[Zrouter-src-freebsd] ZRouter.org: push to FreeBSD HEAD tree

zrouter-src-freebsd at zrouter.org zrouter-src-freebsd at zrouter.org
Tue Apr 17 08:58:59 UTC 2012


details:   http://zrouter.org/hg/FreeBSD/head//rev/f2935497fa04
changeset: 453:f2935497fa04
user:      Aleksandr Rybalko <ray at ddteam.net>
date:      Tue Apr 17 11:51:51 2012 +0300
description:
FreeBSD HEAD @svn 234370r.

diffstat:

 head/Makefile                                                             =
                        |     21 +-
 head/Makefile.inc1                                                        =
                        |     63 +-
 head/ObsoleteFiles.inc                                                    =
                        |     61 +-
 head/UPDATING                                                             =
                        |      9 +-
 head/bin/kenv/kenv.1                                                      =
                        |      3 +-
 head/bin/ps/ps.1                                                          =
                        |     64 +-
 head/bin/pwait/pwait.1                                                    =
                        |      5 +-
 head/bin/setfacl/setfacl.1                                                =
                        |      4 +-
 head/bin/sh/jobs.c                                                        =
                        |      6 +-
 head/bin/sh/sh.1                                                          =
                        |      7 +-
 head/bin/stty/stty.1                                                      =
                        |      7 +-
 head/cddl/contrib/opensolaris/cmd/zpool/zpool.8                           =
                        |      4 +-
 head/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.c              =
                        |      2 +-
 head/cddl/contrib/opensolaris/tools/ctf/cvt/ctf.c                         =
                        |     99 +
 head/cddl/contrib/opensolaris/tools/ctf/cvt/ctfmerge.c                    =
                        |      4 +-
 head/cddl/contrib/opensolaris/tools/ctf/cvt/ctftools.h                    =
                        |      1 +
 head/cddl/contrib/opensolaris/tools/ctf/cvt/output.c                      =
                        |     20 +-
 head/cddl/lib/Makefile                                                    =
                        |      4 +-
 head/cddl/lib/libdtrace/Makefile                                          =
                        |     10 +-
 head/cddl/usr.sbin/Makefile                                               =
                        |      6 +-
 head/contrib/bind9/CHANGES                                                =
                        |    360 +-
 head/contrib/bind9/COPYRIGHT                                              =
                        |      4 +-
 head/contrib/bind9/FAQ.xml                                                =
                        |      2 +-
 head/contrib/bind9/Makefile.in                                            =
                        |      8 +-
 head/contrib/bind9/README                                                 =
                        |     51 +
 head/contrib/bind9/acconfig.h                                             =
                        |      2 +-
 head/contrib/bind9/bin/Makefile.in                                        =
                        |      2 +-
 head/contrib/bind9/bin/check/Makefile.in                                  =
                        |      2 +-
 head/contrib/bind9/bin/check/check-tool.c                                 =
                        |      2 +-
 head/contrib/bind9/bin/check/check-tool.h                                 =
                        |      2 +-
 head/contrib/bind9/bin/check/named-checkconf.8                            =
                        |      2 +-
 head/contrib/bind9/bin/check/named-checkconf.c                            =
                        |      2 +-
 head/contrib/bind9/bin/check/named-checkconf.docbook                      =
                        |      2 +-
 head/contrib/bind9/bin/check/named-checkconf.html                         =
                        |     12 +-
 head/contrib/bind9/bin/check/named-checkzone.8                            =
                        |      2 +-
 head/contrib/bind9/bin/check/named-checkzone.c                            =
                        |     14 +-
 head/contrib/bind9/bin/check/named-checkzone.docbook                      =
                        |      2 +-
 head/contrib/bind9/bin/check/named-checkzone.html                         =
                        |     12 +-
 head/contrib/bind9/bin/confgen/Makefile.in                                =
                        |      2 +-
 head/contrib/bind9/bin/confgen/ddns-confgen.8                             =
                        |      2 +-
 head/contrib/bind9/bin/confgen/ddns-confgen.c                             =
                        |      2 +-
 head/contrib/bind9/bin/confgen/ddns-confgen.docbook                       =
                        |      2 +-
 head/contrib/bind9/bin/confgen/ddns-confgen.html                          =
                        |     10 +-
 head/contrib/bind9/bin/confgen/include/confgen/os.h                       =
                        |      2 +-
 head/contrib/bind9/bin/confgen/keygen.c                                   =
                        |      2 +-
 head/contrib/bind9/bin/confgen/keygen.h                                   =
                        |      2 +-
 head/contrib/bind9/bin/confgen/rndc-confgen.8                             =
                        |      2 +-
 head/contrib/bind9/bin/confgen/rndc-confgen.c                             =
                        |      2 +-
 head/contrib/bind9/bin/confgen/rndc-confgen.docbook                       =
                        |      2 +-
 head/contrib/bind9/bin/confgen/rndc-confgen.html                          =
                        |     12 +-
 head/contrib/bind9/bin/confgen/unix/Makefile.in                           =
                        |      2 +-
 head/contrib/bind9/bin/confgen/unix/os.c                                  =
                        |      2 +-
 head/contrib/bind9/bin/confgen/util.c                                     =
                        |      2 +-
 head/contrib/bind9/bin/confgen/util.h                                     =
                        |      2 +-
 head/contrib/bind9/bin/dig/Makefile.in                                    =
                        |      2 +-
 head/contrib/bind9/bin/dig/dig.1                                          =
                        |      2 +-
 head/contrib/bind9/bin/dig/dig.c                                          =
                        |      4 +-
 head/contrib/bind9/bin/dig/dig.docbook                                    =
                        |      2 +-
 head/contrib/bind9/bin/dig/dig.html                                       =
                        |     20 +-
 head/contrib/bind9/bin/dig/dighost.c                                      =
                        |     96 +-
 head/contrib/bind9/bin/dig/host.1                                         =
                        |      2 +-
 head/contrib/bind9/bin/dig/host.c                                         =
                        |      2 +-
 head/contrib/bind9/bin/dig/host.docbook                                   =
                        |      2 +-
 head/contrib/bind9/bin/dig/host.html                                      =
                        |     10 +-
 head/contrib/bind9/bin/dig/include/dig/dig.h                              =
                        |      4 +-
 head/contrib/bind9/bin/dig/nslookup.1                                     =
                        |      2 +-
 head/contrib/bind9/bin/dig/nslookup.c                                     =
                        |      2 +-
 head/contrib/bind9/bin/dig/nslookup.docbook                               =
                        |      2 +-
 head/contrib/bind9/bin/dig/nslookup.html                                  =
                        |     16 +-
 head/contrib/bind9/bin/dnssec/Makefile.in                                 =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.8                          =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.c                          =
                        |     13 +-
 head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.docbook                    =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.html                       =
                        |     16 +-
 head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.8                       =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.c                       =
                        |     14 +-
 head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.docbook                 =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.html                    =
                        |     14 +-
 head/contrib/bind9/bin/dnssec/dnssec-keygen.8                             =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-keygen.c                             =
                        |     14 +-
 head/contrib/bind9/bin/dnssec/dnssec-keygen.docbook                       =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-keygen.html                          =
                        |     16 +-
 head/contrib/bind9/bin/dnssec/dnssec-revoke.8                             =
                        |     13 +-
 head/contrib/bind9/bin/dnssec/dnssec-revoke.c                             =
                        |     14 +-
 head/contrib/bind9/bin/dnssec/dnssec-revoke.docbook                       =
                        |     16 +-
 head/contrib/bind9/bin/dnssec/dnssec-revoke.html                          =
                        |     19 +-
 head/contrib/bind9/bin/dnssec/dnssec-settime.8                            =
                        |      4 +-
 head/contrib/bind9/bin/dnssec/dnssec-settime.c                            =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-settime.docbook                      =
                        |      5 +-
 head/contrib/bind9/bin/dnssec/dnssec-settime.html                         =
                        |     17 +-
 head/contrib/bind9/bin/dnssec/dnssec-signzone.8                           =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-signzone.c                           =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-signzone.docbook                     =
                        |      2 +-
 head/contrib/bind9/bin/dnssec/dnssec-signzone.html                        =
                        |     12 +-
 head/contrib/bind9/bin/dnssec/dnssectool.c                                =
                        |     25 +-
 head/contrib/bind9/bin/dnssec/dnssectool.h                                =
                        |      9 +-
 head/contrib/bind9/bin/named/Makefile.in                                  =
                        |      2 +-
 head/contrib/bind9/bin/named/bind.keys.h                                  =
                        |      4 +-
 head/contrib/bind9/bin/named/bind9.xsl                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/bind9.xsl.h                                  =
                        |      6 +-
 head/contrib/bind9/bin/named/builtin.c                                    =
                        |      6 +-
 head/contrib/bind9/bin/named/client.c                                     =
                        |     30 +-
 head/contrib/bind9/bin/named/config.c                                     =
                        |      2 +-
 head/contrib/bind9/bin/named/control.c                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/controlconf.c                                =
                        |     22 +-
 head/contrib/bind9/bin/named/convertxsl.pl                                =
                        |      4 +-
 head/contrib/bind9/bin/named/include/dlz/dlz_dlopen_driver.h              =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/builtin.h                      =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/client.h                       =
                        |      7 +-
 head/contrib/bind9/bin/named/include/named/config.h                       =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/control.h                      =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/globals.h                      =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/interfacemgr.h                 =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/listenlist.h                   =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/log.h                          =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/logconf.h                      =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/lwaddr.h                       =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/lwdclient.h                    =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/lwresd.h                       =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/lwsearch.h                     =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/main.h                         =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/notify.h                       =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/ns_smf_globals.h               =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/query.h                        =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/server.h                       =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/sortlist.h                     =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/statschannel.h                 =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/tkeyconf.h                     =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/tsigconf.h                     =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/types.h                        =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/update.h                       =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/xfrout.h                       =
                        |      2 +-
 head/contrib/bind9/bin/named/include/named/zoneconf.h                     =
                        |      2 +-
 head/contrib/bind9/bin/named/interfacemgr.c                               =
                        |      2 +-
 head/contrib/bind9/bin/named/listenlist.c                                 =
                        |      2 +-
 head/contrib/bind9/bin/named/log.c                                        =
                        |      2 +-
 head/contrib/bind9/bin/named/logconf.c                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/lwaddr.c                                     =
                        |      2 +-
 head/contrib/bind9/bin/named/lwdclient.c                                  =
                        |      2 +-
 head/contrib/bind9/bin/named/lwderror.c                                   =
                        |      2 +-
 head/contrib/bind9/bin/named/lwdgabn.c                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/lwdgnba.c                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/lwdgrbn.c                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/lwdnoop.c                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/lwresd.8                                     =
                        |      2 +-
 head/contrib/bind9/bin/named/lwresd.c                                     =
                        |      2 +-
 head/contrib/bind9/bin/named/lwresd.docbook                               =
                        |      2 +-
 head/contrib/bind9/bin/named/lwresd.html                                  =
                        |     14 +-
 head/contrib/bind9/bin/named/lwsearch.c                                   =
                        |      2 +-
 head/contrib/bind9/bin/named/main.c                                       =
                        |     21 +-
 head/contrib/bind9/bin/named/named.8                                      =
                        |      2 +-
 head/contrib/bind9/bin/named/named.conf.5                                 =
                        |      7 +-
 head/contrib/bind9/bin/named/named.conf.docbook                           =
                        |      7 +-
 head/contrib/bind9/bin/named/named.conf.html                              =
                        |     37 +-
 head/contrib/bind9/bin/named/named.docbook                                =
                        |      2 +-
 head/contrib/bind9/bin/named/named.html                                   =
                        |     16 +-
 head/contrib/bind9/bin/named/notify.c                                     =
                        |      2 +-
 head/contrib/bind9/bin/named/query.c                                      =
                        |   1019 +-
 head/contrib/bind9/bin/named/server.c                                     =
                        |     55 +-
 head/contrib/bind9/bin/named/sortlist.c                                   =
                        |      2 +-
 head/contrib/bind9/bin/named/statschannel.c                               =
                        |      2 +-
 head/contrib/bind9/bin/named/tkeyconf.c                                   =
                        |      2 +-
 head/contrib/bind9/bin/named/tsigconf.c                                   =
                        |      2 +-
 head/contrib/bind9/bin/named/unix/Makefile.in                             =
                        |      2 +-
 head/contrib/bind9/bin/named/unix/dlz_dlopen_driver.c                     =
                        |      6 +-
 head/contrib/bind9/bin/named/unix/include/named/os.h                      =
                        |      2 +-
 head/contrib/bind9/bin/named/unix/os.c                                    =
                        |      2 +-
 head/contrib/bind9/bin/named/update.c                                     =
                        |     14 +-
 head/contrib/bind9/bin/named/xfrout.c                                     =
                        |     17 +-
 head/contrib/bind9/bin/named/zoneconf.c                                   =
                        |     28 +-
 head/contrib/bind9/bin/nsupdate/Makefile.in                               =
                        |      2 +-
 head/contrib/bind9/bin/nsupdate/nsupdate.1                                =
                        |      2 +-
 head/contrib/bind9/bin/nsupdate/nsupdate.c                                =
                        |      3 +-
 head/contrib/bind9/bin/nsupdate/nsupdate.docbook                          =
                        |      2 +-
 head/contrib/bind9/bin/nsupdate/nsupdate.html                             =
                        |     14 +-
 head/contrib/bind9/bin/rndc/Makefile.in                                   =
                        |      2 +-
 head/contrib/bind9/bin/rndc/include/rndc/os.h                             =
                        |      2 +-
 head/contrib/bind9/bin/rndc/rndc.8                                        =
                        |      2 +-
 head/contrib/bind9/bin/rndc/rndc.c                                        =
                        |      8 +-
 head/contrib/bind9/bin/rndc/rndc.conf                                     =
                        |      2 +-
 head/contrib/bind9/bin/rndc/rndc.conf.5                                   =
                        |      2 +-
 head/contrib/bind9/bin/rndc/rndc.conf.docbook                             =
                        |      2 +-
 head/contrib/bind9/bin/rndc/rndc.conf.html                                =
                        |     12 +-
 head/contrib/bind9/bin/rndc/rndc.docbook                                  =
                        |      2 +-
 head/contrib/bind9/bin/rndc/rndc.html                                     =
                        |     12 +-
 head/contrib/bind9/bin/rndc/util.c                                        =
                        |      2 +-
 head/contrib/bind9/bin/rndc/util.h                                        =
                        |      2 +-
 head/contrib/bind9/bin/tools/Makefile.in                                  =
                        |      2 +-
 head/contrib/bind9/bin/tools/arpaname.1                                   =
                        |      2 +-
 head/contrib/bind9/bin/tools/arpaname.c                                   =
                        |      2 +-
 head/contrib/bind9/bin/tools/arpaname.docbook                             =
                        |      2 +-
 head/contrib/bind9/bin/tools/arpaname.html                                =
                        |      8 +-
 head/contrib/bind9/bin/tools/genrandom.8                                  =
                        |      6 +-
 head/contrib/bind9/bin/tools/genrandom.c                                  =
                        |      2 +-
 head/contrib/bind9/bin/tools/genrandom.docbook                            =
                        |      5 +-
 head/contrib/bind9/bin/tools/genrandom.html                               =
                        |     12 +-
 head/contrib/bind9/bin/tools/isc-hmac-fixup.8                             =
                        |      2 +-
 head/contrib/bind9/bin/tools/isc-hmac-fixup.c                             =
                        |      2 +-
 head/contrib/bind9/bin/tools/isc-hmac-fixup.docbook                       =
                        |      2 +-
 head/contrib/bind9/bin/tools/isc-hmac-fixup.html                          =
                        |     10 +-
 head/contrib/bind9/bin/tools/named-journalprint.8                         =
                        |      2 +-
 head/contrib/bind9/bin/tools/named-journalprint.c                         =
                        |      2 +-
 head/contrib/bind9/bin/tools/named-journalprint.docbook                   =
                        |      2 +-
 head/contrib/bind9/bin/tools/named-journalprint.html                      =
                        |      8 +-
 head/contrib/bind9/bin/tools/nsec3hash.8                                  =
                        |      2 +-
 head/contrib/bind9/bin/tools/nsec3hash.c                                  =
                        |      7 +-
 head/contrib/bind9/bin/tools/nsec3hash.docbook                            =
                        |      2 +-
 head/contrib/bind9/bin/tools/nsec3hash.html                               =
                        |     10 +-
 head/contrib/bind9/config.h.in                                            =
                        |     25 +-
 head/contrib/bind9/config.threads.in                                      =
                        |      7 +-
 head/contrib/bind9/configure.in                                           =
                        |     30 +-
 head/contrib/bind9/doc/Makefile.in                                        =
                        |      2 +-
 head/contrib/bind9/doc/arm/Bv9ARM-book.xml                                =
                        |    432 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch01.html                               =
                        |     52 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch02.html                               =
                        |     24 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch03.html                               =
                        |     43 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch04.html                               =
                        |    279 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch05.html                               =
                        |      8 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch06.html                               =
                        |    488 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch07.html                               =
                        |     21 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch08.html                               =
                        |     20 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch09.html                               =
                        |    222 +-
 head/contrib/bind9/doc/arm/Bv9ARM.ch10.html                               =
                        |      4 +-
 head/contrib/bind9/doc/arm/Bv9ARM.html                                    =
                        |    208 +-
 head/contrib/bind9/doc/arm/Bv9ARM.pdf                                     =
                        |    Bin=20
 head/contrib/bind9/doc/arm/Makefile.in                                    =
                        |      2 +-
 head/contrib/bind9/doc/arm/README-SGML                                    =
                        |      2 +-
 head/contrib/bind9/doc/arm/dnssec.xml                                     =
                        |      4 +-
 head/contrib/bind9/doc/arm/libdns.xml                                     =
                        |      2 +-
 head/contrib/bind9/doc/arm/man.arpaname.html                              =
                        |     10 +-
 head/contrib/bind9/doc/arm/man.ddns-confgen.html                          =
                        |     12 +-
 head/contrib/bind9/doc/arm/man.dig.html                                   =
                        |     22 +-
 head/contrib/bind9/doc/arm/man.dnssec-dsfromkey.html                      =
                        |     18 +-
 head/contrib/bind9/doc/arm/man.dnssec-keyfromlabel.html                   =
                        |     16 +-
 head/contrib/bind9/doc/arm/man.dnssec-keygen.html                         =
                        |     18 +-
 head/contrib/bind9/doc/arm/man.dnssec-revoke.html                         =
                        |     19 +-
 head/contrib/bind9/doc/arm/man.dnssec-settime.html                        =
                        |     19 +-
 head/contrib/bind9/doc/arm/man.dnssec-signzone.html                       =
                        |     14 +-
 head/contrib/bind9/doc/arm/man.genrandom.html                             =
                        |     12 +-
 head/contrib/bind9/doc/arm/man.host.html                                  =
                        |     12 +-
 head/contrib/bind9/doc/arm/man.isc-hmac-fixup.html                        =
                        |     12 +-
 head/contrib/bind9/doc/arm/man.named-checkconf.html                       =
                        |     14 +-
 head/contrib/bind9/doc/arm/man.named-checkzone.html                       =
                        |     14 +-
 head/contrib/bind9/doc/arm/man.named-journalprint.html                    =
                        |     10 +-
 head/contrib/bind9/doc/arm/man.named.html                                 =
                        |     18 +-
 head/contrib/bind9/doc/arm/man.nsec3hash.html                             =
                        |     12 +-
 head/contrib/bind9/doc/arm/man.nsupdate.html                              =
                        |     16 +-
 head/contrib/bind9/doc/arm/man.rndc-confgen.html                          =
                        |     14 +-
 head/contrib/bind9/doc/arm/man.rndc.conf.html                             =
                        |     14 +-
 head/contrib/bind9/doc/arm/man.rndc.html                                  =
                        |     14 +-
 head/contrib/bind9/doc/arm/managed-keys.xml                               =
                        |      2 +-
 head/contrib/bind9/doc/arm/pkcs11.xml                                     =
                        |    125 +-
 head/contrib/bind9/doc/misc/Makefile.in                                   =
                        |      2 +-
 head/contrib/bind9/doc/misc/dnssec                                        =
                        |      2 +-
 head/contrib/bind9/doc/misc/format-options.pl                             =
                        |      2 +-
 head/contrib/bind9/doc/misc/ipv6                                          =
                        |      2 +-
 head/contrib/bind9/doc/misc/migration                                     =
                        |      2 +-
 head/contrib/bind9/doc/misc/migration-4to9                                =
                        |      2 +-
 head/contrib/bind9/doc/misc/options                                       =
                        |     14 +-
 head/contrib/bind9/doc/misc/rfc-compliance                                =
                        |      2 +-
 head/contrib/bind9/doc/misc/roadmap                                       =
                        |      2 +-
 head/contrib/bind9/doc/misc/sdb                                           =
                        |      2 +-
 head/contrib/bind9/doc/misc/sort-options.pl                               =
                        |      2 +-
 head/contrib/bind9/isc-config.sh.in                                       =
                        |      2 +-
 head/contrib/bind9/lib/Makefile.in                                        =
                        |      2 +-
 head/contrib/bind9/lib/bind9/Makefile.in                                  =
                        |      2 +-
 head/contrib/bind9/lib/bind9/api                                          =
                        |      7 +-
 head/contrib/bind9/lib/bind9/check.c                                      =
                        |     66 +-
 head/contrib/bind9/lib/bind9/getaddresses.c                               =
                        |      2 +-
 head/contrib/bind9/lib/bind9/include/Makefile.in                          =
                        |      2 +-
 head/contrib/bind9/lib/bind9/include/bind9/Makefile.in                    =
                        |      2 +-
 head/contrib/bind9/lib/bind9/include/bind9/check.h                        =
                        |      2 +-
 head/contrib/bind9/lib/bind9/include/bind9/getaddresses.h                 =
                        |      2 +-
 head/contrib/bind9/lib/bind9/include/bind9/version.h                      =
                        |      2 +-
 head/contrib/bind9/lib/bind9/version.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/dns/Makefile.in                                    =
                        |      4 +-
 head/contrib/bind9/lib/dns/acache.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/acl.c                                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/adb.c                                          =
                        |      5 +-
 head/contrib/bind9/lib/dns/api                                            =
                        |     11 +-
 head/contrib/bind9/lib/dns/byaddr.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/cache.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/callbacks.c                                    =
                        |      4 +-
 head/contrib/bind9/lib/dns/client.c                                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/compress.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/dns/db.c                                           =
                        |      9 +-
 head/contrib/bind9/lib/dns/dbiterator.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/dns/dbtable.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/diff.c                                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/dispatch.c                                     =
                        |      4 +-
 head/contrib/bind9/lib/dns/dlz.c                                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/dns64.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/dnssec.c                                       =
                        |     15 +-
 head/contrib/bind9/lib/dns/ds.c                                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/dst_api.c                                      =
                        |     30 +-
 head/contrib/bind9/lib/dns/dst_internal.h                                 =
                        |      6 +-
 head/contrib/bind9/lib/dns/dst_lib.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/dst_openssl.h                                  =
                        |      4 +-
 head/contrib/bind9/lib/dns/dst_parse.c                                    =
                        |     19 +-
 head/contrib/bind9/lib/dns/dst_parse.h                                    =
                        |      2 +-
 head/contrib/bind9/lib/dns/dst_result.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/dns/ecdb.c                                         =
                        |     20 +-
 head/contrib/bind9/lib/dns/forward.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/gen-unix.h                                     =
                        |      2 +-
 head/contrib/bind9/lib/dns/gen.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/gssapi_link.c                                  =
                        |      4 +-
 head/contrib/bind9/lib/dns/gssapictx.c                                    =
                        |     22 +-
 head/contrib/bind9/lib/dns/hmac_link.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/Makefile.in                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/Makefile.in                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/acache.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/acl.h                              =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/adb.h                              =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/bit.h                              =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/byaddr.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/cache.h                            =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/callbacks.h                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/cert.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/client.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/compress.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/db.h                               =
                        |     14 +-
 head/contrib/bind9/lib/dns/include/dns/dbiterator.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/dbtable.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/diff.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/dispatch.h                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/dlz.h                              =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/dlz_dlopen.h                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/dns64.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/dnssec.h                           =
                        |      7 +-
 head/contrib/bind9/lib/dns/include/dns/ds.h                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/ecdb.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/events.h                           =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/fixedname.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/forward.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/iptable.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/journal.h                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/keydata.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/keyflags.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/keytable.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/keyvalues.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/lib.h                              =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/log.h                              =
                        |      5 +-
 head/contrib/bind9/lib/dns/include/dns/lookup.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/master.h                           =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/masterdump.h                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/message.h                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/name.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/ncache.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/nsec.h                             =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/nsec3.h                            =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/opcode.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/order.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/peer.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/portlist.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/private.h                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/rbt.h                              =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/rcode.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/rdata.h                            =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/rdataclass.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/rdatalist.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/rdataset.h                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/rdatasetiter.h                     =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/rdataslab.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/rdatatype.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/request.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/resolver.h                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/result.h                           =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/rootns.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/rpz.h                              =
                        |     59 +-
 head/contrib/bind9/lib/dns/include/dns/rriterator.h                       =
                        |     88 +-
 head/contrib/bind9/lib/dns/include/dns/sdb.h                              =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/sdlz.h                             =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/secalg.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/secproto.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/soa.h                              =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/ssu.h                              =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/stats.h                            =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/tcpmsg.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/time.h                             =
                        |     10 +-
 head/contrib/bind9/lib/dns/include/dns/timer.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/tkey.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/tsec.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/tsig.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/ttl.h                              =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/types.h                            =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/validator.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/version.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/view.h                             =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dns/xfrin.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/zone.h                             =
                        |     37 +-
 head/contrib/bind9/lib/dns/include/dns/zonekey.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dns/zt.h                               =
                        |      4 +-
 head/contrib/bind9/lib/dns/include/dst/Makefile.in                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dst/dst.h                              =
                        |     13 +-
 head/contrib/bind9/lib/dns/include/dst/gssapi.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dst/lib.h                              =
                        |      2 +-
 head/contrib/bind9/lib/dns/include/dst/result.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/iptable.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/journal.c                                      =
                        |      4 +-
 head/contrib/bind9/lib/dns/key.c                                          =
                        |     37 +-
 head/contrib/bind9/lib/dns/keydata.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/keytable.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/dns/lib.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/log.c                                          =
                        |      5 +-
 head/contrib/bind9/lib/dns/lookup.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/master.c                                       =
                        |     14 +-
 head/contrib/bind9/lib/dns/masterdump.c                                   =
                        |     10 +-
 head/contrib/bind9/lib/dns/message.c                                      =
                        |      4 +-
 head/contrib/bind9/lib/dns/name.c                                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/ncache.c                                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/nsec.c                                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/nsec3.c                                        =
                        |      8 +-
 head/contrib/bind9/lib/dns/openssl_link.c                                 =
                        |      4 +-
 head/contrib/bind9/lib/dns/openssldh_link.c                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/openssldsa_link.c                              =
                        |      4 +-
 head/contrib/bind9/lib/dns/opensslgost_link.c                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/opensslrsa_link.c                              =
                        |      4 +-
 head/contrib/bind9/lib/dns/order.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/peer.c                                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/portlist.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/dns/private.c                                      =
                        |      4 +-
 head/contrib/bind9/lib/dns/rbt.c                                          =
                        |      8 +-
 head/contrib/bind9/lib/dns/rbtdb.c                                        =
                        |    395 +-
 head/contrib/bind9/lib/dns/rbtdb.h                                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/rbtdb64.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/rbtdb64.h                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/rcode.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata.c                                        =
                        |     82 +-
 head/contrib/bind9/lib/dns/rdata/any_255/tsig_250.c                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/any_255/tsig_250.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/ch_3/a_1.c                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/ch_3/a_1.h                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/afsdb_18.c                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/afsdb_18.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/cert_37.c                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/cert_37.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/cname_5.c                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/cname_5.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/dlv_32769.c                      =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/dlv_32769.h                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/dname_39.c                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/dname_39.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/dnskey_48.c                      =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/dnskey_48.h                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/ds_43.c                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/ds_43.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/gpos_27.c                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/gpos_27.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/hinfo_13.c                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/hinfo_13.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/hip_55.c                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/hip_55.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/ipseckey_45.c                    =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/ipseckey_45.h                    =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/isdn_20.c                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/isdn_20.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/key_25.c                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/key_25.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/keydata_65533.c                  =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/keydata_65533.h                  =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/loc_29.c                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/loc_29.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mb_7.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mb_7.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/md_3.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/md_3.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mf_4.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mf_4.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mg_8.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mg_8.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/minfo_14.c                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/minfo_14.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mr_9.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mr_9.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mx_15.c                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/mx_15.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/ns_2.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/ns_2.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/nsec3_50.c                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/nsec3_50.h                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/nsec3param_51.c                  =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/nsec3param_51.h                  =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/nsec_47.c                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/nsec_47.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/null_10.c                        =
                        |     10 +-
 head/contrib/bind9/lib/dns/rdata/generic/null_10.h                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/nxt_30.c                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/nxt_30.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/opt_41.c                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/opt_41.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/proforma.c                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/proforma.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/ptr_12.c                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/ptr_12.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/rp_17.c                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/rp_17.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/rrsig_46.c                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/rrsig_46.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/rt_21.c                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/rt_21.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/sig_24.c                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/sig_24.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/soa_6.c                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/soa_6.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/spf_99.c                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/spf_99.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/sshfp_44.c                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/sshfp_44.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/tkey_249.c                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/generic/tkey_249.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/txt_16.c                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/txt_16.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/unspec_103.c                     =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/unspec_103.h                     =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/x25_19.c                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/generic/x25_19.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/hs_4/a_1.c                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/hs_4/a_1.h                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/a6_38.c                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/a6_38.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/a_1.c                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/a_1.h                               =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/aaaa_28.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/aaaa_28.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/apl_42.c                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/apl_42.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/dhcid_49.c                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/in_1/dhcid_49.h                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/kx_36.c                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/kx_36.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/naptr_35.c                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdata/in_1/naptr_35.h                          =
                        |      6 +-
 head/contrib/bind9/lib/dns/rdata/in_1/nsap-ptr_23.c                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/nsap-ptr_23.h                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/nsap_22.c                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/nsap_22.h                           =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/px_26.c                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/px_26.h                             =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/srv_33.c                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/srv_33.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/in_1/wks_11.c                            =
                        |     53 +-
 head/contrib/bind9/lib/dns/rdata/in_1/wks_11.h                            =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/rdatastructpre.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdata/rdatastructsuf.h                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdatalist.c                                    =
                        |      4 +-
 head/contrib/bind9/lib/dns/rdatalist_p.h                                  =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdataset.c                                     =
                        |     10 +-
 head/contrib/bind9/lib/dns/rdatasetiter.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/dns/rdataslab.c                                    =
                        |      5 +-
 head/contrib/bind9/lib/dns/request.c                                      =
                        |     12 +-
 head/contrib/bind9/lib/dns/resolver.c                                     =
                        |    230 +-
 head/contrib/bind9/lib/dns/result.c                                       =
                        |      4 +-
 head/contrib/bind9/lib/dns/rootns.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/rpz.c                                          =
                        |    183 +-
 head/contrib/bind9/lib/dns/rriterator.c                                   =
                        |     10 +-
 head/contrib/bind9/lib/dns/sdb.c                                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/sdlz.c                                         =
                        |      8 +-
 head/contrib/bind9/lib/dns/soa.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/spnego.asn1                                    =
                        |      1 +
 head/contrib/bind9/lib/dns/spnego.c                                       =
                        |     15 +-
 head/contrib/bind9/lib/dns/spnego.h                                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/spnego_asn1.c                                  =
                        |      2 +-
 head/contrib/bind9/lib/dns/spnego_asn1.pl                                 =
                        |      4 +-
 head/contrib/bind9/lib/dns/ssu.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/dns/ssu_external.c                                 =
                        |      4 +-
 head/contrib/bind9/lib/dns/stats.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/tcpmsg.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/dns/time.c                                         =
                        |     16 +-
 head/contrib/bind9/lib/dns/timer.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/dns/tkey.c                                         =
                        |      4 +-
 head/contrib/bind9/lib/dns/tsec.c                                         =
                        |      2 +-
 head/contrib/bind9/lib/dns/tsig.c                                         =
                        |     30 +-
 head/contrib/bind9/lib/dns/ttl.c                                          =
                        |      4 +-
 head/contrib/bind9/lib/dns/validator.c                                    =
                        |     75 +-
 head/contrib/bind9/lib/dns/version.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/view.c                                         =
                        |      7 +-
 head/contrib/bind9/lib/dns/xfrin.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/dns/zone.c                                         =
                        |    345 +-
 head/contrib/bind9/lib/dns/zonekey.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/dns/zt.c                                           =
                        |      4 +-
 head/contrib/bind9/lib/export/Makefile.in                                 =
                        |      2 +-
 head/contrib/bind9/lib/export/dns/Makefile.in                             =
                        |      4 +-
 head/contrib/bind9/lib/export/dns/include/Makefile.in                     =
                        |      2 +-
 head/contrib/bind9/lib/export/dns/include/dns/Makefile.in                 =
                        |      2 +-
 head/contrib/bind9/lib/export/dns/include/dst/Makefile.in                 =
                        |      2 +-
 head/contrib/bind9/lib/export/irs/Makefile.in                             =
                        |      4 +-
 head/contrib/bind9/lib/export/irs/include/Makefile.in                     =
                        |      6 +-
 head/contrib/bind9/lib/export/irs/include/irs/Makefile.in                 =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/Makefile.in                             =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/include/Makefile.in                     =
                        |      6 +-
 head/contrib/bind9/lib/export/isc/include/isc/Makefile.in                 =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/include/isc/bind9.h                     =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/nls/Makefile.in                         =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/nothreads/Makefile.in                   =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/nothreads/include/Makefile.in           =
                        |      6 +-
 head/contrib/bind9/lib/export/isc/nothreads/include/isc/Makefile.in       =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/pthreads/Makefile.in                    =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/pthreads/include/Makefile.in            =
                        |      6 +-
 head/contrib/bind9/lib/export/isc/pthreads/include/isc/Makefile.in        =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/unix/Makefile.in                        =
                        |      2 +-
 head/contrib/bind9/lib/export/isc/unix/include/Makefile.in                =
                        |      6 +-
 head/contrib/bind9/lib/export/isc/unix/include/isc/Makefile.in            =
                        |      2 +-
 head/contrib/bind9/lib/export/isccfg/Makefile.in                          =
                        |      4 +-
 head/contrib/bind9/lib/export/isccfg/include/Makefile.in                  =
                        |      6 +-
 head/contrib/bind9/lib/export/isccfg/include/isccfg/Makefile.in           =
                        |      2 +-
 head/contrib/bind9/lib/export/samples/Makefile-postinstall.in             =
                        |      2 +-
 head/contrib/bind9/lib/export/samples/Makefile.in                         =
                        |      2 +-
 head/contrib/bind9/lib/export/samples/nsprobe.c                           =
                        |      4 +-
 head/contrib/bind9/lib/export/samples/sample-async.c                      =
                        |      2 +-
 head/contrib/bind9/lib/export/samples/sample-gai.c                        =
                        |      2 +-
 head/contrib/bind9/lib/export/samples/sample-request.c                    =
                        |      2 +-
 head/contrib/bind9/lib/export/samples/sample-update.c                     =
                        |      2 +-
 head/contrib/bind9/lib/export/samples/sample.c                            =
                        |      2 +-
 head/contrib/bind9/lib/irs/Makefile.in                                    =
                        |      2 +-
 head/contrib/bind9/lib/irs/api                                            =
                        |      7 +-
 head/contrib/bind9/lib/irs/context.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/irs/dnsconf.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/irs/gai_strerror.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/irs/getaddrinfo.c                                  =
                        |      2 +-
 head/contrib/bind9/lib/irs/getnameinfo.c                                  =
                        |      4 +-
 head/contrib/bind9/lib/irs/include/Makefile.in                            =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/Makefile.in                        =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/context.h                          =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/dnsconf.h                          =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/netdb.h.in                         =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/platform.h.in                      =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/resconf.h                          =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/types.h                            =
                        |      2 +-
 head/contrib/bind9/lib/irs/include/irs/version.h                          =
                        |      2 +-
 head/contrib/bind9/lib/irs/resconf.c                                      =
                        |      4 +-
 head/contrib/bind9/lib/irs/version.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/Makefile.in                                    =
                        |      4 +-
 head/contrib/bind9/lib/isc/alpha/Makefile.in                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/alpha/include/Makefile.in                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/alpha/include/isc/Makefile.in                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/alpha/include/isc/atomic.h                     =
                        |      4 +-
 head/contrib/bind9/lib/isc/api                                            =
                        |      7 +-
 head/contrib/bind9/lib/isc/app_api.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/assertions.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/backtrace-emptytbl.c                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/backtrace.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/base32.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/base64.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/bitstring.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/buffer.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/bufferlist.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/commandline.c                                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/entropy.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/error.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/event.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/fsaccess.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isc/hash.c                                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/heap.c                                         =
                        |      4 +-
 head/contrib/bind9/lib/isc/hex.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/hmacmd5.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/hmacsha.c                                      =
                        |     19 +-
 head/contrib/bind9/lib/isc/httpd.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/isc/ia64/Makefile.in                               =
                        |      2 +-
 head/contrib/bind9/lib/isc/ia64/include/Makefile.in                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/ia64/include/isc/Makefile.in                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/ia64/include/isc/atomic.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/Makefile.in                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/Makefile.in                        =
                        |      6 +-
 head/contrib/bind9/lib/isc/include/isc/app.h                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/assertions.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/backtrace.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/base32.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/base64.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/bind9.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/bitstring.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/boolean.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/buffer.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/bufferlist.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/commandline.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/entropy.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/error.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/event.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/eventclass.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/file.h                             =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/formatcheck.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/fsaccess.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/hash.h                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/heap.h                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/hex.h                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/hmacmd5.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/hmacsha.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/httpd.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/interfaceiter.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/ipv6.h                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/iterated_hash.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/lang.h                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/lex.h                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/lfsr.h                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/lib.h                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/list.h                             =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/log.h                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/magic.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/md5.h                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/mem.h                              =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/msgcat.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/msgs.h                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/mutexblock.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/namespace.h                        =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/netaddr.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/netscope.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/ondestroy.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/os.h                               =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/parseint.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/platform.h.in                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/portset.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/print.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/quota.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/radix.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/random.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/ratelimiter.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/refcount.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/region.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/resource.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/result.h                           =
                        |      7 +-
 head/contrib/bind9/lib/isc/include/isc/resultclass.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/rwlock.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/serial.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/sha1.h                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/sha2.h                             =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/sockaddr.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/socket.h                           =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/stats.h                            =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/stdio.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/stdlib.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/string.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/symtab.h                           =
                        |     12 +-
 head/contrib/bind9/lib/isc/include/isc/task.h                             =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/taskpool.h                         =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/timer.h                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/types.h                            =
                        |      4 +-
 head/contrib/bind9/lib/isc/include/isc/util.h                             =
                        |     14 +-
 head/contrib/bind9/lib/isc/include/isc/version.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/include/isc/xml.h                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/inet_aton.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/inet_ntop.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/inet_pton.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/iterated_hash.c                                =
                        |      2 +-
 head/contrib/bind9/lib/isc/lex.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/lfsr.c                                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/lib.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/log.c                                          =
                        |      4 +-
 head/contrib/bind9/lib/isc/md5.c                                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/mem.c                                          =
                        |      4 +-
 head/contrib/bind9/lib/isc/mem_api.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/mips/Makefile.in                               =
                        |      2 +-
 head/contrib/bind9/lib/isc/mips/include/Makefile.in                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/mips/include/isc/Makefile.in                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/mips/include/isc/atomic.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/mutexblock.c                                   =
                        |      9 +-
 head/contrib/bind9/lib/isc/netaddr.c                                      =
                        |      4 +-
 head/contrib/bind9/lib/isc/netscope.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isc/nls/Makefile.in                                =
                        |      2 +-
 head/contrib/bind9/lib/isc/nls/msgcat.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/noatomic/Makefile.in                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/noatomic/include/Makefile.in                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/noatomic/include/isc/Makefile.in               =
                        |      2 +-
 head/contrib/bind9/lib/isc/noatomic/include/isc/atomic.h                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/Makefile.in                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/condition.c                          =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/include/Makefile.in                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/include/isc/Makefile.in              =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/include/isc/condition.h              =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/include/isc/mutex.h                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/include/isc/once.h                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/include/isc/thread.h                 =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/mutex.c                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/nothreads/thread.c                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/ondestroy.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/parseint.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isc/portset.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/powerpc/Makefile.in                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/powerpc/include/Makefile.in                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/powerpc/include/isc/Makefile.in                =
                        |      2 +-
 head/contrib/bind9/lib/isc/powerpc/include/isc/atomic.h                   =
                        |      4 +-
 head/contrib/bind9/lib/isc/print.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/Makefile.in                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/condition.c                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/include/Makefile.in                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/include/isc/Makefile.in               =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/include/isc/condition.h               =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/include/isc/mutex.h                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/include/isc/once.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/include/isc/thread.h                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/mutex.c                               =
                        |      2 +-
 head/contrib/bind9/lib/isc/pthreads/thread.c                              =
                        |      2 +-
 head/contrib/bind9/lib/isc/quota.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/radix.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/isc/random.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/ratelimiter.c                                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/refcount.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isc/region.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/result.c                                       =
                        |      5 +-
 head/contrib/bind9/lib/isc/rwlock.c                                       =
                        |      4 +-
 head/contrib/bind9/lib/isc/serial.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/sha1.c                                         =
                        |      4 +-
 head/contrib/bind9/lib/isc/sha2.c                                         =
                        |     20 +-
 head/contrib/bind9/lib/isc/sockaddr.c                                     =
                        |      4 +-
 head/contrib/bind9/lib/isc/socket_api.c                                   =
                        |      4 +-
 head/contrib/bind9/lib/isc/sparc64/Makefile.in                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/sparc64/include/Makefile.in                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/sparc64/include/isc/Makefile.in                =
                        |      2 +-
 head/contrib/bind9/lib/isc/sparc64/include/isc/atomic.h                   =
                        |      4 +-
 head/contrib/bind9/lib/isc/stats.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/isc/string.c                                       =
                        |      4 +-
 head/contrib/bind9/lib/isc/strtoul.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/symtab.c                                       =
                        |     53 +-
 head/contrib/bind9/lib/isc/task.c                                         =
                        |      4 +-
 head/contrib/bind9/lib/isc/task_api.c                                     =
                        |      4 +-
 head/contrib/bind9/lib/isc/task_p.h                                       =
                        |      4 +-
 head/contrib/bind9/lib/isc/taskpool.c                                     =
                        |      4 +-
 head/contrib/bind9/lib/isc/timer.c                                        =
                        |      4 +-
 head/contrib/bind9/lib/isc/timer_api.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/timer_p.h                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/Makefile.in                               =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/app.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/dir.c                                     =
                        |      4 +-
 head/contrib/bind9/lib/isc/unix/entropy.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/errno2result.c                            =
                        |     11 +-
 head/contrib/bind9/lib/isc/unix/errno2result.h                            =
                        |      8 +-
 head/contrib/bind9/lib/isc/unix/file.c                                    =
                        |      4 +-
 head/contrib/bind9/lib/isc/unix/fsaccess.c                                =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/ifiter_getifaddrs.c                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/ifiter_ioctl.c                            =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/ifiter_sysctl.c                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/Makefile.in                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/Makefile.in                   =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/dir.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/int.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/keyboard.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/net.h                         =
                        |      4 +-
 head/contrib/bind9/lib/isc/unix/include/isc/netdb.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/offset.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/stat.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/stdtime.h                     =
                        |      4 +-
 head/contrib/bind9/lib/isc/unix/include/isc/strerror.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/syslog.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/include/isc/time.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/interfaceiter.c                           =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/ipv6.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/keyboard.c                                =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/net.c                                     =
                        |      4 +-
 head/contrib/bind9/lib/isc/unix/os.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/resource.c                                =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/socket.c                                  =
                        |     40 +-
 head/contrib/bind9/lib/isc/unix/socket_p.h                                =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/stdio.c                                   =
                        |     17 +-
 head/contrib/bind9/lib/isc/unix/stdtime.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/strerror.c                                =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/syslog.c                                  =
                        |      2 +-
 head/contrib/bind9/lib/isc/unix/time.c                                    =
                        |     28 +-
 head/contrib/bind9/lib/isc/version.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_32/Makefile.in                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_32/include/Makefile.in                     =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_32/include/isc/Makefile.in                 =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_32/include/isc/atomic.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_64/Makefile.in                             =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_64/include/Makefile.in                     =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_64/include/isc/Makefile.in                 =
                        |      2 +-
 head/contrib/bind9/lib/isc/x86_64/include/isc/atomic.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isccc/Makefile.in                                  =
                        |      4 +-
 head/contrib/bind9/lib/isccc/alist.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isccc/api                                          =
                        |      7 +-
 head/contrib/bind9/lib/isccc/base64.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isccc/cc.c                                         =
                        |     29 +-
 head/contrib/bind9/lib/isccc/ccmsg.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/Makefile.in                          =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/Makefile.in                    =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/alist.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/base64.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/cc.h                           =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/ccmsg.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/events.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/lib.h                          =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/result.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/sexpr.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/symtab.h                       =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/symtype.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/types.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/util.h                         =
                        |      2 +-
 head/contrib/bind9/lib/isccc/include/isccc/version.h                      =
                        |      2 +-
 head/contrib/bind9/lib/isccc/lib.c                                        =
                        |      2 +-
 head/contrib/bind9/lib/isccc/result.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isccc/sexpr.c                                      =
                        |      2 +-
 head/contrib/bind9/lib/isccc/symtab.c                                     =
                        |      2 +-
 head/contrib/bind9/lib/isccc/version.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/Makefile.in                                 =
                        |      4 +-
 head/contrib/bind9/lib/isccfg/aclconf.c                                   =
                        |      6 +-
 head/contrib/bind9/lib/isccfg/api                                         =
                        |      7 +-
 head/contrib/bind9/lib/isccfg/dnsconf.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/Makefile.in                         =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/Makefile.in                  =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/aclconf.h                    =
                        |      4 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/cfg.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/dnsconf.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/grammar.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/log.h                        =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/namedconf.h                  =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/include/isccfg/version.h                    =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/log.c                                       =
                        |      2 +-
 head/contrib/bind9/lib/isccfg/namedconf.c                                 =
                        |     14 +-
 head/contrib/bind9/lib/isccfg/parser.c                                    =
                        |      4 +-
 head/contrib/bind9/lib/isccfg/version.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/lwres/Makefile.in                                  =
                        |      2 +-
 head/contrib/bind9/lib/lwres/api                                          =
                        |      7 +-
 head/contrib/bind9/lib/lwres/assert_p.h                                   =
                        |      4 +-
 head/contrib/bind9/lib/lwres/context.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/lwres/context_p.h                                  =
                        |      2 +-
 head/contrib/bind9/lib/lwres/gai_strerror.c                               =
                        |      2 +-
 head/contrib/bind9/lib/lwres/getaddrinfo.c                                =
                        |      2 +-
 head/contrib/bind9/lib/lwres/gethost.c                                    =
                        |      2 +-
 head/contrib/bind9/lib/lwres/getipnode.c                                  =
                        |      2 +-
 head/contrib/bind9/lib/lwres/getnameinfo.c                                =
                        |     33 +-
 head/contrib/bind9/lib/lwres/getrrset.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/lwres/herror.c                                     =
                        |      4 +-
 head/contrib/bind9/lib/lwres/include/Makefile.in                          =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/Makefile.in                    =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/context.h                      =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/int.h                          =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/ipv6.h                         =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/lang.h                         =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/list.h                         =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/lwbuffer.h                     =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/lwpacket.h                     =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/lwres.h                        =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/netdb.h.in                     =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/platform.h.in                  =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/result.h                       =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/stdlib.h                       =
                        |      2 +-
 head/contrib/bind9/lib/lwres/include/lwres/version.h                      =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwbuffer.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwconfig.c                                   =
                        |      4 +-
 head/contrib/bind9/lib/lwres/lwinetaton.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwinetntop.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwinetpton.c                                 =
                        |     13 +-
 head/contrib/bind9/lib/lwres/lwpacket.c                                   =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwres_gabn.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwres_gnba.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwres_grbn.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwres_noop.c                                 =
                        |      2 +-
 head/contrib/bind9/lib/lwres/lwresutil.c                                  =
                        |      2 +-
 head/contrib/bind9/lib/lwres/man/Makefile.in                              =
                        |      2 +-
 head/contrib/bind9/lib/lwres/man/lwres.3                                  =
                        |      2 +-
 head/contrib/bind9/lib/lwres/man/lwres.docbook                            =
                        |      2 +-
 head/contrib/bind9/lib/lwres/man/lwres.html                               =
                        |     14 +-
 head/contrib/bind9/lib/lwres/man/lwres_buffer.3                           =
                        |      2 +-
 head/contrib/bind9/lib/lwres/man/lwres_buffer.docbook                     =
                        |      2 +-
 head/contrib/bind9/lib/lwres/man/lwres_buffer.html                        =
                        |      4 +-
 head/contrib/bind9/lib/lwres/man/lwres_config.3                           =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_config.docbook                     =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_config.html                        =
                        |     12 +-
 head/contrib/bind9/lib/lwres/man/lwres_context.3                          =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_context.docbook                    =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_context.html                       =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_gabn.3                             =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_gabn.docbook                       =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_gabn.html                          =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.3                     =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.docbook               =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.html                  =
                        |      8 +-
 head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.3                      =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.docbook                =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.html                   =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_gethostent.3                       =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_gethostent.docbook                 =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_gethostent.html                    =
                        |     12 +-
 head/contrib/bind9/lib/lwres/man/lwres_getipnode.3                        =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_getipnode.docbook                  =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_getipnode.html                     =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.3                      =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.docbook                =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.html                   =
                        |     12 +-
 head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.3                   =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.docbook             =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.html                =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_gnba.3                             =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_gnba.docbook                       =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_gnba.html                          =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_hstrerror.3                        =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_hstrerror.docbook                  =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_hstrerror.html                     =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_inetntop.3                         =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_inetntop.docbook                   =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_inetntop.html                      =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_noop.3                             =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_noop.docbook                       =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_noop.html                          =
                        |     10 +-
 head/contrib/bind9/lib/lwres/man/lwres_packet.3                           =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_packet.docbook                     =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_packet.html                        =
                        |      8 +-
 head/contrib/bind9/lib/lwres/man/lwres_resutil.3                          =
                        |      6 +-
 head/contrib/bind9/lib/lwres/man/lwres_resutil.docbook                    =
                        |      5 +-
 head/contrib/bind9/lib/lwres/man/lwres_resutil.html                       =
                        |     10 +-
 head/contrib/bind9/lib/lwres/print.c                                      =
                        |      4 +-
 head/contrib/bind9/lib/lwres/print_p.h                                    =
                        |      4 +-
 head/contrib/bind9/lib/lwres/strtoul.c                                    =
                        |      4 +-
 head/contrib/bind9/lib/lwres/unix/Makefile.in                             =
                        |      4 +-
 head/contrib/bind9/lib/lwres/unix/include/Makefile.in                     =
                        |      4 +-
 head/contrib/bind9/lib/lwres/unix/include/lwres/Makefile.in               =
                        |      4 +-
 head/contrib/bind9/lib/lwres/unix/include/lwres/net.h                     =
                        |      8 +-
 head/contrib/bind9/lib/lwres/version.c                                    =
                        |      4 +-
 head/contrib/bind9/make/Makefile.in                                       =
                        |      4 +-
 head/contrib/bind9/make/includes.in                                       =
                        |      4 +-
 head/contrib/bind9/make/mkdep.in                                          =
                        |     38 +-
 head/contrib/bind9/make/rules.in                                          =
                        |     38 +-
 head/contrib/bind9/mkinstalldirs                                          =
                        |      2 +-
 head/contrib/bind9/version                                                =
                        |      8 +-
 head/contrib/com_err/com_err.3                                            =
                        |    325 +-
 head/contrib/com_err/com_err.c                                            =
                        |     92 +-
 head/contrib/com_err/com_err.h                                            =
                        |     92 +-
 head/contrib/com_err/com_right.h                                          =
                        |    100 +-
 head/contrib/com_err/compile_et.c                                         =
                        |    106 +-
 head/contrib/com_err/compile_et.h                                         =
                        |     57 +-
 head/contrib/com_err/error.c                                              =
                        |     92 +-
 head/contrib/com_err/lex.h                                                =
                        |     54 +-
 head/contrib/com_err/lex.l                                                =
                        |     62 +-
 head/contrib/com_err/parse.y                                              =
                        |     65 +-
 head/contrib/com_err/roken_rename.h                                       =
                        |     66 +-
 head/contrib/com_err/version-script.map                                   =
                        |      2 +
 head/contrib/gcc/ChangeLog.gcc43                                          =
                        |      5 +
 head/contrib/gcc/builtins.c                                               =
                        |      2 +-
 head/contrib/gcc/config/mips/freebsd.h                                    =
                        |      5 +-
 head/contrib/libcxxrt/dynamic_cast.cc                                     =
                        |    107 +-
 head/contrib/libcxxrt/exception.cc                                        =
                        |     47 +-
 head/contrib/libcxxrt/typeinfo.h                                          =
                        |    107 +-
 head/contrib/llvm/LICENSE.TXT                                             =
                        |      3 +-
 head/contrib/llvm/include/llvm-c/Analysis.h                               =
                        |     10 +
 head/contrib/llvm/include/llvm-c/BitReader.h                              =
                        |     10 +
 head/contrib/llvm/include/llvm-c/BitWriter.h                              =
                        |     10 +
 head/contrib/llvm/include/llvm-c/Core.h                                   =
                        |   1746 +-
 head/contrib/llvm/include/llvm-c/Disassembler.h                           =
                        |     11 +
 head/contrib/llvm/include/llvm-c/EnhancedDisassembly.h                    =
                        |     17 +
 head/contrib/llvm/include/llvm-c/ExecutionEngine.h                        =
                        |     11 +
 head/contrib/llvm/include/llvm-c/Initialization.h                         =
                        |     14 +
 head/contrib/llvm/include/llvm-c/LinkTimeOptimizer.h                      =
                        |     11 +
 head/contrib/llvm/include/llvm-c/Object.h                                 =
                        |     76 +-
 head/contrib/llvm/include/llvm-c/Target.h                                 =
                        |     65 +
 head/contrib/llvm/include/llvm-c/Transforms/IPO.h                         =
                        |     11 +
 head/contrib/llvm/include/llvm-c/Transforms/PassManagerBuilder.h          =
                        |     11 +
 head/contrib/llvm/include/llvm-c/Transforms/Scalar.h                      =
                        |     10 +
 head/contrib/llvm/include/llvm-c/lto.h                                    =
                        |     51 +-
 head/contrib/llvm/include/llvm/ADT/APFloat.h                              =
                        |     13 +-
 head/contrib/llvm/include/llvm/ADT/APInt.h                                =
                        |     41 +-
 head/contrib/llvm/include/llvm/ADT/ArrayRef.h                             =
                        |    129 +-
 head/contrib/llvm/include/llvm/ADT/BitVector.h                            =
                        |     92 +-
 head/contrib/llvm/include/llvm/ADT/DAGDeltaAlgorithm.h                    =
                        |      1 +
 head/contrib/llvm/include/llvm/ADT/DenseMap.h                             =
                        |     70 +-
 head/contrib/llvm/include/llvm/ADT/DenseMapInfo.h                         =
                        |      2 +-
 head/contrib/llvm/include/llvm/ADT/FoldingSet.h                           =
                        |     28 +-
 head/contrib/llvm/include/llvm/ADT/GraphTraits.h                          =
                        |      5 +-
 head/contrib/llvm/include/llvm/ADT/ImmutableSet.h                         =
                        |     16 +-
 head/contrib/llvm/include/llvm/ADT/IntervalMap.h                          =
                        |      4 +-
 head/contrib/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h                   =
                        |     25 +-
 head/contrib/llvm/include/llvm/ADT/PointerIntPair.h                       =
                        |      6 +-
 head/contrib/llvm/include/llvm/ADT/PointerUnion.h                         =
                        |     21 +-
 head/contrib/llvm/include/llvm/ADT/SetVector.h                            =
                        |      6 +
 head/contrib/llvm/include/llvm/ADT/SmallBitVector.h                       =
                        |      6 +-
 head/contrib/llvm/include/llvm/ADT/SmallPtrSet.h                          =
                        |     16 +
 head/contrib/llvm/include/llvm/ADT/SmallSet.h                             =
                        |      4 +-
 head/contrib/llvm/include/llvm/ADT/SmallString.h                          =
                        |    233 +-
 head/contrib/llvm/include/llvm/ADT/SmallVector.h                          =
                        |    108 +-
 head/contrib/llvm/include/llvm/ADT/SparseBitVector.h                      =
                        |     43 +-
 head/contrib/llvm/include/llvm/ADT/Statistic.h                            =
                        |      2 +
 head/contrib/llvm/include/llvm/ADT/StringExtras.h                         =
                        |     37 -
 head/contrib/llvm/include/llvm/ADT/StringMap.h                            =
                        |     67 +-
 head/contrib/llvm/include/llvm/ADT/StringRef.h                            =
                        |     67 +-
 head/contrib/llvm/include/llvm/ADT/TinyPtrVector.h                        =
                        |     42 +-
 head/contrib/llvm/include/llvm/ADT/Trie.h                                 =
                        |      6 +-
 head/contrib/llvm/include/llvm/ADT/Triple.h                               =
                        |    202 +-
 head/contrib/llvm/include/llvm/ADT/Twine.h                                =
                        |      3 +-
 head/contrib/llvm/include/llvm/ADT/ValueMap.h                             =
                        |     24 +-
 head/contrib/llvm/include/llvm/ADT/ilist.h                                =
                        |      4 -
 head/contrib/llvm/include/llvm/Analysis/AliasAnalysis.h                   =
                        |      7 +-
 head/contrib/llvm/include/llvm/Analysis/AliasSetTracker.h                 =
                        |      1 +
 head/contrib/llvm/include/llvm/Analysis/BlockFrequencyImpl.h              =
                        |     15 +-
 head/contrib/llvm/include/llvm/Analysis/BlockFrequencyInfo.h              =
                        |      2 +-
 head/contrib/llvm/include/llvm/Analysis/BranchProbabilityInfo.h           =
                        |    126 +-
 head/contrib/llvm/include/llvm/Analysis/CFGPrinter.h                      =
                        |     12 +-
 head/contrib/llvm/include/llvm/Analysis/CaptureTracking.h                 =
                        |     34 +-
 head/contrib/llvm/include/llvm/Analysis/CodeMetrics.h                     =
                        |     87 +-
 head/contrib/llvm/include/llvm/Analysis/ConstantFolding.h                 =
                        |     26 +-
 head/contrib/llvm/include/llvm/Analysis/DIBuilder.h                       =
                        |     42 +-
 head/contrib/llvm/include/llvm/Analysis/DOTGraphTraitsPass.h              =
                        |      6 +-
 head/contrib/llvm/include/llvm/Analysis/DebugInfo.h                       =
                        |     92 +-
 head/contrib/llvm/include/llvm/Analysis/DominanceFrontier.h               =
                        |      1 +
 head/contrib/llvm/include/llvm/Analysis/DominatorInternals.h              =
                        |      2 +-
 head/contrib/llvm/include/llvm/Analysis/Dominators.h                      =
                        |    136 +-
 head/contrib/llvm/include/llvm/Analysis/IVUsers.h                         =
                        |      6 +
 head/contrib/llvm/include/llvm/Analysis/InlineCost.h                      =
                        |    191 +-
 head/contrib/llvm/include/llvm/Analysis/InstructionSimplify.h             =
                        |     97 +-
 head/contrib/llvm/include/llvm/Analysis/IntervalIterator.h                =
                        |      4 +-
 head/contrib/llvm/include/llvm/Analysis/LazyValueInfo.h                   =
                        |      6 +-
 head/contrib/llvm/include/llvm/Analysis/Loads.h                           =
                        |      8 +-
 head/contrib/llvm/include/llvm/Analysis/LoopInfo.h                        =
                        |     74 +-
 head/contrib/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h        =
                        |      4 +
 head/contrib/llvm/include/llvm/Analysis/PHITransAddr.h                    =
                        |      8 +-
 head/contrib/llvm/include/llvm/Analysis/ProfileInfo.h                     =
                        |      9 +-
 head/contrib/llvm/include/llvm/Analysis/RegionInfo.h                      =
                        |      2 +-
 head/contrib/llvm/include/llvm/Analysis/ScalarEvolution.h                 =
                        |     26 +-
 head/contrib/llvm/include/llvm/Analysis/ScalarEvolutionExpander.h         =
                        |     37 +-
 head/contrib/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h      =
                        |      1 -
 head/contrib/llvm/include/llvm/Analysis/ValueTracking.h                   =
                        |     58 +-
 head/contrib/llvm/include/llvm/Argument.h                                 =
                        |      1 +
 head/contrib/llvm/include/llvm/Assembly/AssemblyAnnotationWriter.h        =
                        |     20 +-
 head/contrib/llvm/include/llvm/Assembly/Parser.h                          =
                        |      1 -
 head/contrib/llvm/include/llvm/Assembly/Writer.h                          =
                        |      1 -
 head/contrib/llvm/include/llvm/Attributes.h                               =
                        |    185 +-
 head/contrib/llvm/include/llvm/AutoUpgrade.h                              =
                        |      8 -
 head/contrib/llvm/include/llvm/BasicBlock.h                               =
                        |      7 +-
 head/contrib/llvm/include/llvm/Bitcode/Archive.h                          =
                        |      2 +-
 head/contrib/llvm/include/llvm/Bitcode/BitCodes.h                         =
                        |     13 +-
 head/contrib/llvm/include/llvm/Bitcode/BitstreamReader.h                  =
                        |     99 +-
 head/contrib/llvm/include/llvm/Bitcode/BitstreamWriter.h                  =
                        |     83 +-
 head/contrib/llvm/include/llvm/Bitcode/LLVMBitCodes.h                     =
                        |     40 +-
 head/contrib/llvm/include/llvm/Bitcode/ReaderWriter.h                     =
                        |     49 +-
 head/contrib/llvm/include/llvm/CodeGen/Analysis.h                         =
                        |      7 +-
 head/contrib/llvm/include/llvm/CodeGen/AsmPrinter.h                       =
                        |     32 +-
 head/contrib/llvm/include/llvm/CodeGen/CallingConvLower.h                 =
                        |     12 +-
 head/contrib/llvm/include/llvm/CodeGen/EdgeBundles.h                      =
                        |      3 +-
 head/contrib/llvm/include/llvm/CodeGen/FastISel.h                         =
                        |     11 +-
 head/contrib/llvm/include/llvm/CodeGen/FunctionLoweringInfo.h             =
                        |     24 +-
 head/contrib/llvm/include/llvm/CodeGen/GCStrategy.h                       =
                        |     13 +-
 head/contrib/llvm/include/llvm/CodeGen/ISDOpcodes.h                       =
                        |     15 +-
 head/contrib/llvm/include/llvm/CodeGen/JITCodeEmitter.h                   =
                        |      1 +
 head/contrib/llvm/include/llvm/CodeGen/LatencyPriorityQueue.h             =
                        |      4 +-
 head/contrib/llvm/include/llvm/CodeGen/LexicalScopes.h                    =
                        |      3 +-
 head/contrib/llvm/include/llvm/CodeGen/LinkAllCodegenComponents.h         =
                        |      8 +-
 head/contrib/llvm/include/llvm/CodeGen/LiveInterval.h                     =
                        |     54 +-
 head/contrib/llvm/include/llvm/CodeGen/LiveIntervalAnalysis.h             =
                        |    258 +-
 head/contrib/llvm/include/llvm/CodeGen/LiveVariables.h                    =
                        |      9 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineBasicBlock.h                =
                        |    247 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineBlockFrequencyInfo.h        =
                        |      6 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineBranchProbabilityInfo.h     =
                        |     16 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineCodeEmitter.h               =
                        |      3 +
 head/contrib/llvm/include/llvm/CodeGen/MachineConstantPool.h              =
                        |      1 +
 head/contrib/llvm/include/llvm/CodeGen/MachineDominators.h                =
                        |      3 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineFrameInfo.h                 =
                        |      2 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineFunction.h                  =
                        |     35 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineFunctionAnalysis.h          =
                        |      5 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineInstr.h                     =
                        |    376 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineInstrBuilder.h              =
                        |     52 +
 head/contrib/llvm/include/llvm/CodeGen/MachineJumpTableInfo.h             =
                        |      7 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineMemOperand.h                =
                        |     13 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineModuleInfo.h                =
                        |     16 +-
 head/contrib/llvm/include/llvm/CodeGen/MachineOperand.h                   =
                        |     72 +-
 head/contrib/llvm/include/llvm/CodeGen/MachinePassRegistry.h              =
                        |      1 +
 head/contrib/llvm/include/llvm/CodeGen/MachineRegisterInfo.h              =
                        |    180 +-
 head/contrib/llvm/include/llvm/CodeGen/PBQP/Graph.h                       =
                        |     37 +
 head/contrib/llvm/include/llvm/CodeGen/PBQP/HeuristicBase.h               =
                        |     14 +-
 head/contrib/llvm/include/llvm/CodeGen/PBQP/Heuristics/Briggs.h           =
                        |      6 +
 head/contrib/llvm/include/llvm/CodeGen/Passes.h                           =
                        |    369 +-
 head/contrib/llvm/include/llvm/CodeGen/RegisterScavenging.h               =
                        |     14 +-
 head/contrib/llvm/include/llvm/CodeGen/ScheduleDAG.h                      =
                        |     73 +-
 head/contrib/llvm/include/llvm/CodeGen/SchedulerRegistry.h                =
                        |     16 +-
 head/contrib/llvm/include/llvm/CodeGen/SelectionDAG.h                     =
                        |     27 +-
 head/contrib/llvm/include/llvm/CodeGen/SelectionDAGISel.h                 =
                        |     17 +-
 head/contrib/llvm/include/llvm/CodeGen/SelectionDAGNodes.h                =
                        |     37 +-
 head/contrib/llvm/include/llvm/CodeGen/SlotIndexes.h                      =
                        |    126 +-
 head/contrib/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h     =
                        |     13 +-
 head/contrib/llvm/include/llvm/CodeGen/ValueTypes.h                       =
                        |    113 +-
 head/contrib/llvm/include/llvm/CodeGen/ValueTypes.td                      =
                        |     62 +-
 head/contrib/llvm/include/llvm/Constant.h                                 =
                        |     23 +-
 head/contrib/llvm/include/llvm/Constants.h                                =
                        |    326 +-
 head/contrib/llvm/include/llvm/DefaultPasses.h                            =
                        |      2 +
 head/contrib/llvm/include/llvm/DerivedTypes.h                             =
                        |     10 +-
 head/contrib/llvm/include/llvm/ExecutionEngine/ExecutionEngine.h          =
                        |     59 +-
 head/contrib/llvm/include/llvm/ExecutionEngine/JITEventListener.h         =
                        |     50 +-
 head/contrib/llvm/include/llvm/ExecutionEngine/JITMemoryManager.h         =
                        |     27 +
 head/contrib/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h              =
                        |     33 +-
 head/contrib/llvm/include/llvm/Function.h                                 =
                        |      8 +-
 head/contrib/llvm/include/llvm/GlobalValue.h                              =
                        |      7 +-
 head/contrib/llvm/include/llvm/InitializePasses.h                         =
                        |     27 +-
 head/contrib/llvm/include/llvm/InlineAsm.h                                =
                        |      1 +
 head/contrib/llvm/include/llvm/InstrTypes.h                               =
                        |      1 +
 head/contrib/llvm/include/llvm/Instruction.def                            =
                        |    125 +-
 head/contrib/llvm/include/llvm/Instruction.h                              =
                        |     26 +-
 head/contrib/llvm/include/llvm/Instructions.h                             =
                        |    340 +-
 head/contrib/llvm/include/llvm/IntrinsicInst.h                            =
                        |     28 -
 head/contrib/llvm/include/llvm/Intrinsics.td                              =
                        |     11 +-
 head/contrib/llvm/include/llvm/IntrinsicsX86.td                           =
                        |   1176 +-
 head/contrib/llvm/include/llvm/LLVMContext.h                              =
                        |     11 +-
 head/contrib/llvm/include/llvm/LinkAllPasses.h                            =
                        |      5 +-
 head/contrib/llvm/include/llvm/Linker.h                                   =
                        |      3 +-
 head/contrib/llvm/include/llvm/MC/MCAsmBackend.h                          =
                        |     49 +-
 head/contrib/llvm/include/llvm/MC/MCAsmInfo.h                             =
                        |     44 +-
 head/contrib/llvm/include/llvm/MC/MCAsmInfoCOFF.h                         =
                        |     14 +-
 head/contrib/llvm/include/llvm/MC/MCAsmInfoDarwin.h                       =
                        |      4 +-
 head/contrib/llvm/include/llvm/MC/MCAsmLayout.h                           =
                        |      1 +
 head/contrib/llvm/include/llvm/MC/MCAssembler.h                           =
                        |     47 +-
 head/contrib/llvm/include/llvm/MC/MCCodeEmitter.h                         =
                        |      6 +-
 head/contrib/llvm/include/llvm/MC/MCCodeGenInfo.h                         =
                        |     11 +-
 head/contrib/llvm/include/llvm/MC/MCContext.h                             =
                        |     62 +-
 head/contrib/llvm/include/llvm/MC/MCDisassembler.h                        =
                        |      2 +-
 head/contrib/llvm/include/llvm/MC/MCDwarf.h                               =
                        |     67 +-
 head/contrib/llvm/include/llvm/MC/MCELFObjectWriter.h                     =
                        |     75 +-
 head/contrib/llvm/include/llvm/MC/MCExpr.h                                =
                        |     28 +-
 head/contrib/llvm/include/llvm/MC/MCFixup.h                               =
                        |     19 +-
 head/contrib/llvm/include/llvm/MC/MCInst.h                                =
                        |     28 +-
 head/contrib/llvm/include/llvm/MC/MCInstPrinter.h                         =
                        |     11 +-
 head/contrib/llvm/include/llvm/MC/MCInstrAnalysis.h                       =
                        |      2 +-
 head/contrib/llvm/include/llvm/MC/MCInstrDesc.h                           =
                        |    208 +-
 head/contrib/llvm/include/llvm/MC/MCInstrInfo.h                           =
                        |     17 +-
 head/contrib/llvm/include/llvm/MC/MCObjectFileInfo.h                      =
                        |     44 +-
 head/contrib/llvm/include/llvm/MC/MCObjectStreamer.h                      =
                        |      7 +-
 head/contrib/llvm/include/llvm/MC/MCObjectWriter.h                        =
                        |      8 +-
 head/contrib/llvm/include/llvm/MC/MCParser/MCAsmLexer.h                   =
                        |      1 +
 head/contrib/llvm/include/llvm/MC/MCParser/MCAsmParser.h                  =
                        |     14 +-
 head/contrib/llvm/include/llvm/MC/MCRegisterInfo.h                        =
                        |    184 +-
 head/contrib/llvm/include/llvm/MC/MCSection.h                             =
                        |      2 -
 head/contrib/llvm/include/llvm/MC/MCSectionCOFF.h                         =
                        |      2 +-
 head/contrib/llvm/include/llvm/MC/MCSectionELF.h                          =
                        |      1 +
 head/contrib/llvm/include/llvm/MC/MCSectionMachO.h                        =
                        |      1 +
 head/contrib/llvm/include/llvm/MC/MCStreamer.h                            =
                        |     49 +-
 head/contrib/llvm/include/llvm/Metadata.h                                 =
                        |     25 +-
 head/contrib/llvm/include/llvm/Module.h                                   =
                        |     64 +-
 head/contrib/llvm/include/llvm/Object/Archive.h                           =
                        |     59 +-
 head/contrib/llvm/include/llvm/Object/Binary.h                            =
                        |     53 +-
 head/contrib/llvm/include/llvm/Object/COFF.h                              =
                        |     77 +-
 head/contrib/llvm/include/llvm/Object/MachO.h                             =
                        |     37 +-
 head/contrib/llvm/include/llvm/Object/MachOObject.h                       =
                        |      6 +-
 head/contrib/llvm/include/llvm/Object/ObjectFile.h                        =
                        |    275 +-
 head/contrib/llvm/include/llvm/Operator.h                                 =
                        |      4 +-
 head/contrib/llvm/include/llvm/Pass.h                                     =
                        |     38 +-
 head/contrib/llvm/include/llvm/PassAnalysisSupport.h                      =
                        |      1 +
 head/contrib/llvm/include/llvm/PassManager.h                              =
                        |     22 +-
 head/contrib/llvm/include/llvm/PassManagers.h                             =
                        |     75 +-
 head/contrib/llvm/include/llvm/PassSupport.h                              =
                        |      7 +-
 head/contrib/llvm/include/llvm/Support/BlockFrequency.h                   =
                        |      2 +
 head/contrib/llvm/include/llvm/Support/BranchProbability.h                =
                        |     31 +-
 head/contrib/llvm/include/llvm/Support/CFG.h                              =
                        |      8 +
 head/contrib/llvm/include/llvm/Support/COFF.h                             =
                        |    294 +-
 head/contrib/llvm/include/llvm/Support/CallSite.h                         =
                        |     10 +
 head/contrib/llvm/include/llvm/Support/Capacity.h                         =
                        |      2 +
 head/contrib/llvm/include/llvm/Support/CodeGen.h                          =
                        |     20 +
 head/contrib/llvm/include/llvm/Support/CommandLine.h                      =
                        |    156 +-
 head/contrib/llvm/include/llvm/Support/Compiler.h                         =
                        |     27 +-
 head/contrib/llvm/include/llvm/Support/DOTGraphTraits.h                   =
                        |     30 +-
 head/contrib/llvm/include/llvm/Support/DataTypes.h.in                     =
                        |     15 +
 head/contrib/llvm/include/llvm/Support/Debug.h                            =
                        |      6 +-
 head/contrib/llvm/include/llvm/Support/Dwarf.h                            =
                        |      6 +-
 head/contrib/llvm/include/llvm/Support/DynamicLibrary.h                   =
                        |      3 +
 head/contrib/llvm/include/llvm/Support/ELF.h                              =
                        |     50 +
 head/contrib/llvm/include/llvm/Support/Endian.h                           =
                        |     12 +
 head/contrib/llvm/include/llvm/Support/FileSystem.h                       =
                        |    228 +-
 head/contrib/llvm/include/llvm/Support/GraphWriter.h                      =
                        |     14 +-
 head/contrib/llvm/include/llvm/Support/Host.h                             =
                        |      6 +-
 head/contrib/llvm/include/llvm/Support/IRReader.h                         =
                        |     10 +-
 head/contrib/llvm/include/llvm/Support/InstVisitor.h                      =
                        |    105 +-
 head/contrib/llvm/include/llvm/Support/MachO.h                            =
                        |      7 +
 head/contrib/llvm/include/llvm/Support/ManagedStatic.h                    =
                        |      5 +
 head/contrib/llvm/include/llvm/Support/MathExtras.h                       =
                        |     14 +
 head/contrib/llvm/include/llvm/Support/MemoryObject.h                     =
                        |     11 +-
 head/contrib/llvm/include/llvm/Support/PathV1.h                           =
                        |     14 -
 head/contrib/llvm/include/llvm/Support/PatternMatch.h                     =
                        |     91 +-
 head/contrib/llvm/include/llvm/Support/Process.h                          =
                        |      3 -
 head/contrib/llvm/include/llvm/Support/Program.h                          =
                        |     13 +-
 head/contrib/llvm/include/llvm/Support/Recycler.h                         =
                        |      3 +-
 head/contrib/llvm/include/llvm/Support/SMLoc.h                            =
                        |     22 +-
 head/contrib/llvm/include/llvm/Support/SourceMgr.h                        =
                        |     52 +-
 head/contrib/llvm/include/llvm/Support/TargetRegistry.h                   =
                        |     50 +-
 head/contrib/llvm/include/llvm/Support/TargetSelect.h                     =
                        |     12 +
 head/contrib/llvm/include/llvm/Support/Valgrind.h                         =
                        |     43 +
 head/contrib/llvm/include/llvm/Support/ValueHandle.h                      =
                        |     43 +-
 head/contrib/llvm/include/llvm/Support/system_error.h                     =
                        |     15 +-
 head/contrib/llvm/include/llvm/Support/type_traits.h                      =
                        |     95 +-
 head/contrib/llvm/include/llvm/TableGen/Record.h                          =
                        |    228 +-
 head/contrib/llvm/include/llvm/TableGen/TableGenAction.h                  =
                        |      1 +
 head/contrib/llvm/include/llvm/TableGen/TableGenBackend.h                 =
                        |      4 +-
 head/contrib/llvm/include/llvm/Target/Mangler.h                           =
                        |      4 +-
 head/contrib/llvm/include/llvm/Target/Target.td                           =
                        |     62 +-
 head/contrib/llvm/include/llvm/Target/TargetCallingConv.h                 =
                        |      4 +
 head/contrib/llvm/include/llvm/Target/TargetCallingConv.td                =
                        |     11 +
 head/contrib/llvm/include/llvm/Target/TargetData.h                        =
                        |     34 +-
 head/contrib/llvm/include/llvm/Target/TargetELFWriterInfo.h               =
                        |      3 -
 head/contrib/llvm/include/llvm/Target/TargetFrameLowering.h               =
                        |      4 -
 head/contrib/llvm/include/llvm/Target/TargetInstrInfo.h                   =
                        |    128 +-
 head/contrib/llvm/include/llvm/Target/TargetJITInfo.h                     =
                        |     21 +-
 head/contrib/llvm/include/llvm/Target/TargetLibraryInfo.h                 =
                        |    248 +-
 head/contrib/llvm/include/llvm/Target/TargetLowering.h                    =
                        |    138 +-
 head/contrib/llvm/include/llvm/Target/TargetLoweringObjectFile.h          =
                        |     30 +-
 head/contrib/llvm/include/llvm/Target/TargetMachine.h                     =
                        |    138 +-
 head/contrib/llvm/include/llvm/Target/TargetOpcodes.h                     =
                        |      7 +-
 head/contrib/llvm/include/llvm/Target/TargetOptions.h                     =
                        |    252 +-
 head/contrib/llvm/include/llvm/Target/TargetRegisterInfo.h                =
                        |    124 +-
 head/contrib/llvm/include/llvm/Target/TargetSelectionDAG.td               =
                        |     47 +
 head/contrib/llvm/include/llvm/Target/TargetSubtargetInfo.h               =
                        |      4 +-
 head/contrib/llvm/include/llvm/Transforms/IPO.h                           =
                        |      1 +
 head/contrib/llvm/include/llvm/Transforms/IPO/InlinerPass.h               =
                        |     27 +-
 head/contrib/llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h        =
                        |     20 +-
 head/contrib/llvm/include/llvm/Transforms/Instrumentation.h               =
                        |      9 +-
 head/contrib/llvm/include/llvm/Transforms/Scalar.h                        =
                        |     14 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h         =
                        |      5 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/BuildLibCalls.h           =
                        |      8 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/Cloning.h                 =
                        |     23 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/SSAUpdater.h              =
                        |     21 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/SSAUpdaterImpl.h          =
                        |     51 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/SimplifyIndVar.h          =
                        |     16 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/UnrollLoop.h              =
                        |      5 +-
 head/contrib/llvm/include/llvm/Transforms/Utils/ValueMapper.h             =
                        |      2 +-
 head/contrib/llvm/include/llvm/Type.h                                     =
                        |    150 +-
 head/contrib/llvm/include/llvm/User.h                                     =
                        |      6 +-
 head/contrib/llvm/include/llvm/Value.h                                    =
                        |     47 +-
 head/contrib/llvm/lib/Analysis/AliasAnalysis.cpp                          =
                        |     16 +
 head/contrib/llvm/lib/Analysis/AliasAnalysisCounter.cpp                   =
                        |      6 +-
 head/contrib/llvm/lib/Analysis/AliasAnalysisEvaluator.cpp                 =
                        |      4 -
 head/contrib/llvm/lib/Analysis/AliasSetTracker.cpp                        =
                        |      4 +-
 head/contrib/llvm/lib/Analysis/BasicAliasAnalysis.cpp                     =
                        |     59 +-
 head/contrib/llvm/lib/Analysis/BlockFrequencyInfo.cpp                     =
                        |      2 +-
 head/contrib/llvm/lib/Analysis/BranchProbabilityInfo.cpp                  =
                        |    395 +-
 head/contrib/llvm/lib/Analysis/CFGPrinter.cpp                             =
                        |      8 +-
 head/contrib/llvm/lib/Analysis/CaptureTracking.cpp                        =
                        |     95 +-
 head/contrib/llvm/lib/Analysis/ConstantFolding.cpp                        =
                        |    373 +-
 head/contrib/llvm/lib/Analysis/DIBuilder.cpp                              =
                        |    112 +-
 head/contrib/llvm/lib/Analysis/DebugInfo.cpp                              =
                        |    110 +-
 head/contrib/llvm/lib/Analysis/DominanceFrontier.cpp                      =
                        |      2 +
 head/contrib/llvm/lib/Analysis/IPA/CallGraph.cpp                          =
                        |     13 +-
 head/contrib/llvm/lib/Analysis/IPA/GlobalsModRef.cpp                      =
                        |      6 +
 head/contrib/llvm/lib/Analysis/IVUsers.cpp                                =
                        |     67 +-
 head/contrib/llvm/lib/Analysis/InlineCost.cpp                             =
                        |   1557 +-
 head/contrib/llvm/lib/Analysis/InstructionSimplify.cpp                    =
                        |   1175 +-
 head/contrib/llvm/lib/Analysis/LazyValueInfo.cpp                          =
                        |    123 +-
 head/contrib/llvm/lib/Analysis/Lint.cpp                                   =
                        |     19 +-
 head/contrib/llvm/lib/Analysis/Loads.cpp                                  =
                        |     16 +-
 head/contrib/llvm/lib/Analysis/LoopDependenceAnalysis.cpp                 =
                        |      2 -
 head/contrib/llvm/lib/Analysis/LoopInfo.cpp                               =
                        |    127 +-
 head/contrib/llvm/lib/Analysis/LoopPass.cpp                               =
                        |     23 +-
 head/contrib/llvm/lib/Analysis/MemDepPrinter.cpp                          =
                        |      2 +-
 head/contrib/llvm/lib/Analysis/MemoryBuiltins.cpp                         =
                        |      8 +-
 head/contrib/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp               =
                        |     94 +-
 head/contrib/llvm/lib/Analysis/PHITransAddr.cpp                           =
                        |     13 +-
 head/contrib/llvm/lib/Analysis/PathNumbering.cpp                          =
                        |      4 +-
 head/contrib/llvm/lib/Analysis/PathProfileVerifier.cpp                    =
                        |     16 +-
 head/contrib/llvm/lib/Analysis/ProfileEstimatorPass.cpp                   =
                        |      2 +-
 head/contrib/llvm/lib/Analysis/ProfileInfoLoaderPass.cpp                  =
                        |      4 +-
 head/contrib/llvm/lib/Analysis/ProfileVerifierPass.cpp                    =
                        |     18 +-
 head/contrib/llvm/lib/Analysis/RegionInfo.cpp                             =
                        |      8 +-
 head/contrib/llvm/lib/Analysis/ScalarEvolution.cpp                        =
                        |    476 +-
 head/contrib/llvm/lib/Analysis/ScalarEvolutionExpander.cpp                =
                        |    513 +-
 head/contrib/llvm/lib/Analysis/ScalarEvolutionNormalization.cpp           =
                        |      2 -
 head/contrib/llvm/lib/Analysis/SparsePropagation.cpp                      =
                        |      8 +-
 head/contrib/llvm/lib/Analysis/Trace.cpp                                  =
                        |      2 +-
 head/contrib/llvm/lib/Analysis/ValueTracking.cpp                          =
                        |    985 +-
 head/contrib/llvm/lib/Archive/ArchiveReader.cpp                           =
                        |     31 +-
 head/contrib/llvm/lib/Archive/ArchiveWriter.cpp                           =
                        |      6 +-
 head/contrib/llvm/lib/AsmParser/LLLexer.cpp                               =
                        |     62 +-
 head/contrib/llvm/lib/AsmParser/LLLexer.h                                 =
                        |      1 -
 head/contrib/llvm/lib/AsmParser/LLParser.cpp                              =
                        |    127 +-
 head/contrib/llvm/lib/AsmParser/LLParser.h                                =
                        |     15 +-
 head/contrib/llvm/lib/AsmParser/LLToken.h                                 =
                        |      4 +-
 head/contrib/llvm/lib/AsmParser/Parser.cpp                                =
                        |      2 +-
 head/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp                    =
                        |    680 +-
 head/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.h                      =
                        |     40 +-
 head/contrib/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp                    =
                        |    320 +-
 head/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp                  =
                        |     44 +-
 head/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.h                    =
                        |      4 +
 head/contrib/llvm/lib/CodeGen/AggressiveAntiDepBreaker.cpp                =
                        |     29 +-
 head/contrib/llvm/lib/CodeGen/AllocationOrder.cpp                         =
                        |      2 +-
 head/contrib/llvm/lib/CodeGen/AllocationOrder.h                           =
                        |      3 +-
 head/contrib/llvm/lib/CodeGen/Analysis.cpp                                =
                        |     73 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/ARMException.cpp                 =
                        |     19 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp                   =
                        |    304 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp              =
                        |     45 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp          =
                        |      6 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DIE.cpp                          =
                        |     42 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DIE.h                            =
                        |     87 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCFIException.cpp            =
                        |      6 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp             =
                        |    299 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h               =
                        |     68 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp                   =
                        |    427 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h                     =
                        |     56 +-
 head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfException.cpp               =
                        |     46 +-
 head/contrib/llvm/lib/CodeGen/BranchFolding.cpp                           =
                        |    129 +-
 head/contrib/llvm/lib/CodeGen/CallingConvLower.cpp                        =
                        |      2 +-
 head/contrib/llvm/lib/CodeGen/CodeGen.cpp                                 =
                        |     17 +-
 head/contrib/llvm/lib/CodeGen/CodePlacementOpt.cpp                        =
                        |      9 +-
 head/contrib/llvm/lib/CodeGen/CriticalAntiDepBreaker.cpp                  =
                        |     72 +-
 head/contrib/llvm/lib/CodeGen/CriticalAntiDepBreaker.h                    =
                        |      3 +-
 head/contrib/llvm/lib/CodeGen/DeadMachineInstructionElim.cpp              =
                        |     31 +-
 head/contrib/llvm/lib/CodeGen/DwarfEHPrepare.cpp                          =
                        |    701 +-
 head/contrib/llvm/lib/CodeGen/EdgeBundles.cpp                             =
                        |      2 +-
 head/contrib/llvm/lib/CodeGen/ExecutionDepsFix.cpp                        =
                        |    524 +-
 head/contrib/llvm/lib/CodeGen/ExpandISelPseudos.cpp                       =
                        |     14 +-
 head/contrib/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp                     =
                        |     12 +-
 head/contrib/llvm/lib/CodeGen/GCMetadata.cpp                              =
                        |      6 +-
 head/contrib/llvm/lib/CodeGen/GCStrategy.cpp                              =
                        |    160 +-
 head/contrib/llvm/lib/CodeGen/IfConversion.cpp                            =
                        |    132 +-
 head/contrib/llvm/lib/CodeGen/InlineSpiller.cpp                           =
                        |    191 +-
 head/contrib/llvm/lib/CodeGen/InterferenceCache.cpp                       =
                        |     35 +-
 head/contrib/llvm/lib/CodeGen/InterferenceCache.h                         =
                        |     15 +-
 head/contrib/llvm/lib/CodeGen/IntrinsicLowering.cpp                       =
                        |      5 -
 head/contrib/llvm/lib/CodeGen/LLVMTargetMachine.cpp                       =
                        |    436 +-
 head/contrib/llvm/lib/CodeGen/LatencyPriorityQueue.cpp                    =
                        |      6 +-
 head/contrib/llvm/lib/CodeGen/LexicalScopes.cpp                           =
                        |      2 +
 head/contrib/llvm/lib/CodeGen/LiveDebugVariables.cpp                      =
                        |     23 +-
 head/contrib/llvm/lib/CodeGen/LiveInterval.cpp                            =
                        |     36 +-
 head/contrib/llvm/lib/CodeGen/LiveIntervalAnalysis.cpp                    =
                        |   2144 +-
 head/contrib/llvm/lib/CodeGen/LiveIntervalUnion.cpp                       =
                        |      2 +
 head/contrib/llvm/lib/CodeGen/LiveIntervalUnion.h                         =
                        |      2 -
 head/contrib/llvm/lib/CodeGen/LiveRangeCalc.cpp                           =
                        |      4 +-
 head/contrib/llvm/lib/CodeGen/LiveRangeEdit.cpp                           =
                        |    110 +-
 head/contrib/llvm/lib/CodeGen/LiveVariables.cpp                           =
                        |    114 +-
 head/contrib/llvm/lib/CodeGen/LocalStackSlotAllocation.cpp                =
                        |     10 +-
 head/contrib/llvm/lib/CodeGen/MachineBasicBlock.cpp                       =
                        |    221 +-
 head/contrib/llvm/lib/CodeGen/MachineBlockFrequencyInfo.cpp               =
                        |      2 +-
 head/contrib/llvm/lib/CodeGen/MachineBranchProbabilityInfo.cpp            =
                        |     65 +-
 head/contrib/llvm/lib/CodeGen/MachineCSE.cpp                              =
                        |    108 +-
 head/contrib/llvm/lib/CodeGen/MachineFunction.cpp                         =
                        |     91 +-
 head/contrib/llvm/lib/CodeGen/MachineFunctionAnalysis.cpp                 =
                        |      5 +-
 head/contrib/llvm/lib/CodeGen/MachineInstr.cpp                            =
                        |    252 +-
 head/contrib/llvm/lib/CodeGen/MachineLICM.cpp                             =
                        |    616 +-
 head/contrib/llvm/lib/CodeGen/MachineModuleInfo.cpp                       =
                        |     18 +-
 head/contrib/llvm/lib/CodeGen/MachinePassRegistry.cpp                     =
                        |      1 +
 head/contrib/llvm/lib/CodeGen/MachineRegisterInfo.cpp                     =
                        |     65 +-
 head/contrib/llvm/lib/CodeGen/MachineSSAUpdater.cpp                       =
                        |      7 +-
 head/contrib/llvm/lib/CodeGen/MachineSink.cpp                             =
                        |    286 +-
 head/contrib/llvm/lib/CodeGen/MachineVerifier.cpp                         =
                        |    468 +-
 head/contrib/llvm/lib/CodeGen/OptimizePHIs.cpp                            =
                        |      9 +-
 head/contrib/llvm/lib/CodeGen/PHIElimination.cpp                          =
                        |     13 +-
 head/contrib/llvm/lib/CodeGen/Passes.cpp                                  =
                        |    609 +-
 head/contrib/llvm/lib/CodeGen/PeepholeOptimizer.cpp                       =
                        |     35 +-
 head/contrib/llvm/lib/CodeGen/PostRASchedulerList.cpp                     =
                        |    256 +-
 head/contrib/llvm/lib/CodeGen/ProcessImplicitDefs.cpp                     =
                        |     36 +-
 head/contrib/llvm/lib/CodeGen/PrologEpilogInserter.cpp                    =
                        |     41 +-
 head/contrib/llvm/lib/CodeGen/PrologEpilogInserter.h                      =
                        |      4 -
 head/contrib/llvm/lib/CodeGen/PseudoSourceValue.cpp                       =
                        |      2 -
 head/contrib/llvm/lib/CodeGen/RegAllocBase.h                              =
                        |     36 +-
 head/contrib/llvm/lib/CodeGen/RegAllocBasic.cpp                           =
                        |    316 +-
 head/contrib/llvm/lib/CodeGen/RegAllocFast.cpp                            =
                        |    323 +-
 head/contrib/llvm/lib/CodeGen/RegAllocGreedy.cpp                          =
                        |    110 +-
 head/contrib/llvm/lib/CodeGen/RegAllocPBQP.cpp                            =
                        |    171 +-
 head/contrib/llvm/lib/CodeGen/RegisterClassInfo.cpp                       =
                        |     16 +-
 head/contrib/llvm/lib/CodeGen/RegisterClassInfo.h                         =
                        |      2 +-
 head/contrib/llvm/lib/CodeGen/RegisterCoalescer.cpp                       =
                        |    252 +-
 head/contrib/llvm/lib/CodeGen/RegisterCoalescer.h                         =
                        |      6 +-
 head/contrib/llvm/lib/CodeGen/RegisterScavenging.cpp                      =
                        |     67 +-
 head/contrib/llvm/lib/CodeGen/RenderMachineFunction.cpp                   =
                        |     19 +-
 head/contrib/llvm/lib/CodeGen/ScheduleDAG.cpp                             =
                        |     62 +-
 head/contrib/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp                       =
                        |    654 +-
 head/contrib/llvm/lib/CodeGen/ScheduleDAGPrinter.cpp                      =
                        |     24 +-
 head/contrib/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp              =
                        |      4 -
 head/contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp                =
                        |   1128 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp                   =
                        |    215 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp       =
                        |     67 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp               =
                        |    117 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp                =
                        |   1263 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp         =
                        |     10 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp       =
                        |    134 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp              =
                        |     20 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h                =
                        |      2 +
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp       =
                        |     13 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp          =
                        |    140 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp        =
                        |    163 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp            =
                        |     30 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp          =
                        |    656 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp         =
                        |    130 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h           =
                        |     40 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp               =
                        |   1054 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp        =
                        |    633 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h          =
                        |     18 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp           =
                        |    268 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp        =
                        |      4 +-
 head/contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp             =
                        |    215 +-
 head/contrib/llvm/lib/CodeGen/ShadowStackGC.cpp                           =
                        |      3 +-
 head/contrib/llvm/lib/CodeGen/ShrinkWrapping.cpp                          =
                        |      7 +-
 head/contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp                           =
                        |    775 +-
 head/contrib/llvm/lib/CodeGen/SlotIndexes.cpp                             =
                        |     12 +-
 head/contrib/llvm/lib/CodeGen/Spiller.cpp                                 =
                        |     81 +-
 head/contrib/llvm/lib/CodeGen/Spiller.h                                   =
                        |      1 +
 head/contrib/llvm/lib/CodeGen/SplitKit.cpp                                =
                        |     85 +-
 head/contrib/llvm/lib/CodeGen/SplitKit.h                                  =
                        |     15 +-
 head/contrib/llvm/lib/CodeGen/StackProtector.cpp                          =
                        |      7 +-
 head/contrib/llvm/lib/CodeGen/StackSlotColoring.cpp                       =
                        |    358 +-
 head/contrib/llvm/lib/CodeGen/StrongPHIElimination.cpp                    =
                        |     18 +-
 head/contrib/llvm/lib/CodeGen/TailDuplication.cpp                         =
                        |     39 +-
 head/contrib/llvm/lib/CodeGen/TargetInstrInfoImpl.cpp                     =
                        |    106 +-
 head/contrib/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp            =
                        |    123 +-
 head/contrib/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp               =
                        |    525 +-
 head/contrib/llvm/lib/CodeGen/VirtRegMap.cpp                              =
                        |    168 +-
 head/contrib/llvm/lib/CodeGen/VirtRegMap.h                                =
                        |    335 +-
 head/contrib/llvm/lib/DebugInfo/DWARFContext.cpp                          =
                        |      2 +
 head/contrib/llvm/lib/DebugInfo/DWARFContext.h                            =
                        |      1 +
 head/contrib/llvm/lib/DebugInfo/DWARFDebugAbbrev.cpp                      =
                        |      2 +-
 head/contrib/llvm/lib/DebugInfo/DWARFDebugAbbrev.h                        =
                        |      6 +-
 head/contrib/llvm/lib/DebugInfo/DWARFDebugArangeSet.cpp                   =
                        |      5 +-
 head/contrib/llvm/lib/DebugInfo/DWARFDebugAranges.cpp                     =
                        |      7 +-
 head/contrib/llvm/lib/DebugInfo/DWARFDebugInfoEntry.cpp                   =
                        |      4 +-
 head/contrib/llvm/lib/DebugInfo/DWARFDebugInfoEntry.h                     =
                        |      4 +-
 head/contrib/llvm/lib/DebugInfo/DWARFDebugLine.cpp                        =
                        |      7 +-
 head/contrib/llvm/lib/DebugInfo/DWARFFormValue.cpp                        =
                        |     20 +-
 head/contrib/llvm/lib/ExecutionEngine/ExecutionEngine.cpp                 =
                        |    108 +-
 head/contrib/llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp         =
                        |      2 -
 head/contrib/llvm/lib/ExecutionEngine/Interpreter/Execution.cpp           =
                        |     29 +-
 head/contrib/llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.cpp   =
                        |     31 +-
 head/contrib/llvm/lib/ExecutionEngine/Interpreter/Interpreter.h           =
                        |      7 +-
 head/contrib/llvm/lib/ExecutionEngine/JIT/JIT.cpp                         =
                        |     45 +-
 head/contrib/llvm/lib/ExecutionEngine/JIT/JIT.h                           =
                        |     11 +-
 head/contrib/llvm/lib/ExecutionEngine/JIT/JITDwarfEmitter.cpp             =
                        |      2 +-
 head/contrib/llvm/lib/ExecutionEngine/JIT/JITEmitter.cpp                  =
                        |     43 +-
 head/contrib/llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp            =
                        |    194 +
 head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp                     =
                        |     41 +-
 head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h                       =
                        |     17 +-
 head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJITMemoryManager.h          =
                        |     47 +-
 head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp         =
                        |    446 +-
 head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h       =
                        |    236 +-
 head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cpp    =
                        |    573 +-
 head/contrib/llvm/lib/ExecutionEngine/TargetSelect.cpp                    =
                        |     41 +-
 head/contrib/llvm/lib/Linker/LinkArchives.cpp                             =
                        |      5 +-
 head/contrib/llvm/lib/Linker/LinkModules.cpp                              =
                        |    513 +-
 head/contrib/llvm/lib/Linker/Linker.cpp                                   =
                        |      1 -
 head/contrib/llvm/lib/MC/ELFObjectWriter.cpp                              =
                        |    935 +-
 head/contrib/llvm/lib/MC/MCAsmBackend.cpp                                 =
                        |     21 +-
 head/contrib/llvm/lib/MC/MCAsmInfo.cpp                                    =
                        |      4 +-
 head/contrib/llvm/lib/MC/MCAsmInfoCOFF.cpp                                =
                        |     15 +-
 head/contrib/llvm/lib/MC/MCAsmInfoDarwin.cpp                              =
                        |      7 +-
 head/contrib/llvm/lib/MC/MCAsmStreamer.cpp                                =
                        |    106 +-
 head/contrib/llvm/lib/MC/MCAssembler.cpp                                  =
                        |    124 +-
 head/contrib/llvm/lib/MC/MCCodeGenInfo.cpp                                =
                        |      4 +-
 head/contrib/llvm/lib/MC/MCContext.cpp                                    =
                        |     60 +-
 head/contrib/llvm/lib/MC/MCDisassembler/Disassembler.cpp                  =
                        |     18 +-
 head/contrib/llvm/lib/MC/MCDisassembler/Disassembler.h                    =
                        |     10 +
 head/contrib/llvm/lib/MC/MCDisassembler/EDDisassembler.cpp                =
                        |    116 +-
 head/contrib/llvm/lib/MC/MCDisassembler/EDDisassembler.h                  =
                        |     23 +-
 head/contrib/llvm/lib/MC/MCDisassembler/EDOperand.cpp                     =
                        |     20 +-
 head/contrib/llvm/lib/MC/MCDwarf.cpp                                      =
                        |    459 +-
 head/contrib/llvm/lib/MC/MCELF.cpp                                        =
                        |      4 +-
 head/contrib/llvm/lib/MC/MCELFObjectTargetWriter.cpp                      =
                        |     29 +-
 head/contrib/llvm/lib/MC/MCELFStreamer.cpp                                =
                        |    158 +-
 head/contrib/llvm/lib/MC/MCExpr.cpp                                       =
                        |     42 +-
 head/contrib/llvm/lib/MC/MCInst.cpp                                       =
                        |      2 +
 head/contrib/llvm/lib/MC/MCInstPrinter.cpp                                =
                        |      6 +-
 head/contrib/llvm/lib/MC/MCMachOStreamer.cpp                              =
                        |     27 +-
 head/contrib/llvm/lib/MC/MCModule.cpp                                     =
                        |      2 +-
 head/contrib/llvm/lib/MC/MCNullStreamer.cpp                               =
                        |     14 +-
 head/contrib/llvm/lib/MC/MCObjectFileInfo.cpp                             =
                        |    101 +-
 head/contrib/llvm/lib/MC/MCObjectStreamer.cpp                             =
                        |     52 +-
 head/contrib/llvm/lib/MC/MCObjectWriter.cpp                               =
                        |     14 +-
 head/contrib/llvm/lib/MC/MCParser/AsmParser.cpp                           =
                        |    279 +-
 head/contrib/llvm/lib/MC/MCParser/COFFAsmParser.cpp                       =
                        |     17 +
 head/contrib/llvm/lib/MC/MCParser/ELFAsmParser.cpp                        =
                        |      1 +
 head/contrib/llvm/lib/MC/MCParser/MCAsmLexer.cpp                          =
                        |      4 +
 head/contrib/llvm/lib/MC/MCParser/MCAsmParser.cpp                         =
                        |      4 +-
 head/contrib/llvm/lib/MC/MCPureStreamer.cpp                               =
                        |     15 +-
 head/contrib/llvm/lib/MC/MCStreamer.cpp                                   =
                        |    109 +-
 head/contrib/llvm/lib/MC/MCSymbol.cpp                                     =
                        |      7 +-
 head/contrib/llvm/lib/MC/MachObjectWriter.cpp                             =
                        |     15 +-
 head/contrib/llvm/lib/MC/SubtargetFeature.cpp                             =
                        |     24 +-
 head/contrib/llvm/lib/MC/WinCOFFObjectWriter.cpp                          =
                        |     89 +-
 head/contrib/llvm/lib/MC/WinCOFFStreamer.cpp                              =
                        |     20 +-
 head/contrib/llvm/lib/Object/Archive.cpp                                  =
                        |    142 +-
 head/contrib/llvm/lib/Object/COFFObjectFile.cpp                           =
                        |    319 +-
 head/contrib/llvm/lib/Object/ELFObjectFile.cpp                            =
                        |   1415 +-
 head/contrib/llvm/lib/Object/MachOObject.cpp                              =
                        |     35 +-
 head/contrib/llvm/lib/Object/MachOObjectFile.cpp                          =
                        |    694 +-
 head/contrib/llvm/lib/Object/Object.cpp                                   =
                        |    150 +
 head/contrib/llvm/lib/Object/ObjectFile.cpp                               =
                        |      4 +-
 head/contrib/llvm/lib/Support/APFloat.cpp                                 =
                        |    127 +-
 head/contrib/llvm/lib/Support/APInt.cpp                                   =
                        |    223 +-
 head/contrib/llvm/lib/Support/Allocator.cpp                               =
                        |      4 +-
 head/contrib/llvm/lib/Support/Atomic.cpp                                  =
                        |      2 +-
 head/contrib/llvm/lib/Support/BlockFrequency.cpp                          =
                        |     12 +-
 head/contrib/llvm/lib/Support/BranchProbability.cpp                       =
                        |     13 +-
 head/contrib/llvm/lib/Support/CommandLine.cpp                             =
                        |     26 +-
 head/contrib/llvm/lib/Support/ConstantRange.cpp                           =
                        |    100 +-
 head/contrib/llvm/lib/Support/CrashRecoveryContext.cpp                    =
                        |      1 -
 head/contrib/llvm/lib/Support/DAGDeltaAlgorithm.cpp                       =
                        |      3 +
 head/contrib/llvm/lib/Support/DataExtractor.cpp                           =
                        |      2 +-
 head/contrib/llvm/lib/Support/Dwarf.cpp                                   =
                        |      2 +
 head/contrib/llvm/lib/Support/FileUtilities.cpp                           =
                        |      1 -
 head/contrib/llvm/lib/Support/FoldingSet.cpp                              =
                        |     26 +-
 head/contrib/llvm/lib/Support/GraphWriter.cpp                             =
                        |     77 +-
 head/contrib/llvm/lib/Support/Host.cpp                                    =
                        |     13 +-
 head/contrib/llvm/lib/Support/ManagedStatic.cpp                           =
                        |      8 +-
 head/contrib/llvm/lib/Support/MemoryBuffer.cpp                            =
                        |     38 +-
 head/contrib/llvm/lib/Support/Mutex.cpp                                   =
                        |    109 +-
 head/contrib/llvm/lib/Support/Path.cpp                                    =
                        |     36 +-
 head/contrib/llvm/lib/Support/PathV2.cpp                                  =
                        |    179 +-
 head/contrib/llvm/lib/Support/Program.cpp                                 =
                        |      1 +
 head/contrib/llvm/lib/Support/RWMutex.cpp                                 =
                        |     96 +-
 head/contrib/llvm/lib/Support/SmallPtrSet.cpp                             =
                        |     51 +
 head/contrib/llvm/lib/Support/SourceMgr.cpp                               =
                        |    141 +-
 head/contrib/llvm/lib/Support/Statistic.cpp                               =
                        |     16 +-
 head/contrib/llvm/lib/Support/StringExtras.cpp                            =
                        |     21 -
 head/contrib/llvm/lib/Support/StringMap.cpp                               =
                        |     61 +-
 head/contrib/llvm/lib/Support/StringRef.cpp                               =
                        |    168 +-
 head/contrib/llvm/lib/Support/TargetRegistry.cpp                          =
                        |      2 +-
 head/contrib/llvm/lib/Support/ThreadLocal.cpp                             =
                        |      2 +-
 head/contrib/llvm/lib/Support/Threading.cpp                               =
                        |      8 +-
 head/contrib/llvm/lib/Support/Timer.cpp                                   =
                        |     16 +-
 head/contrib/llvm/lib/Support/Triple.cpp                                  =
                        |    636 +-
 head/contrib/llvm/lib/Support/Unix/Host.inc                               =
                        |     23 +-
 head/contrib/llvm/lib/Support/Unix/Path.inc                               =
                        |     16 +-
 head/contrib/llvm/lib/Support/Unix/PathV2.inc                             =
                        |     85 +-
 head/contrib/llvm/lib/Support/Unix/Process.inc                            =
                        |      8 +-
 head/contrib/llvm/lib/Support/Unix/Program.inc                            =
                        |     12 +-
 head/contrib/llvm/lib/Support/Unix/Signals.inc                            =
                        |     20 +
 head/contrib/llvm/lib/Support/Valgrind.cpp                                =
                        |     13 +
 head/contrib/llvm/lib/Support/Windows/Host.inc                            =
                        |      5 +-
 head/contrib/llvm/lib/Support/Windows/Path.inc                            =
                        |     35 +-
 head/contrib/llvm/lib/Support/Windows/PathV2.inc                          =
                        |    170 +-
 head/contrib/llvm/lib/Support/Windows/Process.inc                         =
                        |      4 -
 head/contrib/llvm/lib/Support/Windows/Program.inc                         =
                        |     36 +-
 head/contrib/llvm/lib/Support/Windows/Signals.inc                         =
                        |      4 +-
 head/contrib/llvm/lib/Support/Windows/Windows.h                           =
                        |    120 +-
 head/contrib/llvm/lib/Support/raw_ostream.cpp                             =
                        |      1 +
 head/contrib/llvm/lib/TableGen/Error.cpp                                  =
                        |      4 +-
 head/contrib/llvm/lib/TableGen/Record.cpp                                 =
                        |    173 +-
 head/contrib/llvm/lib/TableGen/TGLexer.cpp                                =
                        |     57 +-
 head/contrib/llvm/lib/TableGen/TGLexer.h                                  =
                        |      6 +-
 head/contrib/llvm/lib/TableGen/TGParser.cpp                               =
                        |    554 +-
 head/contrib/llvm/lib/TableGen/TGParser.h                                 =
                        |     73 +-
 head/contrib/llvm/lib/TableGen/TableGenBackend.cpp                        =
                        |      4 +-
 head/contrib/llvm/lib/Target/ARM/ARM.h                                    =
                        |      4 +-
 head/contrib/llvm/lib/Target/ARM/ARM.td                                   =
                        |     20 +-
 head/contrib/llvm/lib/Target/ARM/ARMAsmPrinter.cpp                        =
                        |    165 +-
 head/contrib/llvm/lib/Target/ARM/ARMAsmPrinter.h                          =
                        |      5 +-
 head/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp                     =
                        |    665 +-
 head/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.h                       =
                        |     18 +-
 head/contrib/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp                  =
                        |    220 +-
 head/contrib/llvm/lib/Target/ARM/ARMBaseRegisterInfo.h                    =
                        |     28 +-
 head/contrib/llvm/lib/Target/ARM/ARMBuildAttrs.h                          =
                        |      2 +-
 head/contrib/llvm/lib/Target/ARM/ARMCallingConv.h                         =
                        |     21 +-
 head/contrib/llvm/lib/Target/ARM/ARMCallingConv.td                        =
                        |     38 +-
 head/contrib/llvm/lib/Target/ARM/ARMCodeEmitter.cpp                       =
                        |     25 +-
 head/contrib/llvm/lib/Target/ARM/ARMConstantIslandPass.cpp                =
                        |   1317 +-
 head/contrib/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp                 =
                        |      8 +-
 head/contrib/llvm/lib/Target/ARM/ARMConstantPoolValue.h                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/ARM/ARMELFWriterInfo.cpp                     =
                        |     33 +-
 head/contrib/llvm/lib/Target/ARM/ARMELFWriterInfo.h                       =
                        |      1 +
 head/contrib/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp                 =
                        |    539 +-
 head/contrib/llvm/lib/Target/ARM/ARMFastISel.cpp                          =
                        |   1333 +-
 head/contrib/llvm/lib/Target/ARM/ARMFrameLowering.cpp                     =
                        |    454 +-
 head/contrib/llvm/lib/Target/ARM/ARMFrameLowering.h                       =
                        |      5 +-
 head/contrib/llvm/lib/Target/ARM/ARMHazardRecognizer.cpp                  =
                        |     28 +-
 head/contrib/llvm/lib/Target/ARM/ARMHazardRecognizer.h                    =
                        |      8 +-
 head/contrib/llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp                      =
                        |    284 +-
 head/contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp                      =
                        |   1158 +-
 head/contrib/llvm/lib/Target/ARM/ARMISelLowering.h                        =
                        |     29 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrFormats.td                       =
                        |    112 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.cpp                         =
                        |     19 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.h                           =
                        |      8 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.td                          =
                        |    775 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrNEON.td                          =
                        |   3197 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrThumb.td                         =
                        |    127 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrThumb2.td                        =
                        |    407 +-
 head/contrib/llvm/lib/Target/ARM/ARMInstrVFP.td                           =
                        |    492 +-
 head/contrib/llvm/lib/Target/ARM/ARMJITInfo.cpp                           =
                        |      6 +-
 head/contrib/llvm/lib/Target/ARM/ARMJITInfo.h                             =
                        |      2 +-
 head/contrib/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp                =
                        |    214 +-
 head/contrib/llvm/lib/Target/ARM/ARMMCInstLower.cpp                       =
                        |     10 +-
 head/contrib/llvm/lib/Target/ARM/ARMMachineFunctionInfo.h                 =
                        |     19 +-
 head/contrib/llvm/lib/Target/ARM/ARMPerfectShuffle.h                      =
                        |      2 +-
 head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.cpp                      =
                        |      6 +-
 head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.h                        =
                        |      6 +-
 head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.td                       =
                        |    188 +-
 head/contrib/llvm/lib/Target/ARM/ARMRelocations.h                         =
                        |      2 +-
 head/contrib/llvm/lib/Target/ARM/ARMSchedule.td                           =
                        |     10 +-
 head/contrib/llvm/lib/Target/ARM/ARMScheduleA8.td                         =
                        |     19 +
 head/contrib/llvm/lib/Target/ARM/ARMScheduleA9.td                         =
                        |     36 +
 head/contrib/llvm/lib/Target/ARM/ARMScheduleV6.td                         =
                        |     12 +-
 head/contrib/llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp                  =
                        |     10 +-
 head/contrib/llvm/lib/Target/ARM/ARMSubtarget.cpp                         =
                        |     12 +-
 head/contrib/llvm/lib/Target/ARM/ARMSubtarget.h                           =
                        |     18 +-
 head/contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp                     =
                        |    108 +-
 head/contrib/llvm/lib/Target/ARM/ARMTargetMachine.h                       =
                        |     24 +-
 head/contrib/llvm/lib/Target/ARM/ARMTargetObjectFile.cpp                  =
                        |     34 +-
 head/contrib/llvm/lib/Target/ARM/ARMTargetObjectFile.h                    =
                        |      4 +
 head/contrib/llvm/lib/Target/ARM/AsmParser/ARMAsmLexer.cpp                =
                        |      9 +-
 head/contrib/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp               =
                        |   3578 +-
 head/contrib/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp         =
                        |   1407 +-
 head/contrib/llvm/lib/Target/ARM/InstPrinter/ARMInstPrinter.cpp           =
                        |    192 +-
 head/contrib/llvm/lib/Target/ARM/InstPrinter/ARMInstPrinter.h             =
                        |     34 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h        =
                        |     11 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp           =
                        |    180 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h               =
                        |     36 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h             =
                        |     24 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp            =
                        |      6 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h              =
                        |     10 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp        =
                        |     76 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp               =
                        |      5 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.h                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp         =
                        |     24 +-
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h           =
                        |      4 +
 head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp     =
                        |    116 +-
 head/contrib/llvm/lib/Target/ARM/MLxExpansionPass.cpp                     =
                        |     10 +-
 head/contrib/llvm/lib/Target/ARM/Thumb1FrameLowering.cpp                  =
                        |     19 +-
 head/contrib/llvm/lib/Target/ARM/Thumb1InstrInfo.cpp                      =
                        |     22 +-
 head/contrib/llvm/lib/Target/ARM/Thumb1InstrInfo.h                        =
                        |      8 +-
 head/contrib/llvm/lib/Target/ARM/Thumb1RegisterInfo.cpp                   =
                        |     35 +-
 head/contrib/llvm/lib/Target/ARM/Thumb1RegisterInfo.h                     =
                        |      3 +-
 head/contrib/llvm/lib/Target/ARM/Thumb2ITBlockPass.cpp                    =
                        |     21 +-
 head/contrib/llvm/lib/Target/ARM/Thumb2InstrInfo.cpp                      =
                        |     31 +-
 head/contrib/llvm/lib/Target/ARM/Thumb2InstrInfo.h                        =
                        |      8 +-
 head/contrib/llvm/lib/Target/ARM/Thumb2RegisterInfo.cpp                   =
                        |      6 +-
 head/contrib/llvm/lib/Target/ARM/Thumb2RegisterInfo.h                     =
                        |      3 +-
 head/contrib/llvm/lib/Target/ARM/Thumb2SizeReduction.cpp                  =
                        |    141 +-
 head/contrib/llvm/lib/Target/CellSPU/CellSDKIntrinsics.td                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.cpp        =
                        |      2 +
 head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.h          =
                        |      4 +-
 head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.cpp     =
                        |      8 +-
 head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.h       =
                        |      2 -
 head/contrib/llvm/lib/Target/CellSPU/SPU.h                                =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPU.td                               =
                        |      4 +-
 head/contrib/llvm/lib/Target/CellSPU/SPU128InstrInfo.td                   =
                        |      4 +-
 head/contrib/llvm/lib/Target/CellSPU/SPU64InstrInfo.td                    =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUAsmPrinter.cpp                    =
                        |      3 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUCallingConv.td                    =
                        |      4 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUFrameLowering.cpp                 =
                        |      5 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUFrameLowering.h                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUISelDAGToDAG.cpp                  =
                        |     18 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUISelLowering.cpp                  =
                        |    140 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUISelLowering.h                    =
                        |      5 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUInstrBuilder.h                    =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUInstrFormats.td                   =
                        |      6 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUInstrInfo.cpp                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUInstrInfo.h                       =
                        |      4 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUMachineFunction.h                 =
                        |      3 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUMathInstr.td                      =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUNodes.td                          =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUNopFiller.cpp                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUOperands.td                       =
                        |      6 +-
 head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.cpp                  =
                        |      8 +-
 head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.h                    =
                        |      4 +-
 head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.td                   =
                        |      6 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUSchedule.td                       =
                        |      6 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUSubtarget.cpp                     =
                        |      3 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUTargetMachine.cpp                 =
                        |     41 +-
 head/contrib/llvm/lib/Target/CellSPU/SPUTargetMachine.h                   =
                        |     20 +-
 head/contrib/llvm/lib/Target/CppBackend/CPPBackend.cpp                    =
                        |    124 +-
 head/contrib/llvm/lib/Target/CppBackend/CPPTargetMachine.h                =
                        |      8 +-
 head/contrib/llvm/lib/Target/MBlaze/AsmParser/MBlazeAsmLexer.cpp          =
                        |     10 +-
 head/contrib/llvm/lib/Target/MBlaze/AsmParser/MBlazeAsmParser.cpp         =
                        |      3 -
 head/contrib/llvm/lib/Target/MBlaze/Disassembler/MBlazeDisassembler.cpp   =
                        |     31 +-
 head/contrib/llvm/lib/Target/MBlaze/Disassembler/MBlazeDisassembler.h     =
                        |      6 +-
 head/contrib/llvm/lib/Target/MBlaze/InstPrinter/MBlazeInstPrinter.h       =
                        |      8 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlaze.td                             =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeAsmPrinter.cpp                  =
                        |      8 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeDelaySlotFiller.cpp             =
                        |     22 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeELFWriterInfo.cpp               =
                        |     12 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeELFWriterInfo.h                 =
                        |      1 +
 head/contrib/llvm/lib/Target/MBlaze/MBlazeFrameLowering.cpp               =
                        |     39 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeFrameLowering.h                 =
                        |      3 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeISelLowering.cpp                =
                        |     24 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeISelLowering.h                  =
                        |      6 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFPU.td                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFSL.td                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFormats.td                 =
                        |     26 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.cpp                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.h                     =
                        |      4 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.td                    =
                        |    171 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsicInfo.cpp               =
                        |     16 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsicInfo.h                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsics.td                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeMCInstLower.cpp                 =
                        |     11 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeMCInstLower.h                   =
                        |      3 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeMachineFunction.h               =
                        |      5 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.cpp                =
                        |     10 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.h                  =
                        |      4 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.td                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeRelocations.h                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule.td                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule3.td                    =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule5.td                    =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeSubtarget.cpp                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeSubtarget.h                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeTargetMachine.cpp               =
                        |     51 +-
 head/contrib/llvm/lib/Target/MBlaze/MBlazeTargetMachine.h                 =
                        |      9 +-
 head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeAsmBackend.cpp     =
                        |     53 +-
 head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeBaseInfo.h         =
                        |      5 +-
 head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.cpp      =
                        |      2 +
 head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.h        =
                        |      4 +-
 head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCCodeEmitter.cpp  =
                        |     19 +-
 head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.cpp   =
                        |     13 +-
 head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.h     =
                        |      8 +-
 head/contrib/llvm/lib/Target/MSP430/InstPrinter/MSP430InstPrinter.cpp     =
                        |      1 -
 head/contrib/llvm/lib/Target/MSP430/InstPrinter/MSP430InstPrinter.h       =
                        |      7 +-
 head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp      =
                        |      3 +
 head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h        =
                        |      8 +-
 head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.cpp   =
                        |     11 +-
 head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h     =
                        |      2 -
 head/contrib/llvm/lib/Target/MSP430/MSP430.td                             =
                        |      2 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430AsmPrinter.cpp                  =
                        |      2 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430BranchSelector.cpp              =
                        |      2 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp               =
                        |      6 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp                =
                        |     40 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.h                  =
                        |      6 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430InstrFormats.td                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.cpp                   =
                        |     32 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.h                     =
                        |      4 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.td                    =
                        |      2 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430MCInstLower.cpp                 =
                        |     11 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430MCInstLower.h                   =
                        |      3 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430MachineFunctionInfo.h           =
                        |      2 +
 head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp                =
                        |     14 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.h                  =
                        |     11 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.td                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430Subtarget.cpp                   =
                        |      4 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430Subtarget.h                     =
                        |      6 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430TargetMachine.cpp               =
                        |     35 +-
 head/contrib/llvm/lib/Target/MSP430/MSP430TargetMachine.h                 =
                        |     10 +-
 head/contrib/llvm/lib/Target/Mangler.cpp                                  =
                        |     11 +-
 head/contrib/llvm/lib/Target/Mips/InstPrinter/MipsInstPrinter.cpp         =
                        |     70 +-
 head/contrib/llvm/lib/Target/Mips/InstPrinter/MipsInstPrinter.h           =
                        |     16 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp         =
                        |    264 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h             =
                        |    126 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h           =
                        |    122 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp          =
                        |      7 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h            =
                        |      5 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp      =
                        |    256 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp       =
                        |     45 +-
 head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h         =
                        |     25 +-
 head/contrib/llvm/lib/Target/Mips/Mips.h                                  =
                        |      2 -
 head/contrib/llvm/lib/Target/Mips/Mips.td                                 =
                        |     10 +-
 head/contrib/llvm/lib/Target/Mips/Mips64InstrInfo.td                      =
                        |    241 +-
 head/contrib/llvm/lib/Target/Mips/MipsAsmPrinter.cpp                      =
                        |    230 +-
 head/contrib/llvm/lib/Target/Mips/MipsAsmPrinter.h                        =
                        |     20 +-
 head/contrib/llvm/lib/Target/Mips/MipsCallingConv.td                      =
                        |     56 +-
 head/contrib/llvm/lib/Target/Mips/MipsCodeEmitter.cpp                     =
                        |    223 +-
 head/contrib/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp                 =
                        |     33 +-
 head/contrib/llvm/lib/Target/Mips/MipsEmitGPRestore.cpp                   =
                        |     13 +-
 head/contrib/llvm/lib/Target/Mips/MipsExpandPseudo.cpp                    =
                        |     20 +-
 head/contrib/llvm/lib/Target/Mips/MipsFrameLowering.cpp                   =
                        |    200 +-
 head/contrib/llvm/lib/Target/Mips/MipsFrameLowering.h                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp                    =
                        |    474 +-
 head/contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp                    =
                        |   1323 +-
 head/contrib/llvm/lib/Target/Mips/MipsISelLowering.h                      =
                        |     25 +-
 head/contrib/llvm/lib/Target/Mips/MipsInstrFPU.td                         =
                        |    268 +-
 head/contrib/llvm/lib/Target/Mips/MipsInstrFormats.td                     =
                        |     41 +-
 head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.cpp                       =
                        |    107 +-
 head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.h                         =
                        |     91 +-
 head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.td                        =
                        |    652 +-
 head/contrib/llvm/lib/Target/Mips/MipsJITInfo.cpp                         =
                        |     17 +-
 head/contrib/llvm/lib/Target/Mips/MipsJITInfo.h                           =
                        |      4 +-
 head/contrib/llvm/lib/Target/Mips/MipsMCInstLower.cpp                     =
                        |    325 +-
 head/contrib/llvm/lib/Target/Mips/MipsMCInstLower.h                       =
                        |     20 +-
 head/contrib/llvm/lib/Target/Mips/MipsMachineFunction.h                   =
                        |     26 +-
 head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.cpp                    =
                        |    256 +-
 head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.h                      =
                        |      7 +-
 head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.td                     =
                        |    136 +-
 head/contrib/llvm/lib/Target/Mips/MipsRelocations.h                       =
                        |     10 +-
 head/contrib/llvm/lib/Target/Mips/MipsSchedule.td                         =
                        |      2 +-
 head/contrib/llvm/lib/Target/Mips/MipsSubtarget.cpp                       =
                        |     22 +-
 head/contrib/llvm/lib/Target/Mips/MipsSubtarget.h                         =
                        |      8 +-
 head/contrib/llvm/lib/Target/Mips/MipsTargetMachine.cpp                   =
                        |    120 +-
 head/contrib/llvm/lib/Target/Mips/MipsTargetMachine.h                     =
                        |     42 +-
 head/contrib/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp                =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/InstPrinter/PTXInstPrinter.cpp           =
                        |     77 +-
 head/contrib/llvm/lib/Target/PTX/InstPrinter/PTXInstPrinter.h             =
                        |      8 +-
 head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXBaseInfo.h               =
                        |     71 +
 head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCAsmInfo.cpp            =
                        |      2 +
 head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCAsmInfo.h              =
                        |      6 +-
 head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCTargetDesc.cpp         =
                        |     11 +-
 head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCTargetDesc.h           =
                        |      2 -
 head/contrib/llvm/lib/Target/PTX/PTX.h                                    =
                        |      1 -
 head/contrib/llvm/lib/Target/PTX/PTX.td                                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/PTXAsmPrinter.cpp                        =
                        |    348 +-
 head/contrib/llvm/lib/Target/PTX/PTXAsmPrinter.h                          =
                        |      4 +-
 head/contrib/llvm/lib/Target/PTX/PTXFPRoundingModePass.cpp                =
                        |      6 +-
 head/contrib/llvm/lib/Target/PTX/PTXFrameLowering.cpp                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/PTXFrameLowering.h                       =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/PTXISelLowering.cpp                      =
                        |    168 +-
 head/contrib/llvm/lib/Target/PTX/PTXISelLowering.h                        =
                        |      9 +-
 head/contrib/llvm/lib/Target/PTX/PTXInstrFormats.td                       =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.cpp                         =
                        |     25 +-
 head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.h                           =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.td                          =
                        |     46 +-
 head/contrib/llvm/lib/Target/PTX/PTXInstrLoadStore.td                     =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/PTXIntrinsicInstrInfo.td                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/PTX/PTXMCAsmStreamer.cpp                     =
                        |     30 +-
 head/contrib/llvm/lib/Target/PTX/PTXMFInfoExtract.cpp                     =
                        |     23 +-
 head/contrib/llvm/lib/Target/PTX/PTXMachineFunctionInfo.h                 =
                        |    158 +-
 head/contrib/llvm/lib/Target/PTX/PTXParamManager.cpp                      =
                        |      4 +-
 head/contrib/llvm/lib/Target/PTX/PTXParamManager.h                        =
                        |      3 +-
 head/contrib/llvm/lib/Target/PTX/PTXRegAlloc.cpp                          =
                        |      7 +-
 head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.cpp                      =
                        |     46 +-
 head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.h                        =
                        |      7 +-
 head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.td                       =
                        |      3 +-
 head/contrib/llvm/lib/Target/PTX/PTXSelectionDAGInfo.cpp                  =
                        |      5 +-
 head/contrib/llvm/lib/Target/PTX/PTXSubtarget.cpp                         =
                        |      6 +-
 head/contrib/llvm/lib/Target/PTX/PTXSubtarget.h                           =
                        |      3 +-
 head/contrib/llvm/lib/Target/PTX/PTXTargetMachine.cpp                     =
                        |    342 +-
 head/contrib/llvm/lib/Target/PTX/PTXTargetMachine.h                       =
                        |     35 +-
 head/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp       =
                        |      9 +-
 head/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.h         =
                        |     10 +-
 head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp       =
                        |     75 +-
 head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCBaseInfo.h           =
                        |      2 +-
 head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp        =
                        |      6 +-
 head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h          =
                        |     10 +-
 head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cpp    =
                        |      2 +-
 head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp     =
                        |     12 +-
 head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h       =
                        |     10 +-
 head/contrib/llvm/lib/Target/PowerPC/PPC.h                                =
                        |      5 +-
 head/contrib/llvm/lib/Target/PowerPC/PPC.td                               =
                        |     16 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp                    =
                        |     52 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCBranchSelector.cpp                =
                        |      2 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCCallingConv.td                    =
                        |     35 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCCodeEmitter.cpp                   =
                        |     10 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCFrameLowering.cpp                 =
                        |     38 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCFrameLowering.h                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCHazardRecognizers.cpp             =
                        |    189 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCHazardRecognizers.h               =
                        |     28 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp                  =
                        |     12 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp                  =
                        |    256 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.h                    =
                        |     36 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCInstr64Bit.td                     =
                        |    102 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCInstrAltivec.td                   =
                        |     54 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCInstrFormats.td                   =
                        |     63 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.cpp                     =
                        |    129 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.h                       =
                        |     13 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.td                      =
                        |     97 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCJITInfo.cpp                       =
                        |      8 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCJITInfo.h                         =
                        |      2 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCMCInstLower.cpp                   =
                        |      4 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCMachineFunctionInfo.h             =
                        |      3 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCPerfectShuffle.h                  =
                        |      2 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp                  =
                        |    288 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.h                    =
                        |     10 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.td                   =
                        |      6 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCRelocations.h                     =
                        |      6 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCSchedule.td                       =
                        |     71 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG3.td                     =
                        |      9 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG4.td                     =
                        |      9 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG4Plus.td                 =
                        |      9 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG5.td                     =
                        |      9 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCSubtarget.cpp                     =
                        |     24 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCSubtarget.h                       =
                        |     12 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp                 =
                        |     75 +-
 head/contrib/llvm/lib/Target/PowerPC/PPCTargetMachine.h                   =
                        |     33 +-
 head/contrib/llvm/lib/Target/Sparc/DelaySlotFiller.cpp                    =
                        |     18 +-
 head/contrib/llvm/lib/Target/Sparc/FPMover.cpp                            =
                        |      8 +-
 head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp        =
                        |      2 +
 head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h          =
                        |      8 +-
 head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp     =
                        |      8 +-
 head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h       =
                        |      2 -
 head/contrib/llvm/lib/Target/Sparc/Sparc.h                                =
                        |      5 +-
 head/contrib/llvm/lib/Target/Sparc/Sparc.td                               =
                        |      6 +-
 head/contrib/llvm/lib/Target/Sparc/SparcAsmPrinter.cpp                    =
                        |     22 +-
 head/contrib/llvm/lib/Target/Sparc/SparcCallingConv.td                    =
                        |      6 +-
 head/contrib/llvm/lib/Target/Sparc/SparcFrameLowering.cpp                 =
                        |      2 +-
 head/contrib/llvm/lib/Target/Sparc/SparcFrameLowering.h                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp                  =
                        |      1 -
 head/contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp                  =
                        |     50 +-
 head/contrib/llvm/lib/Target/Sparc/SparcISelLowering.h                    =
                        |      8 +-
 head/contrib/llvm/lib/Target/Sparc/SparcInstrFormats.td                   =
                        |      6 +-
 head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.cpp                     =
                        |     19 +-
 head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.h                       =
                        |     11 +-
 head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.td                      =
                        |      6 +-
 head/contrib/llvm/lib/Target/Sparc/SparcMachineFunctionInfo.h             =
                        |      1 +
 head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.cpp                  =
                        |     12 +-
 head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.h                    =
                        |      4 +-
 head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.td                   =
                        |      7 +-
 head/contrib/llvm/lib/Target/Sparc/SparcSubtarget.cpp                     =
                        |      4 +-
 head/contrib/llvm/lib/Target/Sparc/SparcSubtarget.h                       =
                        |      3 +-
 head/contrib/llvm/lib/Target/Sparc/SparcTargetMachine.cpp                 =
                        |     65 +-
 head/contrib/llvm/lib/Target/Sparc/SparcTargetMachine.h                   =
                        |     18 +-
 head/contrib/llvm/lib/Target/TargetData.cpp                               =
                        |    123 +-
 head/contrib/llvm/lib/Target/TargetInstrInfo.cpp                          =
                        |     42 -
 head/contrib/llvm/lib/Target/TargetLibraryInfo.cpp                        =
                        |    112 +
 head/contrib/llvm/lib/Target/TargetLoweringObjectFile.cpp                 =
                        |     38 +-
 head/contrib/llvm/lib/Target/TargetMachine.cpp                            =
                        |    228 +-
 head/contrib/llvm/lib/Target/TargetRegisterInfo.cpp                       =
                        |      4 +-
 head/contrib/llvm/lib/Target/X86/AsmParser/X86AsmLexer.cpp                =
                        |      7 +-
 head/contrib/llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp               =
                        |    730 +-
 head/contrib/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp         =
                        |    239 +-
 head/contrib/llvm/lib/Target/X86/Disassembler/X86Disassembler.h           =
                        |     46 +-
 head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.c    =
                        |     80 +-
 head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.h    =
                        |     15 +-
 head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoderCommon=
.h                      |     23 +-
 head/contrib/llvm/lib/Target/X86/InstPrinter/X86ATTInstPrinter.cpp        =
                        |     78 +-
 head/contrib/llvm/lib/Target/X86/InstPrinter/X86ATTInstPrinter.h          =
                        |     10 +-
 head/contrib/llvm/lib/Target/X86/InstPrinter/X86InstComments.cpp          =
                        |    329 +-
 head/contrib/llvm/lib/Target/X86/InstPrinter/X86InstComments.h            =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/InstPrinter/X86IntelInstPrinter.cpp      =
                        |     72 +-
 head/contrib/llvm/lib/Target/X86/InstPrinter/X86IntelInstPrinter.h        =
                        |      9 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp           =
                        |     80 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h               =
                        |    111 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86FixupKinds.h             =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp            =
                        |     25 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h              =
                        |     22 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp        =
                        |    389 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp         =
                        |    105 +-
 head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h           =
                        |     11 +
 head/contrib/llvm/lib/Target/X86/Utils/X86ShuffleDecode.cpp               =
                        |    193 +-
 head/contrib/llvm/lib/Target/X86/Utils/X86ShuffleDecode.h                 =
                        |     84 +-
 head/contrib/llvm/lib/Target/X86/X86.h                                    =
                        |      2 -
 head/contrib/llvm/lib/Target/X86/X86.td                                   =
                        |    114 +-
 head/contrib/llvm/lib/Target/X86/X86AsmPrinter.cpp                        =
                        |     48 +-
 head/contrib/llvm/lib/Target/X86/X86AsmPrinter.h                          =
                        |      5 -
 head/contrib/llvm/lib/Target/X86/X86COFFMachineModuleInfo.cpp             =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/X86COFFMachineModuleInfo.h               =
                        |      4 +-
 head/contrib/llvm/lib/Target/X86/X86CallingConv.td                        =
                        |     58 +-
 head/contrib/llvm/lib/Target/X86/X86CodeEmitter.cpp                       =
                        |     18 +-
 head/contrib/llvm/lib/Target/X86/X86ELFWriterInfo.cpp                     =
                        |      8 +-
 head/contrib/llvm/lib/Target/X86/X86FastISel.cpp                          =
                        |     75 +-
 head/contrib/llvm/lib/Target/X86/X86FloatingPoint.cpp                     =
                        |     33 +-
 head/contrib/llvm/lib/Target/X86/X86FrameLowering.cpp                     =
                        |    384 +-
 head/contrib/llvm/lib/Target/X86/X86FrameLowering.h                       =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp                      =
                        |    548 +-
 head/contrib/llvm/lib/Target/X86/X86ISelLowering.cpp                      =
                        |   5585 +-
 head/contrib/llvm/lib/Target/X86/X86ISelLowering.h                        =
                        |    202 +-
 head/contrib/llvm/lib/Target/X86/X86Instr3DNow.td                         =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/X86InstrArithmetic.td                    =
                        |    319 +-
 head/contrib/llvm/lib/Target/X86/X86InstrBuilder.h                        =
                        |      1 -
 head/contrib/llvm/lib/Target/X86/X86InstrCMovSetCC.td                     =
                        |     28 +-
 head/contrib/llvm/lib/Target/X86/X86InstrCompiler.td                      =
                        |    288 +-
 head/contrib/llvm/lib/Target/X86/X86InstrControl.td                       =
                        |    196 +-
 head/contrib/llvm/lib/Target/X86/X86InstrExtension.td                     =
                        |     84 +-
 head/contrib/llvm/lib/Target/X86/X86InstrFMA.td                           =
                        |    204 +-
 head/contrib/llvm/lib/Target/X86/X86InstrFPStack.td                       =
                        |     63 +-
 head/contrib/llvm/lib/Target/X86/X86InstrFormats.td                       =
                        |    340 +-
 head/contrib/llvm/lib/Target/X86/X86InstrFragmentsSIMD.td                 =
                        |    215 +-
 head/contrib/llvm/lib/Target/X86/X86InstrInfo.cpp                         =
                        |    441 +-
 head/contrib/llvm/lib/Target/X86/X86InstrInfo.h                           =
                        |      9 +-
 head/contrib/llvm/lib/Target/X86/X86InstrInfo.td                          =
                        |    221 +-
 head/contrib/llvm/lib/Target/X86/X86InstrMMX.td                           =
                        |     30 +-
 head/contrib/llvm/lib/Target/X86/X86InstrSSE.td                           =
                        |   6215 +-
 head/contrib/llvm/lib/Target/X86/X86InstrShiftRotate.td                   =
                        |    548 +-
 head/contrib/llvm/lib/Target/X86/X86InstrSystem.td                        =
                        |     72 +-
 head/contrib/llvm/lib/Target/X86/X86InstrVMX.td                           =
                        |     38 +-
 head/contrib/llvm/lib/Target/X86/X86JITInfo.cpp                           =
                        |      8 +-
 head/contrib/llvm/lib/Target/X86/X86JITInfo.h                             =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/X86MCInstLower.cpp                       =
                        |     45 +-
 head/contrib/llvm/lib/Target/X86/X86MCInstLower.h                         =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/X86MachineFunctionInfo.h                 =
                        |      8 +-
 head/contrib/llvm/lib/Target/X86/X86RegisterInfo.cpp                      =
                        |    218 +-
 head/contrib/llvm/lib/Target/X86/X86RegisterInfo.h                        =
                        |      5 +-
 head/contrib/llvm/lib/Target/X86/X86RegisterInfo.td                       =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/X86Relocations.h                         =
                        |      2 +-
 head/contrib/llvm/lib/Target/X86/X86SelectionDAGInfo.cpp                  =
                        |      3 +-
 head/contrib/llvm/lib/Target/X86/X86Subtarget.cpp                         =
                        |    131 +-
 head/contrib/llvm/lib/Target/X86/X86Subtarget.h                           =
                        |     82 +-
 head/contrib/llvm/lib/Target/X86/X86TargetMachine.cpp                     =
                        |     77 +-
 head/contrib/llvm/lib/Target/X86/X86TargetMachine.h                       =
                        |     44 +-
 head/contrib/llvm/lib/Target/X86/X86TargetObjectFile.cpp                  =
                        |      3 +-
 head/contrib/llvm/lib/Target/X86/X86TargetObjectFile.h                    =
                        |      3 +-
 head/contrib/llvm/lib/Target/X86/X86VZeroUpper.cpp                        =
                        |    234 +-
 head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp        =
                        |      3 +
 head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h          =
                        |      5 +-
 head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp     =
                        |      8 +-
 head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h       =
                        |      2 -
 head/contrib/llvm/lib/Target/XCore/XCore.h                                =
                        |      3 +-
 head/contrib/llvm/lib/Target/XCore/XCore.td                               =
                        |      3 +-
 head/contrib/llvm/lib/Target/XCore/XCoreFrameLowering.cpp                 =
                        |     11 +-
 head/contrib/llvm/lib/Target/XCore/XCoreFrameLowering.h                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/XCore/XCoreISelDAGToDAG.cpp                  =
                        |     13 +-
 head/contrib/llvm/lib/Target/XCore/XCoreISelLowering.cpp                  =
                        |     69 +-
 head/contrib/llvm/lib/Target/XCore/XCoreISelLowering.h                    =
                        |      8 +-
 head/contrib/llvm/lib/Target/XCore/XCoreInstrFormats.td                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.cpp                     =
                        |      4 +-
 head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.h                       =
                        |      4 +-
 head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.td                      =
                        |      2 +-
 head/contrib/llvm/lib/Target/XCore/XCoreMachineFunctionInfo.h             =
                        |      4 +-
 head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.cpp                  =
                        |     24 +-
 head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.h                    =
                        |     13 +-
 head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.td                   =
                        |      2 +-
 head/contrib/llvm/lib/Target/XCore/XCoreSubtarget.cpp                     =
                        |      4 +-
 head/contrib/llvm/lib/Target/XCore/XCoreSubtarget.h                       =
                        |      3 +-
 head/contrib/llvm/lib/Target/XCore/XCoreTargetMachine.cpp                 =
                        |     31 +-
 head/contrib/llvm/lib/Target/XCore/XCoreTargetMachine.h                   =
                        |     11 +-
 head/contrib/llvm/lib/Target/XCore/XCoreTargetObjectFile.h                =
                        |      2 +-
 head/contrib/llvm/lib/Transforms/IPO/ConstantMerge.cpp                    =
                        |     14 +-
 head/contrib/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp          =
                        |      2 +-
 head/contrib/llvm/lib/Transforms/IPO/FunctionAttrs.cpp                    =
                        |    227 +-
 head/contrib/llvm/lib/Transforms/IPO/GlobalOpt.cpp                        =
                        |    717 +-
 head/contrib/llvm/lib/Transforms/IPO/InlineAlways.cpp                     =
                        |    102 +-
 head/contrib/llvm/lib/Transforms/IPO/InlineSimple.cpp                     =
                        |     58 +-
 head/contrib/llvm/lib/Transforms/IPO/Inliner.cpp                          =
                        |    149 +-
 head/contrib/llvm/lib/Transforms/IPO/Internalize.cpp                      =
                        |      7 +-
 head/contrib/llvm/lib/Transforms/IPO/PassManagerBuilder.cpp               =
                        |     27 +-
 head/contrib/llvm/lib/Transforms/IPO/PruneEH.cpp                          =
                        |      3 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombine.h                =
                        |     10 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp        =
                        |     74 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp      =
                        |    245 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp         =
                        |    160 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp         =
                        |     44 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp      =
                        |     89 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cp=
p                       |     71 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp     =
                        |     58 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp        =
                        |     39 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp        =
                        |     83 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDemanded.c=
pp                      |    101 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp     =
                        |    373 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstCombineWorklist.h        =
                        |      4 +-
 head/contrib/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp     =
                        |     85 +-
 head/contrib/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp        =
                        |    139 +-
 head/contrib/llvm/lib/Transforms/Instrumentation/Instrumentation.cpp      =
                        |      2 +
 head/contrib/llvm/lib/Transforms/Instrumentation/OptimalEdgeProfiling.cpp =
                        |      4 +-
 head/contrib/llvm/lib/Transforms/Instrumentation/PathProfiling.cpp        =
                        |     13 +-
 head/contrib/llvm/lib/Transforms/Scalar/CodeGenPrepare.cpp                =
                        |     47 +-
 head/contrib/llvm/lib/Transforms/Scalar/ConstantProp.cpp                  =
                        |     13 +-
 head/contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp    =
                        |     92 +-
 head/contrib/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp          =
                        |    287 +-
 head/contrib/llvm/lib/Transforms/Scalar/EarlyCSE.cpp                      =
                        |    146 +-
 head/contrib/llvm/lib/Transforms/Scalar/GVN.cpp                           =
                        |    331 +-
 head/contrib/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp                =
                        |    557 +-
 head/contrib/llvm/lib/Transforms/Scalar/JumpThreading.cpp                 =
                        |     35 +-
 head/contrib/llvm/lib/Transforms/Scalar/LICM.cpp                          =
                        |     17 +-
 head/contrib/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp              =
                        |      6 +-
 head/contrib/llvm/lib/Transforms/Scalar/LoopRotation.cpp                  =
                        |    166 +-
 head/contrib/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp            =
                        |    985 +-
 head/contrib/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp                =
                        |     58 +-
 head/contrib/llvm/lib/Transforms/Scalar/LoopUnswitch.cpp                  =
                        |    467 +-
 head/contrib/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp               =
                        |     36 +-
 head/contrib/llvm/lib/Transforms/Scalar/ObjCARC.cpp                       =
                        |   1334 +-
 head/contrib/llvm/lib/Transforms/Scalar/Reassociate.cpp                   =
                        |     10 +-
 head/contrib/llvm/lib/Transforms/Scalar/SCCP.cpp                          =
                        |    500 +-
 head/contrib/llvm/lib/Transforms/Scalar/Scalar.cpp                        =
                        |      1 +
 head/contrib/llvm/lib/Transforms/Scalar/ScalarReplAggregates.cpp          =
                        |     70 +-
 head/contrib/llvm/lib/Transforms/Scalar/SimplifyLibCalls.cpp              =
                        |    182 +-
 head/contrib/llvm/lib/Transforms/Scalar/Sink.cpp                          =
                        |      3 +-
 head/contrib/llvm/lib/Transforms/Utils/AddrModeMatcher.cpp                =
                        |      9 +-
 head/contrib/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp                =
                        |     16 +-
 head/contrib/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp             =
                        |      3 +-
 head/contrib/llvm/lib/Transforms/Utils/BuildLibCalls.cpp                  =
                        |     34 +-
 head/contrib/llvm/lib/Transforms/Utils/CloneFunction.cpp                  =
                        |    206 +-
 head/contrib/llvm/lib/Transforms/Utils/CodeExtractor.cpp                  =
                        |      7 +-
 head/contrib/llvm/lib/Transforms/Utils/DemoteRegToStack.cpp               =
                        |     57 +-
 head/contrib/llvm/lib/Transforms/Utils/InlineFunction.cpp                 =
                        |    607 +-
 head/contrib/llvm/lib/Transforms/Utils/Local.cpp                          =
                        |    109 +-
 head/contrib/llvm/lib/Transforms/Utils/LoopSimplify.cpp                   =
                        |     61 +-
 head/contrib/llvm/lib/Transforms/Utils/LoopUnroll.cpp                     =
                        |     40 +-
 head/contrib/llvm/lib/Transforms/Utils/LowerExpectIntrinsic.cpp           =
                        |     22 +-
 head/contrib/llvm/lib/Transforms/Utils/LowerInvoke.cpp                    =
                        |     28 +-
 head/contrib/llvm/lib/Transforms/Utils/LowerSwitch.cpp                    =
                        |     10 +-
 head/contrib/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp        =
                        |      9 +-
 head/contrib/llvm/lib/Transforms/Utils/SSAUpdater.cpp                     =
                        |      7 +
 head/contrib/llvm/lib/Transforms/Utils/SimplifyCFG.cpp                    =
                        |    619 +-
 head/contrib/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp                 =
                        |     45 +-
 head/contrib/llvm/lib/Transforms/Utils/SimplifyInstructions.cpp           =
                        |     12 +-
 head/contrib/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp         =
                        |     20 -
 head/contrib/llvm/lib/VMCore/AsmWriter.cpp                                =
                        |    133 +-
 head/contrib/llvm/lib/VMCore/Attributes.cpp                               =
                        |      8 +-
 head/contrib/llvm/lib/VMCore/AutoUpgrade.cpp                              =
                        |    594 +-
 head/contrib/llvm/lib/VMCore/BasicBlock.cpp                               =
                        |      3 +
 head/contrib/llvm/lib/VMCore/ConstantFold.cpp                             =
                        |    544 +-
 head/contrib/llvm/lib/VMCore/Constants.cpp                                =
                        |   1225 +-
 head/contrib/llvm/lib/VMCore/ConstantsContext.h                           =
                        |    234 +-
 head/contrib/llvm/lib/VMCore/Core.cpp                                     =
                        |     73 +-
 head/contrib/llvm/lib/VMCore/DebugLoc.cpp                                 =
                        |      5 +-
 head/contrib/llvm/lib/VMCore/Dominators.cpp                               =
                        |    202 +-
 head/contrib/llvm/lib/VMCore/Function.cpp                                 =
                        |     52 +-
 head/contrib/llvm/lib/VMCore/GCOV.cpp                                     =
                        |      2 +-
 head/contrib/llvm/lib/VMCore/IRBuilder.cpp                                =
                        |      4 +-
 head/contrib/llvm/lib/VMCore/Instruction.cpp                              =
                        |     56 -
 head/contrib/llvm/lib/VMCore/Instructions.cpp                             =
                        |    263 +-
 head/contrib/llvm/lib/VMCore/LLVMContext.cpp                              =
                        |     18 +-
 head/contrib/llvm/lib/VMCore/LLVMContextImpl.cpp                          =
                        |     51 +-
 head/contrib/llvm/lib/VMCore/LLVMContextImpl.h                            =
                        |    162 +-
 head/contrib/llvm/lib/VMCore/Metadata.cpp                                 =
                        |     89 +-
 head/contrib/llvm/lib/VMCore/Module.cpp                                   =
                        |     56 +
 head/contrib/llvm/lib/VMCore/Pass.cpp                                     =
                        |     24 +-
 head/contrib/llvm/lib/VMCore/PassManager.cpp                              =
                        |    161 +-
 head/contrib/llvm/lib/VMCore/Type.cpp                                     =
                        |    185 +-
 head/contrib/llvm/lib/VMCore/Use.cpp                                      =
                        |      1 +
 head/contrib/llvm/lib/VMCore/User.cpp                                     =
                        |      2 +
 head/contrib/llvm/lib/VMCore/Value.cpp                                    =
                        |    127 +-
 head/contrib/llvm/lib/VMCore/ValueTypes.cpp                               =
                        |     12 +-
 head/contrib/llvm/lib/VMCore/Verifier.cpp                                 =
                        |    284 +-
 head/contrib/llvm/tools/bugpoint/BugDriver.cpp                            =
                        |      4 +-
 head/contrib/llvm/tools/bugpoint/CrashDebugger.cpp                        =
                        |     11 +-
 head/contrib/llvm/tools/bugpoint/ExecutionDriver.cpp                      =
                        |     50 +-
 head/contrib/llvm/tools/bugpoint/ExtractFunction.cpp                      =
                        |     62 +-
 head/contrib/llvm/tools/bugpoint/Miscompilation.cpp                       =
                        |      3 +-
 head/contrib/llvm/tools/bugpoint/OptimizerDriver.cpp                      =
                        |     12 +-
 head/contrib/llvm/tools/bugpoint/ToolRunner.cpp                           =
                        |     93 +-
 head/contrib/llvm/tools/bugpoint/ToolRunner.h                             =
                        |      1 +
 head/contrib/llvm/tools/bugpoint/bugpoint.cpp                             =
                        |      1 +
 head/contrib/llvm/tools/clang/LICENSE.TXT                                 =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang-c/Index.h                     =
                        |    956 +-
 head/contrib/llvm/tools/clang/include/clang/ARCMigrate/ARCMT.h            =
                        |     18 +-
 head/contrib/llvm/tools/clang/include/clang/ARCMigrate/ARCMTActions.h     =
                        |     26 +
 head/contrib/llvm/tools/clang/include/clang/ARCMigrate/FileRemapper.h     =
                        |     11 +-
 head/contrib/llvm/tools/clang/include/clang/AST/APValue.h                 =
                        |    269 +-
 head/contrib/llvm/tools/clang/include/clang/AST/ASTConsumer.h             =
                        |     24 +-
 head/contrib/llvm/tools/clang/include/clang/AST/ASTContext.h              =
                        |    203 +-
 head/contrib/llvm/tools/clang/include/clang/AST/ASTDiagnostic.h           =
                        |      4 +-
 head/contrib/llvm/tools/clang/include/clang/AST/ASTImporter.h             =
                        |      6 +
 head/contrib/llvm/tools/clang/include/clang/AST/ASTMutationListener.h     =
                        |     17 +
 head/contrib/llvm/tools/clang/include/clang/AST/Attr.h                    =
                        |     18 +-
 head/contrib/llvm/tools/clang/include/clang/AST/CanonicalType.h           =
                        |      9 +
 head/contrib/llvm/tools/clang/include/clang/AST/Decl.h                    =
                        |    868 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DeclBase.h                =
                        |    354 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h                 =
                        |    676 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DeclFriend.h              =
                        |      6 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DeclObjC.h                =
                        |    794 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DeclTemplate.h            =
                        |    529 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DeclVisitor.h             =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DeclarationName.h         =
                        |     14 +-
 head/contrib/llvm/tools/clang/include/clang/AST/DependentDiagnostic.h     =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/AST/Expr.h                    =
                        |   1197 +-
 head/contrib/llvm/tools/clang/include/clang/AST/ExprCXX.h                 =
                        |   1570 +-
 head/contrib/llvm/tools/clang/include/clang/AST/ExprObjC.h                =
                        |    517 +-
 head/contrib/llvm/tools/clang/include/clang/AST/ExternalASTSource.h       =
                        |     46 +
 head/contrib/llvm/tools/clang/include/clang/AST/Mangle.h                  =
                        |      4 +-
 head/contrib/llvm/tools/clang/include/clang/AST/NestedNameSpecifier.h     =
                        |    103 +-
 head/contrib/llvm/tools/clang/include/clang/AST/OperationKinds.h          =
                        |     30 +-
 head/contrib/llvm/tools/clang/include/clang/AST/PrettyPrinter.h           =
                        |      6 +-
 head/contrib/llvm/tools/clang/include/clang/AST/RecordLayout.h            =
                        |     20 +-
 head/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h     =
                        |    270 +-
 head/contrib/llvm/tools/clang/include/clang/AST/Redeclarable.h            =
                        |     32 +-
 head/contrib/llvm/tools/clang/include/clang/AST/Stmt.h                    =
                        |    223 +-
 head/contrib/llvm/tools/clang/include/clang/AST/StmtCXX.h                 =
                        |     96 +-
 head/contrib/llvm/tools/clang/include/clang/AST/StmtIterator.h            =
                        |     10 +-
 head/contrib/llvm/tools/clang/include/clang/AST/StmtObjC.h                =
                        |     15 +-
 head/contrib/llvm/tools/clang/include/clang/AST/StmtVisitor.h             =
                        |      2 -
 head/contrib/llvm/tools/clang/include/clang/AST/TemplateBase.h            =
                        |     45 +-
 head/contrib/llvm/tools/clang/include/clang/AST/Type.h                    =
                        |    714 +-
 head/contrib/llvm/tools/clang/include/clang/AST/TypeLoc.h                 =
                        |    142 +-
 head/contrib/llvm/tools/clang/include/clang/AST/TypeVisitor.h             =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/AST/VTableBuilder.h           =
                        |     82 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/FormatString=
.h                      |    143 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/LiveVariable=
s.h                     |     10 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/ReachableCod=
e.h                     |      5 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafety=
.h                      |     14 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/Uninitialize=
dValues.h               |     12 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/AnalysisContext.h    =
                        |    207 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/AnalysisDiagnostic.h =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/CFG.h                =
                        |    188 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/DomainSpecific/CocoaC=
onventions.h            |     12 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/ProgramPoint.h       =
                        |    113 +-
 head/contrib/llvm/tools/clang/include/clang/Analysis/Visitors/CFGRecStmtDe=
clVisitor.h             |      3 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/Attr.td                 =
                        |     42 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/Builtins.def            =
                        |    109 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsX86.def         =
                        |    271 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/ConvertUTF.h            =
                        |     14 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DeclNodes.td            =
                        |      4 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/Diagnostic.h            =
                        |    276 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/Diagnostic.td           =
                        |      9 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticASTKinds.td   =
                        |     98 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticAnalysisKinds.=
td                      |      3 -
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticCommonKinds.td=
                        |     13 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticDriverKinds.td=
                        |     24 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticFrontendKinds.=
td                      |     93 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td     =
                        |    127 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticIDs.h         =
                        |     65 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticLexKinds.td   =
                        |    175 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticParseKinds.td =
                        |    246 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds.td  =
                        |   1274 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/ExpressionTraits.h      =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/FileManager.h           =
                        |     17 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/FileSystemStatCache.h   =
                        |      4 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/IdentifierTable.h       =
                        |     79 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/LLVM.h                  =
                        |     22 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.def         =
                        |     20 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.h           =
                        |     38 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/Linkage.h               =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/OnDiskHashTable.h       =
                        |     10 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/PartialDiagnostic.h     =
                        |    137 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/SourceLocation.h        =
                        |      4 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h         =
                        |    206 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/Specifiers.h            =
                        |     10 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/StmtNodes.td            =
                        |     11 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/TargetBuiltins.h        =
                        |     49 +
 head/contrib/llvm/tools/clang/include/clang/Basic/TargetInfo.h            =
                        |     47 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/TokenKinds.def          =
                        |     29 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/TypeTraits.h            =
                        |     10 +-
 head/contrib/llvm/tools/clang/include/clang/Basic/Version.h               =
                        |     24 +-
 head/contrib/llvm/tools/clang/include/clang/CodeGen/CodeGenAction.h       =
                        |     14 +-
 head/contrib/llvm/tools/clang/include/clang/CodeGen/ModuleBuilder.h       =
                        |      1 +
 head/contrib/llvm/tools/clang/include/clang/Driver/Action.h               =
                        |     24 +
 head/contrib/llvm/tools/clang/include/clang/Driver/ArgList.h              =
                        |     12 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/CC1AsOptions.td        =
                        |      9 +
 head/contrib/llvm/tools/clang/include/clang/Driver/CC1Options.td          =
                        |    131 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/Compilation.h          =
                        |     15 +
 head/contrib/llvm/tools/clang/include/clang/Driver/Driver.h               =
                        |     34 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/DriverDiagnostic.h     =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/Job.h                  =
                        |      2 +
 head/contrib/llvm/tools/clang/include/clang/Driver/ObjCRuntime.h          =
                        |      5 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/OptTable.h             =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/Options.td             =
                        |    157 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/Tool.h                 =
                        |      1 +
 head/contrib/llvm/tools/clang/include/clang/Driver/ToolChain.h            =
                        |     37 +-
 head/contrib/llvm/tools/clang/include/clang/Driver/Types.def              =
                        |      2 +
 head/contrib/llvm/tools/clang/include/clang/Frontend/ASTUnit.h            =
                        |    185 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/Analyses.def         =
                        |     17 +
 head/contrib/llvm/tools/clang/include/clang/Frontend/AnalyzerOptions.h    =
                        |     29 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/ChainedDiagnosticCons=
umer.h                  |     10 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.h     =
                        |     26 +
 head/contrib/llvm/tools/clang/include/clang/Frontend/CompilerInstance.h   =
                        |     78 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/CompilerInvocation.h =
                        |     47 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/DependencyOutputOptio=
ns.h                    |      5 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/DiagnosticOptions.h  =
                        |     10 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendAction.h     =
                        |     57 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendActions.h    =
                        |     50 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendDiagnostic.h =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendOptions.h    =
                        |     63 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/LangStandard.h       =
                        |      6 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/LangStandards.def    =
                        |     23 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/MultiplexConsumer.h  =
                        |     13 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/PreprocessorOptions.h=
                        |     20 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/TextDiagnosticPrinter=
.h                      |     36 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/Utils.h              =
                        |     23 +-
 head/contrib/llvm/tools/clang/include/clang/Frontend/VerifyDiagnosticConsu=
mer.h                   |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Index/ASTLocation.h           =
                        |     17 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/DirectoryLookup.h         =
                        |     21 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/ExternalPreprocessorSource=
.h                      |      3 +
 head/contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h            =
                        |    229 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/LexDiagnostic.h           =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/Lexer.h                   =
                        |     75 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/LiteralSupport.h          =
                        |     54 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/MacroInfo.h               =
                        |     25 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/ModuleLoader.h            =
                        |     32 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/PPCallbacks.h             =
                        |     89 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/PreprocessingRecord.h     =
                        |    111 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h            =
                        |    210 +-
 head/contrib/llvm/tools/clang/include/clang/Lex/PreprocessorLexer.h       =
                        |      1 +
 head/contrib/llvm/tools/clang/include/clang/Lex/Token.h                   =
                        |      6 +-
 head/contrib/llvm/tools/clang/include/clang/Parse/ParseAST.h              =
                        |      6 +-
 head/contrib/llvm/tools/clang/include/clang/Parse/ParseDiagnostic.h       =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Parse/Parser.h                =
                        |    585 +-
 head/contrib/llvm/tools/clang/include/clang/Rewrite/ASTConsumers.h        =
                        |      5 +
 head/contrib/llvm/tools/clang/include/clang/Rewrite/FixItRewriter.h       =
                        |     28 +-
 head/contrib/llvm/tools/clang/include/clang/Rewrite/FrontendActions.h     =
                        |     15 +-
 head/contrib/llvm/tools/clang/include/clang/Rewrite/TokenRewriter.h       =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/AttributeList.h          =
                        |    149 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/CodeCompleteConsumer.h   =
                        |    469 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/DeclSpec.h               =
                        |    153 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/DelayedDiagnostic.h      =
                        |     10 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/ExternalSemaSource.h     =
                        |      5 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/IdentifierResolver.h     =
                        |     33 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/Initialization.h         =
                        |    252 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/LocInfoType.h            =
                        |     12 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/Lookup.h                 =
                        |     55 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/Overload.h               =
                        |    145 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/ParsedTemplate.h         =
                        |      6 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/PrettyDeclStackTrace.h   =
                        |      5 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/Scope.h                  =
                        |     35 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/ScopeInfo.h              =
                        |    274 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/Sema.h                   =
                        |   1693 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/SemaConsumer.h           =
                        |      1 +
 head/contrib/llvm/tools/clang/include/clang/Sema/SemaDiagnostic.h         =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/SemaFixItUtils.h         =
                        |      2 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/Template.h               =
                        |     64 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/TemplateDeduction.h      =
                        |     21 +-
 head/contrib/llvm/tools/clang/include/clang/Sema/TypoCorrection.h         =
                        |    148 +-
 head/contrib/llvm/tools/clang/include/clang/Serialization/ASTBitCodes.h   =
                        |    215 +-
 head/contrib/llvm/tools/clang/include/clang/Serialization/ASTDeserializati=
onListener.h            |      6 +
 head/contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h     =
                        |    542 +-
 head/contrib/llvm/tools/clang/include/clang/Serialization/ASTWriter.h     =
                        |    235 +-
 head/contrib/llvm/tools/clang/include/clang/Serialization/ContinuousRangeM=
ap.h                    |     10 +
 head/contrib/llvm/tools/clang/include/clang/Serialization/Module.h        =
                        |    229 +-
 head/contrib/llvm/tools/clang/include/clang/Serialization/ModuleManager.h =
                        |     30 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugReporte=
r/BugReporter.h         |    199 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugReporte=
r/BugReporterVisitor.h  |     80 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugReporte=
r/BugType.h             |      1 +
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugReporte=
r/PathDiagnostic.h      |    394 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Checker.h =
                        |     44 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerMan=
ager.h                  |     83 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/CheckerReg=
istry.h                 |      4 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathDiagno=
sticConsumers.h         |      4 +
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/AnalysisManager.h   |     95 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/BasicValueFactory.h |      7 -
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/CheckerContext.h    |    228 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/ConstraintManager.h |     27 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/CoreEngine.h        |    563 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/Environment.h       |     66 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/ExplodedGraph.h     |     84 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/ExprEngine.h        |    210 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/MemRegion.h         |    204 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/ObjCMessage.h       |    246 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/ProgramState.h      |    260 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/ProgramStateTrait.h |     19 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/SValBuilder.h       |    102 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/SVals.h             |     63 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/Store.h             |     63 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/SubEngine.h         |     51 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/SymbolManager.h     |    173 +-
 head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathSensit=
ive/WorkList.h          |      1 +
 head/contrib/llvm/tools/clang/lib/ARCMigrate/ARCMT.cpp                    =
                        |    165 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/ARCMTActions.cpp             =
                        |     17 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/FileRemapper.cpp             =
                        |     44 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/Internals.h                  =
                        |     19 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransARCAssign.cpp           =
                        |      3 +
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransAutoreleasePool.cpp     =
                        |      4 -
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransBlockObjCVariable.cpp   =
                        |     66 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransEmptyStatementsAndDeallo=
c.cpp                   |     43 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransProperties.cpp          =
                        |    328 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransRetainReleaseDealloc.cpp=
                        |    112 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp      =
                        |     30 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransUnusedInitDelegate.cpp  =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransZeroOutPropsInDealloc.cp=
p                       |     75 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/TransformActions.cpp         =
                        |     33 +
 head/contrib/llvm/tools/clang/lib/ARCMigrate/Transforms.cpp               =
                        |    346 +-
 head/contrib/llvm/tools/clang/lib/ARCMigrate/Transforms.h                 =
                        |    118 +-
 head/contrib/llvm/tools/clang/lib/AST/APValue.cpp                         =
                        |    569 +-
 head/contrib/llvm/tools/clang/lib/AST/ASTConsumer.cpp                     =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp                      =
                        |    522 +-
 head/contrib/llvm/tools/clang/lib/AST/ASTDiagnostic.cpp                   =
                        |     26 +-
 head/contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp                     =
                        |    779 +-
 head/contrib/llvm/tools/clang/lib/AST/AttrImpl.cpp                        =
                        |      4 +
 head/contrib/llvm/tools/clang/lib/AST/CXXInheritance.cpp                  =
                        |     15 +-
 head/contrib/llvm/tools/clang/lib/AST/Decl.cpp                            =
                        |    931 +-
 head/contrib/llvm/tools/clang/lib/AST/DeclBase.cpp                        =
                        |    416 +-
 head/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp                         =
                        |    467 +-
 head/contrib/llvm/tools/clang/lib/AST/DeclFriend.cpp                      =
                        |      7 +-
 head/contrib/llvm/tools/clang/lib/AST/DeclObjC.cpp                        =
                        |    438 +-
 head/contrib/llvm/tools/clang/lib/AST/DeclPrinter.cpp                     =
                        |     91 +-
 head/contrib/llvm/tools/clang/lib/AST/DeclTemplate.cpp                    =
                        |    198 +-
 head/contrib/llvm/tools/clang/lib/AST/DeclarationName.cpp                 =
                        |     16 +-
 head/contrib/llvm/tools/clang/lib/AST/DumpXML.cpp                         =
                        |     50 +-
 head/contrib/llvm/tools/clang/lib/AST/Expr.cpp                            =
                        |   1009 +-
 head/contrib/llvm/tools/clang/lib/AST/ExprCXX.cpp                         =
                        |    538 +-
 head/contrib/llvm/tools/clang/lib/AST/ExprClassification.cpp              =
                        |     90 +-
 head/contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp                    =
                        |   5953 +-
 head/contrib/llvm/tools/clang/lib/AST/ItaniumMangle.cpp                   =
                        |    391 +-
 head/contrib/llvm/tools/clang/lib/AST/Mangle.cpp                          =
                        |     12 +-
 head/contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp                 =
                        |     33 +-
 head/contrib/llvm/tools/clang/lib/AST/NestedNameSpecifier.cpp             =
                        |     28 +-
 head/contrib/llvm/tools/clang/lib/AST/ParentMap.cpp                       =
                        |      4 +
 head/contrib/llvm/tools/clang/lib/AST/RecordLayout.cpp                    =
                        |      4 +-
 head/contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp             =
                        |    760 +-
 head/contrib/llvm/tools/clang/lib/AST/Stmt.cpp                            =
                        |    102 +-
 head/contrib/llvm/tools/clang/lib/AST/StmtDumper.cpp                      =
                        |     69 +-
 head/contrib/llvm/tools/clang/lib/AST/StmtPrinter.cpp                     =
                        |    412 +-
 head/contrib/llvm/tools/clang/lib/AST/StmtProfile.cpp                     =
                        |     99 +-
 head/contrib/llvm/tools/clang/lib/AST/TemplateBase.cpp                    =
                        |    114 +-
 head/contrib/llvm/tools/clang/lib/AST/TemplateName.cpp                    =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/AST/Type.cpp                            =
                        |    277 +-
 head/contrib/llvm/tools/clang/lib/AST/TypeLoc.cpp                         =
                        |    113 +-
 head/contrib/llvm/tools/clang/lib/AST/TypePrinter.cpp                     =
                        |    109 +-
 head/contrib/llvm/tools/clang/lib/AST/VTableBuilder.cpp                   =
                        |     17 +-
 head/contrib/llvm/tools/clang/lib/Analysis/CFG.cpp                        =
                        |    417 +-
 head/contrib/llvm/tools/clang/lib/Analysis/CocoaConventions.cpp           =
                        |     49 +-
 head/contrib/llvm/tools/clang/lib/Analysis/FormatString.cpp               =
                        |    259 +-
 head/contrib/llvm/tools/clang/lib/Analysis/FormatStringParsing.h          =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/Analysis/LiveVariables.cpp              =
                        |    171 +-
 head/contrib/llvm/tools/clang/lib/Analysis/PrintfFormatString.cpp         =
                        |    177 +-
 head/contrib/llvm/tools/clang/lib/Analysis/ProgramPoint.cpp               =
                        |      2 -
 head/contrib/llvm/tools/clang/lib/Analysis/PseudoConstantAnalysis.cpp     =
                        |     17 +-
 head/contrib/llvm/tools/clang/lib/Analysis/ReachableCode.cpp              =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/Analysis/ScanfFormatString.cpp          =
                        |    290 +-
 head/contrib/llvm/tools/clang/lib/Analysis/ThreadSafety.cpp               =
                        |   1531 +-
 head/contrib/llvm/tools/clang/lib/Analysis/UninitializedValues.cpp        =
                        |     10 +-
 head/contrib/llvm/tools/clang/lib/Basic/Builtins.cpp                      =
                        |      1 +
 head/contrib/llvm/tools/clang/lib/Basic/ConvertUTF.c                      =
                        |    143 +-
 head/contrib/llvm/tools/clang/lib/Basic/Diagnostic.cpp                    =
                        |    126 +-
 head/contrib/llvm/tools/clang/lib/Basic/DiagnosticIDs.cpp                 =
                        |    231 +-
 head/contrib/llvm/tools/clang/lib/Basic/FileManager.cpp                   =
                        |     27 +-
 head/contrib/llvm/tools/clang/lib/Basic/FileSystemStatCache.cpp           =
                        |      2 +
 head/contrib/llvm/tools/clang/lib/Basic/IdentifierTable.cpp               =
                        |     43 +-
 head/contrib/llvm/tools/clang/lib/Basic/LangOptions.cpp                   =
                        |      2 +
 head/contrib/llvm/tools/clang/lib/Basic/SourceLocation.cpp                =
                        |      4 +
 head/contrib/llvm/tools/clang/lib/Basic/SourceManager.cpp                 =
                        |    144 +-
 head/contrib/llvm/tools/clang/lib/Basic/TargetInfo.cpp                    =
                        |      5 +
 head/contrib/llvm/tools/clang/lib/Basic/Targets.cpp                       =
                        |    962 +-
 head/contrib/llvm/tools/clang/lib/Basic/Version.cpp                       =
                        |     58 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/ABIInfo.h                       =
                        |     21 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp                 =
                        |    143 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp                    =
                        |    387 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.h                      =
                        |     47 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp                   =
                        |   2692 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGCXX.cpp                       =
                        |     29 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGCXXABI.cpp                    =
                        |     43 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGCXXABI.h                      =
                        |     34 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGCall.cpp                      =
                        |    627 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGCall.h                        =
                        |    154 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGClass.cpp                     =
                        |    362 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGCleanup.cpp                   =
                        |     74 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp                 =
                        |    956 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.h                   =
                        |     42 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp                      =
                        |    243 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGDeclCXX.cpp                   =
                        |    222 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGException.cpp                 =
                        |    145 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGExpr.cpp                      =
                        |   1023 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp                   =
                        |    580 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGExprCXX.cpp                   =
                        |    296 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGExprComplex.cpp               =
                        |     66 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGExprConstant.cpp              =
                        |    923 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp                =
                        |    335 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGObjC.cpp                      =
                        |    842 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCGNU.cpp                   =
                        |    296 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp                   =
                        |    861 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp               =
                        |     74 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.h                 =
                        |     28 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGRTTI.cpp                      =
                        |     59 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp       =
                        |    185 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGStmt.cpp                      =
                        |     62 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGVTT.cpp                       =
                        |     21 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGVTables.cpp                   =
                        |     40 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CGValue.h                       =
                        |     84 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp               =
                        |    107 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.cpp             =
                        |    180 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.h               =
                        |    407 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp               =
                        |    619 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.h                 =
                        |    115 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTBAA.cpp                 =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTBAA.h                   =
                        |      4 +
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.cpp                =
                        |     44 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.h                  =
                        |     97 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp               =
                        |    328 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/MicrosoftCXXABI.cpp             =
                        |      7 +
 head/contrib/llvm/tools/clang/lib/CodeGen/ModuleBuilder.cpp               =
                        |     17 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp                  =
                        |   1074 +-
 head/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.h                    =
                        |      5 +-
 head/contrib/llvm/tools/clang/lib/Driver/Action.cpp                       =
                        |     31 +
 head/contrib/llvm/tools/clang/lib/Driver/Arg.cpp                          =
                        |      4 +-
 head/contrib/llvm/tools/clang/lib/Driver/ArgList.cpp                      =
                        |     30 +-
 head/contrib/llvm/tools/clang/lib/Driver/CC1AsOptions.cpp                 =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Driver/CC1Options.cpp                   =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp                  =
                        |      8 +-
 head/contrib/llvm/tools/clang/lib/Driver/Driver.cpp                       =
                        |    364 +-
 head/contrib/llvm/tools/clang/lib/Driver/DriverOptions.cpp                =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Driver/Job.cpp                          =
                        |      2 +
 head/contrib/llvm/tools/clang/lib/Driver/Option.cpp                       =
                        |      2 -
 head/contrib/llvm/tools/clang/lib/Driver/ToolChain.cpp                    =
                        |    187 +-
 head/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp                   =
                        |   1513 +-
 head/contrib/llvm/tools/clang/lib/Driver/ToolChains.h                     =
                        |    337 +-
 head/contrib/llvm/tools/clang/lib/Driver/Tools.cpp                        =
                        |   1696 +-
 head/contrib/llvm/tools/clang/lib/Driver/Tools.h                          =
                        |     97 +-
 head/contrib/llvm/tools/clang/lib/Driver/Types.cpp                        =
                        |      1 +
 head/contrib/llvm/tools/clang/lib/Frontend/ASTConsumers.cpp               =
                        |      3 +-
 head/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp                   =
                        |     13 +-
 head/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp                    =
                        |    746 +-
 head/contrib/llvm/tools/clang/lib/Frontend/CacheTokens.cpp                =
                        |      4 +-
 head/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp           =
                        |    819 +-
 head/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp         =
                        |    816 +-
 head/contrib/llvm/tools/clang/lib/Frontend/CreateInvocationFromCommandLine=
.cpp                    |     17 +-
 head/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp             =
                        |     64 +-
 head/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp             =
                        |    137 +-
 head/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp            =
                        |    314 +-
 head/contrib/llvm/tools/clang/lib/Frontend/HeaderIncludeGen.cpp           =
                        |      5 +-
 head/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp           =
                        |     46 +-
 head/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp           =
                        |    128 +-
 head/contrib/llvm/tools/clang/lib/Frontend/LangStandards.cpp              =
                        |      3 +-
 head/contrib/llvm/tools/clang/lib/Frontend/LogDiagnosticPrinter.cpp       =
                        |      8 +-
 head/contrib/llvm/tools/clang/lib/Frontend/MultiplexConsumer.cpp          =
                        |     50 +-
 head/contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cpp    =
                        |      8 +-
 head/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticBuffer.cpp       =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp      =
                        |   1148 +-
 head/contrib/llvm/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp   =
                        |     38 +-
 head/contrib/llvm/tools/clang/lib/Frontend/Warnings.cpp                   =
                        |    192 +-
 head/contrib/llvm/tools/clang/lib/FrontendTool/ExecuteCompilerInvocation.c=
pp                      |     43 +-
 head/contrib/llvm/tools/clang/lib/Headers/avxintrin.h                     =
                        |    319 +-
 head/contrib/llvm/tools/clang/lib/Headers/emmintrin.h                     =
                        |     56 +-
 head/contrib/llvm/tools/clang/lib/Headers/float.h                         =
                        |     11 +
 head/contrib/llvm/tools/clang/lib/Headers/immintrin.h                     =
                        |     18 +-
 head/contrib/llvm/tools/clang/lib/Headers/mm3dnow.h                       =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Headers/smmintrin.h                     =
                        |    127 +-
 head/contrib/llvm/tools/clang/lib/Headers/tgmath.h                        =
                        |     23 +-
 head/contrib/llvm/tools/clang/lib/Headers/tmmintrin.h                     =
                        |     11 +-
 head/contrib/llvm/tools/clang/lib/Headers/wmmintrin.h                     =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Headers/x86intrin.h                     =
                        |     26 +-
 head/contrib/llvm/tools/clang/lib/Headers/xmmintrin.h                     =
                        |     21 +-
 head/contrib/llvm/tools/clang/lib/Index/ASTLocation.cpp                   =
                        |     12 +-
 head/contrib/llvm/tools/clang/lib/Index/Analyzer.cpp                      =
                        |      4 +-
 head/contrib/llvm/tools/clang/lib/Lex/HeaderMap.cpp                       =
                        |      4 +-
 head/contrib/llvm/tools/clang/lib/Lex/HeaderSearch.cpp                    =
                        |    520 +-
 head/contrib/llvm/tools/clang/lib/Lex/Lexer.cpp                           =
                        |    442 +-
 head/contrib/llvm/tools/clang/lib/Lex/LiteralSupport.cpp                  =
                        |    462 +-
 head/contrib/llvm/tools/clang/lib/Lex/MacroArgs.cpp                       =
                        |      9 +-
 head/contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp                       =
                        |      5 +-
 head/contrib/llvm/tools/clang/lib/Lex/PPCaching.cpp                       =
                        |     22 +-
 head/contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp                    =
                        |    354 +-
 head/contrib/llvm/tools/clang/lib/Lex/PPExpressions.cpp                   =
                        |     22 +-
 head/contrib/llvm/tools/clang/lib/Lex/PPLexerChange.cpp                   =
                        |     88 +-
 head/contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp                =
                        |    134 +-
 head/contrib/llvm/tools/clang/lib/Lex/PTHLexer.cpp                        =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/Lex/Pragma.cpp                          =
                        |    211 +-
 head/contrib/llvm/tools/clang/lib/Lex/PreprocessingRecord.cpp             =
                        |    265 +-
 head/contrib/llvm/tools/clang/lib/Lex/Preprocessor.cpp                    =
                        |    149 +-
 head/contrib/llvm/tools/clang/lib/Lex/PreprocessorLexer.cpp               =
                        |      2 +
 head/contrib/llvm/tools/clang/lib/Lex/TokenConcatenation.cpp              =
                        |     49 +-
 head/contrib/llvm/tools/clang/lib/Lex/TokenLexer.cpp                      =
                        |     12 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseAST.cpp                      =
                        |     35 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseCXXInlineMethods.cpp         =
                        |    118 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp                     =
                        |   1566 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp                  =
                        |    695 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseExpr.cpp                     =
                        |    365 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp                  =
                        |    618 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseInit.cpp                     =
                        |    179 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseObjc.cpp                     =
                        |    526 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParsePragma.cpp                   =
                        |    118 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParsePragma.h                     =
                        |     10 +
 head/contrib/llvm/tools/clang/lib/Parse/ParseStmt.cpp                     =
                        |    252 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseTemplate.cpp                 =
                        |    182 +-
 head/contrib/llvm/tools/clang/lib/Parse/ParseTentative.cpp                =
                        |    331 +-
 head/contrib/llvm/tools/clang/lib/Parse/Parser.cpp                        =
                        |    454 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/FixItRewriter.cpp               =
                        |    115 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/FrontendActions.cpp             =
                        |     75 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/HTMLPrint.cpp                   =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/HTMLRewrite.cpp                 =
                        |     10 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/RewriteMacros.cpp               =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/RewriteObjC.cpp                 =
                        |   3231 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/RewriteTest.cpp                 =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Rewrite/Rewriter.cpp                    =
                        |      3 +-
 head/contrib/llvm/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp          =
                        |    250 +-
 head/contrib/llvm/tools/clang/lib/Sema/AttributeList.cpp                  =
                        |    133 +-
 head/contrib/llvm/tools/clang/lib/Sema/CodeCompleteConsumer.cpp           =
                        |    186 +-
 head/contrib/llvm/tools/clang/lib/Sema/DeclSpec.cpp                       =
                        |     33 +-
 head/contrib/llvm/tools/clang/lib/Sema/DelayedDiagnostic.cpp              =
                        |      6 +-
 head/contrib/llvm/tools/clang/lib/Sema/IdentifierResolver.cpp             =
                        |    162 +-
 head/contrib/llvm/tools/clang/lib/Sema/JumpDiagnostics.cpp                =
                        |    126 +-
 head/contrib/llvm/tools/clang/lib/Sema/Scope.cpp                          =
                        |     28 +-
 head/contrib/llvm/tools/clang/lib/Sema/Sema.cpp                           =
                        |    269 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaAccess.cpp                     =
                        |    326 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaAttr.cpp                       =
                        |     54 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaCXXScopeSpec.cpp               =
                        |    167 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaCast.cpp                       =
                        |    271 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp                   =
                        |   2136 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp               =
                        |   1151 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp                       =
                        |   2366 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp                   =
                        |    267 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp                    =
                        |   3299 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaDeclObjC.cpp                   =
                        |    781 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaExceptionSpec.cpp              =
                        |     21 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp                       =
                        |   3570 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp                    =
                        |   1369 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaExprMember.cpp                 =
                        |    346 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp                   =
                        |   1515 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaFixItUtils.cpp                 =
                        |     44 +
 head/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp                       =
                        |   2148 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaLookup.cpp                     =
                        |    839 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaObjCProperty.cpp               =
                        |    382 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp                   =
                        |   2125 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaStmt.cpp                       =
                        |    534 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaTemplate.cpp                   =
                        |   1273 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateDeduction.cpp          =
                        |    765 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp        =
                        |    303 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp    =
                        |    654 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateVariadic.cpp           =
                        |    117 +-
 head/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp                       =
                        |    843 +-
 head/contrib/llvm/tools/clang/lib/Sema/TargetAttributesSema.cpp           =
                        |      2 +-
 head/contrib/llvm/tools/clang/lib/Sema/TreeTransform.h                    =
                        |   1151 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ASTCommon.cpp             =
                        |      3 +
 head/contrib/llvm/tools/clang/lib/Serialization/ASTCommon.h               =
                        |      1 -
 head/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp             =
                        |   1621 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp         =
                        |   1533 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderInternals.h      =
                        |     25 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderStmt.cpp         =
                        |    377 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp             =
                        |    931 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ASTWriterDecl.cpp         =
                        |    437 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ASTWriterStmt.cpp         =
                        |    295 +-
 head/contrib/llvm/tools/clang/lib/Serialization/GeneratePCH.cpp           =
                        |     13 +-
 head/contrib/llvm/tools/clang/lib/Serialization/Module.cpp                =
                        |     18 +-
 head/contrib/llvm/tools/clang/lib/Serialization/ModuleManager.cpp         =
                        |     51 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AdjustedReturnVa=
lueChecker.cpp          |     11 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AnalyzerStatsChe=
cker.cpp                |     74 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecke=
r.cpp                   |      9 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundChecke=
rV2.cpp                 |     63 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AttrNonNullCheck=
er.cpp                  |     13 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFoundat=
ionChecks.cpp           |     70 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunctionC=
hecker.cpp              |     21 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CStringChecker.c=
pp                      |    481 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CallAndMessageCh=
ecker.cpp               |    128 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.=
cpp                     |      6 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CastToStructChec=
ker.cpp                 |      4 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCDealloc=
.cpp                    |     21 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCInstMet=
hSignature.cpp          |      4 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckSecuritySyn=
taxOnly.cpp             |    232 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckSizeofPoint=
er.cpp                  |      9 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/Checkers.td     =
                        |    148 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cp=
p                       |     22 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ClangSACheckers.=
h                       |      2 +
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DeadStoresChecke=
r.cpp                   |     56 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DebugCheckers.cp=
p                       |     70 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DereferenceCheck=
er.cpp                  |     60 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DivZeroChecker.c=
pp                      |     45 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/FixedAddressChec=
ker.cpp                 |      9 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/IdempotentOperat=
ionChecker.cpp          |     34 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/IteratorsChecker=
.cpp                    |     46 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/LLVMConventionsC=
hecker.cpp              |     15 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPI=
Checker.cpp             |    229 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MacOSXAPIChecker=
.cpp                    |     34 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cp=
p                       |   1357 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocOverflowSe=
curityChecker.cpp       |      7 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoo=
lChecker.cpp            |     31 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NSErrorChecker.c=
pp                      |     14 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFunction=
Checker.cpp             |      4 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/OSAtomicChecker.=
cpp                     |     96 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCAtSyncChecke=
r.cpp                   |     21 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCSelfInitChec=
ker.cpp                 |     82 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedIVarsC=
hecker.cpp              |      2 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PointerArithChec=
ker.cpp                 |     11 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PointerSubChecke=
r.cpp                   |     11 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PthreadLockCheck=
er.cpp                  |     44 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCountCheck=
er.cpp                  |    916 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ReturnPointerRan=
geChecker.cpp           |     10 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ReturnUndefCheck=
er.cpp                  |      7 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeC=
hecker.cpp              |     64 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cp=
p                       |    109 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefBranchCheck=
er.cpp                  |     37 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefCapturedBlo=
ckVarChecker.cpp        |     20 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefResultCheck=
er.cpp                  |     20 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedArraySu=
bscriptChecker.cpp      |      7 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedAssignm=
entChecker.cpp          |      8 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.c=
pp                      |    206 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnreachableCodeC=
hecker.cpp              |     34 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.c=
pp                      |     87 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/AnalysisManager.cpp =
                        |     38 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BasicConstraintManag=
er.cpp                  |     66 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp     =
                        |    744 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.=
cpp                     |    237 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Checker.cpp         =
                        |      9 +
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerContext.cpp  =
                        |     76 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.cpp  =
                        |    174 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerRegistry.cpp =
                        |      5 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp      =
                        |    616 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Environment.cpp     =
                        |    147 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp   =
                        |    176 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp      =
                        |   1225 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp     =
                        |    609 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp   =
                        |    239 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallAndRet=
urn.cpp                 |    357 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp  =
                        |     92 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp =
                        |    127 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp       =
                        |    170 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ObjCMessage.cpp     =
                        |    118 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/PathDiagnostic.cpp  =
                        |    466 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/PlistDiagnostics.cpp=
                        |    298 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ProgramState.cpp    =
                        |    352 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/RangeConstraintManag=
er.cpp                  |     64 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/RegionStore.cpp     =
                        |    388 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp     =
                        |    152 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SVals.cpp           =
                        |     89 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleConstraintMana=
ger.cpp                 |    174 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleConstraintMana=
ger.h                   |     36 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cp=
p                       |    337 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Store.cpp           =
                        |     46 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SymbolManager.cpp   =
                        |    128 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/TextPathDiagnostics.=
cpp                     |     31 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Frontend/AnalysisConsumer=
.cpp                    |    414 +-
 head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Frontend/CheckerRegistrat=
ion.cpp                 |      2 +-
 head/contrib/llvm/tools/clang/tools/driver/cc1_main.cpp                   =
                        |     22 +-
 head/contrib/llvm/tools/clang/tools/driver/cc1as_main.cpp                 =
                        |     80 +-
 head/contrib/llvm/tools/clang/tools/driver/driver.cpp                     =
                        |     38 +-
 head/contrib/llvm/tools/clang/utils/TableGen/ClangAttrEmitter.cpp         =
                        |    318 +-
 head/contrib/llvm/tools/clang/utils/TableGen/ClangAttrEmitter.h           =
                        |     39 +
 head/contrib/llvm/tools/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp  =
                        |    113 +-
 head/contrib/llvm/tools/clang/utils/TableGen/NeonEmitter.cpp              =
                        |     91 +-
 head/contrib/llvm/tools/clang/utils/TableGen/NeonEmitter.h                =
                        |     34 +
 head/contrib/llvm/tools/clang/utils/TableGen/TableGen.cpp                 =
                        |     26 +-
 head/contrib/llvm/tools/llc/llc.cpp                                       =
                        |    224 +-
 head/contrib/llvm/tools/lli/lli.cpp                                       =
                        |     38 +-
 head/contrib/llvm/tools/llvm-as/llvm-as.cpp                               =
                        |      2 +-
 head/contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp               =
                        |    123 +-
 head/contrib/llvm/tools/llvm-diff/DiffConsumer.cpp                        =
                        |      6 +
 head/contrib/llvm/tools/llvm-diff/DiffConsumer.h                          =
                        |      1 +
 head/contrib/llvm/tools/llvm-diff/DifferenceEngine.cpp                    =
                        |     18 +-
 head/contrib/llvm/tools/llvm-diff/DifferenceEngine.h                      =
                        |      4 +-
 head/contrib/llvm/tools/llvm-diff/llvm-diff.cpp                           =
                        |      2 +-
 head/contrib/llvm/tools/llvm-dis/llvm-dis.cpp                             =
                        |     19 +-
 head/contrib/llvm/tools/llvm-extract/llvm-extract.cpp                     =
                        |     12 +-
 head/contrib/llvm/tools/llvm-ld/llvm-ld.cpp                               =
                        |      4 +-
 head/contrib/llvm/tools/llvm-link/llvm-link.cpp                           =
                        |      2 +-
 head/contrib/llvm/tools/llvm-mc/Disassembler.cpp                          =
                        |     36 +-
 head/contrib/llvm/tools/llvm-mc/llvm-mc.cpp                               =
                        |     49 +-
 head/contrib/llvm/tools/llvm-nm/llvm-nm.cpp                               =
                        |    102 +-
 head/contrib/llvm/tools/llvm-objdump/MachODump.cpp                        =
                        |    404 +-
 head/contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp                     =
                        |    228 +-
 head/contrib/llvm/tools/llvm-objdump/llvm-objdump.h                       =
                        |      2 +-
 head/contrib/llvm/tools/llvm-prof/llvm-prof.cpp                           =
                        |     18 +-
 head/contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp                       =
                        |     31 +-
 head/contrib/llvm/tools/opt/PrintSCC.cpp                                  =
                        |      4 +-
 head/contrib/llvm/tools/opt/opt.cpp                                       =
                        |      9 +-
 head/contrib/llvm/utils/TableGen/AsmMatcherEmitter.cpp                    =
                        |    471 +-
 head/contrib/llvm/utils/TableGen/AsmWriterEmitter.cpp                     =
                        |    185 +-
 head/contrib/llvm/utils/TableGen/AsmWriterEmitter.h                       =
                        |      2 -
 head/contrib/llvm/utils/TableGen/CallingConvEmitter.cpp                   =
                        |      6 +-
 head/contrib/llvm/utils/TableGen/CodeEmitterGen.cpp                       =
                        |     26 +-
 head/contrib/llvm/utils/TableGen/CodeGenDAGPatterns.cpp                   =
                        |     22 +-
 head/contrib/llvm/utils/TableGen/CodeGenDAGPatterns.h                     =
                        |     10 +-
 head/contrib/llvm/utils/TableGen/CodeGenInstruction.cpp                   =
                        |     45 +-
 head/contrib/llvm/utils/TableGen/CodeGenRegisters.cpp                     =
                        |   1024 +-
 head/contrib/llvm/utils/TableGen/CodeGenRegisters.h                       =
                        |    247 +-
 head/contrib/llvm/utils/TableGen/CodeGenTarget.cpp                        =
                        |     29 +-
 head/contrib/llvm/utils/TableGen/CodeGenTarget.h                          =
                        |     10 +
 head/contrib/llvm/utils/TableGen/DAGISelMatcher.cpp                       =
                        |      6 +
 head/contrib/llvm/utils/TableGen/DAGISelMatcher.h                         =
                        |      3 +
 head/contrib/llvm/utils/TableGen/DAGISelMatcherEmitter.cpp                =
                        |     11 +-
 head/contrib/llvm/utils/TableGen/DAGISelMatcherGen.cpp                    =
                        |      2 +-
 head/contrib/llvm/utils/TableGen/DisassemblerEmitter.cpp                  =
                        |      1 -
 head/contrib/llvm/utils/TableGen/EDEmitter.cpp                            =
                        |     36 +-
 head/contrib/llvm/utils/TableGen/FastISelEmitter.cpp                      =
                        |      3 +-
 head/contrib/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp               =
                        |    334 +-
 head/contrib/llvm/utils/TableGen/FixedLenDecoderEmitter.h                 =
                        |     18 +-
 head/contrib/llvm/utils/TableGen/InstrInfoEmitter.cpp                     =
                        |     49 +-
 head/contrib/llvm/utils/TableGen/InstrInfoEmitter.h                       =
                        |     10 +-
 head/contrib/llvm/utils/TableGen/IntrinsicEmitter.cpp                     =
                        |    141 +-
 head/contrib/llvm/utils/TableGen/IntrinsicEmitter.h                       =
                        |      2 -
 head/contrib/llvm/utils/TableGen/PseudoLoweringEmitter.cpp                =
                        |      9 +-
 head/contrib/llvm/utils/TableGen/RegisterInfoEmitter.cpp                  =
                        |    829 +-
 head/contrib/llvm/utils/TableGen/RegisterInfoEmitter.h                    =
                        |      6 +
 head/contrib/llvm/utils/TableGen/SetTheory.cpp                            =
                        |     23 +
 head/contrib/llvm/utils/TableGen/SetTheory.h                              =
                        |      8 +-
 head/contrib/llvm/utils/TableGen/StringToOffsetTable.h                    =
                        |     13 +-
 head/contrib/llvm/utils/TableGen/SubtargetEmitter.cpp                     =
                        |     82 +-
 head/contrib/llvm/utils/TableGen/TableGen.cpp                             =
                        |    175 +-
 head/contrib/llvm/utils/TableGen/X86DisassemblerTables.cpp                =
                        |    148 +-
 head/contrib/llvm/utils/TableGen/X86ModRMFilters.h                        =
                        |     15 +-
 head/contrib/llvm/utils/TableGen/X86RecognizableInstr.cpp                 =
                        |    236 +-
 head/contrib/llvm/utils/TableGen/X86RecognizableInstr.h                   =
                        |     10 +-
 head/contrib/openbsm/libauditd/auditd_lib.c                               =
                        |      1 +
 head/contrib/openpam/lib/openpam_configure.c                              =
                        |     14 +-
 head/contrib/telnet/libtelnet/kerberos5.c                                 =
                        |    110 +-
 head/contrib/tzdata/antarctica                                            =
                        |     21 +-
 head/contrib/tzdata/asia                                                  =
                        |     24 +-
 head/contrib/tzdata/australasia                                           =
                        |     28 +-
 head/contrib/tzdata/europe                                                =
                        |     14 +-
 head/contrib/tzdata/leapseconds                                           =
                        |     42 +-
 head/contrib/tzdata/northamerica                                          =
                        |     93 +-
 head/contrib/tzdata/southamerica                                          =
                        |     53 +-
 head/contrib/tzdata/zone.tab                                              =
                        |      5 +-
 head/crypto/heimdal/ChangeLog                                             =
                        |   1783 +-
 head/crypto/heimdal/ChangeLog.2002                                        =
                        |      2 +-
 head/crypto/heimdal/ChangeLog.2003                                        =
                        |    286 +-
 head/crypto/heimdal/ChangeLog.2004                                        =
                        |    246 +-
 head/crypto/heimdal/ChangeLog.2005                                        =
                        |    336 +-
 head/crypto/heimdal/ChangeLog.2006                                        =
                        |    388 +-
 head/crypto/heimdal/LICENSE                                               =
                        |      5 +-
 head/crypto/heimdal/Makefile.am                                           =
                        |     14 +-
 head/crypto/heimdal/Makefile.am.common                                    =
                        |      2 +-
 head/crypto/heimdal/Makefile.in                                           =
                        |    338 +-
 head/crypto/heimdal/NEWS                                                  =
                        |    172 +
 head/crypto/heimdal/README                                                =
                        |     11 +-
 head/crypto/heimdal/acinclude.m4                                          =
                        |      3 +-
 head/crypto/heimdal/aclocal.m4                                            =
                        |   6905 +-
 head/crypto/heimdal/admin/ChangeLog                                       =
                        |     12 +-
 head/crypto/heimdal/admin/Makefile.am                                     =
                        |      7 +-
 head/crypto/heimdal/admin/Makefile.in                                     =
                        |    391 +-
 head/crypto/heimdal/admin/add.c                                           =
                        |     60 +-
 head/crypto/heimdal/admin/change.c                                        =
                        |     72 +-
 head/crypto/heimdal/admin/copy.c                                          =
                        |    106 +-
 head/crypto/heimdal/admin/get.c                                           =
                        |    107 +-
 head/crypto/heimdal/admin/ktutil-commands.in                              =
                        |     39 +-
 head/crypto/heimdal/admin/ktutil.8                                        =
                        |    178 +-
 head/crypto/heimdal/admin/ktutil.c                                        =
                        |     93 +-
 head/crypto/heimdal/admin/ktutil_locl.h                                   =
                        |     60 +-
 head/crypto/heimdal/admin/list.c                                          =
                        |     80 +-
 head/crypto/heimdal/admin/purge.c                                         =
                        |     58 +-
 head/crypto/heimdal/admin/remove.c                                        =
                        |     54 +-
 head/crypto/heimdal/admin/rename.c                                        =
                        |     70 +-
 head/crypto/heimdal/appl/Makefile.am                                      =
                        |      4 +-
 head/crypto/heimdal/appl/Makefile.in                                      =
                        |    249 +-
 head/crypto/heimdal/appl/afsutil/ChangeLog                                =
                        |     20 +-
 head/crypto/heimdal/appl/afsutil/Makefile.am                              =
                        |      4 +-
 head/crypto/heimdal/appl/afsutil/Makefile.in                              =
                        |    375 +-
 head/crypto/heimdal/appl/afsutil/afslog.1                                 =
                        |    113 +-
 head/crypto/heimdal/appl/afsutil/afslog.c                                 =
                        |     86 +-
 head/crypto/heimdal/appl/afsutil/pagsh.1                                  =
                        |     82 +-
 head/crypto/heimdal/appl/afsutil/pagsh.c                                  =
                        |     56 +-
 head/crypto/heimdal/appl/ftp/ChangeLog                                    =
                        |    108 +-
 head/crypto/heimdal/appl/ftp/Makefile.am                                  =
                        |      4 +-
 head/crypto/heimdal/appl/ftp/Makefile.in                                  =
                        |    249 +-
 head/crypto/heimdal/appl/ftp/common/Makefile.am                           =
                        |      4 +-
 head/crypto/heimdal/appl/ftp/common/Makefile.in                           =
                        |    211 +-
 head/crypto/heimdal/appl/ftp/common/buffer.c                              =
                        |     14 +-
 head/crypto/heimdal/appl/ftp/common/common.h                              =
                        |     14 +-
 head/crypto/heimdal/appl/ftp/common/sockbuf.c                             =
                        |     36 +-
 head/crypto/heimdal/appl/ftp/ftp/Makefile.am                              =
                        |     13 +-
 head/crypto/heimdal/appl/ftp/ftp/Makefile.in                              =
                        |    399 +-
 head/crypto/heimdal/appl/ftp/ftp/cmds.c                                   =
                        |     33 +-
 head/crypto/heimdal/appl/ftp/ftp/cmdtab.c                                 =
                        |     24 +-
 head/crypto/heimdal/appl/ftp/ftp/domacro.c                                =
                        |      2 +-
 head/crypto/heimdal/appl/ftp/ftp/extern.h                                 =
                        |      4 +-
 head/crypto/heimdal/appl/ftp/ftp/ftp.1                                    =
                        |      8 +-
 head/crypto/heimdal/appl/ftp/ftp/ftp.c                                    =
                        |     84 +-
 head/crypto/heimdal/appl/ftp/ftp/ftp_locl.h                               =
                        |     15 +-
 head/crypto/heimdal/appl/ftp/ftp/globals.c                                =
                        |      4 +-
 head/crypto/heimdal/appl/ftp/ftp/gssapi.c                                 =
                        |    145 +-
 head/crypto/heimdal/appl/ftp/ftp/kauth.c                                  =
                        |    152 +-
 head/crypto/heimdal/appl/ftp/ftp/main.c                                   =
                        |     11 +-
 head/crypto/heimdal/appl/ftp/ftp/ruserpass.c                              =
                        |     12 +-
 head/crypto/heimdal/appl/ftp/ftp/security.c                               =
                        |     78 +-
 head/crypto/heimdal/appl/ftp/ftp/security.h                               =
                        |     65 +-
 head/crypto/heimdal/appl/ftp/ftpd/Makefile.am                             =
                        |     13 +-
 head/crypto/heimdal/appl/ftp/ftpd/Makefile.in                             =
                        |    474 +-
 head/crypto/heimdal/appl/ftp/ftpd/extern.h                                =
                        |      4 +-
 head/crypto/heimdal/appl/ftp/ftpd/ftpcmd.c                                =
                        |    279 +-
 head/crypto/heimdal/appl/ftp/ftpd/ftpcmd.y                                =
                        |     68 +-
 head/crypto/heimdal/appl/ftp/ftpd/ftpd.8                                  =
                        |     16 +-
 head/crypto/heimdal/appl/ftp/ftpd/ftpd.c                                  =
                        |    164 +-
 head/crypto/heimdal/appl/ftp/ftpd/ftpd_locl.h                             =
                        |     60 +-
 head/crypto/heimdal/appl/ftp/ftpd/ftpusers.5                              =
                        |      2 +-
 head/crypto/heimdal/appl/ftp/ftpd/gss_userok.c                            =
                        |    174 +-
 head/crypto/heimdal/appl/ftp/ftpd/gssapi.c                                =
                        |    145 +-
 head/crypto/heimdal/appl/ftp/ftpd/kauth.c                                 =
                        |    242 +-
 head/crypto/heimdal/appl/ftp/ftpd/klist.c                                 =
                        |     22 +-
 head/crypto/heimdal/appl/ftp/ftpd/logwtmp.c                               =
                        |     85 +-
 head/crypto/heimdal/appl/ftp/ftpd/ls.c                                    =
                        |     78 +-
 head/crypto/heimdal/appl/ftp/ftpd/popen.c                                 =
                        |     14 +-
 head/crypto/heimdal/appl/ftp/ftpd/security.c                              =
                        |     78 +-
 head/crypto/heimdal/appl/gssmask/Makefile.am                              =
                        |      5 +-
 head/crypto/heimdal/appl/gssmask/Makefile.in                              =
                        |    229 +-
 head/crypto/heimdal/appl/gssmask/common.c                                 =
                        |     28 +-
 head/crypto/heimdal/appl/gssmask/common.h                                 =
                        |     30 +-
 head/crypto/heimdal/appl/gssmask/gssmaestro.c                             =
                        |    212 +-
 head/crypto/heimdal/appl/gssmask/gssmask.c                                =
                        |    279 +-
 head/crypto/heimdal/appl/gssmask/protocol.h                               =
                        |     81 +-
 head/crypto/heimdal/appl/kf/Makefile.am                                   =
                        |      4 +-
 head/crypto/heimdal/appl/kf/Makefile.in                                   =
                        |    503 +-
 head/crypto/heimdal/appl/kf/kf.1                                          =
                        |     72 +-
 head/crypto/heimdal/appl/kf/kf.c                                          =
                        |     83 +-
 head/crypto/heimdal/appl/kf/kf_locl.h                                     =
                        |     52 +-
 head/crypto/heimdal/appl/kf/kfd.8                                         =
                        |     64 +-
 head/crypto/heimdal/appl/kf/kfd.c                                         =
                        |     65 +-
 head/crypto/heimdal/appl/login/ChangeLog                                  =
                        |     31 +-
 head/crypto/heimdal/appl/login/Makefile.am                                =
                        |     15 +-
 head/crypto/heimdal/appl/login/Makefile.in                                =
                        |    472 +-
 head/crypto/heimdal/appl/login/conf.c                                     =
                        |     24 +-
 head/crypto/heimdal/appl/login/env.c                                      =
                        |     69 +-
 head/crypto/heimdal/appl/login/limits_conf.c                              =
                        |     60 +-
 head/crypto/heimdal/appl/login/login.1                                    =
                        |     57 +-
 head/crypto/heimdal/appl/login/login.access.5                             =
                        |     11 +-
 head/crypto/heimdal/appl/login/login.c                                    =
                        |    240 +-
 head/crypto/heimdal/appl/login/login_access.c                             =
                        |      6 +-
 head/crypto/heimdal/appl/login/login_locl.h                               =
                        |     65 +-
 head/crypto/heimdal/appl/login/loginpaths.h                               =
                        |     52 +-
 head/crypto/heimdal/appl/login/osfc2.c                                    =
                        |     66 +-
 head/crypto/heimdal/appl/login/read_string.c                              =
                        |     62 +-
 head/crypto/heimdal/appl/login/shadow.c                                   =
                        |     56 +-
 head/crypto/heimdal/appl/login/stty_default.c                             =
                        |     16 +-
 head/crypto/heimdal/appl/login/tty.c                                      =
                        |     16 +-
 head/crypto/heimdal/appl/login/utmp_login.c                               =
                        |     26 +-
 head/crypto/heimdal/appl/login/utmpx_login.c                              =
                        |      4 +-
 head/crypto/heimdal/appl/push/ChangeLog                                   =
                        |      4 +-
 head/crypto/heimdal/appl/push/Makefile.am                                 =
                        |      7 +-
 head/crypto/heimdal/appl/push/Makefile.in                                 =
                        |    491 +-
 head/crypto/heimdal/appl/push/pfrom.1                                     =
                        |     64 +-
 head/crypto/heimdal/appl/push/pfrom.in                                    =
                        |      2 +-
 head/crypto/heimdal/appl/push/push.8                                      =
                        |     34 +-
 head/crypto/heimdal/appl/push/push.c                                      =
                        |    175 +-
 head/crypto/heimdal/appl/push/push_locl.h                                 =
                        |     56 +-
 head/crypto/heimdal/appl/rcp/ChangeLog                                    =
                        |     23 +-
 head/crypto/heimdal/appl/rcp/Makefile.am                                  =
                        |      4 +-
 head/crypto/heimdal/appl/rcp/Makefile.in                                  =
                        |    375 +-
 head/crypto/heimdal/appl/rcp/extern.h                                     =
                        |      5 +-
 head/crypto/heimdal/appl/rcp/rcp.1                                        =
                        |     21 +-
 head/crypto/heimdal/appl/rcp/rcp.c                                        =
                        |     69 +-
 head/crypto/heimdal/appl/rcp/rcp_locl.h                                   =
                        |     52 +-
 head/crypto/heimdal/appl/rcp/util.c                                       =
                        |     24 +-
 head/crypto/heimdal/appl/rsh/ChangeLog                                    =
                        |     36 +-
 head/crypto/heimdal/appl/rsh/Makefile.am                                  =
                        |      7 +-
 head/crypto/heimdal/appl/rsh/Makefile.in                                  =
                        |    515 +-
 head/crypto/heimdal/appl/rsh/common.c                                     =
                        |     74 +-
 head/crypto/heimdal/appl/rsh/limits_conf.c                                =
                        |     60 +-
 head/crypto/heimdal/appl/rsh/login_access.c                               =
                        |      6 +-
 head/crypto/heimdal/appl/rsh/rsh.1                                        =
                        |     95 +-
 head/crypto/heimdal/appl/rsh/rsh.c                                        =
                        |    222 +-
 head/crypto/heimdal/appl/rsh/rsh_locl.h                                   =
                        |     71 +-
 head/crypto/heimdal/appl/rsh/rshd.8                                       =
                        |     71 +-
 head/crypto/heimdal/appl/rsh/rshd.c                                       =
                        |    250 +-
 head/crypto/heimdal/appl/su/ChangeLog                                     =
                        |     22 +-
 head/crypto/heimdal/appl/su/Makefile.am                                   =
                        |      6 +-
 head/crypto/heimdal/appl/su/Makefile.in                                   =
                        |    378 +-
 head/crypto/heimdal/appl/su/su.1                                          =
                        |     82 +-
 head/crypto/heimdal/appl/su/su.c                                          =
                        |    208 +-
 head/crypto/heimdal/appl/su/supaths.h                                     =
                        |     50 +-
 head/crypto/heimdal/appl/telnet/ChangeLog                                 =
                        |     95 +-
 head/crypto/heimdal/appl/telnet/Makefile.am                               =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/Makefile.in                               =
                        |    250 +-
 head/crypto/heimdal/appl/telnet/libtelnet/Makefile.am                     =
                        |      7 +-
 head/crypto/heimdal/appl/telnet/libtelnet/Makefile.in                     =
                        |    221 +-
 head/crypto/heimdal/appl/telnet/libtelnet/auth-proto.h                    =
                        |     27 +-
 head/crypto/heimdal/appl/telnet/libtelnet/auth.c                          =
                        |     42 +-
 head/crypto/heimdal/appl/telnet/libtelnet/auth.h                          =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/libtelnet/enc-proto.h                     =
                        |     10 +-
 head/crypto/heimdal/appl/telnet/libtelnet/enc_des.c                       =
                        |     59 +-
 head/crypto/heimdal/appl/telnet/libtelnet/encrypt.c                       =
                        |     29 +-
 head/crypto/heimdal/appl/telnet/libtelnet/encrypt.h                       =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/libtelnet/genget.c                        =
                        |      9 +-
 head/crypto/heimdal/appl/telnet/libtelnet/kerberos5.c                     =
                        |     69 +-
 head/crypto/heimdal/appl/telnet/libtelnet/misc-proto.h                    =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/libtelnet/misc.c                          =
                        |      2 +-
 head/crypto/heimdal/appl/telnet/libtelnet/rsaencpwd.c                     =
                        |      9 +-
 head/crypto/heimdal/appl/telnet/libtelnet/spx.c                           =
                        |     21 +-
 head/crypto/heimdal/appl/telnet/telnet/Makefile.am                        =
                        |      7 +-
 head/crypto/heimdal/appl/telnet/telnet/Makefile.in                        =
                        |    387 +-
 head/crypto/heimdal/appl/telnet/telnet/authenc.c                          =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/telnet/commands.c                         =
                        |     33 +-
 head/crypto/heimdal/appl/telnet/telnet/externs.h                          =
                        |      5 +-
 head/crypto/heimdal/appl/telnet/telnet/main.c                             =
                        |     32 +-
 head/crypto/heimdal/appl/telnet/telnet/network.c                          =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/telnet/ring.c                             =
                        |      2 +-
 head/crypto/heimdal/appl/telnet/telnet/ring.h                             =
                        |      2 +-
 head/crypto/heimdal/appl/telnet/telnet/sys_bsd.c                          =
                        |     12 +-
 head/crypto/heimdal/appl/telnet/telnet/telnet.c                           =
                        |     12 +-
 head/crypto/heimdal/appl/telnet/telnet/telnet_locl.h                      =
                        |     14 +-
 head/crypto/heimdal/appl/telnet/telnet/terminal.c                         =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/telnet/utilities.c                        =
                        |     69 +-
 head/crypto/heimdal/appl/telnet/telnetd/Makefile.am                       =
                        |      7 +-
 head/crypto/heimdal/appl/telnet/telnetd/Makefile.in                       =
                        |    385 +-
 head/crypto/heimdal/appl/telnet/telnetd/authenc.c                         =
                        |      2 +-
 head/crypto/heimdal/appl/telnet/telnetd/defs.h                            =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/telnetd/ext.h                             =
                        |      6 +-
 head/crypto/heimdal/appl/telnet/telnetd/global.c                          =
                        |      2 +-
 head/crypto/heimdal/appl/telnet/telnetd/slc.c                             =
                        |      8 +-
 head/crypto/heimdal/appl/telnet/telnetd/state.c                           =
                        |      4 +-
 head/crypto/heimdal/appl/telnet/telnetd/sys_term.c                        =
                        |     75 +-
 head/crypto/heimdal/appl/telnet/telnetd/telnetd.c                         =
                        |     12 +-
 head/crypto/heimdal/appl/telnet/telnetd/telnetd.h                         =
                        |      4 -
 head/crypto/heimdal/appl/telnet/telnetd/termstat.c                        =
                        |      2 +-
 head/crypto/heimdal/appl/telnet/telnetd/utility.c                         =
                        |     69 +-
 head/crypto/heimdal/appl/test/Makefile.am                                 =
                        |      4 +-
 head/crypto/heimdal/appl/test/Makefile.in                                 =
                        |    232 +-
 head/crypto/heimdal/appl/test/common.c                                    =
                        |     60 +-
 head/crypto/heimdal/appl/test/gss_common.c                                =
                        |     58 +-
 head/crypto/heimdal/appl/test/gss_common.h                                =
                        |     52 +-
 head/crypto/heimdal/appl/test/gssapi_client.c                             =
                        |    103 +-
 head/crypto/heimdal/appl/test/gssapi_server.c                             =
                        |     79 +-
 head/crypto/heimdal/appl/test/http_client.c                               =
                        |     76 +-
 head/crypto/heimdal/appl/test/nt_gss_client.c                             =
                        |     52 +-
 head/crypto/heimdal/appl/test/nt_gss_common.c                             =
                        |     58 +-
 head/crypto/heimdal/appl/test/nt_gss_common.h                             =
                        |     52 +-
 head/crypto/heimdal/appl/test/nt_gss_server.c                             =
                        |     85 +-
 head/crypto/heimdal/appl/test/tcp_client.c                                =
                        |     52 +-
 head/crypto/heimdal/appl/test/tcp_server.c                                =
                        |     58 +-
 head/crypto/heimdal/appl/test/test_locl.h                                 =
                        |     52 +-
 head/crypto/heimdal/appl/test/uu_client.c                                 =
                        |     66 +-
 head/crypto/heimdal/appl/test/uu_server.c                                 =
                        |     92 +-
 head/crypto/heimdal/autogen.sh                                            =
                        |      1 +
 head/crypto/heimdal/compile                                               =
                        |     21 +-
 head/crypto/heimdal/config.guess                                          =
                        |    291 +-
 head/crypto/heimdal/config.sub                                            =
                        |    149 +-
 head/crypto/heimdal/configure                                             =
                        |  55953 ++-------
 head/crypto/heimdal/doc/Makefile.am                                       =
                        |    105 +-
 head/crypto/heimdal/doc/Makefile.in                                       =
                        |    389 +-
 head/crypto/heimdal/doc/ack.texi                                          =
                        |     66 +-
 head/crypto/heimdal/doc/apps.texi                                         =
                        |     28 +-
 head/crypto/heimdal/doc/doxytmpl.dxy                                      =
                        |      1 -
 head/crypto/heimdal/doc/hcrypto.din                                       =
                        |      3 +-
 head/crypto/heimdal/doc/heimdal.texi                                      =
                        |    247 +-
 head/crypto/heimdal/doc/hx509.din                                         =
                        |      2 +-
 head/crypto/heimdal/doc/hx509.texi                                        =
                        |    424 +-
 head/crypto/heimdal/doc/install.texi                                      =
                        |    103 +-
 head/crypto/heimdal/doc/intro.texi                                        =
                        |      5 +-
 head/crypto/heimdal/doc/kerberos4.texi                                    =
                        |     63 +-
 head/crypto/heimdal/doc/krb5.din                                          =
                        |      2 +-
 head/crypto/heimdal/doc/migration.texi                                    =
                        |     12 +-
 head/crypto/heimdal/doc/misc.texi                                         =
                        |      2 +-
 head/crypto/heimdal/doc/ntlm.din                                          =
                        |      3 +-
 head/crypto/heimdal/doc/programming.texi                                  =
                        |    643 +-
 head/crypto/heimdal/doc/setup.texi                                        =
                        |    549 +-
 head/crypto/heimdal/doc/vars.texi                                         =
                        |      2 +-
 head/crypto/heimdal/doc/whatis.texi                                       =
                        |      2 +-
 head/crypto/heimdal/doc/win2k.texi                                        =
                        |    112 +-
 head/crypto/heimdal/etc/Makefile.am                                       =
                        |      4 +-
 head/crypto/heimdal/etc/Makefile.in                                       =
                        |    148 +-
 head/crypto/heimdal/etc/services.append                                   =
                        |      2 +-
 head/crypto/heimdal/include/Makefile.am                                   =
                        |     94 +-
 head/crypto/heimdal/include/Makefile.in                                   =
                        |    433 +-
 head/crypto/heimdal/include/bits.c                                        =
                        |    117 +-
 head/crypto/heimdal/include/config.h.in                                   =
                        |    254 +-
 head/crypto/heimdal/include/gssapi/Makefile.am                            =
                        |      5 +-
 head/crypto/heimdal/include/gssapi/Makefile.in                            =
                        |    149 +-
 head/crypto/heimdal/include/hcrypto/Makefile.am                           =
                        |      9 +-
 head/crypto/heimdal/include/hcrypto/Makefile.in                           =
                        |    152 +-
 head/crypto/heimdal/include/kadm5/Makefile.am                             =
                        |      7 +-
 head/crypto/heimdal/include/kadm5/Makefile.in                             =
                        |    150 +-
 head/crypto/heimdal/install-sh                                            =
                        |    225 +-
 head/crypto/heimdal/kadmin/ChangeLog                                      =
                        |    130 +-
 head/crypto/heimdal/kadmin/Makefile.am                                    =
                        |     19 +-
 head/crypto/heimdal/kadmin/Makefile.in                                    =
                        |    556 +-
 head/crypto/heimdal/kadmin/add-random-users.c                             =
                        |     59 +-
 head/crypto/heimdal/kadmin/add_enctype.c                                  =
                        |     53 +-
 head/crypto/heimdal/kadmin/ank.c                                          =
                        |     90 +-
 head/crypto/heimdal/kadmin/check.c                                        =
                        |     63 +-
 head/crypto/heimdal/kadmin/cpw.c                                          =
                        |     58 +-
 head/crypto/heimdal/kadmin/del.c                                          =
                        |     52 +-
 head/crypto/heimdal/kadmin/del_enctype.c                                  =
                        |     54 +-
 head/crypto/heimdal/kadmin/dump.c                                         =
                        |     58 +-
 head/crypto/heimdal/kadmin/ext.c                                          =
                        |     60 +-
 head/crypto/heimdal/kadmin/get.c                                          =
                        |    142 +-
 head/crypto/heimdal/kadmin/init.c                                         =
                        |    103 +-
 head/crypto/heimdal/kadmin/kadm_conn.c                                    =
                        |    193 +-
 head/crypto/heimdal/kadmin/kadmin-commands.in                             =
                        |     14 +-
 head/crypto/heimdal/kadmin/kadmin.8                                       =
                        |    181 +-
 head/crypto/heimdal/kadmin/kadmin.c                                       =
                        |    126 +-
 head/crypto/heimdal/kadmin/kadmin_locl.h                                  =
                        |     75 +-
 head/crypto/heimdal/kadmin/kadmind.8                                      =
                        |    102 +-
 head/crypto/heimdal/kadmin/kadmind.c                                      =
                        |    142 +-
 head/crypto/heimdal/kadmin/load.c                                         =
                        |     92 +-
 head/crypto/heimdal/kadmin/mod.c                                          =
                        |    126 +-
 head/crypto/heimdal/kadmin/pw_quality.c                                   =
                        |     52 +-
 head/crypto/heimdal/kadmin/random_password.c                              =
                        |     64 +-
 head/crypto/heimdal/kadmin/rename.c                                       =
                        |     52 +-
 head/crypto/heimdal/kadmin/server.c                                       =
                        |    369 +-
 head/crypto/heimdal/kadmin/stash.c                                        =
                        |     81 +-
 head/crypto/heimdal/kadmin/test_util.c                                    =
                        |     30 +-
 head/crypto/heimdal/kadmin/util.c                                         =
                        |    110 +-
 head/crypto/heimdal/kcm/Makefile.am                                       =
                        |     19 +-
 head/crypto/heimdal/kcm/Makefile.in                                       =
                        |    411 +-
 head/crypto/heimdal/kcm/acl.c                                             =
                        |     61 +-
 head/crypto/heimdal/kcm/acquire.c                                         =
                        |    424 +-
 head/crypto/heimdal/kcm/cache.c                                           =
                        |    327 +-
 head/crypto/heimdal/kcm/client.c                                          =
                        |     32 +-
 head/crypto/heimdal/kcm/config.c                                          =
                        |     83 +-
 head/crypto/heimdal/kcm/connect.c                                         =
                        |    718 +-
 head/crypto/heimdal/kcm/events.c                                          =
                        |     11 +-
 head/crypto/heimdal/kcm/glue.c                                            =
                        |      3 +-
 head/crypto/heimdal/kcm/headers.h                                         =
                        |     21 +-
 head/crypto/heimdal/kcm/kcm.8                                             =
                        |    178 +-
 head/crypto/heimdal/kcm/kcm_locl.h                                        =
                        |     45 +-
 head/crypto/heimdal/kcm/log.c                                             =
                        |     52 +-
 head/crypto/heimdal/kcm/main.c                                            =
                        |     70 +-
 head/crypto/heimdal/kcm/protocol.c                                        =
                        |   1026 +-
 head/crypto/heimdal/kcm/renew.c                                           =
                        |      2 +-
 head/crypto/heimdal/kdc/Makefile.am                                       =
                        |     45 +-
 head/crypto/heimdal/kdc/Makefile.in                                       =
                        |    752 +-
 head/crypto/heimdal/kdc/config.c                                          =
                        |    193 +-
 head/crypto/heimdal/kdc/connect.c                                         =
                        |    309 +-
 head/crypto/heimdal/kdc/default_config.c                                  =
                        |    314 +-
 head/crypto/heimdal/kdc/digest.c                                          =
                        |    667 +-
 head/crypto/heimdal/kdc/headers.h                                         =
                        |     67 +-
 head/crypto/heimdal/kdc/hprop.8                                           =
                        |    162 +-
 head/crypto/heimdal/kdc/hprop.c                                           =
                        |    473 +-
 head/crypto/heimdal/kdc/hprop.h                                           =
                        |     52 +-
 head/crypto/heimdal/kdc/hpropd.8                                          =
                        |     95 +-
 head/crypto/heimdal/kdc/hpropd.c                                          =
                        |    132 +-
 head/crypto/heimdal/kdc/kdc-private.h                                     =
                        |    152 +-
 head/crypto/heimdal/kdc/kdc-protos.h                                      =
                        |     25 +
 head/crypto/heimdal/kdc/kdc-replay.c                                      =
                        |     77 +-
 head/crypto/heimdal/kdc/kdc.8                                             =
                        |    150 +-
 head/crypto/heimdal/kdc/kdc.h                                             =
                        |     97 +-
 head/crypto/heimdal/kdc/kdc_locl.h                                        =
                        |     70 +-
 head/crypto/heimdal/kdc/kerberos5.c                                       =
                        |   1081 +-
 head/crypto/heimdal/kdc/krb5tgs.c                                         =
                        |   1373 +-
 head/crypto/heimdal/kdc/kstash.8                                          =
                        |     90 +-
 head/crypto/heimdal/kdc/kstash.c                                          =
                        |     88 +-
 head/crypto/heimdal/kdc/kx509.c                                           =
                        |    184 +-
 head/crypto/heimdal/kdc/log.c                                             =
                        |     76 +-
 head/crypto/heimdal/kdc/main.c                                            =
                        |    124 +-
 head/crypto/heimdal/kdc/misc.c                                            =
                        |    148 +-
 head/crypto/heimdal/kdc/mit_dump.c                                        =
                        |    112 +-
 head/crypto/heimdal/kdc/pkinit.c                                          =
                        |   1257 +-
 head/crypto/heimdal/kdc/process.c                                         =
                        |    285 +-
 head/crypto/heimdal/kdc/rx.h                                              =
                        |     52 +-
 head/crypto/heimdal/kdc/set_dbinfo.c                                      =
                        |    107 +-
 head/crypto/heimdal/kdc/string2key.8                                      =
                        |    111 +-
 head/crypto/heimdal/kdc/string2key.c                                      =
                        |    105 +-
 head/crypto/heimdal/kdc/version-script.map                                =
                        |      9 +-
 head/crypto/heimdal/kdc/windc.c                                           =
                        |    112 +-
 head/crypto/heimdal/kdc/windc_plugin.h                                    =
                        |     75 +-
 head/crypto/heimdal/kpasswd/Makefile.am                                   =
                        |      5 +-
 head/crypto/heimdal/kpasswd/Makefile.in                                   =
                        |    524 +-
 head/crypto/heimdal/kpasswd/kpasswd-generator.c                           =
                        |     65 +-
 head/crypto/heimdal/kpasswd/kpasswd.1                                     =
                        |     60 +-
 head/crypto/heimdal/kpasswd/kpasswd.c                                     =
                        |    100 +-
 head/crypto/heimdal/kpasswd/kpasswd_locl.h                                =
                        |     52 +-
 head/crypto/heimdal/kpasswd/kpasswdd.8                                    =
                        |     74 +-
 head/crypto/heimdal/kpasswd/kpasswdd.c                                    =
                        |    214 +-
 head/crypto/heimdal/kuser/Makefile.am                                     =
                        |     50 +-
 head/crypto/heimdal/kuser/Makefile.in                                     =
                        |    614 +-
 head/crypto/heimdal/kuser/copy_cred_cache.1                               =
                        |     35 +-
 head/crypto/heimdal/kuser/copy_cred_cache.c                               =
                        |    176 +-
 head/crypto/heimdal/kuser/generate-requests.c                             =
                        |     80 +-
 head/crypto/heimdal/kuser/kdecode_ticket.c                                =
                        |     61 +-
 head/crypto/heimdal/kuser/kdestroy.1                                      =
                        |     78 +-
 head/crypto/heimdal/kuser/kdestroy.c                                      =
                        |    158 +-
 head/crypto/heimdal/kuser/kdigest-commands.in                             =
                        |      4 +-
 head/crypto/heimdal/kuser/kdigest.c                                       =
                        |    211 +-
 head/crypto/heimdal/kuser/kgetcred.1                                      =
                        |     94 +-
 head/crypto/heimdal/kuser/kgetcred.c                                      =
                        |     95 +-
 head/crypto/heimdal/kuser/kimpersonate.c                                  =
                        |    120 +-
 head/crypto/heimdal/kuser/kinit.1                                         =
                        |    230 +-
 head/crypto/heimdal/kuser/kinit.c                                         =
                        |    530 +-
 head/crypto/heimdal/kuser/klist.1                                         =
                        |    103 +-
 head/crypto/heimdal/kuser/klist.c                                         =
                        |    439 +-
 head/crypto/heimdal/kuser/kuser_locl.h                                    =
                        |     79 +-
 head/crypto/heimdal/kuser/kverify.c                                       =
                        |     68 +-
 head/crypto/heimdal/lib/Makefile.am                                       =
                        |     33 +-
 head/crypto/heimdal/lib/Makefile.in                                       =
                        |    278 +-
 head/crypto/heimdal/lib/asn1/ChangeLog                                    =
                        |    614 +-
 head/crypto/heimdal/lib/asn1/Makefile.am                                  =
                        |    592 +-
 head/crypto/heimdal/lib/asn1/Makefile.in                                  =
                        |   1370 +-
 head/crypto/heimdal/lib/asn1/asn1-common.h                                =
                        |     19 +-
 head/crypto/heimdal/lib/asn1/asn1_err.et                                  =
                        |      6 +-
 head/crypto/heimdal/lib/asn1/asn1_gen.c                                   =
                        |     75 +-
 head/crypto/heimdal/lib/asn1/asn1_print.c                                 =
                        |    130 +-
 head/crypto/heimdal/lib/asn1/asn1_queue.h                                 =
                        |      2 +-
 head/crypto/heimdal/lib/asn1/canthandle.asn1                              =
                        |      3 +-
 head/crypto/heimdal/lib/asn1/check-common.c                               =
                        |    136 +-
 head/crypto/heimdal/lib/asn1/check-common.h                               =
                        |     74 +-
 head/crypto/heimdal/lib/asn1/check-der.c                                  =
                        |    150 +-
 head/crypto/heimdal/lib/asn1/check-gen.c                                  =
                        |    500 +-
 head/crypto/heimdal/lib/asn1/check-timegm.c                               =
                        |     61 +-
 head/crypto/heimdal/lib/asn1/der-protos.h                                 =
                        |     67 +-
 head/crypto/heimdal/lib/asn1/der.c                                        =
                        |     52 +-
 head/crypto/heimdal/lib/asn1/der.h                                        =
                        |     56 +-
 head/crypto/heimdal/lib/asn1/der_cmp.c                                    =
                        |     70 +-
 head/crypto/heimdal/lib/asn1/der_copy.c                                   =
                        |    102 +-
 head/crypto/heimdal/lib/asn1/der_format.c                                 =
                        |     60 +-
 head/crypto/heimdal/lib/asn1/der_free.c                                   =
                        |     85 +-
 head/crypto/heimdal/lib/asn1/der_get.c                                    =
                        |    229 +-
 head/crypto/heimdal/lib/asn1/der_length.c                                 =
                        |     76 +-
 head/crypto/heimdal/lib/asn1/der_locl.h                                   =
                        |     59 +-
 head/crypto/heimdal/lib/asn1/der_put.c                                    =
                        |    114 +-
 head/crypto/heimdal/lib/asn1/digest.asn1                                  =
                        |     17 +
 head/crypto/heimdal/lib/asn1/extra.c                                      =
                        |    112 +-
 head/crypto/heimdal/lib/asn1/gen.c                                        =
                        |    479 +-
 head/crypto/heimdal/lib/asn1/gen_copy.c                                   =
                        |     96 +-
 head/crypto/heimdal/lib/asn1/gen_decode.c                                 =
                        |    295 +-
 head/crypto/heimdal/lib/asn1/gen_encode.c                                 =
                        |    139 +-
 head/crypto/heimdal/lib/asn1/gen_free.c                                   =
                        |     91 +-
 head/crypto/heimdal/lib/asn1/gen_glue.c                                   =
                        |     88 +-
 head/crypto/heimdal/lib/asn1/gen_length.c                                 =
                        |    102 +-
 head/crypto/heimdal/lib/asn1/gen_locl.h                                   =
                        |     73 +-
 head/crypto/heimdal/lib/asn1/gen_seq.c                                    =
                        |     74 +-
 head/crypto/heimdal/lib/asn1/hash.c                                       =
                        |     52 +-
 head/crypto/heimdal/lib/asn1/hash.h                                       =
                        |     54 +-
 head/crypto/heimdal/lib/asn1/heim_asn1.h                                  =
                        |     50 +-
 head/crypto/heimdal/lib/asn1/kx509.asn1                                   =
                        |     12 +
 head/crypto/heimdal/lib/asn1/lex.c                                        =
                        |    186 +-
 head/crypto/heimdal/lib/asn1/lex.h                                        =
                        |     54 +-
 head/crypto/heimdal/lib/asn1/lex.l                                        =
                        |     80 +-
 head/crypto/heimdal/lib/asn1/main.c                                       =
                        |    130 +-
 head/crypto/heimdal/lib/asn1/pkcs12.asn1                                  =
                        |      3 +-
 head/crypto/heimdal/lib/asn1/pkcs8.asn1                                   =
                        |      3 +-
 head/crypto/heimdal/lib/asn1/pkcs9.asn1                                   =
                        |      1 +
 head/crypto/heimdal/lib/asn1/pkinit.asn1                                  =
                        |     34 +-
 head/crypto/heimdal/lib/asn1/rfc2459.asn1                                 =
                        |     86 +-
 head/crypto/heimdal/lib/asn1/setchgpw2.asn1                               =
                        |      3 +-
 head/crypto/heimdal/lib/asn1/symbol.c                                     =
                        |      8 +-
 head/crypto/heimdal/lib/asn1/symbol.h                                     =
                        |     85 +-
 head/crypto/heimdal/lib/asn1/test.asn1                                    =
                        |     60 +-
 head/crypto/heimdal/lib/asn1/test.gen                                     =
                        |      2 +-
 head/crypto/heimdal/lib/asn1/timegm.c                                     =
                        |    124 +-
 head/crypto/heimdal/lib/com_err/ChangeLog                                 =
                        |     22 +-
 head/crypto/heimdal/lib/com_err/Makefile.am                               =
                        |     15 +-
 head/crypto/heimdal/lib/com_err/Makefile.in                               =
                        |    371 +-
 head/crypto/heimdal/lib/com_err/com_err.c                                 =
                        |     91 +-
 head/crypto/heimdal/lib/com_err/com_err.h                                 =
                        |     80 +-
 head/crypto/heimdal/lib/com_err/com_right.h                               =
                        |     86 +-
 head/crypto/heimdal/lib/com_err/compile_et.c                              =
                        |     96 +-
 head/crypto/heimdal/lib/com_err/compile_et.h                              =
                        |     54 +-
 head/crypto/heimdal/lib/com_err/error.c                                   =
                        |     93 +-
 head/crypto/heimdal/lib/com_err/lex.c                                     =
                        |    237 +-
 head/crypto/heimdal/lib/com_err/lex.h                                     =
                        |     54 +-
 head/crypto/heimdal/lib/com_err/lex.l                                     =
                        |     59 +-
 head/crypto/heimdal/lib/com_err/parse.c                                   =
                        |     89 +-
 head/crypto/heimdal/lib/com_err/parse.h                                   =
                        |      2 +-
 head/crypto/heimdal/lib/com_err/parse.y                                   =
                        |     63 +-
 head/crypto/heimdal/lib/com_err/roken_rename.h                            =
                        |     66 +-
 head/crypto/heimdal/lib/com_err/version-script.map                        =
                        |      2 +
 head/crypto/heimdal/lib/gssapi/ChangeLog                                  =
                        |    513 +-
 head/crypto/heimdal/lib/gssapi/Makefile.am                                =
                        |     99 +-
 head/crypto/heimdal/lib/gssapi/Makefile.in                                =
                        |   1484 +-
 head/crypto/heimdal/lib/gssapi/gss-commands.in                            =
                        |     17 +-
 head/crypto/heimdal/lib/gssapi/gss_acquire_cred.3                         =
                        |      6 +-
 head/crypto/heimdal/lib/gssapi/gssapi.3                                   =
                        |    153 +-
 head/crypto/heimdal/lib/gssapi/gssapi.h                                   =
                        |     52 +-
 head/crypto/heimdal/lib/gssapi/gssapi/gssapi.h                            =
                        |    555 +-
 head/crypto/heimdal/lib/gssapi/gssapi/gssapi_krb5.h                       =
                        |    177 +-
 head/crypto/heimdal/lib/gssapi/gssapi/gssapi_spnego.h                     =
                        |     63 +-
 head/crypto/heimdal/lib/gssapi/gssapi_mech.h                              =
                        |    309 +-
 head/crypto/heimdal/lib/gssapi/krb5/8003.c                                =
                        |    127 +-
 head/crypto/heimdal/lib/gssapi/krb5/accept_sec_context.c                  =
                        |    376 +-
 head/crypto/heimdal/lib/gssapi/krb5/acquire_cred.c                        =
                        |    310 +-
 head/crypto/heimdal/lib/gssapi/krb5/add_cred.c                            =
                        |    101 +-
 head/crypto/heimdal/lib/gssapi/krb5/address_to_krb5addr.c                 =
                        |     70 +-
 head/crypto/heimdal/lib/gssapi/krb5/arcfour.c                             =
                        |    190 +-
 head/crypto/heimdal/lib/gssapi/krb5/canonicalize_name.c                   =
                        |     72 +-
 head/crypto/heimdal/lib/gssapi/krb5/ccache_name.c                         =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/cfx.c                                 =
                        |   1249 +-
 head/crypto/heimdal/lib/gssapi/krb5/cfx.h                                 =
                        |      2 +-
 head/crypto/heimdal/lib/gssapi/krb5/compare_name.c                        =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/compat.c                              =
                        |     67 +-
 head/crypto/heimdal/lib/gssapi/krb5/context_time.c                        =
                        |     62 +-
 head/crypto/heimdal/lib/gssapi/krb5/copy_ccache.c                         =
                        |     70 +-
 head/crypto/heimdal/lib/gssapi/krb5/decapsulate.c                         =
                        |     66 +-
 head/crypto/heimdal/lib/gssapi/krb5/delete_sec_context.c                  =
                        |     61 +-
 head/crypto/heimdal/lib/gssapi/krb5/display_name.c                        =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/display_status.c                      =
                        |     97 +-
 head/crypto/heimdal/lib/gssapi/krb5/duplicate_name.c                      =
                        |     63 +-
 head/crypto/heimdal/lib/gssapi/krb5/encapsulate.c                         =
                        |     64 +-
 head/crypto/heimdal/lib/gssapi/krb5/export_name.c                         =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/export_sec_context.c                  =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/external.c                            =
                        |    424 +-
 head/crypto/heimdal/lib/gssapi/krb5/get_mic.c                             =
                        |    100 +-
 head/crypto/heimdal/lib/gssapi/krb5/gkrb5_err.et                          =
                        |      2 +-
 head/crypto/heimdal/lib/gssapi/krb5/gsskrb5-private.h                     =
                        |    297 +-
 head/crypto/heimdal/lib/gssapi/krb5/gsskrb5_locl.h                        =
                        |     80 +-
 head/crypto/heimdal/lib/gssapi/krb5/import_name.c                         =
                        |    142 +-
 head/crypto/heimdal/lib/gssapi/krb5/import_sec_context.c                  =
                        |     70 +-
 head/crypto/heimdal/lib/gssapi/krb5/indicate_mechs.c                      =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/init.c                                =
                        |     54 +-
 head/crypto/heimdal/lib/gssapi/krb5/init_sec_context.c                    =
                        |    740 +-
 head/crypto/heimdal/lib/gssapi/krb5/inquire_context.c                     =
                        |     58 +-
 head/crypto/heimdal/lib/gssapi/krb5/inquire_cred.c                        =
                        |     68 +-
 head/crypto/heimdal/lib/gssapi/krb5/inquire_cred_by_mech.c                =
                        |     60 +-
 head/crypto/heimdal/lib/gssapi/krb5/inquire_cred_by_oid.c                 =
                        |      6 +-
 head/crypto/heimdal/lib/gssapi/krb5/inquire_mechs_for_name.c              =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/inquire_names_for_mech.c              =
                        |     75 +-
 head/crypto/heimdal/lib/gssapi/krb5/inquire_sec_context_by_oid.c          =
                        |    106 +-
 head/crypto/heimdal/lib/gssapi/krb5/prf.c                                 =
                        |     93 +-
 head/crypto/heimdal/lib/gssapi/krb5/process_context_token.c               =
                        |     64 +-
 head/crypto/heimdal/lib/gssapi/krb5/release_buffer.c                      =
                        |     54 +-
 head/crypto/heimdal/lib/gssapi/krb5/release_cred.c                        =
                        |     62 +-
 head/crypto/heimdal/lib/gssapi/krb5/release_name.c                        =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/krb5/sequence.c                            =
                        |    102 +-
 head/crypto/heimdal/lib/gssapi/krb5/set_cred_option.c                     =
                        |     41 +-
 head/crypto/heimdal/lib/gssapi/krb5/set_sec_context_option.c              =
                        |     84 +-
 head/crypto/heimdal/lib/gssapi/krb5/test_cfx.c                            =
                        |     78 +-
 head/crypto/heimdal/lib/gssapi/krb5/ticket_flags.c                        =
                        |     54 +-
 head/crypto/heimdal/lib/gssapi/krb5/unwrap.c                              =
                        |    191 +-
 head/crypto/heimdal/lib/gssapi/krb5/verify_mic.c                          =
                        |    144 +-
 head/crypto/heimdal/lib/gssapi/krb5/wrap.c                                =
                        |    191 +-
 head/crypto/heimdal/lib/gssapi/ntlm/accept_sec_context.c                  =
                        |    102 +-
 head/crypto/heimdal/lib/gssapi/ntlm/acquire_cred.c                        =
                        |     77 +-
 head/crypto/heimdal/lib/gssapi/ntlm/add_cred.c                            =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/canonicalize_name.c                   =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/ntlm/compare_name.c                        =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/context_time.c                        =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/crypto.c                              =
                        |    135 +-
 head/crypto/heimdal/lib/gssapi/ntlm/delete_sec_context.c                  =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/display_name.c                        =
                        |     63 +-
 head/crypto/heimdal/lib/gssapi/ntlm/display_status.c                      =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/ntlm/duplicate_name.c                      =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/ntlm/export_name.c                         =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/ntlm/export_sec_context.c                  =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/external.c                            =
                        |    121 +-
 head/crypto/heimdal/lib/gssapi/ntlm/import_name.c                         =
                        |     84 +-
 head/crypto/heimdal/lib/gssapi/ntlm/import_sec_context.c                  =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/indicate_mechs.c                      =
                        |     54 +-
 head/crypto/heimdal/lib/gssapi/ntlm/init_sec_context.c                    =
                        |    187 +-
 head/crypto/heimdal/lib/gssapi/ntlm/inquire_context.c                     =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/ntlm/inquire_cred_by_mech.c                =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/ntlm/inquire_mechs_for_name.c              =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/ntlm/inquire_names_for_mech.c              =
                        |     58 +-
 head/crypto/heimdal/lib/gssapi/ntlm/ntlm-private.h                        =
                        |     74 +-
 head/crypto/heimdal/lib/gssapi/ntlm/ntlm.h                                =
                        |     66 +-
 head/crypto/heimdal/lib/gssapi/ntlm/process_context_token.c               =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/release_cred.c                        =
                        |     56 +-
 head/crypto/heimdal/lib/gssapi/ntlm/release_name.c                        =
                        |     57 +-
 head/crypto/heimdal/lib/gssapi/spnego/accept_sec_context.c                =
                        |    299 +-
 head/crypto/heimdal/lib/gssapi/spnego/compat.c                            =
                        |     31 +-
 head/crypto/heimdal/lib/gssapi/spnego/context_stubs.c                     =
                        |    374 +-
 head/crypto/heimdal/lib/gssapi/spnego/cred_stubs.c                        =
                        |    167 +-
 head/crypto/heimdal/lib/gssapi/spnego/external.c                          =
                        |    100 +-
 head/crypto/heimdal/lib/gssapi/spnego/init_sec_context.c                  =
                        |    165 +-
 head/crypto/heimdal/lib/gssapi/spnego/spnego-private.h                    =
                        |    183 +-
 head/crypto/heimdal/lib/gssapi/spnego/spnego.asn1                         =
                        |      1 +
 head/crypto/heimdal/lib/gssapi/spnego/spnego_locl.h                       =
                        |     20 +-
 head/crypto/heimdal/lib/gssapi/test_acquire_cred.c                        =
                        |    142 +-
 head/crypto/heimdal/lib/gssapi/test_common.c                              =
                        |     43 +-
 head/crypto/heimdal/lib/gssapi/test_common.h                              =
                        |     24 +-
 head/crypto/heimdal/lib/gssapi/test_context.c                             =
                        |    586 +-
 head/crypto/heimdal/lib/gssapi/test_cred.c                                =
                        |     43 +-
 head/crypto/heimdal/lib/gssapi/test_kcred.c                               =
                        |     38 +-
 head/crypto/heimdal/lib/gssapi/test_names.c                               =
                        |     41 +-
 head/crypto/heimdal/lib/gssapi/test_ntlm.c                                =
                        |     40 +-
 head/crypto/heimdal/lib/gssapi/test_oid.c                                 =
                        |     60 +-
 head/crypto/heimdal/lib/gssapi/version-script.map                         =
                        |    255 +-
 head/crypto/heimdal/lib/hdb/Makefile.am                                   =
                        |     63 +-
 head/crypto/heimdal/lib/hdb/Makefile.in                                   =
                        |    558 +-
 head/crypto/heimdal/lib/hdb/common.c                                      =
                        |    166 +-
 head/crypto/heimdal/lib/hdb/db.c                                          =
                        |    113 +-
 head/crypto/heimdal/lib/hdb/db3.c                                         =
                        |     97 +-
 head/crypto/heimdal/lib/hdb/dbinfo.c                                      =
                        |     74 +-
 head/crypto/heimdal/lib/hdb/ext.c                                         =
                        |    172 +-
 head/crypto/heimdal/lib/hdb/hdb-ldap.c                                    =
                        |    553 +-
 head/crypto/heimdal/lib/hdb/hdb-private.h                                 =
                        |      9 +-
 head/crypto/heimdal/lib/hdb/hdb-protos.h                                  =
                        |     22 +-
 head/crypto/heimdal/lib/hdb/hdb.asn1                                      =
                        |     17 +-
 head/crypto/heimdal/lib/hdb/hdb.c                                         =
                        |    211 +-
 head/crypto/heimdal/lib/hdb/hdb.h                                         =
                        |    297 +-
 head/crypto/heimdal/lib/hdb/hdb.schema                                    =
                        |      2 +-
 head/crypto/heimdal/lib/hdb/hdb_err.et                                    =
                        |      4 +-
 head/crypto/heimdal/lib/hdb/hdb_locl.h                                    =
                        |     53 +-
 head/crypto/heimdal/lib/hdb/keys.c                                        =
                        |    156 +-
 head/crypto/heimdal/lib/hdb/keytab.c                                      =
                        |    376 +-
 head/crypto/heimdal/lib/hdb/mkey.c                                        =
                        |    181 +-
 head/crypto/heimdal/lib/hdb/ndbm.c                                        =
                        |    204 +-
 head/crypto/heimdal/lib/hdb/print.c                                       =
                        |     61 +-
 head/crypto/heimdal/lib/hdb/test_dbinfo.c                                 =
                        |     70 +-
 head/crypto/heimdal/lib/hx509/ChangeLog                                   =
                        |    440 +-
 head/crypto/heimdal/lib/hx509/Makefile.am                                 =
                        |    104 +-
 head/crypto/heimdal/lib/hx509/Makefile.in                                 =
                        |    955 +-
 head/crypto/heimdal/lib/hx509/ca.c                                        =
                        |    273 +-
 head/crypto/heimdal/lib/hx509/cert.c                                      =
                        |   1036 +-
 head/crypto/heimdal/lib/hx509/cms.c                                       =
                        |    591 +-
 head/crypto/heimdal/lib/hx509/collector.c                                 =
                        |     83 +-
 head/crypto/heimdal/lib/hx509/crmf.asn1                                   =
                        |      1 +
 head/crypto/heimdal/lib/hx509/crypto.c                                    =
                        |   1757 +-
 head/crypto/heimdal/lib/hx509/doxygen.c                                   =
                        |     54 +-
 head/crypto/heimdal/lib/hx509/env.c                                       =
                        |    254 +-
 head/crypto/heimdal/lib/hx509/error.c                                     =
                        |     68 +-
 head/crypto/heimdal/lib/hx509/file.c                                      =
                        |    156 +-
 head/crypto/heimdal/lib/hx509/hx509-private.h                             =
                        |    146 +-
 head/crypto/heimdal/lib/hx509/hx509-protos.h                              =
                        |    220 +-
 head/crypto/heimdal/lib/hx509/hx509.h                                     =
                        |     96 +-
 head/crypto/heimdal/lib/hx509/hx509_err.et                                =
                        |      8 +-
 head/crypto/heimdal/lib/hx509/hx_locl.h                                   =
                        |     91 +-
 head/crypto/heimdal/lib/hx509/hxtool-commands.in                          =
                        |     71 +-
 head/crypto/heimdal/lib/hx509/hxtool.c                                    =
                        |    913 +-
 head/crypto/heimdal/lib/hx509/keyset.c                                    =
                        |    242 +-
 head/crypto/heimdal/lib/hx509/ks_dir.c                                    =
                        |     66 +-
 head/crypto/heimdal/lib/hx509/ks_file.c                                   =
                        |    281 +-
 head/crypto/heimdal/lib/hx509/ks_keychain.c                               =
                        |    152 +-
 head/crypto/heimdal/lib/hx509/ks_mem.c                                    =
                        |     71 +-
 head/crypto/heimdal/lib/hx509/ks_null.c                                   =
                        |     53 +-
 head/crypto/heimdal/lib/hx509/ks_p11.c                                    =
                        |    216 +-
 head/crypto/heimdal/lib/hx509/ks_p12.c                                    =
                        |    163 +-
 head/crypto/heimdal/lib/hx509/lock.c                                      =
                        |     73 +-
 head/crypto/heimdal/lib/hx509/name.c                                      =
                        |    486 +-
 head/crypto/heimdal/lib/hx509/ocsp.asn1                                   =
                        |      1 +
 head/crypto/heimdal/lib/hx509/peer.c                                      =
                        |     87 +-
 head/crypto/heimdal/lib/hx509/pkcs10.asn1                                 =
                        |      1 +
 head/crypto/heimdal/lib/hx509/print.c                                     =
                        |    263 +-
 head/crypto/heimdal/lib/hx509/req.c                                       =
                        |     93 +-
 head/crypto/heimdal/lib/hx509/revoke.c                                    =
                        |    238 +-
 head/crypto/heimdal/lib/hx509/softp11.c                                   =
                        |    278 +-
 head/crypto/heimdal/lib/hx509/test_ca.in                                  =
                        |      4 +-
 head/crypto/heimdal/lib/hx509/test_cert.in                                =
                        |     17 +-
 head/crypto/heimdal/lib/hx509/test_chain.in                               =
                        |     18 +-
 head/crypto/heimdal/lib/hx509/test_cms.in                                 =
                        |    141 +-
 head/crypto/heimdal/lib/hx509/test_crypto.in                              =
                        |     33 +-
 head/crypto/heimdal/lib/hx509/test_java_pkcs11.in                         =
                        |      2 +-
 head/crypto/heimdal/lib/hx509/test_name.c                                 =
                        |    310 +-
 head/crypto/heimdal/lib/hx509/test_nist.in                                =
                        |      6 +-
 head/crypto/heimdal/lib/hx509/test_nist2.in                               =
                        |     26 +-
 head/crypto/heimdal/lib/hx509/test_nist_cert.in                           =
                        |      4 +-
 head/crypto/heimdal/lib/hx509/test_nist_pkcs12.in                         =
                        |      4 +-
 head/crypto/heimdal/lib/hx509/test_pkcs11.in                              =
                        |      2 +-
 head/crypto/heimdal/lib/hx509/test_query.in                               =
                        |     63 +-
 head/crypto/heimdal/lib/hx509/test_req.in                                 =
                        |      4 +-
 head/crypto/heimdal/lib/hx509/test_soft_pkcs11.c                          =
                        |     68 +-
 head/crypto/heimdal/lib/hx509/test_windows.in                             =
                        |      4 +-
 head/crypto/heimdal/lib/hx509/tst-crypto-available2                       =
                        |      3 +-
 head/crypto/heimdal/lib/hx509/tst-crypto-select1                          =
                        |      2 +-
 head/crypto/heimdal/lib/hx509/tst-crypto-select2                          =
                        |      2 +-
 head/crypto/heimdal/lib/hx509/version-script.map                          =
                        |    107 +-
 head/crypto/heimdal/lib/kadm5/ChangeLog                                   =
                        |    200 +-
 head/crypto/heimdal/lib/kadm5/Makefile.am                                 =
                        |     21 +-
 head/crypto/heimdal/lib/kadm5/Makefile.in                                 =
                        |    665 +-
 head/crypto/heimdal/lib/kadm5/acl.c                                       =
                        |     58 +-
 head/crypto/heimdal/lib/kadm5/ad.c                                        =
                        |    195 +-
 head/crypto/heimdal/lib/kadm5/admin.h                                     =
                        |     70 +-
 head/crypto/heimdal/lib/kadm5/bump_pw_expire.c                            =
                        |     52 +-
 head/crypto/heimdal/lib/kadm5/check-cracklib.pl                           =
                        |     14 +-
 head/crypto/heimdal/lib/kadm5/chpass_c.c                                  =
                        |     72 +-
 head/crypto/heimdal/lib/kadm5/chpass_s.c                                  =
                        |    130 +-
 head/crypto/heimdal/lib/kadm5/client_glue.c                               =
                        |     52 +-
 head/crypto/heimdal/lib/kadm5/common_glue.c                               =
                        |     52 +-
 head/crypto/heimdal/lib/kadm5/context_s.c                                 =
                        |     88 +-
 head/crypto/heimdal/lib/kadm5/create_c.c                                  =
                        |     62 +-
 head/crypto/heimdal/lib/kadm5/create_s.c                                  =
                        |     99 +-
 head/crypto/heimdal/lib/kadm5/default_keys.c                              =
                        |     56 +-
 head/crypto/heimdal/lib/kadm5/delete_c.c                                  =
                        |     58 +-
 head/crypto/heimdal/lib/kadm5/delete_s.c                                  =
                        |     58 +-
 head/crypto/heimdal/lib/kadm5/destroy_c.c                                 =
                        |     54 +-
 head/crypto/heimdal/lib/kadm5/destroy_s.c                                 =
                        |     62 +-
 head/crypto/heimdal/lib/kadm5/ent_setup.c                                 =
                        |     79 +-
 head/crypto/heimdal/lib/kadm5/error.c                                     =
                        |     52 +-
 head/crypto/heimdal/lib/kadm5/flush.c                                     =
                        |     56 +-
 head/crypto/heimdal/lib/kadm5/flush_c.c                                   =
                        |     26 +-
 head/crypto/heimdal/lib/kadm5/flush_s.c                                   =
                        |     26 +-
 head/crypto/heimdal/lib/kadm5/free.c                                      =
                        |     64 +-
 head/crypto/heimdal/lib/kadm5/get_c.c                                     =
                        |     64 +-
 head/crypto/heimdal/lib/kadm5/get_princs_c.c                              =
                        |     58 +-
 head/crypto/heimdal/lib/kadm5/get_princs_s.c                              =
                        |     58 +-
 head/crypto/heimdal/lib/kadm5/get_s.c                                     =
                        |    136 +-
 head/crypto/heimdal/lib/kadm5/init_c.c                                    =
                        |    234 +-
 head/crypto/heimdal/lib/kadm5/init_s.c                                    =
                        |    130 +-
 head/crypto/heimdal/lib/kadm5/iprop-commands.in                           =
                        |      4 +-
 head/crypto/heimdal/lib/kadm5/iprop-log.8                                 =
                        |    137 +-
 head/crypto/heimdal/lib/kadm5/iprop-log.c                                 =
                        |     91 +-
 head/crypto/heimdal/lib/kadm5/iprop.8                                     =
                        |    200 +-
 head/crypto/heimdal/lib/kadm5/iprop.h                                     =
                        |     52 +-
 head/crypto/heimdal/lib/kadm5/ipropd_common.c                             =
                        |     54 +-
 head/crypto/heimdal/lib/kadm5/ipropd_master.c                             =
                        |    219 +-
 head/crypto/heimdal/lib/kadm5/ipropd_slave.c                              =
                        |    450 +-
 head/crypto/heimdal/lib/kadm5/kadm5-private.h                             =
                        |     20 +-
 head/crypto/heimdal/lib/kadm5/kadm5-pwcheck.h                             =
                        |     54 +-
 head/crypto/heimdal/lib/kadm5/kadm5_err.et                                =
                        |      2 +-
 head/crypto/heimdal/lib/kadm5/kadm5_locl.h                                =
                        |     56 +-
 head/crypto/heimdal/lib/kadm5/kadm5_pwcheck.3                             =
                        |     35 +-
 head/crypto/heimdal/lib/kadm5/keys.c                                      =
                        |    100 +-
 head/crypto/heimdal/lib/kadm5/log.c                                       =
                        |    211 +-
 head/crypto/heimdal/lib/kadm5/marshall.c                                  =
                        |     84 +-
 head/crypto/heimdal/lib/kadm5/modify_c.c                                  =
                        |     60 +-
 head/crypto/heimdal/lib/kadm5/modify_s.c                                  =
                        |     70 +-
 head/crypto/heimdal/lib/kadm5/password_quality.c                          =
                        |    146 +-
 head/crypto/heimdal/lib/kadm5/private.h                                   =
                        |     64 +-
 head/crypto/heimdal/lib/kadm5/privs_c.c                                   =
                        |     58 +-
 head/crypto/heimdal/lib/kadm5/privs_s.c                                   =
                        |     52 +-
 head/crypto/heimdal/lib/kadm5/randkey_c.c                                 =
                        |     62 +-
 head/crypto/heimdal/lib/kadm5/randkey_s.c                                 =
                        |     62 +-
 head/crypto/heimdal/lib/kadm5/rename_c.c                                  =
                        |     54 +-
 head/crypto/heimdal/lib/kadm5/rename_s.c                                  =
                        |     63 +-
 head/crypto/heimdal/lib/kadm5/sample_passwd_check.c                       =
                        |     24 +-
 head/crypto/heimdal/lib/kadm5/send_recv.c                                 =
                        |     70 +-
 head/crypto/heimdal/lib/kadm5/server_glue.c                               =
                        |     52 +-
 head/crypto/heimdal/lib/kadm5/set_keys.c                                  =
                        |     78 +-
 head/crypto/heimdal/lib/kadm5/set_modifier.c                              =
                        |     54 +-
 head/crypto/heimdal/lib/kadm5/test_pw_quality.c                           =
                        |     54 +-
 head/crypto/heimdal/lib/kafs/ChangeLog                                    =
                        |     84 +-
 head/crypto/heimdal/lib/kafs/Makefile.am                                  =
                        |     26 +-
 head/crypto/heimdal/lib/kafs/Makefile.in                                  =
                        |    427 +-
 head/crypto/heimdal/lib/kafs/afskrb5.c                                    =
                        |     87 +-
 head/crypto/heimdal/lib/kafs/afslib.c                                     =
                        |     18 +-
 head/crypto/heimdal/lib/kafs/afssys.c                                     =
                        |     58 +-
 head/crypto/heimdal/lib/kafs/afssysdefs.h                                 =
                        |     14 +-
 head/crypto/heimdal/lib/kafs/common.c                                     =
                        |    141 +-
 head/crypto/heimdal/lib/kafs/kafs.3                                       =
                        |     68 +-
 head/crypto/heimdal/lib/kafs/kafs.h                                       =
                        |     22 +-
 head/crypto/heimdal/lib/kafs/kafs_locl.h                                  =
                        |     24 +-
 head/crypto/heimdal/lib/kafs/roken_rename.h                               =
                        |     58 +-
 head/crypto/heimdal/lib/krb5/Makefile.am                                  =
                        |    154 +-
 head/crypto/heimdal/lib/krb5/Makefile.in                                  =
                        |   2278 +-
 head/crypto/heimdal/lib/krb5/acache.c                                     =
                        |    447 +-
 head/crypto/heimdal/lib/krb5/acl.c                                        =
                        |     42 +-
 head/crypto/heimdal/lib/krb5/add_et_list.c                                =
                        |     64 +-
 head/crypto/heimdal/lib/krb5/addr_families.c                              =
                        |    398 +-
 head/crypto/heimdal/lib/krb5/aes-test.c                                   =
                        |    788 +-
 head/crypto/heimdal/lib/krb5/aname_to_localname.c                         =
                        |     58 +-
 head/crypto/heimdal/lib/krb5/appdefault.c                                 =
                        |    130 +-
 head/crypto/heimdal/lib/krb5/asn1_glue.c                                  =
                        |     72 +-
 head/crypto/heimdal/lib/krb5/auth_context.c                               =
                        |    165 +-
 head/crypto/heimdal/lib/krb5/build_ap_req.c                               =
                        |     60 +-
 head/crypto/heimdal/lib/krb5/build_auth.c                                 =
                        |    170 +-
 head/crypto/heimdal/lib/krb5/cache.c                                      =
                        |   1254 +-
 head/crypto/heimdal/lib/krb5/changepw.c                                   =
                        |    285 +-
 head/crypto/heimdal/lib/krb5/codec.c                                      =
                        |    102 +-
 head/crypto/heimdal/lib/krb5/config_file.c                                =
                        |    866 +-
 head/crypto/heimdal/lib/krb5/constants.c                                  =
                        |     82 +-
 head/crypto/heimdal/lib/krb5/context.c                                    =
                        |    871 +-
 head/crypto/heimdal/lib/krb5/convert_creds.c                              =
                        |    193 +-
 head/crypto/heimdal/lib/krb5/copy_host_realm.c                            =
                        |     71 +-
 head/crypto/heimdal/lib/krb5/crc.c                                        =
                        |     56 +-
 head/crypto/heimdal/lib/krb5/creds.c                                      =
                        |    128 +-
 head/crypto/heimdal/lib/krb5/crypto.c                                     =
                        |   4353 +-
 head/crypto/heimdal/lib/krb5/data.c                                       =
                        |    130 +-
 head/crypto/heimdal/lib/krb5/derived-key-test.c                           =
                        |     26 +-
 head/crypto/heimdal/lib/krb5/digest.c                                     =
                        |    422 +-
 head/crypto/heimdal/lib/krb5/doxygen.c                                    =
                        |    697 +-
 head/crypto/heimdal/lib/krb5/eai_to_heim_errno.c                          =
                        |     64 +-
 head/crypto/heimdal/lib/krb5/error_string.c                               =
                        |    329 +-
 head/crypto/heimdal/lib/krb5/expand_hostname.c                            =
                        |     97 +-
 head/crypto/heimdal/lib/krb5/fcache.c                                     =
                        |    593 +-
 head/crypto/heimdal/lib/krb5/free.c                                       =
                        |     56 +-
 head/crypto/heimdal/lib/krb5/free_host_realm.c                            =
                        |     63 +-
 head/crypto/heimdal/lib/krb5/generate_seq_number.c                        =
                        |     80 +-
 head/crypto/heimdal/lib/krb5/generate_subkey.c                            =
                        |     77 +-
 head/crypto/heimdal/lib/krb5/get_addrs.c                                  =
                        |    132 +-
 head/crypto/heimdal/lib/krb5/get_cred.c                                   =
                        |   1067 +-
 head/crypto/heimdal/lib/krb5/get_default_principal.c                      =
                        |    116 +-
 head/crypto/heimdal/lib/krb5/get_default_realm.c                          =
                        |     61 +-
 head/crypto/heimdal/lib/krb5/get_for_creds.c                              =
                        |    121 +-
 head/crypto/heimdal/lib/krb5/get_host_realm.c                             =
                        |     99 +-
 head/crypto/heimdal/lib/krb5/get_in_tkt.c                                 =
                        |    456 +-
 head/crypto/heimdal/lib/krb5/get_port.c                                   =
                        |     58 +-
 head/crypto/heimdal/lib/krb5/heim_err.et                                  =
                        |      5 +-
 head/crypto/heimdal/lib/krb5/init_creds.c                                 =
                        |    270 +-
 head/crypto/heimdal/lib/krb5/init_creds_pw.c                              =
                        |   1696 +-
 head/crypto/heimdal/lib/krb5/k524_err.et                                  =
                        |      2 +-
 head/crypto/heimdal/lib/krb5/kcm.c                                        =
                        |    825 +-
 head/crypto/heimdal/lib/krb5/kcm.h                                        =
                        |     29 +-
 head/crypto/heimdal/lib/krb5/kerberos.8                                   =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/keyblock.c                                   =
                        |    157 +-
 head/crypto/heimdal/lib/krb5/keytab.c                                     =
                        |    677 +-
 head/crypto/heimdal/lib/krb5/keytab_any.c                                 =
                        |    106 +-
 head/crypto/heimdal/lib/krb5/keytab_file.c                                =
                        |    342 +-
 head/crypto/heimdal/lib/krb5/keytab_keyfile.c                             =
                        |    216 +-
 head/crypto/heimdal/lib/krb5/keytab_memory.c                              =
                        |    110 +-
 head/crypto/heimdal/lib/krb5/krb5-private.h                               =
                        |    508 +-
 head/crypto/heimdal/lib/krb5/krb5-protos.h                                =
                        |   2207 +-
 head/crypto/heimdal/lib/krb5/krb5-v4compat.h                              =
                        |     75 +-
 head/crypto/heimdal/lib/krb5/krb5.conf.5                                  =
                        |     59 +-
 head/crypto/heimdal/lib/krb5/krb5.h                                       =
                        |    452 +-
 head/crypto/heimdal/lib/krb5/krb5.moduli                                  =
                        |      2 +-
 head/crypto/heimdal/lib/krb5/krb524_convert_creds_kdc.3                   =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_425_conv_principal.3                    =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_acl_match_file.3                        =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_aname_to_localname.3                    =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_appdefault.3                            =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_auth_context.3                          =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_c_make_checksum.3                       =
                        |     20 +-
 head/crypto/heimdal/lib/krb5/krb5_ccapi.h                                 =
                        |     75 +-
 head/crypto/heimdal/lib/krb5/krb5_check_transited.3                       =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_create_checksum.3                       =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_creds.3                                 =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_digest.3                                =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_eai_to_heim_errno.3                     =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_encrypt.3                               =
                        |     10 +-
 head/crypto/heimdal/lib/krb5/krb5_err.et                                  =
                        |     14 +-
 head/crypto/heimdal/lib/krb5/krb5_find_padata.3                           =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_generate_random_block.3                 =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_get_all_client_addrs.3                  =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_get_credentials.3                       =
                        |     35 +-
 head/crypto/heimdal/lib/krb5/krb5_get_creds.3                             =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_get_forwarded_creds.3                   =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_get_in_cred.3                           =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_get_init_creds.3                        =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_get_krbhst.3                            =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_getportbyname.3                         =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_init_context.3                          =
                        |     14 +-
 head/crypto/heimdal/lib/krb5/krb5_is_thread_safe.3                        =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_krbhst_init.3                           =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_locl.h                                  =
                        |    165 +-
 head/crypto/heimdal/lib/krb5/krb5_mk_req.3                                =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_mk_safe.3                               =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_openlog.3                               =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_parse_name.3                            =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_principal.3                             =
                        |     24 +-
 head/crypto/heimdal/lib/krb5/krb5_rcache.3                                =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_rd_error.3                              =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_rd_safe.3                               =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_set_default_realm.3                     =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_set_password.3                          =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_string_to_key.3                         =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_timeofday.3                             =
                        |      6 +-
 head/crypto/heimdal/lib/krb5/krb5_verify_init_creds.3                     =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krb5_verify_user.3                           =
                        |      4 +-
 head/crypto/heimdal/lib/krb5/krbhst-test.c                                =
                        |     58 +-
 head/crypto/heimdal/lib/krb5/krbhst.c                                     =
                        |    355 +-
 head/crypto/heimdal/lib/krb5/kuserok.c                                    =
                        |    135 +-
 head/crypto/heimdal/lib/krb5/locate_plugin.h                              =
                        |     58 +-
 head/crypto/heimdal/lib/krb5/log.c                                        =
                        |    165 +-
 head/crypto/heimdal/lib/krb5/mcache.c                                     =
                        |    193 +-
 head/crypto/heimdal/lib/krb5/misc.c                                       =
                        |    114 +-
 head/crypto/heimdal/lib/krb5/mit_glue.c                                   =
                        |    221 +-
 head/crypto/heimdal/lib/krb5/mk_error.c                                   =
                        |     64 +-
 head/crypto/heimdal/lib/krb5/mk_priv.c                                    =
                        |     70 +-
 head/crypto/heimdal/lib/krb5/mk_rep.c                                     =
                        |     72 +-
 head/crypto/heimdal/lib/krb5/mk_req.c                                     =
                        |     60 +-
 head/crypto/heimdal/lib/krb5/mk_req_ext.c                                 =
                        |     77 +-
 head/crypto/heimdal/lib/krb5/mk_safe.c                                    =
                        |     68 +-
 head/crypto/heimdal/lib/krb5/n-fold-test.c                                =
                        |     24 +-
 head/crypto/heimdal/lib/krb5/n-fold.c                                     =
                        |     54 +-
 head/crypto/heimdal/lib/krb5/net_read.c                                   =
                        |     59 +-
 head/crypto/heimdal/lib/krb5/net_write.c                                  =
                        |     97 +-
 head/crypto/heimdal/lib/krb5/pac.c                                        =
                        |    566 +-
 head/crypto/heimdal/lib/krb5/padata.c                                     =
                        |     67 +-
 head/crypto/heimdal/lib/krb5/parse-name-test.c                            =
                        |     26 +-
 head/crypto/heimdal/lib/krb5/pkinit.c                                     =
                        |   1739 +-
 head/crypto/heimdal/lib/krb5/plugin.c                                     =
                        |    641 +-
 head/crypto/heimdal/lib/krb5/principal.c                                  =
                        |   1110 +-
 head/crypto/heimdal/lib/krb5/prog_setup.c                                 =
                        |     62 +-
 head/crypto/heimdal/lib/krb5/prompter_posix.c                             =
                        |     54 +-
 head/crypto/heimdal/lib/krb5/rd_cred.c                                    =
                        |    138 +-
 head/crypto/heimdal/lib/krb5/rd_error.c                                   =
                        |    104 +-
 head/crypto/heimdal/lib/krb5/rd_priv.c                                    =
                        |     99 +-
 head/crypto/heimdal/lib/krb5/rd_rep.c                                     =
                        |     89 +-
 head/crypto/heimdal/lib/krb5/rd_req.c                                     =
                        |    509 +-
 head/crypto/heimdal/lib/krb5/rd_safe.c                                    =
                        |    104 +-
 head/crypto/heimdal/lib/krb5/read_message.c                               =
                        |     66 +-
 head/crypto/heimdal/lib/krb5/recvauth.c                                   =
                        |     93 +-
 head/crypto/heimdal/lib/krb5/replay.c                                     =
                        |    168 +-
 head/crypto/heimdal/lib/krb5/send_to_kdc.c                                =
                        |    227 +-
 head/crypto/heimdal/lib/krb5/sendauth.c                                   =
                        |     71 +-
 head/crypto/heimdal/lib/krb5/set_default_realm.c                          =
                        |     64 +-
 head/crypto/heimdal/lib/krb5/sock_principal.c                             =
                        |     62 +-
 head/crypto/heimdal/lib/krb5/store-int.h                                  =
                        |     52 +-
 head/crypto/heimdal/lib/krb5/store-test.c                                 =
                        |     35 +-
 head/crypto/heimdal/lib/krb5/store.c                                      =
                        |    818 +-
 head/crypto/heimdal/lib/krb5/store_emem.c                                 =
                        |    122 +-
 head/crypto/heimdal/lib/krb5/store_fd.c                                   =
                        |     47 +-
 head/crypto/heimdal/lib/krb5/store_mem.c                                  =
                        |    125 +-
 head/crypto/heimdal/lib/krb5/string-to-key-test.c                         =
                        |     50 +-
 head/crypto/heimdal/lib/krb5/test_acl.c                                   =
                        |     31 +-
 head/crypto/heimdal/lib/krb5/test_addr.c                                  =
                        |     97 +-
 head/crypto/heimdal/lib/krb5/test_alname.c                                =
                        |     40 +-
 head/crypto/heimdal/lib/krb5/test_cc.c                                    =
                        |    348 +-
 head/crypto/heimdal/lib/krb5/test_config.c                                =
                        |    174 +-
 head/crypto/heimdal/lib/krb5/test_crypto.c                                =
                        |     39 +-
 head/crypto/heimdal/lib/krb5/test_crypto_wrapping.c                       =
                        |     32 +-
 head/crypto/heimdal/lib/krb5/test_forward.c                               =
                        |     30 +-
 head/crypto/heimdal/lib/krb5/test_get_addrs.c                             =
                        |     31 +-
 head/crypto/heimdal/lib/krb5/test_hostname.c                              =
                        |     26 +-
 head/crypto/heimdal/lib/krb5/test_keytab.c                                =
                        |    134 +-
 head/crypto/heimdal/lib/krb5/test_kuserok.c                               =
                        |     28 +-
 head/crypto/heimdal/lib/krb5/test_mem.c                                   =
                        |     28 +-
 head/crypto/heimdal/lib/krb5/test_pac.c                                   =
                        |    174 +-
 head/crypto/heimdal/lib/krb5/test_pkinit_dh2key.c                         =
                        |     30 +-
 head/crypto/heimdal/lib/krb5/test_plugin.c                                =
                        |     58 +-
 head/crypto/heimdal/lib/krb5/test_prf.c                                   =
                        |     28 +-
 head/crypto/heimdal/lib/krb5/test_princ.c                                 =
                        |     57 +-
 head/crypto/heimdal/lib/krb5/test_renew.c                                 =
                        |     31 +-
 head/crypto/heimdal/lib/krb5/test_store.c                                 =
                        |    133 +-
 head/crypto/heimdal/lib/krb5/test_time.c                                  =
                        |     26 +-
 head/crypto/heimdal/lib/krb5/ticket.c                                     =
                        |    692 +-
 head/crypto/heimdal/lib/krb5/time.c                                       =
                        |     95 +-
 head/crypto/heimdal/lib/krb5/transited.c                                  =
                        |    219 +-
 head/crypto/heimdal/lib/krb5/verify_init.c                                =
                        |    112 +-
 head/crypto/heimdal/lib/krb5/verify_krb5_conf.8                           =
                        |      8 +-
 head/crypto/heimdal/lib/krb5/verify_krb5_conf.c                           =
                        |    107 +-
 head/crypto/heimdal/lib/krb5/verify_user.c                                =
                        |    115 +-
 head/crypto/heimdal/lib/krb5/version-script.map                           =
                        |    110 +-
 head/crypto/heimdal/lib/krb5/version.c                                    =
                        |     54 +-
 head/crypto/heimdal/lib/krb5/warn.c                                       =
                        |    262 +-
 head/crypto/heimdal/lib/krb5/write_message.c                              =
                        |     60 +-
 head/crypto/heimdal/lib/ntlm/ChangeLog                                    =
                        |     38 +-
 head/crypto/heimdal/lib/ntlm/Makefile.am                                  =
                        |     32 +-
 head/crypto/heimdal/lib/ntlm/Makefile.in                                  =
                        |    425 +-
 head/crypto/heimdal/lib/ntlm/heimntlm-protos.h                            =
                        |     71 +-
 head/crypto/heimdal/lib/ntlm/heimntlm.h                                   =
                        |     93 +-
 head/crypto/heimdal/lib/ntlm/ntlm.c                                       =
                        |    907 +-
 head/crypto/heimdal/lib/ntlm/test_ntlm.c                                  =
                        |    115 +-
 head/crypto/heimdal/lib/ntlm/version-script.map                           =
                        |      5 +-
 head/crypto/heimdal/lib/roken/ChangeLog                                   =
                        |    219 +-
 head/crypto/heimdal/lib/roken/Makefile.am                                 =
                        |     75 +-
 head/crypto/heimdal/lib/roken/Makefile.in                                 =
                        |   1225 +-
 head/crypto/heimdal/lib/roken/base64-test.c                               =
                        |     21 +-
 head/crypto/heimdal/lib/roken/base64.c                                    =
                        |     28 +-
 head/crypto/heimdal/lib/roken/base64.h                                    =
                        |     22 +-
 head/crypto/heimdal/lib/roken/bswap.c                                     =
                        |     20 +-
 head/crypto/heimdal/lib/roken/chown.c                                     =
                        |     17 +-
 head/crypto/heimdal/lib/roken/closefrom.c                                 =
                        |     55 +-
 head/crypto/heimdal/lib/roken/concat.c                                    =
                        |     28 +-
 head/crypto/heimdal/lib/roken/copyhostent.c                               =
                        |     17 +-
 head/crypto/heimdal/lib/roken/daemon.c                                    =
                        |      6 +-
 head/crypto/heimdal/lib/roken/dumpdata.c                                  =
                        |     61 +-
 head/crypto/heimdal/lib/roken/ecalloc.3                                   =
                        |     58 +-
 head/crypto/heimdal/lib/roken/ecalloc.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/emalloc.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/environment.c                               =
                        |     27 +-
 head/crypto/heimdal/lib/roken/eread.c                                     =
                        |     20 +-
 head/crypto/heimdal/lib/roken/erealloc.c                                  =
                        |     17 +-
 head/crypto/heimdal/lib/roken/err.c                                       =
                        |     19 +-
 head/crypto/heimdal/lib/roken/err.hin                                     =
                        |     24 +-
 head/crypto/heimdal/lib/roken/errx.c                                      =
                        |     19 +-
 head/crypto/heimdal/lib/roken/esetenv.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/estrdup.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/ewrite.c                                    =
                        |     20 +-
 head/crypto/heimdal/lib/roken/fchown.c                                    =
                        |     17 +-
 head/crypto/heimdal/lib/roken/flock.c                                     =
                        |     93 +-
 head/crypto/heimdal/lib/roken/fnmatch.c                                   =
                        |     12 +-
 head/crypto/heimdal/lib/roken/fnmatch.hin                                 =
                        |      4 +-
 head/crypto/heimdal/lib/roken/freeaddrinfo.c                              =
                        |     17 +-
 head/crypto/heimdal/lib/roken/freehostent.c                               =
                        |     17 +-
 head/crypto/heimdal/lib/roken/gai_strerror.c                              =
                        |     17 +-
 head/crypto/heimdal/lib/roken/get_default_username.c                      =
                        |     61 +-
 head/crypto/heimdal/lib/roken/get_window_size.c                           =
                        |     98 +-
 head/crypto/heimdal/lib/roken/getaddrinfo-test.c                          =
                        |     57 +-
 head/crypto/heimdal/lib/roken/getaddrinfo.c                               =
                        |     17 +-
 head/crypto/heimdal/lib/roken/getaddrinfo_hostspec.c                      =
                        |     35 +-
 head/crypto/heimdal/lib/roken/getarg.3                                    =
                        |     70 +-
 head/crypto/heimdal/lib/roken/getarg.c                                    =
                        |    186 +-
 head/crypto/heimdal/lib/roken/getarg.h                                    =
                        |     80 +-
 head/crypto/heimdal/lib/roken/getcap.c                                    =
                        |    107 +-
 head/crypto/heimdal/lib/roken/getcwd.c                                    =
                        |     17 +-
 head/crypto/heimdal/lib/roken/getdtablesize.c                             =
                        |     23 +-
 head/crypto/heimdal/lib/roken/getegid.c                                   =
                        |     19 +-
 head/crypto/heimdal/lib/roken/geteuid.c                                   =
                        |     19 +-
 head/crypto/heimdal/lib/roken/getgid.c                                    =
                        |     18 +-
 head/crypto/heimdal/lib/roken/gethostname.c                               =
                        |     16 +-
 head/crypto/heimdal/lib/roken/getifaddrs.c                                =
                        |    171 +-
 head/crypto/heimdal/lib/roken/getipnodebyaddr.c                           =
                        |     17 +-
 head/crypto/heimdal/lib/roken/getipnodebyname.c                           =
                        |     17 +-
 head/crypto/heimdal/lib/roken/getnameinfo.c                               =
                        |     17 +-
 head/crypto/heimdal/lib/roken/getnameinfo_verified.c                      =
                        |     26 +-
 head/crypto/heimdal/lib/roken/getopt.c                                    =
                        |     20 +-
 head/crypto/heimdal/lib/roken/getprogname.c                               =
                        |     19 +-
 head/crypto/heimdal/lib/roken/gettimeofday.c                              =
                        |     45 +-
 head/crypto/heimdal/lib/roken/getuid.c                                    =
                        |     18 +-
 head/crypto/heimdal/lib/roken/getusershell.c                              =
                        |     10 +-
 head/crypto/heimdal/lib/roken/glob.c                                      =
                        |     62 +-
 head/crypto/heimdal/lib/roken/glob.hin                                    =
                        |      4 +-
 head/crypto/heimdal/lib/roken/h_errno.c                                   =
                        |     15 +-
 head/crypto/heimdal/lib/roken/hex-test.c                                  =
                        |     18 +-
 head/crypto/heimdal/lib/roken/hex.c                                       =
                        |     29 +-
 head/crypto/heimdal/lib/roken/hex.h                                       =
                        |     22 +-
 head/crypto/heimdal/lib/roken/hostent_find_fqdn.c                         =
                        |     17 +-
 head/crypto/heimdal/lib/roken/hstrerror.c                                 =
                        |     17 +-
 head/crypto/heimdal/lib/roken/ifaddrs.hin                                 =
                        |      8 +-
 head/crypto/heimdal/lib/roken/inet_aton.c                                 =
                        |     17 +-
 head/crypto/heimdal/lib/roken/inet_ntop.c                                 =
                        |     38 +-
 head/crypto/heimdal/lib/roken/inet_pton.c                                 =
                        |     87 +-
 head/crypto/heimdal/lib/roken/initgroups.c                                =
                        |     17 +-
 head/crypto/heimdal/lib/roken/innetgr.c                                   =
                        |     30 +-
 head/crypto/heimdal/lib/roken/iruserok.c                                  =
                        |      5 +-
 head/crypto/heimdal/lib/roken/issuid.c                                    =
                        |     55 +-
 head/crypto/heimdal/lib/roken/k_getpwnam.c                                =
                        |     17 +-
 head/crypto/heimdal/lib/roken/k_getpwuid.c                                =
                        |     17 +-
 head/crypto/heimdal/lib/roken/localtime_r.c                               =
                        |     25 +-
 head/crypto/heimdal/lib/roken/lstat.c                                     =
                        |     17 +-
 head/crypto/heimdal/lib/roken/memmove.c                                   =
                        |     21 +-
 head/crypto/heimdal/lib/roken/mini_inetd.c                                =
                        |    135 +-
 head/crypto/heimdal/lib/roken/mkstemp.c                                   =
                        |     20 +-
 head/crypto/heimdal/lib/roken/ndbm_wrap.c                                 =
                        |     56 +-
 head/crypto/heimdal/lib/roken/ndbm_wrap.h                                 =
                        |     36 +-
 head/crypto/heimdal/lib/roken/net_read.c                                  =
                        |     82 +-
 head/crypto/heimdal/lib/roken/net_write.c                                 =
                        |     71 +-
 head/crypto/heimdal/lib/roken/parse_bytes-test.c                          =
                        |     55 +-
 head/crypto/heimdal/lib/roken/parse_bytes.c                               =
                        |     59 +-
 head/crypto/heimdal/lib/roken/parse_bytes.h                               =
                        |     62 +-
 head/crypto/heimdal/lib/roken/parse_reply-test.c                          =
                        |     53 +-
 head/crypto/heimdal/lib/roken/parse_time-test.c                           =
                        |     71 +-
 head/crypto/heimdal/lib/roken/parse_time.3                                =
                        |     74 +-
 head/crypto/heimdal/lib/roken/parse_time.c                                =
                        |     61 +-
 head/crypto/heimdal/lib/roken/parse_time.h                                =
                        |     64 +-
 head/crypto/heimdal/lib/roken/parse_units.c                               =
                        |     77 +-
 head/crypto/heimdal/lib/roken/parse_units.h                               =
                        |     70 +-
 head/crypto/heimdal/lib/roken/putenv.c                                    =
                        |     21 +-
 head/crypto/heimdal/lib/roken/rcmd.c                                      =
                        |     17 +-
 head/crypto/heimdal/lib/roken/readv.c                                     =
                        |     17 +-
 head/crypto/heimdal/lib/roken/realloc.c                                   =
                        |     20 +-
 head/crypto/heimdal/lib/roken/recvmsg.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/resolve-test.c                              =
                        |    192 +-
 head/crypto/heimdal/lib/roken/resolve.c                                   =
                        |    473 +-
 head/crypto/heimdal/lib/roken/resolve.h                                   =
                        |    165 +-
 head/crypto/heimdal/lib/roken/roken-common.h                              =
                        |    221 +-
 head/crypto/heimdal/lib/roken/roken.awk                                   =
                        |     11 +-
 head/crypto/heimdal/lib/roken/roken.h.in                                  =
                        |    718 +-
 head/crypto/heimdal/lib/roken/roken_gethostby.c                           =
                        |     91 +-
 head/crypto/heimdal/lib/roken/rtbl.3                                      =
                        |      6 +-
 head/crypto/heimdal/lib/roken/rtbl.c                                      =
                        |     64 +-
 head/crypto/heimdal/lib/roken/rtbl.h                                      =
                        |     50 +-
 head/crypto/heimdal/lib/roken/sendmsg.c                                   =
                        |    105 +-
 head/crypto/heimdal/lib/roken/setegid.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/setenv.c                                    =
                        |     36 +-
 head/crypto/heimdal/lib/roken/seteuid.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/setprogname.c                               =
                        |     52 +-
 head/crypto/heimdal/lib/roken/signal.c                                    =
                        |     17 +-
 head/crypto/heimdal/lib/roken/simple_exec.c                               =
                        |    124 +-
 head/crypto/heimdal/lib/roken/snprintf-test.c                             =
                        |     33 +-
 head/crypto/heimdal/lib/roken/snprintf.c                                  =
                        |     78 +-
 head/crypto/heimdal/lib/roken/socket.c                                    =
                        |    152 +-
 head/crypto/heimdal/lib/roken/socket_wrapper.c                            =
                        |     96 +-
 head/crypto/heimdal/lib/roken/socket_wrapper.h                            =
                        |     10 +-
 head/crypto/heimdal/lib/roken/strcasecmp.c                                =
                        |     55 +-
 head/crypto/heimdal/lib/roken/strcollect.c                                =
                        |     57 +-
 head/crypto/heimdal/lib/roken/strdup.c                                    =
                        |     17 +-
 head/crypto/heimdal/lib/roken/strerror.c                                  =
                        |     17 +-
 head/crypto/heimdal/lib/roken/strftime.c                                  =
                        |     40 +-
 head/crypto/heimdal/lib/roken/strlcat.c                                   =
                        |     30 +-
 head/crypto/heimdal/lib/roken/strlcpy.c                                   =
                        |     25 +-
 head/crypto/heimdal/lib/roken/strlwr.c                                    =
                        |     17 +-
 head/crypto/heimdal/lib/roken/strncasecmp.c                               =
                        |     57 +-
 head/crypto/heimdal/lib/roken/strndup.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/strnlen.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/strpftime-test.c                            =
                        |     28 +-
 head/crypto/heimdal/lib/roken/strpftime-test.h                            =
                        |     29 +-
 head/crypto/heimdal/lib/roken/strpool.c                                   =
                        |     64 +-
 head/crypto/heimdal/lib/roken/strptime.c                                  =
                        |     32 +-
 head/crypto/heimdal/lib/roken/strsep.c                                    =
                        |     55 +-
 head/crypto/heimdal/lib/roken/strsep_copy.c                               =
                        |     57 +-
 head/crypto/heimdal/lib/roken/strtok_r.c                                  =
                        |     17 +-
 head/crypto/heimdal/lib/roken/strupr.c                                    =
                        |     17 +-
 head/crypto/heimdal/lib/roken/swab.c                                      =
                        |     18 +-
 head/crypto/heimdal/lib/roken/test-mem.c                                  =
                        |     93 +-
 head/crypto/heimdal/lib/roken/test-mem.h                                  =
                        |     54 +-
 head/crypto/heimdal/lib/roken/test-readenv.c                              =
                        |     57 +-
 head/crypto/heimdal/lib/roken/timegm.c                                    =
                        |     65 +-
 head/crypto/heimdal/lib/roken/timeval.c                                   =
                        |     25 +-
 head/crypto/heimdal/lib/roken/tm2time.c                                   =
                        |     17 +-
 head/crypto/heimdal/lib/roken/unsetenv.c                                  =
                        |     21 +-
 head/crypto/heimdal/lib/roken/unvis.c                                     =
                        |     45 +-
 head/crypto/heimdal/lib/roken/verify.c                                    =
                        |     19 +-
 head/crypto/heimdal/lib/roken/verr.c                                      =
                        |     21 +-
 head/crypto/heimdal/lib/roken/verrx.c                                     =
                        |     21 +-
 head/crypto/heimdal/lib/roken/vis.c                                       =
                        |    395 +-
 head/crypto/heimdal/lib/roken/vis.hin                                     =
                        |     74 +-
 head/crypto/heimdal/lib/roken/vsyslog.c                                   =
                        |     22 +-
 head/crypto/heimdal/lib/roken/vwarn.c                                     =
                        |     21 +-
 head/crypto/heimdal/lib/roken/vwarnx.c                                    =
                        |     21 +-
 head/crypto/heimdal/lib/roken/warn.c                                      =
                        |     17 +-
 head/crypto/heimdal/lib/roken/warnerr.c                                   =
                        |     21 +-
 head/crypto/heimdal/lib/roken/warnx.c                                     =
                        |     19 +-
 head/crypto/heimdal/lib/roken/write_pid.c                                 =
                        |     69 +-
 head/crypto/heimdal/lib/roken/writev.c                                    =
                        |     17 +-
 head/crypto/heimdal/lib/roken/xdbm.h                                      =
                        |     14 +-
 head/crypto/heimdal/lib/sl/ChangeLog                                      =
                        |     44 +-
 head/crypto/heimdal/lib/sl/Makefile.am                                    =
                        |     28 +-
 head/crypto/heimdal/lib/sl/Makefile.in                                    =
                        |    568 +-
 head/crypto/heimdal/lib/sl/roken_rename.h                                 =
                        |     70 +-
 head/crypto/heimdal/lib/sl/sl.c                                           =
                        |     35 +-
 head/crypto/heimdal/lib/sl/sl.h                                           =
                        |     20 +-
 head/crypto/heimdal/lib/sl/sl_locl.h                                      =
                        |     16 +-
 head/crypto/heimdal/lib/sl/slc-gram.c                                     =
                        |    163 +-
 head/crypto/heimdal/lib/sl/slc-gram.h                                     =
                        |      2 +-
 head/crypto/heimdal/lib/sl/slc-gram.y                                     =
                        |    143 +-
 head/crypto/heimdal/lib/sl/slc-lex.c                                      =
                        |    226 +-
 head/crypto/heimdal/lib/sl/slc-lex.l                                      =
                        |     68 +-
 head/crypto/heimdal/lib/sl/slc.h                                          =
                        |     52 +-
 head/crypto/heimdal/lib/sl/test_sl.c                                      =
                        |     26 +-
 head/crypto/heimdal/lib/vers/ChangeLog                                    =
                        |     16 +-
 head/crypto/heimdal/lib/vers/Makefile.am                                  =
                        |     25 +-
 head/crypto/heimdal/lib/vers/Makefile.in                                  =
                        |    268 +-
 head/crypto/heimdal/lib/vers/print_version.c                              =
                        |     71 +-
 head/crypto/heimdal/lib/vers/vers.h                                       =
                        |     14 +-
 head/crypto/heimdal/ltmain.sh                                             =
                        |  10743 +-
 head/crypto/heimdal/missing                                               =
                        |     49 +-
 head/crypto/heimdal/tools/Makefile.am                                     =
                        |      5 +-
 head/crypto/heimdal/tools/Makefile.in                                     =
                        |    328 +-
 head/crypto/heimdal/tools/heimdal-gssapi.pc.in                            =
                        |      4 +-
 head/crypto/heimdal/tools/kdc-log-analyze.pl                              =
                        |      4 +-
 head/crypto/heimdal/tools/krb5-config.1                                   =
                        |     68 +-
 head/crypto/heimdal/tools/krb5-config.in                                  =
                        |     38 +-
 head/etc/defaults/rc.conf                                                 =
                        |      4 +-
 head/etc/mtree/BSD.include.dist                                           =
                        |      8 +-
 head/etc/mtree/BSD.usr.dist                                               =
                        |      4 +-
 head/etc/rc.d/Makefile                                                    =
                        |      3 +-
 head/etc/root/dot.cshrc                                                   =
                        |     25 +-
 head/etc/services                                                         =
                        |      4 +-
 head/games/pom/pom.6                                                      =
                        |      4 +-
 head/gnu/lib/csu/Makefile                                                 =
                        |      3 +-
 head/gnu/lib/libgcc/Makefile                                              =
                        |      4 +-
 head/gnu/lib/libstdc++/Makefile                                           =
                        |      4 +-
 head/gnu/lib/libsupc++/Makefile                                           =
                        |      9 +-
 head/gnu/usr.bin/binutils/Makefile.inc0                                   =
                        |      7 +-
 head/gnu/usr.bin/binutils/as/Makefile                                     =
                        |      9 +-
 head/gnu/usr.bin/binutils/as/mips-freebsd/itbl-cpu.h                      =
                        |      7 +-
 head/gnu/usr.bin/cc/Makefile.tgt                                          =
                        |      7 +-
 head/gnu/usr.bin/gdb/Makefile.inc                                         =
                        |      4 +-
 head/gnu/usr.bin/gdb/libgdb/Makefile                                      =
                        |      4 +-
 head/include/ctype.h                                                      =
                        |      4 +-
 head/include/inttypes.h                                                   =
                        |      5 +-
 head/include/langinfo.h                                                   =
                        |      4 +-
 head/include/malloc_np.h                                                  =
                        |     29 +-
 head/include/monetary.h                                                   =
                        |      5 +-
 head/include/stdio.h                                                      =
                        |      5 +-
 head/include/stdlib.h                                                     =
                        |     12 +-
 head/include/string.h                                                     =
                        |      4 +-
 head/include/time.h                                                       =
                        |      4 +-
 head/include/wchar.h                                                      =
                        |      4 +-
 head/kerberos5/Makefile.inc                                               =
                        |      8 +-
 head/kerberos5/include/config.h                                           =
                        |    294 +-
 head/kerberos5/include/crypto-headers.h                                   =
                        |     16 +-
 head/kerberos5/include/krb5-types.h                                       =
                        |     52 +-
 head/kerberos5/include/version.h                                          =
                        |      9 +-
 head/kerberos5/lib/Makefile                                               =
                        |      4 +-
 head/kerberos5/lib/Makefile.inc                                           =
                        |      4 +-
 head/kerberos5/lib/libasn1/Makefile                                       =
                        |    493 +-
 head/kerberos5/lib/libgssapi_krb5/Makefile                                =
                        |     15 +-
 head/kerberos5/lib/libgssapi_krb5/gss_krb5.c                              =
                        |      3 +-
 head/kerberos5/lib/libgssapi_ntlm/Makefile                                =
                        |     15 +-
 head/kerberos5/lib/libgssapi_ntlm/prefix.c                                =
                        |      9 +-
 head/kerberos5/lib/libgssapi_spnego/Makefile                              =
                        |     48 +-
 head/kerberos5/lib/libhdb/Makefile                                        =
                        |     81 +-
 head/kerberos5/lib/libheimntlm/Makefile                                   =
                        |     40 +-
 head/kerberos5/lib/libhx509/Makefile                                      =
                        |    244 +-
 head/kerberos5/lib/libkadm5clnt/Makefile                                  =
                        |      8 +-
 head/kerberos5/lib/libkadm5srv/Makefile                                   =
                        |      7 +-
 head/kerberos5/lib/libkafs5/Makefile                                      =
                        |     16 +-
 head/kerberos5/lib/libkrb5/Makefile                                       =
                        |    373 +-
 head/kerberos5/lib/libroken/Makefile                                      =
                        |     56 +-
 head/kerberos5/lib/libvers/Makefile                                       =
                        |     15 +-
 head/kerberos5/libexec/Makefile                                           =
                        |      5 +-
 head/kerberos5/libexec/hprop/Makefile                                     =
                        |      4 +-
 head/kerberos5/libexec/ipropd-master/Makefile                             =
                        |      4 +-
 head/kerberos5/libexec/kadmind/Makefile                                   =
                        |     17 +-
 head/kerberos5/libexec/kcm/Makefile                                       =
                        |     16 +-
 head/kerberos5/libexec/kdc/Makefile                                       =
                        |     29 +-
 head/kerberos5/tools/Makefile                                             =
                        |      4 +-
 head/kerberos5/tools/Makefile.inc                                         =
                        |      4 +-
 head/kerberos5/tools/asn1_compile/Makefile                                =
                        |     56 +-
 head/kerberos5/tools/make-roken/Makefile                                  =
                        |      6 +-
 head/kerberos5/tools/slc/Makefile                                         =
                        |     33 +-
 head/kerberos5/usr.bin/Makefile                                           =
                        |      6 +-
 head/kerberos5/usr.bin/kadmin/Makefile                                    =
                        |      9 +-
 head/kerberos5/usr.bin/kdestroy/Makefile                                  =
                        |     11 +-
 head/kerberos5/usr.bin/kinit/Makefile                                     =
                        |      8 +-
 head/kerberos5/usr.bin/krb5-config/Makefile                               =
                        |      3 +-
 head/kerberos5/usr.sbin/Makefile                                          =
                        |      4 +-
 head/kerberos5/usr.sbin/kstash/Makefile                                   =
                        |     10 +-
 head/kerberos5/usr.sbin/ktutil/Makefile                                   =
                        |     21 +-
 head/lib/Makefile                                                         =
                        |     12 +-
 head/lib/bind/config.h                                                    =
                        |      7 +-
 head/lib/bind/dns/code.h                                                  =
                        |      4 +-
 head/lib/bind/dns/dns/enumclass.h                                         =
                        |      4 +-
 head/lib/bind/dns/dns/enumtype.h                                          =
                        |      4 +-
 head/lib/bind/dns/dns/rdatastruct.h                                       =
                        |    126 +-
 head/lib/bind/lwres/lwres/netdb.h                                         =
                        |      4 +-
 head/lib/bind/lwres/lwres/platform.h                                      =
                        |      4 +-
 head/lib/clang/Makefile                                                   =
                        |      8 +-
 head/lib/clang/clang.build.mk                                             =
                        |     27 +-
 head/lib/clang/include/Makefile                                           =
                        |      7 +-
 head/lib/clang/include/clang/Basic/Version.inc                            =
                        |     10 +-
 head/lib/clang/include/llvm/Config/config.h                               =
                        |     65 +-
 head/lib/clang/include/llvm/Config/llvm-config.h                          =
                        |     20 +-
 head/lib/clang/libclanganalysis/Makefile                                  =
                        |      7 +-
 head/lib/clang/libclangarcmigrate/Makefile                                =
                        |      6 +-
 head/lib/clang/libclangast/Makefile                                       =
                        |      4 +-
 head/lib/clang/libclangbasic/Makefile                                     =
                        |      4 +-
 head/lib/clang/libclangcodegen/Makefile                                   =
                        |      3 +-
 head/lib/clang/libclangdriver/Makefile                                    =
                        |      6 +-
 head/lib/clang/libclangfrontend/Makefile                                  =
                        |     10 +-
 head/lib/clang/libclangindex/Makefile                                     =
                        |      3 +-
 head/lib/clang/libclanglex/Makefile                                       =
                        |      4 +-
 head/lib/clang/libclangparse/Makefile                                     =
                        |      3 +-
 head/lib/clang/libclangrewrite/Makefile                                   =
                        |      4 +-
 head/lib/clang/libclangsema/Makefile                                      =
                        |     11 +-
 head/lib/clang/libclangserialization/Makefile                             =
                        |      5 +-
 head/lib/clang/libclangstaticanalyzercheckers/Makefile                    =
                        |     14 +-
 head/lib/clang/libclangstaticanalyzercore/Makefile                        =
                        |      7 +-
 head/lib/clang/libllvmanalysis/Makefile                                   =
                        |     11 +-
 head/lib/clang/libllvmarmcodegen/Makefile                                 =
                        |      4 +-
 head/lib/clang/libllvmarmdesc/Makefile                                    =
                        |      3 +-
 head/lib/clang/libllvmasmprinter/Makefile                                 =
                        |      3 +-
 head/lib/clang/libllvmcodegen/Makefile                                    =
                        |     22 +-
 head/lib/clang/libllvmcore/Makefile                                       =
                        |      3 +-
 head/lib/clang/libllvminstrumentation/Makefile                            =
                        |      9 +-
 head/lib/clang/libllvmjit/Makefile                                        =
                        |      9 +-
 head/lib/clang/libllvmmc/Makefile                                         =
                        |      3 +-
 head/lib/clang/libllvmmcjit/Makefile                                      =
                        |     11 +-
 head/lib/clang/libllvmmipscodegen/Makefile                                =
                        |      7 +-
 head/lib/clang/libllvmmipsdesc/Makefile                                   =
                        |      4 +-
 head/lib/clang/libllvmpowerpccodegen/Makefile                             =
                        |      3 +-
 head/lib/clang/libllvmpowerpcdesc/Makefile                                =
                        |      5 +-
 head/lib/clang/libllvmruntimedyld/Makefile                                =
                        |      3 +-
 head/lib/clang/libllvmscalaropts/Makefile                                 =
                        |      5 +-
 head/lib/clang/libllvmselectiondag/Makefile                               =
                        |      6 +-
 head/lib/clang/libllvmsupport/Makefile                                    =
                        |      9 +-
 head/lib/clang/libllvmtablegen/Makefile                                   =
                        |      3 +-
 head/lib/clang/libllvmtarget/Makefile                                     =
                        |      5 +-
 head/lib/clang/libllvmtransformutils/Makefile                             =
                        |      7 +-
 head/lib/clang/libllvmx86codegen/Makefile                                 =
                        |      3 +-
 head/lib/clang/libllvmx86desc/Makefile                                    =
                        |      6 +-
 head/lib/csu/powerpc/Makefile                                             =
                        |      5 +-
 head/lib/libarchive/Makefile                                              =
                        |      3 +-
 head/lib/libbluetooth/bluetooth.3                                         =
                        |      6 +-
 head/lib/libc/Makefile                                                    =
                        |      3 +-
 head/lib/libc/arm/gen/Makefile.inc                                        =
                        |      4 +-
 head/lib/libc/gen/fstab.c                                                 =
                        |      4 +-
 head/lib/libc/gen/fts.3                                                   =
                        |      8 +-
 head/lib/libc/gen/getpagesizes.3                                          =
                        |      4 +-
 head/lib/libc/gen/getutxent.c                                             =
                        |      7 +-
 head/lib/libc/gen/psignal.3                                               =
                        |      4 +-
 head/lib/libc/gen/sem_new.c                                               =
                        |     40 +-
 head/lib/libc/gen/sysconf.3                                               =
                        |      4 +-
 head/lib/libc/gen/tls.c                                                   =
                        |     25 +-
 head/lib/libc/gen/utxdb.c                                                 =
                        |      6 +-
 head/lib/libc/i386/sys/i386_get_ioperm.2                                  =
                        |      4 +-
 head/lib/libc/i386/sys/i386_set_watch.3                                   =
                        |      4 +-
 head/lib/libc/i386/sys/i386_vm86.2                                        =
                        |      4 +-
 head/lib/libc/iconv/iconv.3                                               =
                        |      4 +-
 head/lib/libc/iconv/iconvctl.3                                            =
                        |      6 +-
 head/lib/libc/iconv/iconvlist.3                                           =
                        |      4 +-
 head/lib/libc/locale/ctype.3                                              =
                        |      4 +-
 head/lib/libc/locale/ctype_l.3                                            =
                        |      6 +-
 head/lib/libc/locale/digittoint.3                                         =
                        |      4 +-
 head/lib/libc/locale/duplocale.3                                          =
                        |     21 +-
 head/lib/libc/locale/isalnum.3                                            =
                        |     30 +-
 head/lib/libc/locale/isalpha.3                                            =
                        |     28 +-
 head/lib/libc/locale/isblank.3                                            =
                        |      4 +-
 head/lib/libc/locale/iscntrl.3                                            =
                        |     19 +-
 head/lib/libc/locale/isdigit.3                                            =
                        |      7 +-
 head/lib/libc/locale/isgraph.3                                            =
                        |     41 +-
 head/lib/libc/locale/islower.3                                            =
                        |     15 +-
 head/lib/libc/locale/isprint.3                                            =
                        |     41 +-
 head/lib/libc/locale/ispunct.3                                            =
                        |     17 +-
 head/lib/libc/locale/isspace.3                                            =
                        |      5 +-
 head/lib/libc/locale/isupper.3                                            =
                        |     15 +-
 head/lib/libc/locale/isxdigit.3                                           =
                        |     13 +-
 head/lib/libc/locale/newlocale.3                                          =
                        |      8 +-
 head/lib/libc/locale/xlocale.3                                            =
                        |     33 +-
 head/lib/libc/net/getaddrinfo.c                                           =
                        |      4 +-
 head/lib/libc/net/getipnodebyname.3                                       =
                        |     14 +-
 head/lib/libc/net/if_nametoindex.c                                        =
                        |      5 +-
 head/lib/libc/net/inet_net.3                                              =
                        |      3 +-
 head/lib/libc/net/name6.c                                                 =
                        |      4 +-
 head/lib/libc/net/nsdispatch.3                                            =
                        |     11 +-
 head/lib/libc/net/sctp_bindx.3                                            =
                        |      6 +-
 head/lib/libc/net/sctp_connectx.3                                         =
                        |     10 +-
 head/lib/libc/net/sctp_freepaddrs.3                                       =
                        |      6 +-
 head/lib/libc/net/sctp_getaddrlen.3                                       =
                        |      4 +-
 head/lib/libc/net/sctp_getassocid.3                                       =
                        |      5 +-
 head/lib/libc/net/sctp_getpaddrs.3                                        =
                        |      4 +-
 head/lib/libc/net/sctp_opt_info.3                                         =
                        |      6 +-
 head/lib/libc/net/sctp_recvmsg.3                                          =
                        |     36 +-
 head/lib/libc/net/sctp_send.3                                             =
                        |     40 +-
 head/lib/libc/net/sctp_sendmsg.3                                          =
                        |     36 +-
 head/lib/libc/net/sourcefilter.3                                          =
                        |      4 +-
 head/lib/libc/posix1e/acl_add_flag_np.3                                   =
                        |     12 +-
 head/lib/libc/posix1e/acl_add_perm.3                                      =
                        |     34 +-
 head/lib/libc/posix1e/acl_create_entry.3                                  =
                        |      4 +-
 head/lib/libc/posix1e/acl_set_entry_type_np.3                             =
                        |      6 +-
 head/lib/libc/posix1e/acl_set_tag_type.3                                  =
                        |     18 +-
 head/lib/libc/posix1e/acl_to_text.3                                       =
                        |      9 +-
 head/lib/libc/powerpc/gen/_setjmp.S                                       =
                        |      3 +-
 head/lib/libc/powerpc/gen/setjmp.S                                        =
                        |      3 +-
 head/lib/libc/powerpc/gen/sigsetjmp.S                                     =
                        |      3 +-
 head/lib/libc/powerpc64/gen/_setjmp.S                                     =
                        |      3 +-
 head/lib/libc/powerpc64/gen/makecontext.c                                 =
                        |      4 +-
 head/lib/libc/powerpc64/gen/setjmp.S                                      =
                        |      3 +-
 head/lib/libc/powerpc64/gen/sigsetjmp.S                                   =
                        |      3 +-
 head/lib/libc/rpc/rpc_soc.3                                               =
                        |     19 +-
 head/lib/libc/stdio/getline.3                                             =
                        |      4 +-
 head/lib/libc/stdlib/Makefile.inc                                         =
                        |     18 +-
 head/lib/libc/stdlib/Symbol.map                                           =
                        |     14 +-
 head/lib/libc/stdlib/at_quick_exit.3                                      =
                        |     14 +-
 head/lib/libc/stdlib/getenv.3                                             =
                        |      4 +-
 head/lib/libc/string/memchr.3                                             =
                        |      4 +-
 head/lib/libc/sys/cap_new.2                                               =
                        |     12 +-
 head/lib/libc/sys/chflags.2                                               =
                        |     25 +-
 head/lib/libc/sys/cpuset.2                                                =
                        |     10 +-
 head/lib/libc/sys/cpuset_getaffinity.2                                    =
                        |      5 +-
 head/lib/libc/sys/dup.2                                                   =
                        |     19 +-
 head/lib/libc/sys/fcntl.2                                                 =
                        |      4 +-
 head/lib/libc/sys/jail.2                                                  =
                        |      6 +-
 head/lib/libc/sys/kldstat.2                                               =
                        |      6 +-
 head/lib/libc/sys/kqueue.2                                                =
                        |     10 +-
 head/lib/libc/sys/kse.2                                                   =
                        |      4 +-
 head/lib/libc/sys/ktrace.2                                                =
                        |     36 +-
 head/lib/libc/sys/pathconf.2                                              =
                        |      5 +-
 head/lib/libc/sys/posix_fadvise.2                                         =
                        |      3 +-
 head/lib/libc/sys/posix_fallocate.2                                       =
                        |      3 +-
 head/lib/libc/sys/ptrace.2                                                =
                        |      4 +-
 head/lib/libc/sys/quotactl.2                                              =
                        |      6 +-
 head/lib/libc/sys/sctp_generic_sendmsg.2                                  =
                        |      6 +-
 head/lib/libc/sys/sctp_peeloff.2                                          =
                        |      5 +-
 head/lib/libc/sys/select.2                                                =
                        |      4 +-
 head/lib/libc/sys/sendfile.2                                              =
                        |      4 +-
 head/lib/libc/sys/shm_open.2                                              =
                        |      3 +-
 head/lib/libcom_err/Makefile                                              =
                        |      5 +-
 head/lib/libcrypt/crypt.3                                                 =
                        |      8 +-
 head/lib/libcxxrt/Version.map                                             =
                        |      7 +-
 head/lib/libelf/elf.3                                                     =
                        |      4 +-
 head/lib/libelf/elf_getdata.3                                             =
                        |      4 +-
 head/lib/libelf/elf_getphdrnum.3                                          =
                        |      5 +-
 head/lib/libelf/elf_getphnum.3                                            =
                        |      3 +-
 head/lib/libelf/elf_getshdrnum.3                                          =
                        |      5 +-
 head/lib/libelf/elf_getshdrstrndx.3                                       =
                        |      5 +-
 head/lib/libelf/elf_getshnum.3                                            =
                        |      3 +-
 head/lib/libelf/elf_getshstrndx.3                                         =
                        |      3 +-
 head/lib/libelf/libelf_data.c                                             =
                        |      6 +-
 head/lib/libfetch/fetch.3                                                 =
                        |      4 +-
 head/lib/libfetch/fetch.c                                                 =
                        |     53 +-
 head/lib/libgpib/gpib.3                                                   =
                        |      3 +-
 head/lib/libgssapi/Symbol.map                                             =
                        |      3 +-
 head/lib/libgssapi/gss_accept_sec_context.3                               =
                        |      4 +-
 head/lib/libgssapi/gss_display_status.c                                   =
                        |     14 +-
 head/lib/libgssapi/gss_release_buffer.3                                   =
                        |      4 +-
 head/lib/libgssapi/gss_release_oid_set.3                                  =
                        |      4 +-
 head/lib/libgssapi/mech.5                                                 =
                        |      6 +-
 head/lib/libgssapi/mech_switch.h                                          =
                        |      3 +-
 head/lib/libpam/modules/pam_exec/pam_exec.8                               =
                        |     86 +-
 head/lib/libpam/modules/pam_exec/pam_exec.c                               =
                        |    364 +-
 head/lib/libpam/modules/pam_krb5/pam_krb5.c                               =
                        |    171 +-
 head/lib/libpam/modules/pam_ksu/pam_ksu.c                                 =
                        |     40 +-
 head/lib/libpam/modules/pam_nologin/pam_nologin.8                         =
                        |      4 +-
 head/lib/libpmc/Makefile                                                  =
                        |      6 +-
 head/lib/libpmc/libpmc.c                                                  =
                        |    158 +-
 head/lib/libpmc/pmc.3                                                     =
                        |      6 +-
 head/lib/libpmc/pmc.atom.3                                                =
                        |      3 +-
 head/lib/libpmc/pmc.core.3                                                =
                        |      7 +-
 head/lib/libpmc/pmc.core2.3                                               =
                        |      3 +-
 head/lib/libpmc/pmc.corei7.3                                              =
                        |      3 +-
 head/lib/libpmc/pmc.corei7uc.3                                            =
                        |      3 +-
 head/lib/libpmc/pmc.h                                                     =
                        |      4 +-
 head/lib/libpmc/pmc.iaf.3                                                 =
                        |      3 +-
 head/lib/libpmc/pmc.k7.3                                                  =
                        |      4 +-
 head/lib/libpmc/pmc.k8.3                                                  =
                        |      4 +-
 head/lib/libpmc/pmc.p4.3                                                  =
                        |      4 +-
 head/lib/libpmc/pmc.p5.3                                                  =
                        |      3 +-
 head/lib/libpmc/pmc.p6.3                                                  =
                        |      3 +-
 head/lib/libpmc/pmc.sandybridge.3                                         =
                        |      3 +-
 head/lib/libpmc/pmc.sandybridgeuc.3                                       =
                        |      3 +-
 head/lib/libpmc/pmc.tsc.3                                                 =
                        |      3 +-
 head/lib/libpmc/pmc.ucf.3                                                 =
                        |      3 +-
 head/lib/libpmc/pmc.westmere.3                                            =
                        |      3 +-
 head/lib/libpmc/pmc.westmereuc.3                                          =
                        |      3 +-
 head/lib/libpmc/pmc.xscale.3                                              =
                        |     19 +-
 head/lib/libpmc/pmc_capabilities.3                                        =
                        |      4 +-
 head/lib/libpmc/pmclog.c                                                  =
                        |      8 +-
 head/lib/libpmc/pmclog.h                                                  =
                        |     10 +-
 head/lib/libproc/proc_bkpt.c                                              =
                        |      5 +-
 head/lib/libproc/proc_regs.c                                              =
                        |     10 +-
 head/lib/libprocstat/Symbol.map                                           =
                        |      6 +-
 head/lib/libprocstat/Versions.def                                         =
                        |      7 +-
 head/lib/libprocstat/libprocstat.3                                        =
                        |     17 +-
 head/lib/libprocstat/libprocstat.c                                        =
                        |     74 +-
 head/lib/libprocstat/libprocstat.h                                        =
                        |      8 +-
 head/lib/librpcsec_gss/rpc_gss_seccreate.3                                =
                        |      4 +-
 head/lib/librt/sigev_thread.c                                             =
                        |     12 +-
 head/lib/librt/sigev_thread.h                                             =
                        |      4 +-
 head/lib/libtacplus/libtacplus.3                                          =
                        |      5 +-
 head/lib/libthr/thread/thr_private.h                                      =
                        |      4 +-
 head/lib/libthr/thread/thr_sig.c                                          =
                        |      8 +-
 head/lib/libthr/thread/thr_umtx.h                                         =
                        |     23 +-
 head/lib/libulog/utempter_add_record.3                                    =
                        |      4 +-
 head/lib/libusb/Makefile                                                  =
                        |      3 +-
 head/lib/libusb/libusb.3                                                  =
                        |     22 +-
 head/lib/libusb/libusb.h                                                  =
                        |      3 +-
 head/lib/libusb/libusb10.c                                                =
                        |     26 +-
 head/lib/libusb/libusb20.3                                                =
                        |      7 +-
 head/lib/libutil/kinfo_getallproc.3                                       =
                        |      4 +-
 head/lib/libutil/kinfo_getproc.3                                          =
                        |      4 +-
 head/lib/libutil/login.conf.5                                             =
                        |    150 +-
 head/lib/libutil/login_cap.3                                              =
                        |      6 +-
 head/lib/libutil/quotafile.3                                              =
                        |      6 +-
 head/lib/msun/man/csqrt.3                                                 =
                        |     16 +-
 head/lib/msun/man/ieee.3                                                  =
                        |      3 +-
 head/lib/msun/src/s_remquo.c                                              =
                        |      9 +-
 head/lib/msun/src/s_remquof.c                                             =
                        |      5 +-
 head/lib/msun/src/s_remquol.c                                             =
                        |      5 +-
 head/libexec/bootpd/bootpd.8                                              =
                        |     36 +-
 head/libexec/getty/gettytab.5                                             =
                        |      6 +-
 head/libexec/rtld-elf/Makefile                                            =
                        |      9 +-
 head/libexec/rtld-elf/amd64/reloc.c                                       =
                        |     36 +-
 head/libexec/rtld-elf/arm/reloc.c                                         =
                        |     28 +-
 head/libexec/rtld-elf/i386/reloc.c                                        =
                        |     32 +-
 head/libexec/rtld-elf/ia64/reloc.c                                        =
                        |     39 +-
 head/libexec/rtld-elf/malloc.c                                            =
                        |     20 +-
 head/libexec/rtld-elf/mips/reloc.c                                        =
                        |     20 +-
 head/libexec/rtld-elf/mips/rtld_start.S                                   =
                        |      5 +-
 head/libexec/rtld-elf/powerpc/reloc.c                                     =
                        |     27 +-
 head/libexec/rtld-elf/powerpc64/reloc.c                                   =
                        |     29 +-
 head/libexec/rtld-elf/rtld.c                                              =
                        |    161 +-
 head/libexec/rtld-elf/rtld.h                                              =
                        |     36 +-
 head/libexec/rtld-elf/sparc64/reloc.c                                     =
                        |     21 +-
 head/libexec/rtld-elf/xmalloc.c                                           =
                        |     34 +-
 head/libexec/tftpd/tftpd.8                                                =
                        |      8 +-
 head/sbin/bsdlabel/bsdlabel.c                                             =
                        |      5 +-
 head/sbin/camcontrol/camcontrol.8                                         =
                        |      7 +-
 head/sbin/devfs/devfs.8                                                   =
                        |      6 +-
 head/sbin/fdisk/fdisk.c                                                   =
                        |      3 +-
 head/sbin/geom/class/eli/geli.8                                           =
                        |      4 +-
 head/sbin/geom/class/multipath/gmultipath.8                               =
                        |      4 +-
 head/sbin/geom/class/sched/gsched.8                                       =
                        |      3 +-
 head/sbin/growfs/debug.c                                                  =
                        |      6 +-
 head/sbin/growfs/growfs.c                                                 =
                        |   1191 +-
 head/sbin/gvinum/gvinum.8                                                 =
                        |     13 +-
 head/sbin/hastd/hastd.c                                                   =
                        |     14 +-
 head/sbin/hastd/nv.c                                                      =
                        |     16 +-
 head/sbin/ifconfig/ifconfig.8                                             =
                        |     48 +-
 head/sbin/ifconfig/ifieee80211.c                                          =
                        |      6 +-
 head/sbin/ifconfig/ifpfsync.c                                             =
                        |     30 +-
 head/sbin/init/init.8                                                     =
                        |      4 +-
 head/sbin/init/init.c                                                     =
                        |      8 +-
 head/sbin/ipfw/ipfw.8                                                     =
                        |    117 +-
 head/sbin/ipfw/ipfw2.c                                                    =
                        |     14 +-
 head/sbin/iscontrol/Makefile                                              =
                        |      4 +-
 head/sbin/iscontrol/iscontrol.8                                           =
                        |      4 +-
 head/sbin/iscontrol/iscontrol.c                                           =
                        |     22 +-
 head/sbin/iscontrol/iscsi.conf.5                                          =
                        |      4 +-
 head/sbin/kldload/kldload.8                                               =
                        |      3 +-
 head/sbin/mdconfig/mdconfig.8                                             =
                        |     51 +-
 head/sbin/mdmfs/mdmfs.8                                                   =
                        |     10 +-
 head/sbin/mount_unionfs/mount_unionfs.8                                   =
                        |      4 +-
 head/sbin/ping6/ping6.8                                                   =
                        |      6 +-
 head/sbin/quotacheck/quotacheck.8                                         =
                        |      4 +-
 head/sbin/rcorder/rcorder.8                                               =
                        |      4 +-
 head/sbin/route/route.8                                                   =
                        |     38 +-
 head/sbin/savecore/savecore.c                                             =
                        |      3 +-
 head/sbin/setkey/setkey.8                                                 =
                        |     19 +-
 head/sbin/sunlabel/sunlabel.8                                             =
                        |     18 +-
 head/sbin/sysctl/sysctl.8                                                 =
                        |    134 +-
 head/sbin/sysctl/sysctl.c                                                 =
                        |      4 +-
 head/secure/usr.bin/ssh/Makefile                                          =
                        |      6 +-
 head/secure/usr.sbin/sshd/Makefile                                        =
                        |      6 +-
 head/share/doc/bind9/Makefile                                             =
                        |      8 +-
 head/share/examples/Makefile                                              =
                        |      4 +-
 head/share/examples/cvsup/cvs-supfile                                     =
                        |     19 +-
 head/share/examples/cvsup/doc-supfile                                     =
                        |     19 +-
 head/share/examples/cvsup/gnats-supfile                                   =
                        |     19 +-
 head/share/examples/cvsup/ports-supfile                                   =
                        |     19 +-
 head/share/examples/cvsup/stable-supfile                                  =
                        |     19 +-
 head/share/examples/cvsup/standard-supfile                                =
                        |     19 +-
 head/share/examples/cvsup/www-supfile                                     =
                        |     19 +-
 head/share/man/man3/pthread_attr_affinity_np.3                            =
                        |      4 +-
 head/share/man/man3/pthread_cond_destroy.3                                =
                        |      8 +-
 head/share/man/man3/pthread_cond_timedwait.3                              =
                        |      6 +-
 head/share/man/man3/pthread_cond_wait.3                                   =
                        |      6 +-
 head/share/man/man3/tgmath.3                                              =
                        |      6 +-
 head/share/man/man4/acpi.4                                                =
                        |     14 +-
 head/share/man/man4/acpi_hp.4                                             =
                        |     27 +-
 head/share/man/man4/acpi_wmi.4                                            =
                        |      4 +-
 head/share/man/man4/ada.4                                                 =
                        |      4 +-
 head/share/man/man4/adv.4                                                 =
                        |     78 +-
 head/share/man/man4/ahc.4                                                 =
                        |     33 +-
 head/share/man/man4/aibs.4                                                =
                        |      8 +-
 head/share/man/man4/amdsmb.4                                              =
                        |      4 +-
 head/share/man/man4/ath.4                                                 =
                        |     10 +-
 head/share/man/man4/atkbd.4                                               =
                        |      3 +-
 head/share/man/man4/atp.4                                                 =
                        |      8 +-
 head/share/man/man4/bce.4                                                 =
                        |      4 +-
 head/share/man/man4/bpf.4                                                 =
                        |     33 +-
 head/share/man/man4/bridge.4                                              =
                        |      3 +-
 head/share/man/man4/bt.4                                                  =
                        |     71 +-
 head/share/man/man4/bwi.4                                                 =
                        |      9 +-
 head/share/man/man4/bwn.4                                                 =
                        |      9 +-
 head/share/man/man4/carp.4                                                =
                        |      4 +-
 head/share/man/man4/cas.4                                                 =
                        |      8 +-
 head/share/man/man4/cc_vegas.4                                            =
                        |      4 +-
 head/share/man/man4/cd.4                                                  =
                        |      4 +-
 head/share/man/man4/coda.4                                                =
                        |      4 +-
 head/share/man/man4/cy.4                                                  =
                        |      3 +-
 head/share/man/man4/dpms.4                                                =
                        |      3 +-
 head/share/man/man4/ed.4                                                  =
                        |      3 +-
 head/share/man/man4/em.4                                                  =
                        |      3 +-
 head/share/man/man4/epair.4                                               =
                        |      5 +-
 head/share/man/man4/fdc.4                                                 =
                        |      3 +-
 head/share/man/man4/fwohci.4                                              =
                        |      3 +-
 head/share/man/man4/gem.4                                                 =
                        |     17 +-
 head/share/man/man4/geom_fox.4                                            =
                        |      3 +-
 head/share/man/man4/geom_uzip.4                                           =
                        |      3 +-
 head/share/man/man4/gre.4                                                 =
                        |      4 +-
 head/share/man/man4/hptiop.4                                              =
                        |      3 +-
 head/share/man/man4/igb.4                                                 =
                        |      3 +-
 head/share/man/man4/ip.4                                                  =
                        |      4 +-
 head/share/man/man4/ipmi.4                                                =
                        |      4 +-
 head/share/man/man4/ipw.4                                                 =
                        |      4 +-
 head/share/man/man4/isci.4                                                =
                        |     12 +-
 head/share/man/man4/iscsi_initiator.4                                     =
                        |     35 +-
 head/share/man/man4/isp.4                                                 =
                        |      3 +-
 head/share/man/man4/iwi.4                                                 =
                        |      4 +-
 head/share/man/man4/iwn.4                                                 =
                        |     36 +-
 head/share/man/man4/iwnfw.4                                               =
                        |      4 +-
 head/share/man/man4/ixgbe.4                                               =
                        |      8 +-
 head/share/man/man4/ksyms.4                                               =
                        |     40 +-
 head/share/man/man4/ktr.4                                                 =
                        |      4 +-
 head/share/man/man4/lmc.4                                                 =
                        |      4 +-
 head/share/man/man4/malo.4                                                =
                        |     13 +-
 head/share/man/man4/man4.i386/apm.4                                       =
                        |     24 +-
 head/share/man/man4/man4.i386/glxsb.4                                     =
                        |      4 +-
 head/share/man/man4/man4.powerpc/abtn.4                                   =
                        |      4 +-
 head/share/man/man4/man4.powerpc/akbd.4                                   =
                        |     10 +-
 head/share/man/man4/man4.powerpc/bm.4                                     =
                        |      8 +-
 head/share/man/man4/man4.powerpc/cuda.4                                   =
                        |      4 +-
 head/share/man/man4/man4.powerpc/smu.4                                    =
                        |      4 +-
 head/share/man/man4/man4.powerpc/snd_ai2s.4                               =
                        |      6 +-
 head/share/man/man4/man4.powerpc/snd_davbus.4                             =
                        |      4 +-
 head/share/man/man4/md.4                                                  =
                        |      4 +-
 head/share/man/man4/mld.4                                                 =
                        |      4 +-
 head/share/man/man4/mmc.4                                                 =
                        |      4 +-
 head/share/man/man4/mos.4                                                 =
                        |      4 +-
 head/share/man/man4/mps.4                                                 =
                        |     14 +-
 head/share/man/man4/mwl.4                                                 =
                        |      8 +-
 head/share/man/man4/net80211.4                                            =
                        |     12 +-
 head/share/man/man4/netmap.4                                              =
                        |     11 +-
 head/share/man/man4/ng_car.4                                              =
                        |      4 +-
 head/share/man/man4/ng_deflate.4                                          =
                        |      8 +-
 head/share/man/man4/ng_nat.4                                              =
                        |      6 +-
 head/share/man/man4/ng_netflow.4                                          =
                        |     11 +-
 head/share/man/man4/ng_patch.4                                            =
                        |      4 +-
 head/share/man/man4/ng_ppp.4                                              =
                        |     22 +-
 head/share/man/man4/ng_pred1.4                                            =
                        |      8 +-
 head/share/man/man4/ng_tty.4                                              =
                        |      4 +-
 head/share/man/man4/nvram2env.4                                           =
                        |      9 +-
 head/share/man/man4/nxge.4                                                =
                        |      6 +-
 head/share/man/man4/oce.4                                                 =
                        |      3 +-
 head/share/man/man4/pcm.4                                                 =
                        |     10 +-
 head/share/man/man4/ppbus.4                                               =
                        |      5 +-
 head/share/man/man4/psm.4                                                 =
                        |     22 +-
 head/share/man/man4/pts.4                                                 =
                        |      4 +-
 head/share/man/man4/ral.4                                                 =
                        |      4 +-
 head/share/man/man4/run.4                                                 =
                        |      4 +-
 head/share/man/man4/runfw.4                                               =
                        |      4 +-
 head/share/man/man4/sfxge.4                                               =
                        |      4 +-
 head/share/man/man4/smp.4                                                 =
                        |      4 +-
 head/share/man/man4/snd_emu10kx.4                                         =
                        |      6 +-
 head/share/man/man4/snd_hda.4                                             =
                        |      5 +-
 head/share/man/man4/snd_ich.4                                             =
                        |      4 +-
 head/share/man/man4/syscons.4                                             =
                        |     12 +-
 head/share/man/man4/tcp.4                                                 =
                        |      3 +-
 head/share/man/man4/tpm.4                                                 =
                        |      4 +-
 head/share/man/man4/u3g.4                                                 =
                        |      3 +-
 head/share/man/man4/uark.4                                                =
                        |      4 +-
 head/share/man/man4/uath.4                                                =
                        |      9 +-
 head/share/man/man4/ufoma.4                                               =
                        |      4 +-
 head/share/man/man4/uipaq.4                                               =
                        |      8 +-
 head/share/man/man4/ulpt.4                                                =
                        |      4 +-
 head/share/man/man4/umcs.4                                                =
                        |      8 +-
 head/share/man/man4/upgt.4                                                =
                        |     12 +-
 head/share/man/man4/vge.4                                                 =
                        |      4 +-
 head/share/man/man4/virtio.4                                              =
                        |      6 +-
 head/share/man/man4/vxge.4                                                =
                        |      4 +-
 head/share/man/man4/wbwd.4                                                =
                        |      6 +-
 head/share/man/man4/wi.4                                                  =
                        |      4 +-
 head/share/man/man4/wlan_acl.4                                            =
                        |      4 +-
 head/share/man/man4/wlan_amrr.4                                           =
                        |      4 +-
 head/share/man/man4/wpi.4                                                 =
                        |     10 +-
 head/share/man/man4/xen.4                                                 =
                        |      6 +-
 head/share/man/man4/xnb.4                                                 =
                        |     53 +-
 head/share/man/man5/ar.5                                                  =
                        |      6 +-
 head/share/man/man5/fdescfs.5                                             =
                        |      4 +-
 head/share/man/man5/fs.5                                                  =
                        |      6 +-
 head/share/man/man5/fstab.5                                               =
                        |      8 +-
 head/share/man/man5/nsmb.conf.5                                           =
                        |      6 +-
 head/share/man/man5/quota.user.5                                          =
                        |     12 +-
 head/share/man/man5/services.5                                            =
                        |      4 +-
 head/share/man/man5/src.conf.5                                            =
                        |      8 +-
 head/share/man/man5/style.Makefile.5                                      =
                        |      4 +-
 head/share/man/man7/mailaddr.7                                            =
                        |      8 +-
 head/share/man/man7/operator.7                                            =
                        |      4 +-
 head/share/man/man7/release.7                                             =
                        |     18 +-
 head/share/man/man8/picobsd.8                                             =
                        |      4 +-
 head/share/man/man9/BUS_DESCRIBE_INTR.9                                   =
                        |      4 +-
 head/share/man/man9/BUS_SETUP_INTR.9                                      =
                        |      6 +-
 head/share/man/man9/DB_COMMAND.9                                          =
                        |     17 +-
 head/share/man/man9/DEVICE_PROBE.9                                        =
                        |      8 +-
 head/share/man/man9/Makefile                                              =
                        |      4 +-
 head/share/man/man9/SYSINIT.9                                             =
                        |      4 +-
 head/share/man/man9/buf_ring.9                                            =
                        |      4 +-
 head/share/man/man9/condvar.9                                             =
                        |      6 +-
 head/share/man/man9/crypto.9                                              =
                        |      4 +-
 head/share/man/man9/devclass_get_maxunit.9                                =
                        |      4 +-
 head/share/man/man9/device_get_children.9                                 =
                        |      6 +-
 head/share/man/man9/drbr.9                                                =
                        |     10 +-
 head/share/man/man9/eventtimers.9                                         =
                        |      4 +-
 head/share/man/man9/fail.9                                                =
                        |      3 +-
 head/share/man/man9/firmware.9                                            =
                        |      4 +-
 head/share/man/man9/ieee80211.9                                           =
                        |     22 +-
 head/share/man/man9/ieee80211_amrr.9                                      =
                        |      8 +-
 head/share/man/man9/ieee80211_bmiss.9                                     =
                        |      6 +-
 head/share/man/man9/ieee80211_crypto.9                                    =
                        |      8 +-
 head/share/man/man9/ieee80211_input.9                                     =
                        |      4 +-
 head/share/man/man9/ieee80211_node.9                                      =
                        |     14 +-
 head/share/man/man9/ieee80211_output.9                                    =
                        |     10 +-
 head/share/man/man9/ieee80211_proto.9                                     =
                        |     14 +-
 head/share/man/man9/ieee80211_radiotap.9                                  =
                        |      6 +-
 head/share/man/man9/ieee80211_regdomain.9                                 =
                        |      6 +-
 head/share/man/man9/ieee80211_scan.9                                      =
                        |      4 +-
 head/share/man/man9/ieee80211_vap.9                                       =
                        |      6 +-
 head/share/man/man9/ifnet.9                                               =
                        |    299 +-
 head/share/man/man9/kproc.9                                               =
                        |      8 +-
 head/share/man/man9/kqueue.9                                              =
                        |     25 +-
 head/share/man/man9/kthread.9                                             =
                        |     10 +-
 head/share/man/man9/lock.9                                                =
                        |      5 +-
 head/share/man/man9/locking.9                                             =
                        |     25 +-
 head/share/man/man9/make_dev.9                                            =
                        |      3 +-
 head/share/man/man9/malloc.9                                              =
                        |      4 +-
 head/share/man/man9/mi_switch.9                                           =
                        |      4 +-
 head/share/man/man9/osd.9                                                 =
                        |      4 +-
 head/share/man/man9/rmlock.9                                              =
                        |     12 +-
 head/share/man/man9/shm_map.9                                             =
                        |      4 +-
 head/share/man/man9/sleep.9                                               =
                        |      6 +-
 head/share/man/man9/spl.9                                                 =
                        |      6 +-
 head/share/man/man9/swi.9                                                 =
                        |     33 +-
 head/share/man/man9/sysctl_ctx_init.9                                     =
                        |      4 +-
 head/share/man/man9/taskqueue.9                                           =
                        |     10 +-
 head/share/man/man9/timeout.9                                             =
                        |      6 +-
 head/share/man/man9/usbdi.9                                               =
                        |     20 +-
 head/share/man/man9/vm_map_find.9                                         =
                        |      4 +-
 head/share/man/man9/watchdog.9                                            =
                        |      4 +-
 head/share/misc/committers-ports.dot                                      =
                        |     10 +-
 head/share/misc/committers-src.dot                                        =
                        |      7 +-
 head/share/mk/bsd.endian.mk                                               =
                        |      4 +-
 head/share/mk/bsd.libnames.mk                                             =
                        |      6 +-
 head/share/mk/bsd.sys.mk                                                  =
                        |     15 +-
 head/share/mk/sys.mk                                                      =
                        |      4 +-
 head/share/termcap/termcap.5                                              =
                        |      3 +-
 head/sys/Makefile                                                         =
                        |      4 +-
 head/sys/amd64/acpica/acpi_wakeup.c                                       =
                        |     10 +-
 head/sys/amd64/amd64/identcpu.c                                           =
                        |      4 +-
 head/sys/amd64/amd64/initcpu.c                                            =
                        |     31 +-
 head/sys/amd64/amd64/machdep.c                                            =
                        |      9 +-
 head/sys/amd64/amd64/mp_machdep.c                                         =
                        |      9 +-
 head/sys/amd64/amd64/pmap.c                                               =
                        |     88 +-
 head/sys/amd64/amd64/trap.c                                               =
                        |     86 +-
 head/sys/amd64/conf/GENERIC                                               =
                        |      9 +-
 head/sys/amd64/conf/NOTES                                                 =
                        |     54 +-
 head/sys/amd64/include/intr_machdep.h                                     =
                        |      6 +-
 head/sys/amd64/include/pmc_mdep.h                                         =
                        |     25 +-
 head/sys/amd64/include/proc.h                                             =
                        |      3 +-
 head/sys/amd64/include/vm.h                                               =
                        |      4 +-
 head/sys/amd64/linux32/linux32_dummy.c                                    =
                        |      3 +-
 head/sys/amd64/linux32/linux32_machdep.c                                  =
                        |     21 +-
 head/sys/amd64/linux32/linux32_proto.h                                    =
                        |     20 +-
 head/sys/amd64/linux32/linux32_syscall.h                                  =
                        |      4 +-
 head/sys/amd64/linux32/linux32_syscalls.c                                 =
                        |      4 +-
 head/sys/amd64/linux32/linux32_sysent.c                                   =
                        |      6 +-
 head/sys/amd64/linux32/linux32_systrace_args.c                            =
                        |     58 +-
 head/sys/amd64/linux32/syscalls.master                                    =
                        |     20 +-
 head/sys/arm/at91/at91_pio.c                                              =
                        |     49 +-
 head/sys/arm/at91/at91_piovar.h                                           =
                        |     18 +-
 head/sys/arm/at91/at91_pit.c                                              =
                        |     35 +-
 head/sys/arm/at91/at91_pmc.c                                              =
                        |     49 +-
 head/sys/arm/at91/at91_rst.c                                              =
                        |     21 +-
 head/sys/arm/at91/at91_twi.c                                              =
                        |     31 +-
 head/sys/arm/at91/at91_twireg.h                                           =
                        |     82 +-
 head/sys/arm/at91/at91_wdt.c                                              =
                        |     36 +-
 head/sys/arm/at91/at91reg.h                                               =
                        |     50 +-
 head/sys/arm/at91/at91sam9260.c                                           =
                        |     63 +-
 head/sys/arm/at91/at91var.h                                               =
                        |     25 +-
 head/sys/arm/at91/if_ate.c                                                =
                        |     74 +-
 head/sys/arm/conf/AVILA                                                   =
                        |      3 +-
 head/sys/arm/conf/BWCT                                                    =
                        |      3 +-
 head/sys/arm/conf/CAMBRIA                                                 =
                        |      3 +-
 head/sys/arm/conf/CNS11XXNAS                                              =
                        |      3 +-
 head/sys/arm/conf/CRB                                                     =
                        |      3 +-
 head/sys/arm/conf/DB-78XXX                                                =
                        |      3 +-
 head/sys/arm/conf/DB-88F5XXX                                              =
                        |      3 +-
 head/sys/arm/conf/DB-88F6XXX                                              =
                        |      3 +-
 head/sys/arm/conf/DOCKSTAR                                                =
                        |      3 +-
 head/sys/arm/conf/EP80219                                                 =
                        |      3 +-
 head/sys/arm/conf/GUMSTIX                                                 =
                        |      4 +-
 head/sys/arm/conf/HL200                                                   =
                        |      3 +-
 head/sys/arm/conf/HL201                                                   =
                        |      3 +-
 head/sys/arm/conf/IQ31244                                                 =
                        |      3 +-
 head/sys/arm/conf/KB920X                                                  =
                        |      3 +-
 head/sys/arm/conf/LN2410SBC                                               =
                        |      3 +-
 head/sys/arm/conf/NSLU                                                    =
                        |      3 +-
 head/sys/arm/conf/QILA9G20                                                =
                        |      3 +-
 head/sys/arm/conf/SAM9G20EK                                               =
                        |      3 +-
 head/sys/arm/conf/SHEEVAPLUG                                              =
                        |      3 +-
 head/sys/arm/conf/TS7800                                                  =
                        |      3 +-
 head/sys/arm/include/armreg.h                                             =
                        |      7 +-
 head/sys/arm/include/pmc_mdep.h                                           =
                        |      4 +-
 head/sys/arm/include/sysarch.h                                            =
                        |      4 +-
 head/sys/arm/xscale/pxa/uart_bus_pxa.c                                    =
                        |     22 +-
 head/sys/boot/common/crc32.c                                              =
                        |      4 +-
 head/sys/boot/common/gpt.c                                                =
                        |     16 +-
 head/sys/boot/common/loader.8                                             =
                        |      4 +-
 head/sys/boot/fdt/fdt_loader_cmd.c                                        =
                        |    212 +-
 head/sys/boot/forth/loader.conf.5                                         =
                        |      4 +-
 head/sys/boot/forth/menu-commands.4th                                     =
                        |     23 +-
 head/sys/boot/i386/zfsboot/zfsboot.c                                      =
                        |     12 +-
 head/sys/boot/powerpc/ps3/start.S                                         =
                        |      4 +-
 head/sys/boot/uboot/common/metadata.c                                     =
                        |     15 +-
 head/sys/boot/uboot/lib/Makefile                                          =
                        |      8 +-
 head/sys/boot/uboot/lib/glue.c                                            =
                        |     72 +-
 head/sys/cam/ctl/ctl.c                                                    =
                        |     84 +-
 head/sys/cam/ctl/ctl_backend.c                                            =
                        |      3 +-
 head/sys/cam/ctl/ctl_cmd_table.c                                          =
                        |      3 +-
 head/sys/cam/ctl/ctl_error.c                                              =
                        |      3 +-
 head/sys/cam/ctl/ctl_frontend.c                                           =
                        |      3 +-
 head/sys/cam/ctl/ctl_frontend_internal.c                                  =
                        |      3 +-
 head/sys/cam/ctl/ctl_private.h                                            =
                        |      5 +-
 head/sys/cam/scsi/scsi_da.c                                               =
                        |    262 +-
 head/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c              =
                        |      6 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c           =
                        |     12 +-
 head/sys/cddl/dev/dtrace/dtrace_ioctl.c                                   =
                        |      8 +-
 head/sys/cddl/dev/lockstat/lockstat.c                                     =
                        |      4 +-
 head/sys/cddl/dev/profile/profile.c                                       =
                        |      9 +-
 head/sys/cddl/dev/sdt/sdt.c                                               =
                        |      9 +-
 head/sys/compat/linux/linux_file.c                                        =
                        |     51 +-
 head/sys/conf/NOTES                                                       =
                        |     21 +-
 head/sys/conf/files                                                       =
                        |    171 +-
 head/sys/conf/files.amd64                                                 =
                        |      7 +-
 head/sys/conf/files.arm                                                   =
                        |      3 +-
 head/sys/conf/files.i386                                                  =
                        |      7 +-
 head/sys/conf/files.ia64                                                  =
                        |      3 +-
 head/sys/conf/files.mips                                                  =
                        |      5 +-
 head/sys/conf/files.pc98                                                  =
                        |      6 +-
 head/sys/conf/files.powerpc                                               =
                        |      5 +-
 head/sys/conf/files.sparc64                                               =
                        |      3 +-
 head/sys/conf/kern.mk                                                     =
                        |      3 +-
 head/sys/conf/kern.post.mk                                                =
                        |     16 +-
 head/sys/conf/kern.pre.mk                                                 =
                        |     10 +-
 head/sys/conf/kmod.mk                                                     =
                        |      4 +-
 head/sys/conf/makeLINT.mk                                                 =
                        |      3 +-
 head/sys/conf/options                                                     =
                        |      6 +-
 head/sys/conf/options.amd64                                               =
                        |      4 +-
 head/sys/conf/options.arm                                                 =
                        |      3 +-
 head/sys/conf/options.i386                                                =
                        |      3 +-
 head/sys/contrib/dev/acpica/acpica_prep.sh                                =
                        |      4 +-
 head/sys/contrib/dev/acpica/changes.txt                                   =
                        |     92 +
 head/sys/contrib/dev/acpica/common/adisasm.c                              =
                        |     48 +-
 head/sys/contrib/dev/acpica/common/getopt.c                               =
                        |     31 +-
 head/sys/contrib/dev/acpica/compiler/aslcodegen.c                         =
                        |      2 +-
 head/sys/contrib/dev/acpica/compiler/aslcompile.c                         =
                        |     42 +-
 head/sys/contrib/dev/acpica/compiler/aslcompiler.h                        =
                        |     13 +-
 head/sys/contrib/dev/acpica/compiler/aslcompiler.y                        =
                        |      5 +
 head/sys/contrib/dev/acpica/compiler/aslerror.c                           =
                        |    213 +-
 head/sys/contrib/dev/acpica/compiler/aslfiles.c                           =
                        |     34 +-
 head/sys/contrib/dev/acpica/compiler/aslglobal.h                          =
                        |      9 +-
 head/sys/contrib/dev/acpica/compiler/aslmain.c                            =
                        |    115 +-
 head/sys/contrib/dev/acpica/compiler/aslmessages.h                        =
                        |     31 +-
 head/sys/contrib/dev/acpica/compiler/aslstartup.c                         =
                        |     30 +-
 head/sys/contrib/dev/acpica/compiler/asltypes.h                           =
                        |      6 +-
 head/sys/contrib/dev/acpica/compiler/aslutils.c                           =
                        |      8 +
 head/sys/contrib/dev/acpica/compiler/dtcompile.c                          =
                        |     11 +
 head/sys/contrib/dev/acpica/compiler/dtcompiler.h                         =
                        |      4 +
 head/sys/contrib/dev/acpica/compiler/dtexpress.c                          =
                        |     11 +-
 head/sys/contrib/dev/acpica/compiler/dtio.c                               =
                        |      4 -
 head/sys/contrib/dev/acpica/compiler/dtparser.y                           =
                        |      4 +
 head/sys/contrib/dev/acpica/components/debugger/dbcmds.c                  =
                        |      4 +-
 head/sys/contrib/dev/acpica/components/hardware/hwesleep.c                =
                        |     40 +-
 head/sys/contrib/dev/acpica/components/hardware/hwsleep.c                 =
                        |     32 +-
 head/sys/contrib/dev/acpica/components/hardware/hwxfsleep.c               =
                        |     28 +-
 head/sys/contrib/dev/acpica/components/namespace/nsdump.c                 =
                        |     16 +-
 head/sys/contrib/dev/acpica/components/namespace/nsdumpdv.c               =
                        |      2 +-
 head/sys/contrib/dev/acpica/components/namespace/nspredef.c               =
                        |      2 +-
 head/sys/contrib/dev/acpica/components/namespace/nsrepair.c               =
                        |    164 +-
 head/sys/contrib/dev/acpica/components/namespace/nsutils.c                =
                        |      2 +-
 head/sys/contrib/dev/acpica/components/parser/psargs.c                    =
                        |      2 +
 head/sys/contrib/dev/acpica/components/tables/tbfadt.c                    =
                        |     11 +-
 head/sys/contrib/dev/acpica/components/tables/tbinstal.c                  =
                        |      4 +-
 head/sys/contrib/dev/acpica/components/tables/tbutils.c                   =
                        |     19 +-
 head/sys/contrib/dev/acpica/include/achware.h                             =
                        |     18 +-
 head/sys/contrib/dev/acpica/include/aclocal.h                             =
                        |      1 +
 head/sys/contrib/dev/acpica/include/acnames.h                             =
                        |     12 +-
 head/sys/contrib/dev/acpica/include/acnamesp.h                            =
                        |      3 +-
 head/sys/contrib/dev/acpica/include/acoutput.h                            =
                        |      1 +
 head/sys/contrib/dev/acpica/include/acpixf.h                              =
                        |      8 +-
 head/sys/contrib/dev/acpica/include/actypes.h                             =
                        |     10 +-
 head/sys/contrib/dev/ral/LICENSE                                          =
                        |      2 +-
 head/sys/contrib/dev/ral/rt2561.fw.uu                                     =
                        |      2 +-
 head/sys/contrib/dev/ral/rt2561s.fw.uu                                    =
                        |      2 +-
 head/sys/contrib/dev/ral/rt2661.fw.uu                                     =
                        |      2 +-
 head/sys/contrib/dev/ral/rt2860.fw.uu                                     =
                        |      2 +-
 head/sys/contrib/dev/run/rt2870.fw.uu                                     =
                        |    274 +-
 head/sys/contrib/pf/net/if_pfsync.c                                       =
                        |     42 +-
 head/sys/contrib/pf/net/if_pfsync.h                                       =
                        |      2 +-
 head/sys/ddb/db_main.c                                                    =
                        |     18 +-
 head/sys/dev/acpica/acpi.c                                                =
                        |     32 +-
 head/sys/dev/acpica/acpi_pcib_acpi.c                                      =
                        |     53 +-
 head/sys/dev/acpica/acpivar.h                                             =
                        |      7 +-
 head/sys/dev/aic7xxx/aicasm/aicasm_symbol.c                               =
                        |      4 +-
 head/sys/dev/ale/if_ale.c                                                 =
                        |    121 +-
 head/sys/dev/ale/if_alevar.h                                              =
                        |      3 +-
 head/sys/dev/ata/ata-all.c                                                =
                        |     46 +-
 head/sys/dev/ata/ata-all.h                                                =
                        |      6 +-
 head/sys/dev/ata/ata-card.c                                               =
                        |      8 +-
 head/sys/dev/ata/ata-cbus.c                                               =
                        |     14 +-
 head/sys/dev/ata/ata-disk.c                                               =
                        |      4 +-
 head/sys/dev/ata/ata-pci.c                                                =
                        |     26 +-
 head/sys/dev/ata/ata-pci.h                                                =
                        |     19 +-
 head/sys/dev/ata/ata-queue.c                                              =
                        |     34 +-
 head/sys/dev/ata/ata-raid.c                                               =
                        |      4 +-
 head/sys/dev/ata/atapi-cam.c                                              =
                        |      4 +-
 head/sys/dev/ata/atapi-cd.c                                               =
                        |      4 +-
 head/sys/dev/ata/atapi-fd.c                                               =
                        |      4 +-
 head/sys/dev/ata/atapi-tape.c                                             =
                        |      4 +-
 head/sys/dev/ata/chipsets/ata-acard.c                                     =
                        |     21 +-
 head/sys/dev/ata/chipsets/ata-acerlabs.c                                  =
                        |     11 +-
 head/sys/dev/ata/chipsets/ata-adaptec.c                                   =
                        |      5 +-
 head/sys/dev/ata/chipsets/ata-ahci.c                                      =
                        |      7 +-
 head/sys/dev/ata/chipsets/ata-amd.c                                       =
                        |     10 +-
 head/sys/dev/ata/chipsets/ata-ati.c                                       =
                        |     26 +-
 head/sys/dev/ata/chipsets/ata-cyrix.c                                     =
                        |     10 +-
 head/sys/dev/ata/chipsets/ata-highpoint.c                                 =
                        |     10 +-
 head/sys/dev/ata/chipsets/ata-intel.c                                     =
                        |     10 +-
 head/sys/dev/ata/chipsets/ata-ite.c                                       =
                        |     15 +-
 head/sys/dev/ata/chipsets/ata-jmicron.c                                   =
                        |      6 +-
 head/sys/dev/ata/chipsets/ata-marvell.c                                   =
                        |      4 +-
 head/sys/dev/ata/chipsets/ata-national.c                                  =
                        |     10 +-
 head/sys/dev/ata/chipsets/ata-nvidia.c                                    =
                        |     10 +-
 head/sys/dev/ata/chipsets/ata-promise.c                                   =
                        |      8 +-
 head/sys/dev/ata/chipsets/ata-serverworks.c                               =
                        |      8 +-
 head/sys/dev/ata/chipsets/ata-siliconimage.c                              =
                        |     21 +-
 head/sys/dev/ata/chipsets/ata-sis.c                                       =
                        |     40 +-
 head/sys/dev/ata/chipsets/ata-via.c                                       =
                        |     18 +-
 head/sys/dev/ath/ah_osdep.c                                               =
                        |      6 +-
 head/sys/dev/ath/ath_hal/ah.h                                             =
                        |      5 +-
 head/sys/dev/ath/ath_hal/ah_decode.h                                      =
                        |      3 +-
 head/sys/dev/ath/ath_hal/ar5416/ar5416.h                                  =
                        |      6 +-
 head/sys/dev/ath/ath_hal/ar5416/ar5416_interrupts.c                       =
                        |     13 +-
 head/sys/dev/ath/ath_hal/ar5416/ar5416_power.c                            =
                        |      3 +-
 head/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c                            =
                        |     20 +-
 head/sys/dev/ath/ath_hal/ar5416/ar5416_xmit.c                             =
                        |     22 +-
 head/sys/dev/ath/ath_hal/ar5416/ar5416reg.h                               =
                        |      5 +-
 head/sys/dev/ath/if_ath.c                                                 =
                        |    116 +-
 head/sys/dev/ath/if_ath_debug.c                                           =
                        |      7 +-
 head/sys/dev/ath/if_ath_pci.c                                             =
                        |    208 +-
 head/sys/dev/ath/if_ath_sysctl.c                                          =
                        |     28 +-
 head/sys/dev/ath/if_ath_tx.c                                              =
                        |    604 +-
 head/sys/dev/ath/if_ath_tx_ht.c                                           =
                        |     76 +-
 head/sys/dev/ath/if_athioctl.h                                            =
                        |      7 +-
 head/sys/dev/ath/if_athvar.h                                              =
                        |     42 +-
 head/sys/dev/atkbdc/atkbdc_isa.c                                          =
                        |      3 +-
 head/sys/dev/atkbdc/psm.c                                                 =
                        |    275 +-
 head/sys/dev/bce/if_bce.c                                                 =
                        |    115 +-
 head/sys/dev/bce/if_bcereg.h                                              =
                        |      3 +-
 head/sys/dev/cfi/cfi_core.c                                               =
                        |      2 +
 head/sys/dev/e1000/e1000_osdep.h                                          =
                        |      5 +-
 head/sys/dev/e1000/if_em.c                                                =
                        |     98 +-
 head/sys/dev/e1000/if_igb.c                                               =
                        |    128 +-
 head/sys/dev/e1000/if_igb.h                                               =
                        |      3 +-
 head/sys/dev/fb/s3_pci.c                                                  =
                        |      4 +-
 head/sys/dev/fb/vesa.c                                                    =
                        |     51 +-
 head/sys/dev/fb/vga.c                                                     =
                        |      6 +-
 head/sys/dev/fxp/if_fxp.c                                                 =
                        |     98 +-
 head/sys/dev/fxp/if_fxpreg.h                                              =
                        |     20 +-
 head/sys/dev/fxp/if_fxpvar.h                                              =
                        |      4 +-
 head/sys/dev/gpio/gpioc.c                                                 =
                        |      4 +-
 head/sys/dev/hwpmc/hwpmc_amd.c                                            =
                        |     12 +-
 head/sys/dev/hwpmc/hwpmc_core.c                                           =
                        |     14 +-
 head/sys/dev/hwpmc/hwpmc_intel.c                                          =
                        |     11 +-
 head/sys/dev/hwpmc/hwpmc_logging.c                                        =
                        |     36 +-
 head/sys/dev/hwpmc/hwpmc_mips.c                                           =
                        |    451 +-
 head/sys/dev/hwpmc/hwpmc_mips24k.c                                        =
                        |    642 +-
 head/sys/dev/hwpmc/hwpmc_mod.c                                            =
                        |    277 +-
 head/sys/dev/hwpmc/hwpmc_piv.c                                            =
                        |      6 +-
 head/sys/dev/hwpmc/hwpmc_powerpc.c                                        =
                        |      5 +-
 head/sys/dev/hwpmc/hwpmc_ppro.c                                           =
                        |      4 +-
 head/sys/dev/hwpmc/hwpmc_tsc.c                                            =
                        |      5 +-
 head/sys/dev/hwpmc/hwpmc_x86.c                                            =
                        |      9 +-
 head/sys/dev/hwpmc/hwpmc_xscale.c                                         =
                        |      6 +-
 head/sys/dev/hwpmc/pmc_events.h                                           =
                        |     77 +-
 head/sys/dev/ipw/if_ipw.c                                                 =
                        |     16 +-
 head/sys/dev/isci/isci.h                                                  =
                        |     12 +-
 head/sys/dev/isci/isci_controller.c                                       =
                        |     57 +-
 head/sys/dev/isci/isci_domain.c                                           =
                        |     22 +-
 head/sys/dev/isci/isci_io_request.c                                       =
                        |     64 +-
 head/sys/dev/isci/isci_remote_device.c                                    =
                        |     36 +-
 head/sys/dev/isci/isci_task_request.c                                     =
                        |      4 +-
 head/sys/dev/isci/scil/sati_read_capacity.c                               =
                        |      6 +-
 head/sys/dev/iscsi/initiator/isc_subr.c                                   =
                        |    102 +-
 head/sys/dev/iscsi/initiator/iscsi.c                                      =
                        |     23 +-
 head/sys/dev/iscsi/initiator/iscsi_subr.c                                 =
                        |     12 +-
 head/sys/dev/iscsi/initiator/iscsivar.h                                   =
                        |     12 +-
 head/sys/dev/iwi/if_iwi.c                                                 =
                        |     14 +-
 head/sys/dev/iwn/if_iwn.c                                                 =
                        |    101 +-
 head/sys/dev/ixgbe/ixgbe.c                                                =
                        |     20 +-
 head/sys/dev/mfi/mfi.c                                                    =
                        |   1469 +-
 head/sys/dev/mfi/mfi_cam.c                                                =
                        |      8 +-
 head/sys/dev/mfi/mfi_debug.c                                              =
                        |     22 +-
 head/sys/dev/mfi/mfi_disk.c                                               =
                        |     23 +-
 head/sys/dev/mfi/mfi_ioctl.h                                              =
                        |     12 +-
 head/sys/dev/mfi/mfi_linux.c                                              =
                        |      3 +-
 head/sys/dev/mfi/mfi_pci.c                                                =
                        |     41 +-
 head/sys/dev/mfi/mfireg.h                                                 =
                        |    661 +-
 head/sys/dev/mfi/mfivar.h                                                 =
                        |    199 +-
 head/sys/dev/mpt/mpilib/mpi.h                                             =
                        |     12 +-
 head/sys/dev/mpt/mpilib/mpi_cnfg.h                                        =
                        |     71 +-
 head/sys/dev/mpt/mpilib/mpi_fc.h                                          =
                        |      4 +-
 head/sys/dev/mpt/mpilib/mpi_init.h                                        =
                        |      4 +-
 head/sys/dev/mpt/mpilib/mpi_ioc.h                                         =
                        |      5 +-
 head/sys/dev/mpt/mpilib/mpi_lan.h                                         =
                        |      4 +-
 head/sys/dev/mpt/mpilib/mpi_raid.h                                        =
                        |     11 +-
 head/sys/dev/mpt/mpilib/mpi_sas.h                                         =
                        |     20 +-
 head/sys/dev/mpt/mpilib/mpi_targ.h                                        =
                        |      4 +-
 head/sys/dev/mpt/mpilib/mpi_tool.h                                        =
                        |      4 +-
 head/sys/dev/mpt/mpilib/mpi_type.h                                        =
                        |      4 +-
 head/sys/dev/mpt/mpt.h                                                    =
                        |      4 +-
 head/sys/dev/mpt/mpt_pci.c                                                =
                        |    245 +-
 head/sys/dev/mwl/if_mwl.c                                                 =
                        |     29 +-
 head/sys/dev/mwl/if_mwlvar.h                                              =
                        |      6 +-
 head/sys/dev/netmap/if_re_netmap.h                                        =
                        |      6 +-
 head/sys/dev/netmap/ixgbe_netmap.h                                        =
                        |    102 +-
 head/sys/dev/netmap/netmap.c                                              =
                        |    620 +-
 head/sys/dev/netmap/netmap_kern.h                                         =
                        |     56 +-
 head/sys/dev/pci/pci.c                                                    =
                        |     34 +-
 head/sys/dev/sfxge/sfxge_rx.c                                             =
                        |      8 +-
 head/sys/dev/smc/if_smc.c                                                 =
                        |      7 +-
 head/sys/dev/sound/pci/emu10kx.c                                          =
                        |      4 +-
 head/sys/dev/sound/pci/hda/hdaa.c                                         =
                        |     11 +-
 head/sys/dev/sound/pci/hda/hdac.c                                         =
                        |      5 +-
 head/sys/dev/sound/usb/uaudio.c                                           =
                        |     32 +-
 head/sys/dev/sound/usb/uaudioreg.h                                        =
                        |      6 +-
 head/sys/dev/syscons/syscons.c                                            =
                        |     26 +-
 head/sys/dev/uart/uart_bus.h                                              =
                        |      3 +-
 head/sys/dev/uart/uart_core.c                                             =
                        |     17 +-
 head/sys/dev/uart/uart_if.m                                               =
                        |      3 +-
 head/sys/dev/usb/controller/at91dci.c                                     =
                        |      9 +-
 head/sys/dev/usb/controller/atmegadci.c                                   =
                        |      9 +-
 head/sys/dev/usb/controller/avr32dci.c                                    =
                        |      9 +-
 head/sys/dev/usb/controller/dwc_otg.c                                     =
                        |      9 +-
 head/sys/dev/usb/controller/ehci.c                                        =
                        |     11 +-
 head/sys/dev/usb/controller/musb_otg.c                                    =
                        |      9 +-
 head/sys/dev/usb/controller/ohci.c                                        =
                        |     11 +-
 head/sys/dev/usb/controller/uhci.c                                        =
                        |     14 +-
 head/sys/dev/usb/controller/uss820dci.c                                   =
                        |      9 +-
 head/sys/dev/usb/controller/xhci.c                                        =
                        |      9 +-
 head/sys/dev/usb/input/atp.c                                              =
                        |     29 +-
 head/sys/dev/usb/input/uep.c                                              =
                        |      6 +-
 head/sys/dev/usb/input/uhid.c                                             =
                        |      8 +-
 head/sys/dev/usb/input/ukbd.c                                             =
                        |      4 +-
 head/sys/dev/usb/input/ums.c                                              =
                        |      8 +-
 head/sys/dev/usb/misc/ufm.c                                               =
                        |      4 +-
 head/sys/dev/usb/net/if_aue.c                                             =
                        |      6 +-
 head/sys/dev/usb/net/if_axe.c                                             =
                        |      6 +-
 head/sys/dev/usb/net/if_cdce.c                                            =
                        |     26 +-
 head/sys/dev/usb/net/if_cue.c                                             =
                        |      4 +-
 head/sys/dev/usb/net/if_ipheth.c                                          =
                        |      4 +-
 head/sys/dev/usb/net/if_kue.c                                             =
                        |      4 +-
 head/sys/dev/usb/net/if_rue.c                                             =
                        |      4 +-
 head/sys/dev/usb/net/if_udav.c                                            =
                        |      6 +-
 head/sys/dev/usb/net/if_usie.c                                            =
                        |      4 +-
 head/sys/dev/usb/net/ruephy.c                                             =
                        |      8 +-
 head/sys/dev/usb/net/uhso.c                                               =
                        |     10 +-
 head/sys/dev/usb/serial/ubsa.c                                            =
                        |      4 +-
 head/sys/dev/usb/serial/uchcom.c                                          =
                        |      8 +-
 head/sys/dev/usb/serial/ucycom.c                                          =
                        |      4 +-
 head/sys/dev/usb/serial/ufoma.c                                           =
                        |      4 +-
 head/sys/dev/usb/serial/ulpt.c                                            =
                        |      8 +-
 head/sys/dev/usb/serial/umodem.c                                          =
                        |      8 +-
 head/sys/dev/usb/serial/uplcom.c                                          =
                        |      4 +-
 head/sys/dev/usb/serial/usb_serial.c                                      =
                        |     15 +-
 head/sys/dev/usb/serial/usb_serial.h                                      =
                        |      6 +-
 head/sys/dev/usb/storage/umass.c                                          =
                        |      8 +-
 head/sys/dev/usb/storage/urio.c                                           =
                        |      4 +-
 head/sys/dev/usb/storage/ustorage_fs.c                                    =
                        |     42 +-
 head/sys/dev/usb/template/usb_template.c                                  =
                        |      4 +-
 head/sys/dev/usb/usb.h                                                    =
                        |     18 +-
 head/sys/dev/usb/usb_busdma.c                                             =
                        |      6 +-
 head/sys/dev/usb/usb_compat_linux.c                                       =
                        |      4 +-
 head/sys/dev/usb/usb_dev.c                                                =
                        |      8 +-
 head/sys/dev/usb/usb_device.c                                             =
                        |      4 +-
 head/sys/dev/usb/usb_handle_request.c                                     =
                        |      6 +-
 head/sys/dev/usb/usb_hid.c                                                =
                        |      6 +-
 head/sys/dev/usb/usb_hub.c                                                =
                        |      8 +-
 head/sys/dev/usb/usb_msctest.c                                            =
                        |      7 +-
 head/sys/dev/usb/usb_request.c                                            =
                        |     58 +-
 head/sys/dev/usb/usb_request.h                                            =
                        |      4 +-
 head/sys/dev/usb/usb_transfer.c                                           =
                        |      5 +-
 head/sys/dev/usb/usbdi.h                                                  =
                        |      4 +-
 head/sys/dev/usb/usbhid.h                                                 =
                        |      6 +-
 head/sys/dev/usb/wlan/if_rum.c                                            =
                        |     15 +-
 head/sys/dev/usb/wlan/if_run.c                                            =
                        |     45 +-
 head/sys/dev/usb/wlan/if_uath.c                                           =
                        |     25 +-
 head/sys/dev/usb/wlan/if_upgt.c                                           =
                        |     27 +-
 head/sys/dev/usb/wlan/if_ural.c                                           =
                        |     12 +-
 head/sys/dev/usb/wlan/if_urtw.c                                           =
                        |     30 +-
 head/sys/dev/usb/wlan/if_zyd.c                                            =
                        |     60 +-
 head/sys/dev/virtio/balloon/virtio_balloon.c                              =
                        |      9 +-
 head/sys/dev/virtio/block/virtio_blk.c                                    =
                        |    235 +-
 head/sys/dev/virtio/network/if_vtnet.c                                    =
                        |      4 +-
 head/sys/dev/virtio/pci/virtio_pci.c                                      =
                        |      4 +-
 head/sys/dev/virtio/virtio_ring.h                                         =
                        |     25 +-
 head/sys/dev/virtio/virtqueue.c                                           =
                        |     86 +-
 head/sys/dev/virtio/virtqueue.h                                           =
                        |      3 +-
 head/sys/dev/wpi/if_wpi.c                                                 =
                        |     15 +-
 head/sys/dev/xen/balloon/balloon.c                                        =
                        |      4 +-
 head/sys/dev/xen/blkfront/blkfront.c                                      =
                        |     36 +-
 head/sys/fs/ext2fs/ext2_vnops.c                                           =
                        |     16 +-
 head/sys/fs/msdosfs/msdosfs_vfsops.c                                      =
                        |      6 +-
 head/sys/fs/tmpfs/tmpfs.h                                                 =
                        |     64 +-
 head/sys/fs/tmpfs/tmpfs_subr.c                                            =
                        |     96 +-
 head/sys/fs/tmpfs/tmpfs_vfsops.c                                          =
                        |     83 +-
 head/sys/fs/tmpfs/tmpfs_vnops.c                                           =
                        |      4 +-
 head/sys/gdb/gdb_main.c                                                   =
                        |      4 +-
 head/sys/geom/geom_vfs.c                                                  =
                        |     45 +-
 head/sys/geom/part/g_part.c                                               =
                        |     25 +-
 head/sys/geom/part/g_part_ldm.c                                           =
                        |     37 +-
 head/sys/gnu/fs/reiserfs/reiserfs_vfsops.c                                =
                        |     16 +-
 head/sys/i386/acpica/acpi_wakeup.c                                        =
                        |      4 +-
 head/sys/i386/conf/GENERIC                                                =
                        |      9 +-
 head/sys/i386/conf/NOTES                                                  =
                        |     44 +-
 head/sys/i386/conf/XBOX                                                   =
                        |      3 +-
 head/sys/i386/conf/XEN                                                    =
                        |      3 +-
 head/sys/i386/i386/identcpu.c                                             =
                        |      4 +-
 head/sys/i386/i386/machdep.c                                              =
                        |      9 +-
 head/sys/i386/i386/mp_machdep.c                                           =
                        |      8 +-
 head/sys/i386/i386/pmap.c                                                 =
                        |      3 +-
 head/sys/i386/i386/trap.c                                                 =
                        |     91 +-
 head/sys/i386/i386/vm86.c                                                 =
                        |     25 +-
 head/sys/i386/include/intr_machdep.h                                      =
                        |      6 +-
 head/sys/i386/include/pmc_mdep.h                                          =
                        |     31 +-
 head/sys/i386/include/proc.h                                              =
                        |      3 +-
 head/sys/i386/include/vm.h                                                =
                        |      4 +-
 head/sys/i386/linux/linux_dummy.c                                         =
                        |      3 +-
 head/sys/i386/linux/linux_machdep.c                                       =
                        |     21 +-
 head/sys/i386/linux/linux_proto.h                                         =
                        |     20 +-
 head/sys/i386/linux/linux_syscall.h                                       =
                        |      4 +-
 head/sys/i386/linux/linux_syscalls.c                                      =
                        |      4 +-
 head/sys/i386/linux/linux_sysent.c                                        =
                        |      6 +-
 head/sys/i386/linux/linux_systrace_args.c                                 =
                        |     58 +-
 head/sys/i386/linux/syscalls.master                                       =
                        |     20 +-
 head/sys/i386/xbox/xboxfb.c                                               =
                        |      4 +-
 head/sys/ia64/conf/GENERIC                                                =
                        |      3 +-
 head/sys/ia64/conf/SKI                                                    =
                        |      3 +-
 head/sys/kern/kern_clock.c                                                =
                        |     14 +-
 head/sys/kern/kern_descrip.c                                              =
                        |     32 +-
 head/sys/kern/kern_event.c                                                =
                        |     44 +-
 head/sys/kern/kern_exit.c                                                 =
                        |     40 +-
 head/sys/kern/kern_ktrace.c                                               =
                        |     42 +-
 head/sys/kern/kern_linker.c                                               =
                        |     23 +-
 head/sys/kern/kern_lock.c                                                 =
                        |     17 +-
 head/sys/kern/kern_mutex.c                                                =
                        |     17 +-
 head/sys/kern/kern_pmc.c                                                  =
                        |    163 +-
 head/sys/kern/kern_proc.c                                                 =
                        |     52 +-
 head/sys/kern/kern_rwlock.c                                               =
                        |     14 +-
 head/sys/kern/kern_sdt.c                                                  =
                        |     76 +-
 head/sys/kern/kern_sig.c                                                  =
                        |     49 +-
 head/sys/kern/kern_sx.c                                                   =
                        |     14 +-
 head/sys/kern/kern_sysctl.c                                               =
                        |     14 +-
 head/sys/kern/kern_umtx.c                                                 =
                        |    609 +-
 head/sys/kern/sched_ule.c                                                 =
                        |     54 +-
 head/sys/kern/subr_bus.c                                                  =
                        |     20 +-
 head/sys/kern/subr_firmware.c                                             =
                        |     12 +-
 head/sys/kern/subr_kdb.c                                                  =
                        |     29 +-
 head/sys/kern/subr_syscall.c                                              =
                        |     12 +-
 head/sys/kern/subr_trap.c                                                 =
                        |     12 +-
 head/sys/kern/subr_turnstile.c                                            =
                        |     10 +-
 head/sys/kern/subr_uio.c                                                  =
                        |     10 +-
 head/sys/kern/subr_witness.c                                              =
                        |      6 +-
 head/sys/kern/sys_pipe.c                                                  =
                        |     26 +-
 head/sys/kern/uipc_shm.c                                                  =
                        |     16 +-
 head/sys/kern/uipc_socket.c                                               =
                        |     13 +-
 head/sys/kern/vfs_mount.c                                                 =
                        |     44 +-
 head/sys/kern/vfs_subr.c                                                  =
                        |      5 +-
 head/sys/libkern/crc32.c                                                  =
                        |     22 +-
 head/sys/mips/atheros/apb.c                                               =
                        |     25 +-
 head/sys/mips/atheros/ar71xx_chip.c                                       =
                        |      4 +-
 head/sys/mips/atheros/ar71xx_chip.h                                       =
                        |      3 +-
 head/sys/mips/atheros/ar71xx_pci.c                                        =
                        |    221 +-
 head/sys/mips/atheros/ar91xx_chip.c                                       =
                        |     12 +-
 head/sys/mips/atheros/files.ar71xx                                        =
                        |      4 +-
 head/sys/mips/atheros/std.ar71xx                                          =
                        |      4 +-
 head/sys/mips/cavium/cvmx_config.h                                        =
                        |      5 +-
 head/sys/mips/cavium/files.octeon1                                        =
                        |      6 +-
 head/sys/mips/cavium/octeon_ebt3000_cf.c                                  =
                        |    114 +-
 head/sys/mips/cavium/octeon_irq.h                                         =
                        |      4 +-
 head/sys/mips/cavium/octeon_machdep.c                                     =
                        |     16 +-
 head/sys/mips/cavium/std.octeon1                                          =
                        |      4 +-
 head/sys/mips/conf/AR71XX_BASE                                            =
                        |      4 +-
 head/sys/mips/conf/AR91XX_BASE                                            =
                        |      4 +-
 head/sys/mips/conf/OCTEON1                                                =
                        |      3 +-
 head/sys/mips/conf/RT305X                                                 =
                        |      3 +-
 head/sys/mips/conf/SWARM                                                  =
                        |      4 +-
 head/sys/mips/conf/SWARM64                                                =
                        |      4 +-
 head/sys/mips/conf/SWARM64_SMP                                            =
                        |      4 +-
 head/sys/mips/conf/SWARM_SMP                                              =
                        |      4 +-
 head/sys/mips/conf/XLP                                                    =
                        |      4 +-
 head/sys/mips/conf/XLP64                                                  =
                        |      4 +-
 head/sys/mips/conf/XLPN32                                                 =
                        |      4 +-
 head/sys/mips/conf/XLR                                                    =
                        |      5 +-
 head/sys/mips/conf/XLR64                                                  =
                        |      5 +-
 head/sys/mips/conf/XLRN32                                                 =
                        |      5 +-
 head/sys/mips/conf/std.XLP                                                =
                        |     38 +-
 head/sys/mips/include/param.h                                             =
                        |     10 +-
 head/sys/mips/include/pmap.h                                              =
                        |      4 +-
 head/sys/mips/include/pmc_mdep.h                                          =
                        |     58 +-
 head/sys/mips/include/vm.h                                                =
                        |      4 +-
 head/sys/mips/mips/bus_space_generic.c                                    =
                        |      6 +-
 head/sys/mips/mips/exception.S                                            =
                        |     23 +-
 head/sys/mips/mips/intr_machdep.c                                         =
                        |     11 +-
 head/sys/mips/mips/machdep.c                                              =
                        |      4 +-
 head/sys/mips/mips/pmap.c                                                 =
                        |      4 +-
 head/sys/mips/mips/trap.c                                                 =
                        |     75 +-
 head/sys/mips/nlm/board.c                                                 =
                        |    460 +-
 head/sys/mips/nlm/board.h                                                 =
                        |     98 +-
 head/sys/mips/nlm/cms.c                                                   =
                        |     46 +-
 head/sys/mips/nlm/files.xlp                                               =
                        |     32 +-
 head/sys/mips/nlm/hal/iomap.h                                             =
                        |     15 +-
 head/sys/mips/nlm/hal/nlm_hal.c                                           =
                        |    161 +-
 head/sys/mips/nlm/hal/pcibus.h                                            =
                        |     44 +-
 head/sys/mips/nlm/hal/pic.h                                               =
                        |      4 +-
 head/sys/mips/nlm/hal/sys.h                                               =
                        |     23 +-
 head/sys/mips/nlm/intr_machdep.c                                          =
                        |      6 +-
 head/sys/mips/nlm/mpreset.S                                               =
                        |     16 +-
 head/sys/mips/nlm/msgring.h                                               =
                        |     14 +-
 head/sys/mips/nlm/uart_cpu_xlp.c                                          =
                        |     13 +-
 head/sys/mips/nlm/xlp.h                                                   =
                        |     61 +-
 head/sys/mips/nlm/xlp_machdep.c                                           =
                        |     33 +-
 head/sys/mips/nlm/xlp_pci.c                                               =
                        |    558 +-
 head/sys/modules/cyclic/Makefile                                          =
                        |      4 +-
 head/sys/modules/dtrace/Makefile                                          =
                        |      6 +-
 head/sys/modules/hwpmc/Makefile                                           =
                        |      4 +-
 head/sys/modules/iscsi/initiator/Makefile                                 =
                        |     14 +-
 head/sys/modules/mfi/Makefile                                             =
                        |      6 +-
 head/sys/modules/mlx4/Makefile                                            =
                        |     19 +-
 head/sys/modules/mlx4ib/Makefile                                          =
                        |     20 +-
 head/sys/modules/mlxen/Makefile                                           =
                        |     19 +-
 head/sys/modules/mps/Makefile                                             =
                        |      5 +-
 head/sys/modules/mthca/Makefile                                           =
                        |     20 +-
 head/sys/modules/ral/Makefile                                             =
                        |      6 +-
 head/sys/modules/ralfw/Makefile.inc                                       =
                        |      2 +-
 head/sys/modules/ralfw/rt2561/Makefile                                    =
                        |      2 +-
 head/sys/modules/ralfw/rt2561s/Makefile                                   =
                        |      2 +-
 head/sys/modules/ralfw/rt2661/Makefile                                    =
                        |      2 +-
 head/sys/net/bpf.c                                                        =
                        |    349 +-
 head/sys/net/bpf.h                                                        =
                        |     10 +-
 head/sys/net/bpf_buffer.c                                                 =
                        |      8 +-
 head/sys/net/bpf_zerocopy.c                                               =
                        |     12 +-
 head/sys/net/bpfdesc.h                                                    =
                        |     26 +-
 head/sys/net/if_lagg.c                                                    =
                        |     18 +-
 head/sys/net/if_media.h                                                   =
                        |     11 +-
 head/sys/net/netmap.h                                                     =
                        |     16 +-
 head/sys/net/netmap_user.h                                                =
                        |      4 +-
 head/sys/net80211/ieee80211.c                                             =
                        |     10 +-
 head/sys/net80211/ieee80211_ddb.c                                         =
                        |      6 +-
 head/sys/net80211/ieee80211_freebsd.c                                     =
                        |      4 +-
 head/sys/net80211/ieee80211_ht.c                                          =
                        |     90 +-
 head/sys/net80211/ieee80211_ht.h                                          =
                        |      6 +-
 head/sys/net80211/ieee80211_ioctl.h                                       =
                        |      9 +-
 head/sys/net80211/ieee80211_node.c                                        =
                        |     10 +-
 head/sys/net80211/ieee80211_node.h                                        =
                        |      5 +-
 head/sys/net80211/ieee80211_output.c                                      =
                        |      8 +-
 head/sys/net80211/ieee80211_proto.c                                       =
                        |     16 +-
 head/sys/net80211/ieee80211_regdomain.c                                   =
                        |     72 +-
 head/sys/net80211/ieee80211_sta.c                                         =
                        |     15 +-
 head/sys/net80211/ieee80211_superg.c                                      =
                        |     16 +-
 head/sys/net80211/ieee80211_var.h                                         =
                        |      7 +-
 head/sys/netgraph/bluetooth/drivers/ubt/ng_ubt.c                          =
                        |     14 +-
 head/sys/netgraph/ng_source.c                                             =
                        |      3 +-
 head/sys/netinet/in.c                                                     =
                        |      4 +-
 head/sys/netinet/ip_carp.c                                                =
                        |     87 +-
 head/sys/netinet/ip_fw.h                                                  =
                        |      5 +-
 head/sys/netinet/ipfw/ip_fw2.c                                            =
                        |     47 +-
 head/sys/netinet/ipfw/ip_fw_private.h                                     =
                        |      7 +-
 head/sys/netinet/ipfw/ip_fw_sockopt.c                                     =
                        |      6 +-
 head/sys/netinet/ipfw/ip_fw_table.c                                       =
                        |     64 +-
 head/sys/netinet/sctp.h                                                   =
                        |     20 +-
 head/sys/netinet/sctp_constants.h                                         =
                        |      5 +-
 head/sys/netinet/sctp_header.h                                            =
                        |      4 +-
 head/sys/netinet/sctp_input.c                                             =
                        |    140 +-
 head/sys/netinet/sctp_output.c                                            =
                        |    163 +-
 head/sys/netinet/sctp_output.h                                            =
                        |     12 +-
 head/sys/netinet/sctp_pcb.h                                               =
                        |      3 +-
 head/sys/netinet/sctp_peeloff.c                                           =
                        |      4 +-
 head/sys/netinet/sctp_structs.h                                           =
                        |      7 +-
 head/sys/netinet/sctp_timer.c                                             =
                        |     20 +-
 head/sys/netinet/sctp_uio.h                                               =
                        |     75 +-
 head/sys/netinet/sctp_usrreq.c                                            =
                        |    292 +-
 head/sys/netinet/sctputil.c                                               =
                        |    251 +-
 head/sys/netinet/sctputil.h                                               =
                        |      8 +-
 head/sys/netinet/tcp_input.c                                              =
                        |     21 +-
 head/sys/netinet/tcp_output.c                                             =
                        |      4 +-
 head/sys/netinet/tcp_subr.c                                               =
                        |     31 +-
 head/sys/netinet/tcp_var.h                                                =
                        |      5 +-
 head/sys/netinet/udp_usrreq.c                                             =
                        |     10 +-
 head/sys/netinet/udp_var.h                                                =
                        |      4 +-
 head/sys/netinet6/in6_pcb.c                                               =
                        |      6 +-
 head/sys/ofed/drivers/infiniband/core/addr.c                              =
                        |     21 +-
 head/sys/ofed/drivers/infiniband/core/cma.c                               =
                        |     17 +-
 head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_cm.c                     =
                        |     15 +-
 head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_ib.c                     =
                        |      1 -
 head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c                   =
                        |      2 +-
 head/sys/ofed/drivers/net/mlx4/en_frag.c                                  =
                        |      4 +
 head/sys/ofed/drivers/net/mlx4/en_netdev.c                                =
                        |     18 +-
 head/sys/ofed/drivers/net/mlx4/en_port.c                                  =
                        |     16 +-
 head/sys/ofed/drivers/net/mlx4/en_port.h                                  =
                        |     11 +-
 head/sys/ofed/drivers/net/mlx4/en_rx.c                                    =
                        |     13 +
 head/sys/ofed/include/linux/in.h                                          =
                        |      2 +
 head/sys/ofed/include/linux/in6.h                                         =
                        |      2 -
 head/sys/ofed/include/linux/io.h                                          =
                        |      2 +-
 head/sys/ofed/include/linux/page.h                                        =
                        |      2 +-
 head/sys/ofed/include/net/ip.h                                            =
                        |      4 +
 head/sys/ofed/include/net/ipv6.h                                          =
                        |      2 -
 head/sys/pc98/conf/GENERIC                                                =
                        |      3 +-
 head/sys/pci/intpm.c                                                      =
                        |     14 +-
 head/sys/powerpc/aim/machdep.c                                            =
                        |     35 +-
 head/sys/powerpc/aim/mmu_oea.c                                            =
                        |     46 +-
 head/sys/powerpc/aim/mmu_oea64.c                                          =
                        |    363 +-
 head/sys/powerpc/aim/moea64_native.c                                      =
                        |     45 +-
 head/sys/powerpc/conf/GENERIC                                             =
                        |      3 +-
 head/sys/powerpc/conf/GENERIC64                                           =
                        |      3 +-
 head/sys/powerpc/conf/MPC85XX                                             =
                        |      3 +-
 head/sys/powerpc/include/cpu.h                                            =
                        |      3 +-
 head/sys/powerpc/include/pmap.h                                           =
                        |      7 +-
 head/sys/powerpc/include/pmc_mdep.h                                       =
                        |      5 +-
 head/sys/powerpc/include/trap.h                                           =
                        |      6 +-
 head/sys/powerpc/include/trap_aim.h                                       =
                        |      7 +-
 head/sys/powerpc/include/trap_booke.h                                     =
                        |      7 +-
 head/sys/powerpc/include/vm.h                                             =
                        |      3 +-
 head/sys/powerpc/powerpc/exec_machdep.c                                   =
                        |     16 +-
 head/sys/security/mac/mac_net.c                                           =
                        |      4 +-
 head/sys/security/mac/mac_syscalls.c                                      =
                        |     43 +-
 head/sys/sparc64/conf/GENERIC                                             =
                        |      5 +-
 head/sys/sparc64/pci/fire.c                                               =
                        |      9 +-
 head/sys/sparc64/pci/firereg.h                                            =
                        |      9 +-
 head/sys/sparc64/sparc64/intr_machdep.c                                   =
                        |      5 +-
 head/sys/sparc64/sparc64/machdep.c                                        =
                        |      9 +-
 head/sys/sparc64/sparc64/trap.c                                           =
                        |     13 +-
 head/sys/sys/bus.h                                                        =
                        |      3 +-
 head/sys/sys/conf.h                                                       =
                        |      6 +-
 head/sys/sys/elf_common.h                                                 =
                        |      4 +-
 head/sys/sys/event.h                                                      =
                        |      4 +-
 head/sys/sys/kdb.h                                                        =
                        |     16 +-
 head/sys/sys/ktrace.h                                                     =
                        |     23 +-
 head/sys/sys/libkern.h                                                    =
                        |      8 +-
 head/sys/sys/mman.h                                                       =
                        |      8 +-
 head/sys/sys/mount.h                                                      =
                        |     14 +-
 head/sys/sys/param.h                                                      =
                        |      4 +-
 head/sys/sys/pmc.h                                                        =
                        |     72 +-
 head/sys/sys/pmckern.h                                                    =
                        |     99 +-
 head/sys/sys/pmclog.h                                                     =
                        |     19 +-
 head/sys/sys/proc.h                                                       =
                        |      4 +-
 head/sys/sys/sdt.h                                                        =
                        |      6 +-
 head/sys/sys/signal.h                                                     =
                        |      3 +-
 head/sys/sys/sysctl.h                                                     =
                        |      3 +-
 head/sys/sys/tty.h                                                        =
                        |      2 +-
 head/sys/sys/umtx.h                                                       =
                        |      7 +-
 head/sys/sys/vnode.h                                                      =
                        |      4 +-
 head/sys/ufs/ffs/ffs_balloc.c                                             =
                        |     10 +-
 head/sys/ufs/ffs/ffs_extern.h                                             =
                        |      9 +-
 head/sys/ufs/ffs/ffs_inode.c                                              =
                        |     31 +-
 head/sys/ufs/ffs/ffs_rawread.c                                            =
                        |      4 +-
 head/sys/ufs/ffs/ffs_snapshot.c                                           =
                        |     41 +-
 head/sys/ufs/ffs/ffs_softdep.c                                            =
                        |    105 +-
 head/sys/ufs/ffs/ffs_vfsops.c                                             =
                        |    103 +-
 head/sys/ufs/ffs/ffs_vnops.c                                              =
                        |     16 +-
 head/sys/ufs/ufs/ufs_quota.c                                              =
                        |      5 +-
 head/sys/ufs/ufs/ufs_vnops.c                                              =
                        |     46 +-
 head/sys/vm/vm_fault.c                                                    =
                        |     31 +-
 head/sys/vm/vm_mmap.c                                                     =
                        |      5 +-
 head/sys/vm/vm_page.c                                                     =
                        |     31 +-
 head/sys/vm/vm_page.h                                                     =
                        |      8 +-
 head/sys/vm/vm_reserv.c                                                   =
                        |     14 +-
 head/sys/vm/vnode_pager.c                                                 =
                        |      6 +-
 head/sys/x86/acpica/madt.c                                                =
                        |     16 +-
 head/sys/x86/include/endian.h                                             =
                        |      6 +-
 head/sys/x86/include/mca.h                                                =
                        |      4 +-
 head/sys/x86/include/segments.h                                           =
                        |      4 +-
 head/sys/x86/include/specialreg.h                                         =
                        |     39 +-
 head/sys/x86/isa/isa_dma.c                                                =
                        |      7 +-
 head/sys/x86/pci/pci_bus.c                                                =
                        |     25 +-
 head/sys/x86/x86/intr_machdep.c                                           =
                        |      5 +-
 head/sys/x86/x86/mca.c                                                    =
                        |    122 +-
 head/sys/x86/x86/mptable_pci.c                                            =
                        |     16 +-
 head/tools/build/mk/OptionalObsoleteFiles.inc                             =
                        |    658 +-
 head/tools/make_libdeps.sh                                                =
                        |      4 +-
 head/tools/regression/lib/msun/test-rem.c                                 =
                        |     42 +-
 head/tools/tools/ath/athdecode/main.c                                     =
                        |      4 +-
 head/tools/tools/ath/athrd/athrd.1                                        =
                        |     12 +-
 head/tools/tools/ath/common/dumpregs_5416.c                               =
                        |      4 +-
 head/tools/tools/ether_reflect/ether_reflect.1                            =
                        |      4 +-
 head/tools/tools/net80211/wlanstats/wlanstats.c                           =
                        |     14 +-
 head/tools/tools/netmap/bridge.c                                          =
                        |     90 +-
 head/tools/tools/netmap/pcap.c                                            =
                        |      3 +-
 head/tools/tools/vimage/vimage.8                                          =
                        |      8 +-
 head/usr.bin/Makefile                                                     =
                        |      7 +-
 head/usr.bin/bsdiff/bsdiff/bsdiff.1                                       =
                        |      4 +-
 head/usr.bin/calendar/calendar.1                                          =
                        |      7 +-
 head/usr.bin/calendar/calendars/calendar.freebsd                          =
                        |      4 +-
 head/usr.bin/clang/bugpoint/Makefile                                      =
                        |      4 +-
 head/usr.bin/clang/bugpoint/bugpoint.1                                    =
                        |      4 +-
 head/usr.bin/clang/clang/Makefile                                         =
                        |     28 +-
 head/usr.bin/clang/clang/clang.1                                          =
                        |      6 +-
 head/usr.bin/clang/llc/llc.1                                              =
                        |      6 +-
 head/usr.bin/clang/lli/Makefile                                           =
                        |      4 +-
 head/usr.bin/clang/lli/lli.1                                              =
                        |      4 +-
 head/usr.bin/clang/llvm-ar/llvm-ar.1                                      =
                        |      4 +-
 head/usr.bin/clang/llvm-as/llvm-as.1                                      =
                        |      4 +-
 head/usr.bin/clang/llvm-bcanalyzer/llvm-bcanalyzer.1                      =
                        |      4 +-
 head/usr.bin/clang/llvm-diff/llvm-diff.1                                  =
                        |      4 +-
 head/usr.bin/clang/llvm-dis/llvm-dis.1                                    =
                        |      4 +-
 head/usr.bin/clang/llvm-extract/llvm-extract.1                            =
                        |      4 +-
 head/usr.bin/clang/llvm-ld/Makefile                                       =
                        |      4 +-
 head/usr.bin/clang/llvm-ld/llvm-ld.1                                      =
                        |      4 +-
 head/usr.bin/clang/llvm-link/llvm-link.1                                  =
                        |      4 +-
 head/usr.bin/clang/llvm-nm/llvm-nm.1                                      =
                        |      4 +-
 head/usr.bin/clang/llvm-prof/llvm-prof.1                                  =
                        |      4 +-
 head/usr.bin/clang/llvm-ranlib/llvm-ranlib.1                              =
                        |      4 +-
 head/usr.bin/clang/opt/Makefile                                           =
                        |      4 +-
 head/usr.bin/clang/opt/opt.1                                              =
                        |      4 +-
 head/usr.bin/clang/tblgen/Makefile                                        =
                        |      8 +-
 head/usr.bin/clang/tblgen/tblgen.1                                        =
                        |     50 +-
 head/usr.bin/comm/comm.1                                                  =
                        |      4 +-
 head/usr.bin/compile_et/Makefile                                          =
                        |      8 +-
 head/usr.bin/csup/cpasswd.1                                               =
                        |      4 +-
 head/usr.bin/csup/csup.1                                                  =
                        |     26 +-
 head/usr.bin/find/find.1                                                  =
                        |     27 +-
 head/usr.bin/fstat/fstat.c                                                =
                        |     31 +-
 head/usr.bin/fstat/fuser.1                                                =
                        |      4 +-
 head/usr.bin/hexdump/hexdump.1                                            =
                        |     32 +-
 head/usr.bin/hexdump/od.1                                                 =
                        |      4 +-
 head/usr.bin/indent/indent.1                                              =
                        |      5 +-
 head/usr.bin/ipcrm/ipcrm.1                                                =
                        |      4 +-
 head/usr.bin/jot/jot.1                                                    =
                        |      3 +-
 head/usr.bin/kdump/Makefile                                               =
                        |      4 +-
 head/usr.bin/kdump/kdump.1                                                =
                        |      6 +-
 head/usr.bin/kdump/kdump.c                                                =
                        |     35 +-
 head/usr.bin/kdump/mkioctls                                               =
                        |      4 +-
 head/usr.bin/kdump/mksubr                                                 =
                        |     25 +-
 head/usr.bin/killall/killall.1                                            =
                        |      4 +-
 head/usr.bin/ktrace/ktrace.1                                              =
                        |      8 +-
 head/usr.bin/ktrace/ktrace.h                                              =
                        |      5 +-
 head/usr.bin/ktrace/subr.c                                                =
                        |      5 +-
 head/usr.bin/lex/flex.skl                                                 =
                        |      8 +-
 head/usr.bin/locale/locale.1                                              =
                        |      6 +-
 head/usr.bin/lockf/lockf.1                                                =
                        |      4 +-
 head/usr.bin/m4/eval.c                                                    =
                        |      7 +-
 head/usr.bin/m4/extern.h                                                  =
                        |      3 +-
 head/usr.bin/m4/main.c                                                    =
                        |      6 +-
 head/usr.bin/man/man.conf.5                                               =
                        |      4 +-
 head/usr.bin/ministat/ministat.1                                          =
                        |      6 +-
 head/usr.bin/mkulzma/mkulzma.8                                            =
                        |      4 +-
 head/usr.bin/netstat/if.c                                                 =
                        |      6 +-
 head/usr.bin/netstat/inet.c                                               =
                        |      6 +-
 head/usr.bin/printf/printf.1                                              =
                        |      4 +-
 head/usr.bin/procstat/procstat.1                                          =
                        |      8 +-
 head/usr.bin/procstat/procstat_bin.c                                      =
                        |     18 +-
 head/usr.bin/procstat/procstat_files.c                                    =
                        |     12 +-
 head/usr.bin/rctl/rctl.8                                                  =
                        |     51 +-
 head/usr.bin/sed/sed.1                                                    =
                        |      6 +-
 head/usr.bin/setchannel/setchannel.1                                      =
                        |      3 +-
 head/usr.bin/tftp/tftp.1                                                  =
                        |     23 +-
 head/usr.bin/top/top.local.1                                              =
                        |     20 +-
 head/usr.bin/touch/touch.1                                                =
                        |     14 +-
 head/usr.bin/tr/tr.1                                                      =
                        |     50 +-
 head/usr.bin/truss/Makefile                                               =
                        |      4 +-
 head/usr.bin/unifdef/unifdef.1                                            =
                        |      3 +-
 head/usr.bin/units/units.1                                                =
                        |     36 +-
 head/usr.bin/unzip/unzip.1                                                =
                        |      5 +-
 head/usr.bin/unzip/unzip.c                                                =
                        |    113 +-
 head/usr.bin/vgrind/vgrindefs.5                                           =
                        |      5 +-
 head/usr.bin/vmstat/vmstat.c                                              =
                        |     24 +-
 head/usr.bin/wall/wall.1                                                  =
                        |      8 +-
 head/usr.bin/wall/wall.c                                                  =
                        |     84 +-
 head/usr.bin/xlint/Makefile.inc                                           =
                        |      4 +-
 head/usr.sbin/Makefile                                                    =
                        |      3 +-
 head/usr.sbin/Makefile.mips                                               =
                        |      6 +-
 head/usr.sbin/ac/ac.8                                                     =
                        |      4 +-
 head/usr.sbin/acpi/iasl/Makefile                                          =
                        |     15 +-
 head/usr.sbin/adduser/adduser.conf.5                                      =
                        |      4 +-
 head/usr.sbin/apmd/apmd.8                                                 =
                        |      4 +-
 head/usr.sbin/arp/arp.4                                                   =
                        |      4 +-
 head/usr.sbin/arp/arp.c                                                   =
                        |      6 +-
 head/usr.sbin/bluetooth/ath3kfw/ath3kfw.8                                 =
                        |      6 +-
 head/usr.sbin/boot0cfg/boot0cfg.8                                         =
                        |      3 +-
 head/usr.sbin/bootparamd/bootparamd/bootparamd.8                          =
                        |      4 +-
 head/usr.sbin/bsdinstall/bsdinstall.8                                     =
                        |      6 +-
 head/usr.sbin/bsdinstall/partedit/gpart_ops.c                             =
                        |      4 +-
 head/usr.sbin/bsnmpd/modules/snmp_netgraph/snmp_netgraph.3                =
                        |      5 +-
 head/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3                        =
                        |     14 +-
 head/usr.sbin/bsnmpd/tools/bsnmptools/bsnmpget.1                          =
                        |      5 +-
 head/usr.sbin/cdcontrol/cdcontrol.1                                       =
                        |      4 +-
 head/usr.sbin/config/config.8                                             =
                        |      8 +-
 head/usr.sbin/ctladm/ctladm.8                                             =
                        |     33 +-
 head/usr.sbin/edquota/edquota.8                                           =
                        |      4 +-
 head/usr.sbin/faithd/faithd.8                                             =
                        |     16 +-
 head/usr.sbin/fdwrite/fdwrite.1                                           =
                        |      4 +-
 head/usr.sbin/freebsd-update/freebsd-update.8                             =
                        |      4 +-
 head/usr.sbin/fwcontrol/fwcontrol.8                                       =
                        |      8 +-
 head/usr.sbin/gpioctl/gpioctl.8                                           =
                        |      7 +-
 head/usr.sbin/i2c/i2c.8                                                   =
                        |     10 +-
 head/usr.sbin/ifmcstat/ifmcstat.8                                         =
                        |      3 +-
 head/usr.sbin/lmcconfig/lmcconfig.8                                       =
                        |      6 +-
 head/usr.sbin/lpr/lpc/cmds.c                                              =
                        |     10 +-
 head/usr.sbin/lpr/lpr/printcap.5                                          =
                        |      4 +-
 head/usr.sbin/makefs/cd9660/cd9660_eltorito.c                             =
                        |     38 +-
 head/usr.sbin/mfiutil/mfi_config.c                                        =
                        |      9 +-
 head/usr.sbin/mfiutil/mfi_drive.c                                         =
                        |      4 +-
 head/usr.sbin/mfiutil/mfiutil.8                                           =
                        |      7 +-
 head/usr.sbin/mountd/exports.5                                            =
                        |      6 +-
 head/usr.sbin/mptutil/mptutil.8                                           =
                        |      7 +-
 head/usr.sbin/mtest/mtest.8                                               =
                        |      3 +-
 head/usr.sbin/mtree/mtree.5                                               =
                        |      3 +-
 head/usr.sbin/newsyslog/newsyslog.c                                       =
                        |      9 +-
 head/usr.sbin/newsyslog/newsyslog.conf.5                                  =
                        |      8 +-
 head/usr.sbin/nfsd/nfsv4.4                                                =
                        |      4 +-
 head/usr.sbin/ntp/doc/ntp-keygen.8                                        =
                        |      3 +-
 head/usr.sbin/ntp/doc/ntpdate.8                                           =
                        |      3 +-
 head/usr.sbin/pciconf/pciconf.8                                           =
                        |      4 +-
 head/usr.sbin/pkg_install/updating/pkg_updating.1                         =
                        |      8 +-
 head/usr.sbin/pmcstat/pmcpl_calltree.c                                    =
                        |    626 +-
 head/usr.sbin/pmcstat/pmcstat.8                                           =
                        |      4 +-
 head/usr.sbin/pmcstat/pmcstat_log.c                                       =
                        |     42 +-
 head/usr.sbin/powerd/powerd.c                                             =
                        |      5 +-
 head/usr.sbin/rtadvd/rtadvd.8                                             =
                        |      4 +-
 head/usr.sbin/rtadvd/rtadvd.conf.5                                        =
                        |     10 +-
 head/usr.sbin/setfib/setfib.1                                             =
                        |      4 +-
 head/usr.sbin/tcpdump/tcpdump/tcpdump.1                                   =
                        |     18 +-
 head/usr.sbin/timed/timed/timed.8                                         =
                        |      8 +-
 head/usr.sbin/utx/utx.8                                                   =
                        |      3 +-
 head/usr.sbin/wlandebug/wlandebug.8                                       =
                        |      4 +-
 head/usr.sbin/wlconfig/wlconfig.8                                         =
                        |     10 +-
 head/usr.sbin/ypserv/ypserv.8                                             =
                        |      4 +-
 5218 files changed, 303068 insertions(+), 216015 deletions(-)

diffs (901657 lines):

diff -r 428842767fa6 -r f2935497fa04 head/Makefile
--- a/head/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/Makefile 232907 2012-03-13 00:38:49Z jmallett $
+# $FreeBSD: head/Makefile 233644 2012-03-29 02:54:35Z jmallett $
 #
 # The user-driven targets are:
 #
@@ -132,20 +132,19 @@
=20
 # Guess machine architecture from machine type, and vice versa.
 .if !defined(TARGET_ARCH) && defined(TARGET)
-_TARGET_ARCH=3D	${TARGET:S/pc98/i386/:S/mips/mipsel/}
+_TARGET_ARCH=3D	${TARGET:S/pc98/i386/}
 .elif !defined(TARGET) && defined(TARGET_ARCH) && \
     ${TARGET_ARCH} !=3D ${MACHINE_ARCH}
-_TARGET=3D		${TARGET_ARCH:C/mips.*e[lb]/mips/:C/armeb/arm/}
+_TARGET=3D		${TARGET_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/}
 .endif
-# Legacy names, for a transition period mips:mips -> mipsel:mips
+# Legacy names, for another transition period mips:mips(n32|64)?eb -> mips=
:mips\1
 .if defined(TARGET) && defined(TARGET_ARCH) && \
-    ${TARGET_ARCH} =3D=3D "mips" && ${TARGET} =3D=3D "mips"
-.warning "TARGET_ARCH of mips is deprecated in favor of mipsel or mipseb"
-.if defined(TARGET_BIG_ENDIAN)
-_TARGET_ARCH=3Dmipseb
-.else
-_TARGET_ARCH=3Dmipsel
+    ${TARGET} =3D=3D "mips" && ${TARGET_ARCH:Mmips*eb}
+_TARGET_ARCH=3D		${TARGET_ARCH:C/eb$//}
+.warning "TARGET_ARCH of ${TARGET_ARCH} is deprecated in favor of ${_TARGE=
T_ARCH}"
 .endif
+.if defined(TARGET) && ${TARGET} =3D=3D "mips" && defined(TARGET_BIG_ENDIA=
N)
+.warning "TARGET_BIG_ENDIAN is no longer necessary for MIPS.  Big-endian i=
s not the default."
 .endif
 # arm with TARGET_BIG_ENDIAN -> armeb
 .if defined(TARGET_ARCH) && ${TARGET_ARCH} =3D=3D "arm" && defined(TARGET_=
BIG_ENDIAN)
@@ -331,7 +330,7 @@
 .if make(universe) || make(universe_kernels) || make(tinderbox) || make(ta=
rgets)
 TARGETS?=3Damd64 arm i386 ia64 mips pc98 powerpc sparc64
 TARGET_ARCHES_arm?=3D	arm armeb
-TARGET_ARCHES_mips?=3D	mipsel mipseb mips64el mips64eb mipsn32eb
+TARGET_ARCHES_mips?=3D	mipsel mips mips64el mips64 mipsn32
 TARGET_ARCHES_powerpc?=3D	powerpc powerpc64
 TARGET_ARCHES_pc98?=3D	i386
 .for target in ${TARGETS}
diff -r 428842767fa6 -r f2935497fa04 head/Makefile.inc1
--- a/head/Makefile.inc1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/Makefile.inc1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/Makefile.inc1 233098 2012-03-17 22:12:09Z peter $
+# $FreeBSD: head/Makefile.inc1 233645 2012-03-29 03:04:59Z jmallett $
 #
 # Make command line options:
 #	-DNO_CLEANDIR run ${MAKE} clean, instead of ${MAKE} cleandir
@@ -137,7 +137,7 @@
 VERSION+=3D	${OSRELDATE}
 .endif
=20
-KNOWN_ARCHES?=3D	amd64 arm armeb/arm i386 i386/pc98 ia64 mipsel/mips mipse=
b/mips mips64el/mips mips64eb/mips mipsn32el/mips mipsn32eb/mips powerpc po=
werpc64/powerpc sparc64
+KNOWN_ARCHES?=3D	amd64 arm armeb/arm i386 i386/pc98 ia64 mips mipsel/mips =
mips64el/mips mips64/mips mipsn32el/mips mipsn32/mips powerpc powerpc64/pow=
erpc sparc64
 .if ${TARGET} =3D=3D ${TARGET_ARCH}
 _t=3D		${TARGET}
 .else
@@ -471,13 +471,6 @@
 	    -p ${LIB32TMP}/usr/include >/dev/null
 	mkdir -p ${WORLDTMP}
 	ln -sf ${.CURDIR}/sys ${WORLDTMP}
-.if ${MK_KERBEROS} !=3D "no"
-.for _t in obj depend all
-	cd ${.CURDIR}/kerberos5/tools; \
-	    MAKEOBJDIRPREFIX=3D${OBJTREE}/lib32 ${MAKE} SSP_CFLAGS=3D DESTDIR=3D \
-	    DIRPRFX=3Dkerberos5/tools/ ${_t}
-.endfor
-.endif
 .for _t in obj includes
 	cd ${.CURDIR}/include; ${LIB32WMAKE} DIRPRFX=3Dinclude/ ${_t}
 	cd ${.CURDIR}/lib; ${LIB32WMAKE} DIRPRFX=3Dlib/ ${_t}
@@ -1071,9 +1064,11 @@
 	usr.bin/clang/clang-tblgen
 .endif
=20
+# dtrace tools are required for older bootstrap env and cross-build
 .if ${MK_CDDL} !=3D "no" && \
-    ${BOOTSTRAPPING} < 800038 && \
-    !(${BOOTSTRAPPING} >=3D 700112 && ${BOOTSTRAPPING} < 799999)
+    ((${BOOTSTRAPPING} < 800038 && \
+          !(${BOOTSTRAPPING} >=3D 700112 && ${BOOTSTRAPPING} < 799999)) \
+      || (${MACHINE} !=3D ${TARGET} || ${MACHINE_ARCH} !=3D ${TARGET_ARCH}=
))
 _dtrace_tools=3D cddl/usr.bin/sgsmsg cddl/lib/libctf lib/libelf \
     lib/libdwarf cddl/usr.bin/ctfconvert cddl/usr.bin/ctfmerge
 .endif
@@ -1082,12 +1077,22 @@
 _dtc=3D gnu/usr.bin/dtc
 .endif
=20
+.if ${MK_KERBEROS} !=3D "no"
+_kerberos5_bootstrap_tools=3D \
+	kerberos5/tools/make-roken \
+	kerberos5/lib/libroken \
+	kerberos5/lib/libvers \
+	kerberos5/tools/asn1_compile \
+	kerberos5/tools/slc
+.endif
+
 #	Please document (add comment) why something is in 'bootstrap-tools'.
 #	Try to bound the building of the bootstrap-tool to just the
 #	FreeBSD versions that need the tool built at this stage of the build.
 bootstrap-tools:
 .for _tool in \
     ${_clang_tblgen} \
+    ${_kerberos5_bootstrap_tools} \
     ${_dtrace_tools} \
     ${_strfile} \
     ${_gperf} \
@@ -1129,10 +1134,6 @@
 _gcc_tools=3D gnu/usr.bin/cc/cc_tools
 .endif
=20
-.if ${MK_KERBEROS} !=3D "no"
-_kerberos5_tools=3D kerberos5/tools
-.endif
-
 .if ${MK_RESCUE} !=3D "no"
 _rescue=3D rescue/rescue
 .endif
@@ -1157,8 +1158,7 @@
 		${MAKE} DIRPRFX=3D${_tool}/ build-tools
 .endfor
 .for _tool in \
-    ${_gcc_tools} \
-    ${_kerberos5_tools}
+    ${_gcc_tools}
 	${_+_}@${ECHODIR} "=3D=3D=3D> ${_tool} (obj,depend,all)"; \
 		cd ${.CURDIR}/${_tool}; \
 		${MAKE} DIRPRFX=3D${_tool}/ obj; \
@@ -1264,11 +1264,16 @@
 lib/libcxxrt__L: gnu/lib/libgcc__L
 .endif
=20
-_prebuild_libs=3D	${_kerberos5_lib_libasn1} ${_kerberos5_lib_libhdb} \
+_prebuild_libs=3D	${_kerberos5_lib_libasn1} \
+		${_kerberos5_lib_libhdb} \
+		${_kerberos5_lib_libheimbase} \
 		${_kerberos5_lib_libheimntlm} \
+		${_kerberos5_lib_libheimsqlite} \
+		${_kerberos5_lib_libheimipcc} \
 		${_kerberos5_lib_libhx509} ${_kerberos5_lib_libkrb5} \
 		${_kerberos5_lib_libroken} \
-		lib/libbz2 lib/libcom_err lib/libcrypt \
+		${_kerberos5_lib_libwind} \
+		lib/libbz2 ${_libcom_err} lib/libcrypt \
 		lib/libexpat \
 		${_lib_libgssapi} ${_lib_libipx} \
 		lib/libkiconv lib/libkvm lib/liblzma lib/libmd \
@@ -1318,14 +1323,21 @@
 .if ${MK_KERBEROS} !=3D "no"
 kerberos5/lib/libasn1__L: lib/libcom_err__L kerberos5/lib/libroken__L
 kerberos5/lib/libhdb__L: kerberos5/lib/libasn1__L lib/libcom_err__L \
-    kerberos5/lib/libkrb5__L kerberos5/lib/libroken__L
-kerberos5/lib/libheimntlm__L: secure/lib/libcrypto__L kerberos5/lib/libkrb=
5__L
+    kerberos5/lib/libkrb5__L kerberos5/lib/libroken__L \
+    kerberos5/lib/libwind__L kerberos5/lib/libheimsqlite__L=20
+kerberos5/lib/libheimntlm__L: secure/lib/libcrypto__L kerberos5/lib/libkrb=
5__L \
+    kerberos5/lib/libroken__L lib/libcom_err__L
 kerberos5/lib/libhx509__L: kerberos5/lib/libasn1__L lib/libcom_err__L \
-    secure/lib/libcrypto__L kerberos5/lib/libroken__L
+    secure/lib/libcrypto__L kerberos5/lib/libroken__L kerberos5/lib/libwin=
d__L
 kerberos5/lib/libkrb5__L: kerberos5/lib/libasn1__L lib/libcom_err__L \
     lib/libcrypt__L secure/lib/libcrypto__L kerberos5/lib/libhx509__L \
-    kerberos5/lib/libroken__L
+    kerberos5/lib/libroken__L kerberos5/lib/libwind__L \
+    kerberos5/lib/libheimbase__L kerberos5/lib/libheimipcc__L
 kerberos5/lib/libroken__L: lib/libcrypt__L
+kerberos5/lib/libwind__L: kerberos5/lib/libroken__L lib/libcom_err__L
+kerberos5/lib/libheimbase__L: lib/libthr__L
+kerberos5/lib/libheimipcc__L: kerberos5/lib/libroken__L kerberos5/lib/libh=
eimbase__L lib/libthr__L
+kerberos5/lib/libheimsqlite__L: lib/libthr__L
 .endif
=20
 .if ${MK_GSSAPI} !=3D "no"
@@ -1340,10 +1352,15 @@
 _kerberos5_lib=3D	kerberos5/lib
 _kerberos5_lib_libasn1=3D kerberos5/lib/libasn1
 _kerberos5_lib_libhdb=3D kerberos5/lib/libhdb
+_kerberos5_lib_libheimbase=3D kerberos5/lib/libheimbase
 _kerberos5_lib_libkrb5=3D kerberos5/lib/libkrb5
 _kerberos5_lib_libhx509=3D kerberos5/lib/libhx509
 _kerberos5_lib_libroken=3D kerberos5/lib/libroken
 _kerberos5_lib_libheimntlm=3D kerberos5/lib/libheimntlm
+_kerberos5_lib_libheimsqlite=3D kerberos5/lib/libheimsqlite
+_kerberos5_lib_libheimipcc=3D kerberos5/lib/libheimipcc
+_kerberos5_lib_libwind=3D kerberos5/lib/libwind
+_libcom_err=3D lib/libcom_err
 .endif
=20
 .if ${MK_NIS} !=3D "no"
diff -r 428842767fa6 -r f2935497fa04 head/ObsoleteFiles.inc
--- a/head/ObsoleteFiles.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/ObsoleteFiles.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/ObsoleteFiles.inc 233010 2012-03-15 17:01:25Z pluknet $
+# $FreeBSD: head/ObsoleteFiles.inc 234353 2012-04-16 21:23:25Z dim $
 #
 # This file lists old files (OLD_FILES), libraries (OLD_LIBS) and
 # directories (OLD_DIRS) which should get removed at an update. Recently
@@ -38,6 +38,63 @@
 #   xargs -n1 | sort | uniq -d;
 # done
=20
+# 20120415: new clang import which bumps version from 3.0 to 3.1
+OLD_FILES+=3Dusr/include/clang/3.0/altivec.h
+OLD_FILES+=3Dusr/include/clang/3.0/avxintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/emmintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/immintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/mm3dnow.h
+OLD_FILES+=3Dusr/include/clang/3.0/mm_malloc.h
+OLD_FILES+=3Dusr/include/clang/3.0/mmintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/nmmintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/pmmintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/smmintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/tmmintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/wmmintrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/x86intrin.h
+OLD_FILES+=3Dusr/include/clang/3.0/xmmintrin.h
+OLD_DIRS+=3Dusr/include/clang/3.0
+# 20120322: Update heimdal to 1.5.1.
+OLD_FILES+=3Dusr/include/krb5-v4compat.h \
+	usr/include/krb_err.h \
+	usr/include/hdb-private.h \
+        usr/share/man/man3/krb5_addresses.3.gz \
+        usr/share/man/man3/krb5_cc_cursor.3.gz \
+        usr/share/man/man3/krb5_cc_ops.3.gz \
+        usr/share/man/man3/krb5_config.3.gz \
+        usr/share/man/man3/krb5_config_get_int_default.3.gz \
+        usr/share/man/man3/krb5_context.3.gz \
+        usr/share/man/man3/krb5_data.3.gz \
+        usr/share/man/man3/krb5_err.3.gz \
+        usr/share/man/man3/krb5_errx.3.gz \
+        usr/share/man/man3/krb5_keyblock.3.gz \
+        usr/share/man/man3/krb5_keytab_entry.3.gz \
+        usr/share/man/man3/krb5_kt_cursor.3.gz \
+        usr/share/man/man3/krb5_kt_ops.3.gz \
+        usr/share/man/man3/krb5_set_warn_dest.3.gz \
+        usr/share/man/man3/krb5_verr.3.gz \
+        usr/share/man/man3/krb5_verrx.3.gz \
+        usr/share/man/man3/krb5_vwarnx.3.gz \
+        usr/share/man/man3/krb5_warn.3.gz \
+        usr/share/man/man3/krb5_warnx.3.gz
+OLD_LIBS+=3Dusr/lib/libasn1.so.10 \
+	usr/lib/libhdb.so.10 \
+	usr/lib/libheimntlm.so.10 \
+	usr/lib/libhx509.so.10 \
+	usr/lib/libkadm5clnt.so.10 \
+	usr/lib/libkadm5srv.so.10 \
+	usr/lib/libkafs5.so.10 \
+	usr/lib/libkrb5.so.10 \
+	usr/lib/libroken.so.10 \
+	usr/lib32/libasn1.so.10 \
+	usr/lib32/libhdb.so.10 \
+	usr/lib32/libheimntlm.so.10 \
+	usr/lib32/libhx509.so.10 \
+	usr/lib32/libkadm5clnt.so.10 \
+	usr/lib32/libkadm5srv.so.10 \
+	usr/lib32/libkafs5.so.10 \
+	usr/lib32/libkrb5.so.10 \
+	usr/lib32/libroken.so.10
 # 20120309: Remove fifofs header files.
 OLD_FILES+=3Dusr/include/fs/fifofs/fifo.h
 OLD_DIRS+=3Dusr/include/fs/fifofs
@@ -4567,9 +4624,7 @@
 OLD_FILES+=3Dusr/share/man/man3/SSL_COMP_add_compression_method.3.gz
 OLD_FILES+=3Dusr/share/man/man3/SSL_CTX_get_ex_new_index.3.gz
 OLD_FILES+=3Dusr/share/man/man3/archive_entry_dup.3.gz
-OLD_FILES+=3Dusr/share/man/man3/archive_entry_hardlink_w.3.gz
 OLD_FILES+=3Dusr/share/man/man3/archive_entry_set_tartype.3.gz
-OLD_FILES+=3Dusr/share/man/man3/archive_entry_symlink_w.3.gz
 OLD_FILES+=3Dusr/share/man/man3/archive_entry_tartype.3.gz
 OLD_FILES+=3Dusr/share/man/man3/archive_read_data_into_file.3.gz
 OLD_FILES+=3Dusr/share/man/man3/archive_read_open_tar.3.gz
diff -r 428842767fa6 -r f2935497fa04 head/UPDATING
--- a/head/UPDATING	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/UPDATING	Tue Apr 17 11:51:51 2012 +0300
@@ -22,6 +22,13 @@
 	machines to maximize performance.  (To disable malloc debugging, run
 	ln -s aj /etc/malloc.conf.)
=20
+20120328:
+	Big-endian MIPS TARGET_ARCH values no longer end in "eb".  mips64eb
+	is now spelled mips64.  mipsn32eb is now spelled mipsn32.  mipseb is
+	now spelled mips.  This is to aid compatibility with third-party
+	software that expects this naming scheme in uname(3).  Little-endian
+	settings are unchanged.
+
 20120306:
 	Disable by default the option VFS_ALLOW_NONMPSAFE for all supported
 	platforms.
@@ -1569,4 +1576,4 @@
 Contact Warner Losh if you have any questions about your use of
 this document.
=20
-$FreeBSD: head/UPDATING 232619 2012-03-06 20:01:25Z attilio $
+$FreeBSD: head/UPDATING 233644 2012-03-29 02:54:35Z jmallett $
diff -r 428842767fa6 -r f2935497fa04 head/bin/kenv/kenv.1
--- a/head/bin/kenv/kenv.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/bin/kenv/kenv.1	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/bin/kenv/kenv.1 233457 2012-03-25 09:20:14Z joel $
 .\"
 .Dd January 13, 2009
 .Dt KENV 1
@@ -84,7 +84,6 @@
 character except '=3D' is acceptable as part of a name.  Quotes
 are optional and necessary only if the value contains
 whitespace.
-.Pp
 .Sh SEE ALSO
 .Xr kenv 2 ,
 .Xr config 5 ,
diff -r 428842767fa6 -r f2935497fa04 head/bin/ps/ps.1
--- a/head/bin/ps/ps.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/bin/ps/ps.1	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)ps.1	8.3 (Berkeley) 4/18/94
-.\" $FreeBSD: head/bin/ps/ps.1 232694 2012-03-08 13:00:49Z kib $
+.\" $FreeBSD: head/bin/ps/ps.1 233665 2012-03-29 16:02:40Z joel $
 .\"
 .Dd March 8, 2012
 .Dt PS 1
@@ -292,37 +292,37 @@
 the include file
 .In sys/proc.h :
 .Bl -column P_SINGLE_BOUNDARY 0x40000000
-.It Dv "P_ADVLOCK" Ta No "0x00001	Process may hold a POSIX advisory lock"
-.It Dv "P_CONTROLT" Ta No "0x00002	Has a controlling terminal"
-.It Dv "P_KTHREAD" Ta No "0x00004	Kernel thread"
-.It Dv "P_FOLLOWFORK" Ta No "0x00008	Attach debugger to new children"
-.It Dv "P_PPWAIT" Ta No "0x00010	Parent is waiting for child to exec/exit"
-.It Dv "P_PROFIL" Ta No "0x00020	Has started profiling"
-.It Dv "P_STOPPROF" Ta No "0x00040	Has thread in requesting to stop prof"
-.It Dv "P_HADTHREADS" Ta No "0x00080	Has had threads (no cleanup shortcuts=
)"
-.It Dv "P_SUGID" Ta No "0x00100		Had set id privileges since last exec"
-.It Dv "P_SYSTEM" Ta No "0x00200	System proc: no sigs, stats or swapping"
-.It Dv "P_SINGLE_EXIT" Ta No "0x00400	Threads suspending should exit, not =
wait"
-.It Dv "P_TRACED" Ta No "0x00800	Debugged process being traced"
-.It Dv "P_WAITED" Ta No "0x01000	Someone is waiting for us"
-.It Dv "P_WEXIT" Ta No "0x02000		Working on exiting"
-.It Dv "P_EXEC" Ta No "0x04000		Process called exec"
-.It Dv "P_WKILLED" Ta No "0x08000	Killed, shall go to kernel/user boundary=
 ASAP"
-.It Dv "P_CONTINUED" Ta No "0x10000	Proc has continued from a stopped stat=
e"
-.It Dv "P_STOPPED_SIG" Ta No "0x20000	Stopped due to SIGSTOP/SIGTSTP"
-.It Dv "P_STOPPED_TRACE" Ta No "0x40000	Stopped because of tracing"
-.It Dv "P_STOPPED_SINGLE" Ta No "0x80000	Only one thread can continue"
-.It Dv "P_PROTECTED" Ta No "0x100000	Do not kill on memory overcommit"
-.It Dv "P_SIGEVENT" Ta No "0x200000	Process pending signals changed"
-.It Dv "P_SINGLE_BOUNDARY" Ta No "0x400000	Threads should suspend at user =
boundary"
-.It Dv "P_HWPMC" Ta No "0x800000	Process is using HWPMCs"
-.It Dv "P_JAILED" Ta No "0x1000000	Process is in jail"
-.It Dv "P_ORPHAN" Ta No "0x2000000	Orphaned by original parent, reparented=
 to debugger"
-.It Dv "P_INEXEC" Ta No "0x4000000	Process is in execve()"
-.It Dv "P_STATCHILD" Ta No "0x8000000	Child process stopped or exited"
-.It Dv "P_INMEM" Ta No "0x10000000	Loaded into memory"
-.It Dv "P_SWAPPINGOUT" Ta No "0x20000000	Process is being swapped out"
-.It Dv "P_SWAPPINGIN" Ta No "0x40000000	Process is being swapped in"
+.It Dv "P_ADVLOCK" Ta No "0x00001" Ta "Process may hold a POSIX advisory l=
ock"
+.It Dv "P_CONTROLT" Ta No "0x00002" Ta "Has a controlling terminal"
+.It Dv "P_KTHREAD" Ta No "0x00004" Ta "Kernel thread"
+.It Dv "P_FOLLOWFORK" Ta No "0x00008" Ta "Attach debugger to new children"
+.It Dv "P_PPWAIT" Ta No "0x00010" Ta "Parent is waiting for child to exec/=
exit"
+.It Dv "P_PROFIL" Ta No "0x00020" Ta "Has started profiling"
+.It Dv "P_STOPPROF" Ta No "0x00040" Ta "Has thread in requesting to stop p=
rof"
+.It Dv "P_HADTHREADS" Ta No "0x00080" Ta "Has had threads (no cleanup shor=
tcuts)"
+.It Dv "P_SUGID" Ta No "0x00100" Ta "Had set id privileges since last exec"
+.It Dv "P_SYSTEM" Ta No "0x00200" Ta "System proc: no sigs, stats or swapp=
ing"
+.It Dv "P_SINGLE_EXIT" Ta No "0x00400" Ta "Threads suspending should exit,=
 not wait"
+.It Dv "P_TRACED" Ta No "0x00800" Ta "Debugged process being traced"
+.It Dv "P_WAITED" Ta No "0x01000" Ta "Someone is waiting for us"
+.It Dv "P_WEXIT" Ta No "0x02000" Ta "Working on exiting"
+.It Dv "P_EXEC" Ta No "0x04000" Ta "Process called exec"
+.It Dv "P_WKILLED" Ta No "0x08000" Ta "Killed, shall go to kernel/user bou=
ndary ASAP"
+.It Dv "P_CONTINUED" Ta No "0x10000" Ta "Proc has continued from a stopped=
 state"
+.It Dv "P_STOPPED_SIG" Ta No "0x20000" Ta "Stopped due to SIGSTOP/SIGTSTP"
+.It Dv "P_STOPPED_TRACE" Ta No "0x40000" Ta "Stopped because of tracing"
+.It Dv "P_STOPPED_SINGLE" Ta No "0x80000" Ta "Only one thread can continue"
+.It Dv "P_PROTECTED" Ta No "0x100000" Ta "Do not kill on memory overcommit"
+.It Dv "P_SIGEVENT" Ta No "0x200000" Ta "Process pending signals changed"
+.It Dv "P_SINGLE_BOUNDARY" Ta No "0x400000" Ta "Threads should suspend at =
user boundary"
+.It Dv "P_HWPMC" Ta No "0x800000" Ta "Process is using HWPMCs"
+.It Dv "P_JAILED" Ta No "0x1000000" Ta "Process is in jail"
+.It Dv "P_ORPHAN" Ta No "0x2000000" Ta "Orphaned by original parent, repar=
ented to debugger"
+.It Dv "P_INEXEC" Ta No "0x4000000" Ta "Process is in execve()"
+.It Dv "P_STATCHILD" Ta No "0x8000000" Ta "Child process stopped or exited"
+.It Dv "P_INMEM" Ta No "0x10000000" Ta "Loaded into memory"
+.It Dv "P_SWAPPINGOUT" Ta No "0x20000000" Ta "Process is being swapped out"
+.It Dv "P_SWAPPINGIN" Ta No "0x40000000" Ta "Process is being swapped in"
 .El
 .It Cm label
 The MAC label of the process.
diff -r 428842767fa6 -r f2935497fa04 head/bin/pwait/pwait.1
--- a/head/bin/pwait/pwait.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/bin/pwait/pwait.1	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 .\" OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/bin/pwait/pwait.1 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd November 1, 2009
 .Dt PWAIT 1
@@ -46,7 +46,7 @@
 .Sh DESCRIPTION
 The
 .Nm
-utility will wait until each of the given processes has terminated.=20
+utility will wait until each of the given processes has terminated.
 .Pp
 The following option is available:
 .Bl -tag -width indent
@@ -54,7 +54,6 @@
 Print the exit status when each process terminates.
 .El
 .Sh DIAGNOSTICS
-.Pp
 The
 .Nm
 utility returns 0 on success, and >0 if an error occurs.
diff -r 428842767fa6 -r f2935497fa04 head/bin/setfacl/setfacl.1
--- a/head/bin/setfacl/setfacl.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/bin/setfacl/setfacl.1	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/bin/setfacl/setfacl.1 220465 2011-04-09 07:42:25Z trasz=
 $
+.\" $FreeBSD: head/bin/setfacl/setfacl.1 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd April 9, 2011
 .Dt SETFACL 1
@@ -295,7 +295,7 @@
 the ACL entry.
 It may consist of one of the following: uid or
 user name, or gid or group name.  In entries whose tag type is
-one of=20
+one of
 .Dq Li owner@ ,
 .Dq Li group@ ,
 or
diff -r 428842767fa6 -r f2935497fa04 head/bin/sh/jobs.c
--- a/head/bin/sh/jobs.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/bin/sh/jobs.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
 #endif
 #endif /* not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/bin/sh/jobs.c 230998 2012-02-04 23:12:14Z jilles =
$");
+__FBSDID("$FreeBSD: head/bin/sh/jobs.c 233792 2012-04-02 17:16:24Z jilles =
$");
=20
 #include <sys/ioctl.h>
 #include <sys/param.h>
@@ -893,8 +893,8 @@
 	struct jmploc jmploc;
 	struct jmploc *savehandler;
=20
-	TRACE(("vforkexecshell(%%%td, %p, %d) called\n", jp - jobtab, (void *)n,
-	    mode));
+	TRACE(("vforkexecshell(%%%td, %s, %p) called\n", jp - jobtab, argv[0],
+	    (void *)pip));
 	INTOFF;
 	flushall();
 	savehandler =3D handler;
diff -r 428842767fa6 -r f2935497fa04 head/bin/sh/sh.1
--- a/head/bin/sh/sh.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/bin/sh/sh.1	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	from: @(#)sh.1	8.6 (Berkeley) 5/4/95
-.\" $FreeBSD: head/bin/sh/sh.1 227122 2011-11-05 21:56:45Z jilles $
+.\" $FreeBSD: head/bin/sh/sh.1 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd November 5, 2011
 .Dt SH 1
@@ -381,7 +381,7 @@
 .It Redirection operators:
 .Bl -column "XXX" "XXX" "XXX" "XXX" "XXX" -offset center -compact
 .It Li < Ta Li > Ta Li << Ta Li >> Ta Li <>
-.It Li <& Ta Li >& Ta Li <<- Ta Li >|
+.It Li <& Ta Li >& Ta Li <<- Ta Li >| Ta \&
 .El
 .El
 .Pp
@@ -1027,7 +1027,6 @@
 .Pp
 The first form executes the commands in a subshell environment.
 A subshell environment has its own copy of:
-.Pp
 .Bl -enum
 .It
 The current working directory as set by
@@ -1632,7 +1631,7 @@
 .It Constants
 Decimal, octal (starting with
 .Li 0 )
-and hexadecimal (starting with=20
+and hexadecimal (starting with
 .Li 0x )
 integer constants.
 .It Variables
diff -r 428842767fa6 -r f2935497fa04 head/bin/stty/stty.1
--- a/head/bin/stty/stty.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/bin/stty/stty.1	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)stty.1	8.4 (Berkeley) 4/18/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/bin/stty/stty.1 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd August 23, 2008
 .Dt STTY 1
@@ -90,7 +90,6 @@
 The following arguments are available to set the terminal
 characteristics:
 .Ss Control Modes:
-.Pp
 Control mode flags affect hardware characteristics associated with the
 terminal.
 This corresponds to the c_cflag in the termios structure.
@@ -256,7 +255,6 @@
 On the terminal NL performs (does not perform) the CR function.
 .El
 .Ss Local Modes:
-.Pp
 Local mode flags (lflags) affect various and sundry characteristics of ter=
minal
 processing.
 Historically the term "local" pertained to new job control features
@@ -386,7 +384,7 @@
 Recognized control-characters:
 .Bd -ragged -offset indent
 .Bl -column character Subscript
-.It control-
+.It control- Ta \& Ta \&
 .It character Ta Subscript Ta Description
 .It _________ Ta _________ Ta _______________
 .It eof Ta Tn VEOF Ta EOF No character
@@ -513,7 +511,6 @@
 first rows, then columns.
 .El
 .Ss Compatibility Modes:
-.Pp
 These modes remain for compatibility with the previous version of
 the
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/cddl/contrib/opensolaris/cmd/zpoo=
l/zpool.8
--- a/head/cddl/contrib/opensolaris/cmd/zpool/zpool.8	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/cddl/contrib/opensolaris/cmd/zpool/zpool.8	Tue Apr 17 11:51:51 2=
012 +0300
@@ -21,7 +21,7 @@
 .\" Copyright 2011, Nexenta Systems, Inc. All Rights Reserved.
 .\" Copyright (c) 2011, Justin T. Gibbs <gibbs at FreeBSD.org>
 .\"
-.\" $FreeBSD: head/cddl/contrib/opensolaris/cmd/zpool/zpool.8 228206 2011-=
12-02 19:56:46Z mm $
+.\" $FreeBSD: head/cddl/contrib/opensolaris/cmd/zpool/zpool.8 234336 2012-=
04-16 08:19:43Z mm $
 .\"
 .Dd November 28, 2011
 .Dt ZPOOL 8
@@ -1779,7 +1779,7 @@
 storage pool consisting of two, two-way
 mirrors and mirrored log devices:
 .Bd -literal -offset 2n
-.Li # Ic zpool create pool mirror da0 da1 mirror da2 da3 log miror da4 da5
+.Li # Ic zpool create pool mirror da0 da1 mirror da2 da3 log mirror da4 da5
 .Ed
 .It Sy Example 14 No Adding Cache Devices to a Tn ZFS No Pool
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/cddl/contrib/opensolaris/lib/libd=
trace/common/dt_proc.c
--- a/head/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.c	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/cddl/contrib/opensolaris/lib/libdtrace/common/dt_proc.c	Tue Apr =
17 11:51:51 2012 +0300
@@ -811,7 +811,7 @@
 #if defined(sun)
 		(void) _lwp_kill(dpr->dpr_tid, SIGCANCEL);
 #else
-		pthread_kill(dpr->dpr_tid, SIGUSR1);
+		pthread_kill(dpr->dpr_tid, SIGTHR);
 #endif
=20
 		/*
diff -r 428842767fa6 -r f2935497fa04 head/cddl/contrib/opensolaris/tools/ct=
f/cvt/ctf.c
--- a/head/cddl/contrib/opensolaris/tools/ctf/cvt/ctf.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/cddl/contrib/opensolaris/tools/ctf/cvt/ctf.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -62,6 +62,18 @@
 	int ntholes;		/* number of type holes */
 };
=20
+/*
+ * Macros to reverse byte order
+ */
+#define	BSWAP_8(x)	((x) & 0xff)
+#define	BSWAP_16(x)	((BSWAP_8(x) << 8) | BSWAP_8((x) >> 8))
+#define	BSWAP_32(x)	((BSWAP_16(x) << 16) | BSWAP_16((x) >> 16))
+
+#define	SWAP_16(x)	(x) =3D BSWAP_16(x)
+#define	SWAP_32(x)	(x) =3D BSWAP_32(x)
+
+static int target_requires_swap;
+
 /*PRINTFLIKE1*/
 static void
 parseterminate(const char *fmt, ...)
@@ -140,6 +152,11 @@
 	ctl.ctl_label =3D strtab_insert(&b->ctb_strtab, le->le_name);
 	ctl.ctl_typeidx =3D le->le_idx;
=20
+	if (target_requires_swap) {
+		SWAP_32(ctl.ctl_label);
+		SWAP_32(ctl.ctl_typeidx);
+	}
+
 	ctf_buf_write(b, &ctl, sizeof (ctl));
=20
 	return (1);
@@ -152,6 +169,10 @@
=20
 	ctf_buf_write(b, &id, sizeof (id));
=20
+	if (target_requires_swap) {
+		SWAP_16(id);
+	}
+
 	debug(3, "Wrote object %s (%d)\n", (idp ? idp->ii_name : "(null)"), id);
 }
=20
@@ -180,10 +201,21 @@
=20
 	fdata[0] =3D CTF_TYPE_INFO(CTF_K_FUNCTION, 1, nargs);
 	fdata[1] =3D idp->ii_dtype->t_id;
+
+	if (target_requires_swap) {
+		SWAP_16(fdata[0]);
+		SWAP_16(fdata[1]);
+	}
+
 	ctf_buf_write(b, fdata, sizeof (fdata));
=20
 	for (i =3D 0; i < idp->ii_nargs; i++) {
 		id =3D idp->ii_args[i]->t_id;
+
+		if (target_requires_swap) {
+			SWAP_16(id);
+		}
+
 		ctf_buf_write(b, &id, sizeof (id));
 	}
=20
@@ -208,11 +240,25 @@
 		ctt->ctt_size =3D CTF_LSIZE_SENT;
 		ctt->ctt_lsizehi =3D CTF_SIZE_TO_LSIZE_HI(size);
 		ctt->ctt_lsizelo =3D CTF_SIZE_TO_LSIZE_LO(size);
+		if (target_requires_swap) {
+			SWAP_32(ctt->ctt_name);
+			SWAP_16(ctt->ctt_info);
+			SWAP_16(ctt->ctt_size);
+			SWAP_32(ctt->ctt_lsizehi);
+			SWAP_32(ctt->ctt_lsizelo);
+		}
 		ctf_buf_write(b, ctt, sizeof (*ctt));
 	} else {
 		ctf_stype_t *cts =3D (ctf_stype_t *)ctt;
=20
 		cts->ctt_size =3D (ushort_t)size;
+
+		if (target_requires_swap) {
+			SWAP_32(cts->ctt_name);
+			SWAP_16(cts->ctt_info);
+			SWAP_16(cts->ctt_size);
+		}
+
 		ctf_buf_write(b, cts, sizeof (*cts));
 	}
 }
@@ -222,6 +268,12 @@
 {
 	ctf_stype_t *cts =3D (ctf_stype_t *)ctt;
=20
+	if (target_requires_swap) {
+		SWAP_32(cts->ctt_name);
+		SWAP_16(cts->ctt_info);
+		SWAP_16(cts->ctt_size);
+	}
+
 	ctf_buf_write(b, cts, sizeof (*cts));
 }
=20
@@ -296,6 +348,9 @@
 			encoding =3D ip->intr_fformat;
=20
 		data =3D CTF_INT_DATA(encoding, ip->intr_offset, ip->intr_nbits);
+		if (target_requires_swap) {
+			SWAP_32(data);
+		}
 		ctf_buf_write(b, &data, sizeof (data));
 		break;
=20
@@ -312,6 +367,11 @@
 		cta.cta_contents =3D tp->t_ardef->ad_contents->t_id;
 		cta.cta_index =3D tp->t_ardef->ad_idxtype->t_id;
 		cta.cta_nelems =3D tp->t_ardef->ad_nelems;
+		if (target_requires_swap) {
+			SWAP_16(cta.cta_contents);
+			SWAP_16(cta.cta_index);
+			SWAP_32(cta.cta_nelems);
+		}
 		ctf_buf_write(b, &cta, sizeof (cta));
 		break;
=20
@@ -341,6 +401,11 @@
 				    offset);
 				ctm.ctm_type =3D mp->ml_type->t_id;
 				ctm.ctm_offset =3D mp->ml_offset;
+				if (target_requires_swap) {
+					SWAP_32(ctm.ctm_name);
+					SWAP_16(ctm.ctm_type);
+					SWAP_16(ctm.ctm_offset);
+				}
 				ctf_buf_write(b, &ctm, sizeof (ctm));
 			}
 		} else {
@@ -355,6 +420,14 @@
 				    CTF_OFFSET_TO_LMEMHI(mp->ml_offset);
 				ctlm.ctlm_offsetlo =3D
 				    CTF_OFFSET_TO_LMEMLO(mp->ml_offset);
+
+				if (target_requires_swap) {
+					SWAP_32(ctlm.ctlm_name);
+					SWAP_16(ctlm.ctlm_type);
+					SWAP_32(ctlm.ctlm_offsethi);
+					SWAP_32(ctlm.ctlm_offsetlo);
+				}
+
 				ctf_buf_write(b, &ctlm, sizeof (ctlm));
 			}
 		}
@@ -377,6 +450,12 @@
 			offset =3D strtab_insert(&b->ctb_strtab, ep->el_name);
 			cte.cte_name =3D CTF_TYPE_NAME(CTF_STRTAB_0, offset);
 			cte.cte_value =3D ep->el_number;
+
+			if (target_requires_swap) {
+				SWAP_32(cte.cte_name);
+				SWAP_32(cte.cte_value);
+			}
+
 			ctf_buf_write(b, &cte, sizeof (cte));
 			i--;
 		}
@@ -420,6 +499,11 @@
=20
 		for (i =3D 0; i < (int) tp->t_fndef->fn_nargs; i++) {
 			id =3D tp->t_fndef->fn_args[i]->t_id;
+
+			if (target_requires_swap) {
+				SWAP_16(id);
+			}
+
 			ctf_buf_write(b, &id, sizeof (id));
 		}
=20
@@ -613,6 +697,9 @@
=20
 	int i;
=20
+	target_requires_swap =3D do_compress & CTF_SWAP_BYTES;
+	do_compress &=3D ~CTF_SWAP_BYTES;
+
 	/*
 	 * Prepare the header, and create the CTF output buffers.  The data
 	 * object section and function section are both lists of 2-byte
@@ -649,6 +736,18 @@
 	h.cth_stroff =3D ctf_buf_cur(buf);
 	h.cth_strlen =3D strtab_size(&buf->ctb_strtab);
=20
+	if (target_requires_swap) {
+		SWAP_16(h.cth_preamble.ctp_magic);
+		SWAP_32(h.cth_parlabel);
+		SWAP_32(h.cth_parname);
+		SWAP_32(h.cth_lbloff);
+		SWAP_32(h.cth_objtoff);
+		SWAP_32(h.cth_funcoff);
+		SWAP_32(h.cth_typeoff);
+		SWAP_32(h.cth_stroff);
+		SWAP_32(h.cth_strlen);
+	}
+
 	/*
 	 * We only do compression for ctfmerge, as ctfconvert is only
 	 * supposed to be used on intermediary build objects. This is
diff -r 428842767fa6 -r f2935497fa04 head/cddl/contrib/opensolaris/tools/ct=
f/cvt/ctfmerge.c
--- a/head/cddl/contrib/opensolaris/tools/ctf/cvt/ctfmerge.c	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/cddl/contrib/opensolaris/tools/ctf/cvt/ctfmerge.c	Tue Apr 17 11:=
51:51 2012 +0300
@@ -620,7 +620,7 @@
 		terminate("No CTF data found in source file %s\n", srcfile);
=20
 	tmpname =3D mktmpname(destfile, ".ctf");
-	write_ctf(srctd, destfile, tmpname, CTF_COMPRESS | keep_stabs);
+	write_ctf(srctd, destfile, tmpname, CTF_COMPRESS | CTF_SWAP_BYTES | keep_=
stabs);
 	if (rename(tmpname, destfile) !=3D 0) {
 		terminate("Couldn't rename temp file %s to %s", tmpname,
 		    destfile);
@@ -1015,7 +1015,7 @@
=20
 	tmpname =3D mktmpname(outfile, ".ctf");
 	write_ctf(savetd, outfile, tmpname,
-	    CTF_COMPRESS | write_fuzzy_match | dynsym | keep_stabs);
+	    CTF_COMPRESS | CTF_SWAP_BYTES | write_fuzzy_match | dynsym | keep_sta=
bs);
 	if (rename(tmpname, outfile) !=3D 0)
 		terminate("Couldn't rename output temp file %s", tmpname);
 	free(tmpname);
diff -r 428842767fa6 -r f2935497fa04 head/cddl/contrib/opensolaris/tools/ct=
f/cvt/ctftools.h
--- a/head/cddl/contrib/opensolaris/tools/ctf/cvt/ctftools.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/cddl/contrib/opensolaris/tools/ctf/cvt/ctftools.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -391,6 +391,7 @@
 #define	CTF_USE_DYNSYM	0x2 /* use .dynsym not .symtab */
 #define	CTF_COMPRESS	0x4 /* compress CTF output */
 #define	CTF_KEEP_STABS	0x8 /* keep .stabs sections */
+#define	CTF_SWAP_BYTES	0x10 /* target byte order is different from host */
=20
 void write_ctf(tdata_t *, const char *, const char *, int);
=20
diff -r 428842767fa6 -r f2935497fa04 head/cddl/contrib/opensolaris/tools/ct=
f/cvt/output.c
--- a/head/cddl/contrib/opensolaris/tools/ctf/cvt/output.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/cddl/contrib/opensolaris/tools/ctf/cvt/output.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -717,7 +717,7 @@
=20
 	iiburst =3D sort_iidescs(elf, file, td, flags & CTF_FUZZY_MATCH,
 	    flags & CTF_USE_DYNSYM);
-	data =3D ctf_gen(iiburst, lenp, flags & CTF_COMPRESS);
+	data =3D ctf_gen(iiburst, lenp, flags & (CTF_COMPRESS |  CTF_SWAP_BYTES));
=20
 	iiburst_free(iiburst);
=20
@@ -730,10 +730,12 @@
 	struct stat st;
 	Elf *elf =3D NULL;
 	Elf *telf =3D NULL;
+	GElf_Ehdr ehdr;
 	caddr_t data;
 	size_t len;
 	int fd =3D -1;
 	int tfd =3D -1;
+	int byteorder;
=20
 	(void) elf_version(EV_CURRENT);
 	if ((fd =3D open(curname, O_RDONLY)) < 0 || fstat(fd, &st) < 0)
@@ -746,6 +748,22 @@
 	if ((telf =3D elf_begin(tfd, ELF_C_WRITE, NULL)) =3D=3D NULL)
 		elfterminate(curname, "Cannot write");
=20
+	if (gelf_getehdr(elf, &ehdr)) {
+#if BYTE_ORDER =3D=3D _BIG_ENDIAN
+		byteorder =3D ELFDATA2MSB;
+#else
+		byteorder =3D ELFDATA2LSB;
+#endif
+		/*
+		 * If target and host has the same byte order
+		 * clear byte swapping request
+		 */
+		if  (ehdr.e_ident[EI_DATA] =3D=3D byteorder)
+			flags &=3D ~CTF_SWAP_BYTES;
+	}
+	else=20
+		elfterminate(curname, "Failed to get EHDR");
+
 	data =3D make_ctf_data(td, elf, curname, &len, flags);
 	write_file(elf, curname, telf, newname, data, len, flags);
 	free(data);
diff -r 428842767fa6 -r f2935497fa04 head/cddl/lib/Makefile
--- a/head/cddl/lib/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/cddl/lib/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/cddl/lib/Makefile 233415 2012-03-24 05:29:07Z gonzo $
=20
 .include <bsd.own.mk>
=20
@@ -19,7 +19,7 @@
 .endif
 .endif
=20
-.if ${MACHINE_ARCH} =3D=3D "amd64" || ${MACHINE_ARCH} =3D=3D "i386"
+.if ${MACHINE_ARCH} =3D=3D "amd64" || ${MACHINE_ARCH} =3D=3D "i386" ||  ${=
MACHINE_CPUARCH} =3D=3D "mips"
 _drti=3D		drti
 _libdtrace=3D	libdtrace
 .endif
diff -r 428842767fa6 -r f2935497fa04 head/cddl/lib/libdtrace/Makefile
--- a/head/cddl/lib/libdtrace/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/cddl/lib/libdtrace/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/cddl/lib/libdtrace/Makefile 233415 2012-03-24 05:29:07Z g=
onzo $
=20
 .PATH: ${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/common
 .PATH: ${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libgen/common
@@ -42,8 +42,7 @@
 		dt_subr.c \
 		dt_work.c \
 		dt_xlator.c \
-		gmatch.c \
-		dis_tables.c
+		gmatch.c
=20
 DSRCS=3D		errno.d			\
 		psinfo.d		\
@@ -70,12 +69,17 @@
 .elif ${MACHINE_CPUARCH} =3D=3D "sparc64"
 CFLAGS+=3D	-I${OPENSOLARIS_SYS_DISTDIR}/uts/sparc
 .PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/sparc
+.elif ${MACHINE_CPUARCH} =3D=3D "mips"
+CFLAGS+=3D	-I${OPENSOLARIS_SYS_DISTDIR}/uts/mips
+.PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/mips
+.PATH:		${.CURDIR}/../../../sys/cddl/dev/dtrace/mips
 .else
 # temporary hack
 CFLAGS+=3D	-I${OPENSOLARIS_SYS_DISTDIR}/uts/intel
 .endif
=20
 .if ${MACHINE_ARCH} =3D=3D "i386" || ${MACHINE_ARCH} =3D=3D "amd64"
+SRCS+=3D		dis_tables.c
 DSRCS+=3D		regs_x86.d
 .endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/cddl/usr.sbin/Makefile
--- a/head/cddl/usr.sbin/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/cddl/usr.sbin/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/cddl/usr.sbin/Makefile 233415 2012-03-24 05:29:07Z gonzo $
=20
 .include <bsd.own.mk>
=20
@@ -19,4 +19,8 @@
 _lockstat=3D	lockstat
 .endif
=20
+.if ${MACHINE_CPUARCH} =3D=3D "mips"
+_dtrace=3D	dtrace
+.endif
+
 .include <bsd.subdir.mk>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/CHANGES
--- a/head/contrib/bind9/CHANGES	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/CHANGES	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,309 @@
-	--- 9.8.1-P1 released ---
+	--- 9.8.2 released ---
+
+3298.	[bug]		Named could dereference a NULL pointer in
+			zmgr_start_xfrin_ifquota if the zone was being removed.
+			[RT #28419]
+
+3297.	[bug]		Named could die on a malformed master file. [RT #28467]
+
+3295.	[bug]		Adjust isc_time_secondsastimet range check to be more
+			portable. [RT # 26542]
+
+3294.	[bug]		isccc/cc.c:table_fromwire failed to free alist on
+			error. [RT #28265]
+
+3291.	[port]		Fixed a build error on systems without ENOTSUP.
+			[RT #28200]
+
+3290.	[bug]		<isc/hmacsha.h> was not being installed. [RT #28169]
+
+3288.	[bug]		dlz_destroy() function wasn't correctly registered
+			by the DLZ dlopen driver. [RT #28056]
+
+3287.	[port]		Update ans.pl to work with Net::DNS 0.68. [RT #28028]
+
+3286.	[bug]		Managed key maintenance timer could fail to start
+			after 'rndc reconfig'. [RT #26786]
+
+	--- 9.8.2rc2 released ---
+
+3285.	[bug]		val-frdataset was incorrectly disassociated in
+			proveunsecure after calling startfinddlvsep.
+			[RT #27928]
+
+3284.	[bug]		Address race conditions with the handling of
+			rbtnode.deadlink. [RT #27738]
+
+3283.	[bug]		Raw zones with with more than 512 records in a RRset
+			failed to load. [RT #27863]
+
+3282.	[bug]		Restrict the TTL of NS RRset to no more than that
+			of the old NS RRset when replacing it.
+			[RT #27792] [RT #27884]
+
+3281.	[bug]		SOA refresh queries could be treated as cancelled
+			despite succeeding over the loopback interface.
+			[RT #27782]
+
+3280.	[bug]		Potential double free of a rdataset on out of memory
+			with DNS64. [RT #27762]
+
+3278.	[bug]		Make sure automatic key maintenance is started
+			when "auto-dnssec maintain" is turned on during
+			"rndc reconfig". [RT #26805]
+
+3276.	[bug]		win32: ns_os_openfile failed to return NULL on
+			safe_open failure. [RT #27696]
+
+3274.	[bug]		Log when a zone is not reusable.  Only set loadtime
+			on successful loads.  [RT #27650]
+
+3273.   [bug]           AAAA responses could be returned in the additional
+                        section even when filter-aaaa-on-v4 was in use.
+                        [RT #27292]
+
+3271.	[port]		darwin: mksymtbl is not always stable, loop several
+			times before giving up.  mksymtbl was using non
+			portable perl to covert 64 bit hex strings. [RT #27653]
+
+3268.	[bug]		Convert RRSIG expiry times to 64 timestamps to work
+			out the earliest expiry time. [RT #23311]
+
+3267.	[bug]		Memory allocation failures could be mis-reported as
+			unexpected error.  New ISC_R_UNSET result code.
+			[RT #27336]
+
+3266.	[bug]		The maximum number of NSEC3 iterations for a
+			DNSKEY RRset was not being properly computed.
+			[RT #26543]
+
+3262.	[bug]		Signed responses were handled incorrectly by RPZ.
+			[RT #27316]
+
+	--- 9.8.2rc1 released ---
+
+3260.	[bug]		"rrset-order cyclic" could appear not to rotate
+			for some query patterns.  [RT #27170/27185]
+
+3259.	[bug]		named-compilezone: Suppress "dump zone to <file>"
+			message when writing to stdout. [RT #27109]
+
+3258.	[test]		Add "forcing full sign with unreadable keys" test.
+			[RT #27153]
+
+3257.	[bug]		Do not generate a error message when calling fsync()
+			in a pipe or socket. [RT #27109]
+
+3256.	[bug]		Disable empty zones for lwresd -C. [RT #27139]
+
+3254.	[bug]		Set isc_socket_ipv6only() on the IPv6 control channels.
+			[RT #22249]
+
+3253.	[bug]		Return DNS_R_SYNTAX when the input to a text field is
+			too long. [RT #26956]
+
+3251.	[bug]		Enforce a upper bound (65535 bytes) on the amount of
+			memory dns_sdlz_putrr() can allocate per record to
+			prevent run away memory consumption on ISC_R_NOSPACE.
+			[RT #26956]
+
+3250.	[func]		'configure --enable-developer'; turn on various
+			configure options, normally off by default, that
+			we want developers to build and test with. [RT #27103]
+
+3249.	[bug]		Update log message when saving slave zones files for
+			analysis after load failures. [RT #27087]
+
+3248.	[bug]		Configure options --enable-fixed-rrset and
+			--enable-exportlib were incompatible with each
+			other. [RT #27087]
+
+3247.	[bug]		'raw' format zones failed to preserve load order
+			breaking 'fixed' sort order. [RT #27087]
+
+3243.	[port]		netbsd,bsdi: the thread defaults were not being
+			properly set.
+
+3241.	[bug]		Address race conditions in the resolver code.
+			[RT #26889]
+
+3240.	[bug]		DNSKEY state change events could be missed. [RT #26874]
+
+3239.	[bug]		dns_dnssec_findmatchingkeys needs to use a consistent
+			timestamp. [RT #26883]
+
+3238.	[bug]		keyrdata was not being reinitialized in
+			lib/dns/rbtdb.c:iszonesecure. [RT#26913]
+
+3237.	[bug]		dig -6 didn't work with +trace. [RT #26906]
+
+	--- 9.8.2b1 released ---
+
+3234.	[bug]		'make depend' produced invalid makefiles. [RT #26830]
+
+3231.	[bug]		named could fail to send a uncompressable zone.
+			[RT #26796]
+
+3230.	[bug]		'dig axfr' failed to properly handle a multi-message
+			axfr with a serial of 0. [RT #26796]
+
+3229.	[bug]		Fix local variable to struct var assignment
+			found by CLANG warning.
+
+3228.	[tuning]	Dynamically grow symbol table to improve zone
+			loading performance. [RT #26523]
+
+3227.	[bug]		Interim fix to make WKS's use of getprotobyname()
+			and getservbyname() self thread safe. [RT #26232]
+
+3226.	[bug]		Address minor resource leakages. [RT #26624]
+
+3221.	[bug]		Fixed a potential coredump on shutdown due to
+			referencing fetch context after it's been freed.
+			[RT #26720]
+
+3220.	[bug]		Change #3186 was incomplete; dns_db_rpz_findips()
+			could fail to set the database version correctly,
+			causing an assertion failure. [RT #26180]
=20
 3218.	[security]	Cache lookup could return RRSIG data associated with
 			nonexistent records, leading to an assertion
 			failure. [RT #26590]
=20
+3217.	[cleanup]	Fix build problem with --disable-static. [RT #26476]
+
+3216.	[bug]		resolver.c:validated() was not thread-safe. [RT #26478]
+
+3213.	[doc]		Clarify ixfr-from-differences behavior. [RT #25188]
+
+3212.	[bug]		rbtdb.c: failed to remove a node from the deadnodes
+			list prior to adding a reference to it leading a
+			possible assertion failure. [RT #23219]
+
+3209.	[func]		Add "dnssec-lookaside 'no'".  [RT #24858]
+
+3208.	[bug]		'dig -y' handle unknown tsig alorithm better.
+			[RT #25522]
+
+3207.	[contrib]	Fixed build error in Berkeley DB DLZ module. [RT #26444]
+
+3206.	[cleanup]	Add ISC information to log at start time. [RT #25484]
+
+3204.	[bug]		When a master server that has been marked as
+			unreachable sends a NOTIFY, mark it reachable
+			again. [RT #25960]
+
+3203.	[bug]		Increase log level to 'info' for validation failures
+			from expired or not-yet-valid RRSIGs. [RT #21796]
+
+3200.	[doc]		Some rndc functions were undocumented or were
+			missing from 'rndc -h' output. [RT #25555]
+
+3198.	[doc]		Clarified that dnssec-settime can alter keyfile
+			permissions. [RT #24866]
+
+3196.	[bug]		nsupdate: return nonzero exit code when target zone
+			doesn't exist. [RT #25783]
+
+3195.	[cleanup]	Silence "file not found" warnings when loading
+			managed-keys zone. [RT #26340]
+
+3194.	[doc]		Updated RFC references in the 'empty-zones-enable'
+			documentation. [RT #25203]
+
+3193.	[cleanup]	Changed MAXZONEKEYS to DNS_MAXZONEKEYS, moved to
+			dnssec.h. [RT #26415]
+
+3192.	[bug]		A query structure could be used after being freed.
+			[RT #22208]
+
+3191.	[bug]		Print NULL records using "unknown" format. [RT #26392]
+
+3190.	[bug]		Underflow in error handling in isc_mutexblock_init.
+			[RT #26397]
+
+3189.	[test]		Added a summary report after system tests. [RT #25517]
+
+3188.	[bug]		zone.c:zone_refreshkeys() could fail to detach
+			references correctly when errors occurred, causing
+			a hang on shutdown. [RT #26372]
+
+3187.	[port]		win32: support for Visual Studio 2008.  [RT #26356]
+
+3186.	[bug]		Version/db mis-match in rpz code. [RT #26180]
+
+3179.	[port]		kfreebsd: build issues. [RT #26273]
+
+3175.	[bug]		Fix how DNSSEC positive wildcard responses from a
+			NSEC3 signed zone are validated.  Stop sending a
+			unnecessary NSEC3 record when generating such
+			responses. [RT #26200]
+
+3174.	[bug]		Always compute to revoked key tag from scratch.
+			[RT #26186]
+
+3173.	[port]		Correctly validate root DS responses. [RT #25726]
+
+3171.	[bug]		Exclusively lock the task when adding a zone using
+			'rndc addzone'.  [RT #25600]
+
+3170.	[func]		RPZ update:
+			- fix precedence among competing rules
+			- improve ARM text including documenting rule precedence
+			- try to rewrite CNAME chains until first hit
+			- new "rpz" logging channel
+			- RDATA for CNAME rules can include wildcards
+			- replace "NO-OP" named.conf policy override with
+			  "PASSTHRU" and add "DISABLED" override ("NO-OP"
+			  is still recognized)
+			[RT #25172]
+
+3169.	[func]		Catch db/version mis-matches when calling dns_db_*().
+			[RT #26017]
+
+3167.	[bug]		Negative answers from forwarders were not being
+			correctly tagged making them appear to not be cached.
+			[RT #25380]
+
+3162.	[test]		start.pl: modified to allow for "named.args" in
+			ns*/ subdirectory to override stock arguments to
+			named. Largely from RT#26044, but no separate ticket.
+
+3161.	[bug]		zone.c:del_sigs failed to always reset rdata leading
+			assertion failures. [RT #25880]
+
+3157.	[tuning]	Reduce the time spent in "rndc reconfig" by parsing
+			the config file before pausing the server. [RT #21373]
+
+3155.	[bug]		Fixed a build failure when using contrib DLZ
+			drivers (e.g., mysql, postgresql, etc). [RT #25710]
+
+3154.	[bug]		Attempting to print an empty rdataset could trigger
+			an assert. [RT #25452]
+
+3152.	[cleanup]	Some versions of gcc and clang failed due to
+			incorrect use of __builtin_expect. [RT #25183]
+
+3151.	[bug]		Queries for type RRSIG or SIG could be handled
+			incorrectly.  [RT #21050]
+
+3148.	[bug]		Processing of normal queries could be stalled when
+			forwarding a UPDATE message. [RT #24711]
+
+3146.	[test]		Fixed gcc4.6.0 errors in ATF. [RT #25598]
+
+3145.	[test]		Capture output of ATF unit tests in "./atf.out" if
+			there were any errors while running them. [RT #25527]
+
+3144.	[bug]		dns_dbiterator_seek() could trigger an assert when
+			used with a nonexistent database node. [RT #25358]
+
+3143.	[bug]		Silence clang compiler warnings. [RT #25174]
+
+3139.	[test]		Added tests from RFC 6234, RFC 2202, and RFC 1321
+			for the hashing algorithms (md5, sha1 - sha512, and
+			their hmac counterparts).  [RT #25067]
+
 	--- 9.8.1 released ---
=20
 	--- 9.8.1rc1 released ---
@@ -14,7 +314,7 @@
 3138.	[bug]		Address memory leaks and out-of-order operations when
 			shutting named down. [RT #25210]
=20
-3136.	[func]		Add RFC 1918 reverse zones to the list of built-in=20
+3136.	[func]		Add RFC 1918 reverse zones to the list of built-in
 			empty zones switched on by the 'empty-zones-enable'
 			option. [RT #24990]
=20
@@ -34,9 +334,9 @@
=20
 3133.	[bug]		Change #3114 was incomplete. [RT #24577]
=20
-3131.   [tuning]        Improve scalability by allocating one zone task
-                        per 100 zones at startup time, rather than using a
-                        fixed-size task table. [RT #24406]
+3131.	[tuning]	Improve scalability by allocating one zone task
+			per 100 zones at startup time, rather than using a
+			fixed-size task table. [RT #24406]
=20
 3129.	[bug]		Named could crash on 'rndc reconfig' when
 			allow-new-zones was set to yes and named ACLs
@@ -62,10 +362,10 @@
=20
 3122.	[cleanup]	dnssec-settime: corrected usage message. [RT #24664]
=20
-3121.   [security]      An authoritative name server sending a negative
-                        response containing a very large RRset could
-                        trigger an off-by-one error in the ncache code
-                        and crash named. [RT #24650]
+3121.	[security]	An authoritative name server sending a negative
+			response containing a very large RRset could
+			trigger an off-by-one error in the ncache code
+			and crash named. [RT #24650]
=20
 3120.	[bug]		Named could fail to validate zones listed in a DLV
 			that validated insecure without using DLV and had
@@ -99,9 +399,9 @@
 			"krb5-subdomain", which allow machines to update
 			their own records, to the BIND 9 ARM.
=20
-3111.   [bug]           Improved consistency checks for dnssec-enable and
-                        dnssec-validation, added test cases to the
-                        checkconf system test. [RT #24398]
+3111.	[bug]		Improved consistency checks for dnssec-enable and
+			dnssec-validation, added test cases to the
+			checkconf system test. [RT #24398]
=20
 3110.	[bug]		dnssec-signzone: Wrong error message could appear
 			when attempting to sign with no KSK. [RT #24369]
@@ -109,10 +409,10 @@
 3107.	[bug]		dnssec-signzone: Report the correct number of ZSKs
 			when using -x. [RT #20852]
=20
-3105.   [bug]           GOST support can be suppressed by "configure
-                        --without-gost" [RT #24367]
-
-3104.   [bug]           Better support for cross-compiling. [RT #24367]
+3105.	[bug]		GOST support can be suppressed by "configure
+			--without-gost" [RT #24367]
+
+3104.	[bug]		Better support for cross-compiling. [RT #24367]
=20
 3103.	[bug]		Configuring 'dnssec-validation auto' in a view
 			instead of in the options statement could trigger
@@ -142,7 +442,7 @@
=20
 3094.	[doc]		Expand dns64 documentation.
=20
-3093.   [bug]           Fix gssapi/kerberos dependencies [RT #23836]
+3093.	[bug]		Fix gssapi/kerberos dependencies [RT #23836]
=20
 3092.	[bug]		Signatures for records at the zone apex could go
 			stale due to an incorrect timer setting. [RT #23769]
@@ -151,7 +451,7 @@
 			and then subsequently activated could fail to trigger
 			automatic signing. [RT #22911]
=20
-3090.   [func]          Make --with-gssapi default [RT #23738]
+3090.	[func]		Make --with-gssapi default [RT #23738]
=20
 3088.	[bug]		Remove bin/tests/system/logfileconfig/ns1/named.conf
 			and add setup.sh in order to resolve changing
@@ -269,9 +569,9 @@
=20
 3043.	[test]		Merged in the NetBSD ATF test framework (currently
 			version 0.12) for development of future unit tests.
-                        Use configure --with-atf to build ATF internally
-                        or configure --with-atf=3Dprefix to use an external
-                        copy.  [RT #23209]
+			Use configure --with-atf to build ATF internally
+			or configure --with-atf=3Dprefix to use an external
+			copy.  [RT #23209]
=20
 3042.	[bug]		dig +trace could fail attempting to use IPv6
 			addresses on systems with only IPv4 connectivity.
@@ -706,7 +1006,7 @@
 2929.	[bug]		Improved handling of GSS security contexts:
 			 - added LRU expiration for generated TSIGs
 			 - added the ability to use a non-default realm
-                         - added new "realm" keyword in nsupdate
+			 - added new "realm" keyword in nsupdate
 			 - limited lifetime of generated keys to 1 hour
 			   or the lifetime of the context (whichever is
 			   smaller)
@@ -1535,7 +1835,7 @@
 			--with-export-includedir. [RT #20252]
=20
 2675.	[bug]		dnssec-signzone could crash if the key directory
-                        did not exist. [RT #20232]
+			did not exist. [RT #20232]
=20
 	--- 9.7.0a3 released ---
=20
@@ -1626,7 +1926,7 @@
 			64-bit systems. [RT #20076]
=20
 2650.	[bug]		Assertion failure in dnssec-signzone when trying
-                        to read keyset-* files. [RT #20075]
+			to read keyset-* files. [RT #20075]
=20
 2649.	[bug]		Set the domain for forward only zones. [RT #19944]
=20
@@ -1698,7 +1998,7 @@
 2630.	[func]		Improved syntax for DDNS autoconfiguration:  use
 			"update-policy local;" to switch on local DDNS in a
 			zone. (The "ddns-autoconf" option has been removed.)
-                        [RT #19875]
+			[RT #19875]
=20
 2629.	[port]		Check for seteuid()/setegid(), use setresuid()/
 			setresgid() if not present. [RT #19932]
@@ -2383,10 +2683,10 @@
 			time. [RT #18277]
=20
 2423.	[security]	Randomize server selection on queries, so as to
-                        make forgery a little more difficult.  Instead of
-                        always preferring the server with the lowest RTT,
-                        pick a server with RTT within the same 128
-                        millisecond band.  [RT #18441]
+			make forgery a little more difficult.  Instead of
+			always preferring the server with the lowest RTT,
+			pick a server with RTT within the same 128
+			millisecond band.  [RT #18441]
=20
 2422.	[bug]		Handle the special return value of a empty node as
 			if it was a NXRRSET in the validator. [RT #18447]
@@ -2467,7 +2767,7 @@
=20
 2399.	[placeholder]
=20
-2398.	[bug]           Improve file descriptor management.  New,
+2398.	[bug]		Improve file descriptor management.  New,
 			temporary, named.conf option reserved-sockets,
 			default 512. [RT #18344]
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/COPYRIGHT
--- a/head/contrib/bind9/COPYRIGHT	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/COPYRIGHT	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
 Copyright (C) 1996-2003  Internet Software Consortium.
=20
 Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 PERFORMANCE OF THIS SOFTWARE.
=20
-$Id: COPYRIGHT,v 1.17.14.1 2011-02-22 06:34:47 marka Exp $
+$Id: COPYRIGHT,v 1.17.14.2 2012/01/04 23:46:18 tbox Exp $
=20
 	Portions of this code release fall under one or more of the
 	following Copyright notices.  Please see individual source
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/FAQ.xml
--- a/head/contrib/bind9/FAQ.xml	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/FAQ.xml	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: FAQ.xml,v 1.54 2010-01-19 23:48:55 tbox Exp $ -->
+<!-- $Id: FAQ.xml,v 1.54 2010/01/19 23:48:55 tbox Exp $ -->
=20
 <article class=3D"faq">
   <title>Frequently Asked Questions about BIND 9</title>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/Makefile.in
--- a/head/contrib/bind9/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.58.250.2 2011-02-28 01:19:57 tbox Exp $
+# $Id: Makefile.in,v 1.58.250.4 2011/09/06 04:06:11 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
@@ -64,8 +64,10 @@
 check: test
=20
 test:
-	(cd bin/tests && ${MAKE} ${MAKEDEFS} test)
-	(test -f unit/unittest.sh && $(SHELL) unit/unittest.sh)
+	status=3D0; \
+	(cd bin/tests && ${MAKE} ${MAKEDEFS} test) || status=3D1; \
+	(test -f unit/unittest.sh && $(SHELL) unit/unittest.sh) || status=3D1; \
+	exit $$status
=20
 FAQ: FAQ.xml
 	${XSLTPROC} doc/xsl/isc-docbook-text.xsl FAQ.xml | \
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/README
--- a/head/contrib/bind9/README	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/README	Tue Apr 17 11:51:51 2012 +0300
@@ -48,6 +48,14 @@
 	For a detailed list of user-visible changes from
 	previous releases, see the CHANGES file.
=20
+        For up-to-date release notes and errata, see
+        http://www.isc.org/software/bind9/releasenotes
+
+BIND 9.8.2
+
+	BIND 9.8.2 includes a number of bug fixes and prevents a security
+	problem described in CVE-2011-4313
+
 BIND 9.8.1
=20
         BIND 9.8.1 includes a number of bug fixes and enhancements from
@@ -314,6 +322,7 @@
 	libraries.  sh-utils-1.16 provides a "printf" which compiles
 	on SunOS 4.
=20
+
 Documentation
=20
 	The BIND 9 Administrator Reference Manual is included with the
@@ -336,6 +345,48 @@
         in the other README files.
=20
=20
+Change Log
+
+	A detailed list of all changes to BIND 9 is included in the=20
+	file CHANGES, with the most recent changes listed first.
+	Change notes include tags indicating the category of the
+	change that was made; these categories are:
+
+	   [func]	  New feature
+
+	   [bug]	  General bug fix
+
+	   [security]	  Fix for a significant security flaw
+
+	   [experimental] Used for new features when the syntax
+	   		  or other aspects of the design are still
+			  in flux and may change
+
+	   [port]	  Portability enhancement
+
+	   [maint]	  Updates to built-in data such as root
+			  server addresses and keys
+
+	   [tuning]	  Changes to built-in configuration defaults
+	   		  and constants to improve performanceo
+
+	   [protocol]	  Updates to the DNS protocol such as new
+			  RR types
+
+           [test]         Changes to the automatic tests, not
+                          affecting server functionality
+
+           [cleanup]      Minor corrections and refactoring
+
+	   [doc]	  Documentation
+
+	In general, [func] and [experimental] tags will only appear
+	in new-feature releases (i.e., those with version numbers
+	ending in zero).  Some new functionality may be backported to
+	older releases on a case-by-case basis.  All other change
+	types may be applied to all currently-supported releases.
+
+
 Bug Reports and Mailing Lists
=20
 	Bugs reports should be sent to
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/acconfig.h
--- a/head/contrib/bind9/acconfig.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/acconfig.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: acconfig.h,v 1.53 2008-12-01 23:47:44 tbox Exp $ */
+/* $Id: acconfig.h,v 1.53 2008/12/01 23:47:44 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/Makefile.in
--- a/head/contrib/bind9/bin/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.29 2009-10-05 12:07:08 fdupont Exp $
+# $Id: Makefile.in,v 1.29 2009/10/05 12:07:08 fdupont Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/Makefile.=
in
--- a/head/contrib/bind9/bin/check/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/check/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.36 2009-12-05 23:31:40 each Exp $
+# $Id: Makefile.in,v 1.36 2009/12/05 23:31:40 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/check-too=
l.c
--- a/head/contrib/bind9/bin/check/check-tool.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/bin/check/check-tool.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: check-tool.c,v 1.41 2010-09-07 23:46:59 tbox Exp $ */
+/* $Id: check-tool.c,v 1.41 2010/09/07 23:46:59 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/check-too=
l.h
--- a/head/contrib/bind9/bin/check/check-tool.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/bin/check/check-tool.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: check-tool.h,v 1.16 2010-09-07 23:46:59 tbox Exp $ */
+/* $Id: check-tool.h,v 1.16 2010/09/07 23:46:59 tbox Exp $ */
=20
 #ifndef CHECK_TOOL_H
 #define CHECK_TOOL_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckconf.8
--- a/head/contrib/bind9/bin/check/named-checkconf.8	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/check/named-checkconf.8	Tue Apr 17 11:51:51 20=
12 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: named-checkconf.8,v 1.33 2009-12-29 01:14:03 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckconf.c
--- a/head/contrib/bind9/bin/check/named-checkconf.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/check/named-checkconf.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: named-checkconf.c,v 1.54.62.2 2011-03-12 04:59:13 tbox Exp $ */
+/* $Id: named-checkconf.c,v 1.54.62.2 2011/03/12 04:59:13 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckconf.docbook
--- a/head/contrib/bind9/bin/check/named-checkconf.docbook	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/check/named-checkconf.docbook	Tue Apr 17 11:51=
:51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: named-checkconf.docbook,v 1.22 2009-12-28 23:21:16 each Exp $ -->
+<!-- $Id: named-checkconf.docbook,v 1.22 2009/12/28 23:21:16 each Exp $ -->
 <refentry id=3D"man.named-checkconf">
   <refentryinfo>
     <date>June 14, 2000</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckconf.html
--- a/head/contrib/bind9/bin/check/named-checkconf.html	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/bin/check/named-checkconf.html	Tue Apr 17 11:51:51=
 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: named-checkconf.html,v 1.33 2009-12-29 01:14:03 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named-checkconf</cod=
e>  [<code class=3D"option">-h</code>] [<code class=3D"option">-v</code>] [=
<code class=3D"option">-j</code>] [<code class=3D"option">-t <em class=3D"r=
eplaceable"><code>directory</code></em></code>] {filename} [<code class=3D"=
option">-p</code>] [<code class=3D"option">-z</code>]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543395"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543396"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">named-checkconf</strong></span>
       checks the syntax, but not the semantics, of a
       <span><strong class=3D"command">named</strong></span> configuration =
file.  The file is parsed
@@ -52,7 +52,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543444"></a><h2>OPTIONS</h2>
+<a name=3D"id2543445"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-h</span></dt>
 <dd><p>
@@ -91,21 +91,21 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543568"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543569"></a><h2>RETURN VALUES</h2>
 <p><span><strong class=3D"command">named-checkconf</strong></span>
       returns an exit status of 1 if
       errors were detected and 0 otherwise.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543579"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543580"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">named</span>=
(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named-che=
ckzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543609"></a><h2>AUTHOR</h2>
+<a name=3D"id2543610"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckzone.8
--- a/head/contrib/bind9/bin/check/named-checkzone.8	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/check/named-checkzone.8	Tue Apr 17 11:51:51 20=
12 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: named-checkzone.8,v 1.47 2010-01-17 01:14:02 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckzone.c
--- a/head/contrib/bind9/bin/check/named-checkzone.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/check/named-checkzone.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: named-checkzone.c,v 1.61 2010-09-07 23:46:59 tbox Exp $ */
+/* $Id: named-checkzone.c,v 1.61.62.2 2011/12/22 23:45:54 tbox Exp $ */
=20
 /*! \file */
=20
@@ -112,6 +112,7 @@
 	const char *outputformatstr =3D NULL;
 	dns_masterformat_t inputformat =3D dns_masterformat_text;
 	dns_masterformat_t outputformat =3D dns_masterformat_text;
+	isc_boolean_t logdump =3D ISC_FALSE;
 	FILE *errout =3D stdout;
=20
 	outputstyle =3D &dns_master_style_full;
@@ -418,6 +419,7 @@
=20
 	if (progmode =3D=3D progmode_compile) {
 		dumpzone =3D 1;	/* always dump */
+		logdump =3D !quiet;
 		if (output_filename =3D=3D NULL) {
 			fprintf(stderr,
 				"output file required, but not specified\n");
@@ -436,8 +438,10 @@
 	    (output_filename =3D=3D NULL ||
 	     strcmp(output_filename, "-") =3D=3D 0 ||
 	     strcmp(output_filename, "/dev/fd/1") =3D=3D 0 ||
-	     strcmp(output_filename, "/dev/stdout") =3D=3D 0))
+	     strcmp(output_filename, "/dev/stdout") =3D=3D 0)) {
 		errout =3D stderr;
+		logdump =3D ISC_FALSE;
+	}
=20
 	if (isc_commandline_index + 2 !=3D argc)
 		usage();
@@ -462,13 +466,13 @@
 			   &zone);
=20
 	if (result =3D=3D ISC_R_SUCCESS && dumpzone) {
-		if (!quiet && progmode =3D=3D progmode_compile) {
+		if (logdump) {
 			fprintf(errout, "dump zone to %s...", output_filename);
 			fflush(errout);
 		}
 		result =3D dump_zone(origin, zone, output_filename,
 				   outputformat, outputstyle);
-		if (!quiet && progmode =3D=3D progmode_compile)
+		if (logdump)
 			fprintf(errout, "done\n");
 	}
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckzone.docbook
--- a/head/contrib/bind9/bin/check/named-checkzone.docbook	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/check/named-checkzone.docbook	Tue Apr 17 11:51=
:51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: named-checkzone.docbook,v 1.40 2010-01-16 23:48:15 tbox Exp $ -->
+<!-- $Id: named-checkzone.docbook,v 1.40 2010/01/16 23:48:15 tbox Exp $ -->
 <refentry id=3D"man.named-checkzone">
   <refentryinfo>
     <date>June 13, 2000</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/check/named-che=
ckzone.html
--- a/head/contrib/bind9/bin/check/named-checkzone.html	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/bin/check/named-checkzone.html	Tue Apr 17 11:51:51=
 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: named-checkzone.html,v 1.47 2010-01-17 01:14:02 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -33,7 +33,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named-compilezone</c=
ode>  [<code class=3D"option">-d</code>] [<code class=3D"option">-j</code>]=
 [<code class=3D"option">-q</code>] [<code class=3D"option">-v</code>] [<co=
de class=3D"option">-c <em class=3D"replaceable"><code>class</code></em></c=
ode>] [<code class=3D"option">-C <em class=3D"replaceable"><code>mode</code=
></em></code>] [<code class=3D"option">-f <em class=3D"replaceable"><code>f=
ormat</code></em></code>] [<code class=3D"option">-F <em class=3D"replaceab=
le"><code>format</code></em></code>] [<code class=3D"option">-i <em class=
=3D"replaceable"><code>mode</code></em></code>] [<code class=3D"option">-k =
<em class=3D"replaceable"><code>mode</code></em></code>] [<code class=3D"op=
tion">-m <em class=3D"replaceable"><code>mode</code></em></code>] [<code cl=
ass=3D"option">-n <em class=3D"replaceable"><code>mode</code></em></code>] =
[<code class=3D"option">-r <em class=3D"replaceable"><code>mode</code></em>=
</code>] [<code class=3D"option">-s <em class=3D"replaceable"><code>style</=
code></em></code>] [<code class=3D"option">-t <em class=3D"replaceable"><co=
de>directory</code></em></code>] [<code class=3D"option">-w <em class=3D"re=
placeable"><code>directory</code></em></code>] [<code class=3D"option">-D</=
code>] [<code class=3D"option">-W <em class=3D"replaceable"><code>mode</cod=
e></em></code>] {<code class=3D"option">-o <em class=3D"replaceable"><code>=
filename</code></em></code>} {zonename} {filename}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543694"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543696"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">named-checkzone</strong></span>
       checks the syntax and integrity of a zone file.  It performs the
       same checks as <span><strong class=3D"command">named</strong></span>=
 does when loading a
@@ -53,7 +53,7 @@
      </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543730"></a><h2>OPTIONS</h2>
+<a name=3D"id2543731"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-d</span></dt>
 <dd><p>
@@ -247,14 +247,14 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544377"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2544446"></a><h2>RETURN VALUES</h2>
 <p><span><strong class=3D"command">named-checkzone</strong></span>
       returns an exit status of 1 if
       errors were detected and 0 otherwise.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544389"></a><h2>SEE ALSO</h2>
+<a name=3D"id2544458"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">named</span>=
(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named-che=
ckconf</span>(8)</span>,
       <em class=3D"citetitle">RFC 1035</em>,
@@ -262,7 +262,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544422"></a><h2>AUTHOR</h2>
+<a name=3D"id2544491"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/Makefil=
e.in
--- a/head/contrib/bind9/bin/confgen/Makefile.in	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/confgen/Makefile.in	Tue Apr 17 11:51:51 2012 +=
0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.8 2009-12-05 23:31:40 each Exp $
+# $Id: Makefile.in,v 1.8 2009/12/05 23:31:40 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/ddns-co=
nfgen.8
--- a/head/contrib/bind9/bin/confgen/ddns-confgen.8	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/confgen/ddns-confgen.8	Tue Apr 17 11:51:51 201=
2 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: ddns-confgen.8,v 1.10 2009-09-19 01:14:52 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/ddns-co=
nfgen.c
--- a/head/contrib/bind9/bin/confgen/ddns-confgen.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/confgen/ddns-confgen.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ddns-confgen.c,v 1.9.308.2 2011-03-12 04:59:13 tbox Exp $ */
+/* $Id: ddns-confgen.c,v 1.9.308.2 2011/03/12 04:59:13 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/ddns-co=
nfgen.docbook
--- a/head/contrib/bind9/bin/confgen/ddns-confgen.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/confgen/ddns-confgen.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: ddns-confgen.docbook,v 1.6 2009-09-18 22:08:55 fdupont Exp $ -->
+<!-- $Id: ddns-confgen.docbook,v 1.6 2009/09/18 22:08:55 fdupont Exp $ -->
 <refentry id=3D"man.ddns-confgen">
   <refentryinfo>
     <date>Jan 29, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/ddns-co=
nfgen.html
--- a/head/contrib/bind9/bin/confgen/ddns-confgen.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/confgen/ddns-confgen.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: ddns-confgen.html,v 1.10 2009-09-19 01:14:52 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">ddns-confgen</code> =
 [<code class=3D"option">-a <em class=3D"replaceable"><code>algorithm</code=
></em></code>] [<code class=3D"option">-h</code>] [<code class=3D"option">-=
k <em class=3D"replaceable"><code>keyname</code></em></code>] [<code class=
=3D"option">-r <em class=3D"replaceable"><code>randomfile</code></em></code=
>] [ -s <em class=3D"replaceable"><code>name</code></em>  |   -z <em class=
=3D"replaceable"><code>zone</code></em> ] [<code class=3D"option">-q</code>=
] [name]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543395"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543396"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">ddns-confgen</strong></span>
       generates a key for use by <span><strong class=3D"command">nsupdate<=
/strong></span>
       and <span><strong class=3D"command">named</strong></span>.  It simpl=
ifies configuration
@@ -58,7 +58,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543454"></a><h2>OPTIONS</h2>
+<a name=3D"id2543456"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></span></dt>
 <dd><p>
@@ -125,7 +125,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543642"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543643"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">nsupdate</sp=
an>(1)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named.con=
f</span>(5)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
@@ -133,7 +133,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543681"></a><h2>AUTHOR</h2>
+<a name=3D"id2543682"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/include=
/confgen/os.h
--- a/head/contrib/bind9/bin/confgen/include/confgen/os.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/confgen/include/confgen/os.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: os.h,v 1.3 2009-06-11 23:47:55 tbox Exp $ */
+/* $Id: os.h,v 1.3 2009/06/11 23:47:55 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/keygen.c
--- a/head/contrib/bind9/bin/confgen/keygen.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/confgen/keygen.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keygen.c,v 1.4 2009-11-12 14:02:38 marka Exp $ */
+/* $Id: keygen.c,v 1.4 2009/11/12 14:02:38 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/keygen.h
--- a/head/contrib/bind9/bin/confgen/keygen.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/confgen/keygen.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keygen.h,v 1.3 2009-06-11 23:47:55 tbox Exp $ */
+/* $Id: keygen.h,v 1.3 2009/06/11 23:47:55 tbox Exp $ */
=20
 #ifndef RNDC_KEYGEN_H
 #define RNDC_KEYGEN_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/rndc-co=
nfgen.8
--- a/head/contrib/bind9/bin/confgen/rndc-confgen.8	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/confgen/rndc-confgen.8	Tue Apr 17 11:51:51 201=
2 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: rndc-confgen.8,v 1.7 2009-07-11 01:12:45 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/rndc-co=
nfgen.c
--- a/head/contrib/bind9/bin/confgen/rndc-confgen.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/confgen/rndc-confgen.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rndc-confgen.c,v 1.5.308.2 2011-03-12 04:59:13 tbox Exp $ */
+/* $Id: rndc-confgen.c,v 1.5.308.2 2011/03/12 04:59:13 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/rndc-co=
nfgen.docbook
--- a/head/contrib/bind9/bin/confgen/rndc-confgen.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/confgen/rndc-confgen.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: rndc-confgen.docbook,v 1.4 2009-06-15 23:47:59 tbox Exp $ -->
+<!-- $Id: rndc-confgen.docbook,v 1.4 2009/06/15 23:47:59 tbox Exp $ -->
 <refentry id=3D"man.rndc-confgen">
   <refentryinfo>
     <date>Aug 27, 2001</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/rndc-co=
nfgen.html
--- a/head/contrib/bind9/bin/confgen/rndc-confgen.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/confgen/rndc-confgen.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: rndc-confgen.html,v 1.7 2009-07-11 01:12:45 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">rndc-confgen</code> =
 [<code class=3D"option">-a</code>] [<code class=3D"option">-b <em class=3D=
"replaceable"><code>keysize</code></em></code>] [<code class=3D"option">-c =
<em class=3D"replaceable"><code>keyfile</code></em></code>] [<code class=3D=
"option">-h</code>] [<code class=3D"option">-k <em class=3D"replaceable"><c=
ode>keyname</code></em></code>] [<code class=3D"option">-p <em class=3D"rep=
laceable"><code>port</code></em></code>] [<code class=3D"option">-r <em cla=
ss=3D"replaceable"><code>randomfile</code></em></code>] [<code class=3D"opt=
ion">-s <em class=3D"replaceable"><code>address</code></em></code>] [<code =
class=3D"option">-t <em class=3D"replaceable"><code>chrootdir</code></em></=
code>] [<code class=3D"option">-u <em class=3D"replaceable"><code>user</cod=
e></em></code>]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543432"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543433"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">rndc-confgen</strong></span>
       generates configuration files
       for <span><strong class=3D"command">rndc</strong></span>.  It can be=
 used as a
@@ -48,7 +48,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543477"></a><h2>OPTIONS</h2>
+<a name=3D"id2543478"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a</span></dt>
 <dd>
@@ -155,7 +155,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543790"></a><h2>EXAMPLES</h2>
+<a name=3D"id2543792"></a><h2>EXAMPLES</h2>
 <p>
       To allow <span><strong class=3D"command">rndc</strong></span> to be =
used with
       no manual configuration, run
@@ -172,7 +172,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543832"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543833"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">rndc</span>(=
8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rndc.conf=
</span>(5)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
@@ -180,7 +180,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543870"></a><h2>AUTHOR</h2>
+<a name=3D"id2543872"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/unix/Ma=
kefile.in
--- a/head/contrib/bind9/bin/confgen/unix/Makefile.in	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/bin/confgen/unix/Makefile.in	Tue Apr 17 11:51:51 2=
012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-06-11 23:47:55 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/06/11 23:47:55 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/unix/os=
.c
--- a/head/contrib/bind9/bin/confgen/unix/os.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/confgen/unix/os.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: os.c,v 1.3 2009-06-11 23:47:55 tbox Exp $ */
+/* $Id: os.c,v 1.3 2009/06/11 23:47:55 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/util.c
--- a/head/contrib/bind9/bin/confgen/util.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/confgen/util.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: util.c,v 1.3 2009-06-11 23:47:55 tbox Exp $ */
+/* $Id: util.c,v 1.3 2009/06/11 23:47:55 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/confgen/util.h
--- a/head/contrib/bind9/bin/confgen/util.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/confgen/util.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: util.h,v 1.4 2009-09-29 15:06:05 fdupont Exp $ */
+/* $Id: util.h,v 1.4 2009/09/29 15:06:05 fdupont Exp $ */
=20
 #ifndef RNDC_UTIL_H
 #define RNDC_UTIL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/Makefile.in
--- a/head/contrib/bind9/bin/dig/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.47 2009-12-05 23:31:40 each Exp $
+# $Id: Makefile.in,v 1.47 2009/12/05 23:31:40 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/dig.1
--- a/head/contrib/bind9/bin/dig/dig.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/dig.1	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: dig.1,v 1.54 2010-03-05 01:14:15 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/dig.c
--- a/head/contrib/bind9/bin/dig/dig.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/dig.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dig.c,v 1.237.124.3 2011-03-11 06:46:58 marka Exp $ */
+/* $Id: dig.c,v 1.237.124.4 2011/12/07 17:23:55 each Exp $ */
=20
 /*! \file */
=20
@@ -1527,7 +1527,7 @@
 		if (strncmp(rv[0], "%", 1) =3D=3D 0)
 			break;
 		if (strncmp(rv[0], "@", 1) =3D=3D 0) {
-			addresscount =3D getaddresses(lookup, &rv[0][1]);
+			addresscount =3D getaddresses(lookup, &rv[0][1], NULL);
 		} else if (rv[0][0] =3D=3D '+') {
 			plus_option(&rv[0][1], is_batchfile,
 				    lookup);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/dig.docbook
--- a/head/contrib/bind9/bin/dig/dig.docbook	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/dig.docbook	Tue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dig.docbook,v 1.47 2010-03-04 23:50:34 tbox Exp $ -->
+<!-- $Id: dig.docbook,v 1.47 2010/03/04 23:50:34 tbox Exp $ -->
 <refentry id=3D"man.dig">
=20
   <refentryinfo>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/dig.html
--- a/head/contrib/bind9/bin/dig/dig.html	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/dig.html	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: dig.html,v 1.49 2010-03-05 01:14:15 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -34,7 +34,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dig</code>  [global-=
queryopt...] [query...]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543522"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543524"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dig</strong></span>
       (domain information groper) is a flexible tool
       for interrogating DNS name servers.  It performs DNS lookups and
@@ -80,7 +80,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543595"></a><h2>SIMPLE USAGE</h2>
+<a name=3D"id2543597"></a><h2>SIMPLE USAGE</h2>
 <p>
       A typical invocation of <span><strong class=3D"command">dig</strong>=
</span> looks like:
       </p>
@@ -126,7 +126,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543686"></a><h2>OPTIONS</h2>
+<a name=3D"id2543688"></a><h2>OPTIONS</h2>
 <p>
       The <code class=3D"option">-b</code> option sets the source IP addre=
ss of the query
       to <em class=3D"parameter"><code>address</code></em>.  This must be =
a valid
@@ -230,7 +230,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544035"></a><h2>QUERY OPTIONS</h2>
+<a name=3D"id2544037"></a><h2>QUERY OPTIONS</h2>
 <p><span><strong class=3D"command">dig</strong></span>
       provides a number of query options which affect
       the way in which lookups are made and the results displayed.  Some of
@@ -561,7 +561,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545184"></a><h2>MULTIPLE QUERIES</h2>
+<a name=3D"id2545186"></a><h2>MULTIPLE QUERIES</h2>
 <p>
       The BIND 9 implementation of <span><strong class=3D"command">dig </s=
trong></span>
       supports
@@ -607,7 +607,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545245"></a><h2>IDN SUPPORT</h2>
+<a name=3D"id2545248"></a><h2>IDN SUPPORT</h2>
 <p>
       If <span><strong class=3D"command">dig</strong></span> has been buil=
t with IDN (internationalized
       domain name) support, it can accept and display non-ASCII domain nam=
es.
@@ -621,14 +621,14 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545336"></a><h2>FILES</h2>
+<a name=3D"id2545338"></a><h2>FILES</h2>
 <p><code class=3D"filename">/etc/resolv.conf</code>
     </p>
 <p><code class=3D"filename">${HOME}/.digrc</code>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545353"></a><h2>SEE ALSO</h2>
+<a name=3D"id2545355"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">host</span>(=
1)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-ke=
ygen</span>(8)</span>,
@@ -636,7 +636,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545390"></a><h2>BUGS</h2>
+<a name=3D"id2545393"></a><h2>BUGS</h2>
 <p>
       There are probably too many query options.
     </p>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/dighost.c
--- a/head/contrib/bind9/bin/dig/dighost.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/dighost.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dighost.c,v 1.336.22.4 2011-03-11 06:46:58 marka Exp $ */
+/* $Id: dighost.c,v 1.336.22.9 2011/12/07 17:23:55 each Exp $ */
=20
 /*! \file
  *  \note
@@ -66,6 +66,7 @@
 #include <dns/tsig.h>
=20
 #include <dst/dst.h>
+#include <dst/result.h>
=20
 #include <isc/app.h>
 #include <isc/base64.h>
@@ -81,6 +82,7 @@
 #include <isc/print.h>
 #include <isc/random.h>
 #include <isc/result.h>
+#include <isc/serial.h>
 #include <isc/string.h>
 #include <isc/task.h>
 #include <isc/timer.h>
@@ -360,6 +362,8 @@
 static void
 launch_next_query(dig_query_t *query, isc_boolean_t include_question);
=20
+static void
+send_tcp_connect(dig_query_t *query);
=20
 static void *
 mem_alloc(void *arg, size_t size) {
@@ -742,7 +746,7 @@
 	looknew->xfr_q =3D NULL;
 	looknew->current_query =3D NULL;
 	looknew->doing_xfr =3D ISC_FALSE;
-	looknew->ixfr_serial =3D ISC_FALSE;
+	looknew->ixfr_serial =3D 0;
 	looknew->trace =3D ISC_FALSE;
 	looknew->trace_root =3D ISC_FALSE;
 	looknew->identify =3D ISC_FALSE;
@@ -787,6 +791,7 @@
 	looknew->new_search =3D ISC_FALSE;
 	looknew->done_as_is =3D ISC_FALSE;
 	looknew->need_search =3D ISC_FALSE;
+	dns_fixedname_init(&looknew->fdomain);
 	ISC_LINK_INIT(looknew, link);
 	ISC_LIST_INIT(looknew->q);
 	ISC_LIST_INIT(looknew->my_server_list);
@@ -862,6 +867,8 @@
 	looknew->tsigctx =3D NULL;
 	looknew->need_search =3D lookold->need_search;
 	looknew->done_as_is =3D lookold->done_as_is;
+	dns_name_copy(dns_fixedname_name(&lookold->fdomain),
+		      dns_fixedname_name(&looknew->fdomain), NULL);
=20
 	if (servers)
 		clone_server_list(lookold->my_server_list,
@@ -925,6 +932,11 @@
=20
 	secretsize =3D isc_buffer_usedlength(&secretbuf);
=20
+	if (hmacname =3D=3D NULL) {
+		result =3D DST_R_UNSUPPORTEDALG;
+		goto failure;
+	}
+
 	result =3D dns_name_fromtext(&keyname, namebuf, dns_rootname, 0, namebuf);
 	if (result !=3D ISC_R_SUCCESS)
 		goto failure;
@@ -1698,6 +1710,9 @@
 	isc_result_t result;
 	isc_boolean_t success =3D ISC_FALSE;
 	int numLookups =3D 0;
+	int num;
+	isc_result_t lresult, addresses_result;
+	char bad_namestr[DNS_NAME_FORMATSIZE];
 	dns_name_t *domain;
 	isc_boolean_t horizontal =3D ISC_FALSE, bad =3D ISC_FALSE;
=20
@@ -1705,6 +1720,8 @@
=20
 	debug("following up %s", query->lookup->textname);
=20
+	addresses_result =3D ISC_R_SUCCESS;
+	bad_namestr[0] =3D '\0';
 	for (result =3D dns_message_firstname(msg, section);
 	     result =3D=3D ISC_R_SUCCESS;
 	     result =3D dns_message_nextname(msg, section)) {
@@ -1783,15 +1800,27 @@
 				lookup->trace_root =3D ISC_FALSE;
 				if (lookup->ns_search_only)
 					lookup->recurse =3D ISC_FALSE;
-				dns_fixedname_init(&lookup->fdomain);
 				domain =3D dns_fixedname_name(&lookup->fdomain);
 				dns_name_copy(name, domain, NULL);
 			}
 			debug("adding server %s", namestr);
-			numLookups +=3D getaddresses(lookup, namestr);
+			num =3D getaddresses(lookup, namestr, &lresult);
+			if (lresult !=3D ISC_R_SUCCESS) {
+				debug("couldn't get address for '%s': %s",
+				      namestr, isc_result_totext(lresult));
+				if (addresses_result =3D=3D ISC_R_SUCCESS) {
+					addresses_result =3D lresult;
+					strcpy(bad_namestr, namestr);
+				}
+			}
+			numLookups +=3D num;
 			dns_rdata_reset(&rdata);
 		}
 	}
+	if (numLookups =3D=3D 0 && addresses_result !=3D ISC_R_SUCCESS) {
+		fatal("couldn't get address for '%s': %s",
+		      bad_namestr, isc_result_totext(result));
+	}
=20
 	if (lookup =3D=3D NULL &&
 	    section =3D=3D DNS_SECTION_ANSWER &&
@@ -1838,12 +1867,10 @@
  * Return ISC_TRUE iff there was another searchlist entry.
  */
 static isc_boolean_t
-next_origin(dns_message_t *msg, dig_query_t *query) {
+next_origin(dig_query_t *query) {
 	dig_lookup_t *lookup;
 	dig_searchlist_t *search;
=20
-	UNUSED(msg);
-
 	INSIST(!free_now);
=20
 	debug("next_origin()");
@@ -2318,7 +2345,7 @@
 	query->waiting_senddone =3D ISC_FALSE;
 	l =3D query->lookup;
=20
-	if (l->ns_search_only && !l->trace_root) {
+	if (l->ns_search_only && !l->trace_root && !l->tcp_mode) {
 		debug("sending next, since searching");
 		next =3D ISC_LIST_NEXT(query, link);
 		if (next !=3D NULL)
@@ -2865,8 +2892,10 @@
 	dns_rdataset_t *rdataset =3D NULL;
 	dns_rdata_t rdata =3D DNS_RDATA_INIT;
 	dns_rdata_soa_t soa;
-	isc_uint32_t serial;
+	isc_uint32_t ixfr_serial =3D query->lookup->ixfr_serial, serial;
 	isc_result_t result;
+	isc_boolean_t ixfr =3D query->lookup->rdtype =3D=3D dns_rdatatype_ixfr;
+	isc_boolean_t axfr =3D query->lookup->rdtype =3D=3D dns_rdatatype_axfr;
=20
 	debug("check_for_more_data()");
=20
@@ -2916,6 +2945,7 @@
 					query->second_rr_rcvd =3D ISC_TRUE;
 					query->second_rr_serial =3D 0;
 					debug("got the second rr as nonsoa");
+					axfr =3D ISC_TRUE;
 					goto next_rdata;
 				}
=20
@@ -2925,6 +2955,7 @@
 				 */
 				if (rdata.type !=3D dns_rdatatype_soa)
 					goto next_rdata;
+
 				/* Now we have an SOA.  Work with it. */
 				debug("got an SOA");
 				result =3D dns_rdata_tostruct(&rdata, &soa, NULL);
@@ -2934,15 +2965,17 @@
 				if (!query->first_soa_rcvd) {
 					query->first_soa_rcvd =3D ISC_TRUE;
 					query->first_rr_serial =3D serial;
-					debug("this is the first %d",
-					       query->lookup->ixfr_serial);
-					if (query->lookup->ixfr_serial >=3D
-					    serial)
+					debug("this is the first serial %u",
+					      serial);
+					if (ixfr && isc_serial_ge(ixfr_serial,
+								  serial)) {
+						debug("got up to date "
+						      "response");
 						goto doexit;
+					}
 					goto next_rdata;
 				}
-				if (query->lookup->rdtype =3D=3D
-				    dns_rdatatype_axfr) {
+				if (axfr) {
 					debug("doing axfr, got second SOA");
 					goto doexit;
 				}
@@ -2952,22 +2985,12 @@
 						      "empty zone");
 						goto doexit;
 					}
-					debug("this is the second %d",
-					       query->lookup->ixfr_serial);
+					debug("this is the second serial %u",
+					      serial);
 					query->second_rr_rcvd =3D ISC_TRUE;
 					query->second_rr_serial =3D serial;
 					goto next_rdata;
 				}
-				if (query->second_rr_serial =3D=3D 0) {
-					/*
-					 * If the second RR was a non-SOA
-					 * record, and we're getting any
-					 * other SOA, then this is an
-					 * AXFR, and we're done.
-					 */
-					debug("done, since axfr");
-					goto doexit;
-				}
 				/*
 				 * If we get to this point, we're doing an
 				 * IXFR and have to start really looking
@@ -2983,7 +3006,7 @@
 					debug("done with ixfr");
 					goto doexit;
 				}
-				debug("meaningless soa %d", serial);
+				debug("meaningless soa %u", serial);
 			next_rdata:
 				result =3D dns_rdataset_next(rdataset);
 			} while (result =3D=3D ISC_R_SUCCESS);
@@ -3360,7 +3383,7 @@
 	if (!l->doing_xfr || l->xfr_q =3D=3D query) {
 		if (msg->rcode !=3D dns_rcode_noerror &&
 		    (l->origin !=3D NULL || l->need_search)) {
-			if (!next_origin(msg, query) || showsearch) {
+			if (!next_origin(query) || showsearch) {
 				printmessage(query, msg, ISC_TRUE);
 				received(b->used, &sevent->address, query);
 			}
@@ -3546,7 +3569,7 @@
 }
=20
 int
-getaddresses(dig_lookup_t *lookup, const char *host) {
+getaddresses(dig_lookup_t *lookup, const char *host, isc_result_t *resultp=
) {
 	isc_result_t result;
 	isc_sockaddr_t sockaddrs[DIG_MAX_ADDRESSES];
 	isc_netaddr_t netaddr;
@@ -3556,9 +3579,14 @@
=20
 	result =3D bind9_getaddresses(host, 0, sockaddrs,
 				    DIG_MAX_ADDRESSES, &count);
-	if (result !=3D ISC_R_SUCCESS)
-		fatal("couldn't get address for '%s': %s",
-		      host, isc_result_totext(result));
+	if (resultp !=3D NULL)
+		*resultp =3D result;
+	if (result !=3D ISC_R_SUCCESS) {
+		if (resultp =3D=3D NULL)
+			fatal("couldn't get address for '%s': %s",
+			      host, isc_result_totext(result));
+		return 0;
+	}
=20
 	for (i =3D 0; i < count; i++) {
 		isc_netaddr_fromsockaddr(&netaddr, &sockaddrs[i]);
@@ -4208,7 +4236,6 @@
 	return (result);
 }
=20
-
 isc_result_t
 get_trusted_key(isc_mem_t *mctx)
 {
@@ -4270,6 +4297,7 @@
 		if (key !=3D NULL)
 			dst_key_free(&key);
 	}
+	fclose(fp);
 	return (ISC_R_SUCCESS);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/host.1
--- a/head/contrib/bind9/bin/dig/host.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/host.1	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: host.1,v 1.31 2009-07-11 01:12:45 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/host.c
--- a/head/contrib/bind9/bin/dig/host.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/host.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: host.c,v 1.124.40.3 2011-03-11 06:46:59 marka Exp $ */
+/* $Id: host.c,v 1.124.40.3 2011/03/11 06:46:59 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/host.docbook
--- a/head/contrib/bind9/bin/dig/host.docbook	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/host.docbook	Tue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: host.docbook,v 1.20 2009-01-20 23:47:56 tbox Exp $ -->
+<!-- $Id: host.docbook,v 1.20 2009/01/20 23:47:56 tbox Exp $ -->
 <refentry id=3D"man.host">
=20
   <refentryinfo>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/host.html
--- a/head/contrib/bind9/bin/dig/host.html	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/host.html	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: host.html,v 1.30 2009-07-11 01:12:45 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">host</code>  [<code =
class=3D"option">-aCdlnrsTwv</code>] [<code class=3D"option">-c <em class=
=3D"replaceable"><code>class</code></em></code>] [<code class=3D"option">-N=
 <em class=3D"replaceable"><code>ndots</code></em></code>] [<code class=3D"=
option">-R <em class=3D"replaceable"><code>number</code></em></code>] [<cod=
e class=3D"option">-t <em class=3D"replaceable"><code>type</code></em></cod=
e>] [<code class=3D"option">-W <em class=3D"replaceable"><code>wait</code><=
/em></code>] [<code class=3D"option">-m <em class=3D"replaceable"><code>fla=
g</code></em></code>] [<code class=3D"option">-4</code>] [<code class=3D"op=
tion">-6</code>] {name} [server]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543434"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543436"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">host</strong></span>
       is a simple utility for performing DNS lookups.
       It is normally used to convert names to IP addresses and vice versa.
@@ -184,7 +184,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543800"></a><h2>IDN SUPPORT</h2>
+<a name=3D"id2543802"></a><h2>IDN SUPPORT</h2>
 <p>
       If <span><strong class=3D"command">host</strong></span> has been bui=
lt with IDN (internationalized
       domain name) support, it can accept and display non-ASCII domain nam=
es.=20
@@ -198,12 +198,12 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543822"></a><h2>FILES</h2>
+<a name=3D"id2543825"></a><h2>FILES</h2>
 <p><code class=3D"filename">/etc/resolv.conf</code>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543834"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543836"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dig</span>(1=
)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>.
     </p>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/include/dig=
/dig.h
--- a/head/contrib/bind9/bin/dig/include/dig/dig.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/bin/dig/include/dig/dig.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dig.h,v 1.111.306.2 2011-02-28 01:19:58 tbox Exp $ */
+/* $Id: dig.h,v 1.111.306.3 2011/12/07 17:23:55 each Exp $ */
=20
 #ifndef DIG_H
 #define DIG_H
@@ -289,7 +289,7 @@
 get_address(char *host, in_port_t port, isc_sockaddr_t *sockaddr);
=20
 int
-getaddresses(dig_lookup_t *lookup, const char *host);
+getaddresses(dig_lookup_t *lookup, const char *host, isc_result_t *resultp=
);
=20
 isc_result_t
 get_reverse(char *reverse, size_t len, char *value, isc_boolean_t ip6_int,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/nslookup.1
--- a/head/contrib/bind9/bin/dig/nslookup.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/nslookup.1	Tue Apr 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: nslookup.1,v 1.16 2010-02-23 01:14:31 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/nslookup.c
--- a/head/contrib/bind9/bin/dig/nslookup.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dig/nslookup.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nslookup.c,v 1.127.38.2 2011-02-28 01:19:58 tbox Exp $ */
+/* $Id: nslookup.c,v 1.127.38.2 2011/02/28 01:19:58 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/nslookup.do=
cbook
--- a/head/contrib/bind9/bin/dig/nslookup.docbook	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/bin/dig/nslookup.docbook	Tue Apr 17 11:51:51 2012 =
+0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: nslookup.docbook,v 1.18 2010-02-22 23:49:11 tbox Exp $ -->
+<!-- $Id: nslookup.docbook,v 1.18 2010/02/22 23:49:11 tbox Exp $ -->
 <!--
  - Copyright (c) 1985, 1989
  -    The Regents of the University of California.  All rights reserved.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dig/nslookup.ht=
ml
--- a/head/contrib/bind9/bin/dig/nslookup.html	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/dig/nslookup.html	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: nslookup.html,v 1.23 2010-02-23 01:14:31 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -21,7 +21,7 @@
 <meta name=3D"generator" content=3D"DocBook XSL Stylesheets V1.71.1">
 </head>
 <body bgcolor=3D"white" text=3D"black" link=3D"#0000FF" vlink=3D"#840084" =
alink=3D"#0000FF"><div class=3D"refentry" lang=3D"en">
-<a name=3D"id2476276"></a><div class=3D"titlepage"></div>
+<a name=3D"id2476277"></a><div class=3D"titlepage"></div>
 <div class=3D"refnamediv">
 <h2>Name</h2>
 <p>nslookup — query Internet name servers interactively</p>
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">nslookup</code>  [<c=
ode class=3D"option">-option</code>] [name | -] [server]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543358"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543361"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">Nslookup</strong></span>
       is a program to query Internet domain name servers.  <span><strong c=
lass=3D"command">Nslookup</strong></span>
       has two modes: interactive and non-interactive.  Interactive mode al=
lows
@@ -43,7 +43,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543374"></a><h2>ARGUMENTS</h2>
+<a name=3D"id2543377"></a><h2>ARGUMENTS</h2>
 <p>
       Interactive mode is entered in the following cases:
       </p>
@@ -78,7 +78,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543418"></a><h2>INTERACTIVE COMMANDS</h2>
+<a name=3D"id2543420"></a><h2>INTERACTIVE COMMANDS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><code class=3D"constant">host</code> [<span class=
=3D"optional">server</span>]</span></dt>
 <dd>
@@ -288,19 +288,19 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2546284"></a><h2>FILES</h2>
+<a name=3D"id2546286"></a><h2>FILES</h2>
 <p><code class=3D"filename">/etc/resolv.conf</code>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2546296"></a><h2>SEE ALSO</h2>
+<a name=3D"id2546298"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dig</span>(1=
)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">host</spa=
n>(1)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2546330"></a><h2>Author</h2>
+<a name=3D"id2546332"></a><h2>Author</h2>
 <p>
       Andrew Cherenson
     </p>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/Makefile=
.in
--- a/head/contrib/bind9/bin/dnssec/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/bin/dnssec/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.42 2009-12-05 23:31:40 each Exp $
+# $Id: Makefile.in,v 1.42 2009/12/05 23:31:40 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-d=
sfromkey.8
--- a/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.8	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.8	Tue Apr 17 11:51:51 =
2012 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: dnssec-dsfromkey.8,v 1.13 2010-12-24 01:14:20 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-d=
sfromkey.c
--- a/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2008-2011  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssec-dsfromkey.c,v 1.19 2010-12-23 04:07:59 marka Exp $ */
+/* $Id: dnssec-dsfromkey.c,v 1.19.14.2 2011/09/05 23:45:53 tbox Exp $ */
=20
 /*! \file */
=20
@@ -265,12 +265,10 @@
 		fatal("can't print class");
=20
 	isc_buffer_usedregion(&nameb, &r);
-	isc_util_fwrite(r.base, 1, r.length, stdout);
-
-	putchar(' ');
+	printf("%.*s ", (int)r.length, r.base);
=20
 	isc_buffer_usedregion(&classb, &r);
-	isc_util_fwrite(r.base, 1, r.length, stdout);
+	printf("%.*s", (int)r.length, r.base);
=20
 	if (lookaside =3D=3D NULL)
 		printf(" DS ");
@@ -278,8 +276,7 @@
 		printf(" DLV ");
=20
 	isc_buffer_usedregion(&textb, &r);
-	isc_util_fwrite(r.base, 1, r.length, stdout);
-	putchar('\n');
+	printf("%.*s\n", (int)r.length, r.base);
 }
=20
 ISC_PLATFORM_NORETURN_PRE static void
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-d=
sfromkey.docbook
--- a/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.docbook	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.docbook	Tue Apr 17 11:=
51:51 2012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dnssec-dsfromkey.docbook,v 1.12 2010-12-23 23:47:08 tbox Exp $ -=
->
+<!-- $Id: dnssec-dsfromkey.docbook,v 1.12 2010/12/23 23:47:08 tbox Exp $ -=
->
 <refentry id=3D"man.dnssec-dsfromkey">
   <refentryinfo>
     <date>August 26, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-d=
sfromkey.html
--- a/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.html	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-dsfromkey.html	Tue Apr 17 11:51:=
51 2012 +0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: dnssec-dsfromkey.html,v 1.13 2010-12-24 01:14:19 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,14 +32,14 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-dsfromkey</co=
de>  {-s} [<code class=3D"option">-1</code>] [<code class=3D"option">-2</co=
de>] [<code class=3D"option">-a <em class=3D"replaceable"><code>alg</code><=
/em></code>] [<code class=3D"option">-K <em class=3D"replaceable"><code>dir=
ectory</code></em></code>] [<code class=3D"option">-l <em class=3D"replacea=
ble"><code>domain</code></em></code>] [<code class=3D"option">-s</code>] [<=
code class=3D"option">-c <em class=3D"replaceable"><code>class</code></em><=
/code>] [<code class=3D"option">-f <em class=3D"replaceable"><code>file</co=
de></em></code>] [<code class=3D"option">-A</code>] [<code class=3D"option"=
>-v <em class=3D"replaceable"><code>level</code></em></code>] {dnsname}</p>=
</div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543464"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543465"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-dsfromkey</strong></span>
       outputs the Delegation Signer (DS) resource record (RR), as defined =
in
       RFC 3658 and RFC 4509, for the given key(s).
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543476"></a><h2>OPTIONS</h2>
+<a name=3D"id2543477"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-1</span></dt>
 <dd><p>
@@ -100,7 +100,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543662"></a><h2>EXAMPLE</h2>
+<a name=3D"id2543664"></a><h2>EXAMPLE</h2>
 <p>
       To build the SHA-256 DS RR from the
       <strong class=3D"userinput"><code>Kexample.com.+003+26160</code></st=
rong>
@@ -115,7 +115,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543692"></a><h2>FILES</h2>
+<a name=3D"id2543693"></a><h2>FILES</h2>
 <p>
       The keyfile can be designed by the key identification
       <code class=3D"filename">Knnnn.+aaa+iiiii</code> or the full file na=
me
@@ -129,13 +129,13 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543728"></a><h2>CAVEAT</h2>
+<a name=3D"id2543729"></a><h2>CAVEAT</h2>
 <p>
       A keyfile error can give a "file not found" even if the file exists.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543737"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543738"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-si=
gnzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
@@ -145,7 +145,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543777"></a><h2>AUTHOR</h2>
+<a name=3D"id2543778"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eyfromlabel.8
--- a/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.8	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.8	Tue Apr 17 11:51:=
51 2012 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: dnssec-keyfromlabel.8,v 1.18.14.2 2011-02-28 02:37:42 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eyfromlabel.c
--- a/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssec-keyfromlabel.c,v 1.32.14.2 2011-03-12 04:59:14 tbox Exp $ */
+/* $Id: dnssec-keyfromlabel.c,v 1.32.14.4 2011/11/30 00:51:38 marka Exp $ =
*/
=20
 /*! \file */
=20
@@ -110,7 +110,8 @@
=20
 int
 main(int argc, char **argv) {
-	char		*algname =3D NULL, *nametype =3D NULL, *type =3D NULL;
+	char		*algname =3D NULL, *freeit =3D NULL;
+	char		*nametype =3D NULL, *type =3D NULL;
 	const char	*directory =3D NULL;
 #ifdef USE_PKCS11
 	const char	*engine =3D "pkcs11";
@@ -342,6 +343,9 @@
 			algname =3D strdup(DEFAULT_NSEC3_ALGORITHM);
 		else
 			algname =3D strdup(DEFAULT_ALGORITHM);
+		if (algname =3D=3D NULL)
+			fatal("strdup failed");
+		freeit =3D algname;
 		if (verbose > 0)
 			fprintf(stderr, "no algorithm specified; "
 				"defaulting to %s\n", algname);
@@ -514,8 +518,7 @@
 	 * is a risk of ID collision due to this key or another key
 	 * being revoked.
 	 */
-	if (key_collision(dst_key_id(key), name, directory, alg, mctx, &exact))
-	{
+	if (key_collision(key, name, directory, mctx, &exact)) {
 		isc_buffer_clear(&buf);
 		ret =3D dst_key_buildfilename(key, 0, directory, &buf);
 		if (ret !=3D ISC_R_SUCCESS)
@@ -560,5 +563,8 @@
 	isc_mem_free(mctx, label);
 	isc_mem_destroy(&mctx);
=20
+	if (freeit !=3D NULL)
+		free(freeit);
+
 	return (0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eyfromlabel.docbook
--- a/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.docbook	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.docbook	Tue Apr 17 =
11:51:51 2012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dnssec-keyfromlabel.docbook,v 1.18.14.2 2011-02-28 01:19:58 tbox=
 Exp $ -->
+<!-- $Id: dnssec-keyfromlabel.docbook,v 1.18.14.2 2011/02/28 01:19:58 tbox=
 Exp $ -->
 <refentry id=3D"man.dnssec-keyfromlabel">
   <refentryinfo>
     <date>February 8, 2008</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eyfromlabel.html
--- a/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.html	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keyfromlabel.html	Tue Apr 17 11:=
51:51 2012 +0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: dnssec-keyfromlabel.html,v 1.17.14.2 2011-02-28 02:37:42 tbox Ex=
p $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-keyfromlabel<=
/code>  {-l <em class=3D"replaceable"><code>label</code></em>} [<code class=
=3D"option">-3</code>] [<code class=3D"option">-a <em class=3D"replaceable"=
><code>algorithm</code></em></code>] [<code class=3D"option">-A <em class=
=3D"replaceable"><code>date/offset</code></em></code>] [<code class=3D"opti=
on">-c <em class=3D"replaceable"><code>class</code></em></code>] [<code cla=
ss=3D"option">-D <em class=3D"replaceable"><code>date/offset</code></em></c=
ode>] [<code class=3D"option">-E <em class=3D"replaceable"><code>engine</co=
de></em></code>] [<code class=3D"option">-f <em class=3D"replaceable"><code=
>flag</code></em></code>] [<code class=3D"option">-G</code>] [<code class=
=3D"option">-I <em class=3D"replaceable"><code>date/offset</code></em></cod=
e>] [<code class=3D"option">-k</code>] [<code class=3D"option">-K <em class=
=3D"replaceable"><code>directory</code></em></code>] [<code class=3D"option=
">-n <em class=3D"replaceable"><code>nametype</code></em></code>] [<code cl=
ass=3D"option">-P <em class=3D"replaceable"><code>date/offset</code></em></=
code>] [<code class=3D"option">-p <em class=3D"replaceable"><code>protocol<=
/code></em></code>] [<code class=3D"option">-R <em class=3D"replaceable"><c=
ode>date/offset</code></em></code>] [<code class=3D"option">-t <em class=3D=
"replaceable"><code>type</code></em></code>] [<code class=3D"option">-v <em=
 class=3D"replaceable"><code>level</code></em></code>] [<code class=3D"opti=
on">-y</code>] {name}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543494"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543495"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-keyfromlabel</strong></span>
       gets keys with the given label from a crypto hardware and builds
       key files for DNSSEC (Secure DNS), as defined in RFC 2535
@@ -44,7 +44,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543512"></a><h2>OPTIONS</h2>
+<a name=3D"id2543513"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></span></dt>
 <dd>
@@ -163,7 +163,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543876"></a><h2>TIMING OPTIONS</h2>
+<a name=3D"id2543877"></a><h2>TIMING OPTIONS</h2>
 <p>
       Dates can be expressed in the format YYYYMMDD or YYYYMMDDHHMMSS.
       If the argument begins with a '+' or '-', it is interpreted as
@@ -210,7 +210,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544042"></a><h2>GENERATED KEY FILES</h2>
+<a name=3D"id2544043"></a><h2>GENERATED KEY FILES</h2>
 <p>
       When <span><strong class=3D"command">dnssec-keyfromlabel</strong></s=
pan> completes
       successfully,
@@ -249,7 +249,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544115"></a><h2>SEE ALSO</h2>
+<a name=3D"id2544116"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-si=
gnzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
@@ -257,7 +257,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544148"></a><h2>AUTHOR</h2>
+<a name=3D"id2544149"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eygen.8
--- a/head/contrib/bind9/bin/dnssec/dnssec-keygen.8	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keygen.8	Tue Apr 17 11:51:51 201=
2 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: dnssec-keygen.8,v 1.55 2010-12-24 01:14:19 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eygen.c
--- a/head/contrib/bind9/bin/dnssec/dnssec-keygen.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keygen.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -29,7 +29,7 @@
  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssec-keygen.c,v 1.115.14.2 2011-03-12 04:59:14 tbox Exp $ */
+/* $Id: dnssec-keygen.c,v 1.115.14.4 2011/11/30 00:51:38 marka Exp $ */
=20
 /*! \file */
=20
@@ -197,7 +197,8 @@
=20
 int
 main(int argc, char **argv) {
-	char		*algname =3D NULL, *nametype =3D NULL, *type =3D NULL;
+	char		*algname =3D NULL, *freeit =3D NULL;
+	char		*nametype =3D NULL, *type =3D NULL;
 	char		*classname =3D NULL;
 	char		*endp;
 	dst_key_t	*key =3D NULL;
@@ -509,6 +510,9 @@
 				algname =3D strdup(DEFAULT_NSEC3_ALGORITHM);
 			else
 				algname =3D strdup(DEFAULT_ALGORITHM);
+			if (algname =3D=3D NULL)
+				fatal("strdup failed");
+			freeit =3D algname;
 			if (verbose > 0)
 				fprintf(stderr, "no algorithm specified; "
 						"defaulting to %s\n", algname);
@@ -965,8 +969,7 @@
 		 * if there is a risk of ID collision due to this key
 		 * or another key being revoked.
 		 */
-		if (key_collision(dst_key_id(key), name, directory,
-				  alg, mctx, NULL)) {
+		if (key_collision(key, name, directory, mctx, NULL)) {
 			conflict =3D ISC_TRUE;
 			if (null_key) {
 				dst_key_free(&key);
@@ -1020,5 +1023,8 @@
 		isc_mem_stats(mctx, stdout);
 	isc_mem_destroy(&mctx);
=20
+	if (freeit !=3D NULL)
+		free(freeit);
+
 	return (0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eygen.docbook
--- a/head/contrib/bind9/bin/dnssec/dnssec-keygen.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keygen.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dnssec-keygen.docbook,v 1.36 2010-12-23 04:07:59 marka Exp $ -->
+<!-- $Id: dnssec-keygen.docbook,v 1.36 2010/12/23 04:07:59 marka Exp $ -->
 <refentry id=3D"man.dnssec-keygen">
   <refentryinfo>
     <date>June 30, 2000</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-k=
eygen.html
--- a/head/contrib/bind9/bin/dnssec/dnssec-keygen.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-keygen.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: dnssec-keygen.html,v 1.47 2010-12-24 01:14:20 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-keygen</code>=
  [<code class=3D"option">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></code>] [<code class=3D"option">-b <em class=3D"replaceable"><code>=
keysize</code></em></code>] [<code class=3D"option">-n <em class=3D"replace=
able"><code>nametype</code></em></code>] [<code class=3D"option">-3</code>]=
 [<code class=3D"option">-A <em class=3D"replaceable"><code>date/offset</co=
de></em></code>] [<code class=3D"option">-C</code>] [<code class=3D"option"=
>-c <em class=3D"replaceable"><code>class</code></em></code>] [<code class=
=3D"option">-D <em class=3D"replaceable"><code>date/offset</code></em></cod=
e>] [<code class=3D"option">-E <em class=3D"replaceable"><code>engine</code=
></em></code>] [<code class=3D"option">-e</code>] [<code class=3D"option">-=
f <em class=3D"replaceable"><code>flag</code></em></code>] [<code class=3D"=
option">-G</code>] [<code class=3D"option">-g <em class=3D"replaceable"><co=
de>generator</code></em></code>] [<code class=3D"option">-h</code>] [<code =
class=3D"option">-I <em class=3D"replaceable"><code>date/offset</code></em>=
</code>] [<code class=3D"option">-i <em class=3D"replaceable"><code>interva=
l</code></em></code>] [<code class=3D"option">-K <em class=3D"replaceable">=
<code>directory</code></em></code>] [<code class=3D"option">-k</code>] [<co=
de class=3D"option">-P <em class=3D"replaceable"><code>date/offset</code></=
em></code>] [<code class=3D"option">-p <em class=3D"replaceable"><code>prot=
ocol</code></em></code>] [<code class=3D"option">-q</code>] [<code class=3D=
"option">-R <em class=3D"replaceable"><code>date/offset</code></em></code>]=
 [<code class=3D"option">-r <em class=3D"replaceable"><code>randomdev</code=
></em></code>] [<code class=3D"option">-S <em class=3D"replaceable"><code>k=
ey</code></em></code>] [<code class=3D"option">-s <em class=3D"replaceable"=
><code>strength</code></em></code>] [<code class=3D"option">-t <em class=3D=
"replaceable"><code>type</code></em></code>] [<code class=3D"option">-v <em=
 class=3D"replaceable"><code>level</code></em></code>] [<code class=3D"opti=
on">-z</code>] {name}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543578"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543579"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-keygen</strong></span>
       generates keys for DNSSEC (Secure DNS), as defined in RFC 2535
       and RFC 4034.  It can also generate keys for use with
@@ -46,7 +46,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543596"></a><h2>OPTIONS</h2>
+<a name=3D"id2543597"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></span></dt>
 <dd>
@@ -248,7 +248,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544301"></a><h2>TIMING OPTIONS</h2>
+<a name=3D"id2544166"></a><h2>TIMING OPTIONS</h2>
 <p>
       Dates can be expressed in the format YYYYMMDD or YYYYMMDDHHMMSS.
       If the argument begins with a '+' or '-', it is interpreted as
@@ -319,7 +319,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544491"></a><h2>GENERATED KEYS</h2>
+<a name=3D"id2544356"></a><h2>GENERATED KEYS</h2>
 <p>
       When <span><strong class=3D"command">dnssec-keygen</strong></span> c=
ompletes
       successfully,
@@ -365,7 +365,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544642"></a><h2>EXAMPLE</h2>
+<a name=3D"id2544506"></a><h2>EXAMPLE</h2>
 <p>
       To generate a 768-bit DSA key for the domain
       <strong class=3D"userinput"><code>example.com</code></strong>, the f=
ollowing command would be
@@ -386,7 +386,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544685"></a><h2>SEE ALSO</h2>
+<a name=3D"id2544550"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-signz=
one</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 2539</em>,
@@ -395,7 +395,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544716"></a><h2>AUTHOR</h2>
+<a name=3D"id2544581"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-r=
evoke.8
--- a/head/contrib/bind9/bin/dnssec/dnssec-revoke.8	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-revoke.8	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2009 Internet Systems Consortium, Inc. ("ISC")
+.\" Copyright (C) 2009, 2011 Internet Systems Consortium, Inc. ("ISC")
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
 .\" purpose with or without fee is hereby granted, provided that the above
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: dnssec-revoke.8,v 1.9 2010-05-19 01:14:14 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -32,7 +32,7 @@
 dnssec\-revoke \- Set the REVOKED bit on a DNSSEC key
 .SH "SYNOPSIS"
 .HP 14
-\fBdnssec\-revoke\fR [\fB\-hr\fR] [\fB\-v\ \fR\fB\fIlevel\fR\fR] [\fB\-K\ =
\fR\fB\fIdirectory\fR\fR] [\fB\-E\ \fR\fB\fIengine\fR\fR] [\fB\-f\fR] {keyf=
ile}
+\fBdnssec\-revoke\fR [\fB\-hr\fR] [\fB\-v\ \fR\fB\fIlevel\fR\fR] [\fB\-K\ =
\fR\fB\fIdirectory\fR\fR] [\fB\-E\ \fR\fB\fIengine\fR\fR] [\fB\-f\fR] [\fB\=
-R\fR] {keyfile}
 .SH "DESCRIPTION"
 .PP
 \fBdnssec\-revoke\fR
@@ -70,6 +70,11 @@
 \fBdnssec\-revoke\fR
 to write the new key pair even if a file already exists matching the algor=
ithm and key ID of the revoked key.
 .RE
+.PP
+\-R
+.RS 4
+Print the key tag of the key with the REVOKE bit set but do not revoke the=
 key.
+.RE
 .SH "SEE ALSO"
 .PP
 \fBdnssec\-keygen\fR(8),
@@ -79,5 +84,5 @@
 .PP
 Internet Systems Consortium
 .SH "COPYRIGHT"
-Copyright \(co 2009 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2009, 2011 Internet Systems Consortium, Inc. ("ISC")
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-r=
evoke.c
--- a/head/contrib/bind9/bin/dnssec/dnssec-revoke.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-revoke.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009, 2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssec-revoke.c,v 1.22 2010-05-06 23:50:56 tbox Exp $ */
+/* $Id: dnssec-revoke.c,v 1.22.124.2 2011/10/20 23:46:27 tbox Exp $ */
=20
 /*! \file */
=20
@@ -92,6 +92,7 @@
 	isc_buffer_t buf;
 	isc_boolean_t force =3D ISC_FALSE;
 	isc_boolean_t remove =3D ISC_FALSE;
+	isc_boolean_t id =3D ISC_FALSE;
=20
 	if (argc =3D=3D 1)
 		usage();
@@ -104,7 +105,7 @@
=20
 	isc_commandline_errprint =3D ISC_FALSE;
=20
-	while ((ch =3D isc_commandline_parse(argc, argv, "E:fK:rhv:")) !=3D -1) {
+	while ((ch =3D isc_commandline_parse(argc, argv, "E:fK:rRhv:")) !=3D -1) {
 		switch (ch) {
 		    case 'E':
 			engine =3D isc_commandline_argument;
@@ -126,6 +127,9 @@
 		    case 'r':
 			remove =3D ISC_TRUE;
 			break;
+		    case 'R':
+			id =3D ISC_TRUE;
+			break;
 		    case 'v':
 			verbose =3D strtol(isc_commandline_argument, &endp, 0);
 			if (*endp !=3D '\0')
@@ -186,6 +190,10 @@
 		fatal("Invalid keyfile name %s: %s",
 		      filename, isc_result_totext(result));
=20
+	if (id) {
+		fprintf(stdout, "%u\n", dst_key_rid(key));
+		goto cleanup;
+	}
 	dst_key_format(key, keystr, sizeof(keystr));
=20
 	if (verbose > 2)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-r=
evoke.docbook
--- a/head/contrib/bind9/bin/dnssec/dnssec-revoke.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-revoke.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
                [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2009, 2011  Internet Systems Consortium, Inc. ("ISC")
  -
  - Permission to use, copy, modify, and/or distribute this software for any
  - purpose with or without fee is hereby granted, provided that the above
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dnssec-revoke.docbook,v 1.7 2009-11-03 21:44:46 each Exp $ -->
+<!-- $Id: dnssec-revoke.docbook,v 1.7.266.2 2011/10/20 23:46:27 tbox Exp $=
 -->
 <refentry id=3D"man.dnssec-revoke">
   <refentryinfo>
     <date>June 1, 2009</date>
@@ -37,6 +37,7 @@
   <docinfo>
     <copyright>
       <year>2009</year>
+      <year>2011</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
   </docinfo>
@@ -49,6 +50,7 @@
       <arg><option>-K <replaceable class=3D"parameter">directory</replacea=
ble></option></arg>
       <arg><option>-E <replaceable class=3D"parameter">engine</replaceable=
></option></arg>
       <arg><option>-f</option></arg>
+      <arg><option>-R</option></arg>
       <arg choice=3D"req">keyfile</arg>
     </cmdsynopsis>
   </refsynopsisdiv>
@@ -123,6 +125,16 @@
           </para>
         </listitem>
       </varlistentry>
+
+      <varlistentry>
+        <term>-R</term>
+        <listitem>
+          <para>
+	    Print the key tag of the key with the REVOKE bit set but do
+	    not revoke the key.
+          </para>
+        </listitem>
+      </varlistentry>
     </variablelist>
   </refsect1>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-r=
evoke.html
--- a/head/contrib/bind9/bin/dnssec/dnssec-revoke.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-revoke.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2009 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2009, 2011 Internet Systems Consortium, Inc. ("ISC")
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
  - purpose with or without fee is hereby granted, provided that the above
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: dnssec-revoke.html,v 1.9 2010-05-19 01:14:14 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -28,10 +28,10 @@
 </div>
 <div class=3D"refsynopsisdiv">
 <h2>Synopsis</h2>
-<div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-revoke</code>=
  [<code class=3D"option">-hr</code>] [<code class=3D"option">-v <em class=
=3D"replaceable"><code>level</code></em></code>] [<code class=3D"option">-K=
 <em class=3D"replaceable"><code>directory</code></em></code>] [<code class=
=3D"option">-E <em class=3D"replaceable"><code>engine</code></em></code>] [=
<code class=3D"option">-f</code>] {keyfile}</p></div>
+<div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-revoke</code>=
  [<code class=3D"option">-hr</code>] [<code class=3D"option">-v <em class=
=3D"replaceable"><code>level</code></em></code>] [<code class=3D"option">-K=
 <em class=3D"replaceable"><code>directory</code></em></code>] [<code class=
=3D"option">-E <em class=3D"replaceable"><code>engine</code></em></code>] [=
<code class=3D"option">-f</code>] [<code class=3D"option">-R</code>] {keyfi=
le}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543373"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543382"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-revoke</strong></span>
       reads a DNSSEC key file, sets the REVOKED bit on the key as defined
       in RFC 5011, and creates a new pair of key files containing the
@@ -39,7 +39,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543385"></a><h2>OPTIONS</h2>
+<a name=3D"id2543394"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-h</span></dt>
 <dd><p>
@@ -69,17 +69,22 @@
             write the new key pair even if a file already exists matching
             the algorithm and key ID of the revoked key.
           </p></dd>
+<dt><span class=3D"term">-R</span></dt>
+<dd><p>
+	    Print the key tag of the key with the REVOKE bit set but do
+	    not revoke the key.
+          </p></dd>
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543491"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543512"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 5011</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543515"></a><h2>AUTHOR</h2>
+<a name=3D"id2543537"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ettime.8
--- a/head/contrib/bind9/bin/dnssec/dnssec-settime.8	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-settime.8	Tue Apr 17 11:51:51 20=
12 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: dnssec-settime.8,v 1.14.70.1 2011-03-22 02:37:44 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -52,7 +52,7 @@
 .PP
 When key metadata fields are changed, both files of a key pair (\fIKnnnn.+=
aaa+iiiii.key\fR
 and
-\fIKnnnn.+aaa+iiiii.private\fR) are regenerated. Metadata fields are store=
d in the private file. A human\-readable description of the metadata is als=
o placed in comments in the key file.
+\fIKnnnn.+aaa+iiiii.private\fR) are regenerated. Metadata fields are store=
d in the private file. A human\-readable description of the metadata is als=
o placed in comments in the key file. The private file's permissions are al=
ways set to be inaccessible to anyone other than the owner (mode 0600).
 .SH "OPTIONS"
 .PP
 \-f
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ettime.c
--- a/head/contrib/bind9/bin/dnssec/dnssec-settime.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-settime.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssec-settime.c,v 1.28.16.3 2011-06-02 20:24:11 each Exp $ */
+/* $Id: dnssec-settime.c,v 1.28.16.3 2011/06/02 20:24:11 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ettime.docbook
--- a/head/contrib/bind9/bin/dnssec/dnssec-settime.docbook	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-settime.docbook	Tue Apr 17 11:51=
:51 2012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dnssec-settime.docbook,v 1.11.70.2 2011-03-21 23:46:58 tbox Exp =
$ -->
+<!-- $Id: dnssec-settime.docbook,v 1.11.70.3 2011/11/03 20:21:30 each Exp =
$ -->
 <refentry id=3D"man.dnssec-settime">
   <refentryinfo>
     <date>July 15, 2009</date>
@@ -82,7 +82,8 @@
       <filename>Knnnn.+aaa+iiiii.private</filename>) are regenerated.
       Metadata fields are stored in the private file.  A human-readable
       description of the metadata is also placed in comments in the key
-      file.
+      file.  The private file's permissions are always set to be
+      inaccessible to anyone other than the owner (mode 0600).
     </para>
   </refsect1>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ettime.html
--- a/head/contrib/bind9/bin/dnssec/dnssec-settime.html	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-settime.html	Tue Apr 17 11:51:51=
 2012 +0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: dnssec-settime.html,v 1.14.70.1 2011-03-22 02:37:44 tbox Exp $ -=
->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-settime</code=
>  [<code class=3D"option">-f</code>] [<code class=3D"option">-K <em class=
=3D"replaceable"><code>directory</code></em></code>] [<code class=3D"option=
">-P <em class=3D"replaceable"><code>date/offset</code></em></code>] [<code=
 class=3D"option">-A <em class=3D"replaceable"><code>date/offset</code></em=
></code>] [<code class=3D"option">-R <em class=3D"replaceable"><code>date/o=
ffset</code></em></code>] [<code class=3D"option">-I <em class=3D"replaceab=
le"><code>date/offset</code></em></code>] [<code class=3D"option">-D <em cl=
ass=3D"replaceable"><code>date/offset</code></em></code>] [<code class=3D"o=
ption">-h</code>] [<code class=3D"option">-v <em class=3D"replaceable"><cod=
e>level</code></em></code>] [<code class=3D"option">-E <em class=3D"replace=
able"><code>engine</code></em></code>] {keyfile}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543422"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543424"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-settime</strong></span>
       reads a DNSSEC private key file and sets the key timing metadata
       as specified by the <code class=3D"option">-P</code>, <code class=3D=
"option">-A</code>,
@@ -52,11 +52,12 @@
       <code class=3D"filename">Knnnn.+aaa+iiiii.private</code>) are regene=
rated.
       Metadata fields are stored in the private file.  A human-readable
       description of the metadata is also placed in comments in the key
-      file.
+      file.  The private file's permissions are always set to be
+      inaccessible to anyone other than the owner (mode 0600).
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543470"></a><h2>OPTIONS</h2>
+<a name=3D"id2543472"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-f</span></dt>
 <dd><p>
@@ -89,7 +90,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543562"></a><h2>TIMING OPTIONS</h2>
+<a name=3D"id2543563"></a><h2>TIMING OPTIONS</h2>
 <p>
       Dates can be expressed in the format YYYYMMDD or YYYYMMDDHHMMSS.
       If the argument begins with a '+' or '-', it is interpreted as
@@ -168,7 +169,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543701"></a><h2>PRINTING OPTIONS</h2>
+<a name=3D"id2543770"></a><h2>PRINTING OPTIONS</h2>
 <p>
       <span><strong class=3D"command">dnssec-settime</strong></span> can a=
lso be used to print the
       timing metadata associated with a key.
@@ -194,7 +195,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543915"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543848"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-si=
gnzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
@@ -202,7 +203,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543948"></a><h2>AUTHOR</h2>
+<a name=3D"id2543881"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ignzone.8
--- a/head/contrib/bind9/bin/dnssec/dnssec-signzone.8	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-signzone.8	Tue Apr 17 11:51:51 2=
012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: dnssec-signzone.8,v 1.59 2009-12-04 01:13:44 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ignzone.c
--- a/head/contrib/bind9/bin/dnssec/dnssec-signzone.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-signzone.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -29,7 +29,7 @@
  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssec-signzone.c,v 1.262.110.9 2011-07-19 23:47:12 tbox Exp $ */
+/* $Id: dnssec-signzone.c,v 1.262.110.9 2011/07/19 23:47:12 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ignzone.docbook
--- a/head/contrib/bind9/bin/dnssec/dnssec-signzone.docbook	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-signzone.docbook	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dnssec-signzone.docbook,v 1.44 2009-12-03 23:18:16 each Exp $ -->
+<!-- $Id: dnssec-signzone.docbook,v 1.44 2009/12/03 23:18:16 each Exp $ -->
 <refentry id=3D"man.dnssec-signzone">
   <refentryinfo>
     <date>June 05, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssec-s=
ignzone.html
--- a/head/contrib/bind9/bin/dnssec/dnssec-signzone.html	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/bin/dnssec/dnssec-signzone.html	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: dnssec-signzone.html,v 1.45 2009-12-04 01:13:44 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-signzone</cod=
e>  [<code class=3D"option">-a</code>] [<code class=3D"option">-c <em class=
=3D"replaceable"><code>class</code></em></code>] [<code class=3D"option">-d=
 <em class=3D"replaceable"><code>directory</code></em></code>] [<code class=
=3D"option">-E <em class=3D"replaceable"><code>engine</code></em></code>] [=
<code class=3D"option">-e <em class=3D"replaceable"><code>end-time</code></=
em></code>] [<code class=3D"option">-f <em class=3D"replaceable"><code>outp=
ut-file</code></em></code>] [<code class=3D"option">-g</code>] [<code class=
=3D"option">-h</code>] [<code class=3D"option">-K <em class=3D"replaceable"=
><code>directory</code></em></code>] [<code class=3D"option">-k <em class=
=3D"replaceable"><code>key</code></em></code>] [<code class=3D"option">-l <=
em class=3D"replaceable"><code>domain</code></em></code>] [<code class=3D"o=
ption">-i <em class=3D"replaceable"><code>interval</code></em></code>] [<co=
de class=3D"option">-I <em class=3D"replaceable"><code>input-format</code><=
/em></code>] [<code class=3D"option">-j <em class=3D"replaceable"><code>jit=
ter</code></em></code>] [<code class=3D"option">-N <em class=3D"replaceable=
"><code>soa-serial-format</code></em></code>] [<code class=3D"option">-o <e=
m class=3D"replaceable"><code>origin</code></em></code>] [<code class=3D"op=
tion">-O <em class=3D"replaceable"><code>output-format</code></em></code>] =
[<code class=3D"option">-p</code>] [<code class=3D"option">-P</code>] [<cod=
e class=3D"option">-r <em class=3D"replaceable"><code>randomdev</code></em>=
</code>] [<code class=3D"option">-S</code>] [<code class=3D"option">-s <em =
class=3D"replaceable"><code>start-time</code></em></code>] [<code class=3D"=
option">-T <em class=3D"replaceable"><code>ttl</code></em></code>] [<code c=
lass=3D"option">-t</code>] [<code class=3D"option">-u</code>] [<code class=
=3D"option">-v <em class=3D"replaceable"><code>level</code></em></code>] [<=
code class=3D"option">-x</code>] [<code class=3D"option">-z</code>] [<code =
class=3D"option">-3 <em class=3D"replaceable"><code>salt</code></em></code>=
] [<code class=3D"option">-H <em class=3D"replaceable"><code>iterations</co=
de></em></code>] [<code class=3D"option">-A</code>] {zonefile} [key...]</p>=
</div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543596"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543597"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-signzone</strong></span>
       signs a zone.  It generates
       NSEC and RRSIG records and produces a signed version of the
@@ -43,7 +43,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543611"></a><h2>OPTIONS</h2>
+<a name=3D"id2543612"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a</span></dt>
 <dd><p>
@@ -379,7 +379,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544896"></a><h2>EXAMPLE</h2>
+<a name=3D"id2544965"></a><h2>EXAMPLE</h2>
 <p>
       The following command signs the <strong class=3D"userinput"><code>ex=
ample.com</code></strong>
       zone with the DSA key generated by <span><strong class=3D"command">d=
nssec-keygen</strong></span>
@@ -409,14 +409,14 @@
 %</pre>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545019"></a><h2>SEE ALSO</h2>
+<a name=3D"id2545020"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 4033</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545044"></a><h2>AUTHOR</h2>
+<a name=3D"id2545045"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssecto=
ol.c
--- a/head/contrib/bind9/bin/dnssec/dnssectool.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/dnssec/dnssectool.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009, 2010  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009-2011  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssectool.c,v 1.60 2010-01-19 23:48:56 tbox Exp $ */
+/* $Id: dnssectool.c,v 1.60.162.3 2011/10/21 03:56:32 marka Exp $ */
=20
 /*! \file */
=20
@@ -406,19 +406,24 @@
 }
=20
 isc_boolean_t
-key_collision(isc_uint16_t id, dns_name_t *name, const char *dir,
-	      dns_secalg_t alg, isc_mem_t *mctx, isc_boolean_t *exact)
+key_collision(dst_key_t *dstkey, dns_name_t *name, const char *dir,
+	      isc_mem_t *mctx, isc_boolean_t *exact)
 {
 	isc_result_t result;
 	isc_boolean_t conflict =3D ISC_FALSE;
 	dns_dnsseckeylist_t matchkeys;
 	dns_dnsseckey_t *key =3D NULL;
-	isc_uint16_t oldid, diff;
-	isc_uint16_t bits =3D DNS_KEYFLAG_REVOKE;   /* flag bits to look for */
+	isc_uint16_t id, oldid;
+	isc_uint32_t rid, roldid;
+	dns_secalg_t alg;
=20
 	if (exact !=3D NULL)
 		*exact =3D ISC_FALSE;
=20
+	id =3D dst_key_id(dstkey);
+	rid =3D dst_key_rid(dstkey);
+	alg =3D dst_key_alg(dstkey);
+
 	ISC_LIST_INIT(matchkeys);
 	result =3D dns_dnssec_findmatchingkeys(name, dir, mctx, &matchkeys);
 	if (result =3D=3D ISC_R_NOTFOUND)
@@ -430,10 +435,11 @@
 			goto next;
=20
 		oldid =3D dst_key_id(key->key);
-		diff =3D (oldid > id) ? (oldid - id) : (id - oldid);
-		if ((diff & ~bits) =3D=3D 0) {
+		roldid =3D dst_key_rid(key->key);
+
+		if (oldid =3D=3D rid || roldid =3D=3D id || id =3D=3D oldid) {
 			conflict =3D ISC_TRUE;
-			if (diff !=3D 0) {
+			if (id !=3D oldid) {
 				if (verbose > 1)
 					fprintf(stderr, "Key ID %d could "
 						"collide with %d\n",
@@ -461,4 +467,3 @@
=20
 	return (conflict);
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/dnssec/dnssecto=
ol.h
--- a/head/contrib/bind9/bin/dnssec/dnssectool.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/dnssec/dnssectool.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2007-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004, 2007-2011  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssectool.h,v 1.31 2010-01-19 23:48:56 tbox Exp $ */
+/* $Id: dnssectool.h,v 1.31.162.2 2011/10/20 23:46:27 tbox Exp $ */
=20
 #ifndef DNSSECTOOL_H
 #define DNSSECTOOL_H 1
@@ -78,6 +78,7 @@
 set_keyversion(dst_key_t *key);
=20
 isc_boolean_t
-key_collision(isc_uint16_t id, dns_name_t *name, const char *dir,
-	      dns_secalg_t alg, isc_mem_t *mctx, isc_boolean_t *exact);
+key_collision(dst_key_t *key, dns_name_t *name, const char *dir,
+	      isc_mem_t *mctx, isc_boolean_t *exact);
+
 #endif /* DNSSEC_DNSSECTOOL_H */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/Makefile.=
in
--- a/head/contrib/bind9/bin/named/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/named/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.114.14.2 2011-03-10 23:47:25 tbox Exp $
+# $Id: Makefile.in,v 1.114.14.2 2011/03/10 23:47:25 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/bind.keys=
.h
--- a/head/contrib/bind9/bin/named/bind.keys.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/named/bind.keys.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,6 +1,6 @@
 /*
- * Generated by bindkeys.pl 1.7 2011-01-04 23:47:13 tbox Exp =20
- * From bind.keys 1.7 2011-01-03 23:45:07 each Exp =20
+ * Generated by bindkeys.pl 1.7 2011/01/04 23:47:13 tbox Exp =20
+ * From bind.keys 1.7 2011/01/03 23:45:07 each Exp =20
  */
 #define TRUSTED_KEYS "\
 # The bind.keys file is used to override the built-in DNSSEC trust anchors=
\n\
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/bind9.xsl
--- a/head/contrib/bind9/bin/named/bind9.xsl	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/bind9.xsl	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: bind9.xsl,v 1.21 2009-01-27 23:47:54 tbox Exp $ -->
+<!-- $Id: bind9.xsl,v 1.21 2009/01/27 23:47:54 tbox Exp $ -->
=20
 <xsl:stylesheet version=3D"1.0"
    xmlns:xsl=3D"http://www.w3.org/1999/XSL/Transform"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/bind9.xsl=
.h
--- a/head/contrib/bind9/bin/named/bind9.xsl.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/named/bind9.xsl.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,6 +1,6 @@
 /*
- * Generated by convertxsl.pl 1.14 2008-07-17 23:43:26 jinmei Exp =20
- * From bind9.xsl 1.21 2009-01-27 23:47:54 tbox Exp=20
+ * Generated by convertxsl.pl 1.14 2008/07/17 23:43:26 jinmei Exp =20
+ * From bind9.xsl 1.21 2009/01/27 23:47:54 tbox Exp=20
  */
 static char xslmsg[] =3D
 	"<?xml version=3D\"1.0\" encoding=3D\"UTF-8\"?>\n"
@@ -20,7 +20,7 @@
 	" - PERFORMANCE OF THIS SOFTWARE.\n"
 	"-->\n"
 	"\n"
-	"<!-- \045Id: bind9.xsl,v 1.21 2009-01-27 23:47:54 tbox Exp \045 -->\n"
+	"<!-- \045Id: bind9.xsl,v 1.21 2009/01/27 23:47:54 tbox Exp \045 -->\n"
 	"\n"
 	"<xsl:stylesheet version=3D\"1.0\"\n"
 	" xmlns:xsl=3D\"http://www.w3.org/1999/XSL/Transform\"\n"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/builtin.c
--- a/head/contrib/bind9/bin/named/builtin.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/builtin.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009-2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009-2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 2001-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: builtin.c,v 1.20 2011-01-07 23:47:07 tbox Exp $ */
+/* $Id: builtin.c,v 1.20.14.3 2012/01/11 20:19:40 ckb Exp $ */
=20
 /*! \file
  * \brief
@@ -300,6 +300,7 @@
 	const char **p;
 	static const char *authors[] =3D {
 		"Mark Andrews",
+		"Curtis Blackburn",
 		"James Brister",
 		"Ben Cottrell",
 		"Michael Graff",
@@ -308,6 +309,7 @@
 		"Evan Hunt",
 		"JINMEI Tatuya",
 		"David Lawrence",
+		"Scott Mann",
 		"Danny Mayer",
 		"Damien Neil",
 		"Matt Nelson",
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/client.c
--- a/head/contrib/bind9/bin/named/client.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/client.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: client.c,v 1.271.10.2 2011-07-28 04:30:54 marka Exp $ */
+/* $Id: client.c,v 1.271.10.4 2012/01/31 23:46:39 tbox Exp $ */
=20
 #include <config.h>
=20
@@ -934,6 +934,15 @@
 		render_opts =3D 0;
 	else
 		render_opts =3D DNS_MESSAGERENDER_OMITDNSSEC;
+
+	preferred_glue =3D 0;
+	if (client->view !=3D NULL) {
+		if (client->view->preferred_glue =3D=3D dns_rdatatype_a)
+			preferred_glue =3D DNS_MESSAGERENDER_PREFER_A;
+		else if (client->view->preferred_glue =3D=3D dns_rdatatype_aaaa)
+			preferred_glue =3D DNS_MESSAGERENDER_PREFER_AAAA;
+	}
+
 #ifdef ALLOW_FILTER_AAAA_ON_V4
 	/*
 	 * filter-aaaa-on-v4 yes or break-dnssec option to suppress
@@ -942,17 +951,15 @@
 	 * that we have both AAAA and A records,
 	 * and that we either have no signatures that the client wants
 	 * or we are supposed to break DNSSEC.
+	 *
+	 * Override preferred glue if necessary.
 	 */
-	if ((client->attributes & NS_CLIENTATTR_FILTER_AAAA) !=3D 0)
+	if ((client->attributes & NS_CLIENTATTR_FILTER_AAAA) !=3D 0) {
 		render_opts |=3D DNS_MESSAGERENDER_FILTER_AAAA;
+		if (preferred_glue =3D=3D DNS_MESSAGERENDER_PREFER_AAAA)
+			preferred_glue =3D DNS_MESSAGERENDER_PREFER_A;
+	}
 #endif
-	preferred_glue =3D 0;
-	if (client->view !=3D NULL) {
-		if (client->view->preferred_glue =3D=3D dns_rdatatype_a)
-			preferred_glue =3D DNS_MESSAGERENDER_PREFER_A;
-		else if (client->view->preferred_glue =3D=3D dns_rdatatype_aaaa)
-			preferred_glue =3D DNS_MESSAGERENDER_PREFER_AAAA;
-	}
=20
 	/*
 	 * XXXRTH  The following doesn't deal with TCP buffer resizing.
@@ -2109,6 +2116,9 @@
 	client->recursionquota =3D NULL;
 	client->interface =3D NULL;
 	client->peeraddr_valid =3D ISC_FALSE;
+#ifdef ALLOW_FILTER_AAAA_ON_V4
+	client->filter_aaaa =3D dns_v4_aaaa_ok;
+#endif
 	ISC_EVENT_INIT(&client->ctlevent, sizeof(client->ctlevent), 0, NULL,
 		       NS_EVENT_CLIENTCONTROL, client_start, client, client,
 		       NULL, NULL);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/config.c
--- a/head/contrib/bind9/bin/named/config.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/config.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: config.c,v 1.113.16.2 2011-02-28 01:19:58 tbox Exp $ */
+/* $Id: config.c,v 1.113.16.2 2011/02/28 01:19:58 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/control.c
--- a/head/contrib/bind9/bin/named/control.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/control.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: control.c,v 1.41 2010-12-03 22:05:19 each Exp $ */
+/* $Id: control.c,v 1.41 2010/12/03 22:05:19 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/controlco=
nf.c
--- a/head/contrib/bind9/bin/named/controlconf.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/named/controlconf.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2008, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 2001-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: controlconf.c,v 1.60.544.2 2011-03-12 04:59:14 tbox Exp $ */
+/* $Id: controlconf.c,v 1.60.544.3 2011/12/22 08:10:09 marka Exp $ */
=20
 /*! \file */
=20
@@ -373,17 +373,8 @@
 		if (result =3D=3D ISC_R_SUCCESS)
 			break;
 		isc_mem_put(listener->mctx, secret.rstart, REGION_SIZE(secret));
-		if (result =3D=3D ISCCC_R_BADAUTH) {
-			/*
-			 * For some reason, request is non-NULL when
-			 * isccc_cc_fromwire returns ISCCC_R_BADAUTH.
-			 */
-			if (request !=3D NULL)
-				isccc_sexpr_free(&request);
-		} else {
-			log_invalid(&conn->ccmsg, result);
-			goto cleanup;
-		}
+		log_invalid(&conn->ccmsg, result);
+		goto cleanup;
 	}
=20
 	if (key =3D=3D NULL) {
@@ -1148,6 +1139,11 @@
 	if (result =3D=3D ISC_R_SUCCESS)
 		isc_socket_setname(listener->sock, "control", NULL);
=20
+#ifndef ISC_ALLOW_MAPPED
+	if (result =3D=3D ISC_R_SUCCESS)
+		isc_socket_ipv6only(listener->sock, ISC_TRUE);
+#endif
+
 	if (result =3D=3D ISC_R_SUCCESS)
 		result =3D isc_socket_bind(listener->sock, &listener->address,
 					 ISC_SOCKET_REUSEADDRESS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/convertxs=
l.pl
--- a/head/contrib/bind9/bin/named/convertxsl.pl	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/named/convertxsl.pl	Tue Apr 17 11:51:51 2012 +=
0300
@@ -14,12 +14,12 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: convertxsl.pl,v 1.14 2008-07-17 23:43:26 jinmei Exp $
+# $Id: convertxsl.pl,v 1.14 2008/07/17 23:43:26 jinmei Exp $
=20
 use strict;
 use warnings;
=20
-my $rev =3D '$Id: convertxsl.pl,v 1.14 2008-07-17 23:43:26 jinmei Exp $';
+my $rev =3D '$Id: convertxsl.pl,v 1.14 2008/07/17 23:43:26 jinmei Exp $';
 $rev =3D~ s/\$//g;
 $rev =3D~ s/,v//g;
 $rev =3D~ s/Id: //;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/d=
lz/dlz_dlopen_driver.h
--- a/head/contrib/bind9/bin/named/include/dlz/dlz_dlopen_driver.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/dlz/dlz_dlopen_driver.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlz_dlopen_driver.h,v 1.1.4.4 2011-03-17 09:41:06 fdupont Exp $ */
+/* $Id: dlz_dlopen_driver.h,v 1.1.4.4 2011/03/17 09:41:06 fdupont Exp $ */
=20
 #ifndef DLZ_DLOPEN_DRIVER_H
 #define DLZ_DLOPEN_DRIVER_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/builtin.h
--- a/head/contrib/bind9/bin/named/include/named/builtin.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/builtin.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: builtin.h,v 1.6 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: builtin.h,v 1.6 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_BUILTIN_H
 #define NAMED_BUILTIN_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/client.h
--- a/head/contrib/bind9/bin/named/include/named/client.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/client.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: client.h,v 1.91 2009-10-26 23:14:53 each Exp $ */
+/* $Id: client.h,v 1.91.278.2 2012/01/31 23:46:39 tbox Exp $ */
=20
 #ifndef NAMED_CLIENT_H
 #define NAMED_CLIENT_H 1
@@ -141,6 +141,9 @@
 	isc_netaddr_t		destaddr;
 	struct in6_pktinfo	pktinfo;
 	isc_event_t		ctlevent;
+#ifdef ALLOW_FILTER_AAAA_ON_V4
+	dns_v4_aaaa_t		filter_aaaa;
+#endif
 	/*%
 	 * Information about recent FORMERR response(s), for
 	 * FORMERR loop avoidance.  This is separate for each
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/config.h
--- a/head/contrib/bind9/bin/named/include/named/config.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/config.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: config.h,v 1.16 2009-06-11 23:47:55 tbox Exp $ */
+/* $Id: config.h,v 1.16 2009/06/11 23:47:55 tbox Exp $ */
=20
 #ifndef NAMED_CONFIG_H
 #define NAMED_CONFIG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/control.h
--- a/head/contrib/bind9/bin/named/include/named/control.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/control.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: control.h,v 1.31 2010-08-16 22:21:06 marka Exp $ */
+/* $Id: control.h,v 1.31 2010/08/16 22:21:06 marka Exp $ */
=20
 #ifndef NAMED_CONTROL_H
 #define NAMED_CONTROL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/globals.h
--- a/head/contrib/bind9/bin/named/include/named/globals.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/globals.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: globals.h,v 1.89.54.2 2011-06-17 23:47:10 tbox Exp $ */
+/* $Id: globals.h,v 1.89.54.2 2011/06/17 23:47:10 tbox Exp $ */
=20
 #ifndef NAMED_GLOBALS_H
 #define NAMED_GLOBALS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/interfacemgr.h
--- a/head/contrib/bind9/bin/named/include/named/interfacemgr.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/interfacemgr.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: interfacemgr.h,v 1.33 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: interfacemgr.h,v 1.33 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_INTERFACEMGR_H
 #define NAMED_INTERFACEMGR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/listenlist.h
--- a/head/contrib/bind9/bin/named/include/named/listenlist.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/listenlist.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: listenlist.h,v 1.15 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: listenlist.h,v 1.15 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_LISTENLIST_H
 #define NAMED_LISTENLIST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/log.h
--- a/head/contrib/bind9/bin/named/include/named/log.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/log.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.h,v 1.27 2009-01-07 23:47:46 tbox Exp $ */
+/* $Id: log.h,v 1.27 2009/01/07 23:47:46 tbox Exp $ */
=20
 #ifndef NAMED_LOG_H
 #define NAMED_LOG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/logconf.h
--- a/head/contrib/bind9/bin/named/include/named/logconf.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/logconf.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: logconf.h,v 1.17 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: logconf.h,v 1.17 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_LOGCONF_H
 #define NAMED_LOGCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/lwaddr.h
--- a/head/contrib/bind9/bin/named/include/named/lwaddr.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/lwaddr.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwaddr.h,v 1.8 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: lwaddr.h,v 1.8 2007/06/19 23:46:59 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/lwdclient.h
--- a/head/contrib/bind9/bin/named/include/named/lwdclient.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/lwdclient.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwdclient.h,v 1.20 2009-01-17 23:47:42 tbox Exp $ */
+/* $Id: lwdclient.h,v 1.20 2009/01/17 23:47:42 tbox Exp $ */
=20
 #ifndef NAMED_LWDCLIENT_H
 #define NAMED_LWDCLIENT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/lwresd.h
--- a/head/contrib/bind9/bin/named/include/named/lwresd.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/lwresd.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwresd.h,v 1.19 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: lwresd.h,v 1.19 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_LWRESD_H
 #define NAMED_LWRESD_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/lwsearch.h
--- a/head/contrib/bind9/bin/named/include/named/lwsearch.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/lwsearch.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwsearch.h,v 1.9 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: lwsearch.h,v 1.9 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_LWSEARCH_H
 #define NAMED_LWSEARCH_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/main.h
--- a/head/contrib/bind9/bin/named/include/named/main.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/main.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: main.h,v 1.17 2009-09-29 23:48:03 tbox Exp $ */
+/* $Id: main.h,v 1.17 2009/09/29 23:48:03 tbox Exp $ */
=20
 #ifndef NAMED_MAIN_H
 #define NAMED_MAIN_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/notify.h
--- a/head/contrib/bind9/bin/named/include/named/notify.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/notify.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: notify.h,v 1.16 2009-01-17 23:47:42 tbox Exp $ */
+/* $Id: notify.h,v 1.16 2009/01/17 23:47:42 tbox Exp $ */
=20
 #ifndef NAMED_NOTIFY_H
 #define NAMED_NOTIFY_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/ns_smf_globals.h
--- a/head/contrib/bind9/bin/named/include/named/ns_smf_globals.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/ns_smf_globals.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ns_smf_globals.h,v 1.7 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: ns_smf_globals.h,v 1.7 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NS_SMF_GLOBALS_H
 #define NS_SMF_GLOBALS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/query.h
--- a/head/contrib/bind9/bin/named/include/named/query.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/query.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: query.h,v 1.45 2011-01-13 04:59:24 tbox Exp $ */
+/* $Id: query.h,v 1.45 2011/01/13 04:59:24 tbox Exp $ */
=20
 #ifndef NAMED_QUERY_H
 #define NAMED_QUERY_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/server.h
--- a/head/contrib/bind9/bin/named/include/named/server.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/server.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: server.h,v 1.110 2010-08-16 23:46:52 tbox Exp $ */
+/* $Id: server.h,v 1.110 2010/08/16 23:46:52 tbox Exp $ */
=20
 #ifndef NAMED_SERVER_H
 #define NAMED_SERVER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/sortlist.h
--- a/head/contrib/bind9/bin/named/include/named/sortlist.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/sortlist.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sortlist.h,v 1.11 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: sortlist.h,v 1.11 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_SORTLIST_H
 #define NAMED_SORTLIST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/statschannel.h
--- a/head/contrib/bind9/bin/named/include/named/statschannel.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/statschannel.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: statschannel.h,v 1.3 2008-04-03 05:55:51 marka Exp $ */
+/* $Id: statschannel.h,v 1.3 2008/04/03 05:55:51 marka Exp $ */
=20
 #ifndef NAMED_STATSCHANNEL_H
 #define NAMED_STATSCHANNEL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/tkeyconf.h
--- a/head/contrib/bind9/bin/named/include/named/tkeyconf.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/tkeyconf.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tkeyconf.h,v 1.16 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: tkeyconf.h,v 1.16 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NS_TKEYCONF_H
 #define NS_TKEYCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/tsigconf.h
--- a/head/contrib/bind9/bin/named/include/named/tsigconf.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/tsigconf.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsigconf.h,v 1.18 2009-06-11 23:47:55 tbox Exp $ */
+/* $Id: tsigconf.h,v 1.18 2009/06/11 23:47:55 tbox Exp $ */
=20
 #ifndef NS_TSIGCONF_H
 #define NS_TSIGCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/types.h
--- a/head/contrib/bind9/bin/named/include/named/types.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/types.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: types.h,v 1.31 2009-01-09 23:47:45 tbox Exp $ */
+/* $Id: types.h,v 1.31 2009/01/09 23:47:45 tbox Exp $ */
=20
 #ifndef NAMED_TYPES_H
 #define NAMED_TYPES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/update.h
--- a/head/contrib/bind9/bin/named/include/named/update.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/update.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: update.h,v 1.13 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: update.h,v 1.13 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_UPDATE_H
 #define NAMED_UPDATE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/xfrout.h
--- a/head/contrib/bind9/bin/named/include/named/xfrout.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/xfrout.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: xfrout.h,v 1.12 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: xfrout.h,v 1.12 2007/06/19 23:46:59 tbox Exp $ */
=20
 #ifndef NAMED_XFROUT_H
 #define NAMED_XFROUT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/include/n=
amed/zoneconf.h
--- a/head/contrib/bind9/bin/named/include/named/zoneconf.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/include/named/zoneconf.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zoneconf.h,v 1.28 2010-12-20 23:47:20 tbox Exp $ */
+/* $Id: zoneconf.h,v 1.28 2010/12/20 23:47:20 tbox Exp $ */
=20
 #ifndef NS_ZONECONF_H
 #define NS_ZONECONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/interface=
mgr.c
--- a/head/contrib/bind9/bin/named/interfacemgr.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/bin/named/interfacemgr.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: interfacemgr.c,v 1.95.426.2 2011-03-12 04:59:14 tbox Exp $ */
+/* $Id: interfacemgr.c,v 1.95.426.2 2011/03/12 04:59:14 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/listenlis=
t.c
--- a/head/contrib/bind9/bin/named/listenlist.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/bin/named/listenlist.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: listenlist.c,v 1.14 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: listenlist.c,v 1.14 2007/06/19 23:46:59 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/log.c
--- a/head/contrib/bind9/bin/named/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.c,v 1.49 2009-01-07 01:46:40 jinmei Exp $ */
+/* $Id: log.c,v 1.49 2009/01/07 01:46:40 jinmei Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/logconf.c
--- a/head/contrib/bind9/bin/named/logconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/logconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: logconf.c,v 1.42.816.3 2011-03-05 23:52:06 tbox Exp $ */
+/* $Id: logconf.c,v 1.42.816.3 2011/03/05 23:52:06 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwaddr.c
--- a/head/contrib/bind9/bin/named/lwaddr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwaddr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwaddr.c,v 1.10 2008-01-11 23:46:56 tbox Exp $ */
+/* $Id: lwaddr.c,v 1.10 2008/01/11 23:46:56 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwdclient=
.c
--- a/head/contrib/bind9/bin/named/lwdclient.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/named/lwdclient.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwdclient.c,v 1.22 2007-06-18 23:47:18 tbox Exp $ */
+/* $Id: lwdclient.c,v 1.22 2007/06/18 23:47:18 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwderror.c
--- a/head/contrib/bind9/bin/named/lwderror.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwderror.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwderror.c,v 1.12 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: lwderror.c,v 1.12 2007/06/19 23:46:59 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwdgabn.c
--- a/head/contrib/bind9/bin/named/lwdgabn.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwdgabn.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwdgabn.c,v 1.24 2009-09-02 23:48:01 tbox Exp $ */
+/* $Id: lwdgabn.c,v 1.24 2009/09/02 23:48:01 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwdgnba.c
--- a/head/contrib/bind9/bin/named/lwdgnba.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwdgnba.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwdgnba.c,v 1.22 2008-01-14 23:46:56 tbox Exp $ */
+/* $Id: lwdgnba.c,v 1.22 2008/01/14 23:46:56 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwdgrbn.c
--- a/head/contrib/bind9/bin/named/lwdgrbn.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwdgrbn.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwdgrbn.c,v 1.22 2009-09-02 23:48:01 tbox Exp $ */
+/* $Id: lwdgrbn.c,v 1.22 2009/09/02 23:48:01 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwdnoop.c
--- a/head/contrib/bind9/bin/named/lwdnoop.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwdnoop.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwdnoop.c,v 1.13 2008-01-22 23:28:04 tbox Exp $ */
+/* $Id: lwdnoop.c,v 1.13 2008/01/22 23:28:04 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwresd.8
--- a/head/contrib/bind9/bin/named/lwresd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwresd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwresd.8,v 1.31 2009-07-11 01:12:45 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwresd.c
--- a/head/contrib/bind9/bin/named/lwresd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwresd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwresd.c,v 1.60 2009-09-02 23:48:01 tbox Exp $ */
+/* $Id: lwresd.c,v 1.60 2009/09/02 23:48:01 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwresd.do=
cbook
--- a/head/contrib/bind9/bin/named/lwresd.docbook	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/bin/named/lwresd.docbook	Tue Apr 17 11:51:51 2012 =
+0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwresd.docbook,v 1.20 2009-01-20 23:47:56 tbox Exp $ -->
+<!-- $Id: lwresd.docbook,v 1.20 2009/01/20 23:47:56 tbox Exp $ -->
 <refentry>
   <refentryinfo>
     <date>June 30, 2000</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwresd.ht=
ml
--- a/head/contrib/bind9/bin/named/lwresd.html	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/named/lwresd.html	Tue Apr 17 11:51:51 2012 +03=
00
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwresd.html,v 1.27 2009-07-11 01:12:45 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -22,7 +22,7 @@
 <meta name=3D"generator" content=3D"DocBook XSL Stylesheets V1.71.1">
 </head>
 <body bgcolor=3D"white" text=3D"black" link=3D"#0000FF" vlink=3D"#840084" =
alink=3D"#0000FF"><div class=3D"refentry" lang=3D"en">
-<a name=3D"id2476275"></a><div class=3D"titlepage"></div>
+<a name=3D"id2476274"></a><div class=3D"titlepage"></div>
 <div class=3D"refnamediv">
 <h2>Name</h2>
 <p><span class=3D"application">lwresd</span> — lightweight resolver =
daemon</p>
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">lwresd</code>  [<cod=
e class=3D"option">-c <em class=3D"replaceable"><code>config-file</code></e=
m></code>] [<code class=3D"option">-C <em class=3D"replaceable"><code>confi=
g-file</code></em></code>] [<code class=3D"option">-d <em class=3D"replacea=
ble"><code>debug-level</code></em></code>] [<code class=3D"option">-f</code=
>] [<code class=3D"option">-g</code>] [<code class=3D"option">-i <em class=
=3D"replaceable"><code>pid-file</code></em></code>] [<code class=3D"option"=
>-m <em class=3D"replaceable"><code>flag</code></em></code>] [<code class=
=3D"option">-n <em class=3D"replaceable"><code>#cpus</code></em></code>] [<=
code class=3D"option">-P <em class=3D"replaceable"><code>port</code></em></=
code>] [<code class=3D"option">-p <em class=3D"replaceable"><code>port</cod=
e></em></code>] [<code class=3D"option">-s</code>] [<code class=3D"option">=
-t <em class=3D"replaceable"><code>directory</code></em></code>] [<code cla=
ss=3D"option">-u <em class=3D"replaceable"><code>user</code></em></code>] [=
<code class=3D"option">-v</code>] [<code class=3D"option">-4</code>] [<code=
 class=3D"option">-6</code>]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543467"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543469"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">lwresd</strong></span>
       is the daemon providing name lookup
       services to clients that use the BIND 9 lightweight resolver
@@ -67,7 +67,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543514"></a><h2>OPTIONS</h2>
+<a name=3D"id2543516"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-4</span></dt>
 <dd><p>
@@ -197,7 +197,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543931"></a><h2>FILES</h2>
+<a name=3D"id2543933"></a><h2>FILES</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><code class=3D"filename">/etc/resolv.conf</code><=
/span></dt>
 <dd><p>
@@ -210,14 +210,14 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543971"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543973"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">named</span>=
(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres</sp=
an>(3)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">resolver<=
/span>(5)</span>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544005"></a><h2>AUTHOR</h2>
+<a name=3D"id2544007"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/lwsearch.c
--- a/head/contrib/bind9/bin/named/lwsearch.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/lwsearch.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwsearch.c,v 1.13 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: lwsearch.c,v 1.13 2007/06/19 23:46:59 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/main.c
--- a/head/contrib/bind9/bin/named/main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: main.c,v 1.180.14.3 2011-03-11 06:47:00 marka Exp $ */
+/* $Id: main.c,v 1.180.14.4 2011/11/05 00:45:52 each Exp $ */
=20
 /*! \file */
=20
@@ -793,6 +793,25 @@
 	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
 		      ISC_LOG_NOTICE, "built with %s", ns_g_configargs);
=20
+	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
+		      ISC_LOG_NOTICE,
+		      "----------------------------------------------------");
+	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
+		      ISC_LOG_NOTICE,
+		      "BIND 9 is maintained by Internet Systems Consortium,");
+	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
+		      ISC_LOG_NOTICE,
+		      "Inc. (ISC), a non-profit 501(c)(3) public-benefit ");
+	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
+		      ISC_LOG_NOTICE,
+		      "corporation.  Support and training for BIND 9 are ");
+	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
+		      ISC_LOG_NOTICE,
+		      "available at https://www.isc.org/support");
+	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_MAIN,
+		      ISC_LOG_NOTICE,
+		      "----------------------------------------------------");
+
 	dump_symboltable();
=20
 	/*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/named.8
--- a/head/contrib/bind9/bin/named/named.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/named.8	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: named.8,v 1.41 2009-10-06 01:14:41 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/named.con=
f.5
--- a/head/contrib/bind9/bin/named/named.conf.5	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/bin/named/named.conf.5	Tue Apr 17 11:51:51 2012 +0=
300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: named.conf.5,v 1.44.12.1 2011-02-03 12:29:12 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -254,8 +254,7 @@
 	disable\-algorithms \fIstring\fR { \fIstring\fR; ... };
 	dnssec\-enable \fIboolean\fR;
 	dnssec\-validation \fIboolean\fR;
-	dnssec\-lookaside \fIstring\fR trust\-anchor \fIstring\fR;
-	dnssec\-lookaside ( \fIauto\fR | \fIdomain\fR trust\-anchor \fIdomain\fR =
);
+	dnssec\-lookaside ( \fIauto\fR | \fIno\fR | \fIdomain\fR trust\-anchor \f=
Idomain\fR );
 	dnssec\-must\-be\-secure \fIstring\fR \fIboolean\fR;
 	dnssec\-accept\-expired \fIboolean\fR;
 	dns64\-server \fIstring\fR;
@@ -424,7 +423,7 @@
 	disable\-algorithms \fIstring\fR { \fIstring\fR; ... };
 	dnssec\-enable \fIboolean\fR;
 	dnssec\-validation \fIboolean\fR;
-	dnssec\-lookaside \fIstring\fR trust\-anchor \fIstring\fR;
+	dnssec\-lookaside ( \fIauto\fR | \fIno\fR | \fIdomain\fR trust\-anchor \f=
Idomain\fR );
 	dnssec\-must\-be\-secure \fIstring\fR \fIboolean\fR;
 	dnssec\-accept\-expired \fIboolean\fR;
 	dns64\-server \fIstring\fR;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/named.con=
f.docbook
--- a/head/contrib/bind9/bin/named/named.conf.docbook	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/bin/named/named.conf.docbook	Tue Apr 17 11:51:51 2=
012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: named.conf.docbook,v 1.49.14.1 2011-02-03 05:50:05 marka Exp $ -=
->
+<!-- $Id: named.conf.docbook,v 1.49.14.2 2011/11/07 00:31:47 marka Exp $ -=
->
 <refentry>
   <refentryinfo>
     <date>Aug 13, 2004</date>
@@ -285,8 +285,7 @@
 	disable-algorithms <replaceable>string</replaceable> { <replaceable>strin=
g</replaceable>; ... };
 	dnssec-enable <replaceable>boolean</replaceable>;
 	dnssec-validation <replaceable>boolean</replaceable>;
-	dnssec-lookaside <replaceable>string</replaceable> trust-anchor <replacea=
ble>string</replaceable>;
-	dnssec-lookaside ( <replaceable>auto</replaceable> | <replaceable>domain<=
/replaceable> trust-anchor <replaceable>domain</replaceable> );
+	dnssec-lookaside ( <replaceable>auto</replaceable> | <replaceable>no</rep=
laceable> | <replaceable>domain</replaceable> trust-anchor <replaceable>dom=
ain</replaceable> );
 	dnssec-must-be-secure <replaceable>string</replaceable> <replaceable>bool=
ean</replaceable>;
 	dnssec-accept-expired <replaceable>boolean</replaceable>;
=20
@@ -473,7 +472,7 @@
 	disable-algorithms <replaceable>string</replaceable> { <replaceable>strin=
g</replaceable>; ... };
 	dnssec-enable <replaceable>boolean</replaceable>;
 	dnssec-validation <replaceable>boolean</replaceable>;
-	dnssec-lookaside <replaceable>string</replaceable> trust-anchor <replacea=
ble>string</replaceable>;
+	dnssec-lookaside ( <replaceable>auto</replaceable> | <replaceable>no</rep=
laceable> | <replaceable>domain</replaceable> trust-anchor <replaceable>dom=
ain</replaceable> );
 	dnssec-must-be-secure <replaceable>string</replaceable> <replaceable>bool=
ean</replaceable>;
 	dnssec-accept-expired <replaceable>boolean</replaceable>;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/named.con=
f.html
--- a/head/contrib/bind9/bin/named/named.conf.html	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/bin/named/named.conf.html	Tue Apr 17 11:51:51 2012=
 +0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: named.conf.html,v 1.53.12.1 2011-02-03 12:29:12 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named.conf</code> </=
p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543352"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543353"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"filename">named.conf</code> is the configuration file
       for
       <span><strong class=3D"command">named</strong></span>.  Statements a=
re enclosed
@@ -50,14 +50,14 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543380"></a><h2>ACL</h2>
+<a name=3D"id2543381"></a><h2>ACL</h2>
 <div class=3D"literallayout"><p><br>
 acl=A0<em class=3D"replaceable"><code>string</code></em>=A0{=A0<em class=
=3D"replaceable"><code>address_match_element</code></em>;=A0...=A0};<br>
 <br>
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543396"></a><h2>KEY</h2>
+<a name=3D"id2543397"></a><h2>KEY</h2>
 <div class=3D"literallayout"><p><br>
 key=A0<em class=3D"replaceable"><code>domain_name</code></em>=A0{<br>
 	algorithm=A0<em class=3D"replaceable"><code>string</code></em>;<br>
@@ -66,7 +66,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543415"></a><h2>MASTERS</h2>
+<a name=3D"id2543416"></a><h2>MASTERS</h2>
 <div class=3D"literallayout"><p><br>
 masters=A0<em class=3D"replaceable"><code>string</code></em>=A0[<span clas=
s=3D"optional">=A0port=A0<em class=3D"replaceable"><code>integer</code></em=
>=A0</span>]=A0{<br>
 	(=A0<em class=3D"replaceable"><code>masters</code></em>=A0|=A0<em class=
=3D"replaceable"><code>ipv4_address</code></em>=A0[<span class=3D"optional"=
>port=A0<em class=3D"replaceable"><code>integer</code></em></span>]=A0|<br>
@@ -75,7 +75,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543461"></a><h2>SERVER</h2>
+<a name=3D"id2543462"></a><h2>SERVER</h2>
 <div class=3D"literallayout"><p><br>
 server=A0(=A0<em class=3D"replaceable"><code>ipv4_address[<span class=3D"o=
ptional">/prefixlen</span>]</code></em>=A0|=A0<em class=3D"replaceable"><co=
de>ipv6_address[<span class=3D"optional">/prefixlen</span>]</code></em>=A0)=
=A0{<br>
 	bogus=A0<em class=3D"replaceable"><code>boolean</code></em>;<br>
@@ -97,7 +97,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543529"></a><h2>TRUSTED-KEYS</h2>
+<a name=3D"id2543530"></a><h2>TRUSTED-KEYS</h2>
 <div class=3D"literallayout"><p><br>
 trusted-keys=A0{<br>
 	<em class=3D"replaceable"><code>domain_name</code></em>=A0<em class=3D"re=
placeable"><code>flags</code></em>=A0<em class=3D"replaceable"><code>protoc=
ol</code></em>=A0<em class=3D"replaceable"><code>algorithm</code></em>=A0<e=
m class=3D"replaceable"><code>key</code></em>;=A0...=A0<br>
@@ -105,7 +105,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543555"></a><h2>MANAGED-KEYS</h2>
+<a name=3D"id2543556"></a><h2>MANAGED-KEYS</h2>
 <div class=3D"literallayout"><p><br>
 managed-keys=A0{<br>
 	<em class=3D"replaceable"><code>domain_name</code></em>=A0<code class=3D"=
constant">initial-key</code>=A0<em class=3D"replaceable"><code>flags</code>=
</em>=A0<em class=3D"replaceable"><code>protocol</code></em>=A0<em class=3D=
"replaceable"><code>algorithm</code></em>=A0<em class=3D"replaceable"><code=
>key</code></em>;=A0...=A0<br>
@@ -113,7 +113,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543584"></a><h2>CONTROLS</h2>
+<a name=3D"id2543585"></a><h2>CONTROLS</h2>
 <div class=3D"literallayout"><p><br>
 controls=A0{<br>
 	inet=A0(=A0<em class=3D"replaceable"><code>ipv4_address</code></em>=A0|=
=A0<em class=3D"replaceable"><code>ipv6_address</code></em>=A0|=A0*=A0)<br>
@@ -125,7 +125,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543619"></a><h2>LOGGING</h2>
+<a name=3D"id2543620"></a><h2>LOGGING</h2>
 <div class=3D"literallayout"><p><br>
 logging=A0{<br>
 	channel=A0<em class=3D"replaceable"><code>string</code></em>=A0{<br>
@@ -143,7 +143,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543657"></a><h2>LWRES</h2>
+<a name=3D"id2543658"></a><h2>LWRES</h2>
 <div class=3D"literallayout"><p><br>
 lwres=A0{<br>
 	listen-on=A0[<span class=3D"optional">=A0port=A0<em class=3D"replaceable"=
><code>integer</code></em>=A0</span>]=A0{<br>
@@ -156,7 +156,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543699"></a><h2>OPTIONS</h2>
+<a name=3D"id2543700"></a><h2>OPTIONS</h2>
 <div class=3D"literallayout"><p><br>
 options=A0{<br>
 	avoid-v4-udp-ports=A0{=A0<em class=3D"replaceable"><code>port</code></em>=
;=A0...=A0};<br>
@@ -251,8 +251,7 @@
 	disable-algorithms=A0<em class=3D"replaceable"><code>string</code></em>=
=A0{=A0<em class=3D"replaceable"><code>string</code></em>;=A0...=A0};<br>
 	dnssec-enable=A0<em class=3D"replaceable"><code>boolean</code></em>;<br>
 	dnssec-validation=A0<em class=3D"replaceable"><code>boolean</code></em>;<=
br>
-	dnssec-lookaside=A0<em class=3D"replaceable"><code>string</code></em>=A0t=
rust-anchor=A0<em class=3D"replaceable"><code>string</code></em>;<br>
-	dnssec-lookaside=A0(=A0<em class=3D"replaceable"><code>auto</code></em>=
=A0|=A0<em class=3D"replaceable"><code>domain</code></em>=A0trust-anchor=A0=
<em class=3D"replaceable"><code>domain</code></em>=A0);<br>
+	dnssec-lookaside=A0(=A0<em class=3D"replaceable"><code>auto</code></em>=
=A0|=A0<em class=3D"replaceable"><code>no</code></em>=A0|=A0<em class=3D"re=
placeable"><code>domain</code></em>=A0trust-anchor=A0<em class=3D"replaceab=
le"><code>domain</code></em>=A0);<br>
 	dnssec-must-be-secure=A0<em class=3D"replaceable"><code>string</code></em=
>=A0<em class=3D"replaceable"><code>boolean</code></em>;<br>
 	dnssec-accept-expired=A0<em class=3D"replaceable"><code>boolean</code></e=
m>;<br>
 <br>
@@ -361,7 +360,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544577"></a><h2>VIEW</h2>
+<a name=3D"id2544574"></a><h2>VIEW</h2>
 <div class=3D"literallayout"><p><br>
 view=A0<em class=3D"replaceable"><code>string</code></em>=A0<em class=3D"r=
eplaceable"><code>optional_class</code></em>=A0{<br>
 	match-clients=A0{=A0<em class=3D"replaceable"><code>address_match_element=
</code></em>;=A0...=A0};<br>
@@ -438,7 +437,7 @@
 	disable-algorithms=A0<em class=3D"replaceable"><code>string</code></em>=
=A0{=A0<em class=3D"replaceable"><code>string</code></em>;=A0...=A0};<br>
 	dnssec-enable=A0<em class=3D"replaceable"><code>boolean</code></em>;<br>
 	dnssec-validation=A0<em class=3D"replaceable"><code>boolean</code></em>;<=
br>
-	dnssec-lookaside=A0<em class=3D"replaceable"><code>string</code></em>=A0t=
rust-anchor=A0<em class=3D"replaceable"><code>string</code></em>;<br>
+	dnssec-lookaside=A0(=A0<em class=3D"replaceable"><code>auto</code></em>=
=A0|=A0<em class=3D"replaceable"><code>no</code></em>=A0|=A0<em class=3D"re=
placeable"><code>domain</code></em>=A0trust-anchor=A0<em class=3D"replaceab=
le"><code>domain</code></em>=A0);<br>
 	dnssec-must-be-secure=A0<em class=3D"replaceable"><code>string</code></em=
>=A0<em class=3D"replaceable"><code>boolean</code></em>;<br>
 	dnssec-accept-expired=A0<em class=3D"replaceable"><code>boolean</code></e=
m>;<br>
 <br>
@@ -524,7 +523,7 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545280"></a><h2>ZONE</h2>
+<a name=3D"id2545284"></a><h2>ZONE</h2>
 <div class=3D"literallayout"><p><br>
 zone=A0<em class=3D"replaceable"><code>string</code></em>=A0<em class=3D"r=
eplaceable"><code>optional_class</code></em>=A0{<br>
 	type=A0(=A0master=A0|=A0slave=A0|=A0stub=A0|=A0hint=A0|<br>
@@ -619,12 +618,12 @@
 </p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545659"></a><h2>FILES</h2>
+<a name=3D"id2545664"></a><h2>FILES</h2>
 <p><code class=3D"filename">/etc/named.conf</code>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2545671"></a><h2>SEE ALSO</h2>
+<a name=3D"id2545675"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">named</span>=
(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named-che=
ckconf</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rndc</spa=
n>(8)</span>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/named.doc=
book
--- a/head/contrib/bind9/bin/named/named.docbook	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/named/named.docbook	Tue Apr 17 11:51:51 2012 +=
0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: named.docbook,v 1.26 2009-10-05 17:30:49 fdupont Exp $ -->
+<!-- $Id: named.docbook,v 1.26 2009/10/05 17:30:49 fdupont Exp $ -->
 <refentry id=3D"man.named">
   <refentryinfo>
     <date>May 21, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/named.html
--- a/head/contrib/bind9/bin/named/named.html	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/named.html	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: named.html,v 1.33 2009-10-06 01:14:41 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named</code>  [<code=
 class=3D"option">-4</code>] [<code class=3D"option">-6</code>] [<code clas=
s=3D"option">-c <em class=3D"replaceable"><code>config-file</code></em></co=
de>] [<code class=3D"option">-d <em class=3D"replaceable"><code>debug-level=
</code></em></code>] [<code class=3D"option">-E <em class=3D"replaceable"><=
code>engine-name</code></em></code>] [<code class=3D"option">-f</code>] [<c=
ode class=3D"option">-g</code>] [<code class=3D"option">-m <em class=3D"rep=
laceable"><code>flag</code></em></code>] [<code class=3D"option">-n <em cla=
ss=3D"replaceable"><code>#cpus</code></em></code>] [<code class=3D"option">=
-p <em class=3D"replaceable"><code>port</code></em></code>] [<code class=3D=
"option">-s</code>] [<code class=3D"option">-S <em class=3D"replaceable"><c=
ode>#max-socks</code></em></code>] [<code class=3D"option">-t <em class=3D"=
replaceable"><code>directory</code></em></code>] [<code class=3D"option">-u=
 <em class=3D"replaceable"><code>user</code></em></code>] [<code class=3D"o=
ption">-v</code>] [<code class=3D"option">-V</code>] [<code class=3D"option=
">-x <em class=3D"replaceable"><code>cache-file</code></em></code>]</p></di=
v>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543480"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543482"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">named</strong></span>
       is a Domain Name System (DNS) server,
       part of the BIND 9 distribution from ISC.  For more
@@ -47,7 +47,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543505"></a><h2>OPTIONS</h2>
+<a name=3D"id2543507"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-4</span></dt>
 <dd><p>
@@ -228,7 +228,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543962"></a><h2>SIGNALS</h2>
+<a name=3D"id2543964"></a><h2>SIGNALS</h2>
 <p>
       In routine operation, signals should not be used to control
       the nameserver; <span><strong class=3D"command">rndc</strong></span>=
 should be used
@@ -249,7 +249,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544010"></a><h2>CONFIGURATION</h2>
+<a name=3D"id2544012"></a><h2>CONFIGURATION</h2>
 <p>
       The <span><strong class=3D"command">named</strong></span> configurat=
ion file is too complex
       to describe in detail here.  A complete description is provided
@@ -266,7 +266,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544046"></a><h2>FILES</h2>
+<a name=3D"id2544049"></a><h2>FILES</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><code class=3D"filename">/etc/named.conf</code></=
span></dt>
 <dd><p>
@@ -279,7 +279,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544086"></a><h2>SEE ALSO</h2>
+<a name=3D"id2544088"></a><h2>SEE ALSO</h2>
 <p><em class=3D"citetitle">RFC 1033</em>,
       <em class=3D"citetitle">RFC 1034</em>,
       <em class=3D"citetitle">RFC 1035</em>,
@@ -292,7 +292,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544293"></a><h2>AUTHOR</h2>
+<a name=3D"id2544295"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/notify.c
--- a/head/contrib/bind9/bin/named/notify.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/notify.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: notify.c,v 1.37 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: notify.c,v 1.37 2007/06/19 23:46:59 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/query.c
--- a/head/contrib/bind9/bin/named/query.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/query.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: query.c,v 1.353.8.11.4.1 2011-11-16 09:32:08 marka Exp $ */
+/* $Id: query.c,v 1.353.8.24 2012/02/07 01:14:39 marka Exp $ */
=20
 /*! \file */
=20
@@ -830,57 +830,41 @@
 }
=20
 static void
-rpz_log(ns_client_t *client) {
-	char namebuf1[DNS_NAME_FORMATSIZE];
-	char namebuf2[DNS_NAME_FORMATSIZE];
-	dns_rpz_st_t *st;
-	const char *pat;
-
-	if (!ns_g_server->log_queries ||
-	    !isc_log_wouldlog(ns_g_lctx, DNS_RPZ_INFO_LEVEL))
+rpz_log_rewrite(ns_client_t *client, const char *disabled,
+		dns_rpz_policy_t policy, dns_rpz_type_t type,
+		dns_name_t *rpz_qname) {
+	char qname_buf[DNS_NAME_FORMATSIZE];
+	char rpz_qname_buf[DNS_NAME_FORMATSIZE];
+
+	if (!isc_log_wouldlog(ns_g_lctx, DNS_RPZ_INFO_LEVEL))
 		return;
=20
-	st =3D client->query.rpz_st;
-	dns_name_format(client->query.qname, namebuf1, sizeof(namebuf1));
-	dns_name_format(st->qname, namebuf2, sizeof(namebuf2));
-
-	switch (st->m.policy) {
-	case DNS_RPZ_POLICY_NO_OP:
-		pat =3D"response policy %s rewrite %s NO-OP using %s";
-		break;
-	case DNS_RPZ_POLICY_NXDOMAIN:
-		pat =3D "response policy %s rewrite %s to NXDOMAIN using %s";
-		break;
-	case DNS_RPZ_POLICY_NODATA:
-		pat =3D "response policy %s rewrite %s to NODATA using %s";
-		break;
-	case DNS_RPZ_POLICY_RECORD:
-	case DNS_RPZ_POLICY_CNAME:
-		pat =3D "response policy %s rewrite %s using %s";
-		break;
-	default:
-		INSIST(0);
-	}
-	ns_client_log(client, NS_LOGCATEGORY_QUERIES, NS_LOGMODULE_QUERY,
-		      DNS_RPZ_INFO_LEVEL, pat, dns_rpz_type2str(st->m.type),
-		      namebuf1, namebuf2);
+	dns_name_format(client->query.qname, qname_buf, sizeof(qname_buf));
+	dns_name_format(rpz_qname, rpz_qname_buf, sizeof(rpz_qname_buf));
+
+	ns_client_log(client, DNS_LOGCATEGORY_RPZ, NS_LOGMODULE_QUERY,
+		      DNS_RPZ_INFO_LEVEL, "%srpz %s %s rewrite %s via %s",
+		      disabled,
+		      dns_rpz_type2str(type), dns_rpz_policy2str(policy),
+		      qname_buf, rpz_qname_buf);
 }
=20
 static void
-rpz_fail_log(ns_client_t *client, int level, dns_rpz_type_t rpz_type,
-	     dns_name_t *name, const char *str, isc_result_t result)
+rpz_log_fail(ns_client_t *client, int level,
+	     dns_rpz_type_t rpz_type, dns_name_t *name,
+	     const char *str, isc_result_t result)
 {
 	char namebuf1[DNS_NAME_FORMATSIZE];
 	char namebuf2[DNS_NAME_FORMATSIZE];
=20
-	if (!ns_g_server->log_queries || !isc_log_wouldlog(ns_g_lctx, level))
+	if (!isc_log_wouldlog(ns_g_lctx, level))
 		return;
=20
 	dns_name_format(client->query.qname, namebuf1, sizeof(namebuf1));
 	dns_name_format(name, namebuf2, sizeof(namebuf2));
 	ns_client_log(client, NS_LOGCATEGORY_QUERY_EERRORS,
 		      NS_LOGMODULE_QUERY, level,
-		      "response policy %s rewrite %s via %s %sfailed: %s",
+		      "rpz %s rewrite %s via %s %sfailed: %s",
 		      dns_rpz_type2str(rpz_type),
 		      namebuf1, namebuf2, str, isc_result_totext(result));
 }
@@ -889,9 +873,8 @@
  * Get a policy rewrite zone database.
  */
 static isc_result_t
-rpz_getdb(ns_client_t *client, dns_rpz_type_t rpz_type,
-	  dns_name_t *rpz_qname, dns_zone_t **zonep,
-	  dns_db_t **dbp, dns_dbversion_t **versionp)
+rpz_getdb(ns_client_t *client, dns_rpz_type_t rpz_type, dns_name_t *rpz_qn=
ame,
+	  dns_zone_t **zonep, dns_db_t **dbp, dns_dbversion_t **versionp)
 {
 	char namebuf1[DNS_NAME_FORMATSIZE];
 	char namebuf2[DNS_NAME_FORMATSIZE];
@@ -901,12 +884,11 @@
 	result =3D query_getzonedb(client, rpz_qname, dns_rdatatype_any,
 				 DNS_GETDB_IGNOREACL, zonep, dbp, &rpz_version);
 	if (result =3D=3D ISC_R_SUCCESS) {
-		if (ns_g_server->log_queries &&
-		    isc_log_wouldlog(ns_g_lctx, DNS_RPZ_DEBUG_LEVEL2)) {
+		if (isc_log_wouldlog(ns_g_lctx, DNS_RPZ_DEBUG_LEVEL2)) {
 			dns_name_format(client->query.qname, namebuf1,
 					sizeof(namebuf1));
 			dns_name_format(rpz_qname, namebuf2, sizeof(namebuf2));
-			ns_client_log(client, NS_LOGCATEGORY_QUERIES,
+			ns_client_log(client, DNS_LOGCATEGORY_RPZ,
 				      NS_LOGMODULE_QUERY, DNS_RPZ_DEBUG_LEVEL2,
 				      "try rpz %s rewrite %s via %s",
 				      dns_rpz_type2str(rpz_type),
@@ -915,7 +897,7 @@
 		*versionp =3D rpz_version;
 		return (ISC_R_SUCCESS);
 	}
-	rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL, rpz_type, rpz_qname,
+	rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL, rpz_type, rpz_qname,
 		     "query_getzonedb() ", result);
 	return (result);
 }
@@ -1144,7 +1126,8 @@
 	if (name =3D=3D mname)
 		mname =3D NULL;
=20
-	*mnamep =3D mname;
+	if (mnamep !=3D NULL)
+		*mnamep =3D mname;
=20
 	CTRACE("query_isduplicate: false: done");
 	return (ISC_FALSE);
@@ -1363,6 +1346,10 @@
 	}
=20
 	if (qtype =3D=3D dns_rdatatype_a) {
+#ifdef ALLOW_FILTER_AAAA_ON_V4
+		isc_boolean_t have_a =3D ISC_FALSE;
+#endif
+
 		/*
 		 * We now go looking for A and AAAA records, along with
 		 * their signatures.
@@ -1385,6 +1372,8 @@
 			if (sigrdataset =3D=3D NULL)
 				goto addname;
 		}
+		if (query_isduplicate(client, fname, dns_rdatatype_a, NULL))
+			goto aaaa_lookup;
 		result =3D dns_db_findrdataset(db, node, version,
 					     dns_rdatatype_a, 0,
 					     client->now, rdataset,
@@ -1399,6 +1388,9 @@
 		}
 		if (result =3D=3D ISC_R_SUCCESS) {
 			mname =3D NULL;
+#ifdef ALLOW_FILTER_AAAA_ON_V4
+			have_a =3D ISC_TRUE;
+#endif
 			if (!query_isduplicate(client, fname,
 					       dns_rdatatype_a, &mname)) {
 				if (mname !=3D NULL) {
@@ -1428,6 +1420,9 @@
 					dns_rdataset_disassociate(sigrdataset);
 			}
 		}
+  aaaa_lookup:
+		if (query_isduplicate(client, fname, dns_rdatatype_aaaa, NULL))
+			goto addname;
 		result =3D dns_db_findrdataset(db, node, version,
 					     dns_rdatatype_aaaa, 0,
 					     client->now, rdataset,
@@ -1442,6 +1437,17 @@
 		}
 		if (result =3D=3D ISC_R_SUCCESS) {
 			mname =3D NULL;
+			/*
+			 * There's an A; check whether we're filtering AAAA
+			 */
+#ifdef ALLOW_FILTER_AAAA_ON_V4
+			if (have_a &&
+			    (client->filter_aaaa =3D=3D dns_v4_aaaa_break_dnssec ||
+			    (client->filter_aaaa =3D=3D dns_v4_aaaa_filter &&
+			     (!WANTDNSSEC(client) || sigrdataset =3D=3D NULL ||
+			      !dns_rdataset_isassociated(sigrdataset)))))
+				goto addname;
+#endif
 			if (!query_isduplicate(client, fname,
 					       dns_rdatatype_aaaa, &mname)) {
 				if (mname !=3D NULL) {
@@ -1593,7 +1599,13 @@
 	dns_rdatatype_t type;
 	dns_rdatasetadditional_t additionaltype;
=20
-	if (qtype !=3D dns_rdatatype_a) {
+	/*
+	 * If we don't have an additional cache call query_addadditional.
+	 */
+	client =3D additionalctx->client;
+	REQUIRE(NS_CLIENT_VALID(client));
+
+	if (qtype !=3D dns_rdatatype_a || client->view->acache =3D=3D NULL) {
 		/*
 		 * This function is optimized for "address" types.  For other
 		 * types, use a generic routine.
@@ -1607,8 +1619,6 @@
 	 * Initialization.
 	 */
 	rdataset_base =3D additionalctx->rdataset;
-	client =3D additionalctx->client;
-	REQUIRE(NS_CLIENT_VALID(client));
 	eresult =3D ISC_R_SUCCESS;
 	fname =3D NULL;
 	rdataset =3D NULL;
@@ -1861,6 +1871,9 @@
 	if (sigrdataset =3D=3D NULL)
 		goto cleanup;
=20
+	if (additionaltype =3D=3D dns_rdatasetadditional_fromcache &&
+	    query_isduplicate(client, fname, dns_rdatatype_a, NULL))
+		goto aaaa_lookup;
 	/*
 	 * Find A RRset with sig RRset.  Even if we don't find a sig RRset
 	 * for a client using DNSSEC, we'll continue the process to make a
@@ -1905,6 +1918,10 @@
 		}
 	}
=20
+ aaaa_lookup:
+	if (additionaltype =3D=3D dns_rdatasetadditional_fromcache &&
+	    query_isduplicate(client, fname, dns_rdatatype_aaaa, NULL))
+		goto foundcache;
 	/* Find AAAA RRset with sig RRset */
 	result =3D dns_db_findrdataset(db, node, version, dns_rdatatype_aaaa,
 				     0, client->now, rdataset, sigrdataset);
@@ -3350,8 +3367,9 @@
 				       sigrdataset, fname, ISC_TRUE, cname);
 		if (!dns_rdataset_isassociated(rdataset))
 			goto cleanup;
-		query_addrrset(client, &fname, &rdataset, &sigrdataset,
-			       dbuf, DNS_SECTION_AUTHORITY);
+		if (!ispositive)
+			query_addrrset(client, &fname, &rdataset, &sigrdataset,
+				       dbuf, DNS_SECTION_AUTHORITY);
=20
 		/*
 		 * Replace resources which were consumed by query_addrrset.
@@ -3799,14 +3817,15 @@
 	dns_rpz_st_t *st =3D client->query.rpz_st;
=20
 	rpz_clean(&st->m.zone, &st->m.db, &st->m.node, NULL);
+	st->m.version =3D NULL;
 	if (st->m.rdataset !=3D NULL)
 		query_putrdataset(client, &st->m.rdataset);
=20
-	rpz_clean(NULL, &st->ns.db, NULL, NULL);
-	if (st->ns.ns_rdataset !=3D NULL)
-		query_putrdataset(client, &st->ns.ns_rdataset);
-	if (st->ns.r_rdataset !=3D NULL)
-		query_putrdataset(client, &st->ns.r_rdataset);
+	rpz_clean(NULL, &st->r.db, NULL, NULL);
+	if (st->r.ns_rdataset !=3D NULL)
+		query_putrdataset(client, &st->r.ns_rdataset);
+	if (st->r.r_rdataset !=3D NULL)
+		query_putrdataset(client, &st->r.r_rdataset);
=20
 	rpz_clean(&st->q.zone, &st->q.db, &st->q.node, NULL);
 	if (st->q.rdataset !=3D NULL)
@@ -3814,15 +3833,18 @@
 	if (st->q.sigrdataset !=3D NULL)
 		query_putrdataset(client, &st->q.sigrdataset);
 	st->state =3D 0;
+	st->m.type =3D DNS_RPZ_TYPE_BAD;
+	st->m.policy =3D DNS_RPZ_POLICY_MISS;
 }
=20
 /*
- * Get NS, A, or AAAA rrset for rpz nsdname or nsip checking.
+ * Get NS, A, or AAAA rrset for response policy zone checks.
  */
 static isc_result_t
-rpz_ns_find(ns_client_t *client, dns_name_t *name, dns_rdatatype_t type,
-	    dns_db_t **dbp, dns_dbversion_t *version,
-	    dns_rdataset_t **rdatasetp, isc_boolean_t resuming)
+rpz_rrset_find(ns_client_t *client, dns_rpz_type_t rpz_type,
+	       dns_name_t *name, dns_rdatatype_t type,
+	       dns_db_t **dbp, dns_dbversion_t *version,
+	       dns_rdataset_t **rdatasetp, isc_boolean_t resuming)
 {
 	dns_rpz_st_t *st;
 	isc_boolean_t is_zone;
@@ -3833,22 +3855,22 @@
=20
 	st =3D client->query.rpz_st;
 	if ((st->state & DNS_RPZ_RECURSING) !=3D 0) {
-		INSIST(st->ns.r_type =3D=3D type);
+		INSIST(st->r.r_type =3D=3D type);
 		INSIST(dns_name_equal(name, st->r_name));
 		INSIST(*rdatasetp =3D=3D NULL ||
 		       !dns_rdataset_isassociated(*rdatasetp));
 		st->state &=3D ~DNS_RPZ_RECURSING;
-		*dbp =3D st->ns.db;
-		st->ns.db =3D NULL;
+		*dbp =3D st->r.db;
+		st->r.db =3D NULL;
 		if (*rdatasetp !=3D NULL)
 			query_putrdataset(client, rdatasetp);
-		*rdatasetp =3D st->ns.r_rdataset;
-		st->ns.r_rdataset =3D NULL;
-		result =3D st->ns.r_result;
+		*rdatasetp =3D st->r.r_rdataset;
+		st->r.r_rdataset =3D NULL;
+		result =3D st->r.r_result;
 		if (result =3D=3D DNS_R_DELEGATION) {
-			rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL,
-				     DNS_RPZ_TYPE_NSIP, name,
-				     "rpz_ns_find() ", result);
+			rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL,
+				     rpz_type, name,
+				     "rpz_rrset_find(1) ", result);
 			st->m.policy =3D DNS_RPZ_POLICY_ERROR;
 			result =3D DNS_R_SERVFAIL;
 		}
@@ -3870,9 +3892,9 @@
 		result =3D query_getdb(client, name, type, 0, &zone, dbp,
 				     &version, &is_zone);
 		if (result !=3D ISC_R_SUCCESS) {
-			rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL,
-				     DNS_RPZ_TYPE_NSIP, name, "NS getdb() ",
-				     result);
+			rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL,
+				     rpz_type, name,
+				     "rpz_rrset_find(2) ", result);
 			st->m.policy =3D DNS_RPZ_POLICY_ERROR;
 			if (zone !=3D NULL)
 				dns_zone_detach(&zone);
@@ -3885,8 +3907,8 @@
 	node =3D NULL;
 	dns_fixedname_init(&fixed);
 	found =3D dns_fixedname_name(&fixed);
-	result =3D dns_db_find(*dbp, name, version, type, 0, client->now, &node,
-			     found, *rdatasetp, NULL);
+	result =3D dns_db_find(*dbp, name, version, type, DNS_DBFIND_GLUEOK,
+			     client->now, &node, found, *rdatasetp, NULL);
 	if (result =3D=3D DNS_R_DELEGATION && is_zone && USECACHE(client)) {
 		/*
 		 * Try the cache if we're authoritative for an
@@ -3901,16 +3923,21 @@
 	}
 	rpz_clean(NULL, dbp, &node, NULL);
 	if (result =3D=3D DNS_R_DELEGATION) {
+		rpz_clean(NULL, NULL, NULL, rdatasetp);
 		/*
-		 * Recurse to get NS rrset or A or AAAA rrset for an NS name.
+		 * Recurse for NS rrset or A or AAAA rrset for an NS.
+		 * Do not recurse for addresses for the query name.
 		 */
-		rpz_clean(NULL, NULL, NULL, rdatasetp);
-		dns_name_copy(name, st->r_name, NULL);
-		result =3D query_recurse(client, type, st->r_name, NULL, NULL,
-				       resuming);
-		if (result =3D=3D ISC_R_SUCCESS) {
-			st->state |=3D DNS_RPZ_RECURSING;
-			result =3D DNS_R_DELEGATION;
+		if (rpz_type =3D=3D DNS_RPZ_TYPE_IP) {
+			result =3D DNS_R_NXRRSET;
+		} else {
+			dns_name_copy(name, st->r_name, NULL);
+			result =3D query_recurse(client, type, st->r_name,
+					       NULL, NULL, resuming);
+			if (result =3D=3D ISC_R_SUCCESS) {
+				st->state |=3D DNS_RPZ_RECURSING;
+				result =3D DNS_R_DELEGATION;
+			}
 		}
 	}
 	return (result);
@@ -3928,7 +3955,7 @@
 	dns_dbversion_t *version;
 	dns_zone_t *zone;
 	dns_db_t *db;
-	dns_rpz_zone_t *new_rpz;
+	dns_rpz_zone_t *rpz;
 	isc_result_t result;
=20
 	st =3D client->query.rpz_st;
@@ -3939,16 +3966,26 @@
 	}
 	zone =3D NULL;
 	db =3D NULL;
-	for (new_rpz =3D ISC_LIST_HEAD(client->view->rpz_zones);
-	     new_rpz !=3D NULL;
-	     new_rpz =3D ISC_LIST_NEXT(new_rpz, link)) {
+	for (rpz =3D ISC_LIST_HEAD(client->view->rpz_zones);
+	     rpz !=3D NULL;
+	     rpz =3D ISC_LIST_NEXT(rpz, link)) {
+		/*
+		 * Do not check policy zones that cannot replace a policy
+		 * already known to match.
+		 */
+		if (st->m.policy !=3D DNS_RPZ_POLICY_MISS) {
+			if (st->m.rpz->num < rpz->num)
+				break;
+			if (st->m.rpz->num =3D=3D rpz->num &&
+			    st->m.type < rpz_type)
+				continue;
+		}
+
+		/*
+		 * Find the database for this policy zone to get its radix tree.
+		 */
 		version =3D NULL;
-
-		/*
-		 * Find the database for this policy zone to get its
-		 * radix tree.
-		 */
-		result =3D rpz_getdb(client, rpz_type, &new_rpz->origin,
+		result =3D rpz_getdb(client, rpz_type, &rpz->origin,
 				   &zone, &db, &version);
 		if (result !=3D ISC_R_SUCCESS) {
 			rpz_clean(&zone, &db, NULL, NULL);
@@ -3960,26 +3997,31 @@
 		 * hit, if any.  Note the domain name and quality of the
 		 * best hit.
 		 */
-		result =3D dns_db_rpz_findips(new_rpz, rpz_type, zone, db,
-					    version, rdataset, st);
-		RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
+		(void)dns_db_rpz_findips(rpz, rpz_type, zone, db, version,
+					 rdataset, st,
+					 client->query.rpz_st->qname);
 		rpz_clean(&zone, &db, NULL, NULL);
 	}
 	return (ISC_R_SUCCESS);
 }
=20
+/*
+ * Look for an A or AAAA rdataset
+ * and check for IP or NSIP rewrite policy rules.
+ */
 static isc_result_t
-rpz_rewrite_nsip(ns_client_t *client, dns_rdatatype_t type, dns_name_t *na=
me,
-		 dns_db_t **dbp, dns_dbversion_t *version,
-		 dns_rdataset_t **rdatasetp, isc_boolean_t resuming)
+rpz_rewrite_rrset(ns_client_t *client, dns_rpz_type_t rpz_type,
+		  dns_rdatatype_t type, dns_name_t *name,
+		  dns_db_t **dbp, dns_dbversion_t *version,
+		  dns_rdataset_t **rdatasetp, isc_boolean_t resuming)
 {
 	isc_result_t result;
=20
-	result =3D rpz_ns_find(client, name, type, dbp, version, rdatasetp,
-			     resuming);
+	result =3D rpz_rrset_find(client, rpz_type, name, type, dbp, version,
+				rdatasetp, resuming);
 	switch (result) {
 	case ISC_R_SUCCESS:
-		result =3D rpz_rewrite_ip(client, *rdatasetp, DNS_RPZ_TYPE_NSIP);
+		result =3D rpz_rewrite_ip(client, *rdatasetp, rpz_type);
 		break;
 	case DNS_R_EMPTYNAME:
 	case DNS_R_EMPTYWILD:
@@ -3987,17 +4029,24 @@
 	case DNS_R_NCACHENXDOMAIN:
 	case DNS_R_NXRRSET:
 	case DNS_R_NCACHENXRRSET:
+	case ISC_R_NOTFOUND:
 		result =3D ISC_R_SUCCESS;
 		break;
 	case DNS_R_DELEGATION:
 	case DNS_R_DUPLICATE:
 	case DNS_R_DROP:
 		break;
+	case DNS_R_CNAME:
+	case DNS_R_DNAME:
+		rpz_log_fail(client, DNS_RPZ_DEBUG_LEVEL1, rpz_type,
+			     name, "NS address rewrite rrset ", result);
+		result =3D ISC_R_SUCCESS;
+		break;
 	default:
 		if (client->query.rpz_st->m.policy !=3D DNS_RPZ_POLICY_ERROR) {
 			client->query.rpz_st->m.policy =3D DNS_RPZ_POLICY_ERROR;
-			rpz_fail_log(client, ISC_LOG_WARNING, DNS_RPZ_TYPE_NSIP,
-				     name, "NS address rewrite nsip ", result);
+			rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL, rpz_type,
+				     name, "NS address rewrite rrset ", result);
 		}
 		break;
 	}
@@ -4005,15 +4054,61 @@
 }
=20
 /*
+ * Look for both A and AAAA rdatasets
+ * and check for IP or NSIP rewrite policy rules.
+ * Look only for addresses that will be in the ANSWER section
+ * when checking for IP rules.
+ */
+static isc_result_t
+rpz_rewrite_rrsets(ns_client_t *client, dns_rpz_type_t rpz_type,
+		   dns_name_t *name, dns_rdatatype_t type,
+		   dns_rdataset_t **rdatasetp, isc_boolean_t resuming)
+{
+	dns_rpz_st_t *st;
+	dns_dbversion_t *version;
+	dns_db_t *ipdb;
+	isc_result_t result;
+
+	st =3D client->query.rpz_st;
+	version =3D NULL;
+	ipdb =3D NULL;
+	if ((st->state & DNS_RPZ_DONE_IPv4) =3D=3D 0 &&
+	    ((rpz_type =3D=3D DNS_RPZ_TYPE_NSIP) ?
+	     (st->state & DNS_RPZ_HAVE_NSIPv4) :
+	     (st->state & DNS_RPZ_HAVE_IP)) !=3D 0 &&
+	    (type =3D=3D dns_rdatatype_any || type =3D=3D dns_rdatatype_a)) {
+		result =3D rpz_rewrite_rrset(client, rpz_type, dns_rdatatype_a,
+					   name, &ipdb, version, rdatasetp,
+					   resuming);
+		if (result =3D=3D ISC_R_SUCCESS)
+			st->state |=3D DNS_RPZ_DONE_IPv4;
+	} else {
+		result =3D ISC_R_SUCCESS;
+	}
+	if (result =3D=3D ISC_R_SUCCESS &&
+	    ((rpz_type =3D=3D DNS_RPZ_TYPE_NSIP) ?
+	     (st->state & DNS_RPZ_HAVE_NSIPv6) :
+	     (st->state & DNS_RPZ_HAVE_IP)) !=3D 0 &&
+	    (type =3D=3D dns_rdatatype_any || type =3D=3D dns_rdatatype_aaaa)) {
+		result =3D rpz_rewrite_rrset(client, rpz_type, dns_rdatatype_aaaa,
+					   name, &ipdb, version, rdatasetp,
+					   resuming);
+	}
+	if (ipdb !=3D NULL)
+		dns_db_detach(&ipdb);
+	return (result);
+}
+
+/*
  * Get the rrset from a response policy zone.
  */
 static isc_result_t
 rpz_find(ns_client_t *client, dns_rdatatype_t qtype, dns_name_t *qnamef,
 	 dns_name_t *sname, dns_rpz_type_t rpz_type, dns_zone_t **zonep,
-	 dns_db_t **dbp, dns_dbnode_t **nodep, dns_rdataset_t **rdatasetp,
+	 dns_db_t **dbp, dns_dbversion_t **versionp,
+	 dns_dbnode_t **nodep, dns_rdataset_t **rdatasetp,
 	 dns_rpz_policy_t *policyp)
 {
-	dns_dbversion_t *version;
 	dns_rpz_policy_t policy;
 	dns_fixedname_t fixed;
 	dns_name_t *found;
@@ -4029,8 +4124,8 @@
 	 * Try to get either a CNAME or the type of record demanded by the
 	 * request from the policy zone.
 	 */
-	version =3D NULL;
-	result =3D rpz_getdb(client, rpz_type, qnamef, zonep, dbp, &version);
+	*versionp =3D NULL;
+	result =3D rpz_getdb(client, rpz_type, qnamef, zonep, dbp, versionp);
 	if (result !=3D ISC_R_SUCCESS) {
 		*policyp =3D DNS_RPZ_POLICY_MISS;
 		return (DNS_R_NXDOMAIN);
@@ -4038,17 +4133,17 @@
=20
 	dns_fixedname_init(&fixed);
 	found =3D dns_fixedname_name(&fixed);
-	result =3D dns_db_find(*dbp, qnamef, version, dns_rdatatype_any, 0,
+	result =3D dns_db_find(*dbp, qnamef, *versionp, dns_rdatatype_any, 0,
 			     client->now, nodep, found, *rdatasetp, NULL);
 	if (result =3D=3D ISC_R_SUCCESS) {
 		dns_rdatasetiter_t *rdsiter;
=20
 		rdsiter =3D NULL;
-		result =3D dns_db_allrdatasets(*dbp, *nodep, version, 0,
+		result =3D dns_db_allrdatasets(*dbp, *nodep, *versionp, 0,
 					     &rdsiter);
 		if (result !=3D ISC_R_SUCCESS) {
 			dns_db_detachnode(*dbp, nodep);
-			rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL, rpz_type,
+			rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL, rpz_type,
 				     qnamef, "allrdatasets()", result);
 			*policyp =3D DNS_RPZ_POLICY_ERROR;
 			return (DNS_R_SERVFAIL);
@@ -4065,7 +4160,7 @@
 		dns_rdatasetiter_destroy(&rdsiter);
 		if (result !=3D ISC_R_SUCCESS) {
 			if (result !=3D ISC_R_NOMORE) {
-				rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL,
+				rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL,
 					     rpz_type, qnamef, "rdatasetiter",
 					     result);
 				*policyp =3D DNS_RPZ_POLICY_ERROR;
@@ -4083,7 +4178,7 @@
 			    qtype =3D=3D dns_rdatatype_sig)
 				result =3D DNS_R_NXRRSET;
 			else
-				result =3D dns_db_find(*dbp, qnamef, version,
+				result =3D dns_db_find(*dbp, qnamef, *versionp,
 						     qtype, 0, client->now,
 						     nodep, found, *rdatasetp,
 						     NULL);
@@ -4095,7 +4190,8 @@
 			policy =3D DNS_RPZ_POLICY_RECORD;
 		} else {
 			policy =3D dns_rpz_decode_cname(*rdatasetp, sname);
-			if (policy =3D=3D DNS_RPZ_POLICY_RECORD &&
+			if ((policy =3D=3D DNS_RPZ_POLICY_RECORD ||
+			     policy =3D=3D DNS_RPZ_POLICY_WILDCNAME) &&
 			    qtype !=3D dns_rdatatype_cname &&
 			    qtype !=3D dns_rdatatype_any)
 				result =3D DNS_R_CNAME;
@@ -4106,8 +4202,8 @@
 		 * DNAME policy RRs have very few if any uses that are not
 		 * better served with simple wildcards.  Making the work would
 		 * require complications to get the number of labels matched
-		 * in the name or the found name itself to the main DNS_R_DNAME
-		 * case in query_find(). So fall through to treat them as NODATA.
+		 * in the name or the found name to the main DNS_R_DNAME case
+		 * in query_find(). So fall through to treat them as NODATA.
 		 */
 	case DNS_R_NXRRSET:
 		policy =3D DNS_RPZ_POLICY_NODATA;
@@ -4126,7 +4222,7 @@
 	default:
 		dns_db_detach(dbp);
 		dns_zone_detach(zonep);
-		rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL, rpz_type, qnamef,
+		rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL, rpz_type, qnamef,
 			     "", result);
 		policy =3D DNS_RPZ_POLICY_ERROR;
 		result =3D DNS_R_SERVFAIL;
@@ -4150,6 +4246,7 @@
 	dns_name_t *prefix, *suffix, *rpz_qname;
 	dns_zone_t *zone;
 	dns_db_t *db;
+	dns_dbversion_t *version;
 	dns_dbnode_t *node;
 	dns_rpz_policy_t policy;
 	unsigned int labels;
@@ -4164,7 +4261,18 @@
 	     rpz !=3D NULL;
 	     rpz =3D ISC_LIST_NEXT(rpz, link)) {
 		/*
-		 * Construct the rule's owner name.
+		 * Do not check policy zones that cannot replace a policy
+		 * already known to match.
+		 */
+		if (st->m.policy !=3D DNS_RPZ_POLICY_MISS) {
+			if (st->m.rpz->num < rpz->num)
+				break;
+			if (st->m.rpz->num =3D=3D rpz->num &&
+			    st->m.type < rpz_type)
+				continue;
+		}
+		/*
+		 * Construct the policy's owner name.
 		 */
 		dns_fixedname_init(&prefixf);
 		prefix =3D dns_fixedname_name(&prefixf);
@@ -4183,13 +4291,13 @@
 			INSIST(result =3D=3D DNS_R_NAMETOOLONG);
 			labels =3D dns_name_countlabels(prefix);
 			if (labels < 2) {
-				rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL,
+				rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL,
 					     rpz_type, suffix,
 					     "concatentate() ", result);
 				return (ISC_R_SUCCESS);
 			}
 			if (labels+1 =3D=3D dns_name_countlabels(qname)) {
-				rpz_fail_log(client, DNS_RPZ_DEBUG_LEVEL1,
+				rpz_log_fail(client, DNS_RPZ_DEBUG_LEVEL1,
 					     rpz_type, suffix,
 					     "concatentate() ", result);
 			}
@@ -4197,10 +4305,11 @@
 		}
=20
 		/*
-		 * See if the qname rule (or RR) exists.
+		 * See if the policy record exists.
 		 */
 		result =3D rpz_find(client, qtype, rpz_qname, qname, rpz_type,
-				  &zone, &db, &node, rdatasetp, &policy);
+				  &zone, &db, &version, &node, rdatasetp,
+				  &policy);
 		switch (result) {
 		case DNS_R_NXDOMAIN:
 		case DNS_R_EMPTYNAME:
@@ -4211,14 +4320,31 @@
 			return (DNS_R_SERVFAIL);
 		default:
 			/*
-			 * when more than one name or address hits a rule,
-			 * prefer the first set of names (qname or NS),
-			 * the first policy zone, and the smallest name
+			 * We are dealing with names here.
+			 * With more than one applicable policy, prefer
+			 * the earliest configured policy,
+			 * QNAME over IP over NSDNAME over NSIP,
+			 * and the smallest name.
+			 * Because of the testing above,
+			 * we known st->m.rpz->num >=3D rpz->num  and either
+			 * st->m.rpz->num > rpz->num or st->m.type >=3D rpz_type
 			 */
-			if (st->m.type =3D=3D rpz_type &&
-			    rpz->num > st->m.rpz->num &&
-			    0 <=3D dns_name_compare(rpz_qname, st->qname))
+			if (st->m.policy !=3D DNS_RPZ_POLICY_MISS &&
+			    rpz->num =3D=3D st->m.rpz->num &&
+			    (st->m.type < rpz_type ||
+			     (st->m.type =3D=3D rpz_type &&
+			      0 >=3D dns_name_compare(rpz_qname, st->qname))))
 				continue;
+
+			/*
+			 * Merely log DNS_RPZ_POLICY_DISABLED hits.
+			 */
+			if (rpz->policy =3D=3D DNS_RPZ_POLICY_DISABLED) {
+				rpz_log_rewrite(client, "disabled ",
+						policy, rpz_type, rpz_qname);
+				continue;
+			}
+
 			rpz_clean(&st->m.zone, &st->m.db, &st->m.node,
 				  &st->m.rdataset);
 			st->m.rpz =3D rpz;
@@ -4227,7 +4353,8 @@
 			st->m.policy =3D policy;
 			st->m.result =3D result;
 			dns_name_copy(rpz_qname, st->qname, NULL);
-			if (dns_rdataset_isassociated(*rdatasetp)) {
+			if (*rdatasetp !=3D NULL &&
+			    dns_rdataset_isassociated(*rdatasetp)) {
 				dns_rdataset_t *trdataset;
=20
 				trdataset =3D st->m.rdataset;
@@ -4241,6 +4368,7 @@
 			node =3D NULL;
 			st->m.db =3D db;
 			db =3D NULL;
+			st->m.version =3D version;
 			st->m.zone =3D zone;
 			zone =3D NULL;
 		}
@@ -4250,24 +4378,38 @@
 	return (ISC_R_SUCCESS);
 }
=20
+static void
+rpz_rewrite_ns_skip(ns_client_t *client, dns_name_t *nsname,
+		    isc_result_t result, int level, const char *str)
+{
+	dns_rpz_st_t *st;
+
+	st =3D client->query.rpz_st;
+
+	if (str !=3D NULL)
+		rpz_log_fail(client, level, DNS_RPZ_TYPE_NSIP, nsname,
+			     str, result);
+	if (st->r.ns_rdataset !=3D NULL &&
+	    dns_rdataset_isassociated(st->r.ns_rdataset))
+		dns_rdataset_disassociate(st->r.ns_rdataset);
+
+	st->r.label--;
+}
+
 /*
- * Look for response policy zone NSIP and NSDNAME rewriting.
+ * Look for response policy zone QNAME, NSIP, and NSDNAME rewriting.
  */
 static isc_result_t
-rpz_rewrite(ns_client_t *client, dns_rdatatype_t qtype,
+rpz_rewrite(ns_client_t *client, dns_rdatatype_t qtype, isc_result_t qresu=
lt,
 	    isc_boolean_t resuming)
 {
 	dns_rpz_st_t *st;
-	dns_db_t *ipdb;
 	dns_rdataset_t *rdataset;
 	dns_fixedname_t nsnamef;
 	dns_name_t *nsname;
-	dns_dbversion_t *version;
+	isc_boolean_t ck_ip;
 	isc_result_t result;
=20
-	ipdb =3D NULL;
-	rdataset =3D NULL;
-
 	st =3D client->query.rpz_st;
 	if (st =3D=3D NULL) {
 		st =3D isc_mem_get(client->mctx, sizeof(*st));
@@ -4275,7 +4417,9 @@
 			return (ISC_R_NOMEMORY);
 		st->state =3D 0;
 		memset(&st->m, 0, sizeof(st->m));
-		memset(&st->ns, 0, sizeof(st->ns));
+		st->m.type =3D DNS_RPZ_TYPE_BAD;
+		st->m.policy =3D DNS_RPZ_POLICY_MISS;
+		memset(&st->r, 0, sizeof(st->r));
 		memset(&st->q, 0, sizeof(st->q));
 		dns_fixedname_init(&st->_qnamef);
 		dns_fixedname_init(&st->_r_namef);
@@ -4285,78 +4429,147 @@
 		st->fname =3D dns_fixedname_name(&st->_fnamef);
 		client->query.rpz_st =3D st;
 	}
+
+	/*
+	 * There is nothing to rewrite if the main query failed.
+	 */
+	switch (qresult) {
+	case ISC_R_SUCCESS:
+	case DNS_R_GLUE:
+	case DNS_R_ZONECUT:
+		ck_ip =3D ISC_TRUE;
+		break;
+	case DNS_R_EMPTYNAME:
+	case DNS_R_NXRRSET:
+	case DNS_R_NXDOMAIN:
+	case DNS_R_EMPTYWILD:
+	case DNS_R_NCACHENXDOMAIN:
+	case DNS_R_NCACHENXRRSET:
+	case DNS_R_CNAME:
+	case DNS_R_DNAME:
+		ck_ip =3D ISC_FALSE;
+		break;
+	case DNS_R_DELEGATION:
+	case ISC_R_NOTFOUND:
+		return (ISC_R_SUCCESS);
+	case ISC_R_FAILURE:
+	case ISC_R_TIMEDOUT:
+	case DNS_R_BROKENCHAIN:
+		rpz_log_fail(client, DNS_RPZ_DEBUG_LEVEL3, DNS_RPZ_TYPE_QNAME,
+			     client->query.qname,
+			     "stop on qresult in rpz_rewrite()",
+			     qresult);
+		return (ISC_R_SUCCESS);
+	default:
+		rpz_log_fail(client, DNS_RPZ_DEBUG_LEVEL1, DNS_RPZ_TYPE_QNAME,
+			     client->query.qname,
+			     "stop on unrecognized qresult in rpz_rewrite()",
+			     qresult);
+		return (ISC_R_SUCCESS);
+	}
+
+	rdataset =3D NULL;
 	if ((st->state & DNS_RPZ_DONE_QNAME) =3D=3D 0) {
-		st->state =3D DNS_RPZ_DONE_QNAME;
-		st->m.type =3D DNS_RPZ_TYPE_BAD;
-		st->m.policy =3D DNS_RPZ_POLICY_MISS;
-
 		/*
-		 * Check rules for the name if this it the first time,
-		 * i.e. we've not been recursing.
+		 * Check rules for the query name if this it the first time
+		 * for the current qname, i.e. we've not been recursing.
+		 * There is a first time for each name in a CNAME chain.
 		 */
-		st->state &=3D ~(DNS_RPZ_HAVE_IP | DNS_RPZ_HAVE_NSIPv4 |
-			       DNS_RPZ_HAVE_NSIPv6 | DNS_RPZ_HAD_NSDNAME);
 		result =3D rpz_rewrite_name(client, qtype, client->query.qname,
 					  DNS_RPZ_TYPE_QNAME, &rdataset);
 		if (result !=3D ISC_R_SUCCESS)
 			goto cleanup;
-		if (st->m.policy !=3D DNS_RPZ_POLICY_MISS)
+
+		st->r.label =3D dns_name_countlabels(client->query.qname);
+
+		st->state &=3D ~(DNS_RPZ_DONE_QNAME_IP | DNS_RPZ_DONE_IPv4);
+		st->state |=3D DNS_RPZ_DONE_QNAME;
+	}
+
+	/*
+	 * Check known IP addresses for the query name.
+	 * Any recursion required for the query has already happened.
+	 * Do not check addresses that will not be in the ANSWER section.
+	 */
+	if ((st->state & DNS_RPZ_DONE_QNAME_IP) =3D=3D 0 &&
+	    (st->state & DNS_RPZ_HAVE_IP) !=3D 0 && ck_ip) {
+		result =3D rpz_rewrite_rrsets(client, DNS_RPZ_TYPE_IP,
+					    client->query.qname, qtype,
+					    &rdataset, resuming);
+		if (result !=3D ISC_R_SUCCESS)
 			goto cleanup;
-		if ((st->state & (DNS_RPZ_HAVE_NSIPv4 | DNS_RPZ_HAVE_NSIPv6 |
-				  DNS_RPZ_HAD_NSDNAME)) =3D=3D 0)
-			goto cleanup;
-		st->ns.label =3D dns_name_countlabels(client->query.qname);
+		st->state &=3D ~DNS_RPZ_DONE_IPv4;
+		st->state |=3D DNS_RPZ_DONE_QNAME_IP;
+	}
+
+	/*
+	 * Stop looking for rules if there are none of the other kinds.
+	 */
+	if ((st->state & (DNS_RPZ_HAVE_NSIPv4 | DNS_RPZ_HAVE_NSIPv6 |
+			  DNS_RPZ_HAVE_NSDNAME)) =3D=3D 0) {
+		result =3D ISC_R_SUCCESS;
+		goto cleanup;
 	}
=20
 	dns_fixedname_init(&nsnamef);
 	dns_name_clone(client->query.qname, dns_fixedname_name(&nsnamef));
-	while (st->ns.label > 1 && st->m.policy =3D=3D DNS_RPZ_POLICY_MISS) {
-		if (st->ns.label =3D=3D dns_name_countlabels(client->query.qname)) {
+	while (st->r.label > 1) {
+		/*
+		 * Get NS rrset for each domain in the current qname.
+		 */
+		if (st->r.label =3D=3D dns_name_countlabels(client->query.qname)) {
 			nsname =3D client->query.qname;
 		} else {
 			nsname =3D dns_fixedname_name(&nsnamef);
-			dns_name_split(client->query.qname, st->ns.label,
+			dns_name_split(client->query.qname, st->r.label,
 				       NULL, nsname);
 		}
-		if (st->ns.ns_rdataset =3D=3D NULL ||
-		    !dns_rdataset_isassociated(st->ns.ns_rdataset)) {
+		if (st->r.ns_rdataset =3D=3D NULL ||
+		    !dns_rdataset_isassociated(st->r.ns_rdataset)) {
 			dns_db_t *db =3D NULL;
-			result =3D rpz_ns_find(client, nsname, dns_rdatatype_ns,
-					     &db, NULL, &st->ns.ns_rdataset,
-					     resuming);
+			result =3D rpz_rrset_find(client, DNS_RPZ_TYPE_NSDNAME,
+						nsname, dns_rdatatype_ns,
+						&db, NULL, &st->r.ns_rdataset,
+						resuming);
 			if (db !=3D NULL)
 				dns_db_detach(&db);
-			if (result !=3D ISC_R_SUCCESS) {
-				if (result =3D=3D DNS_R_DELEGATION)
+			if (st->m.policy =3D=3D DNS_RPZ_POLICY_ERROR)
+				goto cleanup;
+			switch (result) {
+			case ISC_R_SUCCESS:
+				result =3D dns_rdataset_first(st->r.ns_rdataset);
+				if (result !=3D ISC_R_SUCCESS)
 					goto cleanup;
-				if (result =3D=3D DNS_R_EMPTYNAME ||
-				    result =3D=3D DNS_R_NXRRSET ||
-				    result =3D=3D DNS_R_EMPTYWILD ||
-				    result =3D=3D DNS_R_NXDOMAIN ||
-				    result =3D=3D DNS_R_NCACHENXDOMAIN ||
-				    result =3D=3D DNS_R_NCACHENXRRSET ||
-				    result =3D=3D DNS_R_CNAME ||
-				    result =3D=3D DNS_R_DNAME) {
-					rpz_fail_log(client,
-						     DNS_RPZ_DEBUG_LEVEL2,
-						     DNS_RPZ_TYPE_NSIP, nsname,
-						     "NS db_find() ", result);
-					dns_rdataset_disassociate(st->ns.
-							ns_rdataset);
-					st->ns.label--;
-					continue;
-				}
-				if (st->m.policy !=3D DNS_RPZ_POLICY_ERROR) {
-					rpz_fail_log(client, DNS_RPZ_INFO_LEVEL,
-						     DNS_RPZ_TYPE_NSIP, nsname,
-						     "NS db_find() ", result);
-					st->m.policy =3D DNS_RPZ_POLICY_ERROR;
-				}
+				st->state &=3D ~(DNS_RPZ_DONE_NSDNAME |
+					       DNS_RPZ_DONE_IPv4);
+				break;
+			case DNS_R_DELEGATION:
 				goto cleanup;
+			case DNS_R_EMPTYNAME:
+			case DNS_R_NXRRSET:
+			case DNS_R_EMPTYWILD:
+			case DNS_R_NXDOMAIN:
+			case DNS_R_NCACHENXDOMAIN:
+			case DNS_R_NCACHENXRRSET:
+			case ISC_R_NOTFOUND:
+			case DNS_R_CNAME:
+			case DNS_R_DNAME:
+				rpz_rewrite_ns_skip(client, nsname, result,
+						    0, NULL);
+				continue;
+			case ISC_R_TIMEDOUT:
+			case DNS_R_BROKENCHAIN:
+			case ISC_R_FAILURE:
+				rpz_rewrite_ns_skip(client, nsname, result,
+						DNS_RPZ_DEBUG_LEVEL3,
+						"NS db_find() ");
+				continue;
+			default:
+				rpz_rewrite_ns_skip(client, nsname, result,
+						DNS_RPZ_INFO_LEVEL,
+						"unrecognized NS db_find() ");
+				continue;
 			}
-			result =3D dns_rdataset_first(st->ns.ns_rdataset);
-			if (result !=3D ISC_R_SUCCESS)
-				goto cleanup;
 		}
 		/*
 		 * Check all NS names.
@@ -4365,17 +4578,30 @@
 			dns_rdata_ns_t ns;
 			dns_rdata_t nsrdata =3D DNS_RDATA_INIT;
=20
-			dns_rdataset_current(st->ns.ns_rdataset, &nsrdata);
+			dns_rdataset_current(st->r.ns_rdataset, &nsrdata);
 			result =3D dns_rdata_tostruct(&nsrdata, &ns, NULL);
 			dns_rdata_reset(&nsrdata);
 			if (result !=3D ISC_R_SUCCESS) {
-				rpz_fail_log(client, DNS_RPZ_ERROR_LEVEL,
+				rpz_log_fail(client, DNS_RPZ_ERROR_LEVEL,
 					     DNS_RPZ_TYPE_NSIP, nsname,
 					     "rdata_tostruct() ", result);
 				st->m.policy =3D DNS_RPZ_POLICY_ERROR;
 				goto cleanup;
 			}
-			if ((st->state & DNS_RPZ_HAD_NSDNAME) !=3D 0) {
+			/*
+			 * Do nothing about "NS ."
+			 */
+			if (dns_name_equal(&ns.name, dns_rootname)) {
+				dns_rdata_freestruct(&ns);
+				result =3D dns_rdataset_next(st->r.ns_rdataset);
+				continue;
+			}
+			/*
+			 * Check this NS name if we did not handle it
+			 * during a previous recursion.
+			 */
+			if ((st->state & DNS_RPZ_DONE_NSDNAME) =3D=3D 0 &&
+			    (st->state & DNS_RPZ_HAVE_NSDNAME) !=3D 0) {
 				result =3D rpz_rewrite_name(client, qtype,
 							&ns.name,
 							DNS_RPZ_TYPE_NSDNAME,
@@ -4384,42 +4610,23 @@
 					dns_rdata_freestruct(&ns);
 					goto cleanup;
 				}
+				st->state |=3D DNS_RPZ_DONE_NSDNAME;
 			}
 			/*
-			 * Check all IP addresses for this NS name, but don't
-			 * bother without NSIP rules or with a NSDNAME hit.
+			 * Check all IP addresses for this NS name.
 			 */
-			version =3D NULL;
-			if ((st->state & DNS_RPZ_HAVE_NSIPv4) !=3D 0 &&
-			    st->m.type !=3D DNS_RPZ_TYPE_NSDNAME &&
-			    (st->state & DNS_RPZ_DONE_A) =3D=3D 0) {
-				result =3D rpz_rewrite_nsip(client,
-							  dns_rdatatype_a,
-							  &ns.name, &ipdb,
-							  version, &rdataset,
-							  resuming);
-				if (result =3D=3D ISC_R_SUCCESS)
-					st->state |=3D DNS_RPZ_DONE_A;
-			}
-			if (result =3D=3D ISC_R_SUCCESS &&
-			    (st->state & DNS_RPZ_HAVE_NSIPv6) !=3D 0 &&
-			    st->m.type !=3D DNS_RPZ_TYPE_NSDNAME) {
-				result =3D rpz_rewrite_nsip(client,
-							  dns_rdatatype_aaaa,
-							  &ns.name, &ipdb,
-							  version, &rdataset,
-							  resuming);
-			}
+			result =3D rpz_rewrite_rrsets(client, DNS_RPZ_TYPE_NSIP,
+						    &ns.name, dns_rdatatype_any,
+						    &rdataset, resuming);
 			dns_rdata_freestruct(&ns);
-			if (ipdb !=3D NULL)
-				dns_db_detach(&ipdb);
 			if (result !=3D ISC_R_SUCCESS)
 				goto cleanup;
-			st->state &=3D ~DNS_RPZ_DONE_A;
-			result =3D dns_rdataset_next(st->ns.ns_rdataset);
+			st->state &=3D ~(DNS_RPZ_DONE_NSDNAME |
+				       DNS_RPZ_DONE_IPv4);
+			result =3D dns_rdataset_next(st->r.ns_rdataset);
 		} while (result =3D=3D ISC_R_SUCCESS);
-		dns_rdataset_disassociate(st->ns.ns_rdataset);
-		st->ns.label--;
+		dns_rdataset_disassociate(st->r.ns_rdataset);
+		st->r.label--;
 	}
=20
 	/*
@@ -4429,31 +4636,76 @@
=20
 cleanup:
 	if (st->m.policy !=3D DNS_RPZ_POLICY_MISS &&
-	    st->m.policy !=3D DNS_RPZ_POLICY_NO_OP &&
 	    st->m.policy !=3D DNS_RPZ_POLICY_ERROR &&
 	    st->m.rpz->policy !=3D DNS_RPZ_POLICY_GIVEN)
 		st->m.policy =3D st->m.rpz->policy;
-	if (st->m.policy =3D=3D DNS_RPZ_POLICY_NO_OP)
-		rpz_log(client);
 	if (st->m.policy =3D=3D DNS_RPZ_POLICY_MISS ||
-	    st->m.policy =3D=3D DNS_RPZ_POLICY_NO_OP ||
-	    st->m.policy =3D=3D DNS_RPZ_POLICY_ERROR)
+	    st->m.policy =3D=3D DNS_RPZ_POLICY_PASSTHRU ||
+	    st->m.policy =3D=3D DNS_RPZ_POLICY_ERROR) {
+		if (st->m.policy =3D=3D DNS_RPZ_POLICY_PASSTHRU)
+			rpz_log_rewrite(client, "", st->m.policy, st->m.type,
+					st->qname);
 		rpz_clean(&st->m.zone, &st->m.db, &st->m.node, &st->m.rdataset);
-	if (st->m.policy !=3D DNS_RPZ_POLICY_MISS)
-		st->state |=3D DNS_RPZ_REWRITTEN;
+	}
 	if (st->m.policy =3D=3D DNS_RPZ_POLICY_ERROR) {
 		st->m.type =3D DNS_RPZ_TYPE_BAD;
 		result =3D DNS_R_SERVFAIL;
 	}
-	if (rdataset !=3D NULL)
-		query_putrdataset(client, &rdataset);
-	if ((st->state & DNS_RPZ_RECURSING) =3D=3D 0) {
-		rpz_clean(NULL, &st->ns.db, NULL, &st->ns.ns_rdataset);
-	}
+	query_putrdataset(client, &rdataset);
+	if ((st->state & DNS_RPZ_RECURSING) =3D=3D 0)
+		rpz_clean(NULL, &st->r.db, NULL, &st->r.ns_rdataset);
=20
 	return (result);
 }
=20
+/*
+ * Add a CNAME to the query response, including translating foo.evil.com a=
nd
+ *	*.evil.com CNAME *.example.com
+ * to
+ *	foo.evil.com CNAME foo.evil.com.example.com
+ */
+static isc_result_t
+rpz_add_cname(ns_client_t *client, dns_rpz_st_t *st,
+	      dns_name_t *cname, dns_name_t *fname, isc_buffer_t *dbuf)
+{
+	dns_fixedname_t prefix, suffix;
+	unsigned int labels;
+	isc_result_t result;
+
+	labels =3D dns_name_countlabels(cname);
+	if (labels > 2 && dns_name_iswildcard(cname)) {
+		dns_fixedname_init(&prefix);
+		dns_name_split(client->query.qname, 1,
+			       dns_fixedname_name(&prefix), NULL);
+		dns_fixedname_init(&suffix);
+		dns_name_split(cname, labels-1,
+			       NULL, dns_fixedname_name(&suffix));
+		result =3D dns_name_concatenate(dns_fixedname_name(&prefix),
+					      dns_fixedname_name(&suffix),
+					      fname, NULL);
+		if (result =3D=3D DNS_R_NAMETOOLONG)
+			client->message->rcode =3D dns_rcode_yxdomain;
+	} else {
+		result =3D dns_name_copy(cname, fname, NULL);
+		RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
+	}
+	if (result !=3D ISC_R_SUCCESS)
+		return (result);
+	query_keepname(client, fname, dbuf);
+	result =3D query_add_cname(client, client->query.qname,
+				 fname, dns_trust_authanswer, st->m.ttl);
+	if (result !=3D ISC_R_SUCCESS)
+		return (result);
+	rpz_log_rewrite(client, "", st->m.policy, st->m.type, st->qname);
+	ns_client_qnamereplace(client, fname);
+	/*
+	 * Turn off DNSSEC because the results of a
+	 * response policy zone cannot verify.
+	 */
+	client->attributes &=3D ~NS_CLIENTATTR_WANTDNSSEC;
+	return (ISC_R_SUCCESS);
+}
+
 #define MAX_RESTARTS 16
=20
 #define QUERY_ERROR(r) \
@@ -5027,14 +5279,12 @@
 			rpz_st->q.sigrdataset =3D NULL;
 			qtype =3D rpz_st->q.qtype;
=20
+			rpz_st->r.db =3D event->db;
 			if (event->node !=3D NULL)
-				dns_db_detachnode(db, &event->node);
-			rpz_st->ns.db =3D event->db;
-			rpz_st->ns.r_type =3D event->qtype;
-			rpz_st->ns.r_rdataset =3D event->rdataset;
-			if (event->sigrdataset !=3D NULL &&
-			    dns_rdataset_isassociated(event->sigrdataset))
-				dns_rdataset_disassociate(event->sigrdataset);
+				dns_db_detachnode(event->db, &event->node);
+			rpz_st->r.r_type =3D event->qtype;
+			rpz_st->r.r_rdataset =3D event->rdataset;
+			query_putrdataset(client, &event->sigrdataset);
 		} else {
 			authoritative =3D ISC_FALSE;
=20
@@ -5085,7 +5335,7 @@
 		}
 		if (rpz_st !=3D NULL &&
 		    (rpz_st->state & DNS_RPZ_RECURSING) !=3D 0) {
-			rpz_st->ns.r_result =3D event->result;
+			rpz_st->r.r_result =3D event->result;
 			result =3D rpz_st->q.result;
 			isc_event_free(ISC_EVENT_PTR(&event));
 		} else {
@@ -5248,13 +5498,14 @@
=20
 	if (!ISC_LIST_EMPTY(client->view->rpz_zones) &&
 	    RECURSIONOK(client) && !RECURSING(client) &&
-	    result !=3D DNS_R_DELEGATION && result !=3D ISC_R_NOTFOUND &&
+	    (!WANTDNSSEC(client) || sigrdataset =3D=3D NULL ||
+	     !dns_rdataset_isassociated(sigrdataset)) &&
 	    (client->query.rpz_st =3D=3D NULL ||
 	     (client->query.rpz_st->state & DNS_RPZ_REWRITTEN) =3D=3D 0) &&
 	    !dns_name_equal(client->query.qname, dns_rootname)) {
 		isc_result_t rresult;
=20
-		rresult =3D rpz_rewrite(client, qtype, resuming);
+		rresult =3D rpz_rewrite(client, qtype, result, resuming);
 		rpz_st =3D client->query.rpz_st;
 		switch (rresult) {
 		case ISC_R_SUCCESS:
@@ -5285,16 +5536,19 @@
 			RECURSE_ERROR(rresult);
 			goto cleanup;
 		}
+		if (rpz_st->m.policy !=3D DNS_RPZ_POLICY_MISS)
+			rpz_st->state |=3D DNS_RPZ_REWRITTEN;
 		if (rpz_st->m.policy !=3D DNS_RPZ_POLICY_MISS &&
-		    rpz_st->m.policy !=3D DNS_RPZ_POLICY_NO_OP) {
-			result =3D dns_name_copy(client->query.qname, fname,
-					       NULL);
-			RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
- finish_rewrite:
+		    rpz_st->m.policy !=3D DNS_RPZ_POLICY_PASSTHRU &&
+		    rpz_st->m.policy !=3D DNS_RPZ_POLICY_ERROR) {
+			if (rpz_st->m.type =3D=3D DNS_RPZ_TYPE_QNAME) {
+				result =3D dns_name_copy(client->query.qname,
+						       fname, NULL);
+				RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
+			}
 			rpz_clean(&zone, &db, &node, NULL);
 			if (rpz_st->m.rdataset !=3D NULL) {
-				if (rdataset !=3D NULL)
-					query_putrdataset(client, &rdataset);
+				query_putrdataset(client, &rdataset);
 				rdataset =3D rpz_st->m.rdataset;
 				rpz_st->m.rdataset =3D NULL;
 			} else if (rdataset !=3D NULL &&
@@ -5305,10 +5559,11 @@
 			rpz_st->m.node =3D NULL;
 			db =3D rpz_st->m.db;
 			rpz_st->m.db =3D NULL;
+			version =3D rpz_st->m.version;
+			rpz_st->m.version =3D NULL;
 			zone =3D rpz_st->m.zone;
 			rpz_st->m.zone =3D NULL;
=20
-			result =3D rpz_st->m.result;
 			switch (rpz_st->m.policy) {
 			case DNS_RPZ_POLICY_NXDOMAIN:
 				result =3D DNS_R_NXDOMAIN;
@@ -5317,27 +5572,39 @@
 				result =3D DNS_R_NXRRSET;
 				break;
 			case DNS_RPZ_POLICY_RECORD:
+				result =3D rpz_st->m.result;
 				if (type =3D=3D dns_rdatatype_any &&
 				    result !=3D DNS_R_CNAME &&
 				    dns_rdataset_isassociated(rdataset))
 					dns_rdataset_disassociate(rdataset);
 				break;
-			case DNS_RPZ_POLICY_CNAME:
-				result =3D dns_name_copy(&rpz_st->m.rpz->cname,
-						       fname, NULL);
+			case DNS_RPZ_POLICY_WILDCNAME:
+				result =3D dns_rdataset_first(rdataset);
 				RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
-				query_keepname(client, fname, dbuf);
-				result =3D query_add_cname(client,
-							client->query.qname,
-							fname,
-							dns_trust_authanswer,
-							rpz_st->m.ttl);
+				dns_rdataset_current(rdataset, &rdata);
+				result =3D dns_rdata_tostruct(&rdata, &cname,
+							    NULL);
+				RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
+				dns_rdata_reset(&rdata);
+				result =3D rpz_add_cname(client, rpz_st,
+						       &cname.cname,
+						       fname, dbuf);
 				if (result !=3D ISC_R_SUCCESS)
 					goto cleanup;
-				ns_client_qnamereplace(client, fname);
 				fname =3D NULL;
-				client->attributes &=3D ~NS_CLIENTATTR_WANTDNSSEC;
-				rpz_log(client);
+				want_restart =3D ISC_TRUE;
+				goto cleanup;
+			case DNS_RPZ_POLICY_CNAME:
+				/*
+				 * Add overridding CNAME from a named.conf
+				 * response-policy statement
+				 */
+				result =3D rpz_add_cname(client, rpz_st,
+						       &rpz_st->m.rpz->cname,
+						       fname, dbuf);
+				if (result !=3D ISC_R_SUCCESS)
+					goto cleanup;
+				fname =3D NULL;
 				want_restart =3D ISC_TRUE;
 				goto cleanup;
 			default:
@@ -5349,11 +5616,10 @@
 			 * response policy zone cannot verify.
 			 */
 			client->attributes &=3D ~NS_CLIENTATTR_WANTDNSSEC;
-			if (sigrdataset !=3D NULL &&
-			    dns_rdataset_isassociated(sigrdataset))
-				dns_rdataset_disassociate(sigrdataset);
+			query_putrdataset(client, &sigrdataset);
 			is_zone =3D ISC_TRUE;
-			rpz_log(client);
+			rpz_log_rewrite(client, "", rpz_st->m.policy,
+					rpz_st->m.type, rpz_st->qname);
 		}
 	}
=20
@@ -5668,7 +5934,7 @@
=20
 	case DNS_R_EMPTYNAME:
 	case DNS_R_NXRRSET:
-	nxrrset:
+	iszone_nxrrset:
 		INSIST(is_zone);
=20
 #ifdef dns64_bis_return_excluded_addresses
@@ -5686,6 +5952,8 @@
 				query_putrdataset(client, &sigrdataset);
 			rdataset =3D client->query.dns64_aaaa;
 			sigrdataset =3D client->query.dns64_sigaaaa;
+			client->query.dns64_aaaa =3D NULL;
+			client->query.dns64_sigaaaa =3D NULL;
 			if (fname =3D=3D NULL) {
 				dbuf =3D query_getnamebuf(client);
 				if (dbuf =3D=3D NULL) {
@@ -5699,8 +5967,6 @@
 				}
 			}
 			dns_name_copy(client->query.qname, fname, NULL);
-			client->query.dns64_aaaa =3D NULL;
-			client->query.dns64_sigaaaa =3D NULL;
 			dns64 =3D ISC_FALSE;
 #ifdef dns64_bis_return_excluded_addresses
 			/*
@@ -5735,6 +6001,7 @@
 		/*
 		 * Look for a NSEC3 record if we don't have a NSEC record.
 		 */
+ nxrrset_rrsig:
 		if (!dns_rdataset_isassociated(rdataset) &&
 		     WANTDNSSEC(client)) {
 			if ((fname->attributes & DNS_NAMEATTR_WILDCARD) =3D=3D 0) {
@@ -5860,6 +6127,7 @@
 			 */
 			query_releasename(client, &fname);
 		}
+
 		/*
 		 * Add SOA.  If the query was for a SOA record force the
 		 * ttl to zero so that it is possible for clients to find
@@ -5936,6 +6204,8 @@
 				query_putrdataset(client, &sigrdataset);
 			rdataset =3D client->query.dns64_aaaa;
 			sigrdataset =3D client->query.dns64_sigaaaa;
+			client->query.dns64_aaaa =3D NULL;
+			client->query.dns64_sigaaaa =3D NULL;
 			if (fname =3D=3D NULL) {
 				dbuf =3D query_getnamebuf(client);
 				if (dbuf =3D=3D NULL) {
@@ -5949,8 +6219,6 @@
 				}
 			}
 			dns_name_copy(client->query.qname, fname, NULL);
-			client->query.dns64_aaaa =3D NULL;
-			client->query.dns64_sigaaaa =3D NULL;
 			dns64 =3D ISC_FALSE;
 #ifdef dns64_bis_return_excluded_addresses
 			if (dns64_excluded)
@@ -6201,9 +6469,21 @@
 		need_wildcardproof =3D ISC_TRUE;
 	}
=20
+#ifdef ALLOW_FILTER_AAAA_ON_V4
+	if (client->view->v4_aaaa !=3D dns_v4_aaaa_ok &&
+	    is_v4_client(client) &&
+	    ns_client_checkaclsilent(client, NULL,
+				     client->view->v4_aaaa_acl,
+				     ISC_TRUE) =3D=3D ISC_R_SUCCESS)
+		client->filter_aaaa =3D client->view->v4_aaaa;
+	else
+		client->filter_aaaa =3D dns_v4_aaaa_ok;
+
+#endif
+
 	if (type =3D=3D dns_rdatatype_any) {
 #ifdef ALLOW_FILTER_AAAA_ON_V4
-		isc_boolean_t have_aaaa, have_a, have_sig, filter_aaaa;
+		isc_boolean_t have_aaaa, have_a, have_sig;
=20
 		/*
 		 * The filter-aaaa-on-v4 option should
@@ -6215,14 +6495,6 @@
 		have_aaaa =3D ISC_FALSE;
 		have_a =3D !authoritative;
 		have_sig =3D ISC_FALSE;
-		if (client->view->v4_aaaa !=3D dns_v4_aaaa_ok &&
-		    is_v4_client(client) &&
-		    ns_client_checkaclsilent(client, NULL,
-					     client->view->v4_aaaa_acl,
-					     ISC_TRUE) =3D=3D ISC_R_SUCCESS)
-			filter_aaaa =3D ISC_TRUE;
-		else
-			filter_aaaa =3D ISC_FALSE;
 #endif
 		/*
 		 * XXXRTH  Need to handle zonecuts with special case
@@ -6237,53 +6509,6 @@
 		}
=20
 		/*
-		 * Check all A and AAAA records in all response policy
-		 * IP address zones
-		 */
-		rpz_st =3D client->query.rpz_st;
-		if (rpz_st !=3D NULL &&
-		    (rpz_st->state & DNS_RPZ_DONE_QNAME) !=3D 0 &&
-		    (rpz_st->state & DNS_RPZ_REWRITTEN) =3D=3D 0 &&
-		    RECURSIONOK(client) && !RECURSING(client) &&
-		    (rpz_st->state & DNS_RPZ_HAVE_IP) !=3D 0) {
-			for (result =3D dns_rdatasetiter_first(rdsiter);
-			     result =3D=3D ISC_R_SUCCESS;
-			     result =3D dns_rdatasetiter_next(rdsiter)) {
-				dns_rdatasetiter_current(rdsiter, rdataset);
-				if (rdataset->type =3D=3D dns_rdatatype_a ||
-				    rdataset->type =3D=3D dns_rdatatype_aaaa)
-					result =3D rpz_rewrite_ip(client,
-							      rdataset,
-							      DNS_RPZ_TYPE_IP);
-				dns_rdataset_disassociate(rdataset);
-				if (result !=3D ISC_R_SUCCESS)
-					break;
-			}
-			if (result !=3D ISC_R_NOMORE) {
-				dns_rdatasetiter_destroy(&rdsiter);
-				QUERY_ERROR(DNS_R_SERVFAIL);
-				goto cleanup;
-			}
-			switch (rpz_st->m.policy) {
-			case DNS_RPZ_POLICY_MISS:
-				break;
-			case DNS_RPZ_POLICY_NO_OP:
-				rpz_log(client);
-				rpz_st->state |=3D DNS_RPZ_REWRITTEN;
-				break;
-			case DNS_RPZ_POLICY_NXDOMAIN:
-			case DNS_RPZ_POLICY_NODATA:
-			case DNS_RPZ_POLICY_RECORD:
-			case DNS_RPZ_POLICY_CNAME:
-				dns_rdatasetiter_destroy(&rdsiter);
-				rpz_st->state |=3D DNS_RPZ_REWRITTEN;
-				goto finish_rewrite;
-			default:
-				INSIST(0);
-			}
-		}
-
-		/*
 		 * Calling query_addrrset() with a non-NULL dbuf is going
 		 * to either keep or release the name.  We don't want it to
 		 * release fname, since we may have to call query_addrrset()
@@ -6304,7 +6529,7 @@
 			 * Notice the presence of A and AAAAs so
 			 * that AAAAs can be hidden from IPv4 clients.
 			 */
-			if (filter_aaaa) {
+			if (client->filter_aaaa !=3D dns_v4_aaaa_ok) {
 				if (rdataset->type =3D=3D dns_rdatatype_aaaa)
 					have_aaaa =3D ISC_TRUE;
 				else if (rdataset->type =3D=3D dns_rdatatype_a)
@@ -6361,76 +6586,52 @@
 		 * Filter AAAAs if there is an A and there is no signature
 		 * or we are supposed to break DNSSEC.
 		 */
-		if (filter_aaaa && have_aaaa && have_a &&
-		    (!have_sig || !WANTDNSSEC(client) ||
-		     client->view->v4_aaaa =3D=3D dns_v4_aaaa_break_dnssec))
+		if (client->filter_aaaa =3D=3D dns_v4_aaaa_break_dnssec)
 			client->attributes |=3D NS_CLIENTATTR_FILTER_AAAA;
+		else if (client->filter_aaaa !=3D dns_v4_aaaa_ok &&
+			 have_aaaa && have_a &&
+			 (!have_sig || !WANTDNSSEC(client)))
+			  client->attributes |=3D NS_CLIENTATTR_FILTER_AAAA;
 #endif
 		if (fname !=3D NULL)
 			dns_message_puttempname(client->message, &fname);
=20
-		if (n =3D=3D 0 && is_zone) {
+		if (n =3D=3D 0) {
 			/*
-			 * We didn't match any rdatasets.
+			 * No matching rdatasets found in cache. If we were
+			 * searching for RRSIG/SIG, that's probably okay;
+			 * otherwise this is an error condition.
 			 */
 			if ((qtype =3D=3D dns_rdatatype_rrsig ||
 			     qtype =3D=3D dns_rdatatype_sig) &&
 			    result =3D=3D ISC_R_NOMORE) {
-				/*
-				 * XXXRTH  If this is a secure zone and we
-				 * didn't find any SIGs, we should generate
-				 * an error unless we were searching for
-				 * glue.  Ugh.
-				 */
 				if (!is_zone) {
-					/*
-					 * Note: this is dead code because
-					 * is_zone is always true due to the
-					 * condition above.  But naive
-					 * recursion would cause infinite
-					 * attempts of recursion because
-					 * the answer to (RR)SIG queries
-					 * won't be cached.  Until we figure
-					 * out what we should do and implement
-					 * it we intentionally keep this code
-					 * dead.
-					 */
 					authoritative =3D ISC_FALSE;
 					dns_rdatasetiter_destroy(&rdsiter);
-					if (RECURSIONOK(client)) {
-						result =3D query_recurse(client,
-							    qtype,
-							    client->query.qname,
-							    NULL, NULL,
-							    resuming);
-						if (result =3D=3D ISC_R_SUCCESS)
-						    client->query.attributes |=3D
-							NS_QUERYATTR_RECURSING;
-						else
-						    RECURSE_ERROR(result);
-					}
+					client->attributes &=3D ~NS_CLIENTATTR_RA;
 					goto addauth;
 				}
-				/*
-				 * We were searching for SIG records in
-				 * a nonsecure zone.  Send a "no error,
-				 * no data" response.
-				 */
-				/*
-				 * Add SOA.
-				 */
-				result =3D query_addsoa(client, db, version,
-						      ISC_UINT32_MAX,
-						      ISC_FALSE);
-				if (result =3D=3D ISC_R_SUCCESS)
-					result =3D ISC_R_NOMORE;
-			} else {
-				/*
-				 * Something went wrong.
-				 */
+
+				if (dns_db_issecure(db)) {
+					char namebuf[DNS_NAME_FORMATSIZE];
+					dns_name_format(client->query.qname,
+							namebuf,
+							sizeof(namebuf));
+					ns_client_log(client,
+						      DNS_LOGCATEGORY_DNSSEC,
+						      NS_LOGMODULE_QUERY,
+						      ISC_LOG_WARNING,
+						      "missing signature "
+						      "for %s", namebuf);
+				}
+
+				dns_rdatasetiter_destroy(&rdsiter);
+				fname =3D query_newname(client, dbuf, &b);
+				goto nxrrset_rrsig;
+			} else
 				result =3D DNS_R_SERVFAIL;
-			}
 		}
+
 		dns_rdatasetiter_destroy(&rdsiter);
 		if (result !=3D ISC_R_NOMORE) {
 			QUERY_ERROR(DNS_R_SERVFAIL);
@@ -6442,48 +6643,6 @@
 		 * we know the answer.
 		 */
=20
-		/*
-		 * Check all A and AAAA records in all response policy
-		 * IP address zones
-		 */
-		rpz_st =3D client->query.rpz_st;
-		if (rpz_st !=3D NULL &&
-		    (rpz_st->state & DNS_RPZ_DONE_QNAME) !=3D 0 &&
-		    (rpz_st->state & DNS_RPZ_REWRITTEN) =3D=3D 0 &&
-		    RECURSIONOK(client) && !RECURSING(client) &&
-		    (rpz_st->state & DNS_RPZ_HAVE_IP) !=3D 0 &&
-		    (qtype =3D=3D dns_rdatatype_aaaa || qtype =3D=3D dns_rdatatype_a)) {
-			result =3D rpz_rewrite_ip(client, rdataset,
-						DNS_RPZ_TYPE_IP);
-			if (result !=3D ISC_R_SUCCESS) {
-				QUERY_ERROR(DNS_R_SERVFAIL);
-				goto cleanup;
-			}
-			/*
-			 * After a hit in the radix tree for the policy domain,
-			 * either stop trying to rewrite (DNS_RPZ_POLICY_NO_OP)
-			 * or restart to ask the ordinary database of the
-			 * policy zone for the DNS record corresponding to the
-			 * record in the radix tree.
-			 */
-			switch (rpz_st->m.policy) {
-			case DNS_RPZ_POLICY_MISS:
-				break;
-			case DNS_RPZ_POLICY_NO_OP:
-				rpz_log(client);
-				rpz_st->state |=3D DNS_RPZ_REWRITTEN;
-				break;
-			case DNS_RPZ_POLICY_NXDOMAIN:
-			case DNS_RPZ_POLICY_NODATA:
-			case DNS_RPZ_POLICY_RECORD:
-			case DNS_RPZ_POLICY_CNAME:
-				rpz_st->state |=3D DNS_RPZ_REWRITTEN;
-				goto finish_rewrite;
-			default:
-				INSIST(0);
-			}
-		}
-
 #ifdef ALLOW_FILTER_AAAA_ON_V4
 		/*
 		 * Optionally hide AAAAs from IPv4 clients if there is an A.
@@ -6493,15 +6652,11 @@
 		 * so fundamentally wrong, unavoidably inaccurate, and
 		 * unneeded that it is best to keep it as short as possible.
 		 */
-		if (client->view->v4_aaaa !=3D dns_v4_aaaa_ok &&
-		    is_v4_client(client) &&
-		    ns_client_checkaclsilent(client, NULL,
-					     client->view->v4_aaaa_acl,
-					     ISC_TRUE) =3D=3D ISC_R_SUCCESS &&
-		    (!WANTDNSSEC(client) ||
-		     sigrdataset =3D=3D NULL ||
-		     !dns_rdataset_isassociated(sigrdataset) ||
-		     client->view->v4_aaaa =3D=3D dns_v4_aaaa_break_dnssec)) {
+		if (client->filter_aaaa =3D=3D dns_v4_aaaa_break_dnssec ||
+		    (client->filter_aaaa =3D=3D dns_v4_aaaa_filter &&
+		     (!WANTDNSSEC(client) || sigrdataset =3D=3D NULL ||
+		     !dns_rdataset_isassociated(sigrdataset))))
+		{
 			if (qtype =3D=3D dns_rdatatype_aaaa) {
 				trdataset =3D query_newrdataset(client);
 				result =3D dns_db_findrdataset(db, node, version,
@@ -6633,7 +6788,7 @@
 				}
 #endif
 				if (is_zone)
-					goto nxrrset;
+					goto iszone_nxrrset;
 				else
 					goto ncache_nxrrset;
 			} else if (result !=3D ISC_R_SUCCESS) {
@@ -6691,9 +6846,11 @@
 	 * General cleanup.
 	 */
 	rpz_st =3D client->query.rpz_st;
-	if (rpz_st !=3D NULL && (rpz_st->state & DNS_RPZ_RECURSING) =3D=3D 0)
+	if (rpz_st !=3D NULL && (rpz_st->state & DNS_RPZ_RECURSING) =3D=3D 0) {
 		rpz_clean(&rpz_st->m.zone, &rpz_st->m.db, &rpz_st->m.node,
 			  &rpz_st->m.rdataset);
+		rpz_st->state &=3D ~DNS_RPZ_DONE_QNAME;
+	}
 	if (rdataset !=3D NULL)
 		query_putrdataset(client, &rdataset);
 	if (sigrdataset !=3D NULL)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/server.c
--- a/head/contrib/bind9/bin/named/server.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/server.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: server.c,v 1.599.8.12 2011-08-02 04:58:45 each Exp $ */
+/* $Id: server.c,v 1.599.8.19 2012/02/22 00:33:32 each Exp $ */
=20
 /*! \file */
=20
@@ -2596,14 +2596,19 @@
 	if (result =3D=3D ISC_R_SUCCESS) {
 		/* If set to "auto", use the version from the defaults */
 		const cfg_obj_t *dlvobj;
+		const char *dom;
 		dlvobj =3D cfg_listelt_value(cfg_list_first(obj));
-		if (!strcmp(cfg_obj_asstring(cfg_tuple_get(dlvobj, "domain")),
-			    "auto") &&
-		    cfg_obj_isvoid(cfg_tuple_get(dlvobj, "trust-anchor"))) {
-			auto_dlv =3D ISC_TRUE;
-			obj =3D NULL;
-			result =3D cfg_map_get(ns_g_defaults,
-					     "dnssec-lookaside", &obj);
+		dom =3D cfg_obj_asstring(cfg_tuple_get(dlvobj, "domain"));
+		if (cfg_obj_isvoid(cfg_tuple_get(dlvobj, "trust-anchor"))) {
+			/* If "no", skip; if "auto", use global default */
+			if (!strcasecmp(dom, "no"))
+				result =3D ISC_R_NOTFOUND;
+			else if (!strcasecmp(dom, "auto")) {
+				auto_dlv =3D ISC_TRUE;
+				obj =3D NULL;
+				result =3D cfg_map_get(ns_g_defaults,
+						     "dnssec-lookaside", &obj);
+			}
 		}
 	}
=20
@@ -2704,7 +2709,7 @@
 		rfc1918 =3D ISC_FALSE;
 		empty_zones_enable =3D ISC_FALSE;
 	}
-	if (empty_zones_enable) {
+	if (empty_zones_enable && !lwresd_g_useresolvconf) {
 		const char *empty;
 		int empty_zone =3D 0;
 		dns_fixedname_t fixed;
@@ -2842,7 +2847,8 @@
 			CHECK(dns_zone_create(&zone, mctx));
 			CHECK(dns_zone_setorigin(zone, name));
 			dns_zone_setview(zone, view);
-			CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr, zone));
+			CHECK(dns_zonemgr_managezone(ns_g_server->zonemgr,
+						     zone));
 			dns_zone_setclass(zone, view->rdclass);
 			dns_zone_settype(zone, dns_zone_master);
 			dns_zone_setstats(zone, ns_g_server->zonestats);
@@ -3449,6 +3455,12 @@
 	 */
 	CHECK(dns_view_addzone(view, zone));
=20
+	/*
+	 * Ensure that zone keys are reloaded on reconfig
+	 */
+	if ((dns_zone_getkeyopts(zone) & DNS_ZONEKEY_MAINTAIN) !=3D 0)
+		dns_zone_rekey(zone, ISC_FALSE);
+
  cleanup:
 	if (zone !=3D NULL)
 		dns_zone_detach(&zone);
@@ -3489,6 +3501,7 @@
 		dns_zone_attach(pview->managed_keys, &view->managed_keys);
 		dns_zone_setview(pview->managed_keys, view);
 		dns_view_detach(&pview);
+		dns_zone_synckeyzone(view->managed_keys);
 		return (ISC_R_SUCCESS);
 	}
=20
@@ -4278,15 +4291,12 @@
 	ns_cache_t *nsc;
 	struct cfg_context *nzctx;
 	int num_zones =3D 0;
+	isc_boolean_t exclusive =3D ISC_FALSE;
=20
 	ISC_LIST_INIT(viewlist);
 	ISC_LIST_INIT(builtin_viewlist);
 	ISC_LIST_INIT(cachelist);
=20
-	/* Ensure exclusive access to configuration data. */
-	result =3D isc_task_beginexclusive(server->task);
-	RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
-
 	/* Create the ACL configuration context */
 	if (ns_g_aclconfctx !=3D NULL)
 		cfg_aclconfctx_detach(&ns_g_aclconfctx);
@@ -4382,6 +4392,13 @@
 		CHECK(result);
 	}
=20
+	/* Ensure exclusive access to configuration data. */
+	if (!exclusive) {
+		result =3D isc_task_beginexclusive(server->task);
+		RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
+		exclusive =3D ISC_TRUE;
+	}
+
 	/*
 	 * Set process limits, which (usually) needs to be done as root.
 	 */
@@ -5149,7 +5166,8 @@
 		adjust_interfaces(server, ns_g_mctx);
=20
 	/* Relinquish exclusive access to configuration data. */
-	isc_task_endexclusive(server->task);
+	if (exclusive)
+		isc_task_endexclusive(server->task);
=20
 	isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER,
 		      ISC_LOG_DEBUG(1), "load_configuration: %s",
@@ -7352,13 +7370,14 @@
 	CHECK(isc_stdio_open(view->new_zone_file, "a", &fp));
=20
 	/* Mark view unfrozen so that zone can be added */
+	isc_task_beginexclusive(server->task);
 	dns_view_thaw(view);
 	result =3D configure_zone(cfg->config, parms, vconfig,
 				server->mctx, view, cfg->actx, ISC_FALSE);
 	dns_view_freeze(view);
-	if (result !=3D ISC_R_SUCCESS) {
+	isc_task_endexclusive(server->task);
+	if (result !=3D ISC_R_SUCCESS)
 		goto cleanup;
-	}
=20
 	/* Is it there yet? */
 	CHECK(dns_zt_find(view->zonetable, &dnsname, 0, NULL, &zone));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/sortlist.c
--- a/head/contrib/bind9/bin/named/sortlist.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/sortlist.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sortlist.c,v 1.17 2007-09-14 01:46:05 marka Exp $ */
+/* $Id: sortlist.c,v 1.17 2007/09/14 01:46:05 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/statschan=
nel.c
--- a/head/contrib/bind9/bin/named/statschannel.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/bin/named/statschannel.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: statschannel.c,v 1.26.150.2 2011-03-12 04:59:14 tbox Exp $ */
+/* $Id: statschannel.c,v 1.26.150.2 2011/03/12 04:59:14 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/tkeyconf.c
--- a/head/contrib/bind9/bin/named/tkeyconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/tkeyconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tkeyconf.c,v 1.33 2010-12-20 23:47:20 tbox Exp $ */
+/* $Id: tkeyconf.c,v 1.33 2010/12/20 23:47:20 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/tsigconf.c
--- a/head/contrib/bind9/bin/named/tsigconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/tsigconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsigconf.c,v 1.35 2011-01-11 23:47:12 tbox Exp $ */
+/* $Id: tsigconf.c,v 1.35 2011/01/11 23:47:12 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/unix/Make=
file.in
--- a/head/contrib/bind9/bin/named/unix/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/named/unix/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.13.244.2 2011-03-10 23:47:26 tbox Exp $
+# $Id: Makefile.in,v 1.13.244.2 2011/03/10 23:47:26 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/unix/dlz_=
dlopen_driver.c
--- a/head/contrib/bind9/bin/named/unix/dlz_dlopen_driver.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/unix/dlz_dlopen_driver.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlz_dlopen_driver.c,v 1.1.4.4 2011-03-17 09:41:06 fdupont Exp $ */
+/* $Id: dlz_dlopen_driver.c,v 1.1.4.6 2012/02/22 23:46:35 tbox Exp $ */
=20
 #include <config.h>
=20
@@ -313,6 +313,8 @@
 		dl_load_symbol(cd, "dlz_subrdataset", ISC_FALSE);
 	cd->dlz_delrdataset =3D (dlz_dlopen_delrdataset_t *)
 		dl_load_symbol(cd, "dlz_delrdataset", ISC_FALSE);
+	cd->dlz_destroy =3D (dlz_dlopen_destroy_t *)
+		dl_load_symbol(cd, "dlz_destroy", ISC_FALSE);
=20
 	/* Check the version of the API is the same */
 	cd->version =3D cd->dlz_version(&cd->flags);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/unix/incl=
ude/named/os.h
--- a/head/contrib/bind9/bin/named/unix/include/named/os.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/unix/include/named/os.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: os.h,v 1.31 2009-08-05 23:47:43 tbox Exp $ */
+/* $Id: os.h,v 1.31 2009/08/05 23:47:43 tbox Exp $ */
=20
 #ifndef NS_OS_H
 #define NS_OS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/unix/os.c
--- a/head/contrib/bind9/bin/named/unix/os.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/unix/os.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: os.c,v 1.104.38.3 2011-03-02 00:04:01 marka Exp $ */
+/* $Id: os.c,v 1.104.38.3 2011/03/02 00:04:01 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/update.c
--- a/head/contrib/bind9/bin/named/update.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/update.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: update.c,v 1.186.16.5 2011-03-25 23:53:52 each Exp $ */
+/* $Id: update.c,v 1.186.16.7 2011/11/03 02:55:34 each Exp $ */
=20
 #include <config.h>
=20
@@ -1506,8 +1506,6 @@
  * Incremental updating of NSECs and RRSIGs.
  */
=20
-#define MAXZONEKEYS 32	/*%< Maximum number of zone keys supported. */
-
 /*%
  * We abuse the dns_diff_t type to represent a set of domain names
  * affected by the update.
@@ -2131,7 +2129,7 @@
 	dns_diff_t nsec_diff;
 	dns_diff_t nsec_mindiff;
 	isc_boolean_t flag, build_nsec, build_nsec3;
-	dst_key_t *zone_keys[MAXZONEKEYS];
+	dst_key_t *zone_keys[DNS_MAXZONEKEYS];
 	unsigned int nkeys =3D 0;
 	unsigned int i;
 	isc_stdtime_t now, inception, expire;
@@ -2154,7 +2152,7 @@
 	dns_diff_init(client->mctx, &nsec_mindiff);
=20
 	result =3D find_zone_keys(zone, db, newver, client->mctx,
-				MAXZONEKEYS, zone_keys, &nkeys);
+				DNS_MAXZONEKEYS, zone_keys, &nkeys);
 	if (result !=3D ISC_R_SUCCESS) {
 		update_log(client, zone, ISC_LOG_ERROR,
 			   "could not get zone keys for secure dynamic update");
@@ -4473,6 +4471,12 @@
 	isc_task_t *zonetask =3D NULL;
 	ns_client_t *evclient;
=20
+	/*
+	 * This may take some time so replace this client.
+	 */
+	if (!client->mortal && (client->attributes & NS_CLIENTATTR_TCP) =3D=3D 0)
+		CHECK(ns_client_replace(client));
+
 	event =3D (update_event_t *)
 		isc_event_allocate(client->mctx, client, DNS_EVENT_UPDATE,
 				   forward_action, NULL, sizeof(*event));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/xfrout.c
--- a/head/contrib/bind9/bin/named/xfrout.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/xfrout.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: xfrout.c,v 1.139.16.3 2011-07-28 04:30:54 marka Exp $ */
+/* $Id: xfrout.c,v 1.139.16.4 2011/12/01 01:00:50 marka Exp $ */
=20
 #include <config.h>
=20
@@ -1287,6 +1287,13 @@
 			isc_buffer_free(&xfr->lasttsig);
=20
 		/*
+		 * Account for reserved space.
+		 */
+		if (xfr->tsigkey !=3D NULL)
+			INSIST(msg->reserved !=3D 0U);
+		isc_buffer_add(&xfr->buf, msg->reserved);
+
+		/*
 		 * Include a question section in the first message only.
 		 * BIND 8.2.1 will not recognize an IXFR if it does not
 		 * have a question section.
@@ -1324,9 +1331,13 @@
 			ISC_LIST_APPEND(qname->list, qrdataset, link);
=20
 			dns_message_addname(msg, qname, DNS_SECTION_QUESTION);
+		} else {
+			/*
+			 * Reserve space for the 12-byte message header
+			 */
+			isc_buffer_add(&xfr->buf, 12);
+			msg->tcp_continuation =3D 1;
 		}
-		else
-			msg->tcp_continuation =3D 1;
 	}
=20
 	/*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/named/zoneconf.c
--- a/head/contrib/bind9/bin/named/zoneconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/named/zoneconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zoneconf.c,v 1.170.14.4 2011-05-23 20:56:10 each Exp $ */
+/* $Id: zoneconf.c,v 1.170.14.7 2012/01/31 23:46:39 tbox Exp $ */
=20
 /*% */
=20
@@ -1329,8 +1329,11 @@
 							 &count));
 			result =3D dns_zone_setmasterswithkeys(zone, addrs,
 							     keynames, count);
-			ns_config_putipandkeylist(mctx, &addrs, &keynames,
-						  count);
+			if (count !=3D 0)
+				ns_config_putipandkeylist(mctx, &addrs,
+							  &keynames, count);
+			else
+				INSIST(addrs =3D=3D NULL && keynames =3D=3D NULL);
 		} else
 			result =3D dns_zone_setmasters(zone, NULL, 0);
 		RETERR(result);
@@ -1462,15 +1465,21 @@
=20
 	zoptions =3D cfg_tuple_get(zconfig, "options");
=20
-	if (zonetype_fromconfig(zoptions) !=3D dns_zone_gettype(zone))
+	if (zonetype_fromconfig(zoptions) !=3D dns_zone_gettype(zone)) {
+		dns_zone_log(zone, ISC_LOG_DEBUG(1),
+			     "not reusable: type mismatch");
 		return (ISC_FALSE);
+	}
=20
 	/*
 	 * We always reconfigure a static-stub zone for simplicity, assuming
 	 * the amount of data to be loaded is small.
 	 */
-	if (zonetype_fromconfig(zoptions) =3D=3D dns_zone_staticstub)
+	if (zonetype_fromconfig(zoptions) =3D=3D dns_zone_staticstub) {
+		dns_zone_log(zone, ISC_LOG_DEBUG(1),
+			     "not reusable: staticstub");
 		return (ISC_FALSE);
+	}
=20
 	obj =3D NULL;
 	(void)cfg_map_get(zoptions, "file", &obj);
@@ -1481,8 +1490,11 @@
 	zfilename =3D dns_zone_getfile(zone);
 	if (!((cfilename =3D=3D NULL && zfilename =3D=3D NULL) ||
 	      (cfilename !=3D NULL && zfilename !=3D NULL &&
-	       strcmp(cfilename, zfilename) =3D=3D 0)))
-	    return (ISC_FALSE);
+	       strcmp(cfilename, zfilename) =3D=3D 0))) {
+		dns_zone_log(zone, ISC_LOG_DEBUG(1),
+			"not reusable: filename mismatch");
+		return (ISC_FALSE);
+	}
=20
 	return (ISC_TRUE);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/nsupdate/Makefi=
le.in
--- a/head/contrib/bind9/bin/nsupdate/Makefile.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/bin/nsupdate/Makefile.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.36 2009-12-05 23:31:40 each Exp $
+# $Id: Makefile.in,v 1.36 2009/12/05 23:31:40 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/nsupdate/nsupda=
te.1
--- a/head/contrib/bind9/bin/nsupdate/nsupdate.1	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/nsupdate/nsupdate.1	Tue Apr 17 11:51:51 2012 +=
0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: nsupdate.1,v 1.13 2010-07-10 01:14:19 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/nsupdate/nsupda=
te.c
--- a/head/contrib/bind9/bin/nsupdate/nsupdate.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/nsupdate/nsupdate.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsupdate.c,v 1.193.12.3 2011-05-23 22:12:14 each Exp $ */
+/* $Id: nsupdate.c,v 1.193.12.4 2011/11/03 04:30:09 each Exp $ */
=20
 /*! \file */
=20
@@ -2280,6 +2280,7 @@
 		dns_message_destroy(&soaquery);
 		ddebug("Out of recvsoa");
 		done_update();
+		seenerror =3D ISC_TRUE;
 		return;
 	}
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/nsupdate/nsupda=
te.docbook
--- a/head/contrib/bind9/bin/nsupdate/nsupdate.docbook	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/nsupdate/nsupdate.docbook	Tue Apr 17 11:51:51 =
2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: nsupdate.docbook,v 1.44 2010-07-09 23:46:51 tbox Exp $ -->
+<!-- $Id: nsupdate.docbook,v 1.44 2010/07/09 23:46:51 tbox Exp $ -->
 <refentry id=3D"man.nsupdate">
   <refentryinfo>
     <date>Aug 25, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/nsupdate/nsupda=
te.html
--- a/head/contrib/bind9/bin/nsupdate/nsupdate.html	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/nsupdate/nsupdate.html	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: nsupdate.html,v 1.50 2010-07-10 01:14:19 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">nsupdate</code>  [<c=
ode class=3D"option">-d</code>] [<code class=3D"option">-D</code>] [[<code =
class=3D"option">-g</code>] |  [<code class=3D"option">-o</code>] |  [<code=
 class=3D"option">-l</code>] |  [<code class=3D"option">-y <em class=3D"rep=
laceable"><code>[<span class=3D"optional">hmac:</span>]keyname:secret</code=
></em></code>] |  [<code class=3D"option">-k <em class=3D"replaceable"><cod=
e>keyfile</code></em></code>]] [<code class=3D"option">-t <em class=3D"repl=
aceable"><code>timeout</code></em></code>] [<code class=3D"option">-u <em c=
lass=3D"replaceable"><code>udptimeout</code></em></code>] [<code class=3D"o=
ption">-r <em class=3D"replaceable"><code>udpretries</code></em></code>] [<=
code class=3D"option">-R <em class=3D"replaceable"><code>randomdev</code></=
em></code>] [<code class=3D"option">-v</code>] [filename]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543457"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543459"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">nsupdate</strong></span>
       is used to submit Dynamic DNS Update requests as defined in RFC 2136
       to a name server.
@@ -192,7 +192,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543788"></a><h2>INPUT FORMAT</h2>
+<a name=3D"id2543790"></a><h2>INPUT FORMAT</h2>
 <p><span><strong class=3D"command">nsupdate</strong></span>
       reads input from
       <em class=3D"parameter"><code>filename</code></em>
@@ -480,7 +480,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544700"></a><h2>EXAMPLES</h2>
+<a name=3D"id2544702"></a><h2>EXAMPLES</h2>
 <p>
       The examples below show how
       <span><strong class=3D"command">nsupdate</strong></span>
@@ -534,7 +534,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544744"></a><h2>FILES</h2>
+<a name=3D"id2544746"></a><h2>FILES</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><code class=3D"constant">/etc/resolv.conf</code><=
/span></dt>
 <dd><p>
@@ -557,7 +557,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544827"></a><h2>SEE ALSO</h2>
+<a name=3D"id2544829"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">RFC 2136</em>,
       <em class=3D"citetitle">RFC 3007</em>,
@@ -572,7 +572,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2542154"></a><h2>BUGS</h2>
+<a name=3D"id2542156"></a><h2>BUGS</h2>
 <p>
       The TSIG key is redundantly stored in two separate files.
       This is a consequence of nsupdate using the DST library
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/Makefile.in
--- a/head/contrib/bind9/bin/rndc/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.49 2009-12-05 23:31:40 each Exp $
+# $Id: Makefile.in,v 1.49 2009/12/05 23:31:40 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/include/rn=
dc/os.h
--- a/head/contrib/bind9/bin/rndc/include/rndc/os.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/rndc/include/rndc/os.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: os.h,v 1.12 2009-06-10 00:27:21 each Exp $ */
+/* $Id: os.h,v 1.12 2009/06/10 00:27:21 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.8
--- a/head/contrib/bind9/bin/rndc/rndc.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/rndc.8	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: rndc.8,v 1.43 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.c
--- a/head/contrib/bind9/bin/rndc/rndc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/rndc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rndc.c,v 1.131.20.2 2011-02-28 01:19:59 tbox Exp $ */
+/* $Id: rndc.c,v 1.131.20.3 2011/11/03 22:06:31 each Exp $ */
=20
 /*! \file */
=20
@@ -142,13 +142,17 @@
 		Flush the given name from the server's cache(s)\n\
   status	Display status of the server.\n\
   recursing	Dump the queries that are currently recursing (named.recursing=
)\n\
+  tsig-list	List all currently active TSIG keys, including both statically=
\n\
+		configured and TKEY-negotiated keys.\n\
+  tsig-delete keyname [view]	\n\
+		Delete a TKEY-negotiated TSIG key.\n\
   validation newstate [view]\n\
 		Enable / disable DNSSEC validation.\n\
-  *restart	Restart the server.\n\
   addzone [\"file\"] zone [class [view]] { zone-options }\n\
 		Add zone to given view. Requires new-zone-file option.\n\
   delzone [\"file\"] zone [class [view]]\n\
 		Removes zone from given view. Requires new-zone-file option.\n\
+  *restart	Restart the server.\n\
 \n\
 * =3D=3D not yet implemented\n\
 Version: %s\n",
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.conf
--- a/head/contrib/bind9/bin/rndc/rndc.conf	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/rndc.conf	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rndc.conf,v 1.11 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: rndc.conf,v 1.11 2007/06/19 23:46:59 tbox Exp $ */
=20
 /*
  * Sample rndc configuration file.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.conf.5
--- a/head/contrib/bind9/bin/rndc/rndc.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/rndc.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: rndc.conf.5,v 1.41 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.conf.=
docbook
--- a/head/contrib/bind9/bin/rndc/rndc.conf.docbook	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/rndc/rndc.conf.docbook	Tue Apr 17 11:51:51 201=
2 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: rndc.conf.docbook,v 1.17 2007-06-18 23:47:25 tbox Exp $ -->
+<!-- $Id: rndc.conf.docbook,v 1.17 2007/06/18 23:47:25 tbox Exp $ -->
 <refentry id=3D"man.rndc.conf">
   <refentryinfo>
     <date>June 30, 2000</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.conf.=
html
--- a/head/contrib/bind9/bin/rndc/rndc.conf.html	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/rndc/rndc.conf.html	Tue Apr 17 11:51:51 2012 +=
0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: rndc.conf.html,v 1.32 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">rndc.conf</code> </p=
></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543352"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543354"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"filename">rndc.conf</code> is the configuration file
       for <span><strong class=3D"command">rndc</strong></span>, the BIND 9=
 name server control
       utility.  This file has a similar structure and syntax to
@@ -117,7 +117,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543500"></a><h2>EXAMPLE</h2>
+<a name=3D"id2543502"></a><h2>EXAMPLE</h2>
 <pre class=3D"programlisting">
       options {
         default-server  localhost;
@@ -191,7 +191,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543592"></a><h2>NAME SERVER CONFIGURATION</h2>
+<a name=3D"id2543594"></a><h2>NAME SERVER CONFIGURATION</h2>
 <p>
       The name server must be configured to accept rndc connections and
       to recognize the key specified in the <code class=3D"filename">rndc.=
conf</code>
@@ -201,7 +201,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543613"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543616"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">rndc</span>(=
8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rndc-conf=
gen</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">mmencode<=
/span>(1)</span>,
@@ -209,7 +209,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543652"></a><h2>AUTHOR</h2>
+<a name=3D"id2543654"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.docbo=
ok
--- a/head/contrib/bind9/bin/rndc/rndc.docbook	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/rndc/rndc.docbook	Tue Apr 17 11:51:51 2012 +03=
00
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: rndc.docbook,v 1.21 2007-12-14 20:39:14 marka Exp $ -->
+<!-- $Id: rndc.docbook,v 1.21 2007/12/14 20:39:14 marka Exp $ -->
 <refentry id=3D"man.rndc">
   <refentryinfo>
     <date>June 30, 2000</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/rndc.html
--- a/head/contrib/bind9/bin/rndc/rndc.html	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/rndc.html	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: rndc.html,v 1.32 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -32,7 +32,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">rndc</code>  [<code =
class=3D"option">-b <em class=3D"replaceable"><code>source-address</code></=
em></code>] [<code class=3D"option">-c <em class=3D"replaceable"><code>conf=
ig-file</code></em></code>] [<code class=3D"option">-k <em class=3D"replace=
able"><code>key-file</code></em></code>] [<code class=3D"option">-s <em cla=
ss=3D"replaceable"><code>server</code></em></code>] [<code class=3D"option"=
>-p <em class=3D"replaceable"><code>port</code></em></code>] [<code class=
=3D"option">-V</code>] [<code class=3D"option">-y <em class=3D"replaceable"=
><code>key_id</code></em></code>] {command}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543413"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543415"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">rndc</strong></span>
       controls the operation of a name
       server.  It supersedes the <span><strong class=3D"command">ndc</stro=
ng></span> utility
@@ -61,7 +61,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543448"></a><h2>OPTIONS</h2>
+<a name=3D"id2543450"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-b <em class=3D"replaceable"><code>source-address=
</code></em></span></dt>
 <dd><p>
@@ -133,7 +133,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543656"></a><h2>LIMITATIONS</h2>
+<a name=3D"id2543658"></a><h2>LIMITATIONS</h2>
 <p><span><strong class=3D"command">rndc</strong></span>
       does not yet support all the commands of
       the BIND 8 <span><strong class=3D"command">ndc</strong></span> utili=
ty.
@@ -147,7 +147,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543683"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543685"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">rndc.conf</s=
pan>(5)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rndc-conf=
gen</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
@@ -157,7 +157,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543738"></a><h2>AUTHOR</h2>
+<a name=3D"id2543740"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/util.c
--- a/head/contrib/bind9/bin/rndc/util.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/util.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: util.c,v 1.7 2007-06-19 23:46:59 tbox Exp $ */
+/* $Id: util.c,v 1.7 2007/06/19 23:46:59 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/rndc/util.h
--- a/head/contrib/bind9/bin/rndc/util.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/rndc/util.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: util.h,v 1.12 2009-09-29 23:48:03 tbox Exp $ */
+/* $Id: util.h,v 1.12 2009/09/29 23:48:03 tbox Exp $ */
=20
 #ifndef RNDC_UTIL_H
 #define RNDC_UTIL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/Makefile.=
in
--- a/head/contrib/bind9/bin/tools/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/tools/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.13 2010-01-07 23:48:53 tbox Exp $
+# $Id: Makefile.in,v 1.13 2010/01/07 23:48:53 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/arpaname.1
--- a/head/contrib/bind9/bin/tools/arpaname.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/tools/arpaname.1	Tue Apr 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: arpaname.1,v 1.4 2010-05-19 01:14:14 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/arpaname.c
--- a/head/contrib/bind9/bin/tools/arpaname.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/tools/arpaname.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: arpaname.c,v 1.4 2009-10-27 03:05:33 marka Exp $ */
+/* $Id: arpaname.c,v 1.4 2009/10/27 03:05:33 marka Exp $ */
=20
 #include "config.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/arpaname.=
docbook
--- a/head/contrib/bind9/bin/tools/arpaname.docbook	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/tools/arpaname.docbook	Tue Apr 17 11:51:51 201=
2 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: arpaname.docbook,v 1.1 2009-03-04 01:30:27 marka Exp $ -->
+<!-- $Id: arpaname.docbook,v 1.1 2009/03/04 01:30:27 marka Exp $ -->
 <refentry id=3D"man.arpaname">
   <refentryinfo>
     <date>March 4, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/arpaname.=
html
--- a/head/contrib/bind9/bin/tools/arpaname.html	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/bin/tools/arpaname.html	Tue Apr 17 11:51:51 2012 +=
0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: arpaname.html,v 1.4 2010-05-19 01:14:14 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,20 +31,20 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">arpaname</code>  {<e=
m class=3D"replaceable"><code>ipaddress </code></em>...}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543345"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543347"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">arpaname</strong></span> translates =
IP addresses (IPv4 and
       IPv6) to the corresponding IN-ADDR.ARPA or IP6.ARPA names.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543357"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543360"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543371"></a><h2>AUTHOR</h2>
+<a name=3D"id2543373"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/genrandom=
.8
--- a/head/contrib/bind9/bin/tools/genrandom.8	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/tools/genrandom.8	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2009-2011 Internet Systems Consortium, Inc. ("ISC")
+.\" Copyright (C) 2009-2012 Internet Systems Consortium, Inc. ("ISC")
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
 .\" purpose with or without fee is hereby granted, provided that the above
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: genrandom.8,v 1.8.124.1 2011-08-09 01:52:58 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -65,5 +65,5 @@
 .PP
 Internet Systems Consortium
 .SH "COPYRIGHT"
-Copyright \(co 2009\-2011 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2009\-2012 Internet Systems Consortium, Inc. ("ISC")
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/genrandom=
.c
--- a/head/contrib/bind9/bin/tools/genrandom.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/tools/genrandom.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: genrandom.c,v 1.7 2010-05-17 23:51:04 tbox Exp $ */
+/* $Id: genrandom.c,v 1.7 2010/05/17 23:51:04 tbox Exp $ */
=20
 /*! \file */
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/genrandom=
.docbook
--- a/head/contrib/bind9/bin/tools/genrandom.docbook	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/tools/genrandom.docbook	Tue Apr 17 11:51:51 20=
12 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2009-2012  Internet Systems Consortium, Inc. ("ISC")
  -
  - Permission to use, copy, modify, and/or distribute this software for any
  - purpose with or without fee is hereby granted, provided that the above
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: genrandom.docbook,v 1.6.124.2 2011-08-08 23:45:44 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry id=3D"man.genrandom">
   <refentryinfo>
     <date>Feb 19, 2009</date>
@@ -39,6 +39,7 @@
       <year>2009</year>
       <year>2010</year>
       <year>2011</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
   </docinfo>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/genrandom=
.html
--- a/head/contrib/bind9/bin/tools/genrandom.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/bin/tools/genrandom.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2009-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2009-2012 Internet Systems Consortium, Inc. ("ISC")
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
  - purpose with or without fee is hereby granted, provided that the above
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: genrandom.html,v 1.8.124.1 2011-08-09 01:52:58 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">genrandom</code>  [<=
code class=3D"option">-n <em class=3D"replaceable"><code>number</code></em>=
</code>] {<em class=3D"replaceable"><code>size</code></em>} {<em class=3D"r=
eplaceable"><code>filename</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543366"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543370"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">genrandom</strong></span>
       generates a file or a set of files containing a specified quantity
@@ -40,7 +40,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543379"></a><h2>ARGUMENTS</h2>
+<a name=3D"id2543383"></a><h2>ARGUMENTS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-n <em class=3D"replaceable"><code>number</code><=
/em></span></dt>
 <dd><p>
@@ -58,14 +58,14 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543440"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543444"></a><h2>SEE ALSO</h2>
 <p>
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rand</spa=
n>(3)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">arc4rando=
m</span>(3)</span>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543466"></a><h2>AUTHOR</h2>
+<a name=3D"id2543470"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/isc-hmac-=
fixup.8
--- a/head/contrib/bind9/bin/tools/isc-hmac-fixup.8	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/tools/isc-hmac-fixup.8	Tue Apr 17 11:51:51 201=
2 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: isc-hmac-fixup.8,v 1.4 2010-05-19 01:14:14 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/isc-hmac-=
fixup.c
--- a/head/contrib/bind9/bin/tools/isc-hmac-fixup.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/bin/tools/isc-hmac-fixup.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: isc-hmac-fixup.c,v 1.4 2010-03-10 02:17:52 marka Exp $ */
+/* $Id: isc-hmac-fixup.c,v 1.4 2010/03/10 02:17:52 marka Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/isc-hmac-=
fixup.docbook
--- a/head/contrib/bind9/bin/tools/isc-hmac-fixup.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/bin/tools/isc-hmac-fixup.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: isc-hmac-fixup.docbook,v 1.2 2010-01-07 21:52:11 each Exp $ -->
+<!-- $Id: isc-hmac-fixup.docbook,v 1.2 2010/01/07 21:52:11 each Exp $ -->
 <refentry id=3D"man.isc-hmac-fixup">
   <refentryinfo>
     <date>January 5, 2010</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/isc-hmac-=
fixup.html
--- a/head/contrib/bind9/bin/tools/isc-hmac-fixup.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/bin/tools/isc-hmac-fixup.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: isc-hmac-fixup.html,v 1.4 2010-05-19 01:14:14 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">isc-hmac-fixup</code=
>  {<em class=3D"replaceable"><code>algorithm</code></em>} {<em class=3D"re=
placeable"><code>secret</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543351"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543352"></a><h2>DESCRIPTION</h2>
 <p>
       Versions of BIND 9 up to and including BIND 9.6 had a bug causing
       HMAC-SHA* TSIG keys which were longer than the digest length of the
@@ -57,7 +57,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543374"></a><h2>SECURITY CONSIDERATIONS</h2>
+<a name=3D"id2543376"></a><h2>SECURITY CONSIDERATIONS</h2>
 <p>
       Secrets that have been converted by <span><strong class=3D"command">=
isc-hmac-fixup</strong></span>
       are shortened, but as this is how the HMAC protocol works in
@@ -68,14 +68,14 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543388"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543389"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 2104</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543405"></a><h2>AUTHOR</h2>
+<a name=3D"id2543406"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/named-jou=
rnalprint.8
--- a/head/contrib/bind9/bin/tools/named-journalprint.8	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/bin/tools/named-journalprint.8	Tue Apr 17 11:51:51=
 2012 +0300
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: named-journalprint.8,v 1.4 2010-05-19 01:14:14 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/named-jou=
rnalprint.c
--- a/head/contrib/bind9/bin/tools/named-journalprint.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/bin/tools/named-journalprint.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: named-journalprint.c,v 1.2 2009-12-04 21:59:23 marka Exp $ */
+/* $Id: named-journalprint.c,v 1.2 2009/12/04 21:59:23 marka Exp $ */
=20
 /*! \file */
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/named-jou=
rnalprint.docbook
--- a/head/contrib/bind9/bin/tools/named-journalprint.docbook	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/bin/tools/named-journalprint.docbook	Tue Apr 17 11=
:51:51 2012 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: named-journalprint.docbook,v 1.2 2009-12-04 21:59:23 marka Exp $=
 -->
+<!-- $Id: named-journalprint.docbook,v 1.2 2009/12/04 21:59:23 marka Exp $=
 -->
 <refentry id=3D"man.named-journalprint">
   <refentryinfo>
     <date>Feb 18, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/named-jou=
rnalprint.html
--- a/head/contrib/bind9/bin/tools/named-journalprint.html	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/bin/tools/named-journalprint.html	Tue Apr 17 11:51=
:51 2012 +0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: named-journalprint.html,v 1.4 2010-05-19 01:14:14 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named-journalprint</=
code>  {<em class=3D"replaceable"><code>journal</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543342"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543344"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">named-journalprint</strong></span>
       prints the contents of a zone journal file in a human-readable
@@ -57,7 +57,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543378"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543379"></a><h2>SEE ALSO</h2>
 <p>
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">nsupdate<=
/span>(8)</span>,
@@ -65,7 +65,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543409"></a><h2>AUTHOR</h2>
+<a name=3D"id2543410"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/nsec3hash=
.8
--- a/head/contrib/bind9/bin/tools/nsec3hash.8	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/tools/nsec3hash.8	Tue Apr 17 11:51:51 2012 +03=
00
@@ -12,7 +12,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: nsec3hash.8,v 1.5 2010-05-19 01:14:14 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/nsec3hash=
.c
--- a/head/contrib/bind9/bin/tools/nsec3hash.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/bin/tools/nsec3hash.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006, 2008, 2009  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2006, 2008, 2009, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec3hash.c,v 1.6 2009-10-06 21:20:44 each Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
@@ -60,7 +60,8 @@
=20
 static void
 usage() {
-	fatal("salt hash iterations domain");
+	printf("Usage: %s salt algorithm iterations domain\n", program);
+	exit(1);
 }
=20
 int
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/nsec3hash=
.docbook
--- a/head/contrib/bind9/bin/tools/nsec3hash.docbook	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/bin/tools/nsec3hash.docbook	Tue Apr 17 11:51:51 20=
12 +0300
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: nsec3hash.docbook,v 1.3 2009-03-02 23:47:43 tbox Exp $ -->
+<!-- $Id: nsec3hash.docbook,v 1.3 2009/03/02 23:47:43 tbox Exp $ -->
 <refentry id=3D"man.nsec3hash">
   <refentryinfo>
     <date>Feb 18, 2009</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/bin/tools/nsec3hash=
.html
--- a/head/contrib/bind9/bin/tools/nsec3hash.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/bin/tools/nsec3hash.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -13,7 +13,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: nsec3hash.html,v 1.5 2010-05-19 01:14:14 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -31,7 +31,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">nsec3hash</code>  {<=
em class=3D"replaceable"><code>salt</code></em>} {<em class=3D"replaceable"=
><code>algorithm</code></em>} {<em class=3D"replaceable"><code>iterations</=
code></em>} {<em class=3D"replaceable"><code>domain</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543367"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543369"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">nsec3hash</strong></span> generates =
an NSEC3 hash based on
       a set of NSEC3 parameters.  This can be used to check the validity
@@ -39,7 +39,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543380"></a><h2>ARGUMENTS</h2>
+<a name=3D"id2543382"></a><h2>ARGUMENTS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">salt</span></dt>
 <dd><p>
@@ -63,14 +63,14 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543442"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543444"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 5155</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543459"></a><h2>AUTHOR</h2>
+<a name=3D"id2543461"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/config.h.in
--- a/head/contrib/bind9/config.h.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/config.h.in	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: config.h.in,v 1.143.8.4 2011-03-10 04:29:14 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -144,6 +144,9 @@
 /* Define if threads need PTHREAD_SCOPE_SYSTEM */
 #undef NEED_PTHREAD_SCOPE_SYSTEM
=20
+/* Define if building universal (internal helper macro) */
+#undef AC_APPLE_UNIVERSAL_BUILD
+
 /* Define to enable the "filter-aaaa-on-v4" option. */
 #undef ALLOW_FILTER_AAAA_ON_V4
=20
@@ -380,6 +383,9 @@
 /* Define to the one symbol short name of this package. */
 #undef PACKAGE_TARNAME
=20
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
 /* Define to the version of this package. */
 #undef PACKAGE_VERSION
=20
@@ -387,6 +393,9 @@
    (O_NDELAY/O_NONBLOCK). */
 #undef PORT_NONBLOCK
=20
+/* The size of `void *', as computed by sizeof. */
+#undef SIZEOF_VOID_P
+
 /* Define to 1 if you have the ANSI C header files. */
 #undef STDC_HEADERS
=20
@@ -400,9 +409,17 @@
 /* define if idnkit support is to be included. */
 #undef WITH_IDN
=20
-/* Define to 1 if your processor stores words with the most significant by=
te
-   first (like Motorola and SPARC, unlike Intel and VAX). */
-#undef WORDS_BIGENDIAN
+/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
+   significant byte first (like Motorola and SPARC, unlike Intel). */
+#if defined AC_APPLE_UNIVERSAL_BUILD
+# if defined __BIG_ENDIAN__
+#  define WORDS_BIGENDIAN 1
+# endif
+#else
+# ifndef WORDS_BIGENDIAN
+#  undef WORDS_BIGENDIAN
+# endif
+#endif
=20
 /* Define to empty if `const' does not conform to ANSI C. */
 #undef const
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/config.threads.in
--- a/head/contrib/bind9/config.threads.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/config.threads.in	Tue Apr 17 11:51:51 2012 +0300
@@ -33,8 +33,9 @@
 *-*-sysv*OpenUNIX*)
         # UnixWare
 	use_threads=3Dtrue ;;
-*-netbsd[1234].*)
-	# NetBSD earlier than NetBSD 5.0 has poor pthreads.  Don't use it by defa=
ult.
+[*-netbsd[1234].*])
+	# NetBSD earlier than NetBSD 5.0 has poor pthreads.
+	#  Don't use it by default.
 	use_threads=3Dfalse ;;
 *-netbsd*)
 	use_threads=3Dtrue ;;
@@ -44,7 +45,7 @@
 	use_threads=3Dfalse ;;
 *-freebsd*)
 	use_threads=3Dfalse ;;
-*-bsdi[234]*)
+[*-bsdi[234]*])
 	# Thread signals do not work reliably on some versions of BSD/OS.
 	use_threads=3Dfalse ;;
 *-bsdi5*)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/configure.in
--- a/head/contrib/bind9/configure.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/configure.in	Tue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
 esyscmd([sed "s/^/# /" COPYRIGHT])dnl
 AC_DIVERT_POP()dnl
=20
-AC_REVISION($Revision: 1.512.8.12 $)
+AC_REVISION($Revision: 1.512.8.15 $)
=20
 AC_INIT(lib/dns/name.c)
 AC_PREREQ(2.59)
@@ -62,6 +62,25 @@
 		;;
 esac
=20
+AC_ARG_ENABLE(developer, [  --enable-developer     enable developer build =
settings])
+case "$enable_developer" in
+yes)
+	test "${enable_fixed_rrset+set}" =3D set || enable_fixed_rrset=3Dyes
+	test "${with_atf+set}" =3D set || with_atf=3Dyes
+	test "${enable_filter_aaaa+set}" =3D set || enable_filter_aaaa=3Dyes
+	test "${enable_rpz_nsip+set}" =3D set || enable_rpz_nsip=3Dyes
+	test "${enable_rpz_nsdname+set}" =3D set || enable_rpz_nsdname=3Dyes
+	test "${with_dlz_filesystem+set}" =3D set || with_dlz_filesystem=3Dyes
+	case "$host" in
+	*-darwin*)
+		test "${enable_exportlib+set}" =3D set || enable_exportlib=3Dyes
+		;;
+	*-linux*)
+		test "${enable_exportlib+set}" =3D set || enable_exportlib=3Dyes
+		;;
+	esac
+	;;
+esac
 #
 # Make very sure that these are the first files processed by
 # config.status, since we use the processed output as the input for
@@ -263,7 +282,7 @@
 	# as it breaks how the two halves (Basic and Advanced) of the IPv6
 	# Socket API were designed to be used but we have to live with it.
 	# Define _GNU_SOURCE to pull in the IPv6 Advanced Socket API.
-	*-linux*)
+	*-linux* | *-kfreebsd*-gnu)
 		STD_CDEFINES=3D"$STD_CDEFINES -D_GNU_SOURCE"
 		CPPFLAGS=3D"$CPPFLAGS -D_GNU_SOURCE"
 		;;
@@ -502,7 +521,6 @@
 #
 AC_C_BIGENDIAN
=20
-
 #
 # was --with-openssl specified?
 #
@@ -1437,9 +1455,9 @@
 		O=3Dlo
 		A=3Dla
 		LIBTOOL_MKDEP_SED=3D's;\.o;\.lo;'
-		LIBTOOL_MODE_COMPILE=3D'--mode=3Dcompile'
-		LIBTOOL_MODE_INSTALL=3D'--mode=3Dinstall'
-		LIBTOOL_MODE_LINK=3D'--mode=3Dlink'
+		LIBTOOL_MODE_COMPILE=3D'--mode=3Dcompile --tag=3DCC'
+		LIBTOOL_MODE_INSTALL=3D'--mode=3Dinstall --tag=3DCC'
+		LIBTOOL_MODE_LINK=3D'--mode=3Dlink --tag=3DCC'
 		case "$host" in
 		*) LIBTOOL_ALLOW_UNDEFINED=3D ;;
 		esac
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/Makefile.in
--- a/head/contrib/bind9/doc/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.11 2007-06-19 23:47:13 tbox Exp $
+# $Id: Makefile.in,v 1.11 2007/06/19 23:47:13 tbox Exp $
=20
 # This Makefile is a placeholder.  It exists merely to make
 # sure that its directory gets created in the object directory
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM-book=
.xml
--- a/head/contrib/bind9/doc/arm/Bv9ARM-book.xml	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM-book.xml	Tue Apr 17 11:51:51 2012 +=
0300
@@ -2,7 +2,7 @@
               "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- File: $Id: Bv9ARM-book.xml,v 1.478.8.11 2011-08-02 04:58:46 each Exp =
$ -->
+<!-- File: $Id$ -->
 <book xmlns:xi=3D"http://www.w3.org/2001/XInclude">
   <title>BIND 9 Administrator Reference Manual</title>
=20
@@ -32,6 +32,7 @@
       <year>2009</year>
       <year>2010</year>
       <year>2011</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
@@ -1462,6 +1463,31 @@
                   </varlistentry>
=20
                   <varlistentry>
+                    <term><userinput>tsig-list</userinput></term>
+                    <listitem>
+                      <para>
+                        List the names of all TSIG keys currently configur=
ed
+                        for use by <command>named</command> in each view. =
 The
+                        list both statically configured keys and dynamic
+                        TKEY-negotiated keys.
+                      </para>
+                    </listitem>
+                  </varlistentry>
+
+                  <varlistentry>
+                    <term><userinput>tsig-delete</userinput>
+                     <replaceable>keyname</replaceable>
+                     <optional><replaceable>view</replaceable></optional><=
/term>
+                    <listitem>
+                      <para>
+                        Delete a given TKEY-negotated key from the server.
+                        (This does not apply to statically configured TSIG
+                        keys.)
+                      </para>
+                    </listitem>
+                  </varlistentry>
+
+                  <varlistentry>
                     <term><userinput>addzone
                         <replaceable>zone</replaceable>
                         <optional><replaceable>class</replaceable>
@@ -1898,11 +1924,13 @@
       </para>
=20
       <para>
-        When acting as a slave, <acronym>BIND</acronym> 9 will
-        attempt to use IXFR unless
-        it is explicitly disabled. For more information about disabling
-        IXFR, see the description of the <command>request-ixfr</command> c=
lause
-        of the <command>server</command> statement.
+        When acting as a slave, <acronym>BIND</acronym> 9 will attempt
+        to use IXFR unless it is explicitly disabled via the
+        <command>request-ixfr</command> option or the use of
+        <command>ixfr-from-differences</command>.  For
+        more information about disabling IXFR, see the description
+        of the <command>request-ixfr</command> clause of the
+        <command>server</command> statement.
       </para>
     </sect1>
=20
@@ -4645,6 +4673,19 @@
 		    </para>
 		  </entry>
 		</row>
+                <row rowsep=3D"0">
+                  <entry colname=3D"1">
+                    <para><command>RPZ</command></para>
+                  </entry>
+		  <entry colname=3D"2">
+		    <para>
+		      Information about errors in response policy zone files,
+		      rewritten responses, and at the highest
+		      <command>debug</command> levels, mere rewriting
+		      attempts.
+		    </para>
+		  </entry>
+		</row>
 	      </tbody>
 	    </tgroup>
 	  </informaltable>
@@ -4993,6 +5034,10 @@
     <optional> cache-file <replaceable>path_name</replaceable>; </optional>
     <optional> dump-file <replaceable>path_name</replaceable>; </optional>
     <optional> bindkeys-file <replaceable>path_name</replaceable>; </optio=
nal>
+    <optional> secroots-file <replaceable>path_name</replaceable>; </optio=
nal>
+    <optional> session-keyfile <replaceable>path_name</replaceable>; </opt=
ional>
+    <optional> session-keyname <replaceable>key_name</replaceable>; </opti=
onal>
+    <optional> session-keyalg <replaceable>algorithm_id</replaceable>; </o=
ptional>
     <optional> memstatistics <replaceable>yes_or_no</replaceable>; </optio=
nal>
     <optional> memstatistics-file <replaceable>path_name</replaceable>; </=
optional>
     <optional> pid-file <replaceable>path_name</replaceable>; </optional>
@@ -5018,7 +5063,8 @@
     <optional> ixfr-from-differences (<replaceable>yes_or_no</replaceable>=
 | <constant>master</constant> | <constant>slave</constant>); </optional>
     <optional> dnssec-enable <replaceable>yes_or_no</replaceable>; </optio=
nal>
     <optional> dnssec-validation (<replaceable>yes_or_no</replaceable> | <=
constant>auto</constant>); </optional>
-    <optional> dnssec-lookaside ( <replaceable>auto</replaceable> |=20
+    <optional> dnssec-lookaside ( <replaceable>auto</replaceable> |
+			<replaceable>no</replaceable> |
                         <replaceable>domain</replaceable> trust-anchor <re=
placeable>domain</replaceable> ); </optional>
     <optional> dnssec-must-be-secure <replaceable>domain yes_or_no</replac=
eable>; </optional>
     <optional> dnssec-accept-expired <replaceable>yes_or_no</replaceable>;=
 </optional>
@@ -5166,7 +5212,7 @@
     <optional> resolver-query-timeout <replaceable>number</replaceable> ; =
</optional>
     <optional> deny-answer-addresses { <replaceable>address_match_list</re=
placeable> } <optional> except-from { <replaceable>namelist</replaceable> }=
 </optional>;</optional>
     <optional> deny-answer-aliases { <replaceable>namelist</replaceable> }=
 <optional> except-from { <replaceable>namelist</replaceable> } </optional>=
;</optional>
-    <optional> response-policy { <replaceable>zone_name</replaceable> <opt=
ional> policy <replaceable>given</replaceable> | <replaceable>no-op</replac=
eable> | <replaceable>nxdomain</replaceable> | <replaceable>nodata</replace=
able> | <replaceable>cname domain</replaceable> </optional> ; } ; </optiona=
l>
+    <optional> response-policy { <replaceable>zone_name</replaceable> <opt=
ional> policy given | disabled | passthru | nxdomain | nodata | cname <repl=
aceable>domain</replaceable> </optional> ; } ; </optional>
 };
 </programlisting>
=20
@@ -5516,7 +5562,8 @@
                 The pathname of the file the server dumps
                 security roots to when instructed to do so with
                 <command>rndc secroots</command>.
-                If not specified, the default is <filename>named.secroots<=
/filename>.
+                If not specified, the default is
+		<filename>named.secroots</filename>.
               </para>
             </listitem>
           </varlistentry>
@@ -5561,19 +5608,6 @@
           </varlistentry>
=20
           <varlistentry>
-            <term><command>session-keyfile</command></term>
-            <listitem>
-              <para>
-                The pathname of the file into which to write a session TSIG
-                key for use by <command>nsupdate -l</command>.  (See the
-                discussion of the <command>update-policy</command>
-                statement's <userinput>local</userinput> option for more
-                details on this feature.)
-              </para>
-            </listitem>
-          </varlistentry>
-
-          <varlistentry>
             <term><command>port</command></term>
             <listitem>
               <para>
@@ -5708,6 +5742,11 @@
 		values for the DLV domain and trust anchor will be
 		used, along with a built-in key for validation.
 	      </para>
+	      <para>
+		If <command>dnssec-lookaside</command> is set to
+		<userinput>no</userinput>, then dnssec-lookaside
+		is not used.
+	      </para>
               <para>
                 The default DLV key is stored in the file
                 <filename>bind.keys</filename>;
@@ -8590,7 +8629,7 @@
 		<para>
 		  Specify a private RDATA type to be used when generating
 		  key signing records.  The default is
-		  <literal>65535</literal>.
+		  <literal>65534</literal>.
 		</para>
 		<para>
 		  It is expected that this parameter may be removed
@@ -8853,10 +8892,11 @@
 	    and which queries should not be sent to the Internet's root
 	    servers.  The official servers which cover these namespaces
 	    return NXDOMAIN responses to these queries.  In particular,
-	    these cover the reverse namespace for addresses from RFC 1918 and
-	    RFC 3330.  They also include the reverse namespace for IPv6 local
-	    address (locally assigned), IPv6 link local addresses, the IPv6
-	    loopback address and the IPv6 unknown address.
+            these cover the reverse namespaces for addresses from
+            RFC 1918, RFC 4193, and RFC 5737.  They also include the
+            reverse namespace for IPv6 local address (locally assigned),
+            IPv6 link local addresses, the IPv6 loopback address and the
+            IPv6 unknown address.
 	  </para>
 	  <para>
 	    Named will attempt to determine if a built-in zone already exists
@@ -9227,141 +9267,228 @@
 	  <title>Response Policy Zone (RPZ) Rewriting</title>
 	  <para>
 	    <acronym>BIND</acronym> 9 includes an intentionally limited
-            mechanism to modify DNS responses for recursive requests
-            similar to email anti-spam DNS blacklists.
-            All response policy zones are named in the
-            <command>response-policy</command> option for the view or amon=
g the
-            global options if there is no response-policy option for the v=
iew.
-          </para>
-
-          <para>
-            The rules encoded in a response policy zone (RPZ) are applied
-            only to responses to queries that ask for recursion (RD=3D1).
-            RPZs are normal DNS zones containing RRsets
-            that can be queried normally if allowed.
-            It is usually best to restrict those queries with something li=
ke
-            <command>allow-query {none; };</command> or
-            <command>allow-query { 127.0.0.1; };</command>.
-          </para>
-
-          <para>
-            There are four kinds of RPZ rewrite rules.  QNAME rules are
-            applied to query names in requests and to targets of CNAME
-            records resolved in the process of generating the response.
-            The owner name of a QNAME rule is the query name relativized
-            to the RPZ.
-	    The records in a rewrite rule are usually A, AAAA, or special
-	    CNAMEs, but can be any type except DNAME.
-          </para>
-
-          <para>
-            IP rules are triggered by addresses in A and AAAA records.
-            All IP addresses in A or AAAA RRsets are tested and the rule
-            longest prefix is applied.  Ties between rules with equal pref=
ixes
-            are broken in favor of the first RPZ mentioned in the
-            response-policy option.
-            The rule matching the smallest IP address is chosen among equal
-            prefix rules from a single RPZ.
-            IP rules are expressed in RRsets with owner names that are
-            subdomains of rpz-ip and encoding an IP address block, reversed
-            as in IN-ARPA.
-            prefix.B.B.B.B with prefix between 1 and 32 and B between 1 an=
d 255
-            encodes an IPv4 address.
-            IPv6 addresses are encoded by with prefix.W.W.W.W.W.W.W.W or
-            prefix.WORDS.zz.WORDS.  The words in the standard IPv6 text
-            representation are reversed, "::" is replaced with ".zz.",
-            and ":" becomes ".".
-          </para>
-
-          <para>
-            NSDNAME rules match names in NS RRsets for the response or a
-            parent.  They are encoded as subdomains of rpz-nsdomain relati=
vized
-            to the RPZ origin name.
-          </para>
-
-          <para>
-            NSIP rules match IP addresses in A and AAAA RRsets for names of
-            responsible servers or the names that can be matched by NSDNAME
-            rules.  The are encoded like IP rules except as subdomains of
-            rpz-nsip.
-	  </para>
-
-	  <para>
-            Authority verification issues and variations in authority data=
 in
-	    the current version of <acronym>BIND</acronym> 9 can cause
-	    inconsistent results from NSIP and NSDNAME.  So they are available
+	    mechanism to modify DNS responses for recursive requests
+	    somewhat similar to email anti-spam DNS blacklists.
+	    Responses can be changed to deny the existence of domains(NXDOMAIN),
+	    deny the existence of IP addresses for domains (NODATA),
+	    or contain other IP addresses or data.
+	  </para>
+
+	  <para>
+	    The actions encoded in a response policy zone (RPZ) are applied
+	    only to queries that ask for recursion (RD=3D1).
+	    Response policy zones are named in the
+	    <command>response-policy</command> option for the view or among the
+	    global options if there is no response-policy option for the view.
+	    RPZs are ordinary DNS zones containing RRsets
+	    that can be queried normally if allowed.
+	    It is usually best to restrict those queries with something like
+	    <command>allow-query { localhost; };</command>.
+	  </para>
+
+	  <para>
+	    There are four kinds of RPZ records, QNAME, IP, NSIP,
+	    and NSDNAME.
+	    QNAME records are applied to query names of requests and targets
+	    of CNAME records resolved to generate the response.
+	    The owner name of a QNAME RPZ record is the query name relativized
+	    to the RPZ.
+	  </para>
+
+	  <para>
+	    The second kind of RPZ record, an IP policy record,
+	    is triggered by addresses in A and AAAA records
+	    for the ANSWER sections of responses.
+	    IP policy records have owner names that are
+	    subdomains of <userinput>rpz-ip</userinput> relativized to the
+	    RPZ origin name and encode an IP address or address block.
+	    IPv4 addresses are encoded as
+	    <userinput>prefixlength.B4.B3.B2.B1.rpz-ip</userinput>.
+	    The prefix length must be between 1 and 32.
+	    All four bytes, B4, B3, B2, and B1, must be present.
+	    B4 is the decimal value of the least significant byte of the
+	    IPv4 address as in IN-ADDR.ARPA.
+	    IPv6 addresses are encoded in a format similar to the standard
+	    IPv6 text representation,
+	    <userinput>prefixlength.W8.W7.W6.W5.W4.W3.W2.W1.rpz-ip</userinput>.
+	    Each of W8,...,W1 is a one to four digit hexadecimal number
+	    representing 16 bits of the IPv6 address as in the standard text
+	    representation of IPv6 addresses, but reversed as in IN-ADDR.ARPA.
+	    All 8 words must be present except when consecutive
+	    zero words are replaced with <userinput>.zz.</userinput>
+	    analogous to double colons (::) in standard IPv6 text encodings.
+	    The prefix length must be between 1 and 128.
+	  </para>
+
+	  <para>
+	    NSDNAME policy records match names of authoritative servers
+	    for the query name, a parent of the query name, a CNAME,
+	    or a parent of a CNAME.
+	    They are encoded as subdomains of
+	    <userinput>rpz-nsdomain</userinput> relativized
+	    to the RPZ origin name.
+	  </para>
+
+	  <para>
+	    NSIP policy records match IP addresses in A and AAAA RRsets
+	    for domains that can be checked against NSDNAME policy records.
+	    The are encoded like IP policies except as subdomains of
+	    <userinput>rpz-nsip</userinput>.
+	  </para>
+
+	  <para>
+	    The query response is checked against all RPZs, so
+	    two or more policy records can apply to a single response.
+	    Because DNS responses can be rewritten according by at most a
+	    single policy record, a single policy (other than
+	    <command>DISABLED</command> policies) must be chosen.
+	    Policies are chosen in the following order:
+	    <itemizedlist>
+	      <listitem>Among applicable zones, use the RPZ that appears first
+		in the response-policy option.
+	      </listitem>
+	      <listitem>Prefer QNAME to IP to NSDNAME to NSIP policy records
+		in a single RPZ
+	      </listitem>
+	      <listitem>Among applicable NSDNAME policy records, prefer the
+		policy record that matches the lexically smallest name
+	      </listitem>
+	      <listitem>Among IP or NSIP policy records, prefer the record
+		with the longest prefix.
+	      </listitem>
+	      <listitem>Among records with the same prefex length,
+		prefer the IP or NSIP policy record that matches
+		the smallest IP address.
+	      </listitem>
+	    </itemizedlist>
+	  </para>
+
+	  <para>
+	    When the processing of a response is restarted to resolve
+	    DNAME or CNAME records and an applicable policy record set has
+	    not been found,
+	    all RPZs are again consulted for the DNAME or CNAME names
+	    and addresses.
+	  </para>
+
+	  <para>
+	    Authority verification issues and variations in authority data
+	    can cause inconsistent results for NSIP and NSDNAME policy records.
+	    Glue NS records often differ from authoritative NS records.
+	    So they are available
 	    only when <acronym>BIND</acronym> is built with the
 	    <userinput>--enable-rpz-nsip</userinput> or
 	    <userinput>--enable-rpz-nsdname</userinput> options
-            on the "configure" command line.
-          </para>
-
-          <para>
-            Four policies can be expressed.
-            The <command>NXDOMAIN</command> policy causes a NXDOMAIN respo=
nse
-            and is expressed with an RRset consisting of a single CNAME
-            whose target is the root domain (.).
-            <command>NODATA</command> generates NODATA or ANCOUNT=3D1 rega=
rdless
-            of query type.
-            It is expressed with a CNAME whose target is the wildcard
-            top-level domain (*.).
-            The <command>NO-OP</command> policy does not change the respon=
se
-            and is used to "poke holes" in policies for larger CIDR blocks=
 or in
-            zones named later in the <command>response-policy</command> op=
tion.
-            The NO-OP policy is expressed by a CNAME with a target consist=
ing
-            of the variable part of the owner name, such as "example.com."=
 for
-            a QNAME rule or "128.1.0.0.127." for an IP rule.
-            The <command>CNAME</command> policy is used to replace the RRs=
ets
-            of response.
-            A and AAAA RRsets are most common and useful to capture
-            an evil domain in a walled garden, but any valid set of RRsets
-            is possible.
-          </para>
-
-          <para>
-            All of the policies in an RPZ can be overridden with a
-            <command>policy</command> clause.
-            <command>given</command> says "do not override."
-            <command>no-op</command> says "do nothing" regardless of the p=
olicy
-            in RPZ records.
-            <command>nxdomain</command> causes all RPZ rules to generate
-            NXDOMAIN results.
-            <command>nodata</command> gives nodata.
-            <command>cname domain</command> causes all RPZ rules to act as=
 if
-            the consisted of a "cname domain" record.
-          </para>
-
-          <para>
-            For example, you might use this option statement
-          </para>
-<programlisting>response-policy { zone "bl"; };</programlisting>
+	    on the "configure" command line.
+	  </para>
+
+	  <para>
+	    RPZ record sets are special CNAME records or one or more
+	    of any types of DNS record except DNAME or DNSSEC.
+	    Except when a policy record is a CNAME, there can be more
+	    more than one record and more than one type
+	    in a set of policy records.
+	    Except for three kinds of CNAME records that are illegal except
+	    in policy zones, the records in a set are used in the response as if
+	    their owner name were the query name.  They are copied to the
+	    response as dictated by their types.
+	    <itemizedlist>
+	      <listitem>A CNAME whose target is the root domain (.)
+		specifies the <command>NXDOMAIN</command> policy,
+		which generates an NXDOMAIN response.
+	      </listitem>
+	      <listitem>A CNAME whose target is the wildcard top-level
+		domain (*.) specifies the <command>NODATA</command> policy,
+		which rewrites the response to NODATA or ANCOUNT=3D1.
+	      </listitem>
+	      <listitem>A CNAME whose target is a wildcard hostname such
+		as *.example.com is used normally after the astrisk (*)
+		has been replaced with the query name.
+		These records are usually resolved with ordinary CNAMEs
+		outside the policy zones.  They can be useful for logging.
+	      </listitem>
+	      <listitem>The <command>PASSTHRU</command> policy is specified
+		by a CNAME whose target is the variable part of its own
+		owner name.  It causes the response to not be rewritten
+		and is most often used to "poke holes" in policies for
+		CIDR blocks.
+	      </listitem>
+	    </itemizedlist>
+	  </para>
+
+	  <para>
+	    The policies specified in individual records
+	    in an RPZ can be overridden with a <command>policy</command> clause
+	    in the <command>response-policy</command> option.
+	    An organization using an RPZ provided by another organization might
+	    use this mechanism to redirect domains to its own walled garden.
+	    <itemizedlist>
+	      <listitem><command>GIVEN</command> says "do not override."
+	      </listitem>
+	      <listitem><command>DISABLED</command> causes policy records to do
+		nothing but log what they might have done.
+		The response to the DNS query will be written according to
+		any matching policy records that are not disabled.
+		Policy zones overridden with <command>DISABLED</command> should
+		appear first, because they will often not be logged
+		if a higher precedence policy is found first.
+	      </listitem>
+	      <listitem><command>PASSTHRU</command> causes all policy records
+		to act as if they were CNAME records with targets the variable
+		part of their owner name.  They protect the response from
+		being changed.
+	      </listitem>
+	      <listitem><command>NXDOMAIN</command> causes all RPZ records
+		to specify NXDOMAIN policies.
+	      </listitem>
+	      <listitem><command>NODATA</command> overrides with the
+		NODATA policy
+	      </listitem>
+	      <listitem><command>CNAME domain</command> causes all RPZ
+		policy records to act as if they were "cname domain" records.
+	      </listitem>
+	    </itemizedlist>
+	  </para>
+
+	  <para>
+	    For example, you might use this option statement
+          </para>
+<programlisting>    response-policy { zone "badlist"; };</programlisting>
           <para>
             and this zone statement
           </para>
-<programlisting>zone "bl" {type master; file "example/bl"; allow-query {no=
ne;}; };</programlisting>
+<programlisting>    zone "badlist" {type master; file "master/badlist"; al=
low-query {none;}; };</programlisting>
           <para>
             with this zone file
           </para>
 <programlisting>$TTL 1H
-@                   SOA LOCALHOST. named-mgr.example.com (1 1h 15m 30d 2h)
-
-; QNAME rules
-nxdomain.domain.com         CNAME   .
-nodata.domain.com           CNAME   *.
-bad.domain.com              A       10.0.0.1
-                            AAAA    2001:2::1
-ok.domain.com               CNAME   ok.domain.com.
-*.badzone.domain.com	    CNAME   garden.example.com.
-
-; IP rules rewriting all answers for 127/8 except 127.0.0.1
-8.0.0.0.127.ip              CNAME   .
-32.1.0.0.127.ip             CNAME   32.1.0.0.127.
-
-; NSDNAME and NSIP rules
+@                       SOA LOCALHOST. named-mgr.example.com (1 1h 15m 30d=
 2h)
+                        NS  LOCALHOST.
+
+; QNAME policy records.  There are no periods (.) after the owner names.
+nxdomain.domain.com     CNAME   .               ; NXDOMAIN policy
+nodata.domain.com       CNAME   *.              ; NODATA policy
+bad.domain.com          A       10.0.0.1        ; redirect to a walled gar=
den
+                        AAAA    2001:2::1
+
+; do not rewrite (PASSTHRU) OK.DOMAIN.COM
+ok.domain.com           CNAME   ok.domain.com.
+
+bzone.domain.com        CNAME   garden.example.com.
+
+; redirect x.bzone.domain.com to x.bzone.domain.com.garden.example.com
+*.bzone.domain.com      CNAME   *.garden.example.com.
+
+
+; IP policy records that rewrite all answers for 127/8 except 127.0.0.1
+8.0.0.0.127.rpz-ip      CNAME   .
+32.1.0.0.127.rpz-ip     CNAME   32.1.0.0.127.   ; PASSTHRU for 127.0.0.1
+
+; NSDNAME and NSIP policy records
 ns.domain.com.rpz-nsdname   CNAME   .
 48.zz.2.2001.rpz-nsip       CNAME   .
 </programlisting>
-	</sect3>
+        </sect3>
       </sect2>
=20
       <sect2 id=3D"server_statement_grammar">
@@ -14725,9 +14852,8 @@
 // RFC1918 space and some reserved space, which is
 // commonly used in spoofing attacks.
 acl bogusnets {
-        0.0.0.0/8; 1.0.0.0/8; 2.0.0.0/8; 192.0.2.0/24;
-        224.0.0.0/3; 10.0.0.0/8; 172.16.0.0/12;
-        192.168.0.0/16;
+        0.0.0.0/8;  192.0.2.0/24; 224.0.0.0/3;
+        10.0.0.0/8; 172.16.0.0/12; 192.168.0.0/16;
 };
=20
 // Set up an ACL called our-nets. Replace this with the
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch01=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch01.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch01.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch01.html,v 1.49.14.1 2011-06-22 02:37:19 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -45,17 +45,17 @@
 <div class=3D"toc">
 <p><b>Table of Contents</b></p>
 <dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564371">Scope of =
Document</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564394">Organizat=
ion of This Document</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564534">Conventio=
ns Used in This Document</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564715">The Domai=
n Name System (<acronym class=3D"acronym">DNS</acronym>)</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564375">Scope of =
Document</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564398">Organizat=
ion of This Document</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564538">Conventio=
ns Used in This Document</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564720">The Domai=
n Name System (<acronym class=3D"acronym">DNS</acronym>)</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564737">DNS Funda=
mentals</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564771">Domains a=
nd Domain Names</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567176">Zones</a>=
</span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567253">Authorita=
tive Name Servers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567426">Caching N=
ame Servers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567556">Name Serv=
ers in Multiple Roles</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564741">DNS Funda=
mentals</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564775">Domains a=
nd Domain Names</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567180">Zones</a>=
</span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567257">Authorita=
tive Name Servers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567430">Caching N=
ame Servers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567560">Name Serv=
ers in Multiple Roles</a></span></dt>
 </dl></dd>
 </dl>
 </div>
@@ -71,7 +71,7 @@
     </p>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2564371"></a>Scope of Document</h2></div></div></div>
+<a name=3D"id2564375"></a>Scope of Document</h2></div></div></div>
 <p>
         The Berkeley Internet Name Domain
         (<acronym class=3D"acronym">BIND</acronym>) implements a
@@ -87,7 +87,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2564394"></a>Organization of This Document</h2></div></div></=
div>
+<a name=3D"id2564398"></a>Organization of This Document</h2></div></div></=
div>
 <p>
         In this document, <span class=3D"emphasis"><em>Chapter 1</em></spa=
n> introduces
         the basic <acronym class=3D"acronym">DNS</acronym> and <acronym cl=
ass=3D"acronym">BIND</acronym> concepts. <span class=3D"emphasis"><em>Chapt=
er 2</em></span>
@@ -116,7 +116,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2564534"></a>Conventions Used in This Document</h2></div></di=
v></div>
+<a name=3D"id2564538"></a>Conventions Used in This Document</h2></div></di=
v></div>
 <p>
         In this document, we use the following general typographic
         conventions:
@@ -243,7 +243,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2564715"></a>The Domain Name System (<acronym class=3D"acrony=
m">DNS</acronym>)</h2></div></div></div>
+<a name=3D"id2564720"></a>The Domain Name System (<acronym class=3D"acrony=
m">DNS</acronym>)</h2></div></div></div>
 <p>
         The purpose of this document is to explain the installation
         and upkeep of the <acronym class=3D"acronym">BIND</acronym> (Berke=
ley Internet
@@ -253,7 +253,7 @@
       </p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2564737"></a>DNS Fundamentals</h3></div></div></div>
+<a name=3D"id2564741"></a>DNS Fundamentals</h3></div></div></div>
 <p>
           The Domain Name System (DNS) is a hierarchical, distributed
           database.  It stores information for mapping Internet host names=
 to
@@ -275,7 +275,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2564771"></a>Domains and Domain Names</h3></div></div></div>
+<a name=3D"id2564775"></a>Domains and Domain Names</h3></div></div></div>
 <p>
           The data stored in the DNS is identified by <span class=3D"empha=
sis"><em>domain names</em></span> that are organized as a tree according to
           organizational or administrative boundaries. Each node of the tr=
ee,
@@ -321,7 +321,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2567176"></a>Zones</h3></div></div></div>
+<a name=3D"id2567180"></a>Zones</h3></div></div></div>
 <p>
           To properly operate a name server, it is important to understand
           the difference between a <span class=3D"emphasis"><em>zone</em><=
/span>
@@ -374,7 +374,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2567253"></a>Authoritative Name Servers</h3></div></div></div>
+<a name=3D"id2567257"></a>Authoritative Name Servers</h3></div></div></div>
 <p>
           Each zone is served by at least
           one <span class=3D"emphasis"><em>authoritative name server</em><=
/span>,
@@ -391,7 +391,7 @@
         </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2567276"></a>The Primary Master</h4></div></div></div>
+<a name=3D"id2567281"></a>The Primary Master</h4></div></div></div>
 <p>
             The authoritative server where the master copy of the zone
             data is maintained is called the
@@ -411,7 +411,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2567374"></a>Slave Servers</h4></div></div></div>
+<a name=3D"id2567379"></a>Slave Servers</h4></div></div></div>
 <p>
             The other authoritative servers, the <span class=3D"emphasis">=
<em>slave</em></span>
             servers (also known as <span class=3D"emphasis"><em>secondary<=
/em></span> servers)
@@ -427,7 +427,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2567396"></a>Stealth Servers</h4></div></div></div>
+<a name=3D"id2567400"></a>Stealth Servers</h4></div></div></div>
 <p>
             Usually all of the zone's authoritative servers are listed in
             NS records in the parent zone.  These NS records constitute
@@ -462,7 +462,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2567426"></a>Caching Name Servers</h3></div></div></div>
+<a name=3D"id2567430"></a>Caching Name Servers</h3></div></div></div>
 <p>
           The resolver libraries provided by most operating systems are
           <span class=3D"emphasis"><em>stub resolvers</em></span>, meaning=
 that they are not
@@ -489,7 +489,7 @@
         </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2567529"></a>Forwarding</h4></div></div></div>
+<a name=3D"id2567533"></a>Forwarding</h4></div></div></div>
 <p>
             Even a caching name server does not necessarily perform
             the complete recursive lookup itself.  Instead, it can
@@ -516,7 +516,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2567556"></a>Name Servers in Multiple Roles</h3></div></div><=
/div>
+<a name=3D"id2567560"></a>Name Servers in Multiple Roles</h3></div></div><=
/div>
 <p>
           The <acronym class=3D"acronym">BIND</acronym> name server can
           simultaneously act as
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch02=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch02.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch02.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch02.html,v 1.43 2011-01-05 01:14:07 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -45,16 +45,16 @@
 <div class=3D"toc">
 <p><b>Table of Contents</b></p>
 <dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567590">Hardware =
requirements</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567617">CPU Requi=
rements</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567629">Memory Re=
quirements</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567724">Name Serv=
er Intensive Environment Issues</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567735">Supported=
 Operating Systems</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567594">Hardware =
requirements</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567621">CPU Requi=
rements</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567634">Memory Re=
quirements</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567729">Name Serv=
er Intensive Environment Issues</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567739">Supported=
 Operating Systems</a></span></dt>
 </dl>
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2567590"></a>Hardware requirements</h2></div></div></div>
+<a name=3D"id2567594"></a>Hardware requirements</h2></div></div></div>
 <p>
         <acronym class=3D"acronym">DNS</acronym> hardware requirements have
         traditionally been quite modest.
@@ -73,7 +73,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2567617"></a>CPU Requirements</h2></div></div></div>
+<a name=3D"id2567621"></a>CPU Requirements</h2></div></div></div>
 <p>
         CPU requirements for <acronym class=3D"acronym">BIND</acronym> 9 r=
ange from
         i486-class machines
@@ -84,7 +84,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2567629"></a>Memory Requirements</h2></div></div></div>
+<a name=3D"id2567634"></a>Memory Requirements</h2></div></div></div>
 <p>
         The memory of the server has to be large enough to fit the
         cache and zones loaded off disk.  The <span><strong class=3D"comma=
nd">max-cache-size</strong></span>
@@ -107,7 +107,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2567724"></a>Name Server Intensive Environment Issues</h2></d=
iv></div></div>
+<a name=3D"id2567729"></a>Name Server Intensive Environment Issues</h2></d=
iv></div></div>
 <p>
         For name server intensive environments, there are two alternative
         configurations that may be used. The first is where clients and
@@ -124,7 +124,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2567735"></a>Supported Operating Systems</h2></div></div></di=
v>
+<a name=3D"id2567739"></a>Supported Operating Systems</h2></div></div></di=
v>
 <p>
         ISC <acronym class=3D"acronym">BIND</acronym> 9 compiles and runs =
on a large
         number
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch03=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch03.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch03.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch03.html,v 1.83.8.1 2011-05-24 02:37:17 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -47,14 +47,14 @@
 <dl>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#sample_configuration=
">Sample Configurations</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567767">A Caching=
-only Name Server</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567988">An Author=
itative-only Name Server</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567771">A Caching=
-only Name Server</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567992">An Author=
itative-only Name Server</a></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568010">Load Bala=
ncing</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568364">Name Serv=
er Operations</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568014">Load Bala=
ncing</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568369">Name Serv=
er Operations</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2568370">Tools for=
 Use With the Name Server Daemon</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2570378">Signals</=
a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2568374">Tools for=
 Use With the Name Server Daemon</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2570421">Signals</=
a></span></dt>
 </dl></dd>
 </dl>
 </div>
@@ -68,7 +68,7 @@
 <a name=3D"sample_configuration"></a>Sample Configurations</h2></div></div=
></div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2567767"></a>A Caching-only Name Server</h3></div></div></div>
+<a name=3D"id2567771"></a>A Caching-only Name Server</h3></div></div></div>
 <p>
           The following sample configuration is appropriate for a caching-=
only
           name server for use by clients internal to a corporation.  All
@@ -98,7 +98,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2567988"></a>An Authoritative-only Name Server</h3></div></di=
v></div>
+<a name=3D"id2567992"></a>An Authoritative-only Name Server</h3></div></di=
v></div>
 <p>
           This sample configuration is for an authoritative-only server
           that is the master server for "<code class=3D"filename">example.=
com</code>"
@@ -146,7 +146,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2568010"></a>Load Balancing</h2></div></div></div>
+<a name=3D"id2568014"></a>Load Balancing</h2></div></div></div>
 <p>
         A primitive form of load balancing can be achieved in
         the <acronym class=3D"acronym">DNS</acronym> by using multiple rec=
ords
@@ -289,10 +289,10 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2568364"></a>Name Server Operations</h2></div></div></div>
+<a name=3D"id2568369"></a>Name Server Operations</h2></div></div></div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2568370"></a>Tools for Use With the Name Server Daemon</h3></=
div></div></div>
+<a name=3D"id2568374"></a>Tools for Use With the Name Server Daemon</h3></=
div></div></div>
 <p>
           This section describes several indispensable diagnostic,
           administrative and monitoring tools available to the system
@@ -670,6 +670,21 @@
                         set to <strong class=3D"userinput"><code>yes</code=
></strong> to be effective.
                         It defaults to enabled.
                       </p></dd>
+<dt><span class=3D"term"><strong class=3D"userinput"><code>tsig-list</code=
></strong></span></dt>
+<dd><p>
+                        List the names of all TSIG keys currently configur=
ed
+                        for use by <span><strong class=3D"command">named</=
strong></span> in each view.  The
+                        list both statically configured keys and dynamic
+                        TKEY-negotiated keys.
+                      </p></dd>
+<dt><span class=3D"term"><strong class=3D"userinput"><code>tsig-delete</co=
de></strong>
+                     <em class=3D"replaceable"><code>keyname</code></em>
+                     [<span class=3D"optional"><em class=3D"replaceable"><=
code>view</code></em></span>]</span></dt>
+<dd><p>
+                        Delete a given TKEY-negotated key from the server.
+                        (This does not apply to statically configured TSIG
+                        keys.)
+                      </p></dd>
 <dt><span class=3D"term"><strong class=3D"userinput"><code>addzone
                         <em class=3D"replaceable"><code>zone</code></em>
                         [<span class=3D"optional"><em class=3D"replaceable=
"><code>class</code></em>
@@ -873,7 +888,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2570378"></a>Signals</h3></div></div></div>
+<a name=3D"id2570421"></a>Signals</h3></div></div></div>
 <p>
           Certain UNIX signals cause the name server to take specific
           actions, as described in the following table.  These signals can
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch04=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch04.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch04.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch04.html,v 1.125.8.9 2011-08-03 02:35:12 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -49,59 +49,59 @@
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#dynamic_update">Dyna=
mic Update</a></span></dt>
 <dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#journal">The=
 journal file</a></span></dt></dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#incremental_zone_tra=
nsfers">Incremental Zone Transfers (IXFR)</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2570885">Split DNS=
</a></span></dt>
-<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2570903">E=
xample split DNS setup</a></span></dt></dl></dd>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2570934">Split DNS=
</a></span></dt>
+<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2570952">E=
xample split DNS setup</a></span></dt></dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#tsig">TSIG</a></span=
></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571336">Generate =
Shared Keys for Each Pair of Hosts</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571478">Copying t=
he Shared Secret to Both Machines</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571489">Informing=
 the Servers of the Key's Existence</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571525">Instructi=
ng the Server to Use the Key</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571651">TSIG Key =
Based Access Control</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571700">Errors</a=
></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2564012">Generate =
Shared Keys for Each Pair of Hosts</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2564086">Copying t=
he Shared Secret to Both Machines</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571811">Informing=
 the Servers of the Key's Existence</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571847">Instructi=
ng the Server to Use the Key</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571905">TSIG Key =
Based Access Control</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571954">Errors</a=
></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2571714">TKEY</a><=
/span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2563980">SIG(0)</a=
></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2571968">TKEY</a><=
/span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2572153">SIG(0)</a=
></span></dt>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#DNSSEC">DNSSEC</a></=
span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2564117">Generatin=
g Keys</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572183">Signing t=
he Zone</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572264">Configuri=
ng Servers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572221">Generatin=
g Keys</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572300">Signing t=
he Zone</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572381">Configuri=
ng Servers</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#dnssec.dynamic.zones=
">DNSSEC, Dynamic Zones, and Automatic Signing</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563484">Convertin=
g from insecure to secure</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563522">Dynamic D=
NS update method</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563626">Fully aut=
omatic zone signing</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563777">Private-t=
ype records</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563814">DNSKEY ro=
llovers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563827">Dynamic D=
NS update method</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563860">Automatic=
 key rollovers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563886">NSEC3PARA=
M rollovers via UPDATE</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563896">Convertin=
g from NSEC to NSEC3</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563906">Convertin=
g from NSEC3 to NSEC</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563918">Convertin=
g from secure to insecure</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563956">Periodic =
re-signing</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571816">NSEC3 and=
 OPTOUT</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571421">Convertin=
g from insecure to secure</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571459">Dynamic D=
NS update method</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563508">Fully aut=
omatic zone signing</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563590">Private-t=
ype records</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563696">DNSKEY ro=
llovers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563708">Dynamic D=
NS update method</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563741">Automatic=
 key rollovers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563836">NSEC3PARA=
M rollovers via UPDATE</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563846">Convertin=
g from NSEC to NSEC3</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563856">Convertin=
g from NSEC3 to NSEC</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563868">Convertin=
g from secure to insecure</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563906">Periodic =
re-signing</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563915">NSEC3 and=
 OPTOUT</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#rfc5011.support">Dyn=
amic Trust Anchor Management</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571869">Validatin=
g Resolver</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571892">Authorita=
tive Server</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571685">Validatin=
g Resolver</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571707">Authorita=
tive Server</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#pkcs11">PKCS #11 (Cr=
yptoki) support</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2609757">Prerequis=
ites</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2607912">Building =
BIND 9 with PKCS#11</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2608144">PKCS #11 =
Tools</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2608174">Using the=
 HSM</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610353">Specifyin=
g the engine on the command line</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610467">Running n=
amed with automatic zone re-signing</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2609970">Prerequis=
ites</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2608219">Building =
BIND 9 with PKCS#11</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610529">PKCS #11 =
Tools</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610560">Using the=
 HSM</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2635129">Specifyin=
g the engine on the command line</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2635243">Running n=
amed with automatic zone re-signing</a></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2572484">IPv6 Supp=
ort in <acronym class=3D"acronym">BIND</acronym> 9</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2572669">IPv6 Supp=
ort in <acronym class=3D"acronym">BIND</acronym> 9</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572819">Address L=
ookups Using AAAA Records</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572840">Address t=
o Name Lookups Using Nibble Format</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572868">Address L=
ookups Using AAAA Records</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572889">Address t=
o Name Lookups Using Nibble Format</a></span></dt>
 </dl></dd>
 </dl>
 </div>
@@ -247,16 +247,18 @@
         to <strong class=3D"userinput"><code>yes</code></strong>.
       </p>
 <p>
-        When acting as a slave, <acronym class=3D"acronym">BIND</acronym> =
9 will
-        attempt to use IXFR unless
-        it is explicitly disabled. For more information about disabling
-        IXFR, see the description of the <span><strong class=3D"command">r=
equest-ixfr</strong></span> clause
-        of the <span><strong class=3D"command">server</strong></span> stat=
ement.
+        When acting as a slave, <acronym class=3D"acronym">BIND</acronym> =
9 will attempt
+        to use IXFR unless it is explicitly disabled via the
+        <span><strong class=3D"command">request-ixfr</strong></span> optio=
n or the use of
+        <span><strong class=3D"command">ixfr-from-differences</strong></sp=
an>.  For
+        more information about disabling IXFR, see the description
+        of the <span><strong class=3D"command">request-ixfr</strong></span=
> clause of the
+        <span><strong class=3D"command">server</strong></span> statement.
       </p>
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2570885"></a>Split DNS</h2></div></div></div>
+<a name=3D"id2570934"></a>Split DNS</h2></div></div></div>
 <p>
         Setting up different views, or visibility, of the DNS space to
         internal and external resolvers is usually referred to as a
@@ -286,7 +288,7 @@
       </p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2570903"></a>Example split DNS setup</h3></div></div></div>
+<a name=3D"id2570952"></a>Example split DNS setup</h3></div></div></div>
 <p>
         Let's say a company named <span class=3D"emphasis"><em>Example, In=
c.</em></span>
         (<code class=3D"literal">example.com</code>)
@@ -543,7 +545,7 @@
       </p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571336"></a>Generate Shared Keys for Each Pair of Hosts</h3>=
</div></div></div>
+<a name=3D"id2564012"></a>Generate Shared Keys for Each Pair of Hosts</h3>=
</div></div></div>
 <p>
           A shared secret is generated to be shared between <span class=3D=
"emphasis"><em>host1</em></span> and <span class=3D"emphasis"><em>host2</em=
></span>.
           An arbitrary key name is chosen: "host1-host2.". The key name mu=
st
@@ -551,7 +553,7 @@
         </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2571353"></a>Automatic Generation</h4></div></div></div>
+<a name=3D"id2564029"></a>Automatic Generation</h4></div></div></div>
 <p>
             The following command will generate a 128-bit (16 byte) HMAC-S=
HA256
             key as described above. Longer keys are better, but shorter ke=
ys
@@ -575,7 +577,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2571392"></a>Manual Generation</h4></div></div></div>
+<a name=3D"id2564068"></a>Manual Generation</h4></div></div></div>
 <p>
             The shared secret is simply a random sequence of bits, encoded
             in base-64. Most ASCII strings are valid base-64 strings (assu=
ming
@@ -590,7 +592,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571478"></a>Copying the Shared Secret to Both Machines</h3><=
/div></div></div>
+<a name=3D"id2564086"></a>Copying the Shared Secret to Both Machines</h3><=
/div></div></div>
 <p>
           This is beyond the scope of DNS. A secure transport mechanism
           should be used. This could be secure FTP, ssh, telephone, etc.
@@ -598,7 +600,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571489"></a>Informing the Servers of the Key's Existence</h3=
></div></div></div>
+<a name=3D"id2571811"></a>Informing the Servers of the Key's Existence</h3=
></div></div></div>
 <p>
           Imagine <span class=3D"emphasis"><em>host1</em></span> and <span=
 class=3D"emphasis"><em>host 2</em></span>
           are
@@ -625,7 +627,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571525"></a>Instructing the Server to Use the Key</h3></div>=
</div></div>
+<a name=3D"id2571847"></a>Instructing the Server to Use the Key</h3></div>=
</div></div>
 <p>
           Since keys are shared between two hosts only, the server must
           be told when keys are to be used. The following is added to the =
<code class=3D"filename">named.conf</code> file
@@ -657,7 +659,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571651"></a>TSIG Key Based Access Control</h3></div></div></=
div>
+<a name=3D"id2571905"></a>TSIG Key Based Access Control</h3></div></div></=
div>
 <p>
           <acronym class=3D"acronym">BIND</acronym> allows IP addresses an=
d ranges
           to be specified in ACL
@@ -684,7 +686,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571700"></a>Errors</h3></div></div></div>
+<a name=3D"id2571954"></a>Errors</h3></div></div></div>
 <p>
           The processing of TSIG signed messages can result in
           several errors. If a signed message is sent to a non-TSIG aware
@@ -710,7 +712,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2571714"></a>TKEY</h2></div></div></div>
+<a name=3D"id2571968"></a>TKEY</h2></div></div></div>
 <p><span><strong class=3D"command">TKEY</strong></span>
         is a mechanism for automatically generating a shared secret
         between two hosts.  There are several "modes" of
@@ -746,7 +748,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2563980"></a>SIG(0)</h2></div></div></div>
+<a name=3D"id2572153"></a>SIG(0)</h2></div></div></div>
 <p>
         <acronym class=3D"acronym">BIND</acronym> 9 partially supports DNS=
SEC SIG(0)
             transaction signatures as specified in RFC 2535 and RFC 2931.
@@ -807,7 +809,7 @@
       </p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2564117"></a>Generating Keys</h3></div></div></div>
+<a name=3D"id2572221"></a>Generating Keys</h3></div></div></div>
 <p>
           The <span><strong class=3D"command">dnssec-keygen</strong></span=
> program is used to
           generate keys.
@@ -863,7 +865,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2572183"></a>Signing the Zone</h3></div></div></div>
+<a name=3D"id2572300"></a>Signing the Zone</h3></div></div></div>
 <p>
           The <span><strong class=3D"command">dnssec-signzone</strong></sp=
an> program is used
           to sign a zone.
@@ -905,7 +907,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2572264"></a>Configuring Servers</h3></div></div></div>
+<a name=3D"id2572381"></a>Configuring Servers</h3></div></div></div>
 <p>
           To enable <span><strong class=3D"command">named</strong></span> =
to respond appropriately
           to DNS requests from DNSSEC aware clients,
@@ -1065,7 +1067,7 @@
   from insecure to signed and back again. A secure zone can use
   either NSEC or NSEC3 chains.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563484"></a>Converting from insecure to secure</h3></div></d=
iv></div></div>
+<a name=3D"id2571421"></a>Converting from insecure to secure</h3></div></d=
iv></div></div>
 <p>Changing a zone from insecure to secure can be done in two
   ways: using a dynamic DNS update, or the=20
   <span><strong class=3D"command">auto-dnssec</strong></span> zone option.=
</p>
@@ -1091,7 +1093,7 @@
   well. An NSEC chain will be generated as part of the initial
   signing process.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563522"></a>Dynamic DNS update method</h3></div></div></div>=
</div>
+<a name=3D"id2571459"></a>Dynamic DNS update method</h3></div></div></div>=
</div>
 <p>To insert the keys via dynamic update:</p>
 <pre class=3D"screen">
         % nsupdate
@@ -1127,7 +1129,7 @@
 <p>While the initial signing and NSEC/NSEC3 chain generation
   is happening, other updates are possible as well.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563626"></a>Fully automatic zone signing</h3></div></div></d=
iv></div>
+<a name=3D"id2563508"></a>Fully automatic zone signing</h3></div></div></d=
iv></div>
 <p>To enable automatic signing, add the=20
   <span><strong class=3D"command">auto-dnssec</strong></span> option to th=
e zone statement in=20
   <code class=3D"filename">named.conf</code>.=20
@@ -1162,7 +1164,7 @@
   configuration. If this has not been done, the configuration will
   fail.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563777"></a>Private-type records</h3></div></div></div></div>
+<a name=3D"id2563590"></a>Private-type records</h3></div></div></div></div>
 <p>The state of the signing process is signaled by
   private-type records (with a default type value of 65534). When
   signing is complete, these records will have a nonzero value for
@@ -1203,12 +1205,12 @@
 <p>
   </p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563814"></a>DNSKEY rollovers</h3></div></div></div></div>
+<a name=3D"id2563696"></a>DNSKEY rollovers</h3></div></div></div></div>
 <p>As with insecure-to-secure conversions, rolling DNSSEC
   keys can be done in two ways: using a dynamic DNS update, or the=20
   <span><strong class=3D"command">auto-dnssec</strong></span> zone option.=
</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563827"></a>Dynamic DNS update method</h3></div></div></div>=
</div>
+<a name=3D"id2563708"></a>Dynamic DNS update method</h3></div></div></div>=
</div>
 <p> To perform key rollovers via dynamic update, you need to add
   the <code class=3D"filename">K*</code> files for the new keys so that=20
   <span><strong class=3D"command">named</strong></span> can find them. You=
 can then add the new
@@ -1230,7 +1232,7 @@
   <span><strong class=3D"command">named</strong></span> will clean out any=
 signatures generated
   by the old key after the update completes.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563860"></a>Automatic key rollovers</h3></div></div></div></=
div>
+<a name=3D"id2563741"></a>Automatic key rollovers</h3></div></div></div></=
div>
 <p>When a new key reaches its activation date (as set by
   <span><strong class=3D"command">dnssec-keygen</strong></span> or <span><=
strong class=3D"command">dnssec-settime</strong></span>),
   if the <span><strong class=3D"command">auto-dnssec</strong></span> zone =
option is set to=20
@@ -1245,27 +1247,27 @@
   completes in 30 days, after which it will be safe to remove the
   old key from the DNSKEY RRset.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563886"></a>NSEC3PARAM rollovers via UPDATE</h3></div></div>=
</div></div>
+<a name=3D"id2563836"></a>NSEC3PARAM rollovers via UPDATE</h3></div></div>=
</div></div>
 <p>Add the new NSEC3PARAM record via dynamic update. When the
   new NSEC3 chain has been generated, the NSEC3PARAM flag field
   will be zero. At this point you can remove the old NSEC3PARAM
   record. The old chain will be removed after the update request
   completes.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563896"></a>Converting from NSEC to NSEC3</h3></div></div></=
div></div>
+<a name=3D"id2563846"></a>Converting from NSEC to NSEC3</h3></div></div></=
div></div>
 <p>To do this, you just need to add an NSEC3PARAM record. When
   the conversion is complete, the NSEC chain will have been removed
   and the NSEC3PARAM record will have a zero flag field. The NSEC3
   chain will be generated before the NSEC chain is
   destroyed.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563906"></a>Converting from NSEC3 to NSEC</h3></div></div></=
div></div>
+<a name=3D"id2563856"></a>Converting from NSEC3 to NSEC</h3></div></div></=
div></div>
 <p>To do this, use <span><strong class=3D"command">nsupdate</strong></span=
> to
   remove all NSEC3PARAM records with a zero flag
   field. The NSEC chain will be generated before the NSEC3 chain is
   removed.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563918"></a>Converting from secure to insecure</h3></div></d=
iv></div></div>
+<a name=3D"id2563868"></a>Converting from secure to insecure</h3></div></d=
iv></div></div>
 <p>To convert a signed zone to unsigned using dynamic DNS,
   delete all the DNSKEY records from the zone apex using
   <span><strong class=3D"command">nsupdate</strong></span>. All signatures=
, NSEC or NSEC3 chains,
@@ -1280,14 +1282,14 @@
   <span><strong class=3D"command">allow</strong></span> instead (or it wil=
l re-sign).
   </p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2563956"></a>Periodic re-signing</h3></div></div></div></div>
+<a name=3D"id2563906"></a>Periodic re-signing</h3></div></div></div></div>
 <p>In any secure zone which supports dynamic updates, named
   will periodically re-sign RRsets which have not been re-signed as
   a result of some update action. The signature lifetimes will be
   adjusted so as to spread the re-sign load over time rather than
   all at once.</p>
 <div class=3D"sect2" lang=3D"en"><div class=3D"titlepage"><div><div><h3 cl=
ass=3D"title">
-<a name=3D"id2571816"></a>NSEC3 and OPTOUT</h3></div></div></div></div>
+<a name=3D"id2563915"></a>NSEC3 and OPTOUT</h3></div></div></div></div>
 <p>
   <span><strong class=3D"command">named</strong></span> only supports crea=
ting new NSEC3 chains
   where all the NSEC3 records in the zone have the same OPTOUT
@@ -1309,7 +1311,7 @@
   configuration files.</p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571869"></a>Validating Resolver</h3></div></div></div>
+<a name=3D"id2571685"></a>Validating Resolver</h3></div></div></div>
 <p>To configure a validating resolver to use RFC 5011 to
     maintain a trust anchor, configure the trust anchor using a=20
     <span><strong class=3D"command">managed-keys</strong></span> statement=
. Information about
@@ -1320,7 +1322,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2571892"></a>Authoritative Server</h3></div></div></div>
+<a name=3D"id2571707"></a>Authoritative Server</h3></div></div></div>
 <p>To set up an authoritative zone for RFC 5011 trust anchor
     maintenance, generate two (or more) key signing keys (KSKs) for
     the zone. Sign the zone with one of them; this is the "active"
@@ -1394,7 +1396,7 @@
   Debian Linux, Solaris x86 and Windows Server 2003.</p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2609757"></a>Prerequisites</h3></div></div></div>
+<a name=3D"id2609970"></a>Prerequisites</h3></div></div></div>
 <p>See the HSM vendor documentation for information about
     installing, initializing, testing and troubleshooting the
     HSM.</p>
@@ -1429,13 +1431,16 @@
         other computationally-intensive operations. The AEP Keyper
         is an example of such a device.</p></li>
 </ul></div>
-<p>The modified OpenSSL code is included in the BIND 9.7.0
-    release, in the form of a context diff against the latest OpenSSL.
+<p>The modified OpenSSL code is included in the BIND 9 release,
+        in the form of a context diff against the latest verions of
+        OpenSSL.  OpenSSL 0.9.8 and 1.0.0 are both supported; there are
+        separate diffs for each version.  In the examples to follow,
+        we use OpenSSL 0.9.8, but the same methods work with OpenSSL 1.0.0.
     </p>
 <div class=3D"note" style=3D"margin-left: 0.5in; margin-right: 0.5in;">
 <h3 class=3D"title">Note</h3>
-      The latest OpenSSL version at the time of the BIND release
-      is 0.9.8l.
+      The latest OpenSSL versions at the time of the BIND release
+      are 0.9.8s and 1.0.0f.
       ISC will provide an updated patch as new versions of OpenSSL
       are released. The version number in the following examples
       is expected to change.</div>
@@ -1444,18 +1449,18 @@
     necessary to build OpenSSL with this patch in place and inform
     it of the path to the HSM-specific PKCS #11 provider
     library.</p>
-<p>Obtain OpenSSL 0.9.8l:</p>
+<p>Obtain OpenSSL 0.9.8s:</p>
 <pre class=3D"screen">
-$ <strong class=3D"userinput"><code>wget <a href=3D"" target=3D"_top">http=
://www.openssl.org/source/openssl-0.9.8l.tar.gz</a></code></strong>
+$ <strong class=3D"userinput"><code>wget <a href=3D"" target=3D"_top">http=
://www.openssl.org/source/openssl-0.9.8s.tar.gz</a></code></strong>
 </pre>
 <p>Extract the tarball:</p>
 <pre class=3D"screen">
-$ <strong class=3D"userinput"><code>tar zxf openssl-0.9.8l.tar.gz</code></=
strong>
+$ <strong class=3D"userinput"><code>tar zxf openssl-0.9.8s.tar.gz</code></=
strong>
 </pre>
 <p>Apply the patch from the BIND 9 release:</p>
 <pre class=3D"screen">
-$ <strong class=3D"userinput"><code>patch -p1 -d openssl-0.9.8l \
-            < bind-9.7.0/bin/pkcs11/openssl-0.9.8l-patch</code></strong>
+$ <strong class=3D"userinput"><code>patch -p1 -d openssl-0.9.8s \
+            < bind9/bin/pkcs11/openssl-0.9.8s-patch</code></strong>
 </pre>
 <div class=3D"note" style=3D"margin-left: 0.5in; margin-right: 0.5in;">
 <h3 class=3D"title">Note</h3>(Note that the patch file may not be compatib=
le with the
@@ -1468,7 +1473,7 @@
     when we configure BIND 9.</p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2607669"></a>Building OpenSSL for the AEP Keyper on Linux</h4=
></div></div></div>
+<a name=3D"id2607881"></a>Building OpenSSL for the AEP Keyper on Linux</h4=
></div></div></div>
 <p>The AEP Keyper is a highly secure key storage device,
       but does not provide hardware cryptographic acceleration. It
       can carry out cryptographic operations, but it is probably
@@ -1487,7 +1492,7 @@
 <p>Finally, the Keyper library requires threads, so we
       must specify -pthread.</p>
 <pre class=3D"screen">
-$ <strong class=3D"userinput"><code>cd openssl-0.9.8l</code></strong>
+$ <strong class=3D"userinput"><code>cd openssl-0.9.8s</code></strong>
 $ <strong class=3D"userinput"><code>./Configure linux-generic32 -m32 -pthr=
ead \
             --pk11-libname=3D/opt/pkcs11/usr/lib/libpkcs11.so \
             --pk11-flavor=3Dsign-only \
@@ -1500,7 +1505,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2607806"></a>Building OpenSSL for the SCA 6000 on Solaris</h4=
></div></div></div>
+<a name=3D"id2608019"></a>Building OpenSSL for the SCA 6000 on Solaris</h4=
></div></div></div>
 <p>The SCA-6000 PKCS #11 provider is installed as a system
       library, libpkcs11. It is a true crypto accelerator, up to 4
       times faster than any CPU, so the flavor shall be
@@ -1508,7 +1513,7 @@
 <p>In this example, we are building on Solaris x86 on an
       AMD64 system.</p>
 <pre class=3D"screen">
-$ <strong class=3D"userinput"><code>cd openssl-0.9.8l</code></strong>
+$ <strong class=3D"userinput"><code>cd openssl-0.9.8s</code></strong>
 $ <strong class=3D"userinput"><code>./Configure solaris64-x86_64-cc \
             --pk11-libname=3D/usr/lib/64/libpkcs11.so \
             --pk11-flavor=3Dcrypto-accelerator \
@@ -1519,11 +1524,50 @@
 <p>After configuring, run=20
       <span><strong class=3D"command">make</strong></span> and=20
       <span><strong class=3D"command">make test</strong></span>.</p>
+</div>
+<div class=3D"sect3" lang=3D"en">
+<div class=3D"titlepage"><div><div><h4 class=3D"title">
+<a name=3D"id2608068"></a>Building OpenSSL for SoftHSM</h4></div></div></d=
iv>
+<p>SoftHSM is a software library provided by the OpenDNSSEC
+      project (http://www.opendnssec.org) which provides a PKCS#11
+      interface to a virtual HSM, implemented in the form of encrypted
+      data on the local filesystem.  It uses the Botan library for
+      encryption and SQLite3 for data storage.  Though less secure
+      than a true HSM, it can provide more secure key storage than
+      traditional key files, and can allow you to experiment with
+      PKCS#11 when an HSM is not available.</p>
+<p>The SoftHSM cryptographic store must be installed and
+      initialized before using it with OpenSSL, and the SOFTHSM_CONF
+      environment variable must always point to the SoftHSM configuration
+      file:</p>
+<pre class=3D"screen">
+$ <strong class=3D"userinput"><code> cd softhsm-1.3.0 </code></strong>
+$ <strong class=3D"userinput"><code> configure --prefix=3D/opt/pkcs11/usr =
</code></strong>
+$ <strong class=3D"userinput"><code> make </code></strong>
+$ <strong class=3D"userinput"><code> make install </code></strong>
+$ <strong class=3D"userinput"><code> export SOFTHSM_CONF=3D/opt/pkcs11/sof=
thsm.conf </code></strong>
+$ <strong class=3D"userinput"><code> echo "0:/opt/pkcs11/softhsm.db" > =
$SOFTHSM_CONF </code></strong>
+$ <strong class=3D"userinput"><code> /opt/pkcs11/usr/bin/softhsm --init-to=
ken 0 --slot 0 --label softhsm </code></strong>
+</pre>
+<p>SoftHSM can perform all cryptographic operations, but
+      since it only uses your system CPU, there is no need to use it
+      for anything but signing.  Therefore, we choose the 'sign-only'
+      flavor when building OpenSSL.</p>
+<pre class=3D"screen">
+$ <strong class=3D"userinput"><code>cd openssl-0.9.8s</code></strong>
+$ <strong class=3D"userinput"><code>./Configure linux-x86_64 -pthread \
+            --pk11-libname=3D/opt/pkcs11/usr/lib/libpkcs11.so \
+            --pk11-flavor=3Dsign-only \
+            --prefix=3D/opt/pkcs11/usr</code></strong>
+</pre>
+<p>After configuring, run "<span><strong class=3D"command">make</strong></=
span>"
+      and "<span><strong class=3D"command">make test</strong></span>".</p>
+</div>
 <p>Once you have built OpenSSL, run
-      "<span><strong class=3D"command">apps/openssl engine pkcs11</strong>=
</span>" to confirm
-      that PKCS #11 support was compiled in correctly. The output
-      should be one of the following lines, depending on the flavor
-      selected:</p>
+    "<span><strong class=3D"command">apps/openssl engine pkcs11</strong></=
span>" to confirm
+    that PKCS #11 support was compiled in correctly. The output
+    should be one of the following lines, depending on the flavor
+    selected:</p>
 <pre class=3D"screen">
         (pkcs11) PKCS #11 engine support (sign only)
 </pre>
@@ -1532,24 +1576,23 @@
         (pkcs11) PKCS #11 engine support (crypto accelerator)
 </pre>
 <p>Next, run
-      "<span><strong class=3D"command">apps/openssl engine pkcs11 -t</stro=
ng></span>". This will
-      attempt to initialize the PKCS #11 engine. If it is able to
-      do so successfully, it will report
-      “<span class=3D"quote"><code class=3D"literal">[ available ]</=
code></span>”.</p>
+    "<span><strong class=3D"command">apps/openssl engine pkcs11 -t</strong=
></span>". This will
+    attempt to initialize the PKCS #11 engine. If it is able to
+    do so successfully, it will report
+    “<span class=3D"quote"><code class=3D"literal">[ available ]</co=
de></span>”.</p>
 <p>If the output is correct, run
-      "<span><strong class=3D"command">make install</strong></span>" which=
 will install the
-      modified OpenSSL suite to=20
-      <code class=3D"filename">/opt/pkcs11/usr</code>.</p>
-</div>
+    "<span><strong class=3D"command">make install</strong></span>" which w=
ill install the
+    modified OpenSSL suite to=20
+    <code class=3D"filename">/opt/pkcs11/usr</code>.</p>
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2607912"></a>Building BIND 9 with PKCS#11</h3></div></div></d=
iv>
+<a name=3D"id2608219"></a>Building BIND 9 with PKCS#11</h3></div></div></d=
iv>
 <p>When building BIND 9, the location of the custom-built
     OpenSSL library must be specified via configure.</p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2607921"></a>Configuring BIND 9 for Linux</h4></div></div></d=
iv>
+<a name=3D"id2608228"></a>Configuring BIND 9 for Linux with the AEP Keyper=
</h4></div></div></div>
 <p>To link with the PKCS #11 provider, threads must be
       enabled in the BIND 9 build.</p>
 <p>The PKCS #11 library for the AEP Keyper is currently
@@ -1557,7 +1600,7 @@
       64-bit host, we must force a 32-bit build by adding "-m32" to
       the CC options on the "configure" command line.</p>
 <pre class=3D"screen">
-$ <strong class=3D"userinput"><code>cd ../bind-9.7.0</code></strong>
+$ <strong class=3D"userinput"><code>cd ../bind9</code></strong>
 $ <strong class=3D"userinput"><code>./configure CC=3D"gcc -m32" --enable-t=
hreads \
            --with-openssl=3D/opt/pkcs11/usr \
            --with-pkcs11=3D/opt/pkcs11/usr/lib/libpkcs11.so</code></strong>
@@ -1565,11 +1608,11 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2608020"></a>Configuring BIND 9 for Solaris</h4></div></div><=
/div>
+<a name=3D"id2608260"></a>Configuring BIND 9 for Solaris with the SCA 6000=
</h4></div></div></div>
 <p>To link with the PKCS #11 provider, threads must be
       enabled in the BIND 9 build.</p>
 <pre class=3D"screen">
-$ <strong class=3D"userinput"><code>cd ../bind-9.7.0</code></strong>
+$ <strong class=3D"userinput"><code>cd ../bind9</code></strong>
 $ <strong class=3D"userinput"><code>./configure CC=3D"cc -xarch=3Damd64" -=
-enable-threads \
             --with-openssl=3D/opt/pkcs11/usr \
             --with-pkcs11=3D/usr/lib/64/libpkcs11.so</code></strong>
@@ -1581,14 +1624,26 @@
       same as the --prefix argument to the OpenSSL
       Configure).</p>
 </div>
+<div class=3D"sect3" lang=3D"en">
+<div class=3D"titlepage"><div><div><h4 class=3D"title">
+<a name=3D"id2610481"></a>Configuring BIND 9 for SoftHSM</h4></div></div><=
/div>
+<pre class=3D"screen">
+$ <strong class=3D"userinput"><code>cd ../bind9</code></strong>
+$ <strong class=3D"userinput"><code>./configure --enable-threads \
+           --with-openssl=3D/opt/pkcs11/usr \
+           --with-pkcs11=3D/opt/pkcs11/usr/lib/libpkcs11.so</code></strong>
+</pre>
+</div>
 <p>After configuring, run
     "<span><strong class=3D"command">make</strong></span>",
     "<span><strong class=3D"command">make test</strong></span>" and
     "<span><strong class=3D"command">make install</strong></span>".</p>
+<p>(Note: If "make test" fails in the "pkcs11" system test, you may
+    have forgotten to set the SOFTHSM_CONF environment variable.)</p>
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608144"></a>PKCS #11 Tools</h3></div></div></div>
+<a name=3D"id2610529"></a>PKCS #11 Tools</h3></div></div></div>
 <p>BIND 9 includes a minimal set of tools to operate the
     HSM, including=20
     <span><strong class=3D"command">pkcs11-keygen</strong></span> to gener=
ate a new key pair
@@ -1606,7 +1661,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608174"></a>Using the HSM</h3></div></div></div>
+<a name=3D"id2610560"></a>Using the HSM</h3></div></div></div>
 <p>First, we must set up the runtime environment so the
     OpenSSL and PKCS #11 libraries can be loaded:</p>
 <pre class=3D"screen">
@@ -1694,7 +1749,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2610353"></a>Specifying the engine on the command line</h3></=
div></div></div>
+<a name=3D"id2635129"></a>Specifying the engine on the command line</h3></=
div></div></div>
 <p>The OpenSSL engine can be specified in=20
     <span><strong class=3D"command">named</strong></span> and all of the B=
IND=20
     <span><strong class=3D"command">dnssec-*</strong></span> tools by usin=
g the "-E
@@ -1715,7 +1770,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2610467"></a>Running named with automatic zone re-signing</h3=
></div></div></div>
+<a name=3D"id2635243"></a>Running named with automatic zone re-signing</h3=
></div></div></div>
 <p>If you want=20
     <span><strong class=3D"command">named</strong></span> to dynamically r=
e-sign zones using HSM
     keys, and/or to to sign new records inserted via nsupdate, then
@@ -1751,7 +1806,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2572484"></a>IPv6 Support in <acronym class=3D"acronym">BIND<=
/acronym> 9</h2></div></div></div>
+<a name=3D"id2572669"></a>IPv6 Support in <acronym class=3D"acronym">BIND<=
/acronym> 9</h2></div></div></div>
 <p>
         <acronym class=3D"acronym">BIND</acronym> 9 fully supports all cur=
rently
         defined forms of IPv6 name to address and address to name
@@ -1789,7 +1844,7 @@
       </p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2572819"></a>Address Lookups Using AAAA Records</h3></div></d=
iv></div>
+<a name=3D"id2572868"></a>Address Lookups Using AAAA Records</h3></div></d=
iv></div>
 <p>
           The IPv6 AAAA record is a parallel to the IPv4 A record,
           and, unlike the deprecated A6 record, specifies the entire
@@ -1808,7 +1863,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2572840"></a>Address to Name Lookups Using Nibble Format</h3>=
</div></div></div>
+<a name=3D"id2572889"></a>Address to Name Lookups Using Nibble Format</h3>=
</div></div></div>
 <p>
           When looking up an address in nibble format, the address
           components are simply reversed, just as in IPv4, and
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch05=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch05.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch05.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch05.html,v 1.93.14.1 2011-05-24 02:37:16 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -45,13 +45,13 @@
 <div class=3D"toc">
 <p><b>Table of Contents</b></p>
 <dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch05.html#id2572873">The Light=
weight Resolver Library</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch05.html#id2572922">The Light=
weight Resolver Library</a></span></dt>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch05.html#lwresd">Running a Re=
solver Daemon</a></span></dt>
 </dl>
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2572873"></a>The Lightweight Resolver Library</h2></div></div=
></div>
+<a name=3D"id2572922"></a>The Lightweight Resolver Library</h2></div></div=
></div>
 <p>
         Traditionally applications have been linked with a stub resolver
         library that sends recursive DNS queries to a local caching name
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch06=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch06.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch06.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch06.html,v 1.275.8.10 2011-08-03 02:35:13 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -48,58 +48,58 @@
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#configuration_file_e=
lements">Configuration File Elements</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#address_match_lists"=
>Address Match Lists</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574283">Comment S=
yntax</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574332">Comment S=
yntax</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#Configuration_File_G=
rammar">Configuration File Grammar</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574937"><span><st=
rong class=3D"command">acl</strong></span> Statement Grammar</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574986"><span><st=
rong class=3D"command">acl</strong></span> Statement Grammar</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#acl"><span><strong c=
lass=3D"command">acl</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575127"><span><st=
rong class=3D"command">controls</strong></span> Statement Grammar</a></span=
></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575176"><span><st=
rong class=3D"command">controls</strong></span> Statement Grammar</a></span=
></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#controls_statement_d=
efinition_and_usage"><span><strong class=3D"command">controls</strong></spa=
n> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575418"><span><st=
rong class=3D"command">include</strong></span> Statement Grammar</a></span>=
</dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575504"><span><st=
rong class=3D"command">include</strong></span> Statement Definition and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575467"><span><st=
rong class=3D"command">include</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575484"><span><st=
rong class=3D"command">include</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575527"><span><st=
rong class=3D"command">key</strong></span> Statement Grammar</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575550"><span><st=
rong class=3D"command">key</strong></span> Statement Definition and Usage</=
a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575709"><span><st=
rong class=3D"command">logging</strong></span> Statement Grammar</a></span>=
</dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575835"><span><st=
rong class=3D"command">logging</strong></span> Statement Definition and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575576"><span><st=
rong class=3D"command">key</strong></span> Statement Grammar</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575600"><span><st=
rong class=3D"command">key</strong></span> Statement Definition and Usage</=
a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575758"><span><st=
rong class=3D"command">logging</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575884"><span><st=
rong class=3D"command">logging</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577834"><span><st=
rong class=3D"command">lwres</strong></span> Statement Grammar</a></span></=
dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577908"><span><st=
rong class=3D"command">lwres</strong></span> Statement Definition and Usage=
</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578040"><span><st=
rong class=3D"command">masters</strong></span> Statement Grammar</a></span>=
</dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578084"><span><st=
rong class=3D"command">masters</strong></span> Statement Definition and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577910"><span><st=
rong class=3D"command">lwres</strong></span> Statement Grammar</a></span></=
dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577984"><span><st=
rong class=3D"command">lwres</strong></span> Statement Definition and Usage=
</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578116"><span><st=
rong class=3D"command">masters</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578160"><span><st=
rong class=3D"command">masters</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578099"><span><st=
rong class=3D"command">options</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578174"><span><st=
rong class=3D"command">options</strong></span> Statement Grammar</a></span>=
</dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#options"><span><stro=
ng class=3D"command">options</strong></span> Statement Definition and
           Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#server_statement_gra=
mmar"><span><strong class=3D"command">server</strong></span> Statement Gram=
mar</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#server_statement_def=
inition_and_usage"><span><strong class=3D"command">server</strong></span> S=
tatement Definition and
             Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#statschannels"><span=
><strong class=3D"command">statistics-channels</strong></span> Statement Gr=
ammar</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589395"><span><st=
rong class=3D"command">statistics-channels</strong></span> Statement Defini=
tion and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589481"><span><st=
rong class=3D"command">statistics-channels</strong></span> Statement Defini=
tion and
             Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#trusted-keys"><span>=
<strong class=3D"command">trusted-keys</strong></span> Statement Grammar</a=
></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589534"><span><st=
rong class=3D"command">trusted-keys</strong></span> Statement Definition
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589689"><span><st=
rong class=3D"command">trusted-keys</strong></span> Statement Definition
             and Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589581"><span><st=
rong class=3D"command">managed-keys</strong></span> Statement Grammar</a></=
span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589736"><span><st=
rong class=3D"command">managed-keys</strong></span> Statement Grammar</a></=
span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#managed-keys"><span>=
<strong class=3D"command">managed-keys</strong></span> Statement Definition
             and Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#view_statement_gramm=
ar"><span><strong class=3D"command">view</strong></span> Statement Grammar<=
/a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2590007"><span><st=
rong class=3D"command">view</strong></span> Statement Definition and Usage<=
/a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2590162"><span><st=
rong class=3D"command">view</strong></span> Statement Definition and Usage<=
/a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#zone_statement_gramm=
ar"><span><strong class=3D"command">zone</strong></span>
             Statement Grammar</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2591558"><span><st=
rong class=3D"command">zone</strong></span> Statement Definition and Usage<=
/a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2591713"><span><st=
rong class=3D"command">zone</strong></span> Statement Definition and Usage<=
/a></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#id2595030">Zone File=
</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#id2595116">Zone File=
</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#types_of_resource_re=
cords_and_when_to_use_them">Types of Resource Records and When to Use Them<=
/a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597260">Discussio=
n of MX Records</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597415">Discussio=
n of MX Records</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#Setting_TTLs">Settin=
g TTLs</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597876">Inverse M=
apping in IPv4</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598003">Other Zon=
e File Directives</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598276"><acronym =
class=3D"acronym">BIND</acronym> Master File Extension: the  <span><strong =
class=3D"command">$GENERATE</strong></span> Directive</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597962">Inverse M=
apping in IPv4</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598157">Other Zon=
e File Directives</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598430"><acronym =
class=3D"acronym">BIND</acronym> Master File Extension: the  <span><strong =
class=3D"command">$GENERATE</strong></span> Directive</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#zonefile_format">Add=
itional File Formats</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#statistics">BIND9 St=
atistics</a></span></dt>
@@ -477,7 +477,7 @@
 <a name=3D"address_match_lists"></a>Address Match Lists</h3></div></div></=
div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2574050"></a>Syntax</h4></div></div></div>
+<a name=3D"id2574099"></a>Syntax</h4></div></div></div>
 <pre class=3D"programlisting"><code class=3D"varname">address_match_list</=
code> =3D address_match_list_element ;
   [<span class=3D"optional"> address_match_list_element; ... </span>]
 <code class=3D"varname">address_match_list_element</code> =3D [<span class=
=3D"optional"> ! </span>] (ip_address [<span class=3D"optional">/length</sp=
an>] |
@@ -486,7 +486,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2574077"></a>Definition and Usage</h4></div></div></div>
+<a name=3D"id2574126"></a>Definition and Usage</h4></div></div></div>
 <p>
             Address match lists are primarily used to determine access
             control for various server operations. They are also used in
@@ -570,7 +570,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2574283"></a>Comment Syntax</h3></div></div></div>
+<a name=3D"id2574332"></a>Comment Syntax</h3></div></div></div>
 <p>
           The <acronym class=3D"acronym">BIND</acronym> 9 comment syntax a=
llows for
           comments to appear
@@ -580,7 +580,7 @@
         </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2574298"></a>Syntax</h4></div></div></div>
+<a name=3D"id2574347"></a>Syntax</h4></div></div></div>
 <p>
             </p>
 <pre class=3D"programlisting">/* This is a <acronym class=3D"acronym">BIND=
</acronym> comment as in C */</pre>
@@ -596,7 +596,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2574328"></a>Definition and Usage</h4></div></div></div>
+<a name=3D"id2574377"></a>Definition and Usage</h4></div></div></div>
 <p>
             Comments may appear anywhere that whitespace may appear in
             a <acronym class=3D"acronym">BIND</acronym> configuration file.
@@ -848,7 +848,7 @@
       </p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2574937"></a><span><strong class=3D"command">acl</strong></sp=
an> Statement Grammar</h3></div></div></div>
+<a name=3D"id2574986"></a><span><strong class=3D"command">acl</strong></sp=
an> Statement Grammar</h3></div></div></div>
 <pre class=3D"programlisting"><span><strong class=3D"command">acl</strong>=
</span> acl-name {
     address_match_list
 };
@@ -930,7 +930,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2575127"></a><span><strong class=3D"command">controls</strong=
></span> Statement Grammar</h3></div></div></div>
+<a name=3D"id2575176"></a><span><strong class=3D"command">controls</strong=
></span> Statement Grammar</h3></div></div></div>
 <pre class=3D"programlisting"><span><strong class=3D"command">controls</st=
rong></span> {
    [ inet ( ip_addr | * ) [ port ip_port ]
                 allow { <em class=3D"replaceable"><code> address_match_lis=
t </code></em> }
@@ -1054,12 +1054,12 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2575418"></a><span><strong class=3D"command">include</strong>=
</span> Statement Grammar</h3></div></div></div>
+<a name=3D"id2575467"></a><span><strong class=3D"command">include</strong>=
</span> Statement Grammar</h3></div></div></div>
 <pre class=3D"programlisting"><span><strong class=3D"command">include</str=
ong></span> <em class=3D"replaceable"><code>filename</code></em>;</pre>
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2575504"></a><span><strong class=3D"command">include</strong>=
</span> Statement Definition and
+<a name=3D"id2575484"></a><span><strong class=3D"command">include</strong>=
</span> Statement Definition and
           Usage</h3></div></div></div>
 <p>
           The <span><strong class=3D"command">include</strong></span> stat=
ement inserts the
@@ -1074,7 +1074,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2575527"></a><span><strong class=3D"command">key</strong></sp=
an> Statement Grammar</h3></div></div></div>
+<a name=3D"id2575576"></a><span><strong class=3D"command">key</strong></sp=
an> Statement Grammar</h3></div></div></div>
 <pre class=3D"programlisting"><span><strong class=3D"command">key</strong>=
</span> <em class=3D"replaceable"><code>key_id</code></em> {
     algorithm <em class=3D"replaceable"><code>string</code></em>;
     secret <em class=3D"replaceable"><code>string</code></em>;
@@ -1083,7 +1083,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2575550"></a><span><strong class=3D"command">key</strong></sp=
an> Statement Definition and Usage</h3></div></div></div>
+<a name=3D"id2575600"></a><span><strong class=3D"command">key</strong></sp=
an> Statement Definition and Usage</h3></div></div></div>
 <p>
           The <span><strong class=3D"command">key</strong></span> statemen=
t defines a shared
           secret key for use with TSIG (see <a href=3D"Bv9ARM.ch04.html#ts=
ig" title=3D"TSIG">the section called “TSIG”</a>)
@@ -1130,7 +1130,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2575709"></a><span><strong class=3D"command">logging</strong>=
</span> Statement Grammar</h3></div></div></div>
+<a name=3D"id2575758"></a><span><strong class=3D"command">logging</strong>=
</span> Statement Grammar</h3></div></div></div>
 <pre class=3D"programlisting"><span><strong class=3D"command">logging</str=
ong></span> {
    [ <span><strong class=3D"command">channel</strong></span> <em class=3D"=
replaceable"><code>channel_name</code></em> {
      ( <span><strong class=3D"command">file</strong></span> <em class=3D"r=
eplaceable"><code>path_name</code></em>
@@ -1154,7 +1154,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2575835"></a><span><strong class=3D"command">logging</strong>=
</span> Statement Definition and
+<a name=3D"id2575884"></a><span><strong class=3D"command">logging</strong>=
</span> Statement Definition and
           Usage</h3></div></div></div>
 <p>
           The <span><strong class=3D"command">logging</strong></span> stat=
ement configures a
@@ -1188,7 +1188,7 @@
         </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2575888"></a>The <span><strong class=3D"command">channel</str=
ong></span> Phrase</h4></div></div></div>
+<a name=3D"id2576005"></a>The <span><strong class=3D"command">channel</str=
ong></span> Phrase</h4></div></div></div>
 <p>
             All log output goes to one or more <span class=3D"emphasis"><e=
m>channels</em></span>;
             you can make as many of them as you want.
@@ -1748,12 +1748,25 @@
                     </p>
                   </td>
 </tr>
+<tr>
+<td>
+                    <p><span><strong class=3D"command">RPZ</strong></span>=
</p>
+                  </td>
+<td>
+                    <p>
+                      Information about errors in response policy zone fil=
es,
+                      rewritten responses, and at the highest
+                      <span><strong class=3D"command">debug</strong></span=
> levels, mere rewriting
+                      attempts.
+                    </p>
+                  </td>
+</tr>
 </tbody>
 </table></div>
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2577315"></a>The <span><strong class=3D"command">query-errors=
</strong></span> Category</h4></div></div></div>
+<a name=3D"id2577322"></a>The <span><strong class=3D"command">query-errors=
</strong></span> Category</h4></div></div></div>
 <p>
             The <span><strong class=3D"command">query-errors</strong></spa=
n> category is
             specifically intended for debugging purposes: To identify
@@ -1981,7 +1994,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2577834"></a><span><strong class=3D"command">lwres</strong></=
span> Statement Grammar</h3></div></div></div>
+<a name=3D"id2577910"></a><span><strong class=3D"command">lwres</strong></=
span> Statement Grammar</h3></div></div></div>
 <p>
            This is the grammar of the <span><strong class=3D"command">lwre=
s</strong></span>
           statement in the <code class=3D"filename">named.conf</code> file:
@@ -1997,7 +2010,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2577908"></a><span><strong class=3D"command">lwres</strong></=
span> Statement Definition and Usage</h3></div></div></div>
+<a name=3D"id2577984"></a><span><strong class=3D"command">lwres</strong></=
span> Statement Definition and Usage</h3></div></div></div>
 <p>
           The <span><strong class=3D"command">lwres</strong></span> statem=
ent configures the
           name
@@ -2048,7 +2061,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2578040"></a><span><strong class=3D"command">masters</strong>=
</span> Statement Grammar</h3></div></div></div>
+<a name=3D"id2578116"></a><span><strong class=3D"command">masters</strong>=
</span> Statement Grammar</h3></div></div></div>
 <pre class=3D"programlisting">
 <span><strong class=3D"command">masters</strong></span> <em class=3D"repla=
ceable"><code>name</code></em> [<span class=3D"optional">port <em class=3D"=
replaceable"><code>ip_port</code></em></span>] { ( <em class=3D"replaceable=
"><code>masters_list</code></em> |=20
       <em class=3D"replaceable"><code>ip_addr</code></em> [<span class=3D"=
optional">port <em class=3D"replaceable"><code>ip_port</code></em></span>] =
[<span class=3D"optional">key <em class=3D"replaceable"><code>key</code></e=
m></span>] ) ; [<span class=3D"optional">...</span>] };
@@ -2056,7 +2069,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2578084"></a><span><strong class=3D"command">masters</strong>=
</span> Statement Definition and
+<a name=3D"id2578160"></a><span><strong class=3D"command">masters</strong>=
</span> Statement Definition and
           Usage</h3></div></div></div>
 <p><span><strong class=3D"command">masters</strong></span>
           lists allow for a common set of masters to be easily used by
@@ -2065,7 +2078,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2578099"></a><span><strong class=3D"command">options</strong>=
</span> Statement Grammar</h3></div></div></div>
+<a name=3D"id2578174"></a><span><strong class=3D"command">options</strong>=
</span> Statement Grammar</h3></div></div></div>
 <p>
           This is the grammar of the <span><strong class=3D"command">optio=
ns</strong></span>
           statement in the <code class=3D"filename">named.conf</code> file:
@@ -2086,6 +2099,10 @@
     [<span class=3D"optional"> cache-file <em class=3D"replaceable"><code>=
path_name</code></em>; </span>]
     [<span class=3D"optional"> dump-file <em class=3D"replaceable"><code>p=
ath_name</code></em>; </span>]
     [<span class=3D"optional"> bindkeys-file <em class=3D"replaceable"><co=
de>path_name</code></em>; </span>]
+    [<span class=3D"optional"> secroots-file <em class=3D"replaceable"><co=
de>path_name</code></em>; </span>]
+    [<span class=3D"optional"> session-keyfile <em class=3D"replaceable"><=
code>path_name</code></em>; </span>]
+    [<span class=3D"optional"> session-keyname <em class=3D"replaceable"><=
code>key_name</code></em>; </span>]
+    [<span class=3D"optional"> session-keyalg <em class=3D"replaceable"><c=
ode>algorithm_id</code></em>; </span>]
     [<span class=3D"optional"> memstatistics <em class=3D"replaceable"><co=
de>yes_or_no</code></em>; </span>]
     [<span class=3D"optional"> memstatistics-file <em class=3D"replaceable=
"><code>path_name</code></em>; </span>]
     [<span class=3D"optional"> pid-file <em class=3D"replaceable"><code>pa=
th_name</code></em>; </span>]
@@ -2111,7 +2128,8 @@
     [<span class=3D"optional"> ixfr-from-differences (<em class=3D"replace=
able"><code>yes_or_no</code></em> | <code class=3D"constant">master</code> =
| <code class=3D"constant">slave</code>); </span>]
     [<span class=3D"optional"> dnssec-enable <em class=3D"replaceable"><co=
de>yes_or_no</code></em>; </span>]
     [<span class=3D"optional"> dnssec-validation (<em class=3D"replaceable=
"><code>yes_or_no</code></em> | <code class=3D"constant">auto</code>); </sp=
an>]
-    [<span class=3D"optional"> dnssec-lookaside ( <em class=3D"replaceable=
"><code>auto</code></em> |=20
+    [<span class=3D"optional"> dnssec-lookaside ( <em class=3D"replaceable=
"><code>auto</code></em> |
+                        <em class=3D"replaceable"><code>no</code></em> |
                         <em class=3D"replaceable"><code>domain</code></em>=
 trust-anchor <em class=3D"replaceable"><code>domain</code></em> ); </span>]
     [<span class=3D"optional"> dnssec-must-be-secure <em class=3D"replacea=
ble"><code>domain yes_or_no</code></em>; </span>]
     [<span class=3D"optional"> dnssec-accept-expired <em class=3D"replacea=
ble"><code>yes_or_no</code></em>; </span>]
@@ -2259,7 +2277,7 @@
     [<span class=3D"optional"> resolver-query-timeout <em class=3D"replace=
able"><code>number</code></em> ; </span>]
     [<span class=3D"optional"> deny-answer-addresses { <em class=3D"replac=
eable"><code>address_match_list</code></em> } [<span class=3D"optional"> ex=
cept-from { <em class=3D"replaceable"><code>namelist</code></em> } </span>]=
;</span>]
     [<span class=3D"optional"> deny-answer-aliases { <em class=3D"replacea=
ble"><code>namelist</code></em> } [<span class=3D"optional"> except-from { =
<em class=3D"replaceable"><code>namelist</code></em> } </span>];</span>]
-    [<span class=3D"optional"> response-policy { <em class=3D"replaceable"=
><code>zone_name</code></em> [<span class=3D"optional"> policy <em class=3D=
"replaceable"><code>given</code></em> | <em class=3D"replaceable"><code>no-=
op</code></em> | <em class=3D"replaceable"><code>nxdomain</code></em> | <em=
 class=3D"replaceable"><code>nodata</code></em> | <em class=3D"replaceable"=
><code>cname domain</code></em> </span>] ; } ; </span>]
+    [<span class=3D"optional"> response-policy { <em class=3D"replaceable"=
><code>zone_name</code></em> [<span class=3D"optional"> policy given | disa=
bled | passthru | nxdomain | nodata | cname <em class=3D"replaceable"><code=
>domain</code></em> </span>] ; } ; </span>]
 };
 </pre>
 </div>
@@ -2517,7 +2535,8 @@
                 The pathname of the file the server dumps
                 security roots to when instructed to do so with
                 <span><strong class=3D"command">rndc secroots</strong></sp=
an>.
-                If not specified, the default is <code class=3D"filename">=
named.secroots</code>.
+                If not specified, the default is
+                <code class=3D"filename">named.secroots</code>.
               </p></dd>
 <dt><span class=3D"term"><span><strong class=3D"command">session-keyfile</=
strong></span></span></dt>
 <dd><p>
@@ -2543,14 +2562,6 @@
                 hmac-sha384, hmac-sha512 and hmac-md5.  If not
                 specified, the default is hmac-sha256.
               </p></dd>
-<dt><span class=3D"term"><span><strong class=3D"command">session-keyfile</=
strong></span></span></dt>
-<dd><p>
-                The pathname of the file into which to write a session TSIG
-                key for use by <span><strong class=3D"command">nsupdate -l=
</strong></span>.  (See the
-                discussion of the <span><strong class=3D"command">update-p=
olicy</strong></span>
-                statement's <strong class=3D"userinput"><code>local</code>=
</strong> option for more
-                details on this feature.)
-              </p></dd>
 <dt><span class=3D"term"><span><strong class=3D"command">port</strong></sp=
an></span></dt>
 <dd><p>
                 The UDP/TCP port number the server uses for
@@ -2663,6 +2674,11 @@
                 used, along with a built-in key for validation.
               </p>
 <p>
+                If <span><strong class=3D"command">dnssec-lookaside</stron=
g></span> is set to
+                <strong class=3D"userinput"><code>no</code></strong>, then=
 dnssec-lookaside
+                is not used.
+              </p>
+<p>
                 The default DLV key is stored in the file
                 <code class=3D"filename">bind.keys</code>;
                 <span><strong class=3D"command">named</strong></span> will=
 load that key at
@@ -3649,7 +3665,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2583636"></a>Forwarding</h4></div></div></div>
+<a name=3D"id2583643"></a>Forwarding</h4></div></div></div>
 <p>
             The forwarding facility can be used to create a large site-wide
             cache on a few servers, reducing traffic over links to external
@@ -3693,7 +3709,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2583763"></a>Dual-stack Servers</h4></div></div></div>
+<a name=3D"id2583702"></a>Dual-stack Servers</h4></div></div></div>
 <p>
             Dual-stack servers are used as servers of last resort to work
             around
@@ -3904,7 +3920,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2584382"></a>Interfaces</h4></div></div></div>
+<a name=3D"id2584322"></a>Interfaces</h4></div></div></div>
 <p>
             The interfaces and ports that the server will answer queries
             from may be specified using the <span><strong class=3D"command=
">listen-on</strong></span> option. <span><strong class=3D"command">listen-=
on</strong></span> takes
@@ -4363,7 +4379,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2585456"></a>UDP Port Lists</h4></div></div></div>
+<a name=3D"id2585531"></a>UDP Port Lists</h4></div></div></div>
 <p>
             <span><strong class=3D"command">use-v4-udp-ports</strong></spa=
n>,
             <span><strong class=3D"command">avoid-v4-udp-ports</strong></s=
pan>,
@@ -4405,7 +4421,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2585584"></a>Operating System Resource Limits</h4></div></div=
></div>
+<a name=3D"id2585591"></a>Operating System Resource Limits</h4></div></div=
></div>
 <p>
             The server's usage of many system resources can be limited.
             Scaled values are allowed when specifying resource limits.  For
@@ -4567,7 +4583,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2585869"></a>Periodic Task Intervals</h4></div></div></div>
+<a name=3D"id2586082"></a>Periodic Task Intervals</h4></div></div></div>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><span><strong class=3D"command">cleaning-interval=
</strong></span></span></dt>
 <dd><p>
@@ -4988,7 +5004,7 @@
 <p>
                   Specify a private RDATA type to be used when generating
                   key signing records.  The default is
-                  <code class=3D"literal">65535</code>.
+                  <code class=3D"literal">65534</code>.
                 </p>
 <p>
                   It is expected that this parameter may be removed
@@ -5210,10 +5226,11 @@
             and which queries should not be sent to the Internet's root
             servers.  The official servers which cover these namespaces
             return NXDOMAIN responses to these queries.  In particular,
-            these cover the reverse namespace for addresses from RFC 1918 =
and
-            RFC 3330.  They also include the reverse namespace for IPv6 lo=
cal
-            address (locally assigned), IPv6 link local addresses, the IPv6
-            loopback address and the IPv6 unknown address.
+            these cover the reverse namespaces for addresses from
+            RFC 1918, RFC 4193, and RFC 5737.  They also include the
+            reverse namespace for IPv6 local address (locally assigned),
+            IPv6 link local addresses, the IPv6 loopback address and the
+            IPv6 unknown address.
           </p>
 <p>
             Named will attempt to determine if a built-in zone already exi=
sts
@@ -5406,7 +5423,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2588113"></a>Content Filtering</h4></div></div></div>
+<a name=3D"id2588188"></a>Content Filtering</h4></div></div></div>
 <p>
             <acronym class=3D"acronym">BIND</acronym> 9 provides the abili=
ty to filter
             out DNS responses from external DNS servers containing
@@ -5529,131 +5546,228 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2588372"></a>Response Policy Zone (RPZ) Rewriting</h4></div><=
/div></div>
+<a name=3D"id2588379"></a>Response Policy Zone (RPZ) Rewriting</h4></div><=
/div></div>
 <p>
             <acronym class=3D"acronym">BIND</acronym> 9 includes an intent=
ionally limited
             mechanism to modify DNS responses for recursive requests
-            similar to email anti-spam DNS blacklists.
-            All response policy zones are named in the
+            somewhat similar to email anti-spam DNS blacklists.
+            Responses can be changed to deny the existence of domains(NXDO=
MAIN),
+            deny the existence of IP addresses for domains (NODATA),
+            or contain other IP addresses or data.
+          </p>
+<p>
+            The actions encoded in a response policy zone (RPZ) are applied
+            only to queries that ask for recursion (RD=3D1).
+            Response policy zones are named in the
             <span><strong class=3D"command">response-policy</strong></span=
> option for the view or among the
             global options if there is no response-policy option for the v=
iew.
-          </p>
-<p>
-            The rules encoded in a response policy zone (RPZ) are applied
-            only to responses to queries that ask for recursion (RD=3D1).
-            RPZs are normal DNS zones containing RRsets
+            RPZs are ordinary DNS zones containing RRsets
             that can be queried normally if allowed.
             It is usually best to restrict those queries with something li=
ke
-            <span><strong class=3D"command">allow-query {none; };</strong>=
</span> or
-            <span><strong class=3D"command">allow-query { 127.0.0.1; };</s=
trong></span>.
-          </p>
-<p>
-            There are four kinds of RPZ rewrite rules.  QNAME rules are
-            applied to query names in requests and to targets of CNAME
-            records resolved in the process of generating the response.
-            The owner name of a QNAME rule is the query name relativized
+            <span><strong class=3D"command">allow-query { localhost; };</s=
trong></span>.
+          </p>
+<p>
+            There are four kinds of RPZ records, QNAME, IP, NSIP,
+            and NSDNAME.
+            QNAME records are applied to query names of requests and targe=
ts
+            of CNAME records resolved to generate the response.
+            The owner name of a QNAME RPZ record is the query name relativ=
ized
             to the RPZ.
-            The records in a rewrite rule are usually A, AAAA, or special
-            CNAMEs, but can be any type except DNAME.
-          </p>
-<p>
-            IP rules are triggered by addresses in A and AAAA records.
-            All IP addresses in A or AAAA RRsets are tested and the rule
-            longest prefix is applied.  Ties between rules with equal pref=
ixes
-            are broken in favor of the first RPZ mentioned in the
-            response-policy option.
-            The rule matching the smallest IP address is chosen among equal
-            prefix rules from a single RPZ.
-            IP rules are expressed in RRsets with owner names that are
-            subdomains of rpz-ip and encoding an IP address block, reversed
-            as in IN-ARPA.
-            prefix.B.B.B.B with prefix between 1 and 32 and B between 1 an=
d 255
-            encodes an IPv4 address.
-            IPv6 addresses are encoded by with prefix.W.W.W.W.W.W.W.W or
-            prefix.WORDS.zz.WORDS.  The words in the standard IPv6 text
-            representation are reversed, "::" is replaced with ".zz.",
-            and ":" becomes ".".
-          </p>
-<p>
-            NSDNAME rules match names in NS RRsets for the response or a
-            parent.  They are encoded as subdomains of rpz-nsdomain relati=
vized
+          </p>
+<p>
+            The second kind of RPZ record, an IP policy record,
+            is triggered by addresses in A and AAAA records
+            for the ANSWER sections of responses.
+            IP policy records have owner names that are
+            subdomains of <strong class=3D"userinput"><code>rpz-ip</code><=
/strong> relativized to the
+            RPZ origin name and encode an IP address or address block.
+            IPv4 addresses are encoded as
+            <strong class=3D"userinput"><code>prefixlength.B4.B3.B2.B1.rpz=
-ip</code></strong>.
+            The prefix length must be between 1 and 32.
+            All four bytes, B4, B3, B2, and B1, must be present.
+            B4 is the decimal value of the least significant byte of the
+            IPv4 address as in IN-ADDR.ARPA.
+            IPv6 addresses are encoded in a format similar to the standard
+            IPv6 text representation,
+            <strong class=3D"userinput"><code>prefixlength.W8.W7.W6.W5.W4.=
W3.W2.W1.rpz-ip</code></strong>.
+            Each of W8,...,W1 is a one to four digit hexadecimal number
+            representing 16 bits of the IPv6 address as in the standard te=
xt
+            representation of IPv6 addresses, but reversed as in IN-ADDR.A=
RPA.
+            All 8 words must be present except when consecutive
+            zero words are replaced with <strong class=3D"userinput"><code=
>.zz.</code></strong>
+            analogous to double colons (::) in standard IPv6 text encoding=
s.
+            The prefix length must be between 1 and 128.
+          </p>
+<p>
+            NSDNAME policy records match names of authoritative servers
+            for the query name, a parent of the query name, a CNAME,
+            or a parent of a CNAME.
+            They are encoded as subdomains of
+            <strong class=3D"userinput"><code>rpz-nsdomain</code></strong>=
 relativized
             to the RPZ origin name.
           </p>
 <p>
-            NSIP rules match IP addresses in A and AAAA RRsets for names of
-            responsible servers or the names that can be matched by NSDNAME
-            rules.  The are encoded like IP rules except as subdomains of
-            rpz-nsip.
-          </p>
-<p>
-            Authority verification issues and variations in authority data=
 in
-            the current version of <acronym class=3D"acronym">BIND</acrony=
m> 9 can cause
-            inconsistent results from NSIP and NSDNAME.  So they are avail=
able
+            NSIP policy records match IP addresses in A and AAAA RRsets
+            for domains that can be checked against NSDNAME policy records.
+            The are encoded like IP policies except as subdomains of
+            <strong class=3D"userinput"><code>rpz-nsip</code></strong>.
+          </p>
+<p>
+            The query response is checked against all RPZs, so
+            two or more policy records can apply to a single response.
+            Because DNS responses can be rewritten according by at most a
+            single policy record, a single policy (other than
+            <span><strong class=3D"command">DISABLED</strong></span> polic=
ies) must be chosen.
+            Policies are chosen in the following order:
+            </p>
+<div class=3D"itemizedlist"><ul type=3D"disc">
+<li>Among applicable zones, use the RPZ that appears first
+                in the response-policy option.
+              </li>
+<li>Prefer QNAME to IP to NSDNAME to NSIP policy records
+                in a single RPZ
+              </li>
+<li>Among applicable NSDNAME policy records, prefer the
+                policy record that matches the lexically smallest name
+              </li>
+<li>Among IP or NSIP policy records, prefer the record
+                with the longest prefix.
+              </li>
+<li>Among records with the same prefex length,
+                prefer the IP or NSIP policy record that matches
+                the smallest IP address.
+              </li>
+</ul></div>
+<p>
+          </p>
+<p>
+            When the processing of a response is restarted to resolve
+            DNAME or CNAME records and an applicable policy record set has
+            not been found,
+            all RPZs are again consulted for the DNAME or CNAME names
+            and addresses.
+          </p>
+<p>
+            Authority verification issues and variations in authority data
+            can cause inconsistent results for NSIP and NSDNAME policy rec=
ords.
+            Glue NS records often differ from authoritative NS records.
+            So they are available
             only when <acronym class=3D"acronym">BIND</acronym> is built w=
ith the
             <strong class=3D"userinput"><code>--enable-rpz-nsip</code></st=
rong> or
             <strong class=3D"userinput"><code>--enable-rpz-nsdname</code><=
/strong> options
             on the "configure" command line.
           </p>
 <p>
-            Four policies can be expressed.
-            The <span><strong class=3D"command">NXDOMAIN</strong></span> p=
olicy causes a NXDOMAIN response
-            and is expressed with an RRset consisting of a single CNAME
-            whose target is the root domain (.).
-            <span><strong class=3D"command">NODATA</strong></span> generat=
es NODATA or ANCOUNT=3D1 regardless
-            of query type.
-            It is expressed with a CNAME whose target is the wildcard
-            top-level domain (*.).
-            The <span><strong class=3D"command">NO-OP</strong></span> poli=
cy does not change the response
-            and is used to "poke holes" in policies for larger CIDR blocks=
 or in
-            zones named later in the <span><strong class=3D"command">respo=
nse-policy</strong></span> option.
-            The NO-OP policy is expressed by a CNAME with a target consist=
ing
-            of the variable part of the owner name, such as "example.com."=
 for
-            a QNAME rule or "128.1.0.0.127." for an IP rule.
-            The <span><strong class=3D"command">CNAME</strong></span> poli=
cy is used to replace the RRsets
-            of response.
-            A and AAAA RRsets are most common and useful to capture
-            an evil domain in a walled garden, but any valid set of RRsets
-            is possible.
-          </p>
-<p>
-            All of the policies in an RPZ can be overridden with a
-            <span><strong class=3D"command">policy</strong></span> clause.
-            <span><strong class=3D"command">given</strong></span> says "do=
 not override."
-            <span><strong class=3D"command">no-op</strong></span> says "do=
 nothing" regardless of the policy
-            in RPZ records.
-            <span><strong class=3D"command">nxdomain</strong></span> cause=
s all RPZ rules to generate
-            NXDOMAIN results.
-            <span><strong class=3D"command">nodata</strong></span> gives n=
odata.
-            <span><strong class=3D"command">cname domain</strong></span> c=
auses all RPZ rules to act as if
-            the consisted of a "cname domain" record.
+            RPZ record sets are special CNAME records or one or more
+            of any types of DNS record except DNAME or DNSSEC.
+            Except when a policy record is a CNAME, there can be more
+            more than one record and more than one type
+            in a set of policy records.
+            Except for three kinds of CNAME records that are illegal except
+            in policy zones, the records in a set are used in the response=
 as if
+            their owner name were the query name.  They are copied to the
+            response as dictated by their types.
+            </p>
+<div class=3D"itemizedlist"><ul type=3D"disc">
+<li>A CNAME whose target is the root domain (.)
+                specifies the <span><strong class=3D"command">NXDOMAIN</st=
rong></span> policy,
+                which generates an NXDOMAIN response.
+              </li>
+<li>A CNAME whose target is the wildcard top-level
+                domain (*.) specifies the <span><strong class=3D"command">=
NODATA</strong></span> policy,
+                which rewrites the response to NODATA or ANCOUNT=3D1.
+              </li>
+<li>A CNAME whose target is a wildcard hostname such
+                as *.example.com is used normally after the astrisk (*)
+                has been replaced with the query name.
+                These records are usually resolved with ordinary CNAMEs
+                outside the policy zones.  They can be useful for logging.
+              </li>
+<li>The <span><strong class=3D"command">PASSTHRU</strong></span> policy is=
 specified
+                by a CNAME whose target is the variable part of its own
+                owner name.  It causes the response to not be rewritten
+                and is most often used to "poke holes" in policies for
+                CIDR blocks.
+              </li>
+</ul></div>
+<p>
+          </p>
+<p>
+            The policies specified in individual records
+            in an RPZ can be overridden with a <span><strong class=3D"comm=
and">policy</strong></span> clause
+            in the <span><strong class=3D"command">response-policy</strong=
></span> option.
+            An organization using an RPZ provided by another organization =
might
+            use this mechanism to redirect domains to its own walled garde=
n.
+            </p>
+<div class=3D"itemizedlist"><ul type=3D"disc">
+<li>
+<span><strong class=3D"command">GIVEN</strong></span> says "do not overrid=
e."
+              </li>
+<li>
+<span><strong class=3D"command">DISABLED</strong></span> causes policy rec=
ords to do
+                nothing but log what they might have done.
+                The response to the DNS query will be written according to
+                any matching policy records that are not disabled.
+                Policy zones overridden with <span><strong class=3D"comman=
d">DISABLED</strong></span> should
+                appear first, because they will often not be logged
+                if a higher precedence policy is found first.
+              </li>
+<li>
+<span><strong class=3D"command">PASSTHRU</strong></span> causes all policy=
 records
+                to act as if they were CNAME records with targets the vari=
able
+                part of their owner name.  They protect the response from
+                being changed.
+              </li>
+<li>
+<span><strong class=3D"command">NXDOMAIN</strong></span> causes all RPZ re=
cords
+                to specify NXDOMAIN policies.
+              </li>
+<li>
+<span><strong class=3D"command">NODATA</strong></span> overrides with the
+                NODATA policy
+              </li>
+<li>
+<span><strong class=3D"command">CNAME domain</strong></span> causes all RPZ
+                policy records to act as if they were "cname domain" recor=
ds.
+              </li>
+</ul></div>
+<p>
           </p>
 <p>
             For example, you might use this option statement
           </p>
-<pre class=3D"programlisting">response-policy { zone "bl"; };</pre>
+<pre class=3D"programlisting">    response-policy { zone "badlist"; };</pr=
e>
 <p>
             and this zone statement
           </p>
-<pre class=3D"programlisting">zone "bl" {type master; file "example/bl"; a=
llow-query {none;}; };</pre>
+<pre class=3D"programlisting">    zone "badlist" {type master; file "maste=
r/badlist"; allow-query {none;}; };</pre>
 <p>
             with this zone file
           </p>
 <pre class=3D"programlisting">$TTL 1H
-@                   SOA LOCALHOST. named-mgr.example.com (1 1h 15m 30d 2h)
+@                       SOA LOCALHOST. named-mgr.example.com (1 1h 15m 30d=
 2h)
+                        NS  LOCALHOST.
=20
-; QNAME rules
-nxdomain.domain.com         CNAME   .
-nodata.domain.com           CNAME   *.
-bad.domain.com              A       10.0.0.1
-                            AAAA    2001:2::1
-ok.domain.com               CNAME   ok.domain.com.
-*.badzone.domain.com        CNAME   garden.example.com.
+; QNAME policy records.  There are no periods (.) after the owner names.
+nxdomain.domain.com     CNAME   .               ; NXDOMAIN policy
+nodata.domain.com       CNAME   *.              ; NODATA policy
+bad.domain.com          A       10.0.0.1        ; redirect to a walled gar=
den
+                        AAAA    2001:2::1
=20
-; IP rules rewriting all answers for 127/8 except 127.0.0.1
-8.0.0.0.127.ip              CNAME   .
-32.1.0.0.127.ip             CNAME   32.1.0.0.127.
+; do not rewrite (PASSTHRU) OK.DOMAIN.COM
+ok.domain.com           CNAME   ok.domain.com.
=20
-; NSDNAME and NSIP rules
+bzone.domain.com        CNAME   garden.example.com.
+
+; redirect x.bzone.domain.com to x.bzone.domain.com.garden.example.com
+*.bzone.domain.com      CNAME   *.garden.example.com.
+
+
+; IP policy records that rewrite all answers for 127/8 except 127.0.0.1
+8.0.0.0.127.rpz-ip      CNAME   .
+32.1.0.0.127.rpz-ip     CNAME   32.1.0.0.127.   ; PASSTHRU for 127.0.0.1
+
+; NSDNAME and NSIP policy records
 ns.domain.com.rpz-nsdname   CNAME   .
 48.zz.2.2001.rpz-nsip       CNAME   .
 </pre>
@@ -5867,7 +5981,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2589395"></a><span><strong class=3D"command">statistics-chann=
els</strong></span> Statement Definition and
+<a name=3D"id2589481"></a><span><strong class=3D"command">statistics-chann=
els</strong></span> Statement Definition and
             Usage</h3></div></div></div>
 <p>
           The <span><strong class=3D"command">statistics-channels</strong>=
</span> statement
@@ -5927,7 +6041,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2589534"></a><span><strong class=3D"command">trusted-keys</st=
rong></span> Statement Definition
+<a name=3D"id2589689"></a><span><strong class=3D"command">trusted-keys</st=
rong></span> Statement Definition
             and Usage</h3></div></div></div>
 <p>
             The <span><strong class=3D"command">trusted-keys</strong></spa=
n> statement defines
@@ -5967,7 +6081,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2589581"></a><span><strong class=3D"command">managed-keys</st=
rong></span> Statement Grammar</h3></div></div></div>
+<a name=3D"id2589736"></a><span><strong class=3D"command">managed-keys</st=
rong></span> Statement Grammar</h3></div></div></div>
 <pre class=3D"programlisting"><span><strong class=3D"command">managed-keys=
</strong></span> {
     <em class=3D"replaceable"><code>string</code></em> initial-key <em cla=
ss=3D"replaceable"><code>number</code></em> <em class=3D"replaceable"><code=
>number</code></em> <em class=3D"replaceable"><code>number</code></em> <em =
class=3D"replaceable"><code>string</code></em> ;
     [<span class=3D"optional"> <em class=3D"replaceable"><code>string</cod=
e></em> initial-key <em class=3D"replaceable"><code>number</code></em> <em =
class=3D"replaceable"><code>number</code></em> <em class=3D"replaceable"><c=
ode>number</code></em> <em class=3D"replaceable"><code>string</code></em> ;=
 [<span class=3D"optional">...</span>]</span>]
@@ -6102,7 +6216,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2590007"></a><span><strong class=3D"command">view</strong></s=
pan> Statement Definition and Usage</h3></div></div></div>
+<a name=3D"id2590162"></a><span><strong class=3D"command">view</strong></s=
pan> Statement Definition and Usage</h3></div></div></div>
 <p>
             The <span><strong class=3D"command">view</strong></span> state=
ment is a powerful
             feature
@@ -6391,10 +6505,10 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2591558"></a><span><strong class=3D"command">zone</strong></s=
pan> Statement Definition and Usage</h3></div></div></div>
+<a name=3D"id2591713"></a><span><strong class=3D"command">zone</strong></s=
pan> Statement Definition and Usage</h3></div></div></div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2591565"></a>Zone Types</h4></div></div></div>
+<a name=3D"id2591720"></a>Zone Types</h4></div></div></div>
 <div class=3D"informaltable"><table border=3D"1">
 <colgroup>
 <col>
@@ -6654,7 +6768,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2592179"></a>Class</h4></div></div></div>
+<a name=3D"id2592402"></a>Class</h4></div></div></div>
 <p>
               The zone's name may optionally be followed by a class. If
               a class is not specified, class <code class=3D"literal">IN</=
code> (for <code class=3D"varname">Internet</code>),
@@ -6676,7 +6790,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2592212"></a>Zone Options</h4></div></div></div>
+<a name=3D"id2592503"></a>Zone Options</h4></div></div></div>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><span><strong class=3D"command">allow-notify</str=
ong></span></span></dt>
 <dd><p>
@@ -7553,7 +7667,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2595030"></a>Zone File</h2></div></div></div>
+<a name=3D"id2595116"></a>Zone File</h2></div></div></div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
 <a name=3D"types_of_resource_records_and_when_to_use_them"></a>Types of Re=
source Records and When to Use Them</h3></div></div></div>
@@ -7566,7 +7680,7 @@
           </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2595048"></a>Resource Records</h4></div></div></div>
+<a name=3D"id2595134"></a>Resource Records</h4></div></div></div>
 <p>
               A domain name identifies a node.  Each node has a set of
               resource information, which may be empty.  The set of resour=
ce
@@ -8303,7 +8417,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2596603"></a>Textual expression of RRs</h4></div></div></div>
+<a name=3D"id2596826"></a>Textual expression of RRs</h4></div></div></div>
 <p>
               RRs are represented in binary form in the packets of the DNS
               protocol, and are usually represented in highly encoded form
@@ -8506,7 +8620,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2597260"></a>Discussion of MX Records</h3></div></div></div>
+<a name=3D"id2597415"></a>Discussion of MX Records</h3></div></div></div>
 <p>
             As described above, domain servers store information as a
             series of resource records, each of which contains a particular
@@ -8762,7 +8876,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2597876"></a>Inverse Mapping in IPv4</h3></div></div></div>
+<a name=3D"id2597962"></a>Inverse Mapping in IPv4</h3></div></div></div>
 <p>
             Reverse name resolution (that is, translation from IP address
             to name) is achieved by means of the <span class=3D"emphasis">=
<em>in-addr.arpa</em></span> domain
@@ -8823,7 +8937,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2598003"></a>Other Zone File Directives</h3></div></div></div>
+<a name=3D"id2598157"></a>Other Zone File Directives</h3></div></div></div>
 <p>
             The Master File Format was initially defined in RFC 1035 and
             has subsequently been extended. While the Master File Format
@@ -8838,7 +8952,7 @@
           </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2598093"></a>The <span><strong class=3D"command">@</strong></=
span> (at-sign)</h4></div></div></div>
+<a name=3D"id2598180"></a>The <span><strong class=3D"command">@</strong></=
span> (at-sign)</h4></div></div></div>
 <p>
               When used in the label (or name) field, the asperand or
               at-sign (@) symbol represents the current origin.
@@ -8849,7 +8963,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2598109"></a>The <span><strong class=3D"command">$ORIGIN</str=
ong></span> Directive</h4></div></div></div>
+<a name=3D"id2598196"></a>The <span><strong class=3D"command">$ORIGIN</str=
ong></span> Directive</h4></div></div></div>
 <p>
               Syntax: <span><strong class=3D"command">$ORIGIN</strong></sp=
an>
               <em class=3D"replaceable"><code>domain-name</code></em>
@@ -8878,7 +8992,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2598170"></a>The <span><strong class=3D"command">$INCLUDE</st=
rong></span> Directive</h4></div></div></div>
+<a name=3D"id2598325"></a>The <span><strong class=3D"command">$INCLUDE</st=
rong></span> Directive</h4></div></div></div>
 <p>
               Syntax: <span><strong class=3D"command">$INCLUDE</strong></s=
pan>
               <em class=3D"replaceable"><code>filename</code></em>
@@ -8914,7 +9028,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2598240"></a>The <span><strong class=3D"command">$TTL</strong=
></span> Directive</h4></div></div></div>
+<a name=3D"id2598394"></a>The <span><strong class=3D"command">$TTL</strong=
></span> Directive</h4></div></div></div>
 <p>
               Syntax: <span><strong class=3D"command">$TTL</strong></span>
               <em class=3D"replaceable"><code>default-ttl</code></em>
@@ -8933,7 +9047,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2598276"></a><acronym class=3D"acronym">BIND</acronym> Master=
 File Extension: the  <span><strong class=3D"command">$GENERATE</strong></s=
pan> Directive</h3></div></div></div>
+<a name=3D"id2598430"></a><acronym class=3D"acronym">BIND</acronym> Master=
 File Extension: the  <span><strong class=3D"command">$GENERATE</strong></s=
pan> Directive</h3></div></div></div>
 <p>
             Syntax: <span><strong class=3D"command">$GENERATE</strong></sp=
an>
             <em class=3D"replaceable"><code>range</code></em>
@@ -9357,7 +9471,7 @@
           </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2599229"></a>Name Server Statistics Counters</h4></div></div>=
</div>
+<a name=3D"id2599384"></a>Name Server Statistics Counters</h4></div></div>=
</div>
 <div class=3D"informaltable"><table border=3D"1">
 <colgroup>
 <col>
@@ -9914,7 +10028,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2600702"></a>Zone Maintenance Statistics Counters</h4></div><=
/div></div>
+<a name=3D"id2600857"></a>Zone Maintenance Statistics Counters</h4></div><=
/div></div>
 <div class=3D"informaltable"><table border=3D"1">
 <colgroup>
 <col>
@@ -10068,7 +10182,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2601154"></a>Resolver Statistics Counters</h4></div></div></d=
iv>
+<a name=3D"id2601308"></a>Resolver Statistics Counters</h4></div></div></d=
iv>
 <div class=3D"informaltable"><table border=3D"1">
 <colgroup>
 <col>
@@ -10451,7 +10565,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2602312"></a>Socket I/O Statistics Counters</h4></div></div><=
/div>
+<a name=3D"id2602398"></a>Socket I/O Statistics Counters</h4></div></div><=
/div>
 <p>
               Socket I/O statistics counters are defined per socket
               types, which are
@@ -10606,7 +10720,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2602685"></a>Compatibility with <span class=3D"emphasis"><em>=
BIND</em></span> 8 Counters</h4></div></div></div>
+<a name=3D"id2602840"></a>Compatibility with <span class=3D"emphasis"><em>=
BIND</em></span> 8 Counters</h4></div></div></div>
 <p>
               Most statistics counters that were available
               in <span><strong class=3D"command">BIND</strong></span> 8 ar=
e also supported in
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch07=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch07.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch07.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch07.html,v 1.242.8.7 2011-08-03 02:35:10 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -46,10 +46,10 @@
 <p><b>Table of Contents</b></p>
 <dl>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#Access_Control_Lists=
">Access Control Lists</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#id2602996"><span><st=
rong class=3D"command">Chroot</strong></span> and <span><strong class=3D"co=
mmand">Setuid</strong></span></a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#id2603082"><span><st=
rong class=3D"command">Chroot</strong></span> and <span><strong class=3D"co=
mmand">Setuid</strong></span></a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603077">The <span=
><strong class=3D"command">chroot</strong></span> Environment</a></span></d=
t>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603137">Using the=
 <span><strong class=3D"command">setuid</strong></span> Function</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603232">The <span=
><strong class=3D"command">chroot</strong></span> Environment</a></span></d=
t>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603291">Using the=
 <span><strong class=3D"command">setuid</strong></span> Function</a></span>=
</dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#dynamic_update_secur=
ity">Dynamic Update Security</a></span></dt>
 </dl>
@@ -84,9 +84,8 @@
 // RFC1918 space and some reserved space, which is
 // commonly used in spoofing attacks.
 acl bogusnets {
-        0.0.0.0/8; 1.0.0.0/8; 2.0.0.0/8; 192.0.2.0/24;
-        224.0.0.0/3; 10.0.0.0/8; 172.16.0.0/12;
-        192.168.0.0/16;
+        0.0.0.0/8;  192.0.2.0/24; 224.0.0.0/3;
+        10.0.0.0/8; 172.16.0.0/12; 192.168.0.0/16;
 };
=20
 // Set up an ACL called our-nets. Replace this with the
@@ -122,7 +121,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2602996"></a><span><strong class=3D"command">Chroot</strong><=
/span> and <span><strong class=3D"command">Setuid</strong></span>
+<a name=3D"id2603082"></a><span><strong class=3D"command">Chroot</strong><=
/span> and <span><strong class=3D"command">Setuid</strong></span>
 </h2></div></div></div>
 <p>
           On UNIX servers, it is possible to run <acronym class=3D"acronym=
">BIND</acronym>
@@ -148,7 +147,7 @@
         </p>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2603077"></a>The <span><strong class=3D"command">chroot</stro=
ng></span> Environment</h3></div></div></div>
+<a name=3D"id2603232"></a>The <span><strong class=3D"command">chroot</stro=
ng></span> Environment</h3></div></div></div>
 <p>
             In order for a <span><strong class=3D"command">chroot</strong>=
</span> environment
             to
@@ -176,7 +175,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2603137"></a>Using the <span><strong class=3D"command">setuid=
</strong></span> Function</h3></div></div></div>
+<a name=3D"id2603291"></a>Using the <span><strong class=3D"command">setuid=
</strong></span> Function</h3></div></div></div>
 <p>
             Prior to running the <span><strong class=3D"command">named</st=
rong></span> daemon,
             use
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch08=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch08.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch08.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch08.html,v 1.242.8.7 2011-08-03 02:35:11 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -45,18 +45,18 @@
 <div class=3D"toc">
 <p><b>Table of Contents</b></p>
 <dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603285">Common Pr=
oblems</a></span></dt>
-<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch08.html#id2603290">I=
t's not working; how can I figure out what's wrong?</a></span></dt></dl></d=
d>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603302">Increment=
ing and Changing the Serial Number</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603319">Where Can=
 I Get Help?</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603371">Common Pr=
oblems</a></span></dt>
+<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch08.html#id2603377">I=
t's not working; how can I figure out what's wrong?</a></span></dt></dl></d=
d>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603388">Increment=
ing and Changing the Serial Number</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603405">Where Can=
 I Get Help?</a></span></dt>
 </dl>
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2603285"></a>Common Problems</h2></div></div></div>
+<a name=3D"id2603371"></a>Common Problems</h2></div></div></div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2603290"></a>It's not working; how can I figure out what's wr=
ong?</h3></div></div></div>
+<a name=3D"id2603377"></a>It's not working; how can I figure out what's wr=
ong?</h3></div></div></div>
 <p>
             The best solution to solving installation and
             configuration issues is to take preventative measures by setti=
ng
@@ -68,7 +68,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2603302"></a>Incrementing and Changing the Serial Number</h2>=
</div></div></div>
+<a name=3D"id2603388"></a>Incrementing and Changing the Serial Number</h2>=
</div></div></div>
 <p>
           Zone serial numbers are just numbers — they aren't
           date related.  A lot of people set them to a number that
@@ -95,7 +95,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2603319"></a>Where Can I Get Help?</h2></div></div></div>
+<a name=3D"id2603405"></a>Where Can I Get Help?</h2></div></div></div>
 <p>
           The Internet Systems Consortium
           (<acronym class=3D"acronym">ISC</acronym>) offers a wide range
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch09=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch09.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch09.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch09.html,v 1.246.8.9 2011-08-03 02:35:11 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -45,31 +45,31 @@
 <div class=3D"toc">
 <p><b>Table of Contents</b></p>
 <dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603449">Acknowled=
gments</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603536">Acknowled=
gments</a></span></dt>
 <dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#historical_d=
ns_information">A Brief History of the <acronym class=3D"acronym">DNS</acro=
nym> and <acronym class=3D"acronym">BIND</acronym></a></span></dt></dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603553">General <=
acronym class=3D"acronym">DNS</acronym> Reference Information</a></span></d=
t>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603707">General <=
acronym class=3D"acronym">DNS</acronym> Reference Information</a></span></d=
t>
 <dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#ipv6addresse=
s">IPv6 addresses (AAAA)</a></span></dt></dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#bibliography">Biblio=
graphy (and Suggested Reading)</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#rfcs">Request for Co=
mments (RFCs)</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#internet_drafts">Int=
ernet Drafts</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2606901">Other Doc=
uments About <acronym class=3D"acronym">BIND</acronym></a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2607124">Other Doc=
uments About <acronym class=3D"acronym">BIND</acronym></a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#bind9.library">BIND =
9 DNS Library Support</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608203">Prerequis=
ite</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608213">Compilati=
on</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608237">Installat=
ion</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608268">Known Def=
ects/Restrictions</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608413">The dns.c=
onf File</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608440">Sample Ap=
plications</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2609345">Library R=
eferences</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608280">Prerequis=
ite</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608290">Compilati=
on</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608314">Installat=
ion</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608345">Known Def=
ects/Restrictions</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608422">The dns.c=
onf File</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608449">Sample Ap=
plications</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2609490">Library R=
eferences</a></span></dt>
 </dl></dd>
 </dl>
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2603449"></a>Acknowledgments</h2></div></div></div>
+<a name=3D"id2603536"></a>Acknowledgments</h2></div></div></div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
 <a name=3D"historical_dns_information"></a>A Brief History of the <acronym=
 class=3D"acronym">DNS</acronym> and <acronym class=3D"acronym">BIND</acron=
ym>
@@ -172,7 +172,7 @@
 </div>
 <div class=3D"sect1" lang=3D"en">
 <div class=3D"titlepage"><div><div><h2 class=3D"title" style=3D"clear: bot=
h">
-<a name=3D"id2603553"></a>General <acronym class=3D"acronym">DNS</acronym>=
 Reference Information</h2></div></div></div>
+<a name=3D"id2603707"></a>General <acronym class=3D"acronym">DNS</acronym>=
 Reference Information</h2></div></div></div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
 <a name=3D"ipv6addresses"></a>IPv6 addresses (AAAA)</h3></div></div></div>
@@ -260,17 +260,17 @@
           </p>
 <div class=3D"bibliography">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2603809"></a>Bibliography</h4></div></div></div>
+<a name=3D"id2603895"></a>Bibliography</h4></div></div></div>
 <div class=3D"bibliodiv">
 <h3 class=3D"title">Standards</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2603819"></a><p>[<abbr class=3D"abbrev">RFC974</abbr>] <span =
class=3D"author"><span class=3D"firstname">C.</span> <span class=3D"surname=
">Partridge</span>. </span><span class=3D"title"><i>Mail Routing and the Do=
main System</i>. </span><span class=3D"pubdate">January 1986. </span></p>
+<a name=3D"id2603906"></a><p>[<abbr class=3D"abbrev">RFC974</abbr>] <span =
class=3D"author"><span class=3D"firstname">C.</span> <span class=3D"surname=
">Partridge</span>. </span><span class=3D"title"><i>Mail Routing and the Do=
main System</i>. </span><span class=3D"pubdate">January 1986. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2603843"></a><p>[<abbr class=3D"abbrev">RFC1034</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.V.</span> <span class=3D"surn=
ame">Mockapetris</span>. </span><span class=3D"title"><i>Domain Names &#821=
2; Concepts and Facilities</i>. </span><span class=3D"pubdate">November 198=
7. </span></p>
+<a name=3D"id2603929"></a><p>[<abbr class=3D"abbrev">RFC1034</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.V.</span> <span class=3D"surn=
ame">Mockapetris</span>. </span><span class=3D"title"><i>Domain Names &#821=
2; Concepts and Facilities</i>. </span><span class=3D"pubdate">November 198=
7. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2603866"></a><p>[<abbr class=3D"abbrev">RFC1035</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P. V.</span> <span class=3D"sur=
name">Mockapetris</span>. </span><span class=3D"title"><i>Domain Names &#82=
12; Implementation and
+<a name=3D"id2603953"></a><p>[<abbr class=3D"abbrev">RFC1035</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P. V.</span> <span class=3D"sur=
name">Mockapetris</span>. </span><span class=3D"title"><i>Domain Names &#82=
12; Implementation and
                   Specification</i>. </span><span class=3D"pubdate">Novemb=
er 1987. </span></p>
 </div>
 </div>
@@ -278,42 +278,42 @@
 <h3 class=3D"title">
 <a name=3D"proposed_standards"></a>Proposed Standards</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2603902"></a><p>[<abbr class=3D"abbrev">RFC2181</abbr>] <span=
 class=3D"author"><span class=3D"firstname">R., R. Bush</span> <span class=
=3D"surname">Elz</span>. </span><span class=3D"title"><i>Clarifications to =
the <acronym class=3D"acronym">DNS</acronym>
+<a name=3D"id2603989"></a><p>[<abbr class=3D"abbrev">RFC2181</abbr>] <span=
 class=3D"author"><span class=3D"firstname">R., R. Bush</span> <span class=
=3D"surname">Elz</span>. </span><span class=3D"title"><i>Clarifications to =
the <acronym class=3D"acronym">DNS</acronym>
                   Specification</i>. </span><span class=3D"pubdate">July 1=
997. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2603929"></a><p>[<abbr class=3D"abbrev">RFC2308</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Andrews</span>. </span><span class=3D"title"><i>Negative Caching of <acr=
onym class=3D"acronym">DNS</acronym>
+<a name=3D"id2604016"></a><p>[<abbr class=3D"abbrev">RFC2308</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Andrews</span>. </span><span class=3D"title"><i>Negative Caching of <acr=
onym class=3D"acronym">DNS</acronym>
                   Queries</i>. </span><span class=3D"pubdate">March 1998. =
</span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2603955"></a><p>[<abbr class=3D"abbrev">RFC1995</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Ohta</span>. </span><span class=3D"title"><i>Incremental Zone Transfer i=
n <acronym class=3D"acronym">DNS</acronym></i>. </span><span class=3D"pubda=
te">August 1996. </span></p>
+<a name=3D"id2604041"></a><p>[<abbr class=3D"abbrev">RFC1995</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Ohta</span>. </span><span class=3D"title"><i>Incremental Zone Transfer i=
n <acronym class=3D"acronym">DNS</acronym></i>. </span><span class=3D"pubda=
te">August 1996. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2603979"></a><p>[<abbr class=3D"abbrev">RFC1996</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.</span> <span class=3D"surnam=
e">Vixie</span>. </span><span class=3D"title"><i>A Mechanism for Prompt Not=
ification of Zone Changes</i>. </span><span class=3D"pubdate">August 1996. =
</span></p>
+<a name=3D"id2604066"></a><p>[<abbr class=3D"abbrev">RFC1996</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.</span> <span class=3D"surnam=
e">Vixie</span>. </span><span class=3D"title"><i>A Mechanism for Prompt Not=
ification of Zone Changes</i>. </span><span class=3D"pubdate">August 1996. =
</span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604003"></a><p>[<abbr class=3D"abbrev">RFC2136</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Vixie</span>, <span class=3D"firstname">S.</span> <span class=3D"su=
rname">Thomson</span>, <span class=3D"firstname">Y.</span> <span class=3D"s=
urname">Rekhter</span>, and <span class=3D"firstname">J.</span> <span class=
=3D"surname">Bound</span>. </span><span class=3D"title"><i>Dynamic Updates =
in the Domain Name System</i>. </span><span class=3D"pubdate">April 1997. <=
/span></p>
+<a name=3D"id2604089"></a><p>[<abbr class=3D"abbrev">RFC2136</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Vixie</span>, <span class=3D"firstname">S.</span> <span class=3D"su=
rname">Thomson</span>, <span class=3D"firstname">Y.</span> <span class=3D"s=
urname">Rekhter</span>, and <span class=3D"firstname">J.</span> <span class=
=3D"surname">Bound</span>. </span><span class=3D"title"><i>Dynamic Updates =
in the Domain Name System</i>. </span><span class=3D"pubdate">April 1997. <=
/span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604058"></a><p>[<abbr class=3D"abbrev">RFC2671</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Vixie</span>. </span><span class=3D"title"><i>Extension Mechanisms =
for DNS (EDNS0)</i>. </span><span class=3D"pubdate">August 1997. </span></p>
+<a name=3D"id2604145"></a><p>[<abbr class=3D"abbrev">RFC2671</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Vixie</span>. </span><span class=3D"title"><i>Extension Mechanisms =
for DNS (EDNS0)</i>. </span><span class=3D"pubdate">August 1997. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604085"></a><p>[<abbr class=3D"abbrev">RFC2672</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Crawford</span>. </span><span class=3D"title"><i>Non-Terminal DNS N=
ame Redirection</i>. </span><span class=3D"pubdate">August 1999. </span></p>
+<a name=3D"id2604171"></a><p>[<abbr class=3D"abbrev">RFC2672</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Crawford</span>. </span><span class=3D"title"><i>Non-Terminal DNS N=
ame Redirection</i>. </span><span class=3D"pubdate">August 1999. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604112"></a><p>[<abbr class=3D"abbrev">RFC2845</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Vixie</span>, <span class=3D"firstname">O.</span> <span class=3D"su=
rname">Gudmundsson</span>, <span class=3D"firstname">D.</span> <span class=
=3D"surname">Eastlake</span>, <span class=3D"lineage">3rd</span>, and <span=
 class=3D"firstname">B.</span> <span class=3D"surname">Wellington</span>. <=
/span><span class=3D"title"><i>Secret Key Transaction Authentication for <a=
cronym class=3D"acronym">DNS</acronym> (TSIG)</i>. </span><span class=3D"pu=
bdate">May 2000. </span></p>
+<a name=3D"id2604198"></a><p>[<abbr class=3D"abbrev">RFC2845</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Vixie</span>, <span class=3D"firstname">O.</span> <span class=3D"su=
rname">Gudmundsson</span>, <span class=3D"firstname">D.</span> <span class=
=3D"surname">Eastlake</span>, <span class=3D"lineage">3rd</span>, and <span=
 class=3D"firstname">B.</span> <span class=3D"surname">Wellington</span>. <=
/span><span class=3D"title"><i>Secret Key Transaction Authentication for <a=
cronym class=3D"acronym">DNS</acronym> (TSIG)</i>. </span><span class=3D"pu=
bdate">May 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604173"></a><p>[<abbr class=3D"abbrev">RFC2930</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Secret Key Establishment for DNS (TKEY RR)</i>. </span><s=
pan class=3D"pubdate">September 2000. </span></p>
+<a name=3D"id2604260"></a><p>[<abbr class=3D"abbrev">RFC2930</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Secret Key Establishment for DNS (TKEY RR)</i>. </span><s=
pan class=3D"pubdate">September 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604203"></a><p>[<abbr class=3D"abbrev">RFC2931</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>DNS Request and Transaction Signatures (SIG(0)s)</i>. </s=
pan><span class=3D"pubdate">September 2000. </span></p>
+<a name=3D"id2604290"></a><p>[<abbr class=3D"abbrev">RFC2931</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>DNS Request and Transaction Signatures (SIG(0)s)</i>. </s=
pan><span class=3D"pubdate">September 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604233"></a><p>[<abbr class=3D"abbrev">RFC3007</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Wellington</span>. </span><span class=3D"title"><i>Secure Domain Na=
me System (DNS) Dynamic Update</i>. </span><span class=3D"pubdate">November=
 2000. </span></p>
+<a name=3D"id2604320"></a><p>[<abbr class=3D"abbrev">RFC3007</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Wellington</span>. </span><span class=3D"title"><i>Secure Domain Na=
me System (DNS) Dynamic Update</i>. </span><span class=3D"pubdate">November=
 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604260"></a><p>[<abbr class=3D"abbrev">RFC3645</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">S.</span> <span class=3D"s=
urname">Kwan</span>, <span class=3D"firstname">P.</span> <span class=3D"sur=
name">Garg</span>, <span class=3D"firstname">J.</span> <span class=3D"surna=
me">Gilroy</span>, <span class=3D"firstname">L.</span> <span class=3D"surna=
me">Esibov</span>, <span class=3D"firstname">J.</span> <span class=3D"surna=
me">Westhead</span>, and <span class=3D"firstname">R.</span> <span class=3D=
"surname">Hall</span>. </span><span class=3D"title"><i>Generic Security Ser=
vice Algorithm for Secret
+<a name=3D"id2604346"></a><p>[<abbr class=3D"abbrev">RFC3645</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">S.</span> <span class=3D"s=
urname">Kwan</span>, <span class=3D"firstname">P.</span> <span class=3D"sur=
name">Garg</span>, <span class=3D"firstname">J.</span> <span class=3D"surna=
me">Gilroy</span>, <span class=3D"firstname">L.</span> <span class=3D"surna=
me">Esibov</span>, <span class=3D"firstname">J.</span> <span class=3D"surna=
me">Westhead</span>, and <span class=3D"firstname">R.</span> <span class=3D=
"surname">Hall</span>. </span><span class=3D"title"><i>Generic Security Ser=
vice Algorithm for Secret
                        Key Transaction Authentication for DNS
                        (GSS-TSIG)</i>. </span><span class=3D"pubdate">Octo=
ber 2003. </span></p>
 </div>
@@ -322,19 +322,19 @@
 <h3 class=3D"title">
 <acronym class=3D"acronym">DNS</acronym> Security Proposed Standards</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2604342"></a><p>[<abbr class=3D"abbrev">RFC3225</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Conrad</span>. </span><span class=3D"title"><i>Indicating Resolver =
Support of DNSSEC</i>. </span><span class=3D"pubdate">December 2001. </span=
></p>
+<a name=3D"id2604428"></a><p>[<abbr class=3D"abbrev">RFC3225</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Conrad</span>. </span><span class=3D"title"><i>Indicating Resolver =
Support of DNSSEC</i>. </span><span class=3D"pubdate">December 2001. </span=
></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604369"></a><p>[<abbr class=3D"abbrev">RFC3833</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Atkins</span> and <span class=3D"firstname">R.</span> <span class=
=3D"surname">Austein</span>. </span><span class=3D"title"><i>Threat Analysi=
s of the Domain Name System (DNS)</i>. </span><span class=3D"pubdate">Augus=
t 2004. </span></p>
+<a name=3D"id2604455"></a><p>[<abbr class=3D"abbrev">RFC3833</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Atkins</span> and <span class=3D"firstname">R.</span> <span class=
=3D"surname">Austein</span>. </span><span class=3D"title"><i>Threat Analysi=
s of the Domain Name System (DNS)</i>. </span><span class=3D"pubdate">Augus=
t 2004. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604405"></a><p>[<abbr class=3D"abbrev">RFC4033</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Arends</span>, <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Austein</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Larson</span>, <span class=3D"firstname">D.</span> <span class=3D"=
surname">Massey</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>DNS Security Intr=
oduction and Requirements</i>. </span><span class=3D"pubdate">March 2005. <=
/span></p>
+<a name=3D"id2604491"></a><p>[<abbr class=3D"abbrev">RFC4033</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Arends</span>, <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Austein</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Larson</span>, <span class=3D"firstname">D.</span> <span class=3D"=
surname">Massey</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>DNS Security Intr=
oduction and Requirements</i>. </span><span class=3D"pubdate">March 2005. <=
/span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604470"></a><p>[<abbr class=3D"abbrev">RFC4034</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Arends</span>, <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Austein</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Larson</span>, <span class=3D"firstname">D.</span> <span class=3D"=
surname">Massey</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>Resource Records =
for the DNS Security Extensions</i>. </span><span class=3D"pubdate">March 2=
005. </span></p>
+<a name=3D"id2604625"></a><p>[<abbr class=3D"abbrev">RFC4034</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Arends</span>, <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Austein</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Larson</span>, <span class=3D"firstname">D.</span> <span class=3D"=
surname">Massey</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>Resource Records =
for the DNS Security Extensions</i>. </span><span class=3D"pubdate">March 2=
005. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604603"></a><p>[<abbr class=3D"abbrev">RFC4035</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Arends</span>, <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Austein</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Larson</span>, <span class=3D"firstname">D.</span> <span class=3D"=
surname">Massey</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>Protocol Modifica=
tions for the DNS
+<a name=3D"id2604690"></a><p>[<abbr class=3D"abbrev">RFC4035</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Arends</span>, <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Austein</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Larson</span>, <span class=3D"firstname">D.</span> <span class=3D"=
surname">Massey</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>Protocol Modifica=
tions for the DNS
                        Security Extensions</i>. </span><span class=3D"pubd=
ate">March 2005. </span></p>
 </div>
 </div>
@@ -342,146 +342,146 @@
 <h3 class=3D"title">Other Important RFCs About <acronym class=3D"acronym">=
DNS</acronym>
                 Implementation</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2604677"></a><p>[<abbr class=3D"abbrev">RFC1535</abbr>] <span=
 class=3D"author"><span class=3D"firstname">E.</span> <span class=3D"surnam=
e">Gavron</span>. </span><span class=3D"title"><i>A Security Problem and Pr=
oposed Correction With Widely
+<a name=3D"id2604763"></a><p>[<abbr class=3D"abbrev">RFC1535</abbr>] <span=
 class=3D"author"><span class=3D"firstname">E.</span> <span class=3D"surnam=
e">Gavron</span>. </span><span class=3D"title"><i>A Security Problem and Pr=
oposed Correction With Widely
                   Deployed <acronym class=3D"acronym">DNS</acronym> Softwa=
re.</i>. </span><span class=3D"pubdate">October 1993. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604702"></a><p>[<abbr class=3D"abbrev">RFC1536</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Kumar</span>, <span class=3D"firstname">J.</span> <span class=3D"su=
rname">Postel</span>, <span class=3D"firstname">C.</span> <span class=3D"su=
rname">Neuman</span>, <span class=3D"firstname">P.</span> <span class=3D"su=
rname">Danzig</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Miller</span>. </span><span class=3D"title"><i>Common <acronym=
 class=3D"acronym">DNS</acronym> Implementation
+<a name=3D"id2604789"></a><p>[<abbr class=3D"abbrev">RFC1536</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Kumar</span>, <span class=3D"firstname">J.</span> <span class=3D"su=
rname">Postel</span>, <span class=3D"firstname">C.</span> <span class=3D"su=
rname">Neuman</span>, <span class=3D"firstname">P.</span> <span class=3D"su=
rname">Danzig</span>, and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Miller</span>. </span><span class=3D"title"><i>Common <acronym=
 class=3D"acronym">DNS</acronym> Implementation
                   Errors and Suggested Fixes</i>. </span><span class=3D"pu=
bdate">October 1993. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604771"></a><p>[<abbr class=3D"abbrev">RFC1982</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Elz</span> and <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Bush</span>. </span><span class=3D"title"><i>Serial Number Arithmet=
ic</i>. </span><span class=3D"pubdate">August 1996. </span></p>
+<a name=3D"id2604857"></a><p>[<abbr class=3D"abbrev">RFC1982</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Elz</span> and <span class=3D"firstname">R.</span> <span class=3D"s=
urname">Bush</span>. </span><span class=3D"title"><i>Serial Number Arithmet=
ic</i>. </span><span class=3D"pubdate">August 1996. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604806"></a><p>[<abbr class=3D"abbrev">RFC4074</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">Y.</span> <span class=3D"s=
urname">Morishita</span> and <span class=3D"firstname">T.</span> <span clas=
s=3D"surname">Jinmei</span>. </span><span class=3D"title"><i>Common Misbeha=
viour Against <acronym class=3D"acronym">DNS</acronym>
+<a name=3D"id2604892"></a><p>[<abbr class=3D"abbrev">RFC4074</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">Y.</span> <span class=3D"s=
urname">Morishita</span> and <span class=3D"firstname">T.</span> <span clas=
s=3D"surname">Jinmei</span>. </span><span class=3D"title"><i>Common Misbeha=
viour Against <acronym class=3D"acronym">DNS</acronym>
                 Queries for IPv6 Addresses</i>. </span><span class=3D"pubd=
ate">May 2005. </span></p>
 </div>
 </div>
 <div class=3D"bibliodiv">
 <h3 class=3D"title">Resource Record Types</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2604852"></a><p>[<abbr class=3D"abbrev">RFC1183</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">C.F.</span> <span class=3D=
"surname">Everhart</span>, <span class=3D"firstname">L. A.</span> <span cla=
ss=3D"surname">Mamakos</span>, <span class=3D"firstname">R.</span> <span cl=
ass=3D"surname">Ullmann</span>, and <span class=3D"firstname">P.</span> <sp=
an class=3D"surname">Mockapetris</span>. </span><span class=3D"title"><i>Ne=
w <acronym class=3D"acronym">DNS</acronym> RR Definitions</i>. </span><span=
 class=3D"pubdate">October 1990. </span></p>
+<a name=3D"id2604938"></a><p>[<abbr class=3D"abbrev">RFC1183</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">C.F.</span> <span class=3D=
"surname">Everhart</span>, <span class=3D"firstname">L. A.</span> <span cla=
ss=3D"surname">Mamakos</span>, <span class=3D"firstname">R.</span> <span cl=
ass=3D"surname">Ullmann</span>, and <span class=3D"firstname">P.</span> <sp=
an class=3D"surname">Mockapetris</span>. </span><span class=3D"title"><i>Ne=
w <acronym class=3D"acronym">DNS</acronym> RR Definitions</i>. </span><span=
 class=3D"pubdate">October 1990. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604909"></a><p>[<abbr class=3D"abbrev">RFC1706</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Manning</span> and <span class=3D"firstname">R.</span> <span class=
=3D"surname">Colella</span>. </span><span class=3D"title"><i><acronym class=
=3D"acronym">DNS</acronym> NSAP Resource Records</i>. </span><span class=3D=
"pubdate">October 1994. </span></p>
+<a name=3D"id2604996"></a><p>[<abbr class=3D"abbrev">RFC1706</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Manning</span> and <span class=3D"firstname">R.</span> <span class=
=3D"surname">Colella</span>. </span><span class=3D"title"><i><acronym class=
=3D"acronym">DNS</acronym> NSAP Resource Records</i>. </span><span class=3D=
"pubdate">October 1994. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604947"></a><p>[<abbr class=3D"abbrev">RFC2168</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Daniel</span> and <span class=3D"firstname">M.</span> <span class=
=3D"surname">Mealling</span>. </span><span class=3D"title"><i>Resolution of=
 Uniform Resource Identifiers using
+<a name=3D"id2605033"></a><p>[<abbr class=3D"abbrev">RFC2168</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">R.</span> <span class=3D"s=
urname">Daniel</span> and <span class=3D"firstname">M.</span> <span class=
=3D"surname">Mealling</span>. </span><span class=3D"title"><i>Resolution of=
 Uniform Resource Identifiers using
                   the Domain Name System</i>. </span><span class=3D"pubdat=
e">June 1997. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2604982"></a><p>[<abbr class=3D"abbrev">RFC1876</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">C.</span> <span class=3D"s=
urname">Davis</span>, <span class=3D"firstname">P.</span> <span class=3D"su=
rname">Vixie</span>, <span class=3D"firstname">T.</span>, and <span class=
=3D"firstname">I.</span> <span class=3D"surname">Dickinson</span>. </span><=
span class=3D"title"><i>A Means for Expressing Location Information in the
+<a name=3D"id2605137"></a><p>[<abbr class=3D"abbrev">RFC1876</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">C.</span> <span class=3D"s=
urname">Davis</span>, <span class=3D"firstname">P.</span> <span class=3D"su=
rname">Vixie</span>, <span class=3D"firstname">T.</span>, and <span class=
=3D"firstname">I.</span> <span class=3D"surname">Dickinson</span>. </span><=
span class=3D"title"><i>A Means for Expressing Location Information in the
                   Domain
                   Name System</i>. </span><span class=3D"pubdate">January =
1996. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605036"></a><p>[<abbr class=3D"abbrev">RFC2052</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Gulbrandsen</span> and <span class=3D"firstname">P.</span> <span cl=
ass=3D"surname">Vixie</span>. </span><span class=3D"title"><i>A <acronym cl=
ass=3D"acronym">DNS</acronym> RR for Specifying the
+<a name=3D"id2605191"></a><p>[<abbr class=3D"abbrev">RFC2052</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Gulbrandsen</span> and <span class=3D"firstname">P.</span> <span cl=
ass=3D"surname">Vixie</span>. </span><span class=3D"title"><i>A <acronym cl=
ass=3D"acronym">DNS</acronym> RR for Specifying the
                   Location of
                   Services.</i>. </span><span class=3D"pubdate">October 19=
96. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605075"></a><p>[<abbr class=3D"abbrev">RFC2163</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Allocchio</span>. </span><span class=3D"title"><i>Using the Internet <ac=
ronym class=3D"acronym">DNS</acronym> to
+<a name=3D"id2605229"></a><p>[<abbr class=3D"abbrev">RFC2163</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Allocchio</span>. </span><span class=3D"title"><i>Using the Internet <ac=
ronym class=3D"acronym">DNS</acronym> to
                   Distribute MIXER
                   Conformant Global Address Mapping</i>. </span><span clas=
s=3D"pubdate">January 1998. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605100"></a><p>[<abbr class=3D"abbrev">RFC2230</abbr>] <span=
 class=3D"author"><span class=3D"firstname">R.</span> <span class=3D"surnam=
e">Atkinson</span>. </span><span class=3D"title"><i>Key Exchange Delegation=
 Record for the <acronym class=3D"acronym">DNS</acronym></i>. </span><span =
class=3D"pubdate">October 1997. </span></p>
+<a name=3D"id2605255"></a><p>[<abbr class=3D"abbrev">RFC2230</abbr>] <span=
 class=3D"author"><span class=3D"firstname">R.</span> <span class=3D"surnam=
e">Atkinson</span>. </span><span class=3D"title"><i>Key Exchange Delegation=
 Record for the <acronym class=3D"acronym">DNS</acronym></i>. </span><span =
class=3D"pubdate">October 1997. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605126"></a><p>[<abbr class=3D"abbrev">RFC2536</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>DSA KEYs and SIGs in the Domain Name System (DNS)</i>. </span=
><span class=3D"pubdate">March 1999. </span></p>
+<a name=3D"id2605281"></a><p>[<abbr class=3D"abbrev">RFC2536</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>DSA KEYs and SIGs in the Domain Name System (DNS)</i>. </span=
><span class=3D"pubdate">March 1999. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605153"></a><p>[<abbr class=3D"abbrev">RFC2537</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>RSA/MD5 KEYs and SIGs in the Domain Name System (DNS)</i>. </=
span><span class=3D"pubdate">March 1999. </span></p>
+<a name=3D"id2605307"></a><p>[<abbr class=3D"abbrev">RFC2537</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>RSA/MD5 KEYs and SIGs in the Domain Name System (DNS)</i>. </=
span><span class=3D"pubdate">March 1999. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605179"></a><p>[<abbr class=3D"abbrev">RFC2538</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span> and <span class=
=3D"firstname">O.</span> <span class=3D"surname">Gudmundsson</span>. </span=
><span class=3D"title"><i>Storing Certificates in the Domain Name System (D=
NS)</i>. </span><span class=3D"pubdate">March 1999. </span></p>
+<a name=3D"id2605334"></a><p>[<abbr class=3D"abbrev">RFC2538</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span> and <span class=
=3D"firstname">O.</span> <span class=3D"surname">Gudmundsson</span>. </span=
><span class=3D"title"><i>Storing Certificates in the Domain Name System (D=
NS)</i>. </span><span class=3D"pubdate">March 1999. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605219"></a><p>[<abbr class=3D"abbrev">RFC2539</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Storage of Diffie-Hellman Keys in the Domain Name System =
(DNS)</i>. </span><span class=3D"pubdate">March 1999. </span></p>
+<a name=3D"id2605373"></a><p>[<abbr class=3D"abbrev">RFC2539</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Storage of Diffie-Hellman Keys in the Domain Name System =
(DNS)</i>. </span><span class=3D"pubdate">March 1999. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605249"></a><p>[<abbr class=3D"abbrev">RFC2540</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Detached Domain Name System (DNS) Information</i>. </span=
><span class=3D"pubdate">March 1999. </span></p>
+<a name=3D"id2605403"></a><p>[<abbr class=3D"abbrev">RFC2540</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Detached Domain Name System (DNS) Information</i>. </span=
><span class=3D"pubdate">March 1999. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605278"></a><p>[<abbr class=3D"abbrev">RFC2782</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Gulbrandsen</span>. </span><span class=3D"author"><span class=3D"firstna=
me">P.</span> <span class=3D"surname">Vixie</span>. </span><span class=3D"a=
uthor"><span class=3D"firstname">L.</span> <span class=3D"surname">Esibov</=
span>. </span><span class=3D"title"><i>A DNS RR for specifying the location=
 of services (DNS SRV)</i>. </span><span class=3D"pubdate">February 2000. <=
/span></p>
+<a name=3D"id2605433"></a><p>[<abbr class=3D"abbrev">RFC2782</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Gulbrandsen</span>. </span><span class=3D"author"><span class=3D"firstna=
me">P.</span> <span class=3D"surname">Vixie</span>. </span><span class=3D"a=
uthor"><span class=3D"firstname">L.</span> <span class=3D"surname">Esibov</=
span>. </span><span class=3D"title"><i>A DNS RR for specifying the location=
 of services (DNS SRV)</i>. </span><span class=3D"pubdate">February 2000. <=
/span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605321"></a><p>[<abbr class=3D"abbrev">RFC2915</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Mealling</span>. </span><span class=3D"author"><span class=3D"firstname"=
>R.</span> <span class=3D"surname">Daniel</span>. </span><span class=3D"tit=
le"><i>The Naming Authority Pointer (NAPTR) DNS Resource Record</i>. </span=
><span class=3D"pubdate">September 2000. </span></p>
+<a name=3D"id2605476"></a><p>[<abbr class=3D"abbrev">RFC2915</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Mealling</span>. </span><span class=3D"author"><span class=3D"firstname"=
>R.</span> <span class=3D"surname">Daniel</span>. </span><span class=3D"tit=
le"><i>The Naming Authority Pointer (NAPTR) DNS Resource Record</i>. </span=
><span class=3D"pubdate">September 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605354"></a><p>[<abbr class=3D"abbrev">RFC3110</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>RSA/SHA-1 SIGs and RSA KEYs in the Domain Name System (DNS)</=
i>. </span><span class=3D"pubdate">May 2001. </span></p>
+<a name=3D"id2605509"></a><p>[<abbr class=3D"abbrev">RFC3110</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>RSA/SHA-1 SIGs and RSA KEYs in the Domain Name System (DNS)</=
i>. </span><span class=3D"pubdate">May 2001. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605381"></a><p>[<abbr class=3D"abbrev">RFC3123</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.</span> <span class=3D"surnam=
e">Koch</span>. </span><span class=3D"title"><i>A DNS RR Type for Lists of =
Address Prefixes (APL RR)</i>. </span><span class=3D"pubdate">June 2001. </=
span></p>
+<a name=3D"id2605536"></a><p>[<abbr class=3D"abbrev">RFC3123</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.</span> <span class=3D"surnam=
e">Koch</span>. </span><span class=3D"title"><i>A DNS RR Type for Lists of =
Address Prefixes (APL RR)</i>. </span><span class=3D"pubdate">June 2001. </=
span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605473"></a><p>[<abbr class=3D"abbrev">RFC3596</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">S.</span> <span class=3D"s=
urname">Thomson</span>, <span class=3D"firstname">C.</span> <span class=3D"=
surname">Huitema</span>, <span class=3D"firstname">V.</span> <span class=3D=
"surname">Ksinant</span>, and <span class=3D"firstname">M.</span> <span cla=
ss=3D"surname">Souissi</span>. </span><span class=3D"title"><i><acronym cla=
ss=3D"acronym">DNS</acronym> Extensions to support IP
+<a name=3D"id2605559"></a><p>[<abbr class=3D"abbrev">RFC3596</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">S.</span> <span class=3D"s=
urname">Thomson</span>, <span class=3D"firstname">C.</span> <span class=3D"=
surname">Huitema</span>, <span class=3D"firstname">V.</span> <span class=3D=
"surname">Ksinant</span>, and <span class=3D"firstname">M.</span> <span cla=
ss=3D"surname">Souissi</span>. </span><span class=3D"title"><i><acronym cla=
ss=3D"acronym">DNS</acronym> Extensions to support IP
                   version 6</i>. </span><span class=3D"pubdate">October 20=
03. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605530"></a><p>[<abbr class=3D"abbrev">RFC3597</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Gustafsson</span>. </span><span class=3D"title"><i>Handling of Unknown D=
NS Resource Record (RR) Types</i>. </span><span class=3D"pubdate">September=
 2003. </span></p>
+<a name=3D"id2605617"></a><p>[<abbr class=3D"abbrev">RFC3597</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Gustafsson</span>. </span><span class=3D"title"><i>Handling of Unknown D=
NS Resource Record (RR) Types</i>. </span><span class=3D"pubdate">September=
 2003. </span></p>
 </div>
 </div>
 <div class=3D"bibliodiv">
 <h3 class=3D"title">
 <acronym class=3D"acronym">DNS</acronym> and the Internet</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2605562"></a><p>[<abbr class=3D"abbrev">RFC1101</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P. V.</span> <span class=3D"sur=
name">Mockapetris</span>. </span><span class=3D"title"><i><acronym class=3D=
"acronym">DNS</acronym> Encoding of Network Names
+<a name=3D"id2605649"></a><p>[<abbr class=3D"abbrev">RFC1101</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P. V.</span> <span class=3D"sur=
name">Mockapetris</span>. </span><span class=3D"title"><i><acronym class=3D=
"acronym">DNS</acronym> Encoding of Network Names
                   and Other Types</i>. </span><span class=3D"pubdate">Apri=
l 1989. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605588"></a><p>[<abbr class=3D"abbrev">RFC1123</abbr>] <span=
 class=3D"author"><span class=3D"surname">Braden</span>. </span><span class=
=3D"title"><i>Requirements for Internet Hosts - Application and
+<a name=3D"id2605674"></a><p>[<abbr class=3D"abbrev">RFC1123</abbr>] <span=
 class=3D"author"><span class=3D"surname">Braden</span>. </span><span class=
=3D"title"><i>Requirements for Internet Hosts - Application and
                   Support</i>. </span><span class=3D"pubdate">October 1989=
. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605610"></a><p>[<abbr class=3D"abbrev">RFC1591</abbr>] <span=
 class=3D"author"><span class=3D"firstname">J.</span> <span class=3D"surnam=
e">Postel</span>. </span><span class=3D"title"><i>Domain Name System Struct=
ure and Delegation</i>. </span><span class=3D"pubdate">March 1994. </span><=
/p>
+<a name=3D"id2605697"></a><p>[<abbr class=3D"abbrev">RFC1591</abbr>] <span=
 class=3D"author"><span class=3D"firstname">J.</span> <span class=3D"surnam=
e">Postel</span>. </span><span class=3D"title"><i>Domain Name System Struct=
ure and Delegation</i>. </span><span class=3D"pubdate">March 1994. </span><=
/p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605634"></a><p>[<abbr class=3D"abbrev">RFC2317</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">H.</span> <span class=3D"s=
urname">Eidnes</span>, <span class=3D"firstname">G.</span> <span class=3D"s=
urname">de Groot</span>, and <span class=3D"firstname">P.</span> <span clas=
s=3D"surname">Vixie</span>. </span><span class=3D"title"><i>Classless IN-AD=
DR.ARPA Delegation</i>. </span><span class=3D"pubdate">March 1998. </span><=
/p>
+<a name=3D"id2605720"></a><p>[<abbr class=3D"abbrev">RFC2317</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">H.</span> <span class=3D"s=
urname">Eidnes</span>, <span class=3D"firstname">G.</span> <span class=3D"s=
urname">de Groot</span>, and <span class=3D"firstname">P.</span> <span clas=
s=3D"surname">Vixie</span>. </span><span class=3D"title"><i>Classless IN-AD=
DR.ARPA Delegation</i>. </span><span class=3D"pubdate">March 1998. </span><=
/p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605680"></a><p>[<abbr class=3D"abbrev">RFC2826</abbr>] <span=
 class=3D"authorgroup"><span class=3D"surname">Internet Architecture Board<=
/span>. </span><span class=3D"title"><i>IAB Technical Comment on the Unique=
 DNS Root</i>. </span><span class=3D"pubdate">May 2000. </span></p>
+<a name=3D"id2605766"></a><p>[<abbr class=3D"abbrev">RFC2826</abbr>] <span=
 class=3D"authorgroup"><span class=3D"surname">Internet Architecture Board<=
/span>. </span><span class=3D"title"><i>IAB Technical Comment on the Unique=
 DNS Root</i>. </span><span class=3D"pubdate">May 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605703"></a><p>[<abbr class=3D"abbrev">RFC2929</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>, <span class=3D=
"firstname">E.</span> <span class=3D"surname">Brunner-Williams</span>, and =
<span class=3D"firstname">B.</span> <span class=3D"surname">Manning</span>.=
 </span><span class=3D"title"><i>Domain Name System (DNS) IANA Consideratio=
ns</i>. </span><span class=3D"pubdate">September 2000. </span></p>
+<a name=3D"id2605789"></a><p>[<abbr class=3D"abbrev">RFC2929</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>, <span class=3D=
"firstname">E.</span> <span class=3D"surname">Brunner-Williams</span>, and =
<span class=3D"firstname">B.</span> <span class=3D"surname">Manning</span>.=
 </span><span class=3D"title"><i>Domain Name System (DNS) IANA Consideratio=
ns</i>. </span><span class=3D"pubdate">September 2000. </span></p>
 </div>
 </div>
 <div class=3D"bibliodiv">
 <h3 class=3D"title">
 <acronym class=3D"acronym">DNS</acronym> Operations</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2605761"></a><p>[<abbr class=3D"abbrev">RFC1033</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Lottor</span>. </span><span class=3D"title"><i>Domain administrators ope=
rations guide.</i>. </span><span class=3D"pubdate">November 1987. </span></=
p>
+<a name=3D"id2605847"></a><p>[<abbr class=3D"abbrev">RFC1033</abbr>] <span=
 class=3D"author"><span class=3D"firstname">M.</span> <span class=3D"surnam=
e">Lottor</span>. </span><span class=3D"title"><i>Domain administrators ope=
rations guide.</i>. </span><span class=3D"pubdate">November 1987. </span></=
p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605784"></a><p>[<abbr class=3D"abbrev">RFC1537</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.</span> <span class=3D"surnam=
e">Beertema</span>. </span><span class=3D"title"><i>Common <acronym class=
=3D"acronym">DNS</acronym> Data File
+<a name=3D"id2605870"></a><p>[<abbr class=3D"abbrev">RFC1537</abbr>] <span=
 class=3D"author"><span class=3D"firstname">P.</span> <span class=3D"surnam=
e">Beertema</span>. </span><span class=3D"title"><i>Common <acronym class=
=3D"acronym">DNS</acronym> Data File
                   Configuration Errors</i>. </span><span class=3D"pubdate"=
>October 1993. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605811"></a><p>[<abbr class=3D"abbrev">RFC1912</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Barr</span>. </span><span class=3D"title"><i>Common <acronym class=3D"ac=
ronym">DNS</acronym> Operational and
+<a name=3D"id2605897"></a><p>[<abbr class=3D"abbrev">RFC1912</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Barr</span>. </span><span class=3D"title"><i>Common <acronym class=3D"ac=
ronym">DNS</acronym> Operational and
                   Configuration Errors</i>. </span><span class=3D"pubdate"=
>February 1996. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605837"></a><p>[<abbr class=3D"abbrev">RFC2010</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Manning</span> and <span class=3D"firstname">P.</span> <span class=
=3D"surname">Vixie</span>. </span><span class=3D"title"><i>Operational Crit=
eria for Root Name Servers.</i>. </span><span class=3D"pubdate">October 199=
6. </span></p>
+<a name=3D"id2605924"></a><p>[<abbr class=3D"abbrev">RFC2010</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Manning</span> and <span class=3D"firstname">P.</span> <span class=
=3D"surname">Vixie</span>. </span><span class=3D"title"><i>Operational Crit=
eria for Root Name Servers.</i>. </span><span class=3D"pubdate">October 199=
6. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605874"></a><p>[<abbr class=3D"abbrev">RFC2219</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Hamilton</span> and <span class=3D"firstname">R.</span> <span class=
=3D"surname">Wright</span>. </span><span class=3D"title"><i>Use of <acronym=
 class=3D"acronym">DNS</acronym> Aliases for
+<a name=3D"id2605960"></a><p>[<abbr class=3D"abbrev">RFC2219</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Hamilton</span> and <span class=3D"firstname">R.</span> <span class=
=3D"surname">Wright</span>. </span><span class=3D"title"><i>Use of <acronym=
 class=3D"acronym">DNS</acronym> Aliases for
                   Network Services.</i>. </span><span class=3D"pubdate">Oc=
tober 1997. </span></p>
 </div>
 </div>
 <div class=3D"bibliodiv">
 <h3 class=3D"title">Internationalized Domain Names</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2605920"></a><p>[<abbr class=3D"abbrev">RFC2825</abbr>] <span=
 class=3D"authorgroup"><span class=3D"surname">IAB</span> and <span class=
=3D"firstname">R.</span> <span class=3D"surname">Daigle</span>. </span><spa=
n class=3D"title"><i>A Tangled Web: Issues of I18N, Domain Names,
+<a name=3D"id2606006"></a><p>[<abbr class=3D"abbrev">RFC2825</abbr>] <span=
 class=3D"authorgroup"><span class=3D"surname">IAB</span> and <span class=
=3D"firstname">R.</span> <span class=3D"surname">Daigle</span>. </span><spa=
n class=3D"title"><i>A Tangled Web: Issues of I18N, Domain Names,
                        and the Other Internet protocols</i>. </span><span =
class=3D"pubdate">May 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605952"></a><p>[<abbr class=3D"abbrev">RFC3490</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Faltstrom</span>, <span class=3D"firstname">P.</span> <span class=
=3D"surname">Hoffman</span>, and <span class=3D"firstname">A.</span> <span =
class=3D"surname">Costello</span>. </span><span class=3D"title"><i>Internat=
ionalizing Domain Names in Applications (IDNA)</i>. </span><span class=3D"p=
ubdate">March 2003. </span></p>
+<a name=3D"id2606038"></a><p>[<abbr class=3D"abbrev">RFC3490</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Faltstrom</span>, <span class=3D"firstname">P.</span> <span class=
=3D"surname">Hoffman</span>, and <span class=3D"firstname">A.</span> <span =
class=3D"surname">Costello</span>. </span><span class=3D"title"><i>Internat=
ionalizing Domain Names in Applications (IDNA)</i>. </span><span class=3D"p=
ubdate">March 2003. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2605997"></a><p>[<abbr class=3D"abbrev">RFC3491</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Hoffman</span> and <span class=3D"firstname">M.</span> <span class=
=3D"surname">Blanchet</span>. </span><span class=3D"title"><i>Nameprep: A S=
tringprep Profile for Internationalized Domain Names</i>. </span><span clas=
s=3D"pubdate">March 2003. </span></p>
+<a name=3D"id2606084"></a><p>[<abbr class=3D"abbrev">RFC3491</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">P.</span> <span class=3D"s=
urname">Hoffman</span> and <span class=3D"firstname">M.</span> <span class=
=3D"surname">Blanchet</span>. </span><span class=3D"title"><i>Nameprep: A S=
tringprep Profile for Internationalized Domain Names</i>. </span><span clas=
s=3D"pubdate">March 2003. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606033"></a><p>[<abbr class=3D"abbrev">RFC3492</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Costello</span>. </span><span class=3D"title"><i>Punycode: A Bootst=
ring encoding of Unicode
+<a name=3D"id2606119"></a><p>[<abbr class=3D"abbrev">RFC3492</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Costello</span>. </span><span class=3D"title"><i>Punycode: A Bootst=
ring encoding of Unicode
                        for Internationalized Domain Names in
                        Applications (IDNA)</i>. </span><span class=3D"pubd=
ate">March 2003. </span></p>
 </div>
@@ -497,47 +497,47 @@
                 </p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606077"></a><p>[<abbr class=3D"abbrev">RFC1464</abbr>] <span=
 class=3D"author"><span class=3D"firstname">R.</span> <span class=3D"surnam=
e">Rosenbaum</span>. </span><span class=3D"title"><i>Using the Domain Name =
System To Store Arbitrary String
+<a name=3D"id2606164"></a><p>[<abbr class=3D"abbrev">RFC1464</abbr>] <span=
 class=3D"author"><span class=3D"firstname">R.</span> <span class=3D"surnam=
e">Rosenbaum</span>. </span><span class=3D"title"><i>Using the Domain Name =
System To Store Arbitrary String
                   Attributes</i>. </span><span class=3D"pubdate">May 1993.=
 </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606100"></a><p>[<abbr class=3D"abbrev">RFC1713</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Romao</span>. </span><span class=3D"title"><i>Tools for <acronym class=
=3D"acronym">DNS</acronym> Debugging</i>. </span><span class=3D"pubdate">No=
vember 1994. </span></p>
+<a name=3D"id2606186"></a><p>[<abbr class=3D"abbrev">RFC1713</abbr>] <span=
 class=3D"author"><span class=3D"firstname">A.</span> <span class=3D"surnam=
e">Romao</span>. </span><span class=3D"title"><i>Tools for <acronym class=
=3D"acronym">DNS</acronym> Debugging</i>. </span><span class=3D"pubdate">No=
vember 1994. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606125"></a><p>[<abbr class=3D"abbrev">RFC1794</abbr>] <span=
 class=3D"author"><span class=3D"firstname">T.</span> <span class=3D"surnam=
e">Brisco</span>. </span><span class=3D"title"><i><acronym class=3D"acronym=
">DNS</acronym> Support for Load
+<a name=3D"id2606212"></a><p>[<abbr class=3D"abbrev">RFC1794</abbr>] <span=
 class=3D"author"><span class=3D"firstname">T.</span> <span class=3D"surnam=
e">Brisco</span>. </span><span class=3D"title"><i><acronym class=3D"acronym=
">DNS</acronym> Support for Load
                   Balancing</i>. </span><span class=3D"pubdate">April 1995=
. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606151"></a><p>[<abbr class=3D"abbrev">RFC2240</abbr>] <span=
 class=3D"author"><span class=3D"firstname">O.</span> <span class=3D"surnam=
e">Vaughan</span>. </span><span class=3D"title"><i>A Legal Basis for Domain=
 Name Allocation</i>. </span><span class=3D"pubdate">November 1997. </span>=
</p>
+<a name=3D"id2606306"></a><p>[<abbr class=3D"abbrev">RFC2240</abbr>] <span=
 class=3D"author"><span class=3D"firstname">O.</span> <span class=3D"surnam=
e">Vaughan</span>. </span><span class=3D"title"><i>A Legal Basis for Domain=
 Name Allocation</i>. </span><span class=3D"pubdate">November 1997. </span>=
</p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606174"></a><p>[<abbr class=3D"abbrev">RFC2345</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">J.</span> <span class=3D"s=
urname">Klensin</span>, <span class=3D"firstname">T.</span> <span class=3D"=
surname">Wolf</span>, and <span class=3D"firstname">G.</span> <span class=
=3D"surname">Oglesby</span>. </span><span class=3D"title"><i>Domain Names a=
nd Company Name Retrieval</i>. </span><span class=3D"pubdate">May 1998. </s=
pan></p>
+<a name=3D"id2606329"></a><p>[<abbr class=3D"abbrev">RFC2345</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">J.</span> <span class=3D"s=
urname">Klensin</span>, <span class=3D"firstname">T.</span> <span class=3D"=
surname">Wolf</span>, and <span class=3D"firstname">G.</span> <span class=
=3D"surname">Oglesby</span>. </span><span class=3D"title"><i>Domain Names a=
nd Company Name Retrieval</i>. </span><span class=3D"pubdate">May 1998. </s=
pan></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606220"></a><p>[<abbr class=3D"abbrev">RFC2352</abbr>] <span=
 class=3D"author"><span class=3D"firstname">O.</span> <span class=3D"surnam=
e">Vaughan</span>. </span><span class=3D"title"><i>A Convention For Using L=
egal Names as Domain Names</i>. </span><span class=3D"pubdate">May 1998. </=
span></p>
+<a name=3D"id2606375"></a><p>[<abbr class=3D"abbrev">RFC2352</abbr>] <span=
 class=3D"author"><span class=3D"firstname">O.</span> <span class=3D"surnam=
e">Vaughan</span>. </span><span class=3D"title"><i>A Convention For Using L=
egal Names as Domain Names</i>. </span><span class=3D"pubdate">May 1998. </=
span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606244"></a><p>[<abbr class=3D"abbrev">RFC3071</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">J.</span> <span class=3D"s=
urname">Klensin</span>. </span><span class=3D"title"><i>Reflections on the =
DNS, RFC 1591, and Categories of Domains</i>. </span><span class=3D"pubdate=
">February 2001. </span></p>
+<a name=3D"id2606398"></a><p>[<abbr class=3D"abbrev">RFC3071</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">J.</span> <span class=3D"s=
urname">Klensin</span>. </span><span class=3D"title"><i>Reflections on the =
DNS, RFC 1591, and Categories of Domains</i>. </span><span class=3D"pubdate=
">February 2001. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606270"></a><p>[<abbr class=3D"abbrev">RFC3258</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">T.</span> <span class=3D"s=
urname">Hardie</span>. </span><span class=3D"title"><i>Distributing Authori=
tative Name Servers via
+<a name=3D"id2606425"></a><p>[<abbr class=3D"abbrev">RFC3258</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">T.</span> <span class=3D"s=
urname">Hardie</span>. </span><span class=3D"title"><i>Distributing Authori=
tative Name Servers via
                        Shared Unicast Addresses</i>. </span><span class=3D=
"pubdate">April 2002. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606296"></a><p>[<abbr class=3D"abbrev">RFC3901</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Durand</span> and <span class=3D"firstname">J.</span> <span class=
=3D"surname">Ihren</span>. </span><span class=3D"title"><i>DNS IPv6 Transpo=
rt Operational Guidelines</i>. </span><span class=3D"pubdate">September 200=
4. </span></p>
+<a name=3D"id2606451"></a><p>[<abbr class=3D"abbrev">RFC3901</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">A.</span> <span class=3D"s=
urname">Durand</span> and <span class=3D"firstname">J.</span> <span class=
=3D"surname">Ihren</span>. </span><span class=3D"title"><i>DNS IPv6 Transpo=
rt Operational Guidelines</i>. </span><span class=3D"pubdate">September 200=
4. </span></p>
 </div>
 </div>
 <div class=3D"bibliodiv">
 <h3 class=3D"title">Obsolete and Unimplemented Experimental RFC</h3>
 <div class=3D"biblioentry">
-<a name=3D"id2606340"></a><p>[<abbr class=3D"abbrev">RFC1712</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">C.</span> <span class=3D"s=
urname">Farrell</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Schulze</span>, <span class=3D"firstname">S.</span> <span class=3D=
"surname">Pleitner</span>, and <span class=3D"firstname">D.</span> <span cl=
ass=3D"surname">Baldoni</span>. </span><span class=3D"title"><i><acronym cl=
ass=3D"acronym">DNS</acronym> Encoding of Geographical
+<a name=3D"id2606494"></a><p>[<abbr class=3D"abbrev">RFC1712</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">C.</span> <span class=3D"s=
urname">Farrell</span>, <span class=3D"firstname">M.</span> <span class=3D"=
surname">Schulze</span>, <span class=3D"firstname">S.</span> <span class=3D=
"surname">Pleitner</span>, and <span class=3D"firstname">D.</span> <span cl=
ass=3D"surname">Baldoni</span>. </span><span class=3D"title"><i><acronym cl=
ass=3D"acronym">DNS</acronym> Encoding of Geographical
                   Location</i>. </span><span class=3D"pubdate">November 19=
94. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606397"></a><p>[<abbr class=3D"abbrev">RFC2673</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Crawford</span>. </span><span class=3D"title"><i>Binary Labels in t=
he Domain Name System</i>. </span><span class=3D"pubdate">August 1999. </sp=
an></p>
+<a name=3D"id2606552"></a><p>[<abbr class=3D"abbrev">RFC2673</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Crawford</span>. </span><span class=3D"title"><i>Binary Labels in t=
he Domain Name System</i>. </span><span class=3D"pubdate">August 1999. </sp=
an></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606424"></a><p>[<abbr class=3D"abbrev">RFC2874</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Crawford</span> and <span class=3D"firstname">C.</span> <span class=
=3D"surname">Huitema</span>. </span><span class=3D"title"><i>DNS Extensions=
 to Support IPv6 Address Aggregation
+<a name=3D"id2606579"></a><p>[<abbr class=3D"abbrev">RFC2874</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">M.</span> <span class=3D"s=
urname">Crawford</span> and <span class=3D"firstname">C.</span> <span class=
=3D"surname">Huitema</span>. </span><span class=3D"title"><i>DNS Extensions=
 to Support IPv6 Address Aggregation
                        and Renumbering</i>. </span><span class=3D"pubdate"=
>July 2000. </span></p>
 </div>
 </div>
@@ -551,39 +551,39 @@
                 </p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606472"></a><p>[<abbr class=3D"abbrev">RFC2065</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span> and <span class=
=3D"firstname">C.</span> <span class=3D"surname">Kaufman</span>. </span><sp=
an class=3D"title"><i>Domain Name System Security Extensions</i>. </span><s=
pan class=3D"pubdate">January 1997. </span></p>
+<a name=3D"id2606695"></a><p>[<abbr class=3D"abbrev">RFC2065</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span> and <span class=
=3D"firstname">C.</span> <span class=3D"surname">Kaufman</span>. </span><sp=
an class=3D"title"><i>Domain Name System Security Extensions</i>. </span><s=
pan class=3D"pubdate">January 1997. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606512"></a><p>[<abbr class=3D"abbrev">RFC2137</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>Secure Domain Name System Dynamic Update</i>. </span><span cl=
ass=3D"pubdate">April 1997. </span></p>
+<a name=3D"id2606734"></a><p>[<abbr class=3D"abbrev">RFC2137</abbr>] <span=
 class=3D"author"><span class=3D"firstname">D.</span> <span class=3D"surnam=
e">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span class=
=3D"title"><i>Secure Domain Name System Dynamic Update</i>. </span><span cl=
ass=3D"pubdate">April 1997. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606538"></a><p>[<abbr class=3D"abbrev">RFC2535</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Domain Name System Security Extensions</i>. </span><span =
class=3D"pubdate">March 1999. </span></p>
+<a name=3D"id2606761"></a><p>[<abbr class=3D"abbrev">RFC2535</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Eastlake</span>, <span class=3D"lineage">3rd</span>. </span><span c=
lass=3D"title"><i>Domain Name System Security Extensions</i>. </span><span =
class=3D"pubdate">March 1999. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606568"></a><p>[<abbr class=3D"abbrev">RFC3008</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Wellington</span>. </span><span class=3D"title"><i>Domain Name Syst=
em Security (DNSSEC)
+<a name=3D"id2606791"></a><p>[<abbr class=3D"abbrev">RFC3008</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Wellington</span>. </span><span class=3D"title"><i>Domain Name Syst=
em Security (DNSSEC)
                        Signing Authority</i>. </span><span class=3D"pubdat=
e">November 2000. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606594"></a><p>[<abbr class=3D"abbrev">RFC3090</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">E.</span> <span class=3D"s=
urname">Lewis</span>. </span><span class=3D"title"><i>DNS Security Extensio=
n Clarification on Zone Status</i>. </span><span class=3D"pubdate">March 20=
01. </span></p>
+<a name=3D"id2606817"></a><p>[<abbr class=3D"abbrev">RFC3090</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">E.</span> <span class=3D"s=
urname">Lewis</span>. </span><span class=3D"title"><i>DNS Security Extensio=
n Clarification on Zone Status</i>. </span><span class=3D"pubdate">March 20=
01. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606620"></a><p>[<abbr class=3D"abbrev">RFC3445</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Massey</span> and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>Limiting the Scop=
e of the KEY Resource Record (RR)</i>. </span><span class=3D"pubdate">Decem=
ber 2002. </span></p>
+<a name=3D"id2606843"></a><p>[<abbr class=3D"abbrev">RFC3445</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">D.</span> <span class=3D"s=
urname">Massey</span> and <span class=3D"firstname">S.</span> <span class=
=3D"surname">Rose</span>. </span><span class=3D"title"><i>Limiting the Scop=
e of the KEY Resource Record (RR)</i>. </span><span class=3D"pubdate">Decem=
ber 2002. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606657"></a><p>[<abbr class=3D"abbrev">RFC3655</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Wellington</span> and <span class=3D"firstname">O.</span> <span cla=
ss=3D"surname">Gudmundsson</span>. </span><span class=3D"title"><i>Redefini=
tion of DNS Authenticated Data (AD) bit</i>. </span><span class=3D"pubdate"=
>November 2003. </span></p>
+<a name=3D"id2606880"></a><p>[<abbr class=3D"abbrev">RFC3655</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">B.</span> <span class=3D"s=
urname">Wellington</span> and <span class=3D"firstname">O.</span> <span cla=
ss=3D"surname">Gudmundsson</span>. </span><span class=3D"title"><i>Redefini=
tion of DNS Authenticated Data (AD) bit</i>. </span><span class=3D"pubdate"=
>November 2003. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606693"></a><p>[<abbr class=3D"abbrev">RFC3658</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">O.</span> <span class=3D"s=
urname">Gudmundsson</span>. </span><span class=3D"title"><i>Delegation Sign=
er (DS) Resource Record (RR)</i>. </span><span class=3D"pubdate">December 2=
003. </span></p>
+<a name=3D"id2606916"></a><p>[<abbr class=3D"abbrev">RFC3658</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">O.</span> <span class=3D"s=
urname">Gudmundsson</span>. </span><span class=3D"title"><i>Delegation Sign=
er (DS) Resource Record (RR)</i>. </span><span class=3D"pubdate">December 2=
003. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606720"></a><p>[<abbr class=3D"abbrev">RFC3755</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">S.</span> <span class=3D"s=
urname">Weiler</span>. </span><span class=3D"title"><i>Legacy Resolver Comp=
atibility for Delegation Signer (DS)</i>. </span><span class=3D"pubdate">Ma=
y 2004. </span></p>
+<a name=3D"id2606942"></a><p>[<abbr class=3D"abbrev">RFC3755</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">S.</span> <span class=3D"s=
urname">Weiler</span>. </span><span class=3D"title"><i>Legacy Resolver Comp=
atibility for Delegation Signer (DS)</i>. </span><span class=3D"pubdate">Ma=
y 2004. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606746"></a><p>[<abbr class=3D"abbrev">RFC3757</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">O.</span> <span class=3D"s=
urname">Kolkman</span>, <span class=3D"firstname">J.</span> <span class=3D"=
surname">Schlyter</span>, and <span class=3D"firstname">E.</span> <span cla=
ss=3D"surname">Lewis</span>. </span><span class=3D"title"><i>Domain Name Sy=
stem KEY (DNSKEY) Resource Record
+<a name=3D"id2607037"></a><p>[<abbr class=3D"abbrev">RFC3757</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">O.</span> <span class=3D"s=
urname">Kolkman</span>, <span class=3D"firstname">J.</span> <span class=3D"=
surname">Schlyter</span>, and <span class=3D"firstname">E.</span> <span cla=
ss=3D"surname">Lewis</span>. </span><span class=3D"title"><i>Domain Name Sy=
stem KEY (DNSKEY) Resource Record
                       (RR) Secure Entry Point (SEP) Flag</i>. </span><span=
 class=3D"pubdate">April 2004. </span></p>
 </div>
 <div class=3D"biblioentry">
-<a name=3D"id2606791"></a><p>[<abbr class=3D"abbrev">RFC3845</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">J.</span> <span class=3D"s=
urname">Schlyter</span>. </span><span class=3D"title"><i>DNS Security (DNSS=
EC) NextSECure (NSEC) RDATA Format</i>. </span><span class=3D"pubdate">Augu=
st 2004. </span></p>
+<a name=3D"id2607082"></a><p>[<abbr class=3D"abbrev">RFC3845</abbr>] <span=
 class=3D"authorgroup"><span class=3D"firstname">J.</span> <span class=3D"s=
urname">Schlyter</span>. </span><span class=3D"title"><i>DNS Security (DNSS=
EC) NextSECure (NSEC) RDATA Format</i>. </span><span class=3D"pubdate">Augu=
st 2004. </span></p>
 </div>
 </div>
 </div>
@@ -604,14 +604,14 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2606901"></a>Other Documents About <acronym class=3D"acronym"=
>BIND</acronym>
+<a name=3D"id2607124"></a>Other Documents About <acronym class=3D"acronym"=
>BIND</acronym>
 </h3></div></div></div>
 <p></p>
 <div class=3D"bibliography">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2606910"></a>Bibliography</h4></div></div></div>
+<a name=3D"id2607133"></a>Bibliography</h4></div></div></div>
 <div class=3D"biblioentry">
-<a name=3D"id2606913"></a><p><span class=3D"authorgroup"><span class=3D"fi=
rstname">Paul</span> <span class=3D"surname">Albitz</span> and <span class=
=3D"firstname">Cricket</span> <span class=3D"surname">Liu</span>. </span><s=
pan class=3D"title"><i><acronym class=3D"acronym">DNS</acronym> and <acrony=
m class=3D"acronym">BIND</acronym></i>. </span><span class=3D"copyright">Co=
pyright =A9 1998 Sebastopol, CA: O'Reilly and Associates. </span></p>
+<a name=3D"id2607136"></a><p><span class=3D"authorgroup"><span class=3D"fi=
rstname">Paul</span> <span class=3D"surname">Albitz</span> and <span class=
=3D"firstname">Cricket</span> <span class=3D"surname">Liu</span>. </span><s=
pan class=3D"title"><i><acronym class=3D"acronym">DNS</acronym> and <acrony=
m class=3D"acronym">BIND</acronym></i>. </span><span class=3D"copyright">Co=
pyright =A9 1998 Sebastopol, CA: O'Reilly and Associates. </span></p>
 </div>
 </div>
 </div>
@@ -648,7 +648,7 @@
 </ul></div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608203"></a>Prerequisite</h3></div></div></div>
+<a name=3D"id2608280"></a>Prerequisite</h3></div></div></div>
 <p>GNU make is required to build the export libraries (other
   part of BIND 9 can still be built with other types of make). In
   the reminder of this document, "make" means GNU make. Note that
@@ -657,7 +657,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608213"></a>Compilation</h3></div></div></div>
+<a name=3D"id2608290"></a>Compilation</h3></div></div></div>
 <pre class=3D"screen">
 $ <strong class=3D"userinput"><code>./configure --enable-exportlib <em cla=
ss=3D"replaceable"><code>[other flags]</code></em></code></strong>
 $ <strong class=3D"userinput"><code>make</code></strong>
@@ -672,7 +672,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608237"></a>Installation</h3></div></div></div>
+<a name=3D"id2608314"></a>Installation</h3></div></div></div>
 <pre class=3D"screen">
 $ <strong class=3D"userinput"><code>cd lib/export</code></strong>
 $ <strong class=3D"userinput"><code>make install</code></strong>
@@ -694,7 +694,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608268"></a>Known Defects/Restrictions</h3></div></div></div>
+<a name=3D"id2608345"></a>Known Defects/Restrictions</h3></div></div></div>
 <div class=3D"itemizedlist"><ul type=3D"disc">
 <li><p>Currently, win32 is not supported for the export
       library. (Normal BIND 9 application can be built as
@@ -734,7 +734,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608413"></a>The dns.conf File</h3></div></div></div>
+<a name=3D"id2608422"></a>The dns.conf File</h3></div></div></div>
 <p>The IRS library supports an "advanced" configuration file
   related to the DNS library for configuration parameters that
   would be beyond the capability of the
@@ -752,14 +752,14 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2608440"></a>Sample Applications</h3></div></div></div>
+<a name=3D"id2608449"></a>Sample Applications</h3></div></div></div>
 <p>Some sample application programs using this API are
   provided for reference. The following is a brief description of
   these applications.
   </p>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2608449"></a>sample: a simple stub resolver utility</h4></div=
></div></div>
+<a name=3D"id2608457"></a>sample: a simple stub resolver utility</h4></div=
></div></div>
 <p>
   It sends a query of a given name (of a given optional RR type) to a
   specified recursive server, and prints the result as a list of
@@ -823,7 +823,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2608608"></a>sample-async: a simple stub resolver, working as=
ynchronously</h4></div></div></div>
+<a name=3D"id2608548"></a>sample-async: a simple stub resolver, working as=
ynchronously</h4></div></div></div>
 <p>
   Similar to "sample", but accepts a list
   of (query) domain names as a separate file and resolves the names
@@ -864,7 +864,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2608661"></a>sample-request: a simple DNS transaction client<=
/h4></div></div></div>
+<a name=3D"id2608601"></a>sample-request: a simple DNS transaction client<=
/h4></div></div></div>
 <p>
   It sends a query to a specified server, and
   prints the response with minimal processing. It doesn't act as a
@@ -905,7 +905,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2608725"></a>sample-gai: getaddrinfo() and getnameinfo() test=
 code</h4></div></div></div>
+<a name=3D"id2608733"></a>sample-gai: getaddrinfo() and getnameinfo() test=
 code</h4></div></div></div>
 <p>
   This is a test program
   to check getaddrinfo() and getnameinfo() behavior. It takes a
@@ -922,7 +922,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2608740"></a>sample-update: a simple dynamic update client pr=
ogram</h4></div></div></div>
+<a name=3D"id2608748"></a>sample-update: a simple dynamic update client pr=
ogram</h4></div></div></div>
 <p>
   It accepts a single update command as a
   command-line argument, sends an update request message to the
@@ -1017,7 +1017,7 @@
 </div>
 <div class=3D"sect3" lang=3D"en">
 <div class=3D"titlepage"><div><div><h4 class=3D"title">
-<a name=3D"id2609281"></a>nsprobe: domain/name server checker in terms of =
RFC 4074</h4></div></div></div>
+<a name=3D"id2609426"></a>nsprobe: domain/name server checker in terms of =
RFC 4074</h4></div></div></div>
 <p>
   It checks a set
   of domains to see the name servers of the domains behave
@@ -1074,7 +1074,7 @@
 </div>
 <div class=3D"sect2" lang=3D"en">
 <div class=3D"titlepage"><div><div><h3 class=3D"title">
-<a name=3D"id2609345"></a>Library References</h3></div></div></div>
+<a name=3D"id2609490"></a>Library References</h3></div></div></div>
 <p>As of this writing, there is no formal "manual" of the
   libraries, except this document, header files (some of them
   provide pretty detailed explanations), and sample application
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.ch10=
.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.ch10.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.ch10.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.ch10.html,v 1.20 2011-01-05 01:14:09 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.html
--- a/head/contrib/bind9/doc/arm/Bv9ARM.html	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/Bv9ARM.html	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: Bv9ARM.html,v 1.263.8.9 2011-08-03 02:35:13 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -40,8 +40,8 @@
 <div class=3D"titlepage">
 <div>
 <div><h1 class=3D"title">
-<a name=3D"id2563174"></a>BIND 9 Administrator Reference Manual</h1></div>
-<div><p class=3D"copyright">Copyright =A9 2004-2011 Internet Systems Conso=
rtium, Inc. ("ISC")</p></div>
+<a name=3D"id2563175"></a>BIND 9 Administrator Reference Manual</h1></div>
+<div><p class=3D"copyright">Copyright =A9 2004-2012 Internet Systems Conso=
rtium, Inc. ("ISC")</p></div>
 <div><p class=3D"copyright">Copyright =A9 2000-2003 Internet Software Cons=
ortium.</p></div>
 </div>
 <hr>
@@ -51,39 +51,39 @@
 <dl>
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch01.html">1. Introduction</=
a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564371">Scope of =
Document</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564394">Organizat=
ion of This Document</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564534">Conventio=
ns Used in This Document</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564715">The Domai=
n Name System (<acronym class=3D"acronym">DNS</acronym>)</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564375">Scope of =
Document</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564398">Organizat=
ion of This Document</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564538">Conventio=
ns Used in This Document</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch01.html#id2564720">The Domai=
n Name System (<acronym class=3D"acronym">DNS</acronym>)</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564737">DNS Funda=
mentals</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564771">Domains a=
nd Domain Names</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567176">Zones</a>=
</span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567253">Authorita=
tive Name Servers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567426">Caching N=
ame Servers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567556">Name Serv=
ers in Multiple Roles</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564741">DNS Funda=
mentals</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2564775">Domains a=
nd Domain Names</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567180">Zones</a>=
</span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567257">Authorita=
tive Name Servers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567430">Caching N=
ame Servers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch01.html#id2567560">Name Serv=
ers in Multiple Roles</a></span></dt>
 </dl></dd>
 </dl></dd>
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch02.html">2. <acronym class=
=3D"acronym">BIND</acronym> Resource Requirements</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567590">Hardware =
requirements</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567617">CPU Requi=
rements</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567629">Memory Re=
quirements</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567724">Name Serv=
er Intensive Environment Issues</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567735">Supported=
 Operating Systems</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567594">Hardware =
requirements</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567621">CPU Requi=
rements</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567634">Memory Re=
quirements</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567729">Name Serv=
er Intensive Environment Issues</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch02.html#id2567739">Supported=
 Operating Systems</a></span></dt>
 </dl></dd>
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch03.html">3. Name Server Co=
nfiguration</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#sample_configuration=
">Sample Configurations</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567767">A Caching=
-only Name Server</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567988">An Author=
itative-only Name Server</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567771">A Caching=
-only Name Server</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2567992">An Author=
itative-only Name Server</a></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568010">Load Bala=
ncing</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568364">Name Serv=
er Operations</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568014">Load Bala=
ncing</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch03.html#id2568369">Name Serv=
er Operations</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2568370">Tools for=
 Use With the Name Server Daemon</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2570378">Signals</=
a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2568374">Tools for=
 Use With the Name Server Daemon</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch03.html#id2570421">Signals</=
a></span></dt>
 </dl></dd>
 </dl></dd>
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch04.html">4. Advanced DNS F=
eatures</a></span></dt>
@@ -92,64 +92,64 @@
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#dynamic_update">Dyna=
mic Update</a></span></dt>
 <dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#journal">The=
 journal file</a></span></dt></dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#incremental_zone_tra=
nsfers">Incremental Zone Transfers (IXFR)</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2570885">Split DNS=
</a></span></dt>
-<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2570903">E=
xample split DNS setup</a></span></dt></dl></dd>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2570934">Split DNS=
</a></span></dt>
+<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2570952">E=
xample split DNS setup</a></span></dt></dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#tsig">TSIG</a></span=
></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571336">Generate =
Shared Keys for Each Pair of Hosts</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571478">Copying t=
he Shared Secret to Both Machines</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571489">Informing=
 the Servers of the Key's Existence</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571525">Instructi=
ng the Server to Use the Key</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571651">TSIG Key =
Based Access Control</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571700">Errors</a=
></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2564012">Generate =
Shared Keys for Each Pair of Hosts</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2564086">Copying t=
he Shared Secret to Both Machines</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571811">Informing=
 the Servers of the Key's Existence</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571847">Instructi=
ng the Server to Use the Key</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571905">TSIG Key =
Based Access Control</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571954">Errors</a=
></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2571714">TKEY</a><=
/span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2563980">SIG(0)</a=
></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2571968">TKEY</a><=
/span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2572153">SIG(0)</a=
></span></dt>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#DNSSEC">DNSSEC</a></=
span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2564117">Generatin=
g Keys</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572183">Signing t=
he Zone</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572264">Configuri=
ng Servers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572221">Generatin=
g Keys</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572300">Signing t=
he Zone</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572381">Configuri=
ng Servers</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#dnssec.dynamic.zones=
">DNSSEC, Dynamic Zones, and Automatic Signing</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563484">Convertin=
g from insecure to secure</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563522">Dynamic D=
NS update method</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563626">Fully aut=
omatic zone signing</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563777">Private-t=
ype records</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563814">DNSKEY ro=
llovers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563827">Dynamic D=
NS update method</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563860">Automatic=
 key rollovers</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563886">NSEC3PARA=
M rollovers via UPDATE</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563896">Convertin=
g from NSEC to NSEC3</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563906">Convertin=
g from NSEC3 to NSEC</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563918">Convertin=
g from secure to insecure</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563956">Periodic =
re-signing</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571816">NSEC3 and=
 OPTOUT</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571421">Convertin=
g from insecure to secure</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571459">Dynamic D=
NS update method</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563508">Fully aut=
omatic zone signing</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563590">Private-t=
ype records</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563696">DNSKEY ro=
llovers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563708">Dynamic D=
NS update method</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563741">Automatic=
 key rollovers</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563836">NSEC3PARA=
M rollovers via UPDATE</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563846">Convertin=
g from NSEC to NSEC3</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563856">Convertin=
g from NSEC3 to NSEC</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563868">Convertin=
g from secure to insecure</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563906">Periodic =
re-signing</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2563915">NSEC3 and=
 OPTOUT</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#rfc5011.support">Dyn=
amic Trust Anchor Management</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571869">Validatin=
g Resolver</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571892">Authorita=
tive Server</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571685">Validatin=
g Resolver</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2571707">Authorita=
tive Server</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#pkcs11">PKCS #11 (Cr=
yptoki) support</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2609757">Prerequis=
ites</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2607912">Building =
BIND 9 with PKCS#11</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2608144">PKCS #11 =
Tools</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2608174">Using the=
 HSM</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610353">Specifyin=
g the engine on the command line</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610467">Running n=
amed with automatic zone re-signing</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2609970">Prerequis=
ites</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2608219">Building =
BIND 9 with PKCS#11</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610529">PKCS #11 =
Tools</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2610560">Using the=
 HSM</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2635129">Specifyin=
g the engine on the command line</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2635243">Running n=
amed with automatic zone re-signing</a></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2572484">IPv6 Supp=
ort in <acronym class=3D"acronym">BIND</acronym> 9</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch04.html#id2572669">IPv6 Supp=
ort in <acronym class=3D"acronym">BIND</acronym> 9</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572819">Address L=
ookups Using AAAA Records</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572840">Address t=
o Name Lookups Using Nibble Format</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572868">Address L=
ookups Using AAAA Records</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch04.html#id2572889">Address t=
o Name Lookups Using Nibble Format</a></span></dt>
 </dl></dd>
 </dl></dd>
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch05.html">5. The <acronym c=
lass=3D"acronym">BIND</acronym> 9 Lightweight Resolver</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch05.html#id2572873">The Light=
weight Resolver Library</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch05.html#id2572922">The Light=
weight Resolver Library</a></span></dt>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch05.html#lwresd">Running a Re=
solver Daemon</a></span></dt>
 </dl></dd>
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch06.html">6. <acronym class=
=3D"acronym">BIND</acronym> 9 Configuration Reference</a></span></dt>
@@ -157,58 +157,58 @@
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#configuration_file_e=
lements">Configuration File Elements</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#address_match_lists"=
>Address Match Lists</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574283">Comment S=
yntax</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574332">Comment S=
yntax</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#Configuration_File_G=
rammar">Configuration File Grammar</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574937"><span><st=
rong class=3D"command">acl</strong></span> Statement Grammar</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2574986"><span><st=
rong class=3D"command">acl</strong></span> Statement Grammar</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#acl"><span><strong c=
lass=3D"command">acl</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575127"><span><st=
rong class=3D"command">controls</strong></span> Statement Grammar</a></span=
></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575176"><span><st=
rong class=3D"command">controls</strong></span> Statement Grammar</a></span=
></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#controls_statement_d=
efinition_and_usage"><span><strong class=3D"command">controls</strong></spa=
n> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575418"><span><st=
rong class=3D"command">include</strong></span> Statement Grammar</a></span>=
</dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575504"><span><st=
rong class=3D"command">include</strong></span> Statement Definition and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575467"><span><st=
rong class=3D"command">include</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575484"><span><st=
rong class=3D"command">include</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575527"><span><st=
rong class=3D"command">key</strong></span> Statement Grammar</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575550"><span><st=
rong class=3D"command">key</strong></span> Statement Definition and Usage</=
a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575709"><span><st=
rong class=3D"command">logging</strong></span> Statement Grammar</a></span>=
</dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575835"><span><st=
rong class=3D"command">logging</strong></span> Statement Definition and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575576"><span><st=
rong class=3D"command">key</strong></span> Statement Grammar</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575600"><span><st=
rong class=3D"command">key</strong></span> Statement Definition and Usage</=
a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575758"><span><st=
rong class=3D"command">logging</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2575884"><span><st=
rong class=3D"command">logging</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577834"><span><st=
rong class=3D"command">lwres</strong></span> Statement Grammar</a></span></=
dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577908"><span><st=
rong class=3D"command">lwres</strong></span> Statement Definition and Usage=
</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578040"><span><st=
rong class=3D"command">masters</strong></span> Statement Grammar</a></span>=
</dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578084"><span><st=
rong class=3D"command">masters</strong></span> Statement Definition and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577910"><span><st=
rong class=3D"command">lwres</strong></span> Statement Grammar</a></span></=
dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2577984"><span><st=
rong class=3D"command">lwres</strong></span> Statement Definition and Usage=
</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578116"><span><st=
rong class=3D"command">masters</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578160"><span><st=
rong class=3D"command">masters</strong></span> Statement Definition and
           Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578099"><span><st=
rong class=3D"command">options</strong></span> Statement Grammar</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2578174"><span><st=
rong class=3D"command">options</strong></span> Statement Grammar</a></span>=
</dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#options"><span><stro=
ng class=3D"command">options</strong></span> Statement Definition and
           Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#server_statement_gra=
mmar"><span><strong class=3D"command">server</strong></span> Statement Gram=
mar</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#server_statement_def=
inition_and_usage"><span><strong class=3D"command">server</strong></span> S=
tatement Definition and
             Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#statschannels"><span=
><strong class=3D"command">statistics-channels</strong></span> Statement Gr=
ammar</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589395"><span><st=
rong class=3D"command">statistics-channels</strong></span> Statement Defini=
tion and
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589481"><span><st=
rong class=3D"command">statistics-channels</strong></span> Statement Defini=
tion and
             Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#trusted-keys"><span>=
<strong class=3D"command">trusted-keys</strong></span> Statement Grammar</a=
></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589534"><span><st=
rong class=3D"command">trusted-keys</strong></span> Statement Definition
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589689"><span><st=
rong class=3D"command">trusted-keys</strong></span> Statement Definition
             and Usage</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589581"><span><st=
rong class=3D"command">managed-keys</strong></span> Statement Grammar</a></=
span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2589736"><span><st=
rong class=3D"command">managed-keys</strong></span> Statement Grammar</a></=
span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#managed-keys"><span>=
<strong class=3D"command">managed-keys</strong></span> Statement Definition
             and Usage</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#view_statement_gramm=
ar"><span><strong class=3D"command">view</strong></span> Statement Grammar<=
/a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2590007"><span><st=
rong class=3D"command">view</strong></span> Statement Definition and Usage<=
/a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2590162"><span><st=
rong class=3D"command">view</strong></span> Statement Definition and Usage<=
/a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#zone_statement_gramm=
ar"><span><strong class=3D"command">zone</strong></span>
             Statement Grammar</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2591558"><span><st=
rong class=3D"command">zone</strong></span> Statement Definition and Usage<=
/a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2591713"><span><st=
rong class=3D"command">zone</strong></span> Statement Definition and Usage<=
/a></span></dt>
 </dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#id2595030">Zone File=
</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#id2595116">Zone File=
</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#types_of_resource_re=
cords_and_when_to_use_them">Types of Resource Records and When to Use Them<=
/a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597260">Discussio=
n of MX Records</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597415">Discussio=
n of MX Records</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#Setting_TTLs">Settin=
g TTLs</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597876">Inverse M=
apping in IPv4</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598003">Other Zon=
e File Directives</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598276"><acronym =
class=3D"acronym">BIND</acronym> Master File Extension: the  <span><strong =
class=3D"command">$GENERATE</strong></span> Directive</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2597962">Inverse M=
apping in IPv4</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598157">Other Zon=
e File Directives</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#id2598430"><acronym =
class=3D"acronym">BIND</acronym> Master File Extension: the  <span><strong =
class=3D"command">$GENERATE</strong></span> Directive</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch06.html#zonefile_format">Add=
itional File Formats</a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch06.html#statistics">BIND9 St=
atistics</a></span></dt>
@@ -217,41 +217,41 @@
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch07.html">7. <acronym class=
=3D"acronym">BIND</acronym> 9 Security Considerations</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#Access_Control_Lists=
">Access Control Lists</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#id2602996"><span><st=
rong class=3D"command">Chroot</strong></span> and <span><strong class=3D"co=
mmand">Setuid</strong></span></a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#id2603082"><span><st=
rong class=3D"command">Chroot</strong></span> and <span><strong class=3D"co=
mmand">Setuid</strong></span></a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603077">The <span=
><strong class=3D"command">chroot</strong></span> Environment</a></span></d=
t>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603137">Using the=
 <span><strong class=3D"command">setuid</strong></span> Function</a></span>=
</dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603232">The <span=
><strong class=3D"command">chroot</strong></span> Environment</a></span></d=
t>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch07.html#id2603291">Using the=
 <span><strong class=3D"command">setuid</strong></span> Function</a></span>=
</dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch07.html#dynamic_update_secur=
ity">Dynamic Update Security</a></span></dt>
 </dl></dd>
 <dt><span class=3D"chapter"><a href=3D"Bv9ARM.ch08.html">8. Troubleshootin=
g</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603285">Common Pr=
oblems</a></span></dt>
-<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch08.html#id2603290">I=
t's not working; how can I figure out what's wrong?</a></span></dt></dl></d=
d>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603302">Increment=
ing and Changing the Serial Number</a></span></dt>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603319">Where Can=
 I Get Help?</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603371">Common Pr=
oblems</a></span></dt>
+<dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch08.html#id2603377">I=
t's not working; how can I figure out what's wrong?</a></span></dt></dl></d=
d>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603388">Increment=
ing and Changing the Serial Number</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch08.html#id2603405">Where Can=
 I Get Help?</a></span></dt>
 </dl></dd>
 <dt><span class=3D"appendix"><a href=3D"Bv9ARM.ch09.html">A. Appendices</a=
></span></dt>
 <dd><dl>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603449">Acknowled=
gments</a></span></dt>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603536">Acknowled=
gments</a></span></dt>
 <dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#historical_d=
ns_information">A Brief History of the <acronym class=3D"acronym">DNS</acro=
nym> and <acronym class=3D"acronym">BIND</acronym></a></span></dt></dl></dd>
-<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603553">General <=
acronym class=3D"acronym">DNS</acronym> Reference Information</a></span></d=
t>
+<dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#id2603707">General <=
acronym class=3D"acronym">DNS</acronym> Reference Information</a></span></d=
t>
 <dd><dl><dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#ipv6addresse=
s">IPv6 addresses (AAAA)</a></span></dt></dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#bibliography">Biblio=
graphy (and Suggested Reading)</a></span></dt>
 <dd><dl>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#rfcs">Request for Co=
mments (RFCs)</a></span></dt>
 <dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#internet_drafts">Int=
ernet Drafts</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2606901">Other Doc=
uments About <acronym class=3D"acronym">BIND</acronym></a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2607124">Other Doc=
uments About <acronym class=3D"acronym">BIND</acronym></a></span></dt>
 </dl></dd>
 <dt><span class=3D"sect1"><a href=3D"Bv9ARM.ch09.html#bind9.library">BIND =
9 DNS Library Support</a></span></dt>
 <dd><dl>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608203">Prerequis=
ite</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608213">Compilati=
on</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608237">Installat=
ion</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608268">Known Def=
ects/Restrictions</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608413">The dns.c=
onf File</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608440">Sample Ap=
plications</a></span></dt>
-<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2609345">Library R=
eferences</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608280">Prerequis=
ite</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608290">Compilati=
on</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608314">Installat=
ion</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608345">Known Def=
ects/Restrictions</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608422">The dns.c=
onf File</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2608449">Sample Ap=
plications</a></span></dt>
+<dt><span class=3D"sect2"><a href=3D"Bv9ARM.ch09.html#id2609490">Library R=
eferences</a></span></dt>
 </dl></dd>
 </dl></dd>
 <dt><span class=3D"reference"><a href=3D"Bv9ARM.ch10.html">I. Manual pages=
</a></span></dt>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Bv9ARM.pdf
Binary file head/contrib/bind9/doc/arm/Bv9ARM.pdf has changed
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/Makefile.in
--- a/head/contrib/bind9/doc/arm/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.22 2009-02-12 23:47:56 tbox Exp $
+# $Id: Makefile.in,v 1.22 2009/02/12 23:47:56 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/README-SGML
--- a/head/contrib/bind9/doc/arm/README-SGML	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/README-SGML	Tue Apr 17 11:51:51 2012 +0300
@@ -4,7 +4,7 @@
=20
 The BIND v9 ARM master document is now kept in DocBook XML format.
=20
-Version: $Id: README-SGML,v 1.17 2004-03-05 05:04:43 marka Exp $
+Version: $Id: README-SGML,v 1.17 2004/03/05 05:04:43 marka Exp $
=20
 The entire ARM is in the single file:
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/dnssec.xml
--- a/head/contrib/bind9/doc/arm/dnssec.xml	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/dnssec.xml	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 <?xml version=3D"1.0" encoding=3D"utf-8"?>
 <!--
- - Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2010, 2012  Internet Systems Consortium, Inc. ("ISC")
  -
  - Permission to use, copy, modify, and/or distribute this software for any
  - purpose with or without fee is hereby granted, provided that the above
@@ -15,7 +15,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: dnssec.xml,v 1.4 2010-08-16 22:21:06 marka Exp $ -->
+<!-- $Id$ -->
=20
 <sect1 id=3D"dnssec.dynamic.zones">
   <title>DNSSEC, Dynamic Zones, and Automatic Signing</title>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/libdns.xml
--- a/head/contrib/bind9/doc/arm/libdns.xml	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/libdns.xml	Tue Apr 17 11:51:51 2012 +0300
@@ -527,4 +527,4 @@
   programs.</para>
   </sect2>
 </sect1>
-<!-- $Id: libdns.xml,v 1.3 2010-02-03 23:49:07 tbox Exp $ -->
+<!-- $Id: libdns.xml,v 1.3 2010/02/03 23:49:07 tbox Exp $ -->
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.arpanam=
e.html
--- a/head/contrib/bind9/doc/arm/man.arpaname.html	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/doc/arm/man.arpaname.html	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.arpaname.html,v 1.33.8.11 2011-08-03 02:35:10 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,20 +50,20 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">arpaname</code>  {<e=
m class=3D"replaceable"><code>ipaddress </code></em>...}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648201"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2614792"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">arpaname</strong></span> translates =
IP addresses (IPv4 and
       IPv6) to the corresponding IN-ADDR.ARPA or IP6.ARPA names.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648216"></a><h2>SEE ALSO</h2>
+<a name=3D"id2614807"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648230"></a><h2>AUTHOR</h2>
+<a name=3D"id2652026"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.ddns-co=
nfgen.html
--- a/head/contrib/bind9/doc/arm/man.ddns-confgen.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.ddns-confgen.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.ddns-confgen.html,v 1.69.8.11 2011-08-03 02:35:10 tbox Exp $=
 -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">ddns-confgen</code> =
 [<code class=3D"option">-a <em class=3D"replaceable"><code>algorithm</code=
></em></code>] [<code class=3D"option">-h</code>] [<code class=3D"option">-=
k <em class=3D"replaceable"><code>keyname</code></em></code>] [<code class=
=3D"option">-r <em class=3D"replaceable"><code>randomfile</code></em></code=
>] [ -s <em class=3D"replaceable"><code>name</code></em>  |   -z <em class=
=3D"replaceable"><code>zone</code></em> ] [<code class=3D"option">-q</code>=
] [name]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2644606"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2651677"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">ddns-confgen</strong></span>
       generates a key for use by <span><strong class=3D"command">nsupdate<=
/strong></span>
       and <span><strong class=3D"command">named</strong></span>.  It simpl=
ifies configuration
@@ -77,7 +77,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2644762"></a><h2>OPTIONS</h2>
+<a name=3D"id2651765"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></span></dt>
 <dd><p>
@@ -144,7 +144,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2645987"></a><h2>SEE ALSO</h2>
+<a name=3D"id2651965"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">nsupdate</sp=
an>(1)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named.con=
f</span>(5)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
@@ -152,7 +152,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648141"></a><h2>AUTHOR</h2>
+<a name=3D"id2652004"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.dig.html
--- a/head/contrib/bind9/doc/arm/man.dig.html	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.dig.html	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.dig.html,v 1.162.8.9 2011-08-03 02:35:11 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -52,7 +52,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dig</code>  [global-=
queryopt...] [query...]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2609512"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2610001"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dig</strong></span>
       (domain information groper) is a flexible tool
       for interrogating DNS name servers.  It performs DNS lookups and
@@ -98,7 +98,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2609607"></a><h2>SIMPLE USAGE</h2>
+<a name=3D"id2610096"></a><h2>SIMPLE USAGE</h2>
 <p>
       A typical invocation of <span><strong class=3D"command">dig</strong>=
</span> looks like:
       </p>
@@ -144,7 +144,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2610059"></a><h2>OPTIONS</h2>
+<a name=3D"id2610889"></a><h2>OPTIONS</h2>
 <p>
       The <code class=3D"option">-b</code> option sets the source IP addre=
ss of the query
       to <em class=3D"parameter"><code>address</code></em>.  This must be =
a valid
@@ -248,7 +248,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2662694"></a><h2>QUERY OPTIONS</h2>
+<a name=3D"id2662636"></a><h2>QUERY OPTIONS</h2>
 <p><span><strong class=3D"command">dig</strong></span>
       provides a number of query options which affect
       the way in which lookups are made and the results displayed.  Some of
@@ -579,7 +579,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2663708"></a><h2>MULTIPLE QUERIES</h2>
+<a name=3D"id2663651"></a><h2>MULTIPLE QUERIES</h2>
 <p>
       The BIND 9 implementation of <span><strong class=3D"command">dig </s=
trong></span>
       supports
@@ -625,7 +625,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2663794"></a><h2>IDN SUPPORT</h2>
+<a name=3D"id2663804"></a><h2>IDN SUPPORT</h2>
 <p>
       If <span><strong class=3D"command">dig</strong></span> has been buil=
t with IDN (internationalized
       domain name) support, it can accept and display non-ASCII domain nam=
es.
@@ -639,14 +639,14 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2663822"></a><h2>FILES</h2>
+<a name=3D"id2663833"></a><h2>FILES</h2>
 <p><code class=3D"filename">/etc/resolv.conf</code>
     </p>
 <p><code class=3D"filename">${HOME}/.digrc</code>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2663912"></a><h2>SEE ALSO</h2>
+<a name=3D"id2663854"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">host</span>(=
1)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-ke=
ygen</span>(8)</span>,
@@ -654,7 +654,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2663949"></a><h2>BUGS</h2>
+<a name=3D"id2663892"></a><h2>BUGS</h2>
 <p>
       There are probably too many query options.
     </p>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.dnssec-=
dsfromkey.html
--- a/head/contrib/bind9/doc/arm/man.dnssec-dsfromkey.html	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.dnssec-dsfromkey.html	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.dnssec-dsfromkey.html,v 1.74.8.9 2011-08-03 02:35:10 tbox Ex=
p $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -51,14 +51,14 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-dsfromkey</co=
de>  {-s} [<code class=3D"option">-1</code>] [<code class=3D"option">-2</co=
de>] [<code class=3D"option">-a <em class=3D"replaceable"><code>alg</code><=
/em></code>] [<code class=3D"option">-K <em class=3D"replaceable"><code>dir=
ectory</code></em></code>] [<code class=3D"option">-l <em class=3D"replacea=
ble"><code>domain</code></em></code>] [<code class=3D"option">-s</code>] [<=
code class=3D"option">-c <em class=3D"replaceable"><code>class</code></em><=
/code>] [<code class=3D"option">-f <em class=3D"replaceable"><code>file</co=
de></em></code>] [<code class=3D"option">-A</code>] [<code class=3D"option"=
>-v <em class=3D"replaceable"><code>level</code></em></code>] {dnsname}</p>=
</div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2611562"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2611846"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-dsfromkey</strong></span>
       outputs the Delegation Signer (DS) resource record (RR), as defined =
in
       RFC 3658 and RFC 4509, for the given key(s).
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2611576"></a><h2>OPTIONS</h2>
+<a name=3D"id2611860"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-1</span></dt>
 <dd><p>
@@ -119,7 +119,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2611765"></a><h2>EXAMPLE</h2>
+<a name=3D"id2612526"></a><h2>EXAMPLE</h2>
 <p>
       To build the SHA-256 DS RR from the
       <strong class=3D"userinput"><code>Kexample.com.+003+26160</code></st=
rong>
@@ -134,7 +134,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2611801"></a><h2>FILES</h2>
+<a name=3D"id2612563"></a><h2>FILES</h2>
 <p>
       The keyfile can be designed by the key identification
       <code class=3D"filename">Knnnn.+aaa+iiiii</code> or the full file na=
me
@@ -148,13 +148,13 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2612184"></a><h2>CAVEAT</h2>
+<a name=3D"id2612604"></a><h2>CAVEAT</h2>
 <p>
       A keyfile error can give a "file not found" even if the file exists.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2612194"></a><h2>SEE ALSO</h2>
+<a name=3D"id2612614"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-si=
gnzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
@@ -164,7 +164,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2612233"></a><h2>AUTHOR</h2>
+<a name=3D"id2612858"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.dnssec-=
keyfromlabel.html
--- a/head/contrib/bind9/doc/arm/man.dnssec-keyfromlabel.html	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.dnssec-keyfromlabel.html	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.dnssec-keyfromlabel.html,v 1.110.8.10 2011-08-03 02:35:10 tb=
ox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-keyfromlabel<=
/code>  {-l <em class=3D"replaceable"><code>label</code></em>} [<code class=
=3D"option">-3</code>] [<code class=3D"option">-a <em class=3D"replaceable"=
><code>algorithm</code></em></code>] [<code class=3D"option">-A <em class=
=3D"replaceable"><code>date/offset</code></em></code>] [<code class=3D"opti=
on">-c <em class=3D"replaceable"><code>class</code></em></code>] [<code cla=
ss=3D"option">-D <em class=3D"replaceable"><code>date/offset</code></em></c=
ode>] [<code class=3D"option">-E <em class=3D"replaceable"><code>engine</co=
de></em></code>] [<code class=3D"option">-f <em class=3D"replaceable"><code=
>flag</code></em></code>] [<code class=3D"option">-G</code>] [<code class=
=3D"option">-I <em class=3D"replaceable"><code>date/offset</code></em></cod=
e>] [<code class=3D"option">-k</code>] [<code class=3D"option">-K <em class=
=3D"replaceable"><code>directory</code></em></code>] [<code class=3D"option=
">-n <em class=3D"replaceable"><code>nametype</code></em></code>] [<code cl=
ass=3D"option">-P <em class=3D"replaceable"><code>date/offset</code></em></=
code>] [<code class=3D"option">-p <em class=3D"replaceable"><code>protocol<=
/code></em></code>] [<code class=3D"option">-R <em class=3D"replaceable"><c=
ode>date/offset</code></em></code>] [<code class=3D"option">-t <em class=3D=
"replaceable"><code>type</code></em></code>] [<code class=3D"option">-v <em=
 class=3D"replaceable"><code>level</code></em></code>] [<code class=3D"opti=
on">-y</code>] {name}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2613155"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2613302"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-keyfromlabel</strong></span>
       gets keys with the given label from a crypto hardware and builds
       key files for DNSSEC (Secure DNS), as defined in RFC 2535
@@ -63,7 +63,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2613175"></a><h2>OPTIONS</h2>
+<a name=3D"id2613322"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></span></dt>
 <dd>
@@ -182,7 +182,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2615181"></a><h2>TIMING OPTIONS</h2>
+<a name=3D"id2614168"></a><h2>TIMING OPTIONS</h2>
 <p>
       Dates can be expressed in the format YYYYMMDD or YYYYMMDDHHMMSS.
       If the argument begins with a '+' or '-', it is interpreted as
@@ -229,7 +229,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2666480"></a><h2>GENERATED KEY FILES</h2>
+<a name=3D"id2614266"></a><h2>GENERATED KEY FILES</h2>
 <p>
       When <span><strong class=3D"command">dnssec-keyfromlabel</strong></s=
pan> completes
       successfully,
@@ -268,7 +268,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2666573"></a><h2>SEE ALSO</h2>
+<a name=3D"id2615589"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-si=
gnzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
@@ -276,7 +276,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2666606"></a><h2>AUTHOR</h2>
+<a name=3D"id2615622"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.dnssec-=
keygen.html
--- a/head/contrib/bind9/doc/arm/man.dnssec-keygen.html	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.dnssec-keygen.html	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.dnssec-keygen.html,v 1.179.8.10 2011-08-03 02:35:10 tbox Exp=
 $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-keygen</code>=
  [<code class=3D"option">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></code>] [<code class=3D"option">-b <em class=3D"replaceable"><code>=
keysize</code></em></code>] [<code class=3D"option">-n <em class=3D"replace=
able"><code>nametype</code></em></code>] [<code class=3D"option">-3</code>]=
 [<code class=3D"option">-A <em class=3D"replaceable"><code>date/offset</co=
de></em></code>] [<code class=3D"option">-C</code>] [<code class=3D"option"=
>-c <em class=3D"replaceable"><code>class</code></em></code>] [<code class=
=3D"option">-D <em class=3D"replaceable"><code>date/offset</code></em></cod=
e>] [<code class=3D"option">-E <em class=3D"replaceable"><code>engine</code=
></em></code>] [<code class=3D"option">-e</code>] [<code class=3D"option">-=
f <em class=3D"replaceable"><code>flag</code></em></code>] [<code class=3D"=
option">-G</code>] [<code class=3D"option">-g <em class=3D"replaceable"><co=
de>generator</code></em></code>] [<code class=3D"option">-h</code>] [<code =
class=3D"option">-I <em class=3D"replaceable"><code>date/offset</code></em>=
</code>] [<code class=3D"option">-i <em class=3D"replaceable"><code>interva=
l</code></em></code>] [<code class=3D"option">-K <em class=3D"replaceable">=
<code>directory</code></em></code>] [<code class=3D"option">-k</code>] [<co=
de class=3D"option">-P <em class=3D"replaceable"><code>date/offset</code></=
em></code>] [<code class=3D"option">-p <em class=3D"replaceable"><code>prot=
ocol</code></em></code>] [<code class=3D"option">-q</code>] [<code class=3D=
"option">-R <em class=3D"replaceable"><code>date/offset</code></em></code>]=
 [<code class=3D"option">-r <em class=3D"replaceable"><code>randomdev</code=
></em></code>] [<code class=3D"option">-S <em class=3D"replaceable"><code>k=
ey</code></em></code>] [<code class=3D"option">-s <em class=3D"replaceable"=
><code>strength</code></em></code>] [<code class=3D"option">-t <em class=3D=
"replaceable"><code>type</code></em></code>] [<code class=3D"option">-v <em=
 class=3D"replaceable"><code>level</code></em></code>] [<code class=3D"opti=
on">-z</code>] {name}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2614380"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2614596"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-keygen</strong></span>
       generates keys for DNSSEC (Secure DNS), as defined in RFC 2535
       and RFC 4034.  It can also generate keys for use with
@@ -64,7 +64,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2614401"></a><h2>OPTIONS</h2>
+<a name=3D"id2614684"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a <em class=3D"replaceable"><code>algorithm</cod=
e></em></span></dt>
 <dd>
@@ -266,7 +266,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2667754"></a><h2>TIMING OPTIONS</h2>
+<a name=3D"id2668243"></a><h2>TIMING OPTIONS</h2>
 <p>
       Dates can be expressed in the format YYYYMMDD or YYYYMMDDHHMMSS.
       If the argument begins with a '+' or '-', it is interpreted as
@@ -337,7 +337,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2667944"></a><h2>GENERATED KEYS</h2>
+<a name=3D"id2668501"></a><h2>GENERATED KEYS</h2>
 <p>
       When <span><strong class=3D"command">dnssec-keygen</strong></span> c=
ompletes
       successfully,
@@ -383,7 +383,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2668052"></a><h2>EXAMPLE</h2>
+<a name=3D"id2668609"></a><h2>EXAMPLE</h2>
 <p>
       To generate a 768-bit DSA key for the domain
       <strong class=3D"userinput"><code>example.com</code></strong>, the f=
ollowing command would be
@@ -404,7 +404,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2668245"></a><h2>SEE ALSO</h2>
+<a name=3D"id2668665"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-signz=
one</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 2539</em>,
@@ -413,7 +413,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2668276"></a><h2>AUTHOR</h2>
+<a name=3D"id2668696"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.dnssec-=
revoke.html
--- a/head/contrib/bind9/doc/arm/man.dnssec-revoke.html	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.dnssec-revoke.html	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.dnssec-revoke.html,v 1.62.8.10 2011-08-03 02:35:12 tbox Exp =
$ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -47,10 +47,10 @@
 </div>
 <div class=3D"refsynopsisdiv">
 <h2>Synopsis</h2>
-<div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-revoke</code>=
  [<code class=3D"option">-hr</code>] [<code class=3D"option">-v <em class=
=3D"replaceable"><code>level</code></em></code>] [<code class=3D"option">-K=
 <em class=3D"replaceable"><code>directory</code></em></code>] [<code class=
=3D"option">-E <em class=3D"replaceable"><code>engine</code></em></code>] [=
<code class=3D"option">-f</code>] {keyfile}</p></div>
+<div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-revoke</code>=
  [<code class=3D"option">-hr</code>] [<code class=3D"option">-v <em class=
=3D"replaceable"><code>level</code></em></code>] [<code class=3D"option">-K=
 <em class=3D"replaceable"><code>directory</code></em></code>] [<code class=
=3D"option">-E <em class=3D"replaceable"><code>engine</code></em></code>] [=
<code class=3D"option">-f</code>] [<code class=3D"option">-R</code>] {keyfi=
le}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2614715"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2615650"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-revoke</strong></span>
       reads a DNSSEC key file, sets the REVOKED bit on the key as defined
       in RFC 5011, and creates a new pair of key files containing the
@@ -58,7 +58,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2614729"></a><h2>OPTIONS</h2>
+<a name=3D"id2615664"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-h</span></dt>
 <dd><p>
@@ -88,17 +88,22 @@
             write the new key pair even if a file already exists matching
             the algorithm and key ID of the revoked key.
           </p></dd>
+<dt><span class=3D"term">-R</span></dt>
+<dd><p>
+	    Print the key tag of the key with the REVOKE bit set but do
+	    not revoke the key.
+          </p></dd>
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2614837"></a><h2>SEE ALSO</h2>
+<a name=3D"id2615784"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 5011</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2614861"></a><h2>AUTHOR</h2>
+<a name=3D"id2615809"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.dnssec-=
settime.html
--- a/head/contrib/bind9/doc/arm/man.dnssec-settime.html	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.dnssec-settime.html	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.dnssec-settime.html,v 1.58.8.11 2011-08-03 02:35:13 tbox Exp=
 $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-settime</code=
>  [<code class=3D"option">-f</code>] [<code class=3D"option">-K <em class=
=3D"replaceable"><code>directory</code></em></code>] [<code class=3D"option=
">-P <em class=3D"replaceable"><code>date/offset</code></em></code>] [<code=
 class=3D"option">-A <em class=3D"replaceable"><code>date/offset</code></em=
></code>] [<code class=3D"option">-R <em class=3D"replaceable"><code>date/o=
ffset</code></em></code>] [<code class=3D"option">-I <em class=3D"replaceab=
le"><code>date/offset</code></em></code>] [<code class=3D"option">-D <em cl=
ass=3D"replaceable"><code>date/offset</code></em></code>] [<code class=3D"o=
ption">-h</code>] [<code class=3D"option">-v <em class=3D"replaceable"><cod=
e>level</code></em></code>] [<code class=3D"option">-E <em class=3D"replace=
able"><code>engine</code></em></code>] {keyfile}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2615479"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2615924"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-settime</strong></span>
       reads a DNSSEC private key file and sets the key timing metadata
       as specified by the <code class=3D"option">-P</code>, <code class=3D=
"option">-A</code>,
@@ -71,11 +71,12 @@
       <code class=3D"filename">Knnnn.+aaa+iiiii.private</code>) are regene=
rated.
       Metadata fields are stored in the private file.  A human-readable
       description of the metadata is also placed in comments in the key
-      file.
+      file.  The private file's permissions are always set to be
+      inaccessible to anyone other than the owner (mode 0600).
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2615538"></a><h2>OPTIONS</h2>
+<a name=3D"id2616051"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-f</span></dt>
 <dd><p>
@@ -108,7 +109,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2615632"></a><h2>TIMING OPTIONS</h2>
+<a name=3D"id2616145"></a><h2>TIMING OPTIONS</h2>
 <p>
       Dates can be expressed in the format YYYYMMDD or YYYYMMDDHHMMSS.
       If the argument begins with a '+' or '-', it is interpreted as
@@ -187,7 +188,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2616453"></a><h2>PRINTING OPTIONS</h2>
+<a name=3D"id2616488"></a><h2>PRINTING OPTIONS</h2>
 <p>
       <span><strong class=3D"command">dnssec-settime</strong></span> can a=
lso be used to print the
       timing metadata associated with a key.
@@ -213,7 +214,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2616533"></a><h2>SEE ALSO</h2>
+<a name=3D"id2616636"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-si=
gnzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
@@ -221,7 +222,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2616566"></a><h2>AUTHOR</h2>
+<a name=3D"id2617693"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.dnssec-=
signzone.html
--- a/head/contrib/bind9/doc/arm/man.dnssec-signzone.html	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.dnssec-signzone.html	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.dnssec-signzone.html,v 1.179.8.11 2011-08-03 02:35:13 tbox E=
xp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">dnssec-signzone</cod=
e>  [<code class=3D"option">-a</code>] [<code class=3D"option">-c <em class=
=3D"replaceable"><code>class</code></em></code>] [<code class=3D"option">-d=
 <em class=3D"replaceable"><code>directory</code></em></code>] [<code class=
=3D"option">-E <em class=3D"replaceable"><code>engine</code></em></code>] [=
<code class=3D"option">-e <em class=3D"replaceable"><code>end-time</code></=
em></code>] [<code class=3D"option">-f <em class=3D"replaceable"><code>outp=
ut-file</code></em></code>] [<code class=3D"option">-g</code>] [<code class=
=3D"option">-h</code>] [<code class=3D"option">-K <em class=3D"replaceable"=
><code>directory</code></em></code>] [<code class=3D"option">-k <em class=
=3D"replaceable"><code>key</code></em></code>] [<code class=3D"option">-l <=
em class=3D"replaceable"><code>domain</code></em></code>] [<code class=3D"o=
ption">-i <em class=3D"replaceable"><code>interval</code></em></code>] [<co=
de class=3D"option">-I <em class=3D"replaceable"><code>input-format</code><=
/em></code>] [<code class=3D"option">-j <em class=3D"replaceable"><code>jit=
ter</code></em></code>] [<code class=3D"option">-N <em class=3D"replaceable=
"><code>soa-serial-format</code></em></code>] [<code class=3D"option">-o <e=
m class=3D"replaceable"><code>origin</code></em></code>] [<code class=3D"op=
tion">-O <em class=3D"replaceable"><code>output-format</code></em></code>] =
[<code class=3D"option">-p</code>] [<code class=3D"option">-P</code>] [<cod=
e class=3D"option">-r <em class=3D"replaceable"><code>randomdev</code></em>=
</code>] [<code class=3D"option">-S</code>] [<code class=3D"option">-s <em =
class=3D"replaceable"><code>start-time</code></em></code>] [<code class=3D"=
option">-T <em class=3D"replaceable"><code>ttl</code></em></code>] [<code c=
lass=3D"option">-t</code>] [<code class=3D"option">-u</code>] [<code class=
=3D"option">-v <em class=3D"replaceable"><code>level</code></em></code>] [<=
code class=3D"option">-x</code>] [<code class=3D"option">-z</code>] [<code =
class=3D"option">-3 <em class=3D"replaceable"><code>salt</code></em></code>=
] [<code class=3D"option">-H <em class=3D"replaceable"><code>iterations</co=
de></em></code>] [<code class=3D"option">-A</code>] {zonefile} [key...]</p>=
</div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2617358"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2617803"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">dnssec-signzone</strong></span>
       signs a zone.  It generates
       NSEC and RRSIG records and produces a signed version of the
@@ -61,7 +61,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2617378"></a><h2>OPTIONS</h2>
+<a name=3D"id2617822"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a</span></dt>
 <dd><p>
@@ -397,7 +397,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2672040"></a><h2>EXAMPLE</h2>
+<a name=3D"id2672553"></a><h2>EXAMPLE</h2>
 <p>
       The following command signs the <strong class=3D"userinput"><code>ex=
ample.com</code></strong>
       zone with the DSA key generated by <span><strong class=3D"command">d=
nssec-keygen</strong></span>
@@ -427,14 +427,14 @@
 %</pre>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2672119"></a><h2>SEE ALSO</h2>
+<a name=3D"id2672632"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dnssec-keyge=
n</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 4033</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2672144"></a><h2>AUTHOR</h2>
+<a name=3D"id2672657"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.genrand=
om.html
--- a/head/contrib/bind9/doc/arm/man.genrandom.html	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/doc/arm/man.genrandom.html	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.genrandom.html,v 1.34.8.12 2011-08-09 01:52:59 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">genrandom</code>  [<=
code class=3D"option">-n <em class=3D"replaceable"><code>number</code></em>=
</code>] {<em class=3D"replaceable"><code>size</code></em>} {<em class=3D"r=
eplaceable"><code>filename</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2615898"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2652195"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">genrandom</strong></span>
       generates a file or a set of files containing a specified quantity
@@ -59,7 +59,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648272"></a><h2>ARGUMENTS</h2>
+<a name=3D"id2652210"></a><h2>ARGUMENTS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-n <em class=3D"replaceable"><code>number</code><=
/em></span></dt>
 <dd><p>
@@ -77,14 +77,14 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648332"></a><h2>SEE ALSO</h2>
+<a name=3D"id2652270"></a><h2>SEE ALSO</h2>
 <p>
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rand</spa=
n>(3)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">arc4rando=
m</span>(3)</span>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648427"></a><h2>AUTHOR</h2>
+<a name=3D"id2652980"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.host.ht=
ml
--- a/head/contrib/bind9/doc/arm/man.host.html	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/doc/arm/man.host.html	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.host.html,v 1.160.8.9 2011-08-03 02:35:10 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">host</code>  [<code =
class=3D"option">-aCdlnrsTwv</code>] [<code class=3D"option">-c <em class=
=3D"replaceable"><code>class</code></em></code>] [<code class=3D"option">-N=
 <em class=3D"replaceable"><code>ndots</code></em></code>] [<code class=3D"=
option">-R <em class=3D"replaceable"><code>number</code></em></code>] [<cod=
e class=3D"option">-t <em class=3D"replaceable"><code>type</code></em></cod=
e>] [<code class=3D"option">-W <em class=3D"replaceable"><code>wait</code><=
/em></code>] [<code class=3D"option">-m <em class=3D"replaceable"><code>fla=
g</code></em></code>] [<code class=3D"option">-4</code>] [<code class=3D"op=
tion">-6</code>] {name} [server]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2610601"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2611091"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">host</strong></span>
       is a simple utility for performing DNS lookups.
       It is normally used to convert names to IP addresses and vice versa.
@@ -202,7 +202,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2611184"></a><h2>IDN SUPPORT</h2>
+<a name=3D"id2611537"></a><h2>IDN SUPPORT</h2>
 <p>
       If <span><strong class=3D"command">host</strong></span> has been bui=
lt with IDN (internationalized
       domain name) support, it can accept and display non-ASCII domain nam=
es.=20
@@ -216,12 +216,12 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2611212"></a><h2>FILES</h2>
+<a name=3D"id2611565"></a><h2>FILES</h2>
 <p><code class=3D"filename">/etc/resolv.conf</code>
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2611226"></a><h2>SEE ALSO</h2>
+<a name=3D"id2611579"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">dig</span>(1=
)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>.
     </p>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.isc-hma=
c-fixup.html
--- a/head/contrib/bind9/doc/arm/man.isc-hmac-fixup.html	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.isc-hmac-fixup.html	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.isc-hmac-fixup.html,v 1.31.8.12 2011-08-09 01:52:59 tbox Exp=
 $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">isc-hmac-fixup</code=
>  {<em class=3D"replaceable"><code>algorithm</code></em>} {<em class=3D"re=
placeable"><code>secret</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648612"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2615000"></a><h2>DESCRIPTION</h2>
 <p>
       Versions of BIND 9 up to and including BIND 9.6 had a bug causing
       HMAC-SHA* TSIG keys which were longer than the digest length of the
@@ -76,7 +76,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648640"></a><h2>SECURITY CONSIDERATIONS</h2>
+<a name=3D"id2653052"></a><h2>SECURITY CONSIDERATIONS</h2>
 <p>
       Secrets that have been converted by <span><strong class=3D"command">=
isc-hmac-fixup</strong></span>
       are shortened, but as this is how the HMAC protocol works in
@@ -87,14 +87,14 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648656"></a><h2>SEE ALSO</h2>
+<a name=3D"id2653068"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 2104</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648673"></a><h2>AUTHOR</h2>
+<a name=3D"id2653085"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.named-c=
heckconf.html
--- a/head/contrib/bind9/doc/arm/man.named-checkconf.html	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.named-checkconf.html	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.named-checkconf.html,v 1.174.8.11 2011-08-03 02:35:11 tbox E=
xp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named-checkconf</cod=
e>  [<code class=3D"option">-h</code>] [<code class=3D"option">-v</code>] [=
<code class=3D"option">-j</code>] [<code class=3D"option">-t <em class=3D"r=
eplaceable"><code>directory</code></em></code>] {filename} [<code class=3D"=
option">-p</code>] [<code class=3D"option">-z</code>]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2618224"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2617986"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">named-checkconf</strong></span>
       checks the syntax, but not the semantics, of a
       <span><strong class=3D"command">named</strong></span> configuration =
file.  The file is parsed
@@ -70,7 +70,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2618294"></a><h2>OPTIONS</h2>
+<a name=3D"id2618056"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-h</span></dt>
 <dd><p>
@@ -109,21 +109,21 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2618428"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2618190"></a><h2>RETURN VALUES</h2>
 <p><span><strong class=3D"command">named-checkconf</strong></span>
       returns an exit status of 1 if
       errors were detected and 0 otherwise.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2618579"></a><h2>SEE ALSO</h2>
+<a name=3D"id2618204"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">named</span>=
(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named-che=
ckzone</span>(8)</span>,
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2618609"></a><h2>AUTHOR</h2>
+<a name=3D"id2618234"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.named-c=
heckzone.html
--- a/head/contrib/bind9/doc/arm/man.named-checkzone.html	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.named-checkzone.html	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.named-checkzone.html,v 1.183.8.11 2011-08-03 02:35:12 tbox E=
xp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -51,7 +51,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named-compilezone</c=
ode>  [<code class=3D"option">-d</code>] [<code class=3D"option">-j</code>]=
 [<code class=3D"option">-q</code>] [<code class=3D"option">-v</code>] [<co=
de class=3D"option">-c <em class=3D"replaceable"><code>class</code></em></c=
ode>] [<code class=3D"option">-C <em class=3D"replaceable"><code>mode</code=
></em></code>] [<code class=3D"option">-f <em class=3D"replaceable"><code>f=
ormat</code></em></code>] [<code class=3D"option">-F <em class=3D"replaceab=
le"><code>format</code></em></code>] [<code class=3D"option">-i <em class=
=3D"replaceable"><code>mode</code></em></code>] [<code class=3D"option">-k =
<em class=3D"replaceable"><code>mode</code></em></code>] [<code class=3D"op=
tion">-m <em class=3D"replaceable"><code>mode</code></em></code>] [<code cl=
ass=3D"option">-n <em class=3D"replaceable"><code>mode</code></em></code>] =
[<code class=3D"option">-r <em class=3D"replaceable"><code>mode</code></em>=
</code>] [<code class=3D"option">-s <em class=3D"replaceable"><code>style</=
code></em></code>] [<code class=3D"option">-t <em class=3D"replaceable"><co=
de>directory</code></em></code>] [<code class=3D"option">-w <em class=3D"re=
placeable"><code>directory</code></em></code>] [<code class=3D"option">-D</=
code>] [<code class=3D"option">-W <em class=3D"replaceable"><code>mode</cod=
e></em></code>] {<code class=3D"option">-o <em class=3D"replaceable"><code>=
filename</code></em></code>} {zonename} {filename}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2632057"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2633185"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">named-checkzone</strong></span>
       checks the syntax and integrity of a zone file.  It performs the
       same checks as <span><strong class=3D"command">named</strong></span>=
 does when loading a
@@ -71,7 +71,7 @@
      </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2632107"></a><h2>OPTIONS</h2>
+<a name=3D"id2633235"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-d</span></dt>
 <dd><p>
@@ -265,14 +265,14 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2673019"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2673464"></a><h2>RETURN VALUES</h2>
 <p><span><strong class=3D"command">named-checkzone</strong></span>
       returns an exit status of 1 if
       errors were detected and 0 otherwise.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2673033"></a><h2>SEE ALSO</h2>
+<a name=3D"id2673478"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">named</span>=
(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named-che=
ckconf</span>(8)</span>,
       <em class=3D"citetitle">RFC 1035</em>,
@@ -280,7 +280,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2673066"></a><h2>AUTHOR</h2>
+<a name=3D"id2673511"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.named-j=
ournalprint.html
--- a/head/contrib/bind9/doc/arm/man.named-journalprint.html	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.named-journalprint.html	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.named-journalprint.html,v 1.33.8.11 2011-08-03 02:35:12 tbox=
 Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named-journalprint</=
code>  {<em class=3D"replaceable"><code>journal</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2613550"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2612358"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">named-journalprint</strong></span>
       prints the contents of a zone journal file in a human-readable
@@ -76,7 +76,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2635032"></a><h2>SEE ALSO</h2>
+<a name=3D"id2638618"></a><h2>SEE ALSO</h2>
 <p>
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">nsupdate<=
/span>(8)</span>,
@@ -84,7 +84,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2635063"></a><h2>AUTHOR</h2>
+<a name=3D"id2638649"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.named.h=
tml
--- a/head/contrib/bind9/doc/arm/man.named.html	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/doc/arm/man.named.html	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.named.html,v 1.185.8.11 2011-08-03 02:35:13 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">named</code>  [<code=
 class=3D"option">-4</code>] [<code class=3D"option">-6</code>] [<code clas=
s=3D"option">-c <em class=3D"replaceable"><code>config-file</code></em></co=
de>] [<code class=3D"option">-d <em class=3D"replaceable"><code>debug-level=
</code></em></code>] [<code class=3D"option">-E <em class=3D"replaceable"><=
code>engine-name</code></em></code>] [<code class=3D"option">-f</code>] [<c=
ode class=3D"option">-g</code>] [<code class=3D"option">-m <em class=3D"rep=
laceable"><code>flag</code></em></code>] [<code class=3D"option">-n <em cla=
ss=3D"replaceable"><code>#cpus</code></em></code>] [<code class=3D"option">=
-p <em class=3D"replaceable"><code>port</code></em></code>] [<code class=3D=
"option">-s</code>] [<code class=3D"option">-S <em class=3D"replaceable"><c=
ode>#max-socks</code></em></code>] [<code class=3D"option">-t <em class=3D"=
replaceable"><code>directory</code></em></code>] [<code class=3D"option">-u=
 <em class=3D"replaceable"><code>user</code></em></code>] [<code class=3D"o=
ption">-v</code>] [<code class=3D"option">-V</code>] [<code class=3D"option=
">-x <em class=3D"replaceable"><code>cache-file</code></em></code>]</p></di=
v>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2632834"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2635533"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">named</strong></span>
       is a Domain Name System (DNS) server,
       part of the BIND 9 distribution from ISC.  For more
@@ -65,7 +65,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2632933"></a><h2>OPTIONS</h2>
+<a name=3D"id2635564"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-4</span></dt>
 <dd><p>
@@ -246,7 +246,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2639904"></a><h2>SIGNALS</h2>
+<a name=3D"id2660284"></a><h2>SIGNALS</h2>
 <p>
       In routine operation, signals should not be used to control
       the nameserver; <span><strong class=3D"command">rndc</strong></span>=
 should be used
@@ -267,7 +267,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2674906"></a><h2>CONFIGURATION</h2>
+<a name=3D"id2660334"></a><h2>CONFIGURATION</h2>
 <p>
       The <span><strong class=3D"command">named</strong></span> configurat=
ion file is too complex
       to describe in detail here.  A complete description is provided
@@ -284,7 +284,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2674955"></a><h2>FILES</h2>
+<a name=3D"id2660384"></a><h2>FILES</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><code class=3D"filename">/etc/named.conf</code></=
span></dt>
 <dd><p>
@@ -297,7 +297,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2675067"></a><h2>SEE ALSO</h2>
+<a name=3D"id2660427"></a><h2>SEE ALSO</h2>
 <p><em class=3D"citetitle">RFC 1033</em>,
       <em class=3D"citetitle">RFC 1034</em>,
       <em class=3D"citetitle">RFC 1035</em>,
@@ -310,7 +310,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2675138"></a><h2>AUTHOR</h2>
+<a name=3D"id2675585"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.nsec3ha=
sh.html
--- a/head/contrib/bind9/doc/arm/man.nsec3hash.html	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/doc/arm/man.nsec3hash.html	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.nsec3hash.html,v 1.34.8.12 2011-08-09 01:52:59 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -48,7 +48,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">nsec3hash</code>  {<=
em class=3D"replaceable"><code>salt</code></em>} {<em class=3D"replaceable"=
><code>algorithm</code></em>} {<em class=3D"replaceable"><code>iterations</=
code></em>} {<em class=3D"replaceable"><code>domain</code></em>}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2616633"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2653133"></a><h2>DESCRIPTION</h2>
 <p>
       <span><strong class=3D"command">nsec3hash</strong></span> generates =
an NSEC3 hash based on
       a set of NSEC3 parameters.  This can be used to check the validity
@@ -56,7 +56,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2616648"></a><h2>ARGUMENTS</h2>
+<a name=3D"id2653148"></a><h2>ARGUMENTS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">salt</span></dt>
 <dd><p>
@@ -80,14 +80,14 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648795"></a><h2>SEE ALSO</h2>
+<a name=3D"id2653210"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">BIND 9 Administrator Reference Manual</em>,
       <em class=3D"citetitle">RFC 5155</em>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648812"></a><h2>AUTHOR</h2>
+<a name=3D"id2653227"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.nsupdat=
e.html
--- a/head/contrib/bind9/doc/arm/man.nsupdate.html	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/doc/arm/man.nsupdate.html	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.nsupdate.html,v 1.110.8.11 2011-08-03 02:35:12 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">nsupdate</code>  [<c=
ode class=3D"option">-d</code>] [<code class=3D"option">-D</code>] [[<code =
class=3D"option">-g</code>] |  [<code class=3D"option">-o</code>] |  [<code=
 class=3D"option">-l</code>] |  [<code class=3D"option">-y <em class=3D"rep=
laceable"><code>[<span class=3D"optional">hmac:</span>]keyname:secret</code=
></em></code>] |  [<code class=3D"option">-k <em class=3D"replaceable"><cod=
e>keyfile</code></em></code>]] [<code class=3D"option">-t <em class=3D"repl=
aceable"><code>timeout</code></em></code>] [<code class=3D"option">-u <em c=
lass=3D"replaceable"><code>udptimeout</code></em></code>] [<code class=3D"o=
ption">-r <em class=3D"replaceable"><code>udpretries</code></em></code>] [<=
code class=3D"option">-R <em class=3D"replaceable"><code>randomdev</code></=
em></code>] [<code class=3D"option">-v</code>] [filename]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2635224"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2639154"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">nsupdate</strong></span>
       is used to submit Dynamic DNS Update requests as defined in RFC 2136
       to a name server.
@@ -210,7 +210,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2638766"></a><h2>INPUT FORMAT</h2>
+<a name=3D"id2639897"></a><h2>INPUT FORMAT</h2>
 <p><span><strong class=3D"command">nsupdate</strong></span>
       reads input from
       <em class=3D"parameter"><code>filename</code></em>
@@ -498,7 +498,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2678249"></a><h2>EXAMPLES</h2>
+<a name=3D"id2678629"></a><h2>EXAMPLES</h2>
 <p>
       The examples below show how
       <span><strong class=3D"command">nsupdate</strong></span>
@@ -552,7 +552,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2678299"></a><h2>FILES</h2>
+<a name=3D"id2678679"></a><h2>FILES</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term"><code class=3D"constant">/etc/resolv.conf</code><=
/span></dt>
 <dd><p>
@@ -575,7 +575,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2678382"></a><h2>SEE ALSO</h2>
+<a name=3D"id2678762"></a><h2>SEE ALSO</h2>
 <p>
       <em class=3D"citetitle">RFC 2136</em>,
       <em class=3D"citetitle">RFC 3007</em>,
@@ -590,7 +590,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2678440"></a><h2>BUGS</h2>
+<a name=3D"id2678820"></a><h2>BUGS</h2>
 <p>
       The TSIG key is redundantly stored in two separate files.
       This is a consequence of nsupdate using the DST library
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.rndc-co=
nfgen.html
--- a/head/contrib/bind9/doc/arm/man.rndc-confgen.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/doc/arm/man.rndc-confgen.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.rndc-confgen.html,v 1.189.8.11 2011-08-03 02:35:09 tbox Exp =
$ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">rndc-confgen</code> =
 [<code class=3D"option">-a</code>] [<code class=3D"option">-b <em class=3D=
"replaceable"><code>keysize</code></em></code>] [<code class=3D"option">-c =
<em class=3D"replaceable"><code>keyfile</code></em></code>] [<code class=3D=
"option">-h</code>] [<code class=3D"option">-k <em class=3D"replaceable"><c=
ode>keyname</code></em></code>] [<code class=3D"option">-p <em class=3D"rep=
laceable"><code>port</code></em></code>] [<code class=3D"option">-r <em cla=
ss=3D"replaceable"><code>randomfile</code></em></code>] [<code class=3D"opt=
ion">-s <em class=3D"replaceable"><code>address</code></em></code>] [<code =
class=3D"option">-t <em class=3D"replaceable"><code>chrootdir</code></em></=
code>] [<code class=3D"option">-u <em class=3D"replaceable"><code>user</cod=
e></em></code>]</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2642305"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2642617"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">rndc-confgen</strong></span>
       generates configuration files
       for <span><strong class=3D"command">rndc</strong></span>.  It can be=
 used as a
@@ -66,7 +66,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2642439"></a><h2>OPTIONS</h2>
+<a name=3D"id2642683"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-a</span></dt>
 <dd>
@@ -173,7 +173,7 @@
 </dl></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2643098"></a><h2>EXAMPLES</h2>
+<a name=3D"id2650101"></a><h2>EXAMPLES</h2>
 <p>
       To allow <span><strong class=3D"command">rndc</strong></span> to be =
used with
       no manual configuration, run
@@ -190,7 +190,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648548"></a><h2>SEE ALSO</h2>
+<a name=3D"id2652410"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">rndc</span>(=
8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rndc.conf=
</span>(5)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
@@ -198,7 +198,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2648586"></a><h2>AUTHOR</h2>
+<a name=3D"id2652449"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.rndc.co=
nf.html
--- a/head/contrib/bind9/doc/arm/man.rndc.conf.html	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/doc/arm/man.rndc.conf.html	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.rndc.conf.html,v 1.190.8.11 2011-08-03 02:35:12 tbox Exp $ -=
->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">rndc.conf</code> </p=
></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2614578"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2641106"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"filename">rndc.conf</code> is the configuration file
       for <span><strong class=3D"command">rndc</strong></span>, the BIND 9=
 name server control
       utility.  This file has a similar structure and syntax to
@@ -135,7 +135,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2640759"></a><h2>EXAMPLE</h2>
+<a name=3D"id2641346"></a><h2>EXAMPLE</h2>
 <pre class=3D"programlisting">
       options {
         default-server  localhost;
@@ -209,7 +209,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2641358"></a><h2>NAME SERVER CONFIGURATION</h2>
+<a name=3D"id2641672"></a><h2>NAME SERVER CONFIGURATION</h2>
 <p>
       The name server must be configured to accept rndc connections and
       to recognize the key specified in the <code class=3D"filename">rndc.=
conf</code>
@@ -219,7 +219,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2641384"></a><h2>SEE ALSO</h2>
+<a name=3D"id2641698"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">rndc</span>(=
8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rndc-conf=
gen</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">mmencode<=
/span>(1)</span>,
@@ -227,7 +227,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2641422"></a><h2>AUTHOR</h2>
+<a name=3D"id2642419"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/man.rndc.ht=
ml
--- a/head/contrib/bind9/doc/arm/man.rndc.html	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/doc/arm/man.rndc.html	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  - Copyright (C) 2000-2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: man.rndc.html,v 1.188.8.11 2011-08-03 02:35:12 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 <div class=3D"cmdsynopsis"><p><code class=3D"command">rndc</code>  [<code =
class=3D"option">-b <em class=3D"replaceable"><code>source-address</code></=
em></code>] [<code class=3D"option">-c <em class=3D"replaceable"><code>conf=
ig-file</code></em></code>] [<code class=3D"option">-k <em class=3D"replace=
able"><code>key-file</code></em></code>] [<code class=3D"option">-s <em cla=
ss=3D"replaceable"><code>server</code></em></code>] [<code class=3D"option"=
>-p <em class=3D"replaceable"><code>port</code></em></code>] [<code class=
=3D"option">-V</code>] [<code class=3D"option">-y <em class=3D"replaceable"=
><code>key_id</code></em></code>] {command}</p></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2640011"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2640665"></a><h2>DESCRIPTION</h2>
 <p><span><strong class=3D"command">rndc</strong></span>
       controls the operation of a name
       server.  It supersedes the <span><strong class=3D"command">ndc</stro=
ng></span> utility
@@ -79,7 +79,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2640061"></a><h2>OPTIONS</h2>
+<a name=3D"id2640715"></a><h2>OPTIONS</h2>
 <div class=3D"variablelist"><dl>
 <dt><span class=3D"term">-b <em class=3D"replaceable"><code>source-address=
</code></em></span></dt>
 <dd><p>
@@ -151,7 +151,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2640355"></a><h2>LIMITATIONS</h2>
+<a name=3D"id2640940"></a><h2>LIMITATIONS</h2>
 <p><span><strong class=3D"command">rndc</strong></span>
       does not yet support all the commands of
       the BIND 8 <span><strong class=3D"command">ndc</strong></span> utili=
ty.
@@ -165,7 +165,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2640386"></a><h2>SEE ALSO</h2>
+<a name=3D"id2640971"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">rndc.conf</s=
pan>(5)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">rndc-conf=
gen</span>(8)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">named</sp=
an>(8)</span>,
@@ -175,7 +175,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2640578"></a><h2>AUTHOR</h2>
+<a name=3D"id2641027"></a><h2>AUTHOR</h2>
 <p><span class=3D"corpauthor">Internet Systems Consortium</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/managed-key=
s.xml
--- a/head/contrib/bind9/doc/arm/managed-keys.xml	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/arm/managed-keys.xml	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: managed-keys.xml,v 1.3 2010-02-03 23:49:07 tbox Exp $ -->
+<!-- $Id: managed-keys.xml,v 1.3 2010/02/03 23:49:07 tbox Exp $ -->
=20
 <sect1 id=3D"rfc5011.support">
   <title>Dynamic Trust Anchor Management</title>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/arm/pkcs11.xml
--- a/head/contrib/bind9/doc/arm/pkcs11.xml	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/arm/pkcs11.xml	Tue Apr 17 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
                [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2010, 2012  Internet Systems Consortium, Inc. ("ISC")
  -
  - Permission to use, copy, modify, and/or distribute this software for any
  - purpose with or without fee is hereby granted, provided that the above
@@ -17,7 +17,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: pkcs11.xml,v 1.3 2010-02-06 07:42:02 marka Exp $ -->
+<!-- $Id$ -->
=20
 <sect1 id=3D"pkcs11">
   <title>PKCS #11 (Cryptoki) support</title>
@@ -68,12 +68,15 @@
         is an example of such a device.</para>
       </listitem>
     </itemizedlist>
-    <para>The modified OpenSSL code is included in the BIND 9.7.0
-    release, in the form of a context diff against the latest OpenSSL.
+    <para>The modified OpenSSL code is included in the BIND 9 release,
+        in the form of a context diff against the latest verions of
+        OpenSSL.  OpenSSL 0.9.8 and 1.0.0 are both supported; there are
+        separate diffs for each version.  In the examples to follow,
+        we use OpenSSL 0.9.8, but the same methods work with OpenSSL 1.0.0.
     </para>
     <note>
-      The latest OpenSSL version at the time of the BIND release
-      is 0.9.8l.
+      The latest OpenSSL versions at the time of the BIND release
+      are 0.9.8s and 1.0.0f.
       ISC will provide an updated patch as new versions of OpenSSL
       are released. The version number in the following examples
       is expected to change.</note>
@@ -82,18 +85,18 @@
     necessary to build OpenSSL with this patch in place and inform
     it of the path to the HSM-specific PKCS #11 provider
     library.</para>
-    <para>Obtain OpenSSL 0.9.8l:</para>
+    <para>Obtain OpenSSL 0.9.8s:</para>
     <screen>
-$ <userinput>wget <ulink>http://www.openssl.org/source/openssl-0.9.8l.tar.=
gz</ulink></userinput>
+$ <userinput>wget <ulink>http://www.openssl.org/source/openssl-0.9.8s.tar.=
gz</ulink></userinput>
 </screen>
     <para>Extract the tarball:</para>
     <screen>
-$ <userinput>tar zxf openssl-0.9.8l.tar.gz</userinput>
+$ <userinput>tar zxf openssl-0.9.8s.tar.gz</userinput>
 </screen>
     <para>Apply the patch from the BIND 9 release:</para>
     <screen>
-$ <userinput>patch -p1 -d openssl-0.9.8l \
-            < bind-9.7.0/bin/pkcs11/openssl-0.9.8l-patch</userinput>
+$ <userinput>patch -p1 -d openssl-0.9.8s \
+            < bind9/bin/pkcs11/openssl-0.9.8s-patch</userinput>
 </screen>
     <note>(Note that the patch file may not be compatible with the
     "patch" utility on all operating systems. You may need to
@@ -124,7 +127,7 @@
       <para>Finally, the Keyper library requires threads, so we
       must specify -pthread.</para>
       <screen>
-$ <userinput>cd openssl-0.9.8l</userinput>
+$ <userinput>cd openssl-0.9.8s</userinput>
 $ <userinput>./Configure linux-generic32 -m32 -pthread \
             --pk11-libname=3D/opt/pkcs11/usr/lib/libpkcs11.so \
             --pk11-flavor=3Dsign-only \
@@ -145,7 +148,7 @@
       <para>In this example, we are building on Solaris x86 on an
       AMD64 system.</para>
       <screen>
-$ <userinput>cd openssl-0.9.8l</userinput>
+$ <userinput>cd openssl-0.9.8s</userinput>
 $ <userinput>./Configure solaris64-x86_64-cc \
             --pk11-libname=3D/usr/lib/64/libpkcs11.so \
             --pk11-flavor=3Dcrypto-accelerator \
@@ -156,36 +159,74 @@
       <para>After configuring, run=20
       <command>make</command> and=20
       <command>make test</command>.</para>
-      <para>Once you have built OpenSSL, run
-      "<command>apps/openssl engine pkcs11</command>" to confirm
-      that PKCS #11 support was compiled in correctly. The output
-      should be one of the following lines, depending on the flavor
-      selected:</para>
+    </sect3>
+    <sect3>
+      <!-- Example 3 -->
+      <title>Building OpenSSL for SoftHSM</title>
+      <para>SoftHSM is a software library provided by the OpenDNSSEC
+      project (http://www.opendnssec.org) which provides a PKCS#11
+      interface to a virtual HSM, implemented in the form of encrypted
+      data on the local filesystem.  It uses the Botan library for
+      encryption and SQLite3 for data storage.  Though less secure
+      than a true HSM, it can provide more secure key storage than
+      traditional key files, and can allow you to experiment with
+      PKCS#11 when an HSM is not available.</para>
+      <para>The SoftHSM cryptographic store must be installed and
+      initialized before using it with OpenSSL, and the SOFTHSM_CONF
+      environment variable must always point to the SoftHSM configuration
+      file:</para>
       <screen>
+$ <userinput> cd softhsm-1.3.0 </userinput>
+$ <userinput> configure --prefix=3D/opt/pkcs11/usr </userinput>
+$ <userinput> make </userinput>
+$ <userinput> make install </userinput>
+$ <userinput> export SOFTHSM_CONF=3D/opt/pkcs11/softhsm.conf </userinput>
+$ <userinput> echo "0:/opt/pkcs11/softhsm.db" > $SOFTHSM_CONF </userinput>
+$ <userinput> /opt/pkcs11/usr/bin/softhsm --init-token 0 --slot 0 --label =
softhsm </userinput>
+</screen>
+      <para>SoftHSM can perform all cryptographic operations, but
+      since it only uses your system CPU, there is no need to use it
+      for anything but signing.  Therefore, we choose the 'sign-only'
+      flavor when building OpenSSL.</para>
+      <screen>
+$ <userinput>cd openssl-0.9.8s</userinput>
+$ <userinput>./Configure linux-x86_64 -pthread \
+            --pk11-libname=3D/opt/pkcs11/usr/lib/libpkcs11.so \
+            --pk11-flavor=3Dsign-only \
+            --prefix=3D/opt/pkcs11/usr</userinput>
+</screen>
+      <para>After configuring, run "<command>make</command>"
+      and "<command>make test</command>".</para>
+    </sect3>
+    <para>Once you have built OpenSSL, run
+    "<command>apps/openssl engine pkcs11</command>" to confirm
+    that PKCS #11 support was compiled in correctly. The output
+    should be one of the following lines, depending on the flavor
+    selected:</para>
+    <screen>
         (pkcs11) PKCS #11 engine support (sign only)
 </screen>
-      <para>Or:</para>
-      <screen>
+    <para>Or:</para>
+    <screen>
         (pkcs11) PKCS #11 engine support (crypto accelerator)
 </screen>
-      <para>Next, run
-      "<command>apps/openssl engine pkcs11 -t</command>". This will
-      attempt to initialize the PKCS #11 engine. If it is able to
-      do so successfully, it will report
-      <quote><literal>[ available ]</literal></quote>.</para>
-      <para>If the output is correct, run
-      "<command>make install</command>" which will install the
-      modified OpenSSL suite to=20
-      <filename>/opt/pkcs11/usr</filename>.</para>
-    </sect3>
+    <para>Next, run
+    "<command>apps/openssl engine pkcs11 -t</command>". This will
+    attempt to initialize the PKCS #11 engine. If it is able to
+    do so successfully, it will report
+    <quote><literal>[ available ]</literal></quote>.</para>
+    <para>If the output is correct, run
+    "<command>make install</command>" which will install the
+    modified OpenSSL suite to=20
+    <filename>/opt/pkcs11/usr</filename>.</para>
   </sect2>
   <sect2>
     <title>Building BIND 9 with PKCS#11</title>
     <para>When building BIND 9, the location of the custom-built
     OpenSSL library must be specified via configure.</para>
     <sect3>
-      <!-- Example 3 -->
-      <title>Configuring BIND 9 for Linux</title>
+      <!-- Example 4 -->
+      <title>Configuring BIND 9 for Linux with the AEP Keyper</title>
       <para>To link with the PKCS #11 provider, threads must be
       enabled in the BIND 9 build.</para>
       <para>The PKCS #11 library for the AEP Keyper is currently
@@ -193,19 +234,19 @@
       64-bit host, we must force a 32-bit build by adding "-m32" to
       the CC options on the "configure" command line.</para>
       <screen>
-$ <userinput>cd ../bind-9.7.0</userinput>
+$ <userinput>cd ../bind9</userinput>
 $ <userinput>./configure CC=3D"gcc -m32" --enable-threads \
            --with-openssl=3D/opt/pkcs11/usr \
            --with-pkcs11=3D/opt/pkcs11/usr/lib/libpkcs11.so</userinput>
 </screen>
     </sect3>
     <sect3>
-      <!-- Example 4 -->
-      <title>Configuring BIND 9 for Solaris</title>
+      <!-- Example 5 -->
+      <title>Configuring BIND 9 for Solaris with the SCA 6000</title>
       <para>To link with the PKCS #11 provider, threads must be
       enabled in the BIND 9 build.</para>
       <screen>
-$ <userinput>cd ../bind-9.7.0</userinput>
+$ <userinput>cd ../bind9</userinput>
 $ <userinput>./configure CC=3D"cc -xarch=3Damd64" --enable-threads \
             --with-openssl=3D/opt/pkcs11/usr \
             --with-pkcs11=3D/usr/lib/64/libpkcs11.so</userinput>
@@ -217,10 +258,22 @@
       same as the --prefix argument to the OpenSSL
       Configure).</para>
     </sect3>
+    <sect3>
+      <!-- Example 6 -->
+      <title>Configuring BIND 9 for SoftHSM</title>
+      <screen>
+$ <userinput>cd ../bind9</userinput>
+$ <userinput>./configure --enable-threads \
+           --with-openssl=3D/opt/pkcs11/usr \
+           --with-pkcs11=3D/opt/pkcs11/usr/lib/libpkcs11.so</userinput>
+</screen>
+    </sect3>
     <para>After configuring, run
     "<command>make</command>",
     "<command>make test</command>" and
     "<command>make install</command>".</para>
+    <para>(Note: If "make test" fails in the "pkcs11" system test, you may
+    have forgotten to set the SOFTHSM_CONF environment variable.)</para>
   </sect2>
   <sect2>
     <title>PKCS #11 Tools</title>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/Makefile.in
--- a/head/contrib/bind9/doc/misc/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/misc/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.9 2009-07-10 23:47:58 tbox Exp $
+# $Id: Makefile.in,v 1.9 2009/07/10 23:47:58 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/dnssec
--- a/head/contrib/bind9/doc/misc/dnssec	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/misc/dnssec	Tue Apr 17 11:51:51 2012 +0300
@@ -81,4 +81,4 @@
 ensure the integrity of zone transfers.
=20
=20
-$Id: dnssec,v 1.19 2004-03-05 05:04:53 marka Exp $
+$Id: dnssec,v 1.19 2004/03/05 05:04:53 marka Exp $
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/format-opt=
ions.pl
--- a/head/contrib/bind9/doc/misc/format-options.pl	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/doc/misc/format-options.pl	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: format-options.pl,v 1.5 2007-09-24 04:21:59 marka Exp $
+# $Id: format-options.pl,v 1.5 2007/09/24 04:21:59 marka Exp $
=20
 print <<END;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/ipv6
--- a/head/contrib/bind9/doc/misc/ipv6	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/misc/ipv6	Tue Apr 17 11:51:51 2012 +0300
@@ -110,4 +110,4 @@
 3542:  Advanced Sockets Application Program Interface (API) for IPv6
=20
=20
-$Id: ipv6,v 1.9 2004-08-10 04:27:51 jinmei Exp $
+$Id: ipv6,v 1.9 2004/08/10 04:27:51 jinmei Exp $
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/migration
--- a/head/contrib/bind9/doc/misc/migration	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/misc/migration	Tue Apr 17 11:51:51 2012 +0300
@@ -264,4 +264,4 @@
 start the named process.
=20
=20
-$Id: migration,v 1.49 2008-03-18 15:42:53 jreed Exp $
+$Id: migration,v 1.49 2008/03/18 15:42:53 jreed Exp $
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/migration-=
4to9
--- a/head/contrib/bind9/doc/misc/migration-4to9	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/doc/misc/migration-4to9	Tue Apr 17 11:51:51 2012 +=
0300
@@ -2,7 +2,7 @@
 Copyright (C) 2001  Internet Software Consortium.
 See COPYRIGHT in the source root or http://isc.org/copyright.html for term=
s.
=20
-$Id: migration-4to9,v 1.4 2004-03-05 05:04:53 marka Exp $
+$Id: migration-4to9,v 1.4 2004/03/05 05:04:53 marka Exp $
=20
 		   BIND 4 to BIND 9 Migration Notes
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/options
--- a/head/contrib/bind9/doc/misc/options	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/misc/options	Tue Apr 17 11:51:51 2012 +0300
@@ -74,6 +74,7 @@
             * ) ];
         attach-cache <string>;
         auth-nxdomain <boolean>; // default changed
+        auto-dnssec ( allow | maintain | off );
         avoid-v4-udp-ports { <portrange>; ... };
         avoid-v6-udp-ports { <portrange>; ... };
         bindkeys-file <quoted_string>;
@@ -113,7 +114,7 @@
         dnssec-accept-expired <boolean>;
         dnssec-dnskey-kskonly <boolean>;
         dnssec-enable <boolean>;
-        dnssec-lookaside ( <string> trust-anchor <string> | auto );
+        dnssec-lookaside ( <string> trust-anchor <string> | auto | no );
         dnssec-must-be-secure <string> <boolean>;
         dnssec-secure-to-insecure <boolean>;
         dnssec-validation ( yes | no | auto );
@@ -196,8 +197,8 @@
         reserved-sockets <integer>;
         resolver-query-timeout <integer>;
         response-policy {
-                zone <string> [ policy ( given | no-op | nxdomain | nodata
-                    | cname <domain> ) ];
+                zone <string> [ policy ( given | disabled | passthru |
+                    no-op | nxdomain | nodata | cname <domain> ) ];
         };
         rfc2308-type1 <boolean>; // not yet implemented
         root-delegation-only [ exclude { <quoted_string>; ... } ];
@@ -297,6 +298,7 @@
             * ) ];
         attach-cache <string>;
         auth-nxdomain <boolean>; // default changed
+        auto-dnssec ( allow | maintain | off );
         cache-file <quoted_string>;
         check-dup-records ( fail | warn | ignore );
         check-integrity <boolean>;
@@ -332,7 +334,7 @@
         dnssec-accept-expired <boolean>;
         dnssec-dnskey-kskonly <boolean>;
         dnssec-enable <boolean>;
-        dnssec-lookaside ( <string> trust-anchor <string> | auto );
+        dnssec-lookaside ( <string> trust-anchor <string> | auto | no );
         dnssec-must-be-secure <string> <boolean>;
         dnssec-secure-to-insecure <boolean>;
         dnssec-validation ( yes | no | auto );
@@ -399,8 +401,8 @@
         request-nsid <boolean>;
         resolver-query-timeout <integer>;
         response-policy {
-                zone <string> [ policy ( given | no-op | nxdomain | nodata
-                    | cname <domain> ) ];
+                zone <string> [ policy ( given | disabled | passthru |
+                    no-op | nxdomain | nodata | cname <domain> ) ];
         };
         rfc2308-type1 <boolean>; // not yet implemented
         root-delegation-only [ exclude { <quoted_string>; ... } ];
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/rfc-compli=
ance
--- a/head/contrib/bind9/doc/misc/rfc-compliance	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/doc/misc/rfc-compliance	Tue Apr 17 11:51:51 2012 +=
0300
@@ -2,7 +2,7 @@
 Copyright (C) 2001  Internet Software Consortium.
 See COPYRIGHT in the source root or http://isc.org/copyright.html for term=
s.
=20
-$Id: rfc-compliance,v 1.4 2004-03-05 05:04:53 marka Exp $
+$Id: rfc-compliance,v 1.4 2004/03/05 05:04:53 marka Exp $
=20
 BIND 9 is striving for strict compliance with IETF standards.  We
 believe this release of BIND 9 complies with the following RFCs, with
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/roadmap
--- a/head/contrib/bind9/doc/misc/roadmap	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/misc/roadmap	Tue Apr 17 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
 Copyright (C) 2000, 2001  Internet Software Consortium.
 See COPYRIGHT in the source root or http://isc.org/copyright.html for term=
s.
=20
-$Id: roadmap,v 1.2 2004-03-05 05:04:54 marka Exp $
+$Id: roadmap,v 1.2 2004/03/05 05:04:54 marka Exp $
=20
 Road Map to the BIND 9 Source Tree
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/sdb
--- a/head/contrib/bind9/doc/misc/sdb	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/doc/misc/sdb	Tue Apr 17 11:51:51 2012 +0300
@@ -166,4 +166,4 @@
 A future release may support dynamic loading of sdb drivers.
=20
=20
-$Id: sdb,v 1.6 2004-03-05 05:04:54 marka Exp $
+$Id: sdb,v 1.6 2004/03/05 05:04:54 marka Exp $
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/doc/misc/sort-optio=
ns.pl
--- a/head/contrib/bind9/doc/misc/sort-options.pl	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/doc/misc/sort-options.pl	Tue Apr 17 11:51:51 2012 =
+0300
@@ -14,7 +14,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: sort-options.pl,v 1.3 2007-09-24 23:46:48 tbox Exp $
+# $Id: sort-options.pl,v 1.3 2007/09/24 23:46:48 tbox Exp $
=20
 sub sortlevel() {
 	my @options =3D ();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/isc-config.sh.in
--- a/head/contrib/bind9/isc-config.sh.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/isc-config.sh.in	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: isc-config.sh.in,v 1.17 2007-06-19 23:46:59 tbox Exp $
+# $Id: isc-config.sh.in,v 1.17 2007/06/19 23:46:59 tbox Exp $
=20
 prefix=3D at prefix@
 exec_prefix=3D at exec_prefix@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/Makefile.in
--- a/head/contrib/bind9/lib/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.21 2007-06-19 23:47:13 tbox Exp $
+# $Id: Makefile.in,v 1.21 2007/06/19 23:47:13 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/Makefile.=
in
--- a/head/contrib/bind9/lib/bind9/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/bind9/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.14 2009-12-05 23:31:40 each Exp $
+# $Id: Makefile.in,v 1.14 2009/12/05 23:31:40 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/api
--- a/head/contrib/bind9/lib/bind9/api	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/bind9/api	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,8 @@
+# LIBINTERFACE ranges
+# 9.6: 50-59, 110-119
+# 9.7: 60-79
+# 9.8: 80-89
+# 9.9: 90-109
 LIBINTERFACE =3D 80
-LIBREVISION =3D 3
+LIBREVISION =3D 4
 LIBAGE =3D 0
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/check.c
--- a/head/contrib/bind9/lib/bind9/check.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/bind9/check.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2001-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: check.c,v 1.125.14.6 2011-06-17 07:04:31 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -671,8 +671,17 @@
 	unsigned int max;
 } intervaltable;
=20
+typedef enum {
+	optlevel_config,
+	optlevel_options,
+	optlevel_view,
+	optlevel_zone
+} optlevel_t;
+
 static isc_result_t
-check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx=
) {
+check_options(const cfg_obj_t *options, isc_log_t *logctx, isc_mem_t *mctx,
+	      optlevel_t optlevel)
+{
 	isc_result_t result =3D ISC_R_SUCCESS;
 	isc_result_t tresult;
 	unsigned int i;
@@ -844,19 +853,23 @@
 		     element =3D cfg_list_next(element))
 		{
 			const char *dlv;
-			const cfg_obj_t *anchor;
+			const cfg_obj_t *dlvobj, *anchor;
=20
 			obj =3D cfg_listelt_value(element);
=20
-			dlv =3D cfg_obj_asstring(cfg_tuple_get(obj, "domain"));
 			anchor =3D cfg_tuple_get(obj, "trust-anchor");
+			dlvobj =3D cfg_tuple_get(obj, "domain");
+			dlv =3D cfg_obj_asstring(dlvobj);
=20
 			/*
-			 * If domain is "auto" and trust anchor is missing,
-			 * skip remaining tests
+			 * If domain is "auto" or "no" and trust anchor
+			 * is missing, skip remaining tests
 			 */
-			if (!strcmp(dlv, "auto") && cfg_obj_isvoid(anchor))
-				continue;
+			if (cfg_obj_isvoid(anchor)) {
+				if (!strcasecmp(dlv, "no") ||
+				    !strcasecmp(dlv, "auto"))
+					continue;
+			}
=20
 			isc_buffer_init(&b, dlv, strlen(dlv));
 			isc_buffer_add(&b, strlen(dlv));
@@ -908,8 +921,8 @@
 			} else {
 				cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
 					"dnssec-lookaside requires "
-					"either 'auto' or a domain and "
-					"trust anchor");
+					"either 'auto' or 'no', or a "
+					"domain and trust anchor");
 				if (result =3D=3D ISC_R_SUCCESS)
 					result =3D ISC_R_FAILURE;
 			}
@@ -920,6 +933,21 @@
 	}
=20
 	/*
+	 * Check auto-dnssec at the view/options level
+	 */
+	obj =3D NULL;
+	(void)cfg_map_get(options, "auto-dnssec", &obj);
+	if (obj !=3D NULL) {
+		const char *arg =3D cfg_obj_asstring(obj);
+		if (optlevel !=3D optlevel_zone && strcasecmp(arg, "off") !=3D 0) {
+			cfg_obj_log(obj, logctx, ISC_LOG_ERROR,
+				    "auto-dnssec may only be activated at the "
+				    "zone level");
+			result =3D ISC_R_FAILURE;
+		}
+	}
+
+	/*
 	 * Check dnssec-must-be-secure.
 	 */
 	obj =3D NULL;
@@ -1644,7 +1672,7 @@
 	/*
 	 * Check various options.
 	 */
-	tresult =3D check_options(zoptions, logctx, mctx);
+	tresult =3D check_options(zoptions, logctx, mctx, optlevel_zone);
 	if (tresult !=3D ISC_R_SUCCESS)
 		result =3D tresult;
=20
@@ -2101,7 +2129,7 @@
 	 * Check that all zone statements are syntactically correct and
 	 * there are no duplicate zones.
 	 */
-	tresult =3D isc_symtab_create(mctx, 100, freekey, mctx,
+	tresult =3D isc_symtab_create(mctx, 1000, freekey, mctx,
 				    ISC_FALSE, &symtab);
 	if (tresult !=3D ISC_R_SUCCESS)
 		return (ISC_R_NOMEMORY);
@@ -2165,7 +2193,7 @@
 	 * Check that all key statements are syntactically correct and
 	 * there are no duplicate keys.
 	 */
-	tresult =3D isc_symtab_create(mctx, 100, freekey, mctx,
+	tresult =3D isc_symtab_create(mctx, 1000, freekey, mctx,
 				    ISC_FALSE, &symtab);
 	if (tresult !=3D ISC_R_SUCCESS)
 		return (ISC_R_NOMEMORY);
@@ -2277,13 +2305,16 @@
 				result =3D tresult;
 		}
 	}
+
 	/*
 	 * Check options.
 	 */
 	if (voptions !=3D NULL)
-		tresult =3D check_options(voptions, logctx, mctx);
+		tresult =3D check_options(voptions, logctx, mctx,
+					optlevel_view);
 	else
-		tresult =3D check_options(config, logctx, mctx);
+		tresult =3D check_options(config, logctx, mctx,
+					optlevel_config);
 	if (tresult !=3D ISC_R_SUCCESS)
 		result =3D tresult;
=20
@@ -2574,7 +2605,8 @@
 	(void)cfg_map_get(config, "options", &options);
=20
 	if (options !=3D NULL &&
-	    check_options(options, logctx, mctx) !=3D ISC_R_SUCCESS)
+	    check_options(options, logctx, mctx,
+			  optlevel_options) !=3D ISC_R_SUCCESS)
 		result =3D ISC_R_FAILURE;
=20
 	if (bind9_check_logging(config, logctx, mctx) !=3D ISC_R_SUCCESS)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/getaddres=
ses.c
--- a/head/contrib/bind9/lib/bind9/getaddresses.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/bind9/getaddresses.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getaddresses.c,v 1.22 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: getaddresses.c,v 1.22 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/include/M=
akefile.in
--- a/head/contrib/bind9/lib/bind9/include/Makefile.in	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/bind9/include/Makefile.in	Tue Apr 17 11:51:51 =
2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4 2007-06-19 23:47:16 tbox Exp $
+# $Id: Makefile.in,v 1.4 2007/06/19 23:47:16 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/include/b=
ind9/Makefile.in
--- a/head/contrib/bind9/lib/bind9/include/bind9/Makefile.in	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/bind9/include/bind9/Makefile.in	Tue Apr 17 11:=
51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.8 2007-06-19 23:47:16 tbox Exp $
+# $Id: Makefile.in,v 1.8 2007/06/19 23:47:16 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/include/b=
ind9/check.h
--- a/head/contrib/bind9/lib/bind9/include/bind9/check.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/bind9/include/bind9/check.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: check.h,v 1.9 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: check.h,v 1.9 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef BIND9_CHECK_H
 #define BIND9_CHECK_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/include/b=
ind9/getaddresses.h
--- a/head/contrib/bind9/lib/bind9/include/bind9/getaddresses.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/bind9/include/bind9/getaddresses.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getaddresses.h,v 1.11 2009-01-17 23:47:42 tbox Exp $ */
+/* $Id: getaddresses.h,v 1.11 2009/01/17 23:47:42 tbox Exp $ */
=20
 #ifndef BIND9_GETADDRESSES_H
 #define BIND9_GETADDRESSES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/include/b=
ind9/version.h
--- a/head/contrib/bind9/lib/bind9/include/bind9/version.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/bind9/include/bind9/version.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.h,v 1.9 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: version.h,v 1.9 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file bind9/version.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/bind9/version.c
--- a/head/contrib/bind9/lib/bind9/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/bind9/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.c,v 1.8 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: version.c,v 1.8 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/Makefile.in
--- a/head/contrib/bind9/lib/dns/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
 # Copyright (C) 1998-2003  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.176.8.2 2011-03-10 04:29:17 each Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/acache.c
--- a/head/contrib/bind9/lib/dns/acache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/acache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: acache.c,v 1.22 2008-02-07 23:46:54 tbox Exp $ */
+/* $Id: acache.c,v 1.22 2008/02/07 23:46:54 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/acl.c
--- a/head/contrib/bind9/lib/dns/acl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/acl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: acl.c,v 1.53.426.2 2011-06-17 23:47:11 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/adb.c
--- a/head/contrib/bind9/lib/dns/adb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/adb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: adb.c,v 1.254.14.4 2011-03-13 03:36:47 marka Exp $ */
+/* $Id$ */
=20
 /*! \file
  *
@@ -254,6 +254,7 @@
=20
 	ISC_LIST(dns_adblameinfo_t)     lameinfo;
 	ISC_LINK(dns_adbentry_t)        plink;
+
 };
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/api
--- a/head/contrib/bind9/lib/dns/api	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/api	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,8 @@
-LIBINTERFACE =3D 84
-LIBREVISION =3D 1
-LIBAGE =3D 3
+# LIBINTERFACE ranges
+# 9.6: 50-59, 110-119
+# 9.7: 60-79
+# 9.8: 80-89
+# 9.9: 90-109
+LIBINTERFACE =3D 87
+LIBREVISION =3D 0
+LIBAGE =3D 6
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/byaddr.c
--- a/head/contrib/bind9/lib/dns/byaddr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/byaddr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: byaddr.c,v 1.41 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: byaddr.c,v 1.41 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/cache.c
--- a/head/contrib/bind9/lib/dns/cache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/cache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cache.c,v 1.87.262.2 2011-03-03 23:47:09 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/callbacks.c
--- a/head/contrib/bind9/lib/dns/callbacks.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/callbacks.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: callbacks.c,v 1.17 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/client.c
--- a/head/contrib/bind9/lib/dns/client.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/client.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009-2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: client.c,v 1.12.24.2 2011-03-12 04:59:16 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/compress.c
--- a/head/contrib/bind9/lib/dns/compress.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/compress.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: compress.c,v 1.59 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: compress.c,v 1.59 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/db.c
--- a/head/contrib/bind9/lib/dns/db.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/db.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: db.c,v 1.97 2011-01-13 04:59:25 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -955,10 +955,11 @@
 isc_result_t
 dns_db_rpz_findips(dns_rpz_zone_t *rpz, dns_rpz_type_t rpz_type,
 		   dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *version,
-		   dns_rdataset_t *ardataset, dns_rpz_st_t *st)
+		   dns_rdataset_t *ardataset, dns_rpz_st_t *st,
+		   dns_name_t *query_qname)
 {
 	if (db->methods->rpz_findips =3D=3D NULL)
 		return (ISC_R_NOTIMPLEMENTED);
 	return ((db->methods->rpz_findips)(rpz, rpz_type, zone, db, version,
-					   ardataset, st));
+					   ardataset, st, query_qname));
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dbiterator.c
--- a/head/contrib/bind9/lib/dns/dbiterator.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dbiterator.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dbiterator.c,v 1.18 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: dbiterator.c,v 1.18 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dbtable.c
--- a/head/contrib/bind9/lib/dns/dbtable.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dbtable.c	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
  */
=20
 /*
- * $Id: dbtable.c,v 1.33 2007-06-19 23:47:16 tbox Exp $
+ * $Id: dbtable.c,v 1.33 2007/06/19 23:47:16 tbox Exp $
  */
=20
 /*! \file
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/diff.c
--- a/head/contrib/bind9/lib/dns/diff.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/diff.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 2000-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: diff.c,v 1.23.248.3 2011-03-25 23:53:52 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dispatch.c
--- a/head/contrib/bind9/lib/dns/dispatch.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dispatch.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dispatch.c,v 1.168.248.4 2011-04-06 10:30:08 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dlz.c
--- a/head/contrib/bind9/lib/dns/dlz.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dlz.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2005, 2007, 2009-2011  Internet Systems Consorti=
um, Inc. ("ISC")
+ * Portions Copyright (C) 2005, 2007, 2009-2012  Internet Systems Consorti=
um, Inc. ("ISC")
  * Portions Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -50,7 +50,7 @@
  * USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlz.c,v 1.10.14.2 2011-03-12 04:59:16 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dns64.c
--- a/head/contrib/bind9/lib/dns/dns64.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dns64.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2010-2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dns64.c,v 1.6.22.2 2011-03-12 04:59:16 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dnssec.c
--- a/head/contrib/bind9/lib/dns/dnssec.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dnssec.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -16,7 +16,7 @@
  */
=20
 /*
- * $Id: dnssec.c,v 1.119.170.4 2011-05-06 21:07:50 each Exp $
+ * $Id$
  */
=20
 /*! \file */
@@ -1134,17 +1134,15 @@
 }
=20
 static void
-get_hints(dns_dnsseckey_t *key) {
+get_hints(dns_dnsseckey_t *key, isc_stdtime_t now) {
 	isc_result_t result;
-	isc_stdtime_t now, publish, active, revoke, inactive, delete;
+	isc_stdtime_t publish, active, revoke, inactive, delete;
 	isc_boolean_t pubset =3D ISC_FALSE, actset =3D ISC_FALSE;
 	isc_boolean_t revset =3D ISC_FALSE, inactset =3D ISC_FALSE;
 	isc_boolean_t delset =3D ISC_FALSE;
=20
 	REQUIRE(key !=3D NULL && key->key !=3D NULL);
=20
-	isc_stdtime_get(&now);
-
 	result =3D dst_key_gettime(key->key, DST_TIME_PUBLISH, &publish);
 	if (result =3D=3D ISC_R_SUCCESS)
 		pubset =3D ISC_TRUE;
@@ -1241,6 +1239,7 @@
 	char namebuf[DNS_NAME_FORMATSIZE], *p;
 	isc_buffer_t b;
 	unsigned int len;
+	isc_stdtime_t now;
=20
 	REQUIRE(keylist !=3D NULL);
 	ISC_LIST_INIT(list);
@@ -1256,6 +1255,8 @@
 	RETERR(isc_dir_open(&dir, directory));
 	dir_open =3D ISC_TRUE;
=20
+	isc_stdtime_get(&now);
+
 	while (isc_dir_read(&dir) =3D=3D ISC_R_SUCCESS) {
 		if (dir.entry.name[0] =3D=3D 'K' &&
 		    dir.entry.length > len + 1 &&
@@ -1286,7 +1287,7 @@
=20
 			RETERR(dns_dnsseckey_create(mctx, &dstkey, &key));
 			key->source =3D dns_keysource_repository;
-			get_hints(key);
+			get_hints(key, now);
=20
 			if (key->legacy) {
 				dns_dnsseckey_destroy(mctx, &key);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/ds.c
--- a/head/contrib/bind9/lib/dns/ds.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/ds.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ds.c,v 1.13 2010-12-23 23:47:08 tbox Exp $ */
+/* $Id: ds.c,v 1.13 2010/12/23 23:47:08 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dst_api.c
--- a/head/contrib/bind9/lib/dns/dst_api.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dst_api.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("I=
SC")
+ * Portions Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("I=
SC")
  * Portions Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -31,7 +31,7 @@
=20
 /*
  * Principal Author: Brian Wellington
- * $Id: dst_api.c,v 1.57.10.1 2011-03-21 19:53:34 each Exp $
+ * $Id$
  */
=20
 /*! \file */
@@ -447,7 +447,6 @@
 		dst_key_free(&key);
 		return (DST_R_INVALIDPRIVATEKEY);
 	}
-	key->key_id =3D id;
=20
 	*keyp =3D key;
 	return (ISC_R_SUCCESS);
@@ -598,7 +597,7 @@
 	isc_uint8_t alg, proto;
 	isc_uint32_t flags, extflags;
 	dst_key_t *key =3D NULL;
-	dns_keytag_t id;
+	dns_keytag_t id, rid;
 	isc_region_t r;
 	isc_result_t result;
=20
@@ -613,6 +612,7 @@
 	alg =3D isc_buffer_getuint8(source);
=20
 	id =3D dst_region_computeid(&r, alg);
+	rid =3D dst_region_computerid(&r, alg);
=20
 	if (flags & DNS_KEYFLAG_EXTENDED) {
 		if (isc_buffer_remaininglength(source) < 2)
@@ -626,6 +626,7 @@
 	if (result !=3D ISC_R_SUCCESS)
 		return (result);
 	key->key_id =3D id;
+	key->key_rid =3D rid;
=20
 	*keyp =3D key;
 	return (ISC_R_SUCCESS);
@@ -926,13 +927,6 @@
 	if (key1->key_alg !=3D key2->key_alg)
 		return (ISC_FALSE);
=20
-	/*
-	 * For all algorithms except RSAMD5, revoking the key
-	 * changes the key ID, increasing it by 128.  If we want to
-	 * be able to find matching keys even if one of them is the
-	 * revoked version of the other one, then we need to check
-	 * for that possibility.
-	 */
 	if (key1->key_id !=3D key2->key_id) {
 		if (!match_revoked_key)
 			return (ISC_FALSE);
@@ -941,11 +935,8 @@
 		if ((key1->key_flags & DNS_KEYFLAG_REVOKE) =3D=3D
 		    (key2->key_flags & DNS_KEYFLAG_REVOKE))
 			return (ISC_FALSE);
-		if ((key1->key_flags & DNS_KEYFLAG_REVOKE) !=3D 0 &&
-		    key1->key_id !=3D ((key2->key_id + 128) & 0xffff))
-			return (ISC_FALSE);
-		if ((key2->key_flags & DNS_KEYFLAG_REVOKE) !=3D 0 &&
-		    key2->key_id !=3D ((key1->key_id + 128) & 0xffff))
+		if (key1->key_id !=3D key2->key_rid &&
+		    key1->key_rid !=3D key2->key_id)
 			return (ISC_FALSE);
 	}
=20
@@ -1572,7 +1563,8 @@
 	fprintf(fp, " ");
=20
 	isc_buffer_usedregion(&classb, &r);
-	isc_util_fwrite(r.base, 1, r.length, fp);
+	if ((unsigned) fwrite(r.base, 1, r.length, fp) !=3D r.length)
+	       ret =3D DST_R_WRITEERROR;
=20
 	if ((type & DST_TYPE_KEY) !=3D 0)
 		fprintf(fp, " KEY ");
@@ -1580,7 +1572,8 @@
 		fprintf(fp, " DNSKEY ");
=20
 	isc_buffer_usedregion(&textb, &r);
-	isc_util_fwrite(r.base, 1, r.length, fp);
+	if ((unsigned) fwrite(r.base, 1, r.length, fp) !=3D r.length)
+	       ret =3D DST_R_WRITEERROR;
=20
 	fputc('\n', fp);
 	fflush(fp);
@@ -1643,6 +1636,7 @@
=20
 	isc_buffer_usedregion(&dnsbuf, &r);
 	key->key_id =3D dst_region_computeid(&r, key->key_alg);
+	key->key_rid =3D dst_region_computerid(&r, key->key_alg);
 	return (ISC_R_SUCCESS);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dst_interna=
l.h
--- a/head/contrib/bind9/lib/dns/dst_internal.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/dns/dst_internal.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("I=
SC")
+ * Portions Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("I=
SC")
  * Portions Copyright (C) 2000-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -29,7 +29,7 @@
  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dst_internal.h,v 1.29 2011-01-11 23:47:13 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DST_DST_INTERNAL_H
 #define DST_DST_INTERNAL_H 1
@@ -94,6 +94,8 @@
 	unsigned int	key_alg;	/*%< algorithm of the key */
 	isc_uint32_t	key_flags;	/*%< flags of the public key */
 	isc_uint16_t	key_id;		/*%< identifier of the key */
+	isc_uint16_t	key_rid;	/*%< identifier of the key when
+					     revoked */
 	isc_uint16_t	key_bits;	/*%< hmac digest bits */
 	dns_rdataclass_t key_class;	/*%< class of the key record */
 	isc_mem_t	*mctx;		/*%< memory context */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dst_lib.c
--- a/head/contrib/bind9/lib/dns/dst_lib.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dst_lib.c	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
=20
 /*
  * Principal Author: Brian Wellington
- * $Id: dst_lib.c,v 1.5 2007-06-19 23:47:16 tbox Exp $
+ * $Id: dst_lib.c,v 1.5 2007/06/19 23:47:16 tbox Exp $
  */
=20
 /*! \file */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dst_openssl=
.h
--- a/head/contrib/bind9/lib/dns/dst_openssl.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/dns/dst_openssl.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dst_openssl.h,v 1.9.302.2 2011-03-12 04:59:16 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DST_OPENSSL_H
 #define DST_OPENSSL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dst_parse.c
--- a/head/contrib/bind9/lib/dns/dst_parse.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dst_parse.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004-2010  Internet Systems Consortium, Inc. ("I=
SC")
+ * Portions Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("I=
SC")
  * Portions Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -31,7 +31,7 @@
=20
 /*%
  * Principal Author: Brian Wellington
- * $Id: dst_parse.c,v 1.27 2010-12-23 04:07:58 marka Exp $
+ * $Id$
  */
=20
 #include <config.h>
@@ -641,9 +641,7 @@
 		}
 		isc_buffer_usedregion(&b, &r);
=20
-		fprintf(fp, "%s ", s);
-		isc_util_fwrite(r.base, 1, r.length, fp);
-		fprintf(fp, "\n");
+	       fprintf(fp, "%s %.*s\n", s, (int)r.length, r.base);
 	}
=20
 	/* Add the metadata tags */
@@ -661,14 +659,15 @@
=20
 			isc_buffer_init(&b, buffer, sizeof(buffer));
 			result =3D dns_time32_totext(when, &b);
-			if (result !=3D ISC_R_SUCCESS)
-				continue;
+		       if (result !=3D ISC_R_SUCCESS) {
+			       fclose(fp);
+			       return (DST_R_INVALIDPRIVATEKEY);
+		       }
=20
 			isc_buffer_usedregion(&b, &r);
=20
-			fprintf(fp, "%s ", timetags[i]);
-			isc_util_fwrite(r.base, 1, r.length, fp);
-			fprintf(fp, "\n");
+		       fprintf(fp, "%s %.*s\n", timetags[i], (int)r.length,
+				r.base);
 		}
 	}
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dst_parse.h
--- a/head/contrib/bind9/lib/dns/dst_parse.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dst_parse.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dst_parse.h,v 1.17 2010-12-23 23:47:08 tbox Exp $ */
+/* $Id: dst_parse.h,v 1.17 2010/12/23 23:47:08 tbox Exp $ */
=20
 /*! \file */
 #ifndef DST_DST_PARSE_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/dst_result.c
--- a/head/contrib/bind9/lib/dns/dst_result.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/dst_result.c	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
=20
 /*%
  * Principal Author: Brian Wellington
- * $Id: dst_result.c,v 1.7 2008-04-01 23:47:10 tbox Exp $
+ * $Id: dst_result.c,v 1.7 2008/04/01 23:47:10 tbox Exp $
  */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/ecdb.c
--- a/head/contrib/bind9/lib/dns/ecdb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/ecdb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009-2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ecdb.c,v 1.8 2011-01-14 00:51:43 tbox Exp $ */
+/* $Id$ */
=20
 #include "config.h"
=20
@@ -37,10 +37,6 @@
 #define ECDBNODE_MAGIC		ISC_MAGIC('E', 'C', 'D', 'N')
 #define VALID_ECDBNODE(ecdbn)	ISC_MAGIC_VALID(ecdbn, ECDBNODE_MAGIC)
=20
-#if DNS_RDATASET_FIXED
-#error "Fixed rdataset isn't supported in this implementation"
-#endif
-
 /*%
  * The 'ephemeral' cache DB (ecdb) implementation.  An ecdb just provides
  * temporary storage for ongoing name resolution with the common DB interf=
aces.
@@ -660,7 +656,11 @@
 		rdataset->private5 =3D NULL;
 		return (ISC_R_NOMORE);
 	}
+#if DNS_RDATASET_FIXED
+	raw +=3D 2 + (4 * count);
+#else
 	raw +=3D 2;
+#endif
 	/*
 	 * The privateuint4 field is the number of rdata beyond the cursor
 	 * position, so we decrement the total count by one before storing
@@ -686,7 +686,11 @@
 	rdataset->privateuint4 =3D count;
 	raw =3D rdataset->private5;
 	length =3D raw[0] * 256 + raw[1];
+#if DNS_RDATASET_FIXED
+	raw +=3D length + 4;
+#else
 	raw +=3D length + 2;
+#endif
 	rdataset->private5 =3D raw;
=20
 	return (ISC_R_SUCCESS);
@@ -702,7 +706,11 @@
 	REQUIRE(raw !=3D NULL);
=20
 	length =3D raw[0] * 256 + raw[1];
+#if DNS_RDATASET_FIXED
+	raw +=3D 4;
+#else
 	raw +=3D 2;
+#endif
 	if (rdataset->type =3D=3D dns_rdatatype_rrsig) {
 		if (*raw & DNS_RDATASLAB_OFFLINE)
 			flags |=3D DNS_RDATA_OFFLINE;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/forward.c
--- a/head/contrib/bind9/lib/dns/forward.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/forward.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: forward.c,v 1.14 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: forward.c,v 1.14 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/gen-unix.h
--- a/head/contrib/bind9/lib/dns/gen-unix.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/gen-unix.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gen-unix.h,v 1.21 2009-01-17 23:47:42 tbox Exp $ */
+/* $Id: gen-unix.h,v 1.21 2009/01/17 23:47:42 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/gen.c
--- a/head/contrib/bind9/lib/dns/gen.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/gen.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gen.c,v 1.85 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: gen.c,v 1.85 2009/12/04 22:06:37 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/gssapi_link=
.c
--- a/head/contrib/bind9/lib/dns/gssapi_link.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/dns/gssapi_link.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 2000-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -16,7 +16,7 @@
  */
=20
 /*
- * $Id: gssapi_link.c,v 1.16.10.1 2011-03-28 05:36:05 marka Exp $
+ * $Id$
  */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/gssapictx.c
--- a/head/contrib/bind9/lib/dns/gssapictx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/gssapictx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gssapictx.c,v 1.26.12.2 2011-04-07 23:05:01 marka Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
@@ -135,6 +135,7 @@
 	}
=20
 	result =3D dns_name_toprincipal(namep, buffer);
+	RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
 	isc_buffer_putuint8(buffer, 0);
 	isc_buffer_usedregion(buffer, &r);
 	REGION_TO_GBUFFER(r, *gbuffer);
@@ -309,7 +310,7 @@
 	if (gret !=3D GSS_S_COMPLETE) {
 		gss_log(3, "failed to acquire %s credentials for %s: %s",
 			initiate ? "initiate" : "accept",
-			(char *)gnamebuf.value,
+			(gname !=3D NULL) ? (char *)gnamebuf.value : "?",
 			gss_error_tostring(gret, minor, buf, sizeof(buf)));
 		check_config((char *)array);
 		return (ISC_R_FAILURE);
@@ -317,12 +318,14 @@
=20
 	gss_log(4, "acquired %s credentials for %s",
 		initiate ? "initiate" : "accept",
-		(char *)gnamebuf.value);
+		(gname !=3D NULL) ? (char *)gnamebuf.value : "?");
=20
 	log_cred(*cred);
=20
 	return (ISC_R_SUCCESS);
 #else
+	REQUIRE(cred !=3D NULL && *cred =3D=3D NULL);
+
 	UNUSED(name);
 	UNUSED(initiate);
 	UNUSED(cred);
@@ -342,13 +345,15 @@
 	char *sname;
 	char *rname;
 	isc_buffer_t buffer;
+	isc_result_t result;
=20
 	/*
 	 * It is far, far easier to write the names we are looking at into
 	 * a string, and do string operations on them.
 	 */
 	isc_buffer_init(&buffer, sbuf, sizeof(sbuf));
-	dns_name_toprincipal(signer, &buffer);
+	result =3D dns_name_toprincipal(signer, &buffer);
+	RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
 	isc_buffer_putuint8(&buffer, 0);
 	if (name !=3D NULL)
 		dns_name_format(name, nbuf, sizeof(nbuf));
@@ -414,13 +419,15 @@
 	char *nname;
 	char *rname;
 	isc_buffer_t buffer;
+	isc_result_t result;
=20
 	/*
 	 * It is far, far easier to write the names we are looking at into
 	 * a string, and do string operations on them.
 	 */
 	isc_buffer_init(&buffer, sbuf, sizeof(sbuf));
-	dns_name_toprincipal(signer, &buffer);
+	result =3D dns_name_toprincipal(signer, &buffer);
+	RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
 	isc_buffer_putuint8(&buffer, 0);
 	if (name !=3D NULL)
 		dns_name_format(name, nbuf, sizeof(nbuf));
@@ -664,8 +671,7 @@
 			gss_log(3, "failed "
 				"gsskrb5_register_acceptor_identity(%s): %s",
 				gssapi_keytab,
-				gss_error_tostring(gret, minor,
-						   buf, sizeof(buf)));
+				gss_error_tostring(gret, 0, buf, sizeof(buf)));
 			return (DNS_R_INVALIDTKEY);
 		}
 #else
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/hmac_link.c
--- a/head/contrib/bind9/lib/dns/hmac_link.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/hmac_link.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
=20
 /*
  * Principal Author: Brian Wellington
- * $Id: hmac_link.c,v 1.19 2011-01-11 23:47:13 tbox Exp $
+ * $Id: hmac_link.c,v 1.19 2011/01/11 23:47:13 tbox Exp $
  */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/Mak=
efile.in
--- a/head/contrib/bind9/lib/dns/include/Makefile.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/Makefile.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.15 2007-06-19 23:47:16 tbox Exp $
+# $Id: Makefile.in,v 1.15 2007/06/19 23:47:16 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/Makefile.in
--- a/head/contrib/bind9/lib/dns/include/dns/Makefile.in	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/Makefile.in	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2007-2009, 2011  Internet Systems Consortium, Inc. (=
"ISC")
+# Copyright (C) 2004, 2007-2009, 2011, 2012  Internet Systems Consortium, =
Inc. ("ISC")
 # Copyright (C) 1998-2003  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.57.296.2 2011-02-28 01:20:02 tbox Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/acache.h
--- a/head/contrib/bind9/lib/dns/include/dns/acache.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/acache.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: acache.h,v 1.8 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: acache.h,v 1.8 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_ACACHE_H
 #define DNS_ACACHE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/acl.h
--- a/head/contrib/bind9/lib/dns/include/dns/acl.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/acl.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: acl.h,v 1.33.426.2 2011-06-17 23:47:11 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_ACL_H
 #define DNS_ACL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/adb.h
--- a/head/contrib/bind9/lib/dns/include/dns/adb.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/adb.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2008, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: adb.h,v 1.85 2008-04-03 06:09:04 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_ADB_H
 #define DNS_ADB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/bit.h
--- a/head/contrib/bind9/lib/dns/include/dns/bit.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/bit.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: bit.h,v 1.14 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: bit.h,v 1.14 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_BIT_H
 #define DNS_BIT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/byaddr.h
--- a/head/contrib/bind9/lib/dns/include/dns/byaddr.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/byaddr.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: byaddr.h,v 1.22 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: byaddr.h,v 1.22 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_BYADDR_H
 #define DNS_BYADDR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/cache.h
--- a/head/contrib/bind9/lib/dns/include/dns/cache.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/cache.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cache.h,v 1.28.428.2 2011-03-03 23:47:09 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_CACHE_H
 #define DNS_CACHE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/callbacks.h
--- a/head/contrib/bind9/lib/dns/include/dns/callbacks.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/callbacks.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: callbacks.h,v 1.24 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_CALLBACKS_H
 #define DNS_CALLBACKS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/cert.h
--- a/head/contrib/bind9/lib/dns/include/dns/cert.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/cert.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cert.h,v 1.19 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: cert.h,v 1.19 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_CERT_H
 #define DNS_CERT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/client.h
--- a/head/contrib/bind9/lib/dns/include/dns/client.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/client.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: client.h,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: client.h,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef DNS_CLIENT_H
 #define DNS_CLIENT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/compress.h
--- a/head/contrib/bind9/lib/dns/include/dns/compress.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/compress.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: compress.h,v 1.42 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: compress.h,v 1.42 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef DNS_COMPRESS_H
 #define DNS_COMPRESS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/db.h
--- a/head/contrib/bind9/lib/dns/include/dns/db.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/include/dns/db.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: db.h,v 1.104.8.1 2011-05-19 04:42:51 each Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_DB_H
 #define DNS_DB_H 1
@@ -177,7 +177,8 @@
 				       dns_zone_t *zone, dns_db_t *db,
 				       dns_dbversion_t *version,
 				       dns_rdataset_t *ardataset,
-				       dns_rpz_st_t *st);
+				       dns_rpz_st_t *st,
+				       dns_name_t *query_qname);
 } dns_dbmethods_t;
=20
 typedef isc_result_t
@@ -1509,7 +1510,8 @@
 isc_result_t
 dns_db_rpz_findips(dns_rpz_zone_t *rpz, dns_rpz_type_t rpz_type,
 		   dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *version,
-		   dns_rdataset_t *ardataset, dns_rpz_st_t *st);
+		   dns_rdataset_t *ardataset, dns_rpz_st_t *st,
+		   dns_name_t *query_qname);
 /*%<
  * Search the CDIR block tree of a response policy tree of trees for the b=
est
  * match to any of the IP addresses in an A or AAAA rdataset.
@@ -1522,6 +1524,10 @@
  * \li	'ardataset' is an A or AAAA rdataset of addresses to check
  * \li	'found' specifies the previous best match if any or
  *	    or NULL, an empty name, 0, DNS_RPZ_POLICY_MISS, and 0
+ *
+ * Returns:
+ * \li	#ISC_R_SUCCESS
+ * \li	#ISC_R_UNEXPECTED
  */
=20
 ISC_LANG_ENDDECLS
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/dbiterator.h
--- a/head/contrib/bind9/lib/dns/include/dns/dbiterator.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/dbiterator.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dbiterator.h,v 1.25 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: dbiterator.h,v 1.25 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_DBITERATOR_H
 #define DNS_DBITERATOR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/dbtable.h
--- a/head/contrib/bind9/lib/dns/include/dns/dbtable.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/dbtable.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dbtable.h,v 1.23 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: dbtable.h,v 1.23 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_DBTABLE_H
 #define DNS_DBTABLE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/diff.h
--- a/head/contrib/bind9/lib/dns/include/dns/diff.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/diff.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: diff.h,v 1.19 2010-06-04 23:51:14 tbox Exp $ */
+/* $Id: diff.h,v 1.19 2010/06/04 23:51:14 tbox Exp $ */
=20
 #ifndef DNS_DIFF_H
 #define DNS_DIFF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/dispatch.h
--- a/head/contrib/bind9/lib/dns/include/dns/dispatch.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/dispatch.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dispatch.h,v 1.62 2009-01-27 23:47:54 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_DISPATCH_H
 #define DNS_DISPATCH_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/dlz.h
--- a/head/contrib/bind9/lib/dns/include/dns/dlz.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/dlz.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2005-2007, 2009-2011  Internet Systems Consortiu=
m, Inc. ("ISC")
+ * Portions Copyright (C) 2005-2007, 2009-2012  Internet Systems Consortiu=
m, Inc. ("ISC")
  * Portions Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -50,7 +50,7 @@
  * USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlz.h,v 1.12.14.2 2011-03-17 23:47:06 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file dns/dlz.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/dlz_dlopen.h
--- a/head/contrib/bind9/lib/dns/include/dns/dlz_dlopen.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/dlz_dlopen.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlz_dlopen.h,v 1.2.2.2 2011-03-17 09:41:07 fdupont Exp $ */
+/* $Id$ */
=20
 /*! \file dns/dlz_open.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/dns64.h
--- a/head/contrib/bind9/lib/dns/include/dns/dns64.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/dns64.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dns64.h,v 1.3 2010-12-08 23:51:56 tbox Exp $ */
+/* $Id: dns64.h,v 1.3 2010/12/08 23:51:56 tbox Exp $ */
=20
 #ifndef DNS_DNS64_H
 #define DNS_DNS64_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/dnssec.h
--- a/head/contrib/bind9/lib/dns/include/dns/dnssec.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/dnssec.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009-2011  Internet Systems Consortium, Inc. (=
"ISC")
+ * Copyright (C) 2004-2007, 2009-2012  Internet Systems Consortium, Inc. (=
"ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnssec.h,v 1.42.178.2 2011-05-06 23:47:05 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_DNSSEC_H
 #define DNS_DNSSEC_H 1
@@ -32,6 +32,9 @@
=20
 ISC_LANG_BEGINDECLS
=20
+/*%< Maximum number of keys supported in a zone. */
+#define DNS_MAXZONEKEYS 32
+
 /*
  * Indicates how the signer found this key: in the key repository, at the
  * zone apex, or specified by the user.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/ds.h
--- a/head/contrib/bind9/lib/dns/include/dns/ds.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/include/dns/ds.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ds.h,v 1.12 2010-12-23 23:47:08 tbox Exp $ */
+/* $Id: ds.h,v 1.12 2010/12/23 23:47:08 tbox Exp $ */
=20
 #ifndef DNS_DS_H
 #define DNS_DS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/ecdb.h
--- a/head/contrib/bind9/lib/dns/include/dns/ecdb.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/ecdb.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ecdb.h,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: ecdb.h,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef DNS_ECDB_H
 #define DNS_ECDB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/events.h
--- a/head/contrib/bind9/lib/dns/include/dns/events.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/events.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009, 2010  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2009, 2010, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: events.h,v 1.56 2010-12-21 03:11:42 marka Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_EVENTS_H
 #define DNS_EVENTS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/fixedname.h
--- a/head/contrib/bind9/lib/dns/include/dns/fixedname.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/fixedname.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: fixedname.h,v 1.19 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: fixedname.h,v 1.19 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_FIXEDNAME_H
 #define DNS_FIXEDNAME_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/forward.h
--- a/head/contrib/bind9/lib/dns/include/dns/forward.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/forward.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: forward.h,v 1.13 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: forward.h,v 1.13 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef DNS_FORWARD_H
 #define DNS_FORWARD_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/iptable.h
--- a/head/contrib/bind9/lib/dns/include/dns/iptable.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/iptable.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: iptable.h,v 1.4 2007-09-14 01:46:05 marka Exp $ */
+/* $Id: iptable.h,v 1.4 2007/09/14 01:46:05 marka Exp $ */
=20
 #ifndef DNS_IPTABLE_H
 #define DNS_IPTABLE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/journal.h
--- a/head/contrib/bind9/lib/dns/include/dns/journal.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/journal.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: journal.h,v 1.37 2009-11-04 23:48:18 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_JOURNAL_H
 #define DNS_JOURNAL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/keydata.h
--- a/head/contrib/bind9/lib/dns/include/dns/keydata.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/keydata.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keydata.h,v 1.2 2009-06-30 02:52:32 each Exp $ */
+/* $Id: keydata.h,v 1.2 2009/06/30 02:52:32 each Exp $ */
=20
 #ifndef DNS_KEYDATA_H
 #define DNS_KEYDATA_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/keyflags.h
--- a/head/contrib/bind9/lib/dns/include/dns/keyflags.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/keyflags.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keyflags.h,v 1.16 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: keyflags.h,v 1.16 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_KEYFLAGS_H
 #define DNS_KEYFLAGS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/keytable.h
--- a/head/contrib/bind9/lib/dns/include/dns/keytable.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/keytable.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keytable.h,v 1.23 2010-06-25 03:24:05 marka Exp $ */
+/* $Id: keytable.h,v 1.23 2010/06/25 03:24:05 marka Exp $ */
=20
 #ifndef DNS_KEYTABLE_H
 #define DNS_KEYTABLE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/keyvalues.h
--- a/head/contrib/bind9/lib/dns/include/dns/keyvalues.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/keyvalues.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keyvalues.h,v 1.29 2010-12-23 23:47:08 tbox Exp $ */
+/* $Id: keyvalues.h,v 1.29 2010/12/23 23:47:08 tbox Exp $ */
=20
 #ifndef DNS_KEYVALUES_H
 #define DNS_KEYVALUES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/lib.h
--- a/head/contrib/bind9/lib/dns/include/dns/lib.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/lib.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lib.h,v 1.18 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: lib.h,v 1.18 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef DNS_LIB_H
 #define DNS_LIB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/log.h
--- a/head/contrib/bind9/lib/dns/include/dns/log.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/log.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.h,v 1.45 2009-12-18 22:16:49 each Exp $ */
+/* $Id$ */
=20
 /*! \file dns/log.h
  * \author  Principal Authors: DCL */
@@ -42,6 +42,7 @@
 #define DNS_LOGCATEGORY_LAME_SERVERS	(&dns_categories[9])
 #define DNS_LOGCATEGORY_DELEGATION_ONLY	(&dns_categories[10])
 #define DNS_LOGCATEGORY_EDNS_DISABLED	(&dns_categories[11])
+#define DNS_LOGCATEGORY_RPZ		(&dns_categories[12])
=20
 /* Backwards compatibility. */
 #define DNS_LOGCATEGORY_GENERAL		ISC_LOGCATEGORY_GENERAL
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/lookup.h
--- a/head/contrib/bind9/lib/dns/include/dns/lookup.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/lookup.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lookup.h,v 1.14 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: lookup.h,v 1.14 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef DNS_LOOKUP_H
 #define DNS_LOOKUP_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/master.h
--- a/head/contrib/bind9/lib/dns/include/dns/master.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/master.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: master.h,v 1.53 2009-07-01 23:47:36 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_MASTER_H
 #define DNS_MASTER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/masterdump.h
--- a/head/contrib/bind9/lib/dns/include/dns/masterdump.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/masterdump.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2008, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: masterdump.h,v 1.42.524.2 2011-05-28 00:27:48 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_MASTERDUMP_H
 #define DNS_MASTERDUMP_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/message.h
--- a/head/contrib/bind9/lib/dns/include/dns/message.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/message.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2010, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: message.h,v 1.132 2010-03-04 23:50:34 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_MESSAGE_H
 #define DNS_MESSAGE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/name.h
--- a/head/contrib/bind9/lib/dns/include/dns/name.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/name.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: name.h,v 1.137 2011-01-13 04:59:26 tbox Exp $ */
+/* $Id: name.h,v 1.137 2011/01/13 04:59:26 tbox Exp $ */
=20
 #ifndef DNS_NAME_H
 #define DNS_NAME_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/ncache.h
--- a/head/contrib/bind9/lib/dns/include/dns/ncache.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/ncache.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ncache.h,v 1.29 2010-05-14 23:50:40 tbox Exp $ */
+/* $Id: ncache.h,v 1.29 2010/05/14 23:50:40 tbox Exp $ */
=20
 #ifndef DNS_NCACHE_H
 #define DNS_NCACHE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/nsec.h
--- a/head/contrib/bind9/lib/dns/include/dns/nsec.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/nsec.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2008, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec.h,v 1.12 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_NSEC_H
 #define DNS_NSEC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/nsec3.h
--- a/head/contrib/bind9/lib/dns/include/dns/nsec3.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/nsec3.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2008-2010, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec3.h,v 1.12 2010-05-18 02:38:10 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_NSEC3_H
 #define DNS_NSEC3_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/opcode.h
--- a/head/contrib/bind9/lib/dns/include/dns/opcode.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/opcode.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: opcode.h,v 1.8 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: opcode.h,v 1.8 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_OPCODE_H
 #define DNS_OPCODE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/order.h
--- a/head/contrib/bind9/lib/dns/include/dns/order.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/order.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: order.h,v 1.9 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: order.h,v 1.9 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_ORDER_H
 #define DNS_ORDER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/peer.h
--- a/head/contrib/bind9/lib/dns/include/dns/peer.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/peer.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: peer.h,v 1.35 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: peer.h,v 1.35 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef DNS_PEER_H
 #define DNS_PEER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/portlist.h
--- a/head/contrib/bind9/lib/dns/include/dns/portlist.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/portlist.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: portlist.h,v 1.9 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: portlist.h,v 1.9 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file dns/portlist.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/private.h
--- a/head/contrib/bind9/lib/dns/include/dns/private.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/private.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: private.h,v 1.3 2009-10-09 23:48:09 tbox Exp $ */
+/* $Id$ */
=20
 #include <isc/lang.h>
 #include <isc/types.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rbt.h
--- a/head/contrib/bind9/lib/dns/include/dns/rbt.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rbt.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rbt.h,v 1.77 2009-11-04 01:18:19 marka Exp $ */
+/* $Id: rbt.h,v 1.77 2009/11/04 01:18:19 marka Exp $ */
=20
 #ifndef DNS_RBT_H
 #define DNS_RBT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rcode.h
--- a/head/contrib/bind9/lib/dns/include/dns/rcode.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rcode.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rcode.h,v 1.21 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: rcode.h,v 1.21 2008/09/25 04:02:39 tbox Exp $ */
=20
 #ifndef DNS_RCODE_H
 #define DNS_RCODE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rdata.h
--- a/head/contrib/bind9/lib/dns/include/dns/rdata.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rdata.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdata.h,v 1.77 2009-12-04 21:09:33 marka Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_RDATA_H
 #define DNS_RDATA_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rdataclass.h
--- a/head/contrib/bind9/lib/dns/include/dns/rdataclass.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rdataclass.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdataclass.h,v 1.24 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rdataclass.h,v 1.24 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_RDATACLASS_H
 #define DNS_RDATACLASS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rdatalist.h
--- a/head/contrib/bind9/lib/dns/include/dns/rdatalist.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rdatalist.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatalist.h,v 1.22 2008-04-03 06:09:05 tbox Exp $ */
+/* $Id: rdatalist.h,v 1.22 2008/04/03 06:09:05 tbox Exp $ */
=20
 #ifndef DNS_RDATALIST_H
 #define DNS_RDATALIST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rdataset.h
--- a/head/contrib/bind9/lib/dns/include/dns/rdataset.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rdataset.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdataset.h,v 1.69.148.3 2011-06-08 23:02:43 each Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_RDATASET_H
 #define DNS_RDATASET_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rdatasetiter.h
--- a/head/contrib/bind9/lib/dns/include/dns/rdatasetiter.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rdatasetiter.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatasetiter.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rdatasetiter.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_RDATASETITER_H
 #define DNS_RDATASETITER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rdataslab.h
--- a/head/contrib/bind9/lib/dns/include/dns/rdataslab.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rdataslab.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdataslab.h,v 1.33 2008-04-01 23:47:10 tbox Exp $ */
+/* $Id: rdataslab.h,v 1.33 2008/04/01 23:47:10 tbox Exp $ */
=20
 #ifndef DNS_RDATASLAB_H
 #define DNS_RDATASLAB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rdatatype.h
--- a/head/contrib/bind9/lib/dns/include/dns/rdatatype.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rdatatype.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatatype.h,v 1.26 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: rdatatype.h,v 1.26 2008/09/25 04:02:39 tbox Exp $ */
=20
 #ifndef DNS_RDATATYPE_H
 #define DNS_RDATATYPE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/request.h
--- a/head/contrib/bind9/lib/dns/include/dns/request.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/request.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: request.h,v 1.31 2010-03-04 23:50:34 tbox Exp $ */
+/* $Id: request.h,v 1.31 2010/03/04 23:50:34 tbox Exp $ */
=20
 #ifndef DNS_REQUEST_H
 #define DNS_REQUEST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/resolver.h
--- a/head/contrib/bind9/lib/dns/include/dns/resolver.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/resolver.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: resolver.h,v 1.67.86.2 2011-02-28 01:20:02 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_RESOLVER_H
 #define DNS_RESOLVER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/result.h
--- a/head/contrib/bind9/lib/dns/include/dns/result.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/result.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.h,v 1.122 2011-01-11 23:47:13 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_RESULT_H
 #define DNS_RESULT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rootns.h
--- a/head/contrib/bind9/lib/dns/include/dns/rootns.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rootns.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rootns.h,v 1.16 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rootns.h,v 1.16 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_ROOTNS_H
 #define DNS_ROOTNS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rpz.h
--- a/head/contrib/bind9/lib/dns/include/dns/rpz.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rpz.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rpz.h,v 1.3 2011-01-13 04:59:26 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_RPZ_H
 #define DNS_RPZ_H 1
@@ -37,21 +37,24 @@
 	DNS_RPZ_TYPE_BAD,
 	DNS_RPZ_TYPE_QNAME,
 	DNS_RPZ_TYPE_IP,
-	DNS_RPZ_TYPE_NSIP,
-	DNS_RPZ_TYPE_NSDNAME
+	DNS_RPZ_TYPE_NSDNAME,
+	DNS_RPZ_TYPE_NSIP
 } dns_rpz_type_t;
=20
 /*
- * Require DNS_RPZ_POLICY_NO_OP < DNS_RPZ_POLICY_NXDOMAIN <
- *	   DNS_RPZ_POLICY_NODATA < DNS_RPZ_POLICY_CNAME.
+ * Require DNS_RPZ_POLICY_PASSTHRU < DNS_RPZ_POLICY_NXDOMAIN <
+ * DNS_RPZ_POLICY_NODATA < DNS_RPZ_POLICY_CNAME to choose among competing
+ * policies.
  */
 typedef enum {
-	DNS_RPZ_POLICY_GIVEN =3D 0,	/* 'given': what something else says */
-	DNS_RPZ_POLICY_NO_OP =3D 1,	/* 'no-op': do not rewrite */
-	DNS_RPZ_POLICY_NXDOMAIN =3D 2,	/* 'nxdomain': answer with NXDOMAIN */
-	DNS_RPZ_POLICY_NODATA =3D 3,	/* 'nodata': answer with ANCOUNT=3D0 */
-	DNS_RPZ_POLICY_CNAME =3D 4,	/* 'cname x': answer with x's rrsets */
-	DNS_RPZ_POLICY_RECORD =3D 5,
+	DNS_RPZ_POLICY_GIVEN =3D 0,	/* 'given': what policy record says */
+	DNS_RPZ_POLICY_DISABLED =3D 1,	/* 'cname x': answer with x's rrsets */
+	DNS_RPZ_POLICY_PASSTHRU =3D 2,	/* 'passthru': do not rewrite */
+	DNS_RPZ_POLICY_NXDOMAIN =3D 3,	/* 'nxdomain': answer with NXDOMAIN */
+	DNS_RPZ_POLICY_NODATA =3D 4,	/* 'nodata': answer with ANCOUNT=3D0 */
+	DNS_RPZ_POLICY_CNAME =3D 5,	/* 'cname x': answer with x's rrsets */
+	DNS_RPZ_POLICY_RECORD,
+	DNS_RPZ_POLICY_WILDCNAME,
 	DNS_RPZ_POLICY_MISS,
 	DNS_RPZ_POLICY_ERROR
 } dns_rpz_policy_t;
@@ -65,10 +68,9 @@
 	ISC_LINK(dns_rpz_zone_t) link;
 	int			 num;
 	dns_name_t		 origin;  /* Policy zone name */
-	dns_name_t		 nsdname; /* RPZ_NSDNAME_ZONE.origin */
-	dns_rpz_policy_t	 policy;  /* RPZ_POLICY_GIVEN or override */
-	dns_name_t		 cname;	  /* override name for
-					     RPZ_POLICY_CNAME */
+	dns_name_t		 nsdname; /* DNS_RPZ_NSDNAME_ZONE.origin */
+	dns_rpz_policy_t	 policy;  /* DNS_RPZ_POLICY_GIVEN or override */
+	dns_name_t		 cname;	  /* override value for ..._CNAME */
 };
=20
 /*
@@ -82,13 +84,15 @@
 typedef struct {
 	unsigned int		state;
 # define DNS_RPZ_REWRITTEN	0x0001
-# define DNS_RPZ_DONE_QNAME	0x0002
-# define DNS_RPZ_DONE_A	 	0x0004
-# define DNS_RPZ_RECURSING	0x0008
-# define DNS_RPZ_HAVE_IP 	0x0010
-# define DNS_RPZ_HAVE_NSIPv4	0x0020
-# define DNS_RPZ_HAVE_NSIPv6	0x0040
-# define DNS_RPZ_HAD_NSDNAME	0x0080
+# define DNS_RPZ_DONE_QNAME	0x0002	/* qname checked */
+# define DNS_RPZ_DONE_QNAME_IP	0x0004	/* IP addresses of qname checked */
+# define DNS_RPZ_DONE_NSDNAME	0x0008	/* NS name missed; checking addresses=
 */
+# define DNS_RPZ_DONE_IPv4 	0x0010
+# define DNS_RPZ_RECURSING	0x0020
+# define DNS_RPZ_HAVE_IP 	0x0040	/* a policy zone has IP addresses */
+# define DNS_RPZ_HAVE_NSIPv4	0x0080	/*		  IPv4 NISP addresses */
+# define DNS_RPZ_HAVE_NSIPv6	0x0100	/*		  IPv6 NISP addresses */
+# define DNS_RPZ_HAVE_NSDNAME	0x0200	/*		  NS names */
 	/*
 	 * Best match so far.
 	 */
@@ -101,11 +105,12 @@
 		isc_result_t		result;
 		dns_zone_t		*zone;
 		dns_db_t		*db;
+		dns_dbversion_t		*version;
 		dns_dbnode_t		*node;
 		dns_rdataset_t		*rdataset;
 	} m;
 	/*
-	 * State for chasing NS names and addresses including recursion.
+	 * State for chasing IP addresses and NS names including recursion.
 	 */
 	struct {
 		unsigned int		label;
@@ -114,7 +119,7 @@
 		dns_rdatatype_t		r_type;
 		isc_result_t		r_result;
 		dns_rdataset_t		*r_rdataset;
-	} ns;
+	} r;
 	/*
 	 * State of real query while recursing for NSIP or NSDNAME.
 	 */
@@ -146,6 +151,7 @@
 #define DNS_RPZ_INFO_LEVEL	ISC_LOG_INFO
 #define DNS_RPZ_DEBUG_LEVEL1	ISC_LOG_DEBUG(1)
 #define DNS_RPZ_DEBUG_LEVEL2	ISC_LOG_DEBUG(2)
+#define DNS_RPZ_DEBUG_LEVEL3	ISC_LOG_DEBUG(3)
=20
 const char *
 dns_rpz_type2str(dns_rpz_type_t type);
@@ -153,6 +159,9 @@
 dns_rpz_policy_t
 dns_rpz_str2policy(const char *str);
=20
+const char *
+dns_rpz_policy2str(dns_rpz_policy_t policy);
+
 void
 dns_rpz_set_need(isc_boolean_t need);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/rriterator.h
--- a/head/contrib/bind9/lib/dns/include/dns/rriterator.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/rriterator.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC=
")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rriterator.h,v 1.2 2009-06-30 02:52:32 each Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_RRITERATOR_H
 #define DNS_RRITERATOR_H 1
@@ -77,26 +77,110 @@
 isc_result_t
 dns_rriterator_init(dns_rriterator_t *it, dns_db_t *db,
 		       dns_dbversion_t *ver, isc_stdtime_t now);
+/*%
+ * Initialize an rriterator; sets the cursor to the origin node
+ * of the database.
+ *
+ * Requires:
+ *
+ * \li	'db' is a valid database.
+ *
+ * Returns:
+ *
+ * \li	#ISC_R_SUCCESS
+ * \li	#ISC_R_NOMEMORY
+ */
=20
 isc_result_t
 dns_rriterator_first(dns_rriterator_t *it);
+/*%<
+ * Move the rriterator cursor to the first rdata in the database.
+ *
+ * Requires:
+ *\li	'it' is a valid, initialized rriterator
+ *
+ * Returns:
+ *\li	#ISC_R_SUCCESS
+ *\li	#ISC_R_NOMORE			There are no rdata in the set.
+ */
=20
 isc_result_t
 dns_rriterator_nextrrset(dns_rriterator_t *it);
+/*%<
+ * Move the rriterator cursor to the next rrset in the database,
+ * skipping over any remaining records that have the same rdatatype
+ * as the current one.
+ *
+ * Requires:
+ *\li	'it' is a valid, initialized rriterator
+ *
+ * Returns:
+ *\li	#ISC_R_SUCCESS
+ *\li	#ISC_R_NOMORE			No more rrsets in the database
+ */
=20
 isc_result_t
 dns_rriterator_next(dns_rriterator_t *it);
+/*%<
+ * Move the rriterator cursor to the next rrset in the database,
+ * skipping over any remaining records that have the same rdatatype
+ * as the current one.
+ *
+ * Requires:
+ *\li	'it' is a valid, initialized rriterator
+ *
+ * Returns:
+ *\li	#ISC_R_SUCCESS
+ *\li	#ISC_R_NOMORE			No more records in the database
+ */
=20
 void
 dns_rriterator_current(dns_rriterator_t *it, dns_name_t **name,
 			  isc_uint32_t *ttl, dns_rdataset_t **rdataset,
 			  dns_rdata_t **rdata);
+/*%<
+ * Make '*name' refer to the current name.  If 'rdataset' is not NULL,
+ * make '*rdataset' refer to the current * rdataset.  If '*rdata' is not
+ * NULL, make '*rdata' refer to the current record.
+ *
+ * Requires:
+ *\li	'*name' is a valid name object
+ *\li	'rdataset' is NULL or '*rdataset' is NULL
+ *\li	'rdata' is NULL or '*rdata' is NULL
+ *
+ * Ensures:
+ *\li	'rdata' refers to the rdata at the rdata cursor location of
+ *\li	'rdataset'.
+ */
=20
 void
 dns_rriterator_pause(dns_rriterator_t *it);
+/*%<
+ * Pause rriterator.  Frees any locks held by the database iterator.
+ * Callers should use this routine any time they are not going to
+ * execute another rriterator method in the immediate future.
+ *
+ * Requires:
+ *\li	'it' is a valid iterator.
+ *
+ * Ensures:
+ *\li	Any database locks being held for efficiency of iterator access are
+ *	released.
+ */
=20
 void
 dns_rriterator_destroy(dns_rriterator_t *it);
+/*%<
+ * Shut down and free resources in rriterator 'it'.
+ *
+ * Requires:
+ *
+ *\li	'it' is a valid iterator.
+ *
+ * Ensures:
+ *
+ *\li	All resources used by the rriterator are freed.
+ */
=20
 ISC_LANG_ENDDECLS
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/sdb.h
--- a/head/contrib/bind9/lib/dns/include/dns/sdb.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/sdb.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2009, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sdb.h,v 1.23 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_SDB_H
 #define DNS_SDB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/sdlz.h
--- a/head/contrib/bind9/lib/dns/include/dns/sdlz.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/sdlz.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2005-2007, 2009-2011  Internet Systems Consortiu=
m, Inc. ("ISC")
+ * Portions Copyright (C) 2005-2007, 2009-2012  Internet Systems Consortiu=
m, Inc. ("ISC")
  * Portions Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -50,7 +50,7 @@
  * USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sdlz.h,v 1.14.8.2 2011-03-17 23:47:06 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file dns/sdlz.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/secalg.h
--- a/head/contrib/bind9/lib/dns/include/dns/secalg.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/secalg.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: secalg.h,v 1.21 2009-10-12 23:48:02 tbox Exp $ */
+/* $Id: secalg.h,v 1.21 2009/10/12 23:48:02 tbox Exp $ */
=20
 #ifndef DNS_SECALG_H
 #define DNS_SECALG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/secproto.h
--- a/head/contrib/bind9/lib/dns/include/dns/secproto.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/secproto.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: secproto.h,v 1.16 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: secproto.h,v 1.16 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_SECPROTO_H
 #define DNS_SECPROTO_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/soa.h
--- a/head/contrib/bind9/lib/dns/include/dns/soa.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/soa.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: soa.h,v 1.12 2009-09-10 01:47:09 each Exp $ */
+/* $Id: soa.h,v 1.12 2009/09/10 01:47:09 each Exp $ */
=20
 #ifndef DNS_SOA_H
 #define DNS_SOA_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/ssu.h
--- a/head/contrib/bind9/lib/dns/include/dns/ssu.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/ssu.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ssu.h,v 1.28 2011-01-06 23:47:00 tbox Exp $ */
+/* $Id: ssu.h,v 1.28 2011/01/06 23:47:00 tbox Exp $ */
=20
 #ifndef DNS_SSU_H
 #define DNS_SSU_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/stats.h
--- a/head/contrib/bind9/lib/dns/include/dns/stats.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/stats.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stats.h,v 1.20 2009-01-27 23:47:54 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_STATS_H
 #define DNS_STATS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/tcpmsg.h
--- a/head/contrib/bind9/lib/dns/include/dns/tcpmsg.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/tcpmsg.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tcpmsg.h,v 1.22 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: tcpmsg.h,v 1.22 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_TCPMSG_H
 #define DNS_TCPMSG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/time.h
--- a/head/contrib/bind9/lib/dns/include/dns/time.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/time.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: time.h,v 1.17 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_TIME_H
 #define DNS_TIME_H 1
@@ -67,6 +67,12 @@
  * current date is chosen.
  */
=20
+isc_int64_t
+dns_time64_from32(isc_uint32_t value);
+/*%<
+ * Covert a 32-bit cyclic time value into a 64 bit time stamp.
+ */
+
 ISC_LANG_ENDDECLS
=20
 #endif /* DNS_TIME_H */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/timer.h
--- a/head/contrib/bind9/lib/dns/include/dns/timer.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/timer.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: timer.h,v 1.9 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: timer.h,v 1.9 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_TIMER_H
 #define DNS_TIMER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/tkey.h
--- a/head/contrib/bind9/lib/dns/include/dns/tkey.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/tkey.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tkey.h,v 1.32 2011-01-08 23:47:01 tbox Exp $ */
+/* $Id: tkey.h,v 1.32 2011/01/08 23:47:01 tbox Exp $ */
=20
 #ifndef DNS_TKEY_H
 #define DNS_TKEY_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/tsec.h
--- a/head/contrib/bind9/lib/dns/include/dns/tsec.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/tsec.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsec.h,v 1.6 2010-12-09 00:54:34 marka Exp $ */
+/* $Id: tsec.h,v 1.6 2010/12/09 00:54:34 marka Exp $ */
=20
 #ifndef DNS_TSEC_H
 #define DNS_TSEC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/tsig.h
--- a/head/contrib/bind9/lib/dns/include/dns/tsig.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/tsig.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsig.h,v 1.59 2011-01-11 23:47:13 tbox Exp $ */
+/* $Id: tsig.h,v 1.59 2011/01/11 23:47:13 tbox Exp $ */
=20
 #ifndef DNS_TSIG_H
 #define DNS_TSIG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/ttl.h
--- a/head/contrib/bind9/lib/dns/include/dns/ttl.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/ttl.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ttl.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ttl.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_TTL_H
 #define DNS_TTL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/types.h
--- a/head/contrib/bind9/lib/dns/include/dns/types.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/types.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2010, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: types.h,v 1.143 2010-12-08 02:46:16 marka Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_TYPES_H
 #define DNS_TYPES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/validator.h
--- a/head/contrib/bind9/lib/dns/include/dns/validator.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/validator.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: validator.h,v 1.46 2010-02-25 05:08:01 tbox Exp $ */
+/* $Id: validator.h,v 1.46 2010/02/25 05:08:01 tbox Exp $ */
=20
 #ifndef DNS_VALIDATOR_H
 #define DNS_VALIDATOR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/version.h
--- a/head/contrib/bind9/lib/dns/include/dns/version.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/version.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.h,v 1.9 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: version.h,v 1.9 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file dns/version.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/view.h
--- a/head/contrib/bind9/lib/dns/include/dns/view.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/view.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: view.h,v 1.132 2011-01-13 01:59:28 marka Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_VIEW_H
 #define DNS_VIEW_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/xfrin.h
--- a/head/contrib/bind9/lib/dns/include/dns/xfrin.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/xfrin.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: xfrin.h,v 1.30 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: xfrin.h,v 1.30 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef DNS_XFRIN_H
 #define DNS_XFRIN_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/zone.h
--- a/head/contrib/bind9/lib/dns/include/dns/zone.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/zone.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zone.h,v 1.182.16.2 2011-07-08 23:47:16 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_ZONE_H
 #define DNS_ZONE_H 1
@@ -1570,6 +1570,32 @@
  *\li	'local' to be a valid sockaddr.
  */
=20
+isc_boolean_t
+dns_zonemgr_unreachable(dns_zonemgr_t *zmgr, isc_sockaddr_t *remote,
+			isc_sockaddr_t *local, isc_time_t *now);
+/*%<
+ *	Returns ISC_TRUE if the given local/remote address pair
+ *	is found in the zone maanger's unreachable cache.
+ *
+ * Requires:
+ *\li	'zmgr' to be a valid zone manager.
+ *\li	'remote' to be a valid sockaddr.
+ *\li	'local' to be a valid sockaddr.
+ *\li	'now' !=3D NULL
+ */
+
+void
+dns_zonemgr_unreachabledel(dns_zonemgr_t *zmgr, isc_sockaddr_t *remote,
+			   isc_sockaddr_t *local);
+/*%<
+ *	Remove the pair of addresses from the unreachable cache.
+ *
+ * Requires:
+ *\li	'zmgr' to be a valid zone manager.
+ *\li	'remote' to be a valid sockaddr.
+ *\li	'local' to be a valid sockaddr.
+ */
+
 void
 dns_zone_forcereload(dns_zone_t *zone);
 /*%<
@@ -1865,6 +1891,13 @@
  * Load the origin names for a writeable DLZ database.
  */
=20
+isc_result_t
+dns_zone_synckeyzone(dns_zone_t *zone);
+/*%
+ * Force the managed key zone to synchronize, and start the key
+ * maintenance timer.
+ */
+
 ISC_LANG_ENDDECLS
=20
 #endif /* DNS_ZONE_H */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/zonekey.h
--- a/head/contrib/bind9/lib/dns/include/dns/zonekey.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dns/zonekey.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zonekey.h,v 1.10 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: zonekey.h,v 1.10 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_ZONEKEY_H
 #define DNS_ZONEKEY_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dns=
/zt.h
--- a/head/contrib/bind9/lib/dns/include/dns/zt.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/include/dns/zt.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zt.h,v 1.38 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_ZT_H
 #define DNS_ZT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dst=
/Makefile.in
--- a/head/contrib/bind9/lib/dns/include/dst/Makefile.in	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dst/Makefile.in	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4 2007-12-11 20:28:55 marka Exp $
+# $Id: Makefile.in,v 1.4 2007/12/11 20:28:55 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dst=
/dst.h
--- a/head/contrib/bind9/lib/dns/include/dst/dst.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dst/dst.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dst.h,v 1.31.10.1 2011-03-21 19:53:35 each Exp $ */
+/* $Id$ */
=20
 #ifndef DST_DST_H
 #define DST_DST_H 1
@@ -641,6 +641,9 @@
 dns_keytag_t
 dst_key_id(const dst_key_t *key);
=20
+dns_keytag_t
+dst_key_rid(const dst_key_t *key);
+
 dns_rdataclass_t
 dst_key_class(const dst_key_t *key);
=20
@@ -706,9 +709,11 @@
=20
 isc_uint16_t
 dst_region_computeid(const isc_region_t *source, unsigned int alg);
+isc_uint16_t
+dst_region_computerid(const isc_region_t *source, unsigned int alg);
 /*%<
- * Computes the key id of the key stored in the provided region with the
- * given algorithm.
+ * Computes the (revoked) key id of the key stored in the provided
+ * region with the given algorithm.
  *
  * Requires:
  *\li	"source" contains a valid, non-NULL region.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dst=
/gssapi.h
--- a/head/contrib/bind9/lib/dns/include/dst/gssapi.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dst/gssapi.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gssapi.h,v 1.16 2011-01-08 23:47:01 tbox Exp $ */
+/* $Id: gssapi.h,v 1.16 2011/01/08 23:47:01 tbox Exp $ */
=20
 #ifndef DST_GSSAPI_H
 #define DST_GSSAPI_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dst=
/lib.h
--- a/head/contrib/bind9/lib/dns/include/dst/lib.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/include/dst/lib.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lib.h,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: lib.h,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DST_LIB_H
 #define DST_LIB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/include/dst=
/result.h
--- a/head/contrib/bind9/lib/dns/include/dst/result.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/include/dst/result.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.h,v 1.9 2008-04-01 23:47:10 tbox Exp $ */
+/* $Id: result.h,v 1.9 2008/04/01 23:47:10 tbox Exp $ */
=20
 #ifndef DST_RESULT_H
 #define DST_RESULT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/iptable.c
--- a/head/contrib/bind9/lib/dns/iptable.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/iptable.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: iptable.c,v 1.15 2009-02-18 23:47:48 tbox Exp $ */
+/* $Id: iptable.c,v 1.15 2009/02/18 23:47:48 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/journal.c
--- a/head/contrib/bind9/lib/dns/journal.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/journal.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004, 2005, 2007-2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: journal.c,v 1.112.38.2 2011-03-12 04:59:17 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/key.c
--- a/head/contrib/bind9/lib/dns/key.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/key.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: key.c,v 1.8 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
@@ -56,6 +56,33 @@
 	return ((isc_uint16_t)(ac & 0xffff));
 }
=20
+isc_uint16_t
+dst_region_computerid(const isc_region_t *source, unsigned int alg) {
+	isc_uint32_t ac;
+	const unsigned char *p;
+	int size;
+
+	REQUIRE(source !=3D NULL);
+	REQUIRE(source->length >=3D 4);
+
+	p =3D source->base;
+	size =3D source->length;
+
+	if (alg =3D=3D DST_ALG_RSAMD5)
+		return ((p[size - 3] << 8) + p[size - 2]);
+
+	ac =3D ((*p) << 8) + *(p + 1);
+	ac |=3D DNS_KEYFLAG_REVOKE;
+	for (size -=3D 2, p +=3D2; size > 1; size -=3D 2, p +=3D 2)
+		ac +=3D ((*p) << 8) + *(p + 1);
+
+	if (size > 0)
+		ac +=3D ((*p) << 8);
+	ac +=3D (ac >> 16) & 0xffff;
+
+	return ((isc_uint16_t)(ac & 0xffff));
+}
+
 dns_name_t *
 dst_key_name(const dst_key_t *key) {
 	REQUIRE(VALID_KEY(key));
@@ -92,6 +119,12 @@
 	return (key->key_id);
 }
=20
+dns_keytag_t
+dst_key_rid(const dst_key_t *key) {
+	REQUIRE(VALID_KEY(key));
+	return (key->key_rid);
+}
+
 dns_rdataclass_t
 dst_key_class(const dst_key_t *key) {
 	REQUIRE(VALID_KEY(key));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/keydata.c
--- a/head/contrib/bind9/lib/dns/keydata.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/keydata.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keydata.c,v 1.3 2009-07-01 23:47:36 tbox Exp $ */
+/* $Id: keydata.c,v 1.3 2009/07/01 23:47:36 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/keytable.c
--- a/head/contrib/bind9/lib/dns/keytable.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/keytable.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keytable.c,v 1.41 2010-06-25 23:46:51 tbox Exp $ */
+/* $Id: keytable.c,v 1.41 2010/06/25 23:46:51 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/lib.c
--- a/head/contrib/bind9/lib/dns/lib.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/lib.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lib.c,v 1.19 2009-09-03 00:12:23 each Exp $ */
+/* $Id: lib.c,v 1.19 2009/09/03 00:12:23 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/log.c
--- a/head/contrib/bind9/lib/dns/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.c,v 1.47 2009-12-18 23:49:03 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -44,6 +44,7 @@
 	{ "lame-servers", 0 },
 	{ "delegation-only", 0 },
 	{ "edns-disabled", 0 },
+	{ "rpz",	0 },
 	{ NULL, 	0 }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/lookup.c
--- a/head/contrib/bind9/lib/dns/lookup.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/lookup.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lookup.c,v 1.21 2007-06-18 23:47:40 tbox Exp $ */
+/* $Id: lookup.c,v 1.21 2007/06/18 23:47:40 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/master.c
--- a/head/contrib/bind9/lib/dns/master.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/master.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: master.c,v 1.178.346.2 2011-03-12 04:59:17 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -2257,14 +2257,14 @@
 		if (rdcount > rdata_size) {
 			dns_rdata_t *new_rdata =3D NULL;
=20
-			new_rdata =3D grow_rdata(rdata_size + RDSZ, rdata,
+			new_rdata =3D grow_rdata(rdcount + RDSZ, rdata,
 					       rdata_size, &head,
 					       &dummy, mctx);
 			if (new_rdata =3D=3D NULL) {
 				result =3D ISC_R_NOMEMORY;
 				goto cleanup;
 			}
-			rdata_size +=3D RDSZ;
+			rdata_size =3D rdcount + RDSZ;
 			rdata =3D new_rdata;
 		}
=20
@@ -2687,6 +2687,7 @@
 	}
 	while ((this =3D ISC_LIST_HEAD(save)) !=3D NULL) {
 		ISC_LIST_UNLINK(save, this, link);
+		INSIST(rdlcount < new_len);
 		new[rdlcount] =3D *this;
 		ISC_LIST_APPEND(*current, &new[rdlcount], link);
 		rdlcount++;
@@ -2699,6 +2700,7 @@
 	}
 	while ((this =3D ISC_LIST_HEAD(save)) !=3D NULL) {
 		ISC_LIST_UNLINK(save, this, link);
+		INSIST(rdlcount < new_len);
 		new[rdlcount] =3D *this;
 		ISC_LIST_APPEND(*glue, &new[rdlcount], link);
 		rdlcount++;
@@ -2742,6 +2744,7 @@
 		}
 		while ((rdata =3D ISC_LIST_HEAD(save)) !=3D NULL) {
 			ISC_LIST_UNLINK(save, rdata, link);
+			INSIST(rdcount < new_len);
 			new[rdcount] =3D *rdata;
 			ISC_LIST_APPEND(this->rdata, &new[rdcount], link);
 			rdcount++;
@@ -2761,13 +2764,14 @@
 		}
 		while ((rdata =3D ISC_LIST_HEAD(save)) !=3D NULL) {
 			ISC_LIST_UNLINK(save, rdata, link);
+			INSIST(rdcount < new_len);
 			new[rdcount] =3D *rdata;
 			ISC_LIST_APPEND(this->rdata, &new[rdcount], link);
 			rdcount++;
 		}
 		this =3D ISC_LIST_NEXT(this, link);
 	}
-	INSIST(rdcount =3D=3D old_len);
+	INSIST(rdcount =3D=3D old_len || rdcount =3D=3D 0);
 	if (old !=3D NULL)
 		isc_mem_put(mctx, old, old_len * sizeof(*old));
 	return (new);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/masterdump.c
--- a/head/contrib/bind9/lib/dns/masterdump.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/masterdump.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: masterdump.c,v 1.99.258.7 2011-06-08 23:02:42 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -416,12 +416,11 @@
=20
 	rdataset->attributes |=3D DNS_RDATASETATTR_LOADORDER;
 	result =3D dns_rdataset_first(rdataset);
-	REQUIRE(result =3D=3D ISC_R_SUCCESS);
=20
 	current_ttl =3D ctx->current_ttl;
 	current_ttl_valid =3D ctx->current_ttl_valid;
=20
-	do {
+	while (result =3D=3D ISC_R_SUCCESS) {
 		column =3D 0;
=20
 		/*
@@ -546,7 +545,7 @@
=20
 		first =3D ISC_FALSE;
 		result =3D dns_rdataset_next(rdataset);
-	} while (result =3D=3D ISC_R_SUCCESS);
+	}
=20
 	if (result !=3D ISC_R_NOMORE)
 		return (result);
@@ -928,6 +927,7 @@
 	REQUIRE(buffer->length > 0);
 	REQUIRE(DNS_RDATASET_VALID(rdataset));
=20
+	rdataset->attributes |=3D DNS_RDATASETATTR_LOADORDER;
  restart:
 	totallen =3D 0;
 	result =3D dns_rdataset_first(rdataset);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/message.c
--- a/head/contrib/bind9/lib/dns/message.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/message.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: message.c,v 1.254.114.3 2011-06-08 23:02:42 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/name.c
--- a/head/contrib/bind9/lib/dns/name.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/name.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: name.c,v 1.174.8.1 2011-03-11 06:47:04 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/ncache.c
--- a/head/contrib/bind9/lib/dns/ncache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/ncache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2008, 2010, 2011  Internet Systems Cons=
ortium, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2008, 2010-2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ncache.c,v 1.50.124.4 2011-06-08 23:02:42 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/nsec.c
--- a/head/contrib/bind9/lib/dns/nsec.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/nsec.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec.c,v 1.13.428.2 2011-03-12 04:59:17 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/nsec3.c
--- a/head/contrib/bind9/lib/dns/nsec3.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/nsec3.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006, 2008-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2006, 2008-2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec3.c,v 1.19.24.3 2011-06-08 23:02:42 each Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
@@ -1784,7 +1784,7 @@
 	dst_key_t *key =3D NULL;
 	isc_buffer_t buffer;
 	isc_result_t result;
-	isc_uint16_t bits, minbits =3D 4096;
+	unsigned int bits, minbits =3D 4096;
=20
 	result =3D dns_db_getoriginnode(db, &node);
 	if (result !=3D ISC_R_SUCCESS)
@@ -1811,7 +1811,7 @@
 		isc_buffer_add(&buffer, rdata.length);
 		CHECK(dst_key_fromdns(dns_db_origin(db), rdataset.rdclass,
 				      &buffer, mctx, &key));
-		bits =3D dst_key_getbits(key);
+		bits =3D dst_key_size(key);
 		dst_key_free(&key);
 		if (minbits > bits)
 			minbits =3D bits;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/openssl_lin=
k.c
--- a/head/contrib/bind9/lib/dns/openssl_link.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/dns/openssl_link.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("I=
SC")
+ * Portions Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("I=
SC")
  * Portions Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -31,7 +31,7 @@
=20
 /*
  * Principal Author: Brian Wellington
- * $Id: openssl_link.c,v 1.29.54.2 2011-03-12 04:59:17 tbox Exp $
+ * $Id$
  */
 #ifdef OPENSSL
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/openssldh_l=
ink.c
--- a/head/contrib/bind9/lib/dns/openssldh_link.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/openssldh_link.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -31,7 +31,7 @@
=20
 /*
  * Principal Author: Brian Wellington
- * $Id: openssldh_link.c,v 1.20 2011-01-11 23:47:13 tbox Exp $
+ * $Id: openssldh_link.c,v 1.20 2011/01/11 23:47:13 tbox Exp $
  */
=20
 #ifdef OPENSSL
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/openssldsa_=
link.c
--- a/head/contrib/bind9/lib/dns/openssldsa_link.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/openssldsa_link.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004-2009, 2011  Internet Systems Consortium, In=
c. ("ISC")
+ * Portions Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consorti=
um, Inc. ("ISC")
  * Portions Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -29,7 +29,7 @@
  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: openssldsa_link.c,v 1.20.10.1 2011-03-11 06:47:04 marka Exp $ */
+/* $Id$ */
=20
 #ifdef OPENSSL
 #ifndef USE_EVP
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/opensslgost=
_link.c
--- a/head/contrib/bind9/lib/dns/opensslgost_link.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/opensslgost_link.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: opensslgost_link.c,v 1.5 2011-01-19 23:47:12 tbox Exp $ */
+/* $Id: opensslgost_link.c,v 1.5 2011/01/19 23:47:12 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/opensslrsa_=
link.c
--- a/head/contrib/bind9/lib/dns/opensslrsa_link.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/dns/opensslrsa_link.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 2000-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -17,7 +17,7 @@
=20
 /*
  * Principal Author: Brian Wellington
- * $Id: opensslrsa_link.c,v 1.39.10.2 2011-03-11 02:57:35 marka Exp $
+ * $Id$
  */
 #ifdef OPENSSL
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/order.c
--- a/head/contrib/bind9/lib/dns/order.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/order.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: order.c,v 1.10 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: order.c,v 1.10 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/peer.c
--- a/head/contrib/bind9/lib/dns/peer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/peer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: peer.c,v 1.33 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: peer.c,v 1.33 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/portlist.c
--- a/head/contrib/bind9/lib/dns/portlist.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/portlist.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: portlist.c,v 1.13 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: portlist.c,v 1.13 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/private.c
--- a/head/contrib/bind9/lib/dns/private.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/private.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: private.c,v 1.3 2009-10-09 23:48:09 tbox Exp $ */
+/* $Id$ */
=20
 #include "config.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rbt.c
--- a/head/contrib/bind9/lib/dns/rbt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rbt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rbt.c,v 1.146.278.2 2011-03-12 04:59:17 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -1929,6 +1929,8 @@
 					sibling =3D RIGHT(parent);
 				}
=20
+				INSIST(sibling !=3D NULL);
+
 				if (IS_BLACK(LEFT(sibling)) &&
 				    IS_BLACK(RIGHT(sibling))) {
 					MAKE_RED(sibling);
@@ -1965,6 +1967,8 @@
 					sibling =3D LEFT(parent);
 				}
=20
+				INSIST(sibling !=3D NULL);
+
 				if (IS_BLACK(LEFT(sibling)) &&
 				    IS_BLACK(RIGHT(sibling))) {
 					MAKE_RED(sibling);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rbtdb.c
--- a/head/contrib/bind9/lib/dns/rbtdb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rbtdb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rbtdb.c,v 1.310.8.5.4.1 2011-11-16 09:32:08 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -365,9 +365,12 @@
 	dns_db_secure
 } dns_db_secure_t;
=20
+typedef struct dns_rbtdb dns_rbtdb_t;
+
 typedef struct rbtdb_version {
 	/* Not locked */
 	rbtdb_serial_t                  serial;
+	dns_rbtdb_t *			rbtdb;
 	/*
 	 * Protected in the refcount routines.
 	 * XXXJT: should we change the lock policy based on the refcount
@@ -392,7 +395,7 @@
=20
 typedef ISC_LIST(rbtdb_version_t)       rbtdb_versionlist_t;
=20
-typedef struct {
+struct dns_rbtdb {
 	/* Unlocked. */
 	dns_db_t                        common;
 	/* Locks the data in this struct */
@@ -452,7 +455,7 @@
=20
 	/* Unlocked */
 	unsigned int                    quantum;
-} dns_rbtdb_t;
+};
=20
 #define RBTDB_ATTR_LOADED               0x01
 #define RBTDB_ATTR_LOADING              0x02
@@ -1105,6 +1108,7 @@
 	version =3D allocate_version(rbtdb->common.mctx, rbtdb->next_serial, 1,
 				   ISC_TRUE);
 	if (version !=3D NULL) {
+		version->rbtdb =3D rbtdb;
 		version->commit_ok =3D ISC_TRUE;
 		version->secure =3D rbtdb->current_version->secure;
 		version->havensec3 =3D rbtdb->current_version->havensec3;
@@ -1146,6 +1150,7 @@
 	unsigned int refs;
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
+	INSIST(rbtversion !=3D NULL && rbtversion->rbtdb =3D=3D rbtdb);
=20
 	isc_refcount_increment(&rbtversion->references, &refs);
 	INSIST(refs > 1);
@@ -1603,14 +1608,14 @@
 }
=20
 /*
- * Caller must be holding the node lock if its reference must be protected
- * by the lock.
+ * Caller must be holding the node lock.
  */
 static inline void
 new_reference(dns_rbtdb_t *rbtdb, dns_rbtnode_t *node) {
 	unsigned int lockrefs, noderefs;
 	isc_refcount_t *lockref;
=20
+	INSIST(!ISC_LINK_LINKED(node, deadlink));
 	dns_rbtnode_refincrement0(node, &noderefs);
 	if (noderefs =3D=3D 1) {    /* this is the first reference to the node */
 		lockref =3D &rbtdb->node_locks[node->locknum].references;
@@ -1634,33 +1639,43 @@
 reactivate_node(dns_rbtdb_t *rbtdb, dns_rbtnode_t *node,
 		isc_rwlocktype_t treelocktype)
 {
-	isc_boolean_t need_relock =3D ISC_FALSE;
-
-	NODE_STRONGLOCK(&rbtdb->node_locks[node->locknum].lock);
-	new_reference(rbtdb, node);
-
-	NODE_WEAKLOCK(&rbtdb->node_locks[node->locknum].lock,
-		      isc_rwlocktype_read);
-	if (ISC_LINK_LINKED(node, deadlink))
-		need_relock =3D ISC_TRUE;
-	else if (!ISC_LIST_EMPTY(rbtdb->deadnodes[node->locknum]) &&
-		 treelocktype =3D=3D isc_rwlocktype_write)
-		need_relock =3D ISC_TRUE;
-	NODE_WEAKUNLOCK(&rbtdb->node_locks[node->locknum].lock,
-			isc_rwlocktype_read);
-	if (need_relock) {
-		NODE_WEAKLOCK(&rbtdb->node_locks[node->locknum].lock,
-			      isc_rwlocktype_write);
+	isc_rwlocktype_t locktype =3D isc_rwlocktype_read;
+	nodelock_t *nodelock =3D &rbtdb->node_locks[node->locknum].lock;
+	isc_boolean_t maybe_cleanup =3D ISC_FALSE;
+
+	POST(locktype);
+
+	NODE_STRONGLOCK(nodelock);
+	NODE_WEAKLOCK(nodelock, locktype);
+
+	/*
+	 * Check if we can possibly cleanup the dead node.  If so, upgrade
+	 * the node lock below to perform the cleanup.
+	 */
+	if (!ISC_LIST_EMPTY(rbtdb->deadnodes[node->locknum]) &&
+	    treelocktype =3D=3D isc_rwlocktype_write) {
+		maybe_cleanup =3D ISC_TRUE;
+	}
+
+	if (ISC_LINK_LINKED(node, deadlink) || maybe_cleanup) {
+		/*
+		 * Upgrade the lock and test if we still need to unlink.
+		 */
+		NODE_WEAKUNLOCK(nodelock, locktype);
+		locktype =3D isc_rwlocktype_write;
+		POST(locktype);
+		NODE_WEAKLOCK(nodelock, locktype);
 		if (ISC_LINK_LINKED(node, deadlink))
 			ISC_LIST_UNLINK(rbtdb->deadnodes[node->locknum],
 					node, deadlink);
-		if (treelocktype =3D=3D isc_rwlocktype_write)
+		if (maybe_cleanup)
 			cleanup_dead_nodes(rbtdb, node->locknum);
-		NODE_WEAKUNLOCK(&rbtdb->node_locks[node->locknum].lock,
-				isc_rwlocktype_write);
-	}
-
-	NODE_STRONGUNLOCK(&rbtdb->node_locks[node->locknum].lock);
+	}
+
+	new_reference(rbtdb, node);
+
+	NODE_WEAKUNLOCK(nodelock, locktype);
+	NODE_STRONGUNLOCK(nodelock);
 }
=20
 /*
@@ -1684,7 +1699,7 @@
 	rbtdb_nodelock_t *nodelock;
 	unsigned int refs, nrefs;
 	int bucket =3D node->locknum;
-	isc_boolean_t no_reference;
+	isc_boolean_t no_reference =3D ISC_TRUE;
=20
 	nodelock =3D &rbtdb->node_locks[bucket];
=20
@@ -1704,6 +1719,7 @@
 		NODE_WEAKUNLOCK(&nodelock->lock, isc_rwlocktype_read);
 		NODE_WEAKLOCK(&nodelock->lock, isc_rwlocktype_write);
 	}
+
 	dns_rbtnode_refdecrement(node, &nrefs);
 	INSIST((int)nrefs >=3D 0);
 	if (nrefs > 0) {
@@ -1713,7 +1729,7 @@
 		return (ISC_FALSE);
 	}
=20
-	if (node->dirty && dns_rbtnode_refcurrent(node) =3D=3D 0) {
+	if (node->dirty) {
 		if (IS_CACHE(rbtdb))
 			clean_cache_node(rbtdb, node);
 		else {
@@ -1731,19 +1747,6 @@
 		}
 	}
=20
-	isc_refcount_decrement(&nodelock->references, &refs);
-	INSIST((int)refs >=3D 0);
-
-	/*
-	 * XXXDCL should this only be done for cache zones?
-	 */
-	if (node->data !=3D NULL || node->down !=3D NULL) {
-		/* Restore the lock? */
-		if (nlock =3D=3D isc_rwlocktype_read)
-			NODE_WEAKDOWNGRADE(&nodelock->lock);
-		return (ISC_TRUE);
-	}
-
 	/*
 	 * Attempt to switch to a write lock on the tree.  If this fails,
 	 * we will add this node to a linked list of nodes in this locking
@@ -1767,13 +1770,18 @@
 	} else
 		write_locked =3D ISC_TRUE;
=20
-	no_reference =3D ISC_TRUE;
-	if (write_locked && dns_rbtnode_refcurrent(node) =3D=3D 0) {
+	isc_refcount_decrement(&nodelock->references, &refs);
+	INSIST((int)refs >=3D 0);
+
+	/*
+	 * XXXDCL should this only be done for cache zones?
+	 */
+	if (node->data !=3D NULL || node->down !=3D NULL)
+		goto restore_locks;
+
+	if (write_locked) {
 		/*
-		 * We can now delete the node if the reference counter is
-		 * zero.  This should be typically the case, but a different
-		 * thread may still gain a (new) reference just before the
-		 * current thread locks the tree (e.g., in findnode()).
+		 * We can now delete the node.
 		 */
=20
 		/*
@@ -1825,6 +1833,7 @@
 					      ISC_LOG_INFO,
 					      "decrement_reference: failed to "
 					      "allocate pruning event");
+				INSIST(node->data =3D=3D NULL);
 				INSIST(!ISC_LINK_LINKED(node, deadlink));
 				ISC_LIST_APPEND(rbtdb->deadnodes[bucket], node,
 						deadlink);
@@ -1847,12 +1856,13 @@
=20
 			delete_node(rbtdb, node);
 		}
-	} else if (dns_rbtnode_refcurrent(node) =3D=3D 0) {
+	} else {
+		INSIST(node->data =3D=3D NULL);
 		INSIST(!ISC_LINK_LINKED(node, deadlink));
 		ISC_LIST_APPEND(rbtdb->deadnodes[bucket], node, deadlink);
-	} else
-		no_reference =3D ISC_FALSE;
-
+	}
+
+ restore_locks:
 	/* Restore the lock? */
 	if (nlock =3D=3D isc_rwlocktype_read)
 		NODE_WEAKDOWNGRADE(&nodelock->lock);
@@ -1919,11 +1929,10 @@
 			 * from the list beforehand as we do in
 			 * reactivate_node().
 			 */
-			new_reference(rbtdb, parent);
-			if (ISC_LINK_LINKED(parent, deadlink)) {
+			if (ISC_LINK_LINKED(parent, deadlink))
 				ISC_LIST_UNLINK(rbtdb->deadnodes[locknum],
 						parent, deadlink);
-			}
+			new_reference(rbtdb, parent);
 		} else
 			parent =3D NULL;
=20
@@ -1998,9 +2007,9 @@
 	result =3D dns_db_findrdataset(db, origin, version, dns_rdatatype_dnskey,
 				     0, 0, &keyset, NULL);
 	if (result =3D=3D ISC_R_SUCCESS) {
-		dns_rdata_t keyrdata =3D DNS_RDATA_INIT;
 		result =3D dns_rdataset_first(&keyset);
 		while (result =3D=3D ISC_R_SUCCESS) {
+			dns_rdata_t keyrdata =3D DNS_RDATA_INIT;
 			dns_rdataset_current(&keyset, &keyrdata);
 			if (dns_zonekey_iszonekey(&keyrdata)) {
 				haszonekey =3D ISC_TRUE;
@@ -2182,6 +2191,7 @@
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
 	version =3D (rbtdb_version_t *)*versionp;
+	INSIST(version->rbtdb =3D=3D rbtdb);
=20
 	cleanup_version =3D NULL;
 	ISC_LIST_INIT(cleanup_list);
@@ -2494,20 +2504,19 @@
 }
=20
 static isc_result_t
-findnode(dns_db_t *db, dns_name_t *name, isc_boolean_t create,
-	 dns_dbnode_t **nodep)
+findnodeintree(dns_rbtdb_t *rbtdb, dns_rbt_t *tree, dns_name_t *name,
+	       isc_boolean_t create, dns_dbnode_t **nodep)
 {
-	dns_rbtdb_t *rbtdb =3D (dns_rbtdb_t *)db;
 	dns_rbtnode_t *node =3D NULL;
 	dns_name_t nodename;
 	isc_result_t result;
 	isc_rwlocktype_t locktype =3D isc_rwlocktype_read;
=20
-	REQUIRE(VALID_RBTDB(rbtdb));
+	INSIST(tree =3D=3D rbtdb->tree || tree =3D=3D rbtdb->nsec3);
=20
 	dns_name_init(&nodename, NULL);
 	RWLOCK(&rbtdb->tree_lock, locktype);
-	result =3D dns_rbt_findnode(rbtdb->tree, name, NULL, &node, NULL,
+	result =3D dns_rbt_findnode(tree, name, NULL, &node, NULL,
 				  DNS_RBTFIND_EMPTYDATA, NULL, NULL);
 	if (result !=3D ISC_R_SUCCESS) {
 		RWUNLOCK(&rbtdb->tree_lock, locktype);
@@ -2523,10 +2532,10 @@
 		locktype =3D isc_rwlocktype_write;
 		RWLOCK(&rbtdb->tree_lock, locktype);
 		node =3D NULL;
-		result =3D dns_rbt_addnode(rbtdb->tree, name, &node);
+		result =3D dns_rbt_addnode(tree, name, &node);
 		if (result =3D=3D ISC_R_SUCCESS) {
 #ifdef BIND9
-			if (rbtdb->rpz_cidr !=3D NULL) {
+			if (tree =3D=3D rbtdb->tree && rbtdb->rpz_cidr !=3D NULL) {
 				dns_fixedname_t fnamef;
 				dns_name_t *fname;
=20
@@ -2543,20 +2552,28 @@
 			node->locknum =3D dns_name_hash(&nodename, ISC_TRUE) %
 				rbtdb->node_lock_count;
 #endif
-			add_empty_wildcards(rbtdb, name);
-
-			if (dns_name_iswildcard(name)) {
-				result =3D add_wildcard_magic(rbtdb, name);
-				if (result !=3D ISC_R_SUCCESS) {
-					RWUNLOCK(&rbtdb->tree_lock, locktype);
-					return (result);
+			if (tree =3D=3D rbtdb->tree) {
+				add_empty_wildcards(rbtdb, name);
+
+				if (dns_name_iswildcard(name)) {
+					result =3D add_wildcard_magic(rbtdb, name);
+					if (result !=3D ISC_R_SUCCESS) {
+						RWUNLOCK(&rbtdb->tree_lock, locktype);
+						return (result);
+					}
 				}
 			}
+			if (tree =3D=3D rbtdb->nsec3)
+				node->nsec =3D DNS_RBT_NSEC_NSEC3;
 		} else if (result !=3D ISC_R_EXISTS) {
 			RWUNLOCK(&rbtdb->tree_lock, locktype);
 			return (result);
 		}
 	}
+
+	if (tree =3D=3D rbtdb->nsec3)
+		INSIST(node->nsec =3D=3D DNS_RBT_NSEC_NSEC3);
+
 	reactivate_node(rbtdb, node, locktype);
 	RWUNLOCK(&rbtdb->tree_lock, locktype);
=20
@@ -2566,60 +2583,25 @@
 }
=20
 static isc_result_t
+findnode(dns_db_t *db, dns_name_t *name, isc_boolean_t create,
+	 dns_dbnode_t **nodep)
+{
+	dns_rbtdb_t *rbtdb =3D (dns_rbtdb_t *)db;
+
+	REQUIRE(VALID_RBTDB(rbtdb));
+
+	return (findnodeintree(rbtdb, rbtdb->tree, name, create, nodep));
+}
+
+static isc_result_t
 findnsec3node(dns_db_t *db, dns_name_t *name, isc_boolean_t create,
 	      dns_dbnode_t **nodep)
 {
 	dns_rbtdb_t *rbtdb =3D (dns_rbtdb_t *)db;
-	dns_rbtnode_t *node =3D NULL;
-	dns_name_t nodename;
-	isc_result_t result;
-	isc_rwlocktype_t locktype =3D isc_rwlocktype_read;
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
=20
-	dns_name_init(&nodename, NULL);
-	RWLOCK(&rbtdb->tree_lock, locktype);
-	result =3D dns_rbt_findnode(rbtdb->nsec3, name, NULL, &node, NULL,
-				  DNS_RBTFIND_EMPTYDATA, NULL, NULL);
-	if (result !=3D ISC_R_SUCCESS) {
-		RWUNLOCK(&rbtdb->tree_lock, locktype);
-		if (!create) {
-			if (result =3D=3D DNS_R_PARTIALMATCH)
-				result =3D ISC_R_NOTFOUND;
-			return (result);
-		}
-		/*
-		 * It would be nice to try to upgrade the lock instead of
-		 * unlocking then relocking.
-		 */
-		locktype =3D isc_rwlocktype_write;
-		RWLOCK(&rbtdb->tree_lock, locktype);
-		node =3D NULL;
-		result =3D dns_rbt_addnode(rbtdb->nsec3, name, &node);
-		if (result =3D=3D ISC_R_SUCCESS) {
-			dns_rbt_namefromnode(node, &nodename);
-#ifdef DNS_RBT_USEHASH
-			node->locknum =3D node->hashval % rbtdb->node_lock_count;
-#else
-			node->locknum =3D dns_name_hash(&nodename, ISC_TRUE) %
-				rbtdb->node_lock_count;
-#endif
-			node->nsec =3D DNS_RBT_NSEC_NSEC3;
-		} else if (result !=3D ISC_R_EXISTS) {
-			RWUNLOCK(&rbtdb->tree_lock, locktype);
-			return (result);
-		}
-	} else {
-		INSIST(node->nsec =3D=3D DNS_RBT_NSEC_NSEC3);
-	}
-	NODE_STRONGLOCK(&rbtdb->node_locks[node->locknum].lock);
-	new_reference(rbtdb, node);
-	NODE_STRONGUNLOCK(&rbtdb->node_locks[node->locknum].lock);
-	RWUNLOCK(&rbtdb->tree_lock, locktype);
-
-	*nodep =3D (dns_dbnode_t *)node;
-
-	return (ISC_R_SUCCESS);
+	return (findnodeintree(rbtdb, rbtdb->nsec3, name, create, nodep));
 }
=20
 static isc_result_t
@@ -3649,6 +3631,8 @@
 	search.rbtdb =3D (dns_rbtdb_t *)db;
=20
 	REQUIRE(VALID_RBTDB(search.rbtdb));
+	INSIST(version =3D=3D NULL ||
+	       ((rbtdb_version_t *)version)->rbtdb =3D=3D (dns_rbtdb_t *)db);
=20
 	/*
 	 * We don't care about 'now'.
@@ -4580,15 +4564,19 @@
  * Search the CDIR block tree of a response policy tree of trees for all of
  * the IP addresses in an A or AAAA rdataset.
  * Among the policies for all IPv4 and IPv6 addresses for a name, choose
- * the longest prefix.  Among those with the longest prefix, the first
- * configured policy.  Among answers for with the longest prefixes for
- * two or more IP addresses in the A and AAAA rdatasets the lexically
- * smallest address.
+ *	the earliest configured policy,
+ *	QNAME over IP over NSDNAME over NSIP,
+ *	the longest prefix,
+ *	the lexically smallest address.
+ * The caller must have already checked that any existing policy was not
+ * configured earlier than this policy zone and does not have a higher
+ * precedence type.
  */
 static isc_result_t
 rpz_findips(dns_rpz_zone_t *rpz, dns_rpz_type_t rpz_type,
 	    dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *version,
-	    dns_rdataset_t *ardataset, dns_rpz_st_t *st)
+	    dns_rdataset_t *ardataset, dns_rpz_st_t *st,
+	    dns_name_t *query_qname)
 {
 	dns_rbtdb_t *rbtdb;
 	struct in_addr ina;
@@ -4609,8 +4597,6 @@
=20
 	if (rbtdb->rpz_cidr =3D=3D NULL) {
 		RWUNLOCK(&rbtdb->tree_lock, isc_rwlocktype_read);
-		dns_db_detach(&db);
-		dns_zone_detach(&zone);
 		return (ISC_R_UNEXPECTED);
 	}
=20
@@ -4645,17 +4631,19 @@
 			continue;
=20
 		/*
-		 * Choose the policy with the longest matching prefix.
-		 * Between policies with the same prefix, choose the first
-		 * configured.
+		 * If we already have a rule, discard this new rule if
+		 * is not better.
+		 * The caller has checked that st->m.rpz->num > rpz->num
+		 * or st->m.rpz->num =3D=3D rpz->num and st->m.type >=3D rpz_type
 		 */
-		if (st->m.policy !=3D DNS_RPZ_POLICY_MISS) {
-			if (prefix < st->m.prefix)
-				continue;
-			if (prefix =3D=3D st->m.prefix &&
-			    rpz->num > st->m.rpz->num)
-				continue;
-		}
+		if (st->m.policy !=3D DNS_RPZ_POLICY_MISS &&
+		    st->m.rpz->num =3D=3D rpz->num &&
+		    (st->m.type < rpz_type ||
+		     (st->m.type =3D=3D rpz_type &&
+		      (st->m.prefix > prefix ||
+		       (st->m.prefix =3D=3D prefix &&
+			0 > dns_name_rdatacompare(st->qname, qname))))))
+			continue;
=20
 		/*
 		 * We have rpz_st an entry with a prefix at least as long as
@@ -4669,8 +4657,8 @@
 			char namebuf[DNS_NAME_FORMATSIZE];
=20
 			dns_name_format(qname, namebuf, sizeof(namebuf));
-			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
-				      DNS_LOGMODULE_CACHE, DNS_RPZ_ERROR_LEVEL,
+			isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
+				      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
 				      "rpz_findips findnode(%s): %s",
 				      namebuf, isc_result_totext(result));
 			continue;
@@ -4694,7 +4682,8 @@
 			} else {
 				rpz_policy =3D dns_rpz_decode_cname(&zrdataset,
 								  selfname);
-				if (rpz_policy =3D=3D DNS_RPZ_POLICY_RECORD)
+				if (rpz_policy =3D=3D DNS_RPZ_POLICY_RECORD ||
+				    rpz_policy =3D=3D DNS_RPZ_POLICY_WILDCNAME)
 					result =3D DNS_R_CNAME;
 			}
 			ttl =3D zrdataset.ttl;
@@ -4707,44 +4696,60 @@
 		/*
 		 * Use an overriding action specified in the configuration file
 		 */
-		if (rpz->policy !=3D DNS_RPZ_POLICY_GIVEN &&
-		    rpz_policy !=3D DNS_RPZ_POLICY_NO_OP)
+		if (rpz->policy !=3D DNS_RPZ_POLICY_GIVEN) {
+			/*
+			 * only log DNS_RPZ_POLICY_DISABLED hits
+			 */
+			if (rpz->policy =3D=3D DNS_RPZ_POLICY_DISABLED) {
+				if (isc_log_wouldlog(dns_lctx,
+						     DNS_RPZ_INFO_LEVEL)) {
+					char qname_buf[DNS_NAME_FORMATSIZE];
+					char rpz_qname_buf[DNS_NAME_FORMATSIZE];
+					dns_name_format(query_qname, qname_buf,
+							sizeof(qname_buf));
+					dns_name_format(qname, rpz_qname_buf,
+							sizeof(rpz_qname_buf));
+
+					isc_log_write(dns_lctx,
+						DNS_LOGCATEGORY_RPZ,
+						DNS_LOGMODULE_RBTDB,
+						DNS_RPZ_INFO_LEVEL,
+						"disabled rpz %s %s rewrite"
+						" %s via %s",
+						dns_rpz_type2str(rpz_type),
+						dns_rpz_policy2str(rpz_policy),
+						qname_buf, rpz_qname_buf);
+				}
+				continue;
+			}
+
 			rpz_policy =3D rpz->policy;
-
-		/*
-		 * We know the new prefix is at least as long as the current.
-		 * Prefer the new answer if the new prefix is longer.
-		 * Prefer the zone configured first if the prefixes are equal.
-		 * With two actions from the same zone, prefer the action
-		 * on the "smallest" name.
-		 */
-		if (st->m.policy =3D=3D DNS_RPZ_POLICY_MISS ||
-		    prefix > st->m.prefix ||
-		    rpz->num <=3D st->m.rpz->num ||
-		    0 > dns_name_compare(qname, st->qname)) {
-			if (dns_rdataset_isassociated(st->m.rdataset))
-				dns_rdataset_disassociate(st->m.rdataset);
-			if (st->m.node !=3D NULL)
-				dns_db_detachnode(st->m.db, &st->m.node);
-			if (st->m.db !=3D NULL)
-				dns_db_detach(&st->m.db);
-			if (st->m.zone !=3D NULL)
-				dns_zone_detach(&st->m.zone);
-			st->m.rpz =3D rpz;
-			st->m.type =3D rpz_type;
-			st->m.prefix =3D prefix;
-			st->m.policy =3D rpz_policy;
-			st->m.ttl =3D ttl;
-			st->m.result =3D result;
-			dns_name_copy(qname, st->qname, NULL);
-			if (rpz_policy =3D=3D DNS_RPZ_POLICY_RECORD &&
-			    result !=3D DNS_R_NXRRSET) {
-				dns_rdataset_clone(&zrdataset,st->m.rdataset);
-				dns_db_attachnode(db, node, &st->m.node);
-			}
-			dns_db_attach(db, &st->m.db);
-			dns_zone_attach(zone, &st->m.zone);
-		}
+		}
+
+		if (dns_rdataset_isassociated(st->m.rdataset))
+			dns_rdataset_disassociate(st->m.rdataset);
+		if (st->m.node !=3D NULL)
+			dns_db_detachnode(st->m.db, &st->m.node);
+		if (st->m.db !=3D NULL)
+			dns_db_detach(&st->m.db);
+		if (st->m.zone !=3D NULL)
+			dns_zone_detach(&st->m.zone);
+		st->m.rpz =3D rpz;
+		st->m.type =3D rpz_type;
+		st->m.prefix =3D prefix;
+		st->m.policy =3D rpz_policy;
+		st->m.ttl =3D ttl;
+		st->m.result =3D result;
+		dns_name_copy(qname, st->qname, NULL);
+		if ((rpz_policy =3D=3D DNS_RPZ_POLICY_RECORD ||
+		    rpz_policy =3D=3D DNS_RPZ_POLICY_WILDCNAME) &&
+		    result !=3D DNS_R_NXRRSET) {
+			dns_rdataset_clone(&zrdataset,st->m.rdataset);
+			dns_db_attachnode(db, node, &st->m.node);
+		}
+		dns_db_attach(db, &st->m.db);
+		st->m.version =3D version;
+		dns_zone_attach(zone, &st->m.zone);
 		if (dns_rdataset_isassociated(&zrdataset))
 			dns_rdataset_disassociate(&zrdataset);
 	}
@@ -5544,6 +5549,7 @@
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
 	REQUIRE(type !=3D dns_rdatatype_any);
+	INSIST(rbtversion =3D=3D NULL || rbtversion->rbtdb =3D=3D rbtdb);
=20
 	if (rbtversion =3D=3D NULL) {
 		currentversion(db, (dns_dbversion_t **) (void *)(&rbtversion));
@@ -5732,6 +5738,8 @@
 		else {
 			unsigned int refs;
=20
+			INSIST(rbtversion->rbtdb =3D=3D rbtdb);
+
 			isc_refcount_increment(&rbtversion->references,
 					       &refs);
 			INSIST(refs > 1);
@@ -6122,6 +6130,19 @@
 					      addedrdataset);
 			return (ISC_R_SUCCESS);
 		}
+		/*
+		 * If we have will be replacing a NS RRset force its TTL
+		 * to be no more than the current NS RRset's TTL.  This
+		 * ensures the delegations that are withdrawn are honoured.
+		 */
+		if (IS_CACHE(rbtdb) && header->rdh_ttl > now &&
+		    header->type =3D=3D dns_rdatatype_ns &&
+		    !header_nx && !newheader_nx &&
+		    header->trust <=3D newheader->trust) {
+			if (newheader->rdh_ttl > header->rdh_ttl) {
+				newheader->rdh_ttl =3D header->rdh_ttl;
+			}
+		}
 		if (IS_CACHE(rbtdb) && header->rdh_ttl > now &&
 		    (header->type =3D=3D dns_rdatatype_a ||
 		     header->type =3D=3D dns_rdatatype_aaaa) &&
@@ -6401,6 +6422,7 @@
 	isc_boolean_t cache_is_overmem =3D ISC_FALSE;
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
+	INSIST(rbtversion =3D=3D NULL || rbtversion->rbtdb =3D=3D rbtdb);
=20
 	if (rbtdb->common.methods =3D=3D &zone_methods)
 		REQUIRE(((rbtnode->nsec =3D=3D DNS_RBT_NSEC_NSEC3 &&
@@ -6417,8 +6439,7 @@
 		now =3D 0;
=20
 	result =3D dns_rdataslab_fromrdataset(rdataset, rbtdb->common.mctx,
-					    &region,
-					    sizeof(rdatasetheader_t));
+					    &region, sizeof(rdatasetheader_t));
 	if (result !=3D ISC_R_SUCCESS)
 		return (result);
=20
@@ -6591,6 +6612,7 @@
 	rbtdb_changed_t *changed;
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
+	REQUIRE(rbtversion !=3D NULL && rbtversion->rbtdb =3D=3D rbtdb);
=20
 	if (rbtdb->common.methods =3D=3D &zone_methods)
 		REQUIRE(((rbtnode->nsec =3D=3D DNS_RBT_NSEC_NSEC3 &&
@@ -6771,6 +6793,7 @@
 	rdatasetheader_t *newheader;
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
+	INSIST(rbtversion =3D=3D NULL || rbtversion->rbtdb =3D=3D rbtdb);
=20
 	if (type =3D=3D dns_rdatatype_any)
 		return (ISC_R_NOTIMPLEMENTED);
@@ -7064,10 +7087,12 @@
 dump(dns_db_t *db, dns_dbversion_t *version, const char *filename,
      dns_masterformat_t masterformat) {
 	dns_rbtdb_t *rbtdb;
+	rbtdb_version_t *rbtversion =3D version;
=20
 	rbtdb =3D (dns_rbtdb_t *)db;
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
+	INSIST(rbtversion =3D=3D NULL || rbtversion->rbtdb =3D=3D rbtdb);
=20
 #ifdef BIND9
 	return (dns_master_dump2(rbtdb->common.mctx, db, version,
@@ -7206,6 +7231,7 @@
 	rbtdb =3D (dns_rbtdb_t *)db;
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
+	INSIST(rbtversion =3D=3D NULL || rbtversion->rbtdb =3D=3D rbtdb);
=20
 	RWLOCK(&rbtdb->tree_lock, isc_rwlocktype_read);
=20
@@ -7335,11 +7361,16 @@
=20
 	REQUIRE(VALID_RBTDB(rbtdb));
 	REQUIRE(rdataset !=3D NULL);
+	REQUIRE(rdataset->methods =3D=3D &rdataset_methods);
 	REQUIRE(rbtdb->future_version =3D=3D rbtversion);
+	REQUIRE(rbtversion !=3D NULL);
 	REQUIRE(rbtversion->writer);
+	REQUIRE(rbtversion->rbtdb =3D=3D rbtdb);
=20
 	node =3D rdataset->private2;
+	INSIST(node !=3D NULL);
 	header =3D rdataset->private3;
+	INSIST(header !=3D NULL);
 	header--;
=20
 	RWLOCK(&rbtdb->tree_lock, isc_rwlocktype_write);
@@ -7750,6 +7781,7 @@
 		free_rbtdb(rbtdb, ISC_FALSE, NULL);
 		return (ISC_R_NOMEMORY);
 	}
+	rbtdb->current_version->rbtdb =3D rbtdb;
 	rbtdb->current_version->secure =3D dns_db_insecure;
 	rbtdb->current_version->havensec3 =3D ISC_FALSE;
 	rbtdb->current_version->flags =3D 0;
@@ -8480,7 +8512,7 @@
=20
 static isc_result_t
 dbiterator_seek(dns_dbiterator_t *iterator, dns_name_t *name) {
-	isc_result_t result;
+	isc_result_t result, tresult;
 	rbtdb_dbiterator_t *rbtdbiter =3D (rbtdb_dbiterator_t *)iterator;
 	dns_rbtdb_t *rbtdb =3D (dns_rbtdb_t *)iterator->db;
 	dns_name_t *iname, *origin;
@@ -8523,13 +8555,14 @@
 					  DNS_RBTFIND_EMPTYDATA, NULL, NULL);
 		if (result =3D=3D DNS_R_PARTIALMATCH) {
 			dns_rbtnode_t *node =3D NULL;
-			result =3D dns_rbt_findnode(rbtdb->nsec3, name, NULL,
+			tresult =3D dns_rbt_findnode(rbtdb->nsec3, name, NULL,
 						  &node, &rbtdbiter->nsec3chain,
 						  DNS_RBTFIND_EMPTYDATA,
 						  NULL, NULL);
-			if (result =3D=3D ISC_R_SUCCESS) {
+			if (tresult =3D=3D ISC_R_SUCCESS) {
 				rbtdbiter->node =3D node;
 				rbtdbiter->current =3D &rbtdbiter->nsec3chain;
+				result =3D tresult;
 			}
 		}
 	}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rbtdb.h
--- a/head/contrib/bind9/lib/dns/rbtdb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rbtdb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rbtdb.h,v 1.18.814.2 2011-03-03 23:47:09 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef DNS_RBTDB_H
 #define DNS_RBTDB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rbtdb64.c
--- a/head/contrib/bind9/lib/dns/rbtdb64.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rbtdb64.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rbtdb64.c,v 1.11 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: rbtdb64.c,v 1.11 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rbtdb64.h
--- a/head/contrib/bind9/lib/dns/rbtdb64.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rbtdb64.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rbtdb64.h,v 1.17 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: rbtdb64.h,v 1.17 2007/06/19 23:47:16 tbox Exp $ */
=20
 #ifndef DNS_RBTDB64_H
 #define DNS_RBTDB64_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rcode.c
--- a/head/contrib/bind9/lib/dns/rcode.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rcode.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rcode.c,v 1.16.14.2 2011-02-28 01:20:02 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
 #include <ctype.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata.c
--- a/head/contrib/bind9/lib/dns/rdata.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdata.c,v 1.209.8.2 2011-03-11 06:47:05 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -208,6 +208,10 @@
 static isc_uint16_t
 uint16_consume_fromregion(isc_region_t *region);
=20
+static isc_result_t
+unknown_totext(dns_rdata_t *rdata, dns_rdata_textctx_t *tctx,
+	       isc_buffer_t *target);
+
 static inline int
 getquad(const void *src, struct in_addr *dst,
 	isc_lex_t *lexer, dns_rdatacallbacks_t *callbacks)
@@ -621,8 +625,7 @@
 	if (result !=3D ISC_R_SUCCESS) {
 		name =3D isc_lex_getsourcename(lexer);
 		line =3D isc_lex_getsourceline(lexer);
-		fromtext_error(callback, callbacks, name, line,
-			       &token, result);
+		fromtext_error(callback, callbacks, name, line, NULL, result);
 		return (result);
 	}
=20
@@ -683,13 +686,53 @@
 }
=20
 static isc_result_t
+unknown_totext(dns_rdata_t *rdata, dns_rdata_textctx_t *tctx,
+	       isc_buffer_t *target)
+{
+	isc_result_t result;
+	char buf[sizeof("65535")];
+	isc_region_t sr;
+
+	strlcpy(buf, "\\# ", sizeof(buf));
+	result =3D str_totext(buf, target);
+	if (result !=3D ISC_R_SUCCESS)
+		return (result);
+
+	dns_rdata_toregion(rdata, &sr);
+	INSIST(sr.length < 65536);
+	snprintf(buf, sizeof(buf), "%u", sr.length);
+	result =3D str_totext(buf, target);
+	if (result !=3D ISC_R_SUCCESS)
+		return (result);
+
+	if (sr.length !=3D 0U) {
+		if ((tctx->flags & DNS_STYLEFLAG_MULTILINE) !=3D 0)
+			result =3D str_totext(" ( ", target);
+		else
+			result =3D str_totext(" ", target);
+
+		if (result !=3D ISC_R_SUCCESS)
+			return (result);
+
+		if (tctx->width =3D=3D 0) /* No splitting */
+			result =3D isc_hex_totext(&sr, 0, "", target);
+		else
+			result =3D isc_hex_totext(&sr, tctx->width - 2,
+						tctx->linebreak,
+						target);
+		if (result =3D=3D ISC_R_SUCCESS &&
+		    (tctx->flags & DNS_STYLEFLAG_MULTILINE) !=3D 0)
+			result =3D str_totext(" )", target);
+	}
+	return (result);
+}
+
+static isc_result_t
 rdata_totext(dns_rdata_t *rdata, dns_rdata_textctx_t *tctx,
 	     isc_buffer_t *target)
 {
 	isc_result_t result =3D ISC_R_NOTIMPLEMENTED;
 	isc_boolean_t use_default =3D ISC_FALSE;
-	char buf[sizeof("65535")];
-	isc_region_t sr;
=20
 	REQUIRE(rdata !=3D NULL);
 	REQUIRE(tctx->origin =3D=3D NULL ||
@@ -705,28 +748,8 @@
=20
 	TOTEXTSWITCH
=20
-	if (use_default) {
-		strlcpy(buf, "\\# ", sizeof(buf));
-		result =3D str_totext(buf, target);
-		INSIST(result =3D=3D ISC_R_SUCCESS);
-		dns_rdata_toregion(rdata, &sr);
-		INSIST(sr.length < 65536);
-		snprintf(buf, sizeof(buf), "%u", sr.length);
-		result =3D str_totext(buf, target);
-		if (sr.length !=3D 0 && result =3D=3D ISC_R_SUCCESS) {
-			if ((tctx->flags & DNS_STYLEFLAG_MULTILINE) !=3D 0)
-				result =3D str_totext(" ( ", target);
-			else
-				result =3D str_totext(" ", target);
-			if (result =3D=3D ISC_R_SUCCESS)
-				result =3D isc_hex_totext(&sr, tctx->width - 2,
-							tctx->linebreak,
-							target);
-			if (result =3D=3D ISC_R_SUCCESS &&
-			    (tctx->flags & DNS_STYLEFLAG_MULTILINE) !=3D 0)
-				result =3D str_totext(" )", target);
-		}
-	}
+	if (use_default)
+		result =3D unknown_totext(rdata, tctx, target);
=20
 	return (result);
 }
@@ -1099,7 +1122,8 @@
 		}
 		escape =3D ISC_FALSE;
 		if (nrem =3D=3D 0)
-			return (ISC_R_NOSPACE);
+			return ((tregion.length <=3D 256U) ?
+				ISC_R_NOSPACE : DNS_R_SYNTAX);
 		*t++ =3D c;
 		nrem--;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/any_2=
55/tsig_250.c
--- a/head/contrib/bind9/lib/dns/rdata/any_255/tsig_250.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/any_255/tsig_250.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsig_250.c,v 1.65 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Thu Mar 16 13:39:43 PST 2000 by gson */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/any_2=
55/tsig_250.h
--- a/head/contrib/bind9/lib/dns/rdata/any_255/tsig_250.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/any_255/tsig_250.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsig_250.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: tsig_250.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef ANY_255_TSIG_250_H
 #define ANY_255_TSIG_250_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/ch_3/=
a_1.c
--- a/head/contrib/bind9/lib/dns/rdata/ch_3/a_1.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/rdata/ch_3/a_1.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: a_1.c,v 1.8 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: a_1.c,v 1.8 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* by Bjorn.Victor at it.uu.se, 2005-05-07 */
 /* Based on generic/soa_6.c and generic/mx_15.c */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/ch_3/=
a_1.h
--- a/head/contrib/bind9/lib/dns/rdata/ch_3/a_1.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/rdata/ch_3/a_1.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: a_1.h,v 1.5 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a_1.h,v 1.5 2007/06/19 23:47:17 tbox Exp $ */
=20
 /* by Bjorn.Victor at it.uu.se, 2005-05-07 */
 /* Based on generic/mx_15.h */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/afsdb_18.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/afsdb_18.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/afsdb_18.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: afsdb_18.c,v 1.49 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: afsdb_18.c,v 1.49 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Wed Mar 15 14:59:00 PST 2000 by explorer */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/afsdb_18.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/afsdb_18.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/afsdb_18.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_AFSDB_18_H
 #define GENERIC_AFSDB_18_H 1
=20
-/* $Id: afsdb_18.h,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: afsdb_18.h,v 1.20 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/cert_37.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/cert_37.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/cert_37.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cert_37.c,v 1.52 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Wed Mar 15 21:14:32 EST 2000 by tale */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/cert_37.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/cert_37.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/cert_37.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cert_37.h,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: cert_37.h,v 1.20 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_CERT_37_H
 #define GENERIC_CERT_37_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/cname_5.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/cname_5.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/cname_5.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cname_5.c,v 1.49 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: cname_5.c,v 1.49 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 16:48:45 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/cname_5.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/cname_5.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/cname_5.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cname_5.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: cname_5.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_CNAME_5_H
 #define GENERIC_CNAME_5_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/dlv_32769.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/dlv_32769.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/dlv_32769.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2006, 2007, 2009, 2010  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2006, 2007, 2009, 2010, 2012  Internet Systems Cons=
ortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlv_32769.c,v 1.10 2010-12-23 23:47:08 tbox Exp $ */
+/* $Id$ */
=20
 /* draft-ietf-dnsext-delegation-signer-05.txt */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/dlv_32769.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/dlv_32769.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/dlv_32769.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlv_32769.h,v 1.5 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dlv_32769.h,v 1.5 2007/06/19 23:47:17 tbox Exp $ */
=20
 /* draft-ietf-dnsext-delegation-signer-05.txt */
 #ifndef GENERIC_DLV_32769_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/dname_39.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/dname_39.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/dname_39.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dname_39.c,v 1.40 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: dname_39.c,v 1.40 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Wed Mar 15 16:52:38 PST 2000 by explorer */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/dname_39.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/dname_39.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/dname_39.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_DNAME_39_H
 #define GENERIC_DNAME_39_H 1
=20
-/* $Id: dname_39.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dname_39.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief per RFC2672 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/dnskey_48.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/dnskey_48.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/dnskey_48.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnskey_48.c,v 1.10 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /*
  * Reviewed: Wed Mar 15 16:47:10 PST 2000 by halley.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/dnskey_48.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/dnskey_48.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/dnskey_48.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_DNSKEY_48_H
 #define GENERIC_DNSKEY_48_H 1
=20
-/* $Id: dnskey_48.h,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dnskey_48.h,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief per RFC2535 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ds_43.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/ds_43.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ds_43.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009, 2010  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2010, 2012  Internet Systems Cons=
ortium, Inc. ("ISC")
  * Copyright (C) 2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ds_43.c,v 1.16 2010-12-23 23:47:08 tbox Exp $ */
+/* $Id$ */
=20
 /* draft-ietf-dnsext-delegation-signer-05.txt */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ds_43.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/ds_43.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ds_43.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ds_43.h,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ds_43.h,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_DS_43_H
 #define GENERIC_DS_43_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/gpos_27.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/gpos_27.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/gpos_27.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gpos_27.c,v 1.43 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: gpos_27.c,v 1.43 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 16:48:45 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/gpos_27.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/gpos_27.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/gpos_27.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_GPOS_27_H
 #define GENERIC_GPOS_27_H 1
=20
-/* $Id: gpos_27.h,v 1.17 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: gpos_27.h,v 1.17 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief per RFC1712 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/hinfo_13.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/hinfo_13.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/hinfo_13.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hinfo_13.c,v 1.46 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: hinfo_13.c,v 1.46 2009/12/04 22:06:37 tbox Exp $ */
=20
 /*
  * Reviewed: Wed Mar 15 16:47:10 PST 2000 by halley.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/hinfo_13.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/hinfo_13.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/hinfo_13.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_HINFO_13_H
 #define GENERIC_HINFO_13_H 1
=20
-/* $Id: hinfo_13.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: hinfo_13.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_hinfo {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/hip_55.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/hip_55.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/hip_55.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hip_55.c,v 1.8 2011-01-13 04:59:26 tbox Exp $ */
+/* $Id: hip_55.c,v 1.8 2011/01/13 04:59:26 tbox Exp $ */
=20
 /* reviewed: TBC */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/hip_55.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/hip_55.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/hip_55.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hip_55.h,v 1.2 2009-02-26 06:09:19 marka Exp $ */
+/* $Id: hip_55.h,v 1.2 2009/02/26 06:09:19 marka Exp $ */
=20
 #ifndef GENERIC_HIP_5_H
 #define GENERIC_HIP_5_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ipseckey_45.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/ipseckey_45.c	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ipseckey_45.c	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005, 2007, 2009, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2005, 2007, 2009, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ipseckey_45.c,v 1.11 2011-01-13 04:59:26 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef RDATA_GENERIC_IPSECKEY_45_C
 #define RDATA_GENERIC_IPSECKEY_45_C
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ipseckey_45.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/ipseckey_45.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ipseckey_45.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ipseckey_45.h,v 1.4 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ipseckey_45.h,v 1.4 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_IPSECKEY_45_H
 #define GENERIC_IPSECKEY_45_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/isdn_20.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/isdn_20.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/isdn_20.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: isdn_20.c,v 1.40 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: isdn_20.c,v 1.40 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Wed Mar 15 16:53:11 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/isdn_20.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/isdn_20.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/isdn_20.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_ISDN_20_H
 #define GENERIC_ISDN_20_H 1
=20
-/* $Id: isdn_20.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: isdn_20.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  * \brief Per RFC1183 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/key_25.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/key_25.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/key_25.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: key_25.c,v 1.53 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /*
  * Reviewed: Wed Mar 15 16:47:10 PST 2000 by halley.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/key_25.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/key_25.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/key_25.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_KEY_25_H
 #define GENERIC_KEY_25_H 1
=20
-/* $Id: key_25.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: key_25.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  * \brief Per RFC2535 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/keydata_65533.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/keydata_65533.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/keydata_65533.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keydata_65533.c,v 1.3 2009-12-04 21:09:33 marka Exp $ */
+/* $Id$ */
=20
 #ifndef GENERIC_KEYDATA_65533_C
 #define GENERIC_KEYDATA_65533_C 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/keydata_65533.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/keydata_65533.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/keydata_65533.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -17,7 +17,7 @@
 #ifndef GENERIC_KEYDATA_65533_H
 #define GENERIC_KEYDATA_65533_H 1
=20
-/* $Id: keydata_65533.h,v 1.2 2009-06-30 02:52:32 each Exp $ */
+/* $Id: keydata_65533.h,v 1.2 2009/06/30 02:52:32 each Exp $ */
=20
 typedef struct dns_rdata_keydata {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/loc_29.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/loc_29.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/loc_29.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: loc_29.c,v 1.50 2009-12-04 21:09:33 marka Exp $ */
+/* $Id: loc_29.c,v 1.50 2009/12/04 21:09:33 marka Exp $ */
=20
 /* Reviewed: Wed Mar 15 18:13:09 PST 2000 by explorer */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/loc_29.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/loc_29.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/loc_29.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_LOC_29_H
 #define GENERIC_LOC_29_H 1
=20
-/* $Id: loc_29.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: loc_29.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  * \brief Per RFC1876 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mb_7.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/mb_7.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mb_7.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mb_7.c,v 1.47 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: mb_7.c,v 1.47 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Wed Mar 15 17:31:26 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mb_7.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/mb_7.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mb_7.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_MB_7_H
 #define GENERIC_MB_7_H 1
=20
-/* $Id: mb_7.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mb_7.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mb {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/md_3.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/md_3.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/md_3.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: md_3.c,v 1.49 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: md_3.c,v 1.49 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Wed Mar 15 17:48:20 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/md_3.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/md_3.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/md_3.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_MD_3_H
 #define GENERIC_MD_3_H 1
=20
-/* $Id: md_3.h,v 1.28 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: md_3.h,v 1.28 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_md {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mf_4.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/mf_4.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mf_4.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mf_4.c,v 1.47 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: mf_4.c,v 1.47 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 17:47:33 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mf_4.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/mf_4.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mf_4.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_MF_4_H
 #define GENERIC_MF_4_H 1
=20
-/* $Id: mf_4.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mf_4.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mf {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mg_8.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/mg_8.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mg_8.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mg_8.c,v 1.45 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: mg_8.c,v 1.45 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 17:49:21 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mg_8.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/mg_8.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mg_8.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_MG_8_H
 #define GENERIC_MG_8_H 1
=20
-/* $Id: mg_8.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mg_8.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mg {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/minfo_14.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/minfo_14.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/minfo_14.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: minfo_14.c,v 1.47 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: minfo_14.c,v 1.47 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 17:45:32 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/minfo_14.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/minfo_14.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/minfo_14.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_MINFO_14_H
 #define GENERIC_MINFO_14_H 1
=20
-/* $Id: minfo_14.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: minfo_14.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_minfo {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mr_9.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/mr_9.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mr_9.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mr_9.c,v 1.44 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: mr_9.c,v 1.44 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Wed Mar 15 21:30:35 EST 2000 by tale */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mr_9.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/mr_9.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mr_9.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_MR_9_H
 #define GENERIC_MR_9_H 1
=20
-/* $Id: mr_9.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mr_9.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mr {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mx_15.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/mx_15.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mx_15.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mx_15.c,v 1.58 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: mx_15.c,v 1.58 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 18:05:46 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/mx_15.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/mx_15.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/mx_15.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_MX_15_H
 #define GENERIC_MX_15_H 1
=20
-/* $Id: mx_15.h,v 1.29 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mx_15.h,v 1.29 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mx {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ns_2.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/ns_2.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ns_2.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ns_2.c,v 1.48 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: ns_2.c,v 1.48 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Wed Mar 15 18:15:00 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ns_2.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/ns_2.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ns_2.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_NS_2_H
 #define GENERIC_NS_2_H 1
=20
-/* $Id: ns_2.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ns_2.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_ns {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nsec3_50.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/nsec3_50.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nsec3_50.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2008, 2009, 2012  Internet Systems Consortium, Inc. ("ISC=
")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec3_50.c,v 1.7 2009-12-04 21:09:34 marka Exp $ */
+/* $Id$ */
=20
 /*
  * Copyright (C) 2004  Nominet, Ltd.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nsec3_50.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/nsec3_50.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nsec3_50.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2008, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -18,7 +18,7 @@
 #ifndef GENERIC_NSEC3_50_H
 #define GENERIC_NSEC3_50_H 1
=20
-/* $Id: nsec3_50.h,v 1.4 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id$ */
=20
 /*!
  * \brief Per RFC 5155 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nsec3param_51.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/nsec3param_51.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nsec3param_51.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec3param_51.c,v 1.7 2009-12-04 21:09:34 marka Exp $ */
+/* $Id: nsec3param_51.c,v 1.7 2009/12/04 21:09:34 marka Exp $ */
=20
 /*
  * Copyright (C) 2004  Nominet, Ltd.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nsec3param_51.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/nsec3param_51.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nsec3param_51.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_NSEC3PARAM_51_H
 #define GENERIC_NSEC3PARAM_51_H 1
=20
-/* $Id: nsec3param_51.h,v 1.4 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: nsec3param_51.h,v 1.4 2008/09/25 04:02:39 tbox Exp $ */
=20
 /*!
  * \brief Per RFC 5155 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nsec_47.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/nsec_47.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nsec_47.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsec_47.c,v 1.15 2011-01-13 04:59:26 tbox Exp $ */
+/* $Id: nsec_47.c,v 1.15 2011/01/13 04:59:26 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 18:21:15 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nsec_47.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/nsec_47.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nsec_47.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_NSEC_47_H
 #define GENERIC_NSEC_47_H 1
=20
-/* $Id: nsec_47.h,v 1.10 2008-07-15 23:47:21 tbox Exp $ */
+/* $Id: nsec_47.h,v 1.10 2008/07/15 23:47:21 tbox Exp $ */
=20
 /*!
  * \brief Per RFC 3845 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/null_10.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/null_10.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/null_10.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2007, 2009  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2007, 2009, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1998-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: null_10.c,v 1.44 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Thu Mar 16 13:57:50 PST 2000 by explorer */
=20
@@ -43,11 +43,7 @@
 totext_null(ARGS_TOTEXT) {
 	REQUIRE(rdata->type =3D=3D 10);
=20
-	UNUSED(rdata);
-	UNUSED(tctx);
-	UNUSED(target);
-
-	return (DNS_R_SYNTAX);
+	return (unknown_totext(rdata, tctx, target));
 }
=20
 static inline isc_result_t
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/null_10.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/null_10.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/null_10.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_NULL_10_H
 #define GENERIC_NULL_10_H 1
=20
-/* $Id: null_10.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: null_10.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_null {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nxt_30.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/nxt_30.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nxt_30.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nxt_30.c,v 1.65 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: nxt_30.c,v 1.65 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Wed Mar 15 18:21:15 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/nxt_30.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/nxt_30.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/nxt_30.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_NXT_30_H
 #define GENERIC_NXT_30_H 1
=20
-/* $Id: nxt_30.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: nxt_30.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief RFC2535 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/opt_41.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/opt_41.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/opt_41.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1998-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: opt_41.c,v 1.35 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Thu Mar 16 14:06:44 PST 2000 by gson */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/opt_41.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/opt_41.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/opt_41.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_OPT_41_H
 #define GENERIC_OPT_41_H 1
=20
-/* $Id: opt_41.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: opt_41.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC2671 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/proforma.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/proforma.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/proforma.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: proforma.c,v 1.38 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: proforma.c,v 1.38 2009/12/04 22:06:37 tbox Exp $ */
=20
 #ifndef RDATA_GENERIC_#_#_C
 #define RDATA_GENERIC_#_#_C
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/proforma.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/proforma.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/proforma.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_PROFORMA_H
 #define GENERIC_PROFORMA_H 1
=20
-/* $Id: proforma.h,v 1.23 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: proforma.h,v 1.23 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_# {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ptr_12.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/ptr_12.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ptr_12.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ptr_12.c,v 1.45 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: ptr_12.c,v 1.45 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Thu Mar 16 14:05:12 PST 2000 by explorer */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/ptr_12.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/ptr_12.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/ptr_12.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_PTR_12_H
 #define GENERIC_PTR_12_H 1
=20
-/* $Id: ptr_12.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ptr_12.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_ptr {
         dns_rdatacommon_t       common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/rp_17.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/rp_17.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/rp_17.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rp_17.c,v 1.44 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: rp_17.c,v 1.44 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* RFC1183 */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/rp_17.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/rp_17.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/rp_17.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_RP_17_H
 #define GENERIC_RP_17_H 1
=20
-/* $Id: rp_17.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rp_17.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/rrsig_46.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/rrsig_46.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/rrsig_46.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009, 2011  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2011, 2012  Internet Systems Cons=
ortium, Inc. ("ISC")
  * Copyright (C) 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rrsig_46.c,v 1.14 2011-01-13 04:59:26 tbox Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Fri Mar 17 09:05:02 PST 2000 by gson */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/rrsig_46.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/rrsig_46.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/rrsig_46.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_DNSSIG_46_H
 #define GENERIC_DNSSIG_46_H 1
=20
-/* $Id: rrsig_46.h,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rrsig_46.h,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC2535 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/rt_21.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/rt_21.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/rt_21.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rt_21.c,v 1.48 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: rt_21.c,v 1.48 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Thu Mar 16 15:02:31 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/rt_21.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/rt_21.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/rt_21.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_RT_21_H
 #define GENERIC_RT_21_H 1
=20
-/* $Id: rt_21.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rt_21.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/sig_24.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/sig_24.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/sig_24.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sig_24.c,v 1.68 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Fri Mar 17 09:05:02 PST 2000 by gson */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/sig_24.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/sig_24.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/sig_24.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_SIG_24_H
 #define GENERIC_SIG_24_H 1
=20
-/* $Id: sig_24.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: sig_24.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC2535 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/soa_6.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/soa_6.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/soa_6.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2007, 2009  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2007, 2009, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 1998-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: soa_6.c,v 1.64 2009-12-04 21:09:34 marka Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Thu Mar 16 15:18:32 PST 2000 by explorer */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/soa_6.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/soa_6.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/soa_6.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_SOA_6_H
 #define GENERIC_SOA_6_H 1
=20
-/* $Id: soa_6.h,v 1.32 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: soa_6.h,v 1.32 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_soa {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/spf_99.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/spf_99.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/spf_99.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: spf_99.c,v 1.6 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: spf_99.c,v 1.6 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Thu Mar 16 15:40:00 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/spf_99.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/spf_99.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/spf_99.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_SPF_99_H
 #define GENERIC_SPF_99_H 1
=20
-/* $Id: spf_99.h,v 1.4 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: spf_99.h,v 1.4 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_spf_string {
                 isc_uint8_t    length;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/sshfp_44.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/sshfp_44.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/sshfp_44.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2006, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2006, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sshfp_44.c,v 1.9 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /* RFC 4255 */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/sshfp_44.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/sshfp_44.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/sshfp_44.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sshfp_44.h,v 1.8 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: sshfp_44.h,v 1.8 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC 4255 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/tkey_249.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/tkey_249.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/tkey_249.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2007, 2009  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2007, 2009, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tkey_249.c,v 1.59 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /*
  * Reviewed: Thu Mar 16 17:35:30 PST 2000 by halley.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/tkey_249.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/tkey_249.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/tkey_249.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_TKEY_249_H
 #define GENERIC_TKEY_249_H 1
=20
-/* $Id: tkey_249.h,v 1.24 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: tkey_249.h,v 1.24 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per draft-ietf-dnsind-tkey-00.txt */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/txt_16.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/txt_16.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/txt_16.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: txt_16.c,v 1.47 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: txt_16.c,v 1.47 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Thu Mar 16 15:40:00 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/txt_16.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/txt_16.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/txt_16.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_TXT_16_H
 #define GENERIC_TXT_16_H 1
=20
-/* $Id: txt_16.h,v 1.28 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: txt_16.h,v 1.28 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_txt_string {
                 isc_uint8_t    length;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/unspec_103.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/unspec_103.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/unspec_103.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: unspec_103.c,v 1.37 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: unspec_103.c,v 1.37 2009/12/04 22:06:37 tbox Exp $ */
=20
 #ifndef RDATA_GENERIC_UNSPEC_103_C
 #define RDATA_GENERIC_UNSPEC_103_C
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/unspec_103.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/unspec_103.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/unspec_103.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -19,7 +19,7 @@
 #ifndef GENERIC_UNSPEC_103_H
 #define GENERIC_UNSPEC_103_H 1
=20
-/* $Id: unspec_103.h,v 1.17 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: unspec_103.h,v 1.17 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_unspec_t {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/x25_19.c
--- a/head/contrib/bind9/lib/dns/rdata/generic/x25_19.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/x25_19.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: x25_19.c,v 1.41 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: x25_19.c,v 1.41 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Thu Mar 16 16:15:57 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/gener=
ic/x25_19.h
--- a/head/contrib/bind9/lib/dns/rdata/generic/x25_19.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/generic/x25_19.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef GENERIC_X25_19_H
 #define GENERIC_X25_19_H 1
=20
-/* $Id: x25_19.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: x25_19.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/hs_4/=
a_1.c
--- a/head/contrib/bind9/lib/dns/rdata/hs_4/a_1.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/rdata/hs_4/a_1.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: a_1.c,v 1.33 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: a_1.c,v 1.33 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* reviewed: Thu Mar 16 15:58:36 PST 2000 by brister */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/hs_4/=
a_1.h
--- a/head/contrib/bind9/lib/dns/rdata/hs_4/a_1.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/rdata/hs_4/a_1.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -19,7 +19,7 @@
 #ifndef HS_4_A_1_H
 #define HS_4_A_1_H 1
=20
-/* $Id: a_1.h,v 1.12 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a_1.h,v 1.12 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_hs_a {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
a6_38.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/a6_38.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/a6_38.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: a6_38.c,v 1.56 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: a6_38.c,v 1.56 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* RFC2874 */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
a6_38.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/a6_38.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/a6_38.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_A6_38_H
 #define IN_1_A6_38_H 1
=20
-/* $Id: a6_38.h,v 1.24 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a6_38.h,v 1.24 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC2874 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
a_1.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/a_1.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/a_1.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: a_1.c,v 1.55 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: a_1.c,v 1.55 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Thu Mar 16 16:52:50 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
a_1.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/a_1.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/a_1.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -19,7 +19,7 @@
 #ifndef IN_1_A_1_H
 #define IN_1_A_1_H 1
=20
-/* $Id: a_1.h,v 1.28 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a_1.h,v 1.28 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_in_a {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
aaaa_28.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/aaaa_28.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/aaaa_28.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: aaaa_28.c,v 1.47 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: aaaa_28.c,v 1.47 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Thu Mar 16 16:52:50 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
aaaa_28.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/aaaa_28.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/aaaa_28.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_AAAA_28_H
 #define IN_1_AAAA_28_H 1
=20
-/* $Id: aaaa_28.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: aaaa_28.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC1886 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
apl_42.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/apl_42.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/apl_42.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: apl_42.c,v 1.16 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: apl_42.c,v 1.16 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* RFC3123 */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
apl_42.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/apl_42.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/apl_42.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -19,7 +19,7 @@
 #ifndef IN_1_APL_42_H
 #define IN_1_APL_42_H 1
=20
-/* $Id: apl_42.h,v 1.6 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: apl_42.h,v 1.6 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_apl_ent {
 	isc_boolean_t	negative;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
dhcid_49.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/dhcid_49.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/dhcid_49.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006, 2007, 2009  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2006, 2007, 2009, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dhcid_49.c,v 1.7 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id$ */
=20
 /* RFC 4701 */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
dhcid_49.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/dhcid_49.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/dhcid_49.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_DHCID_49_H
 #define IN_1_DHCID_49_H 1
=20
-/* $Id: dhcid_49.h,v 1.5 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dhcid_49.h,v 1.5 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_in_dhcid {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
kx_36.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/kx_36.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/kx_36.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: kx_36.c,v 1.47 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: kx_36.c,v 1.47 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Thu Mar 16 17:24:54 PST 2000 by explorer */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
kx_36.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/kx_36.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/kx_36.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_KX_36_H
 #define IN_1_KX_36_H 1
=20
-/* $Id: kx_36.h,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: kx_36.h,v 1.20 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC2230 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
naptr_35.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/naptr_35.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/naptr_35.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: naptr_35.c,v 1.56 2009-12-04 21:09:34 marka Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Thu Mar 16 16:52:50 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
naptr_35.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/naptr_35.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/naptr_35.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -18,9 +18,9 @@
 #ifndef IN_1_NAPTR_35_H
 #define IN_1_NAPTR_35_H 1
=20
-/* $Id: naptr_35.h,v 1.23 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id$ */
=20
-/*!=20
+/*!
  *  \brief Per RFC2915 */
=20
 typedef struct dns_rdata_in_naptr {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
nsap-ptr_23.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/nsap-ptr_23.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/nsap-ptr_23.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsap-ptr_23.c,v 1.40 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: nsap-ptr_23.c,v 1.40 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Fri Mar 17 10:16:02 PST 2000 by gson */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
nsap-ptr_23.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/nsap-ptr_23.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/nsap-ptr_23.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_NSAP_PTR_23_H
 #define IN_1_NSAP_PTR_23_H 1
=20
-/* $Id: nsap-ptr_23.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: nsap-ptr_23.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC1348.  Obsoleted in RFC 1706 - use PTR instead. */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
nsap_22.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/nsap_22.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/nsap_22.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsap_22.c,v 1.44 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: nsap_22.c,v 1.44 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Fri Mar 17 10:41:07 PST 2000 by gson */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
nsap_22.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/nsap_22.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/nsap_22.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_NSAP_22_H
 #define IN_1_NSAP_22_H 1
=20
-/* $Id: nsap_22.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: nsap_22.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC1706 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
px_26.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/px_26.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/px_26.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: px_26.c,v 1.45 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: px_26.c,v 1.45 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Mon Mar 20 10:44:27 PST 2000 */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
px_26.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/px_26.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/px_26.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_PX_26_H
 #define IN_1_PX_26_H 1
=20
-/* $Id: px_26.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: px_26.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC2163 */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
srv_33.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/srv_33.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/srv_33.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: srv_33.c,v 1.47 2009-12-04 22:06:37 tbox Exp $ */
+/* $Id: srv_33.c,v 1.47 2009/12/04 22:06:37 tbox Exp $ */
=20
 /* Reviewed: Fri Mar 17 13:01:00 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
srv_33.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/srv_33.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/srv_33.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_SRV_33_H
 #define IN_1_SRV_33_H 1
=20
-/* $Id: srv_33.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: srv_33.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /* Reviewed: Fri Mar 17 13:01:00 PST 2000 by bwelling */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
wks_11.c
--- a/head/contrib/bind9/lib/dns/rdata/in_1/wks_11.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/wks_11.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2007, 2009  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2007, 2009, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: wks_11.c,v 1.57 2009-12-04 21:09:34 marka Exp $ */
+/* $Id$ */
=20
 /* Reviewed: Fri Mar 17 15:01:49 PST 2000 by explorer */
=20
@@ -27,16 +27,46 @@
=20
 #include <isc/net.h>
 #include <isc/netdb.h>
+#include <isc/once.h>
=20
 #define RRTYPE_WKS_ATTRIBUTES (0)
=20
+static isc_mutex_t wks_lock;
+
+static void init_lock(void) {
+	RUNTIME_CHECK(isc_mutex_init(&wks_lock) =3D=3D ISC_R_SUCCESS);
+}
+
+static isc_boolean_t
+mygetprotobyname(const char *name, long *proto) {
+	struct protoent *pe;
+
+	LOCK(&wks_lock);
+	pe =3D getprotobyname(name);
+	if (pe !=3D NULL)
+		*proto =3D pe->p_proto;
+	UNLOCK(&wks_lock);
+	return (ISC_TF(pe !=3D NULL));
+}
+
+static isc_boolean_t
+mygetservbyname(const char *name, const char *proto, long *port) {
+	struct servent *se;
+
+	LOCK(&wks_lock);
+	se =3D getservbyname(name, proto);
+	if (se !=3D NULL)
+		*port =3D ntohs(se->s_port);
+	UNLOCK(&wks_lock);
+	return (ISC_TF(se !=3D NULL));
+}
+
 static inline isc_result_t
 fromtext_in_wks(ARGS_FROMTEXT) {
+	static isc_once_t once =3D ISC_ONCE_INIT;
 	isc_token_t token;
 	isc_region_t region;
 	struct in_addr addr;
-	struct protoent *pe;
-	struct servent *se;
 	char *e;
 	long proto;
 	unsigned char bm[8*1024]; /* 64k bits */
@@ -55,6 +85,8 @@
 	UNUSED(options);
 	UNUSED(rdclass);
=20
+	RUNTIME_CHECK(isc_once_do(&once, init_lock) =3D=3D ISC_R_SUCCESS);
+
 	/*
 	 * IPv4 dotted quad.
 	 */
@@ -78,10 +110,9 @@
 	proto =3D strtol(DNS_AS_STR(token), &e, 10);
 	if (*e =3D=3D 0)
 		;
-	else if ((pe =3D getprotobyname(DNS_AS_STR(token))) !=3D NULL)
-		proto =3D pe->p_proto;
-	else
+	else if (!mygetprotobyname(DNS_AS_STR(token), &proto))
 		RETTOK(DNS_R_UNKNOWNPROTO);
+
 	if (proto < 0 || proto > 0xff)
 		RETTOK(ISC_R_RANGE);
=20
@@ -112,12 +143,8 @@
 		port =3D strtol(DNS_AS_STR(token), &e, 10);
 		if (*e =3D=3D 0)
 			;
-		else if ((se =3D getservbyname(service, ps)) !=3D NULL)
-			port =3D ntohs(se->s_port);
-		else if ((se =3D getservbyname(DNS_AS_STR(token), ps))
-			  !=3D NULL)
-			port =3D ntohs(se->s_port);
-		else
+		else if (!mygetservbyname(service, ps, &port) &&
+			 !mygetservbyname(DNS_AS_STR(token), ps, &port))
 			RETTOK(DNS_R_UNKNOWNSERVICE);
 		if (port < 0 || port > 0xffff)
 			RETTOK(ISC_R_RANGE);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/in_1/=
wks_11.h
--- a/head/contrib/bind9/lib/dns/rdata/in_1/wks_11.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/in_1/wks_11.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -18,7 +18,7 @@
 #ifndef IN_1_WKS_11_H
 #define IN_1_WKS_11_H 1
=20
-/* $Id: wks_11.h,v 1.22 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: wks_11.h,v 1.22 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef	struct dns_rdata_in_wks {
 	dns_rdatacommon_t	common;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/rdata=
structpre.h
--- a/head/contrib/bind9/lib/dns/rdata/rdatastructpre.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/rdatastructpre.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatastructpre.h,v 1.16 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rdatastructpre.h,v 1.16 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_RDATASTRUCT_H
 #define DNS_RDATASTRUCT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdata/rdata=
structsuf.h
--- a/head/contrib/bind9/lib/dns/rdata/rdatastructsuf.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdata/rdatastructsuf.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatastructsuf.h,v 1.10 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rdatastructsuf.h,v 1.10 2007/06/19 23:47:17 tbox Exp $ */
=20
 ISC_LANG_ENDDECLS
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdatalist.c
--- a/head/contrib/bind9/lib/dns/rdatalist.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdatalist.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2008, 2010, 2011  Internet Systems Cons=
ortium, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2008, 2010-2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatalist.c,v 1.40.40.2 2011-02-28 01:20:02 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdatalist_p=
.h
--- a/head/contrib/bind9/lib/dns/rdatalist_p.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/dns/rdatalist_p.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatalist_p.h,v 1.11 2008-09-25 04:02:38 tbox Exp $ */
+/* $Id: rdatalist_p.h,v 1.11 2008/09/25 04:02:38 tbox Exp $ */
=20
 #ifndef DNS_RDATALIST_P_H
 #define DNS_RDATALIST_P_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdataset.c
--- a/head/contrib/bind9/lib/dns/rdataset.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdataset.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdataset.c,v 1.86.148.4 2011-06-08 23:02:42 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -442,11 +442,11 @@
 			j =3D val % count;
 			for (i =3D 0; i < count; i++) {
 				if (order !=3D NULL)
-					sorted[j].key =3D (*order)(&shuffled[i],
+					sorted[i].key =3D (*order)(&shuffled[j],
 								 order_arg);
 				else
-					sorted[j].key =3D 0; /* Unused */
-				sorted[j].rdata =3D &shuffled[i];
+					sorted[i].key =3D 0; /* Unused */
+				sorted[i].rdata =3D &shuffled[j];
 				j++;
 				if (j =3D=3D count)
 					j =3D 0; /* Wrap around. */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdatasetite=
r.c
--- a/head/contrib/bind9/lib/dns/rdatasetiter.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/dns/rdatasetiter.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatasetiter.c,v 1.16 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: rdatasetiter.c,v 1.16 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rdataslab.c
--- a/head/contrib/bind9/lib/dns/rdataslab.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rdataslab.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdataslab.c,v 1.52.148.2 2011-02-28 01:20:02 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -53,6 +53,7 @@
  *	record count	(2 bytes)
  *	data records
  *		data length	(2 bytes)
+ *		meta data	(1 byte for RRSIG's)
  *		data		(data length bytes)
  *
  * Offsets are from the end of the header.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/request.c
--- a/head/contrib/bind9/lib/dns/request.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/request.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: request.c,v 1.87.148.2 2011-03-12 04:59:17 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -1133,9 +1133,7 @@
  */
 static void
 send_if_done(dns_request_t *request, isc_result_t result) {
-	if (!DNS_REQUEST_CONNECTING(request) &&
-	    !DNS_REQUEST_SENDING(request) &&
-	    !request->canceling)
+	if (request->event !=3D NULL && !request->canceling)
 		req_sendevent(request, result);
 }
=20
@@ -1319,8 +1317,8 @@
 		else
 			send_if_done(request, ISC_R_CANCELED);
 	} else if (sevent->result !=3D ISC_R_SUCCESS) {
-			req_cancel(request);
-			send_if_done(request, ISC_R_CANCELED);
+		req_cancel(request);
+		send_if_done(request, ISC_R_CANCELED);
 	}
 	UNLOCK(&request->requestmgr->locks[request->hash]);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/resolver.c
--- a/head/contrib/bind9/lib/dns/resolver.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/resolver.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: resolver.c,v 1.428.6.7 2011-06-08 23:02:43 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -216,6 +216,8 @@
 	ISC_LIST(dns_validator_t)       validators;
 	dns_db_t *			cache;
 	dns_adb_t *			adb;
+	isc_boolean_t			ns_ttl_ok;
+	isc_uint32_t			ns_ttl;
=20
 	/*%
 	 * The number of events we're waiting for.
@@ -453,7 +455,7 @@
 				      dns_rdataset_t *ardataset,
 				      isc_result_t *eresultp);
 static void validated(isc_task_t *task, isc_event_t *event);
-static void maybe_destroy(fetchctx_t *fctx);
+static isc_boolean_t maybe_destroy(fetchctx_t *fctx, isc_boolean_t locked);
 static void add_bad(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
 		    isc_result_t reason, badnstype_t badtype);
=20
@@ -746,8 +748,11 @@
 	INSIST(query->tcpsocket =3D=3D NULL);
=20
 	query->fctx->nqueries--;
-	if (SHUTTINGDOWN(query->fctx))
-		maybe_destroy(query->fctx);     /* Locks bucket. */
+	if (SHUTTINGDOWN(query->fctx)) {
+		dns_resolver_t *res =3D query->fctx->res;
+		if (maybe_destroy(query->fctx, ISC_FALSE))
+			empty_bucket(res);
+	}
 	query->magic =3D 0;
 	isc_mem_put(query->mctx, query, sizeof(*query));
 	*queryp =3D NULL;
@@ -1562,9 +1567,11 @@
 		dns_dispatch_detach(&query->dispatch);
=20
  cleanup_query:
-	query->magic =3D 0;
-	isc_mem_put(res->buckets[fctx->bucketnum].mctx,
-		    query, sizeof(*query));
+	if (query->connects =3D=3D 0) {
+		query->magic =3D 0;
+		isc_mem_put(res->buckets[fctx->bucketnum].mctx,
+			    query, sizeof(*query));
+	}
=20
  stop_idle_timer:
 	RUNTIME_CHECK(fctx_stopidletimer(fctx) =3D=3D ISC_R_SUCCESS);
@@ -1682,6 +1689,7 @@
 	dns_compress_t cctx;
 	isc_boolean_t cleanup_cctx =3D ISC_FALSE;
 	isc_boolean_t secure_domain;
+	isc_boolean_t connecting =3D ISC_FALSE;
=20
 	fctx =3D query->fctx;
 	QTRACE("send");
@@ -1972,6 +1980,7 @@
 						    query);
 			if (result !=3D ISC_R_SUCCESS)
 				goto cleanup_message;
+			connecting =3D ISC_TRUE;
 			query->connects++;
 		}
 	}
@@ -1983,8 +1992,19 @@
 	 */
 	result =3D isc_socket_sendto(socket, &r, task, resquery_senddone,
 				   query, address, NULL);
-	if (result !=3D ISC_R_SUCCESS)
+	if (result !=3D ISC_R_SUCCESS) {
+		if (connecting) {
+			/*
+			 * This query is still connecting.
+			 * Mark it as canceled so that it will just be
+			 * cleaned up when the connected event is received.
+			 * Keep fctx around until the event is processed.
+			 */
+			query->fctx->nqueries++;
+			query->attributes |=3D RESQUERY_ATTR_CANCELED;
+		}
 		goto cleanup_message;
+	}
=20
 	query->sends++;
=20
@@ -2146,6 +2166,7 @@
 	isc_boolean_t want_try =3D ISC_FALSE;
 	isc_boolean_t want_done =3D ISC_FALSE;
 	isc_boolean_t bucket_empty =3D ISC_FALSE;
+	isc_boolean_t destroy =3D ISC_FALSE;
 	unsigned int bucketnum;
=20
 	find =3D event->ev_sender;
@@ -2157,6 +2178,9 @@
=20
 	FCTXTRACE("finddone");
=20
+	bucketnum =3D fctx->bucketnum;
+	LOCK(&res->buckets[bucketnum].lock);
+
 	INSIST(fctx->pending > 0);
 	fctx->pending--;
=20
@@ -2181,17 +2205,17 @@
 		}
 	} else if (SHUTTINGDOWN(fctx) && fctx->pending =3D=3D 0 &&
 		   fctx->nqueries =3D=3D 0 && ISC_LIST_EMPTY(fctx->validators)) {
-		bucketnum =3D fctx->bucketnum;
-		LOCK(&res->buckets[bucketnum].lock);
 		/*
 		 * Note that we had to wait until we had the lock before
 		 * looking at fctx->references.
 		 */
 		if (fctx->references =3D=3D 0)
-			bucket_empty =3D fctx_destroy(fctx);
-		UNLOCK(&res->buckets[bucketnum].lock);
-	}
-
+			destroy =3D ISC_TRUE;
+	}
+	UNLOCK(&res->buckets[bucketnum].lock);
+
+	if (destroy)
+		bucket_empty =3D fctx_destroy(fctx);
 	isc_event_free(&event);
 	dns_adb_destroyfind(&find);
=20
@@ -3421,6 +3445,20 @@
 	return (ISC_R_SUCCESS);
 }
=20
+static inline void
+log_ns_ttl(fetchctx_t *fctx, const char *where) {
+	char namebuf[DNS_NAME_FORMATSIZE];
+	char domainbuf[DNS_NAME_FORMATSIZE];
+
+	dns_name_format(&fctx->name, namebuf, sizeof(namebuf));
+	dns_name_format(&fctx->domain, domainbuf, sizeof(domainbuf));
+	isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
+		      DNS_LOGMODULE_RESOLVER, ISC_LOG_DEBUG(10),
+		      "log_ns_ttl: fctx %p: %s: %s (in '%s'?): %u %u",
+		      fctx, where, namebuf, domainbuf,
+		      fctx->ns_ttl_ok, fctx->ns_ttl);
+}
+
 static isc_result_t
 fctx_create(dns_resolver_t *res, dns_name_t *name, dns_rdatatype_t type,
 	    dns_name_t *domain, dns_rdataset_t *nameservers,
@@ -3514,6 +3552,8 @@
 	fctx->timeout =3D ISC_FALSE;
 	fctx->addrinfo =3D NULL;
 	fctx->client =3D NULL;
+	fctx->ns_ttl =3D 0;
+	fctx->ns_ttl_ok =3D ISC_FALSE;
=20
 	dns_name_init(&fctx->nsname, NULL);
 	fctx->nsfetch =3D NULL;
@@ -3563,6 +3603,8 @@
 				dns_rdataset_disassociate(&fctx->nameservers);
 				goto cleanup_name;
 			}
+			fctx->ns_ttl =3D fctx->nameservers.ttl;
+			fctx->ns_ttl_ok =3D ISC_TRUE;
 		} else {
 			/*
 			 * We're in forward-only mode.  Set the query domain.
@@ -3580,7 +3622,11 @@
 		if (result !=3D ISC_R_SUCCESS)
 			goto cleanup_name;
 		dns_rdataset_clone(nameservers, &fctx->nameservers);
-	}
+		fctx->ns_ttl =3D fctx->nameservers.ttl;
+		fctx->ns_ttl_ok =3D ISC_TRUE;
+	}
+
+	log_ns_ttl(fctx, "fctx_create");
=20
 	INSIST(dns_name_issubdomain(&fctx->name, &fctx->domain));
=20
@@ -3874,14 +3920,16 @@
=20
 /*
  * Destroy '*fctx' if it is ready to be destroyed (i.e., if it has
- * no references and is no longer waiting for any events).  If this
- * was the last fctx in the resolver, destroy the resolver.
+ * no references and is no longer waiting for any events).
  *
  * Requires:
  *      '*fctx' is shutting down.
+ *
+ * Returns:
+ *	true if the resolver is exiting and this is the last fctx in the bucket.
  */
-static void
-maybe_destroy(fetchctx_t *fctx) {
+static isc_boolean_t
+maybe_destroy(fetchctx_t *fctx, isc_boolean_t locked) {
 	unsigned int bucketnum;
 	isc_boolean_t bucket_empty =3D ISC_FALSE;
 	dns_resolver_t *res =3D fctx->res;
@@ -3889,8 +3937,11 @@
=20
 	REQUIRE(SHUTTINGDOWN(fctx));
=20
+	bucketnum =3D fctx->bucketnum;
+	if (!locked)
+		LOCK(&res->buckets[bucketnum].lock);
 	if (fctx->pending !=3D 0 || fctx->nqueries !=3D 0)
-		return;
+		goto unlock;
=20
 	for (validator =3D ISC_LIST_HEAD(fctx->validators);
 	     validator !=3D NULL; validator =3D next_validator) {
@@ -3898,14 +3949,12 @@
 		dns_validator_cancel(validator);
 	}
=20
-	bucketnum =3D fctx->bucketnum;
-	LOCK(&res->buckets[bucketnum].lock);
 	if (fctx->references =3D=3D 0 && ISC_LIST_EMPTY(fctx->validators))
 		bucket_empty =3D fctx_destroy(fctx);
-	UNLOCK(&res->buckets[bucketnum].lock);
-
-	if (bucket_empty)
-		empty_bucket(res);
+ unlock:
+	if (!locked)
+		UNLOCK(&res->buckets[bucketnum].lock);
+	return (bucket_empty);
 }
=20
 /*
@@ -3913,31 +3962,33 @@
  */
 static void
 validated(isc_task_t *task, isc_event_t *event) {
-	isc_result_t result =3D ISC_R_SUCCESS;
-	isc_result_t eresult =3D ISC_R_SUCCESS;
-	isc_stdtime_t now;
-	fetchctx_t *fctx;
-	dns_validatorevent_t *vevent;
+	dns_adbaddrinfo_t *addrinfo;
+	dns_dbnode_t *node =3D NULL;
+	dns_dbnode_t *nsnode =3D NULL;
 	dns_fetchevent_t *hevent;
+	dns_name_t *name;
 	dns_rdataset_t *ardataset =3D NULL;
 	dns_rdataset_t *asigrdataset =3D NULL;
-	dns_dbnode_t *node =3D NULL;
-	isc_boolean_t negative;
-	isc_boolean_t chaining;
-	isc_boolean_t sentresponse;
-	isc_uint32_t ttl;
-	dns_dbnode_t *nsnode =3D NULL;
-	dns_name_t *name;
 	dns_rdataset_t *rdataset;
 	dns_rdataset_t *sigrdataset;
+	dns_resolver_t *res;
 	dns_valarg_t *valarg;
-	dns_adbaddrinfo_t *addrinfo;
+	dns_validatorevent_t *vevent;
+	fetchctx_t *fctx;
+	isc_boolean_t chaining;
+	isc_boolean_t negative;
+	isc_boolean_t sentresponse;
+	isc_result_t eresult =3D ISC_R_SUCCESS;
+	isc_result_t result =3D ISC_R_SUCCESS;
+	isc_stdtime_t now;
+	isc_uint32_t ttl;
=20
 	UNUSED(task); /* for now */
=20
 	REQUIRE(event->ev_type =3D=3D DNS_EVENT_VALIDATORDONE);
 	valarg =3D event->ev_arg;
 	fctx =3D valarg->fctx;
+	res =3D fctx->res;
 	addrinfo =3D valarg->addrinfo;
 	REQUIRE(VALID_FCTX(fctx));
 	REQUIRE(!ISC_LIST_EMPTY(fctx->validators));
@@ -3947,6 +3998,8 @@
=20
 	FCTXTRACE("received validation completion event");
=20
+	LOCK(&res->buckets[fctx->bucketnum].lock);
+
 	ISC_LIST_UNLINK(fctx->validators, vevent->validator, link);
 	fctx->validator =3D NULL;
=20
@@ -3955,7 +4008,7 @@
 	 * destroy the fctx if necessary.
 	 */
 	dns_validator_destroy(&vevent->validator);
-	isc_mem_put(fctx->res->buckets[fctx->bucketnum].mctx,
+	isc_mem_put(res->buckets[fctx->bucketnum].mctx,
 		    valarg, sizeof(*valarg));
=20
 	negative =3D ISC_TF(vevent->rdataset =3D=3D NULL);
@@ -3968,12 +4021,15 @@
 	 * so, destroy the fctx.
 	 */
 	if (SHUTTINGDOWN(fctx) && !sentresponse) {
-		maybe_destroy(fctx);    /* Locks bucket. */
+		isc_uint32_t bucketnum =3D fctx->bucketnum;
+		isc_boolean_t bucket_empty;
+		bucket_empty =3D maybe_destroy(fctx, ISC_TRUE);
+		UNLOCK(&res->buckets[bucketnum].lock);
+		if (bucket_empty)
+			empty_bucket(res);
 		goto cleanup_event;
 	}
=20
-	LOCK(&fctx->res->buckets[fctx->bucketnum].lock);
-
 	isc_stdtime_get(&now);
=20
 	/*
@@ -4019,7 +4075,7 @@
=20
 	if (vevent->result !=3D ISC_R_SUCCESS) {
 		FCTXTRACE("validation failed");
-		inc_stats(fctx->res, dns_resstatscounter_valfail);
+		inc_stats(res, dns_resstatscounter_valfail);
 		fctx->valfail++;
 		fctx->vresult =3D vevent->result;
 		if (fctx->vresult !=3D DNS_R_BROKENCHAIN) {
@@ -4068,7 +4124,7 @@
 		result =3D fctx->vresult;
 		add_bad(fctx, addrinfo, result, badns_validation);
 		isc_event_free(&event);
-		UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
+		UNLOCK(&res->buckets[fctx->bucketnum].lock);
 		INSIST(fctx->validator =3D=3D NULL);
 		fctx->validator =3D ISC_LIST_HEAD(fctx->validators);
 		if (fctx->validator !=3D NULL)
@@ -4087,8 +4143,7 @@
 			     fctx->type =3D=3D dns_rdatatype_dlv ||
 			     fctx->type =3D=3D dns_rdatatype_ds) &&
 			     tresult =3D=3D ISC_R_SUCCESS)
-				dns_resolver_addbadcache(fctx->res,
-							 &fctx->name,
+				dns_resolver_addbadcache(res, &fctx->name,
 							 fctx->type, &expire);
 			fctx_done(fctx, result, __LINE__); /* Locks bucket. */
 		} else
@@ -4101,7 +4156,7 @@
 		dns_rdatatype_t covers;
 		FCTXTRACE("nonexistence validation OK");
=20
-		inc_stats(fctx->res, dns_resstatscounter_valnegsuccess);
+		inc_stats(res, dns_resstatscounter_valnegsuccess);
=20
 		if (fctx->rmessage->rcode =3D=3D dns_rcode_nxdomain)
 			covers =3D dns_rdatatype_any;
@@ -4118,10 +4173,9 @@
 		 * to zero to facilitate locating the containing zone of
 		 * a arbitrary zone.
 		 */
-		ttl =3D fctx->res->view->maxncachettl;
+		ttl =3D res->view->maxncachettl;
 		if (fctx->type =3D=3D dns_rdatatype_soa &&
-		    covers =3D=3D dns_rdatatype_any &&
-		    fctx->res->zero_no_soa_ttl)
+		    covers =3D=3D dns_rdatatype_any && res->zero_no_soa_ttl)
 			ttl =3D 0;
=20
 		result =3D ncache_adderesult(fctx->rmessage, fctx->cache, node,
@@ -4131,7 +4185,7 @@
 			goto noanswer_response;
 		goto answer_response;
 	} else
-		inc_stats(fctx->res, dns_resstatscounter_valsuccess);
+		inc_stats(res, dns_resstatscounter_valsuccess);
=20
 	FCTXTRACE("validation OK");
=20
@@ -4179,14 +4233,17 @@
 	}
=20
 	if (sentresponse) {
+		isc_boolean_t bucket_empty =3D ISC_FALSE;
 		/*
 		 * If we only deferred the destroy because we wanted to cache
 		 * the data, destroy now.
 		 */
 		dns_db_detachnode(fctx->cache, &node);
-		UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
 		if (SHUTTINGDOWN(fctx))
-			maybe_destroy(fctx);    /* Locks bucket. */
+			bucket_empty =3D maybe_destroy(fctx, ISC_TRUE);
+		UNLOCK(&res->buckets[fctx->bucketnum].lock);
+		if (bucket_empty)
+			empty_bucket(res);
 		goto cleanup_event;
 	}
=20
@@ -4201,7 +4258,7 @@
 		 * be validated.
 		 */
 		dns_db_detachnode(fctx->cache, &node);
-		UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
+		UNLOCK(&res->buckets[fctx->bucketnum].lock);
 		dns_validator_send(ISC_LIST_HEAD(fctx->validators));
 		goto cleanup_event;
 	}
@@ -4276,8 +4333,7 @@
 	if (node !=3D NULL)
 		dns_db_detachnode(fctx->cache, &node);
=20
-	UNLOCK(&fctx->res->buckets[fctx->bucketnum].lock);
-
+	UNLOCK(&res->buckets[fctx->bucketnum].lock);
 	fctx_done(fctx, result, __LINE__); /* Locks bucket. */
=20
  cleanup_event:
@@ -5248,6 +5304,26 @@
 	return (ISC_TRUE);
 }
=20
+static void
+trim_ns_ttl(fetchctx_t *fctx, dns_name_t *name, dns_rdataset_t *rdataset) {
+	char ns_namebuf[DNS_NAME_FORMATSIZE];
+	char namebuf[DNS_NAME_FORMATSIZE];
+	char tbuf[DNS_RDATATYPE_FORMATSIZE];
+
+	if (fctx->ns_ttl_ok && rdataset->ttl > fctx->ns_ttl) {
+		dns_name_format(name, ns_namebuf, sizeof(ns_namebuf));
+		dns_name_format(&fctx->name, namebuf, sizeof(namebuf));
+		dns_rdatatype_format(fctx->type, tbuf, sizeof(tbuf));
+
+		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
+			      DNS_LOGMODULE_RESOLVER, ISC_LOG_DEBUG(10),
+			      "fctx %p: trimming ttl of %s/NS for %s/%s: "
+			      "%u -> %u", fctx, ns_namebuf, namebuf, tbuf,
+			      rdataset->ttl, fctx->ns_ttl);
+		rdataset->ttl =3D fctx->ns_ttl;
+	}
+}
+
 /*
  * Handle a no-answer response (NXDOMAIN, NXRRSET, or referral).
  * If look_in_options has LOOK_FOR_NS_IN_ANSWER then we look in the answer
@@ -5418,6 +5494,9 @@
 					if (aa)
 						rdataset->trust =3D
 						    dns_trust_authauthority;
+					else if (ISFORWARDER(fctx->addrinfo))
+						rdataset->trust =3D
+							dns_trust_answer;
 					else
 						rdataset->trust =3D
 							dns_trust_additional;
@@ -5431,6 +5510,12 @@
 			return (result);
 	}
=20
+	log_ns_ttl(fctx, "noanswer_response");
+
+	if (ns_rdataset !=3D NULL && dns_name_equal(&fctx->domain, ns_name) &&
+	    !dns_name_equal(ns_name, dns_rootname))
+		trim_ns_ttl(fctx, ns_name, ns_rdataset);
+
 	/*
 	 * A negative response has a SOA record (Type 2)
 	 * and a optional NS RRset (Type 1) or it has neither
@@ -5471,6 +5556,9 @@
 					if (aa)
 						rdataset->trust =3D
 						    dns_trust_authauthority;
+					else if (ISFORWARDER(fctx->addrinfo))
+						rdataset->trust =3D
+							dns_trust_answer;
 					else
 						rdataset->trust =3D
 							dns_trust_additional;
@@ -5512,6 +5600,9 @@
 					if (aa)
 						rdataset->trust =3D
 						    dns_trust_authauthority;
+					else if (ISFORWARDER(fctx->addrinfo))
+						rdataset->trust =3D
+							dns_trust_answer;
 					else
 						rdataset->trust =3D
 							dns_trust_additional;
@@ -5643,6 +5734,8 @@
 		if (result !=3D ISC_R_SUCCESS)
 			return (result);
 		fctx->attributes |=3D FCTX_ATTR_WANTCACHE;
+		fctx->ns_ttl_ok =3D ISC_FALSE;
+		log_ns_ttl(fctx, "DELEGATION");
 		return (DNS_R_DELEGATION);
 	}
=20
@@ -5663,8 +5756,8 @@
 answer_response(fetchctx_t *fctx) {
 	isc_result_t result;
 	dns_message_t *message;
-	dns_name_t *name, *qname, tname;
-	dns_rdataset_t *rdataset;
+	dns_name_t *name, *qname, tname, *ns_name;
+	dns_rdataset_t *rdataset, *ns_rdataset;
 	isc_boolean_t done, external, chaining, aa, found, want_chaining;
 	isc_boolean_t have_answer, found_cname, found_type, wanted_chaining;
 	unsigned int aflag;
@@ -6064,6 +6157,8 @@
 	 * in this section, and we expect that it is not external.
 	 */
 	done =3D ISC_FALSE;
+	ns_name =3D NULL;
+	ns_rdataset =3D NULL;
 	result =3D dns_message_firstname(message, DNS_SECTION_AUTHORITY);
 	while (!done && result =3D=3D ISC_R_SUCCESS) {
 		name =3D NULL;
@@ -6091,6 +6186,10 @@
 						rdataset->trust =3D
 						    dns_trust_additional;
=20
+					if (rdataset->type =3D=3D dns_rdatatype_ns) {
+						ns_name =3D name;
+						ns_rdataset =3D rdataset;
+					}
 					/*
 					 * Mark any additional data related
 					 * to this rdataset.
@@ -6108,6 +6207,12 @@
 	if (result =3D=3D ISC_R_NOMORE)
 		result =3D ISC_R_SUCCESS;
=20
+	log_ns_ttl(fctx, "answer_response");
+
+	if (ns_rdataset !=3D NULL && dns_name_equal(&fctx->domain, ns_name) &&
+	    !dns_name_equal(ns_name, dns_rootname))
+		trim_ns_ttl(fctx, ns_name, ns_rdataset);
+
 	return (result);
 }
=20
@@ -6179,6 +6284,9 @@
 		if (dns_rdataset_isassociated(&fctx->nameservers))
 			dns_rdataset_disassociate(&fctx->nameservers);
 		dns_rdataset_clone(fevent->rdataset, &fctx->nameservers);
+		fctx->ns_ttl =3D fctx->nameservers.ttl;
+		fctx->ns_ttl_ok =3D ISC_TRUE;
+		log_ns_ttl(fctx, "resume_dslookup");
 		dns_name_free(&fctx->domain,
 			      fctx->res->buckets[bucketnum].mctx);
 		dns_name_init(&fctx->domain, NULL);
@@ -7112,6 +7220,8 @@
 				fctx_done(fctx, DNS_R_SERVFAIL, __LINE__);
 				return;
 			}
+			fctx->ns_ttl =3D fctx->nameservers.ttl;
+			fctx->ns_ttl_ok =3D ISC_TRUE;
 			fctx_cancelqueries(fctx, ISC_TRUE);
 			fctx_cleanupfinds(fctx);
 			fctx_cleanupaltfinds(fctx);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/result.c
--- a/head/contrib/bind9/lib/dns/result.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/result.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004, 2005, 2007-2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.c,v 1.132 2011-01-11 23:47:13 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rootns.c
--- a/head/contrib/bind9/lib/dns/rootns.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rootns.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rootns.c,v 1.40 2010-06-18 05:36:24 marka Exp $ */
+/* $Id: rootns.c,v 1.40 2010/06/18 05:36:24 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rpz.c
--- a/head/contrib/bind9/lib/dns/rpz.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rpz.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rpz.c,v 1.7 2011-01-17 04:27:23 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -116,20 +116,17 @@
=20
 struct dns_rpz_cidr {
 	isc_mem_t		*mctx;
-	isc_boolean_t		had_nsdname;
+	isc_boolean_t		have_nsdname;	/* zone has NSDNAME record */
 	dns_rpz_cidr_node_t	*root;
-	dns_name_t		ip_name;        /* RPZ_IP_ZONE.LOCALHOST. */
+	dns_name_t		ip_name;	/* RPZ_IP_ZONE.LOCALHOST. */
 	dns_name_t		nsip_name;      /* RPZ_NSIP_ZONE.LOCALHOST. */
 	dns_name_t		nsdname_name;	/* RPZ_NSDNAME_ZONE.LOCALHOST */
 };
=20
-
 static isc_boolean_t		have_rpz_zones =3D ISC_FALSE;
=20
-
 const char *
-dns_rpz_type2str(dns_rpz_type_t type)
-{
+dns_rpz_type2str(dns_rpz_type_t type) {
 	switch (type) {
 	case DNS_RPZ_TYPE_QNAME:
 		return ("QNAME");
@@ -143,31 +140,61 @@
 		break;
 	}
 	FATAL_ERROR(__FILE__, __LINE__,
-		    "impossible response policy zone type %d", type);
+		    "impossible rpz type %d", type);
 	return ("impossible");
 }
=20
-
-
 dns_rpz_policy_t
-dns_rpz_str2policy(const char *str)
-{
+dns_rpz_str2policy(const char *str) {
 	if (str =3D=3D NULL)
 		return (DNS_RPZ_POLICY_ERROR);
 	if (!strcasecmp(str, "given"))
 		return (DNS_RPZ_POLICY_GIVEN);
-	if (!strcasecmp(str, "no-op"))
-		return (DNS_RPZ_POLICY_NO_OP);
+	if (!strcasecmp(str, "disabled"))
+		return (DNS_RPZ_POLICY_DISABLED);
+	if (!strcasecmp(str, "passthru"))
+		return (DNS_RPZ_POLICY_PASSTHRU);
 	if (!strcasecmp(str, "nxdomain"))
 		return (DNS_RPZ_POLICY_NXDOMAIN);
 	if (!strcasecmp(str, "nodata"))
 		return (DNS_RPZ_POLICY_NODATA);
 	if (!strcasecmp(str, "cname"))
 		return (DNS_RPZ_POLICY_CNAME);
+	/*
+	 * Obsolete
+	 */
+	if (!strcasecmp(str, "no-op"))
+		return (DNS_RPZ_POLICY_PASSTHRU);
 	return (DNS_RPZ_POLICY_ERROR);
 }
=20
+const char *
+dns_rpz_policy2str(dns_rpz_policy_t policy) {
+	const char *str;
=20
+	switch (policy) {
+	case DNS_RPZ_POLICY_PASSTHRU:
+		str =3D "PASSTHRU";
+		break;
+	case DNS_RPZ_POLICY_NXDOMAIN:
+		str =3D "NXDOMAIN";
+		break;
+	case DNS_RPZ_POLICY_NODATA:
+		str =3D "NODATA";
+		break;
+	case DNS_RPZ_POLICY_RECORD:
+		str =3D "records";
+		break;
+	case DNS_RPZ_POLICY_CNAME:
+	case DNS_RPZ_POLICY_WILDCNAME:
+		str =3D "CNAME";
+		break;
+	default:
+		str =3D "";
+		INSIST(0);
+	}
+	return (str);
+}
=20
 /*
  * Free the radix tree of a response policy database.
@@ -214,8 +241,6 @@
 	*cidrp =3D NULL;
 }
=20
-
-
 /*
  * Forget a view's list of policy zones.
  */
@@ -244,20 +269,15 @@
  * zone is in at least one view's list of policy zones.
  */
 void
-dns_rpz_set_need(isc_boolean_t need)
-{
+dns_rpz_set_need(isc_boolean_t need) {
 	have_rpz_zones =3D need;
 }
=20
-
 isc_boolean_t
-dns_rpz_needed(void)
-{
+dns_rpz_needed(void) {
 	return (have_rpz_zones);
 }
=20
-
-
 /*
  * Start a new radix tree for a response policy zone.
  */
@@ -313,12 +333,13 @@
 	return (ISC_R_SUCCESS);
 }
=20
-
 /*
  * See if a policy zone has IP, NSIP, or NSDNAME rules or records.
  */
 void
 dns_rpz_enabled(dns_rpz_cidr_t *cidr, dns_rpz_st_t *st) {
+	if (cidr =3D=3D NULL)
+		return;
 	if (cidr->root !=3D NULL &&
 	    (cidr->root->flags & DNS_RPZ_CIDR_FG_IP) !=3D 0)
 		st->state |=3D DNS_RPZ_HAVE_IP;
@@ -328,8 +349,8 @@
 	if (cidr->root !=3D NULL &&
 	    (cidr->root->flags & DNS_RPZ_CIDR_FG_NSIPv6) !=3D 0)
 		st->state |=3D DNS_RPZ_HAVE_NSIPv6;
-	if (cidr->had_nsdname)
-		st->state |=3D DNS_RPZ_HAD_NSDNAME;
+	if (cidr->have_nsdname)
+		st->state |=3D DNS_RPZ_HAVE_NSDNAME;
 }
=20
 static inline dns_rpz_cidr_flags_t
@@ -350,8 +371,6 @@
 	}
 }
=20
-
-
 /*
  * Mark a node as having IP or NSIP data and all of its parents
  * as members of the IP or NSIP tree.
@@ -371,8 +390,6 @@
 	}
 }
=20
-
-
 /*
  * Make a radix tree node.
  */
@@ -409,24 +426,18 @@
 	return (node);
 }
=20
-
-
 static void
-badname(int level, dns_name_t *name, const char *comment)
-{
+badname(int level, dns_name_t *name, const char *comment) {
 	char printname[DNS_NAME_FORMATSIZE];
=20
 	if (isc_log_wouldlog(dns_lctx, level)) {
 		dns_name_format(name, printname, sizeof(printname));
-		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
+		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
 			      DNS_LOGMODULE_RBTDB, level,
-			      "invalid response policy name \"%s\"%s",
-			      printname, comment);
+			      "invalid rpz \"%s\"%s", printname, comment);
 	}
 }
=20
-
-
 /*
  * Convert an IP address from radix tree binary (host byte order) to
  * to its canonical response policy domain name and its name in the
@@ -520,8 +531,6 @@
 	return (ISC_R_SUCCESS);
 }
=20
-
-
 /*
  * Decide which kind of IP address response policy zone a name is in.
  */
@@ -548,8 +557,6 @@
 	return (DNS_RPZ_TYPE_QNAME);
 }
=20
-
-
 /*
  * Convert an IP address from canonical response policy domain name form
  * to radix tree binary (host byte order).
@@ -695,26 +702,37 @@
 	return (ISC_R_SUCCESS);
 }
=20
-
-
 /*
- * find first differing bit
+ * Find first differing bit.
  */
 static int
 ffbit(dns_rpz_cidr_word_t w) {
 	int bit;
=20
-	if (w =3D=3D 0)
-		return (DNS_RPZ_CIDR_WORD_BITS);
-	for (bit =3D 0; (w & (1U << (DNS_RPZ_CIDR_WORD_BITS-1))) =3D=3D 0; bit++)
-		w <<=3D 1;
+	bit =3D DNS_RPZ_CIDR_WORD_BITS-1;
+	if ((w & 0xffff0000) !=3D 0) {
+		w >>=3D 16;
+		bit -=3D 16;
+	}
+	if ((w & 0xff00) !=3D 0) {
+		w >>=3D 8;
+		bit -=3D 8;
+	}
+	if ((w & 0xf0) !=3D 0) {
+		w >>=3D 4;
+		bit -=3D 4;
+	}
+	if ((w & 0xc) !=3D 0) {
+		w >>=3D 2;
+		bit -=3D 2;
+	}
+	if ((w & 2) !=3D 0)
+		--bit;
 	return (bit);
 }
=20
-
-
 /*
- * find the first differing bit in two keys
+ * Find the first differing bit in two keys.
  */
 static int
 diff_keys(const dns_rpz_cidr_key_t *key1, dns_rpz_cidr_bits_t bits1,
@@ -741,14 +759,12 @@
 	return (ISC_MIN(bit, maxbit));
 }
=20
-
-
 /*
  * Search a radix tree for an IP address for ordinary lookup
  *	or for a CIDR block adding or deleting an entry
  * The tree read (for simple search) or write lock must be held by the cal=
ler.
  *
- * return ISC_R_SUCCESS, ISC_R_NOTFOUND, DNS_R_PARTIALMATCH, ISC_R_EXISTS,
+ * Return ISC_R_SUCCESS, ISC_R_NOTFOUND, DNS_R_PARTIALMATCH, ISC_R_EXISTS,
  *	ISC_R_NOMEMORY
  */
 static isc_result_t
@@ -912,15 +928,12 @@
 	}
 }
=20
-
-
 /*
  * Add an IP address to the radix tree of a response policy database.
  *	The tree write lock must be held by the caller.
  */
 void
-dns_rpz_cidr_addip(dns_rpz_cidr_t *cidr, dns_name_t *name)
-{
+dns_rpz_cidr_addip(dns_rpz_cidr_t *cidr, dns_name_t *name) {
 	dns_rpz_cidr_key_t tgt_ip;
 	dns_rpz_cidr_bits_t tgt_prefix;
 	dns_rpz_type_t type;
@@ -929,7 +942,7 @@
 		return;
=20
 	/*
-	 * no worries if the new name is not an IP address
+	 * No worries if the new name is not an IP address.
 	 */
 	type =3D set_type(cidr, name);
 	switch (type) {
@@ -937,7 +950,7 @@
 	case DNS_RPZ_TYPE_NSIP:
 		break;
 	case DNS_RPZ_TYPE_NSDNAME:
-		cidr->had_nsdname =3D ISC_TRUE;
+		cidr->have_nsdname =3D ISC_TRUE;
 		return;
 	case DNS_RPZ_TYPE_QNAME:
 	case DNS_RPZ_TYPE_BAD:
@@ -953,15 +966,12 @@
 		char printname[DNS_NAME_FORMATSIZE];
=20
 		dns_name_format(name, printname, sizeof(printname));
-		isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
+		isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
 			      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
-			      "duplicate response policy name \"%s\"",
-			      printname);
+			      "duplicate rpz name \"%s\"", printname);
 	}
 }
=20
-
-
 /*
  * Delete an IP address from the radix tree of a response policy database.
  *	The tree write lock must be held by the caller.
@@ -1000,7 +1010,7 @@
 	/*
 	 * Do not get excited about the deletion of interior rbt nodes.
 	 */
-	if (ISC_R_SUCCESS !=3D name2ipkey(cidr, DNS_RPZ_DEBUG_LEVEL2, name,
+	if (ISC_R_SUCCESS !=3D name2ipkey(cidr, DNS_RPZ_DEBUG_LEVEL3, name,
 					type, &tgt_ip, &tgt_prefix))
 		return;
 	if (ISC_R_SUCCESS !=3D search(cidr, &tgt_ip, tgt_prefix, type,
@@ -1009,10 +1019,9 @@
 			char printname[DNS_NAME_FORMATSIZE];
=20
 			dns_name_format(name, printname, sizeof(printname));
-			isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE,
+			isc_log_write(dns_lctx, DNS_LOGCATEGORY_RPZ,
 				      DNS_LOGMODULE_RBTDB, DNS_RPZ_ERROR_LEVEL,
-				      "missing response policy node \"%s\"",
-				      printname);
+				      "missing rpz node \"%s\"", printname);
 		}
 		return;
 	}
@@ -1073,8 +1082,6 @@
 	} while (tgt !=3D NULL);
 }
=20
-
-
 /*
  * Caller must hold tree lock.
  * Return  ISC_R_NOTFOUND
@@ -1124,8 +1131,6 @@
 			canon_name, search_name));
 }
=20
-
-
 /*
  * Translate CNAME rdata to a QNAME response policy action.
  */
@@ -1148,21 +1153,31 @@
 	if (dns_name_equal(&cname.cname, dns_rootname))
 		return (DNS_RPZ_POLICY_NXDOMAIN);
=20
-	/*
-	 * CNAME *. means NODATA
-	 */
-	if (dns_name_countlabels(&cname.cname) =3D=3D 2
-	    && dns_name_iswildcard(&cname.cname))
-		return (DNS_RPZ_POLICY_NODATA);
+	if (dns_name_iswildcard(&cname.cname)) {
+		/*
+		 * CNAME *. means NODATA
+		 */
+		if (dns_name_countlabels(&cname.cname) =3D=3D 2)
+			return (DNS_RPZ_POLICY_NODATA);
+
+		/*
+		 * A qname of www.evil.com and a policy of
+		 *	*.evil.com    CNAME   *.garden.net
+		 * gives a result of
+		 *	evil.com    CNAME   evil.com.garden.net
+		 */
+		if (dns_name_countlabels(&cname.cname) > 2)
+			return (DNS_RPZ_POLICY_WILDCNAME);
+	}
=20
 	/*
 	 * 128.1.0.127.rpz-ip CNAME  128.1.0.0.127. means "do not rewrite"
 	 */
 	if (selfname !=3D NULL && dns_name_equal(&cname.cname, selfname))
-		return (DNS_RPZ_POLICY_NO_OP);
+		return (DNS_RPZ_POLICY_PASSTHRU);
=20
 	/*
-	 * evil.com CNAME garden.net rewrites www.evil.com to www.garden.net.
+	 * Any other rdata gives a response consisting of the rdata.
 	 */
 	return (DNS_RPZ_POLICY_RECORD);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/rriterator.c
--- a/head/contrib/bind9/lib/dns/rriterator.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/rriterator.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC=
")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rriterator.c,v 1.2 2009-06-30 02:52:32 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -187,6 +187,8 @@
 	REQUIRE(name !=3D NULL && *name =3D=3D NULL);
 	REQUIRE(VALID_RRITERATOR(it));
 	REQUIRE(it->result =3D=3D ISC_R_SUCCESS);
+	REQUIRE(rdataset =3D=3D NULL || *rdataset =3D=3D NULL);
+	REQUIRE(rdata =3D=3D NULL || *rdata =3D=3D NULL);
=20
 	*name =3D dns_fixedname_name(&it->fixedname);
 	*ttl =3D it->rdataset.ttl;
@@ -194,9 +196,9 @@
 	dns_rdata_reset(&it->rdata);
 	dns_rdataset_current(&it->rdataset, &it->rdata);
=20
-	if (rdataset)
+	if (rdataset !=3D NULL)
 		*rdataset =3D &it->rdataset;
=20
-	if (rdata)
+	if (rdata !=3D NULL)
 		*rdata =3D &it->rdata;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/sdb.c
--- a/head/contrib/bind9/lib/dns/sdb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/sdb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sdb.c,v 1.76.8.1 2011-03-14 13:40:14 fdupont Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/sdlz.c
--- a/head/contrib/bind9/lib/dns/sdlz.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/sdlz.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2005-2011  Internet Systems Consortium, Inc. ("I=
SC")
+ * Portions Copyright (C) 2005-2012  Internet Systems Consortium, Inc. ("I=
SC")
  * Portions Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -50,7 +50,7 @@
  * USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sdlz.c,v 1.31.8.2 2011-03-21 19:53:34 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -1836,7 +1836,11 @@
 					    &lookup->callbacks);
 		if (result !=3D ISC_R_SUCCESS)
 			isc_buffer_free(&rdatabuf);
+		if (size >=3D 65535)
+			break;
 		size *=3D 2;
+		if (size >=3D 65535)
+			size =3D 65535;
 	} while (result =3D=3D ISC_R_NOSPACE);
=20
 	if (result !=3D ISC_R_SUCCESS)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/soa.c
--- a/head/contrib/bind9/lib/dns/soa.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/soa.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: soa.c,v 1.12 2009-09-10 02:18:40 each Exp $ */
+/* $Id: soa.c,v 1.12 2009/09/10 02:18:40 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/spnego.asn1
--- a/head/contrib/bind9/lib/dns/spnego.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/spnego.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -4,7 +4,7 @@
=20
 -- (The above copyright notice is per RFC 3978 5.6 (a), q.v.)
=20
--- $Id: spnego.asn1,v 1.2 2006-12-04 01:52:46 marka Exp $
+-- $Id: spnego.asn1,v 1.2 2006/12/04 01:52:46 marka Exp $
=20
 -- This is the SPNEGO ASN.1 module from RFC 4178, tweaked
 -- to get the Heimdal ASN.1 compiler to accept it.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/spnego.c
--- a/head/contrib/bind9/lib/dns/spnego.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/spnego.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2006-2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: spnego.c,v 1.16.10.2 2011-04-04 11:10:57 marka Exp $ */
+/* $Id$ */
=20
 /*! \file
  * \brief
@@ -948,8 +948,9 @@
 	e =3D der_get_length(p, len, length_ret, &l);
 	if (e)
 		return (e);
-	p +=3D l;
+	/* p +=3D l; */
 	len -=3D l;
+	POST(len);
 	ret +=3D l;
 	if (size)
 		*size =3D ret;
@@ -980,6 +981,7 @@
 		return (e);
 	p +=3D l;
 	len -=3D l;
+	POST(p); POST(len);
 	ret +=3D l;
 	if (size)
 		*size =3D ret;
@@ -1016,6 +1018,7 @@
 		return (e);
 	p +=3D l;
 	len -=3D l;
+	POST(p); POST(len);
 	ret +=3D l;
 	if (size)
 		*size =3D ret;
@@ -1052,6 +1055,7 @@
 		return (e);
 	p +=3D l;
 	len -=3D l;
+	POST(p); POST(len);
 	ret +=3D l;
 	if (size)
 		*size =3D ret;
@@ -1198,6 +1202,7 @@
 		return (ASN1_OVERFLOW);
 	p -=3D data->length;
 	len -=3D data->length;
+	POST(len);
 	memcpy(p + 1, data->data, data->length);
 	*size =3D data->length;
 	return (0);
@@ -1263,6 +1268,7 @@
 		return (e);
 	p -=3D l;
 	len -=3D l;
+	POST(p); POST(len);
 	ret +=3D l;
 	*size =3D ret;
 	return (0);
@@ -1287,6 +1293,7 @@
 		return (e);
 	p -=3D l;
 	len -=3D l;
+	POST(p); POST(len);
 	ret +=3D l;
 	*size =3D ret;
 	return (0);
@@ -1311,6 +1318,7 @@
 		return (e);
 	p -=3D l;
 	len -=3D l;
+	POST(p); POST(len);
 	ret +=3D l;
 	*size =3D ret;
 	return (0);
@@ -1335,6 +1343,7 @@
 		return (e);
 	p -=3D l;
 	len -=3D l;
+	POST(p); POST(len);
 	ret +=3D l;
 	*size =3D ret;
 	return (0);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/spnego.h
--- a/head/contrib/bind9/lib/dns/spnego.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/spnego.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: spnego.h,v 1.4 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: spnego.h,v 1.4 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/spnego_asn1=
.c
--- a/head/contrib/bind9/lib/dns/spnego_asn1.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/dns/spnego_asn1.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: spnego_asn1.c,v 1.4 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: spnego_asn1.c,v 1.4 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file
  * \brief Method routines generated from SPNEGO ASN.1 module.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/spnego_asn1=
.pl
--- a/head/contrib/bind9/lib/dns/spnego_asn1.pl	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/dns/spnego_asn1.pl	Tue Apr 17 11:51:51 2012 +0=
300
@@ -14,7 +14,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: spnego_asn1.pl,v 1.4 2007-06-19 23:47:16 tbox Exp $
+# $Id: spnego_asn1.pl,v 1.4 2007/06/19 23:47:16 tbox Exp $
=20
 # Our SPNEGO implementation uses some functions generated by the
 # Heimdal ASN.1 compiler, which this script then whacks a bit to make
@@ -99,7 +99,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: spnego_asn1.pl,v 1.4 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: spnego_asn1.pl,v 1.4 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file
  * \brief Method routines generated from SPNEGO ASN.1 module.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/ssu.c
--- a/head/contrib/bind9/lib/dns/ssu.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/ssu.c	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
=20
 /*! \file */
 /*
- * $Id: ssu.c,v 1.38 2011-01-06 23:47:00 tbox Exp $
+ * $Id: ssu.c,v 1.38 2011/01/06 23:47:00 tbox Exp $
  * Principal Author: Brian Wellington
  */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/ssu_externa=
l.c
--- a/head/contrib/bind9/lib/dns/ssu_external.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/dns/ssu_external.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ssu_external.c,v 1.7.8.1 2011-03-21 19:53:34 each Exp $ */
+/* $Id$ */
=20
 /*
  * This implements external update-policy rules.  This allows permission
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/stats.c
--- a/head/contrib/bind9/lib/dns/stats.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/stats.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stats.c,v 1.18 2009-01-27 23:47:54 tbox Exp $ */
+/* $Id: stats.c,v 1.18 2009/01/27 23:47:54 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/tcpmsg.c
--- a/head/contrib/bind9/lib/dns/tcpmsg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/tcpmsg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tcpmsg.c,v 1.31 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: tcpmsg.c,v 1.31 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/time.c
--- a/head/contrib/bind9/lib/dns/time.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/time.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009-2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009-2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: time.c,v 1.35.132.2 2011-03-09 23:46:55 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -103,8 +103,8 @@
 	return (ISC_R_SUCCESS);
 }
=20
-isc_result_t
-dns_time32_totext(isc_uint32_t value, isc_buffer_t *target) {
+isc_int64_t
+dns_time64_from32(isc_uint32_t value) {
 	isc_stdtime_t now;
 	isc_int64_t start;
 	isc_int64_t t;
@@ -121,7 +121,13 @@
 		t =3D start + (value - now);
 	else
 		t =3D start - (now - value);
-	return (dns_time64_totext(t, target));
+
+	return (t);
+}
+
+isc_result_t
+dns_time32_totext(isc_uint32_t value, isc_buffer_t *target) {
+	return (dns_time64_totext(dns_time64_from32(value), target));
 }
=20
 isc_result_t
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/timer.c
--- a/head/contrib/bind9/lib/dns/timer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/timer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: timer.c,v 1.7 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: timer.c,v 1.7 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/tkey.c
--- a/head/contrib/bind9/lib/dns/tkey.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/tkey.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -16,7 +16,7 @@
  */
=20
 /*
- * $Id: tkey.c,v 1.100.12.1 2011-03-11 06:47:05 marka Exp $
+ * $Id$
  */
 /*! \file */
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/tsec.c
--- a/head/contrib/bind9/lib/dns/tsec.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/tsec.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsec.c,v 1.7 2010-12-09 00:54:34 marka Exp $ */
+/* $Id: tsec.c,v 1.7 2010/12/09 00:54:34 marka Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/tsig.c
--- a/head/contrib/bind9/lib/dns/tsig.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/tsig.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -16,7 +16,7 @@
  */
=20
 /*
- * $Id: tsig.c,v 1.147.10.1 2011-03-21 19:53:34 each Exp $
+ * $Id$
  */
 /*! \file */
 #include <config.h>
@@ -889,6 +889,7 @@
 	isc_result_t ret;
 	unsigned char badtimedata[BADTIMELEN];
 	unsigned int sigsize =3D 0;
+	isc_boolean_t response =3D is_response(msg);
=20
 	REQUIRE(msg !=3D NULL);
 	REQUIRE(VALID_TSIG_KEY(dns_message_gettsigkey(msg)));
@@ -896,7 +897,7 @@
 	/*
 	 * If this is a response, there should be a query tsig.
 	 */
-	if (is_response(msg) && msg->querytsig =3D=3D NULL)
+	if (response && msg->querytsig =3D=3D NULL)
 		return (DNS_R_EXPECTEDTSIG);
=20
 	dynbuf =3D NULL;
@@ -919,7 +920,7 @@
=20
 	isc_buffer_init(&databuf, data, sizeof(data));
=20
-	if (is_response(msg))
+	if (response)
 		tsig.error =3D msg->querytsigstatus;
 	else
 		tsig.error =3D dns_rcode_noerror;
@@ -948,7 +949,7 @@
 		/*
 		 * If this is a response, digest the query signature.
 		 */
-		if (is_response(msg)) {
+		if (response) {
 			dns_rdata_t querytsigrdata =3D DNS_RDATA_INIT;
=20
 			ret =3D dns_rdataset_first(msg->querytsig);
@@ -1017,8 +1018,10 @@
 		}
 		/* Digest the timesigned and fudge */
 		isc_buffer_clear(&databuf);
-		if (tsig.error =3D=3D dns_tsigerror_badtime)
+		if (tsig.error =3D=3D dns_tsigerror_badtime) {
+			INSIST(response);
 			tsig.timesigned =3D querytsig.timesigned;
+		}
 		isc_buffer_putuint48(&databuf, tsig.timesigned);
 		isc_buffer_putuint16(&databuf, tsig.fudge);
 		isc_buffer_usedregion(&databuf, &r);
@@ -1040,7 +1043,7 @@
 				goto cleanup_context;
=20
 			/*
-			 * Digest the error and other data.
+			 * Digest other data.
 			 */
 			if (tsig.otherlen > 0) {
 				r.length =3D tsig.otherlen;
@@ -1068,7 +1071,7 @@
 		digestbits =3D dst_key_getbits(key->key);
 		if (digestbits !=3D 0) {
 			unsigned int bytes =3D (digestbits + 1) / 8;
-			if (is_response(msg) && bytes < querytsig.siglen)
+			if (response && bytes < querytsig.siglen)
 				bytes =3D querytsig.siglen;
 			if (bytes > isc_buffer_usedlength(&sigbuf))
 				bytes =3D isc_buffer_usedlength(&sigbuf);
@@ -1170,10 +1173,12 @@
 	isc_uint16_t addcount, id;
 	unsigned int siglen;
 	unsigned int alg;
+	isc_boolean_t response;
=20
 	REQUIRE(source !=3D NULL);
 	REQUIRE(DNS_MESSAGE_VALID(msg));
 	tsigkey =3D dns_message_gettsigkey(msg);
+	response =3D is_response(msg);
=20
 	REQUIRE(tsigkey =3D=3D NULL || VALID_TSIG_KEY(tsigkey));
=20
@@ -1195,8 +1200,7 @@
 	 * If this is a response and there's no key or query TSIG, there
 	 * shouldn't be one on the response.
 	 */
-	if (is_response(msg) &&
-	    (tsigkey =3D=3D NULL || msg->querytsig =3D=3D NULL))
+	if (response && (tsigkey =3D=3D NULL || msg->querytsig =3D=3D NULL))
 		return (DNS_R_UNEXPECTEDTSIG);
=20
 	mctx =3D msg->mctx;
@@ -1215,7 +1219,7 @@
 	if (ret !=3D ISC_R_SUCCESS)
 		return (ret);
 	dns_rdata_reset(&rdata);
-	if (is_response(msg)) {
+	if (response) {
 		ret =3D dns_rdataset_first(msg->querytsig);
 		if (ret !=3D ISC_R_SUCCESS)
 			return (ret);
@@ -1228,7 +1232,7 @@
 	/*
 	 * Do the key name and algorithm match that of the query?
 	 */
-	if (is_response(msg) &&
+	if (response &&
 	    (!dns_name_equal(keyname, &tsigkey->name) ||
 	     !dns_name_equal(&tsig.algorithm, &querytsig.algorithm))) {
 		msg->tsigstatus =3D dns_tsigerror_badkey;
@@ -1326,7 +1330,7 @@
 		if (ret !=3D ISC_R_SUCCESS)
 			return (ret);
=20
-		if (is_response(msg)) {
+		if (response) {
 			isc_buffer_init(&databuf, data, sizeof(data));
 			isc_buffer_putuint16(&databuf, querytsig.siglen);
 			isc_buffer_usedregion(&databuf, &r);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/ttl.c
--- a/head/contrib/bind9/lib/dns/ttl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/ttl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ttl.c,v 1.29.814.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/validator.c
--- a/head/contrib/bind9/lib/dns/validator.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/validator.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: validator.c,v 1.197.14.7 2011-06-08 23:02:43 each Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
@@ -846,7 +846,7 @@
  * Return ISC_R_IGNORE when the NSEC is not the appropriate one.
  */
 static isc_result_t
-nsecnoexistnodata(dns_validator_t *val, dns_name_t* name, dns_name_t *nsec=
name,
+nsecnoexistnodata(dns_validator_t *val, dns_name_t *name, dns_name_t *nsec=
name,
 		  dns_rdataset_t *nsecset, isc_boolean_t *exists,
 		  isc_boolean_t *data, dns_name_t *wild)
 {
@@ -887,9 +887,11 @@
=20
 	if (order =3D=3D 0) {
 		/*
-		 * The names are the same.
+		 * The names are the same.   If we are validating "."
+		 * then atparent should not be set as there is no parent.
 		 */
-		atparent =3D dns_rdatatype_atparent(val->event->type);
+		atparent =3D (olabels !=3D 1) &&
+			   dns_rdatatype_atparent(val->event->type);
 		ns =3D dns_nsec_typepresent(&rdata, dns_rdatatype_ns);
 		soa =3D dns_nsec_typepresent(&rdata, dns_rdatatype_soa);
 		if (ns && !soa) {
@@ -1920,14 +1922,17 @@
 	isc_result_t result;
 	dns_fixedname_t fixed;
 	isc_boolean_t ignore =3D ISC_FALSE;
+	dns_name_t *wild;
=20
 	val->attributes |=3D VALATTR_TRIEDVERIFY;
 	dns_fixedname_init(&fixed);
+	wild =3D dns_fixedname_name(&fixed);
  again:
 	result =3D dns_dnssec_verify2(val->event->name, val->event->rdataset,
-				    key, ignore, val->view->mctx, rdata,
-				    dns_fixedname_name(&fixed));
-	if (result =3D=3D DNS_R_SIGEXPIRED && val->view->acceptexpired) {
+				    key, ignore, val->view->mctx, rdata, wild);
+	if ((result =3D=3D DNS_R_SIGEXPIRED || result =3D=3D DNS_R_SIGFUTURE) &&
+	    val->view->acceptexpired)
+	{
 		ignore =3D ISC_TRUE;
 		goto again;
 	}
@@ -1936,14 +1941,29 @@
 			      "accepted expired %sRRSIG (keyid=3D%u)",
 			      (result =3D=3D DNS_R_FROMWILDCARD) ?
 			      "wildcard " : "", keyid);
+	else if (result =3D=3D DNS_R_SIGEXPIRED || result =3D=3D DNS_R_SIGFUTURE)
+		validator_log(val, ISC_LOG_INFO,
+			      "verify failed due to bad signature (keyid=3D%u): "
+			      "%s", keyid, isc_result_totext(result));
 	else
 		validator_log(val, ISC_LOG_DEBUG(3),
 			      "verify rdataset (keyid=3D%u): %s",
 			      keyid, isc_result_totext(result));
 	if (result =3D=3D DNS_R_FROMWILDCARD) {
-		if (!dns_name_equal(val->event->name,
-				    dns_fixedname_name(&fixed)))
+		if (!dns_name_equal(val->event->name, wild)) {
+			dns_name_t *closest;
+			unsigned int labels;
+
+			/*
+			 * Compute the closest encloser in case we need it
+			 * for the NSEC3 NOQNAME proof.
+			 */
+			closest =3D dns_fixedname_name(&val->closest);
+			dns_name_copy(wild, closest, NULL);
+			labels =3D dns_name_countlabels(closest) - 1;
+			dns_name_getlabelsequence(closest, 1, labels, closest);
 			val->attributes |=3D VALATTR_NEEDNOQNAME;
+		}
 		result =3D ISC_R_SUCCESS;
 	}
 	return (result);
@@ -2871,9 +2891,9 @@
 	dns_name_t *name, tname;
 	isc_result_t result;
 	isc_boolean_t exists, data, optout, unknown;
-	isc_boolean_t setclosest, setnearest;
+	isc_boolean_t setclosest, setnearest, *setclosestp;
 	dns_fixedname_t fclosest, fnearest, fzonename;
-	dns_name_t *closest, *nearest, *zonename;
+	dns_name_t *closest, *nearest, *zonename, *closestp;
 	dns_name_t **proofs =3D val->event->proofs;
 	dns_rdataset_t *rdataset, trdataset;
=20
@@ -2920,6 +2940,25 @@
 	if (dns_name_countlabels(zonename) =3D=3D 0)
 		return (ISC_R_SUCCESS);
=20
+	/*
+	 * If the val->closest is set then we want to use it otherwise
+	 * we need to discover it.
+	 */
+	if (dns_name_countlabels(dns_fixedname_name(&val->closest)) !=3D 0) {
+		char namebuf[DNS_NAME_FORMATSIZE];
+
+		dns_name_format(dns_fixedname_name(&val->closest),
+				 namebuf, sizeof(namebuf));
+		validator_log(val, ISC_LOG_DEBUG(3), "closest encloser from "
+			      "wildcard signature '%s'", namebuf);
+		dns_name_copy(dns_fixedname_name(&val->closest), closest, NULL);
+		closestp =3D NULL;
+		setclosestp =3D NULL;
+	} else {
+		closestp =3D closest;
+		setclosestp =3D &setclosest;
+	}
+
 	for (result =3D val_rdataset_first(val, &name, &rdataset);
 	     result =3D=3D ISC_R_SUCCESS;
 	     result =3D val_rdataset_next(val, &name, &rdataset))
@@ -2937,8 +2976,8 @@
 		unknown =3D ISC_FALSE;
 		(void)nsec3noexistnodata(val, val->event->name, name, rdataset,
 					 zonename, &exists, &data, &optout,
-					 &unknown, &setclosest, &setnearest,
-					 closest, nearest);
+					 &unknown, setclosestp, &setnearest,
+					 closestp, nearest);
 		if (setclosest)
 			proofs[DNS_VALIDATOR_CLOSESTENCLOSER] =3D name;
 		if (unknown)
@@ -3704,9 +3743,8 @@
 				result =3D ISC_R_SUCCESS;
 				goto out;
 			}
-			result =3D startfinddlvsep(val,
-					      dns_fixedname_name(&val->fname));
-			goto out;
+			return(startfinddlvsep(val,
+					      dns_fixedname_name(&val->fname)));
 		}
 		val->labels++;
 	}
@@ -3842,8 +3880,7 @@
 						result =3D ISC_R_SUCCESS;
 						goto out;
 					}
-					result =3D startfinddlvsep(val, tname);
-					goto out;
+					return(startfinddlvsep(val, tname));
 				}
 				continue;
 			}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/version.c
--- a/head/contrib/bind9/lib/dns/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.c,v 1.15 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: version.c,v 1.15 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/view.c
--- a/head/contrib/bind9/lib/dns/view.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/view.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: view.c,v 1.178.8.1 2011-03-11 06:47:06 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -1713,6 +1713,9 @@
 dns_view_issecuredomain(dns_view_t *view, dns_name_t *name,
 			 isc_boolean_t *secure_domain) {
 	REQUIRE(DNS_VIEW_VALID(view));
+
+	if (view->secroots_priv =3D=3D NULL)
+		return (ISC_R_NOTFOUND);
 	return (dns_keytable_issecuredomain(view->secroots_priv, name,
 					    secure_domain));
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/xfrin.c
--- a/head/contrib/bind9/lib/dns/xfrin.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/xfrin.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2008, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: xfrin.c,v 1.166.522.4 2011-03-11 06:47:06 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/zone.c
--- a/head/contrib/bind9/lib/dns/zone.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/zone.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zone.c,v 1.582.8.26 2011-08-09 02:34:24 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -74,6 +74,7 @@
 #include <dns/soa.h>
 #include <dns/ssu.h>
 #include <dns/stats.h>
+#include <dns/time.h>
 #include <dns/tsig.h>
 #include <dns/xfrin.h>
 #include <dns/zone.h>
@@ -136,6 +137,7 @@
 typedef struct dns_stub dns_stub_t;
 typedef struct dns_load dns_load_t;
 typedef struct dns_forward dns_forward_t;
+typedef ISC_LIST(dns_forward_t) dns_forwardlist_t;
 typedef struct dns_io dns_io_t;
 typedef ISC_LIST(dns_io_t) dns_iolist_t;
 typedef struct dns_signing dns_signing_t;
@@ -336,6 +338,11 @@
 	 * whether a rpz radix was needed when last loaded
 	 */
 	isc_boolean_t           rpz_zone;
+
+	/*%
+	 * Outstanding forwarded UPDATE requests.
+	 */
+	dns_forwardlist_t	forwards;
 };
=20
 #define DNS_ZONE_FLAG(z,f) (ISC_TF(((z)->flags & (f)) !=3D 0))
@@ -500,6 +507,7 @@
 	isc_sockaddr_t		addr;
 	dns_updatecallback_t	callback;
 	void			*callback_arg;
+	ISC_LINK(dns_forward_t)	link;
 };
=20
 /*%
@@ -659,10 +667,6 @@
 static void zone_maintenance(dns_zone_t *zone);
 static void zone_notify(dns_zone_t *zone, isc_time_t *now);
 static void dump_done(void *arg, isc_result_t result);
-static isc_boolean_t dns_zonemgr_unreachable(dns_zonemgr_t *zmgr,
-					     isc_sockaddr_t *remote,
-					     isc_sockaddr_t *local,
-					     isc_time_t *now);
 static isc_result_t zone_signwithkey(dns_zone_t *zone, dns_secalg_t algori=
thm,
 				     isc_uint16_t keyid, isc_boolean_t delete);
 static isc_result_t delete_nsec(dns_db_t *db, dns_dbversion_t *ver,
@@ -851,6 +855,7 @@
 	zone->privatetype =3D (dns_rdatatype_t)0xffffU;
 	zone->added =3D ISC_FALSE;
 	zone->rpz_zone =3D ISC_FALSE;
+	ISC_LIST_INIT(zone->forwards);
=20
 	zone->magic =3D ZONE_MAGIC;
=20
@@ -3183,7 +3188,7 @@
 	for (result =3D dns_rriterator_first(&rrit);
 	     result =3D=3D ISC_R_SUCCESS;
 	     result =3D dns_rriterator_nextrrset(&rrit)) {
-		dns_rdataset_t *rdataset;
+		dns_rdataset_t *rdataset =3D NULL;
 		dns_name_t *rrname =3D NULL;
 		isc_uint32_t ttl;
=20
@@ -3319,7 +3324,11 @@
 					     zone->masterfile,
 					     dns_result_totext(result));
 		} else {
-			dns_zone_log(zone, ISC_LOG_ERROR,
+			int level =3D ISC_LOG_ERROR;
+			if (zone->type =3D=3D dns_zone_key &&
+			    result =3D=3D ISC_R_FILENOTFOUND)
+				level =3D ISC_LOG_DEBUG(1);
+			dns_zone_log(zone, level,
 				     "loading from master file %s failed: %s",
 				     zone->masterfile,
 				     dns_result_totext(result));
@@ -3388,9 +3397,7 @@
 			needdump =3D ISC_TRUE;
 	}
=20
-	zone->loadtime =3D loadtime;
-
-	dns_zone_log(zone, ISC_LOG_DEBUG(1), "loaded");
+	dns_zone_log(zone, ISC_LOG_DEBUG(1), "loaded; checking validity");
 	/*
 	 * Obtain ns, soa and cname counts for top of zone.
 	 */
@@ -3635,6 +3642,7 @@
 		dns_zone_log(zone, ISC_LOG_INFO, "loaded serial %u%s", serial,
 			     dns_db_issecure(db) ? " (DNSSEC signed)" : "");
=20
+	zone->loadtime =3D loadtime;
 	return (result);
=20
  cleanup:
@@ -3988,6 +3996,26 @@
 	UNLOCK_ZONE(source);
 }
=20
+isc_result_t
+dns_zone_synckeyzone(dns_zone_t *zone) {
+	isc_result_t result;
+	dns_db_t *db =3D NULL;
+
+	if (zone->type !=3D dns_zone_key)
+		return (DNS_R_BADZONE);
+
+	CHECK(dns_zone_getdb(zone, &db));
+
+	LOCK_ZONE(zone);
+	result =3D sync_keyzone(zone, db);
+	UNLOCK_ZONE(zone);
+
+ failure:
+	if (db !=3D NULL)
+		dns_db_detach(&db);
+	return (result);
+}
+
 static void
 zone_iattach(dns_zone_t *source, dns_zone_t **target) {
=20
@@ -4486,8 +4514,6 @@
 	return (dumping);
 }
=20
-#define MAXZONEKEYS 10
-
 static isc_result_t
 find_zone_keys(dns_zone_t *zone, dns_db_t *db, dns_dbversion_t *ver,
 	       isc_mem_t *mctx, unsigned int maxkeys,
@@ -4604,11 +4630,10 @@
 	isc_result_t result;
 	dns_dbnode_t *node =3D NULL;
 	dns_rdataset_t rdataset;
-	dns_rdata_t rdata =3D DNS_RDATA_INIT;
 	unsigned int i;
 	dns_rdata_rrsig_t rrsig;
 	isc_boolean_t found, changed;
-	isc_stdtime_t warn =3D 0, maybe =3D 0;
+	isc_int64_t warn =3D 0, maybe =3D 0;
=20
 	dns_rdataset_init(&rdataset);
=20
@@ -4637,6 +4662,8 @@
 	for (result =3D dns_rdataset_first(&rdataset);
 	     result =3D=3D ISC_R_SUCCESS;
 	     result =3D dns_rdataset_next(&rdataset)) {
+		dns_rdata_t rdata =3D DNS_RDATA_INIT;
+
 		dns_rdataset_current(&rdataset, &rdata);
 		result =3D dns_rdata_tostruct(&rdata, &rrsig, NULL);
 		RUNTIME_CHECK(result =3D=3D ISC_R_SUCCESS);
@@ -4648,7 +4675,6 @@
 					       rdataset.ttl, &rdata);
 				if (incremental)
 					changed =3D ISC_TRUE;
-				dns_rdata_reset(&rdata);
 				if (result !=3D ISC_R_SUCCESS)
 					break;
 			} else {
@@ -4709,21 +4735,20 @@
 				 * iff there is a new offline signature.
 				 */
 				if (!dst_key_isprivate(keys[i])) {
-					if (warn !=3D 0 &&
-					    warn > rrsig.timeexpire)
-						warn =3D rrsig.timeexpire;
+					isc_int64_t timeexpire =3D
+					   dns_time64_from32(rrsig.timeexpire);
+					if (warn !=3D 0 && warn > timeexpire)
+						warn =3D timeexpire;
 					if (rdata.flags & DNS_RDATA_OFFLINE) {
 						if (maybe =3D=3D 0 ||
-						    maybe > rrsig.timeexpire)
-							maybe =3D
-							     rrsig.timeexpire;
+						    maybe > timeexpire)
+							maybe =3D timeexpire;
 						break;
 					}
 					if (warn =3D=3D 0)
 						warn =3D maybe;
-					if (warn =3D=3D 0 ||
-					    warn > rrsig.timeexpire)
-						warn =3D rrsig.timeexpire;
+					if (warn =3D=3D 0 || warn > timeexpire)
+						warn =3D timeexpire;
 					result =3D offline(db, ver, diff, name,
 							 rdataset.ttl, &rdata);
 					break;
@@ -4744,7 +4769,6 @@
 			result =3D update_one_rr(db, ver, diff,
 					       DNS_DIFFOP_DELRESIGN, name,
 					       rdataset.ttl, &rdata);
-		dns_rdata_reset(&rdata);
 		if (result !=3D ISC_R_SUCCESS)
 			break;
 	}
@@ -4755,8 +4779,18 @@
 	dns_rdataset_disassociate(&rdataset);
 	if (result =3D=3D ISC_R_NOMORE)
 		result =3D ISC_R_SUCCESS;
-	if (warn !=3D 0)
-		set_key_expiry_warning(zone, warn, now);
+	if (warn > 0) {
+#if defined(STDTIME_ON_32BITS)
+		isc_stdtime_t stdwarn =3D (isc_stdtime_t)warn;
+		if (warn =3D=3D stdwarn)
+#endif
+			set_key_expiry_warning(zone, (isc_stdtime_t)warn, now);
+#if defined(STDTIME_ON_32BITS)
+		else
+			dns_zone_log(zone, ISC_LOG_ERROR,
+				     "key expiry warning time out of range");
+#endif
+	}
  failure:
 	if (node !=3D NULL)
 		dns_db_detachnode(db, &node);
@@ -4869,7 +4903,7 @@
 	dns_name_t *name;
 	dns_rdataset_t rdataset;
 	dns_rdatatype_t covers;
-	dst_key_t *zone_keys[MAXZONEKEYS];
+	dst_key_t *zone_keys[DNS_MAXZONEKEYS];
 	isc_boolean_t check_ksk, keyset_kskonly =3D ISC_FALSE;
 	isc_result_t result;
 	isc_stdtime_t now, inception, soaexpire, expire, stop;
@@ -4903,7 +4937,7 @@
 		goto failure;
 	}
=20
-	result =3D find_zone_keys(zone, db, version, zone->mctx, MAXZONEKEYS,
+	result =3D find_zone_keys(zone, db, version, zone->mctx, DNS_MAXZONEKEYS,
 				zone_keys, &nkeys);
 	if (result !=3D ISC_R_SUCCESS) {
 		dns_zone_log(zone, ISC_LOG_ERROR,
@@ -5761,7 +5795,7 @@
 	dns_rdataset_t rdataset;
 	dns_nsec3chain_t *nsec3chain =3D NULL, *nextnsec3chain;
 	dns_nsec3chainlist_t cleanup;
-	dst_key_t *zone_keys[MAXZONEKEYS];
+	dst_key_t *zone_keys[DNS_MAXZONEKEYS];
 	isc_int32_t signatures;
 	isc_boolean_t check_ksk, keyset_kskonly;
 	isc_boolean_t delegation;
@@ -5813,7 +5847,7 @@
 	}
=20
 	result =3D find_zone_keys(zone, db, version, zone->mctx,
-				MAXZONEKEYS, zone_keys, &nkeys);
+				DNS_MAXZONEKEYS, zone_keys, &nkeys);
 	if (result !=3D ISC_R_SUCCESS) {
 		dns_zone_log(zone, ISC_LOG_ERROR,
 			     "zone_nsec3chain:find_zone_keys -> %s\n",
@@ -6592,7 +6626,7 @@
 	dns_rdataset_t rdataset;
 	dns_signing_t *signing, *nextsigning;
 	dns_signinglist_t cleanup;
-	dst_key_t *zone_keys[MAXZONEKEYS];
+	dst_key_t *zone_keys[DNS_MAXZONEKEYS];
 	isc_int32_t signatures;
 	isc_boolean_t check_ksk, keyset_kskonly, is_ksk;
 	isc_boolean_t commit =3D ISC_FALSE;
@@ -6638,7 +6672,7 @@
 	}
=20
 	result =3D find_zone_keys(zone, db, version, zone->mctx,
-				MAXZONEKEYS, zone_keys, &nkeys);
+				DNS_MAXZONEKEYS, zone_keys, &nkeys);
 	if (result !=3D ISC_R_SUCCESS) {
 		dns_zone_log(zone, ISC_LOG_ERROR,
 			     "zone_sign:find_zone_keys -> %s\n",
@@ -7272,8 +7306,7 @@
=20
 		if (dst_key_alg(dstkey) =3D=3D sig.algorithm &&
 		    (dst_key_id(dstkey) =3D=3D sig.keyid ||
-		     (sig.algorithm !=3D 1 && sig.keyid =3D=3D
-		       ((dst_key_id(dstkey) + 128) & 0xffff)))) {
+		     dst_key_rid(dstkey) =3D=3D sig.keyid)) {
 			result =3D dns_dnssec_verify2(keyname,
 					    &kfetch->dnskeyset,
 					    dstkey, ISC_FALSE, mctx, &sigrr,
@@ -7771,6 +7804,7 @@
 	dns_rdata_keydata_t kd;
 	isc_stdtime_t now;
 	isc_boolean_t commit =3D ISC_FALSE;
+	isc_boolean_t fetching =3D ISC_FALSE, fetch_err =3D ISC_FALSE;
=20
 	ENTER;
 	REQUIRE(zone->db !=3D NULL);
@@ -7799,16 +7833,14 @@
 	     result =3D=3D ISC_R_SUCCESS;
 	     result =3D dns_rriterator_nextrrset(&rrit)) {
 		isc_stdtime_t timer =3D 0xffffffff;
+		dns_name_t *name =3D NULL, *kname =3D NULL;
+		dns_rdataset_t *kdset =3D NULL;
 		dns_keyfetch_t *kfetch;
-		dns_rdataset_t *kdset;
-		dns_name_t *name =3D NULL;
 		isc_uint32_t ttl;
=20
 		dns_rriterator_current(&rrit, &name, &ttl, &kdset, NULL);
-		if (!dns_rdataset_isassociated(kdset))
-			continue;
-
-		if (kdset->type !=3D dns_rdatatype_keydata)
+		if (kdset =3D=3D NULL || kdset->type !=3D dns_rdatatype_keydata ||
+		    !dns_rdataset_isassociated(kdset))
 			continue;
=20
 		/*
@@ -7843,15 +7875,19 @@
 		if (timer > now)
 			continue;
=20
+		kfetch =3D isc_mem_get(zone->mctx, sizeof(dns_keyfetch_t));
+		if (kfetch =3D=3D NULL) {
+			fetch_err =3D ISC_TRUE;
+			goto failure;
+		}
+
 		zone->refreshkeycount++;
-
-		kfetch =3D isc_mem_get(zone->mctx, sizeof(dns_keyfetch_t));
 		kfetch->zone =3D zone;
 		zone->irefs++;
 		INSIST(zone->irefs !=3D 0);
 		dns_fixedname_init(&kfetch->name);
-		dns_name_dup(name, zone->mctx,
-			     dns_fixedname_name(&kfetch->name));
+		kname =3D dns_fixedname_name(&kfetch->name);
+		dns_name_dup(name, zone->mctx, kname);
 		dns_rdataset_init(&kfetch->dnskeyset);
 		dns_rdataset_init(&kfetch->dnskeysigset);
 		dns_rdataset_init(&kfetch->keydataset);
@@ -7860,25 +7896,59 @@
 		dns_db_attach(db, &kfetch->db);
 		kfetch->fetch =3D NULL;
=20
-		dns_resolver_createfetch(zone->view->resolver,
-					 dns_fixedname_name(&kfetch->name),
-					 dns_rdatatype_dnskey,
-					 NULL, NULL, NULL,
-					 DNS_FETCHOPT_NOVALIDATE,
-					 zone->task, keyfetch_done, kfetch,
-					 &kfetch->dnskeyset,
-					 &kfetch->dnskeysigset,
-					 &kfetch->fetch);
+		result =3D dns_resolver_createfetch(zone->view->resolver,
+						  kname, dns_rdatatype_dnskey,
+						  NULL, NULL, NULL,
+						  DNS_FETCHOPT_NOVALIDATE,
+						  zone->task,
+						  keyfetch_done, kfetch,
+						  &kfetch->dnskeyset,
+						  &kfetch->dnskeysigset,
+						  &kfetch->fetch);
+		if (result =3D=3D ISC_R_SUCCESS)
+			fetching =3D ISC_TRUE;
+		else {
+			zone->refreshkeycount--;
+			zone->irefs--;
+			dns_db_detach(&kfetch->db);
+			dns_rdataset_disassociate(&kfetch->keydataset);
+			dns_name_free(kname, zone->mctx);
+			isc_mem_put(zone->mctx, kfetch, sizeof(dns_keyfetch_t));
+			dns_zone_log(zone, ISC_LOG_WARNING,
+				     "Failed to create fetch for "
+				     "DNSKEY update");
+			fetch_err =3D ISC_TRUE;
+		}
 	}
 	if (!ISC_LIST_EMPTY(diff.tuples)) {
 		CHECK(increment_soa_serial(db, ver, &diff, zone->mctx));
-		CHECK(zone_journal(zone, &diff, "sync_keyzone"));
+		CHECK(zone_journal(zone, &diff, "zone_refreshkeys"));
 		commit =3D ISC_TRUE;
 		DNS_ZONE_SETFLAG(zone, DNS_ZONEFLG_LOADED);
 		zone_needdump(zone, 30);
 	}
=20
   failure:
+	if (fetch_err) {
+		/*
+		 * Error during a key fetch; retry in an hour.
+		 */
+		isc_time_t timenow, timethen;
+		char timebuf[80];
+
+		TIME_NOW(&timenow);
+		DNS_ZONE_TIME_ADD(&timenow, HOUR, &timethen);
+		zone->refreshkeytime =3D timethen;
+		zone_settimer(zone, &timenow);
+
+		isc_time_formattimestamp(&zone->refreshkeytime, timebuf, 80);
+		dns_zone_log(zone, ISC_LOG_DEBUG(1), "retry key refresh: %s",
+			     timebuf);
+
+		if (!fetching)
+			DNS_ZONE_CLRFLAG(zone, DNS_ZONEFLG_REFRESHING);
+	}
+
 	UNLOCK_ZONE(zone);
=20
 	dns_diff_clear(&diff);
@@ -7903,7 +7973,7 @@
 	 * Configuring the view of this zone may have
 	 * failed, for example because the config file
 	 * had a syntax error.	In that case, the view
-	 * adb or resolver, and we had better not try
+	 * db or resolver will be NULL, and we had better not try
 	 * to do maintenance on it.
 	 */
 	if (zone->view =3D=3D NULL || zone->view->adb =3D=3D NULL)
@@ -8435,6 +8505,24 @@
 }
=20
 static void
+forward_cancel(dns_zone_t *zone) {
+	dns_forward_t *forward;
+
+	/*
+	 * 'zone' locked by caller.
+	 */
+
+	REQUIRE(LOCKED_ZONE(zone));
+
+	for (forward =3D ISC_LIST_HEAD(zone->forwards);
+	     forward !=3D NULL;
+	     forward =3D ISC_LIST_NEXT(forward, link)) {
+		if (forward->request !=3D NULL)
+			dns_request_cancel(forward->request);
+	}
+}
+
+static void
 zone_unload(dns_zone_t *zone) {
=20
 	/*
@@ -9404,7 +9492,7 @@
 	dns_rdata_t rdata =3D DNS_RDATA_INIT;
 	dns_rdata_soa_t soa;
 	isc_result_t result;
-	isc_uint32_t serial, oldserial;
+	isc_uint32_t serial, oldserial =3D 0;
 	unsigned int j;
=20
 	zone =3D revent->ev_arg;
@@ -9446,7 +9534,8 @@
 				if (!dns_zonemgr_unreachable(zone->zmgr,
 							     &zone->masteraddr,
 							     &zone->sourceaddr,
-							     &now)) {
+							     &now))
+				{
 					LOCK_ZONE(zone);
 					DNS_ZONE_SETFLAG(zone,
 						     DNS_ZONEFLG_SOABEFOREAXFR);
@@ -9640,7 +9729,8 @@
 	    DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FORCEXFER) ||
 	    isc_serial_gt(serial, oldserial)) {
 		if (dns_zonemgr_unreachable(zone->zmgr, &zone->masteraddr,
-					    &zone->sourceaddr, &now)) {
+					    &zone->sourceaddr, &now))
+		{
 			dns_zone_log(zone, ISC_LOG_INFO,
 				     "refresh: skipping %s as master %s "
 				     "(source %s) is unreachable (cached)",
@@ -10344,6 +10434,7 @@
 	REQUIRE(DNS_ZONE_VALID(zone));
 	INSIST(event->ev_type =3D=3D DNS_EVENT_ZONECONTROL);
 	INSIST(isc_refcount_current(&zone->erefs) =3D=3D 0);
+
 	zone_debuglog(zone, "zone_shutdown", 3, "shutting down");
=20
 	/*
@@ -10402,6 +10493,8 @@
=20
 	notify_cancel(zone);
=20
+	forward_cancel(zone);
+
 	if (zone->timer !=3D NULL) {
 		isc_timer_detach(&zone->timer);
 		INSIST(zone->irefs > 0);
@@ -10744,6 +10837,7 @@
 	char fromtext[ISC_SOCKADDR_FORMATSIZE];
 	int match =3D 0;
 	isc_netaddr_t netaddr;
+	isc_sockaddr_t local, remote;
=20
 	REQUIRE(DNS_ZONE_VALID(zone));
=20
@@ -10894,7 +10988,10 @@
 		return (ISC_R_SUCCESS);
 	}
 	zone->notifyfrom =3D *from;
-	UNLOCK_ZONE(zone);
+	local =3D zone->masteraddr;
+	remote =3D zone->sourceaddr;
+	UNLOCK_ZONE(zone);
+	dns_zonemgr_unreachabledel(zone->zmgr, &local, &remote);
 	dns_zone_refresh(zone);
 	return (ISC_R_SUCCESS);
 }
@@ -11916,11 +12013,13 @@
 	 * This transfer finishing freed up a transfer quota slot.
 	 * Let any other zones waiting for quota have it.
 	 */
+	UNLOCK_ZONE(zone);
 	RWLOCK(&zone->zmgr->rwlock, isc_rwlocktype_write);
 	ISC_LIST_UNLINK(zone->zmgr->xfrin_in_progress, zone, statelink);
 	zone->statelist =3D NULL;
 	zmgr_resume_xfrs(zone->zmgr, ISC_FALSE);
 	RWUNLOCK(&zone->zmgr->rwlock, isc_rwlocktype_write);
+	LOCK_ZONE(zone);
=20
 	/*
 	 * Retry with a different server if necessary.
@@ -12087,7 +12186,8 @@
=20
 	isc_sockaddr_format(&zone->masteraddr, master, sizeof(master));
 	if (dns_zonemgr_unreachable(zone->zmgr, &zone->masteraddr,
-				    &zone->sourceaddr, &now)) {
+				    &zone->sourceaddr, &now))
+	{
 		isc_sockaddr_format(&zone->sourceaddr, source, sizeof(source));
 		dns_zone_log(zone, ISC_LOG_INFO,
 			     "got_transfer_quota: skipping zone transfer as "
@@ -12227,8 +12327,13 @@
 		dns_request_destroy(&forward->request);
 	if (forward->msgbuf !=3D NULL)
 		isc_buffer_free(&forward->msgbuf);
-	if (forward->zone !=3D NULL)
+	if (forward->zone !=3D NULL) {
+		LOCK(&forward->zone->lock);
+		if (ISC_LINK_LINKED(forward, link))
+			ISC_LIST_UNLINK(forward->zone->forwards, forward, link);
+		UNLOCK(&forward->zone->lock);
 		dns_zone_idetach(&forward->zone);
+	}
 	isc_mem_putanddetach(&forward->mctx, forward, sizeof(*forward));
 }
=20
@@ -12238,6 +12343,12 @@
 	isc_sockaddr_t src;
=20
 	LOCK_ZONE(forward->zone);
+
+	if (DNS_ZONE_FLAG(forward->zone, DNS_ZONEFLG_EXITING)) {
+		UNLOCK_ZONE(forward->zone);
+		return (ISC_R_CANCELED);
+	}
+
 	if (forward->which >=3D forward->zone->masterscnt) {
 		UNLOCK_ZONE(forward->zone);
 		return (ISC_R_NOMORE);
@@ -12268,6 +12379,11 @@
 				       forward->zone->task,
 				       forward_callback, forward,
 				       &forward->request);
+	if (result =3D=3D ISC_R_SUCCESS) {
+		if (!ISC_LINK_LINKED(forward, link))
+			ISC_LIST_APPEND(forward->zone->forwards, forward, link);
+	}
+
  unlock:
 	UNLOCK_ZONE(forward->zone);
 	return (result);
@@ -12394,6 +12510,7 @@
 	forward->mctx =3D 0;
 	forward->callback =3D callback;
 	forward->callback_arg =3D callback_arg;
+	ISC_LINK_INIT(forward, link);
 	forward->magic =3D FORWARD_MAGIC;
=20
 	mr =3D dns_message_getrawmessage(msg);
@@ -12676,6 +12793,8 @@
=20
 void
 dns_zonemgr_shutdown(dns_zonemgr_t *zmgr) {
+	dns_zone_t *zone;
+
 	REQUIRE(DNS_ZONEMGR_VALID(zmgr));
=20
 	isc_ratelimiter_shutdown(zmgr->rl);
@@ -12684,6 +12803,18 @@
 		isc_task_destroy(&zmgr->task);
 	if (zmgr->zonetasks !=3D NULL)
 		isc_taskpool_destroy(&zmgr->zonetasks);
+
+	RWLOCK(&zmgr->rwlock, isc_rwlocktype_read);
+	for (zone =3D ISC_LIST_HEAD(zmgr->zones);
+	     zone !=3D NULL;
+	     zone =3D ISC_LIST_NEXT(zone, link))
+	{
+		LOCK_ZONE(zone);
+		forward_cancel(zone);
+		UNLOCK_ZONE(zone);
+	}
+	RWUNLOCK(&zmgr->rwlock, isc_rwlocktype_read);
+
 }
=20
 isc_result_t
@@ -12827,12 +12958,22 @@
 	isc_event_t *e;
=20
 	/*
+	 * If we are exiting just pretend we got quota so the zone will
+	 * be cleaned up in the zone's task context.
+	 */
+	LOCK_ZONE(zone);
+	if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {
+		UNLOCK_ZONE(zone);
+		goto gotquota;
+	}
+
+	/*
 	 * Find any configured information about the server we'd
 	 * like to transfer this zone from.
 	 */
 	isc_netaddr_fromsockaddr(&masterip, &zone->masteraddr);
-	(void)dns_peerlist_peerbyaddr(zone->view->peers,
-				      &masterip, &peer);
+	(void)dns_peerlist_peerbyaddr(zone->view->peers, &masterip, &peer);
+	UNLOCK_ZONE(zone);
=20
 	/*
 	 * Determine the total maximum number of simultaneous
@@ -12856,7 +12997,11 @@
 	     x =3D ISC_LIST_NEXT(x, statelink))
 	{
 		isc_netaddr_t xip;
+
+		LOCK_ZONE(x);
 		isc_netaddr_fromsockaddr(&xip, &x->masteraddr);
+		UNLOCK_ZONE(x);
+
 		nxfrsin++;
 		if (isc_netaddr_equal(&xip, &masterip))
 			nxfrsperns++;
@@ -12869,15 +13014,14 @@
 	if (nxfrsperns >=3D maxtransfersperns)
 		return (ISC_R_QUOTA);
=20
+ gotquota:
 	/*
 	 * We have sufficient quota.  Move the zone to the "xfrin_in_progress"
 	 * list and send it an event to let it start the actual transfer in the
 	 * context of its own task.
 	 */
-	e =3D isc_event_allocate(zmgr->mctx, zmgr,
-			       DNS_EVENT_ZONESTARTXFRIN,
-			       got_transfer_quota, zone,
-			       sizeof(isc_event_t));
+	e =3D isc_event_allocate(zmgr->mctx, zmgr, DNS_EVENT_ZONESTARTXFRIN,
+			       got_transfer_quota, zone, sizeof(isc_event_t));
 	if (e =3D=3D NULL)
 		return (ISC_R_NOMEMORY);
=20
@@ -13049,8 +13193,9 @@
 	if (result !=3D ISC_R_SUCCESS)
 		goto cleanup;
=20
-	dns_zone_log(zone, ISC_LOG_WARNING, "saved '%s' as '%s'",
-		     path, buf);
+	dns_zone_log(zone, ISC_LOG_WARNING, "unable to load from '%s'; "
+		     "renaming file to '%s' for failure analysis and "
+		     "retransferring.", path, buf);
=20
  cleanup:
 	isc_mem_put(zone->mctx, buf, buflen);
@@ -13113,7 +13258,7 @@
 	return (zmgr->serialqueryrate);
 }
=20
-static isc_boolean_t
+isc_boolean_t
 dns_zonemgr_unreachable(dns_zonemgr_t *zmgr, isc_sockaddr_t *remote,
 			isc_sockaddr_t *local, isc_time_t *now)
 {
@@ -13143,6 +13288,43 @@
 }
=20
 void
+dns_zonemgr_unreachabledel(dns_zonemgr_t *zmgr, isc_sockaddr_t *remote,
+			   isc_sockaddr_t *local)
+{
+	unsigned int i;
+	isc_rwlocktype_t locktype;
+	isc_result_t result;
+
+	char master[ISC_SOCKADDR_FORMATSIZE];
+	char source[ISC_SOCKADDR_FORMATSIZE];
+
+	isc_sockaddr_format(remote, master, sizeof(master));
+	isc_sockaddr_format(local, source, sizeof(source));
+
+	REQUIRE(DNS_ZONEMGR_VALID(zmgr));
+
+	locktype =3D isc_rwlocktype_read;
+	RWLOCK(&zmgr->rwlock, locktype);
+	for (i =3D 0; i < UNREACH_CHACHE_SIZE; i++) {
+		if (isc_sockaddr_equal(&zmgr->unreachable[i].remote, remote) &&
+		    isc_sockaddr_equal(&zmgr->unreachable[i].local, local)) {
+			result =3D isc_rwlock_tryupgrade(&zmgr->rwlock);
+			if (result =3D=3D ISC_R_SUCCESS) {
+				locktype =3D isc_rwlocktype_write;
+				zmgr->unreachable[i].expire =3D 0;
+				isc_log_write(dns_lctx, DNS_LOGCATEGORY_GENERAL,
+					      DNS_LOGMODULE_ZONE, ISC_LOG_INFO,
+					      "master %s (source %s) deleted "
+					      "from unreachable cache",
+					      master, source);
+			}
+			break;
+		}
+	}
+	RWUNLOCK(&zmgr->rwlock, locktype);
+}
+
+void
 dns_zonemgr_unreachableadd(dns_zonemgr_t *zmgr, isc_sockaddr_t *remote,
 			   isc_sockaddr_t *local, isc_time_t *now)
 {
@@ -13802,11 +13984,11 @@
 	isc_result_t result;
 	isc_stdtime_t now, inception, soaexpire;
 	isc_boolean_t check_ksk, keyset_kskonly;
-	dst_key_t *zone_keys[MAXZONEKEYS];
+	dst_key_t *zone_keys[DNS_MAXZONEKEYS];
 	unsigned int nkeys =3D 0, i;
 	dns_difftuple_t *tuple;
=20
-	result =3D find_zone_keys(zone, db, ver, zone->mctx, MAXZONEKEYS,
+	result =3D find_zone_keys(zone, db, ver, zone->mctx, DNS_MAXZONEKEYS,
 				zone_keys, &nkeys);
 	if (result !=3D ISC_R_SUCCESS) {
 		dns_zone_log(zone, ISC_LOG_ERROR,
@@ -14043,6 +14225,9 @@
 	CHECK(dns_db_newversion(db, &ver));
 	CHECK(dns_db_getoriginnode(db, &node));
=20
+	TIME_NOW(&timenow);
+	now =3D isc_time_seconds(&timenow);
+
 	dns_zone_log(zone, ISC_LOG_INFO, "reconfiguring zone keys");
=20
 	/* Get the SOA record's TTL */
@@ -14092,7 +14277,8 @@
 			goto trylater;
 		}
=20
-		/* See if any pre-existing keys have newly become active;
+		/*
+		 * See if any pre-existing keys have newly become active;
 		 * also, see if any new key is for a new algorithm, as in that
 		 * event, we need to sign the zone fully.  (If there's a new
 		 * key, but it's for an already-existing algorithm, then
@@ -14142,7 +14328,6 @@
 	dns_db_closeversion(db, &ver, commit);
=20
 	if (commit) {
-		isc_time_t timenow;
 		dns_difftuple_t *tuple;
=20
 		LOCK_ZONE(zone);
@@ -14150,7 +14335,6 @@
=20
 		zone_needdump(zone, DNS_DUMP_DELAY);
=20
-		TIME_NOW(&timenow);
 		zone_settimer(zone, &timenow);
=20
 		/* Remove any signatures from removed keys.  */
@@ -14260,13 +14444,6 @@
 		UNLOCK_ZONE(zone);
 	}
=20
-	/*
-	 * If we are doing automatic key maintenance and the key metadata
-	 * indicates there is a key change event scheduled in the future,
-	 * set the key refresh timer.
-	 */
-	isc_stdtime_get(&now);
-	TIME_NOW(&timenow);
 	isc_time_settoepoch(&zone->refreshkeytime);
=20
 	/*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/zonekey.c
--- a/head/contrib/bind9/lib/dns/zonekey.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/zonekey.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zonekey.c,v 1.9 2007-06-19 23:47:16 tbox Exp $ */
+/* $Id: zonekey.c,v 1.9 2007/06/19 23:47:16 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/dns/zt.c
--- a/head/contrib/bind9/lib/dns/zt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/dns/zt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: zt.c,v 1.47.814.3 2011-03-19 23:47:24 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/Makefile=
.in
--- a/head/contrib/bind9/lib/export/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/export/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/dns/Make=
file.in
--- a/head/contrib/bind9/lib/export/dns/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/export/dns/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009-2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.8.14.2 2011-05-16 23:47:16 tbox Exp $
+# $Id$
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/dns
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/dns/incl=
ude/Makefile.in
--- a/head/contrib/bind9/lib/export/dns/include/Makefile.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/dns/include/Makefile.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/dns/incl=
ude/dns/Makefile.in
--- a/head/contrib/bind9/lib/export/dns/include/dns/Makefile.in	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/dns/include/dns/Makefile.in	Tue Apr 17 =
11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4 2009-09-18 07:18:04 jinmei Exp $
+# $Id: Makefile.in,v 1.4 2009/09/18 07:18:04 jinmei Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/dns/incl=
ude/dst/Makefile.in
--- a/head/contrib/bind9/lib/export/dns/include/dst/Makefile.in	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/dns/include/dst/Makefile.in	Tue Apr 17 =
11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/irs/Make=
file.in
--- a/head/contrib/bind9/lib/export/irs/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/export/irs/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4.244.2 2011-05-16 23:47:16 tbox Exp $
+# $Id$
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/irs
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/irs/incl=
ude/Makefile.in
--- a/head/contrib/bind9/lib/export/irs/include/Makefile.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/irs/include/Makefile.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,9 +12,9 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id$
=20
-srcdir =3D	@srdir@
+srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/irs/incl=
ude/irs/Makefile.in
--- a/head/contrib/bind9/lib/export/irs/include/irs/Makefile.in	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/irs/include/irs/Makefile.in	Tue Apr 17 =
11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/Make=
file.in
--- a/head/contrib/bind9/lib/export/isc/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/export/isc/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.8 2010-06-09 23:50:58 tbox Exp $
+# $Id: Makefile.in,v 1.8 2010/06/09 23:50:58 tbox Exp $
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/isc
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/incl=
ude/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/include/Makefile.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/include/Makefile.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,9 +12,9 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id$
=20
-srcdir =3D	@srdir@
+srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/incl=
ude/isc/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/include/isc/Makefile.in	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/include/isc/Makefile.in	Tue Apr 17 =
11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-12-05 23:31:41 each Exp $
+# $Id: Makefile.in,v 1.3 2009/12/05 23:31:41 each Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/incl=
ude/isc/bind9.h
--- a/head/contrib/bind9/lib/export/isc/include/isc/bind9.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/include/isc/bind9.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: bind9.h,v 1.2 2009-12-05 23:31:41 each Exp $ */
+/* $Id: bind9.h,v 1.2 2009/12/05 23:31:41 each Exp $ */
=20
 #ifndef ISC_BIND9_H
 #define ISC_BIND9_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/nls/=
Makefile.in
--- a/head/contrib/bind9/lib/export/isc/nls/Makefile.in	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/nls/Makefile.in	Tue Apr 17 11:51:51=
 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/isc/nls
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/noth=
reads/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/nothreads/Makefile.in	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/nothreads/Makefile.in	Tue Apr 17 11=
:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.5 2010-06-09 23:50:58 tbox Exp $
+# $Id: Makefile.in,v 1.5 2010/06/09 23:50:58 tbox Exp $
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/isc/nothreads
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/noth=
reads/include/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/nothreads/include/Makefile.in	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/nothreads/include/Makefile.in	Tue A=
pr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,9 +12,9 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id$
=20
-srcdir =3D	@srdir@
+srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/noth=
reads/include/isc/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/nothreads/include/isc/Makefile.in	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/nothreads/include/isc/Makefile.in	T=
ue Apr 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id: Makefile.in,v 1.2 2009/09/01 00:22:27 jinmei Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/pthr=
eads/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/pthreads/Makefile.in	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/pthreads/Makefile.in	Tue Apr 17 11:=
51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/isc/pthreads
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/pthr=
eads/include/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/pthreads/include/Makefile.in	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/pthreads/include/Makefile.in	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,9 +12,9 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id$
=20
-srcdir =3D	@srdir@
+srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/pthr=
eads/include/isc/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/pthreads/include/isc/Makefile.in	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/pthreads/include/isc/Makefile.in	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id: Makefile.in,v 1.2 2009/09/01 00:22:27 jinmei Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/unix=
/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/unix/Makefile.in	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/unix/Makefile.in	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/isc/unix
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/unix=
/include/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/unix/include/Makefile.in	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/unix/include/Makefile.in	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,9 +12,9 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id$
=20
-srcdir =3D	@srdir@
+srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isc/unix=
/include/isc/Makefile.in
--- a/head/contrib/bind9/lib/export/isc/unix/include/isc/Makefile.in	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isc/unix/include/isc/Makefile.in	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id: Makefile.in,v 1.2 2009/09/01 00:22:27 jinmei Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isccfg/M=
akefile.in
--- a/head/contrib/bind9/lib/export/isccfg/Makefile.in	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/export/isccfg/Makefile.in	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4.244.2 2011-05-16 23:47:17 tbox Exp $
+# $Id$
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/isccfg
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isccfg/i=
nclude/Makefile.in
--- a/head/contrib/bind9/lib/export/isccfg/include/Makefile.in	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isccfg/include/Makefile.in	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
 #
 # Permission to use, copy, modify, and/or distribute this software for any
 # purpose with or without fee is hereby granted, provided that the above
@@ -12,9 +12,9 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2009-09-01 00:22:27 jinmei Exp $
+# $Id$
=20
-srcdir =3D	@srdir@
+srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/isccfg/i=
nclude/isccfg/Makefile.in
--- a/head/contrib/bind9/lib/export/isccfg/include/isccfg/Makefile.in	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/isccfg/include/isccfg/Makefile.in	Tue A=
pr 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
Makefile-postinstall.in
--- a/head/contrib/bind9/lib/export/samples/Makefile-postinstall.in	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/samples/Makefile-postinstall.in	Tue Apr=
 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile-postinstall.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile-postinstall.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 #prefix =3D	@prefix@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
Makefile.in
--- a/head/contrib/bind9/lib/export/samples/Makefile.in	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/export/samples/Makefile.in	Tue Apr 17 11:51:51=
 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4 2009-12-05 23:31:41 each Exp $
+# $Id: Makefile.in,v 1.4 2009/12/05 23:31:41 each Exp $
=20
 srcdir =3D	@srcdir@
 top_srcdir =3D	@top_srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
nsprobe.c
--- a/head/contrib/bind9/lib/export/samples/nsprobe.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/export/samples/nsprobe.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009-2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: nsprobe.c,v 1.7.180.3 2011-04-05 06:35:00 marka Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
sample-async.c
--- a/head/contrib/bind9/lib/export/samples/sample-async.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/samples/sample-async.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sample-async.c,v 1.5 2009-09-29 15:06:07 fdupont Exp $ */
+/* $Id: sample-async.c,v 1.5 2009/09/29 15:06:07 fdupont Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
sample-gai.c
--- a/head/contrib/bind9/lib/export/samples/sample-gai.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/export/samples/sample-gai.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sample-gai.c,v 1.4 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: sample-gai.c,v 1.4 2009/09/02 23:48:02 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
sample-request.c
--- a/head/contrib/bind9/lib/export/samples/sample-request.c	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/samples/sample-request.c	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sample-request.c,v 1.5 2009-09-29 15:06:07 fdupont Exp $ */
+/* $Id: sample-request.c,v 1.5 2009/09/29 15:06:07 fdupont Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
sample-update.c
--- a/head/contrib/bind9/lib/export/samples/sample-update.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/export/samples/sample-update.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sample-update.c,v 1.10 2010-12-09 00:54:34 marka Exp $ */
+/* $Id: sample-update.c,v 1.10 2010/12/09 00:54:34 marka Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/export/samples/=
sample.c
--- a/head/contrib/bind9/lib/export/samples/sample.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/export/samples/sample.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sample.c,v 1.5 2009-09-29 15:06:07 fdupont Exp $ */
+/* $Id: sample.c,v 1.5 2009/09/29 15:06:07 fdupont Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/Makefile.in
--- a/head/contrib/bind9/lib/irs/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/irs/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/api
--- a/head/contrib/bind9/lib/irs/api	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/irs/api	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,8 @@
+# LIBINTERFACE ranges
+# 9.6: 50-59, 110-119
+# 9.7: 60-79
+# 9.8: 80-89
+# 9.9: 90-109
 LIBINTERFACE =3D 80
-LIBREVISION =3D 1
+LIBREVISION =3D 2
 LIBAGE =3D 0
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/context.c
--- a/head/contrib/bind9/lib/irs/context.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/irs/context.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: context.c,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: context.c,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/dnsconf.c
--- a/head/contrib/bind9/lib/irs/dnsconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/irs/dnsconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnsconf.c,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: dnsconf.c,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/gai_strerro=
r.c
--- a/head/contrib/bind9/lib/irs/gai_strerror.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/irs/gai_strerror.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gai_strerror.c,v 1.5 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: gai_strerror.c,v 1.5 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file gai_strerror.c
  * gai_strerror() returns an error message corresponding to an
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/getaddrinfo=
.c
--- a/head/contrib/bind9/lib/irs/getaddrinfo.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/irs/getaddrinfo.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getaddrinfo.c,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: getaddrinfo.c,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/getnameinfo=
.c
--- a/head/contrib/bind9/lib/irs/getnameinfo.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/irs/getnameinfo.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC=
")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getnameinfo.c,v 1.4.346.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/Mak=
efile.in
--- a/head/contrib/bind9/lib/irs/include/Makefile.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/irs/include/Makefile.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/Makefile.in
--- a/head/contrib/bind9/lib/irs/include/irs/Makefile.in	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/Makefile.in	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.3 2009-09-02 23:48:02 tbox Exp $
+# $Id: Makefile.in,v 1.3 2009/09/02 23:48:02 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/context.h
--- a/head/contrib/bind9/lib/irs/include/irs/context.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/context.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: context.h,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: context.h,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef IRS_CONTEXT_H
 #define IRS_CONTEXT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/dnsconf.h
--- a/head/contrib/bind9/lib/irs/include/irs/dnsconf.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/dnsconf.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnsconf.h,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: dnsconf.h,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef IRS_DNSCONF_H
 #define IRS_DNSCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/netdb.h.in
--- a/head/contrib/bind9/lib/irs/include/irs/netdb.h.in	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/netdb.h.in	Tue Apr 17 11:51:51=
 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: netdb.h.in,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: netdb.h.in,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/platform.h.in
--- a/head/contrib/bind9/lib/irs/include/irs/platform.h.in	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/platform.h.in	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: platform.h.in,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: platform.h.in,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/resconf.h
--- a/head/contrib/bind9/lib/irs/include/irs/resconf.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/resconf.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: resconf.h,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: resconf.h,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef IRS_RESCONF_H
 #define IRS_RESCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/types.h
--- a/head/contrib/bind9/lib/irs/include/irs/types.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/types.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: types.h,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: types.h,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef IRS_TYPES_H
 #define IRS_TYPES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/include/irs=
/version.h
--- a/head/contrib/bind9/lib/irs/include/irs/version.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/irs/include/irs/version.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.h,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: version.h,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/resconf.c
--- a/head/contrib/bind9/lib/irs/resconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/irs/resconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2011, 2012  Internet Systems Consortium, Inc. ("ISC=
")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: resconf.c,v 1.3.346.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file resconf.c */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/irs/version.c
--- a/head/contrib/bind9/lib/irs/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/irs/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.c,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: version.c,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
 # Copyright (C) 1998-2003  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.109.108.2 2011-07-08 23:47:16 tbox Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/alpha/Makef=
ile.in
--- a/head/contrib/bind9/lib/isc/alpha/Makefile.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/alpha/Makefile.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/alpha/inclu=
de/Makefile.in
--- a/head/contrib/bind9/lib/isc/alpha/include/Makefile.in	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/alpha/include/Makefile.in	Tue Apr 17 11:51=
:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/alpha/inclu=
de/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/alpha/include/isc/Makefile.in	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/alpha/include/isc/Makefile.in	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/alpha/inclu=
de/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/alpha/include/isc/atomic.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/alpha/include/isc/atomic.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.7 2009-04-08 06:48:23 tbox Exp $ */
+/* $Id: atomic.h,v 1.7 2009/04/08 06:48:23 tbox Exp $ */
=20
 /*
  * This code was written based on FreeBSD's kernel source whose copyright
@@ -46,7 +46,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/contrib/bind9/lib/isc/alpha/include/isc/atomic.h 224092 =
2011-07-16 11:12:09Z dougb $
+ * $FreeBSD: head/contrib/bind9/lib/isc/alpha/include/isc/atomic.h 233914 =
2012-04-05 04:29:35Z dougb $
  */
=20
 #ifndef ISC_ATOMIC_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/api
--- a/head/contrib/bind9/lib/isc/api	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/api	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,8 @@
+# LIBINTERFACE ranges
+# 9.6: 50-59, 110-119
+# 9.7: 60-79
+# 9.8: 80-89
+# 9.9: 90-109
 LIBINTERFACE =3D 83
-LIBREVISION =3D 1
+LIBREVISION =3D 5
 LIBAGE =3D 0
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/app_api.c
--- a/head/contrib/bind9/lib/isc/app_api.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/app_api.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: app_api.c,v 1.5 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: app_api.c,v 1.5 2009/09/02 23:48:02 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/assertions.c
--- a/head/contrib/bind9/lib/isc/assertions.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/assertions.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: assertions.c,v 1.26 2009-09-29 15:06:07 fdupont Exp $ */
+/* $Id: assertions.c,v 1.26 2009/09/29 15:06:07 fdupont Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/backtrace-e=
mptytbl.c
--- a/head/contrib/bind9/lib/isc/backtrace-emptytbl.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/backtrace-emptytbl.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: backtrace-emptytbl.c,v 1.3 2009-09-01 20:13:44 each Exp $ */
+/* $Id: backtrace-emptytbl.c,v 1.3 2009/09/01 20:13:44 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/backtrace.c
--- a/head/contrib/bind9/lib/isc/backtrace.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/backtrace.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: backtrace.c,v 1.3 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: backtrace.c,v 1.3 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/base32.c
--- a/head/contrib/bind9/lib/isc/base32.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/base32.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: base32.c,v 1.6 2009-10-21 01:22:29 each Exp $ */
+/* $Id: base32.c,v 1.6 2009/10/21 01:22:29 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/base64.c
--- a/head/contrib/bind9/lib/isc/base64.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/base64.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: base64.c,v 1.34 2009-10-21 23:48:05 tbox Exp $ */
+/* $Id: base64.c,v 1.34 2009/10/21 23:48:05 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/bitstring.c
--- a/head/contrib/bind9/lib/isc/bitstring.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/bitstring.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: bitstring.c,v 1.17 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: bitstring.c,v 1.17 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/buffer.c
--- a/head/contrib/bind9/lib/isc/buffer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/buffer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: buffer.c,v 1.49 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: buffer.c,v 1.49 2008/09/25 04:02:39 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/bufferlist.c
--- a/head/contrib/bind9/lib/isc/bufferlist.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/bufferlist.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: bufferlist.c,v 1.17 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: bufferlist.c,v 1.17 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/commandline=
.c
--- a/head/contrib/bind9/lib/isc/commandline.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/isc/commandline.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -48,7 +48,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: commandline.c,v 1.22 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: commandline.c,v 1.22 2008/09/25 04:02:39 tbox Exp $ */
=20
 /*! \file
  * This file was adapted from the NetBSD project's source tree, RCS ID:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/entropy.c
--- a/head/contrib/bind9/lib/isc/entropy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/entropy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: entropy.c,v 1.22 2010-08-10 23:48:19 tbox Exp $ */
+/* $Id: entropy.c,v 1.22 2010/08/10 23:48:19 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/error.c
--- a/head/contrib/bind9/lib/isc/error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: error.c,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: error.c,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/event.c
--- a/head/contrib/bind9/lib/isc/event.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/event.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: event.c,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: event.c,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  * \file
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/fsaccess.c
--- a/head/contrib/bind9/lib/isc/fsaccess.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/fsaccess.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: fsaccess.c,v 1.10 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: fsaccess.c,v 1.10 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/hash.c
--- a/head/contrib/bind9/lib/isc/hash.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/hash.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hash.c,v 1.16 2009-09-01 00:22:28 jinmei Exp $ */
+/* $Id: hash.c,v 1.16 2009/09/01 00:22:28 jinmei Exp $ */
=20
 /*! \file
  * Some portion of this code was derived from universal hash function
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/heap.c
--- a/head/contrib/bind9/lib/isc/heap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/heap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2010, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2010-2012  Internet Systems Consortium, Inc. (=
"ISC")
  * Copyright (C) 1997-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: heap.c,v 1.39.150.2 2011-03-03 23:47:09 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file
  * Heap implementation of priority queues adapted from the following:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/hex.c
--- a/head/contrib/bind9/lib/isc/hex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/hex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hex.c,v 1.20 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: hex.c,v 1.20 2008/09/25 04:02:39 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/hmacmd5.c
--- a/head/contrib/bind9/lib/isc/hmacmd5.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/hmacmd5.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hmacmd5.c,v 1.16 2009-02-06 23:47:42 tbox Exp $ */
+/* $Id: hmacmd5.c,v 1.16 2009/02/06 23:47:42 tbox Exp $ */
=20
 /*! \file
  * This code implements the HMAC-MD5 keyed hash algorithm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/hmacsha.c
--- a/head/contrib/bind9/lib/isc/hmacsha.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/hmacsha.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005-2007, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2005-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hmacsha.c,v 1.10 2009-02-06 23:47:42 tbox Exp $ */
+/* $Id$ */
=20
 /*
  * This code implements the HMAC-SHA1, HMAC-SHA224, HMAC-SHA256, HMAC-SHA3=
84
@@ -224,8 +224,7 @@
 void
 isc_hmacsha1_invalidate(isc_hmacsha1_t *ctx) {
 	isc_sha1_invalidate(&ctx->sha1ctx);
-	memset(ctx->key, 0, sizeof(ctx->key));
-	memset(ctx, 0, sizeof(ctx));
+	memset(ctx, 0, sizeof(*ctx));
 }
=20
 /*
@@ -292,8 +291,7 @@
=20
 void
 isc_hmacsha224_invalidate(isc_hmacsha224_t *ctx) {
-	memset(ctx->key, 0, sizeof(ctx->key));
-	memset(ctx, 0, sizeof(ctx));
+	memset(ctx, 0, sizeof(*ctx));
 }
=20
 /*
@@ -359,8 +357,7 @@
=20
 void
 isc_hmacsha256_invalidate(isc_hmacsha256_t *ctx) {
-	memset(ctx->key, 0, sizeof(ctx->key));
-	memset(ctx, 0, sizeof(ctx));
+	memset(ctx, 0, sizeof(*ctx));
 }
=20
 /*
@@ -426,8 +423,7 @@
=20
 void
 isc_hmacsha384_invalidate(isc_hmacsha384_t *ctx) {
-	memset(ctx->key, 0, sizeof(ctx->key));
-	memset(ctx, 0, sizeof(ctx));
+	memset(ctx, 0, sizeof(*ctx));
 }
=20
 /*
@@ -493,8 +489,7 @@
=20
 void
 isc_hmacsha512_invalidate(isc_hmacsha512_t *ctx) {
-	memset(ctx->key, 0, sizeof(ctx->key));
-	memset(ctx, 0, sizeof(ctx));
+	memset(ctx, 0, sizeof(*ctx));
 }
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/httpd.c
--- a/head/contrib/bind9/lib/isc/httpd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/httpd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2008, 2010, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2006-2008, 2010-2012  Internet Systems Consortium, Inc. (=
"ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: httpd.c,v 1.20.40.3 2011-03-11 06:47:07 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/ia64/Makefi=
le.in
--- a/head/contrib/bind9/lib/isc/ia64/Makefile.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/isc/ia64/Makefile.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/ia64/includ=
e/Makefile.in
--- a/head/contrib/bind9/lib/isc/ia64/include/Makefile.in	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/ia64/include/Makefile.in	Tue Apr 17 11:51:=
51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/ia64/includ=
e/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/ia64/include/isc/Makefile.in	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/ia64/include/isc/Makefile.in	Tue Apr 17 11=
:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/ia64/includ=
e/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/ia64/include/isc/atomic.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/ia64/include/isc/atomic.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.7 2009-06-24 02:22:50 marka Exp $ */
+/* $Id: atomic.h,v 1.7 2009/06/24 02:22:50 marka Exp $ */
=20
 #ifndef ISC_ATOMIC_H
 #define ISC_ATOMIC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/Mak=
efile.in
--- a/head/contrib/bind9/lib/isc/include/Makefile.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/Makefile.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.13 2007-06-19 23:47:18 tbox Exp $
+# $Id: Makefile.in,v 1.13 2007/06/19 23:47:18 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/Makefile.in
--- a/head/contrib/bind9/lib/isc/include/isc/Makefile.in	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/Makefile.in	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
 # Copyright (C) 1998-2001, 2003  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.68 2009-12-05 23:31:41 each Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
@@ -29,7 +29,7 @@
 HEADERS =3D	app.h assertions.h base64.h bind9.h bitstring.h boolean.h \
 		buffer.h bufferlist.h commandline.h entropy.h error.h event.h \
 		eventclass.h file.h formatcheck.h fsaccess.h \
-		hash.h heap.h hex.h hmacmd5.h \
+		hash.h heap.h hex.h hmacmd5.h hmacsha.h \
 		httpd.h \
 		interfaceiter.h @ISC_IPV6_H@ iterated_hash.h lang.h lex.h \
 		lfsr.h lib.h list.h log.h \
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/app.h
--- a/head/contrib/bind9/lib/isc/include/isc/app.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/app.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: app.h,v 1.11 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: app.h,v 1.11 2009/09/02 23:48:03 tbox Exp $ */
=20
 #ifndef ISC_APP_H
 #define ISC_APP_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/assertions.h
--- a/head/contrib/bind9/lib/isc/include/isc/assertions.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/assertions.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -16,7 +16,7 @@
  */
=20
 /*
- * $Id: assertions.h,v 1.28 2009-09-29 23:48:04 tbox Exp $
+ * $Id: assertions.h,v 1.28 2009/09/29 23:48:04 tbox Exp $
  */
 /*! \file isc/assertions.h
  */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/backtrace.h
--- a/head/contrib/bind9/lib/isc/include/isc/backtrace.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/backtrace.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: backtrace.h,v 1.2 2009-09-01 18:40:25 jinmei Exp $ */
+/* $Id: backtrace.h,v 1.2 2009/09/01 18:40:25 jinmei Exp $ */
=20
 /*! \file isc/backtrace.h
  * \brief provide a back trace of the running process to help debug proble=
ms.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/base32.h
--- a/head/contrib/bind9/lib/isc/include/isc/base32.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/base32.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: base32.h,v 1.3 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: base32.h,v 1.3 2008/09/25 04:02:39 tbox Exp $ */
=20
 #ifndef ISC_BASE32_H
 #define ISC_BASE32_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/base64.h
--- a/head/contrib/bind9/lib/isc/include/isc/base64.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/base64.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: base64.h,v 1.22 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: base64.h,v 1.22 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_BASE64_H
 #define ISC_BASE64_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/bind9.h
--- a/head/contrib/bind9/lib/isc/include/isc/bind9.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/bind9.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: bind9.h,v 1.2 2009-12-05 23:31:41 each Exp $ */
+/* $Id: bind9.h,v 1.2 2009/12/05 23:31:41 each Exp $ */
=20
 #ifndef ISC_BIND9_H
 #define ISC_BIND9_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/bitstring.h
--- a/head/contrib/bind9/lib/isc/include/isc/bitstring.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/bitstring.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: bitstring.h,v 1.14 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: bitstring.h,v 1.14 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_BITSTRING_H
 #define ISC_BITSTRING_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/boolean.h
--- a/head/contrib/bind9/lib/isc/include/isc/boolean.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/boolean.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: boolean.h,v 1.19 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: boolean.h,v 1.19 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_BOOLEAN_H
 #define ISC_BOOLEAN_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/buffer.h
--- a/head/contrib/bind9/lib/isc/include/isc/buffer.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/buffer.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: buffer.h,v 1.55 2010-12-20 23:47:21 tbox Exp $ */
+/* $Id: buffer.h,v 1.55 2010/12/20 23:47:21 tbox Exp $ */
=20
 #ifndef ISC_BUFFER_H
 #define ISC_BUFFER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/bufferlist.h
--- a/head/contrib/bind9/lib/isc/include/isc/bufferlist.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/bufferlist.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: bufferlist.h,v 1.17 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: bufferlist.h,v 1.17 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_BUFFERLIST_H
 #define ISC_BUFFERLIST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/commandline.h
--- a/head/contrib/bind9/lib/isc/include/isc/commandline.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/commandline.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: commandline.h,v 1.16 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: commandline.h,v 1.16 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_COMMANDLINE_H
 #define ISC_COMMANDLINE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/entropy.h
--- a/head/contrib/bind9/lib/isc/include/isc/entropy.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/entropy.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: entropy.h,v 1.35 2009-10-19 02:37:08 marka Exp $ */
+/* $Id: entropy.h,v 1.35 2009/10/19 02:37:08 marka Exp $ */
=20
 #ifndef ISC_ENTROPY_H
 #define ISC_ENTROPY_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/error.h
--- a/head/contrib/bind9/lib/isc/include/isc/error.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/error.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: error.h,v 1.22 2009-09-29 23:48:04 tbox Exp $ */
+/* $Id: error.h,v 1.22 2009/09/29 23:48:04 tbox Exp $ */
=20
 #ifndef ISC_ERROR_H
 #define ISC_ERROR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/event.h
--- a/head/contrib/bind9/lib/isc/include/isc/event.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/event.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: event.h,v 1.34 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: event.h,v 1.34 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_EVENT_H
 #define ISC_EVENT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/eventclass.h
--- a/head/contrib/bind9/lib/isc/include/isc/eventclass.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/eventclass.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: eventclass.h,v 1.18 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: eventclass.h,v 1.18 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_EVENTCLASS_H
 #define ISC_EVENTCLASS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/file.h
--- a/head/contrib/bind9/lib/isc/include/isc/file.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/file.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: file.h,v 1.39.10.2 2011-03-04 23:47:28 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_FILE_H
 #define ISC_FILE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/formatcheck.h
--- a/head/contrib/bind9/lib/isc/include/isc/formatcheck.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/formatcheck.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: formatcheck.h,v 1.13 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: formatcheck.h,v 1.13 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_FORMATCHECK_H
 #define ISC_FORMATCHECK_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/fsaccess.h
--- a/head/contrib/bind9/lib/isc/include/isc/fsaccess.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/fsaccess.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: fsaccess.h,v 1.16 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: fsaccess.h,v 1.16 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef ISC_FSACCESS_H
 #define ISC_FSACCESS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/hash.h
--- a/head/contrib/bind9/lib/isc/include/isc/hash.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/hash.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hash.h,v 1.12 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: hash.h,v 1.12 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef ISC_HASH_H
 #define ISC_HASH_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/heap.h
--- a/head/contrib/bind9/lib/isc/include/isc/heap.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/heap.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: heap.h,v 1.26 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: heap.h,v 1.26 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef ISC_HEAP_H
 #define ISC_HEAP_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/hex.h
--- a/head/contrib/bind9/lib/isc/include/isc/hex.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/hex.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hex.h,v 1.13 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: hex.h,v 1.13 2008/09/25 04:02:39 tbox Exp $ */
=20
 #ifndef ISC_HEX_H
 #define ISC_HEX_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/hmacmd5.h
--- a/head/contrib/bind9/lib/isc/include/isc/hmacmd5.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/hmacmd5.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hmacmd5.h,v 1.14 2009-02-06 23:47:42 tbox Exp $ */
+/* $Id: hmacmd5.h,v 1.14 2009/02/06 23:47:42 tbox Exp $ */
=20
 /*! \file isc/hmacmd5.h
  * \brief This is the header file for the HMAC-MD5 keyed hash algorithm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/hmacsha.h
--- a/head/contrib/bind9/lib/isc/include/isc/hmacsha.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/hmacsha.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hmacsha.h,v 1.9 2009-02-06 23:47:42 tbox Exp $ */
+/* $Id: hmacsha.h,v 1.9 2009/02/06 23:47:42 tbox Exp $ */
=20
 /*! \file isc/hmacsha.h
  * This is the header file for the HMAC-SHA1, HMAC-SHA224, HMAC-SHA256,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/httpd.h
--- a/head/contrib/bind9/lib/isc/include/isc/httpd.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/httpd.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: httpd.h,v 1.9 2008-08-08 05:06:49 marka Exp $ */
+/* $Id: httpd.h,v 1.9 2008/08/08 05:06:49 marka Exp $ */
=20
 #ifndef ISC_HTTPD_H
 #define ISC_HTTPD_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/interfaceiter.h
--- a/head/contrib/bind9/lib/isc/include/isc/interfaceiter.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/interfaceiter.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: interfaceiter.h,v 1.17 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: interfaceiter.h,v 1.17 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_INTERFACEITER_H
 #define ISC_INTERFACEITER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/ipv6.h
--- a/head/contrib/bind9/lib/isc/include/isc/ipv6.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/ipv6.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ipv6.h,v 1.24 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: ipv6.h,v 1.24 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_IPV6_H
 #define ISC_IPV6_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/iterated_hash.h
--- a/head/contrib/bind9/lib/isc/include/isc/iterated_hash.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/iterated_hash.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: iterated_hash.h,v 1.3 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: iterated_hash.h,v 1.3 2008/09/25 04:02:39 tbox Exp $ */
=20
 #ifndef ISC_ITERATED_HASH_H
 #define ISC_ITERATED_HASH_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/lang.h
--- a/head/contrib/bind9/lib/isc/include/isc/lang.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/lang.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lang.h,v 1.13 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: lang.h,v 1.13 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_LANG_H
 #define ISC_LANG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/lex.h
--- a/head/contrib/bind9/lib/isc/include/isc/lex.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/lex.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lex.h,v 1.37 2008-05-30 23:47:01 tbox Exp $ */
+/* $Id: lex.h,v 1.37 2008/05/30 23:47:01 tbox Exp $ */
=20
 #ifndef ISC_LEX_H
 #define ISC_LEX_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/lfsr.h
--- a/head/contrib/bind9/lib/isc/include/isc/lfsr.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/lfsr.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lfsr.h,v 1.17 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: lfsr.h,v 1.17 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_LFSR_H
 #define ISC_LFSR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/lib.h
--- a/head/contrib/bind9/lib/isc/include/isc/lib.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/lib.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lib.h,v 1.16 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: lib.h,v 1.16 2009/09/02 23:48:03 tbox Exp $ */
=20
 #ifndef ISC_LIB_H
 #define ISC_LIB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/list.h
--- a/head/contrib/bind9/lib/isc/include/isc/list.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/list.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2006, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2006, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 1997-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: list.h,v 1.24 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_LIST_H
 #define ISC_LIST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/log.h
--- a/head/contrib/bind9/lib/isc/include/isc/log.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/log.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.h,v 1.59 2009-02-16 02:01:16 marka Exp $ */
+/* $Id: log.h,v 1.59 2009/02/16 02:01:16 marka Exp $ */
=20
 #ifndef ISC_LOG_H
 #define ISC_LOG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/magic.h
--- a/head/contrib/bind9/lib/isc/include/isc/magic.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/magic.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: magic.h,v 1.18 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: magic.h,v 1.18 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_MAGIC_H
 #define ISC_MAGIC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/md5.h
--- a/head/contrib/bind9/lib/isc/include/isc/md5.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/md5.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: md5.h,v 1.20 2010-01-07 23:48:54 tbox Exp $ */
+/* $Id: md5.h,v 1.20 2010/01/07 23:48:54 tbox Exp $ */
=20
 /*! \file isc/md5.h
  * \brief This is the header file for the MD5 message-digest algorithm.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/mem.h
--- a/head/contrib/bind9/lib/isc/include/isc/mem.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/mem.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2010, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1997-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mem.h,v 1.89 2010-08-11 22:54:58 jinmei Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_MEM_H
 #define ISC_MEM_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/msgcat.h
--- a/head/contrib/bind9/lib/isc/include/isc/msgcat.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/msgcat.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: msgcat.h,v 1.13 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: msgcat.h,v 1.13 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_MSGCAT_H
 #define ISC_MSGCAT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/msgs.h
--- a/head/contrib/bind9/lib/isc/include/isc/msgs.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/msgs.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: msgs.h,v 1.19 2009-10-01 23:48:08 tbox Exp $ */
+/* $Id: msgs.h,v 1.19 2009/10/01 23:48:08 tbox Exp $ */
=20
 #ifndef ISC_MSGS_H
 #define ISC_MSGS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/mutexblock.h
--- a/head/contrib/bind9/lib/isc/include/isc/mutexblock.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/mutexblock.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mutexblock.h,v 1.17 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: mutexblock.h,v 1.17 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_MUTEXBLOCK_H
 #define ISC_MUTEXBLOCK_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/namespace.h
--- a/head/contrib/bind9/lib/isc/include/isc/namespace.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/namespace.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009, 2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2010, 2012  Internet Systems Consortium, Inc. ("ISC=
")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: namespace.h,v 1.9 2010-12-04 13:25:59 marka Exp $ */
+/* $Id$ */
=20
 #ifndef ISCAPI_NAMESPACE_H
 #define ISCAPI_NAMESPACE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/netaddr.h
--- a/head/contrib/bind9/lib/isc/include/isc/netaddr.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/netaddr.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: netaddr.h,v 1.37 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: netaddr.h,v 1.37 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef ISC_NETADDR_H
 #define ISC_NETADDR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/netscope.h
--- a/head/contrib/bind9/lib/isc/include/isc/netscope.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/netscope.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: netscope.h,v 1.13 2009-06-25 23:48:02 tbox Exp $ */
+/* $Id: netscope.h,v 1.13 2009/06/25 23:48:02 tbox Exp $ */
=20
 #ifndef ISC_NETSCOPE_H
 #define ISC_NETSCOPE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/ondestroy.h
--- a/head/contrib/bind9/lib/isc/include/isc/ondestroy.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/ondestroy.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ondestroy.h,v 1.14 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: ondestroy.h,v 1.14 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_ONDESTROY_H
 #define ISC_ONDESTROY_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/os.h
--- a/head/contrib/bind9/lib/isc/include/isc/os.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/isc/include/isc/os.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: os.h,v 1.12 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: os.h,v 1.12 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_OS_H
 #define ISC_OS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/parseint.h
--- a/head/contrib/bind9/lib/isc/include/isc/parseint.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/parseint.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: parseint.h,v 1.9 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: parseint.h,v 1.9 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_PARSEINT_H
 #define ISC_PARSEINT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/platform.h.in
--- a/head/contrib/bind9/lib/isc/include/isc/platform.h.in	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/platform.h.in	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: platform.h.in,v 1.56 2010-12-18 01:56:23 each Exp $ */
+/* $Id: platform.h.in,v 1.56 2010/12/18 01:56:23 each Exp $ */
=20
 #ifndef ISC_PLATFORM_H
 #define ISC_PLATFORM_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/portset.h
--- a/head/contrib/bind9/lib/isc/include/isc/portset.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/portset.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: portset.h,v 1.6 2009-06-25 05:28:34 marka Exp $ */
+/* $Id: portset.h,v 1.6 2009/06/25 05:28:34 marka Exp $ */
=20
 /*! \file isc/portset.h
  * \brief Transport Protocol Port Manipulation Module
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/print.h
--- a/head/contrib/bind9/lib/isc/include/isc/print.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/print.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: print.h,v 1.26 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: print.h,v 1.26 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_PRINT_H
 #define ISC_PRINT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/quota.h
--- a/head/contrib/bind9/lib/isc/include/isc/quota.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/quota.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: quota.h,v 1.16 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: quota.h,v 1.16 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_QUOTA_H
 #define ISC_QUOTA_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/radix.h
--- a/head/contrib/bind9/lib/isc/include/isc/radix.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/radix.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: radix.h,v 1.13 2008-12-01 23:47:45 tbox Exp $ */
+/* $Id: radix.h,v 1.13 2008/12/01 23:47:45 tbox Exp $ */
=20
 /*
  * This source was adapted from MRT's RCS Ids:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/random.h
--- a/head/contrib/bind9/lib/isc/include/isc/random.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/random.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: random.h,v 1.20 2009-01-17 23:47:43 tbox Exp $ */
+/* $Id: random.h,v 1.20 2009/01/17 23:47:43 tbox Exp $ */
=20
 #ifndef ISC_RANDOM_H
 #define ISC_RANDOM_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/ratelimiter.h
--- a/head/contrib/bind9/lib/isc/include/isc/ratelimiter.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/ratelimiter.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ratelimiter.h,v 1.23 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id: ratelimiter.h,v 1.23 2009/01/18 23:48:14 tbox Exp $ */
=20
 #ifndef ISC_RATELIMITER_H
 #define ISC_RATELIMITER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/refcount.h
--- a/head/contrib/bind9/lib/isc/include/isc/refcount.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/refcount.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: refcount.h,v 1.17 2009-09-29 23:48:04 tbox Exp $ */
+/* $Id: refcount.h,v 1.17 2009/09/29 23:48:04 tbox Exp $ */
=20
 #ifndef ISC_REFCOUNT_H
 #define ISC_REFCOUNT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/region.h
--- a/head/contrib/bind9/lib/isc/include/isc/region.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/region.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: region.h,v 1.25 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: region.h,v 1.25 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_REGION_H
 #define ISC_REGION_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/resource.h
--- a/head/contrib/bind9/lib/isc/include/isc/resource.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/resource.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: resource.h,v 1.13 2008-07-11 23:47:09 tbox Exp $ */
+/* $Id: resource.h,v 1.13 2008/07/11 23:47:09 tbox Exp $ */
=20
 #ifndef ISC_RESOURCE_H
 #define ISC_RESOURCE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/result.h
--- a/head/contrib/bind9/lib/isc/include/isc/result.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/result.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.h,v 1.73 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_RESULT_H
 #define ISC_RESULT_H 1
@@ -87,9 +87,10 @@
 #define ISC_R_MAXSIZE			58	/*%< max size */
 #define ISC_R_BADADDRESSFORM		59	/*%< invalid address format */
 #define ISC_R_BADBASE32			60	/*%< bad base32 encoding */
+#define ISC_R_UNSET			61	/*%< unset */
=20
 /*% Not a result code: the number of results. */
-#define ISC_R_NRESULTS 			61
+#define ISC_R_NRESULTS 			62
=20
 ISC_LANG_BEGINDECLS
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/resultclass.h
--- a/head/contrib/bind9/lib/isc/include/isc/resultclass.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/resultclass.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: resultclass.h,v 1.20 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: resultclass.h,v 1.20 2009/09/02 23:48:03 tbox Exp $ */
=20
 #ifndef ISC_RESULTCLASS_H
 #define ISC_RESULTCLASS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/rwlock.h
--- a/head/contrib/bind9/lib/isc/include/isc/rwlock.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/rwlock.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rwlock.h,v 1.28 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: rwlock.h,v 1.28 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_RWLOCK_H
 #define ISC_RWLOCK_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/serial.h
--- a/head/contrib/bind9/lib/isc/include/isc/serial.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/serial.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: serial.h,v 1.18 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id: serial.h,v 1.18 2009/01/18 23:48:14 tbox Exp $ */
=20
 #ifndef ISC_SERIAL_H
 #define ISC_SERIAL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/sha1.h
--- a/head/contrib/bind9/lib/isc/include/isc/sha1.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/sha1.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -18,7 +18,7 @@
 #ifndef ISC_SHA1_H
 #define ISC_SHA1_H 1
=20
-/* $Id: sha1.h,v 1.19 2009-02-06 23:47:42 tbox Exp $ */
+/* $Id: sha1.h,v 1.19 2009/02/06 23:47:42 tbox Exp $ */
=20
 /*	$NetBSD: sha1.h,v 1.2 1998/05/29 22:55:44 thorpej Exp $	*/
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/sha2.h
--- a/head/contrib/bind9/lib/isc/include/isc/sha2.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/sha2.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,9 +14,9 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sha2.h,v 1.12 2009-10-22 02:21:31 each Exp $ */
+/* $Id: sha2.h,v 1.12 2009/10/22 02:21:31 each Exp $ */
=20
-/*	$FreeBSD: head/contrib/bind9/lib/isc/include/isc/sha2.h 224092 2011-07-=
16 11:12:09Z dougb $	*/
+/*	$FreeBSD: head/contrib/bind9/lib/isc/include/isc/sha2.h 233914 2012-04-=
05 04:29:35Z dougb $	*/
 /*	$KAME: sha2.h,v 1.3 2001/03/12 08:27:48 itojun Exp $	*/
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/sockaddr.h
--- a/head/contrib/bind9/lib/isc/include/isc/sockaddr.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/sockaddr.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sockaddr.h,v 1.57 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id: sockaddr.h,v 1.57 2009/01/18 23:48:14 tbox Exp $ */
=20
 #ifndef ISC_SOCKADDR_H
 #define ISC_SOCKADDR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/socket.h
--- a/head/contrib/bind9/lib/isc/include/isc/socket.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/socket.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: socket.h,v 1.94 2009-10-01 01:30:01 sar Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_SOCKET_H
 #define ISC_SOCKET_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/stats.h
--- a/head/contrib/bind9/lib/isc/include/isc/stats.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/stats.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stats.h,v 1.4 2009-01-29 01:03:56 jinmei Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_STATS_H
 #define ISC_STATS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/stdio.h
--- a/head/contrib/bind9/lib/isc/include/isc/stdio.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/stdio.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stdio.h,v 1.13 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: stdio.h,v 1.13 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_STDIO_H
 #define ISC_STDIO_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/stdlib.h
--- a/head/contrib/bind9/lib/isc/include/isc/stdlib.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/stdlib.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stdlib.h,v 1.8 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: stdlib.h,v 1.8 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_STDLIB_H
 #define ISC_STDLIB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/string.h
--- a/head/contrib/bind9/lib/isc/include/isc/string.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/string.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: string.h,v 1.23 2007-09-13 04:48:16 each Exp $ */
+/* $Id: string.h,v 1.23 2007/09/13 04:48:16 each Exp $ */
=20
 #ifndef ISC_STRING_H
 #define ISC_STRING_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/symtab.h
--- a/head/contrib/bind9/lib/isc/include/isc/symtab.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/symtab.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1996-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: symtab.h,v 1.26 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_SYMTAB_H
 #define ISC_SYMTAB_H 1
@@ -57,6 +57,14 @@
  * undefined.  It can be used to free memory associated with keys and/or
  * values.
  *
+ * A symbol table is implemented as a hash table of lists; the size of the
+ * hash table is set by the 'size' parameter to isc_symtbl_create().  When
+ * the number of entries in the symbol table reaches three quarters of this
+ * value, the hash table is reallocated with size doubled, in order to
+ * optimize lookup performance.  This has a negative effect on insertion
+ * performance, which can be mitigated by sizing the table appropriately
+ * when creating it.
+ *
  * \li MP:
  *	The callers of this module must ensure any required synchronization.
  *
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/task.h
--- a/head/contrib/bind9/lib/isc/include/isc/task.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/task.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009-2011  Internet Systems Consortium, Inc. (=
"ISC")
+ * Copyright (C) 2004-2007, 2009-2012  Internet Systems Consortium, Inc. (=
"ISC")
  * Copyright (C) 1998-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: task.h,v 1.69.14.2 2011-02-28 01:20:04 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_TASK_H
 #define ISC_TASK_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/taskpool.h
--- a/head/contrib/bind9/lib/isc/include/isc/taskpool.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/taskpool.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: taskpool.h,v 1.15.814.2 2011-07-08 23:47:16 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_TASKPOOL_H
 #define ISC_TASKPOOL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/timer.h
--- a/head/contrib/bind9/lib/isc/include/isc/timer.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/timer.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: timer.h,v 1.43 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: timer.h,v 1.43 2009/09/02 23:48:03 tbox Exp $ */
=20
 #ifndef ISC_TIMER_H
 #define ISC_TIMER_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/types.h
--- a/head/contrib/bind9/lib/isc/include/isc/types.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/types.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: types.h,v 1.52 2009-12-05 23:31:41 each Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_TYPES_H
 #define ISC_TYPES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/util.h
--- a/head/contrib/bind9/lib/isc/include/isc/util.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/util.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2010, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2010-2012  Internet Systems Consortium, Inc. (=
"ISC")
  * Copyright (C) 1998-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: util.h,v 1.32.170.2 2011-03-12 04:59:19 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_UTIL_H
 #define ISC_UTIL_H 1
@@ -235,14 +235,4 @@
  */
 #define TIME_NOW(tp) 	RUNTIME_CHECK(isc_time_now((tp)) =3D=3D ISC_R_SUCCES=
S)
=20
-/*%
- * Prevent Linux spurious warnings
- */
-#if defined(__GNUC__) && (__GNUC__ > 3)
-#define isc_util_fwrite(a, b, c, d)	\
-	__builtin_expect(fwrite((a), (b), (c), (d)), (c))
-#else
-#define isc_util_fwrite(a, b, c, d)	fwrite((a), (b), (c), (d))
-#endif
-
 #endif /* ISC_UTIL_H */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/version.h
--- a/head/contrib/bind9/lib/isc/include/isc/version.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/version.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.h,v 1.9 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: version.h,v 1.9 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*! \file isc/version.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/include/isc=
/xml.h
--- a/head/contrib/bind9/lib/isc/include/isc/xml.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/include/isc/xml.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: xml.h,v 1.4 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: xml.h,v 1.4 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_XML_H
 #define ISC_XML_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/inet_aton.c
--- a/head/contrib/bind9/lib/isc/inet_aton.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/inet_aton.c	Tue Apr 17 11:51:51 2012 +0300
@@ -71,7 +71,7 @@
=20
 #if defined(LIBC_SCCS) && !defined(lint)
 static char sccsid[] =3D "@(#)inet_addr.c	8.1 (Berkeley) 6/17/93";
-static char rcsid[] =3D "$Id: inet_aton.c,v 1.23 2008-12-01 23:47:45 tbox =
Exp $";
+static char rcsid[] =3D "$Id: inet_aton.c,v 1.23 2008/12/01 23:47:45 tbox =
Exp $";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/inet_ntop.c
--- a/head/contrib/bind9/lib/isc/inet_ntop.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/inet_ntop.c	Tue Apr 17 11:51:51 2012 +0300
@@ -19,7 +19,7 @@
=20
 #if defined(LIBC_SCCS) && !defined(lint)
 static char rcsid[] =3D
-	"$Id: inet_ntop.c,v 1.21 2009-07-17 23:47:41 tbox Exp $";
+	"$Id: inet_ntop.c,v 1.21 2009/07/17 23:47:41 tbox Exp $";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/inet_pton.c
--- a/head/contrib/bind9/lib/isc/inet_pton.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/inet_pton.c	Tue Apr 17 11:51:51 2012 +0300
@@ -19,7 +19,7 @@
=20
 #if defined(LIBC_SCCS) && !defined(lint)
 static char rcsid[] =3D
-	"$Id: inet_pton.c,v 1.19 2007-06-19 23:47:17 tbox Exp $";
+	"$Id: inet_pton.c,v 1.19 2007/06/19 23:47:17 tbox Exp $";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/iterated_ha=
sh.c
--- a/head/contrib/bind9/lib/isc/iterated_hash.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/isc/iterated_hash.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: iterated_hash.c,v 1.6 2009-02-18 23:47:48 tbox Exp $ */
+/* $Id: iterated_hash.c,v 1.6 2009/02/18 23:47:48 tbox Exp $ */
=20
 #include "config.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/lex.c
--- a/head/contrib/bind9/lib/isc/lex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/lex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lex.c,v 1.86 2007-09-17 09:56:29 shane Exp $ */
+/* $Id: lex.c,v 1.86 2007/09/17 09:56:29 shane Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/lfsr.c
--- a/head/contrib/bind9/lib/isc/lfsr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/lfsr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lfsr.c,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: lfsr.c,v 1.20 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/lib.c
--- a/head/contrib/bind9/lib/isc/lib.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/lib.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lib.c,v 1.16 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: lib.c,v 1.16 2009/09/02 23:48:02 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/log.c
--- a/head/contrib/bind9/lib/isc/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2009, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.c,v 1.99.404.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file
  * \author  Principal Authors: DCL */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/md5.c
--- a/head/contrib/bind9/lib/isc/md5.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/md5.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: md5.c,v 1.16 2009-02-06 23:47:42 tbox Exp $ */
+/* $Id: md5.c,v 1.16 2009/02/06 23:47:42 tbox Exp $ */
=20
 /*! \file
  * This code implements the MD5 message-digest algorithm.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/mem.c
--- a/head/contrib/bind9/lib/isc/mem.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/mem.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2010, 2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1997-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mem.c,v 1.160 2010-12-08 02:46:16 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/mem_api.c
--- a/head/contrib/bind9/lib/isc/mem_api.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/mem_api.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mem_api.c,v 1.8 2010-08-12 21:30:26 jinmei Exp $ */
+/* $Id: mem_api.c,v 1.8 2010/08/12 21:30:26 jinmei Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/mips/Makefi=
le.in
--- a/head/contrib/bind9/lib/isc/mips/Makefile.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/isc/mips/Makefile.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/mips/includ=
e/Makefile.in
--- a/head/contrib/bind9/lib/isc/mips/include/Makefile.in	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/mips/include/Makefile.in	Tue Apr 17 11:51:=
51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/mips/includ=
e/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/mips/include/isc/Makefile.in	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/mips/include/isc/Makefile.in	Tue Apr 17 11=
:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/mips/includ=
e/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/mips/include/isc/atomic.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/mips/include/isc/atomic.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.3 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: atomic.h,v 1.3 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_ATOMIC_H
 #define ISC_ATOMIC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/mutexblock.c
--- a/head/contrib/bind9/lib/isc/mutexblock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/mutexblock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mutexblock.c,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -32,10 +32,9 @@
 	for (i =3D 0; i < count; i++) {
 		result =3D isc_mutex_init(&block[i]);
 		if (result !=3D ISC_R_SUCCESS) {
-			i--;
-			while (i > 0) {
+			while (i > 0U) {
+				i--;
 				DESTROYLOCK(&block[i]);
-				i--;
 			}
 			return (result);
 		}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/netaddr.c
--- a/head/contrib/bind9/lib/isc/netaddr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/netaddr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2010, 2011  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2010-2012  Internet Systems Consortium,=
 Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: netaddr.c,v 1.41.38.3 2011-03-11 06:47:07 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/netscope.c
--- a/head/contrib/bind9/lib/isc/netscope.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/netscope.c	Tue Apr 17 11:51:51 2012 +0300
@@ -19,7 +19,7 @@
=20
 #if defined(LIBC_SCCS) && !defined(lint)
 static char rcsid[] =3D
-	"$Id: netscope.c,v 1.13 2007-06-19 23:47:17 tbox Exp $";
+	"$Id: netscope.c,v 1.13 2007/06/19 23:47:17 tbox Exp $";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nls/Makefil=
e.in
--- a/head/contrib/bind9/lib/isc/nls/Makefile.in	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/isc/nls/Makefile.in	Tue Apr 17 11:51:51 2012 +=
0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.17 2009-12-05 23:31:41 each Exp $
+# $Id: Makefile.in,v 1.17 2009/12/05 23:31:41 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nls/msgcat.c
--- a/head/contrib/bind9/lib/isc/nls/msgcat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/nls/msgcat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: msgcat.c,v 1.18 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: msgcat.c,v 1.18 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*! \file msgcat.c
  *
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/noatomic/Ma=
kefile.in
--- a/head/contrib/bind9/lib/isc/noatomic/Makefile.in	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/noatomic/Makefile.in	Tue Apr 17 11:51:51 2=
012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/noatomic/in=
clude/Makefile.in
--- a/head/contrib/bind9/lib/isc/noatomic/include/Makefile.in	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/noatomic/include/Makefile.in	Tue Apr 17 11=
:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/noatomic/in=
clude/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/noatomic/include/isc/Makefile.in	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/noatomic/include/isc/Makefile.in	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/noatomic/in=
clude/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/noatomic/include/isc/atomic.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/noatomic/include/isc/atomic.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.4 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: atomic.h,v 1.4 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_ATOMIC_H
 #define ISC_ATOMIC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/M=
akefile.in
--- a/head/contrib/bind9/lib/isc/nothreads/Makefile.in	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/Makefile.in	Tue Apr 17 11:51:51 =
2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.12 2010-06-09 23:50:58 tbox Exp $
+# $Id: Makefile.in,v 1.12 2010/06/09 23:50:58 tbox Exp $
=20
 top_srcdir =3D	@top_srcdir@
 srcdir =3D	@top_srcdir@/lib/isc/nothreads
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/c=
ondition.c
--- a/head/contrib/bind9/lib/isc/nothreads/condition.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/condition.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: condition.c,v 1.10 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: condition.c,v 1.10 2007/06/19 23:47:18 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/i=
nclude/Makefile.in
--- a/head/contrib/bind9/lib/isc/nothreads/include/Makefile.in	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/include/Makefile.in	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.5 2007-06-19 23:47:18 tbox Exp $
+# $Id: Makefile.in,v 1.5 2007/06/19 23:47:18 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/i=
nclude/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/nothreads/include/isc/Makefile.in	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/include/isc/Makefile.in	Tue Apr =
17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.7 2007-06-19 23:47:18 tbox Exp $
+# $Id: Makefile.in,v 1.7 2007/06/19 23:47:18 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/i=
nclude/isc/condition.h
--- a/head/contrib/bind9/lib/isc/nothreads/include/isc/condition.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/include/isc/condition.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: condition.h,v 1.6 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: condition.h,v 1.6 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*
  * This provides a limited subset of the isc_condition_t
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/i=
nclude/isc/mutex.h
--- a/head/contrib/bind9/lib/isc/nothreads/include/isc/mutex.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/include/isc/mutex.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mutex.h,v 1.6 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: mutex.h,v 1.6 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_MUTEX_H
 #define ISC_MUTEX_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/i=
nclude/isc/once.h
--- a/head/contrib/bind9/lib/isc/nothreads/include/isc/once.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/include/isc/once.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: once.h,v 1.6 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: once.h,v 1.6 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_ONCE_H
 #define ISC_ONCE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/i=
nclude/isc/thread.h
--- a/head/contrib/bind9/lib/isc/nothreads/include/isc/thread.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/include/isc/thread.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: thread.h,v 1.6 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: thread.h,v 1.6 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_THREAD_H
 #define ISC_THREAD_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/m=
utex.c
--- a/head/contrib/bind9/lib/isc/nothreads/mutex.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/mutex.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mutex.c,v 1.10 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: mutex.c,v 1.10 2007/06/19 23:47:18 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/nothreads/t=
hread.c
--- a/head/contrib/bind9/lib/isc/nothreads/thread.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/nothreads/thread.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: thread.c,v 1.5 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: thread.c,v 1.5 2007/06/19 23:47:18 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/ondestroy.c
--- a/head/contrib/bind9/lib/isc/ondestroy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/ondestroy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ondestroy.c,v 1.16 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ondestroy.c,v 1.16 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/parseint.c
--- a/head/contrib/bind9/lib/isc/parseint.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/parseint.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: parseint.c,v 1.8 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: parseint.c,v 1.8 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/portset.c
--- a/head/contrib/bind9/lib/isc/portset.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/portset.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: portset.c,v 1.4 2008-06-24 23:24:35 marka Exp $ */
+/* $Id: portset.c,v 1.4 2008/06/24 23:24:35 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/powerpc/Mak=
efile.in
--- a/head/contrib/bind9/lib/isc/powerpc/Makefile.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/powerpc/Makefile.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/powerpc/inc=
lude/Makefile.in
--- a/head/contrib/bind9/lib/isc/powerpc/include/Makefile.in	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/powerpc/include/Makefile.in	Tue Apr 17 11:=
51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/powerpc/inc=
lude/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/powerpc/include/isc/Makefile.in	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/powerpc/include/isc/Makefile.in	Tue Apr 17=
 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/powerpc/inc=
lude/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/powerpc/include/isc/atomic.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/powerpc/include/isc/atomic.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005, 2007, 2009, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2005, 2007, 2009, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.8.284.3 2011-03-08 00:52:21 marka Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_ATOMIC_H
 #define ISC_ATOMIC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/print.c
--- a/head/contrib/bind9/lib/isc/print.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/print.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: print.c,v 1.37 2010-10-18 23:47:08 tbox Exp $ */
+/* $Id: print.c,v 1.37 2010/10/18 23:47:08 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/Ma=
kefile.in
--- a/head/contrib/bind9/lib/isc/pthreads/Makefile.in	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/Makefile.in	Tue Apr 17 11:51:51 2=
012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.22 2009-12-05 23:31:41 each Exp $
+# $Id: Makefile.in,v 1.22 2009/12/05 23:31:41 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/co=
ndition.c
--- a/head/contrib/bind9/lib/isc/pthreads/condition.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/condition.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: condition.c,v 1.36 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: condition.c,v 1.36 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/in=
clude/Makefile.in
--- a/head/contrib/bind9/lib/isc/pthreads/include/Makefile.in	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/include/Makefile.in	Tue Apr 17 11=
:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.14 2007-06-19 23:47:18 tbox Exp $
+# $Id: Makefile.in,v 1.14 2007/06/19 23:47:18 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/in=
clude/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/pthreads/include/isc/Makefile.in	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/include/isc/Makefile.in	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.16 2007-06-19 23:47:18 tbox Exp $
+# $Id: Makefile.in,v 1.16 2007/06/19 23:47:18 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/in=
clude/isc/condition.h
--- a/head/contrib/bind9/lib/isc/pthreads/include/isc/condition.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/include/isc/condition.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: condition.h,v 1.26 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: condition.h,v 1.26 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_CONDITION_H
 #define ISC_CONDITION_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/in=
clude/isc/mutex.h
--- a/head/contrib/bind9/lib/isc/pthreads/include/isc/mutex.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/include/isc/mutex.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mutex.h,v 1.30 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: mutex.h,v 1.30 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_MUTEX_H
 #define ISC_MUTEX_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/in=
clude/isc/once.h
--- a/head/contrib/bind9/lib/isc/pthreads/include/isc/once.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/include/isc/once.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: once.h,v 1.13 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: once.h,v 1.13 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_ONCE_H
 #define ISC_ONCE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/in=
clude/isc/thread.h
--- a/head/contrib/bind9/lib/isc/pthreads/include/isc/thread.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/include/isc/thread.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: thread.h,v 1.26 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: thread.h,v 1.26 2007/06/19 23:47:18 tbox Exp $ */
=20
 #ifndef ISC_THREAD_H
 #define ISC_THREAD_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/mu=
tex.c
--- a/head/contrib/bind9/lib/isc/pthreads/mutex.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/isc/pthreads/mutex.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: mutex.c,v 1.18 2011-01-04 23:47:14 tbox Exp $ */
+/* $Id: mutex.c,v 1.18 2011/01/04 23:47:14 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/pthreads/th=
read.c
--- a/head/contrib/bind9/lib/isc/pthreads/thread.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/isc/pthreads/thread.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: thread.c,v 1.17 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: thread.c,v 1.17 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/quota.c
--- a/head/contrib/bind9/lib/isc/quota.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/quota.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: quota.c,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: quota.c,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/radix.c
--- a/head/contrib/bind9/lib/isc/radix.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/radix.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2007-2009, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: radix.c,v 1.23.426.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*
  * This source was adapted from MRT's RCS Ids:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/random.c
--- a/head/contrib/bind9/lib/isc/random.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/random.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: random.c,v 1.28 2009-07-16 05:52:46 marka Exp $ */
+/* $Id: random.c,v 1.28 2009/07/16 05:52:46 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/ratelimiter=
.c
--- a/head/contrib/bind9/lib/isc/ratelimiter.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/isc/ratelimiter.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ratelimiter.c,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ratelimiter.c,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/refcount.c
--- a/head/contrib/bind9/lib/isc/refcount.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/refcount.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: refcount.c,v 1.5 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: refcount.c,v 1.5 2007/06/19 23:47:17 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/region.c
--- a/head/contrib/bind9/lib/isc/region.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/region.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: region.c,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: region.c,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/result.c
--- a/head/contrib/bind9/lib/isc/result.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/result.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2008  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2008, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1998-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.c,v 1.71 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -102,6 +102,7 @@
 	"max size",				/*%< 58 */
 	"invalid address format",		/*%< 59 */
 	"bad base32 encoding",			/*%< 60 */
+	"unset",				/*%< 61 */
 };
=20
 #define ISC_RESULT_RESULTSET			2
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/rwlock.c
--- a/head/contrib/bind9/lib/isc/rwlock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/rwlock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009, 2011  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2011, 2012  Internet Systems Cons=
ortium, Inc. ("ISC")
  * Copyright (C) 1998-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rwlock.c,v 1.46.426.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/serial.c
--- a/head/contrib/bind9/lib/isc/serial.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/serial.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: serial.c,v 1.12 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: serial.c,v 1.12 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/sha1.c
--- a/head/contrib/bind9/lib/isc/sha1.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/sha1.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009, 2011  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2011, 2012  Internet Systems Cons=
ortium, Inc. ("ISC")
  * Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sha1.c,v 1.20.408.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*	$NetBSD: sha1.c,v 1.5 2000/01/22 22:19:14 mycroft Exp $	*/
 /*	$OpenBSD: sha1.c,v 1.9 1997/07/23 21:12:32 kstailey Exp $	*/
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/sha2.c
--- a/head/contrib/bind9/lib/isc/sha2.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/sha2.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2005-2007, 2009, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2005-2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,9 +14,9 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sha2.c,v 1.18.280.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
-/*	$FreeBSD: head/contrib/bind9/lib/isc/sha2.c 225361 2011-09-03 07:13:45Z=
 dougb $	*/
+/*	$FreeBSD: head/contrib/bind9/lib/isc/sha2.c 233914 2012-04-05 04:29:35Z=
 dougb $	*/
 /*	$KAME: sha2.c,v 1.8 2001/11/08 01:07:52 itojun Exp $	*/
=20
 /*
@@ -905,7 +905,7 @@
 	}
=20
 	/* Clean up state data: */
-	memset(context, 0, sizeof(context));
+	memset(context, 0, sizeof(*context));
 	usedspace =3D 0;
 	POST(usedspace);
 }
@@ -1229,7 +1229,7 @@
 	}
=20
 	/* Zero out state data */
-	memset(context, 0, sizeof(context));
+	memset(context, 0, sizeof(*context));
 }
=20
=20
@@ -1282,7 +1282,7 @@
 	}
=20
 	/* Zero out state data */
-	memset(context, 0, sizeof(context));
+	memset(context, 0, sizeof(*context));
 }
 #endif /* !ISC_PLATFORM_OPENSSLHASH */
=20
@@ -1313,7 +1313,7 @@
 #ifdef ISC_PLATFORM_OPENSSLHASH
 		EVP_MD_CTX_cleanup(context);
 #else
-		memset(context, 0, sizeof(context));
+		memset(context, 0, sizeof(*context));
 #endif
 	}
 	memset(digest, 0, ISC_SHA224_DIGESTLENGTH);
@@ -1352,7 +1352,7 @@
 #ifdef ISC_PLATFORM_OPENSSLHASH
 		EVP_MD_CTX_cleanup(context);
 #else
-		memset(context, 0, sizeof(context));
+		memset(context, 0, sizeof(*context));
 #endif
 	}
 	memset(digest, 0, ISC_SHA256_DIGESTLENGTH);
@@ -1391,7 +1391,7 @@
 #ifdef ISC_PLATFORM_OPENSSLHASH
 		EVP_MD_CTX_cleanup(context);
 #else
-		memset(context, 0, sizeof(context));
+		memset(context, 0, sizeof(*context));
 #endif
 	}
 	memset(digest, 0, ISC_SHA512_DIGESTLENGTH);
@@ -1430,7 +1430,7 @@
 #ifdef ISC_PLATFORM_OPENSSLHASH
 		EVP_MD_CTX_cleanup(context);
 #else
-		memset(context, 0, sizeof(context));
+		memset(context, 0, sizeof(*context));
 #endif
 	}
 	memset(digest, 0, ISC_SHA384_DIGESTLENGTH);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/sockaddr.c
--- a/head/contrib/bind9/lib/isc/sockaddr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/sockaddr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2010, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2010-2012  Internet Systems Consortium, Inc. (=
"ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sockaddr.c,v 1.73.38.2 2011-02-28 01:20:03 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/socket_api.c
--- a/head/contrib/bind9/lib/isc/socket_api.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/socket_api.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: socket_api.c,v 1.5 2009-10-01 01:30:01 sar Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/sparc64/Mak=
efile.in
--- a/head/contrib/bind9/lib/isc/sparc64/Makefile.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/sparc64/Makefile.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/sparc64/inc=
lude/Makefile.in
--- a/head/contrib/bind9/lib/isc/sparc64/include/Makefile.in	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/sparc64/include/Makefile.in	Tue Apr 17 11:=
51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/sparc64/inc=
lude/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/sparc64/include/isc/Makefile.in	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/sparc64/include/isc/Makefile.in	Tue Apr 17=
 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/sparc64/inc=
lude/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/sparc64/include/isc/atomic.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/sparc64/include/isc/atomic.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.5 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: atomic.h,v 1.5 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*
  * This code was written based on FreeBSD's kernel source whose copyright
@@ -48,7 +48,7 @@
  * SUCH DAMAGE.
  *
  *	from: FreeBSD: src/sys/i386/include/atomic.h,v 1.20 2001/02/11
- * $FreeBSD: head/contrib/bind9/lib/isc/sparc64/include/isc/atomic.h 22381=
1 2011-07-06 00:47:27Z dougb $
+ * $FreeBSD: head/contrib/bind9/lib/isc/sparc64/include/isc/atomic.h 23391=
4 2012-04-05 04:29:35Z dougb $
  */
=20
 #ifndef ISC_ATOMIC_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/stats.c
--- a/head/contrib/bind9/lib/isc/stats.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/stats.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stats.c,v 1.3 2009-01-27 23:47:54 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/string.c
--- a/head/contrib/bind9/lib/isc/string.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/string.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2007, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: string.c,v 1.20.814.2 2011-03-12 04:59:18 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/strtoul.c
--- a/head/contrib/bind9/lib/isc/strtoul.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/strtoul.c	Tue Apr 17 11:51:51 2012 +0300
@@ -53,7 +53,7 @@
 static char sccsid[] =3D "@(#)strtoul.c	8.1 (Berkeley) 6/4/93";
 #endif /* LIBC_SCCS and not lint */
=20
-/* $Id: strtoul.c,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: strtoul.c,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/symtab.c
--- a/head/contrib/bind9/lib/isc/symtab.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/symtab.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1996-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: symtab.c,v 1.30 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -46,6 +46,8 @@
 	unsigned int			magic;
 	isc_mem_t *			mctx;
 	unsigned int			size;
+	unsigned int			count;
+	unsigned int			maxload;
 	eltlist_t *			table;
 	isc_symtabaction_t		undefine_action;
 	void *				undefine_arg;
@@ -79,6 +81,8 @@
 		INIT_LIST(symtab->table[i]);
 	symtab->mctx =3D mctx;
 	symtab->size =3D size;
+	symtab->count =3D 0;
+	symtab->maxload =3D size * 3 / 4;
 	symtab->undefine_action =3D undefine_action;
 	symtab->undefine_arg =3D undefine_arg;
 	symtab->case_sensitive =3D case_sensitive;
@@ -181,6 +185,46 @@
 	return (ISC_R_SUCCESS);
 }
=20
+static void
+grow_table(isc_symtab_t *symtab) {
+	eltlist_t *newtable;
+	unsigned int i, newsize, newmax;
+
+	REQUIRE(symtab !=3D NULL);
+
+	newsize =3D symtab->size * 2;
+	newmax =3D newsize * 3 / 4;
+	INSIST(newsize > 0U && newmax > 0U);
+
+	newtable =3D isc_mem_get(symtab->mctx, newsize * sizeof(eltlist_t));
+	if (newtable =3D=3D NULL)
+		return;
+
+	for (i =3D 0; i < newsize; i++)
+		INIT_LIST(newtable[i]);
+
+	for (i =3D 0; i < symtab->size; i++) {
+		elt_t *elt, *nelt;
+
+		for (elt =3D HEAD(symtab->table[i]); elt !=3D NULL; elt =3D nelt) {
+			unsigned int hv;
+
+			nelt =3D NEXT(elt, link);
+
+			UNLINK(symtab->table[i], elt, link);
+			hv =3D hash(elt->key, symtab->case_sensitive);
+			APPEND(newtable[hv % newsize], elt, link);
+		}
+	}
+
+	isc_mem_put(symtab->mctx, symtab->table,
+		    symtab->size * sizeof(eltlist_t));
+
+	symtab->table =3D newtable;
+	symtab->size =3D newsize;
+	symtab->maxload =3D newmax;
+}
+
 isc_result_t
 isc_symtab_define(isc_symtab_t *symtab, const char *key, unsigned int type,
 		  isc_symvalue_t value, isc_symexists_t exists_policy)
@@ -208,6 +252,7 @@
 		if (elt =3D=3D NULL)
 			return (ISC_R_NOMEMORY);
 		ISC_LINK_INIT(elt, link);
+		symtab->count++;
 	}
=20
 	/*
@@ -226,6 +271,9 @@
 	 */
 	PREPEND(symtab->table[bucket], elt, link);
=20
+	if (symtab->count > symtab->maxload)
+		grow_table(symtab);
+
 	return (ISC_R_SUCCESS);
 }
=20
@@ -247,6 +295,7 @@
 					  elt->value, symtab->undefine_arg);
 	UNLINK(symtab->table[bucket], elt, link);
 	isc_mem_put(symtab->mctx, elt, sizeof(*elt));
+	symtab->count--;
=20
 	return (ISC_R_SUCCESS);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/task.c
--- a/head/contrib/bind9/lib/isc/task.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/task.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: task.c,v 1.115.14.2 2011-02-28 01:20:03 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file
  * \author Principal Author: Bob Halley
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/task_api.c
--- a/head/contrib/bind9/lib/isc/task_api.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/task_api.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009, 2010  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2009, 2010, 2012  Internet Systems Consortium, Inc. ("ISC=
")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: task_api.c,v 1.7 2010-12-22 23:46:59 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/task_p.h
--- a/head/contrib/bind9/lib/isc/task_p.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/task_p.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: task_p.h,v 1.13 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_TASK_P_H
 #define ISC_TASK_P_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/taskpool.c
--- a/head/contrib/bind9/lib/isc/taskpool.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/taskpool.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: taskpool.c,v 1.18.814.2 2011-07-08 23:47:16 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/timer.c
--- a/head/contrib/bind9/lib/isc/timer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/timer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 1998-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: timer.c,v 1.95.302.3 2011-03-11 06:47:08 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/timer_api.c
--- a/head/contrib/bind9/lib/isc/timer_api.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/timer_api.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: timer_api.c,v 1.4 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: timer_api.c,v 1.4 2009/09/02 23:48:02 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/timer_p.h
--- a/head/contrib/bind9/lib/isc/timer_p.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/timer_p.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: timer_p.h,v 1.12 2009-09-02 23:48:02 tbox Exp $ */
+/* $Id: timer_p.h,v 1.12 2009/09/02 23:48:02 tbox Exp $ */
=20
 #ifndef ISC_TIMER_P_H
 #define ISC_TIMER_P_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/Makefi=
le.in
--- a/head/contrib/bind9/lib/isc/unix/Makefile.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/isc/unix/Makefile.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.44 2009-12-05 23:31:41 each Exp $
+# $Id: Makefile.in,v 1.44 2009/12/05 23:31:41 each Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/app.c
--- a/head/contrib/bind9/lib/isc/unix/app.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/app.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: app.c,v 1.64 2009-11-04 05:58:46 marka Exp $ */
+/* $Id: app.c,v 1.64 2009/11/04 05:58:46 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/dir.c
--- a/head/contrib/bind9/lib/isc/unix/dir.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/dir.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007-2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007-2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dir.c,v 1.29.404.2 2011-03-12 04:59:19 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file
  * \author  Principal Authors: DCL */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/entrop=
y.c
--- a/head/contrib/bind9/lib/isc/unix/entropy.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/isc/unix/entropy.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: entropy.c,v 1.82 2008-12-01 23:47:45 tbox Exp $ */
+/* $Id: entropy.c,v 1.82 2008/12/01 23:47:45 tbox Exp $ */
=20
 /* \file unix/entropy.c
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/errno2=
result.c
--- a/head/contrib/bind9/lib/isc/unix/errno2result.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/unix/errno2result.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 2000-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: errno2result.c,v 1.17 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -34,7 +34,7 @@
  * not already there.
  */
 isc_result_t
-isc__errno2result(int posixerrno) {
+isc___errno2result(int posixerrno, const char *file, unsigned int line) {
 	char strbuf[ISC_STRERRORSIZE];
=20
 	switch (posixerrno) {
@@ -55,7 +55,7 @@
 		return (ISC_R_IOERROR);
 	case ENOMEM:
 		return (ISC_R_NOMEMORY);
-	case ENFILE:=09
+	case ENFILE:
 	case EMFILE:
 		return (ISC_R_TOOMANYOPENFILES);
 	case EPIPE:
@@ -108,8 +108,7 @@
 		return (ISC_R_CONNREFUSED);
 	default:
 		isc__strerror(posixerrno, strbuf, sizeof(strbuf));
-		UNEXPECTED_ERROR(__FILE__, __LINE__,
-				 "unable to convert errno "
+		UNEXPECTED_ERROR(file, line, "unable to convert errno "
 				 "to isc_result: %d: %s",
 				 posixerrno, strbuf);
 		/*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/errno2=
result.h
--- a/head/contrib/bind9/lib/isc/unix/errno2result.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/unix/errno2result.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: errno2result.h,v 1.12 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef UNIX_ERRNO2RESULT_H
 #define UNIX_ERRNO2RESULT_H 1
@@ -31,8 +31,10 @@
=20
 ISC_LANG_BEGINDECLS
=20
+#define isc__errno2result(x) isc___errno2result(x, __FILE__, __LINE__)
+
 isc_result_t
-isc__errno2result(int posixerrno);
+isc___errno2result(int posixerrno, const char *file, unsigned int line);
=20
 ISC_LANG_ENDDECLS
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/file.c
--- a/head/contrib/bind9/lib/isc/unix/file.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/file.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2009, 2011  Internet Systems Consortium=
, Inc. ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2009, 2011, 2012  Internet Systems Cons=
ortium, Inc. ("ISC")
  * Copyright (C) 2000-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -48,7 +48,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: file.c,v 1.57.10.1 2011-03-04 14:10:13 smann Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/fsacce=
ss.c
--- a/head/contrib/bind9/lib/isc/unix/fsaccess.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/isc/unix/fsaccess.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: fsaccess.c,v 1.13 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: fsaccess.c,v 1.13 2007/06/19 23:47:18 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/ifiter=
_getifaddrs.c
--- a/head/contrib/bind9/lib/isc/unix/ifiter_getifaddrs.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/ifiter_getifaddrs.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ifiter_getifaddrs.c,v 1.13 2009-09-24 23:48:13 tbox Exp $ */
+/* $Id: ifiter_getifaddrs.c,v 1.13 2009/09/24 23:48:13 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/ifiter=
_ioctl.c
--- a/head/contrib/bind9/lib/isc/unix/ifiter_ioctl.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/isc/unix/ifiter_ioctl.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ifiter_ioctl.c,v 1.62 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id: ifiter_ioctl.c,v 1.62 2009/01/18 23:48:14 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/ifiter=
_sysctl.c
--- a/head/contrib/bind9/lib/isc/unix/ifiter_sysctl.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/ifiter_sysctl.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ifiter_sysctl.c,v 1.25 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: ifiter_sysctl.c,v 1.25 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*! \file
  * \brief
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/Makefile.in
--- a/head/contrib/bind9/lib/isc/unix/include/Makefile.in	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/Makefile.in	Tue Apr 17 11:51:=
51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.14 2007-06-19 23:47:18 tbox Exp $
+# $Id: Makefile.in,v 1.14 2007/06/19 23:47:18 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/unix/include/isc/Makefile.in	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/Makefile.in	Tue Apr 17 11=
:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.30 2007-06-19 23:47:19 tbox Exp $
+# $Id: Makefile.in,v 1.30 2007/06/19 23:47:19 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/dir.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/dir.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/dir.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dir.h,v 1.21 2007-06-19 23:47:19 tbox Exp $ */
+/* $Id: dir.h,v 1.21 2007/06/19 23:47:19 tbox Exp $ */
=20
 /* Principal Authors: DCL */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/int.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/int.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/int.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: int.h,v 1.16 2007-06-19 23:47:19 tbox Exp $ */
+/* $Id: int.h,v 1.16 2007/06/19 23:47:19 tbox Exp $ */
=20
 #ifndef ISC_INT_H
 #define ISC_INT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/keyboard.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/keyboard.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/keyboard.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keyboard.h,v 1.11 2007-06-19 23:47:19 tbox Exp $ */
+/* $Id: keyboard.h,v 1.11 2007/06/19 23:47:19 tbox Exp $ */
=20
 #ifndef ISC_KEYBOARD_H
 #define ISC_KEYBOARD_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/net.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/net.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/net.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2008  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2008, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: net.h,v 1.50 2008-12-01 04:14:54 marka Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_NET_H
 #define ISC_NET_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/netdb.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/netdb.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/netdb.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: netdb.h,v 1.11 2007-06-19 23:47:19 tbox Exp $ */
+/* $Id: netdb.h,v 1.11 2007/06/19 23:47:19 tbox Exp $ */
=20
 #ifndef ISC_NETDB_H
 #define ISC_NETDB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/offset.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/offset.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/offset.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: offset.h,v 1.17 2008-12-01 23:47:45 tbox Exp $ */
+/* $Id: offset.h,v 1.17 2008/12/01 23:47:45 tbox Exp $ */
=20
 #ifndef ISC_OFFSET_H
 #define ISC_OFFSET_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/stat.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/stat.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/stat.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stat.h,v 1.5 2007-06-19 23:47:19 tbox Exp $ */
+/* $Id: stat.h,v 1.5 2007/06/19 23:47:19 tbox Exp $ */
=20
 #ifndef ISC_STAT_H
 #define ISC_STAT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/stdtime.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/stdtime.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/stdtime.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stdtime.h,v 1.14.814.2 2011-03-18 23:47:15 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISC_STDTIME_H
 #define ISC_STDTIME_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/strerror.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/strerror.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/strerror.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: strerror.h,v 1.10 2008-12-01 23:47:45 tbox Exp $ */
+/* $Id: strerror.h,v 1.10 2008/12/01 23:47:45 tbox Exp $ */
=20
 #ifndef ISC_STRERROR_H
 #define ISC_STRERROR_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/syslog.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/syslog.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/syslog.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: syslog.h,v 1.7 2007-06-19 23:47:19 tbox Exp $ */
+/* $Id: syslog.h,v 1.7 2007/06/19 23:47:19 tbox Exp $ */
=20
 #ifndef ISC_SYSLOG_H
 #define ISC_SYSLOG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/includ=
e/isc/time.h
--- a/head/contrib/bind9/lib/isc/unix/include/isc/time.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/include/isc/time.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: time.h,v 1.40 2009-01-05 23:47:54 tbox Exp $ */
+/* $Id: time.h,v 1.40 2009/01/05 23:47:54 tbox Exp $ */
=20
 #ifndef ISC_TIME_H
 #define ISC_TIME_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/interf=
aceiter.c
--- a/head/contrib/bind9/lib/isc/unix/interfaceiter.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/interfaceiter.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: interfaceiter.c,v 1.45 2008-12-01 03:51:47 marka Exp $ */
+/* $Id: interfaceiter.c,v 1.45 2008/12/01 03:51:47 marka Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/ipv6.c
--- a/head/contrib/bind9/lib/isc/unix/ipv6.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/ipv6.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ipv6.c,v 1.14 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: ipv6.c,v 1.14 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/keyboa=
rd.c
--- a/head/contrib/bind9/lib/isc/unix/keyboard.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/isc/unix/keyboard.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: keyboard.c,v 1.13 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: keyboard.c,v 1.13 2007/06/19 23:47:18 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/net.c
--- a/head/contrib/bind9/lib/isc/unix/net.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/net.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2008  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2008, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: net.c,v 1.40 2008-07-04 05:52:31 each Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/os.c
--- a/head/contrib/bind9/lib/isc/unix/os.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/os.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: os.c,v 1.18 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: os.c,v 1.18 2007/06/19 23:47:18 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/resour=
ce.c
--- a/head/contrib/bind9/lib/isc/unix/resource.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/isc/unix/resource.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: resource.c,v 1.23 2009-02-13 23:48:14 tbox Exp $ */
+/* $Id: resource.c,v 1.23 2009/02/13 23:48:14 tbox Exp $ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/socket=
.c
--- a/head/contrib/bind9/lib/isc/unix/socket.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/isc/unix/socket.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: socket.c,v 1.333.14.9 2011-07-29 02:19:20 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -1584,7 +1584,7 @@
 	if (ev =3D=3D NULL)
 		return (NULL);
=20
-	ev->result =3D ISC_R_UNEXPECTED;
+	ev->result =3D ISC_R_UNSET;
 	ISC_LINK_INIT(ev, ev_link);
 	ISC_LIST_INIT(ev->bufferlist);
 	ev->region.base =3D NULL;
@@ -2037,8 +2037,6 @@
 	if (sock =3D=3D NULL)
 		return (ISC_R_NOMEMORY);
=20
-	result =3D ISC_R_UNEXPECTED;
-
 	sock->common.magic =3D 0;
 	sock->common.impmagic =3D 0;
 	sock->references =3D 0;
@@ -2066,8 +2064,10 @@
 	sock->recvcmsgbuflen =3D cmsgbuflen;
 	if (sock->recvcmsgbuflen !=3D 0U) {
 		sock->recvcmsgbuf =3D isc_mem_get(manager->mctx, cmsgbuflen);
-		if (sock->recvcmsgbuf =3D=3D NULL)
+		if (sock->recvcmsgbuf =3D=3D NULL) {
+			result =3D ISC_R_NOMEMORY;
 			goto error;
+		}
 	}
=20
 	cmsgbuflen =3D 0;
@@ -2084,8 +2084,10 @@
 	sock->sendcmsgbuflen =3D cmsgbuflen;
 	if (sock->sendcmsgbuflen !=3D 0U) {
 		sock->sendcmsgbuf =3D isc_mem_get(manager->mctx, cmsgbuflen);
-		if (sock->sendcmsgbuf =3D=3D NULL)
+		if (sock->sendcmsgbuf =3D=3D NULL) {
+			result =3D ISC_R_NOMEMORY;
 			goto error;
+		}
 	}
=20
 	memset(sock->name, 0, sizeof(sock->name));
@@ -2223,6 +2225,7 @@
=20
 static isc_result_t
 opensocket(isc__socketmgr_t *manager, isc__socket_t *sock) {
+	isc_result_t result;
 	char strbuf[ISC_STRERRORSIZE];
 	const char *err =3D "socket";
 	int tries =3D 0;
@@ -2327,9 +2330,10 @@
 		}
 	}
=20
-	if (make_nonblock(sock->fd) !=3D ISC_R_SUCCESS) {
+	result =3D make_nonblock(sock->fd);
+	if (result !=3D ISC_R_SUCCESS) {
 		(void)close(sock->fd);
-		return (ISC_R_UNEXPECTED);
+		return (result);
 	}
=20
 #ifdef SO_BSDCOMPAT
@@ -3191,10 +3195,12 @@
=20
 	UNLOCK(&sock->lock);
=20
-	if (fd !=3D -1 && (make_nonblock(fd) !=3D ISC_R_SUCCESS)) {
-		(void)close(fd);
-		fd =3D -1;
-		result =3D ISC_R_UNEXPECTED;
+	if (fd !=3D -1) {
+		result =3D make_nonblock(fd);
+		if (result !=3D ISC_R_SUCCESS) {
+			(void)close(fd);
+			fd =3D -1;
+		}
 	}
=20
 	/*
@@ -3729,7 +3735,6 @@
 watcher(void *uap) {
 	isc__socketmgr_t *manager =3D uap;
 	isc_boolean_t done;
-	int ctlfd;
 	int cc;
 #ifdef USE_KQUEUE
 	const char *fnname =3D "kevent()";
@@ -3741,16 +3746,19 @@
 #elif defined (USE_SELECT)
 	const char *fnname =3D "select()";
 	int maxfd;
+	int ctlfd;
 #endif
 	char strbuf[ISC_STRERRORSIZE];
 #ifdef ISC_SOCKET_USE_POLLWATCH
 	pollstate_t pollstate =3D poll_idle;
 #endif
=20
+#if defined (USE_SELECT)
 	/*
 	 * Get the control fd here.  This will never change.
 	 */
 	ctlfd =3D manager->pipe_fds[0];
+#endif
 	done =3D ISC_FALSE;
 	while (!done) {
 		do {
@@ -4551,7 +4559,7 @@
 	isc__socket_t *sock =3D (isc__socket_t *)sock0;
=20
 	event->ev_sender =3D sock;
-	event->result =3D ISC_R_UNEXPECTED;
+	event->result =3D ISC_R_UNSET;
 	ISC_LIST_INIT(event->bufferlist);
 	event->region =3D *region;
 	event->n =3D 0;
@@ -4765,7 +4773,7 @@
 	if ((flags & ISC_SOCKFLAG_NORETRY) !=3D 0)
 		REQUIRE(sock->type =3D=3D isc_sockettype_udp);
 	event->ev_sender =3D sock;
-	event->result =3D ISC_R_UNEXPECTED;
+	event->result =3D ISC_R_UNSET;
 	ISC_LIST_INIT(event->bufferlist);
 	event->region =3D *region;
 	event->n =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/socket=
_p.h
--- a/head/contrib/bind9/lib/isc/unix/socket_p.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/isc/unix/socket_p.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: socket_p.h,v 1.15 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: socket_p.h,v 1.15 2009/09/02 23:48:03 tbox Exp $ */
=20
 #ifndef ISC_SOCKET_P_H
 #define ISC_SOCKET_P_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/stdio.c
--- a/head/contrib/bind9/lib/isc/unix/stdio.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/stdio.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2007, 2011  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2007, 2011, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stdio.c,v 1.8.814.2 2011-03-05 23:52:09 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
@@ -105,12 +105,23 @@
 		return (isc__errno2result(errno));
 }
=20
+/*
+ * OpenBSD has deprecated ENOTSUP in favor of EOPNOTSUPP.
+ */
+#if defined(EOPNOTSUPP) && !defined(ENOTSUP)
+#define ENOTSUP EOPNOTSUPP
+#endif
+
 isc_result_t
 isc_stdio_sync(FILE *f) {
 	int r;
=20
 	r =3D fsync(fileno(f));
-	if (r =3D=3D 0)
+	/*
+	 * fsync is not supported on sockets and pipes which
+	 * result in EINVAL / ENOTSUP.
+	 */
+	if (r =3D=3D 0 || errno =3D=3D EINVAL || errno =3D=3D ENOTSUP)
 		return (ISC_R_SUCCESS);
 	else
 		return (isc__errno2result(errno));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/stdtim=
e.c
--- a/head/contrib/bind9/lib/isc/unix/stdtime.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/isc/unix/stdtime.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stdtime.c,v 1.19 2007-06-19 23:47:18 tbox Exp $ */
+/* $Id: stdtime.c,v 1.19 2007/06/19 23:47:18 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/strerr=
or.c
--- a/head/contrib/bind9/lib/isc/unix/strerror.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/isc/unix/strerror.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: strerror.c,v 1.10 2009-02-16 23:48:04 tbox Exp $ */
+/* $Id: strerror.c,v 1.10 2009/02/16 23:48:04 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/syslog=
.c
--- a/head/contrib/bind9/lib/isc/unix/syslog.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/isc/unix/syslog.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: syslog.c,v 1.8 2007-09-13 04:45:18 each Exp $ */
+/* $Id: syslog.c,v 1.8 2007/09/13 04:45:18 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/unix/time.c
--- a/head/contrib/bind9/lib/isc/unix/time.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/unix/time.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2008, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 1998-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: time.c,v 1.56.608.2 2011-03-12 04:59:19 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -334,7 +334,6 @@
=20
 isc_result_t
 isc_time_secondsastimet(const isc_time_t *t, time_t *secondsp) {
-	isc_uint64_t i;
 	time_t seconds;
=20
 	REQUIRE(t !=3D NULL);
@@ -354,33 +353,16 @@
 	 * pretty much only true if time_t is a signed integer of the same
 	 * size as the return value of isc_time_seconds.
 	 *
-	 * The use of the 64 bit integer ``i'' takes advantage of C's
-	 * conversion rules to either zero fill or sign extend the widened
-	 * type.
-	 *
-	 * Solaris 5.6 gives this warning about the left shift:
-	 *	warning: integer overflow detected: op "<<"
-	 * if the U(nsigned) qualifier is not on the 1.
+	 * If the paradox in the if clause below is true, t->seconds is out
+	 * of range for time_t.
 	 */
 	seconds =3D (time_t)t->seconds;
=20
 	INSIST(sizeof(unsigned int) =3D=3D sizeof(isc_uint32_t));
 	INSIST(sizeof(time_t) >=3D sizeof(isc_uint32_t));
=20
-	if (sizeof(time_t) =3D=3D sizeof(isc_uint32_t) &&	       /* Same size. */
-	    (time_t)0.5 !=3D 0.5 &&	       /* Not a floating point type. */
-	    (i =3D (time_t)-1) !=3D 4294967295u &&		       /* Is signed. */
-	    (seconds &
-	     (1U << (sizeof(time_t) * CHAR_BIT - 1))) !=3D 0U) {   /* Negative. */
-		/*
-		 * This UNUSED() is here to shut up the IRIX compiler:
-		 *	variable "i" was set but never used
-		 * when the value of i *was* used in the third test.
-		 * (Let's hope the compiler got the actual test right.)
-		 */
-		UNUSED(i);
+	if (t->seconds > (~0U>>1) && seconds <=3D (time_t)(~0U>>1))
 		return (ISC_R_RANGE);
-	}
=20
 	*secondsp =3D seconds;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/version.c
--- a/head/contrib/bind9/lib/isc/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.c,v 1.15 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: version.c,v 1.15 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_32/Make=
file.in
--- a/head/contrib/bind9/lib/isc/x86_32/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/x86_32/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_32/incl=
ude/Makefile.in
--- a/head/contrib/bind9/lib/isc/x86_32/include/Makefile.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/x86_32/include/Makefile.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_32/incl=
ude/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/x86_32/include/isc/Makefile.in	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/x86_32/include/isc/Makefile.in	Tue Apr 17 =
11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_32/incl=
ude/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/x86_32/include/isc/atomic.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/x86_32/include/isc/atomic.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.10 2008-01-24 23:47:00 tbox Exp $ */
+/* $Id: atomic.h,v 1.10 2008/01/24 23:47:00 tbox Exp $ */
=20
 #ifndef ISC_ATOMIC_H
 #define ISC_ATOMIC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_64/Make=
file.in
--- a/head/contrib/bind9/lib/isc/x86_64/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/isc/x86_64/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_64/incl=
ude/Makefile.in
--- a/head/contrib/bind9/lib/isc/x86_64/include/Makefile.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/x86_64/include/Makefile.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:09:59 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:09:59 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_64/incl=
ude/isc/Makefile.in
--- a/head/contrib/bind9/lib/isc/x86_64/include/isc/Makefile.in	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/x86_64/include/isc/Makefile.in	Tue Apr 17 =
11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.2 2007-09-14 04:10:00 marka Exp $
+# $Id: Makefile.in,v 1.2 2007/09/14 04:10:00 marka Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isc/x86_64/incl=
ude/isc/atomic.h
--- a/head/contrib/bind9/lib/isc/x86_64/include/isc/atomic.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isc/x86_64/include/isc/atomic.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: atomic.h,v 1.6 2008-01-24 23:47:00 tbox Exp $ */
+/* $Id: atomic.h,v 1.6 2008/01/24 23:47:00 tbox Exp $ */
=20
 #ifndef ISC_ATOMIC_H
 #define ISC_ATOMIC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/Makefile.=
in
--- a/head/contrib/bind9/lib/isccc/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/isccc/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2007, 2009, 2011  Internet Systems Consortium, Inc. =
("ISC")
+# Copyright (C) 2004, 2007, 2009, 2011, 2012  Internet Systems Consortium,=
 Inc. ("ISC")
 # Copyright (C) 2001, 2003  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.12.244.2 2011-02-28 01:20:04 tbox Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/alist.c
--- a/head/contrib/bind9/lib/isccc/alist.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/alist.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: alist.c,v 1.8 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: alist.c,v 1.8 2007/08/28 07:20:43 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/api
--- a/head/contrib/bind9/lib/isccc/api	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/api	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,8 @@
+# LIBINTERFACE ranges
+# 9.6: 50-59, 110-119
+# 9.7: 60-79
+# 9.8: 80-89
+# 9.9: 90-109
 LIBINTERFACE =3D 80
-LIBREVISION =3D 0
+LIBREVISION =3D 1
 LIBAGE =3D 0
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/base64.c
--- a/head/contrib/bind9/lib/isccc/base64.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/base64.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: base64.c,v 1.8 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: base64.c,v 1.8 2007/08/28 07:20:43 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/cc.c
--- a/head/contrib/bind9/lib/isccc/cc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/cc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004-2007  Internet Systems Consortium, Inc. ("I=
SC")
+ * Portions Copyright (C) 2004-2007, 2012  Internet Systems Consortium, In=
c. ("ISC")
  * Portions Copyright (C) 2001-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cc.c,v 1.18 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: cc.c,v 1.18 2007/08/28 07:20:43 tbox Exp $ */
=20
 /*! \file */
=20
@@ -403,16 +403,17 @@
=20
 	if (secret !=3D NULL) {
 		if (checksum_rstart !=3D NULL)
-			return (verify(alist, checksum_rstart,
-				       (source->rend - checksum_rstart),
-				       secret));
-		return (ISCCC_R_BADAUTH);
-	}
-
-	return (ISC_R_SUCCESS);
+			result =3D verify(alist, checksum_rstart,
+					(source->rend - checksum_rstart),
+					secret);
+		else
+			result =3D ISCCC_R_BADAUTH;
+	} else
+		result =3D ISC_R_SUCCESS;
=20
  bad:
-	isccc_sexpr_free(&alist);
+	if (result !=3D ISC_R_SUCCESS)
+		isccc_sexpr_free(&alist);
=20
 	return (result);
 }
@@ -439,7 +440,7 @@
 	}
=20
 	*listp =3D list;
-=09
+
 	return (ISC_R_SUCCESS);
 }
=20
@@ -455,8 +456,8 @@
 		return (ISC_R_UNEXPECTEDEND);
 	GET32(version, source->rstart);
 	if (version !=3D 1)
-		return (ISCCC_R_UNKNOWNVERSION);=09
-=09
+		return (ISCCC_R_UNKNOWNVERSION);
+
 	return (table_fromwire(source, secret, alistp));
 }
=20
@@ -507,7 +508,7 @@
 	if (to !=3D NULL &&
 	    isccc_cc_definestring(_ctrl, "_to", to) =3D=3D NULL)
 		goto bad;
-	=09
+
 	*alistp =3D alist;
=20
 	return (ISC_R_SUCCESS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/ccmsg.c
--- a/head/contrib/bind9/lib/isccc/ccmsg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/ccmsg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ccmsg.c,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: ccmsg.c,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/M=
akefile.in
--- a/head/contrib/bind9/lib/isccc/include/Makefile.in	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/Makefile.in	Tue Apr 17 11:51:51 =
2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.5 2007-06-19 23:47:22 tbox Exp $
+# $Id: Makefile.in,v 1.5 2007/06/19 23:47:22 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/Makefile.in
--- a/head/contrib/bind9/lib/isccc/include/isccc/Makefile.in	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/Makefile.in	Tue Apr 17 11:=
51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.7 2007-06-19 23:47:22 tbox Exp $
+# $Id: Makefile.in,v 1.7 2007/06/19 23:47:22 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/alist.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/alist.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/alist.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: alist.h,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: alist.h,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_ALIST_H
 #define ISCCC_ALIST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/base64.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/base64.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/base64.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: base64.h,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: base64.h,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_BASE64_H
 #define ISCCC_BASE64_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/cc.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/cc.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/cc.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cc.h,v 1.11 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: cc.h,v 1.11 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_CC_H
 #define ISCCC_CC_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/ccmsg.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/ccmsg.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/ccmsg.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ccmsg.h,v 1.11 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: ccmsg.h,v 1.11 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_CCMSG_H
 #define ISCCC_CCMSG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/events.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/events.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/events.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: events.h,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: events.h,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_EVENTS_H
 #define ISCCC_EVENTS_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/lib.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/lib.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/lib.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lib.h,v 1.11 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: lib.h,v 1.11 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_LIB_H
 #define ISCCC_LIB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/result.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/result.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/result.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.h,v 1.12 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: result.h,v 1.12 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_RESULT_H
 #define ISCCC_RESULT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/sexpr.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/sexpr.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/sexpr.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sexpr.h,v 1.11 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: sexpr.h,v 1.11 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_SEXPR_H
 #define ISCCC_SEXPR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/symtab.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/symtab.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/symtab.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: symtab.h,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: symtab.h,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_SYMTAB_H
 #define ISCCC_SYMTAB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/symtype.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/symtype.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/symtype.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: symtype.h,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: symtype.h,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_SYMTYPE_H
 #define ISCCC_SYMTYPE_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/types.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/types.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/types.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: types.h,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: types.h,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_TYPES_H
 #define ISCCC_TYPES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/util.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/util.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/util.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: util.h,v 1.11 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: util.h,v 1.11 2007/08/28 07:20:43 tbox Exp $ */
=20
 #ifndef ISCCC_UTIL_H
 #define ISCCC_UTIL_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/include/i=
sccc/version.h
--- a/head/contrib/bind9/lib/isccc/include/isccc/version.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/include/isccc/version.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.h,v 1.9 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: version.h,v 1.9 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file isccc/version.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/lib.c
--- a/head/contrib/bind9/lib/isccc/lib.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/lib.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lib.c,v 1.9 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: lib.c,v 1.9 2007/08/28 07:20:43 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/result.c
--- a/head/contrib/bind9/lib/isccc/result.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/result.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.c,v 1.10 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: result.c,v 1.10 2007/08/28 07:20:43 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/sexpr.c
--- a/head/contrib/bind9/lib/isccc/sexpr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/sexpr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sexpr.c,v 1.9 2007-08-28 07:20:43 tbox Exp $ */
+/* $Id: sexpr.c,v 1.9 2007/08/28 07:20:43 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/symtab.c
--- a/head/contrib/bind9/lib/isccc/symtab.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/symtab.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: symtab.c,v 1.11 2007-09-13 04:45:18 each Exp $ */
+/* $Id: symtab.c,v 1.11 2007/09/13 04:45:18 each Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccc/version.c
--- a/head/contrib/bind9/lib/isccc/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccc/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.c,v 1.7 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: version.c,v 1.7 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/Makefile=
.in
--- a/head/contrib/bind9/lib/isccfg/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/isccfg/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2005, 2007, 2009, 2011  Internet Systems Consortium,=
 Inc. ("ISC")
+# Copyright (C) 2004, 2005, 2007, 2009, 2011, 2012  Internet Systems Conso=
rtium, Inc. ("ISC")
 # Copyright (C) 2001-2003  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.21.244.3 2011-03-10 04:29:18 each Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/aclconf.c
--- a/head/contrib/bind9/lib/isccfg/aclconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/aclconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1999-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: aclconf.c,v 1.29.72.2 2011-06-17 23:47:11 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
@@ -74,13 +74,11 @@
 cfg_aclconfctx_detach(cfg_aclconfctx_t **actxp) {
 	cfg_aclconfctx_t *actx;
 	dns_acl_t *dacl, *next;
-	isc_mem_t *mctx;
 	unsigned int refs;
=20
 	REQUIRE(actxp !=3D NULL && *actxp !=3D NULL);
=20
 	actx =3D *actxp;
-	mctx =3D actx->mctx;
=20
 	isc_refcount_decrement(&actx->references, &refs);
 	if (refs =3D=3D 0) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/api
--- a/head/contrib/bind9/lib/isccfg/api	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/api	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,8 @@
+# LIBINTERFACE ranges
+# 9.6: 50-59, 110-119
+# 9.7: 60-79
+# 9.8: 80-89
+# 9.9: 90-109
 LIBINTERFACE =3D 82
-LIBREVISION =3D 0
+LIBREVISION =3D 1
 LIBAGE =3D 0
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/dnsconf.c
--- a/head/contrib/bind9/lib/isccfg/dnsconf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/dnsconf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnsconf.c,v 1.4 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: dnsconf.c,v 1.4 2009/09/02 23:48:03 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
Makefile.in
--- a/head/contrib/bind9/lib/isccfg/include/Makefile.in	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/Makefile.in	Tue Apr 17 11:51:51=
 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.7 2007-06-19 23:47:22 tbox Exp $
+# $Id: Makefile.in,v 1.7 2007/06/19 23:47:22 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/Makefile.in
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/Makefile.in	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/Makefile.in	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.12 2007-06-19 23:47:22 tbox Exp $
+# $Id: Makefile.in,v 1.12 2007/06/19 23:47:22 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/aclconf.h
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/aclconf.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/aclconf.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2007, 2010, 2011  Internet Systems Consortium, Inc. =
("ISC")
+ * Copyright (C) 2004-2007, 2010-2012  Internet Systems Consortium, Inc. (=
"ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: aclconf.h,v 1.12.72.2 2011-06-17 23:47:12 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef ISCCFG_ACLCONF_H
 #define ISCCFG_ACLCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/cfg.h
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/cfg.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/cfg.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cfg.h,v 1.46 2010-08-13 23:47:04 tbox Exp $ */
+/* $Id: cfg.h,v 1.46 2010/08/13 23:47:04 tbox Exp $ */
=20
 #ifndef ISCCFG_CFG_H
 #define ISCCFG_CFG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/dnsconf.h
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/dnsconf.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/dnsconf.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,7 +14,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dnsconf.h,v 1.3 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: dnsconf.h,v 1.3 2009/09/02 23:48:03 tbox Exp $ */
=20
 #ifndef ISCCFG_NAMEDCONF_H
 #define ISCCFG_NAMEDCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/grammar.h
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/grammar.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/grammar.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: grammar.h,v 1.24 2011-01-04 23:47:14 tbox Exp $ */
+/* $Id: grammar.h,v 1.24 2011/01/04 23:47:14 tbox Exp $ */
=20
 #ifndef ISCCFG_GRAMMAR_H
 #define ISCCFG_GRAMMAR_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/log.h
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/log.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/log.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.h,v 1.14 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id: log.h,v 1.14 2009/01/18 23:48:14 tbox Exp $ */
=20
 #ifndef ISCCFG_LOG_H
 #define ISCCFG_LOG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/namedconf.h
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/namedconf.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/namedconf.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: namedconf.h,v 1.18 2010-08-11 18:14:20 each Exp $ */
+/* $Id: namedconf.h,v 1.18 2010/08/11 18:14:20 each Exp $ */
=20
 #ifndef ISCCFG_NAMEDCONF_H
 #define ISCCFG_NAMEDCONF_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/include/=
isccfg/version.h
--- a/head/contrib/bind9/lib/isccfg/include/isccfg/version.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/include/isccfg/version.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.h,v 1.9 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: version.h,v 1.9 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file isccfg/version.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/log.c
--- a/head/contrib/bind9/lib/isccfg/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: log.c,v 1.11 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: log.c,v 1.11 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/namedcon=
f.c
--- a/head/contrib/bind9/lib/isccfg/namedconf.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/isccfg/namedconf.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2002, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: namedconf.c,v 1.131.8.4 2011-05-23 20:56:11 each Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -1016,7 +1016,8 @@
=20
 /*
  *  response-policy {
- *	zone <string> [ policy (given|no-op|nxdomain|nodata|cname <domain> ) ];
+ *	zone <string> [ policy (given|disabled|passthru|
+ *					nxdomain|nodata|cname <domain> ) ];
  *  };
  *
  * this is a chimera of doc_optional_keyvalue() and cfg_doc_enum()
@@ -1084,7 +1085,8 @@
 }
=20
 static const char *rpz_policies[] =3D {
-	"given", "no-op", "nxdomain", "nodata", "cname", NULL
+	"given", "disabled", "passthru", "no-op", "nxdomain", "nodata",
+	"cname", NULL
 };
 static cfg_type_t cfg_type_rpz_policylist =3D {
 	"policies", cfg_parse_enum, cfg_print_ustring, cfg_doc_enum,
@@ -1145,7 +1147,7 @@
 static void
 doc_lookaside(cfg_printer_t *pctx, const cfg_type_t *type) {
 	UNUSED(type);
-	cfg_print_cstr(pctx, "( <string> trust-anchor <string> | auto )");
+	cfg_print_cstr(pctx, "( <string> trust-anchor <string> | auto | no )");
 }
=20
 static keyword_type_t trustanchor_kw =3D { "trust-anchor", &cfg_type_astri=
ng };
@@ -1349,6 +1351,7 @@
 	{ "also-notify", &cfg_type_portiplist, 0 },
 	{ "alt-transfer-source", &cfg_type_sockaddr4wild, 0 },
 	{ "alt-transfer-source-v6", &cfg_type_sockaddr6wild, 0 },
+	{ "auto-dnssec", &cfg_type_autodnssec, 0 },
 	{ "check-dup-records", &cfg_type_checkmode, 0 },
 	{ "check-integrity", &cfg_type_boolean, 0 },
 	{ "check-mx", &cfg_type_checkmode, 0 },
@@ -1418,7 +1421,6 @@
 	 */
 	{ "check-names", &cfg_type_checkmode, 0 },
 	{ "ixfr-from-differences", &cfg_type_boolean, 0 },
-	{ "auto-dnssec", &cfg_type_autodnssec, 0 },
 	{ "server-addresses", &cfg_type_bracketed_sockaddrlist, 0 },
 	{ "server-names", &cfg_type_namelist, 0 },
 	{ NULL, NULL, 0 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/parser.c
--- a/head/contrib/bind9/lib/isccfg/parser.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/parser.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012  Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 2000-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: parser.c,v 1.139.14.2 2011-03-11 06:47:09 marka Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/isccfg/version.c
--- a/head/contrib/bind9/lib/isccfg/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/isccfg/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.c,v 1.7 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: version.c,v 1.7 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/Makefile.=
in
--- a/head/contrib/bind9/lib/lwres/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/lwres/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.34 2007-06-19 23:47:22 tbox Exp $
+# $Id: Makefile.in,v 1.34 2007/06/19 23:47:22 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/api
--- a/head/contrib/bind9/lib/lwres/api	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/api	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,8 @@
+# LIBINTERFACE ranges
+# 9.6: 50-59, 110-119
+# 9.7: 60-79
+# 9.8: 80-89
+# 9.9: 90-109
 LIBINTERFACE =3D 80
-LIBREVISION =3D 1
+LIBREVISION =3D 2
 LIBAGE =3D 0
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/assert_p.h
--- a/head/contrib/bind9/lib/lwres/assert_p.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/assert_p.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: assert_p.h,v 1.14.814.2 2011-03-12 04:59:19 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef LWRES_ASSERT_P_H
 #define LWRES_ASSERT_P_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/context.c
--- a/head/contrib/bind9/lib/lwres/context.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/context.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: context.c,v 1.55 2009-09-02 23:48:03 tbox Exp $ */
+/* $Id: context.c,v 1.55 2009/09/02 23:48:03 tbox Exp $ */
=20
 /*! \file context.c
    lwres_context_create() creates a #lwres_context_t structure for use in
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/context_p=
.h
--- a/head/contrib/bind9/lib/lwres/context_p.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/lwres/context_p.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: context_p.h,v 1.19 2008-12-17 23:47:58 tbox Exp $ */
+/* $Id: context_p.h,v 1.19 2008/12/17 23:47:58 tbox Exp $ */
=20
 #ifndef LWRES_CONTEXT_P_H
 #define LWRES_CONTEXT_P_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/gai_strer=
ror.c
--- a/head/contrib/bind9/lib/lwres/gai_strerror.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/lwres/gai_strerror.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gai_strerror.c,v 1.22 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: gai_strerror.c,v 1.22 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file gai_strerror.c
  * lwres_gai_strerror() returns an error message corresponding to an
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/getaddrin=
fo.c
--- a/head/contrib/bind9/lib/lwres/getaddrinfo.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/lwres/getaddrinfo.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -18,7 +18,7 @@
  * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getaddrinfo.c,v 1.54 2008-11-25 23:47:23 tbox Exp $ */
+/* $Id: getaddrinfo.c,v 1.54 2008/11/25 23:47:23 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/gethost.c
--- a/head/contrib/bind9/lib/lwres/gethost.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/gethost.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: gethost.c,v 1.34 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: gethost.c,v 1.34 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/getipnode=
.c
--- a/head/contrib/bind9/lib/lwres/getipnode.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/lwres/getipnode.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getipnode.c,v 1.47 2009-09-01 23:47:45 tbox Exp $ */
+/* $Id: getipnode.c,v 1.47 2009/09/01 23:47:45 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/getnamein=
fo.c
--- a/head/contrib/bind9/lib/lwres/getnameinfo.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/bind9/lib/lwres/getnameinfo.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, I=
nc. ("ISC")
+ * Portions Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems C=
onsortium, Inc. ("ISC")
  * Portions Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getnameinfo.c,v 1.39 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
@@ -62,51 +62,51 @@
  *    sockaddr sa which is salen bytes long. The hostname is of length
  *    hostlen and is returned via *host. The maximum length of the hostname
  *    is 1025 bytes: #NI_MAXHOST.
- *=20
+ *
  *    The name of the service associated with the port number in sa is
  *    returned in *serv. It is servlen bytes long. The maximum length of t=
he
  *    service name is #NI_MAXSERV - 32 bytes.
- *=20
+ *
  *    The flags argument sets the following bits:
- *=20
+ *
  * \li   #NI_NOFQDN:
  *           A fully qualified domain name is not required for local hosts.
  *           The local part of the fully qualified domain name is returned
  *           instead.
- *=20
+ *
  * \li   #NI_NUMERICHOST
  *           Return the address in numeric form, as if calling inet_ntop(),
  *           instead of a host name.
- *=20
+ *
  * \li   #NI_NAMEREQD
  *           A name is required. If the hostname cannot be found in the DNS
  *           and this flag is set, a non-zero error code is returned. If t=
he
  *           hostname is not found and the flag is not set, the address is
  *           returned in numeric form.
- *=20
+ *
  * \li   #NI_NUMERICSERV
  *           The service name is returned as a digit string representing t=
he
  *           port number.
- *=20
+ *
  * \li   #NI_DGRAM
  *           Specifies that the service being looked up is a datagram
  *           service, and causes getservbyport() to be called with a second
  *           argument of "udp" instead of its default of "tcp". This is
  *           required for the few ports (512-514) that have different
  *           services for UDP and TCP.
- *=20
+ *
  * \section getnameinfo_return Return Values
- *=20
+ *
  *    lwres_getnameinfo() returns 0 on success or a non-zero error code if
  *    an error occurs.
- *=20
+ *
  * \section getname_see See Also
- *=20
- *    RFC2133, getservbyport(),=20
+ *
+ *    RFC2133, getservbyport(),
  *    lwres_getnamebyaddr(). lwres_net_ntop().
- *=20
+ *
  * \section getnameinfo_bugs Bugs
- *=20
+ *
  *    RFC2133 fails to define what the nonzero return values of
  *    getnameinfo() are.
  */
@@ -219,6 +219,7 @@
 	default:
 		port =3D 0;
 		addr =3D NULL;
+		POST(port); POST(addr);
 		INSIST(0);
 	}
 	proto =3D (flags & NI_DGRAM) ? "udp" : "tcp";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/getrrset.c
--- a/head/contrib/bind9/lib/lwres/getrrset.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/getrrset.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: getrrset.c,v 1.18 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: getrrset.c,v 1.18 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/herror.c
--- a/head/contrib/bind9/lib/lwres/herror.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/herror.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Portions Copyright (C) 2004, 2005, 2007, 2011  Internet Systems Consort=
ium, Inc. ("ISC")
+ * Portions Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems C=
onsortium, Inc. ("ISC")
  * Portions Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -72,7 +72,7 @@
 #if defined(LIBC_SCCS) && !defined(lint)
 static const char sccsid[] =3D "@(#)herror.c	8.1 (Berkeley) 6/4/93";
 static const char rcsid[] =3D
-	"$Id: herror.c,v 1.17.814.2 2011-03-12 04:59:19 tbox Exp $";
+	"$Id$";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/M=
akefile.in
--- a/head/contrib/bind9/lib/lwres/include/Makefile.in	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/Makefile.in	Tue Apr 17 11:51:51 =
2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.8 2007-06-19 23:47:22 tbox Exp $
+# $Id: Makefile.in,v 1.8 2007/06/19 23:47:22 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/Makefile.in
--- a/head/contrib/bind9/lib/lwres/include/lwres/Makefile.in	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/Makefile.in	Tue Apr 17 11:=
51:51 2012 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.23 2007-06-19 23:47:22 tbox Exp $
+# $Id: Makefile.in,v 1.23 2007/06/19 23:47:22 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/context.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/context.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/context.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: context.h,v 1.23 2008-12-17 23:47:58 tbox Exp $ */
+/* $Id: context.h,v 1.23 2008/12/17 23:47:58 tbox Exp $ */
=20
 #ifndef LWRES_CONTEXT_H
 #define LWRES_CONTEXT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/int.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/int.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/int.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: int.h,v 1.14 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: int.h,v 1.14 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_INT_H
 #define LWRES_INT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/ipv6.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/ipv6.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/ipv6.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ipv6.h,v 1.16 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: ipv6.h,v 1.16 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_IPV6_H
 #define LWRES_IPV6_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/lang.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/lang.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/lang.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lang.h,v 1.13 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: lang.h,v 1.13 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_LANG_H
 #define LWRES_LANG_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/list.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/list.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/list.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: list.h,v 1.14 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: list.h,v 1.14 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_LIST_H
 #define LWRES_LIST_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/lwbuffer.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/lwbuffer.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/lwbuffer.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwbuffer.h,v 1.22 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: lwbuffer.h,v 1.22 2007/06/19 23:47:23 tbox Exp $ */
=20
=20
 /*! \file lwres/lwbuffer.h
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/lwpacket.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/lwpacket.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/lwpacket.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwpacket.h,v 1.24 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: lwpacket.h,v 1.24 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_LWPACKET_H
 #define LWRES_LWPACKET_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/lwres.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/lwres.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/lwres.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwres.h,v 1.57 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: lwres.h,v 1.57 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_LWRES_H
 #define LWRES_LWRES_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/netdb.h.in
--- a/head/contrib/bind9/lib/lwres/include/lwres/netdb.h.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/netdb.h.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: netdb.h.in,v 1.41 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id: netdb.h.in,v 1.41 2009/01/18 23:48:14 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/platform.h.in
--- a/head/contrib/bind9/lib/lwres/include/lwres/platform.h.in	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/platform.h.in	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: platform.h.in,v 1.21 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: platform.h.in,v 1.21 2007/06/19 23:47:23 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/result.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/result.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/result.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: result.h,v 1.21 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: result.h,v 1.21 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_RESULT_H
 #define LWRES_RESULT_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/stdlib.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/stdlib.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/stdlib.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: stdlib.h,v 1.6 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: stdlib.h,v 1.6 2007/06/19 23:47:23 tbox Exp $ */
=20
 #ifndef LWRES_STDLIB_H
 #define LWRES_STDLIB_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/include/l=
wres/version.h
--- a/head/contrib/bind9/lib/lwres/include/lwres/version.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/include/lwres/version.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.h,v 1.9 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: version.h,v 1.9 2007/06/19 23:47:23 tbox Exp $ */
=20
 /*! \file lwres/version.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwbuffer.c
--- a/head/contrib/bind9/lib/lwres/lwbuffer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/lwbuffer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwbuffer.c,v 1.15 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: lwbuffer.c,v 1.15 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwconfig.c
--- a/head/contrib/bind9/lib/lwres/lwconfig.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/lwconfig.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004-2008, 2011  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2008, 2011, 2012  Internet Systems Consortium, Inc. =
("ISC")
  * Copyright (C) 2000-2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwconfig.c,v 1.48.436.2 2011-03-12 04:59:19 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwinetato=
n.c
--- a/head/contrib/bind9/lib/lwres/lwinetaton.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/lwres/lwinetaton.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -72,7 +72,7 @@
  */
 #if defined(LIBC_SCCS) && !defined(lint)
 static char sccsid[] =3D "@(#)inet_addr.c	8.1 (Berkeley) 6/17/93";
-static char rcsid[] =3D "$Id: lwinetaton.c,v 1.16 2007-06-19 23:47:22 tbox=
 Exp $";
+static char rcsid[] =3D "$Id: lwinetaton.c,v 1.16 2007/06/19 23:47:22 tbox=
 Exp $";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwinetnto=
p.c
--- a/head/contrib/bind9/lib/lwres/lwinetntop.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/lwres/lwinetntop.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -19,7 +19,7 @@
  */
 #if defined(LIBC_SCCS) && !defined(lint)
 static char rcsid[] =3D
-	"$Id: lwinetntop.c,v 1.18 2007-06-19 23:47:22 tbox Exp $";
+	"$Id: lwinetntop.c,v 1.18 2007/06/19 23:47:22 tbox Exp $";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwinetpto=
n.c
--- a/head/contrib/bind9/lib/lwres/lwinetpton.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/lwres/lwinetpton.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1996-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -19,7 +19,7 @@
  */
=20
 #if defined(LIBC_SCCS) && !defined(lint)
-static char rcsid[] =3D "$Id: lwinetpton.c,v 1.12 2007-06-19 23:47:22 tbox=
 Exp $";
+static char rcsid[] =3D "$Id$";
 #endif /* LIBC_SCCS and not lint */
=20
 #include <config.h>
@@ -41,7 +41,7 @@
 static int inet_pton4(const char *src, unsigned char *dst);
 static int inet_pton6(const char *src, unsigned char *dst);
=20
-/*!=20
+/*!
  * int
  * lwres_net_pton(af, src, dst)
  *	convert from presentation format (which usually means ASCII printable)
@@ -103,7 +103,12 @@
 		} else if (ch =3D=3D '.' && saw_digit) {
 			if (octets =3D=3D 4)
 				return (0);
-			*++tp =3D 0;
+			/*
+			 * "clang --analyse" generates warnings using:
+			 * 		*++tp =3D 0;
+			 */
+			tp++;
+			*tp =3D 0;
 			saw_digit =3D 0;
 		} else
 			return (0);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwpacket.c
--- a/head/contrib/bind9/lib/lwres/lwpacket.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/lwpacket.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwpacket.c,v 1.18 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: lwpacket.c,v 1.18 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwres_gab=
n.c
--- a/head/contrib/bind9/lib/lwres/lwres_gabn.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/lwres/lwres_gabn.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwres_gabn.c,v 1.33 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: lwres_gabn.c,v 1.33 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file lwres_gabn.c
    These are low-level routines for creating and parsing lightweight
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwres_gnb=
a.c
--- a/head/contrib/bind9/lib/lwres/lwres_gnba.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/lwres/lwres_gnba.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwres_gnba.c,v 1.28 2007-09-24 17:18:25 each Exp $ */
+/* $Id: lwres_gnba.c,v 1.28 2007/09/24 17:18:25 each Exp $ */
=20
 /*! \file lwres_gnba.c
    These are low-level routines for creating and parsing lightweight
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwres_grb=
n.c
--- a/head/contrib/bind9/lib/lwres/lwres_grbn.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/lwres/lwres_grbn.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwres_grbn.c,v 1.10 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: lwres_grbn.c,v 1.10 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file lwres_grbn.c
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwres_noo=
p.c
--- a/head/contrib/bind9/lib/lwres/lwres_noop.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/bind9/lib/lwres/lwres_noop.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwres_noop.c,v 1.19 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: lwres_noop.c,v 1.19 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/lwresutil=
.c
--- a/head/contrib/bind9/lib/lwres/lwresutil.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/lwres/lwresutil.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: lwresutil.c,v 1.34 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id: lwresutil.c,v 1.34 2007/06/19 23:47:22 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/Makef=
ile.in
--- a/head/contrib/bind9/lib/lwres/man/Makefile.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/bind9/lib/lwres/man/Makefile.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.9 2007-06-19 23:47:23 tbox Exp $
+# $Id: Makefile.in,v 1.9 2007/06/19 23:47:23 tbox Exp $
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
.3
--- a/head/contrib/bind9/lib/lwres/man/lwres.3	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/bind9/lib/lwres/man/lwres.3	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres.3,v 1.29 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres.docbook	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres.docbook	Tue Apr 17 11:51:51 20=
12 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres.docbook,v 1.10 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id: lwres.docbook,v 1.10 2007/06/18 23:47:51 tbox Exp $ -->
 <refentry>
=20
   <refentryinfo>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
.html
--- a/head/contrib/bind9/lib/lwres/man/lwres.html	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres.html	Tue Apr 17 11:51:51 2012 =
+0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres.html,v 1.24 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -22,7 +22,7 @@
 <meta name=3D"generator" content=3D"DocBook XSL Stylesheets V1.71.1">
 </head>
 <body bgcolor=3D"white" text=3D"black" link=3D"#0000FF" vlink=3D"#840084" =
alink=3D"#0000FF"><div class=3D"refentry" lang=3D"en">
-<a name=3D"id2476275"></a><div class=3D"titlepage"></div>
+<a name=3D"id2476274"></a><div class=3D"titlepage"></div>
 <div class=3D"refnamediv">
 <h2>Name</h2>
 <p>lwres — introduction to the lightweight resolver library</p>
@@ -32,7 +32,7 @@
 <div class=3D"funcsynopsis"><pre class=3D"funcsynopsisinfo">#include <l=
wres/lwres.h></pre></div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543348"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543350"></a><h2>DESCRIPTION</h2>
 <p>
       The BIND 9 lightweight resolver library is a simple, name service
       independent stub resolver library.  It provides hostname-to-address
@@ -47,7 +47,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543361"></a><h2>OVERVIEW</h2>
+<a name=3D"id2543363"></a><h2>OVERVIEW</h2>
 <p>
       The lwresd library implements multiple name service APIs.
       The standard
@@ -101,7 +101,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543425"></a><h2>CLIENT-SIDE LOW-LEVEL API CALL FLOW</h2>
+<a name=3D"id2543427"></a><h2>CLIENT-SIDE LOW-LEVEL API CALL FLOW</h2>
 <p>
       When a client program wishes to make an lwres request using the
       native low-level API, it typically performs the following
@@ -149,7 +149,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543573"></a><h2>SERVER-SIDE LOW-LEVEL API CALL FLOW</h2>
+<a name=3D"id2543575"></a><h2>SERVER-SIDE LOW-LEVEL API CALL FLOW</h2>
 <p>
       When implementing the server side of the lightweight resolver
       protocol using the lwres library, a sequence of actions like the
@@ -191,7 +191,7 @@
 <p></p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543656"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543658"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_gethos=
tent</span>(3)</span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_get=
ipnode</span>(3)</span>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_buffer.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_buffer.3	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_buffer.3	Tue Apr 17 11:51:51 2=
012 +0300
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_buffer.3,v 1.27 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_buffer.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_buffer.docbook	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_buffer.docbook	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_buffer.docbook,v 1.10 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id: lwres_buffer.docbook,v 1.10 2007/06/18 23:47:51 tbox Exp $ -->
 <refentry>
   <refentryinfo>
     <date>Jun 30, 2000</date>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_buffer.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_buffer.html	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_buffer.html	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_buffer.html,v 1.22 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -262,7 +262,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543892"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543893"></a><h2>DESCRIPTION</h2>
 <p>
       These functions provide bounds checked access to a region of memory
       where data is being read or written.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_config.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_config.3	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_config.3	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_config.3,v 1.27 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -100,7 +100,7 @@
 .PP
 \fI/etc/resolv.conf\fR
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_config.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_config.docbook	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_config.docbook	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_config.docbook,v 1.9 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
   <refentryinfo>
=20
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_config.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_config.html	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_config.html	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_config.html,v 1.23 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -90,7 +90,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543441"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543445"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_conf_init()</code>
       creates an empty
       <span class=3D"type">lwres_conf_t</span>
@@ -123,7 +123,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543508"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543512"></a><h2>RETURN VALUES</h2>
 <p><code class=3D"function">lwres_conf_parse()</code>
       returns <span class=3D"errorcode">LWRES_R_SUCCESS</span>
       if it successfully read and parsed
@@ -142,13 +142,13 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543545"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543549"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">stdio</span>=
(3)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">resolver<=
/span>(5)</span>.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543571"></a><h2>FILES</h2>
+<a name=3D"id2543575"></a><h2>FILES</h2>
 <p><code class=3D"filename">/etc/resolv.conf</code>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_context.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_context.3	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_context.3	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001, 2003 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_context.3,v 1.29 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -164,7 +164,7 @@
 \fBmalloc\fR(3),
 \fBfree\fR(3).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001, 2003 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_context.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_context.docbook	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_context.docbook	Tue Apr 17 11:=
51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_context.docbook,v 1.11 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_context.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_context.html	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_context.html	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001, 2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_context.html,v 1.24 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -172,7 +172,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543531"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543536"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_context_create()</code>
       creates a <span class=3D"type">lwres_context_t</span> structure for =
use in
       lightweight resolver operations.  It holds a socket and other
@@ -258,7 +258,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543719"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543723"></a><h2>RETURN VALUES</h2>
 <p><code class=3D"function">lwres_context_create()</code>
       returns <span class=3D"errorcode">LWRES_R_NOMEMORY</span> if memory =
for
       the <span class=3D"type">struct lwres_context</span> could not be al=
located,
@@ -283,7 +283,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543769"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543773"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_conf_i=
nit</span>(3)</span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">malloc</s=
pan>(3)</span>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gabn.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_gabn.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gabn.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_gabn.3,v 1.28 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -189,7 +189,7 @@
 .PP
 \fBlwres_packet\fR(3)
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gabn.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_gabn.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gabn.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_gabn.docbook,v 1.10 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gabn.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_gabn.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gabn.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_gabn.html,v 1.25 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -178,7 +178,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543522"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543526"></a><h2>DESCRIPTION</h2>
 <p>
       These are low-level routines for creating and parsing
       lightweight resolver name-to-address lookup request and
@@ -278,7 +278,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543667"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543671"></a><h2>RETURN VALUES</h2>
 <p>
       The getaddrbyname opcode functions
       <code class=3D"function">lwres_gabnrequest_render()</code>,
@@ -316,7 +316,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543733"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543737"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_packet=
</span>(3)</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gai_strerror.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.3	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.3	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_gai_strerror.3,v 1.28 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -123,7 +123,7 @@
 \fBgetaddrinfo\fR(3),
 \fBRFC2133\fR().
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gai_strerror.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.docbook	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.docbook	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_gai_strerror.docbook,v 1.10 2007-06-18 23:47:51 tbox Exp $=
 -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gai_strerror.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.html	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gai_strerror.html	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_gai_strerror.html,v 1.25 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -42,7 +42,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543361"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543365"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_gai_strerror()</code>
       returns an error message corresponding to an error code returned by
       <code class=3D"function">getaddrinfo()</code>.
@@ -110,7 +110,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543576"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543580"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">strerror</sp=
an>(3)</span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_get=
addrinfo</span>(3)</span>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getaddrinfo.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.3	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.3	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001, 2003 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_getaddrinfo.3,v 1.32 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -240,7 +240,7 @@
 \fBsendmsg\fR(2),
 \fBsocket\fR(2).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001, 2003 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getaddrinfo.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.docbook	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.docbook	Tue Apr 17=
 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_getaddrinfo.docbook,v 1.13 2007-06-18 23:47:51 tbox Exp $ =
-->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getaddrinfo.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.html	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getaddrinfo.html	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001, 2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_getaddrinfo.html,v 1.28 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -89,7 +89,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543412"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543416"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_getaddrinfo()</code>
       is used to get a list of IP addresses and port numbers for host
       <em class=3D"parameter"><code>hostname</code></em> and service
@@ -283,7 +283,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543789"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543794"></a><h2>RETURN VALUES</h2>
 <p><code class=3D"function">lwres_getaddrinfo()</code>
       returns zero on success or one of the error codes listed in
       <span class=3D"citerefentry"><span class=3D"refentrytitle">gai_strer=
ror</span>(3)</span>
@@ -294,7 +294,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543827"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543831"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres</span>=
(3)</span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_get=
addrinfo</span>(3)</span>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gethostent.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_gethostent.3	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gethostent.3	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_gethostent.3,v 1.30 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -309,7 +309,7 @@
 or
 \fBNIS\fR, consequently the above functions don't, either.
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gethostent.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_gethostent.docbook	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gethostent.docbook	Tue Apr 17 =
11:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_gethostent.docbook,v 1.11 2007-06-18 23:47:51 tbox Exp $ -=
->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gethostent.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_gethostent.html	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gethostent.html	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_gethostent.html,v 1.25 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -228,7 +228,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543608"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543612"></a><h2>DESCRIPTION</h2>
 <p>
       These functions provide hostname-to-address and
       address-to-hostname lookups by means of the lightweight resolver.
@@ -366,7 +366,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543959"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543963"></a><h2>RETURN VALUES</h2>
 <p>
       The functions
       <code class=3D"function">lwres_gethostbyname()</code>,
@@ -430,7 +430,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544193"></a><h2>SEE ALSO</h2>
+<a name=3D"id2544197"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">gethostent</=
span>(3)</span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_get=
ipnode</span>(3)</span>,
@@ -439,7 +439,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2544227"></a><h2>BUGS</h2>
+<a name=3D"id2544231"></a><h2>BUGS</h2>
 <p><code class=3D"function">lwres_gethostbyname()</code>,
       <code class=3D"function">lwres_gethostbyname2()</code>,
       <code class=3D"function">lwres_gethostbyaddr()</code>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getipnode.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_getipnode.3	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getipnode.3	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001, 2003 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_getipnode.3,v 1.29 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -200,7 +200,7 @@
 \fBlwres_getnameinfo\fR(3),
 \fBlwres_hstrerror\fR(3).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001, 2003 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getipnode.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_getipnode.docbook	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getipnode.docbook	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001, 2003  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_getipnode.docbook,v 1.12 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getipnode.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_getipnode.html	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getipnode.html	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001, 2003 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_getipnode.html,v 1.26 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -98,7 +98,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543431"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543435"></a><h2>DESCRIPTION</h2>
 <p>
       These functions perform thread safe, protocol independent
       nodename-to-address and address-to-nodename
@@ -217,7 +217,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543689"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543693"></a><h2>RETURN VALUES</h2>
 <p>
       If an error occurs,
       <code class=3D"function">lwres_getipnodebyname()</code>
@@ -261,7 +261,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543786"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543790"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">RFC2553</spa=
n></span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres</sp=
an>(3)</span>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getnameinfo.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.3	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.3	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_getnameinfo.3,v 1.30 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -111,7 +111,7 @@
 \fBgetnameinfo\fR(3)
 are.
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getnameinfo.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.docbook	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.docbook	Tue Apr 17=
 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_getnameinfo.docbook,v 1.10 2007-06-18 23:47:51 tbox Exp $ =
-->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getnameinfo.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.html	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getnameinfo.html	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_getnameinfo.html,v 1.24 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -82,7 +82,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543393"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543397"></a><h2>DESCRIPTION</h2>
 <p>
        This function is equivalent to the
       <span class=3D"citerefentry"><span class=3D"refentrytitle">getnamein=
fo</span>(3)</span> function defined in RFC2133.
@@ -149,13 +149,13 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543534"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543539"></a><h2>RETURN VALUES</h2>
 <p><code class=3D"function">lwres_getnameinfo()</code>
       returns 0 on success or a non-zero error code if an error occurs.
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543546"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543550"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">RFC2133</spa=
n></span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">getservby=
port</span>(3)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres</sp=
an>(3)</span>,
@@ -165,7 +165,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543604"></a><h2>BUGS</h2>
+<a name=3D"id2543608"></a><h2>BUGS</h2>
 <p>
       RFC2133 fails to define what the nonzero return values of
       <span class=3D"citerefentry"><span class=3D"refentrytitle">getnamein=
fo</span>(3)</span>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getrrsetbyname.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.3	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.3	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_getrrsetbyname.3,v 1.26 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -158,7 +158,7 @@
 .PP
 \fBlwres\fR(3).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getrrsetbyname.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.docbook	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.docbook	Tue Apr=
 17 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_getrrsetbyname.docbook,v 1.10 2007-06-18 23:47:51 tbox Exp=
 $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_getrrsetbyname.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.html	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_getrrsetbyname.html	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_getrrsetbyname.html,v 1.24 2009-07-11 01:12:46 tbox Exp $ =
-->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -102,7 +102,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543414"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543418"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_getrrsetbyname()</code>
       gets a set of resource records associated with a
       <em class=3D"parameter"><code>hostname</code></em>, <em class=3D"par=
ameter"><code>class</code></em>,
@@ -150,7 +150,7 @@
 <p></p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543526"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543530"></a><h2>RETURN VALUES</h2>
 <p><code class=3D"function">lwres_getrrsetbyname()</code>
       returns zero on success, and one of the following error codes if
       an error occurred:
@@ -184,7 +184,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543626"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543630"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres</span>=
(3)</span>.
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gnba.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_gnba.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gnba.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_gnba.3,v 1.28 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -177,7 +177,7 @@
 .PP
 \fBlwres_packet\fR(3).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gnba.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_gnba.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gnba.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_gnba.docbook,v 1.11 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_gnba.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_gnba.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_gnba.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_gnba.html,v 1.25 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -183,7 +183,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543525"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543529"></a><h2>DESCRIPTION</h2>
 <p>
       These are low-level routines for creating and parsing
       lightweight resolver address-to-name lookup request and
@@ -270,7 +270,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543665"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543669"></a><h2>RETURN VALUES</h2>
 <p>
       The getnamebyaddr opcode functions
       <code class=3D"function">lwres_gnbarequest_render()</code>,
@@ -308,7 +308,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543731"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543735"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_packet=
</span>(3)</span>.
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_hstrerror.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_hstrerror.3	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_hstrerror.3	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_hstrerror.3,v 1.28 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -93,7 +93,7 @@
 \fBherror\fR(3),
 \fBlwres_hstrerror\fR(3).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_hstrerror.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_hstrerror.docbook	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_hstrerror.docbook	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_hstrerror.docbook,v 1.11 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_hstrerror.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_hstrerror.html	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_hstrerror.html	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_hstrerror.html,v 1.24 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -50,7 +50,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543379"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543383"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_herror()</code>
       prints the string <em class=3D"parameter"><code>s</code></em> on
       <span class=3D"type">stderr</span> followed by the string generated =
by
@@ -84,7 +84,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543497"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543501"></a><h2>RETURN VALUES</h2>
 <p>
       The string <span class=3D"errorname">Unknown resolver error</span> i=
s returned by
       <code class=3D"function">lwres_hstrerror()</code>
@@ -94,7 +94,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543517"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543522"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">herror</span=
>(3)</span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_hst=
rerror</span>(3)</span>.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_inetntop.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_inetntop.3	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_inetntop.3	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_inetntop.3,v 1.27 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -71,7 +71,7 @@
 \fBinet_ntop\fR(3),
 \fBerrno\fR(3).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_inetntop.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_inetntop.docbook	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_inetntop.docbook	Tue Apr 17 11=
:51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_inetntop.docbook,v 1.10 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_inetntop.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_inetntop.html	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_inetntop.html	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_inetntop.html,v 1.24 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -62,7 +62,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543379"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543383"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_net_ntop()</code>
       converts an IP address of protocol family
       <em class=3D"parameter"><code>af</code></em> — IPv4 or IPv6 &#=
8212; at
@@ -80,7 +80,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543411"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543415"></a><h2>RETURN VALUES</h2>
 <p>
       If successful, the function returns <em class=3D"parameter"><code>ds=
t</code></em>:
       a pointer to a string containing the presentation format of the
@@ -93,7 +93,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543444"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543448"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">RFC1884</spa=
n></span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">inet_ntop=
</span>(3)</span>,
       <span class=3D"citerefentry"><span class=3D"refentrytitle">errno</sp=
an>(3)</span>.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_noop.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_noop.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_noop.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_noop.3,v 1.29 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -177,7 +177,7 @@
 .PP
 \fBlwres_packet\fR(3)
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_noop.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_noop.docbook	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_noop.docbook	Tue Apr 17 11:51:=
51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_noop.docbook,v 1.11 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_noop.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_noop.html	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_noop.html	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_noop.html,v 1.26 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -179,7 +179,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543522"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543526"></a><h2>DESCRIPTION</h2>
 <p>
       These are low-level routines for creating and parsing
       lightweight resolver no-op request and response messages.
@@ -270,7 +270,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543672"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543676"></a><h2>RETURN VALUES</h2>
 <p>
       The no-op opcode functions
       <code class=3D"function">lwres_nooprequest_render()</code>,
@@ -309,7 +309,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543738"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543742"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_packet=
</span>(3)</span>
     </p>
 </div>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_packet.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_packet.3	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_packet.3	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_packet.3,v 1.30 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -164,7 +164,7 @@
 both functions return
 \fBLWRES_R_UNEXPECTEDEND\fR.
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_packet.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_packet.docbook	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_packet.docbook	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_packet.docbook,v 1.13 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_packet.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_packet.html	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_packet.html	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_packet.html,v 1.27 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -66,7 +66,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543389"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543394"></a><h2>DESCRIPTION</h2>
 <p>
       These functions rely on a
       <span class=3D"type">struct lwres_lwpacket</span>
@@ -219,7 +219,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543706"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543710"></a><h2>RETURN VALUES</h2>
 <p>
       Successful calls to
       <code class=3D"function">lwres_lwpacket_renderheader()</code> and
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_resutil.3
--- a/head/contrib/bind9/lib/lwres/man/lwres_resutil.3	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_resutil.3	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC=
")
+.\" Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc.=
 ("ISC")
 .\" Copyright (C) 2000, 2001 Internet Software Consortium.
 .\"=20
 .\" Permission to use, copy, modify, and/or distribute this software for a=
ny
@@ -13,7 +13,7 @@
 .\" OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE=
 OR
 .\" PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $Id: lwres_resutil.3,v 1.29 2009-07-11 01:12:46 tbox Exp $
+.\" $Id$
 .\"
 .hy 0
 .ad l
@@ -164,7 +164,7 @@
 \fBlwres_buffer\fR(3),
 \fBlwres_gabn\fR(3).
 .SH "COPYRIGHT"
-Copyright \(co 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+Copyright \(co 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. ("=
ISC")
 .br
 Copyright \(co 2000, 2001 Internet Software Consortium.
 .br
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_resutil.docbook
--- a/head/contrib/bind9/lib/lwres/man/lwres_resutil.docbook	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_resutil.docbook	Tue Apr 17 11:=
51:51 2012 +0300
@@ -2,7 +2,7 @@
                "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
 	       [<!ENTITY mdash "—">]>
 <!--
- - Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ - Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  - Copyright (C) 2000, 2001  Internet Software Consortium.
  -
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -18,7 +18,7 @@
  - PERFORMANCE OF THIS SOFTWARE.
 -->
=20
-<!-- $Id: lwres_resutil.docbook,v 1.12 2007-06-18 23:47:51 tbox Exp $ -->
+<!-- $Id$ -->
 <refentry>
=20
   <refentryinfo>
@@ -36,6 +36,7 @@
       <year>2004</year>
       <year>2005</year>
       <year>2007</year>
+      <year>2012</year>
       <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
     </copyright>
     <copyright>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/man/lwres=
_resutil.html
--- a/head/contrib/bind9/lib/lwres/man/lwres_resutil.html	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/man/lwres_resutil.html	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,5 @@
 <!--
- - Copyright (C) 2004, 2005, 2007 Internet Systems Consortium, Inc. ("ISC")
+ - Copyright (C) 2004, 2005, 2007, 2012 Internet Systems Consortium, Inc. =
("ISC")
  - Copyright (C) 2000, 2001 Internet Software Consortium.
  -=20
  - Permission to use, copy, modify, and/or distribute this software for any
@@ -14,7 +14,7 @@
  - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE =
OR
  - PERFORMANCE OF THIS SOFTWARE.
 -->
-<!-- $Id: lwres_resutil.html,v 1.26 2009-07-11 01:12:46 tbox Exp $ -->
+<!-- $Id$ -->
 <html>
 <head>
 <meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3DISO-8859=
-1">
@@ -134,7 +134,7 @@
 </div>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543466"></a><h2>DESCRIPTION</h2>
+<a name=3D"id2543470"></a><h2>DESCRIPTION</h2>
 <p><code class=3D"function">lwres_string_parse()</code>
       retrieves a DNS-encoded string starting the current pointer of
       lightweight resolver buffer <em class=3D"parameter"><code>b</code></=
em>: i.e.
@@ -210,7 +210,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543605"></a><h2>RETURN VALUES</h2>
+<a name=3D"id2543609"></a><h2>RETURN VALUES</h2>
 <p>
       Successful calls to
       <code class=3D"function">lwres_string_parse()</code>
@@ -248,7 +248,7 @@
     </p>
 </div>
 <div class=3D"refsect1" lang=3D"en">
-<a name=3D"id2543676"></a><h2>SEE ALSO</h2>
+<a name=3D"id2543681"></a><h2>SEE ALSO</h2>
 <p><span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_buffer=
</span>(3)</span>,
=20
       <span class=3D"citerefentry"><span class=3D"refentrytitle">lwres_gab=
n</span>(3)</span>.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/print.c
--- a/head/contrib/bind9/lib/lwres/print.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/print.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007, 2011  Internet Systems Consortium, Inc.=
 ("ISC")
+ * Copyright (C) 2004, 2005, 2007, 2011, 2012  Internet Systems Consortium=
, Inc. ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: print.c,v 1.10.814.2 2011-03-12 04:59:19 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/print_p.h
--- a/head/contrib/bind9/lib/lwres/print_p.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/print_p.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2007, 2010  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2007, 2010, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: print_p.h,v 1.6 2010-08-16 23:46:52 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef LWRES_PRINT_P_H
 #define LWRES_PRINT_P_H 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/strtoul.c
--- a/head/contrib/bind9/lib/lwres/strtoul.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/strtoul.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 2003  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -53,7 +53,7 @@
 static char sccsid[] =3D "@(#)strtoul.c	8.1 (Berkeley) 6/4/93";
 #endif /* LIBC_SCCS and not lint */
=20
-/* $Id: strtoul.c,v 1.4 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id$ */
=20
 #include <config.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/unix/Make=
file.in
--- a/head/contrib/bind9/lib/lwres/unix/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/bind9/lib/lwres/unix/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2007  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004, 2007, 2012  Internet Systems Consortium, Inc. ("ISC")
 # Copyright (C) 2001  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4 2007-06-19 23:47:23 tbox Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/unix/incl=
ude/Makefile.in
--- a/head/contrib/bind9/lib/lwres/unix/include/Makefile.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/unix/include/Makefile.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2007  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004, 2007, 2012  Internet Systems Consortium, Inc. ("ISC")
 # Copyright (C) 2001  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4 2007-06-19 23:47:23 tbox Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/unix/incl=
ude/lwres/Makefile.in
--- a/head/contrib/bind9/lib/lwres/unix/include/lwres/Makefile.in	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/unix/include/lwres/Makefile.in	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2007  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004, 2007, 2012  Internet Systems Consortium, Inc. ("ISC")
 # Copyright (C) 2001  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.4 2007-06-19 23:47:23 tbox Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/unix/incl=
ude/lwres/net.h
--- a/head/contrib/bind9/lib/lwres/unix/include/lwres/net.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/unix/include/lwres/net.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 2000-2002  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: net.h,v 1.9 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id$ */
=20
 #ifndef LWRES_NET_H
 #define LWRES_NET_H 1
@@ -65,7 +65,7 @@
 #ifdef LWRES_PLATFORM_NEEDNETINET6IN6H
 #include <netinet6/in6.h>	/* Required on BSD/OS for in6_pktinfo. */
 #endif
-#include <net/if.h>=09
+#include <net/if.h>
=20
 #include <lwres/lang.h>
=20
@@ -80,7 +80,7 @@
 /*!
  * Required for some pre RFC2133 implementations.
  * IN6ADDR_ANY_INIT and IN6ADDR_LOOPBACK_INIT were added in
- * draft-ietf-ipngwg-bsd-api-04.txt or draft-ietf-ipngwg-bsd-api-05.txt. =20
+ * draft-ietf-ipngwg-bsd-api-04.txt or draft-ietf-ipngwg-bsd-api-05.txt.
  * If 's6_addr' is defined then assume that there is a union and three
  * levels otherwise assume two levels required.
  */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/lib/lwres/version.c
--- a/head/contrib/bind9/lib/lwres/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/lib/lwres/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 2000, 2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: version.c,v 1.12 2007-06-19 23:47:22 tbox Exp $ */
+/* $Id$ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/make/Makefile.in
--- a/head/contrib/bind9/make/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/make/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2007  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004, 2007, 2012  Internet Systems Consortium, Inc. ("ISC")
 # Copyright (C) 1998-2001  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: Makefile.in,v 1.16 2007-06-19 23:47:24 tbox Exp $
+# $Id$
=20
 srcdir =3D	@srcdir@
 VPATH =3D		@srcdir@
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/make/includes.in
--- a/head/contrib/bind9/make/includes.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/make/includes.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc. =
("ISC")
 # Copyright (C) 1999-2001  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: includes.in,v 1.21 2007-06-19 23:47:24 tbox Exp $
+# $Id$
=20
 # Search for machine-generated header files in the build tree,
 # and for normal headers in the source tree (${top_srcdir}).
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/make/mkdep.in
--- a/head/contrib/bind9/make/mkdep.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/make/mkdep.in	Tue Apr 17 11:51:51 2012 +0300
@@ -140,25 +140,37 @@
 else
     @MKDEPCC@ @MKDEPCFLAGS@ ${newargs} |
     sed "
-	s; \./; ;g
+	s; \\./; ;g
+	s; \\\\; ;g
 	@LIBTOOL_MKDEP_SED@
 	$SED" |
-    awk '{
-	if ($1 !=3D prev) {
+    awk '$1 ~ /:$/ {
 		if (rec !=3D "")
-			print rec;
-		rec =3D $0;
-		prev =3D $1;
+			 print rec;
+		if (NF =3D=3D 1)
+			rec =3D $1;
+		else
+			rec =3D $1 " " $2;
+		for (i =3D 3; i <=3D NF; i++) {
+			if (length(rec $i) > 76) {
+				print rec " \\";
+				rec =3D "    " $i;
+			} else {
+				rec =3D rec " " $i;
+			}
+		}
+		next;
 	}
-	else {
-		if (length(rec $2) > 78) {
-			print rec;
-			rec =3D $0;
+	{
+		for (i =3D 1; i <=3D NF; i++) {
+			if (length(rec $i) > 76) {
+				print rec, "\\";
+				rec =3D  "    " $i;
+			} else {
+				rec =3D rec " " $i;
+			}
 		}
-		else
-			rec =3D rec " " $2
 	}
-    }
     END {
 	print rec
     }' >> $TMP
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/make/rules.in
--- a/head/contrib/bind9/make/rules.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/make/rules.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# Copyright (C) 2004-2009, 2011  Internet Systems Consortium, Inc. ("ISC")
+# Copyright (C) 2004-2009, 2011, 2012  Internet Systems Consortium, Inc. (=
"ISC")
 # Copyright (C) 1998-2003  Internet Software Consortium.
 #
 # Permission to use, copy, modify, and/or distribute this software for any
@@ -13,7 +13,7 @@
 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 # PERFORMANCE OF THIS SOFTWARE.
=20
-# $Id: rules.in,v 1.68.346.2 2011-02-28 01:20:04 tbox Exp $
+# $Id$
=20
 ###
 ### Common Makefile rules for BIND 9.
@@ -214,7 +214,21 @@
 		-o $@tmp2 $${BASEOBJS} $@-symtbl. at O@ $${LIBS0} ${NOSYMLIBS}; \
 		${MKSYMTBL_PROGRAM} ${top_srcdir}/util/mksymtbl.pl \
 		-o [email protected] $@tmp2; \
-		diff [email protected] [email protected] || exit 1;\
+		count=3D0; \
+		until diff [email protected] [email protected] > /dev/null ; \
+		do \
+			count=3D`expr $$count + 1` ; \
+			test $$count =3D 42 && exit 1 ; \
+			rm -f [email protected] $@-symtbl. at O@; \
+			${MKSYMTBL_PROGRAM} ${top_srcdir}/util/mksymtbl.pl \
+			-o [email protected] $@tmp2 || exit 1; \
+			$(MAKE) $@-symtbl. at O@ || exit 1; \
+			${LIBTOOL_MODE_LINK} ${PURIFY} ${CC} ${CFLAGS} \
+			${LDFLAGS} -o $@tmp2 $${BASEOBJS} $@-symtbl. at O@ \
+			$${LIBS0} ${NOSYMLIBS}; \
+			${MKSYMTBL_PROGRAM} ${top_srcdir}/util/mksymtbl.pl \
+			-o [email protected] $@tmp2; \
+		done ; \
 		mv $@tmp2 $@; \
 		rm -f $@tmp0 $@tmp1 $@tmp2 [email protected]; \
 	fi
@@ -236,20 +250,20 @@
 			(cd $$i; ${MAKE} ${MAKEDEFS} DESTDIR=3D"${DESTDIR}" $@) || exit 1; \
 		fi; \
 	done
-	@if [ X"${VPATH}" !=3D X ] ; then \
+	@if [ X"${srcdir}" !=3D X. ] ; then \
 		if [ X"${SRCS}" !=3D X -a X"${PSRCS}" !=3D X ] ; then \
-			echo ${MKDEP} -vpath ${VPATH} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
-			${MKDEP} -vpath ${VPATH} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
-			echo ${MKDEP} -vpath ${VPATH} -ap ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRCS=
}; \
-			${MKDEP} -vpath ${VPATH} -ap ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRCS}; \
+			echo ${MKDEP} -vpath ${srcdir} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
+			${MKDEP} -vpath ${srcdir} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
+			echo ${MKDEP} -vpath ${srcdir} -ap ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRC=
S}; \
+			${MKDEP} -vpath ${srcdir} -ap ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRCS}; \
 			${DEPENDEXTRA} \
 		elif [ X"${SRCS}" !=3D X ] ; then \
-			echo ${MKDEP} -vpath ${VPATH} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
-			${MKDEP} -vpath ${VPATH} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
+			echo ${MKDEP} -vpath ${srcdir} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
+			${MKDEP} -vpath ${srcdir} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${SRCS}; \
 			${DEPENDEXTRA} \
 		elif [ X"${PSRCS}" !=3D X ] ; then \
-			echo ${MKDEP} -vpath ${VPATH} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRCS}; \
-			${MKDEP} -vpath ${VPATH} -p ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRCS}; \
+			echo ${MKDEP} -vpath ${srcdir} ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRCS}; \
+			${MKDEP} -vpath ${srcdir} -p ${ALL_CPPFLAGS} ${ALL_CFLAGS} ${PSRCS}; \
 			${DEPENDEXTRA} \
 		fi \
 	else \
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/mkinstalldirs
--- a/head/contrib/bind9/mkinstalldirs	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/mkinstalldirs	Tue Apr 17 11:51:51 2012 +0300
@@ -4,7 +4,7 @@
 # Created: 1993-05-16
 # Public domain
=20
-# $Id: mkinstalldirs,v 1.1 2000-09-20 19:05:51 gson Exp $
+# $Id$
=20
 errstatus=3D0
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/bind9/version
--- a/head/contrib/bind9/version	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/bind9/version	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-# $Id: version,v 1.53.8.9.6.1 2011-11-16 09:32:07 marka Exp $
+# $Id$
 #=20
 # This file must follow /bin/sh rules.  It is imported directly via
 # configure.
 #
 MAJORVER=3D9
 MINORVER=3D8
-PATCHVER=3D1
-RELEASETYPE=3D-P
-RELEASEVER=3D1
+PATCHVER=3D2
+RELEASETYPE=3D
+RELEASEVER=3D
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/com_err.3
--- a/head/contrib/com_err/com_err.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/com_err.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,96 +1,245 @@
-.\" Copyright (c) 1988 Massachusetts Institute of Technology,
-.\" Student Information Processing Board.  All rights reserved.
+.\" Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" $FreeBSD$
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.TH COM_ERR 3 "22 Nov 1988" SIPB
-.SH NAME
-com_err \- common error display routine
-.SH SYNOPSIS
-.nf
- #include <com_err.h>
-.PP
-void com_err (whoami, code, format, ...);
-	const char *whoami;
-	long code;
-	const char *format;
-.PP
-proc =3D set_com_err_hook (proc);
-.fi
-void (*
-.I proc
-) (const char *, long, const char *, va_list);
-.nf
-.PP
-proc =3D reset_com_err_hook ();
-.PP
-void initialize_XXXX_error_table ();
-.fi
-.SH DESCRIPTION
-.I Com_err
-displays an error message on the standard error stream
-.I stderr
-(see
-.IR stdio (3S))
-composed of the
-.I whoami
-string, which should specify the program name or some subportion of
-a program, followed by an error message generated from the
-.I code
-value (derived from
-.IR compile_et (1)),
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
+.\"
+.\" This manpage was contributed by Gregory McGarry.
+.\"
+.Dd July  7, 2005
+.Dt COM_ERR 3
+.Os
+.Sh NAME
+.Nm com_err ,
+.Nm com_err_va ,
+.Nm error_message ,
+.Nm error_table_name ,
+.Nm init_error_table ,
+.Nm set_com_err_hook ,
+.Nm reset_com_err_hook ,
+.Nm add_to_error_table ,
+.Nm initialize_error_table_r
+.Nm free_error_table ,
+.Nm com_right
+.Nd common error display library
+.Sh LIBRARY
+Common Error Library (libcom_err, -lcom_err)
+.Sh SYNOPSIS
+.Fd #include <stdio.h>
+.Fd #include <stdarg.h>
+.Fd #include <krb5/com_err.h>
+.Fd #include \&"XXX_err.h\&"
+.Pp
+typedef void (*errf)(const char *, long, const char *, ...);
+.Ft void
+.Fn com_err "const char *whoami" "long code" "const char *format" "..."
+.Ft void
+.Fn com_err_va "const char *whoami" "long code" "const char *format" "..."
+.Ft const char *
+.Fn error_message "long code"
+.Ft const char *
+.Fn error_table_name "int num"
+.Ft int
+.Fn init_error_table "const char **msgs" "long base" "int count"
+.Ft errf
+.Fn set_com_err_hook "errf func"
+.Ft errf
+.Fn reset_com_err_hook ""
+.Ft void
+.Fn add_to_error_table "struct et_list *new_table"
+.Ft void
+.Fn initialize_error_table_r "struct et_list **et_list" "const char **msgs=
" "int base" "long count"
+.Ft void
+.Fn free_error_table "struct et_list *"
+.Ft const char *
+.Fn com_right "struct et_list *list" long code"
+.Sh DESCRIPTION
+The
+.Nm
+library provides a common error-reporting mechanism for defining and
+accessing error codes and descriptions for application software
+packages.  Error descriptions are defined in a table and error codes
+are used to index the table.  The error table, the descriptions and
+the error codes are generated using
+.Xr compile_et 1 .
+.Pp
+The error table is registered with the
+.Nm
+library by calling its initialisation function defined in its header
+file.  The initialisation function is generally defined as
+.Fn initialize_<name>_error_table ,
+where
+.Em name
+is the name of the error table.
+.Pp
+If a thread-safe version of the library is needed
+.Fn initialize_<name>_error_table_r
+that internally calls
+.Fn initialize_error_table_r
+instead be used.
+.Pp
+Any variable which is to contain an error code should be declared
+.Em <name>_error_number
+where
+.Em name
+is the name of the error table.
+.Sh FUNCTIONS
+The following functions are available to the application developer:
+.Bl -tag -width compact
+.It Fn com_err "whoami" "code" "format" "..."
+Displays an error message on standard error composed of the
+.Fa whoami
+string, which should specify the program name, followed by an error
+message generated from
+.Fa code ,
 and a string produced using the
-.I format
-string and any following arguments, in the same style as
-.IR fprintf (3).
+.Xr printf 3
+.Fa format
+string and any following arguments.  If
+.Fa format
+is NULL, the formatted message will not be
+printed.  The argument
+.Fa format
+may not be omitted.
+.It Fn com_err_va "whoami" "code" "format" "va_list args"
+This routine provides an interface, equivalent to
+.Fn com_err ,
+which may be used by higher-level variadic functions (functions which
+accept variable numbers of arguments).
+.It Fn error_message "code"
+Returns the character string error message associate with
+.Fa code .
+If
+.Fa code is associated with an unknown error table, or if
+.Fa code
+is associated with a known error table but is not in the table, a
+string of the form `Unknown code XXXX NN' is returned, where XXXX is
+the error table name produced by reversing the compaction performed on
+the error table number implied by that error code, and NN is the
+offset from that base value.
+.Pp
+Although this routine is available for use when needed, its use should
+be left to circumstances which render
+.Fn com_err
+unusable.
+.Pp
+.Fn com_right
+returns the error string just like
+.Fa com_err
+but in a thread-safe way.
+.Pp
+.It Fn error_table_name "num"
+Convert a machine-independent error table number
+.Fa num
+into an error table name.
+.It Fn init_error_table "msgs" "base" "count"
+Initialise the internal error table with the array of character string
+error messages in
+.Fa msgs
+of length
+.Fa count .
+The error codes are assigned incrementally from
+.Fa base .
+This function is useful for using the error-reporting mechanism with
+custom error tables that have not been generated with
+.Xr compile_et 1 .
+Although this routine is available for use when needed, its use should
+be restricted.
+.Pp
+.Fn initialize_error_table_r
+initialize the
+.Fa et_list
+in the same way as
+.Fn init_error_table ,
+but in a thread-safe way.
+.Pp
+.It Fn set_com_err_hook "func"
+Provides a hook into the
+.Nm
+library to allow the routine
+.Fa func
+to be dynamically substituted for
+.Fn com_err .
+After
+.Fn set_com_err_hook
+ has been called, calls to
+.Fn com_err
+will turn into calls to the new hook routine.  This function is
+intended to be used in daemons to use a routine which calls
+.Xr syslog 3 ,
+or in a window system application to pop up a dialogue box.
+.It Fn reset_com_err_hook ""
+Turns off the hook set in
+.Fn set_com_err_hook .
+.It Fn add_to_error_table "new_table"
+Add the error table, its messages strings and error codes in
+.Fa new_table
+to the internal error table.
+.El
+.Sh EXAMPLES
+The following is an example using the table defined in
+.Xr compile_et 1 :
+.Pp
+.Bd -literal
+	#include <stdio.h>
+	#include <stdarg.h>
+	#include <syslog.h>
=20
-The behavior of
-.I com_err
-can be modified using
-.I set_com_err_hook;
-this defines a procedure which is called with the arguments passed to
-.I com_err,
-instead of the default internal procedure which sends the formatted
-text to error output.  Thus the error messages from a program can all
-easily be diverted to another form of diagnostic logging, such as
-.IR syslog (3).
-.I Reset_com_err_hook
-may be used to restore the behavior of
-.I com_err
-to its default form.  Both procedures return the previous ``hook''
-value.  These ``hook'' procedures must have the declaration given for
-.I proc
-above in the synopsis.
+	#include "test_err.h"
=20
-The
-.I initialize_XXXX_error_table
-routine is generated mechanically by
-.IR compile_et (1)
-from a source file containing names and associated strings.  Each
-table has a name of up to four characters, which is used in place of
-the
-.B XXXX
-in the name of the routine.  These routines should be called before
-any of the corresponding error codes are used, so that the
-.I com_err
-library will recognize error codes from these tables when they are
-used.
+	void
+	hook(const char *whoami, long code,
+		const char *format, va_list args)
+	{
+		char buffer[BUFSIZ];
+		static int initialized =3D 0;
=20
-The
-.B com_err.h
-header file should be included in any source file that uses routines
-from the
-.I com_err
-library; executable files must be linked using
-.I ``-lcom_err''
-in order to cause the
-.I com_err
-library to be included.
+		if (!initialized) {
+			openlog(whoami, LOG_NOWAIT, LOG_DAEMON);
+			initialized =3D 1;
+		}
+		vsprintf(buffer, format, args);
+		syslog(LOG_ERR, "%s %s", error_message(code), buffer);
+	}
=20
-.\" .IR for manual entries
-.\" .PP for paragraph breaks
+	int
+	main(int argc, char *argv[])
+	{
+		char *whoami =3D argv[0];
=20
-.SH "SEE ALSO"
-compile_et (1), syslog (3).
-
-Ken Raeburn, "A Common Error Description Library for UNIX".
+		initialize_test_error_table();
+		com_err(whoami, TEST_INVAL, "before hook");
+		set_com_err_hook(hook);
+		com_err(whoami, TEST_IO, "after hook");
+		return (0);
+	}
+.Ed
+.Sh SEE ALSO
+.Xr compile_et 1
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/com_err.c
--- a/head/contrib/com_err/com_err.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/com_err.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,37 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
-/* $FreeBSD$ */
=20
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-RCSID("$Id: com_err.c 14930 2005-04-24 19:43:06Z lha $");
-#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -44,7 +40,7 @@
 struct et_list *_et_list =3D NULL;
=20
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 error_message (long code)
 {
     static char msg[128];
@@ -57,23 +53,23 @@
     }
     if (p !=3D NULL && *p !=3D '\0') {
 	strlcpy(msg, p, sizeof(msg));
-    } else=20
+    } else
 	snprintf(msg, sizeof(msg), "Unknown error %ld", code);
     return msg;
 }
=20
-int
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 init_error_table(const char **msgs, long base, int count)
 {
     initialize_error_table_r(&_et_list, msgs, count, base);
     return 0;
 }
=20
-static void
+static void KRB5_CALLCONV
 default_proc (const char *whoami, long code, const char *fmt, va_list args)
     __attribute__((__format__(__printf__, 3, 0)));
-=20
-static void
+
+static void KRB5_CALLCONV
 default_proc (const char *whoami, long code, const char *fmt, va_list args)
 {
     if (whoami)
@@ -87,19 +83,19 @@
=20
 static errf com_err_hook =3D default_proc;
=20
-void=20
-com_err_va (const char *whoami,=20
-	    long code,=20
-	    const char *fmt,=20
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err_va (const char *whoami,
+	    long code,
+	    const char *fmt,
 	    va_list args)
 {
     (*com_err_hook) (whoami, code, fmt, args);
 }
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 com_err (const char *whoami,
 	 long code,
-	 const char *fmt,=20
+	 const char *fmt,
 	 ...)
 {
     va_list ap;
@@ -108,7 +104,7 @@
     va_end(ap);
 }
=20
-errf
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
 set_com_err_hook (errf new)
 {
     errf old =3D com_err_hook;
@@ -117,12 +113,12 @@
 	com_err_hook =3D new;
     else
 	com_err_hook =3D default_proc;
-   =20
+
     return old;
 }
=20
-errf
-reset_com_err_hook (void)=20
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+reset_com_err_hook (void)
 {
     return set_com_err_hook(NULL);
 }
@@ -135,7 +131,7 @@
=20
 static char buf[6];
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 error_table_name(int num)
 {
     int ch;
@@ -157,7 +153,7 @@
     return(buf);
 }
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 add_to_error_table(struct et_list *new_table)
 {
     struct et_list *et;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/com_err.h
--- a/head/contrib/com_err/com_err.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/com_err.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,66 +1,76 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $FreeBSD$ */
-/* $Id: com_err.h 15566 2005-07-07 14:58:07Z lha $ */
+/* $Id$ */
=20
 /* MIT compatible com_err library */
=20
 #ifndef __COM_ERR_H__
 #define __COM_ERR_H__
=20
-#include <sys/cdefs.h>
-#include <stdarg.h>
-
 #include <com_right.h>
 #include <stdarg.h>
=20
-typedef void (*errf) __P((const char *, long, const char *, va_list));
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(X)
+#endif
=20
-const char * error_message (long);
-int init_error_table (const char**, long, int);
+typedef void (KRB5_CALLCONV *errf) (const char *, long, const char *, va_l=
ist);
=20
-void com_err_va __P((const char *, long, const char *, va_list))
-    __printflike(3, 0);
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_message (long);
=20
-void com_err __P((const char *, long, const char *, ...))
-    __printflike(3, 4);
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+init_error_table (const char**, long, int);
=20
-errf set_com_err_hook (errf);
-errf reset_com_err_hook (void);
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err_va (const char *, long, const char *, va_list)
+    __attribute__((format(printf, 3, 0)));
=20
-const char *error_table_name  (int num);
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err (const char *, long, const char *, ...)
+    __attribute__((format(printf, 3, 4)));
=20
-void add_to_error_table (struct et_list *new_table);
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+set_com_err_hook (errf);
+
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+reset_com_err_hook (void);
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_table_name  (int num);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+add_to_error_table (struct et_list *new_table);
=20
 #endif /* __COM_ERR_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/com_right.h
--- a/head/contrib/com_err/com_right.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/com_right.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,76 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: com_right.h 14551 2005-02-03 08:45:13Z lha $ */
-/* $FreeBSD$ */
+/* $Id$ */
=20
 #ifndef __COM_RIGHT_H__
 #define __COM_RIGHT_H__
=20
+#ifndef KRB5_LIB_FUNCTION
+#if defined(_WIN32)
+#define KRB5_LIB_FUNCTION __declspec(dllimport)
+#else
+#define KRB5_LIB_FUNCTION
+#endif
+#endif
+
+#ifndef KRB5_LIB_CALL
+#if defined(_WIN32)
+#define KRB5_LIB_CALL __stdcall
+#else
+#define KRB5_LIB_CALL
+#endif
+#endif
+
+#ifndef KRB5_LIB_VARIABLE
+#if defined(_WIN32)
+#define KRB5_LIB_VARIABLE __declspec(dllimport)
+#else
+#define KRB5_LIB_VARIABLE
+#endif
+#endif
+
+#ifdef _WIN32
+#define KRB5_CALLCONV __stdcall
+#else
+#define KRB5_CALLCONV
+#endif
+
 #include <sys/cdefs.h>
+
+#ifdef __STDC__
 #include <stdarg.h>
+#endif
=20
 struct error_table {
     char const * const * msgs;
@@ -51,8 +83,16 @@
 };
 extern struct et_list *_et_list;
=20
-const char *com_right (struct et_list *list, long code);
-void initialize_error_table_r (struct et_list **, const char **, int, long=
);
-void free_error_table (struct et_list *);
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right (struct et_list *list, long code);
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right_r (struct et_list *list, long code, char *, size_t);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+initialize_error_table_r (struct et_list **, const char **, int, long);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+free_error_table (struct et_list *);
=20
 #endif /* __COM_RIGHT_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/compile_et.c
--- a/head/contrib/com_err/compile_et.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/compile_et.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,45 +1,44 @@
 /*
- * Copyright (c) 1998-2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998-2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
-/* $FreeBSD$ */
=20
 #undef ROKEN_RENAME
+
+#define	rk_PATH_DELIM	'/'
+
 #include "compile_et.h"
 #include <getarg.h>
=20
-#if 0
-RCSID("$Id: compile_et.c 15426 2005-06-16 19:21:42Z lha $");
-#endif
-
+#include <roken.h>
 #include <err.h>
 #include "parse.h"
=20
@@ -77,13 +76,15 @@
 	return 1;
=20
     fprintf(c_file, "/* Generated from %s */\n", filename);
-    if(id_str)=20
+    if(id_str)
 	fprintf(c_file, "/* %s */\n", id_str);
     fprintf(c_file, "\n");
     fprintf(c_file, "#include <stddef.h>\n");
     fprintf(c_file, "#include <com_err.h>\n");
     fprintf(c_file, "#include \"%s\"\n", hfn);
     fprintf(c_file, "\n");
+    fprintf(c_file, "#define N_(x) (x)\n");
+    fprintf(c_file, "\n");
=20
     fprintf(c_file, "static const char *%s_error_strings[] =3D {\n", name);
=20
@@ -92,9 +93,10 @@
 	    fprintf(c_file, "\t/* %03d */ \"Reserved %s error (%d)\",\n",
 		    n, name, n);
 	    n++;
-	   =20
+
 	}
-	fprintf(c_file, "\t/* %03d */ \"%s\",\n", ec->number, ec->string);
+	fprintf(c_file, "\t/* %03d */ N_(\"%s\"),\n",
+		ec->number, ec->string);
     }
=20
     fprintf(c_file, "\tNULL\n");
@@ -102,11 +104,11 @@
     fprintf(c_file, "\n");
     fprintf(c_file, "#define num_errors %d\n", number);
     fprintf(c_file, "\n");
-    fprintf(c_file,=20
-	    "void initialize_%s_error_table_r(struct et_list **list)\n",=20
+    fprintf(c_file,
+	    "void initialize_%s_error_table_r(struct et_list **list)\n",
 	    name);
     fprintf(c_file, "{\n");
-    fprintf(c_file,=20
+    fprintf(c_file,
 	    "    initialize_error_table_r(list, %s_error_strings, "
 	    "num_errors, ERROR_TABLE_BASE_%s);\n", name, name);
     fprintf(c_file, "}\n");
@@ -137,9 +139,9 @@
     for(p =3D fn; *p; p++)
 	if(!isalnum((unsigned char)*p))
 	    *p =3D '_';
-   =20
+
     fprintf(h_file, "/* Generated from %s */\n", filename);
-    if(id_str)=20
+    if(id_str)
 	fprintf(h_file, "/* %s */\n", id_str);
     fprintf(h_file, "\n");
     fprintf(h_file, "#ifndef %s\n", fn);
@@ -147,18 +149,18 @@
     fprintf(h_file, "\n");
     fprintf(h_file, "struct et_list;\n");
     fprintf(h_file, "\n");
-    fprintf(h_file,=20
+    fprintf(h_file,
 	    "void initialize_%s_error_table_r(struct et_list **);\n",
 	    name);
     fprintf(h_file, "\n");
     fprintf(h_file, "void initialize_%s_error_table(void);\n", name);
-    fprintf(h_file, "#define init_%s_err_tbl initialize_%s_error_table\n",=20
+    fprintf(h_file, "#define init_%s_err_tbl initialize_%s_error_table\n",
 	    name, name);
     fprintf(h_file, "\n");
     fprintf(h_file, "typedef enum %s_error_number{\n", name);
=20
     for(ec =3D codes; ec; ec =3D ec->next) {
-	fprintf(h_file, "\t%s =3D %ld%s\n", ec->name, base_id + ec->number,=20
+	fprintf(h_file, "\t%s =3D %ld%s\n", ec->name, base_id + ec->number,
 		(ec->next !=3D NULL) ? "," : "");
     }
=20
@@ -166,6 +168,8 @@
     fprintf(h_file, "\n");
     fprintf(h_file, "#define ERROR_TABLE_BASE_%s %ld\n", name, base_id);
     fprintf(h_file, "\n");
+    fprintf(h_file, "#define COM_ERR_BINDDOMAIN_%s \"heim_com_err%ld\"\n",=
 name, base_id);
+    fprintf(h_file, "\n");
     fprintf(h_file, "#endif /* %s */\n", fn);
=20
=20
@@ -179,8 +183,10 @@
     return generate_c() || generate_h();
 }
=20
+int version_flag;
 int help_flag;
 struct getargs args[] =3D {
+    { "version", 0, arg_flag, &version_flag },
     { "help", 0, arg_flag, &help_flag }
 };
 int num_args =3D sizeof(args) / sizeof(args[0]);
@@ -203,27 +209,31 @@
 	usage(1);
     if(help_flag)
 	usage(0);
+    if(version_flag) {
+	print_version(NULL);
+	exit(0);
+    }
=20
-    if(optidx =3D=3D argc)=20
+    if(optidx =3D=3D argc)
 	usage(1);
     filename =3D argv[optidx];
     yyin =3D fopen(filename, "r");
     if(yyin =3D=3D NULL)
 	err(1, "%s", filename);
-=09
-   =20
-    p =3D strrchr(filename, '/');
+
+
+    p =3D strrchr(filename, rk_PATH_DELIM);
     if(p)
 	p++;
     else
 	p =3D filename;
     strlcpy(Basename, p, sizeof(Basename));
-   =20
+
     Basename[strcspn(Basename, ".")] =3D '\0';
-   =20
+
     snprintf(hfn, sizeof(hfn), "%s.h", Basename);
     snprintf(cfn, sizeof(cfn), "%s.c", Basename);
-   =20
+
     yyparse();
     if(numerror)
 	return 1;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/compile_et.h
--- a/head/contrib/com_err/compile_et.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/compile_et.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,46 +1,41 @@
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: compile_et.h 15426 2005-06-16 19:21:42Z lha $ */
-/* $FreeBSD$ */
+/* $Id$ */
=20
 #ifndef __COMPILE_ET_H__
 #define __COMPILE_ET_H__
=20
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
 #include <err.h>
 #include <stdio.h>
 #include <string.h>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/error.c
--- a/head/contrib/com_err/error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,52 +1,72 @@
 /*
- * Copyright (c) 1997, 1998, 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-RCSID("$Id: error.c 9724 2001-02-28 20:00:13Z joda $");
-#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <com_right.h>
=20
-const char *
+#ifdef LIBINTL
+#include <libintl.h>
+#else
+#define dgettext(d,s) (s)
+#endif
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 com_right(struct et_list *list, long code)
 {
     struct et_list *p;
-    for (p =3D list; p; p =3D p->next) {
+    for (p =3D list; p; p =3D p->next)
 	if (code >=3D p->table->base && code < p->table->base + p->table->n_msgs)
 	    return p->table->msgs[code - p->table->base];
+    return NULL;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right_r(struct et_list *list, long code, char *str, size_t len)
+{
+    struct et_list *p;
+    for (p =3D list; p; p =3D p->next) {
+	if (code >=3D p->table->base && code < p->table->base + p->table->n_msgs)=
 {
+	    const char *msg =3D p->table->msgs[code - p->table->base];
+#ifdef LIBINTL
+	    char domain[12 + 20];
+	    snprintf(domain, sizeof(domain), "heim_com_err%d", p->table->base);
+#endif
+	    strlcpy(str, dgettext(domain, msg), len);
+	    return str;
+	}
     }
     return NULL;
 }
@@ -56,9 +76,9 @@
     struct error_table et;
 };
=20
-void
-initialize_error_table_r(struct et_list **list,=20
-			 const char **messages,=20
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+initialize_error_table_r(struct et_list **list,
+			 const char **messages,
 			 int num_errors,
 			 long base)
 {
@@ -78,9 +98,9 @@
     et->next =3D NULL;
     *end =3D et;
 }
-		=09
=20
-void
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 free_error_table(struct et_list *et)
 {
     while(et){
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/lex.h
--- a/head/contrib/com_err/lex.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/lex.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: lex.h 8451 2000-06-22 00:42:52Z assar $ */
+/* $Id$ */
=20
-void error_message (const char *, ...)
+void _lex_error_message (const char *, ...)
 __attribute__ ((format (printf, 1, 2)));
=20
 int yylex(void);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/lex.l
--- a/head/contrib/com_err/lex.l	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/lex.l	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,36 @@
 %{
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
-/* $FreeBSD$ */
=20
 /*
  * This is to handle the definition of this symbol in some AIX
@@ -45,10 +44,6 @@
 #include "parse.h"
 #include "lex.h"
=20
-#if 0
-RCSID("$Id: lex.l 15143 2005-05-16 08:52:54Z lha $");
-#endif
-
 static unsigned lineno =3D 1;
 static int getstring(void);
=20
@@ -58,6 +53,7 @@
=20
 %}
=20
+%option nounput
=20
 %%
 et			{ return ET; }
@@ -79,7 +75,7 @@
=20
 #ifndef yywrap /* XXX */
 int
-yywrap ()=20
+yywrap ()
 {
      return 1;
 }
@@ -99,7 +95,7 @@
 	    continue;
 	}
 	if(c =3D=3D '\n'){
-	    error_message("unterminated string");
+	    _lex_error_message("unterminated string");
 	    lineno++;
 	    break;
 	}
@@ -119,7 +115,7 @@
 }
=20
 void
-error_message (const char *format, ...)
+_lex_error_message (const char *format, ...)
 {
      va_list args;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/parse.y
--- a/head/contrib/com_err/parse.y	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/parse.y	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,39 @@
 %{
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
-/* $FreeBSD$ */
=20
 #include "compile_et.h"
 #include "lex.h"
-#if 0
-RCSID("$Id: parse.y 15426 2005-06-16 19:21:42Z lha $");
-#endif
=20
 void yyerror (char *s);
 static long name2number(const char *str);
@@ -50,6 +46,9 @@
 #define alloca(x) malloc(x)
 #endif
=20
+#define YYMALLOC malloc
+#define YYFREE free
+
 %}
=20
 %union {
@@ -63,7 +62,7 @@
=20
 %%
=20
-file		: /* */=20
+file		: /* */
 		| header statements
 		;
=20
@@ -96,7 +95,7 @@
 		| statements statement
 		;
=20
-statement	: INDEX NUMBER=20
+statement	: INDEX NUMBER
 		{
 			number =3D $2;
 		}
@@ -118,7 +117,7 @@
 		| EC STRING ',' STRING
 		{
 		    struct error_code *ec =3D malloc(sizeof(*ec));
-		   =20
+
 		    if (ec =3D=3D NULL)
 			errx(1, "malloc");
=20
@@ -171,5 +170,5 @@
 void
 yyerror (char *s)
 {
-     error_message ("%s\n", s);
+     _lex_error_message ("%s\n", s);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/roken_rename.h
--- a/head/contrib/com_err/roken_rename.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/roken_rename.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,61 +1,61 @@
 /*
- * Copyright (c) 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: roken_rename.h 14930 2005-04-24 19:43:06Z lha $ */
+/* $Id$ */
=20
 #ifndef __roken_rename_h__
 #define __roken_rename_h__
=20
 #ifndef HAVE_SNPRINTF
-#define snprintf _com_err_snprintf
+#define rk_snprintf _com_err_snprintf
 #endif
 #ifndef HAVE_VSNPRINTF
-#define vsnprintf _com_err_vsnprintf
+#define rk_vsnprintf _com_err_vsnprintf
 #endif
 #ifndef HAVE_ASPRINTF
-#define asprintf _com_err_asprintf
+#define rk_asprintf _com_err_asprintf
 #endif
 #ifndef HAVE_ASNPRINTF
-#define asnprintf _com_err_asnprintf
+#define rk_asnprintf _com_err_asnprintf
 #endif
 #ifndef HAVE_VASPRINTF
-#define vasprintf _com_err_vasprintf
+#define rk_vasprintf _com_err_vasprintf
 #endif
 #ifndef HAVE_VASNPRINTF
-#define vasnprintf _com_err_vasnprintf
+#define rk_vasnprintf _com_err_vasnprintf
 #endif
 #ifndef HAVE_STRLCPY
-#define strlcpy _com_err_strlcpy
+#define rk_strlcpy _com_err_strlcpy
 #endif
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/com_err/version-script.map
--- a/head/contrib/com_err/version-script.map	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/com_err/version-script.map	Tue Apr 17 11:51:51 2012 +0300
@@ -3,6 +3,7 @@
 HEIMDAL_COM_ERR_1.0 {
 	global:
 		com_right;
+		com_right_r;
 		free_error_table;
 		initialize_error_table_r;
 		add_to_error_table;
@@ -13,6 +14,7 @@
 		init_error_table;
 		reset_com_err_hook;
 		set_com_err_hook;
+		_et_list;
 	local:
 		*;
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/gcc/ChangeLog.gcc43
--- a/head/contrib/gcc/ChangeLog.gcc43	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/gcc/ChangeLog.gcc43	Tue Apr 17 11:51:51 2012 +0300
@@ -169,3 +169,8 @@
 	* doc/extend.texi: Document SSSE3 built-in functions.
=20
 	* doc/invoke.texi: Document -mssse3/-mno-ssse3 switches.
+
+2006-10-21  Richard Guenther  <rguenther at suse.de>
+
+	* builtins.c (fold_builtin_classify): Fix typo.
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/gcc/builtins.c
--- a/head/contrib/gcc/builtins.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/gcc/builtins.c	Tue Apr 17 11:51:51 2012 +0300
@@ -8738,7 +8738,7 @@
     case BUILT_IN_FINITE:
       if (!HONOR_NANS (TYPE_MODE (TREE_TYPE (arg)))
 	  && !HONOR_INFINITIES (TYPE_MODE (TREE_TYPE (arg))))
-	return omit_one_operand (type, integer_zero_node, arg);
+	return omit_one_operand (type, integer_one_node, arg);
=20
       if (TREE_CODE (arg) =3D=3D REAL_CST)
 	{
diff -r 428842767fa6 -r f2935497fa04 head/contrib/gcc/config/mips/freebsd.h
--- a/head/contrib/gcc/config/mips/freebsd.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/gcc/config/mips/freebsd.h	Tue Apr 17 11:51:51 2012 +0300
@@ -19,7 +19,7 @@
 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
 Boston, MA 02110-1301, USA.  */
=20
-/* $FreeBSD$ */
+/* $FreeBSD: head/contrib/gcc/config/mips/freebsd.h 233397 2012-03-23 21:0=
7:10Z gonzo $ */
=20
 /* This defines which switch letters take arguments.  -G is a MIPS
    special.  */
@@ -351,4 +351,5 @@
 #endif
=20
 /************************[  Debugger stuff  ]*****************************=
****/
-
+#undef DBX_DEBUGGING_INFO
+#undef MIPS_DEBUGGING_INFO
diff -r 428842767fa6 -r f2935497fa04 head/contrib/libcxxrt/dynamic_cast.cc
--- a/head/contrib/libcxxrt/dynamic_cast.cc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/libcxxrt/dynamic_cast.cc	Tue Apr 17 11:51:51 2012 +0300
@@ -46,9 +46,65 @@
  */
 #define ADD_TO_PTR(x, off) (__typeof__(x))(((char*)x) + off)
=20
-bool __class_type_info::can_cast_to(const struct __class_type_info *other)=
 const
+bool std::type_info::__do_catch(std::type_info const *ex_type,
+                                void **exception_object,
+                                unsigned int outer) const
 {
-    return this =3D=3D other;
+	const type_info *type =3D this;
+
+	if (type =3D=3D ex_type)
+	{
+		return true;
+	}
+	if (const __class_type_info *cti =3D dynamic_cast<const __class_type_info=
 *>(type))
+	{
+		return ex_type->__do_upcast(cti, exception_object);
+	}
+	return false;
+}
+
+bool __pbase_type_info::__do_catch(std::type_info const *ex_type,
+                                   void **exception_object,
+                                   unsigned int outer) const
+{
+	if (ex_type =3D=3D this)
+	{
+		return true;
+	}
+	if (!ex_type->__is_pointer_p())
+	{
+		// Can't catch a non-pointer type in a pointer catch
+		return false;
+	}
+
+	if (!(outer & 1))
+	{
+		// If the low bit is cleared on this means that we've gone
+		// through a pointer that is not const qualified.
+		return false;
+	}
+	// Clear the low bit on outer if we're not const qualified.
+	if (!(__flags & __const_mask))
+	{
+		outer &=3D ~1;
+	}
+
+	const __pbase_type_info *ptr_type =3D
+	        static_cast<const __pbase_type_info*>(ex_type);
+
+	if (ptr_type->__flags & ~__flags)
+	{
+		// Handler pointer is less qualified
+		return false;
+	}
+
+	// Special case for void* handler. =20
+	if(*__pointee =3D=3D typeid(void))
+	{
+		return true;
+	}
+
+	return __pointee->__do_catch(ptr_type->__pointee, exception_object, outer=
);
 }
=20
 void *__class_type_info::cast_to(void *obj, const struct __class_type_info=
 *other) const
@@ -60,12 +116,6 @@
 	return 0;
 }
=20
-
-bool __si_class_type_info::can_cast_to(const struct __class_type_info *oth=
er) const
-{
-    return this =3D=3D other || __base_type->can_cast_to(other);
-}
-
 void *__si_class_type_info::cast_to(void *obj, const struct __class_type_i=
nfo *other) const
 {
 	if (this =3D=3D other)
@@ -74,31 +124,32 @@
 	}
 	return __base_type->cast_to(obj, other);
 }
-
-
-bool __vmi_class_type_info::can_cast_to(const struct __class_type_info *ot=
her) const
+bool __si_class_type_info::__do_upcast(const __class_type_info *target,
+                                     void **thrown_object) const
 {
-	if (this =3D=3D other)
+	if (this =3D=3D target)
 	{
 		return true;
 	}
-	for (unsigned int i=3D0 ; i<__base_count ; i++)
-	{
-		const __base_class_type_info *info =3D &__base_info[i];
-        if(info->isPublic() && info->__base_type->can_cast_to(other))
-        {
-            return true;
-        }
-	}
-	return false;
+	return __base_type->__do_upcast(target, thrown_object);
 }
=20
 void *__vmi_class_type_info::cast_to(void *obj, const struct __class_type_=
info *other) const
 {
-	if (this =3D=3D other)
+	if (__do_upcast(other, &obj))
 	{
 		return obj;
 	}
+	return 0;
+}
+
+bool __vmi_class_type_info::__do_upcast(const __class_type_info *target,
+		                      void **thrown_object) const
+{
+	if (this =3D=3D target)
+	{
+		return true;
+	}
 	for (unsigned int i=3D0 ; i<__base_count ; i++)
 	{
 		const __base_class_type_info *info =3D &__base_info[i];
@@ -111,6 +162,7 @@
 		// virtual table of the virtual base offset for the virtual base
 		// referenced (negative).'
=20
+		void *obj =3D *thrown_object;
 		if (info->isVirtual())
 		{
 			// Object's vtable
@@ -121,18 +173,17 @@
 		}
 		void *cast =3D ADD_TO_PTR(obj, offset);
=20
-		if (info->__base_type =3D=3D other)
+		if (info->__base_type =3D=3D target ||
+		    (info->__base_type->__do_upcast(target, &cast)))
 		{
-			return cast;
-		}
-		if ((cast =3D info->__base_type->cast_to(cast, other)))
-		{
-			return cast;
+			*thrown_object =3D cast;
+			return true;
 		}
 	}
 	return 0;
 }
=20
+
 /**
  * ABI function used to implement the dynamic_cast<> operator.  Some cases=
 of
  * this operator are implemented entirely in the compiler (e.g. to void*).
diff -r 428842767fa6 -r f2935497fa04 head/contrib/libcxxrt/exception.cc
--- a/head/contrib/libcxxrt/exception.cc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/libcxxrt/exception.cc	Tue Apr 17 11:51:51 2012 +0300
@@ -847,14 +847,11 @@
                                  const std::type_info *type,
                                  void *&adjustedPtr)
 {
-	// TODO: For compatibility with the GNU implementation, we should move th=
is
-	// out into a __do_catch() virtual function in std::type_info
 	void *exception_ptr =3D (void*)(ex+1);
-    const std::type_info *ex_type =3D ex->exceptionType;
+	const std::type_info *ex_type =3D ex->exceptionType;
=20
-	const __pointer_type_info *ptr_type =3D
-		dynamic_cast<const __pointer_type_info*>(ex_type);
-	if (0 !=3D ptr_type)
+	bool is_ptr =3D ex_type->__is_pointer_p();
+	if (is_ptr)
 	{
 		exception_ptr =3D *(void**)exception_ptr;
 	}
@@ -862,11 +859,6 @@
 	//
 	// Note: A 0 here is a catchall, not a cleanup, so we return true to
 	// indicate that we found a catch.
-	//
-	// TODO: Provide a class for matching against foreign exceptions.  This is
-	// already done in libobjc2, allowing C++ exceptions to be boxed as
-	// Objective-C objects.  We should do something similar, allowing foreign
-	// exceptions to be wrapped in a C++ exception and delivered.
 	if (0 =3D=3D type)
 	{
 		if (ex)
@@ -878,28 +870,6 @@
=20
 	if (0 =3D=3D ex) { return false; }
=20
-	const __pointer_type_info *target_ptr_type =3D
-		dynamic_cast<const __pointer_type_info*>(type);
-
-	if (0 !=3D ptr_type && 0 !=3D target_ptr_type)
-	{
-		if (ptr_type->__flags & ~target_ptr_type->__flags)
-		{
-			// Handler pointer is less qualified
-			return false;
-		}
-
-		// Special case for void* handler. =20
-		if(*target_ptr_type->__pointee =3D=3D typeid(void))
-		{
-			adjustedPtr =3D exception_ptr;
-			return true;
-		}
-
-		ex_type =3D ptr_type->__pointee;
-		type =3D target_ptr_type->__pointee;
-	}
-
 	// If the types are the same, no casting is needed.
 	if (*type =3D=3D *ex_type)
 	{
@@ -907,18 +877,13 @@
 		return true;
 	}
=20
-	const __class_type_info *cls_type =3D
-		dynamic_cast<const __class_type_info*>(ex_type);
-	const __class_type_info *target_cls_type =3D
-		dynamic_cast<const __class_type_info*>(type);
=20
-	if (0 !=3D cls_type &&
-		0 !=3D target_cls_type &&
-		cls_type->can_cast_to(target_cls_type))
+	if (type->__do_catch(ex_type, &exception_ptr, 1))
 	{
-		adjustedPtr =3D cls_type->cast_to(exception_ptr, target_cls_type);
+		adjustedPtr =3D exception_ptr;
 		return true;
 	}
+
 	return false;
 }
 /**
diff -r 428842767fa6 -r f2935497fa04 head/contrib/libcxxrt/typeinfo.h
--- a/head/contrib/libcxxrt/typeinfo.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/libcxxrt/typeinfo.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,86 @@
=20
 #include <stddef.h>
 #include "abi_namespace.h"
-#include "typeinfo"
+
+namespace ABI_NAMESPACE
+{
+	struct __class_type_info;
+}
+namespace std
+{
+	/**
+	  * Standard type info class.  The layout of this class is specified by t=
he
+	  * ABI.  The layout of the vtable is not, but is intended to be
+	  * compatible with the GNU ABI.
+	  *
+	  * Unlike the GNU version, the vtable layout is considered semi-private.
+	  */
+	class type_info
+	{
+		public:
+		/**
+		 * Virtual destructor.  This class must have one virtual function to
+		 * ensure that it has a vtable.
+		 */
+		virtual ~type_info();
+		bool operator=3D=3D(const type_info &) const;
+		bool operator!=3D(const type_info &) const;
+		bool before(const type_info &) const;
+		const char* name() const;
+		type_info();
+		private:
+		type_info(const type_info& rhs);
+		type_info& operator=3D (const type_info& rhs);
+		const char *__type_name;
+		/*
+		 * The following functions are in this order to match the
+		 * vtable layout of libsupc++.  This allows libcxxrt to be used
+		 * with libraries that depend on this.
+		 *
+		 * These functions are in the public headers for libstdc++, so
+		 * we have to assume that someone will probably call them and
+		 * expect them to work.  Their names must also match the names used in
+		 * libsupc++, so that code linking against this library can subclass
+		 * type_info and correctly fill in the values in the vtables.
+		 */
+		public:
+		/**
+		 * Catch function.  Allows external libraries to implement
+		 * their own basic types.  This is used, for example, in the
+		 * GNUstep Objective-C runtime to allow Objective-C types to be
+		 * caught in G++ catch blocks.
+		 *
+		 * The outer parameter indicates the number of outer pointers
+		 * in the high bits.  The low bit indicates whether the
+		 * pointers are const qualified.
+		 */
+		virtual bool __do_catch(const type_info *thrown_type,
+		                        void **thrown_object,
+		                        unsigned outer) const;
+		/**
+		 * Performs an upcast.  This is used in exception handling to
+		 * cast from subclasses to superclasses.  If the upcast is
+		 * possible, it returns true and adjusts the pointer.  If the
+		 * upcast is not possible, it returns false and does not adjust
+		 * the pointer.
+		 */
+		virtual bool __do_upcast(
+		                const ABI_NAMESPACE::__class_type_info *target,
+		                void **thrown_object) const
+		{
+			return false;
+		}
+		/**
+		 * Returns true if this is some pointer type, false otherwise.
+		 */
+		virtual bool __is_pointer_p() const { return false; }
+		/**
+		 * Returns true if this is some function type, false otherwise.
+		 */
+		virtual bool __is_function_p() const { return false; }
+	};
+}
+
=20
 namespace ABI_NAMESPACE
 {
@@ -50,6 +129,7 @@
 	struct __function_type_info : public std::type_info
 	{
 		virtual ~__function_type_info();
+		virtual bool __is_function_p() const { return true; }
 	};
 	/**
 	 * Type info for enums.
@@ -68,13 +148,12 @@
 		/**
 		 * Function implementing dynamic casts.
 		 */
-		virtual void *cast_to(void *obj,
-		                      const struct __class_type_info *other) const;
-		/**
-		 * Function returning whether a cast from this type to another type is
-		 * possible.
-		 */
-		virtual bool can_cast_to(const struct __class_type_info *other) const;
+		virtual void *cast_to(void *obj, const struct __class_type_info *other) =
const;
+		virtual bool __do_upcast(const __class_type_info *target,
+		                       void **thrown_object) const
+		{
+			return this =3D=3D target;
+		}
 	};
=20
 	/**
@@ -85,8 +164,10 @@
 	{
 		virtual ~__si_class_type_info();
 		const __class_type_info *__base_type;
+		virtual bool __do_upcast(
+		                const ABI_NAMESPACE::__class_type_info *target,
+		                void **thrown_object) const;
 		virtual void *cast_to(void *obj, const struct __class_type_info *other) =
const;
-        virtual bool can_cast_to(const struct __class_type_info *other) co=
nst;
 	};
=20
 	/**
@@ -166,8 +247,10 @@
 			/** The class is diamond shaped. */
 			__diamond_shaped_mask =3D 0x2
 		};
+		virtual bool __do_upcast(
+		                const ABI_NAMESPACE::__class_type_info *target,
+		                void **thrown_object) const;
 		virtual void *cast_to(void *obj, const struct __class_type_info *other) =
const;
-        virtual bool can_cast_to(const struct __class_type_info *other) co=
nst;
 	};
=20
 	/**
@@ -201,6 +284,10 @@
 			/** Pointer is a pointer to a member of an incomplete class. */
 			__incomplete_class_mask =3D 0x10
 		};
+		virtual bool __is_pointer_p() const { return true; }
+		virtual bool __do_catch(const type_info *thrown_type,
+		                        void **thrown_object,
+		                        unsigned outer) const;
 	};
=20
 	/**
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/LICENSE.TXT
--- a/head/contrib/llvm/LICENSE.TXT	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/LICENSE.TXT	Tue Apr 17 11:51:51 2012 +0300
@@ -4,7 +4,7 @@
 University of Illinois/NCSA
 Open Source License
=20
-Copyright (c) 2003-2011 University of Illinois at Urbana-Champaign.
+Copyright (c) 2003-2012 University of Illinois at Urbana-Champaign.
 All rights reserved.
=20
 Developed by:
@@ -67,3 +67,4 @@
 CellSPU backend     llvm/lib/Target/CellSPU/README.txt
 Google Test         llvm/utils/unittest/googletest
 OpenBSD regex       llvm/lib/Support/{reg*, COPYRIGHT.regex}
+pyyaml tests        llvm/test/YAMLParser/{*.data, LICENSE.TXT}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Analy=
sis.h
--- a/head/contrib/llvm/include/llvm-c/Analysis.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/include/llvm-c/Analysis.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -25,6 +25,12 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCAnalysis Analysis
+ * @ingroup LLVMC
+ *
+ * @{
+ */
=20
 typedef enum {
   LLVMAbortProcessAction, /* verifier will print to stderr and abort() */
@@ -48,6 +54,10 @@
 void LLVMViewFunctionCFG(LLVMValueRef Fn);
 void LLVMViewFunctionCFGOnly(LLVMValueRef Fn);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/BitRe=
ader.h
--- a/head/contrib/llvm/include/llvm-c/BitReader.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm-c/BitReader.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -25,6 +25,12 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCBitReader Bit Reader
+ * @ingroup LLVMC
+ *
+ * @{
+ */
=20
 /* Builds a module from the bitcode in the specified memory buffer, return=
ing a
    reference to the module via the OutModule parameter. Returns 0 on succe=
ss.
@@ -59,6 +65,10 @@
                                       LLVMModuleProviderRef *OutMP,
                                       char **OutMessage);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/BitWr=
iter.h
--- a/head/contrib/llvm/include/llvm-c/BitWriter.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm-c/BitWriter.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -25,6 +25,12 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCBitWriter Bit Writer
+ * @ingroup LLVMC
+ *
+ * @{
+ */
=20
 /*=3D=3D=3D-- Operations on modules --------------------------------------=
-------=3D=3D=3D*/
=20
@@ -39,6 +45,10 @@
     descriptor. Returns 0 on success. Closes the Handle. */=20
 int LLVMWriteBitcodeToFileHandle(LLVMModuleRef M, int Handle);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Core.h
--- a/head/contrib/llvm/include/llvm-c/Core.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/Core.h	Tue Apr 17 11:51:51 2012 +0300
@@ -10,24 +10,6 @@
 |* This header declares the C interface to libLLVMCore.a, which implements=
    *|
 |* the LLVM intermediate representation.                                  =
    *|
 |*                                                                        =
    *|
-|* LLVM uses a polymorphic type hierarchy which C cannot represent, theref=
ore *|
-|* parameters must be passed as base types. Despite the declared types, mo=
st  *|
-|* of the functions provided operate only on branches of the type hierarch=
y.  *|
-|* The declared parameter names are descriptive and specify which type is =
    *|
-|* required. Additionally, each type hierarchy is documented along with th=
e   *|
-|* functions that operate upon it. For more detail, refer to LLVM's C++ co=
de. *|
-|* If in doubt, refer to Core.cpp, which performs paramter downcasts in th=
e   *|
-|* form unwrap<RequiredType>(Param).                                      =
    *|
-|*                                                                        =
    *|
-|* Many exotic languages can interoperate with C code but have a harder ti=
me  *|
-|* with C++ due to name mangling. So in addition to C, this interface enab=
les *|
-|* tools written in such languages.                                       =
    *|
-|*                                                                        =
    *|
-|* When included into a C++ source file, also declares 'wrap' and 'unwrap'=
    *|
-|* helpers to perform opaque reference<-->pointer conversions. These helpe=
rs  *|
-|* are shorter and more tightly typed than writing the casts by hand when =
    *|
-|* authoring bindings. In assert builds, they will do runtime type checkin=
g.  *|
-|*                                                                        =
    *|
 \*=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D*/
=20
 #ifndef LLVM_C_CORE_H
@@ -46,50 +28,121 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMC LLVM-C: C interface to LLVM
+ *
+ * This module exposes parts of the LLVM library as a C API.
+ *
+ * @{
+ */
+
+/**
+ * @defgroup LLVMCTransforms Transforms
+ */
+
+/**
+ * @defgroup LLVMCCore Core
+ *
+ * This modules provide an interface to libLLVMCore, which implements
+ * the LLVM intermediate representation as well as other related types
+ * and utilities.
+ *
+ * LLVM uses a polymorphic type hierarchy which C cannot represent, theref=
ore
+ * parameters must be passed as base types. Despite the declared types, mo=
st
+ * of the functions provided operate only on branches of the type hierarch=
y.
+ * The declared parameter names are descriptive and specify which type is
+ * required. Additionally, each type hierarchy is documented along with the
+ * functions that operate upon it. For more detail, refer to LLVM's C++ co=
de.
+ * If in doubt, refer to Core.cpp, which performs paramter downcasts in the
+ * form unwrap<RequiredType>(Param).
+ *
+ * Many exotic languages can interoperate with C code but have a harder ti=
me
+ * with C++ due to name mangling. So in addition to C, this interface enab=
les
+ * tools written in such languages.
+ *
+ * When included into a C++ source file, also declares 'wrap' and 'unwrap'
+ * helpers to perform opaque reference<-->pointer conversions. These helpe=
rs
+ * are shorter and more tightly typed than writing the casts by hand when
+ * authoring bindings. In assert builds, they will do runtime type checkin=
g.
+ *
+ * @{
+ */
+
+/**
+ * @defgroup LLVMCCoreTypes Types and Enumerations
+ *
+ * @{
+ */
=20
 typedef int LLVMBool;
=20
 /* Opaque types. */
=20
 /**
- * The top-level container for all LLVM global data.  See the LLVMContext =
class.
+ * The top-level container for all LLVM global data. See the LLVMContext c=
lass.
  */
 typedef struct LLVMOpaqueContext *LLVMContextRef;
=20
 /**
  * The top-level container for all other LLVM Intermediate Representation =
(IR)
- * objects. See the llvm::Module class.
+ * objects.
+ *
+ * @see llvm::Module
  */
 typedef struct LLVMOpaqueModule *LLVMModuleRef;
=20
 /**
- * Each value in the LLVM IR has a type, an LLVMTypeRef. See the llvm::Type
- * class.
+ * Each value in the LLVM IR has a type, an LLVMTypeRef.
+ *
+ * @see llvm::Type
  */
 typedef struct LLVMOpaqueType *LLVMTypeRef;
=20
+/**
+ * Represents an individual value in LLVM IR.
+ *
+ * This models llvm::Value.
+ */
 typedef struct LLVMOpaqueValue *LLVMValueRef;
+
+/**
+ * Represents a basic block of instruction in LLVM IR.
+ *
+ * This models llvm::BasicBlock.
+ */
 typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef;
+
+/**
+ * Represents an LLVM basic block builder.
+ *
+ * This models llvm::IRBuilder.
+ */
 typedef struct LLVMOpaqueBuilder *LLVMBuilderRef;
=20
-/* Interface used to provide a module to JIT or interpreter.  This is now =
just a
- * synonym for llvm::Module, but we have to keep using the different type =
to
- * keep binary compatibility.
+/**
+ * Interface used to provide a module to JIT or interpreter.
+ * This is now just a synonym for llvm::Module, but we have to keep using =
the
+ * different type to keep binary compatibility.
  */
 typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef;
=20
-/* Used to provide a module to JIT or interpreter.
- * See the llvm::MemoryBuffer class.
+/**
+ * Used to provide a module to JIT or interpreter.
+ *
+ * @see llvm::MemoryBuffer
  */
 typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef;
=20
-/** See the llvm::PassManagerBase class. */
+/** @see llvm::PassManagerBase */
 typedef struct LLVMOpaquePassManager *LLVMPassManagerRef;
=20
-/** See the llvm::PassRegistry class. */
+/** @see llvm::PassRegistry */
 typedef struct LLVMOpaquePassRegistry *LLVMPassRegistryRef;
=20
-/** Used to get the users and usees of a Value. See the llvm::Use class. */
+/**
+ * Used to get the users and usees of a Value.
+ *
+ * @see llvm::Use */
 typedef struct LLVMOpaqueUse *LLVMUseRef;
=20
 typedef enum {
@@ -119,6 +172,11 @@
     LLVMReturnsTwice =3D 1 << 29,
     LLVMUWTable =3D 1 << 30,
     LLVMNonLazyBind =3D 1 << 31
+
+    // FIXME: This attribute is currently not included in the C API as
+    // a temporary measure until the API/ABI impact to the C API is unders=
tood
+    // and the path forward agreed upon.
+    //LLVMAddressSafety =3D 1ULL << 32
 } LLVMAttribute;
=20
 typedef enum {
@@ -195,14 +253,13 @@
=20
   /* Exception Handling Operators */
   LLVMResume         =3D 58,
-  LLVMLandingPad     =3D 59,
-  LLVMUnwind         =3D 60
-
+  LLVMLandingPad     =3D 59
=20
 } LLVMOpcode;
=20
 typedef enum {
   LLVMVoidTypeKind,        /**< type with no size */
+  LLVMHalfTypeKind,        /**< 16 bit floating point type */
   LLVMFloatTypeKind,       /**< 32 bit floating point type */
   LLVMDoubleTypeKind,      /**< 64 bit floating point type */
   LLVMX86_FP80TypeKind,    /**< 80 bit floating point type (X87) */
@@ -294,6 +351,10 @@
   LLVMLandingPadFilter    /**< A filter clause  */
 } LLVMLandingPadClauseTy;
=20
+/**
+ * @}
+ */
+
 void LLVMInitializeCore(LLVMPassRegistryRef R);
=20
=20
@@ -302,49 +363,233 @@
 void LLVMDisposeMessage(char *Message);
=20
=20
-/*=3D=3D=3D-- Contexts ---------------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @defgroup LLVMCCoreContext Contexts
+ *
+ * Contexts are execution states for the core LLVM IR system.
+ *
+ * Most types are tied to a context instance. Multiple contexts can
+ * exist simultaneously. A single context is not thread safe. However,
+ * different contexts can execute on different threads simultaneously.
+ *
+ * @{
+ */
=20
-/* Create and destroy contexts. */
+/**
+ * Create a new context.
+ *
+ * Every call to this function should be paired with a call to
+ * LLVMContextDispose() or the context will leak memory.
+ */
 LLVMContextRef LLVMContextCreate(void);
+
+/**
+ * Obtain the global context instance.
+ */
 LLVMContextRef LLVMGetGlobalContext(void);
+
+/**
+ * Destroy a context instance.
+ *
+ * This should be called for every call to LLVMContextCreate() or memory
+ * will be leaked.
+ */
 void LLVMContextDispose(LLVMContextRef C);
=20
 unsigned LLVMGetMDKindIDInContext(LLVMContextRef C, const char* Name,
                                   unsigned SLen);
 unsigned LLVMGetMDKindID(const char* Name, unsigned SLen);
=20
-/*=3D=3D=3D-- Modules ----------------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @}
+ */
=20
-/* Create and destroy modules. */=20
-/** See llvm::Module::Module. */
+/**
+ * @defgroup LLVMCCoreModule Modules
+ *
+ * Modules represent the top-level structure in a LLVM program. An LLVM
+ * module is effectively a translation unit or a collection of
+ * translation units merged together.
+ *
+ * @{
+ */
+
+/**
+ * Create a new, empty module in the global context.
+ *
+ * This is equivalent to calling LLVMModuleCreateWithNameInContext with
+ * LLVMGetGlobalContext() as the context parameter.
+ *
+ * Every invocation should be paired with LLVMDisposeModule() or memory
+ * will be leaked.
+ */
 LLVMModuleRef LLVMModuleCreateWithName(const char *ModuleID);
+
+/**
+ * Create a new, empty module in a specific context.
+ *
+ * Every invocation should be paired with LLVMDisposeModule() or memory
+ * will be leaked.
+ */
 LLVMModuleRef LLVMModuleCreateWithNameInContext(const char *ModuleID,
                                                 LLVMContextRef C);
=20
-/** See llvm::Module::~Module. */
+/**
+ * Destroy a module instance.
+ *
+ * This must be called for every created module or memory will be
+ * leaked.
+ */
 void LLVMDisposeModule(LLVMModuleRef M);
=20
-/** Data layout. See Module::getDataLayout. */
+/**
+ * Obtain the data layout for a module.
+ *
+ * @see Module::getDataLayout()
+ */
 const char *LLVMGetDataLayout(LLVMModuleRef M);
+
+/**
+ * Set the data layout for a module.
+ *
+ * @see Module::setDataLayout()
+ */
 void LLVMSetDataLayout(LLVMModuleRef M, const char *Triple);
=20
-/** Target triple. See Module::getTargetTriple. */
+/**
+ * Obtain the target triple for a module.
+ *
+ * @see Module::getTargetTriple()
+ */
 const char *LLVMGetTarget(LLVMModuleRef M);
+
+/**
+ * Set the target triple for a module.
+ *
+ * @see Module::setTargetTriple()
+ */
 void LLVMSetTarget(LLVMModuleRef M, const char *Triple);
=20
-/** See Module::dump. */
+/**
+ * Dump a representation of a module to stderr.
+ *
+ * @see Module::dump()
+ */
 void LLVMDumpModule(LLVMModuleRef M);
=20
-/** See Module::setModuleInlineAsm. */
+/**
+ * Set inline assembly for a module.
+ *
+ * @see Module::setModuleInlineAsm()
+ */
 void LLVMSetModuleInlineAsm(LLVMModuleRef M, const char *Asm);
=20
-/** See Module::getContext. */
+/**
+ * Obtain the context to which this module is associated.
+ *
+ * @see Module::getContext()
+ */
 LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M);
=20
-/*=3D=3D=3D-- Types ------------------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * Obtain a Type from a module by its registered name.
+ */
+LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name);
=20
-/* LLVM types conform to the following hierarchy:
- *=20
+/**
+ * Obtain the number of operands for named metadata in a module.
+ *
+ * @see llvm::Module::getNamedMetadata()
+ */
+unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char* name=
);
+
+/**
+ * Obtain the named metadata operands for a module.
+ *
+ * The passed LLVMValueRef pointer should refer to an array of
+ * LLVMValueRef at least LLVMGetNamedMetadataNumOperands long. This
+ * array will be populated with the LLVMValueRef instances. Each
+ * instance corresponds to a llvm::MDNode.
+ *
+ * @see llvm::Module::getNamedMetadata()
+ * @see llvm::MDNode::getOperand()
+ */
+void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char* name, LLVMV=
alueRef *Dest);
+
+/**
+ * Add an operand to named metadata.
+ *
+ * @see llvm::Module::getNamedMetadata()
+ * @see llvm::MDNode::addOperand()
+ */
+void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char* name,
+                                 LLVMValueRef Val);
+
+/**
+ * Add a function to a module under a specified name.
+ *
+ * @see llvm::Function::Create()
+ */
+LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,
+                             LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain a Function value from a Module by its name.
+ *
+ * The returned value corresponds to a llvm::Function value.
+ *
+ * @see llvm::Module::getFunction()
+ */
+LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name);
+
+/**
+ * Obtain an iterator to the first Function in a Module.
+ *
+ * @see llvm::Module::begin()
+ */
+LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M);
+
+/**
+ * Obtain an iterator to the last Function in a Module.
+ *
+ * @see llvm::Module::end()
+ */
+LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M);
+
+/**
+ * Advance a Function iterator to the next Function.
+ *
+ * Returns NULL if the iterator was already at the end and there are no mo=
re
+ * functions.
+ */
+LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn);
+
+/**
+ * Decrement a Function iterator to the previous Function.
+ *
+ * Returns NULL if the iterator was already at the beginning and there are
+ * no previous functions.
+ */
+LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreType Types
+ *
+ * Types represent the type of a value.
+ *
+ * Types are associated with a context instance. The context internally
+ * deduplicates types so there is only 1 instance of a specific type
+ * alive at a time. In other words, a unique type is shared among all
+ * consumers within a context.
+ *
+ * A Type in the C API corresponds to llvm::Type.
+ *
+ * Types have the following hierarchy:
+ *
  *   types:
  *     integer type
  *     real type
@@ -356,16 +601,44 @@
  *     void type
  *     label type
  *     opaque type
+ *
+ * @{
  */
=20
-/** See llvm::LLVMTypeKind::getTypeID. */
+/**
+ * Obtain the enumerated type of a Type instance.
+ *
+ * @see llvm::Type:getTypeID()
+ */
 LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty);
+
+/**
+ * Whether the type has a known size.
+ *
+ * Things that don't have a size are abstract types, labels, and void.a
+ *
+ * @see llvm::Type::isSized()
+ */
 LLVMBool LLVMTypeIsSized(LLVMTypeRef Ty);
=20
-/** See llvm::LLVMType::getContext. */
+/**
+ * Obtain the context to which this type instance is associated.
+ *
+ * @see llvm::Type::getContext()
+ */
 LLVMContextRef LLVMGetTypeContext(LLVMTypeRef Ty);
=20
-/* Operations on integer types */
+/**
+ * @defgroup LLVMCCoreTypeInt Integer Types
+ *
+ * Functions in this section operate on integer types.
+ *
+ * @{
+ */
+
+/**
+ * Obtain an integer type from a context with specified bit width.
+ */
 LLVMTypeRef LLVMInt1TypeInContext(LLVMContextRef C);
 LLVMTypeRef LLVMInt8TypeInContext(LLVMContextRef C);
 LLVMTypeRef LLVMInt16TypeInContext(LLVMContextRef C);
@@ -373,6 +646,10 @@
 LLVMTypeRef LLVMInt64TypeInContext(LLVMContextRef C);
 LLVMTypeRef LLVMIntTypeInContext(LLVMContextRef C, unsigned NumBits);
=20
+/**
+ * Obtain an integer type from the global context with a specified bit
+ * width.
+ */
 LLVMTypeRef LLVMInt1Type(void);
 LLVMTypeRef LLVMInt8Type(void);
 LLVMTypeRef LLVMInt16Type(void);
@@ -381,68 +658,336 @@
 LLVMTypeRef LLVMIntType(unsigned NumBits);
 unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy);
=20
-/* Operations on real types */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeFloat Floating Point Types
+ *
+ * @{
+ */
+
+/**
+ * Obtain a 16-bit floating point type from a context.
+ */
+LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 32-bit floating point type from a context.
+ */
 LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 64-bit floating point type from a context.
+ */
 LLVMTypeRef LLVMDoubleTypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 80-bit floating point type (X87) from a context.
+ */
 LLVMTypeRef LLVMX86FP80TypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 128-bit floating point type (112-bit mantissa) from a
+ * context.
+ */
 LLVMTypeRef LLVMFP128TypeInContext(LLVMContextRef C);
+
+/**
+ * Obtain a 128-bit floating point type (two 64-bits) from a context.
+ */
 LLVMTypeRef LLVMPPCFP128TypeInContext(LLVMContextRef C);
=20
+/**
+ * Obtain a floating point type from the global context.
+ *
+ * These map to the functions in this group of the same name.
+ */
+LLVMTypeRef LLVMHalfType(void);
 LLVMTypeRef LLVMFloatType(void);
 LLVMTypeRef LLVMDoubleType(void);
 LLVMTypeRef LLVMX86FP80Type(void);
 LLVMTypeRef LLVMFP128Type(void);
 LLVMTypeRef LLVMPPCFP128Type(void);
=20
-/* Operations on function types */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeFunction Function Types
+ *
+ * @{
+ */
+
+/**
+ * Obtain a function type consisting of a specified signature.
+ *
+ * The function is defined as a tuple of a return Type, a list of
+ * parameter types, and whether the function is variadic.
+ */
 LLVMTypeRef LLVMFunctionType(LLVMTypeRef ReturnType,
                              LLVMTypeRef *ParamTypes, unsigned ParamCount,
                              LLVMBool IsVarArg);
+
+/**
+ * Returns whether a function type is variadic.
+ */
 LLVMBool LLVMIsFunctionVarArg(LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain the Type this function Type returns.
+ */
 LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain the number of parameters this function accepts.
+ */
 unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy);
+
+/**
+ * Obtain the types of a function's parameters.
+ *
+ * The Dest parameter should point to a pre-allocated array of
+ * LLVMTypeRef at least LLVMCountParamTypes() large. On return, the
+ * first LLVMCountParamTypes() entries in the array will be populated
+ * with LLVMTypeRef instances.
+ *
+ * @param FunctionTy The function type to operate on.
+ * @param Dest Memory address of an array to be filled with result.
+ */
 void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest);
=20
-/* Operations on struct types */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeStruct Structure Types
+ *
+ * These functions relate to LLVMTypeRef instances.
+ *
+ * @see llvm::StructType
+ *
+ * @{
+ */
+
+/**
+ * Create a new structure type in a context.
+ *
+ * A structure is specified by a list of inner elements/types and
+ * whether these can be packed together.
+ *
+ * @see llvm::StructType::create()
+ */
 LLVMTypeRef LLVMStructTypeInContext(LLVMContextRef C, LLVMTypeRef *Element=
Types,
                                     unsigned ElementCount, LLVMBool Packed=
);
+
+/**
+ * Create a new structure type in the global context.
+ *
+ * @see llvm::StructType::create()
+ */
 LLVMTypeRef LLVMStructType(LLVMTypeRef *ElementTypes, unsigned ElementCoun=
t,
                            LLVMBool Packed);
+
+/**
+ * Create an empty structure in a context having a specified name.
+ *
+ * @see llvm::StructType::create()
+ */
 LLVMTypeRef LLVMStructCreateNamed(LLVMContextRef C, const char *Name);
+
+/**
+ * Obtain the name of a structure.
+ *
+ * @see llvm::StructType::getName()
+ */
 const char *LLVMGetStructName(LLVMTypeRef Ty);
+
+/**
+ * Set the contents of a structure type.
+ *
+ * @see llvm::StructType::setBody()
+ */
 void LLVMStructSetBody(LLVMTypeRef StructTy, LLVMTypeRef *ElementTypes,
                        unsigned ElementCount, LLVMBool Packed);
=20
+/**
+ * Get the number of elements defined inside the structure.
+ *
+ * @see llvm::StructType::getNumElements()
+ */
 unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy);
+
+/**
+ * Get the elements within a structure.
+ *
+ * The function is passed the address of a pre-allocated array of
+ * LLVMTypeRef at least LLVMCountStructElementTypes() long. After
+ * invocation, this array will be populated with the structure's
+ * elements. The objects in the destination array will have a lifetime
+ * of the structure type itself, which is the lifetime of the context it
+ * is contained in.
+ */
 void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest);
+
+/**
+ * Determine whether a structure is packed.
+ *
+ * @see llvm::StructType::isPacked()
+ */
 LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy);
+
+/**
+ * Determine whether a structure is opaque.
+ *
+ * @see llvm::StructType::isOpaque()
+ */
 LLVMBool LLVMIsOpaqueStruct(LLVMTypeRef StructTy);
=20
-LLVMTypeRef LLVMGetTypeByName(LLVMModuleRef M, const char *Name);
+/**
+ * @}
+ */
=20
-/* Operations on array, pointer, and vector types (sequence types) */
+
+/**
+ * @defgroup LLVMCCoreTypeSequential Sequential Types
+ *
+ * Sequential types represents "arrays" of types. This is a super class
+ * for array, vector, and pointer types.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the type of elements within a sequential type.
+ *
+ * This works on array, vector, and pointer types.
+ *
+ * @see llvm::SequentialType::getElementType()
+ */
+LLVMTypeRef LLVMGetElementType(LLVMTypeRef Ty);
+
+/**
+ * Create a fixed size array type that refers to a specific type.
+ *
+ * The created type will exist in the context that its element type
+ * exists in.
+ *
+ * @see llvm::ArrayType::get()
+ */
 LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount);
+
+/**
+ * Obtain the length of an array type.
+ *
+ * This only works on types that represent arrays.
+ *
+ * @see llvm::ArrayType::getNumElements()
+ */
+unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy);
+
+/**
+ * Create a pointer type that points to a defined type.
+ *
+ * The created type will exist in the context that its pointee type
+ * exists in.
+ *
+ * @see llvm::PointerType::get()
+ */
 LLVMTypeRef LLVMPointerType(LLVMTypeRef ElementType, unsigned AddressSpace=
);
+
+/**
+ * Obtain the address space of a pointer type.
+ *
+ * This only works on types that represent pointers.
+ *
+ * @see llvm::PointerType::getAddressSpace()
+ */
+unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy);
+
+/**
+ * Create a vector type that contains a defined type and has a specific
+ * number of elements.
+ *
+ * The created type will exist in the context thats its element type
+ * exists in.
+ *
+ * @see llvm::VectorType::get()
+ */
 LLVMTypeRef LLVMVectorType(LLVMTypeRef ElementType, unsigned ElementCount);
=20
-LLVMTypeRef LLVMGetElementType(LLVMTypeRef Ty);
-unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy);
-unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy);
+/**
+ * Obtain the number of elements in a vector type.
+ *
+ * This only works on types that represent vectors.
+ *
+ * @see llvm::VectorType::getNumElements()
+ */
 unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy);
=20
-/* Operations on other types */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreTypeOther Other Types
+ *
+ * @{
+ */
+
+/**
+ * Create a void type in a context.
+ */
 LLVMTypeRef LLVMVoidTypeInContext(LLVMContextRef C);
+
+/**
+ * Create a label type in a context.
+ */
 LLVMTypeRef LLVMLabelTypeInContext(LLVMContextRef C);
+
+/**
+ * Create a X86 MMX type in a context.
+ */
 LLVMTypeRef LLVMX86MMXTypeInContext(LLVMContextRef C);
=20
+/**
+ * These are similar to the above functions except they operate on the
+ * global context.
+ */
 LLVMTypeRef LLVMVoidType(void);
 LLVMTypeRef LLVMLabelType(void);
 LLVMTypeRef LLVMX86MMXType(void);
=20
-/*=3D=3D=3D-- Values -----------------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @}
+ */
=20
-/* The bulk of LLVM's object model consists of values, which comprise a ve=
ry
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValues Values
+ *
+ * The bulk of LLVM's object model consists of values, which comprise a ve=
ry
  * rich type hierarchy.
+ *
+ * LLVMValueRef essentially represents llvm::Value. There is a rich
+ * hierarchy of classes within this type. Depending on the instance
+ * obtain, not all APIs are available.
+ *
+ * Callers can determine the type of a LLVMValueRef by calling the
+ * LLVMIsA* family of functions (e.g. LLVMIsAArgument()). These
+ * functions are defined by a macro, so it isn't obvious which are
+ * available by looking at the Doxygen source code. Instead, look at the
+ * source definition of LLVM_FOR_EACH_VALUE_SUBCLASS and note the list
+ * of value names given. These value names also correspond to classes in
+ * the llvm::Value hierarchy.
+ *
+ * @{
  */
=20
 #define LLVM_FOR_EACH_VALUE_SUBCLASS(macro) \
@@ -473,8 +1018,6 @@
         macro(IntrinsicInst)                \
           macro(DbgInfoIntrinsic)           \
             macro(DbgDeclareInst)           \
-          macro(EHExceptionInst)            \
-          macro(EHSelectorInst)             \
           macro(MemIntrinsic)               \
             macro(MemCpyInst)               \
             macro(MemMoveInst)              \
@@ -518,92 +1061,399 @@
       macro(LoadInst)                       \
       macro(VAArgInst)
=20
-/* Operations on all values */
+/**
+ * @defgroup LLVMCCoreValueGeneral General APIs
+ *
+ * Functions in this section work on all LLVMValueRef instances,
+ * regardless of their sub-type. They correspond to functions available
+ * on llvm::Value.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the type of a value.
+ *
+ * @see llvm::Value::getType()
+ */
 LLVMTypeRef LLVMTypeOf(LLVMValueRef Val);
+
+/**
+ * Obtain the string name of a value.
+ *
+ * @see llvm::Value::getName()
+ */
 const char *LLVMGetValueName(LLVMValueRef Val);
+
+/**
+ * Set the string name of a value.
+ *
+ * @see llvm::Value::setName()
+ */
 void LLVMSetValueName(LLVMValueRef Val, const char *Name);
+
+/**
+ * Dump a representation of a value to stderr.
+ *
+ * @see llvm::Value::dump()
+ */
 void LLVMDumpValue(LLVMValueRef Val);
+
+/**
+ * Replace all uses of a value with another one.
+ *
+ * @see llvm::Value::replaceAllUsesWith()
+ */
 void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal);
-int LLVMHasMetadata(LLVMValueRef Val);
-LLVMValueRef LLVMGetMetadata(LLVMValueRef Val, unsigned KindID);
-void LLVMSetMetadata(LLVMValueRef Val, unsigned KindID, LLVMValueRef Node);
=20
-/* Conversion functions. Return the input value if it is an instance of the
-   specified class, otherwise NULL. See llvm::dyn_cast_or_null<>. */
+/**
+ * Determine whether the specified constant instance is constant.
+ */
+LLVMBool LLVMIsConstant(LLVMValueRef Val);
+
+/**
+ * Determine whether a value instance is undefined.
+ */
+LLVMBool LLVMIsUndef(LLVMValueRef Val);
+
+/**
+ * Convert value instances between types.
+ *
+ * Internally, a LLVMValueRef is "pinned" to a specific type. This
+ * series of functions allows you to cast an instance to a specific
+ * type.
+ *
+ * If the cast is not valid for the specified type, NULL is returned.
+ *
+ * @see llvm::dyn_cast_or_null<>
+ */
 #define LLVM_DECLARE_VALUE_CAST(name) \
   LLVMValueRef LLVMIsA##name(LLVMValueRef Val);
 LLVM_FOR_EACH_VALUE_SUBCLASS(LLVM_DECLARE_VALUE_CAST)
=20
-/* Operations on Uses */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueUses Usage
+ *
+ * This module defines functions that allow you to inspect the uses of a
+ * LLVMValueRef.
+ *
+ * It is possible to obtain a LLVMUseRef for any LLVMValueRef instance.
+ * Each LLVMUseRef (which corresponds to a llvm::Use instance) holds a
+ * llvm::User and llvm::Value.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the first use of a value.
+ *
+ * Uses are obtained in an iterator fashion. First, call this function
+ * to obtain a reference to the first use. Then, call LLVMGetNextUse()
+ * on that instance and all subsequently obtained instances untl
+ * LLVMGetNextUse() returns NULL.
+ *
+ * @see llvm::Value::use_begin()
+ */
 LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val);
+
+/**
+ * Obtain the next use of a value.
+ *
+ * This effectively advances the iterator. It returns NULL if you are on
+ * the final use and no more are available.
+ */
 LLVMUseRef LLVMGetNextUse(LLVMUseRef U);
+
+/**
+ * Obtain the user value for a user.
+ *
+ * The returned value corresponds to a llvm::User type.
+ *
+ * @see llvm::Use::getUser()
+ */
 LLVMValueRef LLVMGetUser(LLVMUseRef U);
+
+/**
+ * Obtain the value this use corresponds to.
+ *
+ * @see llvm::Use::get().
+ */
 LLVMValueRef LLVMGetUsedValue(LLVMUseRef U);
=20
-/* Operations on Users */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueUser User value
+ *
+ * Function in this group pertain to LLVMValueRef instances that descent
+ * from llvm::User. This includes constants, instructions, and
+ * operators.
+ *
+ * @{
+ */
+
+/**
+ * Obtain an operand at a specific index in a llvm::User value.
+ *
+ * @see llvm::User::getOperand()
+ */
 LLVMValueRef LLVMGetOperand(LLVMValueRef Val, unsigned Index);
+
+/**
+ * Set an operand at a specific index in a llvm::User value.
+ *
+ * @see llvm::User::setOperand()
+ */
 void LLVMSetOperand(LLVMValueRef User, unsigned Index, LLVMValueRef Val);
+
+/**
+ * Obtain the number of operands in a llvm::User value.
+ *
+ * @see llvm::User::getNumOperands()
+ */
 int LLVMGetNumOperands(LLVMValueRef Val);
=20
-/* Operations on constants of any type */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueConstant Constants
+ *
+ * This section contains APIs for interacting with LLVMValueRef that
+ * correspond to llvm::Constant instances.
+ *
+ * These functions will work for any LLVMValueRef in the llvm::Constant
+ * class hierarchy.
+ *
+ * @{
+ */
+
+/**
+ * Obtain a constant value referring to the null instance of a type.
+ *
+ * @see llvm::Constant::getNullValue()
+ */
 LLVMValueRef LLVMConstNull(LLVMTypeRef Ty); /* all zeroes */
-LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty); /* only for int/vector */
+
+/**
+ * Obtain a constant value referring to the instance of a type
+ * consisting of all ones.
+ *
+ * This is only valid for integer types.
+ *
+ * @see llvm::Constant::getAllOnesValue()
+ */
+LLVMValueRef LLVMConstAllOnes(LLVMTypeRef Ty);
+
+/**
+ * Obtain a constant value referring to an undefined value of a type.
+ *
+ * @see llvm::UndefValue::get()
+ */
 LLVMValueRef LLVMGetUndef(LLVMTypeRef Ty);
-LLVMBool LLVMIsConstant(LLVMValueRef Val);
+
+/**
+ * Determine whether a value instance is null.
+ *
+ * @see llvm::Constant::isNullValue()
+ */
 LLVMBool LLVMIsNull(LLVMValueRef Val);
-LLVMBool LLVMIsUndef(LLVMValueRef Val);
+
+/**
+ * Obtain a constant that is a constant pointer pointing to NULL for a
+ * specified type.
+ */
 LLVMValueRef LLVMConstPointerNull(LLVMTypeRef Ty);
=20
-/* Operations on metadata */
-LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
-                                   unsigned SLen);
-LLVMValueRef LLVMMDString(const char *Str, unsigned SLen);
-LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals,
-                                 unsigned Count);
-LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count);
-const char  *LLVMGetMDString(LLVMValueRef V, unsigned* Len);
-int LLVMGetMDNodeNumOperands(LLVMValueRef V);
-LLVMValueRef *LLVMGetMDNodeOperand(LLVMValueRef V, unsigned i);
-unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char* name=
);
-void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char* name, LLVMV=
alueRef *Dest);
+/**
+ * @defgroup LLVMCCoreValueConstantScalar Scalar constants
+ *
+ * Functions in this group model LLVMValueRef instances that correspond
+ * to constants referring to scalar types.
+ *
+ * For integer types, the LLVMTypeRef parameter should correspond to a
+ * llvm::IntegerType instance and the returned LLVMValueRef will
+ * correspond to a llvm::ConstantInt.
+ *
+ * For floating point types, the LLVMTypeRef returned corresponds to a
+ * llvm::ConstantFP.
+ *
+ * @{
+ */
=20
-/* Operations on scalar constants */
+/**
+ * Obtain a constant value for an integer type.
+ *
+ * The returned value corresponds to a llvm::ConstantInt.
+ *
+ * @see llvm::ConstantInt::get()
+ *
+ * @param IntTy Integer type to obtain value of.
+ * @param N The value the returned instance should refer to.
+ * @param SignExtend Whether to sign extend the produced value.
+ */
 LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N,
                           LLVMBool SignExtend);
+
+/**
+ * Obtain a constant value for an integer of arbitrary precision.
+ *
+ * @see llvm::ConstantInt::get()
+ */
 LLVMValueRef LLVMConstIntOfArbitraryPrecision(LLVMTypeRef IntTy,
                                               unsigned NumWords,
                                               const uint64_t Words[]);
+
+/**
+ * Obtain a constant value for an integer parsed from a string.
+ *
+ * A similar API, LLVMConstIntOfStringAndSize is also available. If the
+ * string's length is available, it is preferred to call that function
+ * instead.
+ *
+ * @see llvm::ConstantInt::get()
+ */
 LLVMValueRef LLVMConstIntOfString(LLVMTypeRef IntTy, const char *Text,
                                   uint8_t Radix);
+
+/**
+ * Obtain a constant value for an integer parsed from a string with
+ * specified length.
+ *
+ * @see llvm::ConstantInt::get()
+ */
 LLVMValueRef LLVMConstIntOfStringAndSize(LLVMTypeRef IntTy, const char *Te=
xt,
                                          unsigned SLen, uint8_t Radix);
+
+/**
+ * Obtain a constant value referring to a double floating point value.
+ */
 LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N);
+
+/**
+ * Obtain a constant for a floating point value parsed from a string.
+ *
+ * A similar API, LLVMConstRealOfStringAndSize is also available. It
+ * should be used if the input string's length is known.
+ */
 LLVMValueRef LLVMConstRealOfString(LLVMTypeRef RealTy, const char *Text);
+
+/**
+ * Obtain a constant for a floating point value parsed from a string.
+ */
 LLVMValueRef LLVMConstRealOfStringAndSize(LLVMTypeRef RealTy, const char *=
Text,
                                           unsigned SLen);
+
+/**
+ * Obtain the zero extended value for an integer constant value.
+ *
+ * @see llvm::ConstantInt::getZExtValue()
+ */
 unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal);
+
+/**
+ * Obtain the sign extended value for an integer constant value.
+ *
+ * @see llvm::ConstantInt::getSExtValue()
+ */
 long long LLVMConstIntGetSExtValue(LLVMValueRef ConstantVal);
=20
+/**
+ * @}
+ */
=20
-/* Operations on composite constants */
+/**
+ * @defgroup LLVMCCoreValueConstantComposite Composite Constants
+ *
+ * Functions in this group operate on composite constants.
+ *
+ * @{
+ */
+
+/**
+ * Create a ConstantDataSequential and initialize it with a string.
+ *
+ * @see llvm::ConstantDataArray::getString()
+ */
 LLVMValueRef LLVMConstStringInContext(LLVMContextRef C, const char *Str,
                                       unsigned Length, LLVMBool DontNullTe=
rminate);
-LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,=20
+
+/**
+ * Create a ConstantDataSequential with string content in the global conte=
xt.
+ *
+ * This is the same as LLVMConstStringInContext except it operates on the
+ * global context.
+ *
+ * @see LLVMConstStringInContext()
+ * @see llvm::ConstantDataArray::getString()
+ */
+LLVMValueRef LLVMConstString(const char *Str, unsigned Length,
+                             LLVMBool DontNullTerminate);
+
+/**
+ * Create an anonymous ConstantStruct with the specified values.
+ *
+ * @see llvm::ConstantStruct::getAnon()
+ */
+LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,
                                       LLVMValueRef *ConstantVals,
                                       unsigned Count, LLVMBool Packed);
=20
-LLVMValueRef LLVMConstString(const char *Str, unsigned Length,
-                             LLVMBool DontNullTerminate);
+/**
+ * Create a ConstantStruct in the global Context.
+ *
+ * This is the same as LLVMConstStructInContext except it operates on the
+ * global Context.
+ *
+ * @see LLVMConstStructInContext()
+ */
+LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
+                             LLVMBool Packed);
+
+/**
+ * Create a ConstantArray from values.
+ *
+ * @see llvm::ConstantArray::get()
+ */
 LLVMValueRef LLVMConstArray(LLVMTypeRef ElementTy,
                             LLVMValueRef *ConstantVals, unsigned Length);
-LLVMValueRef LLVMConstStruct(LLVMValueRef *ConstantVals, unsigned Count,
-                             LLVMBool Packed);
+
+/**
+ * Create a non-anonymous ConstantStruct from values.
+ *
+ * @see llvm::ConstantStruct::get()
+ */
 LLVMValueRef LLVMConstNamedStruct(LLVMTypeRef StructTy,
                                   LLVMValueRef *ConstantVals,
                                   unsigned Count);
+
+/**
+ * Create a ConstantVector from values.
+ *
+ * @see llvm::ConstantVector::get()
+ */
 LLVMValueRef LLVMConstVector(LLVMValueRef *ScalarConstantVals, unsigned Si=
ze);
=20
-/* Constant expressions */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueConstantExpressions Constant Expressions
+ *
+ * Functions in this group correspond to APIs on llvm::ConstantExpr.
+ *
+ * @see llvm::ConstantExpr.
+ *
+ * @{
+ */
 LLVMOpcode LLVMGetConstOpcode(LLVMValueRef ConstantVal);
 LLVMValueRef LLVMAlignOf(LLVMTypeRef Ty);
 LLVMValueRef LLVMSizeOf(LLVMTypeRef Ty);
@@ -690,7 +1540,21 @@
                                 LLVMBool HasSideEffects, LLVMBool IsAlignS=
tack);
 LLVMValueRef LLVMBlockAddress(LLVMValueRef F, LLVMBasicBlockRef BB);
=20
-/* Operations on global variables, functions, and aliases (globals) */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueConstantGlobals Global Values
+ *
+ * This group contains functions that operate on global values. Functions =
in
+ * this group relate to functions in the llvm::GlobalValue class tree.
+ *
+ * @see llvm::GlobalValue
+ *
+ * @{
+ */
+
 LLVMModuleRef LLVMGetGlobalParent(LLVMValueRef Global);
 LLVMBool LLVMIsDeclaration(LLVMValueRef Global);
 LLVMLinkage LLVMGetLinkage(LLVMValueRef Global);
@@ -702,7 +1566,15 @@
 unsigned LLVMGetAlignment(LLVMValueRef Global);
 void LLVMSetAlignment(LLVMValueRef Global, unsigned Bytes);
=20
-/* Operations on global variables */
+/**
+ * @defgroup LLVMCoreValueConstantGlobalVariable Global Variables
+ *
+ * This group contains functions that operate on global variable values.
+ *
+ * @see llvm::GlobalVariable
+ *
+ * @{
+ */
 LLVMValueRef LLVMAddGlobal(LLVMModuleRef M, LLVMTypeRef Ty, const char *Na=
me);
 LLVMValueRef LLVMAddGlobalInAddressSpace(LLVMModuleRef M, LLVMTypeRef Ty,
                                          const char *Name,
@@ -720,110 +1592,672 @@
 LLVMBool LLVMIsGlobalConstant(LLVMValueRef GlobalVar);
 void LLVMSetGlobalConstant(LLVMValueRef GlobalVar, LLVMBool IsConstant);
=20
-/* Operations on aliases */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCoreValueConstantGlobalAlias Global Aliases
+ *
+ * This group contains function that operate on global alias values.
+ *
+ * @see llvm::GlobalAlias
+ *
+ * @{
+ */
 LLVMValueRef LLVMAddAlias(LLVMModuleRef M, LLVMTypeRef Ty, LLVMValueRef Al=
iasee,
                           const char *Name);
=20
-/* Operations on functions */
-LLVMValueRef LLVMAddFunction(LLVMModuleRef M, const char *Name,
-                             LLVMTypeRef FunctionTy);
-LLVMValueRef LLVMGetNamedFunction(LLVMModuleRef M, const char *Name);
-LLVMValueRef LLVMGetFirstFunction(LLVMModuleRef M);
-LLVMValueRef LLVMGetLastFunction(LLVMModuleRef M);
-LLVMValueRef LLVMGetNextFunction(LLVMValueRef Fn);
-LLVMValueRef LLVMGetPreviousFunction(LLVMValueRef Fn);
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueFunction Function values
+ *
+ * Functions in this group operate on LLVMValueRef instances that
+ * correspond to llvm::Function instances.
+ *
+ * @see llvm::Function
+ *
+ * @{
+ */
+
+/**
+ * Remove a function from its containing module and deletes it.
+ *
+ * @see llvm::Function::eraseFromParent()
+ */
 void LLVMDeleteFunction(LLVMValueRef Fn);
+
+/**
+ * Obtain the ID number from a function instance.
+ *
+ * @see llvm::Function::getIntrinsicID()
+ */
 unsigned LLVMGetIntrinsicID(LLVMValueRef Fn);
+
+/**
+ * Obtain the calling function of a function.
+ *
+ * The returned value corresponds to the LLVMCallConv enumeration.
+ *
+ * @see llvm::Function::getCallingConv()
+ */
 unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn);
+
+/**
+ * Set the calling convention of a function.
+ *
+ * @see llvm::Function::setCallingConv()
+ *
+ * @param Fn Function to operate on
+ * @param CC LLVMCallConv to set calling convention to
+ */
 void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC);
+
+/**
+ * Obtain the name of the garbage collector to use during code
+ * generation.
+ *
+ * @see llvm::Function::getGC()
+ */
 const char *LLVMGetGC(LLVMValueRef Fn);
+
+/**
+ * Define the garbage collector to use during code generation.
+ *
+ * @see llvm::Function::setGC()
+ */
 void LLVMSetGC(LLVMValueRef Fn, const char *Name);
+
+/**
+ * Add an attribute to a function.
+ *
+ * @see llvm::Function::addAttribute()
+ */
 void LLVMAddFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA);
+
+/**
+ * Obtain an attribute from a function.
+ *
+ * @see llvm::Function::getAttributes()
+ */
 LLVMAttribute LLVMGetFunctionAttr(LLVMValueRef Fn);
+
+/**
+ * Remove an attribute from a function.
+ */
 void LLVMRemoveFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA);
=20
-/* Operations on parameters */
+/**
+ * @defgroup LLVMCCoreValueFunctionParameters Function Parameters
+ *
+ * Functions in this group relate to arguments/parameters on functions.
+ *
+ * Functions in this group expect LLVMValueRef instances that correspond
+ * to llvm::Function instances.
+ *
+ * @{
+ */
+
+/**
+ * Obtain the number of parameters in a function.
+ *
+ * @see llvm::Function::arg_size()
+ */
 unsigned LLVMCountParams(LLVMValueRef Fn);
+
+/**
+ * Obtain the parameters in a function.
+ *
+ * The takes a pointer to a pre-allocated array of LLVMValueRef that is
+ * at least LLVMCountParams() long. This array will be filled with
+ * LLVMValueRef instances which correspond to the parameters the
+ * function receives. Each LLVMValueRef corresponds to a llvm::Argument
+ * instance.
+ *
+ * @see llvm::Function::arg_begin()
+ */
 void LLVMGetParams(LLVMValueRef Fn, LLVMValueRef *Params);
+
+/**
+ * Obtain the parameter at the specified index.
+ *
+ * Parameters are indexed from 0.
+ *
+ * @see llvm::Function::arg_begin()
+ */
 LLVMValueRef LLVMGetParam(LLVMValueRef Fn, unsigned Index);
+
+/**
+ * Obtain the function to which this argument belongs.
+ *
+ * Unlike other functions in this group, this one takes a LLVMValueRef
+ * that corresponds to a llvm::Attribute.
+ *
+ * The returned LLVMValueRef is the llvm::Function to which this
+ * argument belongs.
+ */
 LLVMValueRef LLVMGetParamParent(LLVMValueRef Inst);
+
+/**
+ * Obtain the first parameter to a function.
+ *
+ * @see llvm::Function::arg_begin()
+ */
 LLVMValueRef LLVMGetFirstParam(LLVMValueRef Fn);
+
+/**
+ * Obtain the last parameter to a function.
+ *
+ * @see llvm::Function::arg_end()
+ */
 LLVMValueRef LLVMGetLastParam(LLVMValueRef Fn);
+
+/**
+ * Obtain the next parameter to a function.
+ *
+ * This takes a LLVMValueRef obtained from LLVMGetFirstParam() (which is
+ * actually a wrapped iterator) and obtains the next parameter from the
+ * underlying iterator.
+ */
 LLVMValueRef LLVMGetNextParam(LLVMValueRef Arg);
+
+/**
+ * Obtain the previous parameter to a function.
+ *
+ * This is the opposite of LLVMGetNextParam().
+ */
 LLVMValueRef LLVMGetPreviousParam(LLVMValueRef Arg);
+
+/**
+ * Add an attribute to a function argument.
+ *
+ * @see llvm::Argument::addAttr()
+ */
 void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA);
+
+/**
+ * Remove an attribute from a function argument.
+ *
+ * @see llvm::Argument::removeAttr()
+ */
 void LLVMRemoveAttribute(LLVMValueRef Arg, LLVMAttribute PA);
+
+/**
+ * Get an attribute from a function argument.
+ */
 LLVMAttribute LLVMGetAttribute(LLVMValueRef Arg);
+
+/**
+ * Set the alignment for a function parameter.
+ *
+ * @see llvm::Argument::addAttr()
+ * @see llvm::Attribute::constructAlignmentFromInt()
+ */
 void LLVMSetParamAlignment(LLVMValueRef Arg, unsigned align);
=20
-/* Operations on basic blocks */
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueMetadata Metadata
+ *
+ * @{
+ */
+
+/**
+ * Obtain a MDString value from a context.
+ *
+ * The returned instance corresponds to the llvm::MDString class.
+ *
+ * The instance is specified by string data of a specified length. The
+ * string content is copied, so the backing memory can be freed after
+ * this function returns.
+ */
+LLVMValueRef LLVMMDStringInContext(LLVMContextRef C, const char *Str,
+                                   unsigned SLen);
+
+/**
+ * Obtain a MDString value from the global context.
+ */
+LLVMValueRef LLVMMDString(const char *Str, unsigned SLen);
+
+/**
+ * Obtain a MDNode value from a context.
+ *
+ * The returned value corresponds to the llvm::MDNode class.
+ */
+LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals,
+                                 unsigned Count);
+
+/**
+ * Obtain a MDNode value from the global context.
+ */
+LLVMValueRef LLVMMDNode(LLVMValueRef *Vals, unsigned Count);
+
+/**
+ * Obtain the underlying string from a MDString value.
+ *
+ * @param V Instance to obtain string from.
+ * @param Len Memory address which will hold length of returned string.
+ * @return String data in MDString.
+ */
+const char  *LLVMGetMDString(LLVMValueRef V, unsigned* Len);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueBasicBlock Basic Block
+ *
+ * A basic block represents a single entry single exit section of code.
+ * Basic blocks contain a list of instructions which form the body of
+ * the block.
+ *
+ * Basic blocks belong to functions. They have the type of label.
+ *
+ * Basic blocks are themselves values. However, the C API models them as
+ * LLVMBasicBlockRef.
+ *
+ * @see llvm::BasicBlock
+ *
+ * @{
+ */
+
+/**
+ * Convert a basic block instance to a value type.
+ */
 LLVMValueRef LLVMBasicBlockAsValue(LLVMBasicBlockRef BB);
+
+/**
+ * Determine whether a LLVMValueRef is itself a basic block.
+ */
 LLVMBool LLVMValueIsBasicBlock(LLVMValueRef Val);
+
+/**
+ * Convert a LLVMValueRef to a LLVMBasicBlockRef instance.
+ */
 LLVMBasicBlockRef LLVMValueAsBasicBlock(LLVMValueRef Val);
+
+/**
+ * Obtain the function to which a basic block belongs.
+ *
+ * @see llvm::BasicBlock::getParent()
+ */
 LLVMValueRef LLVMGetBasicBlockParent(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the terminator instruction for a basic block.
+ *
+ * If the basic block does not have a terminator (it is not well-formed
+ * if it doesn't), then NULL is returned.
+ *
+ * The returned LLVMValueRef corresponds to a llvm::TerminatorInst.
+ *
+ * @see llvm::BasicBlock::getTerminator()
+ */
 LLVMValueRef LLVMGetBasicBlockTerminator(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the number of basic blocks in a function.
+ *
+ * @param Fn Function value to operate on.
+ */
 unsigned LLVMCountBasicBlocks(LLVMValueRef Fn);
+
+/**
+ * Obtain all of the basic blocks in a function.
+ *
+ * This operates on a function value. The BasicBlocks parameter is a
+ * pointer to a pre-allocated array of LLVMBasicBlockRef of at least
+ * LLVMCountBasicBlocks() in length. This array is populated with
+ * LLVMBasicBlockRef instances.
+ */
 void LLVMGetBasicBlocks(LLVMValueRef Fn, LLVMBasicBlockRef *BasicBlocks);
+
+/**
+ * Obtain the first basic block in a function.
+ *
+ * The returned basic block can be used as an iterator. You will likely
+ * eventually call into LLVMGetNextBasicBlock() with it.
+ *
+ * @see llvm::Function::begin()
+ */
 LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn);
+
+/**
+ * Obtain the last basic block in a function.
+ *
+ * @see llvm::Function::end()
+ */
 LLVMBasicBlockRef LLVMGetLastBasicBlock(LLVMValueRef Fn);
+
+/**
+ * Advance a basic block iterator.
+ */
 LLVMBasicBlockRef LLVMGetNextBasicBlock(LLVMBasicBlockRef BB);
+
+/**
+ * Go backwards in a basic block iterator.
+ */
 LLVMBasicBlockRef LLVMGetPreviousBasicBlock(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the basic block that corresponds to the entry point of a
+ * function.
+ *
+ * @see llvm::Function::getEntryBlock()
+ */
 LLVMBasicBlockRef LLVMGetEntryBasicBlock(LLVMValueRef Fn);
=20
+/**
+ * Append a basic block to the end of a function.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
 LLVMBasicBlockRef LLVMAppendBasicBlockInContext(LLVMContextRef C,
                                                 LLVMValueRef Fn,
                                                 const char *Name);
+
+/**
+ * Append a basic block to the end of a function using the global
+ * context.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
+LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef Fn, const char *Name);
+
+/**
+ * Insert a basic block in a function before another basic block.
+ *
+ * The function to add to is determined by the function of the
+ * passed basic block.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
 LLVMBasicBlockRef LLVMInsertBasicBlockInContext(LLVMContextRef C,
                                                 LLVMBasicBlockRef BB,
                                                 const char *Name);
=20
-LLVMBasicBlockRef LLVMAppendBasicBlock(LLVMValueRef Fn, const char *Name);
+/**
+ * Insert a basic block in a function using the global context.
+ *
+ * @see llvm::BasicBlock::Create()
+ */
 LLVMBasicBlockRef LLVMInsertBasicBlock(LLVMBasicBlockRef InsertBeforeBB,
                                        const char *Name);
+
+/**
+ * Remove a basic block from a function and delete it.
+ *
+ * This deletes the basic block from its containing function and deletes
+ * the basic block itself.
+ *
+ * @see llvm::BasicBlock::eraseFromParent()
+ */
 void LLVMDeleteBasicBlock(LLVMBasicBlockRef BB);
+
+/**
+ * Remove a basic block from a function.
+ *
+ * This deletes the basic block from its containing function but keep
+ * the basic block alive.
+ *
+ * @see llvm::BasicBlock::removeFromParent()
+ */
 void LLVMRemoveBasicBlockFromParent(LLVMBasicBlockRef BB);
=20
+/**
+ * Move a basic block to before another one.
+ *
+ * @see llvm::BasicBlock::moveBefore()
+ */
 void LLVMMoveBasicBlockBefore(LLVMBasicBlockRef BB, LLVMBasicBlockRef Move=
Pos);
+
+/**
+ * Move a basic block to after another one.
+ *
+ * @see llvm::BasicBlock::moveAfter()
+ */
 void LLVMMoveBasicBlockAfter(LLVMBasicBlockRef BB, LLVMBasicBlockRef MoveP=
os);
=20
+/**
+ * Obtain the first instruction in a basic block.
+ *
+ * The returned LLVMValueRef corresponds to a llvm::Instruction
+ * instance.
+ */
 LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB);
+
+/**
+ * Obtain the last instruction in a basic block.
+ *
+ * The returned LLVMValueRef corresponds to a LLVM:Instruction.
+ */
 LLVMValueRef LLVMGetLastInstruction(LLVMBasicBlockRef BB);
=20
-/* Operations on instructions */
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreValueInstruction Instructions
+ *
+ * Functions in this group relate to the inspection and manipulation of
+ * individual instructions.
+ *
+ * In the C++ API, an instruction is modeled by llvm::Instruction. This
+ * class has a large number of descendents. llvm::Instruction is a
+ * llvm::Value and in the C API, instructions are modeled by
+ * LLVMValueRef.
+ *
+ * This group also contains sub-groups which operate on specific
+ * llvm::Instruction types, e.g. llvm::CallInst.
+ *
+ * @{
+ */
+
+/**
+ * Determine whether an instruction has any metadata attached.
+ */
+int LLVMHasMetadata(LLVMValueRef Val);
+
+/**
+ * Return metadata associated with an instruction value.
+ */
+LLVMValueRef LLVMGetMetadata(LLVMValueRef Val, unsigned KindID);
+
+/**
+ * Set metadata associated with an instruction value.
+ */
+void LLVMSetMetadata(LLVMValueRef Val, unsigned KindID, LLVMValueRef Node);
+
+/**
+ * Obtain the basic block to which an instruction belongs.
+ *
+ * @see llvm::Instruction::getParent()
+ */
 LLVMBasicBlockRef LLVMGetInstructionParent(LLVMValueRef Inst);
+
+/**
+ * Obtain the instruction that occurs after the one specified.
+ *
+ * The next instruction will be from the same basic block.
+ *
+ * If this is the last instruction in a basic block, NULL will be
+ * returned.
+ */
 LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst);
+
+/**
+ * Obtain the instruction that occured before this one.
+ *
+ * If the instruction is the first instruction in a basic block, NULL
+ * will be returned.
+ */
 LLVMValueRef LLVMGetPreviousInstruction(LLVMValueRef Inst);
+
+/**
+ * Remove and delete an instruction.
+ *
+ * The instruction specified is removed from its containing building
+ * block and then deleted.
+ *
+ * @see llvm::Instruction::eraseFromParent()
+ */
 void LLVMInstructionEraseFromParent(LLVMValueRef Inst);
+
+/**
+ * Obtain the code opcode for an individual instruction.
+ *
+ * @see llvm::Instruction::getOpCode()
+ */
 LLVMOpcode   LLVMGetInstructionOpcode(LLVMValueRef Inst);
+
+/**
+ * Obtain the predicate of an instruction.
+ *
+ * This is only valid for instructions that correspond to llvm::ICmpInst
+ * or llvm::ConstantExpr whose opcode is llvm::Instruction::ICmp.
+ *
+ * @see llvm::ICmpInst::getPredicate()
+ */
 LLVMIntPredicate LLVMGetICmpPredicate(LLVMValueRef Inst);
=20
-/* Operations on call sites */
+/**
+ * @defgroup LLVMCCoreValueInstructionCall Call Sites and Invocations
+ *
+ * Functions in this group apply to instructions that refer to call
+ * sites and invocations. These correspond to C++ types in the
+ * llvm::CallInst class tree.
+ *
+ * @{
+ */
+
+/**
+ * Set the calling convention for a call instruction.
+ *
+ * This expects an LLVMValueRef that corresponds to a llvm::CallInst or
+ * llvm::InvokeInst.
+ *
+ * @see llvm::CallInst::setCallingConv()
+ * @see llvm::InvokeInst::setCallingConv()
+ */
 void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC);
+
+/**
+ * Obtain the calling convention for a call instruction.
+ *
+ * This is the opposite of LLVMSetInstructionCallConv(). Reads its
+ * usage.
+ *
+ * @see LLVMSetInstructionCallConv()
+ */
 unsigned LLVMGetInstructionCallConv(LLVMValueRef Instr);
+
+
 void LLVMAddInstrAttribute(LLVMValueRef Instr, unsigned index, LLVMAttribu=
te);
-void LLVMRemoveInstrAttribute(LLVMValueRef Instr, unsigned index,=20
+void LLVMRemoveInstrAttribute(LLVMValueRef Instr, unsigned index,
                               LLVMAttribute);
-void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index,=20
+void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index,
                                 unsigned align);
=20
-/* Operations on call instructions (only) */
+/**
+ * Obtain whether a call instruction is a tail call.
+ *
+ * This only works on llvm::CallInst instructions.
+ *
+ * @see llvm::CallInst::isTailCall()
+ */
 LLVMBool LLVMIsTailCall(LLVMValueRef CallInst);
+
+/**
+ * Set whether a call instruction is a tail call.
+ *
+ * This only works on llvm::CallInst instructions.
+ *
+ * @see llvm::CallInst::setTailCall()
+ */
 void LLVMSetTailCall(LLVMValueRef CallInst, LLVMBool IsTailCall);
=20
-/* Operations on switch instructions (only) */
+/**
+ * @}
+ */
+
+/**
+ * Obtain the default destination basic block of a switch instruction.
+ *
+ * This only works on llvm::SwitchInst instructions.
+ *
+ * @see llvm::SwitchInst::getDefaultDest()
+ */
 LLVMBasicBlockRef LLVMGetSwitchDefaultDest(LLVMValueRef SwitchInstr);
=20
-/* Operations on phi nodes */
+/**
+ * @defgroup LLVMCCoreValueInstructionPHINode PHI Nodes
+ *
+ * Functions in this group only apply to instructions that map to
+ * llvm::PHINode instances.
+ *
+ * @{
+ */
+
+/**
+ * Add an incoming value to the end of a PHI list.
+ */
 void LLVMAddIncoming(LLVMValueRef PhiNode, LLVMValueRef *IncomingValues,
                      LLVMBasicBlockRef *IncomingBlocks, unsigned Count);
+
+/**
+ * Obtain the number of incoming basic blocks to a PHI node.
+ */
 unsigned LLVMCountIncoming(LLVMValueRef PhiNode);
+
+/**
+ * Obtain an incoming value to a PHI node as a LLVMValueRef.
+ */
 LLVMValueRef LLVMGetIncomingValue(LLVMValueRef PhiNode, unsigned Index);
+
+/**
+ * Obtain an incoming value to a PHI node as a LLVMBasicBlockRef.
+ */
 LLVMBasicBlockRef LLVMGetIncomingBlock(LLVMValueRef PhiNode, unsigned Inde=
x);
=20
-/*=3D=3D=3D-- Instruction builders ---------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @}
+ */
=20
-/* An instruction builder represents a point within a basic block, and is =
the
- * exclusive means of building instructions using the C interface.
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCoreInstructionBuilder Instruction Builders
+ *
+ * An instruction builder represents a point within a basic block and is
+ * the exclusive means of building instructions using the C interface.
+ *
+ * @{
  */
=20
 LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C);
@@ -964,6 +2398,8 @@
                                    const char *Name);
 LLVMValueRef LLVMBuildGlobalStringPtr(LLVMBuilderRef B, const char *Str,
                                       const char *Name);
+LLVMBool LLVMGetVolatile(LLVMValueRef MemoryAccessInst);
+void LLVMSetVolatile(LLVMValueRef MemoryAccessInst, LLVMBool IsVolatile);
=20
 /* Casts */
 LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef, LLVMValueRef Val,
@@ -1044,21 +2480,37 @@
 LLVMValueRef LLVMBuildPtrDiff(LLVMBuilderRef, LLVMValueRef LHS,
                               LLVMValueRef RHS, const char *Name);
=20
+/**
+ * @}
+ */
=20
-/*=3D=3D=3D-- Module providers -------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @defgroup LLVMCCoreModuleProvider Module Providers
+ *
+ * @{
+ */
=20
-/* Changes the type of M so it can be passed to FunctionPassManagers and t=
he
+/**
+ * Changes the type of M so it can be passed to FunctionPassManagers and t=
he
  * JIT.  They take ModuleProviders for historical reasons.
  */
 LLVMModuleProviderRef
 LLVMCreateModuleProviderForExistingModule(LLVMModuleRef M);
=20
-/* Destroys the module M.
+/**
+ * Destroys the module M.
  */
 void LLVMDisposeModuleProvider(LLVMModuleProviderRef M);
=20
+/**
+ * @}
+ */
=20
-/*=3D=3D=3D-- Memory buffers ---------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @defgroup LLVMCCoreMemoryBuffers Memory Buffers
+ *
+ * @{
+ */
=20
 LLVMBool LLVMCreateMemoryBufferWithContentsOfFile(const char *Path,
                                                   LLVMMemoryBufferRef *Out=
MemBuf,
@@ -1067,23 +2519,39 @@
                                          char **OutMessage);
 void LLVMDisposeMemoryBuffer(LLVMMemoryBufferRef MemBuf);
=20
-/*=3D=3D=3D-- Pass Registry ----------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCorePassRegistry Pass Registry
+ *
+ * @{
+ */
=20
 /** Return the global pass registry, for use with initialization functions.
-    See llvm::PassRegistry::getPassRegistry. */
+    @see llvm::PassRegistry::getPassRegistry */
 LLVMPassRegistryRef LLVMGetGlobalPassRegistry(void);
=20
-/*=3D=3D=3D-- Pass Managers ----------------------------------------------=
-------=3D=3D=3D*/
+/**
+ * @}
+ */
+
+/**
+ * @defgroup LLVMCCorePassManagers Pass Managers
+ *
+ * @{
+ */
=20
 /** Constructs a new whole-module pass pipeline. This type of pipeline is
     suitable for link-time optimization and whole-module transformations.
-    See llvm::PassManager::PassManager. */
+    @see llvm::PassManager::PassManager */
 LLVMPassManagerRef LLVMCreatePassManager(void);
=20
 /** Constructs a new function-by-function pass pipeline over the module
     provider. It does not take ownership of the module provider. This type=
 of
     pipeline is suitable for code generation and JIT compilation tasks.
-    See llvm::FunctionPassManager::FunctionPassManager. */
+    @see llvm::FunctionPassManager::FunctionPassManager */
 LLVMPassManagerRef LLVMCreateFunctionPassManagerForModule(LLVMModuleRef M);
=20
 /** Deprecated: Use LLVMCreateFunctionPassManagerForModule instead. */
@@ -1091,30 +2559,42 @@
=20
 /** Initializes, executes on the provided module, and finalizes all of the
     passes scheduled in the pass manager. Returns 1 if any of the passes
-    modified the module, 0 otherwise. See llvm::PassManager::run(Module&).=
 */
+    modified the module, 0 otherwise.
+    @see llvm::PassManager::run(Module&) */
 LLVMBool LLVMRunPassManager(LLVMPassManagerRef PM, LLVMModuleRef M);
=20
 /** Initializes all of the function passes scheduled in the function pass
     manager. Returns 1 if any of the passes modified the module, 0 otherwi=
se.
-    See llvm::FunctionPassManager::doInitialization. */
+    @see llvm::FunctionPassManager::doInitialization */
 LLVMBool LLVMInitializeFunctionPassManager(LLVMPassManagerRef FPM);
=20
 /** Executes all of the function passes scheduled in the function pass man=
ager
     on the provided function. Returns 1 if any of the passes modified the
     function, false otherwise.
-    See llvm::FunctionPassManager::run(Function&). */
+    @see llvm::FunctionPassManager::run(Function&) */
 LLVMBool LLVMRunFunctionPassManager(LLVMPassManagerRef FPM, LLVMValueRef F=
);
=20
 /** Finalizes all of the function passes scheduled in in the function pass
     manager. Returns 1 if any of the passes modified the module, 0 otherwi=
se.
-    See llvm::FunctionPassManager::doFinalization. */
+    @see llvm::FunctionPassManager::doFinalization */
 LLVMBool LLVMFinalizeFunctionPassManager(LLVMPassManagerRef FPM);
=20
 /** Frees the memory of a pass pipeline. For function pipelines, does not =
free
     the module provider.
-    See llvm::PassManagerBase::~PassManagerBase. */
+    @see llvm::PassManagerBase::~PassManagerBase. */
 void LLVMDisposePassManager(LLVMPassManagerRef PM);
=20
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
=20
 #ifdef __cplusplus
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Disas=
sembler.h
--- a/head/contrib/llvm/include/llvm-c/Disassembler.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm-c/Disassembler.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -19,6 +19,13 @@
 #include <stddef.h>
=20
 /**
+ * @defgroup LLVMCDisassembler Disassembler
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
+/**
  * An opaque reference to a disassembler context.
  */
 typedef void *LLVMDisasmContextRef;
@@ -157,6 +164,10 @@
                              uint64_t BytesSize, uint64_t PC,
                              char *OutString, size_t OutStringSize);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
 #endif /* !defined(__cplusplus) */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Enhan=
cedDisassembly.h
--- a/head/contrib/llvm/include/llvm-c/EnhancedDisassembly.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/EnhancedDisassembly.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -25,6 +25,19 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCEnhancedDisassembly Enhanced Disassembly
+ * @ingroup LLVMC
+ * @deprecated
+ *
+ * This module contains an interface to the Enhanced Disassembly (edis)
+ * library. The edis library is deprecated and will likely disappear in
+ * the near future. You should use the @ref LLVMCDisassembler interface
+ * instead.
+ *
+ * @{
+ */
+
 /*!
  @typedef EDByteReaderCallback
  Interface to memory from which instructions may be read.
@@ -504,6 +517,10 @@
 int EDBlockVisitTokens(EDInstRef inst,
                        EDTokenVisitor_t visitor);
=20
+/**
+ * @}
+ */
+
 #endif
=20
 #ifdef __cplusplus
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Execu=
tionEngine.h
--- a/head/contrib/llvm/include/llvm-c/ExecutionEngine.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/ExecutionEngine.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -26,6 +26,13 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCExecutionEngine Execution Engine
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
 void LLVMLinkInJIT(void);
 void LLVMLinkInInterpreter(void);
=20
@@ -125,6 +132,10 @@
=20
 void *LLVMGetPointerToGlobal(LLVMExecutionEngineRef EE, LLVMValueRef Globa=
l);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Initi=
alization.h
--- a/head/contrib/llvm/include/llvm-c/Initialization.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/Initialization.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -22,9 +22,19 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCInitialization Initialization Routines
+ * @ingroup LLVMC
+ *
+ * This module contains routines used to initialize the LLVM system.
+ *
+ * @{
+ */
+
 void LLVMInitializeCore(LLVMPassRegistryRef R);
 void LLVMInitializeTransformUtils(LLVMPassRegistryRef R);
 void LLVMInitializeScalarOpts(LLVMPassRegistryRef R);
+void LLVMInitializeVectorization(LLVMPassRegistryRef R);
 void LLVMInitializeInstCombine(LLVMPassRegistryRef R);
 void LLVMInitializeIPO(LLVMPassRegistryRef R);
 void LLVMInitializeInstrumentation(LLVMPassRegistryRef R);
@@ -33,6 +43,10 @@
 void LLVMInitializeCodeGen(LLVMPassRegistryRef R);
 void LLVMInitializeTarget(LLVMPassRegistryRef R);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/LinkT=
imeOptimizer.h
--- a/head/contrib/llvm/include/llvm-c/LinkTimeOptimizer.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/LinkTimeOptimizer.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -20,6 +20,13 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCLinkTimeOptimizer Link Time Optimization
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
   /// This provides a dummy type for pointers to the LTO object.
   typedef void* llvm_lto_t;
=20
@@ -51,6 +58,10 @@
   extern llvm_lto_status_t llvm_optimize_modules
     (llvm_lto_t lto, const char* output_filename);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Objec=
t.h
--- a/head/contrib/llvm/include/llvm-c/Object.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm-c/Object.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -28,23 +28,74 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCObject Object file reading and writing
+ * @ingroup LLVMC
+ *
+ * @{
+ */
=20
+// Opaque type wrappers
 typedef struct LLVMOpaqueObjectFile *LLVMObjectFileRef;
+typedef struct LLVMOpaqueSectionIterator *LLVMSectionIteratorRef;
+typedef struct LLVMOpaqueSymbolIterator *LLVMSymbolIteratorRef;
+typedef struct LLVMOpaqueRelocationIterator *LLVMRelocationIteratorRef;
=20
-typedef struct LLVMOpaqueSectionIterator *LLVMSectionIteratorRef;
-
+// ObjectFile creation
 LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf);
 void LLVMDisposeObjectFile(LLVMObjectFileRef ObjectFile);
=20
+// ObjectFile Section iterators
 LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile);
 void LLVMDisposeSectionIterator(LLVMSectionIteratorRef SI);
 LLVMBool LLVMIsSectionIteratorAtEnd(LLVMObjectFileRef ObjectFile,
                                 LLVMSectionIteratorRef SI);
 void LLVMMoveToNextSection(LLVMSectionIteratorRef SI);
+void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect,
+                                 LLVMSymbolIteratorRef Sym);
+
+// ObjectFile Symbol iterators
+LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile);
+void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI);
+LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile,
+                                LLVMSymbolIteratorRef SI);
+void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI);
+
+// SectionRef accessors
 const char *LLVMGetSectionName(LLVMSectionIteratorRef SI);
 uint64_t LLVMGetSectionSize(LLVMSectionIteratorRef SI);
 const char *LLVMGetSectionContents(LLVMSectionIteratorRef SI);
+uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI);
+LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI,
+                                 LLVMSymbolIteratorRef Sym);
=20
+// Section Relocation iterators
+LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Sectio=
n);
+void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef RI);
+LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section,
+                                       LLVMRelocationIteratorRef RI);
+void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef RI);
+
+
+// SymbolRef accessors
+const char *LLVMGetSymbolName(LLVMSymbolIteratorRef SI);
+uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI);
+uint64_t LLVMGetSymbolFileOffset(LLVMSymbolIteratorRef SI);
+uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI);
+
+// RelocationRef accessors
+uint64_t LLVMGetRelocationAddress(LLVMRelocationIteratorRef RI);
+uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI);
+LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI=
);
+uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI);
+// NOTE: Caller takes ownership of returned string of the two
+// following functions.
+const char *LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI);
+const char *LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI);
+
+/**
+ * @}
+ */
=20
 #ifdef __cplusplus
 }
@@ -68,6 +119,27 @@
       return reinterpret_cast<LLVMSectionIteratorRef>
         (const_cast<section_iterator*>(SI));
     }
+
+    inline symbol_iterator *unwrap(LLVMSymbolIteratorRef SI) {
+      return reinterpret_cast<symbol_iterator*>(SI);
+    }
+
+    inline LLVMSymbolIteratorRef
+    wrap(const symbol_iterator *SI) {
+      return reinterpret_cast<LLVMSymbolIteratorRef>
+        (const_cast<symbol_iterator*>(SI));
+    }
+
+    inline relocation_iterator *unwrap(LLVMRelocationIteratorRef SI) {
+      return reinterpret_cast<relocation_iterator*>(SI);
+    }
+
+    inline LLVMRelocationIteratorRef
+    wrap(const relocation_iterator *SI) {
+      return reinterpret_cast<LLVMRelocationIteratorRef>
+        (const_cast<relocation_iterator*>(SI));
+    }
+
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Targe=
t.h
--- a/head/contrib/llvm/include/llvm-c/Target.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm-c/Target.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -26,6 +26,13 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCTarget Target information
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
 enum LLVMByteOrdering { LLVMBigEndian, LLVMLittleEndian };
=20
 typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
@@ -47,6 +54,24 @@
 #include "llvm/Config/Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
  =20
+/* Declare all of the available assembly printer initialization functions.=
 */
+#define LLVM_ASM_PRINTER(TargetName) \
+  void LLVMInitialize##TargetName##AsmPrinter();
+#include "llvm/Config/AsmPrinters.def"
+#undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */
+
+/* Declare all of the available assembly parser initialization functions. =
*/
+#define LLVM_ASM_PARSER(TargetName) \
+  void LLVMInitialize##TargetName##AsmParser();
+#include "llvm/Config/AsmParsers.def"
+#undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */
+
+/* Declare all of the available disassembler initialization functions. */
+#define LLVM_DISASSEMBLER(TargetName) \
+  void LLVMInitialize##TargetName##Disassembler();
+#include "llvm/Config/Disassemblers.def"
+#undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */
+ =20
 /** LLVMInitializeAllTargetInfos - The main program should call this funct=
ion if
     it wants access to all available targets that LLVM is configured to
     support. */
@@ -64,6 +89,43 @@
 #include "llvm/Config/Targets.def"
 #undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
 }
+
+/** LLVMInitializeAllTargetMCs - The main program should call this functio=
n if
+    it wants access to all available target MC that LLVM is configured to
+    support. */
+static inline void LLVMInitializeAllTargetMCs(void) {
+#define LLVM_TARGET(TargetName) LLVMInitialize##TargetName##TargetMC();
+#include "llvm/Config/Targets.def"
+#undef LLVM_TARGET  /* Explicit undef to make SWIG happier */
+}
+ =20
+/** LLVMInitializeAllAsmPrinters - The main program should call this funct=
ion if
+    it wants all asm printers that LLVM is configured to support, to make =
them
+    available via the TargetRegistry. */
+static inline void LLVMInitializeAllAsmPrinters() {
+#define LLVM_ASM_PRINTER(TargetName) LLVMInitialize##TargetName##AsmPrinte=
r();
+#include "llvm/Config/AsmPrinters.def"
+#undef LLVM_ASM_PRINTER  /* Explicit undef to make SWIG happier */
+}
+ =20
+/** LLVMInitializeAllAsmParsers - The main program should call this functi=
on if
+    it wants all asm parsers that LLVM is configured to support, to make t=
hem
+    available via the TargetRegistry. */
+static inline void LLVMInitializeAllAsmParsers() {
+#define LLVM_ASM_PARSER(TargetName) LLVMInitialize##TargetName##AsmParser(=
);
+#include "llvm/Config/AsmParsers.def"
+#undef LLVM_ASM_PARSER  /* Explicit undef to make SWIG happier */
+}
+ =20
+/** LLVMInitializeAllDisassemblers - The main program should call this fun=
ction
+    if it wants all disassemblers that LLVM is configured to support, to m=
ake
+    them available via the TargetRegistry. */
+static inline void LLVMInitializeAllDisassemblers() {
+#define LLVM_DISASSEMBLER(TargetName) \
+  LLVMInitialize##TargetName##Disassembler();
+#include "llvm/Config/Disassemblers.def"
+#undef LLVM_DISASSEMBLER  /* Explicit undef to make SWIG happier */
+}
  =20
 /** LLVMInitializeNativeTarget - The main program should call this functio=
n to
     initialize the native target corresponding to the host.  This is usefu=
l=20
@@ -157,6 +219,9 @@
     See the destructor llvm::TargetData::~TargetData. */
 void LLVMDisposeTargetData(LLVMTargetDataRef);
=20
+/**
+ * @}
+ */
=20
 #ifdef __cplusplus
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Trans=
forms/IPO.h
--- a/head/contrib/llvm/include/llvm-c/Transforms/IPO.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/Transforms/IPO.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -21,6 +21,13 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCTransformsIPO Interprocedural transformations
+ * @ingroup LLVMCTransforms
+ *
+ * @{
+ */
+
 /** See llvm::createArgumentPromotionPass function. */
 void LLVMAddArgumentPromotionPass(LLVMPassManagerRef PM);
=20
@@ -63,6 +70,10 @@
 /** See llvm::createStripSymbolsPass function. */
 void LLVMAddStripSymbolsPass(LLVMPassManagerRef PM);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
 #endif /* defined(__cplusplus) */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Trans=
forms/PassManagerBuilder.h
--- a/head/contrib/llvm/include/llvm-c/Transforms/PassManagerBuilder.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/Transforms/PassManagerBuilder.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -23,6 +23,13 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCTransformsPassManagerBuilder Pass manager builder
+ * @ingroup LLVMCTransforms
+ *
+ * @{
+ */
+
 /** See llvm::PassManagerBuilder. */
 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void);
 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB);
@@ -73,6 +80,10 @@
                                                   bool Internalize,
                                                   bool RunInliner);
=20
+/**
+ * @}
+ */
+
 #ifdef __cplusplus
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/Trans=
forms/Scalar.h
--- a/head/contrib/llvm/include/llvm-c/Transforms/Scalar.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/Transforms/Scalar.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -25,6 +25,13 @@
 extern "C" {
 #endif
=20
+/**
+ * @defgroup LLVMCTransformsScalar Scalar transformations
+ * @ingroup LLVMCTransforms
+ *
+ * @{
+ */
+
 /** See llvm::createAggressiveDCEPass function. */
 void LLVMAddAggressiveDCEPass(LLVMPassManagerRef PM);
=20
@@ -116,6 +123,9 @@
 /** See llvm::createBasicAliasAnalysisPass function */
 void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef PM);
=20
+/**
+ * @}
+ */
=20
 #ifdef __cplusplus
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm-c/lto.h
--- a/head/contrib/llvm/include/llvm-c/lto.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm-c/lto.h	Tue Apr 17 11:51:51 2012 +0300
@@ -20,24 +20,31 @@
 #include <stddef.h>
 #include <unistd.h>
=20
+/**
+ * @defgroup LLVMCLTO LTO
+ * @ingroup LLVMC
+ *
+ * @{
+ */
+
 #define LTO_API_VERSION 4
=20
 typedef enum {
     LTO_SYMBOL_ALIGNMENT_MASK              =3D 0x0000001F, /* log2 of alig=
nment */
-    LTO_SYMBOL_PERMISSIONS_MASK            =3D 0x000000E0,   =20
-    LTO_SYMBOL_PERMISSIONS_CODE            =3D 0x000000A0,   =20
-    LTO_SYMBOL_PERMISSIONS_DATA            =3D 0x000000C0,   =20
-    LTO_SYMBOL_PERMISSIONS_RODATA          =3D 0x00000080,   =20
-    LTO_SYMBOL_DEFINITION_MASK             =3D 0x00000700,   =20
-    LTO_SYMBOL_DEFINITION_REGULAR          =3D 0x00000100,   =20
-    LTO_SYMBOL_DEFINITION_TENTATIVE        =3D 0x00000200,   =20
-    LTO_SYMBOL_DEFINITION_WEAK             =3D 0x00000300,   =20
-    LTO_SYMBOL_DEFINITION_UNDEFINED        =3D 0x00000400,   =20
+    LTO_SYMBOL_PERMISSIONS_MASK            =3D 0x000000E0,
+    LTO_SYMBOL_PERMISSIONS_CODE            =3D 0x000000A0,
+    LTO_SYMBOL_PERMISSIONS_DATA            =3D 0x000000C0,
+    LTO_SYMBOL_PERMISSIONS_RODATA          =3D 0x00000080,
+    LTO_SYMBOL_DEFINITION_MASK             =3D 0x00000700,
+    LTO_SYMBOL_DEFINITION_REGULAR          =3D 0x00000100,
+    LTO_SYMBOL_DEFINITION_TENTATIVE        =3D 0x00000200,
+    LTO_SYMBOL_DEFINITION_WEAK             =3D 0x00000300,
+    LTO_SYMBOL_DEFINITION_UNDEFINED        =3D 0x00000400,
     LTO_SYMBOL_DEFINITION_WEAKUNDEF        =3D 0x00000500,
-    LTO_SYMBOL_SCOPE_MASK                  =3D 0x00003800,   =20
-    LTO_SYMBOL_SCOPE_INTERNAL              =3D 0x00000800,   =20
-    LTO_SYMBOL_SCOPE_HIDDEN                =3D 0x00001000,   =20
-    LTO_SYMBOL_SCOPE_PROTECTED             =3D 0x00002000,   =20
+    LTO_SYMBOL_SCOPE_MASK                  =3D 0x00003800,
+    LTO_SYMBOL_SCOPE_INTERNAL              =3D 0x00000800,
+    LTO_SYMBOL_SCOPE_HIDDEN                =3D 0x00001000,
+    LTO_SYMBOL_SCOPE_PROTECTED             =3D 0x00002000,
     LTO_SYMBOL_SCOPE_DEFAULT               =3D 0x00001800,
     LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN =3D 0x00002800
 } lto_symbol_attributes;
@@ -88,7 +95,7 @@
  * Checks if a file is a loadable object compiled for requested target.
  */
 extern bool
-lto_module_is_object_file_for_target(const char* path,=20
+lto_module_is_object_file_for_target(const char* path,
                                      const char* target_triple_prefix);
=20
=20
@@ -103,7 +110,7 @@
  * Checks if a buffer is a loadable object compiled for requested target.
  */
 extern bool
-lto_module_is_object_file_in_memory_for_target(const void* mem, size_t len=
gth,=20
+lto_module_is_object_file_in_memory_for_target(const void* mem, size_t len=
gth,
                                               const char* target_triple_pr=
efix);
=20
=20
@@ -244,6 +251,12 @@
                                int nargs);
=20
 /**
+ * Enables the internalize pass during LTO optimizations.
+ */
+extern void
+lto_codegen_set_whole_program_optimization(lto_code_gen_t cg);
+
+/**
  * Adds to a list of all global symbols that must exist in the final
  * generated code.  If a function is not listed, it might be
  * inlined into every usage and optimized away.
@@ -251,7 +264,6 @@
 extern void
 lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char* symbol=
);
=20
-
 /**
  * Writes a new object file at the specified path that contains the
  * merged contents of all modules added so far.
@@ -260,11 +272,10 @@
 extern bool
 lto_codegen_write_merged_modules(lto_code_gen_t cg, const char* path);
=20
-
 /**
  * Generates code for all added modules into one native object file.
  * On success returns a pointer to a generated mach-o/ELF buffer and
- * length set to the buffer size.  The buffer is owned by the=20
+ * length set to the buffer size.  The buffer is owned by the
  * lto_code_gen_t and will be freed when lto_codegen_dispose()
  * is called, or lto_codegen_compile() is called again.
  * On failure, returns NULL (check lto_get_error_message() for details).
@@ -285,9 +296,13 @@
  */
 extern void
 lto_codegen_debug_options(lto_code_gen_t cg, const char *);
+
 #ifdef __cplusplus
 }
 #endif
=20
+/**
+ * @}
+ */
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/APF=
loat.h
--- a/head/contrib/llvm/include/llvm/ADT/APFloat.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/APFloat.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -320,6 +320,7 @@
     const fltSemantics &getSemantics() const { return *semantics; }
     bool isZero() const { return category =3D=3D fcZero; }
     bool isNonZero() const { return category !=3D fcZero; }
+    bool isNormal() const { return category =3D=3D fcNormal; }
     bool isNaN() const { return category =3D=3D fcNaN; }
     bool isInfinity() const { return category =3D=3D fcInfinity; }
     bool isNegative() const { return sign; }
@@ -328,8 +329,16 @@
=20
     APFloat& operator=3D(const APFloat &);
=20
-    /* Return an arbitrary integer value usable for hashing. */
-    uint32_t getHashValue() const;
+    /// \brief Overload to compute a hash code for an APFloat value.
+    ///
+    /// Note that the use of hash codes for floating point values is in ge=
neral
+    /// frought with peril. Equality is hard to define for these values. F=
or
+    /// example, should negative and positive zero hash to different codes=
? Are
+    /// they equal or not? This hash value implementation specifically
+    /// emphasizes producing different codes for different inputs in order=
 to
+    /// be used in canonicalization and memoization. As such, equality is
+    /// bitwiseIsEqual, and 0 !=3D -0.
+    friend hash_code hash_value(const APFloat &Arg);
=20
     /// Converts this value into a decimal string.
     ///
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/API=
nt.h
--- a/head/contrib/llvm/include/llvm/ADT/APInt.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/include/llvm/ADT/APInt.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -23,11 +23,12 @@
 #include <string>
=20
 namespace llvm {
-  class Serializer;
   class Deserializer;
   class FoldingSetNodeID;
+  class Serializer;
+  class StringRef;
+  class hash_code;
   class raw_ostream;
-  class StringRef;
=20
   template<typename T>
   class SmallVectorImpl;
@@ -497,15 +498,13 @@
     if (loBitsSet =3D=3D APINT_BITS_PER_WORD)
       return APInt(numBits, -1ULL);
     // For small values, return quickly.
-    if (numBits < APINT_BITS_PER_WORD)
-      return APInt(numBits, (1ULL << loBitsSet) - 1);
+    if (loBitsSet <=3D APINT_BITS_PER_WORD)
+      return APInt(numBits, -1ULL >> (APINT_BITS_PER_WORD - loBitsSet));
     return getAllOnesValue(numBits).lshr(numBits - loBitsSet);
   }
=20
-  /// The hash value is computed as the sum of the words and the bit width.
-  /// @returns A hash value computed from the sum of the APInt words.
-  /// @brief Get a hash value based on this APInt
-  uint64_t getHashValue() const;
+  /// \brief Overload to compute a hash_code for an APInt value.
+  friend hash_code hash_value(const APInt &Arg);
=20
   /// This function returns a pointer to the internal storage of the APInt.
   /// This is useful for writing out the APInt in binary form without any
@@ -562,7 +561,15 @@
   /// Performs logical negation operation on this APInt.
   /// @returns true if *this is zero, false otherwise.
   /// @brief Logical negation operator.
-  bool operator!() const;
+  bool operator!() const {
+    if (isSingleWord())
+      return !VAL;
+
+    for (unsigned i =3D 0; i !=3D getNumWords(); ++i)
+      if (pVal[i])
+        return false;
+    return true;
+  }
=20
   /// @}
   /// @name Assignment Operators
@@ -835,7 +842,11 @@
=20
   /// @returns the bit value at bitPosition
   /// @brief Array-indexing support.
-  bool operator[](unsigned bitPosition) const;
+  bool operator[](unsigned bitPosition) const {
+    assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
+    return (maskBit(bitPosition) &
+            (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) !=3D 0;
+  }
=20
   /// @}
   /// @name Comparison Operators
@@ -1056,6 +1067,16 @@
   /// @brief Zero extend or truncate to width
   APInt zextOrTrunc(unsigned width) const;
=20
+  /// Make this APInt have the bit width given by \p width. The value is s=
ign
+  /// extended, or left alone to make it that width.
+  /// @brief Sign extend or truncate to width
+  APInt sextOrSelf(unsigned width) const;
+
+  /// Make this APInt have the bit width given by \p width. The value is z=
ero
+  /// extended, or left alone to make it that width.
+  /// @brief Zero extend or truncate to width
+  APInt zextOrSelf(unsigned width) const;
+
   /// @}
   /// @name Bit Manipulation Operators
   /// @{
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Arr=
ayRef.h
--- a/head/contrib/llvm/include/llvm/ADT/ArrayRef.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/ArrayRef.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,8 +14,7 @@
 #include <vector>
=20
 namespace llvm {
-  class APInt;
- =20
+
   /// ArrayRef - Represent a constant reference to an array (0 or more ele=
ments
   /// consecutively in memory), i.e. a start pointer and a length.  It all=
ows
   /// various APIs to take consecutive elements easily and conveniently.
@@ -33,33 +32,33 @@
     typedef const T *iterator;
     typedef const T *const_iterator;
     typedef size_t size_type;
-   =20
+
   private:
     /// The start of the array, in an external buffer.
     const T *Data;
-   =20
+
     /// The number of elements.
     size_type Length;
-   =20
+
   public:
     /// @name Constructors
     /// @{
-   =20
+
     /// Construct an empty ArrayRef.
     /*implicit*/ ArrayRef() : Data(0), Length(0) {}
-   =20
+
     /// Construct an ArrayRef from a single element.
     /*implicit*/ ArrayRef(const T &OneElt)
       : Data(&OneElt), Length(1) {}
-   =20
+
     /// Construct an ArrayRef from a pointer and length.
     /*implicit*/ ArrayRef(const T *data, size_t length)
       : Data(data), Length(length) {}
-   =20
+
     /// Construct an ArrayRef from a range.
     ArrayRef(const T *begin, const T *end)
       : Data(begin), Length(end - begin) {}
-   =20
+
     /// Construct an ArrayRef from a SmallVector.
     /*implicit*/ ArrayRef(const SmallVectorImpl<T> &Vec)
       : Data(Vec.data()), Length(Vec.size()) {}
@@ -67,39 +66,39 @@
     /// Construct an ArrayRef from a std::vector.
     /*implicit*/ ArrayRef(const std::vector<T> &Vec)
       : Data(Vec.empty() ? (T*)0 : &Vec[0]), Length(Vec.size()) {}
-   =20
+
     /// Construct an ArrayRef from a C array.
     template <size_t N>
     /*implicit*/ ArrayRef(const T (&Arr)[N])
       : Data(Arr), Length(N) {}
-   =20
+
     /// @}
     /// @name Simple Operations
     /// @{
=20
     iterator begin() const { return Data; }
     iterator end() const { return Data + Length; }
-   =20
+
     /// empty - Check if the array is empty.
     bool empty() const { return Length =3D=3D 0; }
-   =20
+
     const T *data() const { return Data; }
-   =20
+
     /// size - Get the array size.
     size_t size() const { return Length; }
-   =20
+
     /// front - Get the first element.
     const T &front() const {
       assert(!empty());
       return Data[0];
     }
-   =20
+
     /// back - Get the last element.
     const T &back() const {
       assert(!empty());
       return Data[Length-1];
     }
-   =20
+
     /// equals - Check for element-wise equality.
     bool equals(ArrayRef RHS) const {
       if (Length !=3D RHS.Length)
@@ -111,18 +110,18 @@
     }
=20
     /// slice(n) - Chop off the first N elements of the array.
-    ArrayRef<T> slice(unsigned N) {
+    ArrayRef<T> slice(unsigned N) const {
       assert(N <=3D size() && "Invalid specifier");
       return ArrayRef<T>(data()+N, size()-N);
     }
=20
     /// slice(n, m) - Chop off the first N elements of the array, and keep=
 M
     /// elements in the array.
-    ArrayRef<T> slice(unsigned N, unsigned M) {
+    ArrayRef<T> slice(unsigned N, unsigned M) const {
       assert(N+M <=3D size() && "Invalid specifier");
       return ArrayRef<T>(data()+N, M);
     }
-   =20
+
     /// @}
     /// @name Operator Overloads
     /// @{
@@ -130,22 +129,104 @@
       assert(Index < Length && "Invalid index!");
       return Data[Index];
     }
-   =20
+
     /// @}
     /// @name Expensive Operations
     /// @{
     std::vector<T> vec() const {
       return std::vector<T>(Data, Data+Length);
     }
-   =20
+
     /// @}
     /// @name Conversion operators
     /// @{
     operator std::vector<T>() const {
       return std::vector<T>(Data, Data+Length);
     }
+
+    /// @}
+  };
+
+  /// MutableArrayRef - Represent a mutable reference to an array (0 or mo=
re
+  /// elements consecutively in memory), i.e. a start pointer and a length=
.  It
+  /// allows various APIs to take and modify consecutive elements easily a=
nd
+  /// conveniently.
+  ///
+  /// This class does not own the underlying data, it is expected to be us=
ed in
+  /// situations where the data resides in some other buffer, whose lifeti=
me
+  /// extends past that of the MutableArrayRef. For this reason, it is not=
 in
+  /// general safe to store a MutableArrayRef.
+  ///
+  /// This is intended to be trivially copyable, so it should be passed by
+  /// value.
+  template<typename T>
+  class MutableArrayRef : public ArrayRef<T> {
+  public:
+    typedef T *iterator;
+
+    /// Construct an empty ArrayRef.
+    /*implicit*/ MutableArrayRef() : ArrayRef<T>() {}
+   =20
+    /// Construct an MutableArrayRef from a single element.
+    /*implicit*/ MutableArrayRef(T &OneElt) : ArrayRef<T>(OneElt) {}
+   =20
+    /// Construct an MutableArrayRef from a pointer and length.
+    /*implicit*/ MutableArrayRef(T *data, size_t length)
+      : ArrayRef<T>(data, length) {}
+   =20
+    /// Construct an MutableArrayRef from a range.
+    MutableArrayRef(T *begin, T *end) : ArrayRef<T>(begin, end) {}
+   =20
+    /// Construct an MutableArrayRef from a SmallVector.
+    /*implicit*/ MutableArrayRef(SmallVectorImpl<T> &Vec)
+    : ArrayRef<T>(Vec) {}
+   =20
+    /// Construct a MutableArrayRef from a std::vector.
+    /*implicit*/ MutableArrayRef(std::vector<T> &Vec)
+    : ArrayRef<T>(Vec) {}
+   =20
+    /// Construct an MutableArrayRef from a C array.
+    template <size_t N>
+    /*implicit*/ MutableArrayRef(T (&Arr)[N])
+      : ArrayRef<T>(Arr) {}
+   =20
+    T *data() const { return const_cast<T*>(ArrayRef<T>::data()); }
+
+    iterator begin() const { return data(); }
+    iterator end() const { return data() + this->size(); }
+   =20
+    /// front - Get the first element.
+    T &front() const {
+      assert(!this->empty());
+      return data()[0];
+    }
+   =20
+    /// back - Get the last element.
+    T &back() const {
+      assert(!this->empty());
+      return data()[this->size()-1];
+    }
+
+    /// slice(n) - Chop off the first N elements of the array.
+    MutableArrayRef<T> slice(unsigned N) const {
+      assert(N <=3D this->size() && "Invalid specifier");
+      return MutableArrayRef<T>(data()+N, this->size()-N);
+    }
+   =20
+    /// slice(n, m) - Chop off the first N elements of the array, and keep=
 M
+    /// elements in the array.
+    MutableArrayRef<T> slice(unsigned N, unsigned M) const {
+      assert(N+M <=3D this->size() && "Invalid specifier");
+      return MutableArrayRef<T>(data()+N, M);
+    }
    =20
     /// @}
+    /// @name Operator Overloads
+    /// @{
+    T &operator[](size_t Index) const {
+      assert(Index < this->size() && "Invalid index!");
+      return data()[Index];
+    }
   };
=20
   /// @name ArrayRef Convenience constructors
@@ -215,5 +296,5 @@
     static const bool value =3D true;
   };
 }
-
+ =20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Bit=
Vector.h
--- a/head/contrib/llvm/include/llvm/ADT/BitVector.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/BitVector.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,12 +14,12 @@
 #ifndef LLVM_ADT_BITVECTOR_H
 #define LLVM_ADT_BITVECTOR_H
=20
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include <algorithm>
 #include <cassert>
 #include <climits>
 #include <cstdlib>
-#include <cstring>
=20
 namespace llvm {
=20
@@ -116,7 +116,7 @@
       else if (sizeof(BitWord) =3D=3D 8)
         NumBits +=3D CountPopulation_64(Bits[i]);
       else
-        assert(0 && "Unsupported!");
+        llvm_unreachable("Unsupported!");
     return NumBits;
   }
=20
@@ -146,10 +146,9 @@
       if (Bits[i] !=3D 0) {
         if (sizeof(BitWord) =3D=3D 4)
           return i * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Bits[i=
]);
-        else if (sizeof(BitWord) =3D=3D 8)
+        if (sizeof(BitWord) =3D=3D 8)
           return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
-        else
-          assert(0 && "Unsupported!");
+        llvm_unreachable("Unsupported!");
       }
     return -1;
   }
@@ -170,10 +169,9 @@
     if (Copy !=3D 0) {
       if (sizeof(BitWord) =3D=3D 4)
         return WordPos * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Co=
py);
-      else if (sizeof(BitWord) =3D=3D 8)
+      if (sizeof(BitWord) =3D=3D 8)
         return WordPos * BITWORD_SIZE + CountTrailingZeros_64(Copy);
-      else
-        assert(0 && "Unsupported!");
+      llvm_unreachable("Unsupported!");
     }
=20
     // Check subsequent words.
@@ -181,10 +179,9 @@
       if (Bits[i] !=3D 0) {
         if (sizeof(BitWord) =3D=3D 4)
           return i * BITWORD_SIZE + CountTrailingZeros_32((uint32_t)Bits[i=
]);
-        else if (sizeof(BitWord) =3D=3D 8)
+        if (sizeof(BitWord) =3D=3D 8)
           return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
-        else
-          assert(0 && "Unsupported!");
+        llvm_unreachable("Unsupported!");
       }
     return -1;
   }
@@ -318,6 +315,16 @@
     return *this;
   }
=20
+  // reset - Reset bits that are set in RHS. Same as *this &=3D ~RHS.
+  BitVector &reset(const BitVector &RHS) {
+    unsigned ThisWords =3D NumBitWords(size());
+    unsigned RHSWords  =3D NumBitWords(RHS.size());
+    unsigned i;
+    for (i =3D 0; i !=3D std::min(ThisWords, RHSWords); ++i)
+      Bits[i] &=3D ~RHS.Bits[i];
+    return *this;
+  }
+
   BitVector &operator|=3D(const BitVector &RHS) {
     if (size() < RHS.size())
       resize(RHS.size());
@@ -365,6 +372,42 @@
     std::swap(Capacity, RHS.Capacity);
   }
=20
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+  // Portable bit mask operations.
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+  //
+  // These methods all operate on arrays of uint32_t, each holding 32 bits=
. The
+  // fixed word size makes it easier to work with literal bit vector const=
ants
+  // in portable code.
+  //
+  // The LSB in each word is the lowest numbered bit.  The size of a porta=
ble
+  // bit mask is always a whole multiple of 32 bits.  If no bit mask size =
is
+  // given, the bit mask is assumed to cover the entire BitVector.
+
+  /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
+  /// This computes "*this |=3D Mask".
+  void setBitsInMask(const uint32_t *Mask, unsigned MaskWords =3D ~0u) {
+    applyMask<true, false>(Mask, MaskWords);
+  }
+
+  /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
+  /// Don't resize. This computes "*this &=3D ~Mask".
+  void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords =3D ~0u) {
+    applyMask<false, false>(Mask, MaskWords);
+  }
+
+  /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mas=
k.
+  /// Don't resize.  This computes "*this |=3D ~Mask".
+  void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords =3D ~0u) {
+    applyMask<true, true>(Mask, MaskWords);
+  }
+
+  /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in=
 Mask.
+  /// Don't resize.  This computes "*this &=3D Mask".
+  void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords =3D ~0u=
) {
+    applyMask<false, true>(Mask, MaskWords);
+  }
+
 private:
   unsigned NumBitWords(unsigned S) const {
     return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
@@ -400,6 +443,33 @@
   void init_words(BitWord *B, unsigned NumWords, bool t) {
     memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
   }
+
+  template<bool AddBits, bool InvertMask>
+  void applyMask(const uint32_t *Mask, unsigned MaskWords) {
+    assert(BITWORD_SIZE % 32 =3D=3D 0 && "Unsupported BitWord size.");
+    MaskWords =3D std::min(MaskWords, (size() + 31) / 32);
+    const unsigned Scale =3D BITWORD_SIZE / 32;
+    unsigned i;
+    for (i =3D 0; MaskWords >=3D Scale; ++i, MaskWords -=3D Scale) {
+      BitWord BW =3D Bits[i];
+      // This inner loop should unroll completely when BITWORD_SIZE > 32.
+      for (unsigned b =3D 0; b !=3D BITWORD_SIZE; b +=3D 32) {
+        uint32_t M =3D *Mask++;
+        if (InvertMask) M =3D ~M;
+        if (AddBits) BW |=3D   BitWord(M) << b;
+        else         BW &=3D ~(BitWord(M) << b);
+      }
+      Bits[i] =3D BW;
+    }
+    for (unsigned b =3D 0; MaskWords; b +=3D 32, --MaskWords) {
+      uint32_t M =3D *Mask++;
+      if (InvertMask) M =3D ~M;
+      if (AddBits) Bits[i] |=3D   BitWord(M) << b;
+      else         Bits[i] &=3D ~(BitWord(M) << b);
+    }
+    if (AddBits)
+      clear_unused_bits();
+  }
 };
=20
 inline BitVector operator&(const BitVector &LHS, const BitVector &RHS) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/DAG=
DeltaAlgorithm.h
--- a/head/contrib/llvm/include/llvm/ADT/DAGDeltaAlgorithm.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/DAGDeltaAlgorithm.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -36,6 +36,7 @@
 /// for more information on the properties which the predicate function it=
self
 /// should satisfy.
 class DAGDeltaAlgorithm {
+  virtual void anchor();
 public:
   typedef unsigned change_ty;
   typedef std::pair<change_ty, change_ty> edge_ty;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Den=
seMap.h
--- a/head/contrib/llvm/include/llvm/ADT/DenseMap.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/DenseMap.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -30,12 +30,11 @@
=20
 template<typename KeyT, typename ValueT,
          typename KeyInfoT =3D DenseMapInfo<KeyT>,
-         typename ValueInfoT =3D DenseMapInfo<ValueT>, bool IsConst =3D fa=
lse>
+         bool IsConst =3D false>
 class DenseMapIterator;
=20
 template<typename KeyT, typename ValueT,
-         typename KeyInfoT =3D DenseMapInfo<KeyT>,
-         typename ValueInfoT =3D DenseMapInfo<ValueT> >
+         typename KeyInfoT =3D DenseMapInfo<KeyT> >
 class DenseMap {
   typedef std::pair<KeyT, ValueT> BucketT;
   unsigned NumBuckets;
@@ -80,19 +79,19 @@
=20
   typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
   typedef DenseMapIterator<KeyT, ValueT,
-                           KeyInfoT, ValueInfoT, true> const_iterator;
+                           KeyInfoT, true> const_iterator;
   inline iterator begin() {
     // When the map is empty, avoid the overhead of AdvancePastEmptyBucket=
s().
     return empty() ? end() : iterator(Buckets, Buckets+NumBuckets);
   }
   inline iterator end() {
-    return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
+    return iterator(Buckets+NumBuckets, Buckets+NumBuckets, true);
   }
   inline const_iterator begin() const {
     return empty() ? end() : const_iterator(Buckets, Buckets+NumBuckets);
   }
   inline const_iterator end() const {
-    return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
+    return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets, true);
   }
=20
   bool empty() const { return NumEntries =3D=3D 0; }
@@ -137,13 +136,33 @@
   iterator find(const KeyT &Val) {
     BucketT *TheBucket;
     if (LookupBucketFor(Val, TheBucket))
-      return iterator(TheBucket, Buckets+NumBuckets);
+      return iterator(TheBucket, Buckets+NumBuckets, true);
     return end();
   }
   const_iterator find(const KeyT &Val) const {
     BucketT *TheBucket;
     if (LookupBucketFor(Val, TheBucket))
-      return const_iterator(TheBucket, Buckets+NumBuckets);
+      return const_iterator(TheBucket, Buckets+NumBuckets, true);
+    return end();
+  }
+
+  /// Alternate version of find() which allows a different, and possibly
+  /// less expensive, key type.
+  /// The DenseMapInfo is responsible for supplying methods
+  /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
+  /// type used.
+  template<class LookupKeyT>
+  iterator find_as(const LookupKeyT &Val) {
+    BucketT *TheBucket;
+    if (LookupBucketFor(Val, TheBucket))
+      return iterator(TheBucket, Buckets+NumBuckets, true);
+    return end();
+  }
+  template<class LookupKeyT>
+  const_iterator find_as(const LookupKeyT &Val) const {
+    BucketT *TheBucket;
+    if (LookupBucketFor(Val, TheBucket))
+      return const_iterator(TheBucket, Buckets+NumBuckets, true);
     return end();
   }
=20
@@ -162,13 +181,12 @@
   std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
     BucketT *TheBucket;
     if (LookupBucketFor(KV.first, TheBucket))
-      return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
+      return std::make_pair(iterator(TheBucket, Buckets+NumBuckets, true),
                             false); // Already in map.
=20
     // Otherwise, insert the new element.
     TheBucket =3D InsertIntoBucket(KV.first, KV.second, TheBucket);
-    return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
-                          true);
+    return std::make_pair(iterator(TheBucket, Buckets+NumBuckets, true), t=
rue);
   }
=20
   /// insert - Range insertion of pairs.
@@ -237,7 +255,7 @@
 private:
   void CopyFrom(const DenseMap& other) {
     if (NumBuckets !=3D 0 &&
-        (!isPodLike<KeyInfoT>::value || !isPodLike<ValueInfoT>::value)) {
+        (!isPodLike<KeyT>::value || !isPodLike<ValueT>::value)) {
       const KeyT EmptyKey =3D getEmptyKey(), TombstoneKey =3D getTombstone=
Key();
       for (BucketT *P =3D Buckets, *E =3D Buckets+NumBuckets; P !=3D E; ++=
P) {
         if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
@@ -266,7 +284,7 @@
=20
     Buckets =3D static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBu=
ckets));
=20
-    if (isPodLike<KeyInfoT>::value && isPodLike<ValueInfoT>::value)
+    if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
       memcpy(Buckets, other.Buckets, NumBuckets * sizeof(BucketT));
     else
       for (size_t i =3D 0; i < NumBuckets; ++i) {
@@ -310,6 +328,10 @@
   static unsigned getHashValue(const KeyT &Val) {
     return KeyInfoT::getHashValue(Val);
   }
+  template<typename LookupKeyT>
+  static unsigned getHashValue(const LookupKeyT &Val) {
+    return KeyInfoT::getHashValue(Val);
+  }
   static const KeyT getEmptyKey() {
     return KeyInfoT::getEmptyKey();
   }
@@ -321,7 +343,8 @@
   /// FoundBucket.  If the bucket contains the key and a value, this retur=
ns
   /// true, otherwise it returns a bucket with an empty marker or tombston=
e and
   /// returns false.
-  bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
+  template<typename LookupKeyT>
+  bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) const=
 {
     unsigned BucketNo =3D getHashValue(Val);
     unsigned ProbeAmt =3D 1;
     BucketT *BucketsPtr =3D Buckets;
@@ -342,7 +365,7 @@
     while (1) {
       BucketT *ThisBucket =3D BucketsPtr + (BucketNo & (NumBuckets-1));
       // Found Val's bucket?  If so, return it.
-      if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
+      if (KeyInfoT::isEqual(Val, ThisBucket->first)) {
         FoundBucket =3D ThisBucket;
         return true;
       }
@@ -478,12 +501,12 @@
 };
=20
 template<typename KeyT, typename ValueT,
-         typename KeyInfoT, typename ValueInfoT, bool IsConst>
+         typename KeyInfoT, bool IsConst>
 class DenseMapIterator {
   typedef std::pair<KeyT, ValueT> Bucket;
   typedef DenseMapIterator<KeyT, ValueT,
-                           KeyInfoT, ValueInfoT, true> ConstIterator;
-  friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, ValueInfoT, true>;
+                           KeyInfoT, true> ConstIterator;
+  friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>;
 public:
   typedef ptrdiff_t difference_type;
   typedef typename conditional<IsConst, const Bucket, Bucket>::type value_=
type;
@@ -495,15 +518,16 @@
 public:
   DenseMapIterator() : Ptr(0), End(0) {}
=20
-  DenseMapIterator(pointer Pos, pointer E) : Ptr(Pos), End(E) {
-    AdvancePastEmptyBuckets();
+  DenseMapIterator(pointer Pos, pointer E, bool NoAdvance =3D false)
+    : Ptr(Pos), End(E) {
+    if (!NoAdvance) AdvancePastEmptyBuckets();
   }
=20
   // If IsConst is true this is a converting constructor from iterator to
   // const_iterator and the default copy constructor is used.
   // Otherwise this is a copy constructor for iterator.
   DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
-                                          KeyInfoT, ValueInfoT, false>& I)
+                                          KeyInfoT, false>& I)
     : Ptr(I.Ptr), End(I.End) {}
=20
   reference operator*() const {
@@ -541,9 +565,9 @@
   }
 };
  =20
-template<typename KeyT, typename ValueT, typename KeyInfoT, typename Value=
InfoT>
+template<typename KeyT, typename ValueT, typename KeyInfoT>
 static inline size_t
-capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT, ValueInfoT> &X) {
+capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
   return X.getMemorySize();
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Den=
seMapInfo.h
--- a/head/contrib/llvm/include/llvm/ADT/DenseMapInfo.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/DenseMapInfo.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -59,7 +59,7 @@
  =20
 // Provide DenseMapInfo for unsigned ints.
 template<> struct DenseMapInfo<unsigned> {
-  static inline unsigned getEmptyKey() { return ~0; }
+  static inline unsigned getEmptyKey() { return ~0U; }
   static inline unsigned getTombstoneKey() { return ~0U - 1; }
   static unsigned getHashValue(const unsigned& Val) { return Val * 37U; }
   static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Fol=
dingSet.h
--- a/head/contrib/llvm/include/llvm/ADT/FoldingSet.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/FoldingSet.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -193,12 +193,11 @@
   virtual void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const =3D 0;
   /// NodeEquals - Instantiations of the FoldingSet template implement
   /// this function to compare the given node with the given ID.
-  virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID,
+  virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned ID=
Hash,
                           FoldingSetNodeID &TempID) const=3D0;
-  /// NodeEquals - Instantiations of the FoldingSet template implement
+  /// ComputeNodeHash - Instantiations of the FoldingSet template implement
   /// this function to compute a hash value for the given node.
-  virtual unsigned ComputeNodeHash(Node *N,
-                                   FoldingSetNodeID &TempID) const =3D 0;
+  virtual unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) cons=
t =3D 0;
 };
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -220,7 +219,7 @@
   // to compute a temporary ID if necessary. The default implementation
   // just calls Profile and does a regular comparison. Implementations
   // can override this to provide more efficient implementations.
-  static inline bool Equals(T &X, const FoldingSetNodeID &ID,
+  static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDH=
ash,
                             FoldingSetNodeID &TempID);
=20
   // ComputeHash - Compute a hash value for X, using TempID to
@@ -249,7 +248,7 @@
   static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context) {
     X.Profile(ID, Context);
   }
-  static inline bool Equals(T &X, const FoldingSetNodeID &ID,
+  static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDH=
ash,
                             FoldingSetNodeID &TempID, Ctx Context);
   static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID,
                                      Ctx Context);
@@ -344,7 +343,7 @@
 template<typename T>
 inline bool
 DefaultFoldingSetTrait<T>::Equals(T &X, const FoldingSetNodeID &ID,
-                                  FoldingSetNodeID &TempID) {
+                                  unsigned IDHash, FoldingSetNodeID &TempI=
D) {
   FoldingSetTrait<T>::Profile(X, TempID);
   return TempID =3D=3D ID;
 }
@@ -358,6 +357,7 @@
 inline bool
 DefaultContextualFoldingSetTrait<T, Ctx>::Equals(T &X,
                                                  const FoldingSetNodeID &I=
D,
+                                                 unsigned IDHash,
                                                  FoldingSetNodeID &TempID,
                                                  Ctx Context) {
   ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
@@ -387,15 +387,14 @@
   }
   /// NodeEquals - Instantiations may optionally provide a way to compare a
   /// node with a specified ID.
-  virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID,
+  virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned ID=
Hash,
                           FoldingSetNodeID &TempID) const {
     T *TN =3D static_cast<T *>(N);
-    return FoldingSetTrait<T>::Equals(*TN, ID, TempID);
+    return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
   }
-  /// NodeEquals - Instantiations may optionally provide a way to compute a
+  /// ComputeNodeHash - Instantiations may optionally provide a way to com=
pute a
   /// hash value directly from a node.
-  virtual unsigned ComputeNodeHash(Node *N,
-                                   FoldingSetNodeID &TempID) const {
+  virtual unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) cons=
t {
     T *TN =3D static_cast<T *>(N);
     return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
   }
@@ -465,10 +464,11 @@
     ContextualFoldingSetTrait<T, Ctx>::Profile(*TN, ID, Context);
   }
   virtual bool NodeEquals(FoldingSetImpl::Node *N,
-                          const FoldingSetNodeID &ID,
+                          const FoldingSetNodeID &ID, unsigned IDHash,
                           FoldingSetNodeID &TempID) const {
     T *TN =3D static_cast<T *>(N);
-    return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, TempID, Cont=
ext);
+    return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, Temp=
ID,
+                                                     Context);
   }
   virtual unsigned ComputeNodeHash(FoldingSetImpl::Node *N,
                                    FoldingSetNodeID &TempID) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Gra=
phTraits.h
--- a/head/contrib/llvm/include/llvm/ADT/GraphTraits.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/GraphTraits.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -43,8 +43,11 @@
   // typedef  ...iterator nodes_iterator;
   // static nodes_iterator nodes_begin(GraphType *G)
   // static nodes_iterator nodes_end  (GraphType *G)
+  //    nodes_iterator/begin/end - Allow iteration over all nodes in the g=
raph
+
+  // static unsigned       size       (GraphType *G)
+  //    Return total number of nodes in the graph
   //
-  //    nodes_iterator/begin/end - Allow iteration over all nodes in the g=
raph
=20
=20
   // If anyone tries to use this class without having an appropriate
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Imm=
utableSet.h
--- a/head/contrib/llvm/include/llvm/ADT/ImmutableSet.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/ImmutableSet.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,6 +18,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cassert>
 #include <functional>
 #include <vector>
@@ -346,7 +347,7 @@
       if (prev)
         prev->next =3D next;
       else
-        factory->Cache[computeDigest()] =3D next;
+        factory->Cache[factory->maskCacheIndex(computeDigest())] =3D next;
     }
    =20
     // We need to clear the mutability bit in case we are
@@ -428,6 +429,11 @@
   TreeTy*         getRight(TreeTy* T) const { return T->getRight(); }
   value_type_ref  getValue(TreeTy* T) const { return T->value; }
=20
+  // Make sure the index is not the Tombstone or Entry key of the DenseMap.
+  static inline unsigned maskCacheIndex(unsigned I) {
+	return (I & ~0x02);
+  }
+
   unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
     unsigned hl =3D getHeight(L);
     unsigned hr =3D getHeight(R);
@@ -610,7 +616,7 @@
     // Search the hashtable for another tree with the same digest, and
     // if find a collision compare those trees by their contents.
     unsigned digest =3D TNew->computeDigest();
-    TreeTy *&entry =3D Cache[digest];
+    TreeTy *&entry =3D Cache[maskCacheIndex(digest)];
     do {
       if (!entry)
         break;
@@ -686,7 +692,7 @@
         stack.back() |=3D VisitedRight;
         break;
       default:
-        assert(false && "Unreachable.");
+        llvm_unreachable("Unreachable.");
     }
   }
=20
@@ -722,7 +728,7 @@
         skipToParent();
         break;
       default:
-        assert(false && "Unreachable.");
+        llvm_unreachable("Unreachable.");
     }
     return *this;
   }
@@ -747,7 +753,7 @@
           stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
         break;
       default:
-        assert(false && "Unreachable.");
+        llvm_unreachable("Unreachable.");
     }
     return *this;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Int=
ervalMap.h
--- a/head/contrib/llvm/include/llvm/ADT/IntervalMap.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/IntervalMap.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -739,7 +739,7 @@
 // A Path is used by iterators to represent a position in a B+-tree, and t=
he
 // path to get there from the root.
 //
-// The Path class also constains the tree navigation code that doesn't hav=
e to
+// The Path class also contains the tree navigation code that doesn't have=
 to
 // be templatized.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1977,7 +1977,7 @@
     CurSize[Nodes] =3D CurSize[NewNode];
     Node[Nodes] =3D Node[NewNode];
     CurSize[NewNode] =3D 0;
-    Node[NewNode] =3D this->map->newNode<NodeT>();
+    Node[NewNode] =3D this->map->template newNode<NodeT>();
     ++Nodes;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Int=
rusiveRefCntPtr.h
--- a/head/contrib/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -46,6 +46,7 @@
=20
   public:
     RefCountedBase() : ref_cnt(0) {}
+    RefCountedBase(const RefCountedBase &) : ref_cnt(0) {}
=20
     void Retain() const { ++ref_cnt; }
     void Release() const {
@@ -64,9 +65,12 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
   class RefCountedBaseVPTR {
     mutable unsigned ref_cnt;
+    virtual void anchor();
=20
   protected:
     RefCountedBaseVPTR() : ref_cnt(0) {}
+    RefCountedBaseVPTR(const RefCountedBaseVPTR &) : ref_cnt(0) {}
+
     virtual ~RefCountedBaseVPTR() {}
=20
     void Retain() const { ++ref_cnt; }
@@ -76,9 +80,15 @@
     }
=20
     template <typename T>
-    friend class IntrusiveRefCntPtr;
+    friend struct IntrusiveRefCntPtrInfo;
   };
=20
+ =20
+  template <typename T> struct IntrusiveRefCntPtrInfo {
+    static void retain(T *obj) { obj->Retain(); }
+    static void release(T *obj) { obj->Release(); }
+  };
+ =20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 /// IntrusiveRefCntPtr - A template class that implements a "smart pointer"
 ///  that assumes the wrapped object has a reference count associated
@@ -105,7 +115,7 @@
=20
     explicit IntrusiveRefCntPtr() : Obj(0) {}
=20
-    explicit IntrusiveRefCntPtr(T* obj) : Obj(obj) {
+    IntrusiveRefCntPtr(T* obj) : Obj(obj) {
       retain();
     }
=20
@@ -153,14 +163,19 @@
       other.Obj =3D Obj;
       Obj =3D tmp;
     }
-   =20
+
+    void reset() {
+      release();
+      Obj =3D 0;
+    }
+
     void resetWithoutRelease() {
       Obj =3D 0;
     }
=20
   private:
-    void retain() { if (Obj) Obj->Retain(); }
-    void release() { if (Obj) Obj->Release(); }
+    void retain() { if (Obj) IntrusiveRefCntPtrInfo<T>::retain(Obj); }
+    void release() { if (Obj) IntrusiveRefCntPtrInfo<T>::release(Obj); }
=20
     void replace(T* S) {
       this_type(S).swap(*this);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Poi=
nterIntPair.h
--- a/head/contrib/llvm/include/llvm/ADT/PointerIntPair.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/PointerIntPair.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -92,10 +92,14 @@
   }
=20
   PointerTy const *getAddrOfPointer() const {
+    return const_cast<PointerIntPair *>(this)->getAddrOfPointer();
+  }
+
+  PointerTy *getAddrOfPointer() {
     assert(Value =3D=3D reinterpret_cast<intptr_t>(getPointer()) &&
            "Can only return the address if IntBits is cleared and "
            "PtrTraits doesn't change the pointer");
-    return reinterpret_cast<PointerTy const *>(&Value);
+    return reinterpret_cast<PointerTy *>(&Value);
   }
=20
   void *getOpaqueValue() const { return reinterpret_cast<void*>(Value); }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Poi=
nterUnion.h
--- a/head/contrib/llvm/include/llvm/ADT/PointerUnion.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/PointerUnion.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -142,16 +142,19 @@
       return T();
     }
=20
-    /// \brief If the union is set to the first pointer type we can get an
-    /// address pointing to it.
-    template <typename T>
-    PT1 const *getAddrOf() const {
+    /// \brief If the union is set to the first pointer type get an address
+    /// pointing to it.
+    PT1 const *getAddrOfPtr1() const {
+      return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
+    }
+
+    /// \brief If the union is set to the first pointer type get an address
+    /// pointing to it.
+    PT1 *getAddrOfPtr1() {
       assert(is<PT1>() && "Val is not the first pointer");
       assert(get<PT1>() =3D=3D Val.getPointer() &&
          "Can't get the address because PointerLikeTypeTraits changes the =
ptr");
-      T const *can_only_get_address_of_first_pointer_type
-                        =3D reinterpret_cast<PT1 const *>(Val.getAddrOfPoi=
nter());
-      return can_only_get_address_of_first_pointer_type;
+      return (PT1 *)Val.getAddrOfPointer();
     }
    =20
     /// Assignment operators - Allow assigning into this union from either
@@ -263,7 +266,7 @@
         ::llvm::PointerUnionTypeSelector<PT1, T, IsInnerUnion,
           ::llvm::PointerUnionTypeSelector<PT2, T, IsInnerUnion, IsPT3 >
                                                                    >::Retu=
rn Ty;
-      return Ty(Val).is<T>();
+      return Ty(Val).template is<T>();
     }
    =20
     /// get<T>() - Return the value of the specified pointer type. If the
@@ -276,7 +279,7 @@
         ::llvm::PointerUnionTypeSelector<PT1, T, IsInnerUnion,
           ::llvm::PointerUnionTypeSelector<PT2, T, IsInnerUnion, IsPT3 >
                                                                    >::Retu=
rn Ty;
-      return Ty(Val).get<T>();
+      return Ty(Val).template get<T>();
     }
    =20
     /// dyn_cast<T>() - If the current value is of the specified pointer t=
ype,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Set=
Vector.h
--- a/head/contrib/llvm/include/llvm/ADT/SetVector.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/SetVector.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -144,6 +144,12 @@
     set_.erase(back());
     vector_.pop_back();
   }
+ =20
+  T pop_back_val() {
+    T Ret =3D back();
+    pop_back();
+    return Ret;
+  }
=20
   bool operator=3D=3D(const SetVector &that) const {
     return vector_ =3D=3D that.vector_;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Sma=
llBitVector.h
--- a/head/contrib/llvm/include/llvm/ADT/SmallBitVector.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/SmallBitVector.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -175,7 +175,7 @@
         return CountPopulation_32(Bits);
       if (sizeof(uintptr_t) * CHAR_BIT =3D=3D 64)
         return CountPopulation_64(Bits);
-      assert(0 && "Unsupported!");
+      llvm_unreachable("Unsupported!");
     }
     return getPointer()->count();
   }
@@ -212,7 +212,7 @@
         return CountTrailingZeros_32(Bits);
       if (sizeof(uintptr_t) * CHAR_BIT =3D=3D 64)
         return CountTrailingZeros_64(Bits);
-      assert(0 && "Unsupported!");
+      llvm_unreachable("Unsupported!");
     }
     return getPointer()->find_first();
   }
@@ -230,7 +230,7 @@
         return CountTrailingZeros_32(Bits);
       if (sizeof(uintptr_t) * CHAR_BIT =3D=3D 64)
         return CountTrailingZeros_64(Bits);
-      assert(0 && "Unsupported!");
+      llvm_unreachable("Unsupported!");
     }
     return getPointer()->find_next(Prev);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Sma=
llPtrSet.h
--- a/head/contrib/llvm/include/llvm/ADT/SmallPtrSet.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/SmallPtrSet.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -137,6 +137,10 @@
=20
   void operator=3D(const SmallPtrSetImpl &RHS);  // DO NOT IMPLEMENT.
 protected:
+  /// swap - Swaps the elements of two sets.
+  /// Note: This method assumes that both sets have the same small size.
+  void swap(SmallPtrSetImpl &RHS);
+
   void CopyFrom(const SmallPtrSetImpl &RHS);
 };
=20
@@ -287,8 +291,20 @@
     return *this;
   }
=20
+  /// swap - Swaps the elements of two sets.
+  void swap(SmallPtrSet<PtrType, SmallSize> &RHS) {
+    SmallPtrSetImpl::swap(RHS);
+  }
 };
=20
 }
=20
+namespace std {
+  /// Implement std::swap in terms of SmallPtrSet swap.
+  template<class T, unsigned N>
+  inline void swap(llvm::SmallPtrSet<T, N> &LHS, llvm::SmallPtrSet<T, N> &=
RHS) {
+    LHS.swap(RHS);
+  }
+}
+
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Sma=
llSet.h
--- a/head/contrib/llvm/include/llvm/ADT/SmallSet.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/SmallSet.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -27,13 +27,13 @@
 ///
 /// Note that this set does not provide a way to iterate over members in t=
he
 /// set.
-template <typename T, unsigned N>
+template <typename T, unsigned N,  typename C =3D std::less<T> >
 class SmallSet {
   /// Use a SmallVector to hold the elements here (even though it will nev=
er
   /// reach its 'large' stage) to avoid calling the default ctors of eleme=
nts
   /// we will never use.
   SmallVector<T, N> Vector;
-  std::set<T> Set;
+  std::set<T, C> Set;
   typedef typename SmallVector<T, N>::const_iterator VIterator;
   typedef typename SmallVector<T, N>::iterator mutable_iterator;
 public:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Sma=
llString.h
--- a/head/contrib/llvm/include/llvm/ADT/SmallString.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/SmallString.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -24,21 +24,244 @@
 template<unsigned InternalLen>
 class SmallString : public SmallVector<char, InternalLen> {
 public:
-  // Default ctor - Initialize to empty.
+  /// Default ctor - Initialize to empty.
   SmallString() {}
=20
-  // Initialize from a StringRef.
+  /// Initialize from a StringRef.
   SmallString(StringRef S) : SmallVector<char, InternalLen>(S.begin(), S.e=
nd()) {}
=20
-  // Initialize with a range.
+  /// Initialize with a range.
   template<typename ItTy>
   SmallString(ItTy S, ItTy E) : SmallVector<char, InternalLen>(S, E) {}
=20
-  // Copy ctor.
+  /// Copy ctor.
   SmallString(const SmallString &RHS) : SmallVector<char, InternalLen>(RHS=
) {}
=20
+  // Note that in order to add new overloads for append & assign, we have =
to
+  // duplicate the inherited versions so as not to inadvertently hide them.
+
+  /// @}
+  /// @name String Assignment
+  /// @{
+
+  /// Assign from a repeated element
+  void assign(unsigned NumElts, char Elt) {
+    this->SmallVectorImpl<char>::assign(NumElts, Elt);
+  }
+
+  /// Assign from an iterator pair
+  template<typename in_iter>
+  void assign(in_iter S, in_iter E) {
+    this->clear();
+    SmallVectorImpl<char>::append(S, E);
+  }
+
+  /// Assign from a StringRef
+  void assign(StringRef RHS) {
+    this->clear();
+    SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+  }
+
+  /// Assign from a SmallVector
+  void assign(const SmallVectorImpl<char> &RHS) {
+    this->clear();
+    SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+  }
+
+  /// @}
+  /// @name String Concatenation
+  /// @{
+
+  /// Append from an iterator pair
+  template<typename in_iter>
+  void append(in_iter S, in_iter E) {
+    SmallVectorImpl<char>::append(S, E);
+  }
+
+  /// Append from a StringRef
+  void append(StringRef RHS) {
+    SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+  }
+
+  /// Append from a SmallVector
+  void append(const SmallVectorImpl<char> &RHS) {
+    SmallVectorImpl<char>::append(RHS.begin(), RHS.end());
+  }
+
+  /// @}
+  /// @name String Comparison
+  /// @{
+
+  /// equals - Check for string equality, this is more efficient than
+  /// compare() when the relative ordering of inequal strings isn't needed.
+  bool equals(StringRef RHS) const {
+    return str().equals(RHS);
+  }
+
+  /// equals_lower - Check for string equality, ignoring case.
+  bool equals_lower(StringRef RHS) const {
+    return str().equals_lower(RHS);
+  }
+
+  /// compare - Compare two strings; the result is -1, 0, or 1 if this str=
ing
+  /// is lexicographically less than, equal to, or greater than the \arg R=
HS.
+  int compare(StringRef RHS) const {
+    return str().compare(RHS);
+  }
+
+  /// compare_lower - Compare two strings, ignoring case.
+  int compare_lower(StringRef RHS) const {
+    return str().compare_lower(RHS);
+  }
+
+  /// compare_numeric - Compare two strings, treating sequences of digits =
as
+  /// numbers.
+  int compare_numeric(StringRef RHS) const {
+    return str().compare_numeric(RHS);
+  }
+
+  /// @}
+  /// @name String Predicates
+  /// @{
+
+  /// startswith - Check if this string starts with the given \arg Prefix.
+  bool startswith(StringRef Prefix) const {
+    return str().startswith(Prefix);
+  }
+
+  /// endswith - Check if this string ends with the given \arg Suffix.
+  bool endswith(StringRef Suffix) const {
+    return str().endswith(Suffix);
+  }
+
+  /// @}
+  /// @name String Searching
+  /// @{
+
+  /// find - Search for the first character \arg C in the string.
+  ///
+  /// \return - The index of the first occurrence of \arg C, or npos if not
+  /// found.
+  size_t find(char C, size_t From =3D 0) const {
+    return str().find(C, From);
+  }
+
+  /// find - Search for the first string \arg Str in the string.
+  ///
+  /// \return - The index of the first occurrence of \arg Str, or npos if =
not
+  /// found.
+  size_t find(StringRef Str, size_t From =3D 0) const {
+    return str().find(Str, From);
+  }
+
+  /// rfind - Search for the last character \arg C in the string.
+  ///
+  /// \return - The index of the last occurrence of \arg C, or npos if not
+  /// found.
+  size_t rfind(char C, size_t From =3D StringRef::npos) const {
+    return str().rfind(C, From);
+  }
+
+  /// rfind - Search for the last string \arg Str in the string.
+  ///
+  /// \return - The index of the last occurrence of \arg Str, or npos if n=
ot
+  /// found.
+  size_t rfind(StringRef Str) const {
+    return str().rfind(Str);
+  }
+
+  /// find_first_of - Find the first character in the string that is \arg =
C,
+  /// or npos if not found. Same as find.
+  size_t find_first_of(char C, size_t From =3D 0) const {
+    return str().find_first_of(C, From);
+  }
+
+  /// find_first_of - Find the first character in the string that is in \a=
rg
+  /// Chars, or npos if not found.
+  ///
+  /// Note: O(size() + Chars.size())
+  size_t find_first_of(StringRef Chars, size_t From =3D 0) const {
+    return str().find_first_of(Chars, From);
+  }
+
+  /// find_first_not_of - Find the first character in the string that is n=
ot
+  /// \arg C or npos if not found.
+  size_t find_first_not_of(char C, size_t From =3D 0) const {
+    return str().find_first_not_of(C, From);
+  }
+
+  /// find_first_not_of - Find the first character in the string that is n=
ot
+  /// in the string \arg Chars, or npos if not found.
+  ///
+  /// Note: O(size() + Chars.size())
+  size_t find_first_not_of(StringRef Chars, size_t From =3D 0) const {
+    return str().find_first_not_of(Chars, From);
+  }
+
+  /// find_last_of - Find the last character in the string that is \arg C,=
 or
+  /// npos if not found.
+  size_t find_last_of(char C, size_t From =3D StringRef::npos) const {
+    return str().find_last_of(C, From);
+  }
+
+  /// find_last_of - Find the last character in the string that is in \arg=
 C,
+  /// or npos if not found.
+  ///
+  /// Note: O(size() + Chars.size())
+  size_t find_last_of(
+      StringRef Chars, size_t From =3D StringRef::npos) const {
+    return str().find_last_of(Chars, From);
+  }
+
+  /// @}
+  /// @name Helpful Algorithms
+  /// @{
+
+  /// count - Return the number of occurrences of \arg C in the string.
+  size_t count(char C) const {
+    return str().count(C);
+  }
+
+  /// count - Return the number of non-overlapped occurrences of \arg Str =
in
+  /// the string.
+  size_t count(StringRef Str) const {
+    return str().count(Str);
+  }
+
+  /// @}
+  /// @name Substring Operations
+  /// @{
+
+  /// substr - Return a reference to the substring from [Start, Start + N).
+  ///
+  /// \param Start - The index of the starting character in the substring;=
 if
+  /// the index is npos or greater than the length of the string then the
+  /// empty substring will be returned.
+  ///
+  /// \param N - The number of characters to included in the substring. If=
 N
+  /// exceeds the number of characters remaining in the string, the string
+  /// suffix (starting with \arg Start) will be returned.
+  StringRef substr(size_t Start, size_t N =3D StringRef::npos) const {
+    return str().substr(Start, N);
+  }
+
+  /// slice - Return a reference to the substring from [Start, End).
+  ///
+  /// \param Start - The index of the starting character in the substring;=
 if
+  /// the index is npos or greater than the length of the string then the
+  /// empty substring will be returned.
+  ///
+  /// \param End - The index following the last character to include in the
+  /// substring. If this is npos, or less than \arg Start, or exceeds the
+  /// number of characters remaining in the string, the string suffix
+  /// (starting with \arg Start) will be returned.
+  StringRef slice(size_t Start, size_t End) const {
+    return str().slice(Start, End);
+  }
=20
   // Extra methods.
+
+  /// Explicit conversion to StringRef
   StringRef str() const { return StringRef(this->begin(), this->size()); }
=20
   // TODO: Make this const, if it's safe...
@@ -48,7 +271,7 @@
     return this->data();
   }
=20
-  // Implicit conversion to StringRef.
+  /// Implicit conversion to StringRef.
   operator StringRef() const { return str(); }
=20
   // Extra operators.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Sma=
llVector.h
--- a/head/contrib/llvm/include/llvm/ADT/SmallVector.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/SmallVector.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -23,30 +23,6 @@
 #include <iterator>
 #include <memory>
=20
-#ifdef _MSC_VER
-namespace std {
-#if _MSC_VER <=3D 1310
-  // Work around flawed VC++ implementation of std::uninitialized_copy.  D=
efine
-  // additional overloads so that elements with pointer types are recogniz=
ed as
-  // scalars and not objects, causing bizarre type conversion errors.
-  template<class T1, class T2>
-  inline _Scalar_ptr_iterator_tag _Ptr_cat(T1 **, T2 **) {
-    _Scalar_ptr_iterator_tag _Cat;
-    return _Cat;
-  }
-
-  template<class T1, class T2>
-  inline _Scalar_ptr_iterator_tag _Ptr_cat(T1* const *, T2 **) {
-    _Scalar_ptr_iterator_tag _Cat;
-    return _Cat;
-  }
-#else
-// FIXME: It is not clear if the problem is fixed in VS 2005.  What is cle=
ar
-// is that the above hack won't work if it wasn't fixed.
-#endif
-}
-#endif
-
 namespace llvm {
=20
 /// SmallVectorBase - This is all the non-templated stuff common to all
@@ -100,10 +76,10 @@
 template <typename T>
 class SmallVectorTemplateCommon : public SmallVectorBase {
 protected:
+  SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
+
   void setEnd(T *P) { this->EndX =3D P; }
 public:
-  SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {}
-
   typedef size_t size_type;
   typedef ptrdiff_t difference_type;
   typedef T value_type;
@@ -174,7 +150,7 @@
 /// implementations that are designed to work with non-POD-like T's.
 template <typename T, bool isPodLike>
 class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
-public:
+protected:
   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size=
) {}
=20
   static void destroy_range(T *S, T *E) {
@@ -194,6 +170,23 @@
   /// grow - double the size of the allocated memory, guaranteeing space f=
or at
   /// least one more element or MinSize if specified.
   void grow(size_t MinSize =3D 0);
+ =20
+public:
+  void push_back(const T &Elt) {
+    if (this->EndX < this->CapacityX) {
+    Retry:
+      new (this->end()) T(Elt);
+      this->setEnd(this->end()+1);
+      return;
+    }
+    this->grow();
+    goto Retry;
+  }
+ =20
+  void pop_back() {
+    this->setEnd(this->end()-1);
+    this->end()->~T();
+  }
 };
=20
 // Define this out-of-line to dissuade the C++ compiler from inlining it.
@@ -226,7 +219,7 @@
 /// implementations that are designed to work with POD-like T's.
 template <typename T>
 class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<=
T> {
-public:
+protected:
   SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size=
) {}
=20
   // No need to do a destroy loop for POD's.
@@ -255,6 +248,21 @@
   void grow(size_t MinSize =3D 0) {
     this->grow_pod(MinSize*sizeof(T), sizeof(T));
   }
+public:
+  void push_back(const T &Elt) {
+    if (this->EndX < this->CapacityX) {
+    Retry:
+      *this->end() =3D Elt;
+      this->setEnd(this->end()+1);
+      return;
+    }
+    this->grow();
+    goto Retry;
+  }
+ =20
+  void pop_back() {
+    this->setEnd(this->end()-1);
+  }
 };
=20
=20
@@ -270,11 +278,13 @@
   typedef typename SuperClass::iterator iterator;
   typedef typename SuperClass::size_type size_type;
=20
+protected:
   // Default ctor - Initialize to empty.
   explicit SmallVectorImpl(unsigned N)
     : SmallVectorTemplateBase<T, isPodLike<T>::value>(N*sizeof(T)) {
   }
=20
+public:
   ~SmallVectorImpl() {
     // Destroy the constructed elements in the vector.
     this->destroy_range(this->begin(), this->end());
@@ -297,7 +307,7 @@
     } else if (N > this->size()) {
       if (this->capacity() < N)
         this->grow(N);
-      this->construct_range(this->end(), this->begin()+N, T());
+      std::uninitialized_fill(this->end(), this->begin()+N, T());
       this->setEnd(this->begin()+N);
     }
   }
@@ -309,7 +319,7 @@
     } else if (N > this->size()) {
       if (this->capacity() < N)
         this->grow(N);
-      construct_range(this->end(), this->begin()+N, NV);
+      std::uninitialized_fill(this->end(), this->begin()+N, NV);
       this->setEnd(this->begin()+N);
     }
   }
@@ -319,25 +329,9 @@
       this->grow(N);
   }
=20
-  void push_back(const T &Elt) {
-    if (this->EndX < this->CapacityX) {
-    Retry:
-      new (this->end()) T(Elt);
-      this->setEnd(this->end()+1);
-      return;
-    }
-    this->grow();
-    goto Retry;
-  }
-
-  void pop_back() {
-    this->setEnd(this->end()-1);
-    this->end()->~T();
-  }
-
   T pop_back_val() {
     T Result =3D this->back();
-    pop_back();
+    this->pop_back();
     return Result;
   }
=20
@@ -376,7 +370,7 @@
     if (this->capacity() < NumElts)
       this->grow(NumElts);
     this->setEnd(this->begin()+NumElts);
-    construct_range(this->begin(), this->end(), Elt);
+    std::uninitialized_fill(this->begin(), this->end(), Elt);
   }
=20
   iterator erase(iterator I) {
@@ -384,7 +378,7 @@
     // Shift all elts down one.
     std::copy(I+1, this->end(), I);
     // Drop the last elt.
-    pop_back();
+    this->pop_back();
     return(N);
   }
=20
@@ -400,7 +394,7 @@
=20
   iterator insert(iterator I, const T &Elt) {
     if (I =3D=3D this->end()) {  // Important special case for empty vecto=
r.
-      push_back(Elt);
+      this->push_back(Elt);
       return this->end()-1;
     }
=20
@@ -554,12 +548,6 @@
     assert(N <=3D this->capacity());
     this->setEnd(this->begin() + N);
   }
-
-private:
-  static void construct_range(T *S, T *E, const T &Elt) {
-    for (; S !=3D E; ++S)
-      new (S) T(Elt);
-  }
 };
=20
=20
@@ -686,9 +674,7 @@
=20
   explicit SmallVector(unsigned Size, const T &Value =3D T())
     : SmallVectorImpl<T>(NumTsAvailable) {
-    this->reserve(Size);
-    while (Size--)
-      this->push_back(Value);
+    this->assign(Size, Value);
   }
=20
   template<typename ItTy>
@@ -718,9 +704,7 @@
=20
   explicit SmallVector(unsigned Size, const T &Value =3D T())
     : SmallVectorImpl<T>(0) {
-    this->reserve(Size);
-    while (Size--)
-      this->push_back(Value);
+    this->assign(Size, Value);
   }
=20
   template<typename ItTy>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Spa=
rseBitVector.h
--- a/head/contrib/llvm/include/llvm/ADT/SparseBitVector.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/SparseBitVector.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -18,11 +18,11 @@
 #include "llvm/ADT/ilist.h"
 #include "llvm/ADT/ilist_node.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include <cassert>
 #include <climits>
-#include <cstring>
=20
 namespace llvm {
=20
@@ -128,7 +128,7 @@
       else if (sizeof(BitWord) =3D=3D 8)
         NumBits +=3D CountPopulation_64(Bits[i]);
       else
-        assert(0 && "Unsupported!");
+        llvm_unreachable("Unsupported!");
     return NumBits;
   }
=20
@@ -138,13 +138,11 @@
       if (Bits[i] !=3D 0) {
         if (sizeof(BitWord) =3D=3D 4)
           return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
-        else if (sizeof(BitWord) =3D=3D 8)
+        if (sizeof(BitWord) =3D=3D 8)
           return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
-        else
-          assert(0 && "Unsupported!");
+        llvm_unreachable("Unsupported!");
       }
-    assert(0 && "Illegal empty element");
-    return 0; // Not reached
+    llvm_unreachable("Illegal empty element");
   }
=20
   /// find_next - Returns the index of the next set bit starting from the
@@ -165,10 +163,9 @@
     if (Copy !=3D 0) {
       if (sizeof(BitWord) =3D=3D 4)
         return WordPos * BITWORD_SIZE + CountTrailingZeros_32(Copy);
-      else if (sizeof(BitWord) =3D=3D 8)
+      if (sizeof(BitWord) =3D=3D 8)
         return WordPos * BITWORD_SIZE + CountTrailingZeros_64(Copy);
-      else
-        assert(0 && "Unsupported!");
+      llvm_unreachable("Unsupported!");
     }
=20
     // Check subsequent words.
@@ -176,10 +173,9 @@
       if (Bits[i] !=3D 0) {
         if (sizeof(BitWord) =3D=3D 4)
           return i * BITWORD_SIZE + CountTrailingZeros_32(Bits[i]);
-        else if (sizeof(BitWord) =3D=3D 8)
+        if (sizeof(BitWord) =3D=3D 8)
           return i * BITWORD_SIZE + CountTrailingZeros_64(Bits[i]);
-        else
-          assert(0 && "Unsupported!");
+        llvm_unreachable("Unsupported!");
       }
     return -1;
   }
@@ -264,15 +260,6 @@
     }
     BecameZero =3D allzero;
   }
-
-  // Get a hash value for this element;
-  uint64_t getHashValue() const {
-    uint64_t HashVal =3D 0;
-    for (unsigned i =3D 0; i < BITWORDS_PER_ELEMENT; ++i) {
-      HashVal ^=3D Bits[i];
-    }
-    return HashVal;
-  }
 };
=20
 template <unsigned ElementSize =3D 128>
@@ -813,18 +800,6 @@
   iterator end() const {
     return iterator(this, true);
   }
-
-  // Get a hash value for this bitmap.
-  uint64_t getHashValue() const {
-    uint64_t HashVal =3D 0;
-    for (ElementListConstIter Iter =3D Elements.begin();
-         Iter !=3D Elements.end();
-         ++Iter) {
-      HashVal ^=3D Iter->index();
-      HashVal ^=3D Iter->getHashValue();
-    }
-    return HashVal;
-  }
 };
=20
 // Convenience functions to allow Or and And without dereferencing in the =
user
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Sta=
tistic.h
--- a/head/contrib/llvm/include/llvm/ADT/Statistic.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/Statistic.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -27,6 +27,7 @@
 #define LLVM_ADT_STATISTIC_H
=20
 #include "llvm/Support/Atomic.h"
+#include "llvm/Support/Valgrind.h"
=20
 namespace llvm {
 class raw_ostream;
@@ -110,6 +111,7 @@
     bool tmp =3D Initialized;
     sys::MemoryFence();
     if (!tmp) RegisterStatistic();
+    TsanHappensAfter(this);
     return *this;
   }
   void RegisterStatistic();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Str=
ingExtras.h
--- a/head/contrib/llvm/include/llvm/ADT/StringExtras.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/StringExtras.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,12 +15,7 @@
 #define LLVM_ADT_STRINGEXTRAS_H
=20
 #include "llvm/Support/DataTypes.h"
-#include "llvm/ADT/APFloat.h"
-#include "llvm/ADT/DenseMapInfo.h"
 #include "llvm/ADT/StringRef.h"
-#include <cctype>
-#include <cstdio>
-#include <string>
=20
 namespace llvm {
 template<typename T> class SmallVectorImpl;
@@ -101,38 +96,6 @@
     return utostr(static_cast<uint64_t>(X));
 }
=20
-static inline std::string ftostr(double V) {
-  char Buffer[200];
-  sprintf(Buffer, "%20.6e", V);
-  char *B =3D Buffer;
-  while (*B =3D=3D ' ') ++B;
-  return B;
-}
-
-static inline std::string ftostr(const APFloat& V) {
-  if (&V.getSemantics() =3D=3D &APFloat::IEEEdouble)
-    return ftostr(V.convertToDouble());
-  else if (&V.getSemantics() =3D=3D &APFloat::IEEEsingle)
-    return ftostr((double)V.convertToFloat());
-  return "<unknown format in ftostr>"; // error
-}
-
-static inline std::string LowercaseString(const std::string &S) {
-  std::string result(S);
-  for (unsigned i =3D 0; i < S.length(); ++i)
-    if (isupper(result[i]))
-      result[i] =3D char(tolower(result[i]));
-  return result;
-}
-
-static inline std::string UppercaseString(const std::string &S) {
-  std::string result(S);
-  for (unsigned i =3D 0; i < S.length(); ++i)
-    if (islower(result[i]))
-      result[i] =3D char(toupper(result[i]));
-  return result;
-}
-
 /// StrInStrNoCase - Portable version of strcasestr.  Locates the first
 /// occurrence of string 's1' in string 's2', ignoring case.  Returns
 /// the offset of s2 in s1 or npos if s2 cannot be found.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Str=
ingMap.h
--- a/head/contrib/llvm/include/llvm/ADT/StringMap.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/StringMap.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -51,20 +51,11 @@
 /// StringMapImpl - This is the base class of StringMap that is shared amo=
ng
 /// all of its instantiations.
 class StringMapImpl {
-public:
-  /// ItemBucket - The hash table consists of an array of these.  If Item =
is
-  /// non-null, this is an extant entry, otherwise, it is a hole.
-  struct ItemBucket {
-    /// FullHashValue - This remembers the full hash value of the key for
-    /// easy scanning.
-    unsigned FullHashValue;
-
-    /// Item - This is a pointer to the actual item object.
-    StringMapEntryBase *Item;
-  };
-
 protected:
-  ItemBucket *TheTable;
+  // Array of NumBuckets pointers to entries, null pointers are holes.
+  // TheTable[NumBuckets] contains a sentinel value for easy iteration. Fo=
llwed
+  // by an array of the actual hash values as unsigned integers.
+  StringMapEntryBase **TheTable;
   unsigned NumBuckets;
   unsigned NumItems;
   unsigned NumTombstones;
@@ -238,8 +229,9 @@
 template<typename ValueTy, typename AllocatorTy =3D MallocAllocator>
 class StringMap : public StringMapImpl {
   AllocatorTy Allocator;
+public:
   typedef StringMapEntry<ValueTy> MapEntryTy;
-public:
+ =20
   StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
   explicit StringMap(unsigned InitialSize)
     : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))=
) {}
@@ -289,13 +281,13 @@
   iterator find(StringRef Key) {
     int Bucket =3D FindKey(Key);
     if (Bucket =3D=3D -1) return end();
-    return iterator(TheTable+Bucket);
+    return iterator(TheTable+Bucket, true);
   }
=20
   const_iterator find(StringRef Key) const {
     int Bucket =3D FindKey(Key);
     if (Bucket =3D=3D -1) return end();
-    return const_iterator(TheTable+Bucket);
+    return const_iterator(TheTable+Bucket, true);
   }
=20
    /// lookup - Return the entry for the specified key, or a default
@@ -320,13 +312,13 @@
   /// insert it and return true.
   bool insert(MapEntryTy *KeyValue) {
     unsigned BucketNo =3D LookupBucketFor(KeyValue->getKey());
-    ItemBucket &Bucket =3D TheTable[BucketNo];
-    if (Bucket.Item && Bucket.Item !=3D getTombstoneVal())
+    StringMapEntryBase *&Bucket =3D TheTable[BucketNo];
+    if (Bucket && Bucket !=3D getTombstoneVal())
       return false;  // Already exists in map.
=20
-    if (Bucket.Item =3D=3D getTombstoneVal())
+    if (Bucket =3D=3D getTombstoneVal())
       --NumTombstones;
-    Bucket.Item =3D KeyValue;
+    Bucket =3D KeyValue;
     ++NumItems;
     assert(NumItems + NumTombstones <=3D NumBuckets);
=20
@@ -340,10 +332,11 @@
=20
     // Zap all values, resetting the keys back to non-present (not tombsto=
ne),
     // which is safe because we're removing all elements.
-    for (ItemBucket *I =3D TheTable, *E =3D TheTable+NumBuckets; I !=3D E;=
 ++I) {
-      if (I->Item && I->Item !=3D getTombstoneVal()) {
-        static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
-        I->Item =3D 0;
+    for (unsigned I =3D 0, E =3D NumBuckets; I !=3D E; ++I) {
+      StringMapEntryBase *&Bucket =3D TheTable[I];
+      if (Bucket && Bucket !=3D getTombstoneVal()) {
+        static_cast<MapEntryTy*>(Bucket)->Destroy(Allocator);
+        Bucket =3D 0;
       }
     }
=20
@@ -357,21 +350,21 @@
   template <typename InitTy>
   MapEntryTy &GetOrCreateValue(StringRef Key, InitTy Val) {
     unsigned BucketNo =3D LookupBucketFor(Key);
-    ItemBucket &Bucket =3D TheTable[BucketNo];
-    if (Bucket.Item && Bucket.Item !=3D getTombstoneVal())
-      return *static_cast<MapEntryTy*>(Bucket.Item);
+    StringMapEntryBase *&Bucket =3D TheTable[BucketNo];
+    if (Bucket && Bucket !=3D getTombstoneVal())
+      return *static_cast<MapEntryTy*>(Bucket);
=20
     MapEntryTy *NewItem =3D
       MapEntryTy::Create(Key.begin(), Key.end(), Allocator, Val);
=20
-    if (Bucket.Item =3D=3D getTombstoneVal())
+    if (Bucket =3D=3D getTombstoneVal())
       --NumTombstones;
     ++NumItems;
     assert(NumItems + NumTombstones <=3D NumBuckets);
=20
     // Fill in the bucket for the hash table.  The FullHashValue was alrea=
dy
     // filled in by LookupBucketFor.
-    Bucket.Item =3D NewItem;
+    Bucket =3D NewItem;
=20
     RehashTable();
     return *NewItem;
@@ -410,21 +403,21 @@
 template<typename ValueTy>
 class StringMapConstIterator {
 protected:
-  StringMapImpl::ItemBucket *Ptr;
+  StringMapEntryBase **Ptr;
 public:
   typedef StringMapEntry<ValueTy> value_type;
=20
-  explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
+  explicit StringMapConstIterator(StringMapEntryBase **Bucket,
                                   bool NoAdvance =3D false)
   : Ptr(Bucket) {
     if (!NoAdvance) AdvancePastEmptyBuckets();
   }
=20
   const value_type &operator*() const {
-    return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
+    return *static_cast<StringMapEntry<ValueTy>*>(*Ptr);
   }
   const value_type *operator->() const {
-    return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
+    return static_cast<StringMapEntry<ValueTy>*>(*Ptr);
   }
=20
   bool operator=3D=3D(const StringMapConstIterator &RHS) const {
@@ -445,7 +438,7 @@
=20
 private:
   void AdvancePastEmptyBuckets() {
-    while (Ptr->Item =3D=3D 0 || Ptr->Item =3D=3D StringMapImpl::getTombst=
oneVal())
+    while (*Ptr =3D=3D 0 || *Ptr =3D=3D StringMapImpl::getTombstoneVal())
       ++Ptr;
   }
 };
@@ -453,15 +446,15 @@
 template<typename ValueTy>
 class StringMapIterator : public StringMapConstIterator<ValueTy> {
 public:
-  explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
+  explicit StringMapIterator(StringMapEntryBase **Bucket,
                              bool NoAdvance =3D false)
     : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
   }
   StringMapEntry<ValueTy> &operator*() const {
-    return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
+    return *static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
   }
   StringMapEntry<ValueTy> *operator->() const {
-    return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
+    return static_cast<StringMapEntry<ValueTy>*>(*this->Ptr);
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Str=
ingRef.h
--- a/head/contrib/llvm/include/llvm/ADT/StringRef.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/StringRef.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -10,15 +10,26 @@
 #ifndef LLVM_ADT_STRINGREF_H
 #define LLVM_ADT_STRINGREF_H
=20
+#include "llvm/Support/type_traits.h"
+
 #include <cassert>
 #include <cstring>
+#include <limits>
+#include <string>
 #include <utility>
-#include <string>
=20
 namespace llvm {
   template<typename T>
   class SmallVectorImpl;
   class APInt;
+  class hash_code;
+  class StringRef;
+
+  /// Helper functions for StringRef::getAsInteger.
+  bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
+                            unsigned long long &Result);
+
+  bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result=
);
=20
   /// StringRef - Represent a constant reference to a string, i.e. a chara=
cter
   /// array and a length, which need not be null terminated.
@@ -304,14 +315,29 @@
     ///
     /// If the string is invalid or if only a subset of the string is vali=
d,
     /// this returns true to signify the error.  The string is considered
-    /// erroneous if empty.
+    /// erroneous if empty or if it overflows T.
     ///
-    bool getAsInteger(unsigned Radix, long long &Result) const;
-    bool getAsInteger(unsigned Radix, unsigned long long &Result) const;
-    bool getAsInteger(unsigned Radix, int &Result) const;
-    bool getAsInteger(unsigned Radix, unsigned &Result) const;
+    template <typename T>
+    typename enable_if_c<std::numeric_limits<T>::is_signed, bool>::type
+    getAsInteger(unsigned Radix, T &Result) const {
+      long long LLVal;
+      if (getAsSignedInteger(*this, Radix, LLVal) ||
+            static_cast<T>(LLVal) !=3D LLVal)
+        return true;
+      Result =3D LLVal;
+      return false;
+    }
=20
-    // TODO: Provide overloads for int/unsigned that check for overflow.
+    template <typename T>
+    typename enable_if_c<!std::numeric_limits<T>::is_signed, bool>::type
+    getAsInteger(unsigned Radix, T &Result) const {
+      unsigned long long ULLVal;
+      if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
+            static_cast<T>(ULLVal) !=3D ULLVal)
+        return true;
+      Result =3D ULLVal;
+      return false;
+    }
=20
     /// getAsInteger - Parse the current string as an integer of the
     /// specified radix, or of an autosensed radix if the radix given
@@ -327,6 +353,16 @@
     bool getAsInteger(unsigned Radix, APInt &Result) const;
=20
     /// @}
+    /// @name String Operations
+    /// @{
+
+    // lower - Convert the given ASCII string to lowercase.
+    std::string lower() const;
+
+    /// upper - Convert the given ASCII string to uppercase.
+    std::string upper() const;
+
+    /// @}
     /// @name Substring Operations
     /// @{
=20
@@ -343,6 +379,20 @@
       Start =3D min(Start, Length);
       return StringRef(Data + Start, min(N, Length - Start));
     }
+   =20
+    /// drop_front - Return a StringRef equal to 'this' but with the first
+    /// elements dropped.
+    StringRef drop_front(unsigned N =3D 1) const {
+      assert(size() >=3D N && "Dropping more elements than exist");
+      return substr(N);
+    }
+
+    /// drop_back - Return a StringRef equal to 'this' but with the last
+    /// elements dropped.
+    StringRef drop_back(unsigned N =3D 1) const {
+      assert(size() >=3D N && "Dropping more elements than exist");
+      return substr(0, size()-N);
+    }
=20
     /// slice - Return a reference to the substring from [Start, End).
     ///
@@ -466,6 +516,9 @@
=20
   /// @}
=20
+  /// \brief Compute a hash_code for a StringRef.
+  hash_code hash_value(StringRef S);
+
   // StringRefs can be treated like a POD type.
   template <typename T> struct isPodLike;
   template <> struct isPodLike<StringRef> { static const bool value =3D tr=
ue; };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Tin=
yPtrVector.h
--- a/head/contrib/llvm/include/llvm/ADT/TinyPtrVector.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/TinyPtrVector.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -37,6 +37,15 @@
       delete V;
   }
  =20
+  // implicit conversion operator to ArrayRef.
+  operator ArrayRef<EltTy>() const {
+    if (Val.isNull())
+      return ArrayRef<EltTy>();
+    if (Val.template is<EltTy>())
+      return *Val.getAddrOfPtr1();
+    return *Val.template get<VecTy*>();
+  }
+ =20
   bool empty() const {
     // This vector can be empty if it contains no element, or if it
     // contains a pointer to an empty vector.
@@ -54,18 +63,20 @@
     return Val.template get<VecTy*>()->size();
   }
  =20
-  typedef const EltTy *iterator;
-  iterator begin() const {
+  typedef const EltTy *const_iterator;
+  typedef EltTy *iterator;
+
+  iterator begin() {
     if (empty())
       return 0;
    =20
     if (Val.template is<EltTy>())
-      return Val.template getAddrOf<EltTy>();
+      return Val.getAddrOfPtr1();
    =20
     return Val.template get<VecTy *>()->begin();
=20
   }
-  iterator end() const {
+  iterator end() {
     if (empty())
       return 0;
    =20
@@ -75,7 +86,14 @@
     return Val.template get<VecTy *>()->end();
   }
=20
- =20
+  const_iterator begin() const {
+    return (const_iterator)const_cast<TinyPtrVector*>(this)->begin();
+  }
+
+  const_iterator end() const {
+    return (const_iterator)const_cast<TinyPtrVector*>(this)->end();
+  }
+
   EltTy operator[](unsigned i) const {
     assert(!Val.isNull() && "can't index into an empty vector");
     if (EltTy V =3D Val.template dyn_cast<EltTy>()) {
@@ -124,6 +142,20 @@
     }
     // Otherwise, we're already empty.
   }
+
+  iterator erase(iterator I) {
+    // If we have a single value, convert to empty.
+    if (Val.template is<EltTy>()) {
+      if (I =3D=3D begin())
+        Val =3D (EltTy)0;
+    } else if (VecTy *Vec =3D Val.template dyn_cast<VecTy*>()) {
+      // multiple items in a vector; just do the erase, there is no
+      // benefit to collapsing back to a pointer
+      return Vec->erase(I);
+    }
+
+    return 0;
+  }
  =20
 private:
   void operator=3D(const TinyPtrVector&); // NOT IMPLEMENTED YET.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Tri=
e.h
--- a/head/contrib/llvm/include/llvm/ADT/Trie.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm/ADT/Trie.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -220,8 +220,7 @@
         assert(0 && "FIXME!");
         return false;
       case Node::DontMatch:
-        assert(0 && "Impossible!");
-        return false;
+        llvm_unreachable("Impossible!");
       case Node::LabelIsPrefix:
         s1 =3D s1.substr(nNode->label().length());
         cNode =3D nNode;
@@ -258,8 +257,7 @@
       case Node::StringIsPrefix:
         return Empty;
       case Node::DontMatch:
-        assert(0 && "Impossible!");
-        return Empty;
+        llvm_unreachable("Impossible!");
       case Node::LabelIsPrefix:
         s1 =3D s1.substr(nNode->label().length());
         cNode =3D nNode;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Tri=
ple.h
--- a/head/contrib/llvm/include/llvm/ADT/Triple.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/include/llvm/ADT/Triple.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -43,20 +43,19 @@
   enum ArchType {
     UnknownArch,
=20
-    alpha,   // Alpha: alpha
     arm,     // ARM; arm, armv.*, xscale
-    bfin,    // Blackfin: bfin
     cellspu, // CellSPU: spu, cellspu
+    hexagon, // Hexagon: hexagon
     mips,    // MIPS: mips, mipsallegrex
-    mipsel,  // MIPSEL: mipsel, mipsallegrexel, psp
+    mipsel,  // MIPSEL: mipsel, mipsallegrexel
     mips64,  // MIPS64: mips64
     mips64el,// MIPS64EL: mips64el
     msp430,  // MSP430: msp430
     ppc,     // PPC: powerpc
     ppc64,   // PPC64: powerpc64, ppu
+    r600,    // R600: AMD GPUs HD2XXX - HD6XXX
     sparc,   // Sparc: sparc
     sparcv9, // Sparcv9: Sparcv9
-    systemz, // SystemZ: s390x
     tce,     // TCE (http://tce.cs.tut.fi/): tce
     thumb,   // Thumb: thumb, thumbv.*
     x86,     // X86: i[3-9]86
@@ -66,16 +65,16 @@
     ptx32,   // PTX: ptx (32-bit)
     ptx64,   // PTX: ptx (64-bit)
     le32,    // le32: generic little-endian 32-bit CPU (PNaCl / Emscripten)
-    amdil,   // amdil: amd IL
-
-    InvalidArch
+    amdil   // amdil: amd IL
   };
   enum VendorType {
     UnknownVendor,
=20
     Apple,
     PC,
-    SCEI
+    SCEI,
+    BGP,
+    BGQ
   };
   enum OSType {
     UnknownOS,
@@ -93,61 +92,52 @@
     MinGW32,    // i*86-pc-mingw32, *-w64-mingw32
     NetBSD,
     OpenBSD,
-    Psp,
     Solaris,
     Win32,
     Haiku,
     Minix,
     RTEMS,
-    NativeClient
+    NativeClient,
+    CNK         // BG/P Compute-Node Kernel
   };
   enum EnvironmentType {
     UnknownEnvironment,
=20
     GNU,
     GNUEABI,
+    GNUEABIHF,
     EABI,
-    MachO
+    MachO,
+    ANDROIDEABI
   };
=20
 private:
   std::string Data;
=20
-  /// The parsed arch type (or InvalidArch if uninitialized).
-  mutable ArchType Arch;
+  /// The parsed arch type.
+  ArchType Arch;
=20
   /// The parsed vendor type.
-  mutable VendorType Vendor;
+  VendorType Vendor;
=20
   /// The parsed OS type.
-  mutable OSType OS;
+  OSType OS;
=20
   /// The parsed Environment type.
-  mutable EnvironmentType Environment;
-
-  bool isInitialized() const { return Arch !=3D InvalidArch; }
-  static ArchType ParseArch(StringRef ArchName);
-  static VendorType ParseVendor(StringRef VendorName);
-  static OSType ParseOS(StringRef OSName);
-  static EnvironmentType ParseEnvironment(StringRef EnvironmentName);
-  void Parse() const;
+  EnvironmentType Environment;
=20
 public:
   /// @name Constructors
   /// @{
=20
-  Triple() : Data(), Arch(InvalidArch) {}
-  explicit Triple(const Twine &Str) : Data(Str.str()), Arch(InvalidArch) {}
-  Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr)
-    : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr).str()),
-      Arch(InvalidArch) {
-  }
+  /// \brief Default constructor is the same as an empty string and leaves=
 all
+  /// triple fields unknown.
+  Triple() : Data(), Arch(), Vendor(), OS(), Environment() {}
=20
+  explicit Triple(const Twine &Str);
+  Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr);
   Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr,
-         const Twine &EnvironmentStr)
-    : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr + Twine(=
'-') +
-            EnvironmentStr).str()), Arch(InvalidArch) {
-  }
+         const Twine &EnvironmentStr);
=20
   /// @}
   /// @name Normalization
@@ -164,22 +154,13 @@
   /// @{
=20
   /// getArch - Get the parsed architecture type of this triple.
-  ArchType getArch() const {
-    if (!isInitialized()) Parse();
-    return Arch;
-  }
+  ArchType getArch() const { return Arch; }
=20
   /// getVendor - Get the parsed vendor type of this triple.
-  VendorType getVendor() const {
-    if (!isInitialized()) Parse();
-    return Vendor;
-  }
+  VendorType getVendor() const { return Vendor; }
=20
   /// getOS - Get the parsed operating system type of this triple.
-  OSType getOS() const {
-    if (!isInitialized()) Parse();
-    return OS;
-  }
+  OSType getOS() const { return OS; }
=20
   /// hasEnvironment - Does this triple have the optional environment
   /// (fourth) component?
@@ -188,11 +169,31 @@
   }
=20
   /// getEnvironment - Get the parsed environment type of this triple.
-  EnvironmentType getEnvironment() const {
-    if (!isInitialized()) Parse();
-    return Environment;
+  EnvironmentType getEnvironment() const { return Environment; }
+
+  /// getOSVersion - Parse the version number from the OS name component o=
f the
+  /// triple, if present.
+  ///
+  /// For example, "fooos1.2.3" would return (1, 2, 3).
+  ///
+  /// If an entry is not defined, it will be returned as 0.
+  void getOSVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) con=
st;
+
+  /// getOSMajorVersion - Return just the major version number, this is
+  /// specialized because it is a common query.
+  unsigned getOSMajorVersion() const {
+    unsigned Maj, Min, Micro;
+    getOSVersion(Maj, Min, Micro);
+    return Maj;
   }
=20
+  /// getMacOSXVersion - Parse the version number as with getOSVersion and=
 then
+  /// translate generic "darwin" versions to the corresponding OS X versio=
ns.
+  /// This may also be called with IOS triples but the OS X version number=
 is
+  /// just set to a constant 10.4.0 in that case.  Returns true if success=
ful.
+  bool getMacOSXVersion(unsigned &Major, unsigned &Minor,
+                        unsigned &Micro) const;
+
   /// @}
   /// @name Direct Component Access
   /// @{
@@ -221,21 +222,28 @@
   /// if the environment component is present).
   StringRef getOSAndEnvironmentName() const;
=20
-  /// getOSVersion - Parse the version number from the OS name component o=
f the
-  /// triple, if present.
+  /// @}
+  /// @name Convenience Predicates
+  /// @{
+
+  /// \brief Test whether the architecture is 64-bit
   ///
-  /// For example, "fooos1.2.3" would return (1, 2, 3).
+  /// Note that this tests for 64-bit pointer width, and nothing else. Note
+  /// that we intentionally expose only three predicates, 64-bit, 32-bit, =
and
+  /// 16-bit. The inner details of pointer width for particular architectu=
res
+  /// is not summed up in the triple, and so only a coarse grained predica=
te
+  /// system is provided.
+  bool isArch64Bit() const;
+
+  /// \brief Test whether the architecture is 32-bit
   ///
-  /// If an entry is not defined, it will be returned as 0.
-  void getOSVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) con=
st;
+  /// Note that this tests for 32-bit pointer width, and nothing else.
+  bool isArch32Bit() const;
=20
-  /// getOSMajorVersion - Return just the major version number, this is
-  /// specialized because it is a common query.
-  unsigned getOSMajorVersion() const {
-    unsigned Maj, Min, Micro;
-    getOSVersion(Maj, Min, Micro);
-    return Maj;
-  }
+  /// \brief Test whether the architecture is 16-bit
+  ///
+  /// Note that this tests for 16-bit pointer width, and nothing else.
+  bool isArch16Bit() const;
=20
   /// isOSVersionLT - Helper function for doing comparisons against version
   /// numbers included in the target triple.
@@ -254,23 +262,6 @@
     return false;
   }
=20
-  /// isMacOSX - Is this a Mac OS X triple. For legacy reasons, we support=
 both
-  /// "darwin" and "osx" as OS X triples.
-  bool isMacOSX() const {
-    return getOS() =3D=3D Triple::Darwin || getOS() =3D=3D Triple::MacOSX;
-  }
-
-  /// isOSDarwin - Is this a "Darwin" OS (OS X or iOS).
-  bool isOSDarwin() const {
-    return isMacOSX() || getOS() =3D=3D Triple::IOS;
-  }
-
-  /// isOSWindows - Is this a "Windows" OS.
-  bool isOSWindows() const {
-    return getOS() =3D=3D Triple::Win32 || getOS() =3D=3D Triple::Cygwin ||
-      getOS() =3D=3D Triple::MinGW32;
-  }
-
   /// isMacOSXVersionLT - Comparison function for checking OS X version
   /// compatibility, which handles supporting skewed version numbering sch=
emes
   /// used by the "darwin" triples.
@@ -287,6 +278,43 @@
     return isOSVersionLT(Minor + 4, Micro, 0);
   }
=20
+  /// isMacOSX - Is this a Mac OS X triple. For legacy reasons, we support=
 both
+  /// "darwin" and "osx" as OS X triples.
+  bool isMacOSX() const {
+    return getOS() =3D=3D Triple::Darwin || getOS() =3D=3D Triple::MacOSX;
+  }
+
+  /// isOSDarwin - Is this a "Darwin" OS (OS X or iOS).
+  bool isOSDarwin() const {
+    return isMacOSX() || getOS() =3D=3D Triple::IOS;
+  }
+
+  /// \brief Tests for either Cygwin or MinGW OS
+  bool isOSCygMing() const {
+    return getOS() =3D=3D Triple::Cygwin || getOS() =3D=3D Triple::MinGW32;
+  }
+
+  /// isOSWindows - Is this a "Windows" OS.
+  bool isOSWindows() const {
+    return getOS() =3D=3D Triple::Win32 || isOSCygMing();
+  }
+
+  /// \brief Tests whether the OS uses the ELF binary format.
+  bool isOSBinFormatELF() const {
+    return !isOSDarwin() && !isOSWindows();
+  }
+
+  /// \brief Tests whether the OS uses the COFF binary format.
+  bool isOSBinFormatCOFF() const {
+    return isOSWindows();
+  }
+
+  /// \brief Tests whether the environment is MachO.
+  // FIXME: Should this be an OSBinFormat predicate?
+  bool isEnvironmentMachO() const {
+    return getEnvironment() =3D=3D Triple::MachO || isOSDarwin();
+  }
+
   /// @}
   /// @name Mutators
   /// @{
@@ -335,6 +363,26 @@
   const char *getArchNameForAssembler();
=20
   /// @}
+  /// @name Helpers to build variants of a particular triple.
+  /// @{
+
+  /// \brief Form a triple with a 32-bit variant of the current architectu=
re.
+  ///
+  /// This can be used to move across "families" of architectures where us=
eful.
+  ///
+  /// \returns A new triple with a 32-bit architecture or an unknown
+  ///          architecture if no such variant can be found.
+  llvm::Triple get32BitArchVariant() const;
+
+  /// \brief Form a triple with a 64-bit variant of the current architectu=
re.
+  ///
+  /// This can be used to move across "families" of architectures where us=
eful.
+  ///
+  /// \returns A new triple with a 64-bit architecture or an unknown
+  ///          architecture if no such variant can be found.
+  llvm::Triple get64BitArchVariant() const;
+
+  /// @}
   /// @name Static helpers for IDs.
   /// @{
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Twi=
ne.h
--- a/head/contrib/llvm/include/llvm/ADT/Twine.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/include/llvm/ADT/Twine.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -12,6 +12,7 @@
=20
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cassert>
 #include <string>
=20
@@ -425,7 +426,7 @@
     StringRef getSingleStringRef() const {
       assert(isSingleStringRef() &&"This cannot be had as a single stringr=
ef!");
       switch (getLHSKind()) {
-      default: assert(0 && "Out of sync with isSingleStringRef");
+      default: llvm_unreachable("Out of sync with isSingleStringRef");
       case EmptyKind:      return StringRef();
       case CStringKind:    return StringRef(LHS.cString);
       case StdStringKind:  return StringRef(*LHS.stdString);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/Val=
ueMap.h
--- a/head/contrib/llvm/include/llvm/ADT/ValueMap.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/ADT/ValueMap.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -35,7 +35,7 @@
=20
 namespace llvm {
=20
-template<typename KeyT, typename ValueT, typename Config, typename ValueIn=
foT>
+template<typename KeyT, typename ValueT, typename Config>
 class ValueMapCallbackVH;
=20
 template<typename DenseMapT, typename KeyT>
@@ -72,13 +72,11 @@
 };
=20
 /// See the file comment.
-template<typename KeyT, typename ValueT, typename Config =3D ValueMapConfi=
g<KeyT>,
-         typename ValueInfoT =3D DenseMapInfo<ValueT> >
+template<typename KeyT, typename ValueT, typename Config =3DValueMapConfig=
<KeyT> >
 class ValueMap {
-  friend class ValueMapCallbackVH<KeyT, ValueT, Config, ValueInfoT>;
-  typedef ValueMapCallbackVH<KeyT, ValueT, Config, ValueInfoT> ValueMapCVH;
-  typedef DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH>,
-                   ValueInfoT> MapT;
+  friend class ValueMapCallbackVH<KeyT, ValueT, Config>;
+  typedef ValueMapCallbackVH<KeyT, ValueT, Config> ValueMapCVH;
+  typedef DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH> > MapT;
   typedef typename Config::ExtraData ExtraData;
   MapT Map;
   ExtraData Data;
@@ -190,11 +188,11 @@
=20
 // This CallbackVH updates its ValueMap when the contained Value changes,
 // according to the user's preferences expressed through the Config object.
-template<typename KeyT, typename ValueT, typename Config, typename ValueIn=
foT>
+template<typename KeyT, typename ValueT, typename Config>
 class ValueMapCallbackVH : public CallbackVH {
-  friend class ValueMap<KeyT, ValueT, Config, ValueInfoT>;
+  friend class ValueMap<KeyT, ValueT, Config>;
   friend struct DenseMapInfo<ValueMapCallbackVH>;
-  typedef ValueMap<KeyT, ValueT, Config, ValueInfoT> ValueMapT;
+  typedef ValueMap<KeyT, ValueT, Config> ValueMapT;
   typedef typename llvm::remove_pointer<KeyT>::type KeySansPointerT;
=20
   ValueMapT *Map;
@@ -244,9 +242,9 @@
   }
 };
=20
-template<typename KeyT, typename ValueT, typename Config, typename ValueIn=
foT>
-struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config, ValueInfoT> >=
 {
-  typedef ValueMapCallbackVH<KeyT, ValueT, Config, ValueInfoT> VH;
+template<typename KeyT, typename ValueT, typename Config>
+struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config> > {
+  typedef ValueMapCallbackVH<KeyT, ValueT, Config> VH;
   typedef DenseMapInfo<KeyT> PointerInfo;
=20
   static inline VH getEmptyKey() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/ADT/ili=
st.h
--- a/head/contrib/llvm/include/llvm/ADT/ilist.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/include/llvm/ADT/ilist.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -652,10 +652,6 @@
   void push_front(const NodeTy &val) { insert(this->begin(), val); }
   void push_back(const NodeTy &val) { insert(this->end(), val); }
=20
-  // Special forms of insert...
-  template<class InIt> void insert(iterator where, InIt first, InIt last) {
-    for (; first !=3D last; ++first) insert(where, *first);
-  }
   void insert(iterator where, size_type count, const NodeTy &val) {
     for (; count !=3D 0; --count) insert(where, val);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/AliasAnalysis.h
--- a/head/contrib/llvm/include/llvm/Analysis/AliasAnalysis.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/AliasAnalysis.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -327,7 +327,7 @@
   }
=20
   /// doesAccessArgPointees - Return true if functions with the specified
-  /// behavior are known to potentially read or write  from objects pointed
+  /// behavior are known to potentially read or write from objects pointed
   /// to be their pointer-typed arguments (with arbitrary offsets).
   ///
   static bool doesAccessArgPointees(ModRefBehavior MRB) {
@@ -568,6 +568,11 @@
 ///
 bool isIdentifiedObject(const Value *V);
=20
+/// isKnownNonNull - Return true if this pointer couldn't possibly be null=
 by
+/// its definition.  This returns true for allocas, non-extern-weak global=
s and
+/// byval arguments.
+bool isKnownNonNull(const Value *V);
+
 } // End llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/AliasSetTracker.h
--- a/head/contrib/llvm/include/llvm/Analysis/AliasSetTracker.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/AliasSetTracker.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -264,6 +264,7 @@
   }
   void setVolatile() { Volatile =3D true; }
=20
+public:
   /// aliasesPointer - Return true if the specified pointer "may" (or must)
   /// alias one of the members in the set.
   ///
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/BlockFrequencyImpl.h
--- a/head/contrib/llvm/include/llvm/Analysis/BlockFrequencyImpl.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/BlockFrequencyImpl.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -24,7 +24,6 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 #include <vector>
-#include <sstream>
 #include <string>
=20
 namespace llvm {
@@ -41,7 +40,7 @@
 template<class BlockT, class FunctionT, class BlockProbInfoT>
 class BlockFrequencyImpl {
=20
-  DenseMap<BlockT *, BlockFrequency> Freqs;
+  DenseMap<const BlockT *, BlockFrequency> Freqs;
=20
   BlockProbInfoT *BPI;
=20
@@ -52,15 +51,16 @@
   const uint32_t EntryFreq;
=20
   std::string getBlockName(BasicBlock *BB) const {
-    return BB->getNameStr();
+    return BB->getName().str();
   }
=20
   std::string getBlockName(MachineBasicBlock *MBB) const {
-    std::stringstream ss;
+    std::string str;
+    raw_string_ostream ss(str);
     ss << "BB#" << MBB->getNumber();
=20
     if (const BasicBlock *BB =3D MBB->getBasicBlock())
-      ss << " derived from LLVM BB " << BB->getNameStr();
+      ss << " derived from LLVM BB " << BB->getName();
=20
     return ss.str();
   }
@@ -308,8 +308,9 @@
=20
 public:
   /// getBlockFreq - Return block frequency. Return 0 if we don't have it.
-  BlockFrequency getBlockFreq(BlockT *BB) const {
-    typename DenseMap<BlockT *, BlockFrequency>::const_iterator I =3D Freq=
s.find(BB);
+  BlockFrequency getBlockFreq(const BlockT *BB) const {
+    typename DenseMap<const BlockT *, BlockFrequency>::const_iterator
+      I =3D Freqs.find(BB);
     if (I !=3D Freqs.end())
       return I->second;
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/BlockFrequencyInfo.h
--- a/head/contrib/llvm/include/llvm/Analysis/BlockFrequencyInfo.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/BlockFrequencyInfo.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -47,7 +47,7 @@
   /// that we should not rely on the value itself, but only on the compari=
son to
   /// the other block frequencies. We do this to avoid using of floating p=
oints.
   ///
-  BlockFrequency getBlockFreq(BasicBlock *BB) const;
+  BlockFrequency getBlockFreq(const BasicBlock *BB) const;
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/BranchProbabilityInfo.h
--- a/head/contrib/llvm/include/llvm/Analysis/BranchProbabilityInfo.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/BranchProbabilityInfo.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -17,13 +17,82 @@
 #include "llvm/InitializePasses.h"
 #include "llvm/Pass.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/BranchProbability.h"
=20
 namespace llvm {
-
+class LoopInfo;
 class raw_ostream;
=20
+/// \brief Analysis pass providing branch probability information.
+///
+/// This is a function analysis pass which provides information on the rel=
ative
+/// probabilities of each "edge" in the function's CFG where such an edge =
is
+/// defined by a pair of basic blocks. The probability for a given block a=
nd
+/// a successor block are always relative to the probabilities of the other
+/// successor blocks. Another way of looking at it is that the probabiliti=
es
+/// for a given block B and each of its successors should sum to exactly
+/// one (100%).
 class BranchProbabilityInfo : public FunctionPass {
+public:
+  static char ID;
+
+  BranchProbabilityInfo() : FunctionPass(ID) {
+    initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
+  }
+
+  void getAnalysisUsage(AnalysisUsage &AU) const;
+  bool runOnFunction(Function &F);
+  void print(raw_ostream &OS, const Module *M =3D 0) const;
+
+  /// \brief Get an edge's probability, relative to other out-edges of the=
 Src.
+  ///
+  /// This routine provides access to the fractional probability between z=
ero
+  /// (0%) and one (100%) of this edge executing, relative to other edges
+  /// leaving the 'Src' block. The returned probability is never zero, and=
 can
+  /// only be one if the source block has only one successor.
+  BranchProbability getEdgeProbability(const BasicBlock *Src,
+                                       const BasicBlock *Dst) const;
+
+  /// \brief Test if an edge is hot relative to other out-edges of the Src.
+  ///
+  /// Check whether this edge out of the source block is 'hot'. We define =
hot
+  /// as having a relative probability >=3D 80%.
+  bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
+
+  /// \brief Retrieve the hot successor of a block if one exists.
+  ///
+  /// Given a basic block, look through its successors and if one exists f=
or
+  /// which \see isEdgeHot would return true, return that successor block.
+  BasicBlock *getHotSucc(BasicBlock *BB) const;
+
+  /// \brief Print an edge's probability.
+  ///
+  /// Retrieves an edge's probability similarly to \see getEdgeProbability=
, but
+  /// then prints that probability to the provided stream. That stream is =
then
+  /// returned.
+  raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
+                                    const BasicBlock *Dst) const;
+
+  /// \brief Get the raw edge weight calculated for the block pair.
+  ///
+  /// This returns the raw edge weight. It is guaranteed to fall between 1=
 and
+  /// UINT32_MAX. Note that the raw edge weight is not meaningful in isola=
tion.
+  /// This interface should be very carefully, and primarily by routines t=
hat
+  /// are updating the analysis by later calling setEdgeWeight.
+  uint32_t getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) con=
st;
+
+  /// \brief Set the raw edge weight for the block pair.
+  ///
+  /// This allows a pass to explicitly set the edge weight for a block. It=
 can
+  /// be used when updating the CFG to update and preserve the branch
+  /// probability information. Read the implementation of how these edge
+  /// weights are calculated carefully before using!
+  void setEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst,
+                     uint32_t Weight);
+
+private:
+  typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
=20
   // Default weight value. Used when we don't have information about the e=
dge.
   // TODO: DEFAULT_WEIGHT makes sense during static predication, when none=
 of
@@ -33,49 +102,26 @@
   // weight to just "inherit" the non-zero weight of an adjacent successor.
   static const uint32_t DEFAULT_WEIGHT =3D 16;
=20
-  typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
-
   DenseMap<Edge, uint32_t> Weights;
=20
-  // Get sum of the block successors' weights.
+  /// \brief Handle to the LoopInfo analysis.
+  LoopInfo *LI;
+
+  /// \brief Track the last function we run over for printing.
+  Function *LastF;
+
+  /// \brief Track the set of blocks directly succeeded by a returning blo=
ck.
+  SmallPtrSet<BasicBlock *, 16> PostDominatedByUnreachable;
+
+  /// \brief Get sum of the block successors' weights.
   uint32_t getSumForBlock(const BasicBlock *BB) const;
=20
-public:
-  static char ID;
-
-  BranchProbabilityInfo() : FunctionPass(ID) {
-    initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
-  }
-
-  void getAnalysisUsage(AnalysisUsage &AU) const;
-
-  bool runOnFunction(Function &F);
-
-  // Returned value is between 1 and UINT32_MAX. Look at
-  // BranchProbabilityInfo.cpp for details.
-  uint32_t getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) con=
st;
-
-  // Look at BranchProbabilityInfo.cpp for details. Use it with caution!
-  void setEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst,
-                     uint32_t Weight);
-
-  // A 'Hot' edge is an edge which probability is >=3D 80%.
-  bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
-
-  // Return a hot successor for the block BB or null if there isn't one.
-  BasicBlock *getHotSucc(BasicBlock *BB) const;
-
-  // Return a probability as a fraction between 0 (0% probability) and
-  // 1 (100% probability), however the value is never equal to 0, and can =
be 1
-  // only iff SRC block has only one successor.
-  BranchProbability getEdgeProbability(const BasicBlock *Src,
-                                       const BasicBlock *Dst) const;
-
-  // Print value between 0 (0% probability) and 1 (100% probability),
-  // however the value is never equal to 0, and can be 1 only iff SRC block
-  // has only one successor.
-  raw_ostream &printEdgeProbability(raw_ostream &OS, BasicBlock *Src,
-                                    BasicBlock *Dst) const;
+  bool calcUnreachableHeuristics(BasicBlock *BB);
+  bool calcMetadataWeights(BasicBlock *BB);
+  bool calcPointerHeuristics(BasicBlock *BB);
+  bool calcLoopBranchHeuristics(BasicBlock *BB);
+  bool calcZeroHeuristics(BasicBlock *BB);
+  bool calcFloatingPointHeuristics(BasicBlock *BB);
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/CFGPrinter.h
--- a/head/contrib/llvm/include/llvm/Analysis/CFGPrinter.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/CFGPrinter.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -29,13 +29,13 @@
   DOTGraphTraits (bool isSimple=3Dfalse) : DefaultDOTGraphTraits(isSimple)=
 {}
=20
   static std::string getGraphName(const Function *F) {
-    return "CFG for '" + F->getNameStr() + "' function";
+    return "CFG for '" + F->getName().str() + "' function";
   }
=20
   static std::string getSimpleNodeLabel(const BasicBlock *Node,
-                                  const Function *Graph) {
+                                        const Function *) {
     if (!Node->getName().empty())
-      return Node->getNameStr();=20
+      return Node->getName().str();
=20
     std::string Str;
     raw_string_ostream OS(Str);
@@ -45,7 +45,7 @@
   }
=20
   static std::string getCompleteNodeLabel(const BasicBlock *Node,=20
-                                          const Function *Graph) {
+                                          const Function *) {
     std::string Str;
     raw_string_ostream OS(Str);
=20
@@ -95,7 +95,9 @@
      =20
       std::string Str;
       raw_string_ostream OS(Str);
-      OS << SI->getCaseValue(SuccNo)->getValue();
+      SwitchInst::ConstCaseIt Case =3D
+          SwitchInst::ConstCaseIt::fromSuccessorIndex(SI, SuccNo);=20
+      OS << Case.getCaseValue()->getValue();
       return OS.str();
     }   =20
     return "";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/CaptureTracking.h
--- a/head/contrib/llvm/include/llvm/Analysis/CaptureTracking.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/CaptureTracking.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -14,9 +14,12 @@
 #ifndef LLVM_ANALYSIS_CAPTURETRACKING_H
 #define LLVM_ANALYSIS_CAPTURETRACKING_H
=20
+#include "llvm/Constants.h"
+#include "llvm/Instructions.h"
+#include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/Support/CallSite.h"
+
 namespace llvm {
-  class Value;
-
   /// PointerMayBeCaptured - Return true if this pointer value may be capt=
ured
   /// by the enclosing function (which is required to exist).  This routin=
e can
   /// be expensive, so consider caching the results.  The boolean ReturnCa=
ptures
@@ -28,6 +31,33 @@
                             bool ReturnCaptures,
                             bool StoreCaptures);
=20
+  /// This callback is used in conjunction with PointerMayBeCaptured. In
+  /// addition to the interface here, you'll need to provide your own gett=
ers
+  /// to see whether anything was captured.
+  struct CaptureTracker {
+    virtual ~CaptureTracker();
+
+    /// tooManyUses - The depth of traversal has breached a limit. There m=
ay be
+    /// capturing instructions that will not be passed into captured().
+    virtual void tooManyUses() =3D 0;
+
+    /// shouldExplore - This is the use of a value derived from the pointe=
r.
+    /// To prune the search (ie., assume that none of its users could poss=
ibly
+    /// capture) return false. To search it, return true.
+    ///
+    /// U->getUser() is always an Instruction.
+    virtual bool shouldExplore(Use *U) =3D 0;
+
+    /// captured - Information about the pointer was captured by the user =
of
+    /// use U. Return true to stop the traversal or false to continue look=
ing
+    /// for more capturing instructions.
+    virtual bool captured(Use *U) =3D 0;
+  };
+
+  /// PointerMayBeCaptured - Visit the value and the values derived from i=
t and
+  /// find values which appear to be capturing the pointer value. This fee=
ds
+  /// results into and is controlled by the CaptureTracker object.
+  void PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker);
 } // end namespace llvm
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/CodeMetrics.h
--- a/head/contrib/llvm/include/llvm/Analysis/CodeMetrics.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/CodeMetrics.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- CodeMetrics.h - Measures the weight of a function---------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D- CodeMetrics.h - Code cost measurements -------------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,80 +18,75 @@
 #include "llvm/ADT/DenseMap.h"
=20
 namespace llvm {
+  class BasicBlock;
+  class Function;
+  class Instruction;
+  class TargetData;
+  class Value;
=20
-  class TargetData;
+  /// \brief Check whether an instruction is likely to be "free" when lowe=
red.
+  bool isInstructionFree(const Instruction *I, const TargetData *TD =3D 0);
=20
-  // CodeMetrics - Calculate size and a few similar metrics for a set of
-  // basic blocks.
+  /// \brief Check whether a call will lower to something small.
+  ///
+  /// This tests checks whether calls to this function will lower to somet=
hing
+  /// significantly cheaper than a traditional call, often a single
+  /// instruction.
+  bool callIsSmall(const Function *F);
+
+  /// \brief Utility to calculate the size and a few similar metrics for a=
 set
+  /// of basic blocks.
   struct CodeMetrics {
-    /// NeverInline - True if this callee should never be inlined into a
-    /// caller.
-    // bool NeverInline;
+    /// \brief True if this function contains a call to setjmp or other fu=
nctions
+    /// with attribute "returns twice" without having the attribute itself.
+    bool exposesReturnsTwice;
=20
-    // True if this function contains a call to setjmp or _setjmp
-    bool callsSetJmp;
-
-    // True if this function calls itself
+    /// \brief True if this function calls itself.
     bool isRecursive;
=20
-    // True if this function contains one or more indirect branches
+    /// \brief True if this function contains one or more indirect branche=
s.
     bool containsIndirectBr;
=20
-    /// usesDynamicAlloca - True if this function calls alloca (in the C s=
ense).
+    /// \brief True if this function calls alloca (in the C sense).
     bool usesDynamicAlloca;
=20
-    /// NumInsts, NumBlocks - Keep track of how large each function is, wh=
ich
-    /// is used to estimate the code size cost of inlining it.
-    unsigned NumInsts, NumBlocks;
+    /// \brief Number of instructions in the analyzed blocks.
+    unsigned NumInsts;
=20
-    /// NumBBInsts - Keeps track of basic block code size estimates.
+    /// \brief Number of analyzed blocks.
+    unsigned NumBlocks;
+
+    /// \brief Keeps track of basic block code size estimates.
     DenseMap<const BasicBlock *, unsigned> NumBBInsts;
=20
-    /// NumCalls - Keep track of the number of calls to 'big' functions.
+    /// \brief Keep track of the number of calls to 'big' functions.
     unsigned NumCalls;
=20
-    /// NumInlineCandidates - Keep track of the number of calls to internal
-    /// functions with only a single caller.  These are likely targets for
-    /// future inlining, likely exposed by interleaved devirtualization.
+    /// \brief The number of calls to internal functions with a single cal=
ler.
+    ///
+    /// These are likely targets for future inlining, likely exposed by
+    /// interleaved devirtualization.
     unsigned NumInlineCandidates;
=20
-    /// NumVectorInsts - Keep track of how many instructions produce vector
-    /// values.  The inliner is being more aggressive with inlining vector
-    /// kernels.
+    /// \brief How many instructions produce vector values.
+    ///
+    /// The inliner is more aggressive with inlining vector kernels.
     unsigned NumVectorInsts;
=20
-    /// NumRets - Keep track of how many Ret instructions the block contai=
ns.
+    /// \brief How many 'ret' instructions the blocks contain.
     unsigned NumRets;
=20
-    CodeMetrics() : callsSetJmp(false), isRecursive(false),
+    CodeMetrics() : exposesReturnsTwice(false), isRecursive(false),
                     containsIndirectBr(false), usesDynamicAlloca(false),
                     NumInsts(0), NumBlocks(0), NumCalls(0),
                     NumInlineCandidates(0), NumVectorInsts(0),
                     NumRets(0) {}
=20
-    /// analyzeBasicBlock - Add information about the specified basic block
-    /// to the current structure.
+    /// \brief Add information about a block to the current state.
     void analyzeBasicBlock(const BasicBlock *BB, const TargetData *TD =3D =
0);
=20
-    /// analyzeFunction - Add information about the specified function
-    /// to the current structure.
+    /// \brief Add information about a function to the current state.
     void analyzeFunction(Function *F, const TargetData *TD =3D 0);
-
-    /// CountCodeReductionForConstant - Figure out an approximation for how
-    /// many instructions will be constant folded if the specified value is
-    /// constant.
-    unsigned CountCodeReductionForConstant(Value *V);
-
-    /// CountBonusForConstant - Figure out an approximation for how much
-    /// per-call performance boost we can expect if the specified value is
-    /// constant.
-    unsigned CountBonusForConstant(Value *V);
-
-    /// CountCodeReductionForAlloca - Figure out an approximation of how m=
uch
-    /// smaller the function will be if it is inlined into a context where=
 an
-    /// argument becomes an alloca.
-    ///
-    unsigned CountCodeReductionForAlloca(Value *V);
   };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/ConstantFolding.h
--- a/head/contrib/llvm/include/llvm/Analysis/ConstantFolding.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/ConstantFolding.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -25,6 +25,7 @@
   class ConstantExpr;
   class Instruction;
   class TargetData;
+  class TargetLibraryInfo;
   class Function;
   class Type;
   template<typename T>
@@ -35,13 +36,15 @@
 /// Note that this fails if not all of the operands are constant.  Otherwi=
se,
 /// this function can only fail when attempting to fold instructions like =
loads
 /// and stores, which have no constant expression form.
-Constant *ConstantFoldInstruction(Instruction *I, const TargetData *TD =3D=
 0);
+Constant *ConstantFoldInstruction(Instruction *I, const TargetData *TD =3D=
 0,
+                                  const TargetLibraryInfo *TLI =3D 0);
=20
 /// ConstantFoldConstantExpression - Attempt to fold the constant expressi=
on
 /// using the specified TargetData.  If successful, the constant result is
 /// result is returned, if not, null is returned.
 Constant *ConstantFoldConstantExpression(const ConstantExpr *CE,
-                                         const TargetData *TD =3D 0);
+                                         const TargetData *TD =3D 0,
+                                         const TargetLibraryInfo *TLI =3D =
0);
=20
 /// ConstantFoldInstOperands - Attempt to constant fold an instruction wit=
h the
 /// specified operands.  If successful, the constant result is returned, i=
f not,
@@ -51,7 +54,8 @@
 ///
 Constant *ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
                                    ArrayRef<Constant *> Ops,
-                                   const TargetData *TD =3D 0);
+                                   const TargetData *TD =3D 0,
+                                   const TargetLibraryInfo *TLI =3D 0);
=20
 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
@@ -59,7 +63,8 @@
 ///
 Constant *ConstantFoldCompareInstOperands(unsigned Predicate,
                                           Constant *LHS, Constant *RHS,
-                                          const TargetData *TD =3D 0);
+                                          const TargetData *TD =3D 0,
+                                          const TargetLibraryInfo *TLI =3D=
 0);
=20
 /// ConstantFoldInsertValueInstruction - Attempt to constant fold an inser=
tvalue
 /// instruction with the specified operands and indices.  The constant res=
ult is
@@ -76,15 +81,22 @@
 /// getelementptr constantexpr, return the constant value being addressed =
by the
 /// constant expression, or null if something is funny and we can't decide.
 Constant *ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr=
 *CE);
- =20
+
+/// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
+/// indices (with an *implied* zero pointer index that is not in the list),
+/// return the constant value being addressed by a virtual load, or null if
+/// something is funny and we can't decide.
+Constant *ConstantFoldLoadThroughGEPIndices(Constant *C,
+                                            ArrayRef<Constant*> Indices);
+
 /// canConstantFoldCallTo - Return true if its even possible to fold a cal=
l to
 /// the specified function.
 bool canConstantFoldCallTo(const Function *F);
=20
 /// ConstantFoldCall - Attempt to constant fold a call to the specified fu=
nction
 /// with the specified arguments, returning null if unsuccessful.
-Constant *
-ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands);
+Constant *ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
+                           const TargetLibraryInfo *TLI =3D 0);
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/DIBuilder.h
--- a/head/contrib/llvm/include/llvm/Analysis/DIBuilder.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/DIBuilder.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -42,6 +42,7 @@
   class DISubprogram;
   class DITemplateTypeParameter;
   class DITemplateValueParameter;
+  class DIObjCProperty;
=20
   class DIBuilder {
     private:
@@ -190,6 +191,39 @@
                           StringRef PropertySetterName =3D StringRef(),
                           unsigned PropertyAttributes =3D 0);
=20
+    /// createObjCIVar - Create debugging information entry for Objective-C
+    /// instance variable.
+    /// @param Name         Member name.
+    /// @param File         File where this member is defined.
+    /// @param LineNo       Line number.
+    /// @param SizeInBits   Member size.
+    /// @param AlignInBits  Member alignment.
+    /// @param OffsetInBits Member offset.
+    /// @param Flags        Flags to encode member attribute, e.g. private
+    /// @param Ty           Parent type.
+    /// @param Property     Property associated with this ivar.
+    DIType createObjCIVar(StringRef Name, DIFile File,
+                          unsigned LineNo, uint64_t SizeInBits,=20
+                          uint64_t AlignInBits, uint64_t OffsetInBits,=20
+                          unsigned Flags, DIType Ty,
+                          MDNode *PropertyNode);
+
+    /// createObjCProperty - Create debugging information entry for Object=
ive-C
+    /// property.
+    /// @param Name         Property name.
+    /// @param File         File where this property is defined.
+    /// @param LineNumber   Line number.
+    /// @param GetterName   Name of the Objective C property getter select=
or.
+    /// @param SetterName   Name of the Objective C property setter select=
or.
+    /// @param PropertyAttributes Objective C property attributes.
+    /// @param Ty           Type.
+    DIObjCProperty createObjCProperty(StringRef Name,
+				      DIFile File, unsigned LineNumber,
+				      StringRef GetterName,
+				      StringRef SetterName,
+				      unsigned PropertyAttributes,
+				      DIType Ty);
+     =20
     /// createClassType - Create debugging information entry for a class.
     /// @param Scope        Scope in which this class is defined.
     /// @param Name         class name.
@@ -313,6 +347,10 @@
     DIType createTemporaryType();
     DIType createTemporaryType(DIFile F);
=20
+    /// createForwardDecl - Create a temporary forward-declared type.
+    DIType createForwardDecl(unsigned Tag, StringRef Name, DIFile F,
+                             unsigned Line, unsigned RuntimeLang =3D 0);
+
     /// retainType - Retain DIType in a module even if it is not reference=
d=20
     /// through debug info anchors.
     void retainType(DIType T);
@@ -407,6 +445,7 @@
     /// @param Ty            Function type.
     /// @param isLocalToUnit True if this function is not externally visib=
le..
     /// @param isDefinition  True if this is a function definition.
+    /// @param ScopeLine     Set to the beginning of the scope this starts
     /// @param Flags         e.g. is this function prototyped or not.
     ///                      This flags are used to emit dwarf attributes.
     /// @param isOptimized   True if optimization is ON.
@@ -417,6 +456,7 @@
                                 DIFile File, unsigned LineNo,
                                 DIType Ty, bool isLocalToUnit,
                                 bool isDefinition,
+                                unsigned ScopeLine,
                                 unsigned Flags =3D 0,
                                 bool isOptimized =3D false,
                                 Function *Fn =3D 0,
@@ -470,7 +510,7 @@
     /// @param Scope       Lexical block.
     /// @param File        Source file.
     DILexicalBlockFile createLexicalBlockFile(DIDescriptor Scope,
-					      DIFile File);
+                                              DIFile File);
    =20
     /// createLexicalBlock - This creates a descriptor for a lexical block
     /// with the specified parent context.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/DOTGraphTraitsPass.h
--- a/head/contrib/llvm/include/llvm/Analysis/DOTGraphTraitsPass.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/DOTGraphTraitsPass.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
     std::string Title, GraphName;
     Graph =3D &getAnalysis<Analysis>();
     GraphName =3D DOTGraphTraits<Analysis*>::getGraphName(Graph);
-    Title =3D GraphName + " for '" + F.getNameStr() + "' function";
+    Title =3D GraphName + " for '" + F.getName().str() + "' function";
     ViewGraph(Graph, Name, Simple, Title);
=20
     return false;
@@ -55,7 +55,7 @@
=20
   virtual bool runOnFunction(Function &F) {
     Analysis *Graph;
-    std::string Filename =3D Name + "." + F.getNameStr() + ".dot";
+    std::string Filename =3D Name + "." + F.getName().str() + ".dot";
     errs() << "Writing '" << Filename << "'...";
=20
     std::string ErrorInfo;
@@ -64,7 +64,7 @@
=20
     std::string Title, GraphName;
     GraphName =3D DOTGraphTraits<Analysis*>::getGraphName(Graph);
-    Title =3D GraphName + " for '" + F.getNameStr() + "' function";
+    Title =3D GraphName + " for '" + F.getName().str() + "' function";
=20
     if (ErrorInfo.empty())
       WriteGraph(File, Graph, Simple, Title);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/DebugInfo.h
--- a/head/contrib/llvm/include/llvm/Analysis/DebugInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/DebugInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -43,6 +43,7 @@
   class DILexicalBlockFile;
   class DIVariable;
   class DIType;
+  class DIObjCProperty;
=20
   /// DIDescriptor - A thin wraper around MDNode to access encoded debug i=
nfo.
   /// This should not be stored in a container, because underly MDNode may
@@ -128,6 +129,7 @@
     bool isUnspecifiedParameter() const;
     bool isTemplateTypeParameter() const;
     bool isTemplateValueParameter() const;
+    bool isObjCProperty() const;
   };
=20
   /// DISubrange - This is used to represent ranges, for array bounds.
@@ -135,8 +137,8 @@
   public:
     explicit DISubrange(const MDNode *N =3D 0) : DIDescriptor(N) {}
=20
-    int64_t getLo() const { return (int64_t)getUInt64Field(1); }
-    int64_t getHi() const { return (int64_t)getUInt64Field(2); }
+    uint64_t getLo() const { return getUInt64Field(1); }
+    uint64_t getHi() const { return getUInt64Field(2); }
   };
=20
   /// DIArray - This descriptor holds an array of descriptors.
@@ -153,6 +155,7 @@
=20
   /// DIScope - A base class for various scopes.
   class DIScope : public DIDescriptor {
+    virtual void anchor();
   public:
     explicit DIScope(const MDNode *N =3D 0) : DIDescriptor (N) {}
     virtual ~DIScope() {}
@@ -163,6 +166,7 @@
=20
   /// DICompileUnit - A wrapper for a compile unit.
   class DICompileUnit : public DIScope {
+    virtual void anchor();
   public:
     explicit DICompileUnit(const MDNode *N =3D 0) : DIScope(N) {}
=20
@@ -202,6 +206,7 @@
=20
   /// DIFile - This is a wrapper for a file.
   class DIFile : public DIScope {
+    virtual void anchor();
   public:
     explicit DIFile(const MDNode *N =3D 0) : DIScope(N) {
       if (DbgNode && !isFile())
@@ -230,7 +235,7 @@
   /// FIXME: Types should be factored much better so that CV qualifiers and
   /// others do not require a huge and empty descriptor full of zeros.
   class DIType : public DIScope {
-  public:
+    virtual void anchor();
   protected:
     // This ctor is used when the Tag has already been validated by a deri=
ved
     // ctor.
@@ -240,7 +245,6 @@
=20
     /// Verify - Verify that a type descriptor is well formed.
     bool Verify() const;
-  public:
     explicit DIType(const MDNode *N);
     explicit DIType() {}
     virtual ~DIType() {}
@@ -320,6 +324,7 @@
=20
   /// DIBasicType - A basic type, like 'int' or 'float'.
   class DIBasicType : public DIType {
+    virtual void anchor();
   public:
     explicit DIBasicType(const MDNode *N =3D 0) : DIType(N) {}
=20
@@ -338,6 +343,7 @@
   /// DIDerivedType - A simple derived type, like a const qualified type,
   /// a typedef, a pointer or reference, etc.
   class DIDerivedType : public DIType {
+    virtual void anchor();
   protected:
     explicit DIDerivedType(const MDNode *N, bool, bool)
       : DIType(N, true, true) {}
@@ -351,29 +357,45 @@
     /// return base type size.
     uint64_t getOriginalTypeSize() const;
=20
-    StringRef getObjCPropertyName() const { return getStringField(10); }
+    /// getObjCProperty - Return property node, if this ivar is=20
+    /// associated with one.
+    MDNode *getObjCProperty() const;
+
+    StringRef getObjCPropertyName() const {=20
+      if (getVersion() > LLVMDebugVersion11)
+        return StringRef();
+      return getStringField(10);=20
+    }
     StringRef getObjCPropertyGetterName() const {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return getStringField(11);
     }
     StringRef getObjCPropertySetterName() const {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return getStringField(12);
     }
     bool isReadOnlyObjCProperty() {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_readonly) !=
=3D 0;
     }
     bool isReadWriteObjCProperty() {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_readwrite) !=
=3D 0;
     }
     bool isAssignObjCProperty() {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_assign) !=3D=
 0;
     }
     bool isRetainObjCProperty() {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_retain) !=3D=
 0;
     }
     bool isCopyObjCProperty() {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_copy) !=3D 0;
     }
     bool isNonAtomicObjCProperty() {
+      assert (getVersion() <=3D LLVMDebugVersion11  && "Invalid Request");
       return (getUnsignedField(13) & dwarf::DW_APPLE_PROPERTY_nonatomic) !=
=3D 0;
     }
=20
@@ -391,6 +413,7 @@
   /// other types, like a function or struct.
   /// FIXME: Why is this a DIDerivedType??
   class DICompositeType : public DIDerivedType {
+    virtual void anchor();
   public:
     explicit DICompositeType(const MDNode *N =3D 0)
       : DIDerivedType(N, true, true) {
@@ -454,6 +477,7 @@
=20
   /// DISubprogram - This is a wrapper for a subprogram (e.g. a function).
   class DISubprogram : public DIScope {
+    virtual void anchor();
   public:
     explicit DISubprogram(const MDNode *N =3D 0) : DIScope(N) {}
=20
@@ -495,6 +519,7 @@
     DICompositeType getContainingType() const {
       return getFieldAs<DICompositeType>(13);
     }
+
     unsigned isArtificial() const    {=20
       if (getVersion() <=3D llvm::LLVMDebugVersion8)
         return getUnsignedField(14);=20
@@ -543,6 +568,11 @@
       return getFieldAs<DIFile>(6).getDirectory();=20
     }
=20
+    /// getScopeLineNumber - Get the beginning of the scope of the
+    /// function, not necessarily where the name of the program
+    /// starts.
+    unsigned getScopeLineNumber() const { return getUnsignedField(20); }
+
     /// Verify - Verify that a subprogram descriptor is well formed.
     bool Verify() const;
=20
@@ -621,7 +651,7 @@
=20
     DIScope getContext() const          { return getFieldAs<DIScope>(1); }
     StringRef getName() const           { return getStringField(2);     }
-    DICompileUnit getCompileUnit() const{=20
+    DICompileUnit getCompileUnit() const {=20
       assert (getVersion() <=3D LLVMDebugVersion10 && "Invalid getCompileU=
nit!");
       if (getVersion() =3D=3D llvm::LLVMDebugVersion7)
         return getFieldAs<DICompileUnit>(3);
@@ -687,6 +717,7 @@
=20
   /// DILexicalBlock - This is a wrapper for a lexical block.
   class DILexicalBlock : public DIScope {
+    virtual void anchor();
   public:
     explicit DILexicalBlock(const MDNode *N =3D 0) : DIScope(N) {}
     DIScope getContext() const       { return getFieldAs<DIScope>(1);     =
 }
@@ -705,6 +736,7 @@
   /// DILexicalBlockFile - This is a wrapper for a lexical block with
   /// a filename change.
   class DILexicalBlockFile : public DIScope {
+    virtual void anchor();
   public:
     explicit DILexicalBlockFile(const MDNode *N =3D 0) : DIScope(N) {}
     DIScope getContext() const { return getScope().getContext(); }
@@ -724,6 +756,7 @@
=20
   /// DINameSpace - A wrapper for a C++ style name space.
   class DINameSpace : public DIScope {=20
+    virtual void anchor();
   public:
     explicit DINameSpace(const MDNode *N =3D 0) : DIScope(N) {}
     DIScope getContext() const     { return getFieldAs<DIScope>(1);      }
@@ -760,6 +793,51 @@
     bool Verify() const;
   };
=20
+  class DIObjCProperty : public DIDescriptor {
+  public:
+    explicit DIObjCProperty(const MDNode *N) : DIDescriptor(N) { }
+
+    StringRef getObjCPropertyName() const { return getStringField(1); }
+    DIFile getFile() const { return getFieldAs<DIFile>(2); }
+    unsigned getLineNumber() const { return getUnsignedField(3); }
+
+    StringRef getObjCPropertyGetterName() const {
+      return getStringField(4);
+    }
+    StringRef getObjCPropertySetterName() const {
+      return getStringField(5);
+    }
+    bool isReadOnlyObjCProperty() {
+      return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_readonly) !=
=3D 0;
+    }
+    bool isReadWriteObjCProperty() {
+      return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_readwrite) !=
=3D 0;
+    }
+    bool isAssignObjCProperty() {
+      return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_assign) !=3D =
0;
+    }
+    bool isRetainObjCProperty() {
+      return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_retain) !=3D =
0;
+    }
+    bool isCopyObjCProperty() {
+      return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_copy) !=3D 0;
+    }
+    bool isNonAtomicObjCProperty() {
+      return (getUnsignedField(6) & dwarf::DW_APPLE_PROPERTY_nonatomic) !=
=3D 0;
+    }
+
+    DIType getType() const { return getFieldAs<DIType>(7); }
+
+    /// Verify - Verify that a derived type descriptor is well formed.
+    bool Verify() const;
+
+    /// print - print derived type.
+    void print(raw_ostream &OS) const;
+
+    /// dump - print derived type to dbgs() with a newline.
+    void dump() const;
+  };
+
   /// getDISubprogram - Find subprogram that is enclosing this scope.
   DISubprogram getDISubprogram(const MDNode *Scope);
=20
@@ -816,7 +894,7 @@
     /// addGlobalVariable - Add global variable into GVs.
     bool addGlobalVariable(DIGlobalVariable DIG);
=20
-    // addSubprogram - Add subprgoram into SPs.
+    // addSubprogram - Add subprogram into SPs.
     bool addSubprogram(DISubprogram SP);
=20
     /// addType - Add type into Tys.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/DominanceFrontier.h
--- a/head/contrib/llvm/include/llvm/Analysis/DominanceFrontier.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/DominanceFrontier.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -154,6 +154,7 @@
 /// used to compute a forward dominator frontiers.
 ///
 class DominanceFrontier : public DominanceFrontierBase {
+  virtual void anchor();
 public:
   static char ID; // Pass ID, replacement for typeid
   DominanceFrontier() :
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/DominatorInternals.h
--- a/head/contrib/llvm/include/llvm/Analysis/DominatorInternals.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/DominatorInternals.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -171,7 +171,7 @@
=20
   // it might be that some blocks did not get a DFS number (e.g., blocks o=
f=20
   // infinite loops). In these cases an artificial exit node is required.
-  MultipleRoots |=3D (DT.isPostDominator() && N !=3D F.size());
+  MultipleRoots |=3D (DT.isPostDominator() && N !=3D GraphTraits<FuncT*>::=
size(&F));
=20
   // When naively implemented, the Lengauer-Tarjan algorithm requires a se=
parate
   // bucket for each vertex. However, this is unnecessary, because each ve=
rtex
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/Dominators.h
--- a/head/contrib/llvm/include/llvm/Analysis/Dominators.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/Dominators.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -185,6 +185,18 @@
=20
 template<class NodeT>
 class DominatorTreeBase : public DominatorBase<NodeT> {
+  bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
+                               const DomTreeNodeBase<NodeT> *B) const {
+    assert(A !=3D B);
+    assert(isReachableFromEntry(B));
+    assert(isReachableFromEntry(A));
+
+    const DomTreeNodeBase<NodeT> *IDom;
+    while ((IDom =3D B->getIDom()) !=3D 0 && IDom !=3D A && IDom !=3D B)
+      B =3D IDom;   // Walk up the tree
+    return IDom !=3D 0;
+  }
+
 protected:
   typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
   DomTreeNodeMapType DomTreeNodes;
@@ -321,8 +333,7 @@
   /// block.  This is the same as using operator[] on this class.
   ///
   inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
-    typename DomTreeNodeMapType::const_iterator I =3D DomTreeNodes.find(BB=
);
-    return I !=3D DomTreeNodes.end() ? I->second : 0;
+    return DomTreeNodes.lookup(BB);
   }
=20
   /// getRootNode - This returns the entry node for the CFG of the functio=
n.  If
@@ -339,38 +350,26 @@
   /// Note that this is not a constant time operation!
   ///
   bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
-                         const DomTreeNodeBase<NodeT> *B) const {
-    if (A =3D=3D 0 || B =3D=3D 0) return false;
-    return dominatedBySlowTreeWalk(A, B);
+                         const DomTreeNodeBase<NodeT> *B) {
+    if (A =3D=3D 0 || B =3D=3D 0)
+      return false;
+    if (A =3D=3D B)
+      return false;
+    return dominates(A, B);
   }
=20
-  inline bool properlyDominates(const NodeT *A, const NodeT *B) {
-    if (A =3D=3D B)
-      return false;
-
-    // Cast away the const qualifiers here. This is ok since
-    // this function doesn't actually return the values returned
-    // from getNode.
-    return properlyDominates(getNode(const_cast<NodeT *>(A)),
-                             getNode(const_cast<NodeT *>(B)));
-  }
-
-  bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
-                               const DomTreeNodeBase<NodeT> *B) const {
-    const DomTreeNodeBase<NodeT> *IDom;
-    if (A =3D=3D 0 || B =3D=3D 0) return false;
-    while ((IDom =3D B->getIDom()) !=3D 0 && IDom !=3D A && IDom !=3D B)
-      B =3D IDom;   // Walk up the tree
-    return IDom !=3D 0;
-  }
-
+  bool properlyDominates(const NodeT *A, const NodeT *B);
=20
   /// isReachableFromEntry - Return true if A is dominated by the entry
   /// block of the function containing it.
-  bool isReachableFromEntry(const NodeT* A) {
+  bool isReachableFromEntry(const NodeT* A) const {
     assert(!this->isPostDominator() &&
            "This is not implemented for post dominators");
-    return dominates(&A->getParent()->front(), A);
+    return isReachableFromEntry(getNode(const_cast<NodeT *>(A)));
+  }
+
+  inline bool isReachableFromEntry(const DomTreeNodeBase<NodeT> *A) const {
+    return A;
   }
=20
   /// dominates - Returns true iff A dominates B.  Note that this is not a
@@ -378,10 +377,16 @@
   ///
   inline bool dominates(const DomTreeNodeBase<NodeT> *A,
                         const DomTreeNodeBase<NodeT> *B) {
+    // A node trivially dominates itself.
     if (B =3D=3D A)
-      return true;  // A node trivially dominates itself.
+      return true;
=20
-    if (A =3D=3D 0 || B =3D=3D 0)
+    // An unreachable node is dominated by anything.
+    if (!isReachableFromEntry(B))
+      return true;
+
+    // And dominates nothing.
+    if (!isReachableFromEntry(A))
       return false;
=20
     // Compare the result of the tree walk and the dfs numbers, if expensi=
ve
@@ -406,16 +411,7 @@
     return dominatedBySlowTreeWalk(A, B);
   }
=20
-  inline bool dominates(const NodeT *A, const NodeT *B) {
-    if (A =3D=3D B)
-      return true;
-
-    // Cast away the const qualifiers here. This is ok since
-    // this function doesn't actually return the values returned
-    // from getNode.
-    return dominates(getNode(const_cast<NodeT *>(A)),
-                     getNode(const_cast<NodeT *>(B)));
-  }
+  bool dominates(const NodeT *A, const NodeT *B);
=20
   NodeT *getRoot() const {
     assert(this->Roots.size() =3D=3D 1 && "Should always have entry node!"=
);
@@ -623,9 +619,8 @@
   }
=20
   DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
-    typename DomTreeNodeMapType::iterator I =3D this->DomTreeNodes.find(BB=
);
-    if (I !=3D this->DomTreeNodes.end() && I->second)
-      return I->second;
+    if (DomTreeNodeBase<NodeT> *Node =3D getNode(BB))
+      return Node;
=20
     // Haven't calculated this node yet?  Get or calculate the node for the
     // immediate dominator.
@@ -641,8 +636,7 @@
   }
=20
   inline NodeT *getIDom(NodeT *BB) const {
-    typename DenseMap<NodeT*, NodeT*>::const_iterator I =3D IDoms.find(BB);
-    return I !=3D IDoms.end() ? I->second : 0;
+    return IDoms.lookup(BB);
   }
=20
   inline void addRoot(NodeT* BB) {
@@ -653,21 +647,24 @@
   /// recalculate - compute a dominator tree for the given function
   template<class FT>
   void recalculate(FT& F) {
+    typedef GraphTraits<FT*> TraitsTy;
     reset();
     this->Vertex.push_back(0);
=20
     if (!this->IsPostDominators) {
       // Initialize root
-      this->Roots.push_back(&F.front());
-      this->IDoms[&F.front()] =3D 0;
-      this->DomTreeNodes[&F.front()] =3D 0;
+      NodeT *entry =3D TraitsTy::getEntryNode(&F);
+      this->Roots.push_back(entry);
+      this->IDoms[entry] =3D 0;
+      this->DomTreeNodes[entry] =3D 0;
=20
       Calculate<FT, NodeT*>(*this, F);
     } else {
       // Initialize the roots list
-      for (typename FT::iterator I =3D F.begin(), E =3D F.end(); I !=3D E;=
 ++I) {
-        if (std::distance(GraphTraits<FT*>::child_begin(I),
-                          GraphTraits<FT*>::child_end(I)) =3D=3D 0)
+      for (typename TraitsTy::nodes_iterator I =3D TraitsTy::nodes_begin(&=
F),
+                                        E =3D TraitsTy::nodes_end(&F); I !=
=3D E; ++I) {
+        if (std::distance(TraitsTy::child_begin(I),
+                          TraitsTy::child_end(I)) =3D=3D 0)
           addRoot(I);
=20
         // Prepopulate maps so that we don't get iterator invalidation iss=
ues later.
@@ -680,6 +677,32 @@
   }
 };
=20
+// These two functions are declared out of line as a workaround for buildi=
ng
+// with old (< r147295) versions of clang because of pr11642.
+template<class NodeT>
+bool DominatorTreeBase<NodeT>::dominates(const NodeT *A, const NodeT *B) {
+  if (A =3D=3D B)
+    return true;
+
+  // Cast away the const qualifiers here. This is ok since
+  // this function doesn't actually return the values returned
+  // from getNode.
+  return dominates(getNode(const_cast<NodeT *>(A)),
+                   getNode(const_cast<NodeT *>(B)));
+}
+template<class NodeT>
+bool
+DominatorTreeBase<NodeT>::properlyDominates(const NodeT *A, const NodeT *B=
) {
+  if (A =3D=3D B)
+    return false;
+
+  // Cast away the const qualifiers here. This is ok since
+  // this function doesn't actually return the values returned
+  // from getNode.
+  return dominates(getNode(const_cast<NodeT *>(A)),
+                   getNode(const_cast<NodeT *>(B)));
+}
+
 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
=20
 //=3D=3D=3D-------------------------------------
@@ -749,9 +772,12 @@
     return DT->dominates(A, B);
   }
=20
-  // dominates - Return true if A dominates B. This performs the
-  // special checks necessary if A and B are in the same basic block.
-  bool dominates(const Instruction *A, const Instruction *B) const;
+  // dominates - Return true if Def dominates a use in User. This performs
+  // the special checks necessary if Def and User are in the same basic bl=
ock.
+  // Note that Def doesn't dominate a use in Def itself!
+  bool dominates(const Instruction *Def, const Use &U) const;
+  bool dominates(const Instruction *Def, const Instruction *User) const;
+  bool dominates(const Instruction *Def, const BasicBlock *BB) const;
=20
   bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const=
 {
     return DT->properlyDominates(A, B);
@@ -814,10 +840,12 @@
     DT->splitBlock(NewBB);
   }
=20
-  bool isReachableFromEntry(const BasicBlock* A) {
+  bool isReachableFromEntry(const BasicBlock* A) const {
     return DT->isReachableFromEntry(A);
   }
=20
+  bool isReachableFromEntry(const Use &U) const;
+
=20
   virtual void releaseMemory() {
     DT->releaseMemory();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/IVUsers.h
--- a/head/contrib/llvm/include/llvm/Analysis/IVUsers.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/IVUsers.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -166,10 +166,16 @@
   const_iterator end() const   { return IVUses.end(); }
   bool empty() const { return IVUses.empty(); }
=20
+  bool isIVUserOrOperand(Instruction *Inst) const {
+    return Processed.count(Inst);
+  }
+
   void print(raw_ostream &OS, const Module* =3D 0) const;
=20
   /// dump - This method is used for debugging.
   void dump() const;
+protected:
+  bool AddUsersImpl(Instruction *I, SmallPtrSet<Loop*,16> &SimpleLoopNests=
);
 };
=20
 Pass *createIVUsersPass();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/InlineCost.h
--- a/head/contrib/llvm/include/llvm/Analysis/InlineCost.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/InlineCost.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,171 +14,118 @@
 #ifndef LLVM_ANALYSIS_INLINECOST_H
 #define LLVM_ANALYSIS_INLINECOST_H
=20
+#include "llvm/Function.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/ValueMap.h"
+#include "llvm/Analysis/CodeMetrics.h"
 #include <cassert>
 #include <climits>
 #include <vector>
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/ValueMap.h"
-#include "llvm/Analysis/CodeMetrics.h"
=20
 namespace llvm {
=20
-  class Value;
-  class Function;
-  class BasicBlock;
   class CallSite;
-  template<class PtrType, unsigned SmallSize>
-  class SmallPtrSet;
   class TargetData;
=20
   namespace InlineConstants {
     // Various magic constants used to adjust heuristics.
     const int InstrCost =3D 5;
-    const int IndirectCallBonus =3D -100;
+    const int IndirectCallThreshold =3D 100;
     const int CallPenalty =3D 25;
     const int LastCallToStaticBonus =3D -15000;
     const int ColdccPenalty =3D 2000;
     const int NoreturnPenalty =3D 10000;
   }
=20
-  /// InlineCost - Represent the cost of inlining a function. This
-  /// supports special values for functions which should "always" or
-  /// "never" be inlined. Otherwise, the cost represents a unitless
-  /// amount; smaller values increase the likelihood of the function
-  /// being inlined.
+  /// \brief Represents the cost of inlining a function.
+  ///
+  /// This supports special values for functions which should "always" or
+  /// "never" be inlined. Otherwise, the cost represents a unitless amount;
+  /// smaller values increase the likelihood of the function being inlined.
+  ///
+  /// Objects of this type also provide the adjusted threshold for inlining
+  /// based on the information available for a particular callsite. They c=
an be
+  /// directly tested to determine if inlining should occur given the cost=
 and
+  /// threshold for this cost metric.
   class InlineCost {
-    enum Kind {
-      Value,
-      Always,
-      Never
+    enum SentinelValues {
+      AlwaysInlineCost =3D INT_MIN,
+      NeverInlineCost =3D INT_MAX
     };
=20
-    // This is a do-it-yourself implementation of
-    //   int Cost : 30;
-    //   unsigned Type : 2;
-    // We used to use bitfields, but they were sometimes miscompiled (PR38=
22).
-    enum { TYPE_BITS =3D 2 };
-    enum { COST_BITS =3D unsigned(sizeof(unsigned)) * CHAR_BIT - TYPE_BITS=
 };
-    unsigned TypedCost; // int Cost : COST_BITS; unsigned Type : TYPE_BITS;
+    /// \brief The estimated cost of inlining this callsite.
+    const int Cost;
=20
-    Kind getType() const {
-      return Kind(TypedCost >> COST_BITS);
+    /// \brief The adjusted threshold against which this cost was computed.
+    const int Threshold;
+
+    // Trivial constructor, interesting logic in the factory functions bel=
ow.
+    InlineCost(int Cost, int Threshold)
+      : Cost(Cost), Threshold(Threshold) {}
+
+  public:
+    static InlineCost get(int Cost, int Threshold) {
+      assert(Cost > AlwaysInlineCost && "Cost crosses sentinel value");
+      assert(Cost < NeverInlineCost && "Cost crosses sentinel value");
+      return InlineCost(Cost, Threshold);
+    }
+    static InlineCost getAlways() {
+      return InlineCost(AlwaysInlineCost, 0);
+    }
+    static InlineCost getNever() {
+      return InlineCost(NeverInlineCost, 0);
     }
=20
-    int getCost() const {
-      // Sign-extend the bottom COST_BITS bits.
-      return (int(TypedCost << TYPE_BITS)) >> TYPE_BITS;
+    /// \brief Test whether the inline cost is low enough for inlining.
+    operator bool() const {
+      return Cost < Threshold;
     }
=20
-    InlineCost(int C, int T) {
-      TypedCost =3D (unsigned(C << TYPE_BITS) >> TYPE_BITS) | (T << COST_B=
ITS);
-      assert(getCost() =3D=3D C && "Cost exceeds InlineCost precision");
+    bool isAlways() const   { return Cost =3D=3D AlwaysInlineCost; }
+    bool isNever() const    { return Cost =3D=3D NeverInlineCost; }
+    bool isVariable() const { return !isAlways() && !isNever(); }
+
+    /// \brief Get the inline cost estimate.
+    /// It is an error to call this on an "always" or "never" InlineCost.
+    int getCost() const {
+      assert(isVariable() && "Invalid access of InlineCost");
+      return Cost;
     }
-  public:
-    static InlineCost get(int Cost) { return InlineCost(Cost, Value); }
-    static InlineCost getAlways() { return InlineCost(0, Always); }
-    static InlineCost getNever() { return InlineCost(0, Never); }
=20
-    bool isVariable() const { return getType() =3D=3D Value; }
-    bool isAlways() const { return getType() =3D=3D Always; }
-    bool isNever() const { return getType() =3D=3D Never; }
-
-    /// getValue() - Return a "variable" inline cost's amount. It is
-    /// an error to call this on an "always" or "never" InlineCost.
-    int getValue() const {
-      assert(getType() =3D=3D Value && "Invalid access of InlineCost");
-      return getCost();
-    }
+    /// \brief Get the cost delta from the threshold for inlining.
+    /// Only valid if the cost is of the variable kind. Returns a negative
+    /// value if the cost is too high to inline.
+    int getCostDelta() const { return Threshold - getCost(); }
   };
=20
   /// InlineCostAnalyzer - Cost analyzer used by inliner.
   class InlineCostAnalyzer {
-    struct ArgInfo {
-    public:
-      unsigned ConstantWeight;
-      unsigned AllocaWeight;
-
-      ArgInfo(unsigned CWeight, unsigned AWeight)
-        : ConstantWeight(CWeight), AllocaWeight(AWeight)
-          {}
-    };
-
-    struct FunctionInfo {
-      CodeMetrics Metrics;
-
-      /// ArgumentWeights - Each formal argument of the function is inspec=
ted to
-      /// see if it is used in any contexts where making it a constant or =
alloca
-      /// would reduce the code size.  If so, we add some value to the arg=
ument
-      /// entry here.
-      std::vector<ArgInfo> ArgumentWeights;
-
-      /// analyzeFunction - Add information about the specified function
-      /// to the current structure.
-      void analyzeFunction(Function *F, const TargetData *TD);
-
-      /// NeverInline - Returns true if the function should never be
-      /// inlined into any caller.
-      bool NeverInline();
-    };
-
-    // The Function* for a function can be changed (by ArgumentPromotion);
-    // the ValueMap will update itself when this happens.
-    ValueMap<const Function *, FunctionInfo> CachedFunctionInfo;
-
     // TargetData if available, or null.
     const TargetData *TD;
=20
-    int CountBonusForConstant(Value *V, Constant *C =3D NULL);
-    int ConstantFunctionBonus(CallSite CS, Constant *C);
-    int getInlineSize(CallSite CS, Function *Callee);
-    int getInlineBonuses(CallSite CS, Function *Callee);
   public:
     InlineCostAnalyzer(): TD(0) {}
=20
     void setTargetData(const TargetData *TData) { TD =3D TData; }
=20
-    /// getInlineCost - The heuristic used to determine if we should inlin=
e the
-    /// function call or not.
+    /// \brief Get an InlineCost object representing the cost of inlining =
this
+    /// callsite.
     ///
-    InlineCost getInlineCost(CallSite CS,
-                             SmallPtrSet<const Function *, 16> &NeverInlin=
e);
+    /// Note that threshold is passed into this function. Only costs below=
 the
+    /// threshold are computed with any accuracy. The threshold can be use=
d to
+    /// bound the computation necessary to determine whether the cost is
+    /// sufficiently low to warrant inlining.
+    InlineCost getInlineCost(CallSite CS, int Threshold);
     /// getCalledFunction - The heuristic used to determine if we should i=
nline
     /// the function call or not.  The callee is explicitly specified, to =
allow
-    /// you to calculate the cost of inlining a function via a pointer.  T=
he
-    /// result assumes that the inlined version will always be used.  You =
should
-    /// weight it yourself in cases where this callee will not always be c=
alled.
-    InlineCost getInlineCost(CallSite CS,
-                             Function *Callee,
-                             SmallPtrSet<const Function *, 16> &NeverInlin=
e);
-
-    /// getSpecializationBonus - The heuristic used to determine the per-c=
all
-    /// performance boost for using a specialization of Callee with argume=
nt
-    /// SpecializedArgNos replaced by a constant.
-    int getSpecializationBonus(Function *Callee,
-             SmallVectorImpl<unsigned> &SpecializedArgNo);
-
-    /// getSpecializationCost - The heuristic used to determine the code-s=
ize
-    /// impact of creating a specialized version of Callee with argument
-    /// SpecializedArgNo replaced by a constant.
-    InlineCost getSpecializationCost(Function *Callee,
-               SmallVectorImpl<unsigned> &SpecializedArgNo);
-
-    /// getInlineFudgeFactor - Return a > 1.0 factor if the inliner should=
 use a
-    /// higher threshold to determine if the function call should be inlin=
ed.
-    float getInlineFudgeFactor(CallSite CS);
-
-    /// resetCachedFunctionInfo - erase any cached cost info for this func=
tion.
-    void resetCachedCostInfo(Function* Caller) {
-      CachedFunctionInfo[Caller] =3D FunctionInfo();
-    }
-
-    /// growCachedCostInfo - update the cached cost info for Caller after =
Callee
-    /// has been inlined. If Callee is NULL it means a dead call has been
-    /// eliminated.
-    void growCachedCostInfo(Function* Caller, Function* Callee);
-
-    /// clear - empty the cache of inline costs
-    void clear();
+    /// you to calculate the cost of inlining a function via a pointer.  T=
his
+    /// behaves exactly as the version with no explicit callee parameter i=
n all
+    /// other respects.
+    //
+    //  Note: This is used by out-of-tree passes, please do not remove wit=
hout
+    //  adding a replacement API.
+    InlineCost getInlineCost(CallSite CS, Function *Callee, int Threshold);
   };
=20
   /// callIsSmall - If a call is likely to lower to a single target instru=
ction,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/InstructionSimplify.h
--- a/head/contrib/llvm/include/llvm/Analysis/InstructionSimplify.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/InstructionSimplify.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -20,147 +20,198 @@
 #define LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
=20
 namespace llvm {
+  template<typename T>
+  class ArrayRef;
   class DominatorTree;
   class Instruction;
+  class TargetData;
+  class TargetLibraryInfo;
+  class Type;
   class Value;
-  class TargetData;
-  template<typename T>
-  class ArrayRef;
=20
   /// SimplifyAddInst - Given operands for an Add, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
-                         const TargetData *TD =3D 0, const DominatorTree *=
DT =3D 0);
+                         const TargetData *TD =3D 0,
+                         const TargetLibraryInfo *TLI =3D 0,
+                         const DominatorTree *DT =3D 0);
=20
   /// SimplifySubInst - Given operands for a Sub, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
-                         const TargetData *TD =3D 0, const DominatorTree *=
DT =3D 0);
+                         const TargetData *TD =3D 0,
+                         const TargetLibraryInfo *TLI =3D 0,
+                         const DominatorTree *DT =3D 0);
=20
   /// SimplifyMulInst - Given operands for a Mul, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyMulInst(Value *LHS, Value *RHS, const TargetData *TD =3D =
0,
+                         const TargetLibraryInfo *TLI =3D 0,
                          const DominatorTree *DT =3D 0);
=20
   /// SimplifySDivInst - Given operands for an SDiv, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifySDivInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifyUDivInst - Given operands for a UDiv, see if we can
   /// fold the result.  If not, this returns null.
-  Value *SimplifyUDivInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,
+  Value *SimplifyUDivInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,=20
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifyFDivInst - Given operands for an FDiv, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyFDivInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifySRemInst - Given operands for an SRem, see if we can
   /// fold the result.  If not, this returns null.
-  Value *SimplifySRemInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,
+  Value *SimplifySRemInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,=20
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifyURemInst - Given operands for a URem, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyURemInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifyFRemInst - Given operands for an FRem, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyFRemInst(Value *LHS, Value *RHS, const TargetData *TD =3D=
 0,
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifyShlInst - Given operands for a Shl, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
-                         const TargetData *TD =3D 0, const DominatorTree *=
DT =3D 0);
+                         const TargetData *TD =3D 0,=20
+                         const TargetLibraryInfo *TLI =3D 0,
+                         const DominatorTree *DT =3D 0);
=20
   /// SimplifyLShrInst - Given operands for a LShr, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
-                          const TargetData *TD =3D 0, const DominatorTree =
*DT=3D0);
+                          const TargetData *TD =3D 0,
+                          const TargetLibraryInfo *TLI =3D 0,
+                          const DominatorTree *DT =3D 0);
=20
   /// SimplifyAShrInst - Given operands for a AShr, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
                           const TargetData *TD =3D 0,
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifyAndInst - Given operands for an And, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyAndInst(Value *LHS, Value *RHS, const TargetData *TD =3D =
0,
+                         const TargetLibraryInfo *TLI =3D 0,
                          const DominatorTree *DT =3D 0);
=20
   /// SimplifyOrInst - Given operands for an Or, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyOrInst(Value *LHS, Value *RHS, const TargetData *TD =3D 0,
+                        const TargetLibraryInfo *TLI =3D 0,
                         const DominatorTree *DT =3D 0);
=20
   /// SimplifyXorInst - Given operands for a Xor, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyXorInst(Value *LHS, Value *RHS, const TargetData *TD =3D =
0,
+                         const TargetLibraryInfo *TLI =3D 0,
                          const DominatorTree *DT =3D 0);
=20
   /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                          const TargetData *TD =3D 0,
+                          const TargetData *TD =3D 0,=20
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                          const TargetData *TD =3D 0,
+                          const TargetData *TD =3D 0,=20
+                          const TargetLibraryInfo *TLI =3D 0,
                           const DominatorTree *DT =3D 0);
=20
   /// SimplifySelectInst - Given operands for a SelectInst, see if we can =
fold
   /// the result.  If not, this returns null.
   Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
                             const TargetData *TD =3D 0,
+                            const TargetLibraryInfo *TLI =3D 0,
                             const DominatorTree *DT =3D 0);
=20
   /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we=
 can
   /// fold the result.  If not, this returns null.
-  Value *SimplifyGEPInst(ArrayRef<Value *> Ops,
-                         const TargetData *TD =3D 0, const DominatorTree *=
DT =3D 0);
+  Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD =3D 0,
+                         const TargetLibraryInfo *TLI =3D 0,
+                         const DominatorTree *DT =3D 0);
=20
   /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see=
 if we
   /// can fold the result.  If not, this returns null.
   Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
                                  ArrayRef<unsigned> Idxs,
                                  const TargetData *TD =3D 0,
+                                 const TargetLibraryInfo *TLI =3D 0,
                                  const DominatorTree *DT =3D 0);
=20
+  /// SimplifyTruncInst - Given operands for an TruncInst, see if we can f=
old
+  /// the result.  If not, this returns null.
+  Value *SimplifyTruncInst(Value *Op, Type *Ty, const TargetData *TD =3D 0,
+                           const TargetLibraryInfo *TLI =3D 0,
+                           const DominatorTree *DT =3D 0);
+
   //=3D=3D=3D Helper functions for higher up the class hierarchy.
=20
=20
   /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                         const TargetData *TD =3D 0, const DominatorTree *=
DT =3D 0);
+                         const TargetData *TD =3D 0,
+                         const TargetLibraryInfo *TLI =3D 0,
+                         const DominatorTree *DT =3D 0);
=20
   /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
   /// fold the result.  If not, this returns null.
   Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
-                       const TargetData *TD =3D 0, const DominatorTree *DT=
 =3D 0);
+                       const TargetData *TD =3D 0,=20
+                       const TargetLibraryInfo *TLI =3D 0,
+                       const DominatorTree *DT =3D 0);
=20
   /// SimplifyInstruction - See if we can compute a simplified version of =
this
   /// instruction.  If not, this returns null.
   Value *SimplifyInstruction(Instruction *I, const TargetData *TD =3D 0,
+                             const TargetLibraryInfo *TLI =3D 0,
                              const DominatorTree *DT =3D 0);
=20
=20
-  /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and=
 then
-  /// delete the From instruction.  In addition to a basic RAUW, this does=
 a
-  /// recursive simplification of the updated instructions.  This catches
-  /// things where one simplification exposes other opportunities.  This o=
nly
-  /// simplifies and deletes scalar operations, it does not change the CFG.
+  /// \brief Replace all uses of 'I' with 'SimpleV' and simplify the uses
+  /// recursively.
   ///
-  void ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
-                                 const TargetData *TD =3D 0,
-                                 const DominatorTree *DT =3D 0);
+  /// This first performs a normal RAUW of I with SimpleV. It then recursi=
vely
+  /// attempts to simplify those users updated by the operation. The 'I'
+  /// instruction must not be equal to the simplified value 'SimpleV'.
+  ///
+  /// The function returns true if any simplifications were performed.
+  bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
+                                     const TargetData *TD =3D 0,
+                                     const TargetLibraryInfo *TLI =3D 0,
+                                     const DominatorTree *DT =3D 0);
+
+  /// \brief Recursively attempt to simplify an instruction.
+  ///
+  /// This routine uses SimplifyInstruction to simplify 'I', and if succes=
sful
+  /// replaces uses of 'I' with the simplified value. It then recurses on =
each
+  /// of the users impacted. It returns true if any simplifications were
+  /// performed.
+  bool recursivelySimplifyInstruction(Instruction *I,
+                                      const TargetData *TD =3D 0,
+                                      const TargetLibraryInfo *TLI =3D 0,
+                                      const DominatorTree *DT =3D 0);
 } // end namespace llvm
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/IntervalIterator.h
--- a/head/contrib/llvm/include/llvm/Analysis/IntervalIterator.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/IntervalIterator.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -101,14 +101,14 @@
   IntervalIterator(Function *M, bool OwnMemory) : IOwnMem(OwnMemory) {
     OrigContainer =3D M;
     if (!ProcessInterval(&M->front())) {
-      assert(0 && "ProcessInterval should never fail for first interval!");
+      llvm_unreachable("ProcessInterval should never fail for first interv=
al!");
     }
   }
=20
   IntervalIterator(IntervalPartition &IP, bool OwnMemory) : IOwnMem(OwnMem=
ory) {
     OrigContainer =3D &IP;
     if (!ProcessInterval(IP.getRootInterval())) {
-      assert(0 && "ProcessInterval should never fail for first interval!");
+      llvm_unreachable("ProcessInterval should never fail for first interv=
al!");
     }
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/LazyValueInfo.h
--- a/head/contrib/llvm/include/llvm/Analysis/LazyValueInfo.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/LazyValueInfo.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -20,12 +20,14 @@
 namespace llvm {
   class Constant;
   class TargetData;
+  class TargetLibraryInfo;
   class Value;
  =20
 /// LazyValueInfo - This pass computes, caches, and vends lazy value const=
raint
 /// information.
 class LazyValueInfo : public FunctionPass {
   class TargetData *TD;
+  class TargetLibraryInfo *TLI;
   void *PImpl;
   LazyValueInfo(const LazyValueInfo&); // DO NOT IMPLEMENT.
   void operator=3D(const LazyValueInfo&); // DO NOT IMPLEMENT.
@@ -68,9 +70,7 @@
  =20
   // Implementation boilerplate.
  =20
-  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
-    AU.setPreservesAll();
-  }
+  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
   virtual void releaseMemory();
   virtual bool runOnFunction(Function &F);
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/Loads.h
--- a/head/contrib/llvm/include/llvm/Analysis/Loads.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/Loads.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -20,6 +20,7 @@
=20
 class AliasAnalysis;
 class TargetData;
+class MDNode;
=20
 /// isSafeToLoadUnconditionally - Return true if we know that executing a =
load
 /// from this value cannot trap.  If it is not obviously safe to load from=
 the
@@ -41,10 +42,15 @@
 /// MaxInstsToScan specifies the maximum instructions to scan in the block.
 /// If it is set to 0, it will scan the whole block. You can also optional=
ly
 /// specify an alias analysis implementation, which makes this more precis=
e.
+///
+/// If TBAATag is non-null and a load or store is found, the TBAA tag from=
 the
+/// load or store is recorded there.  If there is no TBAA tag or if no acc=
ess
+/// is found, it is left unmodified.
 Value *FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
                                 BasicBlock::iterator &ScanFrom,
                                 unsigned MaxInstsToScan =3D 6,
-                                AliasAnalysis *AA =3D 0);
+                                AliasAnalysis *AA =3D 0,
+                                MDNode **TBAATag =3D 0);
=20
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/LoopInfo.h
--- a/head/contrib/llvm/include/llvm/Analysis/LoopInfo.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/LoopInfo.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -23,7 +23,6 @@
 //  * whether or not a particular block branches out of the loop
 //  * the successor blocks of the loop
 //  * the loop depth
-//  * the trip count
 //  * etc...
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -416,14 +415,26 @@
 #ifndef NDEBUG
     assert(!Blocks.empty() && "Loop header is missing");
=20
+    // Setup for using a depth-first iterator to visit every block in the =
loop.
+    SmallVector<BlockT*, 8> ExitBBs;
+    getExitBlocks(ExitBBs);
+    llvm::SmallPtrSet<BlockT*, 8> VisitSet;
+    VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
+    df_ext_iterator<BlockT*, llvm::SmallPtrSet<BlockT*, 8> >
+        BI =3D df_ext_begin(getHeader(), VisitSet),
+        BE =3D df_ext_end(getHeader(), VisitSet);
+
+    // Keep track of the number of BBs visited.
+    unsigned NumVisited =3D 0;
+
     // Sort the blocks vector so that we can use binary search to do quick
     // lookups.
     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
     std::sort(LoopBBs.begin(), LoopBBs.end());
=20
     // Check the individual blocks.
-    for (block_iterator I =3D block_begin(), E =3D block_end(); I !=3D E; =
++I) {
-      BlockT *BB =3D *I;
+    for ( ; BI !=3D BE; ++BI) {
+      BlockT *BB =3D *BI;
       bool HasInsideLoopSuccs =3D false;
       bool HasInsideLoopPreds =3D false;
       SmallVector<BlockT *, 2> OutsideLoopPreds;
@@ -440,7 +451,7 @@
       for (typename InvBlockTraits::ChildIteratorType PI =3D
            InvBlockTraits::child_begin(BB), PE =3D InvBlockTraits::child_e=
nd(BB);
            PI !=3D PE; ++PI) {
-        typename InvBlockTraits::NodeType *N =3D *PI;
+        BlockT *N =3D *PI;
         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N))
           HasInsideLoopPreds =3D true;
         else
@@ -464,8 +475,12 @@
       assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!"=
);
       assert(BB !=3D getHeader()->getParent()->begin() &&
              "Loop contains function entry block!");
+
+      NumVisited++;
     }
=20
+    assert(NumVisited =3D=3D getNumBlocks() && "Unreachable block in loop"=
);
+
     // Check the subloops.
     for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I)
       // Each block in each subloop should be contained within this loop.
@@ -571,37 +586,6 @@
   ///
   PHINode *getCanonicalInductionVariable() const;
=20
-  /// getTripCount - Return a loop-invariant LLVM value indicating the num=
ber of
-  /// times the loop will be executed.  Note that this means that the back=
edge
-  /// of the loop executes N-1 times.  If the trip-count cannot be determi=
ned,
-  /// this returns null.
-  ///
-  /// The IndVarSimplify pass transforms loops to have a form that this
-  /// function easily understands.
-  ///
-  Value *getTripCount() const;
-
-  /// getSmallConstantTripCount - Returns the trip count of this loop as a
-  /// normal unsigned value, if possible. Returns 0 if the trip count is u=
nknown
-  /// of not constant. Will also return 0 if the trip count is very large
-  /// (>=3D 2^32)
-  ///
-  /// The IndVarSimplify pass transforms loops to have a form that this
-  /// function easily understands.
-  ///
-  unsigned getSmallConstantTripCount() const;
-
-  /// getSmallConstantTripMultiple - Returns the largest constant divisor =
of the
-  /// trip count of this loop as a normal unsigned value, if possible. This
-  /// means that the actual trip count is always a multiple of the returned
-  /// value (don't forget the trip count could very well be zero as well!).
-  ///
-  /// Returns 1 if the trip count is unknown or not guaranteed to be the
-  /// multiple of a constant (which is also the case if the trip count is =
simply
-  /// constant, use getSmallConstantTripCount for that case), Will also re=
turn 1
-  /// if the trip count is very large (>=3D 2^32).
-  unsigned getSmallConstantTripMultiple() const;
-
   /// isLCSSAForm - Return true if the Loop is in LCSSA form
   bool isLCSSAForm(DominatorTree &DT) const;
=20
@@ -610,6 +594,9 @@
   /// normal form.
   bool isLoopSimplifyForm() const;
=20
+  /// isSafeToClone - Return true if the loop body is safe to clone in pra=
ctice.
+  bool isSafeToClone() const;
+
   /// hasDedicatedExits - Return true if no exit block for the loop
   /// has a predecessor that is outside the loop.
   bool hasDedicatedExits() const;
@@ -671,9 +658,7 @@
   /// block is in no loop (for example the entry node), null is returned.
   ///
   LoopT *getLoopFor(const BlockT *BB) const {
-    typename DenseMap<BlockT *, LoopT *>::const_iterator I=3D
-      BBMap.find(const_cast<BlockT*>(BB));
-    return I !=3D BBMap.end() ? I->second : 0;
+    return BBMap.lookup(const_cast<BlockT*>(BB));
   }
=20
   /// operator[] - same as getLoopFor...
@@ -712,9 +697,7 @@
   /// the loop hierarchy tree.
   void changeLoopFor(BlockT *BB, LoopT *L) {
     if (!L) {
-      typename DenseMap<BlockT *, LoopT *>::iterator I =3D BBMap.find(BB);
-      if (I !=3D BBMap.end())
-        BBMap.erase(I);
+      BBMap.erase(BB);
       return;
     }
     BBMap[BB] =3D L;
@@ -771,7 +754,7 @@
   }
=20
   LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
-    if (BBMap.find(BB) !=3D BBMap.end()) return 0;// Haven't processed thi=
s node?
+    if (BBMap.count(BB)) return 0; // Haven't processed this node?
=20
     std::vector<BlockT *> TodoStack;
=20
@@ -782,7 +765,8 @@
          InvBlockTraits::child_begin(BB), E =3D InvBlockTraits::child_end(=
BB);
          I !=3D E; ++I) {
       typename InvBlockTraits::NodeType *N =3D *I;
-      if (DT.dominates(BB, N))   // If BB dominates its predecessor...
+      // If BB dominates its predecessor...
+      if (DT.dominates(BB, N) && DT.isReachableFromEntry(N))
           TodoStack.push_back(N);
     }
=20
@@ -792,14 +776,12 @@
     LoopT *L =3D new LoopT(BB);
     BBMap[BB] =3D L;
=20
-    BlockT *EntryBlock =3D BB->getParent()->begin();
-
     while (!TodoStack.empty()) {  // Process all the nodes in the loop
       BlockT *X =3D TodoStack.back();
       TodoStack.pop_back();
=20
       if (!L->contains(X) &&         // As of yet unprocessed??
-          DT.dominates(EntryBlock, X)) {   // X is reachable from entry bl=
ock?
+          DT.isReachableFromEntry(X)) {
         // Check to see if this block already belongs to a loop.  If this =
occurs
         // then we have a case where a loop that is supposed to be a child=
 of
         // the current loop was processed before the current loop.  When t=
his
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/MemoryDependenceAnalysis.h
--- a/head/contrib/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -324,6 +324,7 @@
     /// Current AA implementation, just a cache.
     AliasAnalysis *AA;
     TargetData *TD;
+    DominatorTree *DT;
     OwningPtr<PredIteratorCache> PredCache;
   public:
     MemoryDependenceAnalysis();
@@ -430,6 +431,9 @@
=20
     void RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P);
    =20
+    AliasAnalysis::ModRefResult
+    getModRefInfo(const Instruction *Inst, const AliasAnalysis::Location &=
Loc);
+
     /// verifyRemoved - Verify that the specified instruction does not occ=
ur
     /// in our internal data structures.
     void verifyRemoved(Instruction *Inst) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/PHITransAddr.h
--- a/head/contrib/llvm/include/llvm/Analysis/PHITransAddr.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/PHITransAddr.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -20,7 +20,8 @@
 namespace llvm {
   class DominatorTree;
   class TargetData;
- =20
+  class TargetLibraryInfo;
+
 /// PHITransAddr - An address value which tracks and handles phi translati=
on.
 /// As we walk "up" the CFG through predecessors, we need to ensure that t=
he
 /// address we're tracking is kept up to date.  For example, if we're anal=
yzing
@@ -37,11 +38,14 @@
  =20
   /// TD - The target data we are playing with if known, otherwise null.
   const TargetData *TD;
+
+  /// TLI - The target library info if known, otherwise null.
+  const TargetLibraryInfo *TLI;
  =20
   /// InstInputs - The inputs for our symbolic address.
   SmallVector<Instruction*, 4> InstInputs;
 public:
-  PHITransAddr(Value *addr, const TargetData *td) : Addr(addr), TD(td) {
+  PHITransAddr(Value *addr, const TargetData *td) : Addr(addr), TD(td), TL=
I(0) {
     // If the address is an instruction, the whole thing is considered an =
input.
     if (Instruction *I =3D dyn_cast<Instruction>(Addr))
       InstInputs.push_back(I);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/ProfileInfo.h
--- a/head/contrib/llvm/include/llvm/Analysis/ProfileInfo.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/ProfileInfo.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -22,6 +22,7 @@
 #define LLVM_ANALYSIS_PROFILEINFO_H
=20
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/raw_ostream.h"
 #include <cassert>
@@ -85,13 +86,11 @@
=20
     // getFunction() - Returns the Function for an Edge, checking for vali=
dity.
     static const FType* getFunction(Edge e) {
-      if (e.first) {
+      if (e.first)
         return e.first->getParent();
-      } else if (e.second) {
+      if (e.second)
         return e.second->getParent();
-      }
-      assert(0 && "Invalid ProfileInfo::Edge");
-      return (const FType*)0;
+      llvm_unreachable("Invalid ProfileInfo::Edge");
     }
=20
     // getEdge() - Creates an Edge from two BasicBlocks.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/RegionInfo.h
--- a/head/contrib/llvm/include/llvm/Analysis/RegionInfo.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/RegionInfo.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -681,7 +681,7 @@
   if (Node.isSubRegion())
     return OS << Node.getNodeAs<Region>()->getNameStr();
   else
-    return OS << Node.getNodeAs<BasicBlock>()->getNameStr();
+    return OS << Node.getNodeAs<BasicBlock>()->getName();
 }
 } // End llvm namespace
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/ScalarEvolution.h
--- a/head/contrib/llvm/include/llvm/Analysis/ScalarEvolution.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/ScalarEvolution.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -41,6 +41,7 @@
   class Type;
   class ScalarEvolution;
   class TargetData;
+  class TargetLibraryInfo;
   class LLVMContext;
   class Loop;
   class LoopInfo;
@@ -118,6 +119,10 @@
     ///
     bool isAllOnesValue() const;
=20
+    /// isNonConstantNegative - Return true if the specified scev is negat=
ed,
+    /// but not a constant.
+    bool isNonConstantNegative() const;
+
     /// print - Print out the internal representation of this scalar to the
     /// specified stream.  This should really only be used for debugging
     /// purposes.
@@ -135,7 +140,7 @@
       ID =3D X.FastID;
     }
     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
-                       FoldingSetNodeID &TempID) {
+                       unsigned IDHash, FoldingSetNodeID &TempID) {
       return ID =3D=3D X.FastID;
     }
     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
@@ -224,6 +229,10 @@
     ///
     TargetData *TD;
=20
+    /// TLI - The target library information for the target we are targeti=
ng.
+    ///
+    TargetLibraryInfo *TLI;
+
     /// DT - The dominator tree.
     ///
     DominatorTree *DT;
@@ -721,16 +730,21 @@
                                      const SCEV *LHS, const SCEV *RHS);
=20
     /// getSmallConstantTripCount - Returns the maximum trip count of this=
 loop
-    /// as a normal unsigned value, if possible. Returns 0 if the trip cou=
nt is
-    /// unknown or not constant.
-    unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitBlock);
+    /// as a normal unsigned value. Returns 0 if the trip count is unknown=
 or
+    /// not constant. This "trip count" assumes that control exits via
+    /// ExitingBlock. More precisely, it is the number of times that contr=
ol may
+    /// reach ExitingBlock before taking the branch. For loops with multip=
le
+    /// exits, it may not be the number times that the loop header execute=
s if
+    /// the loop exits prematurely via another branch.
+    unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
=20
     /// getSmallConstantTripMultiple - Returns the largest constant diviso=
r of
     /// the trip count of this loop as a normal unsigned value, if
     /// possible. This means that the actual trip count is always a multip=
le of
     /// the returned value (don't forget the trip count could very well be=
 zero
-    /// as well!).
-    unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitBlock);
+    /// as well!). As explained in the comments for getSmallConstantTripCo=
unt,
+    /// this assumes that control exits the loop via ExitingBlock.
+    unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBloc=
k);
=20
     // getExitCount - Get the expression for the number of loop iterations=
 for
     // which this loop is guaranteed not to exit via ExitingBlock. Otherwi=
se
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/ScalarEvolutionExpander.h
--- a/head/contrib/llvm/include/llvm/Analysis/ScalarEvolutionExpander.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/ScalarEvolutionExpander.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -22,6 +22,8 @@
 #include <set>
=20
 namespace llvm {
+  class TargetLowering;
+
   /// SCEVExpander - This class uses information about analyze scalars to
   /// rewrite expressions in canonical form.
   ///
@@ -58,6 +60,9 @@
     /// insert the IV increment at this position.
     Instruction *IVIncInsertPos;
=20
+    /// Phis that complete an IV chain. Reuse
+    std::set<AssertingVH<PHINode> > ChainedPhis;
+
     /// CanonicalMode - When true, expressions are expanded in "canonical"
     /// form. In particular, addrecs are expanded as arithmetic based on
     /// a canonical induction variable. When false, expression are expanded
@@ -100,6 +105,7 @@
       InsertedExpressions.clear();
       InsertedValues.clear();
       InsertedPostIncValues.clear();
+      ChainedPhis.clear();
     }
=20
     /// getOrInsertCanonicalInductionVariable - This method returns the
@@ -108,14 +114,18 @@
     /// starts at zero and steps by one on each iteration.
     PHINode *getOrInsertCanonicalInductionVariable(const Loop *L, Type *Ty=
);
=20
-    /// hoistStep - Utility for hoisting an IV increment.
-    static bool hoistStep(Instruction *IncV, Instruction *InsertPos,
-                          const DominatorTree *DT);
+    /// getIVIncOperand - Return the induction variable increment's IV ope=
rand.
+    Instruction *getIVIncOperand(Instruction *IncV, Instruction *InsertPos,
+                                 bool allowScale);
+
+    /// hoistIVInc - Utility for hoisting an IV increment.
+    bool hoistIVInc(Instruction *IncV, Instruction *InsertPos);
=20
     /// replaceCongruentIVs - replace congruent phis with their most canon=
ical
     /// representative. Return the number of phis eliminated.
     unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
-                                 SmallVectorImpl<WeakVH> &DeadInsts);
+                                 SmallVectorImpl<WeakVH> &DeadInsts,
+                                 const TargetLowering *TLI =3D NULL);
=20
     /// expandCodeFor - Insert code to directly compute the specified SCEV
     /// expression into the program.  The inserted code is inserted into t=
he
@@ -161,6 +171,16 @@
     void clearInsertPoint() {
       Builder.ClearInsertionPoint();
     }
+
+    /// isInsertedInstruction - Return true if the specified instruction w=
as
+    /// inserted by the code rewriter.  If so, the client should not modif=
y the
+    /// instruction.
+    bool isInsertedInstruction(Instruction *I) const {
+      return InsertedValues.count(I) || InsertedPostIncValues.count(I);
+    }
+
+    void setChainedPhi(PHINode *PN) { ChainedPhis.insert(PN); }
+
   private:
     LLVMContext &getContext() const { return SE.getContext(); }
=20
@@ -195,13 +215,6 @@
     /// result will be expanded to have that type, with a cast if necessar=
y.
     Value *expandCodeFor(const SCEV *SH, Type *Ty =3D 0);
=20
-    /// isInsertedInstruction - Return true if the specified instruction w=
as
-    /// inserted by the code rewriter.  If so, the client should not modif=
y the
-    /// instruction.
-    bool isInsertedInstruction(Instruction *I) const {
-      return InsertedValues.count(I) || InsertedPostIncValues.count(I);
-    }
-
     /// getRelevantLoop - Determine the most "relevant" loop for the given=
 SCEV.
     const Loop *getRelevantLoop(const SCEV *);
=20
@@ -244,6 +257,8 @@
                                        const Loop *L,
                                        Type *ExpandTy,
                                        Type *IntTy);
+    Value *expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
+                       Type *ExpandTy, Type *IntTy, bool useSubtract);
   };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/ScalarEvolutionExpressions.h
--- a/head/contrib/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/ScalarEvolutionExpressions.h	=
Tue Apr 17 11:51:51 2012 +0300
@@ -491,7 +491,6 @@
=20
     RetVal visitCouldNotCompute(const SCEVCouldNotCompute *S) {
       llvm_unreachable("Invalid use of SCEVCouldNotCompute!");
-      return RetVal();
     }
   };
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Analysi=
s/ValueTracking.h
--- a/head/contrib/llvm/include/llvm/Analysis/ValueTracking.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Analysis/ValueTracking.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -17,15 +17,15 @@
=20
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/Support/DataTypes.h"
-#include <string>
=20
 namespace llvm {
-  template <typename T> class SmallVectorImpl;
   class Value;
   class Instruction;
   class APInt;
   class TargetData;
- =20
+  class StringRef;
+  class MDNode;
+
   /// ComputeMaskedBits - Determine which of the bits specified in Mask are
   /// known to be either zero or one and return them in the KnownZero/Know=
nOne
   /// bit sets.  This code only analyzes bits in Mask, in order to short-c=
ircuit
@@ -36,10 +36,10 @@
   /// where V is a vector, the mask, known zero, and known one values are =
the
   /// same width as the vector element, and the bit is set only if it is t=
rue
   /// for all of the elements in the vector.
-  void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
-                         APInt &KnownOne, const TargetData *TD =3D 0,
-                         unsigned Depth =3D 0);
- =20
+  void ComputeMaskedBits(Value *V,  APInt &KnownZero, APInt &KnownOne,
+                         const TargetData *TD =3D 0, unsigned Depth =3D 0);
+  void computeMaskedBitsLoad(const MDNode &Ranges, APInt &KnownZero);
+
   /// ComputeSignBit - Determine whether the sign bit is known to be zero =
or
   /// one.  Convenience wrapper around ComputeMaskedBits.
   void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
@@ -48,8 +48,10 @@
   /// isPowerOfTwo - Return true if the given value is known to have exact=
ly one
   /// bit set when defined. For vectors return true if every element is kn=
own to
   /// be a power of two when defined.  Supports values with integer or poi=
nter
-  /// type and vectors of integers.
-  bool isPowerOfTwo(Value *V, const TargetData *TD =3D 0, unsigned Depth =
=3D 0);
+  /// type and vectors of integers.  If 'OrZero' is set then returns true =
if the
+  /// given value is either a power of two or zero.
+  bool isPowerOfTwo(Value *V, const TargetData *TD =3D 0, bool OrZero =3D =
false,
+                    unsigned Depth =3D 0);
=20
   /// isKnownNonZero - Return true if the given value is known to be non-z=
ero
   /// when defined.  For vectors return true if every element is known to =
be
@@ -123,16 +125,15 @@
     return GetPointerBaseWithConstantOffset(const_cast<Value*>(Ptr), Offse=
t,TD);
   }
  =20
-  /// GetConstantStringInfo - This function computes the length of a
+  /// getConstantStringInfo - This function computes the length of a
   /// null-terminated C string pointed to by V.  If successful, it returns=
 true
-  /// and returns the string in Str.  If unsuccessful, it returns false.  =
If
-  /// StopAtNul is set to true (the default), the returned string is trunc=
ated
-  /// by a nul character in the global.  If StopAtNul is false, the nul
-  /// character is included in the result string.
-  bool GetConstantStringInfo(const Value *V, std::string &Str,
-                             uint64_t Offset =3D 0,
-                             bool StopAtNul =3D true);
-                       =20
+  /// and returns the string in Str.  If unsuccessful, it returns false.  =
This
+  /// does not include the trailing nul character by default.  If TrimAtNu=
l is
+  /// set to false, then this returns any trailing nul characters as well =
as any
+  /// other characters that come after it.
+  bool getConstantStringInfo(const Value *V, StringRef &Str,
+                             uint64_t Offset =3D 0, bool TrimAtNul =3D tru=
e);
+
   /// GetStringLength - If we can compute the length of the string pointed=
 to by
   /// the specified pointer, return 'len+1'.  If we can't, return 0.
   uint64_t GetStringLength(Value *V);
@@ -154,6 +155,27 @@
   /// are lifetime markers.
   bool onlyUsedByLifetimeMarkers(const Value *V);
=20
+  /// isSafeToSpeculativelyExecute - Return true if the instruction does n=
ot
+  /// have any effects besides calculating the result and does not have
+  /// undefined behavior.
+  ///
+  /// This method never returns true for an instruction that returns true =
for
+  /// mayHaveSideEffects; however, this method also does some other checks=
 in
+  /// addition. It checks for undefined behavior, like dividing by zero or
+  /// loading from an invalid pointer (but not for undefined results, like=
 a
+  /// shift with a shift amount larger than the width of the result). It c=
hecks
+  /// for malloc and alloca because speculatively executing them might cau=
se a
+  /// memory leak. It also returns false for instructions related to contr=
ol
+  /// flow, specifically terminators and PHI nodes.
+  ///
+  /// This method only looks at the instruction itself and its operands, s=
o if
+  /// this method returns true, it is safe to move the instruction as long=
 as
+  /// the correct dominance relationships for the operands and users hold.
+  /// However, this method can return true for instructions that read memo=
ry;
+  /// for such instructions, moving them may change the resulting value.
+  bool isSafeToSpeculativelyExecute(const Value *V,
+                                    const TargetData *TD =3D 0);
+
 } // end namespace llvm
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Argumen=
t.h
--- a/head/contrib/llvm/include/llvm/Argument.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm/Argument.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -30,6 +30,7 @@
 /// the function was called with.
 /// @brief LLVM Argument representation =20
 class Argument : public Value, public ilist_node<Argument> {
+  virtual void anchor();
   Function *Parent;
=20
   friend class SymbolTableListTraits<Argument, Function>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Assembl=
y/AssemblyAnnotationWriter.h
--- a/head/contrib/llvm/include/llvm/Assembly/AssemblyAnnotationWriter.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Assembly/AssemblyAnnotationWriter.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 class Function;
 class BasicBlock;
 class Instruction;
-class raw_ostream;
+class Value;
 class formatted_raw_ostream;
=20
 class AssemblyAnnotationWriter {
@@ -32,30 +32,30 @@
=20
   /// emitFunctionAnnot - This may be implemented to emit a string right b=
efore
   /// the start of a function.
-  virtual void emitFunctionAnnot(const Function *F,
-                                 formatted_raw_ostream &OS) {}
+  virtual void emitFunctionAnnot(const Function *,
+                                 formatted_raw_ostream &) {}
=20
   /// emitBasicBlockStartAnnot - This may be implemented to emit a string =
right
   /// after the basic block label, but before the first instruction in the
   /// block.
-  virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
-                                        formatted_raw_ostream &OS) {
+  virtual void emitBasicBlockStartAnnot(const BasicBlock *,
+                                        formatted_raw_ostream &) {
   }
=20
   /// emitBasicBlockEndAnnot - This may be implemented to emit a string ri=
ght
   /// after the basic block.
-  virtual void emitBasicBlockEndAnnot(const BasicBlock *BB,
-                                      formatted_raw_ostream &OS) {
+  virtual void emitBasicBlockEndAnnot(const BasicBlock *,
+                                      formatted_raw_ostream &) {
   }
=20
   /// emitInstructionAnnot - This may be implemented to emit a string right
   /// before an instruction is emitted.
-  virtual void emitInstructionAnnot(const Instruction *I,=20
-                                    formatted_raw_ostream &OS) {}
+  virtual void emitInstructionAnnot(const Instruction *,=20
+                                    formatted_raw_ostream &) {}
=20
   /// printInfoComment - This may be implemented to emit a comment to the
   /// right of an instruction or global value.
-  virtual void printInfoComment(const Value &V, formatted_raw_ostream &OS)=
 {}
+  virtual void printInfoComment(const Value &, formatted_raw_ostream &) {}
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Assembl=
y/Parser.h
--- a/head/contrib/llvm/include/llvm/Assembly/Parser.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/Assembly/Parser.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -21,7 +21,6 @@
 class Module;
 class MemoryBuffer;
 class SMDiagnostic;
-class raw_ostream;
 class LLVMContext;
=20
 /// This function is the main interface to the LLVM Assembly Parser. It pa=
rses
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Assembl=
y/Writer.h
--- a/head/contrib/llvm/include/llvm/Assembly/Writer.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/Assembly/Writer.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -19,7 +19,6 @@
=20
 namespace llvm {
=20
-class Type;
 class Module;
 class Value;
 class raw_ostream;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Attribu=
tes.h
--- a/head/contrib/llvm/include/llvm/Attributes.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/include/llvm/Attributes.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -22,8 +22,66 @@
 namespace llvm {
 class Type;
=20
+namespace Attribute {
+/// We use this proxy POD type to allow constructing Attributes constants
+/// using initializer lists. Do not use this class directly.
+struct AttrConst {
+  uint64_t v;
+  AttrConst operator | (const AttrConst Attrs) const {
+    AttrConst Res =3D {v | Attrs.v};
+    return Res;
+  }
+  AttrConst operator ~ () const {
+    AttrConst Res =3D {~v};
+    return Res;
+  }
+};
+}  // namespace Attribute
+
+
 /// Attributes - A bitset of attributes.
-typedef unsigned Attributes;
+class Attributes {
+ public:
+  Attributes() : Bits(0) { }
+  explicit Attributes(uint64_t Val) : Bits(Val) { }
+  /*implicit*/ Attributes(Attribute::AttrConst Val) : Bits(Val.v) { }
+  Attributes(const Attributes &Attrs) : Bits(Attrs.Bits) { }
+  // This is a "safe bool() operator".
+  operator const void *() const { return Bits ? this : 0; }
+  bool isEmptyOrSingleton() const { return (Bits & (Bits - 1)) =3D=3D 0; }
+  Attributes &operator =3D (const Attributes &Attrs) {
+    Bits =3D Attrs.Bits;
+    return *this;
+  }
+  bool operator =3D=3D (const Attributes &Attrs) const {
+    return Bits =3D=3D Attrs.Bits;
+  }
+  bool operator !=3D (const Attributes &Attrs) const {
+    return Bits !=3D Attrs.Bits;
+  }
+  Attributes operator | (const Attributes &Attrs) const {
+    return Attributes(Bits | Attrs.Bits);
+  }
+  Attributes operator & (const Attributes &Attrs) const {
+    return Attributes(Bits & Attrs.Bits);
+  }
+  Attributes operator ^ (const Attributes &Attrs) const {
+    return Attributes(Bits ^ Attrs.Bits);
+  }
+  Attributes &operator |=3D (const Attributes &Attrs) {
+    Bits |=3D Attrs.Bits;
+    return *this;
+  }
+  Attributes &operator &=3D (const Attributes &Attrs) {
+    Bits &=3D Attrs.Bits;
+    return *this;
+  }
+  Attributes operator ~ () const { return Attributes(~Bits); }
+  uint64_t Raw() const { return Bits; }
+ private:
+  // Currently, we need less than 64 bits.
+  uint64_t Bits;
+};
=20
 namespace Attribute {
=20
@@ -33,44 +91,55 @@
 /// results or the function itself.
 /// @brief Function attributes.
=20
-const Attributes None      =3D 0;     ///< No attributes have been set
-const Attributes ZExt      =3D 1<<0;  ///< Zero extended before/after call
-const Attributes SExt      =3D 1<<1;  ///< Sign extended before/after call
-const Attributes NoReturn  =3D 1<<2;  ///< Mark the function as not return=
ing
-const Attributes InReg     =3D 1<<3;  ///< Force argument to be passed in =
register
-const Attributes StructRet =3D 1<<4;  ///< Hidden pointer to structure to =
return
-const Attributes NoUnwind  =3D 1<<5;  ///< Function doesn't unwind stack
-const Attributes NoAlias   =3D 1<<6;  ///< Considered to not alias after c=
all
-const Attributes ByVal     =3D 1<<7;  ///< Pass structure by value
-const Attributes Nest      =3D 1<<8;  ///< Nested function static chain
-const Attributes ReadNone  =3D 1<<9;  ///< Function does not access memory
-const Attributes ReadOnly  =3D 1<<10; ///< Function only reads from memory
-const Attributes NoInline        =3D 1<<11; ///< inline=3Dnever
-const Attributes AlwaysInline    =3D 1<<12; ///< inline=3Dalways
-const Attributes OptimizeForSize =3D 1<<13; ///< opt_size
-const Attributes StackProtect    =3D 1<<14; ///< Stack protection.
-const Attributes StackProtectReq =3D 1<<15; ///< Stack protection required.
-const Attributes Alignment =3D 31<<16; ///< Alignment of parameter (5 bits)
+// We declare AttrConst objects that will be used throughout the code
+// and also raw uint64_t objects with _i suffix to be used below for other
+// constant declarations. This is done to avoid static CTORs and at the sa=
me
+// time to keep type-safety of Attributes.
+#define DECLARE_LLVM_ATTRIBUTE(name, value) \
+  const uint64_t name##_i =3D value; \
+  const AttrConst name =3D {value};
+
+DECLARE_LLVM_ATTRIBUTE(None,0)    ///< No attributes have been set
+DECLARE_LLVM_ATTRIBUTE(ZExt,1<<0) ///< Zero extended before/after call
+DECLARE_LLVM_ATTRIBUTE(SExt,1<<1) ///< Sign extended before/after call
+DECLARE_LLVM_ATTRIBUTE(NoReturn,1<<2) ///< Mark the function as not return=
ing
+DECLARE_LLVM_ATTRIBUTE(InReg,1<<3) ///< Force argument to be passed in reg=
ister
+DECLARE_LLVM_ATTRIBUTE(StructRet,1<<4) ///< Hidden pointer to structure to=
 return
+DECLARE_LLVM_ATTRIBUTE(NoUnwind,1<<5) ///< Function doesn't unwind stack
+DECLARE_LLVM_ATTRIBUTE(NoAlias,1<<6) ///< Considered to not alias after ca=
ll
+DECLARE_LLVM_ATTRIBUTE(ByVal,1<<7) ///< Pass structure by value
+DECLARE_LLVM_ATTRIBUTE(Nest,1<<8) ///< Nested function static chain
+DECLARE_LLVM_ATTRIBUTE(ReadNone,1<<9) ///< Function does not access memory
+DECLARE_LLVM_ATTRIBUTE(ReadOnly,1<<10) ///< Function only reads from memory
+DECLARE_LLVM_ATTRIBUTE(NoInline,1<<11) ///< inline=3Dnever
+DECLARE_LLVM_ATTRIBUTE(AlwaysInline,1<<12) ///< inline=3Dalways
+DECLARE_LLVM_ATTRIBUTE(OptimizeForSize,1<<13) ///< opt_size
+DECLARE_LLVM_ATTRIBUTE(StackProtect,1<<14) ///< Stack protection.
+DECLARE_LLVM_ATTRIBUTE(StackProtectReq,1<<15) ///< Stack protection requir=
ed.
+DECLARE_LLVM_ATTRIBUTE(Alignment,31<<16) ///< Alignment of parameter (5 bi=
ts)
                                      // stored as log2 of alignment with +=
1 bias
                                      // 0 means unaligned different from a=
lign 1
-const Attributes NoCapture =3D 1<<21; ///< Function creates no aliases of =
pointer
-const Attributes NoRedZone =3D 1<<22; /// disable redzone
-const Attributes NoImplicitFloat =3D 1<<23; /// disable implicit floating =
point
-                                          /// instructions.
-const Attributes Naked           =3D 1<<24; ///< Naked function
-const Attributes InlineHint      =3D 1<<25; ///< source said inlining was
-                                          ///desirable
-const Attributes StackAlignment  =3D 7<<26; ///< Alignment of stack for
-                                          ///function (3 bits) stored as l=
og2
-                                          ///of alignment with +1 bias
-                                          ///0 means unaligned (different =
from
-                                          ///alignstack(1))
-const Attributes ReturnsTwice    =3D 1<<29; ///< Function can return twice
-const Attributes UWTable     =3D 1<<30;     ///< Function must be in a unw=
ind
-                                          ///table
-const Attributes NonLazyBind =3D 1U<<31;    ///< Function is called early =
and/or
-                                          ///  often, so lazy binding isn't
-                                          ///  worthwhile.
+DECLARE_LLVM_ATTRIBUTE(NoCapture,1<<21) ///< Function creates no aliases o=
f pointer
+DECLARE_LLVM_ATTRIBUTE(NoRedZone,1<<22) /// disable redzone
+DECLARE_LLVM_ATTRIBUTE(NoImplicitFloat,1<<23) /// disable implicit floatin=
g point
+                                           /// instructions.
+DECLARE_LLVM_ATTRIBUTE(Naked,1<<24) ///< Naked function
+DECLARE_LLVM_ATTRIBUTE(InlineHint,1<<25) ///< source said inlining was
+                                           ///desirable
+DECLARE_LLVM_ATTRIBUTE(StackAlignment,7<<26) ///< Alignment of stack for
+                                           ///function (3 bits) stored as =
log2
+                                           ///of alignment with +1 bias
+                                           ///0 means unaligned (different=
 from
+                                           ///alignstack=3D {1))
+DECLARE_LLVM_ATTRIBUTE(ReturnsTwice,1<<29) ///< Function can return twice
+DECLARE_LLVM_ATTRIBUTE(UWTable,1<<30) ///< Function must be in a unwind
+                                           ///table
+DECLARE_LLVM_ATTRIBUTE(NonLazyBind,1U<<31) ///< Function is called early a=
nd/or
+                                            /// often, so lazy binding isn=
't
+                                            /// worthwhile.
+DECLARE_LLVM_ATTRIBUTE(AddressSafety,1ULL<<32) ///< Address safety checkin=
g is on.
+
+#undef DECLARE_LLVM_ATTRIBUTE
=20
 /// Note that uwtable is about the ABI or the user mandating an entry in t=
he
 /// unwind table. The nounwind attribute is about an exception passing by =
the
@@ -85,24 +154,26 @@
 /// uwtable + nounwind =3D Needs an entry because the ABI says so.
=20
 /// @brief Attributes that only apply to function parameters.
-const Attributes ParameterOnly =3D ByVal | Nest | StructRet | NoCapture;
+const AttrConst ParameterOnly =3D {ByVal_i | Nest_i |
+    StructRet_i | NoCapture_i};
=20
 /// @brief Attributes that may be applied to the function itself.  These c=
annot
 /// be used on return values or function parameters.
-const Attributes FunctionOnly =3D NoReturn | NoUnwind | ReadNone | ReadOnl=
y |
-  NoInline | AlwaysInline | OptimizeForSize | StackProtect | StackProtectR=
eq |
-  NoRedZone | NoImplicitFloat | Naked | InlineHint | StackAlignment |
-  UWTable | NonLazyBind | ReturnsTwice;
+const AttrConst FunctionOnly =3D {NoReturn_i | NoUnwind_i | ReadNone_i |
+  ReadOnly_i | NoInline_i | AlwaysInline_i | OptimizeForSize_i |
+  StackProtect_i | StackProtectReq_i | NoRedZone_i | NoImplicitFloat_i |
+  Naked_i | InlineHint_i | StackAlignment_i |
+  UWTable_i | NonLazyBind_i | ReturnsTwice_i | AddressSafety_i};
=20
 /// @brief Parameter attributes that do not apply to vararg call arguments.
-const Attributes VarArgsIncompatible =3D StructRet;
+const AttrConst VarArgsIncompatible =3D {StructRet_i};
=20
 /// @brief Attributes that are mutually incompatible.
-const Attributes MutuallyIncompatible[4] =3D {
-  ByVal | InReg | Nest | StructRet,
-  ZExt  | SExt,
-  ReadNone | ReadOnly,
-  NoInline | AlwaysInline
+const AttrConst MutuallyIncompatible[4] =3D {
+  {ByVal_i | InReg_i | Nest_i | StructRet_i},
+  {ZExt_i  | SExt_i},
+  {ReadNone_i | ReadOnly_i},
+  {NoInline_i | AlwaysInline_i}
 };
=20
 /// @brief Which attributes cannot be applied to a type.
@@ -113,20 +184,20 @@
 inline Attributes constructAlignmentFromInt(unsigned i) {
   // Default alignment, allow the target to define how to align it.
   if (i =3D=3D 0)
-    return 0;
+    return None;
=20
   assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
   assert(i <=3D 0x40000000 && "Alignment too large.");
-  return (Log2_32(i)+1) << 16;
+  return Attributes((Log2_32(i)+1) << 16);
 }
=20
 /// This returns the alignment field of an attribute as a byte alignment v=
alue.
 inline unsigned getAlignmentFromAttrs(Attributes A) {
   Attributes Align =3D A & Attribute::Alignment;
-  if (Align =3D=3D 0)
+  if (!Align)
     return 0;
=20
-  return 1U << ((Align >> 16) - 1);
+  return 1U << ((Align.Raw() >> 16) - 1);
 }
=20
 /// This turns an int stack alignment (which must be a power of 2) into
@@ -134,21 +205,21 @@
 inline Attributes constructStackAlignmentFromInt(unsigned i) {
   // Default alignment, allow the target to define how to align it.
   if (i =3D=3D 0)
-    return 0;
+    return None;
=20
   assert(isPowerOf2_32(i) && "Alignment must be a power of two.");
   assert(i <=3D 0x100 && "Alignment too large.");
-  return (Log2_32(i)+1) << 26;
+  return Attributes((Log2_32(i)+1) << 26);
 }
=20
 /// This returns the stack alignment field of an attribute as a byte align=
ment
 /// value.
 inline unsigned getStackAlignmentFromAttrs(Attributes A) {
   Attributes StackAlign =3D A & Attribute::StackAlignment;
-  if (StackAlign =3D=3D 0)
+  if (!StackAlign)
     return 0;
=20
-  return 1U << ((StackAlign >> 26) - 1);
+  return 1U << ((StackAlign.Raw() >> 26) - 1);
 }
=20
=20
@@ -242,7 +313,7 @@
   /// paramHasAttr - Return true if the specified parameter index has the
   /// specified attribute set.
   bool paramHasAttr(unsigned Idx, Attributes Attr) const {
-    return (getAttributes(Idx) & Attr) !=3D 0;
+    return getAttributes(Idx) & Attr;
   }
=20
   /// getParamAlignment - Return the alignment for the specified function
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/AutoUpg=
rade.h
--- a/head/contrib/llvm/include/llvm/AutoUpgrade.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/AutoUpgrade.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -39,14 +39,6 @@
   /// This checks for global variables which should be upgraded. It return=
s true
   /// if it requires upgrading.
   bool UpgradeGlobalVariable(GlobalVariable *GV);
-
-  /// This function checks debug info intrinsics. If an intrinsic is inval=
id
-  /// then this function simply removes the intrinsic.=20
-  void CheckDebugInfoIntrinsics(Module *M);
- =20
-  /// This function upgrades the old pre-3.0 exception handling system to =
the
-  /// new one. N.B. This will be removed in 3.1.
-  void UpgradeExceptionHandling(Module *M);
 } // End llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/BasicBl=
ock.h
--- a/head/contrib/llvm/include/llvm/BasicBlock.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/include/llvm/BasicBlock.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -110,12 +110,6 @@
   const Function *getParent() const { return Parent; }
         Function *getParent()       { return Parent; }
=20
-  /// use_back - Specialize the methods defined in Value, as we know that =
an
-  /// BasicBlock can only be used by Users (specifically terminators
-  /// and BlockAddress's).
-  User       *use_back()       { return cast<User>(*use_begin());}
-  const User *use_back() const { return cast<User>(*use_begin());}
-
   /// getTerminator() - If this is a well formed basic block, then this re=
turns
   /// a pointer to the terminator instruction.  If it is not, then you get=
 a
   /// null pointer back.
@@ -274,6 +268,7 @@
   /// getLandingPadInst() - Return the landingpad instruction associated w=
ith
   /// the landing pad.
   LandingPadInst *getLandingPadInst();
+  const LandingPadInst *getLandingPadInst() const;
=20
 private:
   /// AdjustBlockAddressRefCount - BasicBlock stores the number of BlockAd=
dress
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Bitcode=
/Archive.h
--- a/head/contrib/llvm/include/llvm/Bitcode/Archive.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/Bitcode/Archive.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -394,7 +394,7 @@
     /// @brief Look up multiple symbols in the archive.
     bool findModulesDefiningSymbols(
       std::set<std::string>& symbols,     ///< Symbols to be sought
-      std::set<Module*>& modules,         ///< The modules matching \p sym=
bols
+      SmallVectorImpl<Module*>& modules,  ///< The modules matching \p sym=
bols
       std::string* ErrMessage             ///< Error msg storage, if non-z=
ero
     );
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Bitcode=
/BitCodes.h
--- a/head/contrib/llvm/include/llvm/Bitcode/BitCodes.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Bitcode/BitCodes.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -20,6 +20,7 @@
=20
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cassert>
=20
 namespace llvm {
@@ -114,7 +115,6 @@
   bool hasEncodingData() const { return hasEncodingData(getEncoding()); }
   static bool hasEncodingData(Encoding E) {
     switch (E) {
-    default: assert(0 && "Unknown encoding");
     case Fixed:
     case VBR:
       return true;
@@ -123,6 +123,7 @@
     case Blob:
       return false;
     }
+    llvm_unreachable("Invalid encoding");
   }
=20
   /// isChar6 - Return true if this character is legal in the Char6 encodi=
ng.
@@ -139,8 +140,7 @@
     if (C >=3D '0' && C <=3D '9') return C-'0'+26+26;
     if (C =3D=3D '.') return 62;
     if (C =3D=3D '_') return 63;
-    assert(0 && "Not a value Char6 character!");
-    return 0;
+    llvm_unreachable("Not a value Char6 character!");
   }
=20
   static char DecodeChar6(unsigned V) {
@@ -150,17 +150,18 @@
     if (V < 26+26+10) return V-26-26+'0';
     if (V =3D=3D 62) return '.';
     if (V =3D=3D 63) return '_';
-    assert(0 && "Not a value Char6 character!");
-    return ' ';
+    llvm_unreachable("Not a value Char6 character!");
   }
=20
 };
=20
+template <> struct isPodLike<BitCodeAbbrevOp> { static const bool value=3D=
true; };
+
 /// BitCodeAbbrev - This class represents an abbreviation record.  An
 /// abbreviation allows a complex record that has redundancy to be stored =
in a
 /// specialized format instead of the fully-general, fully-vbr, format.
 class BitCodeAbbrev {
-  SmallVector<BitCodeAbbrevOp, 8> OperandList;
+  SmallVector<BitCodeAbbrevOp, 32> OperandList;
   unsigned char RefCount; // Number of things using this.
   ~BitCodeAbbrev() {}
 public:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Bitcode=
/BitstreamReader.h
--- a/head/contrib/llvm/include/llvm/Bitcode/BitstreamReader.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Bitcode/BitstreamReader.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,7 +15,10 @@
 #ifndef BITSTREAM_READER_H
 #define BITSTREAM_READER_H
=20
+#include "llvm/ADT/OwningPtr.h"
 #include "llvm/Bitcode/BitCodes.h"
+#include "llvm/Support/Endian.h"
+#include "llvm/Support/StreamableMemoryObject.h"
 #include <climits>
 #include <string>
 #include <vector>
@@ -36,9 +39,7 @@
     std::vector<std::pair<unsigned, std::string> > RecordNames;
   };
 private:
-  /// FirstChar/LastChar - This remembers the first and last bytes of the
-  /// stream.
-  const unsigned char *FirstChar, *LastChar;
+  OwningPtr<StreamableMemoryObject> BitcodeBytes;
  =20
   std::vector<BlockInfo> BlockInfoRecords;
=20
@@ -47,10 +48,10 @@
   /// uses this.
   bool IgnoreBlockInfoNames;
  =20
-  BitstreamReader(const BitstreamReader&);  // NOT IMPLEMENTED
-  void operator=3D(const BitstreamReader&);  // NOT IMPLEMENTED
+  BitstreamReader(const BitstreamReader&);  // DO NOT IMPLEMENT
+  void operator=3D(const BitstreamReader&);  // DO NOT IMPLEMENT
 public:
-  BitstreamReader() : FirstChar(0), LastChar(0), IgnoreBlockInfoNames(true=
) {
+  BitstreamReader() : IgnoreBlockInfoNames(true) {
   }
=20
   BitstreamReader(const unsigned char *Start, const unsigned char *End) {
@@ -58,12 +59,17 @@
     init(Start, End);
   }
=20
+  BitstreamReader(StreamableMemoryObject *bytes) {
+    BitcodeBytes.reset(bytes);
+  }
+
   void init(const unsigned char *Start, const unsigned char *End) {
-    FirstChar =3D Start;
-    LastChar =3D End;
     assert(((End-Start) & 3) =3D=3D 0 &&"Bitcode stream not a multiple of =
4 bytes");
+    BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
   }
=20
+  StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
+
   ~BitstreamReader() {
     // Free the BlockInfoRecords.
     while (!BlockInfoRecords.empty()) {
@@ -75,9 +81,6 @@
       BlockInfoRecords.pop_back();
     }
   }
- =20
-  const unsigned char *getFirstChar() const { return FirstChar; }
-  const unsigned char *getLastChar() const { return LastChar; }
=20
   /// CollectBlockInfoNames - This is called by clients that want block/re=
cord
   /// name information.
@@ -122,7 +125,7 @@
 class BitstreamCursor {
   friend class Deserializer;
   BitstreamReader *BitStream;
-  const unsigned char *NextChar;
+  size_t NextChar;
  =20
   /// CurWord - This is the current data we have pulled from the stream bu=
t have
   /// not returned to the client.
@@ -156,8 +159,7 @@
   }
  =20
   explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
-    NextChar =3D R.getFirstChar();
-    assert(NextChar && "Bitstream not initialized yet");
+    NextChar =3D 0;
     CurWord =3D 0;
     BitsInCurWord =3D 0;
     CurCodeSize =3D 2;
@@ -167,8 +169,7 @@
     freeState();
    =20
     BitStream =3D &R;
-    NextChar =3D R.getFirstChar();
-    assert(NextChar && "Bitstream not initialized yet");
+    NextChar =3D 0;
     CurWord =3D 0;
     BitsInCurWord =3D 0;
     CurCodeSize =3D 2;
@@ -225,13 +226,39 @@
   /// GetAbbrevIDWidth - Return the number of bits used to encode an abbre=
v #.
   unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
  =20
-  bool AtEndOfStream() const {
-    return NextChar =3D=3D BitStream->getLastChar() && BitsInCurWord =3D=
=3D 0;
+  bool isEndPos(size_t pos) {
+    return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(=
pos));
+  }
+
+  bool canSkipToPos(size_t pos) const {
+    // pos can be skipped to if it is a valid address or one byte past the=
 end.
+    return pos =3D=3D 0 || BitStream->getBitcodeBytes().isValidAddress(
+        static_cast<uint64_t>(pos - 1));
+  }
+
+  unsigned char getByte(size_t pos) {
+    uint8_t byte =3D -1;
+    BitStream->getBitcodeBytes().readByte(pos, &byte);
+    return byte;
+  }
+
+  uint32_t getWord(size_t pos) {
+    uint8_t buf[sizeof(uint32_t)];
+    memset(buf, 0xFF, sizeof(buf));
+    BitStream->getBitcodeBytes().readBytes(pos,
+                                           sizeof(buf),
+                                           buf,
+                                           NULL);
+    return *reinterpret_cast<support::ulittle32_t *>(buf);
+  }
+
+  bool AtEndOfStream() {
+    return isEndPos(NextChar) && BitsInCurWord =3D=3D 0;
   }
  =20
   /// GetCurrentBitNo - Return the bit # of the bit we are reading.
   uint64_t GetCurrentBitNo() const {
-    return (NextChar-BitStream->getFirstChar())*CHAR_BIT - BitsInCurWord;
+    return NextChar*CHAR_BIT - BitsInCurWord;
   }
  =20
   BitstreamReader *getBitStreamReader() {
@@ -246,12 +273,10 @@
   void JumpToBit(uint64_t BitNo) {
     uintptr_t ByteNo =3D uintptr_t(BitNo/8) & ~3;
     uintptr_t WordBitNo =3D uintptr_t(BitNo) & 31;
-    assert(ByteNo <=3D (uintptr_t)(BitStream->getLastChar()-
-                                 BitStream->getFirstChar()) &&
-           "Invalid location");
+    assert(canSkipToPos(ByteNo) && "Invalid location");
    =20
     // Move the cursor to the right word.
-    NextChar =3D BitStream->getFirstChar()+ByteNo;
+    NextChar =3D ByteNo;
     BitsInCurWord =3D 0;
     CurWord =3D 0;
    =20
@@ -272,7 +297,7 @@
     }
=20
     // If we run out of data, stop at the end of the stream.
-    if (NextChar =3D=3D BitStream->getLastChar()) {
+    if (isEndPos(NextChar)) {
       CurWord =3D 0;
       BitsInCurWord =3D 0;
       return 0;
@@ -281,8 +306,7 @@
     unsigned R =3D CurWord;
=20
     // Read the next word from the stream.
-    CurWord =3D (NextChar[0] <<  0) | (NextChar[1] << 8) |
-              (NextChar[2] << 16) | (NextChar[3] << 24);
+    CurWord =3D getWord(NextChar);
     NextChar +=3D 4;
=20
     // Extract NumBits-BitsInCurWord from what we just read.
@@ -376,9 +400,8 @@
=20
     // Check that the block wasn't partially defined, and that the offset =
isn't
     // bogus.
-    const unsigned char *const SkipTo =3D NextChar + NumWords*4;
-    if (AtEndOfStream() || SkipTo > BitStream->getLastChar() ||
-                           SkipTo < BitStream->getFirstChar())
+    size_t SkipTo =3D NextChar + NumWords*4;
+    if (AtEndOfStream() || !canSkipToPos(SkipTo))
       return true;
=20
     NextChar =3D SkipTo;
@@ -409,8 +432,7 @@
     if (NumWordsP) *NumWordsP =3D NumWords;
=20
     // Validate that this block is sane.
-    if (CurCodeSize =3D=3D 0 || AtEndOfStream() ||
-        NextChar+NumWords*4 > BitStream->getLastChar())
+    if (CurCodeSize =3D=3D 0 || AtEndOfStream())
       return true;
=20
     return false;
@@ -455,10 +477,10 @@
   void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
                             SmallVectorImpl<uint64_t> &Vals) {
     assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
-   =20
+
     // Decode the value as we are commanded.
     switch (Op.getEncoding()) {
-    default: assert(0 && "Unknown encoding!");
+    default: llvm_unreachable("Unknown encoding!");
     case BitCodeAbbrevOp::Fixed:
       Vals.push_back(Read((unsigned)Op.getEncodingData()));
       break;
@@ -512,24 +534,25 @@
         SkipToWord();  // 32-bit alignment
=20
         // Figure out where the end of this blob will be including tail pa=
dding.
-        const unsigned char *NewEnd =3D NextChar+((NumElts+3)&~3);
+        size_t NewEnd =3D NextChar+((NumElts+3)&~3);
        =20
         // If this would read off the end of the bitcode file, just set the
         // record to empty and return.
-        if (NewEnd > BitStream->getLastChar()) {
+        if (!canSkipToPos(NewEnd)) {
           Vals.append(NumElts, 0);
-          NextChar =3D BitStream->getLastChar();
+          NextChar =3D BitStream->getBitcodeBytes().getExtent();
           break;
         }
        =20
         // Otherwise, read the number of bytes.  If we can return a refere=
nce to
         // the data, do so to avoid copying it.
         if (BlobStart) {
-          *BlobStart =3D (const char*)NextChar;
+          *BlobStart =3D (const char*)BitStream->getBitcodeBytes().getPoin=
ter(
+              NextChar, NumElts);
           *BlobLen =3D NumElts;
         } else {
           for (; NumElts; ++NextChar, --NumElts)
-            Vals.push_back(*NextChar);
+            Vals.push_back(getByte(NextChar));
         }
         // Skip over tail padding.
         NextChar =3D NewEnd;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Bitcode=
/BitstreamWriter.h
--- a/head/contrib/llvm/include/llvm/Bitcode/BitstreamWriter.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Bitcode/BitstreamWriter.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -16,13 +16,14 @@
 #define BITSTREAM_WRITER_H
=20
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Bitcode/BitCodes.h"
 #include <vector>
=20
 namespace llvm {
=20
 class BitstreamWriter {
-  std::vector<unsigned char> &Out;
+  SmallVectorImpl<char> &Out;
=20
   /// CurBit - Always between 0 and 31 inclusive, specifies the next bit t=
o use.
   unsigned CurBit;
@@ -59,8 +60,40 @@
   };
   std::vector<BlockInfo> BlockInfoRecords;
=20
+  // BackpatchWord - Backpatch a 32-bit word in the output with the specif=
ied
+  // value.
+  void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
+    Out[ByteNo++] =3D (unsigned char)(NewWord >>  0);
+    Out[ByteNo++] =3D (unsigned char)(NewWord >>  8);
+    Out[ByteNo++] =3D (unsigned char)(NewWord >> 16);
+    Out[ByteNo  ] =3D (unsigned char)(NewWord >> 24);
+  }
+
+  void WriteByte(unsigned char Value) {
+    Out.push_back(Value);
+  }
+
+  void WriteWord(unsigned Value) {
+    unsigned char Bytes[4] =3D {
+      (unsigned char)(Value >>  0),
+      (unsigned char)(Value >>  8),
+      (unsigned char)(Value >> 16),
+      (unsigned char)(Value >> 24) };
+    Out.append(&Bytes[0], &Bytes[4]);
+  }
+
+  unsigned GetBufferOffset() const {
+    return Out.size();
+  }
+
+  unsigned GetWordIndex() const {
+    unsigned Offset =3D GetBufferOffset();
+    assert((Offset & 3) =3D=3D 0 && "Not 32-bit aligned");
+    return Offset / 4;
+  }
+
 public:
-  explicit BitstreamWriter(std::vector<unsigned char> &O)
+  explicit BitstreamWriter(SmallVectorImpl<char> &O)
     : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
=20
   ~BitstreamWriter() {
@@ -78,10 +111,8 @@
     }
   }
=20
-  std::vector<unsigned char> &getBuffer() { return Out; }
-
   /// \brief Retrieve the current position in the stream, in bits.
-  uint64_t GetCurrentBitNo() const { return Out.size() * 8 + CurBit; }
+  uint64_t GetCurrentBitNo() const { return GetBufferOffset() * 8 + CurBit=
; }
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Basic Primitives for emitting bits to the stream.
@@ -97,11 +128,7 @@
     }
=20
     // Add the current word.
-    unsigned V =3D CurValue;
-    Out.push_back((unsigned char)(V >>  0));
-    Out.push_back((unsigned char)(V >>  8));
-    Out.push_back((unsigned char)(V >> 16));
-    Out.push_back((unsigned char)(V >> 24));
+    WriteWord(CurValue);
=20
     if (CurBit)
       CurValue =3D Val >> (32-CurBit);
@@ -121,11 +148,7 @@
=20
   void FlushToWord() {
     if (CurBit) {
-      unsigned V =3D CurValue;
-      Out.push_back((unsigned char)(V >>  0));
-      Out.push_back((unsigned char)(V >>  8));
-      Out.push_back((unsigned char)(V >> 16));
-      Out.push_back((unsigned char)(V >> 24));
+      WriteWord(CurValue);
       CurBit =3D 0;
       CurValue =3D 0;
     }
@@ -164,15 +187,6 @@
     Emit(Val, CurCodeSize);
   }
=20
-  // BackpatchWord - Backpatch a 32-bit word in the output with the specif=
ied
-  // value.
-  void BackpatchWord(unsigned ByteNo, unsigned NewWord) {
-    Out[ByteNo++] =3D (unsigned char)(NewWord >>  0);
-    Out[ByteNo++] =3D (unsigned char)(NewWord >>  8);
-    Out[ByteNo++] =3D (unsigned char)(NewWord >> 16);
-    Out[ByteNo  ] =3D (unsigned char)(NewWord >> 24);
-  }
-
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Block Manipulation
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
@@ -199,7 +213,7 @@
     EmitVBR(CodeLen, bitc::CodeLenWidth);
     FlushToWord();
=20
-    unsigned BlockSizeWordLoc =3D static_cast<unsigned>(Out.size());
+    unsigned BlockSizeWordIndex =3D GetWordIndex();
     unsigned OldCodeSize =3D CurCodeSize;
=20
     // Emit a placeholder, which will be replaced when the block is popped.
@@ -209,7 +223,7 @@
=20
     // Push the outer block's abbrev set onto the stack, start out with an
     // empty abbrev set.
-    BlockScope.push_back(Block(OldCodeSize, BlockSizeWordLoc/4));
+    BlockScope.push_back(Block(OldCodeSize, BlockSizeWordIndex));
     BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
=20
     // If there is a blockinfo for this BlockID, add all the predefined ab=
brevs
@@ -239,7 +253,7 @@
     FlushToWord();
=20
     // Compute the size of the block, in words, not counting the size fiel=
d.
-    unsigned SizeInWords=3D static_cast<unsigned>(Out.size())/4-B.StartSiz=
eWord-1;
+    unsigned SizeInWords =3D GetWordIndex() - B.StartSizeWord - 1;
     unsigned ByteNo =3D B.StartSizeWord*4;
=20
     // Update the block size field in the header of this sub-block.
@@ -275,7 +289,7 @@
    =20
     // Encode the value as we are commanded.
     switch (Op.getEncoding()) {
-    default: assert(0 && "Unknown encoding!");
+    default: llvm_unreachable("Unknown encoding!");
     case BitCodeAbbrevOp::Fixed:
       if (Op.getEncodingData())
         Emit((unsigned)V, (unsigned)Op.getEncodingData());
@@ -355,25 +369,24 @@
        =20
         // Flush to a 32-bit alignment boundary.
         FlushToWord();
-        assert((Out.size() & 3) =3D=3D 0 && "Not 32-bit aligned");
=20
         // Emit each field as a literal byte.
         if (BlobData) {
           for (unsigned i =3D 0; i !=3D BlobLen; ++i)
-            Out.push_back((unsigned char)BlobData[i]);
+            WriteByte((unsigned char)BlobData[i]);
          =20
           // Know that blob data is consumed for assertion below.
           BlobData =3D 0;
         } else {
           for (unsigned e =3D Vals.size(); RecordIdx !=3D e; ++RecordIdx) {
             assert(Vals[RecordIdx] < 256 && "Value too large to emit as bl=
ob");
-            Out.push_back((unsigned char)Vals[RecordIdx]);
+            WriteByte((unsigned char)Vals[RecordIdx]);
           }
         }
+
         // Align end to 32-bits.
-        while (Out.size() & 3)
-          Out.push_back(0);
-       =20
+        while (GetBufferOffset() & 3)
+          WriteByte(0);
       } else {  // Single scalar field.
         assert(RecordIdx < Vals.size() && "Invalid abbrev/record");
         EmitAbbreviatedField(Op, Vals[RecordIdx]);
@@ -488,7 +501,7 @@
   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
   void EnterBlockInfoBlock(unsigned CodeWidth) {
     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
-    BlockInfoCurBID =3D -1U;
+    BlockInfoCurBID =3D ~0U;
   }
 private:
   /// SwitchToBlockID - If we aren't already talking about the specified b=
lock
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Bitcode=
/LLVMBitCodes.h
--- a/head/contrib/llvm/include/llvm/Bitcode/LLVMBitCodes.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Bitcode/LLVMBitCodes.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -29,23 +29,21 @@
=20
     // Module sub-block id's.
     PARAMATTR_BLOCK_ID,
-   =20
-    /// TYPE_BLOCK_ID_OLD - This is the type descriptor block in LLVM 2.9 =
and
-    /// earlier, replaced with TYPE_BLOCK_ID2.  FIXME: Remove in LLVM 3.1.
-    TYPE_BLOCK_ID_OLD,
+
+    UNUSED_ID1,
    =20
     CONSTANTS_BLOCK_ID,
     FUNCTION_BLOCK_ID,
    =20
-    /// TYPE_SYMTAB_BLOCK_ID_OLD - This type descriptor is from LLVM 2.9 a=
nd
-    /// earlier bitcode files.  FIXME: Remove in LLVM 3.1
-    TYPE_SYMTAB_BLOCK_ID_OLD,
+    UNUSED_ID2,
    =20
     VALUE_SYMTAB_BLOCK_ID,
     METADATA_BLOCK_ID,
     METADATA_ATTACHMENT_ID,
    =20
-    TYPE_BLOCK_ID_NEW
+    TYPE_BLOCK_ID_NEW,
+
+    USELIST_BLOCK_ID
   };
=20
=20
@@ -63,10 +61,10 @@
     MODULE_CODE_GLOBALVAR   =3D 7,
=20
     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignm=
ent,
-    //             section, visibility]
+    //             section, visibility, gc, unnamed_addr]
     MODULE_CODE_FUNCTION    =3D 8,
=20
-    // ALIAS: [alias type, aliasee val#, linkage]
+    // ALIAS: [alias type, aliasee val#, linkage, visibility]
     MODULE_CODE_ALIAS       =3D 9,
=20
     /// MODULE_CODE_PURGEVALS: [numvals]
@@ -92,11 +90,12 @@
     TYPE_CODE_OPAQUE   =3D  6,    // OPAQUE
     TYPE_CODE_INTEGER  =3D  7,    // INTEGER: [width]
     TYPE_CODE_POINTER  =3D  8,    // POINTER: [pointee type]
-    TYPE_CODE_FUNCTION =3D  9,    // FUNCTION: [vararg, retty, paramty x N]
+
+    TYPE_CODE_FUNCTION_OLD =3D 9, // FUNCTION: [vararg, attrid, retty,
+                                //            paramty x N]
    =20
-    // FIXME: This is the encoding used for structs in LLVM 2.9 and earlie=
r.
-    // REMOVE this in LLVM 3.1
-    TYPE_CODE_STRUCT_OLD =3D 10,  // STRUCT: [ispacked, eltty x N]
+    TYPE_CODE_HALF     =3D  10,   // HALF
+   =20
     TYPE_CODE_ARRAY    =3D 11,    // ARRAY: [numelts, eltty]
     TYPE_CODE_VECTOR   =3D 12,    // VECTOR: [numelts, eltty]
=20
@@ -113,7 +112,9 @@
    =20
     TYPE_CODE_STRUCT_ANON =3D 18, // STRUCT_ANON: [ispacked, eltty x N]
     TYPE_CODE_STRUCT_NAME =3D 19, // STRUCT_NAME: [strchr x N]
-    TYPE_CODE_STRUCT_NAMED =3D 20 // STRUCT_NAMED: [ispacked, eltty x N]
+    TYPE_CODE_STRUCT_NAMED =3D 20,// STRUCT_NAMED: [ispacked, eltty x N]
+
+    TYPE_CODE_FUNCTION =3D 21     // FUNCTION: [vararg, retty, paramty x N]
   };
=20
   // The type symbol table only has one code (TST_ENTRY_CODE).
@@ -163,7 +164,8 @@
     CST_CODE_INLINEASM     =3D 18,  // INLINEASM:     [sideeffect,asmstr,c=
onststr]
     CST_CODE_CE_SHUFVEC_EX =3D 19,  // SHUFVEC_EX:    [opty, opval, opval,=
 opval]
     CST_CODE_CE_INBOUNDS_GEP =3D 20,// INBOUNDS_GEP:  [n x operands]
-    CST_CODE_BLOCKADDRESS  =3D 21   // CST_CODE_BLOCKADDRESS [fnty, fnval,=
 bb#]
+    CST_CODE_BLOCKADDRESS  =3D 21,  // CST_CODE_BLOCKADDRESS [fnty, fnval,=
 bb#]
+    CST_CODE_DATA          =3D 22   // DATA:          [n x elements]
   };
=20
   /// CastOpcodes - These are values used in the bitcode files to encode w=
hich
@@ -270,7 +272,7 @@
     FUNC_CODE_INST_BR          =3D 11, // BR:         [bb#, bb#, cond] or =
[bb#]
     FUNC_CODE_INST_SWITCH      =3D 12, // SWITCH:     [opty, op0, op1, ...]
     FUNC_CODE_INST_INVOKE      =3D 13, // INVOKE:     [attr, fnty, op0,op1=
, ...]
-    FUNC_CODE_INST_UNWIND      =3D 14, // UNWIND
+    // 14 is unused.
     FUNC_CODE_INST_UNREACHABLE =3D 15, // UNREACHABLE
=20
     FUNC_CODE_INST_PHI         =3D 16, // PHI:        [ty, val0,bb0, ...]
@@ -314,6 +316,10 @@
     FUNC_CODE_INST_STOREATOMIC =3D 42  // STORE: [ptrty,ptr,val, align, vol
                                      //         ordering, synchscope]
   };
+
+  enum UseListCodes {
+    USELIST_CODE_ENTRY =3D 1   // USELIST_CODE_ENTRY: TBD.
+  };
 } // End bitc namespace
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Bitcode=
/ReaderWriter.h
--- a/head/contrib/llvm/include/llvm/Bitcode/ReaderWriter.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Bitcode/ReaderWriter.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -17,35 +17,45 @@
 #include <string>
=20
 namespace llvm {
+  class BitstreamWriter;
+  class MemoryBuffer;
+  class DataStreamer;
+  class LLVMContext;
   class Module;
-  class MemoryBuffer;
   class ModulePass;
-  class BitstreamWriter;
-  class LLVMContext;
   class raw_ostream;
- =20
+
   /// getLazyBitcodeModule - Read the header of the specified bitcode buff=
er
   /// and prepare for lazy deserialization of function bodies.  If success=
ful,
   /// this takes ownership of 'buffer' and returns a non-null pointer.  On
   /// error, this returns null, *does not* take ownership of Buffer, and f=
ills
   /// in *ErrMsg with an error description if ErrMsg is non-null.
   Module *getLazyBitcodeModule(MemoryBuffer *Buffer,
-                               LLVMContext& Context,
+                               LLVMContext &Context,
                                std::string *ErrMsg =3D 0);
=20
+  /// getStreamedBitcodeModule - Read the header of the specified stream
+  /// and prepare for lazy deserialization and streaming of function bodie=
s.
+  /// On error, this returns null, and fills in *ErrMsg with an error
+  /// description if ErrMsg is non-null.
+  Module *getStreamedBitcodeModule(const std::string &name,
+                                   DataStreamer *streamer,
+                                   LLVMContext &Context,
+                                   std::string *ErrMsg =3D 0);
+
   /// getBitcodeTargetTriple - Read the header of the specified bitcode
   /// buffer and extract just the triple information. If successful,
   /// this returns a string and *does not* take ownership
   /// of 'buffer'. On error, this returns "", and fills in *ErrMsg
   /// if ErrMsg is non-null.
   std::string getBitcodeTargetTriple(MemoryBuffer *Buffer,
-                                     LLVMContext& Context,
+                                     LLVMContext &Context,
                                      std::string *ErrMsg =3D 0);
=20
   /// ParseBitcodeFile - Read the specified bitcode file, returning the mo=
dule.
   /// If an error occurs, this returns null and fills in *ErrMsg if it is
   /// non-null.  This method *never* takes ownership of Buffer.
-  Module *ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
+  Module *ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext &Context,
                            std::string *ErrMsg =3D 0);
=20
   /// WriteBitcodeToFile - Write the specified module to the specified
@@ -53,15 +63,11 @@
   /// should be in "binary" mode.
   void WriteBitcodeToFile(const Module *M, raw_ostream &Out);
=20
-  /// WriteBitcodeToStream - Write the specified module to the specified
-  /// raw output stream.
-  void WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream);
-
   /// createBitcodeWriterPass - Create and return a pass that writes the m=
odule
   /// to the specified ostream.
   ModulePass *createBitcodeWriterPass(raw_ostream &Str);
- =20
- =20
+
+
   /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
   /// for an LLVM IR bitcode wrapper.
   ///
@@ -109,21 +115,24 @@
   ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
   ///   ... potentially other gunk ...
   /// };
-  ///=20
+  ///
   /// This function is called when we find a file with a matching magic nu=
mber.
   /// In this case, skip down to the subsection of the file that is actual=
ly a
   /// BC file.
-  static inline bool SkipBitcodeWrapperHeader(unsigned char *&BufPtr,
-                                              unsigned char *&BufEnd) {
+  /// If 'VerifyBufferSize' is true, check that the buffer is large enough=
 to
+  /// contain the whole bitcode file.
+  static inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
+                                              const unsigned char *&BufEnd,
+                                              bool VerifyBufferSize) {
     enum {
       KnownHeaderSize =3D 4*4,  // Size of header we read.
       OffsetField =3D 2*4,      // Offset in bytes to Offset field.
       SizeField =3D 3*4         // Offset in bytes to Size field.
     };
-   =20
+
     // Must contain the header!
     if (BufEnd-BufPtr < KnownHeaderSize) return true;
-   =20
+
     unsigned Offset =3D ( BufPtr[OffsetField  ]        |
                        (BufPtr[OffsetField+1] << 8)  |
                        (BufPtr[OffsetField+2] << 16) |
@@ -132,9 +141,9 @@
                        (BufPtr[SizeField  +1] << 8)  |
                        (BufPtr[SizeField  +2] << 16) |
                        (BufPtr[SizeField  +3] << 24));
-   =20
+
     // Verify that Offset+Size fits in the file.
-    if (Offset+Size > unsigned(BufEnd-BufPtr))
+    if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr))
       return true;
     BufPtr +=3D Offset;
     BufEnd =3D BufPtr+Size;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/Analysis.h
--- a/head/contrib/llvm/include/llvm/CodeGen/Analysis.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/Analysis.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -27,6 +27,7 @@
 class GlobalVariable;
 class TargetLowering;
 class SDNode;
+class SDValue;
 class SelectionDAG;
=20
 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
@@ -70,6 +71,10 @@
 ///
 ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred);
=20
+/// getFCmpCodeWithoutNaN - Given an ISD condition code comparing floats,
+/// return the equivalent code if we're allowed to assume that NaNs won't =
occur.
+ISD::CondCode getFCmpCodeWithoutNaN(ISD::CondCode CC);
+
 /// getICmpCondCode - Return the ISD condition code corresponding to
 /// the given LLVM IR integer condition code.
 ///
@@ -85,7 +90,7 @@
                           const TargetLowering &TLI);
=20
 bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
-                          const TargetLowering &TLI);
+                          SDValue &Chain, const TargetLowering &TLI);
=20
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/AsmPrinter.h
--- a/head/contrib/llvm/include/llvm/CodeGen/AsmPrinter.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/AsmPrinter.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,16 +18,12 @@
=20
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
=20
 namespace llvm {
   class BlockAddress;
   class GCStrategy;
   class Constant;
-  class ConstantArray;
-  class ConstantFP;
-  class ConstantInt;
-  class ConstantStruct;
-  class ConstantVector;
   class GCMetadataPrinter;
   class GlobalValue;
   class GlobalVariable;
@@ -37,14 +33,11 @@
   class MachineLocation;
   class MachineLoopInfo;
   class MachineLoop;
-  class MachineConstantPool;
-  class MachineConstantPoolEntry;
   class MachineConstantPoolValue;
   class MachineJumpTableInfo;
   class MachineModuleInfo;
   class MachineMove;
   class MCAsmInfo;
-  class MCInst;
   class MCContext;
   class MCSection;
   class MCStreamer;
@@ -56,8 +49,6 @@
   class TargetLoweringObjectFile;
   class TargetData;
   class TargetMachine;
-  class Twine;
-  class Type;
=20
   /// AsmPrinter - This class is intended to be used as a driving class fo=
r all
   /// asm writers.
@@ -97,6 +88,11 @@
     ///
     MCSymbol *CurrentFnSym;
=20
+    /// The symbol used to represent the start of the current function for=
 the
+    /// purpose of calculating its size (e.g. using the .size directive). =
By
+    /// default, this is equal to CurrentFnSym.
+    MCSymbol *CurrentFnSymForSize;
+
   private:
     // GCMetadataPrinters - The garbage collection metadata printer table.
     void *GCMetadataPrinters;  // Really a DenseMap.
@@ -194,6 +190,11 @@
=20
     bool needsSEHMoves();
=20
+    /// needsRelocationsForDwarfStringPool - Specifies whether the object =
format
+    /// expects to use relocations to refer to debug entries. Alternativel=
y we
+    /// emit section offsets in bytes from the start of the string pool.
+    bool needsRelocationsForDwarfStringPool() const;
+
     /// EmitConstantPool - Print to the current output stream assembly
     /// representations of the constants in the constant pool MCP. This is
     /// used to print out constants which have been "spilled to memory" by
@@ -256,13 +257,20 @@
=20
     /// EmitInstruction - Targets should implement this to emit instructio=
ns.
     virtual void EmitInstruction(const MachineInstr *) {
-      assert(0 && "EmitInstruction not implemented");
+      llvm_unreachable("EmitInstruction not implemented");
     }
=20
     virtual void EmitFunctionEntryLabel();
=20
     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MC=
PV);
=20
+    /// EmitXXStructor - Targets can override this to change how global
+    /// constants that are part of a C++ static/global constructor list are
+    /// emitted.
+    virtual void EmitXXStructor(const Constant *CV) {
+      EmitGlobalConstant(CV);
+    }
+
     /// isBlockOnlyReachableByFallthough - Return true if the basic block =
has
     /// exactly one predecessor and the control transfer mechanism between
     /// the predecessor and this block is a fall-through.
@@ -466,7 +474,7 @@
                             const MachineBasicBlock *MBB,
                             unsigned uid) const;
     void EmitLLVMUsedList(const Constant *List);
-    void EmitXXStructorList(const Constant *List);
+    void EmitXXStructorList(const Constant *List, bool isCtor);
     GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy *C);
   };
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/CallingConvLower.h
--- a/head/contrib/llvm/include/llvm/CodeGen/CallingConvLower.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/CallingConvLower.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -229,7 +229,7 @@
=20
   /// getFirstUnallocated - Return the first unallocated register in the s=
et, or
   /// NumRegs if they are all allocated.
-  unsigned getFirstUnallocated(const unsigned *Regs, unsigned NumRegs) con=
st {
+  unsigned getFirstUnallocated(const uint16_t *Regs, unsigned NumRegs) con=
st {
     for (unsigned i =3D 0; i !=3D NumRegs; ++i)
       if (!isAllocated(Regs[i]))
         return i;
@@ -256,7 +256,7 @@
   /// AllocateReg - Attempt to allocate one of the specified registers.  I=
f none
   /// are available, return zero.  Otherwise, return the first one availab=
le,
   /// marking it and any aliases as allocated.
-  unsigned AllocateReg(const unsigned *Regs, unsigned NumRegs) {
+  unsigned AllocateReg(const uint16_t *Regs, unsigned NumRegs) {
     unsigned FirstUnalloc =3D getFirstUnallocated(Regs, NumRegs);
     if (FirstUnalloc =3D=3D NumRegs)
       return 0;    // Didn't find the reg.
@@ -268,7 +268,7 @@
   }
=20
   /// Version of AllocateReg with list of registers to be shadowed.
-  unsigned AllocateReg(const unsigned *Regs, const unsigned *ShadowRegs,
+  unsigned AllocateReg(const uint16_t *Regs, const uint16_t *ShadowRegs,
                        unsigned NumRegs) {
     unsigned FirstUnalloc =3D getFirstUnallocated(Regs, NumRegs);
     if (FirstUnalloc =3D=3D NumRegs)
@@ -306,12 +306,12 @@
=20
   // First GPR that carries part of a byval aggregate that's split
   // between registers and memory.
-  unsigned getFirstByValReg() { return FirstByValRegValid ? FirstByValReg =
: 0; }
+  unsigned getFirstByValReg() const { return FirstByValRegValid ? FirstByV=
alReg : 0; }
   void setFirstByValReg(unsigned r) { FirstByValReg =3D r; FirstByValRegVa=
lid =3D true; }
   void clearFirstByValReg() { FirstByValReg =3D 0; FirstByValRegValid =3D =
false; }
-  bool isFirstByValRegValid() { return FirstByValRegValid; }
+  bool isFirstByValRegValid() const { return FirstByValRegValid; }
=20
-  ParmContext getCallOrPrologue() { return CallOrPrologue; }
+  ParmContext getCallOrPrologue() const { return CallOrPrologue; }
=20
 private:
   /// MarkAllocated - Mark a register and all of its aliases as allocated.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/EdgeBundles.h
--- a/head/contrib/llvm/include/llvm/CodeGen/EdgeBundles.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/EdgeBundles.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -18,6 +18,7 @@
=20
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/IntEqClasses.h"
+#include "llvm/ADT/Twine.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
=20
 namespace llvm {
@@ -61,7 +62,7 @@
 /// Specialize WriteGraph, the standard implementation won't work.
 raw_ostream &WriteGraph(raw_ostream &O, const EdgeBundles &G,
                         bool ShortNames =3D false,
-                        const std::string &Title =3D "");
+                        const Twine &Title =3D "");
=20
 } // end namespace llvm
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/FastISel.h
--- a/head/contrib/llvm/include/llvm/CodeGen/FastISel.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/FastISel.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -21,9 +21,11 @@
 namespace llvm {
=20
 class AllocaInst;
+class Constant;
 class ConstantFP;
 class FunctionLoweringInfo;
 class Instruction;
+class LoadInst;
 class MachineBasicBlock;
 class MachineConstantPool;
 class MachineFunction;
@@ -36,7 +38,8 @@
 class TargetMachine;
 class TargetRegisterClass;
 class TargetRegisterInfo;
-class LoadInst;
+class User;
+class Value;
=20
 /// FastISel - This is a fast-path instruction selection class that
 /// generates poor code and doesn't support illegal types or non-trivial
@@ -358,6 +361,8 @@
=20
   bool SelectExtractValue(const User *I);
=20
+  bool SelectInsertValue(const User *I);
+
   /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor bloc=
ks.
   /// Emit code to ensure constants are copied into registers when needed.
   /// Remember the virtual registers that need to be added to the Machine =
PHI
@@ -378,6 +383,10 @@
=20
   /// hasTrivialKill - Test whether the given value has exactly one use.
   bool hasTrivialKill(const Value *V) const;
+
+  /// removeDeadCode - Remove all dead instructions between the I and E.
+  void removeDeadCode(MachineBasicBlock::iterator I,
+                      MachineBasicBlock::iterator E);
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/FunctionLoweringInfo.h
--- a/head/contrib/llvm/include/llvm/CodeGen/FunctionLoweringInfo.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/FunctionLoweringInfo.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -21,10 +21,8 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/IndexedMap.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
-#ifndef NDEBUG
-#include "llvm/ADT/SmallSet.h"
-#endif
 #include "llvm/Analysis/BranchProbabilityInfo.h"
 #include "llvm/CodeGen/ValueTypes.h"
 #include "llvm/CodeGen/ISDOpcodes.h"
@@ -98,8 +96,8 @@
   MachineBasicBlock::iterator InsertPt;
=20
 #ifndef NDEBUG
-  SmallSet<const Instruction *, 8> CatchInfoLost;
-  SmallSet<const Instruction *, 8> CatchInfoFound;
+  SmallPtrSet<const Instruction *, 8> CatchInfoLost;
+  SmallPtrSet<const Instruction *, 8> CatchInfoFound;
 #endif
=20
   struct LiveOutInfo {
@@ -112,7 +110,7 @@
=20
   /// VisitedBBs - The set of basic blocks visited thus far by instruction
   /// selection.
-  DenseSet<const BasicBlock*> VisitedBBs;
+  SmallPtrSet<const BasicBlock*, 4> VisitedBBs;
=20
   /// PHINodesToUpdate - A list of phi instructions whose operand list will
   /// be updated after processing the current basic block.
@@ -202,7 +200,7 @@
   /// setArgumentFrameIndex - Record frame index for the byval
   /// argument.
   void setArgumentFrameIndex(const Argument *A, int FI);
- =20
+
   /// getArgumentFrameIndex - Get frame index for the byval argument.
   int getArgumentFrameIndex(const Argument *A);
=20
@@ -211,16 +209,18 @@
   IndexedMap<LiveOutInfo, VirtReg2IndexFunctor> LiveOutRegInfo;
 };
=20
+/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
+/// being passed to this variadic function, and set the MachineModuleInfo's
+/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
+/// reference to _fltused on Windows, which will link in MSVCRT's
+/// floating-point support.
+void ComputeUsesVAFloatArgument(const CallInst &I, MachineModuleInfo *MMI);
+
 /// AddCatchInfo - Extract the personality and type infos from an eh.selec=
tor
 /// call, and add them to the specified machine basic block.
 void AddCatchInfo(const CallInst &I,
                   MachineModuleInfo *MMI, MachineBasicBlock *MBB);
=20
-/// CopyCatchInfo - Copy catch information from SuccBB (or one of its
-/// successors) to LPad.
-void CopyCatchInfo(const BasicBlock *SuccBB, const BasicBlock *LPad,
-                   MachineModuleInfo *MMI, FunctionLoweringInfo &FLI);
-
 /// AddLandingPadInfo - Extract the exception handling information from the
 /// landingpad instruction and add them to the specified machine module in=
fo.
 void AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/GCStrategy.h
--- a/head/contrib/llvm/include/llvm/CodeGen/GCStrategy.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/GCStrategy.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -37,6 +37,7 @@
 #define LLVM_CODEGEN_GCSTRATEGY_H
=20
 #include "llvm/CodeGen/GCMetadata.h"
+#include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/Support/Registry.h"
 #include <string>
=20
@@ -68,6 +69,8 @@
     bool CustomReadBarriers;   //< Default is to insert loads.
     bool CustomWriteBarriers;  //< Default is to insert stores.
     bool CustomRoots;          //< Default is to pass through to backend.
+    bool CustomSafePoints;     //< Default is to use NeededSafePoints
+                               //  to find safe points.
     bool InitRoots;            //< If set, roots are nulled during lowerin=
g.
     bool UsesMetadata;         //< If set, backend must emit metadata tabl=
es.
    =20
@@ -87,7 +90,9 @@
=20
     /// needsSafePoitns - True if safe points of any kind are required. By
     //                    default, none are recorded.
-    bool needsSafePoints() const { return NeededSafePoints !=3D 0; }
+    bool needsSafePoints() const {
+      return CustomSafePoints || NeededSafePoints !=3D 0;
+    }
    =20
     /// needsSafePoint(Kind) - True if the given kind of safe point is
     //                          required. By default, none are recorded.
@@ -109,6 +114,11 @@
     ///               can generate a stack map. If true, then
     //                performCustomLowering must delete them.
     bool customRoots() const { return CustomRoots; }
+
+    /// customSafePoints - By default, the GC analysis will find safe
+    ///                    points according to NeededSafePoints. If true,
+    ///                    then findCustomSafePoints must create them.
+    bool customSafePoints() const { return CustomSafePoints; }
    =20
     /// initializeRoots - If set, gcroot intrinsics should initialize their
     //                    allocas to null before the first use. This is
@@ -135,6 +145,7 @@
     /// which the LLVM IR can be modified.
     virtual bool initializeCustomLowering(Module &F);
     virtual bool performCustomLowering(Function &F);
+    virtual bool findCustomSafePoints(GCFunctionInfo& FI, MachineFunction&=
 MF);
   };
  =20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/ISDOpcodes.h
--- a/head/contrib/llvm/include/llvm/CodeGen/ISDOpcodes.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/ISDOpcodes.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -57,7 +57,7 @@
     AssertSext, AssertZext,
=20
     // Various leaf nodes.
-    BasicBlock, VALUETYPE, CONDCODE, Register,
+    BasicBlock, VALUETYPE, CONDCODE, Register, RegisterMask,
     Constant, ConstantFP,
     GlobalAddress, GlobalTLSAddress, FrameIndex,
     JumpTable, ConstantPool, ExternalSymbol, BlockAddress,
@@ -107,13 +107,6 @@
     // and returns an outchain.
     EH_SJLJ_LONGJMP,
=20
-    // OUTCHAIN =3D EH_SJLJ_DISPATCHSETUP(INCHAIN, setjmpval)
-    // This corresponds to the eh.sjlj.dispatchsetup intrinsic. It takes an
-    // input chain and the value returning from setjmp as inputs and retur=
ns an
-    // outchain. By default, this does nothing. Targets can lower this to =
unwind
-    // setup code if needed.
-    EH_SJLJ_DISPATCHSETUP,
-
     // TargetConstant* - Like Constant*, but the DAG does not do any foldi=
ng,
     // simplification, or lowering of the constant. They are used for cons=
tants
     // which are known to fit in the immediate fields of their users, or f=
or
@@ -319,6 +312,9 @@
     /// Byte Swap and Counting operators.
     BSWAP, CTTZ, CTLZ, CTPOP,
=20
+    /// Bit counting operators with an undefined result for zero inputs.
+    CTTZ_ZERO_UNDEF, CTLZ_ZERO_UNDEF,
+
     // Select(COND, TRUEVAL, FALSEVAL).  If the type of the boolean COND i=
s not
     // i1 then the high bits must conform to getBooleanContents.
     SELECT,
@@ -327,6 +323,9 @@
     // and #2), returning a vector result.  All vectors have the same leng=
th.
     // Much like the scalar select and setcc, each bit in the condition se=
lects
     // whether the corresponding result element is taken from op #1 or op =
#2.
+    // At first, the VSELECT condition is of vXi1 type. Later, targets may=
 change
+    // the condition type in order to match the VSELECT node using a a pat=
tern.
+    // The condition follows the BooleanContent format of the target.
     VSELECT,
=20
     // Select with condition operator - This selects between a true value =
and
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/JITCodeEmitter.h
--- a/head/contrib/llvm/include/llvm/CodeGen/JITCodeEmitter.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/JITCodeEmitter.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -51,6 +51,7 @@
 /// occurred, more memory is allocated, and we reemit the code into it.
 ///=20
 class JITCodeEmitter : public MachineCodeEmitter {
+  virtual void anchor();
 public:
   virtual ~JITCodeEmitter() {}
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/LatencyPriorityQueue.h
--- a/head/contrib/llvm/include/llvm/CodeGen/LatencyPriorityQueue.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/LatencyPriorityQueue.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -85,11 +85,11 @@
=20
     virtual void dump(ScheduleDAG* DAG) const;
=20
-    // ScheduledNode - As nodes are scheduled, we look to see if there are=
 any
+    // scheduledNode - As nodes are scheduled, we look to see if there are=
 any
     // successor nodes that have a single unscheduled predecessor.  If so,=
 that
     // single predecessor has a higher priority, since scheduling it will =
make
     // the node available.
-    void ScheduledNode(SUnit *Node);
+    void scheduledNode(SUnit *Node);
=20
 private:
     void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/LexicalScopes.h
--- a/head/contrib/llvm/include/llvm/CodeGen/LexicalScopes.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/LexicalScopes.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -153,6 +153,7 @@
 /// LexicalScope - This class is used to track scope information.
 ///
 class LexicalScope {
+  virtual void anchor();
=20
 public:
   LexicalScope(LexicalScope *P, const MDNode *D, const MDNode *I, bool A)
@@ -208,7 +209,7 @@
       Parent->closeInsnRange(NewScope);
   }
=20
-  /// dominates - Return true if current scope dominsates given lexical sc=
ope.
+  /// dominates - Return true if current scope dominates given lexical sco=
pe.
   bool dominates(const LexicalScope *S) const {
     if (S =3D=3D this)
       return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/LinkAllCodegenComponents.h
--- a/head/contrib/llvm/include/llvm/CodeGen/LinkAllCodegenComponents.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/LinkAllCodegenComponents.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -31,24 +31,20 @@
       if (std::getenv("bar") !=3D (char*) -1)
         return;
=20
-      (void) llvm::createDeadMachineInstructionElimPass();
-
       (void) llvm::createFastRegisterAllocator();
       (void) llvm::createBasicRegisterAllocator();
-      (void) llvm::createLinearScanRegisterAllocator();
       (void) llvm::createGreedyRegisterAllocator();
       (void) llvm::createDefaultPBQPRegisterAllocator();
=20
       llvm::linkOcamlGC();
       llvm::linkShadowStackGC();
-     =20
+
       (void) llvm::createBURRListDAGScheduler(NULL, llvm::CodeGenOpt::Defa=
ult);
-      (void) llvm::createTDRRListDAGScheduler(NULL, llvm::CodeGenOpt::Defa=
ult);
       (void) llvm::createSourceListDAGScheduler(NULL,llvm::CodeGenOpt::Def=
ault);
       (void) llvm::createHybridListDAGScheduler(NULL,llvm::CodeGenOpt::Def=
ault);
-      (void) llvm::createTDListDAGScheduler(NULL, llvm::CodeGenOpt::Defaul=
t);
       (void) llvm::createFastDAGScheduler(NULL, llvm::CodeGenOpt::Default);
       (void) llvm::createDefaultScheduler(NULL, llvm::CodeGenOpt::Default);
+      (void) llvm::createVLIWDAGScheduler(NULL, llvm::CodeGenOpt::Default);
=20
     }
   } ForceCodegenLinking; // Force link by creating a global definition.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/LiveInterval.h
--- a/head/contrib/llvm/include/llvm/CodeGen/LiveInterval.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/LiveInterval.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -43,12 +43,10 @@
   private:
     enum {
       HAS_PHI_KILL    =3D 1,
-      REDEF_BY_EC     =3D 1 << 1,
-      IS_PHI_DEF      =3D 1 << 2,
-      IS_UNUSED       =3D 1 << 3
+      IS_PHI_DEF      =3D 1 << 1,
+      IS_UNUSED       =3D 1 << 2
     };
=20
-    MachineInstr *copy;
     unsigned char flags;
=20
   public:
@@ -57,23 +55,22 @@
     /// The ID number of this value.
     unsigned id;
=20
-    /// The index of the defining instruction (if isDefAccurate() returns =
true).
+    /// The index of the defining instruction.
     SlotIndex def;
=20
     /// VNInfo constructor.
-    VNInfo(unsigned i, SlotIndex d, MachineInstr *c)
-      : copy(c), flags(0), id(i), def(d)
+    VNInfo(unsigned i, SlotIndex d)
+      : flags(0), id(i), def(d)
     { }
=20
     /// VNInfo construtor, copies values from orig, except for the value n=
umber.
     VNInfo(unsigned i, const VNInfo &orig)
-      : copy(orig.copy), flags(orig.flags), id(i), def(orig.def)
+      : flags(orig.flags), id(i), def(orig.def)
     { }
=20
     /// Copy from the parameter into this VNInfo.
     void copyFrom(VNInfo &src) {
       flags =3D src.flags;
-      copy =3D src.copy;
       def =3D src.def;
     }
=20
@@ -86,19 +83,6 @@
       flags =3D (flags | VNI->flags) & ~IS_UNUSED;
     }
=20
-    /// For a register interval, if this VN was definied by a copy instr
-    /// getCopy() returns a pointer to it, otherwise returns 0.
-    /// For a stack interval the behaviour of this method is undefined.
-    MachineInstr* getCopy() const { return copy; }
-    /// For a register interval, set the copy member.
-    /// This method should not be called on stack intervals as it may lead=
 to
-    /// undefined behavior.
-    void setCopy(MachineInstr *c) { copy =3D c; }
-
-    /// isDefByCopy - Return true when this value was defined by a copy-li=
ke
-    /// instruction as determined by MachineInstr::isCopyLike.
-    bool isDefByCopy() const { return copy !=3D 0; }
-
     /// Returns true if one or more kills are PHI nodes.
     /// Obsolete, do not use!
     bool hasPHIKill() const { return flags & HAS_PHI_KILL; }
@@ -110,17 +94,6 @@
         flags &=3D ~HAS_PHI_KILL;
     }
=20
-    /// Returns true if this value is re-defined by an early clobber somew=
here
-    /// during the live range.
-    bool hasRedefByEC() const { return flags & REDEF_BY_EC; }
-    /// Set the "redef by early clobber" flag on this value.
-    void setHasRedefByEC(bool hasRedef) {
-      if (hasRedef)
-        flags |=3D REDEF_BY_EC;
-      else
-        flags &=3D ~REDEF_BY_EC;
-    }
-
     /// Returns true if this value is defined by a PHI instruction (or was,
     /// PHI instrucions may have been eliminated).
     bool isPHIDef() const { return flags & IS_PHI_DEF; }
@@ -294,10 +267,9 @@
=20
     /// getNextValue - Create a new value number and return it.  MIIdx spe=
cifies
     /// the instruction that defines the value number.
-    VNInfo *getNextValue(SlotIndex def, MachineInstr *CopyMI,
-                         VNInfo::Allocator &VNInfoAllocator) {
+    VNInfo *getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator=
) {
       VNInfo *VNI =3D
-        new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def, CopyMI);
+        new (VNInfoAllocator) VNInfo((unsigned)valnos.size(), def);
       valnos.push_back(VNI);
       return VNI;
     }
@@ -381,7 +353,7 @@
     /// point is not contained in the half-open live range. It is usually =
the
     /// getDefIndex() slot following its last use.
     bool killedAt(SlotIndex index) const {
-      const_iterator r =3D find(index.getUseIndex());
+      const_iterator r =3D find(index.getRegSlot(true));
       return r !=3D end() && r->end =3D=3D index;
     }
=20
@@ -405,6 +377,14 @@
       return I =3D=3D end() ? 0 : &*I;
     }
=20
+    const LiveRange *getLiveRangeBefore(SlotIndex Idx) const {
+      return getLiveRangeContaining(Idx.getPrevSlot());
+    }
+
+    LiveRange *getLiveRangeBefore(SlotIndex Idx) {
+      return getLiveRangeContaining(Idx.getPrevSlot());
+    }
+
     /// getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
     VNInfo *getVNInfoAt(SlotIndex Idx) const {
       const_iterator I =3D FindLiveRangeContaining(Idx);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/LiveIntervalAnalysis.h
--- a/head/contrib/llvm/include/llvm/CodeGen/LiveIntervalAnalysis.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/LiveIntervalAnalysis.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -63,8 +63,34 @@
     /// allocatableRegs_ - A bit vector of allocatable registers.
     BitVector allocatableRegs_;
=20
-    /// CloneMIs - A list of clones as result of re-materialization.
-    std::vector<MachineInstr*> CloneMIs;
+    /// reservedRegs_ - A bit vector of reserved registers.
+    BitVector reservedRegs_;
+
+    /// RegMaskSlots - Sorted list of instructions with register mask oper=
ands.
+    /// Always use the 'r' slot, RegMasks are normal clobbers, not early
+    /// clobbers.
+    SmallVector<SlotIndex, 8> RegMaskSlots;
+
+    /// RegMaskBits - This vector is parallel to RegMaskSlots, it holds a
+    /// pointer to the corresponding register mask.  This pointer can be
+    /// recomputed as:
+    ///
+    ///   MI =3D Indexes->getInstructionFromIndex(RegMaskSlot[N]);
+    ///   unsigned OpNum =3D findRegMaskOperand(MI);
+    ///   RegMaskBits[N] =3D MI->getOperand(OpNum).getRegMask();
+    ///
+    /// This is kept in a separate vector partly because some standard
+    /// libraries don't support lower_bound() with mixed objects, partly to
+    /// improve locality when searching in RegMaskSlots.
+    /// Also see the comment in LiveInterval::find().
+    SmallVector<const uint32_t*, 8> RegMaskBits;
+
+    /// For each basic block number, keep (begin, size) pairs indexing int=
o the
+    /// RegMaskSlots and RegMaskBits arrays.
+    /// Note that basic block numbers may not be layout contiguous, that's=
 why
+    /// we can't just keep track of the first register mask in each basic
+    /// block.
+    SmallVector<std::pair<unsigned, unsigned>, 8> RegMaskBlocks;
=20
   public:
     static char ID; // Pass identification, replacement for typeid
@@ -105,6 +131,12 @@
       return allocatableRegs_.test(reg);
     }
=20
+    /// isReserved - is the physical register reg reserved in the current
+    /// function
+    bool isReserved(unsigned reg) const {
+      return reservedRegs_.test(reg);
+    }
+
     /// getScaledIntervalSize - get the size of an interval in "units,"
     /// where every function is composed of one thousand units.  This
     /// measure scales properly with empty index slots in the function.
@@ -125,19 +157,6 @@
       return (unsigned)(IntervalPercentage * indexes_->getFunctionSize());
     }
=20
-    /// conflictsWithPhysReg - Returns true if the specified register is u=
sed or
-    /// defined during the duration of the specified interval. Copies to a=
nd
-    /// from li.reg are allowed. This method is only able to analyze simple
-    /// ranges that stay within a single basic block. Anything else is
-    /// considered a conflict.
-    bool conflictsWithPhysReg(const LiveInterval &li, VirtRegMap &vrm,
-                              unsigned reg);
-
-    /// conflictsWithAliasRef - Similar to conflictsWithPhysRegRef except
-    /// it checks for alias uses and defs.
-    bool conflictsWithAliasRef(LiveInterval &li, unsigned Reg,
-                                   SmallPtrSet<MachineInstr*,32> &JoinedCo=
pies);
-
     // Interval creation
     LiveInterval &getOrCreateInterval(unsigned reg) {
       Reg2IntervalMap::iterator I =3D r2iMap_.find(reg);
@@ -177,14 +196,6 @@
       return indexes_;
     }
=20
-    SlotIndex getZeroIndex() const {
-      return indexes_->getZeroIndex();
-    }
-
-    SlotIndex getInvalidIndex() const {
-      return indexes_->getInvalidIndex();
-    }
-
     /// isNotInMIMap - returns true if the specified machine instr has been
     /// removed or was never entered in the map.
     bool isNotInMIMap(const MachineInstr* Instr) const {
@@ -216,21 +227,11 @@
       return li.liveAt(getMBBStartIdx(mbb));
     }
=20
-    LiveRange* findEnteringRange(LiveInterval &li,
-                                 const MachineBasicBlock *mbb) {
-      return li.getLiveRangeContaining(getMBBStartIdx(mbb));
-    }
-
     bool isLiveOutOfMBB(const LiveInterval &li,
                         const MachineBasicBlock *mbb) const {
       return li.liveAt(getMBBEndIdx(mbb).getPrevSlot());
     }
=20
-    LiveRange* findExitingRange(LiveInterval &li,
-                                const MachineBasicBlock *mbb) {
-      return li.getLiveRangeContaining(getMBBEndIdx(mbb).getPrevSlot());
-    }
-
     MachineBasicBlock* getMBBFromIndex(SlotIndex index) const {
       return indexes_->getMBBFromIndex(index);
     }
@@ -247,19 +248,11 @@
       indexes_->replaceMachineInstrInMaps(MI, NewMI);
     }
=20
-    void InsertMBBInMaps(MachineBasicBlock *MBB) {
-      indexes_->insertMBBInMaps(MBB);
-    }
-
     bool findLiveInMBBs(SlotIndex Start, SlotIndex End,
                         SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
       return indexes_->findLiveInMBBs(Start, End, MBBs);
     }
=20
-    void renumber() {
-      indexes_->renumberIndexes();
-    }
-
     VNInfo::Allocator& getVNInfoAllocator() { return VNInfoAllocator; }
=20
     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
@@ -271,20 +264,6 @@
     /// print - Implement the dump method.
     virtual void print(raw_ostream &O, const Module* =3D 0) const;
=20
-    /// addIntervalsForSpills - Create new intervals for spilled defs / us=
es of
-    /// the given interval. FIXME: It also returns the weight of the spill=
 slot
-    /// (if any is created) by reference. This is temporary.
-    std::vector<LiveInterval*>
-    addIntervalsForSpills(const LiveInterval& i,
-                          const SmallVectorImpl<LiveInterval*> *SpillIs,
-                          const MachineLoopInfo *loopInfo, VirtRegMap& vrm=
);
-
-    /// spillPhysRegAroundRegDefsUses - Spill the specified physical regis=
ter
-    /// around all defs and uses of the specified interval. Return true if=
 it
-    /// was able to cut its interval.
-    bool spillPhysRegAroundRegDefsUses(const LiveInterval &li,
-                                       unsigned PhysReg, VirtRegMap &vrm);
-
     /// isReMaterializable - Returns true if every definition of MI of eve=
ry
     /// val# of the specified interval is re-materializable. Also returns =
true
     /// by reference if all of the defs are load instructions.
@@ -292,34 +271,72 @@
                             const SmallVectorImpl<LiveInterval*> *SpillIs,
                             bool &isLoad);
=20
-    /// isReMaterializable - Returns true if the definition MI of the spec=
ified
-    /// val# of the specified interval is re-materializable.
-    bool isReMaterializable(const LiveInterval &li, const VNInfo *ValNo,
-                            MachineInstr *MI);
-
-    /// getRepresentativeReg - Find the largest super register of the spec=
ified
-    /// physical register.
-    unsigned getRepresentativeReg(unsigned Reg) const;
-
-    /// getNumConflictsWithPhysReg - Return the number of uses and defs of=
 the
-    /// specified interval that conflicts with the specified physical regi=
ster.
-    unsigned getNumConflictsWithPhysReg(const LiveInterval &li,
-                                        unsigned PhysReg) const;
-
-    /// intervalIsInOneMBB - Returns true if the specified interval is ent=
irely
-    /// within a single basic block.
-    bool intervalIsInOneMBB(const LiveInterval &li) const;
-
-    /// getLastSplitPoint - Return the last possible insertion point in mb=
b for
-    /// spilling and splitting code. This is the first terminator, or the =
call
-    /// instruction if li is live into a landing pad successor.
-    MachineBasicBlock::iterator getLastSplitPoint(const LiveInterval &li,
-                                                  MachineBasicBlock *mbb) =
const;
+    /// intervalIsInOneMBB - If LI is confined to a single basic block, re=
turn
+    /// a pointer to that block.  If LI is live in to or out of any block,
+    /// return NULL.
+    MachineBasicBlock *intervalIsInOneMBB(const LiveInterval &LI) const;
=20
     /// addKillFlags - Add kill flags to any instruction that kills a virt=
ual
     /// register.
     void addKillFlags();
=20
+    /// handleMove - call this method to notify LiveIntervals that
+    /// instruction 'mi' has been moved within a basic block. This will up=
date
+    /// the live intervals for all operands of mi. Moves between basic blo=
cks
+    /// are not supported.
+    void handleMove(MachineInstr* MI);
+
+    /// moveIntoBundle - Update intervals for operands of MI so that they
+    /// begin/end on the SlotIndex for BundleStart.
+    ///
+    /// Requires MI and BundleStart to have SlotIndexes, and assumes
+    /// existing liveness is accurate. BundleStart should be the first
+    /// instruction in the Bundle.
+    void handleMoveIntoBundle(MachineInstr* MI, MachineInstr* BundleStart);
+
+    // Register mask functions.
+    //
+    // Machine instructions may use a register mask operand to indicate th=
at a
+    // large number of registers are clobbered by the instruction.  This is
+    // typically used for calls.
+    //
+    // For compile time performance reasons, these clobbers are not record=
ed in
+    // the live intervals for individual physical registers.  Instead,
+    // LiveIntervalAnalysis maintains a sorted list of instructions with
+    // register mask operands.
+
+    /// getRegMaskSlots - Returns a sorted array of slot indices of all
+    /// instructions with register mask operands.
+    ArrayRef<SlotIndex> getRegMaskSlots() const { return RegMaskSlots; }
+
+    /// getRegMaskSlotsInBlock - Returns a sorted array of slot indices of=
 all
+    /// instructions with register mask operands in the basic block number=
ed
+    /// MBBNum.
+    ArrayRef<SlotIndex> getRegMaskSlotsInBlock(unsigned MBBNum) const {
+      std::pair<unsigned, unsigned> P =3D RegMaskBlocks[MBBNum];
+      return getRegMaskSlots().slice(P.first, P.second);
+    }
+
+    /// getRegMaskBits() - Returns an array of register mask pointers
+    /// corresponding to getRegMaskSlots().
+    ArrayRef<const uint32_t*> getRegMaskBits() const { return RegMaskBits;=
 }
+
+    /// getRegMaskBitsInBlock - Returns an array of mask pointers correspo=
nding
+    /// to getRegMaskSlotsInBlock(MBBNum).
+    ArrayRef<const uint32_t*> getRegMaskBitsInBlock(unsigned MBBNum) const=
 {
+      std::pair<unsigned, unsigned> P =3D RegMaskBlocks[MBBNum];
+      return getRegMaskBits().slice(P.first, P.second);
+    }
+
+    /// checkRegMaskInterference - Test if LI is live across any register =
mask
+    /// instructions, and compute a bit mask of physical registers that ar=
e not
+    /// clobbered by any of them.
+    ///
+    /// Returns false if LI doesn't cross any register mask instructions. =
In
+    /// that case, the bit vector is not filled in.
+    bool checkRegMaskInterference(LiveInterval &LI,
+                                  BitVector &UsableRegs);
+
   private:
     /// computeIntervals - Compute live intervals.
     void computeIntervals();
@@ -351,13 +368,12 @@
     void handlePhysicalRegisterDef(MachineBasicBlock* mbb,
                                    MachineBasicBlock::iterator mi,
                                    SlotIndex MIIdx, MachineOperand& MO,
-                                   LiveInterval &interval,
-                                   MachineInstr *CopyMI);
+                                   LiveInterval &interval);
=20
     /// handleLiveInRegister - Create interval for a livein register.
     void handleLiveInRegister(MachineBasicBlock* mbb,
                               SlotIndex MIIdx,
-                              LiveInterval &interval, bool isAlias =3D fal=
se);
+                              LiveInterval &interval);
=20
     /// getReMatImplicitUse - If the remat definition MI has one (for now,=
 we
     /// only allow one) virtual register operand, then its uses are implic=
itly
@@ -379,88 +395,12 @@
                             const SmallVectorImpl<LiveInterval*> *SpillIs,
                             bool &isLoad);
=20
-    /// tryFoldMemoryOperand - Attempts to fold either a spill / restore f=
rom
-    /// slot / to reg or any rematerialized load into ith operand of speci=
fied
-    /// MI. If it is successul, MI is updated with the newly created MI and
-    /// returns true.
-    bool tryFoldMemoryOperand(MachineInstr* &MI, VirtRegMap &vrm,
-                              MachineInstr *DefMI, SlotIndex InstrIdx,
-                              SmallVector<unsigned, 2> &Ops,
-                              bool isSS, int FrameIndex, unsigned Reg);
-
-    /// canFoldMemoryOperand - Return true if the specified load / store
-    /// folding is possible.
-    bool canFoldMemoryOperand(MachineInstr *MI,
-                              SmallVector<unsigned, 2> &Ops,
-                              bool ReMatLoadSS) const;
-
-    /// anyKillInMBBAfterIdx - Returns true if there is a kill of the spec=
ified
-    /// VNInfo that's after the specified index but is within the basic bl=
ock.
-    bool anyKillInMBBAfterIdx(const LiveInterval &li, const VNInfo *VNI,
-                              MachineBasicBlock *MBB,
-                              SlotIndex Idx) const;
-
-    /// hasAllocatableSuperReg - Return true if the specified physical reg=
ister
-    /// has any super register that's allocatable.
-    bool hasAllocatableSuperReg(unsigned Reg) const;
-
-    /// SRInfo - Spill / restore info.
-    struct SRInfo {
-      SlotIndex index;
-      unsigned vreg;
-      bool canFold;
-      SRInfo(SlotIndex i, unsigned vr, bool f)
-        : index(i), vreg(vr), canFold(f) {}
-    };
-
-    bool alsoFoldARestore(int Id, SlotIndex index, unsigned vr,
-                          BitVector &RestoreMBBs,
-                          DenseMap<unsigned,std::vector<SRInfo> >&RestoreI=
dxes);
-    void eraseRestoreInfo(int Id, SlotIndex index, unsigned vr,
-                          BitVector &RestoreMBBs,
-                          DenseMap<unsigned,std::vector<SRInfo> >&RestoreI=
dxes);
-
-    /// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are =
being
-    /// spilled and create empty intervals for their uses.
-    void handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
-                              const TargetRegisterClass* rc,
-                              std::vector<LiveInterval*> &NewLIs);
-
-    /// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. use=
s of
-    /// interval on to-be re-materialized operands of MI) with new registe=
r.
-    void rewriteImplicitOps(const LiveInterval &li,
-                           MachineInstr *MI, unsigned NewVReg, VirtRegMap =
&vrm);
-
-    /// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper
-    /// functions for addIntervalsForSpills to rewrite uses / defs for the=
 given
-    /// live range.
-    bool rewriteInstructionForSpills(const LiveInterval &li, const VNInfo =
*VNI,
-        bool TrySplit, SlotIndex index, SlotIndex end,
-        MachineInstr *MI, MachineInstr *OrigDefMI, MachineInstr *DefMI,
-        unsigned Slot, int LdSlot,
-        bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
-        VirtRegMap &vrm, const TargetRegisterClass* rc,
-        SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
-        unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
-        DenseMap<unsigned,unsigned> &MBBVRegsMap,
-        std::vector<LiveInterval*> &NewLIs);
-    void rewriteInstructionsForSpills(const LiveInterval &li, bool TrySpli=
t,
-        LiveInterval::Ranges::const_iterator &I,
-        MachineInstr *OrigDefMI, MachineInstr *DefMI, unsigned Slot, int L=
dSlot,
-        bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
-        VirtRegMap &vrm, const TargetRegisterClass* rc,
-        SmallVector<int, 4> &ReMatIds, const MachineLoopInfo *loopInfo,
-        BitVector &SpillMBBs,
-        DenseMap<unsigned,std::vector<SRInfo> > &SpillIdxes,
-        BitVector &RestoreMBBs,
-        DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes,
-        DenseMap<unsigned,unsigned> &MBBVRegsMap,
-        std::vector<LiveInterval*> &NewLIs);
-
     static LiveInterval* createInterval(unsigned Reg);
=20
     void printInstrs(raw_ostream &O) const;
     void dumpInstrs() const;
+
+    class HMEditor;
   };
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/LiveVariables.h
--- a/head/contrib/llvm/include/llvm/CodeGen/LiveVariables.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/LiveVariables.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -85,17 +85,11 @@
     ///
     SparseBitVector<> AliveBlocks;
=20
-    /// NumUses - Number of uses of this register across the entire functi=
on.
-    ///
-    unsigned NumUses;
-
     /// Kills - List of MachineInstruction's which are the last use of this
     /// virtual register (kill it) in their basic block.
     ///
     std::vector<MachineInstr*> Kills;
=20
-    VarInfo() : NumUses(0) {}
-
     /// removeKill - Delete a kill corresponding to the specified
     /// machine instruction. Returns true if there was a kill
     /// corresponding to this instruction, false otherwise.
@@ -166,6 +160,9 @@
   /// the last use of the whole register.
   bool HandlePhysRegKill(unsigned Reg, MachineInstr *MI);
=20
+  /// HandleRegMask - Call HandlePhysRegKill for all registers clobbered b=
y Mask.
+  void HandleRegMask(const MachineOperand&);
+
   void HandlePhysRegUse(unsigned Reg, MachineInstr *MI);
   void HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
                         SmallVector<unsigned, 4> &Defs);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineBasicBlock.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineBasicBlock.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineBasicBlock.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -77,6 +77,7 @@
   /// (disable optimization).
   std::vector<uint32_t> Weights;
   typedef std::vector<uint32_t>::iterator weight_iterator;
+  typedef std::vector<uint32_t>::const_iterator const_weight_iterator;
=20
   /// LiveIns - Keep track of the physical registers that are livein of
   /// the basicblock.
@@ -84,8 +85,9 @@
=20
   /// Alignment - Alignment of the basic block. Zero if the basic block do=
es
   /// not need to be aligned.
+  /// The alignment is specified as log2(bytes).
   unsigned Alignment;
- =20
+
   /// IsLandingPad - Indicate that this basic block is entered via an
   /// exception handler.
   bool IsLandingPad;
@@ -115,6 +117,10 @@
   /// "(null)".
   StringRef getName() const;
=20
+  /// getFullName - Return a formatted string to identify this block and i=
ts
+  /// parent function.
+  std::string getFullName() const;
+
   /// hasAddressTaken - Test whether this block is potentially the target
   /// of an indirect branch.
   bool hasAddressTaken() const { return AddressTaken; }
@@ -128,10 +134,89 @@
   const MachineFunction *getParent() const { return xParent; }
   MachineFunction *getParent() { return xParent; }
=20
-  typedef Instructions::iterator                              iterator;
-  typedef Instructions::const_iterator                  const_iterator;
-  typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
-  typedef std::reverse_iterator<iterator>             reverse_iterator;
+
+  /// bundle_iterator - MachineBasicBlock iterator that automatically skip=
s over
+  /// MIs that are inside bundles (i.e. walk top level MIs only).
+  template<typename Ty, typename IterTy>
+  class bundle_iterator
+    : public std::iterator<std::bidirectional_iterator_tag, Ty, ptrdiff_t>=
 {
+    IterTy MII;
+
+  public:
+    bundle_iterator(IterTy mii) : MII(mii) {
+      assert(!MII->isInsideBundle() &&
+             "It's not legal to initialize bundle_iterator with a bundled =
MI");
+    }
+
+    bundle_iterator(Ty &mi) : MII(mi) {
+      assert(!mi.isInsideBundle() &&
+             "It's not legal to initialize bundle_iterator with a bundled =
MI");
+    }
+    bundle_iterator(Ty *mi) : MII(mi) {
+      assert((!mi || !mi->isInsideBundle()) &&
+             "It's not legal to initialize bundle_iterator with a bundled =
MI");
+    }
+    bundle_iterator(const bundle_iterator &I) : MII(I.MII) {}
+    bundle_iterator() : MII(0) {}
+
+    Ty &operator*() const { return *MII; }
+    Ty *operator->() const { return &operator*(); }
+
+    operator Ty*() const { return MII; }
+
+    bool operator=3D=3D(const bundle_iterator &x) const {
+      return MII =3D=3D x.MII;
+    }
+    bool operator!=3D(const bundle_iterator &x) const {
+      return !operator=3D=3D(x);
+    }
+
+    // Increment and decrement operators...
+    bundle_iterator &operator--() {      // predecrement - Back up
+      do {
+        --MII;
+      } while (MII->isInsideBundle());
+      return *this;
+    }
+    bundle_iterator &operator++() {      // preincrement - Advance
+      do {
+        ++MII;
+      } while (MII->isInsideBundle());
+      return *this;
+    }
+    bundle_iterator operator--(int) {    // postdecrement operators...
+      bundle_iterator tmp =3D *this;
+      do {
+        --MII;
+      } while (MII->isInsideBundle());
+      return tmp;
+    }
+    bundle_iterator operator++(int) {    // postincrement operators...
+      bundle_iterator tmp =3D *this;
+      do {
+        ++MII;
+      } while (MII->isInsideBundle());
+      return tmp;
+    }
+
+    IterTy getInstrIterator() const {
+      return MII;
+    }
+  };
+
+  typedef Instructions::iterator                                 instr_ite=
rator;
+  typedef Instructions::const_iterator                     const_instr_ite=
rator;
+  typedef std::reverse_iterator<instr_iterator>          reverse_instr_ite=
rator;
+  typedef
+  std::reverse_iterator<const_instr_iterator>      const_reverse_instr_ite=
rator;
+
+  typedef
+  bundle_iterator<MachineInstr,instr_iterator>                         ite=
rator;
+  typedef
+  bundle_iterator<const MachineInstr,const_instr_iterator>       const_ite=
rator;
+  typedef std::reverse_iterator<const_iterator>          const_reverse_ite=
rator;
+  typedef std::reverse_iterator<iterator>                      reverse_ite=
rator;
+
=20
   unsigned size() const { return (unsigned)Insts.size(); }
   bool empty() const { return Insts.empty(); }
@@ -141,15 +226,53 @@
   const MachineInstr& front() const { return Insts.front(); }
   const MachineInstr& back()  const { return Insts.back(); }
=20
+  instr_iterator                instr_begin()       { return Insts.begin()=
;  }
+  const_instr_iterator          instr_begin() const { return Insts.begin()=
;  }
+  instr_iterator                  instr_end()       { return Insts.end(); =
   }
+  const_instr_iterator            instr_end() const { return Insts.end(); =
   }
+  reverse_instr_iterator       instr_rbegin()       { return Insts.rbegin(=
); }
+  const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(=
); }
+  reverse_instr_iterator       instr_rend  ()       { return Insts.rend();=
   }
+  const_reverse_instr_iterator instr_rend  () const { return Insts.rend();=
   }
+
   iterator                begin()       { return Insts.begin();  }
   const_iterator          begin() const { return Insts.begin();  }
-  iterator                  end()       { return Insts.end();    }
-  const_iterator            end() const { return Insts.end();    }
-  reverse_iterator       rbegin()       { return Insts.rbegin(); }
-  const_reverse_iterator rbegin() const { return Insts.rbegin(); }
+  iterator                  end()       {
+    instr_iterator II =3D instr_end();
+    if (II !=3D instr_begin()) {
+      while (II->isInsideBundle())
+        --II;
+    }
+    return II;
+  }
+  const_iterator            end() const {
+    const_instr_iterator II =3D instr_end();
+    if (II !=3D instr_begin()) {
+      while (II->isInsideBundle())
+        --II;
+    }
+    return II;
+  }
+  reverse_iterator       rbegin()       {
+    reverse_instr_iterator II =3D instr_rbegin();
+    if (II !=3D instr_rend()) {
+      while (II->isInsideBundle())
+        ++II;
+    }
+    return II;
+  }
+  const_reverse_iterator rbegin() const {
+    const_reverse_instr_iterator II =3D instr_rbegin();
+    if (II !=3D instr_rend()) {
+      while (II->isInsideBundle())
+        ++II;
+    }
+    return II;
+  }
   reverse_iterator       rend  ()       { return Insts.rend();   }
   const_reverse_iterator rend  () const { return Insts.rend();   }
=20
+
   // Machine-CFG iterators
   typedef std::vector<MachineBasicBlock *>::iterator       pred_iterator;
   typedef std::vector<MachineBasicBlock *>::const_iterator const_pred_iter=
ator;
@@ -219,10 +342,12 @@
   bool            livein_empty() const { return LiveIns.empty(); }
=20
   /// getAlignment - Return alignment of the basic block.
+  /// The alignment is specified as log2(bytes).
   ///
   unsigned getAlignment() const { return Alignment; }
=20
   /// setAlignment - Set alignment of the basic block.
+  /// The alignment is specified as log2(bytes).
   ///
   void setAlignment(unsigned Align) { Alignment =3D Align; }
=20
@@ -239,7 +364,7 @@
   const MachineBasicBlock *getLandingPadSuccessor() const;
=20
   // Code Layout methods.
- =20
+
   /// moveBefore/moveAfter - move 'this' block before or after the specifi=
ed
   /// block.  This only moves the block, it does not modify the CFG or adj=
ust
   /// potential fall-throughs at the end of the block.
@@ -286,7 +411,7 @@
   /// in transferSuccessors, and update PHI operands in the successor bloc=
ks
   /// which refer to fromMBB to refer to this.
   void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB);
- =20
+
   /// isSuccessor - Return true if the specified MBB is a successor of this
   /// block.
   bool isSuccessor(const MachineBasicBlock *MBB) const;
@@ -304,7 +429,7 @@
   /// branch to do so (e.g., a table jump).  True is a conservative answer.
   bool canFallThrough();
=20
-  /// Returns a pointer to the first instructon in this block that is not =
a=20
+  /// Returns a pointer to the first instructon in this block that is not a
   /// PHINode instruction. When adding instruction to the beginning of the
   /// basic block, they should be added before the returned value, not bef=
ore
   /// the first instruction, which might be PHI.
@@ -320,18 +445,16 @@
   /// instruction of this basic block. If a terminator does not exist,
   /// it returns end()
   iterator getFirstTerminator();
+  const_iterator getFirstTerminator() const;
=20
-  const_iterator getFirstTerminator() const {
-    return const_cast<MachineBasicBlock*>(this)->getFirstTerminator();
-  }
+  /// getFirstInstrTerminator - Same getFirstTerminator but it ignores bun=
dles
+  /// and return an instr_iterator instead.
+  instr_iterator getFirstInstrTerminator();
=20
   /// getLastNonDebugInstr - returns an iterator to the last non-debug
   /// instruction in the basic block, or end()
   iterator getLastNonDebugInstr();
-
-  const_iterator getLastNonDebugInstr() const {
-    return const_cast<MachineBasicBlock*>(this)->getLastNonDebugInstr();
-  }
+  const_iterator getLastNonDebugInstr() const;
=20
   /// SplitCriticalEdge - Split the critical edge from this block to the
   /// given successor block, and return the newly created block, or null
@@ -344,38 +467,88 @@
   void pop_front() { Insts.pop_front(); }
   void pop_back() { Insts.pop_back(); }
   void push_back(MachineInstr *MI) { Insts.push_back(MI); }
+
   template<typename IT>
-  void insert(iterator I, IT S, IT E) { Insts.insert(I, S, E); }
-  iterator insert(iterator I, MachineInstr *M) { return Insts.insert(I, M)=
; }
-  iterator insertAfter(iterator I, MachineInstr *M) {=20
-    return Insts.insertAfter(I, M);=20
+  void insert(instr_iterator I, IT S, IT E) {
+    Insts.insert(I, S, E);
+  }
+  instr_iterator insert(instr_iterator I, MachineInstr *M) {
+    return Insts.insert(I, M);
+  }
+  instr_iterator insertAfter(instr_iterator I, MachineInstr *M) {
+    return Insts.insertAfter(I, M);
   }
=20
-  // erase - Remove the specified element or range from the instruction li=
st.
-  // These functions delete any instructions removed.
-  //
-  iterator erase(iterator I)             { return Insts.erase(I); }
-  iterator erase(iterator I, iterator E) { return Insts.erase(I, E); }
-  MachineInstr *remove(MachineInstr *I)  { return Insts.remove(I); }
-  void clear()                           { Insts.clear(); }
+  template<typename IT>
+  void insert(iterator I, IT S, IT E) {
+    Insts.insert(I.getInstrIterator(), S, E);
+  }
+  iterator insert(iterator I, MachineInstr *M) {
+    return Insts.insert(I.getInstrIterator(), M);
+  }
+  iterator insertAfter(iterator I, MachineInstr *M) {
+    return Insts.insertAfter(I.getInstrIterator(), M);
+  }
+
+  /// erase - Remove the specified element or range from the instruction l=
ist.
+  /// These functions delete any instructions removed.
+  ///
+  instr_iterator erase(instr_iterator I) {
+    return Insts.erase(I);
+  }
+  instr_iterator erase(instr_iterator I, instr_iterator E) {
+    return Insts.erase(I, E);
+  }
+  instr_iterator erase_instr(MachineInstr *I) {
+    instr_iterator MII(I);
+    return erase(MII);
+  }
+
+  iterator erase(iterator I);
+  iterator erase(iterator I, iterator E) {
+    return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
+  }
+  iterator erase(MachineInstr *I) {
+    iterator MII(I);
+    return erase(MII);
+  }
+
+  /// remove - Remove the instruction from the instruction list. This func=
tion
+  /// does not delete the instruction. WARNING: Note, if the specified
+  /// instruction is a bundle this function will remove all the bundled
+  /// instructions as well. It is up to the caller to keep a list of the
+  /// bundled instructions and re-insert them if desired. This function is
+  /// *not recommended* for manipulating instructions with bundles. Use
+  /// splice instead.
+  MachineInstr *remove(MachineInstr *I);
+  void clear() {
+    Insts.clear();
+  }
=20
   /// splice - Take an instruction from MBB 'Other' at the position From,
   /// and insert it into this MBB right before 'where'.
-  void splice(iterator where, MachineBasicBlock *Other, iterator From) {
+  void splice(instr_iterator where, MachineBasicBlock *Other,
+              instr_iterator From) {
     Insts.splice(where, Other->Insts, From);
   }
+  void splice(iterator where, MachineBasicBlock *Other, iterator From);
=20
   /// splice - Take a block of instructions from MBB 'Other' in the range =
[From,
   /// To), and insert them into this MBB right before 'where'.
+  void splice(instr_iterator where, MachineBasicBlock *Other, instr_iterat=
or From,
+              instr_iterator To) {
+    Insts.splice(where, Other->Insts, From, To);
+  }
   void splice(iterator where, MachineBasicBlock *Other, iterator From,
               iterator To) {
-    Insts.splice(where, Other->Insts, From, To);
+    Insts.splice(where.getInstrIterator(), Other->Insts,
+                 From.getInstrIterator(), To.getInstrIterator());
   }
=20
   /// removeFromParent - This method unlinks 'this' from the containing
   /// function, and returns it, but does not delete it.
   MachineBasicBlock *removeFromParent();
- =20
+
   /// eraseFromParent - This method unlinks 'this' from the containing
   /// function and deletes it.
   void eraseFromParent();
@@ -396,7 +569,10 @@
=20
   /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skippi=
ng
   /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
-  DebugLoc findDebugLoc(MachineBasicBlock::iterator &MBBI);
+  DebugLoc findDebugLoc(instr_iterator MBBI);
+  DebugLoc findDebugLoc(iterator MBBI) {
+    return findDebugLoc(MBBI.getInstrIterator());
+  }
=20
   // Debugging methods.
   void dump() const;
@@ -418,13 +594,14 @@
   /// getWeightIterator - Return weight iterator corresponding to the I
   /// successor iterator.
   weight_iterator getWeightIterator(succ_iterator I);
+  const_weight_iterator getWeightIterator(const_succ_iterator I) const;
=20
   friend class MachineBranchProbabilityInfo;
=20
   /// getSuccWeight - Return weight of the edge from this block to MBB. Th=
is
   /// method should NOT be called directly, but by using getEdgeWeight met=
hod
   /// from MachineBranchProbabilityInfo class.
-  uint32_t getSuccWeight(MachineBasicBlock *succ);
+  uint32_t getSuccWeight(const MachineBasicBlock *succ) const;
=20
=20
   // Methods used to maintain doubly linked list of blocks...
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineBlockFrequencyInfo.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineBlockFrequencyInfo.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineBlockFrequencyInfo.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
=20
 namespace llvm {
=20
+class MachineBasicBlock;
 class MachineBranchProbabilityInfo;
 template<class BlockT, class FunctionT, class BranchProbInfoT>
 class BlockFrequencyImpl;
@@ -28,7 +29,8 @@
 /// machine basic block frequencies.
 class MachineBlockFrequencyInfo : public MachineFunctionPass {
=20
-  BlockFrequencyImpl<MachineBasicBlock, MachineFunction, MachineBranchProb=
abilityInfo> *MBFI;
+  BlockFrequencyImpl<MachineBasicBlock, MachineFunction,
+                     MachineBranchProbabilityInfo> *MBFI;
=20
 public:
   static char ID;
@@ -46,7 +48,7 @@
   /// that we should not rely on the value itself, but only on the compari=
son to
   /// the other block frequencies. We do this to avoid using of floating p=
oints.
   ///
-  BlockFrequency getBlockFreq(MachineBasicBlock *MBB) const;
+  BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const;
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineBranchProbabilityInfo.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineBranchProbabilityInfo.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineBranchProbabilityInfo.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -25,6 +25,7 @@
 class MachineBasicBlock;
=20
 class MachineBranchProbabilityInfo : public ImmutablePass {
+  virtual void anchor();
=20
   // Default weight value. Used when we don't have information about the e=
dge.
   // TODO: DEFAULT_WEIGHT makes sense during static predication, when none=
 of
@@ -34,9 +35,6 @@
   // weight to just "inherit" the non-zero weight of an adjacent successor.
   static const uint32_t DEFAULT_WEIGHT =3D 16;
=20
-  // Get sum of the block successors' weights.
-  uint32_t getSumForBlock(MachineBasicBlock *MBB) const;
-
 public:
   static char ID;
=20
@@ -51,17 +49,27 @@
=20
   // Return edge weight. If we don't have any informations about it - retu=
rn
   // DEFAULT_WEIGHT.
-  uint32_t getEdgeWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst) c=
onst;
+  uint32_t getEdgeWeight(const MachineBasicBlock *Src,
+                         const MachineBasicBlock *Dst) const;
+
+  // Get sum of the block successors' weights, potentially scaling them to=
 fit
+  // within 32-bits. If scaling is required, sets Scale based on the neces=
sary
+  // adjustment. Any edge weights used with the sum should be divided by S=
cale.
+  uint32_t getSumForBlock(const MachineBasicBlock *MBB, uint32_t &Scale) c=
onst;
=20
   // A 'Hot' edge is an edge which probability is >=3D 80%.
   bool isEdgeHot(MachineBasicBlock *Src, MachineBasicBlock *Dst) const;
=20
   // Return a hot successor for the block BB or null if there isn't one.
+  // NB: This routine's complexity is linear on the number of successors.
   MachineBasicBlock *getHotSucc(MachineBasicBlock *MBB) const;
=20
   // Return a probability as a fraction between 0 (0% probability) and
   // 1 (100% probability), however the value is never equal to 0, and can =
be 1
   // only iff SRC block has only one successor.
+  // NB: This routine's complexity is linear on the number of successors of
+  // Src. Querying sequentially for each successor's probability is a quad=
ratic
+  // query pattern.
   BranchProbability getEdgeProbability(MachineBasicBlock *Src,
                                        MachineBasicBlock *Dst) const;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineCodeEmitter.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineCodeEmitter.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineCodeEmitter.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -20,6 +20,8 @@
 #include "llvm/Support/DataTypes.h"
 #include "llvm/Support/DebugLoc.h"
=20
+#include <string>
+
 namespace llvm {
=20
 class MachineBasicBlock;
@@ -49,6 +51,7 @@
 /// occurred, more memory is allocated, and we reemit the code into it.
 ///=20
 class MachineCodeEmitter {
+  virtual void anchor();
 protected:
   /// BufferBegin/BufferEnd - Pointers to the start and end of the memory
   /// allocated for this code buffer.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineConstantPool.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineConstantPool.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineConstantPool.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -34,6 +34,7 @@
 /// Abstract base class for all machine specific constantpool value subcla=
sses.
 ///
 class MachineConstantPoolValue {
+  virtual void anchor();
   Type *Ty;
=20
 public:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineDominators.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineDominators.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineDominators.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -84,7 +84,8 @@
=20
     // Loop through the basic block until we find A or B.
     MachineBasicBlock::iterator I =3D BBA->begin();
-    for (; &*I !=3D A && &*I !=3D B; ++I) /*empty*/;
+    for (; &*I !=3D A && &*I !=3D B; ++I)
+      /*empty*/ ;
=20
     //if(!DT.IsPostDominators) {
       // A dominates B if it is found first in the basic block.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineFrameInfo.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineFrameInfo.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineFrameInfo.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -465,7 +465,7 @@
   bool isSpillSlotObjectIndex(int ObjectIdx) const {
     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
            "Invalid Object Idx!");
-    return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;;
+    return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
   }
=20
   /// isDeadObjectIndex - Returns true if the specified index corresponds =
to
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineFunction.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineFunction.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineFunction.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -120,10 +120,12 @@
   /// Alignment - The alignment of the function.
   unsigned Alignment;
=20
-  /// CallsSetJmp - True if the function calls setjmp or sigsetjmp. This i=
s used
-  /// to limit optimizations which cannot reason about the control flow of
-  /// setjmp.
-  bool CallsSetJmp;
+  /// ExposesReturnsTwice - True if the function calls setjmp or related
+  /// functions with attribute "returns twice", but doesn't have
+  /// the attribute itself.
+  /// This is used to limit optimizations which cannot reason
+  /// about the control flow of such functions.
+  bool ExposesReturnsTwice;
=20
   MachineFunction(const MachineFunction &); // DO NOT IMPLEMENT
   void operator=3D(const MachineFunction&);   // DO NOT IMPLEMENT
@@ -187,20 +189,22 @@
   ///
   void setAlignment(unsigned A) { Alignment =3D A; }
=20
-  /// EnsureAlignment - Make sure the function is at least 'A' bits aligne=
d.
+  /// EnsureAlignment - Make sure the function is at least 1 << A bytes al=
igned.
   void EnsureAlignment(unsigned A) {
     if (Alignment < A) Alignment =3D A;
   }
=20
-  /// callsSetJmp - Returns true if the function calls setjmp or sigsetjmp.
-  bool callsSetJmp() const {
-    return CallsSetJmp;
+  /// exposesReturnsTwice - Returns true if the function calls setjmp or
+  /// any other similar functions with attribute "returns twice" without
+  /// having the attribute itself.
+  bool exposesReturnsTwice() const {
+    return ExposesReturnsTwice;
   }
=20
-  /// setCallsSetJmp - Set a flag that indicates if there's a call to setj=
mp or
-  /// sigsetjmp.
-  void setCallsSetJmp(bool B) {
-    CallsSetJmp =3D B;
+  /// setCallsSetJmp - Set a flag that indicates if there's a call to
+  /// a "returns twice" function.
+  void setExposesReturnsTwice(bool B) {
+    ExposesReturnsTwice =3D B;
   }
  =20
   /// getInfo - Keep track of various per-function pieces of information f=
or
@@ -376,7 +380,8 @@
   MachineMemOperand *getMachineMemOperand(MachinePointerInfo PtrInfo,
                                           unsigned f, uint64_t s,
                                           unsigned base_alignment,
-                                          const MDNode *TBAAInfo =3D 0);
+                                          const MDNode *TBAAInfo =3D 0,
+                                          const MDNode *Ranges =3D 0);
  =20
   /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
   /// an existing one, adjusting by an offset and using the given size.
@@ -437,6 +442,7 @@
   typedef MachineFunction::iterator nodes_iterator;
   static nodes_iterator nodes_begin(MachineFunction *F) { return F->begin(=
); }
   static nodes_iterator nodes_end  (MachineFunction *F) { return F->end();=
 }
+  static unsigned       size       (MachineFunction *F) { return F->size()=
; }
 };
 template <> struct GraphTraits<const MachineFunction*> :
   public GraphTraits<const MachineBasicBlock*> {
@@ -452,6 +458,9 @@
   static nodes_iterator nodes_end  (const MachineFunction *F) {
     return F->end();
   }
+  static unsigned       size       (const MachineFunction *F)  {
+    return F->size();
+  }
 };
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineFunctionAnalysis.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineFunctionAnalysis.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineFunctionAnalysis.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -26,17 +26,14 @@
 struct MachineFunctionAnalysis : public FunctionPass {
 private:
   const TargetMachine &TM;
-  CodeGenOpt::Level OptLevel;
   MachineFunction *MF;
   unsigned NextFnNum;
 public:
   static char ID;
-  explicit MachineFunctionAnalysis(const TargetMachine &tm,
-                                   CodeGenOpt::Level OL =3D CodeGenOpt::De=
fault);
+  explicit MachineFunctionAnalysis(const TargetMachine &tm);
   ~MachineFunctionAnalysis();
=20
   MachineFunction &getMF() const { return *MF; }
-  CodeGenOpt::Level getOptLevel() const { return OptLevel; }
  =20
   virtual const char* getPassName() const {
     return "Machine Function Analysis";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineInstr.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineInstr.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineInstr.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/MC/MCInstrDesc.h"
 #include "llvm/Target/TargetOpcodes.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/ilist.h"
 #include "llvm/ADT/ilist_node.h"
 #include "llvm/ADT/STLExtras.h"
@@ -53,9 +54,11 @@
   };
=20
   enum MIFlag {
-    NoFlags    =3D 0,
-    FrameSetup =3D 1 << 0                 // Instruction is used as a part=
 of
+    NoFlags      =3D 0,
+    FrameSetup   =3D 1 << 0,              // Instruction is used as a part=
 of
                                         // function frame setup code.
+    InsideBundle =3D 1 << 1               // Instruction is inside a bundl=
e (not
+                                        // the first MI in a bundle)
   };
 private:
   const MCInstrDesc *MCID;              // Instruction descriptor.
@@ -71,9 +74,10 @@
                                         // anything other than to convey c=
omment
                                         // information to AsmPrinter.
=20
+  uint16_t NumMemRefs;                  // information on memory references
+  mmo_iterator MemRefs;
+
   std::vector<MachineOperand> Operands; // the operands
-  mmo_iterator MemRefs;                 // information on memory references
-  mmo_iterator MemRefsEnd;
   MachineBasicBlock *Parent;            // Pointer to the owning basic blo=
ck.
   DebugLoc debugLoc;                    // Source line information.
=20
@@ -148,6 +152,12 @@
     AsmPrinterFlags |=3D (uint8_t)Flag;
   }
=20
+  /// clearAsmPrinterFlag - clear specific AsmPrinter flags
+  ///
+  void clearAsmPrinterFlag(CommentFlag Flag) {
+    AsmPrinterFlags &=3D ~Flag;
+  }
+
   /// getFlags - Return the MI flags bitvector.
   uint8_t getFlags() const {
     return Flags;
@@ -167,12 +177,64 @@
     Flags =3D flags;
   }
=20
-  /// clearAsmPrinterFlag - clear specific AsmPrinter flags
+  /// clearFlag - Clear a MI flag.
+  void clearFlag(MIFlag Flag) {
+    Flags &=3D ~((uint8_t)Flag);
+  }
+
+  /// isInsideBundle - Return true if MI is in a bundle (but not the first=
 MI
+  /// in a bundle).
   ///
-  void clearAsmPrinterFlag(CommentFlag Flag) {
-    AsmPrinterFlags &=3D ~Flag;
+  /// A bundle looks like this before it's finalized:
+  ///   ----------------
+  ///   |      MI      |
+  ///   ----------------
+  ///          |
+  ///   ----------------
+  ///   |      MI    * |
+  ///   ----------------
+  ///          |
+  ///   ----------------
+  ///   |      MI    * |
+  ///   ----------------
+  /// In this case, the first MI starts a bundle but is not inside a bundl=
e, the
+  /// next 2 MIs are considered "inside" the bundle.
+  ///
+  /// After a bundle is finalized, it looks like this:
+  ///   ----------------
+  ///   |    Bundle    |
+  ///   ----------------
+  ///          |
+  ///   ----------------
+  ///   |      MI    * |
+  ///   ----------------
+  ///          |
+  ///   ----------------
+  ///   |      MI    * |
+  ///   ----------------
+  ///          |
+  ///   ----------------
+  ///   |      MI    * |
+  ///   ----------------
+  /// The first instruction has the special opcode "BUNDLE". It's not "ins=
ide"
+  /// a bundle, but the next three MIs are.
+  bool isInsideBundle() const {
+    return getFlag(InsideBundle);
   }
=20
+  /// setIsInsideBundle - Set InsideBundle bit.
+  ///
+  void setIsInsideBundle(bool Val =3D true) {
+    if (Val)
+      setFlag(InsideBundle);
+    else
+      clearFlag(InsideBundle);
+  }
+
+  /// isBundled - Return true if this instruction part of a bundle. This i=
s true
+  /// if either itself or its following instruction is marked "InsideBundl=
e".
+  bool isBundled() const;
+
   /// getDebugLoc - Returns the debug location id of this MachineInstr.
   ///
   DebugLoc getDebugLoc() const { return debugLoc; }
@@ -223,15 +285,285 @@
=20
   /// Access to memory operands of the instruction
   mmo_iterator memoperands_begin() const { return MemRefs; }
-  mmo_iterator memoperands_end() const { return MemRefsEnd; }
-  bool memoperands_empty() const { return MemRefsEnd =3D=3D MemRefs; }
+  mmo_iterator memoperands_end() const { return MemRefs + NumMemRefs; }
+  bool memoperands_empty() const { return NumMemRefs =3D=3D 0; }
=20
   /// hasOneMemOperand - Return true if this instruction has exactly one
   /// MachineMemOperand.
   bool hasOneMemOperand() const {
-    return MemRefsEnd - MemRefs =3D=3D 1;
+    return NumMemRefs =3D=3D 1;
   }
=20
+  /// API for querying MachineInstr properties. They are the same as MCIns=
trDesc
+  /// queries but they are bundle aware.
+
+  enum QueryType {
+    IgnoreBundle,    // Ignore bundles
+    AnyInBundle,     // Return true if any instruction in bundle has prope=
rty
+    AllInBundle      // Return true if all instructions in bundle have pro=
perty
+  };
+
+  /// hasProperty - Return true if the instruction (or in the case of a bu=
ndle,
+  /// the instructions inside the bundle) has the specified property.
+  /// The first argument is the property being queried.
+  /// The second argument indicates whether the query should look inside
+  /// instruction bundles.
+  bool hasProperty(unsigned MCFlag, QueryType Type =3D AnyInBundle) const {
+    // Inline the fast path.
+    if (Type =3D=3D IgnoreBundle || !isBundle())
+      return getDesc().getFlags() & (1 << MCFlag);
+
+    // If we have a bundle, take the slow path.
+    return hasPropertyInBundle(1 << MCFlag, Type);
+  }
+
+  /// isVariadic - Return true if this instruction can have a variable num=
ber of
+  /// operands.  In this case, the variable operands will be after the nor=
mal
+  /// operands but before the implicit definitions and uses (if any are
+  /// present).
+  bool isVariadic(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::Variadic, Type);
+  }
+
+  /// hasOptionalDef - Set if this instruction has an optional definition,=
 e.g.
+  /// ARM instructions which can set condition code if 's' bit is set.
+  bool hasOptionalDef(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::HasOptionalDef, Type);
+  }
+
+  /// isPseudo - Return true if this is a pseudo instruction that doesn't
+  /// correspond to a real machine instruction.
+  ///
+  bool isPseudo(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::Pseudo, Type);
+  }
+
+  bool isReturn(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::Return, Type);
+  }
+
+  bool isCall(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::Call, Type);
+  }
+
+  /// isBarrier - Returns true if the specified instruction stops control =
flow
+  /// from executing the instruction immediately following it.  Examples i=
nclude
+  /// unconditional branches and return instructions.
+  bool isBarrier(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::Barrier, Type);
+  }
+
+  /// isTerminator - Returns true if this instruction part of the terminat=
or for
+  /// a basic block.  Typically this is things like return and branch
+  /// instructions.
+  ///
+  /// Various passes use this to insert code into the bottom of a basic bl=
ock,
+  /// but before control flow occurs.
+  bool isTerminator(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::Terminator, Type);
+  }
+
+  /// isBranch - Returns true if this is a conditional, unconditional, or
+  /// indirect branch.  Predicates below can be used to discriminate betwe=
en
+  /// these cases, and the TargetInstrInfo::AnalyzeBranch method can be us=
ed to
+  /// get more information.
+  bool isBranch(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::Branch, Type);
+  }
+
+  /// isIndirectBranch - Return true if this is an indirect branch, such a=
s a
+  /// branch through a register.
+  bool isIndirectBranch(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::IndirectBranch, Type);
+  }
+
+  /// isConditionalBranch - Return true if this is a branch which may fall
+  /// through to the next instruction or may transfer control flow to some=
 other
+  /// block.  The TargetInstrInfo::AnalyzeBranch method can be used to get=
 more
+  /// information about this branch.
+  bool isConditionalBranch(QueryType Type =3D AnyInBundle) const {
+    return isBranch(Type) & !isBarrier(Type) & !isIndirectBranch(Type);
+  }
+
+  /// isUnconditionalBranch - Return true if this is a branch which always
+  /// transfers control flow to some other block.  The
+  /// TargetInstrInfo::AnalyzeBranch method can be used to get more inform=
ation
+  /// about this branch.
+  bool isUnconditionalBranch(QueryType Type =3D AnyInBundle) const {
+    return isBranch(Type) & isBarrier(Type) & !isIndirectBranch(Type);
+  }
+
+  // isPredicable - Return true if this instruction has a predicate operan=
d that
+  // controls execution.  It may be set to 'always', or may be set to other
+  /// values.   There are various methods in TargetInstrInfo that can be u=
sed to
+  /// control and modify the predicate in this instruction.
+  bool isPredicable(QueryType Type =3D AllInBundle) const {
+    // If it's a bundle than all bundled instructions must be predicable f=
or this
+    // to return true.
+    return hasProperty(MCID::Predicable, Type);
+  }
+
+  /// isCompare - Return true if this instruction is a comparison.
+  bool isCompare(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::Compare, Type);
+  }
+
+  /// isMoveImmediate - Return true if this instruction is a move immediate
+  /// (including conditional moves) instruction.
+  bool isMoveImmediate(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::MoveImm, Type);
+  }
+
+  /// isBitcast - Return true if this instruction is a bitcast instruction.
+  ///
+  bool isBitcast(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::Bitcast, Type);
+  }
+
+  /// isNotDuplicable - Return true if this instruction cannot be safely
+  /// duplicated.  For example, if the instruction has a unique labels att=
ached
+  /// to it, duplicating it would cause multiple definition errors.
+  bool isNotDuplicable(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::NotDuplicable, Type);
+  }
+
+  /// hasDelaySlot - Returns true if the specified instruction has a delay=
 slot
+  /// which must be filled by the code generator.
+  bool hasDelaySlot(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::DelaySlot, Type);
+  }
+
+  /// canFoldAsLoad - Return true for instructions that can be folded as
+  /// memory operands in other instructions. The most common use for this
+  /// is instructions that are simple loads from memory that don't modify
+  /// the loaded value in any way, but it can also be used for instructions
+  /// that can be expressed as constant-pool loads, such as V_SETALLONES
+  /// on x86, to allow them to be folded when it is beneficial.
+  /// This should only be set on instructions that return a value in their
+  /// only virtual register definition.
+  bool canFoldAsLoad(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::FoldableAsLoad, Type);
+  }
+
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+  // Side Effect Analysis
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+
+  /// mayLoad - Return true if this instruction could possibly read memory.
+  /// Instructions with this flag set are not necessarily simple load
+  /// instructions, they may load a value and modify it, for example.
+  bool mayLoad(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::MayLoad, Type);
+  }
+
+
+  /// mayStore - Return true if this instruction could possibly modify mem=
ory.
+  /// Instructions with this flag set are not necessarily simple store
+  /// instructions, they may store a modified value based on their operand=
s, or
+  /// may not actually modify anything, for example.
+  bool mayStore(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::MayStore, Type);
+  }
+
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+  // Flags that indicate whether an instruction can be modified by a metho=
d.
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+
+  /// isCommutable - Return true if this may be a 2- or 3-address
+  /// instruction (of the form "X =3D op Y, Z, ..."), which produces the s=
ame
+  /// result if Y and Z are exchanged.  If this flag is set, then the
+  /// TargetInstrInfo::commuteInstruction method may be used to hack on the
+  /// instruction.
+  ///
+  /// Note that this flag may be set on instructions that are only commuta=
ble
+  /// sometimes.  In these cases, the call to commuteInstruction will fail.
+  /// Also note that some instructions require non-trivial modification to
+  /// commute them.
+  bool isCommutable(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::Commutable, Type);
+  }
+
+  /// isConvertibleTo3Addr - Return true if this is a 2-address instruction
+  /// which can be changed into a 3-address instruction if needed.  Doing =
this
+  /// transformation can be profitable in the register allocator, because =
it
+  /// means that the instruction can use a 2-address form if possible, but
+  /// degrade into a less efficient form if the source and dest register c=
annot
+  /// be assigned to the same register.  For example, this allows the x86
+  /// backend to turn a "shl reg, 3" instruction into an LEA instruction, =
which
+  /// is the same speed as the shift but has bigger code size.
+  ///
+  /// If this returns true, then the target must implement the
+  /// TargetInstrInfo::convertToThreeAddress method for this instruction, =
which
+  /// is allowed to fail if the transformation isn't valid for this specif=
ic
+  /// instruction (e.g. shl reg, 4 on x86).
+  ///
+  bool isConvertibleTo3Addr(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::ConvertibleTo3Addr, Type);
+  }
+
+  /// usesCustomInsertionHook - Return true if this instruction requires
+  /// custom insertion support when the DAG scheduler is inserting it into=
 a
+  /// machine basic block.  If this is true for the instruction, it basica=
lly
+  /// means that it is a pseudo instruction used at SelectionDAG time that=
 is
+  /// expanded out into magic code by the target when MachineInstrs are fo=
rmed.
+  ///
+  /// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock met=
hod
+  /// is used to insert this into the MachineBasicBlock.
+  bool usesCustomInsertionHook(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::UsesCustomInserter, Type);
+  }
+
+  /// hasPostISelHook - Return true if this instruction requires *adjustme=
nt*
+  /// after instruction selection by calling a target hook. For example, t=
his
+  /// can be used to fill in ARM 's' optional operand depending on whether
+  /// the conditional flag register is used.
+  bool hasPostISelHook(QueryType Type =3D IgnoreBundle) const {
+    return hasProperty(MCID::HasPostISelHook, Type);
+  }
+
+  /// isRematerializable - Returns true if this instruction is a candidate=
 for
+  /// remat.  This flag is deprecated, please don't use it anymore.  If th=
is
+  /// flag is set, the isReallyTriviallyReMaterializable() method is calle=
d to
+  /// verify the instruction is really rematable.
+  bool isRematerializable(QueryType Type =3D AllInBundle) const {
+    // It's only possible to re-mat a bundle if all bundled instructions a=
re
+    // re-materializable.
+    return hasProperty(MCID::Rematerializable, Type);
+  }
+
+  /// isAsCheapAsAMove - Returns true if this instruction has the same cos=
t (or
+  /// less) than a move instruction. This is useful during certain types of
+  /// optimizations (e.g., remat during two-address conversion or machine =
licm)
+  /// where we would like to remat or hoist the instruction, but not if it=
 costs
+  /// more than moving the instruction into the appropriate register. Note=
, we
+  /// are not marking copies from and to the same register class with this=
 flag.
+  bool isAsCheapAsAMove(QueryType Type =3D AllInBundle) const {
+    // Only returns true for a bundle if all bundled instructions are chea=
p.
+    // FIXME: This probably requires a target hook.
+    return hasProperty(MCID::CheapAsAMove, Type);
+  }
+
+  /// hasExtraSrcRegAllocReq - Returns true if this instruction source ope=
rands
+  /// have special register allocation requirements that are not captured =
by the
+  /// operand register classes. e.g. ARM::STRD's two source registers must=
 be an
+  /// even / odd pair, ARM::STM registers have to be in ascending order.
+  /// Post-register allocation passes should not attempt to change allocat=
ions
+  /// for sources of instructions with this flag.
+  bool hasExtraSrcRegAllocReq(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::ExtraSrcRegAllocReq, Type);
+  }
+
+  /// hasExtraDefRegAllocReq - Returns true if this instruction def operan=
ds
+  /// have special register allocation requirements that are not captured =
by the
+  /// operand register classes. e.g. ARM::LDRD's two def registers must be=
 an
+  /// even / odd pair, ARM::LDM registers have to be in ascending order.
+  /// Post-register allocation passes should not attempt to change allocat=
ions
+  /// for definitions of instructions with this flag.
+  bool hasExtraDefRegAllocReq(QueryType Type =3D AnyInBundle) const {
+    return hasProperty(MCID::ExtraDefRegAllocReq, Type);
+  }
+
+
   enum MICheckType {
     CheckDefs,      // Check all operands for equality
     CheckKillDead,  // Check all operands including kill / dead markers
@@ -281,6 +613,9 @@
   bool isRegSequence() const {
     return getOpcode() =3D=3D TargetOpcode::REG_SEQUENCE;
   }
+  bool isBundle() const {
+    return getOpcode() =3D=3D TargetOpcode::BUNDLE;
+  }
   bool isCopy() const {
     return getOpcode() =3D=3D TargetOpcode::COPY;
   }
@@ -300,6 +635,9 @@
       getOperand(0).getSubReg() =3D=3D getOperand(1).getSubReg();
   }
=20
+  /// getBundleSize - Return the number of instructions inside the MI bund=
le.
+  unsigned getBundleSize() const;
+
   /// readsRegister - Return true if the MachineInstr reads the specified
   /// register. If TargetRegisterInfo is passed, then it also checks if th=
ere
   /// is a read of a super-register.
@@ -372,6 +710,7 @@
   /// that are not dead are skipped. If Overlap is true, then it also look=
s for
   /// defs that merely overlap the specified register. If TargetRegisterIn=
fo is
   /// non-null, then it also checks if there is a def of a super-register.
+  /// This may also return a register mask operand when Overlap is true.
   int findRegisterDefOperandIdx(unsigned Reg,
                                 bool isDead =3D false, bool Overlap =3D fa=
lse,
                                 const TargetRegisterInfo *TRI =3D NULL) co=
nst;
@@ -416,7 +755,7 @@
   /// isRegTiedToUseOperand - Given the index of a register def operand,
   /// check if the register def is tied to a source operand, due to either
   /// two-address elimination or inline assembly constraints. Returns the
-  /// first tied use operand index by reference is UseOpIdx is not null.
+  /// first tied use operand index by reference if UseOpIdx is not null.
   bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx =3D 0) =
const;
=20
   /// isRegTiedToDefOperand - Return true if the use operand of the specif=
ied
@@ -448,6 +787,10 @@
                          const TargetRegisterInfo *RegInfo,
                          bool AddIfNotFound =3D false);
=20
+  /// clearRegisterKills - Clear all kill flags affecting Reg.  If RegInfo=
 is
+  /// provided, this includes super-register kills.
+  void clearRegisterKills(unsigned Reg, const TargetRegisterInfo *RegInfo);
+
   /// addRegisterDead - We have determined MI defined a register without a=
 use.
   /// Look for the operand that defines it and mark it as IsDead. If
   /// AddIfNotFound is true, add a implicit operand if it's not found. Ret=
urns
@@ -462,7 +805,10 @@
=20
   /// setPhysRegsDeadExcept - Mark every physreg used by this instruction =
as
   /// dead except those in the UsedRegs list.
-  void setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &UsedRegs,
+  ///
+  /// On instructions with register mask operands, also add implicit-def
+  /// operands for all registers in UsedRegs.
+  void setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
                              const TargetRegisterInfo &TRI);
=20
   /// isSafeToMove - Return true if it is safe to move this instruction. If
@@ -550,7 +896,7 @@
   /// list. This does not transfer ownership.
   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
     MemRefs =3D NewMemRefs;
-    MemRefsEnd =3D NewMemRefsEnd;
+    NumMemRefs =3D NewMemRefsEnd - NewMemRefs;
   }
=20
 private:
@@ -572,6 +918,10 @@
   /// this instruction from their respective use lists.  This requires tha=
t the
   /// operands not be on their use lists yet.
   void AddRegOperandsToUseLists(MachineRegisterInfo &RegInfo);
+
+  /// hasPropertyInBundle - Slow path for hasProperty when we're dealing w=
ith a
+  /// bundle.
+  bool hasPropertyInBundle(unsigned Mask, QueryType Type) const;
 };
=20
 /// MachineInstrExpressionTrait - Special DenseMapInfo traits to compare
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineInstrBuilder.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineInstrBuilder.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineInstrBuilder.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -34,6 +34,7 @@
     Undef          =3D 0x20,
     EarlyClobber   =3D 0x40,
     Debug          =3D 0x80,
+    DefineNoRead   =3D Define | Undef,
     ImplicitDefine =3D Implicit | Define,
     ImplicitKill   =3D Implicit | Kill
   };
@@ -124,6 +125,11 @@
     return *this;
   }
=20
+  const MachineInstrBuilder &addRegMask(const uint32_t *Mask) const {
+    MI->addOperand(MachineOperand::CreateRegMask(Mask));
+    return *this;
+  }
+
   const MachineInstrBuilder &addMemOperand(MachineMemOperand *MMO) const {
     MI->addMemOperand(*MI->getParent()->getParent(), MMO);
     return *this;
@@ -209,6 +215,30 @@
   return MachineInstrBuilder(MI).addReg(DestReg, RegState::Define);
 }
=20
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+                                   MachineBasicBlock::instr_iterator I,
+                                   DebugLoc DL,
+                                   const MCInstrDesc &MCID,
+                                   unsigned DestReg) {
+  MachineInstr *MI =3D BB.getParent()->CreateMachineInstr(MCID, DL);
+  BB.insert(I, MI);
+  return MachineInstrBuilder(MI).addReg(DestReg, RegState::Define);
+}
+
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+                                   MachineInstr *I,
+                                   DebugLoc DL,
+                                   const MCInstrDesc &MCID,
+                                   unsigned DestReg) {
+  if (I->isInsideBundle()) {
+    MachineBasicBlock::instr_iterator MII =3D I;
+    return BuildMI(BB, MII, DL, MCID, DestReg);
+  }
+
+  MachineBasicBlock::iterator MII =3D I;
+  return BuildMI(BB, MII, DL, MCID, DestReg);
+}
+
 /// BuildMI - This version of the builder inserts the newly-built
 /// instruction before the given position in the given MachineBasicBlock, =
and
 /// does NOT take a destination register.
@@ -222,6 +252,28 @@
   return MachineInstrBuilder(MI);
 }
=20
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+                                   MachineBasicBlock::instr_iterator I,
+                                   DebugLoc DL,
+                                   const MCInstrDesc &MCID) {
+  MachineInstr *MI =3D BB.getParent()->CreateMachineInstr(MCID, DL);
+  BB.insert(I, MI);
+  return MachineInstrBuilder(MI);
+}
+
+inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
+                                   MachineInstr *I,
+                                   DebugLoc DL,
+                                   const MCInstrDesc &MCID) {
+  if (I->isInsideBundle()) {
+    MachineBasicBlock::instr_iterator MII =3D I;
+    return BuildMI(BB, MII, DL, MCID);
+  }
+
+  MachineBasicBlock::iterator MII =3D I;
+  return BuildMI(BB, MII, DL, MCID);
+}
+
 /// BuildMI - This version of the builder inserts the newly-built
 /// instruction at the end of the given MachineBasicBlock, and does NOT ta=
ke a
 /// destination register.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineJumpTableInfo.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineJumpTableInfo.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineJumpTableInfo.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -47,7 +47,12 @@
     /// EK_BlockAddress - Each entry is a plain address of block, e.g.:
     ///     .word LBB123
     EK_BlockAddress,
-   =20
+
+    /// EK_GPRel64BlockAddress - Each entry is an address of block, encoded
+    /// with a relocation as gp-relative, e.g.:
+    ///     .gpdword LBB123
+    EK_GPRel64BlockAddress,
+
     /// EK_GPRel32BlockAddress - Each entry is an address of block, encoded
     /// with a relocation as gp-relative, e.g.:
     ///     .gprel32 LBB123
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineMemOperand.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineMemOperand.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineMemOperand.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -22,6 +22,7 @@
=20
 class Value;
 class FoldingSetNodeID;
+class MDNode;
 class raw_ostream;
=20
 /// MachinePointerInfo - This class contains a discriminated union of
@@ -83,6 +84,7 @@
   uint64_t Size;
   unsigned Flags;
   const MDNode *TBAAInfo;
+  const MDNode *Ranges;
=20
 public:
   /// Flags values. These may be or'd together.
@@ -95,14 +97,17 @@
     MOVolatile =3D 4,
     /// The memory access is non-temporal.
     MONonTemporal =3D 8,
+    /// The memory access is invariant.
+    MOInvariant =3D 16,
     // This is the number of bits we need to represent flags.
-    MOMaxBits =3D 4
+    MOMaxBits =3D 5
   };
=20
   /// MachineMemOperand - Construct an MachineMemOperand object with the
   /// specified PtrInfo, flags, size, and base alignment.
   MachineMemOperand(MachinePointerInfo PtrInfo, unsigned flags, uint64_t s,
-                    unsigned base_alignment, const MDNode *TBAAInfo =3D 0);
+                    unsigned base_alignment, const MDNode *TBAAInfo =3D 0,
+                    const MDNode *Ranges =3D 0);
=20
   const MachinePointerInfo &getPointerInfo() const { return PtrInfo; }
  =20
@@ -137,10 +142,14 @@
   /// getTBAAInfo - Return the TBAA tag for the memory reference.
   const MDNode *getTBAAInfo() const { return TBAAInfo; }
=20
+  /// getRanges - Return the range tag for the memory reference.
+  const MDNode *getRanges() const { return Ranges; }
+
   bool isLoad() const { return Flags & MOLoad; }
   bool isStore() const { return Flags & MOStore; }
   bool isVolatile() const { return Flags & MOVolatile; }
   bool isNonTemporal() const { return Flags & MONonTemporal; }
+  bool isInvariant() const { return Flags & MOInvariant; }
=20
   /// refineAlignment - Update this MachineMemOperand to reflect the align=
ment
   /// of MMO, if it has a greater alignment. This must only be used when t=
he
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineModuleInfo.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineModuleInfo.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineModuleInfo.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -161,10 +161,10 @@
   /// in this module.
   bool DbgInfoAvailable;
=20
-  /// CallsExternalVAFunctionWithFloatingPointArguments - True if this mod=
ule
-  /// calls VarArg function with floating point arguments.  This is used t=
o emit
-  /// an undefined reference to fltused on Windows targets.
-  bool CallsExternalVAFunctionWithFloatingPointArguments;
+  /// UsesVAFloatArgument - True if this module calls VarArg function with
+  /// floating-point arguments.  This is used to emit an undefined referen=
ce
+  /// to _fltused on Windows targets.
+  bool UsesVAFloatArgument;
=20
 public:
   static char ID; // Pass identification, replacement for typeid
@@ -223,12 +223,12 @@
   bool callsUnwindInit() const { return CallsUnwindInit; }
   void setCallsUnwindInit(bool b) { CallsUnwindInit =3D b; }
=20
-  bool callsExternalVAFunctionWithFloatingPointArguments() const {
-    return CallsExternalVAFunctionWithFloatingPointArguments;
+  bool usesVAFloatArgument() const {
+    return UsesVAFloatArgument;
   }
=20
-  void setCallsExternalVAFunctionWithFloatingPointArguments(bool b) {
-    CallsExternalVAFunctionWithFloatingPointArguments =3D b;
+  void setUsesVAFloatArgument(bool b) {
+    UsesVAFloatArgument =3D b;
   }
=20
   /// getFrameMoves - Returns a reference to a list of moves done in the c=
urrent
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineOperand.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineOperand.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineOperand.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -48,6 +48,7 @@
     MO_ExternalSymbol,         ///< Name of external global symbol
     MO_GlobalAddress,          ///< Address of a global value
     MO_BlockAddress,           ///< Address of a basic block
+    MO_RegisterMask,           ///< Mask of preserved registers.
     MO_Metadata,               ///< Metadata reference (for debug info)
     MO_MCSymbol                ///< MCSymbol reference (for debug/eh info)
   };
@@ -102,6 +103,17 @@
   ///
   bool IsUndef : 1;
=20
+  /// IsInternalRead - True if this operand reads a value that was defined
+  /// inside the same instruction or bundle.  This flag can be set on both=
 use
+  /// and def operands.  On a sub-register def operand, it refers to the p=
art
+  /// of the register that isn't written.  On a full-register def operand,=
 it
+  /// is a noop.
+  ///
+  /// When this flag is set, the instruction bundle must contain at least =
one
+  /// other def of the register.  If multiple instructions in the bundle d=
efine
+  /// the register, the meaning is target-defined.
+  bool IsInternalRead : 1;
+
   /// IsEarlyClobber - True if this MO_Register 'def' operand is written to
   /// by the MachineInstr before all input registers are read.  This is us=
ed to
   /// model the GCC inline asm '&' constraint modifier.
@@ -130,6 +142,7 @@
     const ConstantFP *CFP;    // For MO_FPImmediate.
     const ConstantInt *CI;    // For MO_CImmediate. Integers > 64bit.
     int64_t ImmVal;           // For MO_Immediate.
+    const uint32_t *RegMask;  // For MO_RegisterMask.
     const MDNode *MD;         // For MO_Metadata.
     MCSymbol *Sym;            // For MO_MCSymbol
=20
@@ -209,10 +222,13 @@
   bool isSymbol() const { return OpKind =3D=3D MO_ExternalSymbol; }
   /// isBlockAddress - Tests if this is a MO_BlockAddress operand.
   bool isBlockAddress() const { return OpKind =3D=3D MO_BlockAddress; }
+  /// isRegMask - Tests if this is a MO_RegisterMask operand.
+  bool isRegMask() const { return OpKind =3D=3D MO_RegisterMask; }
   /// isMetadata - Tests if this is a MO_Metadata operand.
   bool isMetadata() const { return OpKind =3D=3D MO_Metadata; }
   bool isMCSymbol() const { return OpKind =3D=3D MO_MCSymbol; }
=20
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Accessors for Register Operands
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
@@ -258,6 +274,11 @@
     return IsUndef;
   }
=20
+  bool isInternalRead() const {
+    assert(isReg() && "Wrong MachineOperand accessor");
+    return IsInternalRead;
+  }
+
   bool isEarlyClobber() const {
     assert(isReg() && "Wrong MachineOperand accessor");
     return IsEarlyClobber;
@@ -272,9 +293,12 @@
   /// register.  A use operand with the <undef> flag set doesn't read its
   /// register.  A sub-register def implicitly reads the other parts of the
   /// register being redefined unless the <undef> flag is set.
+  ///
+  /// This refers to reading the register value from before the current
+  /// instruction or bundle. Internal bundle reads are not included.
   bool readsReg() const {
     assert(isReg() && "Wrong MachineOperand accessor");
-    return !isUndef() && (isUse() || getSubReg());
+    return !isUndef() && !isInternalRead() && (isUse() || getSubReg());
   }
=20
   /// getNextOperandForReg - Return the next MachineOperand in the functio=
n that
@@ -343,6 +367,11 @@
     IsUndef =3D Val;
   }
=20
+  void setIsInternalRead(bool Val =3D true) {
+    assert(isReg() && "Wrong MachineOperand accessor");
+    IsInternalRead =3D Val;
+  }
+
   void setIsEarlyClobber(bool Val =3D true) {
     assert(isReg() && IsDef && "Wrong MachineOperand accessor");
     IsEarlyClobber =3D Val;
@@ -412,6 +441,28 @@
     return Contents.OffsetedInfo.Val.SymbolName;
   }
=20
+  /// clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
+  /// It is sometimes necessary to detach the register mask pointer from i=
ts
+  /// machine operand. This static method can be used for such detached bit
+  /// mask pointers.
+  static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg) {
+    // See TargetRegisterInfo.h.
+    assert(PhysReg < (1u << 30) && "Not a physical register");
+    return !(RegMask[PhysReg / 32] & (1u << PhysReg % 32));
+  }
+
+  /// clobbersPhysReg - Returns true if this RegMask operand clobbers Phys=
Reg.
+  bool clobbersPhysReg(unsigned PhysReg) const {
+     return clobbersPhysReg(getRegMask(), PhysReg);
+  }
+
+  /// getRegMask - Returns a bit mask of registers preserved by this RegMa=
sk
+  /// operand.
+  const uint32_t *getRegMask() const {
+    assert(isRegMask() && "Wrong MachineOperand accessor");
+    return Contents.RegMask;
+  }
+
   const MDNode *getMetadata() const {
     assert(isMetadata() && "Wrong MachineOperand accessor");
     return Contents.MD;
@@ -498,6 +549,7 @@
     Op.IsKill =3D isKill;
     Op.IsDead =3D isDead;
     Op.IsUndef =3D isUndef;
+    Op.IsInternalRead =3D false;
     Op.IsEarlyClobber =3D isEarlyClobber;
     Op.IsDebug =3D isDebug;
     Op.SmallContents.RegNo =3D Reg;
@@ -557,6 +609,24 @@
     Op.setTargetFlags(TargetFlags);
     return Op;
   }
+  /// CreateRegMask - Creates a register mask operand referencing Mask.  T=
he
+  /// operand does not take ownership of the memory referenced by Mask, it=
 must
+  /// remain valid for the lifetime of the operand.
+  ///
+  /// A RegMask operand represents a set of non-clobbered physical registe=
rs on
+  /// an instruction that clobbers many registers, typically a call.  The =
bit
+  /// mask has a bit set for each physreg that is preserved by this
+  /// instruction, as described in the documentation for
+  /// TargetRegisterInfo::getCallPreservedMask().
+  ///
+  /// Any physreg with a 0 bit in the mask is clobbered by the instruction.
+  ///
+  static MachineOperand CreateRegMask(const uint32_t *Mask) {
+    assert(Mask && "Missing register mask");
+    MachineOperand Op(MachineOperand::MO_RegisterMask);
+    Op.Contents.RegMask =3D Mask;
+    return Op;
+  }
   static MachineOperand CreateMetadata(const MDNode *Meta) {
     MachineOperand Op(MachineOperand::MO_Metadata);
     Op.Contents.MD =3D Meta;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachinePassRegistry.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachinePassRegistry.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachinePassRegistry.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -33,6 +33,7 @@
 ///
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 class MachinePassRegistryListener {
+  virtual void anchor();
 public:
   MachinePassRegistryListener() {}
   virtual ~MachinePassRegistryListener() {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/MachineRegisterInfo.h
--- a/head/contrib/llvm/include/llvm/CodeGen/MachineRegisterInfo.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/MachineRegisterInfo.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -15,12 +15,13 @@
 #define LLVM_CODEGEN_MACHINEREGISTERINFO_H
=20
 #include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/CodeGen/MachineInstrBundle.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/IndexedMap.h"
 #include <vector>
=20
 namespace llvm {
- =20
+
 /// MachineRegisterInfo - Keep track of information for virtual and physic=
al
 /// registers, including vreg register classes, use/def chains for registe=
rs,
 /// etc.
@@ -31,6 +32,11 @@
   /// registers have a single def.
   bool IsSSA;
=20
+  /// TracksLiveness - True while register liveness is being tracked accur=
ately.
+  /// Basic block live-in lists, kill flags, and implicit defs may not be
+  /// accurate when after this flag is cleared.
+  bool TracksLiveness;
+
   /// VRegInfo - Information we keep for each virtual register.
   ///
   /// Each element in this list contains the register class of the vreg an=
d the
@@ -46,18 +52,32 @@
   /// the allocator should prefer the physical register allocated to the v=
irtual
   /// register of the hint.
   IndexedMap<std::pair<unsigned, unsigned>, VirtReg2IndexFunctor> RegAlloc=
Hints;
- =20
+
   /// PhysRegUseDefLists - This is an array of the head of the use/def lis=
t for
   /// physical registers.
-  MachineOperand **PhysRegUseDefLists;=20
- =20
+  MachineOperand **PhysRegUseDefLists;
+
   /// UsedPhysRegs - This is a bit vector that is computed and set by the
   /// register allocator, and must be kept up to date by passes that run a=
fter
   /// register allocation (though most don't modify this).  This is used
   /// so that the code generator knows which callee save registers to save=
 and
   /// for other target specific uses.
+  /// This vector only has bits set for registers explicitly used, not the=
ir
+  /// aliases.
   BitVector UsedPhysRegs;
- =20
+
+  /// UsedPhysRegMask - Additional used physregs, but including aliases.
+  BitVector UsedPhysRegMask;
+
+  /// ReservedRegs - This is a bit vector of reserved registers.  The targ=
et
+  /// may change its mind about which registers should be reserved.  This
+  /// vector is the frozen set of reserved registers when register allocat=
ion
+  /// started.
+  BitVector ReservedRegs;
+
+  /// AllocatableRegs - From TRI->getAllocatableSet.
+  mutable BitVector AllocatableRegs;
+
   /// LiveIns/LiveOuts - Keep track of the physical registers that are
   /// livein/liveout of the function.  Live in values are typically argume=
nts in
   /// registers, live out values are typically return values in registers.
@@ -65,7 +85,7 @@
   /// stored in the second element.
   std::vector<std::pair<unsigned, unsigned> > LiveIns;
   std::vector<unsigned> LiveOuts;
- =20
+
   MachineRegisterInfo(const MachineRegisterInfo&); // DO NOT IMPLEMENT
   void operator=3D(const MachineRegisterInfo&);      // DO NOT IMPLEMENT
 public:
@@ -88,6 +108,23 @@
   // leaveSSA - Indicates that the machine function is no longer in SSA fo=
rm.
   void leaveSSA() { IsSSA =3D false; }
=20
+  /// tracksLiveness - Returns true when tracking register liveness accura=
tely.
+  ///
+  /// While this flag is true, register liveness information in basic block
+  /// live-in lists and machine instruction operands is accurate. This mea=
ns it
+  /// can be used to change the code in ways that affect the values in
+  /// registers, for example by the register scavenger.
+  ///
+  /// When this flag is false, liveness is no longer reliable.
+  bool tracksLiveness() const { return TracksLiveness; }
+
+  /// invalidateLiveness - Indicates that register liveness is no longer b=
eing
+  /// tracked accurately.
+  ///
+  /// This should be called by late passes that invalidate the liveness
+  /// information.
+  void invalidateLiveness() { TracksLiveness =3D false; }
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Register Info
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
@@ -141,7 +178,7 @@
     return use_iterator(getRegUseDefListHead(RegNo));
   }
   static use_iterator use_end() { return use_iterator(0); }
- =20
+
   /// use_empty - Return true if there are no instructions using the speci=
fied
   /// register.
   bool use_empty(unsigned RegNo) const { return use_begin(RegNo) =3D=3D us=
e_end(); }
@@ -157,7 +194,7 @@
     return use_nodbg_iterator(getRegUseDefListHead(RegNo));
   }
   static use_nodbg_iterator use_nodbg_end() { return use_nodbg_iterator(0)=
; }
- =20
+
   /// use_nodbg_empty - Return true if there are no non-Debug instructions
   /// using the specified register.
   bool use_nodbg_empty(unsigned RegNo) const {
@@ -171,8 +208,16 @@
   /// replaceRegWith - Replace all instances of FromReg with ToReg in the
   /// machine function.  This is like llvm-level X->replaceAllUsesWith(Y),
   /// except that it also changes any definitions of the register as well.
+  ///
+  /// Note that it is usually necessary to first constrain ToReg's register
+  /// class to match the FromReg constraints using:
+  ///
+  ///   constrainRegClass(ToReg, getRegClass(FromReg))
+  ///
+  /// That function will return NULL if the virtual registers have incompa=
tible
+  /// constraints.
   void replaceRegWith(unsigned FromReg, unsigned ToReg);
- =20
+
   /// getRegUseDefListHead - Return the head pointer for the register use/=
def
   /// list for the specified virtual or physical register.
   MachineOperand *&getRegUseDefListHead(unsigned RegNo) {
@@ -180,7 +225,7 @@
       return VRegInfo[RegNo].second;
     return PhysRegUseDefLists[RegNo];
   }
- =20
+
   MachineOperand *getRegUseDefListHead(unsigned RegNo) const {
     if (TargetRegisterInfo::isVirtualRegister(RegNo))
       return VRegInfo[RegNo].second;
@@ -197,15 +242,20 @@
   /// optimization passes which extend register lifetimes and need only
   /// preserve conservative kill flag information.
   void clearKillFlags(unsigned Reg) const;
- =20
+
 #ifndef NDEBUG
   void dumpUses(unsigned RegNo) const;
 #endif
- =20
+
+  /// isConstantPhysReg - Returns true if PhysReg is unallocatable and con=
stant
+  /// throughout the function.  It is safe to move instructions that read =
such
+  /// a physreg.
+  bool isConstantPhysReg(unsigned PhysReg, const MachineFunction &MF) cons=
t;
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Virtual Register Info
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
- =20
+
   /// getRegClass - Return the register class of the specified virtual reg=
ister.
   ///
   const TargetRegisterClass *getRegClass(unsigned Reg) const {
@@ -246,6 +296,9 @@
   ///
   unsigned getNumVirtRegs() const { return VRegInfo.size(); }
=20
+  /// clearVirtRegs - Remove all virtual registers (after physreg assignme=
nt).
+  void clearVirtRegs();
+
   /// setRegAllocationHint - Specify a register allocation hint for the
   /// specified virtual register.
   void setRegAllocationHint(unsigned Reg, unsigned Type, unsigned PrefReg)=
 {
@@ -271,38 +324,87 @@
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Physical Register Use Info
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
- =20
+
   /// isPhysRegUsed - Return true if the specified register is used in this
   /// function.  This only works after register allocation.
-  bool isPhysRegUsed(unsigned Reg) const { return UsedPhysRegs[Reg]; }
- =20
+  bool isPhysRegUsed(unsigned Reg) const {
+    return UsedPhysRegs.test(Reg) || UsedPhysRegMask.test(Reg);
+  }
+
+  /// isPhysRegOrOverlapUsed - Return true if Reg or any overlapping regis=
ter
+  /// is used in this function.
+  bool isPhysRegOrOverlapUsed(unsigned Reg) const {
+    if (UsedPhysRegMask.test(Reg))
+      return true;
+    for (const uint16_t *AI =3D TRI->getOverlaps(Reg); *AI; ++AI)
+      if (UsedPhysRegs.test(*AI))
+        return true;
+    return false;
+  }
+
   /// setPhysRegUsed - Mark the specified register used in this function.
   /// This should only be called during and after register allocation.
-  void setPhysRegUsed(unsigned Reg) { UsedPhysRegs[Reg] =3D true; }
+  void setPhysRegUsed(unsigned Reg) { UsedPhysRegs.set(Reg); }
=20
   /// addPhysRegsUsed - Mark the specified registers used in this function.
   /// This should only be called during and after register allocation.
   void addPhysRegsUsed(const BitVector &Regs) { UsedPhysRegs |=3D Regs; }
=20
+  /// addPhysRegsUsedFromRegMask - Mark any registers not in RegMask as us=
ed.
+  /// This corresponds to the bit mask attached to register mask operands.
+  void addPhysRegsUsedFromRegMask(const uint32_t *RegMask) {
+    UsedPhysRegMask.setBitsNotInMask(RegMask);
+  }
+
   /// setPhysRegUnused - Mark the specified register unused in this functi=
on.
   /// This should only be called during and after register allocation.
-  void setPhysRegUnused(unsigned Reg) { UsedPhysRegs[Reg] =3D false; }
+  void setPhysRegUnused(unsigned Reg) {
+    UsedPhysRegs.reset(Reg);
+    UsedPhysRegMask.reset(Reg);
+  }
=20
-  /// closePhysRegsUsed - Expand UsedPhysRegs to its transitive closure ov=
er
-  /// subregisters. That means that if R is used, so are all subregisters.
-  void closePhysRegsUsed(const TargetRegisterInfo&);
+
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+  // Reserved Register Info
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+  //
+  // The set of reserved registers must be invariant during register
+  // allocation.  For example, the target cannot suddenly decide it needs a
+  // frame pointer when the register allocator has already used the frame
+  // pointer register for something else.
+  //
+  // These methods can be used by target hooks like hasFP() to avoid chang=
ing
+  // the reserved register set during register allocation.
+
+  /// freezeReservedRegs - Called by the register allocator to freeze the =
set
+  /// of reserved registers before allocation begins.
+  void freezeReservedRegs(const MachineFunction&);
+
+  /// reservedRegsFrozen - Returns true after freezeReservedRegs() was cal=
led
+  /// to ensure the set of reserved registers stays constant.
+  bool reservedRegsFrozen() const {
+    return !ReservedRegs.empty();
+  }
+
+  /// canReserveReg - Returns true if PhysReg can be used as a reserved
+  /// register.  Any register can be reserved before freezeReservedRegs() =
is
+  /// called.
+  bool canReserveReg(unsigned PhysReg) const {
+    return !reservedRegsFrozen() || ReservedRegs.test(PhysReg);
+  }
+
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // LiveIn/LiveOut Management
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
- =20
+
   /// addLiveIn/Out - Add the specified register as a live in/out.  Note t=
hat it
   /// is an error to add the same register to the same set more than once.
   void addLiveIn(unsigned Reg, unsigned vreg =3D 0) {
     LiveIns.push_back(std::make_pair(Reg, vreg));
   }
   void addLiveOut(unsigned Reg) { LiveOuts.push_back(Reg); }
- =20
+
   // Iteration support for live in/out sets.  These sets are kept in sorted
   // order by their register number.
   typedef std::vector<std::pair<unsigned,unsigned> >::const_iterator
@@ -334,7 +436,7 @@
=20
 private:
   void HandleVRegListReallocation();
- =20
+
 public:
   /// defusechain_iterator - This class provides iterator support for mach=
ine
   /// operands in the function that use or define a specific register.  If
@@ -362,31 +464,31 @@
                           MachineInstr, ptrdiff_t>::reference reference;
     typedef std::iterator<std::forward_iterator_tag,
                           MachineInstr, ptrdiff_t>::pointer pointer;
-   =20
+
     defusechain_iterator(const defusechain_iterator &I) : Op(I.Op) {}
     defusechain_iterator() : Op(0) {}
-   =20
+
     bool operator=3D=3D(const defusechain_iterator &x) const {
       return Op =3D=3D x.Op;
     }
     bool operator!=3D(const defusechain_iterator &x) const {
       return !operator=3D=3D(x);
     }
-   =20
+
     /// atEnd - return true if this iterator is equal to reg_end() on the =
value.
     bool atEnd() const { return Op =3D=3D 0; }
-   =20
+
     // Iterator traversal: forward iteration only
     defusechain_iterator &operator++() {          // Preincrement
       assert(Op && "Cannot increment end iterator!");
       Op =3D Op->getNextOperandForReg();
-     =20
+
       // If this is an operand we don't care about, skip it.
-      while (Op && ((!ReturnUses && Op->isUse()) ||=20
+      while (Op && ((!ReturnUses && Op->isUse()) ||
                     (!ReturnDefs && Op->isDef()) ||
                     (SkipDebug && Op->isDebug())))
         Op =3D Op->getNextOperandForReg();
-     =20
+
       return *this;
     }
     defusechain_iterator operator++(int) {        // Postincrement
@@ -404,30 +506,38 @@
       return MI;
     }
=20
+    MachineInstr *skipBundle() {
+      if (!Op) return 0;
+      MachineInstr *MI =3D getBundleStart(Op->getParent());
+      do ++*this;
+      while (Op && getBundleStart(Op->getParent()) =3D=3D MI);
+      return MI;
+    }
+
     MachineOperand &getOperand() const {
       assert(Op && "Cannot dereference end iterator!");
       return *Op;
     }
-   =20
+
     /// getOperandNo - Return the operand # of this MachineOperand in its
     /// MachineInstr.
     unsigned getOperandNo() const {
       assert(Op && "Cannot dereference end iterator!");
       return Op - &Op->getParent()->getOperand(0);
     }
-   =20
+
     // Retrieve a reference to the current operand.
     MachineInstr &operator*() const {
       assert(Op && "Cannot dereference end iterator!");
       return *Op->getParent();
     }
-   =20
+
     MachineInstr *operator->() const {
       assert(Op && "Cannot dereference end iterator!");
       return Op->getParent();
     }
   };
- =20
+
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/PBQP/Graph.h
--- a/head/contrib/llvm/include/llvm/CodeGen/PBQP/Graph.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/PBQP/Graph.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -350,6 +350,43 @@
       numNodes =3D numEdges =3D 0;
     }
=20
+    /// \brief Dump a graph to an output stream.
+    template <typename OStream>
+    void dump(OStream &os) {
+      os << getNumNodes() << " " << getNumEdges() << "\n";
+
+      for (NodeItr nodeItr =3D nodesBegin(), nodeEnd =3D nodesEnd();
+           nodeItr !=3D nodeEnd; ++nodeItr) {
+        const Vector& v =3D getNodeCosts(nodeItr);
+        os << "\n" << v.getLength() << "\n";
+        assert(v.getLength() !=3D 0 && "Empty vector in graph.");
+        os << v[0];
+        for (unsigned i =3D 1; i < v.getLength(); ++i) {
+          os << " " << v[i];
+        }
+        os << "\n";
+      }
+
+      for (EdgeItr edgeItr =3D edgesBegin(), edgeEnd =3D edgesEnd();
+           edgeItr !=3D edgeEnd; ++edgeItr) {
+        unsigned n1 =3D std::distance(nodesBegin(), getEdgeNode1(edgeItr));
+        unsigned n2 =3D std::distance(nodesBegin(), getEdgeNode2(edgeItr));
+        assert(n1 !=3D n2 && "PBQP graphs shound not have self-edges.");
+        const Matrix& m =3D getEdgeCosts(edgeItr);
+        os << "\n" << n1 << " " << n2 << "\n"
+           << m.getRows() << " " << m.getCols() << "\n";
+        assert(m.getRows() !=3D 0 && "No rows in matrix.");
+        assert(m.getCols() !=3D 0 && "No cols in matrix.");
+        for (unsigned i =3D 0; i < m.getRows(); ++i) {
+          os << m[i][0];
+          for (unsigned j =3D 1; j < m.getCols(); ++j) {
+            os << " " << m[i][j];
+          }
+          os << "\n";
+        }
+      }
+    }
+
     /// \brief Print a representation of this graph in DOT format.
     /// @param os Output stream to print on.
     template <typename OStream>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/PBQP/HeuristicBase.h
--- a/head/contrib/llvm/include/llvm/CodeGen/PBQP/HeuristicBase.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/PBQP/HeuristicBase.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -157,7 +157,7 @@
         case 0: s.applyR0(nItr); break;
         case 1: s.applyR1(nItr); break;
         case 2: s.applyR2(nItr); break;
-        default: assert(false &&
+        default: llvm_unreachable(
                         "Optimal reductions of degree > 2 nodes is invalid=
.");
       }
=20
@@ -186,7 +186,7 @@
     /// \brief Add a node to the heuristic reduce list.
     /// @param nItr Node iterator to add to the heuristic reduce list.
     void addToHeuristicList(Graph::NodeItr nItr) {
-      assert(false && "Must be implemented in derived class.");
+      llvm_unreachable("Must be implemented in derived class.");
     }
=20
     /// \brief Heuristically reduce one of the nodes in the heuristic
@@ -194,25 +194,25 @@
     /// @return True if a reduction takes place, false if the heuristic re=
duce
     ///         list is empty.
     void heuristicReduce() {
-      assert(false && "Must be implemented in derived class.");
+      llvm_unreachable("Must be implemented in derived class.");
     }
=20
     /// \brief Prepare a change in the costs on the given edge.
     /// @param eItr Edge iterator.   =20
     void preUpdateEdgeCosts(Graph::EdgeItr eItr) {
-      assert(false && "Must be implemented in derived class.");
+      llvm_unreachable("Must be implemented in derived class.");
     }
=20
     /// \brief Handle the change in the costs on the given edge.
     /// @param eItr Edge iterator.
     void postUpdateEdgeCostts(Graph::EdgeItr eItr) {
-      assert(false && "Must be implemented in derived class.");
+      llvm_unreachable("Must be implemented in derived class.");
     }
=20
     /// \brief Handle the addition of a new edge into the PBQP graph.
     /// @param eItr Edge iterator for the added edge.
     void handleAddEdge(Graph::EdgeItr eItr) {
-      assert(false && "Must be implemented in derived class.");
+      llvm_unreachable("Must be implemented in derived class.");
     }
=20
     /// \brief Handle disconnection of an edge from a node.
@@ -223,7 +223,7 @@
     /// method allows for the effect to be computed only for the remaining
     /// node in the graph.
     void handleRemoveEdge(Graph::EdgeItr eItr, Graph::NodeItr nItr) {
-      assert(false && "Must be implemented in derived class.");
+      llvm_unreachable("Must be implemented in derived class.");
     }
=20
     /// \brief Clean up any structures used by HeuristicBase.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/PBQP/Heuristics/Briggs.h
--- a/head/contrib/llvm/include/llvm/CodeGen/PBQP/Heuristics/Briggs.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/PBQP/Heuristics/Briggs.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -418,6 +418,12 @@
         unsigned numRegs =3D getGraph().getNodeCosts(nItr).getLength() - 1;
=20
         nd.numDenied =3D 0;
+        const Vector& nCosts =3D getGraph().getNodeCosts(nItr);
+        for (unsigned i =3D 1; i < nCosts.getLength(); ++i) {
+          if (nCosts[i] =3D=3D std::numeric_limits<PBQPNum>::infinity())
+            ++nd.numDenied;
+        }
+
         nd.numSafe =3D numRegs;
         nd.unsafeDegrees.resize(numRegs, 0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/Passes.h
--- a/head/contrib/llvm/include/llvm/CodeGen/Passes.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/Passes.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,6 +15,7 @@
 #ifndef LLVM_CODEGEN_PASSES_H
 #define LLVM_CODEGEN_PASSES_H
=20
+#include "llvm/Pass.h"
 #include "llvm/Target/TargetMachine.h"
 #include <string>
=20
@@ -26,7 +27,211 @@
   class TargetLowering;
   class TargetRegisterClass;
   class raw_ostream;
+}
=20
+namespace llvm {
+
+extern char &NoPassID; // Allow targets to choose not to run a pass.
+
+class PassConfigImpl;
+
+/// Target-Independent Code Generator Pass Configuration Options.
+///
+/// This is an ImmutablePass solely for the purpose of exposing CodeGen op=
tions
+/// to the internals of other CodeGen passes.
+class TargetPassConfig : public ImmutablePass {
+public:
+  /// Pseudo Pass IDs. These are defined within TargetPassConfig because t=
hey
+  /// are unregistered pass IDs. They are only useful for use with
+  /// TargetPassConfig APIs to identify multiple occurrences of the same p=
ass.
+  ///
+
+  /// EarlyTailDuplicate - A clone of the TailDuplicate pass that runs ear=
ly
+  /// during codegen, on SSA form.
+  static char EarlyTailDuplicateID;
+
+  /// PostRAMachineLICM - A clone of the LICM pass that runs during late m=
achine
+  /// optimization after regalloc.
+  static char PostRAMachineLICMID;
+
+protected:
+  TargetMachine *TM;
+  PassManagerBase &PM;
+  PassConfigImpl *Impl; // Internal data structures
+  bool Initialized;     // Flagged after all passes are configured.
+
+  // Target Pass Options
+  // Targets provide a default setting, user flags override.
+  //
+  bool DisableVerify;
+
+  /// Default setting for -enable-tail-merge on this target.
+  bool EnableTailMerge;
+
+public:
+  TargetPassConfig(TargetMachine *tm, PassManagerBase &pm);
+  // Dummy constructor.
+  TargetPassConfig();
+
+  virtual ~TargetPassConfig();
+
+  static char ID;
+
+  /// Get the right type of TargetMachine for this target.
+  template<typename TMC> TMC &getTM() const {
+    return *static_cast<TMC*>(TM);
+  }
+
+  const TargetLowering *getTargetLowering() const {
+    return TM->getTargetLowering();
+  }
+
+  //
+  void setInitialized() { Initialized =3D true; }
+
+  CodeGenOpt::Level getOptLevel() const { return TM->getOptLevel(); }
+
+  void setDisableVerify(bool Disable) { setOpt(DisableVerify, Disable); }
+
+  bool getEnableTailMerge() const { return EnableTailMerge; }
+  void setEnableTailMerge(bool Enable) { setOpt(EnableTailMerge, Enable); }
+
+  /// Allow the target to override a specific pass without overriding the =
pass
+  /// pipeline. When passes are added to the standard pipeline at the
+  /// point where StadardID is expected, add TargetID in its place.
+  void substitutePass(char &StandardID, char &TargetID);
+
+  /// Allow the target to enable a specific standard pass by default.
+  void enablePass(char &ID) { substitutePass(ID, ID); }
+
+  /// Allow the target to disable a specific standard pass by default.
+  void disablePass(char &ID) { substitutePass(ID, NoPassID); }
+
+  /// Return the pass ssubtituted for StandardID by the target.
+  /// If no substitution exists, return StandardID.
+  AnalysisID getPassSubstitution(AnalysisID StandardID) const;
+
+  /// Return true if the optimized regalloc pipeline is enabled.
+  bool getOptimizeRegAlloc() const;
+
+  /// Add common target configurable passes that perform LLVM IR to IR
+  /// transforms following machine independent optimization.
+  virtual void addIRPasses();
+
+  /// Add common passes that perform LLVM IR to IR transforms in preparati=
on for
+  /// instruction selection.
+  virtual void addISelPrepare();
+
+  /// addInstSelector - This method should install an instruction selector=
 pass,
+  /// which converts from LLVM code to machine instructions.
+  virtual bool addInstSelector() {
+    return true;
+  }
+
+  /// Add the complete, standard set of LLVM CodeGen passes.
+  /// Fully developed targets will not generally override this.
+  virtual void addMachinePasses();
+
+protected:
+  // Helper to verify the analysis is really immutable.
+  void setOpt(bool &Opt, bool Val);
+
+  /// Methods with trivial inline returns are convenient points in the com=
mon
+  /// codegen pass pipeline where targets may insert passes. Methods with
+  /// out-of-line standard implementations are major CodeGen stages called=
 by
+  /// addMachinePasses. Some targets may override major stages when insert=
ing
+  /// passes is insufficient, but maintaining overriden stages is more wor=
k.
+  ///
+
+  /// addPreISelPasses - This method should add any "last minute" LLVM->LL=
VM
+  /// passes (which are run just before instruction selector).
+  virtual bool addPreISel() {
+    return true;
+  }
+
+  /// addMachineSSAOptimization - Add standard passes that optimize machine
+  /// instructions in SSA form.
+  virtual void addMachineSSAOptimization();
+
+  /// addPreRegAlloc - This method may be implemented by targets that want=
 to
+  /// run passes immediately before register allocation. This should return
+  /// true if -print-machineinstrs should print after these passes.
+  virtual bool addPreRegAlloc() {
+    return false;
+  }
+
+  /// createTargetRegisterAllocator - Create the register allocator pass f=
or
+  /// this target at the current optimization level.
+  virtual FunctionPass *createTargetRegisterAllocator(bool Optimized);
+
+  /// addFastRegAlloc - Add the minimum set of target-independent passes t=
hat
+  /// are required for fast register allocation.
+  virtual void addFastRegAlloc(FunctionPass *RegAllocPass);
+
+  /// addOptimizedRegAlloc - Add passes related to register allocation.
+  /// LLVMTargetMachine provides standard regalloc passes for most targets.
+  virtual void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
+
+  /// addFinalizeRegAlloc - This method may be implemented by targets that=
 want
+  /// to run passes within the regalloc pipeline, immediately after the re=
gister
+  /// allocation pass itself. These passes run as soon as virtual regisite=
rs
+  /// have been rewritten to physical registers but before and other postRA
+  /// optimization happens. Targets that have marked instructions for bund=
ling
+  /// must have finalized those bundles by the time these passes have run,
+  /// because subsequent passes are not guaranteed to be bundle-aware.
+  virtual bool addFinalizeRegAlloc() {
+    return false;
+  }
+
+  /// addPostRegAlloc - This method may be implemented by targets that wan=
t to
+  /// run passes after register allocation pass pipeline but before
+  /// prolog-epilog insertion.  This should return true if -print-machinei=
nstrs
+  /// should print after these passes.
+  virtual bool addPostRegAlloc() {
+    return false;
+  }
+
+  /// Add passes that optimize machine instructions after register allocat=
ion.
+  virtual void addMachineLateOptimization();
+
+  /// addPreSched2 - This method may be implemented by targets that want to
+  /// run passes after prolog-epilog insertion and before the second instr=
uction
+  /// scheduling pass.  This should return true if -print-machineinstrs sh=
ould
+  /// print after these passes.
+  virtual bool addPreSched2() {
+    return false;
+  }
+
+  /// Add standard basic block placement passes.
+  virtual void addBlockPlacement();
+
+  /// addPreEmitPass - This pass may be implemented by targets that want t=
o run
+  /// passes immediately before machine code is emitted.  This should retu=
rn
+  /// true if -print-machineinstrs should print out the code after the pas=
ses.
+  virtual bool addPreEmitPass() {
+    return false;
+  }
+
+  /// Utilities for targets to add passes to the pass manager.
+  ///
+
+  /// Add a CodeGen pass at this point in the pipeline after checking over=
rides.
+  /// Return the pass that was added, or NoPassID.
+  AnalysisID addPass(char &ID);
+
+  /// addMachinePasses helper to create the target-selected or overriden
+  /// regalloc pass.
+  FunctionPass *createRegAllocPass(bool Optimized);
+
+  /// printAndVerify - Add a pass to dump then verify the machine function=
, if
+  /// those steps are enabled.
+  ///
+  void printAndVerify(const char *Banner) const;
+};
+} // namespace llvm
+
+/// List of target independent CodeGen pass IDs.
+namespace llvm {
   /// createUnreachableBlockEliminationPass - The LLVM code generator does=
 not
   /// work well with unreachable basic blocks (what live ranges make sense=
 for a
   /// block that cannot be reached?).  As such, a code generator should ei=
ther
@@ -41,31 +246,29 @@
   createMachineFunctionPrinterPass(raw_ostream &OS,
                                    const std::string &Banner =3D"");
=20
-  /// MachineLoopInfo pass - This pass is a loop analysis pass.
-  ///
+  /// MachineLoopInfo - This pass is a loop analysis pass.
   extern char &MachineLoopInfoID;
=20
-  /// MachineLoopRanges pass - This pass is an on-demand loop coverage
-  /// analysis pass.
-  ///
+  /// MachineLoopRanges - This pass is an on-demand loop coverage analysis.
   extern char &MachineLoopRangesID;
=20
-  /// MachineDominators pass - This pass is a machine dominators analysis =
pass.
-  ///
+  /// MachineDominators - This pass is a machine dominators analysis pass.
   extern char &MachineDominatorsID;
=20
   /// EdgeBundles analysis - Bundle machine CFG edges.
-  ///
   extern char &EdgeBundlesID;
=20
-  /// PHIElimination pass - This pass eliminates machine instruction PHI n=
odes
+  /// LiveVariables pass - This pass computes the set of blocks in which e=
ach
+  /// variable is life and sets machine operand kill flags.
+  extern char &LiveVariablesID;
+
+  /// PHIElimination - This pass eliminates machine instruction PHI nodes
   /// by inserting copy instructions.  This destroys SSA information, but =
is the
   /// desired input for some register allocators.  This pass is "required"=
 by
   /// these register allocator like this: AU.addRequiredID(PHIEliminationI=
D);
-  ///
   extern char &PHIEliminationID;
=20
-  /// StrongPHIElimination pass - This pass eliminates machine instruction=
 PHI
+  /// StrongPHIElimination - This pass eliminates machine instruction PHI
   /// nodes by inserting copy instructions.  This destroys SSA information=
, but
   /// is the desired input for some register allocators.  This pass is
   /// "required" by these register allocator like this:
@@ -76,32 +279,30 @@
   /// LiveStacks pass. An analysis keeping track of the liveness of stack =
slots.
   extern char &LiveStacksID;
=20
-  /// TwoAddressInstruction pass - This pass reduces two-address instructi=
ons to
+  /// TwoAddressInstruction - This pass reduces two-address instructions to
   /// use two operands. This destroys SSA information but it is desired by
   /// register allocators.
   extern char &TwoAddressInstructionPassID;
=20
-  /// RegisteCoalescer pass - This pass merges live ranges to eliminate co=
pies.
-  extern char &RegisterCoalescerPassID;
+  /// ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
+  extern char &ProcessImplicitDefsID;
+
+  /// RegisterCoalescer - This pass merges live ranges to eliminate copies.
+  extern char &RegisterCoalescerID;
+
+  /// MachineScheduler - This pass schedules machine instructions.
+  extern char &MachineSchedulerID;
=20
   /// SpillPlacement analysis. Suggest optimal placement of spill code bet=
ween
   /// basic blocks.
-  ///
   extern char &SpillPlacementID;
=20
-  /// UnreachableMachineBlockElimination pass - This pass removes unreacha=
ble
+  /// UnreachableMachineBlockElimination - This pass removes unreachable
   /// machine basic blocks.
   extern char &UnreachableMachineBlockElimID;
=20
-  /// DeadMachineInstructionElim pass - This pass removes dead machine
-  /// instructions.
-  ///
-  FunctionPass *createDeadMachineInstructionElimPass();
-
-  /// Creates a register allocator as the user specified on the command li=
ne, or
-  /// picks one that matches OptLevel.
-  ///
-  FunctionPass *createRegisterAllocator(CodeGenOpt::Level OptLevel);
+  /// DeadMachineInstructionElim - This pass removes dead machine instruct=
ions.
+  extern char &DeadMachineInstructionElimID;
=20
   /// FastRegisterAllocation Pass - This pass register allocates as fast as
   /// possible. It is best suited for debug code where live ranges are sho=
rt.
@@ -118,56 +319,59 @@
   ///
   FunctionPass *createGreedyRegisterAllocator();
=20
-  /// LinearScanRegisterAllocation Pass - This pass implements the linear =
scan
-  /// register allocation algorithm, a global register allocator.
-  ///
-  FunctionPass *createLinearScanRegisterAllocator();
-
   /// PBQPRegisterAllocation Pass - This pass implements the Partitioned B=
oolean
   /// Quadratic Prograaming (PBQP) based register allocator.
   ///
   FunctionPass *createDefaultPBQPRegisterAllocator();
=20
-  /// PrologEpilogCodeInserter Pass - This pass inserts prolog and epilog =
code,
+  /// PrologEpilogCodeInserter - This pass inserts prolog and epilog code,
   /// and eliminates abstract frame references.
-  ///
-  FunctionPass *createPrologEpilogCodeInserter();
+  extern char &PrologEpilogCodeInserterID;
=20
-  /// ExpandPostRAPseudos Pass - This pass expands pseudo instructions aft=
er
+  /// ExpandPostRAPseudos - This pass expands pseudo instructions after
   /// register allocation.
-  ///
-  FunctionPass *createExpandPostRAPseudosPass();
+  extern char &ExpandPostRAPseudosID;
=20
   /// createPostRAScheduler - This pass performs post register allocation
   /// scheduling.
-  FunctionPass *createPostRAScheduler(CodeGenOpt::Level OptLevel);
+  extern char &PostRASchedulerID;
=20
-  /// BranchFolding Pass - This pass performs machine code CFG based
+  /// BranchFolding - This pass performs machine code CFG based
   /// optimizations to delete branches to branches, eliminate branches to
   /// successor blocks (creating fall throughs), and eliminating branches =
over
   /// branches.
-  FunctionPass *createBranchFoldingPass(bool DefaultEnableTailMerge);
+  extern char &BranchFolderPassID;
=20
-  /// TailDuplicate Pass - Duplicate blocks with unconditional branches
+  /// TailDuplicate - Duplicate blocks with unconditional branches
   /// into tails of their predecessors.
-  FunctionPass *createTailDuplicatePass(bool PreRegAlloc =3D false);
+  extern char &TailDuplicateID;
=20
-  /// IfConverter Pass - This pass performs machine code if conversion.
-  FunctionPass *createIfConverterPass();
+  /// IfConverter - This pass performs machine code if conversion.
+  extern char &IfConverterID;
=20
-  /// Code Placement Pass - This pass optimize code placement and aligns l=
oop
+  /// MachineBlockPlacement - This pass places basic blocks based on branch
+  /// probabilities.
+  extern char &MachineBlockPlacementID;
+
+  /// MachineBlockPlacementStats - This pass collects statistics about the
+  /// basic block placement using branch probabilities and block frequency
+  /// information.
+  extern char &MachineBlockPlacementStatsID;
+
+  /// Code Placement - This pass optimize code placement and aligns loop
   /// headers to target specific alignment boundary.
-  FunctionPass *createCodePlacementOptPass();
+  extern char &CodePlacementOptID;
=20
-  /// IntrinsicLowering Pass - Performs target-independent LLVM IR
-  /// transformations for highly portable strategies.
+  /// GCLowering Pass - Performs target-independent LLVM IR transformation=
s for
+  /// highly portable strategies.
+  ///
   FunctionPass *createGCLoweringPass();
=20
-  /// MachineCodeAnalysis Pass - Target-independent pass to mark safe poin=
ts in
-  /// machine code. Must be added very late during code generation, just p=
rior
-  /// to output, and importantly after all CFG transformations (such as br=
anch
-  /// folding).
-  FunctionPass *createGCMachineCodeAnalysisPass();
+  /// GCMachineCodeAnalysis - Target-independent pass to mark safe points
+  /// in machine code. Must be added very late during code generation, just
+  /// prior to output, and importantly after all CFG transformations (such=
 as
+  /// branch folding).
+  extern char &GCMachineCodeAnalysisID;
=20
   /// Deleter Pass - Releases GC metadata.
   ///
@@ -177,54 +381,56 @@
   ///
   FunctionPass *createGCInfoPrinter(raw_ostream &OS);
=20
-  /// createMachineCSEPass - This pass performs global CSE on machine
-  /// instructions.
-  FunctionPass *createMachineCSEPass();
+  /// MachineCSE - This pass performs global CSE on machine instructions.
+  extern char &MachineCSEID;
=20
-  /// createMachineLICMPass - This pass performs LICM on machine instructi=
ons.
-  ///
-  FunctionPass *createMachineLICMPass(bool PreRegAlloc =3D true);
+  /// MachineLICM - This pass performs LICM on machine instructions.
+  extern char &MachineLICMID;
=20
-  /// createMachineSinkingPass - This pass performs sinking on machine
-  /// instructions.
-  FunctionPass *createMachineSinkingPass();
+  /// MachineSinking - This pass performs sinking on machine instructions.
+  extern char &MachineSinkingID;
=20
-  /// createPeepholeOptimizerPass - This pass performs peephole optimizati=
ons -
+  /// MachineCopyPropagation - This pass performs copy propagation on
+  /// machine instructions.
+  extern char &MachineCopyPropagationID;
+
+  /// PeepholeOptimizer - This pass performs peephole optimizations -
   /// like extension and comparison eliminations.
-  FunctionPass *createPeepholeOptimizerPass();
+  extern char &PeepholeOptimizerID;
=20
-  /// createOptimizePHIsPass - This pass optimizes machine instruction PHIs
+  /// OptimizePHIs - This pass optimizes machine instruction PHIs
   /// to take advantage of opportunities created during DAG legalization.
-  FunctionPass *createOptimizePHIsPass();
+  extern char &OptimizePHIsID;
=20
-  /// createStackSlotColoringPass - This pass performs stack slot coloring.
-  FunctionPass *createStackSlotColoringPass(bool);
+  /// StackSlotColoring - This pass performs stack slot coloring.
+  extern char &StackSlotColoringID;
=20
   /// createStackProtectorPass - This pass adds stack protectors to functi=
ons.
+  ///
   FunctionPass *createStackProtectorPass(const TargetLowering *tli);
=20
   /// createMachineVerifierPass - This pass verifies cenerated machine code
   /// instructions for correctness.
+  ///
   FunctionPass *createMachineVerifierPass(const char *Banner =3D 0);
=20
   /// createDwarfEHPass - This pass mulches exception handling code into a=
 form
   /// adapted to code generation.  Required if using dwarf exception handl=
ing.
   FunctionPass *createDwarfEHPass(const TargetMachine *tm);
=20
-  /// createSjLjEHPass - This pass adapts exception handling code to use
+  /// createSjLjEHPreparePass - This pass adapts exception handling code t=
o use
   /// the GCC-style builtin setjmp/longjmp (sjlj) to handling EH control f=
low.
-  FunctionPass *createSjLjEHPass(const TargetLowering *tli);
+  ///
+  FunctionPass *createSjLjEHPreparePass(const TargetLowering *tli);
=20
-  /// createLocalStackSlotAllocationPass - This pass assigns local frame
-  /// indices to stack slots relative to one another and allocates
-  /// base registers to access them when it is estimated by the target to
-  /// be out of range of normal frame pointer or stack pointer index
-  /// addressing.
-  FunctionPass *createLocalStackSlotAllocationPass();
+  /// LocalStackSlotAllocation - This pass assigns local frame indices to =
stack
+  /// slots relative to one another and allocates base registers to access=
 them
+  /// when it is estimated by the target to be out of range of normal frame
+  /// pointer or stack pointer index addressing.
+  extern char &LocalStackSlotAllocationID;
=20
-  /// createExpandISelPseudosPass - This pass expands pseudo-instructions.
-  ///
-  FunctionPass *createExpandISelPseudosPass();
+  /// ExpandISelPseudos - This pass expands pseudo-instructions.
+  extern char &ExpandISelPseudosID;
=20
   /// createExecutionDependencyFixPass - This pass fixes execution time
   /// problems with dependent instructions, such as switching execution
@@ -234,6 +440,13 @@
   ///
   FunctionPass *createExecutionDependencyFixPass(const TargetRegisterClass=
 *RC);
=20
+  /// UnpackMachineBundles - This pass unpack machine instruction bundles.
+  extern char &UnpackMachineBundlesID;
+
+  /// FinalizeMachineBundles - This pass finalize machine instruction
+  /// bundles (created earlier, e.g. during pre-RA scheduling).
+  extern char &FinalizeMachineBundlesID;
+
 } // End llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/RegisterScavenging.h
--- a/head/contrib/llvm/include/llvm/CodeGen/RegisterScavenging.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/RegisterScavenging.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -68,6 +68,10 @@
   /// available, unset means the register is currently being used.
   BitVector RegsAvailable;
=20
+  // These BitVectors are only used internally to forward(). They are memb=
ers
+  // to avoid frequent reallocations.
+  BitVector KillRegs, DefRegs;
+
 public:
   RegScavenger()
     : MBB(NULL), NumPhysRegs(0), Tracking(false),
@@ -130,8 +134,9 @@
=20
   /// isUsed / isUnused - Test if a register is currently being used.
   ///
-  bool isUsed(unsigned Reg) const   { return !RegsAvailable.test(Reg); }
-  bool isUnused(unsigned Reg) const { return RegsAvailable.test(Reg); }
+  bool isUsed(unsigned Reg) const   {
+    return !RegsAvailable.test(Reg) || ReservedRegs.test(Reg);
+  }
=20
   /// isAliasUsed - Is Reg or an alias currently in use?
   bool isAliasUsed(unsigned Reg) const;
@@ -139,7 +144,7 @@
   /// setUsed / setUnused - Mark the state of one or a number of registers.
   ///
   void setUsed(BitVector &Regs) {
-    RegsAvailable &=3D ~Regs;
+    RegsAvailable.reset(Regs);
   }
   void setUnused(BitVector &Regs) {
     RegsAvailable |=3D Regs;
@@ -148,9 +153,6 @@
   /// Add Reg and all its sub-registers to BV.
   void addRegWithSubRegs(BitVector &BV, unsigned Reg);
=20
-  /// Add Reg and its aliases to BV.
-  void addRegWithAliases(BitVector &BV, unsigned Reg);
-
   /// findSurvivorReg - Return the candidate register that is unused for t=
he
   /// longest after StartMI. UseMI is set to the instruction where the sea=
rch
   /// stopped.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/ScheduleDAG.h
--- a/head/contrib/llvm/include/llvm/CodeGen/ScheduleDAG.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/ScheduleDAG.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -8,7 +8,8 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file implements the ScheduleDAG class, which is used as the common
-// base class for instruction schedulers.
+// base class for instruction schedulers. This encapsulates the scheduling=
 DAG,
+// which is shared between SelectionDAG and MachineInstr scheduling.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -16,7 +17,7 @@
 #define LLVM_CODEGEN_SCHEDULEDAG_H
=20
 #include "llvm/CodeGen/MachineBasicBlock.h"
-#include "llvm/Target/TargetMachine.h"
+#include "llvm/Target/TargetLowering.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/GraphTraits.h"
@@ -129,8 +130,7 @@
                Contents.Order.isMustAlias =3D=3D Other.Contents.Order.isMu=
stAlias &&
                Contents.Order.isArtificial =3D=3D Other.Contents.Order.isA=
rtificial;
       }
-      assert(0 && "Invalid dependency kind!");
-      return false;
+      llvm_unreachable("Invalid dependency kind!");
     }
=20
     bool operator!=3D(const SDep &Other) const {
@@ -232,6 +232,7 @@
   public:
     SUnit *OrigNode;                    // If not this, the node from which
                                         // this node was cloned.
+                                        // (SD scheduling only)
=20
     // Preds/Succs - The SUnits before/after us in the graph.
     SmallVector<SDep, 4> Preds;  // All sunit predecessors.
@@ -409,6 +410,13 @@
       return false;
     }
=20
+    bool isTopReady() const {
+      return NumPredsLeft =3D=3D 0;
+    }
+    bool isBottomReady() const {
+      return NumSuccsLeft =3D=3D 0;
+    }
+
     void dump(const ScheduleDAG *G) const;
     void dumpAll(const ScheduleDAG *G) const;
     void print(raw_ostream &O, const ScheduleDAG *G) const;
@@ -427,6 +435,7 @@
   /// implementation to decide.
   ///
   class SchedulingPriorityQueue {
+    virtual void anchor();
     unsigned CurCycle;
     bool HasReadyFilter;
   public:
@@ -465,13 +474,13 @@
=20
     virtual void dump(ScheduleDAG *) const {}
=20
-    /// ScheduledNode - As each node is scheduled, this method is invoked.=
  This
+    /// scheduledNode - As each node is scheduled, this method is invoked.=
  This
     /// allows the priority function to adjust the priority of related
     /// unscheduled nodes, for example.
     ///
-    virtual void ScheduledNode(SUnit *) {}
+    virtual void scheduledNode(SUnit *) {}
=20
-    virtual void UnscheduledNode(SUnit *) {}
+    virtual void unscheduledNode(SUnit *) {}
=20
     void setCurCycle(unsigned Cycle) {
       CurCycle =3D Cycle;
@@ -484,15 +493,11 @@
=20
   class ScheduleDAG {
   public:
-    MachineBasicBlock *BB;          // The block in which to insert instru=
ctions
-    MachineBasicBlock::iterator InsertPos;// The position to insert instru=
ctions
     const TargetMachine &TM;              // Target processor
     const TargetInstrInfo *TII;           // Target instruction information
     const TargetRegisterInfo *TRI;        // Target processor register info
     MachineFunction &MF;                  // Machine function
     MachineRegisterInfo &MRI;             // Virtual/real register map
-    std::vector<SUnit*> Sequence;         // The schedule. Null SUnit*'s
-                                          // represent noop instructions.
     std::vector<SUnit> SUnits;            // The scheduling units.
     SUnit EntrySU;                        // Special node for the region e=
ntry.
     SUnit ExitSU;                         // Special node for the region e=
xit.
@@ -507,6 +512,9 @@
=20
     virtual ~ScheduleDAG();
=20
+    /// clearDAG - clear the DAG state (between regions).
+    void clearDAG();
+
     /// getInstrDesc - Return the MCInstrDesc of this SUnit.
     /// Return NULL for SDNodes without a machine opcode.
     const MCInstrDesc *getInstrDesc(const SUnit *SU) const {
@@ -517,66 +525,43 @@
     /// viewGraph - Pop up a GraphViz/gv window with the ScheduleDAG rende=
red
     /// using 'dot'.
     ///
+    void viewGraph(const Twine &Name, const Twine &Title);
     void viewGraph();
=20
-    /// EmitSchedule - Insert MachineInstrs into the MachineBasicBlock
-    /// according to the order specified in Sequence.
-    ///
-    virtual MachineBasicBlock *EmitSchedule() =3D 0;
-
-    void dumpSchedule() const;
-
     virtual void dumpNode(const SUnit *SU) const =3D 0;
=20
     /// getGraphNodeLabel - Return a label for an SUnit node in a visualiz=
ation
     /// of the ScheduleDAG.
     virtual std::string getGraphNodeLabel(const SUnit *SU) const =3D 0;
=20
+    /// getDAGLabel - Return a label for the region of code covered by the=
 DAG.
+    virtual std::string getDAGName() const =3D 0;
+
     /// addCustomGraphFeatures - Add custom features for a visualization of
     /// the ScheduleDAG.
     virtual void addCustomGraphFeatures(GraphWriter<ScheduleDAG*> &) const=
 {}
=20
 #ifndef NDEBUG
-    /// VerifySchedule - Verify that all SUnits were scheduled and that
-    /// their state is consistent.
-    void VerifySchedule(bool isBottomUp);
+    /// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
+    /// their state is consistent. Return the number of scheduled SUnits.
+    unsigned VerifyScheduledDAG(bool isBottomUp);
 #endif
=20
   protected:
-    /// Run - perform scheduling.
-    ///
-    void Run(MachineBasicBlock *bb, MachineBasicBlock::iterator insertPos);
-
-    /// BuildSchedGraph - Build SUnits and set up their Preds and Succs
-    /// to form the scheduling dependency graph.
-    ///
-    virtual void BuildSchedGraph(AliasAnalysis *AA) =3D 0;
-
     /// ComputeLatency - Compute node latency.
     ///
-    virtual void ComputeLatency(SUnit *SU) =3D 0;
+    virtual void computeLatency(SUnit *SU) =3D 0;
=20
     /// ComputeOperandLatency - Override dependence edge latency using
     /// operand use/def information
     ///
-    virtual void ComputeOperandLatency(SUnit *, SUnit *,
+    virtual void computeOperandLatency(SUnit *, SUnit *,
                                        SDep&) const { }
=20
-    /// Schedule - Order nodes according to selected style, filling
-    /// in the Sequence member.
-    ///
-    virtual void Schedule() =3D 0;
-
     /// ForceUnitLatencies - Return true if all scheduling edges should be=
 given
     /// a latency value of one.  The default is to return false; scheduler=
s may
     /// override this as needed.
-    virtual bool ForceUnitLatencies() const { return false; }
-
-    /// EmitNoop - Emit a noop instruction.
-    ///
-    void EmitNoop();
-
-    void EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap);
+    virtual bool forceUnitLatencies() const { return false; }
=20
   private:
     // Return the MCInstrDesc of this SDNode or NULL.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/SchedulerRegistry.h
--- a/head/contrib/llvm/include/llvm/CodeGen/SchedulerRegistry.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/SchedulerRegistry.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -42,7 +42,7 @@
   : MachinePassRegistryNode(N, D, (MachinePassCtor)C)
   { Registry.Add(this); }
   ~RegisterScheduler() { Registry.Remove(this); }
- =20
+
=20
   // Accessors.
   //
@@ -68,11 +68,6 @@
 ScheduleDAGSDNodes *createBURRListDAGScheduler(SelectionDAGISel *IS,
                                                CodeGenOpt::Level OptLevel);
=20
-/// createTDRRListDAGScheduler - This creates a top down register usage
-/// reduction list scheduler.
-ScheduleDAGSDNodes *createTDRRListDAGScheduler(SelectionDAGISel *IS,
-                                               CodeGenOpt::Level OptLevel);
-
 /// createBURRListDAGScheduler - This creates a bottom up list scheduler t=
hat
 /// schedules nodes in source code order when possible.
 ScheduleDAGSDNodes *createSourceListDAGScheduler(SelectionDAGISel *IS,
@@ -91,16 +86,17 @@
 /// to reduce register pressure.
 ScheduleDAGSDNodes *createILPListDAGScheduler(SelectionDAGISel *IS,
                                               CodeGenOpt::Level);
-/// createTDListDAGScheduler - This creates a top-down list scheduler with
-/// a hazard recognizer.
-ScheduleDAGSDNodes *createTDListDAGScheduler(SelectionDAGISel *IS,
-                                             CodeGenOpt::Level OptLevel);
=20
 /// createFastDAGScheduler - This creates a "fast" scheduler.
 ///
 ScheduleDAGSDNodes *createFastDAGScheduler(SelectionDAGISel *IS,
                                            CodeGenOpt::Level OptLevel);
=20
+/// createVLIWDAGScheduler - Scheduler for VLIW targets. This creates top =
down
+/// DFA driven list scheduler with clustering heuristic to control
+/// register pressure.
+ScheduleDAGSDNodes *createVLIWDAGScheduler(SelectionDAGISel *IS,
+                                           CodeGenOpt::Level OptLevel);
 /// createDefaultScheduler - This creates an instruction scheduler appropr=
iate
 /// for the target.
 ScheduleDAGSDNodes *createDefaultScheduler(SelectionDAGISel *IS,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/SelectionDAG.h
--- a/head/contrib/llvm/include/llvm/CodeGen/SelectionDAG.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/SelectionDAG.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -51,7 +51,7 @@
   static void noteHead(SDNode*, SDNode*) {}
=20
   static void deleteNode(SDNode *) {
-    assert(0 && "ilist_traits<SDNode> shouldn't see a deleteNode call!");
+    llvm_unreachable("ilist_traits<SDNode> shouldn't see a deleteNode call=
!");
   }
 private:
   static void createNode(const SDNode &);
@@ -112,9 +112,10 @@
 };
=20
 enum CombineLevel {
-  Unrestricted,   // Combine may create illegal operations and illegal typ=
es.
-  NoIllegalTypes, // Combine may create illegal operations but no illegal =
types.
-  NoIllegalOperations // Combine may only create legal operations and type=
s.
+  BeforeLegalizeTypes,
+  AfterLegalizeTypes,
+  AfterLegalizeVectorOps,
+  AfterLegalizeDAG
 };
=20
 class SelectionDAG;
@@ -138,6 +139,7 @@
   const TargetSelectionDAGInfo &TSI;
   MachineFunction *MF;
   LLVMContext *Context;
+  CodeGenOpt::Level OptLevel;
=20
   /// EntryNode - The starting token.
   SDNode EntryNode;
@@ -186,7 +188,7 @@
   SelectionDAG(const SelectionDAG&);   // Do not implement.
=20
 public:
-  explicit SelectionDAG(const TargetMachine &TM);
+  explicit SelectionDAG(const TargetMachine &TM, llvm::CodeGenOpt::Level);
   ~SelectionDAG();
=20
   /// init - Prepare this SelectionDAG to process code in the given
@@ -392,6 +394,7 @@
                                   unsigned char TargetFlags =3D 0);
   SDValue getValueType(EVT);
   SDValue getRegister(unsigned Reg, EVT VT);
+  SDValue getRegisterMask(const uint32_t *RegMask);
   SDValue getEHLabel(DebugLoc dl, SDValue Root, MCSymbol *Label);
   SDValue getBlockAddress(const BlockAddress *BA, EVT VT,
                           bool isTarget =3D false, unsigned char TargetFla=
gs =3D 0);
@@ -650,8 +653,8 @@
   ///
   SDValue getLoad(EVT VT, DebugLoc dl, SDValue Chain, SDValue Ptr,
                   MachinePointerInfo PtrInfo, bool isVolatile,
-                  bool isNonTemporal, unsigned Alignment,
-                  const MDNode *TBAAInfo =3D 0);
+                  bool isNonTemporal, bool isInvariant, unsigned Alignment,
+                  const MDNode *TBAAInfo =3D 0, const MDNode *Ranges =3D 0=
);
   SDValue getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
                      SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInf=
o,
                      EVT MemVT, bool isVolatile,
@@ -663,8 +666,9 @@
                   EVT VT, DebugLoc dl,
                   SDValue Chain, SDValue Ptr, SDValue Offset,
                   MachinePointerInfo PtrInfo, EVT MemVT,
-                  bool isVolatile, bool isNonTemporal, unsigned Alignment,
-                  const MDNode *TBAAInfo =3D 0);
+                  bool isVolatile, bool isNonTemporal, bool isInvariant,
+                  unsigned Alignment, const MDNode *TBAAInfo =3D 0,
+                  const MDNode *Ranges =3D 0);
   SDValue getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
                   EVT VT, DebugLoc dl,
                   SDValue Chain, SDValue Ptr, SDValue Offset,
@@ -976,8 +980,8 @@
   /// bitsets.  This code only analyzes bits in Mask, in order to short-ci=
rcuit
   /// processing.  Targets can implement the computeMaskedBitsForTargetNode
   /// method in the TargetLowering class to allow target nodes to be under=
stood.
-  void ComputeMaskedBits(SDValue Op, const APInt &Mask, APInt &KnownZero,
-                         APInt &KnownOne, unsigned Depth =3D 0) const;
+  void ComputeMaskedBits(SDValue Op, APInt &KnownZero, APInt &KnownOne,
+                         unsigned Depth =3D 0) const;
=20
   /// ComputeNumSignBits - Return the number of times the sign bit of the
   /// register is replicated into the other bits.  We know that at least 1=
 bit
@@ -1033,6 +1037,7 @@
                                void *&InsertPos);
   SDNode *FindModifiedNodeSlot(SDNode *N, const SDValue *Ops, unsigned Num=
Ops,
                                void *&InsertPos);
+  SDNode *UpdadeDebugLocOnMergedSDNode(SDNode *N, DebugLoc loc);
=20
   void DeleteNodeNotInCSEMaps(SDNode *N);
   void DeallocateNode(SDNode *N);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/SelectionDAGISel.h
--- a/head/contrib/llvm/include/llvm/CodeGen/SelectionDAGISel.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/SelectionDAGISel.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -29,6 +29,7 @@
   class MachineFunction;
   class MachineInstr;
   class TargetLowering;
+  class TargetLibraryInfo;
   class TargetInstrInfo;
   class FunctionLoweringInfo;
   class ScheduleHazardRecognizer;
@@ -42,6 +43,7 @@
 public:
   const TargetMachine &TM;
   const TargetLowering &TLI;
+  const TargetLibraryInfo *LibInfo;
   FunctionLoweringInfo *FuncInfo;
   MachineFunction *MF;
   MachineRegisterInfo *RegInfo;
@@ -92,7 +94,7 @@
=20
   /// IsLegalToFold - Returns true if the specific operand node N of
   /// U can be folded during instruction selection that starts at Root.
-  /// FIXME: This is a static member function because the MSP430/SystemZ/X=
86
+  /// FIXME: This is a static member function because the MSP430/X86
   /// targets, which uses it during isel.  This could become a proper memb=
er.
   static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
                             CodeGenOpt::Level OptLevel,
@@ -179,6 +181,7 @@
   /// ISelUpdater - helper class to handle updates of the
   /// instruction selection graph.
   class ISelUpdater : public SelectionDAG::DAGUpdateListener {
+    virtual void anchor();
     SelectionDAG::allnodes_iterator &ISelPosition;
   public:
     explicit ISelUpdater(SelectionDAG::allnodes_iterator &isp)
@@ -237,8 +240,7 @@
   /// succeeds or false if it fails.  The number is a private implementati=
on
   /// detail to the code tblgen produces.
   virtual bool CheckPatternPredicate(unsigned PredNo) const {
-    assert(0 && "Tblgen should generate the implementation of this!");
-    return 0;
+    llvm_unreachable("Tblgen should generate the implementation of this!");
   }
=20
   /// CheckNodePredicate - This function is generated by tblgen in the tar=
get.
@@ -246,20 +248,17 @@
   /// false if it fails.  The number is a private implementation
   /// detail to the code tblgen produces.
   virtual bool CheckNodePredicate(SDNode *N, unsigned PredNo) const {
-    assert(0 && "Tblgen should generate the implementation of this!");
-    return 0;
+    llvm_unreachable("Tblgen should generate the implementation of this!");
   }
=20
   virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N,
                                    unsigned PatternNo,
                         SmallVectorImpl<std::pair<SDValue, SDNode*> > &Res=
ult) {
-    assert(0 && "Tblgen should generate the implementation of this!");
-    return false;
+    llvm_unreachable("Tblgen should generate the implementation of this!");
   }
=20
   virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {
-    assert(0 && "Tblgen should generate this!");
-    return SDValue();
+    llvm_unreachable("Tblgen should generate this!");
   }
=20
   SDNode *SelectCodeCommon(SDNode *NodeToMatch,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/SelectionDAGNodes.h
--- a/head/contrib/llvm/include/llvm/CodeGen/SelectionDAGNodes.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/SelectionDAGNodes.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -917,12 +917,13 @@
   // with MachineMemOperand information.
   bool isVolatile() const { return (SubclassData >> 5) & 1; }
   bool isNonTemporal() const { return (SubclassData >> 6) & 1; }
+  bool isInvariant() const { return (SubclassData >> 7) & 1; }
=20
   AtomicOrdering getOrdering() const {
-    return AtomicOrdering((SubclassData >> 7) & 15);
+    return AtomicOrdering((SubclassData >> 8) & 15);
   }
   SynchronizationScope getSynchScope() const {
-    return SynchronizationScope((SubclassData >> 11) & 1);
+    return SynchronizationScope((SubclassData >> 12) & 1);
   }
=20
   /// Returns the SrcValue and offset that describes the location of the a=
ccess
@@ -932,6 +933,9 @@
   /// Returns the TBAAInfo that describes the dereference.
   const MDNode *getTBAAInfo() const { return MMO->getTBAAInfo(); }
=20
+  /// Returns the Ranges that describes the dereference.
+  const MDNode *getRanges() const { return MMO->getRanges(); }
+
   /// getMemoryVT - Return the type of the in-memory value.
   EVT getMemoryVT() const { return MemoryVT; }
=20
@@ -993,8 +997,8 @@
            "Ordering may not require more than 4 bits!");
     assert((SynchScope & 1) =3D=3D SynchScope &&
            "SynchScope may not require more than 1 bit!");
-    SubclassData |=3D Ordering << 7;
-    SubclassData |=3D SynchScope << 11;
+    SubclassData |=3D Ordering << 8;
+    SubclassData |=3D SynchScope << 12;
     assert(getOrdering() =3D=3D Ordering && "Ordering encoding error!");
     assert(getSynchScope() =3D=3D SynchScope && "Synch-scope encoding erro=
r!");
=20
@@ -1113,11 +1117,9 @@
   }
 public:
=20
-  void getMask(SmallVectorImpl<int> &M) const {
+  ArrayRef<int> getMask() const {
     EVT VT =3D getValueType(0);
-    M.clear();
-    for (unsigned i =3D 0, e =3D VT.getVectorNumElements(); i !=3D e; ++i)
-      M.push_back(Mask[i]);
+    return makeArrayRef(Mask, VT.getVectorNumElements());
   }
   int getMaskElt(unsigned Idx) const {
     assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of ran=
ge!");
@@ -1434,6 +1436,23 @@
   }
 };
=20
+class RegisterMaskSDNode : public SDNode {
+  // The memory for RegMask is not owned by the node.
+  const uint32_t *RegMask;
+  friend class SelectionDAG;
+  RegisterMaskSDNode(const uint32_t *mask)
+    : SDNode(ISD::RegisterMask, DebugLoc(), getSDVTList(MVT::Untyped)),
+      RegMask(mask) {}
+public:
+
+  const uint32_t *getRegMask() const { return RegMask; }
+
+  static bool classof(const RegisterMaskSDNode *) { return true; }
+  static bool classof(const SDNode *N) {
+    return N->getOpcode() =3D=3D ISD::RegisterMask;
+  }
+};
+
 class BlockAddressSDNode : public SDNode {
   const BlockAddress *BA;
   unsigned char TargetFlags;
@@ -1684,6 +1703,8 @@
   /// setMemRefs - Assign this MachineSDNodes's memory reference descriptor
   /// list. This does not transfer ownership.
   void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd) {
+    for (mmo_iterator MMI =3D NewMemRefs, MME =3D NewMemRefsEnd; MMI !=3D =
MME; ++MMI)
+      assert(*MMI && "Null mem ref detected!");
     MemRefs =3D NewMemRefs;
     MemRefsEnd =3D NewMemRefsEnd;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/SlotIndexes.h
--- a/head/contrib/llvm/include/llvm/CodeGen/SlotIndexes.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/SlotIndexes.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -19,7 +19,7 @@
 #ifndef LLVM_CODEGEN_SLOTINDEXES_H
 #define LLVM_CODEGEN_SLOTINDEXES_H
=20
-#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineInstrBundle.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/ADT/PointerIntPair.h"
@@ -83,7 +83,29 @@
     friend class SlotIndexes;
     friend struct DenseMapInfo<SlotIndex>;
=20
-    enum Slot { LOAD, USE, DEF, STORE, NUM };
+    enum Slot {
+      /// Basic block boundary.  Used for live ranges entering and leaving=
 a
+      /// block without being live in the layout neighbor.  Also used as t=
he
+      /// def slot of PHI-defs.
+      Slot_Block,
+
+      /// Early-clobber register use/def slot.  A live range defined at
+      /// Slot_EarlyCLobber interferes with normal live ranges killed at
+      /// Slot_Register.  Also used as the kill slot for live ranges tied =
to an
+      /// early-clobber def.
+      Slot_EarlyClobber,
+
+      /// Normal register use/def slot.  Normal instructions kill and defi=
ne
+      /// register live ranges at this slot.
+      Slot_Register,
+
+      /// Dead def kill point.  Kill slot for a live range that is defined=
 by
+      /// the same instruction (Slot_Register or Slot_EarlyClobber), but i=
sn't
+      /// used anywhere.
+      Slot_Dead,
+
+      Slot_Count
+    };
=20
     PointerIntPair<IndexListEntry*, 2, unsigned> lie;
=20
@@ -113,7 +135,7 @@
     enum {
       /// The default distance between instructions as returned by distanc=
e().
       /// This may vary as instructions are inserted and removed.
-      InstrDist =3D 4*NUM
+      InstrDist =3D 4 * Slot_Count
     };
=20
     static inline SlotIndex getEmptyKey() {
@@ -186,69 +208,55 @@
       return A.lie.getPointer() =3D=3D B.lie.getPointer();
     }
=20
+    /// isEarlierInstr - Return true if A refers to an instruction earlier=
 than
+    /// B. This is equivalent to A < B && !isSameInstr(A, B).
+    static bool isEarlierInstr(SlotIndex A, SlotIndex B) {
+      return A.entry().getIndex() < B.entry().getIndex();
+    }
+
     /// Return the distance from this index to the given one.
     int distance(SlotIndex other) const {
       return other.getIndex() - getIndex();
     }
=20
-    /// isLoad - Return true if this is a LOAD slot.
-    bool isLoad() const {
-      return getSlot() =3D=3D LOAD;
-    }
+    /// isBlock - Returns true if this is a block boundary slot.
+    bool isBlock() const { return getSlot() =3D=3D Slot_Block; }
=20
-    /// isDef - Return true if this is a DEF slot.
-    bool isDef() const {
-      return getSlot() =3D=3D DEF;
-    }
+    /// isEarlyClobber - Returns true if this is an early-clobber slot.
+    bool isEarlyClobber() const { return getSlot() =3D=3D Slot_EarlyClobbe=
r; }
=20
-    /// isUse - Return true if this is a USE slot.
-    bool isUse() const {
-      return getSlot() =3D=3D USE;
-    }
+    /// isRegister - Returns true if this is a normal register use/def slo=
t.
+    /// Note that early-clobber slots may also be used for uses and defs.
+    bool isRegister() const { return getSlot() =3D=3D Slot_Register; }
=20
-    /// isStore - Return true if this is a STORE slot.
-    bool isStore() const {
-      return getSlot() =3D=3D STORE;
-    }
+    /// isDead - Returns true if this is a dead def kill slot.
+    bool isDead() const { return getSlot() =3D=3D Slot_Dead; }
=20
     /// Returns the base index for associated with this index. The base in=
dex
-    /// is the one associated with the LOAD slot for the instruction point=
ed to
-    /// by this index.
+    /// is the one associated with the Slot_Block slot for the instruction
+    /// pointed to by this index.
     SlotIndex getBaseIndex() const {
-      return getLoadIndex();
+      return SlotIndex(&entry(), Slot_Block);
     }
=20
     /// Returns the boundary index for associated with this index. The bou=
ndary
-    /// index is the one associated with the LOAD slot for the instruction
+    /// index is the one associated with the Slot_Block slot for the instr=
uction
     /// pointed to by this index.
     SlotIndex getBoundaryIndex() const {
-      return getStoreIndex();
+      return SlotIndex(&entry(), Slot_Dead);
     }
=20
-    /// Returns the index of the LOAD slot for the instruction pointed to =
by
-    /// this index.
-    SlotIndex getLoadIndex() const {
-      return SlotIndex(&entry(), SlotIndex::LOAD);
-    }   =20
-
-    /// Returns the index of the USE slot for the instruction pointed to by
-    /// this index.
-    SlotIndex getUseIndex() const {
-      return SlotIndex(&entry(), SlotIndex::USE);
+    /// Returns the register use/def slot in the current instruction for a
+    /// normal or early-clobber def.
+    SlotIndex getRegSlot(bool EC =3D false) const {
+      return SlotIndex(&entry(), EC ? Slot_EarlyClobber : Slot_Register);
     }
=20
-    /// Returns the index of the DEF slot for the instruction pointed to by
-    /// this index.
-    SlotIndex getDefIndex() const {
-      return SlotIndex(&entry(), SlotIndex::DEF);
+    /// Returns the dead def kill slot for the current instruction.
+    SlotIndex getDeadSlot() const {
+      return SlotIndex(&entry(), Slot_Dead);
     }
=20
-    /// Returns the index of the STORE slot for the instruction pointed to=
 by
-    /// this index.
-    SlotIndex getStoreIndex() const {
-      return SlotIndex(&entry(), SlotIndex::STORE);
-    }   =20
-
     /// Returns the next slot in the index list. This could be either the
     /// next slot for the instruction pointed to by this index or, if this
     /// index is a STORE, the first slot for the next instruction.
@@ -257,8 +265,8 @@
     /// use one of those methods.
     SlotIndex getNextSlot() const {
       Slot s =3D getSlot();
-      if (s =3D=3D SlotIndex::STORE) {
-        return SlotIndex(entry().getNext(), SlotIndex::LOAD);
+      if (s =3D=3D Slot_Dead) {
+        return SlotIndex(entry().getNext(), Slot_Block);
       }
       return SlotIndex(&entry(), s + 1);
     }
@@ -271,14 +279,14 @@
=20
     /// Returns the previous slot in the index list. This could be either =
the
     /// previous slot for the instruction pointed to by this index or, if =
this
-    /// index is a LOAD, the last slot for the previous instruction.
+    /// index is a Slot_Block, the last slot for the previous instruction.
     /// WARNING: This method is considerably more expensive than the metho=
ds
     /// that return specific slots (getUseIndex(), etc). If you can - plea=
se
     /// use one of those methods.
     SlotIndex getPrevSlot() const {
       Slot s =3D getSlot();
-      if (s =3D=3D SlotIndex::LOAD) {
-        return SlotIndex(entry().getPrev(), SlotIndex::STORE);
+      if (s =3D=3D Slot_Block) {
+        return SlotIndex(entry().getPrev(), Slot_Dead);
       }
       return SlotIndex(&entry(), s - 1);
     }
@@ -464,11 +472,6 @@
       return SlotIndex(back(), 0);
     }
=20
-    /// Returns the invalid index marker for this analysis.
-    SlotIndex getInvalidIndex() {
-      return getZeroIndex();
-    }
-
     /// Returns the distance between the highest and lowest indexes alloca=
ted
     /// so far.
     unsigned getIndexesLength() const {
@@ -486,12 +489,13 @@
     /// Returns true if the given machine instr is mapped to an index,
     /// otherwise returns false.
     bool hasIndex(const MachineInstr *instr) const {
-      return (mi2iMap.find(instr) !=3D mi2iMap.end());
+      return mi2iMap.count(instr);
     }
=20
     /// Returns the base index for the given instruction.
-    SlotIndex getInstructionIndex(const MachineInstr *instr) const {
-      Mi2IndexMap::const_iterator itr =3D mi2iMap.find(instr);
+    SlotIndex getInstructionIndex(const MachineInstr *MI) const {
+      // Instructions inside a bundle have the same number as the bundle i=
tself.
+      Mi2IndexMap::const_iterator itr =3D mi2iMap.find(getBundleStart(MI));
       assert(itr !=3D mi2iMap.end() && "Instruction not found in maps.");
       return itr->second;
     }
@@ -645,6 +649,8 @@
     /// instructions, create the new index after the null indexes instead =
of
     /// before them.
     SlotIndex insertMachineInstrInMaps(MachineInstr *mi, bool Late =3D fal=
se) {
+      assert(!mi->isInsideBundle() &&
+             "Instructions inside bundles should use bundle start's slot."=
);
       assert(mi2iMap.find(mi) =3D=3D mi2iMap.end() && "Instr already index=
ed.");
       // Numbering DBG_VALUE instructions could cause code generation to be
       // affected by debug information.
@@ -677,7 +683,7 @@
       if (dist =3D=3D 0)
         renumberIndexes(newEntry);
=20
-      SlotIndex newIndex(newEntry, SlotIndex::LOAD);
+      SlotIndex newIndex(newEntry, SlotIndex::Slot_Block);
       mi2iMap.insert(std::make_pair(mi, newIndex));
       return newIndex;
     }
@@ -728,8 +734,8 @@
       insert(nextEntry, startEntry);
       insert(nextEntry, stopEntry);
=20
-      SlotIndex startIdx(startEntry, SlotIndex::LOAD);
-      SlotIndex endIdx(nextEntry, SlotIndex::LOAD);
+      SlotIndex startIdx(startEntry, SlotIndex::Slot_Block);
+      SlotIndex endIdx(nextEntry, SlotIndex::Slot_Block);
=20
       assert(unsigned(mbb->getNumber()) =3D=3D MBBRanges.size() &&
              "Blocks must be added in order");
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/TargetLoweringObjectFileImpl.h
--- a/head/contrib/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/TargetLoweringObjectFileImpl.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,9 @@
 #ifndef LLVM_CODEGEN_TARGETLOWERINGOBJECTFILEIMPL_H
 #define LLVM_CODEGEN_TARGETLOWERINGOBJECTFILEIMPL_H
=20
-#include "llvm/ADT/StringRef.h"
 #include "llvm/MC/SectionKind.h"
 #include "llvm/Target/TargetLoweringObjectFile.h"
+#include "llvm/ADT/StringRef.h"
=20
 namespace llvm {
   class MachineModuleInfo;
@@ -65,6 +65,11 @@
   virtual MCSymbol *
   getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
                           MachineModuleInfo *MMI) const;
+
+  virtual const MCSection *
+  getStaticCtorSection(unsigned Priority =3D 65535) const;
+  virtual const MCSection *
+  getStaticDtorSection(unsigned Priority =3D 65535) const;
 };
=20
=20
@@ -73,6 +78,12 @@
 public:
   virtual ~TargetLoweringObjectFileMachO() {}
=20
+  /// emitModuleFlags - Emit the module flags that specify the garbage
+  /// collection information.
+  virtual void emitModuleFlags(MCStreamer &Streamer,
+                               ArrayRef<Module::ModuleFlagEntry> ModuleFla=
gs,
+                               Mangler *Mang, const TargetMachine &TM) con=
st;
+
   virtual const MCSection *
   SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
                          Mangler *Mang, const TargetMachine &TM) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/ValueTypes.h
--- a/head/contrib/llvm/include/llvm/CodeGen/ValueTypes.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/ValueTypes.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -16,10 +16,11 @@
 #ifndef LLVM_CODEGEN_VALUETYPES_H
 #define LLVM_CODEGEN_VALUETYPES_H
=20
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
 #include <cassert>
 #include <string>
-#include "llvm/Support/DataTypes.h"
-#include "llvm/Support/MathExtras.h"
=20
 namespace llvm {
   class Type;
@@ -45,49 +46,56 @@
       FIRST_INTEGER_VALUETYPE =3D i1,
       LAST_INTEGER_VALUETYPE  =3D i128,
=20
-      f32            =3D   7,   // This is a 32 bit floating point value
-      f64            =3D   8,   // This is a 64 bit floating point value
-      f80            =3D   9,   // This is a 80 bit floating point value
-      f128           =3D  10,   // This is a 128 bit floating point value
-      ppcf128        =3D  11,   // This is a PPC 128-bit floating point va=
lue
+      f16            =3D   7,   // This is a 16 bit floating point value
+      f32            =3D   8,   // This is a 32 bit floating point value
+      f64            =3D   9,   // This is a 64 bit floating point value
+      f80            =3D  10,   // This is a 80 bit floating point value
+      f128           =3D  11,   // This is a 128 bit floating point value
+      ppcf128        =3D  12,   // This is a PPC 128-bit floating point va=
lue
=20
-      v2i8           =3D  12,   //  2 x i8
-      v4i8           =3D  13,   //  4 x i8
-      v8i8           =3D  14,   //  8 x i8
-      v16i8          =3D  15,   // 16 x i8
-      v32i8          =3D  16,   // 32 x i8
-      v2i16          =3D  17,   //  2 x i16
-      v4i16          =3D  18,   //  4 x i16
-      v8i16          =3D  19,   //  8 x i16
-      v16i16         =3D  20,   // 16 x i16
-      v2i32          =3D  21,   //  2 x i32
-      v4i32          =3D  22,   //  4 x i32
-      v8i32          =3D  23,   //  8 x i32
-      v1i64          =3D  24,   //  1 x i64
-      v2i64          =3D  25,   //  2 x i64
-      v4i64          =3D  26,   //  4 x i64
-      v8i64          =3D  27,   //  8 x i64
+      FIRST_FP_VALUETYPE =3D f16,
+      LAST_FP_VALUETYPE  =3D ppcf128,
=20
-      v2f32          =3D  28,   //  2 x f32
-      v4f32          =3D  29,   //  4 x f32
-      v8f32          =3D  30,   //  8 x f32
-      v2f64          =3D  31,   //  2 x f64
-      v4f64          =3D  32,   //  4 x f64
+      v2i8           =3D  13,   //  2 x i8
+      v4i8           =3D  14,   //  4 x i8
+      v8i8           =3D  15,   //  8 x i8
+      v16i8          =3D  16,   // 16 x i8
+      v32i8          =3D  17,   // 32 x i8
+      v2i16          =3D  18,   //  2 x i16
+      v4i16          =3D  19,   //  4 x i16
+      v8i16          =3D  20,   //  8 x i16
+      v16i16         =3D  21,   // 16 x i16
+      v2i32          =3D  22,   //  2 x i32
+      v4i32          =3D  23,   //  4 x i32
+      v8i32          =3D  24,   //  8 x i32
+      v1i64          =3D  25,   //  1 x i64
+      v2i64          =3D  26,   //  2 x i64
+      v4i64          =3D  27,   //  4 x i64
+      v8i64          =3D  28,   //  8 x i64
+
+      v2f16          =3D  29,   //  2 x f16
+      v2f32          =3D  30,   //  2 x f32
+      v4f32          =3D  31,   //  4 x f32
+      v8f32          =3D  32,   //  8 x f32
+      v2f64          =3D  33,   //  2 x f64
+      v4f64          =3D  34,   //  4 x f64
=20
       FIRST_VECTOR_VALUETYPE =3D v2i8,
       LAST_VECTOR_VALUETYPE  =3D v4f64,
+      FIRST_FP_VECTOR_VALUETYPE =3D v2f16,
+      LAST_FP_VECTOR_VALUETYPE =3D v4f64,
=20
-      x86mmx         =3D  33,   // This is an X86 MMX value
+      x86mmx         =3D  35,   // This is an X86 MMX value
=20
-      Glue           =3D  34,   // This glues nodes together during pre-RA=
 sched
+      Glue           =3D  36,   // This glues nodes together during pre-RA=
 sched
=20
-      isVoid         =3D  35,   // This has no value
+      isVoid         =3D  37,   // This has no value
=20
-      untyped        =3D  36,   // This value takes a register, but has
+      Untyped        =3D  38,   // This value takes a register, but has
                               // unspecified type.  The register class
                               // will be determined by the opcode.
=20
-      LAST_VALUETYPE =3D  37,   // This always remains at the end of the l=
ist.
+      LAST_VALUETYPE =3D  39,   // This always remains at the end of the l=
ist.
=20
       // This is the current maximum for LAST_VALUETYPE.
       // MVT::MAX_ALLOWED_VALUETYPE is used for asserts and to size bit ve=
ctors
@@ -143,8 +151,10 @@
=20
     /// isFloatingPoint - Return true if this is a FP, or a vector FP type.
     bool isFloatingPoint() const {
-      return ((SimpleTy >=3D MVT::f32 && SimpleTy <=3D MVT::ppcf128) ||
-	      (SimpleTy >=3D MVT::v2f32 && SimpleTy <=3D MVT::v4f64));
+      return ((SimpleTy >=3D MVT::FIRST_FP_VALUETYPE &&
+               SimpleTy <=3D MVT::LAST_FP_VALUETYPE) ||
+	      (SimpleTy >=3D MVT::FIRST_FP_VECTOR_VALUETYPE &&
+         SimpleTy <=3D MVT::LAST_FP_VECTOR_VALUETYPE));
     }
=20
     /// isInteger - Return true if this is an integer, or a vector integer=
 type.
@@ -203,6 +213,7 @@
       case v2i64:
       case v4i64:
       case v8i64: return i64;
+      case v2f16: return f16;
       case v2f32:
       case v4f32:
       case v8f32: return f32;
@@ -233,6 +244,7 @@
       case v2i16:
       case v2i32:
       case v2i64:
+      case v2f16:
       case v2f32:
       case v2f64: return 2;
       case v1i64: return 1;
@@ -242,21 +254,23 @@
     unsigned getSizeInBits() const {
       switch (SimpleTy) {
       case iPTR:
-        assert(0 && "Value type size is target-dependent. Ask TLI.");
+        llvm_unreachable("Value type size is target-dependent. Ask TLI.");
       case iPTRAny:
       case iAny:
       case fAny:
-        assert(0 && "Value type is overloaded.");
+        llvm_unreachable("Value type is overloaded.");
       default:
-        assert(0 && "getSizeInBits called on extended MVT.");
+        llvm_unreachable("getSizeInBits called on extended MVT.");
       case i1  :  return 1;
       case i8  :  return 8;
       case i16 :
+      case f16:
       case v2i8:  return 16;
       case f32 :
       case i32 :
       case v4i8:
-      case v2i16: return 32;
+      case v2i16:
+      case v2f16: return 32;
       case x86mmx:
       case f64 :
       case i64 :
@@ -300,7 +314,9 @@
     static MVT getFloatingPointVT(unsigned BitWidth) {
       switch (BitWidth) {
       default:
-        assert(false && "Bad bit width!");
+        llvm_unreachable("Bad bit width!");
+      case 16:
+        return MVT::f16;
       case 32:
         return MVT::f32;
       case 64:
@@ -359,6 +375,9 @@
         if (NumElements =3D=3D 4)  return MVT::v4i64;
         if (NumElements =3D=3D 8)  return MVT::v8i64;
         break;
+      case MVT::f16:
+        if (NumElements =3D=3D 2)  return MVT::v2f16;
+        break;
       case MVT::f32:
         if (NumElements =3D=3D 2)  return MVT::v2f32;
         if (NumElements =3D=3D 4)  return MVT::v4f32;
@@ -424,20 +443,6 @@
       return getExtendedVectorVT(Context, VT, NumElements);
     }
=20
-    /// getIntVectorWithNumElements - Return any integer vector type that =
has
-    /// the specified number of elements.
-    static EVT getIntVectorWithNumElements(LLVMContext &C, unsigned NumElt=
s) {
-      switch (NumElts) {
-      default: return getVectorVT(C, MVT::i8, NumElts);
-      case  1: return MVT::v1i64;
-      case  2: return MVT::v2i32;
-      case  4: return MVT::v4i16;
-      case  8: return MVT::v8i8;
-      case 16: return MVT::v16i8;
-      }
-      return MVT::INVALID_SIMPLE_VALUE_TYPE;
-    }
-
     /// changeVectorElementTypeToInteger - Return a vector with the same n=
umber
     /// of elements as this vector, but with the element type converted to=
 an
     /// integer type with the same bitwidth.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/CodeGen=
/ValueTypes.td
--- a/head/contrib/llvm/include/llvm/CodeGen/ValueTypes.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/CodeGen/ValueTypes.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -26,39 +26,41 @@
 def i32    : ValueType<32 ,  4>;   // 32-bit integer value
 def i64    : ValueType<64 ,  5>;   // 64-bit integer value
 def i128   : ValueType<128,  6>;   // 128-bit integer value
-def f32    : ValueType<32 ,  7>;   // 32-bit floating point value
-def f64    : ValueType<64 ,  8>;   // 64-bit floating point value
-def f80    : ValueType<80 ,  9>;   // 80-bit floating point value
-def f128   : ValueType<128, 10>;   // 128-bit floating point value
-def ppcf128: ValueType<128, 11>;   // PPC 128-bit floating point value
+def f16    : ValueType<16 ,  7>;   // 32-bit floating point value
+def f32    : ValueType<32 ,  8>;   // 32-bit floating point value
+def f64    : ValueType<64 ,  9>;   // 64-bit floating point value
+def f80    : ValueType<80 , 10>;   // 80-bit floating point value
+def f128   : ValueType<128, 11>;   // 128-bit floating point value
+def ppcf128: ValueType<128, 12>;   // PPC 128-bit floating point value
=20
-def v2i8   : ValueType<16 , 12>;   //  2 x i8  vector value
-def v4i8   : ValueType<32 , 13>;   //  4 x i8  vector value
-def v8i8   : ValueType<64 , 14>;   //  8 x i8  vector value
-def v16i8  : ValueType<128, 15>;   // 16 x i8  vector value
-def v32i8  : ValueType<256, 16>;   // 32 x i8 vector value
-def v2i16  : ValueType<32 , 17>;   //  2 x i16 vector value
-def v4i16  : ValueType<64 , 18>;   //  4 x i16 vector value
-def v8i16  : ValueType<128, 19>;   //  8 x i16 vector value
-def v16i16 : ValueType<256, 20>;   // 16 x i16 vector value
-def v2i32  : ValueType<64 , 21>;   //  2 x i32 vector value
-def v4i32  : ValueType<128, 22>;   //  4 x i32 vector value
-def v8i32  : ValueType<256, 23>;   //  8 x i32 vector value
-def v1i64  : ValueType<64 , 24>;   //  1 x i64 vector value
-def v2i64  : ValueType<128, 25>;   //  2 x i64 vector value
-def v4i64  : ValueType<256, 26>;   //  4 x i64 vector value
-def v8i64  : ValueType<512, 27>;   //  8 x i64 vector value
+def v2i8   : ValueType<16 , 13>;   //  2 x i8  vector value
+def v4i8   : ValueType<32 , 14>;   //  4 x i8  vector value
+def v8i8   : ValueType<64 , 15>;   //  8 x i8  vector value
+def v16i8  : ValueType<128, 16>;   // 16 x i8  vector value
+def v32i8  : ValueType<256, 17>;   // 32 x i8 vector value
+def v2i16  : ValueType<32 , 18>;   //  2 x i16 vector value
+def v4i16  : ValueType<64 , 19>;   //  4 x i16 vector value
+def v8i16  : ValueType<128, 20>;   //  8 x i16 vector value
+def v16i16 : ValueType<256, 21>;   // 16 x i16 vector value
+def v2i32  : ValueType<64 , 22>;   //  2 x i32 vector value
+def v4i32  : ValueType<128, 23>;   //  4 x i32 vector value
+def v8i32  : ValueType<256, 24>;   //  8 x i32 vector value
+def v1i64  : ValueType<64 , 25>;   //  1 x i64 vector value
+def v2i64  : ValueType<128, 26>;   //  2 x i64 vector value
+def v4i64  : ValueType<256, 27>;   //  4 x i64 vector value
+def v8i64  : ValueType<512, 28>;   //  8 x i64 vector value
=20
-def v2f32  : ValueType<64 , 28>;   //  2 x f32 vector value
-def v4f32  : ValueType<128, 29>;   //  4 x f32 vector value
-def v8f32  : ValueType<256, 30>;   //  8 x f32 vector value
-def v2f64  : ValueType<128, 31>;   //  2 x f64 vector value
-def v4f64  : ValueType<256, 32>;   //  4 x f64 vector value
+def v2f16  : ValueType<32 , 29>;   //  2 x f16 vector value
+def v2f32  : ValueType<64 , 30>;   //  2 x f32 vector value
+def v4f32  : ValueType<128, 31>;   //  4 x f32 vector value
+def v8f32  : ValueType<256, 32>;   //  8 x f32 vector value
+def v2f64  : ValueType<128, 33>;   //  2 x f64 vector value
+def v4f64  : ValueType<256, 34>;   //  4 x f64 vector value
=20
-def x86mmx : ValueType<64 , 33>;   // X86 MMX value
-def FlagVT : ValueType<0  , 34>;   // Pre-RA sched glue
-def isVoid : ValueType<0  , 35>;   // Produces no value
-def untyped: ValueType<8  , 36>;   // Produces an untyped value
+def x86mmx : ValueType<64 , 35>;   // X86 MMX value
+def FlagVT : ValueType<0  , 36>;   // Pre-RA sched glue
+def isVoid : ValueType<0  , 37>;   // Produces no value
+def untyped: ValueType<8  , 38>;   // Produces an untyped value
=20
 def MetadataVT: ValueType<0, 250>; // Metadata
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Constan=
t.h
--- a/head/contrib/llvm/include/llvm/Constant.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm/Constant.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -41,6 +41,7 @@
 class Constant : public User {
   void operator=3D(const Constant &);     // Do not implement
   Constant(const Constant &);           // Do not implement
+  virtual void anchor();
  =20
 protected:
   Constant(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps)
@@ -90,12 +91,13 @@
   /// FIXME: This really should not be in VMCore.
   PossibleRelocationsTy getRelocationInfo() const;
  =20
-  /// getVectorElements - This method, which is only valid on constant of =
vector
-  /// type, returns the elements of the vector in the specified smallvecto=
r.
-  /// This handles breaking down a vector undef into undef elements, etc. =
 For
-  /// constant exprs and other cases we can't handle, we return an empty v=
ector.
-  void getVectorElements(SmallVectorImpl<Constant*> &Elts) const;
-
+  /// getAggregateElement - For aggregates (struct/array/vector) return the
+  /// constant that corresponds to the specified element if possible, or n=
ull if
+  /// not.  This can return null if the element index is a ConstantExpr, o=
r if
+  /// 'this' is a constant expr.
+  Constant *getAggregateElement(unsigned Elt) const;
+  Constant *getAggregateElement(Constant *Elt) const;
+ =20
   /// destroyConstant - Called if some element of this constant is no long=
er
   /// valid.  At this point only other constants may be on the use_list fo=
r this
   /// constant.  Any constants on our Use list must also be destroy'd.  The
@@ -103,7 +105,7 @@
   /// available cached constants.  Implementations should call
   /// destroyConstantImpl as the last thing they do, to destroy all users =
and
   /// delete this.
-  virtual void destroyConstant() { assert(0 && "Not reached!"); }
+  virtual void destroyConstant() { llvm_unreachable("Not reached!"); }
=20
   //// Methods for support type inquiry through isa, cast, and dyn_cast:
   static inline bool classof(const Constant *) { return true; }
@@ -129,11 +131,12 @@
     // to be here to avoid link errors.
     assert(getNumOperands() =3D=3D 0 && "replaceUsesOfWithOnConstant must =
be "
            "implemented for all constants that have operands!");
-    assert(0 && "Constants that do not have operands cannot be using 'From=
'!");
+    llvm_unreachable("Constants that do not have operands cannot be using "
+                     "'From'!");
   }
- =20
+
   static Constant *getNullValue(Type* Ty);
- =20
+
   /// @returns the value for an integer constant of the given type that ha=
s all
   /// its bits set to true.
   /// @brief Get the all ones value
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Constan=
ts.h
--- a/head/contrib/llvm/include/llvm/Constants.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/include/llvm/Constants.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -34,10 +34,13 @@
 class StructType;
 class PointerType;
 class VectorType;
+class SequentialType;
=20
 template<class ConstantClass, class TypeClass, class ValType>
 struct ConstantCreator;
 template<class ConstantClass, class TypeClass>
+struct ConstantArrayCreator;
+template<class ConstantClass, class TypeClass>
 struct ConvertConstantType;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -45,6 +48,7 @@
 /// represents both boolean and integral constants.
 /// @brief Class for constant integers.
 class ConstantInt : public Constant {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
   ConstantInt(const ConstantInt &);      // DO NOT IMPLEMENT
   ConstantInt(IntegerType *Ty, const APInt& V);
@@ -229,6 +233,7 @@
 ///
 class ConstantFP : public Constant {
   APFloat Val;
+  virtual void anchor();
   void *operator new(size_t, unsigned);// DO NOT IMPLEMENT
   ConstantFP(const ConstantFP &);      // DO NOT IMPLEMENT
   friend class LLVMContextImpl;
@@ -296,7 +301,6 @@
 /// ConstantAggregateZero - All zero aggregate value
 ///
 class ConstantAggregateZero : public Constant {
-  friend struct ConstantCreator<ConstantAggregateZero, Type, char>;
   void *operator new(size_t, unsigned);                      // DO NOT IMP=
LEMENT
   ConstantAggregateZero(const ConstantAggregateZero &);      // DO NOT IMP=
LEMENT
 protected:
@@ -308,10 +312,26 @@
     return User::operator new(s, 0);
   }
 public:
-  static ConstantAggregateZero* get(Type *Ty);
+  static ConstantAggregateZero *get(Type *Ty);
  =20
   virtual void destroyConstant();
=20
+  /// getSequentialElement - If this CAZ has array or vector type, return =
a zero
+  /// with the right element type.
+  Constant *getSequentialElement() const;
+
+  /// getStructElement - If this CAZ has struct type, return a zero with t=
he
+  /// right element type for the specified element.
+  Constant *getStructElement(unsigned Elt) const;
+
+  /// getElementValue - Return a zero of the right value for the specified=
 GEP
+  /// index.
+  Constant *getElementValue(Constant *C) const;
+
+  /// getElementValue - Return a zero of the right value for the specified=
 GEP
+  /// index.
+  Constant *getElementValue(unsigned Idx) const;
+
   /// Methods for support type inquiry through isa, cast, and dyn_cast:
   ///
   static bool classof(const ConstantAggregateZero *) { return true; }
@@ -325,8 +345,7 @@
 /// ConstantArray - Constant Array Declarations
 ///
 class ConstantArray : public Constant {
-  friend struct ConstantCreator<ConstantArray, ArrayType,
-                                    std::vector<Constant*> >;
+  friend struct ConstantArrayCreator<ConstantArray, ArrayType>;
   ConstantArray(const ConstantArray &);      // DO NOT IMPLEMENT
 protected:
   ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
@@ -334,15 +353,6 @@
   // ConstantArray accessors
   static Constant *get(ArrayType *T, ArrayRef<Constant*> V);
                             =20
-  /// This method constructs a ConstantArray and initializes it with a text
-  /// string. The default behavior (AddNull=3D=3Dtrue) causes a null termi=
nator to
-  /// be placed at the end of the array. This effectively increases the le=
ngth
-  /// of the array by one (you've been warned).  However, in some situatio=
ns=20
-  /// this is not desired so if AddNull=3D=3Dfalse then the string is copi=
ed without
-  /// null termination.
-  static Constant *get(LLVMContext &Context, StringRef Initializer,
-                       bool AddNull =3D true);
- =20
   /// Transparently provide more efficient getOperand methods.
   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
=20
@@ -353,28 +363,6 @@
     return reinterpret_cast<ArrayType*>(Value::getType());
   }
=20
-  /// isString - This method returns true if the array is an array of i8 a=
nd
-  /// the elements of the array are all ConstantInt's.
-  bool isString() const;
-
-  /// isCString - This method returns true if the array is a string (see
-  /// @verbatim
-  /// isString) and it ends in a null byte \0 and does not contains any ot=
her
-  /// @endverbatim
-  /// null bytes except its terminator.
-  bool isCString() const;
-
-  /// getAsString - If this array is isString(), then this method converts=
 the
-  /// array to an std::string and returns it.  Otherwise, it asserts out.
-  ///
-  std::string getAsString() const;
-
-  /// getAsCString - If this array is isCString(), then this method conver=
ts the
-  /// array (without the trailing null byte) to an std::string and returns=
 it.
-  /// Otherwise, it asserts out.
-  ///
-  std::string getAsCString() const;
-
   virtual void destroyConstant();
   virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
=20
@@ -396,8 +384,7 @@
 // ConstantStruct - Constant Struct Declarations
 //
 class ConstantStruct : public Constant {
-  friend struct ConstantCreator<ConstantStruct, StructType,
-                                    std::vector<Constant*> >;
+  friend struct ConstantArrayCreator<ConstantStruct, StructType>;
   ConstantStruct(const ConstantStruct &);      // DO NOT IMPLEMENT
 protected:
   ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
@@ -457,8 +444,7 @@
 /// ConstantVector - Constant Vector Declarations
 ///
 class ConstantVector : public Constant {
-  friend struct ConstantCreator<ConstantVector, VectorType,
-                                    std::vector<Constant*> >;
+  friend struct ConstantArrayCreator<ConstantVector, VectorType>;
   ConstantVector(const ConstantVector &);      // DO NOT IMPLEMENT
 protected:
   ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
@@ -466,6 +452,10 @@
   // ConstantVector accessors
   static Constant *get(ArrayRef<Constant*> V);
  =20
+  /// getSplat - Return a ConstantVector with the specified constant in ea=
ch
+  /// element.
+  static Constant *getSplat(unsigned NumElts, Constant *Elt);
+ =20
   /// Transparently provide more efficient getOperand methods.
   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
=20
@@ -475,12 +465,6 @@
   inline VectorType *getType() const {
     return reinterpret_cast<VectorType*>(Value::getType());
   }
- =20
-  /// This function will return true iff every element in this vector cons=
tant
-  /// is set to all ones.
-  /// @returns true iff this constant's emements are all set to all ones.
-  /// @brief Determine if the value is all ones.
-  bool isAllOnesValue() const;
=20
   /// getSplatValue - If this is a splat constant, meaning that all of the
   /// elements have the same value, return that value. Otherwise return NU=
LL.
@@ -507,7 +491,6 @@
 /// ConstantPointerNull - a constant pointer value that points to null
 ///
 class ConstantPointerNull : public Constant {
-  friend struct ConstantCreator<ConstantPointerNull, PointerType, char>;
   void *operator new(size_t, unsigned);                  // DO NOT IMPLEME=
NT
   ConstantPointerNull(const ConstantPointerNull &);      // DO NOT IMPLEME=
NT
 protected:
@@ -539,6 +522,240 @@
     return V->getValueID() =3D=3D ConstantPointerNullVal;
   }
 };
+ =20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+/// ConstantDataSequential - A vector or array constant whose element type=
 is a
+/// simple 1/2/4/8-byte integer or float/double, and whose elements are ju=
st
+/// simple data values (i.e. ConstantInt/ConstantFP).  This Constant node =
has no
+/// operands because it stores all of the elements of the constant as dens=
ely
+/// packed data, instead of as Value*'s.
+///
+/// This is the common base class of ConstantDataArray and ConstantDataVec=
tor.
+///
+class ConstantDataSequential : public Constant {
+  friend class LLVMContextImpl;
+  /// DataElements - A pointer to the bytes underlying this constant (whic=
h is
+  /// owned by the uniquing StringMap).
+  const char *DataElements;
+ =20
+  /// Next - This forms a link list of ConstantDataSequential nodes that h=
ave
+  /// the same value but different type.  For example, 0,0,0,1 could be a 4
+  /// element array of i8, or a 1-element array of i32.  They'll both end =
up in
+  /// the same StringMap bucket, linked up.
+  ConstantDataSequential *Next;
+  void *operator new(size_t, unsigned);                      // DO NOT IMP=
LEMENT
+  ConstantDataSequential(const ConstantDataSequential &);    // DO NOT IMP=
LEMENT
+protected:
+  explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
+    : Constant(ty, VT, 0, 0), DataElements(Data), Next(0) {}
+  ~ConstantDataSequential() { delete Next; }
+ =20
+  static Constant *getImpl(StringRef Bytes, Type *Ty);
+
+protected:
+  // allocate space for exactly zero operands.
+  void *operator new(size_t s) {
+    return User::operator new(s, 0);
+  }
+public:
+ =20
+  /// isElementTypeCompatible - Return true if a ConstantDataSequential ca=
n be
+  /// formed with a vector or array of the specified element type.
+  /// ConstantDataArray only works with normal float and int types that are
+  /// stored densely in memory, not with things like i42 or x86_f80.
+  static bool isElementTypeCompatible(const Type *Ty);
+ =20
+  /// getElementAsInteger - If this is a sequential container of integers =
(of
+  /// any size), return the specified element in the low bits of a uint64_=
t.
+  uint64_t getElementAsInteger(unsigned i) const;
+
+  /// getElementAsAPFloat - If this is a sequential container of floating =
point
+  /// type, return the specified element as an APFloat.
+  APFloat getElementAsAPFloat(unsigned i) const;
+
+  /// getElementAsFloat - If this is an sequential container of floats, re=
turn
+  /// the specified element as a float.
+  float getElementAsFloat(unsigned i) const;
+ =20
+  /// getElementAsDouble - If this is an sequential container of doubles, =
return
+  /// the specified element as a double.
+  double getElementAsDouble(unsigned i) const;
+ =20
+  /// getElementAsConstant - Return a Constant for a specified index's ele=
ment.
+  /// Note that this has to compute a new constant to return, so it isn't =
as
+  /// efficient as getElementAsInteger/Float/Double.
+  Constant *getElementAsConstant(unsigned i) const;
+ =20
+  /// getType - Specialize the getType() method to always return a
+  /// SequentialType, which reduces the amount of casting needed in parts =
of the
+  /// compiler.
+  inline SequentialType *getType() const {
+    return reinterpret_cast<SequentialType*>(Value::getType());
+  }
+ =20
+  /// getElementType - Return the element type of the array/vector.
+  Type *getElementType() const;
+ =20
+  /// getNumElements - Return the number of elements in the array or vecto=
r.
+  unsigned getNumElements() const;
+
+  /// getElementByteSize - Return the size (in bytes) of each element in t=
he
+  /// array/vector.  The size of the elements is known to be a multiple of=
 one
+  /// byte.
+  uint64_t getElementByteSize() const;
+
+ =20
+  /// isString - This method returns true if this is an array of i8.
+  bool isString() const;
+ =20
+  /// isCString - This method returns true if the array "isString", ends w=
ith a
+  /// nul byte, and does not contains any other nul bytes.
+  bool isCString() const;
+ =20
+  /// getAsString - If this array is isString(), then this method returns =
the
+  /// array as a StringRef.  Otherwise, it asserts out.
+  ///
+  StringRef getAsString() const {
+    assert(isString() && "Not a string");
+    return getRawDataValues();
+  }
+ =20
+  /// getAsCString - If this array is isCString(), then this method return=
s the
+  /// array (without the trailing null byte) as a StringRef. Otherwise, it
+  /// asserts out.
+  ///
+  StringRef getAsCString() const {
+    assert(isCString() && "Isn't a C string");
+    StringRef Str =3D getAsString();
+    return Str.substr(0, Str.size()-1);
+  }
+ =20
+  /// getRawDataValues - Return the raw, underlying, bytes of this data.  =
Note
+  /// that this is an extremely tricky thing to work with, as it exposes t=
he
+  /// host endianness of the data elements.
+  StringRef getRawDataValues() const;
+ =20
+  virtual void destroyConstant();
+ =20
+  /// Methods for support type inquiry through isa, cast, and dyn_cast:
+  ///
+  static bool classof(const ConstantDataSequential *) { return true; }
+  static bool classof(const Value *V) {
+    return V->getValueID() =3D=3D ConstantDataArrayVal ||
+           V->getValueID() =3D=3D ConstantDataVectorVal;
+  }
+private:
+  const char *getElementPointer(unsigned Elt) const;
+};
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+/// ConstantDataArray - An array constant whose element type is a simple
+/// 1/2/4/8-byte integer or float/double, and whose elements are just simp=
le
+/// data values (i.e. ConstantInt/ConstantFP).  This Constant node has no
+/// operands because it stores all of the elements of the constant as dens=
ely
+/// packed data, instead of as Value*'s.
+class ConstantDataArray : public ConstantDataSequential {
+  void *operator new(size_t, unsigned);            // DO NOT IMPLEMENT
+  ConstantDataArray(const ConstantDataArray &);    // DO NOT IMPLEMENT
+  virtual void anchor();
+  friend class ConstantDataSequential;
+  explicit ConstantDataArray(Type *ty, const char *Data)
+    : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
+protected:
+  // allocate space for exactly zero operands.
+  void *operator new(size_t s) {
+    return User::operator new(s, 0);
+  }
+public:
+ =20
+  /// get() constructors - Return a constant with array type with an eleme=
nt
+  /// count and element type matching the ArrayRef passed in.  Note that t=
his
+  /// can return a ConstantAggregateZero object.
+  static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
+ =20
+  /// getString - This method constructs a CDS and initializes it with a t=
ext
+  /// string. The default behavior (AddNull=3D=3Dtrue) causes a null termi=
nator to
+  /// be placed at the end of the array (increasing the length of the stri=
ng by
+  /// one more than the StringRef would normally indicate.  Pass AddNull=
=3Dfalse
+  /// to disable this behavior.
+  static Constant *getString(LLVMContext &Context, StringRef Initializer,
+                             bool AddNull =3D true);
+
+  /// getType - Specialize the getType() method to always return an ArrayT=
ype,
+  /// which reduces the amount of casting needed in parts of the compiler.
+  ///
+  inline ArrayType *getType() const {
+    return reinterpret_cast<ArrayType*>(Value::getType());
+  }
+ =20
+  /// Methods for support type inquiry through isa, cast, and dyn_cast:
+  ///
+  static bool classof(const ConstantDataArray *) { return true; }
+  static bool classof(const Value *V) {
+    return V->getValueID() =3D=3D ConstantDataArrayVal;
+  }
+};
+ =20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+/// ConstantDataVector - A vector constant whose element type is a simple
+/// 1/2/4/8-byte integer or float/double, and whose elements are just simp=
le
+/// data values (i.e. ConstantInt/ConstantFP).  This Constant node has no
+/// operands because it stores all of the elements of the constant as dens=
ely
+/// packed data, instead of as Value*'s.
+class ConstantDataVector : public ConstantDataSequential {
+  void *operator new(size_t, unsigned);              // DO NOT IMPLEMENT
+  ConstantDataVector(const ConstantDataVector &);    // DO NOT IMPLEMENT
+  virtual void anchor();
+  friend class ConstantDataSequential;
+  explicit ConstantDataVector(Type *ty, const char *Data)
+  : ConstantDataSequential(ty, ConstantDataVectorVal, Data) {}
+protected:
+  // allocate space for exactly zero operands.
+  void *operator new(size_t s) {
+    return User::operator new(s, 0);
+  }
+public:
+ =20
+  /// get() constructors - Return a constant with vector type with an elem=
ent
+  /// count and element type matching the ArrayRef passed in.  Note that t=
his
+  /// can return a ConstantAggregateZero object.
+  static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
+  static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
+ =20
+  /// getSplat - Return a ConstantVector with the specified constant in ea=
ch
+  /// element.  The specified constant has to be a of a compatible type (i=
8/i16/
+  /// i32/i64/float/double) and must be a ConstantFP or ConstantInt.
+  static Constant *getSplat(unsigned NumElts, Constant *Elt);
+
+  /// getSplatValue - If this is a splat constant, meaning that all of the
+  /// elements have the same value, return that value. Otherwise return NU=
LL.
+  Constant *getSplatValue() const;
+ =20
+  /// getType - Specialize the getType() method to always return a VectorT=
ype,
+  /// which reduces the amount of casting needed in parts of the compiler.
+  ///
+  inline VectorType *getType() const {
+    return reinterpret_cast<VectorType*>(Value::getType());
+  }
+ =20
+  /// Methods for support type inquiry through isa, cast, and dyn_cast:
+  ///
+  static bool classof(const ConstantDataVector *) { return true; }
+  static bool classof(const Value *V) {
+    return V->getValueID() =3D=3D ConstantDataVectorVal;
+  }
+};
+
+
=20
 /// BlockAddress - The address of a basic block.
 ///
@@ -897,7 +1114,6 @@
 /// LangRef.html#undefvalues for details.
 ///
 class UndefValue : public Constant {
-  friend struct ConstantCreator<UndefValue, Type, char>;
   void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
   UndefValue(const UndefValue &);      // DO NOT IMPLEMENT
 protected:
@@ -913,6 +1129,22 @@
   ///
   static UndefValue *get(Type *T);
=20
+  /// getSequentialElement - If this Undef has array or vector type, retur=
n a
+  /// undef with the right element type.
+  UndefValue *getSequentialElement() const;
+ =20
+  /// getStructElement - If this undef has struct type, return a undef wit=
h the
+  /// right element type for the specified element.
+  UndefValue *getStructElement(unsigned Elt) const;
+ =20
+  /// getElementValue - Return an undef of the right value for the specifi=
ed GEP
+  /// index.
+  UndefValue *getElementValue(Constant *C) const;
+
+  /// getElementValue - Return an undef of the right value for the specifi=
ed GEP
+  /// index.
+  UndefValue *getElementValue(unsigned Idx) const;
+
   virtual void destroyConstant();
=20
   /// Methods for support type inquiry through isa, cast, and dyn_cast:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Default=
Passes.h
--- a/head/contrib/llvm/include/llvm/DefaultPasses.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/DefaultPasses.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,6 +14,8 @@
 #ifndef LLVM_DEFAULT_PASS_SUPPORT_H
 #define LLVM_DEFAULT_PASS_SUPPORT_H
=20
+#include <llvm/PassSupport.h>
+
 namespace llvm {
=20
 class PassManagerBase;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Derived=
Types.h
--- a/head/contrib/llvm/include/llvm/DerivedTypes.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/DerivedTypes.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -195,9 +195,10 @@
     // This is the contents of the SubClassData field.
     SCDB_HasBody =3D 1,
     SCDB_Packed =3D 2,
-    SCDB_IsLiteral =3D 4
+    SCDB_IsLiteral =3D 4,
+    SCDB_IsSized =3D 8
   };
- =20
+
   /// SymbolTableEntry - For a named struct that actually has a name, this=
 is a
   /// pointer to the symbol table entry (maintained by LLVMContext) for the
   /// struct.  This is null if the type is an literal struct or if it is
@@ -248,6 +249,9 @@
   /// isOpaque - Return true if this is a type with an identity that has n=
o body
   /// specified yet.  These prints as 'opaque' in .ll files.
   bool isOpaque() const { return (getSubclassData() & SCDB_HasBody) =3D=3D=
 0; }
+
+  /// isSized - Return true if this is a sized type.
+  bool isSized() const;
  =20
   /// hasName - Return true if this is a named struct that has a non-empty=
 name.
   bool hasName() const { return SymbolTableEntry !=3D 0; }
@@ -374,6 +378,7 @@
   ///
   static VectorType *getInteger(VectorType *VTy) {
     unsigned EltBits =3D VTy->getElementType()->getPrimitiveSizeInBits();
+    assert(EltBits && "Element size must be of a non-zero size");
     Type *EltTy =3D IntegerType::get(VTy->getContext(), EltBits);
     return VectorType::get(EltTy, VTy->getNumElements());
   }
@@ -408,6 +413,7 @@
   unsigned getNumElements() const { return NumElements; }
=20
   /// @brief Return the number of bits in the Vector type.
+  /// Returns zero when the vector is a vector of pointers.
   unsigned getBitWidth() const {
     return NumElements * getElementType()->getPrimitiveSizeInBits();
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Executi=
onEngine/ExecutionEngine.h
--- a/head/contrib/llvm/include/llvm/ExecutionEngine/ExecutionEngine.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ExecutionEngine/ExecutionEngine.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -15,17 +15,19 @@
 #ifndef LLVM_EXECUTION_ENGINE_H
 #define LLVM_EXECUTION_ENGINE_H
=20
-#include <vector>
-#include <map>
-#include <string>
 #include "llvm/MC/MCCodeGenInfo.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/ValueMap.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/ValueHandle.h"
 #include "llvm/Support/Mutex.h"
 #include "llvm/Target/TargetMachine.h"
+#include "llvm/Target/TargetOptions.h"
+#include <vector>
+#include <map>
+#include <string>
=20
 namespace llvm {
=20
@@ -41,6 +43,7 @@
 class Module;
 class MutexGuard;
 class TargetData;
+class Triple;
 class Type;
=20
 /// \brief Helper class for helping synchronize access to the global addre=
ss map
@@ -132,14 +135,12 @@
     Module *M,
     std::string *ErrorStr,
     JITMemoryManager *JMM,
-    CodeGenOpt::Level OptLevel,
     bool GVsWithCode,
     TargetMachine *TM);
   static ExecutionEngine *(*MCJITCtor)(
     Module *M,
     std::string *ErrorStr,
     JITMemoryManager *JMM,
-    CodeGenOpt::Level OptLevel,
     bool GVsWithCode,
     TargetMachine *TM);
   static ExecutionEngine *(*InterpCtor)(Module *M, std::string *ErrorStr);
@@ -228,6 +229,26 @@
   virtual GenericValue runFunction(Function *F,
                                 const std::vector<GenericValue> &ArgValues=
) =3D 0;
=20
+  /// getPointerToNamedFunction - This method returns the address of the
+  /// specified function by using the dlsym function call.  As such it is =
only
+  /// useful for resolving library symbols, not code generated symbols.
+  ///
+  /// If AbortOnFailure is false and no function with the given name is
+  /// found, this function silently returns a null pointer. Otherwise,
+  /// it prints a message to stderr and aborts.
+  ///
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true) =
=3D 0;
+
+  /// mapSectionAddress - map a section to its target address space value.
+  /// Map the address of a JIT section as returned from the memory manager
+  /// to the address in the target process as the running code will see it.
+  /// This is the address which will be used for relocation resolution.
+  virtual void mapSectionAddress(void *LocalAddress, uint64_t TargetAddres=
s) {
+    llvm_unreachable("Re-mapping of section addresses not supported with t=
his "
+                     "EE!");
+  }
+
   /// runStaticConstructorsDestructors - This method is used to execute al=
l of
   /// the static constructors or destructors for a program.
   ///
@@ -462,6 +483,7 @@
   CodeGenOpt::Level OptLevel;
   JITMemoryManager *JMM;
   bool AllocateGVsWithCode;
+  TargetOptions Options;
   Reloc::Model RelocModel;
   CodeModel::Model CMModel;
   std::string MArch;
@@ -475,6 +497,7 @@
     ErrorStr =3D NULL;
     OptLevel =3D CodeGenOpt::Default;
     JMM =3D NULL;
+    Options =3D TargetOptions();
     AllocateGVsWithCode =3D false;
     RelocModel =3D Reloc::Default;
     CMModel =3D CodeModel::JITDefault;
@@ -518,6 +541,13 @@
     return *this;
   }
=20
+  /// setTargetOptions - Set the target options that the ExecutionEngine
+  /// target is using. Defaults to TargetOptions().
+  EngineBuilder &setTargetOptions(const TargetOptions &Opts) {
+    Options =3D Opts;
+    return *this;
+  }
+
   /// setRelocationModel - Set the relocation model that the ExecutionEngi=
ne
   /// target is using. Defaults to target specific default "Reloc::Default=
".
   EngineBuilder &setRelocationModel(Reloc::Model RM) {
@@ -572,17 +602,20 @@
     return *this;
   }
=20
+  TargetMachine *selectTarget();
+
   /// selectTarget - Pick a target either via -march or by guessing the na=
tive
   /// arch.  Add any CPU features specified via -mcpu or -mattr.
-  static TargetMachine *selectTarget(Module *M,
-                                     StringRef MArch,
-                                     StringRef MCPU,
-                                     const SmallVectorImpl<std::string>& M=
Attrs,
-                                     Reloc::Model RM,
-                                     CodeModel::Model CM,
-                                     std::string *Err);
+  TargetMachine *selectTarget(const Triple &TargetTriple,
+                              StringRef MArch,
+                              StringRef MCPU,
+                              const SmallVectorImpl<std::string>& MAttrs);
=20
-  ExecutionEngine *create();
+  ExecutionEngine *create() {
+    return create(selectTarget());
+  }
+
+  ExecutionEngine *create(TargetMachine *TM);
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Executi=
onEngine/JITEventListener.h
--- a/head/contrib/llvm/include/llvm/ExecutionEngine/JITEventListener.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ExecutionEngine/JITEventListener.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #ifndef LLVM_EXECUTION_ENGINE_JIT_EVENTLISTENER_H
 #define LLVM_EXECUTION_ENGINE_JIT_EVENTLISTENER_H
=20
+#include "llvm/Config/config.h"
 #include "llvm/Support/DataTypes.h"
 #include "llvm/Support/DebugLoc.h"
=20
@@ -23,6 +24,8 @@
 namespace llvm {
 class Function;
 class MachineFunction;
+class OProfileWrapper;
+class IntelJITEventsWrapper;
=20
 /// JITEvent_EmittedFunctionDetails - Helper struct for containing informa=
tion
 /// about a generated machine code function.
@@ -59,9 +62,9 @@
   /// NotifyFunctionEmitted - Called after a function has been successfully
   /// emitted to memory.  The function still has its MachineFunction attac=
hed,
   /// if you should happen to need that.
-  virtual void NotifyFunctionEmitted(const Function &F,
-                                     void *Code, size_t Size,
-                                     const EmittedFunctionDetails &Details=
) {}
+  virtual void NotifyFunctionEmitted(const Function &,
+                                     void *, size_t,
+                                     const EmittedFunctionDetails &) {}
=20
   /// NotifyFreeingMachineCode - Called from freeMachineCodeForFunction(),=
 after
   /// the global mapping is removed, but before the machine code is return=
ed to
@@ -71,12 +74,43 @@
   /// parameter to a previous NotifyFunctionEmitted call.  The Function pa=
ssed
   /// to NotifyFunctionEmitted may have been destroyed by the time of the
   /// matching NotifyFreeingMachineCode call.
-  virtual void NotifyFreeingMachineCode(void *OldPtr) {}
+  virtual void NotifyFreeingMachineCode(void *) {}
+
+#if LLVM_USE_INTEL_JITEVENTS
+  // Construct an IntelJITEventListener
+  static JITEventListener *createIntelJITEventListener();
+
+  // Construct an IntelJITEventListener with a test Intel JIT API implemen=
tation
+  static JITEventListener *createIntelJITEventListener(
+                                      IntelJITEventsWrapper* AlternativeIm=
pl);
+#else
+  static JITEventListener *createIntelJITEventListener() { return 0; }
+
+  static JITEventListener *createIntelJITEventListener(
+                                      IntelJITEventsWrapper* AlternativeIm=
pl) {
+    return 0;
+  }
+#endif // USE_INTEL_JITEVENTS
+
+#if LLVM_USE_OPROFILE
+  // Construct an OProfileJITEventListener
+  static JITEventListener *createOProfileJITEventListener();
+
+  // Construct an OProfileJITEventListener with a test opagent implementat=
ion
+  static JITEventListener *createOProfileJITEventListener(
+                                      OProfileWrapper* AlternativeImpl);
+#else
+
+  static JITEventListener *createOProfileJITEventListener() { return 0; }
+
+  static JITEventListener *createOProfileJITEventListener(
+                                      OProfileWrapper* AlternativeImpl) {
+    return 0;
+  }
+#endif // USE_OPROFILE
+
 };
=20
-// This returns NULL if support isn't available.
-JITEventListener *createOProfileJITEventListener();
-
 } // end namespace llvm.
=20
-#endif
+#endif // defined LLVM_EXECUTION_ENGINE_JIT_EVENTLISTENER_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Executi=
onEngine/JITMemoryManager.h
--- a/head/contrib/llvm/include/llvm/ExecutionEngine/JITMemoryManager.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ExecutionEngine/JITMemoryManager.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -47,6 +47,17 @@
   /// debugging, and may be turned on by default in debug mode.
   virtual void setPoisonMemory(bool poison) =3D 0;
=20
+  /// getPointerToNamedFunction - This method returns the address of the
+  /// specified function. As such it is only useful for resolving library
+  /// symbols, not code generated symbols.
+  ///
+  /// If AbortOnFailure is false and no function with the given name is
+  /// found, this function silently returns a null pointer. Otherwise,
+  /// it prints a message to stderr and aborts.
+  ///
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true) =
=3D 0;
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Global Offset Table Management
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
@@ -101,6 +112,22 @@
   virtual void endFunctionBody(const Function *F, uint8_t *FunctionStart,
                                uint8_t *FunctionEnd) =3D 0;
=20
+  /// allocateCodeSection - Allocate a memory block of (at least) the given
+  /// size suitable for executable code. The SectionID is a unique identif=
ier
+  /// assigned by the JIT and passed through to the memory manager for
+  /// the instance class to use if it needs to communicate to the JIT about
+  /// a given section after the fact.
+  virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+                                       unsigned SectionID) =3D 0;
+
+  /// allocateDataSection - Allocate a memory block of (at least) the given
+  /// size suitable for data. The SectionID is a unique identifier
+  /// assigned by the JIT and passed through to the memory manager for
+  /// the instance class to use if it needs to communicate to the JIT about
+  /// a given section after the fact.
+  virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+                                       unsigned SectionID) =3D 0;
+
   /// allocateSpace - Allocate a memory block of the given size.  This met=
hod
   /// cannot be called between calls to startFunctionBody and endFunctionB=
ody.
   virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment) =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Executi=
onEngine/RuntimeDyld.h
--- a/head/contrib/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/ExecutionEngine/RuntimeDyld.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -35,15 +35,18 @@
   RTDyldMemoryManager() {}
   virtual ~RTDyldMemoryManager();
=20
-  // Allocate ActualSize bytes, or more, for the named function. Return
-  // a pointer to the allocated memory and update Size to reflect how much
-  // memory was acutally allocated.
-  virtual uint8_t *startFunctionBody(const char *Name, uintptr_t &Size) =
=3D 0;
+  /// allocateCodeSection - Allocate a memory block of (at least) the given
+  /// size suitable for executable code.
+  virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+                                       unsigned SectionID) =3D 0;
=20
-  // Mark the end of the function, including how much of the allocated
-  // memory was actually used.
-  virtual void endFunctionBody(const char *Name, uint8_t *FunctionStart,
-                               uint8_t *FunctionEnd) =3D 0;
+  /// allocateDataSection - Allocate a memory block of (at least) the given
+  /// size suitable for data.
+  virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+                                       unsigned SectionID) =3D 0;
+
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true) =
=3D 0;
 };
=20
 class RuntimeDyld {
@@ -54,6 +57,10 @@
   // interface.
   RuntimeDyldImpl *Dyld;
   RTDyldMemoryManager *MM;
+protected:
+  // Change the address associated with a section when resolving relocatio=
ns.
+  // Any relocations already associated with the symbol will be re-resolve=
d.
+  void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
 public:
   RuntimeDyld(RTDyldMemoryManager*);
   ~RuntimeDyld();
@@ -65,9 +72,13 @@
   void *getSymbolAddress(StringRef Name);
   // Resolve the relocations for all symbols we currently know about.
   void resolveRelocations();
-  // Change the address associated with a symbol when resolving relocation=
s.
-  // Any relocations already associated with the symbol will be re-resolve=
d.
-  void reassignSymbolAddress(StringRef Name, uint8_t *Addr);
+
+  /// mapSectionAddress - map a section to its target address space value.
+  /// Map the address of a JIT section as returned from the memory manager
+  /// to the address in the target process as the running code will see it.
+  /// This is the address which will be used for relocation resolution.
+  void mapSectionAddress(void *LocalAddress, uint64_t TargetAddress);
+
   StringRef getErrorString();
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Functio=
n.h
--- a/head/contrib/llvm/include/llvm/Function.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm/Function.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -146,7 +146,7 @@
   /// The particular intrinsic functions which correspond to this value are
   /// defined in llvm/Intrinsics.h.
   ///
-  unsigned getIntrinsicID() const LLVM_ATTRIBUTE_READONLY;
+  unsigned getIntrinsicID() const LLVM_READONLY;
   bool isIntrinsic() const { return getIntrinsicID() !=3D 0; }
=20
   /// getCallingConv()/setCallingConv(CC) - These method get and set the
@@ -425,6 +425,12 @@
   ///
   bool hasAddressTaken(const User** =3D 0) const;
=20
+  /// isDefTriviallyDead - Return true if it is trivially safe to remove
+  /// this function definition from the module (because it isn't externally
+  /// visible, does not have its address taken, and has no callers).  To m=
ake
+  /// this more accurate, call removeDeadConstantUsers first.
+  bool isDefTriviallyDead() const;
+
   /// callsFunctionThatReturnsTwice - Return true if the function has a ca=
ll to
   /// setjmp or other function that gcc recognizes as "returning twice".
   bool callsFunctionThatReturnsTwice() const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/GlobalV=
alue.h
--- a/head/contrib/llvm/include/llvm/GlobalValue.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/GlobalValue.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -59,19 +59,18 @@
 protected:
   GlobalValue(Type *ty, ValueTy vty, Use *Ops, unsigned NumOps,
               LinkageTypes linkage, const Twine &Name)
-    : Constant(ty, vty, Ops, NumOps), Parent(0),
-      Linkage(linkage), Visibility(DefaultVisibility), Alignment(0),
-      UnnamedAddr(0) {
+    : Constant(ty, vty, Ops, NumOps), Linkage(linkage),
+      Visibility(DefaultVisibility), Alignment(0), UnnamedAddr(0), Parent(=
0) {
     setName(Name);
   }
=20
-  Module *Parent;
   // Note: VC++ treats enums as signed, so an extra bit is required to pre=
vent
   // Linkage and Visibility from turning into negative values.
   LinkageTypes Linkage : 5;   // The linkage of this global
   unsigned Visibility : 2;    // The visibility style of this global
   unsigned Alignment : 16;    // Alignment of this symbol, must be power o=
f two
   unsigned UnnamedAddr : 1;   // This value's address is not significant
+  Module *Parent;             // The containing module.
   std::string Section;        // Section to emit this into, empty mean def=
ault
 public:
   ~GlobalValue() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Initial=
izePasses.h
--- a/head/contrib/llvm/include/llvm/InitializePasses.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/InitializePasses.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -31,6 +31,10 @@
 /// ScalarOpts library.
 void initializeScalarOpts(PassRegistry&);
=20
+/// initializeVectorization - Initialize all passes linked into the
+/// Vectorize library.
+void initializeVectorization(PassRegistry&);
+
 /// initializeInstCombine - Initialize all passes linked into the
 /// ScalarOpts library.
 void initializeInstCombine(PassRegistry&);
@@ -67,6 +71,7 @@
 void initializeBlockExtractorPassPass(PassRegistry&);
 void initializeBlockFrequencyInfoPass(PassRegistry&);
 void initializeBlockPlacementPass(PassRegistry&);
+void initializeBranchFolderPassPass(PassRegistry&);
 void initializeBranchProbabilityInfoPass(PassRegistry&);
 void initializeBreakCriticalEdgesPass(PassRegistry&);
 void initializeCFGOnlyPrinterPass(PassRegistry&);
@@ -77,8 +82,10 @@
 void initializeCalculateSpillWeightsPass(PassRegistry&);
 void initializeCallGraphAnalysisGroup(PassRegistry&);
 void initializeCodeGenPreparePass(PassRegistry&);
+void initializeCodePlacementOptPass(PassRegistry&);
 void initializeConstantMergePass(PassRegistry&);
 void initializeConstantPropagationPass(PassRegistry&);
+void initializeMachineCopyPropagationPass(PassRegistry&);
 void initializeCorrelatedValuePropagationPass(PassRegistry&);
 void initializeDAEPass(PassRegistry&);
 void initializeDAHPass(PassRegistry&);
@@ -94,12 +101,17 @@
 void initializeDominatorTreePass(PassRegistry&);
 void initializeEdgeBundlesPass(PassRegistry&);
 void initializeEdgeProfilerPass(PassRegistry&);
+void initializeExpandPostRAPass(PassRegistry&);
 void initializePathProfilerPass(PassRegistry&);
 void initializeGCOVProfilerPass(PassRegistry&);
+void initializeAddressSanitizerPass(PassRegistry&);
+void initializeThreadSanitizerPass(PassRegistry&);
 void initializeEarlyCSEPass(PassRegistry&);
 void initializeExpandISelPseudosPass(PassRegistry&);
 void initializeFindUsedTypesPass(PassRegistry&);
 void initializeFunctionAttrsPass(PassRegistry&);
+void initializeGCInfoDeleterPass(PassRegistry&);
+void initializeGCMachineCodeAnalysisPass(PassRegistry&);
 void initializeGCModuleInfoPass(PassRegistry&);
 void initializeGVNPass(PassRegistry&);
 void initializeGlobalDCEPass(PassRegistry&);
@@ -127,6 +139,7 @@
 void initializeLiveVariablesPass(PassRegistry&);
 void initializeLoaderPassPass(PassRegistry&);
 void initializePathProfileLoaderPassPass(PassRegistry&);
+void initializeLocalStackSlotPassPass(PassRegistry&);
 void initializeLoopDeletionPass(PassRegistry&);
 void initializeLoopDependenceAnalysisPass(PassRegistry&);
 void initializeLoopExtractorPass(PassRegistry&);
@@ -134,8 +147,8 @@
 void initializeLoopInstSimplifyPass(PassRegistry&);
 void initializeLoopRotatePass(PassRegistry&);
 void initializeLoopSimplifyPass(PassRegistry&);
-void initializeLoopSplitterPass(PassRegistry&);
 void initializeLoopStrengthReducePass(PassRegistry&);
+void initializeGlobalMergePass(PassRegistry&);
 void initializeLoopUnrollPass(PassRegistry&);
 void initializeLoopUnswitchPass(PassRegistry&);
 void initializeLoopIdiomRecognizePass(PassRegistry&);
@@ -145,6 +158,8 @@
 void initializeLowerInvokePass(PassRegistry&);
 void initializeLowerSwitchPass(PassRegistry&);
 void initializeMachineBlockFrequencyInfoPass(PassRegistry&);
+void initializeMachineBlockPlacementPass(PassRegistry&);
+void initializeMachineBlockPlacementStatsPass(PassRegistry&);
 void initializeMachineBranchProbabilityInfoPass(PassRegistry&);
 void initializeMachineCSEPass(PassRegistry&);
 void initializeMachineDominatorTreePass(PassRegistry&);
@@ -152,6 +167,7 @@
 void initializeMachineLoopInfoPass(PassRegistry&);
 void initializeMachineLoopRangesPass(PassRegistry&);
 void initializeMachineModuleInfoPass(PassRegistry&);
+void initializeMachineSchedulerPass(PassRegistry&);
 void initializeMachineSinkingPass(PassRegistry&);
 void initializeMachineVerifierPassPass(PassRegistry&);
 void initializeMemCpyOptPass(PassRegistry&);
@@ -163,6 +179,7 @@
 void initializeNoProfileInfoPass(PassRegistry&);
 void initializeNoPathProfileInfoPass(PassRegistry&);
 void initializeObjCARCAliasAnalysisPass(PassRegistry&);
+void initializeObjCARCAPElimPass(PassRegistry&);
 void initializeObjCARCExpandPass(PassRegistry&);
 void initializeObjCARCContractPass(PassRegistry&);
 void initializeObjCARCOptPass(PassRegistry&);
@@ -177,6 +194,7 @@
 void initializePostDomPrinterPass(PassRegistry&);
 void initializePostDomViewerPass(PassRegistry&);
 void initializePostDominatorTreePass(PassRegistry&);
+void initializePostRASchedulerPass(PassRegistry&);
 void initializePreVerifierPass(PassRegistry&);
 void initializePrintDbgInfoPass(PassRegistry&);
 void initializePrintFunctionPassPass(PassRegistry&);
@@ -189,7 +207,6 @@
 void initializeProfileVerifierPassPass(PassRegistry&);
 void initializePromotePassPass(PassRegistry&);
 void initializePruneEHPass(PassRegistry&);
-void initializeRALinScanPass(PassRegistry&);
 void initializeReassociatePass(PassRegistry&);
 void initializeRegToMemPass(PassRegistry&);
 void initializeRegionInfoPass(PassRegistry&);
@@ -219,6 +236,8 @@
 void initializeStripSymbolsPass(PassRegistry&);
 void initializeStrongPHIEliminationPass(PassRegistry&);
 void initializeTailCallElimPass(PassRegistry&);
+void initializeTailDuplicatePassPass(PassRegistry&);
+void initializeTargetPassConfigPass(PassRegistry&);
 void initializeTargetDataPass(PassRegistry&);
 void initializeTargetLibraryInfoPass(PassRegistry&);
 void initializeTwoAddressInstructionPassPass(PassRegistry&);
@@ -229,7 +248,9 @@
 void initializeVerifierPass(PassRegistry&);
 void initializeVirtRegMapPass(PassRegistry&);
 void initializeInstSimplifierPass(PassRegistry&);
-
+void initializeUnpackMachineBundlesPass(PassRegistry&);
+void initializeFinalizeMachineBundlesPass(PassRegistry&);
+void initializeBBVectorizePass(PassRegistry&);
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/InlineA=
sm.h
--- a/head/contrib/llvm/include/llvm/InlineAsm.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/include/llvm/InlineAsm.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -17,6 +17,7 @@
 #define LLVM_INLINEASM_H
=20
 #include "llvm/Value.h"
+#include "llvm/ADT/StringRef.h"
 #include <vector>
=20
 namespace llvm {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/InstrTy=
pes.h
--- a/head/contrib/llvm/include/llvm/InstrTypes.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/include/llvm/InstrTypes.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -388,6 +388,7 @@
 /// if (isa<CastInst>(Instr)) { ... }
 /// @brief Base class of casting instructions.
 class CastInst : public UnaryInstruction {
+  virtual void anchor();
 protected:
   /// @brief Constructor with insert-before-instruction semantics for subc=
lasses
   CastInst(Type *Ty, unsigned iType, Value *S,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Instruc=
tion.def
--- a/head/contrib/llvm/include/llvm/Instruction.def	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/Instruction.def	Tue Apr 17 11:51:51 20=
12 +0300
@@ -99,81 +99,80 @@
 HANDLE_TERM_INST  ( 3, Switch     , SwitchInst)
 HANDLE_TERM_INST  ( 4, IndirectBr , IndirectBrInst)
 HANDLE_TERM_INST  ( 5, Invoke     , InvokeInst)
-HANDLE_TERM_INST  ( 6, Unwind     , UnwindInst)
-HANDLE_TERM_INST  ( 7, Resume     , ResumeInst)
-HANDLE_TERM_INST  ( 8, Unreachable, UnreachableInst)
-  LAST_TERM_INST  ( 8)
+HANDLE_TERM_INST  ( 6, Resume     , ResumeInst)
+HANDLE_TERM_INST  ( 7, Unreachable, UnreachableInst)
+  LAST_TERM_INST  ( 7)
=20
 // Standard binary operators...
- FIRST_BINARY_INST( 9)
-HANDLE_BINARY_INST( 9, Add  , BinaryOperator)
-HANDLE_BINARY_INST(10, FAdd , BinaryOperator)
-HANDLE_BINARY_INST(11, Sub  , BinaryOperator)
-HANDLE_BINARY_INST(12, FSub , BinaryOperator)
-HANDLE_BINARY_INST(13, Mul  , BinaryOperator)
-HANDLE_BINARY_INST(14, FMul , BinaryOperator)
-HANDLE_BINARY_INST(15, UDiv , BinaryOperator)
-HANDLE_BINARY_INST(16, SDiv , BinaryOperator)
-HANDLE_BINARY_INST(17, FDiv , BinaryOperator)
-HANDLE_BINARY_INST(18, URem , BinaryOperator)
-HANDLE_BINARY_INST(19, SRem , BinaryOperator)
-HANDLE_BINARY_INST(20, FRem , BinaryOperator)
+ FIRST_BINARY_INST( 8)
+HANDLE_BINARY_INST( 8, Add  , BinaryOperator)
+HANDLE_BINARY_INST( 9, FAdd , BinaryOperator)
+HANDLE_BINARY_INST(10, Sub  , BinaryOperator)
+HANDLE_BINARY_INST(11, FSub , BinaryOperator)
+HANDLE_BINARY_INST(12, Mul  , BinaryOperator)
+HANDLE_BINARY_INST(13, FMul , BinaryOperator)
+HANDLE_BINARY_INST(14, UDiv , BinaryOperator)
+HANDLE_BINARY_INST(15, SDiv , BinaryOperator)
+HANDLE_BINARY_INST(16, FDiv , BinaryOperator)
+HANDLE_BINARY_INST(17, URem , BinaryOperator)
+HANDLE_BINARY_INST(18, SRem , BinaryOperator)
+HANDLE_BINARY_INST(19, FRem , BinaryOperator)
=20
 // Logical operators (integer operands)
-HANDLE_BINARY_INST(21, Shl  , BinaryOperator) // Shift left  (logical)
-HANDLE_BINARY_INST(22, LShr , BinaryOperator) // Shift right (logical)
-HANDLE_BINARY_INST(23, AShr , BinaryOperator) // Shift right (arithmetic)
-HANDLE_BINARY_INST(24, And  , BinaryOperator)
-HANDLE_BINARY_INST(25, Or   , BinaryOperator)
-HANDLE_BINARY_INST(26, Xor  , BinaryOperator)
-  LAST_BINARY_INST(26)
+HANDLE_BINARY_INST(20, Shl  , BinaryOperator) // Shift left  (logical)
+HANDLE_BINARY_INST(21, LShr , BinaryOperator) // Shift right (logical)
+HANDLE_BINARY_INST(22, AShr , BinaryOperator) // Shift right (arithmetic)
+HANDLE_BINARY_INST(23, And  , BinaryOperator)
+HANDLE_BINARY_INST(24, Or   , BinaryOperator)
+HANDLE_BINARY_INST(25, Xor  , BinaryOperator)
+  LAST_BINARY_INST(25)
=20
 // Memory operators...
- FIRST_MEMORY_INST(27)
-HANDLE_MEMORY_INST(27, Alloca, AllocaInst)  // Stack management
-HANDLE_MEMORY_INST(28, Load  , LoadInst  )  // Memory manipulation instrs
-HANDLE_MEMORY_INST(29, Store , StoreInst )
-HANDLE_MEMORY_INST(30, GetElementPtr, GetElementPtrInst)
-HANDLE_MEMORY_INST(31, Fence , FenceInst )
-HANDLE_MEMORY_INST(32, AtomicCmpXchg , AtomicCmpXchgInst )
-HANDLE_MEMORY_INST(33, AtomicRMW , AtomicRMWInst )
-  LAST_MEMORY_INST(33)
+ FIRST_MEMORY_INST(26)
+HANDLE_MEMORY_INST(26, Alloca, AllocaInst)  // Stack management
+HANDLE_MEMORY_INST(27, Load  , LoadInst  )  // Memory manipulation instrs
+HANDLE_MEMORY_INST(28, Store , StoreInst )
+HANDLE_MEMORY_INST(29, GetElementPtr, GetElementPtrInst)
+HANDLE_MEMORY_INST(30, Fence , FenceInst )
+HANDLE_MEMORY_INST(31, AtomicCmpXchg , AtomicCmpXchgInst )
+HANDLE_MEMORY_INST(32, AtomicRMW , AtomicRMWInst )
+  LAST_MEMORY_INST(32)
=20
 // Cast operators ...
 // NOTE: The order matters here because CastInst::isEliminableCastPair=20
 // NOTE: (see Instructions.cpp) encodes a table based on this ordering.
- FIRST_CAST_INST(34)
-HANDLE_CAST_INST(34, Trunc   , TruncInst   )  // Truncate integers
-HANDLE_CAST_INST(35, ZExt    , ZExtInst    )  // Zero extend integers
-HANDLE_CAST_INST(36, SExt    , SExtInst    )  // Sign extend integers
-HANDLE_CAST_INST(37, FPToUI  , FPToUIInst  )  // floating point -> UInt
-HANDLE_CAST_INST(38, FPToSI  , FPToSIInst  )  // floating point -> SInt
-HANDLE_CAST_INST(39, UIToFP  , UIToFPInst  )  // UInt -> floating point
-HANDLE_CAST_INST(40, SIToFP  , SIToFPInst  )  // SInt -> floating point
-HANDLE_CAST_INST(41, FPTrunc , FPTruncInst )  // Truncate floating point
-HANDLE_CAST_INST(42, FPExt   , FPExtInst   )  // Extend floating point
-HANDLE_CAST_INST(43, PtrToInt, PtrToIntInst)  // Pointer -> Integer
-HANDLE_CAST_INST(44, IntToPtr, IntToPtrInst)  // Integer -> Pointer
-HANDLE_CAST_INST(45, BitCast , BitCastInst )  // Type cast
-  LAST_CAST_INST(45)
+ FIRST_CAST_INST(33)
+HANDLE_CAST_INST(33, Trunc   , TruncInst   )  // Truncate integers
+HANDLE_CAST_INST(34, ZExt    , ZExtInst    )  // Zero extend integers
+HANDLE_CAST_INST(35, SExt    , SExtInst    )  // Sign extend integers
+HANDLE_CAST_INST(36, FPToUI  , FPToUIInst  )  // floating point -> UInt
+HANDLE_CAST_INST(37, FPToSI  , FPToSIInst  )  // floating point -> SInt
+HANDLE_CAST_INST(38, UIToFP  , UIToFPInst  )  // UInt -> floating point
+HANDLE_CAST_INST(39, SIToFP  , SIToFPInst  )  // SInt -> floating point
+HANDLE_CAST_INST(40, FPTrunc , FPTruncInst )  // Truncate floating point
+HANDLE_CAST_INST(41, FPExt   , FPExtInst   )  // Extend floating point
+HANDLE_CAST_INST(42, PtrToInt, PtrToIntInst)  // Pointer -> Integer
+HANDLE_CAST_INST(43, IntToPtr, IntToPtrInst)  // Integer -> Pointer
+HANDLE_CAST_INST(44, BitCast , BitCastInst )  // Type cast
+  LAST_CAST_INST(44)
=20
 // Other operators...
- FIRST_OTHER_INST(46)
-HANDLE_OTHER_INST(46, ICmp   , ICmpInst   )  // Integer comparison instruc=
tion
-HANDLE_OTHER_INST(47, FCmp   , FCmpInst   )  // Floating point comparison =
instr.
-HANDLE_OTHER_INST(48, PHI    , PHINode    )  // PHI node instruction
-HANDLE_OTHER_INST(49, Call   , CallInst   )  // Call a function
-HANDLE_OTHER_INST(50, Select , SelectInst )  // select instruction
-HANDLE_OTHER_INST(51, UserOp1, Instruction)  // May be used internally in =
a pass
-HANDLE_OTHER_INST(52, UserOp2, Instruction)  // Internal to passes only
-HANDLE_OTHER_INST(53, VAArg  , VAArgInst  )  // vaarg instruction
-HANDLE_OTHER_INST(54, ExtractElement, ExtractElementInst)// extract from v=
ector
-HANDLE_OTHER_INST(55, InsertElement, InsertElementInst)  // insert into ve=
ctor
-HANDLE_OTHER_INST(56, ShuffleVector, ShuffleVectorInst)  // shuffle two ve=
ctors.
-HANDLE_OTHER_INST(57, ExtractValue, ExtractValueInst)// extract from aggre=
gate
-HANDLE_OTHER_INST(58, InsertValue, InsertValueInst)  // insert into aggreg=
ate
-HANDLE_OTHER_INST(59, LandingPad, LandingPadInst)  // Landing pad instruct=
ion.
-  LAST_OTHER_INST(59)
+ FIRST_OTHER_INST(45)
+HANDLE_OTHER_INST(45, ICmp   , ICmpInst   )  // Integer comparison instruc=
tion
+HANDLE_OTHER_INST(46, FCmp   , FCmpInst   )  // Floating point comparison =
instr.
+HANDLE_OTHER_INST(47, PHI    , PHINode    )  // PHI node instruction
+HANDLE_OTHER_INST(48, Call   , CallInst   )  // Call a function
+HANDLE_OTHER_INST(49, Select , SelectInst )  // select instruction
+HANDLE_OTHER_INST(50, UserOp1, Instruction)  // May be used internally in =
a pass
+HANDLE_OTHER_INST(51, UserOp2, Instruction)  // Internal to passes only
+HANDLE_OTHER_INST(52, VAArg  , VAArgInst  )  // vaarg instruction
+HANDLE_OTHER_INST(53, ExtractElement, ExtractElementInst)// extract from v=
ector
+HANDLE_OTHER_INST(54, InsertElement, InsertElementInst)  // insert into ve=
ctor
+HANDLE_OTHER_INST(55, ShuffleVector, ShuffleVectorInst)  // shuffle two ve=
ctors.
+HANDLE_OTHER_INST(56, ExtractValue, ExtractValueInst)// extract from aggre=
gate
+HANDLE_OTHER_INST(57, InsertValue, InsertValueInst)  // insert into aggreg=
ate
+HANDLE_OTHER_INST(58, LandingPad, LandingPadInst)  // Landing pad instruct=
ion.
+  LAST_OTHER_INST(58)
=20
 #undef  FIRST_TERM_INST
 #undef HANDLE_TERM_INST
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Instruc=
tion.h
--- a/head/contrib/llvm/include/llvm/Instruction.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/Instruction.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -143,7 +143,7 @@
  =20
   /// getMetadata - Get the metadata of given kind attached to this Instru=
ction.
   /// If the metadata is not found then return null.
-  MDNode *getMetadata(const char *Kind) const {
+  MDNode *getMetadata(StringRef Kind) const {
     if (!hasMetadata()) return 0;
     return getMetadataImpl(Kind);
   }
@@ -168,7 +168,7 @@
   /// node.  This updates/replaces metadata if already present, or removes=
 it if
   /// Node is null.
   void setMetadata(unsigned KindID, MDNode *Node);
-  void setMetadata(const char *Kind, MDNode *Node);
+  void setMetadata(StringRef Kind, MDNode *Node);
=20
   /// setDebugLoc - Set the debug location information for this instructio=
n.
   void setDebugLoc(const DebugLoc &Loc) { DbgLoc =3D Loc; }
@@ -185,7 +185,7 @@
  =20
   // These are all implemented in Metadata.cpp.
   MDNode *getMetadataImpl(unsigned KindID) const;
-  MDNode *getMetadataImpl(const char *Kind) const;
+  MDNode *getMetadataImpl(StringRef Kind) const;
   void getAllMetadataImpl(SmallVectorImpl<std::pair<unsigned,MDNode*> > &)=
const;
   void getAllMetadataOtherThanDebugLocImpl(SmallVectorImpl<std::pair<unsig=
ned,
                                            MDNode*> > &) const;
@@ -244,26 +244,6 @@
     return mayWriteToMemory() || mayThrow();
   }
=20
-  /// isSafeToSpeculativelyExecute - Return true if the instruction does n=
ot
-  /// have any effects besides calculating the result and does not have
-  /// undefined behavior.
-  ///
-  /// This method never returns true for an instruction that returns true =
for
-  /// mayHaveSideEffects; however, this method also does some other checks=
 in
-  /// addition. It checks for undefined behavior, like dividing by zero or
-  /// loading from an invalid pointer (but not for undefined results, like=
 a
-  /// shift with a shift amount larger than the width of the result). It c=
hecks
-  /// for malloc and alloca because speculatively executing them might cau=
se a
-  /// memory leak. It also returns false for instructions related to contr=
ol
-  /// flow, specifically terminators and PHI nodes.
-  ///
-  /// This method only looks at the instruction itself and its operands, s=
o if
-  /// this method returns true, it is safe to move the instruction as long=
 as
-  /// the correct dominance relationships for the operands and users hold.
-  /// However, this method can return true for instructions that read memo=
ry;
-  /// for such instructions, moving them may change the resulting value.
-  bool isSafeToSpeculativelyExecute() const;
-
   /// clone() - Create a copy of 'this' instruction that is identical in a=
ll
   /// ways except the following:
   ///   * The instruction has no parent
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Instruc=
tions.h
--- a/head/contrib/llvm/include/llvm/Instructions.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/Instructions.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -776,6 +776,10 @@
   static Type *getIndexedType(Type *Ptr, ArrayRef<Constant *> IdxList);
   static Type *getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList);
=20
+  /// getIndexedType - Returns the address space used by the GEP pointer.
+  ///
+  static unsigned getAddressSpace(Value *Ptr);
+
   inline op_iterator       idx_begin()       { return op_begin()+1; }
   inline const_op_iterator idx_begin() const { return op_begin()+1; }
   inline op_iterator       idx_end()         { return op_end(); }
@@ -788,7 +792,7 @@
     return getOperand(0);
   }
   static unsigned getPointerOperandIndex() {
-    return 0U;                      // get index for modifying correct ope=
rand
+    return 0U;    // get index for modifying correct operand.
   }
=20
   unsigned getPointerAddressSpace() const {
@@ -797,10 +801,25 @@
=20
   /// getPointerOperandType - Method to return the pointer operand as a
   /// PointerType.
-  PointerType *getPointerOperandType() const {
-    return reinterpret_cast<PointerType*>(getPointerOperand()->getType());
-  }
-
+  Type *getPointerOperandType() const {
+    return getPointerOperand()->getType();
+  }
+
+  /// GetGEPReturnType - Returns the pointer type returned by the GEP
+  /// instruction, which may be a vector of pointers.
+  static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
+    Type *PtrTy =3D PointerType::get(checkGEPType(
+                                   getIndexedType(Ptr->getType(), IdxList)=
),
+                                   getAddressSpace(Ptr));
+    // Vector GEP
+    if (Ptr->getType()->isVectorTy()) {
+      unsigned NumElem =3D cast<VectorType>(Ptr->getType())->getNumElement=
s();
+      return VectorType::get(PtrTy, NumElem);
+    }
+
+    // Scalar GEP
+    return PtrTy;
+  }
=20
   unsigned getNumIndices() const {  // Note: always non-negative
     return getNumOperands() - 1;
@@ -847,10 +866,7 @@
                                      unsigned Values,
                                      const Twine &NameStr,
                                      Instruction *InsertBefore)
-  : Instruction(PointerType::get(checkGEPType(
-                                   getIndexedType(Ptr->getType(), IdxList)=
),
-                                 cast<PointerType>(Ptr->getType())
-                                   ->getAddressSpace()),
+  : Instruction(getGEPReturnType(Ptr, IdxList),
                 GetElementPtr,
                 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
                 Values, InsertBefore) {
@@ -861,10 +877,7 @@
                                      unsigned Values,
                                      const Twine &NameStr,
                                      BasicBlock *InsertAtEnd)
-  : Instruction(PointerType::get(checkGEPType(
-                                   getIndexedType(Ptr->getType(), IdxList)=
),
-                                 cast<PointerType>(Ptr->getType())
-                                   ->getAddressSpace()),
+  : Instruction(getGEPReturnType(Ptr, IdxList),
                 GetElementPtr,
                 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
                 Values, InsertAtEnd) {
@@ -905,7 +918,7 @@
           "Both operands to ICmp instruction are not of the same type!");
     // Check that the operands are the right type
     assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
-            getOperand(0)->getType()->isPointerTy()) &&
+            getOperand(0)->getType()->getScalarType()->isPointerTy()) &&
            "Invalid operand types for ICmp instruction");
   }
=20
@@ -945,7 +958,7 @@
           "Both operands to ICmp instruction are not of the same type!");
     // Check that the operands are the right type
     assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
-            getOperand(0)->getType()->isPointerTy()) &&
+            getOperand(0)->getType()->getScalarType()->isPointerTy()) &&
            "Invalid operand types for ICmp instruction");
   }
=20
@@ -1657,10 +1670,33 @@
   /// Transparently provide more efficient getOperand methods.
   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
=20
+  Constant *getMask() const {
+    return reinterpret_cast<Constant*>(getOperand(2));
+  }
+ =20
   /// getMaskValue - Return the index from the shuffle mask for the specif=
ied
   /// output result.  This is either -1 if the element is undef or a numbe=
r less
   /// than 2*numelements.
-  int getMaskValue(unsigned i) const;
+  static int getMaskValue(Constant *Mask, unsigned i);
+
+  int getMaskValue(unsigned i) const {
+    return getMaskValue(getMask(), i);
+  }
+ =20
+  /// getShuffleMask - Return the full mask for this instruction, where ea=
ch
+  /// element is the element number and undef's are returned as -1.
+  static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
+
+  void getShuffleMask(SmallVectorImpl<int> &Result) const {
+    return getShuffleMask(getMask(), Result);
+  }
+
+  SmallVector<int, 16> getShuffleMask() const {
+    SmallVector<int, 16> Mask;
+    getShuffleMask(Mask);
+    return Mask;
+  }
+
=20
   // Methods for support type inquiry through isa, cast, and dyn_cast:
   static inline bool classof(const ShuffleVectorInst *) { return true; }
@@ -2431,6 +2467,122 @@
 protected:
   virtual SwitchInst *clone_impl() const;
 public:
+ =20
+  // -2
+  static const unsigned DefaultPseudoIndex =3D static_cast<unsigned>(~0L-1=
);
+ =20
+  template <class SwitchInstTy, class ConstantIntTy, class BasicBlockTy>=20
+  class CaseIteratorT {
+  protected:
+   =20
+    SwitchInstTy *SI;
+    unsigned Index;
+   =20
+  public:
+   =20
+    typedef CaseIteratorT<SwitchInstTy, ConstantIntTy, BasicBlockTy> Self;
+   =20
+    /// Initializes case iterator for given SwitchInst and for given
+    /// case number.   =20
+    CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
+      this->SI =3D SI;
+      Index =3D CaseNum;
+    }
+   =20
+    /// Initializes case iterator for given SwitchInst and for given
+    /// TerminatorInst's successor index.
+    static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorInd=
ex) {
+      assert(SuccessorIndex < SI->getNumSuccessors() &&
+             "Successor index # out of range!");   =20
+      return SuccessorIndex !=3D 0 ?=20
+             Self(SI, SuccessorIndex - 1) :
+             Self(SI, DefaultPseudoIndex);      =20
+    }
+   =20
+    /// Resolves case value for current case.
+    ConstantIntTy *getCaseValue() {
+      assert(Index < SI->getNumCases() && "Index out the number of cases."=
);
+      return reinterpret_cast<ConstantIntTy*>(SI->getOperand(2 + Index*2));
+    }
+   =20
+    /// Resolves successor for current case.
+    BasicBlockTy *getCaseSuccessor() {
+      assert((Index < SI->getNumCases() ||
+              Index =3D=3D DefaultPseudoIndex) &&
+             "Index out the number of cases.");
+      return SI->getSuccessor(getSuccessorIndex());     =20
+    }
+   =20
+    /// Returns number of current case.
+    unsigned getCaseIndex() const { return Index; }
+   =20
+    /// Returns TerminatorInst's successor index for current case successo=
r.
+    unsigned getSuccessorIndex() const {
+      assert((Index =3D=3D DefaultPseudoIndex || Index < SI->getNumCases()=
) &&
+             "Index out the number of cases.");
+      return Index !=3D DefaultPseudoIndex ? Index + 1 : 0;
+    }
+   =20
+    Self operator++() {
+      // Check index correctness after increment.
+      // Note: Index =3D=3D getNumCases() means end().     =20
+      assert(Index+1 <=3D SI->getNumCases() && "Index out the number of ca=
ses.");
+      ++Index;
+      return *this;
+    }
+    Self operator++(int) {
+      Self tmp =3D *this;
+      ++(*this);
+      return tmp;
+    }
+    Self operator--() {=20
+      // Check index correctness after decrement.
+      // Note: Index =3D=3D getNumCases() means end().
+      // Also allow "-1" iterator here. That will became valid after ++.
+      assert((Index =3D=3D 0 || Index-1 <=3D SI->getNumCases()) &&
+             "Index out the number of cases.");
+      --Index;
+      return *this;
+    }
+    Self operator--(int) {
+      Self tmp =3D *this;
+      --(*this);
+      return tmp;
+    }
+    bool operator=3D=3D(const Self& RHS) const {
+      assert(RHS.SI =3D=3D SI && "Incompatible operators.");
+      return RHS.Index =3D=3D Index;
+    }
+    bool operator!=3D(const Self& RHS) const {
+      assert(RHS.SI =3D=3D SI && "Incompatible operators.");
+      return RHS.Index !=3D Index;
+    }
+  };
+ =20
+  typedef CaseIteratorT<const SwitchInst, const ConstantInt, const BasicBl=
ock>
+    ConstCaseIt;
+
+  class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt, BasicBlock>=
 {
+   =20
+    typedef CaseIteratorT<SwitchInst, ConstantInt, BasicBlock> ParentTy;
+ =20
+  public:
+   =20
+    CaseIt(const ParentTy& Src) : ParentTy(Src) {}
+    CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}
+
+    /// Sets the new value for current case.   =20
+    void setValue(ConstantInt *V) {
+      assert(Index < SI->getNumCases() && "Index out the number of cases."=
);
+      SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
+    }
+   =20
+    /// Sets the new successor for current case.
+    void setSuccessor(BasicBlock *S) {
+      SI->setSuccessor(getSuccessorIndex(), S);     =20
+    }
+  };
+
   static SwitchInst *Create(Value *Value, BasicBlock *Default,
                             unsigned NumCases, Instruction *InsertBefore =
=3D 0) {
     return new SwitchInst(Value, Default, NumCases, InsertBefore);
@@ -2439,6 +2591,7 @@
                             unsigned NumCases, BasicBlock *InsertAtEnd) {
     return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
   }
+ =20
   ~SwitchInst();
=20
   /// Provide fast operand accessors
@@ -2452,61 +2605,94 @@
     return cast<BasicBlock>(getOperand(1));
   }
=20
-  /// getNumCases - return the number of 'cases' in this switch instructio=
n.
-  /// Note that case #0 is always the default case.
+  void setDefaultDest(BasicBlock *DefaultCase) {
+    setOperand(1, reinterpret_cast<Value*>(DefaultCase));
+  }
+
+  /// getNumCases - return the number of 'cases' in this switch instructio=
n,
+  /// except the default case
   unsigned getNumCases() const {
-    return getNumOperands()/2;
-  }
-
-  /// getCaseValue - Return the specified case value.  Note that case #0, =
the
-  /// default destination, does not have a case value.
-  ConstantInt *getCaseValue(unsigned i) {
-    assert(i && i < getNumCases() && "Illegal case value to get!");
-    return getSuccessorValue(i);
-  }
-
-  /// getCaseValue - Return the specified case value.  Note that case #0, =
the
-  /// default destination, does not have a case value.
-  const ConstantInt *getCaseValue(unsigned i) const {
-    assert(i && i < getNumCases() && "Illegal case value to get!");
-    return getSuccessorValue(i);
-  }
-
+    return getNumOperands()/2 - 1;
+  }
+
+  /// Returns a read/write iterator that points to the first
+  /// case in SwitchInst.
+  CaseIt case_begin() {
+    return CaseIt(this, 0);
+  }
+  /// Returns a read-only iterator that points to the first
+  /// case in the SwitchInst.
+  ConstCaseIt case_begin() const {
+    return ConstCaseIt(this, 0);
+  }
+ =20
+  /// Returns a read/write iterator that points one past the last
+  /// in the SwitchInst.
+  CaseIt case_end() {
+    return CaseIt(this, getNumCases());
+  }
+  /// Returns a read-only iterator that points one past the last
+  /// in the SwitchInst.
+  ConstCaseIt case_end() const {
+    return ConstCaseIt(this, getNumCases());
+  }
+  /// Returns an iterator that points to the default case.
+  /// Note: this iterator allows to resolve successor only. Attempt
+  /// to resolve case value causes an assertion.
+  /// Also note, that increment and decrement also causes an assertion and
+  /// makes iterator invalid.=20
+  CaseIt case_default() {
+    return CaseIt(this, DefaultPseudoIndex);
+  }
+  ConstCaseIt case_default() const {
+    return ConstCaseIt(this, DefaultPseudoIndex);
+  }
+ =20
   /// findCaseValue - Search all of the case values for the specified cons=
tant.
-  /// If it is explicitly handled, return the case number of it, otherwise
-  /// return 0 to indicate that it is handled by the default handler.
-  unsigned findCaseValue(const ConstantInt *C) const {
-    for (unsigned i =3D 1, e =3D getNumCases(); i !=3D e; ++i)
-      if (getCaseValue(i) =3D=3D C)
+  /// If it is explicitly handled, return the case iterator of it, otherwi=
se
+  /// return default case iterator to indicate
+  /// that it is handled by the default handler.
+  CaseIt findCaseValue(const ConstantInt *C) {
+    for (CaseIt i =3D case_begin(), e =3D case_end(); i !=3D e; ++i)
+      if (i.getCaseValue() =3D=3D C)
         return i;
-    return 0;
-  }
-
+    return case_default();
+  }
+  ConstCaseIt findCaseValue(const ConstantInt *C) const {
+    for (ConstCaseIt i =3D case_begin(), e =3D case_end(); i !=3D e; ++i)
+      if (i.getCaseValue() =3D=3D C)
+        return i;
+    return case_default();
+  }   =20
+ =20
   /// findCaseDest - Finds the unique case value for a given successor. Re=
turns
   /// null if the successor is not found, not unique, or is the default ca=
se.
   ConstantInt *findCaseDest(BasicBlock *BB) {
     if (BB =3D=3D getDefaultDest()) return NULL;
=20
     ConstantInt *CI =3D NULL;
-    for (unsigned i =3D 1, e =3D getNumCases(); i !=3D e; ++i) {
-      if (getSuccessor(i) =3D=3D BB) {
+    for (CaseIt i =3D case_begin(), e =3D case_end(); i !=3D e; ++i) {
+      if (i.getCaseSuccessor() =3D=3D BB) {
         if (CI) return NULL;   // Multiple cases lead to BB.
-        else CI =3D getCaseValue(i);
+        else CI =3D i.getCaseValue();
       }
     }
     return CI;
   }
=20
   /// addCase - Add an entry to the switch instruction...
-  ///
+  /// Note:
+  /// This action invalidates case_end(). Old case_end() iterator will
+  /// point to the added case.
   void addCase(ConstantInt *OnVal, BasicBlock *Dest);
=20
-  /// removeCase - This method removes the specified successor from the sw=
itch
-  /// instruction.  Note that this cannot be used to remove the default
-  /// destination (successor #0). Also note that this operation may reorde=
r the
+  /// removeCase - This method removes the specified case and its successor
+  /// from the switch instruction. Note that this operation may reorder the
   /// remaining cases at index idx and above.
-  ///
-  void removeCase(unsigned idx);
+  /// Note:
+  /// This action invalidates iterators for all cases following the one re=
moved,
+  /// including the case_end() iterator.
+  void removeCase(CaseIt i);
=20
   unsigned getNumSuccessors() const { return getNumOperands()/2; }
   BasicBlock *getSuccessor(unsigned idx) const {
@@ -2518,20 +2704,6 @@
     setOperand(idx*2+1, (Value*)NewSucc);
   }
=20
-  // getSuccessorValue - Return the value associated with the specified
-  // successor.
-  ConstantInt *getSuccessorValue(unsigned idx) const {
-    assert(idx < getNumSuccessors() && "Successor # out of range!");
-    return reinterpret_cast<ConstantInt*>(getOperand(idx*2));
-  }
-
-  // setSuccessorValue - Updates the value associated with the specified
-  // successor.
-  void setSuccessorValue(unsigned idx, ConstantInt* SuccessorValue) {
-    assert(idx < getNumSuccessors() && "Successor # out of range!");
-    setOperand(idx*2, reinterpret_cast<Value*>(SuccessorValue));
-  }
-
   // Methods for support type inquiry through isa, cast, and dyn_cast:
   static inline bool classof(const SwitchInst *) { return true; }
   static inline bool classof(const Instruction *I) {
@@ -2890,42 +3062,6 @@
 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//                              UnwindInst Class
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-//=3D=3D=3D---------------------------------------------------------------=
------------
-/// UnwindInst - Immediately exit the current function, unwinding the stack
-/// until an invoke instruction is found.
-///
-class UnwindInst : public TerminatorInst {
-  void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
-protected:
-  virtual UnwindInst *clone_impl() const;
-public:
-  // allocate space for exactly zero operands
-  void *operator new(size_t s) {
-    return User::operator new(s, 0);
-  }
-  explicit UnwindInst(LLVMContext &C, Instruction *InsertBefore =3D 0);
-  explicit UnwindInst(LLVMContext &C, BasicBlock *InsertAtEnd);
-
-  unsigned getNumSuccessors() const { return 0; }
-
-  // Methods for support type inquiry through isa, cast, and dyn_cast:
-  static inline bool classof(const UnwindInst *) { return true; }
-  static inline bool classof(const Instruction *I) {
-    return I->getOpcode() =3D=3D Instruction::Unwind;
-  }
-  static inline bool classof(const Value *V) {
-    return isa<Instruction>(V) && classof(cast<Instruction>(V));
-  }
-private:
-  virtual BasicBlock *getSuccessorV(unsigned idx) const;
-  virtual unsigned getNumSuccessorsV() const;
-  virtual void setSuccessorV(unsigned idx, BasicBlock *B);
-};
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                              ResumeInst Class
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Intrins=
icInst.h
--- a/head/contrib/llvm/include/llvm/IntrinsicInst.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/IntrinsicInst.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -277,34 +277,6 @@
     }
   };
=20
-  /// EHExceptionInst - This represents the llvm.eh.exception instruction.
-  ///
-  class EHExceptionInst : public IntrinsicInst {
-  public:
-    // Methods for support type inquiry through isa, cast, and dyn_cast:
-    static inline bool classof(const EHExceptionInst *) { return true; }
-    static inline bool classof(const IntrinsicInst *I) {
-      return I->getIntrinsicID() =3D=3D Intrinsic::eh_exception;
-    }
-    static inline bool classof(const Value *V) {
-      return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
-    }
-  };
-
-  /// EHSelectorInst - This represents the llvm.eh.selector instruction.
-  ///
-  class EHSelectorInst : public IntrinsicInst {
-  public:
-    // Methods for support type inquiry through isa, cast, and dyn_cast:
-    static inline bool classof(const EHSelectorInst *) { return true; }
-    static inline bool classof(const IntrinsicInst *I) {
-      return I->getIntrinsicID() =3D=3D Intrinsic::eh_selector;
-    }
-    static inline bool classof(const Value *V) {
-      return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
-    }
-  };
-
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Intrins=
ics.td
--- a/head/contrib/llvm/include/llvm/Intrinsics.td	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/Intrinsics.td	Tue Apr 17 11:51:51 2012=
 +0300
@@ -284,8 +284,8 @@
 let Properties =3D [IntrNoMem] in {
   def int_bswap: Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>]>;
   def int_ctpop: Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>]>;
-  def int_ctlz : Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>]>;
-  def int_cttz : Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>]>;
+  def int_ctlz : Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>, llvm_i1_ty=
]>;
+  def int_cttz : Intrinsic<[llvm_anyint_ty], [LLVMMatchType<0>, llvm_i1_ty=
]>;
 }
=20
 //=3D=3D=3D------------------------ Debugger Intrinsics ------------------=
-------=3D=3D=3D//
@@ -304,10 +304,6 @@
=20
 //=3D=3D=3D------------------ Exception Handling Intrinsics---------------=
-------=3D=3D=3D//
 //
-def int_eh_exception : Intrinsic<[llvm_ptr_ty], [], [IntrReadMem]>;
-def int_eh_selector  : Intrinsic<[llvm_i32_ty],
-                                 [llvm_ptr_ty, llvm_ptr_ty, llvm_vararg_ty=
]>;
-def int_eh_resume    : Intrinsic<[], [llvm_ptr_ty, llvm_i32_ty], [Throws]>;
=20
 // The result of eh.typeid.for depends on the enclosing function, but insi=
de a
 // given function it is 'const' and may be CSE'd etc.
@@ -326,7 +322,6 @@
   def int_eh_sjlj_callsite         : Intrinsic<[], [llvm_i32_ty]>;
 }
 def int_eh_sjlj_functioncontext : Intrinsic<[], [llvm_ptr_ty]>;
-def int_eh_sjlj_dispatch_setup  : Intrinsic<[], [llvm_i32_ty]>;
 def int_eh_sjlj_setjmp          : Intrinsic<[llvm_i32_ty], [llvm_ptr_ty]>;
 def int_eh_sjlj_longjmp         : Intrinsic<[], [llvm_ptr_ty]>;
=20
@@ -443,6 +438,6 @@
 include "llvm/IntrinsicsX86.td"
 include "llvm/IntrinsicsARM.td"
 include "llvm/IntrinsicsCellSPU.td"
-include "llvm/IntrinsicsAlpha.td"
 include "llvm/IntrinsicsXCore.td"
 include "llvm/IntrinsicsPTX.td"
+include "llvm/IntrinsicsHexagon.td"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Intrins=
icsX86.td
--- a/head/contrib/llvm/include/llvm/IntrinsicsX86.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/IntrinsicsX86.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -145,10 +145,10 @@
=20
 // Comparison ops
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
-  def int_x86_sse_cmp_ss :
+  def int_x86_sse_cmp_ss : GCCBuiltin<"__builtin_ia32_cmpss">,
               Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
                          llvm_v4f32_ty, llvm_i8_ty], [IntrNoMem]>;
-  def int_x86_sse_cmp_ps :
+  def int_x86_sse_cmp_ps : GCCBuiltin<"__builtin_ia32_cmpps">,
               Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
                          llvm_v4f32_ty, llvm_i8_ty], [IntrNoMem]>;
   def int_x86_sse_comieq_ss : GCCBuiltin<"__builtin_ia32_comieq">,
@@ -281,10 +281,10 @@
=20
 // FP comparison ops
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
-  def int_x86_sse2_cmp_sd :
+  def int_x86_sse2_cmp_sd : GCCBuiltin<"__builtin_ia32_cmpsd">,
               Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
                          llvm_v2f64_ty, llvm_i8_ty], [IntrNoMem]>;
-  def int_x86_sse2_cmp_pd :
+  def int_x86_sse2_cmp_pd : GCCBuiltin<"__builtin_ia32_cmppd">,
               Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
                          llvm_v2f64_ty, llvm_i8_ty], [IntrNoMem]>;
   def int_x86_sse2_comieq_sd : GCCBuiltin<"__builtin_ia32_comisdeq">,
@@ -452,28 +452,6 @@
                          llvm_i32_ty], [IntrNoMem]>;
 }
=20
-// Integer comparison ops
-let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
-  def int_x86_sse2_pcmpeq_b : GCCBuiltin<"__builtin_ia32_pcmpeqb128">,
-              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
-                         llvm_v16i8_ty], [IntrNoMem]>;
-  def int_x86_sse2_pcmpeq_w : GCCBuiltin<"__builtin_ia32_pcmpeqw128">,
-              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
-                         llvm_v8i16_ty], [IntrNoMem]>;
-  def int_x86_sse2_pcmpeq_d : GCCBuiltin<"__builtin_ia32_pcmpeqd128">,
-              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
-                         llvm_v4i32_ty], [IntrNoMem]>;
-  def int_x86_sse2_pcmpgt_b : GCCBuiltin<"__builtin_ia32_pcmpgtb128">,
-              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty,
-                         llvm_v16i8_ty], [IntrNoMem]>;
-  def int_x86_sse2_pcmpgt_w : GCCBuiltin<"__builtin_ia32_pcmpgtw128">,
-              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
-                         llvm_v8i16_ty], [IntrNoMem]>;
-  def int_x86_sse2_pcmpgt_d : GCCBuiltin<"__builtin_ia32_pcmpgtd128">,
-              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
-                         llvm_v4i32_ty], [IntrNoMem]>;
-}
-
 // Conversion ops
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
   def int_x86_sse2_cvtdq2pd : GCCBuiltin<"__builtin_ia32_cvtdq2pd">,
@@ -627,8 +605,8 @@
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
                          llvm_x86mmx_ty], [IntrNoMem]>;
   def int_x86_ssse3_phadd_sw_128    : GCCBuiltin<"__builtin_ia32_phaddsw12=
8">,
-              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty,
-                         llvm_v4i32_ty], [IntrNoMem]>;
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
+                         llvm_v8i16_ty], [IntrNoMem]>;
=20
   def int_x86_ssse3_phsub_w         : GCCBuiltin<"__builtin_ia32_phsubw">,
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
@@ -655,8 +633,8 @@
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
                          llvm_x86mmx_ty], [IntrNoMem]>;
   def int_x86_ssse3_pmadd_ub_sw_128 : GCCBuiltin<"__builtin_ia32_pmaddubsw=
128">,
-              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty,
-                         llvm_v8i16_ty], [IntrNoMem]>;
+              Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty,
+                         llvm_v16i8_ty], [IntrNoMem]>;
 }
=20
 // Packed multiply high with round and scale
@@ -792,12 +770,6 @@
=20
 // Vector compare, min, max
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
-  def int_x86_sse41_pcmpeqq         : GCCBuiltin<"__builtin_ia32_pcmpeqq">,
-              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
-                        [IntrNoMem, Commutative]>;
-  def int_x86_sse42_pcmpgtq         : GCCBuiltin<"__builtin_ia32_pcmpgtq">,
-              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
-                        [IntrNoMem]>;
   def int_x86_sse41_pmaxsb          : GCCBuiltin<"__builtin_ia32_pmaxsb128=
">,
               Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
                         [IntrNoMem, Commutative]>;
@@ -919,7 +891,7 @@
 // Vector sum of absolute differences
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
   def int_x86_sse41_mpsadbw         : GCCBuiltin<"__builtin_ia32_mpsadbw12=
8">,
-          Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty,llvm_i3=
2_ty],
+          Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty, llvm_v16i8_ty,llvm_i3=
2_ty],
                     [IntrNoMem, Commutative]>;
 }
=20
@@ -932,13 +904,13 @@
 // Test instruction with bitwise comparison.
 let TargetPrefix =3D "x86" in { // All intrinsics start with "llvm.x86.".
   def int_x86_sse41_ptestz          : GCCBuiltin<"__builtin_ia32_ptestz128=
">,
-          Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+          Intrinsic<[llvm_i32_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
                     [IntrNoMem]>;
   def int_x86_sse41_ptestc          : GCCBuiltin<"__builtin_ia32_ptestc128=
">,
-          Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+          Intrinsic<[llvm_i32_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
                     [IntrNoMem]>;
   def int_x86_sse41_ptestnzc        : GCCBuiltin<"__builtin_ia32_ptestnzc1=
28">,
-          Intrinsic<[llvm_i32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+          Intrinsic<[llvm_i32_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
                     [IntrNoMem]>;
 }
=20
@@ -1120,17 +1092,17 @@
         Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
                   llvm_v8i32_ty, llvm_i8_ty], [IntrNoMem]>;
=20
-  def int_x86_avx_vpermil_pd : GCCBuiltin<"__builtin_ia32_vpermilpd">,
+  def int_x86_avx_vpermil_pd :
         Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty,
                   llvm_i8_ty], [IntrNoMem]>;
-  def int_x86_avx_vpermil_ps : GCCBuiltin<"__builtin_ia32_vpermilps">,
+  def int_x86_avx_vpermil_ps :
         Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty,
                   llvm_i8_ty], [IntrNoMem]>;
=20
-  def int_x86_avx_vpermil_pd_256 : GCCBuiltin<"__builtin_ia32_vpermilpd256=
">,
+  def int_x86_avx_vpermil_pd_256 :
         Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty,
                   llvm_i8_ty], [IntrNoMem]>;
-  def int_x86_avx_vpermil_ps_256 : GCCBuiltin<"__builtin_ia32_vpermilps256=
">,
+  def int_x86_avx_vpermil_ps_256 :
         Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty,
                   llvm_i8_ty], [IntrNoMem]>;
 }
@@ -1281,13 +1253,13 @@
=20
 // Vector load with broadcast
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
-  def int_x86_avx_vbroadcastss :
+  def int_x86_avx_vbroadcast_ss :
         GCCBuiltin<"__builtin_ia32_vbroadcastss">,
         Intrinsic<[llvm_v4f32_ty], [llvm_ptr_ty], [IntrReadMem]>;
   def int_x86_avx_vbroadcast_sd_256 :
         GCCBuiltin<"__builtin_ia32_vbroadcastsd256">,
         Intrinsic<[llvm_v4f64_ty], [llvm_ptr_ty], [IntrReadMem]>;
-  def int_x86_avx_vbroadcastss_256 :
+  def int_x86_avx_vbroadcast_ss_256 :
         GCCBuiltin<"__builtin_ia32_vbroadcastss256">,
         Intrinsic<[llvm_v8f32_ty], [llvm_ptr_ty], [IntrReadMem]>;
   def int_x86_avx_vbroadcastf128_pd_256 :
@@ -1300,12 +1272,6 @@
=20
 // SIMD load ops
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
-  def int_x86_avx_loadu_pd_256 : GCCBuiltin<"__builtin_ia32_loadupd256">,
-        Intrinsic<[llvm_v4f64_ty], [llvm_ptr_ty], [IntrReadMem]>;
-  def int_x86_avx_loadu_ps_256 : GCCBuiltin<"__builtin_ia32_loadups256">,
-        Intrinsic<[llvm_v8f32_ty], [llvm_ptr_ty], [IntrReadMem]>;
-  def int_x86_avx_loadu_dq_256 : GCCBuiltin<"__builtin_ia32_loaddqu256">,
-        Intrinsic<[llvm_v32i8_ty], [llvm_ptr_ty], [IntrReadMem]>;
   def int_x86_avx_ldu_dq_256 : GCCBuiltin<"__builtin_ia32_lddqu256">,
         Intrinsic<[llvm_v32i8_ty], [llvm_ptr_ty], [IntrReadMem]>;
 }
@@ -1361,6 +1327,1046 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// AVX2
+
+// Integer arithmetic ops.
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_padds_b : GCCBuiltin<"__builtin_ia32_paddsb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_padds_w : GCCBuiltin<"__builtin_ia32_paddsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_paddus_b : GCCBuiltin<"__builtin_ia32_paddusb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_paddus_w : GCCBuiltin<"__builtin_ia32_paddusw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_psubs_b : GCCBuiltin<"__builtin_ia32_psubsb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_psubs_w : GCCBuiltin<"__builtin_ia32_psubsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_psubus_b : GCCBuiltin<"__builtin_ia32_psubusb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_psubus_w : GCCBuiltin<"__builtin_ia32_psubusw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_pmulhu_w : GCCBuiltin<"__builtin_ia32_pmulhuw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmulh_w : GCCBuiltin<"__builtin_ia32_pmulhw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmulu_dq : GCCBuiltin<"__builtin_ia32_pmuludq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmul_dq : GCCBuiltin<"__builtin_ia32_pmuldq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmadd_wd : GCCBuiltin<"__builtin_ia32_pmaddwd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pavg_b : GCCBuiltin<"__builtin_ia32_pavgb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pavg_w : GCCBuiltin<"__builtin_ia32_pavgw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_psad_bw : GCCBuiltin<"__builtin_ia32_psadbw256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+}
+
+// Vector min, max
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_pmaxu_b : GCCBuiltin<"__builtin_ia32_pmaxub256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmaxu_w : GCCBuiltin<"__builtin_ia32_pmaxuw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmaxu_d : GCCBuiltin<"__builtin_ia32_pmaxud256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmaxs_b : GCCBuiltin<"__builtin_ia32_pmaxsb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmaxs_w : GCCBuiltin<"__builtin_ia32_pmaxsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmaxs_d : GCCBuiltin<"__builtin_ia32_pmaxsd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pminu_b : GCCBuiltin<"__builtin_ia32_pminub256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pminu_w : GCCBuiltin<"__builtin_ia32_pminuw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pminu_d : GCCBuiltin<"__builtin_ia32_pminud256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmins_b : GCCBuiltin<"__builtin_ia32_pminsb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmins_w : GCCBuiltin<"__builtin_ia32_pminsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_pmins_d : GCCBuiltin<"__builtin_ia32_pminsd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem, Commutative]>;
+}
+
+// Integer shift ops.
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_psll_w : GCCBuiltin<"__builtin_ia32_psllw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_psll_d : GCCBuiltin<"__builtin_ia32_pslld256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v4i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psll_q : GCCBuiltin<"__builtin_ia32_psllq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_v2i64_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrl_w : GCCBuiltin<"__builtin_ia32_psrlw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrl_d : GCCBuiltin<"__builtin_ia32_psrld256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v4i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrl_q : GCCBuiltin<"__builtin_ia32_psrlq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_v2i64_ty], [IntrNoMem]>;
+  def int_x86_avx2_psra_w : GCCBuiltin<"__builtin_ia32_psraw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_psra_d : GCCBuiltin<"__builtin_ia32_psrad256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v4i32_ty], [IntrNoMem]>;
+
+  def int_x86_avx2_pslli_w : GCCBuiltin<"__builtin_ia32_psllwi256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_pslli_d : GCCBuiltin<"__builtin_ia32_pslldi256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_pslli_q : GCCBuiltin<"__builtin_ia32_psllqi256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrli_w : GCCBuiltin<"__builtin_ia32_psrlwi256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrli_d : GCCBuiltin<"__builtin_ia32_psrldi256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrli_q : GCCBuiltin<"__builtin_ia32_psrlqi256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrai_w : GCCBuiltin<"__builtin_ia32_psrawi256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrai_d : GCCBuiltin<"__builtin_ia32_psradi256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+
+  def int_x86_avx2_psll_dq : GCCBuiltin<"__builtin_ia32_pslldqi256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrl_dq : GCCBuiltin<"__builtin_ia32_psrldqi256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psll_dq_bs : GCCBuiltin<"__builtin_ia32_pslldqi256_byte=
shift">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_psrl_dq_bs : GCCBuiltin<"__builtin_ia32_psrldqi256_byte=
shift">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Pack ops.
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_packsswb : GCCBuiltin<"__builtin_ia32_packsswb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_packssdw : GCCBuiltin<"__builtin_ia32_packssdw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_packuswb : GCCBuiltin<"__builtin_ia32_packuswb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_packusdw : GCCBuiltin<"__builtin_ia32_packusdw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem]>;
+}
+
+// Absolute value ops
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_pabs_b : GCCBuiltin<"__builtin_ia32_pabsb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_pabs_w : GCCBuiltin<"__builtin_ia32_pabsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_pabs_d : GCCBuiltin<"__builtin_ia32_pabsd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty], [IntrNoMem]>;
+}
+
+// Horizontal arithmetic ops
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_phadd_w : GCCBuiltin<"__builtin_ia32_phaddw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_phadd_d : GCCBuiltin<"__builtin_ia32_phaddd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_phadd_sw : GCCBuiltin<"__builtin_ia32_phaddsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_phsub_w : GCCBuiltin<"__builtin_ia32_phsubw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_phsub_d : GCCBuiltin<"__builtin_ia32_phsubd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_phsub_sw : GCCBuiltin<"__builtin_ia32_phsubsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_pmadd_ub_sw : GCCBuiltin<"__builtin_ia32_pmaddubsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem]>;
+}
+
+// Sign ops
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_psign_b : GCCBuiltin<"__builtin_ia32_psignb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_psign_w : GCCBuiltin<"__builtin_ia32_psignw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_psign_d : GCCBuiltin<"__builtin_ia32_psignd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty,
+                         llvm_v8i32_ty], [IntrNoMem]>;
+}
+
+// Packed multiply high with round and scale
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_pmul_hr_sw : GCCBuiltin<"__builtin_ia32_pmulhrsw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty,
+                         llvm_v16i16_ty], [IntrNoMem, Commutative]>;
+}
+
+// Vector sign and zero extend
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_pmovsxbd : GCCBuiltin<"__builtin_ia32_pmovsxbd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovsxbq : GCCBuiltin<"__builtin_ia32_pmovsxbq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovsxbw : GCCBuiltin<"__builtin_ia32_pmovsxbw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovsxdq : GCCBuiltin<"__builtin_ia32_pmovsxdq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovsxwd : GCCBuiltin<"__builtin_ia32_pmovsxwd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovsxwq : GCCBuiltin<"__builtin_ia32_pmovsxwq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovzxbd : GCCBuiltin<"__builtin_ia32_pmovzxbd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovzxbq : GCCBuiltin<"__builtin_ia32_pmovzxbq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovzxbw : GCCBuiltin<"__builtin_ia32_pmovzxbw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovzxdq : GCCBuiltin<"__builtin_ia32_pmovzxdq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovzxwd : GCCBuiltin<"__builtin_ia32_pmovzxwd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_pmovzxwq : GCCBuiltin<"__builtin_ia32_pmovzxwq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v8i16_ty],
+                        [IntrNoMem]>;
+}
+
+// Vector blend
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_pblendvb : GCCBuiltin<"__builtin_ia32_pblendvb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty, llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_pblendw : GCCBuiltin<"__builtin_ia32_pblendw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v16i16_ty, llvm_v16i16_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_pblendd_128 : GCCBuiltin<"__builtin_ia32_pblendd128">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_pblendd_256 : GCCBuiltin<"__builtin_ia32_pblendd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty,
+                         llvm_i32_ty], [IntrNoMem]>;
+}
+
+// Vector load with broadcast
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_vbroadcast_ss_ps :
+              GCCBuiltin<"__builtin_ia32_vbroadcastss_ps">,
+              Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+  def int_x86_avx2_vbroadcast_sd_pd_256 :
+              GCCBuiltin<"__builtin_ia32_vbroadcastsd_pd256">,
+              Intrinsic<[llvm_v4f64_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+  def int_x86_avx2_vbroadcast_ss_ps_256 :
+              GCCBuiltin<"__builtin_ia32_vbroadcastss_ps256">,
+              Intrinsic<[llvm_v8f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+  def int_x86_avx2_vbroadcasti128 :
+              GCCBuiltin<"__builtin_ia32_vbroadcastsi256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_ptr_ty], [IntrReadMem]>;
+  def int_x86_avx2_pbroadcastb_128 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastb128">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_pbroadcastb_256 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_pbroadcastw_128 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastw128">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_pbroadcastw_256 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_avx2_pbroadcastd_128 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastd128">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_pbroadcastd_256 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastd256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+  def int_x86_avx2_pbroadcastq_128 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastq128">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty], [IntrNoMem]>;
+  def int_x86_avx2_pbroadcastq_256 :
+              GCCBuiltin<"__builtin_ia32_pbroadcastq256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v2i64_ty], [IntrNoMem]>;
+}
+
+// Vector permutation
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_permd : GCCBuiltin<"__builtin_ia32_permvarsi256">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_permq : GCCBuiltin<"__builtin_ia32_permdi256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty, llvm_i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_permps : GCCBuiltin<"__builtin_ia32_permvarsf256">,
+              Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty, llvm_v8f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_permpd : GCCBuiltin<"__builtin_ia32_permdf256">,
+              Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty, llvm_i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_vperm2i128 : GCCBuiltin<"__builtin_ia32_permti256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_v4i64_ty, llvm_i8_ty], [IntrNoMem]>;
+}
+
+// Vector extract and insert
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_vextracti128 : GCCBuiltin<"__builtin_ia32_extract128i25=
6">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v4i64_ty,
+                         llvm_i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_vinserti128 : GCCBuiltin<"__builtin_ia32_insert128i256"=
>,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty,
+                         llvm_v2i64_ty, llvm_i8_ty], [IntrNoMem]>;
+}
+
+// Conditional load ops
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_maskload_d : GCCBuiltin<"__builtin_ia32_maskloadd">,
+        Intrinsic<[llvm_v4i32_ty], [llvm_ptr_ty, llvm_v4i32_ty], [IntrRead=
Mem]>;
+  def int_x86_avx2_maskload_q : GCCBuiltin<"__builtin_ia32_maskloadq">,
+        Intrinsic<[llvm_v2i64_ty], [llvm_ptr_ty, llvm_v2i64_ty], [IntrRead=
Mem]>;
+  def int_x86_avx2_maskload_d_256 : GCCBuiltin<"__builtin_ia32_maskloadd25=
6">,
+        Intrinsic<[llvm_v8i32_ty], [llvm_ptr_ty, llvm_v8i32_ty], [IntrRead=
Mem]>;
+  def int_x86_avx2_maskload_q_256 : GCCBuiltin<"__builtin_ia32_maskloadq25=
6">,
+        Intrinsic<[llvm_v4i64_ty], [llvm_ptr_ty, llvm_v4i64_ty], [IntrRead=
Mem]>;
+}
+
+// Conditional store ops
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_maskstore_d : GCCBuiltin<"__builtin_ia32_maskstored">,
+        Intrinsic<[], [llvm_ptr_ty, llvm_v4i32_ty, llvm_v4i32_ty], []>;
+  def int_x86_avx2_maskstore_q : GCCBuiltin<"__builtin_ia32_maskstoreq">,
+        Intrinsic<[], [llvm_ptr_ty, llvm_v2i64_ty, llvm_v2i64_ty], []>;
+  def int_x86_avx2_maskstore_d_256 :
+        GCCBuiltin<"__builtin_ia32_maskstored256">,
+        Intrinsic<[], [llvm_ptr_ty, llvm_v8i32_ty, llvm_v8i32_ty], []>;
+  def int_x86_avx2_maskstore_q_256 :
+        GCCBuiltin<"__builtin_ia32_maskstoreq256">,
+        Intrinsic<[], [llvm_ptr_ty, llvm_v4i64_ty, llvm_v4i64_ty], []>;
+}
+
+// Variable bit shift ops
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_psllv_d : GCCBuiltin<"__builtin_ia32_psllv4si">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_psllv_d_256 : GCCBuiltin<"__builtin_ia32_psllv8si">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_psllv_q : GCCBuiltin<"__builtin_ia32_psllv2di">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_psllv_q_256 : GCCBuiltin<"__builtin_ia32_psllv4di">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty, llvm_v4i64_ty],
+                        [IntrNoMem]>;
+
+  def int_x86_avx2_psrlv_d : GCCBuiltin<"__builtin_ia32_psrlv4si">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_psrlv_d_256 : GCCBuiltin<"__builtin_ia32_psrlv8si">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_psrlv_q : GCCBuiltin<"__builtin_ia32_psrlv2di">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_psrlv_q_256 : GCCBuiltin<"__builtin_ia32_psrlv4di">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_v4i64_ty, llvm_v4i64_ty],
+                        [IntrNoMem]>;
+
+  def int_x86_avx2_psrav_d : GCCBuiltin<"__builtin_ia32_psrav4si">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_avx2_psrav_d_256 : GCCBuiltin<"__builtin_ia32_psrav8si">,
+              Intrinsic<[llvm_v8i32_ty], [llvm_v8i32_ty, llvm_v8i32_ty],
+                        [IntrNoMem]>;
+}
+
+// Misc.
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_avx2_pmovmskb : GCCBuiltin<"__builtin_ia32_pmovmskb256">,
+              Intrinsic<[llvm_i32_ty], [llvm_v32i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_pshuf_b : GCCBuiltin<"__builtin_ia32_pshufb256">,
+              Intrinsic<[llvm_v32i8_ty], [llvm_v32i8_ty,
+                         llvm_v32i8_ty], [IntrNoMem]>;
+  def int_x86_avx2_mpsadbw : GCCBuiltin<"__builtin_ia32_mpsadbw256">,
+              Intrinsic<[llvm_v16i16_ty], [llvm_v32i8_ty, llvm_v32i8_ty,
+                         llvm_i32_ty], [IntrNoMem, Commutative]>;
+  def int_x86_avx2_movntdqa : GCCBuiltin<"__builtin_ia32_movntdqa256">,
+              Intrinsic<[llvm_v4i64_ty], [llvm_ptr_ty], [IntrReadMem]>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// FMA4
+
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_fma4_vfmadd_ss : GCCBuiltin<"__builtin_ia32_vfmaddss">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmadd_sd : GCCBuiltin<"__builtin_ia32_vfmaddsd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmadd_ps : GCCBuiltin<"__builtin_ia32_vfmaddps">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmadd_pd : GCCBuiltin<"__builtin_ia32_vfmaddpd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmadd_ps_256 : GCCBuiltin<"__builtin_ia32_vfmaddps256"=
>,
+              Intrinsic<[llvm_v8f32_ty],
+                        [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmadd_pd_256 : GCCBuiltin<"__builtin_ia32_vfmaddpd256"=
>,
+              Intrinsic<[llvm_v4f64_ty],
+                        [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsub_ss : GCCBuiltin<"__builtin_ia32_vfmsubss">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsub_sd : GCCBuiltin<"__builtin_ia32_vfmsubsd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsub_ps : GCCBuiltin<"__builtin_ia32_vfmsubps">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsub_pd : GCCBuiltin<"__builtin_ia32_vfmsubpd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsub_ps_256 : GCCBuiltin<"__builtin_ia32_vfmsubps256"=
>,
+              Intrinsic<[llvm_v8f32_ty],
+                        [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsub_pd_256 : GCCBuiltin<"__builtin_ia32_vfmsubpd256"=
>,
+              Intrinsic<[llvm_v4f64_ty],
+                        [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmadd_ss : GCCBuiltin<"__builtin_ia32_vfnmaddss">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmadd_sd : GCCBuiltin<"__builtin_ia32_vfnmaddsd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmadd_ps : GCCBuiltin<"__builtin_ia32_vfnmaddps">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmadd_pd : GCCBuiltin<"__builtin_ia32_vfnmaddpd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmadd_ps_256 : GCCBuiltin<"__builtin_ia32_vfnmaddps25=
6">,
+              Intrinsic<[llvm_v8f32_ty],
+                        [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmadd_pd_256 : GCCBuiltin<"__builtin_ia32_vfnmaddpd25=
6">,
+              Intrinsic<[llvm_v4f64_ty],
+                        [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmsub_ss : GCCBuiltin<"__builtin_ia32_vfnmsubss">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmsub_sd : GCCBuiltin<"__builtin_ia32_vfnmsubsd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmsub_ps : GCCBuiltin<"__builtin_ia32_vfnmsubps">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmsub_pd : GCCBuiltin<"__builtin_ia32_vfnmsubpd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmsub_ps_256 : GCCBuiltin<"__builtin_ia32_vfnmsubps25=
6">,
+              Intrinsic<[llvm_v8f32_ty],
+                        [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfnmsub_pd_256 : GCCBuiltin<"__builtin_ia32_vfnmsubpd25=
6">,
+              Intrinsic<[llvm_v4f64_ty],
+                        [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmaddsub_ps : GCCBuiltin<"__builtin_ia32_vfmaddsubps">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmaddsub_pd : GCCBuiltin<"__builtin_ia32_vfmaddsubpd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmaddsub_ps_256 :
+               GCCBuiltin<"__builtin_ia32_vfmaddsubps256">,
+              Intrinsic<[llvm_v8f32_ty],
+                        [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmaddsub_pd_256 :
+              GCCBuiltin<"__builtin_ia32_vfmaddsubpd256">,
+              Intrinsic<[llvm_v4f64_ty],
+                        [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsubadd_ps : GCCBuiltin<"__builtin_ia32_vfmsubaddps">,
+              Intrinsic<[llvm_v4f32_ty],
+                        [llvm_v4f32_ty, llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsubadd_pd : GCCBuiltin<"__builtin_ia32_vfmsubaddpd">,
+              Intrinsic<[llvm_v2f64_ty],
+                        [llvm_v2f64_ty, llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsubadd_ps_256 :
+              GCCBuiltin<"__builtin_ia32_vfmsubaddps256">,
+              Intrinsic<[llvm_v8f32_ty],
+                        [llvm_v8f32_ty, llvm_v8f32_ty, llvm_v8f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_fma4_vfmsubadd_pd_256 :
+              GCCBuiltin<"__builtin_ia32_vfmsubaddpd256">,
+              Intrinsic<[llvm_v4f64_ty],
+                        [llvm_v4f64_ty, llvm_v4f64_ty, llvm_v4f64_ty],
+                        [IntrNoMem]>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// XOP
+
+  def int_x86_xop_vpermil2pd : GCCBuiltin<"__builtin_ia32_vpermil2pd">,
+              Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty,
+                                          llvm_v2f64_ty, llvm_i8_ty],
+                        [IntrNoMem]>;
+
+  def int_x86_xop_vpermil2pd_256 :
+              GCCBuiltin<"__builtin_ia32_vpermil2pd256">,
+              Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty, llvm_v4f64_ty,
+                                          llvm_v4f64_ty, llvm_i8_ty],
+                        [IntrNoMem]>;
+
+  def int_x86_xop_vpermil2ps : GCCBuiltin<"__builtin_ia32_vpermil2ps">,
+              Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty,
+                                          llvm_v4f32_ty, llvm_i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpermil2ps_256 :
+              GCCBuiltin<"__builtin_ia32_vpermil2ps256">,
+              Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty, llvm_v8f32_ty,
+                                          llvm_v8f32_ty, llvm_i8_ty],
+                        [IntrNoMem]>;
+
+  def int_x86_xop_vfrcz_pd :
+              GCCBuiltin<"__builtin_ia32_vfrczpd">,
+              Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty], [IntrNoMem]>;
+  def int_x86_xop_vfrcz_ps :
+              GCCBuiltin<"__builtin_ia32_vfrczps">,
+              Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty], [IntrNoMem]>;
+  def int_x86_xop_vfrcz_sd :
+              GCCBuiltin<"__builtin_ia32_vfrczsd">,
+              Intrinsic<[llvm_v2f64_ty], [llvm_v2f64_ty, llvm_v2f64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vfrcz_ss :
+              GCCBuiltin<"__builtin_ia32_vfrczss">,
+              Intrinsic<[llvm_v4f32_ty], [llvm_v4f32_ty, llvm_v4f32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vfrcz_pd_256 :
+              GCCBuiltin<"__builtin_ia32_vfrczpd256">,
+              Intrinsic<[llvm_v4f64_ty], [llvm_v4f64_ty], [IntrNoMem]>;
+  def int_x86_xop_vfrcz_ps_256 :
+              GCCBuiltin<"__builtin_ia32_vfrczps256">,
+              Intrinsic<[llvm_v8f32_ty], [llvm_v8f32_ty], [IntrNoMem]>;
+  def int_x86_xop_vpcmov :
+              GCCBuiltin<"__builtin_ia32_vpcmov">,
+              Intrinsic<[llvm_v2i64_ty],
+                        [llvm_v2i64_ty, llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcmov_256 :
+              GCCBuiltin<"__builtin_ia32_vpcmov_256">,
+              Intrinsic<[llvm_v4i64_ty],
+                        [llvm_v4i64_ty, llvm_v4i64_ty, llvm_v4i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomeqb :
+              GCCBuiltin<"__builtin_ia32_vpcomeqb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomeqw :
+              GCCBuiltin<"__builtin_ia32_vpcomeqw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomeqd :
+              GCCBuiltin<"__builtin_ia32_vpcomeqd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomeqq :
+              GCCBuiltin<"__builtin_ia32_vpcomeqq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomequb :
+              GCCBuiltin<"__builtin_ia32_vpcomequb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomequd :
+              GCCBuiltin<"__builtin_ia32_vpcomequd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomequq :
+              GCCBuiltin<"__builtin_ia32_vpcomequq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomequw :
+              GCCBuiltin<"__builtin_ia32_vpcomequw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalseb :
+              GCCBuiltin<"__builtin_ia32_vpcomfalseb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalsed :
+              GCCBuiltin<"__builtin_ia32_vpcomfalsed">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalseq :
+              GCCBuiltin<"__builtin_ia32_vpcomfalseq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalseub :
+              GCCBuiltin<"__builtin_ia32_vpcomfalseub">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalseud :
+              GCCBuiltin<"__builtin_ia32_vpcomfalseud">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalseuq :
+              GCCBuiltin<"__builtin_ia32_vpcomfalseuq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalseuw :
+              GCCBuiltin<"__builtin_ia32_vpcomfalseuw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomfalsew :
+              GCCBuiltin<"__builtin_ia32_vpcomfalsew">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgeb :
+              GCCBuiltin<"__builtin_ia32_vpcomgeb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomged :
+              GCCBuiltin<"__builtin_ia32_vpcomged">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgeq :
+              GCCBuiltin<"__builtin_ia32_vpcomgeq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgeub :
+              GCCBuiltin<"__builtin_ia32_vpcomgeub">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgeud :
+              GCCBuiltin<"__builtin_ia32_vpcomgeud">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgeuq :
+              GCCBuiltin<"__builtin_ia32_vpcomgeuq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgeuw :
+              GCCBuiltin<"__builtin_ia32_vpcomgeuw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgew :
+              GCCBuiltin<"__builtin_ia32_vpcomgew">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtb :
+              GCCBuiltin<"__builtin_ia32_vpcomgtb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtd :
+              GCCBuiltin<"__builtin_ia32_vpcomgtd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtq :
+              GCCBuiltin<"__builtin_ia32_vpcomgtq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtub :
+              GCCBuiltin<"__builtin_ia32_vpcomgtub">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtud :
+              GCCBuiltin<"__builtin_ia32_vpcomgtud">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtuq :
+              GCCBuiltin<"__builtin_ia32_vpcomgtuq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtuw :
+              GCCBuiltin<"__builtin_ia32_vpcomgtuw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomgtw :
+              GCCBuiltin<"__builtin_ia32_vpcomgtw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomleb :
+              GCCBuiltin<"__builtin_ia32_vpcomleb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomled :
+              GCCBuiltin<"__builtin_ia32_vpcomled">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomleq :
+              GCCBuiltin<"__builtin_ia32_vpcomleq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomleub :
+              GCCBuiltin<"__builtin_ia32_vpcomleub">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomleud :
+              GCCBuiltin<"__builtin_ia32_vpcomleud">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomleuq :
+              GCCBuiltin<"__builtin_ia32_vpcomleuq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomleuw :
+              GCCBuiltin<"__builtin_ia32_vpcomleuw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomlew :
+              GCCBuiltin<"__builtin_ia32_vpcomlew">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltb :
+              GCCBuiltin<"__builtin_ia32_vpcomltb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltd :
+              GCCBuiltin<"__builtin_ia32_vpcomltd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltq :
+              GCCBuiltin<"__builtin_ia32_vpcomltq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltub :
+              GCCBuiltin<"__builtin_ia32_vpcomltub">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltud :
+              GCCBuiltin<"__builtin_ia32_vpcomltud">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltuq :
+              GCCBuiltin<"__builtin_ia32_vpcomltuq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltuw :
+              GCCBuiltin<"__builtin_ia32_vpcomltuw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomltw :
+              GCCBuiltin<"__builtin_ia32_vpcomltw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomneb :
+              GCCBuiltin<"__builtin_ia32_vpcomneb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomned :
+              GCCBuiltin<"__builtin_ia32_vpcomned">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomneq :
+              GCCBuiltin<"__builtin_ia32_vpcomneq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomneub :
+              GCCBuiltin<"__builtin_ia32_vpcomneub">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomneud :
+              GCCBuiltin<"__builtin_ia32_vpcomneud">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomneuq :
+              GCCBuiltin<"__builtin_ia32_vpcomneuq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomneuw :
+              GCCBuiltin<"__builtin_ia32_vpcomneuw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomnew :
+              GCCBuiltin<"__builtin_ia32_vpcomnew">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtrueb :
+              GCCBuiltin<"__builtin_ia32_vpcomtrueb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtrued :
+              GCCBuiltin<"__builtin_ia32_vpcomtrued">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtrueq :
+              GCCBuiltin<"__builtin_ia32_vpcomtrueq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtrueub :
+              GCCBuiltin<"__builtin_ia32_vpcomtrueub">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtrueud :
+              GCCBuiltin<"__builtin_ia32_vpcomtrueud">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtrueuq :
+              GCCBuiltin<"__builtin_ia32_vpcomtrueuq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtrueuw :
+              GCCBuiltin<"__builtin_ia32_vpcomtrueuw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpcomtruew :
+              GCCBuiltin<"__builtin_ia32_vpcomtruew">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vphaddbd :
+              GCCBuiltin<"__builtin_ia32_vphaddbd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddbq :
+              GCCBuiltin<"__builtin_ia32_vphaddbq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddbw :
+              GCCBuiltin<"__builtin_ia32_vphaddbw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_xop_vphadddq :
+              GCCBuiltin<"__builtin_ia32_vphadddq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddubd :
+              GCCBuiltin<"__builtin_ia32_vphaddubd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddubq :
+              GCCBuiltin<"__builtin_ia32_vphaddubq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddubw :
+              GCCBuiltin<"__builtin_ia32_vphaddubw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddudq :
+              GCCBuiltin<"__builtin_ia32_vphaddudq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+  def int_x86_xop_vphadduwd :
+              GCCBuiltin<"__builtin_ia32_vphadduwd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_xop_vphadduwq :
+              GCCBuiltin<"__builtin_ia32_vphadduwq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddwd :
+              GCCBuiltin<"__builtin_ia32_vphaddwd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_xop_vphaddwq :
+              GCCBuiltin<"__builtin_ia32_vphaddwq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_xop_vphsubbw :
+              GCCBuiltin<"__builtin_ia32_vphsubbw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v16i8_ty], [IntrNoMem]>;
+  def int_x86_xop_vphsubdq :
+              GCCBuiltin<"__builtin_ia32_vphsubdq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v4i32_ty], [IntrNoMem]>;
+  def int_x86_xop_vphsubwd :
+              GCCBuiltin<"__builtin_ia32_vphsubwd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_xop_vpmacsdd :
+              GCCBuiltin<"__builtin_ia32_vpmacsdd">,
+              Intrinsic<[llvm_v4i32_ty],
+                        [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacsdqh :
+              GCCBuiltin<"__builtin_ia32_vpmacsdqh">,
+              Intrinsic<[llvm_v2i64_ty],
+                        [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacsdql :
+              GCCBuiltin<"__builtin_ia32_vpmacsdql">,
+              Intrinsic<[llvm_v2i64_ty],
+                        [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacssdd :
+              GCCBuiltin<"__builtin_ia32_vpmacssdd">,
+              Intrinsic<[llvm_v4i32_ty],
+                        [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacssdqh :
+              GCCBuiltin<"__builtin_ia32_vpmacssdqh">,
+              Intrinsic<[llvm_v2i64_ty],
+                        [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacssdql :
+              GCCBuiltin<"__builtin_ia32_vpmacssdql">,
+              Intrinsic<[llvm_v2i64_ty],
+                        [llvm_v4i32_ty, llvm_v4i32_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacsswd :
+              GCCBuiltin<"__builtin_ia32_vpmacsswd">,
+              Intrinsic<[llvm_v4i32_ty],
+                        [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacssww :
+              GCCBuiltin<"__builtin_ia32_vpmacssww">,
+              Intrinsic<[llvm_v8i16_ty],
+                        [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacswd :
+              GCCBuiltin<"__builtin_ia32_vpmacswd">,
+              Intrinsic<[llvm_v4i32_ty],
+                        [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmacsww :
+              GCCBuiltin<"__builtin_ia32_vpmacsww">,
+              Intrinsic<[llvm_v8i16_ty],
+                        [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmadcsswd :
+              GCCBuiltin<"__builtin_ia32_vpmadcsswd">,
+              Intrinsic<[llvm_v4i32_ty],
+                        [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpmadcswd :
+              GCCBuiltin<"__builtin_ia32_vpmadcswd">,
+              Intrinsic<[llvm_v4i32_ty],
+                        [llvm_v8i16_ty, llvm_v8i16_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpperm :
+              GCCBuiltin<"__builtin_ia32_vpperm">,
+              Intrinsic<[llvm_v16i8_ty],
+                        [llvm_v16i8_ty, llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vprotb :
+              GCCBuiltin<"__builtin_ia32_vprotb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vprotd :
+              GCCBuiltin<"__builtin_ia32_vprotd">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vprotq :
+              GCCBuiltin<"__builtin_ia32_vprotq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vprotw :
+              GCCBuiltin<"__builtin_ia32_vprotw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshab :
+              GCCBuiltin<"__builtin_ia32_vpshab">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshad :
+              GCCBuiltin<"__builtin_ia32_vpshad">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshaq :
+              GCCBuiltin<"__builtin_ia32_vpshaq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshaw :
+              GCCBuiltin<"__builtin_ia32_vpshaw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshlb :
+              GCCBuiltin<"__builtin_ia32_vpshlb">,
+              Intrinsic<[llvm_v16i8_ty], [llvm_v16i8_ty, llvm_v16i8_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshld :
+              GCCBuiltin<"__builtin_ia32_vpshld">,
+              Intrinsic<[llvm_v4i32_ty], [llvm_v4i32_ty, llvm_v4i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshlq :
+              GCCBuiltin<"__builtin_ia32_vpshlq">,
+              Intrinsic<[llvm_v2i64_ty], [llvm_v2i64_ty, llvm_v2i64_ty],
+                        [IntrNoMem]>;
+  def int_x86_xop_vpshlw :
+              GCCBuiltin<"__builtin_ia32_vpshlw">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8i16_ty, llvm_v8i16_ty],
+                        [IntrNoMem]>;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // MMX
=20
 // Empty MMX state op.
@@ -1587,13 +2593,13 @@
 let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
   def int_x86_mmx_pcmpeq_b : GCCBuiltin<"__builtin_ia32_pcmpeqb">,
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
-                         llvm_x86mmx_ty], [IntrNoMem]>;
+                         llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
   def int_x86_mmx_pcmpeq_w : GCCBuiltin<"__builtin_ia32_pcmpeqw">,
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
-                         llvm_x86mmx_ty], [IntrNoMem]>;
+                         llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
   def int_x86_mmx_pcmpeq_d : GCCBuiltin<"__builtin_ia32_pcmpeqd">,
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
-                         llvm_x86mmx_ty], [IntrNoMem]>;
+                         llvm_x86mmx_ty], [IntrNoMem, Commutative]>;
=20
   def int_x86_mmx_pcmpgt_b : GCCBuiltin<"__builtin_ia32_pcmpgtb">,
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
@@ -1629,3 +2635,63 @@
               Intrinsic<[llvm_x86mmx_ty], [llvm_x86mmx_ty,
                         llvm_i32_ty, llvm_i32_ty], [IntrNoMem]>;
 }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// BMI
+
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_bmi_bextr_32 : GCCBuiltin<"__builtin_ia32_bextr_u32">,
+              Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNo=
Mem]>;
+  def int_x86_bmi_bextr_64 : GCCBuiltin<"__builtin_ia32_bextr_u64">,
+              Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNo=
Mem]>;
+  def int_x86_bmi_bzhi_32 : GCCBuiltin<"__builtin_ia32_bzhi_si">,
+              Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNo=
Mem]>;
+  def int_x86_bmi_bzhi_64 : GCCBuiltin<"__builtin_ia32_bzhi_di">,
+              Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNo=
Mem]>;
+  def int_x86_bmi_pdep_32 : GCCBuiltin<"__builtin_ia32_pdep_si">,
+              Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNo=
Mem]>;
+  def int_x86_bmi_pdep_64 : GCCBuiltin<"__builtin_ia32_pdep_di">,
+              Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNo=
Mem]>;
+  def int_x86_bmi_pext_32 : GCCBuiltin<"__builtin_ia32_pext_si">,
+              Intrinsic<[llvm_i32_ty], [llvm_i32_ty, llvm_i32_ty], [IntrNo=
Mem]>;
+  def int_x86_bmi_pext_64 : GCCBuiltin<"__builtin_ia32_pext_di">,
+              Intrinsic<[llvm_i64_ty], [llvm_i64_ty, llvm_i64_ty], [IntrNo=
Mem]>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// FS/GS Base
+
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_rdfsbase_32 : GCCBuiltin<"__builtin_ia32_rdfsbase32">,
+              Intrinsic<[llvm_i32_ty], []>;
+  def int_x86_rdgsbase_32 : GCCBuiltin<"__builtin_ia32_rdgsbase32">,
+              Intrinsic<[llvm_i32_ty], []>;
+  def int_x86_rdfsbase_64 : GCCBuiltin<"__builtin_ia32_rdfsbase64">,
+              Intrinsic<[llvm_i64_ty], []>;
+  def int_x86_rdgsbase_64 : GCCBuiltin<"__builtin_ia32_rdgsbase64">,
+              Intrinsic<[llvm_i64_ty], []>;
+  def int_x86_wrfsbase_32 : GCCBuiltin<"__builtin_ia32_wrfsbase32">,
+              Intrinsic<[], [llvm_i32_ty]>;
+  def int_x86_wrgsbase_32 : GCCBuiltin<"__builtin_ia32_wrgsbase32">,
+              Intrinsic<[], [llvm_i32_ty]>;
+  def int_x86_wrfsbase_64 : GCCBuiltin<"__builtin_ia32_wrfsbase64">,
+              Intrinsic<[], [llvm_i64_ty]>;
+  def int_x86_wrgsbase_64 : GCCBuiltin<"__builtin_ia32_wrgsbase64">,
+              Intrinsic<[], [llvm_i64_ty]>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Half float conversion
+
+let TargetPrefix =3D "x86" in {  // All intrinsics start with "llvm.x86.".
+  def int_x86_vcvtph2ps_128 : GCCBuiltin<"__builtin_ia32_vcvtph2ps">,
+              Intrinsic<[llvm_v4f32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_vcvtph2ps_256 : GCCBuiltin<"__builtin_ia32_vcvtph2ps256">,
+              Intrinsic<[llvm_v8f32_ty], [llvm_v8i16_ty], [IntrNoMem]>;
+  def int_x86_vcvtps2ph_128 : GCCBuiltin<"__builtin_ia32_vcvtps2ph">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v4f32_ty, llvm_i32_ty],
+                        [IntrNoMem]>;
+  def int_x86_vcvtps2ph_256 : GCCBuiltin<"__builtin_ia32_vcvtps2ph256">,
+              Intrinsic<[llvm_v8i16_ty], [llvm_v8f32_ty, llvm_i32_ty],
+                        [IntrNoMem]>;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/LLVMCon=
text.h
--- a/head/contrib/llvm/include/llvm/LLVMContext.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/LLVMContext.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -19,6 +19,7 @@
=20
 class LLVMContextImpl;
 class StringRef;
+class Twine;
 class Instruction;
 class Module;
 class SMDiagnostic;
@@ -40,7 +41,9 @@
   enum {
     MD_dbg =3D 0,  // "dbg"
     MD_tbaa =3D 1, // "tbaa"
-    MD_prof =3D 2  // "prof"
+    MD_prof =3D 2,  // "prof"
+    MD_fpaccuracy =3D 3,  // "fpaccuracy"
+    MD_range =3D 4 // "range"
   };
  =20
   /// getMDKindID - Return a unique non-zero ID for the specified metadata=
 kind.
@@ -79,9 +82,9 @@
   /// be prepared to drop the erroneous construct on the floor and "not cr=
ash".
   /// The generated code need not be correct.  The error message will be
   /// implicitly prefixed with "error: " and should not end with a ".".
-  void emitError(unsigned LocCookie, StringRef ErrorStr);
-  void emitError(const Instruction *I, StringRef ErrorStr);
-  void emitError(StringRef ErrorStr);
+  void emitError(unsigned LocCookie, const Twine &ErrorStr);
+  void emitError(const Instruction *I, const Twine &ErrorStr);
+  void emitError(const Twine &ErrorStr);
=20
 private:
   // DO NOT IMPLEMENT
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/LinkAll=
Passes.h
--- a/head/contrib/llvm/include/llvm/LinkAllPasses.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/LinkAllPasses.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -31,6 +31,7 @@
 #include "llvm/Transforms/Instrumentation.h"
 #include "llvm/Transforms/IPO.h"
 #include "llvm/Transforms/Scalar.h"
+#include "llvm/Transforms/Vectorize.h"
 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
 #include <cstdlib>
=20
@@ -69,7 +70,7 @@
       (void) llvm::createEdgeProfilerPass();
       (void) llvm::createOptimalEdgeProfilerPass();
       (void) llvm::createPathProfilerPass();
-      (void) llvm::createGCOVProfilerPass(true, true, false);
+      (void) llvm::createGCOVProfilerPass();
       (void) llvm::createFunctionInliningPass();
       (void) llvm::createAlwaysInlinerPass();
       (void) llvm::createGlobalDCEPass();
@@ -97,6 +98,7 @@
       (void) llvm::createNoAAPass();
       (void) llvm::createNoProfileInfoPass();
       (void) llvm::createObjCARCAliasAnalysisPass();
+      (void) llvm::createObjCARCAPElimPass();
       (void) llvm::createObjCARCExpandPass();
       (void) llvm::createObjCARCContractPass();
       (void) llvm::createObjCARCOptPass();
@@ -150,6 +152,7 @@
       (void) llvm::createCorrelatedValuePropagationPass();
       (void) llvm::createMemDepPrinter();
       (void) llvm::createInstructionSimplifierPass();
+      (void) llvm::createBBVectorizePass();
=20
       (void)new llvm::IntervalPartition();
       (void)new llvm::FindUsedTypes();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Linker.h
--- a/head/contrib/llvm/include/llvm/Linker.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Linker.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,14 +15,15 @@
 #define LLVM_LINKER_H
=20
 #include <memory>
+#include <string>
 #include <vector>
-#include "llvm/ADT/StringRef.h"
=20
 namespace llvm {
   namespace sys { class Path; }
=20
 class Module;
 class LLVMContext;
+class StringRef;
=20
 /// This class provides the core functionality of linking in LLVM. It reta=
ins a
 /// Module object which is the composite of the modules and libraries link=
ed
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCAs=
mBackend.h
--- a/head/contrib/llvm/include/llvm/MC/MCAsmBackend.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCAsmBackend.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -12,17 +12,20 @@
=20
 #include "llvm/MC/MCDirectives.h"
 #include "llvm/MC/MCFixup.h"
-#include "llvm/MC/MCFixupKindInfo.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
=20
 namespace llvm {
+class MCAsmLayout;
+class MCAssembler;
 class MCELFObjectTargetWriter;
-class MCFixup;
+struct MCFixupKindInfo;
+class MCFragment;
 class MCInst;
+class MCInstFragment;
 class MCObjectWriter;
 class MCSection;
-template<typename T>
-class SmallVectorImpl;
+class MCValue;
 class raw_ostream;
=20
 /// MCAsmBackend - Generic interface to target specific assembler backends.
@@ -44,8 +47,8 @@
   /// createELFObjectTargetWriter - Create a new ELFObjectTargetWriter to =
enable
   /// non-standard ELFObjectWriters.
   virtual  MCELFObjectTargetWriter *createELFObjectTargetWriter() const {
-    assert(0 && "createELFObjectTargetWriter is not supported by asm backe=
nd");
-    return 0;
+    llvm_unreachable("createELFObjectTargetWriter is not supported by asm "
+                     "backend");
   }
=20
   /// hasReliableSymbolDifference - Check whether this target implements
@@ -85,12 +88,21 @@
   /// getFixupKindInfo - Get information on a fixup kind.
   virtual const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const;
=20
+  /// processFixupValue - Target hook to adjust the literal value of a fix=
up
+  /// if necessary. IsResolved signals whether the caller believes a reloc=
ation
+  /// is needed; the target can modify the value. The default does nothing.
+  virtual void processFixupValue(const MCAssembler &Asm,
+                                 const MCAsmLayout &Layout,
+                                 const MCFixup &Fixup, const MCFragment *D=
F,
+                                 MCValue &Target, uint64_t &Value,
+                                 bool &IsResolved) {}
+
   /// @}
=20
-  /// ApplyFixup - Apply the \arg Value for given \arg Fixup into the prov=
ided
+  /// applyFixup - Apply the \arg Value for given \arg Fixup into the prov=
ided
   /// data fragment, at the offset specified by the fixup and following the
   /// fixup kind as appropriate.
-  virtual void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataS=
ize,
+  virtual void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataS=
ize,
                           uint64_t Value) const =3D 0;
=20
   /// @}
@@ -98,11 +110,18 @@
   /// @name Target Relaxation Interfaces
   /// @{
=20
-  /// MayNeedRelaxation - Check whether the given instruction may need
+  /// mayNeedRelaxation - Check whether the given instruction may need
   /// relaxation.
   ///
   /// \param Inst - The instruction to test.
-  virtual bool MayNeedRelaxation(const MCInst &Inst) const =3D 0;
+  virtual bool mayNeedRelaxation(const MCInst &Inst) const =3D 0;
+
+  /// fixupNeedsRelaxation - Target specific predicate for whether a given
+  /// fixup requires the associated instruction to be relaxed.
+  virtual bool fixupNeedsRelaxation(const MCFixup &Fixup,
+                                    uint64_t Value,
+                                    const MCInstFragment *DF,
+                                    const MCAsmLayout &Layout) const =3D 0;
=20
   /// RelaxInstruction - Relax the instruction in the given fragment to th=
e next
   /// wider instruction.
@@ -110,20 +129,20 @@
   /// \param Inst - The instruction to relax, which may be the same as the
   /// output.
   /// \parm Res [output] - On return, the relaxed instruction.
-  virtual void RelaxInstruction(const MCInst &Inst, MCInst &Res) const =3D=
 0;
+  virtual void relaxInstruction(const MCInst &Inst, MCInst &Res) const =3D=
 0;
=20
   /// @}
=20
-  /// WriteNopData - Write an (optimal) nop sequence of Count bytes to the=
 given
+  /// writeNopData - Write an (optimal) nop sequence of Count bytes to the=
 given
   /// output. If the target cannot generate such a sequence, it should ret=
urn an
   /// error.
   ///
   /// \return - True on success.
-  virtual bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const =3D =
0;
+  virtual bool writeNopData(uint64_t Count, MCObjectWriter *OW) const =3D =
0;
=20
-  /// HandleAssemblerFlag - Handle any target-specific assembler flags.
+  /// handleAssemblerFlag - Handle any target-specific assembler flags.
   /// By default, do nothing.
-  virtual void HandleAssemblerFlag(MCAssemblerFlag Flag) {}
+  virtual void handleAssemblerFlag(MCAssemblerFlag Flag) {}
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCAs=
mInfo.h
--- a/head/contrib/llvm/include/llvm/MC/MCAsmInfo.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCAsmInfo.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -36,10 +36,6 @@
     enum LCOMMType { None, NoAlignment, ByteAlignment };
   }
=20
-  namespace Structors {
-    enum OutputOrder { None, PriorityOrder, ReversePriorityOrder };
-  }
-
   /// MCAsmInfo - This class is intended to be used as a base class for asm
   /// properties and features specific to the target.
   class MCAsmInfo {
@@ -47,7 +43,7 @@
     //=3D=3D=3D-----------------------------------------------------------=
-------=3D=3D=3D//
     // Properties to be set by the target writer, used to configure asm pr=
inter.
     //
-   =20
+
     /// PointerSize - Pointer size in bytes.
     ///               Default is 4.
     unsigned PointerSize;
@@ -72,11 +68,6 @@
     /// the macho-specific .tbss directive for emitting thread local BSS S=
ymbols
     bool HasMachoTBSSDirective;                 // Default is false.
=20
-    /// StructorOutputOrder - Whether the static ctor/dtor list should be =
output
-    /// in no particular order, in order of increasing priority or the rev=
erse:
-    /// in order of decreasing priority (the default).
-    Structors::OutputOrder StructorOutputOrder; // Default is reverse orde=
r.
-
     /// HasStaticCtorDtorReferenceInStaticMode - True if the compiler shou=
ld
     /// emit a ".reference .constructors_used" or ".reference .destructors=
_used"
     /// directive after the a static ctor/dtor list.  This directive is on=
ly
@@ -152,6 +143,10 @@
     /// symbol names.  This defaults to true.
     bool AllowPeriodsInName;
=20
+    /// AllowUTF8 - This is true if the assembler accepts UTF-8 input.
+    // FIXME: Make this a more general encoding setting?
+    bool AllowUTF8;
+
     //=3D=3D=3D--- Data Emission Directives ------------------------------=
-------=3D=3D=3D//
=20
     /// ZeroDirective - this should be set to the directive used to get so=
me
@@ -189,6 +184,11 @@
     const char *JT32Begin;                   // Defaults to "$a."
     bool SupportsDataRegions;
=20
+    /// GPRel64Directive - if non-null, a directive that is used to emit a=
 word
+    /// which should be relocated as a 64-bit GP-relative offset, e.g. .gp=
dword
+    /// on Mips.
+    const char *GPRel64Directive;            // Defaults to NULL.
+
     /// GPRel32Directive - if non-null, a directive that is used to emit a=
 word
     /// which should be relocated as a 32-bit GP-relative offset, e.g. .gp=
word
     /// on Mips or .gprel32 on Alpha.
@@ -323,13 +323,17 @@
     const char* DwarfSectionOffsetDirective; // Defaults to NULL
=20
     /// DwarfRequiresRelocationForSectionOffset - True if we need to produ=
ce a
-    // relocation when we want a section offset in dwarf.
+    /// relocation when we want a section offset in dwarf.
     bool DwarfRequiresRelocationForSectionOffset;  // Defaults to true;
=20
-    // DwarfUsesLabelOffsetDifference - True if Dwarf2 output can
-    // use EmitLabelOffsetDifference.
+    /// DwarfUsesLabelOffsetDifference - True if Dwarf2 output can
+    /// use EmitLabelOffsetDifference.
     bool DwarfUsesLabelOffsetForRanges;
=20
+    /// DwarfUsesRelocationsForStringPool - True if this Dwarf output must=
 use
+    /// relocations to refer to entries in the string pool.
+    bool DwarfUsesRelocationsForStringPool;
+
     /// DwarfRegNumForCFI - True if dwarf register numbers are printed
     /// instead of symbolic register names in .cfi_* directives.
     bool DwarfRegNumForCFI;  // Defaults to false;
@@ -381,6 +385,7 @@
     const char *getData64bitsDirective(unsigned AS =3D 0) const {
       return AS =3D=3D 0 ? Data64bitsDirective : getDataASDirective(64, AS=
);
     }
+    const char *getGPRel64Directive() const { return GPRel64Directive; }
     const char *getGPRel32Directive() const { return GPRel32Directive; }
=20
     /// [Code|Data]Begin label name accessors.
@@ -424,9 +429,6 @@
     //
     bool hasMachoZeroFillDirective() const { return HasMachoZeroFillDirect=
ive; }
     bool hasMachoTBSSDirective() const { return HasMachoTBSSDirective; }
-    Structors::OutputOrder getStructorOutputOrder() const {
-      return StructorOutputOrder;
-    }
     bool hasStaticCtorDtorReferenceInStaticMode() const {
       return HasStaticCtorDtorReferenceInStaticMode;
     }
@@ -487,6 +489,9 @@
     bool doesAllowPeriodsInName() const {
       return AllowPeriodsInName;
     }
+    bool doesAllowUTF8() const {
+      return AllowUTF8;
+    }
     const char *getZeroDirective() const {
       return ZeroDirective;
     }
@@ -554,7 +559,7 @@
          ExceptionsType =3D=3D ExceptionHandling::ARM ||
          ExceptionsType =3D=3D ExceptionHandling::Win64);
     }
-    bool doesDwarfUsesInlineInfoSection() const {
+    bool doesDwarfUseInlineInfoSection() const {
       return DwarfUsesInlineInfoSection;
     }
     const char *getDwarfSectionOffsetDirective() const {
@@ -563,9 +568,12 @@
     bool doesDwarfRequireRelocationForSectionOffset() const {
       return DwarfRequiresRelocationForSectionOffset;
     }
-    bool doesDwarfUsesLabelOffsetForRanges() const {
+    bool doesDwarfUseLabelOffsetForRanges() const {
       return DwarfUsesLabelOffsetForRanges;
     }
+    bool doesDwarfUseRelocationsForStringPool() const {
+      return DwarfUsesRelocationsForStringPool;
+    }
     bool useDwarfRegNumForCFI() const {
       return DwarfRegNumForCFI;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCAs=
mInfoCOFF.h
--- a/head/contrib/llvm/include/llvm/MC/MCAsmInfoCOFF.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCAsmInfoCOFF.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -14,9 +14,21 @@
=20
 namespace llvm {
   class MCAsmInfoCOFF : public MCAsmInfo {
+    virtual void anchor();
   protected:
     explicit MCAsmInfoCOFF();
-     =20
+  };
+
+  class MCAsmInfoMicrosoft : public MCAsmInfoCOFF {
+    virtual void anchor();
+  protected:
+    explicit MCAsmInfoMicrosoft();
+  };
+
+  class MCAsmInfoGNUCOFF : public MCAsmInfoCOFF {
+    virtual void anchor();
+  protected:
+    explicit MCAsmInfoGNUCOFF();
   };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCAs=
mInfoDarwin.h
--- a/head/contrib/llvm/include/llvm/MC/MCAsmInfoDarwin.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCAsmInfoDarwin.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,9 @@
 #include "llvm/MC/MCAsmInfo.h"
=20
 namespace llvm {
-  struct MCAsmInfoDarwin : public MCAsmInfo {
+  class MCAsmInfoDarwin : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit MCAsmInfoDarwin();
   };
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCAs=
mLayout.h
--- a/head/contrib/llvm/include/llvm/MC/MCAsmLayout.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCAsmLayout.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -10,6 +10,7 @@
 #ifndef LLVM_MC_MCASMLAYOUT_H
 #define LLVM_MC_MCASMLAYOUT_H
=20
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
=20
 namespace llvm {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCAs=
sembler.h
--- a/head/contrib/llvm/include/llvm/MC/MCAssembler.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCAssembler.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -25,7 +25,6 @@
 class raw_ostream;
 class MCAsmLayout;
 class MCAssembler;
-class MCBinaryExpr;
 class MCContext;
 class MCCodeEmitter;
 class MCExpr;
@@ -106,6 +105,7 @@
 };
=20
 class MCDataFragment : public MCFragment {
+  virtual void anchor();
   SmallString<32> Contents;
=20
   /// Fixups - The list of fixups in this fragment.
@@ -160,6 +160,8 @@
 // object with just the MCInst and a code size, then we should just change
 // MCDataFragment to have an optional MCInst at its end.
 class MCInstFragment : public MCFragment {
+  virtual void anchor();
+
   /// Inst - The instruction this is a fragment for.
   MCInst Inst;
=20
@@ -215,6 +217,8 @@
 };
=20
 class MCAlignFragment : public MCFragment {
+  virtual void anchor();
+
   /// Alignment - The alignment to ensure, in bytes.
   unsigned Alignment;
=20
@@ -263,6 +267,8 @@
 };
=20
 class MCFillFragment : public MCFragment {
+  virtual void anchor();
+
   /// Value - Value to use for filling bytes.
   int64_t Value;
=20
@@ -300,6 +306,8 @@
 };
=20
 class MCOrgFragment : public MCFragment {
+  virtual void anchor();
+
   /// Offset - The offset this fragment should start at.
   const MCExpr *Offset;
=20
@@ -327,6 +335,8 @@
 };
=20
 class MCLEBFragment : public MCFragment {
+  virtual void anchor();
+
   /// Value - The value this fragment should contain.
   const MCExpr *Value;
=20
@@ -358,6 +368,8 @@
 };
=20
 class MCDwarfLineAddrFragment : public MCFragment {
+  virtual void anchor();
+
   /// LineDelta - the value of the difference between the two line numbers
   /// between two .loc dwarf directives.
   int64_t LineDelta;
@@ -393,6 +405,8 @@
 };
=20
 class MCDwarfCallFrameFragment : public MCFragment {
+  virtual void anchor();
+
   /// AddrDelta - The expression for the difference of the two symbols that
   /// make up the address delta between two .cfi_* dwarf directives.
   const MCExpr *AddrDelta;
@@ -711,43 +725,44 @@
   /// \return Whether the fixup value was fully resolved. This is true if =
the
   /// \arg Value result is fixed, otherwise the value may change due to
   /// relocation.
-  bool EvaluateFixup(const MCAsmLayout &Layout,
+  bool evaluateFixup(const MCAsmLayout &Layout,
                      const MCFixup &Fixup, const MCFragment *DF,
                      MCValue &Target, uint64_t &Value) const;
=20
   /// Check whether a fixup can be satisfied, or whether it needs to be re=
laxed
   /// (increased in size, in order to hold its value correctly).
-  bool FixupNeedsRelaxation(const MCFixup &Fixup, const MCFragment *DF,
+  bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCInstFragment *DF,
                             const MCAsmLayout &Layout) const;
=20
   /// Check whether the given fragment needs relaxation.
-  bool FragmentNeedsRelaxation(const MCInstFragment *IF,
+  bool fragmentNeedsRelaxation(const MCInstFragment *IF,
                                const MCAsmLayout &Layout) const;
=20
-  /// LayoutOnce - Perform one layout iteration and return true if any off=
sets
+  /// layoutOnce - Perform one layout iteration and return true if any off=
sets
   /// were adjusted.
-  bool LayoutOnce(MCAsmLayout &Layout);
+  bool layoutOnce(MCAsmLayout &Layout);
=20
-  bool LayoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD);
+  bool layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD);
=20
-  bool RelaxInstruction(MCAsmLayout &Layout, MCInstFragment &IF);
+  bool relaxInstruction(MCAsmLayout &Layout, MCInstFragment &IF);
=20
-  bool RelaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
+  bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
=20
-  bool RelaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF=
);
-  bool RelaxDwarfCallFrameFragment(MCAsmLayout &Layout,
+  bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF=
);
+  bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
                                    MCDwarfCallFrameFragment &DF);
=20
-  /// FinishLayout - Finalize a layout, including fragment lowering.
-  void FinishLayout(MCAsmLayout &Layout);
+  /// finishLayout - Finalize a layout, including fragment lowering.
+  void finishLayout(MCAsmLayout &Layout);
=20
-  uint64_t HandleFixup(const MCAsmLayout &Layout,
+  uint64_t handleFixup(const MCAsmLayout &Layout,
                        MCFragment &F, const MCFixup &Fixup);
=20
 public:
   /// Compute the effective fragment size assuming it is laid out at the g=
iven
   /// \arg SectionAddress and \arg FragmentOffset.
-  uint64_t ComputeFragmentSize(const MCAsmLayout &Layout, const MCFragment=
 &F) const;
+  uint64_t computeFragmentSize(const MCAsmLayout &Layout,
+                               const MCFragment &F) const;
=20
   /// Find the symbol which defines the atom containing the given symbol, =
or
   /// null if there is no such symbol.
@@ -760,7 +775,7 @@
   bool isSymbolLinkerVisible(const MCSymbol &SD) const;
=20
   /// Emit the section contents using the given object writer.
-  void WriteSectionData(const MCSectionData *Section,
+  void writeSectionData(const MCSectionData *Section,
                         const MCAsmLayout &Layout) const;
=20
   /// Check whether a given symbol has been flagged with .thumb_func.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCCo=
deEmitter.h
--- a/head/contrib/llvm/include/llvm/MC/MCCodeEmitter.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCCodeEmitter.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -10,12 +10,8 @@
 #ifndef LLVM_MC_MCCODEEMITTER_H
 #define LLVM_MC_MCCODEEMITTER_H
=20
-#include "llvm/MC/MCFixup.h"
-
-#include <cassert>
-
 namespace llvm {
-class MCExpr;
+class MCFixup;
 class MCInst;
 class raw_ostream;
 template<typename T> class SmallVectorImpl;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCCo=
deGenInfo.h
--- a/head/contrib/llvm/include/llvm/MC/MCCodeGenInfo.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCCodeGenInfo.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -20,7 +20,7 @@
 namespace llvm {
=20
   class MCCodeGenInfo {
-    /// RelocationModel - Relocation model: statcic, pic, etc.
+    /// RelocationModel - Relocation model: static, pic, etc.
     ///
     Reloc::Model RelocationModel;
=20
@@ -28,13 +28,20 @@
     ///
     CodeModel::Model CMModel;
=20
+    /// OptLevel - Optimization level.
+    ///
+    CodeGenOpt::Level OptLevel;
+
   public:
     void InitMCCodeGenInfo(Reloc::Model RM =3D Reloc::Default,
-                           CodeModel::Model CM =3D CodeModel::Default);
+                           CodeModel::Model CM =3D CodeModel::Default,
+                           CodeGenOpt::Level OL =3D CodeGenOpt::Default);
=20
     Reloc::Model getRelocationModel() const { return RelocationModel; }
=20
     CodeModel::Model getCodeModel() const { return CMModel; }
+
+    CodeGenOpt::Level getOptLevel() const { return OptLevel; }
   };
 } // namespace llvm
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCCo=
ntext.h
--- a/head/contrib/llvm/include/llvm/MC/MCContext.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCContext.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -15,6 +15,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/Allocator.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/raw_ostream.h"
 #include <vector> // FIXME: Shouldn't be needed.
=20
@@ -29,6 +30,7 @@
   class MCObjectFileInfo;
   class MCRegisterInfo;
   class MCLineSection;
+  class SMLoc;
   class StringRef;
   class Twine;
   class MCSectionMachO;
@@ -43,6 +45,8 @@
   public:
     typedef StringMap<MCSymbol*, BumpPtrAllocator&> SymbolTable;
   private:
+    /// The SourceMgr for this object, if any.
+    const SourceMgr *SrcMgr;
=20
     /// The MCAsmInfo for this target.
     const MCAsmInfo &MAI;
@@ -98,6 +102,27 @@
     MCDwarfLoc CurrentDwarfLoc;
     bool DwarfLocSeen;
=20
+    /// Generate dwarf debugging info for assembly source files.
+    bool GenDwarfForAssembly;
+
+    /// The current dwarf file number when generate dwarf debugging info f=
or
+    /// assembly source files.
+    unsigned GenDwarfFileNumber;
+
+    /// The default initial text section that we generate dwarf debugging =
line
+    /// info for when generating dwarf assembly source files.
+    const MCSection *GenDwarfSection;
+    /// Symbols created for the start and end of this section.
+    MCSymbol *GenDwarfSectionStartSym, *GenDwarfSectionEndSym;
+
+    /// The information gathered from labels that will have dwarf label
+    /// entries when generating dwarf assembly source files.
+    std::vector<const MCGenDwarfLabelEntry *> MCGenDwarfLabelEntries;
+
+    /// The string to embed in the debug information for the compile unit,=
 if
+    /// non-empty.
+    StringRef DwarfDebugFlags;
+
     /// Honor temporary labels, this is useful for debugging semantic
     /// differences between temporary and non-temporary labels (primarily =
on
     /// Darwin).
@@ -116,9 +141,11 @@
=20
   public:
     explicit MCContext(const MCAsmInfo &MAI, const MCRegisterInfo &MRI,
-                       const MCObjectFileInfo *MOFI);
+                       const MCObjectFileInfo *MOFI, const SourceMgr *Mgr =
=3D 0);
     ~MCContext();
=20
+    const SourceMgr *getSourceManager() const { return SrcMgr; }
+
     const MCAsmInfo &getAsmInfo() const { return MAI; }
=20
     const MCRegisterInfo &getRegisterInfo() const { return MRI; }
@@ -204,7 +231,8 @@
     /// @{
=20
     /// GetDwarfFile - creates an entry in the dwarf file and directory ta=
bles.
-    unsigned GetDwarfFile(StringRef FileName, unsigned FileNumber);
+    unsigned GetDwarfFile(StringRef Directory, StringRef FileName,
+                          unsigned FileNumber);
=20
     bool isValidDwarfFileNumber(unsigned FileNumber);
=20
@@ -251,6 +279,31 @@
     bool getDwarfLocSeen() { return DwarfLocSeen; }
     const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
=20
+    bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
+    void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly =3D Valu=
e; }
+    unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
+    unsigned nextGenDwarfFileNumber() { return ++GenDwarfFileNumber; }
+    const MCSection *getGenDwarfSection() { return GenDwarfSection; }
+    void setGenDwarfSection(const MCSection *Sec) { GenDwarfSection =3D Se=
c; }
+    MCSymbol *getGenDwarfSectionStartSym() { return GenDwarfSectionStartSy=
m; }
+    void setGenDwarfSectionStartSym(MCSymbol *Sym) {
+      GenDwarfSectionStartSym =3D Sym;
+    }
+    MCSymbol *getGenDwarfSectionEndSym() { return GenDwarfSectionEndSym; }
+    void setGenDwarfSectionEndSym(MCSymbol *Sym) {
+      GenDwarfSectionEndSym =3D Sym;
+    }
+    const std::vector<const MCGenDwarfLabelEntry *>
+      &getMCGenDwarfLabelEntries() const {
+      return MCGenDwarfLabelEntries;
+    }
+    void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry *E) {
+      MCGenDwarfLabelEntries.push_back(E);
+    }
+
+    void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags =3D S; }
+    StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
+
     /// @}
=20
     char *getSecureLogFile() { return SecureLogFile; }
@@ -268,6 +321,11 @@
     }
     void Deallocate(void *Ptr) {
     }
+
+    // Unrecoverable error has occured. Display the best diagnostic we can
+    // and bail via exit(1). For now, most MC backend errors are unrecover=
able.
+    // FIXME: We should really do something about that.
+    LLVM_ATTRIBUTE_NORETURN void FatalError(SMLoc L, const Twine &Msg);
   };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCDi=
sassembler.h
--- a/head/contrib/llvm/include/llvm/MC/MCDisassembler.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCDisassembler.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -90,7 +90,7 @@
   /// @return         - An array of instruction information, with one entr=
y for
   ///                   each MCInst opcode this disassembler returns.
   ///                   NULL if there is no info for this target.
-  virtual EDInstInfo   *getEDInfo() const { return (EDInstInfo*)0; }
+  virtual const EDInstInfo   *getEDInfo() const { return (EDInstInfo*)0; }
=20
 private:
   //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCDw=
arf.h
--- a/head/contrib/llvm/include/llvm/MC/MCDwarf.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/include/llvm/MC/MCDwarf.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -17,20 +17,18 @@
=20
 #include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MachineLocation.h"
-#include "llvm/MC/MCObjectWriter.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Dwarf.h"
 #include <vector>
=20
 namespace llvm {
   class MCContext;
-  class MCExpr;
+  class MCObjectWriter;
   class MCSection;
-  class MCSectionData;
   class MCStreamer;
   class MCSymbol;
-  class MCObjectStreamer;
-  class raw_ostream;
+  class SourceMgr;
+  class SMLoc;
=20
   /// MCDwarfFile - Instances of this class represent the name of the dwarf
   /// .file directive and its associated dwarf file number in the MC file,
@@ -210,7 +208,7 @@
     //
     // This emits the Dwarf file and the line tables.
     //
-    static void Emit(MCStreamer *MCOS);
+    static const MCSymbol *Emit(MCStreamer *MCOS);
   };
=20
   class MCDwarfLineAddr {
@@ -227,23 +225,63 @@
                       int64_t LineDelta, uint64_t AddrDelta);
   };
=20
+  class MCGenDwarfInfo {
+  public:
+    //
+    // When generating dwarf for assembly source files this emits the Dwarf
+    // sections.
+    //
+    static void Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSymbol);
+  };
+
+  // When generating dwarf for assembly source files this is the info that=
 is
+  // needed to be gathered for each symbol that will have a dwarf label.
+  class MCGenDwarfLabelEntry {
+  private:
+    // Name of the symbol without a leading underbar, if any.
+    StringRef Name;
+    // The dwarf file number this symbol is in.
+    unsigned FileNumber;
+    // The line number this symbol is at.
+    unsigned LineNumber;
+    // The low_pc for the dwarf label is taken from this symbol.
+    MCSymbol *Label;
+
+  public:
+    MCGenDwarfLabelEntry(StringRef name, unsigned fileNumber,
+                         unsigned lineNumber, MCSymbol *label) :
+      Name(name), FileNumber(fileNumber), LineNumber(lineNumber), Label(la=
bel){}
+
+    StringRef getName() const { return Name; }
+    unsigned getFileNumber() const { return FileNumber; }
+    unsigned getLineNumber() const { return LineNumber; }
+    MCSymbol *getLabel() const { return Label; }
+
+    // This is called when label is created when we are generating dwarf f=
or
+    // assembly source files.
+    static void Make(MCSymbol *Symbol, MCStreamer *MCOS, SourceMgr &SrcMgr,
+                     SMLoc &Loc);
+  };
+
   class MCCFIInstruction {
   public:
-    enum OpType { SameValue, Remember, Restore, Move, RelMove };
+    enum OpType { SameValue, RememberState, RestoreState, Move, RelMove, E=
scape,
+                  Restore};
   private:
     OpType Operation;
     MCSymbol *Label;
     // Move to & from location.
     MachineLocation Destination;
     MachineLocation Source;
+    std::vector<char> Values;
   public:
     MCCFIInstruction(OpType Op, MCSymbol *L)
       : Operation(Op), Label(L) {
-      assert(Op =3D=3D Remember || Op =3D=3D Restore);
+      assert(Op =3D=3D RememberState || Op =3D=3D RestoreState);
     }
     MCCFIInstruction(OpType Op, MCSymbol *L, unsigned Register)
       : Operation(Op), Label(L), Destination(Register) {
-      assert(Op =3D=3D SameValue);
+      assert(Op =3D=3D SameValue || Op =3D=3D Restore);
     }
     MCCFIInstruction(MCSymbol *L, const MachineLocation &D,
                      const MachineLocation &S)
@@ -254,16 +292,24 @@
       : Operation(Op), Label(L), Destination(D), Source(S) {
       assert(Op =3D=3D RelMove);
     }
+    MCCFIInstruction(OpType Op, MCSymbol *L, StringRef Vals)
+      : Operation(Op), Label(L), Values(Vals.begin(), Vals.end()) {
+      assert(Op =3D=3D Escape);
+    }
     OpType getOperation() const { return Operation; }
     MCSymbol *getLabel() const { return Label; }
     const MachineLocation &getDestination() const { return Destination; }
     const MachineLocation &getSource() const { return Source; }
+    const StringRef getValues() const {
+      return StringRef(&Values[0], Values.size());
+    }
   };
=20
   struct MCDwarfFrameInfo {
     MCDwarfFrameInfo() : Begin(0), End(0), Personality(0), Lsda(0),
                          Function(0), Instructions(), PersonalityEncoding(=
),
-                         LsdaEncoding(0), CompactUnwindEncoding(0) {}
+                         LsdaEncoding(0), CompactUnwindEncoding(0),
+                         IsSignalFrame(false) {}
     MCSymbol *Begin;
     MCSymbol *End;
     const MCSymbol *Personality;
@@ -273,6 +319,7 @@
     unsigned PersonalityEncoding;
     unsigned LsdaEncoding;
     uint32_t CompactUnwindEncoding;
+    bool IsSignalFrame;
   };
=20
   class MCDwarfFrameEmitter {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCEL=
FObjectWriter.h
--- a/head/contrib/llvm/include/llvm/MC/MCELFObjectWriter.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCELFObjectWriter.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -10,28 +10,91 @@
 #ifndef LLVM_MC_MCELFOBJECTWRITER_H
 #define LLVM_MC_MCELFOBJECTWRITER_H
=20
-#include "llvm/MC/MCObjectWriter.h"
+#include "llvm/ADT/Triple.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ELF.h"
+#include <vector>
=20
 namespace llvm {
+class MCAssembler;
+class MCFixup;
+class MCFragment;
+class MCObjectWriter;
+class MCSymbol;
+class MCValue;
+
+/// @name Relocation Data
+/// @{
+
+struct ELFRelocationEntry {
+  // Make these big enough for both 32-bit and 64-bit
+  uint64_t r_offset;
+  int Index;
+  unsigned Type;
+  const MCSymbol *Symbol;
+  uint64_t r_addend;
+  const MCFixup *Fixup;
+
+  ELFRelocationEntry()
+    : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0), Fixup(0) {}
+
+  ELFRelocationEntry(uint64_t RelocOffset, int Idx, unsigned RelType,
+                     const MCSymbol *Sym, uint64_t Addend, const MCFixup &=
Fixup)
+    : r_offset(RelocOffset), Index(Idx), Type(RelType), Symbol(Sym),
+      r_addend(Addend), Fixup(&Fixup) {}
+
+  // Support lexicographic sorting.
+  bool operator<(const ELFRelocationEntry &RE) const {
+    return RE.r_offset < r_offset;
+  }
+};
+
 class MCELFObjectTargetWriter {
-  const Triple::OSType OSType;
+  const uint8_t OSABI;
   const uint16_t EMachine;
   const unsigned HasRelocationAddend : 1;
   const unsigned Is64Bit : 1;
+
 protected:
-  MCELFObjectTargetWriter(bool Is64Bit_, Triple::OSType OSType_,
+
+  MCELFObjectTargetWriter(bool Is64Bit_, uint8_t OSABI_,
                           uint16_t EMachine_,  bool HasRelocationAddend_);
=20
 public:
-  virtual ~MCELFObjectTargetWriter();
+  static uint8_t getOSABI(Triple::OSType OSType) {
+    switch (OSType) {
+      case Triple::FreeBSD:
+        return ELF::ELFOSABI_FREEBSD;
+      case Triple::Linux:
+        return ELF::ELFOSABI_LINUX;
+      default:
+        return ELF::ELFOSABI_NONE;
+    }
+  }
+
+  virtual ~MCELFObjectTargetWriter() {}
+
+  virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixu=
p,
+                                bool IsPCRel, bool IsRelocWithSymbol,
+                                int64_t Addend) const =3D 0;
+  virtual unsigned getEFlags() const;
+  virtual const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
+                                         const MCValue &Target,
+                                         const MCFragment &F,
+                                         const MCFixup &Fixup,
+                                         bool IsPCRel) const;
+  virtual void adjustFixupOffset(const MCFixup &Fixup,
+                                 uint64_t &RelocOffset);
+
+  virtual void sortRelocs(const MCAssembler &Asm,
+                          std::vector<ELFRelocationEntry> &Relocs);
=20
   /// @name Accessors
   /// @{
-  Triple::OSType getOSType() { return OSType; }
+  uint8_t getOSABI() { return OSABI; }
   uint16_t getEMachine() { return EMachine; }
   bool hasRelocationAddend() { return HasRelocationAddend; }
-  bool is64Bit() { return Is64Bit; }
+  bool is64Bit() const { return Is64Bit; }
   /// @}
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCEx=
pr.h
--- a/head/contrib/llvm/include/llvm/MC/MCExpr.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/include/llvm/MC/MCExpr.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,6 @@
 #include "llvm/Support/DataTypes.h"
=20
 namespace llvm {
-class MCAsmInfo;
 class MCAsmLayout;
 class MCAssembler;
 class MCContext;
@@ -162,6 +161,7 @@
     VK_TPOFF,
     VK_DTPOFF,
     VK_TLVP,      // Mach-O thread local variable relocation
+    VK_SECREL,
     // FIXME: We'd really like to use the generic Kinds listed above for t=
hese.
     VK_ARM_PLT,   // ARM-style PLT references. i.e., (PLT) instead of @PLT
     VK_ARM_TLSGD, //   ditto for TLSGD, GOT, GOTOFF, TPOFF and GOTTPOFF
@@ -169,12 +169,32 @@
     VK_ARM_GOTOFF,
     VK_ARM_TPOFF,
     VK_ARM_GOTTPOFF,
+    VK_ARM_TARGET1,
=20
     VK_PPC_TOC,
     VK_PPC_DARWIN_HA16,  // ha16(symbol)
     VK_PPC_DARWIN_LO16,  // lo16(symbol)
     VK_PPC_GAS_HA16,     // symbol at ha
-    VK_PPC_GAS_LO16      // symbol at l
+    VK_PPC_GAS_LO16,      // symbol at l
+
+    VK_Mips_GPREL,
+    VK_Mips_GOT_CALL,
+    VK_Mips_GOT16,
+    VK_Mips_GOT,
+    VK_Mips_ABS_HI,
+    VK_Mips_ABS_LO,
+    VK_Mips_TLSGD,
+    VK_Mips_TLSLDM,
+    VK_Mips_DTPREL_HI,
+    VK_Mips_DTPREL_LO,
+    VK_Mips_GOTTPREL,
+    VK_Mips_TPREL_HI,
+    VK_Mips_TPREL_LO,
+    VK_Mips_GPOFF_HI,
+    VK_Mips_GPOFF_LO,
+    VK_Mips_GOT_DISP,
+    VK_Mips_GOT_PAGE,
+    VK_Mips_GOT_OFST=20
   };
=20
 private:
@@ -185,7 +205,9 @@
   const VariantKind Kind;
=20
   explicit MCSymbolRefExpr(const MCSymbol *_Symbol, VariantKind _Kind)
-    : MCExpr(MCExpr::SymbolRef), Symbol(_Symbol), Kind(_Kind) {}
+    : MCExpr(MCExpr::SymbolRef), Symbol(_Symbol), Kind(_Kind) {
+    assert(Symbol);
+  }
=20
 public:
   /// @name Construction
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCFi=
xup.h
--- a/head/contrib/llvm/include/llvm/MC/MCFixup.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/include/llvm/MC/MCFixup.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -11,6 +11,8 @@
 #define LLVM_MC_MCFIXUP_H
=20
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/SMLoc.h"
 #include <cassert>
=20
 namespace llvm {
@@ -26,6 +28,14 @@
   FK_PCRel_2,    ///< A two-byte pc relative fixup.
   FK_PCRel_4,    ///< A four-byte pc relative fixup.
   FK_PCRel_8,    ///< A eight-byte pc relative fixup.
+  FK_GPRel_1,    ///< A one-byte gp relative fixup.
+  FK_GPRel_2,    ///< A two-byte gp relative fixup.
+  FK_GPRel_4,    ///< A four-byte gp relative fixup.
+  FK_GPRel_8,    ///< A eight-byte gp relative fixup.
+  FK_SecRel_1,   ///< A one-byte section relative fixup.
+  FK_SecRel_2,   ///< A two-byte section relative fixup.
+  FK_SecRel_4,   ///< A four-byte section relative fixup.
+  FK_SecRel_8,   ///< A eight-byte section relative fixup.
=20
   FirstTargetFixupKind =3D 128,
=20
@@ -61,14 +71,17 @@
   /// determine how the operand value should be encoded into the instructi=
on.
   unsigned Kind;
=20
+  /// The source location which gave rise to the fixup, if any.
+  SMLoc Loc;
 public:
   static MCFixup Create(uint32_t Offset, const MCExpr *Value,
-                        MCFixupKind Kind) {
+                        MCFixupKind Kind, SMLoc Loc =3D SMLoc()) {
     assert(unsigned(Kind) < MaxTargetFixupKind && "Kind out of range!");
     MCFixup FI;
     FI.Value =3D Value;
     FI.Offset =3D Offset;
     FI.Kind =3D unsigned(Kind);
+    FI.Loc =3D Loc;
     return FI;
   }
=20
@@ -83,13 +96,15 @@
   /// size. It is an error to pass an unsupported size.
   static MCFixupKind getKindForSize(unsigned Size, bool isPCRel) {
     switch (Size) {
-    default: assert(0 && "Invalid generic fixup size!");
+    default: llvm_unreachable("Invalid generic fixup size!");
     case 1: return isPCRel ? FK_PCRel_1 : FK_Data_1;
     case 2: return isPCRel ? FK_PCRel_2 : FK_Data_2;
     case 4: return isPCRel ? FK_PCRel_4 : FK_Data_4;
     case 8: return isPCRel ? FK_PCRel_8 : FK_Data_8;
     }
   }
+
+  SMLoc getLoc() const { return Loc; }
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCIn=
st.h
--- a/head/contrib/llvm/include/llvm/MC/MCInst.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/include/llvm/MC/MCInst.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -19,12 +19,14 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/SMLoc.h"
=20
 namespace llvm {
 class raw_ostream;
 class MCAsmInfo;
 class MCInstPrinter;
 class MCExpr;
+class MCInst;
=20
 /// MCOperand - Instances of this class represent operands of the MCInst c=
lass.
 /// This is a simple discriminated union.
@@ -34,7 +36,8 @@
     kRegister,                ///< Register operand.
     kImmediate,               ///< Immediate operand.
     kFPImmediate,             ///< Floating-point immediate operand.
-    kExpr                     ///< Relocatable immediate operand.
+    kExpr,                    ///< Relocatable immediate operand.
+    kInst                     ///< Sub-instruction operand.
   };
   unsigned char Kind;
=20
@@ -43,6 +46,7 @@
     int64_t ImmVal;
     double FPImmVal;
     const MCExpr *ExprVal;
+    const MCInst *InstVal;
   };
 public:
=20
@@ -53,6 +57,7 @@
   bool isImm() const { return Kind =3D=3D kImmediate; }
   bool isFPImm() const { return Kind =3D=3D kFPImmediate; }
   bool isExpr() const { return Kind =3D=3D kExpr; }
+  bool isInst() const { return Kind =3D=3D kInst; }
=20
   /// getReg - Returns the register number.
   unsigned getReg() const {
@@ -94,6 +99,15 @@
     ExprVal =3D Val;
   }
=20
+  const MCInst *getInst() const {
+    assert(isInst() && "This is not a sub-instruction");
+    return InstVal;
+  }
+  void setInst(const MCInst *Val) {
+    assert(isInst() && "This is not a sub-instruction");
+    InstVal =3D Val;
+  }
+
   static MCOperand CreateReg(unsigned Reg) {
     MCOperand Op;
     Op.Kind =3D kRegister;
@@ -118,23 +132,33 @@
     Op.ExprVal =3D Val;
     return Op;
   }
+  static MCOperand CreateInst(const MCInst *Val) {
+    MCOperand Op;
+    Op.Kind =3D kInst;
+    Op.InstVal =3D Val;
+    return Op;
+  }
=20
   void print(raw_ostream &OS, const MCAsmInfo *MAI) const;
   void dump() const;
 };
=20
+template <> struct isPodLike<MCOperand> { static const bool value =3D true=
; };
=20
 /// MCInst - Instances of this class represent a single low-level machine
 /// instruction.
 class MCInst {
   unsigned Opcode;
+  SMLoc Loc;
   SmallVector<MCOperand, 8> Operands;
 public:
   MCInst() : Opcode(0) {}
=20
   void setOpcode(unsigned Op) { Opcode =3D Op; }
+  unsigned getOpcode() const { return Opcode; }
=20
-  unsigned getOpcode() const { return Opcode; }
+  void setLoc(SMLoc loc) { Loc =3D loc; }
+  SMLoc getLoc() const { return Loc; }
=20
   const MCOperand &getOperand(unsigned i) const { return Operands[i]; }
   MCOperand &getOperand(unsigned i) { return Operands[i]; }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCIn=
stPrinter.h
--- a/head/contrib/llvm/include/llvm/MC/MCInstPrinter.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCInstPrinter.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -14,6 +14,8 @@
 class MCInst;
 class raw_ostream;
 class MCAsmInfo;
+class MCInstrInfo;
+class MCRegisterInfo;
 class StringRef;
=20
 /// MCInstPrinter - This is an instance of a target assembly language prin=
ter
@@ -25,6 +27,8 @@
   /// assembly emission is disable.
   raw_ostream *CommentStream;
   const MCAsmInfo &MAI;
+  const MCInstrInfo &MII;
+  const MCRegisterInfo &MRI;
=20
   /// The current set of available features.
   unsigned AvailableFeatures;
@@ -32,8 +36,9 @@
   /// Utility function for printing annotations.
   void printAnnotation(raw_ostream &OS, StringRef Annot);
 public:
-  MCInstPrinter(const MCAsmInfo &mai)
-    : CommentStream(0), MAI(mai), AvailableFeatures(0) {}
+  MCInstPrinter(const MCAsmInfo &mai, const MCInstrInfo &mii,
+                const MCRegisterInfo &mri)
+    : CommentStream(0), MAI(mai), MII(mii), MRI(mri), AvailableFeatures(0)=
 {}
=20
   virtual ~MCInstPrinter();
=20
@@ -47,7 +52,7 @@
=20
   /// getOpcodeName - Return the name of the specified opcode enum (e.g.
   /// "MOV32ri") or empty if we can't resolve it.
-  virtual StringRef getOpcodeName(unsigned Opcode) const;
+  StringRef getOpcodeName(unsigned Opcode) const;
=20
   /// printRegName - Print the assembler register name.
   virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCIn=
strAnalysis.h
--- a/head/contrib/llvm/include/llvm/MC/MCInstrAnalysis.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCInstrAnalysis.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -33,7 +33,7 @@
   }
=20
   virtual bool isConditionalBranch(const MCInst &Inst) const {
-    return Info->get(Inst.getOpcode()).isBranch();
+    return Info->get(Inst.getOpcode()).isConditionalBranch();
   }
=20
   virtual bool isUnconditionalBranch(const MCInst &Inst) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCIn=
strDesc.h
--- a/head/contrib/llvm/include/llvm/MC/MCInstrDesc.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCInstrDesc.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -58,17 +58,17 @@
   /// if the operand is a register.  If isLookupPtrRegClass is set, then t=
his is
   /// an index that is passed to TargetRegisterInfo::getPointerRegClass(x)=
 to
   /// get a dynamic register class.
-  short RegClass;
+  int16_t RegClass;
=20
   /// Flags - These are flags from the MCOI::OperandFlags enum.
-  unsigned short Flags;
+  uint8_t Flags;
+
+  /// OperandType - Information about the type of the operand.
+  uint8_t OperandType;
=20
   /// Lower 16 bits are used to specify which constraints are set. The hig=
her 16
   /// bits are used to specify the value of constraints (4 bits each).
-  unsigned Constraints;
-
-  /// OperandType - Information about the type of the operand.
-  MCOI::OperandType OperandType;
+  uint32_t Constraints;
   /// Currently no other information.
=20
   /// isLookupPtrRegClass - Set if this operand is a pointer value and it
@@ -137,11 +137,10 @@
   unsigned short  NumDefs;       // Num of args that are definitions
   unsigned short  SchedClass;    // enum identifying instr sched class
   unsigned short  Size;          // Number of bytes in encoding.
-  const char *    Name;          // Name of the instruction record in td f=
ile
   unsigned        Flags;         // Flags identifying machine instr class
   uint64_t        TSFlags;       // Target Specific Flag values
-  const unsigned *ImplicitUses;  // Registers implicitly read by this instr
-  const unsigned *ImplicitDefs;  // Registers implicitly defined by this i=
nstr
+  const uint16_t *ImplicitUses;  // Registers implicitly read by this instr
+  const uint16_t *ImplicitDefs;  // Registers implicitly defined by this i=
nstr
   const MCOperandInfo *OpInfo;   // 'NumOperands' entries about operands
=20
   /// getOperandConstraint - Returns the value of the specific constraint =
if
@@ -161,12 +160,6 @@
     return Opcode;
   }
=20
-  /// getName - Return the name of the record in the .td file for this
-  /// instruction, for example "ADD8ri".
-  const char *getName() const {
-    return Name;
-  }
-
   /// getNumOperands - Return the number of declared MachineOperands for t=
his
   /// MachineInstruction.  Note that variadic (isVariadic() returns true)
   /// instructions may have additional operands at the end of the list, an=
d note
@@ -184,6 +177,10 @@
     return NumDefs;
   }
=20
+  /// getFlags - Return flags of this instruction.
+  ///
+  unsigned getFlags() const { return Flags; }
+
   /// isVariadic - Return true if this instruction can have a variable num=
ber of
   /// operands.  In this case, the variable operands will be after the nor=
mal
   /// operands but before the implicit definitions and uses (if any are
@@ -198,84 +195,6 @@
     return Flags & (1 << MCID::HasOptionalDef);
   }
=20
-  /// getImplicitUses - Return a list of registers that are potentially
-  /// read by any instance of this machine instruction.  For example, on X=
86,
-  /// the "adc" instruction adds two register operands and adds the carry =
bit in
-  /// from the flags register.  In this case, the instruction is marked as
-  /// implicitly reading the flags.  Likewise, the variable shift instruct=
ion on
-  /// X86 is marked as implicitly reading the 'CL' register, which it alwa=
ys
-  /// does.
-  ///
-  /// This method returns null if the instruction has no implicit uses.
-  const unsigned *getImplicitUses() const {
-    return ImplicitUses;
-  }
-
-  /// getNumImplicitUses - Return the number of implicit uses this instruc=
tion
-  /// has.
-  unsigned getNumImplicitUses() const {
-    if (ImplicitUses =3D=3D 0) return 0;
-    unsigned i =3D 0;
-    for (; ImplicitUses[i]; ++i) /*empty*/;
-    return i;
-  }
-
-  /// getImplicitDefs - Return a list of registers that are potentially
-  /// written by any instance of this machine instruction.  For example, o=
n X86,
-  /// many instructions implicitly set the flags register.  In this case, =
they
-  /// are marked as setting the FLAGS.  Likewise, many instructions always
-  /// deposit their result in a physical register.  For example, the X86 d=
ivide
-  /// instruction always deposits the quotient and remainder in the EAX/EDX
-  /// registers.  For that instruction, this will return a list containing=
 the
-  /// EAX/EDX/EFLAGS registers.
-  ///
-  /// This method returns null if the instruction has no implicit defs.
-  const unsigned *getImplicitDefs() const {
-    return ImplicitDefs;
-  }
-
-  /// getNumImplicitDefs - Return the number of implicit defs this instruc=
tion
-  /// has.
-  unsigned getNumImplicitDefs() const {
-    if (ImplicitDefs =3D=3D 0) return 0;
-    unsigned i =3D 0;
-    for (; ImplicitDefs[i]; ++i) /*empty*/;
-    return i;
-  }
-
-  /// hasImplicitUseOfPhysReg - Return true if this instruction implicitly
-  /// uses the specified physical register.
-  bool hasImplicitUseOfPhysReg(unsigned Reg) const {
-    if (const unsigned *ImpUses =3D ImplicitUses)
-      for (; *ImpUses; ++ImpUses)
-        if (*ImpUses =3D=3D Reg) return true;
-    return false;
-  }
-
-  /// hasImplicitDefOfPhysReg - Return true if this instruction implicitly
-  /// defines the specified physical register.
-  bool hasImplicitDefOfPhysReg(unsigned Reg) const {
-    if (const unsigned *ImpDefs =3D ImplicitDefs)
-      for (; *ImpDefs; ++ImpDefs)
-        if (*ImpDefs =3D=3D Reg) return true;
-    return false;
-  }
-
-  /// getSchedClass - Return the scheduling class for this instruction.  T=
he
-  /// scheduling class is an index into the InstrItineraryData table.  This
-  /// returns zero if there is no known scheduling information for the
-  /// instruction.
-  ///
-  unsigned getSchedClass() const {
-    return SchedClass;
-  }
-
-  /// getSize - Return the number of bytes in the encoding of this instruc=
tion,
-  /// or zero if the encoding size cannot be known from the opcode.
-  unsigned getSize() const {
-    return Size;
-  }
-
   /// isPseudo - Return true if this is a pseudo instruction that doesn't
   /// correspond to a real machine instruction.
   ///
@@ -298,18 +217,6 @@
     return Flags & (1 << MCID::Barrier);
   }
=20
-  /// findFirstPredOperandIdx() - Find the index of the first operand in t=
he
-  /// operand list that is used to represent the predicate. It returns -1 =
if
-  /// none is found.
-  int findFirstPredOperandIdx() const {
-    if (isPredicable()) {
-      for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i)
-        if (OpInfo[i].isPredicate())
-          return i;
-    }
-    return -1;
-  }
-
   /// isTerminator - Returns true if this instruction part of the terminat=
or for
   /// a basic block.  Typically this is things like return and branch
   /// instructions.
@@ -530,6 +437,97 @@
   bool hasExtraDefRegAllocReq() const {
     return Flags & (1 << MCID::ExtraDefRegAllocReq);
   }
+
+
+  /// getImplicitUses - Return a list of registers that are potentially
+  /// read by any instance of this machine instruction.  For example, on X=
86,
+  /// the "adc" instruction adds two register operands and adds the carry =
bit in
+  /// from the flags register.  In this case, the instruction is marked as
+  /// implicitly reading the flags.  Likewise, the variable shift instruct=
ion on
+  /// X86 is marked as implicitly reading the 'CL' register, which it alwa=
ys
+  /// does.
+  ///
+  /// This method returns null if the instruction has no implicit uses.
+  const uint16_t *getImplicitUses() const {
+    return ImplicitUses;
+  }
+
+  /// getNumImplicitUses - Return the number of implicit uses this instruc=
tion
+  /// has.
+  unsigned getNumImplicitUses() const {
+    if (ImplicitUses =3D=3D 0) return 0;
+    unsigned i =3D 0;
+    for (; ImplicitUses[i]; ++i) /*empty*/;
+    return i;
+  }
+
+  /// getImplicitDefs - Return a list of registers that are potentially
+  /// written by any instance of this machine instruction.  For example, o=
n X86,
+  /// many instructions implicitly set the flags register.  In this case, =
they
+  /// are marked as setting the FLAGS.  Likewise, many instructions always
+  /// deposit their result in a physical register.  For example, the X86 d=
ivide
+  /// instruction always deposits the quotient and remainder in the EAX/EDX
+  /// registers.  For that instruction, this will return a list containing=
 the
+  /// EAX/EDX/EFLAGS registers.
+  ///
+  /// This method returns null if the instruction has no implicit defs.
+  const uint16_t *getImplicitDefs() const {
+    return ImplicitDefs;
+  }
+
+  /// getNumImplicitDefs - Return the number of implicit defs this instruc=
tion
+  /// has.
+  unsigned getNumImplicitDefs() const {
+    if (ImplicitDefs =3D=3D 0) return 0;
+    unsigned i =3D 0;
+    for (; ImplicitDefs[i]; ++i) /*empty*/;
+    return i;
+  }
+
+  /// hasImplicitUseOfPhysReg - Return true if this instruction implicitly
+  /// uses the specified physical register.
+  bool hasImplicitUseOfPhysReg(unsigned Reg) const {
+    if (const uint16_t *ImpUses =3D ImplicitUses)
+      for (; *ImpUses; ++ImpUses)
+        if (*ImpUses =3D=3D Reg) return true;
+    return false;
+  }
+
+  /// hasImplicitDefOfPhysReg - Return true if this instruction implicitly
+  /// defines the specified physical register.
+  bool hasImplicitDefOfPhysReg(unsigned Reg) const {
+    if (const uint16_t *ImpDefs =3D ImplicitDefs)
+      for (; *ImpDefs; ++ImpDefs)
+        if (*ImpDefs =3D=3D Reg) return true;
+    return false;
+  }
+
+  /// getSchedClass - Return the scheduling class for this instruction.  T=
he
+  /// scheduling class is an index into the InstrItineraryData table.  This
+  /// returns zero if there is no known scheduling information for the
+  /// instruction.
+  ///
+  unsigned getSchedClass() const {
+    return SchedClass;
+  }
+
+  /// getSize - Return the number of bytes in the encoding of this instruc=
tion,
+  /// or zero if the encoding size cannot be known from the opcode.
+  unsigned getSize() const {
+    return Size;
+  }
+
+  /// findFirstPredOperandIdx() - Find the index of the first operand in t=
he
+  /// operand list that is used to represent the predicate. It returns -1 =
if
+  /// none is found.
+  int findFirstPredOperandIdx() const {
+    if (isPredicable()) {
+      for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i)
+        if (OpInfo[i].isPredicate())
+          return i;
+    }
+    return -1;
+  }
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCIn=
strInfo.h
--- a/head/contrib/llvm/include/llvm/MC/MCInstrInfo.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCInstrInfo.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -24,14 +24,19 @@
 /// MCInstrInfo - Interface to description of machine instruction set
 ///
 class MCInstrInfo {
-  const MCInstrDesc *Desc;  // Raw array to allow static init'n
-  unsigned NumOpcodes;      // Number of entries in the desc array
+  const MCInstrDesc *Desc;          // Raw array to allow static init'n
+  const unsigned *InstrNameIndices; // Array for name indices in InstrName=
Data
+  const char *InstrNameData;        // Instruction name string pool
+  unsigned NumOpcodes;              // Number of entries in the desc array
=20
 public:
   /// InitMCInstrInfo - Initialize MCInstrInfo, called by TableGen
   /// auto-generated routines. *DO NOT USE*.
-  void InitMCInstrInfo(const MCInstrDesc *D, unsigned NO) {
+  void InitMCInstrInfo(const MCInstrDesc *D, const unsigned *NI, const cha=
r *ND,
+                       unsigned NO) {
     Desc =3D D;
+    InstrNameIndices =3D NI;
+    InstrNameData =3D ND;
     NumOpcodes =3D NO;
   }
=20
@@ -44,6 +49,12 @@
     assert(Opcode < NumOpcodes && "Invalid opcode!");
     return Desc[Opcode];
   }
+
+  /// getName - Returns the name for the instructions with the given opcod=
e.
+  const char *getName(unsigned Opcode) const {
+    assert(Opcode < NumOpcodes && "Invalid opcode!");
+    return &InstrNameData[InstrNameIndices[Opcode]];
+  }
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCOb=
jectFileInfo.h
--- a/head/contrib/llvm/include/llvm/MC/MCObjectFileInfo.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCObjectFileInfo.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,15 +14,14 @@
 #ifndef LLVM_MC_MCBJECTFILEINFO_H
 #define LLVM_MC_MCBJECTFILEINFO_H
=20
-#include "llvm/MC/MCCodeGenInfo.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/MC/SectionKind.h"
+#include "llvm/Support/CodeGen.h"
=20
 namespace llvm {
-class MCContext;
-class MCSection;
-class Triple;
- =20
+  class MCContext;
+  class MCSection;
+  class StringRef;
+  class Triple;
+
 class MCObjectFileInfo { =20
 protected:
   /// CommDirectiveSupportsAlignment - True if .comm supports alignment.  =
This
@@ -47,6 +46,9 @@
   unsigned FDEEncoding;
   unsigned FDECFIEncoding;
   unsigned TTypeEncoding;
+  // Section flags for eh_frame
+  unsigned EHSectionType;
+  unsigned EHSectionFlags;
=20
   /// TextSection - Section directive for standard text.
   ///
@@ -82,13 +84,20 @@
   /// this is the section to emit them into.
   const MCSection *CompactUnwindSection;
=20
+  /// DwarfAccelNamesSection, DwarfAccelObjCSection
+  /// If we use the DWARF accelerated hash tables then we want toe emit th=
ese
+  /// sections.
+  const MCSection *DwarfAccelNamesSection;
+  const MCSection *DwarfAccelObjCSection;
+  const MCSection *DwarfAccelNamespaceSection;
+  const MCSection *DwarfAccelTypesSection;
+
   // Dwarf sections for debug info.  If a target supports debug info, thes=
e must
   // be set.
   const MCSection *DwarfAbbrevSection;
   const MCSection *DwarfInfoSection;
   const MCSection *DwarfLineSection;
   const MCSection *DwarfFrameSection;
-  const MCSection *DwarfPubNamesSection;
   const MCSection *DwarfPubTypesSection;
   const MCSection *DwarfDebugInlineSection;
   const MCSection *DwarfStrSection;
@@ -102,7 +111,7 @@
   const MCSection *TLSExtraDataSection;
  =20
   /// TLSDataSection - Section directive for Thread Local data.
-  /// ELF and MachO only.
+  /// ELF, MachO and COFF.
   const MCSection *TLSDataSection;        // Defaults to ".tdata".
=20
   /// TLSBSSSection - Section directive for Thread Local uninitialized dat=
a.
@@ -156,7 +165,7 @@
   const MCSection *DrectveSection;
   const MCSection *PDataSection;
   const MCSection *XDataSection;
- =20
+
 public:
   void InitMCObjectFileInfo(StringRef TT, Reloc::Model RM, CodeModel::Mode=
l CM,
                             MCContext &ctx);
@@ -181,17 +190,26 @@
   const MCSection *getTextSection() const { return TextSection; }
   const MCSection *getDataSection() const { return DataSection; }
   const MCSection *getBSSSection() const { return BSSSection; }
-  const MCSection *getStaticCtorSection() const { return StaticCtorSection=
; }
-  const MCSection *getStaticDtorSection() const { return StaticDtorSection=
; }
   const MCSection *getLSDASection() const { return LSDASection; }
   const MCSection *getCompactUnwindSection() const{
     return CompactUnwindSection;
   }
+  const MCSection *getDwarfAccelNamesSection() const {
+    return DwarfAccelNamesSection;
+  }
+  const MCSection *getDwarfAccelObjCSection() const {
+    return DwarfAccelObjCSection;
+  }
+  const MCSection *getDwarfAccelNamespaceSection() const {
+    return DwarfAccelNamespaceSection;
+  }
+  const MCSection *getDwarfAccelTypesSection() const {
+    return DwarfAccelTypesSection;
+  }
   const MCSection *getDwarfAbbrevSection() const { return DwarfAbbrevSecti=
on; }
   const MCSection *getDwarfInfoSection() const { return DwarfInfoSection; }
   const MCSection *getDwarfLineSection() const { return DwarfLineSection; }
   const MCSection *getDwarfFrameSection() const { return DwarfFrameSection=
; }
-  const MCSection *getDwarfPubNamesSection() const{return DwarfPubNamesSec=
tion;}
   const MCSection *getDwarfPubTypesSection() const{return DwarfPubTypesSec=
tion;}
   const MCSection *getDwarfDebugInlineSection() const {
     return DwarfDebugInlineSection;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCOb=
jectStreamer.h
--- a/head/contrib/llvm/include/llvm/MC/MCObjectStreamer.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCObjectStreamer.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -34,6 +34,8 @@
   MCSectionData *CurSectionData;
=20
   virtual void EmitInstToData(const MCInst &Inst) =3D 0;
+  virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
+  virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame);
=20
 protected:
   MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
@@ -70,14 +72,15 @@
   virtual void ChangeSection(const MCSection *Section);
   virtual void EmitInstruction(const MCInst &Inst);
   virtual void EmitInstToFragment(const MCInst &Inst);
-  virtual void EmitValueToOffset(const MCExpr *Offset, unsigned char Value=
);
+  virtual bool EmitValueToOffset(const MCExpr *Offset, unsigned char Value=
);
   virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
                                         const MCSymbol *LastLabel,
                                         const MCSymbol *Label,
                                         unsigned PointerSize);
   virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
                                          const MCSymbol *Label);
-  virtual void Finish();
+  virtual void EmitGPRel32Value(const MCExpr *Value);
+  virtual void FinishImpl();
=20
   /// @}
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCOb=
jectWriter.h
--- a/head/contrib/llvm/include/llvm/MC/MCObjectWriter.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCObjectWriter.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -10,7 +10,6 @@
 #ifndef LLVM_MC_MCOBJECTWRITER_H
 #define LLVM_MC_MCOBJECTWRITER_H
=20
-#include "llvm/ADT/Triple.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/DataTypes.h"
 #include <cassert>
@@ -20,11 +19,9 @@
 class MCAssembler;
 class MCFixup;
 class MCFragment;
-class MCSymbol;
 class MCSymbolData;
 class MCSymbolRefExpr;
 class MCValue;
-class raw_ostream;
=20
 /// MCObjectWriter - Defines the object file and target independent interf=
aces
 /// used by the assembler backend to write native file format object files.
@@ -188,11 +185,10 @@
   /// Utility function to encode a SLEB128 value.
   static void EncodeSLEB128(int64_t Value, raw_ostream &OS);
   /// Utility function to encode a ULEB128 value.
-  static void EncodeULEB128(uint64_t Value, raw_ostream &OS);
+  static void EncodeULEB128(uint64_t Value, raw_ostream &OS,
+                            unsigned Padding =3D 0);
 };
=20
-MCObjectWriter *createWinCOFFObjectWriter(raw_ostream &OS, bool is64Bit);
-
 } // End llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCPa=
rser/MCAsmLexer.h
--- a/head/contrib/llvm/include/llvm/MC/MCParser/MCAsmLexer.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCParser/MCAsmLexer.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -71,6 +71,7 @@
   bool isNot(TokenKind K) const { return Kind !=3D K; }
=20
   SMLoc getLoc() const;
+  SMLoc getEndLoc() const;
=20
   /// getStringContents - Get the contents of a string token (without quot=
es).
   StringRef getStringContents() const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCPa=
rser/MCAsmParser.h
--- a/head/contrib/llvm/include/llvm/MC/MCParser/MCAsmParser.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCParser/MCAsmParser.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -11,6 +11,7 @@
 #define LLVM_MC_MCASMPARSER_H
=20
 #include "llvm/Support/DataTypes.h"
+#include "llvm/ADT/ArrayRef.h"
=20
 namespace llvm {
 class AsmToken;
@@ -22,6 +23,7 @@
 class MCStreamer;
 class MCTargetAsmParser;
 class SMLoc;
+class SMRange;
 class SourceMgr;
 class StringRef;
 class Twine;
@@ -62,6 +64,9 @@
   MCTargetAsmParser &getTargetParser() const { return *TargetParser; }
   void setTargetParser(MCTargetAsmParser &P);
=20
+  virtual unsigned getAssemblerDialect() { return 0;}
+  virtual void setAssemblerDialect(unsigned i) { }
+
   bool getShowParsedOperands() const { return ShowParsedOperands; }
   void setShowParsedOperands(bool Value) { ShowParsedOperands =3D Value; }
=20
@@ -72,14 +77,16 @@
   /// Msg.
   ///
   /// \return The return value is true, if warnings are fatal.
-  virtual bool Warning(SMLoc L, const Twine &Msg) =3D 0;
+  virtual bool Warning(SMLoc L, const Twine &Msg,
+                       ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>()) =
=3D 0;
=20
   /// Error - Emit an error at the location \arg L, with the message \arg
   /// Msg.
   ///
   /// \return The return value is always true, as an idiomatic convenience=
 to
   /// clients.
-  virtual bool Error(SMLoc L, const Twine &Msg) =3D 0;
+  virtual bool Error(SMLoc L, const Twine &Msg,
+                     ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>()) =3D=
 0;
=20
   /// Lex - Get the next AsmToken in the stream, possibly handling file
   /// inclusion first.
@@ -89,7 +96,8 @@
   const AsmToken &getTok();
=20
   /// \brief Report an error at the current lexer location.
-  bool TokError(const Twine &Msg);
+  bool TokError(const Twine &Msg,
+                ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>());
=20
   /// ParseIdentifier - Parse an identifier or string (as a quoted identif=
ier)
   /// and set \arg Res to the identifier contents.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCRe=
gisterInfo.h
--- a/head/contrib/llvm/include/llvm/MC/MCRegisterInfo.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCRegisterInfo.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -17,6 +17,7 @@
 #define LLVM_MC_MCREGISTERINFO_H
=20
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cassert>
=20
 namespace llvm {
@@ -24,28 +25,18 @@
 /// MCRegisterClass - Base class of TargetRegisterClass.
 class MCRegisterClass {
 public:
-  typedef const unsigned* iterator;
-  typedef const unsigned* const_iterator;
-private:
-  unsigned ID;
+  typedef const uint16_t* iterator;
+  typedef const uint16_t* const_iterator;
+
   const char *Name;
-  const unsigned RegSize, Alignment; // Size & Alignment of register in by=
tes
-  const int CopyCost;
+  const iterator RegsBegin;
+  const uint8_t *const RegSet;
+  const uint16_t RegsSize;
+  const uint16_t RegSetSize;
+  const uint16_t ID;
+  const uint16_t RegSize, Alignment; // Size & Alignment of register in by=
tes
+  const int8_t CopyCost;
   const bool Allocatable;
-  const iterator RegsBegin, RegsEnd;
-  const unsigned char *const RegSet;
-  const unsigned RegSetSize;
-public:
-  MCRegisterClass(unsigned id, const char *name,
-                  unsigned RS, unsigned Al, int CC, bool Allocable,
-                  iterator RB, iterator RE, const unsigned char *Bits,
-                  unsigned NumBytes)
-    : ID(id), Name(name), RegSize(RS), Alignment(Al), CopyCost(CC),
-      Allocatable(Allocable), RegsBegin(RB), RegsEnd(RE), RegSet(Bits),
-      RegSetSize(NumBytes) {
-    for (iterator i =3D RegsBegin; i !=3D RegsEnd; ++i)
-       assert(contains(*i) && "Bit field corrupted.");
-  }
=20
   /// getID() - Return the register class ID number.
   ///
@@ -58,11 +49,11 @@
   /// begin/end - Return all of the registers in this class.
   ///
   iterator       begin() const { return RegsBegin; }
-  iterator         end() const { return RegsEnd; }
+  iterator         end() const { return RegsBegin + RegsSize; }
=20
   /// getNumRegs - Return the number of registers in this class.
   ///
-  unsigned getNumRegs() const { return (unsigned)(RegsEnd-RegsBegin); }
+  unsigned getNumRegs() const { return RegsSize; }
=20
   /// getRegister - Return the specified register in the class.
   ///
@@ -115,10 +106,10 @@
 /// of AX.
 ///
 struct MCRegisterDesc {
-  const char     *Name;         // Printable name for the reg (for debuggi=
ng)
-  const unsigned *Overlaps;     // Overlapping registers, described above
-  const unsigned *SubRegs;      // Sub-register set, described above
-  const unsigned *SuperRegs;    // Super-register set, described above
+  const char *Name;         // Printable name for the reg (for debugging)
+  uint32_t   Overlaps;      // Overlapping registers, described above
+  uint32_t   SubRegs;       // Sub-register set, described above
+  uint32_t   SuperRegs;     // Super-register set, described above
 };
=20
 /// MCRegisterInfo base class - We assume that the target defines a static
@@ -136,50 +127,82 @@
 class MCRegisterInfo {
 public:
   typedef const MCRegisterClass *regclass_iterator;
+
+  /// DwarfLLVMRegPair - Emitted by tablegen so Dwarf<->LLVM reg mappings =
can be
+  /// performed with a binary search.
+  struct DwarfLLVMRegPair {
+    unsigned FromReg;
+    unsigned ToReg;
+
+    bool operator<(DwarfLLVMRegPair RHS) const { return FromReg < RHS.From=
Reg; }
+  };
 private:
   const MCRegisterDesc *Desc;                 // Pointer to the descriptor=
 array
   unsigned NumRegs;                           // Number of entries in the =
array
   unsigned RAReg;                             // Return address register
   const MCRegisterClass *Classes;             // Pointer to the regclass a=
rray
   unsigned NumClasses;                        // Number of entries in the =
array
-  DenseMap<unsigned, int> L2DwarfRegs;        // LLVM to Dwarf regs mapping
-  DenseMap<unsigned, int> EHL2DwarfRegs;      // LLVM to Dwarf regs mappin=
g EH
-  DenseMap<unsigned, unsigned> Dwarf2LRegs;   // Dwarf to LLVM regs mapping
-  DenseMap<unsigned, unsigned> EHDwarf2LRegs; // Dwarf to LLVM regs mappin=
g EH
+  const uint16_t *RegLists;                   // Pointer to the reglists a=
rray
+  const uint16_t *SubRegIndices;              // Pointer to the subreg loo=
kup
+                                              // array.
+  unsigned NumSubRegIndices;                  // Number of subreg indices.
+
+  unsigned L2DwarfRegsSize;
+  unsigned EHL2DwarfRegsSize;
+  unsigned Dwarf2LRegsSize;
+  unsigned EHDwarf2LRegsSize;
+  const DwarfLLVMRegPair *L2DwarfRegs;        // LLVM to Dwarf regs mapping
+  const DwarfLLVMRegPair *EHL2DwarfRegs;      // LLVM to Dwarf regs mappin=
g EH
+  const DwarfLLVMRegPair *Dwarf2LRegs;        // Dwarf to LLVM regs mapping
+  const DwarfLLVMRegPair *EHDwarf2LRegs;      // Dwarf to LLVM regs mappin=
g EH
   DenseMap<unsigned, int> L2SEHRegs;          // LLVM to SEH regs mapping
=20
 public:
   /// InitMCRegisterInfo - Initialize MCRegisterInfo, called by TableGen
   /// auto-generated routines. *DO NOT USE*.
   void InitMCRegisterInfo(const MCRegisterDesc *D, unsigned NR, unsigned R=
A,
-                          const MCRegisterClass *C, unsigned NC) {
+                          const MCRegisterClass *C, unsigned NC,
+                          const uint16_t *RL,
+                          const uint16_t *SubIndices,
+                          unsigned NumIndices) {
     Desc =3D D;
     NumRegs =3D NR;
     RAReg =3D RA;
     Classes =3D C;
+    RegLists =3D RL;
     NumClasses =3D NC;
+    SubRegIndices =3D SubIndices;
+    NumSubRegIndices =3D NumIndices;
   }
=20
-  /// mapLLVMRegToDwarfReg - Used to initialize LLVM register to Dwarf
+  /// mapLLVMRegsToDwarfRegs - Used to initialize LLVM register to Dwarf
   /// register number mapping. Called by TableGen auto-generated routines.
   /// *DO NOT USE*.
-  void mapLLVMRegToDwarfReg(unsigned LLVMReg, int DwarfReg, bool isEH) {
-    if (isEH)
-      EHL2DwarfRegs[LLVMReg] =3D DwarfReg;
-    else
-      L2DwarfRegs[LLVMReg] =3D DwarfReg;
+  void mapLLVMRegsToDwarfRegs(const DwarfLLVMRegPair *Map, unsigned Size,
+                              bool isEH) {
+    if (isEH) {
+      EHL2DwarfRegs =3D Map;
+      EHL2DwarfRegsSize =3D Size;
+    } else {
+      L2DwarfRegs =3D Map;
+      L2DwarfRegsSize =3D Size;
+    }
   }
-   =20
-  /// mapDwarfRegToLLVMReg - Used to initialize Dwarf register to LLVM
+
+  /// mapDwarfRegsToLLVMRegs - Used to initialize Dwarf register to LLVM
   /// register number mapping. Called by TableGen auto-generated routines.
   /// *DO NOT USE*.
-  void mapDwarfRegToLLVMReg(unsigned DwarfReg, unsigned LLVMReg, bool isEH=
) {
-    if (isEH)
-      EHDwarf2LRegs[DwarfReg] =3D LLVMReg;
-    else
-      Dwarf2LRegs[DwarfReg] =3D LLVMReg;
+  void mapDwarfRegsToLLVMRegs(const DwarfLLVMRegPair *Map, unsigned Size,
+                              bool isEH) {
+    if (isEH) {
+      EHDwarf2LRegs =3D Map;
+      EHDwarf2LRegsSize =3D Size;
+    } else {
+      Dwarf2LRegs =3D Map;
+      Dwarf2LRegsSize =3D Size;
+    }
   }
-    =20
+
   /// mapLLVMRegToSEHReg - Used to initialize LLVM register to SEH register
   /// number mapping. By default the SEH register number is just the same
   /// as the LLVM register number.
@@ -212,9 +235,9 @@
   /// register, or a null list of there are none.  The list returned is ze=
ro
   /// terminated.
   ///
-  const unsigned *getAliasSet(unsigned RegNo) const {
+  const uint16_t *getAliasSet(unsigned RegNo) const {
     // The Overlaps set always begins with Reg itself.
-    return get(RegNo).Overlaps + 1;
+    return RegLists + get(RegNo).Overlaps + 1;
   }
=20
   /// getOverlaps - Return a list of registers that overlap Reg, including
@@ -222,8 +245,8 @@
   /// list.
   /// These are exactly the registers in { x | regsOverlap(x, Reg) }.
   ///
-  const unsigned *getOverlaps(unsigned RegNo) const {
-    return get(RegNo).Overlaps;
+  const uint16_t *getOverlaps(unsigned RegNo) const {
+    return RegLists + get(RegNo).Overlaps;
   }
=20
   /// getSubRegisters - Return the list of registers that are sub-register=
s of
@@ -231,8 +254,35 @@
   /// returned is zero terminated and sorted according to super-sub regist=
er
   /// relations. e.g. X86::RAX's sub-register list is EAX, AX, AL, AH.
   ///
-  const unsigned *getSubRegisters(unsigned RegNo) const {
-    return get(RegNo).SubRegs;
+  const uint16_t *getSubRegisters(unsigned RegNo) const {
+    return RegLists + get(RegNo).SubRegs;
+  }
+
+  /// getSubReg - Returns the physical register number of sub-register "In=
dex"
+  /// for physical register RegNo. Return zero if the sub-register does not
+  /// exist.
+  unsigned getSubReg(unsigned Reg, unsigned Idx) const {
+    return *(SubRegIndices + (Reg - 1) * NumSubRegIndices + Idx - 1);
+  }
+
+  /// getMatchingSuperReg - Return a super-register of the specified regis=
ter
+  /// Reg so its sub-register of index SubIdx is Reg.
+  unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
+                               const MCRegisterClass *RC) const {
+    for (const uint16_t *SRs =3D getSuperRegisters(Reg); unsigned SR =3D *=
SRs;++SRs)
+      if (Reg =3D=3D getSubReg(SR, SubIdx) && RC->contains(SR))
+        return SR;
+    return 0;
+  }
+
+  /// getSubRegIndex - For a given register pair, return the sub-register =
index
+  /// if the second register is a sub-register of the first. Return zero
+  /// otherwise.
+  unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const {
+    for (unsigned I =3D 1; I <=3D NumSubRegIndices; ++I)
+      if (getSubReg(RegNo, I) =3D=3D SubRegNo)
+        return I;
+    return 0;
   }
=20
   /// getSuperRegisters - Return the list of registers that are super-regi=
sters
@@ -240,8 +290,8 @@
   /// returned is zero terminated and sorted according to super-sub regist=
er
   /// relations. e.g. X86::AL's super-register list is AX, EAX, RAX.
   ///
-  const unsigned *getSuperRegisters(unsigned RegNo) const {
-    return get(RegNo).SuperRegs;
+  const uint16_t *getSuperRegisters(unsigned RegNo) const {
+    return RegLists + get(RegNo).SuperRegs;
   }
=20
   /// getName - Return the human-readable symbolic target-specific name fo=
r the
@@ -261,22 +311,26 @@
   /// parameter allows targets to use different numberings for EH info and
   /// debugging info.
   int getDwarfRegNum(unsigned RegNum, bool isEH) const {
-    const DenseMap<unsigned, int> &M =3D isEH ? EHL2DwarfRegs : L2DwarfReg=
s;
-    const DenseMap<unsigned, int>::const_iterator I =3D M.find(RegNum);
-    if (I =3D=3D M.end()) return -1;
-    return I->second;
+    const DwarfLLVMRegPair *M =3D isEH ? EHL2DwarfRegs : L2DwarfRegs;
+    unsigned Size =3D isEH ? EHL2DwarfRegsSize : L2DwarfRegsSize;
+
+    DwarfLLVMRegPair Key =3D { RegNum, 0 };
+    const DwarfLLVMRegPair *I =3D std::lower_bound(M, M+Size, Key);
+    if (I =3D=3D M+Size || I->FromReg !=3D RegNum)
+      return -1;
+    return I->ToReg;
   }
=20
   /// getLLVMRegNum - Map a dwarf register back to a target register.
   ///
   int getLLVMRegNum(unsigned RegNum, bool isEH) const {
-    const DenseMap<unsigned, unsigned> &M =3D isEH ? EHDwarf2LRegs : Dwarf=
2LRegs;
-    const DenseMap<unsigned, unsigned>::const_iterator I =3D M.find(RegNum=
);
-    if (I =3D=3D M.end()) {
-      assert(0 && "Invalid RegNum");
-      return -1;
-    }
-    return I->second;
+    const DwarfLLVMRegPair *M =3D isEH ? EHDwarf2LRegs : Dwarf2LRegs;
+    unsigned Size =3D isEH ? EHDwarf2LRegsSize : Dwarf2LRegsSize;
+
+    DwarfLLVMRegPair Key =3D { RegNum, 0 };
+    const DwarfLLVMRegPair *I =3D std::lower_bound(M, M+Size, Key);
+    assert(I !=3D M+Size && I->FromReg =3D=3D RegNum && "Invalid RegNum");
+    return I->ToReg;
   }
=20
   /// getSEHRegNum - Map a target register to an equivalent SEH register
@@ -301,7 +355,7 @@
     return Classes[i];
   }
 };
-=20
+
 } // End llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCSe=
ction.h
--- a/head/contrib/llvm/include/llvm/MC/MCSection.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCSection.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,12 +14,10 @@
 #ifndef LLVM_MC_MCSECTION_H
 #define LLVM_MC_MCSECTION_H
=20
-#include "llvm/ADT/StringRef.h"
 #include "llvm/MC/SectionKind.h"
 #include "llvm/Support/Casting.h"
=20
 namespace llvm {
-  class MCContext;
   class MCAsmInfo;
   class raw_ostream;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCSe=
ctionCOFF.h
--- a/head/contrib/llvm/include/llvm/MC/MCSectionCOFF.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCSectionCOFF.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,8 +15,8 @@
 #define LLVM_MC_MCSECTIONCOFF_H
=20
 #include "llvm/MC/MCSection.h"
-
 #include "llvm/Support/COFF.h"
+#include "llvm/ADT/StringRef.h"
=20
 namespace llvm {
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCSe=
ctionELF.h
--- a/head/contrib/llvm/include/llvm/MC/MCSectionELF.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCSectionELF.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -16,6 +16,7 @@
=20
 #include "llvm/MC/MCSection.h"
 #include "llvm/Support/ELF.h"
+#include "llvm/ADT/StringRef.h"
=20
 namespace llvm {
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCSe=
ctionMachO.h
--- a/head/contrib/llvm/include/llvm/MC/MCSectionMachO.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCSectionMachO.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,6 +15,7 @@
 #define LLVM_MC_MCSECTIONMACHO_H
=20
 #include "llvm/MC/MCSection.h"
+#include "llvm/ADT/StringRef.h"
=20
 namespace llvm {
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/MC/MCSt=
reamer.h
--- a/head/contrib/llvm/include/llvm/MC/MCStreamer.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/MC/MCStreamer.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -23,7 +23,6 @@
=20
 namespace llvm {
   class MCAsmBackend;
-  class MCAsmInfo;
   class MCCodeEmitter;
   class MCContext;
   class MCExpr;
@@ -32,7 +31,6 @@
   class MCSection;
   class MCSymbol;
   class StringRef;
-  class TargetLoweringObjectFile;
   class Twine;
   class raw_ostream;
   class formatted_raw_ostream;
@@ -94,6 +92,10 @@
=20
     const MCExpr *ForceExpAbs(const MCExpr* Expr);
=20
+    void RecordProcStart(MCDwarfFrameInfo &Frame);
+    virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
+    void RecordProcEnd(MCDwarfFrameInfo &Frame);
+    virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame);
     void EmitFrames(bool usingCFI);
=20
     MCWin64EHUnwindInfo *getCurrentW64UnwindInfo(){return CurrentW64Unwind=
Info;}
@@ -334,6 +336,11 @@
     /// EndCOFFSymbolDef - Marks the end of the symbol definition.
     virtual void EndCOFFSymbolDef() =3D 0;
=20
+    /// EmitCOFFSecRel32 - Emits a COFF section relative relocation.
+    ///
+    /// @param Symbol - Symbol the section relative realocation should poi=
nt to.
+    virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
+
     /// EmitELFSize - Emit an ELF .size directive.
     ///
     /// This corresponds to an assembler statement such as:
@@ -420,7 +427,8 @@
=20
     /// EmitULEB128Value - Special case of EmitULEB128Value that avoids the
     /// client having to pass in a MCExpr for constant integers.
-    void EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace =3D 0);
+    void EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace =3D 0,
+                             unsigned Padding =3D 0);
=20
     /// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the
     /// client having to pass in a MCExpr for constant integers.
@@ -431,6 +439,13 @@
     void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
                          unsigned AddrSpace =3D 0);
=20
+    /// EmitGPRel64Value - Emit the expression @p Value into the output as=
 a
+    /// gprel64 (64-bit GP relative) value.
+    ///
+    /// This is used to implement assembler directives such as .gpdword on
+    /// targets that support them.
+    virtual void EmitGPRel64Value(const MCExpr *Value);
+
     /// EmitGPRel32Value - Emit the expression @p Value into the output as=
 a
     /// gprel32 (32-bit GP relative) value.
     ///
@@ -493,7 +508,8 @@
     /// @param Offset - The offset to reach. This may be an expression, bu=
t the
     /// expression must be associated with the current section.
     /// @param Value - The value to use when filling bytes.
-    virtual void EmitValueToOffset(const MCExpr *Offset,
+    /// @return false on success, true if the offset was invalid.
+    virtual bool EmitValueToOffset(const MCExpr *Offset,
                                    unsigned char Value =3D 0) =3D 0;
=20
     /// @}
@@ -505,7 +521,8 @@
     /// EmitDwarfFileDirective - Associate a filename with a specified log=
ical
     /// file number.  This implements the DWARF2 '.file 4 "foo.c"' assembl=
er
     /// directive.
-    virtual bool EmitDwarfFileDirective(unsigned FileNo,StringRef Filename=
);
+    virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directo=
ry,
+                                        StringRef Filename);
=20
     /// EmitDwarfLocDirective - This implements the DWARF2
     // '.loc fileno lineno ...' assembler directive.
@@ -529,8 +546,8 @@
=20
     virtual void EmitCompactUnwindEncoding(uint32_t CompactUnwindEncoding);
     virtual void EmitCFISections(bool EH, bool Debug);
-    virtual void EmitCFIStartProc();
-    virtual void EmitCFIEndProc();
+    void EmitCFIStartProc();
+    void EmitCFIEndProc();
     virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
     virtual void EmitCFIDefCfaOffset(int64_t Offset);
     virtual void EmitCFIDefCfaRegister(int64_t Register);
@@ -540,8 +557,11 @@
     virtual void EmitCFIRememberState();
     virtual void EmitCFIRestoreState();
     virtual void EmitCFISameValue(int64_t Register);
+    virtual void EmitCFIRestore(int64_t Register);
     virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
     virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
+    virtual void EmitCFIEscape(StringRef Values);
+    virtual void EmitCFISignalFrame();
=20
     virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
     virtual void EmitWin64EHEndProc();
@@ -581,8 +601,10 @@
     virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
                              bool isVector);
=20
+    /// FinishImpl - Streamer specific finalization.
+    virtual void FinishImpl() =3D 0;
     /// Finish - Finish emission of machine code.
-    virtual void Finish() =3D 0;
+    void Finish();
   };
=20
   /// createNullStreamer - Create a dummy machine code streamer, which does
@@ -613,6 +635,7 @@
                                 bool isVerboseAsm,
                                 bool useLoc,
                                 bool useCFI,
+                                bool useDwarfDirectory,
                                 MCInstPrinter *InstPrint =3D 0,
                                 MCCodeEmitter *CE =3D 0,
                                 MCAsmBackend *TAB =3D 0,
@@ -638,14 +661,8 @@
   /// createELFStreamer - Create a machine code streamer which will genera=
te
   /// ELF format object files.
   MCStreamer *createELFStreamer(MCContext &Ctx, MCAsmBackend &TAB,
-				raw_ostream &OS, MCCodeEmitter *CE,
-				bool RelaxAll, bool NoExecStack);
-
-  /// createLoggingStreamer - Create a machine code streamer which just lo=
gs the
-  /// API calls and then dispatches to another streamer.
-  ///
-  /// The new streamer takes ownership of the \arg Child.
-  MCStreamer *createLoggingStreamer(MCStreamer *Child, raw_ostream &OS);
+                                raw_ostream &OS, MCCodeEmitter *CE,
+                                bool RelaxAll, bool NoExecStack);
=20
   /// createPureStreamer - Create a machine code streamer which will gener=
ate
   /// "pure" MC object files, for use with MC-JIT and testing tools.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Metadat=
a.h
--- a/head/contrib/llvm/include/llvm/Metadata.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm/Metadata.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -36,30 +36,27 @@
 /// These are used to efficiently contain a byte sequence for metadata.
 /// MDString is always unnamed.
 class MDString : public Value {
+  virtual void anchor();
   MDString(const MDString &);            // DO NOT IMPLEMENT
=20
-  StringRef Str;
-  explicit MDString(LLVMContext &C, StringRef S);
-
+  explicit MDString(LLVMContext &C);
 public:
   static MDString *get(LLVMContext &Context, StringRef Str);
   static MDString *get(LLVMContext &Context, const char *Str) {
     return get(Context, Str ? StringRef(Str) : StringRef());
   }
=20
-  StringRef getString() const { return Str; }
+  StringRef getString() const { return getName(); }
=20
-  unsigned getLength() const { return (unsigned)Str.size(); }
+  unsigned getLength() const { return (unsigned)getName().size(); }
=20
   typedef StringRef::iterator iterator;
  =20
   /// begin() - Pointer to the first byte of the string.
-  ///
-  iterator begin() const { return Str.begin(); }
+  iterator begin() const { return getName().begin(); }
=20
   /// end() - Pointer to one byte past the end of the string.
-  ///
-  iterator end() const { return Str.end(); }
+  iterator end() const { return getName().end(); }
=20
   /// Methods for support type inquiry through isa, cast, and dyn_cast:
   static inline bool classof(const MDString *) { return true; }
@@ -78,6 +75,10 @@
   void operator=3D(const MDNode &);        // DO NOT IMPLEMENT
   friend class MDNodeOperand;
   friend class LLVMContextImpl;
+  friend struct FoldingSetTrait<MDNode>;
+
+  /// Hash - If the MDNode is uniqued cache the hash to speed up lookup.
+  unsigned Hash;
=20
   /// NumOperands - This many 'MDNodeOperand' items are co-allocated onto =
the
   /// end of this MDNode.
@@ -134,6 +135,9 @@
   /// deleteTemporary - Deallocate a node created by getTemporary. The
   /// node must not have any users.
   static void deleteTemporary(MDNode *N);
+
+  /// replaceOperandWith - Replace a specific operand.
+  void replaceOperandWith(unsigned i, Value *NewVal);
  =20
   /// getOperand - Return specified operand.
   Value *getOperand(unsigned i) const;
@@ -225,6 +229,9 @@
=20
   /// print - Implement operator<< on NamedMDNode.
   void print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW =3D 0) const;
+
+  /// dump() - Allow printing of NamedMDNodes from the debugger.
+  void dump() const;
 };
=20
 } // end llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Module.h
--- a/head/contrib/llvm/include/llvm/Module.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Module.h	Tue Apr 17 11:51:51 2012 +0300
@@ -30,8 +30,7 @@
 class LLVMContext;
 class StructType;
 template<typename T> struct DenseMapInfo;
-template<typename KeyT, typename ValueT,=20
-         typename KeyInfoT, typename ValueInfoT> class DenseMap;
+template<typename KeyT, typename ValueT, typename KeyInfoT> class DenseMap;
=20
 template<> struct ilist_traits<Function>
   : public SymbolTableListTraits<Function, Module> {
@@ -154,6 +153,39 @@
   /// An enumeration for describing the size of a pointer on the target ma=
chine.
   enum PointerSize { AnyPointerSize, Pointer32, Pointer64 };
=20
+  /// An enumeration for the supported behaviors of module flags. The foll=
owing
+  /// module flags behavior values are supported:
+  ///
+  ///    Value        Behavior
+  ///    -----        --------
+  ///      1          Error
+  ///                   Emits an error if two values disagree.
+  ///
+  ///      2          Warning
+  ///                   Emits a warning if two values disagree.
+  ///
+  ///      3          Require
+  ///                   Emits an error when the specified value is not pre=
sent
+  ///                   or doesn't have the specified value. It is an erro=
r for
+  ///                   two (or more) llvm.module.flags with the same ID t=
o have
+  ///                   the Require behavior but different values. There m=
ay be
+  ///                   multiple Require flags per ID.
+  ///
+  ///      4          Override
+  ///                   Uses the specified value if the two values disagre=
e. It
+  ///                   is an error for two (or more) llvm.module.flags wi=
th the
+  ///                   same ID to have the Override behavior but different
+  ///                   values.
+  enum ModFlagBehavior { Error =3D 1, Warning  =3D 2, Require =3D 3, Overr=
ide =3D 4 };
+
+  struct ModuleFlagEntry {
+    ModFlagBehavior Behavior;
+    MDString *Key;
+    Value *Val;
+    ModuleFlagEntry(ModFlagBehavior B, MDString *K, Value *V)
+      : Behavior(B), Key(K), Val(V) {}
+  };
+
 /// @}
 /// @name Member Variables
 /// @{
@@ -266,8 +298,8 @@
   void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
=20
  =20
-  typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*>,
-                   DenseMapInfo<unsigned> > NumeredTypesMapTy;
+  typedef DenseMap<StructType*, unsigned, DenseMapInfo<StructType*> >
+                   NumeredTypesMapTy;
=20
   /// findUsedStructTypes - Walk the entire module and find all of the
   /// struct types that are in use, returning them in a vector.
@@ -373,6 +405,30 @@
   void eraseNamedMetadata(NamedMDNode *NMD);
=20
 /// @}
+/// @name Module Flags Accessors
+/// @{
+
+  /// getModuleFlagsMetadata - Returns the module flags in the provided ve=
ctor.
+  void getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) con=
st;
+
+  /// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
+  /// represents module-level flags. This method returns null if there are=
 no
+  /// module-level flags.
+  NamedMDNode *getModuleFlagsMetadata() const;
+
+  /// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the modu=
le
+  /// that represents module-level flags. If module-level flags aren't fou=
nd,
+  /// it creates the named metadata that contains them.
+  NamedMDNode *getOrInsertModuleFlagsMetadata();
+
+  /// addModuleFlag - Add a module-level flag to the module-level flags
+  /// metadata. It will create the module-level flags named metadata if it
+  /// doesn't already exist.
+  void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, Value *Val);
+  void addModuleFlag(ModFlagBehavior Behavior, StringRef Key, uint32_t Val=
);
+  void addModuleFlag(MDNode *Node);
+
+/// @}
 /// @name Materialization
 /// @{
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Object/=
Archive.h
--- a/head/contrib/llvm/include/llvm/Object/Archive.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/Object/Archive.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -22,6 +22,7 @@
 namespace object {
=20
 class Archive : public Binary {
+  virtual void anchor();
 public:
   class Child {
     const Archive *Parent;
@@ -34,6 +35,10 @@
       return (Parent =3D=3D other.Parent) && (Data.begin() =3D=3D other.Da=
ta.begin());
     }
=20
+    bool operator <(const Child &other) const {
+      return Data.begin() < other.Data.begin();
+    }
+
     Child getNext() const;
     error_code getName(StringRef &Result) const;
     int getLastModified() const;
@@ -50,6 +55,7 @@
   class child_iterator {
     Child child;
   public:
+    child_iterator() : child(Child(0, StringRef())) {}
     child_iterator(const Child &c) : child(c) {}
     const Child* operator->() const {
       return &child;
@@ -63,24 +69,73 @@
       return !(*this =3D=3D other);
     }
=20
+    bool operator <(const child_iterator &other) const {
+      return child < other.child;
+    }
+
     child_iterator& operator++() {  // Preincrement
       child =3D child.getNext();
       return *this;
     }
   };
=20
+  class Symbol {
+    const Archive *Parent;
+    uint32_t SymbolIndex;
+    uint32_t StringIndex; // Extra index to the string.
+
+  public:
+    bool operator =3D=3D(const Symbol &other) const {
+      return (Parent =3D=3D other.Parent) && (SymbolIndex =3D=3D other.Sym=
bolIndex);
+    }
+
+    Symbol(const Archive *p, uint32_t symi, uint32_t stri)
+      : Parent(p)
+      , SymbolIndex(symi)
+      , StringIndex(stri) {}
+    error_code getName(StringRef &Result) const;
+    error_code getMember(child_iterator &Result) const;
+    Symbol getNext() const;
+  };
+
+  class symbol_iterator {
+    Symbol symbol;
+  public:
+    symbol_iterator(const Symbol &s) : symbol(s) {}
+    const Symbol *operator->() const {
+      return &symbol;
+    }
+
+    bool operator=3D=3D(const symbol_iterator &other) const {
+      return symbol =3D=3D other.symbol;
+    }
+
+    bool operator!=3D(const symbol_iterator &other) const {
+      return !(*this =3D=3D other);
+    }
+
+    symbol_iterator& operator++() {  // Preincrement
+      symbol =3D symbol.getNext();
+      return *this;
+    }
+  };
+
   Archive(MemoryBuffer *source, error_code &ec);
=20
-  child_iterator begin_children() const;
+  child_iterator begin_children(bool skip_internal =3D true) const;
   child_iterator end_children() const;
=20
+  symbol_iterator begin_symbols() const;
+  symbol_iterator end_symbols() const;
+
   // Cast methods.
   static inline bool classof(Archive const *v) { return true; }
   static inline bool classof(Binary const *v) {
-    return v->getType() =3D=3D Binary::isArchive;
+    return v->isArchive();
   }
=20
 private:
+  child_iterator SymbolTable;
   child_iterator StringTable;
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Object/=
Binary.h
--- a/head/contrib/llvm/include/llvm/Object/Binary.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/Object/Binary.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -37,15 +37,24 @@
   Binary(unsigned int Type, MemoryBuffer *Source);
=20
   enum {
-    isArchive,
+    ID_Archive,
+    // Object and children.
+    ID_StartObjects,
+    ID_COFF,
+    ID_ELF32L, // ELF 32-bit, little endian
+    ID_ELF32B, // ELF 32-bit, big endian
+    ID_ELF64L, // ELF 64-bit, little endian
+    ID_ELF64B, // ELF 64-bit, big endian
+    ID_MachO,
+    ID_EndObjects
+  };
=20
-    // Object and children.
-    isObject,
-    isCOFF,
-    isELF,
-    isMachO,
-    lastObject
-  };
+  static inline unsigned int getELFType(bool isLittleEndian, bool is64Bits=
) {
+    if (isLittleEndian)
+      return is64Bits ? ID_ELF64L : ID_ELF32L;
+    else
+      return is64Bits ? ID_ELF64B : ID_ELF32B;
+  }
=20
 public:
   virtual ~Binary();
@@ -56,9 +65,37 @@
   // Cast methods.
   unsigned int getType() const { return TypeID; }
   static inline bool classof(const Binary *v) { return true; }
+
+  // Convenience methods
+  bool isObject() const {
+    return TypeID > ID_StartObjects && TypeID < ID_EndObjects;
+  }
+
+  bool isArchive() const {
+    return TypeID =3D=3D ID_Archive;
+  }
+
+  bool isELF() const {
+    return TypeID >=3D ID_ELF32L && TypeID <=3D ID_ELF64B;
+  }
+
+  bool isMachO() const {
+    return TypeID =3D=3D ID_MachO;
+  }
+
+  bool isCOFF() const {
+    return TypeID =3D=3D ID_COFF;
+  }
 };
=20
+/// @brief Create a Binary from Source, autodetecting the file type.
+///
+/// @param Source The data to create the Binary from. Ownership is transfe=
red
+///        to Result if successful. If an error is returned, Source is des=
troyed
+///        by createBinary before returning.
+/// @param Result A pointer to the resulting Binary if no error occured.
 error_code createBinary(MemoryBuffer *Source, OwningPtr<Binary> &Result);
+
 error_code createBinary(StringRef Path, OwningPtr<Binary> &Result);
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Object/=
COFF.h
--- a/head/contrib/llvm/include/llvm/Object/COFF.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/Object/COFF.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -19,6 +19,9 @@
 #include "llvm/Support/Endian.h"
=20
 namespace llvm {
+  template <typename T>
+  class ArrayRef;
+
 namespace object {
=20
 struct coff_file_header {
@@ -45,13 +48,18 @@
   support::ulittle32_t Value;
   support::little16_t SectionNumber;
=20
-  struct {
-    support::ulittle8_t BaseType;
-    support::ulittle8_t ComplexType;
-  } Type;
+  support::ulittle16_t Type;
=20
   support::ulittle8_t  StorageClass;
   support::ulittle8_t  NumberOfAuxSymbols;
+
+  uint8_t getBaseType() const {
+    return Type & 0x0F;
+  }
+
+  uint8_t getComplexType() const {
+    return (Type & 0xF0) >> 4;
+  }
 };
=20
 struct coff_section {
@@ -73,6 +81,16 @@
   support::ulittle16_t Type;
 };
=20
+struct coff_aux_section_definition {
+  support::ulittle32_t Length;
+  support::ulittle16_t NumberOfRelocations;
+  support::ulittle16_t NumberOfLinenumbers;
+  support::ulittle32_t CheckSum;
+  support::ulittle16_t Number;
+  support::ulittle8_t Selection;
+  char Unused[3];
+};
+
 class COFFObjectFile : public ObjectFile {
 private:
   const coff_file_header *Header;
@@ -81,11 +99,7 @@
   const char             *StringTable;
         uint32_t          StringTableSize;
=20
-        error_code        getSection(int32_t index,
-                                     const coff_section *&Res) const;
         error_code        getString(uint32_t offset, StringRef &Res) const;
-        error_code        getSymbol(uint32_t index,
-                                    const coff_symbol *&Res) const;
=20
   const coff_symbol      *toSymb(DataRefImpl Symb) const;
   const coff_section     *toSec(DataRefImpl Sec) const;
@@ -94,13 +108,14 @@
 protected:
   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
-  virtual error_code getSymbolOffset(DataRefImpl Symb, uint64_t &Res) cons=
t;
+  virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) =
const;
   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) con=
st;
   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) cons=
t;
-  virtual error_code isSymbolInternal(DataRefImpl Symb, bool &Res) const;
-  virtual error_code isSymbolGlobal(DataRefImpl Symb, bool &Res) const;
-  virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::SymbolType=
 &Res) const;
+  virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
+  virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res)=
 const;
+  virtual error_code getSymbolSection(DataRefImpl Symb,
+                                      section_iterator &Res) const;
=20
   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) cons=
t;
   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
@@ -111,6 +126,10 @@
   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
+  virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const;
+  virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const;
+  virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
+                                                   bool &Res) const;
   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Sy=
mb,
                                            bool &Result) const;
   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
@@ -120,10 +139,12 @@
                                        RelocationRef &Res) const;
   virtual error_code getRelocationAddress(DataRefImpl Rel,
                                           uint64_t &Res) const;
+  virtual error_code getRelocationOffset(DataRefImpl Rel,
+                                         uint64_t &Res) const;
   virtual error_code getRelocationSymbol(DataRefImpl Rel,
                                          SymbolRef &Res) const;
   virtual error_code getRelocationType(DataRefImpl Rel,
-                                       uint32_t &Res) const;
+                                       uint64_t &Res) const;
   virtual error_code getRelocationTypeName(DataRefImpl Rel,
                                            SmallVectorImpl<char> &Result) =
const;
   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
@@ -131,16 +152,46 @@
   virtual error_code getRelocationValueString(DataRefImpl Rel,
                                            SmallVectorImpl<char> &Result) =
const;
=20
+  virtual error_code getLibraryNext(DataRefImpl LibData,
+                                    LibraryRef &Result) const;
+  virtual error_code getLibraryPath(DataRefImpl LibData,
+                                    StringRef &Result) const;
+
 public:
   COFFObjectFile(MemoryBuffer *Object, error_code &ec);
   virtual symbol_iterator begin_symbols() const;
   virtual symbol_iterator end_symbols() const;
+  virtual symbol_iterator begin_dynamic_symbols() const;
+  virtual symbol_iterator end_dynamic_symbols() const;
+  virtual library_iterator begin_libraries_needed() const;
+  virtual library_iterator end_libraries_needed() const;
   virtual section_iterator begin_sections() const;
   virtual section_iterator end_sections() const;
=20
   virtual uint8_t getBytesInAddress() const;
   virtual StringRef getFileFormatName() const;
   virtual unsigned getArch() const;
+  virtual StringRef getLoadName() const;
+
+  error_code getHeader(const coff_file_header *&Res) const;
+  error_code getSection(int32_t index, const coff_section *&Res) const;
+  error_code getSymbol(uint32_t index, const coff_symbol *&Res) const;
+  template <typename T>
+  error_code getAuxSymbol(uint32_t index, const T *&Res) const {
+    const coff_symbol *s;
+    error_code ec =3D getSymbol(index, s);
+    Res =3D reinterpret_cast<const T*>(s);
+    return ec;
+  }
+  error_code getSymbolName(const coff_symbol *symbol, StringRef &Res) cons=
t;
+  error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
+  error_code getSectionContents(const coff_section *Sec,
+                                ArrayRef<uint8_t> &Res) const;
+
+  static inline bool classof(const Binary *v) {
+    return v->isCOFF();
+  }
+  static inline bool classof(const COFFObjectFile *v) { return true; }
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Object/=
MachO.h
--- a/head/contrib/llvm/include/llvm/Object/MachO.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/Object/MachO.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -18,6 +18,7 @@
 #include "llvm/Object/ObjectFile.h"
 #include "llvm/Object/MachOObject.h"
 #include "llvm/Support/MachO.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/SmallVector.h"
=20
 namespace llvm {
@@ -31,23 +32,36 @@
=20
   virtual symbol_iterator begin_symbols() const;
   virtual symbol_iterator end_symbols() const;
+  virtual symbol_iterator begin_dynamic_symbols() const;
+  virtual symbol_iterator end_dynamic_symbols() const;
+  virtual library_iterator begin_libraries_needed() const;
+  virtual library_iterator end_libraries_needed() const;
   virtual section_iterator begin_sections() const;
   virtual section_iterator end_sections() const;
=20
   virtual uint8_t getBytesInAddress() const;
   virtual StringRef getFileFormatName() const;
   virtual unsigned getArch() const;
+  virtual StringRef getLoadName() const;
+
+  MachOObject *getObject() { return MachOObj; }
+
+  static inline bool classof(const Binary *v) {
+    return v->isMachO();
+  }
+  static inline bool classof(const MachOObjectFile *v) { return true; }
=20
 protected:
   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
-  virtual error_code getSymbolOffset(DataRefImpl Symb, uint64_t &Res) cons=
t;
+  virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) =
const;
   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) con=
st;
   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) cons=
t;
-  virtual error_code isSymbolInternal(DataRefImpl Symb, bool &Res) const;
-  virtual error_code isSymbolGlobal(DataRefImpl Symb, bool &Res) const;
-  virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::SymbolType=
 &Res) const;
+  virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
+  virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res)=
 const;
+  virtual error_code getSymbolSection(DataRefImpl Symb,
+                                      section_iterator &Res) const;
=20
   virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) cons=
t;
   virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
@@ -58,6 +72,10 @@
   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
+  virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
+                                                   bool &Res) const;
+  virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const;
+  virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const;
   virtual error_code sectionContainsSymbol(DataRefImpl DRI, DataRefImpl S,
                                            bool &Result) const;
   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
@@ -67,16 +85,22 @@
                                        RelocationRef &Res) const;
   virtual error_code getRelocationAddress(DataRefImpl Rel,
                                           uint64_t &Res) const;
+  virtual error_code getRelocationOffset(DataRefImpl Rel,
+                                         uint64_t &Res) const;
   virtual error_code getRelocationSymbol(DataRefImpl Rel,
                                          SymbolRef &Res) const;
   virtual error_code getRelocationType(DataRefImpl Rel,
-                                       uint32_t &Res) const;
+                                       uint64_t &Res) const;
   virtual error_code getRelocationTypeName(DataRefImpl Rel,
                                            SmallVectorImpl<char> &Result) =
const;
   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
                                                  int64_t &Res) const;
   virtual error_code getRelocationValueString(DataRefImpl Rel,
                                            SmallVectorImpl<char> &Result) =
const;
+  virtual error_code getRelocationHidden(DataRefImpl Rel, bool &Result) co=
nst;
+
+  virtual error_code getLibraryNext(DataRefImpl LibData, LibraryRef &Res) =
const;
+  virtual error_code getLibraryPath(DataRefImpl LibData, StringRef &Res) c=
onst;
=20
 private:
   MachOObject *MachOObj;
@@ -97,6 +121,9 @@
   void getRelocation(DataRefImpl Rel,
                      InMemoryStruct<macho::RelocationEntry> &Res) const;
   std::size_t getSectionIndex(DataRefImpl Sec) const;
+
+  void printRelocationTargetName(InMemoryStruct<macho::RelocationEntry>& R=
E,
+                                 raw_string_ostream &fmt) const;
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Object/=
MachOObject.h
--- a/head/contrib/llvm/include/llvm/Object/MachOObject.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Object/MachOObject.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -177,14 +177,14 @@
   void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const;
=20
   /// @}
- =20
+
   /// @name Object Dump Facilities
   /// @{
   /// dump - Support for debugging, callable in GDB: V->dump()
   //
   void dump() const;
   void dumpHeader() const;
- =20
+
   /// print - Implement operator<< on Value.
   ///
   void print(raw_ostream &O) const;
@@ -192,7 +192,7 @@
=20
   /// @}
 };
- =20
+
 inline raw_ostream &operator<<(raw_ostream &OS, const MachOObject &V) {
   V.print(OS);
   return OS;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Object/=
ObjectFile.h
--- a/head/contrib/llvm/include/llvm/Object/ObjectFile.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Object/ObjectFile.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -20,6 +20,7 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include <cstring>
+#include <vector>
=20
 namespace llvm {
 namespace object {
@@ -37,6 +38,9 @@
     uint32_t a, b;
   } d;
   uintptr_t p;
+  DataRefImpl() {
+    std::memset(this, 0, sizeof(DataRefImpl));
+  }
 };
=20
 template<class content_type>
@@ -78,52 +82,13 @@
   return std::memcmp(&a, &b, sizeof(DataRefImpl)) =3D=3D 0;
 }
=20
-/// SymbolRef - This is a value type class that represents a single symbol=
 in
-/// the list of symbols in the object file.
-class SymbolRef {
-  friend class SectionRef;
-  DataRefImpl SymbolPimpl;
-  const ObjectFile *OwningObject;
+static bool operator <(const DataRefImpl &a, const DataRefImpl &b) {
+  // Check bitwise identical. This is the only legal way to compare a unio=
n w/o
+  // knowing which member is in use.
+  return std::memcmp(&a, &b, sizeof(DataRefImpl)) < 0;
+}
=20
-public:
-  SymbolRef() : OwningObject(NULL) {
-    std::memset(&SymbolPimpl, 0, sizeof(SymbolPimpl));
-  }
-
-  enum SymbolType {
-    ST_Function,
-    ST_Data,
-    ST_External,    // Defined in another object file
-    ST_Other
-  };
-
-  SymbolRef(DataRefImpl SymbolP, const ObjectFile *Owner);
-
-  bool operator=3D=3D(const SymbolRef &Other) const;
-
-  error_code getNext(SymbolRef &Result) const;
-
-  error_code getName(StringRef &Result) const;
-  error_code getAddress(uint64_t &Result) const;
-  error_code getOffset(uint64_t &Result) const;
-  error_code getSize(uint64_t &Result) const;
-  error_code getSymbolType(SymbolRef::SymbolType &Result) const;
-
-  /// Returns the ascii char that should be displayed in a symbol table du=
mp via
-  /// nm for this symbol.
-  error_code getNMTypeChar(char &Result) const;
-
-  /// Returns true for symbols that are internal to the object file format=
 such
-  /// as section symbols.
-  error_code isInternal(bool &Result) const;
-
-  /// Returns true for symbols that can be used in another objects,
-  /// such as library functions
-  error_code isGlobal(bool &Result) const;
-
-  DataRefImpl getRawDataRefImpl() const;
-};
-typedef content_iterator<SymbolRef> symbol_iterator;
+class SymbolRef;
=20
 /// RelocationRef - This is a value type class that represents a single
 /// relocation in the list of relocations in the object file.
@@ -132,9 +97,7 @@
   const ObjectFile *OwningObject;
=20
 public:
-  RelocationRef() : OwningObject(NULL) {
-    std::memset(&RelocationPimpl, 0, sizeof(RelocationPimpl));
-  }
+  RelocationRef() : OwningObject(NULL) { }
=20
   RelocationRef(DataRefImpl RelocationP, const ObjectFile *Owner);
=20
@@ -143,8 +106,14 @@
   error_code getNext(RelocationRef &Result) const;
=20
   error_code getAddress(uint64_t &Result) const;
+  error_code getOffset(uint64_t &Result) const;
   error_code getSymbol(SymbolRef &Result) const;
-  error_code getType(uint32_t &Result) const;
+  error_code getType(uint64_t &Result) const;
+
+  /// @brief Indicates whether this relocation should hidden when listing
+  /// relocations, usually because it is the trailing part of a multipart
+  /// relocation that will be printed as part of the leading relocation.
+  error_code getHidden(bool &Result) const;
=20
   /// @brief Get a string that represents the type of this relocation.
   ///
@@ -168,13 +137,12 @@
   const ObjectFile *OwningObject;
=20
 public:
-  SectionRef() : OwningObject(NULL) {
-    std::memset(&SectionPimpl, 0, sizeof(SectionPimpl));
-  }
+  SectionRef() : OwningObject(NULL) { }
=20
   SectionRef(DataRefImpl SectionP, const ObjectFile *Owner);
=20
   bool operator=3D=3D(const SectionRef &Other) const;
+  bool operator <(const SectionRef &Other) const;
=20
   error_code getNext(SectionRef &Result) const;
=20
@@ -190,21 +158,112 @@
   error_code isText(bool &Result) const;
   error_code isData(bool &Result) const;
   error_code isBSS(bool &Result) const;
+  error_code isRequiredForExecution(bool &Result) const;
+  error_code isVirtual(bool &Result) const;
+  error_code isZeroInit(bool &Result) const;
=20
   error_code containsSymbol(SymbolRef S, bool &Result) const;
=20
   relocation_iterator begin_relocations() const;
   relocation_iterator end_relocations() const;
+
+  DataRefImpl getRawDataRefImpl() const;
 };
 typedef content_iterator<SectionRef> section_iterator;
=20
+/// SymbolRef - This is a value type class that represents a single symbol=
 in
+/// the list of symbols in the object file.
+class SymbolRef {
+  friend class SectionRef;
+  DataRefImpl SymbolPimpl;
+  const ObjectFile *OwningObject;
+
+public:
+  SymbolRef() : OwningObject(NULL) { }
+
+  enum Type {
+    ST_Unknown, // Type not specified
+    ST_Data,
+    ST_Debug,
+    ST_File,
+    ST_Function,
+    ST_Other
+  };
+
+  enum Flags {
+    SF_None            =3D 0,
+    SF_Undefined       =3D 1U << 0,  // Symbol is defined in another objec=
t file
+    SF_Global          =3D 1U << 1,  // Global symbol
+    SF_Weak            =3D 1U << 2,  // Weak symbol
+    SF_Absolute        =3D 1U << 3,  // Absolute symbol
+    SF_ThreadLocal     =3D 1U << 4,  // Thread local symbol
+    SF_Common          =3D 1U << 5,  // Symbol has common linkage
+    SF_FormatSpecific  =3D 1U << 31  // Specific to the object file format
+                                   // (e.g. section symbols)
+  };
+
+  SymbolRef(DataRefImpl SymbolP, const ObjectFile *Owner);
+
+  bool operator=3D=3D(const SymbolRef &Other) const;
+  bool operator <(const SymbolRef &Other) const;
+
+  error_code getNext(SymbolRef &Result) const;
+
+  error_code getName(StringRef &Result) const;
+  error_code getAddress(uint64_t &Result) const;
+  error_code getFileOffset(uint64_t &Result) const;
+  error_code getSize(uint64_t &Result) const;
+  error_code getType(SymbolRef::Type &Result) const;
+
+  /// Returns the ascii char that should be displayed in a symbol table du=
mp via
+  /// nm for this symbol.
+  error_code getNMTypeChar(char &Result) const;
+
+  /// Get symbol flags (bitwise OR of SymbolRef::Flags)
+  error_code getFlags(uint32_t &Result) const;
+
+  /// @brief Return true for common symbols such as uninitialized globals
+  error_code isCommon(bool &Result) const;
+
+  /// @brief Get section this symbol is defined in reference to. Result is
+  /// end_sections() if it is undefined or is an absolute symbol.
+  error_code getSection(section_iterator &Result) const;
+
+  DataRefImpl getRawDataRefImpl() const;
+};
+typedef content_iterator<SymbolRef> symbol_iterator;
+
+/// LibraryRef - This is a value type class that represents a single libra=
ry in
+/// the list of libraries needed by a shared or dynamic object.
+class LibraryRef {
+  friend class SectionRef;
+  DataRefImpl LibraryPimpl;
+  const ObjectFile *OwningObject;
+
+public:
+  LibraryRef() : OwningObject(NULL) { }
+
+  LibraryRef(DataRefImpl LibraryP, const ObjectFile *Owner);
+
+  bool operator=3D=3D(const LibraryRef &Other) const;
+  bool operator <(const LibraryRef &Other) const;
+
+  error_code getNext(LibraryRef &Result) const;
+
+  // Get the path to this library, as stored in the object file.
+  error_code getPath(StringRef &Result) const;
+
+  DataRefImpl getRawDataRefImpl() const;
+};
+typedef content_iterator<LibraryRef> library_iterator;
+
 const uint64_t UnknownAddressOrSize =3D ~0ULL;
=20
 /// ObjectFile - This class is the base class for all object file types.
 /// Concrete instances of this object are created by createObjectFile, whi=
ch
 /// figure out which type to create.
 class ObjectFile : public Binary {
-private:
+  virtual void anchor();
   ObjectFile(); // =3D delete
   ObjectFile(const ObjectFile &other); // =3D delete
=20
@@ -227,12 +286,15 @@
   virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const=
 =3D 0;
   virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const=
 =3D 0;
   virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) con=
st =3D0;
-  virtual error_code getSymbolOffset(DataRefImpl Symb, uint64_t &Res) cons=
t =3D0;
+  virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) =
const =3D0;
   virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const =
=3D 0;
+  virtual error_code getSymbolType(DataRefImpl Symb,
+                                   SymbolRef::Type &Res) const =3D 0;
   virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) cons=
t =3D 0;
-  virtual error_code isSymbolInternal(DataRefImpl Symb, bool &Res) const =
=3D 0;
-  virtual error_code isSymbolGlobal(DataRefImpl Symb, bool &Res) const =3D=
 0;
-  virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::SymbolType=
 &Res) const =3D 0;
+  virtual error_code getSymbolFlags(DataRefImpl Symb,
+                                    uint32_t &Res) const =3D 0;
+  virtual error_code getSymbolSection(DataRefImpl Symb,
+                                      section_iterator &Res) const =3D 0;
=20
   // Same as above for SectionRef.
   friend class SectionRef;
@@ -245,6 +307,11 @@
   virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const =3D 0;
   virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const =3D 0;
   virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const =3D 0;
+  virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
+                                                   bool &Res) const =3D 0;
+  // A section is 'virtual' if its contents aren't present in the object i=
mage.
+  virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const =
=3D 0;
+  virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const =
=3D 0;
   virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Sy=
mb,
                                            bool &Result) const =3D 0;
   virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const =
=3D 0;
@@ -257,25 +324,42 @@
                                        RelocationRef &Res) const =3D 0;
   virtual error_code getRelocationAddress(DataRefImpl Rel,
                                           uint64_t &Res) const =3D0;
+  virtual error_code getRelocationOffset(DataRefImpl Rel,
+                                         uint64_t &Res) const =3D0;
   virtual error_code getRelocationSymbol(DataRefImpl Rel,
                                          SymbolRef &Res) const =3D 0;
   virtual error_code getRelocationType(DataRefImpl Rel,
-                                       uint32_t &Res) const =3D 0;
+                                       uint64_t &Res) const =3D 0;
   virtual error_code getRelocationTypeName(DataRefImpl Rel,
                                        SmallVectorImpl<char> &Result) cons=
t =3D 0;
   virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
                                                  int64_t &Res) const =3D 0;
   virtual error_code getRelocationValueString(DataRefImpl Rel,
                                        SmallVectorImpl<char> &Result) cons=
t =3D 0;
+  virtual error_code getRelocationHidden(DataRefImpl Rel, bool &Result) co=
nst {
+    Result =3D false;
+    return object_error::success;
+  }
+
+  // Same for LibraryRef
+  friend class LibraryRef;
+  virtual error_code getLibraryNext(DataRefImpl Lib, LibraryRef &Res) cons=
t =3D 0;
+  virtual error_code getLibraryPath(DataRefImpl Lib, StringRef &Res) const=
 =3D 0;
=20
 public:
=20
   virtual symbol_iterator begin_symbols() const =3D 0;
   virtual symbol_iterator end_symbols() const =3D 0;
=20
+  virtual symbol_iterator begin_dynamic_symbols() const =3D 0;
+  virtual symbol_iterator end_dynamic_symbols() const =3D 0;
+
   virtual section_iterator begin_sections() const =3D 0;
   virtual section_iterator end_sections() const =3D 0;
=20
+  virtual library_iterator begin_libraries_needed() const =3D 0;
+  virtual library_iterator end_libraries_needed() const =3D 0;
+
   /// @brief The number of bytes used to represent an address in this obje=
ct
   ///        file format.
   virtual uint8_t getBytesInAddress() const =3D 0;
@@ -283,6 +367,11 @@
   virtual StringRef getFileFormatName() const =3D 0;
   virtual /* Triple::ArchType */ unsigned getArch() const =3D 0;
=20
+  /// For shared objects, returns the name which this object should be
+  /// loaded from at runtime. This corresponds to DT_SONAME on ELF and
+  /// LC_ID_DYLIB (install name) on MachO.
+  virtual StringRef getLoadName() const =3D 0;
+
   /// @returns Pointer to ObjectFile subclass to handle this type of objec=
t.
   /// @param ObjectPath The path to the object file. ObjectPath.isObject m=
ust
   ///        return true.
@@ -291,8 +380,7 @@
   static ObjectFile *createObjectFile(MemoryBuffer *Object);
=20
   static inline bool classof(const Binary *v) {
-    return v->getType() >=3D isObject &&
-           v->getType() < lastObject;
+    return v->isObject();
   }
   static inline bool classof(const ObjectFile *v) { return true; }
=20
@@ -311,6 +399,10 @@
   return SymbolPimpl =3D=3D Other.SymbolPimpl;
 }
=20
+inline bool SymbolRef::operator <(const SymbolRef &Other) const {
+  return SymbolPimpl < Other.SymbolPimpl;
+}
+
 inline error_code SymbolRef::getNext(SymbolRef &Result) const {
   return OwningObject->getSymbolNext(SymbolPimpl, Result);
 }
@@ -323,8 +415,8 @@
   return OwningObject->getSymbolAddress(SymbolPimpl, Result);
 }
=20
-inline error_code SymbolRef::getOffset(uint64_t &Result) const {
-  return OwningObject->getSymbolOffset(SymbolPimpl, Result);
+inline error_code SymbolRef::getFileOffset(uint64_t &Result) const {
+  return OwningObject->getSymbolFileOffset(SymbolPimpl, Result);
 }
=20
 inline error_code SymbolRef::getSize(uint64_t &Result) const {
@@ -335,15 +427,15 @@
   return OwningObject->getSymbolNMTypeChar(SymbolPimpl, Result);
 }
=20
-inline error_code SymbolRef::isInternal(bool &Result) const {
-  return OwningObject->isSymbolInternal(SymbolPimpl, Result);
+inline error_code SymbolRef::getFlags(uint32_t &Result) const {
+  return OwningObject->getSymbolFlags(SymbolPimpl, Result);
 }
=20
-inline error_code SymbolRef::isGlobal(bool &Result) const {
-  return OwningObject->isSymbolGlobal(SymbolPimpl, Result);
+inline error_code SymbolRef::getSection(section_iterator &Result) const {
+  return OwningObject->getSymbolSection(SymbolPimpl, Result);
 }
=20
-inline error_code SymbolRef::getSymbolType(SymbolRef::SymbolType &Result) =
const {
+inline error_code SymbolRef::getType(SymbolRef::Type &Result) const {
   return OwningObject->getSymbolType(SymbolPimpl, Result);
 }
=20
@@ -362,6 +454,10 @@
   return SectionPimpl =3D=3D Other.SectionPimpl;
 }
=20
+inline bool SectionRef::operator <(const SectionRef &Other) const {
+  return SectionPimpl < Other.SectionPimpl;
+}
+
 inline error_code SectionRef::getNext(SectionRef &Result) const {
   return OwningObject->getSectionNext(SectionPimpl, Result);
 }
@@ -398,6 +494,18 @@
   return OwningObject->isSectionBSS(SectionPimpl, Result);
 }
=20
+inline error_code SectionRef::isRequiredForExecution(bool &Result) const {
+  return OwningObject->isSectionRequiredForExecution(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isVirtual(bool &Result) const {
+  return OwningObject->isSectionVirtual(SectionPimpl, Result);
+}
+
+inline error_code SectionRef::isZeroInit(bool &Result) const {
+  return OwningObject->isSectionZeroInit(SectionPimpl, Result);
+}
+
 inline error_code SectionRef::containsSymbol(SymbolRef S, bool &Result) co=
nst {
   return OwningObject->sectionContainsSymbol(SectionPimpl, S.SymbolPimpl,
                                              Result);
@@ -411,6 +519,9 @@
   return OwningObject->getSectionRelEnd(SectionPimpl);
 }
=20
+inline DataRefImpl SectionRef::getRawDataRefImpl() const {
+  return SectionPimpl;
+}
=20
 /// RelocationRef
 inline RelocationRef::RelocationRef(DataRefImpl RelocationP,
@@ -430,11 +541,15 @@
   return OwningObject->getRelocationAddress(RelocationPimpl, Result);
 }
=20
+inline error_code RelocationRef::getOffset(uint64_t &Result) const {
+  return OwningObject->getRelocationOffset(RelocationPimpl, Result);
+}
+
 inline error_code RelocationRef::getSymbol(SymbolRef &Result) const {
   return OwningObject->getRelocationSymbol(RelocationPimpl, Result);
 }
=20
-inline error_code RelocationRef::getType(uint32_t &Result) const {
+inline error_code RelocationRef::getType(uint64_t &Result) const {
   return OwningObject->getRelocationType(RelocationPimpl, Result);
 }
=20
@@ -452,6 +567,30 @@
   return OwningObject->getRelocationValueString(RelocationPimpl, Result);
 }
=20
+inline error_code RelocationRef::getHidden(bool &Result) const {
+  return OwningObject->getRelocationHidden(RelocationPimpl, Result);
+}
+// Inline function definitions.
+inline LibraryRef::LibraryRef(DataRefImpl LibraryP, const ObjectFile *Owne=
r)
+  : LibraryPimpl(LibraryP)
+  , OwningObject(Owner) {}
+
+inline bool LibraryRef::operator=3D=3D(const LibraryRef &Other) const {
+  return LibraryPimpl =3D=3D Other.LibraryPimpl;
+}
+
+inline bool LibraryRef::operator <(const LibraryRef &Other) const {
+  return LibraryPimpl < Other.LibraryPimpl;
+}
+
+inline error_code LibraryRef::getNext(LibraryRef &Result) const {
+  return OwningObject->getLibraryNext(LibraryPimpl, Result);
+}
+
+inline error_code LibraryRef::getPath(StringRef &Result) const {
+  return OwningObject->getLibraryPath(LibraryPimpl, Result);
+}
+
 } // end namespace object
 } // end namespace llvm
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Operato=
r.h
--- a/head/contrib/llvm/include/llvm/Operator.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/include/llvm/Operator.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -261,8 +261,8 @@
=20
   /// getPointerOperandType - Method to return the pointer operand as a
   /// PointerType.
-  PointerType *getPointerOperandType() const {
-    return reinterpret_cast<PointerType*>(getPointerOperand()->getType());
+  Type *getPointerOperandType() const {
+    return getPointerOperand()->getType();
   }
=20
   unsigned getNumIndices() const {  // Note: always non-negative
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Pass.h
--- a/head/contrib/llvm/include/llvm/Pass.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Pass.h	Tue Apr 17 11:51:51 2012 +0300
@@ -53,7 +53,7 @@
 /// Ordering of pass manager types is important here.
 enum PassManagerType {
   PMT_Unknown =3D 0,
-  PMT_ModulePassManager =3D 1, ///< MPPassManager=20
+  PMT_ModulePassManager =3D 1, ///< MPPassManager
   PMT_CallGraphPassManager,  ///< CGPassManager
   PMT_FunctionPassManager,   ///< FPPassManager
   PMT_LoopPassManager,       ///< LPPassManager
@@ -84,14 +84,14 @@
   PassKind Kind;
   void operator=3D(const Pass&);  // DO NOT IMPLEMENT
   Pass(const Pass &);           // DO NOT IMPLEMENT
- =20
+
 public:
-  explicit Pass(PassKind K, char &pid);
+  explicit Pass(PassKind K, char &pid) : Resolver(0), PassID(&pid), Kind(K=
) { }
   virtual ~Pass();
=20
- =20
+
   PassKind getPassKind() const { return Kind; }
- =20
+
   /// getPassName - Return a nice clean name for a pass.  This usually
   /// implemented in terms of the name that is registered by one of the
   /// Registration templates, but can be overloaded directly.
@@ -99,7 +99,7 @@
   virtual const char *getPassName() const;
=20
   /// getPassID - Return the PassID number that corresponds to this pass.
-  virtual AnalysisID getPassID() const {
+  AnalysisID getPassID() const {
     return PassID;
   }
=20
@@ -119,12 +119,12 @@
                                   const std::string &Banner) const =3D 0;
=20
   /// Each pass is responsible for assigning a pass manager to itself.
-  /// PMS is the stack of available pass manager.=20
-  virtual void assignPassManager(PMStack &,=20
+  /// PMS is the stack of available pass manager.
+  virtual void assignPassManager(PMStack &,
                                  PassManagerType) {}
   /// Check if available pass managers are suitable for this pass or not.
   virtual void preparePassManager(PMStack &);
- =20
+
   ///  Return what kind of Pass Manager can manage this pass.
   virtual PassManagerType getPotentialPassManagerType() const;
=20
@@ -159,9 +159,9 @@
   virtual void *getAdjustedAnalysisPointer(AnalysisID ID);
   virtual ImmutablePass *getAsImmutablePass();
   virtual PMDataManager *getAsPMDataManager();
- =20
+
   /// verifyAnalysis() - This member can be implemented by a analysis pass=
 to
-  /// check state of analysis information.=20
+  /// check state of analysis information.
   virtual void verifyAnalysis() const;
=20
   // dumpPassStructure - Implement the -debug-passes=3DPassStructure option
@@ -175,6 +175,10 @@
   // argument string, or null if it is not known.
   static const PassInfo *lookupPassInfo(StringRef Arg);
=20
+  // createPass - Create a object for the specified pass class,
+  // or null if it is not known.
+  static Pass *createPass(AnalysisID ID);
+
   /// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this functio=
n to
   /// get analysis information that might be around, for example to update=
 it.
   /// This is different than getAnalysis in that it can fail (if the analy=
sis
@@ -226,7 +230,7 @@
   /// being operated on.
   virtual bool runOnModule(Module &M) =3D 0;
=20
-  virtual void assignPassManager(PMStack &PMS,=20
+  virtual void assignPassManager(PMStack &PMS,
                                  PassManagerType T);
=20
   ///  Return what kind of Pass Manager can manage this pass.
@@ -259,9 +263,9 @@
   ///
   bool runOnModule(Module &) { return false; }
=20
-  explicit ImmutablePass(char &pid)=20
+  explicit ImmutablePass(char &pid)
   : ModulePass(pid) {}
- =20
+
   // Force out-of-line virtual method.
   virtual ~ImmutablePass();
 };
@@ -286,7 +290,7 @@
   /// any necessary per-module initialization.
   ///
   virtual bool doInitialization(Module &);
- =20
+
   /// runOnFunction - Virtual method overriden by subclasses to do the
   /// per-function processing of the pass.
   ///
@@ -297,7 +301,7 @@
   ///
   virtual bool doFinalization(Module &);
=20
-  virtual void assignPassManager(PMStack &PMS,=20
+  virtual void assignPassManager(PMStack &PMS,
                                  PassManagerType T);
=20
   ///  Return what kind of Pass Manager can manage this pass.
@@ -348,7 +352,7 @@
   ///
   virtual bool doFinalization(Module &);
=20
-  virtual void assignPassManager(PMStack &PMS,=20
+  virtual void assignPassManager(PMStack &PMS,
                                  PassManagerType T);
=20
   ///  Return what kind of Pass Manager can manage this pass.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/PassAna=
lysisSupport.h
--- a/head/contrib/llvm/include/llvm/PassAnalysisSupport.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/PassAnalysisSupport.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -19,6 +19,7 @@
 #ifndef LLVM_PASS_ANALYSIS_SUPPORT_H
 #define LLVM_PASS_ANALYSIS_SUPPORT_H
=20
+#include "llvm/Pass.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include <vector>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/PassMan=
ager.h
--- a/head/contrib/llvm/include/llvm/PassManager.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/PassManager.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -53,17 +53,13 @@
   /// will be destroyed as well, so there is no need to delete the pass.  =
This
   /// implies that all passes MUST be allocated with 'new'.
   void add(Pass *P);
-=20
+
   /// run - Execute all of the passes scheduled for execution.  Keep track=
 of
   /// whether any of the passes modifies the module, and if so, return tru=
e.
   bool run(Module &M);
=20
 private:
-  /// addImpl - Add a pass to the queue of passes to run, without
-  /// checking whether to add a printer pass.
-  void addImpl(Pass *P);
-
-  /// PassManagerImpl_New is the actual class. PassManager is just the=20
+  /// PassManagerImpl_New is the actual class. PassManager is just the
   /// wraper to publish simple pass manager interface
   PassManagerImpl *PM;
 };
@@ -75,11 +71,11 @@
   /// but does not take ownership of, the specified Module.
   explicit FunctionPassManager(Module *M);
   ~FunctionPassManager();
-=20
+
   /// add - Add a pass to the queue of passes to run.  This passes
   /// ownership of the Pass to the PassManager.  When the
   /// PassManager_X is destroyed, the pass will be destroyed as well, so
-  /// there is no need to delete the pass. (TODO delete passes.)
+  /// there is no need to delete the pass.
   /// This implies that all passes MUST be allocated with 'new'.
   void add(Pass *P);
=20
@@ -88,20 +84,16 @@
   /// so, return true.
   ///
   bool run(Function &F);
- =20
+
   /// doInitialization - Run all of the initializers for the function pass=
es.
   ///
   bool doInitialization();
- =20
+
   /// doFinalization - Run all of the finalizers for the function passes.
   ///
   bool doFinalization();
- =20
+
 private:
-  /// addImpl - Add a pass to the queue of passes to run, without
-  /// checking whether to add a printer pass.
-  void addImpl(Pass *P);
-
   FunctionPassManagerImpl *FPM;
   Module *M;
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/PassMan=
agers.h
--- a/head/contrib/llvm/include/llvm/PassManagers.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/PassManagers.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -7,7 +7,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-// This file declares the LLVM Pass Manager infrastructure.=20
+// This file declares the LLVM Pass Manager infrastructure.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -24,11 +24,11 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Overview:
 // The Pass Manager Infrastructure manages passes. It's responsibilities a=
re:
-//=20
+//
 //   o Manage optimization pass execution order
 //   o Make required Analysis information available before pass P is run
 //   o Release memory occupied by dead passes
-//   o If Analysis information is dirtied by a pass then regenerate Analys=
is=20
+//   o If Analysis information is dirtied by a pass then regenerate Analys=
is
 //     information before it is consumed by another pass.
 //
 // Pass Manager Infrastructure uses multiple pass managers.  They are
@@ -43,13 +43,13 @@
 //
 // [o] class PMTopLevelManager;
 //
-// Two top level managers, PassManager and FunctionPassManager, derive fro=
m=20
-// PMTopLevelManager. PMTopLevelManager manages information used by top le=
vel=20
+// Two top level managers, PassManager and FunctionPassManager, derive from
+// PMTopLevelManager. PMTopLevelManager manages information used by top le=
vel
 // managers such as last user info.
 //
 // [o] class PMDataManager;
 //
-// PMDataManager manages information, e.g. list of available analysis info=
,=20
+// PMDataManager manages information, e.g. list of available analysis info,
 // used by a pass manager to manage execution order of passes. It also pro=
vides
 // a place to implement common pass manager APIs. All pass managers derive=
 from
 // PMDataManager.
@@ -82,7 +82,7 @@
 // relies on PassManagerImpl to do all the tasks.
 //
 // [o] class PassManagerImpl : public Pass, public PMDataManager,
-//                             public PMDTopLevelManager
+//                             public PMTopLevelManager
 //
 // PassManagerImpl is a top level pass manager responsible for managing
 // MPPassManagers.
@@ -109,7 +109,7 @@
   ON_REGION_MSG, // " 'on Region ...\n'"
   ON_LOOP_MSG, // " 'on Loop ...\n'"
   ON_CG_MSG // "' on Call Graph ...\n'"
-}; =20
+};
=20
 /// PassManagerPrettyStackEntry - This is used to print informative inform=
ation
 /// about what pass is running when/if a stack trace is generated.
@@ -124,19 +124,19 @@
     : P(p), V(&v), M(0) {} // When P is run on V
   PassManagerPrettyStackEntry(Pass *p, Module &m)
     : P(p), V(0), M(&m) {} // When P is run on M
- =20
+
   /// print - Emit information about this stack frame to OS.
   virtual void print(raw_ostream &OS) const;
 };
- =20
- =20
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PMStack
 //
 /// PMStack - This class implements a stack data structure of PMDataManager
 /// pointers.
 ///
-/// Top level pass managers (see PassManager.cpp) maintain active Pass Man=
agers=20
+/// Top level pass managers (see PassManager.cpp) maintain active Pass Man=
agers
 /// using PMStack. Each Pass implements assignPassManager() to connect its=
elf
 /// with appropriate manager. assignPassManager() walks PMStack to find
 /// suitable manager.
@@ -174,9 +174,8 @@
   void initializeAllAnalysisInfo();
=20
 private:
-  /// This is implemented by top level pass manager and used by=20
-  /// schedulePass() to add analysis info passes that are not available.
-  virtual void addTopLevelPass(Pass  *P) =3D 0;
+  virtual PMDataManager *getAsPMDataManager() =3D 0;
+  virtual PassManagerType getTopLevelPassManagerType() =3D 0;
=20
 public:
   /// Schedule pass P for execution. Make sure that passes required by
@@ -198,7 +197,7 @@
   /// Find analysis usage information for the pass P.
   AnalysisUsage *findAnalysisUsage(Pass *P);
=20
-  virtual ~PMTopLevelManager();=20
+  virtual ~PMTopLevelManager();
=20
   /// Add immutable pass and initialize it.
   inline void addImmutablePass(ImmutablePass *P) {
@@ -228,7 +227,7 @@
   PMStack activeStack;
=20
 protected:
- =20
+
   /// Collection of pass managers
   SmallVector<PMDataManager *, 8> PassManagers;
=20
@@ -254,7 +253,7 @@
 };
=20
=20
- =20
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PMDataManager
=20
@@ -268,7 +267,7 @@
   }
=20
   virtual ~PMDataManager();
- =20
+
   virtual Pass *getAsPass() =3D 0;
=20
   /// Augment AvailableAnalysis by adding analysis made available by pass =
P.
@@ -279,16 +278,16 @@
=20
   /// Remove Analysis that is not preserved by the pass
   void removeNotPreservedAnalysis(Pass *P);
- =20
+
   /// Remove dead passes used by P.
-  void removeDeadPasses(Pass *P, StringRef Msg,=20
+  void removeDeadPasses(Pass *P, StringRef Msg,
                         enum PassDebuggingString);
=20
   /// Remove P.
-  void freePass(Pass *P, StringRef Msg,=20
+  void freePass(Pass *P, StringRef Msg,
                 enum PassDebuggingString);
=20
-  /// Add pass P into the PassVector. Update=20
+  /// Add pass P into the PassVector. Update
   /// AvailableAnalysis appropriately if ProcessAnalysis is true.
   void add(Pass *P, bool ProcessAnalysis =3D true);
=20
@@ -300,7 +299,7 @@
   virtual Pass *getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F);
=20
   /// Initialize available analysis information.
-  void initializeAnalysisInfo() {=20
+  void initializeAnalysisInfo() {
     AvailableAnalysis.clear();
     for (unsigned i =3D 0; i < PMT_Last; ++i)
       InheritedAnalysis[i] =3D NULL;
@@ -347,9 +346,9 @@
     return (unsigned)PassVector.size();
   }
=20
-  virtual PassManagerType getPassManagerType() const {=20
+  virtual PassManagerType getPassManagerType() const {
     assert ( 0 && "Invalid use of getPassManagerType");
-    return PMT_Unknown;=20
+    return PMT_Unknown;
   }
=20
   std::map<AnalysisID, Pass*> *getAvailableAnalysis() {
@@ -377,17 +376,17 @@
   // then PMT_Last active pass mangers.
   std::map<AnalysisID, Pass *> *InheritedAnalysis[PMT_Last];
=20
- =20
+
   /// isPassDebuggingExecutionsOrMore - Return true if -debug-pass=3DExecu=
tions
   /// or higher is specified.
   bool isPassDebuggingExecutionsOrMore() const;
- =20
+
 private:
   void dumpAnalysisUsage(StringRef Msg, const Pass *P,
                          const AnalysisUsage::VectorType &Set) const;
=20
-  // Set of available Analysis. This information is used while scheduling=20
-  // pass. If a pass requires an analysis which is not available then=20
+  // Set of available Analysis. This information is used while scheduling
+  // pass. If a pass requires an analysis which is not available then
   // the required analysis pass is scheduled to run before the pass itself=
 is
   // scheduled to run.
   std::map<AnalysisID, Pass*> AvailableAnalysis;
@@ -403,27 +402,27 @@
 // FPPassManager
 //
 /// FPPassManager manages BBPassManagers and FunctionPasses.
-/// It batches all function passes and basic block pass managers together =
and=20
-/// sequence them to process one function at a time before processing next=20
+/// It batches all function passes and basic block pass managers together =
and
+/// sequence them to process one function at a time before processing next
 /// function.
 class FPPassManager : public ModulePass, public PMDataManager {
 public:
   static char ID;
-  explicit FPPassManager()=20
+  explicit FPPassManager()
   : ModulePass(ID), PMDataManager() { }
- =20
+
   /// run - Execute all of the passes scheduled for execution.  Keep track=
 of
   /// whether any of the passes modifies the module, and if so, return tru=
e.
   bool runOnFunction(Function &F);
   bool runOnModule(Module &M);
- =20
+
   /// cleanup - After running all passes, clean up pass manager cache.
   void cleanup();
=20
   /// doInitialization - Run all of the initializers for the function pass=
es.
   ///
   bool doInitialization(Module &M);
- =20
+
   /// doFinalization - Run all of the finalizers for the function passes.
   ///
   bool doFinalization(Module &M);
@@ -449,8 +448,8 @@
     return FP;
   }
=20
-  virtual PassManagerType getPassManagerType() const {=20
-    return PMT_FunctionPassManager;=20
+  virtual PassManagerType getPassManagerType() const {
+    return PMT_FunctionPassManager;
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/PassSup=
port.h
--- a/head/contrib/llvm/include/llvm/PassSupport.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/PassSupport.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -25,6 +25,7 @@
 #include "llvm/PassRegistry.h"
 #include "llvm/InitializePasses.h"
 #include "llvm/Support/Atomic.h"
+#include "llvm/Support/Valgrind.h"
 #include <vector>
=20
 namespace llvm {
@@ -135,7 +136,10 @@
   if (old_val =3D=3D 0) { \
     function(Registry); \
     sys::MemoryFence(); \
+    TsanIgnoreWritesBegin(); \
+    TsanHappensBefore(&initialized); \
     initialized =3D 2; \
+    TsanIgnoreWritesEnd(); \
   } else { \
     sys::cas_flag tmp =3D initialized; \
     sys::MemoryFence(); \
@@ -143,7 +147,8 @@
       tmp =3D initialized; \
       sys::MemoryFence(); \
     } \
-  }
+  } \
+  TsanHappensAfter(&initialized);
=20
 #define INITIALIZE_PASS(passName, arg, name, cfg, analysis) \
   static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/BlockFrequency.h
--- a/head/contrib/llvm/include/llvm/Support/BlockFrequency.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/BlockFrequency.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -14,6 +14,8 @@
 #ifndef LLVM_SUPPORT_BLOCKFREQUENCY_H
 #define LLVM_SUPPORT_BLOCKFREQUENCY_H
=20
+#include "llvm/Support/DataTypes.h"
+
 namespace llvm {
=20
 class raw_ostream;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/BranchProbability.h
--- a/head/contrib/llvm/include/llvm/Support/BranchProbability.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/BranchProbability.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #define LLVM_SUPPORT_BRANCHPROBABILITY_H
=20
 #include "llvm/Support/DataTypes.h"
+#include <cassert>
=20
 namespace llvm {
=20
@@ -22,7 +23,6 @@
=20
 // This class represents Branch Probability as a non-negative fraction.
 class BranchProbability {
-
   // Numerator
   uint32_t N;
=20
@@ -30,19 +30,44 @@
   uint32_t D;
=20
 public:
-  BranchProbability(uint32_t n, uint32_t d);
+  BranchProbability(uint32_t n, uint32_t d) : N(n), D(d) {
+    assert(d > 0 && "Denomiator cannot be 0!");
+    assert(n <=3D d && "Probability cannot be bigger than 1!");
+  }
+
+  static BranchProbability getZero() { return BranchProbability(0, 1); }
+  static BranchProbability getOne() { return BranchProbability(1, 1); }
=20
   uint32_t getNumerator() const { return N; }
   uint32_t getDenominator() const { return D; }
=20
   // Return (1 - Probability).
-  BranchProbability getCompl() {
+  BranchProbability getCompl() const {
     return BranchProbability(D - N, D);
   }
=20
   void print(raw_ostream &OS) const;
=20
   void dump() const;
+
+  bool operator=3D=3D(BranchProbability RHS) const {
+    return (uint64_t)N * RHS.D =3D=3D (uint64_t)D * RHS.N;
+  }
+  bool operator!=3D(BranchProbability RHS) const {
+    return !(*this =3D=3D RHS);
+  }
+  bool operator<(BranchProbability RHS) const {
+    return (uint64_t)N * RHS.D < (uint64_t)D * RHS.N;
+  }
+  bool operator>(BranchProbability RHS) const {
+    return RHS < *this;
+  }
+  bool operator<=3D(BranchProbability RHS) const {
+    return (uint64_t)N * RHS.D <=3D (uint64_t)D * RHS.N;
+  }
+  bool operator>=3D(BranchProbability RHS) const {
+    return RHS <=3D *this;
+  }
 };
=20
 raw_ostream &operator<<(raw_ostream &OS, const BranchProbability &Prob);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/CFG.h
--- a/head/contrib/llvm/include/llvm/Support/CFG.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/Support/CFG.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -71,6 +71,12 @@
   unsigned getOperandNo() const {
     return It.getOperandNo();
   }
+
+  /// getUse - Return the operand Use in the predecessor's terminator
+  /// of the successor.
+  Use &getUse() const {
+    return It.getUse();
+  }
 };
=20
 typedef PredIterator<BasicBlock, Value::use_iterator> pred_iterator;
@@ -314,6 +320,7 @@
   typedef Function::iterator nodes_iterator;
   static nodes_iterator nodes_begin(Function *F) { return F->begin(); }
   static nodes_iterator nodes_end  (Function *F) { return F->end(); }
+  static unsigned       size       (Function *F) { return F->size(); }
 };
 template <> struct GraphTraits<const Function*> :
   public GraphTraits<const BasicBlock*> {
@@ -323,6 +330,7 @@
   typedef Function::const_iterator nodes_iterator;
   static nodes_iterator nodes_begin(const Function *F) { return F->begin()=
; }
   static nodes_iterator nodes_end  (const Function *F) { return F->end(); }
+  static unsigned       size       (const Function *F) { return F->size();=
 }
 };
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/COFF.h
--- a/head/contrib/llvm/include/llvm/Support/COFF.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/Support/COFF.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -24,6 +24,7 @@
 #define LLVM_SUPPORT_WIN_COFF_H
=20
 #include "llvm/Support/DataTypes.h"
+#include <cassert>
 #include <cstring>
=20
 namespace llvm {
@@ -49,8 +50,65 @@
   };
=20
   enum MachineTypes {
-    IMAGE_FILE_MACHINE_I386 =3D 0x14C,
-    IMAGE_FILE_MACHINE_AMD64 =3D 0x8664
+    IMAGE_FILE_MACHINE_UNKNOWN   =3D 0x0,
+    IMAGE_FILE_MACHINE_AM33      =3D 0x13,
+    IMAGE_FILE_MACHINE_AMD64     =3D 0x8664,
+    IMAGE_FILE_MACHINE_ARM       =3D 0x1C0,
+    IMAGE_FILE_MACHINE_ARMV7     =3D 0x1C4,
+    IMAGE_FILE_MACHINE_EBC       =3D 0xEBC,
+    IMAGE_FILE_MACHINE_I386      =3D 0x14C,
+    IMAGE_FILE_MACHINE_IA64      =3D 0x200,
+    IMAGE_FILE_MACHINE_M32R      =3D 0x9041,
+    IMAGE_FILE_MACHINE_MIPS16    =3D 0x266,
+    IMAGE_FILE_MACHINE_MIPSFPU   =3D 0x366,
+    IMAGE_FILE_MACHINE_MIPSFPU16 =3D 0x466,
+    IMAGE_FILE_MACHINE_POWERPC   =3D 0x1F0,
+    IMAGE_FILE_MACHINE_POWERPCFP =3D 0x1F1,
+    IMAGE_FILE_MACHINE_R4000     =3D 0x166,
+    IMAGE_FILE_MACHINE_SH3       =3D 0x1A2,
+    IMAGE_FILE_MACHINE_SH3DSP    =3D 0x1A3,
+    IMAGE_FILE_MACHINE_SH4       =3D 0x1A6,
+    IMAGE_FILE_MACHINE_SH5       =3D 0x1A8,
+    IMAGE_FILE_MACHINE_THUMB     =3D 0x1C2,
+    IMAGE_FILE_MACHINE_WCEMIPSV2 =3D 0x169
+  };
+
+  enum Characteristics {
+    /// The file does not contain base relocations and must be loaded at i=
ts
+    /// preferred base. If this cannot be done, the loader will error.
+    IMAGE_FILE_RELOCS_STRIPPED         =3D 0x0001,
+    /// The file is valid and can be run.
+    IMAGE_FILE_EXECUTABLE_IMAGE        =3D 0x0002,
+    /// COFF line numbers have been stripped. This is deprecated and shoul=
d be
+    /// 0.
+    IMAGE_FILE_LINE_NUMS_STRIPPED      =3D 0x0004,
+    /// COFF symbol table entries for local symbols have been removed. Thi=
s is
+    /// deprecated and should be 0.
+    IMAGE_FILE_LOCAL_SYMS_STRIPPED     =3D 0x0008,
+    /// Aggressively trim working set. This is deprecated and must be 0.
+    IMAGE_FILE_AGGRESSIVE_WS_TRIM      =3D 0x0010,
+    /// Image can handle > 2GiB addresses.
+    IMAGE_FILE_LARGE_ADDRESS_AWARE     =3D 0x0020,
+    /// Little endian: the LSB precedes the MSB in memory. This is depreca=
ted
+    /// and should be 0.
+    IMAGE_FILE_BYTES_REVERSED_LO       =3D 0x0080,
+    /// Machine is based on a 32bit word architecture.
+    IMAGE_FILE_32BIT_MACHINE           =3D 0x0100,
+    /// Debugging info has been removed.
+    IMAGE_FILE_DEBUG_STRIPPED          =3D 0x0200,
+    /// If the image is on removable media, fully load it and copy it to s=
wap.
+    IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP =3D 0x0400,
+    /// If the image is on network media, fully load it and copy it to swa=
p.
+    IMAGE_FILE_NET_RUN_FROM_SWAP       =3D 0x0800,
+    /// The image file is a system file, not a user program.
+    IMAGE_FILE_SYSTEM                  =3D 0x1000,
+    /// The image file is a DLL.
+    IMAGE_FILE_DLL                     =3D 0x2000,
+    /// This file should only be run on a uniprocessor machine.
+    IMAGE_FILE_UP_SYSTEM_ONLY          =3D 0x4000,
+    /// Big endian: the MSB precedes the LSB in memory. This is deprecated
+    /// and should be 0.
+    IMAGE_FILE_BYTES_REVERSED_HI       =3D 0x8000
   };
=20
   struct symbol {
@@ -231,6 +289,24 @@
     IMAGE_REL_AMD64_SSPAN32   =3D 0x0010
   };
=20
+  enum RelocationTypesARM {
+    IMAGE_REL_ARM_ABSOLUTE  =3D 0x0000,
+    IMAGE_REL_ARM_ADDR32    =3D 0x0001,
+    IMAGE_REL_ARM_ADDR32NB  =3D 0x0002,
+    IMAGE_REL_ARM_BRANCH24  =3D 0x0003,
+    IMAGE_REL_ARM_BRANCH11  =3D 0x0004,
+    IMAGE_REL_ARM_TOKEN     =3D 0x0005,
+    IMAGE_REL_ARM_BLX24     =3D 0x0008,
+    IMAGE_REL_ARM_BLX11     =3D 0x0009,
+    IMAGE_REL_ARM_SECTION   =3D 0x000E,
+    IMAGE_REL_ARM_SECREL    =3D 0x000F,
+    IMAGE_REL_ARM_MOV32A    =3D 0x0010,
+    IMAGE_REL_ARM_MOV32T    =3D 0x0011,
+    IMAGE_REL_ARM_BRANCH20T =3D 0x0012,
+    IMAGE_REL_ARM_BRANCH24T =3D 0x0014,
+    IMAGE_REL_ARM_BLX23T    =3D 0x0015
+  };
+
   enum COMDATType {
     IMAGE_COMDAT_SELECT_NODUPLICATES =3D 1,
     IMAGE_COMDAT_SELECT_ANY,
@@ -292,7 +368,219 @@
     AuxiliarySectionDefinition  SectionDefinition;
   };
=20
+  /// @brief The Import Directory Table.
+  ///
+  /// There is a single array of these and one entry per imported DLL.
+  struct ImportDirectoryTableEntry {
+    uint32_t ImportLookupTableRVA;
+    uint32_t TimeDateStamp;
+    uint32_t ForwarderChain;
+    uint32_t NameRVA;
+    uint32_t ImportAddressTableRVA;
+  };
+
+  /// @brief The PE32 Import Lookup Table.
+  ///
+  /// There is an array of these for each imported DLL. It represents eith=
er
+  /// the ordinal to import from the target DLL, or a name to lookup and i=
mport
+  /// from the target DLL.
+  ///
+  /// This also happens to be the same format used by the Import Address T=
able
+  /// when it is initially written out to the image.
+  struct ImportLookupTableEntry32 {
+    uint32_t data;
+
+    /// @brief Is this entry specified by ordinal, or name?
+    bool isOrdinal() const { return data & 0x80000000; }
+
+    /// @brief Get the ordinal value of this entry. isOrdinal must be true.
+    uint16_t getOrdinal() const {
+      assert(isOrdinal() && "ILT entry is not an ordinal!");
+      return data & 0xFFFF;
+    }
+
+    /// @brief Set the ordinal value and set isOrdinal to true.
+    void setOrdinal(uint16_t o) {
+      data =3D o;
+      data |=3D 0x80000000;
+    }
+
+    /// @brief Get the Hint/Name entry RVA. isOrdinal must be false.
+    uint32_t getHintNameRVA() const {
+      assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
+      return data;
+    }
+
+    /// @brief Set the Hint/Name entry RVA and set isOrdinal to false.
+    void setHintNameRVA(uint32_t rva) { data =3D rva; }
+  };
+
+  /// @brief The DOS compatible header at the front of all PEs.
+  struct DOSHeader {
+    uint16_t Magic;
+    uint16_t UsedBytesInTheLastPage;
+    uint16_t FileSizeInPages;
+    uint16_t NumberOfRelocationItems;
+    uint16_t HeaderSizeInParagraphs;
+    uint16_t MinimumExtraParagraphs;
+    uint16_t MaximumExtraParagraphs;
+    uint16_t InitialRelativeSS;
+    uint16_t InitialSP;
+    uint16_t Checksum;
+    uint16_t InitialIP;
+    uint16_t InitialRelativeCS;
+    uint16_t AddressOfRelocationTable;
+    uint16_t OverlayNumber;
+    uint16_t Reserved[4];
+    uint16_t OEMid;
+    uint16_t OEMinfo;
+    uint16_t Reserved2[10];
+    uint32_t AddressOfNewExeHeader;
+  };
+
+  struct PEHeader {
+    uint32_t Signature;
+    header COFFHeader;
+    uint16_t Magic;
+    uint8_t  MajorLinkerVersion;
+    uint8_t  MinorLinkerVersion;
+    uint32_t SizeOfCode;
+    uint32_t SizeOfInitializedData;
+    uint32_t SizeOfUninitializedData;
+    uint32_t AddressOfEntryPoint; // RVA
+    uint32_t BaseOfCode; // RVA
+    uint32_t BaseOfData; // RVA
+    uint64_t ImageBase;
+    uint32_t SectionAlignment;
+    uint32_t FileAlignment;
+    uint16_t MajorOperatingSystemVersion;
+    uint16_t MinorOperatingSystemVersion;
+    uint16_t MajorImageVersion;
+    uint16_t MinorImageVersion;
+    uint16_t MajorSubsystemVersion;
+    uint16_t MinorSubsystemVersion;
+    uint32_t Win32VersionValue;
+    uint32_t SizeOfImage;
+    uint32_t SizeOfHeaders;
+    uint32_t CheckSum;
+    uint16_t Subsystem;
+    uint16_t DLLCharacteristics;
+    uint64_t SizeOfStackReserve;
+    uint64_t SizeOfStackCommit;
+    uint64_t SizeOfHeapReserve;
+    uint64_t SizeOfHeapCommit;
+    uint32_t LoaderFlags;
+    uint32_t NumberOfRvaAndSize;
+  };
+
+  struct DataDirectory {
+    uint32_t RelativeVirtualAddress;
+    uint32_t Size;
+  };
+
+  enum WindowsSubsystem {
+    IMAGE_SUBSYSTEM_UNKNOWN =3D 0, ///< An unknown subsystem.
+    IMAGE_SUBSYSTEM_NATIVE =3D 1, ///< Device drivers and native Windows p=
rocesses
+    IMAGE_SUBSYSTEM_WINDOWS_GUI =3D 2, ///< The Windows GUI subsystem.
+    IMAGE_SUBSYSTEM_WINDOWS_CUI =3D 3, ///< The Windows character subsyste=
m.
+    IMAGE_SUBSYSTEM_POSIX_CUI =3D 7, ///< The POSIX character subsystem.
+    IMAGE_SUBSYSTEM_WINDOWS_CE_GUI =3D 9, ///< Windows CE.
+    IMAGE_SUBSYSTEM_EFI_APPLICATION =3D 10, ///< An EFI application.
+    IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER =3D 11, ///< An EFI driver wit=
h boot
+                                                  ///  services.
+    IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER =3D 12, ///< An EFI driver with run=
-time
+                                             ///  services.
+    IMAGE_SUBSYSTEM_EFI_ROM =3D 13, ///< An EFI ROM image.
+    IMAGE_SUBSYSTEM_XBOX =3D 14 ///< XBOX.
+  };
+
+  enum DLLCharacteristics {
+    /// DLL can be relocated at load time.
+    IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE =3D 0x0040,
+    /// Code integrity checks are enforced.
+    IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY =3D 0x0080,
+    IMAGE_DLL_CHARACTERISTICS_NX_COMPAT =3D 0x0100, ///< Image is NX compa=
tible.
+    /// Isolation aware, but do not isolate the image.
+    IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION =3D 0x0200,
+    /// Does not use structured exception handling (SEH). No SEH handler m=
ay be
+    /// called in this image.
+    IMAGE_DLL_CHARACTERISTICS_NO_SEH =3D 0x0400,
+    /// Do not bind the image.
+    IMAGE_DLL_CHARACTERISTICS_NO_BIND =3D 0x0800,
+    IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER =3D 0x2000, ///< A WDM driver.
+    /// Terminal Server aware.
+    IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE =3D 0x8000
+  };
+
+  enum DebugType {
+    IMAGE_DEBUG_TYPE_UNKNOWN       =3D 0,
+    IMAGE_DEBUG_TYPE_COFF          =3D 1,
+    IMAGE_DEBUG_TYPE_CODEVIEW      =3D 2,
+    IMAGE_DEBUG_TYPE_FPO           =3D 3,
+    IMAGE_DEBUG_TYPE_MISC          =3D 4,
+    IMAGE_DEBUG_TYPE_EXCEPTION     =3D 5,
+    IMAGE_DEBUG_TYPE_FIXUP         =3D 6,
+    IMAGE_DEBUG_TYPE_OMAP_TO_SRC   =3D 7,
+    IMAGE_DEBUG_TYPE_OMAP_FROM_SRC =3D 8,
+    IMAGE_DEBUG_TYPE_BORLAND       =3D 9,
+    IMAGE_DEBUG_TYPE_CLSID         =3D 11
+  };
+
+  enum BaseRelocationType {
+    IMAGE_REL_BASED_ABSOLUTE       =3D 0,
+    IMAGE_REL_BASED_HIGH           =3D 1,
+    IMAGE_REL_BASED_LOW            =3D 2,
+    IMAGE_REL_BASED_HIGHLOW        =3D 3,
+    IMAGE_REL_BASED_HIGHADJ        =3D 4,
+    IMAGE_REL_BASED_MIPS_JMPADDR   =3D 5,
+    IMAGE_REL_BASED_ARM_MOV32A     =3D 5,
+    IMAGE_REL_BASED_ARM_MOV32T     =3D 7,
+    IMAGE_REL_BASED_MIPS_JMPADDR16 =3D 9,
+    IMAGE_REL_BASED_DIR64          =3D 10
+  };
+
+  enum ImportType {
+    IMPORT_CODE  =3D 0,
+    IMPORT_DATA  =3D 1,
+    IMPORT_CONST =3D 2
+  };
+
+  enum ImportNameType {
+    /// Import is by ordinal. This indicates that the value in the Ordinal=
/Hint
+    /// field of the import header is the import's ordinal. If this consta=
nt is
+    /// not specified, then the Ordinal/Hint field should always be interp=
reted
+    /// as the import's hint.
+    IMPORT_ORDINAL         =3D 0,
+    /// The import name is identical to the public symbol name
+    IMPORT_NAME            =3D 1,
+    /// The import name is the public symbol name, but skipping the leadin=
g ?,
+    /// @, or optionally _.
+    IMPORT_NAME_NOPREFIX   =3D 2,
+    /// The import name is the public symbol name, but skipping the leadin=
g ?,
+    /// @, or optionally _, and truncating at the first @.
+    IMPORT_NAME_UNDECORATE =3D 3
+  };
+
+  struct ImportHeader {
+    uint16_t Sig1; ///< Must be IMAGE_FILE_MACHINE_UNKNOWN (0).
+    uint16_t Sig2; ///< Must be 0xFFFF.
+    uint16_t Version;
+    uint16_t Machine;
+    uint32_t TimeDateStamp;
+    uint32_t SizeOfData;
+    uint16_t OrdinalHint;
+    uint16_t TypeInfo;
+
+    ImportType getType() const {
+      return static_cast<ImportType>(TypeInfo & 0x3);
+    }
+
+    ImportNameType getNameType() const {
+      return static_cast<ImportNameType>((TypeInfo & 0x1C) >> 3);
+    }
+  };
+
+} // End namespace COFF.
 } // End namespace llvm.
-} // End namespace COFF.
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/CallSite.h
--- a/head/contrib/llvm/include/llvm/Support/CallSite.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/CallSite.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -237,6 +237,16 @@
 #undef CALLSITE_DELEGATE_GETTER
 #undef CALLSITE_DELEGATE_SETTER
=20
+  /// @brief Determine whether this argument is not captured.
+  bool doesNotCapture(unsigned ArgNo) const {
+    return paramHasAttr(ArgNo + 1, Attribute::NoCapture);
+  }
+
+  /// @brief Determine whether this argument is passed by value.
+  bool isByValArgument(unsigned ArgNo) const {
+    return paramHasAttr(ArgNo + 1, Attribute::ByVal);
+  }
+
   /// hasArgument - Returns true if this CallSite passes the given Value* =
as an
   /// argument to the called function.
   bool hasArgument(const Value *Arg) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Capacity.h
--- a/head/contrib/llvm/include/llvm/Support/Capacity.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Capacity.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -15,6 +15,8 @@
 #ifndef LLVM_SUPPORT_CAPACITY_H
 #define LLVM_SUPPORT_CAPACITY_H
=20
+#include <cstddef>
+
 namespace llvm {
=20
 template <typename T>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/CodeGen.h
--- a/head/contrib/llvm/include/llvm/Support/CodeGen.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/CodeGen.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -27,6 +27,26 @@
     enum Model { Default, JITDefault, Small, Kernel, Medium, Large };
   }
=20
+  // TLS models.
+  namespace TLSModel {
+    enum Model {
+      GeneralDynamic,
+      LocalDynamic,
+      InitialExec,
+      LocalExec
+    };
+  }
+
+  // Code generation optimization level.
+  namespace CodeGenOpt {
+    enum Level {
+      None,        // -O0
+      Less,        // -O1
+      Default,     // -O2, -Os
+      Aggressive   // -O3
+    };
+  }
+
 }  // end llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/CommandLine.h
--- a/head/contrib/llvm/include/llvm/Support/CommandLine.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/CommandLine.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -40,7 +40,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ParseCommandLineOptions - Command line option processing entry point.
 //
-void ParseCommandLineOptions(int argc, char **argv,
+void ParseCommandLineOptions(int argc, const char * const *argv,
                              const char *Overview =3D 0,
                              bool ReadResponseFiles =3D false);
=20
@@ -83,10 +83,10 @@
 //
=20
 enum NumOccurrencesFlag {      // Flags for the number of occurrences allo=
wed
-  Optional        =3D 0x01,      // Zero or One occurrence
-  ZeroOrMore      =3D 0x02,      // Zero or more occurrences allowed
-  Required        =3D 0x03,      // One occurrence required
-  OneOrMore       =3D 0x04,      // One or more occurrences required
+  Optional        =3D 0x00,      // Zero or One occurrence
+  ZeroOrMore      =3D 0x01,      // Zero or more occurrences allowed
+  Required        =3D 0x02,      // One occurrence required
+  OneOrMore       =3D 0x03,      // One or more occurrences required
=20
   // ConsumeAfter - Indicates that this option is fed anything that follow=
s the
   // last positional argument required by the application (it is an error =
if
@@ -95,23 +95,20 @@
   // found.  Once a filename is found, all of the succeeding arguments are
   // passed, unprocessed, to the ConsumeAfter option.
   //
-  ConsumeAfter    =3D 0x05,
-
-  OccurrencesMask  =3D 0x07
+  ConsumeAfter    =3D 0x04
 };
=20
 enum ValueExpected {           // Is a value required for the option?
-  ValueOptional   =3D 0x08,      // The value can appear... or not
-  ValueRequired   =3D 0x10,      // The value is required to appear!
-  ValueDisallowed =3D 0x18,      // A value may not be specified (for flag=
s)
-  ValueMask       =3D 0x18
+  // zero reserved for the unspecified value
+  ValueOptional   =3D 0x01,      // The value can appear... or not
+  ValueRequired   =3D 0x02,      // The value is required to appear!
+  ValueDisallowed =3D 0x03       // A value may not be specified (for flag=
s)
 };
=20
 enum OptionHidden {            // Control whether -help shows this option
-  NotHidden       =3D 0x20,      // Option included in -help & -help-hidden
-  Hidden          =3D 0x40,      // -help doesn't, but -help-hidden does
-  ReallyHidden    =3D 0x60,      // Neither -help nor -help-hidden show th=
is arg
-  HiddenMask      =3D 0x60
+  NotHidden       =3D 0x00,      // Option included in -help & -help-hidden
+  Hidden          =3D 0x01,      // -help doesn't, but -help-hidden does
+  ReallyHidden    =3D 0x02       // Neither -help nor -help-hidden show th=
is arg
 };
=20
 // Formatting flags - This controls special features that the option might=
 have
@@ -130,18 +127,16 @@
 //
=20
 enum FormattingFlags {
-  NormalFormatting =3D 0x000,     // Nothing special
-  Positional       =3D 0x080,     // Is a positional argument, no '-' requ=
ired
-  Prefix           =3D 0x100,     // Can this option directly prefix its v=
alue?
-  Grouping         =3D 0x180,     // Can this option group with other opti=
ons?
-  FormattingMask   =3D 0x180      // Union of the above flags.
+  NormalFormatting =3D 0x00,     // Nothing special
+  Positional       =3D 0x01,     // Is a positional argument, no '-' requi=
red
+  Prefix           =3D 0x02,     // Can this option directly prefix its va=
lue?
+  Grouping         =3D 0x03      // Can this option group with other optio=
ns?
 };
=20
 enum MiscFlags {               // Miscellaneous flags to adjust argument
-  CommaSeparated     =3D 0x200,  // Should this cl::list split between com=
mas?
-  PositionalEatsArgs =3D 0x400,  // Should this positional cl::list eat -a=
rgs?
-  Sink               =3D 0x800,  // Should this cl::list eat all unknown o=
ptions?
-  MiscMask           =3D 0xE00   // Union of the above flags.
+  CommaSeparated     =3D 0x01,  // Should this cl::list split between comm=
as?
+  PositionalEatsArgs =3D 0x02,  // Should this positional cl::list eat -ar=
gs?
+  Sink               =3D 0x04   // Should this cl::list eat all unknown op=
tions?
 };
=20
=20
@@ -168,7 +163,15 @@
   virtual void anchor();
=20
   int NumOccurrences;     // The number of times specified
-  int Flags;              // Flags for the argument
+  // Occurrences, HiddenFlag, and Formatting are all enum types but to avo=
id
+  // problems with signed enums in bitfields.
+  unsigned Occurrences : 3; // enum NumOccurrencesFlag
+  // not using the enum type for 'Value' because zero is an implementation
+  // detail representing the non-value
+  unsigned Value : 2;
+  unsigned HiddenFlag : 2; // enum OptionHidden
+  unsigned Formatting : 2; // enum FormattingFlags
+  unsigned Misc : 3;
   unsigned Position;      // Position of last occurrence of the option
   unsigned AdditionalVals;// Greater than 0 for multi-valued option.
   Option *NextRegistered; // Singly linked list of registered options.
@@ -178,21 +181,20 @@
   const char *ValueStr;   // String describing what the value of this opti=
on is
=20
   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
-    return static_cast<enum NumOccurrencesFlag>(Flags & OccurrencesMask);
+    return (enum NumOccurrencesFlag)Occurrences;
   }
   inline enum ValueExpected getValueExpectedFlag() const {
-    int VE =3D Flags & ValueMask;
-    return VE ? static_cast<enum ValueExpected>(VE)
+    return Value ? ((enum ValueExpected)Value)
               : getValueExpectedFlagDefault();
   }
   inline enum OptionHidden getOptionHiddenFlag() const {
-    return static_cast<enum OptionHidden>(Flags & HiddenMask);
+    return (enum OptionHidden)HiddenFlag;
   }
   inline enum FormattingFlags getFormattingFlag() const {
-    return static_cast<enum FormattingFlags>(Flags & FormattingMask);
+    return (enum FormattingFlags)Formatting;
   }
   inline unsigned getMiscFlags() const {
-    return Flags & MiscMask;
+    return Misc;
   }
   inline unsigned getPosition() const { return Position; }
   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
@@ -206,27 +208,21 @@
   void setArgStr(const char *S) { ArgStr =3D S; }
   void setDescription(const char *S) { HelpStr =3D S; }
   void setValueStr(const char *S) { ValueStr =3D S; }
-
-  void setFlag(unsigned Flag, unsigned FlagMask) {
-    Flags &=3D ~FlagMask;
-    Flags |=3D Flag;
+  void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) {
+    Occurrences =3D Val;
   }
-
-  void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) {
-    setFlag(Val, OccurrencesMask);
-  }
-  void setValueExpectedFlag(enum ValueExpected Val) { setFlag(Val, ValueMa=
sk); }
-  void setHiddenFlag(enum OptionHidden Val) { setFlag(Val, HiddenMask); }
-  void setFormattingFlag(enum FormattingFlags V) { setFlag(V, FormattingMa=
sk); }
-  void setMiscFlag(enum MiscFlags M) { setFlag(M, M); }
+  void setValueExpectedFlag(enum ValueExpected Val) { Value =3D Val; }
+  void setHiddenFlag(enum OptionHidden Val) { HiddenFlag =3D Val; }
+  void setFormattingFlag(enum FormattingFlags V) { Formatting =3D V; }
+  void setMiscFlag(enum MiscFlags M) { Misc |=3D M; }
   void setPosition(unsigned pos) { Position =3D pos; }
 protected:
-  explicit Option(unsigned DefaultFlags)
-    : NumOccurrences(0), Flags(DefaultFlags | NormalFormatting), Position(=
0),
+  explicit Option(enum NumOccurrencesFlag Occurrences,=20
+                  enum OptionHidden Hidden)
+    : NumOccurrences(0), Occurrences(Occurrences), HiddenFlag(Hidden),=20
+      Formatting(NormalFormatting), Position(0),
       AdditionalVals(0), NextRegistered(0),
       ArgStr(""), HelpStr(""), ValueStr("") {
-    assert(getNumOccurrencesFlag() !=3D 0 &&
-           getOptionHiddenFlag() !=3D 0 && "Not all default flags specifie=
d!");
   }
=20
   inline void setNumAdditionalVals(unsigned n) { AdditionalVals =3D n; }
@@ -326,6 +322,8 @@
 struct GenericOptionValue {
   virtual ~GenericOptionValue() {}
   virtual bool compare(const GenericOptionValue &V) const =3D 0;
+private:
+  virtual void anchor();
 };
=20
 template<class DataType> struct OptionValue;
@@ -339,7 +337,7 @@
=20
   bool hasValue() const { return false; }
=20
-  const DataType &getValue() const { assert(false && "no default value"); }
+  const DataType &getValue() const { llvm_unreachable("no default value");=
 }
=20
   // Some options may take their value from a different data type.
   template<class DT>
@@ -416,6 +414,8 @@
     setValue(V);
     return *this;
   }
+private:
+  virtual void anchor();
 };
=20
 template<>
@@ -431,6 +431,8 @@
     setValue(V);
     return *this;
   }
+private:
+  virtual void anchor();
 };
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1171,14 +1173,14 @@
=20
   // One option...
   template<class M0t>
-  explicit opt(const M0t &M0) : Option(Optional | NotHidden) {
+  explicit opt(const M0t &M0) : Option(Optional, NotHidden) {
     apply(M0, this);
     done();
   }
=20
   // Two options...
   template<class M0t, class M1t>
-  opt(const M0t &M0, const M1t &M1) : Option(Optional | NotHidden) {
+  opt(const M0t &M0, const M1t &M1) : Option(Optional, NotHidden) {
     apply(M0, this); apply(M1, this);
     done();
   }
@@ -1186,21 +1188,21 @@
   // Three options...
   template<class M0t, class M1t, class M2t>
   opt(const M0t &M0, const M1t &M1,
-      const M2t &M2) : Option(Optional | NotHidden) {
+      const M2t &M2) : Option(Optional, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this);
     done();
   }
   // Four options...
   template<class M0t, class M1t, class M2t, class M3t>
   opt(const M0t &M0, const M1t &M1, const M2t &M2,
-      const M3t &M3) : Option(Optional | NotHidden) {
+      const M3t &M3) : Option(Optional, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     done();
   }
   // Five options...
   template<class M0t, class M1t, class M2t, class M3t, class M4t>
   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
-      const M4t &M4) : Option(Optional | NotHidden) {
+      const M4t &M4) : Option(Optional, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this);
     done();
@@ -1209,7 +1211,7 @@
   template<class M0t, class M1t, class M2t, class M3t,
            class M4t, class M5t>
   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
-      const M4t &M4, const M5t &M5) : Option(Optional | NotHidden) {
+      const M4t &M4, const M5t &M5) : Option(Optional, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this);
     done();
@@ -1219,7 +1221,7 @@
            class M4t, class M5t, class M6t>
   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
       const M4t &M4, const M5t &M5,
-      const M6t &M6) : Option(Optional | NotHidden) {
+      const M6t &M6) : Option(Optional, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this); apply(M6, this);
     done();
@@ -1229,7 +1231,7 @@
            class M4t, class M5t, class M6t, class M7t>
   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
       const M4t &M4, const M5t &M5, const M6t &M6,
-      const M7t &M7) : Option(Optional | NotHidden) {
+      const M7t &M7) : Option(Optional, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
     done();
@@ -1338,34 +1340,34 @@
=20
   // One option...
   template<class M0t>
-  explicit list(const M0t &M0) : Option(ZeroOrMore | NotHidden) {
+  explicit list(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this);
     done();
   }
   // Two options...
   template<class M0t, class M1t>
-  list(const M0t &M0, const M1t &M1) : Option(ZeroOrMore | NotHidden) {
+  list(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this);
     done();
   }
   // Three options...
   template<class M0t, class M1t, class M2t>
   list(const M0t &M0, const M1t &M1, const M2t &M2)
-    : Option(ZeroOrMore | NotHidden) {
+    : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this);
     done();
   }
   // Four options...
   template<class M0t, class M1t, class M2t, class M3t>
   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
-    : Option(ZeroOrMore | NotHidden) {
+    : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     done();
   }
   // Five options...
   template<class M0t, class M1t, class M2t, class M3t, class M4t>
   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
-       const M4t &M4) : Option(ZeroOrMore | NotHidden) {
+       const M4t &M4) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this);
     done();
@@ -1374,7 +1376,7 @@
   template<class M0t, class M1t, class M2t, class M3t,
            class M4t, class M5t>
   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
-       const M4t &M4, const M5t &M5) : Option(ZeroOrMore | NotHidden) {
+       const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this);
     done();
@@ -1384,7 +1386,7 @@
            class M4t, class M5t, class M6t>
   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
        const M4t &M4, const M5t &M5, const M6t &M6)
-    : Option(ZeroOrMore | NotHidden) {
+    : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this); apply(M6, this);
     done();
@@ -1394,7 +1396,7 @@
            class M4t, class M5t, class M6t, class M7t>
   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
        const M4t &M4, const M5t &M5, const M6t &M6,
-       const M7t &M7) : Option(ZeroOrMore | NotHidden) {
+       const M7t &M7) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
     done();
@@ -1536,34 +1538,34 @@
=20
   // One option...
   template<class M0t>
-  explicit bits(const M0t &M0) : Option(ZeroOrMore | NotHidden) {
+  explicit bits(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this);
     done();
   }
   // Two options...
   template<class M0t, class M1t>
-  bits(const M0t &M0, const M1t &M1) : Option(ZeroOrMore | NotHidden) {
+  bits(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this);
     done();
   }
   // Three options...
   template<class M0t, class M1t, class M2t>
   bits(const M0t &M0, const M1t &M1, const M2t &M2)
-    : Option(ZeroOrMore | NotHidden) {
+    : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this);
     done();
   }
   // Four options...
   template<class M0t, class M1t, class M2t, class M3t>
   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
-    : Option(ZeroOrMore | NotHidden) {
+    : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     done();
   }
   // Five options...
   template<class M0t, class M1t, class M2t, class M3t, class M4t>
   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
-       const M4t &M4) : Option(ZeroOrMore | NotHidden) {
+       const M4t &M4) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this);
     done();
@@ -1572,7 +1574,7 @@
   template<class M0t, class M1t, class M2t, class M3t,
            class M4t, class M5t>
   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
-       const M4t &M4, const M5t &M5) : Option(ZeroOrMore | NotHidden) {
+       const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this);
     done();
@@ -1582,7 +1584,7 @@
            class M4t, class M5t, class M6t>
   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
        const M4t &M4, const M5t &M5, const M6t &M6)
-    : Option(ZeroOrMore | NotHidden) {
+    : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this); apply(M6, this);
     done();
@@ -1592,7 +1594,7 @@
            class M4t, class M5t, class M6t, class M7t>
   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
        const M4t &M4, const M5t &M5, const M6t &M6,
-       const M7t &M7) : Option(ZeroOrMore | NotHidden) {
+       const M7t &M7) : Option(ZeroOrMore, NotHidden) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
     done();
@@ -1632,27 +1634,27 @@
=20
   // One option...
   template<class M0t>
-  explicit alias(const M0t &M0) : Option(Optional | Hidden), AliasFor(0) {
+  explicit alias(const M0t &M0) : Option(Optional, Hidden), AliasFor(0) {
     apply(M0, this);
     done();
   }
   // Two options...
   template<class M0t, class M1t>
-  alias(const M0t &M0, const M1t &M1) : Option(Optional | Hidden), AliasFo=
r(0) {
+  alias(const M0t &M0, const M1t &M1) : Option(Optional, Hidden), AliasFor=
(0) {
     apply(M0, this); apply(M1, this);
     done();
   }
   // Three options...
   template<class M0t, class M1t, class M2t>
   alias(const M0t &M0, const M1t &M1, const M2t &M2)
-    : Option(Optional | Hidden), AliasFor(0) {
+    : Option(Optional, Hidden), AliasFor(0) {
     apply(M0, this); apply(M1, this); apply(M2, this);
     done();
   }
   // Four options...
   template<class M0t, class M1t, class M2t, class M3t>
   alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
-    : Option(Optional | Hidden), AliasFor(0) {
+    : Option(Optional, Hidden), AliasFor(0) {
     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
     done();
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Compiler.h
--- a/head/contrib/llvm/include/llvm/Support/Compiler.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Compiler.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -49,16 +49,22 @@
 #define LLVM_ATTRIBUTE_UNUSED
 #endif
=20
-#ifdef __GNUC__ // aka 'ATTRIBUTE_CONST' but following LLVM Conventions.
-#define LLVM_ATTRIBUTE_READNONE __attribute__((__const__))
+#if (__GNUC__ >=3D 4) && !defined(__MINGW32__) && !defined(__CYGWIN__)
+#define LLVM_ATTRIBUTE_WEAK __attribute__((__weak__))
 #else
-#define LLVM_ATTRIBUTE_READNONE
+#define LLVM_ATTRIBUTE_WEAK
 #endif
=20
-#ifdef __GNUC__  // aka 'ATTRIBUTE_PURE' but following LLVM Conventions.
-#define LLVM_ATTRIBUTE_READONLY __attribute__((__pure__))
+#ifdef __GNUC__ // aka 'CONST' but following LLVM Conventions.
+#define LLVM_READNONE __attribute__((__const__))
 #else
-#define LLVM_ATTRIBUTE_READONLY
+#define LLVM_READNONE
+#endif
+
+#ifdef __GNUC__  // aka 'PURE' but following LLVM Conventions.
+#define LLVM_READONLY __attribute__((__pure__))
+#else
+#define LLVM_READONLY
 #endif
=20
 #if (__GNUC__ >=3D 4)
@@ -67,6 +73,7 @@
 #define BUILTIN_EXPECT(EXPR, VALUE) (EXPR)
 #endif
=20
+
 // C++ doesn't support 'extern template' of template specializations.  GCC=
 does,
 // but requires __extension__ before it.  In the header, use this:
 //   EXTERN_TEMPLATE_INSTANTIATION(class foo<bar>);
@@ -111,6 +118,14 @@
 #define LLVM_ATTRIBUTE_NORETURN
 #endif
=20
+// LLVM_EXTENSION - Support compilers where we have a keyword to suppress
+// pedantic diagnostics.
+#ifdef __GNUC__
+#define LLVM_EXTENSION __extension__
+#else
+#define LLVM_EXTENSION
+#endif
+
 // LLVM_ATTRIBUTE_DEPRECATED(decl, "message")
 #if __has_feature(attribute_deprecated_with_message)
 # define LLVM_ATTRIBUTE_DEPRECATED(decl, message) \
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/DOTGraphTraits.h
--- a/head/contrib/llvm/include/llvm/Support/DOTGraphTraits.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/DOTGraphTraits.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -42,13 +42,13 @@
   /// top of the graph.
   ///
   template<typename GraphType>
-  static std::string getGraphName(const GraphType& Graph) { return ""; }
+  static std::string getGraphName(const GraphType &) { return ""; }
=20
   /// getGraphProperties - Return any custom properties that should be inc=
luded
   /// in the top level graph structure for dot.
   ///
   template<typename GraphType>
-  static std::string getGraphProperties(const GraphType& Graph) {
+  static std::string getGraphProperties(const GraphType &) {
     return "";
   }
=20
@@ -61,44 +61,44 @@
=20
   /// isNodeHidden - If the function returns true, the given node is not
   /// displayed in the graph.
-  static bool isNodeHidden(const void *Node) {
+  static bool isNodeHidden(const void *) {
     return false;
   }
=20
   /// getNodeLabel - Given a node and a pointer to the top level graph, re=
turn
   /// the label to print in the node.
   template<typename GraphType>
-  std::string getNodeLabel(const void *Node, const GraphType& Graph) {
+  std::string getNodeLabel(const void *, const GraphType &) {
     return "";
   }
=20
   /// hasNodeAddressLabel - If this method returns true, the address of th=
e node
   /// is added to the label of the node.
   template<typename GraphType>
-  static bool hasNodeAddressLabel(const void *Node, const GraphType& Graph=
) {
+  static bool hasNodeAddressLabel(const void *, const GraphType &) {
     return false;
   }
=20
   /// If you want to specify custom node attributes, this is the place to =
do so
   ///
   template<typename GraphType>
-  static std::string getNodeAttributes(const void *Node,
-                                       const GraphType& Graph) {
+  static std::string getNodeAttributes(const void *,
+                                       const GraphType &) {
     return "";
   }
=20
   /// If you want to override the dot attributes printed for a particular =
edge,
   /// override this method.
   template<typename EdgeIter, typename GraphType>
-  static std::string getEdgeAttributes(const void *Node, EdgeIter EI,
-                                       const GraphType& Graph) {
+  static std::string getEdgeAttributes(const void *, EdgeIter,
+                                       const GraphType &) {
     return "";
   }
=20
   /// getEdgeSourceLabel - If you want to label the edge source itself,
   /// implement this method.
   template<typename EdgeIter>
-  static std::string getEdgeSourceLabel(const void *Node, EdgeIter I) {
+  static std::string getEdgeSourceLabel(const void *, EdgeIter) {
     return "";
   }
=20
@@ -106,7 +106,7 @@
   /// should actually target another edge source, not a node.  If this met=
hod is
   /// implemented, getEdgeTarget should be implemented.
   template<typename EdgeIter>
-  static bool edgeTargetsEdgeSource(const void *Node, EdgeIter I) {
+  static bool edgeTargetsEdgeSource(const void *, EdgeIter) {
     return false;
   }
=20
@@ -114,7 +114,7 @@
   /// called to determine which outgoing edge of Node is the target of this
   /// edge.
   template<typename EdgeIter>
-  static EdgeIter getEdgeTarget(const void *Node, EdgeIter I) {
+  static EdgeIter getEdgeTarget(const void *, EdgeIter I) {
     return I;
   }
=20
@@ -126,13 +126,13 @@
=20
   /// numEdgeDestLabels - If hasEdgeDestLabels, this function returns the
   /// number of incoming edge labels the given node has.
-  static unsigned numEdgeDestLabels(const void *Node) {
+  static unsigned numEdgeDestLabels(const void *) {
     return 0;
   }
=20
   /// getEdgeDestLabel - If hasEdgeDestLabels, this function returns the
   /// incoming edge label with the given index in the given node.
-  static std::string getEdgeDestLabel(const void *Node, unsigned i) {
+  static std::string getEdgeDestLabel(const void *, unsigned) {
     return "";
   }
=20
@@ -143,7 +143,7 @@
   /// it to add things to the output graph.
   ///
   template<typename GraphType, typename GraphWriter>
-  static void addCustomGraphFeatures(const GraphType& Graph, GraphWriter &=
GW) {}
+  static void addCustomGraphFeatures(const GraphType &, GraphWriter &) {}
 };
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/DataTypes.h.in
--- a/head/contrib/llvm/include/llvm/Support/DataTypes.h.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/DataTypes.h.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -167,9 +167,24 @@
 # define UINT64_C(C) C##ui64
 #endif
=20
+#ifndef PRId64
+# define PRId64 "I64d"
+#endif
+#ifndef PRIi64
+# define PRIi64 "I64i"
+#endif
+#ifndef PRIo64
+# define PRIo64 "I64o"
+#endif
+#ifndef PRIu64
+# define PRIu64 "I64u"
+#endif
 #ifndef PRIx64
 # define PRIx64 "I64x"
 #endif
+#ifndef PRIX64
+# define PRIX64 "I64X"
+#endif
=20
 #endif /* _MSC_VER */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Debug.h
--- a/head/contrib/llvm/include/llvm/Support/Debug.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Debug.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -35,14 +35,14 @@
 #ifndef DEBUG_TYPE
 #define DEBUG_TYPE ""
 #endif
- =20
+
 #ifndef NDEBUG
 /// DebugFlag - This boolean is set to true if the '-debug' command line o=
ption
 /// is specified.  This should probably not be referenced directly, instea=
d, use
 /// the DEBUG macro below.
 ///
 extern bool DebugFlag;
- =20
+
 /// isCurrentDebugType - Return true if the specified string is the debug =
type
 /// specified on the command line, or if none was specified on the command=
 line
 /// with the -debug-only=3DX option.
@@ -54,7 +54,7 @@
 /// debug output to be produced.
 ///
 void SetCurrentDebugType(const char *Type);
- =20
+
 /// DEBUG_WITH_TYPE macro - This macro should be used by passes to emit de=
bug
 /// information.  In the '-debug' option is specified on the commandline, =
and if
 /// this is a debug build, then the code specified as the option to the ma=
cro
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Dwarf.h
--- a/head/contrib/llvm/include/llvm/Support/Dwarf.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Dwarf.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -22,7 +22,8 @@
 // Debug info constants.
=20
 enum {
-  LLVMDebugVersion =3D (11 << 16),        // Current version of debug info=
rmation.
+  LLVMDebugVersion =3D (12 << 16),        // Current version of debug info=
rmation.
+  LLVMDebugVersion11 =3D (11 << 16),      // Constant for version 11.
   LLVMDebugVersion10 =3D (10 << 16),      // Constant for version 10.
   LLVMDebugVersion9 =3D (9 << 16),        // Constant for version 9.
   LLVMDebugVersion8 =3D (8 << 16),        // Constant for version 8.
@@ -130,6 +131,7 @@
   DW_TAG_GNU_template_parameter_pack =3D 0x4107,
   DW_TAG_GNU_formal_parameter_pack =3D 0x4108,
   DW_TAG_lo_user =3D 0x4080,
+  DW_TAG_APPLE_property =3D 0x4200,
   DW_TAG_hi_user =3D 0xffff,
=20
   // Children flag
@@ -269,6 +271,7 @@
   DW_AT_APPLE_property_setter =3D 0x3fea,
   DW_AT_APPLE_property_attribute =3D 0x3feb,
   DW_AT_APPLE_objc_complete_type =3D 0x3fec,
+  DW_AT_APPLE_property =3D 0x3fed,
=20
   // Attribute form encodings
   DW_FORM_addr =3D 0x01,
@@ -526,6 +529,7 @@
   DW_LANG_D =3D 0x0013,
   DW_LANG_Python =3D 0x0014,
   DW_LANG_lo_user =3D 0x8000,
+  DW_LANG_Mips_Assembler =3D 0x8001,
   DW_LANG_hi_user =3D 0xffff,
=20
   // Identifier case codes
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/DynamicLibrary.h
--- a/head/contrib/llvm/include/llvm/Support/DynamicLibrary.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/DynamicLibrary.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -17,6 +17,9 @@
 #include <string>
=20
 namespace llvm {
+
+class StringRef;
+
 namespace sys {
=20
   /// This class provides a portable interface to dynamic libraries which =
also
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/ELF.h
--- a/head/contrib/llvm/include/llvm/Support/ELF.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/include/llvm/Support/ELF.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -599,7 +599,25 @@
   R_ARM_THM_TLS_DESCSEQ32     =3D 0x82
 };
=20
+// Mips Specific e_flags
+enum {
+  EF_MIPS_NOREORDER =3D 0x00000001, // Don't reorder instructions
+  EF_MIPS_PIC       =3D 0x00000002, // Position independent code
+  EF_MIPS_CPIC      =3D 0x00000004, // Call object with Position independe=
nt code
+  EF_MIPS_ARCH_1    =3D 0x00000000, // MIPS1 instruction set
+  EF_MIPS_ARCH_2    =3D 0x10000000, // MIPS2 instruction set
+  EF_MIPS_ARCH_3    =3D 0x20000000, // MIPS3 instruction set
+  EF_MIPS_ARCH_4    =3D 0x30000000, // MIPS4 instruction set
+  EF_MIPS_ARCH_5    =3D 0x40000000, // MIPS5 instruction set
+  EF_MIPS_ARCH_32   =3D 0x50000000, // MIPS32 instruction set per linux no=
t elf.h
+  EF_MIPS_ARCH_64   =3D 0x60000000, // MIPS64 instruction set per linux no=
t elf.h
+  EF_MIPS_ARCH_32R2 =3D 0x70000000, // mips32r2
+  EF_MIPS_ARCH_64R2 =3D 0x80000000, // mips64r2
+  EF_MIPS_ARCH      =3D 0xf0000000  // Mask for applying EF_MIPS_ARCH_ var=
iant
+};
+
 // ELF Relocation types for Mips
+// .
 enum {
   R_MIPS_NONE              =3D  0,
   R_MIPS_16                =3D  1,
@@ -611,6 +629,7 @@
   R_MIPS_GPREL16           =3D  7,
   R_MIPS_LITERAL           =3D  8,
   R_MIPS_GOT16             =3D  9,
+  R_MIPS_GOT               =3D  9,
   R_MIPS_PC16              =3D 10,
   R_MIPS_CALL16            =3D 11,
   R_MIPS_GPREL32           =3D 12,
@@ -717,6 +736,9 @@
   SHT_GROUP         =3D 17, // Section group.
   SHT_SYMTAB_SHNDX  =3D 18, // Indices for SHN_XINDEX entries.
   SHT_LOOS          =3D 0x60000000, // Lowest operating system-specific ty=
pe.
+  SHT_GNU_verdef    =3D 0x6ffffffd, // GNU version definitions.
+  SHT_GNU_verneed   =3D 0x6ffffffe, // GNU version references.
+  SHT_GNU_versym    =3D 0x6fffffff, // GNU symbol versions table.
   SHT_HIOS          =3D 0x6fffffff, // Highest operating system-specific t=
ype.
   SHT_LOPROC        =3D 0x70000000, // Lowest processor architecture-speci=
fic type.
   // Fixme: All this is duplicated in MCSectionELF. Why??
@@ -871,6 +893,7 @@
   STT_TLS     =3D 6,   // Thread local data object
   STT_LOOS    =3D 7,   // Lowest operating system-specific symbol type
   STT_HIOS    =3D 8,   // Highest operating system-specific symbol type
+  STT_GNU_IFUNC =3D 10, // GNU indirect function
   STT_LOPROC  =3D 13,  // Lowest processor-specific symbol type
   STT_HIPROC  =3D 15   // Highest processor-specific symbol type
 };
@@ -1084,6 +1107,33 @@
   DF_STATIC_TLS =3D 0x10  // Reject attempts to load dynamically.
 };
=20
+// ElfXX_VerDef structure version (GNU versioning)
+enum {
+  VER_DEF_NONE    =3D 0,
+  VER_DEF_CURRENT =3D 1
+};
+
+// VerDef Flags (ElfXX_VerDef::vd_flags)
+enum {
+  VER_FLG_BASE =3D 0x1,
+  VER_FLG_WEAK =3D 0x2,
+  VER_FLG_INFO =3D 0x4
+};
+
+// Special constants for the version table. (SHT_GNU_versym/.gnu.version)
+enum {
+  VER_NDX_LOCAL  =3D 0,      // Unversioned local symbol
+  VER_NDX_GLOBAL =3D 1,      // Unversioned global symbol
+  VERSYM_VERSION =3D 0x7fff, // Version Index mask
+  VERSYM_HIDDEN  =3D 0x8000  // Hidden bit (non-default version)
+};
+
+// ElfXX_VerNeed structure version (GNU versioning)
+enum {
+  VER_NEED_NONE =3D 0,
+  VER_NEED_CURRENT =3D 1
+};
+
 } // end namespace ELF
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Endian.h
--- a/head/contrib/llvm/include/llvm/Support/Endian.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Endian.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -98,6 +98,9 @@
   operator value_type() const {
     return endian::read_le<value_type, unaligned>(Value);
   }
+  void operator=3D(value_type newValue) {
+    endian::write_le<value_type, unaligned>((void *)&Value, newValue);
+  }
 private:
   uint8_t Value[sizeof(value_type)];
 };
@@ -108,6 +111,9 @@
   operator value_type() const {
     return endian::read_be<value_type, unaligned>(Value);
   }
+  void operator=3D(value_type newValue) {
+    endian::write_be<value_type, unaligned>((void *)&Value, newValue);
+  }
 private:
   uint8_t Value[sizeof(value_type)];
 };
@@ -118,6 +124,9 @@
   operator value_type() const {
     return endian::read_le<value_type, aligned>(&Value);
   }
+  void operator=3D(value_type newValue) {
+    endian::write_le<value_type, aligned>((void *)&Value, newValue);
+  }
 private:
   value_type Value;
 };
@@ -128,6 +137,9 @@
   operator value_type() const {
     return endian::read_be<value_type, aligned>(&Value);
   }
+  void operator=3D(value_type newValue) {
+    endian::write_be<value_type, aligned>((void *)&Value, newValue);
+  }
 private:
   value_type Value;
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/FileSystem.h
--- a/head/contrib/llvm/include/llvm/Support/FileSystem.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/FileSystem.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -27,14 +27,21 @@
 #ifndef LLVM_SUPPORT_FILE_SYSTEM_H
 #define LLVM_SUPPORT_FILE_SYSTEM_H
=20
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/DataTypes.h"
-#include "llvm/Support/PathV1.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/system_error.h"
 #include <ctime>
 #include <iterator>
+#include <stack>
 #include <string>
+#include <vector>
+
+#if HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
=20
 namespace llvm {
 namespace sys {
@@ -91,7 +98,20 @@
 ///               a platform specific member to store the result.
 class file_status
 {
-  // implementation defined status field.
+  #if defined(LLVM_ON_UNIX)
+  dev_t st_dev;
+  ino_t st_ino;
+  #elif defined (LLVM_ON_WIN32)
+  uint32_t LastWriteTimeHigh;
+  uint32_t LastWriteTimeLow;
+  uint32_t VolumeSerialNumber;
+  uint32_t FileSizeHigh;
+  uint32_t FileSizeLow;
+  uint32_t FileIndexHigh;
+  uint32_t FileIndexLow;
+  #endif
+  friend bool equivalent(file_status A, file_status B);
+  friend error_code status(const Twine &path, file_status &result);
   file_type Type;
 public:
   explicit file_status(file_type v=3Dfile_type::status_error)
@@ -101,6 +121,44 @@
   void type(file_type v) { Type =3D v; }
 };
=20
+/// file_magic - An "enum class" enumeration of file types based on magic =
(the first
+///         N bytes of the file).
+struct file_magic {
+  enum _ {
+    unknown =3D 0,              ///< Unrecognized file
+    bitcode,                  ///< Bitcode file
+    archive,                  ///< ar style archive file
+    elf_relocatable,          ///< ELF Relocatable object file
+    elf_executable,           ///< ELF Executable image
+    elf_shared_object,        ///< ELF dynamically linked shared lib
+    elf_core,                 ///< ELF core image
+    macho_object,             ///< Mach-O Object file
+    macho_executable,         ///< Mach-O Executable
+    macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM
+    macho_core,               ///< Mach-O Core File
+    macho_preload_executabl,  ///< Mach-O Preloaded Executable
+    macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib
+    macho_dynamic_linker,     ///< The Mach-O dynamic linker
+    macho_bundle,             ///< Mach-O Bundle file
+    macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub
+    macho_dsym_companion,     ///< Mach-O dSYM companion file
+    coff_object,              ///< COFF object file
+    pecoff_executable         ///< PECOFF executable file
+  };
+
+  bool is_object() const {
+    return v_ =3D=3D unknown ? false : true;
+  }
+
+  file_magic() : v_(unknown) {}
+  file_magic(_ v) : v_(v) {}
+  explicit file_magic(int v) : v_(_(v)) {}
+  operator int() const {return v_;}
+
+private:
+  int v_;
+};
+
 /// @}
 /// @name Physical Operators
 /// @{
@@ -241,6 +299,8 @@
=20
 /// @brief Do paths represent the same thing?
 ///
+/// assert(status_known(A) || status_known(B));
+///
 /// @param A Input path A.
 /// @param B Input path B.
 /// @param result Set to true if stat(A) and stat(B) have the same device =
and
@@ -397,13 +457,16 @@
 error_code get_magic(const Twine &path, uint32_t len,
                      SmallVectorImpl<char> &result);
=20
+/// @brief Identify the type of a binary file based on how magical it is.
+file_magic identify_magic(StringRef magic);
+
 /// @brief Get and identify \a path's type based on its content.
 ///
 /// @param path Input path.
 /// @param result Set to the type of file, or LLVMFileType::Unknown_FileTy=
pe.
 /// @results errc::success if result has been successfully set, otherwise a
 ///          platform specific error_code.
-error_code identify_magic(const Twine &path, LLVMFileType &result);
+error_code identify_magic(const Twine &path, file_magic &result);
=20
 /// @brief Get library paths the system linker uses.
 ///
@@ -479,76 +542,171 @@
   bool operator>=3D(const directory_entry& rhs) const;
 };
=20
+namespace detail {
+  struct DirIterState;
+
+  error_code directory_iterator_construct(DirIterState&, StringRef);
+  error_code directory_iterator_increment(DirIterState&);
+  error_code directory_iterator_destruct(DirIterState&);
+
+  /// DirIterState - Keeps state for the directory_iterator. It is referen=
ce
+  /// counted in order to preserve InputIterator semantics on copy.
+  struct DirIterState : public RefCountedBase<DirIterState> {
+    DirIterState()
+      : IterationHandle(0) {}
+
+    ~DirIterState() {
+      directory_iterator_destruct(*this);
+    }
+
+    intptr_t IterationHandle;
+    directory_entry CurrentEntry;
+  };
+}
+
 /// directory_iterator - Iterates through the entries in path. There is no
 /// operator++ because we need an error_code. If it's really needed we can=
 make
 /// it call report_fatal_error on error.
 class directory_iterator {
-  intptr_t IterationHandle;
-  directory_entry CurrentEntry;
-
-  // Platform implementations implement these functions to handle iteratio=
n.
-  friend error_code directory_iterator_construct(directory_iterator &it,
-                                                 StringRef path);
-  friend error_code directory_iterator_increment(directory_iterator &it);
-  friend error_code directory_iterator_destruct(directory_iterator &it);
+  IntrusiveRefCntPtr<detail::DirIterState> State;
=20
 public:
-  explicit directory_iterator(const Twine &path, error_code &ec)
-  : IterationHandle(0) {
+  explicit directory_iterator(const Twine &path, error_code &ec) {
+    State =3D new detail::DirIterState;
     SmallString<128> path_storage;
-    ec =3D directory_iterator_construct(*this, path.toStringRef(path_stora=
ge));
+    ec =3D detail::directory_iterator_construct(*State,
+            path.toStringRef(path_storage));
+  }
+
+  explicit directory_iterator(const directory_entry &de, error_code &ec) {
+    State =3D new detail::DirIterState;
+    ec =3D detail::directory_iterator_construct(*State, de.path());
   }
=20
   /// Construct end iterator.
-  directory_iterator() : IterationHandle(0) {}
-
-  ~directory_iterator() {
-    directory_iterator_destruct(*this);
-  }
+  directory_iterator() : State(new detail::DirIterState) {}
=20
   // No operator++ because we need error_code.
   directory_iterator &increment(error_code &ec) {
-    ec =3D directory_iterator_increment(*this);
+    ec =3D directory_iterator_increment(*State);
     return *this;
   }
=20
-  const directory_entry &operator*() const { return CurrentEntry; }
-  const directory_entry *operator->() const { return &CurrentEntry; }
+  const directory_entry &operator*() const { return State->CurrentEntry; }
+  const directory_entry *operator->() const { return &State->CurrentEntry;=
 }
+
+  bool operator=3D=3D(const directory_iterator &RHS) const {
+    return State->CurrentEntry =3D=3D RHS.State->CurrentEntry;
+  }
=20
   bool operator!=3D(const directory_iterator &RHS) const {
-    return CurrentEntry !=3D RHS.CurrentEntry;
+    return !(*this =3D=3D RHS);
   }
   // Other members as required by
   // C++ Std, 24.1.1 Input iterators [input.iterators]
 };
=20
+namespace detail {
+  /// RecDirIterState - Keeps state for the recursive_directory_iterator. =
It is
+  /// reference counted in order to preserve InputIterator semantics on co=
py.
+  struct RecDirIterState : public RefCountedBase<RecDirIterState> {
+    RecDirIterState()
+      : Level(0)
+      , HasNoPushRequest(false) {}
+
+    std::stack<directory_iterator, std::vector<directory_iterator> > Stack;
+    uint16_t Level;
+    bool HasNoPushRequest;
+  };
+}
+
 /// recursive_directory_iterator - Same as directory_iterator except for it
 /// recurses down into child directories.
 class recursive_directory_iterator {
-  uint16_t  Level;
-  bool HasNoPushRequest;
-  // implementation directory iterator status
+  IntrusiveRefCntPtr<detail::RecDirIterState> State;
=20
 public:
-  explicit recursive_directory_iterator(const Twine &path, error_code &ec);
+  recursive_directory_iterator() {}
+  explicit recursive_directory_iterator(const Twine &path, error_code &ec)
+    : State(new detail::RecDirIterState) {
+    State->Stack.push(directory_iterator(path, ec));
+    if (State->Stack.top() =3D=3D directory_iterator())
+      State.reset();
+  }
   // No operator++ because we need error_code.
-  directory_iterator &increment(error_code &ec);
+  recursive_directory_iterator &increment(error_code &ec) {
+    static const directory_iterator end_itr;
=20
-  const directory_entry &operator*() const;
-  const directory_entry *operator->() const;
+    if (State->HasNoPushRequest)
+      State->HasNoPushRequest =3D false;
+    else {
+      file_status st;
+      if ((ec =3D State->Stack.top()->status(st))) return *this;
+      if (is_directory(st)) {
+        State->Stack.push(directory_iterator(*State->Stack.top(), ec));
+        if (ec) return *this;
+        if (State->Stack.top() !=3D end_itr) {
+          ++State->Level;
+          return *this;
+        }
+        State->Stack.pop();
+      }
+    }
+
+    while (!State->Stack.empty()
+           && State->Stack.top().increment(ec) =3D=3D end_itr) {
+      State->Stack.pop();
+      --State->Level;
+    }
+
+    // Check if we are done. If so, create an end iterator.
+    if (State->Stack.empty())
+      State.reset();
+
+    return *this;
+  }
+
+  const directory_entry &operator*() const { return *State->Stack.top(); }
+  const directory_entry *operator->() const { return &*State->Stack.top();=
 }
=20
   // observers
-  /// Gets the current level. path is at level 0.
-  int level() const;
+  /// Gets the current level. Starting path is at level 0.
+  int level() const { return State->Level; }
+
   /// Returns true if no_push has been called for this directory_entry.
-  bool no_push_request() const;
+  bool no_push_request() const { return State->HasNoPushRequest; }
=20
   // modifiers
   /// Goes up one level if Level > 0.
-  void pop();
+  void pop() {
+    assert(State && "Cannot pop and end itertor!");
+    assert(State->Level > 0 && "Cannot pop an iterator with level < 1");
+
+    static const directory_iterator end_itr;
+    error_code ec;
+    do {
+      if (ec)
+        report_fatal_error("Error incrementing directory iterator.");
+      State->Stack.pop();
+      --State->Level;
+    } while (!State->Stack.empty()
+             && State->Stack.top().increment(ec) =3D=3D end_itr);
+
+    // Check if we are done. If so, create an end iterator.
+    if (State->Stack.empty())
+      State.reset();
+  }
+
   /// Does not go down into the current directory_entry.
-  void no_push();
+  void no_push() { State->HasNoPushRequest =3D true; }
=20
+  bool operator=3D=3D(const recursive_directory_iterator &RHS) const {
+    return State =3D=3D RHS.State;
+  }
+
+  bool operator!=3D(const recursive_directory_iterator &RHS) const {
+    return !(*this =3D=3D RHS);
+  }
   // Other members as required by
   // C++ Std, 24.1.1 Input iterators [input.iterators]
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/GraphWriter.h
--- a/head/contrib/llvm/include/llvm/Support/GraphWriter.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/GraphWriter.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -296,26 +296,26 @@
 template<typename GraphType>
 raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G,
                         bool ShortNames =3D false,
-                        const std::string &Title =3D "") {
+                        const Twine &Title =3D "") {
   // Start the graph emission process...
   GraphWriter<GraphType> W(O, G, ShortNames);
=20
   // Emit the graph.
-  W.writeGraph(Title);
+  W.writeGraph(Title.str());
=20
   return O;
 }
=20
 template<typename GraphType>
-sys::Path WriteGraph(const GraphType &G, const std::string &Name,
-                     bool ShortNames =3D false, const std::string &Title =
=3D "") {
+sys::Path WriteGraph(const GraphType &G, const Twine &Name,
+                     bool ShortNames =3D false, const Twine &Title =3D "")=
 {
   std::string ErrMsg;
   sys::Path Filename =3D sys::Path::GetTemporaryDirectory(&ErrMsg);
   if (Filename.isEmpty()) {
     errs() << "Error: " << ErrMsg << "\n";
     return Filename;
   }
-  Filename.appendComponent(Name + ".dot");
+  Filename.appendComponent((Name + ".dot").str());
   if (Filename.makeUnique(true,&ErrMsg)) {
     errs() << "Error: " << ErrMsg << "\n";
     return sys::Path();
@@ -341,8 +341,8 @@
 /// then cleanup.  For use from the debugger.
 ///
 template<typename GraphType>
-void ViewGraph(const GraphType &G, const std::string &Name,
-               bool ShortNames =3D false, const std::string &Title =3D "",
+void ViewGraph(const GraphType &G, const Twine &Name,
+               bool ShortNames =3D false, const Twine &Title =3D "",
                GraphProgram::Name Program =3D GraphProgram::DOT) {
   sys::Path Filename =3D llvm::WriteGraph(G, Name, ShortNames, Title);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Host.h
--- a/head/contrib/llvm/include/llvm/Support/Host.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Host.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -33,14 +33,14 @@
     return !isLittleEndianHost();
   }
=20
-  /// getHostTriple() - Return the target triple of the running
-  /// system.
+  /// getDefaultTargetTriple() - Return the default target triple the comp=
iler
+  /// has been configured to produce code for.
   ///
   /// The target triple is a string in the format of:
   ///   CPU_TYPE-VENDOR-OPERATING_SYSTEM
   /// or
   ///   CPU_TYPE-VENDOR-KERNEL-OPERATING_SYSTEM
-  std::string getHostTriple();
+  std::string getDefaultTargetTriple();
=20
   /// getHostCPUName - Get the LLVM name for the host CPU. The particular =
format
   /// of the name is target dependent, and suitable for passing as -mcpu t=
o the
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/IRReader.h
--- a/head/contrib/llvm/include/llvm/Support/IRReader.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/IRReader.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -40,7 +40,8 @@
       std::string ErrMsg;
       Module *M =3D getLazyBitcodeModule(Buffer, Context, &ErrMsg);
       if (M =3D=3D 0) {
-        Err =3D SMDiagnostic(Buffer->getBufferIdentifier(), ErrMsg);
+        Err =3D SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_=
Error,
+                           ErrMsg);
         // ParseBitcodeFile does not take ownership of the Buffer in the
         // case of an error.
         delete Buffer;
@@ -60,7 +61,7 @@
                                      LLVMContext &Context) {
     OwningPtr<MemoryBuffer> File;
     if (error_code ec =3D MemoryBuffer::getFileOrSTDIN(Filename.c_str(), F=
ile)) {
-      Err =3D SMDiagnostic(Filename,
+      Err =3D SMDiagnostic(Filename, SourceMgr::DK_Error,
                          "Could not open input file: " + ec.message());
       return 0;
     }
@@ -80,7 +81,8 @@
       std::string ErrMsg;
       Module *M =3D ParseBitcodeFile(Buffer, Context, &ErrMsg);
       if (M =3D=3D 0)
-        Err =3D SMDiagnostic(Buffer->getBufferIdentifier(), ErrMsg);
+        Err =3D SMDiagnostic(Buffer->getBufferIdentifier(), SourceMgr::DK_=
Error,
+                           ErrMsg);
       // ParseBitcodeFile does not take ownership of the Buffer.
       delete Buffer;
       return M;
@@ -97,7 +99,7 @@
                              LLVMContext &Context) {
     OwningPtr<MemoryBuffer> File;
     if (error_code ec =3D MemoryBuffer::getFileOrSTDIN(Filename.c_str(), F=
ile)) {
-      Err =3D SMDiagnostic(Filename,
+      Err =3D SMDiagnostic(Filename, SourceMgr::DK_Error,
                          "Could not open input file: " + ec.message());
       return 0;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/InstVisitor.h
--- a/head/contrib/llvm/include/llvm/Support/InstVisitor.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/InstVisitor.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -14,6 +14,7 @@
 #include "llvm/Function.h"
 #include "llvm/Instructions.h"
 #include "llvm/Module.h"
+#include "llvm/Support/CallSite.h"
 #include "llvm/Support/ErrorHandling.h"
=20
 namespace llvm {
@@ -157,54 +158,74 @@
   // Specific Instruction type classes... note that all of the casts are
   // necessary because we use the instruction classes as opaque types...
   //
-  RetTy visitReturnInst(ReturnInst &I)              { DELEGATE(TerminatorI=
nst);}
-  RetTy visitBranchInst(BranchInst &I)              { DELEGATE(TerminatorI=
nst);}
-  RetTy visitSwitchInst(SwitchInst &I)              { DELEGATE(TerminatorI=
nst);}
-  RetTy visitIndirectBrInst(IndirectBrInst &I)      { DELEGATE(TerminatorI=
nst);}
-  RetTy visitInvokeInst(InvokeInst &I)              { DELEGATE(TerminatorI=
nst);}
-  RetTy visitUnwindInst(UnwindInst &I)              { DELEGATE(TerminatorI=
nst);}
-  RetTy visitResumeInst(ResumeInst &I)              { DELEGATE(TerminatorI=
nst);}
-  RetTy visitUnreachableInst(UnreachableInst &I)    { DELEGATE(TerminatorI=
nst);}
-  RetTy visitICmpInst(ICmpInst &I)                  { DELEGATE(CmpInst);}
-  RetTy visitFCmpInst(FCmpInst &I)                  { DELEGATE(CmpInst);}
-  RetTy visitAllocaInst(AllocaInst &I)              { DELEGATE(Instruction=
); }
-  RetTy visitLoadInst(LoadInst     &I)              { DELEGATE(Instruction=
); }
-  RetTy visitStoreInst(StoreInst   &I)              { DELEGATE(Instruction=
); }
-  RetTy visitAtomicCmpXchgInst(AtomicCmpXchgInst &I){ DELEGATE(Instruction=
); }
-  RetTy visitAtomicRMWInst(AtomicRMWInst &I)        { DELEGATE(Instruction=
); }
-  RetTy visitFenceInst(FenceInst   &I)              { DELEGATE(Instruction=
); }
-  RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(Instruction=
); }
-  RetTy visitPHINode(PHINode       &I)              { DELEGATE(Instruction=
); }
-  RetTy visitTruncInst(TruncInst &I)                { DELEGATE(CastInst); }
-  RetTy visitZExtInst(ZExtInst &I)                  { DELEGATE(CastInst); }
-  RetTy visitSExtInst(SExtInst &I)                  { DELEGATE(CastInst); }
-  RetTy visitFPTruncInst(FPTruncInst &I)            { DELEGATE(CastInst); }
-  RetTy visitFPExtInst(FPExtInst &I)                { DELEGATE(CastInst); }
-  RetTy visitFPToUIInst(FPToUIInst &I)              { DELEGATE(CastInst); }
-  RetTy visitFPToSIInst(FPToSIInst &I)              { DELEGATE(CastInst); }
-  RetTy visitUIToFPInst(UIToFPInst &I)              { DELEGATE(CastInst); }
-  RetTy visitSIToFPInst(SIToFPInst &I)              { DELEGATE(CastInst); }
-  RetTy visitPtrToIntInst(PtrToIntInst &I)          { DELEGATE(CastInst); }
-  RetTy visitIntToPtrInst(IntToPtrInst &I)          { DELEGATE(CastInst); }
-  RetTy visitBitCastInst(BitCastInst &I)            { DELEGATE(CastInst); }
-  RetTy visitSelectInst(SelectInst &I)              { DELEGATE(Instruction=
); }
-  RetTy visitCallInst(CallInst     &I)              { DELEGATE(Instruction=
); }
-  RetTy visitVAArgInst(VAArgInst   &I)              { DELEGATE(Instruction=
); }
+  RetTy visitReturnInst(ReturnInst &I)            { DELEGATE(TerminatorIns=
t);}
+  RetTy visitBranchInst(BranchInst &I)            { DELEGATE(TerminatorIns=
t);}
+  RetTy visitSwitchInst(SwitchInst &I)            { DELEGATE(TerminatorIns=
t);}
+  RetTy visitIndirectBrInst(IndirectBrInst &I)    { DELEGATE(TerminatorIns=
t);}
+  RetTy visitResumeInst(ResumeInst &I)            { DELEGATE(TerminatorIns=
t);}
+  RetTy visitUnreachableInst(UnreachableInst &I)  { DELEGATE(TerminatorIns=
t);}
+  RetTy visitICmpInst(ICmpInst &I)                { DELEGATE(CmpInst);}
+  RetTy visitFCmpInst(FCmpInst &I)                { DELEGATE(CmpInst);}
+  RetTy visitAllocaInst(AllocaInst &I)            { DELEGATE(UnaryInstruct=
ion);}
+  RetTy visitLoadInst(LoadInst     &I)            { DELEGATE(UnaryInstruct=
ion);}
+  RetTy visitStoreInst(StoreInst   &I)            { DELEGATE(Instruction);}
+  RetTy visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { DELEGATE(Instructio=
n);}
+  RetTy visitAtomicRMWInst(AtomicRMWInst &I)      { DELEGATE(Instruction);}
+  RetTy visitFenceInst(FenceInst   &I)            { DELEGATE(Instruction);}
+  RetTy visitGetElementPtrInst(GetElementPtrInst &I){ DELEGATE(Instruction=
);}
+  RetTy visitPHINode(PHINode       &I)            { DELEGATE(Instruction);}
+  RetTy visitTruncInst(TruncInst &I)              { DELEGATE(CastInst);}
+  RetTy visitZExtInst(ZExtInst &I)                { DELEGATE(CastInst);}
+  RetTy visitSExtInst(SExtInst &I)                { DELEGATE(CastInst);}
+  RetTy visitFPTruncInst(FPTruncInst &I)          { DELEGATE(CastInst);}
+  RetTy visitFPExtInst(FPExtInst &I)              { DELEGATE(CastInst);}
+  RetTy visitFPToUIInst(FPToUIInst &I)            { DELEGATE(CastInst);}
+  RetTy visitFPToSIInst(FPToSIInst &I)            { DELEGATE(CastInst);}
+  RetTy visitUIToFPInst(UIToFPInst &I)            { DELEGATE(CastInst);}
+  RetTy visitSIToFPInst(SIToFPInst &I)            { DELEGATE(CastInst);}
+  RetTy visitPtrToIntInst(PtrToIntInst &I)        { DELEGATE(CastInst);}
+  RetTy visitIntToPtrInst(IntToPtrInst &I)        { DELEGATE(CastInst);}
+  RetTy visitBitCastInst(BitCastInst &I)          { DELEGATE(CastInst);}
+  RetTy visitSelectInst(SelectInst &I)            { DELEGATE(Instruction);}
+  RetTy visitVAArgInst(VAArgInst   &I)            { DELEGATE(UnaryInstruct=
ion);}
   RetTy visitExtractElementInst(ExtractElementInst &I) { DELEGATE(Instruct=
ion);}
-  RetTy visitInsertElementInst(InsertElementInst &I) { DELEGATE(Instructio=
n); }
-  RetTy visitShuffleVectorInst(ShuffleVectorInst &I) { DELEGATE(Instructio=
n); }
-  RetTy visitExtractValueInst(ExtractValueInst &I)  { DELEGATE(Instruction=
);}
-  RetTy visitInsertValueInst(InsertValueInst &I)    { DELEGATE(Instruction=
); }
-  RetTy visitLandingPadInst(LandingPadInst &I)      { DELEGATE(Instruction=
); }
+  RetTy visitInsertElementInst(InsertElementInst &I) { DELEGATE(Instructio=
n);}
+  RetTy visitShuffleVectorInst(ShuffleVectorInst &I) { DELEGATE(Instructio=
n);}
+  RetTy visitExtractValueInst(ExtractValueInst &I){ DELEGATE(UnaryInstruct=
ion);}
+  RetTy visitInsertValueInst(InsertValueInst &I)  { DELEGATE(Instruction);=
 }
+  RetTy visitLandingPadInst(LandingPadInst &I)    { DELEGATE(Instruction);=
 }
+
+  // Call and Invoke are slightly different as they delegate first through
+  // a generic CallSite visitor.
+  RetTy visitCallInst(CallInst &I) {
+    return static_cast<SubClass*>(this)->visitCallSite(&I);
+  }
+  RetTy visitInvokeInst(InvokeInst &I) {
+    return static_cast<SubClass*>(this)->visitCallSite(&I);
+  }
=20
   // Next level propagators: If the user does not overload a specific
   // instruction type, they can overload one of these to get the whole cla=
ss
   // of instructions...
   //
-  RetTy visitTerminatorInst(TerminatorInst &I) { DELEGATE(Instruction); }
-  RetTy visitBinaryOperator(BinaryOperator &I) { DELEGATE(Instruction); }
-  RetTy visitCmpInst(CmpInst &I)               { DELEGATE(Instruction); }
-  RetTy visitCastInst(CastInst &I)             { DELEGATE(Instruction); }
+  RetTy visitCastInst(CastInst &I)                { DELEGATE(UnaryInstruct=
ion);}
+  RetTy visitBinaryOperator(BinaryOperator &I)    { DELEGATE(Instruction);}
+  RetTy visitCmpInst(CmpInst &I)                  { DELEGATE(Instruction);}
+  RetTy visitTerminatorInst(TerminatorInst &I)    { DELEGATE(Instruction);}
+  RetTy visitUnaryInstruction(UnaryInstruction &I){ DELEGATE(Instruction);}
+
+  // Provide a special visitor for a 'callsite' that visits both calls and
+  // invokes. When unimplemented, properly delegates to either the termina=
tor or
+  // regular instruction visitor.
+  RetTy visitCallSite(CallSite CS) {
+    assert(CS);
+    Instruction &I =3D *CS.getInstruction();
+    if (CS.isCall())
+      DELEGATE(Instruction);
+
+    assert(CS.isInvoke());
+    DELEGATE(TerminatorInst);
+  }
=20
   // If the user wants a 'default' case, they can choose to override this
   // function.  If this function is not overloaded in the user's subclass,=
 then
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/MachO.h
--- a/head/contrib/llvm/include/llvm/Support/MachO.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/Support/MachO.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -114,6 +114,10 @@
       LoadCommandVersionMinIPhoneOS       =3D 0x00000025u, // LC_VERSION_M=
IN_IPHONEOS
       LoadCommandFunctionStarts           =3D 0x00000026u, // LC_FUNCTION_=
STARTS
       LoadCommandDyldEnvironment          =3D 0x00000027u, // LC_DYLD_ENVI=
RONMENT
+      LoadCommandMain                     =3D 0x80000028u, // LC_MAIN
+      LoadCommandDataInCode               =3D 0x00000029u, // LC_DATA_IN_C=
ODE
+      LoadCommandSourceVersion            =3D 0x0000002Au, // LC_SOURCE_VE=
RSION
+      LoadCommandCodeSignDRs              =3D 0x0000002Bu, // LC_DYLIB_COD=
E_SIGN_DRS
=20
       // Constant bits for the "flags" field in llvm::MachO::segment_comma=
nd
       SegmentCommandFlagBitHighVM             =3D 0x1u, // SG_HIGHVM
@@ -240,6 +244,9 @@
       NListSectionNoSection     =3D 0u, // NO_SECT
       NListSectionMaxSection    =3D 0xffu, // MAX_SECT
=20
+      NListDescWeakRef          =3D 0x40u,
+      NListDescWeakDef          =3D 0x80u,
+
       // Constant values for the "n_type" field in llvm::MachO::nlist and
       // llvm::MachO::nlist_64 when "(n_type & NlistMaskStab) !=3D 0"
       StabGlobalSymbol          =3D 0x20u,  // N_GSYM=09
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/ManagedStatic.h
--- a/head/contrib/llvm/include/llvm/Support/ManagedStatic.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/ManagedStatic.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -16,6 +16,7 @@
=20
 #include "llvm/Support/Atomic.h"
 #include "llvm/Support/Threading.h"
+#include "llvm/Support/Valgrind.h"
=20
 namespace llvm {
=20
@@ -65,6 +66,7 @@
     void* tmp =3D Ptr;
     if (llvm_is_multithreaded()) sys::MemoryFence();
     if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>::=
call);
+    TsanHappensAfter(this);
=20
     return *static_cast<C*>(Ptr);
   }
@@ -72,6 +74,7 @@
     void* tmp =3D Ptr;
     if (llvm_is_multithreaded()) sys::MemoryFence();
     if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>::=
call);
+    TsanHappensAfter(this);
=20
     return static_cast<C*>(Ptr);
   }
@@ -79,6 +82,7 @@
     void* tmp =3D Ptr;
     if (llvm_is_multithreaded()) sys::MemoryFence();
     if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>::=
call);
+    TsanHappensAfter(this);
=20
     return *static_cast<C*>(Ptr);
   }
@@ -86,6 +90,7 @@
     void* tmp =3D Ptr;
     if (llvm_is_multithreaded()) sys::MemoryFence();
     if (!tmp) RegisterManagedStatic(object_creator<C>, object_deleter<C>::=
call);
+    TsanHappensAfter(this);
=20
     return static_cast<C*>(Ptr);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/MathExtras.h
--- a/head/contrib/llvm/include/llvm/Support/MathExtras.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/MathExtras.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -51,6 +51,13 @@
   return static_cast<int32_t>(x) =3D=3D x;
 }
=20
+/// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shif=
ted
+///                     left by S.
+template<unsigned N, unsigned S>
+inline bool isShiftedInt(int64_t x) {
+  return isInt<N+S>(x) && (x % (1<<S) =3D=3D 0);
+}
+
 /// isUInt - Checks if an unsigned integer fits into the given bit width.
 template<unsigned N>
 inline bool isUInt(uint64_t x) {
@@ -70,6 +77,13 @@
   return static_cast<uint32_t>(x) =3D=3D x;
 }
=20
+/// isShiftedUInt<N,S> - Checks if a unsigned integer is an N bit number s=
hifted
+///                     left by S.
+template<unsigned N, unsigned S>
+inline bool isShiftedUInt(uint64_t x) {
+  return isUInt<N+S>(x) && (x % (1<<S) =3D=3D 0);
+}
+
 /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)
 /// bit width.
 inline bool isUIntN(unsigned N, uint64_t x) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/MemoryObject.h
--- a/head/contrib/llvm/include/llvm/Support/MemoryObject.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/MemoryObject.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -23,19 +23,19 @@
 public:
   /// Destructor      - Override as necessary.
   virtual ~MemoryObject();
- =20
+
   /// getBase         - Returns the lowest valid address in the region.
   ///
   /// @result         - The lowest valid address.
   virtual uint64_t getBase() const =3D 0;
- =20
+
   /// getExtent       - Returns the size of the region in bytes.  (The reg=
ion is
-  ///                   contiguous, so the highest valid address of the re=
gion=20
+  ///                   contiguous, so the highest valid address of the re=
gion
   ///                   is getBase() + getExtent() - 1).
   ///
   /// @result         - The size of the region.
   virtual uint64_t getExtent() const =3D 0;
- =20
+
   /// readByte        - Tries to read a single byte from the region.
   ///
   /// @param address  - The address of the byte, in the same space as getB=
ase().
@@ -43,7 +43,7 @@
   /// @result         - 0 if successful; -1 if not.  Failure may be due to=
 a
   ///                   bounds violation or an implementation-specific err=
or.
   virtual int readByte(uint64_t address, uint8_t* ptr) const =3D 0;
- =20
+
   /// readBytes       - Tries to read a contiguous range of bytes from the
   ///                   region, up to the end of the region.
   ///                   You should override this function if there is a qu=
icker
@@ -67,4 +67,3 @@
 }
=20
 #endif
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/PathV1.h
--- a/head/contrib/llvm/include/llvm/Support/PathV1.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/PathV1.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -131,20 +131,6 @@
       /// @brief Find a library.
       static Path FindLibrary(std::string& short_name);
=20
-      /// Construct a path to the default LLVM configuration directory. The
-      /// implementation must ensure that this is a well-known (same on ma=
ny
-      /// systems) directory in which llvm configuration files exist. For
-      /// example, on Unix, the /etc/llvm directory has been selected.
-      /// @brief Construct a path to the default LLVM configuration direct=
ory
-      static Path GetLLVMDefaultConfigDir();
-
-      /// Construct a path to the LLVM installed configuration directory. =
The
-      /// implementation must ensure that this refers to the "etc" directo=
ry of
-      /// the LLVM installation. This is the location where configuration =
files
-      /// will be located for a particular installation of LLVM on a machi=
ne.
-      /// @brief Construct a path to the LLVM installed configuration dire=
ctory
-      static Path GetLLVMConfigDir();
-
       /// Construct a path to the current user's home directory. The
       /// implementation must use an operating system specific mechanism f=
or
       /// determining the user's home directory. For example, the environm=
ent
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/PatternMatch.h
--- a/head/contrib/llvm/include/llvm/Support/PatternMatch.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/PatternMatch.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -31,6 +31,7 @@
=20
 #include "llvm/Constants.h"
 #include "llvm/Instructions.h"
+#include "llvm/Operator.h"
=20
 namespace llvm {
 namespace PatternMatch {
@@ -97,12 +98,19 @@
       Res =3D &CI->getValue();
       return true;
     }
+    // FIXME: Remove this.
     if (ConstantVector *CV =3D dyn_cast<ConstantVector>(V))
       if (ConstantInt *CI =3D
           dyn_cast_or_null<ConstantInt>(CV->getSplatValue())) {
         Res =3D &CI->getValue();
         return true;
       }
+    if (ConstantDataVector *CV =3D dyn_cast<ConstantDataVector>(V))
+      if (ConstantInt *CI =3D
+          dyn_cast_or_null<ConstantInt>(CV->getSplatValue())) {
+        Res =3D &CI->getValue();
+        return true;
+      }
     return false;
   }
 };
@@ -143,9 +151,13 @@
   bool match(ITy *V) {
     if (const ConstantInt *CI =3D dyn_cast<ConstantInt>(V))
       return this->isValue(CI->getValue());
+    // FIXME: Remove this.
     if (const ConstantVector *CV =3D dyn_cast<ConstantVector>(V))
       if (ConstantInt *CI =3D dyn_cast_or_null<ConstantInt>(CV->getSplatVa=
lue()))
         return this->isValue(CI->getValue());
+    if (const ConstantDataVector *CV =3D dyn_cast<ConstantDataVector>(V))
+      if (ConstantInt *CI =3D dyn_cast_or_null<ConstantInt>(CV->getSplatVa=
lue()))
+        return this->isValue(CI->getValue());
     return false;
   }
 };
@@ -163,12 +175,22 @@
         Res =3D &CI->getValue();
         return true;
       }
+   =20
+    // FIXME: remove.
     if (const ConstantVector *CV =3D dyn_cast<ConstantVector>(V))
       if (ConstantInt *CI =3D dyn_cast_or_null<ConstantInt>(CV->getSplatVa=
lue()))
         if (this->isValue(CI->getValue())) {
           Res =3D &CI->getValue();
           return true;
         }
+   =20
+    if (const ConstantDataVector *CV =3D dyn_cast<ConstantDataVector>(V))
+      if (ConstantInt *CI =3D dyn_cast_or_null<ConstantInt>(CV->getSplatVa=
lue()))
+        if (this->isValue(CI->getValue())) {
+          Res =3D &CI->getValue();
+          return true;
+        }
+
     return false;
   }
 };
@@ -441,6 +463,26 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Class that matches exact binary ops.
+//
+template<typename SubPattern_t>
+struct Exact_match {
+  SubPattern_t SubPattern;
+
+  Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
+
+  template<typename OpTy>
+  bool match(OpTy *V) {
+    if (PossiblyExactOperator *PEO =3D dyn_cast<PossiblyExactOperator>(V))
+      return PEO->isExact() && SubPattern.match(V);
+    return false;
+  }
+};
+
+template<typename T>
+inline Exact_match<T> m_Exact(const T &SubPattern) { return SubPattern; }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Matchers for CmpInst classes
 //
=20
@@ -529,10 +571,8 @@
=20
   template<typename OpTy>
   bool match(OpTy *V) {
-    if (CastInst *I =3D dyn_cast<CastInst>(V))
-      return I->getOpcode() =3D=3D Opcode && Op.match(I->getOperand(0));
-    if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V))
-      return CE->getOpcode() =3D=3D Opcode && Op.match(CE->getOperand(0));
+    if (Operator *O =3D dyn_cast<Operator>(V))
+      return O->getOpcode() =3D=3D Opcode && Op.match(O->getOperand(0));
     return false;
   }
 };
@@ -585,21 +625,18 @@
=20
   template<typename OpTy>
   bool match(OpTy *V) {
-    if (Instruction *I =3D dyn_cast<Instruction>(V))
-      if (I->getOpcode() =3D=3D Instruction::Xor)
-        return matchIfNot(I->getOperand(0), I->getOperand(1));
-    if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V))
-      if (CE->getOpcode() =3D=3D Instruction::Xor)
-        return matchIfNot(CE->getOperand(0), CE->getOperand(1));
+    if (Operator *O =3D dyn_cast<Operator>(V))
+      if (O->getOpcode() =3D=3D Instruction::Xor)
+        return matchIfNot(O->getOperand(0), O->getOperand(1));
     return false;
   }
 private:
   bool matchIfNot(Value *LHS, Value *RHS) {
-    if (ConstantInt *CI =3D dyn_cast<ConstantInt>(RHS))
-      return CI->isAllOnesValue() && L.match(LHS);
-    if (ConstantVector *CV =3D dyn_cast<ConstantVector>(RHS))
-      return CV->isAllOnesValue() && L.match(LHS);
-    return false;
+    return (isa<ConstantInt>(RHS) || isa<ConstantDataVector>(RHS) ||
+            // FIXME: Remove CV.
+            isa<ConstantVector>(RHS)) &&
+           cast<Constant>(RHS)->isAllOnesValue() &&
+           L.match(LHS);
   }
 };
=20
@@ -615,19 +652,16 @@
=20
   template<typename OpTy>
   bool match(OpTy *V) {
-    if (Instruction *I =3D dyn_cast<Instruction>(V))
-      if (I->getOpcode() =3D=3D Instruction::Sub)
-        return matchIfNeg(I->getOperand(0), I->getOperand(1));
-    if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V))
-      if (CE->getOpcode() =3D=3D Instruction::Sub)
-        return matchIfNeg(CE->getOperand(0), CE->getOperand(1));
+    if (Operator *O =3D dyn_cast<Operator>(V))
+      if (O->getOpcode() =3D=3D Instruction::Sub)
+        return matchIfNeg(O->getOperand(0), O->getOperand(1));
     return false;
   }
 private:
   bool matchIfNeg(Value *LHS, Value *RHS) {
-    if (ConstantInt *C =3D dyn_cast<ConstantInt>(LHS))
-      return C->isZero() && L.match(RHS);
-    return false;
+    return ((isa<ConstantInt>(LHS) && cast<ConstantInt>(LHS)->isZero()) ||
+            isa<ConstantAggregateZero>(LHS)) &&
+           L.match(RHS);
   }
 };
=20
@@ -644,12 +678,9 @@
=20
   template<typename OpTy>
   bool match(OpTy *V) {
-    if (Instruction *I =3D dyn_cast<Instruction>(V))
-      if (I->getOpcode() =3D=3D Instruction::FSub)
-        return matchIfFNeg(I->getOperand(0), I->getOperand(1));
-    if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V))
-      if (CE->getOpcode() =3D=3D Instruction::FSub)
-        return matchIfFNeg(CE->getOperand(0), CE->getOperand(1));
+    if (Operator *O =3D dyn_cast<Operator>(V))
+      if (O->getOpcode() =3D=3D Instruction::FSub)
+        return matchIfFNeg(O->getOperand(0), O->getOperand(1));
     return false;
   }
 private:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Process.h
--- a/head/contrib/llvm/include/llvm/Support/Process.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Process.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -138,9 +138,6 @@
=20
       /// Resets the terminals colors, or returns an escape sequence to do=
 so.
       static const char *ResetColor();
-
-      /// Change the program working directory to that given by \arg Path.
-      static void SetWorkingDirectory(std::string Path);
     /// @}
   };
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Program.h
--- a/head/contrib/llvm/include/llvm/Support/Program.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Program.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -17,6 +17,7 @@
 #include "llvm/Support/Path.h"
=20
 namespace llvm {
+class error_code;
 namespace sys {
=20
   // TODO: Add operations to communicate with the process, redirect its I/=
O,
@@ -122,12 +123,12 @@
     /// @brief Construct a Program by finding it by name.
     static Path FindProgramByName(const std::string& name);
=20
-    // These methods change the specified standard stream (stdin,
-    // stdout, or stderr) to binary mode. They return true if an error
-    // occurred
-    static bool ChangeStdinToBinary();
-    static bool ChangeStdoutToBinary();
-    static bool ChangeStderrToBinary();
+    // These methods change the specified standard stream (stdin, stdout, =
or
+    // stderr) to binary mode. They return errc::success if the specified =
stream
+    // was changed. Otherwise a platform dependent error is returned.
+    static error_code ChangeStdinToBinary();
+    static error_code ChangeStdoutToBinary();
+    static error_code ChangeStderrToBinary();
=20
     /// A convenience function equivalent to Program prg; prg.Execute(..);
     /// prg.Wait(..);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Recycler.h
--- a/head/contrib/llvm/include/llvm/Support/Recycler.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Recycler.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -17,6 +17,7 @@
=20
 #include "llvm/ADT/ilist.h"
 #include "llvm/Support/AlignOf.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cassert>
=20
 namespace llvm {
@@ -52,7 +53,7 @@
   static void noteHead(RecyclerStruct*, RecyclerStruct*) {}
=20
   static void deleteNode(RecyclerStruct *) {
-    assert(0 && "Recycler's ilist_traits shouldn't see a deleteNode call!"=
);
+    llvm_unreachable("Recycler's ilist_traits shouldn't see a deleteNode c=
all!");
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/SMLoc.h
--- a/head/contrib/llvm/include/llvm/Support/SMLoc.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/include/llvm/Support/SMLoc.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -15,9 +15,11 @@
 #ifndef SUPPORT_SMLOC_H
 #define SUPPORT_SMLOC_H
=20
+#include <cassert>
+
 namespace llvm {
=20
-// SMLoc - Represents a location in source code.
+/// SMLoc - Represents a location in source code.
 class SMLoc {
   const char *Ptr;
 public:
@@ -38,7 +40,23 @@
   }
 };
=20
-}
+/// SMRange - Represents a range in source code.  Note that unlike standar=
d STL
+/// ranges, the locations specified are considered to be *inclusive*.  For
+/// example, [X,X] *does* include X, it isn't an empty range.
+class SMRange {
+public:
+  SMLoc Start, End;
+
+  SMRange() {}
+  SMRange(SMLoc Start, SMLoc End) : Start(Start), End(End) {
+    assert(Start.isValid() =3D=3D End.isValid() &&
+           "Start and end should either both be valid or both be invalid!"=
);
+  }
+ =20
+  bool isValid() const { return Start.isValid(); }
+};
+ =20
+} // end namespace llvm
=20
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/SourceMgr.h
--- a/head/contrib/llvm/include/llvm/Support/SourceMgr.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/SourceMgr.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -17,10 +17,8 @@
 #define SUPPORT_SOURCEMGR_H
=20
 #include "llvm/Support/SMLoc.h"
-
+#include "llvm/ADT/ArrayRef.h"
 #include <string>
-#include <vector>
-#include <cassert>
=20
 namespace llvm {
   class MemoryBuffer;
@@ -33,10 +31,16 @@
 /// and handles diagnostic wrangling.
 class SourceMgr {
 public:
+  enum DiagKind {
+    DK_Error,
+    DK_Warning,
+    DK_Note
+  };
+ =20
   /// DiagHandlerTy - Clients that want to handle their own diagnostics in=
 a
   /// custom way can register a function pointer+context as a diagnostic
   /// handler.  It gets called each time PrintMessage is invoked.
-  typedef void (*DiagHandlerTy)(const SMDiagnostic&, void *Context);
+  typedef void (*DiagHandlerTy)(const SMDiagnostic &, void *Context);
 private:
   struct SrcBuffer {
     /// Buffer - The memory buffer for the file.
@@ -124,11 +128,8 @@
   /// PrintMessage - Emit a message about the specified location with the
   /// specified string.
   ///
-  /// @param Type - If non-null, the kind of message (e.g., "error") which=
 is
-  /// prefixed to the message.
-  /// @param ShowLine - Should the diagnostic show the source line.
-  void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type,
-                    bool ShowLine =3D true) const;
+  void PrintMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,
+                    ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>()) cons=
t;
=20
=20
   /// GetMessage - Return an SMDiagnostic at the specified location with t=
he
@@ -136,10 +137,8 @@
   ///
   /// @param Type - If non-null, the kind of message (e.g., "error") which=
 is
   /// prefixed to the message.
-  /// @param ShowLine - Should the diagnostic show the source line.
-  SMDiagnostic GetMessage(SMLoc Loc,
-                          const Twine &Msg, const char *Type,
-                          bool ShowLine =3D true) const;
+  SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg,=20
+                          ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>()=
) const;
=20
   /// PrintIncludeStack - Prints the names of included files and the line =
of the
   /// file they were included from.  A diagnostic handler can use this bef=
ore
@@ -158,35 +157,38 @@
   SMLoc Loc;
   std::string Filename;
   int LineNo, ColumnNo;
+  SourceMgr::DiagKind Kind;
   std::string Message, LineContents;
-  unsigned ShowLine : 1;
+  std::vector<std::pair<unsigned, unsigned> > Ranges;
=20
 public:
   // Null diagnostic.
-  SMDiagnostic() : SM(0), LineNo(0), ColumnNo(0), ShowLine(0) {}
+  SMDiagnostic()
+    : SM(0), LineNo(0), ColumnNo(0), Kind(SourceMgr::DK_Error) {}
   // Diagnostic with no location (e.g. file not found, command line arg er=
ror).
-  SMDiagnostic(const std::string &filename, const std::string &Msg)
-    : SM(0), Filename(filename), LineNo(-1), ColumnNo(-1),
-      Message(Msg), ShowLine(false) {}
+  SMDiagnostic(const std::string &filename, SourceMgr::DiagKind Kind,
+               const std::string &Msg)
+    : SM(0), Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Kind),
+      Message(Msg) {}
  =20
   // Diagnostic with a location.
   SMDiagnostic(const SourceMgr &sm, SMLoc L, const std::string &FN,
-               int Line, int Col,
+               int Line, int Col, SourceMgr::DiagKind Kind,
                const std::string &Msg, const std::string &LineStr,
-               bool showline =3D true)
-    : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Message(=
Msg),
-      LineContents(LineStr), ShowLine(showline) {}
+               ArrayRef<std::pair<unsigned,unsigned> > Ranges);
=20
   const SourceMgr *getSourceMgr() const { return SM; }
   SMLoc getLoc() const { return Loc; }
   const std::string &getFilename() const { return Filename; }
   int getLineNo() const { return LineNo; }
   int getColumnNo() const { return ColumnNo; }
+  SourceMgr::DiagKind getKind() const { return Kind; }
   const std::string &getMessage() const { return Message; }
   const std::string &getLineContents() const { return LineContents; }
-  bool getShowLine() const { return ShowLine; }
- =20
-  void Print(const char *ProgName, raw_ostream &S) const;
+  const std::vector<std::pair<unsigned, unsigned> > &getRanges() const {
+    return Ranges;
+  }
+  void print(const char *ProgName, raw_ostream &S) const;
 };
=20
 }  // end llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/TargetRegistry.h
--- a/head/contrib/llvm/include/llvm/Support/TargetRegistry.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/TargetRegistry.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -44,12 +44,14 @@
   class MCTargetAsmLexer;
   class MCTargetAsmParser;
   class TargetMachine;
+  class TargetOptions;
   class raw_ostream;
   class formatted_raw_ostream;
=20
   MCStreamer *createAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
                                 bool isVerboseAsm,
                                 bool useLoc, bool useCFI,
+                                bool useDwarfDirectory,
                                 MCInstPrinter *InstPrint,
                                 MCCodeEmitter *CE,
                                 MCAsmBackend *TAB,
@@ -73,7 +75,8 @@
                                             StringRef TT);
     typedef MCCodeGenInfo *(*MCCodeGenInfoCtorFnTy)(StringRef TT,
                                                     Reloc::Model RM,
-                                                    CodeModel::Model CM);
+                                                    CodeModel::Model CM,
+                                                    CodeGenOpt::Level OL);
     typedef MCInstrInfo *(*MCInstrInfoCtorFnTy)(void);
     typedef MCInstrAnalysis *(*MCInstrAnalysisCtorFnTy)(const MCInstrInfo*=
Info);
     typedef MCRegisterInfo *(*MCRegInfoCtorFnTy)(StringRef TT);
@@ -84,8 +87,10 @@
                                                   StringRef TT,
                                                   StringRef CPU,
                                                   StringRef Features,
+                                                  const TargetOptions &Opt=
ions,
                                                   Reloc::Model RM,
-                                                  CodeModel::Model CM);
+                                                  CodeModel::Model CM,
+                                                  CodeGenOpt::Level OL);
     typedef AsmPrinter *(*AsmPrinterCtorTy)(TargetMachine &TM,
                                             MCStreamer &Streamer);
     typedef MCAsmBackend *(*MCAsmBackendCtorTy)(const Target &T, StringRef=
 TT);
@@ -99,6 +104,8 @@
     typedef MCInstPrinter *(*MCInstPrinterCtorTy)(const Target &T,
                                                   unsigned SyntaxVariant,
                                                   const MCAsmInfo &MAI,
+                                                  const MCInstrInfo &MII,
+                                                  const MCRegisterInfo &MR=
I,
                                                   const MCSubtargetInfo &S=
TI);
     typedef MCCodeEmitter *(*MCCodeEmitterCtorTy)(const MCInstrInfo &II,
                                                   const MCSubtargetInfo &S=
TI,
@@ -116,6 +123,7 @@
                                              bool isVerboseAsm,
                                              bool useLoc,
                                              bool useCFI,
+                                             bool useDwarfDirectory,
                                              MCInstPrinter *InstPrint,
                                              MCCodeEmitter *CE,
                                              MCAsmBackend *TAB,
@@ -143,8 +151,8 @@
     /// registered.
     MCAsmInfoCtorFnTy MCAsmInfoCtorFn;
=20
-    /// MCCodeGenInfoCtorFn - Constructor function for this target's MCCod=
eGenInfo,
-    /// if registered.
+    /// MCCodeGenInfoCtorFn - Constructor function for this target's
+    /// MCCodeGenInfo, if registered.
     MCCodeGenInfoCtorFnTy MCCodeGenInfoCtorFn;
=20
     /// MCInstrInfoCtorFn - Constructor function for this target's MCInstr=
Info,
@@ -275,10 +283,11 @@
     /// createMCCodeGenInfo - Create a MCCodeGenInfo implementation.
     ///
     MCCodeGenInfo *createMCCodeGenInfo(StringRef Triple, Reloc::Model RM,
-                                       CodeModel::Model CM) const {
+                                       CodeModel::Model CM,
+                                       CodeGenOpt::Level OL) const {
       if (!MCCodeGenInfoCtorFn)
         return 0;
-      return MCCodeGenInfoCtorFn(Triple, RM, CM);
+      return MCCodeGenInfoCtorFn(Triple, RM, CM, OL);
     }
=20
     /// createMCInstrInfo - Create a MCInstrInfo implementation.
@@ -329,12 +338,14 @@
     /// either the target triple from the module, or the target triple of =
the
     /// host if that does not exist.
     TargetMachine *createTargetMachine(StringRef Triple, StringRef CPU,
-                               StringRef Features,
-                               Reloc::Model RM =3D Reloc::Default,
-                               CodeModel::Model CM =3D CodeModel::Default)=
 const {
+                             StringRef Features, const TargetOptions &Opti=
ons,
+                             Reloc::Model RM =3D Reloc::Default,
+                             CodeModel::Model CM =3D CodeModel::Default,
+                             CodeGenOpt::Level OL =3D CodeGenOpt::Default)=
 const {
       if (!TargetMachineCtorFn)
         return 0;
-      return TargetMachineCtorFn(*this, Triple, CPU, Features, RM, CM);
+      return TargetMachineCtorFn(*this, Triple, CPU, Features, Options,
+                                 RM, CM, OL);
     }
=20
     /// createMCAsmBackend - Create a target specific assembly parser.
@@ -383,10 +394,12 @@
=20
     MCInstPrinter *createMCInstPrinter(unsigned SyntaxVariant,
                                        const MCAsmInfo &MAI,
+                                       const MCInstrInfo &MII,
+                                       const MCRegisterInfo &MRI,
                                        const MCSubtargetInfo &STI) const {
       if (!MCInstPrinterCtorFn)
         return 0;
-      return MCInstPrinterCtorFn(*this, SyntaxVariant, MAI, STI);
+      return MCInstPrinterCtorFn(*this, SyntaxVariant, MAI, MII, MRI, STI);
     }
=20
=20
@@ -426,13 +439,14 @@
                                   bool isVerboseAsm,
                                   bool useLoc,
                                   bool useCFI,
+                                  bool useDwarfDirectory,
                                   MCInstPrinter *InstPrint,
                                   MCCodeEmitter *CE,
                                   MCAsmBackend *TAB,
                                   bool ShowInst) const {
       // AsmStreamerCtorFn is default to llvm::createAsmStreamer
       return AsmStreamerCtorFn(Ctx, OS, isVerboseAsm, useLoc, useCFI,
-                               InstPrint, CE, TAB, ShowInst);
+                               useDwarfDirectory, InstPrint, CE, TAB, Show=
Inst);
     }
=20
     /// @}
@@ -776,7 +790,7 @@
   /// extern "C" void LLVMInitializeFooTargetInfo() {
   ///   RegisterTarget<Triple::foo> X(TheFooTarget, "foo", "Foo descriptio=
n");
   /// }
-  template<Triple::ArchType TargetArchType =3D Triple::InvalidArch,
+  template<Triple::ArchType TargetArchType =3D Triple::UnknownArch,
            bool HasJIT =3D false>
   struct RegisterTarget {
     RegisterTarget(Target &T, const char *Name, const char *Desc) {
@@ -840,8 +854,8 @@
       TargetRegistry::RegisterMCCodeGenInfo(T, &Allocator);
     }
   private:
-    static MCCodeGenInfo *Allocator(StringRef TT,
-                                    Reloc::Model RM, CodeModel::Model CM) {
+    static MCCodeGenInfo *Allocator(StringRef TT, Reloc::Model RM,
+                                    CodeModel::Model CM, CodeGenOpt::Level=
 OL) {
       return new MCCodeGenInfoImpl();
     }
   };
@@ -1010,9 +1024,11 @@
   private:
     static TargetMachine *Allocator(const Target &T, StringRef TT,
                                     StringRef CPU, StringRef FS,
+                                    const TargetOptions &Options,
                                     Reloc::Model RM,
-                                    CodeModel::Model CM) {
-      return new TargetMachineImpl(T, TT, CPU, FS, RM, CM);
+                                    CodeModel::Model CM,
+                                    CodeGenOpt::Level OL) {
+      return new TargetMachineImpl(T, TT, CPU, FS, Options, RM, CM, OL);
     }
   };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/TargetSelect.h
--- a/head/contrib/llvm/include/llvm/Support/TargetSelect.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/TargetSelect.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -149,6 +149,18 @@
 #endif
   } =20
=20
+  /// InitializeNativeTargetDisassembler - The main program should call
+  /// this function to initialize the native target disassembler.
+  inline bool InitializeNativeTargetDisassembler() {
+  // If we have a native target, initialize the corresponding disassembler.
+#ifdef LLVM_NATIVE_DISASSEMBLER
+    LLVM_NATIVE_DISASSEMBLER();
+    return false;
+#else
+    return true;
+#endif
+  } =20
+
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/Valgrind.h
--- a/head/contrib/llvm/include/llvm/Support/Valgrind.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/Valgrind.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -16,8 +16,23 @@
 #ifndef LLVM_SYSTEM_VALGRIND_H
 #define LLVM_SYSTEM_VALGRIND_H
=20
+#include "llvm/Support/Compiler.h"
+#include "llvm/Config/llvm-config.h"
 #include <stddef.h>
=20
+#if LLVM_ENABLE_THREADS !=3D 0 && !defined(NDEBUG)
+// tsan (Thread Sanitizer) is a valgrind-based tool that detects these exa=
ct
+// functions by name.
+extern "C" {
+LLVM_ATTRIBUTE_WEAK void AnnotateHappensAfter(const char *file, int line,
+                                              const volatile void *cv);
+LLVM_ATTRIBUTE_WEAK void AnnotateHappensBefore(const char *file, int line,
+                                               const volatile void *cv);
+LLVM_ATTRIBUTE_WEAK void AnnotateIgnoreWritesBegin(const char *file, int l=
ine);
+LLVM_ATTRIBUTE_WEAK void AnnotateIgnoreWritesEnd(const char *file, int lin=
e);
+}
+#endif
+
 namespace llvm {
 namespace sys {
   // True if Valgrind is controlling this process.
@@ -26,6 +41,34 @@
   // Discard valgrind's translation of code in the range [Addr .. Addr + L=
en).
   // Otherwise valgrind may continue to execute the old version of the cod=
e.
   void ValgrindDiscardTranslations(const void *Addr, size_t Len);
+
+#if LLVM_ENABLE_THREADS !=3D 0 && !defined(NDEBUG)
+  // Thread Sanitizer is a valgrind tool that finds races in code.
+  // See http://code.google.com/p/data-race-test/wiki/DynamicAnnotations .
+
+  // This marker is used to define a happens-before arc. The race detector=
 will
+  // infer an arc from the begin to the end when they share the same point=
er
+  // argument.
+  #define TsanHappensBefore(cv) \
+    AnnotateHappensBefore(__FILE__, __LINE__, cv)
+
+  // This marker defines the destination of a happens-before arc.
+  #define TsanHappensAfter(cv) \
+    AnnotateHappensAfter(__FILE__, __LINE__, cv)
+
+  // Ignore any races on writes between here and the next TsanIgnoreWrites=
End.
+  #define TsanIgnoreWritesBegin() \
+    AnnotateIgnoreWritesBegin(__FILE__, __LINE__)
+
+  // Resume checking for racy writes.
+  #define TsanIgnoreWritesEnd() \
+    AnnotateIgnoreWritesEnd(__FILE__, __LINE__)
+#else
+  #define TsanHappensBefore(cv)
+  #define TsanHappensAfter(cv)
+  #define TsanIgnoreWritesBegin()
+  #define TsanIgnoreWritesEnd()
+#endif
 }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/ValueHandle.h
--- a/head/contrib/llvm/include/llvm/Support/ValueHandle.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/ValueHandle.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -49,52 +49,61 @@
     Tracking,
     Weak
   };
+
 private:
-
   PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
   ValueHandleBase *Next;
-  Value *VP;
+
+  // A subclass may want to store some information along with the value
+  // pointer. Allow them to do this by making the value pointer a pointer-=
int
+  // pair. The 'setValPtrInt' and 'getValPtrInt' methods below give them t=
his
+  // access.
+  PointerIntPair<Value*, 2> VP;
  =20
   explicit ValueHandleBase(const ValueHandleBase&); // DO NOT IMPLEMENT.
 public:
   explicit ValueHandleBase(HandleBaseKind Kind)
-    : PrevPair(0, Kind), Next(0), VP(0) {}
+    : PrevPair(0, Kind), Next(0), VP(0, 0) {}
   ValueHandleBase(HandleBaseKind Kind, Value *V)
-    : PrevPair(0, Kind), Next(0), VP(V) {
-    if (isValid(VP))
+    : PrevPair(0, Kind), Next(0), VP(V, 0) {
+    if (isValid(VP.getPointer()))
       AddToUseList();
   }
   ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
     : PrevPair(0, Kind), Next(0), VP(RHS.VP) {
-    if (isValid(VP))
+    if (isValid(VP.getPointer()))
       AddToExistingUseList(RHS.getPrevPtr());
   }
   ~ValueHandleBase() {
-    if (isValid(VP))
+    if (isValid(VP.getPointer()))
       RemoveFromUseList();
   }
=20
   Value *operator=3D(Value *RHS) {
-    if (VP =3D=3D RHS) return RHS;
-    if (isValid(VP)) RemoveFromUseList();
-    VP =3D RHS;
-    if (isValid(VP)) AddToUseList();
+    if (VP.getPointer() =3D=3D RHS) return RHS;
+    if (isValid(VP.getPointer())) RemoveFromUseList();
+    VP.setPointer(RHS);
+    if (isValid(VP.getPointer())) AddToUseList();
     return RHS;
   }
=20
   Value *operator=3D(const ValueHandleBase &RHS) {
-    if (VP =3D=3D RHS.VP) return RHS.VP;
-    if (isValid(VP)) RemoveFromUseList();
-    VP =3D RHS.VP;
-    if (isValid(VP)) AddToExistingUseList(RHS.getPrevPtr());
-    return VP;
+    if (VP.getPointer() =3D=3D RHS.VP.getPointer()) return RHS.VP.getPoint=
er();
+    if (isValid(VP.getPointer())) RemoveFromUseList();
+    VP.setPointer(RHS.VP.getPointer());
+    if (isValid(VP.getPointer())) AddToExistingUseList(RHS.getPrevPtr());
+    return VP.getPointer();
   }
=20
   Value *operator->() const { return getValPtr(); }
   Value &operator*() const { return *getValPtr(); }
=20
 protected:
-  Value *getValPtr() const { return VP; }
+  Value *getValPtr() const { return VP.getPointer(); }
+
+  void setValPtrInt(unsigned K) { VP.setInt(K); }
+  unsigned getValPtrInt() const { return VP.getInt(); }
+
   static bool isValid(Value *V) {
     return V &&
            V !=3D DenseMapInfo<Value *>::getEmptyKey() &&
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/system_error.h
--- a/head/contrib/llvm/include/llvm/Support/system_error.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/system_error.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -470,17 +470,6 @@
=20
 namespace llvm {
=20
-template <class T, T v>
-struct integral_constant {
-  typedef T value_type;
-  static const value_type value =3D v;
-  typedef integral_constant<T,v> type;
-  operator value_type() { return value; }
-};
-
-typedef integral_constant<bool, true> true_type;
-typedef integral_constant<bool, false> false_type;
-
 // is_error_code_enum
=20
 template <class Tp> struct is_error_code_enum : public false_type {};
@@ -738,6 +727,10 @@
 public:
   error_code() : _val_(0), _cat_(&system_category()) {}
=20
+  static error_code success() {
+    return error_code();
+  }
+
   error_code(int _val, const error_category& _cat)
     : _val_(_val), _cat_(&_cat) {}
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Support=
/type_traits.h
--- a/head/contrib/llvm/include/llvm/Support/type_traits.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Support/type_traits.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -17,6 +17,8 @@
 #ifndef LLVM_SUPPORT_TYPE_TRAITS_H
 #define LLVM_SUPPORT_TYPE_TRAITS_H
=20
+#include "llvm/Support/DataTypes.h"
+#include <cstddef>
 #include <utility>
=20
 // This is actually the conforming implementation which works with abstract
@@ -64,22 +66,99 @@
 // std::pair's are pod-like if their elements are.
 template<typename T, typename U>
 struct isPodLike<std::pair<T, U> > {
-  static const bool value =3D isPodLike<T>::value & isPodLike<U>::value;
+  static const bool value =3D isPodLike<T>::value && isPodLike<U>::value;
 };
  =20
=20
+template <class T, T v>
+struct integral_constant {
+  typedef T value_type;
+  static const value_type value =3D v;
+  typedef integral_constant<T,v> type;
+  operator value_type() { return value; }
+};
+
+typedef integral_constant<bool, true> true_type;
+typedef integral_constant<bool, false> false_type;
+
 /// \brief Metafunction that determines whether the two given types are=20
 /// equivalent.
-template<typename T, typename U>
-struct is_same {
-  static const bool value =3D false;
+template<typename T, typename U> struct is_same       : public false_type =
{};
+template<typename T>             struct is_same<T, T> : public true_type {=
};
+
+/// \brief Metafunction that removes const qualification from a type.
+template <typename T> struct remove_const          { typedef T type; };
+template <typename T> struct remove_const<const T> { typedef T type; };
+
+/// \brief Metafunction that removes volatile qualification from a type.
+template <typename T> struct remove_volatile             { typedef T type;=
 };
+template <typename T> struct remove_volatile<volatile T> { typedef T type;=
 };
+
+/// \brief Metafunction that removes both const and volatile qualification=
 from
+/// a type.
+template <typename T> struct remove_cv {
+  typedef typename remove_const<typename remove_volatile<T>::type>::type t=
ype;
 };
=20
-template<typename T>
-struct is_same<T, T> {
-  static const bool value =3D true;
+/// \brief Helper to implement is_integral metafunction.
+template <typename T> struct is_integral_impl           : false_type {};
+template <> struct is_integral_impl<         bool>      : true_type {};
+template <> struct is_integral_impl<         char>      : true_type {};
+template <> struct is_integral_impl<  signed char>      : true_type {};
+template <> struct is_integral_impl<unsigned char>      : true_type {};
+template <> struct is_integral_impl<         wchar_t>   : true_type {};
+template <> struct is_integral_impl<         short>     : true_type {};
+template <> struct is_integral_impl<unsigned short>     : true_type {};
+template <> struct is_integral_impl<         int>       : true_type {};
+template <> struct is_integral_impl<unsigned int>       : true_type {};
+template <> struct is_integral_impl<         long>      : true_type {};
+template <> struct is_integral_impl<unsigned long>      : true_type {};
+template <> struct is_integral_impl<         long long> : true_type {};
+template <> struct is_integral_impl<unsigned long long> : true_type {};
+
+/// \brief Metafunction that determines whether the given type is an integ=
ral
+/// type.
+template <typename T>
+struct is_integral : is_integral_impl<T> {};
+
+/// \brief Metafunction to remove reference from a type.
+template <typename T> struct remove_reference { typedef T type; };
+template <typename T> struct remove_reference<T&> { typedef T type; };
+
+/// \brief Metafunction that determines whether the given type is a pointer
+/// type.
+template <typename T> struct is_pointer : false_type {};
+template <typename T> struct is_pointer<T*> : true_type {};
+template <typename T> struct is_pointer<T* const> : true_type {};
+template <typename T> struct is_pointer<T* volatile> : true_type {};
+template <typename T> struct is_pointer<T* const volatile> : true_type {};
+
+/// \brief Metafunction that determines whether the given type is either an
+/// integral type or an enumeration type.
+///
+/// Note that this accepts potentially more integral types than we whiteli=
st
+/// above for is_integral because it is based on merely being convertible
+/// implicitly to an integral type.
+template <typename T> class is_integral_or_enum {
+  // Provide an overload which can be called with anything implicitly
+  // convertible to an unsigned long long. This should catch integer types=
 and
+  // enumeration types at least. We blacklist classes with conversion oper=
ators
+  // below.
+  static double check_int_convertible(unsigned long long);
+  static char check_int_convertible(...);
+
+  typedef typename remove_reference<T>::type UnderlyingT;
+  static UnderlyingT &nonce_instance;
+
+public:
+  enum {
+    value =3D (!is_class<UnderlyingT>::value && !is_pointer<UnderlyingT>::=
value &&
+             !is_same<UnderlyingT, float>::value &&
+             !is_same<UnderlyingT, double>::value &&
+             sizeof(char) !=3D sizeof(check_int_convertible(nonce_instance=
)))
+  };
 };
- =20
+
 // enable_if_c - Enable/disable a template based on a metafunction
 template<bool Cond, typename T =3D void>
 struct enable_if_c {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/TableGe=
n/Record.h
--- a/head/contrib/llvm/include/llvm/TableGen/Record.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/include/llvm/TableGen/Record.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -20,6 +20,7 @@
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/DataTypes.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 #include <map>
=20
@@ -32,7 +33,6 @@
 class IntRecTy;
 class StringRecTy;
 class ListRecTy;
-class CodeRecTy;
 class DagRecTy;
 class RecordRecTy;
=20
@@ -43,7 +43,6 @@
 class BitsInit;
 class IntInit;
 class StringInit;
-class CodeInit;
 class ListInit;
 class UnOpInit;
 class BinOpInit;
@@ -68,6 +67,7 @@
=20
 class RecTy {
   ListRecTy *ListTy;
+  virtual void anchor();
 public:
   RecTy() : ListTy(0) {}
   virtual ~RecTy() {}
@@ -99,7 +99,6 @@
   virtual Init *convertValue( TernOpInit *UI) {
     return convertValue((TypedInit*)UI);
   }
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return 0; }
   virtual Init *convertValue(   DefInit *DI) { return 0; }
   virtual Init *convertValue(   DagInit *DI) { return 0; }
@@ -119,7 +118,6 @@
   virtual bool baseClassOf(const IntRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
   virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
 };
@@ -144,7 +142,6 @@
   virtual Init *convertValue(   IntInit *II);
   virtual Init *convertValue(StringInit *SI) { return 0; }
   virtual Init *convertValue(  ListInit *LI) { return 0; }
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return (Init*)VB; }
   virtual Init *convertValue(   DefInit *DI) { return 0; }
   virtual Init *convertValue(   DagInit *DI) { return 0; }
@@ -165,7 +162,6 @@
   virtual bool baseClassOf(const IntRecTy    *RHS) const { return true; }
   virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
   virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
=20
@@ -189,7 +185,6 @@
   virtual Init *convertValue(   IntInit *II);
   virtual Init *convertValue(StringInit *SI) { return 0; }
   virtual Init *convertValue(  ListInit *LI) { return 0; }
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return 0; }
   virtual Init *convertValue(   DefInit *DI) { return 0; }
   virtual Init *convertValue(   DagInit *DI) { return 0; }
@@ -212,7 +207,6 @@
   virtual bool baseClassOf(const IntRecTy    *RHS) const { return true; }
   virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
   virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
=20
@@ -233,7 +227,6 @@
   virtual Init *convertValue(   IntInit *II) { return (Init*)II; }
   virtual Init *convertValue(StringInit *SI) { return 0; }
   virtual Init *convertValue(  ListInit *LI) { return 0; }
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return 0; }
   virtual Init *convertValue(   DefInit *DI) { return 0; }
   virtual Init *convertValue(   DagInit *DI) { return 0; }
@@ -255,7 +248,6 @@
   virtual bool baseClassOf(const IntRecTy    *RHS) const { return true; }
   virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
   virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
=20
@@ -279,7 +271,6 @@
   virtual Init *convertValue( BinOpInit *BO);
   virtual Init *convertValue( TernOpInit *BO) { return RecTy::convertValue=
(BO);}
=20
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return 0; }
   virtual Init *convertValue(   DefInit *DI) { return 0; }
   virtual Init *convertValue(   DagInit *DI) { return 0; }
@@ -298,7 +289,6 @@
   virtual bool baseClassOf(const IntRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const StringRecTy *RHS) const { return true; }
   virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
 };
@@ -322,7 +312,6 @@
   virtual Init *convertValue(   IntInit *II) { return 0; }
   virtual Init *convertValue(StringInit *SI) { return 0; }
   virtual Init *convertValue(  ListInit *LI);
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return 0; }
   virtual Init *convertValue(   DefInit *DI) { return 0; }
   virtual Init *convertValue(   DagInit *DI) { return 0; }
@@ -346,47 +335,6 @@
   virtual bool baseClassOf(const ListRecTy   *RHS) const {
     return RHS->getElementType()->typeIsConvertibleTo(Ty);
   }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
-  virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
-};
-
-/// CodeRecTy - 'code' - Represent an code fragment, function or method.
-///
-class CodeRecTy : public RecTy {
-  static CodeRecTy Shared;
-  CodeRecTy() {}
-public:
-  static CodeRecTy *get() { return &Shared; }
-
-  virtual Init *convertValue( UnsetInit *UI) { return (Init*)UI; }
-  virtual Init *convertValue(   BitInit *BI) { return 0; }
-  virtual Init *convertValue(  BitsInit *BI) { return 0; }
-  virtual Init *convertValue(   IntInit *II) { return 0; }
-  virtual Init *convertValue(StringInit *SI) { return 0; }
-  virtual Init *convertValue(  ListInit *LI) { return 0; }
-  virtual Init *convertValue(  CodeInit *CI) { return (Init*)CI; }
-  virtual Init *convertValue(VarBitInit *VB) { return 0; }
-  virtual Init *convertValue(   DefInit *DI) { return 0; }
-  virtual Init *convertValue(   DagInit *DI) { return 0; }
-  virtual Init *convertValue( UnOpInit *UI) { return RecTy::convertValue(U=
I);}
-  virtual Init *convertValue( BinOpInit *UI) { return RecTy::convertValue(=
UI);}
-  virtual Init *convertValue( TernOpInit *UI) { return RecTy::convertValue=
(UI);}
-  virtual Init *convertValue( TypedInit *TI);
-  virtual Init *convertValue(   VarInit *VI) { return RecTy::convertValue(=
VI);}
-  virtual Init *convertValue( FieldInit *FI) { return RecTy::convertValue(=
FI);}
-
-  std::string getAsString() const { return "code"; }
-
-  bool typeIsConvertibleTo(const RecTy *RHS) const {
-    return RHS->baseClassOf(this);
-  }
-  virtual bool baseClassOf(const BitRecTy    *RHS) const { return false; }
-  virtual bool baseClassOf(const BitsRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const IntRecTy    *RHS) const { return false; }
-  virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
-  virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return true; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
 };
@@ -405,7 +353,6 @@
   virtual Init *convertValue(   IntInit *II) { return 0; }
   virtual Init *convertValue(StringInit *SI) { return 0; }
   virtual Init *convertValue(  ListInit *LI) { return 0; }
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return 0; }
   virtual Init *convertValue(   DefInit *DI) { return 0; }
   virtual Init *convertValue( UnOpInit *BO);
@@ -427,7 +374,6 @@
   virtual bool baseClassOf(const IntRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
   virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return true; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const { return false; }
 };
@@ -451,7 +397,6 @@
   virtual Init *convertValue(   IntInit *II) { return 0; }
   virtual Init *convertValue(StringInit *SI) { return 0; }
   virtual Init *convertValue(  ListInit *LI) { return 0; }
-  virtual Init *convertValue(  CodeInit *CI) { return 0; }
   virtual Init *convertValue(VarBitInit *VB) { return 0; }
   virtual Init *convertValue( UnOpInit *UI) { return RecTy::convertValue(U=
I);}
   virtual Init *convertValue( BinOpInit *UI) { return RecTy::convertValue(=
UI);}
@@ -472,7 +417,6 @@
   virtual bool baseClassOf(const IntRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const StringRecTy *RHS) const { return false; }
   virtual bool baseClassOf(const ListRecTy   *RHS) const { return false; }
-  virtual bool baseClassOf(const CodeRecTy   *RHS) const { return false; }
   virtual bool baseClassOf(const DagRecTy    *RHS) const { return false; }
   virtual bool baseClassOf(const RecordRecTy *RHS) const;
 };
@@ -489,6 +433,7 @@
 class Init {
   Init(const Init &);  // Do not define.
   Init &operator=3D(const Init &);  // Do not define.
+  virtual void anchor();
=20
 protected:
   Init(void) {}
@@ -617,6 +562,7 @@
   UnsetInit() : Init() {}
   UnsetInit(const UnsetInit &);  // Do not define.
   UnsetInit &operator=3D(const UnsetInit &Other);  // Do not define.
+  virtual void anchor();
=20
 public:
   static UnsetInit *get();
@@ -638,6 +584,7 @@
   explicit BitInit(bool V) : Value(V) {}
   BitInit(const BitInit &Other);  // Do not define.
   BitInit &operator=3D(BitInit &Other);  // Do not define.
+  virtual void anchor();
=20
 public:
   static BitInit *get(bool V);
@@ -725,8 +672,7 @@
   ///
   virtual Init *resolveBitReference(Record &R, const RecordVal *RV,
                                     unsigned Bit) const {
-    assert(0 && "Illegal bit reference off int");
-    return 0;
+    llvm_unreachable("Illegal bit reference off int");
   }
=20
   /// resolveListElementReference - This method is used to implement
@@ -734,8 +680,7 @@
   /// now, we return the resolved value, otherwise we return null.
   virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
                                             unsigned Elt) const {
-    assert(0 && "Illegal element reference off int");
-    return 0;
+    llvm_unreachable("Illegal element reference off int");
   }
 };
=20
@@ -750,9 +695,10 @@
=20
   StringInit(const StringInit &Other);  // Do not define.
   StringInit &operator=3D(const StringInit &Other);  // Do not define.
+  virtual void anchor();
=20
 public:
-  static StringInit *get(const std::string &V);
+  static StringInit *get(StringRef);
=20
   const std::string &getValue() const { return Value; }
=20
@@ -769,8 +715,7 @@
   ///
   virtual Init *resolveBitReference(Record &R, const RecordVal *RV,
                                     unsigned Bit) const {
-    assert(0 && "Illegal bit reference off string");
-    return 0;
+    llvm_unreachable("Illegal bit reference off string");
   }
=20
   /// resolveListElementReference - This method is used to implement
@@ -778,33 +723,10 @@
   /// now, we return the resolved value, otherwise we return null.
   virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
                                             unsigned Elt) const {
-    assert(0 && "Illegal element reference off string");
-    return 0;
+    llvm_unreachable("Illegal element reference off string");
   }
 };
=20
-/// CodeInit - "[{...}]" - Represent a code fragment.
-///
-class CodeInit : public Init {
-  std::string Value;
-
-  explicit CodeInit(const std::string &V) : Value(V) {}
-
-  CodeInit(const CodeInit &Other);  // Do not define.
-  CodeInit &operator=3D(const CodeInit &Other);  // Do not define.
-
-public:
-  static CodeInit *get(const std::string &V);
-
-  const std::string &getValue() const { return Value; }
-
-  virtual Init *convertInitializerTo(RecTy *Ty) const {
-    return Ty->convertValue(const_cast<CodeInit *>(this));
-  }
-
-  virtual std::string getAsString() const { return "[{" + Value + "}]"; }
-};
-
 /// ListInit - [AL, AH, CL] - Represent a list of defs
 ///
 class ListInit : public TypedInit, public FoldingSetNode {
@@ -861,8 +783,7 @@
   ///
   virtual Init *resolveBitReference(Record &R, const RecordVal *RV,
                                     unsigned Bit) const {
-    assert(0 && "Illegal bit reference off list");
-    return 0;
+    llvm_unreachable("Illegal bit reference off list");
   }
=20
   /// resolveListElementReference - This method is used to implement
@@ -1058,9 +979,11 @@
 /// VarInit - 'Opcode' - Represent a reference to an entire variable objec=
t.
 ///
 class VarInit : public TypedInit {
-  std::string VarName;
+  Init *VarName;
=20
   explicit VarInit(const std::string &VN, RecTy *T)
+      : TypedInit(T), VarName(StringInit::get(VN)) {}
+  explicit VarInit(Init *VN, RecTy *T)
       : TypedInit(T), VarName(VN) {}
=20
   VarInit(const VarInit &Other);  // Do not define.
@@ -1074,7 +997,11 @@
     return Ty->convertValue(const_cast<VarInit *>(this));
   }
=20
-  const std::string &getName() const { return VarName; }
+  const std::string &getName() const;
+  Init *getNameInit() const { return VarName; }
+  std::string getNameInitAsString() const {
+    return getNameInit()->getAsUnquotedString();
+  }
=20
   virtual Init *resolveBitReference(Record &R, const RecordVal *RV,
                                     unsigned Bit) const;
@@ -1092,7 +1019,7 @@
   ///
   virtual Init *resolveReferences(Record &R, const RecordVal *RV) const;
=20
-  virtual std::string getAsString() const { return VarName; }
+  virtual std::string getAsString() const { return getName(); }
 };
=20
=20
@@ -1201,8 +1128,7 @@
   ///
   virtual Init *resolveBitReference(Record &R, const RecordVal *RV,
                                     unsigned Bit) const {
-    assert(0 && "Illegal bit reference off def");
-    return 0;
+    llvm_unreachable("Illegal bit reference off def");
   }
=20
   /// resolveListElementReference - This method is used to implement
@@ -1210,8 +1136,7 @@
   /// now, we return the resolved value, otherwise we return null.
   virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
                                             unsigned Elt) const {
-    assert(0 && "Illegal element reference off def");
-    return 0;
+    llvm_unreachable("Illegal element reference off def");
   }
 };
=20
@@ -1320,14 +1245,12 @@
=20
   virtual Init *resolveBitReference(Record &R, const RecordVal *RV,
                                     unsigned Bit) const {
-    assert(0 && "Illegal bit reference off dag");
-    return 0;
+    llvm_unreachable("Illegal bit reference off dag");
   }
=20
   virtual Init *resolveListElementReference(Record &R, const RecordVal *RV,
                                             unsigned Elt) const {
-    assert(0 && "Illegal element reference off dag");
-    return 0;
+    llvm_unreachable("Illegal element reference off dag");
   }
 };
=20
@@ -1345,6 +1268,10 @@
   RecordVal(const std::string &N, RecTy *T, unsigned P);
=20
   const std::string &getName() const;
+  const Init *getNameInit() const { return Name; }
+  std::string getNameInitAsString() const {
+    return getNameInit()->getAsUnquotedString();
+  }
=20
   unsigned getPrefix() const { return Prefix; }
   RecTy *getType() const { return Ty; }
@@ -1375,7 +1302,7 @@
   unsigned ID;
   Init *Name;
   SMLoc Loc;
-  std::vector<std::string> TemplateArgs;
+  std::vector<Init *> TemplateArgs;
   std::vector<RecordVal> Values;
   std::vector<Record*> SuperClasses;
=20
@@ -1384,13 +1311,21 @@
=20
   DefInit *TheInit;
=20
+  void init();
   void checkName();
=20
 public:
=20
   // Constructs a record.
   explicit Record(const std::string &N, SMLoc loc, RecordKeeper &records) :
-    ID(LastID++), Name(StringInit::get(N)), Loc(loc), TrackedRecords(recor=
ds), TheInit(0) {}
+    ID(LastID++), Name(StringInit::get(N)), Loc(loc), TrackedRecords(recor=
ds),
+      TheInit(0) {
+    init();
+  }
+  explicit Record(Init *N, SMLoc loc, RecordKeeper &records) :
+    ID(LastID++), Name(N), Loc(loc), TrackedRecords(records), TheInit(0) {
+    init();
+  }
   ~Record() {}
=20
=20
@@ -1400,6 +1335,13 @@
   unsigned getID() const { return ID; }
=20
   const std::string &getName() const;
+  Init *getNameInit() const {
+    return Name;
+  }
+  const std::string getNameInitAsString() const {
+    return getNameInit()->getAsUnquotedString();
+  }
+
   void setName(Init *Name);               // Also updates RecordKeeper.
   void setName(const std::string &Name);  // Also updates RecordKeeper.
=20
@@ -1408,46 +1350,69 @@
   /// get the corresponding DefInit.
   DefInit *getDefInit();
=20
-  const std::vector<std::string> &getTemplateArgs() const {
+  const std::vector<Init *> &getTemplateArgs() const {
     return TemplateArgs;
   }
   const std::vector<RecordVal> &getValues() const { return Values; }
   const std::vector<Record*>   &getSuperClasses() const { return SuperClas=
ses; }
=20
-  bool isTemplateArg(StringRef Name) const {
+  bool isTemplateArg(Init *Name) const {
     for (unsigned i =3D 0, e =3D TemplateArgs.size(); i !=3D e; ++i)
       if (TemplateArgs[i] =3D=3D Name) return true;
     return false;
   }
+  bool isTemplateArg(StringRef Name) const {
+    return isTemplateArg(StringInit::get(Name.str()));
+  }
=20
+  const RecordVal *getValue(const Init *Name) const {
+    for (unsigned i =3D 0, e =3D Values.size(); i !=3D e; ++i)
+      if (Values[i].getNameInit() =3D=3D Name) return &Values[i];
+    return 0;
+  }
   const RecordVal *getValue(StringRef Name) const {
+    return getValue(StringInit::get(Name));
+  }
+  RecordVal *getValue(const Init *Name) {
     for (unsigned i =3D 0, e =3D Values.size(); i !=3D e; ++i)
-      if (Values[i].getName() =3D=3D Name) return &Values[i];
+      if (Values[i].getNameInit() =3D=3D Name) return &Values[i];
     return 0;
   }
   RecordVal *getValue(StringRef Name) {
-    for (unsigned i =3D 0, e =3D Values.size(); i !=3D e; ++i)
-      if (Values[i].getName() =3D=3D Name) return &Values[i];
-    return 0;
+    return getValue(StringInit::get(Name));
   }
=20
-  void addTemplateArg(StringRef Name) {
+  void addTemplateArg(Init *Name) {
     assert(!isTemplateArg(Name) && "Template arg already defined!");
     TemplateArgs.push_back(Name);
   }
+  void addTemplateArg(StringRef Name) {
+    addTemplateArg(StringInit::get(Name.str()));
+  }
=20
   void addValue(const RecordVal &RV) {
-    assert(getValue(RV.getName()) =3D=3D 0 && "Value already added!");
+    assert(getValue(RV.getNameInit()) =3D=3D 0 && "Value already added!");
     Values.push_back(RV);
+    if (Values.size() > 1)
+      // Keep NAME at the end of the list.  It makes record dumps a
+      // bit prettier and allows TableGen tests to be written more
+      // naturally.  Tests can use CHECK-NEXT to look for Record
+      // fields they expect to see after a def.  They can't do that if
+      // NAME is the first Record field.
+      std::swap(Values[Values.size() - 2], Values[Values.size() - 1]);
+  }
+
+  void removeValue(Init *Name) {
+    for (unsigned i =3D 0, e =3D Values.size(); i !=3D e; ++i)
+      if (Values[i].getNameInit() =3D=3D Name) {
+        Values.erase(Values.begin()+i);
+        return;
+      }
+    llvm_unreachable("Cannot remove an entry that does not exist!");
   }
=20
   void removeValue(StringRef Name) {
-    for (unsigned i =3D 0, e =3D Values.size(); i !=3D e; ++i)
-      if (Values[i].getName() =3D=3D Name) {
-        Values.erase(Values.begin()+i);
-        return;
-      }
-    assert(0 && "Cannot remove an entry that does not exist!");
+    removeValue(StringInit::get(Name.str()));
   }
=20
   bool isSubClassOf(const Record *R) const {
@@ -1459,7 +1424,7 @@
=20
   bool isSubClassOf(StringRef Name) const {
     for (unsigned i =3D 0, e =3D SuperClasses.size(); i !=3D e; ++i)
-      if (SuperClasses[i]->getName() =3D=3D Name)
+      if (SuperClasses[i]->getNameInitAsString() =3D=3D Name)
         return true;
     return false;
   }
@@ -1553,12 +1518,6 @@
   /// the value is not the right type.
   ///
   DagInit *getValueAsDag(StringRef FieldName) const;
-
-  /// getValueAsCode - This method looks up the specified field and returns
-  /// its value as the string data in a CodeInit, throwing an exception if=
 the
-  /// field does not exist or if the value is not a code object.
-  ///
-  std::string getValueAsCode(StringRef FieldName) const;
 };
=20
 raw_ostream &operator<<(raw_ostream &OS, const Record &R);
@@ -1576,6 +1535,7 @@
=20
 class RecordKeeper {
   std::map<std::string, Record*> Classes, Defs;
+
 public:
   ~RecordKeeper() {
     for (std::map<std::string, Record*>::iterator I =3D Classes.begin(),
@@ -1598,12 +1558,12 @@
     return I =3D=3D Defs.end() ? 0 : I->second;
   }
   void addClass(Record *R) {
-    assert(getClass(R->getName()) =3D=3D 0 && "Class already exists!");
-    Classes.insert(std::make_pair(R->getName(), R));
+    assert(getClass(R->getNameInitAsString()) =3D=3D 0 && "Class already e=
xists!");
+    Classes.insert(std::make_pair(R->getNameInitAsString(), R));
   }
   void addDef(Record *R) {
-    assert(getDef(R->getName()) =3D=3D 0 && "Def already exists!");
-    Defs.insert(std::make_pair(R->getName(), R));
+    assert(getDef(R->getNameInitAsString()) =3D=3D 0 && "Def already exist=
s!");
+    Defs.insert(std::make_pair(R->getNameInitAsString(), R));
   }
=20
   /// removeClass - Remove, but do not delete, the specified record.
@@ -1650,6 +1610,16 @@
=20
 raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
=20
+/// QualifyName - Return an Init with a qualifier prefix referring
+/// to CurRec's name.
+Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
+                  Init *Name, const std::string &Scoper);
+
+/// QualifyName - Return an Init with a qualifier prefix referring
+/// to CurRec's name.
+Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
+                  const std::string &Name, const std::string &Scoper);
+
 } // End llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/TableGe=
n/TableGenAction.h
--- a/head/contrib/llvm/include/llvm/TableGen/TableGenAction.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/TableGen/TableGenAction.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -21,6 +21,7 @@
 class RecordKeeper;
=20
 class TableGenAction {
+  virtual void anchor();
 public:
   virtual ~TableGenAction() {}
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/TableGe=
n/TableGenBackend.h
--- a/head/contrib/llvm/include/llvm/TableGen/TableGenBackend.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/TableGen/TableGenBackend.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -16,7 +16,6 @@
 #define LLVM_TABLEGEN_TABLEGENBACKEND_H
=20
 #include "llvm/Support/raw_ostream.h"
-#include <string>
=20
 namespace llvm {
=20
@@ -24,6 +23,7 @@
 class RecordKeeper;
=20
 struct TableGenBackend {
+  virtual void anchor();
   virtual ~TableGenBackend() {}
=20
   // run - All TableGen backends should implement the run method, which sh=
ould
@@ -34,7 +34,7 @@
 public:   // Useful helper routines...
   /// EmitSourceFileHeader - Output a LLVM style file header to the specif=
ied
   /// ostream.
-  void EmitSourceFileHeader(const std::string &Desc, raw_ostream &OS) cons=
t;
+  void EmitSourceFileHeader(StringRef Desc, raw_ostream &OS) const;
=20
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
Mangler.h
--- a/head/contrib/llvm/include/llvm/Target/Mangler.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/Mangler.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -17,11 +17,9 @@
 #include "llvm/ADT/DenseMap.h"
=20
 namespace llvm {
-class StringRef;
 class Twine;
-class Value;
 class GlobalValue;
-template <typename T> class SmallVectorImpl;=20
+template <typename T> class SmallVectorImpl;
 class MCContext;
 class MCSymbol;
 class TargetData;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
Target.td
--- a/head/contrib/llvm/include/llvm/Target/Target.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/Target.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -22,8 +22,12 @@
 class RegisterClass; // Forward def
=20
 // SubRegIndex - Use instances of SubRegIndex to identify subregisters.
-class SubRegIndex {
+class SubRegIndex<list<SubRegIndex> comps =3D []> {
   string Namespace =3D "";
+
+  // ComposedOf - A list of two SubRegIndex instances, [A, B].
+  // This indicates that this SubRegIndex is the result of composing A and=
 B.
+  list<SubRegIndex> ComposedOf =3D comps;
 }
=20
 // RegAltNameIndex - The alternate name set to use for register operands of
@@ -83,9 +87,15 @@
   // CostPerUse - Additional cost of instructions using this register comp=
ared
   // to other registers in its class. The register allocator will try to
   // minimize the number of instructions using a register with a CostPerUs=
e.
-  // This is used by the x86-64 and ARM Thumb targets where some registers=20
+  // This is used by the x86-64 and ARM Thumb targets where some registers
   // require larger instruction encodings.
   int CostPerUse =3D 0;
+
+  // CoveredBySubRegs - When this bit is set, the value of this register is
+  // completely determined by the value of its sub-registers.  For example=
, the
+  // x86 register AX is covered by its sub-registers AL and AH, but EAX is=
 not
+  // covered by its sub-register AX.
+  bit CoveredBySubRegs =3D 0;
 }
=20
 // RegisterWithSubRegs - This can be used to define instances of Register =
which
@@ -194,12 +204,15 @@
 //
 // (decimate GPR, 2) - Pick every N'th element, starting with the first.
 //
+// (interleave A, B, ...) - Interleave the elements from each argument lis=
t.
+//
 // All of these operators work on ordered sets, not lists. That means
 // duplicates are removed from sub-expressions.
=20
 // Set operators. The rest is defined in TargetSelectionDAG.td.
 def sequence;
 def decimate;
+def interleave;
=20
 // RegisterTuples - Automatically generate super-registers by forming tupl=
es of
 // sub-registers. This is useful for modeling register sequence constraints
@@ -356,6 +369,15 @@
   // associated with them. Once we've migrated all of them over to true
   // pseudo-instructions that are lowered to real instructions prior to
   // the printer/emitter, we can remove this attribute and just use isPseu=
do.
+  //
+  // The intended use is:
+  // isPseudo: Does not have encoding information and should be expanded,
+  //   at the latest, during lowering to MCInst.
+  //
+  // isCodeGenOnly: Does have encoding information and can go through to t=
he
+  //   CodeEmitter unchanged, but duplicates a canonical instruction
+  //   definition's encoding and should be ignored when constructing the
+  //   assembler match tables.
   bit isCodeGenOnly =3D 0;
=20
   // Is this instruction a pseudo instruction for use by the assembler par=
ser.
@@ -414,7 +436,7 @@
 /// NoHonorSignDependentRounding - This predicate is true if support for
 /// sign-dependent-rounding is not enabled.
 def NoHonorSignDependentRounding
- : Predicate<"!HonorSignDependentRoundingFPMath()">;
+ : Predicate<"!TM.Options.HonorSignDependentRoundingFPMath()">;
=20
 class Requires<list<Predicate> preds> {
   list<Predicate> Predicates =3D preds;
@@ -679,6 +701,11 @@
   let neverHasSideEffects =3D 1;
   let isAsCheapAsAMove =3D 1;
 }
+def BUNDLE : Instruction {
+  let OutOperandList =3D (outs);
+  let InOperandList =3D (ins variable_ops);
+  let AsmString =3D "BUNDLE";
+}
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -698,7 +725,15 @@
   // function of the AsmParser class to call on every matched instruction.
   // This can be used to perform target specific instruction post-processi=
ng.
   string AsmParserInstCleanup  =3D "";
+}
+def DefaultAsmParser : AsmParser;
=20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// AsmParserVariant - Subtargets can have multiple different assembly pars=
ers=20
+// (e.g. AT&T vs Intel syntax on X86 for example). This class can be
+// implemented by targets to describe such variants.
+//
+class AsmParserVariant {
   // Variant - AsmParsers can be of multiple different variants.  Variants=
 are
   // used to support targets that need to parser multiple formats for the
   // assembly language.
@@ -715,7 +750,7 @@
   // purposes of matching.
   string RegisterPrefix =3D "";
 }
-def DefaultAsmParser : AsmParser;
+def DefaultAsmParserVariant : AsmParserVariant;
=20
 /// AssemblerPredicate - This is a Predicate that can be used when the ass=
embler
 /// matches instructions and aliases.
@@ -724,7 +759,20 @@
   string AssemblerCondString =3D cond;
 }
=20
-
+/// TokenAlias - This class allows targets to define assembler token
+/// operand aliases. That is, a token literal operand which is equivalent
+/// to another, canonical, token literal. For example, ARM allows:
+///   vmov.u32 s4, #0  -> vmov.i32, #0
+/// 'u32' is a more specific designator for the 32-bit integer type specif=
ier
+/// and is legal for any instruction which accepts 'i32' as a datatype suf=
fix.
+///   def : TokenAlias<".u32", ".i32">;
+///
+/// This works by marking the match class of 'From' as a subclass of the
+/// match class of 'To'.
+class TokenAlias<string From, string To> {
+  string FromToken =3D From;
+  string ToToken =3D To;
+}
=20
 /// MnemonicAlias - This class allows targets to define assembler mnemonic
 /// aliases.  This should be used when all forms of one mnemonic are accep=
ted
@@ -813,6 +861,10 @@
   // AssemblyParsers - The AsmParser instances available for this target.
   list<AsmParser> AssemblyParsers =3D [DefaultAsmParser];
=20
+  /// AssemblyParserVariants - The AsmParserVariant instances available fo=
r=20
+  /// this target.
+  list<AsmParserVariant> AssemblyParserVariants =3D [DefaultAsmParserVaria=
nt];
+
   // AssemblyWriters - The AsmWriter instances available for this target.
   list<AsmWriter> AssemblyWriters =3D [DefaultAsmWriter];
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetCallingConv.h
--- a/head/contrib/llvm/include/llvm/Target/TargetCallingConv.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetCallingConv.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -14,6 +14,10 @@
 #ifndef LLVM_TARGET_TARGETCALLINGCONV_H
 #define LLVM_TARGET_TARGETCALLINGCONV_H
=20
+#include "llvm/Support/DataTypes.h"
+#include "llvm/Support/MathExtras.h"
+#include <string>
+
 namespace llvm {
=20
 namespace ISD {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetCallingConv.td
--- a/head/contrib/llvm/include/llvm/Target/TargetCallingConv.td	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetCallingConv.td	Tue Apr 17=
 11:51:51 2012 +0300
@@ -133,3 +133,14 @@
 class CallingConv<list<CCAction> actions> {
   list<CCAction> Actions =3D actions;
 }
+
+/// CalleeSavedRegs - A list of callee saved registers for a given calling
+/// convention.  The order of registers is used by PrologEpilogInsertion w=
hen
+/// allocation stack slots for saved registers.
+///
+/// For each CalleeSavedRegs def, TableGen will emit a FOO_SaveList array =
for
+/// returning from getCalleeSavedRegs(), and a FOO_RegMask bit mask suitab=
le for
+/// returning from getCallPreservedMask().
+class CalleeSavedRegs<dag saves> {
+  dag SaveList =3D saves;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetData.h
--- a/head/contrib/llvm/include/llvm/Target/TargetData.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetData.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -44,7 +44,7 @@
   AGGREGATE_ALIGN =3D 'a',             ///< Aggregate alignment
   STACK_ALIGN =3D 's'                  ///< Stack objects alignment
 };
- =20
+
 /// Target alignment element.
 ///
 /// Stores the alignment data associated with a given alignment type (poin=
ter,
@@ -80,7 +80,7 @@
   unsigned      StackNaturalAlign;     ///< Stack natural alignment
=20
   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
- =20
+
   /// Alignments- Where the primitive type alignment data is stored.
   ///
   /// @sa init().
@@ -88,7 +88,7 @@
   /// pointers vs. 64-bit pointers by extending TargetAlignment, but for n=
ow,
   /// we don't.
   SmallVector<TargetAlignElem, 16> Alignments;
- =20
+
   /// InvalidAlignmentElem - This member is a signal that a requested alig=
nment
   /// type and bit width were not found in the SmallVector.
   static const TargetAlignElem InvalidAlignmentElem;
@@ -112,19 +112,30 @@
     return &align !=3D &InvalidAlignmentElem;
   }
=20
+  /// Initialise a TargetData object with default values, ensure that the
+  /// target data pass is registered.
+  void init();
+
 public:
   /// Default ctor.
   ///
   /// @note This has to exist, because this is a pass, but it should never=
 be
   /// used.
   TargetData();
- =20
+
   /// Constructs a TargetData from a specification string. See init().
   explicit TargetData(StringRef TargetDescription)
     : ImmutablePass(ID) {
-    init(TargetDescription);
+    std::string errMsg =3D parseSpecifier(TargetDescription, this);
+    assert(errMsg =3D=3D "" && "Invalid target data layout string.");
+    (void)errMsg;
   }
=20
+  /// Parses a target data specification string. Returns an error message
+  /// if the string is malformed, or the empty string on success. Optional=
ly
+  /// initialises a TargetData object if passed a non-null pointer.
+  static std::string parseSpecifier(StringRef TargetDescription, TargetDat=
a* td =3D 0);
+
   /// Initialize target data from properties stored in the module.
   explicit TargetData(const Module *M);
=20
@@ -141,9 +152,6 @@
=20
   ~TargetData();  // Not virtual, do not subclass this class
=20
-  //! Parse a target data layout string and initialize TargetData alignmen=
ts.
-  void init(StringRef TargetDescription);
-
   /// Target endianness...
   bool isLittleEndian() const { return LittleEndian; }
   bool isBigEndian() const { return !LittleEndian; }
@@ -152,7 +160,7 @@
   /// TargetData.  This representation is in the same format accepted by t=
he
   /// string constructor above.
   std::string getStringRepresentation() const;
- =20
+
   /// isLegalInteger - This function returns true if the specified type is
   /// known to be a native integer type supported by the CPU.  For example,
   /// i64 is not native on most 32-bit CPUs and i37 is not native on any k=
nown
@@ -166,7 +174,7 @@
         return true;
     return false;
   }
- =20
+
   bool isIllegalInteger(unsigned Width) const {
     return !isLegalInteger(Width);
   }
@@ -251,11 +259,11 @@
   /// getABITypeAlignment - Return the minimum ABI-required alignment for =
the
   /// specified type.
   unsigned getABITypeAlignment(Type *Ty) const;
- =20
+
   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignme=
nt for
   /// an integer type of the specified bitwidth.
   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
- =20
+
=20
   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
   /// for the specified type when it is part of a call frame.
@@ -305,7 +313,7 @@
     assert((Alignment & (Alignment-1)) =3D=3D 0 && "Alignment must be powe=
r of 2!");
     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
   }
- =20
+
   static char ID; // Pass identification, replacement for typeid
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetELFWriterInfo.h
--- a/head/contrib/llvm/include/llvm/Target/TargetELFWriterInfo.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetELFWriterInfo.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -15,9 +15,6 @@
 #define LLVM_TARGET_TARGETELFWRITERINFO_H
=20
 namespace llvm {
-  class Function;
-  class TargetData;
-  class TargetMachine;
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   //                          TargetELFWriterInfo
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetFrameLowering.h
--- a/head/contrib/llvm/include/llvm/Target/TargetFrameLowering.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetFrameLowering.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -15,8 +15,6 @@
 #define LLVM_TARGET_TARGETFRAMELOWERING_H
=20
 #include "llvm/CodeGen/MachineBasicBlock.h"
-#include "llvm/MC/MCDwarf.h"
-#include "llvm/ADT/ArrayRef.h"
=20
 #include <utility>
 #include <vector>
@@ -24,8 +22,6 @@
 namespace llvm {
   class CalleeSavedInfo;
   class MachineFunction;
-  class MachineBasicBlock;
-  class MachineMove;
   class RegScavenger;
=20
 /// Information about stack frame layout on the target.  It holds the dire=
ction
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetInstrInfo.h
--- a/head/contrib/llvm/include/llvm/Target/TargetInstrInfo.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetInstrInfo.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #define LLVM_TARGET_TARGETINSTRINFO_H
=20
 #include "llvm/MC/MCInstrInfo.h"
+#include "llvm/CodeGen/DFAPacketizer.h"
 #include "llvm/CodeGen/MachineFunction.h"
=20
 namespace llvm {
@@ -278,8 +279,7 @@
   /// This is only invoked in cases where AnalyzeBranch returns success. It
   /// returns the number of instructions that were removed.
   virtual unsigned RemoveBranch(MachineBasicBlock &MBB) const {
-    assert(0 && "Target didn't implement TargetInstrInfo::RemoveBranch!");
-    return 0;
+    llvm_unreachable("Target didn't implement TargetInstrInfo::RemoveBranc=
h!");
   }
=20
   /// InsertBranch - Insert branch code into the end of the specified
@@ -296,8 +296,7 @@
                                 MachineBasicBlock *FBB,
                                 const SmallVectorImpl<MachineOperand> &Con=
d,
                                 DebugLoc DL) const {
-    assert(0 && "Target didn't implement TargetInstrInfo::InsertBranch!");
-    return 0;
+    llvm_unreachable("Target didn't implement TargetInstrInfo::InsertBranc=
h!");
   }
=20
   /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everyth=
ing
@@ -353,12 +352,28 @@
     return false;
   }
=20
+  /// isProfitableToUnpredicate - Return true if it's profitable to unpred=
icate
+  /// one side of a 'diamond', i.e. two sides of if-else predicated on mut=
ually
+  /// exclusive predicates.
+  /// e.g.
+  ///   subeq  r0, r1, #1
+  ///   addne  r0, r1, #1
+  /// =3D>
+  ///   sub    r0, r1, #1
+  ///   addne  r0, r1, #1
+  ///
+  /// This may be profitable is conditional instructions are always execut=
ed.
+  virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB,
+                                         MachineBasicBlock &FMBB) const {
+    return false;
+  }
+
   /// copyPhysReg - Emit instructions to copy a pair of physical registers.
   virtual void copyPhysReg(MachineBasicBlock &MBB,
                            MachineBasicBlock::iterator MI, DebugLoc DL,
                            unsigned DestReg, unsigned SrcReg,
                            bool KillSrc) const {
-    assert(0 && "Target didn't implement TargetInstrInfo::copyPhysReg!");
+    llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg=
!");
   }
=20
   /// storeRegToStackSlot - Store the specified register of the given regi=
ster
@@ -371,7 +386,8 @@
                                    unsigned SrcReg, bool isKill, int Frame=
Index,
                                    const TargetRegisterClass *RC,
                                    const TargetRegisterInfo *TRI) const {
-  assert(0 && "Target didn't implement TargetInstrInfo::storeRegToStackSlo=
t!");
+    llvm_unreachable("Target didn't implement "
+                     "TargetInstrInfo::storeRegToStackSlot!");
   }
=20
   /// loadRegFromStackSlot - Load the specified register of the given regi=
ster
@@ -383,7 +399,8 @@
                                     unsigned DestReg, int FrameIndex,
                                     const TargetRegisterClass *RC,
                                     const TargetRegisterInfo *TRI) const {
-  assert(0 && "Target didn't implement TargetInstrInfo::loadRegFromStackSl=
ot!");
+    llvm_unreachable("Target didn't implement "
+                     "TargetInstrInfo::loadRegFromStackSlot!");
   }
=20
   /// expandPostRAPseudo - This function is called for all pseudo instruct=
ions
@@ -535,7 +552,7 @@
=20
   /// isUnpredicatedTerminator - Returns true if the instruction is a
   /// terminator instruction that has not been predicated.
-  virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
+  virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const =3D =
0;
=20
   /// PredicateInstruction - Convert the instruction into a predicated
   /// instruction. It returns true if the operation was successful.
@@ -646,7 +663,16 @@
=20
   virtual int getOperandLatency(const InstrItineraryData *ItinData,
                                 SDNode *DefNode, unsigned DefIdx,
-                                SDNode *UseNode, unsigned UseIdx) const;
+                                SDNode *UseNode, unsigned UseIdx) const =
=3D 0;
+
+  /// getOutputLatency - Compute and return the output dependency latency =
of a
+  /// a given pair of defs which both target the same register. This is us=
ually
+  /// one.
+  virtual unsigned getOutputLatency(const InstrItineraryData *ItinData,
+                                    const MachineInstr *DefMI, unsigned De=
fIdx,
+                                    const MachineInstr *DepMI) const {
+    return 1;
+  }
=20
   /// getInstrLatency - Compute the instruction latency of a given instruc=
tion.
   /// If the instruction has higher cost when predicated, it's returned via
@@ -656,7 +682,7 @@
                               unsigned *PredCost =3D 0) const;
=20
   virtual int getInstrLatency(const InstrItineraryData *ItinData,
-                              SDNode *Node) const;
+                              SDNode *Node) const =3D 0;
=20
   /// isHighLatencyDef - Return true if this opcode has high latency to its
   /// result.
@@ -718,6 +744,80 @@
   ///
   virtual void setExecutionDomain(MachineInstr *MI, unsigned Domain) const=
 {}
=20
+
+  /// getPartialRegUpdateClearance - Returns the preferred minimum clearan=
ce
+  /// before an instruction with an unwanted partial register update.
+  ///
+  /// Some instructions only write part of a register, and implicitly need=
 to
+  /// read the other parts of the register.  This may cause unwanted stalls
+  /// preventing otherwise unrelated instructions from executing in parall=
el in
+  /// an out-of-order CPU.
+  ///
+  /// For example, the x86 instruction cvtsi2ss writes its result to bits
+  /// [31:0] of the destination xmm register. Bits [127:32] are unaffected=
, so
+  /// the instruction needs to wait for the old value of the register to b=
ecome
+  /// available:
+  ///
+  ///   addps %xmm1, %xmm0
+  ///   movaps %xmm0, (%rax)
+  ///   cvtsi2ss %rbx, %xmm0
+  ///
+  /// In the code above, the cvtsi2ss instruction needs to wait for the ad=
dps
+  /// instruction before it can issue, even though the high bits of %xmm0
+  /// probably aren't needed.
+  ///
+  /// This hook returns the preferred clearance before MI, measured in
+  /// instructions.  Other defs of MI's operand OpNum are avoided in the l=
ast N
+  /// instructions before MI.  It should only return a positive value for
+  /// unwanted dependencies.  If the old bits of the defined register have
+  /// useful values, or if MI is determined to otherwise read the dependen=
cy,
+  /// the hook should return 0.
+  ///
+  /// The unwanted dependency may be handled by:
+  ///
+  /// 1. Allocating the same register for an MI def and use.  That makes t=
he
+  ///    unwanted dependency identical to a required dependency.
+  ///
+  /// 2. Allocating a register for the def that has no defs in the previou=
s N
+  ///    instructions.
+  ///
+  /// 3. Calling breakPartialRegDependency() with the same arguments.  This
+  ///    allows the target to insert a dependency breaking instruction.
+  ///
+  virtual unsigned
+  getPartialRegUpdateClearance(const MachineInstr *MI, unsigned OpNum,
+                               const TargetRegisterInfo *TRI) const {
+    // The default implementation returns 0 for no partial register depend=
ency.
+    return 0;
+  }
+
+  /// breakPartialRegDependency - Insert a dependency-breaking instruction
+  /// before MI to eliminate an unwanted dependency on OpNum.
+  ///
+  /// If it wasn't possible to avoid a def in the last N instructions befo=
re MI
+  /// (see getPartialRegUpdateClearance), this hook will be called to brea=
k the
+  /// unwanted dependency.
+  ///
+  /// On x86, an xorps instruction can be used as a dependency breaker:
+  ///
+  ///   addps %xmm1, %xmm0
+  ///   movaps %xmm0, (%rax)
+  ///   xorps %xmm0, %xmm0
+  ///   cvtsi2ss %rbx, %xmm0
+  ///
+  /// An <imp-kill> operand should be added to MI if an instruction was
+  /// inserted.  This ties the instructions together in the post-ra schedu=
ler.
+  ///
+  virtual void
+  breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned OpNum,
+                            const TargetRegisterInfo *TRI) const {}
+
+  /// Create machine specific model for scheduling.
+  virtual DFAPacketizer*
+    CreateTargetScheduleState(const TargetMachine*, const ScheduleDAG*) co=
nst {
+    return NULL;
+  }
+
 private:
   int CallFrameSetupOpcode, CallFrameDestroyOpcode;
 };
@@ -746,6 +846,7 @@
   virtual bool hasStoreToStackSlot(const MachineInstr *MI,
                                    const MachineMemOperand *&MMO,
                                    int &FrameIndex) const;
+  virtual bool isUnpredicatedTerminator(const MachineInstr *MI) const;
   virtual bool PredicateInstruction(MachineInstr *MI,
                             const SmallVectorImpl<MachineOperand> &Pred) c=
onst;
   virtual void reMaterialize(MachineBasicBlock &MBB,
@@ -761,6 +862,13 @@
   virtual bool isSchedulingBoundary(const MachineInstr *MI,
                                     const MachineBasicBlock *MBB,
                                     const MachineFunction &MF) const;
+  using TargetInstrInfo::getOperandLatency;
+  virtual int getOperandLatency(const InstrItineraryData *ItinData,
+                                SDNode *DefNode, unsigned DefIdx,
+                                SDNode *UseNode, unsigned UseIdx) const;
+  using TargetInstrInfo::getInstrLatency;
+  virtual int getInstrLatency(const InstrItineraryData *ItinData,
+                              SDNode *Node) const;
=20
   bool usePreRAHazardRecognizer() const;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetJITInfo.h
--- a/head/contrib/llvm/include/llvm/Target/TargetJITInfo.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetJITInfo.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -17,9 +17,9 @@
 #ifndef LLVM_TARGET_TARGETJITINFO_H
 #define LLVM_TARGET_TARGETJITINFO_H
=20
-#include <cassert>
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/DataTypes.h"
+#include <cassert>
=20
 namespace llvm {
   class Function;
@@ -30,6 +30,7 @@
   /// TargetJITInfo - Target specific information required by the Just-In-=
Time
   /// code generator.
   class TargetJITInfo {
+    virtual void anchor();
   public:
     virtual ~TargetJITInfo() {}
=20
@@ -45,8 +46,8 @@
     /// ptr.
     virtual void *emitGlobalValueIndirectSym(const GlobalValue* GV, void *=
ptr,
                                              JITCodeEmitter &JCE) {
-      assert(0 && "This target doesn't implement emitGlobalValueIndirectSy=
m!");
-      return 0;
+      llvm_unreachable("This target doesn't implement "
+                       "emitGlobalValueIndirectSym!");
     }
=20
     /// Records the required size and alignment for a call stub in bytes.
@@ -57,8 +58,6 @@
     /// Returns the maximum size and alignment for a call stub on this tar=
get.
     virtual StubLayout getStubLayout() {
       llvm_unreachable("This target doesn't implement getStubLayout!");
-      StubLayout Result =3D {0, 0};
-      return Result;
     }
=20
     /// emitFunctionStub - Use the specified JITCodeEmitter object to emit=
 a
@@ -68,15 +67,13 @@
     /// aligned from the address the JCE was set up to emit at.
     virtual void *emitFunctionStub(const Function* F, void *Target,
                                    JITCodeEmitter &JCE) {
-      assert(0 && "This target doesn't implement emitFunctionStub!");
-      return 0;
+      llvm_unreachable("This target doesn't implement emitFunctionStub!");
     }
=20
     /// getPICJumpTableEntry - Returns the value of the jumptable entry fo=
r the
     /// specific basic block.
     virtual uintptr_t getPICJumpTableEntry(uintptr_t BB, uintptr_t JTBase)=
 {
-      assert(0 && "This target doesn't implement getPICJumpTableEntry!");
-      return 0;
+      llvm_unreachable("This target doesn't implement getPICJumpTableEntry=
!");
     }
=20
     /// LazyResolverFn - This typedef is used to represent the function th=
at
@@ -97,8 +94,7 @@
     /// function, and giving the JIT the target function used to do the la=
zy
     /// resolving.
     virtual LazyResolverFn getLazyResolverFunction(JITCompilerFn) {
-      assert(0 && "Not implemented for this target!");
-      return 0;
+      llvm_unreachable("Not implemented for this target!");
     }
=20
     /// relocate - Before the JIT can run a block of code that has been em=
itted,
@@ -114,8 +110,7 @@
     /// handling thread local variables. This method returns a value only
     /// meaningful to the target.
     virtual char* allocateThreadLocalMemory(size_t size) {
-      assert(0 && "This target does not implement thread local storage!");
-      return 0;
+      llvm_unreachable("This target does not implement thread local storag=
e!");
     }
=20
     /// needsGOT - Allows a target to specify that it would like the
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetLibraryInfo.h
--- a/head/contrib/llvm/include/llvm/Target/TargetLibraryInfo.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetLibraryInfo.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -11,33 +11,204 @@
 #define LLVM_TARGET_TARGETLIBRARYINFO_H
=20
 #include "llvm/Pass.h"
+#include "llvm/ADT/DenseMap.h"
=20
 namespace llvm {
   class Triple;
=20
   namespace LibFunc {
     enum Func {
+      /// double acos(double x);
+      acos,
+      /// long double acosl(long double x);
+      acosl,
+      /// float acosf(float x);
+      acosf,
+      /// double asin(double x);
+      asin,
+      /// long double asinl(long double x);
+      asinl,
+      /// float asinf(float x);
+      asinf,
+      /// double atan(double x);
+      atan,
+      /// long double atanl(long double x);
+      atanl,
+      /// float atanf(float x);
+      atanf,
+      /// double atan2(double y, double x);
+      atan2,
+      /// long double atan2l(long double y, long double x);
+      atan2l,
+      /// float atan2f(float y, float x);
+      atan2f,
+      /// double ceil(double x);
+      ceil,
+      /// long double ceill(long double x);
+      ceill,
+      /// float ceilf(float x);
+      ceilf,
+      /// double copysign(double x, double y);
+      copysign,
+      /// float copysignf(float x, float y);
+      copysignf,
+      /// long double copysignl(long double x, long double y);
+      copysignl,
+      /// double cos(double x);
+      cos,
+      /// long double cosl(long double x);
+      cosl,
+      /// float cosf(float x);
+      cosf,
+      /// double cosh(double x);
+      cosh,
+      /// long double coshl(long double x);
+      coshl,
+      /// float coshf(float x);
+      coshf,
+      /// double exp(double x);
+      exp,
+      /// long double expl(long double x);
+      expl,
+      /// float expf(float x);
+      expf,
+      /// double exp2(double x);
+      exp2,
+      /// long double exp2l(long double x);
+      exp2l,
+      /// float exp2f(float x);
+      exp2f,
+      /// double expm1(double x);
+      expm1,
+      /// long double expm1l(long double x);
+      expm1l,
+      /// float expm1f(float x);
+      expl1f,
+      /// double fabs(double x);
+      fabs,
+      /// long double fabsl(long double x);
+      fabsl,
+      /// float fabsf(float x);
+      fabsf,
+      /// double floor(double x);
+      floor,
+      /// long double floorl(long double x);
+      floorl,
+      /// float floorf(float x);
+      floorf,
+      /// int fiprintf(FILE *stream, const char *format, ...);
+      fiprintf,
+      /// double fmod(double x, double y);
+      fmod,
+      /// long double fmodl(long double x, long double y);
+      fmodl,
+      /// float fmodf(float x, float y);
+      fmodf,
+      /// int fputs(const char *s, FILE *stream);
+      fputs,
+      /// size_t fwrite(const void *ptr, size_t size, size_t nitems,
+      /// FILE *stream);
+      fwrite,
+      /// int iprintf(const char *format, ...);
+      iprintf,
+      /// double log(double x);
+      log,
+      /// long double logl(long double x);
+      logl,
+      /// float logf(float x);
+      logf,
+      /// double log2(double x);
+      log2,
+      /// double long double log2l(long double x);
+      log2l,
+      /// float log2f(float x);
+      log2f,
+      /// double log10(double x);
+      log10,
+      /// long double log10l(long double x);
+      log10l,
+      /// float log10f(float x);
+      log10f,
+      /// double log1p(double x);
+      log1p,
+      /// long double log1pl(long double x);
+      log1pl,
+      /// float log1pf(float x);
+      log1pf,
+      /// void *memcpy(void *s1, const void *s2, size_t n);
+      memcpy,
+      /// void *memmove(void *s1, const void *s2, size_t n);
+      memmove,
       /// void *memset(void *b, int c, size_t len);
       memset,
-     =20
-      // void *memcpy(void *s1, const void *s2, size_t n);
-      memcpy,
-     =20
-      // void *memmove(void *s1, const void *s2, size_t n);
-      memmove,
-     =20
       /// void memset_pattern16(void *b, const void *pattern16, size_t len=
);
       memset_pattern16,
-     =20
-      /// int iprintf(const char *format, ...);
-      iprintf,
-     =20
+      /// double nearbyint(double x);
+      nearbyint,
+      /// float nearbyintf(float x);
+      nearbyintf,
+      /// long double nearbyintl(long double x);
+      nearbyintl,
+      /// double pow(double x, double y);
+      pow,
+      /// float powf(float x, float y);
+      powf,
+      /// long double powl(long double x, long double y);
+      powl,
+      /// double rint(double x);
+      rint,
+      /// float rintf(float x);
+      rintf,
+      /// long dobule rintl(long double x);
+      rintl,
+      /// double sin(double x);
+      sin,
+      /// long double sinl(long double x);
+      sinl,
+      /// float sinf(float x);
+      sinf,
+      /// double sinh(double x);
+      sinh,
+      /// long double sinhl(long double x);
+      sinhl,
+      /// float sinhf(float x);
+      sinhf,
       /// int siprintf(char *str, const char *format, ...);
       siprintf,
-     =20
-      /// int fiprintf(FILE *stream, const char *format, ...);
-      fiprintf,
-     =20
+      /// double sqrt(double x);
+      sqrt,
+      /// long double sqrtl(long double x);
+      sqrtl,
+      /// float sqrtf(float x);
+      sqrtf,
+      /// double tan(double x);
+      tan,
+      /// long double tanl(long double x);
+      tanl,
+      /// float tanf(float x);
+      tanf,
+      /// double tanh(double x);
+      tanh,
+      /// long double tanhl(long double x);
+      tanhl,
+      /// float tanhf(float x);
+      tanhf,
+      /// double trunc(double x);
+      trunc,
+      /// float truncf(float x);
+      truncf,
+      /// long double truncl(long double x);
+      truncl,
+      /// int __cxa_atexit(void (*f)(void *), void *p, void *d);
+      cxa_atexit,
+      /// void __cxa_guard_abort(guard_t *guard);
+      /// guard_t is int64_t in Itanium ABI or int32_t on ARM eabi.
+      cxa_guard_abort,     =20
+      /// int __cxa_guard_acquire(guard_t *guard);
+      cxa_guard_acquire,
+      /// void __cxa_guard_release(guard_t *guard);
+      cxa_guard_release,
+
       NumLibFuncs
     };
   }
@@ -46,7 +217,24 @@
 /// library functions are available for the current target, and allows a
 /// frontend to disable optimizations through -fno-builtin etc.
 class TargetLibraryInfo : public ImmutablePass {
-  unsigned char AvailableArray[(LibFunc::NumLibFuncs+7)/8];
+  virtual void anchor();
+  unsigned char AvailableArray[(LibFunc::NumLibFuncs+3)/4];
+  llvm::DenseMap<unsigned, std::string> CustomNames;
+  static const char* StandardNames[LibFunc::NumLibFuncs];
+
+  enum AvailabilityState {
+    StandardName =3D 3, // (memset to all ones)
+    CustomName =3D 1,
+    Unavailable =3D 0  // (memset to all zeros)
+  };
+  void setState(LibFunc::Func F, AvailabilityState State) {
+    AvailableArray[F/4] &=3D ~(3 << 2*(F&3));
+    AvailableArray[F/4] |=3D State << 2*(F&3);
+  }
+  AvailabilityState getState(LibFunc::Func F) const {
+    return static_cast<AvailabilityState>((AvailableArray[F/4] >> 2*(F&3))=
 & 3);
+  }
+
 public:
   static char ID;
   TargetLibraryInfo();
@@ -56,19 +244,39 @@
   /// has - This function is used by optimizations that want to match on o=
r form
   /// a given library function.
   bool has(LibFunc::Func F) const {
-    return (AvailableArray[F/8] & (1 << (F&7))) !=3D 0;
+    return getState(F) !=3D Unavailable;
+  }
+
+  StringRef getName(LibFunc::Func F) const {
+    AvailabilityState State =3D getState(F);
+    if (State =3D=3D Unavailable)
+      return StringRef();
+    if (State =3D=3D StandardName)
+      return StandardNames[F];
+    assert(State =3D=3D CustomName);
+    return CustomNames.find(F)->second;
   }
=20
   /// setUnavailable - this can be used by whatever sets up TargetLibraryI=
nfo to
   /// ban use of specific library functions.
   void setUnavailable(LibFunc::Func F) {
-    AvailableArray[F/8] &=3D ~(1 << (F&7));
+    setState(F, Unavailable);
   }
=20
   void setAvailable(LibFunc::Func F) {
-    AvailableArray[F/8] |=3D 1 << (F&7);
+    setState(F, StandardName);
   }
- =20
+
+  void setAvailableWithName(LibFunc::Func F, StringRef Name) {
+    if (StandardNames[F] !=3D Name) {
+      setState(F, CustomName);
+      CustomNames[F] =3D Name;
+      assert(CustomNames.find(F) !=3D CustomNames.end());
+    } else {
+      setState(F, StandardName);
+    }
+  }
+
   /// disableAllFunctions - This disables all builtins, which is used for
   /// options like -fno-builtin.
   void disableAllFunctions();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetLowering.h
--- a/head/contrib/llvm/include/llvm/Target/TargetLowering.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetLowering.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -25,7 +25,6 @@
 #include "llvm/CallingConv.h"
 #include "llvm/InlineAsm.h"
 #include "llvm/Attributes.h"
-#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/CodeGen/SelectionDAGNodes.h"
 #include "llvm/CodeGen/RuntimeLibcalls.h"
 #include "llvm/Support/DebugLoc.h"
@@ -36,41 +35,34 @@
 #include <vector>
=20
 namespace llvm {
-  class AllocaInst;
-  class APFloat;
   class CallInst;
   class CCState;
-  class Function;
   class FastISel;
   class FunctionLoweringInfo;
   class ImmutableCallSite;
+  class IntrinsicInst;
   class MachineBasicBlock;
   class MachineFunction;
-  class MachineFrameInfo;
   class MachineInstr;
   class MachineJumpTableInfo;
   class MCContext;
   class MCExpr;
-  class SDNode;
-  class SDValue;
-  class SelectionDAG;
   template<typename T> class SmallVectorImpl;
   class TargetData;
-  class TargetMachine;
   class TargetRegisterClass;
   class TargetLoweringObjectFile;
   class Value;
=20
-  // FIXME: should this be here?
-  namespace TLSModel {
-    enum Model {
-      GeneralDynamic,
-      LocalDynamic,
-      InitialExec,
-      LocalExec
+  namespace Sched {
+    enum Preference {
+      None,             // No preference
+      Source,           // Follow source order.
+      RegPressure,      // Scheduling for lowest register pressure.
+      Hybrid,           // Scheduling for both latency and register pressu=
re.
+      ILP,              // Scheduling for ILP in low register pressure mod=
e.
+      VLIW              // Scheduling for VLIW targets.
     };
   }
-  TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc);
=20
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -94,7 +86,7 @@
     Custom      // Use the LowerOperation hook to implement custom lowerin=
g.
   };
=20
-  /// LegalizeAction - This enum indicates whether a types are legal for a
+  /// LegalizeTypeAction - This enum indicates whether a types are legal f=
or a
   /// target, and if not, what action should be used to make them valid.
   enum LegalizeTypeAction {
     TypeLegal,           // The target natively supports this type.
@@ -115,8 +107,6 @@
=20
   static ISD::NodeType getExtendForContent(BooleanContent Content) {
     switch (Content) {
-    default:
-      assert(false && "Unknown BooleanContent!");
     case UndefinedBooleanContent:
       // Extend by adding rubbish bits.
       return ISD::ANY_EXTEND;
@@ -127,6 +117,7 @@
       // Extend by copying the sign bit.
       return ISD::SIGN_EXTEND;
     }
+    llvm_unreachable("Invalid content kind");
   }
=20
   /// NOTE: The constructor takes ownership of TLOF.
@@ -199,9 +190,9 @@
=20
   /// getRegClassFor - Return the register class that should be used for t=
he
   /// specified value type.
-  virtual TargetRegisterClass *getRegClassFor(EVT VT) const {
+  virtual const TargetRegisterClass *getRegClassFor(EVT VT) const {
     assert(VT.isSimple() && "getRegClassFor called on illegal type!");
-    TargetRegisterClass *RC =3D RegClassForVT[VT.getSimpleVT().SimpleTy];
+    const TargetRegisterClass *RC =3D RegClassForVT[VT.getSimpleVT().Simpl=
eTy];
     assert(RC && "This value type is not natively supported!");
     return RC;
   }
@@ -292,11 +283,9 @@
         VT =3D getTypeToTransformTo(Context, VT);
         break;
       default:
-        assert(false && "Type is not legal nor is it to be expanded!");
-        return VT;
+        llvm_unreachable("Type is not legal nor is it to be expanded!");
       }
     }
-    return VT;
   }
=20
   /// getVectorTypeBreakdown - Vector types are broken down into some numb=
er of
@@ -520,8 +509,19 @@
   /// AllowUnknown is true, this will return MVT::Other for types with no =
EVT
   /// counterpart (e.g. structs), otherwise it will assert.
   EVT getValueType(Type *Ty, bool AllowUnknown =3D false) const {
-    EVT VT =3D EVT::getEVT(Ty, AllowUnknown);
-    return VT =3D=3D MVT::iPTR ? PointerTy : VT;
+    // Lower scalar pointers to native pointer types.
+    if (Ty->isPointerTy()) return PointerTy;
+
+    if (Ty->isVectorTy()) {
+      VectorType *VTy =3D cast<VectorType>(Ty);
+      Type *Elm =3D VTy->getElementType();
+      // Lower vectors of pointers to native pointer types.
+      if (Elm->isPointerTy())=20
+        Elm =3D EVT(PointerTy).getTypeForEVT(Ty->getContext());
+      return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
+                       VTy->getNumElements());
+    }
+    return EVT::getEVT(Ty, AllowUnknown);
   }
=20
   /// getByValTypeAlignment - Return the desired alignment for ByVal aggre=
gate
@@ -554,8 +554,7 @@
     if (VT.isInteger()) {
       return getRegisterType(Context, getTypeToTransformTo(Context, VT));
     }
-    assert(0 && "Unsupported extended type!");
-    return EVT(MVT::Other); // Not reached
+    llvm_unreachable("Unsupported extended type!");
   }
=20
   /// getNumRegisters - Return the number of registers that this ValueType=
 will
@@ -580,8 +579,7 @@
       unsigned RegWidth =3D getRegisterType(Context, VT).getSizeInBits();
       return (BitWidth + RegWidth - 1) / RegWidth;
     }
-    assert(0 && "Unsupported extended type!");
-    return 0; // Not reached
+    llvm_unreachable("Unsupported extended type!");
   }
=20
   /// ShouldShrinkFPConstant - If true, then instruction selection should
@@ -646,7 +644,7 @@
   /// alignment can satisfy any constraint. Similarly if SrcAlign is zero =
it
   /// means there isn't a need to check it against alignment requirement,
   /// probably because the source does not need to be loaded. If
-  /// 'NonScalarIntSafe' is true, that means it's safe to return a
+  /// 'IsZeroVal' is true, that means it's safe to return a
   /// non-scalar-integer type, e.g. empty string source, constant, or load=
ed
   /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
   /// constant so it does not need to be loaded.
@@ -654,7 +652,7 @@
   /// target-independent logic.
   virtual EVT getOptimalMemOpType(uint64_t /*Size*/,
                                   unsigned /*DstAlign*/, unsigned /*SrcAli=
gn*/,
-                                  bool /*NonScalarIntSafe*/,
+                                  bool /*IsZeroVal*/,
                                   bool /*MemcpyStrSrc*/,
                                   MachineFunction &/*MF*/) const {
     return MVT::Other;
@@ -679,10 +677,10 @@
     return StackPointerRegisterToSaveRestore;
   }
=20
-  /// getExceptionAddressRegister - If a physical register, this returns
+  /// getExceptionPointerRegister - If a physical register, this returns
   /// the register that receives the exception address on entry to a landi=
ng
   /// pad.
-  unsigned getExceptionAddressRegister() const {
+  unsigned getExceptionPointerRegister() const {
     return ExceptionPointerRegister;
   }
=20
@@ -772,8 +770,7 @@
   LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
                             const MachineBasicBlock * /*MBB*/, unsigned /*=
uid*/,
                             MCContext &/*Ctx*/) const {
-    assert(0 && "Need to implement this hook if target has custom JTIs");
-    return 0;
+    llvm_unreachable("Need to implement this hook if target has custom JTI=
s");
   }
=20
   /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
@@ -865,7 +862,6 @@
   /// Mask are known to be either zero or one and return them in the
   /// KnownZero/KnownOne bitsets.
   virtual void computeMaskedBitsForTargetNode(const SDValue Op,
-                                              const APInt &Mask,
                                               APInt &KnownZero,
                                               APInt &KnownOne,
                                               const SelectionDAG &DAG,
@@ -1035,7 +1031,7 @@
   /// addRegisterClass - Add the specified register class as an available
   /// regclass for the specified value type.  This indicates the selector =
can
   /// handle values of that class natively.
-  void addRegisterClass(EVT VT, TargetRegisterClass *RC) {
+  void addRegisterClass(EVT VT, const TargetRegisterClass *RC) {
     assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassFo=
rVT));
     AvailableRegClasses.push_back(std::make_pair(VT, RC));
     RegClassForVT[VT.getSimpleVT().SimpleTy] =3D RC;
@@ -1141,26 +1137,28 @@
     JumpBufAlignment =3D Align;
   }
=20
-  /// setMinFunctionAlignment - Set the target's minimum function alignmen=
t.
+  /// setMinFunctionAlignment - Set the target's minimum function alignmen=
t (in
+  /// log2(bytes))
   void setMinFunctionAlignment(unsigned Align) {
     MinFunctionAlignment =3D Align;
   }
=20
   /// setPrefFunctionAlignment - Set the target's preferred function align=
ment.
   /// This should be set if there is a performance benefit to
-  /// higher-than-minimum alignment
+  /// higher-than-minimum alignment (in log2(bytes))
   void setPrefFunctionAlignment(unsigned Align) {
     PrefFunctionAlignment =3D Align;
   }
=20
   /// setPrefLoopAlignment - Set the target's preferred loop alignment. De=
fault
   /// alignment is zero, it means the target does not care about loop alig=
nment.
+  /// The alignment is specified in log2(bytes).
   void setPrefLoopAlignment(unsigned Align) {
     PrefLoopAlignment =3D Align;
   }
=20
   /// setMinStackArgumentAlignment - Set the minimum stack alignment of an
-  /// argument.
+  /// argument (in log2(bytes)).
   void setMinStackArgumentAlignment(unsigned Align) {
     MinStackArgumentAlignment =3D Align;
   }
@@ -1196,8 +1194,7 @@
                          const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
                          DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
                          SmallVectorImpl<SDValue> &/*InVals*/) const {
-    assert(0 && "Not Implemented");
-    return SDValue();    // this is here to silence compiler errors
+    llvm_unreachable("Not Implemented");
   }
=20
   /// LowerCallTo - This function lowers an abstract call to a function in=
to an
@@ -1224,7 +1221,8 @@
   LowerCallTo(SDValue Chain, Type *RetTy, bool RetSExt, bool RetZExt,
               bool isVarArg, bool isInreg, unsigned NumFixedArgs,
               CallingConv::ID CallConv, bool isTailCall,
-              bool isReturnValueUsed, SDValue Callee, ArgListTy &Args,
+              bool doesNotRet, bool isReturnValueUsed,
+              SDValue Callee, ArgListTy &Args,
               SelectionDAG &DAG, DebugLoc dl) const;
=20
   /// LowerCall - This hook must be implemented to lower calls into the
@@ -1236,14 +1234,13 @@
   virtual SDValue
     LowerCall(SDValue /*Chain*/, SDValue /*Callee*/,
               CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
-              bool &/*isTailCall*/,
+              bool /*doesNotRet*/, bool &/*isTailCall*/,
               const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
               const SmallVectorImpl<SDValue> &/*OutVals*/,
               const SmallVectorImpl<ISD::InputArg> &/*Ins*/,
               DebugLoc /*dl*/, SelectionDAG &/*DAG*/,
               SmallVectorImpl<SDValue> &/*InVals*/) const {
-    assert(0 && "Not Implemented");
-    return SDValue();    // this is here to silence compiler errors
+    llvm_unreachable("Not Implemented");
   }
=20
   /// HandleByVal - Target-specific cleanup for formal ByVal parameters.
@@ -1273,14 +1270,15 @@
                 const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
                 const SmallVectorImpl<SDValue> &/*OutVals*/,
                 DebugLoc /*dl*/, SelectionDAG &/*DAG*/) const {
-    assert(0 && "Not Implemented");
-    return SDValue();    // this is here to silence compiler errors
+    llvm_unreachable("Not Implemented");
   }
=20
   /// isUsedByReturnOnly - Return true if result of the specified node is =
used
-  /// by a return node only. This is used to determine whether it is possi=
ble
+  /// by a return node only. It also compute and return the input chain fo=
r the
+  /// tail call.
+  /// This is used to determine whether it is possible
   /// to codegen a libcall as tail call at legalization time.
-  virtual bool isUsedByReturnOnly(SDNode *) const {
+  virtual bool isUsedByReturnOnly(SDNode *, SDValue &Chain) const {
     return false;
   }
=20
@@ -1339,7 +1337,7 @@
   virtual void ReplaceNodeResults(SDNode * /*N*/,
                                   SmallVectorImpl<SDValue> &/*Results*/,
                                   SelectionDAG &/*DAG*/) const {
-    assert(0 && "ReplaceNodeResults not implemented for this target!");
+    llvm_unreachable("ReplaceNodeResults not implemented for this target!"=
);
   }
=20
   /// getTargetNodeName() - This method returns the name of a target speci=
fic
@@ -1531,6 +1529,17 @@
     AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {}
   };
=20
+  /// GetAddrModeArguments - CodeGenPrepare sinks address calculations int=
o the
+  /// same BB as Load/Store instructions reading the address.  This allows=
 as
+  /// much computation as possible to be done in the address mode for that
+  /// operand.  This hook lets targets also pass back when this should be =
done
+  /// on intrinsics which load/store.
+  virtual bool GetAddrModeArguments(IntrinsicInst *I,
+                                    SmallVectorImpl<Value*> &Ops,
+                                    Type *&AccessTy) const {
+    return false;
+  }
+
   /// isLegalAddressingMode - Return true if the addressing mode represent=
ed by
   /// AM is legal for this target, for a load/store of the specified type.
   /// The type may be VoidTy, in which case only return true if the addres=
sing
@@ -1581,6 +1590,18 @@
     return false;
   }
=20
+  /// isFNegFree - Return true if an fneg operation is free to the point w=
here
+  /// it is never worthwhile to replace it with a bitwise operation.
+  virtual bool isFNegFree(EVT) const {
+    return false;
+  }
+
+  /// isFAbsFree - Return true if an fneg operation is free to the point w=
here
+  /// it is never worthwhile to replace it with a bitwise operation.
+  virtual bool isFAbsFree(EVT) const {
+    return false;
+  }
+
   /// isNarrowingProfitable - Return true if it's profitable to narrow
   /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow
   /// from i32 to i8 but not from i32 to i16.
@@ -1593,9 +1614,9 @@
   //
   SDValue BuildExactSDIV(SDValue Op1, SDValue Op2, DebugLoc dl,
                          SelectionDAG &DAG) const;
-  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG,
+  SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
                       std::vector<SDNode*>* Created) const;
-  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG,
+  SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
                       std::vector<SDNode*>* Created) const;
=20
=20
@@ -1753,7 +1774,7 @@
=20
   /// RegClassForVT - This indicates the default register class to use for
   /// each ValueType the target supports natively.
-  TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
+  const TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE];
   unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE];
   EVT RegisterTypeForVT[MVT::LAST_VALUETYPE];
=20
@@ -1925,12 +1946,9 @@
     // Vectors with illegal element types are expanded.
     EVT NVT =3D EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements()=
 / 2);
     return LegalizeKind(TypeSplitVector, NVT);
-
-    assert(false && "Unable to handle this kind of vector type");
-    return LegalizeKind(TypeLegal, VT);
   }
=20
-  std::vector<std::pair<EVT, TargetRegisterClass*> > AvailableRegClasses;
+  std::vector<std::pair<EVT, const TargetRegisterClass*> > AvailableRegCla=
sses;
=20
   /// TargetDAGCombineArray - Targets can specify ISD nodes that they would
   /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(=
),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetLoweringObjectFile.h
--- a/head/contrib/llvm/include/llvm/Target/TargetLoweringObjectFile.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetLoweringObjectFile.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -15,18 +15,17 @@
 #ifndef LLVM_TARGET_TARGETLOWERINGOBJECTFILE_H
 #define LLVM_TARGET_TARGETLOWERINGOBJECTFILE_H
=20
-#include "llvm/ADT/StringRef.h"
+#include "llvm/Module.h"
 #include "llvm/MC/MCObjectFileInfo.h"
 #include "llvm/MC/SectionKind.h"
+#include "llvm/ADT/ArrayRef.h"
=20
 namespace llvm {
   class MachineModuleInfo;
   class Mangler;
-  class MCAsmInfo;
   class MCContext;
   class MCExpr;
   class MCSection;
-  class MCSectionMachO;
   class MCSymbol;
   class MCStreamer;
   class GlobalValue;
@@ -53,7 +52,13 @@
   virtual void emitPersonalityValue(MCStreamer &Streamer,
                                     const TargetMachine &TM,
                                     const MCSymbol *Sym) const;
- =20
+
+  /// emitModuleFlags - Emit the module flags that the platform cares abou=
t.
+  virtual void emitModuleFlags(MCStreamer &,
+                               ArrayRef<Module::ModuleFlagEntry>,
+                               Mangler *, const TargetMachine &) const {
+  }
+
   /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively
   /// decide not to emit the UsedDirective for some symbols in llvm.used.
   /// FIXME: REMOVE this (rdar://7071300)
@@ -86,9 +91,7 @@
                                     const TargetMachine &TM) const {
     return SectionForGlobal(GV, getKindForGlobal(GV, TM), Mang, TM);
   }
- =20
- =20
- =20
+
   /// getExplicitSectionGlobal - Targets should implement this method to a=
ssign
   /// a section to globals with an explicit section specfied.  The
   /// implementation of this method can assume that GV->hasSection() is tr=
ue.
@@ -121,7 +124,18 @@
   const MCExpr *
   getExprForDwarfReference(const MCSymbol *Sym, unsigned Encoding,
                            MCStreamer &Streamer) const;
- =20
+
+  virtual const MCSection *
+  getStaticCtorSection(unsigned Priority =3D 65535) const {
+    (void)Priority;
+    return StaticCtorSection;
+  }
+  virtual const MCSection *
+  getStaticDtorSection(unsigned Priority =3D 65535) const {
+    (void)Priority;
+    return StaticDtorSection;
+  }
+
 protected:
   virtual const MCSection *
   SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetMachine.h
--- a/head/contrib/llvm/include/llvm/Target/TargetMachine.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetMachine.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -14,7 +14,8 @@
 #ifndef LLVM_TARGET_TARGETMACHINE_H
 #define LLVM_TARGET_TARGETMACHINE_H
=20
-#include "llvm/MC/MCCodeGenInfo.h"
+#include "llvm/Support/CodeGen.h"
+#include "llvm/Target/TargetOptions.h"
 #include "llvm/ADT/StringRef.h"
 #include <cassert>
 #include <string>
@@ -23,11 +24,10 @@
=20
 class InstrItineraryData;
 class JITCodeEmitter;
+class GlobalValue;
 class MCAsmInfo;
 class MCCodeGenInfo;
 class MCContext;
-class Pass;
-class PassManager;
 class PassManagerBase;
 class Target;
 class TargetData;
@@ -37,32 +37,13 @@
 class TargetIntrinsicInfo;
 class TargetJITInfo;
 class TargetLowering;
+class TargetPassConfig;
 class TargetRegisterInfo;
 class TargetSelectionDAGInfo;
 class TargetSubtargetInfo;
 class formatted_raw_ostream;
 class raw_ostream;
=20
-// Code generation optimization level.
-namespace CodeGenOpt {
-  enum Level {
-    None,        // -O0
-    Less,        // -O1
-    Default,     // -O2, -Os
-    Aggressive   // -O3
-  };
-}
-
-namespace Sched {
-  enum Preference {
-    None,             // No preference
-    Latency,          // Scheduling for shortest total latency.
-    RegPressure,      // Scheduling for lowest register pressure.
-    Hybrid,           // Scheduling for both latency and register pressure.
-    ILP               // Scheduling for ILP in low register pressure mode.
-  };
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 ///
 /// TargetMachine - Primary interface to the complete machine description =
for
@@ -74,7 +55,7 @@
   void operator=3D(const TargetMachine &);  // DO NOT IMPLEMENT
 protected: // Can only create subclasses.
   TargetMachine(const Target &T, StringRef TargetTriple,
-                StringRef CPU, StringRef FS);
+                StringRef CPU, StringRef FS, const TargetOptions &Options);
=20
   /// getSubtargetImpl - virtual method implemented by subclasses that ret=
urns
   /// a reference to that target's TargetSubtargetInfo-derived member vari=
able.
@@ -101,6 +82,7 @@
   unsigned MCSaveTempLabels : 1;
   unsigned MCUseLoc : 1;
   unsigned MCUseCFI : 1;
+  unsigned MCUseDwarfDirectory : 1;
=20
 public:
   virtual ~TargetMachine();
@@ -111,6 +93,8 @@
   const StringRef getTargetCPU() const { return TargetCPU; }
   const StringRef getTargetFeatureString() const { return TargetFS; }
=20
+  TargetOptions Options;
+
   // Interfaces to the major aspects of target machine information:
   // -- Instruction opcode and operand information
   // -- Pipelines and scheduling information
@@ -196,6 +180,14 @@
   /// setMCUseCFI - Set whether all we should use dwarf's .cfi_* directive=
s.
   void setMCUseCFI(bool Value) { MCUseCFI =3D Value; }
=20
+  /// hasMCUseDwarfDirectory - Check whether we should use .file directive=
s with
+  /// explicit directories.
+  bool hasMCUseDwarfDirectory() const { return MCUseDwarfDirectory; }
+
+  /// setMCUseDwarfDirectory - Set whether all we should use .file directi=
ves
+  /// with explicit directories.
+  void setMCUseDwarfDirectory(bool Value) { MCUseDwarfDirectory =3D Value;=
 }
+
   /// getRelocationModel - Returns the code generation relocation model. T=
he
   /// choices are static, PIC, and dynamic-no-pic, and target default.
   Reloc::Model getRelocationModel() const;
@@ -204,6 +196,18 @@
   /// medium, large, and target default.
   CodeModel::Model getCodeModel() const;
=20
+  /// getTLSModel - Returns the TLS model which should be used for the giv=
en
+  /// global variable.
+  TLSModel::Model getTLSModel(const GlobalValue *GV) const;
+
+  /// getOptLevel - Returns the optimization level: None, Less,
+  /// Default, or Aggressive.
+  CodeGenOpt::Level getOptLevel() const;
+
+  void setFastISel(bool Enable) { Options.EnableFastISel =3D Enable; }
+
+  bool shouldPrintMachineCode() const { return Options.PrintMachineCode; }
+
   /// getAsmVerbosityDefault - Returns the default value of asm verbosity.
   ///
   static bool getAsmVerbosityDefault();
@@ -236,10 +240,6 @@
     CGFT_Null         // Do not emit any output.
   };
=20
-  /// getEnableTailMergeDefault - the default setting for -enable-tail-mer=
ge
-  /// on this target.  User flag overrides.
-  virtual bool getEnableTailMergeDefault() const { return true; }
-
   /// addPassesToEmitFile - Add passes to the specified pass manager to ge=
t the
   /// specified file emitted.  Typically this will involve several steps o=
f code
   /// generation.  This method should return true if emission of this file=
 type
@@ -247,8 +247,7 @@
   virtual bool addPassesToEmitFile(PassManagerBase &,
                                    formatted_raw_ostream &,
                                    CodeGenFileType,
-                                   CodeGenOpt::Level,
-                                   bool =3D true) {
+                                   bool /*DisableVerify*/ =3D true) {
     return true;
   }
=20
@@ -260,8 +259,7 @@
   ///
   virtual bool addPassesToEmitMachineCode(PassManagerBase &,
                                           JITCodeEmitter &,
-                                          CodeGenOpt::Level,
-                                          bool =3D true) {
+                                          bool /*DisableVerify*/ =3D true)=
 {
     return true;
   }
=20
@@ -273,8 +271,7 @@
   virtual bool addPassesToEmitMC(PassManagerBase &,
                                  MCContext *&,
                                  raw_ostream &,
-                                 CodeGenOpt::Level,
-                                 bool =3D true) {
+                                 bool /*DisableVerify*/ =3D true) {
     return true;
   }
 };
@@ -285,25 +282,21 @@
 class LLVMTargetMachine : public TargetMachine {
 protected: // Can only create subclasses.
   LLVMTargetMachine(const Target &T, StringRef TargetTriple,
-                    StringRef CPU, StringRef FS,
-                    Reloc::Model RM, CodeModel::Model CM);
-
-private:
-  /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for
-  /// both emitting to assembly files or machine code output.
-  ///
-  bool addCommonCodeGenPasses(PassManagerBase &, CodeGenOpt::Level,
-                              bool DisableVerify, MCContext *&OutCtx);
+                    StringRef CPU, StringRef FS, TargetOptions Options,
+                    Reloc::Model RM, CodeModel::Model CM,
+                    CodeGenOpt::Level OL);
=20
 public:
+  /// createPassConfig - Create a pass configuration object to be used by
+  /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
+
   /// addPassesToEmitFile - Add passes to the specified pass manager to ge=
t the
   /// specified file emitted.  Typically this will involve several steps o=
f code
-  /// generation.  If OptLevel is None, the code generator should emit cod=
e as
-  /// fast as possible, though the generated code may be less efficient.
+  /// generation.
   virtual bool addPassesToEmitFile(PassManagerBase &PM,
                                    formatted_raw_ostream &Out,
                                    CodeGenFileType FileType,
-                                   CodeGenOpt::Level,
                                    bool DisableVerify =3D true);
=20
   /// addPassesToEmitMachineCode - Add passes to the specified pass manage=
r to
@@ -314,7 +307,6 @@
   ///
   virtual bool addPassesToEmitMachineCode(PassManagerBase &PM,
                                           JITCodeEmitter &MCE,
-                                          CodeGenOpt::Level,
                                           bool DisableVerify =3D true);
=20
   /// addPassesToEmitMC - Add passes to the specified pass manager to get
@@ -325,65 +317,15 @@
   virtual bool addPassesToEmitMC(PassManagerBase &PM,
                                  MCContext *&Ctx,
                                  raw_ostream &OS,
-                                 CodeGenOpt::Level OptLevel,
                                  bool DisableVerify =3D true);
=20
-  /// Target-Independent Code Generator Pass Configuration Options.
-
-  /// addPreISelPasses - This method should add any "last minute" LLVM->LL=
VM
-  /// passes (which are run just before instruction selector).
-  virtual bool addPreISel(PassManagerBase &, CodeGenOpt::Level) {
-    return true;
-  }
-
-  /// addInstSelector - This method should install an instruction selector=
 pass,
-  /// which converts from LLVM code to machine instructions.
-  virtual bool addInstSelector(PassManagerBase &, CodeGenOpt::Level) {
-    return true;
-  }
-
-  /// addPreRegAlloc - This method may be implemented by targets that want=
 to
-  /// run passes immediately before register allocation. This should return
-  /// true if -print-machineinstrs should print after these passes.
-  virtual bool addPreRegAlloc(PassManagerBase &, CodeGenOpt::Level) {
-    return false;
-  }
-
-  /// addPostRegAlloc - This method may be implemented by targets that want
-  /// to run passes after register allocation but before prolog-epilog
-  /// insertion.  This should return true if -print-machineinstrs should p=
rint
-  /// after these passes.
-  virtual bool addPostRegAlloc(PassManagerBase &, CodeGenOpt::Level) {
-    return false;
-  }
-
-  /// addPreSched2 - This method may be implemented by targets that want to
-  /// run passes after prolog-epilog insertion and before the second instr=
uction
-  /// scheduling pass.  This should return true if -print-machineinstrs sh=
ould
-  /// print after these passes.
-  virtual bool addPreSched2(PassManagerBase &, CodeGenOpt::Level) {
-    return false;
-  }
-
-  /// addPreEmitPass - This pass may be implemented by targets that want t=
o run
-  /// passes immediately before machine code is emitted.  This should retu=
rn
-  /// true if -print-machineinstrs should print out the code after the pas=
ses.
-  virtual bool addPreEmitPass(PassManagerBase &, CodeGenOpt::Level) {
-    return false;
-  }
-
-
   /// addCodeEmitter - This pass should be overridden by the target to add=
 a
   /// code emitter, if supported.  If this is not supported, 'true' should=
 be
   /// returned.
-  virtual bool addCodeEmitter(PassManagerBase &, CodeGenOpt::Level,
+  virtual bool addCodeEmitter(PassManagerBase &,
                               JITCodeEmitter &) {
     return true;
   }
-
-  /// getEnableTailMergeDefault - the default setting for -enable-tail-mer=
ge
-  /// on this target.  User flag overrides.
-  virtual bool getEnableTailMergeDefault() const { return true; }
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetOpcodes.h
--- a/head/contrib/llvm/include/llvm/Target/TargetOpcodes.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetOpcodes.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -82,7 +82,12 @@
=20
     /// COPY - Target-independent register copy. This instruction can also=
 be
     /// used to copy between subregisters of virtual registers.
-    COPY =3D 13
+    COPY =3D 13,
+
+    /// BUNDLE - This instruction represents an instruction bundle. Instru=
ctions
+    /// which immediately follow a BUNDLE instruction which are marked with
+    /// 'InsideBundle' flag are inside the bundle.
+    BUNDLE
   };
 } // end namespace TargetOpcode
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetOptions.h
--- a/head/contrib/llvm/include/llvm/Target/TargetOptions.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetOptions.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,151 +15,177 @@
 #ifndef LLVM_TARGET_TARGETOPTIONS_H
 #define LLVM_TARGET_TARGETOPTIONS_H
=20
+#include <string>
+
 namespace llvm {
   class MachineFunction;
+  class StringRef;
=20
   // Possible float ABI settings. Used with FloatABIType in TargetOptions.=
h.
   namespace FloatABI {
     enum ABIType {
-      Default, // Target-specific (either soft of hard depending on triple=
, etc).
+      Default, // Target-specific (either soft or hard depending on triple=
, etc).
       Soft, // Soft float.
       Hard  // Hard float.
     };
   }
- =20
-  /// PrintMachineCode - This flag is enabled when the -print-machineinstrs
-  /// option is specified on the command line, and should enable debugging
-  /// output from the code generator.
-  extern bool PrintMachineCode;
=20
-  /// NoFramePointerElim - This flag is enabled when the -disable-fp-elim =
is
-  /// specified on the command line.  If the target supports the frame poi=
nter
-  /// elimination optimization, this option should disable it.
-  extern bool NoFramePointerElim;
+  class TargetOptions {
+  public:
+    TargetOptions()
+        : PrintMachineCode(false), NoFramePointerElim(false),
+          NoFramePointerElimNonLeaf(false), LessPreciseFPMADOption(false),
+          NoExcessFPPrecision(false), UnsafeFPMath(false), NoInfsFPMath(fa=
lse),
+          NoNaNsFPMath(false), HonorSignDependentRoundingFPMathOption(fals=
e),
+          UseSoftFloat(false), NoZerosInBSS(false), JITExceptionHandling(f=
alse),
+          JITEmitDebugInfo(false), JITEmitDebugInfoToDisk(false),
+          GuaranteedTailCallOpt(false), DisableTailCalls(false),
+          StackAlignmentOverride(0), RealignStack(true),
+          DisableJumpTables(false), EnableFastISel(false),
+          PositionIndependentExecutable(false), EnableSegmentedStacks(fals=
e),
+          TrapFuncName(""), FloatABIType(FloatABI::Default)
+    {}
=20
-  /// NoFramePointerElimNonLeaf - This flag is enabled when the
-  /// -disable-non-leaf-fp-elim is specified on the command line. If the t=
arget
-  /// supports the frame pointer elimination optimization, this option sho=
uld
-  /// disable it for non-leaf functions.
-  extern bool NoFramePointerElimNonLeaf;
+    /// PrintMachineCode - This flag is enabled when the -print-machineins=
trs
+    /// option is specified on the command line, and should enable debuggi=
ng
+    /// output from the code generator.
+    unsigned PrintMachineCode : 1;
=20
-  /// DisableFramePointerElim - This returns true if frame pointer elimina=
tion
-  /// optimization should be disabled for the given machine function.
-  extern bool DisableFramePointerElim(const MachineFunction &MF);
+    /// NoFramePointerElim - This flag is enabled when the -disable-fp-eli=
m is
+    /// specified on the command line.  If the target supports the frame p=
ointer
+    /// elimination optimization, this option should disable it.
+    unsigned NoFramePointerElim : 1;
=20
-  /// LessPreciseFPMAD - This flag is enabled when the
-  /// -enable-fp-mad is specified on the command line.  When this flag is =
off
-  /// (the default), the code generator is not allowed to generate mad
-  /// (multiply add) if the result is "less precise" than doing those oper=
ations
-  /// individually.
-  extern bool LessPreciseFPMADOption;
-  extern bool LessPreciseFPMAD();
+    /// NoFramePointerElimNonLeaf - This flag is enabled when the
+    /// -disable-non-leaf-fp-elim is specified on the command line. If the
+    /// target supports the frame pointer elimination optimization, this o=
ption
+    /// should disable it for non-leaf functions.
+    unsigned NoFramePointerElimNonLeaf : 1;
=20
-  /// NoExcessFPPrecision - This flag is enabled when the
-  /// -disable-excess-fp-precision flag is specified on the command line. =
 When
-  /// this flag is off (the default), the code generator is allowed to pro=
duce
-  /// results that are "more precise" than IEEE allows.  This includes use=
 of
-  /// FMA-like operations and use of the X86 FP registers without rounding=
 all
-  /// over the place.
-  extern bool NoExcessFPPrecision;
+    /// DisableFramePointerElim - This returns true if frame pointer elimi=
nation
+    /// optimization should be disabled for the given machine function.
+    bool DisableFramePointerElim(const MachineFunction &MF) const;
=20
-  /// UnsafeFPMath - This flag is enabled when the
-  /// -enable-unsafe-fp-math flag is specified on the command line.  When
-  /// this flag is off (the default), the code generator is not allowed to
-  /// produce results that are "less precise" than IEEE allows.  This incl=
udes
-  /// use of X86 instructions like FSIN and FCOS instead of libcalls.
-  /// UnsafeFPMath implies LessPreciseFPMAD.
-  extern bool UnsafeFPMath;
+    /// LessPreciseFPMAD - This flag is enabled when the
+    /// -enable-fp-mad is specified on the command line.  When this flag i=
s off
+    /// (the default), the code generator is not allowed to generate mad
+    /// (multiply add) if the result is "less precise" than doing those
+    /// operations individually.
+    unsigned LessPreciseFPMADOption : 1;
+    bool LessPreciseFPMAD() const;
=20
-  /// NoInfsFPMath - This flag is enabled when the
-  /// -enable-no-infs-fp-math flag is specified on the command line. When
-  /// this flag is off (the default), the code generator is not allowed to
-  /// assume the FP arithmetic arguments and results are never +-Infs.
-  extern bool NoInfsFPMath;
+    /// NoExcessFPPrecision - This flag is enabled when the
+    /// -disable-excess-fp-precision flag is specified on the command line.
+    /// When this flag is off (the default), the code generator is allowed=
 to
+    /// produce results that are "more precise" than IEEE allows.  This in=
cludes
+    /// use of FMA-like operations and use of the X86 FP registers without
+    /// rounding all over the place.
+    unsigned NoExcessFPPrecision : 1;
=20
-  /// NoNaNsFPMath - This flag is enabled when the
-  /// -enable-no-nans-fp-math flag is specified on the command line. When
-  /// this flag is off (the default), the code generator is not allowed to
-  /// assume the FP arithmetic arguments and results are never NaNs.
-  extern bool NoNaNsFPMath;
+    /// UnsafeFPMath - This flag is enabled when the
+    /// -enable-unsafe-fp-math flag is specified on the command line.  When
+    /// this flag is off (the default), the code generator is not allowed =
to
+    /// produce results that are "less precise" than IEEE allows.  This in=
cludes
+    /// use of X86 instructions like FSIN and FCOS instead of libcalls.
+    /// UnsafeFPMath implies LessPreciseFPMAD.
+    unsigned UnsafeFPMath : 1;
=20
-  /// HonorSignDependentRoundingFPMath - This returns true when the
-  /// -enable-sign-dependent-rounding-fp-math is specified.  If this retur=
ns
-  /// false (the default), the code generator is allowed to assume that the
-  /// rounding behavior is the default (round-to-zero for all floating poi=
nt to
-  /// integer conversions, and round-to-nearest for all other arithmetic
-  /// truncations).  If this is enabled (set to true), the code generator =
must
-  /// assume that the rounding mode may dynamically change.
-  extern bool HonorSignDependentRoundingFPMathOption;
-  extern bool HonorSignDependentRoundingFPMath();
- =20
-  /// UseSoftFloat - This flag is enabled when the -soft-float flag is spe=
cified
-  /// on the command line.  When this flag is on, the code generator will
-  /// generate libcalls to the software floating point library instead of
-  /// target FP instructions.
-  extern bool UseSoftFloat;
+    /// NoInfsFPMath - This flag is enabled when the
+    /// -enable-no-infs-fp-math flag is specified on the command line. When
+    /// this flag is off (the default), the code generator is not allowed =
to
+    /// assume the FP arithmetic arguments and results are never +-Infs.
+    unsigned NoInfsFPMath : 1;
=20
-  /// FloatABIType - This setting is set by -float-abi=3Dxxx option is spe=
cfied
-  /// on the command line. This setting may either be Default, Soft, or Ha=
rd.
-  /// Default selects the target's default behavior. Soft selects the ABI =
for
-  /// UseSoftFloat, but does not inidcate that FP hardware may not be used.
-  /// Such a combination is unfortunately popular (e.g. arm-apple-darwin).
-  /// Hard presumes that the normal FP ABI is used.
-  extern FloatABI::ABIType FloatABIType;
+    /// NoNaNsFPMath - This flag is enabled when the
+    /// -enable-no-nans-fp-math flag is specified on the command line. When
+    /// this flag is off (the default), the code generator is not allowed =
to
+    /// assume the FP arithmetic arguments and results are never NaNs.
+    unsigned NoNaNsFPMath : 1;
=20
-  /// NoZerosInBSS - By default some codegens place zero-initialized data =
to
-  /// .bss section. This flag disables such behaviour (necessary, e.g. for
-  /// crt*.o compiling).
-  extern bool NoZerosInBSS;
+    /// HonorSignDependentRoundingFPMath - This returns true when the
+    /// -enable-sign-dependent-rounding-fp-math is specified.  If this ret=
urns
+    /// false (the default), the code generator is allowed to assume that =
the
+    /// rounding behavior is the default (round-to-zero for all floating p=
oint
+    /// to integer conversions, and round-to-nearest for all other arithme=
tic
+    /// truncations).  If this is enabled (set to true), the code generato=
r must
+    /// assume that the rounding mode may dynamically change.
+    unsigned HonorSignDependentRoundingFPMathOption : 1;
+    bool HonorSignDependentRoundingFPMath() const;
=20
-  /// JITExceptionHandling - This flag indicates that the JIT should emit
-  /// exception handling information.
-  extern bool JITExceptionHandling;
+    /// UseSoftFloat - This flag is enabled when the -soft-float flag is
+    /// specified on the command line.  When this flag is on, the code gen=
erator
+    /// will generate libcalls to the software floating point library inst=
ead of
+    /// target FP instructions.
+    unsigned UseSoftFloat : 1;
=20
-  /// JITEmitDebugInfo - This flag indicates that the JIT should try to em=
it
-  /// debug information and notify a debugger about it.
-  extern bool JITEmitDebugInfo;
+    /// NoZerosInBSS - By default some codegens place zero-initialized dat=
a to
+    /// .bss section. This flag disables such behaviour (necessary, e.g. f=
or
+    /// crt*.o compiling).
+    unsigned NoZerosInBSS : 1;
=20
-  /// JITEmitDebugInfoToDisk - This flag indicates that the JIT should wri=
te
-  /// the object files generated by the JITEmitDebugInfo flag to disk.  Th=
is
-  /// flag is hidden and is only for debugging the debug info.
-  extern bool JITEmitDebugInfoToDisk;
+    /// JITExceptionHandling - This flag indicates that the JIT should emit
+    /// exception handling information.
+    unsigned JITExceptionHandling : 1;
=20
-  /// GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is
-  /// specified on the commandline. When the flag is on, participating tar=
gets
-  /// will perform tail call optimization on all calls which use the fastcc
-  /// calling convention and which satisfy certain target-independent
-  /// criteria (being at the end of a function, having the same return type
-  /// as their parent function, etc.), using an alternate ABI if necessary.
-  extern bool GuaranteedTailCallOpt;
+    /// JITEmitDebugInfo - This flag indicates that the JIT should try to =
emit
+    /// debug information and notify a debugger about it.
+    unsigned JITEmitDebugInfo : 1;
=20
-  /// StackAlignmentOverride - Override default stack alignment for target.
-  extern unsigned StackAlignmentOverride;
+    /// JITEmitDebugInfoToDisk - This flag indicates that the JIT should w=
rite
+    /// the object files generated by the JITEmitDebugInfo flag to disk.  =
This
+    /// flag is hidden and is only for debugging the debug info.
+    unsigned JITEmitDebugInfoToDisk : 1;
=20
-  /// RealignStack - This flag indicates whether the stack should be
-  /// automatically realigned, if needed.
-  extern bool RealignStack;
+    /// GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is
+    /// specified on the commandline. When the flag is on, participating t=
argets
+    /// will perform tail call optimization on all calls which use the fas=
tcc
+    /// calling convention and which satisfy certain target-independent
+    /// criteria (being at the end of a function, having the same return t=
ype
+    /// as their parent function, etc.), using an alternate ABI if necessa=
ry.
+    unsigned GuaranteedTailCallOpt : 1;
=20
-  /// DisableJumpTables - This flag indicates jump tables should not be=20
-  /// generated.
-  extern bool DisableJumpTables;
+    /// DisableTailCalls - This flag controls whether we will use tail cal=
ls.
+    /// Disabling them may be useful to maintain a correct call stack.
+    unsigned DisableTailCalls : 1;
=20
-  /// EnableFastISel - This flag enables fast-path instruction selection
-  /// which trades away generated code quality in favor of reducing
-  /// compile time.
-  extern bool EnableFastISel;
- =20
-  /// StrongPHIElim - This flag enables more aggressive PHI elimination
-  /// wth earlier copy coalescing.
-  extern bool StrongPHIElim;
+    /// StackAlignmentOverride - Override default stack alignment for targ=
et.
+    unsigned StackAlignmentOverride;
=20
-  /// getTrapFunctionName - If this returns a non-empty string, this means=
 isel
-  /// should lower Intrinsic::trap to a call to the specified function name
-  /// instead of an ISD::TRAP node.
-  extern StringRef getTrapFunctionName();
+    /// RealignStack - This flag indicates whether the stack should be
+    /// automatically realigned, if needed.
+    unsigned RealignStack : 1;
=20
-  extern bool EnableSegmentedStacks;
+    /// DisableJumpTables - This flag indicates jump tables should not be
+    /// generated.
+    unsigned DisableJumpTables : 1;
=20
+    /// EnableFastISel - This flag enables fast-path instruction selection
+    /// which trades away generated code quality in favor of reducing
+    /// compile time.
+    unsigned EnableFastISel : 1;
+
+    /// PositionIndependentExecutable - This flag indicates whether the co=
de
+    /// will eventually be linked into a single executable, despite the PIC
+    /// relocation model being in use. It's value is undefined (and irrele=
vant)
+    /// if the relocation model is anything other than PIC.
+    unsigned PositionIndependentExecutable : 1;
+
+    unsigned EnableSegmentedStacks : 1;
+
+    /// getTrapFunctionName - If this returns a non-empty string, this mea=
ns
+    /// isel should lower Intrinsic::trap to a call to the specified funct=
ion
+    /// name instead of an ISD::TRAP node.
+    std::string TrapFuncName;
+    StringRef getTrapFunctionName() const;
+
+    /// FloatABIType - This setting is set by -float-abi=3Dxxx option is s=
pecfied
+    /// on the command line. This setting may either be Default, Soft, or =
Hard.
+    /// Default selects the target's default behavior. Soft selects the AB=
I for
+    /// UseSoftFloat, but does not indicate that FP hardware may not be us=
ed.
+    /// Such a combination is unfortunately popular (e.g. arm-apple-darwin=
).
+    /// Hard presumes that the normal FP ABI is used.
+    FloatABI::ABIType FloatABIType;
+  };
 } // End llvm namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetRegisterInfo.h
--- a/head/contrib/llvm/include/llvm/Target/TargetRegisterInfo.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetRegisterInfo.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "llvm/CodeGen/MachineBasicBlock.h"
 #include "llvm/CodeGen/ValueTypes.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/CallingConv.h"
 #include <cassert>
 #include <functional>
=20
@@ -33,25 +34,18 @@
=20
 class TargetRegisterClass {
 public:
-  typedef const unsigned* iterator;
-  typedef const unsigned* const_iterator;
-  typedef const EVT* vt_iterator;
+  typedef const uint16_t* iterator;
+  typedef const uint16_t* const_iterator;
+  typedef const MVT::SimpleValueType* vt_iterator;
   typedef const TargetRegisterClass* const * sc_iterator;
-private:
+
+  // Instance variables filled by tablegen, do not use!
   const MCRegisterClass *MC;
   const vt_iterator VTs;
   const unsigned *SubClassMask;
   const sc_iterator SuperClasses;
   const sc_iterator SuperRegClasses;
-public:
-  TargetRegisterClass(const MCRegisterClass *MC, const EVT *vts,
-                      const unsigned *subcm,
-                      const TargetRegisterClass * const *supcs,
-                      const TargetRegisterClass * const *superregcs)
-    : MC(MC), VTs(vts), SubClassMask(subcm), SuperClasses(supcs),
-      SuperRegClasses(superregcs) {}
-
-  virtual ~TargetRegisterClass() {}     // Allow subclasses
+  ArrayRef<uint16_t> (*OrderFunc)(const MachineFunction&);
=20
   /// getID() - Return the register class ID number.
   ///
@@ -108,7 +102,7 @@
   ///
   bool hasType(EVT vt) const {
     for(int i =3D 0; VTs[i] !=3D MVT::Other; ++i)
-      if (VTs[i] =3D=3D vt)
+      if (EVT(VTs[i]) =3D=3D vt)
         return true;
     return false;
   }
@@ -165,7 +159,7 @@
   /// getSubClassMask - Returns a bit vector of subclasses, including this=
 one.
   /// The vector is indexed by class IDs, see hasSubClassEq() above for ho=
w to
   /// use it.
-  const unsigned *getSubClassMask() const {
+  const uint32_t *getSubClassMask() const {
     return SubClassMask;
   }
=20
@@ -196,9 +190,8 @@
   ///
   /// By default, this method returns all registers in the class.
   ///
-  virtual
-  ArrayRef<unsigned> getRawAllocationOrder(const MachineFunction &MF) cons=
t {
-    return makeArrayRef(begin(), getNumRegs());
+  ArrayRef<uint16_t> getRawAllocationOrder(const MachineFunction &MF) cons=
t {
+    return OrderFunc ? OrderFunc(MF) : makeArrayRef(begin(), getNumRegs());
   }
 };
=20
@@ -209,6 +202,13 @@
   bool inAllocatableClass;      // Register belongs to an allocatable regc=
lass.
 };
=20
+/// Each TargetRegisterClass has a per register weight, and weight
+/// limit which must be less than the limits of its pressure sets.
+struct RegClassWeight {
+  unsigned RegWeigt;
+  unsigned WeightLimit;
+};
+
 /// TargetRegisterInfo base class - We assume that the target defines a st=
atic
 /// array of TargetRegisterDesc objects that represent all of the machine
 /// registers that the target has.  As such, we simply have to track a poi=
nter
@@ -332,7 +332,7 @@
     if (regA =3D=3D regB) return true;
     if (isVirtualRegister(regA) || isVirtualRegister(regB))
       return false;
-    for (const unsigned *regList =3D getOverlaps(regA)+1; *regList; ++regL=
ist) {
+    for (const uint16_t *regList =3D getOverlaps(regA)+1; *regList; ++regL=
ist) {
       if (*regList =3D=3D regB) return true;
     }
     return false;
@@ -347,7 +347,7 @@
   /// isSuperRegister - Returns true if regB is a super-register of regA.
   ///
   bool isSuperRegister(unsigned regA, unsigned regB) const {
-    for (const unsigned *regList =3D getSuperRegisters(regA); *regList;++r=
egList){
+    for (const uint16_t *regList =3D getSuperRegisters(regA); *regList;++r=
egList){
       if (*regList =3D=3D regB) return true;
     }
     return false;
@@ -356,10 +356,33 @@
   /// getCalleeSavedRegs - Return a null-terminated list of all of the
   /// callee saved registers on this target. The register should be in the
   /// order of desired callee-save stack frame offset. The first register =
is
-  /// closed to the incoming stack pointer if stack grows down, and vice v=
ersa.
-  virtual const unsigned* getCalleeSavedRegs(const MachineFunction *MF =3D=
 0)
+  /// closest to the incoming stack pointer if stack grows down, and vice =
versa.
+  ///
+  virtual const uint16_t* getCalleeSavedRegs(const MachineFunction *MF =3D=
 0)
                                                                       cons=
t =3D 0;
=20
+  /// getCallPreservedMask - Return a mask of call-preserved registers for=
 the
+  /// given calling convention on the current sub-target.  The mask should
+  /// include all call-preserved aliases.  This is used by the register
+  /// allocator to determine which registers can be live across a call.
+  ///
+  /// The mask is an array containing (TRI::getNumRegs()+31)/32 entries.
+  /// A set bit indicates that all bits of the corresponding register are
+  /// preserved across the function call.  The bit mask is expected to be
+  /// sub-register complete, i.e. if A is preserved, so are all its
+  /// sub-registers.
+  ///
+  /// Bits are numbered from the LSB, so the bit for physical register Reg=
 can
+  /// be found as (Mask[Reg / 32] >> Reg % 32) & 1.
+  ///
+  /// A NULL pointer means that no register mask will be used, and call
+  /// instructions should use implicit-def operands to indicate call clobb=
ered
+  /// registers.
+  ///
+  virtual const uint32_t *getCallPreservedMask(CallingConv::ID) const {
+    // The default mask clobbers everything.  All targets should override.
+    return 0;
+  }
=20
   /// getReservedRegs - Returns a bitset indexed by physical register numb=
er
   /// indicating if a register is a special register that has particular u=
ses
@@ -367,24 +390,11 @@
   /// used by register scavenger to determine what registers are free.
   virtual BitVector getReservedRegs(const MachineFunction &MF) const =3D 0;
=20
-  /// getSubReg - Returns the physical register number of sub-register "In=
dex"
-  /// for physical register RegNo. Return zero if the sub-register does not
-  /// exist.
-  virtual unsigned getSubReg(unsigned RegNo, unsigned Index) const =3D 0;
-
-  /// getSubRegIndex - For a given register pair, return the sub-register =
index
-  /// if the second register is a sub-register of the first. Return zero
-  /// otherwise.
-  virtual unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const=
 =3D 0;
-
   /// getMatchingSuperReg - Return a super-register of the specified regis=
ter
   /// Reg so its sub-register of index SubIdx is Reg.
   unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
                                const TargetRegisterClass *RC) const {
-    for (const unsigned *SRs =3D getSuperRegisters(Reg); unsigned SR =3D *=
SRs;++SRs)
-      if (Reg =3D=3D getSubReg(SR, SubIdx) && RC->contains(SR))
-        return SR;
-    return 0;
+    return MCRegisterInfo::getMatchingSuperReg(Reg, SubIdx, RC->MC);
   }
=20
   /// canCombineSubRegIndices - Given a register class and a list of
@@ -402,11 +412,11 @@
   /// getMatchingSuperRegClass - Return a subclass of the specified regist=
er
   /// class A so that each register in it has a sub-register of the
   /// specified sub-register index which is in the specified register clas=
s B.
+  ///
+  /// TableGen will synthesize missing A sub-classes.
   virtual const TargetRegisterClass *
   getMatchingSuperRegClass(const TargetRegisterClass *A,
-                           const TargetRegisterClass *B, unsigned Idx) con=
st {
-    return 0;
-  }
+                           const TargetRegisterClass *B, unsigned Idx) con=
st =3D0;
=20
   /// getSubClassWithSubReg - Returns the largest legal sub-class of RC th=
at
   /// supports the sub-register index Idx.
@@ -419,6 +429,7 @@
   /// supported by the full GR32 register class in 64-bit mode, but only b=
y the
   /// GR32_ABCD regiister class in 32-bit mode.
   ///
+  /// TableGen will synthesize missing RC sub-classes.
   virtual const TargetRegisterClass *
   getSubClassWithSubReg(const TargetRegisterClass *RC, unsigned Idx) const=
 =3D0;
=20
@@ -469,8 +480,7 @@
   /// values.  If a target supports multiple different pointer register cl=
asses,
   /// kind specifies which one is indicated.
   virtual const TargetRegisterClass *getPointerRegClass(unsigned Kind=3D0)=
 const {
-    assert(0 && "Target didn't implement getPointerRegClass!");
-    return 0; // Must return a value in order to compile with VS 2005
+    llvm_unreachable("Target didn't implement getPointerRegClass!");
   }
=20
   /// getCrossCopyRegClass - Returns a legal register class to copy a regi=
ster
@@ -497,18 +507,37 @@
   /// getRegPressureLimit - Return the register pressure "high water mark"=
 for
   /// the specific register class. The scheduler is in high register press=
ure
   /// mode (for the specific register class) if it goes over the limit.
+  ///
+  /// Note: this is the old register pressure model that relies on a manua=
lly
+  /// specified representative register class per value type.
   virtual unsigned getRegPressureLimit(const TargetRegisterClass *RC,
                                        MachineFunction &MF) const {
     return 0;
   }
=20
+  /// Get the weight in units of pressure for this register class.
+  virtual const RegClassWeight &getRegClassWeight(
+    const TargetRegisterClass *RC) const =3D 0;
+
+  /// Get the number of dimensions of register pressure.
+  virtual unsigned getNumRegPressureSets() const =3D 0;
+
+  /// Get the register unit pressure limit for this dimension.
+  /// This limit must be adjusted dynamically for reserved registers.
+  virtual unsigned getRegPressureSetLimit(unsigned Idx) const =3D 0;
+
+  /// Get the dimensions of register pressure impacted by this register cl=
ass.
+  /// Returns a -1 terminated array of pressure set IDs.
+  virtual const int *getRegClassPressureSets(
+    const TargetRegisterClass *RC) const =3D 0;
+
   /// getRawAllocationOrder - Returns the register allocation order for a
   /// specified register class with a target-dependent hint. The returned =
list
   /// may contain reserved registers that cannot be allocated.
   ///
   /// Register allocators need only call this function to resolve
   /// target-dependent hints, but it should work without hinting as well.
-  virtual ArrayRef<unsigned>
+  virtual ArrayRef<uint16_t>
   getRawAllocationOrder(const TargetRegisterClass *RC,
                         unsigned HintType, unsigned HintReg,
                         const MachineFunction &MF) const {
@@ -607,22 +636,22 @@
   virtual void materializeFrameBaseRegister(MachineBasicBlock *MBB,
                                             unsigned BaseReg, int FrameIdx,
                                             int64_t Offset) const {
-    assert(0 && "materializeFrameBaseRegister does not exist on this targe=
t");
+    llvm_unreachable("materializeFrameBaseRegister does not exist on this "
+                     "target");
   }
=20
   /// resolveFrameIndex - Resolve a frame index operand of an instruction
   /// to reference the indicated base register plus offset instead.
   virtual void resolveFrameIndex(MachineBasicBlock::iterator I,
                                  unsigned BaseReg, int64_t Offset) const {
-    assert(0 && "resolveFrameIndex does not exist on this target");
+    llvm_unreachable("resolveFrameIndex does not exist on this target");
   }
=20
   /// isFrameOffsetLegal - Determine whether a given offset immediate is
   /// encodable to resolve a frame index.
   virtual bool isFrameOffsetLegal(const MachineInstr *MI,
                                   int64_t Offset) const {
-    assert(0 && "isFrameOffsetLegal does not exist on this target");
-    return false; // Must return a value in order to compile with VS 2005
+    llvm_unreachable("isFrameOffsetLegal does not exist on this target");
   }
=20
   /// eliminateCallFramePseudoInstr - This method is called during prolog/=
epilog
@@ -636,7 +665,8 @@
   eliminateCallFramePseudoInstr(MachineFunction &MF,
                                 MachineBasicBlock &MBB,
                                 MachineBasicBlock::iterator MI) const {
-    assert(0 && "Call Frame Pseudo Instructions do not exist on this targe=
t!");
+    llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
+                     "target!");
   }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetSelectionDAG.td
--- a/head/contrib/llvm/include/llvm/Target/TargetSelectionDAG.td	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetSelectionDAG.td	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -352,6 +352,8 @@
 def ctlz       : SDNode<"ISD::CTLZ"       , SDTIntUnaryOp>;
 def cttz       : SDNode<"ISD::CTTZ"       , SDTIntUnaryOp>;
 def ctpop      : SDNode<"ISD::CTPOP"      , SDTIntUnaryOp>;
+def ctlz_zero_undef : SDNode<"ISD::CTLZ_ZERO_UNDEF", SDTIntUnaryOp>;
+def cttz_zero_undef : SDNode<"ISD::CTTZ_ZERO_UNDEF", SDTIntUnaryOp>;
 def sext       : SDNode<"ISD::SIGN_EXTEND", SDTIntExtendOp>;
 def zext       : SDNode<"ISD::ZERO_EXTEND", SDTIntExtendOp>;
 def anyext     : SDNode<"ISD::ANY_EXTEND" , SDTIntExtendOp>;
@@ -655,6 +657,51 @@
   return cast<LoadSDNode>(N)->getMemoryVT() =3D=3D MVT::i32;
 }]>;
=20
+def extloadvi1  : PatFrag<(ops node:$ptr), (extload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i1;
+}]>;
+def extloadvi8  : PatFrag<(ops node:$ptr), (extload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i8;
+}]>;
+def extloadvi16 : PatFrag<(ops node:$ptr), (extload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i1=
6;
+}]>;
+def extloadvi32 : PatFrag<(ops node:$ptr), (extload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i3=
2;
+}]>;
+def extloadvf32 : PatFrag<(ops node:$ptr), (extload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::f3=
2;
+}]>;
+def extloadvf64 : PatFrag<(ops node:$ptr), (extload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::f6=
4;
+}]>;
+
+def sextloadvi1  : PatFrag<(ops node:$ptr), (sextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i1;
+}]>;
+def sextloadvi8  : PatFrag<(ops node:$ptr), (sextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i8;
+}]>;
+def sextloadvi16 : PatFrag<(ops node:$ptr), (sextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i1=
6;
+}]>;
+def sextloadvi32 : PatFrag<(ops node:$ptr), (sextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i3=
2;
+}]>;
+
+def zextloadvi1  : PatFrag<(ops node:$ptr), (zextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i1;
+}]>;
+def zextloadvi8  : PatFrag<(ops node:$ptr), (zextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i8;
+}]>;
+def zextloadvi16 : PatFrag<(ops node:$ptr), (zextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i1=
6;
+}]>;
+def zextloadvi32 : PatFrag<(ops node:$ptr), (zextload node:$ptr), [{
+  return cast<LoadSDNode>(N)->getMemoryVT().getScalarType() =3D=3D MVT::i3=
2;
+}]>;
+
 // store fragments.
 def unindexedstore : PatFrag<(ops node:$val, node:$ptr),
                              (st node:$val, node:$ptr), [{
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Target/=
TargetSubtargetInfo.h
--- a/head/contrib/llvm/include/llvm/Target/TargetSubtargetInfo.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Target/TargetSubtargetInfo.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 #define LLVM_TARGET_TARGETSUBTARGETINFO_H
=20
 #include "llvm/MC/MCSubtargetInfo.h"
-#include "llvm/Target/TargetMachine.h"
+#include "llvm/Support/CodeGen.h"
=20
 namespace llvm {
=20
@@ -39,7 +39,7 @@
   // AntiDepBreakMode - Type of anti-dependence breaking that should
   // be performed before post-RA scheduling.
   typedef enum { ANTIDEP_NONE, ANTIDEP_CRITICAL, ANTIDEP_ALL } AntiDepBrea=
kMode;
-  typedef SmallVectorImpl<TargetRegisterClass*> RegClassVector;
+  typedef SmallVectorImpl<const TargetRegisterClass*> RegClassVector;
=20
   virtual ~TargetSubtargetInfo();
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/IPO.h
--- a/head/contrib/llvm/include/llvm/Transforms/IPO.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/IPO.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -94,6 +94,7 @@
 /// createAlwaysInlinerPass - Return a new pass object that inlines only=20
 /// functions that are marked as "always_inline".
 Pass *createAlwaysInlinerPass();
+Pass *createAlwaysInlinerPass(bool InsertLifetime);
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 /// createPruneEHPass - Return a new pass object which transforms invoke
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/IPO/InlinerPass.h
--- a/head/contrib/llvm/include/llvm/Transforms/IPO/InlinerPass.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/IPO/InlinerPass.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
 ///
 struct Inliner : public CallGraphSCCPass {
   explicit Inliner(char &ID);
-  explicit Inliner(char &ID, int Threshold);
+  explicit Inliner(char &ID, int Threshold, bool InsertLifetime);
=20
   /// getAnalysisUsage - For this class, we declare that we require and pr=
eserve
   /// the call graph.  If the derived class implements this method, it sho=
uld
@@ -65,28 +65,21 @@
   ///
   virtual InlineCost getInlineCost(CallSite CS) =3D 0;
=20
-  // getInlineFudgeFactor - Return a > 1.0 factor if the inliner should us=
e a
-  // higher threshold to determine if the function call should be inlined.
+  /// removeDeadFunctions - Remove dead functions.
   ///
-  virtual float getInlineFudgeFactor(CallSite CS) =3D 0;
+  /// This also includes a hack in the form of the 'AlwaysInlineOnly' flag
+  /// which restricts it to deleting functions with an 'AlwaysInline'
+  /// attribute. This is useful for the InlineAlways pass that only wants =
to
+  /// deal with that subset of the functions.
+  bool removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly =3D false);
=20
-  /// resetCachedCostInfo - erase any cached cost data from the derived cl=
ass.
-  /// If the derived class has no such data this can be empty.
-  ///=20
-  virtual void resetCachedCostInfo(Function* Caller) =3D 0;
-
-  /// growCachedCostInfo - update the cached cost info for Caller after Ca=
llee
-  /// has been inlined.
-  virtual void growCachedCostInfo(Function *Caller, Function *Callee) =3D =
0;
-
-  /// removeDeadFunctions - Remove dead functions that are not included in
-  /// DNR (Do Not Remove) list.
-  bool removeDeadFunctions(CallGraph &CG,=20
-                           SmallPtrSet<const Function *, 16> *DNR =3D NULL=
);
 private:
   // InlineThreshold - Cache the value here for easy access.
   unsigned InlineThreshold;
=20
+  // InsertLifetime - Insert @llvm.lifetime intrinsics.
+  bool InsertLifetime;
+
   /// shouldInline - Return true if the inliner should attempt to
   /// inline at the given CallSite.
   bool shouldInline(CallSite CS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/IPO/PassManagerBuilder.h
--- a/head/contrib/llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/IPO/PassManagerBuilder.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -60,6 +60,10 @@
     /// out of the frontend.
     EP_EarlyAsPossible,
=20
+    /// EP_ModuleOptimizerEarly - This extension point allows adding passes
+    /// just before the main module-level optimization passes.
+    EP_ModuleOptimizerEarly,
+
     /// EP_LoopOptimizerEnd - This extension point allows adding loop pass=
es to
     /// the end of the loop optimizer.
     EP_LoopOptimizerEnd,
@@ -67,7 +71,16 @@
     /// EP_ScalarOptimizerLate - This extension point allows adding optimi=
zation
     /// passes after most of the main optimizations, but before the last
     /// cleanup-ish optimizations.
-    EP_ScalarOptimizerLate
+    EP_ScalarOptimizerLate,
+
+    /// EP_OptimizerLast -- This extension point allows adding passes that
+    /// run after everything else.
+    EP_OptimizerLast,
+
+    /// EP_EnabledOnOptLevel0 - This extension point allows adding passes =
that
+    /// should not be disabled by O0 optimization level. The passes will be
+    /// inserted after the inlining pass.
+    EP_EnabledOnOptLevel0
   };
=20
   /// The Optimization Level - Specify the basic optimization level.
@@ -90,6 +103,7 @@
   bool DisableSimplifyLibCalls;
   bool DisableUnitAtATime;
   bool DisableUnrollLoops;
+  bool Vectorize;
=20
 private:
   /// ExtensionList - This is list of all of the extensions that are regis=
tered.
@@ -117,8 +131,9 @@
   /// populateModulePassManager - This sets up the primary pass manager.
   void populateModulePassManager(PassManagerBase &MPM);
   void populateLTOPassManager(PassManagerBase &PM, bool Internalize,
-                              bool RunInliner);
+                              bool RunInliner, bool DisableGVNLoadPRE =3D =
false);
 };
+
 /// Registers a function for adding a standard set of passes.  This should=
 be
 /// used by optimizer plugins to allow all front ends to transparently use
 /// them.  Create a static instance of this class in your plugin, providin=
g a
@@ -129,5 +144,6 @@
     PassManagerBuilder::addGlobalExtension(Ty, Fn);
   }
 };
+
 } // end namespace llvm
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Instrumentation.h
--- a/head/contrib/llvm/include/llvm/Transforms/Instrumentation.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Instrumentation.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 namespace llvm {
=20
 class ModulePass;
+class FunctionPass;
=20
 // Insert edge profiling instrumentation
 ModulePass *createEdgeProfilerPass();
@@ -29,7 +30,13 @@
=20
 // Insert GCOV profiling instrumentation
 ModulePass *createGCOVProfilerPass(bool EmitNotes =3D true, bool EmitData =
=3D true,
-                                   bool Use402Format =3D false);
+                                   bool Use402Format =3D false,
+                                   bool UseExtraChecksum =3D false);
+
+// Insert AddressSanitizer (address sanity checking) instrumentation
+ModulePass *createAddressSanitizerPass();
+// Insert ThreadSanitizer (race detection) instrumentation
+FunctionPass *createThreadSanitizerPass();
=20
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Scalar.h
--- a/head/contrib/llvm/include/llvm/Transforms/Scalar.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Scalar.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -112,6 +112,8 @@
 //
 Pass *createLoopStrengthReducePass(const TargetLowering *TLI =3D 0);
=20
+Pass *createGlobalMergePass(const TargetLowering *TLI =3D 0);
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // LoopUnswitch - This pass is a simple loop unswitching pass.
@@ -307,12 +309,6 @@
  =20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-// GEPSplitter - Split complex GEPs into simple ones
-//
-FunctionPass *createGEPSplitterPass();
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//
 // Sink - Code Sinking
 //
 FunctionPass *createSinkingPass();
@@ -331,6 +327,12 @@
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
+// ObjCARCAPElim - ObjC ARC autorelease pool elimination.
+//
+Pass *createObjCARCAPElimPass();
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//
 // ObjCARCExpand - ObjC ARC preliminary simplifications.
 //
 Pass *createObjCARCExpandPass();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/BasicBlockUtils.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -173,9 +173,8 @@
 /// complicated to handle the case where one of the edges being split
 /// is an exit of a loop with other exits).
 ///
-BasicBlock *SplitBlockPredecessors(BasicBlock *BB, BasicBlock *const *Pred=
s,
-                                   unsigned NumPreds, const char *Suffix,
-                                   Pass *P =3D 0);
+BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock*> P=
reds,
+                                   const char *Suffix, Pass *P =3D 0);
=20
 /// SplitLandingPadPredecessors - This method transforms the landing pad,
 /// OrigBB, by introducing two new basic blocks into the function. One of =
those
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/BuildLibCalls.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/BuildLibCalls.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/BuildLibCalls.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 namespace llvm {
   class Value;
   class TargetData;
+  class TargetLibraryInfo;
  =20
   /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
   Value *CastToCStr(Value *V, IRBuilder<> &B);
@@ -68,7 +69,7 @@
   /// 'Op' and returns one value with the same type.  If 'Op' is a long do=
uble,
   /// 'l' is added as the suffix of name, if 'Op' is a float, we add a 'f'
   /// suffix.
-  Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
+  Value *EmitUnaryFloatFnCall(Value *Op, StringRef Name, IRBuilder<> &B,
                               const AttrListPtr &Attrs);
=20
   /// EmitPutChar - Emit a call to the putchar function.  This assumes tha=
t Char
@@ -86,12 +87,13 @@
=20
   /// EmitFPutS - Emit a call to the puts function.  Str is required to be=
 a
   /// pointer and File is a pointer to FILE.
-  void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B, const TargetData=
 *TD);
+  void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B, const TargetData=
 *TD,
+                 const TargetLibraryInfo *TLI);
=20
   /// EmitFWrite - Emit a call to the fwrite function.  This assumes that =
Ptr is
   /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
   void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B,
-                  const TargetData *TD);
+                  const TargetData *TD, const TargetLibraryInfo *TLI);
=20
   /// SimplifyFortifiedLibCalls - Helper class for folding checked library
   /// calls (e.g. __strcpy_chk) into their unchecked counterparts.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/Cloning.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/Cloning.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/Cloning.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -56,21 +56,13 @@
   /// call instruction.
   bool ContainsCalls;
  =20
-  /// ContainsUnwinds - This is set to true if the cloned code contains an
-  /// unwind instruction.
-  bool ContainsUnwinds;
- =20
   /// ContainsDynamicAllocas - This is set to true if the cloned code cont=
ains
   /// a 'dynamic' alloca.  Dynamic allocas are allocas that are either not=
 in
   /// the entry block or they are in the entry block but are not a constant
   /// size.
   bool ContainsDynamicAllocas;
  =20
-  ClonedCodeInfo() {
-    ContainsCalls =3D false;
-    ContainsUnwinds =3D false;
-    ContainsDynamicAllocas =3D false;
-  }
+  ClonedCodeInfo() : ContainsCalls(false), ContainsDynamicAllocas(false) {}
 };
=20
=20
@@ -134,8 +126,8 @@
 /// Clone OldFunc into NewFunc, transforming the old arguments into refere=
nces
 /// to VMap values.  Note that if NewFunc already has basic blocks, the on=
es
 /// cloned into it will be added to the end of the function.  This function
-/// fills in a list of return instructions, and can optionally append the
-/// specified suffix to all values cloned.
+/// fills in a list of return instructions, and can optionally remap types
+/// and/or append the specified suffix to all values cloned.
 ///
 /// If ModuleLevelChanges is false, VMap contains no non-identity GlobalVa=
lue
 /// mappings.
@@ -145,7 +137,8 @@
                        bool ModuleLevelChanges,
                        SmallVectorImpl<ReturnInst*> &Returns,
                        const char *NameSuffix =3D "",=20
-                       ClonedCodeInfo *CodeInfo =3D 0);
+                       ClonedCodeInfo *CodeInfo =3D 0,
+                       ValueMapTypeRemapper *TypeMapper =3D 0);
=20
 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
 /// except that it does some simple constant prop and DCE on the fly.  The
@@ -204,9 +197,9 @@
 /// exists in the instruction stream.  Similarly this will inline a recurs=
ive
 /// function by one level.
 ///
-bool InlineFunction(CallInst *C, InlineFunctionInfo &IFI);
-bool InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI);
-bool InlineFunction(CallSite CS, InlineFunctionInfo &IFI);
+bool InlineFunction(CallInst *C, InlineFunctionInfo &IFI, bool InsertLifet=
ime =3D true);
+bool InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI, bool InsertLi=
fetime =3D true);
+bool InlineFunction(CallSite CS, InlineFunctionInfo &IFI, bool InsertLifet=
ime =3D true);
=20
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/SSAUpdater.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/SSAUpdater.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/SSAUpdater.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -14,16 +14,18 @@
 #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATER_H
 #define LLVM_TRANSFORMS_UTILS_SSAUPDATER_H
=20
+#include "llvm/ADT/StringRef.h"
+
 namespace llvm {
-  class Value;
   class BasicBlock;
-  class Use;
-  class PHINode;
+  class Instruction;
+  class LoadInst;
   template<typename T> class SmallVectorImpl;
   template<typename T> class SSAUpdaterTraits;
-  class DbgDeclareInst;
-  class DIBuilder;
-  class BumpPtrAllocator;
+  class PHINode;
+  class Type;
+  class Use;
+  class Value;
=20
 /// SSAUpdater - This class updates SSA form for a set of values defined in
 /// multiple blocks.  This is used when code duplication or another unstru=
ctured
@@ -137,12 +139,7 @@
   /// passed into the run method).  Clients should implement this with a m=
ore
   /// efficient version if possible.
   virtual bool isInstInList(Instruction *I,
-                            const SmallVectorImpl<Instruction*> &Insts) co=
nst {
-    for (unsigned i =3D 0, e =3D Insts.size(); i !=3D e; ++i)
-      if (Insts[i] =3D=3D I)
-        return true;
-    return false;
-  }
+                            const SmallVectorImpl<Instruction*> &Insts) co=
nst;
  =20
   /// doExtraRewritesBeforeFinalDeletion - This hook is invoked after all =
the
   /// stores are found and inserted as available values, but=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/SSAUpdaterImpl.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/SSAUpdaterImpl.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/SSAUpdaterImpl.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -15,8 +15,16 @@
 #ifndef LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
 #define LLVM_TRANSFORMS_UTILS_SSAUPDATERIMPL_H
=20
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Allocator.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/ValueHandle.h"
+
 namespace llvm {
=20
+class CastInst;
+class PHINode;
 template<typename T> class SSAUpdaterTraits;
=20
 template<typename UpdaterT>
@@ -372,7 +380,7 @@
       if (!SomePHI)
         break;
       if (CheckIfPHIMatches(SomePHI)) {
-        RecordMatchingPHI(SomePHI);
+        RecordMatchingPHIs(BlockList);
         break;
       }
       // Match failed: clear all the PHITag values.
@@ -429,38 +437,17 @@
     return true;
   }
=20
-  /// RecordMatchingPHI - For a PHI node that matches, record it and its i=
nput
-  /// PHIs in both the BBMap and the AvailableVals mapping.
-  void RecordMatchingPHI(PhiT *PHI) {
-    SmallVector<PhiT*, 20> WorkList;
-    WorkList.push_back(PHI);
-
-    // Record this PHI.
-    BlkT *BB =3D PHI->getParent();
-    ValT PHIVal =3D Traits::GetPHIValue(PHI);
-    (*AvailableVals)[BB] =3D PHIVal;
-    BBMap[BB]->AvailableVal =3D PHIVal;
-
-    while (!WorkList.empty()) {
-      PHI =3D WorkList.pop_back_val();
-
-      // Iterate through the PHI's incoming values.
-      for (typename Traits::PHI_iterator I =3D Traits::PHI_begin(PHI),
-             E =3D Traits::PHI_end(PHI); I !=3D E; ++I) {
-        ValT IncomingVal =3D I.getIncomingValue();
-        PhiT *IncomingPHI =3D Traits::ValueIsPHI(IncomingVal, Updater);
-        if (!IncomingPHI) continue;
-        BB =3D IncomingPHI->getParent();
-        BBInfo *Info =3D BBMap[BB];
-        if (!Info || Info->AvailableVal)
-          continue;
-
-        // Record the PHI and add it to the worklist.
-        (*AvailableVals)[BB] =3D IncomingVal;
-        Info->AvailableVal =3D IncomingVal;
-        WorkList.push_back(IncomingPHI);
+  /// RecordMatchingPHIs - For each PHI node that matches, record it in bo=
th
+  /// the BBMap and the AvailableVals mapping.
+  void RecordMatchingPHIs(BlockListTy *BlockList) {
+    for (typename BlockListTy::iterator I =3D BlockList->begin(),
+           E =3D BlockList->end(); I !=3D E; ++I)
+      if (PhiT *PHI =3D (*I)->PHITag) {
+        BlkT *BB =3D PHI->getParent();
+        ValT PHIVal =3D Traits::GetPHIValue(PHI);
+        (*AvailableVals)[BB] =3D PHIVal;
+        BBMap[BB]->AvailableVal =3D PHIVal;
       }
-    }
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/SimplifyIndVar.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/SimplifyIndVar.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/SimplifyIndVar.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -17,21 +17,23 @@
 #define LLVM_TRANSFORMS_UTILS_SIMPLIFYINDVAR_H
=20
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ValueHandle.h"
=20
 namespace llvm {
=20
 extern cl::opt<bool> DisableIVRewrite;
=20
+class CastInst;
+class IVUsers;
 class Loop;
-class LoopInfo;
-class DominatorTree;
+class LPPassManager;
+class PHINode;
 class ScalarEvolution;
-class LPPassManager;
-class IVUsers;
=20
 /// Interface for visiting interesting IV users that are recognized but not
 /// simplified by this utility.
 class IVVisitor {
+  virtual void anchor();
 public:
   virtual ~IVVisitor() {}
   virtual void visitCast(CastInst *Cast) =3D 0;
@@ -47,12 +49,6 @@
 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, LPPassManager *LPM,
                      SmallVectorImpl<WeakVH> &Dead);
=20
-/// simplifyIVUsers - Simplify instructions recorded by the IVUsers pass.
-/// This is a legacy implementation to reproduce the behavior of the
-/// IndVarSimplify pass prior to DisableIVRewrite.
-bool simplifyIVUsers(IVUsers *IU, ScalarEvolution *SE, LPPassManager *LPM,
-                     SmallVectorImpl<WeakVH> &Dead);
-
 } // namespace llvm
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/UnrollLoop.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/UnrollLoop.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/UnrollLoop.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -22,9 +22,12 @@
 class LoopInfo;
 class LPPassManager;
=20
-bool UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
+bool UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, bool AllowRun=
time,
                 unsigned TripMultiple, LoopInfo* LI, LPPassManager* LPM);
=20
+bool UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
+                             LPPassManager* LPM);
+
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Transfo=
rms/Utils/ValueMapper.h
--- a/head/contrib/llvm/include/llvm/Transforms/Utils/ValueMapper.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Transforms/Utils/ValueMapper.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -20,7 +20,7 @@
 namespace llvm {
   class Value;
   class Instruction;
-  typedef ValueMap<const Value *, TrackingVH<Value> > ValueToValueMapTy;
+  typedef ValueMap<const Value *, WeakVH> ValueToValueMapTy;
=20
   /// ValueMapTypeRemapper - This is a class that can be implemented by cl=
ients
   /// to remap types when cloning constants and instructions.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Type.h
--- a/head/contrib/llvm/include/llvm/Type.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Type.h	Tue Apr 17 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #define LLVM_TYPE_H
=20
 #include "llvm/Support/Casting.h"
+#include "llvm/Support/DataTypes.h"
=20
 namespace llvm {
=20
@@ -25,6 +26,7 @@
 class Module;
 class LLVMContext;
 class LLVMContextImpl;
+class StringRef;
 template<class GraphType> struct GraphTraits;
=20
 /// The instances of the Type class are immutable: once they are created,
@@ -47,23 +49,24 @@
   enum TypeID {
     // PrimitiveTypes - make sure LastPrimitiveTyID stays up to date.
     VoidTyID =3D 0,    ///<  0: type with no size
-    FloatTyID,       ///<  1: 32-bit floating point type
-    DoubleTyID,      ///<  2: 64-bit floating point type
-    X86_FP80TyID,    ///<  3: 80-bit floating point type (X87)
-    FP128TyID,       ///<  4: 128-bit floating point type (112-bit mantiss=
a)
-    PPC_FP128TyID,   ///<  5: 128-bit floating point type (two 64-bits, Po=
werPC)
-    LabelTyID,       ///<  6: Labels
-    MetadataTyID,    ///<  7: Metadata
-    X86_MMXTyID,     ///<  8: MMX vectors (64 bits, X86 specific)
+    HalfTyID,        ///<  1: 16-bit floating point type
+    FloatTyID,       ///<  2: 32-bit floating point type
+    DoubleTyID,      ///<  3: 64-bit floating point type
+    X86_FP80TyID,    ///<  4: 80-bit floating point type (X87)
+    FP128TyID,       ///<  5: 128-bit floating point type (112-bit mantiss=
a)
+    PPC_FP128TyID,   ///<  6: 128-bit floating point type (two 64-bits, Po=
werPC)
+    LabelTyID,       ///<  7: Labels
+    MetadataTyID,    ///<  8: Metadata
+    X86_MMXTyID,     ///<  9: MMX vectors (64 bits, X86 specific)
=20
     // Derived types... see DerivedTypes.h file.
     // Make sure FirstDerivedTyID stays up to date!
-    IntegerTyID,     ///<  9: Arbitrary bit width integers
-    FunctionTyID,    ///< 10: Functions
-    StructTyID,      ///< 11: Structures
-    ArrayTyID,       ///< 12: Arrays
-    PointerTyID,     ///< 13: Pointers
-    VectorTyID,      ///< 14: SIMD 'packed' format, or other vector type
+    IntegerTyID,     ///< 10: Arbitrary bit width integers
+    FunctionTyID,    ///< 11: Functions
+    StructTyID,      ///< 12: Structures
+    ArrayTyID,       ///< 13: Arrays
+    PointerTyID,     ///< 14: Pointers
+    VectorTyID,      ///< 15: SIMD 'packed' format, or other vector type
=20
     NumTypeIDs,                         // Must remain as last defined ID
     LastPrimitiveTyID =3D X86_MMXTyID,
@@ -74,21 +77,32 @@
   /// Context - This refers to the LLVMContext in which this type was uniq=
ued.
   LLVMContext &Context;
=20
-  TypeID   ID : 8;            // The current base type of this type.
-  unsigned SubclassData : 24; // Space for subclasses to store data
+  // Due to Ubuntu GCC bug 910363:
+  // https://bugs.launchpad.net/ubuntu/+source/gcc-4.5/+bug/910363
+  // Bitpack ID and SubclassData manually.
+  // Note: TypeID : low 8 bit; SubclassData : high 24 bit.
+  uint32_t IDAndSubclassData;
=20
 protected:
   friend class LLVMContextImpl;
   explicit Type(LLVMContext &C, TypeID tid)
-    : Context(C), ID(tid), SubclassData(0),
-      NumContainedTys(0), ContainedTys(0) {}
+    : Context(C), IDAndSubclassData(0),
+      NumContainedTys(0), ContainedTys(0) {
+    setTypeID(tid);
+  }
   ~Type() {}
-
-  unsigned getSubclassData() const { return SubclassData; }
+ =20
+  void setTypeID(TypeID ID) {
+    IDAndSubclassData =3D (ID & 0xFF) | (IDAndSubclassData & 0xFFFFFF00);
+    assert(getTypeID() =3D=3D ID && "TypeID data too large for field");
+  }
+ =20
+  unsigned getSubclassData() const { return IDAndSubclassData >> 8; }
+ =20
   void setSubclassData(unsigned val) {
-    SubclassData =3D val;
+    IDAndSubclassData =3D (IDAndSubclassData & 0xFF) | (val << 8);
     // Ensure we don't have any accidental truncation.
-    assert(SubclassData =3D=3D val && "Subclass data too large for field");
+    assert(getSubclassData() =3D=3D val && "Subclass data too large for fi=
eld");
   }
=20
   /// NumContainedTys - Keeps track of how many Type*'s there are in the
@@ -116,49 +130,54 @@
   /// getTypeID - Return the type id for the type.  This will return one
   /// of the TypeID enum elements defined above.
   ///
-  TypeID getTypeID() const { return ID; }
+  TypeID getTypeID() const { return (TypeID)(IDAndSubclassData & 0xFF); }
=20
   /// isVoidTy - Return true if this is 'void'.
-  bool isVoidTy() const { return ID =3D=3D VoidTyID; }
+  bool isVoidTy() const { return getTypeID() =3D=3D VoidTyID; }
+
+  /// isHalfTy - Return true if this is 'half', a 16-bit IEEE fp type.
+  bool isHalfTy() const { return getTypeID() =3D=3D HalfTyID; }
=20
   /// isFloatTy - Return true if this is 'float', a 32-bit IEEE fp type.
-  bool isFloatTy() const { return ID =3D=3D FloatTyID; }
+  bool isFloatTy() const { return getTypeID() =3D=3D FloatTyID; }
  =20
   /// isDoubleTy - Return true if this is 'double', a 64-bit IEEE fp type.
-  bool isDoubleTy() const { return ID =3D=3D DoubleTyID; }
+  bool isDoubleTy() const { return getTypeID() =3D=3D DoubleTyID; }
=20
   /// isX86_FP80Ty - Return true if this is x86 long double.
-  bool isX86_FP80Ty() const { return ID =3D=3D X86_FP80TyID; }
+  bool isX86_FP80Ty() const { return getTypeID() =3D=3D X86_FP80TyID; }
=20
   /// isFP128Ty - Return true if this is 'fp128'.
-  bool isFP128Ty() const { return ID =3D=3D FP128TyID; }
+  bool isFP128Ty() const { return getTypeID() =3D=3D FP128TyID; }
=20
   /// isPPC_FP128Ty - Return true if this is powerpc long double.
-  bool isPPC_FP128Ty() const { return ID =3D=3D PPC_FP128TyID; }
+  bool isPPC_FP128Ty() const { return getTypeID() =3D=3D PPC_FP128TyID; }
=20
   /// isFloatingPointTy - Return true if this is one of the five floating =
point
   /// types
   bool isFloatingPointTy() const {
-    return ID =3D=3D FloatTyID || ID =3D=3D DoubleTyID ||
-      ID =3D=3D X86_FP80TyID || ID =3D=3D FP128TyID || ID =3D=3D PPC_FP128=
TyID;
+    return getTypeID() =3D=3D HalfTyID || getTypeID() =3D=3D FloatTyID ||
+           getTypeID() =3D=3D DoubleTyID ||
+           getTypeID() =3D=3D X86_FP80TyID || getTypeID() =3D=3D FP128TyID=
 ||
+           getTypeID() =3D=3D PPC_FP128TyID;
   }
=20
   /// isX86_MMXTy - Return true if this is X86 MMX.
-  bool isX86_MMXTy() const { return ID =3D=3D X86_MMXTyID; }
+  bool isX86_MMXTy() const { return getTypeID() =3D=3D X86_MMXTyID; }
=20
   /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of F=
P.
   ///
   bool isFPOrFPVectorTy() const;
 =20
   /// isLabelTy - Return true if this is 'label'.
-  bool isLabelTy() const { return ID =3D=3D LabelTyID; }
+  bool isLabelTy() const { return getTypeID() =3D=3D LabelTyID; }
=20
   /// isMetadataTy - Return true if this is 'metadata'.
-  bool isMetadataTy() const { return ID =3D=3D MetadataTyID; }
+  bool isMetadataTy() const { return getTypeID() =3D=3D MetadataTyID; }
=20
   /// isIntegerTy - True if this is an instance of IntegerType.
   ///
-  bool isIntegerTy() const { return ID =3D=3D IntegerTyID; }=20
+  bool isIntegerTy() const { return getTypeID() =3D=3D IntegerTyID; }=20
=20
   /// isIntegerTy - Return true if this is an IntegerType of the given wid=
th.
   bool isIntegerTy(unsigned Bitwidth) const;
@@ -170,23 +189,23 @@
  =20
   /// isFunctionTy - True if this is an instance of FunctionType.
   ///
-  bool isFunctionTy() const { return ID =3D=3D FunctionTyID; }
+  bool isFunctionTy() const { return getTypeID() =3D=3D FunctionTyID; }
=20
   /// isStructTy - True if this is an instance of StructType.
   ///
-  bool isStructTy() const { return ID =3D=3D StructTyID; }
+  bool isStructTy() const { return getTypeID() =3D=3D StructTyID; }
=20
   /// isArrayTy - True if this is an instance of ArrayType.
   ///
-  bool isArrayTy() const { return ID =3D=3D ArrayTyID; }
+  bool isArrayTy() const { return getTypeID() =3D=3D ArrayTyID; }
=20
   /// isPointerTy - True if this is an instance of PointerType.
   ///
-  bool isPointerTy() const { return ID =3D=3D PointerTyID; }
+  bool isPointerTy() const { return getTypeID() =3D=3D PointerTyID; }
=20
   /// isVectorTy - True if this is an instance of VectorType.
   ///
-  bool isVectorTy() const { return ID =3D=3D VectorTyID; }
+  bool isVectorTy() const { return getTypeID() =3D=3D VectorTyID; }
=20
   /// canLosslesslyBitCastTo - Return true if this type could be converted=20
   /// with a lossless BitCast to type 'Ty'. For example, i8* to i32*. BitC=
asts=20
@@ -202,14 +221,14 @@
   /// Here are some useful little methods to query what type derived types=
 are
   /// Note that all other types can just compare to see if this =3D=3D Typ=
e::xxxTy;
   ///
-  bool isPrimitiveType() const { return ID <=3D LastPrimitiveTyID; }
-  bool isDerivedType()   const { return ID >=3D FirstDerivedTyID; }
+  bool isPrimitiveType() const { return getTypeID() <=3D LastPrimitiveTyID=
; }
+  bool isDerivedType()   const { return getTypeID() >=3D FirstDerivedTyID;=
 }
=20
   /// isFirstClassType - Return true if the type is "first class", meaning=
 it
   /// is a valid type for a Value.
   ///
   bool isFirstClassType() const {
-    return ID !=3D FunctionTyID && ID !=3D VoidTyID;
+    return getTypeID() !=3D FunctionTyID && getTypeID() !=3D VoidTyID;
   }
=20
   /// isSingleValueType - Return true if the type is a valid type for a
@@ -217,8 +236,9 @@
   /// and array types.
   ///
   bool isSingleValueType() const {
-    return (ID !=3D VoidTyID && isPrimitiveType()) ||
-            ID =3D=3D IntegerTyID || ID =3D=3D PointerTyID || ID =3D=3D Ve=
ctorTyID;
+    return (getTypeID() !=3D VoidTyID && isPrimitiveType()) ||
+            getTypeID() =3D=3D IntegerTyID || getTypeID() =3D=3D PointerTy=
ID ||
+            getTypeID() =3D=3D VectorTyID;
   }
=20
   /// isAggregateType - Return true if the type is an aggregate type. This
@@ -227,7 +247,7 @@
   /// does not include vector types.
   ///
   bool isAggregateType() const {
-    return ID =3D=3D StructTyID || ID =3D=3D ArrayTyID;
+    return getTypeID() =3D=3D StructTyID || getTypeID() =3D=3D ArrayTyID;
   }
=20
   /// isSized - Return true if it makes sense to take the size of this typ=
e.  To
@@ -236,12 +256,14 @@
   ///
   bool isSized() const {
     // If it's a primitive, it is always sized.
-    if (ID =3D=3D IntegerTyID || isFloatingPointTy() || ID =3D=3D PointerT=
yID ||
-        ID =3D=3D X86_MMXTyID)
+    if (getTypeID() =3D=3D IntegerTyID || isFloatingPointTy() ||
+        getTypeID() =3D=3D PointerTyID ||
+        getTypeID() =3D=3D X86_MMXTyID)
       return true;
     // If it is not something that can have a size (e.g. a function or lab=
el),
     // it doesn't have a size.
-    if (ID !=3D StructTyID && ID !=3D ArrayTyID && ID !=3D VectorTyID)
+    if (getTypeID() !=3D StructTyID && getTypeID() !=3D ArrayTyID &&
+        getTypeID() !=3D VectorTyID)
       return false;
     // Otherwise we have to try harder to decide.
     return isSizedDerivedType();
@@ -294,6 +316,34 @@
   unsigned getNumContainedTypes() const { return NumContainedTys; }
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
+  // Helper methods corresponding to subclass methods.  This forces a cast=
 to
+  // the specified subclass and calls its accessor.  "getVectorNumElements=
" (for
+  // example) is shorthand for cast<VectorType>(Ty)->getNumElements().  Th=
is is
+  // only intended to cover the core methods that are frequently used, hel=
per
+  // methods should not be added here.
+ =20
+  unsigned getIntegerBitWidth() const;
+
+  Type *getFunctionParamType(unsigned i) const;
+  unsigned getFunctionNumParams() const;
+  bool isFunctionVarArg() const;
+ =20
+  StringRef getStructName() const;
+  unsigned getStructNumElements() const;
+  Type *getStructElementType(unsigned N) const;
+ =20
+  Type *getSequentialElementType() const;
+ =20
+  uint64_t getArrayNumElements() const;
+  Type *getArrayElementType() const { return getSequentialElementType(); }
+
+  unsigned getVectorNumElements() const;
+  Type *getVectorElementType() const { return getSequentialElementType(); }
+
+  unsigned getPointerAddressSpace() const;
+  Type *getPointerElementType() const { return getSequentialElementType();=
 }
+ =20
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Static members exported by the Type class itself.  Useful for getting
   // instances of Type.
   //
@@ -306,6 +356,7 @@
   //
   static Type *getVoidTy(LLVMContext &C);
   static Type *getLabelTy(LLVMContext &C);
+  static Type *getHalfTy(LLVMContext &C);
   static Type *getFloatTy(LLVMContext &C);
   static Type *getDoubleTy(LLVMContext &C);
   static Type *getMetadataTy(LLVMContext &C);
@@ -324,6 +375,7 @@
   // Convenience methods for getting pointer types with one of the above b=
uiltin
   // types as pointee.
   //
+  static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS =3D 0);
   static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS =3D 0);
   static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS =3D 0);
   static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS =3D 0);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/User.h
--- a/head/contrib/llvm/include/llvm/User.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/User.h	Tue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #ifndef LLVM_USER_H
 #define LLVM_USER_H
=20
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Value.h"
=20
 namespace llvm {
@@ -34,6 +35,7 @@
   void *operator new(size_t);     // Do not implement
   template <unsigned>
   friend struct HungoffOperandTraits;
+  virtual void anchor();
 protected:
   /// OperandList - This is a pointer to the array of Uses for this User.
   /// For nodes of fixed arity (e.g. a binary operator) this array will li=
ve
@@ -64,11 +66,11 @@
   void operator delete(void *Usr);
   /// placement delete - required by std, but never called.
   void operator delete(void*, unsigned) {
-    assert(0 && "Constructor throws?");
+    llvm_unreachable("Constructor throws?");
   }
   /// placement delete - required by std, but never called.
   void operator delete(void*, unsigned, bool) {
-    assert(0 && "Constructor throws?");
+    llvm_unreachable("Constructor throws?");
   }
 protected:
   template <int Idx, typename U> static Use &OpFrom(const U *that) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/include/llvm/Value.h
--- a/head/contrib/llvm/include/llvm/Value.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/include/llvm/Value.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,7 @@
 #define LLVM_VALUE_H
=20
 #include "llvm/Use.h"
-#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Casting.h"
-#include <string>
=20
 namespace llvm {
=20
@@ -32,8 +30,6 @@
 class InlineAsm;
 class ValueSymbolTable;
 template<typename ValueTy> class StringMapEntry;
-template <typename ValueTy =3D Value>
-class AssertingVH;
 typedef StringMapEntry<Value*> ValueName;
 class raw_ostream;
 class AssemblyAnnotationWriter;
@@ -42,6 +38,7 @@
 class Twine;
 class MDNode;
 class Type;
+class StringRef;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                                 Value Class
@@ -110,26 +107,16 @@
   /// All values hold a context through their type.
   LLVMContext &getContext() const;
=20
-  // All values can potentially be named...
-  bool hasName() const { return Name !=3D 0; }
+  // All values can potentially be named.
+  bool hasName() const { return Name !=3D 0 && SubclassID !=3D MDStringVal=
; }
   ValueName *getValueName() const { return Name; }
+  void setValueName(ValueName *VN) { Name =3D VN; }
  =20
   /// getName() - Return a constant reference to the value's name. This is=
 cheap
   /// and guaranteed to return the same reference as long as the value is =
not
   /// modified.
-  ///
-  /// This is currently guaranteed to return a StringRef for which data() =
points
-  /// to a valid null terminated string. The use of StringRef.data() is=20
-  /// deprecated here, however, and clients should not rely on it. If such=20
-  /// behavior is needed, clients should use expensive getNameStr(), or sw=
itch=20
-  /// to an interface that does not depend on null termination.
   StringRef getName() const;
=20
-  /// getNameStr() - Return the name of the specified value, *constructing=
 a
-  /// string* to hold it.  This is guaranteed to construct a string and is=
 very
-  /// expensive, clients should use getName() unless necessary.
-  std::string getNameStr() const;
-
   /// setName() - Change the name of the value, choosing a new unique name=
 if
   /// the provided name is taken.
   ///
@@ -205,6 +192,8 @@
     BlockAddressVal,          // This is an instance of BlockAddress
     ConstantExprVal,          // This is an instance of ConstantExpr
     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZ=
ero
+    ConstantDataArrayVal,     // This is an instance of ConstantDataArray
+    ConstantDataVectorVal,    // This is an instance of ConstantDataVector
     ConstantIntVal,           // This is an instance of ConstantInt
     ConstantFPVal,            // This is an instance of ConstantFP
     ConstantArrayVal,         // This is an instance of ConstantArray
@@ -273,14 +262,32 @@
     return true; // Values are always values.
   }
=20
-  /// stripPointerCasts - This method strips off any unneeded pointer
-  /// casts from the specified value, returning the original uncasted valu=
e.
-  /// Note that the returned value has pointer type if the specified value=
 does.
+  /// stripPointerCasts - This method strips off any unneeded pointer cast=
s and
+  /// all-zero GEPs from the specified value, returning the original uncas=
ted
+  /// value. If this is called on a non-pointer value, it returns 'this'.
   Value *stripPointerCasts();
   const Value *stripPointerCasts() const {
     return const_cast<Value*>(this)->stripPointerCasts();
   }
=20
+  /// stripInBoundsConstantOffsets - This method strips off unneeded point=
er casts and
+  /// all-constant GEPs from the specified value, returning the original
+  /// pointer value. If this is called on a non-pointer value, it returns
+  /// 'this'.
+  Value *stripInBoundsConstantOffsets();
+  const Value *stripInBoundsConstantOffsets() const {
+    return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
+  }
+
+  /// stripInBoundsOffsets - This method strips off unneeded pointer casts=
 and
+  /// any in-bounds Offsets from the specified value, returning the origin=
al
+  /// pointer value. If this is called on a non-pointer value, it returns
+  /// 'this'.
+  Value *stripInBoundsOffsets();
+  const Value *stripInBoundsOffsets() const {
+    return const_cast<Value*>(this)->stripInBoundsOffsets();
+  }
+
   /// isDereferenceablePointer - Test if this value is always a pointer to
   /// allocated and suitably aligned memory for a simple load or store.
   bool isDereferenceablePointer() const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/AliasAn=
alysis.cpp
--- a/head/contrib/llvm/lib/Analysis/AliasAnalysis.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/AliasAnalysis.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -440,3 +440,19 @@
     return A->hasNoAliasAttr() || A->hasByValAttr();
   return false;
 }
+
+/// isKnownNonNull - Return true if we know that the specified value is ne=
ver
+/// null.
+bool llvm::isKnownNonNull(const Value *V) {
+  // Alloca never returns null, malloc might.
+  if (isa<AllocaInst>(V)) return true;
+
+  // A byval argument is never null.
+  if (const Argument *A =3D dyn_cast<Argument>(V))
+    return A->hasByValAttr();
+
+  // Global values are not null unless extern weak.
+  if (const GlobalValue *GV =3D dyn_cast<GlobalValue>(V))
+    return !GV->hasExternalWeakLinkage();
+  return false;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/AliasAn=
alysisCounter.cpp
--- a/head/contrib/llvm/lib/Analysis/AliasAnalysisCounter.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/AliasAnalysisCounter.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -127,9 +127,8 @@
 AliasAnalysisCounter::alias(const Location &LocA, const Location &LocB) {
   AliasResult R =3D getAnalysis<AliasAnalysis>().alias(LocA, LocB);
=20
-  const char *AliasString;
+  const char *AliasString =3D 0;
   switch (R) {
-  default: llvm_unreachable("Unknown alias type!");
   case NoAlias:   No++;   AliasString =3D "No alias"; break;
   case MayAlias:  May++;  AliasString =3D "May alias"; break;
   case PartialAlias: Partial++; AliasString =3D "Partial alias"; break;
@@ -154,9 +153,8 @@
                                     const Location &Loc) {
   ModRefResult R =3D getAnalysis<AliasAnalysis>().getModRefInfo(CS, Loc);
=20
-  const char *MRString;
+  const char *MRString =3D 0;
   switch (R) {
-  default:       llvm_unreachable("Unknown mod/ref type!");
   case NoModRef: NoMR++;     MRString =3D "NoModRef"; break;
   case Ref:      JustRef++;  MRString =3D "JustRef"; break;
   case Mod:      JustMod++;  MRString =3D "JustMod"; break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/AliasAn=
alysisEvaluator.cpp
--- a/head/contrib/llvm/lib/Analysis/AliasAnalysisEvaluator.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/AliasAnalysisEvaluator.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -193,8 +193,6 @@
       case AliasAnalysis::MustAlias:
         PrintResults("MustAlias", PrintMustAlias, *I1, *I2, F.getParent());
         ++MustAlias; break;
-      default:
-        errs() << "Unknown alias query result!\n";
       }
     }
   }
@@ -223,8 +221,6 @@
       case AliasAnalysis::ModRef:
         PrintModRefResults("Both ModRef", PrintModRef, I, *V, F.getParent(=
));
         ++ModRef; break;
-      default:
-        errs() << "Unknown alias query result!\n";
       }
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/AliasSe=
tTracker.cpp
--- a/head/contrib/llvm/lib/Analysis/AliasSetTracker.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/AliasSetTracker.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -189,7 +189,9 @@
   }
=20
   for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I)
-    if (AA.getModRefInfo(Inst, I.getPointer(), I.getSize()) !=3D
+    if (AA.getModRefInfo(Inst, AliasAnalysis::Location(I.getPointer(),
+                                                       I.getSize(),
+                                                       I.getTBAAInfo())) !=
=3D
            AliasAnalysis::NoModRef)
       return true;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/BasicAl=
iasAnalysis.cpp
--- a/head/contrib/llvm/lib/Analysis/BasicAliasAnalysis.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/BasicAliasAnalysis.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -42,22 +42,6 @@
 // Useful predicates
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-/// isKnownNonNull - Return true if we know that the specified value is ne=
ver
-/// null.
-static bool isKnownNonNull(const Value *V) {
-  // Alloca never returns null, malloc might.
-  if (isa<AllocaInst>(V)) return true;
- =20
-  // A byval argument is never null.
-  if (const Argument *A =3D dyn_cast<Argument>(V))
-    return A->hasByValAttr();
-
-  // Global values are not null unless extern weak.
-  if (const GlobalValue *GV =3D dyn_cast<GlobalValue>(V))
-    return !GV->hasExternalWeakLinkage();
-  return false;
-}
-
 /// isNonEscapingLocalObject - Return true if the pointer is to a function=
-local
 /// object that never escapes from the function.
 static bool isNonEscapingLocalObject(const Value *V) {
@@ -100,42 +84,59 @@
=20
 /// getObjectSize - Return the size of the object specified by V, or
 /// UnknownSize if unknown.
-static uint64_t getObjectSize(const Value *V, const TargetData &TD) {
+static uint64_t getObjectSize(const Value *V, const TargetData &TD,
+                              bool RoundToAlign =3D false) {
   Type *AccessTy;
+  unsigned Align;
   if (const GlobalVariable *GV =3D dyn_cast<GlobalVariable>(V)) {
     if (!GV->hasDefinitiveInitializer())
       return AliasAnalysis::UnknownSize;
     AccessTy =3D GV->getType()->getElementType();
+    Align =3D GV->getAlignment();
   } else if (const AllocaInst *AI =3D dyn_cast<AllocaInst>(V)) {
     if (!AI->isArrayAllocation())
       AccessTy =3D AI->getType()->getElementType();
     else
       return AliasAnalysis::UnknownSize;
+    Align =3D AI->getAlignment();
   } else if (const CallInst* CI =3D extractMallocCall(V)) {
-    if (!isArrayMalloc(V, &TD))
+    if (!RoundToAlign && !isArrayMalloc(V, &TD))
       // The size is the argument to the malloc call.
       if (const ConstantInt* C =3D dyn_cast<ConstantInt>(CI->getArgOperand=
(0)))
         return C->getZExtValue();
     return AliasAnalysis::UnknownSize;
   } else if (const Argument *A =3D dyn_cast<Argument>(V)) {
-    if (A->hasByValAttr())
+    if (A->hasByValAttr()) {
       AccessTy =3D cast<PointerType>(A->getType())->getElementType();
-    else
+      Align =3D A->getParamAlignment();
+    } else {
       return AliasAnalysis::UnknownSize;
+    }
   } else {
     return AliasAnalysis::UnknownSize;
   }
- =20
-  if (AccessTy->isSized())
-    return TD.getTypeAllocSize(AccessTy);
-  return AliasAnalysis::UnknownSize;
+
+  if (!AccessTy->isSized())
+    return AliasAnalysis::UnknownSize;
+
+  uint64_t Size =3D TD.getTypeAllocSize(AccessTy);
+  // If there is an explicitly specified alignment, and we need to
+  // take alignment into account, round up the size. (If the alignment
+  // is implicit, getTypeAllocSize is sufficient.)
+  if (RoundToAlign && Align)
+    Size =3D RoundUpToAlignment(Size, Align);
+
+  return Size;
 }
=20
 /// isObjectSmallerThan - Return true if we can prove that the object spec=
ified
 /// by V is smaller than Size.
 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
                                 const TargetData &TD) {
-  uint64_t ObjectSize =3D getObjectSize(V, TD);
+  // This function needs to use the aligned object size because we allow
+  // reads a bit past the end given sufficient alignment.
+  uint64_t ObjectSize =3D getObjectSize(V, TD, /*RoundToAlign*/true);
+ =20
   return ObjectSize !=3D AliasAnalysis::UnknownSize && ObjectSize < Size;
 }
=20
@@ -706,8 +707,7 @@
       // pointer were passed to arguments that were neither of these, then=
 it
       // couldn't be no-capture.
       if (!(*CI)->getType()->isPointerTy() ||
-          (!CS.paramHasAttr(ArgNo+1, Attribute::NoCapture) &&
-           !CS.paramHasAttr(ArgNo+1, Attribute::ByVal)))
+          (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
         continue;
      =20
       // If this is a no-capture pointer argument, see if we can tell that=
 it
@@ -978,10 +978,7 @@
   //
   // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
   // practical effect of this is protecting TBAA in the case of dynamic
-  // indices into arrays of unions. An alternative way to solve this would
-  // be to have clang emit extra metadata for unions and/or union accesses.
-  // A union-specific solution wouldn't handle the problem for malloc'd
-  // memory however.
+  // indices into arrays of unions or malloc'd memory.
   return PartialAlias;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/BlockFr=
equencyInfo.cpp
--- a/head/contrib/llvm/lib/Analysis/BlockFrequencyInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/BlockFrequencyInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -58,6 +58,6 @@
 /// that we should not rely on the value itself, but only on the compariso=
n to
 /// the other block frequencies. We do this to avoid using of floating poi=
nts.
 ///
-BlockFrequency BlockFrequencyInfo::getBlockFreq(BasicBlock *BB) const {
+BlockFrequency BlockFrequencyInfo::getBlockFreq(const BasicBlock *BB) cons=
t {
   return BFI->getBlockFreq(BB);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/BranchP=
robabilityInfo.cpp
--- a/head/contrib/llvm/lib/Analysis/BranchProbabilityInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/BranchProbabilityInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -12,11 +12,14 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Constants.h"
+#include "llvm/Function.h"
 #include "llvm/Instructions.h"
 #include "llvm/LLVMContext.h"
 #include "llvm/Metadata.h"
 #include "llvm/Analysis/BranchProbabilityInfo.h"
 #include "llvm/Analysis/LoopInfo.h"
+#include "llvm/ADT/PostOrderIterator.h"
+#include "llvm/Support/CFG.h"
 #include "llvm/Support/Debug.h"
=20
 using namespace llvm;
@@ -29,121 +32,118 @@
=20
 char BranchProbabilityInfo::ID =3D 0;
=20
-namespace {
-// Please note that BranchProbabilityAnalysis is not a FunctionPass.
-// It is created by BranchProbabilityInfo (which is a FunctionPass), which
-// provides a clear interface. Thanks to that, all heuristics and other
-// private methods are hidden in the .cpp file.
-class BranchProbabilityAnalysis {
+// Weights are for internal use only. They are used by heuristics to help =
to
+// estimate edges' probability. Example:
+//
+// Using "Loop Branch Heuristics" we predict weights of edges for the
+// block BB2.
+//         ...
+//          |
+//          V
+//         BB1<-+
+//          |   |
+//          |   | (Weight =3D 124)
+//          V   |
+//         BB2--+
+//          |
+//          | (Weight =3D 4)
+//          V
+//         BB3
+//
+// Probability of the edge BB2->BB1 =3D 124 / (124 + 4) =3D 0.96875
+// Probability of the edge BB2->BB3 =3D 4 / (124 + 4) =3D 0.03125
+static const uint32_t LBH_TAKEN_WEIGHT =3D 124;
+static const uint32_t LBH_NONTAKEN_WEIGHT =3D 4;
=20
-  typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
+/// \brief Unreachable-terminating branch taken weight.
+///
+/// This is the weight for a branch being taken to a block that terminates
+/// (eventually) in unreachable. These are predicted as unlikely as possib=
le.
+static const uint32_t UR_TAKEN_WEIGHT =3D 1;
=20
-  DenseMap<Edge, uint32_t> *Weights;
+/// \brief Unreachable-terminating branch not-taken weight.
+///
+/// This is the weight for a branch not being taken toward a block that
+/// terminates (eventually) in unreachable. Such a branch is essentially n=
ever
+/// taken. Set the weight to an absurdly high value so that nested loops d=
on't
+/// easily subsume it.
+static const uint32_t UR_NONTAKEN_WEIGHT =3D 1024*1024 - 1;
=20
-  BranchProbabilityInfo *BP;
+static const uint32_t PH_TAKEN_WEIGHT =3D 20;
+static const uint32_t PH_NONTAKEN_WEIGHT =3D 12;
=20
-  LoopInfo *LI;
+static const uint32_t ZH_TAKEN_WEIGHT =3D 20;
+static const uint32_t ZH_NONTAKEN_WEIGHT =3D 12;
=20
+static const uint32_t FPH_TAKEN_WEIGHT =3D 20;
+static const uint32_t FPH_NONTAKEN_WEIGHT =3D 12;
=20
-  // Weights are for internal use only. They are used by heuristics to hel=
p to
-  // estimate edges' probability. Example:
-  //
-  // Using "Loop Branch Heuristics" we predict weights of edges for the
-  // block BB2.
-  //         ...
-  //          |
-  //          V
-  //         BB1<-+
-  //          |   |
-  //          |   | (Weight =3D 124)
-  //          V   |
-  //         BB2--+
-  //          |
-  //          | (Weight =3D 4)
-  //          V
-  //         BB3
-  //
-  // Probability of the edge BB2->BB1 =3D 124 / (124 + 4) =3D 0.96875
-  // Probability of the edge BB2->BB3 =3D 4 / (124 + 4) =3D 0.03125
+// Standard weight value. Used when none of the heuristics set weight for
+// the edge.
+static const uint32_t NORMAL_WEIGHT =3D 16;
=20
-  static const uint32_t LBH_TAKEN_WEIGHT =3D 124;
-  static const uint32_t LBH_NONTAKEN_WEIGHT =3D 4;
+// Minimum weight of an edge. Please note, that weight is NEVER 0.
+static const uint32_t MIN_WEIGHT =3D 1;
=20
-  static const uint32_t RH_TAKEN_WEIGHT =3D 24;
-  static const uint32_t RH_NONTAKEN_WEIGHT =3D 8;
+static uint32_t getMaxWeightFor(BasicBlock *BB) {
+  return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
+}
=20
-  static const uint32_t PH_TAKEN_WEIGHT =3D 20;
-  static const uint32_t PH_NONTAKEN_WEIGHT =3D 12;
=20
-  static const uint32_t ZH_TAKEN_WEIGHT =3D 20;
-  static const uint32_t ZH_NONTAKEN_WEIGHT =3D 12;
-
-  // Standard weight value. Used when none of the heuristics set weight for
-  // the edge.
-  static const uint32_t NORMAL_WEIGHT =3D 16;
-
-  // Minimum weight of an edge. Please note, that weight is NEVER 0.
-  static const uint32_t MIN_WEIGHT =3D 1;
-
-  // Return TRUE if BB leads directly to a Return Instruction.
-  static bool isReturningBlock(BasicBlock *BB) {
-    SmallPtrSet<BasicBlock *, 8> Visited;
-
-    while (true) {
-      TerminatorInst *TI =3D BB->getTerminator();
-      if (isa<ReturnInst>(TI))
-        return true;
-
-      if (TI->getNumSuccessors() > 1)
-        break;
-
-      // It is unreachable block which we can consider as a return instruc=
tion.
-      if (TI->getNumSuccessors() =3D=3D 0)
-        return true;
-
-      Visited.insert(BB);
-      BB =3D TI->getSuccessor(0);
-
-      // Stop if cycle is detected.
-      if (Visited.count(BB))
-        return false;
-    }
-
+/// \brief Calculate edge weights for successors lead to unreachable.
+///
+/// Predict that a successor which leads necessarily to an
+/// unreachable-terminated block as extremely unlikely.
+bool BranchProbabilityInfo::calcUnreachableHeuristics(BasicBlock *BB) {
+  TerminatorInst *TI =3D BB->getTerminator();
+  if (TI->getNumSuccessors() =3D=3D 0) {
+    if (isa<UnreachableInst>(TI))
+      PostDominatedByUnreachable.insert(BB);
     return false;
   }
=20
-  uint32_t getMaxWeightFor(BasicBlock *BB) const {
-    return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
+  SmallPtrSet<BasicBlock *, 4> UnreachableEdges;
+  SmallPtrSet<BasicBlock *, 4> ReachableEdges;
+
+  for (succ_iterator I =3D succ_begin(BB), E =3D succ_end(BB); I !=3D E; +=
+I) {
+    if (PostDominatedByUnreachable.count(*I))
+      UnreachableEdges.insert(*I);
+    else
+      ReachableEdges.insert(*I);
   }
=20
-public:
-  BranchProbabilityAnalysis(DenseMap<Edge, uint32_t> *W,
-                            BranchProbabilityInfo *BP, LoopInfo *LI)
-    : Weights(W), BP(BP), LI(LI) {
-  }
+  // If all successors are in the set of blocks post-dominated by unreacha=
ble,
+  // this block is too.
+  if (UnreachableEdges.size() =3D=3D TI->getNumSuccessors())
+    PostDominatedByUnreachable.insert(BB);
=20
-  // Metadata Weights
-  bool calcMetadataWeights(BasicBlock *BB);
+  // Skip probabilities if this block has a single successor or if all were
+  // reachable.
+  if (TI->getNumSuccessors() =3D=3D 1 || UnreachableEdges.empty())
+    return false;
=20
-  // Return Heuristics
-  bool calcReturnHeuristics(BasicBlock *BB);
+  uint32_t UnreachableWeight =3D
+    std::max(UR_TAKEN_WEIGHT / UnreachableEdges.size(), MIN_WEIGHT);
+  for (SmallPtrSet<BasicBlock *, 4>::iterator I =3D UnreachableEdges.begin=
(),
+                                              E =3D UnreachableEdges.end();
+       I !=3D E; ++I)
+    setEdgeWeight(BB, *I, UnreachableWeight);
=20
-  // Pointer Heuristics
-  bool calcPointerHeuristics(BasicBlock *BB);
+  if (ReachableEdges.empty())
+    return true;
+  uint32_t ReachableWeight =3D
+    std::max(UR_NONTAKEN_WEIGHT / ReachableEdges.size(), NORMAL_WEIGHT);
+  for (SmallPtrSet<BasicBlock *, 4>::iterator I =3D ReachableEdges.begin(),
+                                              E =3D ReachableEdges.end();
+       I !=3D E; ++I)
+    setEdgeWeight(BB, *I, ReachableWeight);
=20
-  // Loop Branch Heuristics
-  bool calcLoopBranchHeuristics(BasicBlock *BB);
-
-  // Zero Heurestics
-  bool calcZeroHeuristics(BasicBlock *BB);
-
-  bool runOnFunction(Function &F);
-};
-} // end anonymous namespace
+  return true;
+}
=20
 // Propagate existing explicit probabilities from either profile data or
 // 'expect' intrinsic processing.
-bool BranchProbabilityAnalysis::calcMetadataWeights(BasicBlock *BB) {
+bool BranchProbabilityInfo::calcMetadataWeights(BasicBlock *BB) {
   TerminatorInst *TI =3D BB->getTerminator();
   if (TI->getNumSuccessors() =3D=3D 1)
     return false;
@@ -174,54 +174,14 @@
   }
   assert(Weights.size() =3D=3D TI->getNumSuccessors() && "Checked above");
   for (unsigned i =3D 0, e =3D TI->getNumSuccessors(); i !=3D e; ++i)
-    BP->setEdgeWeight(BB, TI->getSuccessor(i), Weights[i]);
+    setEdgeWeight(BB, TI->getSuccessor(i), Weights[i]);
=20
   return true;
 }
=20
-// Calculate Edge Weights using "Return Heuristics". Predict a successor w=
hich
-// leads directly to Return Instruction will not be taken.
-bool BranchProbabilityAnalysis::calcReturnHeuristics(BasicBlock *BB){
-  if (BB->getTerminator()->getNumSuccessors() =3D=3D 1)
-    return false;
-
-  SmallPtrSet<BasicBlock *, 4> ReturningEdges;
-  SmallPtrSet<BasicBlock *, 4> StayEdges;
-
-  for (succ_iterator I =3D succ_begin(BB), E =3D succ_end(BB); I !=3D E; +=
+I) {
-    BasicBlock *Succ =3D *I;
-    if (isReturningBlock(Succ))
-      ReturningEdges.insert(Succ);
-    else
-      StayEdges.insert(Succ);
-  }
-
-  if (uint32_t numStayEdges =3D StayEdges.size()) {
-    uint32_t stayWeight =3D RH_TAKEN_WEIGHT / numStayEdges;
-    if (stayWeight < NORMAL_WEIGHT)
-      stayWeight =3D NORMAL_WEIGHT;
-
-    for (SmallPtrSet<BasicBlock *, 4>::iterator I =3D StayEdges.begin(),
-         E =3D StayEdges.end(); I !=3D E; ++I)
-      BP->setEdgeWeight(BB, *I, stayWeight);
-  }
-
-  if (uint32_t numRetEdges =3D ReturningEdges.size()) {
-    uint32_t retWeight =3D RH_NONTAKEN_WEIGHT / numRetEdges;
-    if (retWeight < MIN_WEIGHT)
-      retWeight =3D MIN_WEIGHT;
-    for (SmallPtrSet<BasicBlock *, 4>::iterator I =3D ReturningEdges.begin=
(),
-         E =3D ReturningEdges.end(); I !=3D E; ++I) {
-      BP->setEdgeWeight(BB, *I, retWeight);
-    }
-  }
-
-  return ReturningEdges.size() > 0;
-}
-
 // Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
 // between two pointer or pointer and NULL will fail.
-bool BranchProbabilityAnalysis::calcPointerHeuristics(BasicBlock *BB) {
+bool BranchProbabilityInfo::calcPointerHeuristics(BasicBlock *BB) {
   BranchInst * BI =3D dyn_cast<BranchInst>(BB->getTerminator());
   if (!BI || !BI->isConditional())
     return false;
@@ -249,16 +209,14 @@
   if (!isProb)
     std::swap(Taken, NonTaken);
=20
-  BP->setEdgeWeight(BB, Taken, PH_TAKEN_WEIGHT);
-  BP->setEdgeWeight(BB, NonTaken, PH_NONTAKEN_WEIGHT);
+  setEdgeWeight(BB, Taken, PH_TAKEN_WEIGHT);
+  setEdgeWeight(BB, NonTaken, PH_NONTAKEN_WEIGHT);
   return true;
 }
=20
 // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
 // as taken, exiting edges as not-taken.
-bool BranchProbabilityAnalysis::calcLoopBranchHeuristics(BasicBlock *BB) {
-  uint32_t numSuccs =3D BB->getTerminator()->getNumSuccessors();
-
+bool BranchProbabilityInfo::calcLoopBranchHeuristics(BasicBlock *BB) {
   Loop *L =3D LI->getLoopFor(BB);
   if (!L)
     return false;
@@ -267,17 +225,13 @@
   SmallPtrSet<BasicBlock *, 8> ExitingEdges;
   SmallPtrSet<BasicBlock *, 8> InEdges; // Edges from header to the loop.
=20
-  bool isHeader =3D BB =3D=3D L->getHeader();
-
   for (succ_iterator I =3D succ_begin(BB), E =3D succ_end(BB); I !=3D E; +=
+I) {
-    BasicBlock *Succ =3D *I;
-    Loop *SuccL =3D LI->getLoopFor(Succ);
-    if (SuccL !=3D L)
-      ExitingEdges.insert(Succ);
-    else if (Succ =3D=3D L->getHeader())
-      BackEdges.insert(Succ);
-    else if (isHeader)
-      InEdges.insert(Succ);
+    if (!L->contains(*I))
+      ExitingEdges.insert(*I);
+    else if (L->getHeader() =3D=3D *I)
+      BackEdges.insert(*I);
+    else
+      InEdges.insert(*I);
   }
=20
   if (uint32_t numBackEdges =3D BackEdges.size()) {
@@ -288,7 +242,7 @@
     for (SmallPtrSet<BasicBlock *, 8>::iterator EI =3D BackEdges.begin(),
          EE =3D BackEdges.end(); EI !=3D EE; ++EI) {
       BasicBlock *Back =3D *EI;
-      BP->setEdgeWeight(BB, Back, backWeight);
+      setEdgeWeight(BB, Back, backWeight);
     }
   }
=20
@@ -300,27 +254,26 @@
     for (SmallPtrSet<BasicBlock *, 8>::iterator EI =3D InEdges.begin(),
          EE =3D InEdges.end(); EI !=3D EE; ++EI) {
       BasicBlock *Back =3D *EI;
-      BP->setEdgeWeight(BB, Back, inWeight);
+      setEdgeWeight(BB, Back, inWeight);
     }
   }
=20
-  uint32_t numExitingEdges =3D ExitingEdges.size();
-  if (uint32_t numNonExitingEdges =3D numSuccs - numExitingEdges) {
-    uint32_t exitWeight =3D LBH_NONTAKEN_WEIGHT / numNonExitingEdges;
+  if (uint32_t numExitingEdges =3D ExitingEdges.size()) {
+    uint32_t exitWeight =3D LBH_NONTAKEN_WEIGHT / numExitingEdges;
     if (exitWeight < MIN_WEIGHT)
       exitWeight =3D MIN_WEIGHT;
=20
     for (SmallPtrSet<BasicBlock *, 8>::iterator EI =3D ExitingEdges.begin(=
),
          EE =3D ExitingEdges.end(); EI !=3D EE; ++EI) {
       BasicBlock *Exiting =3D *EI;
-      BP->setEdgeWeight(BB, Exiting, exitWeight);
+      setEdgeWeight(BB, Exiting, exitWeight);
     }
   }
=20
   return true;
 }
=20
-bool BranchProbabilityAnalysis::calcZeroHeuristics(BasicBlock *BB) {
+bool BranchProbabilityInfo::calcZeroHeuristics(BasicBlock *BB) {
   BranchInst * BI =3D dyn_cast<BranchInst>(BB->getTerminator());
   if (!BI || !BI->isConditional())
     return false;
@@ -375,45 +328,94 @@
   if (!isProb)
     std::swap(Taken, NonTaken);
=20
-  BP->setEdgeWeight(BB, Taken, ZH_TAKEN_WEIGHT);
-  BP->setEdgeWeight(BB, NonTaken, ZH_NONTAKEN_WEIGHT);
+  setEdgeWeight(BB, Taken, ZH_TAKEN_WEIGHT);
+  setEdgeWeight(BB, NonTaken, ZH_NONTAKEN_WEIGHT);
=20
   return true;
 }
=20
+bool BranchProbabilityInfo::calcFloatingPointHeuristics(BasicBlock *BB) {
+  BranchInst *BI =3D dyn_cast<BranchInst>(BB->getTerminator());
+  if (!BI || !BI->isConditional())
+    return false;
=20
-bool BranchProbabilityAnalysis::runOnFunction(Function &F) {
+  Value *Cond =3D BI->getCondition();
+  FCmpInst *FCmp =3D dyn_cast<FCmpInst>(Cond);
+  if (!FCmp)
+    return false;
=20
-  for (Function::iterator I =3D F.begin(), E =3D F.end(); I !=3D E; ) {
-    BasicBlock *BB =3D I++;
-
-    if (calcMetadataWeights(BB))
-      continue;
-
-    if (calcLoopBranchHeuristics(BB))
-      continue;
-
-    if (calcReturnHeuristics(BB))
-      continue;
-
-    if (calcPointerHeuristics(BB))
-      continue;
-
-    calcZeroHeuristics(BB);
+  bool isProb;
+  if (FCmp->isEquality()) {
+    // f1 =3D=3D f2 -> Unlikely
+    // f1 !=3D f2 -> Likely
+    isProb =3D !FCmp->isTrueWhenEqual();
+  } else if (FCmp->getPredicate() =3D=3D FCmpInst::FCMP_ORD) {
+    // !isnan -> Likely
+    isProb =3D true;
+  } else if (FCmp->getPredicate() =3D=3D FCmpInst::FCMP_UNO) {
+    // isnan -> Unlikely
+    isProb =3D false;
+  } else {
+    return false;
   }
=20
+  BasicBlock *Taken =3D BI->getSuccessor(0);
+  BasicBlock *NonTaken =3D BI->getSuccessor(1);
+
+  if (!isProb)
+    std::swap(Taken, NonTaken);
+
+  setEdgeWeight(BB, Taken, FPH_TAKEN_WEIGHT);
+  setEdgeWeight(BB, NonTaken, FPH_NONTAKEN_WEIGHT);
+
+  return true;
+}
+
+void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
+  AU.addRequired<LoopInfo>();
+  AU.setPreservesAll();
+}
+
+bool BranchProbabilityInfo::runOnFunction(Function &F) {
+  LastF =3D &F; // Store the last function we ran on for printing.
+  LI =3D &getAnalysis<LoopInfo>();
+  assert(PostDominatedByUnreachable.empty());
+
+  // Walk the basic blocks in post-order so that we can build up state abo=
ut
+  // the successors of a block iteratively.
+  for (po_iterator<BasicBlock *> I =3D po_begin(&F.getEntryBlock()),
+                                 E =3D po_end(&F.getEntryBlock());
+       I !=3D E; ++I) {
+    DEBUG(dbgs() << "Computing probabilities for " << I->getName() << "\n"=
);
+    if (calcUnreachableHeuristics(*I))
+      continue;
+    if (calcMetadataWeights(*I))
+      continue;
+    if (calcLoopBranchHeuristics(*I))
+      continue;
+    if (calcPointerHeuristics(*I))
+      continue;
+    if (calcZeroHeuristics(*I))
+      continue;
+    calcFloatingPointHeuristics(*I);
+  }
+
+  PostDominatedByUnreachable.clear();
   return false;
 }
=20
-void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
-    AU.addRequired<LoopInfo>();
-    AU.setPreservesAll();
-}
-
-bool BranchProbabilityInfo::runOnFunction(Function &F) {
-  LoopInfo &LI =3D getAnalysis<LoopInfo>();
-  BranchProbabilityAnalysis BPA(&Weights, this, &LI);
-  return BPA.runOnFunction(F);
+void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const {
+  OS << "---- Branch Probabilities ----\n";
+  // We print the probabilities from the last function the analysis ran ov=
er,
+  // or the function it is currently running over.
+  assert(LastF && "Cannot print prior to running over a function");
+  for (Function::const_iterator BI =3D LastF->begin(), BE =3D LastF->end();
+       BI !=3D BE; ++BI) {
+    for (succ_const_iterator SI =3D succ_begin(BI), SE =3D succ_end(BI);
+         SI !=3D SE; ++SI) {
+      printEdgeProbability(OS << "  ", BI, *SI);
+    }
+  }
 }
=20
 uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const=
 {
@@ -434,12 +436,8 @@
 bool BranchProbabilityInfo::
 isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
   // Hot probability is at least 4/5 =3D 80%
-  uint32_t Weight =3D getEdgeWeight(Src, Dst);
-  uint32_t Sum =3D getSumForBlock(Src);
-
-  // FIXME: Implement BranchProbability::compare then change this code to
-  // compare this BranchProbability against a static "hot" BranchProbabili=
ty.
-  return (uint64_t)Weight * 5 > (uint64_t)Sum * 4;
+  // FIXME: Compare against a static "hot" BranchProbability.
+  return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
 }
=20
 BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
@@ -461,8 +459,8 @@
     }
   }
=20
-  // FIXME: Use BranchProbability::compare.
-  if ((uint64_t)MaxWeight * 5 > (uint64_t)Sum * 4)
+  // Hot probability is at least 4/5 =3D 80%
+  if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
     return MaxSucc;
=20
   return 0;
@@ -483,8 +481,8 @@
 void BranchProbabilityInfo::
 setEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst, uint32_t Weigh=
t) {
   Weights[std::make_pair(Src, Dst)] =3D Weight;
-  DEBUG(dbgs() << "set edge " << Src->getNameStr() << " -> "
-               << Dst->getNameStr() << " weight to " << Weight
+  DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
+               << Dst->getName() << " weight to " << Weight
                << (isEdgeHot(Src, Dst) ? " [is HOT now]\n" : "\n"));
 }
=20
@@ -499,11 +497,12 @@
 }
=20
 raw_ostream &
-BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, BasicBlock *S=
rc,
-                                            BasicBlock *Dst) const {
+BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
+                                            const BasicBlock *Src,
+                                            const BasicBlock *Dst) const {
=20
   const BranchProbability Prob =3D getEdgeProbability(Src, Dst);
-  OS << "edge " << Src->getNameStr() << " -> " << Dst->getNameStr()
+  OS << "edge " << Src->getName() << " -> " << Dst->getName()
      << " probability is " << Prob
      << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/CFGPrin=
ter.cpp
--- a/head/contrib/llvm/lib/Analysis/CFGPrinter.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Analysis/CFGPrinter.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -77,7 +77,7 @@
     }
=20
     virtual bool runOnFunction(Function &F) {
-      std::string Filename =3D "cfg." + F.getNameStr() + ".dot";
+      std::string Filename =3D "cfg." + F.getName().str() + ".dot";
       errs() << "Writing '" << Filename << "'...";
      =20
       std::string ErrorInfo;
@@ -111,7 +111,7 @@
     }
    =20
     virtual bool runOnFunction(Function &F) {
-      std::string Filename =3D "cfg." + F.getNameStr() + ".dot";
+      std::string Filename =3D "cfg." + F.getName().str() + ".dot";
       errs() << "Writing '" << Filename << "'...";
=20
       std::string ErrorInfo;
@@ -143,7 +143,7 @@
 /// being a 'dot' and 'gv' program in your path.
 ///
 void Function::viewCFG() const {
-  ViewGraph(this, "cfg" + getNameStr());
+  ViewGraph(this, "cfg" + getName());
 }
=20
 /// viewCFGOnly - This function is meant for use from the debugger.  It wo=
rks
@@ -152,7 +152,7 @@
 /// his can make the graph smaller.
 ///
 void Function::viewCFGOnly() const {
-  ViewGraph(this, "cfg" + getNameStr(), true);
+  ViewGraph(this, "cfg" + getName(), true);
 }
=20
 FunctionPass *llvm::createCFGPrinterPass () {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Capture=
Tracking.cpp
--- a/head/contrib/llvm/lib/Analysis/CaptureTracking.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/CaptureTracking.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -16,25 +16,35 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "llvm/Analysis/CaptureTracking.h"
-#include "llvm/Constants.h"
-#include "llvm/Instructions.h"
-#include "llvm/Value.h"
-#include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/Support/CallSite.h"
+#include "llvm/Analysis/CaptureTracking.h"
 using namespace llvm;
=20
-/// As its comment mentions, PointerMayBeCaptured can be expensive.
-/// However, it's not easy for BasicAA to cache the result, because
-/// it's an ImmutablePass. To work around this, bound queries at a
-/// fixed number of uses.
-///
-/// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
-/// a cache. Then we can move the code from BasicAliasAnalysis into
-/// that path, and remove this threshold.
-static int const Threshold =3D 20;
+CaptureTracker::~CaptureTracker() {}
+
+namespace {
+  struct SimpleCaptureTracker : public CaptureTracker {
+    explicit SimpleCaptureTracker(bool ReturnCaptures)
+      : ReturnCaptures(ReturnCaptures), Captured(false) {}
+
+    void tooManyUses() { Captured =3D true; }
+
+    bool shouldExplore(Use *U) { return true; }
+
+    bool captured(Use *U) {
+      if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
+	return false;
+
+      Captured =3D true;
+      return true;
+    }
+
+    bool ReturnCaptures;
+
+    bool Captured;
+  };
+}
=20
 /// PointerMayBeCaptured - Return true if this pointer value may be captur=
ed
 /// by the enclosing function (which is required to exist).  This routine =
can
@@ -45,6 +55,26 @@
 /// counts as capturing it or not.
 bool llvm::PointerMayBeCaptured(const Value *V,
                                 bool ReturnCaptures, bool StoreCaptures) {
+  assert(!isa<GlobalValue>(V) &&
+         "It doesn't make sense to ask whether a global is captured.");
+
+  // TODO: If StoreCaptures is not true, we could do Fancy analysis
+  // to determine whether this store is not actually an escape point.
+  // In that case, BasicAliasAnalysis should be updated as well to
+  // take advantage of this.
+  (void)StoreCaptures;
+
+  SimpleCaptureTracker SCT(ReturnCaptures);
+  PointerMayBeCaptured(V, &SCT);
+  return SCT.Captured;
+}
+
+/// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
+/// a cache. Then we can move the code from BasicAliasAnalysis into
+/// that path, and remove this threshold.
+static int const Threshold =3D 20;
+
+void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
   SmallVector<Use*, Threshold> Worklist;
   SmallSet<Use*, Threshold> Visited;
@@ -55,9 +85,10 @@
     // If there are lots of uses, conservatively say that the value
     // is captured to avoid taking too much compile time.
     if (Count++ >=3D Threshold)
-      return true;
+      return Tracker->tooManyUses();
=20
     Use *U =3D &UI.getUse();
+    if (!Tracker->shouldExplore(U)) continue;
     Visited.insert(U);
     Worklist.push_back(U);
   }
@@ -86,11 +117,10 @@
       // (think of self-referential objects).
       CallSite::arg_iterator B =3D CS.arg_begin(), E =3D CS.arg_end();
       for (CallSite::arg_iterator A =3D B; A !=3D E; ++A)
-        if (A->get() =3D=3D V && !CS.paramHasAttr(A - B + 1, Attribute::No=
Capture))
+        if (A->get() =3D=3D V && !CS.doesNotCapture(A - B))
           // The parameter is not marked 'nocapture' - captured.
-          return true;
-      // Only passed via 'nocapture' arguments, or is the called function =
- not
-      // captured.
+          if (Tracker->captured(U))
+            return;
       break;
     }
     case Instruction::Load:
@@ -99,18 +129,11 @@
     case Instruction::VAArg:
       // "va-arg" from a pointer does not cause it to be captured.
       break;
-    case Instruction::Ret:
-      if (ReturnCaptures)
-        return true;
-      break;
     case Instruction::Store:
       if (V =3D=3D I->getOperand(0))
         // Stored the pointer - conservatively assume it may be captured.
-        // TODO: If StoreCaptures is not true, we could do Fancy analysis
-        // to determine whether this store is not actually an escape point.
-        // In that case, BasicAliasAnalysis should be updated as well to
-        // take advantage of this.
-        return true;
+        if (Tracker->captured(U))
+          return;
       // Storing to the pointee does not cause the pointer to be captured.
       break;
     case Instruction::BitCast:
@@ -122,7 +145,8 @@
            UI !=3D UE; ++UI) {
         Use *U =3D &UI.getUse();
         if (Visited.insert(U))
-          Worklist.push_back(U);
+          if (Tracker->shouldExplore(U))
+            Worklist.push_back(U);
       }
       break;
     case Instruction::ICmp:
@@ -136,13 +160,16 @@
             break;
       // Otherwise, be conservative. There are crazy ways to capture point=
ers
       // using comparisons.
-      return true;
+      if (Tracker->captured(U))
+        return;
+      break;
     default:
       // Something else - be conservative and say it is captured.
-      return true;
+      if (Tracker->captured(U))
+        return;
+      break;
     }
   }
=20
-  // All uses examined - not captured.
-  return false;
+  // All uses examined.
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Constan=
tFolding.cpp
--- a/head/contrib/llvm/lib/Analysis/ConstantFolding.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ConstantFolding.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -26,6 +26,7 @@
 #include "llvm/Operator.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -51,6 +52,42 @@
   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
     return Constant::getAllOnesValue(DestTy);
=20
+  // Handle a vector->integer cast.
+  if (IntegerType *IT =3D dyn_cast<IntegerType>(DestTy)) {
+    ConstantDataVector *CDV =3D dyn_cast<ConstantDataVector>(C);
+    if (CDV =3D=3D 0)
+      return ConstantExpr::getBitCast(C, DestTy);
+
+    unsigned NumSrcElts =3D CDV->getType()->getNumElements();
+   =20
+    Type *SrcEltTy =3D CDV->getType()->getElementType();
+   =20
+    // If the vector is a vector of floating point, convert it to vector o=
f int
+    // to simplify things.
+    if (SrcEltTy->isFloatingPointTy()) {
+      unsigned FPWidth =3D SrcEltTy->getPrimitiveSizeInBits();
+      Type *SrcIVTy =3D
+        VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrc=
Elts);
+      // Ask VMCore to do the conversion now that #elts line up.
+      C =3D ConstantExpr::getBitCast(C, SrcIVTy);
+      CDV =3D cast<ConstantDataVector>(C);
+    }
+   =20
+    // Now that we know that the input value is a vector of integers, just=
 shift
+    // and insert them into our result.
+    unsigned BitShift =3D TD.getTypeAllocSizeInBits(SrcEltTy);
+    APInt Result(IT->getBitWidth(), 0);
+    for (unsigned i =3D 0; i !=3D NumSrcElts; ++i) {
+      Result <<=3D BitShift;
+      if (TD.isLittleEndian())
+        Result |=3D CDV->getElementAsInteger(NumSrcElts-i-1);
+      else
+        Result |=3D CDV->getElementAsInteger(i);
+    }
+  =20
+    return ConstantInt::get(IT, Result);
+  }
+ =20
   // The code below only handles casts to vectors currently.
   VectorType *DestVTy =3D dyn_cast<VectorType>(DestTy);
   if (DestVTy =3D=3D 0)
@@ -64,17 +101,16 @@
   }
  =20
   // If this is a bitcast from constant vector -> vector, fold it.
-  ConstantVector *CV =3D dyn_cast<ConstantVector>(C);
-  if (CV =3D=3D 0)
+  if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
     return ConstantExpr::getBitCast(C, DestTy);
  =20
   // If the element types match, VMCore can fold it.
   unsigned NumDstElt =3D DestVTy->getNumElements();
-  unsigned NumSrcElt =3D CV->getNumOperands();
+  unsigned NumSrcElt =3D C->getType()->getVectorNumElements();
   if (NumDstElt =3D=3D NumSrcElt)
     return ConstantExpr::getBitCast(C, DestTy);
  =20
-  Type *SrcEltTy =3D CV->getType()->getElementType();
+  Type *SrcEltTy =3D C->getType()->getVectorElementType();
   Type *DstEltTy =3D DestVTy->getElementType();
  =20
   // Otherwise, we're changing the number of elements in a vector, which=20
@@ -94,7 +130,6 @@
       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstEl=
t);
     // Recursively handle this integer conversion, if possible.
     C =3D FoldBitCast(C, DestIVTy, TD);
-    if (!C) return ConstantExpr::getBitCast(C, DestTy);
    =20
     // Finally, VMCore can handle this now that #elts line up.
     return ConstantExpr::getBitCast(C, DestTy);
@@ -108,8 +143,9 @@
       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcEl=
t);
     // Ask VMCore to do the conversion now that #elts line up.
     C =3D ConstantExpr::getBitCast(C, SrcIVTy);
-    CV =3D dyn_cast<ConstantVector>(C);
-    if (!CV)  // If VMCore wasn't able to fold it, bail out.
+    // If VMCore wasn't able to fold it, bail out.
+    if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
+        !isa<ConstantDataVector>(C))
       return C;
   }
  =20
@@ -131,7 +167,7 @@
       Constant *Elt =3D Zero;
       unsigned ShiftAmt =3D isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
       for (unsigned j =3D 0; j !=3D Ratio; ++j) {
-        Constant *Src =3D dyn_cast<ConstantInt>(CV->getOperand(SrcElt++));
+        Constant *Src =3Ddyn_cast<ConstantInt>(C->getAggregateElement(SrcE=
lt++));
         if (!Src)  // Reject constantexpr elements.
           return ConstantExpr::getBitCast(C, DestTy);
        =20
@@ -148,28 +184,29 @@
       }
       Result.push_back(Elt);
     }
-  } else {
-    // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
-    unsigned Ratio =3D NumDstElt/NumSrcElt;
-    unsigned DstBitSize =3D DstEltTy->getPrimitiveSizeInBits();
+    return ConstantVector::get(Result);
+  }
+ =20
+  // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
+  unsigned Ratio =3D NumDstElt/NumSrcElt;
+  unsigned DstBitSize =3D DstEltTy->getPrimitiveSizeInBits();
+ =20
+  // Loop over each source value, expanding into multiple results.
+  for (unsigned i =3D 0; i !=3D NumSrcElt; ++i) {
+    Constant *Src =3D dyn_cast<ConstantInt>(C->getAggregateElement(i));
+    if (!Src)  // Reject constantexpr elements.
+      return ConstantExpr::getBitCast(C, DestTy);
    =20
-    // Loop over each source value, expanding into multiple results.
-    for (unsigned i =3D 0; i !=3D NumSrcElt; ++i) {
-      Constant *Src =3D dyn_cast<ConstantInt>(CV->getOperand(i));
-      if (!Src)  // Reject constantexpr elements.
-        return ConstantExpr::getBitCast(C, DestTy);
+    unsigned ShiftAmt =3D isLittleEndian ? 0 : DstBitSize*(Ratio-1);
+    for (unsigned j =3D 0; j !=3D Ratio; ++j) {
+      // Shift the piece of the value into the right place, depending on
+      // endianness.
+      Constant *Elt =3D ConstantExpr::getLShr(Src,=20
+                                  ConstantInt::get(Src->getType(), ShiftAm=
t));
+      ShiftAmt +=3D isLittleEndian ? DstBitSize : -DstBitSize;
      =20
-      unsigned ShiftAmt =3D isLittleEndian ? 0 : DstBitSize*(Ratio-1);
-      for (unsigned j =3D 0; j !=3D Ratio; ++j) {
-        // Shift the piece of the value into the right place, depending on
-        // endianness.
-        Constant *Elt =3D ConstantExpr::getLShr(Src,=20
-                                    ConstantInt::get(Src->getType(), Shift=
Amt));
-        ShiftAmt +=3D isLittleEndian ? DstBitSize : -DstBitSize;
-       =20
-        // Truncate and remember this piece.
-        Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
-      }
+      // Truncate and remember this piece.
+      Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
     }
   }
  =20
@@ -272,7 +309,7 @@
     }
     return false;
   }
-
+ =20
   if (ConstantStruct *CS =3D dyn_cast<ConstantStruct>(C)) {
     const StructLayout *SL =3D TD.getStructLayout(CS->getType());
     unsigned Index =3D SL->getElementContainingOffset(ByteOffset);
@@ -310,12 +347,20 @@
     // not reached.
   }
=20
-  if (ConstantArray *CA =3D dyn_cast<ConstantArray>(C)) {
-    uint64_t EltSize =3D TD.getTypeAllocSize(CA->getType()->getElementType=
());
+  if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
+      isa<ConstantDataSequential>(C)) {
+    Type *EltTy =3D cast<SequentialType>(C->getType())->getElementType();
+    uint64_t EltSize =3D TD.getTypeAllocSize(EltTy);
     uint64_t Index =3D ByteOffset / EltSize;
     uint64_t Offset =3D ByteOffset - Index * EltSize;
-    for (; Index !=3D CA->getType()->getNumElements(); ++Index) {
-      if (!ReadDataFromGlobal(CA->getOperand(Index), Offset, CurPtr,
+    uint64_t NumElts;
+    if (ArrayType *AT =3D dyn_cast<ArrayType>(C->getType()))
+      NumElts =3D AT->getNumElements();
+    else
+      NumElts =3D cast<VectorType>(C->getType())->getNumElements();
+   =20
+    for (; Index !=3D NumElts; ++Index) {
+      if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPt=
r,
                               BytesLeft, TD))
         return false;
       if (EltSize >=3D BytesLeft)
@@ -327,30 +372,12 @@
     }
     return true;
   }
- =20
-  if (ConstantVector *CV =3D dyn_cast<ConstantVector>(C)) {
-    uint64_t EltSize =3D TD.getTypeAllocSize(CV->getType()->getElementType=
());
-    uint64_t Index =3D ByteOffset / EltSize;
-    uint64_t Offset =3D ByteOffset - Index * EltSize;
-    for (; Index !=3D CV->getType()->getNumElements(); ++Index) {
-      if (!ReadDataFromGlobal(CV->getOperand(Index), Offset, CurPtr,
-                              BytesLeft, TD))
-        return false;
-      if (EltSize >=3D BytesLeft)
-        return true;
      =20
-      Offset =3D 0;
-      BytesLeft -=3D EltSize;
-      CurPtr +=3D EltSize;
-    }
-    return true;
-  }
- =20
   if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(C)) {
     if (CE->getOpcode() =3D=3D Instruction::IntToPtr &&
         CE->getOperand(0)->getType() =3D=3D TD.getIntPtrType(CE->getContex=
t()))=20
-        return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,=20
-                                  BytesLeft, TD);
+      return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,=20
+                                BytesLeft, TD);
   }
=20
   // Otherwise, unknown initializer type.
@@ -445,9 +472,9 @@
  =20
   // Instead of loading constant c string, use corresponding integer value
   // directly if string length is small enough.
-  std::string Str;
-  if (TD && GetConstantStringInfo(CE, Str) && !Str.empty()) {
-    unsigned StrLen =3D Str.length();
+  StringRef Str;
+  if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
+    unsigned StrLen =3D Str.size();
     Type *Ty =3D cast<PointerType>(CE->getType())->getElementType();
     unsigned NumBits =3D Ty->getPrimitiveSizeInBits();
     // Replace load with immediate integer if the result is an integer or =
fp
@@ -542,8 +569,8 @@
 /// explicitly cast them so that they aren't implicitly casted by the
 /// getelementptr.
 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
-                                Type *ResultTy,
-                                const TargetData *TD) {
+                                Type *ResultTy, const TargetData *TD,
+                                const TargetLibraryInfo *TLI) {
   if (!TD) return 0;
   Type *IntPtrTy =3D TD->getIntPtrType(ResultTy->getContext());
=20
@@ -568,7 +595,7 @@
   Constant *C =3D
     ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
   if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(C))
-    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD))
+    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD, TLI))
       C =3D Folded;
   return C;
 }
@@ -576,10 +603,11 @@
 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specifie=
d GEP
 /// constant expression, do so.
 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
-                                         Type *ResultTy,
-                                         const TargetData *TD) {
+                                         Type *ResultTy, const TargetData =
*TD,
+                                         const TargetLibraryInfo *TLI) {
   Constant *Ptr =3D Ops[0];
-  if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized=
())
+  if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized=
() ||
+      !Ptr->getType()->isPointerTy())
     return 0;
  =20
   Type *IntPtrTy =3D TD->getIntPtrType(Ptr->getContext());
@@ -602,7 +630,7 @@
           Res =3D ConstantExpr::getSub(Res, CE->getOperand(1));
           Res =3D ConstantExpr::getIntToPtr(Res, ResultTy);
           if (ConstantExpr *ResCE =3D dyn_cast<ConstantExpr>(Res))
-            Res =3D ConstantFoldConstantExpression(ResCE, TD);
+            Res =3D ConstantFoldConstantExpression(ResCE, TD, TLI);
           return Res;
         }
       }
@@ -729,7 +757,9 @@
 /// Note that this fails if not all of the operands are constant.  Otherwi=
se,
 /// this function can only fail when attempting to fold instructions like =
loads
 /// and stores, which have no constant expression form.
-Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *=
TD) {
+Constant *llvm::ConstantFoldInstruction(Instruction *I,
+                                        const TargetData *TD,
+                                        const TargetLibraryInfo *TLI) {
   // Handle PHI nodes quickly here...
   if (PHINode *PN =3D dyn_cast<PHINode>(I)) {
     Constant *CommonValue =3D 0;
@@ -765,7 +795,7 @@
=20
   if (const CmpInst *CI =3D dyn_cast<CmpInst>(I))
     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops=
[1],
-                                           TD);
+                                           TD, TLI);
  =20
   if (const LoadInst *LI =3D dyn_cast<LoadInst>(I))
     return ConstantFoldLoadInst(LI, TD);
@@ -781,28 +811,29 @@
                                     cast<Constant>(EVI->getAggregateOperan=
d()),
                                     EVI->getIndices());
=20
-  return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD);
+  return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, T=
LI);
 }
=20
 /// ConstantFoldConstantExpression - Attempt to fold the constant expressi=
on
 /// using the specified TargetData.  If successful, the constant result is
 /// result is returned, if not, null is returned.
 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
-                                               const TargetData *TD) {
+                                               const TargetData *TD,
+                                               const TargetLibraryInfo *TL=
I) {
   SmallVector<Constant*, 8> Ops;
   for (User::const_op_iterator i =3D CE->op_begin(), e =3D CE->op_end();
        i !=3D e; ++i) {
     Constant *NewC =3D cast<Constant>(*i);
     // Recursively fold the ConstantExpr's operands.
     if (ConstantExpr *NewCE =3D dyn_cast<ConstantExpr>(NewC))
-      NewC =3D ConstantFoldConstantExpression(NewCE, TD);
+      NewC =3D ConstantFoldConstantExpression(NewCE, TD, TLI);
     Ops.push_back(NewC);
   }
=20
   if (CE->isCompare())
     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops=
[1],
-                                           TD);
-  return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD);
+                                           TD, TLI);
+  return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD,=
 TLI);
 }
=20
 /// ConstantFoldInstOperands - Attempt to constant fold an instruction wit=
h the
@@ -817,7 +848,8 @@
 ///
 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,=20
                                          ArrayRef<Constant *> Ops,
-                                         const TargetData *TD) {
+                                         const TargetData *TD,
+                                         const TargetLibraryInfo *TLI) {  =
                                      =20
   // Handle easy binops first.
   if (Instruction::isBinaryOp(Opcode)) {
     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
@@ -830,11 +862,11 @@
   switch (Opcode) {
   default: return 0;
   case Instruction::ICmp:
-  case Instruction::FCmp: assert(0 && "Invalid for compares");
+  case Instruction::FCmp: llvm_unreachable("Invalid for compares");
   case Instruction::Call:
     if (Function *F =3D dyn_cast<Function>(Ops.back()))
       if (canConstantFoldCallTo(F))
-        return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1));
+        return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
     return 0;
   case Instruction::PtrToInt:
     // If the input is a inttoptr, eliminate the pair.  This requires know=
ing
@@ -888,9 +920,9 @@
   case Instruction::ShuffleVector:
     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
   case Instruction::GetElementPtr:
-    if (Constant *C =3D CastGEPIndices(Ops, DestTy, TD))
+    if (Constant *C =3D CastGEPIndices(Ops, DestTy, TD, TLI))
       return C;
-    if (Constant *C =3D SymbolicallyEvaluateGEP(Ops, DestTy, TD))
+    if (Constant *C =3D SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
       return C;
    =20
     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
@@ -903,7 +935,8 @@
 ///
 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
                                                 Constant *Ops0, Constant *=
Ops1,=20
-                                                const TargetData *TD) {
+                                                const TargetData *TD,
+                                                const TargetLibraryInfo *T=
LI) {
   // fold: icmp (inttoptr x), null         -> icmp x, 0
   // fold: icmp (ptrtoint x), 0            -> icmp x, null
   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zex=
t y
@@ -920,7 +953,7 @@
         Constant *C =3D ConstantExpr::getIntegerCast(CE0->getOperand(0),
                                                    IntPtrTy, false);
         Constant *Null =3D Constant::getNullValue(C->getType());
-        return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
+        return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI=
);
       }
      =20
       // Only do this transformation if the int is intptrty in size, other=
wise
@@ -929,7 +962,7 @@
           CE0->getType() =3D=3D IntPtrTy) {
         Constant *C =3D CE0->getOperand(0);
         Constant *Null =3D Constant::getNullValue(C->getType());
-        return ConstantFoldCompareInstOperands(Predicate, C, Null, TD);
+        return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI=
);
       }
     }
    =20
@@ -944,7 +977,7 @@
                                                       IntPtrTy, false);
           Constant *C1 =3D ConstantExpr::getIntegerCast(CE1->getOperand(0),
                                                       IntPtrTy, false);
-          return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD);
+          return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TL=
I);
         }
=20
         // Only do this transformation if the int is intptrty in size, oth=
erwise
@@ -953,7 +986,7 @@
              CE0->getType() =3D=3D IntPtrTy &&
              CE0->getOperand(0)->getType() =3D=3D CE1->getOperand(0)->getT=
ype()))
           return ConstantFoldCompareInstOperands(Predicate, CE0->getOperan=
d(0),
-                                                 CE1->getOperand(0), TD);
+                                                 CE1->getOperand(0), TD, T=
LI);
       }
     }
    =20
@@ -962,13 +995,15 @@
     if ((Predicate =3D=3D ICmpInst::ICMP_EQ || Predicate =3D=3D ICmpInst::=
ICMP_NE) &&
         CE0->getOpcode() =3D=3D Instruction::Or && Ops1->isNullValue()) {
       Constant *LHS =3D=20
-        ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops=
1,TD);
+        ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops=
1,
+                                        TD, TLI);
       Constant *RHS =3D=20
-        ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops=
1,TD);
+        ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops=
1,
+                                        TD, TLI);
       unsigned OpC =3D=20
         Predicate =3D=3D ICmpInst::ICMP_EQ ? Instruction::And : Instructio=
n::Or;
       Constant *Ops[] =3D { LHS, RHS };
-      return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD);
+      return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
     }
   }
  =20
@@ -981,56 +1016,30 @@
 /// constant expression, or null if something is funny and we can't decide.
 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,=20
                                                        ConstantExpr *CE) {
-  if (CE->getOperand(1) !=3D Constant::getNullValue(CE->getOperand(1)->get=
Type()))
+  if (!CE->getOperand(1)->isNullValue())
     return 0;  // Do not allow stepping over the value!
- =20
+
   // Loop over all of the operands, tracking down which value we are
-  // addressing...
-  gep_type_iterator I =3D gep_type_begin(CE), E =3D gep_type_end(CE);
-  for (++I; I !=3D E; ++I)
-    if (StructType *STy =3D dyn_cast<StructType>(*I)) {
-      ConstantInt *CU =3D cast<ConstantInt>(I.getOperand());
-      assert(CU->getZExtValue() < STy->getNumElements() &&
-             "Struct index out of range!");
-      unsigned El =3D (unsigned)CU->getZExtValue();
-      if (ConstantStruct *CS =3D dyn_cast<ConstantStruct>(C)) {
-        C =3D CS->getOperand(El);
-      } else if (isa<ConstantAggregateZero>(C)) {
-        C =3D Constant::getNullValue(STy->getElementType(El));
-      } else if (isa<UndefValue>(C)) {
-        C =3D UndefValue::get(STy->getElementType(El));
-      } else {
-        return 0;
-      }
-    } else if (ConstantInt *CI =3D dyn_cast<ConstantInt>(I.getOperand())) {
-      if (ArrayType *ATy =3D dyn_cast<ArrayType>(*I)) {
-        if (CI->getZExtValue() >=3D ATy->getNumElements())
-         return 0;
-        if (ConstantArray *CA =3D dyn_cast<ConstantArray>(C))
-          C =3D CA->getOperand(CI->getZExtValue());
-        else if (isa<ConstantAggregateZero>(C))
-          C =3D Constant::getNullValue(ATy->getElementType());
-        else if (isa<UndefValue>(C))
-          C =3D UndefValue::get(ATy->getElementType());
-        else
-          return 0;
-      } else if (VectorType *VTy =3D dyn_cast<VectorType>(*I)) {
-        if (CI->getZExtValue() >=3D VTy->getNumElements())
-          return 0;
-        if (ConstantVector *CP =3D dyn_cast<ConstantVector>(C))
-          C =3D CP->getOperand(CI->getZExtValue());
-        else if (isa<ConstantAggregateZero>(C))
-          C =3D Constant::getNullValue(VTy->getElementType());
-        else if (isa<UndefValue>(C))
-          C =3D UndefValue::get(VTy->getElementType());
-        else
-          return 0;
-      } else {
-        return 0;
-      }
-    } else {
-      return 0;
-    }
+  // addressing.
+  for (unsigned i =3D 2, e =3D CE->getNumOperands(); i !=3D e; ++i) {
+    C =3D C->getAggregateElement(CE->getOperand(i));
+    if (C =3D=3D 0) return 0;
+  }
+  return C;
+}
+
+/// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
+/// indices (with an *implied* zero pointer index that is not in the list),
+/// return the constant value being addressed by a virtual load, or null if
+/// something is funny and we can't decide.
+Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
+                                                  ArrayRef<Constant*> Indi=
ces) {
+  // Loop over all of the operands, tracking down which value we are
+  // addressing.
+  for (unsigned i =3D 0, e =3D Indices.size(); i !=3D e; ++i) {
+    C =3D C->getAggregateElement(Indices[i]);
+    if (C =3D=3D 0) return 0;
+  }
   return C;
 }
=20
@@ -1045,6 +1054,7 @@
 llvm::canConstantFoldCallTo(const Function *F) {
   switch (F->getIntrinsicID()) {
   case Intrinsic::sqrt:
+  case Intrinsic::pow:
   case Intrinsic::powi:
   case Intrinsic::bswap:
   case Intrinsic::ctpop:
@@ -1115,7 +1125,6 @@
   if (Ty->isDoubleTy())
     return ConstantFP::get(Ty->getContext(), APFloat(V));
   llvm_unreachable("Can only constant fold float/double");
-  return 0; // dummy return to suppress warning
 }
=20
 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
@@ -1132,7 +1141,6 @@
   if (Ty->isDoubleTy())
     return ConstantFP::get(Ty->getContext(), APFloat(V));
   llvm_unreachable("Can only constant fold float/double");
-  return 0; // dummy return to suppress warning
 }
=20
 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
@@ -1143,11 +1151,8 @@
 /// available for the result. Returns null if the conversion cannot be
 /// performed, otherwise returns the Constant value resulting from the
 /// conversion.
-static Constant *ConstantFoldConvertToInt(ConstantFP *Op, bool roundToward=
Zero,
-                                          Type *Ty) {
-  assert(Op && "Called with NULL operand");
-  APFloat Val(Op->getValueAPF());
-
+static Constant *ConstantFoldConvertToInt(const APFloat &Val,
+                                          bool roundTowardZero, Type *Ty) {
   // All of these conversion intrinsics form an integer of at most 64bits.
   unsigned ResultWidth =3D cast<IntegerType>(Ty)->getBitWidth();
   assert(ResultWidth <=3D 64 &&
@@ -1168,7 +1173,8 @@
 /// ConstantFoldCall - Attempt to constant fold a call to the specified fu=
nction
 /// with the specified arguments, returning null if unsuccessful.
 Constant *
-llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands) {
+llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
+                       const TargetLibraryInfo *TLI) {
   if (!F->hasName()) return 0;
   StringRef Name =3D F->getName();
=20
@@ -1183,6 +1189,8 @@
=20
         return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
       }
+      if (!TLI)
+        return 0;
=20
       if (!Ty->isFloatTy() && !Ty->isDoubleTy())
         return 0;
@@ -1201,43 +1209,43 @@
                                      Op->getValueAPF().convertToDouble();
       switch (Name[0]) {
       case 'a':
-        if (Name =3D=3D "acos")
+        if (Name =3D=3D "acos" && TLI->has(LibFunc::acos))
           return ConstantFoldFP(acos, V, Ty);
-        else if (Name =3D=3D "asin")
+        else if (Name =3D=3D "asin" && TLI->has(LibFunc::asin))
           return ConstantFoldFP(asin, V, Ty);
-        else if (Name =3D=3D "atan")
+        else if (Name =3D=3D "atan" && TLI->has(LibFunc::atan))
           return ConstantFoldFP(atan, V, Ty);
         break;
       case 'c':
-        if (Name =3D=3D "ceil")
+        if (Name =3D=3D "ceil" && TLI->has(LibFunc::ceil))
           return ConstantFoldFP(ceil, V, Ty);
-        else if (Name =3D=3D "cos")
+        else if (Name =3D=3D "cos" && TLI->has(LibFunc::cos))
           return ConstantFoldFP(cos, V, Ty);
-        else if (Name =3D=3D "cosh")
+        else if (Name =3D=3D "cosh" && TLI->has(LibFunc::cosh))
           return ConstantFoldFP(cosh, V, Ty);
-        else if (Name =3D=3D "cosf")
+        else if (Name =3D=3D "cosf" && TLI->has(LibFunc::cosf))
           return ConstantFoldFP(cos, V, Ty);
         break;
       case 'e':
-        if (Name =3D=3D "exp")
+        if (Name =3D=3D "exp" && TLI->has(LibFunc::exp))
           return ConstantFoldFP(exp, V, Ty);
  =20
-        if (Name =3D=3D "exp2") {
+        if (Name =3D=3D "exp2" && TLI->has(LibFunc::exp2)) {
           // Constant fold exp2(x) as pow(2,x) in case the host doesn't ha=
ve a
           // C99 library.
           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
         }
         break;
       case 'f':
-        if (Name =3D=3D "fabs")
+        if (Name =3D=3D "fabs" && TLI->has(LibFunc::fabs))
           return ConstantFoldFP(fabs, V, Ty);
-        else if (Name =3D=3D "floor")
+        else if (Name =3D=3D "floor" && TLI->has(LibFunc::floor))
           return ConstantFoldFP(floor, V, Ty);
         break;
       case 'l':
-        if (Name =3D=3D "log" && V > 0)
+        if (Name =3D=3D "log" && V > 0 && TLI->has(LibFunc::log))
           return ConstantFoldFP(log, V, Ty);
-        else if (Name =3D=3D "log10" && V > 0)
+        else if (Name =3D=3D "log10" && V > 0 && TLI->has(LibFunc::log10))
           return ConstantFoldFP(log10, V, Ty);
         else if (F->getIntrinsicID() =3D=3D Intrinsic::sqrt &&
                  (Ty->isFloatTy() || Ty->isDoubleTy())) {
@@ -1248,21 +1256,21 @@
         }
         break;
       case 's':
-        if (Name =3D=3D "sin")
+        if (Name =3D=3D "sin" && TLI->has(LibFunc::sin))
           return ConstantFoldFP(sin, V, Ty);
-        else if (Name =3D=3D "sinh")
+        else if (Name =3D=3D "sinh" && TLI->has(LibFunc::sinh))
           return ConstantFoldFP(sinh, V, Ty);
-        else if (Name =3D=3D "sqrt" && V >=3D 0)
+        else if (Name =3D=3D "sqrt" && V >=3D 0 && TLI->has(LibFunc::sqrt))
           return ConstantFoldFP(sqrt, V, Ty);
-        else if (Name =3D=3D "sqrtf" && V >=3D 0)
+        else if (Name =3D=3D "sqrtf" && V >=3D 0 && TLI->has(LibFunc::sqrt=
f))
           return ConstantFoldFP(sqrt, V, Ty);
-        else if (Name =3D=3D "sinf")
+        else if (Name =3D=3D "sinf" && TLI->has(LibFunc::sinf))
           return ConstantFoldFP(sin, V, Ty);
         break;
       case 't':
-        if (Name =3D=3D "tan")
+        if (Name =3D=3D "tan" && TLI->has(LibFunc::tan))
           return ConstantFoldFP(tan, V, Ty);
-        else if (Name =3D=3D "tanh")
+        else if (Name =3D=3D "tanh" && TLI->has(LibFunc::tanh))
           return ConstantFoldFP(tanh, V, Ty);
         break;
       default:
@@ -1277,10 +1285,6 @@
         return ConstantInt::get(F->getContext(), Op->getValue().byteSwap()=
);
       case Intrinsic::ctpop:
         return ConstantInt::get(Ty, Op->getValue().countPopulation());
-      case Intrinsic::cttz:
-        return ConstantInt::get(Ty, Op->getValue().countTrailingZeros());
-      case Intrinsic::ctlz:
-        return ConstantInt::get(Ty, Op->getValue().countLeadingZeros());
       case Intrinsic::convert_from_fp16: {
         APFloat Val(Op->getValue());
=20
@@ -1300,24 +1304,31 @@
       }
     }
=20
-    if (ConstantVector *Op =3D dyn_cast<ConstantVector>(Operands[0])) {
+    // Support ConstantVector in case we have an Undef in the top.
+    if (isa<ConstantVector>(Operands[0]) ||=20
+        isa<ConstantDataVector>(Operands[0])) {
+      Constant *Op =3D cast<Constant>(Operands[0]);
       switch (F->getIntrinsicID()) {
       default: break;
       case Intrinsic::x86_sse_cvtss2si:
       case Intrinsic::x86_sse_cvtss2si64:
       case Intrinsic::x86_sse2_cvtsd2si:
       case Intrinsic::x86_sse2_cvtsd2si64:
-        if (ConstantFP *FPOp =3D dyn_cast<ConstantFP>(Op->getOperand(0)))
-          return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=3D*/fals=
e, Ty);
+        if (ConstantFP *FPOp =3D
+              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+          return ConstantFoldConvertToInt(FPOp->getValueAPF(),
+                                          /*roundTowardZero=3D*/false, Ty);
       case Intrinsic::x86_sse_cvttss2si:
       case Intrinsic::x86_sse_cvttss2si64:
       case Intrinsic::x86_sse2_cvttsd2si:
       case Intrinsic::x86_sse2_cvttsd2si64:
-        if (ConstantFP *FPOp =3D dyn_cast<ConstantFP>(Op->getOperand(0)))
-          return ConstantFoldConvertToInt(FPOp, /*roundTowardZero=3D*/true=
, Ty);
+        if (ConstantFP *FPOp =3D
+              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
+          return ConstantFoldConvertToInt(FPOp->getValueAPF(),=20
+                                          /*roundTowardZero=3D*/true, Ty);
       }
     }
-
+ =20
     if (isa<UndefValue>(Operands[0])) {
       if (F->getIntrinsicID() =3D=3D Intrinsic::bswap)
         return Operands[0];
@@ -1337,16 +1348,21 @@
       if (ConstantFP *Op2 =3D dyn_cast<ConstantFP>(Operands[1])) {
         if (Op2->getType() !=3D Op1->getType())
           return 0;
-       =20
+
         double Op2V =3D Ty->isFloatTy() ?=20
                       (double)Op2->getValueAPF().convertToFloat():
                       Op2->getValueAPF().convertToDouble();
=20
-        if (Name =3D=3D "pow")
+        if (F->getIntrinsicID() =3D=3D Intrinsic::pow) {
           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
-        if (Name =3D=3D "fmod")
+        }
+        if (!TLI)
+          return 0;
+        if (Name =3D=3D "pow" && TLI->has(LibFunc::pow))
+          return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
+        if (Name =3D=3D "fmod" && TLI->has(LibFunc::fmod))
           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
-        if (Name =3D=3D "atan2")
+        if (Name =3D=3D "atan2" && TLI->has(LibFunc::atan2))
           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
       } else if (ConstantInt *Op2C =3D dyn_cast<ConstantInt>(Operands[1]))=
 {
         if (F->getIntrinsicID() =3D=3D Intrinsic::powi && Ty->isFloatTy())
@@ -1361,7 +1377,6 @@
       return 0;
     }
    =20
-   =20
     if (ConstantInt *Op1 =3D dyn_cast<ConstantInt>(Operands[0])) {
       if (ConstantInt *Op2 =3D dyn_cast<ConstantInt>(Operands[1])) {
         switch (F->getIntrinsicID()) {
@@ -1375,7 +1390,7 @@
           APInt Res;
           bool Overflow;
           switch (F->getIntrinsicID()) {
-          default: assert(0 && "Invalid case");
+          default: llvm_unreachable("Invalid case");
           case Intrinsic::sadd_with_overflow:
             Res =3D Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
             break;
@@ -1401,6 +1416,14 @@
           };
           return ConstantStruct::get(cast<StructType>(F->getReturnType()),=
 Ops);
         }
+        case Intrinsic::cttz:
+          // FIXME: This should check for Op2 =3D=3D 1, and become unreach=
able if
+          // Op1 =3D=3D 0.
+          return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros()=
);
+        case Intrinsic::ctlz:
+          // FIXME: This should check for Op2 =3D=3D 1, and become unreach=
able if
+          // Op1 =3D=3D 0.
+          return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
         }
       }
      =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/DIBuild=
er.cpp
--- a/head/contrib/llvm/lib/Analysis/DIBuilder.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/Analysis/DIBuilder.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -17,6 +17,7 @@
 #include "llvm/IntrinsicInst.h"
 #include "llvm/Module.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/Support/Dwarf.h"
=20
 using namespace llvm;
@@ -76,10 +77,11 @@
                                   StringRef Directory, StringRef Producer,
                                   bool isOptimized, StringRef Flags,
                                   unsigned RunTimeVer) {
-  assert (Lang <=3D dwarf::DW_LANG_D && Lang >=3D dwarf::DW_LANG_C89
-	  && "Invalid Language tag");
-  assert (!Filename.empty()=20
-	  && "Unable to create compile unit without filename");
+  assert(((Lang <=3D dwarf::DW_LANG_Python && Lang >=3D dwarf::DW_LANG_C89=
) ||
+          (Lang <=3D dwarf::DW_LANG_hi_user && Lang >=3D dwarf::DW_LANG_lo=
_user)) &&
+         "Invalid Language tag");
+  assert(!Filename.empty() &&
+         "Unable to create compile unit without filename");
   Value *TElts[] =3D { GetTagConstant(VMContext, DW_TAG_base_type) };
   TempEnumTypes =3D MDNode::getTemporary(VMContext, TElts);
   Value *THElts[] =3D { TempEnumTypes };
@@ -189,7 +191,7 @@
   return DIType(MDNode::get(VMContext, Elts));
 }
=20
-/// createQaulifiedType - Create debugging information entry for a qualifi=
ed
+/// createQualifiedType - Create debugging information entry for a qualifi=
ed
 /// type, e.g. 'const int'.
 DIType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
   // Qualified types are encoded in DIDerivedType format.
@@ -358,13 +360,58 @@
   return DIType(MDNode::get(VMContext, Elts));
 }
=20
+/// createObjCIVar - Create debugging information entry for Objective-C
+/// instance variable.
+DIType DIBuilder::createObjCIVar(StringRef Name,
+                                 DIFile File, unsigned LineNumber,
+                                 uint64_t SizeInBits, uint64_t AlignInBits,
+                                 uint64_t OffsetInBits, unsigned Flags,
+                                 DIType Ty, MDNode *PropertyNode) {
+  // TAG_member is encoded in DIDerivedType format.
+  Value *Elts[] =3D {
+    GetTagConstant(VMContext, dwarf::DW_TAG_member),
+    getNonCompileUnitScope(File),
+    MDString::get(VMContext, Name),
+    File,
+    ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
+    ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
+    ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
+    ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
+    ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
+    Ty,
+    PropertyNode
+  };
+  return DIType(MDNode::get(VMContext, Elts));
+}
+
+/// createObjCProperty - Create debugging information entry for Objective-C
+/// property.
+DIObjCProperty DIBuilder::createObjCProperty(StringRef Name,
+					     DIFile File, unsigned LineNumber,
+                                             StringRef GetterName,
+                                             StringRef SetterName,=20
+                                             unsigned PropertyAttributes,
+					     DIType Ty) {
+  Value *Elts[] =3D {
+    GetTagConstant(VMContext, dwarf::DW_TAG_APPLE_property),
+    MDString::get(VMContext, Name),
+    File,
+    ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
+    MDString::get(VMContext, GetterName),
+    MDString::get(VMContext, SetterName),
+    ConstantInt::get(Type::getInt32Ty(VMContext), PropertyAttributes),
+    Ty
+  };
+  return DIObjCProperty(MDNode::get(VMContext, Elts));
+}
+
 /// createClassType - Create debugging information entry for a class.
 DIType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
                                   DIFile File, unsigned LineNumber,
                                   uint64_t SizeInBits, uint64_t AlignInBit=
s,
                                   uint64_t OffsetInBits, unsigned Flags,
                                   DIType DerivedFrom, DIArray Elements,
-                                  MDNode *VTableHoder, MDNode *TemplatePar=
ams) {
+                                  MDNode *VTableHolder, MDNode *TemplatePa=
rams) {
  // TAG_class_type is encoded in DICompositeType format.
   Value *Elts[] =3D {
     GetTagConstant(VMContext, dwarf::DW_TAG_class_type),
@@ -379,7 +426,7 @@
     DerivedFrom,
     Elements,
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
-    VTableHoder,
+    VTableHolder,
     TemplateParams
   };
   return DIType(MDNode::get(VMContext, Elts));
@@ -440,7 +487,7 @@
     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
-    llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
+    NULL,
     Elements,
     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeLang),
     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
@@ -465,7 +512,7 @@
     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
     ConstantInt::get(Type::getInt64Ty(VMContext), 0),
     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
-    llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
+    NULL,
     Elements,
     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeLang),
     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
@@ -484,9 +531,9 @@
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
     ConstantInt::get(Type::getInt64Ty(VMContext), 0),
     ConstantInt::get(Type::getInt64Ty(VMContext), 0),
+    ConstantInt::get(Type::getInt64Ty(VMContext), 0),
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
-    ConstantInt::get(Type::getInt32Ty(VMContext), 0),
-    llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
+    NULL,
     ParameterTypes,
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
@@ -500,7 +547,7 @@
                                         DIFile File, unsigned LineNumber,
                                         uint64_t SizeInBits,
                                         uint64_t AlignInBits,
-					DIArray Elements) {
+                                        DIArray Elements) {
   // TAG_enumeration_type is encoded in DICompositeType format.
   Value *Elts[] =3D {
     GetTagConstant(VMContext, dwarf::DW_TAG_enumeration_type),
@@ -512,7 +559,7 @@
     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
-    llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
+    NULL,
     Elements,
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
@@ -628,6 +675,31 @@
   return DIType(Node);
 }
=20
+/// createForwardDecl - Create a temporary forward-declared type that
+/// can be RAUW'd if the full type is seen.
+DIType DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIFile F,
+                                    unsigned Line, unsigned RuntimeLang) {
+  // Create a temporary MDNode.
+  Value *Elts[] =3D {
+    GetTagConstant(VMContext, Tag),
+    NULL, // TheCU
+    MDString::get(VMContext, Name),
+    F,
+    ConstantInt::get(Type::getInt32Ty(VMContext), Line),
+    // To ease transition include sizes etc of 0.
+    ConstantInt::get(Type::getInt32Ty(VMContext), 0),
+    ConstantInt::get(Type::getInt32Ty(VMContext), 0),
+    ConstantInt::get(Type::getInt32Ty(VMContext), 0),
+    ConstantInt::get(Type::getInt32Ty(VMContext),
+                     DIDescriptor::FlagFwdDecl),
+    NULL,
+    DIArray(),
+    ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
+  };
+  MDNode *Node =3D MDNode::getTemporary(VMContext, Elts);
+  return DIType(Node);
+}
+
 /// getOrCreateArray - Get a DIArray, create one if required.
 DIArray DIBuilder::getOrCreateArray(ArrayRef<Value *> Elements) {
   if (Elements.empty()) {
@@ -738,7 +810,7 @@
   Elts.push_back(MDString::get(VMContext, Name));
   Elts.push_back(F);
   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext),
-				  (LineNo | (ArgNo << 24))));
+                                  (LineNo | (ArgNo << 24))));
   Elts.push_back(Ty);
   Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext))=
);
   Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext))=
);
@@ -754,6 +826,7 @@
                                        DIFile File, unsigned LineNo,
                                        DIType Ty,
                                        bool isLocalToUnit, bool isDefiniti=
on,
+                                       unsigned ScopeLine,
                                        unsigned Flags, bool isOptimized,
                                        Function *Fn,
                                        MDNode *TParams,
@@ -777,13 +850,14 @@
     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
     ConstantInt::get(Type::getInt32Ty(VMContext), 0),
-    llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
+    NULL,
     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
     Fn,
     TParams,
     Decl,
-    THolder
+    THolder,
+    ConstantInt::get(Type::getInt32Ty(VMContext), ScopeLine)
   };
   MDNode *Node =3D MDNode::get(VMContext, Elts);
=20
@@ -831,7 +905,9 @@
     Fn,
     TParam,
     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
-    THolder
+    THolder,
+    // FIXME: Do we want to use a different scope lines?
+    ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
   };
   MDNode *Node =3D MDNode::get(VMContext, Elts);
   return DISubprogram(Node);
@@ -854,7 +930,7 @@
 /// createLexicalBlockFile - This creates a new MDNode that encapsulates
 /// an existing scope with a new filename.
 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
-						     DIFile File) {
+                                                     DIFile File) {
   Value *Elts[] =3D {
     GetTagConstant(VMContext, dwarf::DW_TAG_lexical_block),
     Scope,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/DebugIn=
fo.cpp
--- a/head/contrib/llvm/lib/Analysis/DebugInfo.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/Analysis/DebugInfo.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -68,7 +68,7 @@
     return 0;
=20
   if (Elt < DbgNode->getNumOperands())
-    if (ConstantInt *CI =3D dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)=
))
+    if (ConstantInt *CI =3D dyn_cast_or_null<ConstantInt>(DbgNode->getOper=
and(Elt)))
       return CI->getZExtValue();
=20
   return 0;
@@ -289,6 +289,10 @@
   return DbgNode && getTag() =3D=3D dwarf::DW_TAG_enumerator;
 }
=20
+/// isObjCProperty - Return true if the specified tag is DW_TAG
+bool DIDescriptor::isObjCProperty() const {
+  return DbgNode && getTag() =3D=3D dwarf::DW_TAG_APPLE_property;
+}
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Simple Descriptor Constructors and other Methods
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -373,6 +377,19 @@
   return true;
 }
=20
+/// Verify - Verify that an ObjC property is well formed.
+bool DIObjCProperty::Verify() const {
+  if (!DbgNode)
+    return false;
+  unsigned Tag =3D getTag();
+  if (Tag !=3D dwarf::DW_TAG_APPLE_property) return false;
+  DIType Ty =3D getType();
+  if (!Ty.Verify()) return false;
+
+  // Don't worry about the rest of the strings for now.
+  return true;
+}
+
 /// Verify - Verify that a type descriptor is well formed.
 bool DIType::Verify() const {
   if (!DbgNode)
@@ -482,6 +499,7 @@
 /// return base type size.
 uint64_t DIDerivedType::getOriginalTypeSize() const {
   unsigned Tag =3D getTag();
+
   if (Tag =3D=3D dwarf::DW_TAG_member || Tag =3D=3D dwarf::DW_TAG_typedef =
||
       Tag =3D=3D dwarf::DW_TAG_const_type || Tag =3D=3D dwarf::DW_TAG_vola=
tile_type ||
       Tag =3D=3D dwarf::DW_TAG_restrict_type) {
@@ -490,7 +508,13 @@
     // approach.
     if (!BaseType.isValid())
       return getSizeInBits();
-    if (BaseType.isDerivedType())
+    // If this is a derived type, go ahead and get the base type, unless
+    // it's a reference then it's just the size of the field. Pointer types
+    // have no need of this since they're a different type of qualification
+    // on the type.
+    if (BaseType.getTag() =3D=3D dwarf::DW_TAG_reference_type)
+      return getSizeInBits();
+    else if (BaseType.isDerivedType())
       return DIDerivedType(BaseType).getOriginalTypeSize();
     else
       return BaseType.getSizeInBits();
@@ -499,6 +523,13 @@
   return getSizeInBits();
 }
=20
+/// getObjCProperty - Return property node, if this ivar is associated wit=
h one.
+MDNode *DIDerivedType::getObjCProperty() const {
+  if (getVersion() <=3D LLVMDebugVersion11 || DbgNode->getNumOperands() <=
=3D 10)
+    return NULL;
+  return dyn_cast_or_null<MDNode>(DbgNode->getOperand(10));
+}
+
 /// isInlinedFnArgument - Return true if this variable provides debugging
 /// information for an inlined function arguments.
 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
@@ -565,8 +596,7 @@
     return DIType(DbgNode).getFilename();
   if (isFile())
     return DIFile(DbgNode).getFilename();
-  assert(0 && "Invalid DIScope!");
-  return StringRef();
+  llvm_unreachable("Invalid DIScope!");
 }
=20
 StringRef DIScope::getDirectory() const {
@@ -586,8 +616,7 @@
     return DIType(DbgNode).getDirectory();
   if (isFile())
     return DIFile(DbgNode).getDirectory();
-  assert(0 && "Invalid DIScope!");
-  return StringRef();
+  llvm_unreachable("Invalid DIScope!");
 }
=20
 DIArray DICompileUnit::getEnumTypes() const {
@@ -632,6 +661,32 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// DIDescriptor: vtable anchors for all descriptors.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+void DIScope::anchor() { }
+
+void DICompileUnit::anchor() { }
+
+void DIFile::anchor() { }
+
+void DIType::anchor() { }
+
+void DIBasicType::anchor() { }
+
+void DIDerivedType::anchor() { }
+
+void DICompositeType::anchor() { }
+
+void DISubprogram::anchor() { }
+
+void DILexicalBlock::anchor() { }
+
+void DINameSpace::anchor() { }
+
+void DILexicalBlockFile::anchor() { }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // DIDescriptor: dump routines for all descriptors.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -679,8 +734,13 @@
=20
   if (isBasicType())
     DIBasicType(DbgNode).print(OS);
-  else if (isDerivedType())
-    DIDerivedType(DbgNode).print(OS);
+  else if (isDerivedType()) {
+    DIDerivedType DTy =3D DIDerivedType(DbgNode);
+    DTy.print(OS);
+    DICompositeType CTy =3D getDICompositeType(DTy);
+    if (CTy.Verify())
+      CTy.print(OS);
+  }
   else if (isCompositeType())
     DICompositeType(DbgNode).print(OS);
   else {
@@ -698,7 +758,9 @@
=20
 /// print - Print derived type.
 void DIDerivedType::print(raw_ostream &OS) const {
-  OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
+  OS << "\n\t Derived From: ";
+  getTypeDerivedFrom().print(OS);
+  OS << "\n\t";
 }
=20
 /// print - Print composite type.
@@ -725,6 +787,9 @@
   if (isDefinition())
     OS << " [def] ";
=20
+  if (getScopeLineNumber() !=3D getLineNumber())
+    OS << " [Scope: " << getScopeLineNumber() << "] ";
+
   OS << "\n";
 }
=20
@@ -927,9 +992,30 @@
=20
 /// processModule - Process entire module and collect debug info.
 void DebugInfoFinder::processModule(Module &M) {
-  if (NamedMDNode *CU_Nodes =3D M.getNamedMetadata("llvm.dbg.cu"))
-    for (unsigned i =3D 0, e =3D CU_Nodes->getNumOperands(); i !=3D e; ++i)
-      addCompileUnit(DICompileUnit(CU_Nodes->getOperand(i)));
+  if (NamedMDNode *CU_Nodes =3D M.getNamedMetadata("llvm.dbg.cu")) {
+    for (unsigned i =3D 0, e =3D CU_Nodes->getNumOperands(); i !=3D e; ++i=
) {
+      DICompileUnit CU(CU_Nodes->getOperand(i));
+      addCompileUnit(CU);
+      if (CU.getVersion() > LLVMDebugVersion10) {
+        DIArray GVs =3D CU.getGlobalVariables();
+        for (unsigned i =3D 0, e =3D GVs.getNumElements(); i !=3D e; ++i) {
+          DIGlobalVariable DIG(GVs.getElement(i));
+          if (addGlobalVariable(DIG))
+            processType(DIG.getType());
+        }
+        DIArray SPs =3D CU.getSubprograms();
+        for (unsigned i =3D 0, e =3D SPs.getNumElements(); i !=3D e; ++i)
+          processSubprogram(DISubprogram(SPs.getElement(i)));
+        DIArray EnumTypes =3D CU.getEnumTypes();
+        for (unsigned i =3D 0, e =3D EnumTypes.getNumElements(); i !=3D e;=
 ++i)
+          processType(DIType(EnumTypes.getElement(i)));
+        DIArray RetainedTypes =3D CU.getRetainedTypes();
+        for (unsigned i =3D 0, e =3D RetainedTypes.getNumElements(); i !=
=3D e; ++i)
+          processType(DIType(RetainedTypes.getElement(i)));
+        return;
+      }
+    }
+  }
=20
   for (Module::iterator I =3D M.begin(), E =3D M.end(); I !=3D E; ++I)
     for (Function::iterator FI =3D (*I).begin(), FE =3D (*I).end(); FI !=
=3D FE; ++FI)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Dominan=
ceFrontier.cpp
--- a/head/contrib/llvm/lib/Analysis/DominanceFrontier.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/DominanceFrontier.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -35,6 +35,8 @@
   };
 }
=20
+void DominanceFrontier::anchor() { }
+
 const DominanceFrontier::DomSetType &
 DominanceFrontier::calculate(const DominatorTree &DT,
                              const DomTreeNode *Node) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/IPA/Cal=
lGraph.cpp
--- a/head/contrib/llvm/lib/Analysis/IPA/CallGraph.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/IPA/CallGraph.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -127,16 +127,9 @@
       }
     }
=20
-    // Loop over all of the users of the function, looking for non-call us=
es.
-    for (Value::use_iterator I =3D F->use_begin(), E =3D F->use_end(); I !=
=3D E; ++I){
-      User *U =3D *I;
-      if ((!isa<CallInst>(U) && !isa<InvokeInst>(U))
-          || !CallSite(cast<Instruction>(U)).isCallee(I)) {
-        // Not a call, or being used as a parameter rather than as the cal=
lee.
-        ExternalCallingNode->addCalledFunction(CallSite(), Node);
-        break;
-      }
-    }
+    // If this function has its address taken, anything could call it.
+    if (F->hasAddressTaken())
+      ExternalCallingNode->addCalledFunction(CallSite(), Node);
=20
     // If this function is not defined in this translation unit, it could =
call
     // anything.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/IPA/Glo=
balsModRef.cpp
--- a/head/contrib/llvm/lib/Analysis/IPA/GlobalsModRef.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/IPA/GlobalsModRef.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -21,6 +21,7 @@
 #include "llvm/Instructions.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
+#include "llvm/IntrinsicInst.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Analysis/CallGraph.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
@@ -467,6 +468,11 @@
         } else if (isMalloc(&cast<Instruction>(*II)) ||
                    isFreeCall(&cast<Instruction>(*II))) {
           FunctionEffect |=3D ModRef;
+        } else if (IntrinsicInst *Intrinsic =3D dyn_cast<IntrinsicInst>(&*=
II)) {
+          // The callgraph doesn't include intrinsic calls.
+          Function *Callee =3D Intrinsic->getCalledFunction();
+          ModRefBehavior Behaviour =3D AliasAnalysis::getModRefBehavior(Ca=
llee);
+          FunctionEffect |=3D (Behaviour & ModRef);
         }
=20
     if ((FunctionEffect & Mod) =3D=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/IVUsers=
.cpp
--- a/head/contrib/llvm/lib/Analysis/IVUsers.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/Analysis/IVUsers.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -79,10 +79,44 @@
   return false;
 }
=20
-/// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
+/// Return true if all loop headers that dominate this block are in simpli=
fied
+/// form.
+static bool isSimplifiedLoopNest(BasicBlock *BB, const DominatorTree *DT,
+                                 const LoopInfo *LI,
+                                 SmallPtrSet<Loop*,16> &SimpleLoopNests) {
+  Loop *NearestLoop =3D 0;
+  for (DomTreeNode *Rung =3D DT->getNode(BB);
+       Rung; Rung =3D Rung->getIDom()) {
+    BasicBlock *DomBB =3D Rung->getBlock();
+    Loop *DomLoop =3D LI->getLoopFor(DomBB);
+    if (DomLoop && DomLoop->getHeader() =3D=3D DomBB) {
+      // If the domtree walk reaches a loop with no preheader, return fals=
e.
+      if (!DomLoop->isLoopSimplifyForm())
+        return false;
+      // If we have already checked this loop nest, stop checking.
+      if (SimpleLoopNests.count(DomLoop))
+        break;
+      // If we have not already checked this loop nest, remember the loop
+      // header nearest to BB. The nearest loop may not contain BB.
+      if (!NearestLoop)
+        NearestLoop =3D DomLoop;
+    }
+  }
+  if (NearestLoop)
+    SimpleLoopNests.insert(NearestLoop);
+  return true;
+}
+
+/// AddUsersImpl - Inspect the specified instruction.  If it is a
 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
 /// return true.  Otherwise, return false.
-bool IVUsers::AddUsersIfInteresting(Instruction *I) {
+bool IVUsers::AddUsersImpl(Instruction *I,
+                           SmallPtrSet<Loop*,16> &SimpleLoopNests) {
+  // Add this IV user to the Processed set before returning false to ensur=
e that
+  // all IV users are members of the set. See IVUsers::isIVUserOrOperand.
+  if (!Processed.insert(I))
+    return true;    // Instruction already handled.
+
   if (!SE->isSCEVable(I->getType()))
     return false;   // Void and FP expressions cannot be reduced.
=20
@@ -93,9 +127,6 @@
   if (Width > 64 || (TD && !TD->isLegalInteger(Width)))
     return false;
=20
-  if (!Processed.insert(I))
-    return true;    // Instruction already handled.
-
   // Get the symbolic expression for this instruction.
   const SCEV *ISE =3D SE->getSCEV(I);
=20
@@ -115,6 +146,18 @@
     if (isa<PHINode>(User) && Processed.count(User))
       continue;
=20
+    // Only consider IVUsers that are dominated by simplified loop
+    // headers. Otherwise, SCEVExpander will crash.
+    BasicBlock *UseBB =3D User->getParent();
+    // A phi's use is live out of its predecessor block.
+    if (PHINode *PHI =3D dyn_cast<PHINode>(User)) {
+      unsigned OperandNo =3D UI.getOperandNo();
+      unsigned ValNo =3D PHINode::getIncomingValueNumForOperand(OperandNo);
+      UseBB =3D PHI->getIncomingBlock(ValNo);
+    }
+    if (!isSimplifiedLoopNest(UseBB, DT, LI, SimpleLoopNests))
+      return false;
+
     // Descend recursively, but not into PHI nodes outside the current loo=
p.
     // It's important to see the entire expression outside the loop to get
     // choices that depend on addressing mode use right, although we won't
@@ -124,12 +167,12 @@
     bool AddUserToIVUsers =3D false;
     if (LI->getLoopFor(User->getParent()) !=3D L) {
       if (isa<PHINode>(User) || Processed.count(User) ||
-          !AddUsersIfInteresting(User)) {
+          !AddUsersImpl(User, SimpleLoopNests)) {
         DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
                      << "   OF SCEV: " << *ISE << '\n');
         AddUserToIVUsers =3D true;
       }
-    } else if (Processed.count(User) || !AddUsersIfInteresting(User)) {
+    } else if (Processed.count(User) || !AddUsersImpl(User, SimpleLoopNest=
s)) {
       DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
                    << "   OF SCEV: " << *ISE << '\n');
       AddUserToIVUsers =3D true;
@@ -153,6 +196,15 @@
   return true;
 }
=20
+bool IVUsers::AddUsersIfInteresting(Instruction *I) {
+  // SCEVExpander can only handle users that are dominated by simplified l=
oop
+  // entries. Keep track of all loops that are only dominated by other sim=
ple
+  // loops so we don't traverse the domtree for each user.
+  SmallPtrSet<Loop*,16> SimpleLoopNests;
+
+  return AddUsersImpl(I, SimpleLoopNests);
+}
+
 IVStrideUse &IVUsers::AddUser(Instruction *User, Value *Operand) {
   IVUses.push_back(new IVStrideUse(this, User, Operand));
   return IVUses.back();
@@ -268,6 +320,7 @@
=20
 void IVStrideUse::deleted() {
   // Remove this user from the list.
+  Parent->Processed.erase(this->getUser());
   Parent->IVUses.erase(this);
   // this now dangles!
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/InlineC=
ost.cpp
--- a/head/contrib/llvm/lib/Analysis/InlineCost.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Analysis/InlineCost.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -11,645 +11,1012 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#define DEBUG_TYPE "inline-cost"
 #include "llvm/Analysis/InlineCost.h"
+#include "llvm/Analysis/ConstantFolding.h"
+#include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Support/CallSite.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/InstVisitor.h"
+#include "llvm/Support/GetElementPtrTypeIterator.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/CallingConv.h"
 #include "llvm/IntrinsicInst.h"
+#include "llvm/Operator.h"
+#include "llvm/GlobalAlias.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/Statistic.h"
=20
 using namespace llvm;
=20
-/// callIsSmall - If a call is likely to lower to a single target instruct=
ion,
-/// or is otherwise deemed small return true.
-/// TODO: Perhaps calls like memcpy, strcpy, etc?
-bool llvm::callIsSmall(const Function *F) {
-  if (!F) return false;
+STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
=20
-  if (F->hasLocalLinkage()) return false;
+namespace {
=20
-  if (!F->hasName()) return false;
+class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
+  typedef InstVisitor<CallAnalyzer, bool> Base;
+  friend class InstVisitor<CallAnalyzer, bool>;
=20
-  StringRef Name =3D F->getName();
+  // TargetData if available, or null.
+  const TargetData *const TD;
=20
-  // These will all likely lower to a single selection DAG node.
-  if (Name =3D=3D "copysign" || Name =3D=3D "copysignf" || Name =3D=3D "co=
pysignl" ||
-      Name =3D=3D "fabs" || Name =3D=3D "fabsf" || Name =3D=3D "fabsl" ||
-      Name =3D=3D "sin" || Name =3D=3D "sinf" || Name =3D=3D "sinl" ||
-      Name =3D=3D "cos" || Name =3D=3D "cosf" || Name =3D=3D "cosl" ||
-      Name =3D=3D "sqrt" || Name =3D=3D "sqrtf" || Name =3D=3D "sqrtl" )
+  // The called function.
+  Function &F;
+
+  int Threshold;
+  int Cost;
+  const bool AlwaysInline;
+
+  bool IsRecursive;
+  bool ExposesReturnsTwice;
+  bool HasDynamicAlloca;
+  unsigned NumInstructions, NumVectorInstructions;
+  int FiftyPercentVectorBonus, TenPercentVectorBonus;
+  int VectorBonus;
+
+  // While we walk the potentially-inlined instructions, we build up and
+  // maintain a mapping of simplified values specific to this callsite. The
+  // idea is to propagate any special information we have about arguments =
to
+  // this call through the inlinable section of the function, and account =
for
+  // likely simplifications post-inlining. The most important aspect we tr=
ack
+  // is CFG altering simplifications -- when we prove a basic block dead, =
that
+  // can cause dramatic shifts in the cost of inlining a function.
+  DenseMap<Value *, Constant *> SimplifiedValues;
+
+  // Keep track of the values which map back (through function arguments) =
to
+  // allocas on the caller stack which could be simplified through SROA.
+  DenseMap<Value *, Value *> SROAArgValues;
+
+  // The mapping of caller Alloca values to their accumulated cost savings=
. If
+  // we have to disable SROA for one of the allocas, this tells us how much
+  // cost must be added.
+  DenseMap<Value *, int> SROAArgCosts;
+
+  // Keep track of values which map to a pointer base and constant offset.
+  DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
+
+  // Custom simplification helper routines.
+  bool isAllocaDerivedArg(Value *V);
+  bool lookupSROAArgAndCost(Value *V, Value *&Arg,
+                            DenseMap<Value *, int>::iterator &CostIt);
+  void disableSROA(DenseMap<Value *, int>::iterator CostIt);
+  void disableSROA(Value *V);
+  void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
+                          int InstructionCost);
+  bool handleSROACandidate(bool IsSROAValid,
+                           DenseMap<Value *, int>::iterator CostIt,
+                           int InstructionCost);
+  bool isGEPOffsetConstant(GetElementPtrInst &GEP);
+  bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
+  ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
+
+  // Custom analysis routines.
+  bool analyzeBlock(BasicBlock *BB);
+
+  // Disable several entry points to the visitor so we don't accidentally =
use
+  // them by declaring but not defining them here.
+  void visit(Module *);     void visit(Module &);
+  void visit(Function *);   void visit(Function &);
+  void visit(BasicBlock *); void visit(BasicBlock &);
+
+  // Provide base case for our instruction visit.
+  bool visitInstruction(Instruction &I);
+
+  // Our visit overrides.
+  bool visitAlloca(AllocaInst &I);
+  bool visitPHI(PHINode &I);
+  bool visitGetElementPtr(GetElementPtrInst &I);
+  bool visitBitCast(BitCastInst &I);
+  bool visitPtrToInt(PtrToIntInst &I);
+  bool visitIntToPtr(IntToPtrInst &I);
+  bool visitCastInst(CastInst &I);
+  bool visitUnaryInstruction(UnaryInstruction &I);
+  bool visitICmp(ICmpInst &I);
+  bool visitSub(BinaryOperator &I);
+  bool visitBinaryOperator(BinaryOperator &I);
+  bool visitLoad(LoadInst &I);
+  bool visitStore(StoreInst &I);
+  bool visitCallSite(CallSite CS);
+
+public:
+  CallAnalyzer(const TargetData *TD, Function &Callee, int Threshold)
+    : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
+      AlwaysInline(F.hasFnAttr(Attribute::AlwaysInline)),
+      IsRecursive(false), ExposesReturnsTwice(false), HasDynamicAlloca(fal=
se),
+      NumInstructions(0), NumVectorInstructions(0),
+      FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
+      NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
+      NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
+      NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLos=
t(0) {
+  }
+
+  bool analyzeCall(CallSite CS);
+
+  int getThreshold() { return Threshold; }
+  int getCost() { return Cost; }
+
+  // Keep a bunch of stats about the cost savings found so we can print th=
em
+  // out when debugging.
+  unsigned NumConstantArgs;
+  unsigned NumConstantOffsetPtrArgs;
+  unsigned NumAllocaArgs;
+  unsigned NumConstantPtrCmps;
+  unsigned NumConstantPtrDiffs;
+  unsigned NumInstructionsSimplified;
+  unsigned SROACostSavings;
+  unsigned SROACostSavingsLost;
+
+  void dump();
+};
+
+} // namespace
+
+/// \brief Test whether the given value is an Alloca-derived function argu=
ment.
+bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
+  return SROAArgValues.count(V);
+}
+
+/// \brief Lookup the SROA-candidate argument and cost iterator which V ma=
ps to.
+/// Returns false if V does not map to a SROA-candidate.
+bool CallAnalyzer::lookupSROAArgAndCost(
+    Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
+  if (SROAArgValues.empty() || SROAArgCosts.empty())
+    return false;
+
+  DenseMap<Value *, Value *>::iterator ArgIt =3D SROAArgValues.find(V);
+  if (ArgIt =3D=3D SROAArgValues.end())
+    return false;
+
+  Arg =3D ArgIt->second;
+  CostIt =3D SROAArgCosts.find(Arg);
+  return CostIt !=3D SROAArgCosts.end();
+}
+
+/// \brief Disable SROA for the candidate marked by this cost iterator.
+///
+/// This markes the candidate as no longer viable for SROA, and adds the c=
ost
+/// savings associated with it back into the inline cost measurement.
+void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
+  // If we're no longer able to perform SROA we need to undo its cost savi=
ngs
+  // and prevent subsequent analysis.
+  Cost +=3D CostIt->second;
+  SROACostSavings -=3D CostIt->second;
+  SROACostSavingsLost +=3D CostIt->second;
+  SROAArgCosts.erase(CostIt);
+}
+
+/// \brief If 'V' maps to a SROA candidate, disable SROA for it.
+void CallAnalyzer::disableSROA(Value *V) {
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  if (lookupSROAArgAndCost(V, SROAArg, CostIt))
+    disableSROA(CostIt);
+}
+
+/// \brief Accumulate the given cost for a particular SROA candidate.
+void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator Cos=
tIt,
+                                      int InstructionCost) {
+  CostIt->second +=3D InstructionCost;
+  SROACostSavings +=3D InstructionCost;
+}
+
+/// \brief Helper for the common pattern of handling a SROA candidate.
+/// Either accumulates the cost savings if the SROA remains valid, or disa=
bles
+/// SROA for the candidate.
+bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
+                                       DenseMap<Value *, int>::iterator Co=
stIt,
+                                       int InstructionCost) {
+  if (IsSROAValid) {
+    accumulateSROACost(CostIt, InstructionCost);
+    return true;
+  }
+
+  disableSROA(CostIt);
+  return false;
+}
+
+/// \brief Check whether a GEP's indices are all constant.
+///
+/// Respects any simplified values known during the analysis of this calls=
ite.
+bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
+  for (User::op_iterator I =3D GEP.idx_begin(), E =3D GEP.idx_end(); I !=
=3D E; ++I)
+    if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
+      return false;
+
+  return true;
+}
+
+/// \brief Accumulate a constant GEP offset into an APInt if possible.
+///
+/// Returns false if unable to compute the offset for any reason. Respects=
 any
+/// simplified values known during the analysis of this callsite.
+bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
+  if (!TD)
+    return false;
+
+  unsigned IntPtrWidth =3D TD->getPointerSizeInBits();
+  assert(IntPtrWidth =3D=3D Offset.getBitWidth());
+
+  for (gep_type_iterator GTI =3D gep_type_begin(GEP), GTE =3D gep_type_end=
(GEP);
+       GTI !=3D GTE; ++GTI) {
+    ConstantInt *OpC =3D dyn_cast<ConstantInt>(GTI.getOperand());
+    if (!OpC)
+      if (Constant *SimpleOp =3D SimplifiedValues.lookup(GTI.getOperand()))
+        OpC =3D dyn_cast<ConstantInt>(SimpleOp);
+    if (!OpC)
+      return false;
+    if (OpC->isZero()) continue;
+
+    // Handle a struct index, which adds its field offset to the pointer.
+    if (StructType *STy =3D dyn_cast<StructType>(*GTI)) {
+      unsigned ElementIdx =3D OpC->getZExtValue();
+      const StructLayout *SL =3D TD->getStructLayout(STy);
+      Offset +=3D APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
+      continue;
+    }
+
+    APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType())=
);
+    Offset +=3D OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
+  }
+  return true;
+}
+
+bool CallAnalyzer::visitAlloca(AllocaInst &I) {
+  // FIXME: Check whether inlining will turn a dynamic alloca into a static
+  // alloca, and handle that case.
+
+  // We will happily inline static alloca instructions or dynamic alloca
+  // instructions in always-inline situations.
+  if (AlwaysInline || I.isStaticAlloca())
+    return Base::visitAlloca(I);
+
+  // FIXME: This is overly conservative. Dynamic allocas are inefficient f=
or
+  // a variety of reasons, and so we would like to not inline them into
+  // functions which don't currently have a dynamic alloca. This simply
+  // disables inlining altogether in the presence of a dynamic alloca.
+  HasDynamicAlloca =3D true;
+  return false;
+}
+
+bool CallAnalyzer::visitPHI(PHINode &I) {
+  // FIXME: We should potentially be tracking values through phi nodes,
+  // especially when they collapse to a single value due to deleted CFG ed=
ges
+  // during inlining.
+
+  // FIXME: We need to propagate SROA *disabling* through phi nodes, even
+  // though we don't want to propagate it's bonuses. The idea is to disable
+  // SROA if it *might* be used in an inappropriate manner.
+
+  // Phi nodes are always zero-cost.
+  return true;
+}
+
+bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  bool SROACandidate =3D lookupSROAArgAndCost(I.getPointerOperand(),
+                                            SROAArg, CostIt);
+
+  // Try to fold GEPs of constant-offset call site argument pointers. This
+  // requires target data and inbounds GEPs.
+  if (TD && I.isInBounds()) {
+    // Check if we have a base + offset for the pointer.
+    Value *Ptr =3D I.getPointerOperand();
+    std::pair<Value *, APInt> BaseAndOffset =3D ConstantOffsetPtrs.lookup(=
Ptr);
+    if (BaseAndOffset.first) {
+      // Check if the offset of this GEP is constant, and if so accumulate=
 it
+      // into Offset.
+      if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)=
) {
+        // Non-constant GEPs aren't folded, and disable SROA.
+        if (SROACandidate)
+          disableSROA(CostIt);
+        return false;
+      }
+
+      // Add the result as a new mapping to Base + Offset.
+      ConstantOffsetPtrs[&I] =3D BaseAndOffset;
+
+      // Also handle SROA candidates here, we already know that the GEP is
+      // all-constant indexed.
+      if (SROACandidate)
+        SROAArgValues[&I] =3D SROAArg;
+
+      return true;
+    }
+  }
+
+  if (isGEPOffsetConstant(I)) {
+    if (SROACandidate)
+      SROAArgValues[&I] =3D SROAArg;
+
+    // Constant GEPs are modeled as free.
+    return true;
+  }
+
+  // Variable GEPs will require math and will disable SROA.
+  if (SROACandidate)
+    disableSROA(CostIt);
+  return false;
+}
+
+bool CallAnalyzer::visitBitCast(BitCastInst &I) {
+  // Propagate constants through bitcasts.
+  if (Constant *COp =3D dyn_cast<Constant>(I.getOperand(0)))
+    if (Constant *C =3D ConstantExpr::getBitCast(COp, I.getType())) {
+      SimplifiedValues[&I] =3D C;
+      return true;
+    }
+
+  // Track base/offsets through casts
+  std::pair<Value *, APInt> BaseAndOffset
+    =3D ConstantOffsetPtrs.lookup(I.getOperand(0));
+  // Casts don't change the offset, just wrap it up.
+  if (BaseAndOffset.first)
+    ConstantOffsetPtrs[&I] =3D BaseAndOffset;
+
+  // Also look for SROA candidates here.
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
+    SROAArgValues[&I] =3D SROAArg;
+
+  // Bitcasts are always zero cost.
+  return true;
+}
+
+bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
+  // Propagate constants through ptrtoint.
+  if (Constant *COp =3D dyn_cast<Constant>(I.getOperand(0)))
+    if (Constant *C =3D ConstantExpr::getPtrToInt(COp, I.getType())) {
+      SimplifiedValues[&I] =3D C;
+      return true;
+    }
+
+  // Track base/offset pairs when converted to a plain integer provided the
+  // integer is large enough to represent the pointer.
+  unsigned IntegerSize =3D I.getType()->getScalarSizeInBits();
+  if (TD && IntegerSize >=3D TD->getPointerSizeInBits()) {
+    std::pair<Value *, APInt> BaseAndOffset
+      =3D ConstantOffsetPtrs.lookup(I.getOperand(0));
+    if (BaseAndOffset.first)
+      ConstantOffsetPtrs[&I] =3D BaseAndOffset;
+  }
+
+  // This is really weird. Technically, ptrtoint will disable SROA. Howeve=
r,
+  // unless that ptrtoint is *used* somewhere in the live basic blocks aft=
er
+  // inlining, it will be nuked, and SROA should proceed. All of the uses =
which
+  // would block SROA would also block SROA if applied directly to a point=
er,
+  // and so we can just add the integer in here. The only places where SRO=
A is
+  // preserved either cannot fire on an integer, or won't in-and-of themse=
lves
+  // disable SROA (ext) w/o some later use that we would see and disable.
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
+    SROAArgValues[&I] =3D SROAArg;
+
+  // A ptrtoint cast is free so long as the result is large enough to stor=
e the
+  // pointer, and a legal integer type.
+  return TD && TD->isLegalInteger(IntegerSize) &&
+         IntegerSize >=3D TD->getPointerSizeInBits();
+}
+
+bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
+  // Propagate constants through ptrtoint.
+  if (Constant *COp =3D dyn_cast<Constant>(I.getOperand(0)))
+    if (Constant *C =3D ConstantExpr::getIntToPtr(COp, I.getType())) {
+      SimplifiedValues[&I] =3D C;
+      return true;
+    }
+
+  // Track base/offset pairs when round-tripped through a pointer without
+  // modifications provided the integer is not too large.
+  Value *Op =3D I.getOperand(0);
+  unsigned IntegerSize =3D Op->getType()->getScalarSizeInBits();
+  if (TD && IntegerSize <=3D TD->getPointerSizeInBits()) {
+    std::pair<Value *, APInt> BaseAndOffset =3D ConstantOffsetPtrs.lookup(=
Op);
+    if (BaseAndOffset.first)
+      ConstantOffsetPtrs[&I] =3D BaseAndOffset;
+  }
+
+  // "Propagate" SROA here in the same manner as we do for ptrtoint above.
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
+    SROAArgValues[&I] =3D SROAArg;
+
+  // An inttoptr cast is free so long as the input is a legal integer type
+  // which doesn't contain values outside the range of a pointer.
+  return TD && TD->isLegalInteger(IntegerSize) &&
+         IntegerSize <=3D TD->getPointerSizeInBits();
+}
+
+bool CallAnalyzer::visitCastInst(CastInst &I) {
+  // Propagate constants through ptrtoint.
+  if (Constant *COp =3D dyn_cast<Constant>(I.getOperand(0)))
+    if (Constant *C =3D ConstantExpr::getCast(I.getOpcode(), COp, I.getTyp=
e())) {
+      SimplifiedValues[&I] =3D C;
+      return true;
+    }
+
+  // Disable SROA in the face of arbitrary casts we don't whitelist elsewh=
ere.
+  disableSROA(I.getOperand(0));
+
+  // No-op casts don't have any cost.
+  if (I.isLosslessCast())
     return true;
=20
-  // These are all likely to be optimized into something smaller.
-  if (Name =3D=3D "pow" || Name =3D=3D "powf" || Name =3D=3D "powl" ||
-      Name =3D=3D "exp2" || Name =3D=3D "exp2l" || Name =3D=3D "exp2f" ||
-      Name =3D=3D "floor" || Name =3D=3D "floorf" || Name =3D=3D "ceil" ||
-      Name =3D=3D "round" || Name =3D=3D "ffs" || Name =3D=3D "ffsl" ||
-      Name =3D=3D "abs" || Name =3D=3D "labs" || Name =3D=3D "llabs")
+  // trunc to a native type is free (assuming the target has compare and
+  // shift-right of the same width).
+  if (TD && isa<TruncInst>(I) &&
+      TD->isLegalInteger(TD->getTypeSizeInBits(I.getType())))
     return true;
=20
+  // Result of a cmp instruction is often extended (to be used by other
+  // cmp instructions, logical or return instructions). These are usually
+  // no-ops on most sane targets.
+  if (isa<CmpInst>(I.getOperand(0)))
+    return true;
+
+  // Assume the rest of the casts require work.
+  return false;
+}
+
+bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
+  Value *Operand =3D I.getOperand(0);
+  Constant *Ops[1] =3D { dyn_cast<Constant>(Operand) };
+  if (Ops[0] || (Ops[0] =3D SimplifiedValues.lookup(Operand)))
+    if (Constant *C =3D ConstantFoldInstOperands(I.getOpcode(), I.getType(=
),
+                                               Ops, TD)) {
+      SimplifiedValues[&I] =3D C;
+      return true;
+    }
+
+  // Disable any SROA on the argument to arbitrary unary operators.
+  disableSROA(Operand);
+
   return false;
 }
=20
-/// analyzeBasicBlock - Fill in the current structure with information gle=
aned
-/// from the specified block.
-void CodeMetrics::analyzeBasicBlock(const BasicBlock *BB,
-                                    const TargetData *TD) {
-  ++NumBlocks;
-  unsigned NumInstsBeforeThisBB =3D NumInsts;
-  for (BasicBlock::const_iterator II =3D BB->begin(), E =3D BB->end();
-       II !=3D E; ++II) {
-    if (isa<PHINode>(II)) continue;           // PHI nodes don't count.
-
-    // Special handling for calls.
-    if (isa<CallInst>(II) || isa<InvokeInst>(II)) {
-      if (isa<DbgInfoIntrinsic>(II))
-        continue;  // Debug intrinsics don't count as size.
-
-      ImmutableCallSite CS(cast<Instruction>(II));
-
-      if (const Function *F =3D CS.getCalledFunction()) {
-        // If a function is both internal and has a single use, then it is
-        // extremely likely to get inlined in the future (it was probably
-        // exposed by an interleaved devirtualization pass).
-        if (F->hasInternalLinkage() && F->hasOneUse())
-          ++NumInlineCandidates;
-
-        // If this call is to function itself, then the function is recurs=
ive.
-        // Inlining it into other functions is a bad idea, because this is
-        // basically just a form of loop peeling, and our metrics aren't u=
seful
-        // for that case.
-        if (F =3D=3D BB->getParent())
-          isRecursive =3D true;
+bool CallAnalyzer::visitICmp(ICmpInst &I) {
+  Value *LHS =3D I.getOperand(0), *RHS =3D I.getOperand(1);
+  // First try to handle simplified comparisons.
+  if (!isa<Constant>(LHS))
+    if (Constant *SimpleLHS =3D SimplifiedValues.lookup(LHS))
+      LHS =3D SimpleLHS;
+  if (!isa<Constant>(RHS))
+    if (Constant *SimpleRHS =3D SimplifiedValues.lookup(RHS))
+      RHS =3D SimpleRHS;
+  if (Constant *CLHS =3D dyn_cast<Constant>(LHS))
+    if (Constant *CRHS =3D dyn_cast<Constant>(RHS))
+      if (Constant *C =3D ConstantExpr::getICmp(I.getPredicate(), CLHS, CR=
HS)) {
+        SimplifiedValues[&I] =3D C;
+        return true;
       }
=20
-      if (!isa<IntrinsicInst>(II) && !callIsSmall(CS.getCalledFunction()))=
 {
-        // Each argument to a call takes on average one instruction to set=
 up.
-        NumInsts +=3D CS.arg_size();
+  // Otherwise look for a comparison between constant offset pointers with
+  // a common base.
+  Value *LHSBase, *RHSBase;
+  APInt LHSOffset, RHSOffset;
+  llvm::tie(LHSBase, LHSOffset) =3D ConstantOffsetPtrs.lookup(LHS);
+  if (LHSBase) {
+    llvm::tie(RHSBase, RHSOffset) =3D ConstantOffsetPtrs.lookup(RHS);
+    if (RHSBase && LHSBase =3D=3D RHSBase) {
+      // We have common bases, fold the icmp to a constant based on the
+      // offsets.
+      Constant *CLHS =3D ConstantInt::get(LHS->getContext(), LHSOffset);
+      Constant *CRHS =3D ConstantInt::get(RHS->getContext(), RHSOffset);
+      if (Constant *C =3D ConstantExpr::getICmp(I.getPredicate(), CLHS, CR=
HS)) {
+        SimplifiedValues[&I] =3D C;
+        ++NumConstantPtrCmps;
+        return true;
+      }
+    }
+  }
=20
-        // We don't want inline asm to count as a call - that would preven=
t loop
-        // unrolling. The argument setup cost is still real, though.
-        if (!isa<InlineAsm>(CS.getCalledValue()))
-          ++NumCalls;
+  // If the comparison is an equality comparison with null, we can simplif=
y it
+  // for any alloca-derived argument.
+  if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
+    if (isAllocaDerivedArg(I.getOperand(0))) {
+      // We can actually predict the result of comparisons between an
+      // alloca-derived value and null. Note that this fires regardless of
+      // SROA firing.
+      bool IsNotEqual =3D I.getPredicate() =3D=3D CmpInst::ICMP_NE;
+      SimplifiedValues[&I] =3D IsNotEqual ? ConstantInt::getTrue(I.getType=
())
+                                        : ConstantInt::getFalse(I.getType(=
));
+      return true;
+    }
+
+  // Finally check for SROA candidates in comparisons.
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
+    if (isa<ConstantPointerNull>(I.getOperand(1))) {
+      accumulateSROACost(CostIt, InlineConstants::InstrCost);
+      return true;
+    }
+
+    disableSROA(CostIt);
+  }
+
+  return false;
+}
+
+bool CallAnalyzer::visitSub(BinaryOperator &I) {
+  // Try to handle a special case: we can fold computing the difference of=
 two
+  // constant-related pointers.
+  Value *LHS =3D I.getOperand(0), *RHS =3D I.getOperand(1);
+  Value *LHSBase, *RHSBase;
+  APInt LHSOffset, RHSOffset;
+  llvm::tie(LHSBase, LHSOffset) =3D ConstantOffsetPtrs.lookup(LHS);
+  if (LHSBase) {
+    llvm::tie(RHSBase, RHSOffset) =3D ConstantOffsetPtrs.lookup(RHS);
+    if (RHSBase && LHSBase =3D=3D RHSBase) {
+      // We have common bases, fold the subtract to a constant based on the
+      // offsets.
+      Constant *CLHS =3D ConstantInt::get(LHS->getContext(), LHSOffset);
+      Constant *CRHS =3D ConstantInt::get(RHS->getContext(), RHSOffset);
+      if (Constant *C =3D ConstantExpr::getSub(CLHS, CRHS)) {
+        SimplifiedValues[&I] =3D C;
+        ++NumConstantPtrDiffs;
+        return true;
+      }
+    }
+  }
+
+  // Otherwise, fall back to the generic logic for simplifying and handling
+  // instructions.
+  return Base::visitSub(I);
+}
+
+bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
+  Value *LHS =3D I.getOperand(0), *RHS =3D I.getOperand(1);
+  if (!isa<Constant>(LHS))
+    if (Constant *SimpleLHS =3D SimplifiedValues.lookup(LHS))
+      LHS =3D SimpleLHS;
+  if (!isa<Constant>(RHS))
+    if (Constant *SimpleRHS =3D SimplifiedValues.lookup(RHS))
+      RHS =3D SimpleRHS;
+  Value *SimpleV =3D SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
+  if (Constant *C =3D dyn_cast_or_null<Constant>(SimpleV)) {
+    SimplifiedValues[&I] =3D C;
+    return true;
+  }
+
+  // Disable any SROA on arguments to arbitrary, unsimplified binary opera=
tors.
+  disableSROA(LHS);
+  disableSROA(RHS);
+
+  return false;
+}
+
+bool CallAnalyzer::visitLoad(LoadInst &I) {
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
+    if (I.isSimple()) {
+      accumulateSROACost(CostIt, InlineConstants::InstrCost);
+      return true;
+    }
+
+    disableSROA(CostIt);
+  }
+
+  return false;
+}
+
+bool CallAnalyzer::visitStore(StoreInst &I) {
+  Value *SROAArg;
+  DenseMap<Value *, int>::iterator CostIt;
+  if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
+    if (I.isSimple()) {
+      accumulateSROACost(CostIt, InlineConstants::InstrCost);
+      return true;
+    }
+
+    disableSROA(CostIt);
+  }
+
+  return false;
+}
+
+bool CallAnalyzer::visitCallSite(CallSite CS) {
+  if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice()=
 &&
+      !F.hasFnAttr(Attribute::ReturnsTwice)) {
+    // This aborts the entire analysis.
+    ExposesReturnsTwice =3D true;
+    return false;
+  }
+
+  if (IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(CS.getInstruction())) {
+    switch (II->getIntrinsicID()) {
+    default:
+      return Base::visitCallSite(CS);
+
+    case Intrinsic::dbg_declare:
+    case Intrinsic::dbg_value:
+    case Intrinsic::invariant_start:
+    case Intrinsic::invariant_end:
+    case Intrinsic::lifetime_start:
+    case Intrinsic::lifetime_end:
+    case Intrinsic::memset:
+    case Intrinsic::memcpy:
+    case Intrinsic::memmove:
+    case Intrinsic::objectsize:
+    case Intrinsic::ptr_annotation:
+    case Intrinsic::var_annotation:
+      // SROA can usually chew through these intrinsics and they have no c=
ost
+      // so don't pay the price of analyzing them in detail.
+      return true;
+    }
+  }
+
+  if (Function *F =3D CS.getCalledFunction()) {
+    if (F =3D=3D CS.getInstruction()->getParent()->getParent()) {
+      // This flag will fully abort the analysis, so don't bother with any=
thing
+      // else.
+      IsRecursive =3D true;
+      return false;
+    }
+
+    if (!callIsSmall(F)) {
+      // We account for the average 1 instruction per call argument setup
+      // here.
+      Cost +=3D CS.arg_size() * InlineConstants::InstrCost;
+
+      // Everything other than inline ASM will also have a significant cost
+      // merely from making the call.
+      if (!isa<InlineAsm>(CS.getCalledValue()))
+        Cost +=3D InlineConstants::CallPenalty;
+    }
+
+    return Base::visitCallSite(CS);
+  }
+
+  // Otherwise we're in a very special case -- an indirect function call. =
See
+  // if we can be particularly clever about this.
+  Value *Callee =3D CS.getCalledValue();
+
+  // First, pay the price of the argument setup. We account for the average
+  // 1 instruction per call argument setup here.
+  Cost +=3D CS.arg_size() * InlineConstants::InstrCost;
+
+  // Next, check if this happens to be an indirect function call to a known
+  // function in this inline context. If not, we've done all we can.
+  Function *F =3D dyn_cast_or_null<Function>(SimplifiedValues.lookup(Calle=
e));
+  if (!F)
+    return Base::visitCallSite(CS);
+
+  // If we have a constant that we are calling as a function, we can peer
+  // through it and see the function target. This happens not infrequently
+  // during devirtualization and so we want to give it a hefty bonus for
+  // inlining, but cap that bonus in the event that inlining wouldn't pan
+  // out. Pretend to inline the function, with a custom threshold.
+  CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
+  if (CA.analyzeCall(CS)) {
+    // We were able to inline the indirect call! Subtract the cost from the
+    // bonus we want to apply, but don't go below zero.
+    Cost -=3D std::max(0, InlineConstants::IndirectCallThreshold - CA.getC=
ost());
+  }
+
+  return Base::visitCallSite(CS);
+}
+
+bool CallAnalyzer::visitInstruction(Instruction &I) {
+  // We found something we don't understand or can't handle. Mark any SROA=
-able
+  // values in the operand list as no longer viable.
+  for (User::op_iterator OI =3D I.op_begin(), OE =3D I.op_end(); OI !=3D O=
E; ++OI)
+    disableSROA(*OI);
+
+  return false;
+}
+
+
+/// \brief Analyze a basic block for its contribution to the inline cost.
+///
+/// This method walks the analyzer over every instruction in the given bas=
ic
+/// block and accounts for their cost during inlining at this callsite. It
+/// aborts early if the threshold has been exceeded or an impossible to in=
line
+/// construct has been detected. It returns false if inlining is no longer
+/// viable, and true if inlining remains viable.
+bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
+  for (BasicBlock::iterator I =3D BB->begin(), E =3D llvm::prior(BB->end()=
);
+       I !=3D E; ++I) {
+    ++NumInstructions;
+    if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
+      ++NumVectorInstructions;
+
+    // If the instruction simplified to a constant, there is no cost to th=
is
+    // instruction. Visit the instructions using our InstVisitor to accoun=
t for
+    // all of the per-instruction logic. The visit tree returns true if we
+    // consumed the instruction in any way, and false if the instruction's=
 base
+    // cost should count against inlining.
+    if (Base::visit(I))
+      ++NumInstructionsSimplified;
+    else
+      Cost +=3D InlineConstants::InstrCost;
+
+    // If the visit this instruction detected an uninlinable pattern, abor=
t.
+    if (IsRecursive || ExposesReturnsTwice || HasDynamicAlloca)
+      return false;
+
+    if (NumVectorInstructions > NumInstructions/2)
+      VectorBonus =3D FiftyPercentVectorBonus;
+    else if (NumVectorInstructions > NumInstructions/10)
+      VectorBonus =3D TenPercentVectorBonus;
+    else
+      VectorBonus =3D 0;
+
+    // Check if we've past the threshold so we don't spin in huge basic
+    // blocks that will never inline.
+    if (!AlwaysInline && Cost > (Threshold + VectorBonus))
+      return false;
+  }
+
+  return true;
+}
+
+/// \brief Compute the base pointer and cumulative constant offsets for V.
+///
+/// This strips all constant offsets off of V, leaving it the base pointer=
, and
+/// accumulates the total constant offset applied in the returned constant=
. It
+/// returns 0 if V is not a pointer, and returns the constant '0' if there=
 are
+/// no constant offsets applied.
+ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&=
V) {
+  if (!TD || !V->getType()->isPointerTy())
+    return 0;
+
+  unsigned IntPtrWidth =3D TD->getPointerSizeInBits();
+  APInt Offset =3D APInt::getNullValue(IntPtrWidth);
+
+  // Even though we don't look through PHI nodes, we could be called on an
+  // instruction in an unreachable block, which may be on a cycle.
+  SmallPtrSet<Value *, 4> Visited;
+  Visited.insert(V);
+  do {
+    if (GEPOperator *GEP =3D dyn_cast<GEPOperator>(V)) {
+      if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
+        return 0;
+      V =3D GEP->getPointerOperand();
+    } else if (Operator::getOpcode(V) =3D=3D Instruction::BitCast) {
+      V =3D cast<Operator>(V)->getOperand(0);
+    } else if (GlobalAlias *GA =3D dyn_cast<GlobalAlias>(V)) {
+      if (GA->mayBeOverridden())
+        break;
+      V =3D GA->getAliasee();
+    } else {
+      break;
+    }
+    assert(V->getType()->isPointerTy() && "Unexpected operand type!");
+  } while (Visited.insert(V));
+
+  Type *IntPtrTy =3D TD->getIntPtrType(V->getContext());
+  return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
+}
+
+/// \brief Analyze a call site for potential inlining.
+///
+/// Returns true if inlining this call is viable, and false if it is not
+/// viable. It computes the cost and adjusts the threshold based on numero=
us
+/// factors and heuristics. If this method returns false but the computed =
cost
+/// is below the computed threshold, then inlining was forcibly disabled by
+/// some artifact of the rountine.
+bool CallAnalyzer::analyzeCall(CallSite CS) {
+  ++NumCallsAnalyzed;
+
+  // Track whether the post-inlining function would have more than one bas=
ic
+  // block. A single basic block is often intended for inlining. Balloon t=
he
+  // threshold by 50% until we pass the single-BB phase.
+  bool SingleBB =3D true;
+  int SingleBBBonus =3D Threshold / 2;
+  Threshold +=3D SingleBBBonus;
+
+  // Unless we are always-inlining, perform some tweaks to the cost and
+  // threshold based on the direct callsite information.
+  if (!AlwaysInline) {
+    // We want to more aggressively inline vector-dense kernels, so up the
+    // threshold, and we'll lower it if the % of vector instructions gets =
too
+    // low.
+    assert(NumInstructions =3D=3D 0);
+    assert(NumVectorInstructions =3D=3D 0);
+    FiftyPercentVectorBonus =3D Threshold;
+    TenPercentVectorBonus =3D Threshold / 2;
+
+    // Subtract off one instruction per call argument as those will be fre=
e after
+    // inlining.
+    Cost -=3D CS.arg_size() * InlineConstants::InstrCost;
+
+    // If there is only one call of the function, and it has internal link=
age,
+    // the cost of inlining it drops dramatically.
+    if (F.hasLocalLinkage() && F.hasOneUse() && &F =3D=3D CS.getCalledFunc=
tion())
+      Cost +=3D InlineConstants::LastCallToStaticBonus;
+
+    // If the instruction after the call, or if the normal destination of =
the
+    // invoke is an unreachable instruction, the function is noreturn.  As=
 such,
+    // there is little point in inlining this unless there is literally ze=
ro cost.
+    if (InvokeInst *II =3D dyn_cast<InvokeInst>(CS.getInstruction())) {
+      if (isa<UnreachableInst>(II->getNormalDest()->begin()))
+        Threshold =3D 1;
+    } else if (isa<UnreachableInst>(++BasicBlock::iterator(CS.getInstructi=
on())))
+      Threshold =3D 1;
+
+    // If this function uses the coldcc calling convention, prefer not to =
inline
+    // it.
+    if (F.getCallingConv() =3D=3D CallingConv::Cold)
+      Cost +=3D InlineConstants::ColdccPenalty;
+
+    // Check if we're done. This can happen due to bonuses and penalties.
+    if (Cost > Threshold)
+      return false;
+  }
+
+  if (F.empty())
+    return true;
+
+  // Track whether we've seen a return instruction. The first return
+  // instruction is free, as at least one will usually disappear in inlini=
ng.
+  bool HasReturn =3D false;
+
+  // Populate our simplified values by mapping from function arguments to =
call
+  // arguments with known important simplifications.
+  CallSite::arg_iterator CAI =3D CS.arg_begin();
+  for (Function::arg_iterator FAI =3D F.arg_begin(), FAE =3D F.arg_end();
+       FAI !=3D FAE; ++FAI, ++CAI) {
+    assert(CAI !=3D CS.arg_end());
+    if (Constant *C =3D dyn_cast<Constant>(CAI))
+      SimplifiedValues[FAI] =3D C;
+
+    Value *PtrArg =3D *CAI;
+    if (ConstantInt *C =3D stripAndComputeInBoundsConstantOffsets(PtrArg))=
 {
+      ConstantOffsetPtrs[FAI] =3D std::make_pair(PtrArg, C->getValue());
+
+      // We can SROA any pointer arguments derived from alloca instruction=
s.
+      if (isa<AllocaInst>(PtrArg)) {
+        SROAArgValues[FAI] =3D PtrArg;
+        SROAArgCosts[PtrArg] =3D 0;
+      }
+    }
+  }
+  NumConstantArgs =3D SimplifiedValues.size();
+  NumConstantOffsetPtrArgs =3D ConstantOffsetPtrs.size();
+  NumAllocaArgs =3D SROAArgValues.size();
+
+  // The worklist of live basic blocks in the callee *after* inlining. We =
avoid
+  // adding basic blocks of the callee which can be proven to be dead for =
this
+  // particular call site in order to get more accurate cost estimates. Th=
is
+  // requires a somewhat heavyweight iteration pattern: we need to walk the
+  // basic blocks in a breadth-first order as we insert live successors. To
+  // accomplish this, prioritizing for small iterations because we exit af=
ter
+  // crossing our threshold, we use a small-size optimized SetVector.
+  typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
+                                  SmallPtrSet<BasicBlock *, 16> > BBSetVec=
tor;
+  BBSetVector BBWorklist;
+  BBWorklist.insert(&F.getEntryBlock());
+  // Note that we *must not* cache the size, this loop grows the worklist.
+  for (unsigned Idx =3D 0; Idx !=3D BBWorklist.size(); ++Idx) {
+    // Bail out the moment we cross the threshold. This means we'll under-=
count
+    // the cost, but only when undercounting doesn't matter.
+    if (!AlwaysInline && Cost > (Threshold + VectorBonus))
+      break;
+
+    BasicBlock *BB =3D BBWorklist[Idx];
+    if (BB->empty())
+      continue;
+
+    // Handle the terminator cost here where we can track returns and other
+    // function-wide constructs.
+    TerminatorInst *TI =3D BB->getTerminator();
+
+    // We never want to inline functions that contain an indirectbr.  This=
 is
+    // incorrect because all the blockaddress's (in static global initiali=
zers
+    // for example) would be referring to the original function, and this =
indirect
+    // jump would jump from the inlined copy of the function into the orig=
inal
+    // function which is extremely undefined behavior.
+    // FIXME: This logic isn't really right; we can safely inline functions
+    // with indirectbr's as long as no other function or global references=
 the
+    // blockaddress of a block within the current function.  And as a QOI =
issue,
+    // if someone is using a blockaddress without an indirectbr, and that
+    // reference somehow ends up in another function or global, we probably
+    // don't want to inline this function.
+    if (isa<IndirectBrInst>(TI))
+      return false;
+
+    if (!HasReturn && isa<ReturnInst>(TI))
+      HasReturn =3D true;
+    else
+      Cost +=3D InlineConstants::InstrCost;
+
+    // Analyze the cost of this block. If we blow through the threshold, t=
his
+    // returns false, and we can bail on out.
+    if (!analyzeBlock(BB)) {
+      if (IsRecursive || ExposesReturnsTwice || HasDynamicAlloca)
+        return false;
+      break;
+    }
+
+    // Add in the live successors by first checking whether we have termin=
ator
+    // that may be simplified based on the values simplified by this call.
+    if (BranchInst *BI =3D dyn_cast<BranchInst>(TI)) {
+      if (BI->isConditional()) {
+        Value *Cond =3D BI->getCondition();
+        if (ConstantInt *SimpleCond
+              =3D dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Co=
nd))) {
+          BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0)=
);
+          continue;
+        }
+      }
+    } else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
+      Value *Cond =3D SI->getCondition();
+      if (ConstantInt *SimpleCond
+            =3D dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond=
))) {
+        BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor()=
);
+        continue;
       }
     }
=20
-    if (const AllocaInst *AI =3D dyn_cast<AllocaInst>(II)) {
-      if (!AI->isStaticAlloca())
-        this->usesDynamicAlloca =3D true;
-    }
+    // If we're unable to select a particular successor, just count all of
+    // them.
+    for (unsigned TIdx =3D 0, TSize =3D TI->getNumSuccessors(); TIdx !=3D =
TSize; ++TIdx)
+      BBWorklist.insert(TI->getSuccessor(TIdx));
=20
-    if (isa<ExtractElementInst>(II) || II->getType()->isVectorTy())
-      ++NumVectorInsts;
-
-    if (const CastInst *CI =3D dyn_cast<CastInst>(II)) {
-      // Noop casts, including ptr <-> int,  don't count.
-      if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) ||
-          isa<PtrToIntInst>(CI))
-        continue;
-      // trunc to a native type is free (assuming the target has compare a=
nd
-      // shift-right of the same width).
-      if (isa<TruncInst>(CI) && TD &&
-          TD->isLegalInteger(TD->getTypeSizeInBits(CI->getType())))
-        continue;
-      // Result of a cmp instruction is often extended (to be used by other
-      // cmp instructions, logical or return instructions). These are usua=
lly
-      // nop on most sane targets.
-      if (isa<CmpInst>(CI->getOperand(0)))
-        continue;
-    } else if (const GetElementPtrInst *GEPI =3D dyn_cast<GetElementPtrIns=
t>(II)){
-      // If a GEP has all constant indices, it will probably be folded with
-      // a load/store.
-      if (GEPI->hasAllConstantIndices())
-        continue;
-    }
-
-    ++NumInsts;
-  }
-
-  if (isa<ReturnInst>(BB->getTerminator()))
-    ++NumRets;
-
-  // We never want to inline functions that contain an indirectbr.  This is
-  // incorrect because all the blockaddress's (in static global initialize=
rs
-  // for example) would be referring to the original function, and this in=
direct
-  // jump would jump from the inlined copy of the function into the origin=
al
-  // function which is extremely undefined behavior.
-  if (isa<IndirectBrInst>(BB->getTerminator()))
-    containsIndirectBr =3D true;
-
-  // Remember NumInsts for this BB.
-  NumBBInsts[BB] =3D NumInsts - NumInstsBeforeThisBB;
-}
-
-// CountCodeReductionForConstant - Figure out an approximation for how many
-// instructions will be constant folded if the specified value is constant.
-//
-unsigned CodeMetrics::CountCodeReductionForConstant(Value *V) {
-  unsigned Reduction =3D 0;
-  for (Value::use_iterator UI =3D V->use_begin(), E =3D V->use_end(); UI !=
=3D E;++UI){
-    User *U =3D *UI;
-    if (isa<BranchInst>(U) || isa<SwitchInst>(U)) {
-      // We will be able to eliminate all but one of the successors.
-      const TerminatorInst &TI =3D cast<TerminatorInst>(*U);
-      const unsigned NumSucc =3D TI.getNumSuccessors();
-      unsigned Instrs =3D 0;
-      for (unsigned I =3D 0; I !=3D NumSucc; ++I)
-        Instrs +=3D NumBBInsts[TI.getSuccessor(I)];
-      // We don't know which blocks will be eliminated, so use the average=
 size.
-      Reduction +=3D InlineConstants::InstrCost*Instrs*(NumSucc-1)/NumSucc;
-    } else {
-      // Figure out if this instruction will be removed due to simple cons=
tant
-      // propagation.
-      Instruction &Inst =3D cast<Instruction>(*U);
-
-      // We can't constant propagate instructions which have effects or
-      // read memory.
-      //
-      // FIXME: It would be nice to capture the fact that a load from a
-      // pointer-to-constant-global is actually a *really* good thing to z=
ap.
-      // Unfortunately, we don't know the pointer that may get propagated =
here,
-      // so we can't make this decision.
-      if (Inst.mayReadFromMemory() || Inst.mayHaveSideEffects() ||
-          isa<AllocaInst>(Inst))
-        continue;
-
-      bool AllOperandsConstant =3D true;
-      for (unsigned i =3D 0, e =3D Inst.getNumOperands(); i !=3D e; ++i)
-        if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) !=3D =
V) {
-          AllOperandsConstant =3D false;
-          break;
-        }
-
-      if (AllOperandsConstant) {
-        // We will get to remove this instruction...
-        Reduction +=3D InlineConstants::InstrCost;
-
-        // And any other instructions that use it which become constants
-        // themselves.
-        Reduction +=3D CountCodeReductionForConstant(&Inst);
-      }
-    }
-  }
-  return Reduction;
-}
-
-// CountCodeReductionForAlloca - Figure out an approximation of how much s=
maller
-// the function will be if it is inlined into a context where an argument
-// becomes an alloca.
-//
-unsigned CodeMetrics::CountCodeReductionForAlloca(Value *V) {
-  if (!V->getType()->isPointerTy()) return 0;  // Not a pointer
-  unsigned Reduction =3D 0;
-  for (Value::use_iterator UI =3D V->use_begin(), E =3D V->use_end(); UI !=
=3D E;++UI){
-    Instruction *I =3D cast<Instruction>(*UI);
-    if (isa<LoadInst>(I) || isa<StoreInst>(I))
-      Reduction +=3D InlineConstants::InstrCost;
-    else if (GetElementPtrInst *GEP =3D dyn_cast<GetElementPtrInst>(I)) {
-      // If the GEP has variable indices, we won't be able to do much with=
 it.
-      if (GEP->hasAllConstantIndices())
-        Reduction +=3D CountCodeReductionForAlloca(GEP);
-    } else if (BitCastInst *BCI =3D dyn_cast<BitCastInst>(I)) {
-      // Track pointer through bitcasts.
-      Reduction +=3D CountCodeReductionForAlloca(BCI);
-    } else {
-      // If there is some other strange instruction, we're not going to be=
 able
-      // to do much if we inline this.
-      return 0;
+    // If we had any successors at this point, than post-inlining is likel=
y to
+    // have them as well. Note that we assume any basic blocks which exist=
ed
+    // due to branches or switches which folded above will also fold after
+    // inlining.
+    if (SingleBB && TI->getNumSuccessors() > 1) {
+      // Take off the bonus we applied to the threshold.
+      Threshold -=3D SingleBBBonus;
+      SingleBB =3D false;
     }
   }
=20
-  return Reduction;
+  Threshold +=3D VectorBonus;
+
+  return AlwaysInline || Cost < Threshold;
 }
=20
-/// analyzeFunction - Fill in the current structure with information glean=
ed
-/// from the specified function.
-void CodeMetrics::analyzeFunction(Function *F, const TargetData *TD) {
-  // If this function contains a call to setjmp or _setjmp, never inline
-  // it.  This is a hack because we depend on the user marking their local
-  // variables as volatile if they are live across a setjmp call, and they
-  // probably won't do this in callers.
-  if (F->callsFunctionThatReturnsTwice())
-    callsSetJmp =3D true;
-
-  // Look at the size of the callee.
-  for (Function::const_iterator BB =3D F->begin(), E =3D F->end(); BB !=3D=
 E; ++BB)
-    analyzeBasicBlock(&*BB, TD);
+/// \brief Dump stats about this call's analysis.
+void CallAnalyzer::dump() {
+#define DEBUG_PRINT_STAT(x) llvm::dbgs() << "      " #x ": " << x << "\n"
+  DEBUG_PRINT_STAT(NumConstantArgs);
+  DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
+  DEBUG_PRINT_STAT(NumAllocaArgs);
+  DEBUG_PRINT_STAT(NumConstantPtrCmps);
+  DEBUG_PRINT_STAT(NumConstantPtrDiffs);
+  DEBUG_PRINT_STAT(NumInstructionsSimplified);
+  DEBUG_PRINT_STAT(SROACostSavings);
+  DEBUG_PRINT_STAT(SROACostSavingsLost);
+#undef DEBUG_PRINT_STAT
 }
=20
-/// analyzeFunction - Fill in the current structure with information glean=
ed
-/// from the specified function.
-void InlineCostAnalyzer::FunctionInfo::analyzeFunction(Function *F,
-                                                       const TargetData *T=
D) {
-  Metrics.analyzeFunction(F, TD);
-
-  // A function with exactly one return has it removed during the inlining
-  // process (see InlineFunction), so don't count it.
-  // FIXME: This knowledge should really be encoded outside of FunctionInf=
o.
-  if (Metrics.NumRets=3D=3D1)
-    --Metrics.NumInsts;
-
-  // Check out all of the arguments to the function, figuring out how much
-  // code can be eliminated if one of the arguments is a constant.
-  ArgumentWeights.reserve(F->arg_size());
-  for (Function::arg_iterator I =3D F->arg_begin(), E =3D F->arg_end(); I =
!=3D E; ++I)
-    ArgumentWeights.push_back(ArgInfo(Metrics.CountCodeReductionForConstan=
t(I),
-                                      Metrics.CountCodeReductionForAlloca(=
I)));
+InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
+  return getInlineCost(CS, CS.getCalledFunction(), Threshold);
 }
=20
-/// NeverInline - returns true if the function should never be inlined into
-/// any caller
-bool InlineCostAnalyzer::FunctionInfo::NeverInline() {
-  return (Metrics.callsSetJmp || Metrics.isRecursive ||
-          Metrics.containsIndirectBr);
-}
-// getSpecializationBonus - The heuristic used to determine the per-call
-// performance boost for using a specialization of Callee with argument
-// specializedArgNo replaced by a constant.
-int InlineCostAnalyzer::getSpecializationBonus(Function *Callee,
-         SmallVectorImpl<unsigned> &SpecializedArgNos)
-{
-  if (Callee->mayBeOverridden())
-    return 0;
-
-  int Bonus =3D 0;
-  // If this function uses the coldcc calling convention, prefer not to
-  // specialize it.
-  if (Callee->getCallingConv() =3D=3D CallingConv::Cold)
-    Bonus -=3D InlineConstants::ColdccPenalty;
-
-  // Get information about the callee.
-  FunctionInfo *CalleeFI =3D &CachedFunctionInfo[Callee];
-
-  // If we haven't calculated this information yet, do so now.
-  if (CalleeFI->Metrics.NumBlocks =3D=3D 0)
-    CalleeFI->analyzeFunction(Callee, TD);
-
-  unsigned ArgNo =3D 0;
-  unsigned i =3D 0;
-  for (Function::arg_iterator I =3D Callee->arg_begin(), E =3D Callee->arg=
_end();
-       I !=3D E; ++I, ++ArgNo)
-    if (ArgNo =3D=3D SpecializedArgNos[i]) {
-      ++i;
-      Bonus +=3D CountBonusForConstant(I);
-    }
-
-  // Calls usually take a long time, so they make the specialization gain
-  // smaller.
-  Bonus -=3D CalleeFI->Metrics.NumCalls * InlineConstants::CallPenalty;
-
-  return Bonus;
-}
-
-// ConstantFunctionBonus - Figure out how much of a bonus we can get for
-// possibly devirtualizing a function. We'll subtract the size of the func=
tion
-// we may wish to inline from the indirect call bonus providing a limit on
-// growth. Leave an upper limit of 0 for the bonus - we don't want to pena=
lize
-// inlining because we decide we don't want to give a bonus for
-// devirtualizing.
-int InlineCostAnalyzer::ConstantFunctionBonus(CallSite CS, Constant *C) {
-
-  // This could just be NULL.
-  if (!C) return 0;
-
-  Function *F =3D dyn_cast<Function>(C);
-  if (!F) return 0;
-
-  int Bonus =3D InlineConstants::IndirectCallBonus + getInlineSize(CS, F);
-  return (Bonus > 0) ? 0 : Bonus;
-}
-
-// CountBonusForConstant - Figure out an approximation for how much per-ca=
ll
-// performance boost we can expect if the specified value is constant.
-int InlineCostAnalyzer::CountBonusForConstant(Value *V, Constant *C) {
-  unsigned Bonus =3D 0;
-  for (Value::use_iterator UI =3D V->use_begin(), E =3D V->use_end(); UI !=
=3D E;++UI){
-    User *U =3D *UI;
-    if (CallInst *CI =3D dyn_cast<CallInst>(U)) {
-      // Turning an indirect call into a direct call is a BIG win
-      if (CI->getCalledValue() =3D=3D V)
-        Bonus +=3D ConstantFunctionBonus(CallSite(CI), C);
-    } else if (InvokeInst *II =3D dyn_cast<InvokeInst>(U)) {
-      // Turning an indirect call into a direct call is a BIG win
-      if (II->getCalledValue() =3D=3D V)
-        Bonus +=3D ConstantFunctionBonus(CallSite(II), C);
-    }
-    // FIXME: Eliminating conditional branches and switches should
-    // also yield a per-call performance boost.
-    else {
-      // Figure out the bonuses that wll accrue due to simple constant
-      // propagation.
-      Instruction &Inst =3D cast<Instruction>(*U);
-
-      // We can't constant propagate instructions which have effects or
-      // read memory.
-      //
-      // FIXME: It would be nice to capture the fact that a load from a
-      // pointer-to-constant-global is actually a *really* good thing to z=
ap.
-      // Unfortunately, we don't know the pointer that may get propagated =
here,
-      // so we can't make this decision.
-      if (Inst.mayReadFromMemory() || Inst.mayHaveSideEffects() ||
-          isa<AllocaInst>(Inst))
-        continue;
-
-      bool AllOperandsConstant =3D true;
-      for (unsigned i =3D 0, e =3D Inst.getNumOperands(); i !=3D e; ++i)
-        if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) !=3D =
V) {
-          AllOperandsConstant =3D false;
-          break;
-        }
-
-      if (AllOperandsConstant)
-        Bonus +=3D CountBonusForConstant(&Inst);
-    }
-  }
-
-  return Bonus;
-}
-
-int InlineCostAnalyzer::getInlineSize(CallSite CS, Function *Callee) {
-  // Get information about the callee.
-  FunctionInfo *CalleeFI =3D &CachedFunctionInfo[Callee];
-
-  // If we haven't calculated this information yet, do so now.
-  if (CalleeFI->Metrics.NumBlocks =3D=3D 0)
-    CalleeFI->analyzeFunction(Callee, TD);
-
-  // InlineCost - This value measures how good of an inline candidate this=
 call
-  // site is to inline.  A lower inline cost make is more likely for the c=
all to
-  // be inlined.  This value may go negative.
-  //
-  int InlineCost =3D 0;
-
-  // Compute any size reductions we can expect due to arguments being pass=
ed into
-  // the function.
-  //
-  unsigned ArgNo =3D 0;
-  CallSite::arg_iterator I =3D CS.arg_begin();
-  for (Function::arg_iterator FI =3D Callee->arg_begin(), FE =3D Callee->a=
rg_end();
-       FI !=3D FE; ++I, ++FI, ++ArgNo) {
-
-    // If an alloca is passed in, inlining this function is likely to allow
-    // significant future optimization possibilities (like scalar promotio=
n, and
-    // scalarization), so encourage the inlining of the function.
-    //
-    if (isa<AllocaInst>(I))
-      InlineCost -=3D CalleeFI->ArgumentWeights[ArgNo].AllocaWeight;
-
-    // If this is a constant being passed into the function, use the argum=
ent
-    // weights calculated for the callee to determine how much will be fol=
ded
-    // away with this information.
-    else if (isa<Constant>(I))
-      InlineCost -=3D CalleeFI->ArgumentWeights[ArgNo].ConstantWeight;
-  }
-
-  // Each argument passed in has a cost at both the caller and the callee
-  // sides.  Measurements show that each argument costs about the same as =
an
-  // instruction.
-  InlineCost -=3D (CS.arg_size() * InlineConstants::InstrCost);
-
-  // Now that we have considered all of the factors that make the call sit=
e more
-  // likely to be inlined, look at factors that make us not want to inline=
 it.
-
-  // Calls usually take a long time, so they make the inlining gain smalle=
r.
-  InlineCost +=3D CalleeFI->Metrics.NumCalls * InlineConstants::CallPenalt=
y;
-
-  // Look at the size of the callee. Each instruction counts as 5.
-  InlineCost +=3D CalleeFI->Metrics.NumInsts*InlineConstants::InstrCost;
-
-  return InlineCost;
-}
-
-int InlineCostAnalyzer::getInlineBonuses(CallSite CS, Function *Callee) {
-  // Get information about the callee.
-  FunctionInfo *CalleeFI =3D &CachedFunctionInfo[Callee];
-
-  // If we haven't calculated this information yet, do so now.
-  if (CalleeFI->Metrics.NumBlocks =3D=3D 0)
-    CalleeFI->analyzeFunction(Callee, TD);
-
-  bool isDirectCall =3D CS.getCalledFunction() =3D=3D Callee;
-  Instruction *TheCall =3D CS.getInstruction();
-  int Bonus =3D 0;
-
-  // If there is only one call of the function, and it has internal linkag=
e,
-  // make it almost guaranteed to be inlined.
-  //
-  if (Callee->hasLocalLinkage() && Callee->hasOneUse() && isDirectCall)
-    Bonus +=3D InlineConstants::LastCallToStaticBonus;
-
-  // If the instruction after the call, or if the normal destination of the
-  // invoke is an unreachable instruction, the function is noreturn.  As s=
uch,
-  // there is little point in inlining this.
-  if (InvokeInst *II =3D dyn_cast<InvokeInst>(TheCall)) {
-    if (isa<UnreachableInst>(II->getNormalDest()->begin()))
-      Bonus +=3D InlineConstants::NoreturnPenalty;
-  } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
-    Bonus +=3D InlineConstants::NoreturnPenalty;
-
-  // If this function uses the coldcc calling convention, prefer not to in=
line
-  // it.
-  if (Callee->getCallingConv() =3D=3D CallingConv::Cold)
-    Bonus +=3D InlineConstants::ColdccPenalty;
-
-  // Add to the inline quality for properties that make the call valuable =
to
-  // inline.  This includes factors that indicate that the result of inlin=
ing
-  // the function will be optimizable.  Currently this just looks at argum=
ents
-  // passed into the function.
-  //
-  CallSite::arg_iterator I =3D CS.arg_begin();
-  for (Function::arg_iterator FI =3D Callee->arg_begin(), FE =3D Callee->a=
rg_end();
-       FI !=3D FE; ++I, ++FI)
-    // Compute any constant bonus due to inlining we want to give here.
-    if (isa<Constant>(I))
-      Bonus +=3D CountBonusForConstant(FI, cast<Constant>(I));
-
-  return Bonus;
-}
-
-// getInlineCost - The heuristic used to determine if we should inline the
-// function call or not.
-//
-InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS,
-                               SmallPtrSet<const Function*, 16> &NeverInli=
ne) {
-  return getInlineCost(CS, CS.getCalledFunction(), NeverInline);
-}
-
-InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS,
-                               Function *Callee,
-                               SmallPtrSet<const Function*, 16> &NeverInli=
ne) {
-  Instruction *TheCall =3D CS.getInstruction();
-  Function *Caller =3D TheCall->getParent()->getParent();
-
+InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
+                                             int Threshold) {
   // Don't inline functions which can be redefined at link-time to mean
   // something else.  Don't inline functions marked noinline or call sites
   // marked noinline.
-  if (Callee->mayBeOverridden() ||
-      Callee->hasFnAttr(Attribute::NoInline) || NeverInline.count(Callee) =
||
-      CS.isNoInline())
+  if (!Callee || Callee->mayBeOverridden() ||
+      Callee->hasFnAttr(Attribute::NoInline) || CS.isNoInline())
     return llvm::InlineCost::getNever();
=20
-  // Get information about the callee.
-  FunctionInfo *CalleeFI =3D &CachedFunctionInfo[Callee];
+  DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName() <<=
 "...\n");
=20
-  // If we haven't calculated this information yet, do so now.
-  if (CalleeFI->Metrics.NumBlocks =3D=3D 0)
-    CalleeFI->analyzeFunction(Callee, TD);
+  CallAnalyzer CA(TD, *Callee, Threshold);
+  bool ShouldInline =3D CA.analyzeCall(CS);
=20
-  // If we should never inline this, return a huge cost.
-  if (CalleeFI->NeverInline())
+  DEBUG(CA.dump());
+
+  // Check if there was a reason to force inlining or no inlining.
+  if (!ShouldInline && CA.getCost() < CA.getThreshold())
     return InlineCost::getNever();
-
-  // FIXME: It would be nice to kill off CalleeFI->NeverInline. Then we
-  // could move this up and avoid computing the FunctionInfo for
-  // things we are going to just return always inline for. This
-  // requires handling setjmp somewhere else, however.
-  if (!Callee->isDeclaration() && Callee->hasFnAttr(Attribute::AlwaysInlin=
e))
+  if (ShouldInline && CA.getCost() >=3D CA.getThreshold())
     return InlineCost::getAlways();
=20
-  if (CalleeFI->Metrics.usesDynamicAlloca) {
-    // Get information about the caller.
-    FunctionInfo &CallerFI =3D CachedFunctionInfo[Caller];
-
-    // If we haven't calculated this information yet, do so now.
-    if (CallerFI.Metrics.NumBlocks =3D=3D 0) {
-      CallerFI.analyzeFunction(Caller, TD);
-
-      // Recompute the CalleeFI pointer, getting Caller could have invalid=
ated
-      // it.
-      CalleeFI =3D &CachedFunctionInfo[Callee];
-    }
-
-    // Don't inline a callee with dynamic alloca into a caller without the=
m.
-    // Functions containing dynamic alloca's are inefficient in various wa=
ys;
-    // don't create more inefficiency.
-    if (!CallerFI.Metrics.usesDynamicAlloca)
-      return InlineCost::getNever();
-  }
-
-  // InlineCost - This value measures how good of an inline candidate this=
 call
-  // site is to inline.  A lower inline cost make is more likely for the c=
all to
-  // be inlined.  This value may go negative due to the fact that bonuses
-  // are negative numbers.
-  //
-  int InlineCost =3D getInlineSize(CS, Callee) + getInlineBonuses(CS, Call=
ee);
-  return llvm::InlineCost::get(InlineCost);
+  return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
 }
-
-// getSpecializationCost - The heuristic used to determine the code-size
-// impact of creating a specialized version of Callee with argument
-// SpecializedArgNo replaced by a constant.
-InlineCost InlineCostAnalyzer::getSpecializationCost(Function *Callee,
-                               SmallVectorImpl<unsigned> &SpecializedArgNo=
s)
-{
-  // Don't specialize functions which can be redefined at link-time to mean
-  // something else.
-  if (Callee->mayBeOverridden())
-    return llvm::InlineCost::getNever();
-
-  // Get information about the callee.
-  FunctionInfo *CalleeFI =3D &CachedFunctionInfo[Callee];
-
-  // If we haven't calculated this information yet, do so now.
-  if (CalleeFI->Metrics.NumBlocks =3D=3D 0)
-    CalleeFI->analyzeFunction(Callee, TD);
-
-  int Cost =3D 0;
-
-  // Look at the original size of the callee.  Each instruction counts as =
5.
-  Cost +=3D CalleeFI->Metrics.NumInsts * InlineConstants::InstrCost;
-
-  // Offset that with the amount of code that can be constant-folded
-  // away with the given arguments replaced by constants.
-  for (SmallVectorImpl<unsigned>::iterator an =3D SpecializedArgNos.begin(=
),
-       ae =3D SpecializedArgNos.end(); an !=3D ae; ++an)
-    Cost -=3D CalleeFI->ArgumentWeights[*an].ConstantWeight;
-
-  return llvm::InlineCost::get(Cost);
-}
-
-// getInlineFudgeFactor - Return a > 1.0 factor if the inliner should use a
-// higher threshold to determine if the function call should be inlined.
-float InlineCostAnalyzer::getInlineFudgeFactor(CallSite CS) {
-  Function *Callee =3D CS.getCalledFunction();
-
-  // Get information about the callee.
-  FunctionInfo &CalleeFI =3D CachedFunctionInfo[Callee];
-
-  // If we haven't calculated this information yet, do so now.
-  if (CalleeFI.Metrics.NumBlocks =3D=3D 0)
-    CalleeFI.analyzeFunction(Callee, TD);
-
-  float Factor =3D 1.0f;
-  // Single BB functions are often written to be inlined.
-  if (CalleeFI.Metrics.NumBlocks =3D=3D 1)
-    Factor +=3D 0.5f;
-
-  // Be more aggressive if the function contains a good chunk (if it mades=
 up
-  // at least 10% of the instructions) of vector instructions.
-  if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/2)
-    Factor +=3D 2.0f;
-  else if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/10)
-    Factor +=3D 1.5f;
-  return Factor;
-}
-
-/// growCachedCostInfo - update the cached cost info for Caller after Call=
ee has
-/// been inlined.
-void
-InlineCostAnalyzer::growCachedCostInfo(Function *Caller, Function *Callee)=
 {
-  CodeMetrics &CallerMetrics =3D CachedFunctionInfo[Caller].Metrics;
-
-  // For small functions we prefer to recalculate the cost for better accu=
racy.
-  if (CallerMetrics.NumBlocks < 10 && CallerMetrics.NumInsts < 1000) {
-    resetCachedCostInfo(Caller);
-    return;
-  }
-
-  // For large functions, we can save a lot of computation time by skipping
-  // recalculations.
-  if (CallerMetrics.NumCalls > 0)
-    --CallerMetrics.NumCalls;
-
-  if (Callee =3D=3D 0) return;
-
-  CodeMetrics &CalleeMetrics =3D CachedFunctionInfo[Callee].Metrics;
-
-  // If we don't have metrics for the callee, don't recalculate them just =
to
-  // update an approximation in the caller.  Instead, just recalculate the
-  // caller info from scratch.
-  if (CalleeMetrics.NumBlocks =3D=3D 0) {
-    resetCachedCostInfo(Caller);
-    return;
-  }
-
-  // Since CalleeMetrics were already calculated, we know that the CallerM=
etrics
-  // reference isn't invalidated: both were in the DenseMap.
-  CallerMetrics.usesDynamicAlloca |=3D CalleeMetrics.usesDynamicAlloca;
-
-  // FIXME: If any of these three are true for the callee, the callee was
-  // not inlined into the caller, so I think they're redundant here.
-  CallerMetrics.callsSetJmp |=3D CalleeMetrics.callsSetJmp;
-  CallerMetrics.isRecursive |=3D CalleeMetrics.isRecursive;
-  CallerMetrics.containsIndirectBr |=3D CalleeMetrics.containsIndirectBr;
-
-  CallerMetrics.NumInsts +=3D CalleeMetrics.NumInsts;
-  CallerMetrics.NumBlocks +=3D CalleeMetrics.NumBlocks;
-  CallerMetrics.NumCalls +=3D CalleeMetrics.NumCalls;
-  CallerMetrics.NumVectorInsts +=3D CalleeMetrics.NumVectorInsts;
-  CallerMetrics.NumRets +=3D CalleeMetrics.NumRets;
-
-  // analyzeBasicBlock counts each function argument as an inst.
-  if (CallerMetrics.NumInsts >=3D Callee->arg_size())
-    CallerMetrics.NumInsts -=3D Callee->arg_size();
-  else
-    CallerMetrics.NumInsts =3D 0;
-
-  // We are not updating the argument weights. We have already determined =
that
-  // Caller is a fairly large function, so we accept the loss of precision.
-}
-
-/// clear - empty the cache of inline costs
-void InlineCostAnalyzer::clear() {
-  CachedFunctionInfo.clear();
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Instruc=
tionSimplify.cpp
--- a/head/contrib/llvm/lib/Analysis/InstructionSimplify.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/InstructionSimplify.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -18,13 +18,17 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "instsimplify"
+#include "llvm/GlobalAlias.h"
 #include "llvm/Operator.h"
 #include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/SetVector.h"
 #include "llvm/Analysis/InstructionSimplify.h"
+#include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Support/ConstantRange.h"
+#include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/Support/PatternMatch.h"
 #include "llvm/Support/ValueHandle.h"
 #include "llvm/Target/TargetData.h"
@@ -37,23 +41,28 @@
 STATISTIC(NumFactor , "Number of factorizations");
 STATISTIC(NumReassoc, "Number of reassociations");
=20
-static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
-                              const DominatorTree *, unsigned);
-static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
-                            const DominatorTree *, unsigned);
-static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData=
 *,
-                              const DominatorTree *, unsigned);
-static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
-                             const DominatorTree *, unsigned);
-static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
-                              const DominatorTree *, unsigned);
+struct Query {
+  const TargetData *TD;
+  const TargetLibraryInfo *TLI;
+  const DominatorTree *DT;
+
+  Query(const TargetData *td, const TargetLibraryInfo *tli,
+        const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {};
+};
+
+static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
+static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
+                            unsigned);
+static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
+                              unsigned);
+static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
+static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
+static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
=20
 /// getFalse - For a boolean type, or a vector of boolean type, return fal=
se, or
 /// a vector with every element false, as appropriate for the type.
 static Constant *getFalse(Type *Ty) {
-  assert((Ty->isIntegerTy(1) ||
-          (Ty->isVectorTy() &&
-           cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
+  assert(Ty->getScalarType()->isIntegerTy(1) &&
          "Expected i1 type or a vector of i1!");
   return Constant::getNullValue(Ty);
 }
@@ -61,13 +70,25 @@
 /// getTrue - For a boolean type, or a vector of boolean type, return true=
, or
 /// a vector with every element true, as appropriate for the type.
 static Constant *getTrue(Type *Ty) {
-  assert((Ty->isIntegerTy(1) ||
-          (Ty->isVectorTy() &&
-           cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
+  assert(Ty->getScalarType()->isIntegerTy(1) &&
          "Expected i1 type or a vector of i1!");
   return Constant::getAllOnesValue(Ty);
 }
=20
+/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
+static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
+                          Value *RHS) {
+  CmpInst *Cmp =3D dyn_cast<CmpInst>(V);
+  if (!Cmp)
+    return false;
+  CmpInst::Predicate CPred =3D Cmp->getPredicate();
+  Value *CLHS =3D Cmp->getOperand(0), *CRHS =3D Cmp->getOperand(1);
+  if (CPred =3D=3D Pred && CLHS =3D=3D LHS && CRHS =3D=3D RHS)
+    return true;
+  return CPred =3D=3D CmpInst::getSwappedPredicate(Pred) && CLHS =3D=3D RH=
S &&
+    CRHS =3D=3D LHS;
+}
+
 /// ValueDominatesPHI - Does the given value dominate the specified phi no=
de?
 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *D=
T) {
   Instruction *I =3D dyn_cast<Instruction>(V);
@@ -75,9 +96,20 @@
     // Arguments and constants dominate all instructions.
     return true;
=20
+  // If we are processing instructions (and/or basic blocks) that have not=
 been
+  // fully added to a function, the parent nodes may still be null. Simply
+  // return the conservative answer in these cases.
+  if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
+    return false;
+
   // If we have a DominatorTree then do a precise test.
-  if (DT)
+  if (DT) {
+    if (!DT->isReachableFromEntry(P->getParent()))
+      return true;
+    if (!DT->isReachableFromEntry(I->getParent()))
+      return false;
     return DT->dominates(I, P);
+  }
=20
   // Otherwise, if the instruction is in the entry block, and is not an in=
voke,
   // then it obviously dominates all phi nodes.
@@ -94,8 +126,8 @@
 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)=
".
 /// Returns the simplified value, or null if no simplification was perform=
ed.
 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
-                          unsigned OpcToExpand, const TargetData *TD,
-                          const DominatorTree *DT, unsigned MaxRecurse) {
+                          unsigned OpcToExpand, const Query &Q,
+                          unsigned MaxRecurse) {
   Instruction::BinaryOps OpcodeToExpand =3D (Instruction::BinaryOps)OpcToE=
xpand;
   // Recursion is always used, so bail out at once if we already hit the l=
imit.
   if (!MaxRecurse--)
@@ -107,8 +139,8 @@
       // It does!  Try turning it into "(A op C) op' (B op C)".
       Value *A =3D Op0->getOperand(0), *B =3D Op0->getOperand(1), *C =3D R=
HS;
       // Do "A op C" and "B op C" both simplify?
-      if (Value *L =3D SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
-        if (Value *R =3D SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
+      if (Value *L =3D SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
+        if (Value *R =3D SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
           // They do! Return "L op' R" if it simplifies or is already avai=
lable.
           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
           if ((L =3D=3D A && R =3D=3D B) || (Instruction::isCommutative(Op=
codeToExpand)
@@ -117,8 +149,7 @@
             return LHS;
           }
           // Otherwise return "L op' R" if it simplifies.
-          if (Value *V =3D SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
-                                       MaxRecurse)) {
+          if (Value *V =3D SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecur=
se)) {
             ++NumExpand;
             return V;
           }
@@ -131,8 +162,8 @@
       // It does!  Try turning it into "(A op B) op' (A op C)".
       Value *A =3D LHS, *B =3D Op1->getOperand(0), *C =3D Op1->getOperand(=
1);
       // Do "A op B" and "A op C" both simplify?
-      if (Value *L =3D SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
-        if (Value *R =3D SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
+      if (Value *L =3D SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
+        if (Value *R =3D SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
           // They do! Return "L op' R" if it simplifies or is already avai=
lable.
           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
           if ((L =3D=3D B && R =3D=3D C) || (Instruction::isCommutative(Op=
codeToExpand)
@@ -141,8 +172,7 @@
             return RHS;
           }
           // Otherwise return "L op' R" if it simplifies.
-          if (Value *V =3D SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
-                                       MaxRecurse)) {
+          if (Value *V =3D SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecur=
se)) {
             ++NumExpand;
             return V;
           }
@@ -157,8 +187,8 @@
 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(=
B+C)".
 /// Returns the simplified value, or null if no simplification was perform=
ed.
 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
-                             unsigned OpcToExtract, const TargetData *TD,
-                             const DominatorTree *DT, unsigned MaxRecurse)=
 {
+                             unsigned OpcToExtract, const Query &Q,
+                             unsigned MaxRecurse) {
   Instruction::BinaryOps OpcodeToExtract =3D (Instruction::BinaryOps)OpcTo=
Extract;
   // Recursion is always used, so bail out at once if we already hit the l=
imit.
   if (!MaxRecurse--)
@@ -182,7 +212,7 @@
     Value *DD =3D A =3D=3D C ? D : C;
     // Form "A op' (B op DD)" if it simplifies completely.
     // Does "B op DD" simplify?
-    if (Value *V =3D SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
+    if (Value *V =3D SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
       // It does!  Return "A op' V" if it simplifies or is already availab=
le.
       // If V equals B then "A op' V" is just the LHS.  If V equals DD then
       // "A op' V" is just the RHS.
@@ -191,7 +221,7 @@
         return V =3D=3D B ? LHS : RHS;
       }
       // Otherwise return "A op' V" if it simplifies.
-      if (Value *W =3D SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRec=
urse)) {
+      if (Value *W =3D SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)=
) {
         ++NumFactor;
         return W;
       }
@@ -205,7 +235,7 @@
     Value *CC =3D B =3D=3D D ? C : D;
     // Form "(A op CC) op' B" if it simplifies completely..
     // Does "A op CC" simplify?
-    if (Value *V =3D SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
+    if (Value *V =3D SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
       // It does!  Return "V op' B" if it simplifies or is already availab=
le.
       // If V equals A then "V op' B" is just the LHS.  If V equals CC then
       // "V op' B" is just the RHS.
@@ -214,7 +244,7 @@
         return V =3D=3D A ? LHS : RHS;
       }
       // Otherwise return "V op' B" if it simplifies.
-      if (Value *W =3D SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRec=
urse)) {
+      if (Value *W =3D SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)=
) {
         ++NumFactor;
         return W;
       }
@@ -227,9 +257,7 @@
 /// SimplifyAssociativeBinOp - Generic simplifications for associative bin=
ary
 /// operations.  Returns the simpler value, or null if none was found.
 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RH=
S,
-                                       const TargetData *TD,
-                                       const DominatorTree *DT,
-                                       unsigned MaxRecurse) {
+                                       const Query &Q, unsigned MaxRecurse=
) {
   Instruction::BinaryOps Opcode =3D (Instruction::BinaryOps)Opc;
   assert(Instruction::isAssociative(Opcode) && "Not an associative operati=
on!");
=20
@@ -247,12 +275,12 @@
     Value *C =3D RHS;
=20
     // Does "B op C" simplify?
-    if (Value *V =3D SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
+    if (Value *V =3D SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
       // It does!  Return "A op V" if it simplifies or is already availabl=
e.
       // If V equals B then "A op V" is just the LHS.
       if (V =3D=3D B) return LHS;
       // Otherwise return "A op V" if it simplifies.
-      if (Value *W =3D SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
+      if (Value *W =3D SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
         ++NumReassoc;
         return W;
       }
@@ -266,12 +294,12 @@
     Value *C =3D Op1->getOperand(1);
=20
     // Does "A op B" simplify?
-    if (Value *V =3D SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
+    if (Value *V =3D SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
       // It does!  Return "V op C" if it simplifies or is already availabl=
e.
       // If V equals B then "V op C" is just the RHS.
       if (V =3D=3D B) return RHS;
       // Otherwise return "V op C" if it simplifies.
-      if (Value *W =3D SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
+      if (Value *W =3D SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
         ++NumReassoc;
         return W;
       }
@@ -289,12 +317,12 @@
     Value *C =3D RHS;
=20
     // Does "C op A" simplify?
-    if (Value *V =3D SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
+    if (Value *V =3D SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
       // It does!  Return "V op B" if it simplifies or is already availabl=
e.
       // If V equals A then "V op B" is just the LHS.
       if (V =3D=3D A) return LHS;
       // Otherwise return "V op B" if it simplifies.
-      if (Value *W =3D SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
+      if (Value *W =3D SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
         ++NumReassoc;
         return W;
       }
@@ -308,12 +336,12 @@
     Value *C =3D Op1->getOperand(1);
=20
     // Does "C op A" simplify?
-    if (Value *V =3D SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
+    if (Value *V =3D SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
       // It does!  Return "B op V" if it simplifies or is already availabl=
e.
       // If V equals C then "B op V" is just the RHS.
       if (V =3D=3D C) return RHS;
       // Otherwise return "B op V" if it simplifies.
-      if (Value *W =3D SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
+      if (Value *W =3D SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
         ++NumReassoc;
         return W;
       }
@@ -328,9 +356,7 @@
 /// evaluating it on both branches of the select results in the same value.
 /// Returns the common value if so, otherwise returns null.
 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RH=
S,
-                                    const TargetData *TD,
-                                    const DominatorTree *DT,
-                                    unsigned MaxRecurse) {
+                                    const Query &Q, unsigned MaxRecurse) {
   // Recursion is always used, so bail out at once if we already hit the l=
imit.
   if (!MaxRecurse--)
     return 0;
@@ -347,11 +373,11 @@
   Value *TV;
   Value *FV;
   if (SI =3D=3D LHS) {
-    TV =3D SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecur=
se);
-    FV =3D SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecu=
rse);
+    TV =3D SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
+    FV =3D SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
   } else {
-    TV =3D SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecur=
se);
-    FV =3D SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecu=
rse);
+    TV =3D SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
+    FV =3D SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
   }
=20
   // If they simplified to the same value, then return the common value.
@@ -402,8 +428,7 @@
 /// result in the same value.  Returns the common value if so, otherwise r=
eturns
 /// null.
 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
-                                  Value *RHS, const TargetData *TD,
-                                  const DominatorTree *DT,
+                                  Value *RHS, const Query &Q,
                                   unsigned MaxRecurse) {
   // Recursion is always used, so bail out at once if we already hit the l=
imit.
   if (!MaxRecurse--)
@@ -416,40 +441,67 @@
   }
   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!=
");
   SelectInst *SI =3D cast<SelectInst>(LHS);
+  Value *Cond =3D SI->getCondition();
+  Value *TV =3D SI->getTrueValue();
+  Value *FV =3D SI->getFalseValue();
=20
   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
   // Does "cmp TV, RHS" simplify?
-  if (Value *TCmp =3D SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, D=
T,
-                                    MaxRecurse)) {
-    // It does!  Does "cmp FV, RHS" simplify?
-    if (Value *FCmp =3D SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD=
, DT,
-                                      MaxRecurse)) {
-      // It does!  If they simplified to the same value, then use it as the
-      // result of the original comparison.
-      if (TCmp =3D=3D FCmp)
-        return TCmp;
-      Value *Cond =3D SI->getCondition();
-      // If the false value simplified to false, then the result of the co=
mpare
-      // is equal to "Cond && TCmp".  This also catches the case when the =
false
-      // value simplified to false and the true value to true, returning "=
Cond".
-      if (match(FCmp, m_Zero()))
-        if (Value *V =3D SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
-          return V;
-      // If the true value simplified to true, then the result of the comp=
are
-      // is equal to "Cond || FCmp".
-      if (match(TCmp, m_One()))
-        if (Value *V =3D SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
-          return V;
-      // Finally, if the false value simplified to true and the true value=
 to
-      // false, then the result of the compare is equal to "!Cond".
-      if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
-        if (Value *V =3D
-            SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType(=
)),
-                            TD, DT, MaxRecurse))
-          return V;
-    }
+  Value *TCmp =3D SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
+  if (TCmp =3D=3D Cond) {
+    // It not only simplified, it simplified to the select condition.  Rep=
lace
+    // it with 'true'.
+    TCmp =3D getTrue(Cond->getType());
+  } else if (!TCmp) {
+    // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
+    // condition then we can replace it with 'true'.  Otherwise give up.
+    if (!isSameCompare(Cond, Pred, TV, RHS))
+      return 0;
+    TCmp =3D getTrue(Cond->getType());
   }
=20
+  // Does "cmp FV, RHS" simplify?
+  Value *FCmp =3D SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
+  if (FCmp =3D=3D Cond) {
+    // It not only simplified, it simplified to the select condition.  Rep=
lace
+    // it with 'false'.
+    FCmp =3D getFalse(Cond->getType());
+  } else if (!FCmp) {
+    // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
+    // condition then we can replace it with 'false'.  Otherwise give up.
+    if (!isSameCompare(Cond, Pred, FV, RHS))
+      return 0;
+    FCmp =3D getFalse(Cond->getType());
+  }
+
+  // If both sides simplified to the same value, then use it as the result=
 of
+  // the original comparison.
+  if (TCmp =3D=3D FCmp)
+    return TCmp;
+
+  // The remaining cases only make sense if the select condition has the s=
ame
+  // type as the result of the comparison, so bail out if this is not so.
+  if (Cond->getType()->isVectorTy() !=3D RHS->getType()->isVectorTy())
+    return 0;
+  // If the false value simplified to false, then the result of the compare
+  // is equal to "Cond && TCmp".  This also catches the case when the false
+  // value simplified to false and the true value to true, returning "Cond=
".
+  if (match(FCmp, m_Zero()))
+    if (Value *V =3D SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
+      return V;
+  // If the true value simplified to true, then the result of the compare
+  // is equal to "Cond || FCmp".
+  if (match(TCmp, m_One()))
+    if (Value *V =3D SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
+      return V;
+  // Finally, if the false value simplified to true and the true value to
+  // false, then the result of the compare is equal to "!Cond".
+  if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
+    if (Value *V =3D
+        SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
+                        Q, MaxRecurse))
+      return V;
+
   return 0;
 }
=20
@@ -458,8 +510,7 @@
 /// it on the incoming phi values yields the same result for every value. =
 If so
 /// returns the common value, otherwise returns null.
 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
-                                 const TargetData *TD, const DominatorTree=
 *DT,
-                                 unsigned MaxRecurse) {
+                                 const Query &Q, unsigned MaxRecurse) {
   // Recursion is always used, so bail out at once if we already hit the l=
imit.
   if (!MaxRecurse--)
     return 0;
@@ -468,13 +519,13 @@
   if (isa<PHINode>(LHS)) {
     PI =3D cast<PHINode>(LHS);
     // Bail out if RHS and the phi may be mutually interdependent due to a=
 loop.
-    if (!ValueDominatesPHI(RHS, PI, DT))
+    if (!ValueDominatesPHI(RHS, PI, Q.DT))
       return 0;
   } else {
     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
     PI =3D cast<PHINode>(RHS);
     // Bail out if LHS and the phi may be mutually interdependent due to a=
 loop.
-    if (!ValueDominatesPHI(LHS, PI, DT))
+    if (!ValueDominatesPHI(LHS, PI, Q.DT))
       return 0;
   }
=20
@@ -485,8 +536,8 @@
     // If the incoming value is the phi node itself, it can safely be skip=
ped.
     if (Incoming =3D=3D PI) continue;
     Value *V =3D PI =3D=3D LHS ?
-      SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
-      SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
+      SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
+      SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
     // If the operation failed to simplify, or simplified to a different v=
alue
     // to previously, then give up.
     if (!V || (CommonValue && V !=3D CommonValue))
@@ -502,8 +553,7 @@
 /// incoming phi values yields the same result every time.  If so returns =
the
 /// common result, otherwise returns null.
 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value =
*RHS,
-                               const TargetData *TD, const DominatorTree *=
DT,
-                               unsigned MaxRecurse) {
+                               const Query &Q, unsigned MaxRecurse) {
   // Recursion is always used, so bail out at once if we already hit the l=
imit.
   if (!MaxRecurse--)
     return 0;
@@ -517,7 +567,7 @@
   PHINode *PI =3D cast<PHINode>(LHS);
=20
   // Bail out if RHS and the phi may be mutually interdependent due to a l=
oop.
-  if (!ValueDominatesPHI(RHS, PI, DT))
+  if (!ValueDominatesPHI(RHS, PI, Q.DT))
     return 0;
=20
   // Evaluate the BinOp on the incoming phi values.
@@ -526,7 +576,7 @@
     Value *Incoming =3D PI->getIncomingValue(i);
     // If the incoming value is the phi node itself, it can safely be skip=
ped.
     if (Incoming =3D=3D PI) continue;
-    Value *V =3D SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
+    Value *V =3D SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
     // If the operation failed to simplify, or simplified to a different v=
alue
     // to previously, then give up.
     if (!V || (CommonValue && V !=3D CommonValue))
@@ -540,13 +590,12 @@
 /// SimplifyAddInst - Given operands for an Add, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isN=
UW,
-                              const TargetData *TD, const DominatorTree *D=
T,
-                              unsigned MaxRecurse) {
+                              const Query &Q, unsigned MaxRecurse) {
   if (Constant *CLHS =3D dyn_cast<Constant>(Op0)) {
     if (Constant *CRHS =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { CLHS, CRHS };
-      return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
-                                      Ops, TD);
+      return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), O=
ps,
+                                      Q.TD, Q.TLI);
     }
=20
     // Canonicalize the constant to the RHS.
@@ -576,17 +625,17 @@
=20
   /// i1 add -> xor.
   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
-    if (Value *V =3D SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
+    if (Value *V =3D SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
       return V;
=20
   // Try some generic simplifications for associative operations.
-  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD=
, DT,
+  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
                                           MaxRecurse))
     return V;
=20
   // Mul distributes over Add.  Try some generic simplifications based on =
this.
   if (Value *V =3D FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction:=
:Mul,
-                                TD, DT, MaxRecurse))
+                                Q, MaxRecurse))
     return V;
=20
   // Threading Add over selects and phi nodes is pointless, so don't bothe=
r.
@@ -602,20 +651,116 @@
 }
=20
 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNU=
W,
-                             const TargetData *TD, const DominatorTree *DT=
) {
-  return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
+                             const TargetData *TD, const TargetLibraryInfo=
 *TLI,
+                             const DominatorTree *DT) {
+  return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
+                           RecursionLimit);
+}
+
+/// \brief Accumulate the constant integer offset a GEP represents.
+///
+/// Given a getelementptr instruction/constantexpr, accumulate the constant
+/// offset from the base pointer into the provided APInt 'Offset'. Returns=
 true
+/// if the GEP has all-constant indices. Returns false if any non-constant
+/// index is encountered leaving the 'Offset' in an undefined state. The
+/// 'Offset' APInt must be the bitwidth of the target's pointer size.
+static bool accumulateGEPOffset(const TargetData &TD, GEPOperator *GEP,
+                                APInt &Offset) {
+  unsigned IntPtrWidth =3D TD.getPointerSizeInBits();
+  assert(IntPtrWidth =3D=3D Offset.getBitWidth());
+
+  gep_type_iterator GTI =3D gep_type_begin(GEP);
+  for (User::op_iterator I =3D GEP->op_begin() + 1, E =3D GEP->op_end(); I=
 !=3D E;
+       ++I, ++GTI) {
+    ConstantInt *OpC =3D dyn_cast<ConstantInt>(*I);
+    if (!OpC) return false;
+    if (OpC->isZero()) continue;
+
+    // Handle a struct index, which adds its field offset to the pointer.
+    if (StructType *STy =3D dyn_cast<StructType>(*GTI)) {
+      unsigned ElementIdx =3D OpC->getZExtValue();
+      const StructLayout *SL =3D TD.getStructLayout(STy);
+      Offset +=3D APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
+      continue;
+    }
+
+    APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()));
+    Offset +=3D OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
+  }
+  return true;
+}
+
+/// \brief Compute the base pointer and cumulative constant offsets for V.
+///
+/// This strips all constant offsets off of V, leaving it the base pointer=
, and
+/// accumulates the total constant offset applied in the returned constant=
. It
+/// returns 0 if V is not a pointer, and returns the constant '0' if there=
 are
+/// no constant offsets applied.
+static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
+                                                Value *&V) {
+  if (!V->getType()->isPointerTy())
+    return 0;
+
+  unsigned IntPtrWidth =3D TD.getPointerSizeInBits();
+  APInt Offset =3D APInt::getNullValue(IntPtrWidth);
+
+  // Even though we don't look through PHI nodes, we could be called on an
+  // instruction in an unreachable block, which may be on a cycle.
+  SmallPtrSet<Value *, 4> Visited;
+  Visited.insert(V);
+  do {
+    if (GEPOperator *GEP =3D dyn_cast<GEPOperator>(V)) {
+      if (!GEP->isInBounds() || !accumulateGEPOffset(TD, GEP, Offset))
+        break;
+      V =3D GEP->getPointerOperand();
+    } else if (Operator::getOpcode(V) =3D=3D Instruction::BitCast) {
+      V =3D cast<Operator>(V)->getOperand(0);
+    } else if (GlobalAlias *GA =3D dyn_cast<GlobalAlias>(V)) {
+      if (GA->mayBeOverridden())
+        break;
+      V =3D GA->getAliasee();
+    } else {
+      break;
+    }
+    assert(V->getType()->isPointerTy() && "Unexpected operand type!");
+  } while (Visited.insert(V));
+
+  Type *IntPtrTy =3D TD.getIntPtrType(V->getContext());
+  return ConstantInt::get(IntPtrTy, Offset);
+}
+
+/// \brief Compute the constant difference between two pointer values.
+/// If the difference is not a constant, returns zero.
+static Constant *computePointerDifference(const TargetData &TD,
+                                          Value *LHS, Value *RHS) {
+  Constant *LHSOffset =3D stripAndComputeConstantOffsets(TD, LHS);
+  if (!LHSOffset)
+    return 0;
+  Constant *RHSOffset =3D stripAndComputeConstantOffsets(TD, RHS);
+  if (!RHSOffset)
+    return 0;
+
+  // If LHS and RHS are not related via constant offsets to the same base
+  // value, there is nothing we can do here.
+  if (LHS !=3D RHS)
+    return 0;
+
+  // Otherwise, the difference of LHS - RHS can be computed as:
+  //    LHS - RHS
+  //  =3D (LHSOffset + Base) - (RHSOffset + Base)
+  //  =3D LHSOffset - RHSOffset
+  return ConstantExpr::getSub(LHSOffset, RHSOffset);
 }
=20
 /// SimplifySubInst - Given operands for a Sub, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isN=
UW,
-                              const TargetData *TD, const DominatorTree *D=
T,
-                              unsigned MaxRecurse) {
+                              const Query &Q, unsigned MaxRecurse) {
   if (Constant *CLHS =3D dyn_cast<Constant>(Op0))
     if (Constant *CRHS =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { CLHS, CRHS };
       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
-                                      Ops, TD);
+                                      Ops, Q.TD, Q.TLI);
     }
=20
   // X - undef -> undef
@@ -643,19 +788,17 @@
   Value *Y =3D 0, *Z =3D Op1;
   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y=
) - Z
     // See if "V =3D=3D=3D Y - Z" simplifies.
-    if (Value *V =3D SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecu=
rse-1))
+    if (Value *V =3D SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1=
))
       // It does!  Now see if "X + V" simplifies.
-      if (Value *W =3D SimplifyBinOp(Instruction::Add, X, V, TD, DT,
-                                   MaxRecurse-1)) {
+      if (Value *W =3D SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse=
-1)) {
         // It does, we successfully reassociated!
         ++NumReassoc;
         return W;
       }
     // See if "V =3D=3D=3D X - Z" simplifies.
-    if (Value *V =3D SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecu=
rse-1))
+    if (Value *V =3D SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1=
))
       // It does!  Now see if "Y + V" simplifies.
-      if (Value *W =3D SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
-                                   MaxRecurse-1)) {
+      if (Value *W =3D SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse=
-1)) {
         // It does, we successfully reassociated!
         ++NumReassoc;
         return W;
@@ -667,19 +810,17 @@
   X =3D Op0;
   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y=
 + Z)
     // See if "V =3D=3D=3D X - Y" simplifies.
-    if (Value *V =3D SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecu=
rse-1))
+    if (Value *V =3D SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1=
))
       // It does!  Now see if "V - Z" simplifies.
-      if (Value *W =3D SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
-                                   MaxRecurse-1)) {
+      if (Value *W =3D SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse=
-1)) {
         // It does, we successfully reassociated!
         ++NumReassoc;
         return W;
       }
     // See if "V =3D=3D=3D X - Z" simplifies.
-    if (Value *V =3D SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecu=
rse-1))
+    if (Value *V =3D SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1=
))
       // It does!  Now see if "V - Y" simplifies.
-      if (Value *W =3D SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
-                                   MaxRecurse-1)) {
+      if (Value *W =3D SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse=
-1)) {
         // It does, we successfully reassociated!
         ++NumReassoc;
         return W;
@@ -691,23 +832,39 @@
   Z =3D Op0;
   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X -=
 Y)
     // See if "V =3D=3D=3D Z - X" simplifies.
-    if (Value *V =3D SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecu=
rse-1))
+    if (Value *V =3D SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1=
))
       // It does!  Now see if "V + Y" simplifies.
-      if (Value *W =3D SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
-                                   MaxRecurse-1)) {
+      if (Value *W =3D SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse=
-1)) {
         // It does, we successfully reassociated!
         ++NumReassoc;
         return W;
       }
=20
+  // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
+  if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
+      match(Op1, m_Trunc(m_Value(Y))))
+    if (X->getType() =3D=3D Y->getType())
+      // See if "V =3D=3D=3D X - Y" simplifies.
+      if (Value *V =3D SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse=
-1))
+        // It does!  Now see if "trunc V" simplifies.
+        if (Value *W =3D SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurs=
e-1))
+          // It does, return the simplified "trunc V".
+          return W;
+
+  // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i,=
 ...).
+  if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
+      match(Op1, m_PtrToInt(m_Value(Y))))
+    if (Constant *Result =3D computePointerDifference(*Q.TD, X, Y))
+      return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
+
   // Mul distributes over Sub.  Try some generic simplifications based on =
this.
   if (Value *V =3D FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction:=
:Mul,
-                                TD, DT, MaxRecurse))
+                                Q, MaxRecurse))
     return V;
=20
   // i1 sub -> xor.
   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
-    if (Value *V =3D SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
+    if (Value *V =3D SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
       return V;
=20
   // Threading Sub over selects and phi nodes is pointless, so don't bothe=
r.
@@ -723,19 +880,21 @@
 }
=20
 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNU=
W,
-                             const TargetData *TD, const DominatorTree *DT=
) {
-  return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
+                             const TargetData *TD, const TargetLibraryInfo=
 *TLI,
+                             const DominatorTree *DT) {
+  return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
+                           RecursionLimit);
 }
=20
 /// SimplifyMulInst - Given operands for a Mul, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
-                              const DominatorTree *DT, unsigned MaxRecurse=
) {
+static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
+                              unsigned MaxRecurse) {
   if (Constant *CLHS =3D dyn_cast<Constant>(Op0)) {
     if (Constant *CRHS =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { CLHS, CRHS };
       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
-                                      Ops, TD);
+                                      Ops, Q.TD, Q.TLI);
     }
=20
     // Canonicalize the constant to the RHS.
@@ -755,40 +914,37 @@
     return Op0;
=20
   // (X / Y) * Y -> X if the division is exact.
-  Value *X =3D 0, *Y =3D 0;
-  if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y =3D=3D Op1) || // (=
X / Y) * Y
-      (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y =3D=3D Op0)) { // Y=
 * (X / Y)
-    BinaryOperator *Div =3D cast<BinaryOperator>(Y =3D=3D Op1 ? Op0 : Op1);
-    if (Div->isExact())
-      return X;
-  }
+  Value *X =3D 0;
+  if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / =
Y) * Y
+      match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (=
X / Y)
+    return X;
=20
   // i1 mul -> and.
   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
-    if (Value *V =3D SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
+    if (Value *V =3D SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
       return V;
=20
   // Try some generic simplifications for associative operations.
-  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD=
, DT,
+  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
                                           MaxRecurse))
     return V;
=20
   // Mul distributes over Add.  Try some generic simplifications based on =
this.
   if (Value *V =3D ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Ad=
d,
-                             TD, DT, MaxRecurse))
+                             Q, MaxRecurse))
     return V;
=20
   // If the operation is with the result of a select instruction, check wh=
ether
   // operating on either branch of the select always yields the same value.
   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
-    if (Value *V =3D ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD,=
 DT,
+    if (Value *V =3D ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
                                          MaxRecurse))
       return V;
=20
   // If the operation is with the result of a phi instruction, check wheth=
er
   // operating on all incoming values of the phi always yields the same va=
lue.
   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
-    if (Value *V =3D ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
+    if (Value *V =3D ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
                                       MaxRecurse))
       return V;
=20
@@ -796,19 +952,19 @@
 }
=20
 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
+                             const TargetLibraryInfo *TLI,
                              const DominatorTree *DT) {
-  return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value=
 *Op1,
-                          const TargetData *TD, const DominatorTree *DT,
-                          unsigned MaxRecurse) {
+                          const Query &Q, unsigned MaxRecurse) {
   if (Constant *C0 =3D dyn_cast<Constant>(Op0)) {
     if (Constant *C1 =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { C0, C1 };
-      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
+      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.=
TLI);
     }
   }
=20
@@ -842,7 +998,7 @@
   Value *X =3D 0, *Y =3D 0;
   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X =3D=3D Op1 || Y =3D=
=3D Op1)) {
     if (Y !=3D Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, =
Y =3D Op1
-    BinaryOperator *Mul =3D cast<BinaryOperator>(Op0);
+    OverflowingBinaryOperator *Mul =3D cast<OverflowingBinaryOperator>(Op0=
);
     // If the Mul knows it does not overflow, then we are good to go.
     if ((isSigned && Mul->hasNoSignedWrap()) ||
         (!isSigned && Mul->hasNoUnsignedWrap()))
@@ -861,13 +1017,13 @@
   // If the operation is with the result of a select instruction, check wh=
ether
   // operating on either branch of the select always yields the same value.
   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
-    if (Value *V =3D ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRe=
curse))
+    if (Value *V =3D ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse=
))
       return V;
=20
   // If the operation is with the result of a phi instruction, check wheth=
er
   // operating on all incoming values of the phi always yields the same va=
lue.
   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
-    if (Value *V =3D ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecur=
se))
+    if (Value *V =3D ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
       return V;
=20
   return 0;
@@ -875,36 +1031,38 @@
=20
 /// SimplifySDivInst - Given operands for an SDiv, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *T=
D,
-                               const DominatorTree *DT, unsigned MaxRecurs=
e) {
-  if (Value *V =3D SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRec=
urse))
+static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
+                               unsigned MaxRecurse) {
+  if (Value *V =3D SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
     return V;
=20
   return 0;
 }
=20
 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
                               const DominatorTree *DT) {
-  return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *T=
D,
-                               const DominatorTree *DT, unsigned MaxRecurs=
e) {
-  if (Value *V =3D SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRec=
urse))
+static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
+                               unsigned MaxRecurse) {
+  if (Value *V =3D SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
     return V;
=20
   return 0;
 }
=20
 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
                               const DominatorTree *DT) {
-  return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
-static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
-                               const DominatorTree *, unsigned) {
+static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
+                               unsigned) {
   // undef / X -> undef    (the undef could be a snan).
   if (match(Op0, m_Undef()))
     return Op0;
@@ -917,19 +1075,19 @@
 }
=20
 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
                               const DominatorTree *DT) {
-  return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 /// SimplifyRem - Given operands for an SRem or URem, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value=
 *Op1,
-                          const TargetData *TD, const DominatorTree *DT,
-                          unsigned MaxRecurse) {
+                          const Query &Q, unsigned MaxRecurse) {
   if (Constant *C0 =3D dyn_cast<Constant>(Op0)) {
     if (Constant *C1 =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { C0, C1 };
-      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
+      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.=
TLI);
     }
   }
=20
@@ -964,13 +1122,13 @@
   // If the operation is with the result of a select instruction, check wh=
ether
   // operating on either branch of the select always yields the same value.
   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
-    if (Value *V =3D ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRe=
curse))
+    if (Value *V =3D ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse=
))
       return V;
=20
   // If the operation is with the result of a phi instruction, check wheth=
er
   // operating on all incoming values of the phi always yields the same va=
lue.
   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
-    if (Value *V =3D ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecur=
se))
+    if (Value *V =3D ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
       return V;
=20
   return 0;
@@ -978,36 +1136,38 @@
=20
 /// SimplifySRemInst - Given operands for an SRem, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *T=
D,
-                               const DominatorTree *DT, unsigned MaxRecurs=
e) {
-  if (Value *V =3D SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRec=
urse))
+static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
+                               unsigned MaxRecurse) {
+  if (Value *V =3D SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
     return V;
=20
   return 0;
 }
=20
 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
                               const DominatorTree *DT) {
-  return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 /// SimplifyURemInst - Given operands for a URem, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *T=
D,
-                               const DominatorTree *DT, unsigned MaxRecurs=
e) {
-  if (Value *V =3D SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRec=
urse))
+static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
+                               unsigned MaxRecurse) {
+  if (Value *V =3D SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
     return V;
=20
   return 0;
 }
=20
 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
                               const DominatorTree *DT) {
-  return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
-static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
-                               const DominatorTree *, unsigned) {
+static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
+                               unsigned) {
   // undef % X -> undef    (the undef could be a snan).
   if (match(Op0, m_Undef()))
     return Op0;
@@ -1020,19 +1180,19 @@
 }
=20
 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
                               const DominatorTree *DT) {
-  return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
-                            const TargetData *TD, const DominatorTree *DT,
-                            unsigned MaxRecurse) {
+                            const Query &Q, unsigned MaxRecurse) {
   if (Constant *C0 =3D dyn_cast<Constant>(Op0)) {
     if (Constant *C1 =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { C0, C1 };
-      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
+      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.=
TLI);
     }
   }
=20
@@ -1057,13 +1217,13 @@
   // If the operation is with the result of a select instruction, check wh=
ether
   // operating on either branch of the select always yields the same value.
   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
-    if (Value *V =3D ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRe=
curse))
+    if (Value *V =3D ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse=
))
       return V;
=20
   // If the operation is with the result of a phi instruction, check wheth=
er
   // operating on all incoming values of the phi always yields the same va=
lue.
   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
-    if (Value *V =3D ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecur=
se))
+    if (Value *V =3D ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
       return V;
=20
   return 0;
@@ -1072,9 +1232,8 @@
 /// SimplifyShlInst - Given operands for an Shl, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isN=
UW,
-                              const TargetData *TD, const DominatorTree *D=
T,
-                              unsigned MaxRecurse) {
-  if (Value *V =3D SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRe=
curse))
+                              const Query &Q, unsigned MaxRecurse) {
+  if (Value *V =3D SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse=
))
     return V;
=20
   // undef << X -> 0
@@ -1083,23 +1242,23 @@
=20
   // (X >> A) << A -> X
   Value *X;
-  if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
-      cast<PossiblyExactOperator>(Op0)->isExact())
+  if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
     return X;
   return 0;
 }
=20
 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNU=
W,
-                             const TargetData *TD, const DominatorTree *DT=
) {
-  return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
+                             const TargetData *TD, const TargetLibraryInfo=
 *TLI,
+                             const DominatorTree *DT) {
+  return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
+                           RecursionLimit);
 }
=20
 /// SimplifyLShrInst - Given operands for an LShr, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
-                               const TargetData *TD, const DominatorTree *=
DT,
-                               unsigned MaxRecurse) {
-  if (Value *V =3D SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxR=
ecurse))
+                               const Query &Q, unsigned MaxRecurse) {
+  if (Value *V =3D SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurs=
e))
     return V;
=20
   // undef >>l X -> 0
@@ -1116,16 +1275,18 @@
 }
=20
 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
-                              const TargetData *TD, const DominatorTree *D=
T) {
-  return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
+                              const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
+                              const DominatorTree *DT) {
+  return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
+                            RecursionLimit);
 }
=20
 /// SimplifyAShrInst - Given operands for an AShr, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
-                               const TargetData *TD, const DominatorTree *=
DT,
-                               unsigned MaxRecurse) {
-  if (Value *V =3D SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxR=
ecurse))
+                               const Query &Q, unsigned MaxRecurse) {
+  if (Value *V =3D SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurs=
e))
     return V;
=20
   // all ones >>a X -> all ones
@@ -1146,19 +1307,22 @@
 }
=20
 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
-                              const TargetData *TD, const DominatorTree *D=
T) {
-  return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
+                              const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
+                              const DominatorTree *DT) {
+  return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
+                            RecursionLimit);
 }
=20
 /// SimplifyAndInst - Given operands for an And, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
-                              const DominatorTree *DT, unsigned MaxRecurse=
) {
+static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
+                              unsigned MaxRecurse) {
   if (Constant *CLHS =3D dyn_cast<Constant>(Op0)) {
     if (Constant *CRHS =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { CLHS, CRHS };
       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
-                                      Ops, TD);
+                                      Ops, Q.TD, Q.TLI);
     }
=20
     // Canonicalize the constant to the RHS.
@@ -1197,37 +1361,46 @@
       (A =3D=3D Op0 || B =3D=3D Op0))
     return Op0;
=20
+  // A & (-A) =3D A if A is a power of two or zero.
+  if (match(Op0, m_Neg(m_Specific(Op1))) ||
+      match(Op1, m_Neg(m_Specific(Op0)))) {
+    if (isPowerOfTwo(Op0, Q.TD, /*OrZero*/true))
+      return Op0;
+    if (isPowerOfTwo(Op1, Q.TD, /*OrZero*/true))
+      return Op1;
+  }
+
   // Try some generic simplifications for associative operations.
-  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD=
, DT,
+  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
                                           MaxRecurse))
     return V;
=20
   // And distributes over Or.  Try some generic simplifications based on t=
his.
   if (Value *V =3D ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
-                             TD, DT, MaxRecurse))
+                             Q, MaxRecurse))
     return V;
=20
   // And distributes over Xor.  Try some generic simplifications based on =
this.
   if (Value *V =3D ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xo=
r,
-                             TD, DT, MaxRecurse))
+                             Q, MaxRecurse))
     return V;
=20
   // Or distributes over And.  Try some generic simplifications based on t=
his.
   if (Value *V =3D FactorizeBinOp(Instruction::And, Op0, Op1, Instruction:=
:Or,
-                                TD, DT, MaxRecurse))
+                                Q, MaxRecurse))
     return V;
=20
   // If the operation is with the result of a select instruction, check wh=
ether
   // operating on either branch of the select always yields the same value.
   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
-    if (Value *V =3D ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD,=
 DT,
+    if (Value *V =3D ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
                                          MaxRecurse))
       return V;
=20
   // If the operation is with the result of a phi instruction, check wheth=
er
   // operating on all incoming values of the phi always yields the same va=
lue.
   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
-    if (Value *V =3D ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
+    if (Value *V =3D ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
                                       MaxRecurse))
       return V;
=20
@@ -1235,19 +1408,20 @@
 }
=20
 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
+                             const TargetLibraryInfo *TLI,
                              const DominatorTree *DT) {
-  return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 /// SimplifyOrInst - Given operands for an Or, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
-                             const DominatorTree *DT, unsigned MaxRecurse)=
 {
+static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
+                             unsigned MaxRecurse) {
   if (Constant *CLHS =3D dyn_cast<Constant>(Op0)) {
     if (Constant *CRHS =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { CLHS, CRHS };
       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
-                                      Ops, TD);
+                                      Ops, Q.TD, Q.TLI);
     }
=20
     // Canonicalize the constant to the RHS.
@@ -1297,51 +1471,51 @@
     return Constant::getAllOnesValue(Op0->getType());
=20
   // Try some generic simplifications for associative operations.
-  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD,=
 DT,
+  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
                                           MaxRecurse))
     return V;
=20
   // Or distributes over And.  Try some generic simplifications based on t=
his.
-  if (Value *V =3D ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
-                             TD, DT, MaxRecurse))
+  if (Value *V =3D ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And=
, Q,
+                             MaxRecurse))
     return V;
=20
   // And distributes over Or.  Try some generic simplifications based on t=
his.
   if (Value *V =3D FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::=
And,
-                                TD, DT, MaxRecurse))
+                                Q, MaxRecurse))
     return V;
=20
   // If the operation is with the result of a select instruction, check wh=
ether
   // operating on either branch of the select always yields the same value.
   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
-    if (Value *V =3D ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, =
DT,
+    if (Value *V =3D ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
                                          MaxRecurse))
       return V;
=20
   // If the operation is with the result of a phi instruction, check wheth=
er
   // operating on all incoming values of the phi always yields the same va=
lue.
   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
-    if (Value *V =3D ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
-                                      MaxRecurse))
+    if (Value *V =3D ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxR=
ecurse))
       return V;
=20
   return 0;
 }
=20
 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
+                            const TargetLibraryInfo *TLI,
                             const DominatorTree *DT) {
-  return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 /// SimplifyXorInst - Given operands for a Xor, see if we can
 /// fold the result.  If not, this returns null.
-static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
-                              const DominatorTree *DT, unsigned MaxRecurse=
) {
+static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
+                              unsigned MaxRecurse) {
   if (Constant *CLHS =3D dyn_cast<Constant>(Op0)) {
     if (Constant *CRHS =3D dyn_cast<Constant>(Op1)) {
       Constant *Ops[] =3D { CLHS, CRHS };
       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
-                                      Ops, TD);
+                                      Ops, Q.TD, Q.TLI);
     }
=20
     // Canonicalize the constant to the RHS.
@@ -1366,13 +1540,13 @@
     return Constant::getAllOnesValue(Op0->getType());
=20
   // Try some generic simplifications for associative operations.
-  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD=
, DT,
+  if (Value *V =3D SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
                                           MaxRecurse))
     return V;
=20
   // And distributes over Xor.  Try some generic simplifications based on =
this.
   if (Value *V =3D FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction:=
:And,
-                                TD, DT, MaxRecurse))
+                                Q, MaxRecurse))
     return V;
=20
   // Threading Xor over selects and phi nodes is pointless, so don't bothe=
r.
@@ -1388,8 +1562,9 @@
 }
=20
 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
+                             const TargetLibraryInfo *TLI,
                              const DominatorTree *DT) {
-  return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
+  return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
 }
=20
 static Type *GetCompareTy(Value *Op) {
@@ -1416,17 +1591,56 @@
   return 0;
 }
=20
+static Constant *computePointerICmp(const TargetData &TD,
+                                    CmpInst::Predicate Pred,
+                                    Value *LHS, Value *RHS) {
+  // We can only fold certain predicates on pointer comparisons.
+  switch (Pred) {
+  default:
+    return 0;
+
+    // Equality comaprisons are easy to fold.
+  case CmpInst::ICMP_EQ:
+  case CmpInst::ICMP_NE:
+    break;
+
+    // We can only handle unsigned relational comparisons because 'inbound=
s' on
+    // a GEP only protects against unsigned wrapping.
+  case CmpInst::ICMP_UGT:
+  case CmpInst::ICMP_UGE:
+  case CmpInst::ICMP_ULT:
+  case CmpInst::ICMP_ULE:
+    // However, we have to switch them to their signed variants to handle
+    // negative indices from the base pointer.
+    Pred =3D ICmpInst::getSignedPredicate(Pred);
+    break;
+  }
+
+  Constant *LHSOffset =3D stripAndComputeConstantOffsets(TD, LHS);
+  if (!LHSOffset)
+    return 0;
+  Constant *RHSOffset =3D stripAndComputeConstantOffsets(TD, RHS);
+  if (!RHSOffset)
+    return 0;
+
+  // If LHS and RHS are not related via constant offsets to the same base
+  // value, there is nothing we can do here.
+  if (LHS !=3D RHS)
+    return 0;
+
+  return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
+}
+
 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                               const TargetData *TD, const DominatorTree *=
DT,
-                               unsigned MaxRecurse) {
+                               const Query &Q, unsigned MaxRecurse) {
   CmpInst::Predicate Pred =3D (CmpInst::Predicate)Predicate;
   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
=20
   if (Constant *CLHS =3D dyn_cast<Constant>(LHS)) {
     if (Constant *CRHS =3D dyn_cast<Constant>(RHS))
-      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
+      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI=
);
=20
     // If we have a constant, make sure it is on the RHS.
     std::swap(LHS, RHS);
@@ -1443,8 +1657,7 @@
     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
=20
   // Special case logic when the operands have i1 type.
-  if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
-       cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
+  if (OpTy->getScalarType()->isIntegerTy(1)) {
     switch (Pred) {
     default: break;
     case ICmpInst::ICMP_EQ:
@@ -1480,63 +1693,101 @@
     }
   }
=20
-  // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
-  // different addresses, and what's more the address of a stack variable =
is
-  // never null or equal to the address of a global.  Note that generalizi=
ng
-  // to the case where LHS is a global variable address or null is pointle=
ss,
-  // since if both LHS and RHS are constants then we already constant fold=
ed
-  // the compare, and if only one of them is then we moved it to RHS alrea=
dy.
-  if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RH=
S) ||
-                               isa<ConstantPointerNull>(RHS)))
-    // We already know that LHS !=3D RHS.
-    return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
+  // icmp <object*>, <object*/null> - Different identified objects have
+  // different addresses (unless null), and what's more the address of an
+  // identified local is never equal to another argument (again, barring n=
ull).
+  // Note that generalizing to the case where LHS is a global variable add=
ress
+  // or null is pointless, since if both LHS and RHS are constants then we
+  // already constant folded the compare, and if only one of them is then =
we
+  // moved it to RHS already.
+  Value *LHSPtr =3D LHS->stripPointerCasts();
+  Value *RHSPtr =3D RHS->stripPointerCasts();
+  if (LHSPtr =3D=3D RHSPtr)
+    return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
+
+  // Be more aggressive about stripping pointer adjustments when checking a
+  // comparison of an alloca address to another object.  We can rip off all
+  // inbounds GEP operations, even if they are variable.
+  LHSPtr =3D LHSPtr->stripInBoundsOffsets();
+  if (llvm::isIdentifiedObject(LHSPtr)) {
+    RHSPtr =3D RHSPtr->stripInBoundsOffsets();
+    if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
+      // If both sides are different identified objects, they aren't equal
+      // unless they're null.
+      if (LHSPtr !=3D RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
+          Pred =3D=3D CmpInst::ICMP_EQ)
+        return ConstantInt::get(ITy, false);
+
+      // A local identified object (alloca or noalias call) can't equal any
+      // incoming argument, unless they're both null.
+      if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
+          Pred =3D=3D CmpInst::ICMP_EQ)
+        return ConstantInt::get(ITy, false);
+    }
+
+    // Assume that the constant null is on the right.
+    if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
+      if (Pred =3D=3D CmpInst::ICMP_EQ)
+        return ConstantInt::get(ITy, false);
+      else if (Pred =3D=3D CmpInst::ICMP_NE)
+        return ConstantInt::get(ITy, true);
+    }
+  } else if (isa<Argument>(LHSPtr)) {
+    RHSPtr =3D RHSPtr->stripInBoundsOffsets();
+    // An alloca can't be equal to an argument.
+    if (isa<AllocaInst>(RHSPtr)) {
+      if (Pred =3D=3D CmpInst::ICMP_EQ)
+        return ConstantInt::get(ITy, false);
+      else if (Pred =3D=3D CmpInst::ICMP_NE)
+        return ConstantInt::get(ITy, true);
+    }
+  }
=20
   // If we are comparing with zero then try hard since this is a common ca=
se.
   if (match(RHS, m_Zero())) {
     bool LHSKnownNonNegative, LHSKnownNegative;
     switch (Pred) {
-    default:
-      assert(false && "Unknown ICmp predicate!");
+    default: llvm_unreachable("Unknown ICmp predicate!");
     case ICmpInst::ICMP_ULT:
       return getFalse(ITy);
     case ICmpInst::ICMP_UGE:
       return getTrue(ITy);
     case ICmpInst::ICMP_EQ:
     case ICmpInst::ICMP_ULE:
-      if (isKnownNonZero(LHS, TD))
+      if (isKnownNonZero(LHS, Q.TD))
         return getFalse(ITy);
       break;
     case ICmpInst::ICMP_NE:
     case ICmpInst::ICMP_UGT:
-      if (isKnownNonZero(LHS, TD))
+      if (isKnownNonZero(LHS, Q.TD))
         return getTrue(ITy);
       break;
     case ICmpInst::ICMP_SLT:
-      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
+      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
       if (LHSKnownNegative)
         return getTrue(ITy);
       if (LHSKnownNonNegative)
         return getFalse(ITy);
       break;
     case ICmpInst::ICMP_SLE:
-      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
+      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
       if (LHSKnownNegative)
         return getTrue(ITy);
-      if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
+      if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
         return getFalse(ITy);
       break;
     case ICmpInst::ICMP_SGE:
-      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
+      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
       if (LHSKnownNegative)
         return getFalse(ITy);
       if (LHSKnownNonNegative)
         return getTrue(ITy);
       break;
     case ICmpInst::ICMP_SGT:
-      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
+      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
       if (LHSKnownNegative)
         return getFalse(ITy);
-      if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
+      if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
         return getTrue(ITy);
       break;
     }
@@ -1564,6 +1815,9 @@
       // 'srem x, CI2' produces (-|CI2|, |CI2|).
       Upper =3D CI2->getValue().abs();
       Lower =3D (-Upper) + 1;
+    } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
+      // 'udiv CI2, x' produces [0, CI2].
+      Upper =3D CI2->getValue() + 1;
     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
       APInt NegOne =3D APInt::getAllOnesValue(Width);
@@ -1616,19 +1870,19 @@
=20
     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the i=
nput
     // if the integer type is the same size as the pointer type.
-    if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
-        TD->getPointerSizeInBits() =3D=3D DstTy->getPrimitiveSizeInBits())=
 {
+    if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
+        Q.TD->getPointerSizeInBits() =3D=3D DstTy->getPrimitiveSizeInBits(=
)) {
       if (Constant *RHSC =3D dyn_cast<Constant>(RHS)) {
         // Transfer the cast to the constant.
         if (Value *V =3D SimplifyICmpInst(Pred, SrcOp,
                                         ConstantExpr::getIntToPtr(RHSC, Sr=
cTy),
-                                        TD, DT, MaxRecurse-1))
+                                        Q, MaxRecurse-1))
           return V;
       } else if (PtrToIntInst *RI =3D dyn_cast<PtrToIntInst>(RHS)) {
         if (RI->getOperand(0)->getType() =3D=3D SrcTy)
           // Compare without the cast.
           if (Value *V =3D SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
-                                          TD, DT, MaxRecurse-1))
+                                          Q, MaxRecurse-1))
             return V;
       }
     }
@@ -1640,7 +1894,7 @@
         if (MaxRecurse && SrcTy =3D=3D RI->getOperand(0)->getType())
           // Compare X and Y.  Note that signed predicates become unsigned.
           if (Value *V =3D SimplifyICmpInst(ICmpInst::getUnsignedPredicate=
(Pred),
-                                          SrcOp, RI->getOperand(0), TD, DT,
+                                          SrcOp, RI->getOperand(0), Q,
                                           MaxRecurse-1))
             return V;
       }
@@ -1656,15 +1910,14 @@
         // also a case of comparing two zero-extended values.
         if (RExt =3D=3D CI && MaxRecurse)
           if (Value *V =3D SimplifyICmpInst(ICmpInst::getUnsignedPredicate=
(Pred),
-                                          SrcOp, Trunc, TD, DT, MaxRecurse=
-1))
+                                        SrcOp, Trunc, Q, MaxRecurse-1))
             return V;
=20
         // Otherwise the upper bits of LHS are zero while RHS has a non-ze=
ro bit
         // there.  Use this to work out the result of the comparison.
         if (RExt !=3D CI) {
           switch (Pred) {
-          default:
-            assert(false && "Unknown ICmp predicate!");
+          default: llvm_unreachable("Unknown ICmp predicate!");
           // LHS <u RHS.
           case ICmpInst::ICMP_EQ:
           case ICmpInst::ICMP_UGT:
@@ -1701,7 +1954,7 @@
         if (MaxRecurse && SrcTy =3D=3D RI->getOperand(0)->getType())
           // Compare X and Y.  Note that the predicate does not change.
           if (Value *V =3D SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
-                                          TD, DT, MaxRecurse-1))
+                                          Q, MaxRecurse-1))
             return V;
       }
       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is ext=
ended
@@ -1715,16 +1968,14 @@
         // If the re-extended constant didn't change then this is effectiv=
ely
         // also a case of comparing two sign-extended values.
         if (RExt =3D=3D CI && MaxRecurse)
-          if (Value *V =3D SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
-                                          MaxRecurse-1))
+          if (Value *V =3D SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecu=
rse-1))
             return V;
=20
         // Otherwise the upper bits of LHS are all equal, while RHS has va=
rying
         // bits there.  Use this to work out the result of the comparison.
         if (RExt !=3D CI) {
           switch (Pred) {
-          default:
-            assert(false && "Unknown ICmp predicate!");
+          default: llvm_unreachable("Unknown ICmp predicate!");
           case ICmpInst::ICMP_EQ:
             return ConstantInt::getFalse(CI->getContext());
           case ICmpInst::ICMP_NE:
@@ -1751,7 +2002,7 @@
             if (MaxRecurse)
               if (Value *V =3D SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
                                               Constant::getNullValue(SrcTy=
),
-                                              TD, DT, MaxRecurse-1))
+                                              Q, MaxRecurse-1))
                 return V;
             break;
           case ICmpInst::ICMP_ULT:
@@ -1760,7 +2011,7 @@
             if (MaxRecurse)
               if (Value *V =3D SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
                                               Constant::getNullValue(SrcTy=
),
-                                              TD, DT, MaxRecurse-1))
+                                              Q, MaxRecurse-1))
                 return V;
             break;
           }
@@ -1794,14 +2045,14 @@
     if ((A =3D=3D RHS || B =3D=3D RHS) && NoLHSWrapProblem)
       if (Value *V =3D SimplifyICmpInst(Pred, A =3D=3D RHS ? B : A,
                                       Constant::getNullValue(RHS->getType(=
)),
-                                      TD, DT, MaxRecurse-1))
+                                      Q, MaxRecurse-1))
         return V;
=20
     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflo=
w.
     if ((C =3D=3D LHS || D =3D=3D LHS) && NoRHSWrapProblem)
       if (Value *V =3D SimplifyICmpInst(Pred,
                                       Constant::getNullValue(LHS->getType(=
)),
-                                      C =3D=3D LHS ? D : C, TD, DT, MaxRec=
urse-1))
+                                      C =3D=3D LHS ? D : C, Q, MaxRecurse-=
1))
         return V;
=20
     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no over=
flow.
@@ -1810,7 +2061,7 @@
       // Determine Y and Z in the form icmp (X+Y), (X+Z).
       Value *Y =3D (A =3D=3D C || A =3D=3D D) ? B : A;
       Value *Z =3D (C =3D=3D A || C =3D=3D B) ? D : C;
-      if (Value *V =3D SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
+      if (Value *V =3D SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
         return V;
     }
   }
@@ -1822,7 +2073,7 @@
       break;
     case ICmpInst::ICMP_SGT:
     case ICmpInst::ICMP_SGE:
-      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
+      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
       if (!KnownNonNegative)
         break;
       // fall-through
@@ -1832,7 +2083,7 @@
       return getFalse(ITy);
     case ICmpInst::ICMP_SLT:
     case ICmpInst::ICMP_SLE:
-      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
+      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
       if (!KnownNonNegative)
         break;
       // fall-through
@@ -1849,7 +2100,7 @@
       break;
     case ICmpInst::ICMP_SGT:
     case ICmpInst::ICMP_SGE:
-      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
+      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
       if (!KnownNonNegative)
         break;
       // fall-through
@@ -1859,7 +2110,7 @@
       return getTrue(ITy);
     case ICmpInst::ICMP_SLT:
     case ICmpInst::ICMP_SLE:
-      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
+      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
       if (!KnownNonNegative)
         break;
       // fall-through
@@ -1870,6 +2121,15 @@
     }
   }
=20
+  // x udiv y <=3Du x.
+  if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
+    // icmp pred (X /u Y), X
+    if (Pred =3D=3D ICmpInst::ICMP_UGT)
+      return getFalse(ITy);
+    if (Pred =3D=3D ICmpInst::ICMP_ULE)
+      return getTrue(ITy);
+  }
+
   if (MaxRecurse && LBO && RBO && LBO->getOpcode() =3D=3D RBO->getOpcode()=
 &&
       LBO->getOperand(1) =3D=3D RBO->getOperand(1)) {
     switch (LBO->getOpcode()) {
@@ -1884,7 +2144,7 @@
       if (!LBO->isExact() || !RBO->isExact())
         break;
       if (Value *V =3D SimplifyICmpInst(Pred, LBO->getOperand(0),
-                                      RBO->getOperand(0), TD, DT, MaxRecur=
se-1))
+                                      RBO->getOperand(0), Q, MaxRecurse-1))
         return V;
       break;
     case Instruction::Shl: {
@@ -1895,7 +2155,7 @@
       if (!NSW && ICmpInst::isSigned(Pred))
         break;
       if (Value *V =3D SimplifyICmpInst(Pred, LBO->getOperand(0),
-                                      RBO->getOperand(0), TD, DT, MaxRecur=
se-1))
+                                      RBO->getOperand(0), Q, MaxRecurse-1))
         return V;
       break;
     }
@@ -1949,7 +2209,7 @@
         return V;
       // Otherwise, see if "A EqP B" simplifies.
       if (MaxRecurse)
-        if (Value *V =3D SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
+        if (Value *V =3D SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
           return V;
       break;
     case CmpInst::ICMP_NE:
@@ -1963,7 +2223,7 @@
         return V;
       // Otherwise, see if "A InvEqP B" simplifies.
       if (MaxRecurse)
-        if (Value *V =3D SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse=
-1))
+        if (Value *V =3D SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
           return V;
       break;
     }
@@ -2019,7 +2279,7 @@
         return V;
       // Otherwise, see if "A EqP B" simplifies.
       if (MaxRecurse)
-        if (Value *V =3D SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
+        if (Value *V =3D SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
           return V;
       break;
     case CmpInst::ICMP_NE:
@@ -2033,7 +2293,7 @@
         return V;
       // Otherwise, see if "A InvEqP B" simplifies.
       if (MaxRecurse)
-        if (Value *V =3D SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse=
-1))
+        if (Value *V =3D SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
           return V;
       break;
     }
@@ -2090,37 +2350,66 @@
       return getFalse(ITy);
   }
=20
+  // Simplify comparisons of related pointers using a powerful, recursive
+  // GEP-walk when we have target data available..
+  if (Q.TD && LHS->getType()->isPointerTy() && RHS->getType()->isPointerTy=
())
+    if (Constant *C =3D computePointerICmp(*Q.TD, Pred, LHS, RHS))
+      return C;
+
+  if (GetElementPtrInst *GLHS =3D dyn_cast<GetElementPtrInst>(LHS)) {
+    if (GEPOperator *GRHS =3D dyn_cast<GEPOperator>(RHS)) {
+      if (GLHS->getPointerOperand() =3D=3D GRHS->getPointerOperand() &&
+          GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
+          (ICmpInst::isEquality(Pred) ||
+           (GLHS->isInBounds() && GRHS->isInBounds() &&
+            Pred =3D=3D ICmpInst::getSignedPredicate(Pred)))) {
+        // The bases are equal and the indices are constant.  Build a cons=
tant
+        // expression GEP with the same indices and a null base pointer to=
 see
+        // what constant folding can make out of it.
+        Constant *Null =3D Constant::getNullValue(GLHS->getPointerOperandT=
ype());
+        SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_en=
d());
+        Constant *NewLHS =3D ConstantExpr::getGetElementPtr(Null, IndicesL=
HS);
+
+        SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_en=
d());
+        Constant *NewRHS =3D ConstantExpr::getGetElementPtr(Null, IndicesR=
HS);
+        return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
+      }
+    }
+  }
+
   // If the comparison is with the result of a select instruction, check w=
hether
   // comparing with either branch of the select always yields the same val=
ue.
   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
-    if (Value *V =3D ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurs=
e))
+    if (Value *V =3D ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
       return V;
=20
   // If the comparison is with the result of a phi instruction, check whet=
her
   // doing the compare with each incoming phi value yields a common result.
   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
-    if (Value *V =3D ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
+    if (Value *V =3D ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
       return V;
=20
   return 0;
 }
=20
 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                              const TargetData *TD, const DominatorTree *D=
T) {
-  return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
+                              const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
+                              const DominatorTree *DT) {
+  return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
+                            RecursionLimit);
 }
=20
 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                               const TargetData *TD, const DominatorTree *=
DT,
-                               unsigned MaxRecurse) {
+                               const Query &Q, unsigned MaxRecurse) {
   CmpInst::Predicate Pred =3D (CmpInst::Predicate)Predicate;
   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
=20
   if (Constant *CLHS =3D dyn_cast<Constant>(LHS)) {
     if (Constant *CRHS =3D dyn_cast<Constant>(RHS))
-      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
+      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI=
);
=20
     // If we have a constant, make sure it is on the RHS.
     std::swap(LHS, RHS);
@@ -2188,27 +2477,31 @@
   // If the comparison is with the result of a select instruction, check w=
hether
   // comparing with either branch of the select always yields the same val=
ue.
   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
-    if (Value *V =3D ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurs=
e))
+    if (Value *V =3D ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
       return V;
=20
   // If the comparison is with the result of a phi instruction, check whet=
her
   // doing the compare with each incoming phi value yields a common result.
   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
-    if (Value *V =3D ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
+    if (Value *V =3D ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
       return V;
=20
   return 0;
 }
=20
 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                              const TargetData *TD, const DominatorTree *D=
T) {
-  return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
+                              const TargetData *TD,
+                              const TargetLibraryInfo *TLI,
+                              const DominatorTree *DT) {
+  return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
+                            RecursionLimit);
 }
=20
 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fo=
ld
 /// the result.  If not, this returns null.
-Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *Fal=
seVal,
-                                const TargetData *TD, const DominatorTree =
*) {
+static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
+                                 Value *FalseVal, const Query &Q,
+                                 unsigned MaxRecurse) {
   // select true, X, Y  -> X
   // select false, X, Y -> Y
   if (ConstantInt *CB =3D dyn_cast<ConstantInt>(CondVal))
@@ -2231,12 +2524,22 @@
   return 0;
 }
=20
+Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseV=
al,
+                                const TargetData *TD,
+                                const TargetLibraryInfo *TLI,
+                                const DominatorTree *DT) {
+  return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
+                              RecursionLimit);
+}
+
 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we c=
an
 /// fold the result.  If not, this returns null.
-Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops,
-                             const TargetData *TD, const DominatorTree *) {
+static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsig=
ned) {
   // The type of the GEP pointer operand.
-  PointerType *PtrTy =3D cast<PointerType>(Ops[0]->getType());
+  PointerType *PtrTy =3D dyn_cast<PointerType>(Ops[0]->getType());
+  // The GEP pointer operand is not a pointer, it's a vector of pointers.
+  if (!PtrTy)
+    return 0;
=20
   // getelementptr P -> P.
   if (Ops.size() =3D=3D 1)
@@ -2255,9 +2558,9 @@
       if (C->isZero())
         return Ops[0];
     // getelementptr P, N -> P if P points to a type of zero size.
-    if (TD) {
+    if (Q.TD) {
       Type *Ty =3D PtrTy->getElementType();
-      if (Ty->isSized() && TD->getTypeAllocSize(Ty) =3D=3D 0)
+      if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) =3D=3D 0)
         return Ops[0];
     }
   }
@@ -2270,12 +2573,17 @@
   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(=
1));
 }
=20
+Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
+                             const TargetLibraryInfo *TLI,
+                             const DominatorTree *DT) {
+  return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
+}
+
 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see i=
f we
 /// can fold the result.  If not, this returns null.
-Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
-                                     ArrayRef<unsigned> Idxs,
-                                     const TargetData *,
-                                     const DominatorTree *) {
+static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
+                                      ArrayRef<unsigned> Idxs, const Query=
 &Q,
+                                      unsigned) {
   if (Constant *CAgg =3D dyn_cast<Constant>(Agg))
     if (Constant *CVal =3D dyn_cast<Constant>(Val))
       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
@@ -2300,8 +2608,17 @@
   return 0;
 }
=20
+Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
+                                     ArrayRef<unsigned> Idxs,
+                                     const TargetData *TD,
+                                     const TargetLibraryInfo *TLI,
+                                     const DominatorTree *DT) {
+  return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
+                                   RecursionLimit);
+}
+
 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns n=
ull.
-static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
+static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
   // If all of the PHI's incoming values are the same then replace the PHI=
 node
   // with the common value.
   Value *CommonValue =3D 0;
@@ -2329,67 +2646,77 @@
   // instruction, we cannot return X as the result of the PHI node unless =
it
   // dominates the PHI block.
   if (HasUndefInput)
-    return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
+    return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
=20
   return CommonValue;
 }
=20
+static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsig=
ned) {
+  if (Constant *C =3D dyn_cast<Constant>(Op))
+    return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI=
);
+
+  return 0;
+}
+
+Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const TargetData *TD,
+                               const TargetLibraryInfo *TLI,
+                               const DominatorTree *DT) {
+  return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
+}
=20
 //=3D=3D=3D Helper functions for higher up the class hierarchy.
=20
 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
 /// fold the result.  If not, this returns null.
 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
-                            const TargetData *TD, const DominatorTree *DT,
-                            unsigned MaxRecurse) {
+                            const Query &Q, unsigned MaxRecurse) {
   switch (Opcode) {
   case Instruction::Add:
     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
-                           TD, DT, MaxRecurse);
+                           Q, MaxRecurse);
   case Instruction::Sub:
     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
-                           TD, DT, MaxRecurse);
-  case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, TD, DT, MaxRec=
urse);
-  case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRec=
urse);
-  case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRec=
urse);
-  case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRec=
urse);
-  case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRec=
urse);
-  case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRec=
urse);
-  case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRec=
urse);
+                           Q, MaxRecurse);
+  case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
+  case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
+  case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
+  case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
+  case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
+  case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
+  case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
   case Instruction::Shl:
     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
-                           TD, DT, MaxRecurse);
+                           Q, MaxRecurse);
   case Instruction::LShr:
-    return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse=
);
+    return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
   case Instruction::AShr:
-    return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse=
);
-  case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecur=
se);
-  case Instruction::Or:  return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecur=
se);
-  case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecur=
se);
+    return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
+  case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
+  case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
+  case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
   default:
     if (Constant *CLHS =3D dyn_cast<Constant>(LHS))
       if (Constant *CRHS =3D dyn_cast<Constant>(RHS)) {
         Constant *COps[] =3D {CLHS, CRHS};
-        return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD);
+        return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
+                                        Q.TLI);
       }
=20
     // If the operation is associative, try some generic simplifications.
     if (Instruction::isAssociative(Opcode))
-      if (Value *V =3D SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
-                                              MaxRecurse))
+      if (Value *V =3D SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRe=
curse))
         return V;
=20
-    // If the operation is with the result of a select instruction, check =
whether
+    // If the operation is with the result of a select instruction check w=
hether
     // operating on either branch of the select always yields the same val=
ue.
     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
-      if (Value *V =3D ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
-                                           MaxRecurse))
+      if (Value *V =3D ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecur=
se))
         return V;
=20
     // If the operation is with the result of a phi instruction, check whe=
ther
     // operating on all incoming values of the phi always yields the same =
value.
     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
-      if (Value *V =3D ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRec=
urse))
+      if (Value *V =3D ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
         return V;
=20
     return 0;
@@ -2397,119 +2724,136 @@
 }
=20
 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
-                           const TargetData *TD, const DominatorTree *DT) {
-  return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
+                           const TargetData *TD, const TargetLibraryInfo *=
TLI,
+                           const DominatorTree *DT) {
+  return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionL=
imit);
 }
=20
 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
 /// fold the result.
 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                              const TargetData *TD, const DominatorTree *D=
T,
-                              unsigned MaxRecurse) {
+                              const Query &Q, unsigned MaxRecurse) {
   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
-    return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
-  return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
+    return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
+  return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
 }
=20
 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
-                             const TargetData *TD, const DominatorTree *DT=
) {
-  return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
+                             const TargetData *TD, const TargetLibraryInfo=
 *TLI,
+                             const DominatorTree *DT) {
+  return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
+                           RecursionLimit);
+}
+
+static Value *SimplifyCallInst(CallInst *CI, const Query &) {
+  // call undef -> undef
+  if (isa<UndefValue>(CI->getCalledValue()))
+    return UndefValue::get(CI->getType());
+
+  return 0;
 }
=20
 /// SimplifyInstruction - See if we can compute a simplified version of th=
is
 /// instruction.  If not, this returns null.
 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
+                                 const TargetLibraryInfo *TLI,
                                  const DominatorTree *DT) {
   Value *Result;
=20
   switch (I->getOpcode()) {
   default:
-    Result =3D ConstantFoldInstruction(I, TD);
+    Result =3D ConstantFoldInstruction(I, TD, TLI);
     break;
   case Instruction::Add:
     Result =3D SimplifyAddInst(I->getOperand(0), I->getOperand(1),
                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
-                             TD, DT);
+                             TD, TLI, DT);
     break;
   case Instruction::Sub:
     Result =3D SimplifySubInst(I->getOperand(0), I->getOperand(1),
                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
-                             TD, DT);
+                             TD, TLI, DT);
     break;
   case Instruction::Mul:
-    Result =3D SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
+    Result =3D SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI=
, DT);
     break;
   case Instruction::SDiv:
-    Result =3D SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT=
);
+    Result =3D SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TL=
I, DT);
     break;
   case Instruction::UDiv:
-    Result =3D SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT=
);
+    Result =3D SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TL=
I, DT);
     break;
   case Instruction::FDiv:
-    Result =3D SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT=
);
+    Result =3D SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TL=
I, DT);
     break;
   case Instruction::SRem:
-    Result =3D SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT=
);
+    Result =3D SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TL=
I, DT);
     break;
   case Instruction::URem:
-    Result =3D SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT=
);
+    Result =3D SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TL=
I, DT);
     break;
   case Instruction::FRem:
-    Result =3D SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT=
);
+    Result =3D SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TL=
I, DT);
     break;
   case Instruction::Shl:
     Result =3D SimplifyShlInst(I->getOperand(0), I->getOperand(1),
                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
-                             TD, DT);
+                             TD, TLI, DT);
     break;
   case Instruction::LShr:
     Result =3D SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
                               cast<BinaryOperator>(I)->isExact(),
-                              TD, DT);
+                              TD, TLI, DT);
     break;
   case Instruction::AShr:
     Result =3D SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
                               cast<BinaryOperator>(I)->isExact(),
-                              TD, DT);
+                              TD, TLI, DT);
     break;
   case Instruction::And:
-    Result =3D SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
+    Result =3D SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI=
, DT);
     break;
   case Instruction::Or:
-    Result =3D SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
+    Result =3D SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI,=
 DT);
     break;
   case Instruction::Xor:
-    Result =3D SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
+    Result =3D SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI=
, DT);
     break;
   case Instruction::ICmp:
     Result =3D SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
-                              I->getOperand(0), I->getOperand(1), TD, DT);
+                              I->getOperand(0), I->getOperand(1), TD, TLI,=
 DT);
     break;
   case Instruction::FCmp:
     Result =3D SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
-                              I->getOperand(0), I->getOperand(1), TD, DT);
+                              I->getOperand(0), I->getOperand(1), TD, TLI,=
 DT);
     break;
   case Instruction::Select:
     Result =3D SimplifySelectInst(I->getOperand(0), I->getOperand(1),
-                                I->getOperand(2), TD, DT);
+                                I->getOperand(2), TD, TLI, DT);
     break;
   case Instruction::GetElementPtr: {
     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
-    Result =3D SimplifyGEPInst(Ops, TD, DT);
+    Result =3D SimplifyGEPInst(Ops, TD, TLI, DT);
     break;
   }
   case Instruction::InsertValue: {
     InsertValueInst *IV =3D cast<InsertValueInst>(I);
     Result =3D SimplifyInsertValueInst(IV->getAggregateOperand(),
                                      IV->getInsertedValueOperand(),
-                                     IV->getIndices(), TD, DT);
+                                     IV->getIndices(), TD, TLI, DT);
     break;
   }
   case Instruction::PHI:
-    Result =3D SimplifyPHINode(cast<PHINode>(I), DT);
+    Result =3D SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
+    break;
+  case Instruction::Call:
+    Result =3D SimplifyCallInst(cast<CallInst>(I), Query (TD, TLI, DT));
+    break;
+  case Instruction::Trunc:
+    Result =3D SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, =
DT);
     break;
   }
=20
@@ -2519,57 +2863,84 @@
   return Result =3D=3D I ? UndefValue::get(I->getType()) : Result;
 }
=20
-/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and t=
hen
-/// delete the From instruction.  In addition to a basic RAUW, this does a
-/// recursive simplification of the newly formed instructions.  This catch=
es
-/// things where one simplification exposes other opportunities.  This only
-/// simplifies and deletes scalar operations, it does not change the CFG.
+/// \brief Implementation of recursive simplification through an instructi=
ons
+/// uses.
 ///
-void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
-                                     const TargetData *TD,
-                                     const DominatorTree *DT) {
-  assert(From !=3D To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
-
-  // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so th=
at
-  // we can know if it gets deleted out from under us or replaced in a
-  // recursive simplification.
-  WeakVH FromHandle(From);
-  WeakVH ToHandle(To);
-
-  while (!From->use_empty()) {
-    // Update the instruction to use the new value.
-    Use &TheUse =3D From->use_begin().getUse();
-    Instruction *User =3D cast<Instruction>(TheUse.getUser());
-    TheUse =3D To;
-
-    // Check to see if the instruction can be folded due to the operand
-    // replacement.  For example changing (or X, Y) into (or X, -1) can re=
place
-    // the 'or' with -1.
-    Value *SimplifiedVal;
-    {
-      // Sanity check to make sure 'User' doesn't dangle across
-      // SimplifyInstruction.
-      AssertingVH<> UserHandle(User);
-
-      SimplifiedVal =3D SimplifyInstruction(User, TD, DT);
-      if (SimplifiedVal =3D=3D 0) continue;
-    }
-
-    // Recursively simplify this user to the new value.
-    ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
-    From =3D dyn_cast_or_null<Instruction>((Value*)FromHandle);
-    To =3D ToHandle;
-
-    assert(ToHandle && "To value deleted by recursive simplification?");
-
-    // If the recursive simplification ended up revisiting and deleting
-    // 'From' then we're done.
-    if (From =3D=3D 0)
-      return;
+/// This is the common implementation of the recursive simplification rout=
ines.
+/// If we have a pre-simplified value in 'SimpleV', that is forcibly used =
to
+/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list =
of
+/// instructions to process and attempt to simplify it using
+/// InstructionSimplify.
+///
+/// This routine returns 'true' only when *it* simplifies something. The p=
assed
+/// in simplified value does not count toward this.
+static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *Simpl=
eV,
+                                              const TargetData *TD,
+                                              const TargetLibraryInfo *TLI,
+                                              const DominatorTree *DT) {
+  bool Simplified =3D false;
+  SmallSetVector<Instruction *, 8> Worklist;
+
+  // If we have an explicit value to collapse to, do that round of the
+  // simplification loop by hand initially.
+  if (SimpleV) {
+    for (Value::use_iterator UI =3D I->use_begin(), UE =3D I->use_end(); U=
I !=3D UE;
+         ++UI)
+      if (*UI !=3D I)
+        Worklist.insert(cast<Instruction>(*UI));
+
+    // Replace the instruction with its simplified value.
+    I->replaceAllUsesWith(SimpleV);
+
+    // Gracefully handle edge cases where the instruction is not wired int=
o any
+    // parent block.
+    if (I->getParent())
+      I->eraseFromParent();
+  } else {
+    Worklist.insert(I);
   }
=20
-  // If 'From' has value handles referring to it, do a real RAUW to update=
 them.
-  From->replaceAllUsesWith(To);
-
-  From->eraseFromParent();
+  // Note that we must test the size on each iteration, the worklist can g=
row.
+  for (unsigned Idx =3D 0; Idx !=3D Worklist.size(); ++Idx) {
+    I =3D Worklist[Idx];
+
+    // See if this instruction simplifies.
+    SimpleV =3D SimplifyInstruction(I, TD, TLI, DT);
+    if (!SimpleV)
+      continue;
+
+    Simplified =3D true;
+
+    // Stash away all the uses of the old instruction so we can check them=
 for
+    // recursive simplifications after a RAUW. This is cheaper than checki=
ng all
+    // uses of To on the recursive step in most cases.
+    for (Value::use_iterator UI =3D I->use_begin(), UE =3D I->use_end(); U=
I !=3D UE;
+         ++UI)
+      Worklist.insert(cast<Instruction>(*UI));
+
+    // Replace the instruction with its simplified value.
+    I->replaceAllUsesWith(SimpleV);
+
+    // Gracefully handle edge cases where the instruction is not wired int=
o any
+    // parent block.
+    if (I->getParent())
+      I->eraseFromParent();
+  }
+  return Simplified;
 }
+
+bool llvm::recursivelySimplifyInstruction(Instruction *I,
+                                          const TargetData *TD,
+                                          const TargetLibraryInfo *TLI,
+                                          const DominatorTree *DT) {
+  return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
+}
+
+bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
+                                         const TargetData *TD,
+                                         const TargetLibraryInfo *TLI,
+                                         const DominatorTree *DT) {
+  assert(I !=3D SimpleV && "replaceAndRecursivelySimplify(X,X) is not vali=
d!");
+  assert(SimpleV && "Must provide a simplified value.");
+  return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/LazyVal=
ueInfo.cpp
--- a/head/contrib/llvm/lib/Analysis/LazyValueInfo.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/LazyValueInfo.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -20,20 +20,25 @@
 #include "llvm/IntrinsicInst.h"
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/ConstantRange.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/PatternMatch.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/ValueHandle.h"
-#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/STLExtras.h"
 #include <map>
 #include <stack>
 using namespace llvm;
+using namespace PatternMatch;
=20
 char LazyValueInfo::ID =3D 0;
-INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
+INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
+                "Lazy Value Information Analysis", false, true)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
+INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
                 "Lazy Value Information Analysis", false, true)
=20
 namespace llvm {
@@ -61,10 +66,10 @@
     constant,
     /// notconstant - This Value is known to not have the specified value.
     notconstant,
-   =20
+
     /// constantrange - The Value falls within this range.
     constantrange,
-   =20
+
     /// overdefined - This value is not known to be constant, and we know =
that
     /// it has a value.
     overdefined
@@ -207,7 +212,7 @@
=20
         // Unless we can prove that the two Constants are different, we mu=
st
         // move to overdefined.
-        // FIXME: use TargetData for smarter constant folding.
+        // FIXME: use TargetData/TargetLibraryInfo for smarter constant fo=
lding.
         if (ConstantInt *Res =3D dyn_cast<ConstantInt>(
                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
                                                 getConstant(),
@@ -233,7 +238,7 @@
=20
         // Unless we can prove that the two Constants are different, we mu=
st
         // move to overdefined.
-        // FIXME: use TargetData for smarter constant folding.
+        // FIXME: use TargetData/TargetLibraryInfo for smarter constant fo=
lding.
         if (ConstantInt *Res =3D dyn_cast<ConstantInt>(
                 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
                                                 getNotConstant(),
@@ -305,50 +310,6 @@
   };
 }
=20
-namespace llvm {
-  template<>
-  struct DenseMapInfo<LVIValueHandle> {
-    typedef DenseMapInfo<Value*> PointerInfo;
-    static inline LVIValueHandle getEmptyKey() {
-      return LVIValueHandle(PointerInfo::getEmptyKey(),
-                            static_cast<LazyValueInfoCache*>(0));
-    }
-    static inline LVIValueHandle getTombstoneKey() {
-      return LVIValueHandle(PointerInfo::getTombstoneKey(),
-                            static_cast<LazyValueInfoCache*>(0));
-    }
-    static unsigned getHashValue(const LVIValueHandle &Val) {
-      return PointerInfo::getHashValue(Val);
-    }
-    static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &R=
HS) {
-      return LHS =3D=3D RHS;
-    }
-  };
- =20
-  template<>
-  struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
-    typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
-    typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
-    typedef DenseMapInfo<Value*> BPointerInfo;
-    static inline PairTy getEmptyKey() {
-      return std::make_pair(APointerInfo::getEmptyKey(),
-                            BPointerInfo::getEmptyKey());
-    }
-    static inline PairTy getTombstoneKey() {
-      return std::make_pair(APointerInfo::getTombstoneKey(),=20
-                            BPointerInfo::getTombstoneKey());
-    }
-    static unsigned getHashValue( const PairTy &Val) {
-      return APointerInfo::getHashValue(Val.first) ^=20
-             BPointerInfo::getHashValue(Val.second);
-    }
-    static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
-      return APointerInfo::isEqual(LHS.first, RHS.first) &&
-             BPointerInfo::isEqual(LHS.second, RHS.second);
-    }
-  };
-}
-
 namespace {=20
   /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
   /// maintains information about queries across the clients' queries.
@@ -360,14 +321,18 @@
=20
     /// ValueCache - This is all of the cached information for all values,
     /// mapped from Value* to key information.
-    DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
+    std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
    =20
     /// OverDefinedCache - This tracks, on a per-block basis, the set of=20
     /// values that are over-defined at the end of that block.  This is re=
quired
     /// for cache updating.
     typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
     DenseSet<OverDefinedPairTy> OverDefinedCache;
-   =20
+
+    /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
+    /// don't spend time removing unused blocks from our caches.
+    DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
+
     /// BlockValueStack - This stack holds the state of the value solver
     /// during a query.  It basically emulates the callstack of the naive
     /// recursive value lookup process.
@@ -438,6 +403,7 @@
    =20
     /// clear - Empty the cache.
     void clear() {
+      SeenBlocks.clear();
       ValueCache.clear();
       OverDefinedCache.clear();
     }
@@ -466,6 +432,12 @@
 }
=20
 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
+  // Shortcut if we have never seen this block.
+  DenseSet<AssertingVH<BasicBlock> >::iterator I =3D SeenBlocks.find(BB);
+  if (I =3D=3D SeenBlocks.end())
+    return;
+  SeenBlocks.erase(I);
+
   SmallVector<OverDefinedPairTy, 4> ToErase;
   for (DenseSet<OverDefinedPairTy>::iterator  I =3D OverDefinedCache.begin=
(),
        E =3D OverDefinedCache.end(); I !=3D E; ++I) {
@@ -477,7 +449,7 @@
        E =3D ToErase.end(); I !=3D E; ++I)
     OverDefinedCache.erase(*I);
=20
-  for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
+  for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
        I =3D ValueCache.begin(), E =3D ValueCache.end(); I !=3D E; ++I)
     I->second.erase(BB);
 }
@@ -505,6 +477,7 @@
   if (Constant *VC =3D dyn_cast<Constant>(Val))
     return LVILatticeVal::get(VC);
=20
+  SeenBlocks.insert(BB);
   return lookup(Val)[BB];
 }
=20
@@ -513,6 +486,7 @@
     return true;
=20
   ValueCacheEntryTy &Cache =3D lookup(Val);
+  SeenBlocks.insert(BB);
   LVILatticeVal &BBLV =3D Cache[BB];
  =20
   // OverDefinedCacheUpdater is a helper object that will update
@@ -823,9 +797,8 @@
       // If the condition of the branch is an equality comparison, we may =
be
       // able to infer the value.
       ICmpInst *ICI =3D dyn_cast<ICmpInst>(BI->getCondition());
-      if (ICI && ICI->getOperand(0) =3D=3D Val &&
-          isa<Constant>(ICI->getOperand(1))) {
-        if (ICI->isEquality()) {
+      if (ICI && isa<Constant>(ICI->getOperand(1))) {
+        if (ICI->isEquality() && ICI->getOperand(0) =3D=3D Val) {
           // We know that V has the RHS constant if this is a true SETEQ or
           // false SETNE.=20
           if (isTrueDest =3D=3D (ICI->getPredicate() =3D=3D ICmpInst::ICMP=
_EQ))
@@ -835,12 +808,23 @@
           return true;
         }
=20
-        if (ConstantInt *CI =3D dyn_cast<ConstantInt>(ICI->getOperand(1)))=
 {
+        // Recognize the range checking idiom that InstCombine produces.
+        // (X-C1) u< C2 --> [C1, C1+C2)
+        ConstantInt *NegOffset =3D 0;
+        if (ICI->getPredicate() =3D=3D ICmpInst::ICMP_ULT)
+          match(ICI->getOperand(0), m_Add(m_Specific(Val),
+                                          m_ConstantInt(NegOffset)));
+
+        ConstantInt *CI =3D dyn_cast<ConstantInt>(ICI->getOperand(1));
+        if (CI && (ICI->getOperand(0) =3D=3D Val || NegOffset)) {
           // Calculate the range of values that would satisfy the comparis=
on.
           ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
           ConstantRange TrueValues =3D
             ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
=20
+          if (NegOffset) // Apply the offset from above.
+            TrueValues =3D TrueValues.subtract(NegOffset->getValue());
+
           // If we're interested in the false dest, invert the condition.
           if (!isTrueDest) TrueValues =3D TrueValues.inverse();
          =20
@@ -882,10 +866,11 @@
       // BBFrom to BBTo.
       unsigned NumEdges =3D 0;
       ConstantInt *EdgeVal =3D 0;
-      for (unsigned i =3D 1, e =3D SI->getNumSuccessors(); i !=3D e; ++i) {
-        if (SI->getSuccessor(i) !=3D BBTo) continue;
+      for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end();
+           i !=3D e; ++i) {
+        if (i.getCaseSuccessor() !=3D BBTo) continue;
         if (NumEdges++) break;
-        EdgeVal =3D SI->getCaseValue(i);
+        EdgeVal =3D i.getCaseValue();
       }
       assert(EdgeVal && "Missing successor?");
       if (NumEdges =3D=3D 1) {
@@ -1007,12 +992,19 @@
 bool LazyValueInfo::runOnFunction(Function &F) {
   if (PImpl)
     getCache(PImpl).clear();
- =20
+
   TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
+
   // Fully lazy.
   return false;
 }
=20
+void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
+  AU.setPreservesAll();
+  AU.addRequired<TargetLibraryInfo>();
+}
+
 void LazyValueInfo::releaseMemory() {
   // If the cache was allocated, free it.
   if (PImpl) {
@@ -1061,7 +1053,8 @@
   // If we know the value is a constant, evaluate the conditional.
   Constant *Res =3D 0;
   if (Result.isConstant()) {
-    Res =3D ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C,=
 TD);
+    Res =3D ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C,=
 TD,
+                                          TLI);
     if (ConstantInt *ResCI =3D dyn_cast<ConstantInt>(Res))
       return ResCI->isZero() ? False : True;
     return Unknown;
@@ -1102,13 +1095,15 @@
     if (Pred =3D=3D ICmpInst::ICMP_EQ) {
       // !C1 =3D=3D C -> false iff C1 =3D=3D C.
       Res =3D ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
-                                            Result.getNotConstant(), C, TD=
);
+                                            Result.getNotConstant(), C, TD,
+                                            TLI);
       if (Res->isNullValue())
         return False;
     } else if (Pred =3D=3D ICmpInst::ICMP_NE) {
       // !C1 !=3D C -> true iff C1 =3D=3D C.
       Res =3D ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
-                                            Result.getNotConstant(), C, TD=
);
+                                            Result.getNotConstant(), C, TD,
+                                            TLI);
       if (Res->isNullValue())
         return True;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Lint.cpp
--- a/head/contrib/llvm/lib/Analysis/Lint.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/Lint.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -44,6 +44,7 @@
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Pass.h"
 #include "llvm/PassManager.h"
 #include "llvm/IntrinsicInst.h"
@@ -103,6 +104,7 @@
     AliasAnalysis *AA;
     DominatorTree *DT;
     TargetData *TD;
+    TargetLibraryInfo *TLI;
=20
     std::string Messages;
     raw_string_ostream MessagesStr;
@@ -117,6 +119,7 @@
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesAll();
       AU.addRequired<AliasAnalysis>();
+      AU.addRequired<TargetLibraryInfo>();
       AU.addRequired<DominatorTree>();
     }
     virtual void print(raw_ostream &O, const Module *M) const {}
@@ -149,6 +152,7 @@
 char Lint::ID =3D 0;
 INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
                       false, true)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
 INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
@@ -174,6 +178,7 @@
   AA =3D &getAnalysis<AliasAnalysis>();
   DT =3D &getAnalysis<DominatorTree>();
   TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
   visit(F);
   dbgs() << MessagesStr.str();
   Messages.clear();
@@ -411,9 +416,8 @@
=20
     if (Align !=3D 0) {
       unsigned BitWidth =3D TD->getTypeSizeInBits(Ptr->getType());
-      APInt Mask =3D APInt::getAllOnesValue(BitWidth),
-                   KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-      ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
+      APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
+      ComputeMaskedBits(Ptr, KnownZero, KnownOne, TD);
       Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
               "Undefined behavior: Memory reference address is misaligned"=
, &I);
     }
@@ -471,9 +475,8 @@
   if (isa<UndefValue>(V)) return true;
=20
   unsigned BitWidth =3D cast<IntegerType>(V->getType())->getBitWidth();
-  APInt Mask =3D APInt::getAllOnesValue(BitWidth),
-               KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-  ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
+  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
+  ComputeMaskedBits(V, KnownZero, KnownOne, TD);
   return KnownZero.isAllOnesValue();
 }
=20
@@ -614,10 +617,10 @@
=20
   // As a last resort, try SimplifyInstruction or constant folding.
   if (Instruction *Inst =3D dyn_cast<Instruction>(V)) {
-    if (Value *W =3D SimplifyInstruction(Inst, TD, DT))
+    if (Value *W =3D SimplifyInstruction(Inst, TD, TLI, DT))
       return findValueImpl(W, OffsetOk, Visited);
   } else if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V)) {
-    if (Value *W =3D ConstantFoldConstantExpression(CE, TD))
+    if (Value *W =3D ConstantFoldConstantExpression(CE, TD, TLI))
       if (W !=3D V)
         return findValueImpl(W, OffsetOk, Visited);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Loads.c=
pp
--- a/head/contrib/llvm/lib/Analysis/Loads.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Analysis/Loads.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -17,6 +17,7 @@
 #include "llvm/GlobalAlias.h"
 #include "llvm/GlobalVariable.h"
 #include "llvm/IntrinsicInst.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Operator.h"
 using namespace llvm;
=20
@@ -160,10 +161,15 @@
 /// MaxInstsToScan specifies the maximum instructions to scan in the block=
.  If
 /// it is set to 0, it will scan the whole block. You can also optionally
 /// specify an alias analysis implementation, which makes this more precis=
e.
+///
+/// If TBAATag is non-null and a load or store is found, the TBAA tag from=
 the
+/// load or store is recorded there.  If there is no TBAA tag or if no acc=
ess
+/// is found, it is left unmodified.
 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
                                       BasicBlock::iterator &ScanFrom,
                                       unsigned MaxInstsToScan,
-                                      AliasAnalysis *AA) {
+                                      AliasAnalysis *AA,
+                                      MDNode **TBAATag) {
   if (MaxInstsToScan =3D=3D 0) MaxInstsToScan =3D ~0U;
=20
   // If we're using alias analysis to disambiguate get the size of *Ptr.
@@ -191,15 +197,19 @@
     // (This is true even if the load is volatile or atomic, although
     // those cases are unlikely.)
     if (LoadInst *LI =3D dyn_cast<LoadInst>(Inst))
-      if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
+      if (AreEquivalentAddressValues(LI->getOperand(0), Ptr)) {
+        if (TBAATag) *TBAATag =3D LI->getMetadata(LLVMContext::MD_tbaa);
         return LI;
+      }
    =20
     if (StoreInst *SI =3D dyn_cast<StoreInst>(Inst)) {
       // If this is a store through Ptr, the value is available!
       // (This is true even if the store is volatile or atomic, although
       // those cases are unlikely.)
-      if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
+      if (AreEquivalentAddressValues(SI->getOperand(1), Ptr)) {
+        if (TBAATag) *TBAATag =3D SI->getMetadata(LLVMContext::MD_tbaa);
         return SI->getOperand(0);
+      }
      =20
       // If Ptr is an alloca and this is a store to a different alloca, ig=
nore
       // the store.  This is a trivial form of alias analysis that is impo=
rtant
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/LoopDep=
endenceAnalysis.cpp
--- a/head/contrib/llvm/lib/Analysis/LoopDependenceAnalysis.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/LoopDependenceAnalysis.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -91,8 +91,6 @@
   if (StoreInst *i =3D dyn_cast<StoreInst>(I))
     return i->getPointerOperand();
   llvm_unreachable("Value is no load or store instruction!");
-  // Never reached.
-  return 0;
 }
=20
 static AliasAnalysis::AliasResult UnderlyingObjectsAlias(AliasAnalysis *AA,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/LoopInf=
o.cpp
--- a/head/contrib/llvm/lib/Analysis/LoopInfo.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Analysis/LoopInfo.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -19,6 +19,7 @@
 #include "llvm/Instructions.h"
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/LoopIterator.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/CommandLine.h"
@@ -95,7 +96,7 @@
   // Test if the value is already loop-invariant.
   if (isLoopInvariant(I))
     return true;
-  if (!I->isSafeToSpeculativelyExecute())
+  if (!isSafeToSpeculativelyExecute(I))
     return false;
   if (I->mayReadFromMemory())
     return false;
@@ -165,99 +166,6 @@
   return 0;
 }
=20
-/// getTripCount - Return a loop-invariant LLVM value indicating the numbe=
r of
-/// times the loop will be executed.  Note that this means that the backed=
ge
-/// of the loop executes N-1 times.  If the trip-count cannot be determine=
d,
-/// this returns null.
-///
-/// The IndVarSimplify pass transforms loops to have a form that this
-/// function easily understands.
-///
-Value *Loop::getTripCount() const {
-  // Canonical loops will end with a 'cmp ne I, V', where I is the increme=
nted
-  // canonical induction variable and V is the trip count of the loop.
-  PHINode *IV =3D getCanonicalInductionVariable();
-  if (IV =3D=3D 0 || IV->getNumIncomingValues() !=3D 2) return 0;
-
-  bool P0InLoop =3D contains(IV->getIncomingBlock(0));
-  Value *Inc =3D IV->getIncomingValue(!P0InLoop);
-  BasicBlock *BackedgeBlock =3D IV->getIncomingBlock(!P0InLoop);
-
-  if (BranchInst *BI =3D dyn_cast<BranchInst>(BackedgeBlock->getTerminator=
()))
-    if (BI->isConditional()) {
-      if (ICmpInst *ICI =3D dyn_cast<ICmpInst>(BI->getCondition())) {
-        if (ICI->getOperand(0) =3D=3D Inc) {
-          if (BI->getSuccessor(0) =3D=3D getHeader()) {
-            if (ICI->getPredicate() =3D=3D ICmpInst::ICMP_NE)
-              return ICI->getOperand(1);
-          } else if (ICI->getPredicate() =3D=3D ICmpInst::ICMP_EQ) {
-            return ICI->getOperand(1);
-          }
-        }
-      }
-    }
-
-  return 0;
-}
-
-/// getSmallConstantTripCount - Returns the trip count of this loop as a
-/// normal unsigned value, if possible. Returns 0 if the trip count is unk=
nown
-/// or not constant. Will also return 0 if the trip count is very large
-/// (>=3D 2^32)
-unsigned Loop::getSmallConstantTripCount() const {
-  Value* TripCount =3D this->getTripCount();
-  if (TripCount) {
-    if (ConstantInt *TripCountC =3D dyn_cast<ConstantInt>(TripCount)) {
-      // Guard against huge trip counts.
-      if (TripCountC->getValue().getActiveBits() <=3D 32) {
-        return (unsigned)TripCountC->getZExtValue();
-      }
-    }
-  }
-  return 0;
-}
-
-/// getSmallConstantTripMultiple - Returns the largest constant divisor of=
 the
-/// trip count of this loop as a normal unsigned value, if possible. This
-/// means that the actual trip count is always a multiple of the returned
-/// value (don't forget the trip count could very well be zero as well!).
-///
-/// Returns 1 if the trip count is unknown or not guaranteed to be the
-/// multiple of a constant (which is also the case if the trip count is si=
mply
-/// constant, use getSmallConstantTripCount for that case), Will also retu=
rn 1
-/// if the trip count is very large (>=3D 2^32).
-unsigned Loop::getSmallConstantTripMultiple() const {
-  Value* TripCount =3D this->getTripCount();
-  // This will hold the ConstantInt result, if any
-  ConstantInt *Result =3D NULL;
-  if (TripCount) {
-    // See if the trip count is constant itself
-    Result =3D dyn_cast<ConstantInt>(TripCount);
-    // if not, see if it is a multiplication
-    if (!Result)
-      if (BinaryOperator *BO =3D dyn_cast<BinaryOperator>(TripCount)) {
-        switch (BO->getOpcode()) {
-        case BinaryOperator::Mul:
-          Result =3D dyn_cast<ConstantInt>(BO->getOperand(1));
-          break;
-        case BinaryOperator::Shl:
-          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(BO->getOperand(1)))
-            if (CI->getValue().getActiveBits() <=3D 5)
-              return 1u << CI->getZExtValue();
-          break;
-        default:
-          break;
-        }
-      }
-  }
-  // Guard against huge trip counts.
-  if (Result && Result->getValue().getActiveBits() <=3D 32) {
-    return (unsigned)Result->getZExtValue();
-  } else {
-    return 1;
-  }
-}
-
 /// isLCSSAForm - Return true if the Loop is in LCSSA form
 bool Loop::isLCSSAForm(DominatorTree &DT) const {
   // Sort the blocks vector so that we can use binary search to do quick
@@ -297,6 +205,17 @@
   return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
 }
=20
+/// isSafeToClone - Return true if the loop body is safe to clone in pract=
ice.
+/// Routines that reform the loop CFG and split edges often fail on indire=
ctbr.
+bool Loop::isSafeToClone() const {
+  // Return false if any loop blocks contain indirectbrs.
+  for (Loop::block_iterator I =3D block_begin(), E =3D block_end(); I !=3D=
 E; ++I) {
+    if (isa<IndirectBrInst>((*I)->getTerminator()))
+      return false;
+  }
+  return true;
+}
+
 /// hasDedicatedExits - Return true if no exit block for the loop
 /// has a predecessor that is outside the loop.
 bool Loop::hasDedicatedExits() const {
@@ -477,21 +396,19 @@
 /// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors =
below
 /// their new parents.
 void UnloopUpdater::removeBlocksFromAncestors() {
-  // Remove unloop's blocks from all ancestors below their new parents.
+  // Remove all unloop's blocks (including those in nested subloops) from
+  // ancestors below the new parent loop.
   for (Loop::block_iterator BI =3D Unloop->block_begin(),
          BE =3D Unloop->block_end(); BI !=3D BE; ++BI) {
-    Loop *NewParent =3D LI->getLoopFor(*BI);
-    // If this block is an immediate subloop, remove all blocks (including
-    // nested subloops) from ancestors below the new parent loop.
-    // Otherwise, if this block is in a nested subloop, skip it.
-    if (SubloopParents.count(NewParent))
-      NewParent =3D SubloopParents[NewParent];
-    else if (Unloop->contains(NewParent))
-      continue;
-
+    Loop *OuterParent =3D LI->getLoopFor(*BI);
+    if (Unloop->contains(OuterParent)) {
+      while (OuterParent->getParentLoop() !=3D Unloop)
+        OuterParent =3D OuterParent->getParentLoop();
+      OuterParent =3D SubloopParents[OuterParent];
+    }
     // Remove blocks from former Ancestors except Unloop itself which will=
 be
     // deleted.
-    for (Loop *OldParent =3D Unloop->getParentLoop(); OldParent !=3D NewPa=
rent;
+    for (Loop *OldParent =3D Unloop->getParentLoop(); OldParent !=3D Outer=
Parent;
          OldParent =3D OldParent->getParentLoop()) {
       assert(OldParent && "new loop is not an ancestor of the original");
       OldParent->removeBlockFromLoop(*BI);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/LoopPas=
s.cpp
--- a/head/contrib/llvm/lib/Analysis/LoopPass.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Analysis/LoopPass.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -14,10 +14,8 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Analysis/LoopPass.h"
-#include "llvm/DebugInfoProbe.h"
 #include "llvm/Assembly/PrintModulePass.h"
 #include "llvm/Support/Debug.h"
-#include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Timer.h"
 using namespace llvm;
=20
@@ -54,20 +52,6 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// DebugInfoProbe
-
-static DebugInfoProbeInfo *TheDebugProbe;
-static void createDebugInfoProbe() {
-  if (TheDebugProbe) return;
-
-  // Constructed the first time this is called. This guarantees that the
-  // object will be constructed, if -enable-debug-info-probe is set,
-  // before static globals, thus it will be destroyed before them.
-  static ManagedStatic<DebugInfoProbeInfo> DIP;
-  TheDebugProbe =3D &*DIP;
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // LPPassManager
 //
=20
@@ -195,7 +179,6 @@
 bool LPPassManager::runOnFunction(Function &F) {
   LI =3D &getAnalysis<LoopInfo>();
   bool Changed =3D false;
-  createDebugInfoProbe();
=20
   // Collect inherited analysis from Module level pass manager.
   populateInheritedAnalysis(TPM->activeStack);
@@ -227,21 +210,19 @@
     // Run all passes on the current Loop.
     for (unsigned Index =3D 0; Index < getNumContainedPasses(); ++Index) {
       LoopPass *P =3D getContainedPass(Index);
+
       dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
                    CurrentLoop->getHeader()->getName());
       dumpRequiredSet(P);
=20
       initializeAnalysisImpl(P);
-      if (TheDebugProbe)
-        TheDebugProbe->initialize(P, F);
+
       {
         PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
         TimeRegion PassTimer(getPassTimer(P));
=20
         Changed |=3D P->runOnLoop(CurrentLoop, *this);
       }
-      if (TheDebugProbe)
-        TheDebugProbe->finalize(P, F);
=20
       if (Changed)
         dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/MemDepP=
rinter.cpp
--- a/head/contrib/llvm/lib/Analysis/MemDepPrinter.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/MemDepPrinter.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -130,7 +130,7 @@
         AliasAnalysis::Location Loc =3D AA.getLocation(LI);
         MDA.getNonLocalPointerDependency(Loc, true, LI->getParent(), NLDI);
       } else if (StoreInst *SI =3D dyn_cast<StoreInst>(Inst)) {
-        if (!LI->isUnordered()) {
+        if (!SI->isUnordered()) {
           // FIXME: Handle atomic/volatile stores.
           Deps[Inst].insert(std::make_pair(getInstTypePair(0, Unknown),
                                            static_cast<BasicBlock *>(0)));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/MemoryB=
uiltins.cpp
--- a/head/contrib/llvm/lib/Analysis/MemoryBuiltins.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/MemoryBuiltins.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -48,10 +48,10 @@
   // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin=20
   // attribute will exist.
   FunctionType *FTy =3D Callee->getFunctionType();
-  if (FTy->getNumParams() !=3D 1)
-    return false;
-  return FTy->getParamType(0)->isIntegerTy(32) ||
-         FTy->getParamType(0)->isIntegerTy(64);
+  return FTy->getReturnType() =3D=3D Type::getInt8PtrTy(FTy->getContext())=
 &&
+         FTy->getNumParams() =3D=3D 1 &&
+         (FTy->getParamType(0)->isIntegerTy(32) ||
+          FTy->getParamType(0)->isIntegerTy(64));
 }
=20
 /// extractMallocCall - Returns the corresponding CallInst if the instruct=
ion
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/MemoryD=
ependenceAnalysis.cpp
--- a/head/contrib/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -22,6 +22,7 @@
 #include "llvm/Function.h"
 #include "llvm/LLVMContext.h"
 #include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/Analysis/CaptureTracking.h"
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
@@ -91,6 +92,7 @@
 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
   AA =3D &getAnalysis<AliasAnalysis>();
   TD =3D getAnalysisIfAvailable<TargetData>();
+  DT =3D getAnalysisIfAvailable<DominatorTree>();
   if (PredCache =3D=3D 0)
     PredCache.reset(new PredIteratorCache());
   return false;
@@ -321,14 +323,100 @@
         !TD.fitsInLegalInteger(NewLoadByteSize*8))
       return 0;
=20
+    if (LIOffs+NewLoadByteSize > MemLocEnd &&
+        LI->getParent()->getParent()->hasFnAttr(Attribute::AddressSafety))=
 {
+      // We will be reading past the location accessed by the original pro=
gram.
+      // While this is safe in a regular build, Address Safety analysis to=
ols
+      // may start reporting false warnings. So, don't do widening.
+      return 0;
+    }
+
     // If a load of this width would include all of MemLoc, then we succee=
d.
     if (LIOffs+NewLoadByteSize >=3D MemLocEnd)
       return NewLoadByteSize;
    =20
     NewLoadByteSize <<=3D 1;
   }
- =20
-  return 0;
+}
+
+namespace {
+  /// Only find pointer captures which happen before the given instruction=
. Uses
+  /// the dominator tree to determine whether one instruction is before an=
other.
+  struct CapturesBefore : public CaptureTracker {
+    CapturesBefore(const Instruction *I, DominatorTree *DT)
+      : BeforeHere(I), DT(DT), Captured(false) {}
+
+    void tooManyUses() { Captured =3D true; }
+
+    bool shouldExplore(Use *U) {
+      Instruction *I =3D cast<Instruction>(U->getUser());
+      BasicBlock *BB =3D I->getParent();
+      if (BeforeHere !=3D I &&
+          (!DT->isReachableFromEntry(BB) || DT->dominates(BeforeHere, I)))
+        return false;
+      return true;
+    }
+
+    bool captured(Use *U) {
+      Instruction *I =3D cast<Instruction>(U->getUser());
+      BasicBlock *BB =3D I->getParent();
+      if (BeforeHere !=3D I &&
+          (!DT->isReachableFromEntry(BB) || DT->dominates(BeforeHere, I)))
+        return false;
+      Captured =3D true;
+      return true;
+    }
+
+    const Instruction *BeforeHere;
+    DominatorTree *DT;
+
+    bool Captured;
+  };
+}
+
+AliasAnalysis::ModRefResult
+MemoryDependenceAnalysis::getModRefInfo(const Instruction *Inst,
+                                        const AliasAnalysis::Location &Mem=
Loc) {
+  AliasAnalysis::ModRefResult MR =3D AA->getModRefInfo(Inst, MemLoc);
+  if (MR !=3D AliasAnalysis::ModRef) return MR;
+
+  // FIXME: this is really just shoring-up a deficiency in alias analysis.
+  // BasicAA isn't willing to spend linear time determining whether an all=
oca
+  // was captured before or after this particular call, while we are. Howe=
ver,
+  // with a smarter AA in place, this test is just wasting compile time.
+  if (!DT) return AliasAnalysis::ModRef;
+  const Value *Object =3D GetUnderlyingObject(MemLoc.Ptr, TD);
+  if (!isIdentifiedObject(Object) || isa<GlobalValue>(Object))
+    return AliasAnalysis::ModRef;
+  ImmutableCallSite CS(Inst);
+  if (!CS.getInstruction()) return AliasAnalysis::ModRef;
+
+  CapturesBefore CB(Inst, DT);
+  llvm::PointerMayBeCaptured(Object, &CB);
+
+  if (isa<Constant>(Object) || CS.getInstruction() =3D=3D Object || CB.Cap=
tured)
+    return AliasAnalysis::ModRef;
+
+  unsigned ArgNo =3D 0;
+  for (ImmutableCallSite::arg_iterator CI =3D CS.arg_begin(), CE =3D CS.ar=
g_end();
+       CI !=3D CE; ++CI, ++ArgNo) {
+    // Only look at the no-capture or byval pointer arguments.  If this
+    // pointer were passed to arguments that were neither of these, then it
+    // couldn't be no-capture.
+    if (!(*CI)->getType()->isPointerTy() ||
+        (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
+      continue;
+
+    // If this is a no-capture pointer argument, see if we can tell that it
+    // is impossible to alias the pointer we're checking.  If not, we have=
 to
+    // assume that the call could touch the pointer, even though it doesn't
+    // escape.
+    if (!AA->isNoAlias(AliasAnalysis::Location(*CI),
+                       AliasAnalysis::Location(Object))) {
+      return AliasAnalysis::ModRef;
+    }
+  }
+  return AliasAnalysis::NoModRef;
 }
=20
 /// getPointerDependencyFrom - Return the instruction on which a memory
@@ -478,7 +566,7 @@
     }
=20
     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointe=
r.
-    switch (AA->getModRefInfo(Inst, MemLoc)) {
+    switch (getModRefInfo(Inst, MemLoc)) {
     case AliasAnalysis::NoModRef:
       // If the call has no effect on the queried pointer, just ignore it.
       continue;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/PHITran=
sAddr.cpp
--- a/head/contrib/llvm/lib/Analysis/PHITransAddr.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Analysis/PHITransAddr.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -12,6 +12,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Analysis/PHITransAddr.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Constants.h"
 #include "llvm/Instructions.h"
 #include "llvm/Analysis/Dominators.h"
@@ -27,7 +28,7 @@
     return true;
=20
   if (isa<CastInst>(Inst) &&
-      Inst->isSafeToSpeculativelyExecute())
+      isSafeToSpeculativelyExecute(Inst))
     return true;
=20
   if (Inst->getOpcode() =3D=3D Instruction::Add &&
@@ -73,7 +74,6 @@
     errs() << *I << '\n';
     llvm_unreachable("Either something is missing from InstInputs or "
                      "CanPHITrans is wrong.");
-    return false;
   }
=20
   // Validate the operands of the instruction.
@@ -100,7 +100,6 @@
     for (unsigned i =3D 0, e =3D InstInputs.size(); i !=3D e; ++i)
       errs() << "  InstInput #" << i << " is " << *InstInputs[i] << "\n";
     llvm_unreachable("This is unexpected.");
-    return false;
   }
=20
   // a-ok.
@@ -186,7 +185,7 @@
   // operands need to be phi translated, and if so, reconstruct it.
=20
   if (CastInst *Cast =3D dyn_cast<CastInst>(Inst)) {
-    if (!Cast->isSafeToSpeculativelyExecute()) return 0;
+    if (!isSafeToSpeculativelyExecute(Cast)) return 0;
     Value *PHIIn =3D PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredB=
B, DT);
     if (PHIIn =3D=3D 0) return 0;
     if (PHIIn =3D=3D Cast->getOperand(0))
@@ -228,7 +227,7 @@
       return GEP;
=20
     // Simplify the GEP to handle 'gep x, 0' -> x etc.
-    if (Value *V =3D SimplifyGEPInst(GEPOps, TD, DT)) {
+    if (Value *V =3D SimplifyGEPInst(GEPOps, TD, TLI, DT)) {
       for (unsigned i =3D 0, e =3D GEPOps.size(); i !=3D e; ++i)
         RemoveInstInputs(GEPOps[i], InstInputs);
=20
@@ -284,7 +283,7 @@
         }
=20
     // See if the add simplifies away.
-    if (Value *Res =3D SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD, DT)) {
+    if (Value *Res =3D SimplifyAddInst(LHS, RHS, isNSW, isNUW, TD, TLI, DT=
)) {
       // If we simplified the operands, the LHS is no longer an input, but=
 Res
       // is.
       RemoveInstInputs(LHS, InstInputs);
@@ -381,7 +380,7 @@
=20
   // Handle cast of PHI translatable value.
   if (CastInst *Cast =3D dyn_cast<CastInst>(Inst)) {
-    if (!Cast->isSafeToSpeculativelyExecute()) return 0;
+    if (!isSafeToSpeculativelyExecute(Cast)) return 0;
     Value *OpVal =3D InsertPHITranslatedSubExpr(Cast->getOperand(0),
                                               CurBB, PredBB, DT, NewInsts);
     if (OpVal =3D=3D 0) return 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/PathNum=
bering.cpp
--- a/head/contrib/llvm/lib/Analysis/PathNumbering.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/PathNumbering.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -386,8 +386,8 @@
     }
=20
     TerminatorInst* terminator =3D currentNode->getBlock()->getTerminator(=
);
-    if(isa<ReturnInst>(terminator) || isa<UnreachableInst>(terminator)
-       || isa<ResumeInst>(terminator) || isa<UnwindInst>(terminator))
+    if(isa<ReturnInst>(terminator) || isa<UnreachableInst>(terminator) ||
+       isa<ResumeInst>(terminator))
       addEdge(currentNode, getExit(),0);
=20
     currentNode->setColor(BallLarusNode::GRAY);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/PathPro=
fileVerifier.cpp
--- a/head/contrib/llvm/lib/Analysis/PathProfileVerifier.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/PathProfileVerifier.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -137,22 +137,22 @@
         BasicBlock* source =3D nextEdge->getSource();
         BasicBlock* target =3D nextEdge->getTarget();
         unsigned duplicateNumber =3D nextEdge->getDuplicateNumber();
-        DEBUG(dbgs () << source->getNameStr() << " --{" << duplicateNumber
-              << "}--> " << target->getNameStr());
+        DEBUG(dbgs() << source->getName() << " --{" << duplicateNumber
+                     << "}--> " << target->getName());
=20
         // Ensure all the referenced edges exist
         // TODO: make this a separate function
         if( !arrayMap.count(source) ) {
-          errs() << "  error [" << F->getNameStr() << "()]: source '"
-                 << source->getNameStr()
+          errs() << "  error [" << F->getName() << "()]: source '"
+                 << source->getName()
                  << "' does not exist in the array map.\n";
         } else if( !arrayMap[source].count(target) ) {
-          errs() << "  error [" << F->getNameStr() << "()]: target '"
-                 << target->getNameStr()
+          errs() << "  error [" << F->getName() << "()]: target '"
+                 << target->getName()
                  << "' does not exist in the array map.\n";
         } else if( !arrayMap[source][target].count(duplicateNumber) ) {
-          errs() << "  error [" << F->getNameStr() << "()]: edge "
-                 << source->getNameStr() << " -> " << target->getNameStr()
+          errs() << "  error [" << F->getName() << "()]: edge "
+                 << source->getName() << " -> " << target->getName()
                  << " duplicate number " << duplicateNumber
                  << " does not exist in the array map.\n";
         } else {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Profile=
EstimatorPass.cpp
--- a/head/contrib/llvm/lib/Analysis/ProfileEstimatorPass.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ProfileEstimatorPass.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -332,7 +332,7 @@
   // Clear Minimal Edges.
   MinimalWeight.clear();
=20
-  DEBUG(dbgs() << "Working on function " << F.getNameStr() << "\n");
+  DEBUG(dbgs() << "Working on function " << F.getName() << "\n");
=20
   // Since the entry block is the first one and has no predecessors, the e=
dge
   // (0,entry) is inserted with the starting weight of 1.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Profile=
InfoLoaderPass.cpp
--- a/head/contrib/llvm/lib/Analysis/ProfileInfoLoaderPass.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ProfileInfoLoaderPass.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -160,7 +160,7 @@
     ReadCount =3D 0;
     for (Module::iterator F =3D M.begin(), E =3D M.end(); F !=3D E; ++F) {
       if (F->isDeclaration()) continue;
-      DEBUG(dbgs()<<"Working on "<<F->getNameStr()<<"\n");
+      DEBUG(dbgs() << "Working on " << F->getName() << "\n");
       readEdge(getEdge(0,&F->getEntryBlock()), Counters);
       for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D E=
; ++BB) {
         TerminatorInst *TI =3D BB->getTerminator();
@@ -181,7 +181,7 @@
     ReadCount =3D 0;
     for (Module::iterator F =3D M.begin(), E =3D M.end(); F !=3D E; ++F) {
       if (F->isDeclaration()) continue;
-      DEBUG(dbgs()<<"Working on "<<F->getNameStr()<<"\n");
+      DEBUG(dbgs() << "Working on " << F->getName() << "\n");
       readEdge(getEdge(0,&F->getEntryBlock()), Counters);
       for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D E=
; ++BB) {
         TerminatorInst *TI =3D BB->getTerminator();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Profile=
VerifierPass.cpp
--- a/head/contrib/llvm/lib/Analysis/ProfileVerifierPass.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ProfileVerifierPass.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -30,7 +30,7 @@
 ProfileVerifierDisableAssertions("profile-verifier-noassert",
      cl::desc("Disable assertions"));
=20
-namespace llvm {
+namespace {
   template<class FType, class BType>
   class ProfileVerifierPassT : public FunctionPass {
=20
@@ -125,8 +125,8 @@
         outCount++;
       }
     }
-    dbgs() << "Block " << BB->getNameStr()                << " in "=20
-           << BB->getParent()->getNameStr()               << ":"
+    dbgs() << "Block " << BB->getName()                   << " in "
+           << BB->getParent()->getName()                  << ":"
            << "BBWeight=3D"  << format("%20.20g",BBWeight)  << ","
            << "inWeight=3D"  << format("%20.20g",inWeight)  << ","
            << "inCount=3D"   << inCount                     << ","
@@ -143,8 +143,8 @@
=20
   template<class FType, class BType>
   void ProfileVerifierPassT<FType, BType>::debugEntry (DetailedBlockInfo *=
DI) {
-    dbgs() << "TROUBLE: Block " << DI->BB->getNameStr()       << " in "
-           << DI->BB->getParent()->getNameStr()               << ":"
+    dbgs() << "TROUBLE: Block " << DI->BB->getName()          << " in "
+           << DI->BB->getParent()->getName()                  << ":"
            << "BBWeight=3D"  << format("%20.20g",DI->BBWeight)  << ","
            << "inWeight=3D"  << format("%20.20g",DI->inWeight)  << ","
            << "inCount=3D"   << DI->inCount                     << ","
@@ -201,13 +201,13 @@
     double EdgeWeight =3D PI->getEdgeWeight(E);
     if (EdgeWeight =3D=3D ProfileInfoT<FType, BType>::MissingValue) {
       dbgs() << "Edge " << E << " in Function "=20
-             << ProfileInfoT<FType, BType>::getFunction(E)->getNameStr() <=
< ": ";
+             << ProfileInfoT<FType, BType>::getFunction(E)->getName() << "=
: ";
       ASSERTMESSAGE("Edge has missing value");
       return 0;
     } else {
       if (EdgeWeight < 0) {
         dbgs() << "Edge " << E << " in Function "=20
-               << ProfileInfoT<FType, BType>::getFunction(E)->getNameStr()=
 << ": ";
+               << ProfileInfoT<FType, BType>::getFunction(E)->getName() <<=
 ": ";
         ASSERTMESSAGE("Edge has negative value");
       }
       return EdgeWeight;
@@ -220,8 +220,8 @@
                                                       DetailedBlockInfo *D=
I) {
     if (Error) {
       DEBUG(debugEntry(DI));
-      dbgs() << "Block " << DI->BB->getNameStr() << " in Function "=20
-             << DI->BB->getParent()->getNameStr() << ": ";
+      dbgs() << "Block " << DI->BB->getName() << " in Function "
+             << DI->BB->getParent()->getName() << ": ";
       ASSERTMESSAGE(Message);
     }
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/RegionI=
nfo.cpp
--- a/head/contrib/llvm/lib/Analysis/RegionInfo.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Analysis/RegionInfo.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -186,18 +186,16 @@
     raw_string_ostream OS(entryName);
=20
     WriteAsOperand(OS, getEntry(), false);
-    entryName =3D OS.str();
   } else
-    entryName =3D getEntry()->getNameStr();
+    entryName =3D getEntry()->getName();
=20
   if (getExit()) {
     if (getExit()->getName().empty()) {
       raw_string_ostream OS(exitName);
=20
       WriteAsOperand(OS, getExit(), false);
-      exitName =3D OS.str();
     } else
-      exitName =3D getExit()->getNameStr();
+      exitName =3D getExit()->getName();
   } else
     exitName =3D "<Function Return>";
=20
@@ -652,7 +650,7 @@
   // This basic block is a start block of a region. It is already in the
   // BBtoRegion relation. Only the child basic blocks have to be updated.
   if (it !=3D BBtoRegion.end()) {
-    Region *newRegion =3D it->second;;
+    Region *newRegion =3D it->second;
     region->addSubRegion(getTopMostParent(newRegion));
     region =3D newRegion;
   } else {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/ScalarE=
volution.cpp
--- a/head/contrib/llvm/lib/Analysis/ScalarEvolution.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ScalarEvolution.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -74,6 +74,7 @@
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ConstantRange.h"
 #include "llvm/Support/Debug.h"
@@ -108,6 +109,7 @@
                 "Scalar Evolution Analysis", false, true)
 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
 INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
                 "Scalar Evolution Analysis", false, true)
 char ScalarEvolution::ID =3D 0;
@@ -188,6 +190,14 @@
         OS << OpStr;
     }
     OS << ")";
+    switch (NAry->getSCEVType()) {
+    case scAddExpr:
+    case scMulExpr:
+      if (NAry->getNoWrapFlags(FlagNUW))
+        OS << "<nuw>";
+      if (NAry->getNoWrapFlags(FlagNSW))
+        OS << "<nsw>";
+    }
     return;
   }
   case scUDivExpr: {
@@ -249,11 +259,9 @@
     return cast<SCEVUnknown>(this)->getType();
   case scCouldNotCompute:
     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
-    return 0;
-  default: break;
-  }
-  llvm_unreachable("Unknown SCEV kind!");
-  return 0;
+  default:
+    llvm_unreachable("Unknown SCEV kind!");
+  }
 }
=20
 bool SCEV::isZero() const {
@@ -274,6 +282,20 @@
   return false;
 }
=20
+/// isNonConstantNegative - Return true if the specified scev is negated, =
but
+/// not a constant.
+bool SCEV::isNonConstantNegative() const {
+  const SCEVMulExpr *Mul =3D dyn_cast<SCEVMulExpr>(this);
+  if (!Mul) return false;
+
+  // If there is a constant factor, it will be first.
+  const SCEVConstant *SC =3D dyn_cast<SCEVConstant>(Mul->getOperand(0));
+  if (!SC) return false;
+
+  // Return true if the value is negative, this matches things like (-42 *=
 V).
+  return SC->getValue()->getValue().isNegative();
+}
+
 SCEVCouldNotCompute::SCEVCouldNotCompute() :
   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
=20
@@ -587,11 +609,8 @@
       }
=20
       default:
-        break;
+        llvm_unreachable("Unknown SCEV kind!");
       }
-
-      llvm_unreachable("Unknown SCEV kind!");
-      return 0;
     }
   };
 }
@@ -2581,7 +2600,7 @@
=20
   Constant *C =3D ConstantExpr::getSizeOf(AllocTy);
   if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(C))
-    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD))
+    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD, TLI))
       C =3D Folded;
   Type *Ty =3D getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
   return getTruncateOrZeroExtend(getSCEV(C), Ty);
@@ -2590,7 +2609,7 @@
 const SCEV *ScalarEvolution::getAlignOfExpr(Type *AllocTy) {
   Constant *C =3D ConstantExpr::getAlignOf(AllocTy);
   if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(C))
-    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD))
+    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD, TLI))
       C =3D Folded;
   Type *Ty =3D getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
   return getTruncateOrZeroExtend(getSCEV(C), Ty);
@@ -2607,7 +2626,7 @@
=20
   Constant *C =3D ConstantExpr::getOffsetOf(STy, FieldNo);
   if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(C))
-    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD))
+    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD, TLI))
       C =3D Folded;
   Type *Ty =3D getEffectiveSCEVType(PointerType::getUnqual(STy));
   return getTruncateOrZeroExtend(getSCEV(C), Ty);
@@ -2617,7 +2636,7 @@
                                              Constant *FieldNo) {
   Constant *C =3D ConstantExpr::getOffsetOf(CTy, FieldNo);
   if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(C))
-    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD))
+    if (Constant *Folded =3D ConstantFoldConstantExpression(CE, TD, TLI))
       C =3D Folded;
   Type *Ty =3D getEffectiveSCEVType(PointerType::getUnqual(CTy));
   return getTruncateOrZeroExtend(getSCEV(C), Ty);
@@ -3108,7 +3127,7 @@
   // PHI's incoming blocks are in a different loop, in which case doing so
   // risks breaking LCSSA form. Instcombine would normally zap these, but
   // it doesn't have DominatorTree information, so it may miss cases.
-  if (Value *V =3D SimplifyInstruction(PN, TD, DT))
+  if (Value *V =3D SimplifyInstruction(PN, TD, TLI, DT))
     if (LI->replacementPreservesLCSSAForm(PN, V))
       return getSCEV(V);
=20
@@ -3168,7 +3187,7 @@
=20
   // Add the total offset from all the GEP indices to the base.
   return getAddExpr(BaseS, TotalOffset,
-                    isInBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap);
+                    isInBounds ? SCEV::FlagNUW : SCEV::FlagAnyWrap);
 }
=20
 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S=
 is
@@ -3242,9 +3261,8 @@
   if (const SCEVUnknown *U =3D dyn_cast<SCEVUnknown>(S)) {
     // For a SCEVUnknown, ask ValueTracking.
     unsigned BitWidth =3D getTypeSizeInBits(U->getType());
-    APInt Mask =3D APInt::getAllOnesValue(BitWidth);
     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
-    ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
+    ComputeMaskedBits(U->getValue(), Zeros, Ones);
     return Zeros.countTrailingOnes();
   }
=20
@@ -3382,9 +3400,8 @@
=20
   if (const SCEVUnknown *U =3D dyn_cast<SCEVUnknown>(S)) {
     // For a SCEVUnknown, ask ValueTracking.
-    APInt Mask =3D APInt::getAllOnesValue(BitWidth);
     APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
-    ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
+    ComputeMaskedBits(U->getValue(), Zeros, Ones, TD);
     if (Ones =3D=3D ~Zeros + 1)
       return setUnsignedRange(U, ConservativeResult);
     return setUnsignedRange(U,
@@ -3584,6 +3601,12 @@
     // because it leads to N-1 getAddExpr calls for N ultimate operands.
     // Instead, gather up all the operands and make a single getAddExpr ca=
ll.
     // LLVM IR canonical form means we need only traverse the left operand=
s.
+    //
+    // Don't apply this instruction's NSW or NUW flags to the new
+    // expression. The instruction may be guarded by control flow that the
+    // no-wrap behavior depends on. Non-control-equivalent instructions ca=
n be
+    // mapped to the same SCEV expression, and it would be incorrect to tr=
ansfer
+    // NSW/NUW semantics to those operations.
     SmallVector<const SCEV *, 4> AddOps;
     AddOps.push_back(getSCEV(U->getOperand(1)));
     for (Value *Op =3D U->getOperand(0); ; Op =3D U->getOperand(0)) {
@@ -3598,16 +3621,10 @@
         AddOps.push_back(Op1);
     }
     AddOps.push_back(getSCEV(U->getOperand(0)));
-    SCEV::NoWrapFlags Flags =3D SCEV::FlagAnyWrap;
-    OverflowingBinaryOperator *OBO =3D cast<OverflowingBinaryOperator>(V);
-    if (OBO->hasNoSignedWrap())
-      setFlags(Flags, SCEV::FlagNSW);
-    if (OBO->hasNoUnsignedWrap())
-      setFlags(Flags, SCEV::FlagNUW);
-    return getAddExpr(AddOps, Flags);
+    return getAddExpr(AddOps);
   }
   case Instruction::Mul: {
-    // See the Add code above.
+    // Don't transfer NSW/NUW for the same reason as AddExpr.
     SmallVector<const SCEV *, 4> MulOps;
     MulOps.push_back(getSCEV(U->getOperand(1)));
     for (Value *Op =3D U->getOperand(0);
@@ -3641,9 +3658,8 @@
       // knew about to reconstruct a low-bits mask value.
       unsigned LZ =3D A.countLeadingZeros();
       unsigned BitWidth =3D A.getBitWidth();
-      APInt AllOnes =3D APInt::getAllOnesValue(BitWidth);
       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-      ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD=
);
+      ComputeMaskedBits(U->getOperand(0), KnownZero, KnownOne, TD);
=20
       APInt EffectiveMask =3D APInt::getLowBitsSet(BitWidth, BitWidth - LZ=
);
=20
@@ -3915,13 +3931,19 @@
 //
=20
 /// getSmallConstantTripCount - Returns the maximum trip count of this loo=
p as a
-/// normal unsigned value, if possible. Returns 0 if the trip count is unk=
nown
-/// or not constant. Will also return 0 if the maximum trip count is very =
large
-/// (>=3D 2^32)
-unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
-                                                    BasicBlock *ExitBlock)=
 {
+/// normal unsigned value. Returns 0 if the trip count is unknown or not
+/// constant. Will also return 0 if the maximum trip count is very large (=
>=3D
+/// 2^32).
+///
+/// This "trip count" assumes that control exits via ExitingBlock. More
+/// precisely, it is the number of times that control may reach ExitingBlo=
ck
+/// before taking the branch. For loops with multiple exits, it may not be=
 the
+/// number times that the loop header executes because the loop may exit
+/// prematurely via another branch.
+unsigned ScalarEvolution::
+getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock) {
   const SCEVConstant *ExitCount =3D
-    dyn_cast<SCEVConstant>(getExitCount(L, ExitBlock));
+    dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
   if (!ExitCount)
     return 0;
=20
@@ -3944,9 +3966,12 @@
 /// multiple of a constant (which is also the case if the trip count is si=
mply
 /// constant, use getSmallConstantTripCount for that case), Will also retu=
rn 1
 /// if the trip count is very large (>=3D 2^32).
-unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
-                                                       BasicBlock *ExitBlo=
ck) {
-  const SCEV *ExitCount =3D getExitCount(L, ExitBlock);
+///
+/// As explained in the comments for getSmallConstantTripCount, this assum=
es
+/// that control exits the loop via ExitingBlock.
+unsigned ScalarEvolution::
+getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock) {
+  const SCEV *ExitCount =3D getExitCount(L, ExitingBlock);
   if (ExitCount =3D=3D getCouldNotCompute())
     return 1;
=20
@@ -4153,13 +4178,19 @@
 }
=20
 /// getExact - Get the exact loop backedge taken count considering all loop
-/// exits. If all exits are computable, this is the minimum computed count.
+/// exits. A computable result can only be return for loops with a single =
exit.
+/// Returning the minimum taken count among all exits is incorrect because=
 one
+/// of the loop's exit limit's may have been skipped. HowFarToZero assumes=
 that
+/// the limit of each loop test is never skipped. This is a valid assumpti=
on as
+/// long as the loop exits via that test. For precise results, it is the
+/// caller's responsibility to specify the relevant loop exit using
+/// getExact(ExitingBlock, SE).
 const SCEV *
 ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
   // If any exits were not computable, the loop is not computable.
   if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
=20
-  // We need at least one computable exit.
+  // We need exactly one computable exit.
   if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
   assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
=20
@@ -4171,8 +4202,8 @@
=20
     if (!BECount)
       BECount =3D ENT->ExactNotTaken;
-    else
-      BECount =3D SE->getUMinFromMismatchedTypes(BECount, ENT->ExactNotTak=
en);
+    else if (BECount !=3D ENT->ExactNotTaken)
+      return SE->getCouldNotCompute();
   }
   assert(BECount && "Invalid not taken count for loop exit");
   return BECount;
@@ -4253,8 +4284,15 @@
=20
     if (MaxBECount =3D=3D getCouldNotCompute())
       MaxBECount =3D EL.Max;
-    else if (EL.Max !=3D getCouldNotCompute())
-      MaxBECount =3D getUMinFromMismatchedTypes(MaxBECount, EL.Max);
+    else if (EL.Max !=3D getCouldNotCompute()) {
+      // We cannot take the "min" MaxBECount, because non-unit stride loop=
s may
+      // skip some loop tests. Taking the max over the exits is sufficient=
ly
+      // conservative.  TODO: We could do better taking into consideration
+      // that (1) the loop has unit stride (2) the last loop test is
+      // less-than/greater-than (3) any loop test is less-than/greater-tha=
n AND
+      // falls-through some constant times less then the other tests.
+      MaxBECount =3D getUMaxFromMismatchedTypes(MaxBECount, EL.Max);
+    }
   }
=20
   return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
@@ -4539,40 +4577,6 @@
   return cast<SCEVConstant>(Val)->getValue();
 }
=20
-/// GetAddressedElementFromGlobal - Given a global variable with an initia=
lizer
-/// and a GEP expression (missing the pointer index) indexing into it, ret=
urn
-/// the addressed element of the initializer or null if the index expressi=
on is
-/// invalid.
-static Constant *
-GetAddressedElementFromGlobal(GlobalVariable *GV,
-                              const std::vector<ConstantInt*> &Indices) {
-  Constant *Init =3D GV->getInitializer();
-  for (unsigned i =3D 0, e =3D Indices.size(); i !=3D e; ++i) {
-    uint64_t Idx =3D Indices[i]->getZExtValue();
-    if (ConstantStruct *CS =3D dyn_cast<ConstantStruct>(Init)) {
-      assert(Idx < CS->getNumOperands() && "Bad struct index!");
-      Init =3D cast<Constant>(CS->getOperand(Idx));
-    } else if (ConstantArray *CA =3D dyn_cast<ConstantArray>(Init)) {
-      if (Idx >=3D CA->getNumOperands()) return 0;  // Bogus program
-      Init =3D cast<Constant>(CA->getOperand(Idx));
-    } else if (isa<ConstantAggregateZero>(Init)) {
-      if (StructType *STy =3D dyn_cast<StructType>(Init->getType())) {
-        assert(Idx < STy->getNumElements() && "Bad struct index!");
-        Init =3D Constant::getNullValue(STy->getElementType(Idx));
-      } else if (ArrayType *ATy =3D dyn_cast<ArrayType>(Init->getType())) {
-        if (Idx >=3D ATy->getNumElements()) return 0;  // Bogus program
-        Init =3D Constant::getNullValue(ATy->getElementType());
-      } else {
-        llvm_unreachable("Unknown constant aggregate type!");
-      }
-      return 0;
-    } else {
-      return 0; // Unknown initializer type
-    }
-  }
-  return Init;
-}
-
 /// ComputeLoadConstantCompareExitLimit - Given an exit condition of
 /// 'icmp op load X, cst', try to see if we can compute the backedge
 /// execution count.
@@ -4600,7 +4604,7 @@
=20
   // Okay, we allow one non-constant index into the GEP instruction.
   Value *VarIdx =3D 0;
-  std::vector<ConstantInt*> Indexes;
+  std::vector<Constant*> Indexes;
   unsigned VarIdxNum =3D 0;
   for (unsigned i =3D 2, e =3D GEP->getNumOperands(); i !=3D e; ++i)
     if (ConstantInt *CI =3D dyn_cast<ConstantInt>(GEP->getOperand(i))) {
@@ -4612,6 +4616,10 @@
       Indexes.push_back(0);
     }
=20
+  // Loop-invariant loads may be a byproduct of loop optimization. Skip th=
em.
+  if (!VarIdx)
+    return getCouldNotCompute();
+
   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a const=
ant.
   // Check to see if X is a loop variant variable value now.
   const SCEV *Idx =3D getSCEV(VarIdx);
@@ -4634,7 +4642,8 @@
     // Form the GEP offset.
     Indexes[VarIdxNum] =3D Val;
=20
-    Constant *Result =3D GetAddressedElementFromGlobal(GV, Indexes);
+    Constant *Result =3D ConstantFoldLoadThroughGEPIndices(GV->getInitiali=
zer(),
+                                                         Indexes);
     if (Result =3D=3D 0) break;  // Cannot compute!
=20
     // Evaluate the condition for this iteration.
@@ -4658,7 +4667,8 @@
 /// specified type, assuming that all operands were constants.
 static bool CanConstantFold(const Instruction *I) {
   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
-      isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
+      isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) =
||
+      isa<LoadInst>(I))
     return true;
=20
   if (const CallInst *CI =3D dyn_cast<CallInst>(I))
@@ -4748,16 +4758,23 @@
 /// reason, return null.
 static Constant *EvaluateExpression(Value *V, const Loop *L,
                                     DenseMap<Instruction *, Constant *> &V=
als,
-                                    const TargetData *TD) {
+                                    const TargetData *TD,
+                                    const TargetLibraryInfo *TLI) {
   // Convenient constant check, but redundant for recursive calls.
   if (Constant *C =3D dyn_cast<Constant>(V)) return C;
-
-  Instruction *I =3D cast<Instruction>(V);
+  Instruction *I =3D dyn_cast<Instruction>(V);
+  if (!I) return 0;
+
   if (Constant *C =3D Vals.lookup(I)) return C;
=20
-  assert(!isa<PHINode>(I) && "loop header phis should be mapped to constan=
t");
-  assert(canConstantEvolve(I, L) && "cannot evaluate expression in this lo=
op");
-  (void)L;
+  // An instruction inside the loop depends on a value outside the loop th=
at we
+  // weren't given a mapping for, or a value such as a call inside the loo=
p.
+  if (!canConstantEvolve(I, L)) return 0;
+
+  // An unmapped PHI can be due to a branch or another loop inside this lo=
op,
+  // or due to this not being the initial iteration through a loop where we
+  // couldn't compute the evolution of this particular PHI last time.
+  if (isa<PHINode>(I)) return 0;
=20
   std::vector<Constant*> Operands(I->getNumOperands());
=20
@@ -4768,16 +4785,21 @@
       if (!Operands[i]) return 0;
       continue;
     }
-    Constant *C =3D EvaluateExpression(Operand, L, Vals, TD);
+    Constant *C =3D EvaluateExpression(Operand, L, Vals, TD, TLI);
     Vals[Operand] =3D C;
     if (!C) return 0;
     Operands[i] =3D C;
   }
=20
-  if (const CmpInst *CI =3D dyn_cast<CmpInst>(I))
+  if (CmpInst *CI =3D dyn_cast<CmpInst>(I))
     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
-                                           Operands[1], TD);
-  return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, =
TD);
+                                           Operands[1], TD, TLI);
+  if (LoadInst *LI =3D dyn_cast<LoadInst>(I)) {
+    if (!LI->isVolatile())
+      return ConstantFoldLoadFromConstPtr(Operands[0], TD);
+  }
+  return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, =
TD,
+                                  TLI);
 }
=20
 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi =
is
@@ -4798,23 +4820,26 @@
=20
   Constant *&RetVal =3D ConstantEvolutionLoopExitValue[PN];
=20
-  // FIXME: Nick's fix for PR11034 will seed constants for multiple header=
 phis.
   DenseMap<Instruction *, Constant *> CurrentIterVals;
+  BasicBlock *Header =3D L->getHeader();
+  assert(PN->getParent() =3D=3D Header && "Can't evaluate PHI not in loop =
header!");
=20
   // Since the loop is canonicalized, the PHI node must have two entries. =
 One
   // entry must be a constant (coming in from outside of the loop), and the
   // second must be derived from the same PHI.
   bool SecondIsBackedge =3D L->contains(PN->getIncomingBlock(1));
-  Constant *StartCST =3D
-    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
-  if (StartCST =3D=3D 0)
-    return RetVal =3D 0;  // Must be a constant.
-  CurrentIterVals[PN] =3D StartCST;
+  PHINode *PHI =3D 0;
+  for (BasicBlock::iterator I =3D Header->begin();
+       (PHI =3D dyn_cast<PHINode>(I)); ++I) {
+    Constant *StartCST =3D
+      dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
+    if (StartCST =3D=3D 0) continue;
+    CurrentIterVals[PHI] =3D StartCST;
+  }
+  if (!CurrentIterVals.count(PN))
+    return RetVal =3D 0;
=20
   Value *BEValue =3D PN->getIncomingValue(SecondIsBackedge);
-  if (getConstantEvolvingPHI(BEValue, L) !=3D PN &&
-      !isa<Constant>(BEValue))
-    return RetVal =3D 0;  // Not derived from same PHI.
=20
   // Execute the loop symbolically to determine the exit value.
   if (BEs.getActiveBits() >=3D 32)
@@ -4826,15 +4851,46 @@
     if (IterationNum =3D=3D NumIterations)
       return RetVal =3D CurrentIterVals[PN];  // Got exit value!
=20
-    // Compute the value of the PHI node for the next iteration.
+    // Compute the value of the PHIs for the next iteration.
     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
-    Constant *NextPHI =3D EvaluateExpression(BEValue, L, CurrentIterVals, =
TD);
-    if (NextPHI =3D=3D CurrentIterVals[PN])
-      return RetVal =3D NextPHI;  // Stopped evolving!
+    DenseMap<Instruction *, Constant *> NextIterVals;
+    Constant *NextPHI =3D EvaluateExpression(BEValue, L, CurrentIterVals, =
TD,
+                                           TLI);
     if (NextPHI =3D=3D 0)
       return 0;        // Couldn't evaluate!
-    DenseMap<Instruction *, Constant *> NextIterVals;
     NextIterVals[PN] =3D NextPHI;
+
+    bool StoppedEvolving =3D NextPHI =3D=3D CurrentIterVals[PN];
+
+    // Also evaluate the other PHI nodes.  However, we don't get to stop i=
f we
+    // cease to be able to evaluate one of them or if they stop evolving,
+    // because that doesn't necessarily prevent us from computing PN.
+    SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
+    for (DenseMap<Instruction *, Constant *>::const_iterator
+           I =3D CurrentIterVals.begin(), E =3D CurrentIterVals.end(); I !=
=3D E; ++I){
+      PHINode *PHI =3D dyn_cast<PHINode>(I->first);
+      if (!PHI || PHI =3D=3D PN || PHI->getParent() !=3D Header) continue;
+      PHIsToCompute.push_back(std::make_pair(PHI, I->second));
+    }
+    // We use two distinct loops because EvaluateExpression may invalidate=
 any
+    // iterators into CurrentIterVals.
+    for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
+             I =3D PHIsToCompute.begin(), E =3D PHIsToCompute.end(); I !=
=3D E; ++I) {
+      PHINode *PHI =3D I->first;
+      Constant *&NextPHI =3D NextIterVals[PHI];
+      if (!NextPHI) {   // Not already computed.
+        Value *BEValue =3D PHI->getIncomingValue(SecondIsBackedge);
+        NextPHI =3D EvaluateExpression(BEValue, L, CurrentIterVals, TD, TL=
I);
+      }
+      if (NextPHI !=3D I->second)
+        StoppedEvolving =3D false;
+    }
+
+    // If all entries in CurrentIterVals =3D=3D NextIterVals then we can s=
top
+    // iterating, the loop can't continue to change.
+    if (StoppedEvolving)
+      return RetVal =3D CurrentIterVals[PN];
+
     CurrentIterVals.swap(NextIterVals);
   }
 }
@@ -4844,9 +4900,9 @@
 /// try to evaluate a few iterations of the loop until we get the exit
 /// condition gets a value of ExitWhen (true or false).  If we cannot
 /// evaluate the trip count of the loop, return getCouldNotCompute().
-const SCEV * ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
-                                                           Value *Cond,
-                                                           bool ExitWhen) {
+const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
+                                                          Value *Cond,
+                                                          bool ExitWhen) {
   PHINode *PN =3D getConstantEvolvingPHI(Cond, L);
   if (PN =3D=3D 0) return getCouldNotCompute();
=20
@@ -4854,29 +4910,33 @@
   // That's the only form we support here.
   if (PN->getNumIncomingValues() !=3D 2) return getCouldNotCompute();
=20
+  DenseMap<Instruction *, Constant *> CurrentIterVals;
+  BasicBlock *Header =3D L->getHeader();
+  assert(PN->getParent() =3D=3D Header && "Can't evaluate PHI not in loop =
header!");
+
   // One entry must be a constant (coming in from outside of the loop), an=
d the
   // second must be derived from the same PHI.
   bool SecondIsBackedge =3D L->contains(PN->getIncomingBlock(1));
-  Constant *StartCST =3D
-    dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
-  if (StartCST =3D=3D 0) return getCouldNotCompute();  // Must be a consta=
nt.
-
-  Value *BEValue =3D PN->getIncomingValue(SecondIsBackedge);
-  if (getConstantEvolvingPHI(BEValue, L) !=3D PN &&
-      !isa<Constant>(BEValue))
-    return getCouldNotCompute();  // Not derived from same PHI.
+  PHINode *PHI =3D 0;
+  for (BasicBlock::iterator I =3D Header->begin();
+       (PHI =3D dyn_cast<PHINode>(I)); ++I) {
+    Constant *StartCST =3D
+      dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
+    if (StartCST =3D=3D 0) continue;
+    CurrentIterVals[PHI] =3D StartCST;
+  }
+  if (!CurrentIterVals.count(PN))
+    return getCouldNotCompute();
=20
   // Okay, we find a PHI node that defines the trip count of this loop.  E=
xecute
   // the loop symbolically to determine when the condition gets a value of
   // "ExitWhen".
-  unsigned IterationNum =3D 0;
+
   unsigned MaxIterations =3D MaxBruteForceIterations;   // Limit analysis.
-  for (Constant *PHIVal =3D StartCST;
-       IterationNum !=3D MaxIterations; ++IterationNum) {
-    DenseMap<Instruction *, Constant *> PHIValMap;
-    PHIValMap[PN] =3D PHIVal;
+  for (unsigned IterationNum =3D 0; IterationNum !=3D MaxIterations;++Iter=
ationNum){
     ConstantInt *CondVal =3D
-      dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, PHIValMap,=
 TD));
+      dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIte=
rVals,
+                                                       TD, TLI));
=20
     // Couldn't symbolically evaluate.
     if (!CondVal) return getCouldNotCompute();
@@ -4886,11 +4946,29 @@
       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
     }
=20
-    // Compute the value of the PHI node for the next iteration.
-    Constant *NextPHI =3D EvaluateExpression(BEValue, L, PHIValMap, TD);
-    if (NextPHI =3D=3D 0 || NextPHI =3D=3D PHIVal)
-      return getCouldNotCompute();// Couldn't evaluate or not making progr=
ess...
-    PHIVal =3D NextPHI;
+    // Update all the PHI nodes for the next iteration.
+    DenseMap<Instruction *, Constant *> NextIterVals;
+
+    // Create a list of which PHIs we need to compute. We want to do this =
before
+    // calling EvaluateExpression on them because that may invalidate iter=
ators
+    // into CurrentIterVals.
+    SmallVector<PHINode *, 8> PHIsToCompute;
+    for (DenseMap<Instruction *, Constant *>::const_iterator
+           I =3D CurrentIterVals.begin(), E =3D CurrentIterVals.end(); I !=
=3D E; ++I){
+      PHINode *PHI =3D dyn_cast<PHINode>(I->first);
+      if (!PHI || PHI->getParent() !=3D Header) continue;
+      PHIsToCompute.push_back(PHI);
+    }
+    for (SmallVectorImpl<PHINode *>::const_iterator I =3D PHIsToCompute.be=
gin(),
+             E =3D PHIsToCompute.end(); I !=3D E; ++I) {
+      PHINode *PHI =3D *I;
+      Constant *&NextPHI =3D NextIterVals[PHI];
+      if (NextPHI) continue;    // Already computed!
+
+      Value *BEValue =3D PHI->getIncomingValue(SecondIsBackedge);
+      NextPHI =3D EvaluateExpression(BEValue, L, CurrentIterVals, TD, TLI);
+    }
+    CurrentIterVals.swap(NextIterVals);
   }
=20
   // Too many iterations were needed to evaluate.
@@ -4921,6 +4999,98 @@
   return C;
 }
=20
+/// This builds up a Constant using the ConstantExpr interface.  That way,=
 we
+/// will return Constants for objects which aren't represented by a
+/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
+/// Returns NULL if the SCEV isn't representable as a Constant.
+static Constant *BuildConstantFromSCEV(const SCEV *V) {
+  switch (V->getSCEVType()) {
+    default:  // TODO: smax, umax.
+    case scCouldNotCompute:
+    case scAddRecExpr:
+      break;
+    case scConstant:
+      return cast<SCEVConstant>(V)->getValue();
+    case scUnknown:
+      return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
+    case scSignExtend: {
+      const SCEVSignExtendExpr *SS =3D cast<SCEVSignExtendExpr>(V);
+      if (Constant *CastOp =3D BuildConstantFromSCEV(SS->getOperand()))
+        return ConstantExpr::getSExt(CastOp, SS->getType());
+      break;
+    }
+    case scZeroExtend: {
+      const SCEVZeroExtendExpr *SZ =3D cast<SCEVZeroExtendExpr>(V);
+      if (Constant *CastOp =3D BuildConstantFromSCEV(SZ->getOperand()))
+        return ConstantExpr::getZExt(CastOp, SZ->getType());
+      break;
+    }
+    case scTruncate: {
+      const SCEVTruncateExpr *ST =3D cast<SCEVTruncateExpr>(V);
+      if (Constant *CastOp =3D BuildConstantFromSCEV(ST->getOperand()))
+        return ConstantExpr::getTrunc(CastOp, ST->getType());
+      break;
+    }
+    case scAddExpr: {
+      const SCEVAddExpr *SA =3D cast<SCEVAddExpr>(V);
+      if (Constant *C =3D BuildConstantFromSCEV(SA->getOperand(0))) {
+        if (C->getType()->isPointerTy())
+          C =3D ConstantExpr::getBitCast(C, Type::getInt8PtrTy(C->getConte=
xt()));
+        for (unsigned i =3D 1, e =3D SA->getNumOperands(); i !=3D e; ++i) {
+          Constant *C2 =3D BuildConstantFromSCEV(SA->getOperand(i));
+          if (!C2) return 0;
+
+          // First pointer!
+          if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()=
) {
+            std::swap(C, C2);
+            // The offsets have been converted to bytes.  We can add bytes=
 to an
+            // i8* by GEP with the byte count in the first index.
+            C =3D ConstantExpr::getBitCast(C,Type::getInt8PtrTy(C->getCont=
ext()));
+          }
+
+          // Don't bother trying to sum two pointers. We probably can't
+          // statically compute a load that results from it anyway.
+          if (C2->getType()->isPointerTy())
+            return 0;
+
+          if (C->getType()->isPointerTy()) {
+            if (cast<PointerType>(C->getType())->getElementType()->isStruc=
tTy())
+              C2 =3D ConstantExpr::getIntegerCast(
+                  C2, Type::getInt32Ty(C->getContext()), true);
+            C =3D ConstantExpr::getGetElementPtr(C, C2);
+          } else
+            C =3D ConstantExpr::getAdd(C, C2);
+        }
+        return C;
+      }
+      break;
+    }
+    case scMulExpr: {
+      const SCEVMulExpr *SM =3D cast<SCEVMulExpr>(V);
+      if (Constant *C =3D BuildConstantFromSCEV(SM->getOperand(0))) {
+        // Don't bother with pointers at all.
+        if (C->getType()->isPointerTy()) return 0;
+        for (unsigned i =3D 1, e =3D SM->getNumOperands(); i !=3D e; ++i) {
+          Constant *C2 =3D BuildConstantFromSCEV(SM->getOperand(i));
+          if (!C2 || C2->getType()->isPointerTy()) return 0;
+          C =3D ConstantExpr::getMul(C, C2);
+        }
+        return C;
+      }
+      break;
+    }
+    case scUDivExpr: {
+      const SCEVUDivExpr *SU =3D cast<SCEVUDivExpr>(V);
+      if (Constant *LHS =3D BuildConstantFromSCEV(SU->getLHS()))
+        if (Constant *RHS =3D BuildConstantFromSCEV(SU->getRHS()))
+          if (LHS->getType() =3D=3D RHS->getType())
+            return ConstantExpr::getUDiv(LHS, RHS);
+      break;
+    }
+  }
+  return 0;
+}
+
 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop =
*L) {
   if (isa<SCEVConstant>(V)) return V;
=20
@@ -4973,11 +5143,7 @@
           const SCEV *OpV =3D getSCEVAtScope(OrigV, L);
           MadeImprovement |=3D OrigV !=3D OpV;
=20
-          Constant *C =3D 0;
-          if (const SCEVConstant *SC =3D dyn_cast<SCEVConstant>(OpV))
-            C =3D SC->getValue();
-          if (const SCEVUnknown *SU =3D dyn_cast<SCEVUnknown>(OpV))
-            C =3D dyn_cast<Constant>(SU->getValue());
+          Constant *C =3D BuildConstantFromSCEV(OpV);
           if (!C) return V;
           if (C->getType() !=3D Op->getType())
             C =3D ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
@@ -4992,10 +5158,14 @@
           Constant *C =3D 0;
           if (const CmpInst *CI =3D dyn_cast<CmpInst>(I))
             C =3D ConstantFoldCompareInstOperands(CI->getPredicate(),
-                                                Operands[0], Operands[1], =
TD);
-          else
+                                                Operands[0], Operands[1], =
TD,
+                                                TLI);
+          else if (const LoadInst *LI =3D dyn_cast<LoadInst>(I)) {
+            if (!LI->isVolatile())
+              C =3D ConstantFoldLoadFromConstPtr(Operands[0], TD);
+          } else
             C =3D ConstantFoldInstOperands(I->getOpcode(), I->getType(),
-                                         Operands, TD);
+                                         Operands, TD, TLI);
           if (!C) return V;
           return getSCEV(C);
         }
@@ -5113,7 +5283,6 @@
   }
=20
   llvm_unreachable("Unknown SCEV type!");
-  return 0;
 }
=20
 /// getSCEVAtScope - This is a convenience function which does
@@ -5350,10 +5519,10 @@
   // behavior. Loops must exhibit defined behavior until a wrapped value is
   // actually used. So the trip count computed by udiv could be smaller th=
an the
   // number of well-defined iterations.
-  if (AddRec->getNoWrapFlags(SCEV::FlagNW))
+  if (AddRec->getNoWrapFlags(SCEV::FlagNW)) {
     // FIXME: We really want an "isexact" bit for udiv.
     return getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
-
+  }
   // Then, try to solve the above equation provided that Start is constant.
   if (const SCEVConstant *StartC =3D dyn_cast<SCEVConstant>(Start))
     return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
@@ -5744,7 +5913,6 @@
   switch (Pred) {
   default:
     llvm_unreachable("Unexpected ICmpInst::Predicate value!");
-    break;
   case ICmpInst::ICMP_SGT:
     Pred =3D ICmpInst::ICMP_SLT;
     std::swap(LHS, RHS);
@@ -6089,8 +6257,9 @@
     return getCouldNotCompute();
=20
   // Check to see if we have a flag which makes analysis easy.
-  bool NoWrap =3D isSigned ? AddRec->getNoWrapFlags(SCEV::FlagNSW) :
-                           AddRec->getNoWrapFlags(SCEV::FlagNUW);
+  bool NoWrap =3D isSigned ?
+    AddRec->getNoWrapFlags((SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagN=
W)) :
+    AddRec->getNoWrapFlags((SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagN=
W));
=20
   if (AddRec->isAffine()) {
     unsigned BitWidth =3D getTypeSizeInBits(AddRec->getType());
@@ -6381,6 +6550,7 @@
   this->F =3D &F;
   LI =3D &getAnalysis<LoopInfo>();
   TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
   DT =3D &getAnalysis<DominatorTree>();
   return false;
 }
@@ -6417,6 +6587,7 @@
   AU.setPreservesAll();
   AU.addRequiredTransitive<LoopInfo>();
   AU.addRequiredTransitive<DominatorTree>();
+  AU.addRequired<TargetLibraryInfo>();
 }
=20
 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
@@ -6592,11 +6763,8 @@
     return LoopInvariant;
   case scCouldNotCompute:
     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
-    return LoopVariant;
-  default: break;
-  }
-  llvm_unreachable("Unknown SCEV kind!");
-  return LoopVariant;
+  default: llvm_unreachable("Unknown SCEV kind!");
+  }
 }
=20
 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
@@ -6678,11 +6846,9 @@
     return ProperlyDominatesBlock;
   case scCouldNotCompute:
     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
-    return DoesNotDominateBlock;
-  default: break;
-  }
-  llvm_unreachable("Unknown SCEV kind!");
-  return DoesNotDominateBlock;
+  default:
+    llvm_unreachable("Unknown SCEV kind!");
+  }
 }
=20
 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
@@ -6728,11 +6894,9 @@
     return false;
   case scCouldNotCompute:
     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
-    return false;
-  default: break;
-  }
-  llvm_unreachable("Unknown SCEV kind!");
-  return false;
+  default:
+    llvm_unreachable("Unknown SCEV kind!");
+  }
 }
=20
 void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/ScalarE=
volutionExpander.cpp
--- a/head/contrib/llvm/lib/Analysis/ScalarEvolutionExpander.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ScalarEvolutionExpander.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "llvm/LLVMContext.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLowering.h"
 #include "llvm/ADT/STLExtras.h"
=20
 using namespace llvm;
@@ -30,6 +31,19 @@
 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
                                        Instruction::CastOps Op,
                                        BasicBlock::iterator IP) {
+  // This function must be called with the builder having a valid insertion
+  // point. It doesn't need to be the actual IP where the uses of the retu=
rned
+  // cast will be added, but it must dominate such IP.
+  // We use this precondition to produce a cast that will dominate all its
+  // uses. In particular, this is crucial for the case where the builder's
+  // insertion point *is* the point where we were asked to put the cast.
+  // Since we don't know the the builder's insertion point is actually
+  // where the uses will be added (only that it dominates it), we are
+  // not allowed to move it.
+  BasicBlock::iterator BIP =3D Builder.GetInsertPoint();
+
+  Instruction *Ret =3D NULL;
+
   // Check to see if there is already a cast!
   for (Value::use_iterator UI =3D V->use_begin(), E =3D V->use_end();
        UI !=3D E; ++UI) {
@@ -37,27 +51,35 @@
     if (U->getType() =3D=3D Ty)
       if (CastInst *CI =3D dyn_cast<CastInst>(U))
         if (CI->getOpcode() =3D=3D Op) {
-          // If the cast isn't where we want it, fix it.
-          if (BasicBlock::iterator(CI) !=3D IP) {
+          // If the cast isn't where we want it, create a new cast at IP.
+          // Likewise, do not reuse a cast at BIP because it must dominate
+          // instructions that might be inserted before BIP.
+          if (BasicBlock::iterator(CI) !=3D IP || BIP =3D=3D IP) {
             // Create a new cast, and leave the old cast in place in case
             // it is being used as an insert point. Clear its operand
             // so that it doesn't hold anything live.
-            Instruction *NewCI =3D CastInst::Create(Op, V, Ty, "", IP);
-            NewCI->takeName(CI);
-            CI->replaceAllUsesWith(NewCI);
+            Ret =3D CastInst::Create(Op, V, Ty, "", IP);
+            Ret->takeName(CI);
+            CI->replaceAllUsesWith(Ret);
             CI->setOperand(0, UndefValue::get(V->getType()));
-            rememberInstruction(NewCI);
-            return NewCI;
+            break;
           }
-          rememberInstruction(CI);
-          return CI;
+          Ret =3D CI;
+          break;
         }
   }
=20
   // Create a new cast.
-  Instruction *I =3D CastInst::Create(Op, V, Ty, V->getName(), IP);
-  rememberInstruction(I);
-  return I;
+  if (!Ret)
+    Ret =3D CastInst::Create(Op, V, Ty, V->getName(), IP);
+
+  // We assert at the end of the function since IP might point to an
+  // instruction with different dominance properties than a cast
+  // (an invoke for example) and not dominate BIP (but the cast does).
+  assert(SE.DT->dominates(Ret, BIP));
+
+  rememberInstruction(Ret);
+  return Ret;
 }
=20
 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
@@ -73,9 +95,14 @@
          "InsertNoopCastOfTo cannot change sizes!");
=20
   // Short-circuit unnecessary bitcasts.
-  if (Op =3D=3D Instruction::BitCast && V->getType() =3D=3D Ty)
-    return V;
-
+  if (Op =3D=3D Instruction::BitCast) {
+    if (V->getType() =3D=3D Ty)
+      return V;
+    if (CastInst *CI =3D dyn_cast<CastInst>(V)) {
+      if (CI->getOperand(0)->getType() =3D=3D Ty)
+        return CI->getOperand(0);
+    }
+  }
   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
   if ((Op =3D=3D Instruction::PtrToInt || Op =3D=3D Instruction::IntToPtr)=
 &&
       SE.getTypeSizeInBits(Ty) =3D=3D SE.getTypeSizeInBits(V->getType())) {
@@ -115,8 +142,7 @@
   BasicBlock::iterator IP =3D I; ++IP;
   if (InvokeInst *II =3D dyn_cast<InvokeInst>(I))
     IP =3D II->getNormalDest()->begin();
-  while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP) ||
-         isa<LandingPadInst>(IP))
+  while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
     ++IP;
   return ReuseOrCreateCast(I, Ty, Op, IP);
 }
@@ -492,6 +518,9 @@
     V =3D InsertNoopCastOfTo(V,
        Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
=20
+    assert(!isa<Instruction>(V) ||
+           SE.DT->dominates(cast<Instruction>(V), Builder.GetInsertPoint()=
));
+
     // Expand the operands for a plain byte offset.
     Value *Idx =3D expandCodeFor(SE.getAddExpr(Ops), Ty);
=20
@@ -588,20 +617,6 @@
   return expand(SE.getAddExpr(Ops));
 }
=20
-/// isNonConstantNegative - Return true if the specified scev is negated, =
but
-/// not a constant.
-static bool isNonConstantNegative(const SCEV *F) {
-  const SCEVMulExpr *Mul =3D dyn_cast<SCEVMulExpr>(F);
-  if (!Mul) return false;
-
-  // If there is a constant factor, it will be first.
-  const SCEVConstant *SC =3D dyn_cast<SCEVConstant>(Mul->getOperand(0));
-  if (!SC) return false;
-
-  // Return true if the value is negative, this matches things like (-42 *=
 V).
-  return SC->getValue()->getValue().isNegative();
-}
-
 /// PickMostRelevantLoop - Given two loops pick the one that's most releva=
nt for
 /// SCEV expansion. If they are nested, this is the most nested. If they a=
re
 /// neighboring, pick the later.
@@ -655,7 +670,6 @@
     return RelevantLoops[D] =3D Result;
   }
   llvm_unreachable("Unexpected SCEV type!");
-  return 0;
 }
=20
 namespace {
@@ -680,10 +694,10 @@
     // If one operand is a non-constant negative and the other is not,
     // put the non-constant negative on the right so that a sub can
     // be used instead of a negate and add.
-    if (isNonConstantNegative(LHS.second)) {
-      if (!isNonConstantNegative(RHS.second))
+    if (LHS.second->isNonConstantNegative()) {
+      if (!RHS.second->isNonConstantNegative())
         return false;
-    } else if (isNonConstantNegative(RHS.second))
+    } else if (RHS.second->isNonConstantNegative())
       return true;
=20
     // Otherwise they are equivalent according to this comparison.
@@ -744,7 +758,7 @@
       for (++I; I !=3D E && I->first =3D=3D CurLoop; ++I)
         NewOps.push_back(I->second);
       Sum =3D expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand=
(Op));
-    } else if (isNonConstantNegative(Op)) {
+    } else if (Op->isNonConstantNegative()) {
       // Instead of doing a negate and add, just do a subtract.
       Value *W =3D expandCodeFor(SE.getNegativeSCEV(Op), Ty);
       Sum =3D InsertNoopCastOfTo(Sum, Ty);
@@ -875,6 +889,94 @@
   return isNormalAddRecExprPHI(PN, IncV, L);
 }
=20
+/// getIVIncOperand returns an induction variable increment's induction
+/// variable operand.
+///
+/// If allowScale is set, any type of GEP is allowed as long as the nonIV
+/// operands dominate InsertPos.
+///
+/// If allowScale is not set, ensure that a GEP increment conforms to one =
of the
+/// simple patterns generated by getAddRecExprPHILiterally and
+/// expandAddtoGEP. If the pattern isn't recognized, return NULL.
+Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
+                                           Instruction *InsertPos,
+                                           bool allowScale) {
+  if (IncV =3D=3D InsertPos)
+    return NULL;
+
+  switch (IncV->getOpcode()) {
+  default:
+    return NULL;
+  // Check for a simple Add/Sub or GEP of a loop invariant step.
+  case Instruction::Add:
+  case Instruction::Sub: {
+    Instruction *OInst =3D dyn_cast<Instruction>(IncV->getOperand(1));
+    if (!OInst || SE.DT->dominates(OInst, InsertPos))
+      return dyn_cast<Instruction>(IncV->getOperand(0));
+    return NULL;
+  }
+  case Instruction::BitCast:
+    return dyn_cast<Instruction>(IncV->getOperand(0));
+  case Instruction::GetElementPtr:
+    for (Instruction::op_iterator I =3D IncV->op_begin()+1, E =3D IncV->op=
_end();
+         I !=3D E; ++I) {
+      if (isa<Constant>(*I))
+        continue;
+      if (Instruction *OInst =3D dyn_cast<Instruction>(*I)) {
+        if (!SE.DT->dominates(OInst, InsertPos))
+          return NULL;
+      }
+      if (allowScale) {
+        // allow any kind of GEP as long as it can be hoisted.
+        continue;
+      }
+      // This must be a pointer addition of constants (pretty), which is a=
lready
+      // handled, or some number of address-size elements (ugly). Ugly geps
+      // have 2 operands. i1* is used by the expander to represent an
+      // address-size element.
+      if (IncV->getNumOperands() !=3D 2)
+        return NULL;
+      unsigned AS =3D cast<PointerType>(IncV->getType())->getAddressSpace(=
);
+      if (IncV->getType() !=3D Type::getInt1PtrTy(SE.getContext(), AS)
+          && IncV->getType() !=3D Type::getInt8PtrTy(SE.getContext(), AS))
+        return NULL;
+      break;
+    }
+    return dyn_cast<Instruction>(IncV->getOperand(0));
+  }
+}
+
+/// hoistStep - Attempt to hoist a simple IV increment above InsertPos to =
make
+/// it available to other uses in this loop. Recursively hoist any operand=
s,
+/// until we reach a value that dominates InsertPos.
+bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
+  if (SE.DT->dominates(IncV, InsertPos))
+      return true;
+
+  // InsertPos must itself dominate IncV so that IncV's new position satis=
fies
+  // its existing users.
+  if (!SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
+    return false;
+
+  // Check that the chain of IV operands leading back to Phi can be hoiste=
d.
+  SmallVector<Instruction*, 4> IVIncs;
+  for(;;) {
+    Instruction *Oper =3D getIVIncOperand(IncV, InsertPos, /*allowScale*/t=
rue);
+    if (!Oper)
+      return false;
+    // IncV is safe to hoist.
+    IVIncs.push_back(IncV);
+    IncV =3D Oper;
+    if (SE.DT->dominates(IncV, InsertPos))
+      break;
+  }
+  for (SmallVectorImpl<Instruction*>::reverse_iterator I =3D IVIncs.rbegin=
(),
+         E =3D IVIncs.rend(); I !=3D E; ++I) {
+    (*I)->moveBefore(InsertPos);
+  }
+  return true;
+}
+
 /// Determine if this cyclic phi is in a form that would have been generat=
ed by
 /// LSR. We don't care if the phi was actually expanded in this pass, as l=
ong
 /// as it is in a low-cost form, for example, no implied multiplication. T=
his
@@ -882,51 +984,43 @@
 /// expandAddtoGEP.
 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
                                            const Loop *L) {
-  switch (IncV->getOpcode()) {
-  // Check for a simple Add/Sub or GEP of a loop invariant step.
-  case Instruction::Add:
-  case Instruction::Sub:
-    return IncV->getOperand(0) =3D=3D PN
-      && L->isLoopInvariant(IncV->getOperand(1));
-  case Instruction::BitCast:
-    IncV =3D dyn_cast<GetElementPtrInst>(IncV->getOperand(0));
-    if (!IncV)
-      return false;
-    // fall-thru to GEP handling
-  case Instruction::GetElementPtr: {
-    // This must be a pointer addition of constants (pretty) or some numbe=
r of
-    // address-size elements (ugly).
-    for (Instruction::op_iterator I =3D IncV->op_begin()+1, E =3D IncV->op=
_end();
-         I !=3D E; ++I) {
-      if (isa<Constant>(*I))
-        continue;
-      // ugly geps have 2 operands.
-      // i1* is used by the expander to represent an address-size element.
-      if (IncV->getNumOperands() !=3D 2)
-        return false;
-      unsigned AS =3D cast<PointerType>(IncV->getType())->getAddressSpace(=
);
-      if (IncV->getType() !=3D Type::getInt1PtrTy(SE.getContext(), AS)
-          && IncV->getType() !=3D Type::getInt8PtrTy(SE.getContext(), AS))
-        return false;
-      // Ensure the operands dominate the insertion point. I don't know of=
 a
-      // case when this would not be true, so this is somewhat untested.
-      if (L =3D=3D IVIncInsertLoop) {
-        for (User::op_iterator OI =3D IncV->op_begin()+1,
-               OE =3D IncV->op_end(); OI !=3D OE; ++OI)
-          if (Instruction *OInst =3D dyn_cast<Instruction>(OI))
-            if (!SE.DT->dominates(OInst, IVIncInsertPos))
-              return false;
-      }
-      break;
+  for(Instruction *IVOper =3D IncV;
+      (IVOper =3D getIVIncOperand(IVOper, L->getLoopPreheader()->getTermin=
ator(),
+                                /*allowScale=3D*/false));) {
+    if (IVOper =3D=3D PN)
+      return true;
+  }
+  return false;
+}
+
+/// expandIVInc - Expand an IV increment at Builder's current InsertPos.
+/// Typically this is the LatchBlock terminator or IVIncInsertPos, but we =
may
+/// need to materialize IV increments elsewhere to handle difficult situat=
ions.
+Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
+                                 Type *ExpandTy, Type *IntTy,
+                                 bool useSubtract) {
+  Value *IncV;
+  // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
+  if (ExpandTy->isPointerTy()) {
+    PointerType *GEPPtrTy =3D cast<PointerType>(ExpandTy);
+    // If the step isn't constant, don't use an implicitly scaled GEP, bec=
ause
+    // that would require a multiply inside the loop.
+    if (!isa<ConstantInt>(StepV))
+      GEPPtrTy =3D PointerType::get(Type::getInt1Ty(SE.getContext()),
+                                  GEPPtrTy->getAddressSpace());
+    const SCEV *const StepArray[1] =3D { SE.getSCEV(StepV) };
+    IncV =3D expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
+    if (IncV->getType() !=3D PN->getType()) {
+      IncV =3D Builder.CreateBitCast(IncV, PN->getType());
+      rememberInstruction(IncV);
     }
-    IncV =3D dyn_cast<Instruction>(IncV->getOperand(0));
-    if (IncV && IncV->getOpcode() =3D=3D Instruction::BitCast)
-      IncV =3D dyn_cast<Instruction>(IncV->getOperand(0));
-    return IncV =3D=3D PN;
+  } else {
+    IncV =3D useSubtract ?
+      Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
+      Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
+    rememberInstruction(IncV);
   }
-  default:
-    return false;
-  }
+  return IncV;
 }
=20
 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expa=
nd
@@ -956,26 +1050,28 @@
       if (LSRMode) {
         if (!isExpandedAddRecExprPHI(PN, IncV, L))
           continue;
+        if (L =3D=3D IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
+          continue;
       }
       else {
         if (!isNormalAddRecExprPHI(PN, IncV, L))
           continue;
+        if (L =3D=3D IVIncInsertLoop)
+          do {
+            if (SE.DT->dominates(IncV, IVIncInsertPos))
+              break;
+            // Make sure the increment is where we want it. But don't move=
 it
+            // down past a potential existing post-inc user.
+            IncV->moveBefore(IVIncInsertPos);
+            IVIncInsertPos =3D IncV;
+            IncV =3D cast<Instruction>(IncV->getOperand(0));
+          } while (IncV !=3D PN);
       }
       // Ok, the add recurrence looks usable.
       // Remember this PHI, even in post-inc mode.
       InsertedValues.insert(PN);
       // Remember the increment.
       rememberInstruction(IncV);
-      if (L =3D=3D IVIncInsertLoop)
-        do {
-          if (SE.DT->dominates(IncV, IVIncInsertPos))
-            break;
-          // Make sure the increment is where we want it. But don't move it
-          // down past a potential existing post-inc user.
-          IncV->moveBefore(IVIncInsertPos);
-          IVIncInsertPos =3D IncV;
-          IncV =3D cast<Instruction>(IncV->getOperand(0));
-        } while (IncV !=3D PN);
       return PN;
     }
   }
@@ -984,6 +1080,16 @@
   BasicBlock *SaveInsertBB =3D Builder.GetInsertBlock();
   BasicBlock::iterator SaveInsertPt =3D Builder.GetInsertPoint();
=20
+  // Another AddRec may need to be recursively expanded below. For example=
, if
+  // this AddRec is quadratic, the StepV may itself be an AddRec in this
+  // loop. Remove this loop from the PostIncLoops set before expanding such
+  // AddRecs. Otherwise, we cannot find a valid position for the step
+  // (i.e. StepV can never dominate its loop header).  Ideally, we could do
+  // SavedIncLoops.swap(PostIncLoops), but we generally have a single elem=
ent,
+  // so it's not worth implementing SmallPtrSet::swap.
+  PostIncLoopSet SavedPostIncLoops =3D PostIncLoops;
+  PostIncLoops.clear();
+
   // Expand code for the start value.
   Value *StartV =3D expandCodeFor(Normalized->getStart(), ExpandTy,
                                 L->getHeader()->begin());
@@ -993,16 +1099,16 @@
          SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
                                   L->getHeader()));
=20
-  // Expand code for the step value. Insert instructions right before the
-  // terminator corresponding to the back-edge. Do this before creating th=
e PHI
-  // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
-  // negative, insert a sub instead of an add for the increment (unless it=
's a
-  // constant, because subtracts of constants are canonicalized to adds).
+  // Expand code for the step value. Do this before creating the PHI so th=
at PHI
+  // reuse code doesn't see an incomplete PHI.
   const SCEV *Step =3D Normalized->getStepRecurrence(SE);
-  bool isPointer =3D ExpandTy->isPointerTy();
-  bool isNegative =3D !isPointer && isNonConstantNegative(Step);
-  if (isNegative)
+  // If the stride is negative, insert a sub instead of an add for the inc=
rement
+  // (unless it's a constant, because subtracts of constants are canonical=
ized
+  // to adds).
+  bool useSubtract =3D !ExpandTy->isPointerTy() && Step->isNonConstantNega=
tive();
+  if (useSubtract)
     Step =3D SE.getNegativeSCEV(Step);
+  // Expand the step somewhere that dominates the loop header.
   Value *StepV =3D expandCodeFor(Step, IntTy, L->getHeader()->begin());
=20
   // Create the PHI.
@@ -1023,33 +1129,14 @@
       continue;
     }
=20
-    // Create a step value and add it to the PHI. If IVIncInsertLoop is
-    // non-null and equal to the addrec's loop, insert the instructions
-    // at IVIncInsertPos.
+    // Create a step value and add it to the PHI.
+    // If IVIncInsertLoop is non-null and equal to the addrec's loop, inse=
rt the
+    // instructions at IVIncInsertPos.
     Instruction *InsertPos =3D L =3D=3D IVIncInsertLoop ?
       IVIncInsertPos : Pred->getTerminator();
     Builder.SetInsertPoint(InsertPos);
-    Value *IncV;
-    // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
-    if (isPointer) {
-      PointerType *GEPPtrTy =3D cast<PointerType>(ExpandTy);
-      // If the step isn't constant, don't use an implicitly scaled GEP, b=
ecause
-      // that would require a multiply inside the loop.
-      if (!isa<ConstantInt>(StepV))
-        GEPPtrTy =3D PointerType::get(Type::getInt1Ty(SE.getContext()),
-                                    GEPPtrTy->getAddressSpace());
-      const SCEV *const StepArray[1] =3D { SE.getSCEV(StepV) };
-      IncV =3D expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
-      if (IncV->getType() !=3D PN->getType()) {
-        IncV =3D Builder.CreateBitCast(IncV, PN->getType());
-        rememberInstruction(IncV);
-      }
-    } else {
-      IncV =3D isNegative ?
-        Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
-        Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
-      rememberInstruction(IncV);
-    }
+    Value *IncV =3D expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract=
);
+
     PN->addIncoming(IncV, Pred);
   }
=20
@@ -1057,6 +1144,10 @@
   if (SaveInsertBB)
     restoreInsertPoint(SaveInsertBB, SaveInsertPt);
=20
+  // After expanding subexpressions, restore the PostIncLoops set so the c=
aller
+  // can ensure that IVIncrement dominates the current uses.
+  PostIncLoops =3D SavedPostIncLoops;
+
   // Remember this PHI, even in post-inc mode.
   InsertedValues.insert(PN);
=20
@@ -1124,10 +1215,31 @@
     // For an expansion to use the postinc form, the client must call
     // expandCodeFor with an InsertPoint that is either outside the PostIn=
cLoop
     // or dominated by IVIncInsertPos.
-    assert((!isa<Instruction>(Result) ||
-            SE.DT->dominates(cast<Instruction>(Result),
-                             Builder.GetInsertPoint())) &&
-           "postinc expansion does not dominate use");
+    if (isa<Instruction>(Result)
+        && !SE.DT->dominates(cast<Instruction>(Result),
+                             Builder.GetInsertPoint())) {
+      // The induction variable's postinc expansion does not dominate this=
 use.
+      // IVUsers tries to prevent this case, so it is rare. However, it can
+      // happen when an IVUser outside the loop is not dominated by the la=
tch
+      // block. Adjusting IVIncInsertPos before expansion begins cannot ha=
ndle
+      // all cases. Consider a phi outide whose operand is replaced during
+      // expansion with the value of the postinc user. Without fundamental=
ly
+      // changing the way postinc users are tracked, the only remedy is
+      // inserting an extra IV increment. StepV might fold into PostLoopOf=
fset,
+      // but hopefully expandCodeFor handles that.
+      bool useSubtract =3D
+        !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
+      if (useSubtract)
+        Step =3D SE.getNegativeSCEV(Step);
+      // Expand the step somewhere that dominates the loop header.
+      BasicBlock *SaveInsertBB =3D Builder.GetInsertBlock();
+      BasicBlock::iterator SaveInsertPt =3D Builder.GetInsertPoint();
+      Value *StepV =3D expandCodeFor(Step, IntTy, L->getHeader()->begin());
+      // Restore the insertion point to the place where the caller has
+      // determined dominates all uses.
+      restoreInsertPoint(SaveInsertBB, SaveInsertPt);
+      Result =3D expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
+    }
   }
=20
   // Re-apply any non-loop-dominating scale.
@@ -1363,10 +1475,7 @@
 }
=20
 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
-                                   Instruction *I) {
-  BasicBlock::iterator IP =3D I;
-  while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
-    ++IP;
+                                   Instruction *IP) {
   Builder.SetInsertPoint(IP->getParent(), IP);
   return expandCodeFor(SH, Ty);
 }
@@ -1392,14 +1501,23 @@
       if (!L) break;
       if (BasicBlock *Preheader =3D L->getLoopPreheader())
         InsertPt =3D Preheader->getTerminator();
+      else {
+        // LSR sets the insertion point for AddRec start/step values to the
+        // block start to simplify value reuse, even though it's an invalid
+        // position. SCEVExpander must correct for this in all cases.
+        InsertPt =3D L->getHeader()->getFirstInsertionPt();
+      }
     } else {
       // If the SCEV is computable at this level, insert it into the header
       // after the PHIs (and after any other instructions that we've inser=
ted
       // there) so that it is guaranteed to dominate any user inside the l=
oop.
       if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(=
L))
         InsertPt =3D L->getHeader()->getFirstInsertionPt();
-      while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(Inse=
rtPt))
+      while (InsertPt !=3D Builder.GetInsertPoint()
+             && (isInsertedInstruction(InsertPt)
+                 || isa<DbgInfoIntrinsic>(InsertPt))) {
         InsertPt =3D llvm::next(BasicBlock::iterator(InsertPt));
+      }
       break;
     }
=20
@@ -1434,23 +1552,9 @@
     InsertedPostIncValues.insert(I);
   else
     InsertedValues.insert(I);
-
-  // If we just claimed an existing instruction and that instruction had
-  // been the insert point, adjust the insert point forward so that
-  // subsequently inserted code will be dominated.
-  if (Builder.GetInsertPoint() =3D=3D I) {
-    BasicBlock::iterator It =3D cast<Instruction>(I);
-    do { ++It; } while (isInsertedInstruction(It) ||
-                        isa<DbgInfoIntrinsic>(It));
-    Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
-  }
 }
=20
 void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator=
 I) {
-  // If we acquired more instructions since the old insert point was saved,
-  // advance past them.
-  while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
-
   Builder.SetInsertPoint(BB, I);
 }
=20
@@ -1478,40 +1582,13 @@
   return V;
 }
=20
-/// hoistStep - Attempt to hoist an IV increment above a potential use.
-///
-/// To successfully hoist, two criteria must be met:
-/// - IncV operands dominate InsertPos and
-/// - InsertPos dominates IncV
-///
-/// Meeting the second condition means that we don't need to check all of =
IncV's
-/// existing uses (it's moving up in the domtree).
-///
-/// This does not yet recursively hoist the operands, although that would
-/// not be difficult.
-///
-/// This does not require a SCEVExpander instance and could be replaced by=
 a
-/// general code-insertion helper.
-bool SCEVExpander::hoistStep(Instruction *IncV, Instruction *InsertPos,
-                             const DominatorTree *DT) {
-  if (DT->dominates(IncV, InsertPos))
-    return true;
-
-  if (!DT->dominates(InsertPos->getParent(), IncV->getParent()))
-    return false;
-
-  if (IncV->mayHaveSideEffects())
-    return false;
-
-  // Attempt to hoist IncV
-  for (User::op_iterator OI =3D IncV->op_begin(), OE =3D IncV->op_end();
-       OI !=3D OE; ++OI) {
-    Instruction *OInst =3D dyn_cast<Instruction>(OI);
-    if (OInst && !DT->dominates(OInst, InsertPos))
-      return false;
-  }
-  IncV->moveBefore(InsertPos);
-  return true;
+/// Sort values by integer width for replaceCongruentIVs.
+static bool width_descending(Value *lhs, Value *rhs) {
+  // Put pointers at the back and make sure pointer < pointer =3D false.
+  if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
+    return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
+  return rhs->getType()->getPrimitiveSizeInBits()
+    < lhs->getType()->getPrimitiveSizeInBits();
 }
=20
 /// replaceCongruentIVs - Check for congruent phis in this loop header and
@@ -1521,23 +1598,45 @@
 /// This does not depend on any SCEVExpander state but should be used in
 /// the same context that SCEVExpander is used.
 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *D=
T,
-                                           SmallVectorImpl<WeakVH> &DeadIn=
sts) {
+                                           SmallVectorImpl<WeakVH> &DeadIn=
sts,
+                                           const TargetLowering *TLI) {
+  // Find integer phis in order of increasing width.
+  SmallVector<PHINode*, 8> Phis;
+  for (BasicBlock::iterator I =3D L->getHeader()->begin();
+       PHINode *Phi =3D dyn_cast<PHINode>(I); ++I) {
+    Phis.push_back(Phi);
+  }
+  if (TLI)
+    std::sort(Phis.begin(), Phis.end(), width_descending);
+
   unsigned NumElim =3D 0;
   DenseMap<const SCEV *, PHINode *> ExprToIVMap;
-  for (BasicBlock::iterator I =3D L->getHeader()->begin(); isa<PHINode>(I)=
; ++I) {
-    PHINode *Phi =3D cast<PHINode>(I);
+  // Process phis from wide to narrow. Mapping wide phis to the their trun=
cation
+  // so narrow phis can reuse them.
+  for (SmallVectorImpl<PHINode*>::const_iterator PIter =3D Phis.begin(),
+         PEnd =3D Phis.end(); PIter !=3D PEnd; ++PIter) {
+    PHINode *Phi =3D *PIter;
+
     if (!SE.isSCEVable(Phi->getType()))
       continue;
=20
     PHINode *&OrigPhiRef =3D ExprToIVMap[SE.getSCEV(Phi)];
     if (!OrigPhiRef) {
       OrigPhiRef =3D Phi;
+      if (Phi->getType()->isIntegerTy() && TLI
+          && TLI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
+        // This phi can be freely truncated to the narrowest phi type. Map=
 the
+        // truncated expression to it so it will be reused for narrow type=
s.
+        const SCEV *TruncExpr =3D
+          SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
+        ExprToIVMap[TruncExpr] =3D Phi;
+      }
       continue;
     }
=20
-    // If one phi derives from the other via GEPs, types may differ.
-    // We could consider adding a bitcast here to handle it.
-    if (OrigPhiRef->getType() !=3D Phi->getType())
+    // Replacing a pointer phi with an integer phi or vice-versa doesn't m=
ake
+    // sense.
+    if (OrigPhiRef->getType()->isPointerTy() !=3D Phi->getType()->isPointe=
rTy())
       continue;
=20
     if (BasicBlock *LatchBlock =3D L->getLoopLatch()) {
@@ -1546,32 +1645,56 @@
       Instruction *IsomorphicInc =3D
         cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
=20
-      // If this phi is more canonical, swap it with the original.
-      if (!isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)
-          && isExpandedAddRecExprPHI(Phi, IsomorphicInc, L)) {
+      // If this phi has the same width but is more canonical, replace the
+      // original with it. As part of the "more canonical" determination,
+      // respect a prior decision to use an IV chain.
+      if (OrigPhiRef->getType() =3D=3D Phi->getType()
+          && !(ChainedPhis.count(Phi)
+               || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
+          && (ChainedPhis.count(Phi)
+              || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
         std::swap(OrigPhiRef, Phi);
         std::swap(OrigInc, IsomorphicInc);
       }
       // Replacing the congruent phi is sufficient because acyclic redunda=
ncy
       // elimination, CSE/GVN, should handle the rest. However, once SCEV =
proves
       // that a phi is congruent, it's often the head of an IV user cycle =
that
-      // is isomorphic with the original phi. So it's worth eagerly cleani=
ng up
-      // the common case of a single IV increment.
-      if (OrigInc !=3D IsomorphicInc &&
-          OrigInc->getType() =3D=3D IsomorphicInc->getType() &&
-          SE.getSCEV(OrigInc) =3D=3D SE.getSCEV(IsomorphicInc) &&
-          hoistStep(OrigInc, IsomorphicInc, DT)) {
+      // is isomorphic with the original phi. It's worth eagerly cleaning =
up the
+      // common case of a single IV increment so that DeleteDeadPHIs can r=
emove
+      // cycles that had postinc uses.
+      const SCEV *TruncExpr =3D SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
+                                                   IsomorphicInc->getType(=
));
+      if (OrigInc !=3D IsomorphicInc
+          && TruncExpr =3D=3D SE.getSCEV(IsomorphicInc)
+          && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
+              || hoistIVInc(OrigInc, IsomorphicInc))) {
         DEBUG_WITH_TYPE(DebugType, dbgs()
                         << "INDVARS: Eliminated congruent iv.inc: "
                         << *IsomorphicInc << '\n');
-        IsomorphicInc->replaceAllUsesWith(OrigInc);
+        Value *NewInc =3D OrigInc;
+        if (OrigInc->getType() !=3D IsomorphicInc->getType()) {
+          Instruction *IP =3D isa<PHINode>(OrigInc)
+            ? (Instruction*)L->getHeader()->getFirstInsertionPt()
+            : OrigInc->getNextNode();
+          IRBuilder<> Builder(IP);
+          Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
+          NewInc =3D Builder.
+            CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName=
);
+        }
+        IsomorphicInc->replaceAllUsesWith(NewInc);
         DeadInsts.push_back(IsomorphicInc);
       }
     }
     DEBUG_WITH_TYPE(DebugType, dbgs()
                     << "INDVARS: Eliminated congruent iv: " << *Phi << '\n=
');
     ++NumElim;
-    Phi->replaceAllUsesWith(OrigPhiRef);
+    Value *NewIV =3D OrigPhiRef;
+    if (OrigPhiRef->getType() !=3D Phi->getType()) {
+      IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
+      Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
+      NewIV =3D Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), I=
VName);
+    }
+    Phi->replaceAllUsesWith(NewIV);
     DeadInsts.push_back(Phi);
   }
   return NumElim;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/ScalarE=
volutionNormalization.cpp
--- a/head/contrib/llvm/lib/Analysis/ScalarEvolutionNormalization.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ScalarEvolutionNormalization.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -118,7 +118,6 @@
     // Conservatively use AnyWrap until/unless we need FlagNW.
     const SCEV *Result =3D SE.getAddRecExpr(Operands, L, SCEV::FlagAnyWrap=
);
     switch (Kind) {
-    default: llvm_unreachable("Unexpected transform name!");
     case NormalizeAutodetect:
       if (IVUseShouldUsePostIncValue(User, OperandValToReplace, L, &DT)) {
         const SCEV *TransformedStep =3D
@@ -191,7 +190,6 @@
   }
=20
   llvm_unreachable("Unexpected SCEV kind!");
-  return 0;
 }
=20
 /// Manage recursive transformation across an expression DAG. Revisiting
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/SparseP=
ropagation.cpp
--- a/head/contrib/llvm/lib/Analysis/SparsePropagation.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/SparsePropagation.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -194,8 +194,8 @@
     Succs.assign(TI.getNumSuccessors(), true);
     return;
   }
- =20
-  Succs[SI.findCaseValue(cast<ConstantInt>(C))] =3D true;
+  SwitchInst::CaseIt Case =3D SI.findCaseValue(cast<ConstantInt>(C));
+  Succs[Case.getSuccessorIndex()] =3D true;
 }
=20
=20
@@ -327,13 +327,13 @@
 }
=20
 void SparseSolver::Print(Function &F, raw_ostream &OS) const {
-  OS << "\nFUNCTION: " << F.getNameStr() << "\n";
+  OS << "\nFUNCTION: " << F.getName() << "\n";
   for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB=
) {
     if (!BBExecutable.count(BB))
       OS << "INFEASIBLE: ";
     OS << "\t";
     if (BB->hasName())
-      OS << BB->getNameStr() << ":\n";
+      OS << BB->getName() << ":\n";
     else
       OS << "; anon bb\n";
     for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E=
; ++I) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/Trace.c=
pp
--- a/head/contrib/llvm/lib/Analysis/Trace.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Analysis/Trace.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -34,7 +34,7 @@
 ///
 void Trace::print(raw_ostream &O) const {
   Function *F =3D getFunction();
-  O << "; Trace from function " << F->getNameStr() << ", blocks:\n";
+  O << "; Trace from function " << F->getName() << ", blocks:\n";
   for (const_iterator i =3D begin(), e =3D end(); i !=3D e; ++i) {
     O << "; ";
     WriteAsOperand(O, *i, true, getModule());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Analysis/ValueTr=
acking.cpp
--- a/head/contrib/llvm/lib/Analysis/ValueTracking.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Analysis/ValueTracking.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -20,8 +20,10 @@
 #include "llvm/GlobalAlias.h"
 #include "llvm/IntrinsicInst.h"
 #include "llvm/LLVMContext.h"
+#include "llvm/Metadata.h"
 #include "llvm/Operator.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Support/ConstantRange.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/PatternMatch.h"
@@ -41,10 +43,176 @@
   return TD ? TD->getPointerSizeInBits() : 0;
 }
=20
-/// ComputeMaskedBits - Determine which of the bits specified in Mask are
-/// known to be either zero or one and return them in the KnownZero/KnownO=
ne
-/// bit sets.  This code only analyzes bits in Mask, in order to short-cir=
cuit
-/// processing.
+static void ComputeMaskedBitsAddSub(bool Add, Value *Op0, Value *Op1, bool=
 NSW,
+                                    APInt &KnownZero, APInt &KnownOne,
+                                    APInt &KnownZero2, APInt &KnownOne2,
+                                    const TargetData *TD, unsigned Depth) {
+  if (!Add) {
+    if (ConstantInt *CLHS =3D dyn_cast<ConstantInt>(Op0)) {
+      // We know that the top bits of C-X are clear if X contains less bits
+      // than C (i.e. no wrap-around can happen).  For example, 20-X is
+      // positive if we can prove that X is >=3D 0 and < 16.
+      if (!CLHS->getValue().isNegative()) {
+        unsigned BitWidth =3D KnownZero.getBitWidth();
+        unsigned NLZ =3D (CLHS->getValue()+1).countLeadingZeros();
+        // NLZ can't be BitWidth with no sign bit
+        APInt MaskV =3D APInt::getHighBitsSet(BitWidth, NLZ+1);
+        llvm::ComputeMaskedBits(Op1, KnownZero2, KnownOne2, TD, Depth+1);
+   =20
+        // If all of the MaskV bits are known to be zero, then we know the
+        // output top bits are zero, because we now know that the output is
+        // from [0-C].
+        if ((KnownZero2 & MaskV) =3D=3D MaskV) {
+          unsigned NLZ2 =3D CLHS->getValue().countLeadingZeros();
+          // Top bits known zero.
+          KnownZero =3D APInt::getHighBitsSet(BitWidth, NLZ2);
+        }
+      }
+    }
+  }
+
+  unsigned BitWidth =3D KnownZero.getBitWidth();
+
+  // If one of the operands has trailing zeros, then the bits that the
+  // other operand has in those bit positions will be preserved in the
+  // result. For an add, this works with either operand. For a subtract,
+  // this only works if the known zeros are in the right operand.
+  APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
+  llvm::ComputeMaskedBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1);
+  assert((LHSKnownZero & LHSKnownOne) =3D=3D 0 &&
+         "Bits known to be one AND zero?");
+  unsigned LHSKnownZeroOut =3D LHSKnownZero.countTrailingOnes();
+
+  llvm::ComputeMaskedBits(Op1, KnownZero2, KnownOne2, TD, Depth+1);
+  assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND ze=
ro?");=20
+  unsigned RHSKnownZeroOut =3D KnownZero2.countTrailingOnes();
+
+  // Determine which operand has more trailing zeros, and use that
+  // many bits from the other operand.
+  if (LHSKnownZeroOut > RHSKnownZeroOut) {
+    if (Add) {
+      APInt Mask =3D APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
+      KnownZero |=3D KnownZero2 & Mask;
+      KnownOne  |=3D KnownOne2 & Mask;
+    } else {
+      // If the known zeros are in the left operand for a subtract,
+      // fall back to the minimum known zeros in both operands.
+      KnownZero |=3D APInt::getLowBitsSet(BitWidth,
+                                        std::min(LHSKnownZeroOut,
+                                                 RHSKnownZeroOut));
+    }
+  } else if (RHSKnownZeroOut >=3D LHSKnownZeroOut) {
+    APInt Mask =3D APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
+    KnownZero |=3D LHSKnownZero & Mask;
+    KnownOne  |=3D LHSKnownOne & Mask;
+  }
+
+  // Are we still trying to solve for the sign bit?
+  if (!KnownZero.isNegative() && !KnownOne.isNegative()) {
+    if (NSW) {
+      if (Add) {
+        // Adding two positive numbers can't wrap into negative
+        if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
+          KnownZero |=3D APInt::getSignBit(BitWidth);
+        // and adding two negative numbers can't wrap into positive.
+        else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
+          KnownOne |=3D APInt::getSignBit(BitWidth);
+      } else {
+        // Subtracting a negative number from a positive one can't wrap
+        if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
+          KnownZero |=3D APInt::getSignBit(BitWidth);
+        // neither can subtracting a positive number from a negative one.
+        else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
+          KnownOne |=3D APInt::getSignBit(BitWidth);
+      }
+    }
+  }
+}
+
+static void ComputeMaskedBitsMul(Value *Op0, Value *Op1, bool NSW,
+                                 APInt &KnownZero, APInt &KnownOne,
+                                 APInt &KnownZero2, APInt &KnownOne2,
+                                 const TargetData *TD, unsigned Depth) {
+  unsigned BitWidth =3D KnownZero.getBitWidth();
+  ComputeMaskedBits(Op1, KnownZero, KnownOne, TD, Depth+1);
+  ComputeMaskedBits(Op0, KnownZero2, KnownOne2, TD, Depth+1);
+  assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND zero=
?");
+  assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
+
+  bool isKnownNegative =3D false;
+  bool isKnownNonNegative =3D false;
+  // If the multiplication is known not to overflow, compute the sign bit.
+  if (NSW) {
+    if (Op0 =3D=3D Op1) {
+      // The product of a number with itself is non-negative.
+      isKnownNonNegative =3D true;
+    } else {
+      bool isKnownNonNegativeOp1 =3D KnownZero.isNegative();
+      bool isKnownNonNegativeOp0 =3D KnownZero2.isNegative();
+      bool isKnownNegativeOp1 =3D KnownOne.isNegative();
+      bool isKnownNegativeOp0 =3D KnownOne2.isNegative();
+      // The product of two numbers with the same sign is non-negative.
+      isKnownNonNegative =3D (isKnownNegativeOp1 && isKnownNegativeOp0) ||
+        (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
+      // The product of a negative number and a non-negative number is eit=
her
+      // negative or zero.
+      if (!isKnownNonNegative)
+        isKnownNegative =3D (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
+                           isKnownNonZero(Op0, TD, Depth)) ||
+                          (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
+                           isKnownNonZero(Op1, TD, Depth));
+    }
+  }
+
+  // If low bits are zero in either operand, output low known-0 bits.
+  // Also compute a conserative estimate for high known-0 bits.
+  // More trickiness is possible, but this is sufficient for the
+  // interesting case of alignment computation.
+  KnownOne.clearAllBits();
+  unsigned TrailZ =3D KnownZero.countTrailingOnes() +
+                    KnownZero2.countTrailingOnes();
+  unsigned LeadZ =3D  std::max(KnownZero.countLeadingOnes() +
+                             KnownZero2.countLeadingOnes(),
+                             BitWidth) - BitWidth;
+
+  TrailZ =3D std::min(TrailZ, BitWidth);
+  LeadZ =3D std::min(LeadZ, BitWidth);
+  KnownZero =3D APInt::getLowBitsSet(BitWidth, TrailZ) |
+              APInt::getHighBitsSet(BitWidth, LeadZ);
+
+  // Only make use of no-wrap flags if we failed to compute the sign bit
+  // directly.  This matters if the multiplication always overflows, in
+  // which case we prefer to follow the result of the direct computation,
+  // though as the program is invoking undefined behaviour we can choose
+  // whatever we like here.
+  if (isKnownNonNegative && !KnownOne.isNegative())
+    KnownZero.setBit(BitWidth - 1);
+  else if (isKnownNegative && !KnownZero.isNegative())
+    KnownOne.setBit(BitWidth - 1);
+}
+
+void llvm::computeMaskedBitsLoad(const MDNode &Ranges, APInt &KnownZero) {
+  unsigned BitWidth =3D KnownZero.getBitWidth();
+  unsigned NumRanges =3D Ranges.getNumOperands() / 2;
+  assert(NumRanges >=3D 1);
+
+  // Use the high end of the ranges to find leading zeros.
+  unsigned MinLeadingZeros =3D BitWidth;
+  for (unsigned i =3D 0; i < NumRanges; ++i) {
+    ConstantInt *Lower =3D cast<ConstantInt>(Ranges.getOperand(2*i + 0));
+    ConstantInt *Upper =3D cast<ConstantInt>(Ranges.getOperand(2*i + 1));
+    ConstantRange Range(Lower->getValue(), Upper->getValue());
+    if (Range.isWrappedSet())
+      MinLeadingZeros =3D 0; // -1 has no zeros
+    unsigned LeadingZeros =3D (Upper->getValue() - 1).countLeadingZeros();
+    MinLeadingZeros =3D std::min(LeadingZeros, MinLeadingZeros);
+  }
+
+  KnownZero =3D APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
+}
+/// ComputeMaskedBits - Determine which of the bits are known to be either=
 zero
+/// or one and return them in the KnownZero/KnownOne bit sets.
+///
 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is =
that
 /// we cannot optimize based on the assumption that it is zero without cha=
nging
 /// it to be an explicit zero.  If we don't change it to zero, other code =
could
@@ -54,67 +222,75 @@
 ///
 /// This function is defined on values with integer type, values with poin=
ter
 /// type (but only if TD is non-null), and vectors of integers.  In the ca=
se
-/// where V is a vector, the mask, known zero, and known one values are the
+/// where V is a vector, known zero, and known one values are the
 /// same width as the vector element, and the bit is set only if it is true
 /// for all of the elements in the vector.
-void llvm::ComputeMaskedBits(Value *V, const APInt &Mask,
-                             APInt &KnownZero, APInt &KnownOne,
+void llvm::ComputeMaskedBits(Value *V, APInt &KnownZero, APInt &KnownOne,
                              const TargetData *TD, unsigned Depth) {
   assert(V && "No Value?");
   assert(Depth <=3D MaxDepth && "Limit Search Depth");
-  unsigned BitWidth =3D Mask.getBitWidth();
-  assert((V->getType()->isIntOrIntVectorTy() || V->getType()->isPointerTy(=
))
-         && "Not integer or pointer type!");
+  unsigned BitWidth =3D KnownZero.getBitWidth();
+
+  assert((V->getType()->isIntOrIntVectorTy() ||
+          V->getType()->getScalarType()->isPointerTy()) &&
+         "Not integer or pointer type!");
   assert((!TD ||
           TD->getTypeSizeInBits(V->getType()->getScalarType()) =3D=3D BitW=
idth) &&
          (!V->getType()->isIntOrIntVectorTy() ||
           V->getType()->getScalarSizeInBits() =3D=3D BitWidth) &&
-         KnownZero.getBitWidth() =3D=3D BitWidth &&=20
+         KnownZero.getBitWidth() =3D=3D BitWidth &&
          KnownOne.getBitWidth() =3D=3D BitWidth &&
          "V, Mask, KnownOne and KnownZero should have same BitWidth");
=20
   if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V)) {
     // We know all of the bits for a constant!
-    KnownOne =3D CI->getValue() & Mask;
-    KnownZero =3D ~KnownOne & Mask;
+    KnownOne =3D CI->getValue();
+    KnownZero =3D ~KnownOne;
     return;
   }
   // Null and aggregate-zero are all-zeros.
   if (isa<ConstantPointerNull>(V) ||
       isa<ConstantAggregateZero>(V)) {
     KnownOne.clearAllBits();
-    KnownZero =3D Mask;
+    KnownZero =3D APInt::getAllOnesValue(BitWidth);
     return;
   }
   // Handle a constant vector by taking the intersection of the known bits=
 of
-  // each element.
-  if (ConstantVector *CV =3D dyn_cast<ConstantVector>(V)) {
+  // each element.  There is no real need to handle ConstantVector here, b=
ecause
+  // we don't handle undef in any particularly useful way.
+  if (ConstantDataSequential *CDS =3D dyn_cast<ConstantDataSequential>(V))=
 {
+    // We know that CDS must be a vector of integers. Take the intersectio=
n of
+    // each element.
     KnownZero.setAllBits(); KnownOne.setAllBits();
-    for (unsigned i =3D 0, e =3D CV->getNumOperands(); i !=3D e; ++i) {
-      APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
-      ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2,
-                        TD, Depth);
-      KnownZero &=3D KnownZero2;
-      KnownOne &=3D KnownOne2;
+    APInt Elt(KnownZero.getBitWidth(), 0);
+    for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i) {
+      Elt =3D CDS->getElementAsInteger(i);
+      KnownZero &=3D ~Elt;
+      KnownOne &=3D Elt;     =20
     }
     return;
   }
+ =20
   // The address of an aligned GlobalValue has trailing zeros.
   if (GlobalValue *GV =3D dyn_cast<GlobalValue>(V)) {
     unsigned Align =3D GV->getAlignment();
-    if (Align =3D=3D 0 && TD && GV->getType()->getElementType()->isSized()=
) {
-      Type *ObjectType =3D GV->getType()->getElementType();
-      // If the object is defined in the current Module, we'll be giving
-      // it the preferred alignment. Otherwise, we have to assume that it
-      // may only have the minimum ABI alignment.
-      if (!GV->isDeclaration() && !GV->mayBeOverridden())
-        Align =3D TD->getPrefTypeAlignment(ObjectType);
-      else
-        Align =3D TD->getABITypeAlignment(ObjectType);
+    if (Align =3D=3D 0 && TD) {
+      if (GlobalVariable *GVar =3D dyn_cast<GlobalVariable>(GV)) {
+        Type *ObjectType =3D GVar->getType()->getElementType();
+        if (ObjectType->isSized()) {
+          // If the object is defined in the current Module, we'll be givi=
ng
+          // it the preferred alignment. Otherwise, we have to assume that=
 it
+          // may only have the minimum ABI alignment.
+          if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
+            Align =3D TD->getPreferredAlignment(GVar);
+          else
+            Align =3D TD->getABITypeAlignment(ObjectType);
+        }
+      }
     }
     if (Align > 0)
-      KnownZero =3D Mask & APInt::getLowBitsSet(BitWidth,
-                                              CountTrailingZeros_32(Align)=
);
+      KnownZero =3D APInt::getLowBitsSet(BitWidth,
+                                       CountTrailingZeros_32(Align));
     else
       KnownZero.clearAllBits();
     KnownOne.clearAllBits();
@@ -126,8 +302,7 @@
     if (GA->mayBeOverridden()) {
       KnownZero.clearAllBits(); KnownOne.clearAllBits();
     } else {
-      ComputeMaskedBits(GA->getAliasee(), Mask, KnownZero, KnownOne,
-                        TD, Depth+1);
+      ComputeMaskedBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1=
);
     }
     return;
   }
@@ -136,15 +311,15 @@
     // Get alignment information off byval arguments if specified in the I=
R.
     if (A->hasByValAttr())
       if (unsigned Align =3D A->getParamAlignment())
-        KnownZero =3D Mask & APInt::getLowBitsSet(BitWidth,
-                                                CountTrailingZeros_32(Alig=
n));
+        KnownZero =3D APInt::getLowBitsSet(BitWidth,
+                                         CountTrailingZeros_32(Align));
     return;
   }
=20
   // Start out not knowing anything.
   KnownZero.clearAllBits(); KnownOne.clearAllBits();
=20
-  if (Depth =3D=3D MaxDepth || Mask =3D=3D 0)
+  if (Depth =3D=3D MaxDepth)
     return;  // Limit search depth.
=20
   Operator *I =3D dyn_cast<Operator>(V);
@@ -153,12 +328,14 @@
   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
   switch (I->getOpcode()) {
   default: break;
+  case Instruction::Load:
+    if (MDNode *MD =3D cast<LoadInst>(I)->getMetadata(LLVMContext::MD_rang=
e))
+      computeMaskedBitsLoad(*MD, KnownZero);
+    return;
   case Instruction::And: {
     // If either the LHS or the RHS are Zero, the result is zero.
-    ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Dep=
th+1);
-    APInt Mask2(Mask & ~KnownZero);
-    ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
-                      Depth+1);
+    ComputeMaskedBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1=
);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");=20
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
    =20
@@ -169,10 +346,8 @@
     return;
   }
   case Instruction::Or: {
-    ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Dep=
th+1);
-    APInt Mask2(Mask & ~KnownOne);
-    ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
-                      Depth+1);
+    ComputeMaskedBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1=
);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");=20
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
    =20
@@ -183,9 +358,8 @@
     return;
   }
   case Instruction::Xor: {
-    ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Dep=
th+1);
-    ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD,
-                      Depth+1);
+    ComputeMaskedBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1=
);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");=20
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
    =20
@@ -197,55 +371,32 @@
     return;
   }
   case Instruction::Mul: {
-    APInt Mask2 =3D APInt::getAllOnesValue(BitWidth);
-    ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Dep=
th+1);
-    ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD,
-                      Depth+1);
-    assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");=20
-    assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
-   =20
-    // If low bits are zero in either operand, output low known-0 bits.
-    // Also compute a conserative estimate for high known-0 bits.
-    // More trickiness is possible, but this is sufficient for the
-    // interesting case of alignment computation.
-    KnownOne.clearAllBits();
-    unsigned TrailZ =3D KnownZero.countTrailingOnes() +
-                      KnownZero2.countTrailingOnes();
-    unsigned LeadZ =3D  std::max(KnownZero.countLeadingOnes() +
-                               KnownZero2.countLeadingOnes(),
-                               BitWidth) - BitWidth;
-
-    TrailZ =3D std::min(TrailZ, BitWidth);
-    LeadZ =3D std::min(LeadZ, BitWidth);
-    KnownZero =3D APInt::getLowBitsSet(BitWidth, TrailZ) |
-                APInt::getHighBitsSet(BitWidth, LeadZ);
-    KnownZero &=3D Mask;
-    return;
+    bool NSW =3D cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
+    ComputeMaskedBitsMul(I->getOperand(0), I->getOperand(1), NSW,
+                         KnownZero, KnownOne, KnownZero2, KnownOne2, TD, D=
epth);
+    break;
   }
   case Instruction::UDiv: {
     // For the purposes of computing leading zeros we can conservatively
     // treat a udiv as a logical right shift by the power of 2 known to
     // be less than the denominator.
-    APInt AllOnes =3D APInt::getAllOnesValue(BitWidth);
-    ComputeMaskedBits(I->getOperand(0),
-                      AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1=
);
     unsigned LeadZ =3D KnownZero2.countLeadingOnes();
=20
     KnownOne2.clearAllBits();
     KnownZero2.clearAllBits();
-    ComputeMaskedBits(I->getOperand(1),
-                      AllOnes, KnownZero2, KnownOne2, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1=
);
     unsigned RHSUnknownLeadingOnes =3D KnownOne2.countLeadingZeros();
     if (RHSUnknownLeadingOnes !=3D BitWidth)
       LeadZ =3D std::min(BitWidth,
                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
=20
-    KnownZero =3D APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
+    KnownZero =3D APInt::getHighBitsSet(BitWidth, LeadZ);
     return;
   }
   case Instruction::Select:
-    ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Dep=
th+1);
-    ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD,
+    ComputeMaskedBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(1), KnownZero2, KnownOne2, TD,
                       Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");=20
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
@@ -278,11 +429,9 @@
     else
       SrcBitWidth =3D SrcTy->getScalarSizeInBits();
    =20
-    APInt MaskIn =3D Mask.zextOrTrunc(SrcBitWidth);
     KnownZero =3D KnownZero.zextOrTrunc(SrcBitWidth);
     KnownOne =3D KnownOne.zextOrTrunc(SrcBitWidth);
-    ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
-                      Depth+1);
+    ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
     KnownZero =3D KnownZero.zextOrTrunc(BitWidth);
     KnownOne =3D KnownOne.zextOrTrunc(BitWidth);
     // Any top bits are known to be zero.
@@ -296,8 +445,7 @@
         // TODO: For now, not handling conversions like:
         // (bitcast i64 %x to <2 x i32>)
         !I->getType()->isVectorTy()) {
-      ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD,
-                        Depth+1);
+      ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1=
);
       return;
     }
     break;
@@ -306,11 +454,9 @@
     // Compute the bits in the result that are not present in the input.
     unsigned SrcBitWidth =3D I->getOperand(0)->getType()->getScalarSizeInB=
its();
      =20
-    APInt MaskIn =3D Mask.trunc(SrcBitWidth);
     KnownZero =3D KnownZero.trunc(SrcBitWidth);
     KnownOne =3D KnownOne.trunc(SrcBitWidth);
-    ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD,
-                      Depth+1);
+    ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");=20
     KnownZero =3D KnownZero.zext(BitWidth);
     KnownOne =3D KnownOne.zext(BitWidth);
@@ -327,9 +473,7 @@
     // (shl X, C1) & C2 =3D=3D 0   iff   (X & C2 >>u C1) =3D=3D 0
     if (ConstantInt *SA =3D dyn_cast<ConstantInt>(I->getOperand(1))) {
       uint64_t ShiftAmt =3D SA->getLimitedValue(BitWidth);
-      APInt Mask2(Mask.lshr(ShiftAmt));
-      ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
-                        Depth+1);
+      ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1=
);
       assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
       KnownZero <<=3D ShiftAmt;
       KnownOne  <<=3D ShiftAmt;
@@ -344,9 +488,7 @@
       uint64_t ShiftAmt =3D SA->getLimitedValue(BitWidth);
      =20
       // Unsigned shift right.
-      APInt Mask2(Mask.shl(ShiftAmt));
-      ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD,
-                        Depth+1);
+      ComputeMaskedBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1);
       assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
       KnownZero =3D APIntOps::lshr(KnownZero, ShiftAmt);
       KnownOne  =3D APIntOps::lshr(KnownOne, ShiftAmt);
@@ -362,9 +504,7 @@
       uint64_t ShiftAmt =3D SA->getLimitedValue(BitWidth-1);
      =20
       // Signed shift right.
-      APInt Mask2(Mask.shl(ShiftAmt));
-      ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
-                        Depth+1);
+      ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1=
);
       assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
       KnownZero =3D APIntOps::lshr(KnownZero, ShiftAmt);
       KnownOne  =3D APIntOps::lshr(KnownOne, ShiftAmt);
@@ -378,100 +518,25 @@
     }
     break;
   case Instruction::Sub: {
-    if (ConstantInt *CLHS =3D dyn_cast<ConstantInt>(I->getOperand(0))) {
-      // We know that the top bits of C-X are clear if X contains less bits
-      // than C (i.e. no wrap-around can happen).  For example, 20-X is
-      // positive if we can prove that X is >=3D 0 and < 16.
-      if (!CLHS->getValue().isNegative()) {
-        unsigned NLZ =3D (CLHS->getValue()+1).countLeadingZeros();
-        // NLZ can't be BitWidth with no sign bit
-        APInt MaskV =3D APInt::getHighBitsSet(BitWidth, NLZ+1);
-        ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
-                          TD, Depth+1);
-   =20
-        // If all of the MaskV bits are known to be zero, then we know the
-        // output top bits are zero, because we now know that the output is
-        // from [0-C].
-        if ((KnownZero2 & MaskV) =3D=3D MaskV) {
-          unsigned NLZ2 =3D CLHS->getValue().countLeadingZeros();
-          // Top bits known zero.
-          KnownZero =3D APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
-        }
-      }       =20
-    }
+    bool NSW =3D cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
+    ComputeMaskedBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
+                            KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
+                            Depth);
+    break;
   }
-  // fall through
   case Instruction::Add: {
-    // If one of the operands has trailing zeros, then the bits that the
-    // other operand has in those bit positions will be preserved in the
-    // result. For an add, this works with either operand. For a subtract,
-    // this only works if the known zeros are in the right operand.
-    APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
-    APInt Mask2 =3D APInt::getLowBitsSet(BitWidth,
-                                       BitWidth - Mask.countLeadingZeros()=
);
-    ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, =
TD,
-                      Depth+1);
-    assert((LHSKnownZero & LHSKnownOne) =3D=3D 0 &&
-           "Bits known to be one AND zero?");
-    unsigned LHSKnownZeroOut =3D LHSKnownZero.countTrailingOnes();
-
-    ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD,=20
-                      Depth+1);
-    assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");=20
-    unsigned RHSKnownZeroOut =3D KnownZero2.countTrailingOnes();
-
-    // Determine which operand has more trailing zeros, and use that
-    // many bits from the other operand.
-    if (LHSKnownZeroOut > RHSKnownZeroOut) {
-      if (I->getOpcode() =3D=3D Instruction::Add) {
-        APInt Mask =3D APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
-        KnownZero |=3D KnownZero2 & Mask;
-        KnownOne  |=3D KnownOne2 & Mask;
-      } else {
-        // If the known zeros are in the left operand for a subtract,
-        // fall back to the minimum known zeros in both operands.
-        KnownZero |=3D APInt::getLowBitsSet(BitWidth,
-                                          std::min(LHSKnownZeroOut,
-                                                   RHSKnownZeroOut));
-      }
-    } else if (RHSKnownZeroOut >=3D LHSKnownZeroOut) {
-      APInt Mask =3D APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
-      KnownZero |=3D LHSKnownZero & Mask;
-      KnownOne  |=3D LHSKnownOne & Mask;
-    }
-
-    // Are we still trying to solve for the sign bit?
-    if (Mask.isNegative() && !KnownZero.isNegative() && !KnownOne.isNegati=
ve()){
-      OverflowingBinaryOperator *OBO =3D cast<OverflowingBinaryOperator>(I=
);
-      if (OBO->hasNoSignedWrap()) {
-        if (I->getOpcode() =3D=3D Instruction::Add) {
-          // Adding two positive numbers can't wrap into negative
-          if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
-            KnownZero |=3D APInt::getSignBit(BitWidth);
-          // and adding two negative numbers can't wrap into positive.
-          else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
-            KnownOne |=3D APInt::getSignBit(BitWidth);
-        } else {
-          // Subtracting a negative number from a positive one can't wrap
-          if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
-            KnownZero |=3D APInt::getSignBit(BitWidth);
-          // neither can subtracting a positive number from a negative one.
-          else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
-            KnownOne |=3D APInt::getSignBit(BitWidth);
-        }
-      }
-    }
-
-    return;
+    bool NSW =3D cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
+    ComputeMaskedBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
+                            KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
+                            Depth);
+    break;
   }
   case Instruction::SRem:
     if (ConstantInt *Rem =3D dyn_cast<ConstantInt>(I->getOperand(1))) {
       APInt RA =3D Rem->getValue().abs();
       if (RA.isPowerOf2()) {
         APInt LowBits =3D RA - 1;
-        APInt Mask2 =3D LowBits | APInt::getSignBit(BitWidth);
-        ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, =
TD,=20
-                          Depth+1);
+        ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Dep=
th+1);
=20
         // The low bits of the first operand are unchanged by the srem.
         KnownZero =3D KnownZero2 & LowBits;
@@ -487,19 +552,15 @@
         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) !=3D 0))
           KnownOne |=3D ~LowBits;
=20
-        KnownZero &=3D Mask;
-        KnownOne &=3D Mask;
-
         assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AN=
D zero?");=20
       }
     }
=20
     // The sign bit is the LHS's sign bit, except when the result of the
     // remainder is zero.
-    if (Mask.isNegative() && KnownZero.isNonNegative()) {
-      APInt Mask2 =3D APInt::getSignBit(BitWidth);
+    if (KnownZero.isNonNegative()) {
       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
-      ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne=
, TD,
+      ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
                         Depth+1);
       // If it's known zero, our sign bit is also zero.
       if (LHSKnownZero.isNegative())
@@ -512,27 +573,24 @@
       APInt RA =3D Rem->getValue();
       if (RA.isPowerOf2()) {
         APInt LowBits =3D (RA - 1);
-        APInt Mask2 =3D LowBits & Mask;
-        KnownZero |=3D ~LowBits & Mask;
-        ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD,
+        ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD,
                           Depth+1);
         assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AN=
D zero?");
+        KnownZero |=3D ~LowBits;
+        KnownOne &=3D LowBits;
         break;
       }
     }
=20
     // Since the result is less than or equal to either operand, any leadi=
ng
     // zero bits in either operand must also exist in the result.
-    APInt AllOnes =3D APInt::getAllOnesValue(BitWidth);
-    ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
-                      TD, Depth+1);
-    ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
-                      TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1=
);
=20
     unsigned Leaders =3D std::max(KnownZero.countLeadingOnes(),
                                 KnownZero2.countLeadingOnes());
     KnownOne.clearAllBits();
-    KnownZero =3D APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
+    KnownZero =3D APInt::getHighBitsSet(BitWidth, Leaders);
     break;
   }
=20
@@ -543,17 +601,15 @@
       Align =3D TD->getABITypeAlignment(AI->getType()->getElementType());
    =20
     if (Align > 0)
-      KnownZero =3D Mask & APInt::getLowBitsSet(BitWidth,
-                                              CountTrailingZeros_32(Align)=
);
+      KnownZero =3D APInt::getLowBitsSet(BitWidth, CountTrailingZeros_32(A=
lign));
     break;
   }
   case Instruction::GetElementPtr: {
     // Analyze all of the subscripts of this getelementptr instruction
     // to determine if we can prove known low zero bits.
-    APInt LocalMask =3D APInt::getAllOnesValue(BitWidth);
     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
-    ComputeMaskedBits(I->getOperand(0), LocalMask,
-                      LocalKnownZero, LocalKnownOne, TD, Depth+1);
+    ComputeMaskedBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
+                      Depth+1);
     unsigned TrailZ =3D LocalKnownZero.countTrailingOnes();
=20
     gep_type_iterator GTI =3D gep_type_begin(I);
@@ -573,17 +629,15 @@
         if (!IndexedTy->isSized()) return;
         unsigned GEPOpiBits =3D Index->getType()->getScalarSizeInBits();
         uint64_t TypeSize =3D TD ? TD->getTypeAllocSize(IndexedTy) : 1;
-        LocalMask =3D APInt::getAllOnesValue(GEPOpiBits);
         LocalKnownZero =3D LocalKnownOne =3D APInt(GEPOpiBits, 0);
-        ComputeMaskedBits(Index, LocalMask,
-                          LocalKnownZero, LocalKnownOne, TD, Depth+1);
+        ComputeMaskedBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+=
1);
         TrailZ =3D std::min(TrailZ,
                           unsigned(CountTrailingZeros_64(TypeSize) +
                                    LocalKnownZero.countTrailingOnes()));
       }
     }
    =20
-    KnownZero =3D APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
+    KnownZero =3D APInt::getLowBitsSet(BitWidth, TrailZ);
     break;
   }
   case Instruction::PHI: {
@@ -618,17 +672,13 @@
             break;
           // Ok, we have a PHI of the form L op=3D R. Check for low
           // zero bits.
-          APInt Mask2 =3D APInt::getAllOnesValue(BitWidth);
-          ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1);
-          Mask2 =3D APInt::getLowBitsSet(BitWidth,
-                                       KnownZero2.countTrailingOnes());
+          ComputeMaskedBits(R, KnownZero2, KnownOne2, TD, Depth+1);
=20
           // We need to take the minimum number of known bits
           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
-          ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1);
+          ComputeMaskedBits(L, KnownZero3, KnownOne3, TD, Depth+1);
=20
-          KnownZero =3D Mask &
-                      APInt::getLowBitsSet(BitWidth,
+          KnownZero =3D APInt::getLowBitsSet(BitWidth,
                                            std::min(KnownZero2.countTraili=
ngOnes(),
                                                     KnownZero3.countTraili=
ngOnes()));
           break;
@@ -657,8 +707,8 @@
         KnownOne2 =3D APInt(BitWidth, 0);
         // Recurse, but cap the recursion to one level, because we don't
         // want to waste time spinning around in loops.
-        ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne,
-                          KnownZero2, KnownOne2, TD, MaxDepth-1);
+        ComputeMaskedBits(P->getIncomingValue(i), KnownZero2, KnownOne2, T=
D,
+                          MaxDepth-1);
         KnownZero &=3D KnownZero2;
         KnownOne &=3D KnownOne2;
         // If all bits have been ruled out, there's no need to check
@@ -673,10 +723,17 @@
     if (IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(I)) {
       switch (II->getIntrinsicID()) {
       default: break;
-      case Intrinsic::ctpop:
       case Intrinsic::ctlz:
       case Intrinsic::cttz: {
         unsigned LowBits =3D Log2_32(BitWidth)+1;
+        // If this call is undefined for 0, the result will be less than 2=
^n.
+        if (II->getArgOperand(1) =3D=3D ConstantInt::getTrue(II->getContex=
t()))
+          LowBits -=3D 1;
+        KnownZero =3D APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
+        break;
+      }
+      case Intrinsic::ctpop: {
+        unsigned LowBits =3D Log2_32(BitWidth)+1;
         KnownZero =3D APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
         break;
       }
@@ -687,6 +744,34 @@
       }
     }
     break;
+  case Instruction::ExtractValue:
+    if (IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(I->getOperand(0))) {
+      ExtractValueInst *EVI =3D cast<ExtractValueInst>(I);
+      if (EVI->getNumIndices() !=3D 1) break;
+      if (EVI->getIndices()[0] =3D=3D 0) {
+        switch (II->getIntrinsicID()) {
+        default: break;
+        case Intrinsic::uadd_with_overflow:
+        case Intrinsic::sadd_with_overflow:
+          ComputeMaskedBitsAddSub(true, II->getArgOperand(0),
+                                  II->getArgOperand(1), false, KnownZero,
+                                  KnownOne, KnownZero2, KnownOne2, TD, Dep=
th);
+          break;
+        case Intrinsic::usub_with_overflow:
+        case Intrinsic::ssub_with_overflow:
+          ComputeMaskedBitsAddSub(false, II->getArgOperand(0),
+                                  II->getArgOperand(1), false, KnownZero,
+                                  KnownOne, KnownZero2, KnownOne2, TD, Dep=
th);
+          break;
+        case Intrinsic::umul_with_overflow:
+        case Intrinsic::smul_with_overflow:
+          ComputeMaskedBitsMul(II->getArgOperand(0), II->getArgOperand(1),
+                               false, KnownZero, KnownOne,
+                               KnownZero2, KnownOne2, TD, Depth);
+          break;
+        }
+      }
+    }
   }
 }
=20
@@ -702,8 +787,7 @@
   }
   APInt ZeroBits(BitWidth, 0);
   APInt OneBits(BitWidth, 0);
-  ComputeMaskedBits(V, APInt::getSignBit(BitWidth), ZeroBits, OneBits, TD,
-                    Depth);
+  ComputeMaskedBits(V, ZeroBits, OneBits, TD, Depth);
   KnownOne =3D OneBits[BitWidth - 1];
   KnownZero =3D ZeroBits[BitWidth - 1];
 }
@@ -712,10 +796,15 @@
 /// bit set when defined. For vectors return true if every element is know=
n to
 /// be a power of two when defined.  Supports values with integer or point=
er
 /// types and vectors of integers.
-bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, unsigned Depth) {
-  if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V))
-    return CI->getValue().isPowerOf2();
-  // TODO: Handle vector constants.
+bool llvm::isPowerOfTwo(Value *V, const TargetData *TD, bool OrZero,
+                        unsigned Depth) {
+  if (Constant *C =3D dyn_cast<Constant>(V)) {
+    if (C->isNullValue())
+      return OrZero;
+    if (ConstantInt *CI =3D dyn_cast<ConstantInt>(C))
+      return CI->getValue().isPowerOf2();
+    // TODO: Handle vector constants.
+  }
=20
   // 1 << X is clearly a power of two if the one is not shifted off the en=
d.  If
   // it is shifted off the end then the result is undefined.
@@ -731,21 +820,36 @@
   if (Depth++ =3D=3D MaxDepth)
     return false;
=20
+  Value *X =3D 0, *Y =3D 0;
+  // A shift of a power of two is a power of two or zero.
+  if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
+                 match(V, m_Shr(m_Value(X), m_Value()))))
+    return isPowerOfTwo(X, TD, /*OrZero*/true, Depth);
+
   if (ZExtInst *ZI =3D dyn_cast<ZExtInst>(V))
-    return isPowerOfTwo(ZI->getOperand(0), TD, Depth);
+    return isPowerOfTwo(ZI->getOperand(0), TD, OrZero, Depth);
=20
   if (SelectInst *SI =3D dyn_cast<SelectInst>(V))
-    return isPowerOfTwo(SI->getTrueValue(), TD, Depth) &&
-      isPowerOfTwo(SI->getFalseValue(), TD, Depth);
+    return isPowerOfTwo(SI->getTrueValue(), TD, OrZero, Depth) &&
+      isPowerOfTwo(SI->getFalseValue(), TD, OrZero, Depth);
+
+  if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
+    // A power of two and'd with anything is a power of two or zero.
+    if (isPowerOfTwo(X, TD, /*OrZero*/true, Depth) ||
+        isPowerOfTwo(Y, TD, /*OrZero*/true, Depth))
+      return true;
+    // X & (-X) is always a power of two or zero.
+    if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
+      return true;
+    return false;
+  }
=20
   // An exact divide or right shift can only shift off zero bits, so the r=
esult
   // is a power of two only if the first operand is a power of two and not
   // copying a sign bit (sdiv int_min, 2).
-  if (match(V, m_LShr(m_Value(), m_Value())) ||
-      match(V, m_UDiv(m_Value(), m_Value()))) {
-    PossiblyExactOperator *PEO =3D cast<PossiblyExactOperator>(V);
-    if (PEO->isExact())
-      return isPowerOfTwo(PEO->getOperand(0), TD, Depth);
+  if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
+      match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
+    return isPowerOfTwo(cast<Operator>(V)->getOperand(0), TD, OrZero, Dept=
h);
   }
=20
   return false;
@@ -767,7 +871,7 @@
   }
=20
   // The remaining tests are all recursive, so bail out if we hit the limi=
t.
-  if (Depth++ =3D=3D MaxDepth)
+  if (Depth++ >=3D MaxDepth)
     return false;
=20
   unsigned BitWidth =3D getBitWidth(V->getType(), TD);
@@ -785,13 +889,13 @@
   // if the lowest bit is shifted off the end.
   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
     // shl nuw can't remove any non-zero bits.
-    BinaryOperator *BO =3D cast<BinaryOperator>(V);
+    OverflowingBinaryOperator *BO =3D cast<OverflowingBinaryOperator>(V);
     if (BO->hasNoUnsignedWrap())
       return isKnownNonZero(X, TD, Depth);
=20
     APInt KnownZero(BitWidth, 0);
     APInt KnownOne(BitWidth, 0);
-    ComputeMaskedBits(X, APInt(BitWidth, 1), KnownZero, KnownOne, TD, Dept=
h);
+    ComputeMaskedBits(X, KnownZero, KnownOne, TD, Depth);
     if (KnownOne[0])
       return true;
   }
@@ -799,7 +903,7 @@
   // defined if the sign bit is shifted off the end.
   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
     // shr exact can only shift out zero bits.
-    BinaryOperator *BO =3D cast<BinaryOperator>(V);
+    PossiblyExactOperator *BO =3D cast<PossiblyExactOperator>(V);
     if (BO->isExact())
       return isKnownNonZero(X, TD, Depth);
=20
@@ -809,10 +913,8 @@
       return true;
   }
   // div exact can only produce a zero if the dividend is zero.
-  else if (match(V, m_IDiv(m_Value(X), m_Value()))) {
-    BinaryOperator *BO =3D cast<BinaryOperator>(V);
-    if (BO->isExact())
-      return isKnownNonZero(X, TD, Depth);
+  else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
+    return isKnownNonZero(X, TD, Depth);
   }
   // X + Y.
   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
@@ -835,20 +937,29 @@
       APInt Mask =3D APInt::getSignedMaxValue(BitWidth);
       // The sign bit of X is set.  If some other bit is set then X is not=
 equal
       // to INT_MIN.
-      ComputeMaskedBits(X, Mask, KnownZero, KnownOne, TD, Depth);
+      ComputeMaskedBits(X, KnownZero, KnownOne, TD, Depth);
       if ((KnownOne & Mask) !=3D 0)
         return true;
       // The sign bit of Y is set.  If some other bit is set then Y is not=
 equal
       // to INT_MIN.
-      ComputeMaskedBits(Y, Mask, KnownZero, KnownOne, TD, Depth);
+      ComputeMaskedBits(Y, KnownZero, KnownOne, TD, Depth);
       if ((KnownOne & Mask) !=3D 0)
         return true;
     }
=20
     // The sum of a non-negative number and a power of two is not zero.
-    if (XKnownNonNegative && isPowerOfTwo(Y, TD, Depth))
+    if (XKnownNonNegative && isPowerOfTwo(Y, TD, /*OrZero*/false, Depth))
       return true;
-    if (YKnownNonNegative && isPowerOfTwo(X, TD, Depth))
+    if (YKnownNonNegative && isPowerOfTwo(X, TD, /*OrZero*/false, Depth))
+      return true;
+  }
+  // X * Y.
+  else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
+    OverflowingBinaryOperator *BO =3D cast<OverflowingBinaryOperator>(V);
+    // If X and Y are non-zero then so is X * Y as long as the multiplicat=
ion
+    // does not overflow.
+    if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
+        isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
       return true;
   }
   // (C ? X : Y) !=3D 0 if X !=3D 0 and Y !=3D 0.
@@ -861,8 +972,7 @@
   if (!BitWidth) return false;
   APInt KnownZero(BitWidth, 0);
   APInt KnownOne(BitWidth, 0);
-  ComputeMaskedBits(V, APInt::getAllOnesValue(BitWidth), KnownZero, KnownO=
ne,
-                    TD, Depth);
+  ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
   return KnownOne !=3D 0;
 }
=20
@@ -878,7 +988,7 @@
 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
                              const TargetData *TD, unsigned Depth) {
   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
-  ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
+  ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
   assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND zero=
?");=20
   return (KnownZero & Mask) =3D=3D Mask;
 }
@@ -917,30 +1027,28 @@
     Tmp =3D TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
    =20
-  case Instruction::AShr:
+  case Instruction::AShr: {
     Tmp =3D ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
-    // ashr X, C   -> adds C sign bits.
-    if (ConstantInt *C =3D dyn_cast<ConstantInt>(U->getOperand(1))) {
-      Tmp +=3D C->getZExtValue();
+    // ashr X, C   -> adds C sign bits.  Vectors too.
+    const APInt *ShAmt;
+    if (match(U->getOperand(1), m_APInt(ShAmt))) {
+      Tmp +=3D ShAmt->getZExtValue();
       if (Tmp > TyBits) Tmp =3D TyBits;
     }
-    // vector ashr X, <C, C, C, C>  -> adds C sign bits
-    if (ConstantVector *C =3D dyn_cast<ConstantVector>(U->getOperand(1))) {
-      if (ConstantInt *CI =3D dyn_cast_or_null<ConstantInt>(C->getSplatVal=
ue())) {
-        Tmp +=3D CI->getZExtValue();
-        if (Tmp > TyBits) Tmp =3D TyBits;
-      }
-    }
     return Tmp;
-  case Instruction::Shl:
-    if (ConstantInt *C =3D dyn_cast<ConstantInt>(U->getOperand(1))) {
+  }
+  case Instruction::Shl: {
+    const APInt *ShAmt;
+    if (match(U->getOperand(1), m_APInt(ShAmt))) {
       // shl destroys sign bits.
       Tmp =3D ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
-      if (C->getZExtValue() >=3D TyBits ||      // Bad shift.
-          C->getZExtValue() >=3D Tmp) break;    // Shifted all sign bits o=
ut.
-      return Tmp - C->getZExtValue();
+      Tmp2 =3D ShAmt->getZExtValue();
+      if (Tmp2 >=3D TyBits ||      // Bad shift.
+          Tmp2 >=3D Tmp) break;    // Shifted all sign bits out.
+      return Tmp - Tmp2;
     }
     break;
+  }
   case Instruction::And:
   case Instruction::Or:
   case Instruction::Xor:    // NOT is handled here.
@@ -971,13 +1079,11 @@
     if (ConstantInt *CRHS =3D dyn_cast<ConstantInt>(U->getOperand(1)))
       if (CRHS->isAllOnesValue()) {
         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
-        APInt Mask =3D APInt::getAllOnesValue(TyBits);
-        ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD,
-                          Depth+1);
+        ComputeMaskedBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth=
+1);
        =20
         // If the input is known to be 0 or 1, the output is 0/-1, which i=
s all
         // sign bits set.
-        if ((KnownZero | APInt(TyBits, 1)) =3D=3D Mask)
+        if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
           return TyBits;
        =20
         // If we are subtracting one from a positive number, there is no c=
arry
@@ -998,12 +1104,10 @@
     if (ConstantInt *CLHS =3D dyn_cast<ConstantInt>(U->getOperand(0)))
       if (CLHS->isNullValue()) {
         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
-        APInt Mask =3D APInt::getAllOnesValue(TyBits);
-        ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne,=20
-                          TD, Depth+1);
+        ComputeMaskedBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth=
+1);
         // If the input is known to be 0 or 1, the output is 0/-1, which i=
s all
         // sign bits set.
-        if ((KnownZero | APInt(TyBits, 1)) =3D=3D Mask)
+        if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
           return TyBits;
        =20
         // If the input is known to be positive (the sign bit is known cle=
ar),
@@ -1045,8 +1149,8 @@
   // Finally, if we can prove that the top bits of the result are 0's or 1=
's,
   // use this information.
   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
-  APInt Mask =3D APInt::getAllOnesValue(TyBits);
-  ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
+  APInt Mask;
+  ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
  =20
   if (KnownZero.isNegative()) {        // sign bit is 0
     Mask =3D KnownZero;
@@ -1282,23 +1386,21 @@
     }
   }
  =20
-  // A ConstantArray is splatable if all its members are equal and also
-  // splatable.
-  if (ConstantArray *CA =3D dyn_cast<ConstantArray>(V)) {
-    if (CA->getNumOperands() =3D=3D 0)
-      return 0;
-   =20
-    Value *Val =3D isBytewiseValue(CA->getOperand(0));
+  // A ConstantDataArray/Vector is splatable if all its members are equal =
and
+  // also splatable.
+  if (ConstantDataSequential *CA =3D dyn_cast<ConstantDataSequential>(V)) {
+    Value *Elt =3D CA->getElementAsConstant(0);
+    Value *Val =3D isBytewiseValue(Elt);
     if (!Val)
       return 0;
    =20
-    for (unsigned I =3D 1, E =3D CA->getNumOperands(); I !=3D E; ++I)
-      if (CA->getOperand(I-1) !=3D CA->getOperand(I))
+    for (unsigned I =3D 1, E =3D CA->getNumElements(); I !=3D E; ++I)
+      if (CA->getElementAsConstant(I) !=3D Elt)
         return 0;
    =20
     return Val;
   }
- =20
+
   // Conceptually, we could handle things like:
   //   %a =3D zext i8 %X to i16
   //   %b =3D shl i16 %a, 8
@@ -1395,50 +1497,44 @@
 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
                                Instruction *InsertBefore) {
   // Nothing to index? Just return V then (this is useful at the end of our
-  // recursion)
+  // recursion).
   if (idx_range.empty())
     return V;
-  // We have indices, so V should have an indexable type
-  assert((V->getType()->isStructTy() || V->getType()->isArrayTy())
-         && "Not looking at a struct or array?");
-  assert(ExtractValueInst::getIndexedType(V->getType(), idx_range)
-         && "Invalid indices for type?");
-  CompositeType *PTy =3D cast<CompositeType>(V->getType());
+  // We have indices, so V should have an indexable type.
+  assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
+         "Not looking at a struct or array?");
+  assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
+         "Invalid indices for type?");
=20
-  if (isa<UndefValue>(V))
-    return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
-                                                              idx_range));
-  else if (isa<ConstantAggregateZero>(V))
-    return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy,=20
-                                                                  idx_rang=
e));
-  else if (Constant *C =3D dyn_cast<Constant>(V)) {
-    if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
-      // Recursively process this constant
-      return FindInsertedValue(C->getOperand(idx_range[0]), idx_range.slic=
e(1),
-                               InsertBefore);
-  } else if (InsertValueInst *I =3D dyn_cast<InsertValueInst>(V)) {
+  if (Constant *C =3D dyn_cast<Constant>(V)) {
+    C =3D C->getAggregateElement(idx_range[0]);
+    if (C =3D=3D 0) return 0;
+    return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
+  }
+   =20
+  if (InsertValueInst *I =3D dyn_cast<InsertValueInst>(V)) {
     // Loop the indices for the insertvalue instruction in parallel with t=
he
     // requested indices
     const unsigned *req_idx =3D idx_range.begin();
     for (const unsigned *i =3D I->idx_begin(), *e =3D I->idx_end();
          i !=3D e; ++i, ++req_idx) {
       if (req_idx =3D=3D idx_range.end()) {
-        if (InsertBefore)
-          // The requested index identifies a part of a nested aggregate. =
Handle
-          // this specially. For example,
-          // %A =3D insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
-          // %B =3D insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
-          // %C =3D extractvalue {i32, { i32, i32 } } %B, 1
-          // This can be changed into
-          // %A =3D insertvalue {i32, i32 } undef, i32 10, 0
-          // %C =3D insertvalue {i32, i32 } %A, i32 11, 1
-          // which allows the unused 0,0 element from the nested struct to=
 be
-          // removed.
-          return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_=
idx),
-                                   InsertBefore);
-        else
-          // We can't handle this without inserting insertvalues
+        // We can't handle this without inserting insertvalues
+        if (!InsertBefore)
           return 0;
+
+        // The requested index identifies a part of a nested aggregate. Ha=
ndle
+        // this specially. For example,
+        // %A =3D insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
+        // %B =3D insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
+        // %C =3D extractvalue {i32, { i32, i32 } } %B, 1
+        // This can be changed into
+        // %A =3D insertvalue {i32, i32 } undef, i32 10, 0
+        // %C =3D insertvalue {i32, i32 } %A, i32 11, 1
+        // which allows the unused 0,0 element from the nested struct to be
+        // removed.
+        return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_id=
x),
+                                 InsertBefore);
       }
      =20
       // This insert value inserts something else than what we are looking=
 for.
@@ -1454,7 +1550,9 @@
     return FindInsertedValue(I->getInsertedValueOperand(),
                              makeArrayRef(req_idx, idx_range.end()),
                              InsertBefore);
-  } else if (ExtractValueInst *I =3D dyn_cast<ExtractValueInst>(V)) {
+  }
+ =20
+  if (ExtractValueInst *I =3D dyn_cast<ExtractValueInst>(V)) {
     // If we're extracting a value from an aggregrate that was extracted f=
rom
     // something else, we can extract from that something else directly in=
stead.
     // However, we will need to chain I's indices with the requested indic=
es.
@@ -1486,7 +1584,8 @@
 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
                                               const TargetData &TD) {
   Operator *PtrOp =3D dyn_cast<Operator>(Ptr);
-  if (PtrOp =3D=3D 0) return Ptr;
+  if (PtrOp =3D=3D 0 || Ptr->getType()->isVectorTy())
+    return Ptr;
  =20
   // Just look through bitcasts.
   if (PtrOp->getOpcode() =3D=3D Instruction::BitCast)
@@ -1521,34 +1620,19 @@
 }
=20
=20
-/// GetConstantStringInfo - This function computes the length of a
+/// getConstantStringInfo - This function computes the length of a
 /// null-terminated C string pointed to by V.  If successful, it returns t=
rue
 /// and returns the string in Str.  If unsuccessful, it returns false.
-bool llvm::GetConstantStringInfo(const Value *V, std::string &Str,
-                                 uint64_t Offset,
-                                 bool StopAtNul) {
-  // If V is NULL then return false;
-  if (V =3D=3D NULL) return false;
+bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
+                                 uint64_t Offset, bool TrimAtNul) {
+  assert(V);
=20
-  // Look through bitcast instructions.
-  if (const BitCastInst *BCI =3D dyn_cast<BitCastInst>(V))
-    return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNu=
l);
+  // Look through bitcast instructions and geps.
+  V =3D V->stripPointerCasts();
  =20
-  // If the value is not a GEP instruction nor a constant expression with a
-  // GEP instruction, then return false because ConstantArray can't occur
-  // any other way
-  const User *GEP =3D 0;
-  if (const GetElementPtrInst *GEPI =3D dyn_cast<GetElementPtrInst>(V)) {
-    GEP =3D GEPI;
-  } else if (const ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V)) {
-    if (CE->getOpcode() =3D=3D Instruction::BitCast)
-      return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtN=
ul);
-    if (CE->getOpcode() !=3D Instruction::GetElementPtr)
-      return false;
-    GEP =3D CE;
-  }
- =20
-  if (GEP) {
+  // If the value is a GEP instructionor  constant expression, treat it as=
 an
+  // offset.
+  if (const GEPOperator *GEP =3D dyn_cast<GEPOperator>(V)) {
     // Make sure the GEP has exactly three arguments.
     if (GEP->getNumOperands() !=3D 3)
       return false;
@@ -1573,51 +1657,48 @@
       StartIdx =3D CI->getZExtValue();
     else
       return false;
-    return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset,
-                                 StopAtNul);
+    return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
   }
- =20
+
   // The GEP instruction, constant or instruction, must reference a global
   // variable that is a constant and is initialized. The referenced consta=
nt
   // initializer is the array that we'll use for optimization.
-  const GlobalVariable* GV =3D dyn_cast<GlobalVariable>(V);
+  const GlobalVariable *GV =3D dyn_cast<GlobalVariable>(V);
   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
     return false;
-  const Constant *GlobalInit =3D GV->getInitializer();
- =20
-  // Handle the ConstantAggregateZero case
-  if (isa<ConstantAggregateZero>(GlobalInit)) {
+
+  // Handle the all-zeros case
+  if (GV->getInitializer()->isNullValue()) {
     // This is a degenerate case. The initializer is constant zero so the
     // length of the string must be zero.
-    Str.clear();
+    Str =3D "";
     return true;
   }
  =20
   // Must be a Constant Array
-  const ConstantArray *Array =3D dyn_cast<ConstantArray>(GlobalInit);
-  if (Array =3D=3D 0 || !Array->getType()->getElementType()->isIntegerTy(8=
))
+  const ConstantDataArray *Array =3D
+    dyn_cast<ConstantDataArray>(GV->getInitializer());
+  if (Array =3D=3D 0 || !Array->isString())
     return false;
  =20
   // Get the number of elements in the array
-  uint64_t NumElts =3D Array->getType()->getNumElements();
- =20
+  uint64_t NumElts =3D Array->getType()->getArrayNumElements();
+
+  // Start out with the entire array in the StringRef.
+  Str =3D Array->getAsString();
+
   if (Offset > NumElts)
     return false;
  =20
-  // Traverse the constant array from 'Offset' which is the place the GEP =
refers
-  // to in the array.
-  Str.reserve(NumElts-Offset);
-  for (unsigned i =3D Offset; i !=3D NumElts; ++i) {
-    const Constant *Elt =3D Array->getOperand(i);
-    const ConstantInt *CI =3D dyn_cast<ConstantInt>(Elt);
-    if (!CI) // This array isn't suitable, non-int initializer.
-      return false;
-    if (StopAtNul && CI->isZero())
-      return true; // we found end of string, success!
-    Str +=3D (char)CI->getZExtValue();
+  // Skip over 'offset' bytes.
+  Str =3D Str.substr(Offset);
+ =20
+  if (TrimAtNul) {
+    // Trim off the \0 and anything after it.  If the array is not nul
+    // terminated, we just return the whole end of string.  The client may=
 know
+    // some other way that the string is length-bound.
+    Str =3D Str.substr(0, Str.find('\0'));
   }
- =20
-  // The array isn't null terminated, but maybe this is a memcpy, not a st=
rcpy.
   return true;
 }
=20
@@ -1629,8 +1710,7 @@
 /// the specified pointer, return 'len+1'.  If we can't, return 0.
 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs=
) {
   // Look through noop bitcast instructions.
-  if (BitCastInst *BCI =3D dyn_cast<BitCastInst>(V))
-    return GetStringLengthH(BCI->getOperand(0), PHIs);
+  V =3D V->stripPointerCasts();
=20
   // If this is a PHI node, there are two cases: either we have already se=
en it
   // or we haven't.
@@ -1666,75 +1746,13 @@
     if (Len1 !=3D Len2) return 0;
     return Len1;
   }
-
-  // If the value is not a GEP instruction nor a constant expression with a
-  // GEP instruction, then return unknown.
-  User *GEP =3D 0;
-  if (GetElementPtrInst *GEPI =3D dyn_cast<GetElementPtrInst>(V)) {
-    GEP =3D GEPI;
-  } else if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V)) {
-    if (CE->getOpcode() !=3D Instruction::GetElementPtr)
-      return 0;
-    GEP =3D CE;
-  } else {
-    return 0;
-  }
-
-  // Make sure the GEP has exactly three arguments.
-  if (GEP->getNumOperands() !=3D 3)
+ =20
+  // Otherwise, see if we can read the string.
+  StringRef StrData;
+  if (!getConstantStringInfo(V, StrData))
     return 0;
=20
-  // Check to make sure that the first operand of the GEP is an integer and
-  // has value 0 so that we are sure we're indexing into the initializer.
-  if (ConstantInt *Idx =3D dyn_cast<ConstantInt>(GEP->getOperand(1))) {
-    if (!Idx->isZero())
-      return 0;
-  } else
-    return 0;
-
-  // If the second index isn't a ConstantInt, then this is a variable index
-  // into the array.  If this occurs, we can't say anything meaningful abo=
ut
-  // the string.
-  uint64_t StartIdx =3D 0;
-  if (ConstantInt *CI =3D dyn_cast<ConstantInt>(GEP->getOperand(2)))
-    StartIdx =3D CI->getZExtValue();
-  else
-    return 0;
-
-  // The GEP instruction, constant or instruction, must reference a global
-  // variable that is a constant and is initialized. The referenced consta=
nt
-  // initializer is the array that we'll use for optimization.
-  GlobalVariable* GV =3D dyn_cast<GlobalVariable>(GEP->getOperand(0));
-  if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
-      GV->mayBeOverridden())
-    return 0;
-  Constant *GlobalInit =3D GV->getInitializer();
-
-  // Handle the ConstantAggregateZero case, which is a degenerate case. The
-  // initializer is constant zero so the length of the string must be zero.
-  if (isa<ConstantAggregateZero>(GlobalInit))
-    return 1;  // Len =3D 0 offset by 1.
-
-  // Must be a Constant Array
-  ConstantArray *Array =3D dyn_cast<ConstantArray>(GlobalInit);
-  if (!Array || !Array->getType()->getElementType()->isIntegerTy(8))
-    return false;
-
-  // Get the number of elements in the array
-  uint64_t NumElts =3D Array->getType()->getNumElements();
-
-  // Traverse the constant array from StartIdx (derived above) which is
-  // the place the GEP refers to in the array.
-  for (unsigned i =3D StartIdx; i !=3D NumElts; ++i) {
-    Constant *Elt =3D Array->getOperand(i);
-    ConstantInt *CI =3D dyn_cast<ConstantInt>(Elt);
-    if (!CI) // This array isn't suitable, non-int initializer.
-      return 0;
-    if (CI->isZero())
-      return i-StartIdx+1; // We found end of string, success!
-  }
-
-  return 0; // The array isn't null terminated, conservatively return 'unk=
nown'.
+  return StrData.size()+1;
 }
=20
 /// GetStringLength - If we can compute the length of the string pointed t=
o by
@@ -1793,3 +1811,94 @@
   }
   return true;
 }
+
+bool llvm::isSafeToSpeculativelyExecute(const Value *V,
+                                        const TargetData *TD) {
+  const Operator *Inst =3D dyn_cast<Operator>(V);
+  if (!Inst)
+    return false;
+
+  for (unsigned i =3D 0, e =3D Inst->getNumOperands(); i !=3D e; ++i)
+    if (Constant *C =3D dyn_cast<Constant>(Inst->getOperand(i)))
+      if (C->canTrap())
+        return false;
+
+  switch (Inst->getOpcode()) {
+  default:
+    return true;
+  case Instruction::UDiv:
+  case Instruction::URem:
+    // x / y is undefined if y =3D=3D 0, but calcuations like x / 3 are sa=
fe.
+    return isKnownNonZero(Inst->getOperand(1), TD);
+  case Instruction::SDiv:
+  case Instruction::SRem: {
+    Value *Op =3D Inst->getOperand(1);
+    // x / y is undefined if y =3D=3D 0
+    if (!isKnownNonZero(Op, TD))
+      return false;
+    // x / y might be undefined if y =3D=3D -1
+    unsigned BitWidth =3D getBitWidth(Op->getType(), TD);
+    if (BitWidth =3D=3D 0)
+      return false;
+    APInt KnownZero(BitWidth, 0);
+    APInt KnownOne(BitWidth, 0);
+    ComputeMaskedBits(Op, KnownZero, KnownOne, TD);
+    return !!KnownZero;
+  }
+  case Instruction::Load: {
+    const LoadInst *LI =3D cast<LoadInst>(Inst);
+    if (!LI->isUnordered())
+      return false;
+    return LI->getPointerOperand()->isDereferenceablePointer();
+  }
+  case Instruction::Call: {
+   if (const IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(Inst)) {
+     switch (II->getIntrinsicID()) {
+       // These synthetic intrinsics have no side-effects, and just mark
+       // information about their operands.
+       // FIXME: There are other no-op synthetic instructions that potenti=
ally
+       // should be considered at least *safe* to speculate...
+       case Intrinsic::dbg_declare:
+       case Intrinsic::dbg_value:
+         return true;
+
+       case Intrinsic::bswap:
+       case Intrinsic::ctlz:
+       case Intrinsic::ctpop:
+       case Intrinsic::cttz:
+       case Intrinsic::objectsize:
+       case Intrinsic::sadd_with_overflow:
+       case Intrinsic::smul_with_overflow:
+       case Intrinsic::ssub_with_overflow:
+       case Intrinsic::uadd_with_overflow:
+       case Intrinsic::umul_with_overflow:
+       case Intrinsic::usub_with_overflow:
+         return true;
+       // TODO: some fp intrinsics are marked as having the same error han=
dling
+       // as libm. They're safe to speculate when they won't error.
+       // TODO: are convert_{from,to}_fp16 safe?
+       // TODO: can we list target-specific intrinsics here?
+       default: break;
+     }
+   }
+    return false; // The called function could have undefined behavior or
+                  // side-effects, even if marked readnone nounwind.
+  }
+  case Instruction::VAArg:
+  case Instruction::Alloca:
+  case Instruction::Invoke:
+  case Instruction::PHI:
+  case Instruction::Store:
+  case Instruction::Ret:
+  case Instruction::Br:
+  case Instruction::IndirectBr:
+  case Instruction::Switch:
+  case Instruction::Unreachable:
+  case Instruction::Fence:
+  case Instruction::LandingPad:
+  case Instruction::AtomicRMW:
+  case Instruction::AtomicCmpXchg:
+  case Instruction::Resume:
+    return false; // Misc instructions which have effects
+  }
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Archive/ArchiveR=
eader.cpp
--- a/head/contrib/llvm/lib/Archive/ArchiveReader.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Archive/ArchiveReader.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -12,9 +12,11 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "ArchiveInternals.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Bitcode/ReaderWriter.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Module.h"
+#include <cstdio>
 #include <cstdlib>
 #include <memory>
 using namespace llvm;
@@ -504,7 +506,7 @@
 // Modules that define those symbols.
 bool
 Archive::findModulesDefiningSymbols(std::set<std::string>& symbols,
-                                    std::set<Module*>& result,
+                                    SmallVectorImpl<Module*>& result,
                                     std::string* error) {
   if (!mapfile || !base) {
     if (error)
@@ -569,21 +571,26 @@
   // At this point we have a valid symbol table (one way or another) so we
   // just use it to quickly find the symbols requested.
=20
+  SmallPtrSet<Module*, 16> Added;
   for (std::set<std::string>::iterator I=3Dsymbols.begin(),
-       E=3Dsymbols.end(); I !=3D E;) {
+         Next =3D I,
+         E=3Dsymbols.end(); I !=3D E; I =3D Next) {
+    // Increment Next before we invalidate it.
+    ++Next;
+
     // See if this symbol exists
     Module* m =3D findModuleDefiningSymbol(*I,error);
-    if (m) {
-      // The symbol exists, insert the Module into our result, duplicates =
will
-      // be ignored.
-      result.insert(m);
+    if (!m)
+      continue;
+    bool NewMember =3D Added.insert(m);
+    if (!NewMember)
+      continue;
=20
-      // Remove the symbol now that its been resolved, being careful to
-      // post-increment the iterator.
-      symbols.erase(I++);
-    } else {
-      ++I;
-    }
+    // The symbol exists, insert the Module into our result.
+    result.push_back(m);
+
+    // Remove the symbol now that its been resolved.
+    symbols.erase(I);
   }
   return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Archive/ArchiveW=
riter.cpp
--- a/head/contrib/llvm/lib/Archive/ArchiveWriter.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Archive/ArchiveWriter.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -182,11 +182,11 @@
   if (hasSlash || filePath.str().length() > 15)
     flags |=3D ArchiveMember::HasLongFilenameFlag;
=20
-  sys::LLVMFileType type;
+  sys::fs::file_magic type;
   if (sys::fs::identify_magic(mbr->path.str(), type))
-    type =3D sys::Unknown_FileType;
+    type =3D sys::fs::file_magic::unknown;
   switch (type) {
-    case sys::Bitcode_FileType:
+    case sys::fs::file_magic::bitcode:
       flags |=3D ArchiveMember::BitcodeFlag;
       break;
     default:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/AsmParser/LLLexe=
r.cpp
--- a/head/contrib/llvm/lib/AsmParser/LLLexer.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/AsmParser/LLLexer.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -29,7 +29,7 @@
 using namespace llvm;
=20
 bool LLLexer::Error(LocTy ErrorLoc, const Twine &Msg) const {
-  ErrorInfo =3D SM.GetMessage(ErrorLoc, Msg, "error");
+  ErrorInfo =3D SM.GetMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
   return true;
 }
=20
@@ -55,18 +55,22 @@
   return Result;
 }
=20
+static char parseHexChar(char C) {
+  if (C >=3D '0' && C <=3D '9')
+    return C-'0';
+  if (C >=3D 'A' && C <=3D 'F')
+    return C-'A'+10;
+  if (C >=3D 'a' && C <=3D 'f')
+    return C-'a'+10;
+  return 0;
+}
+
 uint64_t LLLexer::HexIntToVal(const char *Buffer, const char *End) {
   uint64_t Result =3D 0;
   for (; Buffer !=3D End; ++Buffer) {
     uint64_t OldRes =3D Result;
     Result *=3D 16;
-    char C =3D *Buffer;
-    if (C >=3D '0' && C <=3D '9')
-      Result +=3D C-'0';
-    else if (C >=3D 'A' && C <=3D 'F')
-      Result +=3D C-'A'+10;
-    else if (C >=3D 'a' && C <=3D 'f')
-      Result +=3D C-'a'+10;
+    Result +=3D parseHexChar(*Buffer);
=20
     if (Result < OldRes) {   // Uh, oh, overflow detected!!!
       Error("constant bigger than 64 bits detected!");
@@ -82,24 +86,12 @@
   for (int i=3D0; i<16; i++, Buffer++) {
     assert(Buffer !=3D End);
     Pair[0] *=3D 16;
-    char C =3D *Buffer;
-    if (C >=3D '0' && C <=3D '9')
-      Pair[0] +=3D C-'0';
-    else if (C >=3D 'A' && C <=3D 'F')
-      Pair[0] +=3D C-'A'+10;
-    else if (C >=3D 'a' && C <=3D 'f')
-      Pair[0] +=3D C-'a'+10;
+    Pair[0] +=3D parseHexChar(*Buffer);
   }
   Pair[1] =3D 0;
   for (int i=3D0; i<16 && Buffer !=3D End; i++, Buffer++) {
     Pair[1] *=3D 16;
-    char C =3D *Buffer;
-    if (C >=3D '0' && C <=3D '9')
-      Pair[1] +=3D C-'0';
-    else if (C >=3D 'A' && C <=3D 'F')
-      Pair[1] +=3D C-'A'+10;
-    else if (C >=3D 'a' && C <=3D 'f')
-      Pair[1] +=3D C-'a'+10;
+    Pair[1] +=3D parseHexChar(*Buffer);
   }
   if (Buffer !=3D End)
     Error("constant bigger than 128 bits detected!");
@@ -113,24 +105,12 @@
   for (int i=3D0; i<4 && Buffer !=3D End; i++, Buffer++) {
     assert(Buffer !=3D End);
     Pair[1] *=3D 16;
-    char C =3D *Buffer;
-    if (C >=3D '0' && C <=3D '9')
-      Pair[1] +=3D C-'0';
-    else if (C >=3D 'A' && C <=3D 'F')
-      Pair[1] +=3D C-'A'+10;
-    else if (C >=3D 'a' && C <=3D 'f')
-      Pair[1] +=3D C-'a'+10;
+    Pair[1] +=3D parseHexChar(*Buffer);
   }
   Pair[0] =3D 0;
   for (int i=3D0; i<16; i++, Buffer++) {
     Pair[0] *=3D 16;
-    char C =3D *Buffer;
-    if (C >=3D '0' && C <=3D '9')
-      Pair[0] +=3D C-'0';
-    else if (C >=3D 'A' && C <=3D 'F')
-      Pair[0] +=3D C-'A'+10;
-    else if (C >=3D 'a' && C <=3D 'f')
-      Pair[0] +=3D C-'a'+10;
+    Pair[0] +=3D parseHexChar(*Buffer);
   }
   if (Buffer !=3D End)
     Error("constant bigger than 128 bits detected!");
@@ -149,9 +129,7 @@
         *BOut++ =3D '\\'; // Two \ becomes one
         BIn +=3D 2;
       } else if (BIn < EndBuffer-2 && isxdigit(BIn[1]) && isxdigit(BIn[2])=
) {
-        char Tmp =3D BIn[3]; BIn[3] =3D 0;      // Terminate string
-        *BOut =3D (char)strtol(BIn+1, 0, 16); // Convert to number
-        BIn[3] =3D Tmp;                       // Restore character
+        *BOut =3D parseHexChar(BIn[1]) * 16 + parseHexChar(BIn[2]);
         BIn +=3D 3;                           // Skip over handled chars
         ++BOut;
       } else {
@@ -503,6 +481,7 @@
   KEYWORD(tail);
   KEYWORD(target);
   KEYWORD(triple);
+  KEYWORD(unwind);
   KEYWORD(deplibs);
   KEYWORD(datalayout);
   KEYWORD(volatile);
@@ -570,6 +549,7 @@
   KEYWORD(noimplicitfloat);
   KEYWORD(naked);
   KEYWORD(nonlazybind);
+  KEYWORD(address_safety);
=20
   KEYWORD(type);
   KEYWORD(opaque);
@@ -596,6 +576,7 @@
   if (Len =3D=3D strlen(STR) && !memcmp(StartChar, STR, strlen(STR))) { \
     TyVal =3D LLVMTY; return lltok::Type; }
   TYPEKEYWORD("void",      Type::getVoidTy(Context));
+  TYPEKEYWORD("half",      Type::getHalfTy(Context));
   TYPEKEYWORD("float",     Type::getFloatTy(Context));
   TYPEKEYWORD("double",    Type::getDoubleTy(Context));
   TYPEKEYWORD("x86_fp80",  Type::getX86_FP80Ty(Context));
@@ -642,7 +623,6 @@
   INSTKEYWORD(indirectbr,  IndirectBr);
   INSTKEYWORD(invoke,      Invoke);
   INSTKEYWORD(resume,      Resume);
-  INSTKEYWORD(unwind,      Unwind);
   INSTKEYWORD(unreachable, Unreachable);
=20
   INSTKEYWORD(alloca,      Alloca);
@@ -715,7 +695,7 @@
   if (Kind =3D=3D 'J') {
     // HexFPConstant - Floating point constant represented in IEEE format =
as a
     // hexadecimal number for when exponential notation is not precise eno=
ugh.
-    // Float and double only.
+    // Half, Float, and double only.
     APFloatVal =3D APFloat(BitsToDouble(HexIntToVal(TokStart+2, CurPtr)));
     return lltok::APFloat;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/AsmParser/LLLexe=
r.h
--- a/head/contrib/llvm/lib/AsmParser/LLLexer.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/AsmParser/LLLexer.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -42,7 +42,6 @@
     APFloat APFloatVal;
     APSInt  APSIntVal;
=20
-    std::string TheError;
   public:
     explicit LLLexer(MemoryBuffer *StartBuf, SourceMgr &SM, SMDiagnostic &,
                      LLVMContext &C);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/AsmParser/LLPars=
er.cpp
--- a/head/contrib/llvm/lib/AsmParser/LLParser.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/AsmParser/LLParser.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -120,11 +120,6 @@
   for (Module::iterator FI =3D M->begin(), FE =3D M->end(); FI !=3D FE; )
     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
=20
-  // Upgrade to new EH scheme. N.B. This will go away in 3.1.
-  UpgradeExceptionHandling(M);
-
-  // Check debug info intrinsics.
-  CheckDebugInfoIntrinsics(M);
   return false;
 }
=20
@@ -879,7 +874,7 @@
 /// ParseOptionalAttrs - Parse a potentially empty attribute list.  AttrKi=
nd
 /// indicates what kind of attribute list this is: 0: function arg, 1: res=
ult,
 /// 2: function attr.
-bool LLParser::ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind) {
+bool LLParser::ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind) {
   Attrs =3D Attribute::None;
   LocTy AttrLoc =3D Lex.getLoc();
=20
@@ -924,6 +919,7 @@
     case lltok::kw_noimplicitfloat: Attrs |=3D Attribute::NoImplicitFloat;=
 break;
     case lltok::kw_naked:           Attrs |=3D Attribute::Naked; break;
     case lltok::kw_nonlazybind:     Attrs |=3D Attribute::NonLazyBind; bre=
ak;
+    case lltok::kw_address_safety:  Attrs |=3D Attribute::AddressSafety; b=
reak;
=20
     case lltok::kw_alignstack: {
       unsigned Alignment;
@@ -1047,13 +1043,11 @@
   case lltok::kw_cc: {
       unsigned ArbitraryCC;
       Lex.Lex();
-      if (ParseUInt32(ArbitraryCC)) {
+      if (ParseUInt32(ArbitraryCC))
         return true;
-      } else
-        CC =3D static_cast<CallingConv::ID>(ArbitraryCC);
-        return false;
+      CC =3D static_cast<CallingConv::ID>(ArbitraryCC);
+      return false;
     }
-    break;
   }
=20
   Lex.Lex();
@@ -1069,7 +1063,7 @@
       return TokError("expected metadata after comma");
=20
     std::string Name =3D Lex.getStrVal();
-    unsigned MDK =3D M->getMDKindID(Name.c_str());
+    unsigned MDK =3D M->getMDKindID(Name);
     Lex.Lex();
=20
     MDNode *Node;
@@ -1358,8 +1352,8 @@
     // Parse the argument.
     LocTy ArgLoc;
     Type *ArgTy =3D 0;
-    unsigned ArgAttrs1 =3D Attribute::None;
-    unsigned ArgAttrs2 =3D Attribute::None;
+    Attributes ArgAttrs1;
+    Attributes ArgAttrs2;
     Value *V;
     if (ParseType(ArgTy, ArgLoc))
       return true;
@@ -1399,7 +1393,7 @@
   } else {
     LocTy TypeLoc =3D Lex.getLoc();
     Type *ArgTy =3D 0;
-    unsigned Attrs;
+    Attributes Attrs;
     std::string Name;
=20
     if (ParseType(ArgTy) ||
@@ -1466,7 +1460,7 @@
   for (unsigned i =3D 0, e =3D ArgList.size(); i !=3D e; ++i) {
     if (!ArgList[i].Name.empty())
       return Error(ArgList[i].Loc, "argument name invalid in function type=
");
-    if (ArgList[i].Attrs !=3D 0)
+    if (ArgList[i].Attrs)
       return Error(ArgList[i].Loc,
                    "argument attributes invalid in function type");
   }
@@ -1612,7 +1606,8 @@
     if ((unsigned)Size !=3D Size)
       return Error(SizeLoc, "size too large for vector");
     if (!VectorType::isValidElementType(EltTy))
-      return Error(TypeLoc, "vector element type must be fp or integer");
+      return Error(TypeLoc,
+       "vector element type must be fp, integer or a pointer to these type=
s");
     Result =3D VectorType::get(EltTy, unsigned(Size));
   } else {
     if (!ArrayType::isValidElementType(EltTy))
@@ -1971,9 +1966,10 @@
       return Error(ID.Loc, "constant vector must not be empty");
=20
     if (!Elts[0]->getType()->isIntegerTy() &&
-        !Elts[0]->getType()->isFloatingPointTy())
+        !Elts[0]->getType()->isFloatingPointTy() &&
+        !Elts[0]->getType()->isPointerTy())
       return Error(FirstEltLoc,
-                   "vector elements must have integer or floating point ty=
pe");
+            "vector elements must have integer, pointer or floating point =
type");
=20
     // Verify that all the vector elements have the same type.
     for (unsigned i =3D 1, e =3D Elts.size(); i !=3D e; ++i)
@@ -2022,7 +2018,8 @@
   }
   case lltok::kw_c:  // c "foo"
     Lex.Lex();
-    ID.ConstantVal =3D ConstantArray::get(Context, Lex.getStrVal(), false);
+    ID.ConstantVal =3D ConstantDataArray::getString(Context, Lex.getStrVal=
(),
+                                                  false);
     if (ParseToken(lltok::StringConstant, "expected string")) return true;
     ID.Kind =3D ValID::t_Constant;
     return false;
@@ -2165,7 +2162,7 @@
     } else {
       assert(Opc =3D=3D Instruction::ICmp && "Unexpected opcode for CmpIns=
t!");
       if (!Val0->getType()->isIntOrIntVectorTy() &&
-          !Val0->getType()->isPointerTy())
+          !Val0->getType()->getScalarType()->isPointerTy())
         return Error(ID.Loc, "icmp requires pointer or integer operands");
       ID.ConstantVal =3D ConstantExpr::getICmp(Pred, Val0, Val1);
     }
@@ -2299,7 +2296,8 @@
       return true;
=20
     if (Opc =3D=3D Instruction::GetElementPtr) {
-      if (Elts.size() =3D=3D 0 || !Elts[0]->getType()->isPointerTy())
+      if (Elts.size() =3D=3D 0 ||
+          !Elts[0]->getType()->getScalarType()->isPointerTy())
         return Error(ID.Loc, "getelementptr requires pointer operand");
=20
       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
@@ -2440,7 +2438,6 @@
     return Error(ID.Loc, "functions are not values, refer to them as point=
ers");
=20
   switch (ID.Kind) {
-  default: llvm_unreachable("Unknown ValID!");
   case ValID::t_LocalID:
     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
     V =3D PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
@@ -2485,13 +2482,16 @@
         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
       return Error(ID.Loc, "floating point constant invalid for type");
=20
-    // The lexer has no type info, so builds all float and double FP const=
ants
-    // as double.  Fix this here.  Long double does not need this.
-    if (&ID.APFloatVal.getSemantics() =3D=3D &APFloat::IEEEdouble &&
-        Ty->isFloatTy()) {
+    // The lexer has no type info, so builds all half, float, and double FP
+    // constants as double.  Fix this here.  Long double does not need thi=
s.
+    if (&ID.APFloatVal.getSemantics() =3D=3D &APFloat::IEEEdouble) {
       bool Ignored;
-      ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToE=
ven,
-                            &Ignored);
+      if (Ty->isHalfTy())
+        ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToE=
ven,
+                              &Ignored);
+      else if (Ty->isFloatTy())
+        ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesT=
oEven,
+                              &Ignored);
     }
     V =3D ConstantFP::get(Context, ID.APFloatVal);
=20
@@ -2549,6 +2549,7 @@
       return Error(ID.Loc, "constant expression type mismatch");
     return false;
   }
+  llvm_unreachable("Invalid ValID");
 }
=20
 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
@@ -2585,7 +2586,8 @@
   LocTy LinkageLoc =3D Lex.getLoc();
   unsigned Linkage;
=20
-  unsigned Visibility, RetAttrs;
+  unsigned Visibility;
+  Attributes RetAttrs;
   CallingConv::ID CC;
   Type *RetType =3D 0;
   LocTy RetTypeLoc =3D Lex.getLoc();
@@ -2649,7 +2651,7 @@
=20
   SmallVector<ArgInfo, 8> ArgList;
   bool isVarArg;
-  unsigned FuncAttrs;
+  Attributes FuncAttrs;
   std::string Section;
   unsigned Alignment;
   std::string GC;
@@ -2835,7 +2837,7 @@
     }
=20
     switch (ParseInstruction(Inst, BB, PFS)) {
-    default: assert(0 && "Unknown ParseInstruction result!");
+    default: llvm_unreachable("Unknown ParseInstruction result!");
     case InstError: return true;
     case InstNormal:
       BB->getInstList().push_back(Inst);
@@ -2881,7 +2883,6 @@
   switch (Token) {
   default:                    return Error(Loc, "expected instruction opco=
de");
   // Terminator Instructions.
-  case lltok::kw_unwind:      Inst =3D new UnwindInst(Context); return fal=
se;
   case lltok::kw_unreachable: Inst =3D new UnreachableInst(Context); retur=
n false;
   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
   case lltok::kw_br:          return ParseBr(Inst, PFS);
@@ -2953,19 +2954,11 @@
   case lltok::kw_tail:           return ParseCall(Inst, PFS, true);
   // Memory.
   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
-  case lltok::kw_load:           return ParseLoad(Inst, PFS, false);
-  case lltok::kw_store:          return ParseStore(Inst, PFS, false);
+  case lltok::kw_load:           return ParseLoad(Inst, PFS);
+  case lltok::kw_store:          return ParseStore(Inst, PFS);
   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
   case lltok::kw_fence:          return ParseFence(Inst, PFS);
-  case lltok::kw_volatile:
-    // For compatibility; canonical location is after load
-    if (EatIfPresent(lltok::kw_load))
-      return ParseLoad(Inst, PFS, true);
-    else if (EatIfPresent(lltok::kw_store))
-      return ParseStore(Inst, PFS, true);
-    else
-      return TokError("expected 'load' or 'store'");
   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
@@ -3169,7 +3162,7 @@
 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
   LocTy CallLoc =3D Lex.getLoc();
-  unsigned RetAttrs, FnAttrs;
+  Attributes RetAttrs, FnAttrs;
   CallingConv::ID CC;
   Type *RetType =3D 0;
   LocTy RetTypeLoc;
@@ -3342,7 +3335,7 @@
   } else {
     assert(Opc =3D=3D Instruction::ICmp && "Unknown opcode for CmpInst!");
     if (!LHS->getType()->isIntOrIntVectorTy() &&
-        !LHS->getType()->isPointerTy())
+        !LHS->getType()->getScalarType()->isPointerTy())
       return Error(Loc, "icmp requires integer operands");
     Inst =3D new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
   }
@@ -3462,7 +3455,7 @@
     return true;
=20
   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
-    return Error(Loc, "invalid extractelement operands");
+    return Error(Loc, "invalid shufflevector operands");
=20
   Inst =3D new ShuffleVectorInst(Op0, Op1, Op2);
   return false;
@@ -3568,7 +3561,7 @@
 ///       ParameterList OptionalAttrs
 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
                          bool isTail) {
-  unsigned RetAttrs, FnAttrs;
+  Attributes RetAttrs, FnAttrs;
   CallingConv::ID CC;
   Type *RetType =3D 0;
   LocTy RetTypeLoc;
@@ -3689,10 +3682,7 @@
 ///   ::=3D 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
 ///   ::=3D 'load' 'atomic' 'volatile'? TypeAndValue=20
 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
-///   Compatibility:
-///   ::=3D 'volatile' 'load' TypeAndValue (',' 'align' i32)?
-int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS,
-                        bool isVolatile) {
+int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
   Value *Val; LocTy Loc;
   unsigned Alignment =3D 0;
   bool AteExtraComma =3D false;
@@ -3701,15 +3691,12 @@
   SynchronizationScope Scope =3D CrossThread;
=20
   if (Lex.getKind() =3D=3D lltok::kw_atomic) {
-    if (isVolatile)
-      return TokError("mixing atomic with old volatile placement");
     isAtomic =3D true;
     Lex.Lex();
   }
=20
+  bool isVolatile =3D false;
   if (Lex.getKind() =3D=3D lltok::kw_volatile) {
-    if (isVolatile)
-      return TokError("duplicate volatile before and after store");
     isVolatile =3D true;
     Lex.Lex();
   }
@@ -3736,10 +3723,7 @@
 ///   ::=3D 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align'=
 i32)?
 ///   ::=3D 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
-///   Compatibility:
-///   ::=3D 'volatile' 'store' TypeAndValue ',' TypeAndValue (',' 'align' =
i32)?
-int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS,
-                         bool isVolatile) {
+int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
   Value *Val, *Ptr; LocTy Loc, PtrLoc;
   unsigned Alignment =3D 0;
   bool AteExtraComma =3D false;
@@ -3748,15 +3732,12 @@
   SynchronizationScope Scope =3D CrossThread;
=20
   if (Lex.getKind() =3D=3D lltok::kw_atomic) {
-    if (isVolatile)
-      return TokError("mixing atomic with old volatile placement");
     isAtomic =3D true;
     Lex.Lex();
   }
=20
+  bool isVolatile =3D false;
   if (Lex.getKind() =3D=3D lltok::kw_volatile) {
-    if (isVolatile)
-      return TokError("duplicate volatile before and after store");
     isVolatile =3D true;
     Lex.Lex();
   }
@@ -3902,13 +3883,15 @@
 /// ParseGetElementPtr
 ///   ::=3D 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS=
) {
-  Value *Ptr, *Val; LocTy Loc, EltLoc;
+  Value *Ptr =3D 0;
+  Value *Val =3D 0;
+  LocTy Loc, EltLoc;
=20
   bool InBounds =3D EatIfPresent(lltok::kw_inbounds);
=20
   if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
=20
-  if (!Ptr->getType()->isPointerTy())
+  if (!Ptr->getType()->getScalarType()->isPointerTy())
     return Error(Loc, "base of getelementptr must be a pointer");
=20
   SmallVector<Value*, 16> Indices;
@@ -3919,11 +3902,23 @@
       break;
     }
     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
-    if (!Val->getType()->isIntegerTy())
+    if (!Val->getType()->getScalarType()->isIntegerTy())
       return Error(EltLoc, "getelementptr index must be an integer");
+    if (Val->getType()->isVectorTy() !=3D Ptr->getType()->isVectorTy())
+      return Error(EltLoc, "getelementptr index type missmatch");
+    if (Val->getType()->isVectorTy()) {
+      unsigned ValNumEl =3D cast<VectorType>(Val->getType())->getNumElemen=
ts();
+      unsigned PtrNumEl =3D cast<VectorType>(Ptr->getType())->getNumElemen=
ts();
+      if (ValNumEl !=3D PtrNumEl)
+        return Error(EltLoc,
+          "getelementptr vector index has a wrong number of elements");
+    }
     Indices.push_back(Val);
   }
=20
+  if (Val && Val->getType()->isVectorTy() && Indices.size() !=3D 1)
+    return Error(EltLoc, "vector getelementptrs must have a single index");
+
   if (!GetElementPtrInst::getIndexedType(Ptr->getType(), Indices))
     return Error(Loc, "invalid getelementptr indices");
   Inst =3D GetElementPtrInst::Create(Ptr, Indices);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/AsmParser/LLPars=
er.h
--- a/head/contrib/llvm/lib/AsmParser/LLParser.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/AsmParser/LLParser.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,6 +15,7 @@
 #define LLVM_ASMPARSER_LLPARSER_H
=20
 #include "LLLexer.h"
+#include "llvm/Attributes.h"
 #include "llvm/Instructions.h"
 #include "llvm/Module.h"
 #include "llvm/Type.h"
@@ -171,7 +172,7 @@
       return ParseUInt32(Val);
     }
     bool ParseOptionalAddrSpace(unsigned &AddrSpace);
-    bool ParseOptionalAttrs(unsigned &Attrs, unsigned AttrKind);
+    bool ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind);
     bool ParseOptionalLinkage(unsigned &Linkage, bool &HasLinkage);
     bool ParseOptionalLinkage(unsigned &Linkage) {
       bool HasLinkage; return ParseOptionalLinkage(Linkage, HasLinkage);
@@ -304,8 +305,8 @@
     struct ParamInfo {
       LocTy Loc;
       Value *V;
-      unsigned Attrs;
-      ParamInfo(LocTy loc, Value *v, unsigned attrs)
+      Attributes Attrs;
+      ParamInfo(LocTy loc, Value *v, Attributes attrs)
         : Loc(loc), V(v), Attrs(attrs) {}
     };
     bool ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
@@ -325,9 +326,9 @@
     struct ArgInfo {
       LocTy Loc;
       Type *Ty;
-      unsigned Attrs;
+      Attributes Attrs;
       std::string Name;
-      ArgInfo(LocTy L, Type *ty, unsigned Attr, const std::string &N)
+      ArgInfo(LocTy L, Type *ty, Attributes Attr, const std::string &N)
         : Loc(L), Ty(ty), Attrs(Attr), Name(N) {}
     };
     bool ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList, bool &isVarA=
rg);
@@ -363,8 +364,8 @@
     bool ParseLandingPad(Instruction *&I, PerFunctionState &PFS);
     bool ParseCall(Instruction *&I, PerFunctionState &PFS, bool isTail);
     int ParseAlloc(Instruction *&I, PerFunctionState &PFS);
-    int ParseLoad(Instruction *&I, PerFunctionState &PFS, bool isVolatile);
-    int ParseStore(Instruction *&I, PerFunctionState &PFS, bool isVolatile=
);
+    int ParseLoad(Instruction *&I, PerFunctionState &PFS);
+    int ParseStore(Instruction *&I, PerFunctionState &PFS);
     int ParseCmpXchg(Instruction *&I, PerFunctionState &PFS);
     int ParseAtomicRMW(Instruction *&I, PerFunctionState &PFS);
     int ParseFence(Instruction *&I, PerFunctionState &PFS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/AsmParser/LLToke=
n.h
--- a/head/contrib/llvm/lib/AsmParser/LLToken.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/AsmParser/LLToken.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -50,6 +50,7 @@
     kw_tail,
     kw_target,
     kw_triple,
+    kw_unwind,=20
     kw_deplibs,
     kw_datalayout,
     kw_volatile,
@@ -102,6 +103,7 @@
     kw_noimplicitfloat,
     kw_naked,
     kw_nonlazybind,
+    kw_address_safety,
=20
     kw_type,
     kw_opaque,
@@ -126,7 +128,7 @@
=20
     kw_landingpad, kw_personality, kw_cleanup, kw_catch, kw_filter,
=20
-    kw_ret, kw_br, kw_switch, kw_indirectbr, kw_invoke, kw_unwind, kw_resu=
me,
+    kw_ret, kw_br, kw_switch, kw_indirectbr, kw_invoke, kw_resume,
     kw_unreachable,
=20
     kw_alloca, kw_load, kw_store, kw_fence, kw_cmpxchg, kw_atomicrmw,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/AsmParser/Parser=
.cpp
--- a/head/contrib/llvm/lib/AsmParser/Parser.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/AsmParser/Parser.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -44,7 +44,7 @@
                                 LLVMContext &Context) {
   OwningPtr<MemoryBuffer> File;
   if (error_code ec =3D MemoryBuffer::getFileOrSTDIN(Filename.c_str(), Fil=
e)) {
-    Err =3D SMDiagnostic(Filename,
+    Err =3D SMDiagnostic(Filename, SourceMgr::DK_Error,
                        "Could not open input file: " + ec.message());
     return 0;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Bitcode/Reader/B=
itcodeReader.cpp
--- a/head/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -22,11 +22,19 @@
 #include "llvm/AutoUpgrade.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/DataStream.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/OperandTraits.h"
 using namespace llvm;
=20
+void BitcodeReader::materializeForwardReferencedFunctions() {
+  while (!BlockAddrFwdRefs.empty()) {
+    Function *F =3D BlockAddrFwdRefs.begin()->first;
+    F->Materialize();
+  }
+}
+
 void BitcodeReader::FreeState() {
   if (BufferOwned)
     delete Buffer;
@@ -394,7 +402,7 @@
   // The type table size is always specified correctly.
   if (ID >=3D TypeList.size())
     return 0;
- =20
+
   if (Type *Ty =3D TypeList[ID])
     return Ty;
=20
@@ -403,14 +411,6 @@
   return TypeList[ID] =3D StructType::create(Context);
 }
=20
-/// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
-Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
-  if (ID >=3D TypeList.size())
-    TypeList.resize(ID+1);
- =20
-  return TypeList[ID];
-}
-
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Functions for parsing blocks from the bitcode file
@@ -462,8 +462,8 @@
       // If Function attributes are using index 0 then transfer them
       // to index ~0. Index 0 is used for return value attributes but used=
 to be
       // used for function attributes.
-      Attributes RetAttribute =3D Attribute::None;
-      Attributes FnAttribute =3D Attribute::None;
+      Attributes RetAttribute;
+      Attributes FnAttribute;
       for (unsigned i =3D 0, e =3D Record.size(); i !=3D e; i +=3D 2) {
         // FIXME: remove in LLVM 3.0
         // The alignment is stored as a 16-bit raw value from bits 31--16.
@@ -473,23 +473,24 @@
         if (Alignment && !isPowerOf2_32(Alignment))
           return Error("Alignment is not a power of two.");
=20
-        Attributes ReconstitutedAttr =3D Record[i+1] & 0xffff;
+        Attributes ReconstitutedAttr(Record[i+1] & 0xffff);
         if (Alignment)
           ReconstitutedAttr |=3D Attribute::constructAlignmentFromInt(Alig=
nment);
-        ReconstitutedAttr |=3D (Record[i+1] & (0xffffull << 32)) >> 11;
-        Record[i+1] =3D ReconstitutedAttr;
+        ReconstitutedAttr |=3D
+            Attributes((Record[i+1] & (0xffffull << 32)) >> 11);
=20
+        Record[i+1] =3D ReconstitutedAttr.Raw();
         if (Record[i] =3D=3D 0)
-          RetAttribute =3D Record[i+1];
+          RetAttribute =3D ReconstitutedAttr;
         else if (Record[i] =3D=3D ~0U)
-          FnAttribute =3D Record[i+1];
+          FnAttribute =3D ReconstitutedAttr;
       }
=20
-      unsigned OldRetAttrs =3D (Attribute::NoUnwind|Attribute::NoReturn|
+      Attributes OldRetAttrs =3D (Attribute::NoUnwind|Attribute::NoReturn|
                               Attribute::ReadOnly|Attribute::ReadNone);
=20
       if (FnAttribute =3D=3D Attribute::None && RetAttribute !=3D Attribut=
e::None &&
-          (RetAttribute & OldRetAttrs) !=3D 0) {
+          (RetAttribute & OldRetAttrs)) {
         if (FnAttribute =3D=3D Attribute::None) { // add a slot so they ge=
t added.
           Record.push_back(~0U);
           Record.push_back(0);
@@ -506,8 +507,9 @@
         } else if (Record[i] =3D=3D ~0U) {
           if (FnAttribute !=3D Attribute::None)
             Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
-        } else if (Record[i+1] !=3D Attribute::None)
-          Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
+        } else if (Attributes(Record[i+1]) !=3D Attribute::None)
+          Attrs.push_back(AttributeWithIndex::get(Record[i],
+                                                  Attributes(Record[i+1]))=
);
       }
=20
       MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
@@ -521,7 +523,7 @@
 bool BitcodeReader::ParseTypeTable() {
   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
     return Error("Malformed block record");
- =20
+
   return ParseTypeTableBody();
 }
=20
@@ -533,7 +535,7 @@
   unsigned NumRecords =3D 0;
=20
   SmallString<64> TypeName;
- =20
+
   // Read all the records for this type table.
   while (1) {
     unsigned Code =3D Stream.ReadCode();
@@ -573,6 +575,9 @@
     case bitc::TYPE_CODE_VOID:      // VOID
       ResultTy =3D Type::getVoidTy(Context);
       break;
+    case bitc::TYPE_CODE_HALF:     // HALF
+      ResultTy =3D Type::getHalfTy(Context);
+      break;
     case bitc::TYPE_CODE_FLOAT:     // FLOAT
       ResultTy =3D Type::getFloatTy(Context);
       break;
@@ -615,12 +620,12 @@
       ResultTy =3D PointerType::get(ResultTy, AddressSpace);
       break;
     }
-    case bitc::TYPE_CODE_FUNCTION: {
+    case bitc::TYPE_CODE_FUNCTION_OLD: {
       // FIXME: attrid is dead, remove it in LLVM 3.0
       // FUNCTION: [vararg, attrid, retty, paramty x N]
       if (Record.size() < 3)
         return Error("Invalid FUNCTION type record");
-      std::vector<Type*> ArgTys;
+      SmallVector<Type*, 8> ArgTys;
       for (unsigned i =3D 3, e =3D Record.size(); i !=3D e; ++i) {
         if (Type *T =3D getTypeByID(Record[i]))
           ArgTys.push_back(T);
@@ -635,10 +640,29 @@
       ResultTy =3D FunctionType::get(ResultTy, ArgTys, Record[0]);
       break;
     }
+    case bitc::TYPE_CODE_FUNCTION: {
+      // FUNCTION: [vararg, retty, paramty x N]
+      if (Record.size() < 2)
+        return Error("Invalid FUNCTION type record");
+      SmallVector<Type*, 8> ArgTys;
+      for (unsigned i =3D 2, e =3D Record.size(); i !=3D e; ++i) {
+        if (Type *T =3D getTypeByID(Record[i]))
+          ArgTys.push_back(T);
+        else
+          break;
+      }
+     =20
+      ResultTy =3D getTypeByID(Record[1]);
+      if (ResultTy =3D=3D 0 || ArgTys.size() < Record.size()-2)
+        return Error("invalid type in function type");
+
+      ResultTy =3D FunctionType::get(ResultTy, ArgTys, Record[0]);
+      break;
+    }
     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
       if (Record.size() < 1)
         return Error("Invalid STRUCT type record");
-      std::vector<Type*> EltTys;
+      SmallVector<Type*, 8> EltTys;
       for (unsigned i =3D 1, e =3D Record.size(); i !=3D e; ++i) {
         if (Type *T =3D getTypeByID(Record[i]))
           EltTys.push_back(T);
@@ -728,247 +752,6 @@
   }
 }
=20
-// FIXME: Remove in LLVM 3.1
-bool BitcodeReader::ParseOldTypeTable() {
-  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_OLD))
-    return Error("Malformed block record");
-
-  if (!TypeList.empty())
-    return Error("Multiple TYPE_BLOCKs found!");
- =20
- =20
-  // While horrible, we have no good ordering of types in the bc file.  Ju=
st
-  // iteratively parse types out of the bc file in multiple passes until w=
e get
-  // them all.  Do this by saving a cursor for the start of the type block.
-  BitstreamCursor StartOfTypeBlockCursor(Stream);
- =20
-  unsigned NumTypesRead =3D 0;
- =20
-  SmallVector<uint64_t, 64> Record;
-RestartScan:
-  unsigned NextTypeID =3D 0;
-  bool ReadAnyTypes =3D false;
- =20
-  // Read all the records for this type table.
-  while (1) {
-    unsigned Code =3D Stream.ReadCode();
-    if (Code =3D=3D bitc::END_BLOCK) {
-      if (NextTypeID !=3D TypeList.size())
-        return Error("Invalid type forward reference in TYPE_BLOCK_ID_OLD"=
);
-     =20
-      // If we haven't read all of the types yet, iterate again.
-      if (NumTypesRead !=3D TypeList.size()) {
-        // If we didn't successfully read any types in this pass, then we =
must
-        // have an unhandled forward reference.
-        if (!ReadAnyTypes)
-          return Error("Obsolete bitcode contains unhandled recursive type=
");
-       =20
-        Stream =3D StartOfTypeBlockCursor;
-        goto RestartScan;
-      }
-     =20
-      if (Stream.ReadBlockEnd())
-        return Error("Error at end of type table block");
-      return false;
-    }
-   =20
-    if (Code =3D=3D bitc::ENTER_SUBBLOCK) {
-      // No known subblocks, always skip them.
-      Stream.ReadSubBlockID();
-      if (Stream.SkipBlock())
-        return Error("Malformed block record");
-      continue;
-    }
-   =20
-    if (Code =3D=3D bitc::DEFINE_ABBREV) {
-      Stream.ReadAbbrevRecord();
-      continue;
-    }
-   =20
-    // Read a record.
-    Record.clear();
-    Type *ResultTy =3D 0;
-    switch (Stream.ReadRecord(Code, Record)) {
-    default: return Error("unknown type in type table");
-    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
-      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
-      // type list.  This allows us to reserve space.
-      if (Record.size() < 1)
-        return Error("Invalid TYPE_CODE_NUMENTRY record");
-      TypeList.resize(Record[0]);
-      continue;
-    case bitc::TYPE_CODE_VOID:      // VOID
-      ResultTy =3D Type::getVoidTy(Context);
-      break;
-    case bitc::TYPE_CODE_FLOAT:     // FLOAT
-      ResultTy =3D Type::getFloatTy(Context);
-      break;
-    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
-      ResultTy =3D Type::getDoubleTy(Context);
-      break;
-    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
-      ResultTy =3D Type::getX86_FP80Ty(Context);
-      break;
-    case bitc::TYPE_CODE_FP128:     // FP128
-      ResultTy =3D Type::getFP128Ty(Context);
-      break;
-    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
-      ResultTy =3D Type::getPPC_FP128Ty(Context);
-      break;
-    case bitc::TYPE_CODE_LABEL:     // LABEL
-      ResultTy =3D Type::getLabelTy(Context);
-      break;
-    case bitc::TYPE_CODE_METADATA:  // METADATA
-      ResultTy =3D Type::getMetadataTy(Context);
-      break;
-    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
-      ResultTy =3D Type::getX86_MMXTy(Context);
-      break;
-    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
-      if (Record.size() < 1)
-        return Error("Invalid Integer type record");
-      ResultTy =3D IntegerType::get(Context, Record[0]);
-      break;
-    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
-      if (NextTypeID < TypeList.size() && TypeList[NextTypeID] =3D=3D 0)
-        ResultTy =3D StructType::create(Context);
-      break;
-    case bitc::TYPE_CODE_STRUCT_OLD: {// STRUCT_OLD
-      if (NextTypeID >=3D TypeList.size()) break;
-      // If we already read it, don't reprocess.
-      if (TypeList[NextTypeID] &&
-          !cast<StructType>(TypeList[NextTypeID])->isOpaque())
-        break;
-
-      // Set a type.
-      if (TypeList[NextTypeID] =3D=3D 0)
-        TypeList[NextTypeID] =3D StructType::create(Context);
-
-      std::vector<Type*> EltTys;
-      for (unsigned i =3D 1, e =3D Record.size(); i !=3D e; ++i) {
-        if (Type *Elt =3D getTypeByIDOrNull(Record[i]))
-          EltTys.push_back(Elt);
-        else
-          break;
-      }
-
-      if (EltTys.size() !=3D Record.size()-1)
-        break;      // Not all elements are ready.
-     =20
-      cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
-      ResultTy =3D TypeList[NextTypeID];
-      TypeList[NextTypeID] =3D 0;
-      break;
-    }
-    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
-      //          [pointee type, address space]
-      if (Record.size() < 1)
-        return Error("Invalid POINTER type record");
-      unsigned AddressSpace =3D 0;
-      if (Record.size() =3D=3D 2)
-        AddressSpace =3D Record[1];
-      if ((ResultTy =3D getTypeByIDOrNull(Record[0])))
-        ResultTy =3D PointerType::get(ResultTy, AddressSpace);
-      break;
-    }
-    case bitc::TYPE_CODE_FUNCTION: {
-      // FIXME: attrid is dead, remove it in LLVM 3.0
-      // FUNCTION: [vararg, attrid, retty, paramty x N]
-      if (Record.size() < 3)
-        return Error("Invalid FUNCTION type record");
-      std::vector<Type*> ArgTys;
-      for (unsigned i =3D 3, e =3D Record.size(); i !=3D e; ++i) {
-        if (Type *Elt =3D getTypeByIDOrNull(Record[i]))
-          ArgTys.push_back(Elt);
-        else
-          break;
-      }
-      if (ArgTys.size()+3 !=3D Record.size())
-        break;  // Something was null.
-      if ((ResultTy =3D getTypeByIDOrNull(Record[2])))
-        ResultTy =3D FunctionType::get(ResultTy, ArgTys, Record[0]);
-      break;
-    }
-    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
-      if (Record.size() < 2)
-        return Error("Invalid ARRAY type record");
-      if ((ResultTy =3D getTypeByIDOrNull(Record[1])))
-        ResultTy =3D ArrayType::get(ResultTy, Record[0]);
-      break;
-    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
-      if (Record.size() < 2)
-        return Error("Invalid VECTOR type record");
-      if ((ResultTy =3D getTypeByIDOrNull(Record[1])))
-        ResultTy =3D VectorType::get(ResultTy, Record[0]);
-      break;
-    }
-   =20
-    if (NextTypeID >=3D TypeList.size())
-      return Error("invalid TYPE table");
-   =20
-    if (ResultTy && TypeList[NextTypeID] =3D=3D 0) {
-      ++NumTypesRead;
-      ReadAnyTypes =3D true;
-     =20
-      TypeList[NextTypeID] =3D ResultTy;
-    }
-   =20
-    ++NextTypeID;
-  }
-}
-
-
-bool BitcodeReader::ParseOldTypeSymbolTable() {
-  if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID_OLD))
-    return Error("Malformed block record");
-
-  SmallVector<uint64_t, 64> Record;
-
-  // Read all the records for this type table.
-  std::string TypeName;
-  while (1) {
-    unsigned Code =3D Stream.ReadCode();
-    if (Code =3D=3D bitc::END_BLOCK) {
-      if (Stream.ReadBlockEnd())
-        return Error("Error at end of type symbol table block");
-      return false;
-    }
-
-    if (Code =3D=3D bitc::ENTER_SUBBLOCK) {
-      // No known subblocks, always skip them.
-      Stream.ReadSubBlockID();
-      if (Stream.SkipBlock())
-        return Error("Malformed block record");
-      continue;
-    }
-
-    if (Code =3D=3D bitc::DEFINE_ABBREV) {
-      Stream.ReadAbbrevRecord();
-      continue;
-    }
-
-    // Read a record.
-    Record.clear();
-    switch (Stream.ReadRecord(Code, Record)) {
-    default:  // Default behavior: unknown type.
-      break;
-    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
-      if (ConvertToString(Record, 1, TypeName))
-        return Error("Invalid TST_ENTRY record");
-      unsigned TypeID =3D Record[0];
-      if (TypeID >=3D TypeList.size())
-        return Error("Invalid Type ID in TST_ENTRY record");
-
-      // Only apply the type name to a struct type with no name.
-      if (StructType *STy =3D dyn_cast<StructType>(TypeList[TypeID]))
-        if (!STy->isLiteral() && !STy->hasName())
-          STy->setName(TypeName);
-      TypeName.clear();
-      break;
-    }
-  }
-}
-
 bool BitcodeReader::ParseValueSymbolTable() {
   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
     return Error("Malformed block record");
@@ -1262,7 +1045,9 @@
     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
       if (Record.empty())
         return Error("Invalid FLOAT record");
-      if (CurTy->isFloatTy())
+      if (CurTy->isHalfTy())
+        V =3D ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[=
0])));
+      else if (CurTy->isFloatTy())
         V =3D ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[=
0])));
       else if (CurTy->isDoubleTy())
         V =3D ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
@@ -1286,7 +1071,7 @@
         return Error("Invalid CST_AGGREGATE record");
=20
       unsigned Size =3D Record.size();
-      std::vector<Constant*> Elts;
+      SmallVector<Constant*, 16> Elts;
=20
       if (StructType *STy =3D dyn_cast<StructType>(CurTy)) {
         for (unsigned i =3D 0; i !=3D Size; ++i)
@@ -1308,35 +1093,78 @@
       }
       break;
     }
-    case bitc::CST_CODE_STRING: { // STRING: [values]
+    case bitc::CST_CODE_STRING:    // STRING: [values]
+    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
       if (Record.empty())
-        return Error("Invalid CST_AGGREGATE record");
-
-      ArrayType *ATy =3D cast<ArrayType>(CurTy);
-      Type *EltTy =3D ATy->getElementType();
+        return Error("Invalid CST_STRING record");
=20
       unsigned Size =3D Record.size();
-      std::vector<Constant*> Elts;
+      SmallString<16> Elts;
       for (unsigned i =3D 0; i !=3D Size; ++i)
-        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
-      V =3D ConstantArray::get(ATy, Elts);
+        Elts.push_back(Record[i]);
+      V =3D ConstantDataArray::getString(Context, Elts,
+                                       BitCode =3D=3D bitc::CST_CODE_CSTRI=
NG);
       break;
     }
-    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
+    case bitc::CST_CODE_DATA: {// DATA: [n x value]
       if (Record.empty())
-        return Error("Invalid CST_AGGREGATE record");
-
-      ArrayType *ATy =3D cast<ArrayType>(CurTy);
-      Type *EltTy =3D ATy->getElementType();
-
+        return Error("Invalid CST_DATA record");
+     =20
+      Type *EltTy =3D cast<SequentialType>(CurTy)->getElementType();
       unsigned Size =3D Record.size();
-      std::vector<Constant*> Elts;
-      for (unsigned i =3D 0; i !=3D Size; ++i)
-        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
-      Elts.push_back(Constant::getNullValue(EltTy));
-      V =3D ConstantArray::get(ATy, Elts);
+     =20
+      if (EltTy->isIntegerTy(8)) {
+        SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
+        if (isa<VectorType>(CurTy))
+          V =3D ConstantDataVector::get(Context, Elts);
+        else
+          V =3D ConstantDataArray::get(Context, Elts);
+      } else if (EltTy->isIntegerTy(16)) {
+        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
+        if (isa<VectorType>(CurTy))
+          V =3D ConstantDataVector::get(Context, Elts);
+        else
+          V =3D ConstantDataArray::get(Context, Elts);
+      } else if (EltTy->isIntegerTy(32)) {
+        SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
+        if (isa<VectorType>(CurTy))
+          V =3D ConstantDataVector::get(Context, Elts);
+        else
+          V =3D ConstantDataArray::get(Context, Elts);
+      } else if (EltTy->isIntegerTy(64)) {
+        SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
+        if (isa<VectorType>(CurTy))
+          V =3D ConstantDataVector::get(Context, Elts);
+        else
+          V =3D ConstantDataArray::get(Context, Elts);
+      } else if (EltTy->isFloatTy()) {
+        SmallVector<float, 16> Elts;
+        for (unsigned i =3D 0; i !=3D Size; ++i) {
+          union { uint32_t I; float F; };
+          I =3D Record[i];
+          Elts.push_back(F);
+        }
+        if (isa<VectorType>(CurTy))
+          V =3D ConstantDataVector::get(Context, Elts);
+        else
+          V =3D ConstantDataArray::get(Context, Elts);
+      } else if (EltTy->isDoubleTy()) {
+        SmallVector<double, 16> Elts;
+        for (unsigned i =3D 0; i !=3D Size; ++i) {
+          union { uint64_t I; double F; };
+          I =3D Record[i];
+          Elts.push_back(F);
+        }
+        if (isa<VectorType>(CurTy))
+          V =3D ConstantDataVector::get(Context, Elts);
+        else
+          V =3D ConstantDataArray::get(Context, Elts);
+      } else {
+        return Error("Unknown element type in CE_DATA");
+      }
       break;
     }
+
     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
       int Opc =3D GetDecodedBinaryOpcode(Record[0], CurTy);
@@ -1517,6 +1345,50 @@
   return false;
 }
=20
+bool BitcodeReader::ParseUseLists() {
+  if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
+    return Error("Malformed block record");
+
+  SmallVector<uint64_t, 64> Record;
+ =20
+  // Read all the records.
+  while (1) {
+    unsigned Code =3D Stream.ReadCode();
+    if (Code =3D=3D bitc::END_BLOCK) {
+      if (Stream.ReadBlockEnd())
+        return Error("Error at end of use-list table block");
+      return false;
+    }
+   =20
+    if (Code =3D=3D bitc::ENTER_SUBBLOCK) {
+      // No known subblocks, always skip them.
+      Stream.ReadSubBlockID();
+      if (Stream.SkipBlock())
+        return Error("Malformed block record");
+      continue;
+    }
+   =20
+    if (Code =3D=3D bitc::DEFINE_ABBREV) {
+      Stream.ReadAbbrevRecord();
+      continue;
+    }
+   =20
+    // Read a use list record.
+    Record.clear();
+    switch (Stream.ReadRecord(Code, Record)) {
+    default:  // Default behavior: unknown type.
+      break;
+    case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
+      unsigned RecordLength =3D Record.size();
+      if (RecordLength < 1)
+        return Error ("Invalid UseList reader!");
+      UseListRecords.push_back(Record);
+      break;
+    }
+    }
+  }
+}
+
 /// RememberAndSkipFunctionBody - When we see the block for a function bod=
y,
 /// remember where it is and then skip it.  This lets us lazily deserializ=
e the
 /// functions.
@@ -1538,8 +1410,36 @@
   return false;
 }
=20
-bool BitcodeReader::ParseModule() {
-  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
+bool BitcodeReader::GlobalCleanup() {
+  // Patch the initializers for globals and aliases up.
+  ResolveGlobalAndAliasInits();
+  if (!GlobalInits.empty() || !AliasInits.empty())
+    return Error("Malformed global initializer set");
+
+  // Look for intrinsic functions which need to be upgraded at some point
+  for (Module::iterator FI =3D TheModule->begin(), FE =3D TheModule->end();
+       FI !=3D FE; ++FI) {
+    Function *NewFn;
+    if (UpgradeIntrinsicFunction(FI, NewFn))
+      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
+  }
+
+  // Look for global variables which need to be renamed.
+  for (Module::global_iterator
+         GI =3D TheModule->global_begin(), GE =3D TheModule->global_end();
+       GI !=3D GE; ++GI)
+    UpgradeGlobalVariable(GI);
+  // Force deallocation of memory for these vectors to favor the client th=
at
+  // want lazy deserialization.
+  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
+  std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
+  return false;
+}
+
+bool BitcodeReader::ParseModule(bool Resume) {
+  if (Resume)
+    Stream.JumpToBit(NextUnreadBit);
+  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
     return Error("Malformed block record");
=20
   SmallVector<uint64_t, 64> Record;
@@ -1553,33 +1453,7 @@
       if (Stream.ReadBlockEnd())
         return Error("Error at end of module block");
=20
-      // Patch the initializers for globals and aliases up.
-      ResolveGlobalAndAliasInits();
-      if (!GlobalInits.empty() || !AliasInits.empty())
-        return Error("Malformed global initializer set");
-      if (!FunctionsWithBodies.empty())
-        return Error("Too few function bodies found");
-
-      // Look for intrinsic functions which need to be upgraded at some po=
int
-      for (Module::iterator FI =3D TheModule->begin(), FE =3D TheModule->e=
nd();
-           FI !=3D FE; ++FI) {
-        Function* NewFn;
-        if (UpgradeIntrinsicFunction(FI, NewFn))
-          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
-      }
-
-      // Look for global variables which need to be renamed.
-      for (Module::global_iterator
-             GI =3D TheModule->global_begin(), GE =3D TheModule->global_en=
d();
-           GI !=3D GE; ++GI)
-        UpgradeGlobalVariable(GI);
-
-      // Force deallocation of memory for these vectors to favor the clien=
t that
-      // want lazy deserialization.
-      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInit=
s);
-      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
-      std::vector<Function*>().swap(FunctionsWithBodies);
-      return false;
+      return GlobalCleanup();
     }
=20
     if (Code =3D=3D bitc::ENTER_SUBBLOCK) {
@@ -1600,17 +1474,10 @@
         if (ParseTypeTable())
           return true;
         break;
-      case bitc::TYPE_BLOCK_ID_OLD:
-        if (ParseOldTypeTable())
-          return true;
-        break;
-      case bitc::TYPE_SYMTAB_BLOCK_ID_OLD:
-        if (ParseOldTypeSymbolTable())
-          return true;
-        break;
       case bitc::VALUE_SYMTAB_BLOCK_ID:
         if (ParseValueSymbolTable())
           return true;
+        SeenValueSymbolTable =3D true;
         break;
       case bitc::CONSTANTS_BLOCK_ID:
         if (ParseConstants() || ResolveGlobalAndAliasInits())
@@ -1623,13 +1490,29 @@
       case bitc::FUNCTION_BLOCK_ID:
         // If this is the first function body we've seen, reverse the
         // FunctionsWithBodies list.
-        if (!HasReversedFunctionsWithBodies) {
+        if (!SeenFirstFunctionBody) {
           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.en=
d());
-          HasReversedFunctionsWithBodies =3D true;
+          if (GlobalCleanup())
+            return true;
+          SeenFirstFunctionBody =3D true;
         }
=20
         if (RememberAndSkipFunctionBody())
           return true;
+        // For streaming bitcode, suspend parsing when we reach the functi=
on
+        // bodies. Subsequent materialization calls will resume it when
+        // necessary. For streaming, the function bodies must be at the en=
d of
+        // the bitcode. If the bitcode file is old, the symbol table will =
be
+        // at the end instead and will not have been seen yet. In this cas=
e,
+        // just finish the parse now.
+        if (LazyStreamer && SeenValueSymbolTable) {
+          NextUnreadBit =3D Stream.GetCurrentBitNo();
+          return false;
+        }
+        break;
+      case bitc::USELIST_BLOCK_ID:
+        if (ParseUseLists())
+          return true;
         break;
       }
       continue;
@@ -1784,8 +1667,10 @@
=20
       // If this is a function with a body, remember the prototype we are
       // creating now, so that we can match up the body with them later.
-      if (!isProto)
+      if (!isProto) {
         FunctionsWithBodies.push_back(Func);
+        if (LazyStreamer) DeferredFunctionInfo[Func] =3D 0;
+      }
       break;
     }
     // ALIAS: [alias type, aliasee val#, linkage]
@@ -1824,24 +1709,7 @@
 bool BitcodeReader::ParseBitcodeInto(Module *M) {
   TheModule =3D 0;
=20
-  unsigned char *BufPtr =3D (unsigned char *)Buffer->getBufferStart();
-  unsigned char *BufEnd =3D BufPtr+Buffer->getBufferSize();
-
-  if (Buffer->getBufferSize() & 3) {
-    if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
-      return Error("Invalid bitcode signature");
-    else
-      return Error("Bitcode stream should be a multiple of 4 bytes in leng=
th");
-  }
-
-  // If we have a wrapper header, parse it and ignore the non-bc file cont=
ents.
-  // The magic number is 0x0B17C0DE stored in little endian.
-  if (isBitcodeWrapper(BufPtr, BufEnd))
-    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
-      return Error("Invalid bitcode wrapper header");
-
-  StreamFile.init(BufPtr, BufEnd);
-  Stream.init(StreamFile);
+  if (InitStream()) return true;
=20
   // Sniff for the signature.
   if (Stream.Read(8) !=3D 'B' ||
@@ -1883,8 +1751,9 @@
       if (TheModule)
         return Error("Multiple MODULE_BLOCKs in same stream");
       TheModule =3D M;
-      if (ParseModule())
+      if (ParseModule(false))
         return true;
+      if (LazyStreamer) return false;
       break;
     default:
       if (Stream.SkipBlock())
@@ -1952,20 +1821,7 @@
 }
=20
 bool BitcodeReader::ParseTriple(std::string &Triple) {
-  if (Buffer->getBufferSize() & 3)
-    return Error("Bitcode stream should be a multiple of 4 bytes in length=
");
-
-  unsigned char *BufPtr =3D (unsigned char *)Buffer->getBufferStart();
-  unsigned char *BufEnd =3D BufPtr+Buffer->getBufferSize();
-
-  // If we have a wrapper header, parse it and ignore the non-bc file cont=
ents.
-  // The magic number is 0x0B17C0DE stored in little endian.
-  if (isBitcodeWrapper(BufPtr, BufEnd))
-    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
-      return Error("Invalid bitcode wrapper header");
-
-  StreamFile.init(BufPtr, BufEnd);
-  Stream.init(StreamFile);
+  if (InitStream()) return true;
=20
   // Sniff for the signature.
   if (Stream.Read(8) !=3D 'B' ||
@@ -2517,10 +2373,6 @@
       InstructionList.push_back(I);
       break;
     }
-    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
-      I =3D new UnwindInst(Context);
-      InstructionList.push_back(I);
-      break;
     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
       I =3D new UnreachableInst(Context);
       InstructionList.push_back(I);
@@ -2845,6 +2697,19 @@
   return false;
 }
=20
+/// FindFunctionInStream - Find the function body in the bitcode stream
+bool BitcodeReader::FindFunctionInStream(Function *F,
+       DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterato=
r) {
+  while (DeferredFunctionInfoIterator->second =3D=3D 0) {
+    if (Stream.AtEndOfStream())
+      return Error("Could not find Function in stream");
+    // ParseModule will parse the next body in the stream and set its
+    // position in the DeferredFunctionInfo map.
+    if (ParseModule(true)) return true;
+  }
+  return false;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // GVMaterializer implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2865,6 +2730,10 @@
=20
   DenseMap<Function*, uint64_t>::iterator DFII =3D DeferredFunctionInfo.fi=
nd(F);
   assert(DFII !=3D DeferredFunctionInfo.end() && "Deferred function not fo=
und!");
+  // If its position is recorded as 0, its body is somewhere in the stream
+  // but we haven't seen it yet.
+  if (DFII->second =3D=3D 0)
+    if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
=20
   // Move the bit stream to the saved position of the deferred function bo=
dy.
   Stream.JumpToBit(DFII->second);
@@ -2920,6 +2789,12 @@
         Materialize(F, ErrInfo))
       return true;
=20
+  // At this point, if there are any function bodies, the current bit is
+  // pointing to the END_BLOCK record after them. Now make sure the rest
+  // of the bits in the module have been read.
+  if (NextUnreadBit)
+    ParseModule(true);
+
   // Upgrade any intrinsic calls that slipped through (should not happen!)=
 and
   // delete the old functions to clean up. We can't do this unless the ent=
ire
   // module is materialized because there could always be another function=
 body
@@ -2939,15 +2814,60 @@
   }
   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
=20
-  // Upgrade to new EH scheme. N.B. This will go away in 3.1.
-  UpgradeExceptionHandling(M);
+  return false;
+}
=20
-  // Check debug info intrinsics.
-  CheckDebugInfoIntrinsics(TheModule);
+bool BitcodeReader::InitStream() {
+  if (LazyStreamer) return InitLazyStream();
+  return InitStreamFromBuffer();
+}
+
+bool BitcodeReader::InitStreamFromBuffer() {
+  const unsigned char *BufPtr =3D (unsigned char *)Buffer->getBufferStart(=
);
+  const unsigned char *BufEnd =3D BufPtr+Buffer->getBufferSize();
+
+  if (Buffer->getBufferSize() & 3) {
+    if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
+      return Error("Invalid bitcode signature");
+    else
+      return Error("Bitcode stream should be a multiple of 4 bytes in leng=
th");
+  }
+
+  // If we have a wrapper header, parse it and ignore the non-bc file cont=
ents.
+  // The magic number is 0x0B17C0DE stored in little endian.
+  if (isBitcodeWrapper(BufPtr, BufEnd))
+    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
+      return Error("Invalid bitcode wrapper header");
+
+  StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
+  Stream.init(*StreamFile);
=20
   return false;
 }
=20
+bool BitcodeReader::InitLazyStream() {
+  // Check and strip off the bitcode wrapper; BitstreamReader expects neve=
r to
+  // see it.
+  StreamingMemoryObject *Bytes =3D new StreamingMemoryObject(LazyStreamer);
+  StreamFile.reset(new BitstreamReader(Bytes));
+  Stream.init(*StreamFile);
+
+  unsigned char buf[16];
+  if (Bytes->readBytes(0, 16, buf, NULL) =3D=3D -1)
+    return Error("Bitcode stream must be at least 16 bytes in length");
+
+  if (!isBitcode(buf, buf + 16))
+    return Error("Invalid bitcode signature");
+
+  if (isBitcodeWrapper(buf, buf + 4)) {
+    const unsigned char *bitcodeStart =3D buf;
+    const unsigned char *bitcodeEnd =3D buf + 16;
+    SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
+    Bytes->dropLeadingBytes(bitcodeStart - buf);
+    Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
+  }
+  return false;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // External interface
@@ -2970,6 +2890,27 @@
   }
   // Have the BitcodeReader dtor delete 'Buffer'.
   R->setBufferOwned(true);
+
+  R->materializeForwardReferencedFunctions();
+
+  return M;
+}
+
+
+Module *llvm::getStreamedBitcodeModule(const std::string &name,
+                                       DataStreamer *streamer,
+                                       LLVMContext &Context,
+                                       std::string *ErrMsg) {
+  Module *M =3D new Module(name, Context);
+  BitcodeReader *R =3D new BitcodeReader(streamer, Context);
+  M->setMaterializer(R);
+  if (R->ParseBitcodeInto(M)) {
+    if (ErrMsg)
+      *ErrMsg =3D R->getErrorString();
+    delete M;  // Also deletes R.
+    return 0;
+  }
+  R->setBufferOwned(false); // no buffer to delete
   return M;
 }
=20
@@ -2990,6 +2931,9 @@
     return 0;
   }
=20
+  // TODO: Restore the use-lists to the in-memory state when the bitcode w=
as
+  // written.  We must defer until the Module has been fully materialized.
+
   return M;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Bitcode/Reader/B=
itcodeReader.h
--- a/head/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Bitcode/Reader/BitcodeReader.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -126,8 +126,11 @@
   Module *TheModule;
   MemoryBuffer *Buffer;
   bool BufferOwned;
-  BitstreamReader StreamFile;
+  OwningPtr<BitstreamReader> StreamFile;
   BitstreamCursor Stream;
+  DataStreamer *LazyStreamer;
+  uint64_t NextUnreadBit;
+  bool SeenValueSymbolTable;
  =20
   const char *ErrorString;
  =20
@@ -135,6 +138,7 @@
   BitcodeReaderValueList ValueList;
   BitcodeReaderMDValueList MDValueList;
   SmallVector<Instruction *, 64> InstructionList;
+  SmallVector<SmallVector<uint64_t, 64>, 64> UseListRecords;
=20
   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
@@ -160,9 +164,10 @@
   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
   DenseMap<unsigned, unsigned> MDKindMap;
  =20
-  // After the module header has been read, the FunctionsWithBodies list i=
s=20
-  // reversed.  This keeps track of whether we've done this yet.
-  bool HasReversedFunctionsWithBodies;
+  // Several operations happen after the module header has been read, but
+  // before function bodies are processed. This keeps track of whether
+  // we've done this yet.
+  bool SeenFirstFunctionBody;
  =20
   /// DeferredFunctionInfo - When function bodies are initially scanned, t=
his
   /// map contains info about where to find deferred function body in the
@@ -177,13 +182,22 @@
 public:
   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
     : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
-      ErrorString(0), ValueList(C), MDValueList(C) {
-    HasReversedFunctionsWithBodies =3D false;
+      LazyStreamer(0), NextUnreadBit(0), SeenValueSymbolTable(false),
+      ErrorString(0), ValueList(C), MDValueList(C),
+      SeenFirstFunctionBody(false) {
+  }
+  explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
+    : Context(C), TheModule(0), Buffer(0), BufferOwned(false),
+      LazyStreamer(streamer), NextUnreadBit(0), SeenValueSymbolTable(false=
),
+      ErrorString(0), ValueList(C), MDValueList(C),
+      SeenFirstFunctionBody(false) {
   }
   ~BitcodeReader() {
     FreeState();
   }
- =20
+
+  void materializeForwardReferencedFunctions();
+
   void FreeState();
  =20
   /// setBufferOwned - If this is true, the reader will destroy the Memory=
Buffer
@@ -211,7 +225,6 @@
   bool ParseTriple(std::string &Triple);
 private:
   Type *getTypeByID(unsigned ID);
-  Type *getTypeByIDOrNull(unsigned ID);
   Value *getFnValueByID(unsigned ID, Type *Ty) {
     if (Ty && Ty->isMetadataTy())
       return MDValueList.getValueFwdRef(ID);
@@ -256,21 +269,26 @@
   }
=20
  =20
-  bool ParseModule();
+  bool ParseModule(bool Resume);
   bool ParseAttributeBlock();
   bool ParseTypeTable();
-  bool ParseOldTypeTable();         // FIXME: Remove in LLVM 3.1
   bool ParseTypeTableBody();
=20
-  bool ParseOldTypeSymbolTable();   // FIXME: Remove in LLVM 3.1
   bool ParseValueSymbolTable();
   bool ParseConstants();
   bool RememberAndSkipFunctionBody();
   bool ParseFunctionBody(Function *F);
+  bool GlobalCleanup();
   bool ResolveGlobalAndAliasInits();
   bool ParseMetadata();
   bool ParseMetadataAttachment();
   bool ParseModuleTriple(std::string &Triple);
+  bool ParseUseLists();
+  bool InitStream();
+  bool InitStreamFromBuffer();
+  bool InitLazyStream();
+  bool FindFunctionInStream(Function *F,
+         DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoItera=
tor);
 };
  =20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Bitcode/Writer/B=
itcodeWriter.cpp
--- a/head/contrib/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -23,6 +23,7 @@
 #include "llvm/Operator.h"
 #include "llvm/ValueSymbolTable.h"
 #include "llvm/ADT/Triple.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
@@ -31,6 +32,12 @@
 #include <map>
 using namespace llvm;
=20
+static cl::opt<bool>
+EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
+                              cl::desc("Turn on experimental support for "
+                                       "use-list order preservation."),
+                              cl::init(false), cl::Hidden);
+
 /// These are manifest constants used by the bitcode writer. They do not n=
eed to
 /// be kept in sync with the reader, but need to be consistent within this=
 file.
 enum {
@@ -119,7 +126,6 @@
=20
 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
   switch (Ordering) {
-  default: llvm_unreachable("Unknown atomic ordering");
   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
   case Unordered: return bitc::ORDERING_UNORDERED;
   case Monotonic: return bitc::ORDERING_MONOTONIC;
@@ -128,14 +134,15 @@
   case AcquireRelease: return bitc::ORDERING_ACQREL;
   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
   }
+  llvm_unreachable("Invalid ordering");
 }
=20
 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
   switch (SynchScope) {
-  default: llvm_unreachable("Unknown synchronization scope");
   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
   }
+  llvm_unreachable("Invalid synch scope");
 }
=20
 static void WriteStringRecord(unsigned Code, StringRef Str,
@@ -172,10 +179,11 @@
       // Store the alignment in the bitcode as a 16-bit raw value instead =
of a
       // 5-bit log2 encoded value. Shift the bits above the alignment up by
       // 11 bits.
-      uint64_t FauxAttr =3D PAWI.Attrs & 0xffff;
+      uint64_t FauxAttr =3D PAWI.Attrs.Raw() & 0xffff;
       if (PAWI.Attrs & Attribute::Alignment)
-        FauxAttr |=3D (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1)=
 >> 16);
-      FauxAttr |=3D (PAWI.Attrs & (0x3FFull << 21)) << 11;
+        FauxAttr |=3D (1ull<<16)<<
+            (((PAWI.Attrs & Attribute::Alignment).Raw()-1) >> 16);
+      FauxAttr |=3D (PAWI.Attrs.Raw() & (0x3FFull << 21)) << 11;
=20
       Record.push_back(FauxAttr);
     }
@@ -194,11 +202,12 @@
   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs *=
/);
   SmallVector<uint64_t, 64> TypeVals;
=20
+  uint64_t NumBits =3D Log2_32_Ceil(VE.getTypes().size()+1);
+
   // Abbrev for TYPE_CODE_POINTER.
   BitCodeAbbrev *Abbv =3D new BitCodeAbbrev();
   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
-                            Log2_32_Ceil(VE.getTypes().size()+1)));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace =3D 0
   unsigned PtrAbbrev =3D Stream.EmitAbbrev(Abbv);
=20
@@ -206,10 +215,9 @@
   Abbv =3D new BitCodeAbbrev();
   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
-  Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
-                            Log2_32_Ceil(VE.getTypes().size()+1)));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
+
   unsigned FunctionAbbrev =3D Stream.EmitAbbrev(Abbv);
=20
   // Abbrev for TYPE_CODE_STRUCT_ANON.
@@ -217,8 +225,8 @@
   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
-                            Log2_32_Ceil(VE.getTypes().size()+1)));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
+
   unsigned StructAnonAbbrev =3D Stream.EmitAbbrev(Abbv);
=20
   // Abbrev for TYPE_CODE_STRUCT_NAME.
@@ -233,16 +241,16 @@
   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
-                            Log2_32_Ceil(VE.getTypes().size()+1)));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
+
   unsigned StructNamedAbbrev =3D Stream.EmitAbbrev(Abbv);
  =20
   // Abbrev for TYPE_CODE_ARRAY.
   Abbv =3D new BitCodeAbbrev();
   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
-  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
-                            Log2_32_Ceil(VE.getTypes().size()+1)));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
+
   unsigned ArrayAbbrev =3D Stream.EmitAbbrev(Abbv);
=20
   // Emit an entry count so the reader can reserve space.
@@ -259,6 +267,7 @@
     switch (T->getTypeID()) {
     default: llvm_unreachable("Unknown type!");
     case Type::VoidTyID:      Code =3D bitc::TYPE_CODE_VOID;   break;
+    case Type::HalfTyID:      Code =3D bitc::TYPE_CODE_HALF;   break;
     case Type::FloatTyID:     Code =3D bitc::TYPE_CODE_FLOAT;  break;
     case Type::DoubleTyID:    Code =3D bitc::TYPE_CODE_DOUBLE; break;
     case Type::X86_FP80TyID:  Code =3D bitc::TYPE_CODE_X86_FP80; break;
@@ -284,10 +293,9 @@
     }
     case Type::FunctionTyID: {
       FunctionType *FT =3D cast<FunctionType>(T);
-      // FUNCTION: [isvararg, attrid, retty, paramty x N]
+      // FUNCTION: [isvararg, retty, paramty x N]
       Code =3D bitc::TYPE_CODE_FUNCTION;
       TypeVals.push_back(FT->isVarArg());
-      TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
       for (unsigned i =3D 0, e =3D FT->getNumParams(); i !=3D e; ++i)
         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
@@ -350,7 +358,6 @@
=20
 static unsigned getEncodedLinkage(const GlobalValue *GV) {
   switch (GV->getLinkage()) {
-  default: llvm_unreachable("Invalid linkage!");
   case GlobalValue::ExternalLinkage:                 return 0;
   case GlobalValue::WeakAnyLinkage:                  return 1;
   case GlobalValue::AppendingLinkage:                return 2;
@@ -368,15 +375,16 @@
   case GlobalValue::LinkerPrivateWeakLinkage:        return 14;
   case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
   }
+  llvm_unreachable("Invalid linkage");
 }
=20
 static unsigned getEncodedVisibility(const GlobalValue *GV) {
   switch (GV->getVisibility()) {
-  default: llvm_unreachable("Invalid visibility!");
   case GlobalValue::DefaultVisibility:   return 0;
   case GlobalValue::HiddenVisibility:    return 1;
   case GlobalValue::ProtectedVisibility: return 2;
   }
+  llvm_unreachable("Invalid visibility");
 }
=20
 // Emit top-level description of module, including target triple, inline a=
sm,
@@ -499,8 +507,8 @@
=20
   // Emit the function proto information.
   for (Module::const_iterator F =3D M->begin(), E =3D M->end(); F !=3D E; =
++F) {
-    // FUNCTION:  [type, callingconv, isproto, paramattr,
-    //             linkage, alignment, section, visibility, gc, unnamed_ad=
dr]
+    // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignm=
ent,
+    //             section, visibility, gc, unnamed_addr]
     Vals.push_back(VE.getTypeID(F->getType()));
     Vals.push_back(F->getCallingConv());
     Vals.push_back(F->isDeclaration());
@@ -520,6 +528,7 @@
   // Emit the alias information.
   for (Module::const_alias_iterator AI =3D M->alias_begin(), E =3D M->alia=
s_end();
        AI !=3D E; ++AI) {
+    // ALIAS: [alias type, aliasee val#, linkage, visibility]
     Vals.push_back(VE.getTypeID(AI->getType()));
     Vals.push_back(VE.getValueID(AI->getAliasee()));
     Vals.push_back(getEncodedLinkage(AI));
@@ -819,7 +828,7 @@
     } else if (const ConstantFP *CFP =3D dyn_cast<ConstantFP>(C)) {
       Code =3D bitc::CST_CODE_FLOAT;
       Type *Ty =3D CFP->getType();
-      if (Ty->isFloatTy() || Ty->isDoubleTy()) {
+      if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue(=
));
       } else if (Ty->isX86_FP80Ty()) {
         // api needed to prevent premature destruction
@@ -836,34 +845,56 @@
       } else {
         assert (0 && "Unknown FP type!");
       }
-    } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()=
) {
-      const ConstantArray *CA =3D cast<ConstantArray>(C);
+    } else if (isa<ConstantDataSequential>(C) &&
+               cast<ConstantDataSequential>(C)->isString()) {
+      const ConstantDataSequential *Str =3D cast<ConstantDataSequential>(C=
);
       // Emit constant strings specially.
-      unsigned NumOps =3D CA->getNumOperands();
+      unsigned NumElts =3D Str->getNumElements();
       // If this is a null-terminated string, use the denser CSTRING encod=
ing.
-      if (CA->getOperand(NumOps-1)->isNullValue()) {
+      if (Str->isCString()) {
         Code =3D bitc::CST_CODE_CSTRING;
-        --NumOps;  // Don't encode the null, which isn't allowed by char6.
+        --NumElts;  // Don't encode the null, which isn't allowed by char6.
       } else {
         Code =3D bitc::CST_CODE_STRING;
         AbbrevToUse =3D String8Abbrev;
       }
       bool isCStr7 =3D Code =3D=3D bitc::CST_CODE_CSTRING;
       bool isCStrChar6 =3D Code =3D=3D bitc::CST_CODE_CSTRING;
-      for (unsigned i =3D 0; i !=3D NumOps; ++i) {
-        unsigned char V =3D cast<ConstantInt>(CA->getOperand(i))->getZExtV=
alue();
+      for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+        unsigned char V =3D Str->getElementAsInteger(i);
         Record.push_back(V);
         isCStr7 &=3D (V & 128) =3D=3D 0;
         if (isCStrChar6)
           isCStrChar6 =3D BitCodeAbbrevOp::isChar6(V);
       }
-
+     =20
       if (isCStrChar6)
         AbbrevToUse =3D CString6Abbrev;
       else if (isCStr7)
         AbbrevToUse =3D CString7Abbrev;
-    } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
-               isa<ConstantVector>(V)) {
+    } else if (const ConstantDataSequential *CDS =3D=20
+                  dyn_cast<ConstantDataSequential>(C)) {
+      Code =3D bitc::CST_CODE_DATA;
+      Type *EltTy =3D CDS->getType()->getElementType();
+      if (isa<IntegerType>(EltTy)) {
+        for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i)
+          Record.push_back(CDS->getElementAsInteger(i));
+      } else if (EltTy->isFloatTy()) {
+        for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i)=
 {
+          union { float F; uint32_t I; };
+          F =3D CDS->getElementAsFloat(i);
+          Record.push_back(I);
+        }
+      } else {
+        assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
+        for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i)=
 {
+          union { double F; uint64_t I; };
+          F =3D CDS->getElementAsDouble(i);
+          Record.push_back(I);
+        }
+      }
+    } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
+               isa<ConstantVector>(C)) {
       Code =3D bitc::CST_CODE_AGGREGATE;
       for (unsigned i =3D 0, e =3D C->getNumOperands(); i !=3D e; ++i)
         Record.push_back(VE.getValueID(C->getOperand(i)));
@@ -1105,10 +1136,18 @@
     }
     break;
   case Instruction::Switch:
-    Code =3D bitc::FUNC_CODE_INST_SWITCH;
-    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
-    for (unsigned i =3D 0, e =3D I.getNumOperands(); i !=3D e; ++i)
-      Vals.push_back(VE.getValueID(I.getOperand(i)));
+    {
+      Code =3D bitc::FUNC_CODE_INST_SWITCH;
+      SwitchInst &SI =3D cast<SwitchInst>(I);
+      Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
+      Vals.push_back(VE.getValueID(SI.getCondition()));
+      Vals.push_back(VE.getValueID(SI.getDefaultDest()));
+      for (SwitchInst::CaseIt i =3D SI.case_begin(), e =3D SI.case_end();
+           i !=3D e; ++i) {
+        Vals.push_back(VE.getValueID(i.getCaseValue()));
+        Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
+      }
+    }
     break;
   case Instruction::IndirectBr:
     Code =3D bitc::FUNC_CODE_INST_INDIRECTBR;
@@ -1146,9 +1185,6 @@
     Code =3D bitc::FUNC_CODE_INST_RESUME;
     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
     break;
-  case Instruction::Unwind:
-    Code =3D bitc::FUNC_CODE_INST_UNWIND;
-    break;
   case Instruction::Unreachable:
     Code =3D bitc::FUNC_CODE_INST_UNREACHABLE;
     AbbrevToUse =3D FUNCTION_INST_UNREACHABLE_ABBREV;
@@ -1573,6 +1609,102 @@
   Stream.ExitBlock();
 }
=20
+// Sort the Users based on the order in which the reader parses the bitcod=
e=20
+// file.
+static bool bitcodereader_order(const User *lhs, const User *rhs) {
+  // TODO: Implement.
+  return true;
+}
+
+static void WriteUseList(const Value *V, const ValueEnumerator &VE,
+                         BitstreamWriter &Stream) {
+
+  // One or zero uses can't get out of order.
+  if (V->use_empty() || V->hasNUses(1))
+    return;
+
+  // Make a copy of the in-memory use-list for sorting.
+  unsigned UseListSize =3D std::distance(V->use_begin(), V->use_end());
+  SmallVector<const User*, 8> UseList;
+  UseList.reserve(UseListSize);
+  for (Value::const_use_iterator I =3D V->use_begin(), E =3D V->use_end();
+       I !=3D E; ++I) {
+    const User *U =3D *I;
+    UseList.push_back(U);
+  }
+
+  // Sort the copy based on the order read by the BitcodeReader.
+  std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
+
+  // TODO: Generate a diff between the BitcodeWriter in-memory use-list an=
d the
+  // sorted list (i.e., the expected BitcodeReader in-memory use-list).
+
+  // TODO: Emit the USELIST_CODE_ENTRYs.
+}
+
+static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
+                                 BitstreamWriter &Stream) {
+  VE.incorporateFunction(*F);
+
+  for (Function::const_arg_iterator AI =3D F->arg_begin(), AE =3D F->arg_e=
nd();
+       AI !=3D AE; ++AI)
+    WriteUseList(AI, VE, Stream);
+  for (Function::const_iterator BB =3D F->begin(), FE =3D F->end(); BB !=
=3D FE;
+       ++BB) {
+    WriteUseList(BB, VE, Stream);
+    for (BasicBlock::const_iterator II =3D BB->begin(), IE =3D BB->end(); =
II !=3D IE;
+         ++II) {
+      WriteUseList(II, VE, Stream);
+      for (User::const_op_iterator OI =3D II->op_begin(), E =3D II->op_end=
();
+           OI !=3D E; ++OI) {
+        if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
+            isa<InlineAsm>(*OI))
+          WriteUseList(*OI, VE, Stream);
+      }
+    }
+  }
+  VE.purgeFunction();
+}
+
+// Emit use-lists.
+static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
+                                BitstreamWriter &Stream) {
+  Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
+
+  // XXX: this modifies the module, but in a way that should never change =
the
+  // behavior of any pass or codegen in LLVM. The problem is that GVs may
+  // contain entries in the use_list that do not exist in the Module and a=
re
+  // not stored in the .bc file.
+  for (Module::const_global_iterator I =3D M->global_begin(), E =3D M->glo=
bal_end();
+       I !=3D E; ++I)
+    I->removeDeadConstantUsers();
+ =20
+  // Write the global variables.
+  for (Module::const_global_iterator GI =3D M->global_begin(),=20
+         GE =3D M->global_end(); GI !=3D GE; ++GI) {
+    WriteUseList(GI, VE, Stream);
+
+    // Write the global variable initializers.
+    if (GI->hasInitializer())
+      WriteUseList(GI->getInitializer(), VE, Stream);
+  }
+
+  // Write the functions.
+  for (Module::const_iterator FI =3D M->begin(), FE =3D M->end(); FI !=3D =
FE; ++FI) {
+    WriteUseList(FI, VE, Stream);
+    if (!FI->isDeclaration())
+      WriteFunctionUseList(FI, VE, Stream);
+  }
+
+  // Write the aliases.
+  for (Module::const_alias_iterator AI =3D M->alias_begin(), AE =3D M->ali=
as_end();
+       AI !=3D AE; ++AI) {
+    WriteUseList(AI, VE, Stream);
+    WriteUseList(AI->getAliasee(), VE, Stream);
+  }
+
+  Stream.ExitBlock();
+}
=20
 /// WriteModule - Emit the specified module to the bitstream.
 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
@@ -1607,17 +1739,21 @@
   // Emit metadata.
   WriteModuleMetadata(M, VE, Stream);
=20
-  // Emit function bodies.
-  for (Module::const_iterator F =3D M->begin(), E =3D M->end(); F !=3D E; =
++F)
-    if (!F->isDeclaration())
-      WriteFunction(*F, VE, Stream);
-
   // Emit metadata.
   WriteModuleMetadataStore(M, Stream);
=20
   // Emit names for globals/functions etc.
   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
=20
+  // Emit use-lists.
+  if (EnablePreserveUseListOrdering)
+    WriteModuleUseLists(M, VE, Stream);
+
+  // Emit function bodies.
+  for (Module::const_iterator F =3D M->begin(), E =3D M->end(); F !=3D E; =
++F)
+    if (!F->isDeclaration())
+      WriteFunction(*F, VE, Stream);
+
   Stream.ExitBlock();
 }
=20
@@ -1639,7 +1775,17 @@
   DarwinBCHeaderSize =3D 5*4
 };
=20
-static void EmitDarwinBCHeader(BitstreamWriter &Stream, const Triple &TT) {
+static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buff=
er,
+                               uint32_t &Position) {
+  Buffer[Position + 0] =3D (unsigned char) (Value >>  0);
+  Buffer[Position + 1] =3D (unsigned char) (Value >>  8);
+  Buffer[Position + 2] =3D (unsigned char) (Value >> 16);
+  Buffer[Position + 3] =3D (unsigned char) (Value >> 24);
+  Position +=3D 4;
+}
+
+static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
+                                         const Triple &TT) {
   unsigned CPUType =3D ~0U;
=20
   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
@@ -1666,63 +1812,55 @@
     CPUType =3D DARWIN_CPU_TYPE_ARM;
=20
   // Traditional Bitcode starts after header.
+  assert(Buffer.size() >=3D DarwinBCHeaderSize &&
+         "Expected header size to be reserved");
   unsigned BCOffset =3D DarwinBCHeaderSize;
+  unsigned BCSize =3D Buffer.size()-DarwinBCHeaderSize;
=20
-  Stream.Emit(0x0B17C0DE, 32);
-  Stream.Emit(0         , 32);  // Version.
-  Stream.Emit(BCOffset  , 32);
-  Stream.Emit(0         , 32);  // Filled in later.
-  Stream.Emit(CPUType   , 32);
-}
-
-/// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
-/// finalize the header.
-static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSi=
ze) {
-  // Update the size field in the header.
-  Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderS=
ize);
+  // Write the magic and version.
+  unsigned Position =3D 0;
+  WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
+  WriteInt32ToBuffer(0          , Buffer, Position); // Version.
+  WriteInt32ToBuffer(BCOffset   , Buffer, Position);
+  WriteInt32ToBuffer(BCSize     , Buffer, Position);
+  WriteInt32ToBuffer(CPUType    , Buffer, Position);
=20
   // If the file is not a multiple of 16 bytes, insert dummy padding.
-  while (BufferSize & 15) {
-    Stream.Emit(0, 8);
-    ++BufferSize;
-  }
+  while (Buffer.size() & 15)
+    Buffer.push_back(0);
 }
=20
-
 /// WriteBitcodeToFile - Write the specified module to the specified output
 /// stream.
 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
-  std::vector<unsigned char> Buffer;
-  BitstreamWriter Stream(Buffer);
-
+  SmallVector<char, 1024> Buffer;
   Buffer.reserve(256*1024);
=20
-  WriteBitcodeToStream( M, Stream );
+  // If this is darwin or another generic macho target, reserve space for =
the
+  // header.
+  Triple TT(M->getTargetTriple());
+  if (TT.isOSDarwin())
+    Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
+
+  // Emit the module into the buffer.
+  {
+    BitstreamWriter Stream(Buffer);
+
+    // Emit the file header.
+    Stream.Emit((unsigned)'B', 8);
+    Stream.Emit((unsigned)'C', 8);
+    Stream.Emit(0x0, 4);
+    Stream.Emit(0xC, 4);
+    Stream.Emit(0xE, 4);
+    Stream.Emit(0xD, 4);
+
+    // Emit the module.
+    WriteModule(M, Stream);
+  }
+
+  if (TT.isOSDarwin())
+    EmitDarwinBCHeaderAndTrailer(Buffer, TT);
=20
   // Write the generated bitstream to "Out".
   Out.write((char*)&Buffer.front(), Buffer.size());
 }
-
-/// WriteBitcodeToStream - Write the specified module to the specified out=
put
-/// stream.
-void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
-  // If this is darwin or another generic macho target, emit a file header=
 and
-  // trailer if needed.
-  Triple TT(M->getTargetTriple());
-  if (TT.isOSDarwin())
-    EmitDarwinBCHeader(Stream, TT);
-
-  // Emit the file header.
-  Stream.Emit((unsigned)'B', 8);
-  Stream.Emit((unsigned)'C', 8);
-  Stream.Emit(0x0, 4);
-  Stream.Emit(0xC, 4);
-  Stream.Emit(0xE, 4);
-  Stream.Emit(0xD, 4);
-
-  // Emit the module.
-  WriteModule(M, Stream);
-
-  if (TT.isOSDarwin())
-    EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Bitcode/Writer/V=
alueEnumerator.cpp
--- a/head/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -19,6 +19,8 @@
 #include "llvm/Module.h"
 #include "llvm/ValueSymbolTable.h"
 #include "llvm/Instructions.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
 #include <algorithm>
 using namespace llvm;
=20
@@ -107,7 +109,6 @@
   OptimizeConstants(FirstConstant, Values.size());
 }
=20
-
 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
   InstructionMapType::const_iterator I =3D InstructionMap.find(Inst);
   assert(I !=3D InstructionMap.end() && "Instruction is not mapped!");
@@ -130,6 +131,43 @@
   return I->second-1;
 }
=20
+void ValueEnumerator::dump() const {
+  print(dbgs(), ValueMap, "Default");
+  dbgs() << '\n';
+  print(dbgs(), MDValueMap, "MetaData");
+  dbgs() << '\n';
+}
+
+void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
+                            const char *Name) const {
+
+  OS << "Map Name: " << Name << "\n";
+  OS << "Size: " << Map.size() << "\n";
+  for (ValueMapType::const_iterator I =3D Map.begin(),
+         E =3D Map.end(); I !=3D E; ++I) {
+
+    const Value *V =3D I->first;
+    if (V->hasName())
+      OS << "Value: " << V->getName();
+    else
+      OS << "Value: [null]\n";
+    V->dump();
+
+    OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
+    for (Value::const_use_iterator UI =3D V->use_begin(), UE =3D V->use_en=
d();
+         UI !=3D UE; ++UI) {
+      if (UI !=3D V->use_begin())
+        OS << ",";
+      if((*UI)->hasName())
+        OS << " " << (*UI)->getName();
+      else
+        OS << " [null]";
+
+    }
+    OS <<  "\n\n";
+  }
+}
+
 // Optimize constant ordering.
 namespace {
   struct CstSortPredicate {
@@ -283,10 +321,6 @@
   if (const Constant *C =3D dyn_cast<Constant>(V)) {
     if (isa<GlobalValue>(C)) {
       // Initializers for globals are handled explicitly elsewhere.
-    } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()=
) {
-      // Do not enumerate the initializers for an array of simple characte=
rs.
-      // The initializers just pollute the value table, and we emit the st=
rings
-      // specially.
     } else if (C->getNumOperands()) {
       // If a constant has operands, enumerate them.  This makes sure that=
 if a
       // constant has uses (for example an array of const ints), that they=
 are
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Bitcode/Writer/V=
alueEnumerator.h
--- a/head/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Bitcode/Writer/ValueEnumerator.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -32,6 +32,7 @@
 class AttrListPtr;
 class ValueSymbolTable;
 class MDSymbolTable;
+class raw_ostream;
=20
 class ValueEnumerator {
 public:
@@ -83,6 +84,9 @@
 public:
   ValueEnumerator(const Module *M);
=20
+  void dump() const;
+  void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) c=
onst;
+
   unsigned getValueID(const Value *V) const;
=20
   unsigned getTypeID(Type *T) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Aggressi=
veAntiDepBreaker.cpp
--- a/head/contrib/llvm/lib/CodeGen/AggressiveAntiDepBreaker.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AggressiveAntiDepBreaker.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -148,7 +148,7 @@
   assert(State =3D=3D NULL);
   State =3D new AggressiveAntiDepState(TRI->getNumRegs(), BB);
=20
-  bool IsReturnBlock =3D (!BB->empty() && BB->back().getDesc().isReturn());
+  bool IsReturnBlock =3D (!BB->empty() && BB->back().isReturn());
   std::vector<unsigned> &KillIndices =3D State->GetKillIndices();
   std::vector<unsigned> &DefIndices =3D State->GetDefIndices();
=20
@@ -157,7 +157,7 @@
     // In a return block, examine the function live-out regs.
     for (MachineRegisterInfo::liveout_iterator I =3D MRI.liveout_begin(),
          E =3D MRI.liveout_end(); I !=3D E; ++I) {
-      for (const unsigned *Alias =3D TRI->getOverlaps(*I);
+      for (const uint16_t *Alias =3D TRI->getOverlaps(*I);
            unsigned Reg =3D *Alias; ++Alias) {
         State->UnionGroups(Reg, 0);
         KillIndices[Reg] =3D BB->size();
@@ -173,7 +173,7 @@
          SE =3D BB->succ_end(); SI !=3D SE; ++SI)
     for (MachineBasicBlock::livein_iterator I =3D (*SI)->livein_begin(),
            E =3D (*SI)->livein_end(); I !=3D E; ++I) {
-      for (const unsigned *Alias =3D TRI->getOverlaps(*I);
+      for (const uint16_t *Alias =3D TRI->getOverlaps(*I);
            unsigned Reg =3D *Alias; ++Alias) {
         State->UnionGroups(Reg, 0);
         KillIndices[Reg] =3D BB->size();
@@ -186,10 +186,10 @@
   // callee-saved register that is not saved in the prolog.
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
   BitVector Pristine =3D MFI->getPristineRegs(BB);
-  for (const unsigned *I =3D TRI->getCalleeSavedRegs(); *I; ++I) {
+  for (const uint16_t *I =3D TRI->getCalleeSavedRegs(&MF); *I; ++I) {
     unsigned Reg =3D *I;
     if (!IsReturnBlock && !Pristine.test(Reg)) continue;
-    for (const unsigned *Alias =3D TRI->getOverlaps(Reg);
+    for (const uint16_t *Alias =3D TRI->getOverlaps(Reg);
          unsigned AliasReg =3D *Alias; ++Alias) {
       State->UnionGroups(AliasReg, 0);
       KillIndices[AliasReg] =3D BB->size();
@@ -265,7 +265,7 @@
         IsImplicitDefUse(MI, MO)) {
       const unsigned Reg =3D MO.getReg();
       PassthruRegs.insert(Reg);
-      for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+      for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
            *Subreg; ++Subreg) {
         PassthruRegs.insert(*Subreg);
       }
@@ -333,7 +333,7 @@
     DEBUG(dbgs() << "->g" << State->GetGroup(Reg) << tag);
   }
   // Repeat for subregisters.
-  for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+  for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
        *Subreg; ++Subreg) {
     unsigned SubregReg =3D *Subreg;
     if (!State->IsLive(SubregReg)) {
@@ -384,7 +384,7 @@
     // If MI's defs have a special allocation requirement, don't allow
     // any def registers to be changed. Also assume all registers
     // defined in a call must not be changed (ABI).
-    if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq() ||
+    if (MI->isCall() || MI->hasExtraDefRegAllocReq() ||
         TII->isPredicated(MI)) {
       DEBUG(if (State->GetGroup(Reg) !=3D 0) dbgs() << "->g0(alloc-req)");
       State->UnionGroups(Reg, 0);
@@ -392,7 +392,7 @@
=20
     // Any aliased that are live at this point are completely or
     // partially defined here, so group those aliases with Reg.
-    for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
+    for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
       unsigned AliasReg =3D *Alias;
       if (State->IsLive(AliasReg)) {
         State->UnionGroups(Reg, AliasReg);
@@ -423,7 +423,7 @@
       continue;
=20
     // Update def for Reg and aliases.
-    for (const unsigned *Alias =3D TRI->getOverlaps(Reg);
+    for (const uint16_t *Alias =3D TRI->getOverlaps(Reg);
          unsigned AliasReg =3D *Alias; ++Alias)
       DefIndices[AliasReg] =3D Count;
   }
@@ -451,8 +451,8 @@
   // instruction which may not be executed. The second R6 def may or may n=
ot
   // re-define R6 so it's not safe to change it since the last R6 use cann=
ot be
   // changed.
-  bool Special =3D MI->getDesc().isCall() ||
-    MI->getDesc().hasExtraSrcRegAllocReq() ||
+  bool Special =3D MI->isCall() ||
+    MI->hasExtraSrcRegAllocReq() ||
     TII->isPredicated(MI);
=20
   // Scan the register uses for this instruction and update
@@ -678,7 +678,7 @@
         goto next_super_reg;
       } else {
         bool found =3D false;
-        for (const unsigned *Alias =3D TRI->getAliasSet(NewReg);
+        for (const uint16_t *Alias =3D TRI->getAliasSet(NewReg);
              *Alias; ++Alias) {
           unsigned AliasReg =3D *Alias;
           if (State->IsLive(AliasReg) ||
@@ -780,6 +780,9 @@
        I !=3D E; --Count) {
     MachineInstr *MI =3D --I;
=20
+    if (MI->isDebugValue())
+      continue;
+
     DEBUG(dbgs() << "Anti: ");
     DEBUG(MI->dump());
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Allocati=
onOrder.cpp
--- a/head/contrib/llvm/lib/CodeGen/AllocationOrder.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AllocationOrder.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -41,7 +41,7 @@
   if (HintPair.first) {
     const TargetRegisterInfo &TRI =3D VRM.getTargetRegInfo();
     // The remaining allocation order may depend on the hint.
-    ArrayRef<unsigned> Order =3D
+    ArrayRef<uint16_t> Order =3D
       TRI.getRawAllocationOrder(RC, HintPair.first, Hint,
                                 VRM.getMachineFunction());
     if (Order.empty())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Allocati=
onOrder.h
--- a/head/contrib/llvm/lib/CodeGen/AllocationOrder.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AllocationOrder.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -34,8 +34,7 @@
   /// AllocationOrder - Create a new AllocationOrder for VirtReg.
   /// @param VirtReg      Virtual register to allocate for.
   /// @param VRM          Virtual register map for function.
-  /// @param ReservedRegs Set of reserved registers as returned by
-  ///        TargetRegisterInfo::getReservedRegs().
+  /// @param RegClassInfo Information about reserved and allocatable regis=
ters.
   AllocationOrder(unsigned VirtReg,
                   const VirtRegMap &VRM,
                   const RegisterClassInfo &RegClassInfo);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Analysis=
.cpp
--- a/head/contrib/llvm/lib/CodeGen/Analysis.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/CodeGen/Analysis.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities --*- C++ -=
-----*-=3D=3D=3D//
+//=3D=3D=3D-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities ----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,6 +12,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/CodeGen/Analysis.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
 #include "llvm/Instructions.h"
@@ -149,33 +150,37 @@
 /// consideration of global floating-point math flags.
 ///
 ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
-  ISD::CondCode FPC, FOC;
   switch (Pred) {
-  case FCmpInst::FCMP_FALSE: FOC =3D FPC =3D ISD::SETFALSE; break;
-  case FCmpInst::FCMP_OEQ:   FOC =3D ISD::SETEQ; FPC =3D ISD::SETOEQ; brea=
k;
-  case FCmpInst::FCMP_OGT:   FOC =3D ISD::SETGT; FPC =3D ISD::SETOGT; brea=
k;
-  case FCmpInst::FCMP_OGE:   FOC =3D ISD::SETGE; FPC =3D ISD::SETOGE; brea=
k;
-  case FCmpInst::FCMP_OLT:   FOC =3D ISD::SETLT; FPC =3D ISD::SETOLT; brea=
k;
-  case FCmpInst::FCMP_OLE:   FOC =3D ISD::SETLE; FPC =3D ISD::SETOLE; brea=
k;
-  case FCmpInst::FCMP_ONE:   FOC =3D ISD::SETNE; FPC =3D ISD::SETONE; brea=
k;
-  case FCmpInst::FCMP_ORD:   FOC =3D FPC =3D ISD::SETO;   break;
-  case FCmpInst::FCMP_UNO:   FOC =3D FPC =3D ISD::SETUO;  break;
-  case FCmpInst::FCMP_UEQ:   FOC =3D ISD::SETEQ; FPC =3D ISD::SETUEQ; brea=
k;
-  case FCmpInst::FCMP_UGT:   FOC =3D ISD::SETGT; FPC =3D ISD::SETUGT; brea=
k;
-  case FCmpInst::FCMP_UGE:   FOC =3D ISD::SETGE; FPC =3D ISD::SETUGE; brea=
k;
-  case FCmpInst::FCMP_ULT:   FOC =3D ISD::SETLT; FPC =3D ISD::SETULT; brea=
k;
-  case FCmpInst::FCMP_ULE:   FOC =3D ISD::SETLE; FPC =3D ISD::SETULE; brea=
k;
-  case FCmpInst::FCMP_UNE:   FOC =3D ISD::SETNE; FPC =3D ISD::SETUNE; brea=
k;
-  case FCmpInst::FCMP_TRUE:  FOC =3D FPC =3D ISD::SETTRUE; break;
-  default:
-    llvm_unreachable("Invalid FCmp predicate opcode!");
-    FOC =3D FPC =3D ISD::SETFALSE;
-    break;
+  case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
+  case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
+  case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
+  case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
+  case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
+  case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
+  case FCmpInst::FCMP_ONE:   return ISD::SETONE;
+  case FCmpInst::FCMP_ORD:   return ISD::SETO;
+  case FCmpInst::FCMP_UNO:   return ISD::SETUO;
+  case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
+  case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
+  case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
+  case FCmpInst::FCMP_ULT:   return ISD::SETULT;
+  case FCmpInst::FCMP_ULE:   return ISD::SETULE;
+  case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
+  case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
+  default: llvm_unreachable("Invalid FCmp predicate opcode!");
   }
-  if (NoNaNsFPMath)
-    return FOC;
-  else
-    return FPC;
+}
+
+ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
+  switch (CC) {
+    case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
+    case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
+    case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
+    case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
+    case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
+    case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
+    default: return CC;
+  }
 }
=20
 /// getICmpCondCode - Return the ISD condition code corresponding to
@@ -195,7 +200,6 @@
   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
   default:
     llvm_unreachable("Invalid ICmp predicate opcode!");
-    return ISD::SETNE;
   }
 }
=20
@@ -221,12 +225,13 @@
   // longjmp on x86), it can end up causing miscompilation that has not
   // been fully understood.
   if (!Ret &&
-      (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return fals=
e;
+      (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt ||
+       !isa<UnreachableInst>(Term))) return false;
=20
   // If I will have a chain, make sure no other instruction that will have=
 a
   // chain interposes between I and the return.
   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
-      !I->isSafeToSpeculativelyExecute())
+      !isSafeToSpeculativelyExecute(I))
     for (BasicBlock::const_iterator BBI =3D prior(prior(ExitBB->end())); ;
          --BBI) {
       if (&*BBI =3D=3D I)
@@ -235,7 +240,7 @@
       if (isa<DbgInfoIntrinsic>(BBI))
         continue;
       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
-          !BBI->isSafeToSpeculativelyExecute())
+          !isSafeToSpeculativelyExecute(BBI))
         return false;
     }
=20
@@ -250,7 +255,7 @@
   // Conservatively require the attributes of the call to match those of
   // the return. Ignore noalias because it doesn't affect the call sequenc=
e.
   const Function *F =3D ExitBB->getParent();
-  unsigned CallerRetAttr =3D F->getAttributes().getRetAttributes();
+  Attributes CallerRetAttr =3D F->getAttributes().getRetAttributes();
   if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
     return false;
=20
@@ -285,12 +290,12 @@
 }
=20
 bool llvm::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
-                                const TargetLowering &TLI) {
+                                SDValue &Chain, const TargetLowering &TLI)=
 {
   const Function *F =3D DAG.getMachineFunction().getFunction();
=20
   // Conservatively require the attributes of the call to match those of
   // the return. Ignore noalias because it doesn't affect the call sequenc=
e.
-  unsigned CallerRetAttr =3D F->getAttributes().getRetAttributes();
+  Attributes CallerRetAttr =3D F->getAttributes().getRetAttributes();
   if (CallerRetAttr & ~Attribute::NoAlias)
     return false;
=20
@@ -299,5 +304,5 @@
     return false;
=20
   // Check if the only use is a function return node.
-  return TLI.isUsedByReturnOnly(Node);
+  return TLI.isUsedByReturnOnly(Node, Chain);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/ARMException.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/ARMException.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/ARMException.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -29,6 +29,7 @@
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Target/TargetRegisterInfo.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Dwarf.h"
 #include "llvm/Support/FormattedStream.h"
 #include "llvm/ADT/SmallString.h"
@@ -36,6 +37,12 @@
 #include "llvm/ADT/Twine.h"
 using namespace llvm;
=20
+cl::opt<bool>
+EnableARMEHABIDescriptors("arm-enable-ehabi-descriptors", cl::Hidden,
+  cl::desc("Generate ARM EHABI tables with unwinding descriptors"),
+  cl::init(false));
+
+
 ARMException::ARMException(AsmPrinter *A)
   : DwarfException(A),
     shouldEmitTable(false), shouldEmitMoves(false), shouldEmitTableModule(=
false)
@@ -72,13 +79,15 @@
       Asm->OutStreamer.EmitPersonality(PerSym);
     }
=20
-    // Map all labels and get rid of any dead landing pads.
-    MMI->TidyLandingPads();
+    if (EnableARMEHABIDescriptors) {
+      // Map all labels and get rid of any dead landing pads.
+      MMI->TidyLandingPads();
=20
-    Asm->OutStreamer.EmitHandlerData();
+      Asm->OutStreamer.EmitHandlerData();
=20
-    // Emit actual exception table
-    EmitExceptionTable();
+      // Emit actual exception table
+      EmitExceptionTable();
+    }
   }
=20
   Asm->OutStreamer.EmitFnEnd();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/AsmPrinter.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -100,6 +100,7 @@
     OutStreamer(Streamer),
     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
   DD =3D 0; DE =3D 0; MMI =3D 0; LI =3D 0;
+  CurrentFnSym =3D CurrentFnSymForSize =3D 0;
   GCMetadataPrinters =3D 0;
   VerboseAsm =3D Streamer.isVerboseAsm();
 }
@@ -613,6 +614,10 @@
     MF->getFunction()->needsUnwindTableEntry();
 }
=20
+bool AsmPrinter::needsRelocationsForDwarfStringPool() const {
+  return MAI->doesDwarfUseRelocationsForStringPool();
+}
+
 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
   MCSymbol *Label =3D MI.getOperand(0).getMCSymbol();
=20
@@ -732,6 +737,18 @@
       OutStreamer.EmitRawText(StringRef("\tnop\n"));
   }
=20
+  const Function *F =3D MF->getFunction();
+  for (Function::const_iterator i =3D F->begin(), e =3D F->end(); i !=3D e=
; ++i) {
+    const BasicBlock *BB =3D i;
+    if (!BB->hasAddressTaken())
+      continue;
+    MCSymbol *Sym =3D GetBlockAddressSymbol(BB);
+    if (Sym->isDefined())
+      continue;
+    OutStreamer.AddComment("Address of block that was removed by CodeGen");
+    OutStreamer.EmitLabel(Sym);
+  }
+
   // Emit target-specific gunk after the function body.
   EmitFunctionBodyEnd();
=20
@@ -745,7 +762,8 @@
=20
     const MCExpr *SizeExp =3D
       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutConte=
xt),
-                              MCSymbolRefExpr::Create(CurrentFnSym, OutCon=
text),
+                              MCSymbolRefExpr::Create(CurrentFnSymForSize,
+                                                      OutContext),
                               OutContext);
     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
   }
@@ -780,7 +798,7 @@
   const TargetRegisterInfo *TRI =3D TM.getRegisterInfo();
   int Reg =3D TRI->getDwarfRegNum(MLoc.getReg(), false);
=20
-  for (const unsigned *SR =3D TRI->getSuperRegisters(MLoc.getReg());
+  for (const uint16_t *SR =3D TRI->getSuperRegisters(MLoc.getReg());
        *SR && Reg < 0; ++SR) {
     Reg =3D TRI->getDwarfRegNum(*SR, false);
     // FIXME: Get the bit range this register uses of the superregister
@@ -841,6 +859,12 @@
     EmitVisibility(Name, V, false);
   }
=20
+  // Emit module flags.
+  SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
+  M.getModuleFlagsMetadata(ModuleFlags);
+  if (!ModuleFlags.empty())
+    getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, T=
M);
+
   // Finalize debug and EH information.
   if (DE) {
     {
@@ -929,6 +953,7 @@
   this->MF =3D &MF;
   // Get the function symbol.
   CurrentFnSym =3D Mang->getSymbol(MF.getFunction());
+  CurrentFnSymForSize =3D CurrentFnSym;
=20
   if (isVerbose())
     LI =3D &getAnalysis<MachineLoopInfo>();
@@ -1120,7 +1145,7 @@
   const MCExpr *Value =3D 0;
   switch (MJTI->getEntryKind()) {
   case MachineJumpTableInfo::EK_Inline:
-    llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
+    llvm_unreachable("Cannot emit EK_Inline jump table entry");
   case MachineJumpTableInfo::EK_Custom32:
     Value =3D TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB,=
 UID,
                                                               OutContext);
@@ -1139,6 +1164,15 @@
     return;
   }
=20
+  case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
+    // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
+    // with a relocation as gp-relative, e.g.:
+    //     .gpdword LBB123
+    MCSymbol *MBBSym =3D MBB->getSymbol();
+    OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContex=
t));
+    return;
+  }
+
   case MachineJumpTableInfo::EK_LabelDifference32: {
     // EK_LabelDifference32 - Each entry is the address of the block minus
     // the address of the jump table.  This is used for PIC jump tables wh=
ere
@@ -1191,12 +1225,8 @@
=20
   assert(GV->hasInitializer() && "Not a special LLVM global!");
=20
-  const TargetData *TD =3D TM.getTargetData();
-  unsigned Align =3D Log2_32(TD->getPointerPrefAlignment());
   if (GV->getName() =3D=3D "llvm.global_ctors") {
-    OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
-    EmitAlignment(Align);
-    EmitXXStructorList(GV->getInitializer());
+    EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
=20
     if (TM.getRelocationModel() =3D=3D Reloc::Static &&
         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
@@ -1208,9 +1238,7 @@
   }
=20
   if (GV->getName() =3D=3D "llvm.global_dtors") {
-    OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
-    EmitAlignment(Align);
-    EmitXXStructorList(GV->getInitializer());
+    EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
=20
     if (TM.getRelocationModel() =3D=3D Reloc::Static &&
         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
@@ -1240,7 +1268,7 @@
   }
 }
=20
-typedef std::pair<int, Constant*> Structor;
+typedef std::pair<unsigned, Constant*> Structor;
=20
 static bool priority_order(const Structor& lhs, const Structor& rhs) {
   return lhs.first < rhs.first;
@@ -1248,7 +1276,7 @@
=20
 /// EmitXXStructorList - Emit the ctor or dtor list taking into account th=
e init
 /// priority.
-void AsmPrinter::EmitXXStructorList(const Constant *List) {
+void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
   // Should be an array of '{ int, void ()* }' structs.  The first value i=
s the
   // init priority.
   if (!isa<ConstantArray>(List)) return;
@@ -1274,19 +1302,20 @@
                                        CS->getOperand(1)));
   }
=20
-  // Emit the function pointers in reverse priority order.
-  switch (MAI->getStructorOutputOrder()) {
-  case Structors::None:
-    break;
-  case Structors::PriorityOrder:
-    std::sort(Structors.begin(), Structors.end(), priority_order);
-    break;
-  case Structors::ReversePriorityOrder:
-    std::sort(Structors.rbegin(), Structors.rend(), priority_order);
-    break;
+  // Emit the function pointers in the target-specific order
+  const TargetData *TD =3D TM.getTargetData();
+  unsigned Align =3D Log2_32(TD->getPointerPrefAlignment());
+  std::stable_sort(Structors.begin(), Structors.end(), priority_order);
+  for (unsigned i =3D 0, e =3D Structors.size(); i !=3D e; ++i) {
+    const MCSection *OutputSection =3D
+      (isCtor ?
+       getObjFileLowering().getStaticCtorSection(Structors[i].first) :
+       getObjFileLowering().getStaticDtorSection(Structors[i].first));
+    OutStreamer.SwitchSection(OutputSection);
+    if (OutStreamer.getCurrentSection() !=3D OutStreamer.getPreviousSectio=
n())
+      EmitAlignment(Align);
+    EmitXXStructor(Structors[i].second);
   }
-  for (unsigned i =3D 0, e =3D Structors.size(); i !=3D e; ++i)
-    EmitGlobalConstant(Structors[i].second);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-----=3D=3D=3D//
@@ -1423,7 +1452,6 @@
   const ConstantExpr *CE =3D dyn_cast<ConstantExpr>(CV);
   if (CE =3D=3D 0) {
     llvm_unreachable("Unknown constant value to lower!");
-    return MCConstantExpr::Create(0, Ctx);
   }
=20
   switch (CE->getOpcode()) {
@@ -1445,7 +1473,6 @@
                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
       report_fatal_error(OS.str());
     }
-    return MCConstantExpr::Create(0, Ctx);
   case Instruction::GetElementPtr: {
     const TargetData &TD =3D *AP.TM.getTargetData();
     // Generate a symbolic expression for the byte address
@@ -1543,6 +1570,19 @@
 /// isRepeatedByteSequence - Determine whether the given value is
 /// composed of a repeated sequence of identical bytes and return the
 /// byte value.  If it is not a repeated sequence, return -1.
+static int isRepeatedByteSequence(const ConstantDataSequential *V) {
+  StringRef Data =3D V->getRawDataValues();
+  assert(!Data.empty() && "Empty aggregates should be CAZ node");
+  char C =3D Data[0];
+  for (unsigned i =3D 1, e =3D Data.size(); i !=3D e; ++i)
+    if (Data[i] !=3D C) return -1;
+  return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
+}
+
+
+/// isRepeatedByteSequence - Determine whether the given value is
+/// composed of a repeated sequence of identical bytes and return the
+/// byte value.  If it is not a repeated sequence, return -1.
 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
=20
   if (const ConstantInt *CI =3D dyn_cast<ConstantInt>(V)) {
@@ -1568,8 +1608,7 @@
   if (const ConstantArray *CA =3D dyn_cast<ConstantArray>(V)) {
     // Make sure all array elements are sequences of the same repeated
     // byte.
-    if (CA->getNumOperands() =3D=3D 0) return -1;
-
+    assert(CA->getNumOperands() !=3D 0 && "Should be a CAZ");
     int Byte =3D isRepeatedByteSequence(CA->getOperand(0), TM);
     if (Byte =3D=3D -1) return -1;
=20
@@ -1580,37 +1619,92 @@
     }
     return Byte;
   }
+ =20
+  if (const ConstantDataSequential *CDS =3D dyn_cast<ConstantDataSequentia=
l>(V))
+    return isRepeatedByteSequence(CDS);
=20
   return -1;
 }
=20
+static void EmitGlobalConstantDataSequential(const ConstantDataSequential =
*CDS,
+                                             unsigned AddrSpace,AsmPrinter=
 &AP){
+ =20
+  // See if we can aggregate this into a .fill, if so, emit it as such.
+  int Value =3D isRepeatedByteSequence(CDS, AP.TM);
+  if (Value !=3D -1) {
+    uint64_t Bytes =3D AP.TM.getTargetData()->getTypeAllocSize(CDS->getTyp=
e());
+    // Don't emit a 1-byte object as a .fill.
+    if (Bytes > 1)
+      return AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
+  }
+ =20
+  // If this can be emitted with .ascii/.asciz, emit it as such.
+  if (CDS->isString())
+    return AP.OutStreamer.EmitBytes(CDS->getAsString(), AddrSpace);
+
+  // Otherwise, emit the values in successive locations.
+  unsigned ElementByteSize =3D CDS->getElementByteSize();
+  if (isa<IntegerType>(CDS->getElementType())) {
+    for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i) {
+      if (AP.isVerbose())
+        AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
+                                                CDS->getElementAsInteger(i=
));
+      AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
+                                  ElementByteSize, AddrSpace);
+    }
+  } else if (ElementByteSize =3D=3D 4) {
+    // FP Constants are printed as integer constants to avoid losing
+    // precision.
+    assert(CDS->getElementType()->isFloatTy());
+    for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i) {
+      union {
+        float F;
+        uint32_t I;
+      };
+     =20
+      F =3D CDS->getElementAsFloat(i);
+      if (AP.isVerbose())
+        AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
+      AP.OutStreamer.EmitIntValue(I, 4, AddrSpace);
+    }
+  } else {
+    assert(CDS->getElementType()->isDoubleTy());
+    for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i) {
+      union {
+        double F;
+        uint64_t I;
+      };
+     =20
+      F =3D CDS->getElementAsDouble(i);
+      if (AP.isVerbose())
+        AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
+      AP.OutStreamer.EmitIntValue(I, 8, AddrSpace);
+    }
+  }
+
+  const TargetData &TD =3D *AP.TM.getTargetData();
+  unsigned Size =3D TD.getTypeAllocSize(CDS->getType());
+  unsigned EmittedSize =3D TD.getTypeAllocSize(CDS->getType()->getElementT=
ype()) *
+                        CDS->getNumElements();
+  if (unsigned Padding =3D Size - EmittedSize)
+    AP.OutStreamer.EmitZeros(Padding, AddrSpace);
+
+}
+
 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned Addr=
Space,
                                     AsmPrinter &AP) {
-  if (AddrSpace !=3D 0 || !CA->isString()) {
-    // Not a string.  Print the values in successive locations.
+  // See if we can aggregate some values.  Make sure it can be
+  // represented as a series of bytes of the constant value.
+  int Value =3D isRepeatedByteSequence(CA, AP.TM);
=20
-    // See if we can aggregate some values.  Make sure it can be
-    // represented as a series of bytes of the constant value.
-    int Value =3D isRepeatedByteSequence(CA, AP.TM);
-
-    if (Value !=3D -1) {
-      uint64_t Bytes =3D AP.TM.getTargetData()->getTypeAllocSize(CA->getTy=
pe());
-      AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
-    }
-    else {
-      for (unsigned i =3D 0, e =3D CA->getNumOperands(); i !=3D e; ++i)
-        EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
-    }
-    return;
+  if (Value !=3D -1) {
+    uint64_t Bytes =3D AP.TM.getTargetData()->getTypeAllocSize(CA->getType=
());
+    AP.OutStreamer.EmitFill(Bytes, Value, AddrSpace);
   }
-
-  // Otherwise, it can be emitted as .ascii.
-  SmallVector<char, 128> TmpVec;
-  TmpVec.reserve(CA->getNumOperands());
-  for (unsigned i =3D 0, e =3D CA->getNumOperands(); i !=3D e; ++i)
-    TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
-
-  AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSp=
ace);
+  else {
+    for (unsigned i =3D 0, e =3D CA->getNumOperands(); i !=3D e; ++i)
+      EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
+  }
 }
=20
 static void EmitGlobalConstantVector(const ConstantVector *CV,
@@ -1656,29 +1750,44 @@
=20
 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
                                  AsmPrinter &AP) {
-  // FP Constants are printed as integer constants to avoid losing
-  // precision.
-  if (CFP->getType()->isDoubleTy()) {
+  if (CFP->getType()->isHalfTy()) {
     if (AP.isVerbose()) {
-      double Val =3D CFP->getValueAPF().convertToDouble();
-      AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
+      SmallString<10> Str;
+      CFP->getValueAPF().toString(Str);
+      AP.OutStreamer.GetCommentOS() << "half " << Str << '\n';
     }
-
     uint64_t Val =3D CFP->getValueAPF().bitcastToAPInt().getZExtValue();
-    AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
+    AP.OutStreamer.EmitIntValue(Val, 2, AddrSpace);
     return;
   }
=20
   if (CFP->getType()->isFloatTy()) {
     if (AP.isVerbose()) {
       float Val =3D CFP->getValueAPF().convertToFloat();
-      AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
+      uint64_t IntVal =3D CFP->getValueAPF().bitcastToAPInt().getZExtValue=
();
+      AP.OutStreamer.GetCommentOS() << "float " << Val << '\n'
+                                    << " (" << format("0x%x", IntVal) << "=
)\n";
     }
     uint64_t Val =3D CFP->getValueAPF().bitcastToAPInt().getZExtValue();
     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
     return;
   }
=20
+  // FP Constants are printed as integer constants to avoid losing
+  // precision.
+  if (CFP->getType()->isDoubleTy()) {
+    if (AP.isVerbose()) {
+      double Val =3D CFP->getValueAPF().convertToDouble();
+      uint64_t IntVal =3D CFP->getValueAPF().bitcastToAPInt().getZExtValue=
();
+      AP.OutStreamer.GetCommentOS() << "double " << Val << '\n'
+                                    << " (" << format("0x%lx", IntVal) << =
")\n";
+    }
+
+    uint64_t Val =3D CFP->getValueAPF().bitcastToAPInt().getZExtValue();
+    AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
+    return;
+  }
+
   if (CFP->getType()->isX86_FP80Ty()) {
     // all long double variants are printed as hex
     // API needed to prevent premature destruction
@@ -1742,20 +1851,20 @@
=20
 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
                                    AsmPrinter &AP) {
-  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
-    uint64_t Size =3D AP.TM.getTargetData()->getTypeAllocSize(CV->getType(=
));
+  const TargetData *TD =3D AP.TM.getTargetData();
+  uint64_t Size =3D TD->getTypeAllocSize(CV->getType());
+  if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
     return AP.OutStreamer.EmitZeros(Size, AddrSpace);
-  }
=20
   if (const ConstantInt *CI =3D dyn_cast<ConstantInt>(CV)) {
-    unsigned Size =3D AP.TM.getTargetData()->getTypeAllocSize(CV->getType(=
));
     switch (Size) {
     case 1:
     case 2:
     case 4:
     case 8:
       if (AP.isVerbose())
-        AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtVal=
ue());
+        AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
+                                                CI->getZExtValue());
       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
       return;
     default:
@@ -1764,29 +1873,45 @@
     }
   }
=20
+  if (const ConstantFP *CFP =3D dyn_cast<ConstantFP>(CV))
+    return EmitGlobalConstantFP(CFP, AddrSpace, AP);
+
+  if (isa<ConstantPointerNull>(CV)) {
+    AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
+    return;
+  }
+
+  if (const ConstantDataSequential *CDS =3D dyn_cast<ConstantDataSequentia=
l>(CV))
+    return EmitGlobalConstantDataSequential(CDS, AddrSpace, AP);
+ =20
   if (const ConstantArray *CVA =3D dyn_cast<ConstantArray>(CV))
     return EmitGlobalConstantArray(CVA, AddrSpace, AP);
=20
   if (const ConstantStruct *CVS =3D dyn_cast<ConstantStruct>(CV))
     return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
=20
-  if (const ConstantFP *CFP =3D dyn_cast<ConstantFP>(CV))
-    return EmitGlobalConstantFP(CFP, AddrSpace, AP);
+  if (const ConstantExpr *CE =3D dyn_cast<ConstantExpr>(CV)) {
+    // Look through bitcasts, which might not be able to be MCExpr'ized (e=
.g. of
+    // vectors).
+    if (CE->getOpcode() =3D=3D Instruction::BitCast)
+      return EmitGlobalConstantImpl(CE->getOperand(0), AddrSpace, AP);
=20
-  if (isa<ConstantPointerNull>(CV)) {
-    unsigned Size =3D AP.TM.getTargetData()->getTypeAllocSize(CV->getType(=
));
-    AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
-    return;
+    if (Size > 8) {
+      // If the constant expression's size is greater than 64-bits, then w=
e have
+      // to emit the value in chunks. Try to constant fold the value and e=
mit it
+      // that way.
+      Constant *New =3D ConstantFoldConstantExpression(CE, TD);
+      if (New && New !=3D CE)
+        return EmitGlobalConstantImpl(New, AddrSpace, AP);
+    }
   }
-
+ =20
   if (const ConstantVector *V =3D dyn_cast<ConstantVector>(CV))
     return EmitGlobalConstantVector(V, AddrSpace, AP);
-
+   =20
   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then em=
it it
   // thread the streamer with EmitValue.
-  AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
-                         AP.TM.getTargetData()->getTypeAllocSize(CV->getTy=
pe()),
-                           AddrSpace);
+  AP.OutStreamer.EmitValue(LowerConstant(CV, AP), Size, AddrSpace);
 }
=20
 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
@@ -1953,7 +2078,7 @@
 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
   // Emit an alignment directive for this block, if needed.
   if (unsigned Align =3D MBB->getAlignment())
-    EmitAlignment(Log2_32(Align));
+    EmitAlignment(Align);
=20
   // If the block has its address taken, emit any labels that were used to
   // reference the block.  It is possible that there is more than one label
@@ -1970,27 +2095,22 @@
       OutStreamer.EmitLabel(Syms[i]);
   }
=20
+  // Print some verbose block comments.
+  if (isVerbose()) {
+    if (const BasicBlock *BB =3D MBB->getBasicBlock())
+      if (BB->hasName())
+        OutStreamer.AddComment("%" + BB->getName());
+    EmitBasicBlockLoopComments(*MBB, LI, *this);
+  }
+
   // Print the main label for the block.
   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
-      if (const BasicBlock *BB =3D MBB->getBasicBlock())
-        if (BB->hasName())
-          OutStreamer.AddComment("%" + BB->getName());
-
-      EmitBasicBlockLoopComments(*MBB, LI, *this);
-
       // NOTE: Want this comment at start of line, don't emit with AddComm=
ent.
       OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
                               Twine(MBB->getNumber()) + ":");
     }
   } else {
-    if (isVerbose()) {
-      if (const BasicBlock *BB =3D MBB->getBasicBlock())
-        if (BB->hasName())
-          OutStreamer.AddComment("%" + BB->getName());
-      EmitBasicBlockLoopComments(*MBB, LI, *this);
-    }
-
     OutStreamer.EmitLabel(MBB->getSymbol());
   }
 }
@@ -2048,7 +2168,7 @@
     MachineInstr &MI =3D *II;
=20
     // If it is not a simple branch, we are in a table somewhere.
-    if (!MI.getDesc().isBranch() || MI.getDesc().isIndirectBranch())
+    if (!MI.isBranch() || MI.isIndirectBranch())
       return false;
=20
     // If we are the operands of one of the branches, this is not
@@ -2090,6 +2210,4 @@
     }
=20
   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Na=
me));
-  return 0;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/AsmPrinterDwarf.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterDwarf.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -25,6 +25,7 @@
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/Dwarf.h"
+#include "llvm/Support/ErrorHandling.h"
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -35,23 +36,8 @@
 void AsmPrinter::EmitSLEB128(int Value, const char *Desc) const {
   if (isVerbose() && Desc)
     OutStreamer.AddComment(Desc);
-   =20
-  if (MAI->hasLEB128()) {
-    OutStreamer.EmitSLEB128IntValue(Value);
-    return;
-  }
=20
-  // If we don't have .sleb128, emit as .bytes.
-  int Sign =3D Value >> (8 * sizeof(Value) - 1);
-  bool IsMore;
- =20
-  do {
-    unsigned char Byte =3D static_cast<unsigned char>(Value & 0x7f);
-    Value >>=3D 7;
-    IsMore =3D Value !=3D Sign || ((Byte ^ Sign) & 0x40) !=3D 0;
-    if (IsMore) Byte |=3D 0x80;
-    OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0);
-  } while (IsMore);
+  OutStreamer.EmitSLEB128IntValue(Value);
 }
=20
 /// EmitULEB128 - emit the specified signed leb128 value.
@@ -60,25 +46,7 @@
   if (isVerbose() && Desc)
     OutStreamer.AddComment(Desc);
=20
-  // FIXME: Should we add a PadTo option to the streamer?
-  if (MAI->hasLEB128() && PadTo =3D=3D 0) {
-    OutStreamer.EmitULEB128IntValue(Value);=20
-    return;
-  }
- =20
-  // If we don't have .uleb128 or we want to emit padding, emit as .bytes.
-  do {
-    unsigned char Byte =3D static_cast<unsigned char>(Value & 0x7f);
-    Value >>=3D 7;
-    if (Value || PadTo !=3D 0) Byte |=3D 0x80;
-    OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0);
-  } while (Value);
-
-  if (PadTo) {
-    if (PadTo > 1)
-      OutStreamer.EmitFill(PadTo - 1, 0x80/*fillval*/, 0/*addrspace*/);
-    OutStreamer.EmitFill(1, 0/*fillval*/, 0/*addrspace*/);
-  }
+  OutStreamer.EmitULEB128IntValue(Value, 0/*addrspace*/, PadTo);
 }
=20
 /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
@@ -143,7 +111,7 @@
     return 0;
  =20
   switch (Encoding & 0x07) {
-  default: assert(0 && "Invalid encoded value.");
+  default: llvm_unreachable("Invalid encoded value.");
   case dwarf::DW_EH_PE_absptr: return TM.getTargetData()->getPointerSize();
   case dwarf::DW_EH_PE_udata2: return 2;
   case dwarf::DW_EH_PE_udata4: return 4;
@@ -177,9 +145,8 @@
 void AsmPrinter::EmitSectionOffset(const MCSymbol *Label,
                                    const MCSymbol *SectionLabel) const {
   // On COFF targets, we have to emit the special .secrel32 directive.
-  if (const char *SecOffDir =3D MAI->getDwarfSectionOffsetDirective()) {
-    // FIXME: MCize.
-    OutStreamer.EmitRawText(SecOffDir + Twine(Label->getName()));
+  if (MAI->getDwarfSectionOffsetDirective()) {
+    OutStreamer.EmitCOFFSecRel32(Label);
     return;
   }
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/AsmPrinterInlineAsm.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/AsmPrinterInlineAsm.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -326,7 +326,11 @@
           OpNo +=3D InlineAsm::getNumOperandRegisters(OpFlags) + 1;
         }
=20
-        if (OpNo >=3D MI->getNumOperands()) {
+	// We may have a location metadata attached to the end of the
+	// instruction, and at no point should see metadata at any
+	// other point while processing. It's an error if so.
+        if (OpNo >=3D MI->getNumOperands() ||
+	    MI->getOperand(OpNo).isMetadata()) {
           Error =3D true;
         } else {
           unsigned OpFlags =3D MI->getOperand(OpNo).getImm();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DIE.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DIE.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DIE.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -112,15 +112,6 @@
     delete Children[i];
 }
=20
-/// addSiblingOffset - Add a sibling offset field to the front of the DIE.
-///
-DIEValue *DIE::addSiblingOffset(BumpPtrAllocator &A) {
-  DIEInteger *DI =3D new (A) DIEInteger(0);
-  Values.insert(Values.begin(), DI);
-  Abbrev.AddFirstAttribute(dwarf::DW_AT_sibling, dwarf::DW_FORM_ref4);
-  return DI;
-}
-
 #ifndef NDEBUG
 void DIE::print(raw_ostream &O, unsigned IncIndent) {
   IndentCount +=3D IncIndent;
@@ -174,6 +165,7 @@
 }
 #endif
=20
+void DIEValue::anchor() { }
=20
 #ifndef NDEBUG
 void DIEValue::dump() {
@@ -223,33 +215,14 @@
   case dwarf::DW_FORM_udata: return MCAsmInfo::getULEB128Size(Integer);
   case dwarf::DW_FORM_sdata: return MCAsmInfo::getSLEB128Size(Integer);
   case dwarf::DW_FORM_addr:  return AP->getTargetData().getPointerSize();
-  default: llvm_unreachable("DIE Value form not supported yet"); break;
+  default: llvm_unreachable("DIE Value form not supported yet");
   }
-  return 0;
 }
=20
 #ifndef NDEBUG
 void DIEInteger::print(raw_ostream &O) {
-  O << "Int: " << (int64_t)Integer
-    << format("  0x%llx", (unsigned long long)Integer);
-}
-#endif
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// DIEString Implementation
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-/// EmitValue - Emit string value.
-///
-void DIEString::EmitValue(AsmPrinter *AP, unsigned Form) const {
-  AP->OutStreamer.EmitBytes(Str, /*addrspace*/0);
-  // Emit nul terminator.
-  AP->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0);
-}
-
-#ifndef NDEBUG
-void DIEString::print(raw_ostream &O) {
-  O << "Str: \"" << Str << "\"";
+  O << "Int: " << (int64_t)Integer << "  0x";
+  O.write_hex(Integer);
 }
 #endif
=20
@@ -267,6 +240,7 @@
 ///
 unsigned DIELabel::SizeOf(AsmPrinter *AP, unsigned Form) const {
   if (Form =3D=3D dwarf::DW_FORM_data4) return 4;
+  if (Form =3D=3D dwarf::DW_FORM_strp) return 4;
   return AP->getTargetData().getPointerSize();
 }
=20
@@ -290,6 +264,7 @@
 ///
 unsigned DIEDelta::SizeOf(AsmPrinter *AP, unsigned Form) const {
   if (Form =3D=3D dwarf::DW_FORM_data4) return 4;
+  if (Form =3D=3D dwarf::DW_FORM_strp) return 4;
   return AP->getTargetData().getPointerSize();
 }
=20
@@ -335,7 +310,7 @@
 ///
 void DIEBlock::EmitValue(AsmPrinter *Asm, unsigned Form) const {
   switch (Form) {
-  default: assert(0 && "Improper form for block");    break;
+  default: llvm_unreachable("Improper form for block");
   case dwarf::DW_FORM_block1: Asm->EmitInt8(Size);    break;
   case dwarf::DW_FORM_block2: Asm->EmitInt16(Size);   break;
   case dwarf::DW_FORM_block4: Asm->EmitInt32(Size);   break;
@@ -355,9 +330,8 @@
   case dwarf::DW_FORM_block2: return Size + sizeof(int16_t);
   case dwarf::DW_FORM_block4: return Size + sizeof(int32_t);
   case dwarf::DW_FORM_block:  return Size + MCAsmInfo::getULEB128Size(Size=
);
-  default: llvm_unreachable("Improper form for block"); break;
+  default: llvm_unreachable("Improper form for block");
   }
-  return 0;
 }
=20
 #ifndef NDEBUG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DIE.h
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DIE.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DIE.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -31,17 +31,17 @@
   class DIEAbbrevData {
     /// Attribute - Dwarf attribute code.
     ///
-    unsigned Attribute;
+    uint16_t Attribute;
=20
     /// Form - Dwarf form code.
     ///
-    unsigned Form;
+    uint16_t Form;
   public:
-    DIEAbbrevData(unsigned A, unsigned F) : Attribute(A), Form(F) {}
+    DIEAbbrevData(uint16_t A, uint16_t F) : Attribute(A), Form(F) {}
=20
     // Accessors.
-    unsigned getAttribute() const { return Attribute; }
-    unsigned getForm()      const { return Form; }
+    uint16_t getAttribute() const { return Attribute; }
+    uint16_t getForm()      const { return Form; }
=20
     /// Profile - Used to gather unique data for the abbreviation folding =
set.
     ///
@@ -54,41 +54,41 @@
   class DIEAbbrev : public FoldingSetNode {
     /// Tag - Dwarf tag code.
     ///
-    unsigned Tag;
+    uint16_t Tag;
+
+    /// ChildrenFlag - Dwarf children flag.
+    ///
+    uint16_t ChildrenFlag;
=20
     /// Unique number for node.
     ///
     unsigned Number;
=20
-    /// ChildrenFlag - Dwarf children flag.
-    ///
-    unsigned ChildrenFlag;
-
     /// Data - Raw data bytes for abbreviation.
     ///
     SmallVector<DIEAbbrevData, 8> Data;
=20
   public:
-    DIEAbbrev(unsigned T, unsigned C) : Tag(T), ChildrenFlag(C), Data() {}
+    DIEAbbrev(uint16_t T, uint16_t C) : Tag(T), ChildrenFlag(C), Data() {}
=20
     // Accessors.
-    unsigned getTag() const { return Tag; }
+    uint16_t getTag() const { return Tag; }
     unsigned getNumber() const { return Number; }
-    unsigned getChildrenFlag() const { return ChildrenFlag; }
+    uint16_t getChildrenFlag() const { return ChildrenFlag; }
     const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
-    void setTag(unsigned T) { Tag =3D T; }
-    void setChildrenFlag(unsigned CF) { ChildrenFlag =3D CF; }
+    void setTag(uint16_t T) { Tag =3D T; }
+    void setChildrenFlag(uint16_t CF) { ChildrenFlag =3D CF; }
     void setNumber(unsigned N) { Number =3D N; }
=20
     /// AddAttribute - Adds another set of attribute information to the
     /// abbreviation.
-    void AddAttribute(unsigned Attribute, unsigned Form) {
+    void AddAttribute(uint16_t Attribute, uint16_t Form) {
       Data.push_back(DIEAbbrevData(Attribute, Form));
     }
=20
     /// AddFirstAttribute - Adds a set of attribute information to the fro=
nt
     /// of the abbreviation.
-    void AddFirstAttribute(unsigned Attribute, unsigned Form) {
+    void AddFirstAttribute(uint16_t Attribute, uint16_t Form) {
       Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
     }
=20
@@ -113,10 +113,6 @@
=20
   class DIE {
   protected:
-    /// Abbrev - Buffer for constructing abbreviation.
-    ///
-    DIEAbbrev Abbrev;
-
     /// Offset - Offset in debug info section.
     ///
     unsigned Offset;
@@ -125,6 +121,10 @@
     ///
     unsigned Size;
=20
+    /// Abbrev - Buffer for constructing abbreviation.
+    ///
+    DIEAbbrev Abbrev;
+
     /// Children DIEs.
     ///
     std::vector<DIE *> Children;
@@ -139,8 +139,8 @@
     mutable unsigned IndentCount;
   public:
     explicit DIE(unsigned Tag)
-      : Abbrev(Tag, dwarf::DW_CHILDREN_no), Offset(0),
-        Size(0), Parent (0), IndentCount(0) {}
+      : Offset(0), Size(0), Abbrev(Tag, dwarf::DW_CHILDREN_no), Parent(0),
+        IndentCount(0) {}
     virtual ~DIE();
=20
     // Accessors.
@@ -163,16 +163,6 @@
       Values.push_back(Value);
     }
=20
-    /// SiblingOffset - Return the offset of the debug information entry's
-    /// sibling.
-    unsigned getSiblingOffset() const { return Offset + Size; }
-
-    /// addSiblingOffset - Add a sibling offset field to the front of the =
DIE.
-    /// The caller is responsible for deleting the return value at or afte=
r the
-    /// same time it destroys this DIE.
-    ///
-    DIEValue *addSiblingOffset(BumpPtrAllocator &A);
-
     /// addChild - Add a child to the DIE.
     ///
     void addChild(DIE *Child) {
@@ -195,12 +185,12 @@
   /// DIEValue - A debug information entry value.
   ///
   class DIEValue {
+    virtual void anchor();
   public:
     enum {
       isInteger,
       isString,
       isLabel,
-      isSectionOffset,
       isDelta,
       isEntry,
       isBlock
@@ -276,33 +266,6 @@
   };
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
-  /// DIEString - A string value DIE. This DIE keeps string reference only.
-  ///
-  class DIEString : public DIEValue {
-    const StringRef Str;
-  public:
-    explicit DIEString(const StringRef S) : DIEValue(isString), Str(S) {}
-
-    /// EmitValue - Emit string value.
-    ///
-    virtual void EmitValue(AsmPrinter *AP, unsigned Form) const;
-
-    /// SizeOf - Determine size of string value in bytes.
-    ///
-    virtual unsigned SizeOf(AsmPrinter *AP, unsigned /*Form*/) const {
-      return Str.size() + sizeof(char); // sizeof('\0');
-    }
-
-    // Implement isa/cast/dyncast.
-    static bool classof(const DIEString *) { return true; }
-    static bool classof(const DIEValue *S) { return S->getType() =3D=3D is=
String; }
-
-#ifndef NDEBUG
-    virtual void print(raw_ostream &O);
-#endif
-  };
-
-  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   /// DIELabel - A label expression DIE.
   //
   class DIELabel : public DIEValue {
@@ -359,7 +322,7 @@
   };
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
-  /// DIEntry - A pointer to another debug information entry.  An instance=
 of
+  /// DIEEntry - A pointer to another debug information entry.  An instanc=
e of
   /// this class can also be used as a proxy for a debug information entry=
 not
   /// yet defined (ie. types.)
   class DIEEntry : public DIEValue {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DwarfCFIException.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCFIException.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCFIException.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -142,12 +142,14 @@
=20
   Asm->OutStreamer.EmitCFIEndProc();
=20
+  if (!shouldEmitPersonality)
+    return;
+
   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("eh_func_end",
                                                 Asm->getFunctionNumber()));
=20
   // Map all labels and get rid of any dead landing pads.
   MMI->TidyLandingPads();
=20
-  if (shouldEmitPersonality)
-    EmitExceptionTable();
+  EmitExceptionTable();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DwarfCompileUnit.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -13,12 +13,14 @@
=20
 #define DEBUG_TYPE "dwarfdebug"
=20
+#include "DwarfAccelTable.h"
 #include "DwarfCompileUnit.h"
 #include "DwarfDebug.h"
 #include "llvm/Constants.h"
 #include "llvm/GlobalVariable.h"
 #include "llvm/Instructions.h"
 #include "llvm/Analysis/DIBuilder.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/Target/Mangler.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetFrameLowering.h"
@@ -30,8 +32,9 @@
 using namespace llvm;
=20
 /// CompileUnit - Compile unit constructor.
-CompileUnit::CompileUnit(unsigned I, DIE *D, AsmPrinter *A, DwarfDebug *DW)
-  : ID(I), CUDie(D), Asm(A), DD(DW), IndexTyDie(0) {
+CompileUnit::CompileUnit(unsigned I, unsigned L, DIE *D, AsmPrinter *A,
+			 DwarfDebug *DW)
+  : ID(I), Language(L), CUDie(D), Asm(A), DD(DW), IndexTyDie(0) {
   DIEIntegerOne =3D new (DIEValueAllocator) DIEInteger(1);
 }
=20
@@ -67,12 +70,19 @@
   Die->addValue(Attribute, Form, Value);
 }
=20
-/// addString - Add a string attribute data and value. DIEString only
-/// keeps string reference.
-void CompileUnit::addString(DIE *Die, unsigned Attribute, unsigned Form,
-                            StringRef String) {
-  DIEValue *Value =3D new (DIEValueAllocator) DIEString(String);
-  Die->addValue(Attribute, Form, Value);
+/// addString - Add a string attribute data and value. We always emit a
+/// reference to the string pool instead of immediate strings so that DIEs=
 have
+/// more predictable sizes.
+void CompileUnit::addString(DIE *Die, unsigned Attribute, StringRef String=
) {
+  MCSymbol *Symb =3D DD->getStringPoolEntry(String);
+  DIEValue *Value;
+  if (Asm->needsRelocationsForDwarfStringPool())
+    Value =3D new (DIEValueAllocator) DIELabel(Symb);
+  else {
+    MCSymbol *StringPool =3D DD->getStringPool();
+    Value =3D new (DIEValueAllocator) DIEDelta(Symb, StringPool);
+  }
+  Die->addValue(Attribute, dwarf::DW_FORM_strp, Value);
 }
=20
 /// addLabel - Add a Dwarf label attribute data and value.
@@ -98,7 +108,6 @@
   Die->addValue(Attribute, Form, createDIEEntry(Entry));
 }
=20
-
 /// addBlock - Add block data.
 ///
 void CompileUnit::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
@@ -135,8 +144,7 @@
   unsigned Line =3D G.getLineNumber();
   if (Line =3D=3D 0)
     return;
-  unsigned FileID =3D DD->GetOrCreateSourceID(G.getFilename(),
-                                            G.getDirectory());
+  unsigned FileID =3D DD->GetOrCreateSourceID(G.getFilename(), G.getDirect=
ory());
   assert(FileID && "Invalid file id");
   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
@@ -148,14 +156,14 @@
   // Verify subprogram.
   if (!SP.Verify())
     return;
+
   // If the line number is 0, don't add it.
-  if (SP.getLineNumber() =3D=3D 0)
+  unsigned Line =3D SP.getLineNumber();
+  if (Line =3D=3D 0)
     return;
=20
-  unsigned Line =3D SP.getLineNumber();
-  if (!SP.getContext().Verify())
-    return;
-  unsigned FileID =3D DD->GetOrCreateSourceID(SP.getFilename(), SP.getDire=
ctory());
+  unsigned FileID =3D DD->GetOrCreateSourceID(SP.getFilename(),
+                                            SP.getDirectory());
   assert(FileID && "Invalid file id");
   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
@@ -169,9 +177,28 @@
     return;
=20
   unsigned Line =3D Ty.getLineNumber();
-  if (Line =3D=3D 0 || !Ty.getContext().Verify())
+  if (Line =3D=3D 0)
     return;
-  unsigned FileID =3D DD->GetOrCreateSourceID(Ty.getFilename(), Ty.getDire=
ctory());
+  unsigned FileID =3D DD->GetOrCreateSourceID(Ty.getFilename(),
+                                            Ty.getDirectory());
+  assert(FileID && "Invalid file id");
+  addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
+  addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
+}
+
+/// addSourceLine - Add location information to specified debug information
+/// entry.
+void CompileUnit::addSourceLine(DIE *Die, DIObjCProperty Ty) {
+  // Verify type.
+  if (!Ty.Verify())
+    return;
+
+  unsigned Line =3D Ty.getLineNumber();
+  if (Line =3D=3D 0)
+    return;
+  DIFile File =3D Ty.getFile();
+  unsigned FileID =3D DD->GetOrCreateSourceID(File.getFilename(),
+					    File.getDirectory());
   assert(FileID && "Invalid file id");
   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
@@ -458,7 +485,7 @@
 /// addConstantValue - Add constant value entry in variable DIE.
 bool CompileUnit::addConstantValue(DIE *Die, const MachineOperand &MO,
                                    DIType Ty) {
-  assert (MO.isImm() && "Invalid machine operand!");
+  assert(MO.isImm() && "Invalid machine operand!");
   DIEBlock *Block =3D new (DIEValueAllocator) DIEBlock();
   int SizeInBits =3D -1;
   bool SignedConstant =3D isTypeSigned(Ty, &SizeInBits);
@@ -558,8 +585,8 @@
       Buffer.addChild(getOrCreateTemplateValueParameterDIE(
                         DITemplateValueParameter(Element)));
   }
+}
=20
-}
 /// addToContextOwner - Add Die into the list of its context owner's child=
ren.
 void CompileUnit::addToContextOwner(DIE *Die, DIDescriptor Context) {
   if (Context.isType()) {
@@ -598,13 +625,29 @@
     assert(Ty.isDerivedType() && "Unknown kind of DIType");
     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
   }
-
+  // If this is a named finished type then include it in the list of types
+  // for the accelerator tables.
+  if (!Ty.getName().empty() && !Ty.isForwardDecl()) {
+    bool IsImplementation =3D 0;
+    if (Ty.isCompositeType()) {
+      DICompositeType CT(Ty);
+      // A runtime language of 0 actually means C/C++ and that any
+      // non-negative value is some version of Objective-C/C++.
+      IsImplementation =3D (CT.getRunTimeLang() =3D=3D 0) ||
+        CT.isObjcClassComplete();
+    }
+    unsigned Flags =3D IsImplementation ?
+                     DwarfAccelTable::eTypeFlagClassIsImplementation : 0;
+    addAccelType(Ty.getName(), std::make_pair(TyDIE, Flags));
+  }
+ =20
   addToContextOwner(TyDIE, Ty.getContext());
   return TyDIE;
 }
=20
 /// addType - Add a new type attribute to the specified entity.
-void CompileUnit::addType(DIE *Entity, DIType Ty) {
+void CompileUnit::addType(DIE *Entity, DIType Ty,
+			  unsigned Attribute) {
   if (!Ty.Verify())
     return;
=20
@@ -612,7 +655,7 @@
   DIEEntry *Entry =3D getDIEEntry(Ty);
   // If it exists then use the existing value.
   if (Entry) {
-    Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
+    Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
     return;
   }
=20
@@ -622,7 +665,7 @@
   // Set up proxy.
   Entry =3D createDIEEntry(Buffer);
   insertDIEEntry(Ty, Entry);
-  Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
+  Entity->addValue(Attribute, dwarf::DW_FORM_ref4, Entry);
=20
   // If this is a complete composite type then include it in the
   // list of global types.
@@ -662,7 +705,7 @@
   StringRef Name =3D BTy.getName();
   // Add name if not anonymous or intermediate type.
   if (!Name.empty())
-    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
+    addString(&Buffer, dwarf::DW_AT_name, Name);
=20
   if (BTy.getTag() =3D=3D dwarf::DW_TAG_unspecified_type) {
     Buffer.setTag(dwarf::DW_TAG_unspecified_type);
@@ -671,8 +714,8 @@
   }
=20
   Buffer.setTag(dwarf::DW_TAG_base_type);
-  addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
-	  BTy.getEncoding());
+  addUInt(&Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
+          BTy.getEncoding());
=20
   uint64_t Size =3D BTy.getSizeInBits() >> 3;
   addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
@@ -696,10 +739,10 @@
=20
   // Add name if not anonymous or intermediate type.
   if (!Name.empty())
-    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
+    addString(&Buffer, dwarf::DW_AT_name, Name);
=20
   // Add size if non-zero (derived types might be zero-sized.)
-  if (Size)
+  if (Size && Tag !=3D dwarf::DW_TAG_pointer_type)
     addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
=20
   // Add source line info if available and TyDesc is not a forward declara=
tion.
@@ -755,8 +798,12 @@
         Buffer.addChild(Arg);
       }
     }
-    // Add prototype flag.
-    if (isPrototyped)
+    // Add prototype flag if we're dealing with a C language and the
+    // function has been prototyped.
+    if (isPrototyped &&
+	(Language =3D=3D dwarf::DW_LANG_C89 ||
+	 Language =3D=3D dwarf::DW_LANG_C99 ||
+	 Language =3D=3D dwarf::DW_LANG_ObjC))
       addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
   }
     break;
@@ -779,13 +826,13 @@
         DISubprogram SP(Element);
         ElemDie =3D getOrCreateSubprogramDIE(DISubprogram(Element));
         if (SP.isProtected())
-          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
+          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data=
1,
                   dwarf::DW_ACCESS_protected);
         else if (SP.isPrivate())
-          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
+          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data=
1,
                   dwarf::DW_ACCESS_private);
         else=20
-          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
+          addUInt(ElemDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data=
1,
             dwarf::DW_ACCESS_public);
         if (SP.isExplicit())
           addUInt(ElemDie, dwarf::DW_AT_explicit, dwarf::DW_FORM_flag, 1);
@@ -793,15 +840,54 @@
       else if (Element.isVariable()) {
         DIVariable DV(Element);
         ElemDie =3D new DIE(dwarf::DW_TAG_variable);
-        addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
-                  DV.getName());
+        addString(ElemDie, dwarf::DW_AT_name, DV.getName());
         addType(ElemDie, DV.getType());
         addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
         addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
         addSourceLine(ElemDie, DV);
-      } else if (Element.isDerivedType())
-        ElemDie =3D createMemberDIE(DIDerivedType(Element));
-      else
+      } else if (Element.isDerivedType()) {
+	DIDerivedType DDTy(Element);
+	if (DDTy.getTag() =3D=3D dwarf::DW_TAG_friend) {
+	  ElemDie =3D new DIE(dwarf::DW_TAG_friend);
+	  addType(ElemDie, DDTy.getTypeDerivedFrom(), dwarf::DW_AT_friend);
+	} else
+	  ElemDie =3D createMemberDIE(DIDerivedType(Element));
+      } else if (Element.isObjCProperty()) {
+        DIObjCProperty Property(Element);
+        ElemDie =3D new DIE(Property.getTag());
+        StringRef PropertyName =3D Property.getObjCPropertyName();
+        addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
+	addType(ElemDie, Property.getType());
+	addSourceLine(ElemDie, Property);
+        StringRef GetterName =3D Property.getObjCPropertyGetterName();
+        if (!GetterName.empty())
+          addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterNam=
e);
+        StringRef SetterName =3D Property.getObjCPropertySetterName();
+        if (!SetterName.empty())
+          addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterNam=
e);
+        unsigned PropertyAttributes =3D 0;
+        if (Property.isReadOnlyObjCProperty())
+          PropertyAttributes |=3D dwarf::DW_APPLE_PROPERTY_readonly;
+        if (Property.isReadWriteObjCProperty())
+          PropertyAttributes |=3D dwarf::DW_APPLE_PROPERTY_readwrite;
+        if (Property.isAssignObjCProperty())
+          PropertyAttributes |=3D dwarf::DW_APPLE_PROPERTY_assign;
+        if (Property.isRetainObjCProperty())
+          PropertyAttributes |=3D dwarf::DW_APPLE_PROPERTY_retain;
+        if (Property.isCopyObjCProperty())
+          PropertyAttributes |=3D dwarf::DW_APPLE_PROPERTY_copy;
+        if (Property.isNonAtomicObjCProperty())
+          PropertyAttributes |=3D dwarf::DW_APPLE_PROPERTY_nonatomic;
+        if (PropertyAttributes)
+          addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, 0,=20
+                 PropertyAttributes);
+
+        DIEEntry *Entry =3D getDIEEntry(Element);
+        if (!Entry) {
+          Entry =3D createDIEEntry(ElemDie);
+          insertDIEEntry(Element, Entry);
+        }
+      } else
         continue;
       Buffer.addChild(ElemDie);
     }
@@ -809,11 +895,6 @@
     if (CTy.isAppleBlockExtension())
       addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
=20
-    unsigned RLang =3D CTy.getRunTimeLang();
-    if (RLang)
-      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
-              dwarf::DW_FORM_data1, RLang);
-
     DICompositeType ContainingType =3D CTy.getContainingType();
     if (DIDescriptor(ContainingType).isCompositeType())
       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_re=
f4,
@@ -827,7 +908,11 @@
       addUInt(&Buffer, dwarf::DW_AT_APPLE_objc_complete_type,
               dwarf::DW_FORM_flag, 1);
=20
-    if (Tag =3D=3D dwarf::DW_TAG_class_type)=20
+    // Add template parameters to a class, structure or union types.
+    // FIXME: The support isn't in the metadata for this yet.
+    if (Tag =3D=3D dwarf::DW_TAG_class_type ||
+        Tag =3D=3D dwarf::DW_TAG_structure_type ||
+        Tag =3D=3D dwarf::DW_TAG_union_type)
       addTemplateParams(Buffer, CTy.getTemplateParams());
=20
     break;
@@ -838,11 +923,11 @@
=20
   // Add name if not anonymous or intermediate type.
   if (!Name.empty())
-    addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
+    addString(&Buffer, dwarf::DW_AT_name, Name);
=20
   if (Tag =3D=3D dwarf::DW_TAG_enumeration_type || Tag =3D=3D dwarf::DW_TA=
G_class_type
       || Tag =3D=3D dwarf::DW_TAG_structure_type || Tag =3D=3D dwarf::DW_T=
AG_union_type)
-    {
+  {
     // Add size if non-zero (derived types might be zero-sized.)
     if (Size)
       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
@@ -857,6 +942,12 @@
     // Add source line info if available.
     if (!CTy.isForwardDecl())
       addSourceLine(&Buffer, CTy);
+
+    // No harm in adding the runtime language to the declaration.
+    unsigned RLang =3D CTy.getRunTimeLang();
+    if (RLang)
+      addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
+              dwarf::DW_FORM_data1, RLang);
   }
 }
=20
@@ -870,7 +961,7 @@
=20
   ParamDIE =3D new DIE(dwarf::DW_TAG_template_type_parameter);
   addType(ParamDIE, TP.getType());
-  addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TP.getName=
());
+  addString(ParamDIE, dwarf::DW_AT_name, TP.getName());
   return ParamDIE;
 }
=20
@@ -885,7 +976,7 @@
   ParamDIE =3D new DIE(dwarf::DW_TAG_template_value_parameter);
   addType(ParamDIE, TPV.getType());
   if (!TPV.getName().empty())
-    addString(ParamDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string, TPV.getN=
ame());
+    addString(ParamDIE, dwarf::DW_AT_name, TPV.getName());
   addUInt(ParamDIE, dwarf::DW_AT_const_value, dwarf::DW_FORM_udata,=20
           TPV.getValue());
   return ParamDIE;
@@ -898,8 +989,11 @@
     return NDie;
   NDie =3D new DIE(dwarf::DW_TAG_namespace);
   insertDIE(NS, NDie);
-  if (!NS.getName().empty())
-    addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName()=
);
+  if (!NS.getName().empty()) {
+    addString(NDie, dwarf::DW_AT_name, NS.getName());
+    addAccelNamespace(NS.getName(), NDie);
+  } else
+    addAccelNamespace("(anonymous namespace)", NDie);
   addSourceLine(NDie, NS);
   addToContextOwner(NDie, NS.getContext());
   return NDie;
@@ -921,6 +1015,12 @@
   if (SPDie)
     return SPDie;
=20
+  DISubprogram SPDecl =3D SP.getFunctionDeclaration();
+  DIE *DeclDie =3D NULL;
+  if (SPDecl.isSubprogram()) {
+    DeclDie =3D getOrCreateSubprogramDIE(SPDecl);
+  }
+
   SPDie =3D new DIE(dwarf::DW_TAG_subprogram);
  =20
   // DW_TAG_inlined_subroutine may refer to this DIE.
@@ -932,25 +1032,36 @@
   // Add function template parameters.
   addTemplateParams(*SPDie, SP.getTemplateParams());
=20
+  // Unfortunately this code needs to stay here to work around
+  // a bug in older gdbs that requires the linkage name to resolve
+  // multiple template functions.
   StringRef LinkageName =3D SP.getLinkageName();
   if (!LinkageName.empty())
-    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,=20
-                    dwarf::DW_FORM_string,
-                    getRealLinkageName(LinkageName));
+    addString(SPDie, dwarf::DW_AT_MIPS_linkage_name,
+              getRealLinkageName(LinkageName));
=20
   // If this DIE is going to refer declaration info using AT_specification
   // then there is no need to add other attributes.
-  if (SP.getFunctionDeclaration().isSubprogram())
+  if (DeclDie) {
+    // Refer function declaration directly.
+    addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
+                DeclDie);
+
     return SPDie;
+  }
=20
   // Constructors and operators for anonymous aggregates do not have names.
   if (!SP.getName().empty())
-    addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,=20
-                    SP.getName());
+    addString(SPDie, dwarf::DW_AT_name, SP.getName());
=20
   addSourceLine(SPDie, SP);
=20
-  if (SP.isPrototyped())=20
+  // Add the prototype if we have a prototype and we have a C like
+  // language.
+  if (SP.isPrototyped() &&
+      (Language =3D=3D dwarf::DW_LANG_C89 ||
+       Language =3D=3D dwarf::DW_LANG_C99 ||
+       Language =3D=3D dwarf::DW_LANG_ObjC))
     addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
=20
   // Add Return Type.
@@ -965,7 +1076,7 @@
=20
   unsigned VK =3D SP.getVirtuality();
   if (VK) {
-    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
+    addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK);
     DIEBlock *Block =3D getDIEBlock();
     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
     addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
@@ -1052,31 +1163,30 @@
   insertDIE(N, VariableDIE);
=20
   // Add name.
-  addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
-                   GV.getDisplayName());
+  addString(VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
   StringRef LinkageName =3D GV.getLinkageName();
   bool isGlobalVariable =3D GV.getGlobal() !=3D NULL;
   if (!LinkageName.empty() && isGlobalVariable)
-    addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,=20
-                     dwarf::DW_FORM_string,
-                     getRealLinkageName(LinkageName));
+    addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
+              getRealLinkageName(LinkageName));
   // Add type.
   DIType GTy =3D GV.getType();
   addType(VariableDIE, GTy);
=20
   // Add scoping info.
-  if (!GV.isLocalToUnit()) {
+  if (!GV.isLocalToUnit())
     addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
-    // Expose as global.=20
-    addGlobal(GV.getName(), VariableDIE);
-  }
+
   // Add line number info.
   addSourceLine(VariableDIE, GV);
   // Add to context owner.
   DIDescriptor GVContext =3D GV.getContext();
   addToContextOwner(VariableDIE, GVContext);
   // Add location.
+  bool addToAccelTable =3D false;
+  DIE *VariableSpecDIE =3D NULL;
   if (isGlobalVariable) {
+    addToAccelTable =3D true;
     DIEBlock *Block =3D new (DIEValueAllocator) DIEBlock();
     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
     addLabel(Block, 0, dwarf::DW_FORM_udata,
@@ -1086,7 +1196,7 @@
     if (GVContext && GV.isDefinition() && !GVContext.isCompileUnit() &&
         !GVContext.isFile() && !isSubprogramContext(GVContext)) {
       // Create specification DIE.
-      DIE *VariableSpecDIE =3D new DIE(dwarf::DW_TAG_variable);
+      VariableSpecDIE =3D new DIE(dwarf::DW_TAG_variable);
       addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
                   dwarf::DW_FORM_ref4, VariableDIE);
       addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
@@ -1095,11 +1205,12 @@
       addDie(VariableSpecDIE);
     } else {
       addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
-    }=20
+    }
   } else if (const ConstantInt *CI =3D=20
              dyn_cast_or_null<ConstantInt>(GV.getConstant()))
     addConstantValue(VariableDIE, CI, GTy.isUnsignedDIType());
   else if (const ConstantExpr *CE =3D getMergedGlobalExpr(N->getOperand(11=
))) {
+    addToAccelTable =3D true;
     // GV is a merged global.
     DIEBlock *Block =3D new (DIEValueAllocator) DIEBlock();
     Value *Ptr =3D CE->getOperand(0);
@@ -1114,6 +1225,16 @@
     addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
   }
=20
+  if (addToAccelTable) {
+    DIE *AddrDIE =3D VariableSpecDIE ? VariableSpecDIE : VariableDIE;
+    addAccelName(GV.getName(), AddrDIE);
+
+    // If the linkage name is different than the name, go ahead and output
+    // that as well into the name table.
+    if (GV.getLinkageName() !=3D "" && GV.getName() !=3D GV.getLinkageName=
())
+      addAccelName(GV.getLinkageName(), AddrDIE);
+  }
+
   return;
 }
=20
@@ -1121,8 +1242,8 @@
 void CompileUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *In=
dexTy){
   DIE *DW_Subrange =3D new DIE(dwarf::DW_TAG_subrange_type);
   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy=
);
-  int64_t L =3D SR.getLo();
-  int64_t H =3D SR.getHi();
+  uint64_t L =3D SR.getLo();
+  uint64_t H =3D SR.getHi();
=20
   // The L value defines the lower bounds which is typically zero for C/C+=
+. The
   // H value is the upper bounds.  Values are 64 bit.  H - L + 1 is the si=
ze
@@ -1135,8 +1256,8 @@
     return;
   }
   if (L)
-    addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
-  addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
+    addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
+  addUInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
   Buffer.addChild(DW_Subrange);
 }
=20
@@ -1175,7 +1296,7 @@
 DIE *CompileUnit::constructEnumTypeDIE(DIEnumerator ETy) {
   DIE *Enumerator =3D new DIE(dwarf::DW_TAG_enumerator);
   StringRef Name =3D ETy.getName();
-  addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
+  addString(Enumerator, dwarf::DW_AT_name, Name);
   int64_t Value =3D ETy.getEnumValue();
   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Valu=
e);
   return Enumerator;
@@ -1212,8 +1333,7 @@
     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
                             dwarf::DW_FORM_ref4, AbsDIE);
   else {
-    addString(VariableDie, dwarf::DW_AT_name,=20
-                          dwarf::DW_FORM_string, Name);
+    addString(VariableDie, dwarf::DW_AT_name, Name);
     addSourceLine(VariableDie, DV->getVariable());
     addType(VariableDie, DV->getType());
   }
@@ -1308,7 +1428,7 @@
   DIE *MemberDie =3D new DIE(DT.getTag());
   StringRef Name =3D DT.getName();
   if (!Name.empty())
-    addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
+    addString(MemberDie, dwarf::DW_AT_name, Name);
=20
   addType(MemberDie, DT.getTypeDerivedFrom());
=20
@@ -1366,32 +1486,35 @@
     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationD=
ie);
=20
   if (DT.isProtected())
-    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
+    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
             dwarf::DW_ACCESS_protected);
   else if (DT.isPrivate())
-    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
+    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
             dwarf::DW_ACCESS_private);
   // Otherwise C++ member and base classes are considered public.
   else=20
-    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
+    addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1,
             dwarf::DW_ACCESS_public);
   if (DT.isVirtual())
-    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
+    addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1,
             dwarf::DW_VIRTUALITY_virtual);
=20
   // Objective-C properties.
+  if (MDNode *PNode =3D DT.getObjCProperty())
+    if (DIEEntry *PropertyDie =3D getDIEEntry(PNode))
+      MemberDie->addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4=
,=20
+                          PropertyDie);
+
+  // This is only for backward compatibility.
   StringRef PropertyName =3D DT.getObjCPropertyName();
   if (!PropertyName.empty()) {
-    addString(MemberDie, dwarf::DW_AT_APPLE_property_name, dwarf::DW_FORM_=
string,
-              PropertyName);
+    addString(MemberDie, dwarf::DW_AT_APPLE_property_name, PropertyName);
     StringRef GetterName =3D DT.getObjCPropertyGetterName();
     if (!GetterName.empty())
-      addString(MemberDie, dwarf::DW_AT_APPLE_property_getter,
-                dwarf::DW_FORM_string, GetterName);
+      addString(MemberDie, dwarf::DW_AT_APPLE_property_getter, GetterName);
     StringRef SetterName =3D DT.getObjCPropertySetterName();
     if (!SetterName.empty())
-      addString(MemberDie, dwarf::DW_AT_APPLE_property_setter,
-                dwarf::DW_FORM_string, SetterName);
+      addString(MemberDie, dwarf::DW_AT_APPLE_property_setter, SetterName);
     unsigned PropertyAttributes =3D 0;
     if (DT.isReadOnlyObjCProperty())
       PropertyAttributes |=3D dwarf::DW_APPLE_PROPERTY_readonly;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DwarfCompileUnit.h
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfCompileUnit.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -29,13 +29,17 @@
 class DbgVariable;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-/// CompileUnit - This dwarf writer support class manages information asso=
ciate
+/// CompileUnit - This dwarf writer support class manages information asso=
ciated
 /// with a source file.
 class CompileUnit {
   /// ID - File identifier for source.
   ///
   unsigned ID;
=20
+  /// Language - The DW_AT_language of the compile unit
+  ///
+  unsigned Language;
+
   /// Die - Compile unit debug information entry.
   ///
   const OwningPtr<DIE> CUDie;
@@ -56,14 +60,17 @@
   /// descriptors to debug information entries using a DIEEntry proxy.
   DenseMap<const MDNode *, DIEEntry *> MDNodeToDIEEntryMap;
=20
-  /// Globals - A map of globally visible named entities for this unit.
-  ///
-  StringMap<DIE*> Globals;
-
   /// GlobalTypes - A map of globally visible types for this unit.
   ///
   StringMap<DIE*> GlobalTypes;
=20
+  /// AccelNames - A map of names for the name accelerator table.
+  ///
+  StringMap<std::vector<DIE*> > AccelNames;
+  StringMap<std::vector<DIE*> > AccelObjC;
+  StringMap<std::vector<DIE*> > AccelNamespace;
+  StringMap<std::vector<std::pair<DIE*, unsigned> > > AccelTypes;
+
   /// DIEBlocks - A list of all the DIEBlocks in use.
   std::vector<DIEBlock *> DIEBlocks;
=20
@@ -73,27 +80,56 @@
   DenseMap<DIE *, const MDNode *> ContainingTypeMap;
=20
 public:
-  CompileUnit(unsigned I, DIE *D, AsmPrinter *A, DwarfDebug *DW);
+  CompileUnit(unsigned I, unsigned L, DIE *D, AsmPrinter *A, DwarfDebug *D=
W);
   ~CompileUnit();
=20
   // Accessors.
   unsigned getID()                  const { return ID; }
+  unsigned getLanguage()            const { return Language; }
   DIE* getCUDie()                   const { return CUDie.get(); }
-  const StringMap<DIE*> &getGlobals()     const { return Globals; }
   const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
=20
+  const StringMap<std::vector<DIE*> > &getAccelNames() const {
+    return AccelNames;
+  }
+  const StringMap<std::vector<DIE*> > &getAccelObjC() const {
+    return AccelObjC;
+  }
+  const StringMap<std::vector<DIE*> > &getAccelNamespace() const {
+    return AccelNamespace;
+  }
+  const StringMap<std::vector<std::pair<DIE*, unsigned > > >
+  &getAccelTypes() const {
+    return AccelTypes;
+  }
+ =20
   /// hasContent - Return true if this compile unit has something to write=
 out.
   ///
   bool hasContent() const { return !CUDie->getChildren().empty(); }
=20
-  /// addGlobal - Add a new global entity to the compile unit.
-  ///
-  void addGlobal(StringRef Name, DIE *Die) { Globals[Name] =3D Die; }
-
   /// addGlobalType - Add a new global type to the compile unit.
   ///
   void addGlobalType(DIType Ty);
=20
+
+  /// addAccelName - Add a new name to the name accelerator table.
+  void addAccelName(StringRef Name, DIE *Die) {
+    std::vector<DIE*> &DIEs =3D AccelNames[Name];
+    DIEs.push_back(Die);
+  }
+  void addAccelObjC(StringRef Name, DIE *Die) {
+    std::vector<DIE*> &DIEs =3D AccelObjC[Name];
+    DIEs.push_back(Die);
+  }
+  void addAccelNamespace(StringRef Name, DIE *Die) {
+    std::vector<DIE*> &DIEs =3D AccelNamespace[Name];
+    DIEs.push_back(Die);
+  }
+  void addAccelType(StringRef Name, std::pair<DIE *, unsigned> Die) {
+    std::vector<std::pair<DIE*, unsigned > > &DIEs =3D AccelTypes[Name];
+    DIEs.push_back(Die);
+  }
+ =20
   /// getDIE - Returns the debug information entry map slot for the
   /// specified debug variable.
   DIE *getDIE(const MDNode *N) { return MDNodeToDieMap.lookup(N); }
@@ -150,8 +186,7 @@
=20
   /// addString - Add a string attribute data and value.
   ///
-  void addString(DIE *Die, unsigned Attribute, unsigned Form,
-                 const StringRef Str);
+  void addString(DIE *Die, unsigned Attribute, const StringRef Str);
=20
   /// addLabel - Add a Dwarf label attribute data and value.
   ///
@@ -178,6 +213,7 @@
   void addSourceLine(DIE *Die, DISubprogram SP);
   void addSourceLine(DIE *Die, DIType Ty);
   void addSourceLine(DIE *Die, DINameSpace NS);
+  void addSourceLine(DIE *Die, DIObjCProperty Ty);
=20
   /// addAddress - Add an address attribute to a die based on the location
   /// provided.
@@ -225,8 +261,10 @@
   /// addToContextOwner - Add Die into the list of its context owner's chi=
ldren.
   void addToContextOwner(DIE *Die, DIDescriptor Context);
=20
-  /// addType - Add a new type attribute to the specified entity.
-  void addType(DIE *Entity, DIType Ty);
+  /// addType - Add a new type attribute to the specified entity. This tak=
es
+  /// and attribute parameter because DW_AT_friend attributes are also
+  /// type references.
+  void addType(DIE *Entity, DIType Ty, unsigned Attribute =3D dwarf::DW_AT=
_type);
=20
   /// getOrCreateNameSpace - Create a DIE for DINameSpace.
   DIE *getOrCreateNameSpace(DINameSpace NS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DwarfDebug.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -14,10 +14,12 @@
 #define DEBUG_TYPE "dwarfdebug"
 #include "DwarfDebug.h"
 #include "DIE.h"
+#include "DwarfAccelTable.h"
 #include "DwarfCompileUnit.h"
 #include "llvm/Constants.h"
 #include "llvm/Module.h"
 #include "llvm/Instructions.h"
+#include "llvm/ADT/Triple.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/MC/MCAsmInfo.h"
@@ -52,6 +54,10 @@
      cl::desc("Make an absence of debug location information explicit."),
      cl::init(false));
=20
+static cl::opt<bool> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
+     cl::desc("Output prototype dwarf accelerator tables."),
+     cl::init(false));
+
 namespace {
   const char *DWARFGroupName =3D "DWARF Emission";
   const char *DbgTimerName =3D "DWARF Debug Writer";
@@ -128,6 +134,11 @@
   DwarfStrSectionSym =3D TextSectionSym =3D 0;
   DwarfDebugRangeSectionSym =3D DwarfDebugLocSectionSym =3D 0;
   FunctionBeginSym =3D FunctionEndSym =3D 0;
+
+  // Turn on accelerator tables for Darwin.
+  if (Triple(M->getTargetTriple()).isOSDarwin())
+    DwarfAccelTables =3D true;
+ =20
   {
     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
     beginModule(M);
@@ -136,6 +147,22 @@
 DwarfDebug::~DwarfDebug() {
 }
=20
+/// EmitSectionSym - Switch to the specified MCSection and emit an assembl=
er
+/// temporary label to it if SymbolStem is specified.
+static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
+                                const char *SymbolStem =3D 0) {
+  Asm->OutStreamer.SwitchSection(Section);
+  if (!SymbolStem) return 0;
+
+  MCSymbol *TmpSym =3D Asm->GetTempSymbol(SymbolStem);
+  Asm->OutStreamer.EmitLabel(TmpSym);
+  return TmpSym;
+}
+
+MCSymbol *DwarfDebug::getStringPool() {
+  return Asm->GetTempSymbol("section_str");
+}
+
 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
   std::pair<MCSymbol*, unsigned> &Entry =3D StringPool[Str];
   if (Entry.first) return Entry.first;
@@ -144,7 +171,6 @@
   return Entry.first =3D Asm->GetTempSymbol("string", Entry.second);
 }
=20
-
 /// assignAbbrevNumber - Define a unique number for the abbreviation.
 ///
 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
@@ -178,6 +204,63 @@
   return LinkageName;
 }
=20
+static bool isObjCClass(StringRef Name) {
+  return Name.startswith("+") || Name.startswith("-");
+}
+
+static bool hasObjCCategory(StringRef Name) {
+  if (!isObjCClass(Name)) return false;
+
+  size_t pos =3D Name.find(')');
+  if (pos !=3D std::string::npos) {
+    if (Name[pos+1] !=3D ' ') return false;
+    return true;
+  }
+  return false;
+}
+
+static void getObjCClassCategory(StringRef In, StringRef &Class,
+                                 StringRef &Category) {
+  if (!hasObjCCategory(In)) {
+    Class =3D In.slice(In.find('[') + 1, In.find(' '));
+    Category =3D "";
+    return;
+  }
+
+  Class =3D In.slice(In.find('[') + 1, In.find('('));
+  Category =3D In.slice(In.find('[') + 1, In.find(' '));
+  return;
+}
+
+static StringRef getObjCMethodName(StringRef In) {
+  return In.slice(In.find(' ') + 1, In.find(']'));
+}
+
+// Add the various names to the Dwarf accelerator table names.
+static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
+                               DIE* Die) {
+  if (!SP.isDefinition()) return;
+ =20
+  TheCU->addAccelName(SP.getName(), Die);
+
+  // If the linkage name is different than the name, go ahead and output
+  // that as well into the name table.
+  if (SP.getLinkageName() !=3D "" && SP.getName() !=3D SP.getLinkageName())
+    TheCU->addAccelName(SP.getLinkageName(), Die);
+
+  // If this is an Objective-C selector name add it to the ObjC accelerator
+  // too.
+  if (isObjCClass(SP.getName())) {
+    StringRef Class, Category;
+    getObjCClassCategory(SP.getName(), Class, Category);
+    TheCU->addAccelObjC(Class, Die);
+    if (Category !=3D "")
+      TheCU->addAccelObjC(Category, Die);
+    // Also add the base method name to the name table.
+    TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
+  }
+}
+
 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
 /// If there are global variables in this scope then create and insert
@@ -190,11 +273,7 @@
   DISubprogram SP(SPNode);
=20
   DISubprogram SPDecl =3D SP.getFunctionDeclaration();
-  if (SPDecl.isSubprogram())
-    // Refer function declaration directly.
-    SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_re=
f4,
-                      SPCU->getOrCreateSubprogramDIE(SPDecl));
-  else {
+  if (!SPDecl.isSubprogram()) {
     // There is not any need to generate specification DIE for a function
     // defined at compile unit level. If a function is defined inside anot=
her
     // function then gdb prefers the definition at top level and but does =
not
@@ -203,7 +282,7 @@
     if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
         !SP.getContext().isFile() &&
         !isSubprogramContext(SP.getContext())) {
-      SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag,=
 1);
+      SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, =
1);
      =20
       // Add arguments.
       DICompositeType SPTy =3D SP.getType();
@@ -241,6 +320,10 @@
   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
   SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
=20
+  // Add name to the name table, we do this here because we're guaranteed
+  // to have concrete versions of our DW_TAG_subprogram nodes.
+  addSubprogramNames(SPCU, SP, SPDie);
+ =20
   return SPDie;
 }
=20
@@ -248,7 +331,6 @@
 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,=20
                                           LexicalScope *Scope) {
-
   DIE *ScopeDIE =3D new DIE(dwarf::DW_TAG_lexical_block);
   if (Scope->isAbstractScope())
     return ScopeDIE;
@@ -294,10 +376,9 @@
 /// of the function.
 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
                                           LexicalScope *Scope) {
-
   const SmallVector<InsnRange, 4> &Ranges =3D Scope->getRanges();
-  assert (Ranges.empty() =3D=3D false
-          && "LexicalScope does not have instruction markers!");
+  assert(Ranges.empty() =3D=3D false &&
+         "LexicalScope does not have instruction markers!");
=20
   if (!Scope->getScopeNode())
     return NULL;
@@ -314,8 +395,7 @@
   const MCSymbol *EndLabel =3D getLabelAfterInsn(RI->second);
=20
   if (StartLabel =3D=3D 0 || EndLabel =3D=3D 0) {
-    assert (0 && "Unexpected Start and End labels for a inlined scope!");
-    return 0;
+    llvm_unreachable("Unexpected Start and End labels for a inlined scope!=
");
   }
   assert(StartLabel->isDefined() &&
          "Invalid starting label for an inlined scope!");
@@ -358,16 +438,20 @@
     I =3D InlineInfo.find(InlinedSP);
=20
   if (I =3D=3D InlineInfo.end()) {
-    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
-                                                             ScopeDIE));
+    InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
     InlinedSPNodes.push_back(InlinedSP);
   } else
     I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
=20
   DILocation DL(Scope->getInlinedAt());
-  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
+  TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
+                 GetOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
=20
+  // Add name to the name table, we do this here because we're guaranteed
+  // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
+  addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
+ =20
   return ScopeDIE;
 }
=20
@@ -376,7 +460,7 @@
   if (!Scope || !Scope->getScopeNode())
     return NULL;
=20
-  SmallVector <DIE *, 8> Children;
+  SmallVector<DIE *, 8> Children;
=20
   // Collect arguments for current function.
   if (LScopes.isCurrentFunctionScope(Scope))
@@ -426,39 +510,39 @@
     ScopeDIE->addChild(*I);
=20
   if (DS.isSubprogram())
-   TheCU->addPubTypes(DISubprogram(DS));
+    TheCU->addPubTypes(DISubprogram(DS));
=20
- return ScopeDIE;
+  return ScopeDIE;
 }
=20
 /// GetOrCreateSourceID - Look up the source id with the given directory a=
nd
 /// source file names. If none currently exists, create a new id and inser=
t it
 /// in the SourceIds map. This can update DirectoryNames and SourceFileNam=
es
 /// maps as well.
-
 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,=20
                                          StringRef DirName) {
   // If FE did not provide a file name, then assume stdin.
   if (FileName.empty())
     return GetOrCreateSourceID("<stdin>", StringRef());
=20
-  // MCStream expects full path name as filename.
-  if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
-    SmallString<128> FullPathName =3D DirName;
-    sys::path::append(FullPathName, FileName);
-    // Here FullPathName will be copied into StringMap by GetOrCreateSourc=
eID.
-    return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
-  }
+  // TODO: this might not belong here. See if we can factor this better.
+  if (DirName =3D=3D CompilationDir)
+    DirName =3D "";
=20
-  StringMapEntry<unsigned> &Entry =3D SourceIdMap.GetOrCreateValue(FileNam=
e);
-  if (Entry.getValue())
-    return Entry.getValue();
+  unsigned SrcId =3D SourceIdMap.size()+1;
=20
-  unsigned SrcId =3D SourceIdMap.size();
-  Entry.setValue(SrcId);
+  // We look up the file/dir pair by concatenating them with a zero byte.
+  SmallString<128> NamePair;
+  NamePair +=3D DirName;
+  NamePair +=3D '\0'; // Zero bytes are not allowed in paths.
+  NamePair +=3D FileName;
+
+  StringMapEntry<unsigned> &Ent =3D SourceIdMap.GetOrCreateValue(NamePair,=
 SrcId);
+  if (Ent.getValue() !=3D SrcId)
+    return Ent.getValue();
=20
   // Print out a .file directive to specify files for .loc directives.
-  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
+  Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
=20
   return SrcId;
 }
@@ -468,39 +552,36 @@
 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
   DICompileUnit DIUnit(N);
   StringRef FN =3D DIUnit.getFilename();
-  StringRef Dir =3D DIUnit.getDirectory();
-  unsigned ID =3D GetOrCreateSourceID(FN, Dir);
+  CompilationDir =3D DIUnit.getDirectory();
+  unsigned ID =3D GetOrCreateSourceID(FN, CompilationDir);
=20
   DIE *Die =3D new DIE(dwarf::DW_TAG_compile_unit);
-  CompileUnit *NewCU =3D new CompileUnit(ID, Die, Asm, this);
-  NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
-                   DIUnit.getProducer());
+  CompileUnit *NewCU =3D new CompileUnit(ID, DIUnit.getLanguage(), Die, As=
m, this);
+  NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
   NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
                  DIUnit.getLanguage());
-  NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
-  // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
-  // simplifies debug range entries.
-  NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
+  NewCU->addString(Die, dwarf::DW_AT_name, FN);
+  // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
+  // into an entity.
+  NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
   // DW_AT_stmt_list is a offset of line number information for this
   // compile unit in debug_line section.
-  if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
+  if (Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
                     Asm->GetTempSymbol("section_line"));
   else
     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
=20
-  if (!Dir.empty())
-    NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Di=
r);
+  if (!CompilationDir.empty())
+    NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
   if (DIUnit.isOptimized())
     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag,=
 1);
=20
   StringRef Flags =3D DIUnit.getFlags();
   if (!Flags.empty())
-    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,=20
-                     Flags);
+    NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
  =20
-  unsigned RVer =3D DIUnit.getRunTimeVersion();
-  if (RVer)
+  if (unsigned RVer =3D DIUnit.getRunTimeVersion())
     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
             dwarf::DW_FORM_data1, RVer);
=20
@@ -513,6 +594,11 @@
 /// construct SubprogramDIE - Construct subprogram DIE.
 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,=20
                                         const MDNode *N) {
+  CompileUnit *&CURef =3D SPMap[N];
+  if (CURef)
+    return;
+  CURef =3D TheCU;
+
   DISubprogram SP(N);
   if (!SP.isDefinition())
     // This is a method declaration which will be handled while constructi=
ng
@@ -527,10 +613,6 @@
   // Add to context owner.
   TheCU->addToContextOwner(SubprogramDie, SP.getContext());
=20
-  // Expose as global.
-  TheCU->addGlobal(SP.getName(), SubprogramDie);
-
-  SPMap[N] =3D TheCU;
   return;
 }
=20
@@ -676,7 +758,7 @@
        =20
         // Construct subprogram DIE and add variables DIEs.
         CompileUnit *SPCU =3D CUMap.lookup(TheCU);
-        assert (SPCU && "Unable to find Compile Unit!");
+        assert(SPCU && "Unable to find Compile Unit!");
         constructSubprogramDIE(SPCU, SP);
         DIE *ScopeDIE =3D SPCU->getDIE(SP);
         for (unsigned vi =3D 0, ve =3D Variables.getNumElements(); vi !=3D=
 ve; ++vi) {
@@ -697,6 +779,13 @@
     DIE *ISP =3D *AI;
     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
   }
+  for (DenseMap<const MDNode *, DIE *>::iterator AI =3D AbstractSPDies.beg=
in(),
+         AE =3D AbstractSPDies.end(); AI !=3D AE; ++AI) {
+    DIE *ISP =3D AI->second;
+    if (InlinedSubprogramDIEs.count(ISP))
+      continue;
+    FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
+  }
=20
   // Emit DW_AT_containing_type attribute to connect types with their
   // vtable holding type.
@@ -727,9 +816,14 @@
   // Corresponding abbreviations into a abbrev section.
   emitAbbreviations();
=20
-  // Emit info into a debug pubnames section.
-  emitDebugPubNames();
-
+  // Emit info into a dwarf accelerator table sections.
+  if (DwarfAccelTables) {
+    emitAccelNames();
+    emitAccelObjC();
+    emitAccelNamespaces();
+    emitAccelTypes();
+  }
+ =20
   // Emit info into a debug pubtypes section.
   emitDebugPubTypes();
=20
@@ -837,7 +931,7 @@
 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
 /// DBG_VALUE instruction, is in a defined reg.
 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
-  assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
+  assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
   return MI->getNumOperands() =3D=3D 3 &&
          MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
          MI->getOperand(1).isImm() && MI->getOperand(1).getImm() =3D=3D 0;
@@ -867,8 +961,7 @@
   if (MI->getOperand(0).isCImm())
     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
=20
-  assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
-  return DotDebugLocEntry();
+  llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
 }
=20
 /// collectVariableInfo - Find variables for each lexical scope.
@@ -964,7 +1057,8 @@
       }
=20
       // The value is valid until the next DBG_VALUE or clobber.
-      DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, B=
egin));
+      DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
+                                                    Begin));
     }
     DotDebugLocEntries.push_back(DotDebugLocEntry());
   }
@@ -999,12 +1093,15 @@
   if (!MI->isDebugValue()) {
     DebugLoc DL =3D MI->getDebugLoc();
     if (DL !=3D PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
-      unsigned Flags =3D DWARF2_FLAG_IS_STMT;
+      unsigned Flags =3D 0;
       PrevInstLoc =3D DL;
       if (DL =3D=3D PrologEndLoc) {
         Flags |=3D DWARF2_FLAG_PROLOGUE_END;
         PrologEndLoc =3D DebugLoc();
       }
+      if (PrologEndLoc.isUnknown())
+        Flags |=3D DWARF2_FLAG_IS_STMT;
+
       if (!DL.isUnknown()) {
         const MDNode *Scope =3D DL.getScope(Asm->MF->getFunction()->getCon=
text());
         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
@@ -1099,12 +1196,19 @@
 }
=20
 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
-/// line number  info for the function.
+/// line number info for the function.
 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
   const MDNode *Scope =3D getScopeNode(DL, Ctx);
   DISubprogram SP =3D getDISubprogram(Scope);
-  if (SP.Verify())=20
-    return DebugLoc::get(SP.getLineNumber(), 0, SP);
+  if (SP.Verify()) {
+    // Check for number of operands since the compatibility is
+    // cheap here.
+    if (SP->getNumOperands() > 19)
+      return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
+    else
+      return DebugLoc::get(SP.getLineNumber(), 0, SP);
+  }
+
   return DebugLoc();
 }
=20
@@ -1135,7 +1239,7 @@
       const MachineInstr *MI =3D II;
=20
       if (MI->isDebugValue()) {
-        assert (MI->getNumOperands() > 1 && "Invalid machine instruction!"=
);
+        assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
=20
         // Keep track of user variables.
         const MDNode *Var =3D
@@ -1206,7 +1310,7 @@
                MOE =3D MI->operands_end(); MOI !=3D MOE; ++MOI) {
           if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
             continue;
-          for (const unsigned *AI =3D TRI->getOverlaps(MOI->getReg());
+          for (const uint16_t *AI =3D TRI->getOverlaps(MOI->getReg());
                unsigned Reg =3D *AI; ++AI) {
             const MDNode *Var =3D LiveUserVar[Reg];
             if (!Var)
@@ -1277,7 +1381,7 @@
                                        MF->getFunction()->getContext());
     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
                      FnStartDL.getScope(MF->getFunction()->getContext()),
-                     DWARF2_FLAG_IS_STMT);
+                     0);
   }
 }
=20
@@ -1303,7 +1407,7 @@
  =20
   LexicalScope *FnScope =3D LScopes.getCurrentFunctionScope();
   CompileUnit *TheCU =3D SPMap.lookup(FnScope->getScopeNode());
-  assert (TheCU && "Unable to find compile unit!");
+  assert(TheCU && "Unable to find compile unit!");
=20
   // Construct abstract scopes.
   ArrayRef<LexicalScope *> AList =3D LScopes.getAbstractScopesList();
@@ -1327,7 +1431,7 @@
  =20
   DIE *CurFnDIE =3D constructScopeDIE(TheCU, FnScope);
  =20
-  if (!DisableFramePointerElim(*MF))
+  if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
     TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
                    dwarf::DW_FORM_flag, 1);
=20
@@ -1380,7 +1484,7 @@
       Fn =3D DB.getFilename();
       Dir =3D DB.getDirectory();
     } else
-      assert(0 && "Unexpected scope info");
+      llvm_unreachable("Unexpected scope info");
=20
     Src =3D GetOrCreateSourceID(Fn, Dir);
   }
@@ -1398,10 +1502,6 @@
   // Get the children.
   const std::vector<DIE *> &Children =3D Die->getChildren();
=20
-  // If not last sibling and has children then add sibling offset attribut=
e.
-  if (!Last && !Children.empty())
-    Die->addSiblingOffset(DIEValueAllocator);
-
   // Record the abbreviation.
   assignAbbrevNumber(Die->getAbbrev());
=20
@@ -1454,18 +1554,6 @@
   }
 }
=20
-/// EmitSectionSym - Switch to the specified MCSection and emit an assembl=
er
-/// temporary label to it if SymbolStem is specified.
-static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
-                                const char *SymbolStem =3D 0) {
-  Asm->OutStreamer.SwitchSection(Section);
-  if (!SymbolStem) return 0;
-
-  MCSymbol *TmpSym =3D Asm->GetTempSymbol(SymbolStem);
-  Asm->OutStreamer.EmitLabel(TmpSym);
-  return TmpSym;
-}
-
 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
 /// the start of each one.
 void DwarfDebug::EmitSectionLabels() {
@@ -1483,7 +1571,6 @@
=20
   EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
   EmitSectionSym(Asm, TLOF.getDwarfLocSection());
-  EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
   EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
   DwarfStrSectionSym =3D
     EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
@@ -1525,9 +1612,6 @@
       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
=20
     switch (Attr) {
-    case dwarf::DW_AT_sibling:
-      Asm->EmitInt32(Die->getSiblingOffset());
-      break;
     case dwarf::DW_AT_abstract_origin: {
       DIEEntry *E =3D cast<DIEEntry>(Values[i]);
       DIE *Origin =3D E->getEntry();
@@ -1539,7 +1623,7 @@
       // DW_AT_range Value encodes offset in debug_range section.
       DIEInteger *V =3D cast<DIEInteger>(Values[i]);
=20
-      if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
+      if (Asm->MAI->doesDwarfUseLabelOffsetForRanges()) {
         Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
                                  V->getValue(),
                                  4);
@@ -1678,62 +1762,133 @@
   Asm->EmitInt8(1);
 }
=20
-/// emitDebugPubNames - Emit visible names into a debug pubnames section.
-///
-void DwarfDebug::emitDebugPubNames() {
+/// emitAccelNames - Emit visible names into a hashed accelerator table
+/// section.
+void DwarfDebug::emitAccelNames() {
+  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOf=
fset,
+                                           dwarf::DW_FORM_data4));
   for (DenseMap<const MDNode *, CompileUnit *>::iterator I =3D CUMap.begin=
(),
          E =3D CUMap.end(); I !=3D E; ++I) {
     CompileUnit *TheCU =3D I->second;
-    // Start the dwarf pubnames section.
-    Asm->OutStreamer.SwitchSection(
-      Asm->getObjFileLowering().getDwarfPubNamesSection());
+    const StringMap<std::vector<DIE*> > &Names =3D TheCU->getAccelNames();
+    for (StringMap<std::vector<DIE*> >::const_iterator
+           GI =3D Names.begin(), GE =3D Names.end(); GI !=3D GE; ++GI) {
+      const char *Name =3D GI->getKeyData();
+      const std::vector<DIE *> &Entities =3D GI->second;
+      for (std::vector<DIE *>::const_iterator DI =3D Entities.begin(),
+             DE =3D Entities.end(); DI !=3D DE; ++DI)
+        AT.AddName(Name, (*DI));
+    }
+  }
=20
-    Asm->OutStreamer.AddComment("Length of Public Names Info");
-    Asm->EmitLabelDifference(
-      Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
-      Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
+  AT.FinalizeTable(Asm, "Names");
+  Asm->OutStreamer.SwitchSection(
+    Asm->getObjFileLowering().getDwarfAccelNamesSection());
+  MCSymbol *SectionBegin =3D Asm->GetTempSymbol("names_begin");
+  Asm->OutStreamer.EmitLabel(SectionBegin);
=20
-    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
-                                                  TheCU->getID()));
+  // Emit the full data.
+  AT.Emit(Asm, SectionBegin, this);
+}
=20
-    Asm->OutStreamer.AddComment("DWARF Version");
-    Asm->EmitInt16(dwarf::DWARF_VERSION);
+/// emitAccelObjC - Emit objective C classes and categories into a hashed
+/// accelerator table section.
+void DwarfDebug::emitAccelObjC() {
+  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOf=
fset,
+                                           dwarf::DW_FORM_data4));
+  for (DenseMap<const MDNode *, CompileUnit *>::iterator I =3D CUMap.begin=
(),
+         E =3D CUMap.end(); I !=3D E; ++I) {
+    CompileUnit *TheCU =3D I->second;
+    const StringMap<std::vector<DIE*> > &Names =3D TheCU->getAccelObjC();
+    for (StringMap<std::vector<DIE*> >::const_iterator
+           GI =3D Names.begin(), GE =3D Names.end(); GI !=3D GE; ++GI) {
+      const char *Name =3D GI->getKeyData();
+      const std::vector<DIE *> &Entities =3D GI->second;
+      for (std::vector<DIE *>::const_iterator DI =3D Entities.begin(),
+             DE =3D Entities.end(); DI !=3D DE; ++DI)
+        AT.AddName(Name, (*DI));
+    }
+  }
=20
-    Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
-    Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()=
),
-                           DwarfInfoSectionSym);
+  AT.FinalizeTable(Asm, "ObjC");
+  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
+                                 .getDwarfAccelObjCSection());
+  MCSymbol *SectionBegin =3D Asm->GetTempSymbol("objc_begin");
+  Asm->OutStreamer.EmitLabel(SectionBegin);
=20
-    Asm->OutStreamer.AddComment("Compilation Unit Length");
-    Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()=
),
-                             Asm->GetTempSymbol("info_begin", TheCU->getID=
()),
-                             4);
+  // Emit the full data.
+  AT.Emit(Asm, SectionBegin, this);
+}
=20
-    const StringMap<DIE*> &Globals =3D TheCU->getGlobals();
-    for (StringMap<DIE*>::const_iterator
-           GI =3D Globals.begin(), GE =3D Globals.end(); GI !=3D GE; ++GI)=
 {
+/// emitAccelNamespace - Emit namespace dies into a hashed accelerator
+/// table.
+void DwarfDebug::emitAccelNamespaces() {
+  DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOf=
fset,
+                                           dwarf::DW_FORM_data4));
+  for (DenseMap<const MDNode *, CompileUnit *>::iterator I =3D CUMap.begin=
(),
+         E =3D CUMap.end(); I !=3D E; ++I) {
+    CompileUnit *TheCU =3D I->second;
+    const StringMap<std::vector<DIE*> > &Names =3D TheCU->getAccelNamespac=
e();
+    for (StringMap<std::vector<DIE*> >::const_iterator
+           GI =3D Names.begin(), GE =3D Names.end(); GI !=3D GE; ++GI) {
       const char *Name =3D GI->getKeyData();
-      DIE *Entity =3D GI->second;
+      const std::vector<DIE *> &Entities =3D GI->second;
+      for (std::vector<DIE *>::const_iterator DI =3D Entities.begin(),
+             DE =3D Entities.end(); DI !=3D DE; ++DI)
+        AT.AddName(Name, (*DI));
+    }
+  }
=20
-      Asm->OutStreamer.AddComment("DIE offset");
-      Asm->EmitInt32(Entity->getOffset());
+  AT.FinalizeTable(Asm, "namespac");
+  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
+                                 .getDwarfAccelNamespaceSection());
+  MCSymbol *SectionBegin =3D Asm->GetTempSymbol("namespac_begin");
+  Asm->OutStreamer.EmitLabel(SectionBegin);
=20
-      if (Asm->isVerbose())
-        Asm->OutStreamer.AddComment("External Name");
-      Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
+  // Emit the full data.
+  AT.Emit(Asm, SectionBegin, this);
+}
+
+/// emitAccelTypes() - Emit type dies into a hashed accelerator table.
+void DwarfDebug::emitAccelTypes() {
+  std::vector<DwarfAccelTable::Atom> Atoms;
+  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffse=
t,
+                                        dwarf::DW_FORM_data4));
+  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
+                                        dwarf::DW_FORM_data2));
+  Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlag=
s,
+                                        dwarf::DW_FORM_data1));
+  DwarfAccelTable AT(Atoms);
+  for (DenseMap<const MDNode *, CompileUnit *>::iterator I =3D CUMap.begin=
(),
+         E =3D CUMap.end(); I !=3D E; ++I) {
+    CompileUnit *TheCU =3D I->second;
+    const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
+      =3D TheCU->getAccelTypes();
+    for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterat=
or
+           GI =3D Names.begin(), GE =3D Names.end(); GI !=3D GE; ++GI) {
+      const char *Name =3D GI->getKeyData();
+      const std::vector<std::pair<DIE *, unsigned> > &Entities =3D GI->sec=
ond;
+      for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
+             =3D Entities.begin(), DE =3D Entities.end(); DI !=3DDE; ++DI)
+        AT.AddName(Name, (*DI).first, (*DI).second);
     }
+  }
=20
-    Asm->OutStreamer.AddComment("End Mark");
-    Asm->EmitInt32(0);
-    Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
-                                                  TheCU->getID()));
-  }
+  AT.FinalizeTable(Asm, "types");
+  Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
+                                 .getDwarfAccelTypesSection());
+  MCSymbol *SectionBegin =3D Asm->GetTempSymbol("types_begin");
+  Asm->OutStreamer.EmitLabel(SectionBegin);
+
+  // Emit the full data.
+  AT.Emit(Asm, SectionBegin, this);
 }
=20
 void DwarfDebug::emitDebugPubTypes() {
   for (DenseMap<const MDNode *, CompileUnit *>::iterator I =3D CUMap.begin=
(),
          E =3D CUMap.end(); I !=3D E; ++I) {
     CompileUnit *TheCU =3D I->second;
-    // Start the dwarf pubnames section.
+    // Start the dwarf pubtypes section.
     Asm->OutStreamer.SwitchSection(
       Asm->getObjFileLowering().getDwarfPubTypesSection());
     Asm->OutStreamer.AddComment("Length of Public Types Info");
@@ -1766,6 +1921,7 @@
       Asm->EmitInt32(Entity->getOffset());
=20
       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
+      // Emit the name with a terminating null byte.
       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
     }
=20
@@ -1801,8 +1957,10 @@
     // Emit a label for reference from debug information entries.
     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
=20
-    // Emit the string itself.
-    Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/=
);
+    // Emit the string itself with a terminating null byte.
+    Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
+                                         Entries[i].second->getKeyLength()=
+1),
+                               0/*addrspace*/);
   }
 }
=20
@@ -1958,7 +2116,7 @@
 /// __debug_info section, and the low_pc is the starting address for the
 /// inlining instance.
 void DwarfDebug::emitDebugInlineInfo() {
-  if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
+  if (!Asm->MAI->doesDwarfUseInlineInfoSection())
     return;
=20
   if (!FirstCU)
@@ -1990,10 +2148,9 @@
     StringRef Name =3D SP.getName();
=20
     Asm->OutStreamer.AddComment("MIPS linkage name");
-    if (LName.empty()) {
-      Asm->OutStreamer.EmitBytes(Name, 0);
-      Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
-    } else
+    if (LName.empty())
+      Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
+    else
       Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
                              DwarfStrSectionSym);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DwarfDebug.h
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -30,7 +30,8 @@
 namespace llvm {
=20
 class CompileUnit;
-class DbgConcreteScope;
+class ConstantInt;
+class ConstantFP;
 class DbgVariable;
 class MachineFrameInfo;
 class MachineModuleInfo;
@@ -207,8 +208,8 @@
   ///
   std::vector<DIEAbbrev *> Abbreviations;
=20
-  /// SourceIdMap - Source id map, i.e. pair of directory id and source fi=
le
-  /// id mapped to a unique id.
+  /// SourceIdMap - Source id map, i.e. pair of source filename and direct=
ory,
+  /// separated by a zero byte, mapped to a unique id.
   StringMap<unsigned> SourceIdMap;
=20
   /// StringPool - A String->Symbol mapping of strings used by indirect
@@ -216,8 +217,6 @@
   StringMap<std::pair<MCSymbol*, unsigned> > StringPool;
   unsigned NextStringPoolNumber;
  =20
-  MCSymbol *getStringPoolEntry(StringRef Str);
-
   /// SectionMap - Provides a unique id per text section.
   ///
   UniqueVector<const MCSection*> SectionMap;
@@ -239,12 +238,12 @@
   /// DotDebugLocEntries - Collection of DotDebugLocEntry.
   SmallVector<DotDebugLocEntry, 4> DotDebugLocEntries;
=20
-  /// InliendSubprogramDIEs - Collection of subprgram DIEs that are marked
+  /// InlinedSubprogramDIEs - Collection of subprogram DIEs that are marked
   /// (at the end of the module) as DW_AT_inline.
   SmallPtrSet<DIE *, 4> InlinedSubprogramDIEs;
=20
   /// InlineInfo - Keep track of inlined functions and their location.  Th=
is
-  /// information is used to populate debug_inlined section.
+  /// information is used to populate the debug_inlined section.
   typedef std::pair<const MCSymbol *, DIE *> InlineInfoLabels;
   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> > InlineInfo;
   SmallVector<const MDNode *, 4> InlinedSPNodes;
@@ -304,6 +303,10 @@
   MCSymbol *DwarfDebugLocSectionSym;
   MCSymbol *FunctionBeginSym, *FunctionEndSym;
=20
+  // As an optimization, there is no need to emit an entry in the directory
+  // table for the same directory as DW_at_comp_dir.
+  StringRef CompilationDir;
+
 private:
=20
   /// assignAbbrevNumber - Define a unique number for the abbreviation.
@@ -340,7 +343,7 @@
   /// the start of each one.
   void EmitSectionLabels();
=20
-  /// emitDIE - Recusively Emits a debug information entry.
+  /// emitDIE - Recursively Emits a debug information entry.
   ///
   void emitDIE(DIE *Die);
=20
@@ -365,10 +368,22 @@
   ///
   void emitEndOfLineMatrix(unsigned SectionEnd);
=20
-  /// emitDebugPubNames - Emit visible names into a debug pubnames section.
+  /// emitAccelNames - Emit visible names into a hashed accelerator table
+  /// section.
+  void emitAccelNames();
+ =20
+  /// emitAccelObjC - Emit objective C classes and categories into a hashed
+  /// accelerator table section.
+  void emitAccelObjC();
+
+  /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
+  /// table.
+  void emitAccelNamespaces();
+
+  /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
   ///
-  void emitDebugPubNames();
-
+  void emitAccelTypes();
+ =20
   /// emitDebugPubTypes - Emit visible types into a debug pubtypes section.
   ///
   void emitDebugPubTypes();
@@ -407,10 +422,10 @@
   /// 3. an unsigned LEB128 number indicating the number of distinct inlin=
ing=20
   /// instances for the function.
   ///=20
-  /// The rest of the entry consists of a {die_offset, low_pc}  pair for e=
ach=20
+  /// The rest of the entry consists of a {die_offset, low_pc} pair for ea=
ch=20
   /// inlined instance; the die_offset points to the inlined_subroutine di=
e in
-  /// the __debug_info section, and the low_pc is the starting address  fo=
r the
-  ///  inlining instance.
+  /// the __debug_info section, and the low_pc is the starting address for=
 the
+  /// inlining instance.
   void emitDebugInlineInfo();
=20
   /// constructCompileUnit - Create new CompileUnit for the given=20
@@ -426,8 +441,8 @@
   void recordSourceLine(unsigned Line, unsigned Col, const MDNode *Scope,
                         unsigned Flags);
  =20
-  /// identifyScopeMarkers() - Indentify instructions that are marking
-  /// beginning of or end of a scope.
+  /// identifyScopeMarkers() - Indentify instructions that are marking the
+  /// beginning of or ending of a scope.
   void identifyScopeMarkers();
=20
   /// addCurrentFnArgument - If Var is an current function argument that a=
dd
@@ -472,7 +487,7 @@
   void collectInfoFromNamedMDNodes(Module *M);
=20
   /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
-  /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
+  /// FIXME - Remove this when DragonEgg switches to DIBuilder.
   bool collectLegacyDebugInfo(Module *M);
=20
   /// beginModule - Emit all Dwarf sections that should come prior to the
@@ -504,6 +519,13 @@
=20
   /// createSubprogramDIE - Create new DIE using SP.
   DIE *createSubprogramDIE(DISubprogram SP);
+
+  /// getStringPool - returns the entry into the start of the pool.
+  MCSymbol *getStringPool();
+
+  /// getStringPoolEntry - returns an entry into the string pool with the =
given
+  /// string text.
+  MCSymbol *getStringPoolEntry(StringRef Str);
 };
 } // End of namespace llvm
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/AsmPrint=
er/DwarfException.cpp
--- a/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfException.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/AsmPrinter/DwarfException.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -31,6 +31,7 @@
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Support/Dwarf.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormattedStream.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
@@ -184,7 +185,7 @@
 /// CallToNoUnwindFunction - Return `true' if this is a call to a function
 /// marked `nounwind'. Return `false' otherwise.
 bool DwarfException::CallToNoUnwindFunction(const MachineInstr *MI) {
-  assert(MI->getDesc().isCall() && "This should be a call instruction!");
+  assert(MI->isCall() && "This should be a call instruction!");
=20
   bool MarkedNoUnwind =3D false;
   bool SawFunc =3D false;
@@ -243,7 +244,7 @@
     for (MachineBasicBlock::const_iterator MI =3D I->begin(), E =3D I->end=
();
          MI !=3D E; ++MI) {
       if (!MI->isLabel()) {
-        if (MI->getDesc().isCall())
+        if (MI->isCall())
           SawPotentiallyThrowing |=3D !CallToNoUnwindFunction(MI);
         continue;
       }
@@ -529,10 +530,8 @@
       // Offset of the landing pad, counted in 16-byte bundles relative to=
 the
       // @LPStart address.
       if (VerboseAsm) {
-        Asm->OutStreamer.AddComment(Twine(">> Call Site ") +
-                                    llvm::utostr(idx) + " <<");
-        Asm->OutStreamer.AddComment(Twine("  On exception at call site ") +
-                                    llvm::utostr(idx));
+        Asm->OutStreamer.AddComment(">> Call Site " + Twine(idx) + " <<");
+        Asm->OutStreamer.AddComment("  On exception at call site "+Twine(i=
dx));
       }
       Asm->EmitULEB128(idx);
=20
@@ -543,8 +542,8 @@
         if (S.Action =3D=3D 0)
           Asm->OutStreamer.AddComment("  Action: cleanup");
         else
-          Asm->OutStreamer.AddComment(Twine("  Action: ") +
-                                      llvm::utostr((S.Action - 1) / 2 + 1)=
);
+          Asm->OutStreamer.AddComment("  Action: " +
+                                      Twine((S.Action - 1) / 2 + 1));
       }
       Asm->EmitULEB128(S.Action);
     }
@@ -596,8 +595,7 @@
       // number of 16-byte bundles. The first call site is counted relativ=
e to
       // the start of the procedure fragment.
       if (VerboseAsm)
-        Asm->OutStreamer.AddComment(Twine(">> Call Site ") +
-                                    llvm::utostr(++Entry) + " <<");
+        Asm->OutStreamer.AddComment(">> Call Site " + Twine(++Entry) + " <=
<");
       Asm->EmitLabelDifference(BeginLabel, EHFuncBeginSym, 4);
       if (VerboseAsm)
         Asm->OutStreamer.AddComment(Twine("  Call between ") +
@@ -625,8 +623,8 @@
         if (S.Action =3D=3D 0)
           Asm->OutStreamer.AddComment("  On action: cleanup");
         else
-          Asm->OutStreamer.AddComment(Twine("  On action: ") +
-                                      llvm::utostr((S.Action - 1) / 2 + 1)=
);
+          Asm->OutStreamer.AddComment("  On action: " +
+                                      Twine((S.Action - 1) / 2 + 1));
       }
       Asm->EmitULEB128(S.Action);
     }
@@ -640,8 +638,7 @@
=20
     if (VerboseAsm) {
       // Emit comments that decode the action table.
-      Asm->OutStreamer.AddComment(Twine(">> Action Record ") +
-                                  llvm::utostr(++Entry) + " <<");
+      Asm->OutStreamer.AddComment(">> Action Record " + Twine(++Entry) + "=
 <<");
     }
=20
     // Type Filter
@@ -650,11 +647,11 @@
     //   type of the catch clauses or the types in the exception specifica=
tion.
     if (VerboseAsm) {
       if (Action.ValueForTypeID > 0)
-        Asm->OutStreamer.AddComment(Twine("  Catch TypeInfo ") +
-                                    llvm::itostr(Action.ValueForTypeID));
+        Asm->OutStreamer.AddComment("  Catch TypeInfo " +
+                                    Twine(Action.ValueForTypeID));
       else if (Action.ValueForTypeID < 0)
-        Asm->OutStreamer.AddComment(Twine("  Filter TypeInfo ") +
-                                    llvm::itostr(Action.ValueForTypeID));
+        Asm->OutStreamer.AddComment("  Filter TypeInfo " +
+                                    Twine(Action.ValueForTypeID));
       else
         Asm->OutStreamer.AddComment("  Cleanup");
     }
@@ -669,8 +666,7 @@
         Asm->OutStreamer.AddComment("  No further actions");
       } else {
         unsigned NextAction =3D Entry + (Action.NextAction + 1) / 2;
-        Asm->OutStreamer.AddComment(Twine("  Continue to action ") +
-                                    llvm::utostr(NextAction));
+        Asm->OutStreamer.AddComment("  Continue to action "+Twine(NextActi=
on));
       }
     }
     Asm->EmitSLEB128(Action.NextAction);
@@ -687,7 +683,7 @@
          I =3D TypeInfos.rbegin(), E =3D TypeInfos.rend(); I !=3D E; ++I) {
     const GlobalVariable *GV =3D *I;
     if (VerboseAsm)
-      Asm->OutStreamer.AddComment(Twine("TypeInfo ") + llvm::utostr(Entry-=
-));
+      Asm->OutStreamer.AddComment("TypeInfo " + Twine(Entry--));
     if (GV)
       Asm->EmitReference(GV, TTypeEncoding);
     else
@@ -707,7 +703,7 @@
     if (VerboseAsm) {
       --Entry;
       if (TypeID !=3D 0)
-        Asm->OutStreamer.AddComment(Twine("FilterInfo ") + llvm::itostr(En=
try));
+        Asm->OutStreamer.AddComment("FilterInfo " + Twine(Entry));
     }
=20
     Asm->EmitULEB128(TypeID);
@@ -719,17 +715,17 @@
 /// EndModule - Emit all exception information that should come after the
 /// content.
 void DwarfException::EndModule() {
-  assert(0 && "Should be implemented");
+  llvm_unreachable("Should be implemented");
 }
=20
 /// BeginFunction - Gather pre-function exception information. Assumes it's
 /// being emitted immediately after the function entry point.
 void DwarfException::BeginFunction(const MachineFunction *MF) {
-  assert(0 && "Should be implemented");
+  llvm_unreachable("Should be implemented");
 }
=20
 /// EndFunction - Gather and emit post-function exception information.
 ///
 void DwarfException::EndFunction() {
-  assert(0 && "Should be implemented");
+  llvm_unreachable("Should be implemented");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/BranchFo=
lding.cpp
--- a/head/contrib/llvm/lib/CodeGen/BranchFolding.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/BranchFolding.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -23,6 +23,7 @@
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
+#include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/RegisterScavenging.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetMachine.h"
@@ -61,29 +62,33 @@
=20
 namespace {
   /// BranchFolderPass - Wrap branch folder in a machine function pass.
-  class BranchFolderPass : public MachineFunctionPass,
-                           public BranchFolder {
+  class BranchFolderPass : public MachineFunctionPass {
   public:
     static char ID;
-    explicit BranchFolderPass(bool defaultEnableTailMerge)
-      : MachineFunctionPass(ID), BranchFolder(defaultEnableTailMerge, true=
) {}
+    explicit BranchFolderPass(): MachineFunctionPass(ID) {}
=20
     virtual bool runOnMachineFunction(MachineFunction &MF);
-    virtual const char *getPassName() const { return "Control Flow Optimiz=
er"; }
+
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+      AU.addRequired<TargetPassConfig>();
+      MachineFunctionPass::getAnalysisUsage(AU);
+    }
   };
 }
=20
 char BranchFolderPass::ID =3D 0;
+char &llvm::BranchFolderPassID =3D BranchFolderPass::ID;
=20
-FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
-  return new BranchFolderPass(DefaultEnableTailMerge);
-}
+INITIALIZE_PASS(BranchFolderPass, "branch-folder",
+                "Control Flow Optimizer", false, false)
=20
 bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
-  return OptimizeFunction(MF,
-                          MF.getTarget().getInstrInfo(),
-                          MF.getTarget().getRegisterInfo(),
-                          getAnalysisIfAvailable<MachineModuleInfo>());
+  TargetPassConfig *PassConfig =3D &getAnalysis<TargetPassConfig>();
+  BranchFolder Folder(PassConfig->getEnableTailMerge(), /*CommonHoist=3D*/=
true);
+  return Folder.OptimizeFunction(MF,
+                                 MF.getTarget().getInstrInfo(),
+                                 MF.getTarget().getRegisterInfo(),
+                                 getAnalysisIfAvailable<MachineModuleInfo>=
());
 }
=20
=20
@@ -132,7 +137,7 @@
       break;
     unsigned Reg =3D I->getOperand(0).getReg();
     ImpDefRegs.insert(Reg);
-    for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+    for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
          unsigned SubReg =3D *SubRegs; ++SubRegs)
       ImpDefRegs.insert(SubReg);
     ++I;
@@ -179,8 +184,14 @@
   TII =3D tii;
   TRI =3D tri;
   MMI =3D mmi;
+  RS =3D NULL;
=20
-  RS =3D TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
+  // Use a RegScavenger to help update liveness when required.
+  MachineRegisterInfo &MRI =3D MF.getRegInfo();
+  if (MRI.tracksLiveness() && TRI->requiresRegisterScavenging(MF))
+    RS =3D new RegScavenger();
+  else
+    MRI.invalidateLiveness();
=20
   // Fix CFG.  The later algorithms expect it to be right.
   bool MadeChange =3D false;
@@ -208,7 +219,7 @@
     delete RS;
     return MadeChange;
   }
- =20
+
   // Walk the function to find jump tables that are live.
   BitVector JTIsLive(JTI->getJumpTables().size());
   for (MachineFunction::iterator BB =3D MF.begin(), E =3D MF.end();
@@ -432,10 +443,9 @@
   for (; I !=3D E; ++I) {
     if (I->isDebugValue())
       continue;
-    const MCInstrDesc &MCID =3D I->getDesc();
-    if (MCID.isCall())
+    if (I->isCall())
       Time +=3D 10;
-    else if (MCID.mayLoad() || MCID.mayStore())
+    else if (I->mayLoad() || I->mayStore())
       Time +=3D 2;
     else
       ++Time;
@@ -484,8 +494,9 @@
     // an object with itself.
 #ifndef _GLIBCXX_DEBUG
     llvm_unreachable("Predecessor appears twice");
+#else
+    return false;
 #endif
-    return false;
   }
 }
=20
@@ -502,7 +513,7 @@
       break;
     }
     --I;
-    if (!I->getDesc().isTerminator()) break;
+    if (!I->isTerminator()) break;
     ++NumTerms;
   }
   return NumTerms;
@@ -550,8 +561,8 @@
   // heuristics.
   unsigned EffectiveTailLen =3D CommonTailLen;
   if (SuccBB && MBB1 !=3D PredBB && MBB2 !=3D PredBB &&
-      !MBB1->back().getDesc().isBarrier() &&
-      !MBB2->back().getDesc().isBarrier())
+      !MBB1->back().isBarrier() &&
+      !MBB2->back().isBarrier())
     ++EffectiveTailLen;
=20
   // Check if the common tail is long enough to be worthwhile.
@@ -870,6 +881,9 @@
         // Visit each predecessor only once.
         if (!UniquePreds.insert(PBB))
           continue;
+        // Skip blocks which may jump to a landing pad. Can't tail merge t=
hese.
+        if (PBB->getLandingPadSuccessor())
+          continue;
         MachineBasicBlock *TBB =3D 0, *FBB =3D 0;
         SmallVector<MachineOperand, 4> Cond;
         if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
@@ -924,8 +938,9 @@
       if (MergePotentials.size() >=3D 2)
         MadeChange |=3D TryTailMergeBlocks(IBB, PredBB);
       // Reinsert an unconditional branch if needed.
-      // The 1 below can occur as a result of removing blocks in TryTailMe=
rgeBlocks.
-      PredBB =3D prior(I);      // this may have been changed in TryTailMe=
rgeBlocks
+      // The 1 below can occur as a result of removing blocks in
+      // TryTailMergeBlocks.
+      PredBB =3D prior(I);     // this may have been changed in TryTailMer=
geBlocks
       if (MergePotentials.size() =3D=3D 1 &&
           MergePotentials.begin()->getBlock() !=3D PredBB)
         FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
@@ -980,7 +995,7 @@
     if (!MBBI->isDebugValue())
       break;
   }
-  return (MBBI->getDesc().isBranch());
+  return (MBBI->isBranch());
 }
=20
 /// IsBetterFallthrough - Return true if it would be clearly better to
@@ -1008,7 +1023,23 @@
   MachineBasicBlock::iterator MBB2I =3D --MBB2->end();
   while (MBB2I->isDebugValue())
     --MBB2I;
-  return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
+  return MBB2I->isCall() && !MBB1I->isCall();
+}
+
+/// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
+/// instructions on the block. Always use the DebugLoc of the first
+/// branching instruction found unless its absent, in which case use the
+/// DebugLoc of the second if present.
+static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
+  MachineBasicBlock::iterator I =3D MBB.end();
+  if (I =3D=3D MBB.begin())
+    return DebugLoc();
+  --I;
+  while (I->isDebugValue() && I !=3D MBB.begin())
+    --I;
+  if (I->isBranch())
+    return I->getDebugLoc();
+  return DebugLoc();
 }
=20
 /// OptimizeBlock - Analyze and optimize control flow related to the speci=
fied
@@ -1016,7 +1047,6 @@
 bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
   bool MadeChange =3D false;
   MachineFunction &MF =3D *MBB->getParent();
-  DebugLoc dl;  // FIXME: this is nowhere
 ReoptimizeBlock:
=20
   MachineFunction::iterator FallThrough =3D MBB;
@@ -1065,6 +1095,7 @@
     // destination, remove the branch, replacing it with an unconditional =
one or
     // a fall-through.
     if (PriorTBB && PriorTBB =3D=3D PriorFBB) {
+      DebugLoc dl =3D getBranchDebugLoc(PrevBB);
       TII->RemoveBranch(PrevBB);
       PriorCond.clear();
       if (PriorTBB !=3D MBB)
@@ -1091,7 +1122,7 @@
         MachineBasicBlock::iterator PrevBBIter =3D PrevBB.end();
         --PrevBBIter;
         MachineBasicBlock::iterator MBBIter =3D MBB->begin();
-        // Check if DBG_VALUE at the end of PrevBB is identical to the=20
+        // Check if DBG_VALUE at the end of PrevBB is identical to the
         // DBG_VALUE at the beginning of MBB.
         while (PrevBBIter !=3D PrevBB.begin() && MBBIter !=3D MBB->end()
                && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
@@ -1103,7 +1134,7 @@
         }
       }
       PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
-      PrevBB.removeSuccessor(PrevBB.succ_begin());;
+      PrevBB.removeSuccessor(PrevBB.succ_begin());
       assert(PrevBB.succ_empty());
       PrevBB.transferSuccessors(MBB);
       MadeChange =3D true;
@@ -1122,6 +1153,7 @@
     // If the prior block branches somewhere else on the condition and her=
e if
     // the condition is false, remove the uncond second branch.
     if (PriorFBB =3D=3D MBB) {
+      DebugLoc dl =3D getBranchDebugLoc(PrevBB);
       TII->RemoveBranch(PrevBB);
       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
       MadeChange =3D true;
@@ -1135,6 +1167,7 @@
     if (PriorTBB =3D=3D MBB) {
       SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
       if (!TII->ReverseBranchCondition(NewPriorCond)) {
+        DebugLoc dl =3D getBranchDebugLoc(PrevBB);
         TII->RemoveBranch(PrevBB);
         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond, dl);
         MadeChange =3D true;
@@ -1172,6 +1205,7 @@
           DEBUG(dbgs() << "\nMoving MBB: " << *MBB
                        << "To make fallthrough to: " << *PriorTBB << "\n");
=20
+          DebugLoc dl =3D getBranchDebugLoc(PrevBB);
           TII->RemoveBranch(PrevBB);
           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond, dl);
=20
@@ -1201,6 +1235,7 @@
     if (CurTBB && CurFBB && CurFBB =3D=3D MBB && CurTBB !=3D MBB) {
       SmallVector<MachineOperand, 4> NewCond(CurCond);
       if (!TII->ReverseBranchCondition(NewCond)) {
+        DebugLoc dl =3D getBranchDebugLoc(*MBB);
         TII->RemoveBranch(*MBB);
         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
         MadeChange =3D true;
@@ -1214,6 +1249,7 @@
     if (CurTBB && CurCond.empty() && CurFBB =3D=3D 0 &&
         IsBranchOnlyBlock(MBB) && CurTBB !=3D MBB &&
         !MBB->hasAddressTaken()) {
+      DebugLoc dl =3D getBranchDebugLoc(*MBB);
       // This block may contain just an unconditional branch.  Because the=
re can
       // be 'non-branch terminators' in the block, try removing the branch=
 and
       // then seeing if the block is empty.
@@ -1256,8 +1292,9 @@
               assert(PriorFBB =3D=3D 0 && "Machine CFG out of date!");
               PriorFBB =3D MBB;
             }
+            DebugLoc pdl =3D getBranchDebugLoc(PrevBB);
             TII->RemoveBranch(PrevBB);
-            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, dl);
+            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
           }
=20
           // Iterate through all the predecessors, revectoring each in-tur=
n.
@@ -1281,9 +1318,10 @@
               bool NewCurUnAnalyzable =3D TII->AnalyzeBranch(*PMBB, NewCur=
TBB,
                       NewCurFBB, NewCurCond, true);
               if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB =3D=3D New=
CurFBB) {
+                DebugLoc pdl =3D getBranchDebugLoc(*PMBB);
                 TII->RemoveBranch(*PMBB);
                 NewCurCond.clear();
-                TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond, dl);
+                TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond, pdl);
                 MadeChange =3D true;
                 ++NumBranchOpts;
                 PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
@@ -1343,7 +1381,7 @@
           if (CurFallsThru) {
             MachineBasicBlock *NextBB =3D llvm::next(MachineFunction::iter=
ator(MBB));
             CurCond.clear();
-            TII->InsertBranch(*MBB, NextBB, 0, CurCond, dl);
+            TII->InsertBranch(*MBB, NextBB, 0, CurCond, DebugLoc());
           }
           MBB->moveAfter(PredBB);
           MadeChange =3D true;
@@ -1446,7 +1484,7 @@
       continue;
     if (MO.isUse()) {
       Uses.insert(Reg);
-      for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
+      for (const uint16_t *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
         Uses.insert(*AS);
     } else if (!MO.isDead())
       // Don't try to hoist code in the rare case the terminator defines a
@@ -1469,6 +1507,9 @@
   bool IsDef =3D false;
   for (unsigned i =3D 0, e =3D PI->getNumOperands(); !IsDef && i !=3D e; +=
+i) {
     const MachineOperand &MO =3D PI->getOperand(i);
+    // If PI has a regmask operand, it is probably a call. Separate away.
+    if (MO.isRegMask())
+      return Loc;
     if (!MO.isReg() || MO.isUse())
       continue;
     unsigned Reg =3D MO.getReg();
@@ -1505,16 +1546,16 @@
       continue;
     if (MO.isUse()) {
       Uses.insert(Reg);
-      for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
+      for (const uint16_t *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
         Uses.insert(*AS);
     } else {
       if (Uses.count(Reg)) {
         Uses.erase(Reg);
-        for (const unsigned *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
+        for (const uint16_t *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
           Uses.erase(*SR); // Use getSubRegisters to be conservative
       }
       Defs.insert(Reg);
-      for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
+      for (const uint16_t *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
         Defs.insert(*AS);
     }
   }
@@ -1581,6 +1622,11 @@
     bool IsSafe =3D true;
     for (unsigned i =3D 0, e =3D TIB->getNumOperands(); i !=3D e; ++i) {
       MachineOperand &MO =3D TIB->getOperand(i);
+      // Don't attempt to hoist instructions with register masks.
+      if (MO.isRegMask()) {
+        IsSafe =3D false;
+        break;
+      }
       if (!MO.isReg())
         continue;
       unsigned Reg =3D MO.getReg();
@@ -1615,6 +1661,11 @@
           IsSafe =3D false;
           break;
         }
+
+        if (MO.isKill() && Uses.count(Reg))
+          // Kills a register that's read by the instruction at the point =
of
+          // insertion. Remove the kill marker.
+          MO.setIsKill(false);
       }
     }
     if (!IsSafe)
@@ -1632,7 +1683,7 @@
       unsigned Reg =3D MO.getReg();
       if (!Reg || !LocalDefsSet.count(Reg))
         continue;
-      for (const unsigned *OR =3D TRI->getOverlaps(Reg); *OR; ++OR)
+      for (const uint16_t *OR =3D TRI->getOverlaps(Reg); *OR; ++OR)
         LocalDefsSet.erase(*OR);
     }
=20
@@ -1645,11 +1696,11 @@
       if (!Reg)
         continue;
       LocalDefs.push_back(Reg);
-      for (const unsigned *OR =3D TRI->getOverlaps(Reg); *OR; ++OR)
+      for (const uint16_t *OR =3D TRI->getOverlaps(Reg); *OR; ++OR)
         LocalDefsSet.insert(*OR);
     }
=20
-    HasDups =3D true;;
+    HasDups =3D true;
     ++TIB;
     ++FIB;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/CallingC=
onvLower.cpp
--- a/head/contrib/llvm/lib/CodeGen/CallingConvLower.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/CallingConvLower.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -58,7 +58,7 @@
=20
 /// MarkAllocated - Mark a register and all of its aliases as allocated.
 void CCState::MarkAllocated(unsigned Reg) {
-  for (const unsigned *Alias =3D TRI.getOverlaps(Reg);
+  for (const uint16_t *Alias =3D TRI.getOverlaps(Reg);
        unsigned Reg =3D *Alias; ++Alias)
     UsedRegs[Reg/32] |=3D 1 << (Reg&31);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/CodeGen.=
cpp
--- a/head/contrib/llvm/lib/CodeGen/CodeGen.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/CodeGen/CodeGen.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -19,36 +19,49 @@
=20
 /// initializeCodeGen - Initialize all passes linked into the CodeGen libr=
ary.
 void llvm::initializeCodeGen(PassRegistry &Registry) {
+  initializeBranchFolderPassPass(Registry);
   initializeCalculateSpillWeightsPass(Registry);
+  initializeCodePlacementOptPass(Registry);
   initializeDeadMachineInstructionElimPass(Registry);
+  initializeExpandPostRAPass(Registry);
+  initializeExpandISelPseudosPass(Registry);
+  initializeFinalizeMachineBundlesPass(Registry);
+  initializeGCMachineCodeAnalysisPass(Registry);
   initializeGCModuleInfoPass(Registry);
   initializeIfConverterPass(Registry);
   initializeLiveDebugVariablesPass(Registry);
   initializeLiveIntervalsPass(Registry);
   initializeLiveStacksPass(Registry);
   initializeLiveVariablesPass(Registry);
+  initializeLocalStackSlotPassPass(Registry);
   initializeMachineBlockFrequencyInfoPass(Registry);
+  initializeMachineBlockPlacementPass(Registry);
+  initializeMachineBlockPlacementStatsPass(Registry);
+  initializeMachineCopyPropagationPass(Registry);
   initializeMachineCSEPass(Registry);
   initializeMachineDominatorTreePass(Registry);
   initializeMachineLICMPass(Registry);
   initializeMachineLoopInfoPass(Registry);
   initializeMachineModuleInfoPass(Registry);
+  initializeMachineSchedulerPass(Registry);
   initializeMachineSinkingPass(Registry);
   initializeMachineVerifierPassPass(Registry);
   initializeOptimizePHIsPass(Registry);
   initializePHIEliminationPass(Registry);
   initializePeepholeOptimizerPass(Registry);
+  initializePostRASchedulerPass(Registry);
   initializeProcessImplicitDefsPass(Registry);
   initializePEIPass(Registry);
-  initializeRALinScanPass(Registry);
   initializeRegisterCoalescerPass(Registry);
   initializeRenderMachineFunctionPass(Registry);
   initializeSlotIndexesPass(Registry);
-  initializeLoopSplitterPass(Registry);
   initializeStackProtectorPass(Registry);
   initializeStackSlotColoringPass(Registry);
   initializeStrongPHIEliminationPass(Registry);
+  initializeTailDuplicatePassPass(Registry);
+  initializeTargetPassConfigPass(Registry);
   initializeTwoAddressInstructionPassPass(Registry);
+  initializeUnpackMachineBundlesPass(Registry);
   initializeUnreachableBlockElimPass(Registry);
   initializeUnreachableMachineBlockElimPass(Registry);
   initializeVirtRegMapPass(Registry);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/CodePlac=
ementOpt.cpp
--- a/head/contrib/llvm/lib/CodeGen/CodePlacementOpt.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/CodePlacementOpt.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -39,9 +39,6 @@
     CodePlacementOpt() : MachineFunctionPass(ID) {}
=20
     virtual bool runOnMachineFunction(MachineFunction &MF);
-    virtual const char *getPassName() const {
-      return "Code Placement Optimizer";
-    }
=20
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<MachineLoopInfo>();
@@ -69,9 +66,9 @@
   char CodePlacementOpt::ID =3D 0;
 } // end anonymous namespace
=20
-FunctionPass *llvm::createCodePlacementOptPass() {
-  return new CodePlacementOpt();
-}
+char &llvm::CodePlacementOptID =3D CodePlacementOpt::ID;
+INITIALIZE_PASS(CodePlacementOpt, "code-placement",
+                "Code Placement Optimizer", false, false)
=20
 /// HasFallthrough - Test whether the given branch has a fallthrough, eith=
er as
 /// a plain fallthrough or as a fallthrough case of a conditional branch.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Critical=
AntiDepBreaker.cpp
--- a/head/contrib/llvm/lib/CodeGen/CriticalAntiDepBreaker.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/CriticalAntiDepBreaker.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -35,7 +35,8 @@
   RegClassInfo(RCI),
   Classes(TRI->getNumRegs(), static_cast<const TargetRegisterClass *>(0)),
   KillIndices(TRI->getNumRegs(), 0),
-  DefIndices(TRI->getNumRegs(), 0) {}
+  DefIndices(TRI->getNumRegs(), 0),
+  KeepRegs(TRI->getNumRegs(), false) {}
=20
 CriticalAntiDepBreaker::~CriticalAntiDepBreaker() {
 }
@@ -52,9 +53,9 @@
   }
=20
   // Clear "do not change" set.
-  KeepRegs.clear();
+  KeepRegs.reset();
=20
-  bool IsReturnBlock =3D (!BB->empty() && BB->back().getDesc().isReturn());
+  bool IsReturnBlock =3D (BBSize !=3D 0 && BB->back().isReturn());
=20
   // Determine the live-out physregs for this block.
   if (IsReturnBlock) {
@@ -63,14 +64,14 @@
          E =3D MRI.liveout_end(); I !=3D E; ++I) {
       unsigned Reg =3D *I;
       Classes[Reg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
-      KillIndices[Reg] =3D BB->size();
+      KillIndices[Reg] =3D BBSize;
       DefIndices[Reg] =3D ~0u;
=20
       // Repeat, for all aliases.
-      for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alia=
s) {
+      for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alia=
s) {
         unsigned AliasReg =3D *Alias;
         Classes[AliasReg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
-        KillIndices[AliasReg] =3D BB->size();
+        KillIndices[AliasReg] =3D BBSize;
         DefIndices[AliasReg] =3D ~0u;
       }
     }
@@ -85,14 +86,14 @@
            E =3D (*SI)->livein_end(); I !=3D E; ++I) {
       unsigned Reg =3D *I;
       Classes[Reg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
-      KillIndices[Reg] =3D BB->size();
+      KillIndices[Reg] =3D BBSize;
       DefIndices[Reg] =3D ~0u;
=20
       // Repeat, for all aliases.
-      for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alia=
s) {
+      for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alia=
s) {
         unsigned AliasReg =3D *Alias;
         Classes[AliasReg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
-        KillIndices[AliasReg] =3D BB->size();
+        KillIndices[AliasReg] =3D BBSize;
         DefIndices[AliasReg] =3D ~0u;
       }
     }
@@ -102,18 +103,18 @@
   // callee-saved register that is not saved in the prolog.
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
   BitVector Pristine =3D MFI->getPristineRegs(BB);
-  for (const unsigned *I =3D TRI->getCalleeSavedRegs(); *I; ++I) {
+  for (const uint16_t *I =3D TRI->getCalleeSavedRegs(&MF); *I; ++I) {
     unsigned Reg =3D *I;
     if (!IsReturnBlock && !Pristine.test(Reg)) continue;
     Classes[Reg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
-    KillIndices[Reg] =3D BB->size();
+    KillIndices[Reg] =3D BBSize;
     DefIndices[Reg] =3D ~0u;
=20
     // Repeat, for all aliases.
-    for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
+    for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
       unsigned AliasReg =3D *Alias;
       Classes[AliasReg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
-      KillIndices[AliasReg] =3D BB->size();
+      KillIndices[AliasReg] =3D BBSize;
       DefIndices[AliasReg] =3D ~0u;
     }
   }
@@ -121,7 +122,7 @@
=20
 void CriticalAntiDepBreaker::FinishBlock() {
   RegRefs.clear();
-  KeepRegs.clear();
+  KeepRegs.reset();
 }
=20
 void CriticalAntiDepBreaker::Observe(MachineInstr *MI, unsigned Count,
@@ -193,8 +194,8 @@
   // instruction which may not be executed. The second R6 def may or may n=
ot
   // re-define R6 so it's not safe to change it since the last R6 use cann=
ot be
   // changed.
-  bool Special =3D MI->getDesc().isCall() ||
-    MI->getDesc().hasExtraSrcRegAllocReq() ||
+  bool Special =3D MI->isCall() ||
+    MI->hasExtraSrcRegAllocReq() ||
     TII->isPredicated(MI);
=20
   // Scan the register operands for this instruction and update
@@ -217,7 +218,7 @@
       Classes[Reg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
=20
     // Now check for aliases.
-    for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
+    for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
       // If an alias of the reg is used during the live range, give up.
       // Note that this allows us to skip checking if AntiDepReg
       // overlaps with any of the aliases, among other things.
@@ -233,10 +234,11 @@
       RegRefs.insert(std::make_pair(Reg, &MO));
=20
     if (MO.isUse() && Special) {
-      if (KeepRegs.insert(Reg)) {
-        for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+      if (!KeepRegs.test(Reg)) {
+        KeepRegs.set(Reg);
+        for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
              *Subreg; ++Subreg)
-          KeepRegs.insert(*Subreg);
+          KeepRegs.set(*Subreg);
       }
     }
   }
@@ -253,6 +255,17 @@
     // address updates.
     for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
       MachineOperand &MO =3D MI->getOperand(i);
+
+      if (MO.isRegMask())
+        for (unsigned i =3D 0, e =3D TRI->getNumRegs(); i !=3D e; ++i)
+          if (MO.clobbersPhysReg(i)) {
+            DefIndices[i] =3D Count;
+            KillIndices[i] =3D ~0u;
+            KeepRegs.reset(i);
+            Classes[i] =3D 0;
+            RegRefs.erase(i);
+          }
+
       if (!MO.isReg()) continue;
       unsigned Reg =3D MO.getReg();
       if (Reg =3D=3D 0) continue;
@@ -265,21 +278,21 @@
       assert(((KillIndices[Reg] =3D=3D ~0u) !=3D
               (DefIndices[Reg] =3D=3D ~0u)) &&
              "Kill and Def maps aren't consistent for Reg!");
-      KeepRegs.erase(Reg);
+      KeepRegs.reset(Reg);
       Classes[Reg] =3D 0;
       RegRefs.erase(Reg);
       // Repeat, for all subregs.
-      for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+      for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
            *Subreg; ++Subreg) {
         unsigned SubregReg =3D *Subreg;
         DefIndices[SubregReg] =3D Count;
         KillIndices[SubregReg] =3D ~0u;
-        KeepRegs.erase(SubregReg);
+        KeepRegs.reset(SubregReg);
         Classes[SubregReg] =3D 0;
         RegRefs.erase(SubregReg);
       }
       // Conservatively mark super-registers as unusable.
-      for (const unsigned *Super =3D TRI->getSuperRegisters(Reg);
+      for (const uint16_t *Super =3D TRI->getSuperRegisters(Reg);
            *Super; ++Super) {
         unsigned SuperReg =3D *Super;
         Classes[SuperReg] =3D reinterpret_cast<TargetRegisterClass *>(-1);
@@ -315,7 +328,7 @@
                "Kill and Def maps aren't consistent for Reg!");
     }
     // Repeat, for all aliases.
-    for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
+    for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)=
 {
       unsigned AliasReg =3D *Alias;
       if (KillIndices[AliasReg] =3D=3D ~0u) {
         KillIndices[AliasReg] =3D Count;
@@ -355,6 +368,9 @@
     for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
       const MachineOperand &CheckOper =3D MI->getOperand(i);
=20
+      if (CheckOper.isRegMask() && CheckOper.clobbersPhysReg(NewReg))
+        return true;
+
       if (!CheckOper.isReg() || !CheckOper.isDef() ||
           CheckOper.getReg() !=3D NewReg)
         continue;
@@ -427,6 +443,8 @@
=20
   // Keep a map of the MachineInstr*'s back to the SUnit representing them.
   // This is used for updating debug information.
+  //
+  // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUn=
itMap
   DenseMap<MachineInstr*,const SUnit*> MISUnitMap;
=20
   // Find the node at the bottom of the critical path.
@@ -535,7 +553,7 @@
           if (!RegClassInfo.isAllocatable(AntiDepReg))
             // Don't break anti-dependencies on non-allocatable registers.
             AntiDepReg =3D 0;
-          else if (KeepRegs.count(AntiDepReg))
+          else if (KeepRegs.test(AntiDepReg))
             // Don't break anti-dependencies if an use down below requires
             // this exact register.
             AntiDepReg =3D 0;
@@ -572,7 +590,7 @@
     // If MI's defs have a special allocation requirement, don't allow
     // any def registers to be changed. Also assume all registers
     // defined in a call must not be changed (ABI).
-    if (MI->getDesc().isCall() || MI->getDesc().hasExtraDefRegAllocReq() ||
+    if (MI->isCall() || MI->hasExtraDefRegAllocReq() ||
         TII->isPredicated(MI))
       // If this instruction's defs have special allocation requirement, d=
on't
       // break this anti-dependency.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Critical=
AntiDepBreaker.h
--- a/head/contrib/llvm/lib/CodeGen/CriticalAntiDepBreaker.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/CriticalAntiDepBreaker.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -24,7 +24,6 @@
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/ScheduleDAG.h"
 #include "llvm/ADT/BitVector.h"
-#include "llvm/ADT/SmallSet.h"
 #include <map>
=20
 namespace llvm {
@@ -66,7 +65,7 @@
=20
     /// KeepRegs - A set of registers which are live and cannot be changed=
 to
     /// break anti-dependencies.
-    SmallSet<unsigned, 4> KeepRegs;
+    BitVector KeepRegs;
=20
   public:
     CriticalAntiDepBreaker(MachineFunction& MFi, const RegisterClassInfo&);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/DeadMach=
ineInstructionElim.cpp
--- a/head/contrib/llvm/lib/CodeGen/DeadMachineInstructionElim.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/DeadMachineInstructionElim.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -28,11 +28,12 @@
 namespace {
   class DeadMachineInstructionElim : public MachineFunctionPass {
     virtual bool runOnMachineFunction(MachineFunction &MF);
-   =20
+
     const TargetRegisterInfo *TRI;
     const MachineRegisterInfo *MRI;
     const TargetInstrInfo *TII;
     BitVector LivePhysRegs;
+    BitVector ReservedRegs;
=20
   public:
     static char ID; // Pass identification, replacement for typeid
@@ -45,14 +46,11 @@
   };
 }
 char DeadMachineInstructionElim::ID =3D 0;
+char &llvm::DeadMachineInstructionElimID =3D DeadMachineInstructionElim::I=
D;
=20
 INITIALIZE_PASS(DeadMachineInstructionElim, "dead-mi-elimination",
                 "Remove dead machine instructions", false, false)
=20
-FunctionPass *llvm::createDeadMachineInstructionElimPass() {
-  return new DeadMachineInstructionElim();
-}
-
 bool DeadMachineInstructionElim::isDead(const MachineInstr *MI) const {
   // Technically speaking inline asm without side effects and no defs can =
still
   // be deleted. But there is so much bad inline asm code out there, we sh=
ould
@@ -70,10 +68,14 @@
     const MachineOperand &MO =3D MI->getOperand(i);
     if (MO.isReg() && MO.isDef()) {
       unsigned Reg =3D MO.getReg();
-      if (TargetRegisterInfo::isPhysicalRegister(Reg) ?
-          LivePhysRegs[Reg] : !MRI->use_nodbg_empty(Reg)) {
-        // This def has a non-debug use. Don't delete the instruction!
-        return false;
+      if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
+        // Don't delete live physreg defs, or any reserved register defs.
+        if (LivePhysRegs.test(Reg) || ReservedRegs.test(Reg))
+          return false;
+      } else {
+        if (!MRI->use_nodbg_empty(Reg))
+          // This def has a non-debug use. Don't delete the instruction!
+          return false;
       }
     }
   }
@@ -89,7 +91,7 @@
   TII =3D MF.getTarget().getInstrInfo();
=20
   // Treat reserved registers as always live.
-  BitVector ReservedRegs =3D TRI->getReservedRegs(MF);
+  ReservedRegs =3D TRI->getReservedRegs(MF);
=20
   // Loop over all instructions in all blocks, from bottom to top, so that=
 it's
   // more likely that chains of dependent but ultimately dead instructions=
 will
@@ -102,7 +104,7 @@
     LivePhysRegs =3D ReservedRegs;
=20
     // Also add any explicit live-out physregs for this block.
-    if (!MBB->empty() && MBB->back().getDesc().isReturn())
+    if (!MBB->empty() && MBB->back().isReturn())
       for (MachineRegisterInfo::liveout_iterator LOI =3D MRI->liveout_begi=
n(),
            LOE =3D MRI->liveout_end(); LOI !=3D LOE; ++LOI) {
         unsigned Reg =3D *LOI;
@@ -169,10 +171,13 @@
             // Check the subreg set, not the alias set, because a def
             // of a super-register may still be partially live after
             // this def.
-            for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+            for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
                  *SubRegs; ++SubRegs)
               LivePhysRegs.reset(*SubRegs);
           }
+        } else if (MO.isRegMask()) {
+          // Register mask of preserved registers. All clobbers are dead.
+          LivePhysRegs.clearBitsNotInMask(MO.getRegMask());
         }
       }
       // Record the physreg uses, after the defs, in case a physreg is
@@ -183,7 +188,7 @@
           unsigned Reg =3D MO.getReg();
           if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
             LivePhysRegs.set(Reg);
-            for (const unsigned *AliasSet =3D TRI->getAliasSet(Reg);
+            for (const uint16_t *AliasSet =3D TRI->getAliasSet(Reg);
                  *AliasSet; ++AliasSet)
               LivePhysRegs.set(*AliasSet);
           }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/DwarfEHP=
repare.cpp
--- a/head/contrib/llvm/lib/CodeGen/DwarfEHPrepare.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/DwarfEHPrepare.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -28,98 +28,34 @@
 #include "llvm/Transforms/Utils/SSAUpdater.h"
 using namespace llvm;
=20
-STATISTIC(NumLandingPadsSplit,     "Number of landing pads split");
-STATISTIC(NumUnwindsLowered,       "Number of unwind instructions lowered"=
);
-STATISTIC(NumResumesLowered,       "Number of eh.resume calls lowered");
-STATISTIC(NumExceptionValuesMoved, "Number of eh.exception calls moved");
+STATISTIC(NumResumesLowered, "Number of resume calls lowered");
=20
 namespace {
   class DwarfEHPrepare : public FunctionPass {
     const TargetMachine *TM;
     const TargetLowering *TLI;
=20
-    // The eh.exception intrinsic.
-    Function *ExceptionValueIntrinsic;
-
-    // The eh.selector intrinsic.
-    Function *SelectorIntrinsic;
-
-    // _Unwind_Resume_or_Rethrow or _Unwind_SjLj_Resume call.
-    Constant *URoR;
-
-    // The EH language-specific catch-all type.
-    GlobalVariable *EHCatchAllValue;
-
-    // _Unwind_Resume or the target equivalent.
+    // RewindFunction - _Unwind_Resume or the target equivalent.
     Constant *RewindFunction;
=20
-    // We both use and preserve dominator info.
-    DominatorTree *DT;
+    bool InsertUnwindResumeCalls(Function &Fn);
+    Instruction *GetExceptionObject(ResumeInst *RI);
=20
-    // The function we are running on.
-    Function *F;
-
-    // The landing pads for this function.
-    typedef SmallPtrSet<BasicBlock*, 8> BBSet;
-    BBSet LandingPads;
-
-    bool InsertUnwindResumeCalls();
-
-    bool NormalizeLandingPads();
-    bool LowerUnwindsAndResumes();
-    bool MoveExceptionValueCalls();
-
-    Instruction *CreateExceptionValueCall(BasicBlock *BB);
-
-    /// CleanupSelectors - Any remaining eh.selector intrinsic calls which=
 still
-    /// use the "llvm.eh.catch.all.value" call need to convert to using its
-    /// initializer instead.
-    bool CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels);
-
-    bool HasCatchAllInSelector(IntrinsicInst *);
-
-    /// FindAllCleanupSelectors - Find all eh.selector calls that are clea=
n-ups.
-    void FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
-                                 SmallPtrSet<IntrinsicInst*, 32> &CatchAll=
Sels);
-
-    /// FindAllURoRInvokes - Find all URoR invokes in the function.
-    void FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes);
-
-    /// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" =
or
-    /// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes ju=
mp to
-    /// a landing pad within the current function. This is a candidate to =
merge
-    /// the selector associated with the URoR invoke with the one from the
-    /// URoR's landing pad.
-    bool HandleURoRInvokes();
-
-    /// FindSelectorAndURoR - Find the eh.selector call and URoR call asso=
ciated
-    /// with the eh.exception call. This recursively looks past instructio=
ns
-    /// which don't change the EH pointer value, like casts or PHI nodes.
-    bool FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
-                             SmallPtrSet<IntrinsicInst*, 8> &SelCalls,
-                             SmallPtrSet<PHINode*, 32> &SeenPHIs);
-     =20
   public:
     static char ID; // Pass identification, replacement for typeid.
     DwarfEHPrepare(const TargetMachine *tm) :
       FunctionPass(ID), TM(tm), TLI(TM->getTargetLowering()),
-      ExceptionValueIntrinsic(0), SelectorIntrinsic(0),
-      URoR(0), EHCatchAllValue(0), RewindFunction(0) {
+      RewindFunction(0) {
         initializeDominatorTreePass(*PassRegistry::getPassRegistry());
       }
=20
     virtual bool runOnFunction(Function &Fn);
=20
-    // getAnalysisUsage - We need the dominator tree for handling URoR.
-    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
-      AU.addRequired<DominatorTree>();
-      AU.addPreserved<DominatorTree>();
-    }
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
=20
     const char *getPassName() const {
       return "Exception handling preparation";
     }
-
   };
 } // end anonymous namespace
=20
@@ -129,543 +65,52 @@
   return new DwarfEHPrepare(tm);
 }
=20
-/// HasCatchAllInSelector - Return true if the intrinsic instruction has a
-/// catch-all.
-bool DwarfEHPrepare::HasCatchAllInSelector(IntrinsicInst *II) {
-  if (!EHCatchAllValue) return false;
+/// GetExceptionObject - Return the exception object from the value passed=
 into
+/// the 'resume' instruction (typically an aggregate). Clean up any dead
+/// instructions, including the 'resume' instruction.
+Instruction *DwarfEHPrepare::GetExceptionObject(ResumeInst *RI) {
+  Value *V =3D RI->getOperand(0);
+  Instruction *ExnObj =3D 0;
+  InsertValueInst *SelIVI =3D dyn_cast<InsertValueInst>(V);
+  LoadInst *SelLoad =3D 0;
+  InsertValueInst *ExcIVI =3D 0;
+  bool EraseIVIs =3D false;
=20
-  unsigned ArgIdx =3D II->getNumArgOperands() - 1;
-  GlobalVariable *GV =3D dyn_cast<GlobalVariable>(II->getArgOperand(ArgIdx=
));
-  return GV =3D=3D EHCatchAllValue;
-}
-
-/// FindAllCleanupSelectors - Find all eh.selector calls that are clean-up=
s.
-void DwarfEHPrepare::
-FindAllCleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sels,
-                        SmallPtrSet<IntrinsicInst*, 32> &CatchAllSels) {
-  for (Value::use_iterator
-         I =3D SelectorIntrinsic->use_begin(),
-         E =3D SelectorIntrinsic->use_end(); I !=3D E; ++I) {
-    IntrinsicInst *II =3D cast<IntrinsicInst>(*I);
-
-    if (II->getParent()->getParent() !=3D F)
-      continue;
-
-    if (!HasCatchAllInSelector(II))
-      Sels.insert(II);
-    else
-      CatchAllSels.insert(II);
-  }
-}
-
-/// FindAllURoRInvokes - Find all URoR invokes in the function.
-void DwarfEHPrepare::
-FindAllURoRInvokes(SmallPtrSet<InvokeInst*, 32> &URoRInvokes) {
-  for (Value::use_iterator
-         I =3D URoR->use_begin(),
-         E =3D URoR->use_end(); I !=3D E; ++I) {
-    if (InvokeInst *II =3D dyn_cast<InvokeInst>(*I))
-      URoRInvokes.insert(II);
-  }
-}
-
-/// CleanupSelectors - Any remaining eh.selector intrinsic calls which sti=
ll use
-/// the "llvm.eh.catch.all.value" call need to convert to using its
-/// initializer instead.
-bool DwarfEHPrepare::CleanupSelectors(SmallPtrSet<IntrinsicInst*, 32> &Sel=
s) {
-  if (!EHCatchAllValue) return false;
-
-  if (!SelectorIntrinsic) {
-    SelectorIntrinsic =3D
-      Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
-    if (!SelectorIntrinsic) return false;
-  }
-
-  bool Changed =3D false;
-  for (SmallPtrSet<IntrinsicInst*, 32>::iterator
-         I =3D Sels.begin(), E =3D Sels.end(); I !=3D E; ++I) {
-    IntrinsicInst *Sel =3D *I;
-
-    // Index of the "llvm.eh.catch.all.value" variable.
-    unsigned OpIdx =3D Sel->getNumArgOperands() - 1;
-    GlobalVariable *GV =3D dyn_cast<GlobalVariable>(Sel->getArgOperand(OpI=
dx));
-    if (GV !=3D EHCatchAllValue) continue;
-    Sel->setArgOperand(OpIdx, EHCatchAllValue->getInitializer());
-    Changed =3D true;
-  }
-
-  return Changed;
-}
-
-/// FindSelectorAndURoR - Find the eh.selector call associated with the
-/// eh.exception call. And indicate if there is a URoR "invoke" associated=
 with
-/// the eh.exception call. This recursively looks past instructions which =
don't
-/// change the EH pointer value, like casts or PHI nodes.
-bool
-DwarfEHPrepare::FindSelectorAndURoR(Instruction *Inst, bool &URoRInvoke,
-                                    SmallPtrSet<IntrinsicInst*, 8> &SelCal=
ls,
-                                    SmallPtrSet<PHINode*, 32> &SeenPHIs) {
-  bool Changed =3D false;
-
-  for (Value::use_iterator
-         I =3D Inst->use_begin(), E =3D Inst->use_end(); I !=3D E; ++I) {
-    Instruction *II =3D dyn_cast<Instruction>(*I);
-    if (!II || II->getParent()->getParent() !=3D F) continue;
-   =20
-    if (IntrinsicInst *Sel =3D dyn_cast<IntrinsicInst>(II)) {
-      if (Sel->getIntrinsicID() =3D=3D Intrinsic::eh_selector)
-        SelCalls.insert(Sel);
-    } else if (InvokeInst *Invoke =3D dyn_cast<InvokeInst>(II)) {
-      if (Invoke->getCalledFunction() =3D=3D URoR)
-        URoRInvoke =3D true;
-    } else if (CastInst *CI =3D dyn_cast<CastInst>(II)) {
-      Changed |=3D FindSelectorAndURoR(CI, URoRInvoke, SelCalls, SeenPHIs);
-    } else if (PHINode *PN =3D dyn_cast<PHINode>(II)) {
-      if (SeenPHIs.insert(PN))
-        // Don't process a PHI node more than once.
-        Changed |=3D FindSelectorAndURoR(PN, URoRInvoke, SelCalls, SeenPHI=
s);
-    }
-  }
-
-  return Changed;
-}
-
-/// HandleURoRInvokes - Handle invokes of "_Unwind_Resume_or_Rethrow" or
-/// "_Unwind_SjLj_Resume" calls. The "unwind" part of these invokes jump t=
o a
-/// landing pad within the current function. This is a candidate to merge =
the
-/// selector associated with the URoR invoke with the one from the URoR's
-/// landing pad.
-bool DwarfEHPrepare::HandleURoRInvokes() {
-  if (!EHCatchAllValue) {
-    EHCatchAllValue =3D
-      F->getParent()->getNamedGlobal("llvm.eh.catch.all.value");
-    if (!EHCatchAllValue) return false;
-  }
-
-  if (!SelectorIntrinsic) {
-    SelectorIntrinsic =3D
-      Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_selector);
-    if (!SelectorIntrinsic) return false;
-  }
-
-  SmallPtrSet<IntrinsicInst*, 32> Sels;
-  SmallPtrSet<IntrinsicInst*, 32> CatchAllSels;
-  FindAllCleanupSelectors(Sels, CatchAllSels);
-
-  if (!URoR) {
-    URoR =3D F->getParent()->getFunction("_Unwind_Resume_or_Rethrow");
-    if (!URoR) return CleanupSelectors(CatchAllSels);
-  }
-
-  SmallPtrSet<InvokeInst*, 32> URoRInvokes;
-  FindAllURoRInvokes(URoRInvokes);
-
-  SmallPtrSet<IntrinsicInst*, 32> SelsToConvert;
-
-  for (SmallPtrSet<IntrinsicInst*, 32>::iterator
-         SI =3D Sels.begin(), SE =3D Sels.end(); SI !=3D SE; ++SI) {
-    const BasicBlock *SelBB =3D (*SI)->getParent();
-    for (SmallPtrSet<InvokeInst*, 32>::iterator
-           UI =3D URoRInvokes.begin(), UE =3D URoRInvokes.end(); UI !=3D U=
E; ++UI) {
-      const BasicBlock *URoRBB =3D (*UI)->getParent();
-      if (DT->dominates(SelBB, URoRBB)) {
-        SelsToConvert.insert(*SI);
-        break;
+  if (SelIVI) {
+    if (SelIVI->getNumIndices() =3D=3D 1 && *SelIVI->idx_begin() =3D=3D 1)=
 {
+      ExcIVI =3D dyn_cast<InsertValueInst>(SelIVI->getOperand(0));
+      if (ExcIVI && isa<UndefValue>(ExcIVI->getOperand(0)) &&
+          ExcIVI->getNumIndices() =3D=3D 1 && *ExcIVI->idx_begin() =3D=3D =
0) {
+        ExnObj =3D cast<Instruction>(ExcIVI->getOperand(1));
+        SelLoad =3D dyn_cast<LoadInst>(SelIVI->getOperand(1));
+        EraseIVIs =3D true;
       }
     }
   }
=20
-  bool Changed =3D false;
+  if (!ExnObj)
+    ExnObj =3D ExtractValueInst::Create(RI->getOperand(0), 0, "exn.obj", R=
I);
=20
-  if (Sels.size() !=3D SelsToConvert.size()) {
-    // If we haven't been able to convert all of the clean-up selectors, t=
hen
-    // loop through the slow way to see if they still need to be converted.
-    if (!ExceptionValueIntrinsic) {
-      ExceptionValueIntrinsic =3D
-        Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_exception);
-      if (!ExceptionValueIntrinsic)
-        return CleanupSelectors(CatchAllSels);
-    }
+  RI->eraseFromParent();
=20
-    for (Value::use_iterator
-           I =3D ExceptionValueIntrinsic->use_begin(),
-           E =3D ExceptionValueIntrinsic->use_end(); I !=3D E; ++I) {
-      IntrinsicInst *EHPtr =3D dyn_cast<IntrinsicInst>(*I);
-      if (!EHPtr || EHPtr->getParent()->getParent() !=3D F) continue;
-
-      bool URoRInvoke =3D false;
-      SmallPtrSet<IntrinsicInst*, 8> SelCalls;
-      SmallPtrSet<PHINode*, 32> SeenPHIs;
-      Changed |=3D FindSelectorAndURoR(EHPtr, URoRInvoke, SelCalls, SeenPH=
Is);
-
-      if (URoRInvoke) {
-        // This EH pointer is being used by an invoke of an URoR instructi=
on and
-        // an eh.selector intrinsic call. If the eh.selector is a 'clean-u=
p', we
-        // need to convert it to a 'catch-all'.
-        for (SmallPtrSet<IntrinsicInst*, 8>::iterator
-               SI =3D SelCalls.begin(), SE =3D SelCalls.end(); SI !=3D SE;=
 ++SI)
-          if (!HasCatchAllInSelector(*SI))
-              SelsToConvert.insert(*SI);
-      }
-    }
+  if (EraseIVIs) {
+    if (SelIVI->getNumUses() =3D=3D 0)
+      SelIVI->eraseFromParent();
+    if (ExcIVI->getNumUses() =3D=3D 0)
+      ExcIVI->eraseFromParent();
+    if (SelLoad && SelLoad->getNumUses() =3D=3D 0)
+      SelLoad->eraseFromParent();
   }
=20
-  if (!SelsToConvert.empty()) {
-    // Convert all clean-up eh.selectors, which are associated with "invok=
es" of
-    // URoR calls, into catch-all eh.selectors.
-    Changed =3D true;
-
-    for (SmallPtrSet<IntrinsicInst*, 8>::iterator
-           SI =3D SelsToConvert.begin(), SE =3D SelsToConvert.end();
-         SI !=3D SE; ++SI) {
-      IntrinsicInst *II =3D *SI;
-
-      // Use the exception object pointer and the personality function
-      // from the original selector.
-      CallSite CS(II);
-      IntrinsicInst::op_iterator I =3D CS.arg_begin();
-      IntrinsicInst::op_iterator E =3D CS.arg_end();
-      IntrinsicInst::op_iterator B =3D prior(E);
-
-      // Exclude last argument if it is an integer.
-      if (isa<ConstantInt>(B)) E =3D B;
-
-      // Add exception object pointer (front).
-      // Add personality function (next).
-      // Add in any filter IDs (rest).
-      SmallVector<Value*, 8> Args(I, E);
-
-      Args.push_back(EHCatchAllValue->getInitializer()); // Catch-all indi=
cator.
-
-      CallInst *NewSelector =3D
-        CallInst::Create(SelectorIntrinsic, Args, "eh.sel.catch.all", II);
-
-      NewSelector->setTailCall(II->isTailCall());
-      NewSelector->setAttributes(II->getAttributes());
-      NewSelector->setCallingConv(II->getCallingConv());
-
-      II->replaceAllUsesWith(NewSelector);
-      II->eraseFromParent();
-    }
-  }
-
-  Changed |=3D CleanupSelectors(CatchAllSels);
-  return Changed;
-}
-
-/// NormalizeLandingPads - Normalize and discover landing pads, noting them
-/// in the LandingPads set.  A landing pad is normal if the only CFG edges
-/// that end at it are unwind edges from invoke instructions. If we inlined
-/// through an invoke we could have a normal branch from the previous
-/// unwind block through to the landing pad for the original invoke.
-/// Abnormal landing pads are fixed up by redirecting all unwind edges to
-/// a new basic block which falls through to the original.
-bool DwarfEHPrepare::NormalizeLandingPads() {
-  bool Changed =3D false;
-
-  const MCAsmInfo *MAI =3D TM->getMCAsmInfo();
-  bool usingSjLjEH =3D MAI->getExceptionHandlingType() =3D=3D ExceptionHan=
dling::SjLj;
-
-  for (Function::iterator I =3D F->begin(), E =3D F->end(); I !=3D E; ++I)=
 {
-    TerminatorInst *TI =3D I->getTerminator();
-    if (!isa<InvokeInst>(TI))
-      continue;
-    BasicBlock *LPad =3D TI->getSuccessor(1);
-    // Skip landing pads that have already been normalized.
-    if (LandingPads.count(LPad))
-      continue;
-
-    // Check that only invoke unwind edges end at the landing pad.
-    bool OnlyUnwoundTo =3D true;
-    bool SwitchOK =3D usingSjLjEH;
-    for (pred_iterator PI =3D pred_begin(LPad), PE =3D pred_end(LPad);
-         PI !=3D PE; ++PI) {
-      TerminatorInst *PT =3D (*PI)->getTerminator();
-      // The SjLj dispatch block uses a switch instruction. This is effect=
ively
-      // an unwind edge, so we can disregard it here. There will only ever
-      // be one dispatch, however, so if there are multiple switches, one
-      // of them truly is a normal edge, not an unwind edge.
-      if (SwitchOK && isa<SwitchInst>(PT)) {
-        SwitchOK =3D false;
-        continue;
-      }
-      if (!isa<InvokeInst>(PT) || LPad =3D=3D PT->getSuccessor(0)) {
-        OnlyUnwoundTo =3D false;
-        break;
-      }
-    }
-
-    if (OnlyUnwoundTo) {
-      // Only unwind edges lead to the landing pad.  Remember the landing =
pad.
-      LandingPads.insert(LPad);
-      continue;
-    }
-
-    // At least one normal edge ends at the landing pad.  Redirect the unw=
ind
-    // edges to a new basic block which falls through into this one.
-
-    // Create the new basic block.
-    BasicBlock *NewBB =3D BasicBlock::Create(F->getContext(),
-                                           LPad->getName() + "_unwind_edge=
");
-
-    // Insert it into the function right before the original landing pad.
-    LPad->getParent()->getBasicBlockList().insert(LPad, NewBB);
-
-    // Redirect unwind edges from the original landing pad to NewBB.
-    for (pred_iterator PI =3D pred_begin(LPad), PE =3D pred_end(LPad); PI =
!=3D PE; ) {
-      TerminatorInst *PT =3D (*PI++)->getTerminator();
-      if (isa<InvokeInst>(PT) && PT->getSuccessor(1) =3D=3D LPad)
-        // Unwind to the new block.
-        PT->setSuccessor(1, NewBB);
-    }
-
-    // If there are any PHI nodes in LPad, we need to update them so that =
they
-    // merge incoming values from NewBB instead.
-    for (BasicBlock::iterator II =3D LPad->begin(); isa<PHINode>(II); ++II=
) {
-      PHINode *PN =3D cast<PHINode>(II);
-      pred_iterator PB =3D pred_begin(NewBB), PE =3D pred_end(NewBB);
-
-      // Check to see if all of the values coming in via unwind edges are =
the
-      // same.  If so, we don't need to create a new PHI node.
-      Value *InVal =3D PN->getIncomingValueForBlock(*PB);
-      for (pred_iterator PI =3D PB; PI !=3D PE; ++PI) {
-        if (PI !=3D PB && InVal !=3D PN->getIncomingValueForBlock(*PI)) {
-          InVal =3D 0;
-          break;
-        }
-      }
-
-      if (InVal =3D=3D 0) {
-        // Different unwind edges have different values.  Create a new PHI=
 node
-        // in NewBB.
-        PHINode *NewPN =3D PHINode::Create(PN->getType(),
-                                         PN->getNumIncomingValues(),
-                                         PN->getName()+".unwind", NewBB);
-        // Add an entry for each unwind edge, using the value from the old=
 PHI.
-        for (pred_iterator PI =3D PB; PI !=3D PE; ++PI)
-          NewPN->addIncoming(PN->getIncomingValueForBlock(*PI), *PI);
-
-        // Now use this new PHI as the common incoming value for NewBB in =
PN.
-        InVal =3D NewPN;
-      }
-
-      // Revector exactly one entry in the PHI node to come from NewBB
-      // and delete all other entries that come from unwind edges.  If
-      // there are both normal and unwind edges from the same predecessor,
-      // this leaves an entry for the normal edge.
-      for (pred_iterator PI =3D PB; PI !=3D PE; ++PI)
-        PN->removeIncomingValue(*PI);
-      PN->addIncoming(InVal, NewBB);
-    }
-
-    // Add a fallthrough from NewBB to the original landing pad.
-    BranchInst::Create(LPad, NewBB);
-
-    // Now update DominatorTree analysis information.
-    DT->splitBlock(NewBB);
-
-    // Remember the newly constructed landing pad.  The original landing p=
ad
-    // LPad is no longer a landing pad now that all unwind edges have been
-    // revectored to NewBB.
-    LandingPads.insert(NewBB);
-    ++NumLandingPadsSplit;
-    Changed =3D true;
-  }
-
-  return Changed;
-}
-
-/// LowerUnwinds - Turn unwind instructions into calls to _Unwind_Resume,
-/// rethrowing any previously caught exception.  This will crash horribly
-/// at runtime if there is no such exception: using unwind to throw a new
-/// exception is currently not supported.
-bool DwarfEHPrepare::LowerUnwindsAndResumes() {
-  SmallVector<Instruction*, 16> ResumeInsts;
-
-  for (Function::iterator fi =3D F->begin(), fe =3D F->end(); fi !=3D fe; =
++fi) {
-    for (BasicBlock::iterator bi =3D fi->begin(), be =3D fi->end(); bi !=
=3D be; ++bi){
-      if (isa<UnwindInst>(bi))
-        ResumeInsts.push_back(bi);
-      else if (CallInst *call =3D dyn_cast<CallInst>(bi))
-        if (Function *fn =3D dyn_cast<Function>(call->getCalledValue()))
-          if (fn->getName() =3D=3D "llvm.eh.resume")
-            ResumeInsts.push_back(bi);
-    }
-  }
-
-  if (ResumeInsts.empty()) return false;
-
-  // Find the rewind function if we didn't already.
-  if (!RewindFunction) {
-    LLVMContext &Ctx =3D ResumeInsts[0]->getContext();
-    FunctionType *FTy =3D FunctionType::get(Type::getVoidTy(Ctx),
-                                          Type::getInt8PtrTy(Ctx), false);
-    const char *RewindName =3D TLI->getLibcallName(RTLIB::UNWIND_RESUME);
-    RewindFunction =3D F->getParent()->getOrInsertFunction(RewindName, FTy=
);
-  }
-
-  bool Changed =3D false;
-
-  for (SmallVectorImpl<Instruction*>::iterator
-         I =3D ResumeInsts.begin(), E =3D ResumeInsts.end(); I !=3D E; ++I=
) {
-    Instruction *RI =3D *I;
-
-    // Replace the resuming instruction with a call to _Unwind_Resume (or =
the
-    // appropriate target equivalent).
-
-    llvm::Value *ExnValue;
-    if (isa<UnwindInst>(RI))
-      ExnValue =3D CreateExceptionValueCall(RI->getParent());
-    else
-      ExnValue =3D cast<CallInst>(RI)->getArgOperand(0);
-
-    // Create the call...
-    CallInst *CI =3D CallInst::Create(RewindFunction, ExnValue, "", RI);
-    CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
-
-    // ...followed by an UnreachableInst, if it was an unwind.
-    // Calls to llvm.eh.resume are typically already followed by this.
-    if (isa<UnwindInst>(RI))
-      new UnreachableInst(RI->getContext(), RI);
-
-    if (isa<UnwindInst>(RI))
-      ++NumUnwindsLowered;
-    else
-      ++NumResumesLowered;
-
-    // Nuke the resume instruction.
-    RI->eraseFromParent();
-
-    Changed =3D true;
-  }
-
-  return Changed;
-}
-
-/// MoveExceptionValueCalls - Ensure that eh.exception is only ever called=
 from
-/// landing pads by replacing calls outside of landing pads with direct us=
e of
-/// a register holding the appropriate value; this requires adding calls i=
nside
-/// all landing pads to initialize the register.  Also, move eh.exception =
calls
-/// inside landing pads to the start of the landing pad (optional, but may=
 make
-/// things simpler for later passes).
-bool DwarfEHPrepare::MoveExceptionValueCalls() {
-  // If the eh.exception intrinsic is not declared in the module then ther=
e is
-  // nothing to do.  Speed up compilation by checking for this common case.
-  if (!ExceptionValueIntrinsic &&
-      !F->getParent()->getFunction(Intrinsic::getName(Intrinsic::eh_except=
ion)))
-    return false;
-
-  bool Changed =3D false;
-
-  // Move calls to eh.exception that are inside a landing pad to the start=
 of
-  // the landing pad.
-  for (BBSet::const_iterator LI =3D LandingPads.begin(), LE =3D LandingPad=
s.end();
-       LI !=3D LE; ++LI) {
-    BasicBlock *LP =3D *LI;
-    for (BasicBlock::iterator II =3D LP->getFirstNonPHIOrDbg(), IE =3D LP-=
>end();
-         II !=3D IE;)
-      if (EHExceptionInst *EI =3D dyn_cast<EHExceptionInst>(II++)) {
-        // Found a call to eh.exception.
-        if (!EI->use_empty()) {
-          // If there is already a call to eh.exception at the start of the
-          // landing pad, then get hold of it; otherwise create such a cal=
l.
-          Value *CallAtStart =3D CreateExceptionValueCall(LP);
-
-          // If the call was at the start of a landing pad then leave it a=
lone.
-          if (EI =3D=3D CallAtStart)
-            continue;
-          EI->replaceAllUsesWith(CallAtStart);
-        }
-        EI->eraseFromParent();
-        ++NumExceptionValuesMoved;
-        Changed =3D true;
-      }
-  }
-
-  // Look for calls to eh.exception that are not in a landing pad.  If one=
 is
-  // found, then a register that holds the exception value will be created=
 in
-  // each landing pad, and the SSAUpdater will be used to compute the valu=
es
-  // returned by eh.exception calls outside of landing pads.
-  SSAUpdater SSA;
-
-  // Remember where we found the eh.exception call, to avoid rescanning ea=
rlier
-  // basic blocks which we already know contain no eh.exception calls.
-  bool FoundCallOutsideLandingPad =3D false;
-  Function::iterator BB =3D F->begin();
-  for (Function::iterator BE =3D F->end(); BB !=3D BE; ++BB) {
-    // Skip over landing pads.
-    if (LandingPads.count(BB))
-      continue;
-
-    for (BasicBlock::iterator II =3D BB->getFirstNonPHIOrDbg(), IE =3D BB-=
>end();
-         II !=3D IE; ++II)
-      if (isa<EHExceptionInst>(II)) {
-        SSA.Initialize(II->getType(), II->getName());
-        FoundCallOutsideLandingPad =3D true;
-        break;
-      }
-
-    if (FoundCallOutsideLandingPad)
-      break;
-  }
-
-  // If all calls to eh.exception are in landing pads then we are done.
-  if (!FoundCallOutsideLandingPad)
-    return Changed;
-
-  // Add a call to eh.exception at the start of each landing pad, and tell=
 the
-  // SSAUpdater that this is the value produced by the landing pad.
-  for (BBSet::iterator LI =3D LandingPads.begin(), LE =3D LandingPads.end(=
);
-       LI !=3D LE; ++LI)
-    SSA.AddAvailableValue(*LI, CreateExceptionValueCall(*LI));
-
-  // Now turn all calls to eh.exception that are not in a landing pad into=
 a use
-  // of the appropriate register.
-  for (Function::iterator BE =3D F->end(); BB !=3D BE; ++BB) {
-    // Skip over landing pads.
-    if (LandingPads.count(BB))
-      continue;
-
-    for (BasicBlock::iterator II =3D BB->getFirstNonPHIOrDbg(), IE =3D BB-=
>end();
-         II !=3D IE;)
-      if (EHExceptionInst *EI =3D dyn_cast<EHExceptionInst>(II++)) {
-        // Found a call to eh.exception, replace it with the value from any
-        // upstream landing pad(s).
-        EI->replaceAllUsesWith(SSA.GetValueAtEndOfBlock(BB));
-        EI->eraseFromParent();
-        ++NumExceptionValuesMoved;
-      }
-  }
-
-  return true;
-}
-
-/// CreateExceptionValueCall - Insert a call to the eh.exception intrinsic=
 at
-/// the start of the basic block (unless there already is one, in which ca=
se
-/// the existing call is returned).
-Instruction *DwarfEHPrepare::CreateExceptionValueCall(BasicBlock *BB) {
-  Instruction *Start =3D BB->getFirstNonPHIOrDbg();
-  // Is this a call to eh.exception?
-  if (IntrinsicInst *CI =3D dyn_cast<IntrinsicInst>(Start))
-    if (CI->getIntrinsicID() =3D=3D Intrinsic::eh_exception)
-      // Reuse the existing call.
-      return Start;
-
-  // Find the eh.exception intrinsic if we didn't already.
-  if (!ExceptionValueIntrinsic)
-    ExceptionValueIntrinsic =3D Intrinsic::getDeclaration(F->getParent(),
-                                                       Intrinsic::eh_excep=
tion);
-
-  // Create the call.
-  return CallInst::Create(ExceptionValueIntrinsic, "eh.value.call", Start);
+  return ExnObj;
 }
=20
 /// InsertUnwindResumeCalls - Convert the ResumeInsts that are still prese=
nt
 /// into calls to the appropriate _Unwind_Resume function.
-bool DwarfEHPrepare::InsertUnwindResumeCalls() {
+bool DwarfEHPrepare::InsertUnwindResumeCalls(Function &Fn) {
   bool UsesNewEH =3D false;
   SmallVector<ResumeInst*, 16> Resumes;
-  for (Function::iterator I =3D F->begin(), E =3D F->end(); I !=3D E; ++I)=
 {
+  for (Function::iterator I =3D Fn.begin(), E =3D Fn.end(); I !=3D E; ++I)=
 {
     TerminatorInst *TI =3D I->getTerminator();
     if (ResumeInst *RI =3D dyn_cast<ResumeInst>(TI))
       Resumes.push_back(RI);
@@ -682,27 +127,45 @@
     FunctionType *FTy =3D FunctionType::get(Type::getVoidTy(Ctx),
                                           Type::getInt8PtrTy(Ctx), false);
     const char *RewindName =3D TLI->getLibcallName(RTLIB::UNWIND_RESUME);
-    RewindFunction =3D F->getParent()->getOrInsertFunction(RewindName, FTy=
);
+    RewindFunction =3D Fn.getParent()->getOrInsertFunction(RewindName, FTy=
);
   }
=20
   // Create the basic block where the _Unwind_Resume call will live.
-  LLVMContext &Ctx =3D F->getContext();
-  BasicBlock *UnwindBB =3D BasicBlock::Create(Ctx, "unwind_resume", F);
-  PHINode *PN =3D PHINode::Create(Type::getInt8PtrTy(Ctx), Resumes.size(),
+  LLVMContext &Ctx =3D Fn.getContext();
+  unsigned ResumesSize =3D Resumes.size();
+
+  if (ResumesSize =3D=3D 1) {
+    // Instead of creating a new BB and PHI node, just append the call to
+    // _Unwind_Resume to the end of the single resume block.
+    ResumeInst *RI =3D Resumes.front();
+    BasicBlock *UnwindBB =3D RI->getParent();
+    Instruction *ExnObj =3D GetExceptionObject(RI);
+
+    // Call the _Unwind_Resume function.
+    CallInst *CI =3D CallInst::Create(RewindFunction, ExnObj, "", UnwindBB=
);
+    CI->setCallingConv(TLI->getLibcallCallingConv(RTLIB::UNWIND_RESUME));
+
+    // We never expect _Unwind_Resume to return.
+    new UnreachableInst(Ctx, UnwindBB);
+    return true;
+  }
+
+  BasicBlock *UnwindBB =3D BasicBlock::Create(Ctx, "unwind_resume", &Fn);
+  PHINode *PN =3D PHINode::Create(Type::getInt8PtrTy(Ctx), ResumesSize,
                                 "exn.obj", UnwindBB);
=20
   // Extract the exception object from the ResumeInst and add it to the PH=
I node
   // that feeds the _Unwind_Resume call.
-  BasicBlock *UnwindBBDom =3D Resumes[0]->getParent();
   for (SmallVectorImpl<ResumeInst*>::iterator
          I =3D Resumes.begin(), E =3D Resumes.end(); I !=3D E; ++I) {
     ResumeInst *RI =3D *I;
-    BranchInst::Create(UnwindBB, RI->getParent());
-    ExtractValueInst *ExnObj =3D ExtractValueInst::Create(RI->getOperand(0=
),
-                                                        0, "exn.obj", RI);
-    PN->addIncoming(ExnObj, RI->getParent());
-    UnwindBBDom =3D DT->findNearestCommonDominator(RI->getParent(), Unwind=
BBDom);
-    RI->eraseFromParent();
+    BasicBlock *Parent =3D RI->getParent();
+    BranchInst::Create(UnwindBB, Parent);
+
+    Instruction *ExnObj =3D GetExceptionObject(RI);
+    PN->addIncoming(ExnObj, Parent);
+
+    ++NumResumesLowered;
   }
=20
   // Call the function.
@@ -711,40 +174,10 @@
=20
   // We never expect _Unwind_Resume to return.
   new UnreachableInst(Ctx, UnwindBB);
-
-  // Now update DominatorTree analysis information.
-  DT->addNewBlock(UnwindBB, UnwindBBDom);
   return true;
 }
=20
 bool DwarfEHPrepare::runOnFunction(Function &Fn) {
-  bool Changed =3D false;
-
-  // Initialize internal state.
-  DT =3D &getAnalysis<DominatorTree>(); // FIXME: We won't need this with =
the new EH.
-  F =3D &Fn;
-
-  if (InsertUnwindResumeCalls()) {
-    // FIXME: The reset of this function can go once the new EH is done.
-    LandingPads.clear();
-    return true;
-  }
-
-  // Ensure that only unwind edges end at landing pads (a landing pad is a
-  // basic block where an invoke unwind edge ends).
-  Changed |=3D NormalizeLandingPads();
-
-  // Turn unwind instructions and eh.resume calls into libcalls.
-  Changed |=3D LowerUnwindsAndResumes();
-
-  // TODO: Move eh.selector calls to landing pads and combine them.
-
-  // Move eh.exception calls to landing pads.
-  Changed |=3D MoveExceptionValueCalls();
-
-  Changed |=3D HandleURoRInvokes();
-
-  LandingPads.clear();
-
+  bool Changed =3D InsertUnwindResumeCalls(Fn);
   return Changed;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/EdgeBund=
les.cpp
--- a/head/contrib/llvm/lib/CodeGen/EdgeBundles.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/CodeGen/EdgeBundles.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -77,7 +77,7 @@
 /// Specialize WriteGraph, the standard implementation won't work.
 raw_ostream &llvm::WriteGraph(raw_ostream &O, const EdgeBundles &G,
                               bool ShortNames,
-                              const std::string &Title) {
+                              const Twine &Title) {
   const MachineFunction *MF =3D G.getMachineFunction();
=20
   O << "digraph {\n";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Executio=
nDepsFix.cpp
--- a/head/contrib/llvm/lib/CodeGen/ExecutionDepsFix.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ExecutionDepsFix.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -26,7 +26,7 @@
 #include "llvm/CodeGen/Passes.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetMachine.h"
-#include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -45,7 +45,7 @@
 /// DomainValue for each register, but it may contain multiple execution
 /// domains. A register value is initially created in a single execution
 /// domain, but if we were forced to pay the penalty of a domain crossing,=
 we
-/// keep track of the fact the the register is now available in multiple
+/// keep track of the fact that the register is now available in multiple
 /// domains.
 namespace {
 struct DomainValue {
@@ -57,8 +57,10 @@
   // domains where the register is available for free.
   unsigned AvailableDomains;
=20
-  // Position of the last defining instruction.
-  unsigned Dist;
+  // Pointer to the next DomainValue in a chain.  When two DomainValues are
+  // merged, Victim.Next is set to point to Victor, so old DomainValue
+  // references can be updated by folowing the chain.
+  DomainValue *Next;
=20
   // Twiddleable instructions using or defining these registers.
   SmallVector<MachineInstr*, 8> Instrs;
@@ -92,16 +94,33 @@
     return CountTrailingZeros_32(AvailableDomains);
   }
=20
-  DomainValue() { clear(); }
+  DomainValue() : Refs(0) { clear(); }
=20
+  // Clear this DomainValue and point to next which has all its data.
   void clear() {
-    Refs =3D AvailableDomains =3D Dist =3D 0;
+    AvailableDomains =3D 0;
+    Next =3D 0;
     Instrs.clear();
   }
 };
 }
=20
 namespace {
+/// LiveReg - Information about a live register.
+struct LiveReg {
+  /// Value currently in this register, or NULL when no value is being tra=
cked.
+  /// This counts as a DomainValue reference.
+  DomainValue *Value;
+
+  /// Instruction that defined this register, relative to the beginning of=
 the
+  /// current basic block.  When a LiveReg is used to represent a live-out
+  /// register, this value is relative to the end of the basic block, so it
+  /// will be a negative number.
+  int Def;
+};
+} // anonynous namespace
+
+namespace {
 class ExeDepsFix : public MachineFunctionPass {
   static char ID;
   SpecificBumpPtrAllocator<DomainValue> Allocator;
@@ -111,13 +130,19 @@
   MachineFunction *MF;
   const TargetInstrInfo *TII;
   const TargetRegisterInfo *TRI;
-  MachineBasicBlock *MBB;
   std::vector<int> AliasMap;
   const unsigned NumRegs;
-  DomainValue **LiveRegs;
-  typedef DenseMap<MachineBasicBlock*,DomainValue**> LiveOutMap;
+  LiveReg *LiveRegs;
+  typedef DenseMap<MachineBasicBlock*, LiveReg*> LiveOutMap;
   LiveOutMap LiveOuts;
-  unsigned Distance;
+
+  /// Current instruction number.
+  /// The first instruction in each basic block is 0.
+  int CurInstr;
+
+  /// True when the current block has a predecessor that hasn't been visit=
ed
+  /// yet.
+  bool SeenUnknownBackEdge;
=20
 public:
   ExeDepsFix(const TargetRegisterClass *rc)
@@ -131,26 +156,33 @@
   virtual bool runOnMachineFunction(MachineFunction &MF);
=20
   virtual const char *getPassName() const {
-    return "SSE execution domain fixup";
+    return "Execution dependency fix";
   }
=20
 private:
   // Register mapping.
-  int RegIndex(unsigned Reg);
+  int regIndex(unsigned Reg);
=20
   // DomainValue allocation.
-  DomainValue *Alloc(int domain =3D -1);
-  void Recycle(DomainValue*);
+  DomainValue *alloc(int domain =3D -1);
+  DomainValue *retain(DomainValue *DV) {
+    if (DV) ++DV->Refs;
+    return DV;
+  }
+  void release(DomainValue*);
+  DomainValue *resolve(DomainValue*&);
=20
   // LiveRegs manipulations.
-  void SetLiveReg(int rx, DomainValue *DV);
-  void Kill(int rx);
-  void Force(int rx, unsigned domain);
-  void Collapse(DomainValue *dv, unsigned domain);
-  bool Merge(DomainValue *A, DomainValue *B);
+  void setLiveReg(int rx, DomainValue *DV);
+  void kill(int rx);
+  void force(int rx, unsigned domain);
+  void collapse(DomainValue *dv, unsigned domain);
+  bool merge(DomainValue *A, DomainValue *B);
=20
-  void enterBasicBlock();
-  void visitGenericInstr(MachineInstr*);
+  void enterBasicBlock(MachineBasicBlock*);
+  void leaveBasicBlock(MachineBasicBlock*);
+  void visitInstr(MachineInstr*);
+  void processDefs(MachineInstr*, bool Kill);
   void visitSoftInstr(MachineInstr*, unsigned mask);
   void visitHardInstr(MachineInstr*, unsigned domain);
 };
@@ -160,83 +192,108 @@
=20
 /// Translate TRI register number to an index into our smaller tables of
 /// interesting registers. Return -1 for boring registers.
-int ExeDepsFix::RegIndex(unsigned Reg) {
+int ExeDepsFix::regIndex(unsigned Reg) {
   assert(Reg < AliasMap.size() && "Invalid register");
   return AliasMap[Reg];
 }
=20
-DomainValue *ExeDepsFix::Alloc(int domain) {
+DomainValue *ExeDepsFix::alloc(int domain) {
   DomainValue *dv =3D Avail.empty() ?
                       new(Allocator.Allocate()) DomainValue :
                       Avail.pop_back_val();
-  dv->Dist =3D Distance;
   if (domain >=3D 0)
     dv->addDomain(domain);
+  assert(dv->Refs =3D=3D 0 && "Reference count wasn't cleared");
+  assert(!dv->Next && "Chained DomainValue shouldn't have been recycled");
   return dv;
 }
=20
-void ExeDepsFix::Recycle(DomainValue *dv) {
-  assert(dv && "Cannot recycle NULL");
-  dv->clear();
-  Avail.push_back(dv);
+/// release - Release a reference to DV.  When the last reference is relea=
sed,
+/// collapse if needed.
+void ExeDepsFix::release(DomainValue *DV) {
+  while (DV) {
+    assert(DV->Refs && "Bad DomainValue");
+    if (--DV->Refs)
+      return;
+
+    // There are no more DV references. Collapse any contained instruction=
s.
+    if (DV->AvailableDomains && !DV->isCollapsed())
+      collapse(DV, DV->getFirstDomain());
+
+    DomainValue *Next =3D DV->Next;
+    DV->clear();
+    Avail.push_back(DV);
+    // Also release the next DomainValue in the chain.
+    DV =3D Next;
+  }
+}
+
+/// resolve - Follow the chain of dead DomainValues until a live DomainVal=
ue is
+/// reached.  Update the referenced pointer when necessary.
+DomainValue *ExeDepsFix::resolve(DomainValue *&DVRef) {
+  DomainValue *DV =3D DVRef;
+  if (!DV || !DV->Next)
+    return DV;
+
+  // DV has a chain. Find the end.
+  do DV =3D DV->Next;
+  while (DV->Next);
+
+  // Update DVRef to point to DV.
+  retain(DV);
+  release(DVRef);
+  DVRef =3D DV;
+  return DV;
 }
=20
 /// Set LiveRegs[rx] =3D dv, updating reference counts.
-void ExeDepsFix::SetLiveReg(int rx, DomainValue *dv) {
+void ExeDepsFix::setLiveReg(int rx, DomainValue *dv) {
   assert(unsigned(rx) < NumRegs && "Invalid index");
-  if (!LiveRegs) {
-    LiveRegs =3D new DomainValue*[NumRegs];
-    std::fill(LiveRegs, LiveRegs+NumRegs, (DomainValue*)0);
-  }
+  assert(LiveRegs && "Must enter basic block first.");
=20
-  if (LiveRegs[rx] =3D=3D dv)
+  if (LiveRegs[rx].Value =3D=3D dv)
     return;
-  if (LiveRegs[rx]) {
-    assert(LiveRegs[rx]->Refs && "Bad refcount");
-    if (--LiveRegs[rx]->Refs =3D=3D 0) Recycle(LiveRegs[rx]);
-  }
-  LiveRegs[rx] =3D dv;
-  if (dv) ++dv->Refs;
+  if (LiveRegs[rx].Value)
+    release(LiveRegs[rx].Value);
+  LiveRegs[rx].Value =3D retain(dv);
 }
=20
 // Kill register rx, recycle or collapse any DomainValue.
-void ExeDepsFix::Kill(int rx) {
+void ExeDepsFix::kill(int rx) {
   assert(unsigned(rx) < NumRegs && "Invalid index");
-  if (!LiveRegs || !LiveRegs[rx]) return;
+  assert(LiveRegs && "Must enter basic block first.");
+  if (!LiveRegs[rx].Value)
+    return;
=20
-  // Before killing the last reference to an open DomainValue, collapse it=
 to
-  // the first available domain.
-  if (LiveRegs[rx]->Refs =3D=3D 1 && !LiveRegs[rx]->isCollapsed())
-    Collapse(LiveRegs[rx], LiveRegs[rx]->getFirstDomain());
-  else
-    SetLiveReg(rx, 0);
+  release(LiveRegs[rx].Value);
+  LiveRegs[rx].Value =3D 0;
 }
=20
 /// Force register rx into domain.
-void ExeDepsFix::Force(int rx, unsigned domain) {
+void ExeDepsFix::force(int rx, unsigned domain) {
   assert(unsigned(rx) < NumRegs && "Invalid index");
-  DomainValue *dv;
-  if (LiveRegs && (dv =3D LiveRegs[rx])) {
+  assert(LiveRegs && "Must enter basic block first.");
+  if (DomainValue *dv =3D LiveRegs[rx].Value) {
     if (dv->isCollapsed())
       dv->addDomain(domain);
     else if (dv->hasDomain(domain))
-      Collapse(dv, domain);
+      collapse(dv, domain);
     else {
       // This is an incompatible open DomainValue. Collapse it to whatever=
 and
       // force the new value into domain. This costs a domain crossing.
-      Collapse(dv, dv->getFirstDomain());
-      assert(LiveRegs[rx] && "Not live after collapse?");
-      LiveRegs[rx]->addDomain(domain);
+      collapse(dv, dv->getFirstDomain());
+      assert(LiveRegs[rx].Value && "Not live after collapse?");
+      LiveRegs[rx].Value->addDomain(domain);
     }
   } else {
     // Set up basic collapsed DomainValue.
-    SetLiveReg(rx, Alloc(domain));
+    setLiveReg(rx, alloc(domain));
   }
 }
=20
 /// Collapse open DomainValue into given domain. If there are multiple
 /// registers using dv, they each get a unique collapsed DomainValue.
-void ExeDepsFix::Collapse(DomainValue *dv, unsigned domain) {
+void ExeDepsFix::collapse(DomainValue *dv, unsigned domain) {
   assert(dv->hasDomain(domain) && "Cannot collapse");
=20
   // Collapse all the instructions.
@@ -247,13 +304,13 @@
   // If there are multiple users, give them new, unique DomainValues.
   if (LiveRegs && dv->Refs > 1)
     for (unsigned rx =3D 0; rx !=3D NumRegs; ++rx)
-      if (LiveRegs[rx] =3D=3D dv)
-        SetLiveReg(rx, Alloc(domain));
+      if (LiveRegs[rx].Value =3D=3D dv)
+        setLiveReg(rx, alloc(domain));
 }
=20
 /// Merge - All instructions and registers in B are moved to A, and B is
 /// released.
-bool ExeDepsFix::Merge(DomainValue *A, DomainValue *B) {
+bool ExeDepsFix::merge(DomainValue *A, DomainValue *B) {
   assert(!A->isCollapsed() && "Cannot merge into collapsed");
   assert(!B->isCollapsed() && "Cannot merge from collapsed");
   if (A =3D=3D B)
@@ -263,47 +320,188 @@
   if (!common)
     return false;
   A->AvailableDomains =3D common;
-  A->Dist =3D std::max(A->Dist, B->Dist);
   A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
+
+  // Clear the old DomainValue so we won't try to swizzle instructions twi=
ce.
+  B->clear();
+  // All uses of B are referred to A.
+  B->Next =3D retain(A);
+
   for (unsigned rx =3D 0; rx !=3D NumRegs; ++rx)
-    if (LiveRegs[rx] =3D=3D B)
-      SetLiveReg(rx, A);
+    if (LiveRegs[rx].Value =3D=3D B)
+      setLiveReg(rx, A);
   return true;
 }
=20
-void ExeDepsFix::enterBasicBlock() {
+// enterBasicBlock - Set up LiveRegs by merging predecessor live-out value=
s.
+void ExeDepsFix::enterBasicBlock(MachineBasicBlock *MBB) {
+  // Detect back-edges from predecessors we haven't processed yet.
+  SeenUnknownBackEdge =3D false;
+
+  // Reset instruction counter in each basic block.
+  CurInstr =3D 0;
+
+  // Set up LiveRegs to represent registers entering MBB.
+  if (!LiveRegs)
+    LiveRegs =3D new LiveReg[NumRegs];
+
+  // Default values are 'nothing happened a long time ago'.
+  for (unsigned rx =3D 0; rx !=3D NumRegs; ++rx) {
+    LiveRegs[rx].Value =3D 0;
+    LiveRegs[rx].Def =3D -(1 << 20);
+  }
+
+  // This is the entry block.
+  if (MBB->pred_empty()) {
+    for (MachineBasicBlock::livein_iterator i =3D MBB->livein_begin(),
+         e =3D MBB->livein_end(); i !=3D e; ++i) {
+      int rx =3D regIndex(*i);
+      if (rx < 0)
+        continue;
+      // Treat function live-ins as if they were defined just before the f=
irst
+      // instruction.  Usually, function arguments are set up immediately
+      // before the call.
+      LiveRegs[rx].Def =3D -1;
+    }
+    DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": entry\n");
+    return;
+  }
+
   // Try to coalesce live-out registers from predecessors.
-  for (MachineBasicBlock::livein_iterator i =3D MBB->livein_begin(),
-         e =3D MBB->livein_end(); i !=3D e; ++i) {
-    int rx =3D RegIndex(*i);
-    if (rx < 0) continue;
-    for (MachineBasicBlock::const_pred_iterator pi =3D MBB->pred_begin(),
-           pe =3D MBB->pred_end(); pi !=3D pe; ++pi) {
-      LiveOutMap::const_iterator fi =3D LiveOuts.find(*pi);
-      if (fi =3D=3D LiveOuts.end()) continue;
-      DomainValue *pdv =3D fi->second[rx];
-      if (!pdv) continue;
-      if (!LiveRegs || !LiveRegs[rx]) {
-        SetLiveReg(rx, pdv);
+  for (MachineBasicBlock::const_pred_iterator pi =3D MBB->pred_begin(),
+       pe =3D MBB->pred_end(); pi !=3D pe; ++pi) {
+    LiveOutMap::const_iterator fi =3D LiveOuts.find(*pi);
+    if (fi =3D=3D LiveOuts.end()) {
+      SeenUnknownBackEdge =3D true;
+      continue;
+    }
+    assert(fi->second && "Can't have NULL entries");
+
+    for (unsigned rx =3D 0; rx !=3D NumRegs; ++rx) {
+      // Use the most recent predecessor def for each register.
+      LiveRegs[rx].Def =3D std::max(LiveRegs[rx].Def, fi->second[rx].Def);
+
+      DomainValue *pdv =3D resolve(fi->second[rx].Value);
+      if (!pdv)
+        continue;
+      if (!LiveRegs[rx].Value) {
+        setLiveReg(rx, pdv);
         continue;
       }
=20
       // We have a live DomainValue from more than one predecessor.
-      if (LiveRegs[rx]->isCollapsed()) {
+      if (LiveRegs[rx].Value->isCollapsed()) {
         // We are already collapsed, but predecessor is not. Force him.
-        unsigned domain =3D LiveRegs[rx]->getFirstDomain();
-        if (!pdv->isCollapsed() && pdv->hasDomain(domain))
-          Collapse(pdv, domain);
+        unsigned Domain =3D LiveRegs[rx].Value->getFirstDomain();
+        if (!pdv->isCollapsed() && pdv->hasDomain(Domain))
+          collapse(pdv, Domain);
         continue;
       }
=20
       // Currently open, merge in predecessor.
       if (!pdv->isCollapsed())
-        Merge(LiveRegs[rx], pdv);
+        merge(LiveRegs[rx].Value, pdv);
       else
-        Force(rx, pdv->getFirstDomain());
+        force(rx, pdv->getFirstDomain());
     }
   }
+  DEBUG(dbgs() << "BB#" << MBB->getNumber()
+        << (SeenUnknownBackEdge ? ": incomplete\n" : ": all preds known\n"=
));
+}
+
+void ExeDepsFix::leaveBasicBlock(MachineBasicBlock *MBB) {
+  assert(LiveRegs && "Must enter basic block first.");
+  // Save live registers at end of MBB - used by enterBasicBlock().
+  // Also use LiveOuts as a visited set to detect back-edges.
+  bool First =3D LiveOuts.insert(std::make_pair(MBB, LiveRegs)).second;
+
+  if (First) {
+    // LiveRegs was inserted in LiveOuts.  Adjust all defs to be relative =
to
+    // the end of this block instead of the beginning.
+    for (unsigned i =3D 0, e =3D NumRegs; i !=3D e; ++i)
+      LiveRegs[i].Def -=3D CurInstr;
+  } else {
+    // Insertion failed, this must be the second pass.
+    // Release all the DomainValues instead of keeping them.
+    for (unsigned i =3D 0, e =3D NumRegs; i !=3D e; ++i)
+      release(LiveRegs[i].Value);
+    delete[] LiveRegs;
+  }
+  LiveRegs =3D 0;
+}
+
+void ExeDepsFix::visitInstr(MachineInstr *MI) {
+  if (MI->isDebugValue())
+    return;
+
+  // Update instructions with explicit execution domains.
+  std::pair<uint16_t, uint16_t> DomP =3D TII->getExecutionDomain(MI);
+  if (DomP.first) {
+    if (DomP.second)
+      visitSoftInstr(MI, DomP.second);
+    else
+      visitHardInstr(MI, DomP.first);
+  }
+
+  // Process defs to track register ages, and kill values clobbered by gen=
eric
+  // instructions.
+  processDefs(MI, !DomP.first);
+}
+
+// Update def-ages for registers defined by MI.
+// If Kill is set, also kill off DomainValues clobbered by the defs.
+void ExeDepsFix::processDefs(MachineInstr *MI, bool Kill) {
+  assert(!MI->isDebugValue() && "Won't process debug values");
+  const MCInstrDesc &MCID =3D MI->getDesc();
+  for (unsigned i =3D 0,
+         e =3D MI->isVariadic() ? MI->getNumOperands() : MCID.getNumDefs();
+         i !=3D e; ++i) {
+    MachineOperand &MO =3D MI->getOperand(i);
+    if (!MO.isReg())
+      continue;
+    if (MO.isImplicit())
+      break;
+    if (MO.isUse())
+      continue;
+    int rx =3D regIndex(MO.getReg());
+    if (rx < 0)
+      continue;
+
+    // This instruction explicitly defines rx.
+    DEBUG(dbgs() << TRI->getName(RC->getRegister(rx)) << ":\t" << CurInstr
+                 << '\t' << *MI);
+
+    // How many instructions since rx was last written?
+    unsigned Clearance =3D CurInstr - LiveRegs[rx].Def;
+    LiveRegs[rx].Def =3D CurInstr;
+
+    // Kill off domains redefined by generic instructions.
+    if (Kill)
+      kill(rx);
+
+    // Verify clearance before partial register updates.
+    unsigned Pref =3D TII->getPartialRegUpdateClearance(MI, i, TRI);
+    if (!Pref)
+      continue;
+    DEBUG(dbgs() << "Clearance: " << Clearance << ", want " << Pref);
+    if (Pref > Clearance) {
+      DEBUG(dbgs() << ": Break dependency.\n");
+      TII->breakPartialRegDependency(MI, i, TRI);
+      continue;
+    }
+
+    // The current clearance seems OK, but we may be ignoring a def from a
+    // back-edge.
+    if (!SeenUnknownBackEdge || Pref <=3D unsigned(CurInstr)) {
+      DEBUG(dbgs() << ": OK.\n");
+      continue;
+    }
+
+    // A def from an unprocessed back-edge may make us break this dependen=
cy.
+    DEBUG(dbgs() << ": Wait for back-edge to resolve.\n");
+  }
+
+  ++CurInstr;
 }
=20
 // A hard instruction only works in one domain. All input registers will be
@@ -314,19 +512,19 @@
                 e =3D mi->getDesc().getNumOperands(); i !=3D e; ++i) {
     MachineOperand &mo =3D mi->getOperand(i);
     if (!mo.isReg()) continue;
-    int rx =3D RegIndex(mo.getReg());
+    int rx =3D regIndex(mo.getReg());
     if (rx < 0) continue;
-    Force(rx, domain);
+    force(rx, domain);
   }
=20
   // Kill all defs and force them.
   for (unsigned i =3D 0, e =3D mi->getDesc().getNumDefs(); i !=3D e; ++i) {
     MachineOperand &mo =3D mi->getOperand(i);
     if (!mo.isReg()) continue;
-    int rx =3D RegIndex(mo.getReg());
+    int rx =3D regIndex(mo.getReg());
     if (rx < 0) continue;
-    Kill(rx);
-    Force(rx, domain);
+    kill(rx);
+    force(rx, domain);
   }
 }
=20
@@ -343,9 +541,9 @@
                   e =3D mi->getDesc().getNumOperands(); i !=3D e; ++i) {
       MachineOperand &mo =3D mi->getOperand(i);
       if (!mo.isReg()) continue;
-      int rx =3D RegIndex(mo.getReg());
+      int rx =3D regIndex(mo.getReg());
       if (rx < 0) continue;
-      if (DomainValue *dv =3D LiveRegs[rx]) {
+      if (DomainValue *dv =3D LiveRegs[rx].Value) {
         // Bitmask of domains that dv and available have in common.
         unsigned common =3D dv->getCommonDomains(available);
         // Is it possible to use this collapsed register for free?
@@ -360,7 +558,7 @@
         else
           // Open DomainValue is not compatible with instruction. It is us=
eless
           // now.
-          Kill(rx);
+          kill(rx);
       }
     }
=20
@@ -374,94 +572,89 @@
=20
   // Kill off any remaining uses that don't match available, and build a l=
ist of
   // incoming DomainValues that we want to merge.
-  SmallVector<DomainValue*,4> doms;
+  SmallVector<LiveReg, 4> Regs;
   for (SmallVector<int, 4>::iterator i=3Dused.begin(), e=3Dused.end(); i!=
=3De; ++i) {
     int rx =3D *i;
-    DomainValue *dv =3D LiveRegs[rx];
+    const LiveReg &LR =3D LiveRegs[rx];
     // This useless DomainValue could have been missed above.
-    if (!dv->getCommonDomains(available)) {
-      Kill(*i);
+    if (!LR.Value->getCommonDomains(available)) {
+      kill(rx);
       continue;
     }
-    // sorted, uniqued insert.
-    bool inserted =3D false;
-    for (SmallVector<DomainValue*,4>::iterator i =3D doms.begin(), e =3D d=
oms.end();
-           i !=3D e && !inserted; ++i) {
-      if (dv =3D=3D *i)
-        inserted =3D true;
-      else if (dv->Dist < (*i)->Dist) {
-        inserted =3D true;
-        doms.insert(i, dv);
+    // Sorted insertion.
+    bool Inserted =3D false;
+    for (SmallVector<LiveReg, 4>::iterator i =3D Regs.begin(), e =3D Regs.=
end();
+           i !=3D e && !Inserted; ++i) {
+      if (LR.Def < i->Def) {
+        Inserted =3D true;
+        Regs.insert(i, LR);
       }
     }
-    if (!inserted)
-      doms.push_back(dv);
+    if (!Inserted)
+      Regs.push_back(LR);
   }
=20
   // doms are now sorted in order of appearance. Try to merge them all, gi=
ving
   // priority to the latest ones.
   DomainValue *dv =3D 0;
-  while (!doms.empty()) {
+  while (!Regs.empty()) {
     if (!dv) {
-      dv =3D doms.pop_back_val();
+      dv =3D Regs.pop_back_val().Value;
+      // Force the first dv to match the current instruction.
+      dv->AvailableDomains =3D dv->getCommonDomains(available);
+      assert(dv->AvailableDomains && "Domain should have been filtered");
       continue;
     }
=20
-    DomainValue *latest =3D doms.pop_back_val();
-    if (Merge(dv, latest)) continue;
+    DomainValue *Latest =3D Regs.pop_back_val().Value;
+    // Skip already merged values.
+    if (Latest =3D=3D dv || Latest->Next)
+      continue;
+    if (merge(dv, Latest))
+      continue;
=20
     // If latest didn't merge, it is useless now. Kill all registers using=
 it.
     for (SmallVector<int,4>::iterator i=3Dused.begin(), e=3Dused.end(); i =
!=3D e; ++i)
-      if (LiveRegs[*i] =3D=3D latest)
-        Kill(*i);
+      if (LiveRegs[*i].Value =3D=3D Latest)
+        kill(*i);
   }
=20
   // dv is the DomainValue we are going to use for this instruction.
-  if (!dv)
-    dv =3D Alloc();
-  dv->Dist =3D Distance;
-  dv->AvailableDomains =3D available;
+  if (!dv) {
+    dv =3D alloc();
+    dv->AvailableDomains =3D available;
+  }
   dv->Instrs.push_back(mi);
=20
   // Finally set all defs and non-collapsed uses to dv.
   for (unsigned i =3D 0, e =3D mi->getDesc().getNumOperands(); i !=3D e; +=
+i) {
     MachineOperand &mo =3D mi->getOperand(i);
     if (!mo.isReg()) continue;
-    int rx =3D RegIndex(mo.getReg());
+    int rx =3D regIndex(mo.getReg());
     if (rx < 0) continue;
-    if (!LiveRegs || !LiveRegs[rx] || (mo.isDef() && LiveRegs[rx]!=3Ddv)) {
-      Kill(rx);
-      SetLiveReg(rx, dv);
+    if (!LiveRegs[rx].Value || (mo.isDef() && LiveRegs[rx].Value !=3D dv))=
 {
+      kill(rx);
+      setLiveReg(rx, dv);
     }
   }
 }
=20
-void ExeDepsFix::visitGenericInstr(MachineInstr *mi) {
-  // Process explicit defs, kill any relevant registers redefined.
-  for (unsigned i =3D 0, e =3D mi->getDesc().getNumDefs(); i !=3D e; ++i) {
-    MachineOperand &mo =3D mi->getOperand(i);
-    if (!mo.isReg()) continue;
-    int rx =3D RegIndex(mo.getReg());
-    if (rx < 0) continue;
-    Kill(rx);
-  }
-}
-
 bool ExeDepsFix::runOnMachineFunction(MachineFunction &mf) {
   MF =3D &mf;
   TII =3D MF->getTarget().getInstrInfo();
   TRI =3D MF->getTarget().getRegisterInfo();
-  MBB =3D 0;
   LiveRegs =3D 0;
-  Distance =3D 0;
   assert(NumRegs =3D=3D RC->getNumRegs() && "Bad regclass");
=20
+  DEBUG(dbgs() << "********** FIX EXECUTION DEPENDENCIES: "
+               << RC->getName() << " **********\n");
+
   // If no relevant registers are used in the function, we can skip it
   // completely.
   bool anyregs =3D false;
   for (TargetRegisterClass::const_iterator I =3D RC->begin(), E =3D RC->en=
d();
        I !=3D E; ++I)
-    if (MF->getRegInfo().isPhysRegUsed(*I)) {
+    if (MF->getRegInfo().isPhysRegOrOverlapUsed(*I)) {
       anyregs =3D true;
       break;
     }
@@ -473,43 +666,48 @@
     // or -1.
     AliasMap.resize(TRI->getNumRegs(), -1);
     for (unsigned i =3D 0, e =3D RC->getNumRegs(); i !=3D e; ++i)
-      for (const unsigned *AI =3D TRI->getOverlaps(RC->getRegister(i)); *A=
I; ++AI)
+      for (const uint16_t *AI =3D TRI->getOverlaps(RC->getRegister(i)); *A=
I; ++AI)
         AliasMap[*AI] =3D i;
   }
=20
   MachineBasicBlock *Entry =3D MF->begin();
-  SmallPtrSet<MachineBasicBlock*, 16> Visited;
-  for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,=
 16> >
-         DFI =3D df_ext_begin(Entry, Visited), DFE =3D df_ext_end(Entry, V=
isited);
-         DFI !=3D DFE; ++DFI) {
-    MBB =3D *DFI;
-    enterBasicBlock();
+  ReversePostOrderTraversal<MachineBasicBlock*> RPOT(Entry);
+  SmallVector<MachineBasicBlock*, 16> Loops;
+  for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
+         MBBI =3D RPOT.begin(), MBBE =3D RPOT.end(); MBBI !=3D MBBE; ++MBB=
I) {
+    MachineBasicBlock *MBB =3D *MBBI;
+    enterBasicBlock(MBB);
+    if (SeenUnknownBackEdge)
+      Loops.push_back(MBB);
     for (MachineBasicBlock::iterator I =3D MBB->begin(), E =3D MBB->end();=
 I !=3D E;
-        ++I) {
-      MachineInstr *mi =3D I;
-      if (mi->isDebugValue()) continue;
-      ++Distance;
-      std::pair<uint16_t, uint16_t> domp =3D TII->getExecutionDomain(mi);
-      if (domp.first)
-        if (domp.second)
-          visitSoftInstr(mi, domp.second);
-        else
-          visitHardInstr(mi, domp.first);
-      else if (LiveRegs)
-        visitGenericInstr(mi);
-    }
-
-    // Save live registers at end of MBB - used by enterBasicBlock().
-    if (LiveRegs)
-      LiveOuts.insert(std::make_pair(MBB, LiveRegs));
-    LiveRegs =3D 0;
+        ++I)
+      visitInstr(I);
+    leaveBasicBlock(MBB);
   }
=20
-  // Clear the LiveOuts vectors. Should we also collapse any remaining
-  // DomainValues?
-  for (LiveOutMap::const_iterator i =3D LiveOuts.begin(), e =3D LiveOuts.e=
nd();
-         i !=3D e; ++i)
-    delete[] i->second;
+  // Visit all the loop blocks again in order to merge DomainValues from
+  // back-edges.
+  for (unsigned i =3D 0, e =3D Loops.size(); i !=3D e; ++i) {
+    MachineBasicBlock *MBB =3D Loops[i];
+    enterBasicBlock(MBB);
+    for (MachineBasicBlock::iterator I =3D MBB->begin(), E =3D MBB->end();=
 I !=3D E;
+        ++I)
+      if (!I->isDebugValue())
+        processDefs(I, false);
+    leaveBasicBlock(MBB);
+  }
+
+  // Clear the LiveOuts vectors and collapse any remaining DomainValues.
+  for (ReversePostOrderTraversal<MachineBasicBlock*>::rpo_iterator
+         MBBI =3D RPOT.begin(), MBBE =3D RPOT.end(); MBBI !=3D MBBE; ++MBB=
I) {
+    LiveOutMap::const_iterator FI =3D LiveOuts.find(*MBBI);
+    if (FI =3D=3D LiveOuts.end() || !FI->second)
+      continue;
+    for (unsigned i =3D 0, e =3D NumRegs; i !=3D e; ++i)
+      if (FI->second[i].Value)
+        release(FI->second[i].Value);
+    delete[] FI->second;
+  }
   LiveOuts.clear();
   Avail.clear();
   Allocator.DestroyAll();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/ExpandIS=
elPseudos.cpp
--- a/head/contrib/llvm/lib/CodeGen/ExpandISelPseudos.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ExpandISelPseudos.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -32,10 +32,6 @@
   private:
     virtual bool runOnMachineFunction(MachineFunction &MF);
=20
-    const char *getPassName() const {
-      return "Expand ISel Pseudo-instructions";
-    }
-
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       MachineFunctionPass::getAnalysisUsage(AU);
     }
@@ -43,12 +39,9 @@
 } // end anonymous namespace
=20
 char ExpandISelPseudos::ID =3D 0;
+char &llvm::ExpandISelPseudosID =3D ExpandISelPseudos::ID;
 INITIALIZE_PASS(ExpandISelPseudos, "expand-isel-pseudos",
-                "Expand CodeGen Pseudo-instructions", false, false)
-
-FunctionPass *llvm::createExpandISelPseudosPass() {
-  return new ExpandISelPseudos();
-}
+                "Expand ISel Pseudo-instructions", false, false)
=20
 bool ExpandISelPseudos::runOnMachineFunction(MachineFunction &MF) {
   bool Changed =3D false;
@@ -62,8 +55,7 @@
       MachineInstr *MI =3D MBBI++;
=20
       // If MI is a pseudo, expand it.
-      const MCInstrDesc &MCID =3D MI->getDesc();
-      if (MCID.usesCustomInsertionHook()) {
+      if (MI->usesCustomInsertionHook()) {
         Changed =3D true;
         MachineBasicBlock *NewMBB =3D
           TLI->EmitInstrWithCustomInserter(MI, MBB);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/ExpandPo=
stRAPseudos.cpp
--- a/head/contrib/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ExpandPostRAPseudos.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -36,10 +36,6 @@
   static char ID; // Pass identification, replacement for typeid
   ExpandPostRA() : MachineFunctionPass(ID) {}
=20
-  const char *getPassName() const {
-    return "Post-RA pseudo instruction expansion pass";
-  }
-
   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
     AU.setPreservesCFG();
     AU.addPreservedID(MachineLoopInfoID);
@@ -61,10 +57,10 @@
 } // end anonymous namespace
=20
 char ExpandPostRA::ID =3D 0;
+char &llvm::ExpandPostRAPseudosID =3D ExpandPostRA::ID;
=20
-FunctionPass *llvm::createExpandPostRAPseudosPass() {
-  return new ExpandPostRA();
-}
+INITIALIZE_PASS(ExpandPostRA, "postrapseudos",
+                "Post-RA pseudo instruction expansion pass", false, false)
=20
 /// TransferDeadFlag - MI is a pseudo-instruction with DstReg dead,
 /// and the lowered replacement instructions immediately precede it.
@@ -207,7 +203,7 @@
       ++mi;
=20
       // Only expand pseudos.
-      if (!MI->getDesc().isPseudo())
+      if (!MI->isPseudo())
         continue;
=20
       // Give targets a chance to expand even standard pseudos.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/GCMetada=
ta.cpp
--- a/head/contrib/llvm/lib/CodeGen/GCMetadata.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/CodeGen/GCMetadata.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -143,12 +143,12 @@
=20
 static const char *DescKind(GC::PointKind Kind) {
   switch (Kind) {
-    default: llvm_unreachable("Unknown GC point kind");
     case GC::Loop:     return "loop";
     case GC::Return:   return "return";
     case GC::PreCall:  return "pre-call";
     case GC::PostCall: return "post-call";
   }
+  llvm_unreachable("Invalid point kind");
 }
=20
 bool Printer::runOnFunction(Function &F) {
@@ -156,12 +156,12 @@
  =20
   GCFunctionInfo *FD =3D &getAnalysis<GCModuleInfo>().getFunctionInfo(F);
  =20
-  OS << "GC roots for " << FD->getFunction().getNameStr() << ":\n";
+  OS << "GC roots for " << FD->getFunction().getName() << ":\n";
   for (GCFunctionInfo::roots_iterator RI =3D FD->roots_begin(),
                                       RE =3D FD->roots_end(); RI !=3D RE; =
++RI)
     OS << "\t" << RI->Num << "\t" << RI->StackOffset << "[sp]\n";
  =20
-  OS << "GC safe points for " << FD->getFunction().getNameStr() << ":\n";
+  OS << "GC safe points for " << FD->getFunction().getName() << ":\n";
   for (GCFunctionInfo::iterator PI =3D FD->begin(),
                                 PE =3D FD->end(); PI !=3D PE; ++PI) {
    =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/GCStrate=
gy.cpp
--- a/head/contrib/llvm/lib/CodeGen/GCStrategy.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/CodeGen/GCStrategy.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -10,8 +10,8 @@
 // This file implements target- and collector-independent garbage collecti=
on
 // infrastructure.
 //
-// MachineCodeAnalysis identifies the GC safe points in the machine code. =
Roots
-// are identified in SelectionDAGISel.
+// GCMachineCodeAnalysis identifies the GC safe points in the machine code.
+// Roots are identified in SelectionDAGISel.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -35,9 +35,9 @@
 using namespace llvm;
=20
 namespace {
- =20
+
   /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
-  /// llvm.gcwrite intrinsics, replacing them with simple loads and stores=
 as=20
+  /// llvm.gcwrite intrinsics, replacing them with simple loads and stores=
 as
   /// directed by the GCStrategy. It also performs automatic root initiali=
zation
   /// and custom intrinsic lowering.
   class LowerIntrinsics : public FunctionPass {
@@ -47,47 +47,46 @@
     bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
     static bool InsertRootInitializers(Function &F,
                                        AllocaInst **Roots, unsigned Count);
-   =20
+
   public:
     static char ID;
-   =20
+
     LowerIntrinsics();
     const char *getPassName() const;
     void getAnalysisUsage(AnalysisUsage &AU) const;
-   =20
+
     bool doInitialization(Module &M);
     bool runOnFunction(Function &F);
   };
- =20
- =20
-  /// MachineCodeAnalysis - This is a target-independent pass over the mac=
hine=20
+
+
+  /// GCMachineCodeAnalysis - This is a target-independent pass over the m=
achine
   /// function representation to identify safe points for the garbage coll=
ector
   /// in the machine code. It inserts labels at safe points and populates a
   /// GCMetadata record for each function.
-  class MachineCodeAnalysis : public MachineFunctionPass {
+  class GCMachineCodeAnalysis : public MachineFunctionPass {
     const TargetMachine *TM;
     GCFunctionInfo *FI;
     MachineModuleInfo *MMI;
     const TargetInstrInfo *TII;
-   =20
+
     void FindSafePoints(MachineFunction &MF);
     void VisitCallPoint(MachineBasicBlock::iterator MI);
-    MCSymbol *InsertLabel(MachineBasicBlock &MBB,=20
+    MCSymbol *InsertLabel(MachineBasicBlock &MBB,
                           MachineBasicBlock::iterator MI,
                           DebugLoc DL) const;
-   =20
+
     void FindStackOffsets(MachineFunction &MF);
-   =20
+
   public:
     static char ID;
-   =20
-    MachineCodeAnalysis();
-    const char *getPassName() const;
+
+    GCMachineCodeAnalysis();
     void getAnalysisUsage(AnalysisUsage &AU) const;
-   =20
+
     bool runOnMachineFunction(MachineFunction &MF);
   };
- =20
+
 }
=20
 // -----------------------------------------------------------------------=
------
@@ -97,6 +96,7 @@
   CustomReadBarriers(false),
   CustomWriteBarriers(false),
   CustomRoots(false),
+  CustomSafePoints(false),
   InitRoots(true),
   UsesMetadata(false)
 {}
@@ -104,18 +104,24 @@
 GCStrategy::~GCStrategy() {
   for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I)
     delete *I;
- =20
+
   Functions.clear();
 }
-=20
+
 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
-=20
+
 bool GCStrategy::performCustomLowering(Function &F) {
   dbgs() << "gc " << getName() << " must override performCustomLowering.\n=
";
+  llvm_unreachable("must override performCustomLowering");
+}
+
+
+bool GCStrategy::findCustomSafePoints(GCFunctionInfo& FI, MachineFunction =
&F) {
+  dbgs() << "gc " << getName() << " must override findCustomSafePoints.\n";
   llvm_unreachable(0);
-  return 0;
 }
=20
+
 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
   GCFunctionInfo *FI =3D new GCFunctionInfo(F, *this);
   Functions.push_back(FI);
@@ -132,7 +138,7 @@
 FunctionPass *llvm::createGCLoweringPass() {
   return new LowerIntrinsics();
 }
-=20
+
 char LowerIntrinsics::ID =3D 0;
=20
 LowerIntrinsics::LowerIntrinsics()
@@ -143,7 +149,7 @@
 const char *LowerIntrinsics::getPassName() const {
   return "Lower Garbage Collection Instructions";
 }
-   =20
+
 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
   FunctionPass::getAnalysisUsage(AU);
   AU.addRequired<GCModuleInfo>();
@@ -161,22 +167,22 @@
   for (Module::iterator I =3D M.begin(), E =3D M.end(); I !=3D E; ++I)
     if (!I->isDeclaration() && I->hasGC())
       MI->getFunctionInfo(*I); // Instantiate the GC strategy.
- =20
+
   bool MadeChange =3D false;
   for (GCModuleInfo::iterator I =3D MI->begin(), E =3D MI->end(); I !=3D E=
; ++I)
     if (NeedsCustomLoweringPass(**I))
       if ((*I)->initializeCustomLowering(M))
         MadeChange =3D true;
- =20
+
   return MadeChange;
 }
=20
-bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roo=
ts,=20
+bool LowerIntrinsics::InsertRootInitializers(Function &F, AllocaInst **Roo=
ts,
                                                           unsigned Count) {
   // Scroll past alloca instructions.
   BasicBlock::iterator IP =3D F.getEntryBlock().begin();
   while (isa<AllocaInst>(IP)) ++IP;
- =20
+
   // Search for initializers in the initial BB.
   SmallPtrSet<AllocaInst*,16> InitedRoots;
   for (; !CouldBecomeSafePoint(IP); ++IP)
@@ -184,10 +190,10 @@
       if (AllocaInst *AI =3D
           dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
         InitedRoots.insert(AI);
- =20
+
   // Add root initializers.
   bool MadeChange =3D false;
- =20
+
   for (AllocaInst **I =3D Roots, **E =3D Roots + Count; I !=3D E; ++I)
     if (!InitedRoots.count(*I)) {
       StoreInst* SI =3D new StoreInst(ConstantPointerNull::get(cast<Pointe=
rType>(
@@ -196,7 +202,7 @@
       SI->insertAfter(*I);
       MadeChange =3D true;
     }
- =20
+
   return MadeChange;
 }
=20
@@ -220,26 +226,26 @@
 bool LowerIntrinsics::CouldBecomeSafePoint(Instruction *I) {
   // The natural definition of instructions which could introduce safe poi=
nts
   // are:
-  //=20
+  //
   //   - call, invoke (AfterCall, BeforeCall)
   //   - phis (Loops)
   //   - invoke, ret, unwind (Exit)
-  //=20
+  //
   // However, instructions as seemingly inoccuous as arithmetic can become
   // libcalls upon lowering (e.g., div i64 on a 32-bit platform), so inste=
ad
   // it is necessary to take a conservative approach.
- =20
+
   if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) ||
       isa<StoreInst>(I) || isa<LoadInst>(I))
     return false;
- =20
+
   // llvm.gcroot is safe because it doesn't do anything at runtime.
   if (CallInst *CI =3D dyn_cast<CallInst>(I))
     if (Function *F =3D CI->getCalledFunction())
       if (unsigned IID =3D F->getIntrinsicID())
         if (IID =3D=3D Intrinsic::gcroot)
           return false;
- =20
+
   return true;
 }
=20
@@ -249,15 +255,15 @@
   // Quick exit for functions that do not use GC.
   if (!F.hasGC())
     return false;
- =20
+
   GCFunctionInfo &FI =3D getAnalysis<GCModuleInfo>().getFunctionInfo(F);
   GCStrategy &S =3D FI.getStrategy();
- =20
+
   bool MadeChange =3D false;
- =20
+
   if (NeedsDefaultLoweringPass(S))
     MadeChange |=3D PerformDefaultLowering(F, S);
- =20
+
   bool UseCustomLoweringPass =3D NeedsCustomLoweringPass(S);
   if (UseCustomLoweringPass)
     MadeChange |=3D S.performCustomLowering(F);
@@ -275,9 +281,9 @@
   bool LowerWr =3D !S.customWriteBarrier();
   bool LowerRd =3D !S.customReadBarrier();
   bool InitRoots =3D S.initializeRoots();
- =20
+
   SmallVector<AllocaInst*, 32> Roots;
- =20
+
   bool MadeChange =3D false;
   for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB=
) {
     for (BasicBlock::iterator II =3D BB->begin(), E =3D BB->end(); II !=3D=
 E;) {
@@ -313,104 +319,104 @@
         default:
           continue;
         }
-       =20
+
         MadeChange =3D true;
       }
     }
   }
- =20
+
   if (Roots.size())
     MadeChange |=3D InsertRootInitializers(F, Roots.begin(), Roots.size());
- =20
+
   return MadeChange;
 }
=20
 // -----------------------------------------------------------------------=
------
=20
-FunctionPass *llvm::createGCMachineCodeAnalysisPass() {
-  return new MachineCodeAnalysis();
-}
+char GCMachineCodeAnalysis::ID =3D 0;
+char &llvm::GCMachineCodeAnalysisID =3D GCMachineCodeAnalysis::ID;
=20
-char MachineCodeAnalysis::ID =3D 0;
+INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
+                "Analyze Machine Code For Garbage Collection", false, fals=
e)
=20
-MachineCodeAnalysis::MachineCodeAnalysis()
+GCMachineCodeAnalysis::GCMachineCodeAnalysis()
   : MachineFunctionPass(ID) {}
=20
-const char *MachineCodeAnalysis::getPassName() const {
-  return "Analyze Machine Code For Garbage Collection";
-}
-
-void MachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
+void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
   MachineFunctionPass::getAnalysisUsage(AU);
   AU.setPreservesAll();
   AU.addRequired<MachineModuleInfo>();
   AU.addRequired<GCModuleInfo>();
 }
=20
-MCSymbol *MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,=20
-                                           MachineBasicBlock::iterator MI,
-                                           DebugLoc DL) const {
+MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
+                                             MachineBasicBlock::iterator M=
I,
+                                             DebugLoc DL) const {
   MCSymbol *Label =3D MBB.getParent()->getContext().CreateTempSymbol();
   BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
   return Label;
 }
=20
-void MachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
+void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI)=
 {
   // Find the return address (next instruction), too, so as to bracket the=
 call
   // instruction.
-  MachineBasicBlock::iterator RAI =3D CI;=20
-  ++RAI;                               =20
- =20
+  MachineBasicBlock::iterator RAI =3D CI;
+  ++RAI;
+
   if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
     MCSymbol* Label =3D InsertLabel(*CI->getParent(), CI, CI->getDebugLoc(=
));
     FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
   }
- =20
+
   if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
     MCSymbol* Label =3D InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc=
());
     FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
   }
 }
=20
-void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
+void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
   for (MachineFunction::iterator BBI =3D MF.begin(),
                                  BBE =3D MF.end(); BBI !=3D BBE; ++BBI)
     for (MachineBasicBlock::iterator MI =3D BBI->begin(),
                                      ME =3D BBI->end(); MI !=3D ME; ++MI)
-      if (MI->getDesc().isCall())
+      if (MI->isCall())
         VisitCallPoint(MI);
 }
=20
-void MachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
+void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
   const TargetFrameLowering *TFI =3D TM->getFrameLowering();
   assert(TFI && "TargetRegisterInfo not available!");
- =20
+
   for (GCFunctionInfo::roots_iterator RI =3D FI->roots_begin(),
                                       RE =3D FI->roots_end(); RI !=3D RE; =
++RI)
     RI->StackOffset =3D TFI->getFrameIndexOffset(MF, RI->Num);
 }
=20
-bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
+bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
   // Quick exit for functions that do not use GC.
   if (!MF.getFunction()->hasGC())
     return false;
- =20
+
   FI =3D &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
   if (!FI->getStrategy().needsSafePoints())
     return false;
- =20
+
   TM =3D &MF.getTarget();
   MMI =3D &getAnalysis<MachineModuleInfo>();
   TII =3D TM->getInstrInfo();
- =20
+
   // Find the size of the stack frame.
   FI->setFrameSize(MF.getFrameInfo()->getStackSize());
- =20
+
   // Find all safe points.
-  FindSafePoints(MF);
- =20
+  if (FI->getStrategy().customSafePoints()) {
+    FI->getStrategy().findCustomSafePoints(*FI, MF);
+  } else {
+    FindSafePoints(MF);
+  }
+
   // Find the stack offsets for all roots.
   FindStackOffsets(MF);
- =20
+
   return false;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/IfConver=
sion.cpp
--- a/head/contrib/llvm/lib/CodeGen/IfConversion.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/CodeGen/IfConversion.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -62,6 +62,7 @@
 STATISTIC(NumDiamonds,     "Number of diamond if-conversions performed");
 STATISTIC(NumIfConvBBs,    "Number of if-converted blocks");
 STATISTIC(NumDupBBs,       "Number of duplicated blocks");
+STATISTIC(NumUnpred,       "Number of true blocks of diamonds unpredicated=
");
=20
 namespace {
   class IfConverter : public MachineFunctionPass {
@@ -169,7 +170,6 @@
     }
=20
     virtual bool runOnMachineFunction(MachineFunction &MF);
-    virtual const char *getPassName() const { return "If Converter"; }
=20
   private:
     bool ReverseBranchCondition(BBInfo &BBI);
@@ -195,7 +195,8 @@
     void PredicateBlock(BBInfo &BBI,
                         MachineBasicBlock::iterator E,
                         SmallVectorImpl<MachineOperand> &Cond,
-                        SmallSet<unsigned, 4> &Redefs);
+                        SmallSet<unsigned, 4> &Redefs,
+                        SmallSet<unsigned, 4> *LaterRedefs =3D 0);
     void CopyAndPredicateBlock(BBInfo &ToBBI, BBInfo &FromBBI,
                                SmallVectorImpl<MachineOperand> &Cond,
                                SmallSet<unsigned, 4> &Redefs,
@@ -251,12 +252,12 @@
   char IfConverter::ID =3D 0;
 }
=20
+char &llvm::IfConverterID =3D IfConverter::ID;
+
 INITIALIZE_PASS_BEGIN(IfConverter, "if-converter", "If Converter", false, =
false)
 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
 INITIALIZE_PASS_END(IfConverter, "if-converter", "If Converter", false, fa=
lse)
=20
-FunctionPass *llvm::createIfConverterPass() { return new IfConverter(); }
-
 bool IfConverter::runOnMachineFunction(MachineFunction &MF) {
   TLI =3D MF.getTarget().getTargetLowering();
   TII =3D MF.getTarget().getInstrInfo();
@@ -313,8 +314,7 @@
=20
       bool RetVal =3D false;
       switch (Kind) {
-      default: assert(false && "Unexpected!");
-        break;
+      default: llvm_unreachable("Unexpected!");
       case ICSimple:
       case ICSimpleFalse: {
         bool isFalse =3D Kind =3D=3D ICSimpleFalse;
@@ -573,12 +573,12 @@
   // blocks, move the end iterators up past any branch instructions.
   while (TIE !=3D TIB) {
     --TIE;
-    if (!TIE->getDesc().isBranch())
+    if (!TIE->isBranch())
       break;
   }
   while (FIE !=3D FIB) {
     --FIE;
-    if (!FIE->getDesc().isBranch())
+    if (!FIE->isBranch())
       break;
   }
=20
@@ -651,12 +651,11 @@
     if (I->isDebugValue())
       continue;
=20
-    const MCInstrDesc &MCID =3D I->getDesc();
-    if (MCID.isNotDuplicable())
+    if (I->isNotDuplicable())
       BBI.CannotBeCopied =3D true;
=20
     bool isPredicated =3D TII->isPredicated(I);
-    bool isCondBr =3D BBI.IsBrAnalyzable && MCID.isConditionalBranch();
+    bool isCondBr =3D BBI.IsBrAnalyzable && I->isConditionalBranch();
=20
     if (!isCondBr) {
       if (!isPredicated) {
@@ -963,7 +962,7 @@
          E =3D BB->livein_end(); I !=3D E; ++I) {
     unsigned Reg =3D *I;
     Redefs.insert(Reg);
-    for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+    for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
          *Subreg; ++Subreg)
       Redefs.insert(*Subreg);
   }
@@ -984,7 +983,7 @@
       Defs.push_back(Reg);
     else if (MO.isKill()) {
       Redefs.erase(Reg);
-      for (const unsigned *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
+      for (const uint16_t *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
         Redefs.erase(*SR);
     }
   }
@@ -997,7 +996,7 @@
                                                 true/*IsImp*/,false/*IsKil=
l*/));
     } else {
       Redefs.insert(Reg);
-      for (const unsigned *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
+      for (const uint16_t *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
         Redefs.insert(*SR);
     }
   }
@@ -1035,7 +1034,7 @@
=20
   if (Kind =3D=3D ICSimpleFalse)
     if (TII->ReverseBranchCondition(Cond))
-      assert(false && "Unable to reverse branch condition!");
+      llvm_unreachable("Unable to reverse branch condition!");
=20
   // Initialize liveins to the first BB. These are potentiall redefined by
   // predicated instructions.
@@ -1108,7 +1107,7 @@
=20
   if (Kind =3D=3D ICTriangleFalse || Kind =3D=3D ICTriangleFRev)
     if (TII->ReverseBranchCondition(Cond))
-      assert(false && "Unable to reverse branch condition!");
+      llvm_unreachable("Unable to reverse branch condition!");
=20
   if (Kind =3D=3D ICTriangleRev || Kind =3D=3D ICTriangleFRev) {
     if (ReverseBranchCondition(*CvtBBI)) {
@@ -1155,7 +1154,7 @@
     SmallVector<MachineOperand, 4> RevCond(CvtBBI->BrCond.begin(),
                                            CvtBBI->BrCond.end());
     if (TII->ReverseBranchCondition(RevCond))
-      assert(false && "Unable to reverse branch condition!");
+      llvm_unreachable("Unable to reverse branch condition!");
     TII->InsertBranch(*BBI.BB, CvtBBI->FalseBB, NULL, RevCond, dl);
     BBI.BB->addSuccessor(CvtBBI->FalseBB);
   }
@@ -1227,7 +1226,7 @@
   BBInfo *BBI2 =3D &FalseBBI;
   SmallVector<MachineOperand, 4> RevCond(BBI.BrCond.begin(), BBI.BrCond.en=
d());
   if (TII->ReverseBranchCondition(RevCond))
-    assert(false && "Unable to reverse branch condition!");
+    llvm_unreachable("Unable to reverse branch condition!");
   SmallVector<MachineOperand, 4> *Cond1 =3D &BBI.BrCond;
   SmallVector<MachineOperand, 4> *Cond2 =3D &RevCond;
=20
@@ -1281,7 +1280,7 @@
   BBI.BB->splice(BBI.BB->end(), BBI1->BB, BBI1->BB->begin(), DI1);
   BBI2->BB->erase(BBI2->BB->begin(), DI2);
=20
-  // Predicate the 'true' block after removing its branch.
+  // Remove branch from 'true' block and remove duplicated instructions.
   BBI1->NonPredSize -=3D TII->RemoveBranch(*BBI1->BB);
   DI1 =3D BBI1->BB->end();
   for (unsigned i =3D 0; i !=3D NumDups2; ) {
@@ -1294,9 +1293,8 @@
       ++i;
   }
   BBI1->BB->erase(DI1, BBI1->BB->end());
-  PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs);
=20
-  // Predicate the 'false' block.
+  // Remove 'false' block branch and find the last instruction to predicat=
e.
   BBI2->NonPredSize -=3D TII->RemoveBranch(*BBI2->BB);
   DI2 =3D BBI2->BB->end();
   while (NumDups2 !=3D 0) {
@@ -1308,6 +1306,55 @@
     if (!DI2->isDebugValue())
       --NumDups2;
   }
+
+  // Remember which registers would later be defined by the false block.
+  // This allows us not to predicate instructions in the true block that w=
ould
+  // later be re-defined. That is, rather than
+  //   subeq  r0, r1, #1
+  //   addne  r0, r1, #1
+  // generate:
+  //   sub    r0, r1, #1
+  //   addne  r0, r1, #1
+  SmallSet<unsigned, 4> RedefsByFalse;
+  SmallSet<unsigned, 4> ExtUses;
+  if (TII->isProfitableToUnpredicate(*BBI1->BB, *BBI2->BB)) {
+    for (MachineBasicBlock::iterator FI =3D BBI2->BB->begin(); FI !=3D DI2=
; ++FI) {
+      if (FI->isDebugValue())
+        continue;
+      SmallVector<unsigned, 4> Defs;
+      for (unsigned i =3D 0, e =3D FI->getNumOperands(); i !=3D e; ++i) {
+        const MachineOperand &MO =3D FI->getOperand(i);
+        if (!MO.isReg())
+          continue;
+        unsigned Reg =3D MO.getReg();
+        if (!Reg)
+          continue;
+        if (MO.isDef()) {
+          Defs.push_back(Reg);
+        } else if (!RedefsByFalse.count(Reg)) {
+          // These are defined before ctrl flow reach the 'false' instruct=
ions.
+          // They cannot be modified by the 'true' instructions.
+          ExtUses.insert(Reg);
+          for (const uint16_t *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
+            ExtUses.insert(*SR);
+        }
+      }
+
+      for (unsigned i =3D 0, e =3D Defs.size(); i !=3D e; ++i) {
+        unsigned Reg =3D Defs[i];
+        if (!ExtUses.count(Reg)) {
+          RedefsByFalse.insert(Reg);
+          for (const uint16_t *SR =3D TRI->getSubRegisters(Reg); *SR; ++SR)
+            RedefsByFalse.insert(*SR);
+        }
+      }
+    }
+  }
+
+  // Predicate the 'true' block.
+  PredicateBlock(*BBI1, BBI1->BB->end(), *Cond1, Redefs, &RedefsByFalse);
+
+  // Predicate the 'false' block.
   PredicateBlock(*BBI2, DI2, *Cond2, Redefs);
=20
   // Merge the true block into the entry of the diamond.
@@ -1319,7 +1366,7 @@
   // fold the tail block in as well. Otherwise, unless it falls through to=
 the
   // tail, add a unconditional branch to it.
   if (TailBB) {
-    BBInfo TailBBI =3D BBAnalysis[TailBB->getNumber()];
+    BBInfo &TailBBI =3D BBAnalysis[TailBB->getNumber()];
     bool CanMergeTail =3D !TailBBI.HasFallThrough;
     // There may still be a fall-through edge from BBI1 or BBI2 to TailBB;
     // check if there are any other predecessors besides those.
@@ -1356,15 +1403,49 @@
   return true;
 }
=20
+static bool MaySpeculate(const MachineInstr *MI,
+                         SmallSet<unsigned, 4> &LaterRedefs,
+                         const TargetInstrInfo *TII) {
+  bool SawStore =3D true;
+  if (!MI->isSafeToMove(TII, 0, SawStore))
+    return false;
+
+  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
+    const MachineOperand &MO =3D MI->getOperand(i);
+    if (!MO.isReg())
+      continue;
+    unsigned Reg =3D MO.getReg();
+    if (!Reg)
+      continue;
+    if (MO.isDef() && !LaterRedefs.count(Reg))
+      return false;
+  }
+
+  return true;
+}
+
 /// PredicateBlock - Predicate instructions from the start of the block to=
 the
 /// specified end with the specified condition.
 void IfConverter::PredicateBlock(BBInfo &BBI,
                                  MachineBasicBlock::iterator E,
                                  SmallVectorImpl<MachineOperand> &Cond,
-                                 SmallSet<unsigned, 4> &Redefs) {
+                                 SmallSet<unsigned, 4> &Redefs,
+                                 SmallSet<unsigned, 4> *LaterRedefs) {
+  bool AnyUnpred =3D false;
+  bool MaySpec =3D LaterRedefs !=3D 0;
   for (MachineBasicBlock::iterator I =3D BBI.BB->begin(); I !=3D E; ++I) {
     if (I->isDebugValue() || TII->isPredicated(I))
       continue;
+    // It may be possible not to predicate an instruction if it's the 'tru=
e'
+    // side of a diamond and the 'false' side may re-define the instructio=
n's
+    // defs.
+    if (MaySpec && MaySpeculate(I, *LaterRedefs, TII)) {
+      AnyUnpred =3D true;
+      continue;
+    }
+    // If any instruction is predicated, then every instruction after it m=
ust
+    // be predicated.
+    MaySpec =3D false;
     if (!TII->PredicateInstruction(I, Cond)) {
 #ifndef NDEBUG
       dbgs() << "Unable to predicate " << *I << "!\n";
@@ -1383,6 +1464,8 @@
   BBI.NonPredSize =3D 0;
=20
   ++NumIfConvBBs;
+  if (AnyUnpred)
+    ++NumUnpred;
 }
=20
 /// CopyAndPredicateBlock - Copy and predicate instructions from source BB=
 to
@@ -1395,9 +1478,8 @@
=20
   for (MachineBasicBlock::iterator I =3D FromBBI.BB->begin(),
          E =3D FromBBI.BB->end(); I !=3D E; ++I) {
-    const MCInstrDesc &MCID =3D I->getDesc();
     // Do not copy the end of the block branches.
-    if (IgnoreBr && MCID.isBranch())
+    if (IgnoreBr && I->isBranch())
       break;
=20
     MachineInstr *MI =3D MF.CloneMachineInstr(I);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/InlineSp=
iller.cpp
--- a/head/contrib/llvm/lib/CodeGen/InlineSpiller.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/InlineSpiller.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -14,14 +14,15 @@
=20
 #define DEBUG_TYPE "regalloc"
 #include "Spiller.h"
-#include "LiveRangeEdit.h"
 #include "VirtRegMap.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "llvm/CodeGen/LiveRangeEdit.h"
 #include "llvm/CodeGen/LiveStackAnalysis.h"
 #include "llvm/CodeGen/MachineDominators.h"
+#include "llvm/CodeGen/MachineInstrBundle.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineLoopInfo.h"
@@ -173,8 +174,7 @@
   void reMaterializeAll();
=20
   bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
-  bool foldMemoryOperand(MachineBasicBlock::iterator MI,
-                         const SmallVectorImpl<unsigned> &Ops,
+  bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
                          MachineInstr *LoadMI =3D 0);
   void insertReload(LiveInterval &NewLI, SlotIndex,
                     MachineBasicBlock::iterator MI);
@@ -578,7 +578,7 @@
     if (unsigned SrcReg =3D isFullCopyOf(MI, Reg)) {
       if (isSibling(SrcReg)) {
         LiveInterval &SrcLI =3D LIS.getInterval(SrcReg);
-        LiveRange *SrcLR =3D SrcLI.getLiveRangeContaining(VNI->def.getUseI=
ndex());
+        LiveRange *SrcLR =3D SrcLI.getLiveRangeContaining(VNI->def.getRegS=
lot(true));
         assert(SrcLR && "Copy from non-existing value");
         // Check if this COPY kills its source.
         SVI->second.KillsSource =3D (SrcLR->end =3D=3D VNI->def);
@@ -644,16 +644,18 @@
       if (VNI->isUnused())
         continue;
       MachineInstr *DefMI =3D 0;
+      if (!VNI->isPHIDef()) {
+       DefMI =3D LIS.getInstructionFromIndex(VNI->def);
+       assert(DefMI && "No defining instruction");
+      }
       // Check possible sibling copies.
-      if (VNI->isPHIDef() || VNI->getCopy()) {
+      if (VNI->isPHIDef() || DefMI->isCopy()) {
         VNInfo *OrigVNI =3D OrigLI.getVNInfoAt(VNI->def);
         assert(OrigVNI && "Def outside original live range");
         if (OrigVNI->def !=3D VNI->def)
           DefMI =3D traceSiblingValue(Reg, VNI, OrigVNI);
       }
-      if (!DefMI && !VNI->isPHIDef())
-        DefMI =3D LIS.getInstructionFromIndex(VNI->def);
-      if (DefMI && Edit->checkRematerializable(VNI, DefMI, TII, AA)) {
+      if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
         DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
                      << VNI->def << " may remat from " << *DefMI);
       }
@@ -665,8 +667,8 @@
 /// a spill at a better location.
 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI=
) {
   SlotIndex Idx =3D LIS.getInstructionIndex(CopyMI);
-  VNInfo *VNI =3D SpillLI.getVNInfoAt(Idx.getDefIndex());
-  assert(VNI && VNI->def =3D=3D Idx.getDefIndex() && "Not defined by copy"=
);
+  VNInfo *VNI =3D SpillLI.getVNInfoAt(Idx.getRegSlot());
+  assert(VNI && VNI->def =3D=3D Idx.getRegSlot() && "Not defined by copy");
   SibValueMap::iterator I =3D SibValues.find(VNI);
   if (I =3D=3D SibValues.end())
     return false;
@@ -726,7 +728,6 @@
                           MRI.getRegClass(SVI.SpillReg), &TRI);
   --MII; // Point to store instruction.
   LIS.InsertMachineInstrInMaps(MII);
-  VRM.addSpillSlotUse(StackSlot, MII);
   DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
=20
   ++NumSpills;
@@ -760,7 +761,7 @@
     // Find all spills and copies of VNI.
     for (MachineRegisterInfo::use_nodbg_iterator UI =3D MRI.use_nodbg_begi=
n(Reg);
          MachineInstr *MI =3D UI.skipInstruction();) {
-      if (!MI->isCopy() && !MI->getDesc().mayStore())
+      if (!MI->isCopy() && !MI->mayStore())
         continue;
       SlotIndex Idx =3D LIS.getInstructionIndex(MI);
       if (LI->getVNInfoAt(Idx) !=3D VNI)
@@ -770,9 +771,9 @@
       if (unsigned DstReg =3D isFullCopyOf(MI, Reg)) {
         if (isSibling(DstReg)) {
            LiveInterval &DstLI =3D LIS.getInterval(DstReg);
-           VNInfo *DstVNI =3D DstLI.getVNInfoAt(Idx.getDefIndex());
+           VNInfo *DstVNI =3D DstLI.getVNInfoAt(Idx.getRegSlot());
            assert(DstVNI && "Missing defined value");
-           assert(DstVNI->def =3D=3D Idx.getDefIndex() && "Wrong copy def =
slot");
+           assert(DstVNI->def =3D=3D Idx.getRegSlot() && "Wrong copy def s=
lot");
            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
         }
         continue;
@@ -811,7 +812,7 @@
       MachineBasicBlock *MBB =3D LIS.getMBBFromIndex(VNI->def);
       for (MachineBasicBlock::pred_iterator PI =3D MBB->pred_begin(),
              PE =3D MBB->pred_end(); PI !=3D PE; ++PI) {
-        VNInfo *PVNI =3D LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot=
());
+        VNInfo *PVNI =3D LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
         if (PVNI)
           WorkList.push_back(std::make_pair(LI, PVNI));
       }
@@ -824,7 +825,7 @@
       continue;
     LiveInterval &SnipLI =3D LIS.getInterval(MI->getOperand(1).getReg());
     assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
-    VNInfo *SnipVNI =3D SnipLI.getVNInfoAt(VNI->def.getUseIndex());
+    VNInfo *SnipVNI =3D SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
     assert(SnipVNI && "Snippet undefined before copy");
     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
   } while (!WorkList.empty());
@@ -833,7 +834,7 @@
 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloa=
ding.
 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
                                      MachineBasicBlock::iterator MI) {
-  SlotIndex UseIdx =3D LIS.getInstructionIndex(MI).getUseIndex();
+  SlotIndex UseIdx =3D LIS.getInstructionIndex(MI).getRegSlot(true);
   VNInfo *ParentVNI =3D VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
=20
   if (!ParentVNI) {
@@ -855,7 +856,7 @@
   SibValueMap::const_iterator SibI =3D SibValues.find(ParentVNI);
   if (SibI !=3D SibValues.end())
     RM.OrigMI =3D SibI->second.DefMI;
-  if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
+  if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
     markValueUsed(&VirtReg, ParentVNI);
     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
     return false;
@@ -863,42 +864,37 @@
=20
   // If the instruction also writes VirtReg.reg, it had better not require=
 the
   // same register for uses and defs.
-  bool Reads, Writes;
-  SmallVector<unsigned, 8> Ops;
-  tie(Reads, Writes) =3D MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
-  if (Writes) {
-    for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i) {
-      MachineOperand &MO =3D MI->getOperand(Ops[i]);
-      if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg())=
 {
-        markValueUsed(&VirtReg, ParentVNI);
-        DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *=
MI);
-        return false;
-      }
-    }
+  SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
+  MIBundleOperands::RegInfo RI =3D
+    MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
+  if (RI.Tied) {
+    markValueUsed(&VirtReg, ParentVNI);
+    DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
+    return false;
   }
=20
   // Before rematerializing into a register for a single instruction, try =
to
   // fold a load into the instruction. That avoids allocating a new regist=
er.
-  if (RM.OrigMI->getDesc().canFoldAsLoad() &&
-      foldMemoryOperand(MI, Ops, RM.OrigMI)) {
+  if (RM.OrigMI->canFoldAsLoad() &&
+      foldMemoryOperand(Ops, RM.OrigMI)) {
     Edit->markRematerialized(RM.ParentVNI);
     ++NumFoldedLoads;
     return true;
   }
=20
   // Alocate a new register for the remat.
-  LiveInterval &NewLI =3D Edit->createFrom(Original, LIS, VRM);
+  LiveInterval &NewLI =3D Edit->createFrom(Original);
   NewLI.markNotSpillable();
=20
   // Finally we can rematerialize OrigMI before MI.
   SlotIndex DefIdx =3D Edit->rematerializeAt(*MI->getParent(), MI, NewLI.r=
eg, RM,
-                                           LIS, TII, TRI);
+                                           TRI);
   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
                << *LIS.getInstructionFromIndex(DefIdx));
=20
   // Replace operands
   for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i) {
-    MachineOperand &MO =3D MI->getOperand(Ops[i]);
+    MachineOperand &MO =3D MI->getOperand(Ops[i].second);
     if (MO.isReg() && MO.isUse() && MO.getReg() =3D=3D VirtReg.reg) {
       MO.setReg(NewLI.reg);
       MO.setIsKill();
@@ -906,8 +902,8 @@
   }
   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI);
=20
-  VNInfo *DefVNI =3D NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator(=
));
-  NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
+  VNInfo *DefVNI =3D NewLI.getNextValue(DefIdx, LIS.getVNInfoAllocator());
+  NewLI.addRange(LiveRange(DefIdx, UseIdx.getRegSlot(), DefVNI));
   DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
   ++NumRemats;
   return true;
@@ -917,7 +913,7 @@
 /// and trim the live ranges after.
 void InlineSpiller::reMaterializeAll() {
   // analyzeSiblingValues has already tested all relevant defining instruc=
tions.
-  if (!Edit->anyRematerializable(LIS, TII, AA))
+  if (!Edit->anyRematerializable(AA))
     return;
=20
   UsedValues.clear();
@@ -929,7 +925,7 @@
     LiveInterval &LI =3D LIS.getInterval(Reg);
     for (MachineRegisterInfo::use_nodbg_iterator
          RI =3D MRI.use_nodbg_begin(Reg);
-         MachineInstr *MI =3D RI.skipInstruction();)
+         MachineInstr *MI =3D RI.skipBundle();)
       anyRemat |=3D reMaterializeFor(LI, MI);
   }
   if (!anyRemat)
@@ -958,7 +954,7 @@
   if (DeadDefs.empty())
     return;
   DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
-  Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
+  Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
=20
   // Get rid of deleted and empty intervals.
   for (unsigned i =3D RegsToSpill.size(); i !=3D 0; --i) {
@@ -970,7 +966,7 @@
     LiveInterval &LI =3D LIS.getInterval(Reg);
     if (!LI.empty())
       continue;
-    Edit->eraseVirtReg(Reg, LIS);
+    Edit->eraseVirtReg(Reg);
     RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
   }
   DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\=
n");
@@ -1008,23 +1004,35 @@
   return true;
 }
=20
-/// foldMemoryOperand - Try folding stack slot references in Ops into MI.
-/// @param MI     Instruction using or defining the current register.
-/// @param Ops    Operand indices from readsWritesVirtualRegister().
+/// foldMemoryOperand - Try folding stack slot references in Ops into their
+/// instructions.
+///
+/// @param Ops    Operand indices from analyzeVirtReg().
 /// @param LoadMI Load instruction to use instead of stack slot when non-n=
ull.
-/// @return       True on success, and MI will be erased.
-bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
-                                      const SmallVectorImpl<unsigned> &Ops,
-                                      MachineInstr *LoadMI) {
+/// @return       True on success.
+bool InlineSpiller::
+foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
+                  MachineInstr *LoadMI) {
+  if (Ops.empty())
+    return false;
+  // Don't attempt folding in bundles.
+  MachineInstr *MI =3D Ops.front().first;
+  if (Ops.back().first !=3D MI || MI->isBundled())
+    return false;
+
   bool WasCopy =3D MI->isCopy();
+  unsigned ImpReg =3D 0;
+
   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
   // operands.
   SmallVector<unsigned, 8> FoldOps;
   for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i) {
-    unsigned Idx =3D Ops[i];
+    unsigned Idx =3D Ops[i].second;
     MachineOperand &MO =3D MI->getOperand(Idx);
-    if (MO.isImplicit())
+    if (MO.isImplicit()) {
+      ImpReg =3D MO.getReg();
       continue;
+    }
     // FIXME: Teach targets to deal with subregs.
     if (MO.getSubReg())
       return false;
@@ -1042,13 +1050,24 @@
   if (!FoldMI)
     return false;
   LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
-  if (!LoadMI)
-    VRM.addSpillSlotUse(StackSlot, FoldMI);
   MI->eraseFromParent();
-  DEBUG(dbgs() << "\tfolded: " << *FoldMI);
+
+  // TII.foldMemoryOperand may have left some implicit operands on the
+  // instruction.  Strip them.
+  if (ImpReg)
+    for (unsigned i =3D FoldMI->getNumOperands(); i; --i) {
+      MachineOperand &MO =3D FoldMI->getOperand(i - 1);
+      if (!MO.isReg() || !MO.isImplicit())
+        break;
+      if (MO.getReg() =3D=3D ImpReg)
+        FoldMI->RemoveOperand(i - 1);
+    }
+
+  DEBUG(dbgs() << "\tfolded:  " << LIS.getInstructionIndex(FoldMI) << '\t'
+               << *FoldMI);
   if (!WasCopy)
     ++NumFolded;
-  else if (Ops.front() =3D=3D 0)
+  else if (Ops.front().second =3D=3D 0)
     ++NumSpills;
   else
     ++NumReloads;
@@ -1063,11 +1082,9 @@
   TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
                            MRI.getRegClass(NewLI.reg), &TRI);
   --MI; // Point to load instruction.
-  SlotIndex LoadIdx =3D LIS.InsertMachineInstrInMaps(MI).getDefIndex();
-  VRM.addSpillSlotUse(StackSlot, MI);
+  SlotIndex LoadIdx =3D LIS.InsertMachineInstrInMaps(MI).getRegSlot();
   DEBUG(dbgs() << "\treload:  " << LoadIdx << '\t' << *MI);
-  VNInfo *LoadVNI =3D NewLI.getNextValue(LoadIdx, 0,
-                                       LIS.getVNInfoAllocator());
+  VNInfo *LoadVNI =3D NewLI.getNextValue(LoadIdx, LIS.getVNInfoAllocator()=
);
   NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
   ++NumReloads;
 }
@@ -1079,10 +1096,9 @@
   TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
                           MRI.getRegClass(NewLI.reg), &TRI);
   --MI; // Point to store instruction.
-  SlotIndex StoreIdx =3D LIS.InsertMachineInstrInMaps(MI).getDefIndex();
-  VRM.addSpillSlotUse(StackSlot, MI);
+  SlotIndex StoreIdx =3D LIS.InsertMachineInstrInMaps(MI).getRegSlot();
   DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
-  VNInfo *StoreVNI =3D NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator()=
);
+  VNInfo *StoreVNI =3D NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
   NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
   ++NumSpills;
 }
@@ -1093,8 +1109,8 @@
   LiveInterval &OldLI =3D LIS.getInterval(Reg);
=20
   // Iterate over instructions using Reg.
-  for (MachineRegisterInfo::reg_iterator RI =3D MRI.reg_begin(Reg);
-       MachineInstr *MI =3D RI.skipInstruction();) {
+  for (MachineRegisterInfo::reg_iterator RegI =3D MRI.reg_begin(Reg);
+       MachineInstr *MI =3D RegI.skipBundle();) {
=20
     // Debug values are not allowed to affect codegen.
     if (MI->isDebugValue()) {
@@ -1123,14 +1139,14 @@
       continue;
=20
     // Analyze instruction.
-    bool Reads, Writes;
-    SmallVector<unsigned, 8> Ops;
-    tie(Reads, Writes) =3D MI->readsWritesVirtualRegister(Reg, &Ops);
+    SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
+    MIBundleOperands::RegInfo RI =3D
+      MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
=20
     // Find the slot index where this instruction reads and writes OldLI.
     // This is usually the def slot, except for tied early clobbers.
-    SlotIndex Idx =3D LIS.getInstructionIndex(MI).getDefIndex();
-    if (VNInfo *VNI =3D OldLI.getVNInfoAt(Idx.getUseIndex()))
+    SlotIndex Idx =3D LIS.getInstructionIndex(MI).getRegSlot();
+    if (VNInfo *VNI =3D OldLI.getVNInfoAt(Idx.getRegSlot(true)))
       if (SlotIndex::isSameInstr(Idx, VNI->def))
         Idx =3D VNI->def;
=20
@@ -1143,7 +1159,7 @@
         SnippetCopies.insert(MI);
         continue;
       }
-      if (Writes) {
+      if (RI.Writes) {
         // Hoist the spill of a sib-reg copy.
         if (hoistSpill(OldLI, MI)) {
           // This COPY is now dead, the value is already in the stack slot.
@@ -1160,24 +1176,24 @@
     }
=20
     // Attempt to fold memory ops.
-    if (foldMemoryOperand(MI, Ops))
+    if (foldMemoryOperand(Ops))
       continue;
=20
     // Allocate interval around instruction.
     // FIXME: Infer regclass from instruction alone.
-    LiveInterval &NewLI =3D Edit->createFrom(Reg, LIS, VRM);
+    LiveInterval &NewLI =3D Edit->createFrom(Reg);
     NewLI.markNotSpillable();
=20
-    if (Reads)
+    if (RI.Reads)
       insertReload(NewLI, Idx, MI);
=20
     // Rewrite instruction operands.
     bool hasLiveDef =3D false;
     for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i) {
-      MachineOperand &MO =3D MI->getOperand(Ops[i]);
+      MachineOperand &MO =3D Ops[i].first->getOperand(Ops[i].second);
       MO.setReg(NewLI.reg);
       if (MO.isUse()) {
-        if (!MI->isRegTiedToDefOperand(Ops[i]))
+        if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
           MO.setIsKill();
       } else {
         if (!MO.isDead())
@@ -1187,15 +1203,15 @@
     DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
=20
     // FIXME: Use a second vreg if instruction has no tied ops.
-    if (Writes) {
-     if (hasLiveDef)
-      insertSpill(NewLI, OldLI, Idx, MI);
-     else {
-       // This instruction defines a dead value.  We don't need to spill i=
t,
-       // but do create a live range for the dead value.
-       VNInfo *VNI =3D NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator()=
);
-       NewLI.addRange(LiveRange(Idx, Idx.getNextSlot(), VNI));
-     }
+    if (RI.Writes) {
+      if (hasLiveDef)
+        insertSpill(NewLI, OldLI, Idx, MI);
+      else {
+        // This instruction defines a dead value.  We don't need to spill =
it,
+        // but do create a live range for the dead value.
+        VNInfo *VNI =3D NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
+        NewLI.addRange(LiveRange(Idx, Idx.getDeadSlot(), VNI));
+      }
     }
=20
     DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
@@ -1208,7 +1224,7 @@
   if (StackSlot =3D=3D VirtRegMap::NO_STACK_SLOT) {
     StackSlot =3D VRM.assignVirt2StackSlot(Original);
     StackInt =3D &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Origi=
nal));
-    StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
+    StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
   } else
     StackInt =3D &LSS.getInterval(StackSlot);
=20
@@ -1228,7 +1244,7 @@
   // Hoisted spills may cause dead code.
   if (!DeadDefs.empty()) {
     DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
-    Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
+    Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
   }
=20
   // Finally delete the SnippetCopies.
@@ -1237,7 +1253,6 @@
          MachineInstr *MI =3D RI.skipInstruction();) {
       assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet co=
py");
       // FIXME: Do this with a LiveRangeEdit callback.
-      VRM.RemoveMachineInstrFromMaps(MI);
       LIS.RemoveMachineInstrFromMaps(MI);
       MI->eraseFromParent();
     }
@@ -1245,7 +1260,7 @@
=20
   // Delete all spilled registers.
   for (unsigned i =3D 0, e =3D RegsToSpill.size(); i !=3D e; ++i)
-    Edit->eraseVirtReg(RegsToSpill[i], LIS);
+    Edit->eraseVirtReg(RegsToSpill[i]);
 }
=20
 void InlineSpiller::spill(LiveRangeEdit &edit) {
@@ -1274,5 +1289,5 @@
   if (!RegsToSpill.empty())
     spillAll();
=20
-  Edit->calculateRegClassAndHint(MF, LIS, Loops);
+  Edit->calculateRegClassAndHint(MF, Loops);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Interfer=
enceCache.cpp
--- a/head/contrib/llvm/lib/CodeGen/InterferenceCache.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/InterferenceCache.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- InterferenceCache.h - Caching per-block interference ---*- C=
++ -*--=3D=3D=3D//
+//=3D=3D=3D-- InterferenceCache.cpp - Caching per-block interference -----=
----*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,6 +15,7 @@
 #include "InterferenceCache.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/CodeGen/LiveIntervalAnalysis.h"
=20
 using namespace llvm;
=20
@@ -24,13 +25,14 @@
 void InterferenceCache::init(MachineFunction *mf,
                              LiveIntervalUnion *liuarray,
                              SlotIndexes *indexes,
+                             LiveIntervals *lis,
                              const TargetRegisterInfo *tri) {
   MF =3D mf;
   LIUArray =3D liuarray;
   TRI =3D tri;
   PhysRegEntries.assign(TRI->getNumRegs(), 0);
   for (unsigned i =3D 0; i !=3D CacheEntries; ++i)
-    Entries[i].clear(mf, indexes);
+    Entries[i].clear(mf, indexes, lis);
 }
=20
 InterferenceCache::Entry *InterferenceCache::get(unsigned PhysReg) {
@@ -78,7 +80,7 @@
   PhysReg =3D physReg;
   Blocks.resize(MF->getNumBlockIDs());
   Aliases.clear();
-  for (const unsigned *AS =3D TRI->getOverlaps(PhysReg); *AS; ++AS) {
+  for (const uint16_t *AS =3D TRI->getOverlaps(PhysReg); *AS; ++AS) {
     LiveIntervalUnion *LIU =3D LIUArray + *AS;
     Aliases.push_back(std::make_pair(LIU, LIU->getTag()));
   }
@@ -94,7 +96,7 @@
 bool InterferenceCache::Entry::valid(LiveIntervalUnion *LIUArray,
                                      const TargetRegisterInfo *TRI) {
   unsigned i =3D 0, e =3D Aliases.size();
-  for (const unsigned *AS =3D TRI->getOverlaps(PhysReg); *AS; ++AS, ++i) {
+  for (const uint16_t *AS =3D TRI->getOverlaps(PhysReg); *AS; ++AS, ++i) {
     LiveIntervalUnion *LIU =3D LIUArray + *AS;
     if (i =3D=3D e ||  Aliases[i].first !=3D LIU)
       return false;
@@ -121,6 +123,8 @@
=20
   MachineFunction::const_iterator MFI =3D MF->getBlockNumbered(MBBNum);
   BlockInterference *BI =3D &Blocks[MBBNum];
+  ArrayRef<SlotIndex> RegMaskSlots;
+  ArrayRef<const uint32_t*> RegMaskBits;
   for (;;) {
     BI->Tag =3D Tag;
     BI->First =3D BI->Last =3D SlotIndex();
@@ -137,6 +141,18 @@
         BI->First =3D StartI;
     }
=20
+    // Also check for register mask interference.
+    RegMaskSlots =3D LIS->getRegMaskSlotsInBlock(MBBNum);
+    RegMaskBits =3D LIS->getRegMaskBitsInBlock(MBBNum);
+    SlotIndex Limit =3D BI->First.isValid() ? BI->First : Stop;
+    for (unsigned i =3D 0, e =3D RegMaskSlots.size();
+         i !=3D e && RegMaskSlots[i] < Limit; ++i)
+      if (MachineOperand::clobbersPhysReg(RegMaskBits[i], PhysReg)) {
+        // Register mask i clobbers PhysReg before the LIU interference.
+        BI->First =3D RegMaskSlots[i];
+        break;
+      }
+
     PrevPos =3D Stop;
     if (BI->First.isValid())
       break;
@@ -166,4 +182,15 @@
     if (Backup)
       ++I;
   }
+
+  // Also check for register mask interference.
+  SlotIndex Limit =3D BI->Last.isValid() ? BI->Last : Start;
+  for (unsigned i =3D RegMaskSlots.size();
+       i && RegMaskSlots[i-1].getDeadSlot() > Limit; --i)
+    if (MachineOperand::clobbersPhysReg(RegMaskBits[i-1], PhysReg)) {
+      // Register mask i-1 clobbers PhysReg after the LIU interference.
+      // Model the regmask clobber as a dead def.
+      BI->Last =3D RegMaskSlots[i-1].getDeadSlot();
+      break;
+    }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Interfer=
enceCache.h
--- a/head/contrib/llvm/lib/CodeGen/InterferenceCache.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/InterferenceCache.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -18,10 +18,11 @@
=20
 namespace llvm {
=20
+class LiveIntervals;
+
 class InterferenceCache {
   const TargetRegisterInfo *TRI;
   LiveIntervalUnion *LIUArray;
-  SlotIndexes *Indexes;
   MachineFunction *MF;
=20
   /// BlockInterference - information about the interference in a single b=
asic
@@ -52,6 +53,9 @@
     /// Indexes - Mapping block numbers to SlotIndex ranges.
     SlotIndexes *Indexes;
=20
+    /// LIS - Used for accessing register mask interference maps.
+    LiveIntervals *LIS;
+
     /// PrevPos - The previous position the iterators were moved to.
     SlotIndex PrevPos;
=20
@@ -71,13 +75,14 @@
     void update(unsigned MBBNum);
=20
   public:
-    Entry() : PhysReg(0), Tag(0), RefCount(0), Indexes(0) {}
+    Entry() : PhysReg(0), Tag(0), RefCount(0), Indexes(0), LIS(0) {}
=20
-    void clear(MachineFunction *mf, SlotIndexes *indexes) {
+    void clear(MachineFunction *mf, SlotIndexes *indexes, LiveIntervals *l=
is) {
       assert(!hasRefs() && "Cannot clear cache entry with references");
       PhysReg =3D 0;
       MF =3D mf;
       Indexes =3D indexes;
+      LIS =3D lis;
     }
=20
     unsigned getPhysReg() const { return PhysReg; }
@@ -124,10 +129,10 @@
   Entry *get(unsigned PhysReg);
=20
 public:
-  InterferenceCache() : TRI(0), LIUArray(0), Indexes(0), MF(0), RoundRobin=
(0) {}
+  InterferenceCache() : TRI(0), LIUArray(0), MF(0), RoundRobin(0) {}
=20
   /// init - Prepare cache for a new function.
-  void init(MachineFunction*, LiveIntervalUnion*, SlotIndexes*,
+  void init(MachineFunction*, LiveIntervalUnion*, SlotIndexes*, LiveInterv=
als*,
             const TargetRegisterInfo *);
=20
   /// getMaxCursors - Return the maximum number of concurrent cursors that=
 can
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Intrinsi=
cLowering.cpp
--- a/head/contrib/llvm/lib/CodeGen/IntrinsicLowering.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/IntrinsicLowering.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -448,11 +448,6 @@
   case Intrinsic::dbg_declare:
     break;    // Simply strip out debugging intrinsics
=20
-  case Intrinsic::eh_exception:
-  case Intrinsic::eh_selector:
-    CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
-    break;
-
   case Intrinsic::eh_typeid_for:
     // Return something different to eh_selector.
     CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LLVMTarg=
etMachine.cpp
--- a/head/contrib/llvm/lib/CodeGen/LLVMTargetMachine.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LLVMTargetMachine.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -11,96 +11,31 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "llvm/Target/TargetMachine.h"
+#include "llvm/Transforms/Scalar.h"
 #include "llvm/PassManager.h"
-#include "llvm/Analysis/Passes.h"
-#include "llvm/Analysis/Verifier.h"
-#include "llvm/Assembly/PrintModulePass.h"
 #include "llvm/CodeGen/AsmPrinter.h"
+#include "llvm/CodeGen/Passes.h"
 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
-#include "llvm/CodeGen/GCStrategy.h"
-#include "llvm/CodeGen/Passes.h"
+#include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetLowering.h"
+#include "llvm/Target/TargetLoweringObjectFile.h"
+#include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
+#include "llvm/Target/TargetSubtargetInfo.h"
+#include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/MC/MCAsmInfo.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSubtargetInfo.h"
-#include "llvm/Target/TargetData.h"
-#include "llvm/Target/TargetInstrInfo.h"
-#include "llvm/Target/TargetLowering.h"
-#include "llvm/Target/TargetLoweringObjectFile.h"
-#include "llvm/Target/TargetRegisterInfo.h"
-#include "llvm/Target/TargetSubtargetInfo.h"
-#include "llvm/Transforms/Scalar.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/Support/CommandLine.h"
-#include "llvm/Support/Debug.h"
 #include "llvm/Support/FormattedStream.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
 using namespace llvm;
=20
-namespace llvm {
-  bool EnableFastISel;
-}
-
-static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
-    cl::desc("Disable Post Regalloc"));
-static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
-    cl::desc("Disable branch folding"));
-static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hi=
dden,
-    cl::desc("Disable tail duplication"));
-static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidd=
en,
-    cl::desc("Disable pre-register allocation tail duplication"));
-static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
-    cl::desc("Disable code placement"));
-static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
-    cl::desc("Disable Stack Slot Coloring"));
-static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
-    cl::desc("Disable Machine Dead Code Elimination"));
-static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
-    cl::desc("Disable Machine LICM"));
-static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
-    cl::desc("Disable Machine Common Subexpression Elimination"));
-static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm=
",
-    cl::Hidden,
-    cl::desc("Disable Machine LICM"));
-static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
-    cl::desc("Disable Machine Sinking"));
-static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
-    cl::desc("Disable Loop Strength Reduction Pass"));
-static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
-    cl::desc("Disable Codegen Prepare"));
-static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
-    cl::desc("Print LLVM IR produced by the loop-reduce pass"));
-static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
-    cl::desc("Print LLVM IR input to isel pass"));
-static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
-    cl::desc("Dump garbage collector data"));
-static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
-    cl::desc("Show encoding in .s output"));
-static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
-    cl::desc("Show instruction structure in .s output"));
-static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
-    cl::desc("Enable MC API logging"));
-static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
-    cl::desc("Verify generated machine code"),
-    cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=3DNULL));
-
-static cl::opt<cl::boolOrDefault>
-AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
-           cl::init(cl::BOU_UNSET));
-
-static bool getVerboseAsm() {
-  switch (AsmVerbose) {
-  default:
-  case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
-  case cl::BOU_TRUE:  return true;
-  case cl::BOU_FALSE: return false;
-  }
-}
-
 // Enable or disable FastISel. Both options are needed, because
 // FastISel is enabled by default with -fast, and we wish to be
 // able to enable or disable fast-isel independently from -O0.
@@ -108,11 +43,31 @@
 EnableFastISelOption("fast-isel", cl::Hidden,
   cl::desc("Enable the \"fast\" instruction selector"));
=20
+static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
+    cl::desc("Show encoding in .s output"));
+static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
+    cl::desc("Show instruction structure in .s output"));
+
+static cl::opt<cl::boolOrDefault>
+AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
+           cl::init(cl::BOU_UNSET));
+
+static bool getVerboseAsm() {
+  switch (AsmVerbose) {
+  case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
+  case cl::BOU_TRUE:  return true;
+  case cl::BOU_FALSE: return false;
+  }
+  llvm_unreachable("Invalid verbose asm state");
+}
+
 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
                                      StringRef CPU, StringRef FS,
-                                     Reloc::Model RM, CodeModel::Model CM)
-  : TargetMachine(T, Triple, CPU, FS) {
-  CodeGenInfo =3D T.createMCCodeGenInfo(Triple, RM, CM);
+                                     TargetOptions Options,
+                                     Reloc::Model RM, CodeModel::Model CM,
+                                     CodeGenOpt::Level OL)
+  : TargetMachine(T, Triple, CPU, FS, Options) {
+  CodeGenInfo =3D T.createMCCodeGenInfo(Triple, RM, CM, OL);
   AsmInfo =3D T.createMCAsmInfo(Triple);
   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.=
0,
   // and if the old one gets included then MCAsmInfo will be NULL and
@@ -123,16 +78,88 @@
          "and that InitializeAllTargetMCs() is being invoked!");
 }
=20
+/// Turn exception handling constructs into something the code generators =
can
+/// handle.
+static void addPassesToHandleExceptions(TargetMachine *TM,
+                                        PassManagerBase &PM) {
+  switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
+  case ExceptionHandling::SjLj:
+    // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to =
both
+    // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
+    // catch info can get misplaced when a selector ends up more than one =
block
+    // removed from the parent invoke(s). This could happen when a landing
+    // pad is shared by multiple invokes and is also a target of a normal
+    // edge from elsewhere.
+    PM.add(createSjLjEHPreparePass(TM->getTargetLowering()));
+    // FALLTHROUGH
+  case ExceptionHandling::DwarfCFI:
+  case ExceptionHandling::ARM:
+  case ExceptionHandling::Win64:
+    PM.add(createDwarfEHPass(TM));
+    break;
+  case ExceptionHandling::None:
+    PM.add(createLowerInvokePass(TM->getTargetLowering()));
+
+    // The lower invoke pass may create unreachable code. Remove it.
+    PM.add(createUnreachableBlockEliminationPass());
+    break;
+  }
+}
+
+/// addPassesToX helper drives creation and initialization of TargetPassCo=
nfig.
+static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
+                                          PassManagerBase &PM,
+                                          bool DisableVerify) {
+  // Targets may override createPassConfig to provide a target-specific su=
blass.
+  TargetPassConfig *PassConfig =3D TM->createPassConfig(PM);
+
+  // Set PassConfig options provided by TargetMachine.
+  PassConfig->setDisableVerify(DisableVerify);
+
+  PM.add(PassConfig);
+
+  PassConfig->addIRPasses();
+
+  addPassesToHandleExceptions(TM, PM);
+
+  PassConfig->addISelPrepare();
+
+  // Install a MachineModuleInfo class, which is an immutable pass that ho=
lds
+  // all the per-module stuff we're generating, including MCContext.
+  MachineModuleInfo *MMI =3D
+    new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
+                          &TM->getTargetLowering()->getObjFileLowering());
+  PM.add(MMI);
+  MCContext *Context =3D &MMI->getContext(); // Return the MCContext by-re=
f.
+
+  // Set up a MachineFunction for the rest of CodeGen to work on.
+  PM.add(new MachineFunctionAnalysis(*TM));
+
+  // Enable FastISel with -fast, but allow that to be overridden.
+  if (EnableFastISelOption =3D=3D cl::BOU_TRUE ||
+      (TM->getOptLevel() =3D=3D CodeGenOpt::None &&
+       EnableFastISelOption !=3D cl::BOU_FALSE))
+    TM->setFastISel(true);
+
+  // Ask the target for an isel.
+  if (PassConfig->addInstSelector())
+    return NULL;
+
+  PassConfig->addMachinePasses();
+
+  PassConfig->setInitialized();
+
+  return Context;
+}
+
 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
                                             formatted_raw_ostream &Out,
                                             CodeGenFileType FileType,
-                                            CodeGenOpt::Level OptLevel,
                                             bool DisableVerify) {
   // Add common CodeGen passes.
-  MCContext *Context =3D 0;
-  if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
+  MCContext *Context =3D addPassesToGenerateCode(this, PM, DisableVerify);
+  if (!Context)
     return true;
-  assert(Context !=3D 0 && "Failed to get MCContext");
=20
   if (hasMCSaveTempLabels())
     Context->setAllowTemporaryLabels(false);
@@ -142,10 +169,11 @@
   OwningPtr<MCStreamer> AsmStreamer;
=20
   switch (FileType) {
-  default: return true;
   case CGFT_AssemblyFile: {
     MCInstPrinter *InstPrinter =3D
-      getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
+      getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
+                                      *getInstrInfo(),
+                                      Context->getRegisterInfo(), STI);
=20
     // Create a code emitter if asked to show the encoding.
     MCCodeEmitter *MCE =3D 0;
@@ -160,6 +188,7 @@
                                                   getVerboseAsm(),
                                                   hasMCUseLoc(),
                                                   hasMCUseCFI(),
+                                                  hasMCUseDwarfDirectory(),
                                                   InstPrinter,
                                                   MCE, MAB,
                                                   ShowMCInst);
@@ -189,9 +218,6 @@
     break;
   }
=20
-  if (EnableMCLogging)
-    AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
-
   // Create the AsmPrinter, which takes ownership of AsmStreamer if succes=
sful.
   FunctionPass *Printer =3D getTarget().createAsmPrinter(*this, *AsmStream=
er);
   if (Printer =3D=3D 0)
@@ -214,14 +240,13 @@
 ///
 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
                                                    JITCodeEmitter &JCE,
-                                                   CodeGenOpt::Level OptLe=
vel,
                                                    bool DisableVerify) {
   // Add common CodeGen passes.
-  MCContext *Ctx =3D 0;
-  if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
+  MCContext *Context =3D addPassesToGenerateCode(this, PM, DisableVerify);
+  if (!Context)
     return true;
=20
-  addCodeEmitter(PM, OptLevel, JCE);
+  addCodeEmitter(PM, JCE);
   PM.add(createGCInfoDeleter());
=20
   return false; // success!
@@ -235,10 +260,10 @@
 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
                                           MCContext *&Ctx,
                                           raw_ostream &Out,
-                                          CodeGenOpt::Level OptLevel,
                                           bool DisableVerify) {
   // Add common CodeGen passes.
-  if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
+  Ctx =3D addPassesToGenerateCode(this, PM, DisableVerify);
+  if (!Ctx)
     return true;
=20
   if (hasMCSaveTempLabels())
@@ -247,7 +272,8 @@
   // Create the code emitter for the target if it exists.  If not, .o file
   // emission fails.
   const MCSubtargetInfo &STI =3D getSubtarget<MCSubtargetInfo>();
-  MCCodeEmitter *MCE =3D getTarget().createMCCodeEmitter(*getInstrInfo(),S=
TI, *Ctx);
+  MCCodeEmitter *MCE =3D getTarget().createMCCodeEmitter(*getInstrInfo(),S=
TI,
+                                                       *Ctx);
   MCAsmBackend *MAB =3D getTarget().createMCAsmBackend(getTargetTriple());
   if (MCE =3D=3D 0 || MAB =3D=3D 0)
     return true;
@@ -271,227 +297,3 @@
=20
   return false; // success!
 }
-
-static void printNoVerify(PassManagerBase &PM, const char *Banner) {
-  if (PrintMachineCode)
-    PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
-}
-
-static void printAndVerify(PassManagerBase &PM,
-                           const char *Banner) {
-  if (PrintMachineCode)
-    PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
-
-  if (VerifyMachineCode)
-    PM.add(createMachineVerifierPass(Banner));
-}
-
-/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
-/// emitting to assembly files or machine code output.
-///
-bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
-                                               CodeGenOpt::Level OptLevel,
-                                               bool DisableVerify,
-                                               MCContext *&OutContext) {
-  // Standard LLVM-Level Passes.
-
-  // Basic AliasAnalysis support.
-  // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
-  // BasicAliasAnalysis wins if they disagree. This is intended to help
-  // support "obvious" type-punning idioms.
-  PM.add(createTypeBasedAliasAnalysisPass());
-  PM.add(createBasicAliasAnalysisPass());
-
-  // Before running any passes, run the verifier to determine if the input
-  // coming from the front-end and/or optimizer is valid.
-  if (!DisableVerify)
-    PM.add(createVerifierPass());
-
-  // Run loop strength reduction before anything else.
-  if (OptLevel !=3D CodeGenOpt::None && !DisableLSR) {
-    PM.add(createLoopStrengthReducePass(getTargetLowering()));
-    if (PrintLSR)
-      PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs=
()));
-  }
-
-  PM.add(createGCLoweringPass());
-
-  // Make sure that no unreachable blocks are instruction selected.
-  PM.add(createUnreachableBlockEliminationPass());
-
-  // Turn exception handling constructs into something the code generators=
 can
-  // handle.
-  switch (getMCAsmInfo()->getExceptionHandlingType()) {
-  case ExceptionHandling::SjLj:
-    // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to =
both
-    // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
-    // catch info can get misplaced when a selector ends up more than one =
block
-    // removed from the parent invoke(s). This could happen when a landing
-    // pad is shared by multiple invokes and is also a target of a normal
-    // edge from elsewhere.
-    PM.add(createSjLjEHPass(getTargetLowering()));
-    // FALLTHROUGH
-  case ExceptionHandling::DwarfCFI:
-  case ExceptionHandling::ARM:
-  case ExceptionHandling::Win64:
-    PM.add(createDwarfEHPass(this));
-    break;
-  case ExceptionHandling::None:
-    PM.add(createLowerInvokePass(getTargetLowering()));
-
-    // The lower invoke pass may create unreachable code. Remove it.
-    PM.add(createUnreachableBlockEliminationPass());
-    break;
-  }
-
-  if (OptLevel !=3D CodeGenOpt::None && !DisableCGP)
-    PM.add(createCodeGenPreparePass(getTargetLowering()));
-
-  PM.add(createStackProtectorPass(getTargetLowering()));
-
-  addPreISel(PM, OptLevel);
-
-  if (PrintISelInput)
-    PM.add(createPrintFunctionPass("\n\n"
-                                   "*** Final LLVM Code input to ISel ***\=
n",
-                                   &dbgs()));
-
-  // All passes which modify the LLVM IR are now complete; run the verifier
-  // to ensure that the IR is valid.
-  if (!DisableVerify)
-    PM.add(createVerifierPass());
-
-  // Standard Lower-Level Passes.
-
-  // Install a MachineModuleInfo class, which is an immutable pass that ho=
lds
-  // all the per-module stuff we're generating, including MCContext.
-  MachineModuleInfo *MMI =3D new MachineModuleInfo(*getMCAsmInfo(),
-                                                 *getRegisterInfo(),
-                                     &getTargetLowering()->getObjFileLower=
ing());
-  PM.add(MMI);
-  OutContext =3D &MMI->getContext(); // Return the MCContext specifically =
by-ref.
-
-  // Set up a MachineFunction for the rest of CodeGen to work on.
-  PM.add(new MachineFunctionAnalysis(*this, OptLevel));
-
-  // Enable FastISel with -fast, but allow that to be overridden.
-  if (EnableFastISelOption =3D=3D cl::BOU_TRUE ||
-      (OptLevel =3D=3D CodeGenOpt::None && EnableFastISelOption !=3D cl::B=
OU_FALSE))
-    EnableFastISel =3D true;
-
-  // Ask the target for an isel.
-  if (addInstSelector(PM, OptLevel))
-    return true;
-
-  // Print the instruction selected machine code...
-  printAndVerify(PM, "After Instruction Selection");
-
-  // Expand pseudo-instructions emitted by ISel.
-  PM.add(createExpandISelPseudosPass());
-
-  // Pre-ra tail duplication.
-  if (OptLevel !=3D CodeGenOpt::None && !DisableEarlyTailDup) {
-    PM.add(createTailDuplicatePass(true));
-    printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
-  }
-
-  // Optimize PHIs before DCE: removing dead PHI cycles may make more
-  // instructions dead.
-  if (OptLevel !=3D CodeGenOpt::None)
-    PM.add(createOptimizePHIsPass());
-
-  // If the target requests it, assign local variables to stack slots rela=
tive
-  // to one another and simplify frame index references where possible.
-  PM.add(createLocalStackSlotAllocationPass());
-
-  if (OptLevel !=3D CodeGenOpt::None) {
-    // With optimization, dead code should already be eliminated. However
-    // there is one known exception: lowered code for arguments that are o=
nly
-    // used by tail calls, where the tail calls reuse the incoming stack
-    // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
-    if (!DisableMachineDCE)
-      PM.add(createDeadMachineInstructionElimPass());
-    printAndVerify(PM, "After codegen DCE pass");
-
-    if (!DisableMachineLICM)
-      PM.add(createMachineLICMPass());
-    if (!DisableMachineCSE)
-      PM.add(createMachineCSEPass());
-    if (!DisableMachineSink)
-      PM.add(createMachineSinkingPass());
-    printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
-
-    PM.add(createPeepholeOptimizerPass());
-    printAndVerify(PM, "After codegen peephole optimization pass");
-  }
-
-  // Run pre-ra passes.
-  if (addPreRegAlloc(PM, OptLevel))
-    printAndVerify(PM, "After PreRegAlloc passes");
-
-  // Perform register allocation.
-  PM.add(createRegisterAllocator(OptLevel));
-  printAndVerify(PM, "After Register Allocation");
-
-  // Perform stack slot coloring and post-ra machine LICM.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    // FIXME: Re-enable coloring with register when it's capable of adding
-    // kill markers.
-    if (!DisableSSC)
-      PM.add(createStackSlotColoringPass(false));
-
-    // Run post-ra machine LICM to hoist reloads / remats.
-    if (!DisablePostRAMachineLICM)
-      PM.add(createMachineLICMPass(false));
-
-    printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
-  }
-
-  // Run post-ra passes.
-  if (addPostRegAlloc(PM, OptLevel))
-    printAndVerify(PM, "After PostRegAlloc passes");
-
-  PM.add(createExpandPostRAPseudosPass());
-  printAndVerify(PM, "After ExpandPostRAPseudos");
-
-  // Insert prolog/epilog code.  Eliminate abstract frame index references=
...
-  PM.add(createPrologEpilogCodeInserter());
-  printAndVerify(PM, "After PrologEpilogCodeInserter");
-
-  // Run pre-sched2 passes.
-  if (addPreSched2(PM, OptLevel))
-    printAndVerify(PM, "After PreSched2 passes");
-
-  // Second pass scheduler.
-  if (OptLevel !=3D CodeGenOpt::None && !DisablePostRA) {
-    PM.add(createPostRAScheduler(OptLevel));
-    printAndVerify(PM, "After PostRAScheduler");
-  }
-
-  // Branch folding must be run after regalloc and prolog/epilog insertion.
-  if (OptLevel !=3D CodeGenOpt::None && !DisableBranchFold) {
-    PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
-    printNoVerify(PM, "After BranchFolding");
-  }
-
-  // Tail duplication.
-  if (OptLevel !=3D CodeGenOpt::None && !DisableTailDuplicate) {
-    PM.add(createTailDuplicatePass(false));
-    printNoVerify(PM, "After TailDuplicate");
-  }
-
-  PM.add(createGCMachineCodeAnalysisPass());
-
-  if (PrintGCInfo)
-    PM.add(createGCInfoPrinter(dbgs()));
-
-  if (OptLevel !=3D CodeGenOpt::None && !DisableCodePlace) {
-    PM.add(createCodePlacementOptPass());
-    printNoVerify(PM, "After CodePlacementOpt");
-  }
-
-  if (addPreEmitPass(PM, OptLevel))
-    printNoVerify(PM, "After PreEmit passes");
-
-  return false;
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LatencyP=
riorityQueue.cpp
--- a/head/contrib/llvm/lib/CodeGen/LatencyPriorityQueue.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LatencyPriorityQueue.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -46,7 +46,7 @@
=20
   // Finally, just to provide a stable ordering, use the node number as a
   // deciding factor.
-  return LHSNum < RHSNum;
+  return RHSNum < LHSNum;
 }
=20
=20
@@ -84,11 +84,11 @@
 }
=20
=20
-// ScheduledNode - As nodes are scheduled, we look to see if there are any
+// scheduledNode - As nodes are scheduled, we look to see if there are any
 // successor nodes that have a single unscheduled predecessor.  If so, that
 // single predecessor has a higher priority, since scheduling it will make
 // the node available.
-void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
+void LatencyPriorityQueue::scheduledNode(SUnit *SU) {
   for (SUnit::const_succ_iterator I =3D SU->Succs.begin(), E =3D SU->Succs=
.end();
        I !=3D E; ++I) {
     AdjustPriorityOfUnscheduledPreds(I->getSUnit());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LexicalS=
copes.cpp
--- a/head/contrib/llvm/lib/CodeGen/LexicalScopes.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LexicalScopes.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -311,6 +311,8 @@
   return Result;
 }
=20
+void LexicalScope::anchor() { }
+
 /// dump - Print data structures.
 void LexicalScope::dump() const {
 #ifndef NDEBUG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveDebu=
gVariables.cpp
--- a/head/contrib/llvm/lib/CodeGen/LiveDebugVariables.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveDebugVariables.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -226,7 +226,7 @@
                  LiveInterval *LI, const VNInfo *VNI,
                  SmallVectorImpl<SlotIndex> *Kills,
                  LiveIntervals &LIS, MachineDominatorTree &MDT,
-		 UserValueScopes &UVS);
+                 UserValueScopes &UVS);
=20
   /// addDefsFromCopies - The value in LI/LocNo may be copies to other
   /// registers. Determine if any of the copies are available at the kill
@@ -468,7 +468,7 @@
       // DBG_VALUE has no slot index, use the previous instruction instead.
       SlotIndex Idx =3D MBBI =3D=3D MBB->begin() ?
         LIS->getMBBStartIdx(MBB) :
-        LIS->getInstructionIndex(llvm::prior(MBBI)).getDefIndex();
+        LIS->getInstructionIndex(llvm::prior(MBBI)).getRegSlot();
       // Handle consecutive DBG_VALUE instructions with the same slot inde=
x.
       do {
         if (handleDebugValue(MBBI, Idx)) {
@@ -486,7 +486,7 @@
                           LiveInterval *LI, const VNInfo *VNI,
                           SmallVectorImpl<SlotIndex> *Kills,
                           LiveIntervals &LIS, MachineDominatorTree &MDT,
-			  UserValueScopes &UVS) {
+                          UserValueScopes &UVS) {
   SmallVector<SlotIndex, 16> Todo;
   Todo.push_back(Idx);
   do {
@@ -575,15 +575,15 @@
     // Is LocNo extended to reach this copy? If not, another def may be bl=
ocking
     // it, or we are looking at a wrong value of LI.
     SlotIndex Idx =3D LIS.getInstructionIndex(MI);
-    LocMap::iterator I =3D locInts.find(Idx.getUseIndex());
+    LocMap::iterator I =3D locInts.find(Idx.getRegSlot(true));
     if (!I.valid() || I.value() !=3D LocNo)
       continue;
=20
     if (!LIS.hasInterval(DstReg))
       continue;
     LiveInterval *DstLI =3D &LIS.getInterval(DstReg);
-    const VNInfo *DstVNI =3D DstLI->getVNInfoAt(Idx.getDefIndex());
-    assert(DstVNI && DstVNI->def =3D=3D Idx.getDefIndex() && "Bad copy val=
ue");
+    const VNInfo *DstVNI =3D DstLI->getVNInfoAt(Idx.getRegSlot());
+    assert(DstVNI && DstVNI->def =3D=3D Idx.getRegSlot() && "Bad copy valu=
e");
     CopyValues.push_back(std::make_pair(DstLI, DstVNI));
   }
=20
@@ -620,7 +620,7 @@
 UserValue::computeIntervals(MachineRegisterInfo &MRI,
                             LiveIntervals &LIS,
                             MachineDominatorTree &MDT,
-			    UserValueScopes &UVS) {
+                            UserValueScopes &UVS) {
   SmallVector<std::pair<SlotIndex, unsigned>, 16> Defs;
=20
   // Collect all defs to be extended (Skipping undefs).
@@ -841,7 +841,7 @@
 UserValue::splitRegister(unsigned OldReg, ArrayRef<LiveInterval*> NewRegs)=
 {
   bool DidChange =3D false;
   // Split locations referring to OldReg. Iterate backwards so splitLocati=
on can
-  // safely erase unuused locations.
+  // safely erase unused locations.
   for (unsigned i =3D locations.size(); i ; --i) {
     unsigned LocNo =3D i-1;
     const MachineOperand *Loc =3D &locations[LocNo];
@@ -889,8 +889,7 @@
       // index is no longer available. That means the user value is in a
       // non-existent sub-register, and %noreg is exactly what we want.
       Loc.substPhysReg(VRM.getPhys(VirtReg), TRI);
-    } else if (VRM.getStackSlot(VirtReg) !=3D VirtRegMap::NO_STACK_SLOT &&
-               VRM.isSpillSlotUsed(VRM.getStackSlot(VirtReg))) {
+    } else if (VRM.getStackSlot(VirtReg) !=3D VirtRegMap::NO_STACK_SLOT) {
       // FIXME: Translate SubIdx to a stackslot offset.
       Loc =3D MachineOperand::CreateFI(VRM.getStackSlot(VirtReg));
     } else {
@@ -921,8 +920,8 @@
   }
=20
   // Don't insert anything after the first terminator, though.
-  return MI->getDesc().isTerminator() ? MBB->getFirstTerminator() :
-                                    llvm::next(MachineBasicBlock::iterator=
(MI));
+  return MI->isTerminator() ? MBB->getFirstTerminator() :
+                              llvm::next(MachineBasicBlock::iterator(MI));
 }
=20
 DebugLoc UserValue::findDebugLoc() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveInte=
rval.cpp
--- a/head/contrib/llvm/lib/CodeGen/LiveInterval.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveInterval.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -381,37 +381,40 @@
   for (unsigned i =3D 0; i !=3D NumVals; ++i) {
     unsigned LHSValID =3D LHSValNoAssignments[i];
     if (i !=3D LHSValID ||
-        (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] !=3D getValNumInfo(i)))
+        (NewVNInfo[LHSValID] && NewVNInfo[LHSValID] !=3D getValNumInfo(i))=
) {
       MustMapCurValNos =3D true;
+      break;
+    }
   }
=20
   // If we have to apply a mapping to our base interval assignment, rewrit=
e it
   // now.
   if (MustMapCurValNos) {
     // Map the first live range.
+
     iterator OutIt =3D begin();
     OutIt->valno =3D NewVNInfo[LHSValNoAssignments[OutIt->valno->id]];
-    ++OutIt;
-    for (iterator I =3D OutIt, E =3D end(); I !=3D E; ++I) {
-      OutIt->valno =3D NewVNInfo[LHSValNoAssignments[I->valno->id]];
+    for (iterator I =3D next(OutIt), E =3D end(); I !=3D E; ++I) {
+      VNInfo* nextValNo =3D NewVNInfo[LHSValNoAssignments[I->valno->id]];
+      assert(nextValNo !=3D 0 && "Huh?");
=20
       // If this live range has the same value # as its immediate predeces=
sor,
       // and if they are neighbors, remove one LiveRange.  This happens wh=
en we
-      // have [0,3:0)[4,7:1) and map 0/1 onto the same value #.
-      if (OutIt->valno =3D=3D (OutIt-1)->valno && (OutIt-1)->end =3D=3D Ou=
tIt->start) {
-        (OutIt-1)->end =3D OutIt->end;
+      // have [0,4:0)[4,7:1) and map 0/1 onto the same value #.
+      if (OutIt->valno =3D=3D nextValNo && OutIt->end =3D=3D I->start) {
+        OutIt->end =3D I->end;
       } else {
-        if (I !=3D OutIt) {
+        // Didn't merge. Move OutIt to the next interval,
+        ++OutIt;
+        OutIt->valno =3D nextValNo;
+        if (OutIt !=3D I) {
           OutIt->start =3D I->start;
           OutIt->end =3D I->end;
         }
-
-        // Didn't merge, on to the next one.
-        ++OutIt;
       }
     }
-
     // If we merge some live ranges, chop off the end.
+    ++OutIt;
     ranges.erase(OutIt, end());
   }
=20
@@ -639,8 +642,6 @@
           OS << "-phidef";
         if (vni->hasPHIKill())
           OS << "-phikill";
-        if (vni->hasRedefByEC())
-          OS << "-ec";
       }
     }
   }
@@ -680,15 +681,14 @@
       // Connect to values live out of predecessors.
       for (MachineBasicBlock::const_pred_iterator PI =3D MBB->pred_begin(),
            PE =3D MBB->pred_end(); PI !=3D PE; ++PI)
-        if (const VNInfo *PVNI =3D
-              LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot()))
+        if (const VNInfo *PVNI =3D LI->getVNInfoBefore(LIS.getMBBEndIdx(*P=
I)))
           EqClass.join(VNI->id, PVNI->id);
     } else {
       // Normal value defined by an instruction. Check for two-addr redef.
       // FIXME: This could be coincidental. Should we really check for a t=
ied
       // operand constraint?
       // Note that VNI->def may be a use slot for an early clobber def.
-      if (const VNInfo *UVNI =3D LI->getVNInfoAt(VNI->def.getPrevSlot()))
+      if (const VNInfo *UVNI =3D LI->getVNInfoBefore(VNI->def))
         EqClass.join(VNI->id, UVNI->id);
     }
   }
@@ -716,7 +716,7 @@
       continue;
     // DBG_VALUE instructions should have been eliminated earlier.
     SlotIndex Idx =3D LIS.getInstructionIndex(MI);
-    Idx =3D MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
+    Idx =3D Idx.getRegSlot(MO.isUse());
     const VNInfo *VNI =3D LI.getVNInfoAt(Idx);
     assert(VNI && "Interval not live at use.");
     MO.setReg(LIV[getEqClass(VNI)]->reg);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveInte=
rvalAnalysis.cpp
--- a/head/contrib/llvm/lib/CodeGen/LiveIntervalAnalysis.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveIntervalAnalysis.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,31 +15,22 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#define DEBUG_TYPE "liveintervals"
+#define DEBUG_TYPE "regalloc"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
-#include "VirtRegMap.h"
 #include "llvm/Value.h"
 #include "llvm/Analysis/AliasAnalysis.h"
-#include "llvm/CodeGen/CalcSpillWeights.h"
 #include "llvm/CodeGen/LiveVariables.h"
-#include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstr.h"
-#include "llvm/CodeGen/MachineInstrBuilder.h"
-#include "llvm/CodeGen/MachineLoopInfo.h"
-#include "llvm/CodeGen/MachineMemOperand.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/Passes.h"
-#include "llvm/CodeGen/ProcessImplicitDefs.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetMachine.h"
-#include "llvm/Target/TargetOptions.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/DepthFirstIterator.h"
-#include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/STLExtras.h"
 #include <algorithm>
@@ -52,19 +43,14 @@
                                   cl::init(false), cl::Hidden);
=20
 STATISTIC(numIntervals , "Number of original intervals");
-STATISTIC(numFolds     , "Number of loads/stores folded into instructions"=
);
-STATISTIC(numSplits    , "Number of intervals split");
=20
 char LiveIntervals::ID =3D 0;
 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
                 "Live Interval Analysis", false, false)
+INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
-INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
-INITIALIZE_PASS_DEPENDENCY(PHIElimination)
-INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
-INITIALIZE_PASS_DEPENDENCY(ProcessImplicitDefs)
+INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
-INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
 INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
                 "Live Interval Analysis", false, false)
=20
@@ -74,18 +60,8 @@
   AU.addPreserved<AliasAnalysis>();
   AU.addRequired<LiveVariables>();
   AU.addPreserved<LiveVariables>();
-  AU.addRequired<MachineLoopInfo>();
-  AU.addPreserved<MachineLoopInfo>();
+  AU.addPreservedID(MachineLoopInfoID);
   AU.addPreservedID(MachineDominatorsID);
-
-  if (!StrongPHIElim) {
-    AU.addPreservedID(PHIEliminationID);
-    AU.addRequiredID(PHIEliminationID);
-  }
-
-  AU.addRequiredID(TwoAddressInstructionPassID);
-  AU.addPreserved<ProcessImplicitDefs>();
-  AU.addRequired<ProcessImplicitDefs>();
   AU.addPreserved<SlotIndexes>();
   AU.addRequiredTransitive<SlotIndexes>();
   MachineFunctionPass::getAnalysisUsage(AU);
@@ -98,14 +74,12 @@
     delete I->second;
=20
   r2iMap_.clear();
+  RegMaskSlots.clear();
+  RegMaskBits.clear();
+  RegMaskBlocks.clear();
=20
   // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
   VNInfoAllocator.Reset();
-  while (!CloneMIs.empty()) {
-    MachineInstr *MI =3D CloneMIs.back();
-    CloneMIs.pop_back();
-    mf_->DeleteMachineInstr(MI);
-  }
 }
=20
 /// runOnMachineFunction - Register allocate the whole function
@@ -120,6 +94,7 @@
   lv_ =3D &getAnalysis<LiveVariables>();
   indexes_ =3D &getAnalysis<SlotIndexes>();
   allocatableRegs_ =3D tri_->getAllocatableSet(fn);
+  reservedRegs_ =3D tri_->getReservedRegs(fn);
=20
   computeIntervals();
=20
@@ -132,10 +107,21 @@
 /// print - Implement the dump method.
 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
   OS << "********** INTERVALS **********\n";
-  for (const_iterator I =3D begin(), E =3D end(); I !=3D E; ++I) {
-    I->second->print(OS, tri_);
-    OS << "\n";
-  }
+
+  // Dump the physregs.
+  for (unsigned Reg =3D 1, RegE =3D tri_->getNumRegs(); Reg !=3D RegE; ++R=
eg)
+    if (const LiveInterval *LI =3D r2iMap_.lookup(Reg)) {
+      LI->print(OS, tri_);
+      OS << '\n';
+    }
+
+  // Dump the virtregs.
+  for (unsigned Reg =3D 0, RegE =3D mri_->getNumVirtRegs(); Reg !=3D RegE;=
 ++Reg)
+    if (const LiveInterval *LI =3D
+        r2iMap_.lookup(TargetRegisterInfo::index2VirtReg(Reg))) {
+      LI->print(OS, tri_);
+      OS << '\n';
+    }
=20
   printInstrs(OS);
 }
@@ -149,103 +135,6 @@
   printInstrs(dbgs());
 }
=20
-bool LiveIntervals::conflictsWithPhysReg(const LiveInterval &li,
-                                         VirtRegMap &vrm, unsigned reg) {
-  // We don't handle fancy stuff crossing basic block boundaries
-  if (li.ranges.size() !=3D 1)
-    return true;
-  const LiveRange &range =3D li.ranges.front();
-  SlotIndex idx =3D range.start.getBaseIndex();
-  SlotIndex end =3D range.end.getPrevSlot().getBaseIndex().getNextIndex();
-
-  // Skip deleted instructions
-  MachineInstr *firstMI =3D getInstructionFromIndex(idx);
-  while (!firstMI && idx !=3D end) {
-    idx =3D idx.getNextIndex();
-    firstMI =3D getInstructionFromIndex(idx);
-  }
-  if (!firstMI)
-    return false;
-
-  // Find last instruction in range
-  SlotIndex lastIdx =3D end.getPrevIndex();
-  MachineInstr *lastMI =3D getInstructionFromIndex(lastIdx);
-  while (!lastMI && lastIdx !=3D idx) {
-    lastIdx =3D lastIdx.getPrevIndex();
-    lastMI =3D getInstructionFromIndex(lastIdx);
-  }
-  if (!lastMI)
-    return false;
-
-  // Range cannot cross basic block boundaries or terminators
-  MachineBasicBlock *MBB =3D firstMI->getParent();
-  if (MBB !=3D lastMI->getParent() || lastMI->getDesc().isTerminator())
-    return true;
-
-  MachineBasicBlock::const_iterator E =3D lastMI;
-  ++E;
-  for (MachineBasicBlock::const_iterator I =3D firstMI; I !=3D E; ++I) {
-    const MachineInstr &MI =3D *I;
-
-    // Allow copies to and from li.reg
-    if (MI.isCopy())
-      if (MI.getOperand(0).getReg() =3D=3D li.reg ||
-          MI.getOperand(1).getReg() =3D=3D li.reg)
-        continue;
-
-    // Check for operands using reg
-    for (unsigned i =3D 0, e =3D MI.getNumOperands(); i !=3D e;  ++i) {
-      const MachineOperand& mop =3D MI.getOperand(i);
-      if (!mop.isReg())
-        continue;
-      unsigned PhysReg =3D mop.getReg();
-      if (PhysReg =3D=3D 0 || PhysReg =3D=3D li.reg)
-        continue;
-      if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
-        if (!vrm.hasPhys(PhysReg))
-          continue;
-        PhysReg =3D vrm.getPhys(PhysReg);
-      }
-      if (PhysReg && tri_->regsOverlap(PhysReg, reg))
-        return true;
-    }
-  }
-
-  // No conflicts found.
-  return false;
-}
-
-bool LiveIntervals::conflictsWithAliasRef(LiveInterval &li, unsigned Reg,
-                                  SmallPtrSet<MachineInstr*,32> &JoinedCop=
ies) {
-  for (LiveInterval::Ranges::const_iterator
-         I =3D li.ranges.begin(), E =3D li.ranges.end(); I !=3D E; ++I) {
-    for (SlotIndex index =3D I->start.getBaseIndex(),
-           end =3D I->end.getPrevSlot().getBaseIndex().getNextIndex();
-           index !=3D end;
-           index =3D index.getNextIndex()) {
-      MachineInstr *MI =3D getInstructionFromIndex(index);
-      if (!MI)
-        continue;               // skip deleted instructions
-
-      if (JoinedCopies.count(MI))
-        continue;
-      for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
-        MachineOperand& MO =3D MI->getOperand(i);
-        if (!MO.isReg())
-          continue;
-        unsigned PhysReg =3D MO.getReg();
-        if (PhysReg =3D=3D 0 || PhysReg =3D=3D Reg ||
-            TargetRegisterInfo::isVirtualRegister(PhysReg))
-          continue;
-        if (tri_->regsOverlap(Reg, PhysReg))
-          return true;
-      }
-    }
-  }
-
-  return false;
-}
-
 static
 bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
   unsigned Reg =3D MI.getOperand(MOIdx).getReg();
@@ -271,9 +160,9 @@
   if (!MO.getSubReg() || MO.isEarlyClobber())
     return false;
=20
-  SlotIndex RedefIndex =3D MIIdx.getDefIndex();
+  SlotIndex RedefIndex =3D MIIdx.getRegSlot();
   const LiveRange *OldLR =3D
-    interval.getLiveRangeContaining(RedefIndex.getUseIndex());
+    interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
   MachineInstr *DefMI =3D getInstructionFromIndex(OldLR->valno->def);
   if (DefMI !=3D 0) {
     return DefMI->findRegisterDefOperandIdx(interval.reg) !=3D -1;
@@ -296,34 +185,13 @@
   LiveVariables::VarInfo& vi =3D lv_->getVarInfo(interval.reg);
   if (interval.empty()) {
     // Get the Idx of the defining instructions.
-    SlotIndex defIndex =3D MIIdx.getDefIndex();
-    // Earlyclobbers move back one, so that they overlap the live range
-    // of inputs.
-    if (MO.isEarlyClobber())
-      defIndex =3D MIIdx.getUseIndex();
+    SlotIndex defIndex =3D MIIdx.getRegSlot(MO.isEarlyClobber());
=20
-    // Make sure the first definition is not a partial redefinition. Add an
-    // <imp-def> of the full register.
-    // FIXME: LiveIntervals shouldn't modify the code like this.  Whoever
-    // created the machine instruction should annotate it with <undef> fla=
gs
-    // as needed.  Then we can simply assert here.  The REG_SEQUENCE lower=
ing
-    // is the main suspect.
-    if (MO.getSubReg()) {
-      mi->addRegisterDefined(interval.reg);
-      // Mark all defs of interval.reg on this instruction as reading <und=
ef>.
-      for (unsigned i =3D MOIdx, e =3D mi->getNumOperands(); i !=3D e; ++i=
) {
-        MachineOperand &MO2 =3D mi->getOperand(i);
-        if (MO2.isReg() && MO2.getReg() =3D=3D interval.reg && MO2.getSubR=
eg())
-          MO2.setIsUndef();
-      }
-    }
+    // Make sure the first definition is not a partial redefinition.
+    assert(!MO.readsReg() && "First def cannot also read virtual register "
+           "missing <undef> flag?");
=20
-    MachineInstr *CopyMI =3D NULL;
-    if (mi->isCopyLike()) {
-      CopyMI =3D mi;
-    }
-
-    VNInfo *ValNo =3D interval.getNextValue(defIndex, CopyMI, VNInfoAlloca=
tor);
+    VNInfo *ValNo =3D interval.getNextValue(defIndex, VNInfoAllocator);
     assert(ValNo->id =3D=3D 0 && "First value in interval is not 0?");
=20
     // Loop over all of the blocks that the vreg is defined in.  There are
@@ -334,9 +202,9 @@
       // FIXME: what about dead vars?
       SlotIndex killIdx;
       if (vi.Kills[0] !=3D mi)
-        killIdx =3D getInstructionIndex(vi.Kills[0]).getDefIndex();
+        killIdx =3D getInstructionIndex(vi.Kills[0]).getRegSlot();
       else
-        killIdx =3D defIndex.getStoreIndex();
+        killIdx =3D defIndex.getDeadSlot();
=20
       // If the kill happens after the definition, we have an intra-block
       // live range.
@@ -384,14 +252,14 @@
     for (unsigned i =3D 0, e =3D vi.Kills.size(); i !=3D e; ++i) {
       MachineInstr *Kill =3D vi.Kills[i];
       SlotIndex Start =3D getMBBStartIdx(Kill->getParent());
-      SlotIndex killIdx =3D getInstructionIndex(Kill).getDefIndex();
+      SlotIndex killIdx =3D getInstructionIndex(Kill).getRegSlot();
=20
       // Create interval with one of a NEW value number.  Note that this v=
alue
       // number isn't actually defined by an instruction, weird huh? :)
       if (PHIJoin) {
         assert(getInstructionFromIndex(Start) =3D=3D 0 &&
                "PHI def index points at actual instruction.");
-        ValNo =3D interval.getNextValue(Start, 0, VNInfoAllocator);
+        ValNo =3D interval.getNextValue(Start, VNInfoAllocator);
         ValNo->setIsPHIDef(true);
       }
       LiveRange LR(Start, killIdx, ValNo);
@@ -422,14 +290,12 @@
       // are actually two values in the live interval.  Because of this we
       // need to take the LiveRegion that defines this register and split =
it
       // into two values.
-      SlotIndex RedefIndex =3D MIIdx.getDefIndex();
-      if (MO.isEarlyClobber())
-        RedefIndex =3D MIIdx.getUseIndex();
+      SlotIndex RedefIndex =3D MIIdx.getRegSlot(MO.isEarlyClobber());
=20
       const LiveRange *OldLR =3D
-        interval.getLiveRangeContaining(RedefIndex.getUseIndex());
+        interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
       VNInfo *OldValNo =3D OldLR->valno;
-      SlotIndex DefIndex =3D OldValNo->def.getDefIndex();
+      SlotIndex DefIndex =3D OldValNo->def.getRegSlot();
=20
       // Delete the previous value, which should be short and continuous,
       // because the 2-addr copy must be in the same MBB as the redef.
@@ -440,12 +306,7 @@
       VNInfo *ValNo =3D interval.createValueCopy(OldValNo, VNInfoAllocator=
);
=20
       // Value#0 is now defined by the 2-addr instruction.
-      OldValNo->def  =3D RedefIndex;
-      OldValNo->setCopy(0);
-
-      // A re-def may be a copy. e.g. %reg1030:6<def> =3D VMOVD %reg1026, =
...
-      if (PartReDef && mi->isCopyLike())
-        OldValNo->setCopy(&*mi);
+      OldValNo->def =3D RedefIndex;
=20
       // Add the new live interval which replaces the range for the input =
copy.
       LiveRange LR(DefIndex, RedefIndex, ValNo);
@@ -455,7 +316,7 @@
       // If this redefinition is dead, we need to add a dummy unit live
       // range covering the def slot.
       if (MO.isDead())
-        interval.addRange(LiveRange(RedefIndex, RedefIndex.getStoreIndex(),
+        interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
                                     OldValNo));
=20
       DEBUG({
@@ -467,15 +328,11 @@
       // live until the end of the block.  We've already taken care of the
       // rest of the live range.
=20
-      SlotIndex defIndex =3D MIIdx.getDefIndex();
+      SlotIndex defIndex =3D MIIdx.getRegSlot();
       if (MO.isEarlyClobber())
-        defIndex =3D MIIdx.getUseIndex();
+        defIndex =3D MIIdx.getRegSlot(true);
=20
-      VNInfo *ValNo;
-      MachineInstr *CopyMI =3D NULL;
-      if (mi->isCopyLike())
-        CopyMI =3D mi;
-      ValNo =3D interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
+      VNInfo *ValNo =3D interval.getNextValue(defIndex, VNInfoAllocator);
=20
       SlotIndex killIndex =3D getMBBEndIdx(mbb);
       LiveRange LR(defIndex, killIndex, ValNo);
@@ -490,21 +347,26 @@
   DEBUG(dbgs() << '\n');
 }
=20
+static bool isRegLiveIntoSuccessor(const MachineBasicBlock *MBB, unsigned =
Reg) {
+  for (MachineBasicBlock::const_succ_iterator SI =3D MBB->succ_begin(),
+                                              SE =3D MBB->succ_end();
+       SI !=3D SE; ++SI) {
+    const MachineBasicBlock* succ =3D *SI;
+    if (succ->isLiveIn(Reg))
+      return true;
+  }
+  return false;
+}
+
 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
                                               MachineBasicBlock::iterator =
mi,
                                               SlotIndex MIIdx,
                                               MachineOperand& MO,
-                                              LiveInterval &interval,
-                                              MachineInstr *CopyMI) {
-  // A physical register cannot be live across basic block, so its
-  // lifetime must end somewhere in its defining basic block.
+                                              LiveInterval &interval) {
   DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, tri_));
=20
   SlotIndex baseIndex =3D MIIdx;
-  SlotIndex start =3D baseIndex.getDefIndex();
-  // Earlyclobbers move back one.
-  if (MO.isEarlyClobber())
-    start =3D MIIdx.getUseIndex();
+  SlotIndex start =3D baseIndex.getRegSlot(MO.isEarlyClobber());
   SlotIndex end =3D start;
=20
   // If it is not used after definition, it is considered dead at
@@ -514,7 +376,7 @@
   // advance below compensates.
   if (MO.isDead()) {
     DEBUG(dbgs() << " dead");
-    end =3D start.getStoreIndex();
+    end =3D start.getDeadSlot();
     goto exit;
   }
=20
@@ -531,21 +393,21 @@
=20
     if (mi->killsRegister(interval.reg, tri_)) {
       DEBUG(dbgs() << " killed");
-      end =3D baseIndex.getDefIndex();
+      end =3D baseIndex.getRegSlot();
       goto exit;
     } else {
       int DefIdx =3D mi->findRegisterDefOperandIdx(interval.reg,false,fals=
e,tri_);
       if (DefIdx !=3D -1) {
         if (mi->isRegTiedToUseOperand(DefIdx)) {
           // Two-address instruction.
-          end =3D baseIndex.getDefIndex();
+          end =3D baseIndex.getRegSlot(mi->getOperand(DefIdx).isEarlyClobb=
er());
         } else {
           // Another instruction redefines the register before it is ever =
read.
           // Then the register is essentially dead at the instruction that
           // defines it. Hence its interval is:
           // [defSlot(def), defSlot(def)+1)
           DEBUG(dbgs() << " dead");
-          end =3D start.getStoreIndex();
+          end =3D start.getDeadSlot();
         }
         goto exit;
       }
@@ -554,12 +416,19 @@
     baseIndex =3D baseIndex.getNextIndex();
   }
=20
-  // The only case we should have a dead physreg here without a killing or
-  // instruction where we know it's dead is if it is live-in to the functi=
on
-  // and never used. Another possible case is the implicit use of the
-  // physical register has been deleted by two-address pass.
-  end =3D start.getStoreIndex();
+  // If we get here the register *should* be live out.
+  assert(!isAllocatable(interval.reg) && "Physregs shouldn't be live out!"=
);
=20
+  // FIXME: We need saner rules for reserved regs.
+  if (isReserved(interval.reg)) {
+    end =3D start.getDeadSlot();
+  } else {
+    // Unreserved, unallocable registers like EFLAGS can be live across ba=
sic
+    // block boundaries.
+    assert(isRegLiveIntoSuccessor(MBB, interval.reg) &&
+           "Unreserved reg not live-out?");
+    end =3D getMBBEndIdx(MBB);
+  }
 exit:
   assert(start < end && "did not find end of interval?");
=20
@@ -567,9 +436,7 @@
   VNInfo *ValNo =3D interval.getVNInfoAt(start);
   bool Extend =3D ValNo !=3D 0;
   if (!Extend)
-    ValNo =3D interval.getNextValue(start, CopyMI, VNInfoAllocator);
-  if (Extend && MO.isEarlyClobber())
-    ValNo->setHasRedefByEC(true);
+    ValNo =3D interval.getNextValue(start, VNInfoAllocator);
   LiveRange LR(start, end, ValNo);
   interval.addRange(LR);
   DEBUG(dbgs() << " +" << LR << '\n');
@@ -583,18 +450,20 @@
   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
     handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
                              getOrCreateInterval(MO.getReg()));
-  else {
-    MachineInstr *CopyMI =3D NULL;
-    if (MI->isCopyLike())
-      CopyMI =3D MI;
+  else
     handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
-                              getOrCreateInterval(MO.getReg()), CopyMI);
-  }
+                              getOrCreateInterval(MO.getReg()));
 }
=20
 void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
                                          SlotIndex MIIdx,
-                                         LiveInterval &interval, bool isAl=
ias) {
+                                         LiveInterval &interval) {
+  assert(TargetRegisterInfo::isPhysicalRegister(interval.reg) &&
+         "Only physical registers can be live in.");
+  assert((!isAllocatable(interval.reg) || MBB->getParent()->begin() ||
+          MBB->isLandingPad()) &&
+          "Allocatable live-ins only valid for entry blocks and landing pa=
ds.");
+
   DEBUG(dbgs() << "\t\tlivein register: " << PrintReg(interval.reg, tri_));
=20
   // Look for kills, if it reaches a def before it's killed, then it shoul=
dn't
@@ -621,16 +490,16 @@
   while (mi !=3D E) {
     if (mi->killsRegister(interval.reg, tri_)) {
       DEBUG(dbgs() << " killed");
-      end =3D baseIndex.getDefIndex();
+      end =3D baseIndex.getRegSlot();
       SeenDefUse =3D true;
       break;
-    } else if (mi->definesRegister(interval.reg, tri_)) {
+    } else if (mi->modifiesRegister(interval.reg, tri_)) {
       // Another instruction redefines the register before it is ever read.
       // Then the register is essentially dead at the instruction that def=
ines
       // it. Hence its interval is:
       // [defSlot(def), defSlot(def)+1)
       DEBUG(dbgs() << " dead");
-      end =3D start.getStoreIndex();
+      end =3D start.getDeadSlot();
       SeenDefUse =3D true;
       break;
     }
@@ -644,10 +513,16 @@
=20
   // Live-in register might not be used at all.
   if (!SeenDefUse) {
-    if (isAlias) {
+    if (isAllocatable(interval.reg) ||
+        !isRegLiveIntoSuccessor(MBB, interval.reg)) {
+      // Allocatable registers are never live through.
+      // Non-allocatable registers that aren't live into any successors al=
so
+      // aren't live through.
       DEBUG(dbgs() << " dead");
-      end =3D MIIdx.getStoreIndex();
+      return;
     } else {
+      // If we get here the register is non-allocatable and live into some
+      // successor. We'll conservatively assume it's live-through.
       DEBUG(dbgs() << " live through");
       end =3D getMBBEndIdx(MBB);
     }
@@ -656,8 +531,7 @@
   SlotIndex defIdx =3D getMBBStartIdx(MBB);
   assert(getInstructionFromIndex(defIdx) =3D=3D 0 &&
          "PHI def index points at actual instruction.");
-  VNInfo *vni =3D
-    interval.getNextValue(defIdx, 0, VNInfoAllocator);
+  VNInfo *vni =3D interval.getNextValue(defIdx, VNInfoAllocator);
   vni->setIsPHIDef(true);
   LiveRange LR(start, end, vni);
=20
@@ -674,10 +548,14 @@
                << "********** Function: "
                << ((Value*)mf_->getFunction())->getName() << '\n');
=20
+  RegMaskBlocks.resize(mf_->getNumBlockIDs());
+
   SmallVector<unsigned, 8> UndefUses;
   for (MachineFunction::iterator MBBI =3D mf_->begin(), E =3D mf_->end();
        MBBI !=3D E; ++MBBI) {
     MachineBasicBlock *MBB =3D MBBI;
+    RegMaskBlocks[MBB->getNumber()].first =3D RegMaskSlots.size();
+
     if (MBB->empty())
       continue;
=20
@@ -690,11 +568,6 @@
     for (MachineBasicBlock::livein_iterator LI =3D MBB->livein_begin(),
            LE =3D MBB->livein_end(); LI !=3D LE; ++LI) {
       handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
-      // Multiple live-ins can alias the same register.
-      for (const unsigned* AS =3D tri_->getSubRegisters(*LI); *AS; ++AS)
-        if (!hasInterval(*AS))
-          handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
-                               true);
     }
=20
     // Skip over empty initial indices.
@@ -706,10 +579,20 @@
       DEBUG(dbgs() << MIIndex << "\t" << *MI);
       if (MI->isDebugValue())
         continue;
+      assert(indexes_->getInstructionFromIndex(MIIndex) =3D=3D MI &&
+             "Lost SlotIndex synchronization");
=20
       // Handle defs.
       for (int i =3D MI->getNumOperands() - 1; i >=3D 0; --i) {
         MachineOperand &MO =3D MI->getOperand(i);
+
+        // Collect register masks.
+        if (MO.isRegMask()) {
+          RegMaskSlots.push_back(MIIndex.getRegSlot());
+          RegMaskBits.push_back(MO.getRegMask());
+          continue;
+        }
+
         if (!MO.isReg() || !MO.getReg())
           continue;
=20
@@ -723,6 +606,10 @@
       // Move to the next instr slot.
       MIIndex =3D indexes_->getNextNonNullIndex(MIIndex);
     }
+
+    // Compute the number of register mask instructions in this block.
+    std::pair<unsigned, unsigned> &RMB =3D RegMaskBlocks[MBB->getNumber()];
+    RMB.second =3D RegMaskSlots.size() - RMB.first;;
   }
=20
   // Create empty intervals for registers defined by implicit_def's (except
@@ -754,7 +641,7 @@
                                  SmallVectorImpl<MachineInstr*> *dead) {
   DEBUG(dbgs() << "Shrink: " << *li << '\n');
   assert(TargetRegisterInfo::isVirtualRegister(li->reg)
-         && "Can't only shrink physical registers");
+         && "Can only shrink virtual registers");
   // Find all the values used, including PHI kills.
   SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
=20
@@ -766,8 +653,10 @@
        MachineInstr *UseMI =3D I.skipInstruction();) {
     if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
       continue;
-    SlotIndex Idx =3D getInstructionIndex(UseMI).getUseIndex();
-    VNInfo *VNI =3D li->getVNInfoAt(Idx);
+    SlotIndex Idx =3D getInstructionIndex(UseMI).getRegSlot();
+    // Note: This intentionally picks up the wrong VNI in case of an EC re=
def.
+    // See below.
+    VNInfo *VNI =3D li->getVNInfoBefore(Idx);
     if (!VNI) {
       // This shouldn't happen: readsVirtualRegister returns true, but the=
re is
       // no live value. It is likely caused by a target getting <undef> fl=
ags
@@ -777,11 +666,12 @@
                     << *li << '\n');
       continue;
     }
-    if (VNI->def =3D=3D Idx) {
-      // Special case: An early-clobber tied operand reads and writes the
-      // register one slot early.
-      Idx =3D Idx.getPrevSlot();
-      VNI =3D li->getVNInfoAt(Idx);
+    // Special case: An early-clobber tied operand reads and writes the
+    // register one slot early.  The getVNInfoBefore call above would have
+    // picked up the value defined by UseMI.  Adjust the kill slot and val=
ue.
+    if (SlotIndex::isSameInstr(VNI->def, Idx)) {
+      Idx =3D VNI->def;
+      VNI =3D li->getVNInfoBefore(Idx);
       assert(VNI && "Early-clobber tied value not available");
     }
     WorkList.push_back(std::make_pair(Idx, VNI));
@@ -794,14 +684,7 @@
     VNInfo *VNI =3D *I;
     if (VNI->isUnused())
       continue;
-    NewLI.addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), VNI));
-
-    // A use tied to an early-clobber def ends at the load slot and isn't =
caught
-    // above. Catch it here instead. This probably only ever happens for i=
nline
-    // assembly.
-    if (VNI->def.isUse())
-      if (VNInfo *UVNI =3D li->getVNInfoAt(VNI->def.getLoadIndex()))
-        WorkList.push_back(std::make_pair(VNI->def.getLoadIndex(), UVNI));
+    NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
   }
=20
   // Keep track of the PHIs that are in use.
@@ -812,11 +695,11 @@
     SlotIndex Idx =3D WorkList.back().first;
     VNInfo *VNI =3D WorkList.back().second;
     WorkList.pop_back();
-    const MachineBasicBlock *MBB =3D getMBBFromIndex(Idx);
+    const MachineBasicBlock *MBB =3D getMBBFromIndex(Idx.getPrevSlot());
     SlotIndex BlockStart =3D getMBBStartIdx(MBB);
=20
     // Extend the live range for VNI to be live at Idx.
-    if (VNInfo *ExtVNI =3D NewLI.extendInBlock(BlockStart, Idx.getNextSlot=
())) {
+    if (VNInfo *ExtVNI =3D NewLI.extendInBlock(BlockStart, Idx)) {
       (void)ExtVNI;
       assert(ExtVNI =3D=3D VNI && "Unexpected existing value number");
       // Is this a PHIDef we haven't seen before?
@@ -827,9 +710,9 @@
            PE =3D MBB->pred_end(); PI !=3D PE; ++PI) {
         if (!LiveOut.insert(*PI))
           continue;
-        SlotIndex Stop =3D getMBBEndIdx(*PI).getPrevSlot();
+        SlotIndex Stop =3D getMBBEndIdx(*PI);
         // A predecessor is not required to have a live-out value for a PH=
I.
-        if (VNInfo *PVNI =3D li->getVNInfoAt(Stop))
+        if (VNInfo *PVNI =3D li->getVNInfoBefore(Stop))
           WorkList.push_back(std::make_pair(Stop, PVNI));
       }
       continue;
@@ -837,15 +720,16 @@
=20
     // VNI is live-in to MBB.
     DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
-    NewLI.addRange(LiveRange(BlockStart, Idx.getNextSlot(), VNI));
+    NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
=20
     // Make sure VNI is live-out from the predecessors.
     for (MachineBasicBlock::const_pred_iterator PI =3D MBB->pred_begin(),
          PE =3D MBB->pred_end(); PI !=3D PE; ++PI) {
       if (!LiveOut.insert(*PI))
         continue;
-      SlotIndex Stop =3D getMBBEndIdx(*PI).getPrevSlot();
-      assert(li->getVNInfoAt(Stop) =3D=3D VNI && "Wrong value out of prede=
cessor");
+      SlotIndex Stop =3D getMBBEndIdx(*PI);
+      assert(li->getVNInfoBefore(Stop) =3D=3D VNI &&
+             "Wrong value out of predecessor");
       WorkList.push_back(std::make_pair(Stop, VNI));
     }
   }
@@ -859,7 +743,7 @@
       continue;
     LiveInterval::iterator LII =3D NewLI.FindLiveRangeContaining(VNI->def);
     assert(LII !=3D NewLI.end() && "Missing live range for PHI");
-    if (LII->end !=3D VNI->def.getNextSlot())
+    if (LII->end !=3D VNI->def.getDeadSlot())
       continue;
     if (VNI->isPHIDef()) {
       // This is a dead PHI. Remove it.
@@ -890,28 +774,6 @@
 // Register allocator hooks.
 //
=20
-MachineBasicBlock::iterator
-LiveIntervals::getLastSplitPoint(const LiveInterval &li,
-                                 MachineBasicBlock *mbb) const {
-  const MachineBasicBlock *lpad =3D mbb->getLandingPadSuccessor();
-
-  // If li is not live into a landing pad, we can insert spill code before=
 the
-  // first terminator.
-  if (!lpad || !isLiveInToMBB(li, lpad))
-    return mbb->getFirstTerminator();
-
-  // When there is a landing pad, spill code must go before the call instr=
uction
-  // that can throw.
-  MachineBasicBlock::iterator I =3D mbb->end(), B =3D mbb->begin();
-  while (I !=3D B) {
-    --I;
-    if (I->getDesc().isCall())
-      return I;
-  }
-  // The block contains no calls that can throw, so use the first terminat=
or.
-  return mbb->getFirstTerminator();
-}
-
 void LiveIntervals::addKillFlags() {
   for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I) {
     unsigned Reg =3D I->first;
@@ -924,8 +786,8 @@
     // Every instruction that kills Reg corresponds to a live range end po=
int.
     for (LiveInterval::iterator RI =3D LI->begin(), RE =3D LI->end(); RI !=
=3D RE;
          ++RI) {
-      // A LOAD index indicates an MBB edge.
-      if (RI->end.isLoad())
+      // A block index indicates an MBB edge.
+      if (RI->end.isBlock())
         continue;
       MachineInstr *MI =3D getInstructionFromIndex(RI->end);
       if (!MI)
@@ -949,16 +811,10 @@
     if (Reg =3D=3D 0 || Reg =3D=3D li.reg)
       continue;
=20
-    if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
-        !allocatableRegs_[Reg])
+    if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isAllocatable(Reg))
       continue;
-    // FIXME: For now, only remat MI with at most one register operand.
-    assert(!RegOp &&
-           "Can't rematerialize instruction with multiple register operand=
!");
     RegOp =3D MO.getReg();
-#ifndef NDEBUG
-    break;
-#endif
+    break; // Found vreg operand - leave the loop.
   }
   return RegOp;
 }
@@ -1011,14 +867,6 @@
   return true;
 }
=20
-/// isReMaterializable - Returns true if the definition MI of the specified
-/// val# of the specified interval is re-materializable.
-bool LiveIntervals::isReMaterializable(const LiveInterval &li,
-                                       const VNInfo *ValNo, MachineInstr *=
MI) {
-  bool Dummy2;
-  return isReMaterializable(li, ValNo, MI, 0, Dummy2);
-}
-
 /// isReMaterializable - Returns true if every definition of MI of every
 /// val# of the specified interval is re-materializable.
 bool
@@ -1044,672 +892,28 @@
   return true;
 }
=20
-/// FilterFoldedOps - Filter out two-address use operands. Return
-/// true if it finds any issue with the operands that ought to prevent
-/// folding.
-static bool FilterFoldedOps(MachineInstr *MI,
-                            SmallVector<unsigned, 2> &Ops,
-                            unsigned &MRInfo,
-                            SmallVector<unsigned, 2> &FoldOps) {
-  MRInfo =3D 0;
-  for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i) {
-    unsigned OpIdx =3D Ops[i];
-    MachineOperand &MO =3D MI->getOperand(OpIdx);
-    // FIXME: fold subreg use.
-    if (MO.getSubReg())
-      return true;
-    if (MO.isDef())
-      MRInfo |=3D (unsigned)VirtRegMap::isMod;
-    else {
-      // Filter out two-address use operand(s).
-      if (MI->isRegTiedToDefOperand(OpIdx)) {
-        MRInfo =3D VirtRegMap::isModRef;
-        continue;
-      }
-      MRInfo |=3D (unsigned)VirtRegMap::isRef;
-    }
-    FoldOps.push_back(OpIdx);
-  }
-  return false;
-}
+MachineBasicBlock*
+LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
+  // A local live range must be fully contained inside the block, meaning =
it is
+  // defined and killed at instructions, not at block boundaries. It is not
+  // live in or or out of any block.
+  //
+  // It is technically possible to have a PHI-defined live range identical=
 to a
+  // single block, but we are going to return false in that case.
=20
+  SlotIndex Start =3D LI.beginIndex();
+  if (Start.isBlock())
+    return NULL;
=20
-/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
-/// slot / to reg or any rematerialized load into ith operand of specified
-/// MI. If it is successul, MI is updated with the newly created MI and
-/// returns true.
-bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
-                                         VirtRegMap &vrm, MachineInstr *De=
fMI,
-                                         SlotIndex InstrIdx,
-                                         SmallVector<unsigned, 2> &Ops,
-                                         bool isSS, int Slot, unsigned Reg=
) {
-  // If it is an implicit def instruction, just delete it.
-  if (MI->isImplicitDef()) {
-    RemoveMachineInstrFromMaps(MI);
-    vrm.RemoveMachineInstrFromMaps(MI);
-    MI->eraseFromParent();
-    ++numFolds;
-    return true;
-  }
+  SlotIndex Stop =3D LI.endIndex();
+  if (Stop.isBlock())
+    return NULL;
=20
-  // Filter the list of operand indexes that are to be folded. Abort if
-  // any operand will prevent folding.
-  unsigned MRInfo =3D 0;
-  SmallVector<unsigned, 2> FoldOps;
-  if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
-    return false;
-
-  // The only time it's safe to fold into a two address instruction is when
-  // it's folding reload and spill from / into a spill stack slot.
-  if (DefMI && (MRInfo & VirtRegMap::isMod))
-    return false;
-
-  MachineInstr *fmi =3D isSS ? tii_->foldMemoryOperand(MI, FoldOps, Slot)
-                           : tii_->foldMemoryOperand(MI, FoldOps, DefMI);
-  if (fmi) {
-    // Remember this instruction uses the spill slot.
-    if (isSS) vrm.addSpillSlotUse(Slot, fmi);
-
-    // Attempt to fold the memory reference into the instruction. If
-    // we can do this, we don't need to insert spill code.
-    if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
-      vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
-    vrm.transferSpillPts(MI, fmi);
-    vrm.transferRestorePts(MI, fmi);
-    vrm.transferEmergencySpills(MI, fmi);
-    ReplaceMachineInstrInMaps(MI, fmi);
-    MI->eraseFromParent();
-    MI =3D fmi;
-    ++numFolds;
-    return true;
-  }
-  return false;
-}
-
-/// canFoldMemoryOperand - Returns true if the specified load / store
-/// folding is possible.
-bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
-                                         SmallVector<unsigned, 2> &Ops,
-                                         bool ReMat) const {
-  // Filter the list of operand indexes that are to be folded. Abort if
-  // any operand will prevent folding.
-  unsigned MRInfo =3D 0;
-  SmallVector<unsigned, 2> FoldOps;
-  if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
-    return false;
-
-  // It's only legal to remat for a use, not a def.
-  if (ReMat && (MRInfo & VirtRegMap::isMod))
-    return false;
-
-  return tii_->canFoldMemoryOperand(MI, FoldOps);
-}
-
-bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
-  LiveInterval::Ranges::const_iterator itr =3D li.ranges.begin();
-
-  MachineBasicBlock *mbb =3D  indexes_->getMBBCoveringRange(itr->start, it=
r->end);
-
-  if (mbb =3D=3D 0)
-    return false;
-
-  for (++itr; itr !=3D li.ranges.end(); ++itr) {
-    MachineBasicBlock *mbb2 =3D
-      indexes_->getMBBCoveringRange(itr->start, itr->end);
-
-    if (mbb2 !=3D mbb)
-      return false;
-  }
-
-  return true;
-}
-
-/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
-/// interval on to-be re-materialized operands of MI) with new register.
-void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
-                                       MachineInstr *MI, unsigned NewVReg,
-                                       VirtRegMap &vrm) {
-  // There is an implicit use. That means one of the other operand is
-  // being remat'ed and the remat'ed instruction has li.reg as an
-  // use operand. Make sure we rewrite that as well.
-  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
-    MachineOperand &MO =3D MI->getOperand(i);
-    if (!MO.isReg())
-      continue;
-    unsigned Reg =3D MO.getReg();
-    if (!TargetRegisterInfo::isVirtualRegister(Reg))
-      continue;
-    if (!vrm.isReMaterialized(Reg))
-      continue;
-    MachineInstr *ReMatMI =3D vrm.getReMaterializedMI(Reg);
-    MachineOperand *UseMO =3D ReMatMI->findRegisterUseOperand(li.reg);
-    if (UseMO)
-      UseMO->setReg(NewVReg);
-  }
-}
-
-/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper fun=
ctions
-/// for addIntervalsForSpills to rewrite uses / defs for the given live ra=
nge.
-bool LiveIntervals::
-rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
-                 bool TrySplit, SlotIndex index, SlotIndex end,
-                 MachineInstr *MI,
-                 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
-                 unsigned Slot, int LdSlot,
-                 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDele=
te,
-                 VirtRegMap &vrm,
-                 const TargetRegisterClass* rc,
-                 SmallVector<int, 4> &ReMatIds,
-                 const MachineLoopInfo *loopInfo,
-                 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &H=
asUse,
-                 DenseMap<unsigned,unsigned> &MBBVRegsMap,
-                 std::vector<LiveInterval*> &NewLIs) {
-  bool CanFold =3D false;
- RestartInstruction:
-  for (unsigned i =3D 0; i !=3D MI->getNumOperands(); ++i) {
-    MachineOperand& mop =3D MI->getOperand(i);
-    if (!mop.isReg())
-      continue;
-    unsigned Reg =3D mop.getReg();
-    if (!TargetRegisterInfo::isVirtualRegister(Reg))
-      continue;
-    if (Reg !=3D li.reg)
-      continue;
-
-    bool TryFold =3D !DefIsReMat;
-    bool FoldSS =3D true; // Default behavior unless it's a remat.
-    int FoldSlot =3D Slot;
-    if (DefIsReMat) {
-      // If this is the rematerializable definition MI itself and
-      // all of its uses are rematerialized, simply delete it.
-      if (MI =3D=3D ReMatOrigDefMI && CanDelete) {
-        DEBUG(dbgs() << "\t\t\t\tErasing re-materializable def: "
-                     << *MI << '\n');
-        RemoveMachineInstrFromMaps(MI);
-        vrm.RemoveMachineInstrFromMaps(MI);
-        MI->eraseFromParent();
-        break;
-      }
-
-      // If def for this use can't be rematerialized, then try folding.
-      // If def is rematerializable and it's a load, also try folding.
-      TryFold =3D !ReMatDefMI || (ReMatDefMI && (MI =3D=3D ReMatOrigDefMI =
|| isLoad));
-      if (isLoad) {
-        // Try fold loads (from stack slot, constant pool, etc.) into uses.
-        FoldSS =3D isLoadSS;
-        FoldSlot =3D LdSlot;
-      }
-    }
-
-    // Scan all of the operands of this instruction rewriting operands
-    // to use NewVReg instead of li.reg as appropriate.  We do this for
-    // two reasons:
-    //
-    //   1. If the instr reads the same spilled vreg multiple times, we
-    //      want to reuse the NewVReg.
-    //   2. If the instr is a two-addr instruction, we are required to
-    //      keep the src/dst regs pinned.
-    //
-    // Keep track of whether we replace a use and/or def so that we can
-    // create the spill interval with the appropriate range.
-    SmallVector<unsigned, 2> Ops;
-    tie(HasUse, HasDef) =3D MI->readsWritesVirtualRegister(Reg, &Ops);
-
-    // Create a new virtual register for the spill interval.
-    // Create the new register now so we can map the fold instruction
-    // to the new register so when it is unfolded we get the correct
-    // answer.
-    bool CreatedNewVReg =3D false;
-    if (NewVReg =3D=3D 0) {
-      NewVReg =3D mri_->createVirtualRegister(rc);
-      vrm.grow();
-      CreatedNewVReg =3D true;
-
-      // The new virtual register should get the same allocation hints as =
the
-      // old one.
-      std::pair<unsigned, unsigned> Hint =3D mri_->getRegAllocationHint(Re=
g);
-      if (Hint.first || Hint.second)
-        mri_->setRegAllocationHint(NewVReg, Hint.first, Hint.second);
-    }
-
-    if (!TryFold)
-      CanFold =3D false;
-    else {
-      // Do not fold load / store here if we are splitting. We'll find an
-      // optimal point to insert a load / store later.
-      if (!TrySplit) {
-        if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
-                                 Ops, FoldSS, FoldSlot, NewVReg)) {
-          // Folding the load/store can completely change the instruction =
in
-          // unpredictable ways, rescan it from the beginning.
-
-          if (FoldSS) {
-            // We need to give the new vreg the same stack slot as the
-            // spilled interval.
-            vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
-          }
-
-          HasUse =3D false;
-          HasDef =3D false;
-          CanFold =3D false;
-          if (isNotInMIMap(MI))
-            break;
-          goto RestartInstruction;
-        }
-      } else {
-        // We'll try to fold it later if it's profitable.
-        CanFold =3D canFoldMemoryOperand(MI, Ops, DefIsReMat);
-      }
-    }
-
-    mop.setReg(NewVReg);
-    if (mop.isImplicit())
-      rewriteImplicitOps(li, MI, NewVReg, vrm);
-
-    // Reuse NewVReg for other reads.
-    bool HasEarlyClobber =3D false;
-    for (unsigned j =3D 0, e =3D Ops.size(); j !=3D e; ++j) {
-      MachineOperand &mopj =3D MI->getOperand(Ops[j]);
-      mopj.setReg(NewVReg);
-      if (mopj.isImplicit())
-        rewriteImplicitOps(li, MI, NewVReg, vrm);
-      if (mopj.isEarlyClobber())
-        HasEarlyClobber =3D true;
-    }
-
-    if (CreatedNewVReg) {
-      if (DefIsReMat) {
-        vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI);
-        if (ReMatIds[VNI->id] =3D=3D VirtRegMap::MAX_STACK_SLOT) {
-          // Each valnum may have its own remat id.
-          ReMatIds[VNI->id] =3D vrm.assignVirtReMatId(NewVReg);
-        } else {
-          vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
-        }
-        if (!CanDelete || (HasUse && HasDef)) {
-          // If this is a two-addr instruction then its use operands are
-          // rematerializable but its def is not. It should be assigned a
-          // stack slot.
-          vrm.assignVirt2StackSlot(NewVReg, Slot);
-        }
-      } else {
-        vrm.assignVirt2StackSlot(NewVReg, Slot);
-      }
-    } else if (HasUse && HasDef &&
-               vrm.getStackSlot(NewVReg) =3D=3D VirtRegMap::NO_STACK_SLOT)=
 {
-      // If this interval hasn't been assigned a stack slot (because earli=
er
-      // def is a deleted remat def), do it now.
-      assert(Slot !=3D VirtRegMap::NO_STACK_SLOT);
-      vrm.assignVirt2StackSlot(NewVReg, Slot);
-    }
-
-    // Re-matting an instruction with virtual register use. Add the
-    // register as an implicit use on the use MI.
-    if (DefIsReMat && ImpUse)
-      MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
-
-    // Create a new register interval for this spill / remat.
-    LiveInterval &nI =3D getOrCreateInterval(NewVReg);
-    if (CreatedNewVReg) {
-      NewLIs.push_back(&nI);
-      MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewV=
Reg));
-      if (TrySplit)
-        vrm.setIsSplitFromReg(NewVReg, li.reg);
-    }
-
-    if (HasUse) {
-      if (CreatedNewVReg) {
-        LiveRange LR(index.getLoadIndex(), index.getDefIndex(),
-                     nI.getNextValue(SlotIndex(), 0, VNInfoAllocator));
-        DEBUG(dbgs() << " +" << LR);
-        nI.addRange(LR);
-      } else {
-        // Extend the split live interval to this def / use.
-        SlotIndex End =3D index.getDefIndex();
-        LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
-                     nI.getValNumInfo(nI.getNumValNums()-1));
-        DEBUG(dbgs() << " +" << LR);
-        nI.addRange(LR);
-      }
-    }
-    if (HasDef) {
-      // An early clobber starts at the use slot, except for an early clob=
ber
-      // tied to a use operand (yes, that is a thing).
-      LiveRange LR(HasEarlyClobber && !HasUse ?
-                   index.getUseIndex() : index.getDefIndex(),
-                   index.getStoreIndex(),
-                   nI.getNextValue(SlotIndex(), 0, VNInfoAllocator));
-      DEBUG(dbgs() << " +" << LR);
-      nI.addRange(LR);
-    }
-
-    DEBUG({
-        dbgs() << "\t\t\t\tAdded new interval: ";
-        nI.print(dbgs(), tri_);
-        dbgs() << '\n';
-      });
-  }
-  return CanFold;
-}
-bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
-                                   const VNInfo *VNI,
-                                   MachineBasicBlock *MBB,
-                                   SlotIndex Idx) const {
-  return li.killedInRange(Idx.getNextSlot(), getMBBEndIdx(MBB));
-}
-
-/// RewriteInfo - Keep track of machine instrs that will be rewritten
-/// during spilling.
-namespace {
-  struct RewriteInfo {
-    SlotIndex Index;
-    MachineInstr *MI;
-    RewriteInfo(SlotIndex i, MachineInstr *mi) : Index(i), MI(mi) {}
-  };
-
-  struct RewriteInfoCompare {
-    bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
-      return LHS.Index < RHS.Index;
-    }
-  };
-}
-
-void LiveIntervals::
-rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
-                    LiveInterval::Ranges::const_iterator &I,
-                    MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
-                    unsigned Slot, int LdSlot,
-                    bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanD=
elete,
-                    VirtRegMap &vrm,
-                    const TargetRegisterClass* rc,
-                    SmallVector<int, 4> &ReMatIds,
-                    const MachineLoopInfo *loopInfo,
-                    BitVector &SpillMBBs,
-                    DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
-                    BitVector &RestoreMBBs,
-                    DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
-                    DenseMap<unsigned,unsigned> &MBBVRegsMap,
-                    std::vector<LiveInterval*> &NewLIs) {
-  bool AllCanFold =3D true;
-  unsigned NewVReg =3D 0;
-  SlotIndex start =3D I->start.getBaseIndex();
-  SlotIndex end =3D I->end.getPrevSlot().getBaseIndex().getNextIndex();
-
-  // First collect all the def / use in this live range that will be rewri=
tten.
-  // Make sure they are sorted according to instruction index.
-  std::vector<RewriteInfo> RewriteMIs;
-  for (MachineRegisterInfo::reg_iterator ri =3D mri_->reg_begin(li.reg),
-         re =3D mri_->reg_end(); ri !=3D re; ) {
-    MachineInstr *MI =3D &*ri;
-    MachineOperand &O =3D ri.getOperand();
-    ++ri;
-    if (MI->isDebugValue()) {
-      // Modify DBG_VALUE now that the value is in a spill slot.
-      if (Slot !=3D VirtRegMap::MAX_STACK_SLOT || isLoadSS) {
-        uint64_t Offset =3D MI->getOperand(1).getImm();
-        const MDNode *MDPtr =3D MI->getOperand(2).getMetadata();
-        DebugLoc DL =3D MI->getDebugLoc();
-        int FI =3D isLoadSS ? LdSlot : (int)Slot;
-        if (MachineInstr *NewDV =3D tii_->emitFrameIndexDebugValue(*mf_, F=
I,
-                                                           Offset, MDPtr, =
DL)) {
-          DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << =
*MI);
-          ReplaceMachineInstrInMaps(MI, NewDV);
-          MachineBasicBlock *MBB =3D MI->getParent();
-          MBB->insert(MBB->erase(MI), NewDV);
-          continue;
-        }
-      }
-
-      DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
-      RemoveMachineInstrFromMaps(MI);
-      vrm.RemoveMachineInstrFromMaps(MI);
-      MI->eraseFromParent();
-      continue;
-    }
-    assert(!(O.isImplicit() && O.isUse()) &&
-           "Spilling register that's used as implicit use?");
-    SlotIndex index =3D getInstructionIndex(MI);
-    if (index < start || index >=3D end)
-      continue;
-
-    if (O.isUndef())
-      // Must be defined by an implicit def. It should not be spilled. Not=
e,
-      // this is for correctness reason. e.g.
-      // 8   %reg1024<def> =3D IMPLICIT_DEF
-      // 12  %reg1024<def> =3D INSERT_SUBREG %reg1024<kill>, %reg1025, 2
-      // The live range [12, 14) are not part of the r1024 live interval s=
ince
-      // it's defined by an implicit def. It will not conflicts with live
-      // interval of r1025. Now suppose both registers are spilled, you can
-      // easily see a situation where both registers are reloaded before
-      // the INSERT_SUBREG and both target registers that would overlap.
-      continue;
-    RewriteMIs.push_back(RewriteInfo(index, MI));
-  }
-  std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
-
-  unsigned ImpUse =3D DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
-  // Now rewrite the defs and uses.
-  for (unsigned i =3D 0, e =3D RewriteMIs.size(); i !=3D e; ) {
-    RewriteInfo &rwi =3D RewriteMIs[i];
-    ++i;
-    SlotIndex index =3D rwi.Index;
-    MachineInstr *MI =3D rwi.MI;
-    // If MI def and/or use the same register multiple times, then there
-    // are multiple entries.
-    while (i !=3D e && RewriteMIs[i].MI =3D=3D MI) {
-      assert(RewriteMIs[i].Index =3D=3D index);
-      ++i;
-    }
-    MachineBasicBlock *MBB =3D MI->getParent();
-
-    if (ImpUse && MI !=3D ReMatDefMI) {
-      // Re-matting an instruction with virtual register use. Prevent inte=
rval
-      // from being spilled.
-      getInterval(ImpUse).markNotSpillable();
-    }
-
-    unsigned MBBId =3D MBB->getNumber();
-    unsigned ThisVReg =3D 0;
-    if (TrySplit) {
-      DenseMap<unsigned,unsigned>::iterator NVI =3D MBBVRegsMap.find(MBBId=
);
-      if (NVI !=3D MBBVRegsMap.end()) {
-        ThisVReg =3D NVI->second;
-        // One common case:
-        // x =3D use
-        // ...
-        // ...
-        // def =3D ...
-        //     =3D use
-        // It's better to start a new interval to avoid artificially
-        // extend the new interval.
-        if (MI->readsWritesVirtualRegister(li.reg) =3D=3D
-            std::make_pair(false,true)) {
-          MBBVRegsMap.erase(MBB->getNumber());
-          ThisVReg =3D 0;
-        }
-      }
-    }
-
-    bool IsNew =3D ThisVReg =3D=3D 0;
-    if (IsNew) {
-      // This ends the previous live interval. If all of its def / use
-      // can be folded, give it a low spill weight.
-      if (NewVReg && TrySplit && AllCanFold) {
-        LiveInterval &nI =3D getOrCreateInterval(NewVReg);
-        nI.weight /=3D 10.0F;
-      }
-      AllCanFold =3D true;
-    }
-    NewVReg =3D ThisVReg;
-
-    bool HasDef =3D false;
-    bool HasUse =3D false;
-    bool CanFold =3D rewriteInstructionForSpills(li, I->valno, TrySplit,
-                         index, end, MI, ReMatOrigDefMI, ReMatDefMI,
-                         Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
-                         CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
-                         ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs);
-    if (!HasDef && !HasUse)
-      continue;
-
-    AllCanFold &=3D CanFold;
-
-    // Update weight of spill interval.
-    LiveInterval &nI =3D getOrCreateInterval(NewVReg);
-    if (!TrySplit) {
-      // The spill weight is now infinity as it cannot be spilled again.
-      nI.markNotSpillable();
-      continue;
-    }
-
-    // Keep track of the last def and first use in each MBB.
-    if (HasDef) {
-      if (MI !=3D ReMatOrigDefMI || !CanDelete) {
-        bool HasKill =3D false;
-        if (!HasUse)
-          HasKill =3D anyKillInMBBAfterIdx(li, I->valno, MBB, index.getDef=
Index());
-        else {
-          // If this is a two-address code, then this index starts a new V=
NInfo.
-          const VNInfo *VNI =3D li.findDefinedVNInfoForRegInt(index.getDef=
Index());
-          if (VNI)
-            HasKill =3D anyKillInMBBAfterIdx(li, VNI, MBB, index.getDefInd=
ex());
-        }
-        DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =3D
-          SpillIdxes.find(MBBId);
-        if (!HasKill) {
-          if (SII =3D=3D SpillIdxes.end()) {
-            std::vector<SRInfo> S;
-            S.push_back(SRInfo(index, NewVReg, true));
-            SpillIdxes.insert(std::make_pair(MBBId, S));
-          } else if (SII->second.back().vreg !=3D NewVReg) {
-            SII->second.push_back(SRInfo(index, NewVReg, true));
-          } else if (index > SII->second.back().index) {
-            // If there is an earlier def and this is a two-address
-            // instruction, then it's not possible to fold the store (which
-            // would also fold the load).
-            SRInfo &Info =3D SII->second.back();
-            Info.index =3D index;
-            Info.canFold =3D !HasUse;
-          }
-          SpillMBBs.set(MBBId);
-        } else if (SII !=3D SpillIdxes.end() &&
-                   SII->second.back().vreg =3D=3D NewVReg &&
-                   index > SII->second.back().index) {
-          // There is an earlier def that's not killed (must be two-addres=
s).
-          // The spill is no longer needed.
-          SII->second.pop_back();
-          if (SII->second.empty()) {
-            SpillIdxes.erase(MBBId);
-            SpillMBBs.reset(MBBId);
-          }
-        }
-      }
-    }
-
-    if (HasUse) {
-      DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =3D
-        SpillIdxes.find(MBBId);
-      if (SII !=3D SpillIdxes.end() &&
-          SII->second.back().vreg =3D=3D NewVReg &&
-          index > SII->second.back().index)
-        // Use(s) following the last def, it's not safe to fold the spill.
-        SII->second.back().canFold =3D false;
-      DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =3D
-        RestoreIdxes.find(MBBId);
-      if (RII !=3D RestoreIdxes.end() && RII->second.back().vreg =3D=3D Ne=
wVReg)
-        // If we are splitting live intervals, only fold if it's the first
-        // use and there isn't another use later in the MBB.
-        RII->second.back().canFold =3D false;
-      else if (IsNew) {
-        // Only need a reload if there isn't an earlier def / use.
-        if (RII =3D=3D RestoreIdxes.end()) {
-          std::vector<SRInfo> Infos;
-          Infos.push_back(SRInfo(index, NewVReg, true));
-          RestoreIdxes.insert(std::make_pair(MBBId, Infos));
-        } else {
-          RII->second.push_back(SRInfo(index, NewVReg, true));
-        }
-        RestoreMBBs.set(MBBId);
-      }
-    }
-
-    // Update spill weight.
-    unsigned loopDepth =3D loopInfo->getLoopDepth(MBB);
-    nI.weight +=3D getSpillWeight(HasDef, HasUse, loopDepth);
-  }
-
-  if (NewVReg && TrySplit && AllCanFold) {
-    // If all of its def / use can be folded, give it a low spill weight.
-    LiveInterval &nI =3D getOrCreateInterval(NewVReg);
-    nI.weight /=3D 10.0F;
-  }
-}
-
-bool LiveIntervals::alsoFoldARestore(int Id, SlotIndex index,
-                        unsigned vr, BitVector &RestoreMBBs,
-                        DenseMap<unsigned,std::vector<SRInfo> > &RestoreId=
xes) {
-  if (!RestoreMBBs[Id])
-    return false;
-  std::vector<SRInfo> &Restores =3D RestoreIdxes[Id];
-  for (unsigned i =3D 0, e =3D Restores.size(); i !=3D e; ++i)
-    if (Restores[i].index =3D=3D index &&
-        Restores[i].vreg =3D=3D vr &&
-        Restores[i].canFold)
-      return true;
-  return false;
-}
-
-void LiveIntervals::eraseRestoreInfo(int Id, SlotIndex index,
-                        unsigned vr, BitVector &RestoreMBBs,
-                        DenseMap<unsigned,std::vector<SRInfo> > &RestoreId=
xes) {
-  if (!RestoreMBBs[Id])
-    return;
-  std::vector<SRInfo> &Restores =3D RestoreIdxes[Id];
-  for (unsigned i =3D 0, e =3D Restores.size(); i !=3D e; ++i)
-    if (Restores[i].index =3D=3D index && Restores[i].vreg)
-      Restores[i].index =3D SlotIndex();
-}
-
-/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
-/// spilled and create empty intervals for their uses.
-void
-LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vr=
m,
-                                    const TargetRegisterClass* rc,
-                                    std::vector<LiveInterval*> &NewLIs) {
-  for (MachineRegisterInfo::reg_iterator ri =3D mri_->reg_begin(li.reg),
-         re =3D mri_->reg_end(); ri !=3D re; ) {
-    MachineOperand &O =3D ri.getOperand();
-    MachineInstr *MI =3D &*ri;
-    ++ri;
-    if (MI->isDebugValue()) {
-      // Remove debug info for now.
-      O.setReg(0U);
-      DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
-      continue;
-    }
-    if (O.isDef()) {
-      assert(MI->isImplicitDef() &&
-             "Register def was not rewritten?");
-      RemoveMachineInstrFromMaps(MI);
-      vrm.RemoveMachineInstrFromMaps(MI);
-      MI->eraseFromParent();
-    } else {
-      // This must be an use of an implicit_def so it's not part of the li=
ve
-      // interval. Create a new empty live interval for it.
-      // FIXME: Can we simply erase some of the instructions? e.g. Stores?
-      unsigned NewVReg =3D mri_->createVirtualRegister(rc);
-      vrm.grow();
-      vrm.setIsImplicitlyDefined(NewVReg);
-      NewLIs.push_back(&getOrCreateInterval(NewVReg));
-      for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
-        MachineOperand &MO =3D MI->getOperand(i);
-        if (MO.isReg() && MO.getReg() =3D=3D li.reg) {
-          MO.setReg(NewVReg);
-          MO.setIsUndef();
-        }
-      }
-    }
-  }
+  // getMBBFromIndex doesn't need to search the MBB table when both indexes
+  // belong to proper instructions.
+  MachineBasicBlock *MBB1 =3D indexes_->getMBBFromIndex(Start);
+  MachineBasicBlock *MBB2 =3D indexes_->getMBBFromIndex(Stop);
+  return MBB1 =3D=3D MBB2 ? MBB1 : NULL;
 }
=20
 float
@@ -1730,455 +934,611 @@
   return (isDef + isUse) * lc;
 }
=20
-static void normalizeSpillWeights(std::vector<LiveInterval*> &NewLIs) {
-  for (unsigned i =3D 0, e =3D NewLIs.size(); i !=3D e; ++i)
-    NewLIs[i]->weight =3D
-      normalizeSpillWeight(NewLIs[i]->weight, NewLIs[i]->getSize());
-}
-
-std::vector<LiveInterval*> LiveIntervals::
-addIntervalsForSpills(const LiveInterval &li,
-                      const SmallVectorImpl<LiveInterval*> *SpillIs,
-                      const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
-  assert(li.isSpillable() && "attempt to spill already spilled interval!");
-
-  DEBUG({
-      dbgs() << "\t\t\t\tadding intervals for spills for interval: ";
-      li.print(dbgs(), tri_);
-      dbgs() << '\n';
-    });
-
-  // Each bit specify whether a spill is required in the MBB.
-  BitVector SpillMBBs(mf_->getNumBlockIDs());
-  DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
-  BitVector RestoreMBBs(mf_->getNumBlockIDs());
-  DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
-  DenseMap<unsigned,unsigned> MBBVRegsMap;
-  std::vector<LiveInterval*> NewLIs;
-  const TargetRegisterClass* rc =3D mri_->getRegClass(li.reg);
-
-  unsigned NumValNums =3D li.getNumValNums();
-  SmallVector<MachineInstr*, 4> ReMatDefs;
-  ReMatDefs.resize(NumValNums, NULL);
-  SmallVector<MachineInstr*, 4> ReMatOrigDefs;
-  ReMatOrigDefs.resize(NumValNums, NULL);
-  SmallVector<int, 4> ReMatIds;
-  ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
-  BitVector ReMatDelete(NumValNums);
-  unsigned Slot =3D VirtRegMap::MAX_STACK_SLOT;
-
-  // Spilling a split live interval. It cannot be split any further. Also,
-  // it's also guaranteed to be a single val# / range interval.
-  if (vrm.getPreSplitReg(li.reg)) {
-    vrm.setIsSplitFromReg(li.reg, 0);
-    // Unset the split kill marker on the last use.
-    SlotIndex KillIdx =3D vrm.getKillPoint(li.reg);
-    if (KillIdx !=3D SlotIndex()) {
-      MachineInstr *KillMI =3D getInstructionFromIndex(KillIdx);
-      assert(KillMI && "Last use disappeared?");
-      int KillOp =3D KillMI->findRegisterUseOperandIdx(li.reg, true);
-      assert(KillOp !=3D -1 && "Last use disappeared?");
-      KillMI->getOperand(KillOp).setIsKill(false);
-    }
-    vrm.removeKillPoint(li.reg);
-    bool DefIsReMat =3D vrm.isReMaterialized(li.reg);
-    Slot =3D vrm.getStackSlot(li.reg);
-    assert(Slot !=3D VirtRegMap::MAX_STACK_SLOT);
-    MachineInstr *ReMatDefMI =3D DefIsReMat ?
-      vrm.getReMaterializedMI(li.reg) : NULL;
-    int LdSlot =3D 0;
-    bool isLoadSS =3D DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, =
LdSlot);
-    bool isLoad =3D isLoadSS ||
-      (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
-    bool IsFirstRange =3D true;
-    for (LiveInterval::Ranges::const_iterator
-           I =3D li.ranges.begin(), E =3D li.ranges.end(); I !=3D E; ++I) {
-      // If this is a split live interval with multiple ranges, it means t=
here
-      // are two-address instructions that re-defined the value. Only the
-      // first def can be rematerialized!
-      if (IsFirstRange) {
-        // Note ReMatOrigDefMI has already been deleted.
-        rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
-                             Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
-                             false, vrm, rc, ReMatIds, loopInfo,
-                             SpillMBBs, SpillIdxes, RestoreMBBs, RestoreId=
xes,
-                             MBBVRegsMap, NewLIs);
-      } else {
-        rewriteInstructionsForSpills(li, false, I, NULL, 0,
-                             Slot, 0, false, false, false,
-                             false, vrm, rc, ReMatIds, loopInfo,
-                             SpillMBBs, SpillIdxes, RestoreMBBs, RestoreId=
xes,
-                             MBBVRegsMap, NewLIs);
-      }
-      IsFirstRange =3D false;
-    }
-
-    handleSpilledImpDefs(li, vrm, rc, NewLIs);
-    normalizeSpillWeights(NewLIs);
-    return NewLIs;
-  }
-
-  bool TrySplit =3D !intervalIsInOneMBB(li);
-  if (TrySplit)
-    ++numSplits;
-  bool NeedStackSlot =3D false;
-  for (LiveInterval::const_vni_iterator i =3D li.vni_begin(), e =3D li.vni=
_end();
-       i !=3D e; ++i) {
-    const VNInfo *VNI =3D *i;
-    unsigned VN =3D VNI->id;
-    if (VNI->isUnused())
-      continue; // Dead val#.
-    // Is the def for the val# rematerializable?
-    MachineInstr *ReMatDefMI =3D getInstructionFromIndex(VNI->def);
-    bool dummy;
-    if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dum=
my)) {
-      // Remember how to remat the def of this val#.
-      ReMatOrigDefs[VN] =3D ReMatDefMI;
-      // Original def may be modified so we have to make a copy here.
-      MachineInstr *Clone =3D mf_->CloneMachineInstr(ReMatDefMI);
-      CloneMIs.push_back(Clone);
-      ReMatDefs[VN] =3D Clone;
-
-      bool CanDelete =3D true;
-      if (VNI->hasPHIKill()) {
-        // A kill is a phi node, not all of its uses can be rematerialized.
-        // It must not be deleted.
-        CanDelete =3D false;
-        // Need a stack slot if there is any live range where uses cannot =
be
-        // rematerialized.
-        NeedStackSlot =3D true;
-      }
-      if (CanDelete)
-        ReMatDelete.set(VN);
-    } else {
-      // Need a stack slot if there is any live range where uses cannot be
-      // rematerialized.
-      NeedStackSlot =3D true;
-    }
-  }
-
-  // One stack slot per live interval.
-  if (NeedStackSlot && vrm.getPreSplitReg(li.reg) =3D=3D 0) {
-    if (vrm.getStackSlot(li.reg) =3D=3D VirtRegMap::NO_STACK_SLOT)
-      Slot =3D vrm.assignVirt2StackSlot(li.reg);
-
-    // This case only occurs when the prealloc splitter has already assign=
ed
-    // a stack slot to this vreg.
-    else
-      Slot =3D vrm.getStackSlot(li.reg);
-  }
-
-  // Create new intervals and rewrite defs and uses.
-  for (LiveInterval::Ranges::const_iterator
-         I =3D li.ranges.begin(), E =3D li.ranges.end(); I !=3D E; ++I) {
-    MachineInstr *ReMatDefMI =3D ReMatDefs[I->valno->id];
-    MachineInstr *ReMatOrigDefMI =3D ReMatOrigDefs[I->valno->id];
-    bool DefIsReMat =3D ReMatDefMI !=3D NULL;
-    bool CanDelete =3D ReMatDelete[I->valno->id];
-    int LdSlot =3D 0;
-    bool isLoadSS =3D DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, =
LdSlot);
-    bool isLoad =3D isLoadSS ||
-      (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
-    rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDef=
MI,
-                               Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
-                               CanDelete, vrm, rc, ReMatIds, loopInfo,
-                               SpillMBBs, SpillIdxes, RestoreMBBs, Restore=
Idxes,
-                               MBBVRegsMap, NewLIs);
-  }
-
-  // Insert spills / restores if we are splitting.
-  if (!TrySplit) {
-    handleSpilledImpDefs(li, vrm, rc, NewLIs);
-    normalizeSpillWeights(NewLIs);
-    return NewLIs;
-  }
-
-  SmallPtrSet<LiveInterval*, 4> AddedKill;
-  SmallVector<unsigned, 2> Ops;
-  if (NeedStackSlot) {
-    int Id =3D SpillMBBs.find_first();
-    while (Id !=3D -1) {
-      std::vector<SRInfo> &spills =3D SpillIdxes[Id];
-      for (unsigned i =3D 0, e =3D spills.size(); i !=3D e; ++i) {
-        SlotIndex index =3D spills[i].index;
-        unsigned VReg =3D spills[i].vreg;
-        LiveInterval &nI =3D getOrCreateInterval(VReg);
-        bool isReMat =3D vrm.isReMaterialized(VReg);
-        MachineInstr *MI =3D getInstructionFromIndex(index);
-        bool CanFold =3D false;
-        bool FoundUse =3D false;
-        Ops.clear();
-        if (spills[i].canFold) {
-          CanFold =3D true;
-          for (unsigned j =3D 0, ee =3D MI->getNumOperands(); j !=3D ee; +=
+j) {
-            MachineOperand &MO =3D MI->getOperand(j);
-            if (!MO.isReg() || MO.getReg() !=3D VReg)
-              continue;
-
-            Ops.push_back(j);
-            if (MO.isDef())
-              continue;
-            if (isReMat ||
-                (!FoundUse && !alsoFoldARestore(Id, index, VReg,
-                                                RestoreMBBs, RestoreIdxes)=
)) {
-              // MI has two-address uses of the same register. If the use
-              // isn't the first and only use in the BB, then we can't fold
-              // it. FIXME: Move this to rewriteInstructionsForSpills.
-              CanFold =3D false;
-              break;
-            }
-            FoundUse =3D true;
-          }
-        }
-        // Fold the store into the def if possible.
-        bool Folded =3D false;
-        if (CanFold && !Ops.empty()) {
-          if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,V=
Reg)){
-            Folded =3D true;
-            if (FoundUse) {
-              // Also folded uses, do not issue a load.
-              eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
-              nI.removeRange(index.getLoadIndex(), index.getDefIndex());
-            }
-            nI.removeRange(index.getDefIndex(), index.getStoreIndex());
-          }
-        }
-
-        // Otherwise tell the spiller to issue a spill.
-        if (!Folded) {
-          LiveRange *LR =3D &nI.ranges[nI.ranges.size()-1];
-          bool isKill =3D LR->end =3D=3D index.getStoreIndex();
-          if (!MI->registerDefIsDead(nI.reg))
-            // No need to spill a dead def.
-            vrm.addSpillPoint(VReg, isKill, MI);
-          if (isKill)
-            AddedKill.insert(&nI);
-        }
-      }
-      Id =3D SpillMBBs.find_next(Id);
-    }
-  }
-
-  int Id =3D RestoreMBBs.find_first();
-  while (Id !=3D -1) {
-    std::vector<SRInfo> &restores =3D RestoreIdxes[Id];
-    for (unsigned i =3D 0, e =3D restores.size(); i !=3D e; ++i) {
-      SlotIndex index =3D restores[i].index;
-      if (index =3D=3D SlotIndex())
-        continue;
-      unsigned VReg =3D restores[i].vreg;
-      LiveInterval &nI =3D getOrCreateInterval(VReg);
-      bool isReMat =3D vrm.isReMaterialized(VReg);
-      MachineInstr *MI =3D getInstructionFromIndex(index);
-      bool CanFold =3D false;
-      Ops.clear();
-      if (restores[i].canFold) {
-        CanFold =3D true;
-        for (unsigned j =3D 0, ee =3D MI->getNumOperands(); j !=3D ee; ++j=
) {
-          MachineOperand &MO =3D MI->getOperand(j);
-          if (!MO.isReg() || MO.getReg() !=3D VReg)
-            continue;
-
-          if (MO.isDef()) {
-            // If this restore were to be folded, it would have been folded
-            // already.
-            CanFold =3D false;
-            break;
-          }
-          Ops.push_back(j);
-        }
-      }
-
-      // Fold the load into the use if possible.
-      bool Folded =3D false;
-      if (CanFold && !Ops.empty()) {
-        if (!isReMat)
-          Folded =3D tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slo=
t,VReg);
-        else {
-          MachineInstr *ReMatDefMI =3D vrm.getReMaterializedMI(VReg);
-          int LdSlot =3D 0;
-          bool isLoadSS =3D tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
-          // If the rematerializable def is a load, also try to fold it.
-          if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
-            Folded =3D tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
-                                          Ops, isLoadSS, LdSlot, VReg);
-          if (!Folded) {
-            unsigned ImpUse =3D getReMatImplicitUse(li, ReMatDefMI);
-            if (ImpUse) {
-              // Re-matting an instruction with virtual register use. Add =
the
-              // register as an implicit use on the use MI and mark the re=
gister
-              // interval as unspillable.
-              LiveInterval &ImpLi =3D getInterval(ImpUse);
-              ImpLi.markNotSpillable();
-              MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true=
));
-            }
-          }
-        }
-      }
-      // If folding is not possible / failed, then tell the spiller to iss=
ue a
-      // load / rematerialization for us.
-      if (Folded)
-        nI.removeRange(index.getLoadIndex(), index.getDefIndex());
-      else
-        vrm.addRestorePoint(VReg, MI);
-    }
-    Id =3D RestoreMBBs.find_next(Id);
-  }
-
-  // Finalize intervals: add kills, finalize spill weights, and filter out
-  // dead intervals.
-  std::vector<LiveInterval*> RetNewLIs;
-  for (unsigned i =3D 0, e =3D NewLIs.size(); i !=3D e; ++i) {
-    LiveInterval *LI =3D NewLIs[i];
-    if (!LI->empty()) {
-      if (!AddedKill.count(LI)) {
-        LiveRange *LR =3D &LI->ranges[LI->ranges.size()-1];
-        SlotIndex LastUseIdx =3D LR->end.getBaseIndex();
-        MachineInstr *LastUse =3D getInstructionFromIndex(LastUseIdx);
-        int UseIdx =3D LastUse->findRegisterUseOperandIdx(LI->reg, false);
-        assert(UseIdx !=3D -1);
-        if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
-          LastUse->getOperand(UseIdx).setIsKill();
-          vrm.addKillPoint(LI->reg, LastUseIdx);
-        }
-      }
-      RetNewLIs.push_back(LI);
-    }
-  }
-
-  handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
-  normalizeSpillWeights(RetNewLIs);
-  return RetNewLIs;
-}
-
-/// hasAllocatableSuperReg - Return true if the specified physical registe=
r has
-/// any super register that's allocatable.
-bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
-  for (const unsigned* AS =3D tri_->getSuperRegisters(Reg); *AS; ++AS)
-    if (allocatableRegs_[*AS] && hasInterval(*AS))
-      return true;
-  return false;
-}
-
-/// getRepresentativeReg - Find the largest super register of the specified
-/// physical register.
-unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
-  // Find the largest super-register that is allocatable.
-  unsigned BestReg =3D Reg;
-  for (const unsigned* AS =3D tri_->getSuperRegisters(Reg); *AS; ++AS) {
-    unsigned SuperReg =3D *AS;
-    if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
-      BestReg =3D SuperReg;
-      break;
-    }
-  }
-  return BestReg;
-}
-
-/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
-/// specified interval that conflicts with the specified physical register.
-unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
-                                                   unsigned PhysReg) const=
 {
-  unsigned NumConflicts =3D 0;
-  const LiveInterval &pli =3D getInterval(getRepresentativeReg(PhysReg));
-  for (MachineRegisterInfo::reg_iterator I =3D mri_->reg_begin(li.reg),
-         E =3D mri_->reg_end(); I !=3D E; ++I) {
-    MachineOperand &O =3D I.getOperand();
-    MachineInstr *MI =3D O.getParent();
-    if (MI->isDebugValue())
-      continue;
-    SlotIndex Index =3D getInstructionIndex(MI);
-    if (pli.liveAt(Index))
-      ++NumConflicts;
-  }
-  return NumConflicts;
-}
-
-/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
-/// around all defs and uses of the specified interval. Return true if it
-/// was able to cut its interval.
-bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
-                                            unsigned PhysReg, VirtRegMap &=
vrm) {
-  unsigned SpillReg =3D getRepresentativeReg(PhysReg);
-
-  DEBUG(dbgs() << "spillPhysRegAroundRegDefsUses " << tri_->getName(PhysRe=
g)
-               << " represented by " << tri_->getName(SpillReg) << '\n');
-
-  for (const unsigned *AS =3D tri_->getAliasSet(PhysReg); *AS; ++AS)
-    // If there are registers which alias PhysReg, but which are not a
-    // sub-register of the chosen representative super register. Assert
-    // since we can't handle it yet.
-    assert(*AS =3D=3D SpillReg || !allocatableRegs_[*AS] || !hasInterval(*=
AS) ||
-           tri_->isSuperRegister(*AS, SpillReg));
-
-  bool Cut =3D false;
-  SmallVector<unsigned, 4> PRegs;
-  if (hasInterval(SpillReg))
-    PRegs.push_back(SpillReg);
-  for (const unsigned *SR =3D tri_->getSubRegisters(SpillReg); *SR; ++SR)
-    if (hasInterval(*SR))
-      PRegs.push_back(*SR);
-
-  DEBUG({
-    dbgs() << "Trying to spill:";
-    for (unsigned i =3D 0, e =3D PRegs.size(); i !=3D e; ++i)
-      dbgs() << ' ' << tri_->getName(PRegs[i]);
-    dbgs() << '\n';
-  });
-
-  SmallPtrSet<MachineInstr*, 8> SeenMIs;
-  for (MachineRegisterInfo::reg_iterator I =3D mri_->reg_begin(li.reg),
-         E =3D mri_->reg_end(); I !=3D E; ++I) {
-    MachineOperand &O =3D I.getOperand();
-    MachineInstr *MI =3D O.getParent();
-    if (MI->isDebugValue() || SeenMIs.count(MI))
-      continue;
-    SeenMIs.insert(MI);
-    SlotIndex Index =3D getInstructionIndex(MI);
-    bool LiveReg =3D false;
-    for (unsigned i =3D 0, e =3D PRegs.size(); i !=3D e; ++i) {
-      unsigned PReg =3D PRegs[i];
-      LiveInterval &pli =3D getInterval(PReg);
-      if (!pli.liveAt(Index))
-        continue;
-      LiveReg =3D true;
-      SlotIndex StartIdx =3D Index.getLoadIndex();
-      SlotIndex EndIdx =3D Index.getNextIndex().getBaseIndex();
-      if (!pli.isInOneLiveRange(StartIdx, EndIdx)) {
-        std::string msg;
-        raw_string_ostream Msg(msg);
-        Msg << "Ran out of registers during register allocation!";
-        if (MI->isInlineAsm()) {
-          Msg << "\nPlease check your inline asm statement for invalid "
-              << "constraints:\n";
-          MI->print(Msg, tm_);
-        }
-        report_fatal_error(Msg.str());
-      }
-      pli.removeRange(StartIdx, EndIdx);
-      LiveReg =3D true;
-    }
-    if (!LiveReg)
-      continue;
-    DEBUG(dbgs() << "Emergency spill around " << Index << '\t' << *MI);
-    vrm.addEmergencySpill(SpillReg, MI);
-    Cut =3D true;
-  }
-  return Cut;
-}
-
 LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
                                                   MachineInstr* startInst)=
 {
   LiveInterval& Interval =3D getOrCreateInterval(reg);
   VNInfo* VN =3D Interval.getNextValue(
-    SlotIndex(getInstructionIndex(startInst).getDefIndex()),
-    startInst, getVNInfoAllocator());
+    SlotIndex(getInstructionIndex(startInst).getRegSlot()),
+    getVNInfoAllocator());
   VN->setHasPHIKill(true);
   LiveRange LR(
-     SlotIndex(getInstructionIndex(startInst).getDefIndex()),
+     SlotIndex(getInstructionIndex(startInst).getRegSlot()),
      getMBBEndIdx(startInst->getParent()), VN);
   Interval.addRange(LR);
=20
   return LR;
 }
=20
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//                          Register mask functions
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
+                                             BitVector &UsableRegs) {
+  if (LI.empty())
+    return false;
+  LiveInterval::iterator LiveI =3D LI.begin(), LiveE =3D LI.end();
+
+  // Use a smaller arrays for local live ranges.
+  ArrayRef<SlotIndex> Slots;
+  ArrayRef<const uint32_t*> Bits;
+  if (MachineBasicBlock *MBB =3D intervalIsInOneMBB(LI)) {
+    Slots =3D getRegMaskSlotsInBlock(MBB->getNumber());
+    Bits =3D getRegMaskBitsInBlock(MBB->getNumber());
+  } else {
+    Slots =3D getRegMaskSlots();
+    Bits =3D getRegMaskBits();
+  }
+
+  // We are going to enumerate all the register mask slots contained in LI.
+  // Start with a binary search of RegMaskSlots to find a starting point.
+  ArrayRef<SlotIndex>::iterator SlotI =3D
+    std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
+  ArrayRef<SlotIndex>::iterator SlotE =3D Slots.end();
+
+  // No slots in range, LI begins after the last call.
+  if (SlotI =3D=3D SlotE)
+    return false;
+
+  bool Found =3D false;
+  for (;;) {
+    assert(*SlotI >=3D LiveI->start);
+    // Loop over all slots overlapping this segment.
+    while (*SlotI < LiveI->end) {
+      // *SlotI overlaps LI. Collect mask bits.
+      if (!Found) {
+        // This is the first overlap. Initialize UsableRegs to all ones.
+        UsableRegs.clear();
+        UsableRegs.resize(tri_->getNumRegs(), true);
+        Found =3D true;
+      }
+      // Remove usable registers clobbered by this mask.
+      UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
+      if (++SlotI =3D=3D SlotE)
+        return Found;
+    }
+    // *SlotI is beyond the current LI segment.
+    LiveI =3D LI.advanceTo(LiveI, *SlotI);
+    if (LiveI =3D=3D LiveE)
+      return Found;
+    // Advance SlotI until it overlaps.
+    while (*SlotI < LiveI->start)
+      if (++SlotI =3D=3D SlotE)
+        return Found;
+  }
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//                         IntervalUpdate class.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+// HMEditor is a toolkit used by handleMove to trim or extend live interva=
ls.
+class LiveIntervals::HMEditor {
+private:
+  LiveIntervals& LIS;
+  const MachineRegisterInfo& MRI;
+  const TargetRegisterInfo& TRI;
+  SlotIndex NewIdx;
+
+  typedef std::pair<LiveInterval*, LiveRange*> IntRangePair;
+  typedef DenseSet<IntRangePair> RangeSet;
+
+  struct RegRanges {
+    LiveRange* Use;
+    LiveRange* EC;
+    LiveRange* Dead;
+    LiveRange* Def;
+    RegRanges() : Use(0), EC(0), Dead(0), Def(0) {}
+  };
+  typedef DenseMap<unsigned, RegRanges> BundleRanges;
+
+public:
+  HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
+           const TargetRegisterInfo& TRI, SlotIndex NewIdx)
+    : LIS(LIS), MRI(MRI), TRI(TRI), NewIdx(NewIdx) {}
+
+  // Update intervals for all operands of MI from OldIdx to NewIdx.
+  // This assumes that MI used to be at OldIdx, and now resides at
+  // NewIdx.
+  void moveAllRangesFrom(MachineInstr* MI, SlotIndex OldIdx) {
+    assert(NewIdx !=3D OldIdx && "No-op move? That's a bit strange.");
+
+    // Collect the operands.
+    RangeSet Entering, Internal, Exiting;
+    bool hasRegMaskOp =3D false;
+    collectRanges(MI, Entering, Internal, Exiting, hasRegMaskOp, OldIdx);
+
+    // To keep the LiveRanges valid within an interval, move the ranges cl=
osest
+    // to the destination first. This prevents ranges from overlapping, to=
 that
+    // APIs like removeRange still work.
+    if (NewIdx < OldIdx) {
+      moveAllEnteringFrom(OldIdx, Entering);
+      moveAllInternalFrom(OldIdx, Internal);
+      moveAllExitingFrom(OldIdx, Exiting);
+    }
+    else {
+      moveAllExitingFrom(OldIdx, Exiting);
+      moveAllInternalFrom(OldIdx, Internal);
+      moveAllEnteringFrom(OldIdx, Entering);
+    }
+
+    if (hasRegMaskOp)
+      updateRegMaskSlots(OldIdx);
+
+#ifndef NDEBUG
+    LIValidator validator;
+    std::for_each(Entering.begin(), Entering.end(), validator);
+    std::for_each(Internal.begin(), Internal.end(), validator);
+    std::for_each(Exiting.begin(), Exiting.end(), validator);
+    assert(validator.rangesOk() && "moveAllOperandsFrom broke liveness.");
+#endif
+
+  }
+
+  // Update intervals for all operands of MI to refer to BundleStart's
+  // SlotIndex.
+  void moveAllRangesInto(MachineInstr* MI, MachineInstr* BundleStart) {
+    if (MI =3D=3D BundleStart)
+      return; // Bundling instr with itself - nothing to do.
+
+    SlotIndex OldIdx =3D LIS.getSlotIndexes()->getInstructionIndex(MI);
+    assert(LIS.getSlotIndexes()->getInstructionFromIndex(OldIdx) =3D=3D MI=
 &&
+           "SlotIndex <-> Instruction mapping broken for MI");
+
+    // Collect all ranges already in the bundle.
+    MachineBasicBlock::instr_iterator BII(BundleStart);
+    RangeSet Entering, Internal, Exiting;
+    bool hasRegMaskOp =3D false;
+    collectRanges(BII, Entering, Internal, Exiting, hasRegMaskOp, NewIdx);
+    assert(!hasRegMaskOp && "Can't have RegMask operand in bundle.");
+    for (++BII; &*BII =3D=3D MI || BII->isInsideBundle(); ++BII) {
+      if (&*BII =3D=3D MI)
+        continue;
+      collectRanges(BII, Entering, Internal, Exiting, hasRegMaskOp, NewIdx=
);
+      assert(!hasRegMaskOp && "Can't have RegMask operand in bundle.");
+    }
+
+    BundleRanges BR =3D createBundleRanges(Entering, Internal, Exiting);
+
+    collectRanges(MI, Entering, Internal, Exiting, hasRegMaskOp, OldIdx);
+    assert(!hasRegMaskOp && "Can't have RegMask operand in bundle.");
+
+    DEBUG(dbgs() << "Entering: " << Entering.size() << "\n");
+    DEBUG(dbgs() << "Internal: " << Internal.size() << "\n");
+    DEBUG(dbgs() << "Exiting: " << Exiting.size() << "\n");
+
+    moveAllEnteringFromInto(OldIdx, Entering, BR);
+    moveAllInternalFromInto(OldIdx, Internal, BR);
+    moveAllExitingFromInto(OldIdx, Exiting, BR);
+
+
+#ifndef NDEBUG
+    LIValidator validator;
+    std::for_each(Entering.begin(), Entering.end(), validator);
+    std::for_each(Internal.begin(), Internal.end(), validator);
+    std::for_each(Exiting.begin(), Exiting.end(), validator);
+    assert(validator.rangesOk() && "moveAllOperandsInto broke liveness.");
+#endif
+  }
+
+private:
+
+#ifndef NDEBUG
+  class LIValidator {
+  private:
+    DenseSet<const LiveInterval*> Checked, Bogus;
+  public:
+    void operator()(const IntRangePair& P) {
+      const LiveInterval* LI =3D P.first;
+      if (Checked.count(LI))
+        return;
+      Checked.insert(LI);
+      if (LI->empty())
+        return;
+      SlotIndex LastEnd =3D LI->begin()->start;
+      for (LiveInterval::const_iterator LRI =3D LI->begin(), LRE =3D LI->e=
nd();
+           LRI !=3D LRE; ++LRI) {
+        const LiveRange& LR =3D *LRI;
+        if (LastEnd > LR.start || LR.start >=3D LR.end)
+          Bogus.insert(LI);
+        LastEnd =3D LR.end;
+      }
+    }
+
+    bool rangesOk() const {
+      return Bogus.empty();
+    }
+  };
+#endif
+
+  // Collect IntRangePairs for all operands of MI that may need fixing.
+  // Treat's MI's index as OldIdx (regardless of what it is in SlotIndexes'
+  // maps).
+  void collectRanges(MachineInstr* MI, RangeSet& Entering, RangeSet& Inter=
nal,
+                     RangeSet& Exiting, bool& hasRegMaskOp, SlotIndex OldI=
dx) {
+    hasRegMaskOp =3D false;
+    for (MachineInstr::mop_iterator MOI =3D MI->operands_begin(),
+                                    MOE =3D MI->operands_end();
+         MOI !=3D MOE; ++MOI) {
+      const MachineOperand& MO =3D *MOI;
+
+      if (MO.isRegMask()) {
+        hasRegMaskOp =3D true;
+        continue;
+      }
+
+      if (!MO.isReg() || MO.getReg() =3D=3D 0)
+        continue;
+
+      unsigned Reg =3D MO.getReg();
+
+      // TODO: Currently we're skipping uses that are reserved or have no
+      // interval, but we're not updating their kills. This should be
+      // fixed.
+      if (!LIS.hasInterval(Reg) ||
+          (TargetRegisterInfo::isPhysicalRegister(Reg) && LIS.isReserved(R=
eg)))
+        continue;
+
+      LiveInterval* LI =3D &LIS.getInterval(Reg);
+
+      if (MO.readsReg()) {
+        LiveRange* LR =3D LI->getLiveRangeContaining(OldIdx);
+        if (LR !=3D 0)
+          Entering.insert(std::make_pair(LI, LR));
+      }
+      if (MO.isDef()) {
+        if (MO.isEarlyClobber()) {
+          LiveRange* LR =3D LI->getLiveRangeContaining(OldIdx.getRegSlot(t=
rue));
+          assert(LR !=3D 0 && "No EC range?");
+          if (LR->end > OldIdx.getDeadSlot())
+            Exiting.insert(std::make_pair(LI, LR));
+          else
+            Internal.insert(std::make_pair(LI, LR));
+        } else if (MO.isDead()) {
+          LiveRange* LR =3D LI->getLiveRangeContaining(OldIdx.getRegSlot()=
);
+          assert(LR !=3D 0 && "No dead-def range?");
+          Internal.insert(std::make_pair(LI, LR));
+        } else {
+          LiveRange* LR =3D LI->getLiveRangeContaining(OldIdx.getDeadSlot(=
));
+          assert(LR && LR->end > OldIdx.getDeadSlot() &&
+                 "Non-dead-def should have live range exiting.");
+          Exiting.insert(std::make_pair(LI, LR));
+        }
+      }
+    }
+  }
+
+  // Collect IntRangePairs for all operands of MI that may need fixing.
+  void collectRangesInBundle(MachineInstr* MI, RangeSet& Entering,
+                             RangeSet& Exiting, SlotIndex MIStartIdx,
+                             SlotIndex MIEndIdx) {
+    for (MachineInstr::mop_iterator MOI =3D MI->operands_begin(),
+                                    MOE =3D MI->operands_end();
+         MOI !=3D MOE; ++MOI) {
+      const MachineOperand& MO =3D *MOI;
+      assert(!MO.isRegMask() && "Can't have RegMasks in bundles.");
+      if (!MO.isReg() || MO.getReg() =3D=3D 0)
+        continue;
+
+      unsigned Reg =3D MO.getReg();
+
+      // TODO: Currently we're skipping uses that are reserved or have no
+      // interval, but we're not updating their kills. This should be
+      // fixed.
+      if (!LIS.hasInterval(Reg) ||
+          (TargetRegisterInfo::isPhysicalRegister(Reg) && LIS.isReserved(R=
eg)))
+        continue;
+
+      LiveInterval* LI =3D &LIS.getInterval(Reg);
+
+      if (MO.readsReg()) {
+        LiveRange* LR =3D LI->getLiveRangeContaining(MIStartIdx);
+        if (LR !=3D 0)
+          Entering.insert(std::make_pair(LI, LR));
+      }
+      if (MO.isDef()) {
+        assert(!MO.isEarlyClobber() && "Early clobbers not allowed in bund=
les.");
+        assert(!MO.isDead() && "Dead-defs not allowed in bundles.");
+        LiveRange* LR =3D LI->getLiveRangeContaining(MIEndIdx.getDeadSlot(=
));
+        assert(LR !=3D 0 && "Internal ranges not allowed in bundles.");
+        Exiting.insert(std::make_pair(LI, LR));
+      }
+    }
+  }
+
+  BundleRanges createBundleRanges(RangeSet& Entering, RangeSet& Internal, =
RangeSet& Exiting) {
+    BundleRanges BR;
+
+    for (RangeSet::iterator EI =3D Entering.begin(), EE =3D Entering.end();
+         EI !=3D EE; ++EI) {
+      LiveInterval* LI =3D EI->first;
+      LiveRange* LR =3D EI->second;
+      BR[LI->reg].Use =3D LR;
+    }
+
+    for (RangeSet::iterator II =3D Internal.begin(), IE =3D Internal.end();
+         II !=3D IE; ++II) {
+      LiveInterval* LI =3D II->first;
+      LiveRange* LR =3D II->second;
+      if (LR->end.isDead()) {
+        BR[LI->reg].Dead =3D LR;
+      } else {
+        BR[LI->reg].EC =3D LR;
+      }
+    }
+
+    for (RangeSet::iterator EI =3D Exiting.begin(), EE =3D Exiting.end();
+         EI !=3D EE; ++EI) {
+      LiveInterval* LI =3D EI->first;
+      LiveRange* LR =3D EI->second;
+      BR[LI->reg].Def =3D LR;
+    }
+
+    return BR;
+  }
+
+  void moveKillFlags(unsigned reg, SlotIndex OldIdx, SlotIndex newKillIdx)=
 {
+    MachineInstr* OldKillMI =3D LIS.getInstructionFromIndex(OldIdx);
+    if (!OldKillMI->killsRegister(reg))
+      return; // Bail out if we don't have kill flags on the old register.
+    MachineInstr* NewKillMI =3D LIS.getInstructionFromIndex(newKillIdx);
+    assert(OldKillMI->killsRegister(reg) && "Old 'kill' instr isn't a kill=
.");
+    assert(!NewKillMI->killsRegister(reg) && "New kill instr is already a =
kill.");
+    OldKillMI->clearRegisterKills(reg, &TRI);
+    NewKillMI->addRegisterKilled(reg, &TRI);
+  }
+
+  void updateRegMaskSlots(SlotIndex OldIdx) {
+    SmallVectorImpl<SlotIndex>::iterator RI =3D
+      std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
+                       OldIdx);
+    assert(*RI =3D=3D OldIdx && "No RegMask at OldIdx.");
+    *RI =3D NewIdx;
+    assert(*prior(RI) < *RI && *RI < *next(RI) &&
+           "RegSlots out of order. Did you move one call across another?");
+  }
+
+  // Return the last use of reg between NewIdx and OldIdx.
+  SlotIndex findLastUseBefore(unsigned Reg, SlotIndex OldIdx) {
+    SlotIndex LastUse =3D NewIdx;
+    for (MachineRegisterInfo::use_nodbg_iterator
+           UI =3D MRI.use_nodbg_begin(Reg),
+           UE =3D MRI.use_nodbg_end();
+         UI !=3D UE; UI.skipInstruction()) {
+      const MachineInstr* MI =3D &*UI;
+      SlotIndex InstSlot =3D LIS.getSlotIndexes()->getInstructionIndex(MI);
+      if (InstSlot > LastUse && InstSlot < OldIdx)
+        LastUse =3D InstSlot;
+    }
+    return LastUse;
+  }
+
+  void moveEnteringUpFrom(SlotIndex OldIdx, IntRangePair& P) {
+    LiveInterval* LI =3D P.first;
+    LiveRange* LR =3D P.second;
+    bool LiveThrough =3D LR->end > OldIdx.getRegSlot();
+    if (LiveThrough)
+      return;
+    SlotIndex LastUse =3D findLastUseBefore(LI->reg, OldIdx);
+    if (LastUse !=3D NewIdx)
+      moveKillFlags(LI->reg, NewIdx, LastUse);
+    LR->end =3D LastUse.getRegSlot();
+  }
+
+  void moveEnteringDownFrom(SlotIndex OldIdx, IntRangePair& P) {
+    LiveInterval* LI =3D P.first;
+    LiveRange* LR =3D P.second;
+    // Extend the LiveRange if NewIdx is past the end.
+    if (NewIdx > LR->end) {
+      // Move kill flags if OldIdx was not originally the end
+      // (otherwise LR->end points to an invalid slot).
+      if (LR->end.getRegSlot() !=3D OldIdx.getRegSlot()) {
+        assert(LR->end > OldIdx && "LiveRange does not cover original slot=
");
+        moveKillFlags(LI->reg, LR->end, NewIdx);
+      }
+      LR->end =3D NewIdx.getRegSlot();
+    }
+  }
+
+  void moveAllEnteringFrom(SlotIndex OldIdx, RangeSet& Entering) {
+    bool GoingUp =3D NewIdx < OldIdx;
+
+    if (GoingUp) {
+      for (RangeSet::iterator EI =3D Entering.begin(), EE =3D Entering.end=
();
+           EI !=3D EE; ++EI)
+        moveEnteringUpFrom(OldIdx, *EI);
+    } else {
+      for (RangeSet::iterator EI =3D Entering.begin(), EE =3D Entering.end=
();
+           EI !=3D EE; ++EI)
+        moveEnteringDownFrom(OldIdx, *EI);
+    }
+  }
+
+  void moveInternalFrom(SlotIndex OldIdx, IntRangePair& P) {
+    LiveInterval* LI =3D P.first;
+    LiveRange* LR =3D P.second;
+    assert(OldIdx < LR->start && LR->start < OldIdx.getDeadSlot() &&
+           LR->end <=3D OldIdx.getDeadSlot() &&
+           "Range should be internal to OldIdx.");
+    LiveRange Tmp(*LR);
+    Tmp.start =3D NewIdx.getRegSlot(LR->start.isEarlyClobber());
+    Tmp.valno->def =3D Tmp.start;
+    Tmp.end =3D LR->end.isDead() ? NewIdx.getDeadSlot() : NewIdx.getRegSlo=
t();
+    LI->removeRange(*LR);
+    LI->addRange(Tmp);
+  }
+
+  void moveAllInternalFrom(SlotIndex OldIdx, RangeSet& Internal) {
+    for (RangeSet::iterator II =3D Internal.begin(), IE =3D Internal.end();
+         II !=3D IE; ++II)
+      moveInternalFrom(OldIdx, *II);
+  }
+
+  void moveExitingFrom(SlotIndex OldIdx, IntRangePair& P) {
+    LiveRange* LR =3D P.second;
+    assert(OldIdx < LR->start && LR->start < OldIdx.getDeadSlot() &&
+           "Range should start in OldIdx.");
+    assert(LR->end > OldIdx.getDeadSlot() && "Range should exit OldIdx.");
+    SlotIndex NewStart =3D NewIdx.getRegSlot(LR->start.isEarlyClobber());
+    LR->start =3D NewStart;
+    LR->valno->def =3D NewStart;
+  }
+
+  void moveAllExitingFrom(SlotIndex OldIdx, RangeSet& Exiting) {
+    for (RangeSet::iterator EI =3D Exiting.begin(), EE =3D Exiting.end();
+         EI !=3D EE; ++EI)
+      moveExitingFrom(OldIdx, *EI);
+  }
+
+  void moveEnteringUpFromInto(SlotIndex OldIdx, IntRangePair& P,
+                              BundleRanges& BR) {
+    LiveInterval* LI =3D P.first;
+    LiveRange* LR =3D P.second;
+    bool LiveThrough =3D LR->end > OldIdx.getRegSlot();
+    if (LiveThrough) {
+      assert((LR->start < NewIdx || BR[LI->reg].Def =3D=3D LR) &&
+             "Def in bundle should be def range.");
+      assert((BR[LI->reg].Use =3D=3D 0 || BR[LI->reg].Use =3D=3D LR) &&
+             "If bundle has use for this reg it should be LR.");
+      BR[LI->reg].Use =3D LR;
+      return;
+    }
+
+    SlotIndex LastUse =3D findLastUseBefore(LI->reg, OldIdx);
+    moveKillFlags(LI->reg, OldIdx, LastUse);
+
+    if (LR->start < NewIdx) {
+      // Becoming a new entering range.
+      assert(BR[LI->reg].Dead =3D=3D 0 && BR[LI->reg].Def =3D=3D 0 &&
+             "Bundle shouldn't be re-defining reg mid-range.");
+      assert((BR[LI->reg].Use =3D=3D 0 || BR[LI->reg].Use =3D=3D LR) &&
+             "Bundle shouldn't have different use range for same reg.");
+      LR->end =3D LastUse.getRegSlot();
+      BR[LI->reg].Use =3D LR;
+    } else {
+      // Becoming a new Dead-def.
+      assert(LR->start =3D=3D NewIdx.getRegSlot(LR->start.isEarlyClobber()=
) &&
+             "Live range starting at unexpected slot.");
+      assert(BR[LI->reg].Def =3D=3D LR && "Reg should have def range.");
+      assert(BR[LI->reg].Dead =3D=3D 0 &&
+               "Can't have def and dead def of same reg in a bundle.");
+      LR->end =3D LastUse.getDeadSlot();
+      BR[LI->reg].Dead =3D BR[LI->reg].Def;
+      BR[LI->reg].Def =3D 0;
+    }
+  }
+
+  void moveEnteringDownFromInto(SlotIndex OldIdx, IntRangePair& P,
+                                BundleRanges& BR) {
+    LiveInterval* LI =3D P.first;
+    LiveRange* LR =3D P.second;
+    if (NewIdx > LR->end) {
+      // Range extended to bundle. Add to bundle uses.
+      // Note: Currently adds kill flags to bundle start.
+      assert(BR[LI->reg].Use =3D=3D 0 &&
+             "Bundle already has use range for reg.");
+      moveKillFlags(LI->reg, LR->end, NewIdx);
+      LR->end =3D NewIdx.getRegSlot();
+      BR[LI->reg].Use =3D LR;
+    } else {
+      assert(BR[LI->reg].Use !=3D 0 &&
+             "Bundle should already have a use range for reg.");
+    }
+  }
+
+  void moveAllEnteringFromInto(SlotIndex OldIdx, RangeSet& Entering,
+                               BundleRanges& BR) {
+    bool GoingUp =3D NewIdx < OldIdx;
+
+    if (GoingUp) {
+      for (RangeSet::iterator EI =3D Entering.begin(), EE =3D Entering.end=
();
+           EI !=3D EE; ++EI)
+        moveEnteringUpFromInto(OldIdx, *EI, BR);
+    } else {
+      for (RangeSet::iterator EI =3D Entering.begin(), EE =3D Entering.end=
();
+           EI !=3D EE; ++EI)
+        moveEnteringDownFromInto(OldIdx, *EI, BR);
+    }
+  }
+
+  void moveInternalFromInto(SlotIndex OldIdx, IntRangePair& P,
+                            BundleRanges& BR) {
+    // TODO: Sane rules for moving ranges into bundles.
+  }
+
+  void moveAllInternalFromInto(SlotIndex OldIdx, RangeSet& Internal,
+                               BundleRanges& BR) {
+    for (RangeSet::iterator II =3D Internal.begin(), IE =3D Internal.end();
+         II !=3D IE; ++II)
+      moveInternalFromInto(OldIdx, *II, BR);
+  }
+
+  void moveExitingFromInto(SlotIndex OldIdx, IntRangePair& P,
+                           BundleRanges& BR) {
+    LiveInterval* LI =3D P.first;
+    LiveRange* LR =3D P.second;
+
+    assert(LR->start.isRegister() &&
+           "Don't know how to merge exiting ECs into bundles yet.");
+
+    if (LR->end > NewIdx.getDeadSlot()) {
+      // This range is becoming an exiting range on the bundle.
+      // If there was an old dead-def of this reg, delete it.
+      if (BR[LI->reg].Dead !=3D 0) {
+        LI->removeRange(*BR[LI->reg].Dead);
+        BR[LI->reg].Dead =3D 0;
+      }
+      assert(BR[LI->reg].Def =3D=3D 0 &&
+             "Can't have two defs for the same variable exiting a bundle."=
);
+      LR->start =3D NewIdx.getRegSlot();
+      LR->valno->def =3D LR->start;
+      BR[LI->reg].Def =3D LR;
+    } else {
+      // This range is becoming internal to the bundle.
+      assert(LR->end =3D=3D NewIdx.getRegSlot() &&
+             "Can't bundle def whose kill is before the bundle");
+      if (BR[LI->reg].Dead || BR[LI->reg].Def) {
+        // Already have a def for this. Just delete range.
+        LI->removeRange(*LR);
+      } else {
+        // Make range dead, record.
+        LR->end =3D NewIdx.getDeadSlot();
+        BR[LI->reg].Dead =3D LR;
+        assert(BR[LI->reg].Use =3D=3D LR &&
+               "Range becoming dead should currently be use.");
+      }
+      // In both cases the range is no longer a use on the bundle.
+      BR[LI->reg].Use =3D 0;
+    }
+  }
+
+  void moveAllExitingFromInto(SlotIndex OldIdx, RangeSet& Exiting,
+                              BundleRanges& BR) {
+    for (RangeSet::iterator EI =3D Exiting.begin(), EE =3D Exiting.end();
+         EI !=3D EE; ++EI)
+      moveExitingFromInto(OldIdx, *EI, BR);
+  }
+
+};
+
+void LiveIntervals::handleMove(MachineInstr* MI) {
+  SlotIndex OldIndex =3D indexes_->getInstructionIndex(MI);
+  indexes_->removeMachineInstrFromMaps(MI);
+  SlotIndex NewIndex =3D MI->isInsideBundle() ?
+                        indexes_->getInstructionIndex(MI) :
+                        indexes_->insertMachineInstrInMaps(MI);
+  assert(getMBBStartIdx(MI->getParent()) <=3D OldIndex &&
+         OldIndex < getMBBEndIdx(MI->getParent()) &&
+         "Cannot handle moves across basic block boundaries.");
+  assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
+
+  HMEditor HME(*this, *mri_, *tri_, NewIndex);
+  HME.moveAllRangesFrom(MI, OldIndex);
+}
+
+void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI, MachineInstr* B=
undleStart) {
+  SlotIndex NewIndex =3D indexes_->getInstructionIndex(BundleStart);
+  HMEditor HME(*this, *mri_, *tri_, NewIndex);
+  HME.moveAllRangesInto(MI, BundleStart);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveInte=
rvalUnion.cpp
--- a/head/contrib/llvm/lib/CodeGen/LiveIntervalUnion.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveIntervalUnion.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -21,6 +21,8 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetRegisterInfo.h"
=20
+#include <algorithm>
+
 using namespace llvm;
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveInte=
rvalUnion.h
--- a/head/contrib/llvm/lib/CodeGen/LiveIntervalUnion.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveIntervalUnion.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -20,8 +20,6 @@
 #include "llvm/ADT/IntervalMap.h"
 #include "llvm/CodeGen/LiveInterval.h"
=20
-#include <algorithm>
-
 namespace llvm {
=20
 class MachineLoopRange;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveRang=
eCalc.cpp
--- a/head/contrib/llvm/lib/CodeGen/LiveRangeCalc.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveRangeCalc.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -65,7 +65,7 @@
   assert(DomTree && "Missing dominator tree");
=20
   MachineBasicBlock *KillMBB =3D Indexes->getMBBFromIndex(Kill.getPrevSlot=
());
-  assert(Kill && "No MBB at Kill");
+  assert(KillMBB && "No MBB at Kill");
=20
   // Is there a def in the same MBB we can extend?
   if (LI->extendInBlock(Indexes->getMBBStartIdx(KillMBB), Kill))
@@ -237,7 +237,7 @@
         assert(Alloc && "Need VNInfo allocator to create PHI-defs");
         SlotIndex Start, End;
         tie(Start, End) =3D Indexes->getMBBRange(MBB);
-        VNInfo *VNI =3D I->LI->getNextValue(Start, 0, *Alloc);
+        VNInfo *VNI =3D I->LI->getNextValue(Start, *Alloc);
         VNI->setIsPHIDef(true);
         I->Value =3D VNI;
         // This block is done, we know the final value.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveRang=
eEdit.cpp
--- a/head/contrib/llvm/lib/CodeGen/LiveRangeEdit.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveRangeEdit.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D--- LiveRangeEdit.cpp - Basic tools for editing a register live=
 range --=3D=3D=3D//
+//=3D=3D=3D-- LiveRangeEdit.cpp - Basic tools for editing a register live =
range -=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,12 +12,12 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "regalloc"
-#include "LiveRangeEdit.h"
 #include "VirtRegMap.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/CodeGen/CalcSpillWeights.h"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "llvm/CodeGen/LiveRangeEdit.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Support/Debug.h"
@@ -29,13 +29,14 @@
 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE"=
);
 STATISTIC(NumFracRanges,     "Number of live ranges fractured by DCE");
=20
-LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg,
-                                        LiveIntervals &LIS,
-                                        VirtRegMap &VRM) {
-  MachineRegisterInfo &MRI =3D VRM.getRegInfo();
+void LiveRangeEdit::Delegate::anchor() { }
+
+LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) {
   unsigned VReg =3D MRI.createVirtualRegister(MRI.getRegClass(OldReg));
-  VRM.grow();
-  VRM.setIsSplitFromReg(VReg, VRM.getOriginal(OldReg));
+  if (VRM) {
+    VRM->grow();
+    VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
+  }
   LiveInterval &LI =3D LIS.getOrCreateInterval(VReg);
   newRegs_.push_back(&LI);
   return LI;
@@ -43,37 +44,32 @@
=20
 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
                                           const MachineInstr *DefMI,
-                                          const TargetInstrInfo &tii,
                                           AliasAnalysis *aa) {
   assert(DefMI && "Missing instruction");
   scannedRemattable_ =3D true;
-  if (!tii.isTriviallyReMaterializable(DefMI, aa))
+  if (!TII.isTriviallyReMaterializable(DefMI, aa))
     return false;
   remattable_.insert(VNI);
   return true;
 }
=20
-void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
-                                   const TargetInstrInfo &tii,
-                                   AliasAnalysis *aa) {
+void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
   for (LiveInterval::vni_iterator I =3D parent_.vni_begin(),
        E =3D parent_.vni_end(); I !=3D E; ++I) {
     VNInfo *VNI =3D *I;
     if (VNI->isUnused())
       continue;
-    MachineInstr *DefMI =3D lis.getInstructionFromIndex(VNI->def);
+    MachineInstr *DefMI =3D LIS.getInstructionFromIndex(VNI->def);
     if (!DefMI)
       continue;
-    checkRematerializable(VNI, DefMI, tii, aa);
+    checkRematerializable(VNI, DefMI, aa);
   }
   scannedRemattable_ =3D true;
 }
=20
-bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
-                                        const TargetInstrInfo &tii,
-                                        AliasAnalysis *aa) {
+bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
   if (!scannedRemattable_)
-    scanRemattable(lis, tii, aa);
+    scanRemattable(aa);
   return !remattable_.empty();
 }
=20
@@ -81,24 +77,18 @@
 /// OrigIdx are also available with the same value at UseIdx.
 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
                                        SlotIndex OrigIdx,
-                                       SlotIndex UseIdx,
-                                       LiveIntervals &lis) {
-  OrigIdx =3D OrigIdx.getUseIndex();
-  UseIdx =3D UseIdx.getUseIndex();
+                                       SlotIndex UseIdx) {
+  OrigIdx =3D OrigIdx.getRegSlot(true);
+  UseIdx =3D UseIdx.getRegSlot(true);
   for (unsigned i =3D 0, e =3D OrigMI->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D OrigMI->getOperand(i);
     if (!MO.isReg() || !MO.getReg() || MO.isDef())
       continue;
     // Reserved registers are OK.
-    if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
+    if (MO.isUndef() || !LIS.hasInterval(MO.getReg()))
       continue;
-    // We cannot depend on virtual registers in uselessRegs_.
-    if (uselessRegs_)
-      for (unsigned ui =3D 0, ue =3D uselessRegs_->size(); ui !=3D ue; ++u=
i)
-        if ((*uselessRegs_)[ui]->reg =3D=3D MO.getReg())
-          return false;
=20
-    LiveInterval &li =3D lis.getInterval(MO.getReg());
+    LiveInterval &li =3D LIS.getInterval(MO.getReg());
     const VNInfo *OVNI =3D li.getVNInfoAt(OrigIdx);
     if (!OVNI)
       continue;
@@ -110,8 +100,7 @@
=20
 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
                                        SlotIndex UseIdx,
-                                       bool cheapAsAMove,
-                                       LiveIntervals &lis) {
+                                       bool cheapAsAMove) {
   assert(scannedRemattable_ && "Call anyRematerializable first");
=20
   // Use scanRemattable info.
@@ -121,19 +110,19 @@
   // No defining instruction provided.
   SlotIndex DefIdx;
   if (RM.OrigMI)
-    DefIdx =3D lis.getInstructionIndex(RM.OrigMI);
+    DefIdx =3D LIS.getInstructionIndex(RM.OrigMI);
   else {
     DefIdx =3D RM.ParentVNI->def;
-    RM.OrigMI =3D lis.getInstructionFromIndex(DefIdx);
+    RM.OrigMI =3D LIS.getInstructionFromIndex(DefIdx);
     assert(RM.OrigMI && "No defining instruction for remattable value");
   }
=20
   // If only cheap remats were requested, bail out early.
-  if (cheapAsAMove && !RM.OrigMI->getDesc().isAsCheapAsAMove())
+  if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
     return false;
=20
   // Verify that all used registers are available with the same values.
-  if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx, lis))
+  if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
     return false;
=20
   return true;
@@ -143,27 +132,22 @@
                                          MachineBasicBlock::iterator MI,
                                          unsigned DestReg,
                                          const Remat &RM,
-                                         LiveIntervals &lis,
-                                         const TargetInstrInfo &tii,
                                          const TargetRegisterInfo &tri,
                                          bool Late) {
   assert(RM.OrigMI && "Invalid remat");
-  tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
+  TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
   rematted_.insert(RM.ParentVNI);
-  return lis.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
-           .getDefIndex();
+  return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
+           .getRegSlot();
 }
=20
-void LiveRangeEdit::eraseVirtReg(unsigned Reg, LiveIntervals &LIS) {
+void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
   if (delegate_ && delegate_->LRE_CanEraseVirtReg(Reg))
     LIS.removeInterval(Reg);
 }
=20
 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
-                               SmallVectorImpl<MachineInstr*> &Dead,
-                               MachineRegisterInfo &MRI,
-                               LiveIntervals &LIS,
-                               const TargetInstrInfo &TII) {
+                               SmallVectorImpl<MachineInstr*> &Dead) {
   MachineInstr *DefMI =3D 0, *UseMI =3D 0;
=20
   // Check that there is a single def and a single use.
@@ -174,7 +158,7 @@
     if (MO.isDef()) {
       if (DefMI && DefMI !=3D MI)
         return false;
-      if (!MI->getDesc().canFoldAsLoad())
+      if (!MI->canFoldAsLoad())
         return false;
       DefMI =3D MI;
     } else if (!MO.isUndef()) {
@@ -209,19 +193,17 @@
 }
=20
 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
-                                      LiveIntervals &LIS, VirtRegMap &VRM,
-                                      const TargetInstrInfo &TII) {
+                                      ArrayRef<unsigned> RegsBeingSpilled)=
 {
   SetVector<LiveInterval*,
             SmallVector<LiveInterval*, 8>,
             SmallPtrSet<LiveInterval*, 8> > ToShrink;
-  MachineRegisterInfo &MRI =3D VRM.getRegInfo();
=20
   for (;;) {
     // Erase all dead defs.
     while (!Dead.empty()) {
       MachineInstr *MI =3D Dead.pop_back_val();
       assert(MI->allDefsAreDead() && "Def isn't really dead");
-      SlotIndex Idx =3D LIS.getInstructionIndex(MI).getDefIndex();
+      SlotIndex Idx =3D LIS.getInstructionIndex(MI).getRegSlot();
=20
       // Never delete inline asm.
       if (MI->isInlineAsm()) {
@@ -265,7 +247,7 @@
             LI.removeValNo(VNI);
             if (LI.empty()) {
               ToShrink.remove(&LI);
-              eraseVirtReg(Reg, LIS);
+              eraseVirtReg(Reg);
             }
           }
         }
@@ -284,12 +266,26 @@
     // Shrink just one live interval. Then delete new dead defs.
     LiveInterval *LI =3D ToShrink.back();
     ToShrink.pop_back();
-    if (foldAsLoad(LI, Dead, MRI, LIS, TII))
+    if (foldAsLoad(LI, Dead))
       continue;
     if (delegate_)
       delegate_->LRE_WillShrinkVirtReg(LI->reg);
     if (!LIS.shrinkToUses(LI, &Dead))
       continue;
+   =20
+    // Don't create new intervals for a register being spilled.
+    // The new intervals would have to be spilled anyway so its not worth =
it.
+    // Also they currently aren't spilled so creating them and not spilling
+    // them results in incorrect code.
+    bool BeingSpilled =3D false;
+    for (unsigned i =3D 0, e =3D RegsBeingSpilled.size(); i !=3D e; ++i) {
+      if (LI->reg =3D=3D RegsBeingSpilled[i]) {
+        BeingSpilled =3D true;
+        break;
+      }
+    }
+   =20
+    if (BeingSpilled) continue;
=20
     // LI may have been separated, create new intervals.
     LI->RenumberValues(LIS);
@@ -298,16 +294,16 @@
     if (NumComp <=3D 1)
       continue;
     ++NumFracRanges;
-    bool IsOriginal =3D VRM.getOriginal(LI->reg) =3D=3D LI->reg;
+    bool IsOriginal =3D VRM && VRM->getOriginal(LI->reg) =3D=3D LI->reg;
     DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
     SmallVector<LiveInterval*, 8> Dups(1, LI);
     for (unsigned i =3D 1; i !=3D NumComp; ++i) {
-      Dups.push_back(&createFrom(LI->reg, LIS, VRM));
+      Dups.push_back(&createFrom(LI->reg));
       // If LI is an original interval that hasn't been split yet, make th=
e new
       // intervals their own originals instead of referring to LI. The ori=
ginal
       // interval must contain all the split products, and LI doesn't.
       if (IsOriginal)
-        VRM.setIsSplitFromReg(Dups.back()->reg, 0);
+        VRM->setIsSplitFromReg(Dups.back()->reg, 0);
       if (delegate_)
         delegate_->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
     }
@@ -316,10 +312,8 @@
 }
=20
 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
-                                             LiveIntervals &LIS,
                                              const MachineLoopInfo &Loops)=
 {
   VirtRegAuxInfo VRAI(MF, LIS, Loops);
-  MachineRegisterInfo &MRI =3D MF.getRegInfo();
   for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I) {
     LiveInterval &LI =3D **I;
     if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LiveVari=
ables.cpp
--- a/head/contrib/llvm/lib/CodeGen/LiveVariables.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LiveVariables.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -14,7 +14,7 @@
 // the instruction, but are never used after the instruction (i.e., they a=
re
 // killed).
 //
-// This class computes live variables using are sparse implementation base=
d on
+// This class computes live variables using a sparse implementation based =
on
 // the machine code SSA form.  This class computes live variable informati=
on for
 // each virtual and _register allocatable_ physical register in a function=
.  It
 // uses the dominance properties of SSA form to efficiently compute live
@@ -33,6 +33,7 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetMachine.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/ADT/DepthFirstIterator.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallSet.h"
@@ -41,6 +42,7 @@
 using namespace llvm;
=20
 char LiveVariables::ID =3D 0;
+char &llvm::LiveVariablesID =3D LiveVariables::ID;
 INITIALIZE_PASS_BEGIN(LiveVariables, "livevars",
                 "Live Variable Analysis", false, false)
 INITIALIZE_PASS_DEPENDENCY(UnreachableMachineBlockElim)
@@ -90,7 +92,7 @@
                                             MachineBasicBlock *MBB,
                                     std::vector<MachineBasicBlock*> &WorkL=
ist) {
   unsigned BBNum =3D MBB->getNumber();
- =20
+
   // Check to see if this basic block is one of the killing blocks.  If so,
   // remove it.
   for (unsigned i =3D 0, e =3D VRInfo.Kills.size(); i !=3D e; ++i)
@@ -98,7 +100,7 @@
       VRInfo.Kills.erase(VRInfo.Kills.begin()+i);  // Erase entry
       break;
     }
- =20
+
   if (MBB =3D=3D DefBlock) return;  // Terminate recursion
=20
   if (VRInfo.AliveBlocks.test(BBNum))
@@ -107,6 +109,7 @@
   // Mark the variable known alive in this bb
   VRInfo.AliveBlocks.set(BBNum);
=20
+  assert(MBB !=3D &MF->front() && "Can't find reaching def for virtreg");
   WorkList.insert(WorkList.end(), MBB->pred_rbegin(), MBB->pred_rend());
 }
=20
@@ -130,7 +133,6 @@
   unsigned BBNum =3D MBB->getNumber();
=20
   VarInfo& VRInfo =3D getVarInfo(reg);
-  VRInfo.NumUses++;
=20
   // Check to see if this basic block is already a kill block.
   if (!VRInfo.Kills.empty() && VRInfo.Kills.back()->getParent() =3D=3D MBB=
) {
@@ -190,7 +192,7 @@
   unsigned LastDefReg =3D 0;
   unsigned LastDefDist =3D 0;
   MachineInstr *LastDef =3D NULL;
-  for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+  for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
        unsigned SubReg =3D *SubRegs; ++SubRegs) {
     MachineInstr *Def =3D PhysRegDef[SubReg];
     if (!Def)
@@ -214,7 +216,7 @@
     unsigned DefReg =3D MO.getReg();
     if (TRI->isSubRegister(Reg, DefReg)) {
       PartDefRegs.insert(DefReg);
-      for (const unsigned *SubRegs =3D TRI->getSubRegisters(DefReg);
+      for (const uint16_t *SubRegs =3D TRI->getSubRegisters(DefReg);
            unsigned SubReg =3D *SubRegs; ++SubRegs)
         PartDefRegs.insert(SubReg);
     }
@@ -245,7 +247,7 @@
                                                            true/*IsImp*/));
       PhysRegDef[Reg] =3D LastPartialDef;
       SmallSet<unsigned, 8> Processed;
-      for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+      for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
            unsigned SubReg =3D *SubRegs; ++SubRegs) {
         if (Processed.count(SubReg))
           continue;
@@ -257,20 +259,19 @@
                                                              false/*IsDef*=
/,
                                                              true/*IsImp*/=
));
         PhysRegDef[SubReg] =3D LastPartialDef;
-        for (const unsigned *SS =3D TRI->getSubRegisters(SubReg); *SS; ++S=
S)
+        for (const uint16_t *SS =3D TRI->getSubRegisters(SubReg); *SS; ++S=
S)
           Processed.insert(*SS);
       }
     }
-  }
-  else if (LastDef && !PhysRegUse[Reg] &&
-           !LastDef->findRegisterDefOperand(Reg))
+  } else if (LastDef && !PhysRegUse[Reg] &&
+             !LastDef->findRegisterDefOperand(Reg))
     // Last def defines the super register, add an implicit def of reg.
-    LastDef->addOperand(MachineOperand::CreateReg(Reg,
-                                                 true/*IsDef*/, true/*IsIm=
p*/));
+    LastDef->addOperand(MachineOperand::CreateReg(Reg, true/*IsDef*/,
+                                                  true/*IsImp*/));
=20
   // Remember this use.
   PhysRegUse[Reg]  =3D MI;
-  for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+  for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
        unsigned SubReg =3D *SubRegs; ++SubRegs)
     PhysRegUse[SubReg] =3D  MI;
 }
@@ -286,7 +287,7 @@
   MachineInstr *LastRefOrPartRef =3D LastUse ? LastUse : LastDef;
   unsigned LastRefOrPartRefDist =3D DistanceMap[LastRefOrPartRef];
   unsigned LastPartDefDist =3D 0;
-  for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+  for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
        unsigned SubReg =3D *SubRegs; ++SubRegs) {
     MachineInstr *Def =3D PhysRegDef[SubReg];
     if (Def && Def !=3D LastDef) {
@@ -331,11 +332,11 @@
   // Or whole register is defined, but only partly used.
   // AX<dead> =3D AL<imp-def>
   //    =3D AL<kill>
-  // AX =3D=20
+  // AX =3D
   MachineInstr *LastPartDef =3D 0;
   unsigned LastPartDefDist =3D 0;
   SmallSet<unsigned, 8> PartUses;
-  for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+  for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
        unsigned SubReg =3D *SubRegs; ++SubRegs) {
     MachineInstr *Def =3D PhysRegDef[SubReg];
     if (Def && Def !=3D LastDef) {
@@ -350,7 +351,7 @@
     }
     if (MachineInstr *Use =3D PhysRegUse[SubReg]) {
       PartUses.insert(SubReg);
-      for (const unsigned *SS =3D TRI->getSubRegisters(SubReg); *SS; ++SS)
+      for (const uint16_t *SS =3D TRI->getSubRegisters(SubReg); *SS; ++SS)
         PartUses.insert(*SS);
       unsigned Dist =3D DistanceMap[Use];
       if (Dist > LastRefOrPartRefDist) {
@@ -366,7 +367,7 @@
     // EAX<dead>  =3D op  AL<imp-def>
     // That is, EAX def is dead but AL def extends pass it.
     PhysRegDef[Reg]->addRegisterDead(Reg, TRI, true);
-    for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+    for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
          unsigned SubReg =3D *SubRegs; ++SubRegs) {
       if (!PartUses.count(SubReg))
         continue;
@@ -387,11 +388,11 @@
       else {
         LastRefOrPartRef->addRegisterKilled(SubReg, TRI, true);
         PhysRegUse[SubReg] =3D LastRefOrPartRef;
-        for (const unsigned *SSRegs =3D TRI->getSubRegisters(SubReg);
+        for (const uint16_t *SSRegs =3D TRI->getSubRegisters(SubReg);
              unsigned SSReg =3D *SSRegs; ++SSRegs)
           PhysRegUse[SSReg] =3D LastRefOrPartRef;
       }
-      for (const unsigned *SS =3D TRI->getSubRegisters(SubReg); *SS; ++SS)
+      for (const uint16_t *SS =3D TRI->getSubRegisters(SubReg); *SS; ++SS)
         PartUses.erase(*SS);
     }
   } else if (LastRefOrPartRef =3D=3D PhysRegDef[Reg] && LastRefOrPartRef !=
=3D MI) {
@@ -419,16 +420,37 @@
   return true;
 }
=20
+void LiveVariables::HandleRegMask(const MachineOperand &MO) {
+  // Call HandlePhysRegKill() for all live registers clobbered by Mask.
+  // Clobbered registers are always dead, sp there is no need to use
+  // HandlePhysRegDef().
+  for (unsigned Reg =3D 1, NumRegs =3D TRI->getNumRegs(); Reg !=3D NumRegs=
; ++Reg) {
+    // Skip dead regs.
+    if (!PhysRegDef[Reg] && !PhysRegUse[Reg])
+      continue;
+    // Skip mask-preserved regs.
+    if (!MO.clobbersPhysReg(Reg))
+      continue;
+    // Kill the largest clobbered super-register.
+    // This avoids needless implicit operands.
+    unsigned Super =3D Reg;
+    for (const uint16_t *SR =3D TRI->getSuperRegisters(Reg); *SR; ++SR)
+      if ((PhysRegDef[*SR] || PhysRegUse[*SR]) && MO.clobbersPhysReg(*SR))
+        Super =3D *SR;
+    HandlePhysRegKill(Super, 0);
+  }
+}
+
 void LiveVariables::HandlePhysRegDef(unsigned Reg, MachineInstr *MI,
                                      SmallVector<unsigned, 4> &Defs) {
   // What parts of the register are previously defined?
   SmallSet<unsigned, 32> Live;
   if (PhysRegDef[Reg] || PhysRegUse[Reg]) {
     Live.insert(Reg);
-    for (const unsigned *SS =3D TRI->getSubRegisters(Reg); *SS; ++SS)
+    for (const uint16_t *SS =3D TRI->getSubRegisters(Reg); *SS; ++SS)
       Live.insert(*SS);
   } else {
-    for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+    for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
          unsigned SubReg =3D *SubRegs; ++SubRegs) {
       // If a register isn't itself defined, but all parts that make up of=
 it
       // are defined, then consider it also defined.
@@ -440,7 +462,7 @@
         continue;
       if (PhysRegDef[SubReg] || PhysRegUse[SubReg]) {
         Live.insert(SubReg);
-        for (const unsigned *SS =3D TRI->getSubRegisters(SubReg); *SS; ++S=
S)
+        for (const uint16_t *SS =3D TRI->getSubRegisters(SubReg); *SS; ++S=
S)
           Live.insert(*SS);
       }
     }
@@ -450,7 +472,7 @@
   // is referenced.
   HandlePhysRegKill(Reg, MI);
   // Only some of the sub-registers are used.
-  for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+  for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
        unsigned SubReg =3D *SubRegs; ++SubRegs) {
     if (!Live.count(SubReg))
       // Skip if this sub-register isn't defined.
@@ -469,7 +491,7 @@
     Defs.pop_back();
     PhysRegDef[Reg]  =3D MI;
     PhysRegUse[Reg]  =3D NULL;
-    for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+    for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
          unsigned SubReg =3D *SubRegs; ++SubRegs) {
       PhysRegDef[SubReg]  =3D MI;
       PhysRegUse[SubReg]  =3D NULL;
@@ -492,6 +514,12 @@
   std::fill(PhysRegUse,  PhysRegUse  + NumRegs, (MachineInstr*)0);
   PHIJoins.clear();
=20
+  // FIXME: LiveIntervals will be updated to remove its dependence on
+  // LiveVariables to improve compilation time and eliminate bizarre pass
+  // dependencies. Until then, we can't change much in -O0.
+  if (!MRI->isSSA())
+    report_fatal_error("regalloc=3D... not currently supported with -O0");
+
   analyzePHINodes(mf);
=20
   // Calculate live variable information in depth first order on the CFG o=
f the
@@ -536,8 +564,13 @@
       // Clear kill and dead markers. LV will recompute them.
       SmallVector<unsigned, 4> UseRegs;
       SmallVector<unsigned, 4> DefRegs;
+      SmallVector<unsigned, 1> RegMasks;
       for (unsigned i =3D 0; i !=3D NumOperandsToProcess; ++i) {
         MachineOperand &MO =3D MI->getOperand(i);
+        if (MO.isRegMask()) {
+          RegMasks.push_back(i);
+          continue;
+        }
         if (!MO.isReg() || MO.getReg() =3D=3D 0)
           continue;
         unsigned MOReg =3D MO.getReg();
@@ -559,6 +592,10 @@
           HandlePhysRegUse(MOReg, MI);
       }
=20
+      // Process all masked registers. (Call clobbers).
+      for (unsigned i =3D 0, e =3D RegMasks.size(); i !=3D e; ++i)
+        HandleRegMask(MI->getOperand(RegMasks[i]));
+
       // Process all defs.
       for (unsigned i =3D 0, e =3D DefRegs.size(); i !=3D e; ++i) {
         unsigned MOReg =3D DefRegs[i];
@@ -590,8 +627,8 @@
     // them.  The tail callee need not take the same registers as input
     // that it produces as output, and there are dependencies for its input
     // registers elsewhere.
-    if (!MBB->empty() && MBB->back().getDesc().isReturn()
-        && !MBB->back().getDesc().isCall()) {
+    if (!MBB->empty() && MBB->back().isReturn()
+        && !MBB->back().isCall()) {
       MachineInstr *Ret =3D &MBB->back();
=20
       for (MachineRegisterInfo::liveout_iterator
@@ -607,10 +644,27 @@
       }
     }
=20
+    // MachineCSE may CSE instructions which write to non-allocatable phys=
ical
+    // registers across MBBs. Remember if any reserved register is liveout.
+    SmallSet<unsigned, 4> LiveOuts;
+    for (MachineBasicBlock::const_succ_iterator SI =3D MBB->succ_begin(),
+           SE =3D MBB->succ_end(); SI !=3D SE; ++SI) {
+      MachineBasicBlock *SuccMBB =3D *SI;
+      if (SuccMBB->isLandingPad())
+        continue;
+      for (MachineBasicBlock::livein_iterator LI =3D SuccMBB->livein_begin=
(),
+             LE =3D SuccMBB->livein_end(); LI !=3D LE; ++LI) {
+        unsigned LReg =3D *LI;
+        if (!TRI->isInAllocatableClass(LReg))
+          // Ignore other live-ins, e.g. those that are live into landing =
pads.
+          LiveOuts.insert(LReg);
+      }
+    }
+
     // Loop over PhysRegDef / PhysRegUse, killing any registers that are
     // available at the end of the basic block.
     for (unsigned i =3D 0; i !=3D NumRegs; ++i)
-      if (PhysRegDef[i] || PhysRegUse[i])
+      if ((PhysRegDef[i] || PhysRegUse[i]) && !LiveOuts.count(i))
         HandlePhysRegDef(i, 0, Defs);
=20
     std::fill(PhysRegDef,  PhysRegDef  + NumRegs, (MachineInstr*)0);
@@ -754,7 +808,7 @@
   const unsigned NumNew =3D BB->getNumber();
=20
   // All registers used by PHI nodes in SuccBB must be live through BB.
-  for (MachineBasicBlock::const_iterator BBI =3D SuccBB->begin(),
+  for (MachineBasicBlock::iterator BBI =3D SuccBB->begin(),
          BBE =3D SuccBB->end(); BBI !=3D BBE && BBI->isPHI(); ++BBI)
     for (unsigned i =3D 1, e =3D BBI->getNumOperands(); i !=3D e; i +=3D 2)
       if (BBI->getOperand(i+1).getMBB() =3D=3D BB)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/LocalSta=
ckSlotAllocation.cpp
--- a/head/contrib/llvm/lib/CodeGen/LocalStackSlotAllocation.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/LocalStackSlotAllocation.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -71,19 +71,15 @@
       AU.setPreservesCFG();
       MachineFunctionPass::getAnalysisUsage(AU);
     }
-    const char *getPassName() const {
-      return "Local Stack Slot Allocation";
-    }
=20
   private:
   };
 } // end anonymous namespace
=20
 char LocalStackSlotPass::ID =3D 0;
-
-FunctionPass *llvm::createLocalStackSlotAllocationPass() {
-  return new LocalStackSlotPass();
-}
+char &llvm::LocalStackSlotAllocationID =3D LocalStackSlotPass::ID;
+INITIALIZE_PASS(LocalStackSlotPass, "localstackalloc",
+                "Local Stack Slot Allocation", false, false)
=20
 bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineB=
asicBlock.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineBasicBlock.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineBasicBlock.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -73,7 +73,8 @@
=20
   // Make sure the instructions have their operands in the reginfo lists.
   MachineRegisterInfo &RegInfo =3D MF.getRegInfo();
-  for (MachineBasicBlock::iterator I =3D N->begin(), E =3D N->end(); I !=
=3D E; ++I)
+  for (MachineBasicBlock::instr_iterator
+         I =3D N->instr_begin(), E =3D N->instr_end(); I !=3D E; ++I)
     I->AddRegOperandsToUseLists(RegInfo);
=20
   LeakDetector::removeGarbageObject(N);
@@ -120,8 +121,8 @@
 /// lists.
 void ilist_traits<MachineInstr>::
 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
-                      MachineBasicBlock::iterator first,
-                      MachineBasicBlock::iterator last) {
+                      ilist_iterator<MachineInstr> first,
+                      ilist_iterator<MachineInstr> last) {
   assert(Parent->getParent() =3D=3D fromList.Parent->getParent() &&
         "MachineInstr parent mismatch!");
=20
@@ -140,33 +141,75 @@
 }
=20
 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
-  iterator I =3D begin();
-  while (I !=3D end() && I->isPHI())
+  instr_iterator I =3D instr_begin(), E =3D instr_end();
+  while (I !=3D E && I->isPHI())
     ++I;
+  assert(!I->isInsideBundle() && "First non-phi MI cannot be inside a bund=
le!");
   return I;
 }
=20
 MachineBasicBlock::iterator
 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
-  while (I !=3D end() && (I->isPHI() || I->isLabel() || I->isDebugValue()))
+  iterator E =3D end();
+  while (I !=3D E && (I->isPHI() || I->isLabel() || I->isDebugValue()))
+    ++I;
+  // FIXME: This needs to change if we wish to bundle labels / dbg_values
+  // inside the bundle.
+  assert(!I->isInsideBundle() &&
+         "First non-phi / non-label instruction is inside a bundle!");
+  return I;
+}
+
+MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
+  iterator B =3D begin(), E =3D end(), I =3D E;
+  while (I !=3D B && ((--I)->isTerminator() || I->isDebugValue()))
+    ; /*noop */
+  while (I !=3D E && !I->isTerminator())
     ++I;
   return I;
 }
=20
-MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
-  iterator I =3D end();
-  while (I !=3D begin() && ((--I)->getDesc().isTerminator() || I->isDebugV=
alue()))
+MachineBasicBlock::const_iterator
+MachineBasicBlock::getFirstTerminator() const {
+  const_iterator B =3D begin(), E =3D end(), I =3D E;
+  while (I !=3D B && ((--I)->isTerminator() || I->isDebugValue()))
     ; /*noop */
-  while (I !=3D end() && !I->getDesc().isTerminator())
+  while (I !=3D E && !I->isTerminator())
+    ++I;
+  return I;
+}
+
+MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminat=
or() {
+  instr_iterator B =3D instr_begin(), E =3D instr_end(), I =3D E;
+  while (I !=3D B && ((--I)->isTerminator() || I->isDebugValue()))
+    ; /*noop */
+  while (I !=3D E && !I->isTerminator())
     ++I;
   return I;
 }
=20
 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
-  iterator B =3D begin(), I =3D end();
+  // Skip over end-of-block dbg_value instructions.
+  instr_iterator B =3D instr_begin(), I =3D instr_end();
   while (I !=3D B) {
     --I;
-    if (I->isDebugValue())
+    // Return instruction that starts a bundle.
+    if (I->isDebugValue() || I->isInsideBundle())
+      continue;
+    return I;
+  }
+  // The block is all debug values.
+  return end();
+}
+
+MachineBasicBlock::const_iterator
+MachineBasicBlock::getLastNonDebugInstr() const {
+  // Skip over end-of-block dbg_value instructions.
+  const_instr_iterator B =3D instr_begin(), I =3D instr_end();
+  while (I !=3D B) {
+    --I;
+    // Return instruction that starts a bundle.
+    if (I->isDebugValue() || I->isInsideBundle())
       continue;
     return I;
   }
@@ -195,6 +238,18 @@
     return "(null)";
 }
=20
+/// Return a hopefully unique identifier for this block.
+std::string MachineBasicBlock::getFullName() const {
+  std::string Name;
+  if (getParent())
+    Name =3D (getParent()->getFunction()->getName() + ":").str();
+  if (getBasicBlock())
+    Name +=3D getBasicBlock()->getName();
+  else
+    Name +=3D (Twine("BB") + Twine(getNumber())).str();
+  return Name;
+}
+
 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const=
 {
   const MachineFunction *MF =3D getParent();
   if (!MF) {
@@ -203,8 +258,6 @@
     return;
   }
=20
-  if (Alignment) { OS << "Alignment " << Alignment << "\n"; }
-
   if (Indexes)
     OS << Indexes->getMBBStartIdx(this) << '\t';
=20
@@ -218,6 +271,12 @@
   }
   if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma =3D ", "; }
   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma =3D ", ";=
 }
+  if (Alignment) {
+    OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
+       << " bytes)";
+    Comma =3D ", ";
+  }
+
   OS << '\n';
=20
   const TargetRegisterInfo *TRI =3D MF->getTarget().getRegisterInfo();
@@ -237,13 +296,15 @@
     OS << '\n';
   }
=20
-  for (const_iterator I =3D begin(); I !=3D end(); ++I) {
+  for (const_instr_iterator I =3D instr_begin(); I !=3D instr_end(); ++I) {
     if (Indexes) {
       if (Indexes->hasIndex(I))
         OS << Indexes->getInstructionIndex(I);
       OS << '\t';
     }
     OS << '\t';
+    if (I->isInsideBundle())
+      OS << "  * ";
     I->print(OS, &getParent()->getTarget());
   }
=20
@@ -260,8 +321,8 @@
 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
   std::vector<unsigned>::iterator I =3D
     std::find(LiveIns.begin(), LiveIns.end(), Reg);
-  assert(I !=3D LiveIns.end() && "Not a live in!");
-  LiveIns.erase(I);
+  if (I !=3D LiveIns.end())
+    LiveIns.erase(I);
 }
=20
 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
@@ -297,8 +358,22 @@
         TII->RemoveBranch(*this);
     } else {
       // The block has an unconditional fallthrough. If its successor is n=
ot
-      // its layout successor, insert a branch.
-      TBB =3D *succ_begin();
+      // its layout successor, insert a branch. First we have to locate the
+      // only non-landing-pad successor, as that is the fallthrough block.
+      for (succ_iterator SI =3D succ_begin(), SE =3D succ_end(); SI !=3D S=
E; ++SI) {
+        if ((*SI)->isLandingPad())
+          continue;
+        assert(!TBB && "Found more than one non-landing-pad successor!");
+        TBB =3D *SI;
+      }
+
+      // If there is no non-landing-pad successor, the block has no
+      // fall-through edges to be concerned with.
+      if (!TBB)
+        return;
+
+      // Finally update the unconditional successor to be reached via a br=
anch
+      // if it would not be reached by fallthrough.
       if (!isLayoutSuccessor(TBB))
         TII->InsertBranch(*this, TBB, 0, Cond, dl);
     }
@@ -435,8 +510,8 @@
     fromMBB->removeSuccessor(Succ);
=20
     // Fix up any PHI nodes in the successor.
-    for (MachineBasicBlock::iterator MI =3D Succ->begin(), ME =3D Succ->en=
d();
-         MI !=3D ME && MI->isPHI(); ++MI)
+    for (MachineBasicBlock::instr_iterator MI =3D Succ->instr_begin(),
+           ME =3D Succ->instr_end(); MI !=3D ME && MI->isPHI(); ++MI)
       for (unsigned i =3D 2, e =3D MI->getNumOperands()+1; i !=3D e; i +=
=3D 2) {
         MachineOperand &MO =3D MI->getOperand(i);
         if (MO.getMBB() =3D=3D fromMBB)
@@ -473,13 +548,10 @@
   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
     // If we couldn't analyze the branch, examine the last instruction.
     // If the block doesn't end in a known control barrier, assume fallthr=
ough
-    // is possible. The isPredicable check is needed because this code can=
 be
+    // is possible. The isPredicated check is needed because this code can=
 be
     // called during IfConversion, where an instruction which is normally a
-    // Barrier is predicated and thus no longer an actual control barrier.=
 This
-    // is over-conservative though, because if an instruction isn't actual=
ly
-    // predicated we could still treat it like a barrier.
-    return empty() || !back().getDesc().isBarrier() ||
-           back().getDesc().isPredicable();
+    // Barrier is predicated and thus no longer an actual control barrier.
+    return empty() || !back().isBarrier() || TII->isPredicated(&back());
   }
=20
   // If there is no branch, control always falls through.
@@ -538,14 +610,16 @@
   // Collect a list of virtual registers killed by the terminators.
   SmallVector<unsigned, 4> KilledRegs;
   if (LV)
-    for (iterator I =3D getFirstTerminator(), E =3D end(); I !=3D E; ++I) {
+    for (instr_iterator I =3D getFirstInstrTerminator(), E =3D instr_end();
+         I !=3D E; ++I) {
       MachineInstr *MI =3D I;
       for (MachineInstr::mop_iterator OI =3D MI->operands_begin(),
            OE =3D MI->operands_end(); OI !=3D OE; ++OI) {
-        if (!OI->isReg() || !OI->isUse() || !OI->isKill() || OI->isUndef())
+        if (!OI->isReg() || OI->getReg() =3D=3D 0 ||
+            !OI->isUse() || !OI->isKill() || OI->isUndef())
           continue;
         unsigned Reg =3D OI->getReg();
-        if (TargetRegisterInfo::isVirtualRegister(Reg) &&
+        if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
             LV->getVarInfo(Reg).removeKill(MI)) {
           KilledRegs.push_back(Reg);
           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
@@ -565,7 +639,8 @@
   }
=20
   // Fix PHI nodes in Succ so they refer to NMBB instead of this
-  for (MachineBasicBlock::iterator i =3D Succ->begin(), e =3D Succ->end();
+  for (MachineBasicBlock::instr_iterator
+         i =3D Succ->instr_begin(),e =3D Succ->instr_end();
        i !=3D e && i->isPHI(); ++i)
     for (unsigned ni =3D 1, ne =3D i->getNumOperands(); ni !=3D ne; ni +=
=3D 2)
       if (i->getOperand(ni+1).getMBB() =3D=3D this)
@@ -577,14 +652,16 @@
     NMBB->addLiveIn(*I);
=20
   // Update LiveVariables.
+  const TargetRegisterInfo *TRI =3D MF->getTarget().getRegisterInfo();
   if (LV) {
     // Restore kills of virtual registers that were killed by the terminat=
ors.
     while (!KilledRegs.empty()) {
       unsigned Reg =3D KilledRegs.pop_back_val();
-      for (iterator I =3D end(), E =3D begin(); I !=3D E;) {
-        if (!(--I)->addRegisterKilled(Reg, NULL, /* addIfNotFound=3D */ fa=
lse))
+      for (instr_iterator I =3D instr_end(), E =3D instr_begin(); I !=3D E=
;) {
+        if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound=3D */ fal=
se))
           continue;
-        LV->getVarInfo(Reg).Kills.push_back(I);
+        if (TargetRegisterInfo::isVirtualRegister(Reg))
+          LV->getVarInfo(Reg).Kills.push_back(I);
         DEBUG(dbgs() << "Restored terminator kill: " << *I);
         break;
       }
@@ -650,6 +727,42 @@
   return NMBB;
 }
=20
+MachineBasicBlock::iterator
+MachineBasicBlock::erase(MachineBasicBlock::iterator I) {
+  if (I->isBundle()) {
+    MachineBasicBlock::iterator E =3D llvm::next(I);
+    return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
+  }
+
+  return Insts.erase(I.getInstrIterator());
+}
+
+MachineInstr *MachineBasicBlock::remove(MachineInstr *I) {
+  if (I->isBundle()) {
+    instr_iterator MII =3D llvm::next(I);
+    iterator E =3D end();
+    while (MII !=3D E && MII->isInsideBundle()) {
+      MachineInstr *MI =3D &*MII++;
+      Insts.remove(MI);
+    }
+  }
+
+  return Insts.remove(I);
+}
+
+void MachineBasicBlock::splice(MachineBasicBlock::iterator where,
+                               MachineBasicBlock *Other,
+                               MachineBasicBlock::iterator From) {
+  if (From->isBundle()) {
+    MachineBasicBlock::iterator To =3D llvm::next(From);
+    Insts.splice(where.getInstrIterator(), Other->Insts,
+                 From.getInstrIterator(), To.getInstrIterator());
+    return;
+  }
+
+  Insts.splice(where.getInstrIterator(), Other->Insts, From.getInstrIterat=
or());
+}
+
 /// removeFromParent - This method unlinks 'this' from the containing func=
tion,
 /// and returns it, but does not delete it.
 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
@@ -673,10 +786,10 @@
                                                MachineBasicBlock *New) {
   assert(Old !=3D New && "Cannot replace self with self!");
=20
-  MachineBasicBlock::iterator I =3D end();
-  while (I !=3D begin()) {
+  MachineBasicBlock::instr_iterator I =3D instr_end();
+  while (I !=3D instr_begin()) {
     --I;
-    if (!I->getDesc().isTerminator()) break;
+    if (!I->isTerminator()) break;
=20
     // Scan the operands of this machine instruction, replacing any uses o=
f Old
     // with New.
@@ -755,27 +868,27 @@
 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
 /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
 DebugLoc
-MachineBasicBlock::findDebugLoc(MachineBasicBlock::iterator &MBBI) {
+MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
   DebugLoc DL;
-  MachineBasicBlock::iterator E =3D end();
-  if (MBBI !=3D E) {
-    // Skip debug declarations, we don't want a DebugLoc from them.
-    MachineBasicBlock::iterator MBBI2 =3D MBBI;
-    while (MBBI2 !=3D E && MBBI2->isDebugValue())
-      MBBI2++;
-    if (MBBI2 !=3D E)
-      DL =3D MBBI2->getDebugLoc();
-  }
+  instr_iterator E =3D instr_end();
+  if (MBBI =3D=3D E)
+    return DL;
+
+  // Skip debug declarations, we don't want a DebugLoc from them.
+  while (MBBI !=3D E && MBBI->isDebugValue())
+    MBBI++;
+  if (MBBI !=3D E)
+    DL =3D MBBI->getDebugLoc();
   return DL;
 }
=20
 /// getSuccWeight - Return weight of the edge from this block to MBB.
 ///
-uint32_t MachineBasicBlock::getSuccWeight(MachineBasicBlock *succ) {
+uint32_t MachineBasicBlock::getSuccWeight(const MachineBasicBlock *succ) c=
onst {
   if (Weights.empty())
     return 0;
=20
-  succ_iterator I =3D std::find(Successors.begin(), Successors.end(), succ=
);
+  const_succ_iterator I =3D std::find(Successors.begin(), Successors.end()=
, succ);
   return *getWeightIterator(I);
 }
=20
@@ -789,6 +902,16 @@
   return Weights.begin() + index;
 }
=20
+/// getWeightIterator - Return wight iterator corresonding to the I succes=
sor
+/// iterator
+MachineBasicBlock::const_weight_iterator MachineBasicBlock::
+getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
+  assert(Weights.size() =3D=3D Successors.size() && "Async weight list!");
+  const size_t index =3D std::distance(Successors.begin(), I);
+  assert(index < Weights.size() && "Not a current successor!");
+  return Weights.begin() + index;
+}
+
 void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
                           bool t) {
   OS << "BB#" << MBB->getNumber();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineB=
lockFrequencyInfo.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineBlockFrequencyInfo.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineBlockFrequencyInfo.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -56,6 +56,6 @@
 /// the other block frequencies. We do this to avoid using of floating poi=
nts.
 ///
 BlockFrequency MachineBlockFrequencyInfo::
-getBlockFreq(MachineBasicBlock *MBB) const {
+getBlockFreq(const MachineBasicBlock *MBB) const {
   return MBFI->getBlockFreq(MBB);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineB=
ranchProbabilityInfo.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineBranchProbabilityInfo.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineBranchProbabilityInfo.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -26,26 +26,43 @@
=20
 char MachineBranchProbabilityInfo::ID =3D 0;
=20
+void MachineBranchProbabilityInfo::anchor() { }
+
 uint32_t MachineBranchProbabilityInfo::
-getSumForBlock(MachineBasicBlock *MBB) const {
-  uint32_t Sum =3D 0;
-
+getSumForBlock(const MachineBasicBlock *MBB, uint32_t &Scale) const {
+  // First we compute the sum with 64-bits of precision, ensuring that can=
not
+  // overflow by bounding the number of weights considered. Hopefully no o=
ne
+  // actually needs 2^32 successors.
+  assert(MBB->succ_size() < UINT32_MAX);
+  uint64_t Sum =3D 0;
+  Scale =3D 1;
   for (MachineBasicBlock::const_succ_iterator I =3D MBB->succ_begin(),
        E =3D MBB->succ_end(); I !=3D E; ++I) {
-    MachineBasicBlock *Succ =3D *I;
-    uint32_t Weight =3D getEdgeWeight(MBB, Succ);
-    uint32_t PrevSum =3D Sum;
-
+    uint32_t Weight =3D getEdgeWeight(MBB, *I);
     Sum +=3D Weight;
-    assert(Sum > PrevSum); (void) PrevSum;
   }
=20
+  // If the computed sum fits in 32-bits, we're done.
+  if (Sum <=3D UINT32_MAX)
+    return Sum;
+
+  // Otherwise, compute the scale necessary to cause the weights to fit, a=
nd
+  // re-sum with that scale applied.
+  assert((Sum / UINT32_MAX) < UINT32_MAX);
+  Scale =3D (Sum / UINT32_MAX) + 1;
+  Sum =3D 0;
+  for (MachineBasicBlock::const_succ_iterator I =3D MBB->succ_begin(),
+       E =3D MBB->succ_end(); I !=3D E; ++I) {
+    uint32_t Weight =3D getEdgeWeight(MBB, *I);
+    Sum +=3D Weight / Scale;
+  }
+  assert(Sum <=3D UINT32_MAX);
   return Sum;
 }
=20
 uint32_t
-MachineBranchProbabilityInfo::getEdgeWeight(MachineBasicBlock *Src,
-                                            MachineBasicBlock *Dst) const {
+MachineBranchProbabilityInfo::getEdgeWeight(const MachineBasicBlock *Src,
+                                            const MachineBasicBlock *Dst) =
const {
   uint32_t Weight =3D Src->getSuccWeight(Dst);
   if (!Weight)
     return DEFAULT_WEIGHT;
@@ -55,37 +72,24 @@
 bool MachineBranchProbabilityInfo::isEdgeHot(MachineBasicBlock *Src,
                                              MachineBasicBlock *Dst) const=
 {
   // Hot probability is at least 4/5 =3D 80%
-  uint32_t Weight =3D getEdgeWeight(Src, Dst);
-  uint32_t Sum =3D getSumForBlock(Src);
-
-  // FIXME: Implement BranchProbability::compare then change this code to
-  // compare this BranchProbability against a static "hot" BranchProbabili=
ty.
-  return (uint64_t)Weight * 5 > (uint64_t)Sum * 4;
+  // FIXME: Compare against a static "hot" BranchProbability.
+  return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
 }
=20
 MachineBasicBlock *
 MachineBranchProbabilityInfo::getHotSucc(MachineBasicBlock *MBB) const {
-  uint32_t Sum =3D 0;
   uint32_t MaxWeight =3D 0;
   MachineBasicBlock *MaxSucc =3D 0;
-
   for (MachineBasicBlock::const_succ_iterator I =3D MBB->succ_begin(),
        E =3D MBB->succ_end(); I !=3D E; ++I) {
-    MachineBasicBlock *Succ =3D *I;
-    uint32_t Weight =3D getEdgeWeight(MBB, Succ);
-    uint32_t PrevSum =3D Sum;
-
-    Sum +=3D Weight;
-    assert(Sum > PrevSum); (void) PrevSum;
-
+    uint32_t Weight =3D getEdgeWeight(MBB, *I);
     if (Weight > MaxWeight) {
       MaxWeight =3D Weight;
-      MaxSucc =3D Succ;
+      MaxSucc =3D *I;
     }
   }
=20
-  // FIXME: Use BranchProbability::compare.
-  if ((uint64_t)MaxWeight * 5 >=3D (uint64_t)Sum * 4)
+  if (getEdgeProbability(MBB, MaxSucc) >=3D BranchProbability(4, 5))
     return MaxSucc;
=20
   return 0;
@@ -94,8 +98,9 @@
 BranchProbability
 MachineBranchProbabilityInfo::getEdgeProbability(MachineBasicBlock *Src,
                                                  MachineBasicBlock *Dst) c=
onst {
-  uint32_t N =3D getEdgeWeight(Src, Dst);
-  uint32_t D =3D getSumForBlock(Src);
+  uint32_t Scale =3D 1;
+  uint32_t D =3D getSumForBlock(Src, Scale);
+  uint32_t N =3D getEdgeWeight(Src, Dst) / Scale;
=20
   return BranchProbability(N, D);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineC=
SE.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineCSE.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineCSE.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -26,13 +26,14 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/RecyclingAllocator.h"
-
 using namespace llvm;
=20
 STATISTIC(NumCoalesces, "Number of copies coalesced");
 STATISTIC(NumCSEs,      "Number of common subexpression eliminated");
 STATISTIC(NumPhysCSEs,
           "Number of physreg referencing common subexpr eliminated");
+STATISTIC(NumCrossBBCSEs,
+          "Number of cross-MBB physreg referencing CS eliminated");
 STATISTIC(NumCommutes,  "Number of copies coalesced after commuting");
=20
 namespace {
@@ -49,7 +50,7 @@
     }
=20
     virtual bool runOnMachineFunction(MachineFunction &MF);
-   =20
+
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
       MachineFunctionPass::getAnalysisUsage(AU);
@@ -62,6 +63,8 @@
     virtual void releaseMemory() {
       ScopeMap.clear();
       Exps.clear();
+      AllocatableRegs.clear();
+      ReservedRegs.clear();
     }
=20
   private:
@@ -75,6 +78,8 @@
     ScopedHTType VNT;
     SmallVector<MachineInstr*, 64> Exps;
     unsigned CurrVN;
+    BitVector AllocatableRegs;
+    BitVector ReservedRegs;
=20
     bool PerformTrivialCoalescing(MachineInstr *MI, MachineBasicBlock *MBB=
);
     bool isPhysDefTriviallyDead(unsigned Reg,
@@ -82,9 +87,12 @@
                                 MachineBasicBlock::const_iterator E) const=
 ;
     bool hasLivePhysRegDefUses(const MachineInstr *MI,
                                const MachineBasicBlock *MBB,
-                               SmallSet<unsigned,8> &PhysRefs) const;
+                               SmallSet<unsigned,8> &PhysRefs,
+                               SmallVector<unsigned,2> &PhysDefs) const;
     bool PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
-                          SmallSet<unsigned,8> &PhysRefs) const;
+                          SmallSet<unsigned,8> &PhysRefs,
+                          SmallVector<unsigned,2> &PhysDefs,
+                          bool &NonLocal) const;
     bool isCSECandidate(MachineInstr *MI);
     bool isProfitableToCSE(unsigned CSReg, unsigned Reg,
                            MachineInstr *CSMI, MachineInstr *MI);
@@ -99,6 +107,7 @@
 } // end anonymous namespace
=20
 char MachineCSE::ID =3D 0;
+char &llvm::MachineCSEID =3D MachineCSE::ID;
 INITIALIZE_PASS_BEGIN(MachineCSE, "machine-cse",
                 "Machine Common Subexpression Elimination", false, false)
 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
@@ -106,8 +115,6 @@
 INITIALIZE_PASS_END(MachineCSE, "machine-cse",
                 "Machine Common Subexpression Elimination", false, false)
=20
-FunctionPass *llvm::createMachineCSEPass() { return new MachineCSE(); }
-
 bool MachineCSE::PerformTrivialCoalescing(MachineInstr *MI,
                                           MachineBasicBlock *MBB) {
   bool Changed =3D false;
@@ -163,6 +170,8 @@
     bool SeenDef =3D false;
     for (unsigned i =3D 0, e =3D I->getNumOperands(); i !=3D e; ++i) {
       const MachineOperand &MO =3D I->getOperand(i);
+      if (MO.isRegMask() && MO.clobbersPhysReg(Reg))
+        SeenDef =3D true;
       if (!MO.isReg() || !MO.getReg())
         continue;
       if (!TRI->regsOverlap(MO.getReg(), Reg))
@@ -173,7 +182,7 @@
       SeenDef =3D true;
     }
     if (SeenDef)
-      // See a def of Reg (or an alias) before encountering any use, it's=20
+      // See a def of Reg (or an alias) before encountering any use, it's
       // trivially dead.
       return true;
=20
@@ -189,7 +198,8 @@
 /// instruction does not uses a physical register.
 bool MachineCSE::hasLivePhysRegDefUses(const MachineInstr *MI,
                                        const MachineBasicBlock *MBB,
-                                       SmallSet<unsigned,8> &PhysRefs) con=
st {
+                                       SmallSet<unsigned,8> &PhysRefs,
+                                       SmallVector<unsigned,2> &PhysDefs) =
const{
   MachineBasicBlock::const_iterator I =3D MI; I =3D llvm::next(I);
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D MI->getOperand(i);
@@ -207,7 +217,9 @@
         (MO.isDead() || isPhysDefTriviallyDead(Reg, I, MBB->end())))
       continue;
     PhysRefs.insert(Reg);
-    for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)
+    if (MO.isDef())
+      PhysDefs.push_back(Reg);
+    for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)
       PhysRefs.insert(*Alias);
   }
=20
@@ -215,25 +227,56 @@
 }
=20
 bool MachineCSE::PhysRegDefsReach(MachineInstr *CSMI, MachineInstr *MI,
-                                  SmallSet<unsigned,8> &PhysRefs) const {
+                                  SmallSet<unsigned,8> &PhysRefs,
+                                  SmallVector<unsigned,2> &PhysDefs,
+                                  bool &NonLocal) const {
   // For now conservatively returns false if the common subexpression is
-  // not in the same basic block as the given instruction.
-  MachineBasicBlock *MBB =3D MI->getParent();
-  if (CSMI->getParent() !=3D MBB)
-    return false;
+  // not in the same basic block as the given instruction. The only except=
ion
+  // is if the common subexpression is in the sole predecessor block.
+  const MachineBasicBlock *MBB =3D MI->getParent();
+  const MachineBasicBlock *CSMBB =3D CSMI->getParent();
+
+  bool CrossMBB =3D false;
+  if (CSMBB !=3D MBB) {
+    if (MBB->pred_size() !=3D 1 || *MBB->pred_begin() !=3D CSMBB)
+      return false;
+
+    for (unsigned i =3D 0, e =3D PhysDefs.size(); i !=3D e; ++i) {
+      if (AllocatableRegs.test(PhysDefs[i]) || ReservedRegs.test(PhysDefs[=
i]))
+        // Avoid extending live range of physical registers if they are
+        //allocatable or reserved.
+        return false;
+    }
+    CrossMBB =3D true;
+  }
   MachineBasicBlock::const_iterator I =3D CSMI; I =3D llvm::next(I);
   MachineBasicBlock::const_iterator E =3D MI;
+  MachineBasicBlock::const_iterator EE =3D CSMBB->end();
   unsigned LookAheadLeft =3D LookAheadLimit;
   while (LookAheadLeft) {
     // Skip over dbg_value's.
-    while (I !=3D E && I->isDebugValue())
+    while (I !=3D E && I !=3D EE && I->isDebugValue())
       ++I;
=20
+    if (I =3D=3D EE) {
+      assert(CrossMBB && "Reaching end-of-MBB without finding MI?");
+      (void)CrossMBB;
+      CrossMBB =3D false;
+      NonLocal =3D true;
+      I =3D MBB->begin();
+      EE =3D MBB->end();
+      continue;
+    }
+
     if (I =3D=3D E)
       return true;
=20
     for (unsigned i =3D 0, e =3D I->getNumOperands(); i !=3D e; ++i) {
       const MachineOperand &MO =3D I->getOperand(i);
+      // RegMasks go on instructions like calls that clobber lots of physr=
egs.
+      // Don't attempt to CSE across such an instruction.
+      if (MO.isRegMask())
+        return false;
       if (!MO.isReg() || !MO.isDef())
         continue;
       unsigned MOReg =3D MO.getReg();
@@ -260,12 +303,11 @@
     return false;
=20
   // Ignore stuff that we obviously can't move.
-  const MCInstrDesc &MCID =3D MI->getDesc(); =20
-  if (MCID.mayStore() || MCID.isCall() || MCID.isTerminator() ||
+  if (MI->mayStore() || MI->isCall() || MI->isTerminator() ||
       MI->hasUnmodeledSideEffects())
     return false;
=20
-  if (MCID.mayLoad()) {
+  if (MI->mayLoad()) {
     // Okay, this instruction does a load. As a refinement, we allow the t=
arget
     // to decide whether the loaded value is actually a constant. If so, w=
e can
     // actually use it as a load.
@@ -287,7 +329,7 @@
   // Heuristics #1: Don't CSE "cheap" computation if the def is not local =
or in
   // an immediate predecessor. We don't want to increase register pressure=
 and
   // end up causing other computation to be spilled.
-  if (MI->getDesc().isAsCheapAsAMove()) {
+  if (MI->isAsCheapAsAMove()) {
     MachineBasicBlock *CSBB =3D CSMI->getParent();
     MachineBasicBlock *BB =3D MI->getParent();
     if (CSBB !=3D BB && !CSBB->isSuccessor(BB))
@@ -376,7 +418,7 @@
=20
     // Commute commutable instructions.
     bool Commuted =3D false;
-    if (!FoundCSE && MI->getDesc().isCommutable()) {
+    if (!FoundCSE && MI->isCommutable()) {
       MachineInstr *NewMI =3D TII->commuteInstruction(MI);
       if (NewMI) {
         Commuted =3D true;
@@ -394,16 +436,18 @@
     // If the instruction defines physical registers and the values *may* =
be
     // used, then it's not safe to replace it with a common subexpression.
     // It's also not safe if the instruction uses physical registers.
+    bool CrossMBBPhysDef =3D false;
     SmallSet<unsigned,8> PhysRefs;
-    if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs)) {
+    SmallVector<unsigned, 2> PhysDefs;
+    if (FoundCSE && hasLivePhysRegDefUses(MI, MBB, PhysRefs, PhysDefs)) {
       FoundCSE =3D false;
=20
-      // ... Unless the CS is local and it also defines the physical regis=
ter
-      // which is not clobbered in between and the physical register uses=20
-      // were not clobbered.
+      // ... Unless the CS is local or is in the sole predecessor block
+      // and it also defines the physical register which is not clobbered
+      // in between and the physical register uses were not clobbered.
       unsigned CSVN =3D VNT.lookup(MI);
       MachineInstr *CSMI =3D Exps[CSVN];
-      if (PhysRegDefsReach(CSMI, MI, PhysRefs))
+      if (PhysRegDefsReach(CSMI, MI, PhysRefs, PhysDefs, CrossMBBPhysDef))
         FoundCSE =3D true;
     }
=20
@@ -458,6 +502,18 @@
         MRI->replaceRegWith(CSEPairs[i].first, CSEPairs[i].second);
         MRI->clearKillFlags(CSEPairs[i].second);
       }
+
+      if (CrossMBBPhysDef) {
+        // Add physical register defs now coming in from a predecessor to =
MBB
+        // livein list.
+        while (!PhysDefs.empty()) {
+          unsigned LiveIn =3D PhysDefs.pop_back_val();
+          if (!MBB->isLiveIn(LiveIn))
+            MBB->addLiveIn(LiveIn);
+        }
+        ++NumCrossBBCSEs;
+      }
+
       MI->eraseFromParent();
       ++NumCSEs;
       if (!PhysRefs.empty())
@@ -542,5 +598,7 @@
   MRI =3D &MF.getRegInfo();
   AA =3D &getAnalysis<AliasAnalysis>();
   DT =3D &getAnalysis<MachineDominatorTree>();
+  AllocatableRegs =3D TRI->getAllocatableSet(MF);
+  ReservedRegs =3D TRI->getReservedRegs(MF);
   return PerformCSE(DT->getRootNode());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineF=
unction.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineFunction.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineFunction.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -13,12 +13,9 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "llvm/DerivedTypes.h"
+#include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/Function.h"
-#include "llvm/Instructions.h"
-#include "llvm/Config/config.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
-#include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstr.h"
@@ -28,6 +25,7 @@
 #include "llvm/CodeGen/Passes.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCContext.h"
+#include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Target/TargetData.h"
@@ -197,9 +195,10 @@
 MachineMemOperand *
 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned=
 f,
                                       uint64_t s, unsigned base_alignment,
-                                      const MDNode *TBAAInfo) {
+                                      const MDNode *TBAAInfo,
+                                      const MDNode *Ranges) {
   return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
-                                           TBAAInfo);
+                                           TBAAInfo, Ranges);
 }
=20
 MachineMemOperand *
@@ -286,7 +285,13 @@
 }
=20
 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
-  OS << "# Machine code for function " << Fn->getName() << ":\n";
+  OS << "# Machine code for function " << Fn->getName() << ": ";
+  if (RegInfo) {
+    OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
+    if (!RegInfo->tracksLiveness())
+      OS << ", not tracking liveness";
+  }
+  OS << '\n';
=20
   // Print Frame Information
   FrameInfo->print(*this, OS);
@@ -335,7 +340,7 @@
   DOTGraphTraits (bool isSimple=3Dfalse) : DefaultDOTGraphTraits(isSimple)=
 {}
=20
     static std::string getGraphName(const MachineFunction *F) {
-      return "CFG for '" + F->getFunction()->getNameStr() + "' function";
+      return "CFG for '" + F->getFunction()->getName().str() + "' function=
";
     }
=20
     std::string getNodeLabel(const MachineBasicBlock *Node,
@@ -368,7 +373,7 @@
 void MachineFunction::viewCFG() const
 {
 #ifndef NDEBUG
-  ViewGraph(this, "mf" + getFunction()->getNameStr());
+  ViewGraph(this, "mf" + getFunction()->getName());
 #else
   errs() << "MachineFunction::viewCFG is only available in debug builds on=
 "
          << "systems with Graphviz or gv!\n";
@@ -378,7 +383,7 @@
 void MachineFunction::viewCFGOnly() const
 {
 #ifndef NDEBUG
-  ViewGraph(this, "mf" + getFunction()->getNameStr(), true);
+  ViewGraph(this, "mf" + getFunction()->getName(), true);
 #else
   errs() << "MachineFunction::viewCFGOnly is only available in debug build=
s on "
          << "systems with Graphviz or gv!\n";
@@ -464,7 +469,7 @@
   if (!isCalleeSavedInfoValid())
     return BV;
=20
-  for (const unsigned *CSR =3D TRI->getCalleeSavedRegs(MF); CSR && *CSR; +=
+CSR)
+  for (const uint16_t *CSR =3D TRI->getCalleeSavedRegs(MF); CSR && *CSR; +=
+CSR)
     BV.set(*CSR);
=20
   // The entry MBB always has all CSRs pristine.
@@ -532,6 +537,8 @@
   switch (getEntryKind()) {
   case MachineJumpTableInfo::EK_BlockAddress:
     return TD.getPointerSize();
+  case MachineJumpTableInfo::EK_GPRel64BlockAddress:
+    return 8;
   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
   case MachineJumpTableInfo::EK_LabelDifference32:
   case MachineJumpTableInfo::EK_Custom32:
@@ -539,8 +546,7 @@
   case MachineJumpTableInfo::EK_Inline:
     return 0;
   }
-  assert(0 && "Unknown jump table encoding!");
-  return ~0;
+  llvm_unreachable("Unknown jump table encoding!");
 }
=20
 /// getEntryAlignment - Return the alignment of each entry in the jump tab=
le.
@@ -551,6 +557,8 @@
   switch (getEntryKind()) {
   case MachineJumpTableInfo::EK_BlockAddress:
     return TD.getPointerABIAlignment();
+  case MachineJumpTableInfo::EK_GPRel64BlockAddress:
+    return TD.getABIIntegerTypeAlignment(64);
   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
   case MachineJumpTableInfo::EK_LabelDifference32:
   case MachineJumpTableInfo::EK_Custom32:
@@ -558,8 +566,7 @@
   case MachineJumpTableInfo::EK_Inline:
     return 1;
   }
-  assert(0 && "Unknown jump table encoding!");
-  return ~0;
+  llvm_unreachable("Unknown jump table encoding!");
 }
=20
 /// createJumpTableIndex - Create a new jump table entry in the jump table=
 info.
@@ -619,6 +626,8 @@
 //  MachineConstantPool implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void MachineConstantPoolValue::anchor() { }
+
 Type *MachineConstantPoolEntry::getType() const {
   if (isMachineConstantPoolEntry())
     return Val.MachineCPVal->getType();
@@ -653,35 +662,37 @@
   // reject them.
   if (A->getType() =3D=3D B->getType()) return false;
=20
+  // We can't handle structs or arrays.
+  if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
+      isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
+    return false;
+ =20
   // For now, only support constants with the same size.
-  if (TD->getTypeStoreSize(A->getType()) !=3D TD->getTypeStoreSize(B->getT=
ype()))
+  uint64_t StoreSize =3D TD->getTypeStoreSize(A->getType());
+  if (StoreSize !=3D TD->getTypeStoreSize(B->getType()) ||=20
+      StoreSize > 128)
     return false;
=20
-  // If a floating-point value and an integer value have the same encoding,
-  // they can share a constant-pool entry.
-  if (const ConstantFP *AFP =3D dyn_cast<ConstantFP>(A))
-    if (const ConstantInt *BI =3D dyn_cast<ConstantInt>(B))
-      return AFP->getValueAPF().bitcastToAPInt() =3D=3D BI->getValue();
-  if (const ConstantFP *BFP =3D dyn_cast<ConstantFP>(B))
-    if (const ConstantInt *AI =3D dyn_cast<ConstantInt>(A))
-      return BFP->getValueAPF().bitcastToAPInt() =3D=3D AI->getValue();
+  Type *IntTy =3D IntegerType::get(A->getContext(), StoreSize*8);
=20
-  // Two vectors can share an entry if each pair of corresponding
-  // elements could.
-  if (const ConstantVector *AV =3D dyn_cast<ConstantVector>(A))
-    if (const ConstantVector *BV =3D dyn_cast<ConstantVector>(B)) {
-      if (AV->getType()->getNumElements() !=3D BV->getType()->getNumElemen=
ts())
-        return false;
-      for (unsigned i =3D 0, e =3D AV->getType()->getNumElements(); i !=3D=
 e; ++i)
-        if (!CanShareConstantPoolEntry(AV->getOperand(i),
-                                       BV->getOperand(i), TD))
-          return false;
-      return true;
-    }
-
-  // TODO: Handle other cases.
-
-  return false;
+  // Try constant folding a bitcast of both instructions to an integer.  I=
f we
+  // get two identical ConstantInt's, then we are good to share them.  We =
use
+  // the constant folding APIs to do this so that we get the benefit of
+  // TargetData.
+  if (isa<PointerType>(A->getType()))
+    A =3D ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
+                                 const_cast<Constant*>(A), TD);
+  else if (A->getType() !=3D IntTy)
+    A =3D ConstantFoldInstOperands(Instruction::BitCast, IntTy,
+                                 const_cast<Constant*>(A), TD);
+  if (isa<PointerType>(B->getType()))
+    B =3D ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
+                                 const_cast<Constant*>(B), TD);
+  else if (B->getType() !=3D IntTy)
+    B =3D ConstantFoldInstOperands(Instruction::BitCast, IntTy,
+                                 const_cast<Constant*>(B), TD);
+ =20
+  return A =3D=3D B;
 }
=20
 /// getConstantPoolIndex - Create a new entry in the constant pool or retu=
rn
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineF=
unctionAnalysis.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineFunctionAnalysis.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineFunctionAnalysis.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -19,9 +19,8 @@
=20
 char MachineFunctionAnalysis::ID =3D 0;
=20
-MachineFunctionAnalysis::MachineFunctionAnalysis(const TargetMachine &tm,
-                                                 CodeGenOpt::Level OL) :
-  FunctionPass(ID), TM(tm), OptLevel(OL), MF(0) {
+MachineFunctionAnalysis::MachineFunctionAnalysis(const TargetMachine &tm) :
+  FunctionPass(ID), TM(tm), MF(0) {
   initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineI=
nstr.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineInstr.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineInstr.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -40,6 +40,7 @@
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/Hashing.h"
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -178,6 +179,7 @@
   IsKill =3D isKill;
   IsDead =3D isDead;
   IsUndef =3D isUndef;
+  IsInternalRead =3D false;
   IsEarlyClobber =3D false;
   IsDebug =3D isDebug;
   SubReg =3D 0;
@@ -191,7 +193,6 @@
     return false;
=20
   switch (getType()) {
-  default: llvm_unreachable("Unrecognized operand type");
   case MachineOperand::MO_Register:
     return getReg() =3D=3D Other.getReg() && isDef() =3D=3D Other.isDef() =
&&
            getSubReg() =3D=3D Other.getSubReg();
@@ -216,11 +217,14 @@
            getOffset() =3D=3D Other.getOffset();
   case MachineOperand::MO_BlockAddress:
     return getBlockAddress() =3D=3D Other.getBlockAddress();
+  case MO_RegisterMask:
+    return getRegMask() =3D=3D Other.getRegMask();
   case MachineOperand::MO_MCSymbol:
     return getMCSymbol() =3D=3D Other.getMCSymbol();
   case MachineOperand::MO_Metadata:
     return getMetadata() =3D=3D Other.getMetadata();
   }
+  llvm_unreachable("Invalid machine operand type");
 }
=20
 /// print - Print the specified machine operand.
@@ -240,7 +244,7 @@
     OS << PrintReg(getReg(), TRI, getSubReg());
=20
     if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
-        isEarlyClobber()) {
+        isInternalRead() || isEarlyClobber()) {
       OS << '<';
       bool NeedComma =3D false;
       if (isDef()) {
@@ -256,14 +260,26 @@
           NeedComma =3D true;
       }
=20
-      if (isKill() || isDead() || isUndef()) {
+      if (isKill() || isDead() || isUndef() || isInternalRead()) {
         if (NeedComma) OS << ',';
-        if (isKill())  OS << "kill";
-        if (isDead())  OS << "dead";
+        NeedComma =3D false;
+        if (isKill()) {
+          OS << "kill";
+          NeedComma =3D true;
+        }
+        if (isDead()) {
+          OS << "dead";
+          NeedComma =3D true;
+        }
         if (isUndef()) {
-          if (isKill() || isDead())
-            OS << ',';
+          if (NeedComma) OS << ',';
           OS << "undef";
+          NeedComma =3D true;
+        }
+        if (isInternalRead()) {
+          if (NeedComma) OS << ',';
+          OS << "internal";
+          NeedComma =3D true;
         }
       }
       OS << '>';
@@ -311,6 +327,9 @@
     WriteAsOperand(OS, getBlockAddress(), /*PrintType=3D*/false);
     OS << '>';
     break;
+  case MachineOperand::MO_RegisterMask:
+    OS << "<regmask>";
+    break;
   case MachineOperand::MO_Metadata:
     OS << '<';
     WriteAsOperand(OS, getMetadata(), /*PrintType=3D*/false);
@@ -319,8 +338,6 @@
   case MachineOperand::MO_MCSymbol:
     OS << "<MCSym=3D" << *getMCSymbol() << '>';
     break;
-  default:
-    llvm_unreachable("Unrecognized operand type");
   }
=20
   if (unsigned TF =3D getTargetFlags())
@@ -364,10 +381,11 @@
=20
 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned =
f,
                                      uint64_t s, unsigned int a,
-                                     const MDNode *TBAAInfo)
+                                     const MDNode *TBAAInfo,
+                                     const MDNode *Ranges)
   : PtrInfo(ptrinfo), Size(s),
     Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
-    TBAAInfo(TBAAInfo) {
+    TBAAInfo(TBAAInfo), Ranges(Ranges) {
   assert((PtrInfo.V =3D=3D 0 || isa<PointerType>(PtrInfo.V->getType())) &&
          "invalid pointer value");
   assert(getBaseAlignment() =3D=3D a && "Alignment is not a power of 2!");
@@ -465,7 +483,7 @@
 /// MCID NULL and no operands.
 MachineInstr::MachineInstr()
   : MCID(0), Flags(0), AsmPrinterFlags(0),
-    MemRefs(0), MemRefsEnd(0),
+    NumMemRefs(0), MemRefs(0),
     Parent(0) {
   // Make sure that we get added to a machine basicblock
   LeakDetector::addGarbageObject(this);
@@ -473,10 +491,10 @@
=20
 void MachineInstr::addImplicitDefUseOperands() {
   if (MCID->ImplicitDefs)
-    for (const unsigned *ImpDefs =3D MCID->ImplicitDefs; *ImpDefs; ++ImpDe=
fs)
+    for (const uint16_t *ImpDefs =3D MCID->getImplicitDefs(); *ImpDefs; ++=
ImpDefs)
       addOperand(MachineOperand::CreateReg(*ImpDefs, true, true));
   if (MCID->ImplicitUses)
-    for (const unsigned *ImpUses =3D MCID->ImplicitUses; *ImpUses; ++ImpUs=
es)
+    for (const uint16_t *ImpUses =3D MCID->getImplicitUses(); *ImpUses; ++=
ImpUses)
       addOperand(MachineOperand::CreateReg(*ImpUses, false, true));
 }
=20
@@ -485,7 +503,7 @@
 /// the MCInstrDesc.
 MachineInstr::MachineInstr(const MCInstrDesc &tid, bool NoImp)
   : MCID(&tid), Flags(0), AsmPrinterFlags(0),
-    MemRefs(0), MemRefsEnd(0), Parent(0) {
+    NumMemRefs(0), MemRefs(0), Parent(0) {
   unsigned NumImplicitOps =3D 0;
   if (!NoImp)
     NumImplicitOps =3D MCID->getNumImplicitDefs() + MCID->getNumImplicitUs=
es();
@@ -500,7 +518,7 @@
 MachineInstr::MachineInstr(const MCInstrDesc &tid, const DebugLoc dl,
                            bool NoImp)
   : MCID(&tid), Flags(0), AsmPrinterFlags(0),
-    MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
+    NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
   unsigned NumImplicitOps =3D 0;
   if (!NoImp)
     NumImplicitOps =3D MCID->getNumImplicitDefs() + MCID->getNumImplicitUs=
es();
@@ -516,7 +534,7 @@
 /// basic block.
 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const MCInstrDesc &tid)
   : MCID(&tid), Flags(0), AsmPrinterFlags(0),
-    MemRefs(0), MemRefsEnd(0), Parent(0) {
+    NumMemRefs(0), MemRefs(0), Parent(0) {
   assert(MBB && "Cannot use inserting ctor with null basic block!");
   unsigned NumImplicitOps =3D
     MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
@@ -532,7 +550,7 @@
 MachineInstr::MachineInstr(MachineBasicBlock *MBB, const DebugLoc dl,
                            const MCInstrDesc &tid)
   : MCID(&tid), Flags(0), AsmPrinterFlags(0),
-    MemRefs(0), MemRefsEnd(0), Parent(0), debugLoc(dl) {
+    NumMemRefs(0), MemRefs(0), Parent(0), debugLoc(dl) {
   assert(MBB && "Cannot use inserting ctor with null basic block!");
   unsigned NumImplicitOps =3D
     MCID->getNumImplicitDefs() + MCID->getNumImplicitUses();
@@ -547,7 +565,7 @@
 ///
 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
   : MCID(&MI.getDesc()), Flags(0), AsmPrinterFlags(0),
-    MemRefs(MI.MemRefs), MemRefsEnd(MI.MemRefsEnd),
+    NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
     Parent(0), debugLoc(MI.getDebugLoc()) {
   Operands.reserve(MI.getNumOperands());
=20
@@ -722,17 +740,33 @@
 void MachineInstr::addMemOperand(MachineFunction &MF,
                                  MachineMemOperand *MO) {
   mmo_iterator OldMemRefs =3D MemRefs;
-  mmo_iterator OldMemRefsEnd =3D MemRefsEnd;
+  uint16_t OldNumMemRefs =3D NumMemRefs;
=20
-  size_t NewNum =3D (MemRefsEnd - MemRefs) + 1;
+  uint16_t NewNum =3D NumMemRefs + 1;
   mmo_iterator NewMemRefs =3D MF.allocateMemRefsArray(NewNum);
-  mmo_iterator NewMemRefsEnd =3D NewMemRefs + NewNum;
=20
-  std::copy(OldMemRefs, OldMemRefsEnd, NewMemRefs);
+  std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
   NewMemRefs[NewNum - 1] =3D MO;
=20
   MemRefs =3D NewMemRefs;
-  MemRefsEnd =3D NewMemRefsEnd;
+  NumMemRefs =3D NewNum;
+}
+
+bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) cons=
t {
+  const MachineBasicBlock *MBB =3D getParent();
+  MachineBasicBlock::const_instr_iterator MII =3D *this; ++MII;
+  while (MII !=3D MBB->end() && MII->isInsideBundle()) {
+    if (MII->getDesc().getFlags() & Mask) {
+      if (Type =3D=3D AnyInBundle)
+        return true;
+    } else {
+      if (Type =3D=3D AllInBundle)
+        return false;
+    }
+    ++MII;
+  }
+
+  return Type =3D=3D AllInBundle;
 }
=20
 bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
@@ -743,6 +777,19 @@
       Other->getNumOperands() !=3D getNumOperands())
     return false;
=20
+  if (isBundle()) {
+    // Both instructions are bundles, compare MIs inside the bundle.
+    MachineBasicBlock::const_instr_iterator I1 =3D *this;
+    MachineBasicBlock::const_instr_iterator E1 =3D getParent()->instr_end(=
);
+    MachineBasicBlock::const_instr_iterator I2 =3D *Other;
+    MachineBasicBlock::const_instr_iterator E2=3D Other->getParent()->inst=
r_end();
+    while (++I1 !=3D E1 && I1->isInsideBundle()) {
+      ++I2;
+      if (I2 =3D=3D E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, =
Check))
+        return false;
+    }
+  }
+
   // Check operands to make sure they match.
   for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D getOperand(i);
@@ -789,6 +836,18 @@
 /// block, and returns it, but does not delete it.
 MachineInstr *MachineInstr::removeFromParent() {
   assert(getParent() && "Not embedded in a basic block!");
+
+  // If it's a bundle then remove the MIs inside the bundle as well.
+  if (isBundle()) {
+    MachineBasicBlock *MBB =3D getParent();
+    MachineBasicBlock::instr_iterator MII =3D *this; ++MII;
+    MachineBasicBlock::instr_iterator E =3D MBB->instr_end();
+    while (MII !=3D E && MII->isInsideBundle()) {
+      MachineInstr *MI =3D &*MII;
+      ++MII;
+      MBB->remove(MI);
+    }
+  }
   getParent()->remove(this);
   return this;
 }
@@ -798,6 +857,17 @@
 /// block, and deletes it.
 void MachineInstr::eraseFromParent() {
   assert(getParent() && "Not embedded in a basic block!");
+  // If it's a bundle then remove the MIs inside the bundle as well.
+  if (isBundle()) {
+    MachineBasicBlock *MBB =3D getParent();
+    MachineBasicBlock::instr_iterator MII =3D *this; ++MII;
+    MachineBasicBlock::instr_iterator E =3D MBB->instr_end();
+    while (MII !=3D E && MII->isInsideBundle()) {
+      MachineInstr *MI =3D &*MII;
+      ++MII;
+      MBB->erase(MI);
+    }
+  }
   getParent()->erase(this);
 }
=20
@@ -817,6 +887,16 @@
   return NumOperands;
 }
=20
+/// isBundled - Return true if this instruction part of a bundle. This is =
true
+/// if either itself or its following instruction is marked "InsideBundle".
+bool MachineInstr::isBundled() const {
+  if (isInsideBundle())
+    return true;
+  MachineBasicBlock::const_instr_iterator nextMI =3D this;
+  ++nextMI;
+  return nextMI !=3D Parent->instr_end() && nextMI->isInsideBundle();
+}
+
 bool MachineInstr::isStackAligningInlineAsm() const {
   if (isInlineAsm()) {
     unsigned ExtraInfo =3D getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
@@ -887,6 +967,20 @@
   return NULL;
 }
=20
+/// getBundleSize - Return the number of instructions inside the MI bundle.
+unsigned MachineInstr::getBundleSize() const {
+  assert(isBundle() && "Expecting a bundle");
+
+  MachineBasicBlock::const_instr_iterator I =3D *this;
+  unsigned Size =3D 0;
+  while ((++I)->isInsideBundle()) {
+    ++Size;
+  }
+  assert(Size > 1 && "Malformed bundle");
+
+  return Size;
+}
+
 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use=
 of
 /// the specific register or -1 if it is not found. It further tightens
 /// the search criteria to a use that kills the register if isKill is true.
@@ -948,6 +1042,10 @@
   bool isPhys =3D TargetRegisterInfo::isPhysicalRegister(Reg);
   for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D getOperand(i);
+    // Accept regmask operands when Overlap is set.
+    // Ignore them when looking for a specific def operand (Overlap =3D=3D=
 false).
+    if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
+      return i;
     if (!MO.isReg() || !MO.isDef())
       continue;
     unsigned MOReg =3D MO.getReg();
@@ -1118,6 +1216,8 @@
=20
 /// copyPredicates - Copies predicate operand(s) from MI.
 void MachineInstr::copyPredicates(const MachineInstr *MI) {
+  assert(!isBundle() && "MachineInstr::copyPredicates() can't handle bundl=
es");
+
   const MCInstrDesc &MCID =3D MI->getDesc();
   if (!MCID.isPredicable())
     return;
@@ -1159,13 +1259,13 @@
                                 AliasAnalysis *AA,
                                 bool &SawStore) const {
   // Ignore stuff that we obviously can't move.
-  if (MCID->mayStore() || MCID->isCall()) {
+  if (mayStore() || isCall()) {
     SawStore =3D true;
     return false;
   }
=20
   if (isLabel() || isDebugValue() ||
-      MCID->isTerminator() || hasUnmodeledSideEffects())
+      isTerminator() || hasUnmodeledSideEffects())
     return false;
=20
   // See if this instruction does a load.  If so, we have to guarantee tha=
t the
@@ -1173,7 +1273,7 @@
   // destination. The check for isInvariantLoad gives the targe the chance=
 to
   // classify the load as always returning a constant, e.g. a constant pool
   // load.
-  if (MCID->mayLoad() && !isInvariantLoad(AA))
+  if (mayLoad() && !isInvariantLoad(AA))
     // Otherwise, this is a real load.  If there is a store between the lo=
ad and
     // end of block, or if the load is volatile, we can't move it.
     return !SawStore && !hasVolatileMemoryRef();
@@ -1213,9 +1313,9 @@
 /// have no volatile memory references.
 bool MachineInstr::hasVolatileMemoryRef() const {
   // An instruction known never to access memory won't have a volatile acc=
ess.
-  if (!MCID->mayStore() &&
-      !MCID->mayLoad() &&
-      !MCID->isCall() &&
+  if (!mayStore() &&
+      !mayLoad() &&
+      !isCall() &&
       !hasUnmodeledSideEffects())
     return false;
=20
@@ -1239,7 +1339,7 @@
 /// *all* loads the instruction does are invariant (if it does multiple lo=
ads).
 bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
   // If the instruction doesn't load at all, it isn't an invariant load.
-  if (!MCID->mayLoad())
+  if (!mayLoad())
     return false;
=20
   // If the instruction has lost its memoperands, conservatively assume th=
at
@@ -1253,6 +1353,7 @@
        E =3D memoperands_end(); I !=3D E; ++I) {
     if ((*I)->isVolatile()) return false;
     if ((*I)->isStore()) return false;
+    if ((*I)->isInvariant()) return true;
=20
     if (const Value *V =3D (*I)->getValue()) {
       // A load from a constant PseudoSourceValue is invariant.
@@ -1291,7 +1392,7 @@
 }
=20
 bool MachineInstr::hasUnmodeledSideEffects() const {
-  if (getDesc().hasUnmodeledSideEffects())
+  if (hasProperty(MCID::UnmodeledSideEffects))
     return true;
   if (isInlineAsm()) {
     unsigned ExtraInfo =3D getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
@@ -1384,7 +1485,10 @@
     OS << " =3D ";
=20
   // Print the opcode name.
-  OS << getDesc().getName();
+  if (TM && TM->getInstrInfo())
+    OS << TM->getInstrInfo()->getName(getOpcode());
+  else
+    OS << "UNKNOWN";
=20
   // Print the rest of the operands.
   bool OmittedAnyCallClobbers =3D false;
@@ -1419,14 +1523,14 @@
     // call instructions much less noisy on targets where calls clobber lo=
ts
     // of registers. Don't rely on MO.isDead() because we may be called be=
fore
     // LiveVariables is run, or we may be looking at a non-allocatable reg.
-    if (MF && getDesc().isCall() &&
+    if (MF && isCall() &&
         MO.isReg() && MO.isImplicit() && MO.isDef()) {
       unsigned Reg =3D MO.getReg();
       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
         const MachineRegisterInfo &MRI =3D MF->getRegInfo();
         if (MRI.use_empty(Reg) && !MRI.isLiveOut(Reg)) {
           bool HasAliasLive =3D false;
-          for (const unsigned *Alias =3D TM->getRegisterInfo()->getAliasSe=
t(Reg);
+          for (const uint16_t *Alias =3D TM->getRegisterInfo()->getAliasSe=
t(Reg);
                unsigned AliasReg =3D *Alias; ++Alias)
             if (!MRI.use_empty(AliasReg) || MRI.isLiveOut(AliasReg)) {
               HasAliasLive =3D true;
@@ -1617,6 +1721,20 @@
   return Found;
 }
=20
+void MachineInstr::clearRegisterKills(unsigned Reg,
+                                      const TargetRegisterInfo *RegInfo) {
+  if (!TargetRegisterInfo::isPhysicalRegister(Reg))
+    RegInfo =3D 0;
+  for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i) {
+    MachineOperand &MO =3D getOperand(i);
+    if (!MO.isReg() || !MO.isUse() || !MO.isKill())
+      continue;
+    unsigned OpReg =3D MO.getReg();
+    if (OpReg =3D=3D Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpRe=
g)))
+      MO.setIsKill(false);
+  }
+}
+
 bool MachineInstr::addRegisterDead(unsigned IncomingReg,
                                    const TargetRegisterInfo *RegInfo,
                                    bool AddIfNotFound) {
@@ -1689,16 +1807,21 @@
                                        true  /*IsImp*/));
 }
=20
-void MachineInstr::setPhysRegsDeadExcept(const SmallVectorImpl<unsigned> &=
UsedRegs,
+void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
                                          const TargetRegisterInfo &TRI) {
+  bool HasRegMask =3D false;
   for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i) {
     MachineOperand &MO =3D getOperand(i);
+    if (MO.isRegMask()) {
+      HasRegMask =3D true;
+      continue;
+    }
     if (!MO.isReg() || !MO.isDef()) continue;
     unsigned Reg =3D MO.getReg();
-    if (Reg =3D=3D 0) continue;
+    if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
     bool Dead =3D true;
-    for (SmallVectorImpl<unsigned>::const_iterator I =3D UsedRegs.begin(),
-         E =3D UsedRegs.end(); I !=3D E; ++I)
+    for (ArrayRef<unsigned>::iterator I =3D UsedRegs.begin(), E =3D UsedRe=
gs.end();
+         I !=3D E; ++I)
       if (TRI.regsOverlap(*I, Reg)) {
         Dead =3D false;
         break;
@@ -1706,53 +1829,66 @@
     // If there are no uses, including partial uses, the def is dead.
     if (Dead) MO.setIsDead();
   }
+
+  // This is a call with a register mask operand.
+  // Mask clobbers are always dead, so add defs for the non-dead defines.
+  if (HasRegMask)
+    for (ArrayRef<unsigned>::iterator I =3D UsedRegs.begin(), E =3D UsedRe=
gs.end();
+         I !=3D E; ++I)
+      addRegisterDefined(*I, &TRI);
 }
=20
 unsigned
 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
-  unsigned Hash =3D MI->getOpcode() * 37;
+  // Build up a buffer of hash code components.
+  //
+  // FIXME: This is a total hack. We should have a hash_value overload for
+  // MachineOperand, but currently that doesn't work because there are many
+  // different ideas of "equality" and thus different sets of information =
that
+  // contribute to the hash code. This one happens to want to take a speci=
fic
+  // subset. And it's still not clear that this routine uses the *correct*
+  // subset of information when computing the hash code. The goal is to us=
e the
+  // same inputs for the hash code here that MachineInstr::isIdenticalTo u=
ses to
+  // test for equality when passed the 'IgnoreVRegDefs' filter flag. It wo=
uld
+  // be very useful to factor the selection of relevant inputs out of the =
two
+  // functions and into a common routine, but it's not clear how that can =
be
+  // done.
+  SmallVector<size_t, 8> HashComponents;
+  HashComponents.reserve(MI->getNumOperands() + 1);
+  HashComponents.push_back(MI->getOpcode());
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D MI->getOperand(i);
-    uint64_t Key =3D (uint64_t)MO.getType() << 32;
     switch (MO.getType()) {
     default: break;
     case MachineOperand::MO_Register:
       if (MO.isDef() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
         continue;  // Skip virtual register defs.
-      Key |=3D MO.getReg();
+      HashComponents.push_back(hash_combine(MO.getType(), MO.getReg()));
       break;
     case MachineOperand::MO_Immediate:
-      Key |=3D MO.getImm();
+      HashComponents.push_back(hash_combine(MO.getType(), MO.getImm()));
       break;
     case MachineOperand::MO_FrameIndex:
     case MachineOperand::MO_ConstantPoolIndex:
     case MachineOperand::MO_JumpTableIndex:
-      Key |=3D MO.getIndex();
+      HashComponents.push_back(hash_combine(MO.getType(), MO.getIndex()));
       break;
     case MachineOperand::MO_MachineBasicBlock:
-      Key |=3D DenseMapInfo<void*>::getHashValue(MO.getMBB());
+      HashComponents.push_back(hash_combine(MO.getType(), MO.getMBB()));
       break;
     case MachineOperand::MO_GlobalAddress:
-      Key |=3D DenseMapInfo<void*>::getHashValue(MO.getGlobal());
+      HashComponents.push_back(hash_combine(MO.getType(), MO.getGlobal()));
       break;
     case MachineOperand::MO_BlockAddress:
-      Key |=3D DenseMapInfo<void*>::getHashValue(MO.getBlockAddress());
+      HashComponents.push_back(hash_combine(MO.getType(),
+                                            MO.getBlockAddress()));
       break;
     case MachineOperand::MO_MCSymbol:
-      Key |=3D DenseMapInfo<void*>::getHashValue(MO.getMCSymbol());
+      HashComponents.push_back(hash_combine(MO.getType(), MO.getMCSymbol()=
));
       break;
     }
-    Key +=3D ~(Key << 32);
-    Key ^=3D (Key >> 22);
-    Key +=3D ~(Key << 13);
-    Key ^=3D (Key >> 8);
-    Key +=3D (Key << 3);
-    Key ^=3D (Key >> 15);
-    Key +=3D ~(Key << 27);
-    Key ^=3D (Key >> 31);
-    Hash =3D (unsigned)Key + Hash * 37;
   }
-  return Hash;
+  return hash_combine_range(HashComponents.begin(), HashComponents.end());
 }
=20
 void MachineInstr::emitError(StringRef Msg) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineL=
ICM.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineLICM.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineLICM.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -45,7 +45,7 @@
 static cl::opt<bool>
 AvoidSpeculation("avoid-speculation",
                  cl::desc("MachineLICM should avoid speculation"),
-                 cl::init(false), cl::Hidden);
+                 cl::init(true), cl::Hidden);
=20
 STATISTIC(NumHoisted,
           "Number of machine instructions hoisted out of loops");
@@ -60,8 +60,6 @@
=20
 namespace {
   class MachineLICM : public MachineFunctionPass {
-    bool PreRegAlloc;
-
     const TargetMachine   *TM;
     const TargetInstrInfo *TII;
     const TargetLowering *TLI;
@@ -69,6 +67,7 @@
     const MachineFrameInfo *MFI;
     MachineRegisterInfo *MRI;
     const InstrItineraryData *InstrItins;
+    bool PreRegAlloc;
=20
     // Various analyses that we use...
     AliasAnalysis        *AA;      // Alias analysis info.
@@ -81,7 +80,13 @@
     MachineLoop *CurLoop;          // The current loop we are working on.
     MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
=20
-    BitVector AllocatableSet;
+    // Exit blocks for CurLoop.
+    SmallVector<MachineBasicBlock*, 8> ExitBlocks;
+
+    bool isExitBlock(const MachineBasicBlock *MBB) const {
+      return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=3D
+        ExitBlocks.end();
+    }
=20
     // Track 'estimated' register pressure.
     SmallSet<unsigned, 32> RegSeen;
@@ -122,8 +127,6 @@
=20
     virtual bool runOnMachineFunction(MachineFunction &MF);
=20
-    const char *getPassName() const { return "Machine Instruction LICM"; }
-
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<MachineLoopInfo>();
       AU.addRequired<MachineDominatorTree>();
@@ -165,7 +168,9 @@
=20
     /// ProcessMI - Examine the instruction for potentai LICM candidate. A=
lso
     /// gather register def and frame object update information.
-    void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
+    void ProcessMI(MachineInstr *MI,
+                   BitVector &PhysRegDefs,
+                   BitVector &PhysRegClobbers,
                    SmallSet<int, 32> &StoredFIs,
                    SmallVector<CandidateInfo, 32> &Candidates);
=20
@@ -182,12 +187,12 @@
     /// invariant. I.e., all virtual register operands are defined outside=
 of
     /// the loop, physical registers aren't accessed (explicitly or implic=
itly),
     /// and the instruction is hoistable.
-    ///=20
+    ///
     bool IsLoopInvariantInst(MachineInstr &I);
=20
-    /// HasAnyPHIUse - Return true if the specified register is used by any
-    /// phi node.
-    bool HasAnyPHIUse(unsigned Reg) const;
+    /// HasLoopPHIUse - Return true if the specified instruction is used b=
y any
+    /// phi node in the current loop.
+    bool HasLoopPHIUse(const MachineInstr *MI) const;
=20
     /// HasHighOperandLatency - Compute operand latency between a def of '=
Reg'
     /// and an use in the current loop, return true if the target consider=
ed
@@ -200,7 +205,7 @@
     /// CanCauseHighRegPressure - Visit BBs from header to current BB,
     /// check if hoisting an instruction of the given cost matrix can caus=
e high
     /// register pressure.
-    bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
+    bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap=
);
=20
     /// UpdateBackTraceRegPressure - Traverse the back trace from header to
     /// the current block and update their register pressures to reflect t=
he
@@ -215,13 +220,25 @@
     /// If not then a load from this mbb may not be safe to hoist.
     bool IsGuaranteedToExecute(MachineBasicBlock *BB);
=20
-    /// HoistRegion - Walk the specified region of the CFG (defined by all
-    /// blocks dominated by the specified block, and that are in the curre=
nt
-    /// loop) in depth first order w.r.t the DominatorTree. This allows us=
 to
-    /// visit definitions before uses, allowing us to hoist a loop body in=
 one
-    /// pass without iteration.
+    void EnterScope(MachineBasicBlock *MBB);
+
+    void ExitScope(MachineBasicBlock *MBB);
+
+    /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to gi=
ven
+    /// dominator tree node if its a leaf or all of its children are done.=
 Walk
+    /// up the dominator tree to destroy ancestors which are now done.
+    void ExitScopeIfDone(MachineDomTreeNode *Node,
+                DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
+                DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &Parent=
Map);
+
+    /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
+    /// blocks dominated by the specified header block, and that are in the
+    /// current loop) in depth first order w.r.t the DominatorTree. This a=
llows
+    /// us to visit definitions before uses, allowing us to hoist a loop b=
ody in
+    /// one pass without iteration.
     ///
-    void HoistRegion(MachineDomTreeNode *N, bool IsHeader =3D false);
+    void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
+    void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
=20
     /// getRegisterClassIDAndCost - For a given MI, register, and the oper=
and
     /// index, return the ID and cost of its representative register class=
 by
@@ -278,6 +295,7 @@
 } // end anonymous namespace
=20
 char MachineLICM::ID =3D 0;
+char &llvm::MachineLICMID =3D MachineLICM::ID;
 INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
                 "Machine Loop Invariant Code Motion", false, false)
 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
@@ -286,10 +304,6 @@
 INITIALIZE_PASS_END(MachineLICM, "machinelicm",
                 "Machine Loop Invariant Code Motion", false, false)
=20
-FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
-  return new MachineLICM(PreRegAlloc);
-}
-
 /// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-m=
ost
 /// loop that has a unique predecessor.
 static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
@@ -305,12 +319,6 @@
 }
=20
 bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
-  if (PreRegAlloc)
-    DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
-  else
-    DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
-  DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
-
   Changed =3D FirstInLoop =3D false;
   TM =3D &MF.getTarget();
   TII =3D TM->getInstrInfo();
@@ -319,7 +327,14 @@
   MFI =3D MF.getFrameInfo();
   MRI =3D &MF.getRegInfo();
   InstrItins =3D TM->getInstrItineraryData();
-  AllocatableSet =3D TRI->getAllocatableSet(MF);
+
+  PreRegAlloc =3D MRI->isSSA();
+
+  if (PreRegAlloc)
+    DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
+  else
+    DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
+  DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
=20
   if (PreRegAlloc) {
     // Estimate register pressure during pre-regalloc pass.
@@ -341,6 +356,7 @@
   while (!Worklist.empty()) {
     CurLoop =3D Worklist.pop_back_val();
     CurPreheader =3D 0;
+    ExitBlocks.clear();
=20
     // If this is done before regalloc, only visit outer-most preheader-sp=
orting
     // loops.
@@ -349,6 +365,8 @@
       continue;
     }
=20
+    CurLoop->getExitBlocks(ExitBlocks);
+
     if (!PreRegAlloc)
       HoistRegionPostRA();
     else {
@@ -356,7 +374,7 @@
       // being hoisted.
       MachineDomTreeNode *N =3D DT->getNode(CurLoop->getHeader());
       FirstInLoop =3D true;
-      HoistRegion(N, true);
+      HoistOutOfLoop(N);
       CSEMap.clear();
     }
   }
@@ -383,7 +401,8 @@
 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
 /// gather register def and frame object update information.
 void MachineLICM::ProcessMI(MachineInstr *MI,
-                            unsigned *PhysRegDefs,
+                            BitVector &PhysRegDefs,
+                            BitVector &PhysRegClobbers,
                             SmallSet<int, 32> &StoredFIs,
                             SmallVector<CandidateInfo, 32> &Candidates) {
   bool RuledOut =3D false;
@@ -402,6 +421,13 @@
       continue;
     }
=20
+    // We can't hoist an instruction defining a physreg that is clobbered =
in
+    // the loop.
+    if (MO.isRegMask()) {
+      PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
+      continue;
+    }
+
     if (!MO.isReg())
       continue;
     unsigned Reg =3D MO.getReg();
@@ -411,7 +437,7 @@
            "Not expecting virtual register!");
=20
     if (!MO.isDef()) {
-      if (Reg && PhysRegDefs[Reg])
+      if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
         // If it's using a non-loop-invariant register, then it's obviousl=
y not
         // safe to hoist.
         HasNonInvariantUse =3D true;
@@ -419,9 +445,8 @@
     }
=20
     if (MO.isImplicit()) {
-      ++PhysRegDefs[Reg];
-      for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
-        ++PhysRegDefs[*AS];
+      for (const uint16_t *AS =3D TRI->getOverlaps(Reg); *AS; ++AS)
+        PhysRegClobbers.set(*AS);
       if (!MO.isDead())
         // Non-dead implicit def? This cannot be hoisted.
         RuledOut =3D true;
@@ -438,14 +463,17 @@
       Def =3D Reg;
=20
     // If we have already seen another instruction that defines the same
-    // register, then this is not safe.
-    if (++PhysRegDefs[Reg] > 1)
-      // MI defined register is seen defined by another instruction in
-      // the loop, it cannot be a LICM candidate.
-      RuledOut =3D true;
-    for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
-      if (++PhysRegDefs[*AS] > 1)
+    // register, then this is not safe.  Two defs is indicated by setting a
+    // PhysRegClobbers bit.
+    for (const uint16_t *AS =3D TRI->getOverlaps(Reg); *AS; ++AS) {
+      if (PhysRegDefs.test(*AS))
+        PhysRegClobbers.set(*AS);
+      if (PhysRegClobbers.test(*AS))
+        // MI defined register is seen defined by another instruction in
+        // the loop, it cannot be a LICM candidate.
         RuledOut =3D true;
+      PhysRegDefs.set(*AS);
+    }
   }
=20
   // Only consider reloads for now and remats which do not have register
@@ -461,9 +489,13 @@
 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
 /// invariants out to the preheader.
 void MachineLICM::HoistRegionPostRA() {
+  MachineBasicBlock *Preheader =3D getCurPreheader();
+  if (!Preheader)
+    return;
+
   unsigned NumRegs =3D TRI->getNumRegs();
-  unsigned *PhysRegDefs =3D new unsigned[NumRegs];
-  std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
+  BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
+  BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
=20
   SmallVector<CandidateInfo, 32> Candidates;
   SmallSet<int, 32> StoredFIs;
@@ -485,16 +517,31 @@
     for (MachineBasicBlock::livein_iterator I =3D BB->livein_begin(),
            E =3D BB->livein_end(); I !=3D E; ++I) {
       unsigned Reg =3D *I;
-      ++PhysRegDefs[Reg];
-      for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
-        ++PhysRegDefs[*AS];
+      for (const uint16_t *AS =3D TRI->getOverlaps(Reg); *AS; ++AS)
+        PhysRegDefs.set(*AS);
     }
=20
     SpeculationState =3D SpeculateUnknown;
     for (MachineBasicBlock::iterator
            MII =3D BB->begin(), E =3D BB->end(); MII !=3D E; ++MII) {
       MachineInstr *MI =3D &*MII;
-      ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
+      ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
+    }
+  }
+
+  // Gather the registers read / clobbered by the terminator.
+  BitVector TermRegs(NumRegs);
+  MachineBasicBlock::iterator TI =3D Preheader->getFirstTerminator();
+  if (TI !=3D Preheader->end()) {
+    for (unsigned i =3D 0, e =3D TI->getNumOperands(); i !=3D e; ++i) {
+      const MachineOperand &MO =3D TI->getOperand(i);
+      if (!MO.isReg())
+        continue;
+      unsigned Reg =3D MO.getReg();
+      if (!Reg)
+        continue;
+      for (const uint16_t *AS =3D TRI->getOverlaps(Reg); *AS; ++AS)
+        TermRegs.set(*AS);
     }
   }
=20
@@ -503,19 +550,25 @@
   //    instruction in the loop.
   // 2. If the candidate is a load from stack slot (always true for now),
   //    check if the slot is stored anywhere in the loop.
+  // 3. Make sure candidate def should not clobber
+  //    registers read by the terminator. Similarly its def should not be
+  //    clobbered by the terminator.
   for (unsigned i =3D 0, e =3D Candidates.size(); i !=3D e; ++i) {
     if (Candidates[i].FI !=3D INT_MIN &&
         StoredFIs.count(Candidates[i].FI))
       continue;
=20
-    if (PhysRegDefs[Candidates[i].Def] =3D=3D 1) {
+    unsigned Def =3D Candidates[i].Def;
+    if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
       bool Safe =3D true;
       MachineInstr *MI =3D Candidates[i].MI;
       for (unsigned j =3D 0, ee =3D MI->getNumOperands(); j !=3D ee; ++j) {
         const MachineOperand &MO =3D MI->getOperand(j);
         if (!MO.isReg() || MO.isDef() || !MO.getReg())
           continue;
-        if (PhysRegDefs[MO.getReg()]) {
+        unsigned Reg =3D MO.getReg();
+        if (PhysRegDefs.test(Reg) ||
+            PhysRegClobbers.test(Reg)) {
           // If it's using a non-loop-invariant register, then it's obviou=
sly
           // not safe to hoist.
           Safe =3D false;
@@ -526,8 +579,6 @@
         HoistPostRA(MI, Candidates[i].Def);
     }
   }
-
-  delete[] PhysRegDefs;
 }
=20
 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the cur=
rent
@@ -556,26 +607,17 @@
 /// dirty work.
 void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
   MachineBasicBlock *Preheader =3D getCurPreheader();
-  if (!Preheader) return;
=20
   // Now move the instructions to the predecessor, inserting it before any
   // terminator instructions.
-  DEBUG({
-      dbgs() << "Hoisting " << *MI;
-      if (Preheader->getBasicBlock())
-        dbgs() << " to MachineBasicBlock "
-               << Preheader->getName();
-      if (MI->getParent()->getBasicBlock())
-        dbgs() << " from MachineBasicBlock "
-               << MI->getParent()->getName();
-      dbgs() << "\n";
-    });
+  DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB=
#"
+               << MI->getParent()->getNumber() << ": " << *MI);
=20
   // Splice the instruction to the preheader.
   MachineBasicBlock *MBB =3D MI->getParent();
   Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
=20
-  // Add register to livein list to all the BBs in the current loop since =
a=20
+  // Add register to livein list to all the BBs in the current loop since a
   // loop invariant must be kept live throughout the whole loop. This is
   // important to ensure later passes do not scavenge the def register.
   AddToLiveIns(Def);
@@ -589,7 +631,7 @@
 bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
   if (SpeculationState !=3D SpeculateUnknown)
     return SpeculationState =3D=3D SpeculateFalse;
-   =20
+
   if (BB !=3D CurLoop->getHeader()) {
     // Check loop exiting blocks.
     SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
@@ -605,57 +647,126 @@
   return true;
 }
=20
-/// HoistRegion - Walk the specified region of the CFG (defined by all blo=
cks
-/// dominated by the specified block, and that are in the current loop) in=
 depth
-/// first order w.r.t the DominatorTree. This allows us to visit definitio=
ns
-/// before uses, allowing us to hoist a loop body in one pass without iter=
ation.
-///
-void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
-  assert(N !=3D 0 && "Null dominator tree node?");
-  MachineBasicBlock *BB =3D N->getBlock();
+void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
+  DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
=20
-  // If the header of the loop containing this basic block is a landing pa=
d,
-  // then don't try to hoist instructions out of this loop.
-  const MachineLoop *ML =3D MLI->getLoopFor(BB);
-  if (ML && ML->getHeader()->isLandingPad()) return;
+  // Remember livein register pressure.
+  BackTrace.push_back(RegPressure);
+}
=20
-  // If this subregion is not in the top level loop at all, exit.
-  if (!CurLoop->contains(BB)) return;
+void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
+  DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
+  BackTrace.pop_back();
+}
=20
-  MachineBasicBlock *Preheader =3D getCurPreheader();
-  if (!Preheader)
+/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the gi=
ven
+/// dominator tree node if its a leaf or all of its children are done. Walk
+/// up the dominator tree to destroy ancestors which are now done.
+void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
+                DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
+                DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &Parent=
Map) {
+  if (OpenChildren[Node])
     return;
=20
-  if (IsHeader) {
+  // Pop scope.
+  ExitScope(Node->getBlock());
+
+  // Now traverse upwards to pop ancestors whose offsprings are all done.
+  while (MachineDomTreeNode *Parent =3D ParentMap[Node]) {
+    unsigned Left =3D --OpenChildren[Parent];
+    if (Left !=3D 0)
+      break;
+    ExitScope(Parent->getBlock());
+    Node =3D Parent;
+  }
+}
+
+/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
+/// blocks dominated by the specified header block, and that are in the
+/// current loop) in depth first order w.r.t the DominatorTree. This allows
+/// us to visit definitions before uses, allowing us to hoist a loop body =
in
+/// one pass without iteration.
+///
+void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
+  SmallVector<MachineDomTreeNode*, 32> Scopes;
+  SmallVector<MachineDomTreeNode*, 8> WorkList;
+  DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
+  DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
+
+  // Perform a DFS walk to determine the order of visit.
+  WorkList.push_back(HeaderN);
+  do {
+    MachineDomTreeNode *Node =3D WorkList.pop_back_val();
+    assert(Node !=3D 0 && "Null dominator tree node?");
+    MachineBasicBlock *BB =3D Node->getBlock();
+
+    // If the header of the loop containing this basic block is a landing =
pad,
+    // then don't try to hoist instructions out of this loop.
+    const MachineLoop *ML =3D MLI->getLoopFor(BB);
+    if (ML && ML->getHeader()->isLandingPad())
+      continue;
+
+    // If this subregion is not in the top level loop at all, exit.
+    if (!CurLoop->contains(BB))
+      continue;
+
+    Scopes.push_back(Node);
+    const std::vector<MachineDomTreeNode*> &Children =3D Node->getChildren=
();
+    unsigned NumChildren =3D Children.size();
+
+    // Don't hoist things out of a large switch statement.  This often cau=
ses
+    // code to be hoisted that wasn't going to be executed, and increases
+    // register pressure in a situation where it's likely to matter.
+    if (BB->succ_size() >=3D 25)
+      NumChildren =3D 0;
+
+    OpenChildren[Node] =3D NumChildren;
+    // Add children in reverse order as then the next popped worklist node=
 is
+    // the first child of this node.  This means we ultimately traverse the
+    // DOM tree in exactly the same order as if we'd recursed.
+    for (int i =3D (int)NumChildren-1; i >=3D 0; --i) {
+      MachineDomTreeNode *Child =3D Children[i];
+      ParentMap[Child] =3D Node;
+      WorkList.push_back(Child);
+    }
+  } while (!WorkList.empty());
+
+  if (Scopes.size() !=3D 0) {
+    MachineBasicBlock *Preheader =3D getCurPreheader();
+    if (!Preheader)
+      return;
+
     // Compute registers which are livein into the loop headers.
     RegSeen.clear();
     BackTrace.clear();
     InitRegPressure(Preheader);
   }
=20
-  // Remember livein register pressure.
-  BackTrace.push_back(RegPressure);
+  // Now perform LICM.
+  for (unsigned i =3D 0, e =3D Scopes.size(); i !=3D e; ++i) {
+    MachineDomTreeNode *Node =3D Scopes[i];
+    MachineBasicBlock *MBB =3D Node->getBlock();
=20
-  SpeculationState =3D SpeculateUnknown;
-  for (MachineBasicBlock::iterator
-         MII =3D BB->begin(), E =3D BB->end(); MII !=3D E; ) {
-    MachineBasicBlock::iterator NextMII =3D MII; ++NextMII;
-    MachineInstr *MI =3D &*MII;
-    if (!Hoist(MI, Preheader))
-      UpdateRegPressure(MI);
-    MII =3D NextMII;
+    MachineBasicBlock *Preheader =3D getCurPreheader();
+    if (!Preheader)
+      continue;
+
+    EnterScope(MBB);
+
+    // Process the block
+    SpeculationState =3D SpeculateUnknown;
+    for (MachineBasicBlock::iterator
+         MII =3D MBB->begin(), E =3D MBB->end(); MII !=3D E; ) {
+      MachineBasicBlock::iterator NextMII =3D MII; ++NextMII;
+      MachineInstr *MI =3D &*MII;
+      if (!Hoist(MI, Preheader))
+        UpdateRegPressure(MI);
+      MII =3D NextMII;
+    }
+
+    // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
+    ExitScopeIfDone(Node, OpenChildren, ParentMap);
   }
-
-  // Don't hoist things out of a large switch statement.  This often causes
-  // code to be hoisted that wasn't going to be executed, and increases
-  // register pressure in a situation where it's likely to matter.
-  if (BB->succ_size() < 25) {
-    const std::vector<MachineDomTreeNode*> &Children =3D N->getChildren();
-    for (unsigned I =3D 0, E =3D Children.size(); I !=3D E; ++I)
-      HoistRegion(Children[I]);
-  }
-
-  BackTrace.pop_back();
 }
=20
 static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *M=
RI) {
@@ -670,7 +781,7 @@
                                        unsigned &RCId, unsigned &RCCost) c=
onst {
   const TargetRegisterClass *RC =3D MRI->getRegClass(Reg);
   EVT VT =3D *RC->vt_begin();
-  if (VT =3D=3D MVT::untyped) {
+  if (VT =3D=3D MVT::Untyped) {
     RCId =3D RC->getID();
     RCCost =3D 1;
   } else {
@@ -678,7 +789,7 @@
     RCCost =3D TLI->getRepRegClassCostFor(VT);
   }
 }
-                                     =20
+
 /// InitRegPressure - Find all virtual register references that are liveou=
t of
 /// the preheader to initialize the starting "register pressure". Note this
 /// does not count live through (livein but not used) registers.
@@ -762,6 +873,21 @@
   }
 }
=20
+/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
+/// loads from global offset table or constant pool.
+static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
+  assert (MI.mayLoad() && "Expected MI that loads!");
+  for (MachineInstr::mmo_iterator I =3D MI.memoperands_begin(),
+         E =3D MI.memoperands_end(); I !=3D E; ++I) {
+    if (const Value *V =3D (*I)->getValue()) {
+      if (const PseudoSourceValue *PSV =3D dyn_cast<PseudoSourceValue>(V))
+        if (PSV =3D=3D PSV->getGOT() || PSV =3D=3D PSV->getConstantPool())
+          return true;
+    }
+  }
+  return false;
+}
+
 /// IsLICMCandidate - Returns true if the instruction may be a suitable
 /// candidate for LICM. e.g. If the instruction is a call, then it's obvio=
usly
 /// not safe to hoist it.
@@ -773,9 +899,12 @@
=20
   // If it is load then check if it is guaranteed to execute by making sur=
e that
   // it dominates all exiting blocks. If it doesn't, then there is a path =
out of
-  // the loop which does not execute this load, so we can't hoist it.
+  // the loop which does not execute this load, so we can't hoist it. Loads
+  // from constant memory are not safe to speculate all the time, for exam=
ple
+  // indexed load from a jump table.
   // Stores and side effects are already checked by isSafeToMove.
-  if (I.getDesc().mayLoad() && !IsGuaranteedToExecute(I.getParent()))
+  if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
+      !IsGuaranteedToExecute(I.getParent()))
     return false;
=20
   return true;
@@ -785,7 +914,7 @@
 /// invariant. I.e., all virtual register operands are defined outside of =
the
 /// loop, physical registers aren't accessed explicitly, and there are no =
side
 /// effects that aren't captured by the operands or other flags.
-///=20
+///
 bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
   if (!IsLICMCandidate(I))
     return false;
@@ -806,18 +935,8 @@
         // If the physreg has no defs anywhere, it's just an ambient regis=
ter
         // and we can freely move its uses. Alternatively, if it's allocat=
able,
         // it could get allocated to something with a def during allocatio=
n.
-        if (!MRI->def_empty(Reg))
+        if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
           return false;
-        if (AllocatableSet.test(Reg))
-          return false;
-        // Check for a def among the register's aliases too.
-        for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Al=
ias) {
-          unsigned AliasReg =3D *Alias;
-          if (!MRI->def_empty(AliasReg))
-            return false;
-          if (AllocatableSet.test(AliasReg))
-            return false;
-        }
         // Otherwise it's safe to move.
         continue;
       } else if (!MO.isDead()) {
@@ -847,22 +966,40 @@
 }
=20
=20
-/// HasAnyPHIUse - Return true if the specified register is used by any
-/// phi node.
-bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
-  for (MachineRegisterInfo::use_iterator UI =3D MRI->use_begin(Reg),
-         UE =3D MRI->use_end(); UI !=3D UE; ++UI) {
-    MachineInstr *UseMI =3D &*UI;
-    if (UseMI->isPHI())
-      return true;
-    // Look pass copies as well.
-    if (UseMI->isCopy()) {
-      unsigned Def =3D UseMI->getOperand(0).getReg();
-      if (TargetRegisterInfo::isVirtualRegister(Def) &&
-          HasAnyPHIUse(Def))
-        return true;
+/// HasLoopPHIUse - Return true if the specified instruction is used by a
+/// phi node and hoisting it could cause a copy to be inserted.
+bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
+  SmallVector<const MachineInstr*, 8> Work(1, MI);
+  do {
+    MI =3D Work.pop_back_val();
+    for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
+      if (!MO->isReg() || !MO->isDef())
+        continue;
+      unsigned Reg =3D MO->getReg();
+      if (!TargetRegisterInfo::isVirtualRegister(Reg))
+        continue;
+      for (MachineRegisterInfo::use_iterator UI =3D MRI->use_begin(Reg),
+           UE =3D MRI->use_end(); UI !=3D UE; ++UI) {
+        MachineInstr *UseMI =3D &*UI;
+        // A PHI may cause a copy to be inserted.
+        if (UseMI->isPHI()) {
+          // A PHI inside the loop causes a copy because the live range of=
 Reg is
+          // extended across the PHI.
+          if (CurLoop->contains(UseMI))
+            return true;
+          // A PHI in an exit block can cause a copy to be inserted if the=
 PHI
+          // has multiple predecessors in the loop with different values.
+          // For now, approximate by rejecting all exit blocks.
+          if (isExitBlock(UseMI->getParent()))
+            return true;
+          continue;
+        }
+        // Look past copies as well.
+        if (UseMI->isCopy() && CurLoop->contains(UseMI))
+          Work.push_back(UseMI);
+      }
     }
-  }
+  } while (!Work.empty());
   return false;
 }
=20
@@ -903,7 +1040,7 @@
 /// IsCheapInstruction - Return true if the instruction is marked "cheap" =
or
 /// the operand latency between its def and a use is one or less.
 bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
-  if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
+  if (MI.isAsCheapAsAMove() || MI.isCopyLike())
     return true;
   if (!InstrItins || InstrItins->isEmpty())
     return false;
@@ -930,16 +1067,25 @@
 /// CanCauseHighRegPressure - Visit BBs from header to current BB, check
 /// if hoisting an instruction of the given cost matrix can cause high
 /// register pressure.
-bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
+bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
+                                          bool CheapInstr) {
   for (DenseMap<unsigned, int>::iterator CI =3D Cost.begin(), CE =3D Cost.=
end();
        CI !=3D CE; ++CI) {
-    if (CI->second <=3D 0)=20
+    if (CI->second <=3D 0)
       continue;
=20
     unsigned RCId =3D CI->first;
+    unsigned Limit =3D RegLimit[RCId];
+    int Cost =3D CI->second;
+
+    // Don't hoist cheap instructions if they would increase register pres=
sure,
+    // even if we're under the limit.
+    if (CheapInstr)
+      return true;
+
     for (unsigned i =3D BackTrace.size(); i !=3D 0; --i) {
       SmallVector<unsigned, 8> &RP =3D BackTrace[i-1];
-      if (RP[RCId] + CI->second >=3D RegLimit[RCId])
+      if (RP[RCId] + Cost >=3D Limit)
         return true;
     }
   }
@@ -999,87 +1145,95 @@
   if (MI.isImplicitDef())
     return true;
=20
-  // If the instruction is cheap, only hoist if it is re-materilizable. LI=
CM
-  // will increase register pressure. It's probably not worth it if the
-  // instruction is cheap.
-  // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoi=
sting
-  // these tend to help performance in low register pressure situation. The
-  // trade off is it may cause spill in high pressure situation. It will e=
nd up
-  // adding a store in the loop preheader. But the reload is no more expen=
sive.
-  // The side benefit is these loads are frequently CSE'ed.
-  if (IsCheapInstruction(MI)) {
-    if (!TII->isTriviallyReMaterializable(&MI, AA))
-      return false;
-  } else {
-    // Estimate register pressure to determine whether to LICM the instruc=
tion.
-    // In low register pressure situation, we can be more aggressive about=20
-    // hoisting. Also, favors hoisting long latency instructions even in
-    // moderately high pressure situation.
-    // FIXME: If there are long latency loop-invariant instructions inside=
 the
-    // loop at this point, why didn't the optimizer's LICM hoist them?
-    DenseMap<unsigned, int> Cost;
-    for (unsigned i =3D 0, e =3D MI.getDesc().getNumOperands(); i !=3D e; =
++i) {
-      const MachineOperand &MO =3D MI.getOperand(i);
-      if (!MO.isReg() || MO.isImplicit())
-        continue;
-      unsigned Reg =3D MO.getReg();
-      if (!TargetRegisterInfo::isVirtualRegister(Reg))
-        continue;
+  // Besides removing computation from the loop, hoisting an instruction h=
as
+  // these effects:
+  //
+  // - The value defined by the instruction becomes live across the entire
+  //   loop. This increases register pressure in the loop.
+  //
+  // - If the value is used by a PHI in the loop, a copy will be required =
for
+  //   lowering the PHI after extending the live range.
+  //
+  // - When hoisting the last use of a value in the loop, that value no lo=
nger
+  //   needs to be live in the loop. This lowers register pressure in the =
loop.
=20
-      unsigned RCId, RCCost;
-      getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
-      if (MO.isDef()) {
-        if (HasHighOperandLatency(MI, i, Reg)) {
-          ++NumHighLatency;
-          return true;
-        }
+  bool CheapInstr =3D IsCheapInstruction(MI);
+  bool CreatesCopy =3D HasLoopPHIUse(&MI);
=20
-        DenseMap<unsigned, int>::iterator CI =3D Cost.find(RCId);
-        if (CI !=3D Cost.end())
-          CI->second +=3D RCCost;
-        else
-          Cost.insert(std::make_pair(RCId, RCCost));
-      } else if (isOperandKill(MO, MRI)) {
-        // Is a virtual register use is a kill, hoisting it out of the loop
-        // may actually reduce register pressure or be register pressure
-        // neutral.
-        DenseMap<unsigned, int>::iterator CI =3D Cost.find(RCId);
-        if (CI !=3D Cost.end())
-          CI->second -=3D RCCost;
-        else
-          Cost.insert(std::make_pair(RCId, -RCCost));
-      }
-    }
-
-    // Visit BBs from header to current BB, if hoisting this doesn't cause
-    // high register pressure, then it's safe to proceed.
-    if (!CanCauseHighRegPressure(Cost)) {
-      ++NumLowRP;
-      return true;
-    }
-
-    // Do not "speculate" in high register pressure situation. If an
-    // instruction is not guaranteed to be executed in the loop, it's best=
 to be
-    // conservative.
-    if (AvoidSpeculation &&
-        (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI)))
-      return false;
-
-    // High register pressure situation, only hoist if the instruction is =
going to
-    // be remat'ed.
-    if (!TII->isTriviallyReMaterializable(&MI, AA) &&
-        !MI.isInvariantLoad(AA))
-      return false;
+  // Don't hoist a cheap instruction if it would create a copy in the loop.
+  if (CheapInstr && CreatesCopy) {
+    DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
+    return false;
   }
=20
-  // If result(s) of this instruction is used by PHIs outside of the loop,=
 then
-  // don't hoist it if the instruction because it will introduce an extra =
copy.
-  for (unsigned i =3D 0, e =3D MI.getNumOperands(); i !=3D e; ++i) {
+  // Rematerializable instructions should always be hoisted since the regi=
ster
+  // allocator can just pull them down again when needed.
+  if (TII->isTriviallyReMaterializable(&MI, AA))
+    return true;
+
+  // Estimate register pressure to determine whether to LICM the instructi=
on.
+  // In low register pressure situation, we can be more aggressive about
+  // hoisting. Also, favors hoisting long latency instructions even in
+  // moderately high pressure situation.
+  // Cheap instructions will only be hoisted if they don't increase regist=
er
+  // pressure at all.
+  // FIXME: If there are long latency loop-invariant instructions inside t=
he
+  // loop at this point, why didn't the optimizer's LICM hoist them?
+  DenseMap<unsigned, int> Cost;
+  for (unsigned i =3D 0, e =3D MI.getDesc().getNumOperands(); i !=3D e; ++=
i) {
     const MachineOperand &MO =3D MI.getOperand(i);
-    if (!MO.isReg() || !MO.isDef())
+    if (!MO.isReg() || MO.isImplicit())
       continue;
-    if (HasAnyPHIUse(MO.getReg()))
-      return false;
+    unsigned Reg =3D MO.getReg();
+    if (!TargetRegisterInfo::isVirtualRegister(Reg))
+      continue;
+
+    unsigned RCId, RCCost;
+    getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
+    if (MO.isDef()) {
+      if (HasHighOperandLatency(MI, i, Reg)) {
+        DEBUG(dbgs() << "Hoist High Latency: " << MI);
+        ++NumHighLatency;
+        return true;
+      }
+      Cost[RCId] +=3D RCCost;
+    } else if (isOperandKill(MO, MRI)) {
+      // Is a virtual register use is a kill, hoisting it out of the loop
+      // may actually reduce register pressure or be register pressure
+      // neutral.
+      Cost[RCId] -=3D RCCost;
+    }
+  }
+
+  // Visit BBs from header to current BB, if hoisting this doesn't cause
+  // high register pressure, then it's safe to proceed.
+  if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
+    DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
+    ++NumLowRP;
+    return true;
+  }
+
+  // Don't risk increasing register pressure if it would create copies.
+  if (CreatesCopy) {
+    DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
+    return false;
+  }
+
+  // Do not "speculate" in high register pressure situation. If an
+  // instruction is not guaranteed to be executed in the loop, it's best t=
o be
+  // conservative.
+  if (AvoidSpeculation &&
+      (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
+    DEBUG(dbgs() << "Won't speculate: " << MI);
+    return false;
+  }
+
+  // High register pressure situation, only hoist if the instruction is go=
ing
+  // to be remat'ed.
+  if (!TII->isTriviallyReMaterializable(&MI, AA) &&
+      !MI.isInvariantLoad(AA)) {
+    DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
+    return false;
   }
=20
   return true;
@@ -1087,7 +1241,7 @@
=20
 MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
   // Don't unfold simple loads.
-  if (MI->getDesc().canFoldAsLoad())
+  if (MI->canFoldAsLoad())
     return 0;
=20
   // If not, we may be able to unfold a load and hoist that.
@@ -1123,8 +1277,9 @@
   assert(NewMIs.size() =3D=3D 2 &&
          "Unfolded a load into multiple instructions!");
   MachineBasicBlock *MBB =3D MI->getParent();
-  MBB->insert(MI, NewMIs[0]);
-  MBB->insert(MI, NewMIs[1]);
+  MachineBasicBlock::iterator Pos =3D MI;
+  MBB->insert(Pos, NewMIs[0]);
+  MBB->insert(Pos, NewMIs[1]);
   // If unfolding produced a load that wasn't loop-invariant or profitable=
 to
   // hoist, discard the new instructions and bail.
   if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])=
) {
@@ -1180,6 +1335,7 @@
=20
     // Replace virtual registers defined by MI by their counterparts defin=
ed
     // by Dup.
+    SmallVector<unsigned, 2> Defs;
     for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
       const MachineOperand &MO =3D MI->getOperand(i);
=20
@@ -1190,11 +1346,33 @@
              "Instructions with different phys regs are not identical!");
=20
       if (MO.isReg() && MO.isDef() &&
-          !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
-        MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
-        MRI->clearKillFlags(Dup->getOperand(i).getReg());
+          !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
+        Defs.push_back(i);
+    }
+
+    SmallVector<const TargetRegisterClass*, 2> OrigRCs;
+    for (unsigned i =3D 0, e =3D Defs.size(); i !=3D e; ++i) {
+      unsigned Idx =3D Defs[i];
+      unsigned Reg =3D MI->getOperand(Idx).getReg();
+      unsigned DupReg =3D Dup->getOperand(Idx).getReg();
+      OrigRCs.push_back(MRI->getRegClass(DupReg));
+
+      if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
+        // Restore old RCs if more than one defs.
+        for (unsigned j =3D 0; j !=3D i; ++j)
+          MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
+        return false;
       }
     }
+
+    for (unsigned i =3D 0, e =3D Defs.size(); i !=3D e; ++i) {
+      unsigned Idx =3D Defs[i];
+      unsigned Reg =3D MI->getOperand(Idx).getReg();
+      unsigned DupReg =3D Dup->getOperand(Idx).getReg();
+      MRI->replaceRegWith(Reg, DupReg);
+      MRI->clearKillFlags(DupReg);
+    }
+
     MI->eraseFromParent();
     ++NumCSEed;
     return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineM=
oduleInfo.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineModuleInfo.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineModuleInfo.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -257,7 +257,7 @@
   : ImmutablePass(ID), Context(MAI, MRI, MOFI),
     ObjFileMMI(0), CompactUnwindEncoding(0), CurCallSite(0), CallsEHReturn=
(0),
     CallsUnwindInit(0), DbgInfoAvailable(false),
-    CallsExternalVAFunctionWithFloatingPointArguments(false) {
+    UsesVAFloatArgument(false) {
   initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
   // Always emit some info, by default "no personality" info.
   Personalities.push_back(NULL);
@@ -268,9 +268,9 @@
 MachineModuleInfo::MachineModuleInfo()
   : ImmutablePass(ID),
     Context(*(MCAsmInfo*)0, *(MCRegisterInfo*)0, (MCObjectFileInfo*)0) {
-  assert(0 && "This MachineModuleInfo constructor should never be called, =
MMI "
-         "should always be explicitly constructed by LLVMTargetMachine");
-  abort();
+  llvm_unreachable("This MachineModuleInfo constructor should never be cal=
led, "
+                   "MMI should always be explicitly constructed by "
+                   "LLVMTargetMachine");
 }
=20
 MachineModuleInfo::~MachineModuleInfo() {
@@ -503,8 +503,7 @@
 /// indexes.
 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym,
                                               ArrayRef<unsigned> Sites) {
-  for (unsigned I =3D 0, E =3D Sites.size(); I !=3D E; ++I)
-    LPadToCallSiteMap[Sym].push_back(Sites[I]);
+  LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
 }
=20
 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is
@@ -541,8 +540,7 @@
   // Add the new filter.
   int FilterID =3D -(1 + FilterIds.size());
   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
-  for (unsigned I =3D 0, N =3D TyIds.size(); I !=3D N; ++I)
-    FilterIds.push_back(TyIds[I]);
+  FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
   FilterEnds.push_back(FilterIds.size());
   FilterIds.push_back(0); // terminator
   return FilterID;
@@ -561,13 +559,13 @@
   const Function* Personality =3D NULL;
=20
   // Scan landing pads. If there is at least one non-NULL personality - us=
e it.
-  for (unsigned i =3D 0; i !=3D LandingPads.size(); ++i)
+  for (unsigned i =3D 0, e =3D LandingPads.size(); i !=3D e; ++i)
     if (LandingPads[i].Personality) {
       Personality =3D LandingPads[i].Personality;
       break;
     }
=20
-  for (unsigned i =3D 0; i < Personalities.size(); ++i) {
+  for (unsigned i =3D 0, e =3D Personalities.size(); i < e; ++i) {
     if (Personalities[i] =3D=3D Personality)
       return i;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineP=
assRegistry.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachinePassRegistry.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachinePassRegistry.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -16,6 +16,7 @@
=20
 using namespace llvm;
=20
+void MachinePassRegistryListener::anchor() { }
=20
 /// Add - Adds a function pass to the registration list.
 ///
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineR=
egisterInfo.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineRegisterInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineRegisterInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -18,11 +18,12 @@
 using namespace llvm;
=20
 MachineRegisterInfo::MachineRegisterInfo(const TargetRegisterInfo &TRI)
-  : TRI(&TRI), IsSSA(true) {
+  : TRI(&TRI), IsSSA(true), TracksLiveness(true) {
   VRegInfo.reserve(256);
   RegAllocHints.reserve(256);
   UsedPhysRegs.resize(TRI.getNumRegs());
- =20
+  UsedPhysRegMask.resize(TRI.getNumRegs());
+
   // Create the physreg use/def lists.
   PhysRegUseDefLists =3D new MachineOperand*[TRI.getNumRegs()];
   memset(PhysRegUseDefLists, 0, sizeof(MachineOperand*)*TRI.getNumRegs());
@@ -30,9 +31,7 @@
=20
 MachineRegisterInfo::~MachineRegisterInfo() {
 #ifndef NDEBUG
-  for (unsigned i =3D 0, e =3D getNumVirtRegs(); i !=3D e; ++i)
-    assert(VRegInfo[TargetRegisterInfo::index2VirtReg(i)].second =3D=3D 0 =
&&
-           "Vreg use list non-empty still?");
+  clearVirtRegs();
   for (unsigned i =3D 0, e =3D UsedPhysRegs.size(); i !=3D e; ++i)
     assert(!PhysRegUseDefLists[i] &&
            "PhysRegUseDefLists has entries after all instructions are dele=
ted");
@@ -76,12 +75,14 @@
   // Accumulate constraints from all uses.
   for (reg_nodbg_iterator I =3D reg_nodbg_begin(Reg), E =3D reg_nodbg_end(=
); I !=3D E;
        ++I) {
-    // TRI doesn't have accurate enough information to model this yet.
-    if (I.getOperand().getSubReg())
-      return false;
     const TargetRegisterClass *OpRC =3D
       I->getRegClassConstraint(I.getOperandNo(), TII, TRI);
-    if (OpRC)
+    if (unsigned SubIdx =3D I.getOperand().getSubReg()) {
+      if (OpRC)
+        NewRC =3D TRI->getMatchingSuperRegClass(NewRC, OpRC, SubIdx);
+      else
+        NewRC =3D TRI->getSubClassWithSubReg(NewRC, SubIdx);
+    } else if (OpRC)
       NewRC =3D TRI->getCommonSubClass(NewRC, OpRC);
     if (!NewRC || NewRC =3D=3D OldRC)
       return false;
@@ -115,6 +116,16 @@
   return Reg;
 }
=20
+/// clearVirtRegs - Remove all virtual registers (after physreg assignment=
).
+void MachineRegisterInfo::clearVirtRegs() {
+#ifndef NDEBUG
+  for (unsigned i =3D 0, e =3D getNumVirtRegs(); i !=3D e; ++i)
+    assert(VRegInfo[TargetRegisterInfo::index2VirtReg(i)].second =3D=3D 0 =
&&
+           "Vreg use list non-empty still?");
+#endif
+  VRegInfo.clear();
+}
+
 /// HandleVRegListReallocation - We just added a virtual register to the
 /// VRegInfo info list and it reallocated.  Update the use/def lists info
 /// pointers.
@@ -150,9 +161,8 @@
 /// form, so there should only be one definition.
 MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const {
   // Since we are in SSA form, we can use the first definition.
-  if (!def_empty(Reg))
-    return &*def_begin(Reg);
-  return 0;
+  def_iterator I =3D def_begin(Reg);
+  return !I.atEnd() ? &*I : 0;
 }
=20
 bool MachineRegisterInfo::hasOneUse(unsigned RegNo) const {
@@ -242,18 +252,31 @@
     }
 }
=20
-void MachineRegisterInfo::closePhysRegsUsed(const TargetRegisterInfo &TRI)=
 {
-  for (int i =3D UsedPhysRegs.find_first(); i >=3D 0;
-       i =3D UsedPhysRegs.find_next(i))
-         for (const unsigned *SS =3D TRI.getSubRegisters(i);
-              unsigned SubReg =3D *SS; ++SS)
-           if (SubReg > unsigned(i))
-             UsedPhysRegs.set(SubReg);
-}
-
 #ifndef NDEBUG
 void MachineRegisterInfo::dumpUses(unsigned Reg) const {
   for (use_iterator I =3D use_begin(Reg), E =3D use_end(); I !=3D E; ++I)
     I.getOperand().getParent()->dump();
 }
 #endif
+
+void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) {
+  ReservedRegs =3D TRI->getReservedRegs(MF);
+}
+
+bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg,
+                                            const MachineFunction &MF) con=
st {
+  assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
+
+  // Check if any overlapping register is modified.
+  for (const uint16_t *R =3D TRI->getOverlaps(PhysReg); *R; ++R)
+    if (!def_empty(*R))
+      return false;
+
+  // Check if any overlapping register is allocatable so it may be used la=
ter.
+  if (AllocatableRegs.empty())
+    AllocatableRegs =3D TRI->getAllocatableSet(MF);
+  for (const uint16_t *R =3D TRI->getOverlaps(PhysReg); *R; ++R)
+    if (AllocatableRegs.test(*R))
+      return false;
+  return true;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineS=
SAUpdater.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineSSAUpdater.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineSSAUpdater.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -81,7 +81,7 @@
   if (BB->empty())
     return 0;
=20
-  MachineBasicBlock::iterator I =3D BB->front();
+  MachineBasicBlock::iterator I =3D BB->begin();
   if (!I->isPHI())
     return 0;
=20
@@ -182,7 +182,7 @@
     return DupPHI;
=20
   // Otherwise, we do need a PHI: insert one now.
-  MachineBasicBlock::iterator Loc =3D BB->empty() ? BB->end() : BB->front(=
);
+  MachineBasicBlock::iterator Loc =3D BB->empty() ? BB->end() : BB->begin(=
);
   MachineInstr *InsertedPHI =3D InsertNewDef(TargetOpcode::PHI, BB,
                                            Loc, VRC, MRI, TII);
=20
@@ -214,7 +214,6 @@
   }
=20
   llvm_unreachable("MachineOperand::getParent() failure?");
-  return 0;
 }
=20
 /// RewriteUse - Rewrite a use of the symbolic value.  This handles PHI no=
des,
@@ -311,7 +310,7 @@
   /// Add it into the specified block and return the register.
   static unsigned CreateEmptyPHI(MachineBasicBlock *BB, unsigned NumPreds,
                                  MachineSSAUpdater *Updater) {
-    MachineBasicBlock::iterator Loc =3D BB->empty() ? BB->end() : BB->fron=
t();
+    MachineBasicBlock::iterator Loc =3D BB->empty() ? BB->end() : BB->begi=
n();
     MachineInstr *PHI =3D InsertNewDef(TargetOpcode::PHI, BB, Loc,
                                      Updater->VRC, Updater->MRI,
                                      Updater->TII);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineS=
ink.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineSink.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineSink.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -32,7 +32,7 @@
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
=20
-static cl::opt<bool>=20
+static cl::opt<bool>
 SplitEdges("machine-sink-split",
            cl::desc("Split critical edges during machine sinking"),
            cl::init(true), cl::Hidden);
@@ -90,12 +90,19 @@
     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB,
                                  MachineBasicBlock *DefMBB,
                                  bool &BreakPHIEdge, bool &LocalUse) const;
+    MachineBasicBlock *FindSuccToSinkTo(MachineInstr *MI, MachineBasicBloc=
k *MBB,
+               bool &BreakPHIEdge);
+    bool isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
+                              MachineBasicBlock *MBB,
+                              MachineBasicBlock *SuccToSinkTo);
+
     bool PerformTrivialForwardCoalescing(MachineInstr *MI,
                                          MachineBasicBlock *MBB);
   };
 } // end anonymous namespace
=20
 char MachineSinking::ID =3D 0;
+char &llvm::MachineSinkingID =3D MachineSinking::ID;
 INITIALIZE_PASS_BEGIN(MachineSinking, "machine-sink",
                 "Machine code sinking", false, false)
 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
@@ -104,8 +111,6 @@
 INITIALIZE_PASS_END(MachineSinking, "machine-sink",
                 "Machine code sinking", false, false)
=20
-FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking=
(); }
-
 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr *MI,
                                                      MachineBasicBlock *MB=
B) {
   if (!MI->isCopy())
@@ -147,14 +152,10 @@
   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
          "Only makes sense for vregs");
=20
+  // Ignore debug uses because debug info doesn't affect the code.
   if (MRI->use_nodbg_empty(Reg))
     return true;
=20
-  // Ignoring debug uses is necessary so debug info doesn't affect the cod=
e.
-  // This may leave a referencing dbg_value in the original block, before
-  // the definition of the vreg.  Dwarf generator handles this although the
-  // user might not get the right info at runtime.
-
   // BreakPHIEdge is true if all the uses are in the successor MBB being s=
unken
   // into and they are all PHI nodes. In this case, machine-sink must break
   // the critical edge first. e.g.
@@ -291,7 +292,7 @@
   if (!CEBCandidates.insert(std::make_pair(From, To)))
     return true;
=20
-  if (!MI->isCopy() && !MI->getDesc().isAsCheapAsAMove())
+  if (!MI->isCopy() && !MI->isAsCheapAsAMove())
     return true;
=20
   // MI is cheap, we probably don't want to break the critical edge for it.
@@ -382,9 +383,9 @@
   return MI->isInsertSubreg() || MI->isSubregToReg() || MI->isRegSequence(=
);
 }
=20
-/// collectDebgValues - Scan instructions following MI and collect any=20
+/// collectDebgValues - Scan instructions following MI and collect any
 /// matching DBG_VALUEs.
-static void collectDebugValues(MachineInstr *MI,=20
+static void collectDebugValues(MachineInstr *MI,
                                SmallVector<MachineInstr *, 2> & DbgValues)=
 {
   DbgValues.clear();
   if (!MI->getOperand(0).isReg())
@@ -401,6 +402,165 @@
   }
 }
=20
+/// isPostDominatedBy - Return true if A is post dominated by B.
+static bool isPostDominatedBy(MachineBasicBlock *A, MachineBasicBlock *B) {
+
+  // FIXME - Use real post dominator.
+  if (A->succ_size() !=3D 2)
+    return false;
+  MachineBasicBlock::succ_iterator I =3D A->succ_begin();
+  if (B =3D=3D *I)
+    ++I;
+  MachineBasicBlock *OtherSuccBlock =3D *I;
+  if (OtherSuccBlock->succ_size() !=3D 1 ||
+      *(OtherSuccBlock->succ_begin()) !=3D B)
+    return false;
+
+  return true;
+}
+
+/// isProfitableToSinkTo - Return true if it is profitable to sink MI.
+bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr *MI,
+                                          MachineBasicBlock *MBB,
+                                          MachineBasicBlock *SuccToSinkTo)=
 {
+  assert (MI && "Invalid MachineInstr!");
+  assert (SuccToSinkTo && "Invalid SinkTo Candidate BB");
+
+  if (MBB =3D=3D SuccToSinkTo)
+    return false;
+
+  // It is profitable if SuccToSinkTo does not post dominate current block.
+  if (!isPostDominatedBy(MBB, SuccToSinkTo))
+      return true;
+
+  // Check if only use in post dominated block is PHI instruction.
+  bool NonPHIUse =3D false;
+  for (MachineRegisterInfo::use_nodbg_iterator
+         I =3D MRI->use_nodbg_begin(Reg), E =3D MRI->use_nodbg_end();
+       I !=3D E; ++I) {
+    MachineInstr *UseInst =3D &*I;
+    MachineBasicBlock *UseBlock =3D UseInst->getParent();
+    if (UseBlock =3D=3D SuccToSinkTo && !UseInst->isPHI())
+      NonPHIUse =3D true;
+  }
+  if (!NonPHIUse)
+    return true;
+
+  // If SuccToSinkTo post dominates then also it may be profitable if MI
+  // can further profitably sinked into another block in next round.
+  bool BreakPHIEdge =3D false;
+  // FIXME - If finding successor is compile time expensive then catch res=
ults.
+  if (MachineBasicBlock *MBB2 =3D FindSuccToSinkTo(MI, SuccToSinkTo, Break=
PHIEdge))
+    return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2);
+
+  // If SuccToSinkTo is final destination and it is a post dominator of cu=
rrent
+  // block then it is not profitable to sink MI into SuccToSinkTo block.
+  return false;
+}
+
+/// FindSuccToSinkTo - Find a successor to sink this instruction to.
+MachineBasicBlock *MachineSinking::FindSuccToSinkTo(MachineInstr *MI,
+                                   MachineBasicBlock *MBB,
+                                   bool &BreakPHIEdge) {
+
+  assert (MI && "Invalid MachineInstr!");
+  assert (MBB && "Invalid MachineBasicBlock!");
+
+  // Loop over all the operands of the specified instruction.  If there is
+  // anything we can't handle, bail out.
+
+  // SuccToSinkTo - This is the successor to sink this instruction to, onc=
e we
+  // decide.
+  MachineBasicBlock *SuccToSinkTo =3D 0;
+  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
+    const MachineOperand &MO =3D MI->getOperand(i);
+    if (!MO.isReg()) continue;  // Ignore non-register operands.
+
+    unsigned Reg =3D MO.getReg();
+    if (Reg =3D=3D 0) continue;
+
+    if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
+      if (MO.isUse()) {
+        // If the physreg has no defs anywhere, it's just an ambient regis=
ter
+        // and we can freely move its uses. Alternatively, if it's allocat=
able,
+        // it could get allocated to something with a def during allocatio=
n.
+        if (!MRI->isConstantPhysReg(Reg, *MBB->getParent()))
+          return NULL;
+      } else if (!MO.isDead()) {
+        // A def that isn't dead. We can't move it.
+        return NULL;
+      }
+    } else {
+      // Virtual register uses are always safe to sink.
+      if (MO.isUse()) continue;
+
+      // If it's not safe to move defs of the register class, then abort.
+      if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
+        return NULL;
+
+      // FIXME: This picks a successor to sink into based on having one
+      // successor that dominates all the uses.  However, there are cases =
where
+      // sinking can happen but where the sink point isn't a successor.  F=
or
+      // example:
+      //
+      //   x =3D computation
+      //   if () {} else {}
+      //   use x
+      //
+      // the instruction could be sunk over the whole diamond for the
+      // if/then/else (or loop, etc), allowing it to be sunk into other bl=
ocks
+      // after that.
+
+      // Virtual register defs can only be sunk if all their uses are in b=
locks
+      // dominated by one of the successors.
+      if (SuccToSinkTo) {
+        // If a previous operand picked a block to sink to, then this oper=
and
+        // must be sinkable to the same block.
+        bool LocalUse =3D false;
+        if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB,
+                                     BreakPHIEdge, LocalUse))
+          return NULL;
+
+        continue;
+      }
+
+      // Otherwise, we should look at all the successors and decide which =
one
+      // we should sink to.
+      for (MachineBasicBlock::succ_iterator SI =3D MBB->succ_begin(),
+           E =3D MBB->succ_end(); SI !=3D E; ++SI) {
+        MachineBasicBlock *SuccBlock =3D *SI;
+        bool LocalUse =3D false;
+        if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB,
+                                    BreakPHIEdge, LocalUse)) {
+          SuccToSinkTo =3D SuccBlock;
+          break;
+        }
+        if (LocalUse)
+          // Def is used locally, it's never safe to move this def.
+          return NULL;
+      }
+
+      // If we couldn't find a block to sink to, ignore this instruction.
+      if (SuccToSinkTo =3D=3D 0)
+        return NULL;
+      else if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo))
+        return NULL;
+    }
+  }
+
+  // It is not possible to sink an instruction into its own block.  This c=
an
+  // happen with loops.
+  if (MBB =3D=3D SuccToSinkTo)
+    return NULL;
+
+  // It's not safe to sink instructions to EH landing pad. Control flow in=
to
+  // landing pad is implicitly defined.
+  if (SuccToSinkTo && SuccToSinkTo->isLandingPad())
+    return NULL;
+
+  return SuccToSinkTo;
+}
+
 /// SinkInstruction - Determine whether it is safe to sink the specified m=
achine
 /// instruction out of its current block into a successor.
 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
@@ -421,114 +581,14 @@
   // "x =3D y + z" down if it kills y and z would increase the live ranges=
 of y
   // and z and only shrink the live range of x.
=20
-  // Loop over all the operands of the specified instruction.  If there is
-  // anything we can't handle, bail out.
+  bool BreakPHIEdge =3D false;
   MachineBasicBlock *ParentBlock =3D MI->getParent();
-
-  // SuccToSinkTo - This is the successor to sink this instruction to, onc=
e we
-  // decide.
-  MachineBasicBlock *SuccToSinkTo =3D 0;
-
-  bool BreakPHIEdge =3D false;
-  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
-    const MachineOperand &MO =3D MI->getOperand(i);
-    if (!MO.isReg()) continue;  // Ignore non-register operands.
-
-    unsigned Reg =3D MO.getReg();
-    if (Reg =3D=3D 0) continue;
-
-    if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
-      if (MO.isUse()) {
-        // If the physreg has no defs anywhere, it's just an ambient regis=
ter
-        // and we can freely move its uses. Alternatively, if it's allocat=
able,
-        // it could get allocated to something with a def during allocatio=
n.
-        if (!MRI->def_empty(Reg))
-          return false;
-
-        if (AllocatableSet.test(Reg))
-          return false;
-
-        // Check for a def among the register's aliases too.
-        for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Al=
ias) {
-          unsigned AliasReg =3D *Alias;
-          if (!MRI->def_empty(AliasReg))
-            return false;
-
-          if (AllocatableSet.test(AliasReg))
-            return false;
-        }
-      } else if (!MO.isDead()) {
-        // A def that isn't dead. We can't move it.
-        return false;
-      }
-    } else {
-      // Virtual register uses are always safe to sink.
-      if (MO.isUse()) continue;
-
-      // If it's not safe to move defs of the register class, then abort.
-      if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg)))
-        return false;
-
-      // FIXME: This picks a successor to sink into based on having one
-      // successor that dominates all the uses.  However, there are cases =
where
-      // sinking can happen but where the sink point isn't a successor.  F=
or
-      // example:
-      //
-      //   x =3D computation
-      //   if () {} else {}
-      //   use x
-      //
-      // the instruction could be sunk over the whole diamond for the
-      // if/then/else (or loop, etc), allowing it to be sunk into other bl=
ocks
-      // after that.
-
-      // Virtual register defs can only be sunk if all their uses are in b=
locks
-      // dominated by one of the successors.
-      if (SuccToSinkTo) {
-        // If a previous operand picked a block to sink to, then this oper=
and
-        // must be sinkable to the same block.
-        bool LocalUse =3D false;
-        if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, ParentBlock,
-                                     BreakPHIEdge, LocalUse))
-          return false;
-
-        continue;
-      }
-
-      // Otherwise, we should look at all the successors and decide which =
one
-      // we should sink to.
-      for (MachineBasicBlock::succ_iterator SI =3D ParentBlock->succ_begin=
(),
-           E =3D ParentBlock->succ_end(); SI !=3D E; ++SI) {
-        bool LocalUse =3D false;
-        if (AllUsesDominatedByBlock(Reg, *SI, ParentBlock,
-                                    BreakPHIEdge, LocalUse)) {
-          SuccToSinkTo =3D *SI;
-          break;
-        }
-        if (LocalUse)
-          // Def is used locally, it's never safe to move this def.
-          return false;
-      }
-
-      // If we couldn't find a block to sink to, ignore this instruction.
-      if (SuccToSinkTo =3D=3D 0)
-        return false;
-    }
-  }
+  MachineBasicBlock *SuccToSinkTo =3D FindSuccToSinkTo(MI, ParentBlock, Br=
eakPHIEdge);
=20
   // If there are no outputs, it must have side-effects.
   if (SuccToSinkTo =3D=3D 0)
     return false;
=20
-  // It's not safe to sink instructions to EH landing pad. Control flow in=
to
-  // landing pad is implicitly defined.
-  if (SuccToSinkTo->isLandingPad())
-    return false;
-
-  // It is not possible to sink an instruction into its own block.  This c=
an
-  // happen with loops.
-  if (MI->getParent() =3D=3D SuccToSinkTo)
-    return false;
=20
   // If the instruction to move defines a dead physical register which is =
live
   // when leaving the basic block, don't move it because it could turn int=
o a
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/MachineV=
erifier.cpp
--- a/head/contrib/llvm/lib/CodeGen/MachineVerifier.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/MachineVerifier.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -28,6 +28,7 @@
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
 #include "llvm/CodeGen/LiveVariables.h"
 #include "llvm/CodeGen/LiveStackAnalysis.h"
+#include "llvm/CodeGen/MachineInstrBundle.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
@@ -69,14 +70,17 @@
     unsigned foundErrors;
=20
     typedef SmallVector<unsigned, 16> RegVector;
+    typedef SmallVector<const uint32_t*, 4> RegMaskVector;
     typedef DenseSet<unsigned> RegSet;
     typedef DenseMap<unsigned, const MachineInstr*> RegMap;
=20
     const MachineInstr *FirstTerminator;
=20
     BitVector regsReserved;
+    BitVector regsAllocatable;
     RegSet regsLive;
     RegVector regsDefined, regsDead, regsKilled;
+    RegMaskVector regMasks;
     RegSet regsLiveInButUnused;
=20
     SlotIndex lastIndex;
@@ -85,7 +89,7 @@
     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
       RV.push_back(Reg);
       if (TargetRegisterInfo::isPhysicalRegister(Reg))
-        for (const unsigned *R =3D TRI->getSubRegisters(Reg); *R; R++)
+        for (const uint16_t *R =3D TRI->getSubRegisters(Reg); *R; R++)
           RV.push_back(*R);
     }
=20
@@ -175,6 +179,10 @@
       return Reg < regsReserved.size() && regsReserved.test(Reg);
     }
=20
+    bool isAllocatable(unsigned Reg) {
+      return Reg < regsAllocatable.size() && regsAllocatable.test(Reg);
+    }
+
     // Analysis information if available
     LiveVariables *LiveVars;
     LiveIntervals *LiveInts;
@@ -194,6 +202,7 @@
     void report(const char *msg, const MachineInstr *MI);
     void report(const char *msg, const MachineOperand *MO, unsigned MONum);
=20
+    void checkLiveness(const MachineOperand *MO, unsigned MONum);
     void markReachable(const MachineBasicBlock *MBB);
     void calcRegsPassed();
     void checkPHIOps(const MachineBasicBlock *MBB);
@@ -279,13 +288,17 @@
   for (MachineFunction::const_iterator MFI =3D MF.begin(), MFE =3D MF.end(=
);
        MFI!=3DMFE; ++MFI) {
     visitMachineBasicBlockBefore(MFI);
-    for (MachineBasicBlock::const_iterator MBBI =3D MFI->begin(),
-           MBBE =3D MFI->end(); MBBI !=3D MBBE; ++MBBI) {
+    for (MachineBasicBlock::const_instr_iterator MBBI =3D MFI->instr_begin=
(),
+           MBBE =3D MFI->instr_end(); MBBI !=3D MBBE; ++MBBI) {
       if (MBBI->getParent() !=3D MFI) {
         report("Bad instruction parent pointer", MFI);
         *OS << "Instruction: " << *MBBI;
         continue;
       }
+      // Skip BUNDLE instruction for now. FIXME: We should add code to ver=
ify
+      // the BUNDLE's specifically.
+      if (MBBI->isBundle())
+        continue;
       visitMachineInstrBefore(MBBI);
       for (unsigned I =3D 0, E =3D MBBI->getNumOperands(); I !=3D E; ++I)
         visitMachineOperand(&MBBI->getOperand(I), I);
@@ -305,6 +318,7 @@
   regsDefined.clear();
   regsDead.clear();
   regsKilled.clear();
+  regMasks.clear();
   regsLiveInButUnused.clear();
   MBBInfoMap.clear();
=20
@@ -320,7 +334,7 @@
     MF->print(*OS, Indexes);
   }
   *OS << "*** Bad machine code: " << msg << " ***\n"
-      << "- function:    " << MF->getFunction()->getNameStr() << "\n";
+      << "- function:    " << MF->getFunction()->getName() << "\n";
 }
=20
 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB=
) {
@@ -370,12 +384,15 @@
   // A sub-register of a reserved register is also reserved
   for (int Reg =3D regsReserved.find_first(); Reg>=3D0;
        Reg =3D regsReserved.find_next(Reg)) {
-    for (const unsigned *Sub =3D TRI->getSubRegisters(Reg); *Sub; ++Sub) {
+    for (const uint16_t *Sub =3D TRI->getSubRegisters(Reg); *Sub; ++Sub) {
       // FIXME: This should probably be:
       // assert(regsReserved.test(*Sub) && "Non-reserved sub-register");
       regsReserved.set(*Sub);
     }
   }
+
+  regsAllocatable =3D TRI->getAllocatableSet(*MF);
+
   markReachable(&MF->front());
 }
=20
@@ -393,6 +410,20 @@
 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB=
) {
   FirstTerminator =3D 0;
=20
+  if (MRI->isSSA()) {
+    // If this block has allocatable physical registers live-in, check that
+    // it is an entry block or landing pad.
+    for (MachineBasicBlock::livein_iterator LI =3D MBB->livein_begin(),
+           LE =3D MBB->livein_end();
+         LI !=3D LE; ++LI) {
+      unsigned reg =3D *LI;
+      if (isAllocatable(reg) && !MBB->isLandingPad() &&
+          MBB !=3D MBB->getParent()->begin()) {
+        report("MBB has allocable live-in, but isn't entry or landing-pad.=
", MBB);
+      }
+    }
+  }
+
   // Count the number of landing pad successors.
   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
   for (MachineBasicBlock::const_succ_iterator I =3D MBB->succ_begin(),
@@ -435,7 +466,7 @@
         report("MBB exits via unconditional fall-through but its successor=
 "
                "differs from its CFG successor!", MBB);
       }
-      if (!MBB->empty() && MBB->back().getDesc().isBarrier() &&
+      if (!MBB->empty() && MBB->back().isBarrier() &&
           !TII->isPredicated(&MBB->back())) {
         report("MBB exits via unconditional fall-through but ends with a "
                "barrier instruction!", MBB);
@@ -456,10 +487,10 @@
       if (MBB->empty()) {
         report("MBB exits via unconditional branch but doesn't contain "
                "any instructions!", MBB);
-      } else if (!MBB->back().getDesc().isBarrier()) {
+      } else if (!MBB->back().isBarrier()) {
         report("MBB exits via unconditional branch but doesn't end with a "
                "barrier instruction!", MBB);
-      } else if (!MBB->back().getDesc().isTerminator()) {
+      } else if (!MBB->back().isTerminator()) {
         report("MBB exits via unconditional branch but the branch isn't a "
                "terminator instruction!", MBB);
       }
@@ -479,10 +510,10 @@
       if (MBB->empty()) {
         report("MBB exits via conditional branch/fall-through but doesn't "
                "contain any instructions!", MBB);
-      } else if (MBB->back().getDesc().isBarrier()) {
+      } else if (MBB->back().isBarrier()) {
         report("MBB exits via conditional branch/fall-through but ends wit=
h a "
                "barrier instruction!", MBB);
-      } else if (!MBB->back().getDesc().isTerminator()) {
+      } else if (!MBB->back().isTerminator()) {
         report("MBB exits via conditional branch/fall-through but the bran=
ch "
                "isn't a terminator instruction!", MBB);
       }
@@ -499,10 +530,10 @@
       if (MBB->empty()) {
         report("MBB exits via conditional branch/branch but doesn't "
                "contain any instructions!", MBB);
-      } else if (!MBB->back().getDesc().isBarrier()) {
+      } else if (!MBB->back().isBarrier()) {
         report("MBB exits via conditional branch/branch but doesn't end wi=
th a "
                "barrier instruction!", MBB);
-      } else if (!MBB->back().getDesc().isTerminator()) {
+      } else if (!MBB->back().isTerminator()) {
         report("MBB exits via conditional branch/branch but the branch "
                "isn't a terminator instruction!", MBB);
       }
@@ -523,7 +554,7 @@
       continue;
     }
     regsLive.insert(*I);
-    for (const unsigned *R =3D TRI->getSubRegisters(*I); *R; R++)
+    for (const uint16_t *R =3D TRI->getSubRegisters(*I); *R; R++)
       regsLive.insert(*R);
   }
   regsLiveInButUnused =3D regsLive;
@@ -533,7 +564,7 @@
   BitVector PR =3D MFI->getPristineRegs(MBB);
   for (int I =3D PR.find_first(); I>0; I =3D PR.find_next(I)) {
     regsLive.insert(I);
-    for (const unsigned *R =3D TRI->getSubRegisters(I); *R; R++)
+    for (const uint16_t *R =3D TRI->getSubRegisters(I); *R; R++)
       regsLive.insert(*R);
   }
=20
@@ -555,19 +586,22 @@
   // Check the MachineMemOperands for basic consistency.
   for (MachineInstr::mmo_iterator I =3D MI->memoperands_begin(),
        E =3D MI->memoperands_end(); I !=3D E; ++I) {
-    if ((*I)->isLoad() && !MCID.mayLoad())
+    if ((*I)->isLoad() && !MI->mayLoad())
       report("Missing mayLoad flag", MI);
-    if ((*I)->isStore() && !MCID.mayStore())
+    if ((*I)->isStore() && !MI->mayStore())
       report("Missing mayStore flag", MI);
   }
=20
   // Debug values must not have a slot index.
-  // Other instructions must have one.
+  // Other instructions must have one, unless they are inside a bundle.
   if (LiveInts) {
     bool mapped =3D !LiveInts->isNotInMIMap(MI);
     if (MI->isDebugValue()) {
       if (mapped)
         report("Debug instruction has a slot index", MI);
+    } else if (MI->isInsideBundle()) {
+      if (mapped)
+        report("Instruction inside bundle has a slot index", MI);
     } else {
       if (!mapped)
         report("Missing slot index", MI);
@@ -575,7 +609,9 @@
   }
=20
   // Ensure non-terminators don't follow terminators.
-  if (MCID.isTerminator()) {
+  // Ignore predicated terminators formed by if conversion.
+  // FIXME: If conversion shouldn't need to violate this rule.
+  if (MI->isTerminator() && !TII->isPredicated(MI)) {
     if (!FirstTerminator)
       FirstTerminator =3D MI;
   } else if (FirstTerminator) {
@@ -606,7 +642,7 @@
     // Don't check if it's the last operand in a variadic instruction. See,
     // e.g., LDM_RET in the arm back end.
     if (MO->isReg() &&
-        !(MCID.isVariadic() && MONum =3D=3D MCID.getNumOperands()-1)) {
+        !(MI->isVariadic() && MONum =3D=3D MCID.getNumOperands()-1)) {
       if (MO->isDef() && !MCOI.isOptionalDef())
           report("Explicit operand marked as def", MO, MONum);
       if (MO->isImplicit())
@@ -614,7 +650,7 @@
     }
   } else {
     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
-    if (MO->isReg() && !MO->isImplicit() && !MCID.isVariadic() && MO->getR=
eg())
+    if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getRe=
g())
       report("Extra explicit operand on non-variadic instruction", MO, MON=
um);
   }
=20
@@ -623,112 +659,9 @@
     const unsigned Reg =3D MO->getReg();
     if (!Reg)
       return;
+    if (MRI->tracksLiveness() && !MI->isDebugValue())
+      checkLiveness(MO, MONum);
=20
-    // Check Live Variables.
-    if (MI->isDebugValue()) {
-      // Liveness checks are not valid for debug values.
-    } else if (MO->isUse() && !MO->isUndef()) {
-      regsLiveInButUnused.erase(Reg);
-
-      bool isKill =3D false;
-      unsigned defIdx;
-      if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
-        // A two-addr use counts as a kill if use and def are the same.
-        unsigned DefReg =3D MI->getOperand(defIdx).getReg();
-        if (Reg =3D=3D DefReg)
-          isKill =3D true;
-        else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
-          report("Two-address instruction operands must be identical",
-                 MO, MONum);
-        }
-      } else
-        isKill =3D MO->isKill();
-
-      if (isKill)
-        addRegWithSubRegs(regsKilled, Reg);
-
-      // Check that LiveVars knows this kill.
-      if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
-          MO->isKill()) {
-        LiveVariables::VarInfo &VI =3D LiveVars->getVarInfo(Reg);
-        if (std::find(VI.Kills.begin(),
-                      VI.Kills.end(), MI) =3D=3D VI.Kills.end())
-          report("Kill missing from LiveVariables", MO, MONum);
-      }
-
-      // Check LiveInts liveness and kill.
-      if (TargetRegisterInfo::isVirtualRegister(Reg) &&
-          LiveInts && !LiveInts->isNotInMIMap(MI)) {
-        SlotIndex UseIdx =3D LiveInts->getInstructionIndex(MI).getUseIndex=
();
-        if (LiveInts->hasInterval(Reg)) {
-          const LiveInterval &LI =3D LiveInts->getInterval(Reg);
-          if (!LI.liveAt(UseIdx)) {
-            report("No live range at use", MO, MONum);
-            *OS << UseIdx << " is not live in " << LI << '\n';
-          }
-          // Check for extra kill flags.
-          // Note that we allow missing kill flags for now.
-          if (MO->isKill() && !LI.killedAt(UseIdx.getDefIndex())) {
-            report("Live range continues after kill flag", MO, MONum);
-            *OS << "Live range: " << LI << '\n';
-          }
-        } else {
-          report("Virtual register has no Live interval", MO, MONum);
-        }
-      }
-
-      // Use of a dead register.
-      if (!regsLive.count(Reg)) {
-        if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
-          // Reserved registers may be used even when 'dead'.
-          if (!isReserved(Reg))
-            report("Using an undefined physical register", MO, MONum);
-        } else {
-          BBInfo &MInfo =3D MBBInfoMap[MI->getParent()];
-          // We don't know which virtual registers are live in, so only co=
mplain
-          // if vreg was killed in this MBB. Otherwise keep track of vregs=
 that
-          // must be live in. PHI instructions are handled separately.
-          if (MInfo.regsKilled.count(Reg))
-            report("Using a killed virtual register", MO, MONum);
-          else if (!MI->isPHI())
-            MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
-        }
-      }
-    } else if (MO->isDef()) {
-      // Register defined.
-      // TODO: verify that earlyclobber ops are not used.
-      if (MO->isDead())
-        addRegWithSubRegs(regsDead, Reg);
-      else
-        addRegWithSubRegs(regsDefined, Reg);
-
-      // Verify SSA form.
-      if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
-          llvm::next(MRI->def_begin(Reg)) !=3D MRI->def_end())
-        report("Multiple virtual register defs in SSA form", MO, MONum);
-
-      // Check LiveInts for a live range, but only for virtual registers.
-      if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
-          !LiveInts->isNotInMIMap(MI)) {
-        SlotIndex DefIdx =3D LiveInts->getInstructionIndex(MI).getDefIndex=
();
-        if (LiveInts->hasInterval(Reg)) {
-          const LiveInterval &LI =3D LiveInts->getInterval(Reg);
-          if (const VNInfo *VNI =3D LI.getVNInfoAt(DefIdx)) {
-            assert(VNI && "NULL valno is not allowed");
-            if (VNI->def !=3D DefIdx && !MO->isEarlyClobber()) {
-              report("Inconsistent valno->def", MO, MONum);
-              *OS << "Valno " << VNI->id << " is not defined at "
-                  << DefIdx << " in " << LI << '\n';
-            }
-          } else {
-            report("No live range at def", MO, MONum);
-            *OS << DefIdx << " is not live in " << LI << '\n';
-          }
-        } else {
-          report("Virtual register has no Live interval", MO, MONum);
-        }
-      }
-    }
=20
     // Check register classes.
     if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
@@ -790,6 +723,10 @@
     break;
   }
=20
+  case MachineOperand::MO_RegisterMask:
+    regMasks.push_back(MO->getRegMask());
+    break;
+
   case MachineOperand::MO_MachineBasicBlock:
     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
       report("PHI operand is not in the CFG", MO, MONum);
@@ -800,11 +737,11 @@
         LiveInts && !LiveInts->isNotInMIMap(MI)) {
       LiveInterval &LI =3D LiveStks->getInterval(MO->getIndex());
       SlotIndex Idx =3D LiveInts->getInstructionIndex(MI);
-      if (MCID.mayLoad() && !LI.liveAt(Idx.getUseIndex())) {
+      if (MI->mayLoad() && !LI.liveAt(Idx.getRegSlot(true))) {
         report("Instruction loads from dead spill slot", MO, MONum);
         *OS << "Live stack: " << LI << '\n';
       }
-      if (MCID.mayStore() && !LI.liveAt(Idx.getDefIndex())) {
+      if (MI->mayStore() && !LI.liveAt(Idx.getRegSlot())) {
         report("Instruction stores to dead spill slot", MO, MONum);
         *OS << "Live stack: " << LI << '\n';
       }
@@ -816,10 +753,127 @@
   }
 }
=20
+void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MON=
um) {
+  const MachineInstr *MI =3D MO->getParent();
+  const unsigned Reg =3D MO->getReg();
+
+  // Both use and def operands can read a register.
+  if (MO->readsReg()) {
+    regsLiveInButUnused.erase(Reg);
+
+    bool isKill =3D false;
+    unsigned defIdx;
+    if (MI->isRegTiedToDefOperand(MONum, &defIdx)) {
+      // A two-addr use counts as a kill if use and def are the same.
+      unsigned DefReg =3D MI->getOperand(defIdx).getReg();
+      if (Reg =3D=3D DefReg)
+        isKill =3D true;
+      else if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
+        report("Two-address instruction operands must be identical", MO, M=
ONum);
+      }
+    } else
+      isKill =3D MO->isKill();
+
+    if (isKill)
+      addRegWithSubRegs(regsKilled, Reg);
+
+    // Check that LiveVars knows this kill.
+    if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
+        MO->isKill()) {
+      LiveVariables::VarInfo &VI =3D LiveVars->getVarInfo(Reg);
+      if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) =3D=3D VI.Kills.=
end())
+        report("Kill missing from LiveVariables", MO, MONum);
+    }
+
+    // Check LiveInts liveness and kill.
+    if (TargetRegisterInfo::isVirtualRegister(Reg) &&
+        LiveInts && !LiveInts->isNotInMIMap(MI)) {
+      SlotIndex UseIdx =3D LiveInts->getInstructionIndex(MI).getRegSlot(tr=
ue);
+      if (LiveInts->hasInterval(Reg)) {
+        const LiveInterval &LI =3D LiveInts->getInterval(Reg);
+        if (!LI.liveAt(UseIdx)) {
+          report("No live range at use", MO, MONum);
+          *OS << UseIdx << " is not live in " << LI << '\n';
+        }
+        // Check for extra kill flags.
+        // Note that we allow missing kill flags for now.
+        if (MO->isKill() && !LI.killedAt(UseIdx.getRegSlot())) {
+          report("Live range continues after kill flag", MO, MONum);
+          *OS << "Live range: " << LI << '\n';
+        }
+      } else {
+        report("Virtual register has no Live interval", MO, MONum);
+      }
+    }
+
+    // Use of a dead register.
+    if (!regsLive.count(Reg)) {
+      if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
+        // Reserved registers may be used even when 'dead'.
+        if (!isReserved(Reg))
+          report("Using an undefined physical register", MO, MONum);
+      } else {
+        BBInfo &MInfo =3D MBBInfoMap[MI->getParent()];
+        // We don't know which virtual registers are live in, so only comp=
lain
+        // if vreg was killed in this MBB. Otherwise keep track of vregs t=
hat
+        // must be live in. PHI instructions are handled separately.
+        if (MInfo.regsKilled.count(Reg))
+          report("Using a killed virtual register", MO, MONum);
+        else if (!MI->isPHI())
+          MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
+      }
+    }
+  }
+
+  if (MO->isDef()) {
+    // Register defined.
+    // TODO: verify that earlyclobber ops are not used.
+    if (MO->isDead())
+      addRegWithSubRegs(regsDead, Reg);
+    else
+      addRegWithSubRegs(regsDefined, Reg);
+
+    // Verify SSA form.
+    if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
+        llvm::next(MRI->def_begin(Reg)) !=3D MRI->def_end())
+      report("Multiple virtual register defs in SSA form", MO, MONum);
+
+    // Check LiveInts for a live range, but only for virtual registers.
+    if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
+        !LiveInts->isNotInMIMap(MI)) {
+      SlotIndex DefIdx =3D LiveInts->getInstructionIndex(MI).getRegSlot();
+      if (LiveInts->hasInterval(Reg)) {
+        const LiveInterval &LI =3D LiveInts->getInterval(Reg);
+        if (const VNInfo *VNI =3D LI.getVNInfoAt(DefIdx)) {
+          assert(VNI && "NULL valno is not allowed");
+          if (VNI->def !=3D DefIdx && !MO->isEarlyClobber()) {
+            report("Inconsistent valno->def", MO, MONum);
+            *OS << "Valno " << VNI->id << " is not defined at "
+              << DefIdx << " in " << LI << '\n';
+          }
+        } else {
+          report("No live range at def", MO, MONum);
+          *OS << DefIdx << " is not live in " << LI << '\n';
+        }
+      } else {
+        report("Virtual register has no Live interval", MO, MONum);
+      }
+    }
+  }
+}
+
 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
   BBInfo &MInfo =3D MBBInfoMap[MI->getParent()];
   set_union(MInfo.regsKilled, regsKilled);
   set_subtract(regsLive, regsKilled); regsKilled.clear();
+  // Kill any masked registers.
+  while (!regMasks.empty()) {
+    const uint32_t *Mask =3D regMasks.pop_back_val();
+    for (RegSet::iterator I =3D regsLive.begin(), E =3D regsLive.end(); I =
!=3D E; ++I)
+      if (TargetRegisterInfo::isPhysicalRegister(*I) &&
+          MachineOperand::clobbersPhysReg(Mask, *I))
+        regsDead.push_back(*I);
+  }
   set_subtract(regsLive, regsDead);   regsDead.clear();
   set_union(regsLive, regsDefined);   regsDefined.clear();
=20
@@ -855,7 +909,7 @@
 void MachineVerifier::calcRegsPassed() {
   // First push live-out regs to successors' vregsPassed. Remember the MBB=
s that
   // have any vregsPassed.
-  DenseSet<const MachineBasicBlock*> todo;
+  SmallPtrSet<const MachineBasicBlock*, 8> todo;
   for (MachineFunction::const_iterator MFI =3D MF->begin(), MFE =3D MF->en=
d();
        MFI !=3D MFE; ++MFI) {
     const MachineBasicBlock &MBB(*MFI);
@@ -892,7 +946,7 @@
 // similar to calcRegsPassed, only backwards.
 void MachineVerifier::calcRegsRequired() {
   // First push live-in regs to predecessors' vregsRequired.
-  DenseSet<const MachineBasicBlock*> todo;
+  SmallPtrSet<const MachineBasicBlock*, 8> todo;
   for (MachineFunction::const_iterator MFI =3D MF->begin(), MFE =3D MF->en=
d();
        MFI !=3D MFE; ++MFI) {
     const MachineBasicBlock &MBB(*MFI);
@@ -925,9 +979,10 @@
 // Check PHI instructions at the beginning of MBB. It is assumed that
 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
+  SmallPtrSet<const MachineBasicBlock*, 8> seen;
   for (MachineBasicBlock::const_iterator BBI =3D MBB->begin(), BBE =3D MBB=
->end();
        BBI !=3D BBE && BBI->isPHI(); ++BBI) {
-    DenseSet<const MachineBasicBlock*> seen;
+    seen.clear();
=20
     for (unsigned i =3D 1, e =3D BBI->getNumOperands(); i !=3D e; i +=3D 2=
) {
       unsigned Reg =3D BBI->getOperand(i).getReg();
@@ -968,8 +1023,17 @@
   }
=20
   // Now check liveness info if available
-  if (LiveVars || LiveInts)
-    calcRegsRequired();
+  calcRegsRequired();
+
+  if (MRI->isSSA() && !MF->empty()) {
+    BBInfo &MInfo =3D MBBInfoMap[&MF->front()];
+    for (RegSet::iterator
+         I =3D MInfo.vregsRequired.begin(), E =3D MInfo.vregsRequired.end(=
); I !=3D E;
+         ++I)
+      report("Virtual register def doesn't dominate all uses.",
+             MRI->getVRegDef(*I));
+  }
+
   if (LiveVars)
     verifyLiveVariables();
   if (LiveInts)
@@ -1065,33 +1129,43 @@
           report("No instruction at def index", MF);
           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
               << " in " << LI << '\n';
-        } else if (!MI->modifiesRegister(LI.reg, TRI)) {
+          continue;
+        }
+
+        bool hasDef =3D false;
+        bool isEarlyClobber =3D false;
+        for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
+          if (!MOI->isReg() || !MOI->isDef())
+            continue;
+          if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
+            if (MOI->getReg() !=3D LI.reg)
+              continue;
+          } else {
+            if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
+                !TRI->regsOverlap(LI.reg, MOI->getReg()))
+              continue;
+          }
+          hasDef =3D true;
+          if (MOI->isEarlyClobber())
+            isEarlyClobber =3D true;
+        }
+
+        if (!hasDef) {
           report("Defining instruction does not modify register", MI);
           *OS << "Valno #" << VNI->id << " in " << LI << '\n';
         }
=20
-        bool isEarlyClobber =3D false;
-        if (MI) {
-          for (MachineInstr::const_mop_iterator MOI =3D MI->operands_begin=
(),
-               MOE =3D MI->operands_end(); MOI !=3D MOE; ++MOI) {
-            if (MOI->isReg() && MOI->getReg() =3D=3D LI.reg && MOI->isDef(=
) &&
-                MOI->isEarlyClobber()) {
-              isEarlyClobber =3D true;
-              break;
-            }
-          }
-        }
-
         // Early clobber defs begin at USE slots, but other defs must begi=
n at
         // DEF slots.
         if (isEarlyClobber) {
-          if (!VNI->def.isUse()) {
-            report("Early clobber def must be at a USE slot", MF);
+          if (!VNI->def.isEarlyClobber()) {
+            report("Early clobber def must be at an early-clobber slot", M=
F);
             *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
                 << " in " << LI << '\n';
           }
-        } else if (!VNI->def.isDef()) {
-          report("Non-PHI, non-early clobber def must be at a DEF slot", M=
F);
+        } else if (!VNI->def.isRegister()) {
+          report("Non-PHI, non-early clobber def must be at a register slo=
t",
+                 MF);
           *OS << "Valno #" << VNI->id << " is defined at " << VNI->def
               << " in " << LI << '\n';
         }
@@ -1137,32 +1211,76 @@
         *OS << " in " << LI << '\n';
         continue;
       }
-      if (I->end !=3D LiveInts->getMBBEndIdx(EndMBB)) {
-        // The live segment is ending inside EndMBB
-        const MachineInstr *MI =3D
-                        LiveInts->getInstructionFromIndex(I->end.getPrevSl=
ot());
-        if (!MI) {
-          report("Live segment doesn't end at a valid instruction", EndMBB=
);
+
+      // No more checks for live-out segments.
+      if (I->end =3D=3D LiveInts->getMBBEndIdx(EndMBB))
+        continue;
+
+      // The live segment is ending inside EndMBB
+      const MachineInstr *MI =3D
+        LiveInts->getInstructionFromIndex(I->end.getPrevSlot());
+      if (!MI) {
+        report("Live segment doesn't end at a valid instruction", EndMBB);
         I->print(*OS);
         *OS << " in " << LI << '\n' << "Basic block starts at "
-            << MBBStartIdx << '\n';
-        } else if (TargetRegisterInfo::isVirtualRegister(LI.reg) &&
-                   !MI->readsVirtualRegister(LI.reg)) {
-          // A live range can end with either a redefinition, a kill flag =
on a
-          // use, or a dead flag on a def.
-          // FIXME: Should we check for each of these?
-          bool hasDeadDef =3D false;
-          for (MachineInstr::const_mop_iterator MOI =3D MI->operands_begin=
(),
-               MOE =3D MI->operands_end(); MOI !=3D MOE; ++MOI) {
-            if (MOI->isReg() && MOI->getReg() =3D=3D LI.reg && MOI->isDef(=
) && MOI->isDead()) {
-              hasDeadDef =3D true;
-              break;
-            }
+          << MBBStartIdx << '\n';
+        continue;
+      }
+
+      // The block slot must refer to a basic block boundary.
+      if (I->end.isBlock()) {
+        report("Live segment ends at B slot of an instruction", MI);
+        I->print(*OS);
+        *OS << " in " << LI << '\n';
+      }
+
+      if (I->end.isDead()) {
+        // Segment ends on the dead slot.
+        // That means there must be a dead def.
+        if (!SlotIndex::isSameInstr(I->start, I->end)) {
+          report("Live segment ending at dead slot spans instructions", MI=
);
+          I->print(*OS);
+          *OS << " in " << LI << '\n';
+        }
+      }
+
+      // A live segment can only end at an early-clobber slot if it is bei=
ng
+      // redefined by an early-clobber def.
+      if (I->end.isEarlyClobber()) {
+        if (I+1 =3D=3D E || (I+1)->start !=3D I->end) {
+          report("Live segment ending at early clobber slot must be "
+                 "redefined by an EC def in the same instruction", MI);
+          I->print(*OS);
+          *OS << " in " << LI << '\n';
+        }
+      }
+
+      // The following checks only apply to virtual registers. Physreg liv=
eness
+      // is too weird to check.
+      if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
+        // A live range can end with either a redefinition, a kill flag on=
 a
+        // use, or a dead flag on a def.
+        bool hasRead =3D false;
+        bool hasDeadDef =3D false;
+        for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
+          if (!MOI->isReg() || MOI->getReg() !=3D LI.reg)
+            continue;
+          if (MOI->readsReg())
+            hasRead =3D true;
+          if (MOI->isDef() && MOI->isDead())
+            hasDeadDef =3D true;
+        }
+
+        if (I->end.isDead()) {
+          if (!hasDeadDef) {
+            report("Instruction doesn't have a dead def operand", MI);
+            I->print(*OS);
+            *OS << " in " << LI << '\n';
           }
-
-          if (!hasDeadDef) {
-            report("Instruction killing live segment neither defines nor r=
eads "
-                   "register", MI);
+        } else {
+          if (!hasRead) {
+            report("Instruction ending live range doesn't read the registe=
r",
+                   MI);
             I->print(*OS);
             *OS << " in " << LI << '\n';
           }
@@ -1192,8 +1310,8 @@
         // Check that VNI is live-out of all predecessors.
         for (MachineBasicBlock::const_pred_iterator PI =3D MFI->pred_begin=
(),
              PE =3D MFI->pred_end(); PI !=3D PE; ++PI) {
-          SlotIndex PEnd =3D LiveInts->getMBBEndIdx(*PI).getPrevSlot();
-          const VNInfo *PVNI =3D LI.getVNInfoAt(PEnd);
+          SlotIndex PEnd =3D LiveInts->getMBBEndIdx(*PI);
+          const VNInfo *PVNI =3D LI.getVNInfoBefore(PEnd);
=20
           if (VNI->isPHIDef() && VNI->def =3D=3D LiveInts->getMBBStartIdx(=
MFI))
             continue;
@@ -1201,7 +1319,7 @@
           if (!PVNI) {
             report("Register not marked live out of predecessor", *PI);
             *OS << "Valno #" << VNI->id << " live into BB#" << MFI->getNum=
ber()
-                << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live at "
+                << '@' << LiveInts->getMBBStartIdx(MFI) << ", not live bef=
ore "
                 << PEnd << " in " << LI << '\n';
             continue;
           }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Optimize=
PHIs.cpp
--- a/head/contrib/llvm/lib/CodeGen/OptimizePHIs.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/CodeGen/OptimizePHIs.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -56,11 +56,10 @@
 }
=20
 char OptimizePHIs::ID =3D 0;
+char &llvm::OptimizePHIsID =3D OptimizePHIs::ID;
 INITIALIZE_PASS(OptimizePHIs, "opt-phis",
                 "Optimize machine instruction PHIs", false, false)
=20
-FunctionPass *llvm::createOptimizePHIsPass() { return new OptimizePHIs(); }
-
 bool OptimizePHIs::runOnMachineFunction(MachineFunction &Fn) {
   MRI =3D &Fn.getRegInfo();
   TII =3D Fn.getTarget().getInstrInfo();
@@ -165,7 +164,11 @@
     InstrSet PHIsInCycle;
     if (IsSingleValuePHICycle(MI, SingleValReg, PHIsInCycle) &&
         SingleValReg !=3D 0) {
-      MRI->replaceRegWith(MI->getOperand(0).getReg(), SingleValReg);
+      unsigned OldReg =3D MI->getOperand(0).getReg();
+      if (!MRI->constrainRegClass(SingleValReg, MRI->getRegClass(OldReg)))
+        continue;
+
+      MRI->replaceRegWith(OldReg, SingleValReg);
       MI->eraseFromParent();
       ++NumPHICycles;
       Changed =3D true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/PHIElimi=
nation.cpp
--- a/head/contrib/llvm/lib/CodeGen/PHIElimination.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/PHIElimination.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -92,10 +92,14 @@
 STATISTIC(NumReused, "Number of reused lowered phis");
=20
 char PHIElimination::ID =3D 0;
-INITIALIZE_PASS(PHIElimination, "phi-node-elimination",
-                "Eliminate PHI nodes for register allocation", false, fals=
e)
+char& llvm::PHIEliminationID =3D PHIElimination::ID;
=20
-char& llvm::PHIEliminationID =3D PHIElimination::ID;
+INITIALIZE_PASS_BEGIN(PHIElimination, "phi-node-elimination",
+                      "Eliminate PHI nodes for register allocation",
+                      false, false)
+INITIALIZE_PASS_DEPENDENCY(LiveVariables)
+INITIALIZE_PASS_END(PHIElimination, "phi-node-elimination",
+                    "Eliminate PHI nodes for register allocation", false, =
false)
=20
 void PHIElimination::getAnalysisUsage(AnalysisUsage &AU) const {
   AU.addPreserved<LiveVariables>();
@@ -241,7 +245,6 @@
       LiveVariables::VarInfo &VI =3D LV->getVarInfo(IncomingReg);
=20
       // Increment use count of the newly created virtual register.
-      VI.NumUses++;
       LV->setPHIJoin(IncomingReg);
=20
       // When we are reusing the incoming register, it may already have be=
en
@@ -410,7 +413,7 @@
     return false;   // Quick exit for basic blocks without PHIs.
=20
   bool Changed =3D false;
-  for (MachineBasicBlock::const_iterator BBI =3D MBB.begin(), BBE =3D MBB.=
end();
+  for (MachineBasicBlock::iterator BBI =3D MBB.begin(), BBE =3D MBB.end();
        BBI !=3D BBE && BBI->isPHI(); ++BBI) {
     for (unsigned i =3D 1, e =3D BBI->getNumOperands(); i !=3D e; i +=3D 2=
) {
       unsigned Reg =3D BBI->getOperand(i).getReg();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Passes.c=
pp
--- a/head/contrib/llvm/lib/CodeGen/Passes.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/CodeGen/Passes.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -12,62 +12,617 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
+#include "llvm/Analysis/Passes.h"
+#include "llvm/Analysis/Verifier.h"
+#include "llvm/Transforms/Scalar.h"
+#include "llvm/PassManager.h"
+#include "llvm/CodeGen/GCStrategy.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/Passes.h"
 #include "llvm/CodeGen/RegAllocRegistry.h"
-#include "llvm/CodeGen/Passes.h"
+#include "llvm/Target/TargetLowering.h"
+#include "llvm/Target/TargetOptions.h"
+#include "llvm/Assembly/PrintModulePass.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
=20
 using namespace llvm;
=20
+static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
+    cl::desc("Disable Post Regalloc"));
+static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
+    cl::desc("Disable branch folding"));
+static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hi=
dden,
+    cl::desc("Disable tail duplication"));
+static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidd=
en,
+    cl::desc("Disable pre-register allocation tail duplication"));
+static cl::opt<bool> EnableBlockPlacement("enable-block-placement",
+    cl::Hidden, cl::desc("Enable probability-driven block placement"));
+static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-sta=
ts",
+    cl::Hidden, cl::desc("Collect probability-driven block placement stats=
"));
+static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
+    cl::desc("Disable code placement"));
+static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
+    cl::desc("Disable Stack Slot Coloring"));
+static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
+    cl::desc("Disable Machine Dead Code Elimination"));
+static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
+    cl::desc("Disable Machine LICM"));
+static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
+    cl::desc("Disable Machine Common Subexpression Elimination"));
+static cl::opt<cl::boolOrDefault>
+OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
+    cl::desc("Enable optimized register allocation compilation path."));
+static cl::opt<cl::boolOrDefault>
+EnableMachineSched("enable-misched", cl::Hidden,
+    cl::desc("Enable the machine instruction scheduling pass."));
+static cl::opt<bool> EnableStrongPHIElim("strong-phi-elim", cl::Hidden,
+    cl::desc("Use strong PHI elimination."));
+static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm=
",
+    cl::Hidden,
+    cl::desc("Disable Machine LICM"));
+static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
+    cl::desc("Disable Machine Sinking"));
+static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
+    cl::desc("Disable Loop Strength Reduction Pass"));
+static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
+    cl::desc("Disable Codegen Prepare"));
+static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
+    cl::desc("Disable Copy Propagation pass"));
+static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
+    cl::desc("Print LLVM IR produced by the loop-reduce pass"));
+static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
+    cl::desc("Print LLVM IR input to isel pass"));
+static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
+    cl::desc("Dump garbage collector data"));
+static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
+    cl::desc("Verify generated machine code"),
+    cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=3DNULL));
+
+/// Allow standard passes to be disabled by command line options. This sup=
ports
+/// simple binary flags that either suppress the pass or do nothing.
+/// i.e. -disable-mypass=3Dfalse has no effect.
+/// These should be converted to boolOrDefault in order to use applyOverri=
de.
+static AnalysisID applyDisable(AnalysisID ID, bool Override) {
+  if (Override)
+    return &NoPassID;
+  return ID;
+}
+
+/// Allow Pass selection to be overriden by command line options. This sup=
ports
+/// flags with ternary conditions. TargetID is passed through by default. =
The
+/// pass is suppressed when the option is false. When the option is true, =
the
+/// StandardID is selected if the target provides no default.
+static AnalysisID applyOverride(AnalysisID TargetID, cl::boolOrDefault Ove=
rride,
+                                AnalysisID StandardID) {
+  switch (Override) {
+  case cl::BOU_UNSET:
+    return TargetID;
+  case cl::BOU_TRUE:
+    if (TargetID !=3D &NoPassID)
+      return TargetID;
+    if (StandardID =3D=3D &NoPassID)
+      report_fatal_error("Target cannot enable pass");
+    return StandardID;
+  case cl::BOU_FALSE:
+    return &NoPassID;
+  }
+  llvm_unreachable("Invalid command line option state");
+}
+
+/// Allow standard passes to be disabled by the command line, regardless o=
f who
+/// is adding the pass.
+///
+/// StandardID is the pass identified in the standard pass pipeline and pr=
ovided
+/// to addPass(). It may be a target-specific ID in the case that the targ=
et
+/// directly adds its own pass, but in that case we harmlessly fall throug=
h.
+///
+/// TargetID is the pass that the target has configured to override Standa=
rdID.
+///
+/// StandardID may be a pseudo ID. In that case TargetID is the name of th=
e real
+/// pass to run. This allows multiple options to control a single pass dep=
ending
+/// on where in the pipeline that pass is added.
+static AnalysisID overridePass(AnalysisID StandardID, AnalysisID TargetID)=
 {
+  if (StandardID =3D=3D &PostRASchedulerID)
+    return applyDisable(TargetID, DisablePostRA);
+
+  if (StandardID =3D=3D &BranchFolderPassID)
+    return applyDisable(TargetID, DisableBranchFold);
+
+  if (StandardID =3D=3D &TailDuplicateID)
+    return applyDisable(TargetID, DisableTailDuplicate);
+
+  if (StandardID =3D=3D &TargetPassConfig::EarlyTailDuplicateID)
+    return applyDisable(TargetID, DisableEarlyTailDup);
+
+  if (StandardID =3D=3D &MachineBlockPlacementID)
+    return applyDisable(TargetID, DisableCodePlace);
+
+  if (StandardID =3D=3D &CodePlacementOptID)
+    return applyDisable(TargetID, DisableCodePlace);
+
+  if (StandardID =3D=3D &StackSlotColoringID)
+    return applyDisable(TargetID, DisableSSC);
+
+  if (StandardID =3D=3D &DeadMachineInstructionElimID)
+    return applyDisable(TargetID, DisableMachineDCE);
+
+  if (StandardID =3D=3D &MachineLICMID)
+    return applyDisable(TargetID, DisableMachineLICM);
+
+  if (StandardID =3D=3D &MachineCSEID)
+    return applyDisable(TargetID, DisableMachineCSE);
+
+  if (StandardID =3D=3D &MachineSchedulerID)
+    return applyOverride(TargetID, EnableMachineSched, StandardID);
+
+  if (StandardID =3D=3D &TargetPassConfig::PostRAMachineLICMID)
+    return applyDisable(TargetID, DisablePostRAMachineLICM);
+
+  if (StandardID =3D=3D &MachineSinkingID)
+    return applyDisable(TargetID, DisableMachineSink);
+
+  if (StandardID =3D=3D &MachineCopyPropagationID)
+    return applyDisable(TargetID, DisableCopyProp);
+
+  return TargetID;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+/// TargetPassConfig
+//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+
+INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
+                "Target Pass Configuration", false, false)
+char TargetPassConfig::ID =3D 0;
+
+static char NoPassIDAnchor =3D 0;
+char &llvm::NoPassID =3D NoPassIDAnchor;
+
+// Pseudo Pass IDs.
+char TargetPassConfig::EarlyTailDuplicateID =3D 0;
+char TargetPassConfig::PostRAMachineLICMID =3D 0;
+
+namespace llvm {
+class PassConfigImpl {
+public:
+  // List of passes explicitly substituted by this target. Normally this is
+  // empty, but it is a convenient way to suppress or replace specific pas=
ses
+  // that are part of a standard pass pipeline without overridding the ent=
ire
+  // pipeline. This mechanism allows target options to inherit a standard =
pass's
+  // user interface. For example, a target may disable a standard pass by
+  // default by substituting NoPass, and the user may still enable that st=
andard
+  // pass with an explicit command line option.
+  DenseMap<AnalysisID,AnalysisID> TargetPasses;
+};
+} // namespace llvm
+
+// Out of line virtual method.
+TargetPassConfig::~TargetPassConfig() {
+  delete Impl;
+}
+
+// Out of line constructor provides default values for pass options and
+// registers all common codegen passes.
+TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
+  : ImmutablePass(ID), TM(tm), PM(pm), Impl(0), Initialized(false),
+    DisableVerify(false),
+    EnableTailMerge(true) {
+
+  Impl =3D new PassConfigImpl();
+
+  // Register all target independent codegen passes to activate their Pass=
IDs,
+  // including this pass itself.
+  initializeCodeGen(*PassRegistry::getPassRegistry());
+
+  // Substitute Pseudo Pass IDs for real ones.
+  substitutePass(EarlyTailDuplicateID, TailDuplicateID);
+  substitutePass(PostRAMachineLICMID, MachineLICMID);
+
+  // Temporarily disable experimental passes.
+  substitutePass(MachineSchedulerID, NoPassID);
+}
+
+/// createPassConfig - Create a pass configuration object to be used by
+/// addPassToEmitX methods for generating a pipeline of CodeGen passes.
 ///
-/// RegisterRegAlloc class - Track the registration of register allocators.
+/// Targets may override this to extend TargetPassConfig.
+TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM)=
 {
+  return new TargetPassConfig(this, PM);
+}
+
+TargetPassConfig::TargetPassConfig()
+  : ImmutablePass(ID), PM(*(PassManagerBase*)0) {
+  llvm_unreachable("TargetPassConfig should not be constructed on-the-fly"=
);
+}
+
+// Helper to verify the analysis is really immutable.
+void TargetPassConfig::setOpt(bool &Opt, bool Val) {
+  assert(!Initialized && "PassConfig is immutable");
+  Opt =3D Val;
+}
+
+void TargetPassConfig::substitutePass(char &StandardID, char &TargetID) {
+  Impl->TargetPasses[&StandardID] =3D &TargetID;
+}
+
+AnalysisID TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
+  DenseMap<AnalysisID, AnalysisID>::const_iterator
+    I =3D Impl->TargetPasses.find(ID);
+  if (I =3D=3D Impl->TargetPasses.end())
+    return ID;
+  return I->second;
+}
+
+/// Add a CodeGen pass at this point in the pipeline after checking for ta=
rget
+/// and command line overrides.
+AnalysisID TargetPassConfig::addPass(char &ID) {
+  assert(!Initialized && "PassConfig is immutable");
+
+  AnalysisID TargetID =3D getPassSubstitution(&ID);
+  AnalysisID FinalID =3D overridePass(&ID, TargetID);
+  if (FinalID =3D=3D &NoPassID)
+    return FinalID;
+
+  Pass *P =3D Pass::createPass(FinalID);
+  if (!P)
+    llvm_unreachable("Pass ID not registered");
+  PM.add(P);
+  return FinalID;
+}
+
+void TargetPassConfig::printAndVerify(const char *Banner) const {
+  if (TM->shouldPrintMachineCode())
+    PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
+
+  if (VerifyMachineCode)
+    PM.add(createMachineVerifierPass(Banner));
+}
+
+/// Add common target configurable passes that perform LLVM IR to IR trans=
forms
+/// following machine independent optimization.
+void TargetPassConfig::addIRPasses() {
+  // Basic AliasAnalysis support.
+  // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
+  // BasicAliasAnalysis wins if they disagree. This is intended to help
+  // support "obvious" type-punning idioms.
+  PM.add(createTypeBasedAliasAnalysisPass());
+  PM.add(createBasicAliasAnalysisPass());
+
+  // Before running any passes, run the verifier to determine if the input
+  // coming from the front-end and/or optimizer is valid.
+  if (!DisableVerify)
+    PM.add(createVerifierPass());
+
+  // Run loop strength reduction before anything else.
+  if (getOptLevel() !=3D CodeGenOpt::None && !DisableLSR) {
+    PM.add(createLoopStrengthReducePass(getTargetLowering()));
+    if (PrintLSR)
+      PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs=
()));
+  }
+
+  PM.add(createGCLoweringPass());
+
+  // Make sure that no unreachable blocks are instruction selected.
+  PM.add(createUnreachableBlockEliminationPass());
+}
+
+/// Add common passes that perform LLVM IR to IR transforms in preparation=
 for
+/// instruction selection.
+void TargetPassConfig::addISelPrepare() {
+  if (getOptLevel() !=3D CodeGenOpt::None && !DisableCGP)
+    PM.add(createCodeGenPreparePass(getTargetLowering()));
+
+  PM.add(createStackProtectorPass(getTargetLowering()));
+
+  addPreISel();
+
+  if (PrintISelInput)
+    PM.add(createPrintFunctionPass("\n\n"
+                                   "*** Final LLVM Code input to ISel ***\=
n",
+                                   &dbgs()));
+
+  // All passes which modify the LLVM IR are now complete; run the verifier
+  // to ensure that the IR is valid.
+  if (!DisableVerify)
+    PM.add(createVerifierPass());
+}
+
+/// Add the complete set of target-independent postISel code generator pas=
ses.
 ///
+/// This can be read as the standard order of major LLVM CodeGen stages. S=
tages
+/// with nontrivial configuration or multiple passes are broken out below =
in
+/// add%Stage routines.
+///
+/// Any TargetPassConfig::addXX routine may be overriden by the Target. The
+/// addPre/Post methods with empty header implementations allow injecting
+/// target-specific fixups just before or after major stages. Additionally,
+/// targets have the flexibility to change pass order within a stage by
+/// overriding default implementation of add%Stage routines below. Each
+/// technique has maintainability tradeoffs because alternate pass orders =
are
+/// not well supported. addPre/Post works better if the target pass is eas=
ily
+/// tied to a common pass. But if it has subtle dependencies on multiple p=
asses,
+/// the target should override the stage instead.
+///
+/// TODO: We could use a single addPre/Post(ID) hook to allow pass injecti=
on
+/// before/after any target-independent pass. But it's currently overkill.
+void TargetPassConfig::addMachinePasses() {
+  // Print the instruction selected machine code...
+  printAndVerify("After Instruction Selection");
+
+  // Expand pseudo-instructions emitted by ISel.
+  addPass(ExpandISelPseudosID);
+
+  // Add passes that optimize machine instructions in SSA form.
+  if (getOptLevel() !=3D CodeGenOpt::None) {
+    addMachineSSAOptimization();
+  }
+  else {
+    // If the target requests it, assign local variables to stack slots re=
lative
+    // to one another and simplify frame index references where possible.
+    addPass(LocalStackSlotAllocationID);
+  }
+
+  // Run pre-ra passes.
+  if (addPreRegAlloc())
+    printAndVerify("After PreRegAlloc passes");
+
+  // Run register allocation and passes that are tightly coupled with it,
+  // including phi elimination and scheduling.
+  if (getOptimizeRegAlloc())
+    addOptimizedRegAlloc(createRegAllocPass(true));
+  else
+    addFastRegAlloc(createRegAllocPass(false));
+
+  // Run post-ra passes.
+  if (addPostRegAlloc())
+    printAndVerify("After PostRegAlloc passes");
+
+  // Insert prolog/epilog code.  Eliminate abstract frame index references=
...
+  addPass(PrologEpilogCodeInserterID);
+  printAndVerify("After PrologEpilogCodeInserter");
+
+  /// Add passes that optimize machine instructions after register allocat=
ion.
+  if (getOptLevel() !=3D CodeGenOpt::None)
+    addMachineLateOptimization();
+
+  // Expand pseudo instructions before second scheduling pass.
+  addPass(ExpandPostRAPseudosID);
+  printAndVerify("After ExpandPostRAPseudos");
+
+  // Run pre-sched2 passes.
+  if (addPreSched2())
+    printAndVerify("After PreSched2 passes");
+
+  // Second pass scheduler.
+  if (getOptLevel() !=3D CodeGenOpt::None) {
+    addPass(PostRASchedulerID);
+    printAndVerify("After PostRAScheduler");
+  }
+
+  // GC
+  addPass(GCMachineCodeAnalysisID);
+  if (PrintGCInfo)
+    PM.add(createGCInfoPrinter(dbgs()));
+
+  // Basic block placement.
+  if (getOptLevel() !=3D CodeGenOpt::None)
+    addBlockPlacement();
+
+  if (addPreEmitPass())
+    printAndVerify("After PreEmit passes");
+}
+
+/// Add passes that optimize machine instructions in SSA form.
+void TargetPassConfig::addMachineSSAOptimization() {
+  // Pre-ra tail duplication.
+  if (addPass(EarlyTailDuplicateID) !=3D &NoPassID)
+    printAndVerify("After Pre-RegAlloc TailDuplicate");
+
+  // Optimize PHIs before DCE: removing dead PHI cycles may make more
+  // instructions dead.
+  addPass(OptimizePHIsID);
+
+  // If the target requests it, assign local variables to stack slots rela=
tive
+  // to one another and simplify frame index references where possible.
+  addPass(LocalStackSlotAllocationID);
+
+  // With optimization, dead code should already be eliminated. However
+  // there is one known exception: lowered code for arguments that are only
+  // used by tail calls, where the tail calls reuse the incoming stack
+  // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
+  addPass(DeadMachineInstructionElimID);
+  printAndVerify("After codegen DCE pass");
+
+  addPass(MachineLICMID);
+  addPass(MachineCSEID);
+  addPass(MachineSinkingID);
+  printAndVerify("After Machine LICM, CSE and Sinking passes");
+
+  addPass(PeepholeOptimizerID);
+  printAndVerify("After codegen peephole optimization pass");
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+/// Register Allocation Pass Configuration
+//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+
+bool TargetPassConfig::getOptimizeRegAlloc() const {
+  switch (OptimizeRegAlloc) {
+  case cl::BOU_UNSET: return getOptLevel() !=3D CodeGenOpt::None;
+  case cl::BOU_TRUE:  return true;
+  case cl::BOU_FALSE: return false;
+  }
+  llvm_unreachable("Invalid optimize-regalloc state");
+}
+
+/// RegisterRegAlloc's global Registry tracks allocator registration.
 MachinePassRegistry RegisterRegAlloc::Registry;
=20
-static FunctionPass *createDefaultRegisterAllocator() { return 0; }
+/// A dummy default pass factory indicates whether the register allocator =
is
+/// overridden on the command line.
+static FunctionPass *useDefaultRegisterAllocator() { return 0; }
 static RegisterRegAlloc
 defaultRegAlloc("default",
                 "pick register allocator based on -O option",
-                createDefaultRegisterAllocator);
+                useDefaultRegisterAllocator);
=20
-//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
-///
-/// RegAlloc command line options.
-///
-//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+/// -regalloc=3D... command line option.
 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
                RegisterPassParser<RegisterRegAlloc> >
 RegAlloc("regalloc",
-         cl::init(&createDefaultRegisterAllocator),
+         cl::init(&useDefaultRegisterAllocator),
          cl::desc("Register allocator to use"));
=20
=20
-//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+/// Instantiate the default register allocator pass for this target for ei=
ther
+/// the optimized or unoptimized allocation path. This will be added to th=
e pass
+/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegA=
lloc
+/// in the optimized case.
 ///
-/// createRegisterAllocator - choose the appropriate register allocator.
+/// A target that uses the standard regalloc pass order for fast or optimi=
zed
+/// allocation may still override this for per-target regalloc
+/// selection. But -regalloc=3D... always takes precedence.
+FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimiz=
ed) {
+  if (Optimized)
+    return createGreedyRegisterAllocator();
+  else
+    return createFastRegisterAllocator();
+}
+
+/// Find and instantiate the register allocation pass requested by this ta=
rget
+/// at the current optimization level.  Different register allocators are
+/// defined as separate passes because they may require different analysis.
 ///
-//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
-FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
+/// This helper ensures that the regalloc=3D option is always available,
+/// even for targets that override the default allocator.
+///
+/// FIXME: When MachinePassRegistry register pass IDs instead of function =
ptrs,
+/// this can be folded into addPass.
+FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
   RegisterRegAlloc::FunctionPassCtor Ctor =3D RegisterRegAlloc::getDefault=
();
=20
+  // Initialize the global default.
   if (!Ctor) {
     Ctor =3D RegAlloc;
     RegisterRegAlloc::setDefault(RegAlloc);
   }
-
-  // This forces linking of the linear scan register allocator,
-  // so -regalloc=3Dlinearscan still works in clang.
-  if (Ctor =3D=3D createLinearScanRegisterAllocator)
-    return createLinearScanRegisterAllocator();
-
-  if (Ctor !=3D createDefaultRegisterAllocator)
+  if (Ctor !=3D useDefaultRegisterAllocator)
     return Ctor();
=20
-  // When the 'default' allocator is requested, pick one based on OptLevel.
-  switch (OptLevel) {
-  case CodeGenOpt::None:
-    return createFastRegisterAllocator();
-  default:
-    return createGreedyRegisterAllocator();
+  // With no -regalloc=3D override, ask the target for a regalloc pass.
+  return createTargetRegisterAllocator(Optimized);
+}
+
+/// Add the minimum set of target-independent passes that are required for
+/// register allocation. No coalescing or scheduling.
+void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
+  addPass(PHIEliminationID);
+  addPass(TwoAddressInstructionPassID);
+
+  PM.add(RegAllocPass);
+  printAndVerify("After Register Allocation");
+}
+
+/// Add standard target-independent passes that are tightly coupled with
+/// optimized register allocation, including coalescing, machine instructi=
on
+/// scheduling, and register allocation itself.
+void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
+  // LiveVariables currently requires pure SSA form.
+  //
+  // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
+  // LiveVariables can be removed completely, and LiveIntervals can be dir=
ectly
+  // computed. (We still either need to regenerate kill flags after regall=
oc, or
+  // preferably fix the scavenger to not depend on them).
+  addPass(LiveVariablesID);
+
+  // Add passes that move from transformed SSA into conventional SSA. This=
 is a
+  // "copy coalescing" problem.
+  //
+  if (!EnableStrongPHIElim) {
+    // Edge splitting is smarter with machine loop info.
+    addPass(MachineLoopInfoID);
+    addPass(PHIEliminationID);
+  }
+  addPass(TwoAddressInstructionPassID);
+
+  // FIXME: Either remove this pass completely, or fix it so that it works=
 on
+  // SSA form. We could modify LiveIntervals to be independent of this pas=
s, But
+  // it would be even better to simply eliminate *all* IMPLICIT_DEFs before
+  // leaving SSA.
+  addPass(ProcessImplicitDefsID);
+
+  if (EnableStrongPHIElim)
+    addPass(StrongPHIEliminationID);
+
+  addPass(RegisterCoalescerID);
+
+  // PreRA instruction scheduling.
+  if (addPass(MachineSchedulerID) !=3D &NoPassID)
+    printAndVerify("After Machine Scheduling");
+
+  // Add the selected register allocation pass.
+  PM.add(RegAllocPass);
+  printAndVerify("After Register Allocation");
+
+  // FinalizeRegAlloc is convenient until MachineInstrBundles is more matu=
re,
+  // but eventually, all users of it should probably be moved to addPostRA=
 and
+  // it can go away.  Currently, it's the intended place for targets to run
+  // FinalizeMachineBundles, because passes other than MachineScheduling an
+  // RegAlloc itself may not be aware of bundles.
+  if (addFinalizeRegAlloc())
+    printAndVerify("After RegAlloc finalization");
+
+  // Perform stack slot coloring and post-ra machine LICM.
+  //
+  // FIXME: Re-enable coloring with register when it's capable of adding
+  // kill markers.
+  addPass(StackSlotColoringID);
+
+  // Run post-ra machine LICM to hoist reloads / remats.
+  //
+  // FIXME: can this move into MachineLateOptimization?
+  addPass(PostRAMachineLICMID);
+
+  printAndVerify("After StackSlotColoring and postra Machine LICM");
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+/// Post RegAlloc Pass Configuration
+//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+
+/// Add passes that optimize machine instructions after register allocatio=
n.
+void TargetPassConfig::addMachineLateOptimization() {
+  // Branch folding must be run after regalloc and prolog/epilog insertion.
+  if (addPass(BranchFolderPassID) !=3D &NoPassID)
+    printAndVerify("After BranchFolding");
+
+  // Tail duplication.
+  if (addPass(TailDuplicateID) !=3D &NoPassID)
+    printAndVerify("After TailDuplicate");
+
+  // Copy propagation.
+  if (addPass(MachineCopyPropagationID) !=3D &NoPassID)
+    printAndVerify("After copy propagation pass");
+}
+
+/// Add standard basic block placement passes.
+void TargetPassConfig::addBlockPlacement() {
+  AnalysisID ID =3D &NoPassID;
+  if (EnableBlockPlacement) {
+    // MachineBlockPlacement is an experimental pass which is disabled by
+    // default currently. Eventually it should subsume CodePlacementOpt, so
+    // when enabled, the other is disabled.
+    ID =3D addPass(MachineBlockPlacementID);
+  } else {
+    ID =3D addPass(CodePlacementOptID);
+  }
+  if (ID !=3D &NoPassID) {
+    // Run a separate pass to collect block placement statistics.
+    if (EnableBlockPlacementStats)
+      addPass(MachineBlockPlacementStatsID);
+
+    printAndVerify("After machine block placement.");
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Peephole=
Optimizer.cpp
--- a/head/contrib/llvm/lib/CodeGen/PeepholeOptimizer.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/PeepholeOptimizer.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -39,7 +39,7 @@
 //   =3D>
 //     v1 =3D bitcast v0
 //        =3D v0
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "peephole-opt"
@@ -68,7 +68,7 @@
 STATISTIC(NumReuse,      "Number of extension results reused");
 STATISTIC(NumBitcasts,   "Number of bitcasts eliminated");
 STATISTIC(NumCmps,       "Number of compares eliminated");
-STATISTIC(NumImmFold,    "Number of move immediate foled");
+STATISTIC(NumImmFold,    "Number of move immediate folded");
=20
 namespace {
   class PeepholeOptimizer : public MachineFunctionPass {
@@ -109,22 +109,19 @@
 }
=20
 char PeepholeOptimizer::ID =3D 0;
+char &llvm::PeepholeOptimizerID =3D PeepholeOptimizer::ID;
 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
                 "Peephole Optimizations", false, false)
 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
                 "Peephole Optimizations", false, false)
=20
-FunctionPass *llvm::createPeepholeOptimizerPass() {
-  return new PeepholeOptimizer();
-}
-
 /// OptimizeExtInstr - If instruction is a copy-like instruction, i.e. it =
reads
 /// a single register and writes a single register and it does not modify =
the
 /// source, and if the source value is preserved as a sub-register of the
 /// result, then replace all reachable uses of the source with the subreg =
of the
 /// result.
-///=20
+///
 /// Do not generate an EXTRACT that is used only in a debug use, as this c=
hanges
 /// the code. Since this code does not currently share EXTRACTs, just igno=
re all
 /// debug uses.
@@ -134,7 +131,7 @@
   unsigned SrcReg, DstReg, SubIdx;
   if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
     return false;
- =20
+
   if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
       TargetRegisterInfo::isPhysicalRegister(SrcReg))
     return false;
@@ -240,6 +237,10 @@
       if (PHIBBs.count(UseMBB))
         continue;
=20
+      // About to add uses of DstReg, clear DstReg's kill flags.
+      if (!Changed)
+        MRI->clearKillFlags(DstReg);
+
       unsigned NewVR =3D MRI->createVirtualRegister(RC);
       BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
               TII->get(TargetOpcode::COPY), NewVR)
@@ -292,7 +293,7 @@
   assert(Def && Src && "Malformed bitcast instruction!");
=20
   MachineInstr *DefMI =3D MRI->getVRegDef(Src);
-  if (!DefMI || !DefMI->getDesc().isBitcast())
+  if (!DefMI || !DefMI->isBitcast())
     return false;
=20
   unsigned SrcSrc =3D 0;
@@ -353,7 +354,7 @@
                                         SmallSet<unsigned, 4> &ImmDefRegs,
                                  DenseMap<unsigned, MachineInstr*> &ImmDef=
MIs) {
   const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.isMoveImmediate())
+  if (!MI->isMoveImmediate())
     return false;
   if (MCID.getNumDefs() !=3D 1)
     return false;
@@ -363,7 +364,7 @@
     ImmDefRegs.insert(Reg);
     return true;
   }
- =20
+
   return false;
 }
=20
@@ -395,7 +396,7 @@
 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
   if (DisablePeephole)
     return false;
- =20
+
   TM  =3D &MF.getTarget();
   TII =3D TM->getInstrInfo();
   MRI =3D &MF.getRegInfo();
@@ -408,7 +409,7 @@
   DenseMap<unsigned, MachineInstr*> ImmDefMIs;
   for (MachineFunction::iterator I =3D MF.begin(), E =3D MF.end(); I !=3D =
E; ++I) {
     MachineBasicBlock *MBB =3D &*I;
-   =20
+
     bool SeenMoveImm =3D false;
     LocalMIs.clear();
     ImmDefRegs.clear();
@@ -428,17 +429,15 @@
         continue;
       }
=20
-      const MCInstrDesc &MCID =3D MI->getDesc();
-
-      if (MCID.isBitcast()) {
+      if (MI->isBitcast()) {
         if (OptimizeBitcastInstr(MI, MBB)) {
           // MI is deleted.
           LocalMIs.erase(MI);
           Changed =3D true;
           MII =3D First ? I->begin() : llvm::next(PMII);
           continue;
-        }       =20
-      } else if (MCID.isCompare()) {
+        }
+      } else if (MI->isCompare()) {
         if (OptimizeCmpInstr(MI, MBB)) {
           // MI is deleted.
           LocalMIs.erase(MI);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/PostRASc=
hedulerList.cpp
--- a/head/contrib/llvm/lib/CodeGen/PostRASchedulerList.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/PostRASchedulerList.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -23,7 +23,6 @@
 #include "AggressiveAntiDepBreaker.h"
 #include "CriticalAntiDepBreaker.h"
 #include "RegisterClassInfo.h"
-#include "ScheduleDAGInstrs.h"
 #include "llvm/CodeGen/Passes.h"
 #include "llvm/CodeGen/LatencyPriorityQueue.h"
 #include "llvm/CodeGen/SchedulerRegistry.h"
@@ -32,6 +31,7 @@
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineLoopInfo.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
+#include "llvm/CodeGen/ScheduleDAGInstrs.h"
 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Target/TargetLowering.h"
@@ -45,7 +45,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/Statistic.h"
-#include <set>
 using namespace llvm;
=20
 STATISTIC(NumNoops, "Number of noops inserted");
@@ -82,16 +81,15 @@
     AliasAnalysis *AA;
     const TargetInstrInfo *TII;
     RegisterClassInfo RegClassInfo;
-    CodeGenOpt::Level OptLevel;
=20
   public:
     static char ID;
-    PostRAScheduler(CodeGenOpt::Level ol) :
-      MachineFunctionPass(ID), OptLevel(ol) {}
+    PostRAScheduler() : MachineFunctionPass(ID) {}
=20
     void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
       AU.addRequired<AliasAnalysis>();
+      AU.addRequired<TargetPassConfig>();
       AU.addRequired<MachineDominatorTree>();
       AU.addPreserved<MachineDominatorTree>();
       AU.addRequired<MachineLoopInfo>();
@@ -99,10 +97,6 @@
       MachineFunctionPass::getAnalysisUsage(AU);
     }
=20
-    const char *getPassName() const {
-      return "Post RA top-down list latency scheduler";
-    }
-
     bool runOnMachineFunction(MachineFunction &Fn);
   };
   char PostRAScheduler::ID =3D 0;
@@ -130,36 +124,49 @@
     /// AA - AliasAnalysis for making memory reference queries.
     AliasAnalysis *AA;
=20
-    /// KillIndices - The index of the most recent kill (proceding bottom-=
up),
-    /// or ~0u if the register is not live.
-    std::vector<unsigned> KillIndices;
+    /// LiveRegs - true if the register is live.
+    BitVector LiveRegs;
+
+    /// The schedule. Null SUnit*'s represent noop instructions.
+    std::vector<SUnit*> Sequence;
=20
   public:
     SchedulePostRATDList(
       MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
       AliasAnalysis *AA, const RegisterClassInfo&,
       TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
-      SmallVectorImpl<TargetRegisterClass*> &CriticalPathRCs);
+      SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
=20
     ~SchedulePostRATDList();
=20
-    /// StartBlock - Initialize register live-range state for scheduling in
+    /// startBlock - Initialize register live-range state for scheduling in
     /// this block.
     ///
-    void StartBlock(MachineBasicBlock *BB);
+    void startBlock(MachineBasicBlock *BB);
+
+    /// Initialize the scheduler state for the next scheduling region.
+    virtual void enterRegion(MachineBasicBlock *bb,
+                             MachineBasicBlock::iterator begin,
+                             MachineBasicBlock::iterator end,
+                             unsigned endcount);
+
+    /// Notify that the scheduler has finished scheduling the current regi=
on.
+    virtual void exitRegion();
=20
     /// Schedule - Schedule the instruction range using list scheduling.
     ///
-    void Schedule();
+    void schedule();
+
+    void EmitSchedule();
=20
     /// Observe - Update liveness information to account for the current
     /// instruction, which will not be scheduled.
     ///
     void Observe(MachineInstr *MI, unsigned Count);
=20
-    /// FinishBlock - Clean up register live-range state.
+    /// finishBlock - Clean up register live-range state.
     ///
-    void FinishBlock();
+    void finishBlock();
=20
     /// FixupKills - Fix register kill flags that have been made
     /// invalid due to scheduling
@@ -177,16 +184,23 @@
     // adjustments may be made to the instruction if necessary. Return
     // true if the operand has been deleted, false if not.
     bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
+
+    void dumpSchedule() const;
   };
 }
=20
+char &llvm::PostRASchedulerID =3D PostRAScheduler::ID;
+
+INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
+                "Post RA top-down list latency scheduler", false, false)
+
 SchedulePostRATDList::SchedulePostRATDList(
   MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
   AliasAnalysis *AA, const RegisterClassInfo &RCI,
   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
-  SmallVectorImpl<TargetRegisterClass*> &CriticalPathRCs)
-  : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits), AA(AA),
-    KillIndices(TRI->getNumRegs())
+  SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs)
+  : ScheduleDAGInstrs(MF, MLI, MDT, /*IsPostRA=3D*/true), Topo(SUnits), AA=
(AA),
+    LiveRegs(TRI->getNumRegs())
 {
   const TargetMachine &TM =3D MF.getTarget();
   const InstrItineraryData *InstrItins =3D TM.getInstrItineraryData();
@@ -204,16 +218,48 @@
   delete AntiDepBreak;
 }
=20
+/// Initialize state associated with the next scheduling region.
+void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
+                 MachineBasicBlock::iterator begin,
+                 MachineBasicBlock::iterator end,
+                 unsigned endcount) {
+  ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
+  Sequence.clear();
+}
+
+/// Print the schedule before exiting the region.
+void SchedulePostRATDList::exitRegion() {
+  DEBUG({
+      dbgs() << "*** Final schedule ***\n";
+      dumpSchedule();
+      dbgs() << '\n';
+    });
+  ScheduleDAGInstrs::exitRegion();
+}
+
+/// dumpSchedule - dump the scheduled Sequence.
+void SchedulePostRATDList::dumpSchedule() const {
+  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; i++) {
+    if (SUnit *SU =3D Sequence[i])
+      SU->dump(this);
+    else
+      dbgs() << "**** NOOP ****\n";
+  }
+}
+
 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
   TII =3D Fn.getTarget().getInstrInfo();
   MachineLoopInfo &MLI =3D getAnalysis<MachineLoopInfo>();
   MachineDominatorTree &MDT =3D getAnalysis<MachineDominatorTree>();
   AliasAnalysis *AA =3D &getAnalysis<AliasAnalysis>();
+  TargetPassConfig *PassConfig =3D &getAnalysis<TargetPassConfig>();
+
   RegClassInfo.runOnMachineFunction(Fn);
=20
   // Check for explicit enable/disable of post-ra scheduling.
-  TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =3D TargetSubtargetInf=
o::ANTIDEP_NONE;
-  SmallVector<TargetRegisterClass*, 4> CriticalPathRCs;
+  TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =3D
+    TargetSubtargetInfo::ANTIDEP_NONE;
+  SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
   if (EnablePostRAScheduler.getPosition() > 0) {
     if (!EnablePostRAScheduler)
       return false;
@@ -221,7 +267,8 @@
     // Check that post-RA scheduling is enabled for this target.
     // This may upgrade the AntiDepMode.
     const TargetSubtargetInfo &ST =3D Fn.getTarget().getSubtarget<TargetSu=
btargetInfo>();
-    if (!ST.enablePostRAScheduler(OptLevel, AntiDepMode, CriticalPathRCs))
+    if (!ST.enablePostRAScheduler(PassConfig->getOptLevel(), AntiDepMode,
+                                  CriticalPathRCs))
       return false;
   }
=20
@@ -248,13 +295,13 @@
       static int bbcnt =3D 0;
       if (bbcnt++ % DebugDiv !=3D DebugMod)
         continue;
-      dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() =
<<
-        ":BB#" << MBB->getNumber() << " ***\n";
+      dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getName()
+             << ":BB#" << MBB->getNumber() << " ***\n";
     }
 #endif
=20
     // Initialize register live-range state for scheduling in this block.
-    Scheduler.StartBlock(MBB);
+    Scheduler.startBlock(MBB);
=20
     // Schedule each sequence of instructions not interrupted by a label
     // or anything else that effectively needs to shut down scheduling.
@@ -262,8 +309,13 @@
     unsigned Count =3D MBB->size(), CurrentCount =3D Count;
     for (MachineBasicBlock::iterator I =3D Current; I !=3D MBB->begin(); )=
 {
       MachineInstr *MI =3D llvm::prior(I);
-      if (TII->isSchedulingBoundary(MI, MBB, Fn)) {
-        Scheduler.Run(MBB, I, Current, CurrentCount);
+      // Calls are not scheduling boundaries before register allocation, b=
ut
+      // post-ra we don't gain anything by scheduling across calls since we
+      // don't need to worry about register pressure.
+      if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
+        Scheduler.enterRegion(MBB, I, Current, CurrentCount);
+        Scheduler.schedule();
+        Scheduler.exitRegion();
         Scheduler.EmitSchedule();
         Current =3D MI;
         CurrentCount =3D Count - 1;
@@ -271,15 +323,19 @@
       }
       I =3D MI;
       --Count;
+      if (MI->isBundle())
+        Count -=3D MI->getBundleSize();
     }
     assert(Count =3D=3D 0 && "Instruction count mismatch!");
     assert((MBB->begin() =3D=3D Current || CurrentCount !=3D 0) &&
            "Instruction count mismatch!");
-    Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
+    Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
+    Scheduler.schedule();
+    Scheduler.exitRegion();
     Scheduler.EmitSchedule();
=20
     // Clean up register live-range state.
-    Scheduler.FinishBlock();
+    Scheduler.finishBlock();
=20
     // Update register kills
     Scheduler.FixupKills(MBB);
@@ -291,9 +347,9 @@
 /// StartBlock - Initialize register live-range state for scheduling in
 /// this block.
 ///
-void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
+void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
   // Call the superclass.
-  ScheduleDAGInstrs::StartBlock(BB);
+  ScheduleDAGInstrs::startBlock(BB);
=20
   // Reset the hazard recognizer and anti-dep breaker.
   HazardRec->Reset();
@@ -303,14 +359,14 @@
=20
 /// Schedule - Schedule the instruction range using list scheduling.
 ///
-void SchedulePostRATDList::Schedule() {
+void SchedulePostRATDList::schedule() {
   // Build the scheduling graph.
-  BuildSchedGraph(AA);
+  buildSchedGraph(AA);
=20
   if (AntiDepBreak !=3D NULL) {
     unsigned Broken =3D
-      AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
-                                          InsertPosIndex, DbgValues);
+      AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
+                                          EndIndex, DbgValues);
=20
     if (Broken !=3D 0) {
       // We made changes. Update the dependency graph.
@@ -319,11 +375,8 @@
       // the def's anti-dependence *and* output-dependence edges due to
       // that register, and add new anti-dependence and output-dependence
       // edges based on the next live range of the register.
-      SUnits.clear();
-      Sequence.clear();
-      EntrySU =3D SUnit();
-      ExitSU =3D SUnit();
-      BuildSchedGraph(AA);
+      ScheduleDAG::clearDAG();
+      buildSchedGraph(AA);
=20
       NumFixedAnti +=3D Broken;
     }
@@ -343,38 +396,36 @@
 ///
 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
   if (AntiDepBreak !=3D NULL)
-    AntiDepBreak->Observe(MI, Count, InsertPosIndex);
+    AntiDepBreak->Observe(MI, Count, EndIndex);
 }
=20
 /// FinishBlock - Clean up register live-range state.
 ///
-void SchedulePostRATDList::FinishBlock() {
+void SchedulePostRATDList::finishBlock() {
   if (AntiDepBreak !=3D NULL)
     AntiDepBreak->FinishBlock();
=20
   // Call the superclass.
-  ScheduleDAGInstrs::FinishBlock();
+  ScheduleDAGInstrs::finishBlock();
 }
=20
 /// StartBlockForKills - Initialize register live-range state for updating=
 kills
 ///
 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
-  // Initialize the indices to indicate that no registers are live.
-  for (unsigned i =3D 0; i < TRI->getNumRegs(); ++i)
-    KillIndices[i] =3D ~0u;
+  // Start with no live registers.
+  LiveRegs.reset();
=20
   // Determine the live-out physregs for this block.
-  if (!BB->empty() && BB->back().getDesc().isReturn()) {
+  if (!BB->empty() && BB->back().isReturn()) {
     // In a return block, examine the function live-out regs.
     for (MachineRegisterInfo::liveout_iterator I =3D MRI.liveout_begin(),
            E =3D MRI.liveout_end(); I !=3D E; ++I) {
       unsigned Reg =3D *I;
-      KillIndices[Reg] =3D BB->size();
+      LiveRegs.set(Reg);
       // Repeat, for all subregs.
-      for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
-           *Subreg; ++Subreg) {
-        KillIndices[*Subreg] =3D BB->size();
-      }
+      for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
+           *Subreg; ++Subreg)
+        LiveRegs.set(*Subreg);
     }
   }
   else {
@@ -384,12 +435,11 @@
       for (MachineBasicBlock::livein_iterator I =3D (*SI)->livein_begin(),
              E =3D (*SI)->livein_end(); I !=3D E; ++I) {
         unsigned Reg =3D *I;
-        KillIndices[Reg] =3D BB->size();
+        LiveRegs.set(Reg);
         // Repeat, for all subregs.
-        for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
-             *Subreg; ++Subreg) {
-          KillIndices[*Subreg] =3D BB->size();
-        }
+        for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
+             *Subreg; ++Subreg)
+          LiveRegs.set(*Subreg);
       }
     }
   }
@@ -404,7 +454,7 @@
   }
=20
   // If MO itself is live, clear the kill flag...
-  if (KillIndices[MO.getReg()] !=3D ~0u) {
+  if (LiveRegs.test(MO.getReg())) {
     MO.setIsKill(false);
     return false;
   }
@@ -414,9 +464,9 @@
   MO.setIsKill(false);
   bool AllDead =3D true;
   const unsigned SuperReg =3D MO.getReg();
-  for (const unsigned *Subreg =3D TRI->getSubRegisters(SuperReg);
+  for (const uint16_t *Subreg =3D TRI->getSubRegisters(SuperReg);
        *Subreg; ++Subreg) {
-    if (KillIndices[*Subreg] !=3D ~0u) {
+    if (LiveRegs.test(*Subreg)) {
       MI->addOperand(MachineOperand::CreateReg(*Subreg,
                                                true  /*IsDef*/,
                                                true  /*IsImp*/,
@@ -437,7 +487,7 @@
 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
=20
-  std::set<unsigned> killedRegs;
+  BitVector killedRegs(TRI->getNumRegs());
   BitVector ReservedRegs =3D TRI->getReservedRegs(MF);
=20
   StartBlockForKills(MBB);
@@ -455,6 +505,8 @@
     // are completely defined.
     for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
       MachineOperand &MO =3D MI->getOperand(i);
+      if (MO.isRegMask())
+        LiveRegs.clearBitsNotInMask(MO.getRegMask());
       if (!MO.isReg()) continue;
       unsigned Reg =3D MO.getReg();
       if (Reg =3D=3D 0) continue;
@@ -462,19 +514,18 @@
       // Ignore two-addr defs.
       if (MI->isRegTiedToUseOperand(i)) continue;
=20
-      KillIndices[Reg] =3D ~0u;
+      LiveRegs.reset(Reg);
=20
       // Repeat for all subregs.
-      for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
-           *Subreg; ++Subreg) {
-        KillIndices[*Subreg] =3D ~0u;
-      }
+      for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
+           *Subreg; ++Subreg)
+        LiveRegs.reset(*Subreg);
     }
=20
     // Examine all used registers and set/clear kill flag. When a
     // register is used multiple times we only set the kill flag on
     // the first use.
-    killedRegs.clear();
+    killedRegs.reset();
     for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
       MachineOperand &MO =3D MI->getOperand(i);
       if (!MO.isReg() || !MO.isUse()) continue;
@@ -482,12 +533,12 @@
       if ((Reg =3D=3D 0) || ReservedRegs.test(Reg)) continue;
=20
       bool kill =3D false;
-      if (killedRegs.find(Reg) =3D=3D killedRegs.end()) {
+      if (!killedRegs.test(Reg)) {
         kill =3D true;
         // A register is not killed if any subregs are live...
-        for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+        for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
              *Subreg; ++Subreg) {
-          if (KillIndices[*Subreg] !=3D ~0u) {
+          if (LiveRegs.test(*Subreg)) {
             kill =3D false;
             break;
           }
@@ -496,7 +547,7 @@
         // If subreg is not live, then register is killed if it became
         // live in this instruction
         if (kill)
-          kill =3D (KillIndices[Reg] =3D=3D ~0u);
+          kill =3D !LiveRegs.test(Reg);
       }
=20
       if (MO.isKill() !=3D kill) {
@@ -506,7 +557,7 @@
         DEBUG(MI->dump());
       }
=20
-      killedRegs.insert(Reg);
+      killedRegs.set(Reg);
     }
=20
     // Mark any used register (that is not using undef) and subregs as
@@ -517,12 +568,11 @@
       unsigned Reg =3D MO.getReg();
       if ((Reg =3D=3D 0) || ReservedRegs.test(Reg)) continue;
=20
-      KillIndices[Reg] =3D Count;
+      LiveRegs.set(Reg);
=20
-      for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
-           *Subreg; ++Subreg) {
-        KillIndices[*Subreg] =3D Count;
-      }
+      for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
+           *Subreg; ++Subreg)
+        LiveRegs.set(*Subreg);
     }
   }
 }
@@ -585,7 +635,7 @@
=20
   ReleaseSuccessors(SU);
   SU->isScheduled =3D true;
-  AvailableQueue.ScheduledNode(SU);
+  AvailableQueue.scheduledNode(SU);
 }
=20
 /// ListScheduleTopDown - The main loop of list scheduling for top-down
@@ -699,14 +749,46 @@
   }
=20
 #ifndef NDEBUG
-  VerifySchedule(/*isBottomUp=3D*/false);
-#endif
+  unsigned ScheduledNodes =3D VerifyScheduledDAG(/*isBottomUp=3D*/false);
+  unsigned Noops =3D 0;
+  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; ++i)
+    if (!Sequence[i])
+      ++Noops;
+  assert(Sequence.size() - Noops =3D=3D ScheduledNodes &&
+         "The number of nodes scheduled doesn't match the expected number!=
");
+#endif // NDEBUG
 }
=20
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//                         Public Constructor Functions
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// EmitSchedule - Emit the machine code in scheduled order.
+void SchedulePostRATDList::EmitSchedule() {
+  RegionBegin =3D RegionEnd;
=20
-FunctionPass *llvm::createPostRAScheduler(CodeGenOpt::Level OptLevel) {
-  return new PostRAScheduler(OptLevel);
+  // If first instruction was a DBG_VALUE then put it back.
+  if (FirstDbgValue)
+    BB->splice(RegionEnd, BB, FirstDbgValue);
+
+  // Then re-insert them according to the given schedule.
+  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; i++) {
+    if (SUnit *SU =3D Sequence[i])
+      BB->splice(RegionEnd, BB, SU->getInstr());
+    else
+      // Null SUnit* is a noop.
+      TII->insertNoop(*BB, RegionEnd);
+
+    // Update the Begin iterator, as the first instruction in the block
+    // may have been scheduled later.
+    if (i =3D=3D 0)
+      RegionBegin =3D prior(RegionEnd);
+  }
+
+  // Reinsert any remaining debug_values.
+  for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
+         DI =3D DbgValues.end(), DE =3D DbgValues.begin(); DI !=3D DE; --D=
I) {
+    std::pair<MachineInstr *, MachineInstr *> P =3D *prior(DI);
+    MachineInstr *DbgValue =3D P.first;
+    MachineBasicBlock::iterator OrigPrivMI =3D P.second;
+    BB->splice(++OrigPrivMI, BB, DbgValue);
+  }
+  DbgValues.clear();
+  FirstDbgValue =3D NULL;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/ProcessI=
mplicitDefs.cpp
--- a/head/contrib/llvm/lib/CodeGen/ProcessImplicitDefs.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ProcessImplicitDefs.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -26,6 +26,8 @@
 using namespace llvm;
=20
 char ProcessImplicitDefs::ID =3D 0;
+char &llvm::ProcessImplicitDefsID =3D ProcessImplicitDefs::ID;
+
 INITIALIZE_PASS_BEGIN(ProcessImplicitDefs, "processimpdefs",
                 "Process Implicit Definitions", false, false)
 INITIALIZE_PASS_DEPENDENCY(LiveVariables)
@@ -36,7 +38,6 @@
   AU.setPreservesCFG();
   AU.addPreserved<AliasAnalysis>();
   AU.addPreserved<LiveVariables>();
-  AU.addRequired<LiveVariables>();
   AU.addPreservedID(MachineLoopInfoID);
   AU.addPreservedID(MachineDominatorsID);
   AU.addPreservedID(TwoAddressInstructionPassID);
@@ -50,10 +51,10 @@
                                             SmallSet<unsigned, 8> &ImpDefR=
egs) {
   switch(OpIdx) {
   case 1:
-    return MI->isCopy() && (MI->getOperand(0).getSubReg() =3D=3D 0 ||
+    return MI->isCopy() && (!MI->getOperand(0).readsReg() ||
                             ImpDefRegs.count(MI->getOperand(0).getReg()));
   case 2:
-    return MI->isSubregToReg() && (MI->getOperand(0).getSubReg() =3D=3D 0 =
||
+    return MI->isSubregToReg() && (!MI->getOperand(0).readsReg() ||
                                   ImpDefRegs.count(MI->getOperand(0).getRe=
g()));
   default: return false;
   }
@@ -66,7 +67,7 @@
     MachineOperand &MO1 =3D MI->getOperand(1);
     if (MO1.getReg() !=3D Reg)
       return false;
-    if (!MO0.getSubReg() || ImpDefRegs.count(MO0.getReg()))
+    if (!MO0.readsReg() || ImpDefRegs.count(MO0.getReg()))
       return true;
     return false;
   }
@@ -87,7 +88,7 @@
   TII =3D fn.getTarget().getInstrInfo();
   TRI =3D fn.getTarget().getRegisterInfo();
   MRI =3D &fn.getRegInfo();
-  LV =3D &getAnalysis<LiveVariables>();
+  LV =3D getAnalysisIfAvailable<LiveVariables>();
=20
   SmallSet<unsigned, 8> ImpDefRegs;
   SmallVector<MachineInstr*, 8> ImpDefMIs;
@@ -105,23 +106,24 @@
       MachineInstr *MI =3D &*I;
       ++I;
       if (MI->isImplicitDef()) {
-        if (MI->getOperand(0).getSubReg())
+        ImpDefMIs.push_back(MI);
+        // Is this a sub-register read-modify-write?
+        if (MI->getOperand(0).readsReg())
           continue;
         unsigned Reg =3D MI->getOperand(0).getReg();
         ImpDefRegs.insert(Reg);
         if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
-          for (const unsigned *SS =3D TRI->getSubRegisters(Reg); *SS; ++SS)
+          for (const uint16_t *SS =3D TRI->getSubRegisters(Reg); *SS; ++SS)
             ImpDefRegs.insert(*SS);
         }
-        ImpDefMIs.push_back(MI);
         continue;
       }
=20
       // Eliminate %reg1032:sub<def> =3D COPY undef.
-      if (MI->isCopy() && MI->getOperand(0).getSubReg()) {
+      if (MI->isCopy() && MI->getOperand(0).readsReg()) {
         MachineOperand &MO =3D MI->getOperand(1);
         if (MO.isUndef() || ImpDefRegs.count(MO.getReg())) {
-          if (MO.isKill()) {
+          if (LV && MO.isKill()) {
             LiveVariables::VarInfo& vi =3D LV->getVarInfo(MO.getReg());
             vi.removeKill(MI);
           }
@@ -140,7 +142,7 @@
       bool ChangedToImpDef =3D false;
       for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
         MachineOperand& MO =3D MI->getOperand(i);
-        if (!MO.isReg() || (MO.isDef() && !MO.getSubReg()) || MO.isUndef())
+        if (!MO.isReg() || !MO.readsReg())
           continue;
         unsigned Reg =3D MO.getReg();
         if (!Reg)
@@ -155,8 +157,10 @@
             MI->RemoveOperand(j);
           if (isKill) {
             ImpDefRegs.erase(Reg);
-            LiveVariables::VarInfo& vi =3D LV->getVarInfo(Reg);
-            vi.removeKill(MI);
+            if (LV) {
+              LiveVariables::VarInfo& vi =3D LV->getVarInfo(Reg);
+              vi.removeKill(MI);
+            }
           }
           ChangedToImpDef =3D true;
           Changed =3D true;
@@ -172,10 +176,10 @@
           continue;
         }
         if (MO.isKill() || MI->isRegTiedToDefOperand(i)) {
-          // Make sure other uses of=20
+          // Make sure other reads of Reg are also marked <undef>.
           for (unsigned j =3D i+1; j !=3D e; ++j) {
             MachineOperand &MOJ =3D MI->getOperand(j);
-            if (MOJ.isReg() && MOJ.isUse() && MOJ.getReg() =3D=3D Reg)
+            if (MOJ.isReg() && MOJ.getReg() =3D=3D Reg && MOJ.readsReg())
               MOJ.setIsUndef();
           }
           ImpDefRegs.erase(Reg);
@@ -265,7 +269,7 @@
           }
=20
           // Update LiveVariables varinfo if the instruction is a kill.
-          if (isKill) {
+          if (LV && isKill) {
             LiveVariables::VarInfo& vi =3D LV->getVarInfo(Reg);
             vi.removeKill(RMI);
           }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/PrologEp=
ilogInserter.cpp
--- a/head/contrib/llvm/lib/CodeGen/PrologEpilogInserter.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/PrologEpilogInserter.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -45,24 +45,22 @@
 using namespace llvm;
=20
 char PEI::ID =3D 0;
+char &llvm::PrologEpilogCodeInserterID =3D PEI::ID;
=20
 INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
                 "Prologue/Epilogue Insertion", false, false)
 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
+INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
 INITIALIZE_PASS_END(PEI, "prologepilog",
-                "Prologue/Epilogue Insertion", false, false)
+                    "Prologue/Epilogue Insertion & Frame Finalization",
+                    false, false)
=20
 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
 STATISTIC(NumBytesStackSpace,
           "Number of bytes used for stack in all functions");
=20
-/// createPrologEpilogCodeInserter - This function returns a pass that ins=
erts
-/// prolog and epilog code, and eliminates abstract frame references.
-///
-FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); }
-
 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
 /// frame indexes with appropriate references.
 ///
@@ -71,6 +69,8 @@
   const TargetRegisterInfo *TRI =3D Fn.getTarget().getRegisterInfo();
   const TargetFrameLowering *TFI =3D Fn.getTarget().getFrameLowering();
=20
+  assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vr=
egs");
+
   RS =3D TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
   FrameIndexVirtualScavenging =3D TRI->requiresFrameIndexScavenging(Fn);
=20
@@ -125,6 +125,9 @@
   if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
     scavengeFrameVirtualRegs(Fn);
=20
+  // Clear any vregs created by virtual scavenging.
+  Fn.getRegInfo().clearVirtRegs();
+
   delete RS;
   clearAllSets();
   return true;
@@ -207,7 +210,7 @@
   MachineFrameInfo *MFI =3D Fn.getFrameInfo();
=20
   // Get the callee saved register list...
-  const unsigned *CSRegs =3D RegInfo->getCalleeSavedRegs(&Fn);
+  const uint16_t *CSRegs =3D RegInfo->getCalleeSavedRegs(&Fn);
=20
   // These are used to keep track the callee-save area. Initialize them.
   MinCSFrameIndex =3D INT_MAX;
@@ -224,17 +227,9 @@
   std::vector<CalleeSavedInfo> CSI;
   for (unsigned i =3D 0; CSRegs[i]; ++i) {
     unsigned Reg =3D CSRegs[i];
-    if (Fn.getRegInfo().isPhysRegUsed(Reg)) {
+    if (Fn.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
       // If the reg is modified, save it!
       CSI.push_back(CalleeSavedInfo(Reg));
-    } else {
-      for (const unsigned *AliasSet =3D RegInfo->getAliasSet(Reg);
-           *AliasSet; ++AliasSet) {  // Check alias registers too.
-        if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) {
-          CSI.push_back(CalleeSavedInfo(Reg));
-          break;
-        }
-      }
     }
   }
=20
@@ -332,7 +327,7 @@
       // Skip over all terminator instructions, which are part of the retu=
rn
       // sequence.
       MachineBasicBlock::iterator I2 =3D I;
-      while (I2 !=3D MBB->begin() && (--I2)->getDesc().isTerminator())
+      while (I2 !=3D MBB->begin() && (--I2)->isTerminator())
         I =3D I2;
=20
       bool AtStart =3D I =3D=3D MBB->begin();
@@ -426,11 +421,11 @@
=20
       // Skip over all terminator instructions, which are part of the
       // return sequence.
-      if (! I->getDesc().isTerminator()) {
+      if (! I->isTerminator()) {
         ++I;
       } else {
         MachineBasicBlock::iterator I2 =3D I;
-        while (I2 !=3D MBB->begin() && (--I2)->getDesc().isTerminator())
+        while (I2 !=3D MBB->begin() && (--I2)->isTerminator())
           I =3D I2;
       }
     }
@@ -698,7 +693,7 @@
   // Add epilogue to restore the callee-save registers in each exiting blo=
ck
   for (MachineFunction::iterator I =3D Fn.begin(), E =3D Fn.end(); I !=3D =
E; ++I) {
     // If last instruction is a return instruction, add an epilogue
-    if (!I->empty() && I->back().getDesc().isReturn())
+    if (!I->empty() && I->back().isReturn())
       TFI.emitEpilogue(Fn, *I);
   }
=20
@@ -706,7 +701,7 @@
   // we've been asked for it.  This, when linked with a runtime with suppo=
rt
   // for segmented stacks (libgcc is one), will result in allocating stack
   // space in small chunks instead of one large contiguous block.
-  if (EnableSegmentedStacks)
+  if (Fn.getTarget().Options.EnableSegmentedStacks)
     TFI.adjustForSegmentedStacks(Fn);
 }
=20
@@ -813,6 +808,10 @@
 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
 /// with physical registers. Use the register scavenger to find an
 /// appropriate register to use.
+///
+/// FIXME: Iterating over the instruction stream is unnecessary. We can si=
mply
+/// iterate over the vreg use list, which at this point only contains mach=
ine
+/// operands for which eliminateFrameIndex need a new scratch reg.
 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
   // Run through the instructions and find any virtual registers.
   for (MachineFunction::iterator BB =3D Fn.begin(),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/PrologEp=
ilogInserter.h
--- a/head/contrib/llvm/lib/CodeGen/PrologEpilogInserter.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/PrologEpilogInserter.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -40,10 +40,6 @@
       initializePEIPass(*PassRegistry::getPassRegistry());
     }
=20
-    const char *getPassName() const {
-      return "Prolog/Epilog Insertion & Frame Finalization";
-    }
-
     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
=20
     /// runOnMachineFunction - Insert prolog/epilog code and replace abstr=
act
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/PseudoSo=
urceValue.cpp
--- a/head/contrib/llvm/lib/CodeGen/PseudoSourceValue.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/PseudoSourceValue.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -87,7 +87,6 @@
       this =3D=3D getJumpTable())
     return true;
   llvm_unreachable("Unknown PseudoSourceValue!");
-  return false;
 }
=20
 bool PseudoSourceValue::isAliased(const MachineFrameInfo *MFI) const {
@@ -97,7 +96,6 @@
       this =3D=3D getJumpTable())
     return false;
   llvm_unreachable("Unknown PseudoSourceValue!");
-  return true;
 }
=20
 bool PseudoSourceValue::mayAlias(const MachineFrameInfo *MFI) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/RegAlloc=
Base.h
--- a/head/contrib/llvm/lib/CodeGen/RegAllocBase.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegAllocBase.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -49,11 +49,6 @@
 class LiveIntervals;
 class Spiller;
=20
-// Forward declare a priority queue of live virtual registers. If an
-// implementation needs to prioritize by anything other than spill weight,=
 then
-// this will become an abstract base class with virtual calls to push/get.
-class LiveVirtRegQueue;
-
 /// RegAllocBase provides the register allocation driver and interface tha=
t can
 /// be extended to add interesting heuristics.
 ///
@@ -67,7 +62,6 @@
   // registers may have changed.
   unsigned UserTag;
=20
-protected:
   // Array of LiveIntervalUnions indexed by physical register.
   class LiveUnionArray {
     unsigned NumRegs;
@@ -88,16 +82,18 @@
     }
   };
=20
+  LiveUnionArray PhysReg2LiveUnion;
+
+  // Current queries, one per physreg. They must be reinitialized each tim=
e we
+  // query on a new live virtual register.
+  OwningArrayPtr<LiveIntervalUnion::Query> Queries;
+
+protected:
   const TargetRegisterInfo *TRI;
   MachineRegisterInfo *MRI;
   VirtRegMap *VRM;
   LiveIntervals *LIS;
   RegisterClassInfo RegClassInfo;
-  LiveUnionArray PhysReg2LiveUnion;
-
-  // Current queries, one per physreg. They must be reinitialized each tim=
e we
-  // query on a new live virtual register.
-  OwningArrayPtr<LiveIntervalUnion::Query> Queries;
=20
   RegAllocBase(): UserTag(0), TRI(0), MRI(0), VRM(0), LIS(0) {}
=20
@@ -115,16 +111,17 @@
     return Queries[PhysReg];
   }
=20
+  // Get direct access to the underlying LiveIntervalUnion for PhysReg.
+  LiveIntervalUnion &getLiveUnion(unsigned PhysReg) {
+    return PhysReg2LiveUnion[PhysReg];
+  }
+
   // Invalidate all cached information about virtual registers - live rang=
es may
   // have changed.
   void invalidateVirtRegs() { ++UserTag; }
=20
   // The top-level driver. The output is a VirtRegMap that us updated with
   // physical register assignments.
-  //
-  // If an implementation wants to override the LiveInterval comparator, we
-  // should modify this interface to allow passing in an instance derived =
from
-  // LiveVirtRegQueue.
   void allocatePhysRegs();
=20
   // Get a temporary reference to a Spiller instance.
@@ -160,12 +157,6 @@
   /// allocation is making progress.
   void unassign(LiveInterval &VirtReg, unsigned PhysReg);
=20
-  // Helper for spilling all live virtual registers currently unified unde=
r preg
-  // that interfere with the most recently queried lvr.  Return true if sp=
illing
-  // was successful, and append any new spilled/split intervals to splitLV=
Rs.
-  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
-                          SmallVectorImpl<LiveInterval*> &SplitVRegs);
-
   /// addMBBLiveIns - Add physreg liveins to basic blocks.
   void addMBBLiveIns(MachineFunction *);
=20
@@ -183,9 +174,6 @@
=20
 private:
   void seedLiveRegs();
-
-  void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
-                SmallVectorImpl<LiveInterval*> &SplitVRegs);
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/RegAlloc=
Basic.cpp
--- a/head/contrib/llvm/lib/CodeGen/RegAllocBasic.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegAllocBasic.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- RegAllocBasic.cpp - basic register allocator ---------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- RegAllocBasic.cpp - Basic Register Allocator ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,18 +15,15 @@
 #define DEBUG_TYPE "regalloc"
 #include "RegAllocBase.h"
 #include "LiveDebugVariables.h"
-#include "LiveIntervalUnion.h"
-#include "LiveRangeEdit.h"
 #include "RenderMachineFunction.h"
 #include "Spiller.h"
 #include "VirtRegMap.h"
-#include "llvm/ADT/OwningPtr.h"
-#include "llvm/ADT/Statistic.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Function.h"
 #include "llvm/PassAnalysisSupport.h"
 #include "llvm/CodeGen/CalcSpillWeights.h"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "llvm/CodeGen/LiveRangeEdit.h"
 #include "llvm/CodeGen/LiveStackAnalysis.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineInstr.h"
@@ -37,35 +34,17 @@
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Target/TargetRegisterInfo.h"
-#ifndef NDEBUG
-#include "llvm/ADT/SparseBitVector.h"
-#endif
 #include "llvm/Support/Debug.h"
-#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/Timer.h"
=20
 #include <cstdlib>
 #include <queue>
=20
 using namespace llvm;
=20
-STATISTIC(NumAssigned     , "Number of registers assigned");
-STATISTIC(NumUnassigned   , "Number of registers unassigned");
-STATISTIC(NumNewQueued    , "Number of new live ranges queued");
-
 static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator",
                                       createBasicRegisterAllocator);
=20
-// Temporary verification option until we can put verification inside
-// MachineVerifier.
-static cl::opt<bool, true>
-VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled=
),
-               cl::desc("Verify during register allocation"));
-
-const char *RegAllocBase::TimerGroupName =3D "Register Allocation";
-bool RegAllocBase::VerifyEnabled =3D false;
-
 namespace {
   struct CompSpillWeight {
     bool operator()(LiveInterval *A, LiveInterval *B) const {
@@ -93,6 +72,11 @@
   std::auto_ptr<Spiller> SpillerInstance;
   std::priority_queue<LiveInterval*, std::vector<LiveInterval*>,
                       CompSpillWeight> Queue;
+
+  // Scratch space.  Allocated here to avoid repeated malloc calls in
+  // selectOrSplit().
+  BitVector UsableRegs;
+
 public:
   RABasic();
=20
@@ -128,6 +112,15 @@
   /// Perform register allocation.
   virtual bool runOnMachineFunction(MachineFunction &mf);
=20
+  // Helper for spilling all live virtual registers currently unified unde=
r preg
+  // that interfere with the most recently queried lvr.  Return true if sp=
illing
+  // was successful, and append any new spilled/split intervals to splitLV=
Rs.
+  bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
+                          SmallVectorImpl<LiveInterval*> &SplitVRegs);
+
+  void spillReg(LiveInterval &VirtReg, unsigned PhysReg,
+                SmallVectorImpl<LiveInterval*> &SplitVRegs);
+
   static char ID;
 };
=20
@@ -139,8 +132,8 @@
   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
-  initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
+  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
@@ -157,9 +150,6 @@
   AU.addPreserved<SlotIndexes>();
   AU.addRequired<LiveDebugVariables>();
   AU.addPreserved<LiveDebugVariables>();
-  if (StrongPHIElim)
-    AU.addRequiredID(StrongPHIEliminationID);
-  AU.addRequiredTransitiveID(RegisterCoalescerPassID);
   AU.addRequired<CalculateSpillWeights>();
   AU.addRequired<LiveStacks>();
   AU.addPreserved<LiveStacks>();
@@ -178,204 +168,10 @@
   RegAllocBase::releaseMemory();
 }
=20
-#ifndef NDEBUG
-// Verify each LiveIntervalUnion.
-void RegAllocBase::verify() {
-  LiveVirtRegBitSet VisitedVRegs;
-  OwningArrayPtr<LiveVirtRegBitSet>
-    unionVRegs(new LiveVirtRegBitSet[PhysReg2LiveUnion.numRegs()]);
-
-  // Verify disjoint unions.
-  for (unsigned PhysReg =3D 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++Ph=
ysReg) {
-    DEBUG(PhysReg2LiveUnion[PhysReg].print(dbgs(), TRI));
-    LiveVirtRegBitSet &VRegs =3D unionVRegs[PhysReg];
-    PhysReg2LiveUnion[PhysReg].verify(VRegs);
-    // Union + intersection test could be done efficiently in one pass, but
-    // don't add a method to SparseBitVector unless we really need it.
-    assert(!VisitedVRegs.intersects(VRegs) && "vreg in multiple unions");
-    VisitedVRegs |=3D VRegs;
-  }
-
-  // Verify vreg coverage.
-  for (LiveIntervals::iterator liItr =3D LIS->begin(), liEnd =3D LIS->end(=
);
-       liItr !=3D liEnd; ++liItr) {
-    unsigned reg =3D liItr->first;
-    if (TargetRegisterInfo::isPhysicalRegister(reg)) continue;
-    if (!VRM->hasPhys(reg)) continue; // spilled?
-    unsigned PhysReg =3D VRM->getPhys(reg);
-    if (!unionVRegs[PhysReg].test(reg)) {
-      dbgs() << "LiveVirtReg " << reg << " not in union " <<
-        TRI->getName(PhysReg) << "\n";
-      llvm_unreachable("unallocated live vreg");
-    }
-  }
-  // FIXME: I'm not sure how to verify spilled intervals.
-}
-#endif //!NDEBUG
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//                         RegAllocBase Implementation
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-// Instantiate a LiveIntervalUnion for each physical register.
-void RegAllocBase::LiveUnionArray::init(LiveIntervalUnion::Allocator &allo=
cator,
-                                        unsigned NRegs) {
-  NumRegs =3D NRegs;
-  Array =3D
-    static_cast<LiveIntervalUnion*>(malloc(sizeof(LiveIntervalUnion)*NRegs=
));
-  for (unsigned r =3D 0; r !=3D NRegs; ++r)
-    new(Array + r) LiveIntervalUnion(r, allocator);
-}
-
-void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis) {
-  NamedRegionTimer T("Initialize", TimerGroupName, TimePassesIsEnabled);
-  TRI =3D &vrm.getTargetRegInfo();
-  MRI =3D &vrm.getRegInfo();
-  VRM =3D &vrm;
-  LIS =3D &lis;
-  RegClassInfo.runOnMachineFunction(vrm.getMachineFunction());
-
-  const unsigned NumRegs =3D TRI->getNumRegs();
-  if (NumRegs !=3D PhysReg2LiveUnion.numRegs()) {
-    PhysReg2LiveUnion.init(UnionAllocator, NumRegs);
-    // Cache an interferece query for each physical reg
-    Queries.reset(new LiveIntervalUnion::Query[PhysReg2LiveUnion.numRegs()=
]);
-  }
-}
-
-void RegAllocBase::LiveUnionArray::clear() {
-  if (!Array)
-    return;
-  for (unsigned r =3D 0; r !=3D NumRegs; ++r)
-    Array[r].~LiveIntervalUnion();
-  free(Array);
-  NumRegs =3D  0;
-  Array =3D 0;
-}
-
-void RegAllocBase::releaseMemory() {
-  for (unsigned r =3D 0, e =3D PhysReg2LiveUnion.numRegs(); r !=3D e; ++r)
-    PhysReg2LiveUnion[r].clear();
-}
-
-// Visit all the live registers. If they are already assigned to a physical
-// register, unify them with the corresponding LiveIntervalUnion, otherwis=
e push
-// them on the priority queue for later assignment.
-void RegAllocBase::seedLiveRegs() {
-  NamedRegionTimer T("Seed Live Regs", TimerGroupName, TimePassesIsEnabled=
);
-  for (LiveIntervals::iterator I =3D LIS->begin(), E =3D LIS->end(); I !=
=3D E; ++I) {
-    unsigned RegNum =3D I->first;
-    LiveInterval &VirtReg =3D *I->second;
-    if (TargetRegisterInfo::isPhysicalRegister(RegNum))
-      PhysReg2LiveUnion[RegNum].unify(VirtReg);
-    else
-      enqueue(&VirtReg);
-  }
-}
-
-void RegAllocBase::assign(LiveInterval &VirtReg, unsigned PhysReg) {
-  DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
-               << " to " << PrintReg(PhysReg, TRI) << '\n');
-  assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
-  VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
-  MRI->setPhysRegUsed(PhysReg);
-  PhysReg2LiveUnion[PhysReg].unify(VirtReg);
-  ++NumAssigned;
-}
-
-void RegAllocBase::unassign(LiveInterval &VirtReg, unsigned PhysReg) {
-  DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
-               << " from " << PrintReg(PhysReg, TRI) << '\n');
-  assert(VRM->getPhys(VirtReg.reg) =3D=3D PhysReg && "Inconsistent unassig=
n");
-  PhysReg2LiveUnion[PhysReg].extract(VirtReg);
-  VRM->clearVirt(VirtReg.reg);
-  ++NumUnassigned;
-}
-
-// Top-level driver to manage the queue of unassigned VirtRegs and call the
-// selectOrSplit implementation.
-void RegAllocBase::allocatePhysRegs() {
-  seedLiveRegs();
-
-  // Continue assigning vregs one at a time to available physical register=
s.
-  while (LiveInterval *VirtReg =3D dequeue()) {
-    assert(!VRM->hasPhys(VirtReg->reg) && "Register already assigned");
-
-    // Unused registers can appear when the spiller coalesces snippets.
-    if (MRI->reg_nodbg_empty(VirtReg->reg)) {
-      DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n');
-      LIS->removeInterval(VirtReg->reg);
-      continue;
-    }
-
-    // Invalidate all interference queries, live ranges could have changed.
-    invalidateVirtRegs();
-
-    // selectOrSplit requests the allocator to return an available physical
-    // register if possible and populate a list of new live intervals that
-    // result from splitting.
-    DEBUG(dbgs() << "\nselectOrSplit "
-                 << MRI->getRegClass(VirtReg->reg)->getName()
-                 << ':' << *VirtReg << '\n');
-    typedef SmallVector<LiveInterval*, 4> VirtRegVec;
-    VirtRegVec SplitVRegs;
-    unsigned AvailablePhysReg =3D selectOrSplit(*VirtReg, SplitVRegs);
-
-    if (AvailablePhysReg =3D=3D ~0u) {
-      // selectOrSplit failed to find a register!
-      const char *Msg =3D "ran out of registers during register allocation=
";
-      // Probably caused by an inline asm.
-      MachineInstr *MI;
-      for (MachineRegisterInfo::reg_iterator I =3D MRI->reg_begin(VirtReg-=
>reg);
-           (MI =3D I.skipInstruction());)
-        if (MI->isInlineAsm())
-          break;
-      if (MI)
-        MI->emitError(Msg);
-      else
-        report_fatal_error(Msg);
-      // Keep going after reporting the error.
-      VRM->assignVirt2Phys(VirtReg->reg,
-                 RegClassInfo.getOrder(MRI->getRegClass(VirtReg->reg)).fro=
nt());
-      continue;
-    }
-
-    if (AvailablePhysReg)
-      assign(*VirtReg, AvailablePhysReg);
-
-    for (VirtRegVec::iterator I =3D SplitVRegs.begin(), E =3D SplitVRegs.e=
nd();
-         I !=3D E; ++I) {
-      LiveInterval *SplitVirtReg =3D *I;
-      assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigne=
d");
-      if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) {
-        DEBUG(dbgs() << "not queueing unused  " << *SplitVirtReg << '\n');
-        LIS->removeInterval(SplitVirtReg->reg);
-        continue;
-      }
-      DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n");
-      assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) &&
-             "expect split value in virtual register");
-      enqueue(SplitVirtReg);
-      ++NumNewQueued;
-    }
-  }
-}
-
-// Check if this live virtual register interferes with a physical register=
. If
-// not, then check for interference on each register that aliases with the
-// physical register. Return the interfering register.
-unsigned RegAllocBase::checkPhysRegInterference(LiveInterval &VirtReg,
-                                                unsigned PhysReg) {
-  for (const unsigned *AliasI =3D TRI->getOverlaps(PhysReg); *AliasI; ++Al=
iasI)
-    if (query(VirtReg, *AliasI).checkInterference())
-      return *AliasI;
-  return 0;
-}
-
-// Helper for spillInteferences() that spills all interfering vregs curren=
tly
+// Helper for spillInterferences() that spills all interfering vregs curre=
ntly
 // assigned to this physical register.
-void RegAllocBase::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
-                            SmallVectorImpl<LiveInterval*> &SplitVRegs) {
+void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg,
+                       SmallVectorImpl<LiveInterval*> &SplitVRegs) {
   LiveIntervalUnion::Query &Q =3D query(VirtReg, PhysReg);
   assert(Q.seenAllInterferences() && "need collectInterferences()");
   const SmallVectorImpl<LiveInterval*> &PendingSpills =3D Q.interferingVRe=
gs();
@@ -391,7 +187,7 @@
     unassign(SpilledVReg, PhysReg);
=20
     // Spill the extracted interval.
-    LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills);
+    LiveRangeEdit LRE(SpilledVReg, SplitVRegs, *MF, *LIS, VRM);
     spiller().spill(LRE);
   }
   // After extracting segments, the query's results are invalid. But keep =
the
@@ -402,14 +198,13 @@
 // Spill or split all live virtual registers currently unified under PhysR=
eg
 // that interfere with VirtReg. The newly spilled or split live intervals =
are
 // returned by appending them to SplitVRegs.
-bool
-RegAllocBase::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
+bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg,
                                  SmallVectorImpl<LiveInterval*> &SplitVReg=
s) {
   // Record each interference and determine if all are spillable before mu=
tating
   // either the union or live intervals.
   unsigned NumInterferences =3D 0;
   // Collect interferences assigned to any alias of the physical register.
-  for (const unsigned *asI =3D TRI->getOverlaps(PhysReg); *asI; ++asI) {
+  for (const uint16_t *asI =3D TRI->getOverlaps(PhysReg); *asI; ++asI) {
     LiveIntervalUnion::Query &QAlias =3D query(VirtReg, *asI);
     NumInterferences +=3D QAlias.collectInterferingVRegs();
     if (QAlias.seenUnspillableVReg()) {
@@ -421,52 +216,11 @@
   assert(NumInterferences > 0 && "expect interference");
=20
   // Spill each interfering vreg allocated to PhysReg or an alias.
-  for (const unsigned *AliasI =3D TRI->getOverlaps(PhysReg); *AliasI; ++Al=
iasI)
+  for (const uint16_t *AliasI =3D TRI->getOverlaps(PhysReg); *AliasI; ++Al=
iasI)
     spillReg(VirtReg, *AliasI, SplitVRegs);
   return true;
 }
=20
-// Add newly allocated physical registers to the MBB live in sets.
-void RegAllocBase::addMBBLiveIns(MachineFunction *MF) {
-  NamedRegionTimer T("MBB Live Ins", TimerGroupName, TimePassesIsEnabled);
-  SlotIndexes *Indexes =3D LIS->getSlotIndexes();
-  if (MF->size() <=3D 1)
-    return;
-
-  LiveIntervalUnion::SegmentIter SI;
-  for (unsigned PhysReg =3D 0; PhysReg < PhysReg2LiveUnion.numRegs(); ++Ph=
ysReg) {
-    LiveIntervalUnion &LiveUnion =3D PhysReg2LiveUnion[PhysReg];
-    if (LiveUnion.empty())
-      continue;
-    DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " live-in:");
-    MachineFunction::iterator MBB =3D llvm::next(MF->begin());
-    MachineFunction::iterator MFE =3D MF->end();
-    SlotIndex Start, Stop;
-    tie(Start, Stop) =3D Indexes->getMBBRange(MBB);
-    SI.setMap(LiveUnion.getMap());
-    SI.find(Start);
-    while (SI.valid()) {
-      if (SI.start() <=3D Start) {
-        if (!MBB->isLiveIn(PhysReg))
-          MBB->addLiveIn(PhysReg);
-        DEBUG(dbgs() << "\tBB#" << MBB->getNumber() << ':'
-                     << PrintReg(SI.value()->reg, TRI));
-      } else if (SI.start() > Stop)
-        MBB =3D Indexes->getMBBFromIndex(SI.start().getPrevIndex());
-      if (++MBB =3D=3D MFE)
-        break;
-      tie(Start, Stop) =3D Indexes->getMBBRange(MBB);
-      SI.advanceTo(Start);
-    }
-    DEBUG(dbgs() << '\n');
-  }
-}
-
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//                         RABasic Implementation
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
 // Driver for the register assignment and splitting heuristics.
 // Manages iteration over the LiveIntervalUnions.
 //
@@ -481,6 +235,10 @@
 // selectOrSplit().
 unsigned RABasic::selectOrSplit(LiveInterval &VirtReg,
                                 SmallVectorImpl<LiveInterval*> &SplitVRegs=
) {
+  // Check for register mask interference.  When live ranges cross calls, =
the
+  // set of usable registers is reduced to the callee-saved ones.
+  bool CrossRegMasks =3D LIS->checkRegMaskInterference(VirtReg, UsableRegs=
);
+
   // Populate a list of physical register spill candidates.
   SmallVector<unsigned, 8> PhysRegSpillCands;
=20
@@ -491,6 +249,11 @@
        ++I) {
     unsigned PhysReg =3D *I;
=20
+    // If PhysReg is clobbered by a register mask, it isn't useful for
+    // allocation or spilling.
+    if (CrossRegMasks && !UsableRegs.test(PhysReg))
+      continue;
+
     // Check interference and as a side effect, intialize queries for this
     // VirtReg and its aliases.
     unsigned interfReg =3D checkPhysRegInterference(VirtReg, PhysReg);
@@ -498,9 +261,9 @@
       // Found an available register.
       return PhysReg;
     }
-    Queries[interfReg].collectInterferingVRegs(1);
-    LiveInterval *interferingVirtReg =3D
-      Queries[interfReg].interferingVRegs().front();
+    LiveIntervalUnion::Query &IntfQ =3D query(VirtReg, interfReg);
+    IntfQ.collectInterferingVRegs(1);
+    LiveInterval *interferingVirtReg =3D IntfQ.interferingVRegs().front();
=20
     // The current VirtReg must either be spillable, or one of its interfe=
rences
     // must have less spill weight.
@@ -524,7 +287,7 @@
   DEBUG(dbgs() << "spilling: " << VirtReg << '\n');
   if (!VirtReg.isSpillable())
     return ~0u;
-  LiveRangeEdit LRE(VirtReg, SplitVRegs);
+  LiveRangeEdit LRE(VirtReg, SplitVRegs, *MF, *LIS, VRM);
   spiller().spill(LRE);
=20
   // The live virtual register requesting allocation was spilled, so tell
@@ -579,7 +342,10 @@
   // Write out new DBG_VALUE instructions.
   getAnalysis<LiveDebugVariables>().emitDebugValues(VRM);
=20
-  // The pass output is in VirtRegMap. Release all the transient data.
+  // All machine operands and other references to virtual registers have b=
een
+  // replaced. Remove the virtual registers and release all the transient =
data.
+  VRM->clearAllVirt();
+  MRI->clearVirtRegs();
   releaseMemory();
=20
   return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/RegAlloc=
Fast.cpp
--- a/head/contrib/llvm/lib/CodeGen/RegAllocFast.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegAllocFast.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -32,6 +32,7 @@
 #include "llvm/ADT/IndexedMap.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SparseSet.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/STLExtras.h"
 #include <algorithm>
@@ -49,10 +50,7 @@
   public:
     static char ID;
     RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
-               isBulkSpilling(false) {
-      initializePHIEliminationPass(*PassRegistry::getPassRegistry());
-      initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegist=
ry());
-    }
+               isBulkSpilling(false) {}
   private:
     const TargetMachine *TM;
     MachineFunction *MF;
@@ -71,16 +69,20 @@
     // Everything we know about a live virtual register.
     struct LiveReg {
       MachineInstr *LastUse;    // Last instr to use reg.
+      unsigned VirtReg;         // Virtual register number.
       unsigned PhysReg;         // Currently held here.
       unsigned short LastOpNum; // OpNum on LastUse.
       bool Dirty;               // Register needs spill.
=20
-      LiveReg(unsigned p=3D0) : LastUse(0), PhysReg(p), LastOpNum(0),
-                              Dirty(false) {}
+      explicit LiveReg(unsigned v)
+        : LastUse(0), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false) {}
+
+      unsigned getSparseSetKey() const {
+        return TargetRegisterInfo::virtReg2Index(VirtReg);
+      }
     };
=20
-    typedef DenseMap<unsigned, LiveReg> LiveRegMap;
-    typedef LiveRegMap::value_type LiveRegEntry;
+    typedef SparseSet<LiveReg> LiveRegMap;
=20
     // LiveVirtRegs - This map contains entries for each virtual register
     // that is currently available in a physical register.
@@ -137,8 +139,6 @@
=20
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
-      AU.addRequiredID(PHIEliminationID);
-      AU.addRequiredID(TwoAddressInstructionPassID);
       MachineFunctionPass::getAnalysisUsage(AU);
     }
=20
@@ -159,14 +159,23 @@
     void usePhysReg(MachineOperand&);
     void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewSta=
te);
     unsigned calcSpillCost(unsigned PhysReg) const;
-    void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
-    void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
+    void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
+    LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
+      return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
+    }
+    LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
+      return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
+    }
+    LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysR=
eg);
+    LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterat=
or,
+                                      unsigned Hint);
     LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
                                        unsigned VirtReg, unsigned Hint);
     LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
                                        unsigned VirtReg, unsigned Hint);
     void spillAll(MachineInstr *MI);
     bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
+    void addRetOperands(MachineBasicBlock *MBB);
   };
   char RAFast::ID =3D 0;
 }
@@ -222,10 +231,10 @@
=20
 /// killVirtReg - Mark virtreg as no longer available.
 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
-  addKillFlag(LRI->second);
-  const LiveReg &LR =3D LRI->second;
-  assert(PhysRegState[LR.PhysReg] =3D=3D LRI->first && "Broken RegState ma=
pping");
-  PhysRegState[LR.PhysReg] =3D regFree;
+  addKillFlag(*LRI);
+  assert(PhysRegState[LRI->PhysReg] =3D=3D LRI->VirtReg &&
+         "Broken RegState mapping");
+  PhysRegState[LRI->PhysReg] =3D regFree;
   // Erase from LiveVirtRegs unless we're spilling in bulk.
   if (!isBulkSpilling)
     LiveVirtRegs.erase(LRI);
@@ -235,7 +244,7 @@
 void RAFast::killVirtReg(unsigned VirtReg) {
   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
          "killVirtReg needs a virtual register");
-  LiveRegMap::iterator LRI =3D LiveVirtRegs.find(VirtReg);
+  LiveRegMap::iterator LRI =3D findLiveVirtReg(VirtReg);
   if (LRI !=3D LiveVirtRegs.end())
     killVirtReg(LRI);
 }
@@ -245,7 +254,7 @@
 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg=
) {
   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
          "Spilling a physical register is illegal!");
-  LiveRegMap::iterator LRI =3D LiveVirtRegs.find(VirtReg);
+  LiveRegMap::iterator LRI =3D findLiveVirtReg(VirtReg);
   assert(LRI !=3D LiveVirtRegs.end() && "Spilling unmapped virtual registe=
r");
   spillVirtReg(MI, LRI);
 }
@@ -253,18 +262,18 @@
 /// spillVirtReg - Do the actual work of spilling.
 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
                           LiveRegMap::iterator LRI) {
-  LiveReg &LR =3D LRI->second;
-  assert(PhysRegState[LR.PhysReg] =3D=3D LRI->first && "Broken RegState ma=
pping");
+  LiveReg &LR =3D *LRI;
+  assert(PhysRegState[LR.PhysReg] =3D=3D LRI->VirtReg && "Broken RegState =
mapping");
=20
   if (LR.Dirty) {
     // If this physreg is used by the instruction, we want to kill it on t=
he
     // instruction, not on the spill.
     bool SpillKill =3D LR.LastUse !=3D MI;
     LR.Dirty =3D false;
-    DEBUG(dbgs() << "Spilling " << PrintReg(LRI->first, TRI)
+    DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
                  << " in " << PrintReg(LR.PhysReg, TRI));
-    const TargetRegisterClass *RC =3D MRI->getRegClass(LRI->first);
-    int FI =3D getStackSpaceFor(LRI->first, RC);
+    const TargetRegisterClass *RC =3D MRI->getRegClass(LRI->VirtReg);
+    int FI =3D getStackSpaceFor(LRI->VirtReg, RC);
     DEBUG(dbgs() << " to stack slot #" << FI << "\n");
     TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
     ++NumStores;   // Update statistics
@@ -272,7 +281,8 @@
     // If this register is used by DBG_VALUE then insert new DBG_VALUE to
     // identify spilled location as the place to find corresponding variab=
le's
     // value.
-    SmallVector<MachineInstr *, 4> &LRIDbgValues =3D LiveDbgValueMap[LRI->=
first];
+    SmallVector<MachineInstr *, 4> &LRIDbgValues =3D
+      LiveDbgValueMap[LRI->VirtReg];
     for (unsigned li =3D 0, le =3D LRIDbgValues.size(); li !=3D le; ++li) {
       MachineInstr *DBG =3D LRIDbgValues[li];
       const MDNode *MDPtr =3D
@@ -295,8 +305,9 @@
         DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *N=
ewDV);
       }
     }
-    // Now this register is spilled there is should not be any DBG_VALUE p=
ointing
-    // to this register because they are all pointing to spilled value now.
+    // Now this register is spilled there is should not be any DBG_VALUE
+    // pointing to this register because they are all pointing to spilled =
value
+    // now.
     LRIDbgValues.clear();
     if (SpillKill)
       LR.LastUse =3D 0; // Don't kill register again
@@ -343,7 +354,7 @@
   }
=20
   // Maybe a superregister is reserved?
-  for (const unsigned *AS =3D TRI->getAliasSet(PhysReg);
+  for (const uint16_t *AS =3D TRI->getAliasSet(PhysReg);
        unsigned Alias =3D *AS; ++AS) {
     switch (PhysRegState[Alias]) {
     case regDisabled:
@@ -397,7 +408,7 @@
=20
   // This is a disabled register, disable all aliases.
   PhysRegState[PhysReg] =3D NewState;
-  for (const unsigned *AS =3D TRI->getAliasSet(PhysReg);
+  for (const uint16_t *AS =3D TRI->getAliasSet(PhysReg);
        unsigned Alias =3D *AS; ++AS) {
     switch (unsigned VirtReg =3D PhysRegState[Alias]) {
     case regDisabled:
@@ -435,14 +446,17 @@
     DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
                  << PrintReg(PhysReg, TRI) << " is reserved already.\n");
     return spillImpossible;
-  default:
-    return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
+  default: {
+    LiveRegMap::const_iterator I =3D findLiveVirtReg(VirtReg);
+    assert(I !=3D LiveVirtRegs.end() && "Missing VirtReg entry");
+    return I->Dirty ? spillDirty : spillClean;
+  }
   }
=20
   // This is a disabled register, add up cost of aliases.
   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
   unsigned Cost =3D 0;
-  for (const unsigned *AS =3D TRI->getAliasSet(PhysReg);
+  for (const uint16_t *AS =3D TRI->getAliasSet(PhysReg);
        unsigned Alias =3D *AS; ++AS) {
     if (UsedInInstr.test(Alias))
       return spillImpossible;
@@ -454,10 +468,13 @@
       break;
     case regReserved:
       return spillImpossible;
-    default:
-      Cost +=3D LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillCle=
an;
+    default: {
+      LiveRegMap::const_iterator I =3D findLiveVirtReg(VirtReg);
+      assert(I !=3D LiveVirtRegs.end() && "Missing VirtReg entry");
+      Cost +=3D I->Dirty ? spillDirty : spillClean;
       break;
     }
+    }
   }
   return Cost;
 }
@@ -467,17 +484,27 @@
 /// that PhysReg is the proper container for VirtReg now.  The physical
 /// register must not be used for anything else when this is called.
 ///
-void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
-  DEBUG(dbgs() << "Assigning " << PrintReg(LRE.first, TRI) << " to "
+void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
+  DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
                << PrintReg(PhysReg, TRI) << "\n");
-  PhysRegState[PhysReg] =3D LRE.first;
-  assert(!LRE.second.PhysReg && "Already assigned a physreg");
-  LRE.second.PhysReg =3D PhysReg;
+  PhysRegState[PhysReg] =3D LR.VirtReg;
+  assert(!LR.PhysReg && "Already assigned a physreg");
+  LR.PhysReg =3D PhysReg;
+}
+
+RAFast::LiveRegMap::iterator
+RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
+  LiveRegMap::iterator LRI =3D findLiveVirtReg(VirtReg);
+  assert(LRI !=3D LiveVirtRegs.end() && "VirtReg disappeared");
+  assignVirtToPhysReg(*LRI, PhysReg);
+  return LRI;
 }
=20
 /// allocVirtReg - Allocate a physical register for VirtReg.
-void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hi=
nt) {
-  const unsigned VirtReg =3D LRE.first;
+RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
+                                                  LiveRegMap::iterator LRI,
+                                                  unsigned Hint) {
+  const unsigned VirtReg =3D LRI->VirtReg;
=20
   assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
          "Can only allocate virtual registers");
@@ -496,7 +523,9 @@
     if (Cost < spillDirty) {
       if (Cost)
         definePhysReg(MI, Hint, regFree);
-      return assignVirtToPhysReg(LRE, Hint);
+      // definePhysReg may kill virtual registers and modify LiveVirtRegs.
+      // That invalidates LRI, so run a new lookup for VirtReg.
+      return assignVirtToPhysReg(VirtReg, Hint);
     }
   }
=20
@@ -505,8 +534,10 @@
   // First try to find a completely free register.
   for (ArrayRef<unsigned>::iterator I =3D AO.begin(), E =3D AO.end(); I !=
=3D E; ++I) {
     unsigned PhysReg =3D *I;
-    if (PhysRegState[PhysReg] =3D=3D regFree && !UsedInInstr.test(PhysReg))
-      return assignVirtToPhysReg(LRE, PhysReg);
+    if (PhysRegState[PhysReg] =3D=3D regFree && !UsedInInstr.test(PhysReg)=
) {
+      assignVirtToPhysReg(*LRI, PhysReg);
+      return LRI;
+    }
   }
=20
   DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
@@ -519,21 +550,25 @@
     DEBUG(dbgs() << "\tCost: " << Cost << "\n");
     DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
     // Cost is 0 when all aliases are already disabled.
-    if (Cost =3D=3D 0)
-      return assignVirtToPhysReg(LRE, *I);
+    if (Cost =3D=3D 0) {
+      assignVirtToPhysReg(*LRI, *I);
+      return LRI;
+    }
     if (Cost < BestCost)
       BestReg =3D *I, BestCost =3D Cost;
   }
=20
   if (BestReg) {
     definePhysReg(MI, BestReg, regFree);
-    return assignVirtToPhysReg(LRE, BestReg);
+    // definePhysReg may kill virtual registers and modify LiveVirtRegs.
+    // That invalidates LRI, so run a new lookup for VirtReg.
+    return assignVirtToPhysReg(VirtReg, BestReg);
   }
=20
   // Nothing we can do. Report an error and keep going with a bad allocati=
on.
   MI->emitError("ran out of registers during register allocation");
   definePhysReg(MI, *AO.begin(), regFree);
-  assignVirtToPhysReg(LRE, *AO.begin());
+  return assignVirtToPhysReg(VirtReg, *AO.begin());
 }
=20
 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
@@ -544,8 +579,7 @@
          "Not a virtual register");
   LiveRegMap::iterator LRI;
   bool New;
-  tie(LRI, New) =3D LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg())=
);
-  LiveReg &LR =3D LRI->second;
+  tie(LRI, New) =3D LiveVirtRegs.insert(LiveReg(VirtReg));
   if (New) {
     // If there is no hint, peek at the only use of this register.
     if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
@@ -555,18 +589,18 @@
       if (UseMI.isCopyLike())
         Hint =3D UseMI.getOperand(0).getReg();
     }
-    allocVirtReg(MI, *LRI, Hint);
-  } else if (LR.LastUse) {
+    LRI =3D allocVirtReg(MI, LRI, Hint);
+  } else if (LRI->LastUse) {
     // Redefining a live register - kill at the last use, unless it is this
     // instruction defining VirtReg multiple times.
-    if (LR.LastUse !=3D MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
-      addKillFlag(LR);
+    if (LRI->LastUse !=3D MI || LRI->LastUse->getOperand(LRI->LastOpNum).i=
sUse())
+      addKillFlag(*LRI);
   }
-  assert(LR.PhysReg && "Register not assigned");
-  LR.LastUse =3D MI;
-  LR.LastOpNum =3D OpNum;
-  LR.Dirty =3D true;
-  UsedInInstr.set(LR.PhysReg);
+  assert(LRI->PhysReg && "Register not assigned");
+  LRI->LastUse =3D MI;
+  LRI->LastOpNum =3D OpNum;
+  LRI->Dirty =3D true;
+  UsedInInstr.set(LRI->PhysReg);
   return LRI;
 }
=20
@@ -578,18 +612,17 @@
          "Not a virtual register");
   LiveRegMap::iterator LRI;
   bool New;
-  tie(LRI, New) =3D LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg())=
);
-  LiveReg &LR =3D LRI->second;
+  tie(LRI, New) =3D LiveVirtRegs.insert(LiveReg(VirtReg));
   MachineOperand &MO =3D MI->getOperand(OpNum);
   if (New) {
-    allocVirtReg(MI, *LRI, Hint);
+    LRI =3D allocVirtReg(MI, LRI, Hint);
     const TargetRegisterClass *RC =3D MRI->getRegClass(VirtReg);
     int FrameIndex =3D getStackSpaceFor(VirtReg, RC);
     DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
-                 << PrintReg(LR.PhysReg, TRI) << "\n");
-    TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
+                 << PrintReg(LRI->PhysReg, TRI) << "\n");
+    TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
     ++NumLoads;
-  } else if (LR.Dirty) {
+  } else if (LRI->Dirty) {
     if (isLastUseOfLocalReg(MO)) {
       DEBUG(dbgs() << "Killing last use: " << MO << "\n");
       if (MO.isUse())
@@ -614,10 +647,10 @@
     DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
     MO.setIsDead(false);
   }
-  assert(LR.PhysReg && "Register not assigned");
-  LR.LastUse =3D MI;
-  LR.LastOpNum =3D OpNum;
-  UsedInInstr.set(LR.PhysReg);
+  assert(LRI->PhysReg && "Register not assigned");
+  LRI->LastUse =3D MI;
+  LRI->LastOpNum =3D OpNum;
+  UsedInInstr.set(LRI->PhysReg);
   return LRI;
 }
=20
@@ -674,7 +707,7 @@
     UsedInInstr.set(Reg);
     if (ThroughRegs.count(PhysRegState[Reg]))
       definePhysReg(MI, Reg, regFree);
-    for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS) {
+    for (const uint16_t *AS =3D TRI->getAliasSet(Reg); *AS; ++AS) {
       UsedInInstr.set(*AS);
       if (ThroughRegs.count(PhysRegState[*AS]))
         definePhysReg(MI, *AS, regFree);
@@ -682,7 +715,7 @@
   }
=20
   SmallVector<unsigned, 8> PartialDefs;
-  DEBUG(dbgs() << "Allocating tied uses and early clobbers.\n");
+  DEBUG(dbgs() << "Allocating tied uses.\n");
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
     MachineOperand &MO =3D MI->getOperand(i);
     if (!MO.isReg()) continue;
@@ -694,7 +727,7 @@
       DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand=
 "
         << DefIdx << ".\n");
       LiveRegMap::iterator LRI =3D reloadVirtReg(MI, i, Reg, 0);
-      unsigned PhysReg =3D LRI->second.PhysReg;
+      unsigned PhysReg =3D LRI->PhysReg;
       setPhysReg(MI, i, PhysReg);
       // Note: we don't update the def operand yet. That would cause the n=
ormal
       // def-scan to attempt spilling.
@@ -703,16 +736,25 @@
       // Reload the register, but don't assign to the operand just yet.
       // That would confuse the later phys-def processing pass.
       LiveRegMap::iterator LRI =3D reloadVirtReg(MI, i, Reg, 0);
-      PartialDefs.push_back(LRI->second.PhysReg);
-    } else if (MO.isEarlyClobber()) {
-      // Note: defineVirtReg may invalidate MO.
-      LiveRegMap::iterator LRI =3D defineVirtReg(MI, i, Reg, 0);
-      unsigned PhysReg =3D LRI->second.PhysReg;
-      if (setPhysReg(MI, i, PhysReg))
-        VirtDead.push_back(Reg);
+      PartialDefs.push_back(LRI->PhysReg);
     }
   }
=20
+  DEBUG(dbgs() << "Allocating early clobbers.\n");
+  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
+    MachineOperand &MO =3D MI->getOperand(i);
+    if (!MO.isReg()) continue;
+    unsigned Reg =3D MO.getReg();
+    if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
+    if (!MO.isEarlyClobber())
+      continue;
+    // Note: defineVirtReg may invalidate MO.
+    LiveRegMap::iterator LRI =3D defineVirtReg(MI, i, Reg, 0);
+    unsigned PhysReg =3D LRI->PhysReg;
+    if (setPhysReg(MI, i, PhysReg))
+      VirtDead.push_back(Reg);
+  }
+
   // Restore UsedInInstr to a state usable for allocating normal virtual u=
ses.
   UsedInInstr.reset();
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
@@ -730,32 +772,66 @@
     UsedInInstr.set(PartialDefs[i]);
 }
=20
+/// addRetOperand - ensure that a return instruction has an operand for ea=
ch
+/// value live out of the function.
+///
+/// Things marked both call and return are tail calls; do not do this for =
them.
+/// The tail callee need not take the same registers as input that it prod=
uces
+/// as output, and there are dependencies for its input registers elsewher=
e.
+///
+/// FIXME: This should be done as part of instruction selection, and this =
helper
+/// should be deleted. Until then, we use custom logic here to create the =
proper
+/// operand under all circumstances. We can't use addRegisterKilled becaus=
e that
+/// doesn't make sense for undefined values. We can't simply avoid calling=
 it
+/// for undefined values, because we must ensure that the operand always e=
xists.
+void RAFast::addRetOperands(MachineBasicBlock *MBB) {
+  if (MBB->empty() || !MBB->back().isReturn() || MBB->back().isCall())
+    return;
+
+  MachineInstr *MI =3D &MBB->back();
+
+  for (MachineRegisterInfo::liveout_iterator
+         I =3D MBB->getParent()->getRegInfo().liveout_begin(),
+         E =3D MBB->getParent()->getRegInfo().liveout_end(); I !=3D E; ++I=
) {
+    unsigned Reg =3D *I;
+    assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
+           "Cannot have a live-out virtual register.");
+
+    bool hasDef =3D PhysRegState[Reg] =3D=3D regReserved;
+
+    // Check if this register already has an operand.
+    bool Found =3D false;
+    for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
+      MachineOperand &MO =3D MI->getOperand(i);
+      if (!MO.isReg() || !MO.isUse())
+        continue;
+
+      unsigned OperReg =3D MO.getReg();
+      if (!TargetRegisterInfo::isPhysicalRegister(OperReg))
+        continue;
+
+      if (OperReg =3D=3D Reg || TRI->isSuperRegister(OperReg, Reg)) {
+        // If the ret already has an operand for this physreg or a superse=
t,
+        // don't duplicate it. Set the kill flag if the value is defined.
+        if (hasDef && !MO.isKill())
+          MO.setIsKill();
+        Found =3D true;
+        break;
+      }
+    }
+    if (!Found)
+      MI->addOperand(MachineOperand::CreateReg(Reg,
+                                               false /*IsDef*/,
+                                               true  /*IsImp*/,
+                                               hasDef/*IsKill*/));
+  }
+}
+
 void RAFast::AllocateBasicBlock() {
   DEBUG(dbgs() << "\nAllocating " << *MBB);
=20
-  // FIXME: This should probably be added by instruction selection instead?
-  // If the last instruction in the block is a return, make sure to mark i=
t as
-  // using all of the live-out values in the function.  Things marked both=
 call
-  // and return are tail calls; do not do this for them.  The tail callee =
need
-  // not take the same registers as input that it produces as output, and =
there
-  // are dependencies for its input registers elsewhere.
-  if (!MBB->empty() && MBB->back().getDesc().isReturn() &&
-      !MBB->back().getDesc().isCall()) {
-    MachineInstr *Ret =3D &MBB->back();
-
-    for (MachineRegisterInfo::liveout_iterator
-         I =3D MF->getRegInfo().liveout_begin(),
-         E =3D MF->getRegInfo().liveout_end(); I !=3D E; ++I) {
-      assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
-             "Cannot have a live-out virtual register.");
-
-      // Add live-out registers as implicit uses.
-      Ret->addRegisterKilled(*I, TRI, true);
-    }
-  }
-
   PhysRegState.assign(TRI->getNumRegs(), regDisabled);
-  assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
+  assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
=20
   MachineBasicBlock::iterator MII =3D MBB->begin();
=20
@@ -783,25 +859,26 @@
           case regReserved:
             dbgs() << "*";
             break;
-          default:
+          default: {
             dbgs() << '=3D' << PrintReg(PhysRegState[Reg]);
-            if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
+            LiveRegMap::iterator I =3D findLiveVirtReg(PhysRegState[Reg]);
+            assert(I !=3D LiveVirtRegs.end() && "Missing VirtReg entry");
+            if (I->Dirty)
               dbgs() << "*";
-            assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg =3D=3D Reg &&
-                   "Bad inverse map");
+            assert(I->PhysReg =3D=3D Reg && "Bad inverse map");
             break;
           }
+          }
         }
         dbgs() << '\n';
         // Check that LiveVirtRegs is the inverse.
         for (LiveRegMap::iterator i =3D LiveVirtRegs.begin(),
              e =3D LiveVirtRegs.end(); i !=3D e; ++i) {
-           assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
+           assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
                   "Bad map key");
-           assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg=
) &&
+           assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
                   "Bad map value");
-           assert(PhysRegState[i->second.PhysReg] =3D=3D i->first &&
-                  "Bad inverse map");
+           assert(PhysRegState[i->PhysReg] =3D=3D i->VirtReg && "Bad inver=
se map");
         }
       });
=20
@@ -815,10 +892,9 @@
           if (!MO.isReg()) continue;
           unsigned Reg =3D MO.getReg();
           if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
-          LiveDbgValueMap[Reg].push_back(MI);
-          LiveRegMap::iterator LRI =3D LiveVirtRegs.find(Reg);
+          LiveRegMap::iterator LRI =3D findLiveVirtReg(Reg);
           if (LRI !=3D LiveVirtRegs.end())
-            setPhysReg(MI, i, LRI->second.PhysReg);
+            setPhysReg(MI, i, LRI->PhysReg);
           else {
             int SS =3D StackSlotForVirtReg[Reg];
             if (SS =3D=3D -1) {
@@ -849,6 +925,7 @@
               }
             }
           }
+          LiveDbgValueMap[Reg].push_back(MI);
         }
       }
       // Next instruction.
@@ -932,7 +1009,7 @@
       if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
       if (MO.isUse()) {
         LiveRegMap::iterator LRI =3D reloadVirtReg(MI, i, Reg, CopyDst);
-        unsigned PhysReg =3D LRI->second.PhysReg;
+        unsigned PhysReg =3D LRI->PhysReg;
         CopySrc =3D (CopySrc =3D=3D Reg || CopySrc =3D=3D PhysReg) ? PhysR=
eg : 0;
         if (setPhysReg(MI, i, PhysReg))
           killVirtReg(LRI);
@@ -953,13 +1030,13 @@
         // Look for physreg defs and tied uses.
         if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
         UsedInInstr.set(Reg);
-        for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
+        for (const uint16_t *AS =3D TRI->getAliasSet(Reg); *AS; ++AS)
           UsedInInstr.set(*AS);
       }
     }
=20
     unsigned DefOpEnd =3D MI->getNumOperands();
-    if (MCID.isCall()) {
+    if (MI->isCall()) {
       // Spill all virtregs before a call. This serves two purposes: 1. If=
 an
       // exception is thrown, the landing pad is going to expect to find
       // registers in their spill slots, and 2. we don't have to wade thro=
ugh
@@ -988,7 +1065,7 @@
         continue;
       }
       LiveRegMap::iterator LRI =3D defineVirtReg(MI, i, Reg, CopySrc);
-      unsigned PhysReg =3D LRI->second.PhysReg;
+      unsigned PhysReg =3D LRI->PhysReg;
       if (setPhysReg(MI, i, PhysReg)) {
         VirtDead.push_back(Reg);
         CopyDst =3D 0; // cancel coalescing;
@@ -1024,6 +1101,9 @@
     MBB->erase(Coalesced[i]);
   NumCopies +=3D Coalesced.size();
=20
+  // addRetOperands must run after we've seen all defs in this block.
+  addRetOperands(MBB);
+
   DEBUG(MBB->dump());
 }
=20
@@ -1038,12 +1118,16 @@
   TM =3D &Fn.getTarget();
   TRI =3D TM->getRegisterInfo();
   TII =3D TM->getInstrInfo();
+  MRI->freezeReservedRegs(Fn);
   RegClassInfo.runOnMachineFunction(Fn);
   UsedInInstr.resize(TRI->getNumRegs());
=20
+  assert(!MRI->isSSA() && "regalloc requires leaving SSA");
+
   // initialize the virtual->physical register map to have a 'null'
   // mapping for all virtual registers
   StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
+  LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
=20
   // Loop over all of the basic blocks, eliminating virtual register refer=
ences
   for (MachineFunction::iterator MBBi =3D Fn.begin(), MBBe =3D Fn.end();
@@ -1052,16 +1136,17 @@
     AllocateBasicBlock();
   }
=20
-  // Make sure the set of used physregs is closed under subreg operations.
-  MRI->closePhysRegsUsed(*TRI);
-
   // Add the clobber lists for all the instructions we skipped earlier.
   for (SmallPtrSet<const MCInstrDesc*, 4>::const_iterator
        I =3D SkippedInstrs.begin(), E =3D SkippedInstrs.end(); I !=3D E; +=
+I)
-    if (const unsigned *Defs =3D (*I)->getImplicitDefs())
+    if (const uint16_t *Defs =3D (*I)->getImplicitDefs())
       while (*Defs)
         MRI->setPhysRegUsed(*Defs++);
=20
+  // All machine operands and other references to virtual registers have b=
een
+  // replaced. Remove the virtual registers.
+  MRI->clearVirtRegs();
+
   SkippedInstrs.clear();
   StackSlotForVirtReg.clear();
   LiveDbgValueMap.clear();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/RegAlloc=
Greedy.cpp
--- a/head/contrib/llvm/lib/CodeGen/RegAllocGreedy.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegAllocGreedy.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -16,7 +16,6 @@
 #include "AllocationOrder.h"
 #include "InterferenceCache.h"
 #include "LiveDebugVariables.h"
-#include "LiveRangeEdit.h"
 #include "RegAllocBase.h"
 #include "Spiller.h"
 #include "SpillPlacement.h"
@@ -29,6 +28,7 @@
 #include "llvm/CodeGen/CalcSpillWeights.h"
 #include "llvm/CodeGen/EdgeBundles.h"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "llvm/CodeGen/LiveRangeEdit.h"
 #include "llvm/CodeGen/LiveStackAnalysis.h"
 #include "llvm/CodeGen/MachineDominators.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
@@ -168,6 +168,19 @@
     }
   };
=20
+  // Register mask interference. The current VirtReg is checked for regist=
er
+  // mask interference on entry to selectOrSplit().  If there is no
+  // interference, UsableRegs is left empty.  If there is interference,
+  // UsableRegs has a bit mask of registers that can be used without regis=
ter
+  // mask interference.
+  BitVector UsableRegs;
+
+  /// clobberedByRegMask - Returns true if PhysReg is not directly usable
+  /// because of register mask clobbers.
+  bool clobberedByRegMask(unsigned PhysReg) const {
+    return !UsableRegs.empty() && !UsableRegs.test(PhysReg);
+  }
+
   // splitting state.
   std::auto_ptr<SplitAnalysis> SA;
   std::auto_ptr<SplitEditor> SE;
@@ -248,7 +261,6 @@
   static char ID;
=20
 private:
-  void LRE_WillEraseInstruction(MachineInstr*);
   bool LRE_CanEraseVirtReg(unsigned);
   void LRE_WillShrinkVirtReg(unsigned);
   void LRE_DidCloneVirtReg(unsigned, unsigned);
@@ -308,8 +320,8 @@
   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
-  initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
+  initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
@@ -328,9 +340,6 @@
   AU.addPreserved<SlotIndexes>();
   AU.addRequired<LiveDebugVariables>();
   AU.addPreserved<LiveDebugVariables>();
-  if (StrongPHIElim)
-    AU.addRequiredID(StrongPHIEliminationID);
-  AU.addRequiredTransitiveID(RegisterCoalescerPassID);
   AU.addRequired<CalculateSpillWeights>();
   AU.addRequired<LiveStacks>();
   AU.addPreserved<LiveStacks>();
@@ -350,11 +359,6 @@
 //                     LiveRangeEdit delegate methods
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-void RAGreedy::LRE_WillEraseInstruction(MachineInstr *MI) {
-  // LRE itself will remove from SlotIndexes and parent basic block.
-  VRM->RemoveMachineInstrFromMaps(MI);
-}
-
 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
   if (unsigned PhysReg =3D VRM->getPhys(VirtReg)) {
     unassign(LIS->getInterval(VirtReg), PhysReg);
@@ -424,13 +428,13 @@
       Prio |=3D (1u << 30);
   }
=20
-  Queue.push(std::make_pair(Prio, Reg));
+  Queue.push(std::make_pair(Prio, ~Reg));
 }
=20
 LiveInterval *RAGreedy::dequeue() {
   if (Queue.empty())
     return 0;
-  LiveInterval *LI =3D &LIS->getInterval(Queue.top().second);
+  LiveInterval *LI =3D &LIS->getInterval(~Queue.top().second);
   Queue.pop();
   return LI;
 }
@@ -446,9 +450,12 @@
                              SmallVectorImpl<LiveInterval*> &NewVRegs) {
   Order.rewind();
   unsigned PhysReg;
-  while ((PhysReg =3D Order.next()))
+  while ((PhysReg =3D Order.next())) {
+    if (clobberedByRegMask(PhysReg))
+      continue;
     if (!checkPhysRegInterference(VirtReg, PhysReg))
       break;
+  }
   if (!PhysReg || Order.isHint(PhysReg))
     return PhysReg;
=20
@@ -457,7 +464,7 @@
   // If we missed a simple hint, try to cheaply evict interference from the
   // preferred register.
   if (unsigned Hint =3D MRI->getSimpleHint(VirtReg.reg))
-    if (Order.isHint(Hint)) {
+    if (Order.isHint(Hint) && !clobberedByRegMask(Hint)) {
       DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
       EvictionCost MaxCost(1);
       if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
@@ -532,7 +539,7 @@
     Cascade =3D NextCascade;
=20
   EvictionCost Cost;
-  for (const unsigned *AliasI =3D TRI->getOverlaps(PhysReg); *AliasI; ++Al=
iasI) {
+  for (const uint16_t *AliasI =3D TRI->getOverlaps(PhysReg); *AliasI; ++Al=
iasI) {
     LiveIntervalUnion::Query &Q =3D query(VirtReg, *AliasI);
     // If there is 10 or more interferences, chances are one is heavier.
     if (Q.collectInterferingVRegs(10) >=3D 10)
@@ -590,7 +597,7 @@
=20
   DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
                << " interference: Cascade " << Cascade << '\n');
-  for (const unsigned *AliasI =3D TRI->getOverlaps(PhysReg); *AliasI; ++Al=
iasI) {
+  for (const uint16_t *AliasI =3D TRI->getOverlaps(PhysReg); *AliasI; ++Al=
iasI) {
     LiveIntervalUnion::Query &Q =3D query(VirtReg, *AliasI);
     assert(Q.seenAllInterferences() && "Didn't check all interfererences."=
);
     for (unsigned i =3D 0, e =3D Q.interferingVRegs().size(); i !=3D e; ++=
i) {
@@ -629,6 +636,8 @@
=20
   Order.rewind();
   while (unsigned PhysReg =3D Order.next()) {
+    if (clobberedByRegMask(PhysReg))
+      continue;
     if (TRI->getCostPerUse(PhysReg) >=3D CostPerUseLimit)
       continue;
     // The first use of a callee-saved register in a function has cost 1.
@@ -1118,6 +1127,8 @@
       }
       --NumCands;
       GlobalCand[Worst] =3D GlobalCand[NumCands];
+      if (BestCand =3D=3D NumCands)
+        BestCand =3D Worst;
     }
=20
     if (GlobalCand.size() <=3D NumCands)
@@ -1172,7 +1183,7 @@
     return 0;
=20
   // Prepare split editor.
-  LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
+  LiveRangeEdit LREdit(VirtReg, NewVRegs, *MF, *LIS, VRM, this);
   SE->reset(LREdit, SplitSpillMode);
=20
   // Assign all edge bundles to the preferred candidate, or NoCand.
@@ -1220,7 +1231,7 @@
   assert(&SA->getParent() =3D=3D &VirtReg && "Live range wasn't analyzed");
   unsigned Reg =3D VirtReg.reg;
   bool SingleInstrs =3D RegClassInfo.isProperSubClass(MRI->getRegClass(Reg=
));
-  LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
+  LiveRangeEdit LREdit(VirtReg, NewVRegs, *MF, *LIS, VRM, this);
   SE->reset(LREdit, SplitSpillMode);
   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks =3D SA->getUseBlocks();
   for (unsigned i =3D 0; i !=3D UseBlocks.size(); ++i) {
@@ -1268,7 +1279,7 @@
                               SmallVectorImpl<float> &GapWeight) {
   assert(SA->getUseBlocks().size() =3D=3D 1 && "Not a local interval");
   const SplitAnalysis::BlockInfo &BI =3D SA->getUseBlocks().front();
-  const SmallVectorImpl<SlotIndex> &Uses =3D SA->UseSlots;
+  ArrayRef<SlotIndex> Uses =3D SA->getUseSlots();
   const unsigned NumGaps =3D Uses.size()-1;
=20
   // Start and end points for the interference check.
@@ -1280,7 +1291,7 @@
   GapWeight.assign(NumGaps, 0.0f);
=20
   // Add interference from each overlapping register.
-  for (const unsigned *AI =3D TRI->getOverlaps(PhysReg); *AI; ++AI) {
+  for (const uint16_t *AI =3D TRI->getOverlaps(PhysReg); *AI; ++AI) {
     if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
            .checkInterference())
       continue;
@@ -1292,7 +1303,7 @@
     // surrounding the instruction. The exception is interference before
     // StartIdx and after StopIdx.
     //
-    LiveIntervalUnion::SegmentIter IntI =3D PhysReg2LiveUnion[*AI].find(St=
artIdx);
+    LiveIntervalUnion::SegmentIter IntI =3D getLiveUnion(*AI).find(StartId=
x);
     for (unsigned Gap =3D 0; IntI.valid() && IntI.start() < StopIdx; ++Int=
I) {
       // Skip the gaps before IntI.
       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
@@ -1329,7 +1340,7 @@
   // that the interval is continuous from FirstInstr to LastInstr. We shou=
ld
   // make sure that we don't do anything illegal to such an interval, thou=
gh.
=20
-  const SmallVectorImpl<SlotIndex> &Uses =3D SA->UseSlots;
+  ArrayRef<SlotIndex> Uses =3D SA->getUseSlots();
   if (Uses.size() <=3D 2)
     return 0;
   const unsigned NumGaps =3D Uses.size()-1;
@@ -1337,10 +1348,40 @@
   DEBUG({
     dbgs() << "tryLocalSplit: ";
     for (unsigned i =3D 0, e =3D Uses.size(); i !=3D e; ++i)
-      dbgs() << ' ' << SA->UseSlots[i];
+      dbgs() << ' ' << Uses[i];
     dbgs() << '\n';
   });
=20
+  // If VirtReg is live across any register mask operands, compute a list =
of
+  // gaps with register masks.
+  SmallVector<unsigned, 8> RegMaskGaps;
+  if (!UsableRegs.empty()) {
+    // Get regmask slots for the whole block.
+    ArrayRef<SlotIndex> RMS =3D LIS->getRegMaskSlotsInBlock(BI.MBB->getNum=
ber());
+    DEBUG(dbgs() << RMS.size() << " regmasks in block:");
+    // Constrain to VirtReg's live range.
+    unsigned ri =3D std::lower_bound(RMS.begin(), RMS.end(),
+                                   Uses.front().getRegSlot()) - RMS.begin(=
);
+    unsigned re =3D RMS.size();
+    for (unsigned i =3D 0; i !=3D NumGaps && ri !=3D re; ++i) {
+      // Look for Uses[i] <=3D RMS <=3D Uses[i+1].
+      assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
+      if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
+        continue;
+      // Skip a regmask on the same instruction as the last use. It doesn't
+      // overlap the live range.
+      if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 =3D=3D NumGaps)
+        break;
+      DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]=
);
+      RegMaskGaps.push_back(i);
+      // Advance ri to the next gap. A regmask on one of the uses counts in
+      // both gaps.
+      while (ri !=3D re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
+        ++ri;
+    }
+    DEBUG(dbgs() << '\n');
+  }
+
   // Since we allow local split results to be split again, there is a risk=
 of
   // creating infinite loops. It is tempting to require that the new live
   // ranges have less instructions than the original. That would guarantee
@@ -1375,6 +1416,11 @@
     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
     calcGapWeights(PhysReg, GapWeight);
=20
+    // Remove any gaps with regmask clobbers.
+    if (clobberedByRegMask(PhysReg))
+      for (unsigned i =3D 0, e =3D RegMaskGaps.size(); i !=3D e; ++i)
+        GapWeight[RegMaskGaps[i]] =3D HUGE_VALF;
+
     // Try to find the best sequence of gaps to close.
     // The new spill weight must be larger than any gap interference.
=20
@@ -1466,7 +1512,7 @@
                << '-' << Uses[BestAfter] << ", " << BestDiff
                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
=20
-  LiveRangeEdit LREdit(VirtReg, NewVRegs, this);
+  LiveRangeEdit LREdit(VirtReg, NewVRegs, *MF, *LIS, VRM, this);
   SE->reset(LREdit);
=20
   SE->openIntv();
@@ -1553,6 +1599,11 @@
=20
 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
                                  SmallVectorImpl<LiveInterval*> &NewVRegs)=
 {
+  // Check if VirtReg is live across any calls.
+  UsableRegs.clear();
+  if (LIS->checkRegMaskInterference(VirtReg, UsableRegs))
+    DEBUG(dbgs() << "Live across regmasks.\n");
+
   // First try assigning a free register.
   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
   if (unsigned PhysReg =3D tryAssign(VirtReg, Order, NewVRegs))
@@ -1593,7 +1644,7 @@
=20
   // Finally spill VirtReg itself.
   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
-  LiveRangeEdit LRE(VirtReg, NewVRegs, this);
+  LiveRangeEdit LRE(VirtReg, NewVRegs, *MF, *LIS, VRM, this);
   spiller().spill(LRE);
   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
=20
@@ -1628,7 +1679,7 @@
   ExtraRegInfo.clear();
   ExtraRegInfo.resize(MRI->getNumVirtRegs());
   NextCascade =3D 1;
-  IntfCache.init(MF, &PhysReg2LiveUnion[0], Indexes, TRI);
+  IntfCache.init(MF, &getLiveUnion(0), Indexes, LIS, TRI);
   GlobalCand.resize(32);  // This will grow as needed.
=20
   allocatePhysRegs();
@@ -1647,7 +1698,10 @@
     DebugVars->emitDebugValues(VRM);
   }
=20
-  // The pass output is in VirtRegMap. Release all the transient data.
+  // All machine operands and other references to virtual registers have b=
een
+  // replaced. Remove the virtual registers and release all the transient =
data.
+  VRM->clearAllVirt();
+  MRI->clearVirtRegs();
   releaseMemory();
=20
   return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/RegAlloc=
PBQP.cpp
--- a/head/contrib/llvm/lib/CodeGen/RegAllocPBQP.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegAllocPBQP.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -32,14 +32,17 @@
 #define DEBUG_TYPE "regalloc"
=20
 #include "RenderMachineFunction.h"
-#include "Splitter.h"
+#include "Spiller.h"
 #include "VirtRegMap.h"
-#include "VirtRegRewriter.h"
 #include "RegisterCoalescer.h"
+#include "llvm/Module.h"
+#include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/CodeGen/CalcSpillWeights.h"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "llvm/CodeGen/LiveRangeEdit.h"
 #include "llvm/CodeGen/LiveStackAnalysis.h"
 #include "llvm/CodeGen/RegAllocPBQP.h"
+#include "llvm/CodeGen/MachineDominators.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineLoopInfo.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
@@ -54,6 +57,7 @@
 #include <limits>
 #include <memory>
 #include <set>
+#include <sstream>
 #include <vector>
=20
 using namespace llvm;
@@ -67,10 +71,12 @@
                 cl::desc("Attempt coalescing during PBQP register allocati=
on."),
                 cl::init(false), cl::Hidden);
=20
+#ifndef NDEBUG
 static cl::opt<bool>
-pbqpPreSplitting("pbqp-pre-splitting",
-                 cl::desc("Pre-split before PBQP register allocation."),
-                 cl::init(false), cl::Hidden);
+pbqpDumpGraphs("pbqp-dump-graphs",
+               cl::desc("Dump graphs for each function/round in the compil=
ation unit."),
+               cl::init(false), cl::Hidden);
+#endif
=20
 namespace {
=20
@@ -88,11 +94,9 @@
       : MachineFunctionPass(ID), builder(b), customPassID(cPassID) {
     initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
     initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
-    initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
     initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
     initializeLiveStacksPass(*PassRegistry::getPassRegistry());
     initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
-    initializeLoopSplitterPass(*PassRegistry::getPassRegistry());
     initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
     initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry());
   }
@@ -132,6 +136,7 @@
   MachineRegisterInfo *mri;
   RenderMachineFunction *rmf;
=20
+  std::auto_ptr<Spiller> spiller;
   LiveIntervals *lis;
   LiveStacks *lss;
   VirtRegMap *vrm;
@@ -141,10 +146,6 @@
   /// \brief Finds the initial set of vreg intervals to allocate.
   void findVRegIntervalsToAlloc();
=20
-  /// \brief Adds a stack interval if the given live interval has been
-  /// spilled. Used to support stack slot coloring.
-  void addStackInterval(const LiveInterval *spilled,MachineRegisterInfo* m=
ri);
-
   /// \brief Given a solved PBQP problem maps this solution back to a regi=
ster
   /// assignment.
   bool mapPBQPToRegAlloc(const PBQPRAProblem &problem,
@@ -170,7 +171,7 @@
   VReg2Node::const_iterator nodeItr =3D vreg2Node.find(vreg);
   assert(nodeItr !=3D vreg2Node.end() && "No node for vreg.");
   return nodeItr->second;
- =20
+
 }
=20
 const PBQPRAProblem::AllowedSet&
@@ -195,9 +196,9 @@
                                                 const RegSet &vregs) {
=20
   typedef std::vector<const LiveInterval*> LIVector;
-
+  ArrayRef<SlotIndex> regMaskSlots =3D lis->getRegMaskSlots();
   MachineRegisterInfo *mri =3D &mf->getRegInfo();
-  const TargetRegisterInfo *tri =3D mf->getTarget().getRegisterInfo(); =20
+  const TargetRegisterInfo *tri =3D mf->getTarget().getRegisterInfo();
=20
   std::auto_ptr<PBQPRAProblem> p(new PBQPRAProblem());
   PBQP::Graph &g =3D p->getGraph();
@@ -214,7 +215,7 @@
=20
   BitVector reservedRegs =3D tri->getReservedRegs(*mf);
=20
-  // Iterate over vregs.=20
+  // Iterate over vregs.
   for (RegSet::const_iterator vregItr =3D vregs.begin(), vregEnd =3D vregs=
.end();
        vregItr !=3D vregEnd; ++vregItr) {
     unsigned vreg =3D *vregItr;
@@ -224,7 +225,7 @@
     // Compute an initial allowed set for the current vreg.
     typedef std::vector<unsigned> VRAllowed;
     VRAllowed vrAllowed;
-    ArrayRef<unsigned> rawOrder =3D trc->getRawAllocationOrder(*mf);
+    ArrayRef<uint16_t> rawOrder =3D trc->getRawAllocationOrder(*mf);
     for (unsigned i =3D 0; i !=3D rawOrder.size(); ++i) {
       unsigned preg =3D rawOrder[i];
       if (!reservedRegs.test(preg)) {
@@ -232,7 +233,9 @@
       }
     }
=20
-    // Remove any physical registers which overlap.
+    RegSet overlappingPRegs;
+
+    // Record physical registers whose ranges overlap.
     for (RegSet::const_iterator pregItr =3D pregs.begin(),
                                 pregEnd =3D pregs.end();
          pregItr !=3D pregEnd; ++pregItr) {
@@ -243,9 +246,41 @@
         continue;
       }
=20
-      if (!vregLI->overlaps(*pregLI)) {
-        continue;
+      if (vregLI->overlaps(*pregLI))
+        overlappingPRegs.insert(preg);     =20
+    }
+
+    // Record any overlaps with regmask operands.
+    BitVector regMaskOverlaps(tri->getNumRegs());
+    for (ArrayRef<SlotIndex>::iterator rmItr =3D regMaskSlots.begin(),
+                                       rmEnd =3D regMaskSlots.end();
+         rmItr !=3D rmEnd; ++rmItr) {
+      SlotIndex rmIdx =3D *rmItr;
+      if (vregLI->liveAt(rmIdx)) {
+        MachineInstr *rmMI =3D lis->getInstructionFromIndex(rmIdx);
+        const uint32_t* regMask =3D 0;
+        for (MachineInstr::mop_iterator mopItr =3D rmMI->operands_begin(),
+                                        mopEnd =3D rmMI->operands_end();
+             mopItr !=3D mopEnd; ++mopItr) {
+          if (mopItr->isRegMask()) {
+            regMask =3D mopItr->getRegMask();
+            break;
+          }
+        }
+        assert(regMask !=3D 0 && "Couldn't find register mask.");
+        regMaskOverlaps.setBitsNotInMask(regMask);
       }
+    }
+
+    for (unsigned preg =3D 0; preg < tri->getNumRegs(); ++preg) {
+      if (regMaskOverlaps.test(preg))
+        overlappingPRegs.insert(preg);
+    }
+
+    for (RegSet::const_iterator pregItr =3D overlappingPRegs.begin(),
+                                pregEnd =3D overlappingPRegs.end();
+         pregItr !=3D pregEnd; ++pregItr) {
+      unsigned preg =3D *pregItr;
=20
       // Remove the register from the allowed set.
       VRAllowed::iterator eraseItr =3D
@@ -256,7 +291,7 @@
       }
=20
       // Also remove any aliases.
-      const unsigned *aliasItr =3D tri->getAliasSet(preg);
+      const uint16_t *aliasItr =3D tri->getAliasSet(preg);
       if (aliasItr !=3D 0) {
         for (; *aliasItr !=3D 0; ++aliasItr) {
           VRAllowed::iterator eraseItr =3D
@@ -270,7 +305,7 @@
     }
=20
     // Construct the node.
-    PBQP::Graph::NodeItr node =3D=20
+    PBQP::Graph::NodeItr node =3D
       g.addNode(PBQP::Vector(vrAllowed.size() + 1, 0));
=20
     // Record the mapping and allowed set in the problem.
@@ -371,7 +406,7 @@
=20
       const float copyFactor =3D 0.5; // Cost of copy relative to load. Cu=
rrent
       // value plucked randomly out of the air.
-                                     =20
+
       PBQP::PBQPNum cBenefit =3D
         copyFactor * LiveIntervals::getSpillWeight(false, true,
                                                    loopInfo->getLoopDepth(=
mbb));
@@ -382,7 +417,7 @@
         }
=20
         const PBQPRAProblem::AllowedSet &allowed =3D p->getAllowedSet(src);
-        unsigned pregOpt =3D 0; =20
+        unsigned pregOpt =3D 0;
         while (pregOpt < allowed.size() && allowed[pregOpt] !=3D dst) {
           ++pregOpt;
         }
@@ -407,7 +442,7 @@
             std::swap(allowed1, allowed2);
           }
         }
-           =20
+
         addVirtRegCoalesce(g.getEdgeCosts(edge), *allowed1, *allowed2,
                            cBenefit);
       }
@@ -439,27 +474,29 @@
=20
       if (preg1 =3D=3D preg2) {
         costMat[i + 1][j + 1] +=3D -benefit;
-      }=20
+      }
     }
   }
 }
=20
=20
 void RegAllocPBQP::getAnalysisUsage(AnalysisUsage &au) const {
+  au.setPreservesCFG();
+  au.addRequired<AliasAnalysis>();
+  au.addPreserved<AliasAnalysis>();
   au.addRequired<SlotIndexes>();
   au.addPreserved<SlotIndexes>();
   au.addRequired<LiveIntervals>();
   //au.addRequiredID(SplitCriticalEdgesID);
-  au.addRequiredID(RegisterCoalescerPassID);
   if (customPassID)
     au.addRequiredID(*customPassID);
   au.addRequired<CalculateSpillWeights>();
   au.addRequired<LiveStacks>();
   au.addPreserved<LiveStacks>();
+  au.addRequired<MachineDominatorTree>();
+  au.addPreserved<MachineDominatorTree>();
   au.addRequired<MachineLoopInfo>();
   au.addPreserved<MachineLoopInfo>();
-  if (pbqpPreSplitting)
-    au.addRequired<LoopSplitter>();
   au.addRequired<VirtRegMap>();
   au.addRequired<RenderMachineFunction>();
   MachineFunctionPass::getAnalysisUsage(au);
@@ -488,29 +525,6 @@
   }
 }
=20
-void RegAllocPBQP::addStackInterval(const LiveInterval *spilled,
-                                    MachineRegisterInfo* mri) {
-  int stackSlot =3D vrm->getStackSlot(spilled->reg);
-
-  if (stackSlot =3D=3D VirtRegMap::NO_STACK_SLOT) {
-    return;
-  }
-
-  const TargetRegisterClass *RC =3D mri->getRegClass(spilled->reg);
-  LiveInterval &stackInterval =3D lss->getOrCreateInterval(stackSlot, RC);
-
-  VNInfo *vni;
-  if (stackInterval.getNumValNums() !=3D 0) {
-    vni =3D stackInterval.getValNumInfo(0);
-  } else {
-    vni =3D stackInterval.getNextValue(
-      SlotIndex(), 0, lss->getVNInfoAllocator());
-  }
-
-  LiveInterval &rhsInterval =3D lis->getInterval(spilled->reg);
-  stackInterval.MergeRangesInAsValue(rhsInterval, vni);
-}
-
 bool RegAllocPBQP::mapPBQPToRegAlloc(const PBQPRAProblem &problem,
                                      const PBQP::Solution &solution) {
   // Set to true if we have any spills
@@ -529,28 +543,22 @@
     unsigned alloc =3D solution.getSelection(node);
=20
     if (problem.isPRegOption(vreg, alloc)) {
-      unsigned preg =3D problem.getPRegForOption(vreg, alloc);   =20
+      unsigned preg =3D problem.getPRegForOption(vreg, alloc);
       DEBUG(dbgs() << "VREG " << vreg << " -> " << tri->getName(preg) << "=
\n");
       assert(preg !=3D 0 && "Invalid preg selected.");
-      vrm->assignVirt2Phys(vreg, preg);     =20
+      vrm->assignVirt2Phys(vreg, preg);
     } else if (problem.isSpillOption(vreg, alloc)) {
       vregsToAlloc.erase(vreg);
-      const LiveInterval* spillInterval =3D &lis->getInterval(vreg);
-      double oldWeight =3D spillInterval->weight;
-      rmf->rememberUseDefs(spillInterval);
-      std::vector<LiveInterval*> newSpills =3D
-        lis->addIntervalsForSpills(*spillInterval, 0, loopInfo, *vrm);
-      addStackInterval(spillInterval, mri);
-      rmf->rememberSpills(spillInterval, newSpills);
+      SmallVector<LiveInterval*, 8> newSpills;
+      LiveRangeEdit LRE(lis->getInterval(vreg), newSpills, *mf, *lis, vrm);
+      spiller->spill(LRE);
=20
-      (void) oldWeight;
       DEBUG(dbgs() << "VREG " << vreg << " -> SPILLED (Cost: "
-                   << oldWeight << ", New vregs: ");
+                   << LRE.getParent().weight << ", New vregs: ");
=20
       // Copy any newly inserted live intervals into the list of regs to
       // allocate.
-      for (std::vector<LiveInterval*>::const_iterator
-           itr =3D newSpills.begin(), end =3D newSpills.end();
+      for (LiveRangeEdit::iterator itr =3D LRE.begin(), end =3D LRE.end();
            itr !=3D end; ++itr) {
         assert(!(*itr)->empty() && "Empty spill range.");
         DEBUG(dbgs() << (*itr)->reg << " ");
@@ -560,9 +568,9 @@
       DEBUG(dbgs() << ")\n");
=20
       // We need another round if spill intervals were added.
-      anotherRoundNeeded |=3D !newSpills.empty();
+      anotherRoundNeeded |=3D !LRE.empty();
     } else {
-      assert(false && "Unknown allocation option.");
+      llvm_unreachable("Unknown allocation option.");
     }
   }
=20
@@ -642,7 +650,7 @@
   tm =3D &mf->getTarget();
   tri =3D tm->getRegisterInfo();
   tii =3D tm->getInstrInfo();
-  mri =3D &mf->getRegInfo();=20
+  mri =3D &mf->getRegInfo();
=20
   lis =3D &getAnalysis<LiveIntervals>();
   lss =3D &getAnalysis<LiveStacks>();
@@ -650,7 +658,9 @@
   rmf =3D &getAnalysis<RenderMachineFunction>();
=20
   vrm =3D &getAnalysis<VirtRegMap>();
+  spiller.reset(createInlineSpiller(*this, MF, *vrm));
=20
+  mri->freezeReservedRegs(MF);
=20
   DEBUG(dbgs() << "PBQP Register Allocating for " << mf->getFunction()->ge=
tName() << "\n");
=20
@@ -666,6 +676,12 @@
   // Find the vreg intervals in need of allocation.
   findVRegIntervalsToAlloc();
=20
+  const Function* func =3D mf->getFunction();
+  std::string fqn =3D
+    func->getParent()->getModuleIdentifier() + "." +
+    func->getName().str();
+  (void)fqn;
+
   // If there are non-empty intervals allocate them using pbqp.
   if (!vregsToAlloc.empty()) {
=20
@@ -677,6 +693,20 @@
=20
       std::auto_ptr<PBQPRAProblem> problem =3D
         builder->build(mf, lis, loopInfo, vregsToAlloc);
+
+#ifndef NDEBUG
+      if (pbqpDumpGraphs) {
+        std::ostringstream rs;
+        rs << round;
+        std::string graphFileName(fqn + "." + rs.str() + ".pbqpgraph");
+        std::string tmp;
+        raw_fd_ostream os(graphFileName.c_str(), tmp);
+        DEBUG(dbgs() << "Dumping graph for round " << round << " to \""
+              << graphFileName << "\"\n");
+        problem->getGraph().dump(os);
+      }
+#endif
+
       PBQP::Solution solution =3D
         PBQP::HeuristicSolver<PBQP::Heuristics::Briggs>::solve(
           problem->getGraph());
@@ -698,9 +728,12 @@
   DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *vrm << "\n");
=20
   // Run rewriter
-  std::auto_ptr<VirtRegRewriter> rewriter(createVirtRegRewriter());
+  vrm->rewrite(lis->getSlotIndexes());
=20
-  rewriter->runOnMachineFunction(*mf, *vrm, lis);
+  // All machine operands and other references to virtual registers have b=
een
+  // replaced. Remove the virtual registers.
+  vrm->clearAllVirt();
+  mri->clearVirtRegs();
=20
   return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Register=
ClassInfo.cpp
--- a/head/contrib/llvm/lib/CodeGen/RegisterClassInfo.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegisterClassInfo.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,12 +18,16 @@
 #include "RegisterClassInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/Target/TargetMachine.h"
-
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
=20
 using namespace llvm;
=20
+static cl::opt<unsigned>
+StressRA("stress-regalloc", cl::Hidden, cl::init(0), cl::value_desc("N"),
+         cl::desc("Limit all regclasses to N registers"));
+
 RegisterClassInfo::RegisterClassInfo() : Tag(0), MF(0), TRI(0), CalleeSave=
d(0)
 {}
=20
@@ -39,14 +43,14 @@
   }
=20
   // Does this MF have different CSRs?
-  const unsigned *CSR =3D TRI->getCalleeSavedRegs(MF);
+  const uint16_t *CSR =3D TRI->getCalleeSavedRegs(MF);
   if (Update || CSR !=3D CalleeSaved) {
     // Build a CSRNum map. Every CSR alias gets an entry pointing to the l=
ast
     // overlapping CSR.
     CSRNum.clear();
     CSRNum.resize(TRI->getNumRegs(), 0);
     for (unsigned N =3D 0; unsigned Reg =3D CSR[N]; ++N)
-      for (const unsigned *AS =3D TRI->getOverlaps(Reg);
+      for (const uint16_t *AS =3D TRI->getOverlaps(Reg);
            unsigned Alias =3D *AS; ++AS)
         CSRNum[Alias] =3D N + 1; // 0 means no CSR, 1 means CalleeSaved[0]=
, ...
     Update =3D true;
@@ -81,7 +85,7 @@
=20
   // FIXME: Once targets reserve registers instead of removing them from t=
he
   // allocation order, we can simply use begin/end here.
-  ArrayRef<unsigned> RawOrder =3D RC->getRawAllocationOrder(*MF);
+  ArrayRef<uint16_t> RawOrder =3D RC->getRawAllocationOrder(*MF);
   for (unsigned i =3D 0; i !=3D RawOrder.size(); ++i) {
     unsigned PhysReg =3D RawOrder[i];
     // Remove reserved registers from the allocation order.
@@ -99,6 +103,10 @@
   // CSR aliases go after the volatile registers, preserve the target's or=
der.
   std::copy(CSRAlias.begin(), CSRAlias.end(), &RCI.Order[N]);
=20
+  // Register allocator stress test.  Clip register class to N registers.
+  if (StressRA && RCI.NumRegs > StressRA)
+    RCI.NumRegs =3D StressRA;
+
   // Check if RC is a proper sub-class.
   if (const TargetRegisterClass *Super =3D TRI->getLargestLegalSuperClass(=
RC))
     if (Super !=3D RC && getNumAllocatableRegs(Super) > RCI.NumRegs)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Register=
ClassInfo.h
--- a/head/contrib/llvm/lib/CodeGen/RegisterClassInfo.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegisterClassInfo.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -49,7 +49,7 @@
=20
   // Callee saved registers of last MF. Assumed to be valid until the next
   // runOnFunction() call.
-  const unsigned *CalleeSaved;
+  const uint16_t *CalleeSaved;
=20
   // Map register number to CalleeSaved index + 1;
   SmallVector<uint8_t, 4> CSRNum;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Register=
Coalescer.cpp
--- a/head/contrib/llvm/lib/CodeGen/RegisterCoalescer.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegisterCoalescer.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -13,7 +13,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#define DEBUG_TYPE "regcoalescing"
+#define DEBUG_TYPE "regalloc"
 #include "RegisterCoalescer.h"
 #include "LiveDebugVariables.h"
 #include "RegisterClassInfo.h"
@@ -169,10 +169,6 @@
     /// it as well.
     bool RemoveDeadDef(LiveInterval &li, MachineInstr *DefMI);
=20
-    /// RemoveCopyFlag - If DstReg is no longer defined by CopyMI, clear t=
he
-    /// VNInfo copy flag for DstReg and all aliases.
-    void RemoveCopyFlag(unsigned DstReg, const MachineInstr *CopyMI);
-
     /// markAsJoined - Remember that CopyMI has already been joined.
     void markAsJoined(MachineInstr *CopyMI);
=20
@@ -197,7 +193,7 @@
   };
 } /// end anonymous namespace
=20
-char &llvm::RegisterCoalescerPassID =3D RegisterCoalescer::ID;
+char &llvm::RegisterCoalescerID =3D RegisterCoalescer::ID;
=20
 INITIALIZE_PASS_BEGIN(RegisterCoalescer, "simple-register-coalescing",
                       "Simple Register Coalescing", false, false)
@@ -205,9 +201,6 @@
 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
-INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
-INITIALIZE_PASS_DEPENDENCY(PHIElimination)
-INITIALIZE_PASS_DEPENDENCY(TwoAddressInstructionPass)
 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
 INITIALIZE_PASS_END(RegisterCoalescer, "simple-register-coalescing",
                     "Simple Register Coalescing", false, false)
@@ -379,9 +372,6 @@
   AU.addRequired<MachineLoopInfo>();
   AU.addPreserved<MachineLoopInfo>();
   AU.addPreservedID(MachineDominatorsID);
-  AU.addPreservedID(StrongPHIEliminationID);
-  AU.addPreservedID(PHIEliminationID);
-  AU.addPreservedID(TwoAddressInstructionPassID);
   MachineFunctionPass::getAnalysisUsage(AU);
 }
=20
@@ -423,7 +413,7 @@
     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
   LiveInterval &IntB =3D
     LIS->getInterval(CP.isFlipped() ? CP.getSrcReg() : CP.getDstReg());
-  SlotIndex CopyIdx =3D LIS->getInstructionIndex(CopyMI).getDefIndex();
+  SlotIndex CopyIdx =3D LIS->getInstructionIndex(CopyMI).getRegSlot();
=20
   // BValNo is a value number in B that is defined by a copy from A.  'B3'=
 in
   // the example above.
@@ -434,40 +424,19 @@
   // Get the location that B is defined at.  Two options: either this valu=
e has
   // an unknown definition point or it is defined at CopyIdx.  If unknown,=
 we
   // can't process it.
-  if (!BValNo->isDefByCopy()) return false;
-  assert(BValNo->def =3D=3D CopyIdx && "Copy doesn't define the value?");
+  if (BValNo->def !=3D CopyIdx) return false;
=20
   // AValNo is the value number in A that defines the copy, A3 in the exam=
ple.
-  SlotIndex CopyUseIdx =3D CopyIdx.getUseIndex();
+  SlotIndex CopyUseIdx =3D CopyIdx.getRegSlot(true);
   LiveInterval::iterator ALR =3D IntA.FindLiveRangeContaining(CopyUseIdx);
   // The live range might not exist after fun with physreg coalescing.
   if (ALR =3D=3D IntA.end()) return false;
   VNInfo *AValNo =3D ALR->valno;
-  // If it's re-defined by an early clobber somewhere in the live range, t=
hen
-  // it's not safe to eliminate the copy. FIXME: This is a temporary worka=
round.
-  // See PR3149:
-  // 172     %ECX<def> =3D MOV32rr %reg1039<kill>
-  // 180     INLINEASM <es:subl $5,$1
-  //         sbbl $3,$0>, 10, %EAX<def>, 14, %ECX<earlyclobber,def>, 9,
-  //         %EAX<kill>,
-  // 36, <fi#0>, 1, %reg0, 0, 9, %ECX<kill>, 36, <fi#1>, 1, %reg0, 0
-  // 188     %EAX<def> =3D MOV32rr %EAX<kill>
-  // 196     %ECX<def> =3D MOV32rr %ECX<kill>
-  // 204     %ECX<def> =3D MOV32rr %ECX<kill>
-  // 212     %EAX<def> =3D MOV32rr %EAX<kill>
-  // 220     %EAX<def> =3D MOV32rr %EAX
-  // 228     %reg1039<def> =3D MOV32rr %ECX<kill>
-  // The early clobber operand ties ECX input to the ECX def.
-  //
-  // The live interval of ECX is represented as this:
-  // %reg20,inf =3D [46,47:1)[174,230:0)  0 at 174-(230) 1 at 46-(47)
-  // The coalescer has no idea there was a def in the middle of [174,230].
-  if (AValNo->hasRedefByEC())
-    return false;
=20
   // If AValNo is defined as a copy from IntB, we can potentially process =
this.
   // Get the instruction that defines this value number.
-  if (!CP.isCoalescable(AValNo->getCopy()))
+  MachineInstr *ACopyMI =3D LIS->getInstructionFromIndex(AValNo->def);
+  if (!CP.isCoalescable(ACopyMI))
     return false;
=20
   // Get the LiveRange in IntB that this value number starts with.
@@ -492,7 +461,7 @@
   // of its aliases is overlapping the live interval of the virtual regist=
er.
   // If so, do not coalesce.
   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
-    for (const unsigned *AS =3D TRI->getAliasSet(IntB.reg); *AS; ++AS)
+    for (const uint16_t *AS =3D TRI->getAliasSet(IntB.reg); *AS; ++AS)
       if (LIS->hasInterval(*AS) && IntA.overlaps(LIS->getInterval(*AS))) {
         DEBUG({
             dbgs() << "\t\tInterfere with alias ";
@@ -511,8 +480,7 @@
   // We are about to delete CopyMI, so need to remove it as the 'instructi=
on
   // that defines this value #'. Update the valnum with the new defining
   // instruction #.
-  BValNo->def  =3D FillerStart;
-  BValNo->setCopy(0);
+  BValNo->def =3D FillerStart;
=20
   // Okay, we can merge them.  We need to insert a new liverange:
   // [ValLR.end, BLR.begin) of either value number, then we merge the
@@ -522,12 +490,12 @@
   // If the IntB live range is assigned to a physical register, and if that
   // physreg has sub-registers, update their live intervals as well.
   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
-    for (const unsigned *SR =3D TRI->getSubRegisters(IntB.reg); *SR; ++SR)=
 {
+    for (const uint16_t *SR =3D TRI->getSubRegisters(IntB.reg); *SR; ++SR)=
 {
       if (!LIS->hasInterval(*SR))
         continue;
       LiveInterval &SRLI =3D LIS->getInterval(*SR);
       SRLI.addRange(LiveRange(FillerStart, FillerEnd,
-                              SRLI.getNextValue(FillerStart, 0,
+                              SRLI.getNextValue(FillerStart,
                                                 LIS->getVNInfoAllocator())=
));
     }
   }
@@ -554,9 +522,11 @@
     ValLREndInst->getOperand(UIdx).setIsKill(false);
   }
=20
-  // If the copy instruction was killing the destination register before t=
he
-  // merge, find the last use and trim the live range. That will also add =
the
-  // isKill marker.
+  // Rewrite the copy. If the copy instruction was killing the destination
+  // register before the merge, find the last use and trim the live range.=
 That
+  // will also add the isKill marker.
+  CopyMI->substituteRegister(IntA.reg, IntB.reg, CP.getSubIdx(),
+                             *TRI);
   if (ALR->end =3D=3D CopyIdx)
     LIS->shrinkToUses(&IntA);
=20
@@ -625,7 +595,7 @@
   if (!LIS->hasInterval(CP.getDstReg()))
     return false;
=20
-  SlotIndex CopyIdx =3D LIS->getInstructionIndex(CopyMI).getDefIndex();
+  SlotIndex CopyIdx =3D LIS->getInstructionIndex(CopyMI).getRegSlot();
=20
   LiveInterval &IntA =3D
     LIS->getInterval(CP.isFlipped() ? CP.getDstReg() : CP.getSrcReg());
@@ -635,13 +605,13 @@
   // BValNo is a value number in B that is defined by a copy from A. 'B3' =
in
   // the example above.
   VNInfo *BValNo =3D IntB.getVNInfoAt(CopyIdx);
-  if (!BValNo || !BValNo->isDefByCopy())
+  if (!BValNo || BValNo->def !=3D CopyIdx)
     return false;
=20
   assert(BValNo->def =3D=3D CopyIdx && "Copy doesn't define the value?");
=20
   // AValNo is the value number in A that defines the copy, A3 in the exam=
ple.
-  VNInfo *AValNo =3D IntA.getVNInfoAt(CopyIdx.getUseIndex());
+  VNInfo *AValNo =3D IntA.getVNInfoAt(CopyIdx.getRegSlot(true));
   assert(AValNo && "COPY source not live");
=20
   // If other defs can reach uses of this def, then it's not safe to perfo=
rm
@@ -651,8 +621,7 @@
   MachineInstr *DefMI =3D LIS->getInstructionFromIndex(AValNo->def);
   if (!DefMI)
     return false;
-  const MCInstrDesc &MCID =3D DefMI->getDesc();
-  if (!MCID.isCommutable())
+  if (!DefMI->isCommutable())
     return false;
   // If DefMI is a two-address instruction then commuting it will change t=
he
   // destination register.
@@ -684,7 +653,7 @@
   // Abort if the aliases of IntB.reg have values that are not simply the
   // clobbers from the superreg.
   if (TargetRegisterInfo::isPhysicalRegister(IntB.reg))
-    for (const unsigned *AS =3D TRI->getAliasSet(IntB.reg); *AS; ++AS)
+    for (const uint16_t *AS =3D TRI->getAliasSet(IntB.reg); *AS; ++AS)
       if (LIS->hasInterval(*AS) &&
           HasOtherReachingDefs(IntA, LIS->getInterval(*AS), AValNo, 0))
         return false;
@@ -718,7 +687,8 @@
     return false;
   if (NewMI !=3D DefMI) {
     LIS->ReplaceMachineInstrInMaps(DefMI, NewMI);
-    MBB->insert(DefMI, NewMI);
+    MachineBasicBlock::iterator Pos =3D DefMI;
+    MBB->insert(Pos, NewMI);
     MBB->erase(DefMI);
   }
   unsigned OpIdx =3D NewMI->findRegisterUseOperandIdx(IntA.reg, false);
@@ -747,7 +717,7 @@
       UseMO.setReg(NewReg);
       continue;
     }
-    SlotIndex UseIdx =3D LIS->getInstructionIndex(UseMI).getUseIndex();
+    SlotIndex UseIdx =3D LIS->getInstructionIndex(UseMI).getRegSlot(true);
     LiveInterval::iterator ULR =3D IntA.FindLiveRangeContaining(UseIdx);
     if (ULR =3D=3D IntA.end() || ULR->valno !=3D AValNo)
       continue;
@@ -765,7 +735,7 @@
=20
     // This copy will become a noop. If it's defining a new val#, merge it=
 into
     // BValNo.
-    SlotIndex DefIdx =3D UseIdx.getDefIndex();
+    SlotIndex DefIdx =3D UseIdx.getRegSlot();
     VNInfo *DVNI =3D IntB.getVNInfoAt(DefIdx);
     if (!DVNI)
       continue;
@@ -779,7 +749,6 @@
   // is updated.
   VNInfo *ValNo =3D BValNo;
   ValNo->def =3D AValNo->def;
-  ValNo->setCopy(0);
   for (LiveInterval::iterator AI =3D IntA.begin(), AE =3D IntA.end();
        AI !=3D AE; ++AI) {
     if (AI->valno !=3D AValNo) continue;
@@ -799,7 +768,7 @@
                                                        bool preserveSrcInt,
                                                        unsigned DstReg,
                                                        MachineInstr *CopyM=
I) {
-  SlotIndex CopyIdx =3D LIS->getInstructionIndex(CopyMI).getUseIndex();
+  SlotIndex CopyIdx =3D LIS->getInstructionIndex(CopyMI).getRegSlot(true);
   LiveInterval::iterator SrcLR =3D SrcInt.FindLiveRangeContaining(CopyIdx);
   assert(SrcLR !=3D SrcInt.end() && "Live range not found!");
   VNInfo *ValNo =3D SrcLR->valno;
@@ -809,14 +778,14 @@
   if (!DefMI)
     return false;
   assert(DefMI && "Defining instruction disappeared");
-  const MCInstrDesc &MCID =3D DefMI->getDesc();
-  if (!MCID.isAsCheapAsAMove())
+  if (!DefMI->isAsCheapAsAMove())
     return false;
   if (!TII->isTriviallyReMaterializable(DefMI, AA))
     return false;
   bool SawStore =3D false;
   if (!DefMI->isSafeToMove(TII, AA, SawStore))
     return false;
+  const MCInstrDesc &MCID =3D DefMI->getDesc();
   if (MCID.getNumDefs() !=3D 1)
     return false;
   if (!DefMI->isImplicitDef()) {
@@ -831,27 +800,52 @@
       return false;
   }
=20
-  RemoveCopyFlag(DstReg, CopyMI);
-
   MachineBasicBlock *MBB =3D CopyMI->getParent();
   MachineBasicBlock::iterator MII =3D
     llvm::next(MachineBasicBlock::iterator(CopyMI));
   TII->reMaterialize(*MBB, MII, DstReg, 0, DefMI, *TRI);
   MachineInstr *NewMI =3D prior(MII);
=20
+  // NewMI may have dead implicit defs (E.g. EFLAGS for MOV<bits>r0 on X86=
).
+  // We need to remember these so we can add intervals once we insert
+  // NewMI into SlotIndexes.
+  SmallVector<unsigned, 4> NewMIImplDefs;
+  for (unsigned i =3D NewMI->getDesc().getNumOperands(),
+         e =3D NewMI->getNumOperands(); i !=3D e; ++i) {
+    MachineOperand &MO =3D NewMI->getOperand(i);
+    if (MO.isReg()) {
+      assert(MO.isDef() && MO.isImplicit() && MO.isDead() &&
+             TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
+      NewMIImplDefs.push_back(MO.getReg());
+    }
+  }
+
   // CopyMI may have implicit operands, transfer them over to the newly
   // rematerialized instruction. And update implicit def interval valnos.
   for (unsigned i =3D CopyMI->getDesc().getNumOperands(),
          e =3D CopyMI->getNumOperands(); i !=3D e; ++i) {
     MachineOperand &MO =3D CopyMI->getOperand(i);
-    if (MO.isReg() && MO.isImplicit())
-      NewMI->addOperand(MO);
-    if (MO.isDef())
-      RemoveCopyFlag(MO.getReg(), CopyMI);
+    if (MO.isReg()) {
+      assert(MO.isImplicit() && "No explicit operands after implict operan=
ds.");
+      // Discard VReg implicit defs.
+      if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
+        NewMI->addOperand(MO);
+      }
+    }
   }
=20
-  NewMI->copyImplicitOps(CopyMI);
   LIS->ReplaceMachineInstrInMaps(CopyMI, NewMI);
+
+  SlotIndex NewMIIdx =3D LIS->getInstructionIndex(NewMI);
+  for (unsigned i =3D 0, e =3D NewMIImplDefs.size(); i !=3D e; ++i) {
+    unsigned reg =3D NewMIImplDefs[i];
+    LiveInterval &li =3D LIS->getInterval(reg);
+    VNInfo *DeadDefVN =3D li.getNextValue(NewMIIdx.getRegSlot(),
+                                        LIS->getVNInfoAllocator());
+    LiveRange lr(NewMIIdx.getRegSlot(), NewMIIdx.getDeadSlot(), DeadDefVN);
+    li.addRange(lr);
+  }
+
   CopyMI->eraseFromParent();
   ReMatCopies.insert(CopyMI);
   ReMatDefs.insert(DefMI);
@@ -887,7 +881,7 @@
     DstInt =3D SrcInt;
   SrcInt =3D 0;
=20
-  VNInfo *DeadVNI =3D DstInt->getVNInfoAt(Idx.getDefIndex());
+  VNInfo *DeadVNI =3D DstInt->getVNInfoAt(Idx.getRegSlot());
   assert(DeadVNI && "No value defined in DstInt");
   DstInt->removeValNo(DeadVNI);
=20
@@ -941,13 +935,10 @@
     SmallVector<unsigned,8> Ops;
     bool Reads, Writes;
     tie(Reads, Writes) =3D UseMI->readsWritesVirtualRegister(SrcReg, &Ops);
-    bool Kills =3D false, Deads =3D false;
=20
     // Replace SrcReg with DstReg in all UseMI operands.
     for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i) {
       MachineOperand &MO =3D UseMI->getOperand(Ops[i]);
-      Kills |=3D MO.isKill();
-      Deads |=3D MO.isDead();
=20
       // Make sure we don't create read-modify-write defs accidentally.  We
       // assume here that a SrcReg def cannot be joined into a live DstReg=
.  If
@@ -967,19 +958,6 @@
     if (JoinedCopies.count(UseMI))
       continue;
=20
-    if (SubIdx) {
-      // If UseMI was a simple SrcReg def, make sure we didn't turn it int=
o a
-      // read-modify-write of DstReg.
-      if (Deads)
-        UseMI->addRegisterDead(DstReg, TRI);
-      else if (!Reads && Writes)
-        UseMI->addRegisterDefined(DstReg, TRI);
-
-      // Kill flags apply to the whole physical register.
-      if (DstIsPhys && Kills)
-        UseMI->addRegisterKilled(DstReg, TRI);
-    }
-
     DEBUG({
         dbgs() << "\t\tupdated: ";
         if (!UseMI->isDebugValue())
@@ -996,7 +974,7 @@
                                   const TargetRegisterInfo *TRI) {
   if (li.empty()) {
     if (TargetRegisterInfo::isPhysicalRegister(li.reg))
-      for (const unsigned* SR =3D TRI->getSubRegisters(li.reg); *SR; ++SR)=
 {
+      for (const uint16_t* SR =3D TRI->getSubRegisters(li.reg); *SR; ++SR)=
 {
         if (!LIS->hasInterval(*SR))
           continue;
         LiveInterval &sli =3D LIS->getInterval(*SR);
@@ -1013,7 +991,7 @@
 /// the val# it defines. If the live interval becomes empty, remove it as =
well.
 bool RegisterCoalescer::RemoveDeadDef(LiveInterval &li,
                                              MachineInstr *DefMI) {
-  SlotIndex DefIdx =3D LIS->getInstructionIndex(DefMI).getDefIndex();
+  SlotIndex DefIdx =3D LIS->getInstructionIndex(DefMI).getRegSlot();
   LiveInterval::iterator MLR =3D li.FindLiveRangeContaining(DefIdx);
   if (DefIdx !=3D MLR->valno->def)
     return false;
@@ -1021,27 +999,6 @@
   return removeIntervalIfEmpty(li, LIS, TRI);
 }
=20
-void RegisterCoalescer::RemoveCopyFlag(unsigned DstReg,
-                                              const MachineInstr *CopyMI) {
-  SlotIndex DefIdx =3D LIS->getInstructionIndex(CopyMI).getDefIndex();
-  if (LIS->hasInterval(DstReg)) {
-    LiveInterval &LI =3D LIS->getInterval(DstReg);
-    if (const LiveRange *LR =3D LI.getLiveRangeContaining(DefIdx))
-      if (LR->valno->def =3D=3D DefIdx)
-        LR->valno->setCopy(0);
-  }
-  if (!TargetRegisterInfo::isPhysicalRegister(DstReg))
-    return;
-  for (const unsigned* AS =3D TRI->getAliasSet(DstReg); *AS; ++AS) {
-    if (!LIS->hasInterval(*AS))
-      continue;
-    LiveInterval &LI =3D LIS->getInterval(*AS);
-    if (const LiveRange *LR =3D LI.getLiveRangeContaining(DefIdx))
-      if (LR->valno->def =3D=3D DefIdx)
-        LR->valno->setCopy(0);
-  }
-}
-
 /// shouldJoinPhys - Return true if a copy involving a physreg should be j=
oined.
 /// We need to be careful about coalescing a source physical register with=
 a
 /// virtual register. Once the coalescing is done, it cannot be broken and=
 these
@@ -1279,7 +1236,7 @@
     }
   }
=20
-  // SrcReg is guarateed to be the register whose live interval that is
+  // SrcReg is guaranteed to be the register whose live interval that is
   // being merged.
   LIS->removeInterval(CP.getSrcReg());
=20
@@ -1368,9 +1325,9 @@
   // FIXME: This is very conservative. For example, we don't handle
   // physical registers.
=20
-  MachineInstr *MI =3D VNI->getCopy();
+  MachineInstr *MI =3D li.getInstructionFromIndex(VNI->def);
=20
-  if (!MI->isFullCopy() || CP.isPartial() || CP.isPhys())
+  if (!MI || !MI->isFullCopy() || CP.isPartial() || CP.isPhys())
     return false;
=20
   unsigned Dst =3D MI->getOperand(0).getReg();
@@ -1388,11 +1345,9 @@
   assert(Dst =3D=3D A);
=20
   VNInfo *Other =3D LR->valno;
-  if (!Other->isDefByCopy())
-    return false;
-  const MachineInstr *OtherMI =3D Other->getCopy();
+  const MachineInstr *OtherMI =3D li.getInstructionFromIndex(Other->def);
=20
-  if (!OtherMI->isFullCopy())
+  if (!OtherMI || !OtherMI->isFullCopy())
     return false;
=20
   unsigned OtherDst =3D OtherMI->getOperand(0).getReg();
@@ -1431,7 +1386,44 @@
   // than the full interfeence check below. We allow overlapping live rang=
es
   // only when one is a copy of the other.
   if (CP.isPhys()) {
-    for (const unsigned *AS =3D TRI->getAliasSet(CP.getDstReg()); *AS; ++A=
S){
+    // Optimization for reserved registers like ESP.
+    // We can only merge with a reserved physreg if RHS has a single value=
 that
+    // is a copy of CP.DstReg().  The live range of the reserved register =
will
+    // look like a set of dead defs - we don't properly track the live ran=
ge of
+    // reserved registers.
+    if (RegClassInfo.isReserved(CP.getDstReg())) {
+      assert(CP.isFlipped() && RHS.containsOneValue() &&
+             "Invalid join with reserved register");
+      // Deny any overlapping intervals.  This depends on all the reserved
+      // register live ranges to look like dead defs.
+      for (const uint16_t *AS =3D TRI->getOverlaps(CP.getDstReg()); *AS; +=
+AS) {
+        if (!LIS->hasInterval(*AS)) {
+          // Make sure at least DstReg itself exists before attempting a j=
oin.
+          if (*AS =3D=3D CP.getDstReg())
+            LIS->getOrCreateInterval(CP.getDstReg());
+          continue;
+        }
+        if (RHS.overlaps(LIS->getInterval(*AS))) {
+          DEBUG(dbgs() << "\t\tInterference: " << PrintReg(*AS, TRI) << '\=
n');
+          return false;
+        }
+      }
+      // Skip any value computations, we are not adding new values to the
+      // reserved register.  Also skip merging the live ranges, the reserv=
ed
+      // register live range doesn't need to be accurate as long as all the
+      // defs are there.
+      return true;
+    }
+
+    // Check if a register mask clobbers DstReg.
+    BitVector UsableRegs;
+    if (LIS->checkRegMaskInterference(RHS, UsableRegs) &&
+        !UsableRegs.test(CP.getDstReg())) {
+      DEBUG(dbgs() << "\t\tRegister mask interference.\n");
+      return false;
+    }
+
+    for (const uint16_t *AS =3D TRI->getAliasSet(CP.getDstReg()); *AS; ++A=
S){
       if (!LIS->hasInterval(*AS))
         continue;
       const LiveInterval &LHS =3D LIS->getInterval(*AS);
@@ -1485,12 +1477,12 @@
   for (LiveInterval::vni_iterator i =3D LHS.vni_begin(), e =3D LHS.vni_end=
();
        i !=3D e; ++i) {
     VNInfo *VNI =3D *i;
-    if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a c=
opy?
+    if (VNI->isUnused() || VNI->isPHIDef())
       continue;
-
-    // Never join with a register that has EarlyClobber redefs.
-    if (VNI->hasRedefByEC())
-      return false;
+    MachineInstr *MI =3D LIS->getInstructionFromIndex(VNI->def);
+    assert(MI && "Missing def");
+    if (!MI->isCopyLike())  // Src not defined by a copy?
+      continue;
=20
     // Figure out the value # from the RHS.
     LiveRange *lr =3D RHS.getLiveRangeContaining(VNI->def.getPrevSlot());
@@ -1499,7 +1491,6 @@
=20
     // DstReg is known to be a register in the LHS interval.  If the src is
     // from the RHS interval, we can use its value #.
-    MachineInstr *MI =3D VNI->getCopy();
     if (!CP.isCoalescable(MI) &&
         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
       continue;
@@ -1512,12 +1503,12 @@
   for (LiveInterval::vni_iterator i =3D RHS.vni_begin(), e =3D RHS.vni_end=
();
        i !=3D e; ++i) {
     VNInfo *VNI =3D *i;
-    if (VNI->isUnused() || !VNI->isDefByCopy())  // Src not defined by a c=
opy?
+    if (VNI->isUnused() || VNI->isPHIDef())
       continue;
-
-    // Never join with a register that has EarlyClobber redefs.
-    if (VNI->hasRedefByEC())
-      return false;
+    MachineInstr *MI =3D LIS->getInstructionFromIndex(VNI->def);
+    assert(MI && "Missing def");
+    if (!MI->isCopyLike())  // Src not defined by a copy?
+      continue;
=20
     // Figure out the value # from the LHS.
     LiveRange *lr =3D LHS.getLiveRangeContaining(VNI->def.getPrevSlot());
@@ -1526,7 +1517,6 @@
=20
     // DstReg is known to be a register in the RHS interval.  If the src is
     // from the LHS interval, we can use its value #.
-    MachineInstr *MI =3D VNI->getCopy();
     if (!CP.isCoalescable(MI) &&
         !RegistersDefinedFromSameValue(*LIS, *TRI, CP, VNI, lr, DupCopies))
         continue;
@@ -1600,10 +1590,6 @@
       if (LHSValNoAssignments[I->valno->id] !=3D
           RHSValNoAssignments[J->valno->id])
         return false;
-      // If it's re-defined by an early clobber somewhere in the live rang=
e,
-      // then conservatively abort coalescing.
-      if (NewVNInfo[LHSValNoAssignments[I->valno->id]]->hasRedefByEC())
-        return false;
     }
=20
     if (I->end < J->end)
@@ -1905,8 +1891,8 @@
           unsigned Reg =3D MO.getReg();
           if (!Reg)
             continue;
+          DeadDefs.push_back(Reg);
           if (TargetRegisterInfo::isVirtualRegister(Reg)) {
-            DeadDefs.push_back(Reg);
             // Remat may also enable register class inflation.
             if (RegClassInfo.isProperSubClass(MRI->getRegClass(Reg)))
               InflateRegs.push_back(Reg);
@@ -1936,7 +1922,7 @@
=20
       // Check for now unnecessary kill flags.
       if (LIS->isNotInMIMap(MI)) continue;
-      SlotIndex DefIdx =3D LIS->getInstructionIndex(MI).getDefIndex();
+      SlotIndex DefIdx =3D LIS->getInstructionIndex(MI).getRegSlot();
       for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
         MachineOperand &MO =3D MI->getOperand(i);
         if (!MO.isReg() || !MO.isKill()) continue;
@@ -1950,7 +1936,7 @@
         // remain alive.
         if (!TargetRegisterInfo::isPhysicalRegister(reg))
           continue;
-        for (const unsigned *SR =3D TRI->getSubRegisters(reg);
+        for (const uint16_t *SR =3D TRI->getSubRegisters(reg);
              unsigned S =3D *SR; ++SR)
           if (LIS->hasInterval(S) && LIS->getInterval(S).liveAt(DefIdx))
             MI->addRegisterDefined(S, TRI);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Register=
Coalescer.h
--- a/head/contrib/llvm/lib/CodeGen/RegisterCoalescer.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegisterCoalescer.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- RegisterCoalescer.h - Register Coalescing Interface ------*-=
 C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- RegisterCoalescer.h - Register Coalescing Interface -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -7,7 +7,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-// This file contains the abstract interface for register coalescers,=20
+// This file contains the abstract interface for register coalescers,
 // allowing them to interact with and query register allocators.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -47,7 +47,7 @@
     /// CrossClass - True when both regs are virtual, and newRC is constra=
ined.
     bool CrossClass;
=20
-    /// Flipped - True when DstReg and SrcReg are reversed from the oriign=
al
+    /// Flipped - True when DstReg and SrcReg are reversed from the origin=
al
     /// copy instruction.
     bool Flipped;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Register=
Scavenging.cpp
--- a/head/contrib/llvm/lib/CodeGen/RegisterScavenging.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RegisterScavenging.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -37,7 +37,7 @@
 void RegScavenger::setUsed(unsigned Reg) {
   RegsAvailable.reset(Reg);
=20
-  for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+  for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
        unsigned SubReg =3D *SubRegs; ++SubRegs)
     RegsAvailable.reset(SubReg);
 }
@@ -45,7 +45,7 @@
 bool RegScavenger::isAliasUsed(unsigned Reg) const {
   if (isUsed(Reg))
     return true;
-  for (const unsigned *R =3D TRI->getAliasSet(Reg); *R; ++R)
+  for (const uint16_t *R =3D TRI->getAliasSet(Reg); *R; ++R)
     if (isUsed(*R))
       return true;
   return false;
@@ -59,9 +59,6 @@
   // All registers started out unused.
   RegsAvailable.set();
=20
-  // Reserved registers are always used.
-  RegsAvailable ^=3D ReservedRegs;
-
   if (!MBB)
     return;
=20
@@ -86,17 +83,24 @@
   assert((NumPhysRegs =3D=3D 0 || NumPhysRegs =3D=3D TRI->getNumRegs()) &&
          "Target changed?");
=20
+  // It is not possible to use the register scavenger after late optimizat=
ion
+  // passes that don't preserve accurate liveness information.
+  assert(MRI->tracksLiveness() &&
+         "Cannot use register scavenger with inaccurate liveness");
+
   // Self-initialize.
   if (!MBB) {
     NumPhysRegs =3D TRI->getNumRegs();
     RegsAvailable.resize(NumPhysRegs);
+    KillRegs.resize(NumPhysRegs);
+    DefRegs.resize(NumPhysRegs);
=20
     // Create reserved registers bitvector.
     ReservedRegs =3D TRI->getReservedRegs(MF);
=20
     // Create callee-saved registers bitvector.
     CalleeSavedRegs.resize(NumPhysRegs);
-    const unsigned *CSRegs =3D TRI->getCalleeSavedRegs();
+    const uint16_t *CSRegs =3D TRI->getCalleeSavedRegs(&MF);
     if (CSRegs !=3D NULL)
       for (unsigned i =3D 0; CSRegs[i]; ++i)
         CalleeSavedRegs.set(CSRegs[i]);
@@ -110,13 +114,7 @@
=20
 void RegScavenger::addRegWithSubRegs(BitVector &BV, unsigned Reg) {
   BV.set(Reg);
-  for (const unsigned *R =3D TRI->getSubRegisters(Reg); *R; R++)
-    BV.set(*R);
-}
-
-void RegScavenger::addRegWithAliases(BitVector &BV, unsigned Reg) {
-  BV.set(Reg);
-  for (const unsigned *R =3D TRI->getAliasSet(Reg); *R; R++)
+  for (const uint16_t *R =3D TRI->getSubRegisters(Reg); *R; R++)
     BV.set(*R);
 }
=20
@@ -148,12 +146,12 @@
   // predicated, conservatively assume "kill" markers do not actually kill=
 the
   // register. Similarly ignores "dead" markers.
   bool isPred =3D TII->isPredicated(MI);
-  BitVector EarlyClobberRegs(NumPhysRegs);
-  BitVector KillRegs(NumPhysRegs);
-  BitVector DefRegs(NumPhysRegs);
-  BitVector DeadRegs(NumPhysRegs);
+  KillRegs.reset();
+  DefRegs.reset();
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D MI->getOperand(i);
+    if (MO.isRegMask())
+      (isPred ? DefRegs : KillRegs).setBitsNotInMask(MO.getRegMask());
     if (!MO.isReg())
       continue;
     unsigned Reg =3D MO.getReg();
@@ -164,21 +162,19 @@
       // Ignore undef uses.
       if (MO.isUndef())
         continue;
-      // Two-address operands implicitly kill.
-      if (!isPred && (MO.isKill() || MI->isRegTiedToDefOperand(i)))
+      if (!isPred && MO.isKill())
         addRegWithSubRegs(KillRegs, Reg);
     } else {
       assert(MO.isDef());
       if (!isPred && MO.isDead())
-        addRegWithSubRegs(DeadRegs, Reg);
+        addRegWithSubRegs(KillRegs, Reg);
       else
         addRegWithSubRegs(DefRegs, Reg);
-      if (MO.isEarlyClobber())
-        addRegWithAliases(EarlyClobberRegs, Reg);
     }
   }
=20
   // Verify uses and defs.
+#ifndef NDEBUG
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D MI->getOperand(i);
     if (!MO.isReg())
@@ -199,17 +195,18 @@
         // Ideally we would like a way to model this, but leaving the
         // insert_subreg around causes both correctness and performance is=
sues.
         bool SubUsed =3D false;
-        for (const unsigned *SubRegs =3D TRI->getSubRegisters(Reg);
+        for (const uint16_t *SubRegs =3D TRI->getSubRegisters(Reg);
              unsigned SubReg =3D *SubRegs; ++SubRegs)
           if (isUsed(SubReg)) {
             SubUsed =3D true;
             break;
           }
-        assert(SubUsed && "Using an undefined register!");
+        if (!SubUsed) {
+          MBB->getParent()->verify(NULL, "In Register Scavenger");
+          llvm_unreachable("Using an undefined register!");
+        }
         (void)SubUsed;
       }
-      assert((!EarlyClobberRegs.test(Reg) || MI->isRegTiedToDefOperand(i))=
 &&
-             "Using an early clobbered register!");
     } else {
       assert(MO.isDef());
 #if 0
@@ -221,18 +218,20 @@
 #endif
     }
   }
+#endif // NDEBUG
=20
   // Commit the changes.
   setUnused(KillRegs);
-  setUnused(DeadRegs);
   setUsed(DefRegs);
 }
=20
 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
+  used =3D RegsAvailable;
+  used.flip();
   if (includeReserved)
-    used =3D ~RegsAvailable;
+    used |=3D ReservedRegs;
   else
-    used =3D ~RegsAvailable & ~ReservedRegs;
+    used.reset(ReservedRegs);
 }
=20
 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RC) const {
@@ -286,6 +285,8 @@
     // Remove any candidates touched by instruction.
     for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
       const MachineOperand &MO =3D MI->getOperand(i);
+      if (MO.isRegMask())
+        Candidates.clearBitsNotInMask(MO.getRegMask());
       if (!MO.isReg() || MO.isUndef() || !MO.getReg())
         continue;
       if (TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
@@ -296,7 +297,7 @@
         continue;
       }
       Candidates.reset(MO.getReg());
-      for (const unsigned *R =3D TRI->getAliasSet(MO.getReg()); *R; R++)
+      for (const uint16_t *R =3D TRI->getAliasSet(MO.getReg()); *R; R++)
         Candidates.reset(*R);
     }
     // If we're not in a virtual reg's live range, this is a valid
@@ -347,9 +348,9 @@
   // RegsAvailable, as RegsAvailable does not take aliases into account.
   // That's what getRegsAvailable() is for.
   BitVector Available =3D getRegsAvailable(RC);
-
-  if ((Candidates & Available).any())
-     Candidates &=3D Available;
+  Available &=3D Candidates;
+  if (Available.any())
+    Candidates =3D Available;
=20
   // Find the register whose use is furthest away.
   MachineBasicBlock::iterator UseMI;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/RenderMa=
chineFunction.cpp
--- a/head/contrib/llvm/lib/CodeGen/RenderMachineFunction.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/RenderMachineFunction.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- llvm/CodeGen/RenderMachineFunction.cpp - MF->HTML -----s----=
-------=3D=3D=3D//
+//=3D=3D=3D-- llvm/CodeGen/RenderMachineFunction.cpp - MF->HTML ----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -560,12 +560,13 @@
=20
     // For uses/defs recorded use/def indexes override current liveness and
     // instruction operands (Only for the interval which records the index=
es).
-    if (i.isUse() || i.isDef()) {
+    // FIXME: This is all wrong, uses and defs share the same slots.
+    if (i.isEarlyClobber() || i.isRegister()) {
       UseDefs::const_iterator udItr =3D useDefs.find(li);
       if (udItr !=3D useDefs.end()) {
         const SlotSet &slotSet =3D udItr->second;
         if (slotSet.count(i)) {
-          if (i.isUse()) {
+          if (i.isEarlyClobber()) {
             return Used;
           }
           // else
@@ -586,9 +587,9 @@
           return AliveStack;
         }
       } else {
-        if (i.isDef() && mi->definesRegister(li->reg, tri)) {
+        if (i.isRegister() && mi->definesRegister(li->reg, tri)) {
           return Defined;
-        } else if (i.isUse() && mi->readsRegister(li->reg)) {
+        } else if (i.isEarlyClobber() && mi->readsRegister(li->reg)) {
           return Used;
         } else {
           if (vrm =3D=3D 0 ||=20
@@ -804,7 +805,7 @@
       os << indent + s(2) << "<tr height=3D6ex>\n";
      =20
       // Render the code column.
-      if (i.isLoad()) {
+      if (i.isBlock()) {
         MachineBasicBlock *mbb =3D sis->getMBBFromIndex(i);
         mi =3D sis->getInstructionFromIndex(i);
=20
@@ -823,7 +824,7 @@
           }
           os << indent + s(4) << "</td>\n";
         } else {
-          i =3D i.getStoreIndex(); // <- Will be incremented to the next i=
ndex.
+          i =3D i.getDeadSlot(); // <- Will be incremented to the next ind=
ex.
           continue;
         }
       }
@@ -952,10 +953,10 @@
          rItr !=3D rEnd; ++rItr) {
       const MachineInstr *mi =3D &*rItr;
       if (mi->readsRegister(li->reg)) {
-        useDefs[li].insert(lis->getInstructionIndex(mi).getUseIndex());
+        useDefs[li].insert(lis->getInstructionIndex(mi).getRegSlot(true));
       }
       if (mi->definesRegister(li->reg)) {
-        useDefs[li].insert(lis->getInstructionIndex(mi).getDefIndex());
+        useDefs[li].insert(lis->getInstructionIndex(mi).getRegSlot());
       }
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Schedule=
DAG.cpp
--- a/head/contrib/llvm/lib/CodeGen/ScheduleDAG.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ScheduleDAG.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -31,6 +31,8 @@
   cl::desc("Stress test instruction scheduling"));
 #endif
=20
+void SchedulingPriorityQueue::anchor() { }
+
 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
   : TM(mf.getTarget()),
     TII(TM.getInstrInfo()),
@@ -44,44 +46,19 @@
=20
 ScheduleDAG::~ScheduleDAG() {}
=20
+/// Clear the DAG state (e.g. between scheduling regions).
+void ScheduleDAG::clearDAG() {
+  SUnits.clear();
+  EntrySU =3D SUnit();
+  ExitSU =3D SUnit();
+}
+
 /// getInstrDesc helper to handle SDNodes.
 const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
   if (!Node || !Node->isMachineOpcode()) return NULL;
   return &TII->get(Node->getMachineOpcode());
 }
=20
-/// dump - dump the schedule.
-void ScheduleDAG::dumpSchedule() const {
-  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; i++) {
-    if (SUnit *SU =3D Sequence[i])
-      SU->dump(this);
-    else
-      dbgs() << "**** NOOP ****\n";
-  }
-}
-
-
-/// Run - perform scheduling.
-///
-void ScheduleDAG::Run(MachineBasicBlock *bb,
-                      MachineBasicBlock::iterator insertPos) {
-  BB =3D bb;
-  InsertPos =3D insertPos;
-
-  SUnits.clear();
-  Sequence.clear();
-  EntrySU =3D SUnit();
-  ExitSU =3D SUnit();
-
-  Schedule();
-
-  DEBUG({
-      dbgs() << "*** Final schedule ***\n";
-      dumpSchedule();
-      dbgs() << '\n';
-    });
-}
-
 /// addPred - This adds the specified edge as a pred of the current node if
 /// not already.  It also adds the current node as a successor of the
 /// specified node.
@@ -313,13 +290,12 @@
       case SDep::Output:      dbgs() << "out "; break;
       case SDep::Order:       dbgs() << "ch  "; break;
       }
-      dbgs() << "#";
-      dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
+      dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
       if (I->isArtificial())
         dbgs() << " *";
       dbgs() << ": Latency=3D" << I->getLatency();
       if (I->isAssignedRegDep())
-        dbgs() << " Reg=3D" << G->TRI->getName(I->getReg());
+        dbgs() << " Reg=3D" << PrintReg(I->getReg(), G->TRI);
       dbgs() << "\n";
     }
   }
@@ -334,8 +310,7 @@
       case SDep::Output:      dbgs() << "out "; break;
       case SDep::Order:       dbgs() << "ch  "; break;
       }
-      dbgs() << "#";
-      dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
+      dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
       if (I->isArtificial())
         dbgs() << " *";
       dbgs() << ": Latency=3D" << I->getLatency();
@@ -346,13 +321,12 @@
 }
=20
 #ifndef NDEBUG
-/// VerifySchedule - Verify that all SUnits were scheduled and that
-/// their state is consistent.
+/// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
+/// their state is consistent. Return the number of scheduled nodes.
 ///
-void ScheduleDAG::VerifySchedule(bool isBottomUp) {
+unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
   bool AnyNotSched =3D false;
   unsigned DeadNodes =3D 0;
-  unsigned Noops =3D 0;
   for (unsigned i =3D 0, e =3D SUnits.size(); i !=3D e; ++i) {
     if (!SUnits[i].isScheduled) {
       if (SUnits[i].NumPreds =3D=3D 0 && SUnits[i].NumSuccs =3D=3D 0) {
@@ -393,12 +367,8 @@
       }
     }
   }
-  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; ++i)
-    if (!Sequence[i])
-      ++Noops;
   assert(!AnyNotSched);
-  assert(Sequence.size() + DeadNodes - Noops =3D=3D SUnits.size() &&
-         "The number of nodes scheduled doesn't match the expected number!=
");
+  return SUnits.size() - DeadNodes;
 }
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Schedule=
DAGInstrs.cpp
--- a/head/contrib/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ScheduleDAGInstrs.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -13,14 +13,15 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "sched-instrs"
-#include "ScheduleDAGInstrs.h"
 #include "llvm/Operator.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Analysis/ValueTracking.h"
+#include "llvm/CodeGen/LiveIntervalAnalysis.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/PseudoSourceValue.h"
+#include "llvm/CodeGen/ScheduleDAGInstrs.h"
 #include "llvm/MC/MCInstrItineraries.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetInstrInfo.h"
@@ -33,25 +34,17 @@
=20
 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
                                      const MachineLoopInfo &mli,
-                                     const MachineDominatorTree &mdt)
+                                     const MachineDominatorTree &mdt,
+                                     bool IsPostRAFlag,
+                                     LiveIntervals *lis)
   : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()),
-    InstrItins(mf.getTarget().getInstrItineraryData()),
-    Defs(TRI->getNumRegs()), Uses(TRI->getNumRegs()),
-    LoopRegs(MLI, MDT), FirstDbgValue(0) {
+    InstrItins(mf.getTarget().getInstrItineraryData()), LIS(lis),
+    IsPostRA(IsPostRAFlag), UnitLatencies(false), LoopRegs(MLI, MDT),
+    FirstDbgValue(0) {
+  assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
   DbgValues.clear();
-}
-
-/// Run - perform scheduling.
-///
-void ScheduleDAGInstrs::Run(MachineBasicBlock *bb,
-                            MachineBasicBlock::iterator begin,
-                            MachineBasicBlock::iterator end,
-                            unsigned endcount) {
-  BB =3D bb;
-  Begin =3D begin;
-  InsertPosIndex =3D endcount;
-
-  ScheduleDAG::Run(bb, end);
+  assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
+         "Virtual registers must be removed prior to PostRA scheduling");
 }
=20
 /// getUnderlyingObjectFromInt - This is the function that does the work of
@@ -133,19 +126,58 @@
   return 0;
 }
=20
-void ScheduleDAGInstrs::StartBlock(MachineBasicBlock *BB) {
+void ScheduleDAGInstrs::startBlock(MachineBasicBlock *BB) {
   LoopRegs.Deps.clear();
   if (MachineLoop *ML =3D MLI.getLoopFor(BB))
-    if (BB =3D=3D ML->getLoopLatch()) {
-      MachineBasicBlock *Header =3D ML->getHeader();
-      for (MachineBasicBlock::livein_iterator I =3D Header->livein_begin(),
-           E =3D Header->livein_end(); I !=3D E; ++I)
-        LoopLiveInRegs.insert(*I);
+    if (BB =3D=3D ML->getLoopLatch())
       LoopRegs.VisitLoop(ML);
-    }
 }
=20
-/// AddSchedBarrierDeps - Add dependencies from instructions in the current
+void ScheduleDAGInstrs::finishBlock() {
+  // Nothing to do.
+}
+
+/// Initialize the map with the number of registers.
+void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
+  PhysRegSet.setUniverse(Limit);
+  SUnits.resize(Limit);
+}
+
+/// Clear the map without deallocating storage.
+void Reg2SUnitsMap::clear() {
+  for (const_iterator I =3D reg_begin(), E =3D reg_end(); I !=3D E; ++I) {
+    SUnits[*I].clear();
+  }
+  PhysRegSet.clear();
+}
+
+/// Initialize the DAG and common scheduler state for the current scheduli=
ng
+/// region. This does not actually create the DAG, only clears it. The
+/// scheduling driver may call BuildSchedGraph multiple times per scheduli=
ng
+/// region.
+void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
+                                    MachineBasicBlock::iterator begin,
+                                    MachineBasicBlock::iterator end,
+                                    unsigned endcount) {
+  BB =3D bb;
+  RegionBegin =3D begin;
+  RegionEnd =3D end;
+  EndIndex =3D endcount;
+  MISUnitMap.clear();
+
+  // Check to see if the scheduler cares about latencies.
+  UnitLatencies =3D forceUnitLatencies();
+
+  ScheduleDAG::clearDAG();
+}
+
+/// Close the current scheduling region. Don't clear any state in case the
+/// driver wants to refer to the previous scheduling region.
+void ScheduleDAGInstrs::exitRegion() {
+  // Nothing to do.
+}
+
+/// addSchedBarrierDeps - Add dependencies from instructions in the current
 /// list of instructions being scheduled to scheduling barrier by adding
 /// the exit SU to the register defs and use list. This is because we want=
 to
 /// make sure instructions which define registers that are either used by
@@ -153,11 +185,11 @@
 /// especially important when the definition latency of the return value(s)
 /// are too high to be hidden by the branch or when the liveout registers
 /// used by instructions in the fallthrough block.
-void ScheduleDAGInstrs::AddSchedBarrierDeps() {
-  MachineInstr *ExitMI =3D InsertPos !=3D BB->end() ? &*InsertPos : 0;
+void ScheduleDAGInstrs::addSchedBarrierDeps() {
+  MachineInstr *ExitMI =3D RegionEnd !=3D BB->end() ? &*RegionEnd : 0;
   ExitSU.setInstr(ExitMI);
   bool AllDepKnown =3D ExitMI &&
-    (ExitMI->getDesc().isCall() || ExitMI->getDesc().isBarrier());
+    (ExitMI->isCall() || ExitMI->isBarrier());
   if (ExitMI && AllDepKnown) {
     // If it's a call or a barrier, add dependencies on the defs and uses =
of
     // instruction.
@@ -167,29 +199,313 @@
       unsigned Reg =3D MO.getReg();
       if (Reg =3D=3D 0) continue;
=20
-      assert(TRI->isPhysicalRegister(Reg) && "Virtual register encountered=
!");
-      Uses[Reg].push_back(&ExitSU);
+      if (TRI->isPhysicalRegister(Reg))
+        Uses[Reg].push_back(&ExitSU);
+      else {
+        assert(!IsPostRA && "Virtual register encountered after regalloc."=
);
+        addVRegUseDeps(&ExitSU, i);
+      }
     }
   } else {
     // For others, e.g. fallthrough, conditional branch, assume the exit
     // uses all the registers that are livein to the successor blocks.
-    SmallSet<unsigned, 8> Seen;
+    assert(Uses.empty() && "Uses in set before adding deps?");
     for (MachineBasicBlock::succ_iterator SI =3D BB->succ_begin(),
            SE =3D BB->succ_end(); SI !=3D SE; ++SI)
       for (MachineBasicBlock::livein_iterator I =3D (*SI)->livein_begin(),
              E =3D (*SI)->livein_end(); I !=3D E; ++I) {
         unsigned Reg =3D *I;
-        if (Seen.insert(Reg))
+        if (!Uses.contains(Reg))
           Uses[Reg].push_back(&ExitSU);
       }
   }
 }
=20
-void ScheduleDAGInstrs::BuildSchedGraph(AliasAnalysis *AA) {
-  // We'll be allocating one SUnit for each instruction, plus one for
-  // the region exit node.
+/// MO is an operand of SU's instruction that defines a physical register.=
 Add
+/// data dependencies from SU to any uses of the physical register.
+void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU,
+                                           const MachineOperand &MO) {
+  assert(MO.isDef() && "expect physreg def");
+
+  // Ask the target if address-backscheduling is desirable, and if so how =
much.
+  const TargetSubtargetInfo &ST =3D TM.getSubtarget<TargetSubtargetInfo>();
+  unsigned SpecialAddressLatency =3D ST.getSpecialAddressLatency();
+  unsigned DataLatency =3D SU->Latency;
+
+  for (const uint16_t *Alias =3D TRI->getOverlaps(MO.getReg()); *Alias; ++=
Alias) {
+    if (!Uses.contains(*Alias))
+      continue;
+    std::vector<SUnit*> &UseList =3D Uses[*Alias];
+    for (unsigned i =3D 0, e =3D UseList.size(); i !=3D e; ++i) {
+      SUnit *UseSU =3D UseList[i];
+      if (UseSU =3D=3D SU)
+        continue;
+      unsigned LDataLatency =3D DataLatency;
+      // Optionally add in a special extra latency for nodes that
+      // feed addresses.
+      // TODO: Perhaps we should get rid of
+      // SpecialAddressLatency and just move this into
+      // adjustSchedDependency for the targets that care about it.
+      if (SpecialAddressLatency !=3D 0 && !UnitLatencies &&
+          UseSU !=3D &ExitSU) {
+        MachineInstr *UseMI =3D UseSU->getInstr();
+        const MCInstrDesc &UseMCID =3D UseMI->getDesc();
+        int RegUseIndex =3D UseMI->findRegisterUseOperandIdx(*Alias);
+        assert(RegUseIndex >=3D 0 && "UseMI doesn't use register!");
+        if (RegUseIndex >=3D 0 &&
+            (UseMI->mayLoad() || UseMI->mayStore()) &&
+            (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
+            UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
+          LDataLatency +=3D SpecialAddressLatency;
+      }
+      // Adjust the dependence latency using operand def/use
+      // information (if any), and then allow the target to
+      // perform its own adjustments.
+      const SDep& dep =3D SDep(SU, SDep::Data, LDataLatency, *Alias);
+      if (!UnitLatencies) {
+        computeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
+        ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
+      }
+      UseSU->addPred(dep);
+    }
+  }
+}
+
+/// addPhysRegDeps - Add register dependencies (data, anti, and output) fr=
om
+/// this SUnit to following instructions in the same scheduling region that
+/// depend the physical register referenced at OperIdx.
+void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
+  const MachineInstr *MI =3D SU->getInstr();
+  const MachineOperand &MO =3D MI->getOperand(OperIdx);
+
+  // Optionally add output and anti dependencies. For anti
+  // dependencies we use a latency of 0 because for a multi-issue
+  // target we want to allow the defining instruction to issue
+  // in the same cycle as the using instruction.
+  // TODO: Using a latency of 1 here for output dependencies assumes
+  //       there's no cost for reusing registers.
+  SDep::Kind Kind =3D MO.isUse() ? SDep::Anti : SDep::Output;
+  for (const uint16_t *Alias =3D TRI->getOverlaps(MO.getReg()); *Alias; ++=
Alias) {
+    if (!Defs.contains(*Alias))
+      continue;
+    std::vector<SUnit *> &DefList =3D Defs[*Alias];
+    for (unsigned i =3D 0, e =3D DefList.size(); i !=3D e; ++i) {
+      SUnit *DefSU =3D DefList[i];
+      if (DefSU =3D=3D &ExitSU)
+        continue;
+      if (DefSU !=3D SU &&
+          (Kind !=3D SDep::Output || !MO.isDead() ||
+           !DefSU->getInstr()->registerDefIsDead(*Alias))) {
+        if (Kind =3D=3D SDep::Anti)
+          DefSU->addPred(SDep(SU, Kind, 0, /*Reg=3D*/*Alias));
+        else {
+          unsigned AOLat =3D TII->getOutputLatency(InstrItins, MI, OperIdx,
+                                                 DefSU->getInstr());
+          DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=3D*/*Alias));
+        }
+      }
+    }
+  }
+
+  if (!MO.isDef()) {
+    // Either insert a new Reg2SUnits entry with an empty SUnits list, or
+    // retrieve the existing SUnits list for this register's uses.
+    // Push this SUnit on the use list.
+    Uses[MO.getReg()].push_back(SU);
+  }
+  else {
+    addPhysRegDataDeps(SU, MO);
+
+    // Either insert a new Reg2SUnits entry with an empty SUnits list, or
+    // retrieve the existing SUnits list for this register's defs.
+    std::vector<SUnit *> &DefList =3D Defs[MO.getReg()];
+
+    // If a def is going to wrap back around to the top of the loop,
+    // backschedule it.
+    if (!UnitLatencies && DefList.empty()) {
+      LoopDependencies::LoopDeps::iterator I =3D LoopRegs.Deps.find(MO.get=
Reg());
+      if (I !=3D LoopRegs.Deps.end()) {
+        const MachineOperand *UseMO =3D I->second.first;
+        unsigned Count =3D I->second.second;
+        const MachineInstr *UseMI =3D UseMO->getParent();
+        unsigned UseMOIdx =3D UseMO - &UseMI->getOperand(0);
+        const MCInstrDesc &UseMCID =3D UseMI->getDesc();
+        const TargetSubtargetInfo &ST =3D
+          TM.getSubtarget<TargetSubtargetInfo>();
+        unsigned SpecialAddressLatency =3D ST.getSpecialAddressLatency();
+        // TODO: If we knew the total depth of the region here, we could
+        // handle the case where the whole loop is inside the region but
+        // is large enough that the isScheduleHigh trick isn't needed.
+        if (UseMOIdx < UseMCID.getNumOperands()) {
+          // Currently, we only support scheduling regions consisting of
+          // single basic blocks. Check to see if the instruction is in
+          // the same region by checking to see if it has the same parent.
+          if (UseMI->getParent() !=3D MI->getParent()) {
+            unsigned Latency =3D SU->Latency;
+            if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
+              Latency +=3D SpecialAddressLatency;
+            // This is a wild guess as to the portion of the latency which
+            // will be overlapped by work done outside the current
+            // scheduling region.
+            Latency -=3D std::min(Latency, Count);
+            // Add the artificial edge.
+            ExitSU.addPred(SDep(SU, SDep::Order, Latency,
+                                /*Reg=3D*/0, /*isNormalMemory=3D*/false,
+                                /*isMustAlias=3D*/false,
+                                /*isArtificial=3D*/true));
+          } else if (SpecialAddressLatency > 0 &&
+                     UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
+            // The entire loop body is within the current scheduling region
+            // and the latency of this operation is assumed to be greater
+            // than the latency of the loop.
+            // TODO: Recursively mark data-edge predecessors as
+            //       isScheduleHigh too.
+            SU->isScheduleHigh =3D true;
+          }
+        }
+        LoopRegs.Deps.erase(I);
+      }
+    }
+
+    // clear this register's use list
+    if (Uses.contains(MO.getReg()))
+      Uses[MO.getReg()].clear();
+
+    if (!MO.isDead())
+      DefList.clear();
+
+    // Calls will not be reordered because of chain dependencies (see
+    // below). Since call operands are dead, calls may continue to be added
+    // to the DefList making dependence checking quadratic in the size of
+    // the block. Instead, we leave only one call at the back of the
+    // DefList.
+    if (SU->isCall) {
+      while (!DefList.empty() && DefList.back()->isCall)
+        DefList.pop_back();
+    }
+    // Defs are pushed in the order they are visited and never reordered.
+    DefList.push_back(SU);
+  }
+}
+
+/// addVRegDefDeps - Add register output and data dependencies from this S=
Unit
+/// to instructions that occur later in the same scheduling region if they=
 read
+/// from or write to the virtual register defined at OperIdx.
+///
+/// TODO: Hoist loop induction variable increments. This has to be
+/// reevaluated. Generally, IV scheduling should be done before coalescing.
+void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
+  const MachineInstr *MI =3D SU->getInstr();
+  unsigned Reg =3D MI->getOperand(OperIdx).getReg();
+
+  // SSA defs do not have output/anti dependencies.
+  // The current operand is a def, so we have at least one.
+  if (llvm::next(MRI.def_begin(Reg)) =3D=3D MRI.def_end())
+    return;
+
+  // Add output dependence to the next nearest def of this vreg.
+  //
+  // Unless this definition is dead, the output dependence should be
+  // transitively redundant with antidependencies from this definition's
+  // uses. We're conservative for now until we have a way to guarantee the=
 uses
+  // are not eliminated sometime during scheduling. The output dependence =
edge
+  // is also useful if output latency exceeds def-use latency.
+  VReg2SUnitMap::iterator DefI =3D findVRegDef(Reg);
+  if (DefI =3D=3D VRegDefs.end())
+    VRegDefs.insert(VReg2SUnit(Reg, SU));
+  else {
+    SUnit *DefSU =3D DefI->SU;
+    if (DefSU !=3D SU && DefSU !=3D &ExitSU) {
+      unsigned OutLatency =3D TII->getOutputLatency(InstrItins, MI, OperId=
x,
+                                                  DefSU->getInstr());
+      DefSU->addPred(SDep(SU, SDep::Output, OutLatency, Reg));
+    }
+    DefI->SU =3D SU;
+  }
+}
+
+/// addVRegUseDeps - Add a register data dependency if the instruction that
+/// defines the virtual register used at OperIdx is mapped to an SUnit. Ad=
d a
+/// register antidependency from this SUnit to instructions that occur lat=
er in
+/// the same scheduling region if they write the virtual register.
+///
+/// TODO: Handle ExitSU "uses" properly.
+void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
+  MachineInstr *MI =3D SU->getInstr();
+  unsigned Reg =3D MI->getOperand(OperIdx).getReg();
+
+  // Lookup this operand's reaching definition.
+  assert(LIS && "vreg dependencies requires LiveIntervals");
+  SlotIndex UseIdx =3D LIS->getInstructionIndex(MI).getRegSlot();
+  LiveInterval *LI =3D &LIS->getInterval(Reg);
+  VNInfo *VNI =3D LI->getVNInfoBefore(UseIdx);
+  // VNI will be valid because MachineOperand::readsReg() is checked by ca=
ller.
+  MachineInstr *Def =3D LIS->getInstructionFromIndex(VNI->def);
+  // Phis and other noninstructions (after coalescing) have a NULL Def.
+  if (Def) {
+    SUnit *DefSU =3D getSUnit(Def);
+    if (DefSU) {
+      // The reaching Def lives within this scheduling region.
+      // Create a data dependence.
+      //
+      // TODO: Handle "special" address latencies cleanly.
+      const SDep &dep =3D SDep(DefSU, SDep::Data, DefSU->Latency, Reg);
+      if (!UnitLatencies) {
+        // Adjust the dependence latency using operand def/use information=
, then
+        // allow the target to perform its own adjustments.
+        computeOperandLatency(DefSU, SU, const_cast<SDep &>(dep));
+        const TargetSubtargetInfo &ST =3D TM.getSubtarget<TargetSubtargetI=
nfo>();
+        ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
+      }
+      SU->addPred(dep);
+    }
+  }
+
+  // Add antidependence to the following def of the vreg it uses.
+  VReg2SUnitMap::iterator DefI =3D findVRegDef(Reg);
+  if (DefI !=3D VRegDefs.end() && DefI->SU !=3D SU)
+    DefI->SU->addPred(SDep(SU, SDep::Anti, 0, Reg));
+}
+
+/// Create an SUnit for each real instruction, numbered in top-down toplol=
ogical
+/// order. The instruction order A < B, implies that no edge exists from B=
 to A.
+///
+/// Map each real instruction to its SUnit.
+///
+/// After initSUnits, the SUnits vector cannot be resized and the schedule=
r may
+/// hang onto SUnit pointers. We may relax this in the future by using SUn=
it IDs
+/// instead of pointers.
+///
+/// MachineScheduler relies on initSUnits numbering the nodes by their ord=
er in
+/// the original instruction list.
+void ScheduleDAGInstrs::initSUnits() {
+  // We'll be allocating one SUnit for each real instruction in the region,
+  // which is contained within a basic block.
   SUnits.reserve(BB->size());
=20
+  for (MachineBasicBlock::iterator I =3D RegionBegin; I !=3D RegionEnd; ++=
I) {
+    MachineInstr *MI =3D I;
+    if (MI->isDebugValue())
+      continue;
+
+    SUnit *SU =3D newSUnit(MI);
+    MISUnitMap[MI] =3D SU;
+
+    SU->isCall =3D MI->isCall();
+    SU->isCommutable =3D MI->isCommutable();
+
+    // Assign the Latency field of SU using target-provided information.
+    if (UnitLatencies)
+      SU->Latency =3D 1;
+    else
+      computeLatency(SU);
+  }
+}
+
+void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA) {
+  // Create an SUnit for each real instruction.
+  initSUnits();
+
   // We build scheduling units by walking a block's instruction list from =
bottom
   // to top.
=20
@@ -203,29 +519,29 @@
   std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
   std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMem=
Uses;
=20
-  // Check to see if the scheduler cares about latencies.
-  bool UnitLatencies =3D ForceUnitLatencies();
-
-  // Ask the target if address-backscheduling is desirable, and if so how =
much.
-  const TargetSubtargetInfo &ST =3D TM.getSubtarget<TargetSubtargetInfo>();
-  unsigned SpecialAddressLatency =3D ST.getSpecialAddressLatency();
-
   // Remove any stale debug info; sometimes BuildSchedGraph is called again
   // without emitting the info from the previous call.
   DbgValues.clear();
   FirstDbgValue =3D NULL;
=20
+  assert(Defs.empty() && Uses.empty() &&
+         "Only BuildGraph should update Defs/Uses");
+  Defs.setRegLimit(TRI->getNumRegs());
+  Uses.setRegLimit(TRI->getNumRegs());
+
+  assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
+  // FIXME: Allow SparseSet to reserve space for the creation of virtual
+  // registers during scheduling. Don't artificially inflate the Universe
+  // because we want to assert that vregs are not created during DAG build=
ing.
+  VRegDefs.setUniverse(MRI.getNumVirtRegs());
+
   // Model data dependencies between instructions being scheduled and the
   // ExitSU.
-  AddSchedBarrierDeps();
-
-  for (int i =3D 0, e =3D TRI->getNumRegs(); i !=3D e; ++i) {
-    assert(Defs[i].empty() && "Only BuildGraph should push/pop Defs");
-  }
+  addSchedBarrierDeps();
=20
   // Walk the list of instructions, from bottom moving up.
   MachineInstr *PrevMI =3D NULL;
-  for (MachineBasicBlock::iterator MII =3D InsertPos, MIE =3D Begin;
+  for (MachineBasicBlock::iterator MII =3D RegionEnd, MIE =3D RegionBegin;
        MII !=3D MIE; --MII) {
     MachineInstr *MI =3D prior(MII);
     if (MI && PrevMI) {
@@ -238,19 +554,11 @@
       continue;
     }
=20
-    const MCInstrDesc &MCID =3D MI->getDesc();
-    assert(!MCID.isTerminator() && !MI->isLabel() &&
+    assert(!MI->isTerminator() && !MI->isLabel() &&
            "Cannot schedule terminators or labels!");
-    // Create the SUnit for this MI.
-    SUnit *SU =3D NewSUnit(MI);
-    SU->isCall =3D MCID.isCall();
-    SU->isCommutable =3D MCID.isCommutable();
=20
-    // Assign the Latency field of SU using target-provided information.
-    if (UnitLatencies)
-      SU->Latency =3D 1;
-    else
-      ComputeLatency(SU);
+    SUnit *SU =3D MISUnitMap[MI];
+    assert(SU && "No SUnit mapped to this MI");
=20
     // Add register-based dependencies (data, anti, and output).
     for (unsigned j =3D 0, n =3D MI->getNumOperands(); j !=3D n; ++j) {
@@ -259,152 +567,14 @@
       unsigned Reg =3D MO.getReg();
       if (Reg =3D=3D 0) continue;
=20
-      assert(TRI->isPhysicalRegister(Reg) && "Virtual register encountered=
!");
-
-      std::vector<SUnit *> &UseList =3D Uses[Reg];
-      // Defs are push in the order they are visited and never reordered.
-      std::vector<SUnit *> &DefList =3D Defs[Reg];
-      // Optionally add output and anti dependencies. For anti
-      // dependencies we use a latency of 0 because for a multi-issue
-      // target we want to allow the defining instruction to issue
-      // in the same cycle as the using instruction.
-      // TODO: Using a latency of 1 here for output dependencies assumes
-      //       there's no cost for reusing registers.
-      SDep::Kind Kind =3D MO.isUse() ? SDep::Anti : SDep::Output;
-      unsigned AOLatency =3D (Kind =3D=3D SDep::Anti) ? 0 : 1;
-      for (unsigned i =3D 0, e =3D DefList.size(); i !=3D e; ++i) {
-        SUnit *DefSU =3D DefList[i];
-        if (DefSU =3D=3D &ExitSU)
-          continue;
-        if (DefSU !=3D SU &&
-            (Kind !=3D SDep::Output || !MO.isDead() ||
-             !DefSU->getInstr()->registerDefIsDead(Reg)))
-          DefSU->addPred(SDep(SU, Kind, AOLatency, /*Reg=3D*/Reg));
-      }
-      for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alia=
s) {
-        std::vector<SUnit *> &MemDefList =3D Defs[*Alias];
-        for (unsigned i =3D 0, e =3D MemDefList.size(); i !=3D e; ++i) {
-          SUnit *DefSU =3D MemDefList[i];
-          if (DefSU =3D=3D &ExitSU)
-            continue;
-          if (DefSU !=3D SU &&
-              (Kind !=3D SDep::Output || !MO.isDead() ||
-               !DefSU->getInstr()->registerDefIsDead(*Alias)))
-            DefSU->addPred(SDep(SU, Kind, AOLatency, /*Reg=3D*/ *Alias));
-        }
-      }
-
-      if (MO.isDef()) {
-        // Add any data dependencies.
-        unsigned DataLatency =3D SU->Latency;
-        for (unsigned i =3D 0, e =3D UseList.size(); i !=3D e; ++i) {
-          SUnit *UseSU =3D UseList[i];
-          if (UseSU =3D=3D SU)
-            continue;
-          unsigned LDataLatency =3D DataLatency;
-          // Optionally add in a special extra latency for nodes that
-          // feed addresses.
-          // TODO: Do this for register aliases too.
-          // TODO: Perhaps we should get rid of
-          // SpecialAddressLatency and just move this into
-          // adjustSchedDependency for the targets that care about it.
-          if (SpecialAddressLatency !=3D 0 && !UnitLatencies &&
-              UseSU !=3D &ExitSU) {
-            MachineInstr *UseMI =3D UseSU->getInstr();
-            const MCInstrDesc &UseMCID =3D UseMI->getDesc();
-            int RegUseIndex =3D UseMI->findRegisterUseOperandIdx(Reg);
-            assert(RegUseIndex >=3D 0 && "UseMI doesn's use register!");
-            if (RegUseIndex >=3D 0 &&
-                (UseMCID.mayLoad() || UseMCID.mayStore()) &&
-                (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
-                UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
-              LDataLatency +=3D SpecialAddressLatency;
-          }
-          // Adjust the dependence latency using operand def/use
-          // information (if any), and then allow the target to
-          // perform its own adjustments.
-          const SDep& dep =3D SDep(SU, SDep::Data, LDataLatency, Reg);
-          if (!UnitLatencies) {
-            ComputeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
-            ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
-          }
-          UseSU->addPred(dep);
-        }
-        for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Al=
ias) {
-          std::vector<SUnit *> &UseList =3D Uses[*Alias];
-          for (unsigned i =3D 0, e =3D UseList.size(); i !=3D e; ++i) {
-            SUnit *UseSU =3D UseList[i];
-            if (UseSU =3D=3D SU)
-              continue;
-            const SDep& dep =3D SDep(SU, SDep::Data, DataLatency, *Alias);
-            if (!UnitLatencies) {
-              ComputeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
-              ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
-            }
-            UseSU->addPred(dep);
-          }
-        }
-
-        // If a def is going to wrap back around to the top of the loop,
-        // backschedule it.
-        if (!UnitLatencies && DefList.empty()) {
-          LoopDependencies::LoopDeps::iterator I =3D LoopRegs.Deps.find(Re=
g);
-          if (I !=3D LoopRegs.Deps.end()) {
-            const MachineOperand *UseMO =3D I->second.first;
-            unsigned Count =3D I->second.second;
-            const MachineInstr *UseMI =3D UseMO->getParent();
-            unsigned UseMOIdx =3D UseMO - &UseMI->getOperand(0);
-            const MCInstrDesc &UseMCID =3D UseMI->getDesc();
-            // TODO: If we knew the total depth of the region here, we cou=
ld
-            // handle the case where the whole loop is inside the region b=
ut
-            // is large enough that the isScheduleHigh trick isn't needed.
-            if (UseMOIdx < UseMCID.getNumOperands()) {
-              // Currently, we only support scheduling regions consisting =
of
-              // single basic blocks. Check to see if the instruction is in
-              // the same region by checking to see if it has the same par=
ent.
-              if (UseMI->getParent() !=3D MI->getParent()) {
-                unsigned Latency =3D SU->Latency;
-                if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
-                  Latency +=3D SpecialAddressLatency;
-                // This is a wild guess as to the portion of the latency w=
hich
-                // will be overlapped by work done outside the current
-                // scheduling region.
-                Latency -=3D std::min(Latency, Count);
-                // Add the artificial edge.
-                ExitSU.addPred(SDep(SU, SDep::Order, Latency,
-                                    /*Reg=3D*/0, /*isNormalMemory=3D*/fals=
e,
-                                    /*isMustAlias=3D*/false,
-                                    /*isArtificial=3D*/true));
-              } else if (SpecialAddressLatency > 0 &&
-                         UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
-                // The entire loop body is within the current scheduling r=
egion
-                // and the latency of this operation is assumed to be grea=
ter
-                // than the latency of the loop.
-                // TODO: Recursively mark data-edge predecessors as
-                //       isScheduleHigh too.
-                SU->isScheduleHigh =3D true;
-              }
-            }
-            LoopRegs.Deps.erase(I);
-          }
-        }
-
-        UseList.clear();
-        if (!MO.isDead())
-          DefList.clear();
-
-        // Calls will not be reordered because of chain dependencies (see
-        // below). Since call operands are dead, calls may continue to be =
added
-        // to the DefList making dependence checking quadratic in the size=
 of
-        // the block. Instead, we leave only one call at the back of the
-        // DefList.
-        if (SU->isCall) {
-          while (!DefList.empty() && DefList.back()->isCall)
-            DefList.pop_back();
-        }
-        DefList.push_back(SU);
-      } else {
-        UseList.push_back(SU);
+      if (TRI->isPhysicalRegister(Reg))
+        addPhysRegDeps(SU, j);
+      else {
+        assert(!IsPostRA && "Virtual register encountered!");
+        if (MO.isDef())
+          addVRegDefDeps(SU, j);
+        else if (MO.readsReg()) // ignore undef operands
+          addVRegUseDeps(SU, j);
       }
     }
=20
@@ -419,9 +589,9 @@
     // produce more precise dependence information.
 #define STORE_LOAD_LATENCY 1
     unsigned TrueMemOrderLatency =3D 0;
-    if (MCID.isCall() || MI->hasUnmodeledSideEffects() ||
+    if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
         (MI->hasVolatileMemoryRef() &&
-         (!MCID.mayLoad() || !MI->isInvariantLoad(AA)))) {
+         (!MI->mayLoad() || !MI->isInvariantLoad(AA)))) {
       // Be conservative with these and add dependencies on all memory
       // references, even those that are known to not alias.
       for (std::map<const Value *, SUnit *>::iterator I =3D
@@ -460,7 +630,7 @@
       PendingLoads.clear();
       AliasMemDefs.clear();
       AliasMemUses.clear();
-    } else if (MCID.mayStore()) {
+    } else if (MI->mayStore()) {
       bool MayAlias =3D true;
       TrueMemOrderLatency =3D STORE_LOAD_LATENCY;
       if (const Value *V =3D getUnderlyingObjectForInstr(MI, MFI, MayAlias=
)) {
@@ -516,7 +686,7 @@
                             /*Reg=3D*/0, /*isNormalMemory=3D*/false,
                             /*isMustAlias=3D*/false,
                             /*isArtificial=3D*/true));
-    } else if (MCID.mayLoad()) {
+    } else if (MI->mayLoad()) {
       bool MayAlias =3D true;
       TrueMemOrderLatency =3D 0;
       if (MI->isInvariantLoad(AA)) {
@@ -558,32 +728,27 @@
   if (PrevMI)
     FirstDbgValue =3D PrevMI;
=20
-  for (int i =3D 0, e =3D TRI->getNumRegs(); i !=3D e; ++i) {
-    Defs[i].clear();
-    Uses[i].clear();
-  }
+  Defs.clear();
+  Uses.clear();
+  VRegDefs.clear();
   PendingLoads.clear();
 }
=20
-void ScheduleDAGInstrs::FinishBlock() {
-  // Nothing to do.
-}
-
-void ScheduleDAGInstrs::ComputeLatency(SUnit *SU) {
+void ScheduleDAGInstrs::computeLatency(SUnit *SU) {
   // Compute the latency for the node.
   if (!InstrItins || InstrItins->isEmpty()) {
     SU->Latency =3D 1;
=20
     // Simplistic target-independent heuristic: assume that loads take
     // extra time.
-    if (SU->getInstr()->getDesc().mayLoad())
+    if (SU->getInstr()->mayLoad())
       SU->Latency +=3D 2;
   } else {
     SU->Latency =3D TII->getInstrLatency(InstrItins, SU->getInstr());
   }
 }
=20
-void ScheduleDAGInstrs::ComputeOperandLatency(SUnit *Def, SUnit *Use,
+void ScheduleDAGInstrs::computeOperandLatency(SUnit *Def, SUnit *Use,
                                               SDep& dep) const {
   if (!InstrItins || InstrItins->isEmpty())
     return;
@@ -608,7 +773,9 @@
       //   %Q1<def> =3D VMULv8i16 %Q1<kill>, %Q3<kill>, ...
       // What we want is to compute latency between def of %D6/%D7 and use=
 of
       // %Q3 instead.
-      DefIdx =3D DefMI->findRegisterDefOperandIdx(Reg, false, true, TRI);
+      unsigned Op2 =3D DefMI->findRegisterDefOperandIdx(Reg, false, true, =
TRI);
+      if (DefMI->getOperand(Op2).isReg())
+        DefIdx =3D Op2;
     }
     MachineInstr *UseMI =3D Use->getInstr();
     // For all uses of the register, calculate the maxmimum latency
@@ -656,43 +823,8 @@
   return oss.str();
 }
=20
-// EmitSchedule - Emit the machine code in scheduled order.
-MachineBasicBlock *ScheduleDAGInstrs::EmitSchedule() {
-  // For MachineInstr-based scheduling, we're rescheduling the instruction=
s in
-  // the block, so start by removing them from the block.
-  while (Begin !=3D InsertPos) {
-    MachineBasicBlock::iterator I =3D Begin;
-    ++Begin;
-    BB->remove(I);
-  }
-
-  // If first instruction was a DBG_VALUE then put it back.
-  if (FirstDbgValue)
-    BB->insert(InsertPos, FirstDbgValue);
-
-  // Then re-insert them according to the given schedule.
-  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; i++) {
-    if (SUnit *SU =3D Sequence[i])
-      BB->insert(InsertPos, SU->getInstr());
-    else
-      // Null SUnit* is a noop.
-      EmitNoop();
-  }
-
-  // Update the Begin iterator, as the first instruction in the block
-  // may have been scheduled later.
-  if (!Sequence.empty())
-    Begin =3D Sequence[0]->getInstr();
-
-  // Reinsert any remaining debug_values.
-  for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
-         DI =3D DbgValues.end(), DE =3D DbgValues.begin(); DI !=3D DE; --D=
I) {
-    std::pair<MachineInstr *, MachineInstr *> P =3D *prior(DI);
-    MachineInstr *DbgValue =3D P.first;
-    MachineInstr *OrigPrivMI =3D P.second;
-    BB->insertAfter(OrigPrivMI, DbgValue);
-  }
-  DbgValues.clear();
-  FirstDbgValue =3D NULL;
-  return BB;
+/// Return the basic block label. It is not necessarilly unique because a =
block
+/// contains multiple scheduling regions. But it is fine for visualization.
+std::string ScheduleDAGInstrs::getDAGName() const {
+  return "dag." + BB->getFullName();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Schedule=
DAGPrinter.cpp
--- a/head/contrib/llvm/lib/CodeGen/ScheduleDAGPrinter.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ScheduleDAGPrinter.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -25,7 +25,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/StringExtras.h"
-#include "llvm/Config/config.h"
 #include <fstream>
 using namespace llvm;
=20
@@ -42,12 +41,12 @@
     static bool renderGraphFromBottomUp() {
       return true;
     }
-   =20
+
     static bool hasNodeAddressLabel(const SUnit *Node,
                                     const ScheduleDAG *Graph) {
       return true;
     }
-   =20
+
     /// If you want to override the dot attributes printed for a particular
     /// edge, override this method.
     static std::string getEdgeAttributes(const SUnit *Node,
@@ -59,7 +58,7 @@
         return "color=3Dblue,style=3Ddashed";
       return "";
     }
-   =20
+
=20
     std::string getNodeLabel(const SUnit *Node, const ScheduleDAG *Graph);
     static std::string getNodeAttributes(const SUnit *N,
@@ -82,18 +81,17 @@
 /// viewGraph - Pop up a ghostview window with the reachable parts of the =
DAG
 /// rendered using 'dot'.
 ///
-void ScheduleDAG::viewGraph() {
-// This code is only for debugging!
+void ScheduleDAG::viewGraph(const Twine &Name, const Twine &Title) {
+  // This code is only for debugging!
 #ifndef NDEBUG
-  if (BB->getBasicBlock())
-    ViewGraph(this, "dag." + MF.getFunction()->getNameStr(), false,
-              "Scheduling-Units Graph for " + MF.getFunction()->getNameStr=
() +=20
-              ":" + BB->getBasicBlock()->getNameStr());
-  else
-    ViewGraph(this, "dag." + MF.getFunction()->getNameStr(), false,
-              "Scheduling-Units Graph for " + MF.getFunction()->getNameStr=
());
+  ViewGraph(this, Name, false, Title);
 #else
   errs() << "ScheduleDAG::viewGraph is only available in debug builds on "
          << "systems with Graphviz or gv!\n";
 #endif  // NDEBUG
 }
+
+/// Out-of-line implementation with no arguments is handy for gdb.
+void ScheduleDAG::viewGraph() {
+  viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Scoreboa=
rdHazardRecognizer.cpp
--- a/head/contrib/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ScoreboardHazardRecognizer.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -140,8 +140,6 @@
=20
       unsigned freeUnits =3D IS->getUnits();
       switch (IS->getReservationKind()) {
-      default:
-       assert(0 && "Invalid FU reservation");
       case InstrStage::Required:
         // Required FUs conflict with both reserved and required ones
         freeUnits &=3D ~ReservedScoreboard[StageCycle];
@@ -194,8 +192,6 @@
=20
       unsigned freeUnits =3D IS->getUnits();
       switch (IS->getReservationKind()) {
-      default:
-       assert(0 && "Invalid FU reservation");
       case InstrStage::Required:
         // Required FUs conflict with both reserved and required ones
         freeUnits &=3D ~ReservedScoreboard[cycle + i];
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/DAGCombiner.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -22,7 +22,6 @@
 #include "llvm/LLVMContext.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetLowering.h"
@@ -64,7 +63,24 @@
     bool LegalTypes;
=20
     // Worklist of all of the nodes that need to be simplified.
-    std::vector<SDNode*> WorkList;
+    //
+    // This has the semantics that when adding to the worklist,
+    // the item added must be next to be processed. It should
+    // also only appear once. The naive approach to this takes
+    // linear time.
+    //
+    // To reduce the insert/remove time to logarithmic, we use
+    // a set and a vector to maintain our worklist.
+    //
+    // The set contains the items on the worklist, but does not
+    // maintain the order they should be visited.
+    //
+    // The vector maintains the order nodes should be visited, but may
+    // contain duplicate or removed nodes. When choosing a node to
+    // visit, we pop off the order stack until we find an item that is
+    // also in the contents set. All operations are O(log N).
+    SmallPtrSet<SDNode*, 64> WorkListContents;
+    SmallVector<SDNode*, 64> WorkListOrder;
=20
     // AA - Used for DAG load/store alias analysis.
     AliasAnalysis &AA;
@@ -84,18 +100,17 @@
     SDValue visit(SDNode *N);
=20
   public:
-    /// AddToWorkList - Add to the work list making sure it's instance is =
at the
-    /// the back (next to be processed.)
+    /// AddToWorkList - Add to the work list making sure its instance is a=
t the
+    /// back (next to be processed.)
     void AddToWorkList(SDNode *N) {
-      removeFromWorkList(N);
-      WorkList.push_back(N);
+      WorkListContents.insert(N);
+      WorkListOrder.push_back(N);
     }
=20
     /// removeFromWorkList - remove all instances of N from the worklist.
     ///
     void removeFromWorkList(SDNode *N) {
-      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
-                     WorkList.end());
+      WorkListContents.erase(N);
     }
=20
     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
@@ -159,7 +174,9 @@
     SDValue visitADD(SDNode *N);
     SDValue visitSUB(SDNode *N);
     SDValue visitADDC(SDNode *N);
+    SDValue visitSUBC(SDNode *N);
     SDValue visitADDE(SDNode *N);
+    SDValue visitSUBE(SDNode *N);
     SDValue visitMUL(SDNode *N);
     SDValue visitSDIV(SDNode *N);
     SDValue visitUDIV(SDNode *N);
@@ -181,7 +198,9 @@
     SDValue visitSRA(SDNode *N);
     SDValue visitSRL(SDNode *N);
     SDValue visitCTLZ(SDNode *N);
+    SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
     SDValue visitCTTZ(SDNode *N);
+    SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
     SDValue visitCTPOP(SDNode *N);
     SDValue visitSELECT(SDNode *N);
     SDValue visitSELECT_CC(SDNode *N);
@@ -279,7 +298,7 @@
=20
   public:
     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
-      : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
+      : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
=20
     /// Run - runs the dag combiner on all nodes in the work list
@@ -362,6 +381,8 @@
 /// specified expression for the same cost as the expression itself, or 2 =
if we
 /// can compute the negated form more cheaply than the expression itself.
 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
+                               const TargetLowering &TLI,
+                               const TargetOptions *Options,
                                unsigned Depth =3D 0) {
   // No compile time optimizations on this type.
   if (Op.getValueType() =3D=3D MVT::ppcf128)
@@ -384,34 +405,44 @@
     return LegalOperations ? 0 : 1;
   case ISD::FADD:
     // FIXME: determine better conditions for this xform.
-    if (!UnsafeFPMath) return 0;
+    if (!Options->UnsafeFPMath) return 0;
+
+    // After operation legalization, it might not be legal to create new F=
SUBs.
+    if (LegalOperations &&
+        !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
+      return 0;
=20
     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
-    if (char V =3D isNegatibleForFree(Op.getOperand(0), LegalOperations, D=
epth+1))
+    if (char V =3D isNegatibleForFree(Op.getOperand(0), LegalOperations, T=
LI,
+                                    Options, Depth + 1))
       return V;
     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
-    return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
+    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Opti=
ons,
+                              Depth + 1);
   case ISD::FSUB:
     // We can't turn -(A-B) into B-A when we honor signed zeros.
-    if (!UnsafeFPMath) return 0;
+    if (!Options->UnsafeFPMath) return 0;
=20
     // fold (fneg (fsub A, B)) -> (fsub B, A)
     return 1;
=20
   case ISD::FMUL:
   case ISD::FDIV:
-    if (HonorSignDependentRoundingFPMath()) return 0;
+    if (Options->HonorSignDependentRoundingFPMath()) return 0;
=20
     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
-    if (char V =3D isNegatibleForFree(Op.getOperand(0), LegalOperations, D=
epth+1))
+    if (char V =3D isNegatibleForFree(Op.getOperand(0), LegalOperations, T=
LI,
+                                    Options, Depth + 1))
       return V;
=20
-    return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
+    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Opti=
ons,
+                              Depth + 1);
=20
   case ISD::FP_EXTEND:
   case ISD::FP_ROUND:
   case ISD::FSIN:
-    return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
+    return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Opti=
ons,
+                              Depth + 1);
   }
 }
=20
@@ -435,10 +466,12 @@
   }
   case ISD::FADD:
     // FIXME: determine better conditions for this xform.
-    assert(UnsafeFPMath);
+    assert(DAG.getTarget().Options.UnsafeFPMath);
=20
     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
-    if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
+    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
+                           DAG.getTargetLoweringInfo(),
+                           &DAG.getTarget().Options, Depth+1))
       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
                          GetNegatedExpression(Op.getOperand(0), DAG,
                                               LegalOperations, Depth+1),
@@ -450,7 +483,7 @@
                        Op.getOperand(0));
   case ISD::FSUB:
     // We can't turn -(A-B) into B-A when we honor signed zeros.
-    assert(UnsafeFPMath);
+    assert(DAG.getTarget().Options.UnsafeFPMath);
=20
     // fold (fneg (fsub 0, B)) -> B
     if (ConstantFPSDNode *N0CFP =3D dyn_cast<ConstantFPSDNode>(Op.getOpera=
nd(0)))
@@ -463,10 +496,12 @@
=20
   case ISD::FMUL:
   case ISD::FDIV:
-    assert(!HonorSignDependentRoundingFPMath());
+    assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
=20
     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
-    if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
+    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
+                           DAG.getTargetLoweringInfo(),
+                           &DAG.getTarget().Options, Depth+1))
       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType=
(),
                          GetNegatedExpression(Op.getOperand(0), DAG,
                                               LegalOperations, Depth+1),
@@ -944,14 +979,13 @@
 void DAGCombiner::Run(CombineLevel AtLevel) {
   // set the instance variables, so that the various visit routines may us=
e it.
   Level =3D AtLevel;
-  LegalOperations =3D Level >=3D NoIllegalOperations;
-  LegalTypes =3D Level >=3D NoIllegalTypes;
+  LegalOperations =3D Level >=3D AfterLegalizeVectorOps;
+  LegalTypes =3D Level >=3D AfterLegalizeTypes;
=20
   // Add all the dag nodes to the worklist.
-  WorkList.reserve(DAG.allnodes_size());
   for (SelectionDAG::allnodes_iterator I =3D DAG.allnodes_begin(),
        E =3D DAG.allnodes_end(); I !=3D E; ++I)
-    WorkList.push_back(I);
+    AddToWorkList(I);
=20
   // Create a dummy node (which is not added to allnodes), that adds a ref=
erence
   // to the root node, preventing it from being deleted, and tracking any
@@ -962,11 +996,17 @@
   // done.  Set it to null to avoid confusion.
   DAG.setRoot(SDValue());
=20
-  // while the worklist isn't empty, inspect the node on the end of it and
+  // while the worklist isn't empty, find a node and
   // try and combine it.
-  while (!WorkList.empty()) {
-    SDNode *N =3D WorkList.back();
-    WorkList.pop_back();
+  while (!WorkListContents.empty()) {
+    SDNode *N;
+    // The WorkListOrder holds the SDNodes in order, but it may contain du=
plicates.
+    // In order to avoid a linear scan, we use a set (O(log N)) to hold wh=
at the
+    // worklist *should* contain, and check the node we want to visit is s=
hould
+    // actually be visited.
+    do {
+      N =3D WorkListOrder.pop_back_val();
+    } while (!WorkListContents.erase(N));
=20
     // If N has no uses, it is dead.  Make sure to revisit all N's operand=
s once
     // N is deleted from the DAG, since they too may now be dead or may ha=
ve a
@@ -1050,7 +1090,9 @@
   case ISD::ADD:                return visitADD(N);
   case ISD::SUB:                return visitSUB(N);
   case ISD::ADDC:               return visitADDC(N);
+  case ISD::SUBC:               return visitSUBC(N);
   case ISD::ADDE:               return visitADDE(N);
+  case ISD::SUBE:               return visitSUBE(N);
   case ISD::MUL:                return visitMUL(N);
   case ISD::SDIV:               return visitSDIV(N);
   case ISD::UDIV:               return visitUDIV(N);
@@ -1071,7 +1113,9 @@
   case ISD::SRA:                return visitSRA(N);
   case ISD::SRL:                return visitSRL(N);
   case ISD::CTLZ:               return visitCTLZ(N);
+  case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
   case ISD::CTTZ:               return visitCTTZ(N);
+  case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
   case ISD::CTPOP:              return visitCTPOP(N);
   case ISD::SELECT:             return visitSELECT(N);
   case ISD::SELECT_CC:          return visitSELECT_CC(N);
@@ -1408,16 +1452,14 @@
   if (VT.isInteger() && !VT.isVector()) {
     APInt LHSZero, LHSOne;
     APInt RHSZero, RHSOne;
-    APInt Mask =3D APInt::getAllOnesValue(VT.getScalarType().getSizeInBits=
());
-    DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
+    DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
=20
     if (LHSZero.getBoolValue()) {
-      DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
+      DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
=20
       // If all possibly-set bits on the LHS are clear on the RHS, return =
an OR.
       // If all possibly-set bits on the RHS are clear on the LHS, return =
an OR.
-      if ((RHSZero & (~LHSZero & Mask)) =3D=3D (~LHSZero & Mask) ||
-          (LHSZero & (~RHSZero & Mask)) =3D=3D (~RHSZero & Mask))
+      if ((RHSZero & ~LHSZero) =3D=3D ~LHSZero || (LHSZero & ~RHSZero) =3D=
=3D ~RHSZero)
         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
     }
   }
@@ -1486,8 +1528,8 @@
   EVT VT =3D N0.getValueType();
=20
   // If the flag result is dead, turn this into an ADD.
-  if (N->hasNUsesOfValue(0, 1))
-    return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0=
),
+  if (!N->hasAnyUseOfValue(1))
+    return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1=
),
                      DAG.getNode(ISD::CARRY_FALSE,
                                  N->getDebugLoc(), MVT::Glue));
=20
@@ -1503,16 +1545,14 @@
   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
   APInt LHSZero, LHSOne;
   APInt RHSZero, RHSOne;
-  APInt Mask =3D APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()=
);
-  DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
+  DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
=20
   if (LHSZero.getBoolValue()) {
-    DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
+    DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
=20
     // If all possibly-set bits on the LHS are clear on the RHS, return an=
 OR.
     // If all possibly-set bits on the RHS are clear on the LHS, return an=
 OR.
-    if ((RHSZero & (~LHSZero & Mask)) =3D=3D (~LHSZero & Mask) ||
-        (LHSZero & (~RHSZero & Mask)) =3D=3D (~RHSZero & Mask))
+    if ((RHSZero & ~LHSZero) =3D=3D ~LHSZero || (LHSZero & ~RHSZero) =3D=
=3D ~RHSZero)
       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N=
1),
                        DAG.getNode(ISD::CARRY_FALSE,
                                    N->getDebugLoc(), MVT::Glue));
@@ -1535,7 +1575,7 @@
=20
   // fold (adde x, y, false) -> (addc x, y)
   if (CarryIn.getOpcode() =3D=3D ISD::CARRY_FALSE)
-    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0=
);
+    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1=
);
=20
   return SDValue();
 }
@@ -1645,6 +1685,51 @@
   return SDValue();
 }
=20
+SDValue DAGCombiner::visitSUBC(SDNode *N) {
+  SDValue N0 =3D N->getOperand(0);
+  SDValue N1 =3D N->getOperand(1);
+  ConstantSDNode *N0C =3D dyn_cast<ConstantSDNode>(N0);
+  ConstantSDNode *N1C =3D dyn_cast<ConstantSDNode>(N1);
+  EVT VT =3D N0.getValueType();
+
+  // If the flag result is dead, turn this into an SUB.
+  if (!N->hasAnyUseOfValue(1))
+    return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1=
),
+                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
+                                 MVT::Glue));
+
+  // fold (subc x, x) -> 0 + no borrow
+  if (N0 =3D=3D N1)
+    return CombineTo(N, DAG.getConstant(0, VT),
+                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
+                                 MVT::Glue));
+
+  // fold (subc x, 0) -> x + no borrow
+  if (N1C && N1C->isNullValue())
+    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
+                                        MVT::Glue));
+
+  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
+  if (N0C && N0C->isAllOnesValue())
+    return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0=
),
+                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
+                                 MVT::Glue));
+
+  return SDValue();
+}
+
+SDValue DAGCombiner::visitSUBE(SDNode *N) {
+  SDValue N0 =3D N->getOperand(0);
+  SDValue N1 =3D N->getOperand(1);
+  SDValue CarryIn =3D N->getOperand(2);
+
+  // fold (sube x, y, false) -> (subc x, y)
+  if (CarryIn.getOpcode() =3D=3D ISD::CARRY_FALSE)
+    return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1=
);
+
+  return SDValue();
+}
+
 SDValue DAGCombiner::visitMUL(SDNode *N) {
   SDValue N0 =3D N->getOperand(0);
   SDValue N1 =3D N->getOperand(1);
@@ -1756,7 +1841,7 @@
   if (N0C && N1C && !N1C->isNullValue())
     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
   // fold (sdiv X, 1) -> X
-  if (N1C && N1C->getSExtValue() =3D=3D 1LL)
+  if (N1C && N1C->getAPIntValue() =3D=3D 1LL)
     return N0;
   // fold (sdiv X, -1) -> 0-X
   if (N1C && N1C->isAllOnesValue())
@@ -1770,17 +1855,15 @@
                          N0, N1);
   }
   // fold (sdiv X, pow2) -> simple ops after legalize
-  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
-      (isPowerOf2_64(N1C->getSExtValue()) ||
-       isPowerOf2_64(-N1C->getSExtValue()))) {
+  if (N1C && !N1C->isNullValue() &&
+      (N1C->getAPIntValue().isPowerOf2() ||
+       (-N1C->getAPIntValue()).isPowerOf2())) {
     // If dividing by powers of two is cheap, then don't perform the follo=
wing
     // fold.
     if (TLI.isPow2DivCheap())
       return SDValue();
=20
-    int64_t pow2 =3D N1C->getSExtValue();
-    int64_t abs2 =3D pow2 > 0 ? pow2 : -pow2;
-    unsigned lg2 =3D Log2_64(abs2);
+    unsigned lg2 =3D N1C->getAPIntValue().countTrailingZeros();
=20
     // Splat the sign bit into the register
     SDValue SGN =3D DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
@@ -1800,7 +1883,7 @@
=20
     // If we're dividing by a positive value, we're done.  Otherwise, we m=
ust
     // negate the result.
-    if (pow2 > 0)
+    if (N1C->getAPIntValue().isNonNegative())
       return SRA;
=20
     AddToWorkList(SRA.getNode());
@@ -1810,8 +1893,7 @@
=20
   // if integer divide is expensive and we satisfy the requirements, emit =
an
   // alternate sequence.
-  if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
-      !TLI.isIntDivCheap()) {
+  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
     SDValue Op =3D BuildSDIV(N);
     if (Op.getNode()) return Op;
   }
@@ -2250,6 +2332,67 @@
                        ORNode, N0.getOperand(1));
   }
=20
+  // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
+  // Only perform this optimization after type legalization and before
+  // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
+  // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
+  // we don't want to undo this promotion.
+  // We also handle SCALAR_TO_VECTOR because xor/or/and operations are che=
aper
+  // on scalars.
+  if ((N0.getOpcode() =3D=3D ISD::BITCAST || N0.getOpcode() =3D=3D ISD::SC=
ALAR_TO_VECTOR)
+      && Level =3D=3D AfterLegalizeVectorOps) {
+    SDValue In0 =3D N0.getOperand(0);
+    SDValue In1 =3D N1.getOperand(0);
+    EVT In0Ty =3D In0.getValueType();
+    EVT In1Ty =3D In1.getValueType();
+    // If both incoming values are integers, and the original types are th=
e same.
+    if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty =3D=3D In1Ty) {
+      SDValue Op =3D DAG.getNode(N->getOpcode(), N->getDebugLoc(), In0Ty, =
In0, In1);
+      SDValue BC =3D DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, Op);
+      AddToWorkList(Op.getNode());
+      return BC;
+    }
+  }
+
+  // Xor/and/or are indifferent to the swizzle operation (shuffle of one v=
alue).
+  // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
+  // If both shuffles use the same mask, and both shuffle within a single
+  // vector, then it is worthwhile to move the swizzle after the operation.
+  // The type-legalizer generates this pattern when loading illegal
+  // vector types from memory. In many cases this allows additional shuffle
+  // optimizations.
+  if (N0.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDA=
G &&
+      N0.getOperand(1).getOpcode() =3D=3D ISD::UNDEF &&
+      N1.getOperand(1).getOpcode() =3D=3D ISD::UNDEF) {
+    ShuffleVectorSDNode *SVN0 =3D cast<ShuffleVectorSDNode>(N0);
+    ShuffleVectorSDNode *SVN1 =3D cast<ShuffleVectorSDNode>(N1);
+
+    assert(N0.getOperand(0).getValueType() =3D=3D N1.getOperand(1).getValu=
eType() &&
+           "Inputs to shuffles are not the same type");
+
+    unsigned NumElts =3D VT.getVectorNumElements();
+
+    // Check that both shuffles use the same mask. The masks are known to =
be of
+    // the same length because the result vector type is the same.
+    bool SameMask =3D true;
+    for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+      int Idx0 =3D SVN0->getMaskElt(i);
+      int Idx1 =3D SVN1->getMaskElt(i);
+      if (Idx0 !=3D Idx1) {
+        SameMask =3D false;
+        break;
+      }
+    }
+
+    if (SameMask) {
+      SDValue Op =3D DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
+                               N0.getOperand(0), N1.getOperand(0));
+      AddToWorkList(Op.getNode());
+      return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
+                                  DAG.getUNDEF(VT), &SVN0->getMask()[0]);
+    }
+  }
+
   return SDValue();
 }
=20
@@ -2312,6 +2455,88 @@
       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
     }
   }
+  // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->=20
+  // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which=
 must
+  // already be zero by virtue of the width of the base type of the load.
+  //
+  // the 'X' node here can either be nothing or an extract_vector_elt to c=
atch
+  // more cases.
+  if ((N0.getOpcode() =3D=3D ISD::EXTRACT_VECTOR_ELT &&
+       N0.getOperand(0).getOpcode() =3D=3D ISD::LOAD) ||
+      N0.getOpcode() =3D=3D ISD::LOAD) {
+    LoadSDNode *Load =3D cast<LoadSDNode>( (N0.getOpcode() =3D=3D ISD::LOA=
D) ?
+                                         N0 : N0.getOperand(0) );
+
+    // Get the constant (if applicable) the zero'th operand is being ANDed=
 with.
+    // This can be a pure constant or a vector splat, in which case we tre=
at the
+    // vector as a scalar and use the splat value.
+    APInt Constant =3D APInt::getNullValue(1);
+    if (const ConstantSDNode *C =3D dyn_cast<ConstantSDNode>(N1)) {
+      Constant =3D C->getAPIntValue();
+    } else if (BuildVectorSDNode *Vector =3D dyn_cast<BuildVectorSDNode>(N=
1)) {
+      APInt SplatValue, SplatUndef;
+      unsigned SplatBitSize;
+      bool HasAnyUndefs;
+      bool IsSplat =3D Vector->isConstantSplat(SplatValue, SplatUndef,
+                                             SplatBitSize, HasAnyUndefs);
+      if (IsSplat) {
+        // Undef bits can contribute to a possible optimisation if set, so
+        // set them.
+        SplatValue |=3D SplatUndef;
+
+        // The splat value may be something like "0x00FFFFFF", which means=
 0 for
+        // the first vector value and FF for the rest, repeating. We need =
a mask
+        // that will apply equally to all members of the vector, so AND al=
l the
+        // lanes of the constant together.
+        EVT VT =3D Vector->getValueType(0);
+        unsigned BitWidth =3D VT.getVectorElementType().getSizeInBits();
+        Constant =3D APInt::getAllOnesValue(BitWidth);
+        for (unsigned i =3D 0, n =3D VT.getVectorNumElements(); i < n; ++i)
+          Constant &=3D SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
+      }
+    }
+
+    // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
+    // actually legal and isn't going to get expanded, else this is a false
+    // optimisation.
+    bool CanZextLoadProfitably =3D TLI.isLoadExtLegal(ISD::ZEXTLOAD,
+                                                    Load->getMemoryVT());
+
+    // Resize the constant to the same size as the original memory access =
before
+    // extension. If it is still the AllOnesValue then this AND is complet=
ely
+    // unneeded.
+    Constant =3D
+      Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBi=
ts());
+
+    bool B;
+    switch (Load->getExtensionType()) {
+    default: B =3D false; break;
+    case ISD::EXTLOAD: B =3D CanZextLoadProfitably; break;
+    case ISD::ZEXTLOAD:
+    case ISD::NON_EXTLOAD: B =3D true; break;
+    }
+
+    if (B && Constant.isAllOnesValue()) {
+      // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
+      // preserve semantics once we get rid of the AND.
+      SDValue NewLoad(Load, 0);
+      if (Load->getExtensionType() =3D=3D ISD::EXTLOAD) {
+        NewLoad =3D DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
+                              Load->getValueType(0), Load->getDebugLoc(),
+                              Load->getChain(), Load->getBasePtr(),
+                              Load->getOffset(), Load->getMemoryVT(),
+                              Load->getMemOperand());
+        // Replace uses of the EXTLOAD with the new ZEXTLOAD.
+        CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
+      }
+
+      // Fold the AND away, taking care not to fold to the old load node i=
f we
+      // replaced it.
+      CombineTo(N, (N0.getNode() =3D=3D Load) ? NewLoad : N0);
+
+      return SDValue(N, 0); // Return N so it doesn't get rechecked!
+    }
+  }
   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, =
CC1)){
     ISD::CondCode Op0 =3D cast<CondCodeSDNode>(CC0)->get();
@@ -3323,7 +3548,9 @@
=20
   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
   //                               (and (srl x, (sub c1, c2), MASK)
-  if (N1C && N0.getOpcode() =3D=3D ISD::SRL &&
+  // Only fold this if the inner shift has no other uses -- if it does, fo=
lding
+  // this will increase the total number of instructions.
+  if (N1C && N0.getOpcode() =3D=3D ISD::SRL && N0.hasOneUse() &&
       N0.getOperand(1).getOpcode() =3D=3D ISD::Constant) {
     uint64_t c1 =3D cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
     if (c1 < VT.getSizeInBits()) {
@@ -3603,8 +3830,7 @@
   if (N1C && N0.getOpcode() =3D=3D ISD::CTLZ &&
       N1C->getAPIntValue() =3D=3D Log2_32(VT.getSizeInBits())) {
     APInt KnownZero, KnownOne;
-    APInt Mask =3D APInt::getAllOnesValue(VT.getScalarType().getSizeInBits=
());
-    DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
+    DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
=20
     // If any of the input bits are KnownOne, then the input couldn't be a=
ll
     // zeros, thus the result of the srl will always be zero.
@@ -3612,7 +3838,7 @@
=20
     // If all of the bits input the to ctlz node are known to be zero, then
     // the result of the ctlz is "32" and the result of the shift is one.
-    APInt UnknownBits =3D ~KnownZero & Mask;
+    APInt UnknownBits =3D ~KnownZero;
     if (UnknownBits =3D=3D 0) return DAG.getConstant(1, VT);
=20
     // Otherwise, check to see if there is exactly one bit input to the ct=
lz.
@@ -3713,6 +3939,16 @@
   return SDValue();
 }
=20
+SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
+  SDValue N0 =3D N->getOperand(0);
+  EVT VT =3D N->getValueType(0);
+
+  // fold (ctlz_zero_undef c1) -> c2
+  if (isa<ConstantSDNode>(N0))
+    return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
+  return SDValue();
+}
+
 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
   SDValue N0 =3D N->getOperand(0);
   EVT VT =3D N->getValueType(0);
@@ -3723,6 +3959,16 @@
   return SDValue();
 }
=20
+SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
+  SDValue N0 =3D N->getOperand(0);
+  EVT VT =3D N->getValueType(0);
+
+  // fold (cttz_zero_undef c1) -> c2
+  if (isa<ConstantSDNode>(N0))
+    return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
+  return SDValue();
+}
+
 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
   SDValue N0 =3D N->getOperand(0);
   EVT VT =3D N->getValueType(0);
@@ -4108,12 +4354,17 @@
     // Only do this before legalize for now.
     if (VT.isVector() && !LegalOperations) {
       EVT N0VT =3D N0.getOperand(0).getValueType();
-        // We know that the # elements of the results is the same as the
-        // # elements of the compare (and the # elements of the compare re=
sult
-        // for that matter).  Check to see that they are the same size.  I=
f so,
-        // we know that the element size of the sext'd result matches the
-        // element size of the compare operands.
-      if (VT.getSizeInBits() =3D=3D N0VT.getSizeInBits())
+      // On some architectures (such as SSE/NEON/etc) the SETCC result typ=
e is
+      // of the same size as the compared operands. Only optimize sext(set=
cc())
+      // if this is the case.
+      EVT SVT =3D TLI.getSetCCResultType(N0VT);
+
+      // We know that the # elements of the results is the same as the
+      // # elements of the compare (and the # elements of the compare resu=
lt
+      // for that matter).  Check to see that they are the same size.  If =
so,
+      // we know that the element size of the sext'd result matches the
+      // element size of the compare operands.
+      if (VT.getSizeInBits() =3D=3D SVT.getSizeInBits())
         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
                              N0.getOperand(1),
                              cast<CondCodeSDNode>(N0.getOperand(2))->get()=
);
@@ -4127,11 +4378,13 @@
         EVT MatchingVectorType =3D
           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
                            N0VT.getVectorNumElements());
-        SDValue VsetCC =3D
-          DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand=
(0),
-                        N0.getOperand(1),
-                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
-        return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
+
+        if (SVT =3D=3D MatchingVectorType) {
+          SDValue VsetCC =3D DAG.getSetCC(N->getDebugLoc(), MatchingVector=
Type,
+                                 N0.getOperand(0), N0.getOperand(1),
+                                 cast<CondCodeSDNode>(N0.getOperand(2))->g=
et());
+          return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
+        }
       }
     }
=20
@@ -4162,6 +4415,44 @@
   return SDValue();
 }
=20
+// isTruncateOf - If N is a truncate of some other value, return true, rec=
ord
+// the value being truncated in Op and which of Op's bits are zero in Know=
nZero.
+// This function computes KnownZero to avoid a duplicated call to
+// ComputeMaskedBits in the caller.
+static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
+                         APInt &KnownZero) {
+  APInt KnownOne;
+  if (N->getOpcode() =3D=3D ISD::TRUNCATE) {
+    Op =3D N->getOperand(0);
+    DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
+    return true;
+  }
+
+  if (N->getOpcode() !=3D ISD::SETCC || N->getValueType(0) !=3D MVT::i1 ||
+      cast<CondCodeSDNode>(N->getOperand(2))->get() !=3D ISD::SETNE)
+    return false;
+
+  SDValue Op0 =3D N->getOperand(0);
+  SDValue Op1 =3D N->getOperand(1);
+  assert(Op0.getValueType() =3D=3D Op1.getValueType());
+
+  ConstantSDNode *COp0 =3D dyn_cast<ConstantSDNode>(Op0);
+  ConstantSDNode *COp1 =3D dyn_cast<ConstantSDNode>(Op1);
+  if (COp0 && COp0->isNullValue())
+    Op =3D Op1;
+  else if (COp1 && COp1->isNullValue())
+    Op =3D Op0;
+  else
+    return false;
+
+  DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
+
+  if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
+    return false;
+
+  return true;
+}
+
 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
   SDValue N0 =3D N->getOperand(0);
   EVT VT =3D N->getValueType(0);
@@ -4175,6 +4466,30 @@
     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
                        N0.getOperand(0));
=20
+  // fold (zext (truncate x)) -> (zext x) or
+  //      (zext (truncate x)) -> (truncate x)
+  // This is valid when the truncated bits of x are already zero.
+  // FIXME: We should extend this to work for vectors too.
+  SDValue Op;
+  APInt KnownZero;
+  if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
+    APInt TruncatedBits =3D
+      (Op.getValueSizeInBits() =3D=3D N0.getValueSizeInBits()) ?
+      APInt(Op.getValueSizeInBits(), 0) :
+      APInt::getBitsSet(Op.getValueSizeInBits(),
+                        N0.getValueSizeInBits(),
+                        std::min(Op.getValueSizeInBits(),
+                                 VT.getSizeInBits()));
+    if (TruncatedBits =3D=3D (KnownZero & TruncatedBits)) {
+      if (VT.bitsGT(Op.getValueType()))
+        return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
+      if (VT.bitsLT(Op.getValueType()))
+        return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
+
+      return Op;
+    }
+  }
+
   // fold (zext (truncate (load x))) -> (zext (smaller load x))
   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)=
))
   if (N0.getOpcode() =3D=3D ISD::TRUNCATE) {
@@ -4567,6 +4882,16 @@
 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
   switch (V.getOpcode()) {
   default: break;
+  case ISD::Constant: {
+    const ConstantSDNode *CV =3D cast<ConstantSDNode>(V.getNode());
+    assert(CV !=3D 0 && "Const value should be ConstSDNode.");
+    const APInt &CVal =3D CV->getAPIntValue();
+    APInt NewVal =3D CVal & Mask;
+    if (NewVal !=3D CVal) {
+      return DAG.getConstant(NewVal, V.getValueType());
+    }
+    break;
+  }
   case ISD::OR:
   case ISD::XOR:
     // If the LHS or RHS don't contribute bits to the or, drop them.
@@ -4705,7 +5030,8 @@
   if (ExtType =3D=3D ISD::NON_EXTLOAD)
     Load =3D  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
                         LN0->getPointerInfo().getWithOffset(PtrOff),
-                        LN0->isVolatile(), LN0->isNonTemporal(), NewAlign);
+                        LN0->isVolatile(), LN0->isNonTemporal(),
+                        LN0->isInvariant(), NewAlign);
   else
     Load =3D DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain()=
,NewPtr,
                           LN0->getPointerInfo().getWithOffset(PtrOff),
@@ -4844,6 +5170,7 @@
 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
   SDValue N0 =3D N->getOperand(0);
   EVT VT =3D N->getValueType(0);
+  bool isLE =3D TLI.isLittleEndian();
=20
   // noop truncate
   if (N0.getValueType() =3D=3D N->getValueType(0))
@@ -4871,6 +5198,44 @@
       return N0.getOperand(0);
   }
=20
+  // Fold extract-and-trunc into a narrow extract. For example:
+  //   i64 x =3D EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
+  //   i32 y =3D TRUNCATE(i64 x)
+  //        -- becomes --
+  //   v16i8 b =3D BITCAST (v2i64 val)
+  //   i8 x =3D EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
+  //
+  // Note: We only run this optimization after type legalization (which of=
ten
+  // creates this pattern) and before operation legalization after which
+  // we need to be more careful about the vector instructions that we gene=
rate.
+  if (N0.getOpcode() =3D=3D ISD::EXTRACT_VECTOR_ELT &&
+      LegalTypes && !LegalOperations && N0->hasOneUse()) {
+
+    EVT VecTy =3D N0.getOperand(0).getValueType();
+    EVT ExTy =3D N0.getValueType();
+    EVT TrTy =3D N->getValueType(0);
+
+    unsigned NumElem =3D VecTy.getVectorNumElements();
+    unsigned SizeRatio =3D ExTy.getSizeInBits()/TrTy.getSizeInBits();
+
+    EVT NVT =3D EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumE=
lem);
+    assert(NVT.getSizeInBits() =3D=3D VecTy.getSizeInBits() && "Invalid Si=
ze");
+
+    SDValue EltNo =3D N0->getOperand(1);
+    if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
+      int Elt =3D cast<ConstantSDNode>(EltNo)->getZExtValue();
+
+      int Index =3D isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1=
));
+
+      SDValue V =3D DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
+                              NVT, N0.getOperand(0));
+
+      return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
+                         N->getDebugLoc(), TrTy, V,
+                         DAG.getConstant(Index, MVT::i32));
+    }
+  }
+
   // See if we can simplify the input to this truncate through knowledge t=
hat
   // only the low bits are being used.
   // For example "trunc (or (shl x, 8), y)" // -> trunc y
@@ -4934,7 +5299,7 @@
         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
                          LD1->getBasePtr(), LD1->getPointerInfo(),
-                         false, false, Align);
+                         false, false, false, Align);
   }
=20
   return SDValue();
@@ -5004,7 +5369,7 @@
       SDValue Load =3D DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
                                  LN0->getBasePtr(), LN0->getPointerInfo(),
                                  LN0->isVolatile(), LN0->isNonTemporal(),
-                                 OrigAlign);
+                                 LN0->isInvariant(), OrigAlign);
       AddToWorkList(N);
       CombineTo(N0.getNode(),
                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
@@ -5017,7 +5382,8 @@
   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
   // This often reduces constant pool loads.
-  if ((N0.getOpcode() =3D=3D ISD::FNEG || N0.getOpcode() =3D=3D ISD::FABS)=
 &&
+  if (((N0.getOpcode() =3D=3D ISD::FNEG && !TLI.isFNegFree(VT)) ||
+       (N0.getOpcode() =3D=3D ISD::FABS && !TLI.isFAbsFree(VT))) &&
       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
     SDValue NewConv =3D DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
                                   N0.getOperand(0));
@@ -5247,20 +5613,24 @@
   if (N0CFP && !N1CFP)
     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
   // fold (fadd A, 0) -> A
-  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
+  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
+      N1CFP->getValueAPF().isZero())
     return N0;
   // fold (fadd A, (fneg B)) -> (fsub A, B)
-  if (isNegatibleForFree(N1, LegalOperations) =3D=3D 2)
+  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
+      isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Option=
s) =3D=3D 2)
     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
                        GetNegatedExpression(N1, DAG, LegalOperations));
   // fold (fadd (fneg A), B) -> (fsub B, A)
-  if (isNegatibleForFree(N0, LegalOperations) =3D=3D 2)
+  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
+      isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Option=
s) =3D=3D 2)
     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
                        GetNegatedExpression(N0, DAG, LegalOperations));
=20
   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
-  if (UnsafeFPMath && N1CFP && N0.getOpcode() =3D=3D ISD::FADD &&
-      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
+  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
+      N0.getOpcode() =3D=3D ISD::FADD && N0.getNode()->hasOneUse() &&
+      isa<ConstantFPSDNode>(N0.getOperand(1)))
     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
                                    N0.getOperand(1), N1));
@@ -5285,20 +5655,39 @@
   if (N0CFP && N1CFP && VT !=3D MVT::ppcf128)
     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
   // fold (fsub A, 0) -> A
-  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
+  if (DAG.getTarget().Options.UnsafeFPMath &&
+      N1CFP && N1CFP->getValueAPF().isZero())
     return N0;
   // fold (fsub 0, B) -> -B
-  if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
-    if (isNegatibleForFree(N1, LegalOperations))
+  if (DAG.getTarget().Options.UnsafeFPMath &&
+      N0CFP && N0CFP->getValueAPF().isZero()) {
+    if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Opti=
ons))
       return GetNegatedExpression(N1, DAG, LegalOperations);
     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
   }
   // fold (fsub A, (fneg B)) -> (fadd A, B)
-  if (isNegatibleForFree(N1, LegalOperations))
+  if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Option=
s))
     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
                        GetNegatedExpression(N1, DAG, LegalOperations));
=20
+  // If 'unsafe math' is enabled, fold
+  //    (fsub x, (fadd x, y)) -> (fneg y) &
+  //    (fsub x, (fadd y, x)) -> (fneg y)
+  if (DAG.getTarget().Options.UnsafeFPMath) {
+    if (N1.getOpcode() =3D=3D ISD::FADD) {
+      SDValue N10 =3D N1->getOperand(0);
+      SDValue N11 =3D N1->getOperand(1);
+
+      if (N10 =3D=3D N0 && isNegatibleForFree(N11, LegalOperations, TLI,
+                                          &DAG.getTarget().Options))
+        return GetNegatedExpression(N11, DAG, LegalOperations);
+      else if (N11 =3D=3D N0 && isNegatibleForFree(N10, LegalOperations, T=
LI,
+                                               &DAG.getTarget().Options))
+        return GetNegatedExpression(N10, DAG, LegalOperations);
+    }
+  }
+
   return SDValue();
 }
=20
@@ -5308,6 +5697,7 @@
   ConstantFPSDNode *N0CFP =3D dyn_cast<ConstantFPSDNode>(N0);
   ConstantFPSDNode *N1CFP =3D dyn_cast<ConstantFPSDNode>(N1);
   EVT VT =3D N->getValueType(0);
+  const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
=20
   // fold vector ops
   if (VT.isVector()) {
@@ -5322,10 +5712,12 @@
   if (N0CFP && !N1CFP)
     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
   // fold (fmul A, 0) -> 0
-  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
+  if (DAG.getTarget().Options.UnsafeFPMath &&
+      N1CFP && N1CFP->getValueAPF().isZero())
     return N1;
   // fold (fmul A, 0) -> 0, vector edition.
-  if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
+  if (DAG.getTarget().Options.UnsafeFPMath &&
+      ISD::isBuildVectorAllZeros(N1.getNode()))
     return N1;
   // fold (fmul X, 2.0) -> (fadd X, X)
   if (N1CFP && N1CFP->isExactlyValue(+2.0))
@@ -5336,8 +5728,10 @@
       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
=20
   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
-  if (char LHSNeg =3D isNegatibleForFree(N0, LegalOperations)) {
-    if (char RHSNeg =3D isNegatibleForFree(N1, LegalOperations)) {
+  if (char LHSNeg =3D isNegatibleForFree(N0, LegalOperations, TLI,
+                                       &DAG.getTarget().Options)) {
+    if (char RHSNeg =3D isNegatibleForFree(N1, LegalOperations, TLI,=20
+                                         &DAG.getTarget().Options)) {
       // Both can be negated for free, check to see if at least one is che=
aper
       // negated.
       if (LHSNeg =3D=3D 2 || RHSNeg =3D=3D 2)
@@ -5348,7 +5742,8 @@
   }
=20
   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
-  if (UnsafeFPMath && N1CFP && N0.getOpcode() =3D=3D ISD::FMUL &&
+  if (DAG.getTarget().Options.UnsafeFPMath &&
+      N1CFP && N0.getOpcode() =3D=3D ISD::FMUL &&
       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
@@ -5363,6 +5758,7 @@
   ConstantFPSDNode *N0CFP =3D dyn_cast<ConstantFPSDNode>(N0);
   ConstantFPSDNode *N1CFP =3D dyn_cast<ConstantFPSDNode>(N1);
   EVT VT =3D N->getValueType(0);
+  const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
=20
   // fold vector ops
   if (VT.isVector()) {
@@ -5374,10 +5770,30 @@
   if (N0CFP && N1CFP && VT !=3D MVT::ppcf128)
     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
=20
+  // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
+  if (N1CFP && VT !=3D MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMat=
h) {
+    // Compute the reciprocal 1.0 / c2.
+    APFloat N1APF =3D N1CFP->getValueAPF();
+    APFloat Recip(N1APF.getSemantics(), 1); // 1.0
+    APFloat::opStatus st =3D Recip.divide(N1APF, APFloat::rmNearestTiesToE=
ven);
+    // Only do the transform if the reciprocal is a legal fp immediate that
+    // isn't too nasty (eg NaN, denormal, ...).
+    if ((st =3D=3D APFloat::opOK || st =3D=3D APFloat::opInexact) && // No=
t too nasty
+        (!LegalOperations ||
+         // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
+         // backend)... we should handle this gracefully after Legalize.
+         // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
+         TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
+         TLI.isFPImmLegal(Recip, VT)))
+      return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
+                         DAG.getConstantFP(Recip, VT));
+  }
=20
   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
-  if (char LHSNeg =3D isNegatibleForFree(N0, LegalOperations)) {
-    if (char RHSNeg =3D isNegatibleForFree(N1, LegalOperations)) {
+  if (char LHSNeg =3D isNegatibleForFree(N0, LegalOperations, TLI,
+                                       &DAG.getTarget().Options)) {
+    if (char RHSNeg =3D isNegatibleForFree(N1, LegalOperations, TLI,
+                                         &DAG.getTarget().Options)) {
       // Both can be negated for free, check to see if at least one is che=
aper
       // negated.
       if (LHSNeg =3D=3D 2 || RHSNeg =3D=3D 2)
@@ -5463,7 +5879,7 @@
   // fold (sint_to_fp c1) -> c1fp
   if (N0C && OpVT !=3D MVT::ppcf128 &&
       // ...but only if the target supports immediate floating-point values
-      (Level =3D=3D llvm::Unrestricted ||
+      (!LegalOperations ||
        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
=20
@@ -5488,7 +5904,7 @@
   // fold (uint_to_fp c1) -> c1fp
   if (N0C && OpVT !=3D MVT::ppcf128 &&
       // ...but only if the target supports immediate floating-point values
-      (Level =3D=3D llvm::Unrestricted ||
+      (!LegalOperations ||
        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
=20
@@ -5630,12 +6046,13 @@
   SDValue N0 =3D N->getOperand(0);
   EVT VT =3D N->getValueType(0);
=20
-  if (isNegatibleForFree(N0, LegalOperations))
+  if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
+                         &DAG.getTarget().Options))
     return GetNegatedExpression(N0, DAG, LegalOperations);
=20
   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
   // constant pool values.
-  if (N0.getOpcode() =3D=3D ISD::BITCAST &&
+  if (!TLI.isFNegFree(VT) && N0.getOpcode() =3D=3D ISD::BITCAST &&
       !VT.isVector() &&
       N0.getNode()->hasOneUse() &&
       N0.getOperand(0).getValueType().isInteger()) {
@@ -5671,7 +6088,8 @@
=20
   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
   // constant pool values.
-  if (N0.getOpcode() =3D=3D ISD::BITCAST && N0.getNode()->hasOneUse() &&
+  if (!TLI.isFAbsFree(VT) &&=20
+      N0.getOpcode() =3D=3D ISD::BITCAST && N0.getNode()->hasOneUse() &&
       N0.getOperand(0).getValueType().isInteger() &&
       !N0.getOperand(0).getValueType().isVector()) {
     SDValue Int =3D N0.getOperand(0);
@@ -5860,6 +6278,47 @@
   return SDValue();
 }
=20
+/// canFoldInAddressingMode - Return true if 'Use' is a load or a store th=
at
+/// uses N as its base pointer and that N may be folded in the load / store
+/// addressing mode.
+static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
+                                    SelectionDAG &DAG,
+                                    const TargetLowering &TLI) {
+  EVT VT;
+  if (LoadSDNode *LD  =3D dyn_cast<LoadSDNode>(Use)) {
+    if (LD->isIndexed() || LD->getBasePtr().getNode() !=3D N)
+      return false;
+    VT =3D Use->getValueType(0);
+  } else if (StoreSDNode *ST  =3D dyn_cast<StoreSDNode>(Use)) {
+    if (ST->isIndexed() || ST->getBasePtr().getNode() !=3D N)
+      return false;
+    VT =3D ST->getValue().getValueType();
+  } else
+    return false;
+
+  TargetLowering::AddrMode AM;
+  if (N->getOpcode() =3D=3D ISD::ADD) {
+    ConstantSDNode *Offset =3D dyn_cast<ConstantSDNode>(N->getOperand(1));
+    if (Offset)
+      // [reg +/- imm]
+      AM.BaseOffs =3D Offset->getSExtValue();
+    else
+      // [reg +/- reg]
+      AM.Scale =3D 1;
+  } else if (N->getOpcode() =3D=3D ISD::SUB) {
+    ConstantSDNode *Offset =3D dyn_cast<ConstantSDNode>(N->getOperand(1));
+    if (Offset)
+      // [reg +/- imm]
+      AM.BaseOffs =3D -Offset->getSExtValue();
+    else
+      // [reg +/- reg]
+      AM.Scale =3D 1;
+  } else
+    return false;
+
+  return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())=
);
+}
+
 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
 /// pre-indexed load / store when the base pointer is an add or subtract
 /// and it has other uses besides the load / store. After the
@@ -5867,7 +6326,7 @@
 /// the add / subtract in and all of its other uses are redirected to the
 /// new load / store.
 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
-  if (!LegalOperations)
+  if (Level < AfterLegalizeDAG)
     return false;
=20
   bool isLoad =3D true;
@@ -5946,10 +6405,9 @@
     if (N->hasPredecessorHelper(Use, Visited, Worklist))
       return false;
=20
-    if (!((Use->getOpcode() =3D=3D ISD::LOAD &&
-           cast<LoadSDNode>(Use)->getBasePtr() =3D=3D Ptr) ||
-          (Use->getOpcode() =3D=3D ISD::STORE &&
-           cast<StoreSDNode>(Use)->getBasePtr() =3D=3D Ptr)))
+    // If Ptr may be folded in addressing mode of other use, then it's
+    // not profitable to do this transformation.
+    if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
       RealUse =3D true;
   }
=20
@@ -5999,7 +6457,7 @@
 /// load / store effectively and all of its uses are redirected to the
 /// new load / store.
 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
-  if (!LegalOperations)
+  if (Level < AfterLegalizeDAG)
     return false;
=20
   bool isLoad =3D true;
@@ -6046,7 +6504,8 @@
         continue;
=20
       // Try turning it into a post-indexed load / store except when
-      // 1) All uses are load / store ops that use it as base ptr.
+      // 1) All uses are load / store ops that use it as base ptr (and
+      //    it may be folded as addressing mmode).
       // 2) Op must be independent of N, i.e. Op is neither a predecessor
       //    nor a successor of N. Otherwise, if Op is folded that would
       //    create a cycle.
@@ -6069,10 +6528,7 @@
           for (SDNode::use_iterator III =3D Use->use_begin(),
                  EEE =3D Use->use_end(); III !=3D EEE; ++III) {
             SDNode *UseUse =3D *III;
-            if (!((UseUse->getOpcode() =3D=3D ISD::LOAD &&
-                   cast<LoadSDNode>(UseUse)->getBasePtr().getNode() =3D=3D=
 Use) ||
-                  (UseUse->getOpcode() =3D=3D ISD::STORE &&
-                   cast<StoreSDNode>(UseUse)->getBasePtr().getNode() =3D=
=3D Use)))
+            if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))=20
               RealUse =3D true;
           }
=20
@@ -6139,7 +6595,7 @@
   if (!LD->isVolatile()) {
     if (N->getValueType(1) =3D=3D MVT::Other) {
       // Unindexed loads.
-      if (N->hasNUsesOfValue(0, 0)) {
+      if (!N->hasAnyUseOfValue(0)) {
         // It's not safe to use the two value CombineTo variant here. e.g.
         // v1, chain2 =3D load chain1, loc
         // v2, chain3 =3D load chain2, loc
@@ -6164,7 +6620,7 @@
     } else {
       // Indexed loads.
       assert(N->getValueType(2) =3D=3D MVT::Other && "Malformed indexed lo=
ads?");
-      if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
+      if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
         SDValue Undef =3D DAG.getUNDEF(N->getValueType(0));
         DEBUG(dbgs() << "\nReplacing.7 ";
               N->dump(&DAG);
@@ -6222,7 +6678,7 @@
         ReplLoad =3D DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
                                BetterChain, Ptr, LD->getPointerInfo(),
                                LD->isVolatile(), LD->isNonTemporal(),
-                               LD->getAlignment());
+                               LD->isInvariant(), LD->getAlignment());
       } else {
         ReplLoad =3D DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLo=
c(),
                                   LD->getValueType(0),
@@ -6486,7 +6942,7 @@
                                   LD->getChain(), NewPtr,
                                   LD->getPointerInfo().getWithOffset(PtrOf=
f),
                                   LD->isVolatile(), LD->isNonTemporal(),
-                                  NewAlign);
+                                  LD->isInvariant(), NewAlign);
       SDValue NewVal =3D DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewL=
D,
                                    DAG.getConstant(NewImm, NewVT));
       SDValue NewST =3D DAG.getStore(Chain, N->getDebugLoc(),
@@ -6546,7 +7002,7 @@
     SDValue NewLD =3D DAG.getLoad(IntVT, Value.getDebugLoc(),
                                 LD->getChain(), LD->getBasePtr(),
                                 LD->getPointerInfo(),
-                                false, false, LDAlign);
+                                false, false, false, LDAlign);
=20
     SDValue NewST =3D DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
                                  NewLD, ST->getBasePtr(),
@@ -6823,13 +7279,14 @@
 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
   // (vextract (scalar_to_vector val, 0) -> val
   SDValue InVec =3D N->getOperand(0);
+  EVT VT =3D InVec.getValueType();
+  EVT NVT =3D N->getValueType(0);
=20
   if (InVec.getOpcode() =3D=3D ISD::SCALAR_TO_VECTOR) {
     // Check if the result type doesn't match the inserted element type. A
     // SCALAR_TO_VECTOR may truncate the inserted element and the
     // EXTRACT_VECTOR_ELT may widen the extracted vector.
     SDValue InOp =3D InVec.getOperand(0);
-    EVT NVT =3D N->getValueType(0);
     if (InOp.getValueType() !=3D NVT) {
       assert(InOp.getValueType().isInteger() && NVT.isInteger());
       return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
@@ -6837,6 +7294,38 @@
     return InOp;
   }
=20
+  SDValue EltNo =3D N->getOperand(1);
+  bool ConstEltNo =3D isa<ConstantSDNode>(EltNo);
+
+  // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_E=
LT.
+  // We only perform this optimization before the op legalization phase be=
cause
+  // we may introduce new vector instructions which are not backed by TD p=
atterns.
+  // For example on AVX, extracting elements from a wide vector without us=
ing
+  // extract_subvector.
+  if (InVec.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE
+      && ConstEltNo && !LegalOperations) {
+    int Elt =3D cast<ConstantSDNode>(EltNo)->getZExtValue();
+    int NumElem =3D VT.getVectorNumElements();
+    ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(InVec);
+    // Find the new index to extract from.
+    int OrigElt =3D SVOp->getMaskElt(Elt);
+
+    // Extracting an undef index is undef.
+    if (OrigElt =3D=3D -1)
+      return DAG.getUNDEF(NVT);
+
+    // Select the right vector half to extract from.
+    if (OrigElt < NumElem) {
+      InVec =3D InVec->getOperand(0);
+    } else {
+      InVec =3D InVec->getOperand(1);
+      OrigElt -=3D NumElem;
+    }
+
+    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
+                       InVec, DAG.getConstant(OrigElt, MVT::i32));
+  }
+
   // Perform only after legalization to ensure build_vector / vector_shuff=
le
   // optimizations have already been done.
   if (!LegalOperations) return SDValue();
@@ -6844,17 +7333,24 @@
   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $a=
ddr)
-  SDValue EltNo =3D N->getOperand(1);
-
-  if (isa<ConstantSDNode>(EltNo)) {
+
+  if (ConstEltNo) {
     int Elt =3D cast<ConstantSDNode>(EltNo)->getZExtValue();
     bool NewLoad =3D false;
     bool BCNumEltsChanged =3D false;
-    EVT VT =3D InVec.getValueType();
     EVT ExtVT =3D VT.getVectorElementType();
     EVT LVT =3D ExtVT;
=20
+    // If the result of load has to be truncated, then it's not necessarily
+    // profitable.
+    if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
+      return SDValue();
+
     if (InVec.getOpcode() =3D=3D ISD::BITCAST) {
+      // Don't duplicate a load with other uses.
+      if (!InVec.hasOneUse())
+        return SDValue();
+
       EVT BCVT =3D InVec.getOperand(0).getValueType();
       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
         return SDValue();
@@ -6872,12 +7368,20 @@
     } else if (InVec.getOpcode() =3D=3D ISD::SCALAR_TO_VECTOR &&
                InVec.getOperand(0).getValueType() =3D=3D ExtVT &&
                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
+      // Don't duplicate a load with other uses.
+      if (!InVec.hasOneUse())
+        return SDValue();
+
       LN0 =3D cast<LoadSDNode>(InVec.getOperand(0));
     } else if ((SVN =3D dyn_cast<ShuffleVectorSDNode>(InVec))) {
       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
       // =3D>
       // (load $addr+1*size)
=20
+      // Don't duplicate a load with other uses.
+      if (!InVec.hasOneUse())
+        return SDValue();
+
       // If the bit convert changed the number of elements, it is unsafe
       // to examine the mask.
       if (BCNumEltsChanged)
@@ -6888,14 +7392,21 @@
       int Idx =3D (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
       InVec =3D (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOpe=
rand(1);
=20
-      if (InVec.getOpcode() =3D=3D ISD::BITCAST)
+      if (InVec.getOpcode() =3D=3D ISD::BITCAST) {
+        // Don't duplicate a load with other uses.
+        if (!InVec.hasOneUse())
+          return SDValue();
+
         InVec =3D InVec.getOperand(0);
+      }
       if (ISD::isNormalLoad(InVec.getNode())) {
         LN0 =3D cast<LoadSDNode>(InVec);
         Elt =3D (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
       }
     }
=20
+    // Make sure we found a non-volatile load and the extractelement is
+    // the only use.
     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
       return SDValue();
=20
@@ -6929,9 +7440,45 @@
                            DAG.getConstant(PtrOff, PtrType));
     }
=20
-    return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
-                       LN0->getPointerInfo().getWithOffset(PtrOff),
-                       LN0->isVolatile(), LN0->isNonTemporal(), Align);
+    // The replacement we need to do here is a little tricky: we need to
+    // replace an extractelement of a load with a load.
+    // Use ReplaceAllUsesOfValuesWith to do the replacement.
+    // Note that this replacement assumes that the extractvalue is the only
+    // use of the load; that's okay because we don't want to perform this
+    // transformation in other cases anyway.
+    SDValue Load;
+    SDValue Chain;
+    if (NVT.bitsGT(LVT)) {
+      // If the result type of vextract is wider than the load, then issue=
 an
+      // extending load instead.
+      ISD::LoadExtType ExtType =3D TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
+        ? ISD::ZEXTLOAD : ISD::EXTLOAD;
+      Load =3D DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChai=
n(),
+                            NewPtr, LN0->getPointerInfo().getWithOffset(Pt=
rOff),
+                            LVT, LN0->isVolatile(), LN0->isNonTemporal(),A=
lign);
+      Chain =3D Load.getValue(1);
+    } else {
+      Load =3D DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
+                         LN0->getPointerInfo().getWithOffset(PtrOff),
+                         LN0->isVolatile(), LN0->isNonTemporal(),=20
+                         LN0->isInvariant(), Align);
+      Chain =3D Load.getValue(1);
+      if (NVT.bitsLT(LVT))
+        Load =3D DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
+      else
+        Load =3D DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
+    }
+    WorkListRemover DeadNodes(*this);
+    SDValue From[] =3D { SDValue(N, 0), SDValue(LN0,1) };
+    SDValue To[] =3D { Load, Chain };
+    DAG.ReplaceAllUsesOfValuesWith(From, To, 2, &DeadNodes);
+    // Since we're explcitly calling ReplaceAllUses, add the new node to t=
he
+    // worklist explicitly as well.
+    AddToWorkList(Load.getNode());
+    AddUsersToWorkList(Load.getNode()); // Add users too
+    // Make sure to revisit this node to clean it up; it will usually be d=
ead.
+    AddToWorkList(N);
+    return SDValue(N, 0);
   }
=20
   return SDValue();
@@ -6939,11 +7486,122 @@
=20
 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
   unsigned NumInScalars =3D N->getNumOperands();
+  DebugLoc dl =3D N->getDebugLoc();
   EVT VT =3D N->getValueType(0);
+  // Check to see if this is a BUILD_VECTOR of a bunch of values
+  // which come from any_extend or zero_extend nodes. If so, we can create
+  // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
+  // optimizations. We do not handle sign-extend because we can't fill the=
 sign
+  // using shuffles.
+  EVT SourceType =3D MVT::Other;
+  bool AllAnyExt =3D true;
+  bool AllUndef =3D true;
+  for (unsigned i =3D 0; i !=3D NumInScalars; ++i) {
+    SDValue In =3D N->getOperand(i);
+    // Ignore undef inputs.
+    if (In.getOpcode() =3D=3D ISD::UNDEF) continue;
+    AllUndef =3D false;
+
+    bool AnyExt  =3D In.getOpcode() =3D=3D ISD::ANY_EXTEND;
+    bool ZeroExt =3D In.getOpcode() =3D=3D ISD::ZERO_EXTEND;
+
+    // Abort if the element is not an extension.
+    if (!ZeroExt && !AnyExt) {
+      SourceType =3D MVT::Other;
+      break;
+    }
+
+    // The input is a ZeroExt or AnyExt. Check the original type.
+    EVT InTy =3D In.getOperand(0).getValueType();
+
+    // Check that all of the widened source types are the same.
+    if (SourceType =3D=3D MVT::Other)
+      // First time.
+      SourceType =3D InTy;
+    else if (InTy !=3D SourceType) {
+      // Multiple income types. Abort.
+      SourceType =3D MVT::Other;
+      break;
+    }
+
+    // Check if all of the extends are ANY_EXTENDs.
+    AllAnyExt &=3D AnyExt;
+  }
+
+  if (AllUndef)
+    return DAG.getUNDEF(VT);
+
+  // In order to have valid types, all of the inputs must be extended from=
 the
+  // same source type and all of the inputs must be any or zero extend.
+  // Scalar sizes must be a power of two.
+  EVT OutScalarTy =3D N->getValueType(0).getScalarType();
+  bool ValidTypes =3D SourceType !=3D MVT::Other &&
+                 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
+                 isPowerOf2_32(SourceType.getSizeInBits());
+
+  // We perform this optimization post type-legalization because
+  // the type-legalizer often scalarizes integer-promoted vectors.
+  // Performing this optimization before may create bit-casts which
+  // will be type-legalized to complex code sequences.
+  // We perform this optimization only before the operation legalizer beca=
use we
+  // may introduce illegal operations.
+  // Create a new simpler BUILD_VECTOR sequence which other optimizations =
can
+  // turn into a single shuffle instruction.
+  if ((Level =3D=3D AfterLegalizeVectorOps || Level =3D=3D AfterLegalizeTy=
pes) &&
+      ValidTypes) {
+    bool isLE =3D TLI.isLittleEndian();
+    unsigned ElemRatio =3D OutScalarTy.getSizeInBits()/SourceType.getSizeI=
nBits();
+    assert(ElemRatio > 1 && "Invalid element size ratio");
+    SDValue Filler =3D AllAnyExt ? DAG.getUNDEF(SourceType):
+                                 DAG.getConstant(0, SourceType);
+
+    unsigned NewBVElems =3D ElemRatio * N->getValueType(0).getVectorNumEle=
ments();
+    SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
+
+    // Populate the new build_vector
+    for (unsigned i=3D0; i < N->getNumOperands(); ++i) {
+      SDValue Cast =3D N->getOperand(i);
+      assert((Cast.getOpcode() =3D=3D ISD::ANY_EXTEND ||
+              Cast.getOpcode() =3D=3D ISD::ZERO_EXTEND ||
+              Cast.getOpcode() =3D=3D ISD::UNDEF) && "Invalid cast opcode"=
);
+      SDValue In;
+      if (Cast.getOpcode() =3D=3D ISD::UNDEF)
+        In =3D DAG.getUNDEF(SourceType);
+      else
+        In =3D Cast->getOperand(0);
+      unsigned Index =3D isLE ? (i * ElemRatio) :
+                              (i * ElemRatio + (ElemRatio - 1));
+
+      assert(Index < Ops.size() && "Invalid index");
+      Ops[Index] =3D In;
+    }
+
+    // The type of the new BUILD_VECTOR node.
+    EVT VecVT =3D EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVEle=
ms);
+    assert(VecVT.getSizeInBits() =3D=3D N->getValueType(0).getSizeInBits()=
 &&
+           "Invalid vector size");
+    // Check if the new vector type is legal.
+    if (!isTypeLegal(VecVT)) return SDValue();
+
+    // Make the new BUILD_VECTOR.
+    SDValue BV =3D DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
+                                 VecVT, &Ops[0], Ops.size());
+
+    // The new BUILD_VECTOR node has the potential to be further optimized.
+    AddToWorkList(BV.getNode());
+    // Bitcast to the desired type.
+    return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
+  }
=20
   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_E=
LT
   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come =
from
   // at most two distinct vectors, turn this into a shuffle node.
+
+  // May only combine to shuffle after legalize if shuffle is legal.
+  if (LegalOperations &&
+      !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
+    return SDValue();
+
   SDValue VecIn1, VecIn2;
   for (unsigned i =3D 0; i !=3D NumInScalars; ++i) {
     // Ignore undef inputs.
@@ -6957,15 +7615,8 @@
       break;
     }
=20
-    // If the input vector type disagrees with the result of the build_vec=
tor,
-    // we can't make a shuffle.
+    // We allow up to two distinct input vectors.
     SDValue ExtractedFromVec =3D N->getOperand(i).getOperand(0);
-    if (ExtractedFromVec.getValueType() !=3D VT) {
-      VecIn1 =3D VecIn2 =3D SDValue(0, 0);
-      break;
-    }
-
-    // Otherwise, remember this.  We allow up to two distinct input vector=
s.
     if (ExtractedFromVec =3D=3D VecIn1 || ExtractedFromVec =3D=3D VecIn2)
       continue;
=20
@@ -6980,7 +7631,7 @@
     }
   }
=20
-  // If everything is good, we can make a shuffle operation.
+    // If everything is good, we can make a shuffle operation.
   if (VecIn1.getNode()) {
     SmallVector<int, 8> Mask;
     for (unsigned i =3D 0; i !=3D NumInScalars; ++i) {
@@ -7006,14 +7657,39 @@
       Mask.push_back(Idx+NumInScalars);
     }
=20
-    // Add count and size info.
+    // We can't generate a shuffle node with mismatched input and output t=
ypes.
+    // Attempt to transform a single input vector to the correct type.
+    if ((VT !=3D VecIn1.getValueType())) {
+      // We don't support shuffeling between TWO values of different types.
+      if (VecIn2.getNode() !=3D 0)
+        return SDValue();
+
+      // We only support widening of vectors which are half the size of the
+      // output registers. For example XMM->YMM widening on X86 with AVX.
+      if (VecIn1.getValueType().getSizeInBits()*2 !=3D VT.getSizeInBits())
+        return SDValue();
+
+      // Widen the input vector by adding undef values.
+      VecIn1 =3D DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
+                           VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
+    }
+
+    // If VecIn2 is unused then change it to undef.
+    VecIn2 =3D VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
+
+    // Check that we were able to transform all incoming values to the sam=
e type.
+    if (VecIn2.getValueType() !=3D VecIn1.getValueType() ||
+        VecIn1.getValueType() !=3D VT)
+          return SDValue();
+
+    // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
     if (!isTypeLegal(VT))
       return SDValue();
=20
     // Return the new VECTOR_SHUFFLE node.
     SDValue Ops[2];
     Ops[0] =3D VecIn1;
-    Ops[1] =3D VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
+    Ops[1] =3D VecIn2;
     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mas=
k[0]);
   }
=20
@@ -7045,19 +7721,23 @@
     if (NVT !=3D SmallVT || NVT.getSizeInBits()*2 !=3D BigVT.getSizeInBits=
())
       return SDValue();
=20
-    // Combine:
-    //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
-    // Into:
-    //    indicies are equal =3D> V1
-    //    otherwise =3D> (extract_subvec V1, ExtIdx)
-    //
-    SDValue InsIdx =3D N->getOperand(1);
-    SDValue ExtIdx =3D V->getOperand(2);
-
-    if (InsIdx =3D=3D ExtIdx)
-      return V->getOperand(1);
-    return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
-                       V->getOperand(0), N->getOperand(1));
+    // Only handle cases where both indexes are constants with the same ty=
pe.
+    ConstantSDNode *InsIdx =3D dyn_cast<ConstantSDNode>(N->getOperand(1));
+    ConstantSDNode *ExtIdx =3D dyn_cast<ConstantSDNode>(V->getOperand(2));
+
+    if (InsIdx && ExtIdx &&
+        InsIdx->getValueType(0).getSizeInBits() <=3D 64 &&
+        ExtIdx->getValueType(0).getSizeInBits() <=3D 64) {
+      // Combine:
+      //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
+      // Into:
+      //    indices are equal =3D> V1
+      //    otherwise =3D> (extract_subvec V1, ExtIdx)
+      if (InsIdx->getZExtValue() =3D=3D ExtIdx->getZExtValue())
+        return V->getOperand(1);
+      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
+                         V->getOperand(0), N->getOperand(1));
+    }
   }
=20
   return SDValue();
@@ -7068,15 +7748,63 @@
   unsigned NumElts =3D VT.getVectorNumElements();
=20
   SDValue N0 =3D N->getOperand(0);
-
-  assert(N0.getValueType().getVectorNumElements() =3D=3D NumElts &&
-        "Vector shuffle must be normalized in DAG");
-
-  // FIXME: implement canonicalizations from DAG.getVectorShuffle()
+  SDValue N1 =3D N->getOperand(1);
+
+  assert(N0.getValueType() =3D=3D VT && "Vector shuffle must be normalized=
 in DAG");
+
+  // Canonicalize shuffle undef, undef -> undef
+  if (N0.getOpcode() =3D=3D ISD::UNDEF && N1.getOpcode() =3D=3D ISD::UNDEF)
+    return DAG.getUNDEF(VT);
+
+  ShuffleVectorSDNode *SVN =3D cast<ShuffleVectorSDNode>(N);
+
+  // Canonicalize shuffle v, v -> v, undef
+  if (N0 =3D=3D N1) {
+    SmallVector<int, 8> NewMask;
+    for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+      int Idx =3D SVN->getMaskElt(i);
+      if (Idx >=3D (int)NumElts) Idx -=3D NumElts;
+      NewMask.push_back(Idx);
+    }
+    return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
+                                &NewMask[0]);
+  }
+
+  // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
+  if (N0.getOpcode() =3D=3D ISD::UNDEF) {
+    SmallVector<int, 8> NewMask;
+    for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+      int Idx =3D SVN->getMaskElt(i);
+      if (Idx >=3D 0) {
+        if (Idx < (int)NumElts)
+          Idx +=3D NumElts;
+        else
+          Idx -=3D NumElts;
+      }
+      NewMask.push_back(Idx);
+    }
+    return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
+                                &NewMask[0]);
+  }
+
+  // Remove references to rhs if it is undef
+  if (N1.getOpcode() =3D=3D ISD::UNDEF) {
+    bool Changed =3D false;
+    SmallVector<int, 8> NewMask;
+    for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+      int Idx =3D SVN->getMaskElt(i);
+      if (Idx >=3D (int)NumElts) {
+        Idx =3D -1;
+        Changed =3D true;
+      }
+      NewMask.push_back(Idx);
+    }
+    if (Changed)
+      return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0=
]);
+  }
=20
   // If it is a splat, check if the argument vector is another splat or a
   // build_vector with all scalar elements the same.
-  ShuffleVectorSDNode *SVN =3D cast<ShuffleVectorSDNode>(N);
   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
     SDNode *V =3D N0.getNode();
=20
@@ -7115,6 +7843,40 @@
         return N0;
     }
   }
+
+  // If this shuffle node is simply a swizzle of another shuffle node,
+  // and it reverses the swizzle of the previous shuffle then we can
+  // optimize shuffle(shuffle(x, undef), undef) -> x.
+  if (N0.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDA=
G &&
+      N1.getOpcode() =3D=3D ISD::UNDEF) {
+
+    ShuffleVectorSDNode *OtherSV =3D cast<ShuffleVectorSDNode>(N0);
+
+    // Shuffle nodes can only reverse shuffles with a single non-undef val=
ue.
+    if (N0.getOperand(1).getOpcode() !=3D ISD::UNDEF)
+      return SDValue();
+
+    // The incoming shuffle must be of the same type as the result of the
+    // current shuffle.
+    assert(OtherSV->getOperand(0).getValueType() =3D=3D VT &&
+           "Shuffle types don't match");
+
+    for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+      int Idx =3D SVN->getMaskElt(i);
+      assert(Idx < (int)NumElts && "Index references undef operand");
+      // Next, this index comes from the first value, which is the incoming
+      // shuffle. Adopt the incoming index.
+      if (Idx >=3D 0)
+        Idx =3D OtherSV->getMaskElt(Idx);
+
+      // The combined shuffle must map each index to itself.
+      if (Idx >=3D 0 && (unsigned)Idx !=3D i)
+        return SDValue();
+    }
+
+    return OtherSV->getOperand(0);
+  }
+
   return SDValue();
 }
=20
@@ -7190,7 +7952,8 @@
         SDValue Elt =3D RHS.getOperand(i);
         if (!isa<ConstantSDNode>(Elt))
           return SDValue();
-        else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
+
+        if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
           Indices.push_back(i);
         else if (cast<ConstantSDNode>(Elt)->isNullValue())
           Indices.push_back(NumElts);
@@ -7261,8 +8024,19 @@
       }
=20
       EVT VT =3D LHSOp.getValueType();
-      assert(RHSOp.getValueType() =3D=3D VT &&
-             "SimplifyVBinOp with different BUILD_VECTOR element types");
+      EVT RVT =3D RHSOp.getValueType();
+      if (RVT !=3D VT) {
+        // Integer BUILD_VECTOR operands may have types larger than the el=
ement
+        // size (e.g., when the element type is not legal).  Prior to type
+        // legalization, the types may not match between the two BUILD_VEC=
TORS.
+        // Truncate one of the operands to make them match.
+        if (RVT.getSizeInBits() > VT.getSizeInBits()) {
+          RHSOp =3D DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp=
);
+        } else {
+          LHSOp =3D DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSO=
p);
+          VT =3D RVT;
+        }
+      }
       SDValue FoldOp =3D DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
                                    LHSOp, RHSOp);
       if (FoldOp.getOpcode() !=3D ISD::UNDEF &&
@@ -7374,8 +8148,8 @@
=20
       if ((LLD->hasAnyUseOfValue(1) &&
            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS)=
)) ||
-          (LLD->hasAnyUseOfValue(1) &&
-           (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS)=
)))
+          (RLD->hasAnyUseOfValue(1) &&
+           (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)=
)))
         return false;
=20
       Addr =3D DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
@@ -7393,7 +8167,7 @@
                          // FIXME: Discards pointer info.
                          LLD->getChain(), Addr, MachinePointerInfo(),
                          LLD->isVolatile(), LLD->isNonTemporal(),
-                         LLD->getAlignment());
+                         LLD->isInvariant(), LLD->getAlignment());
     } else {
       Load =3D DAG.getExtLoad(LLD->getExtensionType() =3D=3D ISD::EXTLOAD ?
                             RLD->getExtensionType() : LLD->getExtensionTyp=
e(),
@@ -7509,7 +8283,7 @@
         AddToWorkList(CPIdx.getNode());
         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CP=
Idx,
                            MachinePointerInfo::getConstantPool(), false,
-                           false, Alignment);
+                           false, false, Alignment);
=20
       }
     }
@@ -7517,8 +8291,6 @@
   // Check to see if we can perform the "gzip trick", transforming
   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
   if (N1C && N3C && N3C->isNullValue() && CC =3D=3D ISD::SETLT &&
-      N0.getValueType().isInteger() &&
-      N2.getValueType().isInteger() &&
       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
        (N1C->getAPIntValue() =3D=3D 1 && N0 =3D=3D N2))) {   // (a < 1) ? =
a : 0
     EVT XType =3D N0.getValueType();
@@ -7720,7 +8492,7 @@
 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
   std::vector<SDNode*> Built;
-  SDValue S =3D TLI.BuildSDIV(N, DAG, &Built);
+  SDValue S =3D TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
=20
   for (std::vector<SDNode*>::iterator ii =3D Built.begin(), ee =3D Built.e=
nd();
        ii !=3D ee; ++ii)
@@ -7734,7 +8506,7 @@
 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
   std::vector<SDNode*> Built;
-  SDValue S =3D TLI.BuildUDIV(N, DAG, &Built);
+  SDValue S =3D TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
=20
   for (std::vector<SDNode*>::iterator ii =3D Built.begin(), ee =3D Built.e=
nd();
        ii !=3D ee; ++ii)
@@ -7856,30 +8628,20 @@
 /// FindAliasInfo - Extracts the relevant alias information from the memory
 /// node.  Returns true if the operand was a load.
 bool DAGCombiner::FindAliasInfo(SDNode *N,
-                        SDValue &Ptr, int64_t &Size,
-                        const Value *&SrcValue,
-                        int &SrcValueOffset,
-                        unsigned &SrcValueAlign,
-                        const MDNode *&TBAAInfo) const {
-  if (LoadSDNode *LD =3D dyn_cast<LoadSDNode>(N)) {
-    Ptr =3D LD->getBasePtr();
-    Size =3D LD->getMemoryVT().getSizeInBits() >> 3;
-    SrcValue =3D LD->getSrcValue();
-    SrcValueOffset =3D LD->getSrcValueOffset();
-    SrcValueAlign =3D LD->getOriginalAlignment();
-    TBAAInfo =3D LD->getTBAAInfo();
-    return true;
-  }
-  if (StoreSDNode *ST =3D dyn_cast<StoreSDNode>(N)) {
-    Ptr =3D ST->getBasePtr();
-    Size =3D ST->getMemoryVT().getSizeInBits() >> 3;
-    SrcValue =3D ST->getSrcValue();
-    SrcValueOffset =3D ST->getSrcValueOffset();
-    SrcValueAlign =3D ST->getOriginalAlignment();
-    TBAAInfo =3D ST->getTBAAInfo();
-    return false;
-  }
-  llvm_unreachable("FindAliasInfo expected a memory operand");
+                                SDValue &Ptr, int64_t &Size,
+                                const Value *&SrcValue,
+                                int &SrcValueOffset,
+                                unsigned &SrcValueAlign,
+                                const MDNode *&TBAAInfo) const {
+  LSBaseSDNode *LS =3D cast<LSBaseSDNode>(N);
+
+  Ptr =3D LS->getBasePtr();
+  Size =3D LS->getMemoryVT().getSizeInBits() >> 3;
+  SrcValue =3D LS->getSrcValue();
+  SrcValueOffset =3D LS->getSrcValueOffset();
+  SrcValueAlign =3D LS->getOriginalAlignment();
+  TBAAInfo =3D LS->getTBAAInfo();
+  return isa<LoadSDNode>(LS);
 }
=20
 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/FastISel.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/FastISel.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -39,6 +39,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#define DEBUG_TYPE "isel"
 #include "llvm/Function.h"
 #include "llvm/GlobalVariable.h"
 #include "llvm/Instructions.h"
@@ -58,8 +59,15 @@
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/ADT/Statistic.h"
 using namespace llvm;
=20
+STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
+          "target-independent selector");
+STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
+          "target-specific selector");
+STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
+
 /// startNewBlock - Set the current block to which generated machine
 /// instructions will be appended, and clear the local CSE map.
 ///
@@ -96,6 +104,11 @@
         !hasTrivialKill(Cast->getOperand(0)))
       return false;
=20
+  // GEPs with all zero indices are trivially coalesced by fast-isel.
+  if (const GetElementPtrInst *GEP =3D dyn_cast<GetElementPtrInst>(I))
+    if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
+      return false;
+
   // Only instructions with a single use in the same basic block are consi=
dered
   // to have trivial kills.
   return I->hasOneUse() &&
@@ -123,15 +136,8 @@
       return 0;
   }
=20
-  // Look up the value to see if we already have a register for it. We
-  // cache values defined by Instructions across blocks, and other values
-  // only locally. This is because Instructions already have the SSA
-  // def-dominates-use requirement enforced.
-  DenseMap<const Value *, unsigned>::iterator I =3D FuncInfo.ValueMap.find=
(V);
-  if (I !=3D FuncInfo.ValueMap.end())
-    return I->second;
-
-  unsigned Reg =3D LocalValueMap[V];
+  // Look up the value to see if we already have a register for it.
+  unsigned Reg =3D lookUpRegForValue(V);
   if (Reg !=3D 0)
     return Reg;
=20
@@ -186,7 +192,7 @@
       uint32_t IntBitWidth =3D IntVT.getSizeInBits();
       bool isExact;
       (void) Flt.convertToInteger(x, IntBitWidth, /*isSigned=3D*/true,
-                                APFloat::rmTowardZero, &isExact);
+                                  APFloat::rmTowardZero, &isExact);
       if (isExact) {
         APInt IntVal(IntBitWidth, x);
=20
@@ -297,6 +303,18 @@
     ++FuncInfo.InsertPt;
 }
=20
+void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
+                              MachineBasicBlock::iterator E) {
+  assert (I && E && std::distance(I, E) > 0 && "Invalid iterator!");
+  while (I !=3D E) {
+    MachineInstr *Dead =3D &*I;
+    ++I;
+    Dead->eraseFromParent();
+    ++NumFastIselDead;
+  }
+  recomputeInsertPt();
+}
+
 FastISel::SavePoint FastISel::enterLocalValueArea() {
   MachineBasicBlock::iterator OldInsertPt =3D FuncInfo.InsertPt;
   DebugLoc OldDL =3D DL;
@@ -377,6 +395,13 @@
       ISDOpcode =3D ISD::SRA;
     }
=20
+    // Transform "urem x, pow2" -> "and x, pow2-1".
+    if (ISDOpcode =3D=3D ISD::UREM && isa<BinaryOperator>(I) &&
+        isPowerOf2_64(Imm)) {
+      --Imm;
+      ISDOpcode =3D ISD::AND;
+    }
+
     unsigned ResultReg =3D FastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
                                       Op0IsKill, Imm, VT.getSimpleVT());
     if (ResultReg =3D=3D 0) return false;
@@ -427,6 +452,11 @@
=20
   bool NIsKill =3D hasTrivialKill(I->getOperand(0));
=20
+  // Keep a running tab of the total offset to coalesce multiple N =3D N +=
 Offset
+  // into a single N =3D N + TotalOffset.
+  uint64_t TotalOffs =3D 0;
+  // FIXME: What's a good SWAG number for MaxOffs?
+  uint64_t MaxOffs =3D 2048;
   Type *Ty =3D I->getOperand(0)->getType();
   MVT VT =3D TLI.getPointerTy();
   for (GetElementPtrInst::const_op_iterator OI =3D I->op_begin()+1,
@@ -436,14 +466,15 @@
       unsigned Field =3D cast<ConstantInt>(Idx)->getZExtValue();
       if (Field) {
         // N =3D N + Offset
-        uint64_t Offs =3D TD.getStructLayout(StTy)->getElementOffset(Field=
);
-        // FIXME: This can be optimized by combining the add with a
-        // subsequent one.
-        N =3D FastEmit_ri_(VT, ISD::ADD, N, NIsKill, Offs, VT);
-        if (N =3D=3D 0)
-          // Unhandled operand. Halt "fast" selection and bail.
-          return false;
-        NIsKill =3D true;
+        TotalOffs +=3D TD.getStructLayout(StTy)->getElementOffset(Field);
+        if (TotalOffs >=3D MaxOffs) {
+          N =3D FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
+          if (N =3D=3D 0)
+            // Unhandled operand. Halt "fast" selection and bail.
+            return false;
+          NIsKill =3D true;
+          TotalOffs =3D 0;
+        }
       }
       Ty =3D StTy->getElementType(Field);
     } else {
@@ -452,14 +483,26 @@
       // If this is a constant subscript, handle it quickly.
       if (const ConstantInt *CI =3D dyn_cast<ConstantInt>(Idx)) {
         if (CI->isZero()) continue;
-        uint64_t Offs =3D
+        // N =3D N + Offset
+        TotalOffs +=3D=20
           TD.getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
-        N =3D FastEmit_ri_(VT, ISD::ADD, N, NIsKill, Offs, VT);
+        if (TotalOffs >=3D MaxOffs) {
+          N =3D FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
+          if (N =3D=3D 0)
+            // Unhandled operand. Halt "fast" selection and bail.
+            return false;
+          NIsKill =3D true;
+          TotalOffs =3D 0;
+        }
+        continue;
+      }
+      if (TotalOffs) {
+        N =3D FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
         if (N =3D=3D 0)
           // Unhandled operand. Halt "fast" selection and bail.
           return false;
         NIsKill =3D true;
-        continue;
+        TotalOffs =3D 0;
       }
=20
       // N =3D N + Idx * ElementSize;
@@ -484,6 +527,12 @@
         return false;
     }
   }
+  if (TotalOffs) {
+    N =3D FastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
+    if (N =3D=3D 0)
+      // Unhandled operand. Halt "fast" selection and bail.
+      return false;
+  }
=20
   // We successfully emitted code for the given LLVM Instruction.
   UpdateValueMap(I, N);
@@ -512,21 +561,32 @@
     return true;
   }
=20
+  MachineModuleInfo &MMI =3D FuncInfo.MF->getMMI();
+  ComputeUsesVAFloatArgument(*Call, &MMI);
+
   const Function *F =3D Call->getCalledFunction();
   if (!F) return false;
=20
   // Handle selected intrinsic function calls.
   switch (F->getIntrinsicID()) {
   default: break;
+    // At -O0 we don't care about the lifetime intrinsics.
+  case Intrinsic::lifetime_start:
+  case Intrinsic::lifetime_end:
+    return true;
   case Intrinsic::dbg_declare: {
     const DbgDeclareInst *DI =3D cast<DbgDeclareInst>(Call);
     if (!DIVariable(DI->getVariable()).Verify() ||
-        !FuncInfo.MF->getMMI().hasDebugInfo())
+        !FuncInfo.MF->getMMI().hasDebugInfo()) {
+      DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
       return true;
+    }
=20
     const Value *Address =3D DI->getAddress();
-    if (!Address || isa<UndefValue>(Address) || isa<AllocaInst>(Address))
+    if (!Address || isa<UndefValue>(Address)) {
+      DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
       return true;
+    }
=20
     unsigned Reg =3D 0;
     unsigned Offset =3D 0;
@@ -534,16 +594,36 @@
       // Some arguments' frame index is recorded during argument lowering.
       Offset =3D FuncInfo.getArgumentFrameIndex(Arg);
       if (Offset)
-	Reg =3D TRI.getFrameRegister(*FuncInfo.MF);
+        Reg =3D TRI.getFrameRegister(*FuncInfo.MF);
     }
     if (!Reg)
-      Reg =3D getRegForValue(Address);
+      Reg =3D lookUpRegForValue(Address);
+
+    // If we have a VLA that has a "use" in a metadata node that's then us=
ed
+    // here but it has no other uses, then we have a problem. E.g.,
+    //
+    //   int foo (const int *x) {
+    //     char a[*x];
+    //     return 0;
+    //   }
+    //
+    // If we assign 'a' a vreg and fast isel later on has to use the selec=
tion
+    // DAG isel, it will want to copy the value to the vreg. However, ther=
e are
+    // no uses, which goes counter to what selection DAG isel expects.
+    if (!Reg && !Address->use_empty() && isa<Instruction>(Address) &&
+        (!isa<AllocaInst>(Address) ||
+         !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
+      Reg =3D FuncInfo.InitializeRegForValue(Address);
=20
     if (Reg)
       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
               TII.get(TargetOpcode::DBG_VALUE))
         .addReg(Reg, RegState::Debug).addImm(Offset)
         .addMetadata(DI->getVariable());
+    else
+      // We can't yet handle anything else here because it would require
+      // generating code, thus altering codegen because of debug info.
+      DEBUG(dbgs() << "Dropping debug info for " << DI);
     return true;
   }
   case Intrinsic::dbg_value: {
@@ -581,60 +661,6 @@
     }
     return true;
   }
-  case Intrinsic::eh_exception: {
-    EVT VT =3D TLI.getValueType(Call->getType());
-    if (TLI.getOperationAction(ISD::EXCEPTIONADDR, VT)!=3DTargetLowering::=
Expand)
-      break;
-
-    assert(FuncInfo.MBB->isLandingPad() &&
-           "Call to eh.exception not in landing pad!");
-    unsigned Reg =3D TLI.getExceptionAddressRegister();
-    const TargetRegisterClass *RC =3D TLI.getRegClassFor(VT);
-    unsigned ResultReg =3D createResultReg(RC);
-    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::CO=
PY),
-            ResultReg).addReg(Reg);
-    UpdateValueMap(Call, ResultReg);
-    return true;
-  }
-  case Intrinsic::eh_selector: {
-    EVT VT =3D TLI.getValueType(Call->getType());
-    if (TLI.getOperationAction(ISD::EHSELECTION, VT) !=3D TargetLowering::=
Expand)
-      break;
-    if (FuncInfo.MBB->isLandingPad())
-      AddCatchInfo(*Call, &FuncInfo.MF->getMMI(), FuncInfo.MBB);
-    else {
-#ifndef NDEBUG
-      FuncInfo.CatchInfoLost.insert(Call);
-#endif
-      // FIXME: Mark exception selector register as live in.  Hack for PR1=
508.
-      unsigned Reg =3D TLI.getExceptionSelectorRegister();
-      if (Reg) FuncInfo.MBB->addLiveIn(Reg);
-    }
-
-    unsigned Reg =3D TLI.getExceptionSelectorRegister();
-    EVT SrcVT =3D TLI.getPointerTy();
-    const TargetRegisterClass *RC =3D TLI.getRegClassFor(SrcVT);
-    unsigned ResultReg =3D createResultReg(RC);
-    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::CO=
PY),
-            ResultReg).addReg(Reg);
-
-    bool ResultRegIsKill =3D hasTrivialKill(Call);
-
-    // Cast the register to the type of the selector.
-    if (SrcVT.bitsGT(MVT::i32))
-      ResultReg =3D FastEmit_r(SrcVT.getSimpleVT(), MVT::i32, ISD::TRUNCAT=
E,
-                             ResultReg, ResultRegIsKill);
-    else if (SrcVT.bitsLT(MVT::i32))
-      ResultReg =3D FastEmit_r(SrcVT.getSimpleVT(), MVT::i32,
-                             ISD::SIGN_EXTEND, ResultReg, ResultRegIsKill);
-    if (ResultReg =3D=3D 0)
-      // Unhandled operand. Halt "fast" selection and bail.
-      return false;
-
-    UpdateValueMap(Call, ResultReg);
-
-    return true;
-  }
   case Intrinsic::objectsize: {
     ConstantInt *CI =3D cast<ConstantInt>(Call->getArgOperand(1));
     unsigned long long Res =3D CI->isZero() ? -1ULL : 0;
@@ -726,8 +752,8 @@
   // First, try to perform the bitcast by inserting a reg-reg copy.
   unsigned ResultReg =3D 0;
   if (SrcVT.getSimpleVT() =3D=3D DstVT.getSimpleVT()) {
-    TargetRegisterClass* SrcClass =3D TLI.getRegClassFor(SrcVT);
-    TargetRegisterClass* DstClass =3D TLI.getRegClassFor(DstVT);
+    const TargetRegisterClass* SrcClass =3D TLI.getRegClassFor(SrcVT);
+    const TargetRegisterClass* DstClass =3D TLI.getRegClassFor(DstVT);
     // Don't attempt a cross-class copy. It will likely fail.
     if (SrcClass =3D=3D DstClass) {
       ResultReg =3D createResultReg(DstClass);
@@ -758,17 +784,33 @@
=20
   DL =3D I->getDebugLoc();
=20
+  MachineBasicBlock::iterator SavedInsertPt =3D FuncInfo.InsertPt;
+
   // First, try doing target-independent selection.
   if (SelectOperator(I, I->getOpcode())) {
+    ++NumFastIselSuccessIndependent;
     DL =3D DebugLoc();
     return true;
   }
+  // Remove dead code.  However, ignore call instructions since we've flus=
hed=20
+  // the local value map and recomputed the insert point.
+  if (!isa<CallInst>(I)) {
+    recomputeInsertPt();
+    if (SavedInsertPt !=3D FuncInfo.InsertPt)
+      removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
+  }
=20
   // Next, try calling the target to attempt to handle the instruction.
+  SavedInsertPt =3D FuncInfo.InsertPt;
   if (TargetSelectInstruction(I)) {
+    ++NumFastIselSuccessTarget;
     DL =3D DebugLoc();
     return true;
   }
+  // Check for dead code and remove as necessary.
+  recomputeInsertPt();
+  if (SavedInsertPt !=3D FuncInfo.InsertPt)
+    removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
=20
   DL =3D DebugLoc();
   return false;
@@ -779,8 +821,11 @@
 /// the CFG.
 void
 FastISel::FastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DL) {
-  if (FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
-    // The unconditional fall-through case, which needs no instructions.
+
+  if (FuncInfo.MBB->getBasicBlock()->size() > 1 && FuncInfo.MBB->isLayoutS=
uccessor(MSucc)) {
+    // For more accurate line information if this is the only instruction
+    // in the block then emit it, otherwise we have the unconditional
+    // fall-through case, which needs no instructions.
   } else {
     // The unconditional branch case.
     TII.InsertBranch(*FuncInfo.MBB, MSucc, NULL,
@@ -1354,8 +1399,8 @@
       // exactly one register for each non-void instruction.
       EVT VT =3D TLI.getValueType(PN->getType(), /*AllowUnknown=3D*/true);
       if (VT =3D=3D MVT::Other || !TLI.isTypeLegal(VT)) {
-        // Promote MVT::i1.
-        if (VT =3D=3D MVT::i1)
+        // Handle integer promotions, though, because they're common and e=
asy.
+        if (VT =3D=3D MVT::i1 || VT =3D=3D MVT::i8 || VT =3D=3D MVT::i16)
           VT =3D TLI.getTypeToTransformTo(LLVMBB->getContext(), VT);
         else {
           FuncInfo.PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/FunctionLoweringInfo.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -13,6 +13,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "function-lowering-info"
+#include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/CodeGen/FunctionLoweringInfo.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
@@ -68,7 +69,7 @@
   GetReturnInfo(Fn->getReturnType(),
                 Fn->getAttributes().getRetAttributes(), Outs, TLI);
   CanLowerReturn =3D TLI.CanLowerReturn(Fn->getCallingConv(), *MF,
-				      Fn->isVarArg(),
+                                      Fn->isVarArg(),
                                       Outs, Fn->getContext());
=20
   // Initialize the mapping of values to registers.  This is only set up f=
or
@@ -92,14 +93,16 @@
         // candidate. I.e., it would trigger the creation of a stack prote=
ctor.
         bool MayNeedSP =3D
           (AI->isArrayAllocation() ||
-           (TySize > 8 && isa<ArrayType>(Ty) &&
+           (TySize >=3D 8 && isa<ArrayType>(Ty) &&
             cast<ArrayType>(Ty)->getElementType()->isIntegerTy(8)));
         StaticAllocaMap[AI] =3D
-          MF->getFrameInfo()->CreateStackObject(TySize, Align, false, MayN=
eedSP);
+          MF->getFrameInfo()->CreateStackObject(TySize, Align, false,
+                                                MayNeedSP);
       }
=20
   for (; BB !=3D EB; ++BB)
-    for (BasicBlock::const_iterator I =3D BB->begin(), E =3D BB->end(); I =
!=3D E; ++I) {
+    for (BasicBlock::const_iterator I =3D BB->begin(), E =3D BB->end();
+         I !=3D E; ++I) {
       // Mark values used outside their block as exported, by allocating
       // a virtual register for them.
       if (isUsedOutsideOfDefiningBlock(I))
@@ -355,7 +358,7 @@
 /// argument. This overrides previous frame index entry for this argument,
 /// if any.
 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
-                                                      int FI) {
+                                                 int FI) {
   ByValArgFrameIndexMap[A] =3D FI;
 }
=20
@@ -367,10 +370,34 @@
     ByValArgFrameIndexMap.find(A);
   if (I !=3D ByValArgFrameIndexMap.end())
     return I->second;
-  DEBUG(dbgs() << "Argument does not have assigned frame index!");
+  DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
   return 0;
 }
=20
+/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
+/// being passed to this variadic function, and set the MachineModuleInfo's
+/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
+/// reference to _fltused on Windows, which will link in MSVCRT's
+/// floating-point support.
+void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
+                                      MachineModuleInfo *MMI)
+{
+  FunctionType *FT =3D cast<FunctionType>(
+    I.getCalledValue()->getType()->getContainedType(0));
+  if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
+    for (unsigned i =3D 0, e =3D I.getNumArgOperands(); i !=3D e; ++i) {
+      Type* T =3D I.getArgOperand(i)->getType();
+      for (po_iterator<Type*> i =3D po_begin(T), e =3D po_end(T);
+           i !=3D e; ++i) {
+        if (i->isFloatingPointTy()) {
+          MMI->setUsesVAFloatArgument(true);
+          return;
+        }
+      }
+    }
+  }
+}
+
 /// AddCatchInfo - Extract the personality and type infos from an eh.selec=
tor
 /// call, and add them to the specified machine basic block.
 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
@@ -425,34 +452,6 @@
   }
 }
=20
-void llvm::CopyCatchInfo(const BasicBlock *SuccBB, const BasicBlock *LPad,
-                         MachineModuleInfo *MMI, FunctionLoweringInfo &FLI=
) {
-  SmallPtrSet<const BasicBlock*, 4> Visited;
-
-  // The 'eh.selector' call may not be in the direct successor of a basic =
block,
-  // but could be several successors deeper. If we don't find it, try goin=
g one
-  // level further. <rdar://problem/8824861>
-  while (Visited.insert(SuccBB)) {
-    for (BasicBlock::const_iterator I =3D SuccBB->begin(), E =3D --SuccBB-=
>end();
-         I !=3D E; ++I)
-      if (const EHSelectorInst *EHSel =3D dyn_cast<EHSelectorInst>(I)) {
-        // Apply the catch info to LPad.
-        AddCatchInfo(*EHSel, MMI, FLI.MBBMap[LPad]);
-#ifndef NDEBUG
-        if (!FLI.MBBMap[SuccBB]->isLandingPad())
-          FLI.CatchInfoFound.insert(EHSel);
-#endif
-        return;
-      }
-
-    const BranchInst *Br =3D dyn_cast<BranchInst>(SuccBB->getTerminator());
-    if (Br && Br->isUnconditional())
-      SuccBB =3D Br->getSuccessor(0);
-    else
-      break;
-  }
-}
-
 /// AddLandingPadInfo - Extract the exception handling information from the
 /// landingpad instruction and add them to the specified machine module in=
fo.
 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &M=
MI,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/InstrEmitter.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/InstrEmitter.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -294,7 +294,7 @@
     const TargetRegisterClass *DstRC =3D 0;
     if (IIOpNum < II->getNumOperands())
       DstRC =3D TII->getRegClass(*II, IIOpNum, TRI);
-    assert((DstRC || (MCID.isVariadic() && IIOpNum >=3D MCID.getNumOperand=
s())) &&
+    assert((DstRC || (MI->isVariadic() && IIOpNum >=3D MCID.getNumOperands=
())) &&
            "Don't have operand info for this instruction!");
     if (DstRC && !MRI->constrainRegClass(VReg, DstRC, MinRCSize)) {
       unsigned NewVReg =3D MRI->createVirtualRegister(DstRC);
@@ -351,6 +351,8 @@
     MI->addOperand(MachineOperand::CreateFPImm(CFP));
   } else if (RegisterSDNode *R =3D dyn_cast<RegisterSDNode>(Op)) {
     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
+  } else if (RegisterMaskSDNode *RM =3D dyn_cast<RegisterMaskSDNode>(Op)) {
+    MI->addOperand(MachineOperand::CreateRegMask(RM->getRegMask()));
   } else if (GlobalAddressSDNode *TGA =3D dyn_cast<GlobalAddressSDNode>(Op=
)) {
     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(), TGA->getOffs=
et(),
                                             TGA->getTargetFlags()));
@@ -574,14 +576,19 @@
   for (unsigned i =3D 1; i !=3D NumOps; ++i) {
     SDValue Op =3D Node->getOperand(i);
     if ((i & 1) =3D=3D 0) {
-      unsigned SubIdx =3D cast<ConstantSDNode>(Op)->getZExtValue();
-      unsigned SubReg =3D getVR(Node->getOperand(i-1), VRBaseMap);
-      const TargetRegisterClass *TRC =3D MRI->getRegClass(SubReg);
-      const TargetRegisterClass *SRC =3D
+      RegisterSDNode *R =3D dyn_cast<RegisterSDNode>(Node->getOperand(i-1)=
);
+      // Skip physical registers as they don't have a vreg to get and we'll
+      // insert copies for them in TwoAddressInstructionPass anyway.
+      if (!R || !TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
+        unsigned SubIdx =3D cast<ConstantSDNode>(Op)->getZExtValue();
+        unsigned SubReg =3D getVR(Node->getOperand(i-1), VRBaseMap);
+        const TargetRegisterClass *TRC =3D MRI->getRegClass(SubReg);
+        const TargetRegisterClass *SRC =3D
         TRI->getMatchingSuperRegClass(RC, TRC, SubIdx);
-      if (SRC && SRC !=3D RC) {
-        MRI->setRegClass(NewVReg, SRC);
-        RC =3D SRC;
+        if (SRC && SRC !=3D RC) {
+          MRI->setRegClass(NewVReg, SRC);
+          RC =3D SRC;
+        }
       }
     }
     AddOperand(MI, Op, i+1, &II, VRBaseMap, /*IsDebug=3D*/false,
@@ -700,33 +707,6 @@
   // Create the new machine instruction.
   MachineInstr *MI =3D BuildMI(*MF, Node->getDebugLoc(), II);
=20
-  // The MachineInstr constructor adds implicit-def operands. Scan through
-  // these to determine which are dead.
-  if (MI->getNumOperands() !=3D 0 &&
-      Node->getValueType(Node->getNumValues()-1) =3D=3D MVT::Glue) {
-    // First, collect all used registers.
-    SmallVector<unsigned, 8> UsedRegs;
-    for (SDNode *F =3D Node->getGluedUser(); F; F =3D F->getGluedUser())
-      if (F->getOpcode() =3D=3D ISD::CopyFromReg)
-        UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg(=
));
-      else {
-        // Collect declared implicit uses.
-        const MCInstrDesc &MCID =3D TII->get(F->getMachineOpcode());
-        UsedRegs.append(MCID.getImplicitUses(),
-                        MCID.getImplicitUses() + MCID.getNumImplicitUses()=
);
-        // In addition to declared implicit uses, we must also check for
-        // direct RegisterSDNode operands.
-        for (unsigned i =3D 0, e =3D F->getNumOperands(); i !=3D e; ++i)
-          if (RegisterSDNode *R =3D dyn_cast<RegisterSDNode>(F->getOperand=
(i))) {
-            unsigned Reg =3D R->getReg();
-            if (TargetRegisterInfo::isPhysicalRegister(Reg))
-              UsedRegs.push_back(Reg);
-          }
-      }
-    // Then mark unused registers as dead.
-    MI->setPhysRegsDeadExcept(UsedRegs, *TRI);
-  }
-
   // Add result register values for things that are defined by this
   // instruction.
   if (NumResults)
@@ -751,30 +731,63 @@
   // hook knows where in the block to insert the replacement code.
   MBB->insert(InsertPos, MI);
=20
+  // The MachineInstr may also define physregs instead of virtregs.  These
+  // physreg values can reach other instructions in different ways:
+  //
+  // 1. When there is a use of a Node value beyond the explicitly defined
+  //    virtual registers, we emit a CopyFromReg for one of the implicitly
+  //    defined physregs.  This only happens when HasPhysRegOuts is true.
+  //
+  // 2. A CopyFromReg reading a physreg may be glued to this instruction.
+  //
+  // 3. A glued instruction may implicitly use a physreg.
+  //
+  // 4. A glued instruction may use a RegisterSDNode operand.
+  //
+  // Collect all the used physreg defs, and make sure that any unused phys=
reg
+  // defs are marked as dead.
+  SmallVector<unsigned, 8> UsedRegs;
+
   // Additional results must be physical register defs.
   if (HasPhysRegOuts) {
     for (unsigned i =3D II.getNumDefs(); i < NumResults; ++i) {
       unsigned Reg =3D II.getImplicitDefs()[i - II.getNumDefs()];
-      if (Node->hasAnyUseOfValue(i))
-        EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
-      // If there are no uses, mark the register as dead now, so that
-      // MachineLICM/Sink can see that it's dead. Don't do this if the
-      // node has a Glue value, for the benefit of targets still using
-      // Glue for values in physregs.
-      else if (Node->getValueType(Node->getNumValues()-1) !=3D MVT::Glue)
-        MI->addRegisterDead(Reg, TRI);
+      if (!Node->hasAnyUseOfValue(i))
+        continue;
+      // This implicitly defined physreg has a use.
+      UsedRegs.push_back(Reg);
+      EmitCopyFromReg(Node, i, IsClone, IsCloned, Reg, VRBaseMap);
     }
   }
=20
-  // If the instruction has implicit defs and the node doesn't, mark the
-  // implicit def as dead.  If the node has any glue outputs, we don't do =
this
-  // because we don't know what implicit defs are being used by glued node=
s.
-  if (Node->getValueType(Node->getNumValues()-1) !=3D MVT::Glue)
-    if (const unsigned *IDList =3D II.getImplicitDefs()) {
-      for (unsigned i =3D NumResults, e =3D II.getNumDefs()+II.getNumImpli=
citDefs();
-           i !=3D e; ++i)
-        MI->addRegisterDead(IDList[i-II.getNumDefs()], TRI);
+  // Scan the glue chain for any used physregs.
+  if (Node->getValueType(Node->getNumValues()-1) =3D=3D MVT::Glue) {
+    for (SDNode *F =3D Node->getGluedUser(); F; F =3D F->getGluedUser()) {
+      if (F->getOpcode() =3D=3D ISD::CopyFromReg) {
+        UsedRegs.push_back(cast<RegisterSDNode>(F->getOperand(1))->getReg(=
));
+        continue;
+      } else if (F->getOpcode() =3D=3D ISD::CopyToReg) {
+        // Skip CopyToReg nodes that are internal to the glue chain.
+        continue;
+      }
+      // Collect declared implicit uses.
+      const MCInstrDesc &MCID =3D TII->get(F->getMachineOpcode());
+      UsedRegs.append(MCID.getImplicitUses(),
+                      MCID.getImplicitUses() + MCID.getNumImplicitUses());
+      // In addition to declared implicit uses, we must also check for
+      // direct RegisterSDNode operands.
+      for (unsigned i =3D 0, e =3D F->getNumOperands(); i !=3D e; ++i)
+        if (RegisterSDNode *R =3D dyn_cast<RegisterSDNode>(F->getOperand(i=
))) {
+          unsigned Reg =3D R->getReg();
+          if (TargetRegisterInfo::isPhysicalRegister(Reg))
+            UsedRegs.push_back(Reg);
+        }
     }
+  }
+
+  // Finally mark unused registers as dead.
+  if (!UsedRegs.empty() || II.getImplicitDefs())
+    MI->setPhysRegsDeadExcept(UsedRegs, *TRI);
=20
   // Run post-isel target hook to adjust this instruction if needed.
 #ifdef NDEBUG
@@ -794,10 +807,8 @@
     Node->dump();
 #endif
     llvm_unreachable("This target-independent node should have been select=
ed!");
-    break;
   case ISD::EntryToken:
     llvm_unreachable("EntryToken should have been excluded from the schedu=
le!");
-    break;
   case ISD::MERGE_VALUES:
   case ISD::TokenFactor: // fall thru
     break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeDAG.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -46,47 +46,27 @@
 /// will attempt merge setcc and brc instructions into brcc's.
 ///
 namespace {
-class SelectionDAGLegalize {
+class SelectionDAGLegalize : public SelectionDAG::DAGUpdateListener {
   const TargetMachine &TM;
   const TargetLowering &TLI;
   SelectionDAG &DAG;
=20
+  /// LegalizePosition - The iterator for walking through the node list.
+  SelectionDAG::allnodes_iterator LegalizePosition;
+
+  /// LegalizedNodes - The set of nodes which have already been legalized.
+  SmallPtrSet<SDNode *, 16> LegalizedNodes;
+
   // Libcall insertion helpers.
=20
-  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has =
been
-  /// legalized.  We use this to ensure that calls are properly serialized
-  /// against each other, including inserted libcalls.
-  SDValue LastCALLSEQ_END;
-
-  /// IsLegalizingCall - This member is used *only* for purposes of provid=
ing
-  /// helpful assertions that a libcall isn't created while another call is
-  /// being legalized (which could lead to non-serialized call sequences).
-  bool IsLegalizingCall;
-
-  /// LegalizedNodes - For nodes that are of legal width, and that have mo=
re
-  /// than one use, this map indicates what regularized operand to use.  T=
his
-  /// allows us to avoid legalizing the same thing more than once.
-  DenseMap<SDValue, SDValue> LegalizedNodes;
-
-  void AddLegalizedOperand(SDValue From, SDValue To) {
-    LegalizedNodes.insert(std::make_pair(From, To));
-    // If someone requests legalization of the new node, return itself.
-    if (From !=3D To)
-      LegalizedNodes.insert(std::make_pair(To, To));
-
-    // Transfer SDDbgValues.
-    DAG.TransferDbgValues(From, To);
-  }
-
 public:
   explicit SelectionDAGLegalize(SelectionDAG &DAG);
=20
   void LegalizeDAG();
=20
 private:
-  /// LegalizeOp - Return a legal replacement for the given operation, with
-  /// all legal operands.
-  SDValue LegalizeOp(SDValue O);
+  /// LegalizeOp - Legalizes the given operation.
+  void LegalizeOp(SDNode *Node);
=20
   SDValue OptimizeFloatStore(StoreSDNode *ST);
=20
@@ -105,10 +85,7 @@
   /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
   SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
                                      SDValue N1, SDValue N2,
-                                     SmallVectorImpl<int> &Mask) const;
-
-  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
-                                    SmallPtrSet<SDNode*, 32> &NodesLeading=
To);
+                                     ArrayRef<int> Mask) const;
=20
   void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &=
CC,
                              DebugLoc dl);
@@ -150,10 +127,46 @@
   SDValue ExpandInsertToVectorThroughStack(SDValue Op);
   SDValue ExpandVectorBuildThroughStack(SDNode* Node);
=20
+  SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
+
   std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
=20
-  void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
-  void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
+  void ExpandNode(SDNode *Node);
+  void PromoteNode(SDNode *Node);
+
+  void ForgetNode(SDNode *N) {
+    LegalizedNodes.erase(N);
+    if (LegalizePosition =3D=3D SelectionDAG::allnodes_iterator(N))
+      ++LegalizePosition;
+  }
+
+public:
+  // DAGUpdateListener implementation.
+  virtual void NodeDeleted(SDNode *N, SDNode *E) {
+    ForgetNode(N);
+  }
+  virtual void NodeUpdated(SDNode *N) {}
+
+  // Node replacement helpers
+  void ReplacedNode(SDNode *N) {
+    if (N->use_empty()) {
+      DAG.RemoveDeadNode(N, this);
+    } else {
+      ForgetNode(N);
+    }
+  }
+  void ReplaceNode(SDNode *Old, SDNode *New) {
+    DAG.ReplaceAllUsesWith(Old, New, this);
+    ReplacedNode(Old);
+  }
+  void ReplaceNode(SDValue Old, SDValue New) {
+    DAG.ReplaceAllUsesWith(Old, New, this);
+    ReplacedNode(Old.getNode());
+  }
+  void ReplaceNode(SDNode *Old, const SDValue *New) {
+    DAG.ReplaceAllUsesWith(Old, New, this);
+    ReplacedNode(Old);
+  }
 };
 }
=20
@@ -164,7 +177,7 @@
 SDValue
 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT,  DebugLo=
c dl,
                                                  SDValue N1, SDValue N2,
-                                             SmallVectorImpl<int> &Mask) c=
onst {
+                                                 ArrayRef<int> Mask) const=
 {
   unsigned NumMaskElts =3D VT.getVectorNumElements();
   unsigned NumDestElts =3D NVT.getVectorNumElements();
   unsigned NumEltsGrowth =3D NumDestElts / NumMaskElts;
@@ -195,145 +208,37 @@
 }
=20
 void SelectionDAGLegalize::LegalizeDAG() {
-  LastCALLSEQ_END =3D DAG.getEntryNode();
-  IsLegalizingCall =3D false;
-
-  // The legalize process is inherently a bottom-up recursive process (use=
rs
-  // legalize their uses before themselves).  Given infinite stack space, =
we
-  // could just start legalizing on the root and traverse the whole graph.=
  In
-  // practice however, this causes us to run out of stack space on large b=
asic
-  // blocks.  To avoid this problem, compute an ordering of the nodes wher=
e each
-  // node is only legalized after all of its operands are legalized.
   DAG.AssignTopologicalOrder();
-  for (SelectionDAG::allnodes_iterator I =3D DAG.allnodes_begin(),
-       E =3D prior(DAG.allnodes_end()); I !=3D llvm::next(E); ++I)
-    LegalizeOp(SDValue(I, 0));
-
-  // Finally, it's possible the root changed.  Get the new root.
-  SDValue OldRoot =3D DAG.getRoot();
-  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
-  DAG.setRoot(LegalizedNodes[OldRoot]);
-
-  LegalizedNodes.clear();
+
+  // Visit all the nodes. We start in topological order, so that we see
+  // nodes with their original operands intact. Legalization can produce
+  // new nodes which may themselves need to be legalized. Iterate until all
+  // nodes have been legalized.
+  for (;;) {
+    bool AnyLegalized =3D false;
+    for (LegalizePosition =3D DAG.allnodes_end();
+         LegalizePosition !=3D DAG.allnodes_begin(); ) {
+      --LegalizePosition;
+
+      SDNode *N =3D LegalizePosition;
+      if (LegalizedNodes.insert(N)) {
+        AnyLegalized =3D true;
+        LegalizeOp(N);
+      }
+    }
+    if (!AnyLegalized)
+      break;
+
+  }
=20
   // Remove dead nodes now.
   DAG.RemoveDeadNodes();
 }
=20
-
-/// FindCallEndFromCallStart - Given a chained node that is part of a call
-/// sequence, find the CALLSEQ_END node that terminates the call sequence.
-static SDNode *FindCallEndFromCallStart(SDNode *Node, int depth =3D 0) {
-  // Nested CALLSEQ_START/END constructs aren't yet legal,
-  // but we can DTRT and handle them correctly here.
-  if (Node->getOpcode() =3D=3D ISD::CALLSEQ_START)
-    depth++;
-  else if (Node->getOpcode() =3D=3D ISD::CALLSEQ_END) {
-    depth--;
-    if (depth =3D=3D 0)
-      return Node;
-  }
-  if (Node->use_empty())
-    return 0;   // No CallSeqEnd
-
-  // The chain is usually at the end.
-  SDValue TheChain(Node, Node->getNumValues()-1);
-  if (TheChain.getValueType() !=3D MVT::Other) {
-    // Sometimes it's at the beginning.
-    TheChain =3D SDValue(Node, 0);
-    if (TheChain.getValueType() !=3D MVT::Other) {
-      // Otherwise, hunt for it.
-      for (unsigned i =3D 1, e =3D Node->getNumValues(); i !=3D e; ++i)
-        if (Node->getValueType(i) =3D=3D MVT::Other) {
-          TheChain =3D SDValue(Node, i);
-          break;
-        }
-
-      // Otherwise, we walked into a node without a chain.
-      if (TheChain.getValueType() !=3D MVT::Other)
-        return 0;
-    }
-  }
-
-  for (SDNode::use_iterator UI =3D Node->use_begin(),
-       E =3D Node->use_end(); UI !=3D E; ++UI) {
-
-    // Make sure to only follow users of our token chain.
-    SDNode *User =3D *UI;
-    for (unsigned i =3D 0, e =3D User->getNumOperands(); i !=3D e; ++i)
-      if (User->getOperand(i) =3D=3D TheChain)
-        if (SDNode *Result =3D FindCallEndFromCallStart(User, depth))
-          return Result;
-  }
-  return 0;
-}
-
-/// FindCallStartFromCallEnd - Given a chained node that is part of a call
-/// sequence, find the CALLSEQ_START node that initiates the call sequence.
-static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
-  int nested =3D 0;
-  assert(Node && "Didn't find callseq_start for a call??");
-  while (Node->getOpcode() !=3D ISD::CALLSEQ_START || nested) {
-    Node =3D Node->getOperand(0).getNode();
-    assert(Node->getOperand(0).getValueType() =3D=3D MVT::Other &&
-           "Node doesn't have a token chain argument!");
-    switch (Node->getOpcode()) {
-    default:
-      break;
-    case ISD::CALLSEQ_START:
-      if (!nested)
-        return Node;
-      nested--;
-      break;
-    case ISD::CALLSEQ_END:
-      nested++;
-      break;
-    }
-  }
-  return 0;
-}
-
-/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking=
 to
-/// see if any uses can reach Dest.  If no dest operands can get to dest,
-/// legalize them, legalize ourself, and return false, otherwise, return t=
rue.
-///
-/// Keep track of the nodes we fine that actually do lead to Dest in
-/// NodesLeadingTo.  This avoids retraversing them exponential number of t=
imes.
-///
-bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode =
*Dest,
-                                     SmallPtrSet<SDNode*, 32> &NodesLeadin=
gTo) {
-  if (N =3D=3D Dest) return true;  // N certainly leads to Dest :)
-
-  // If we've already processed this node and it does lead to Dest, there =
is no
-  // need to reprocess it.
-  if (NodesLeadingTo.count(N)) return true;
-
-  // If the first result of this node has been already legalized, then it =
cannot
-  // reach N.
-  if (LegalizedNodes.count(SDValue(N, 0))) return false;
-
-  // Okay, this node has not already been legalized.  Check and legalize a=
ll
-  // operands.  If none lead to Dest, then we can legalize this node.
-  bool OperandsLeadToDest =3D false;
-  for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i)
-    OperandsLeadToDest |=3D     // If an operand leads to Dest, so do we.
-      LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest,
-                                   NodesLeadingTo);
-
-  if (OperandsLeadToDest) {
-    NodesLeadingTo.insert(N);
-    return true;
-  }
-
-  // Okay, this node looks safe, legalize it and return false.
-  LegalizeOp(SDValue(N, 0));
-  return false;
-}
-
 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant =
or
 /// a load from the constant pool.
-static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
-                                SelectionDAG &DAG, const TargetLowering &T=
LI) {
+SDValue
+SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
   bool Extend =3D false;
   DebugLoc dl =3D CFP->getDebugLoc();
=20
@@ -369,20 +274,27 @@
=20
   SDValue CPIdx =3D DAG.getConstantPool(LLVMC, TLI.getPointerTy());
   unsigned Alignment =3D cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
-  if (Extend)
-    return DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
-                          DAG.getEntryNode(),
-                          CPIdx, MachinePointerInfo::getConstantPool(),
-                          VT, false, false, Alignment);
-  return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
-                     MachinePointerInfo::getConstantPool(), false, false,
-                     Alignment);
+  if (Extend) {
+    SDValue Result =3D
+      DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
+                     DAG.getEntryNode(),
+                     CPIdx, MachinePointerInfo::getConstantPool(),
+                     VT, false, false, Alignment);
+    return Result;
+  }
+  SDValue Result =3D
+    DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
+                MachinePointerInfo::getConstantPool(), false, false, false,
+                Alignment);
+  return Result;
 }
=20
 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size store=
s.
-static
-SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
-                             const TargetLowering &TLI) {
+static void ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
+                                 const TargetLowering &TLI,
+                                 SelectionDAGLegalize *DAGLegalize) {
+  assert(ST->getAddressingMode() =3D=3D ISD::UNINDEXED &&
+         "unaligned indexed stores not implemented!");
   SDValue Chain =3D ST->getChain();
   SDValue Ptr =3D ST->getBasePtr();
   SDValue Val =3D ST->getValue();
@@ -397,8 +309,10 @@
       // same size, then a (misaligned) int store.
       // FIXME: Does not handle truncating floating point stores!
       SDValue Result =3D DAG.getNode(ISD::BITCAST, dl, intVT, Val);
-      return DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
-                          ST->isVolatile(), ST->isNonTemporal(), Alignment=
);
+      Result =3D DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
+                           ST->isVolatile(), ST->isNonTemporal(), Alignmen=
t);
+      DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
+      return;
     }
     // Do a (aligned) store to a stack slot, then copy from the stack slot
     // to the final destination using (unaligned) integer loads and stores.
@@ -427,7 +341,7 @@
       // Load one integer register's worth from the stack slot.
       SDValue Load =3D DAG.getLoad(RegVT, dl, Store, StackPtr,
                                  MachinePointerInfo(),
-                                 false, false, 0);
+                                 false, false, false, 0);
       // Store it to the final location.  Remember the store.
       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
                                   ST->getPointerInfo().getWithOffset(Offse=
t),
@@ -458,8 +372,11 @@
                                        ST->isNonTemporal(),
                                        MinAlign(ST->getAlignment(), Offset=
)));
     // The order of the stores doesn't matter - say it with a TokenFactor.
-    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
-                       Stores.size());
+    SDValue Result =3D
+      DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
+                  Stores.size());
+    DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
+    return;
   }
   assert(ST->getMemoryVT().isInteger() &&
          !ST->getMemoryVT().isVector() &&
@@ -488,13 +405,18 @@
                              NewStoredVT, ST->isVolatile(), ST->isNonTempo=
ral(),
                              Alignment);
=20
-  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
+  SDValue Result =3D
+    DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
+  DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
 }
=20
 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
-static
-SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
-                            const TargetLowering &TLI) {
+static void
+ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
+                    const TargetLowering &TLI,
+                    SDValue &ValResult, SDValue &ChainResult) {
+  assert(LD->getAddressingMode() =3D=3D ISD::UNINDEXED &&
+         "unaligned indexed loads not implemented!");
   SDValue Chain =3D LD->getChain();
   SDValue Ptr =3D LD->getBasePtr();
   EVT VT =3D LD->getValueType(0);
@@ -507,13 +429,15 @@
       // then bitconvert to floating point or vector.
       SDValue newLoad =3D DAG.getLoad(intVT, dl, Chain, Ptr, LD->getPointe=
rInfo(),
                                     LD->isVolatile(),
-                                    LD->isNonTemporal(), LD->getAlignment(=
));
+                                    LD->isNonTemporal(),
+                                    LD->isInvariant(), LD->getAlignment());
       SDValue Result =3D DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
       if (VT.isFloatingPoint() && LoadedVT !=3D VT)
         Result =3D DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
=20
-      SDValue Ops[] =3D { Result, Chain };
-      return DAG.getMergeValues(Ops, 2, dl);
+      ValResult =3D Result;
+      ChainResult =3D Chain;
+      return;
     }
=20
     // Copy the value to a (aligned) stack slot using (unaligned) integer
@@ -537,6 +461,7 @@
       SDValue Load =3D DAG.getLoad(RegVT, dl, Chain, Ptr,
                                  LD->getPointerInfo().getWithOffset(Offset=
),
                                  LD->isVolatile(), LD->isNonTemporal(),
+                                 LD->isInvariant(),
                                  MinAlign(LD->getAlignment(), Offset));
       // Follow the load with a store to the stack slot.  Remember the sto=
re.
       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
@@ -572,8 +497,9 @@
                           MachinePointerInfo(), LoadedVT, false, false, 0);
=20
     // Callers expect a MERGE_VALUES node.
-    SDValue Ops[] =3D { Load, TF };
-    return DAG.getMergeValues(Ops, 2, dl);
+    ValResult =3D Load;
+    ChainResult =3D TF;
+    return;
   }
   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
          "Unaligned load of unsupported type.");
@@ -626,8 +552,8 @@
   SDValue TF =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue=
(1),
                              Hi.getValue(1));
=20
-  SDValue Ops[] =3D { Result, TF };
-  return DAG.getMergeValues(Ops, 2, dl);
+  ValResult =3D Result;
+  ChainResult =3D TF;
 }
=20
 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
@@ -672,7 +598,8 @@
                          false, false, 0);
   // Load the updated vector.
   return DAG.getLoad(VT, dl, Ch, StackPtr,
-                     MachinePointerInfo::getFixedStack(SPFI), false, false=
, 0);
+                     MachinePointerInfo::getFixedStack(SPFI), false, false=
,=20
+                     false, 0);
 }
=20
=20
@@ -763,11 +690,10 @@
=20
 /// LegalizeOp - Return a legal replacement for the given operation, with
 /// all legal operands.
-SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
-  if (Op.getOpcode() =3D=3D ISD::TargetConstant) // Allow illegal target n=
odes.
-    return Op;
-
-  SDNode *Node =3D Op.getNode();
+void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
+  if (Node->getOpcode() =3D=3D ISD::TargetConstant) // Allow illegal targe=
t nodes.
+    return;
+
   DebugLoc dl =3D Node->getDebugLoc();
=20
   for (unsigned i =3D 0, e =3D Node->getNumValues(); i !=3D e; ++i)
@@ -782,13 +708,7 @@
             Node->getOperand(i).getOpcode() =3D=3D ISD::TargetConstant) &&
            "Unexpected illegal type!");
=20
-  // Note that LegalizeOp may be reentered even from single-use nodes, whi=
ch
-  // means that we always must cache transformed nodes.
-  DenseMap<SDValue, SDValue>::iterator I =3D LegalizedNodes.find(Op);
-  if (I !=3D LegalizedNodes.end()) return I->second;
-
   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
-  SDValue Result =3D Op;
   bool isCustom =3D false;
=20
   // Figure out the correct action; the way to query this varies by opcode
@@ -798,10 +718,15 @@
   case ISD::INTRINSIC_W_CHAIN:
   case ISD::INTRINSIC_WO_CHAIN:
   case ISD::INTRINSIC_VOID:
-  case ISD::VAARG:
   case ISD::STACKSAVE:
     Action =3D TLI.getOperationAction(Node->getOpcode(), MVT::Other);
     break;
+  case ISD::VAARG:
+    Action =3D TLI.getOperationAction(Node->getOpcode(),
+                                    Node->getValueType(0));
+    if (Action !=3D TargetLowering::Promote)
+      Action =3D TLI.getOperationAction(Node->getOpcode(), MVT::Other);
+    break;
   case ISD::SINT_TO_FP:
   case ISD::UINT_TO_FP:
   case ISD::EXTRACT_VECTOR_ELT:
@@ -865,7 +790,6 @@
   case ISD::FRAME_TO_ARGS_OFFSET:
   case ISD::EH_SJLJ_SETJMP:
   case ISD::EH_SJLJ_LONGJMP:
-  case ISD::EH_SJLJ_DISPATCHSETUP:
     // These operations lie about being legal: when they claim to be legal,
     // they should actually be expanded.
     Action =3D TLI.getOperationAction(Node->getOpcode(), Node->getValueTyp=
e(0));
@@ -882,17 +806,6 @@
     if (Action =3D=3D TargetLowering::Legal)
       Action =3D TargetLowering::Custom;
     break;
-  case ISD::BUILD_VECTOR:
-    // A weird case: legalization for BUILD_VECTOR never legalizes the
-    // operands!
-    // FIXME: This really sucks... changing it isn't semantically incorrec=
t,
-    // but it massively pessimizes the code for floating-point BUILD_VECTO=
Rs
-    // because ConstantFP operands get legalized into constant pool loads
-    // before the BUILD_VECTOR code can see them.  It doesn't usually bite,
-    // though, because BUILD_VECTORS usually get lowered into other nodes
-    // which get legalized properly.
-    SimpleFinishLegalizing =3D false;
-    break;
   default:
     if (Node->getOpcode() >=3D ISD::BUILTIN_OP_END) {
       Action =3D TargetLowering::Legal;
@@ -903,22 +816,11 @@
   }
=20
   if (SimpleFinishLegalizing) {
-    SmallVector<SDValue, 8> Ops, ResultVals;
+    SmallVector<SDValue, 8> Ops;
     for (unsigned i =3D 0, e =3D Node->getNumOperands(); i !=3D e; ++i)
-      Ops.push_back(LegalizeOp(Node->getOperand(i)));
+      Ops.push_back(Node->getOperand(i));
     switch (Node->getOpcode()) {
     default: break;
-    case ISD::BR:
-    case ISD::BRIND:
-    case ISD::BR_JT:
-    case ISD::BR_CC:
-    case ISD::BRCOND:
-      // Branches tweak the chain to include LastCALLSEQ_END
-      Ops[0] =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
-                           LastCALLSEQ_END);
-      Ops[0] =3D LegalizeOp(Ops[0]);
-      LastCALLSEQ_END =3D DAG.getEntryNode();
-      break;
     case ISD::SHL:
     case ISD::SRL:
     case ISD::SRA:
@@ -926,57 +828,66 @@
     case ISD::ROTR:
       // Legalizing shifts/rotates requires adjusting the shift amount
       // to the appropriate width.
-      if (!Ops[1].getValueType().isVector())
-        Ops[1] =3D LegalizeOp(DAG.getShiftAmountOperand(Ops[0].getValueTyp=
e(),
-                                                      Ops[1]));
+      if (!Ops[1].getValueType().isVector()) {
+        SDValue SAO =3D DAG.getShiftAmountOperand(Ops[0].getValueType(), O=
ps[1]);
+        HandleSDNode Handle(SAO);
+        LegalizeOp(SAO.getNode());
+        Ops[1] =3D Handle.getValue();
+      }
       break;
     case ISD::SRL_PARTS:
     case ISD::SRA_PARTS:
     case ISD::SHL_PARTS:
       // Legalizing shifts/rotates requires adjusting the shift amount
       // to the appropriate width.
-      if (!Ops[2].getValueType().isVector())
-        Ops[2] =3D LegalizeOp(DAG.getShiftAmountOperand(Ops[0].getValueTyp=
e(),
-                                                      Ops[2]));
+      if (!Ops[2].getValueType().isVector()) {
+        SDValue SAO =3D DAG.getShiftAmountOperand(Ops[0].getValueType(), O=
ps[2]);
+        HandleSDNode Handle(SAO);
+        LegalizeOp(SAO.getNode());
+        Ops[2] =3D Handle.getValue();
+      }
       break;
     }
=20
-    Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(), Ops.data(),
-                                            Ops.size()), 0);
+    SDNode *NewNode =3D DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size(=
));
+    if (NewNode !=3D Node) {
+      DAG.ReplaceAllUsesWith(Node, NewNode, this);
+      for (unsigned i =3D 0, e =3D Node->getNumValues(); i !=3D e; ++i)
+        DAG.TransferDbgValues(SDValue(Node, i), SDValue(NewNode, i));
+      ReplacedNode(Node);
+      Node =3D NewNode;
+    }
     switch (Action) {
     case TargetLowering::Legal:
-      for (unsigned i =3D 0, e =3D Node->getNumValues(); i !=3D e; ++i)
-        ResultVals.push_back(Result.getValue(i));
-      break;
+      return;
     case TargetLowering::Custom:
       // FIXME: The handling for custom lowering with multiple results is
       // a complete mess.
-      Tmp1 =3D TLI.LowerOperation(Result, DAG);
+      Tmp1 =3D TLI.LowerOperation(SDValue(Node, 0), DAG);
       if (Tmp1.getNode()) {
+        SmallVector<SDValue, 8> ResultVals;
         for (unsigned i =3D 0, e =3D Node->getNumValues(); i !=3D e; ++i) {
           if (e =3D=3D 1)
             ResultVals.push_back(Tmp1);
           else
             ResultVals.push_back(Tmp1.getValue(i));
         }
-        break;
+        if (Tmp1.getNode() !=3D Node || Tmp1.getResNo() !=3D 0) {
+          DAG.ReplaceAllUsesWith(Node, ResultVals.data(), this);
+          for (unsigned i =3D 0, e =3D Node->getNumValues(); i !=3D e; ++i)
+            DAG.TransferDbgValues(SDValue(Node, i), ResultVals[i]);
+          ReplacedNode(Node);
+        }
+        return;
       }
=20
       // FALL THROUGH
     case TargetLowering::Expand:
-      ExpandNode(Result.getNode(), ResultVals);
-      break;
+      ExpandNode(Node);
+      return;
     case TargetLowering::Promote:
-      PromoteNode(Result.getNode(), ResultVals);
-      break;
-    }
-    if (!ResultVals.empty()) {
-      for (unsigned i =3D 0, e =3D ResultVals.size(); i !=3D e; ++i) {
-        if (ResultVals[i] !=3D SDValue(Node, i))
-          ResultVals[i] =3D LegalizeOp(ResultVals[i]);
-        AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
-      }
-      return ResultVals[Op.getResNo()];
+      PromoteNode(Node);
+      return;
     }
   }
=20
@@ -987,160 +898,24 @@
     Node->dump( &DAG);
     dbgs() << "\n";
 #endif
-    assert(0 && "Do not know how to legalize this operator!");
-
-  case ISD::SRA:
-  case ISD::SRL:
-  case ISD::SHL: {
-    // Scalarize vector SRA/SRL/SHL.
-    EVT VT =3D Node->getValueType(0);
-    assert(VT.isVector() && "Unable to legalize non-vector shift");
-    assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be leg=
al");
-    unsigned NumElem =3D VT.getVectorNumElements();
-
-    SmallVector<SDValue, 8> Scalars;
-    for (unsigned Idx =3D 0; Idx < NumElem; Idx++) {
-      SDValue Ex =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
-                               VT.getScalarType(),
-                               Node->getOperand(0), DAG.getIntPtrConstant(=
Idx));
-      SDValue Sh =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
-                               VT.getScalarType(),
-                               Node->getOperand(1), DAG.getIntPtrConstant(=
Idx));
-      Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
-                                    VT.getScalarType(), Ex, Sh));
-    }
-    Result =3D DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0),
-                         &Scalars[0], Scalars.size());
+    llvm_unreachable("Do not know how to legalize this operator!");
+
+  case ISD::CALLSEQ_START:
+  case ISD::CALLSEQ_END:
     break;
-  }
-
-  case ISD::BUILD_VECTOR:
-    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0=
))) {
-    default: assert(0 && "This action is not supported yet!");
-    case TargetLowering::Custom:
-      Tmp3 =3D TLI.LowerOperation(Result, DAG);
-      if (Tmp3.getNode()) {
-        Result =3D Tmp3;
-        break;
-      }
-      // FALLTHROUGH
-    case TargetLowering::Expand:
-      Result =3D ExpandBUILD_VECTOR(Result.getNode());
-      break;
-    }
-    break;
-  case ISD::CALLSEQ_START: {
-    SDNode *CallEnd =3D FindCallEndFromCallStart(Node);
-
-    // Recursively Legalize all of the inputs of the call end that do not =
lead
-    // to this call start.  This ensures that any libcalls that need be in=
serted
-    // are inserted *before* the CALLSEQ_START.
-    {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
-    for (unsigned i =3D 0, e =3D CallEnd->getNumOperands(); i !=3D e; ++i)
-      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
-                                   NodesLeadingTo);
-    }
-
-    // Now that we have legalized all of the inputs (which may have insert=
ed
-    // libcalls), create the new CALLSEQ_START node.
-    Tmp1 =3D LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-
-    // Merge in the last call to ensure that this call starts after the la=
st
-    // call ended.
-    if (LastCALLSEQ_END.getOpcode() !=3D ISD::EntryToken) {
-      Tmp1 =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
-                         Tmp1, LastCALLSEQ_END);
-      Tmp1 =3D LegalizeOp(Tmp1);
-    }
-
-    // Do not try to legalize the target-specific arguments (#1+).
-    if (Tmp1 !=3D Node->getOperand(0)) {
-      SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
-      Ops[0] =3D Tmp1;
-      Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(), &Ops[0],
-                                              Ops.size()), Result.getResNo=
());
-    }
-
-    // Remember that the CALLSEQ_START is legalized.
-    AddLegalizedOperand(Op.getValue(0), Result);
-    if (Node->getNumValues() =3D=3D 2)    // If this has a flag result, re=
member it.
-      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
-
-    // Now that the callseq_start and all of the non-call nodes above this=
 call
-    // sequence have been legalized, legalize the call itself.  During this
-    // process, no libcalls can/will be inserted, guaranteeing that no cal=
ls
-    // can overlap.
-    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!"=
);
-    // Note that we are selecting this call!
-    LastCALLSEQ_END =3D SDValue(CallEnd, 0);
-    IsLegalizingCall =3D true;
-
-    // Legalize the call, starting from the CALLSEQ_END.
-    LegalizeOp(LastCALLSEQ_END);
-    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
-    return Result;
-  }
-  case ISD::CALLSEQ_END:
-    // If the CALLSEQ_START node hasn't been legalized first, legalize it.=
  This
-    // will cause this node to be legalized as well as handling libcalls r=
ight.
-    if (LastCALLSEQ_END.getNode() !=3D Node) {
-      LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
-      DenseMap<SDValue, SDValue>::iterator I =3D LegalizedNodes.find(Op);
-      assert(I !=3D LegalizedNodes.end() &&
-             "Legalizing the call start should have legalized this node!");
-      return I->second;
-    }
-
-    // Otherwise, the call start has been legalized and everything is going
-    // according to plan.  Just legalize ourselves normally here.
-    Tmp1 =3D LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-    // Do not try to legalize the target-specific arguments (#1+), except =
for
-    // an optional flag input.
-    if (Node->getOperand(Node->getNumOperands()-1).getValueType() !=3D MVT=
::Glue){
-      if (Tmp1 !=3D Node->getOperand(0)) {
-        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
-        Ops[0] =3D Tmp1;
-        Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(),
-                                                &Ops[0], Ops.size()),
-                         Result.getResNo());
-      }
-    } else {
-      Tmp2 =3D LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
-      if (Tmp1 !=3D Node->getOperand(0) ||
-          Tmp2 !=3D Node->getOperand(Node->getNumOperands()-1)) {
-        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
-        Ops[0] =3D Tmp1;
-        Ops.back() =3D Tmp2;
-        Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(),
-                                                &Ops[0], Ops.size()),
-                         Result.getResNo());
-      }
-    }
-    assert(IsLegalizingCall && "Call sequence imbalance between start/end?=
");
-    // This finishes up call legalization.
-    IsLegalizingCall =3D false;
-
-    // If the CALLSEQ_END node has a flag, remember that we legalized it.
-    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
-    if (Node->getNumValues() =3D=3D 2)
-      AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
-    return Result.getValue(Op.getResNo());
   case ISD::LOAD: {
     LoadSDNode *LD =3D cast<LoadSDNode>(Node);
-    Tmp1 =3D LegalizeOp(LD->getChain());   // Legalize the chain.
-    Tmp2 =3D LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
+    Tmp1 =3D LD->getChain();   // Legalize the chain.
+    Tmp2 =3D LD->getBasePtr(); // Legalize the base pointer.
=20
     ISD::LoadExtType ExtType =3D LD->getExtensionType();
     if (ExtType =3D=3D ISD::NON_EXTLOAD) {
       EVT VT =3D Node->getValueType(0);
-      Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(),
-                                              Tmp1, Tmp2, LD->getOffset()),
-                       Result.getResNo());
-      Tmp3 =3D Result.getValue(0);
-      Tmp4 =3D Result.getValue(1);
+      Tmp3 =3D SDValue(Node, 0);
+      Tmp4 =3D SDValue(Node, 1);
=20
       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
-      default: assert(0 && "This action is not supported yet!");
+      default: llvm_unreachable("This action is not supported yet!");
       case TargetLowering::Legal:
         // If this is an unaligned load and the target doesn't support it,
         // expand it.
@@ -1148,20 +923,16 @@
           Type *Ty =3D LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
           unsigned ABIAlignment =3D TLI.getTargetData()->getABITypeAlignme=
nt(Ty);
           if (LD->getAlignment() < ABIAlignment){
-            Result =3D ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode=
()),
-                                         DAG, TLI);
-            Tmp3 =3D Result.getOperand(0);
-            Tmp4 =3D Result.getOperand(1);
-            Tmp3 =3D LegalizeOp(Tmp3);
-            Tmp4 =3D LegalizeOp(Tmp4);
+            ExpandUnalignedLoad(cast<LoadSDNode>(Node),
+                                DAG, TLI, Tmp3, Tmp4);
           }
         }
         break;
       case TargetLowering::Custom:
         Tmp1 =3D TLI.LowerOperation(Tmp3, DAG);
         if (Tmp1.getNode()) {
-          Tmp3 =3D LegalizeOp(Tmp1);
-          Tmp4 =3D LegalizeOp(Tmp1.getValue(1));
+          Tmp3 =3D Tmp1;
+          Tmp4 =3D Tmp1.getValue(1);
         }
         break;
       case TargetLowering::Promote: {
@@ -1172,17 +943,19 @@
=20
         Tmp1 =3D DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getPointerInfo(),
                            LD->isVolatile(), LD->isNonTemporal(),
-                           LD->getAlignment());
-        Tmp3 =3D LegalizeOp(DAG.getNode(ISD::BITCAST, dl, VT, Tmp1));
-        Tmp4 =3D LegalizeOp(Tmp1.getValue(1));
+                           LD->isInvariant(), LD->getAlignment());
+        Tmp3 =3D DAG.getNode(ISD::BITCAST, dl, VT, Tmp1);
+        Tmp4 =3D Tmp1.getValue(1);
         break;
       }
       }
-      // Since loads produce two values, make sure to remember that we
-      // legalized both of them.
-      AddLegalizedOperand(SDValue(Node, 0), Tmp3);
-      AddLegalizedOperand(SDValue(Node, 1), Tmp4);
-      return Op.getResNo() ? Tmp4 : Tmp3;
+      if (Tmp4.getNode() !=3D Node) {
+        assert(Tmp3.getNode() !=3D Node && "Load must be completely replac=
ed");
+        DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp3);
+        DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Tmp4);
+        ReplacedNode(Node);
+      }
+      return;
     }
=20
     EVT SrcVT =3D LD->getMemoryVT();
@@ -1213,9 +986,10 @@
       ISD::LoadExtType NewExtType =3D
         ExtType =3D=3D ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
=20
-      Result =3D DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
-                              Tmp1, Tmp2, LD->getPointerInfo(),
-                              NVT, isVolatile, isNonTemporal, Alignment);
+      SDValue Result =3D
+        DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
+                       Tmp1, Tmp2, LD->getPointerInfo(),
+                       NVT, isVolatile, isNonTemporal, Alignment);
=20
       Ch =3D Result.getValue(1); // The chain.
=20
@@ -1230,8 +1004,8 @@
                              Result.getValueType(), Result,
                              DAG.getValueType(SrcVT));
=20
-      Tmp1 =3D LegalizeOp(Result);
-      Tmp2 =3D LegalizeOp(Ch);
+      Tmp1 =3D Result;
+      Tmp2 =3D Ch;
     } else if (SrcWidth & (SrcWidth - 1)) {
       // If not loading a power-of-2 number of bits, expand as two loads.
       assert(!SrcVT.isVector() && "Unsupported extload!");
@@ -1274,7 +1048,7 @@
                                       TLI.getShiftAmountTy(Hi.getValueType=
())));
=20
         // Join the hi and lo parts.
-        Result =3D DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
+        Tmp1 =3D DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
       } else {
         // Big endian - avoid unaligned loads.
         // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD at +2:i8
@@ -1304,29 +1078,25 @@
                                       TLI.getShiftAmountTy(Hi.getValueType=
())));
=20
         // Join the hi and lo parts.
-        Result =3D DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
+        Tmp1 =3D DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
       }
=20
-      Tmp1 =3D LegalizeOp(Result);
-      Tmp2 =3D LegalizeOp(Ch);
+      Tmp2 =3D Ch;
     } else {
       switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
-      default: assert(0 && "This action is not supported yet!");
+      default: llvm_unreachable("This action is not supported yet!");
       case TargetLowering::Custom:
         isCustom =3D true;
         // FALLTHROUGH
       case TargetLowering::Legal:
-        Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(),
-                                                Tmp1, Tmp2, LD->getOffset(=
)),
-                         Result.getResNo());
-        Tmp1 =3D Result.getValue(0);
-        Tmp2 =3D Result.getValue(1);
+        Tmp1 =3D SDValue(Node, 0);
+        Tmp2 =3D SDValue(Node, 1);
=20
         if (isCustom) {
-          Tmp3 =3D TLI.LowerOperation(Result, DAG);
+          Tmp3 =3D TLI.LowerOperation(SDValue(Node, 0), DAG);
           if (Tmp3.getNode()) {
-            Tmp1 =3D LegalizeOp(Tmp3);
-            Tmp2 =3D LegalizeOp(Tmp3.getValue(1));
+            Tmp1 =3D Tmp3;
+            Tmp2 =3D Tmp3.getValue(1);
           }
         } else {
           // If this is an unaligned load and the target doesn't support i=
t,
@@ -1337,12 +1107,8 @@
             unsigned ABIAlignment =3D
               TLI.getTargetData()->getABITypeAlignment(Ty);
             if (LD->getAlignment() < ABIAlignment){
-              Result =3D ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNo=
de()),
-                                           DAG, TLI);
-              Tmp1 =3D Result.getOperand(0);
-              Tmp2 =3D Result.getOperand(1);
-              Tmp1 =3D LegalizeOp(Tmp1);
-              Tmp2 =3D LegalizeOp(Tmp2);
+              ExpandUnalignedLoad(cast<LoadSDNode>(Node),
+                                  DAG, TLI, Tmp1, Tmp2);
             }
           }
         }
@@ -1352,7 +1118,7 @@
           SDValue Load =3D DAG.getLoad(SrcVT, dl, Tmp1, Tmp2,
                                      LD->getPointerInfo(),
                                      LD->isVolatile(), LD->isNonTemporal(),
-                                     LD->getAlignment());
+                                     LD->isInvariant(), LD->getAlignment()=
);
           unsigned ExtendOp;
           switch (ExtType) {
           case ISD::EXTLOAD:
@@ -1363,95 +1129,13 @@
           case ISD::ZEXTLOAD: ExtendOp =3D ISD::ZERO_EXTEND; break;
           default: llvm_unreachable("Unexpected extend load type!");
           }
-          Result =3D DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load=
);
-          Tmp1 =3D LegalizeOp(Result);  // Relegalize new nodes.
-          Tmp2 =3D LegalizeOp(Load.getValue(1));
+          Tmp1 =3D DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
+          Tmp2 =3D Load.getValue(1);
           break;
         }
=20
-        // If this is a promoted vector load, and the vector element types=
 are
-        // legal, then scalarize it.
-        if (ExtType =3D=3D ISD::EXTLOAD && SrcVT.isVector() &&
-          TLI.isTypeLegal(Node->getValueType(0).getScalarType())) {
-          SmallVector<SDValue, 8> LoadVals;
-          SmallVector<SDValue, 8> LoadChains;
-          unsigned NumElem =3D SrcVT.getVectorNumElements();
-          unsigned Stride =3D SrcVT.getScalarType().getSizeInBits()/8;
-
-          for (unsigned Idx=3D0; Idx<NumElem; Idx++) {
-            Tmp2 =3D DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
-                                DAG.getIntPtrConstant(Stride));
-            SDValue ScalarLoad =3D DAG.getExtLoad(ISD::EXTLOAD, dl,
-                  Node->getValueType(0).getScalarType(),
-                  Tmp1, Tmp2, LD->getPointerInfo().getWithOffset(Idx * Str=
ide),
-                  SrcVT.getScalarType(),
-                  LD->isVolatile(), LD->isNonTemporal(),
-                  LD->getAlignment());
-
-            LoadVals.push_back(ScalarLoad.getValue(0));
-            LoadChains.push_back(ScalarLoad.getValue(1));
-          }
-          Result =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
-            &LoadChains[0], LoadChains.size());
-          SDValue ValRes =3D DAG.getNode(ISD::BUILD_VECTOR, dl,
-            Node->getValueType(0), &LoadVals[0], LoadVals.size());
-
-          Tmp1 =3D LegalizeOp(ValRes);  // Relegalize new nodes.
-          Tmp2 =3D LegalizeOp(Result.getValue(0));  // Relegalize new node=
s.
-          break;
-        }
-
-        // If this is a promoted vector load, and the vector element types=
 are
-        // illegal, create the promoted vector from bitcasted segments.
-        if (ExtType =3D=3D ISD::EXTLOAD && SrcVT.isVector()) {
-          EVT MemElemTy =3D Node->getValueType(0).getScalarType();
-          EVT SrcSclrTy =3D SrcVT.getScalarType();
-          unsigned SizeRatio =3D
-            (MemElemTy.getSizeInBits() / SrcSclrTy.getSizeInBits());
-
-          SmallVector<SDValue, 8> LoadVals;
-          SmallVector<SDValue, 8> LoadChains;
-          unsigned NumElem =3D SrcVT.getVectorNumElements();
-          unsigned Stride =3D SrcVT.getScalarType().getSizeInBits()/8;
-
-          for (unsigned Idx=3D0; Idx<NumElem; Idx++) {
-            Tmp2 =3D DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
-                                DAG.getIntPtrConstant(Stride));
-            SDValue ScalarLoad =3D DAG.getExtLoad(ISD::EXTLOAD, dl,
-                  SrcVT.getScalarType(),
-                  Tmp1, Tmp2, LD->getPointerInfo().getWithOffset(Idx * Str=
ide),
-                  SrcVT.getScalarType(),
-                  LD->isVolatile(), LD->isNonTemporal(),
-                  LD->getAlignment());
-            if (TLI.isBigEndian()) {
-              // MSB (which is garbage, comes first)
-              LoadVals.push_back(ScalarLoad.getValue(0));
-              for (unsigned i =3D 0; i<SizeRatio-1; ++i)
-                LoadVals.push_back(DAG.getUNDEF(SrcVT.getScalarType()));
-            } else {
-              // LSB (which is data, comes first)
-              for (unsigned i =3D 0; i<SizeRatio-1; ++i)
-                LoadVals.push_back(DAG.getUNDEF(SrcVT.getScalarType()));
-              LoadVals.push_back(ScalarLoad.getValue(0));
-            }
-            LoadChains.push_back(ScalarLoad.getValue(1));
-          }
-
-          Result =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
-            &LoadChains[0], LoadChains.size());
-          EVT TempWideVector =3D EVT::getVectorVT(*DAG.getContext(),
-            SrcVT.getScalarType(), NumElem*SizeRatio);
-          SDValue ValRes =3D DAG.getNode(ISD::BUILD_VECTOR, dl,=20
-            TempWideVector, &LoadVals[0], LoadVals.size());
-
-          // Cast to the correct type
-          ValRes =3D DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), =
ValRes);
-
-          Tmp1 =3D LegalizeOp(ValRes);  // Relegalize new nodes.
-          Tmp2 =3D LegalizeOp(Result.getValue(0));  // Relegalize new node=
s.
-          break;
-
-        }
+        assert(!SrcVT.isVector() &&
+               "Vector Loads are handled in LegalizeVectorOps");
=20
         // FIXME: This does not work for vectors on most targets.  Sign- a=
nd
         // zero-extend operations are currently folded into extending load=
s,
@@ -1461,10 +1145,10 @@
                "EXTLOAD should always be supported!");
         // Turn the unsupported load into an EXTLOAD followed by an explic=
it
         // zero/sign extend inreg.
-        Result =3D DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
-                                Tmp1, Tmp2, LD->getPointerInfo(), SrcVT,
-                                LD->isVolatile(), LD->isNonTemporal(),
-                                LD->getAlignment());
+        SDValue Result =3D DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValue=
Type(0),
+                                        Tmp1, Tmp2, LD->getPointerInfo(), =
SrcVT,
+                                        LD->isVolatile(), LD->isNonTempora=
l(),
+                                        LD->getAlignment());
         SDValue ValRes;
         if (ExtType =3D=3D ISD::SEXTLOAD)
           ValRes =3D DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
@@ -1472,42 +1156,41 @@
                                Result, DAG.getValueType(SrcVT));
         else
           ValRes =3D DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarTyp=
e());
-        Tmp1 =3D LegalizeOp(ValRes);  // Relegalize new nodes.
-        Tmp2 =3D LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
+        Tmp1 =3D ValRes;
+        Tmp2 =3D Result.getValue(1);
         break;
       }
     }
=20
     // Since loads produce two values, make sure to remember that we legal=
ized
     // both of them.
-    AddLegalizedOperand(SDValue(Node, 0), Tmp1);
-    AddLegalizedOperand(SDValue(Node, 1), Tmp2);
-    return Op.getResNo() ? Tmp2 : Tmp1;
+    if (Tmp2.getNode() !=3D Node) {
+      assert(Tmp1.getNode() !=3D Node && "Load must be completely replaced=
");
+      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp1);
+      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Tmp2);
+      ReplacedNode(Node);
+    }
+    break;
   }
   case ISD::STORE: {
     StoreSDNode *ST =3D cast<StoreSDNode>(Node);
-    Tmp1 =3D LegalizeOp(ST->getChain());    // Legalize the chain.
-    Tmp2 =3D LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
+    Tmp1 =3D ST->getChain();
+    Tmp2 =3D ST->getBasePtr();
     unsigned Alignment =3D ST->getAlignment();
     bool isVolatile =3D ST->isVolatile();
     bool isNonTemporal =3D ST->isNonTemporal();
=20
     if (!ST->isTruncatingStore()) {
       if (SDNode *OptStore =3D OptimizeFloatStore(ST).getNode()) {
-        Result =3D SDValue(OptStore, 0);
+        ReplaceNode(ST, OptStore);
         break;
       }
=20
       {
-        Tmp3 =3D LegalizeOp(ST->getValue());
-        Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(),
-                                                Tmp1, Tmp3, Tmp2,
-                                                ST->getOffset()),
-                         Result.getResNo());
-
+        Tmp3 =3D ST->getValue();
         EVT VT =3D Tmp3.getValueType();
         switch (TLI.getOperationAction(ISD::STORE, VT)) {
-        default: assert(0 && "This action is not supported yet!");
+        default: llvm_unreachable("This action is not supported yet!");
         case TargetLowering::Legal:
           // If this is an unaligned store and the target doesn't support =
it,
           // expand it.
@@ -1515,27 +1198,31 @@
             Type *Ty =3D ST->getMemoryVT().getTypeForEVT(*DAG.getContext()=
);
             unsigned ABIAlignment=3D TLI.getTargetData()->getABITypeAlignm=
ent(Ty);
             if (ST->getAlignment() < ABIAlignment)
-              Result =3D ExpandUnalignedStore(cast<StoreSDNode>(Result.get=
Node()),
-                                            DAG, TLI);
+              ExpandUnalignedStore(cast<StoreSDNode>(Node),
+                                   DAG, TLI, this);
           }
           break;
         case TargetLowering::Custom:
-          Tmp1 =3D TLI.LowerOperation(Result, DAG);
-          if (Tmp1.getNode()) Result =3D Tmp1;
+          Tmp1 =3D TLI.LowerOperation(SDValue(Node, 0), DAG);
+          if (Tmp1.getNode())
+            ReplaceNode(SDValue(Node, 0), Tmp1);
           break;
-        case TargetLowering::Promote:
+        case TargetLowering::Promote: {
           assert(VT.isVector() && "Unknown legal promote case!");
           Tmp3 =3D DAG.getNode(ISD::BITCAST, dl,
                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
-          Result =3D DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
-                                ST->getPointerInfo(), isVolatile,
-                                isNonTemporal, Alignment);
+          SDValue Result =3D
+            DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
+                         ST->getPointerInfo(), isVolatile,
+                         isNonTemporal, Alignment);
+          ReplaceNode(SDValue(Node, 0), Result);
           break;
         }
+        }
         break;
       }
     } else {
-      Tmp3 =3D LegalizeOp(ST->getValue());
+      Tmp3 =3D ST->getValue();
=20
       EVT StVT =3D ST->getMemoryVT();
       unsigned StWidth =3D StVT.getSizeInBits();
@@ -1547,8 +1234,10 @@
         EVT NVT =3D EVT::getIntegerVT(*DAG.getContext(),
                                     StVT.getStoreSizeInBits());
         Tmp3 =3D DAG.getZeroExtendInReg(Tmp3, dl, StVT);
-        Result =3D DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerI=
nfo(),
-                                   NVT, isVolatile, isNonTemporal, Alignme=
nt);
+        SDValue Result =3D
+          DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
+                            NVT, isVolatile, isNonTemporal, Alignment);
+        ReplaceNode(SDValue(Node, 0), Result);
       } else if (StWidth & (StWidth - 1)) {
         // If not storing a power-of-2 number of bits, expand as two store=
s.
         assert(!StVT.isVector() && "Unsupported truncstore!");
@@ -1602,17 +1291,11 @@
         }
=20
         // The order of the stores doesn't matter.
-        Result =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
+        SDValue Result =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other, L=
o, Hi);
+        ReplaceNode(SDValue(Node, 0), Result);
       } else {
-        if (Tmp1 !=3D ST->getChain() || Tmp3 !=3D ST->getValue() ||
-            Tmp2 !=3D ST->getBasePtr())
-          Result =3D SDValue(DAG.UpdateNodeOperands(Result.getNode(),
-                                                  Tmp1, Tmp3, Tmp2,
-                                                  ST->getOffset()),
-                           Result.getResNo());
-
         switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StV=
T)) {
-        default: assert(0 && "This action is not supported yet!");
+        default: llvm_unreachable("This action is not supported yet!");
         case TargetLowering::Legal:
           // If this is an unaligned store and the target doesn't support =
it,
           // expand it.
@@ -1620,120 +1303,24 @@
             Type *Ty =3D ST->getMemoryVT().getTypeForEVT(*DAG.getContext()=
);
             unsigned ABIAlignment=3D TLI.getTargetData()->getABITypeAlignm=
ent(Ty);
             if (ST->getAlignment() < ABIAlignment)
-              Result =3D ExpandUnalignedStore(cast<StoreSDNode>(Result.get=
Node()),
-                                            DAG, TLI);
+              ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this=
);
           }
           break;
         case TargetLowering::Custom:
-          Result =3D TLI.LowerOperation(Result, DAG);
+          ReplaceNode(SDValue(Node, 0),
+                      TLI.LowerOperation(SDValue(Node, 0), DAG));
           break;
         case TargetLowering::Expand:
-
-          EVT WideScalarVT =3D Tmp3.getValueType().getScalarType();
-          EVT NarrowScalarVT =3D StVT.getScalarType();
-
-          if (StVT.isVector()) {
-            unsigned NumElem =3D StVT.getVectorNumElements();
-            // The type of the data we want to save
-            EVT RegVT =3D Tmp3.getValueType();
-            EVT RegSclVT =3D RegVT.getScalarType();
-            // The type of data as saved in memory.
-            EVT MemSclVT =3D StVT.getScalarType();
-
-            bool RegScalarLegal =3D TLI.isTypeLegal(RegSclVT);
-            bool MemScalarLegal =3D TLI.isTypeLegal(MemSclVT);
-
-            // We need to expand this store. If the register element type
-            // is legal then we can scalarize the vector and use
-            // truncating stores.
-            if (RegScalarLegal) {
-              // Cast floats into integers
-              unsigned ScalarSize =3D MemSclVT.getSizeInBits();
-              EVT EltVT =3D EVT::getIntegerVT(*DAG.getContext(), ScalarSiz=
e);
-
-              // Round odd types to the next pow of two.
-              if (!isPowerOf2_32(ScalarSize))
-                ScalarSize =3D NextPowerOf2(ScalarSize);
-
-              // Store Stride in bytes
-              unsigned Stride =3D ScalarSize/8;
-              // Extract each of the elements from the original vector
-              // and save them into memory individually.
-              SmallVector<SDValue, 8> Stores;
-              for (unsigned Idx =3D 0; Idx < NumElem; Idx++) {
-                SDValue Ex =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
-                                RegSclVT, Tmp3, DAG.getIntPtrConstant(Idx)=
);
-
-                Tmp2 =3D DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tm=
p2,
-                                   DAG.getIntPtrConstant(Stride));
-
-                // This scalar TruncStore may be illegal, but we lehalize =
it
-                // later.
-                SDValue Store =3D DAG.getTruncStore(Tmp1, dl, Ex, Tmp2,
-                      ST->getPointerInfo().getWithOffset(Idx*Stride), MemS=
clVT,
-                      isVolatile, isNonTemporal, Alignment);
-
-                Stores.push_back(Store);
-              }
-
-              Result =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
-                                   &Stores[0], Stores.size());
-              break;
-            }
-
-            // The scalar register type is illegal.
-            // For example saving <2 x i64> -> <2 x i32> on a x86.
-            // In here we bitcast the value into a vector of smaller parts=
 and
-            // save it using smaller scalars.
-            if (!RegScalarLegal && MemScalarLegal) {
-              // Store Stride in bytes
-              unsigned Stride =3D MemSclVT.getSizeInBits()/8;
-
-              unsigned SizeRatio =3D
-                (RegSclVT.getSizeInBits() / MemSclVT.getSizeInBits());
-
-              EVT CastValueVT =3D EVT::getVectorVT(*DAG.getContext(),
-                                                 MemSclVT,
-                                                 SizeRatio * NumElem);
-
-              // Cast the wide elem vector to wider vec with smaller elem =
type.
-              // Example <2 x i64> -> <4 x i32>
-              Tmp3 =3D DAG.getNode(ISD::BITCAST, dl, CastValueVT, Tmp3);
-
-              SmallVector<SDValue, 8> Stores;
-              for (unsigned Idx=3D0; Idx < NumElem * SizeRatio; Idx++) {
-                // Extract the Ith element.
-                SDValue Ex =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
-                               NarrowScalarVT, Tmp3, DAG.getIntPtrConstant=
(Idx));
-                // Bump pointer.
-                Tmp2 =3D DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tm=
p2,
-                                   DAG.getIntPtrConstant(Stride));
-
-                // Store if, this element is:
-                //  - First element on big endian, or
-                //  - Last element on little endian
-                if (( TLI.isBigEndian() && (Idx % SizeRatio =3D=3D 0)) ||
-                    ((!TLI.isBigEndian() && (Idx % SizeRatio =3D=3D SizeRa=
tio-1)))) {
-                  SDValue Store =3D DAG.getStore(Tmp1, dl, Ex, Tmp2,
-                                  ST->getPointerInfo().getWithOffset(Idx*S=
tride),
-                                           isVolatile, isNonTemporal, Alig=
nment);
-                  Stores.push_back(Store);
-                }
-              }
-              Result =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
-                                   &Stores[0], Stores.size());
-              break;
-            }
-
-            assert(false && "Unable to legalize the vector trunc store!");
-          }// is vector
-
+          assert(!StVT.isVector() &&
+                 "Vector Stores are handled in LegalizeVectorOps");
=20
           // TRUNCSTORE:i16 i32 -> STORE i16
           assert(TLI.isTypeLegal(StVT) && "Do not know how to expand this =
store!");
           Tmp3 =3D DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
-          Result =3D DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo=
(),
-                                isVolatile, isNonTemporal, Alignment);
+          SDValue Result =3D
+            DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
+                         isVolatile, isNonTemporal, Alignment);
+          ReplaceNode(SDValue(Node, 0), Result);
           break;
         }
       }
@@ -1741,17 +1328,6 @@
     break;
   }
   }
-  assert(Result.getValueType() =3D=3D Op.getValueType() &&
-         "Bad legalization!");
-
-  // Make sure that the generated code is itself legal.
-  if (Result !=3D Op)
-    Result =3D LegalizeOp(Result);
-
-  // Note that LegalizeOp may be reentered even from single-use nodes, whi=
ch
-  // means that we always must cache transformed nodes.
-  AddLegalizedOperand(Op, Result);
-  return Result;
 }
=20
 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue =
Op) {
@@ -1778,7 +1354,7 @@
=20
   if (Op.getValueType().isVector())
     return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerI=
nfo(),
-                       false, false, 0);
+                       false, false, false, 0);
   return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
                         MachinePointerInfo(),
                         Vec.getValueType().getVectorElementType(),
@@ -1826,7 +1402,7 @@
=20
   // Finally, load the updated vector.
   return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
-                     false, false, 0);
+                     false, false, false, 0);
 }
=20
 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
@@ -1876,7 +1452,8 @@
     StoreChain =3D DAG.getEntryNode();
=20
   // Result is a load from the stack slot.
-  return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo, false, false, 0);
+  return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo,=20
+                     false, false, false, 0);
 }
=20
 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
@@ -1905,7 +1482,7 @@
       assert(FloatVT.isByteSized() && "Unsupported floating point type!");
       // Load out a legal integer with the same sign bit as the float.
       SignBit =3D DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo=
(),
-                            false, false, 0);
+                            false, false, false, 0);
     } else { // Little endian
       SDValue LoadPtr =3D StackPtr;
       // The float may be wider than the integer we are going to load.  Ad=
vance
@@ -1916,7 +1493,7 @@
                             LoadPtr, DAG.getIntPtrConstant(ByteOffset));
       // Load a legal integer containing the sign bit.
       SignBit =3D DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(=
),
-                            false, false, 0);
+                            false, false, false, 0);
       // Move the sign bit to the top bit of the loaded integer.
       unsigned BitShift =3D LoadTy.getSizeInBits() -
         (FloatVT.getSizeInBits() - 8 * ByteOffset);
@@ -1984,7 +1561,7 @@
   EVT OpVT =3D LHS.getValueType();
   ISD::CondCode CCCode =3D cast<CondCodeSDNode>(CC)->get();
   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
-  default: assert(0 && "Unknown condition code action!");
+  default: llvm_unreachable("Unknown condition code action!");
   case TargetLowering::Legal:
     // Nothing to do.
     break;
@@ -1992,7 +1569,7 @@
     ISD::CondCode CC1 =3D ISD::SETCC_INVALID, CC2 =3D ISD::SETCC_INVALID;
     unsigned Opc =3D 0;
     switch (CCCode) {
-    default: assert(0 && "Don't know how to expand this condition!");
+    default: llvm_unreachable("Don't know how to expand this condition!");
     case ISD::SETOEQ: CC1 =3D ISD::SETEQ; CC2 =3D ISD::SETO;  Opc =3D ISD:=
:AND; break;
     case ISD::SETOGT: CC1 =3D ISD::SETGT; CC2 =3D ISD::SETO;  Opc =3D ISD:=
:AND; break;
     case ISD::SETOGE: CC1 =3D ISD::SETGE; CC2 =3D ISD::SETO;  Opc =3D ISD:=
:AND; break;
@@ -2058,7 +1635,7 @@
   // Result is a load from the stack slot.
   if (SlotSize =3D=3D DestSize)
     return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
-                       false, false, DestAlign);
+                       false, false, false, DestAlign);
=20
   assert(SlotSize < DestSize && "Unknown extension!");
   return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
@@ -2081,7 +1658,7 @@
                                  false, false, 0);
   return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
                      MachinePointerInfo::getFixedStack(SPFI),
-                     false, false, 0);
+                     false, false, false, 0);
 }
=20
=20
@@ -2127,7 +1704,7 @@
=20
   // If all elements are constants, create a load from the constant pool.
   if (isConstant) {
-    std::vector<Constant*> CV;
+    SmallVector<Constant*, 16> CV;
     for (unsigned i =3D 0, e =3D NumElems; i !=3D e; ++i) {
       if (ConstantFPSDNode *V =3D
           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
@@ -2155,7 +1732,7 @@
     unsigned Alignment =3D cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
     return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
                        MachinePointerInfo::getConstantPool(),
-                       false, false, Alignment);
+                       false, false, false, Alignment);
   }
=20
   if (!MoreThanTwoValues) {
@@ -2190,12 +1767,6 @@
 // and leave the Hi part unset.
 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Nod=
e,
                                             bool isSigned) {
-  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
-  // The input chain to this libcall is the entry node of the function.
-  // Legalizing the call will automatically add the previous call to the
-  // dependence.
-  SDValue InChain =3D DAG.getEntryNode();
-
   TargetLowering::ArgListTy Args;
   TargetLowering::ArgListEntry Entry;
   for (unsigned i =3D 0, e =3D Node->getNumOperands(); i !=3D e; ++i) {
@@ -2209,26 +1780,31 @@
   SDValue Callee =3D DAG.getExternalSymbol(TLI.getLibcallName(LC),
                                          TLI.getPointerTy());
=20
-  // Splice the libcall in wherever FindInputOutputChains tells us to.
   Type *RetTy =3D Node->getValueType(0).getTypeForEVT(*DAG.getContext());
=20
+  // By default, the input chain to this libcall is the entry node of the
+  // function. If the libcall is going to be emitted as a tail call then
+  // TLI.isUsedByReturnOnly will change it to the right chain if the return
+  // node which is being folded has a non-entry input chain.
+  SDValue InChain =3D DAG.getEntryNode();
+
   // isTailCall may be true since the callee does not reference caller sta=
ck
   // frame. Check if it's in the right position.
-  bool isTailCall =3D isInTailCallPosition(DAG, Node, TLI);
+  SDValue TCChain =3D InChain;
+  bool isTailCall =3D isInTailCallPosition(DAG, Node, TCChain, TLI);
+  if (isTailCall)
+    InChain =3D TCChain;
+
   std::pair<SDValue, SDValue> CallInfo =3D
     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
                     0, TLI.getLibcallCallingConv(LC), isTailCall,
-                    /*isReturnValueUsed=3D*/true,
+                    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/tru=
e,
                     Callee, Args, DAG, Node->getDebugLoc());
=20
   if (!CallInfo.second.getNode())
     // It's a tailcall, return the chain (which is the DAG root).
     return DAG.getRoot();
=20
-  // Legalize the call sequence, starting with the chain.  This will advan=
ce
-  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node =
that
-  // was added by LowerCallTo (guaranteeing proper serialization of calls).
-  LegalizeOp(CallInfo.second);
   return CallInfo.first;
 }
=20
@@ -2254,15 +1830,10 @@
   Type *RetTy =3D RetVT.getTypeForEVT(*DAG.getContext());
   std::pair<SDValue,SDValue> CallInfo =3D
   TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
-                  false, 0, TLI.getLibcallCallingConv(LC), false,
-                  /*isReturnValueUsed=3D*/true,
+                  false, 0, TLI.getLibcallCallingConv(LC), /*isTailCall=3D=
*/false,
+                  /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/true,
                   Callee, Args, DAG, dl);
=20
-  // Legalize the call sequence, starting with the chain.  This will advan=
ce
-  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node =
that
-  // was added by LowerCallTo (guaranteeing proper serialization of calls).
-  LegalizeOp(CallInfo.second);
-
   return CallInfo.first;
 }
=20
@@ -2272,7 +1843,6 @@
 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
                                          SDNode *Node,
                                          bool isSigned) {
-  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
   SDValue InChain =3D Node->getOperand(0);
=20
   TargetLowering::ArgListTy Args;
@@ -2289,18 +1859,13 @@
   SDValue Callee =3D DAG.getExternalSymbol(TLI.getLibcallName(LC),
                                          TLI.getPointerTy());
=20
-  // Splice the libcall in wherever FindInputOutputChains tells us to.
   Type *RetTy =3D Node->getValueType(0).getTypeForEVT(*DAG.getContext());
   std::pair<SDValue, SDValue> CallInfo =3D
     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
                     0, TLI.getLibcallCallingConv(LC), /*isTailCall=3D*/fal=
se,
-                    /*isReturnValueUsed=3D*/true,
+                    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/tru=
e,
                     Callee, Args, DAG, Node->getDebugLoc());
=20
-  // Legalize the call sequence, starting with the chain.  This will advan=
ce
-  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node =
that
-  // was added by LowerCallTo (guaranteeing proper serialization of calls).
-  LegalizeOp(CallInfo.second);
   return CallInfo;
 }
=20
@@ -2311,7 +1876,7 @@
                                               RTLIB::Libcall Call_PPCF128)=
 {
   RTLIB::Libcall LC;
   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
-  default: assert(0 && "Unexpected request for libcall!");
+  default: llvm_unreachable("Unexpected request for libcall!");
   case MVT::f32: LC =3D Call_F32; break;
   case MVT::f64: LC =3D Call_F64; break;
   case MVT::f80: LC =3D Call_F80; break;
@@ -2328,7 +1893,7 @@
                                                RTLIB::Libcall Call_I128) {
   RTLIB::Libcall LC;
   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
-  default: assert(0 && "Unexpected request for libcall!");
+  default: llvm_unreachable("Unexpected request for libcall!");
   case MVT::i8:   LC =3D Call_I8; break;
   case MVT::i16:  LC =3D Call_I16; break;
   case MVT::i32:  LC =3D Call_I32; break;
@@ -2343,7 +1908,7 @@
                                      const TargetLowering &TLI) {
   RTLIB::Libcall LC;
   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
-  default: assert(0 && "Unexpected request for libcall!");
+  default: llvm_unreachable("Unexpected request for libcall!");
   case MVT::i8:   LC=3D isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;=
  break;
   case MVT::i16:  LC=3D isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16=
; break;
   case MVT::i32:  LC=3D isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32=
; break;
@@ -2388,7 +1953,7 @@
=20
   RTLIB::Libcall LC;
   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
-  default: assert(0 && "Unexpected request for libcall!");
+  default: llvm_unreachable("Unexpected request for libcall!");
   case MVT::i8:   LC=3D isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;=
  break;
   case MVT::i16:  LC=3D isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16=
; break;
   case MVT::i32:  LC=3D isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32=
; break;
@@ -2426,21 +1991,16 @@
   SDValue Callee =3D DAG.getExternalSymbol(TLI.getLibcallName(LC),
                                          TLI.getPointerTy());
=20
-  // Splice the libcall in wherever FindInputOutputChains tells us to.
   DebugLoc dl =3D Node->getDebugLoc();
   std::pair<SDValue, SDValue> CallInfo =3D
     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
                     0, TLI.getLibcallCallingConv(LC), /*isTailCall=3D*/fal=
se,
-                    /*isReturnValueUsed=3D*/true, Callee, Args, DAG, dl);
-
-  // Legalize the call sequence, starting with the chain.  This will advan=
ce
-  // the LastCALLSEQ to the legalized version of the CALLSEQ_END node that
-  // was added by LowerCallTo (guaranteeing proper serialization of calls).
-  LegalizeOp(CallInfo.second);
+                    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/tru=
e,
+                    Callee, Args, DAG, dl);
=20
   // Remainder is loaded back from the stack frame.
-  SDValue Rem =3D DAG.getLoad(RetVT, dl, LastCALLSEQ_END, FIPtr,
-                            MachinePointerInfo(), false, false, 0);
+  SDValue Rem =3D DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr,
+                            MachinePointerInfo(), false, false, false, 0);
   Results.push_back(CallInfo.first);
   Results.push_back(Rem);
 }
@@ -2489,7 +2049,7 @@
                                   false, false, 0);
     // load the constructed double
     SDValue Load =3D DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
-                               MachinePointerInfo(), false, false, 0);
+                               MachinePointerInfo(), false, false, false, =
0);
     // FP constant to bias correct the final result
     SDValue Bias =3D DAG.getConstantFP(isSigned ?
                                      BitsToDouble(0x4330000080000000ULL) :
@@ -2611,7 +2171,7 @@
   // offset depending on the data type.
   uint64_t FF;
   switch (Op0.getValueType().getSimpleVT().SimpleTy) {
-  default: assert(0 && "Unsupported integer type!");
+  default: llvm_unreachable("Unsupported integer type!");
   case MVT::i8 : FF =3D 0x43800000ULL; break;  // 2^8  (as a float)
   case MVT::i16: FF =3D 0x47800000ULL; break;  // 2^16 (as a float)
   case MVT::i32: FF =3D 0x4F800000ULL; break;  // 2^32 (as a float)
@@ -2629,13 +2189,15 @@
   if (DestVT =3D=3D MVT::f32)
     FudgeInReg =3D DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
                              MachinePointerInfo::getConstantPool(),
-                             false, false, Alignment);
+                             false, false, false, Alignment);
   else {
-    FudgeInReg =3D
-      LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
-                                DAG.getEntryNode(), CPIdx,
-                                MachinePointerInfo::getConstantPool(),
-                                MVT::f32, false, false, Alignment));
+    SDValue Load =3D DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
+                                  DAG.getEntryNode(), CPIdx,
+                                  MachinePointerInfo::getConstantPool(),
+                                  MVT::f32, false, false, Alignment);
+    HandleSDNode Handle(Load);
+    LegalizeOp(Load.getNode());
+    FudgeInReg =3D Handle.getValue();
   }
=20
   return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
@@ -2731,7 +2293,7 @@
   EVT SHVT =3D TLI.getShiftAmountTy(VT);
   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
   switch (VT.getSimpleVT().SimpleTy) {
-  default: assert(0 && "Unhandled Expand type in BSWAP!");
+  default: llvm_unreachable("Unhandled Expand type in BSWAP!");
   case MVT::i16:
     Tmp2 =3D DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
     Tmp1 =3D DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
@@ -2788,7 +2350,7 @@
 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
                                              DebugLoc dl) {
   switch (Opc) {
-  default: assert(0 && "Cannot expand this yet!");
+  default: llvm_unreachable("Cannot expand this yet!");
   case ISD::CTPOP: {
     EVT VT =3D Op.getValueType();
     EVT ShVT =3D TLI.getShiftAmountTy(VT);
@@ -2831,6 +2393,9 @@
=20
     return Op;
   }
+  case ISD::CTLZ_ZERO_UNDEF:
+    // This trivially expands to CTLZ.
+    return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
   case ISD::CTLZ: {
     // for now, we do this:
     // x =3D x | (x >> 1);
@@ -2852,6 +2417,9 @@
     Op =3D DAG.getNOT(dl, Op, VT);
     return DAG.getNode(ISD::CTPOP, dl, VT, Op);
   }
+  case ISD::CTTZ_ZERO_UNDEF:
+    // This trivially expands to CTTZ.
+    return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
   case ISD::CTTZ: {
     // for now, we use: { return popcount(~x & (x - 1)); }
     // unless the target has ctlz but not ctpop, in which case we use:
@@ -2881,7 +2449,6 @@
   switch (Opc) {
   default:
     llvm_unreachable("Unhandled atomic intrinsic Expand!");
-    break;
   case ISD::ATOMIC_SWAP:
     switch (VT.SimpleTy) {
     default: llvm_unreachable("Unexpected value type for atomic!");
@@ -2959,14 +2526,16 @@
   return ExpandChainLibCall(LC, Node, false);
 }
=20
-void SelectionDAGLegalize::ExpandNode(SDNode *Node,
-                                      SmallVectorImpl<SDValue> &Results) {
+void SelectionDAGLegalize::ExpandNode(SDNode *Node) {
+  SmallVector<SDValue, 8> Results;
   DebugLoc dl =3D Node->getDebugLoc();
   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
   switch (Node->getOpcode()) {
   case ISD::CTPOP:
   case ISD::CTLZ:
+  case ISD::CTLZ_ZERO_UNDEF:
   case ISD::CTTZ:
+  case ISD::CTTZ_ZERO_UNDEF:
     Tmp1 =3D ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
     Results.push_back(Tmp1);
     break;
@@ -2986,7 +2555,6 @@
   case ISD::PREFETCH:
   case ISD::VAEND:
   case ISD::EH_SJLJ_LONGJMP:
-  case ISD::EH_SJLJ_DISPATCHSETUP:
     // If the target didn't expand these, there's nothing to do, so just
     // preserve the chain and be done.
     Results.push_back(Node->getOperand(0));
@@ -3006,7 +2574,7 @@
       TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext=
()),
                       false, false, false, false, 0, CallingConv::C,
                       /*isTailCall=3D*/false,
-                      /*isReturnValueUsed=3D*/true,
+                      /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/t=
rue,
                       DAG.getExternalSymbol("__sync_synchronize",
                                             TLI.getPointerTy()),
                       Args, DAG, dl);
@@ -3083,7 +2651,7 @@
       TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext=
()),
                       false, false, false, false, 0, CallingConv::C,
                       /*isTailCall=3D*/false,
-                      /*isReturnValueUsed=3D*/true,
+                      /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/t=
rue,
                       DAG.getExternalSymbol("abort", TLI.getPointerTy()),
                       Args, DAG, dl);
     Results.push_back(CallResult.second);
@@ -3166,7 +2734,8 @@
     unsigned Align =3D Node->getConstantOperandVal(3);
=20
     SDValue VAListLoad =3D DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
-                                     MachinePointerInfo(V), false, false, =
0);
+                                     MachinePointerInfo(V),=20
+                                     false, false, false, 0);
     SDValue VAList =3D VAListLoad;
=20
     if (Align > TLI.getMinStackArgumentAlignment()) {
@@ -3191,7 +2760,7 @@
                         MachinePointerInfo(V), false, false, 0);
     // Load the actual argument out of the pointer VAList
     Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo=
(),
-                                  false, false, 0));
+                                  false, false, false, 0));
     Results.push_back(Results[0].getValue(1));
     break;
   }
@@ -3202,7 +2771,7 @@
     const Value *VS =3D cast<SrcValueSDNode>(Node->getOperand(4))->getValu=
e();
     Tmp1 =3D DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
                        Node->getOperand(2), MachinePointerInfo(VS),
-                       false, false, 0);
+                       false, false, false, 0);
     Tmp1 =3D DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
                         MachinePointerInfo(VD), false, false, 0);
     Results.push_back(Tmp1);
@@ -3236,15 +2805,57 @@
                                               Node->getOperand(2), dl));
     break;
   case ISD::VECTOR_SHUFFLE: {
-    SmallVector<int, 8> Mask;
-    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
+    SmallVector<int, 32> NewMask;
+    ArrayRef<int> Mask =3D cast<ShuffleVectorSDNode>(Node)->getMask();
=20
     EVT VT =3D Node->getValueType(0);
     EVT EltVT =3D VT.getVectorElementType();
-    if (!TLI.isTypeLegal(EltVT))
-      EltVT =3D TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
+    SDValue Op0 =3D Node->getOperand(0);
+    SDValue Op1 =3D Node->getOperand(1);
+    if (!TLI.isTypeLegal(EltVT)) {
+
+      EVT NewEltVT =3D TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
+
+      // BUILD_VECTOR operands are allowed to be wider than the element ty=
pe.
+      // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not a=
ccept it
+      if (NewEltVT.bitsLT(EltVT)) {
+
+        // Convert shuffle node.
+        // If original node was v4i64 and the new EltVT is i32,
+        // cast operands to v8i32 and re-build the mask.
+
+        // Calculate new VT, the size of the new VT should be equal to ori=
ginal.
+        EVT NewVT =3D EVT::getVectorVT(*DAG.getContext(), NewEltVT,=20
+                                      VT.getSizeInBits()/NewEltVT.getSizeI=
nBits());
+        assert(NewVT.bitsEq(VT));
+
+        // cast operands to new VT
+        Op0 =3D DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
+        Op1 =3D DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
+
+        // Convert the shuffle mask
+        unsigned int factor =3D NewVT.getVectorNumElements()/VT.getVectorN=
umElements();
+
+        // EltVT gets smaller
+        assert(factor > 0);
+
+        for (unsigned i =3D 0; i < VT.getVectorNumElements(); ++i) {
+          if (Mask[i] < 0) {
+            for (unsigned fi =3D 0; fi < factor; ++fi)
+              NewMask.push_back(Mask[i]);
+          }
+          else {
+            for (unsigned fi =3D 0; fi < factor; ++fi)
+              NewMask.push_back(Mask[i]*factor+fi);
+          }
+        }
+        Mask =3D NewMask;
+        VT =3D NewVT;
+      }
+      EltVT =3D NewEltVT;
+    }
     unsigned NumElems =3D VT.getVectorNumElements();
-    SmallVector<SDValue, 8> Ops;
+    SmallVector<SDValue, 16> Ops;
     for (unsigned i =3D 0; i !=3D NumElems; ++i) {
       if (Mask[i] < 0) {
         Ops.push_back(DAG.getUNDEF(EltVT));
@@ -3253,14 +2864,17 @@
       unsigned Idx =3D Mask[i];
       if (Idx < NumElems)
         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
-                                  Node->getOperand(0),
+                                  Op0,
                                   DAG.getIntPtrConstant(Idx)));
       else
         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
-                                  Node->getOperand(1),
+                                  Op1,
                                   DAG.getIntPtrConstant(Idx - NumElems)));
     }
+
     Tmp1 =3D DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
+    // We may have changed the BUILD_VECTOR type. Cast it back to the Node=
 type.
+    Tmp1 =3D DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
     Results.push_back(Tmp1);
     break;
   }
@@ -3408,10 +3022,8 @@
     ConstantFPSDNode *CFP =3D cast<ConstantFPSDNode>(Node);
     // Check to see if this FP immediate is already legal.
     // If this is a legal constant, turn it into a TargetConstantFP node.
-    if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
-      Results.push_back(SDValue(Node, 0));
-    else
-      Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
+    if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
+      Results.push_back(ExpandConstantFP(CFP, true));
     break;
   }
   case ISD::EHSELECTION: {
@@ -3423,13 +3035,23 @@
     break;
   }
   case ISD::EXCEPTIONADDR: {
-    unsigned Reg =3D TLI.getExceptionAddressRegister();
+    unsigned Reg =3D TLI.getExceptionPointerRegister();
     assert(Reg && "Can't expand to unknown register!");
     Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
                                          Node->getValueType(0)));
     Results.push_back(Results[0].getValue(1));
     break;
   }
+  case ISD::FSUB: {
+    EVT VT =3D Node->getValueType(0);
+    assert(TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
+           TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
+           "Don't know how to expand this FP subtraction!");
+    Tmp1 =3D DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
+    Tmp1 =3D DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1);
+    Results.push_back(Tmp1);
+    break;
+  }
   case ISD::SUB: {
     EVT VT =3D Node->getValueType(0);
     assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
@@ -3657,6 +3279,10 @@
                                DAG.getIntPtrConstant(0));
       TopHalf =3D DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
                             DAG.getIntPtrConstant(1));
+      // Ret is a node with an illegal type. Because such things are not
+      // generally permitted during this phase of legalization, delete the
+      // node. The above EXTRACT_ELEMENT nodes should have been folded.
+      DAG.DeleteNode(Ret.getNode());
     }
=20
     if (isSigned) {
@@ -3797,7 +3423,6 @@
=20
     LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
                           Tmp2, Tmp3, Tmp4, dl);
-    LastCALLSEQ_END =3D DAG.getEntryNode();
=20
     assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!"=
);
     Tmp3 =3D DAG.getConstant(0, Tmp2.getValueType());
@@ -3807,6 +3432,35 @@
     Results.push_back(Tmp1);
     break;
   }
+  case ISD::BUILD_VECTOR:
+    Results.push_back(ExpandBUILD_VECTOR(Node));
+    break;
+  case ISD::SRA:
+  case ISD::SRL:
+  case ISD::SHL: {
+    // Scalarize vector SRA/SRL/SHL.
+    EVT VT =3D Node->getValueType(0);
+    assert(VT.isVector() && "Unable to legalize non-vector shift");
+    assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be leg=
al");
+    unsigned NumElem =3D VT.getVectorNumElements();
+
+    SmallVector<SDValue, 8> Scalars;
+    for (unsigned Idx =3D 0; Idx < NumElem; Idx++) {
+      SDValue Ex =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
+                               VT.getScalarType(),
+                               Node->getOperand(0), DAG.getIntPtrConstant(=
Idx));
+      SDValue Sh =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
+                               VT.getScalarType(),
+                               Node->getOperand(1), DAG.getIntPtrConstant(=
Idx));
+      Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
+                                    VT.getScalarType(), Ex, Sh));
+    }
+    SDValue Result =3D
+      DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0),
+                  &Scalars[0], Scalars.size());
+    ReplaceNode(SDValue(Node, 0), Result);
+    break;
+  }
   case ISD::GLOBAL_OFFSET_TABLE:
   case ISD::GlobalAddress:
   case ISD::GlobalTLSAddress:
@@ -3817,13 +3471,16 @@
   case ISD::INTRINSIC_WO_CHAIN:
   case ISD::INTRINSIC_VOID:
     // FIXME: Custom lowering for these operations shouldn't return null!
-    for (unsigned i =3D 0, e =3D Node->getNumValues(); i !=3D e; ++i)
-      Results.push_back(SDValue(Node, i));
     break;
   }
+
+  // Replace the original node with the legalized result.
+  if (!Results.empty())
+    ReplaceNode(Node, Results.data());
 }
-void SelectionDAGLegalize::PromoteNode(SDNode *Node,
-                                       SmallVectorImpl<SDValue> &Results) {
+
+void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
+  SmallVector<SDValue, 8> Results;
   EVT OVT =3D Node->getValueType(0);
   if (Node->getOpcode() =3D=3D ISD::UINT_TO_FP ||
       Node->getOpcode() =3D=3D ISD::SINT_TO_FP ||
@@ -3835,20 +3492,24 @@
   SDValue Tmp1, Tmp2, Tmp3;
   switch (Node->getOpcode()) {
   case ISD::CTTZ:
+  case ISD::CTTZ_ZERO_UNDEF:
   case ISD::CTLZ:
+  case ISD::CTLZ_ZERO_UNDEF:
   case ISD::CTPOP:
     // Zero extend the argument.
     Tmp1 =3D DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
-    // Perform the larger operation.
+    // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
+    // already the correct result.
     Tmp1 =3D DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
     if (Node->getOpcode() =3D=3D ISD::CTTZ) {
-      //if Tmp1 =3D=3D sizeinbits(NVT) then Tmp1 =3D sizeinbits(Old VT)
+      // FIXME: This should set a bit in the zero extended value instead.
       Tmp2 =3D DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
                           Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
                           ISD::SETEQ);
       Tmp1 =3D DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
                           DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
-    } else if (Node->getOpcode() =3D=3D ISD::CTLZ) {
+    } else if (Node->getOpcode() =3D=3D ISD::CTLZ ||
+               Node->getOpcode() =3D=3D ISD::CTLZ_ZERO_UNDEF) {
       // Tmp1 =3D Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
       Tmp1 =3D DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
                           DAG.getConstant(NVT.getSizeInBits() -
@@ -3877,6 +3538,33 @@
                                  Node->getOpcode() =3D=3D ISD::SINT_TO_FP,=
 dl);
     Results.push_back(Tmp1);
     break;
+  case ISD::VAARG: {
+    SDValue Chain =3D Node->getOperand(0); // Get the chain.
+    SDValue Ptr =3D Node->getOperand(1); // Get the pointer.
+
+    unsigned TruncOp;
+    if (OVT.isVector()) {
+      TruncOp =3D ISD::BITCAST;
+    } else {
+      assert(OVT.isInteger()
+        && "VAARG promotion is supported only for vectors or integer types=
");
+      TruncOp =3D ISD::TRUNCATE;
+    }
+
+    // Perform the larger operation, then convert back
+    Tmp1 =3D DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
+             Node->getConstantOperandVal(3));
+    Chain =3D Tmp1.getValue(1);
+
+    Tmp2 =3D DAG.getNode(TruncOp, dl, OVT, Tmp1);
+
+    // Modified the chain result - switch anything that used the old chain=
 to
+    // use the new one.
+    DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
+    DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
+    ReplacedNode(Node);
+    break;
+  }
   case ISD::AND:
   case ISD::OR:
   case ISD::XOR: {
@@ -3924,8 +3612,7 @@
     break;
   }
   case ISD::VECTOR_SHUFFLE: {
-    SmallVector<int, 8> Mask;
-    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
+    ArrayRef<int> Mask =3D cast<ShuffleVectorSDNode>(Node)->getMask();
=20
     // Cast the two input vectors.
     Tmp1 =3D DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
@@ -3950,7 +3637,31 @@
                                   Tmp1, Tmp2, Node->getOperand(2)));
     break;
   }
+  case ISD::FDIV:
+  case ISD::FREM:
+  case ISD::FPOW: {
+    Tmp1 =3D DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
+    Tmp2 =3D DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
+    Tmp3 =3D DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
+    Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
+                                  Tmp3, DAG.getIntPtrConstant(0)));
+    break;
   }
+  case ISD::FLOG2:
+  case ISD::FEXP2:
+  case ISD::FLOG:
+  case ISD::FEXP: {
+    Tmp1 =3D DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
+    Tmp2 =3D DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
+    Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
+                                  Tmp2, DAG.getIntPtrConstant(0)));
+    break;
+  }
+  }
+
+  // Replace the original node with the legalized result.
+  if (!Results.empty())
+    ReplaceNode(Node, Results.data());
 }
=20
 // SelectionDAG::Legalize - This is the entry point for the file.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeFloatTypes.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeFloatTypes.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -479,8 +479,8 @@
   if (L->getExtensionType() =3D=3D ISD::NON_EXTLOAD) {
     NewL =3D DAG.getLoad(L->getAddressingMode(), L->getExtensionType(),
                        NVT, dl, L->getChain(), L->getBasePtr(), L->getOffs=
et(),
-                       L->getPointerInfo(), NVT,
-                       L->isVolatile(), L->isNonTemporal(), L->getAlignmen=
t());
+                       L->getPointerInfo(), NVT, L->isVolatile(),=20
+                       L->isNonTemporal(), false, L->getAlignment());
     // Legalized the chain result - switch anything that used the old chai=
n to
     // use the new one.
     ReplaceValueWith(SDValue(N, 1), NewL.getValue(1));
@@ -492,7 +492,7 @@
                      L->getMemoryVT(), dl, L->getChain(),
                      L->getBasePtr(), L->getOffset(), L->getPointerInfo(),
                      L->getMemoryVT(), L->isVolatile(),
-                     L->isNonTemporal(), L->getAlignment());
+                     L->isNonTemporal(), false, L->getAlignment());
   // Legalized the chain result - switch anything that used the old chain =
to
   // use the new one.
   ReplaceValueWith(SDValue(N, 1), NewL.getValue(1));
@@ -672,7 +672,7 @@
     case ISD::SETUEQ:
       LC2 =3D (VT =3D=3D MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
       break;
-    default: assert(false && "Do not know how to soften this setcc!");
+    default: llvm_unreachable("Do not know how to soften this setcc!");
     }
   }
=20
@@ -1212,7 +1212,7 @@
=20
   switch (SrcVT.getSimpleVT().SimpleTy) {
   default:
-    assert(false && "Unsupported UINT_TO_FP!");
+    llvm_unreachable("Unsupported UINT_TO_FP!");
   case MVT::i32:
     Parts =3D TwoE32;
     break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeIntegerTypes.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -20,7 +20,6 @@
=20
 #include "LegalizeTypes.h"
 #include "llvm/DerivedTypes.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
@@ -57,8 +56,10 @@
   case ISD::Constant:    Res =3D PromoteIntRes_Constant(N); break;
   case ISD::CONVERT_RNDSAT:
                          Res =3D PromoteIntRes_CONVERT_RNDSAT(N); break;
+  case ISD::CTLZ_ZERO_UNDEF:
   case ISD::CTLZ:        Res =3D PromoteIntRes_CTLZ(N); break;
   case ISD::CTPOP:       Res =3D PromoteIntRes_CTPOP(N); break;
+  case ISD::CTTZ_ZERO_UNDEF:
   case ISD::CTTZ:        Res =3D PromoteIntRes_CTTZ(N); break;
   case ISD::EXTRACT_VECTOR_ELT:
                          Res =3D PromoteIntRes_EXTRACT_VECTOR_ELT(N); brea=
k;
@@ -211,13 +212,10 @@
   DebugLoc dl =3D N->getDebugLoc();
=20
   switch (getTypeAction(InVT)) {
-  default:
-    assert(false && "Unknown type action!");
-    break;
   case TargetLowering::TypeLegal:
     break;
   case TargetLowering::TypePromoteInteger:
-    if (NOutVT.bitsEq(NInVT))
+    if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector() && !NInVT.isVector())
       // The input promotes to the same size.  Convert the promoted value.
       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp=
));
     break;
@@ -251,9 +249,11 @@
     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
   }
   case TargetLowering::TypeWidenVector:
-    if (OutVT.bitsEq(NInVT))
-      // The input is widened to the same size.  Convert to the widened va=
lue.
-      return DAG.getNode(ISD::BITCAST, dl, OutVT, GetWidenedVector(InOp));
+    // The input is widened to the same size. Convert to the widened value.
+    // Make sure that the outgoing value is not a vector, because this wou=
ld
+    // make us bitcast between two vectors which are legalized in differen=
t ways.
+    if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector())
+      return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetWidenedVector(InOp));
   }
=20
   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
@@ -312,7 +312,7 @@
   DebugLoc dl =3D N->getDebugLoc();
   EVT OVT =3D N->getValueType(0);
   EVT NVT =3D Op.getValueType();
-  Op =3D DAG.getNode(ISD::CTLZ, dl, NVT, Op);
+  Op =3D DAG.getNode(N->getOpcode(), dl, NVT, Op);
   // Subtract off the extra leading bits in the bigger type.
   return DAG.getNode(ISD::SUB, dl, NVT, Op,
                      DAG.getConstant(NVT.getSizeInBits() -
@@ -330,13 +330,15 @@
   EVT OVT =3D N->getValueType(0);
   EVT NVT =3D Op.getValueType();
   DebugLoc dl =3D N->getDebugLoc();
-  // The count is the same in the promoted type except if the original
-  // value was zero.  This can be handled by setting the bit just off
-  // the top of the original type.
-  APInt TopBit(NVT.getSizeInBits(), 0);
-  TopBit.setBit(OVT.getSizeInBits());
-  Op =3D DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
-  return DAG.getNode(ISD::CTTZ, dl, NVT, Op);
+  if (N->getOpcode() =3D=3D ISD::CTTZ) {
+    // The count is the same in the promoted type except if the original
+    // value was zero.  This can be handled by setting the bit just off
+    // the top of the original type.
+    APInt TopBit(NVT.getSizeInBits(), 0);
+    TopBit.setBit(OVT.getSizeInBits());
+    Op =3D DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
+  }
+  return DAG.getNode(N->getOpcode(), dl, NVT, Op);
 }
=20
 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
@@ -486,7 +488,11 @@
 }
=20
 SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
-  SDValue Mask =3D GetPromotedInteger(N->getOperand(0));
+  SDValue Mask =3D N->getOperand(0);
+  EVT OpTy =3D N->getOperand(1).getValueType();
+
+  // Promote all the way up to the canonical SetCC type.
+  Mask =3D PromoteTargetBoolean(Mask, TLI.getSetCCResultType(OpTy));
   SDValue LHS =3D GetPromotedInteger(N->getOperand(1));
   SDValue RHS =3D GetPromotedInteger(N->getOperand(2));
   return DAG.getNode(ISD::VSELECT, N->getDebugLoc(),
@@ -1098,8 +1104,10 @@
   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
+  case ISD::CTLZ_ZERO_UNDEF:
   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
+  case ISD::CTTZ_ZERO_UNDEF:
   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
@@ -1171,7 +1179,6 @@
   switch (Opc) {
   default:
     llvm_unreachable("Unhandled atomic intrinsic Expand!");
-    break;
   case ISD::ATOMIC_SWAP:
     switch (VT.SimpleTy) {
     default: llvm_unreachable("Unexpected value type for atomic!");
@@ -1355,7 +1362,7 @@
=20
   APInt HighBitMask =3D APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVT=
Bits));
   APInt KnownZero, KnownOne;
-  DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne=
);
+  DAG.ComputeMaskedBits(N->getOperand(1), KnownZero, KnownOne);
=20
   // If we don't know anything about the high bits, exit.
   if (((KnownZero|KnownOne) & HighBitMask) =3D=3D 0)
@@ -1390,15 +1397,15 @@
     }
   }
=20
-#if 0
-  // FIXME: This code is broken for shifts with a zero amount!
   // If we know that all of the high bits of the shift amount are zero, th=
en we
   // can do this as a couple of simple shifts.
   if ((KnownZero & HighBitMask) =3D=3D HighBitMask) {
-    // Compute 32-amt.
-    SDValue Amt2 =3D DAG.getNode(ISD::SUB, ShTy,
-                                 DAG.getConstant(NVTBits, ShTy),
-                                 Amt);
+    // Calculate 31-x. 31 is used instead of 32 to avoid creating an undef=
ined
+    // shift if x is zero.  We can use XOR here because x is known to be s=
maller
+    // than 32.
+    SDValue Amt2 =3D DAG.getNode(ISD::XOR, dl, ShTy, Amt,
+                               DAG.getConstant(NVTBits-1, ShTy));
+
     unsigned Op1, Op2;
     switch (N->getOpcode()) {
     default: llvm_unreachable("Unknown shift");
@@ -1407,13 +1414,23 @@
     case ISD::SRA:  Op1 =3D ISD::SRL; Op2 =3D ISD::SHL; break;
     }
=20
-    Lo =3D DAG.getNode(N->getOpcode(), NVT, InL, Amt);
-    Hi =3D DAG.getNode(ISD::OR, NVT,
-                     DAG.getNode(Op1, NVT, InH, Amt),
-                     DAG.getNode(Op2, NVT, InL, Amt2));
+    // When shifting right the arithmetic for Lo and Hi is swapped.
+    if (N->getOpcode() !=3D ISD::SHL)
+      std::swap(InL, InH);
+
+    // Use a little trick to get the bits that move from Lo to Hi. First
+    // shift by one bit.
+    SDValue Sh1 =3D DAG.getNode(Op2, dl, NVT, InL, DAG.getConstant(1, ShTy=
));
+    // Then compute the remaining shift with amount-1.
+    SDValue Sh2 =3D DAG.getNode(Op2, dl, NVT, Sh1, Amt2);
+
+    Lo =3D DAG.getNode(N->getOpcode(), dl, NVT, InL, Amt);
+    Hi =3D DAG.getNode(ISD::OR, dl, NVT, DAG.getNode(Op1, dl, NVT, InH, Am=
t),Sh2);
+
+    if (N->getOpcode() !=3D ISD::SHL)
+      std::swap(Hi, Lo);
     return true;
   }
-#endif
=20
   return false;
 }
@@ -1493,8 +1510,6 @@
     Hi =3D DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
     return true;
   }
-
-  return false;
 }
=20
 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
@@ -1702,8 +1717,8 @@
   SDValue HiNotZero =3D DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Hi,
                                    DAG.getConstant(0, NVT), ISD::SETNE);
=20
-  SDValue LoLZ =3D DAG.getNode(ISD::CTLZ, dl, NVT, Lo);
-  SDValue HiLZ =3D DAG.getNode(ISD::CTLZ, dl, NVT, Hi);
+  SDValue LoLZ =3D DAG.getNode(N->getOpcode(), dl, NVT, Lo);
+  SDValue HiLZ =3D DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, NVT, Hi);
=20
   Lo =3D DAG.getNode(ISD::SELECT, dl, NVT, HiNotZero, HiLZ,
                    DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
@@ -1732,8 +1747,8 @@
   SDValue LoNotZero =3D DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo,
                                    DAG.getConstant(0, NVT), ISD::SETNE);
=20
-  SDValue LoLZ =3D DAG.getNode(ISD::CTTZ, dl, NVT, Lo);
-  SDValue HiLZ =3D DAG.getNode(ISD::CTTZ, dl, NVT, Hi);
+  SDValue LoLZ =3D DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, NVT, Lo);
+  SDValue HiLZ =3D DAG.getNode(N->getOpcode(), dl, NVT, Hi);
=20
   Lo =3D DAG.getNode(ISD::SELECT, dl, NVT, LoNotZero, LoLZ,
                    DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
@@ -1778,6 +1793,7 @@
   unsigned Alignment =3D N->getAlignment();
   bool isVolatile =3D N->isVolatile();
   bool isNonTemporal =3D N->isNonTemporal();
+  bool isInvariant =3D N->isInvariant();
   DebugLoc dl =3D N->getDebugLoc();
=20
   assert(NVT.isByteSized() && "Expanded type not byte sized!");
@@ -1808,7 +1824,7 @@
   } else if (TLI.isLittleEndian()) {
     // Little-endian - low bits are at low addresses.
     Lo =3D DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
-                     isVolatile, isNonTemporal, Alignment);
+                     isVolatile, isNonTemporal, isInvariant, Alignment);
=20
     unsigned ExcessBits =3D
       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
@@ -2305,12 +2321,14 @@
   SDValue Func =3D DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
   std::pair<SDValue, SDValue> CallInfo =3D
     TLI.LowerCallTo(Chain, RetTy, true, false, false, false,
-		    0, TLI.getLibcallCallingConv(LC), false,
-		    true, Func, Args, DAG, dl);
+		    0, TLI.getLibcallCallingConv(LC),
+                    /*isTailCall=3D*/false,
+		    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/true,
+                    Func, Args, DAG, dl);
=20
   SplitInteger(CallInfo.first, Lo, Hi);
   SDValue Temp2 =3D DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
-			      MachinePointerInfo(), false, false, 0);
+			      MachinePointerInfo(), false, false, false, 0);
   SDValue Ofl =3D DAG.getSetCC(dl, N->getValueType(1), Temp2,
                              DAG.getConstant(0, PtrVT),
                              ISD::SETNE);
@@ -2781,7 +2799,7 @@
     else if (SrcVT =3D=3D MVT::i128)
       FF =3D APInt(32, F32TwoE128);
     else
-      assert(false && "Unsupported UINT_TO_FP!");
+      llvm_unreachable("Unsupported UINT_TO_FP!");
=20
     // Check whether the sign bit is set.
     SDValue Lo, Hi;
@@ -2926,38 +2944,28 @@
 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
   DebugLoc dl =3D N->getDebugLoc();
=20
-  SDValue Op0 =3D N->getOperand(1);
-  SDValue Op1 =3D N->getOperand(1);
-  assert(Op0.getValueType() =3D=3D Op1.getValueType() &&
-         "Invalid input vector types");
-
   EVT OutVT =3D N->getValueType(0);
   EVT NOutVT =3D TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
   assert(NOutVT.isVector() && "This type must be promoted to a vector type=
");
=20
+  EVT InElemTy =3D OutVT.getVectorElementType();
   EVT OutElemTy =3D NOutVT.getVectorElementType();
=20
-  unsigned NumElem0 =3D Op0.getValueType().getVectorNumElements();
-  unsigned NumElem1 =3D Op1.getValueType().getVectorNumElements();
+  unsigned NumElem =3D N->getOperand(0).getValueType().getVectorNumElement=
s();
   unsigned NumOutElem =3D NOutVT.getVectorNumElements();
-  assert(NumElem0 + NumElem1 =3D=3D NumOutElem &&
-         "Invalid number of incoming elements");
+  unsigned NumOperands =3D N->getNumOperands();
+  assert(NumElem * NumOperands =3D=3D NumOutElem &&
+         "Unexpected number of elements");
=20
   // Take the elements from the first vector.
   SmallVector<SDValue, 8> Ops(NumOutElem);
-  for (unsigned i =3D 0; i < NumElem0; ++i) {
-    SDValue Ext =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
-                              Op0.getValueType().getScalarType(), Op0,
-                              DAG.getIntPtrConstant(i));
-    Ops[i] =3D DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
-  }
-
-  // Take the elements from the second vector
-  for (unsigned i =3D 0; i < NumElem1; ++i) {
-    SDValue Ext =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
-                              Op1.getValueType().getScalarType(), Op1,
-                              DAG.getIntPtrConstant(i));
-    Ops[i + NumElem0] =3D DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
+  for (unsigned i =3D 0; i < NumOperands; ++i) {
+    SDValue Op =3D N->getOperand(i);
+    for (unsigned j =3D 0; j < NumElem; ++j) {
+      SDValue Ext =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
+                                InElemTy, Op, DAG.getIntPtrConstant(j));
+      Ops[i * NumElem + j] =3D DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy,=
 Ext);
+    }
   }
=20
   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeTypes.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -222,8 +222,6 @@
     for (unsigned i =3D 0, NumResults =3D N->getNumValues(); i < NumResult=
s; ++i) {
       EVT ResultVT =3D N->getValueType(i);
       switch (getTypeAction(ResultVT)) {
-      default:
-        assert(false && "Unknown action!");
       case TargetLowering::TypeLegal:
         break;
       // The following calls must take care of *all* of the node's results,
@@ -275,8 +273,6 @@
=20
       EVT OpVT =3D N->getOperand(i).getValueType();
       switch (getTypeAction(OpVT)) {
-      default:
-        assert(false && "Unknown action!");
       case TargetLowering::TypeLegal:
         continue;
       // The following calls must either replace all of the node's results
@@ -752,7 +748,11 @@
 }
=20
 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
-  assert(Result.getValueType() =3D=3D Op.getValueType().getVectorElementTy=
pe() &&
+  // Note that in some cases vector operation operands may be greater than
+  // the vector element type. For example BUILD_VECTOR of type <1 x i1> wi=
th
+  // a constant i8 operand.
+  assert(Result.getValueType().getSizeInBits() >=3D
+         Op.getValueType().getVectorElementType().getSizeInBits() &&
          "Invalid type for scalarized vector");
   AnalyzeNewValue(Result);
=20
@@ -889,7 +889,7 @@
                                MachinePointerInfo(), false, false, 0);
   // Result is a load from the stack slot.
   return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo(),
-                     false, false, 0);
+                     false, false, false, 0);
 }
=20
 /// CustomLowerNode - Replace the node's results with custom code provided
@@ -1056,8 +1056,9 @@
   Type *RetTy =3D RetVT.getTypeForEVT(*DAG.getContext());
   std::pair<SDValue,SDValue> CallInfo =3D
     TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
-                    false, 0, TLI.getLibcallCallingConv(LC), false,
-                    /*isReturnValueUsed=3D*/true,
+                    false, 0, TLI.getLibcallCallingConv(LC),
+                    /*isTailCall=3D*/false,
+                    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/tru=
e,
                     Callee, Args, DAG, dl);
   return CallInfo.first;
 }
@@ -1084,12 +1085,11 @@
   SDValue Callee =3D DAG.getExternalSymbol(TLI.getLibcallName(LC),
                                          TLI.getPointerTy());
=20
-  // Splice the libcall in wherever FindInputOutputChains tells us to.
   Type *RetTy =3D Node->getValueType(0).getTypeForEVT(*DAG.getContext());
   std::pair<SDValue, SDValue> CallInfo =3D
     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
                     0, TLI.getLibcallCallingConv(LC), /*isTailCall=3D*/fal=
se,
-                    /*isReturnValueUsed=3D*/true,
+                    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/tru=
e,
                     Callee, Args, DAG, Node->getDebugLoc());
=20
   return CallInfo;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeTypes.h
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -521,6 +521,7 @@
   SDValue ScalarizeVecRes_LOAD(LoadSDNode *N);
   SDValue ScalarizeVecRes_SCALAR_TO_VECTOR(SDNode *N);
   SDValue ScalarizeVecRes_SIGN_EXTEND_INREG(SDNode *N);
+  SDValue ScalarizeVecRes_VSELECT(SDNode *N);
   SDValue ScalarizeVecRes_SELECT(SDNode *N);
   SDValue ScalarizeVecRes_SELECT_CC(SDNode *N);
   SDValue ScalarizeVecRes_SETCC(SDNode *N);
@@ -633,6 +634,7 @@
   SDValue WidenVecOp_EXTRACT_VECTOR_ELT(SDNode *N);
   SDValue WidenVecOp_EXTRACT_SUBVECTOR(SDNode *N);
   SDValue WidenVecOp_STORE(SDNode* N);
+  SDValue WidenVecOp_SETCC(SDNode* N);
=20
   SDValue WidenVecOp_Convert(SDNode *N);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeTypesGeneric.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypesGeneric.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,6 @@
=20
 #include "LegalizeTypes.h"
 #include "llvm/Target/TargetData.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -46,8 +45,6 @@
=20
   // Handle some special cases efficiently.
   switch (getTypeAction(InVT)) {
-    default:
-      assert(false && "Unknown type action!");
     case TargetLowering::TypeLegal:
     case TargetLowering::TypePromoteInteger:
       break;
@@ -130,7 +127,8 @@
                                false, false, 0);
=20
   // Load the first half from the stack slot.
-  Lo =3D DAG.getLoad(NOutVT, dl, Store, StackPtr, PtrInfo, false, false, 0=
);
+  Lo =3D DAG.getLoad(NOutVT, dl, Store, StackPtr, PtrInfo,=20
+                   false, false, false, 0);
=20
   // Increment the pointer to the other half.
   unsigned IncrementSize =3D NOutVT.getSizeInBits() / 8;
@@ -140,7 +138,7 @@
   // Load the second half from the stack slot.
   Hi =3D DAG.getLoad(NOutVT, dl, Store, StackPtr,
                    PtrInfo.getWithOffset(IncrementSize), false,
-                   false, MinAlign(Alignment, IncrementSize));
+                   false, false, MinAlign(Alignment, IncrementSize));
=20
   // Handle endianness of the load.
   if (TLI.isBigEndian())
@@ -212,11 +210,12 @@
   unsigned Alignment =3D LD->getAlignment();
   bool isVolatile =3D LD->isVolatile();
   bool isNonTemporal =3D LD->isNonTemporal();
+  bool isInvariant =3D LD->isInvariant();
=20
   assert(NVT.isByteSized() && "Expanded type not byte sized!");
=20
   Lo =3D DAG.getLoad(NVT, dl, Chain, Ptr, LD->getPointerInfo(),
-                   isVolatile, isNonTemporal, Alignment);
+                   isVolatile, isNonTemporal, isInvariant, Alignment);
=20
   // Increment the pointer to the other half.
   unsigned IncrementSize =3D NVT.getSizeInBits() / 8;
@@ -224,7 +223,7 @@
                     DAG.getIntPtrConstant(IncrementSize));
   Hi =3D DAG.getLoad(NVT, dl, Chain, Ptr,
                    LD->getPointerInfo().getWithOffset(IncrementSize),
-                   isVolatile, isNonTemporal,
+                   isVolatile, isNonTemporal, isInvariant,
                    MinAlign(Alignment, IncrementSize));
=20
   // Build a factor node to remember that this load is independent of the
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeVectorOps.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -64,6 +64,8 @@
   // Implement vselect in terms of XOR, AND, OR when blend is not supported
   // by the target.
   SDValue ExpandVSELECT(SDValue Op);
+  SDValue ExpandLoad(SDValue Op);
+  SDValue ExpandStore(SDValue Op);
   SDValue ExpandFNEG(SDValue Op);
   // Implements vector promotion; this is essentially just bitcasting the
   // operands to a different type and bitcasting the result back to the
@@ -124,6 +126,33 @@
   SDValue Result =3D
     SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops.data(), Ops.size()), =
0);
=20
+  if (Op.getOpcode() =3D=3D ISD::LOAD) {
+    LoadSDNode *LD =3D cast<LoadSDNode>(Op.getNode());
+    ISD::LoadExtType ExtType =3D LD->getExtensionType();
+    if (LD->getMemoryVT().isVector() && ExtType !=3D ISD::NON_EXTLOAD) {
+      if (TLI.isLoadExtLegal(LD->getExtensionType(), LD->getMemoryVT()))
+        return TranslateLegalizeResults(Op, Result);
+      Changed =3D true;
+      return LegalizeOp(ExpandLoad(Op));
+    }
+  } else if (Op.getOpcode() =3D=3D ISD::STORE) {
+    StoreSDNode *ST =3D cast<StoreSDNode>(Op.getNode());
+    EVT StVT =3D ST->getMemoryVT();
+    EVT ValVT =3D ST->getValue().getValueType();
+    if (StVT.isVector() && ST->isTruncatingStore())
+      switch (TLI.getTruncStoreAction(ValVT, StVT)) {
+      default: llvm_unreachable("This action is not supported yet!");
+      case TargetLowering::Legal:
+        return TranslateLegalizeResults(Op, Result);
+      case TargetLowering::Custom:
+        Changed =3D true;
+        return LegalizeOp(TLI.LowerOperation(Result, DAG));
+      case TargetLowering::Expand:
+        Changed =3D true;
+        return LegalizeOp(ExpandStore(Op));
+      }
+  }
+
   bool HasVectorValue =3D false;
   for (SDNode::value_iterator J =3D Node->value_begin(), E =3D Node->value=
_end();
        J !=3D E;
@@ -156,8 +185,10 @@
   case ISD::SRL:
   case ISD::ROTL:
   case ISD::ROTR:
+  case ISD::CTLZ:
   case ISD::CTTZ:
-  case ISD::CTLZ:
+  case ISD::CTLZ_ZERO_UNDEF:
+  case ISD::CTTZ_ZERO_UNDEF:
   case ISD::CTPOP:
   case ISD::SELECT:
   case ISD::VSELECT:
@@ -262,6 +293,97 @@
   return DAG.getNode(ISD::BITCAST, dl, VT, Op);
 }
=20
+
+SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
+  DebugLoc dl =3D Op.getDebugLoc();
+  LoadSDNode *LD =3D cast<LoadSDNode>(Op.getNode());
+  SDValue Chain =3D LD->getChain();
+  SDValue BasePTR =3D LD->getBasePtr();
+  EVT SrcVT =3D LD->getMemoryVT();
+  ISD::LoadExtType ExtType =3D LD->getExtensionType();
+
+  SmallVector<SDValue, 8> LoadVals;
+  SmallVector<SDValue, 8> LoadChains;
+  unsigned NumElem =3D SrcVT.getVectorNumElements();
+  unsigned Stride =3D SrcVT.getScalarType().getSizeInBits()/8;
+
+  for (unsigned Idx=3D0; Idx<NumElem; Idx++) {
+    SDValue ScalarLoad =3D DAG.getExtLoad(ExtType, dl,
+              Op.getNode()->getValueType(0).getScalarType(),
+              Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Str=
ide),
+              SrcVT.getScalarType(),
+              LD->isVolatile(), LD->isNonTemporal(),
+              LD->getAlignment());
+
+    BasePTR =3D DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
+                       DAG.getIntPtrConstant(Stride));
+
+     LoadVals.push_back(ScalarLoad.getValue(0));
+     LoadChains.push_back(ScalarLoad.getValue(1));
+  }
+
+  SDValue NewChain =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
+            &LoadChains[0], LoadChains.size());
+  SDValue Value =3D DAG.getNode(ISD::BUILD_VECTOR, dl,
+            Op.getNode()->getValueType(0), &LoadVals[0], LoadVals.size());
+
+  AddLegalizedOperand(Op.getValue(0), Value);
+  AddLegalizedOperand(Op.getValue(1), NewChain);
+
+  return (Op.getResNo() ? NewChain : Value);
+}
+
+SDValue VectorLegalizer::ExpandStore(SDValue Op) {
+  DebugLoc dl =3D Op.getDebugLoc();
+  StoreSDNode *ST =3D cast<StoreSDNode>(Op.getNode());
+  SDValue Chain =3D ST->getChain();
+  SDValue BasePTR =3D ST->getBasePtr();
+  SDValue Value =3D ST->getValue();
+  EVT StVT =3D ST->getMemoryVT();
+
+  unsigned Alignment =3D ST->getAlignment();
+  bool isVolatile =3D ST->isVolatile();
+  bool isNonTemporal =3D ST->isNonTemporal();
+
+  unsigned NumElem =3D StVT.getVectorNumElements();
+  // The type of the data we want to save
+  EVT RegVT =3D Value.getValueType();
+  EVT RegSclVT =3D RegVT.getScalarType();
+  // The type of data as saved in memory.
+  EVT MemSclVT =3D StVT.getScalarType();
+
+  // Cast floats into integers
+  unsigned ScalarSize =3D MemSclVT.getSizeInBits();
+
+  // Round odd types to the next pow of two.
+  if (!isPowerOf2_32(ScalarSize))
+    ScalarSize =3D NextPowerOf2(ScalarSize);
+
+  // Store Stride in bytes
+  unsigned Stride =3D ScalarSize/8;
+  // Extract each of the elements from the original vector
+  // and save them into memory individually.
+  SmallVector<SDValue, 8> Stores;
+  for (unsigned Idx =3D 0; Idx < NumElem; Idx++) {
+    SDValue Ex =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
+               RegSclVT, Value, DAG.getIntPtrConstant(Idx));
+
+    // This scalar TruncStore may be illegal, but we legalize it later.
+    SDValue Store =3D DAG.getTruncStore(Chain, dl, Ex, BasePTR,
+               ST->getPointerInfo().getWithOffset(Idx*Stride), MemSclVT,
+               isVolatile, isNonTemporal, Alignment);
+
+    BasePTR =3D DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
+                                DAG.getIntPtrConstant(Stride));
+
+    Stores.push_back(Store);
+  }
+  SDValue TF =3D  DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
+                            &Stores[0], Stores.size());
+  AddLegalizedOperand(Op, TF);
+  return TF;
+}
+
 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
   // Implement VSELECT in terms of XOR, AND, OR
   // on platforms which do not support blend natively.
@@ -274,10 +396,12 @@
=20
   // If we can't even use the basic vector operations of
   // AND,OR,XOR, we will have to scalarize the op.
-  if (!TLI.isOperationLegalOrCustom(ISD::AND, VT) ||
-      !TLI.isOperationLegalOrCustom(ISD::XOR, VT) ||
-      !TLI.isOperationLegalOrCustom(ISD::OR, VT))
-        return DAG.UnrollVectorOp(Op.getNode());
+  // Notice that the operation may be 'promoted' which means that it is
+  // 'bitcasted' to another type which is handled.
+  if (TLI.getOperationAction(ISD::AND, VT) =3D=3D TargetLowering::Expand ||
+      TLI.getOperationAction(ISD::XOR, VT) =3D=3D TargetLowering::Expand ||
+      TLI.getOperationAction(ISD::OR,  VT) =3D=3D TargetLowering::Expand)
+    return DAG.UnrollVectorOp(Op.getNode());
=20
   assert(VT.getSizeInBits() =3D=3D Op.getOperand(1).getValueType().getSize=
InBits()
          && "Invalid mask size");
@@ -301,9 +425,9 @@
   DebugLoc DL =3D Op.getDebugLoc();
=20
   // Make sure that the SINT_TO_FP and SRL instructions are available.
-  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, VT) ||
-      !TLI.isOperationLegalOrCustom(ISD::SRL, VT))
-      return DAG.UnrollVectorOp(Op.getNode());
+  if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) =3D=3D TargetLowering::E=
xpand ||
+      TLI.getOperationAction(ISD::SRL,        VT) =3D=3D TargetLowering::E=
xpand)
+    return DAG.UnrollVectorOp(Op.getNode());
=20
  EVT SVT =3D VT.getScalarType();
   assert((SVT.getSizeInBits() =3D=3D 64 || SVT.getSizeInBits() =3D=3D 32) =
&&
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/LegalizeVectorTypes.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,6 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "LegalizeTypes.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
@@ -59,6 +58,7 @@
   case ISD::LOAD:           R =3D ScalarizeVecRes_LOAD(cast<LoadSDNode>(N)=
);break;
   case ISD::SCALAR_TO_VECTOR:  R =3D ScalarizeVecRes_SCALAR_TO_VECTOR(N); =
break;
   case ISD::SIGN_EXTEND_INREG: R =3D ScalarizeVecRes_InregOp(N); break;
+  case ISD::VSELECT:           R =3D ScalarizeVecRes_VSELECT(N); break;
   case ISD::SELECT:            R =3D ScalarizeVecRes_SELECT(N); break;
   case ISD::SELECT_CC:         R =3D ScalarizeVecRes_SELECT_CC(N); break;
   case ISD::SETCC:             R =3D ScalarizeVecRes_SETCC(N); break;
@@ -194,7 +194,7 @@
                                N->getPointerInfo(),
                                N->getMemoryVT().getVectorElementType(),
                                N->isVolatile(), N->isNonTemporal(),
-                               N->getOriginalAlignment());
+                               N->isInvariant(), N->getOriginalAlignment()=
);
=20
   // Legalized the chain result - switch anything that used the old chain =
to
   // use the new one.
@@ -227,6 +227,37 @@
   return InOp;
 }
=20
+SDValue DAGTypeLegalizer::ScalarizeVecRes_VSELECT(SDNode *N) {
+  SDValue Cond =3D GetScalarizedVector(N->getOperand(0));
+  SDValue LHS =3D GetScalarizedVector(N->getOperand(1));
+  TargetLowering::BooleanContent ScalarBool =3D TLI.getBooleanContents(fal=
se);
+  TargetLowering::BooleanContent VecBool =3D TLI.getBooleanContents(true);
+  if (ScalarBool !=3D VecBool) {
+    EVT CondVT =3D Cond.getValueType();
+    switch (ScalarBool) {
+      case TargetLowering::UndefinedBooleanContent:
+        break;
+      case TargetLowering::ZeroOrOneBooleanContent:
+        assert(VecBool =3D=3D TargetLowering::UndefinedBooleanContent ||
+               VecBool =3D=3D TargetLowering::ZeroOrNegativeOneBooleanCont=
ent);
+        // Vector read from all ones, scalar expects a single 1 so mask.
+        Cond =3D DAG.getNode(ISD::AND, N->getDebugLoc(), CondVT,
+                           Cond, DAG.getConstant(1, CondVT));
+        break;
+      case TargetLowering::ZeroOrNegativeOneBooleanContent:
+        assert(VecBool =3D=3D TargetLowering::UndefinedBooleanContent ||
+               VecBool =3D=3D TargetLowering::ZeroOrOneBooleanContent);
+        // Vector reads from a one, scalar from all ones so sign extend.
+        Cond =3D DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), Con=
dVT,
+                           Cond, DAG.getValueType(MVT::i1));
+        break;
+    }
+  }
+  return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
+                     LHS.getValueType(), Cond, LHS,
+                     GetScalarizedVector(N->getOperand(2)));
+}
+
 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
   SDValue LHS =3D GetScalarizedVector(N->getOperand(1));
   return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
@@ -405,6 +436,10 @@
         N->dump(&DAG);
         dbgs() << "\n");
   SDValue Lo, Hi;
+ =20
+  // See if the target wants to custom expand this node.
+  if (CustomLowerNode(N, N->getValueType(ResNo), true))
+    return;
=20
   switch (N->getOpcode()) {
   default:
@@ -442,8 +477,10 @@
   case ISD::ANY_EXTEND:
   case ISD::CONVERT_RNDSAT:
   case ISD::CTLZ:
+  case ISD::CTTZ:
+  case ISD::CTLZ_ZERO_UNDEF:
+  case ISD::CTTZ_ZERO_UNDEF:
   case ISD::CTPOP:
-  case ISD::CTTZ:
   case ISD::FABS:
   case ISD::FCEIL:
   case ISD::FCOS:
@@ -677,7 +714,7 @@
=20
   // Load the Lo part from the stack slot.
   Lo =3D DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, MachinePointe=
rInfo(),
-                   false, false, 0);
+                   false, false, false, 0);
=20
   // Increment the pointer to the other part.
   unsigned IncrementSize =3D Lo.getValueType().getSizeInBits() / 8;
@@ -686,7 +723,7 @@
=20
   // Load the Hi part from the stack slot.
   Hi =3D DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr, MachinePointe=
rInfo(),
-                   false, false, MinAlign(Alignment, IncrementSize));
+                   false, false, false, MinAlign(Alignment, IncrementSize)=
);
 }
=20
 void DAGTypeLegalizer::SplitVecRes_SCALAR_TO_VECTOR(SDNode *N, SDValue &Lo,
@@ -713,20 +750,21 @@
   unsigned Alignment =3D LD->getOriginalAlignment();
   bool isVolatile =3D LD->isVolatile();
   bool isNonTemporal =3D LD->isNonTemporal();
+  bool isInvariant =3D LD->isInvariant();
=20
   EVT LoMemVT, HiMemVT;
   GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
=20
   Lo =3D DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, dl, Ch, Ptr, Offset,
                    LD->getPointerInfo(), LoMemVT, isVolatile, isNonTempora=
l,
-                   Alignment);
+                   isInvariant, Alignment);
=20
   unsigned IncrementSize =3D LoMemVT.getSizeInBits()/8;
   Ptr =3D DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
                     DAG.getIntPtrConstant(IncrementSize));
   Hi =3D DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, dl, Ch, Ptr, Offset,
                    LD->getPointerInfo().getWithOffset(IncrementSize),
-                   HiMemVT, isVolatile, isNonTemporal, Alignment);
+                   HiMemVT, isVolatile, isNonTemporal, isInvariant, Alignm=
ent);
=20
   // Build a factor node to remember that this load is independent of the
   // other one.
@@ -773,46 +811,18 @@
   DebugLoc dl =3D N->getDebugLoc();
   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
=20
-  // Split the input.
+  // If the input also splits, handle it directly for a compile time speed=
up.
+  // Otherwise split it by hand.
   EVT InVT =3D N->getOperand(0).getValueType();
-  switch (getTypeAction(InVT)) {
-  default: llvm_unreachable("Unexpected type action!");
-  case TargetLowering::TypeLegal: {
+  if (getTypeAction(InVT) =3D=3D TargetLowering::TypeSplitVector) {
+    GetSplitVector(N->getOperand(0), Lo, Hi);
+  } else {
     EVT InNVT =3D EVT::getVectorVT(*DAG.getContext(), InVT.getVectorElemen=
tType(),
                                  LoVT.getVectorNumElements());
     Lo =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0),
                      DAG.getIntPtrConstant(0));
     Hi =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0),
                      DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
-    break;
-  }
-  case TargetLowering::TypePromoteInteger: {
-    SDValue InOp =3D GetPromotedInteger(N->getOperand(0));
-    EVT InNVT =3D EVT::getVectorVT(*DAG.getContext(),
-                                 InOp.getValueType().getVectorElementType(=
),
-                                 LoVT.getVectorNumElements());
-    Lo =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, InOp,
-                     DAG.getIntPtrConstant(0));
-    Hi =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, InOp,
-                     DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
-    break;
-  }
-  case TargetLowering::TypeSplitVector:
-    GetSplitVector(N->getOperand(0), Lo, Hi);
-    break;
-  case TargetLowering::TypeWidenVector: {
-    // If the result needs to be split and the input needs to be widened,
-    // the two types must have different lengths. Use the widened result
-    // and extract from it to do the split.
-    SDValue InOp =3D GetWidenedVector(N->getOperand(0));
-    EVT InNVT =3D EVT::getVectorVT(*DAG.getContext(), InVT.getVectorElemen=
tType(),
-                                 LoVT.getVectorNumElements());
-    Lo =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, InOp,
-                     DAG.getIntPtrConstant(0));
-    Hi =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, InOp,
-                     DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
-    break;
-  }
   }
=20
   if (N->getOpcode() =3D=3D ISD::FP_ROUND) {
@@ -1239,6 +1249,7 @@
   case ISD::LOAD:              Res =3D WidenVecRes_LOAD(N); break;
   case ISD::SCALAR_TO_VECTOR:  Res =3D WidenVecRes_SCALAR_TO_VECTOR(N); br=
eak;
   case ISD::SIGN_EXTEND_INREG: Res =3D WidenVecRes_InregOp(N); break;
+  case ISD::VSELECT:
   case ISD::SELECT:            Res =3D WidenVecRes_SELECT(N); break;
   case ISD::SELECT_CC:         Res =3D WidenVecRes_SELECT_CC(N); break;
   case ISD::SETCC:             Res =3D WidenVecRes_SETCC(N); break;
@@ -1590,12 +1601,15 @@
   DebugLoc dl =3D N->getDebugLoc();
=20
   switch (getTypeAction(InVT)) {
-  default:
-    assert(false && "Unknown type action!");
-    break;
   case TargetLowering::TypeLegal:
     break;
   case TargetLowering::TypePromoteInteger:
+    // If the incoming type is a vector that is being promoted, then
+    // we know that the elements are arranged differently and that we
+    // must perform the conversion using a stack slot.
+    if (InVT.isVector())
+      break;
+
     // If the InOp is promoted to the same size, convert it.  Otherwise,
     // fall out of the switch and widen the promoted input.
     InOp =3D GetPromotedInteger(InOp);
@@ -1928,7 +1942,7 @@
   SDValue InOp1 =3D GetWidenedVector(N->getOperand(1));
   SDValue InOp2 =3D GetWidenedVector(N->getOperand(2));
   assert(InOp1.getValueType() =3D=3D WidenVT && InOp2.getValueType() =3D=
=3D WidenVT);
-  return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
+  return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
                      WidenVT, Cond1, InOp1, InOp2);
 }
=20
@@ -2032,6 +2046,7 @@
   case ISD::EXTRACT_SUBVECTOR:  Res =3D WidenVecOp_EXTRACT_SUBVECTOR(N); b=
reak;
   case ISD::EXTRACT_VECTOR_ELT: Res =3D WidenVecOp_EXTRACT_VECTOR_ELT(N); =
break;
   case ISD::STORE:              Res =3D WidenVecOp_STORE(N); break;
+  case ISD::SETCC:              Res =3D WidenVecOp_SETCC(N); break;
=20
   case ISD::FP_EXTEND:
   case ISD::FP_TO_SINT:
@@ -2165,6 +2180,32 @@
                        MVT::Other,&StChain[0],StChain.size());
 }
=20
+SDValue DAGTypeLegalizer::WidenVecOp_SETCC(SDNode *N) {
+  SDValue InOp0 =3D GetWidenedVector(N->getOperand(0));
+  SDValue InOp1 =3D GetWidenedVector(N->getOperand(1));
+  DebugLoc dl =3D N->getDebugLoc();
+
+  // WARNING: In this code we widen the compare instruction with garbage.
+  // This garbage may contain denormal floats which may be slow. Is this a=
 real
+  // concern ? Should we zero the unused lanes if this is a float compare ?
+
+  // Get a new SETCC node to compare the newly widened operands.
+  // Only some of the compared elements are legal.
+  EVT SVT =3D TLI.getSetCCResultType(InOp0.getValueType());
+  SDValue WideSETCC =3D DAG.getNode(ISD::SETCC, N->getDebugLoc(),
+                     SVT, InOp0, InOp1, N->getOperand(2));
+
+  // Extract the needed results from the result vector.
+  EVT ResVT =3D EVT::getVectorVT(*DAG.getContext(),
+                               SVT.getVectorElementType(),
+                               N->getValueType(0).getVectorNumElements());
+  SDValue CC =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
+                           ResVT, WideSETCC, DAG.getIntPtrConstant(0));
+
+  return PromoteTargetBoolean(CC, N->getValueType(0));=20
+}
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Vector Widening Utilities
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2276,6 +2317,7 @@
   unsigned  Align    =3D LD->getAlignment();
   bool      isVolatile =3D LD->isVolatile();
   bool      isNonTemporal =3D LD->isNonTemporal();
+  bool      isInvariant =3D LD->isInvariant();
=20
   int LdWidth =3D LdVT.getSizeInBits();
   int WidthDiff =3D WidenWidth - LdWidth;          // Difference
@@ -2285,7 +2327,7 @@
   EVT NewVT =3D FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff=
);
   int NewVTWidth =3D NewVT.getSizeInBits();
   SDValue LdOp =3D DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerIn=
fo(),
-                             isVolatile, isNonTemporal, Align);
+                             isVolatile, isNonTemporal, isInvariant, Align=
);
   LdChain.push_back(LdOp.getValue(1));
=20
   // Check if we can load the element with one instruction
@@ -2323,18 +2365,37 @@
     BasePtr =3D DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
                           DAG.getIntPtrConstant(Increment));
=20
+    SDValue L;
     if (LdWidth < NewVTWidth) {
       // Our current type we are using is too large, find a better size
       NewVT =3D FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff=
);
       NewVTWidth =3D NewVT.getSizeInBits();
+      L =3D DAG.getLoad(NewVT, dl, Chain, BasePtr,
+                               LD->getPointerInfo().getWithOffset(Offset),
+                               isVolatile,
+                               isNonTemporal, isInvariant,
+                               MinAlign(Align, Increment));
+      LdChain.push_back(L.getValue(1));
+      if (L->getValueType(0).isVector()) {
+        SmallVector<SDValue, 16> Loads;
+        Loads.push_back(L);
+        unsigned size =3D L->getValueSizeInBits(0);
+        while (size < LdOp->getValueSizeInBits(0)) {
+          Loads.push_back(DAG.getUNDEF(L->getValueType(0)));
+          size +=3D L->getValueSizeInBits(0);
+        }
+        L =3D DAG.getNode(ISD::CONCAT_VECTORS, dl, LdOp->getValueType(0),
+                        &Loads[0], Loads.size());
+      }
+    } else {
+      L =3D DAG.getLoad(NewVT, dl, Chain, BasePtr,
+                      LD->getPointerInfo().getWithOffset(Offset), isVolati=
le,
+                      isNonTemporal, isInvariant, MinAlign(Align, Incremen=
t));
+      LdChain.push_back(L.getValue(1));
     }
=20
-    SDValue LdOp =3D DAG.getLoad(NewVT, dl, Chain, BasePtr,
-                               LD->getPointerInfo().getWithOffset(Offset),
-                               isVolatile,
-                               isNonTemporal, MinAlign(Align, Increment));
-    LdChain.push_back(LdOp.getValue(1));
-    LdOps.push_back(LdOp);
+    LdOps.push_back(L);
+
=20
     LdWidth -=3D NewVTWidth;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/ScheduleDAGFast.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGFast.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -43,7 +43,7 @@
     SmallVector<SUnit *, 16> Queue;
=20
     bool empty() const { return Queue.empty(); }
-   =20
+
     void push(SUnit *U) {
       Queue.push_back(U);
     }
@@ -101,8 +101,8 @@
   bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
   void ListScheduleBottomUp();
=20
-  /// ForceUnitLatencies - The fast scheduler doesn't care about real late=
ncies.
-  bool ForceUnitLatencies() const { return true; }
+  /// forceUnitLatencies - The fast scheduler doesn't care about real late=
ncies.
+  bool forceUnitLatencies() const { return true; }
 };
 }  // end anonymous namespace
=20
@@ -112,7 +112,7 @@
   DEBUG(dbgs() << "********** List Scheduling **********\n");
=20
   NumLiveRegs =3D 0;
-  LiveRegDefs.resize(TRI->getNumRegs(), NULL); =20
+  LiveRegDefs.resize(TRI->getNumRegs(), NULL);
   LiveRegCycles.resize(TRI->getNumRegs(), 0);
=20
   // Build the scheduling graph.
@@ -159,7 +159,7 @@
     ReleasePred(SU, &*I);
     if (I->isAssignedRegDep()) {
       // This is a physical register dependency and it's impossible or
-      // expensive to copy the register. Make sure nothing that can=20
+      // expensive to copy the register. Make sure nothing that can
       // clobber the register is scheduled between the predecessor and
       // this node.
       if (!LiveRegDefs[I->getReg()]) {
@@ -245,10 +245,10 @@
     DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
                                    SDValue(LoadNode, 1));
=20
-    SUnit *NewSU =3D NewSUnit(N);
+    SUnit *NewSU =3D newSUnit(N);
     assert(N->getNodeId() =3D=3D -1 && "Node already inserted!");
     N->setNodeId(NewSU->NodeNum);
-     =20
+
     const MCInstrDesc &MCID =3D TII->get(N->getMachineOpcode());
     for (unsigned i =3D 0; i !=3D MCID.getNumOperands(); ++i) {
       if (MCID.getOperandConstraint(i, MCOI::TIED_TO) !=3D -1) {
@@ -268,7 +268,7 @@
       LoadSU =3D &SUnits[LoadNode->getNodeId()];
       isNewLoad =3D false;
     } else {
-      LoadSU =3D NewSUnit(LoadNode);
+      LoadSU =3D newSUnit(LoadNode);
       LoadNode->setNodeId(LoadSU->NodeNum);
     }
=20
@@ -329,7 +329,7 @@
         D.setSUnit(LoadSU);
         AddPred(SuccDep, D);
       }
-    }=20
+    }
     if (isNewLoad) {
       AddPred(NewSU, SDep(LoadSU, SDep::Order, LoadSU->Latency));
     }
@@ -381,11 +381,11 @@
                                               const TargetRegisterClass *D=
estRC,
                                               const TargetRegisterClass *S=
rcRC,
                                                SmallVector<SUnit*, 2> &Cop=
ies) {
-  SUnit *CopyFromSU =3D NewSUnit(static_cast<SDNode *>(NULL));
+  SUnit *CopyFromSU =3D newSUnit(static_cast<SDNode *>(NULL));
   CopyFromSU->CopySrcRC =3D SrcRC;
   CopyFromSU->CopyDstRC =3D DestRC;
=20
-  SUnit *CopyToSU =3D NewSUnit(static_cast<SDNode *>(NULL));
+  SUnit *CopyToSU =3D newSUnit(static_cast<SDNode *>(NULL));
   CopyToSU->CopySrcRC =3D DestRC;
   CopyToSU->CopyDstRC =3D SrcRC;
=20
@@ -425,7 +425,7 @@
   const MCInstrDesc &MCID =3D TII->get(N->getMachineOpcode());
   assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def li=
st!");
   unsigned NumRes =3D MCID.getNumDefs();
-  for (const unsigned *ImpDef =3D MCID.getImplicitDefs(); *ImpDef; ++ImpDe=
f) {
+  for (const uint16_t *ImpDef =3D MCID.getImplicitDefs(); *ImpDef; ++ImpDe=
f) {
     if (Reg =3D=3D *ImpDef)
       break;
     ++NumRes;
@@ -447,7 +447,7 @@
       Added =3D true;
     }
   }
-  for (const unsigned *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)
+  for (const uint16_t *Alias =3D TRI->getAliasSet(Reg); *Alias; ++Alias)
     if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] !=3D SU) {
       if (RegAdded.insert(*Alias)) {
         LRegs.push_back(*Alias);
@@ -508,7 +508,7 @@
     const MCInstrDesc &MCID =3D TII->get(Node->getMachineOpcode());
     if (!MCID.ImplicitDefs)
       continue;
-    for (const unsigned *Reg =3D MCID.ImplicitDefs; *Reg; ++Reg) {
+    for (const uint16_t *Reg =3D MCID.getImplicitDefs(); *Reg; ++Reg) {
       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
     }
   }
@@ -630,7 +630,7 @@
   std::reverse(Sequence.begin(), Sequence.end());
=20
 #ifndef NDEBUG
-  VerifySchedule(/*isBottomUp=3D*/true);
+  VerifyScheduledSequence(/*isBottomUp=3D*/true);
 #endif
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/ScheduleDAGRRList.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGRRList.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -45,10 +45,6 @@
                        "Bottom-up register reduction list scheduling",
                        createBURRListDAGScheduler);
 static RegisterScheduler
-  tdrListrDAGScheduler("list-tdrr",
-                       "Top-down register reduction list scheduling",
-                       createTDRRListDAGScheduler);
-static RegisterScheduler
   sourceListDAGScheduler("source",
                          "Similar to list-burr but schedules in source "
                          "order when possible",
@@ -93,6 +89,9 @@
 static cl::opt<bool> DisableSchedHeight(
   "disable-sched-height", cl::Hidden, cl::init(false),
   cl::desc("Disable scheduled-height priority in sched=3Dlist-ilp"));
+static cl::opt<bool> Disable2AddrHack(
+  "disable-2addr-hack", cl::Hidden, cl::init(true),
+  cl::desc("Disable scheduler's two-address hack"));
=20
 static cl::opt<int> MaxReorderWindow(
   "max-sched-reorder", cl::Hidden, cl::init(6),
@@ -103,17 +102,6 @@
   "sched-avg-ipc", cl::Hidden, cl::init(1),
   cl::desc("Average inst/cycle whan no target itinerary exists."));
=20
-#ifndef NDEBUG
-namespace {
-  // For sched=3Dlist-ilp, Count the number of times each factor comes int=
o play.
-  enum { FactPressureDiff, FactRegUses, FactStall, FactHeight, FactDepth,
-         FactStatic, FactOther, NumFactors };
-}
-static const char *FactorName[NumFactors] =3D
-{"PressureDiff", "RegUses", "Stall", "Height", "Depth","Static", "Other"};
-static int FactorCount[NumFactors];
-#endif //!NDEBUG
-
 namespace {
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 /// ScheduleDAGRRList - The actual register reduction list scheduler
@@ -121,10 +109,6 @@
 ///
 class ScheduleDAGRRList : public ScheduleDAGSDNodes {
 private:
-  /// isBottomUp - This is true if the scheduling problem is bottom-up, fa=
lse if
-  /// it is top-down.
-  bool isBottomUp;
-
   /// NeedLatency - True if the scheduler will make use of latency informa=
tion.
   ///
   bool NeedLatency;
@@ -162,11 +146,15 @@
   /// and similar queries.
   ScheduleDAGTopologicalSort Topo;
=20
+  // Hack to keep track of the inverse of FindCallSeqStart without more cr=
azy
+  // DAG crawling.
+  DenseMap<SUnit*, SUnit*> CallSeqEndForStart;
+
 public:
   ScheduleDAGRRList(MachineFunction &mf, bool needlatency,
                     SchedulingPriorityQueue *availqueue,
                     CodeGenOpt::Level OptLevel)
-    : ScheduleDAGSDNodes(mf), isBottomUp(availqueue->isBottomUp()),
+    : ScheduleDAGSDNodes(mf),
       NeedLatency(needlatency), AvailableQueue(availqueue), CurCycle(0),
       Topo(SUnits) {
=20
@@ -221,8 +209,6 @@
=20
   void ReleasePred(SUnit *SU, const SDep *PredEdge);
   void ReleasePredecessors(SUnit *SU);
-  void ReleaseSucc(SUnit *SU, const SDep *SuccEdge);
-  void ReleaseSuccessors(SUnit *SU);
   void ReleasePending();
   void AdvanceToCycle(unsigned NextCycle);
   void AdvancePastStalls(SUnit *SU);
@@ -242,15 +228,11 @@
   SUnit *PickNodeToScheduleBottomUp();
   void ListScheduleBottomUp();
=20
-  void ScheduleNodeTopDown(SUnit*);
-  void ListScheduleTopDown();
-
-
   /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
   /// Updates the topological ordering if required.
   SUnit *CreateNewSUnit(SDNode *N) {
     unsigned NumSUnits =3D SUnits.size();
-    SUnit *NewNode =3D NewSUnit(N);
+    SUnit *NewNode =3D newSUnit(N);
     // Update the topological ordering.
     if (NewNode->NodeNum >=3D NumSUnits)
       Topo.InitDAGTopologicalSorting();
@@ -268,9 +250,9 @@
     return NewNode;
   }
=20
-  /// ForceUnitLatencies - Register-pressure-reducing scheduling doesn't
+  /// forceUnitLatencies - Register-pressure-reducing scheduling doesn't
   /// need actual latency information but the hybrid scheduler does.
-  bool ForceUnitLatencies() const {
+  bool forceUnitLatencies() const {
     return !NeedLatency;
   }
 };
@@ -278,7 +260,7 @@
=20
 /// GetCostForDef - Looks up the register class and cost for a given defin=
ition.
 /// Typically this just means looking up the representative register class,
-/// but for untyped values (MVT::untyped) it means inspecting the node's
+/// but for untyped values (MVT::Untyped) it means inspecting the node's
 /// opcode to determine what register class is being generated.
 static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos,
                           const TargetLowering *TLI,
@@ -289,7 +271,7 @@
=20
   // Special handling for untyped values.  These values can only come from
   // the expansion of custom DAG-to-DAG patterns.
-  if (VT =3D=3D MVT::untyped) {
+  if (VT =3D=3D MVT::Untyped) {
     const SDNode *Node =3D RegDefPos.GetNode();
     unsigned Opcode =3D Node->getMachineOpcode();
=20
@@ -319,18 +301,16 @@
   DEBUG(dbgs()
         << "********** List Scheduling BB#" << BB->getNumber()
         << " '" << BB->getName() << "' **********\n");
-#ifndef NDEBUG
-  for (int i =3D 0; i < NumFactors; ++i) {
-    FactorCount[i] =3D 0;
-  }
-#endif //!NDEBUG
=20
   CurCycle =3D 0;
   IssueCount =3D 0;
   MinAvailableCycle =3D DisableSchedCycles ? 0 : UINT_MAX;
   NumLiveRegs =3D 0;
-  LiveRegDefs.resize(TRI->getNumRegs(), NULL);
-  LiveRegGens.resize(TRI->getNumRegs(), NULL);
+  // Allocate slots for each physical register, plus one for a special reg=
ister
+  // to track the virtual resource of a calling sequence.
+  LiveRegDefs.resize(TRI->getNumRegs() + 1, NULL);
+  LiveRegGens.resize(TRI->getNumRegs() + 1, NULL);
+  CallSeqEndForStart.clear();
=20
   // Build the scheduling graph.
   BuildSchedGraph(NULL);
@@ -343,18 +323,16 @@
=20
   HazardRec->Reset();
=20
-  // Execute the actual scheduling loop Top-Down or Bottom-Up as appropria=
te.
-  if (isBottomUp)
-    ListScheduleBottomUp();
-  else
-    ListScheduleTopDown();
-
-#ifndef NDEBUG
-  for (int i =3D 0; i < NumFactors; ++i) {
-    DEBUG(dbgs() << FactorName[i] << "\t" << FactorCount[i] << "\n");
-  }
-#endif // !NDEBUG
+  // Execute the actual scheduling loop.
+  ListScheduleBottomUp();
+
   AvailableQueue->releaseState();
+
+  DEBUG({
+      dbgs() << "*** Final schedule ***\n";
+      dumpSchedule();
+      dbgs() << '\n';
+    });
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -376,7 +354,7 @@
 #endif
   --PredSU->NumSuccsLeft;
=20
-  if (!ForceUnitLatencies()) {
+  if (!forceUnitLatencies()) {
     // Updating predecessor's height. This is now the cycle when the
     // predecessor can be scheduled without causing a pipeline stall.
     PredSU->setHeightToAtLeast(SU->getHeight() + PredEdge->getLatency());
@@ -403,6 +381,109 @@
   }
 }
=20
+/// IsChainDependent - Test if Outer is reachable from Inner through
+/// chain dependencies.
+static bool IsChainDependent(SDNode *Outer, SDNode *Inner,
+                             unsigned NestLevel,
+                             const TargetInstrInfo *TII) {
+  SDNode *N =3D Outer;
+  for (;;) {
+    if (N =3D=3D Inner)
+      return true;
+    // For a TokenFactor, examine each operand. There may be multiple ways
+    // to get to the CALLSEQ_BEGIN, but we need to find the path with the
+    // most nesting in order to ensure that we find the corresponding matc=
h.
+    if (N->getOpcode() =3D=3D ISD::TokenFactor) {
+      for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i)
+        if (IsChainDependent(N->getOperand(i).getNode(), Inner, NestLevel,=
 TII))
+          return true;
+      return false;
+    }
+    // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
+    if (N->isMachineOpcode()) {
+      if (N->getMachineOpcode() =3D=3D
+          (unsigned)TII->getCallFrameDestroyOpcode()) {
+        ++NestLevel;
+      } else if (N->getMachineOpcode() =3D=3D
+                 (unsigned)TII->getCallFrameSetupOpcode()) {
+        if (NestLevel =3D=3D 0)
+          return false;
+        --NestLevel;
+      }
+    }
+    // Otherwise, find the chain and continue climbing.
+    for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i)
+      if (N->getOperand(i).getValueType() =3D=3D MVT::Other) {
+        N =3D N->getOperand(i).getNode();
+        goto found_chain_operand;
+      }
+    return false;
+  found_chain_operand:;
+    if (N->getOpcode() =3D=3D ISD::EntryToken)
+      return false;
+  }
+}
+
+/// FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate
+/// the corresponding (lowered) CALLSEQ_BEGIN node.
+///
+/// NestLevel and MaxNested are used in recursion to indcate the current l=
evel
+/// of nesting of CALLSEQ_BEGIN and CALLSEQ_END pairs, as well as the maxi=
mum
+/// level seen so far.
+///
+/// TODO: It would be better to give CALLSEQ_END an explicit operand to po=
int
+/// to the corresponding CALLSEQ_BEGIN to avoid needing to search for it.
+static SDNode *
+FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest,
+                 const TargetInstrInfo *TII) {
+  for (;;) {
+    // For a TokenFactor, examine each operand. There may be multiple ways
+    // to get to the CALLSEQ_BEGIN, but we need to find the path with the
+    // most nesting in order to ensure that we find the corresponding matc=
h.
+    if (N->getOpcode() =3D=3D ISD::TokenFactor) {
+      SDNode *Best =3D 0;
+      unsigned BestMaxNest =3D MaxNest;
+      for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i) {
+        unsigned MyNestLevel =3D NestLevel;
+        unsigned MyMaxNest =3D MaxNest;
+        if (SDNode *New =3D FindCallSeqStart(N->getOperand(i).getNode(),
+                                           MyNestLevel, MyMaxNest, TII))
+          if (!Best || (MyMaxNest > BestMaxNest)) {
+            Best =3D New;
+            BestMaxNest =3D MyMaxNest;
+          }
+      }
+      assert(Best);
+      MaxNest =3D BestMaxNest;
+      return Best;
+    }
+    // Check for a lowered CALLSEQ_BEGIN or CALLSEQ_END.
+    if (N->isMachineOpcode()) {
+      if (N->getMachineOpcode() =3D=3D
+          (unsigned)TII->getCallFrameDestroyOpcode()) {
+        ++NestLevel;
+        MaxNest =3D std::max(MaxNest, NestLevel);
+      } else if (N->getMachineOpcode() =3D=3D
+                 (unsigned)TII->getCallFrameSetupOpcode()) {
+        assert(NestLevel !=3D 0);
+        --NestLevel;
+        if (NestLevel =3D=3D 0)
+          return N;
+      }
+    }
+    // Otherwise, find the chain and continue climbing.
+    for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i)
+      if (N->getOperand(i).getValueType() =3D=3D MVT::Other) {
+        N =3D N->getOperand(i).getNode();
+        goto found_chain_operand;
+      }
+    return 0;
+  found_chain_operand:;
+    if (N->getOpcode() =3D=3D ISD::EntryToken)
+      return 0;
+  }
+}
+
 /// Call ReleasePred for each predecessor, then update register live def/g=
en.
 /// Always update LiveRegDefs for a register dependence even if the curren=
t SU
 /// also defines the register. This effectively create one large live range
@@ -440,6 +521,27 @@
       }
     }
   }
+
+  // If we're scheduling a lowered CALLSEQ_END, find the corresponding
+  // CALLSEQ_BEGIN. Inject an artificial physical register dependence betw=
een
+  // these nodes, to prevent other calls from being interscheduled with th=
em.
+  unsigned CallResource =3D TRI->getNumRegs();
+  if (!LiveRegDefs[CallResource])
+    for (SDNode *Node =3D SU->getNode(); Node; Node =3D Node->getGluedNode=
())
+      if (Node->isMachineOpcode() &&
+          Node->getMachineOpcode() =3D=3D (unsigned)TII->getCallFrameDestr=
oyOpcode()) {
+        unsigned NestLevel =3D 0;
+        unsigned MaxNest =3D 0;
+        SDNode *N =3D FindCallSeqStart(Node, NestLevel, MaxNest, TII);
+
+        SUnit *Def =3D &SUnits[N->getNodeId()];
+        CallSeqEndForStart[Def] =3D SU;
+
+        ++NumLiveRegs;
+        LiveRegDefs[CallResource] =3D Def;
+        LiveRegGens[CallResource] =3D SU;
+        break;
+      }
 }
=20
 /// Check to see if any of the pending instructions are ready to issue.  If
@@ -457,8 +559,7 @@
   // Check to see if any of the pending instructions are ready to issue.  =
If
   // so, add them to the available queue.
   for (unsigned i =3D 0, e =3D PendingQueue.size(); i !=3D e; ++i) {
-    unsigned ReadyCycle =3D
-      isBottomUp ? PendingQueue[i]->getHeight() : PendingQueue[i]->getDept=
h();
+    unsigned ReadyCycle =3D PendingQueue[i]->getHeight();
     if (ReadyCycle < MinAvailableCycle)
       MinAvailableCycle =3D ReadyCycle;
=20
@@ -487,10 +588,7 @@
   }
   else {
     for (; CurCycle !=3D NextCycle; ++CurCycle) {
-      if (isBottomUp)
-        HazardRec->RecedeCycle();
-      else
-        HazardRec->AdvanceCycle();
+      HazardRec->RecedeCycle();
     }
   }
   // FIXME: Instead of visiting the pending Q each time, set a dirty flag =
on the
@@ -511,7 +609,7 @@
   // currently need to treat these nodes like real instructions.
   // if (!SU->getNode() || !SU->getNode()->isMachineOpcode()) return;
=20
-  unsigned ReadyCycle =3D isBottomUp ? SU->getHeight() : SU->getDepth();
+  unsigned ReadyCycle =3D SU->getHeight();
=20
   // Bump CurCycle to account for latency. We assume the latency of other
   // available instructions may be hidden by the stall (not a full pipe st=
all).
@@ -522,7 +620,7 @@
   // Calls are scheduled in their preceding cycle, so don't conflict with
   // hazards from instructions after the call. EmitNode will reset the
   // scoreboard state before emitting the call.
-  if (isBottomUp && SU->isCall)
+  if (SU->isCall)
     return;
=20
   // FIXME: For resource conflicts in very long non-pipelined stages, we
@@ -530,7 +628,7 @@
   int Stalls =3D 0;
   while (true) {
     ScheduleHazardRecognizer::HazardType HT =3D
-      HazardRec->getHazardType(SU, isBottomUp ? -Stalls : Stalls);
+      HazardRec->getHazardType(SU, -Stalls);
=20
     if (HT =3D=3D ScheduleHazardRecognizer::NoHazard)
       break;
@@ -568,17 +666,13 @@
     HazardRec->Reset();
     return;
   }
-  if (isBottomUp && SU->isCall) {
+  if (SU->isCall) {
     // Calls are scheduled with their preceding instructions. For bottom-up
     // scheduling, clear the pipeline state before emitting.
     HazardRec->Reset();
   }
=20
   HazardRec->EmitInstruction(SU);
-
-  if (!isBottomUp && SU->isCall) {
-    HazardRec->Reset();
-  }
 }
=20
 static void resetVRegCycle(SUnit *SU);
@@ -607,7 +701,7 @@
=20
   Sequence.push_back(SU);
=20
-  AvailableQueue->ScheduledNode(SU);
+  AvailableQueue->scheduledNode(SU);
=20
   // If HazardRec is disabled, and each inst counts as one cycle, then
   // advance CurCycle before ReleasePredecessors to avoid useless pushes to
@@ -630,6 +724,20 @@
       LiveRegGens[I->getReg()] =3D NULL;
     }
   }
+  // Release the special call resource dependence, if this is the beginning
+  // of a call.
+  unsigned CallResource =3D TRI->getNumRegs();
+  if (LiveRegDefs[CallResource] =3D=3D SU)
+    for (const SDNode *SUNode =3D SU->getNode(); SUNode;
+         SUNode =3D SUNode->getGluedNode()) {
+      if (SUNode->isMachineOpcode() &&
+          SUNode->getMachineOpcode() =3D=3D (unsigned)TII->getCallFrameSet=
upOpcode()) {
+        assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
+        --NumLiveRegs;
+        LiveRegDefs[CallResource] =3D NULL;
+        LiveRegGens[CallResource] =3D NULL;
+      }
+    }
=20
   resetVRegCycle(SU);
=20
@@ -686,15 +794,41 @@
     }
   }
=20
+  // Reclaim the special call resource dependence, if this is the beginning
+  // of a call.
+  unsigned CallResource =3D TRI->getNumRegs();
+  for (const SDNode *SUNode =3D SU->getNode(); SUNode;
+       SUNode =3D SUNode->getGluedNode()) {
+    if (SUNode->isMachineOpcode() &&
+        SUNode->getMachineOpcode() =3D=3D (unsigned)TII->getCallFrameSetup=
Opcode()) {
+      ++NumLiveRegs;
+      LiveRegDefs[CallResource] =3D SU;
+      LiveRegGens[CallResource] =3D CallSeqEndForStart[SU];
+    }
+  }
+
+  // Release the special call resource dependence, if this is the end
+  // of a call.
+  if (LiveRegGens[CallResource] =3D=3D SU)
+    for (const SDNode *SUNode =3D SU->getNode(); SUNode;
+         SUNode =3D SUNode->getGluedNode()) {
+      if (SUNode->isMachineOpcode() &&
+          SUNode->getMachineOpcode() =3D=3D (unsigned)TII->getCallFrameDes=
troyOpcode()) {
+        assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
+        --NumLiveRegs;
+        LiveRegDefs[CallResource] =3D NULL;
+        LiveRegGens[CallResource] =3D NULL;
+      }
+    }
+
   for (SUnit::succ_iterator I =3D SU->Succs.begin(), E =3D SU->Succs.end();
        I !=3D E; ++I) {
     if (I->isAssignedRegDep()) {
+      if (!LiveRegDefs[I->getReg()])
+        ++NumLiveRegs;
       // This becomes the nearest def. Note that an earlier def may still =
be
       // pending if this is a two-address node.
       LiveRegDefs[I->getReg()] =3D SU;
-      if (!LiveRegDefs[I->getReg()]) {
-        ++NumLiveRegs;
-      }
       if (LiveRegGens[I->getReg()] =3D=3D NULL ||
           I->getSUnit()->getHeight() < LiveRegGens[I->getReg()]->getHeight=
())
         LiveRegGens[I->getReg()] =3D I->getSUnit();
@@ -714,7 +848,7 @@
   else {
     AvailableQueue->push(SU);
   }
-  AvailableQueue->UnscheduledNode(SU);
+  AvailableQueue->unscheduledNode(SU);
 }
=20
 /// After backtracking, the hazard checker needs to be restored to a state
@@ -805,6 +939,11 @@
     if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
       return NULL;
=20
+    // unfolding an x86 DEC64m operation results in store, dec, load which
+    // can't be handled here so quit
+    if (NewNodes.size() =3D=3D 3)
+      return NULL;
+
     DEBUG(dbgs() << "Unfolding SU #" << SU->NodeNum << "\n");
     assert(NewNodes.size() =3D=3D 2 && "Expected a load folding node!");
=20
@@ -830,7 +969,7 @@
       LoadNode->setNodeId(LoadSU->NodeNum);
=20
       InitNumRegDefsLeft(LoadSU);
-      ComputeLatency(LoadSU);
+      computeLatency(LoadSU);
     }
=20
     SUnit *NewSU =3D CreateNewSUnit(N);
@@ -848,7 +987,7 @@
       NewSU->isCommutable =3D true;
=20
     InitNumRegDefsLeft(NewSU);
-    ComputeLatency(NewSU);
+    computeLatency(NewSU);
=20
     // Record all the edges to and from the old SU, by category.
     SmallVector<SDep, 4> ChainPreds;
@@ -1027,7 +1166,7 @@
   const MCInstrDesc &MCID =3D TII->get(N->getMachineOpcode());
   assert(MCID.ImplicitDefs && "Physical reg def must be in implicit def li=
st!");
   unsigned NumRes =3D MCID.getNumDefs();
-  for (const unsigned *ImpDef =3D MCID.getImplicitDefs(); *ImpDef; ++ImpDe=
f) {
+  for (const uint16_t *ImpDef =3D MCID.getImplicitDefs(); *ImpDef; ++ImpDe=
f) {
     if (Reg =3D=3D *ImpDef)
       break;
     ++NumRes;
@@ -1042,7 +1181,7 @@
                                SmallSet<unsigned, 4> &RegAdded,
                                SmallVector<unsigned, 4> &LRegs,
                                const TargetRegisterInfo *TRI) {
-  for (const unsigned *AliasI =3D TRI->getOverlaps(Reg); *AliasI; ++AliasI=
) {
+  for (const uint16_t *AliasI =3D TRI->getOverlaps(Reg); *AliasI; ++AliasI=
) {
=20
     // Check if Ref is live.
     if (!LiveRegDefs[*AliasI]) continue;
@@ -1057,6 +1196,31 @@
   }
 }
=20
+/// CheckForLiveRegDefMasked - Check for any live physregs that are clobbe=
red
+/// by RegMask, and add them to LRegs.
+static void CheckForLiveRegDefMasked(SUnit *SU, const uint32_t *RegMask,
+                                     std::vector<SUnit*> &LiveRegDefs,
+                                     SmallSet<unsigned, 4> &RegAdded,
+                                     SmallVector<unsigned, 4> &LRegs) {
+  // Look at all live registers. Skip Reg0 and the special CallResource.
+  for (unsigned i =3D 1, e =3D LiveRegDefs.size()-1; i !=3D e; ++i) {
+    if (!LiveRegDefs[i]) continue;
+    if (LiveRegDefs[i] =3D=3D SU) continue;
+    if (!MachineOperand::clobbersPhysReg(RegMask, i)) continue;
+    if (RegAdded.insert(i))
+      LRegs.push_back(i);
+  }
+}
+
+/// getNodeRegMask - Returns the register mask attached to an SDNode, if a=
ny.
+static const uint32_t *getNodeRegMask(const SDNode *N) {
+  for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i)
+    if (const RegisterMaskSDNode *Op =3D
+        dyn_cast<RegisterMaskSDNode>(N->getOperand(i).getNode()))
+      return Op->getRegMask();
+  return NULL;
+}
+
 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
 /// scheduling of the given node to satisfy live physical register depende=
ncies.
 /// If the specific node is the last one that's available to schedule, do
@@ -1108,10 +1272,27 @@
=20
     if (!Node->isMachineOpcode())
       continue;
+    // If we're in the middle of scheduling a call, don't begin scheduling
+    // another call. Also, don't allow any physical registers to be live a=
cross
+    // the call.
+    if (Node->getMachineOpcode() =3D=3D (unsigned)TII->getCallFrameDestroy=
Opcode()) {
+      // Check the special calling-sequence resource.
+      unsigned CallResource =3D TRI->getNumRegs();
+      if (LiveRegDefs[CallResource]) {
+        SDNode *Gen =3D LiveRegGens[CallResource]->getNode();
+        while (SDNode *Glued =3D Gen->getGluedNode())
+          Gen =3D Glued;
+        if (!IsChainDependent(Gen, Node, 0, TII) && RegAdded.insert(CallRe=
source))
+          LRegs.push_back(CallResource);
+      }
+    }
+    if (const uint32_t *RegMask =3D getNodeRegMask(Node))
+      CheckForLiveRegDefMasked(SU, RegMask, LiveRegDefs, RegAdded, LRegs);
+
     const MCInstrDesc &MCID =3D TII->get(Node->getMachineOpcode());
     if (!MCID.ImplicitDefs)
       continue;
-    for (const unsigned *Reg =3D MCID.ImplicitDefs; *Reg; ++Reg)
+    for (const uint16_t *Reg =3D MCID.getImplicitDefs(); *Reg; ++Reg)
       CheckForLiveRegDef(SU, *Reg, LiveRegDefs, RegAdded, LRegs, TRI);
   }
=20
@@ -1300,100 +1481,11 @@
   std::reverse(Sequence.begin(), Sequence.end());
=20
 #ifndef NDEBUG
-  VerifySchedule(isBottomUp);
+  VerifyScheduledSequence(/*isBottomUp=3D*/true);
 #endif
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//  Top-Down Scheduling
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it =
to
-/// the AvailableQueue if the count reaches zero. Also update its cycle bo=
und.
-void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, const SDep *SuccEdge) {
-  SUnit *SuccSU =3D SuccEdge->getSUnit();
-
-#ifndef NDEBUG
-  if (SuccSU->NumPredsLeft =3D=3D 0) {
-    dbgs() << "*** Scheduling failed! ***\n";
-    SuccSU->dump(this);
-    dbgs() << " has been released too many times!\n";
-    llvm_unreachable(0);
-  }
-#endif
-  --SuccSU->NumPredsLeft;
-
-  // If all the node's predecessors are scheduled, this node is ready
-  // to be scheduled. Ignore the special ExitSU node.
-  if (SuccSU->NumPredsLeft =3D=3D 0 && SuccSU !=3D &ExitSU) {
-    SuccSU->isAvailable =3D true;
-    AvailableQueue->push(SuccSU);
-  }
-}
-
-void ScheduleDAGRRList::ReleaseSuccessors(SUnit *SU) {
-  // Top down: release successors
-  for (SUnit::succ_iterator I =3D SU->Succs.begin(), E =3D SU->Succs.end();
-       I !=3D E; ++I) {
-    assert(!I->isAssignedRegDep() &&
-           "The list-tdrr scheduler doesn't yet support physreg dependenci=
es!");
-
-    ReleaseSucc(SU, &*I);
-  }
-}
-
-/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pend=
ing
-/// count of its successors. If a successor pending count is zero, add it =
to
-/// the Available queue.
-void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU) {
-  DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
-  DEBUG(SU->dump(this));
-
-  assert(CurCycle >=3D SU->getDepth() && "Node scheduled above its depth!"=
);
-  SU->setDepthToAtLeast(CurCycle);
-  Sequence.push_back(SU);
-
-  ReleaseSuccessors(SU);
-  SU->isScheduled =3D true;
-  AvailableQueue->ScheduledNode(SU);
-}
-
-/// ListScheduleTopDown - The main loop of list scheduling for top-down
-/// schedulers.
-void ScheduleDAGRRList::ListScheduleTopDown() {
-  AvailableQueue->setCurCycle(CurCycle);
-
-  // Release any successors of the special Entry node.
-  ReleaseSuccessors(&EntrySU);
-
-  // All leaves to Available queue.
-  for (unsigned i =3D 0, e =3D SUnits.size(); i !=3D e; ++i) {
-    // It is available if it has no predecessors.
-    if (SUnits[i].Preds.empty()) {
-      AvailableQueue->push(&SUnits[i]);
-      SUnits[i].isAvailable =3D true;
-    }
-  }
-
-  // While Available queue is not empty, grab the node with the highest
-  // priority. If it is not ready put it back.  Schedule the node.
-  Sequence.reserve(SUnits.size());
-  while (!AvailableQueue->empty()) {
-    SUnit *CurSU =3D AvailableQueue->pop();
-
-    if (CurSU)
-      ScheduleNodeTopDown(CurSU);
-    ++CurCycle;
-    AvailableQueue->setCurCycle(CurCycle);
-  }
-
-#ifndef NDEBUG
-  VerifySchedule(isBottomUp);
-#endif
-}
-
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                RegReductionPriorityQueue Definition
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
@@ -1437,21 +1529,6 @@
   bool operator()(SUnit* left, SUnit* right) const;
 };
=20
-// td_ls_rr_sort - Priority function for top down register pressure reduct=
ion
-// scheduler.
-struct td_ls_rr_sort : public queue_sort {
-  enum {
-    IsBottomUp =3D false,
-    HasReadyFilter =3D false
-  };
-
-  RegReductionPQBase *SPQ;
-  td_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
-  td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
-
-  bool operator()(const SUnit* left, const SUnit* right) const;
-};
-
 // src_ls_rr_sort - Priority function for source order scheduler.
 struct src_ls_rr_sort : public queue_sort {
   enum {
@@ -1510,6 +1587,7 @@
   std::vector<SUnit*> Queue;
   unsigned CurQueueId;
   bool TracksRegPressure;
+  bool SrcOrder;
=20
   // SUnits - The SUnits for the current graph.
   std::vector<SUnit> *SUnits;
@@ -1535,11 +1613,12 @@
   RegReductionPQBase(MachineFunction &mf,
                      bool hasReadyFilter,
                      bool tracksrp,
+                     bool srcorder,
                      const TargetInstrInfo *tii,
                      const TargetRegisterInfo *tri,
                      const TargetLowering *tli)
     : SchedulingPriorityQueue(hasReadyFilter),
-      CurQueueId(0), TracksRegPressure(tracksrp),
+      CurQueueId(0), TracksRegPressure(tracksrp), SrcOrder(srcorder),
       MF(mf), TII(tii), TRI(tri), TLI(tli), scheduleDAG(NULL) {
     if (TracksRegPressure) {
       unsigned NumRC =3D TRI->getNumRegClasses();
@@ -1610,9 +1689,9 @@
=20
   int RegPressureDiff(SUnit *SU, unsigned &LiveUses) const;
=20
-  void ScheduledNode(SUnit *SU);
-
-  void UnscheduledNode(SUnit *SU);
+  void scheduledNode(SUnit *SU);
+
+  void unscheduledNode(SUnit *SU);
=20
 protected:
   bool canClobber(const SUnit *SU, const SUnit *Op);
@@ -1654,10 +1733,12 @@
 public:
   RegReductionPriorityQueue(MachineFunction &mf,
                             bool tracksrp,
+                            bool srcorder,
                             const TargetInstrInfo *tii,
                             const TargetRegisterInfo *tri,
                             const TargetLowering *tli)
-    : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, tii, tri, tli),
+    : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
+                         tii, tri, tli),
       Picker(this) {}
=20
   bool isBottomUp() const { return SF::IsBottomUp; }
@@ -1680,10 +1761,7 @@
     SF DumpPicker =3D Picker;
     while (!DumpQueue.empty()) {
       SUnit *SU =3D popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
-      if (isBottomUp())
-        dbgs() << "Height " << SU->getHeight() << ": ";
-      else
-        dbgs() << "Depth " << SU->getDepth() << ": ";
+      dbgs() << "Height " << SU->getHeight() << ": ";
       SU->dump(DAG);
     }
   }
@@ -1692,9 +1770,6 @@
 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
 BURegReductionPriorityQueue;
=20
-typedef RegReductionPriorityQueue<td_ls_rr_sort>
-TDRegReductionPriorityQueue;
-
 typedef RegReductionPriorityQueue<src_ls_rr_sort>
 SrcRegReductionPriorityQueue;
=20
@@ -1919,7 +1994,7 @@
   return PDiff;
 }
=20
-void RegReductionPQBase::ScheduledNode(SUnit *SU) {
+void RegReductionPQBase::scheduledNode(SUnit *SU) {
   if (!TracksRegPressure)
     return;
=20
@@ -1988,7 +2063,7 @@
   dumpRegPressure();
 }
=20
-void RegReductionPQBase::UnscheduledNode(SUnit *SU) {
+void RegReductionPQBase::unscheduledNode(SUnit *SU) {
   if (!TracksRegPressure)
     return;
=20
@@ -2235,37 +2310,29 @@
   int LHeight =3D (int)left->getHeight() + LPenalty;
   int RHeight =3D (int)right->getHeight() + RPenalty;
=20
-  bool LStall =3D (!checkPref || left->SchedulingPref =3D=3D Sched::Latenc=
y) &&
+  bool LStall =3D (!checkPref || left->SchedulingPref =3D=3D Sched::ILP) &&
     BUHasStall(left, LHeight, SPQ);
-  bool RStall =3D (!checkPref || right->SchedulingPref =3D=3D Sched::Laten=
cy) &&
+  bool RStall =3D (!checkPref || right->SchedulingPref =3D=3D Sched::ILP) =
&&
     BUHasStall(right, RHeight, SPQ);
=20
   // If scheduling one of the node will cause a pipeline stall, delay it.
   // If scheduling either one of the node will cause a pipeline stall, sort
   // them according to their height.
   if (LStall) {
-    if (!RStall) {
-      DEBUG(++FactorCount[FactStall]);
+    if (!RStall)
       return 1;
-    }
-    if (LHeight !=3D RHeight) {
-      DEBUG(++FactorCount[FactStall]);
+    if (LHeight !=3D RHeight)
       return LHeight > RHeight ? 1 : -1;
-    }
-  } else if (RStall) {
-    DEBUG(++FactorCount[FactStall]);
+  } else if (RStall)
     return -1;
-  }
=20
   // If either node is scheduling for latency, sort them by height/depth
   // and latency.
-  if (!checkPref || (left->SchedulingPref =3D=3D Sched::Latency ||
-                     right->SchedulingPref =3D=3D Sched::Latency)) {
+  if (!checkPref || (left->SchedulingPref =3D=3D Sched::ILP ||
+                     right->SchedulingPref =3D=3D Sched::ILP)) {
     if (DisableSchedCycles) {
-      if (LHeight !=3D RHeight) {
-        DEBUG(++FactorCount[FactHeight]);
+      if (LHeight !=3D RHeight)
         return LHeight > RHeight ? 1 : -1;
-      }
     }
     else {
       // If neither instruction stalls (!LStall && !RStall) then
@@ -2274,17 +2341,14 @@
       int LDepth =3D left->getDepth() - LPenalty;
       int RDepth =3D right->getDepth() - RPenalty;
       if (LDepth !=3D RDepth) {
-        DEBUG(++FactorCount[FactDepth]);
         DEBUG(dbgs() << "  Comparing latency of SU (" << left->NodeNum
               << ") depth " << LDepth << " vs SU (" << right->NodeNum
               << ") depth " << RDepth << "\n");
         return LDepth < RDepth ? 1 : -1;
       }
     }
-    if (left->Latency !=3D right->Latency) {
-      DEBUG(++FactorCount[FactOther]);
+    if (left->Latency !=3D right->Latency)
       return left->Latency > right->Latency ? 1 : -1;
-    }
   }
   return 0;
 }
@@ -2298,7 +2362,6 @@
     bool LHasPhysReg =3D left->hasPhysRegDefs;
     bool RHasPhysReg =3D right->hasPhysRegDefs;
     if (LHasPhysReg !=3D RHasPhysReg) {
-      DEBUG(++FactorCount[FactRegUses]);
       #ifndef NDEBUG
       const char *PhysRegMsg[] =3D {" has no physreg", " defines a physreg=
"};
       #endif
@@ -2324,10 +2387,8 @@
     LPriority =3D (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
   }
=20
-  if (LPriority !=3D RPriority) {
-    DEBUG(++FactorCount[FactStatic]);
+  if (LPriority !=3D RPriority)
     return LPriority > RPriority;
-  }
=20
   // One or both of the nodes are calls and their sethi-ullman numbers are=
 the
   // same, then keep source order.
@@ -2360,18 +2421,14 @@
   // This creates more short live intervals.
   unsigned LDist =3D closestSucc(left);
   unsigned RDist =3D closestSucc(right);
-  if (LDist !=3D RDist) {
-    DEBUG(++FactorCount[FactOther]);
+  if (LDist !=3D RDist)
     return LDist < RDist;
-  }
=20
   // How many registers becomes live when the node is scheduled.
   unsigned LScratch =3D calcMaxScratches(left);
   unsigned RScratch =3D calcMaxScratches(right);
-  if (LScratch !=3D RScratch) {
-    DEBUG(++FactorCount[FactOther]);
+  if (LScratch !=3D RScratch)
     return LScratch > RScratch;
-  }
=20
   // Comparing latency against a call makes little sense unless the node
   // is register pressure-neutral.
@@ -2386,20 +2443,15 @@
       return result > 0;
   }
   else {
-    if (left->getHeight() !=3D right->getHeight()) {
-      DEBUG(++FactorCount[FactHeight]);
+    if (left->getHeight() !=3D right->getHeight())
       return left->getHeight() > right->getHeight();
-    }
-
-    if (left->getDepth() !=3D right->getDepth()) {
-      DEBUG(++FactorCount[FactDepth]);
+
+    if (left->getDepth() !=3D right->getDepth())
       return left->getDepth() < right->getDepth();
-    }
   }
=20
   assert(left->NodeQueueId && right->NodeQueueId &&
          "NodeQueueId cannot be zero");
-  DEBUG(++FactorCount[FactOther]);
   return (left->NodeQueueId > right->NodeQueueId);
 }
=20
@@ -2459,13 +2511,11 @@
   // Avoid causing spills. If register pressure is high, schedule for
   // register pressure reduction.
   if (LHigh && !RHigh) {
-    DEBUG(++FactorCount[FactPressureDiff]);
     DEBUG(dbgs() << "  pressure SU(" << left->NodeNum << ") > SU("
           << right->NodeNum << ")\n");
     return true;
   }
   else if (!LHigh && RHigh) {
-    DEBUG(++FactorCount[FactPressureDiff]);
     DEBUG(dbgs() << "  pressure SU(" << right->NodeNum << ") > SU("
           << left->NodeNum << ")\n");
     return false;
@@ -2529,7 +2579,6 @@
     RPDiff =3D SPQ->RegPressureDiff(right, RLiveUses);
   }
   if (!DisableSchedRegPressure && LPDiff !=3D RPDiff) {
-    DEBUG(++FactorCount[FactPressureDiff]);
     DEBUG(dbgs() << "RegPressureDiff SU(" << left->NodeNum << "): " << LPD=
iff
           << " !=3D SU(" << right->NodeNum << "): " << RPDiff << "\n");
     return LPDiff > RPDiff;
@@ -2538,7 +2587,6 @@
   if (!DisableSchedRegPressure && (LPDiff > 0 || RPDiff > 0)) {
     bool LReduce =3D canEnableCoalescing(left);
     bool RReduce =3D canEnableCoalescing(right);
-    DEBUG(if (LReduce !=3D RReduce) ++FactorCount[FactPressureDiff]);
     if (LReduce && !RReduce) return false;
     if (RReduce && !LReduce) return true;
   }
@@ -2546,17 +2594,14 @@
   if (!DisableSchedLiveUses && (LLiveUses !=3D RLiveUses)) {
     DEBUG(dbgs() << "Live uses SU(" << left->NodeNum << "): " << LLiveUses
           << " !=3D SU(" << right->NodeNum << "): " << RLiveUses << "\n");
-    DEBUG(++FactorCount[FactRegUses]);
     return LLiveUses < RLiveUses;
   }
=20
   if (!DisableSchedStalls) {
     bool LStall =3D BUHasStall(left, left->getHeight(), SPQ);
     bool RStall =3D BUHasStall(right, right->getHeight(), SPQ);
-    if (LStall !=3D RStall) {
-      DEBUG(++FactorCount[FactHeight]);
+    if (LStall !=3D RStall)
       return left->getHeight() > right->getHeight();
-    }
   }
=20
   if (!DisableSchedCriticalPath) {
@@ -2565,17 +2610,14 @@
       DEBUG(dbgs() << "Depth of SU(" << left->NodeNum << "): "
             << left->getDepth() << " !=3D SU(" << right->NodeNum << "): "
             << right->getDepth() << "\n");
-      DEBUG(++FactorCount[FactDepth]);
       return left->getDepth() < right->getDepth();
     }
   }
=20
   if (!DisableSchedHeight && left->getHeight() !=3D right->getHeight()) {
     int spread =3D (int)left->getHeight() - (int)right->getHeight();
-    if (std::abs(spread) > MaxReorderWindow) {
-      DEBUG(++FactorCount[FactHeight]);
+    if (std::abs(spread) > MaxReorderWindow)
       return left->getHeight() > right->getHeight();
-    }
   }
=20
   return BURRSort(left, right, SPQ);
@@ -2584,9 +2626,10 @@
 void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
   SUnits =3D &sunits;
   // Add pseudo dependency edges for two-address nodes.
-  AddPseudoTwoAddrDeps();
+  if (!Disable2AddrHack)
+    AddPseudoTwoAddrDeps();
   // Reroute edges to nodes with multiple uses.
-  if (!TracksRegPressure)
+  if (!TracksRegPressure && !SrcOrder)
     PrescheduleNodesWithMultipleUses();
   // Calculate node priorities.
   CalculateSethiUllmanNumbers();
@@ -2628,9 +2671,10 @@
                                          ScheduleDAGRRList *scheduleDAG,
                                          const TargetInstrInfo *TII,
                                          const TargetRegisterInfo *TRI) {
-  const unsigned *ImpDefs
+  const uint16_t *ImpDefs
     =3D TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
-  if(!ImpDefs)
+  const uint32_t *RegMask =3D getNodeRegMask(SU->getNode());
+  if(!ImpDefs && !RegMask)
     return false;
=20
   for (SUnit::const_succ_iterator SI =3D SU->Succs.begin(), SE =3D SU->Suc=
cs.end();
@@ -2641,14 +2685,18 @@
       if (!PI->isAssignedRegDep())
         continue;
=20
-      for (const unsigned *ImpDef =3D ImpDefs; *ImpDef; ++ImpDef) {
-        // Return true if SU clobbers this physical register use and the
-        // definition of the register reaches from DepSU. IsReachable quer=
ies a
-        // topological forward sort of the DAG (following the successors).
-        if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
-            scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
-          return true;
-      }
+      if (RegMask && MachineOperand::clobbersPhysReg(RegMask, PI->getReg()=
) &&
+          scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
+        return true;
+
+      if (ImpDefs)
+        for (const uint16_t *ImpDef =3D ImpDefs; *ImpDef; ++ImpDef)
+          // Return true if SU clobbers this physical register use and the
+          // definition of the register reaches from DepSU. IsReachable qu=
eries
+          // a topological forward sort of the DAG (following the successo=
rs).
+          if (TRI->regsOverlap(*ImpDef, PI->getReg()) &&
+              scheduleDAG->IsReachable(DepSU, PI->getSUnit()))
+            return true;
     }
   }
   return false;
@@ -2661,16 +2709,17 @@
                                   const TargetRegisterInfo *TRI) {
   SDNode *N =3D SuccSU->getNode();
   unsigned NumDefs =3D TII->get(N->getMachineOpcode()).getNumDefs();
-  const unsigned *ImpDefs =3D TII->get(N->getMachineOpcode()).getImplicitD=
efs();
+  const uint16_t *ImpDefs =3D TII->get(N->getMachineOpcode()).getImplicitD=
efs();
   assert(ImpDefs && "Caller should check hasPhysRegDefs");
   for (const SDNode *SUNode =3D SU->getNode(); SUNode;
        SUNode =3D SUNode->getGluedNode()) {
     if (!SUNode->isMachineOpcode())
       continue;
-    const unsigned *SUImpDefs =3D
+    const uint16_t *SUImpDefs =3D
       TII->get(SUNode->getMachineOpcode()).getImplicitDefs();
-    if (!SUImpDefs)
-      return false;
+    const uint32_t *SURegMask =3D getNodeRegMask(SUNode);
+    if (!SUImpDefs && !SURegMask)
+      continue;
     for (unsigned i =3D NumDefs, e =3D N->getNumValues(); i !=3D e; ++i) {
       EVT VT =3D N->getValueType(i);
       if (VT =3D=3D MVT::Glue || VT =3D=3D MVT::Other)
@@ -2678,6 +2727,10 @@
       if (!N->hasAnyUseOfValue(i))
         continue;
       unsigned Reg =3D ImpDefs[i - NumDefs];
+      if (SURegMask && MachineOperand::clobbersPhysReg(SURegMask, Reg))
+        return true;
+      if (!SUImpDefs)
+        continue;
       for (;*SUImpDefs; ++SUImpDefs) {
         unsigned SUReg =3D *SUImpDefs;
         if (TRI->regsOverlap(Reg, SUReg))
@@ -2887,69 +2940,6 @@
   }
 }
=20
-/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unschedul=
ed
-/// predecessors of the successors of the SUnit SU. Stop when the provided
-/// limit is exceeded.
-static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
-                                                    unsigned Limit) {
-  unsigned Sum =3D 0;
-  for (SUnit::const_succ_iterator I =3D SU->Succs.begin(), E =3D SU->Succs=
.end();
-       I !=3D E; ++I) {
-    const SUnit *SuccSU =3D I->getSUnit();
-    for (SUnit::const_pred_iterator II =3D SuccSU->Preds.begin(),
-         EE =3D SuccSU->Preds.end(); II !=3D EE; ++II) {
-      SUnit *PredSU =3D II->getSUnit();
-      if (!PredSU->isScheduled)
-        if (++Sum > Limit)
-          return Sum;
-    }
-  }
-  return Sum;
-}
-
-
-// Top down
-bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) cons=
t {
-  if (int res =3D checkSpecialNodes(left, right))
-    return res < 0;
-
-  unsigned LPriority =3D SPQ->getNodePriority(left);
-  unsigned RPriority =3D SPQ->getNodePriority(right);
-  bool LIsTarget =3D left->getNode() && left->getNode()->isMachineOpcode();
-  bool RIsTarget =3D right->getNode() && right->getNode()->isMachineOpcode=
();
-  bool LIsFloater =3D LIsTarget && left->NumPreds =3D=3D 0;
-  bool RIsFloater =3D RIsTarget && right->NumPreds =3D=3D 0;
-  unsigned LBonus =3D (LimitedSumOfUnscheduledPredsOfSuccs(left,1) =3D=3D =
1) ? 2 : 0;
-  unsigned RBonus =3D (LimitedSumOfUnscheduledPredsOfSuccs(right,1) =3D=3D=
 1) ? 2 : 0;
-
-  if (left->NumSuccs =3D=3D 0 && right->NumSuccs !=3D 0)
-    return false;
-  else if (left->NumSuccs !=3D 0 && right->NumSuccs =3D=3D 0)
-    return true;
-
-  if (LIsFloater)
-    LBonus -=3D 2;
-  if (RIsFloater)
-    RBonus -=3D 2;
-  if (left->NumSuccs =3D=3D 1)
-    LBonus +=3D 2;
-  if (right->NumSuccs =3D=3D 1)
-    RBonus +=3D 2;
-
-  if (LPriority+LBonus !=3D RPriority+RBonus)
-    return LPriority+LBonus < RPriority+RBonus;
-
-  if (left->getDepth() !=3D right->getDepth())
-    return left->getDepth() < right->getDepth();
-
-  if (left->NumSuccsLeft !=3D right->NumSuccsLeft)
-    return left->NumSuccsLeft > right->NumSuccsLeft;
-
-  assert(left->NodeQueueId && right->NodeQueueId &&
-         "NodeQueueId cannot be zero");
-  return (left->NodeQueueId > right->NodeQueueId);
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                         Public Constructor Functions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2962,21 +2952,7 @@
   const TargetRegisterInfo *TRI =3D TM.getRegisterInfo();
=20
   BURegReductionPriorityQueue *PQ =3D
-    new BURegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
-  ScheduleDAGRRList *SD =3D new ScheduleDAGRRList(*IS->MF, false, PQ, OptL=
evel);
-  PQ->setScheduleDAG(SD);
-  return SD;
-}
-
-llvm::ScheduleDAGSDNodes *
-llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
-                                 CodeGenOpt::Level OptLevel) {
-  const TargetMachine &TM =3D IS->TM;
-  const TargetInstrInfo *TII =3D TM.getInstrInfo();
-  const TargetRegisterInfo *TRI =3D TM.getRegisterInfo();
-
-  TDRegReductionPriorityQueue *PQ =3D
-    new TDRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
+    new BURegReductionPriorityQueue(*IS->MF, false, false, TII, TRI, 0);
   ScheduleDAGRRList *SD =3D new ScheduleDAGRRList(*IS->MF, false, PQ, OptL=
evel);
   PQ->setScheduleDAG(SD);
   return SD;
@@ -2990,7 +2966,7 @@
   const TargetRegisterInfo *TRI =3D TM.getRegisterInfo();
=20
   SrcRegReductionPriorityQueue *PQ =3D
-    new SrcRegReductionPriorityQueue(*IS->MF, false, TII, TRI, 0);
+    new SrcRegReductionPriorityQueue(*IS->MF, false, true, TII, TRI, 0);
   ScheduleDAGRRList *SD =3D new ScheduleDAGRRList(*IS->MF, false, PQ, OptL=
evel);
   PQ->setScheduleDAG(SD);
   return SD;
@@ -3005,7 +2981,7 @@
   const TargetLowering *TLI =3D &IS->getTargetLowering();
=20
   HybridBURRPriorityQueue *PQ =3D
-    new HybridBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
+    new HybridBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
=20
   ScheduleDAGRRList *SD =3D new ScheduleDAGRRList(*IS->MF, true, PQ, OptLe=
vel);
   PQ->setScheduleDAG(SD);
@@ -3021,7 +2997,7 @@
   const TargetLowering *TLI =3D &IS->getTargetLowering();
=20
   ILPBURRPriorityQueue *PQ =3D
-    new ILPBURRPriorityQueue(*IS->MF, true, TII, TRI, TLI);
+    new ILPBURRPriorityQueue(*IS->MF, true, false, TII, TRI, TLI);
   ScheduleDAGRRList *SD =3D new ScheduleDAGRRList(*IS->MF, true, PQ, OptLe=
vel);
   PQ->setScheduleDAG(SD);
   return SD;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/ScheduleDAGSDNodes.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -17,6 +17,8 @@
 #include "ScheduleDAGSDNodes.h"
 #include "InstrEmitter.h"
 #include "llvm/CodeGen/SelectionDAG.h"
+#include "llvm/CodeGen/MachineInstrBuilder.h"
+#include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/MC/MCInstrItineraries.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetInstrInfo.h"
@@ -44,20 +46,26 @@
            "instructions take for targets with no itinerary"));
=20
 ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf)
-  : ScheduleDAG(mf),
+  : ScheduleDAG(mf), BB(0), DAG(0),
     InstrItins(mf.getTarget().getInstrItineraryData()) {}
=20
 /// Run - perform scheduling.
 ///
-void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb,
-                             MachineBasicBlock::iterator insertPos) {
+void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
+  BB =3D bb;
   DAG =3D dag;
-  ScheduleDAG::Run(bb, insertPos);
+
+  // Clear the scheduler's SUnit DAG.
+  ScheduleDAG::clearDAG();
+  Sequence.clear();
+
+  // Invoke the target's selection of scheduler.
+  Schedule();
 }
=20
 /// NewSUnit - Creates a new SUnit and return a ptr to it.
 ///
-SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) {
+SUnit *ScheduleDAGSDNodes::newSUnit(SDNode *N) {
 #ifndef NDEBUG
   const SUnit *Addr =3D 0;
   if (!SUnits.empty())
@@ -79,7 +87,7 @@
 }
=20
 SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) {
-  SUnit *SU =3D NewSUnit(Old->getNode());
+  SUnit *SU =3D newSUnit(Old->getNode());
   SU->OrigNode =3D Old->OrigNode;
   SU->Latency =3D Old->Latency;
   SU->isVRegCycle =3D Old->isVRegCycle;
@@ -302,7 +310,7 @@
     // If this node has already been processed, stop now.
     if (NI->getNodeId() !=3D -1) continue;
=20
-    SUnit *NodeSUnit =3D NewSUnit(NI);
+    SUnit *NodeSUnit =3D newSUnit(NI);
=20
     // See if anything is glued to this node, if so, add them to glued
     // nodes.  Nodes can have at most one glue input and one glue output. =
 Glue
@@ -360,7 +368,7 @@
     InitNumRegDefsLeft(NodeSUnit);
=20
     // Assign the Latency field of NodeSUnit using target-provided informa=
tion.
-    ComputeLatency(NodeSUnit);
+    computeLatency(NodeSUnit);
   }
=20
   // Find all call operands.
@@ -382,7 +390,7 @@
   const TargetSubtargetInfo &ST =3D TM.getSubtarget<TargetSubtargetInfo>();
=20
   // Check to see if the scheduler cares about latencies.
-  bool UnitLatencies =3D ForceUnitLatencies();
+  bool UnitLatencies =3D forceUnitLatencies();
=20
   // Pass 2: add the preds, succs, etc.
   for (unsigned su =3D 0, e =3D SUnits.size(); su !=3D e; ++su) {
@@ -448,7 +456,7 @@
         const SDep &dep =3D SDep(OpSU, isChain ? SDep::Order : SDep::Data,
                                OpLatency, PhysReg);
         if (!isChain && !UnitLatencies) {
-          ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
+          computeOperandLatency(OpN, N, i, const_cast<SDep &>(dep));
           ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep));
         }
=20
@@ -541,7 +549,7 @@
   }
 }
=20
-void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) {
+void ScheduleDAGSDNodes::computeLatency(SUnit *SU) {
   SDNode *N =3D SU->getNode();
=20
   // TokenFactor operands are considered zero latency, and some schedulers
@@ -553,7 +561,7 @@
   }
=20
   // Check to see if the scheduler cares about latencies.
-  if (ForceUnitLatencies()) {
+  if (forceUnitLatencies()) {
     SU->Latency =3D 1;
     return;
   }
@@ -575,10 +583,10 @@
       SU->Latency +=3D TII->getInstrLatency(InstrItins, N);
 }
=20
-void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use,
+void ScheduleDAGSDNodes::computeOperandLatency(SDNode *Def, SDNode *Use,
                                                unsigned OpIdx, SDep& dep) =
const{
   // Check to see if the scheduler cares about latencies.
-  if (ForceUnitLatencies())
+  if (forceUnitLatencies())
     return;
=20
   if (dep.getKind() !=3D SDep::Data)
@@ -621,6 +629,30 @@
   }
 }
=20
+void ScheduleDAGSDNodes::dumpSchedule() const {
+  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; i++) {
+    if (SUnit *SU =3D Sequence[i])
+      SU->dump(this);
+    else
+      dbgs() << "**** NOOP ****\n";
+  }
+}
+
+#ifndef NDEBUG
+/// VerifyScheduledSequence - Verify that all SUnits were scheduled and th=
at
+/// their state is consistent with the nodes listed in Sequence.
+///
+void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) {
+  unsigned ScheduledNodes =3D ScheduleDAG::VerifyScheduledDAG(isBottomUp);
+  unsigned Noops =3D 0;
+  for (unsigned i =3D 0, e =3D Sequence.size(); i !=3D e; ++i)
+    if (!Sequence[i])
+      ++Noops;
+  assert(Sequence.size() - Noops =3D=3D ScheduledNodes &&
+         "The number of nodes scheduled doesn't match the expected number!=
");
+}
+#endif // NDEBUG
+
 namespace {
   struct OrderSorter {
     bool operator()(const std::pair<unsigned, MachineInstr*> &A,
@@ -686,9 +718,48 @@
   ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order);
 }
=20
+void ScheduleDAGSDNodes::
+EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
+                MachineBasicBlock::iterator InsertPos) {
+  for (SUnit::const_pred_iterator I =3D SU->Preds.begin(), E =3D SU->Preds=
.end();
+       I !=3D E; ++I) {
+    if (I->isCtrl()) continue;  // ignore chain preds
+    if (I->getSUnit()->CopyDstRC) {
+      // Copy to physical register.
+      DenseMap<SUnit*, unsigned>::iterator VRI =3D VRBaseMap.find(I->getSU=
nit());
+      assert(VRI !=3D VRBaseMap.end() && "Node emitted out of order - late=
");
+      // Find the destination physical register.
+      unsigned Reg =3D 0;
+      for (SUnit::const_succ_iterator II =3D SU->Succs.begin(),
+             EE =3D SU->Succs.end(); II !=3D EE; ++II) {
+        if (II->isCtrl()) continue;  // ignore chain preds
+        if (II->getReg()) {
+          Reg =3D II->getReg();
+          break;
+        }
+      }
+      BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Re=
g)
+        .addReg(VRI->second);
+    } else {
+      // Copy from physical register.
+      assert(I->getReg() && "Unknown physical register!");
+      unsigned VRBase =3D MRI.createVirtualRegister(SU->CopyDstRC);
+      bool isNew =3D VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
+      (void)isNew; // Silence compiler warning.
+      assert(isNew && "Node emitted out of order - early");
+      BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VR=
Base)
+        .addReg(I->getReg());
+    }
+    break;
+  }
+}
=20
-/// EmitSchedule - Emit the machine code in scheduled order.
-MachineBasicBlock *ScheduleDAGSDNodes::EmitSchedule() {
+/// EmitSchedule - Emit the machine code in scheduled order. Return the new
+/// InsertPos and MachineBasicBlock that contains this insertion
+/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this=
 does
+/// not necessarily refer to returned BB. The emitter may split blocks.
+MachineBasicBlock *ScheduleDAGSDNodes::
+EmitSchedule(MachineBasicBlock::iterator &InsertPos) {
   InstrEmitter Emitter(BB, InsertPos);
   DenseMap<SDValue, unsigned> VRBaseMap;
   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
@@ -711,7 +782,7 @@
     SUnit *SU =3D Sequence[i];
     if (!SU) {
       // Null SUnit* is a noop.
-      EmitNoop();
+      TII->insertNoop(*Emitter.getBlock(), InsertPos);
       continue;
     }
=20
@@ -719,7 +790,7 @@
     // SDNode and any glued SDNodes and append them to the block.
     if (!SU->getNode()) {
       // Emit a copy.
-      EmitPhysRegCopy(SU, CopyVRBaseMap);
+      EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos);
       continue;
     }
=20
@@ -784,19 +855,24 @@
     }
     // Add trailing DbgValue's before the terminator. FIXME: May want to a=
dd
     // some of them before one or more conditional branches?
+    SmallVector<MachineInstr*, 8> DbgMIs;
     while (DI !=3D DE) {
-      MachineBasicBlock *InsertBB =3D Emitter.getBlock();
-      MachineBasicBlock::iterator Pos=3D Emitter.getBlock()->getFirstTermi=
nator();
-      if (!(*DI)->isInvalidated()) {
-        MachineInstr *DbgMI=3D Emitter.EmitDbgValue(*DI, VRBaseMap);
-        if (DbgMI)
-          InsertBB->insert(Pos, DbgMI);
-      }
+      if (!(*DI)->isInvalidated())
+        if (MachineInstr *DbgMI =3D Emitter.EmitDbgValue(*DI, VRBaseMap))
+          DbgMIs.push_back(DbgMI);
       ++DI;
     }
+
+    MachineBasicBlock *InsertBB =3D Emitter.getBlock();
+    MachineBasicBlock::iterator Pos =3D InsertBB->getFirstTerminator();
+    InsertBB->insert(Pos, DbgMIs.begin(), DbgMIs.end());
   }
=20
-  BB =3D Emitter.getBlock();
   InsertPos =3D Emitter.getInsertPos();
-  return BB;
+  return Emitter.getBlock();
 }
+
+/// Return the basic block label.
+std::string ScheduleDAGSDNodes::getDAGName() const {
+  return "sunit-dag." + BB->getFullName();
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/ScheduleDAGSDNodes.h
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/ScheduleDAGSDNodes.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -35,17 +35,20 @@
   ///
   class ScheduleDAGSDNodes : public ScheduleDAG {
   public:
+    MachineBasicBlock *BB;
     SelectionDAG *DAG;                    // DAG of the current basic block
     const InstrItineraryData *InstrItins;
=20
+    /// The schedule. Null SUnit*'s represent noop instructions.
+    std::vector<SUnit*> Sequence;
+
     explicit ScheduleDAGSDNodes(MachineFunction &mf);
=20
     virtual ~ScheduleDAGSDNodes() {}
=20
     /// Run - perform scheduling.
     ///
-    void Run(SelectionDAG *dag, MachineBasicBlock *bb,
-             MachineBasicBlock::iterator insertPos);
+    void Run(SelectionDAG *dag, MachineBasicBlock *bb);
=20
     /// isPassiveNode - Return true if the node is a non-scheduled leaf.
     ///
@@ -53,6 +56,7 @@
       if (isa<ConstantSDNode>(Node))       return true;
       if (isa<ConstantFPSDNode>(Node))     return true;
       if (isa<RegisterSDNode>(Node))       return true;
+      if (isa<RegisterMaskSDNode>(Node))   return true;
       if (isa<GlobalAddressSDNode>(Node))  return true;
       if (isa<BasicBlockSDNode>(Node))     return true;
       if (isa<FrameIndexSDNode>(Node))     return true;
@@ -67,7 +71,7 @@
=20
     /// NewSUnit - Creates a new SUnit and return a ptr to it.
     ///
-    SUnit *NewSUnit(SDNode *N);
+    SUnit *newSUnit(SDNode *N);
=20
     /// Clone - Creates a clone of the specified SUnit. It does not copy t=
he
     /// predecessors / successors info nor the temporary scheduling states.
@@ -78,7 +82,7 @@
     /// are input.  This SUnit graph is similar to the SelectionDAG, but
     /// excludes nodes that aren't interesting to scheduling, and represen=
ts
     /// flagged together nodes with a single SUnit.
-    virtual void BuildSchedGraph(AliasAnalysis *AA);
+    void BuildSchedGraph(AliasAnalysis *AA);
=20
     /// InitVRegCycleFlag - Set isVRegCycle if this node's single use is
     /// CopyToReg and its only active data operands are CopyFromReg within=
 a
@@ -90,30 +94,41 @@
     ///
     void InitNumRegDefsLeft(SUnit *SU);
=20
-    /// ComputeLatency - Compute node latency.
+    /// computeLatency - Compute node latency.
     ///
-    virtual void ComputeLatency(SUnit *SU);
+    virtual void computeLatency(SUnit *SU);
=20
-    /// ComputeOperandLatency - Override dependence edge latency using
+    /// computeOperandLatency - Override dependence edge latency using
     /// operand use/def information
     ///
-    virtual void ComputeOperandLatency(SUnit *Def, SUnit *Use,
+    virtual void computeOperandLatency(SUnit *Def, SUnit *Use,
                                        SDep& dep) const { }
=20
-    virtual void ComputeOperandLatency(SDNode *Def, SDNode *Use,
+    virtual void computeOperandLatency(SDNode *Def, SDNode *Use,
                                        unsigned OpIdx, SDep& dep) const;
=20
-    virtual MachineBasicBlock *EmitSchedule();
-
     /// Schedule - Order nodes according to selected style, filling
     /// in the Sequence member.
     ///
     virtual void Schedule() =3D 0;
=20
+    /// VerifyScheduledSequence - Verify that all SUnits are scheduled and
+    /// consistent with the Sequence of scheduled instructions.
+    void VerifyScheduledSequence(bool isBottomUp);
+
+    /// EmitSchedule - Insert MachineInstrs into the MachineBasicBlock
+    /// according to the order specified in Sequence.
+    ///
+    MachineBasicBlock *EmitSchedule(MachineBasicBlock::iterator &InsertPos=
);
+
     virtual void dumpNode(const SUnit *SU) const;
=20
+    void dumpSchedule() const;
+
     virtual std::string getGraphNodeLabel(const SUnit *SU) const;
=20
+    virtual std::string getDAGName() const;
+
     virtual void getCustomGraphFeatures(GraphWriter<ScheduleDAG*> &GW) con=
st;
=20
     /// RegDefIter - In place iteration over the values defined by an
@@ -159,6 +174,9 @@
     /// BuildSchedUnits, AddSchedEdges - Helper functions for BuildSchedGr=
aph.
     void BuildSchedUnits();
     void AddSchedEdges();
+
+    void EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap,
+                         MachineBasicBlock::iterator InsertPos);
   };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/SelectionDAG.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -28,7 +28,6 @@
 #include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetLowering.h"
@@ -63,6 +62,7 @@
 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
   switch (VT.getSimpleVT().SimpleTy) {
   default: llvm_unreachable("Unknown FP format");
+  case MVT::f16:     return &APFloat::IEEEhalf;
   case MVT::f32:     return &APFloat::IEEEsingle;
   case MVT::f64:     return &APFloat::IEEEdouble;
   case MVT::f80:     return &APFloat::x87DoubleExtended;
@@ -125,20 +125,29 @@
   if (i =3D=3D e) return false;
=20
   // Do not accept build_vectors that aren't all constants or which have n=
on-~0
-  // elements.
+  // elements. We have to be a bit careful here, as the type of the consta=
nt
+  // may not be the same as the type of the vector elements due to type
+  // legalization (the elements are promoted to a legal type for the targe=
t and
+  // a vector of a type may be legal when the base element type is not).
+  // We only want to check enough bits to cover the vector elements, becau=
se
+  // we care if the resultant vector is all ones, not whether the individu=
al
+  // constants are.
   SDValue NotZero =3D N->getOperand(i);
+  unsigned EltSize =3D N->getValueType(0).getVectorElementType().getSizeIn=
Bits();
   if (isa<ConstantSDNode>(NotZero)) {
-    if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
+    if (cast<ConstantSDNode>(NotZero)->getAPIntValue().countTrailingOnes()=
 <
+        EltSize)
       return false;
   } else if (isa<ConstantFPSDNode>(NotZero)) {
-    if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
-                bitcastToAPInt().isAllOnesValue())
+    if (cast<ConstantFPSDNode>(NotZero)->getValueAPF()
+              .bitcastToAPInt().countTrailingOnes() < EltSize)
       return false;
   } else
     return false;
=20
   // Okay, we have at least one ~0 value, check to see if the rest match o=
r are
-  // undefs.
+  // undefs. Even with the above element type twiddling, this should be OK=
, as
+  // the same type legalization should have applied to all the elements.
   for (++i; i !=3D e; ++i)
     if (N->getOperand(i) !=3D NotZero &&
         N->getOperand(i).getOpcode() !=3D ISD::UNDEF)
@@ -384,7 +393,9 @@
   case ISD::Register:
     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
     break;
-
+  case ISD::RegisterMask:
+    ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
+    break;
   case ISD::SRCVALUE:
     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
     break;
@@ -475,7 +486,7 @@
 ///
 static inline unsigned
 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
-                     bool isNonTemporal) {
+                     bool isNonTemporal, bool isInvariant) {
   assert((ConvType & 3) =3D=3D ConvType &&
          "ConvType may not require more than 2 bits!");
   assert((AM & 7) =3D=3D AM &&
@@ -483,7 +494,8 @@
   return ConvType |
          (AM << 2) |
          (isVolatile << 5) |
-         (isNonTemporal << 6);
+         (isNonTemporal << 6) |
+         (isInvariant << 7);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -564,6 +576,12 @@
=20
 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateList=
ener){
   SmallVector<SDNode*, 16> DeadNodes(1, N);
+
+  // Create a dummy node that adds a reference to the root node, preventing
+  // it from being deleted.  (This matters if the root is an operand of the
+  // dead node.)
+  HandleSDNode Dummy(getRoot());
+
   RemoveDeadNodes(DeadNodes, UpdateListener);
 }
=20
@@ -834,9 +852,9 @@
 }
=20
 // EntryNode could meaningfully have debug info if we can find it...
-SelectionDAG::SelectionDAG(const TargetMachine &tm)
+SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
   : TM(tm), TLI(*tm.getTargetLowering()), TSI(*tm.getSelectionDAGInfo()),
-    EntryNode(ISD::EntryToken, DebugLoc(), getVTList(MVT::Other)),
+    OptLevel(OL), EntryNode(ISD::EntryToken, DebugLoc(), getVTList(MVT::Ot=
her)),
     Root(getEntryNode()), Ordering(0) {
   AllNodes.push_back(&EntryNode);
   Ordering =3D new SDNodeOrdering();
@@ -1025,16 +1043,14 @@
     return getConstantFP(APFloat((float)Val), VT, isTarget);
   else if (EltVT=3D=3DMVT::f64)
     return getConstantFP(APFloat(Val), VT, isTarget);
-  else if (EltVT=3D=3DMVT::f80 || EltVT=3D=3DMVT::f128) {
+  else if (EltVT=3D=3DMVT::f80 || EltVT=3D=3DMVT::f128 || EltVT=3D=3DMVT::=
f16) {
     bool ignored;
     APFloat apf =3D APFloat(Val);
     apf.convert(*EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEve=
n,
                 &ignored);
     return getConstantFP(apf, VT, isTarget);
-  } else {
-    assert(0 && "Unsupported type in getConstantFP");
-    return SDValue();
-  }
+  } else
+    llvm_unreachable("Unsupported type in getConstantFP");
 }
=20
 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, DebugLoc DL,
@@ -1369,6 +1385,20 @@
   return SDValue(N, 0);
 }
=20
+SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), 0, 0);
+  ID.AddPointer(RegMask);
+  void *IP =3D 0;
+  if (SDNode *E =3D CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+
+  SDNode *N =3D new (NodeAllocator) RegisterMaskSDNode(RegMask);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
 SDValue SelectionDAG::getEHLabel(DebugLoc dl, SDValue Root, MCSymbol *Labe=
l) {
   FoldingSetNodeID ID;
   SDValue Ops[] =3D { Root };
@@ -1598,7 +1628,7 @@
 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
                                      unsigned Depth) const {
   APInt KnownZero, KnownOne;
-  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
+  ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
   assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND zero=
?");
   return (KnownZero & Mask) =3D=3D Mask;
 }
@@ -1607,15 +1637,12 @@
 /// known to be either zero or one and return them in the KnownZero/KnownO=
ne
 /// bitsets.  This code only analyzes bits in Mask, in order to short-circ=
uit
 /// processing.
-void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
-                                     APInt &KnownZero, APInt &KnownOne,
-                                     unsigned Depth) const {
-  unsigned BitWidth =3D Mask.getBitWidth();
-  assert(BitWidth =3D=3D Op.getValueType().getScalarType().getSizeInBits()=
 &&
-         "Mask size mismatches value type size!");
+void SelectionDAG::ComputeMaskedBits(SDValue Op, APInt &KnownZero,
+                                     APInt &KnownOne, unsigned Depth) cons=
t {
+  unsigned BitWidth =3D Op.getValueType().getScalarType().getSizeInBits();
=20
   KnownZero =3D KnownOne =3D APInt(BitWidth, 0);   // Don't know anything.
-  if (Depth =3D=3D 6 || Mask =3D=3D 0)
+  if (Depth =3D=3D 6)
     return;  // Limit search depth.
=20
   APInt KnownZero2, KnownOne2;
@@ -1623,14 +1650,13 @@
   switch (Op.getOpcode()) {
   case ISD::Constant:
     // We know all of the bits for a constant!
-    KnownOne =3D cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
-    KnownZero =3D ~KnownOne & Mask;
+    KnownOne =3D cast<ConstantSDNode>(Op)->getAPIntValue();
+    KnownZero =3D ~KnownOne;
     return;
   case ISD::AND:
     // If either the LHS or the RHS are Zero, the result is zero.
-    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1=
);
-    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
-                      KnownZero2, KnownOne2, Depth+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
=20
@@ -1640,9 +1666,8 @@
     KnownZero |=3D KnownZero2;
     return;
   case ISD::OR:
-    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1=
);
-    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
-                      KnownZero2, KnownOne2, Depth+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
=20
@@ -1652,8 +1677,8 @@
     KnownOne |=3D KnownOne2;
     return;
   case ISD::XOR: {
-    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1=
);
-    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth=
+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
=20
@@ -1665,9 +1690,8 @@
     return;
   }
   case ISD::MUL: {
-    APInt Mask2 =3D APInt::getAllOnesValue(BitWidth);
-    ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+=
1);
-    ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Dept=
h+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
=20
@@ -1686,33 +1710,29 @@
     LeadZ =3D std::min(LeadZ, BitWidth);
     KnownZero =3D APInt::getLowBitsSet(BitWidth, TrailZ) |
                 APInt::getHighBitsSet(BitWidth, LeadZ);
-    KnownZero &=3D Mask;
     return;
   }
   case ISD::UDIV: {
     // For the purposes of computing leading zeros we can conservatively
     // treat a udiv as a logical right shift by the power of 2 known to
     // be less than the denominator.
-    APInt AllOnes =3D APInt::getAllOnesValue(BitWidth);
-    ComputeMaskedBits(Op.getOperand(0),
-                      AllOnes, KnownZero2, KnownOne2, Depth+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
     unsigned LeadZ =3D KnownZero2.countLeadingOnes();
=20
     KnownOne2.clearAllBits();
     KnownZero2.clearAllBits();
-    ComputeMaskedBits(Op.getOperand(1),
-                      AllOnes, KnownZero2, KnownOne2, Depth+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
     unsigned RHSUnknownLeadingOnes =3D KnownOne2.countLeadingZeros();
     if (RHSUnknownLeadingOnes !=3D BitWidth)
       LeadZ =3D std::min(BitWidth,
                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
=20
-    KnownZero =3D APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
+    KnownZero =3D APInt::getHighBitsSet(BitWidth, LeadZ);
     return;
   }
   case ISD::SELECT:
-    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1=
);
-    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth=
+1);
+    ComputeMaskedBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
=20
@@ -1721,8 +1741,8 @@
     KnownZero &=3D KnownZero2;
     return;
   case ISD::SELECT_CC:
-    ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1=
);
-    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth=
+1);
+    ComputeMaskedBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
=20
@@ -1754,8 +1774,7 @@
       if (ShAmt >=3D BitWidth)
         return;
=20
-      ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
-                        KnownZero, KnownOne, Depth+1);
+      ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
       assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND =
zero?");
       KnownZero <<=3D ShAmt;
       KnownOne  <<=3D ShAmt;
@@ -1772,13 +1791,12 @@
       if (ShAmt >=3D BitWidth)
         return;
=20
-      ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
-                        KnownZero, KnownOne, Depth+1);
+      ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
       assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND =
zero?");
       KnownZero =3D KnownZero.lshr(ShAmt);
       KnownOne  =3D KnownOne.lshr(ShAmt);
=20
-      APInt HighBits =3D APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
+      APInt HighBits =3D APInt::getHighBitsSet(BitWidth, ShAmt);
       KnownZero |=3D HighBits;  // High bits known zero.
     }
     return;
@@ -1790,15 +1808,11 @@
       if (ShAmt >=3D BitWidth)
         return;
=20
-      APInt InDemandedMask =3D (Mask << ShAmt);
       // If any of the demanded bits are produced by the sign extension, w=
e also
       // demand the input sign bit.
-      APInt HighBits =3D APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
-      if (HighBits.getBoolValue())
-        InDemandedMask |=3D APInt::getSignBit(BitWidth);
-
-      ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, Known=
One,
-                        Depth+1);
+      APInt HighBits =3D APInt::getHighBitsSet(BitWidth, ShAmt);
+
+      ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
       assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND =
zero?");
       KnownZero =3D KnownZero.lshr(ShAmt);
       KnownOne  =3D KnownOne.lshr(ShAmt);
@@ -1820,10 +1834,10 @@
=20
     // Sign extension.  Compute the demanded bits in the result that are n=
ot
     // present in the input.
-    APInt NewBits =3D APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & =
Mask;
+    APInt NewBits =3D APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
=20
     APInt InSignBit =3D APInt::getSignBit(EBits);
-    APInt InputDemandedBits =3D Mask & APInt::getLowBitsSet(BitWidth, EBit=
s);
+    APInt InputDemandedBits =3D APInt::getLowBitsSet(BitWidth, EBits);
=20
     // If the sign extended bits are demanded, we know that the sign
     // bit is demanded.
@@ -1831,8 +1845,9 @@
     if (NewBits.getBoolValue())
       InputDemandedBits |=3D InSignBit;
=20
-    ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
-                      KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
+    KnownOne &=3D InputDemandedBits;
+    KnownZero &=3D InputDemandedBits;
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
=20
     // If the sign bit of the input is known set or clear, then we know the
@@ -1850,7 +1865,9 @@
     return;
   }
   case ISD::CTTZ:
+  case ISD::CTTZ_ZERO_UNDEF:
   case ISD::CTLZ:
+  case ISD::CTLZ_ZERO_UNDEF:
   case ISD::CTPOP: {
     unsigned LowBits =3D Log2_32(BitWidth)+1;
     KnownZero =3D APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
@@ -1858,22 +1875,23 @@
     return;
   }
   case ISD::LOAD: {
+    LoadSDNode *LD =3D cast<LoadSDNode>(Op);
     if (ISD::isZEXTLoad(Op.getNode())) {
-      LoadSDNode *LD =3D cast<LoadSDNode>(Op);
       EVT VT =3D LD->getMemoryVT();
       unsigned MemBits =3D VT.getScalarType().getSizeInBits();
-      KnownZero |=3D APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) &=
 Mask;
+      KnownZero |=3D APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
+    } else if (const MDNode *Ranges =3D LD->getRanges()) {
+      computeMaskedBitsLoad(*Ranges, KnownZero);
     }
     return;
   }
   case ISD::ZERO_EXTEND: {
     EVT InVT =3D Op.getOperand(0).getValueType();
     unsigned InBits =3D InVT.getScalarType().getSizeInBits();
-    APInt NewBits   =3D APInt::getHighBitsSet(BitWidth, BitWidth - InBits)=
 & Mask;
-    APInt InMask    =3D Mask.trunc(InBits);
+    APInt NewBits   =3D APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
     KnownZero =3D KnownZero.trunc(InBits);
     KnownOne =3D KnownOne.trunc(InBits);
-    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth=
+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
     KnownZero =3D KnownZero.zext(BitWidth);
     KnownOne =3D KnownOne.zext(BitWidth);
     KnownZero |=3D NewBits;
@@ -1883,17 +1901,11 @@
     EVT InVT =3D Op.getOperand(0).getValueType();
     unsigned InBits =3D InVT.getScalarType().getSizeInBits();
     APInt InSignBit =3D APInt::getSignBit(InBits);
-    APInt NewBits   =3D APInt::getHighBitsSet(BitWidth, BitWidth - InBits)=
 & Mask;
-    APInt InMask =3D Mask.trunc(InBits);
-
-    // If any of the sign extended bits are demanded, we know that the sign
-    // bit is demanded. Temporarily set this bit in the mask for our calle=
e.
-    if (NewBits.getBoolValue())
-      InMask |=3D InSignBit;
+    APInt NewBits   =3D APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
=20
     KnownZero =3D KnownZero.trunc(InBits);
     KnownOne =3D KnownOne.trunc(InBits);
-    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth=
+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
=20
     // Note if the sign bit is known to be zero or one.
     bool SignBitKnownZero =3D KnownZero.isNegative();
@@ -1901,13 +1913,6 @@
     assert(!(SignBitKnownZero && SignBitKnownOne) &&
            "Sign bit can't be known to be both zero and one!");
=20
-    // If the sign bit wasn't actually demanded by our caller, we don't
-    // want it set in the KnownZero and KnownOne result values. Reset the
-    // mask and reapply it to the result values.
-    InMask =3D Mask.trunc(InBits);
-    KnownZero &=3D InMask;
-    KnownOne  &=3D InMask;
-
     KnownZero =3D KnownZero.zext(BitWidth);
     KnownOne =3D KnownOne.zext(BitWidth);
=20
@@ -1921,10 +1926,9 @@
   case ISD::ANY_EXTEND: {
     EVT InVT =3D Op.getOperand(0).getValueType();
     unsigned InBits =3D InVT.getScalarType().getSizeInBits();
-    APInt InMask =3D Mask.trunc(InBits);
     KnownZero =3D KnownZero.trunc(InBits);
     KnownOne =3D KnownOne.trunc(InBits);
-    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth=
+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
     KnownZero =3D KnownZero.zext(BitWidth);
     KnownOne =3D KnownOne.zext(BitWidth);
     return;
@@ -1932,10 +1936,9 @@
   case ISD::TRUNCATE: {
     EVT InVT =3D Op.getOperand(0).getValueType();
     unsigned InBits =3D InVT.getScalarType().getSizeInBits();
-    APInt InMask =3D Mask.zext(InBits);
     KnownZero =3D KnownZero.zext(InBits);
     KnownOne =3D KnownOne.zext(InBits);
-    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth=
+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     KnownZero =3D KnownZero.trunc(BitWidth);
     KnownOne =3D KnownOne.trunc(BitWidth);
@@ -1944,9 +1947,8 @@
   case ISD::AssertZext: {
     EVT VT =3D cast<VTSDNode>(Op.getOperand(1))->getVT();
     APInt InMask =3D APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
-    ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
-                      KnownOne, Depth+1);
-    KnownZero |=3D (~InMask) & Mask;
+    ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
+    KnownZero |=3D (~InMask);
     return;
   }
   case ISD::FGETSIGN:
@@ -1963,8 +1965,7 @@
         unsigned NLZ =3D (CLHS->getAPIntValue()+1).countLeadingZeros();
         // NLZ can't be BitWidth with no sign bit
         APInt MaskV =3D APInt::getHighBitsSet(BitWidth, NLZ+1);
-        ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
-                          Depth+1);
+        ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1=
);
=20
         // If all of the MaskV bits are known to be zero, then we know the
         // output top bits are zero, because we now know that the output is
@@ -1972,7 +1973,7 @@
         if ((KnownZero2 & MaskV) =3D=3D MaskV) {
           unsigned NLZ2 =3D CLHS->getAPIntValue().countLeadingZeros();
           // Top bits known zero.
-          KnownZero =3D APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
+          KnownZero =3D APInt::getHighBitsSet(BitWidth, NLZ2);
         }
       }
     }
@@ -1983,13 +1984,11 @@
     // Output known-0 bits are known if clear or set in both the low clear=
 bits
     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have t=
he
     // low 3 bits clear.
-    APInt Mask2 =3D APInt::getLowBitsSet(BitWidth,
-                                       BitWidth - Mask.countLeadingZeros()=
);
-    ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Dept=
h+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
     unsigned KnownZeroOut =3D KnownZero2.countTrailingOnes();
=20
-    ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Dept=
h+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
     KnownZeroOut =3D std::min(KnownZeroOut,
                             KnownZero2.countTrailingOnes());
@@ -2013,7 +2012,7 @@
       if (RA.isPowerOf2()) {
         APInt LowBits =3D RA - 1;
         APInt Mask2 =3D LowBits | APInt::getSignBit(BitWidth);
-        ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Dep=
th+1);
+        ComputeMaskedBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1);
=20
         // The low bits of the first operand are unchanged by the srem.
         KnownZero =3D KnownZero2 & LowBits;
@@ -2028,10 +2027,6 @@
         // the upper bits are all one.
         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) !=3D 0))
           KnownOne |=3D ~LowBits;
-
-        KnownZero &=3D Mask;
-        KnownOne &=3D Mask;
-
         assert((KnownZero & KnownOne) =3D=3D 0&&"Bits known to be one AND =
zero?");
       }
     }
@@ -2041,9 +2036,8 @@
       const APInt &RA =3D Rem->getAPIntValue();
       if (RA.isPowerOf2()) {
         APInt LowBits =3D (RA - 1);
-        APInt Mask2 =3D LowBits & Mask;
-        KnownZero |=3D ~LowBits & Mask;
-        ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Dep=
th+1);
+        KnownZero |=3D ~LowBits;
+        ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne,Depth+1);
         assert((KnownZero & KnownOne) =3D=3D 0&&"Bits known to be one AND =
zero?");
         break;
       }
@@ -2051,16 +2045,13 @@
=20
     // Since the result is less than or equal to either operand, any leadi=
ng
     // zero bits in either operand must also exist in the result.
-    APInt AllOnes =3D APInt::getAllOnesValue(BitWidth);
-    ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
-                      Depth+1);
-    ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
-                      Depth+1);
+    ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
+    ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
=20
     uint32_t Leaders =3D std::max(KnownZero.countLeadingOnes(),
                                 KnownZero2.countLeadingOnes());
     KnownOne.clearAllBits();
-    KnownZero =3D APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
+    KnownZero =3D APInt::getHighBitsSet(BitWidth, Leaders);
     return;
   }
   case ISD::FrameIndex:
@@ -2080,8 +2071,7 @@
   case ISD::INTRINSIC_W_CHAIN:
   case ISD::INTRINSIC_VOID:
     // Allow the target to implement this method for its nodes.
-    TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *thi=
s,
-                                       Depth);
+    TLI.computeMaskedBitsForTargetNode(Op, KnownZero, KnownOne, *this, Dep=
th);
     return;
   }
 }
@@ -2205,12 +2195,11 @@
     if (ConstantSDNode *CRHS =3D dyn_cast<ConstantSDNode>(Op.getOperand(1)=
))
       if (CRHS->isAllOnesValue()) {
         APInt KnownZero, KnownOne;
-        APInt Mask =3D APInt::getAllOnesValue(VTBits);
-        ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Dep=
th+1);
+        ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
=20
         // If the input is known to be 0 or 1, the output is 0/-1, which i=
s all
         // sign bits set.
-        if ((KnownZero | APInt(VTBits, 1)) =3D=3D Mask)
+        if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
           return VTBits;
=20
         // If we are subtracting one from a positive number, there is no c=
arry
@@ -2221,8 +2210,7 @@
=20
     Tmp2 =3D ComputeNumSignBits(Op.getOperand(1), Depth+1);
     if (Tmp2 =3D=3D 1) return 1;
-      return std::min(Tmp, Tmp2)-1;
-    break;
+    return std::min(Tmp, Tmp2)-1;
=20
   case ISD::SUB:
     Tmp2 =3D ComputeNumSignBits(Op.getOperand(1), Depth+1);
@@ -2232,11 +2220,10 @@
     if (ConstantSDNode *CLHS =3D dyn_cast<ConstantSDNode>(Op.getOperand(0)=
))
       if (CLHS->isNullValue()) {
         APInt KnownZero, KnownOne;
-        APInt Mask =3D APInt::getAllOnesValue(VTBits);
-        ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Dep=
th+1);
+        ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
         // If the input is known to be 0 or 1, the output is 0/-1, which i=
s all
         // sign bits set.
-        if ((KnownZero | APInt(VTBits, 1)) =3D=3D Mask)
+        if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
           return VTBits;
=20
         // If the input is known to be positive (the sign bit is known cle=
ar),
@@ -2251,8 +2238,7 @@
     // is, at worst, one more bit than the inputs.
     Tmp =3D ComputeNumSignBits(Op.getOperand(0), Depth+1);
     if (Tmp =3D=3D 1) return 1;  // Early out.
-      return std::min(Tmp, Tmp2)-1;
-    break;
+    return std::min(Tmp, Tmp2)-1;
   case ISD::TRUNCATE:
     // FIXME: it's tricky to do anything useful for this, but it is an imp=
ortant
     // case for targets like X86.
@@ -2286,9 +2272,9 @@
   // Finally, if we can prove that the top bits of the result are 0's or 1=
's,
   // use this information.
   APInt KnownZero, KnownOne;
-  APInt Mask =3D APInt::getAllOnesValue(VTBits);
-  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
-
+  ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
+
+  APInt Mask;
   if (KnownZero.isNegative()) {        // sign bit is 0
     Mask =3D KnownZero;
   } else if (KnownOne.isNegative()) {  // sign bit is 1;
@@ -2328,7 +2314,7 @@
=20
 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
   // If we're told that NaNs won't happen, assume they won't.
-  if (NoNaNsFPMath)
+  if (getTarget().Options.NoNaNsFPMath)
     return true;
=20
   // If the value is a constant, we can obviously see if it is a NaN or no=
t.
@@ -2423,8 +2409,10 @@
     case ISD::CTPOP:
       return getConstant(Val.countPopulation(), VT);
     case ISD::CTLZ:
+    case ISD::CTLZ_ZERO_UNDEF:
       return getConstant(Val.countLeadingZeros(), VT);
     case ISD::CTTZ:
+    case ISD::CTTZ_ZERO_UNDEF:
       return getConstant(Val.countTrailingZeros(), VT);
     }
   }
@@ -2440,7 +2428,6 @@
       case ISD::FABS:
         V.clearSign();
         return getConstantFP(V, VT);
-      case ISD::FP_ROUND:
       case ISD::FP_EXTEND: {
         bool ignored;
         // This can return overflow, underflow, or inexact; we don't care.
@@ -2561,17 +2548,18 @@
            "Vector element count mismatch!");
     if (OpOpcode =3D=3D ISD::TRUNCATE)
       return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(=
0));
-    else if (OpOpcode =3D=3D ISD::ZERO_EXTEND || OpOpcode =3D=3D ISD::SIGN=
_EXTEND ||
-             OpOpcode =3D=3D ISD::ANY_EXTEND) {
+    if (OpOpcode =3D=3D ISD::ZERO_EXTEND || OpOpcode =3D=3D ISD::SIGN_EXTE=
ND ||
+        OpOpcode =3D=3D ISD::ANY_EXTEND) {
       // If the source is smaller than the dest, we still need an extend.
       if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
             .bitsLT(VT.getScalarType()))
         return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
-      else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
+      if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
         return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperan=
d(0));
-      else
-        return Operand.getNode()->getOperand(0);
+      return Operand.getNode()->getOperand(0);
     }
+    if (OpOpcode =3D=3D ISD::UNDEF)
+      return getUNDEF(VT);
     break;
   case ISD::BITCAST:
     // Basic sanity checking.
@@ -2601,7 +2589,7 @@
     break;
   case ISD::FNEG:
     // -(X-Y) -> (Y-X) is unsafe because when X=3D=3DY, -0.0 !=3D +0.0
-    if (UnsafeFPMath && OpOpcode =3D=3D ISD::FSUB)
+    if (getTarget().Options.UnsafeFPMath && OpOpcode =3D=3D ISD::FSUB)
       return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
                      Operand.getNode()->getOperand(0));
     if (OpOpcode =3D=3D ISD::FNEG)  // --X -> X
@@ -2736,7 +2724,7 @@
   case ISD::FMUL:
   case ISD::FDIV:
   case ISD::FREM:
-    if (UnsafeFPMath) {
+    if (getTarget().Options.UnsafeFPMath) {
       if (Opcode =3D=3D ISD::FADD) {
         // 0+x --> x
         if (ConstantFPSDNode *CFP =3D dyn_cast<ConstantFPSDNode>(N1))
@@ -3005,6 +2993,16 @@
       default: break;
       }
     }
+
+    if (Opcode =3D=3D ISD::FP_ROUND) {
+      APFloat V =3D N1CFP->getValueAPF();    // make copy
+      bool ignored;
+      // This can return overflow, underflow, or inexact; we don't care.
+      // FIXME need to be more flexible about rounding mode.
+      (void)V.convert(*EVTToAPFloatSemantics(VT),
+                      APFloat::rmNearestTiesToEven, &ignored);
+      return getConstantFP(V, VT);
+    }
   }
=20
   // Canonicalize an UNDEF to the RHS, even over a constant.
@@ -3059,7 +3057,7 @@
     case ISD::FMUL:
     case ISD::FDIV:
     case ISD::FREM:
-      if (UnsafeFPMath)
+      if (getTarget().Options.UnsafeFPMath)
         return N2;
       break;
     case ISD::MUL:
@@ -3133,16 +3131,14 @@
   case ISD::SELECT:
     if (N1C) {
      if (N1C->getZExtValue())
-        return N2;             // select true, X, Y -> X
-      else
-        return N3;             // select false, X, Y -> Y
+       return N2;             // select true, X, Y -> X
+     return N3;             // select false, X, Y -> Y
     }
=20
     if (N2 =3D=3D N3) return N2;   // select C, X, X -> X
     break;
   case ISD::VECTOR_SHUFFLE:
     llvm_unreachable("should use getVectorShuffle constructor!");
-    break;
   case ISD::INSERT_SUBVECTOR: {
     SDValue Index =3D N3;
     if (VT.isSimple() && N1.getValueType().isSimple()
@@ -3275,8 +3271,7 @@
 /// used when a memcpy is turned into a memset when the source is a consta=
nt
 /// string ptr.
 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
-                                  const TargetLowering &TLI,
-                                  std::string &Str, unsigned Offset) {
+                                  const TargetLowering &TLI, StringRef Str=
) {
   // Handle vector with all elements zero.
   if (Str.empty()) {
     if (VT.isInteger())
@@ -3294,15 +3289,18 @@
   }
=20
   assert(!VT.isVector() && "Can't handle vector type here!");
-  unsigned NumBits =3D VT.getSizeInBits();
-  unsigned MSB =3D NumBits / 8;
+  unsigned NumVTBytes =3D VT.getSizeInBits() / 8;
+  unsigned NumBytes =3D std::min(NumVTBytes, unsigned(Str.size()));
+
   uint64_t Val =3D 0;
-  if (TLI.isLittleEndian())
-    Offset =3D Offset + MSB - 1;
-  for (unsigned i =3D 0; i !=3D MSB; ++i) {
-    Val =3D (Val << 8) | (unsigned char)Str[Offset];
-    Offset +=3D TLI.isLittleEndian() ? -1 : 1;
+  if (TLI.isLittleEndian()) {
+    for (unsigned i =3D 0; i !=3D NumBytes; ++i)
+      Val |=3D (uint64_t)(unsigned char)Str[i] << i*8;
+  } else {
+    for (unsigned i =3D 0; i !=3D NumBytes; ++i)
+      Val |=3D (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
   }
+
   return DAG.getConstant(Val, VT);
 }
=20
@@ -3317,7 +3315,7 @@
=20
 /// isMemSrcFromString - Returns true if memcpy source is a string constan=
t.
 ///
-static bool isMemSrcFromString(SDValue Src, std::string &Str) {
+static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
   unsigned SrcDelta =3D 0;
   GlobalAddressSDNode *G =3D NULL;
   if (Src.getOpcode() =3D=3D ISD::GlobalAddress)
@@ -3331,11 +3329,7 @@
   if (!G)
     return false;
=20
-  const GlobalVariable *GV =3D dyn_cast<GlobalVariable>(G->getGlobal());
-  if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
-    return true;
-
-  return false;
+  return getConstantStringInfo(G->getGlobal(), Str, SrcDelta, false);
 }
=20
 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
@@ -3345,7 +3339,7 @@
 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
                                      unsigned Limit, uint64_t Size,
                                      unsigned DstAlign, unsigned SrcAlign,
-                                     bool NonScalarIntSafe,
+                                     bool IsZeroVal,
                                      bool MemcpyStrSrc,
                                      SelectionDAG &DAG,
                                      const TargetLowering &TLI) {
@@ -3359,7 +3353,7 @@
   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it =
does
   // not need to be loaded.
   EVT VT =3D TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
-                                   NonScalarIntSafe, MemcpyStrSrc,
+                                   IsZeroVal, MemcpyStrSrc,
                                    DAG.getMachineFunction());
=20
   if (VT =3D=3D MVT::Other) {
@@ -3438,7 +3432,7 @@
   unsigned SrcAlign =3D DAG.InferPtrAlignment(Src);
   if (Align > SrcAlign)
     SrcAlign =3D Align;
-  std::string Str;
+  StringRef Str;
   bool CopyFromStr =3D isMemSrcFromString(Src, Str);
   bool isZeroStr =3D CopyFromStr && Str.empty();
   unsigned Limit =3D AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSiz=
e);
@@ -3475,7 +3469,7 @@
       // We only handle zero vectors here.
       // FIXME: Handle other cases where store of vector immediate is done=
 in
       // a single instruction.
-      Value =3D getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
+      Value =3D getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
       Store =3D DAG.getStore(Chain, dl, Value,
                            getMemBasePlusOffset(Dst, DstOff, DAG),
                            DstPtrInfo.getWithOffset(DstOff), isVol,
@@ -3562,7 +3556,7 @@
     Value =3D DAG.getLoad(VT, dl, Chain,
                         getMemBasePlusOffset(Src, SrcOff, DAG),
                         SrcPtrInfo.getWithOffset(SrcOff), isVol,
-                        false, SrcAlign);
+                        false, false, SrcAlign);
     LoadValues.push_back(Value);
     LoadChains.push_back(Value.getValue(1));
     SrcOff +=3D VTSize;
@@ -3606,11 +3600,11 @@
   FrameIndexSDNode *FI =3D dyn_cast<FrameIndexSDNode>(Dst);
   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
     DstAlignCanChange =3D true;
-  bool NonScalarIntSafe =3D
+  bool IsZeroVal =3D
     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
                                 Size, (DstAlignCanChange ? 0 : Align), 0,
-                                NonScalarIntSafe, false, DAG, TLI))
+                                IsZeroVal, false, DAG, TLI))
     return SDValue();
=20
   if (DstAlignCanChange) {
@@ -3717,8 +3711,9 @@
   std::pair<SDValue,SDValue> CallResult =3D
     TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
                     false, false, false, false, 0,
-                    TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
-                    /*isReturnValueUsed=3D*/false,
+                    TLI.getLibcallCallingConv(RTLIB::MEMCPY),
+                    /*isTailCall=3D*/false,
+                    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/fal=
se,
                     getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
                                       TLI.getPointerTy()),
                     Args, *this, dl);
@@ -3769,8 +3764,9 @@
   std::pair<SDValue,SDValue> CallResult =3D
     TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
                     false, false, false, false, 0,
-                    TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
-                    /*isReturnValueUsed=3D*/false,
+                    TLI.getLibcallCallingConv(RTLIB::MEMMOVE),
+                    /*isTailCall=3D*/false,
+                    /*doesNotReturn=3D*/false, /*isReturnValueUsed=3D*/fal=
se,
                     getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
                                       TLI.getPointerTy()),
                     Args, *this, dl);
@@ -3829,8 +3825,9 @@
   std::pair<SDValue,SDValue> CallResult =3D
     TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
                     false, false, false, false, 0,
-                    TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
-                    /*isReturnValueUsed=3D*/false,
+                    TLI.getLibcallCallingConv(RTLIB::MEMSET),
+                    /*isTailCall=3D*/false,
+                    /*doesNotReturn*/false, /*isReturnValueUsed=3D*/false,
                     getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
                                       TLI.getPointerTy()),
                     Args, *this, dl);
@@ -4138,8 +4135,9 @@
                       EVT VT, DebugLoc dl, SDValue Chain,
                       SDValue Ptr, SDValue Offset,
                       MachinePointerInfo PtrInfo, EVT MemVT,
-                      bool isVolatile, bool isNonTemporal,
-                      unsigned Alignment, const MDNode *TBAAInfo) {
+                      bool isVolatile, bool isNonTemporal, bool isInvarian=
t,
+                      unsigned Alignment, const MDNode *TBAAInfo,
+                      const MDNode *Ranges) {
   assert(Chain.getValueType() =3D=3D MVT::Other &&=20
         "Invalid chain type");
   if (Alignment =3D=3D 0)  // Ensure that codegen never sees alignment 0
@@ -4150,6 +4148,8 @@
     Flags |=3D MachineMemOperand::MOVolatile;
   if (isNonTemporal)
     Flags |=3D MachineMemOperand::MONonTemporal;
+  if (isInvariant)
+    Flags |=3D MachineMemOperand::MOInvariant;
=20
   // If we don't have a PtrInfo, infer the trivial frame index case to sim=
plify
   // clients.
@@ -4159,7 +4159,7 @@
   MachineFunction &MF =3D getMachineFunction();
   MachineMemOperand *MMO =3D
     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignmen=
t,
-                            TBAAInfo);
+                            TBAAInfo, Ranges);
   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
 }
=20
@@ -4196,7 +4196,8 @@
   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
   ID.AddInteger(MemVT.getRawBits());
   ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
-                                     MMO->isNonTemporal()));
+                                     MMO->isNonTemporal(),=20
+                                     MMO->isInvariant()));
   void *IP =3D 0;
   if (SDNode *E =3D CSEMap.FindNodeOrInsertPos(ID, IP)) {
     cast<LoadSDNode>(E)->refineAlignment(MMO);
@@ -4213,10 +4214,13 @@
                               SDValue Chain, SDValue Ptr,
                               MachinePointerInfo PtrInfo,
                               bool isVolatile, bool isNonTemporal,
-                              unsigned Alignment, const MDNode *TBAAInfo) {
+                              bool isInvariant, unsigned Alignment,=20
+                              const MDNode *TBAAInfo,
+                              const MDNode *Ranges) {
   SDValue Undef =3D getUNDEF(Ptr.getValueType());
   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Und=
ef,
-                 PtrInfo, VT, isVolatile, isNonTemporal, Alignment, TBAAIn=
fo);
+                 PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alig=
nment,
+                 TBAAInfo, Ranges);
 }
=20
 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EV=
T VT,
@@ -4226,7 +4230,7 @@
                                  unsigned Alignment, const MDNode *TBAAInf=
o) {
   SDValue Undef =3D getUNDEF(Ptr.getValueType());
   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
-                 PtrInfo, MemVT, isVolatile, isNonTemporal, Alignment,
+                 PtrInfo, MemVT, isVolatile, isNonTemporal, false, Alignme=
nt,
                  TBAAInfo);
 }
=20
@@ -4239,8 +4243,8 @@
          "Load is already a indexed load!");
   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
-                 LD->getMemoryVT(),
-                 LD->isVolatile(), LD->isNonTemporal(), LD->getAlignment()=
);
+                 LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(),=20
+                 false, LD->getAlignment());
 }
=20
 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
@@ -4282,7 +4286,7 @@
   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
   ID.AddInteger(VT.getRawBits());
   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatil=
e(),
-                                     MMO->isNonTemporal()));
+                                     MMO->isNonTemporal(), MMO->isInvarian=
t()));
   void *IP =3D 0;
   if (SDNode *E =3D CSEMap.FindNodeOrInsertPos(ID, IP)) {
     cast<StoreSDNode>(E)->refineAlignment(MMO);
@@ -4349,7 +4353,7 @@
   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
   ID.AddInteger(SVT.getRawBits());
   ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile=
(),
-                                     MMO->isNonTemporal()));
+                                     MMO->isNonTemporal(), MMO->isInvarian=
t()));
   void *IP =3D 0;
   if (SDNode *E =3D CSEMap.FindNodeOrInsertPos(ID, IP)) {
     cast<StoreSDNode>(E)->refineAlignment(MMO);
@@ -4903,6 +4907,20 @@
   return N;
 }
=20
+/// UpdadeDebugLocOnMergedSDNode - If the opt level is -O0 then it throws =
away
+/// the line number information on the merged node since it is not possibl=
e to
+/// preserve the information that operation is associated with multiple li=
nes.
+/// This will make the debugger working better at -O0, were there is a hig=
her
+/// probability having other instructions associated with that line.
+///
+SDNode *SelectionDAG::UpdadeDebugLocOnMergedSDNode(SDNode *N, DebugLoc OLo=
c) {
+  DebugLoc NLoc =3D N->getDebugLoc();
+  if (!(NLoc.isUnknown()) && (OptLevel =3D=3D CodeGenOpt::None) && (OLoc !=
=3D NLoc)) {
+    N->setDebugLoc(DebugLoc());
+  }
+  return N;
+}
+
 /// MorphNodeTo - This *mutates* the specified node to have the specified
 /// return type, opcode, and operands.
 ///
@@ -4924,7 +4942,7 @@
     FoldingSetNodeID ID;
     AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
     if (SDNode *ON =3D CSEMap.FindNodeOrInsertPos(ID, IP))
-      return ON;
+      return UpdadeDebugLocOnMergedSDNode(ON, N->getDebugLoc());
   }
=20
   if (!RemoveNodeFromCSEMaps(N))
@@ -5128,8 +5146,9 @@
     FoldingSetNodeID ID;
     AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
     IP =3D 0;
-    if (SDNode *E =3D CSEMap.FindNodeOrInsertPos(ID, IP))
-      return cast<MachineSDNode>(E);
+    if (SDNode *E =3D CSEMap.FindNodeOrInsertPos(ID, IP)) {
+      return cast<MachineSDNode>(UpdadeDebugLocOnMergedSDNode(E, DL));
+    }
   }
=20
   // Allocate a new MachineSDNode.
@@ -5290,6 +5309,10 @@
     // already exists there, recursively merge the results together.
     AddModifiedNodeToCSEMaps(User, &Listener);
   }
+
+  // If we just RAUW'd the root, take note.
+  if (FromN =3D=3D getRoot())
+    setRoot(To);
 }
=20
 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
@@ -5335,6 +5358,10 @@
     // already exists there, recursively merge the results together.
     AddModifiedNodeToCSEMaps(User, &Listener);
   }
+
+  // If we just RAUW'd the root, take note.
+  if (From =3D=3D getRoot().getNode())
+    setRoot(SDValue(To, getRoot().getResNo()));
 }
=20
 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
@@ -5373,6 +5400,10 @@
     // already exists there, recursively merge the results together.
     AddModifiedNodeToCSEMaps(User, &Listener);
   }
+
+  // If we just RAUW'd the root, take note.
+  if (From =3D=3D getRoot().getNode())
+    setRoot(SDValue(To[getRoot().getResNo()]));
 }
=20
 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
@@ -5431,6 +5462,10 @@
     // already exists there, recursively merge the results together.
     AddModifiedNodeToCSEMaps(User, &Listener);
   }
+
+  // If we just RAUW'd the root, take note.
+  if (From =3D=3D getRoot())
+    setRoot(To);
 }
=20
 namespace {
@@ -5657,7 +5692,7 @@
                      MachineMemOperand *mmo)
  : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
   SubclassData =3D encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile=
(),
-                                      MMO->isNonTemporal());
+                                      MMO->isNonTemporal(), MMO->isInvaria=
nt());
   assert(isVolatile() =3D=3D MMO->isVolatile() && "Volatile encoding error=
!");
   assert(isNonTemporal() =3D=3D MMO->isNonTemporal() &&
          "Non-temporal encoding error!");
@@ -5670,7 +5705,7 @@
    : SDNode(Opc, dl, VTs, Ops, NumOps),
      MemoryVT(memvt), MMO(mmo) {
   SubclassData =3D encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile=
(),
-                                      MMO->isNonTemporal());
+                                      MMO->isNonTemporal(), MMO->isInvaria=
nt());
   assert(isVolatile() =3D=3D MMO->isVolatile() && "Volatile encoding error=
!");
   assert(memvt.getStoreSize() =3D=3D MMO->getSize() && "Size mismatch!");
 }
@@ -5846,565 +5881,6 @@
   return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
 }
=20
-std::string SDNode::getOperationName(const SelectionDAG *G) const {
-  switch (getOpcode()) {
-  default:
-    if (getOpcode() < ISD::BUILTIN_OP_END)
-      return "<<Unknown DAG Node>>";
-    if (isMachineOpcode()) {
-      if (G)
-        if (const TargetInstrInfo *TII =3D G->getTarget().getInstrInfo())
-          if (getMachineOpcode() < TII->getNumOpcodes())
-            return TII->get(getMachineOpcode()).getName();
-      return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
-    }
-    if (G) {
-      const TargetLowering &TLI =3D G->getTargetLoweringInfo();
-      const char *Name =3D TLI.getTargetNodeName(getOpcode());
-      if (Name) return Name;
-      return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
-    }
-    return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
-
-#ifndef NDEBUG
-  case ISD::DELETED_NODE:
-    return "<<Deleted Node!>>";
-#endif
-  case ISD::PREFETCH:      return "Prefetch";
-  case ISD::MEMBARRIER:    return "MemBarrier";
-  case ISD::ATOMIC_FENCE:    return "AtomicFence";
-  case ISD::ATOMIC_CMP_SWAP:    return "AtomicCmpSwap";
-  case ISD::ATOMIC_SWAP:        return "AtomicSwap";
-  case ISD::ATOMIC_LOAD_ADD:    return "AtomicLoadAdd";
-  case ISD::ATOMIC_LOAD_SUB:    return "AtomicLoadSub";
-  case ISD::ATOMIC_LOAD_AND:    return "AtomicLoadAnd";
-  case ISD::ATOMIC_LOAD_OR:     return "AtomicLoadOr";
-  case ISD::ATOMIC_LOAD_XOR:    return "AtomicLoadXor";
-  case ISD::ATOMIC_LOAD_NAND:   return "AtomicLoadNand";
-  case ISD::ATOMIC_LOAD_MIN:    return "AtomicLoadMin";
-  case ISD::ATOMIC_LOAD_MAX:    return "AtomicLoadMax";
-  case ISD::ATOMIC_LOAD_UMIN:   return "AtomicLoadUMin";
-  case ISD::ATOMIC_LOAD_UMAX:   return "AtomicLoadUMax";
-  case ISD::ATOMIC_LOAD:        return "AtomicLoad";
-  case ISD::ATOMIC_STORE:       return "AtomicStore";
-  case ISD::PCMARKER:      return "PCMarker";
-  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
-  case ISD::SRCVALUE:      return "SrcValue";
-  case ISD::MDNODE_SDNODE: return "MDNode";
-  case ISD::EntryToken:    return "EntryToken";
-  case ISD::TokenFactor:   return "TokenFactor";
-  case ISD::AssertSext:    return "AssertSext";
-  case ISD::AssertZext:    return "AssertZext";
-
-  case ISD::BasicBlock:    return "BasicBlock";
-  case ISD::VALUETYPE:     return "ValueType";
-  case ISD::Register:      return "Register";
-
-  case ISD::Constant:      return "Constant";
-  case ISD::ConstantFP:    return "ConstantFP";
-  case ISD::GlobalAddress: return "GlobalAddress";
-  case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
-  case ISD::FrameIndex:    return "FrameIndex";
-  case ISD::JumpTable:     return "JumpTable";
-  case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
-  case ISD::RETURNADDR: return "RETURNADDR";
-  case ISD::FRAMEADDR: return "FRAMEADDR";
-  case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
-  case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
-  case ISD::LSDAADDR: return "LSDAADDR";
-  case ISD::EHSELECTION: return "EHSELECTION";
-  case ISD::EH_RETURN: return "EH_RETURN";
-  case ISD::EH_SJLJ_SETJMP: return "EH_SJLJ_SETJMP";
-  case ISD::EH_SJLJ_LONGJMP: return "EH_SJLJ_LONGJMP";
-  case ISD::EH_SJLJ_DISPATCHSETUP: return "EH_SJLJ_DISPATCHSETUP";
-  case ISD::ConstantPool:  return "ConstantPool";
-  case ISD::ExternalSymbol: return "ExternalSymbol";
-  case ISD::BlockAddress:  return "BlockAddress";
-  case ISD::INTRINSIC_WO_CHAIN:
-  case ISD::INTRINSIC_VOID:
-  case ISD::INTRINSIC_W_CHAIN: {
-    unsigned OpNo =3D getOpcode() =3D=3D ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
-    unsigned IID =3D cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue(=
);
-    if (IID < Intrinsic::num_intrinsics)
-      return Intrinsic::getName((Intrinsic::ID)IID);
-    else if (const TargetIntrinsicInfo *TII =3D G->getTarget().getIntrinsi=
cInfo())
-      return TII->getName(IID);
-    llvm_unreachable("Invalid intrinsic ID");
-  }
-
-  case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
-  case ISD::TargetConstant: return "TargetConstant";
-  case ISD::TargetConstantFP:return "TargetConstantFP";
-  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
-  case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
-  case ISD::TargetFrameIndex: return "TargetFrameIndex";
-  case ISD::TargetJumpTable:  return "TargetJumpTable";
-  case ISD::TargetConstantPool:  return "TargetConstantPool";
-  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
-  case ISD::TargetBlockAddress: return "TargetBlockAddress";
-
-  case ISD::CopyToReg:     return "CopyToReg";
-  case ISD::CopyFromReg:   return "CopyFromReg";
-  case ISD::UNDEF:         return "undef";
-  case ISD::MERGE_VALUES:  return "merge_values";
-  case ISD::INLINEASM:     return "inlineasm";
-  case ISD::EH_LABEL:      return "eh_label";
-  case ISD::HANDLENODE:    return "handlenode";
-
-  // Unary operators
-  case ISD::FABS:   return "fabs";
-  case ISD::FNEG:   return "fneg";
-  case ISD::FSQRT:  return "fsqrt";
-  case ISD::FSIN:   return "fsin";
-  case ISD::FCOS:   return "fcos";
-  case ISD::FTRUNC: return "ftrunc";
-  case ISD::FFLOOR: return "ffloor";
-  case ISD::FCEIL:  return "fceil";
-  case ISD::FRINT:  return "frint";
-  case ISD::FNEARBYINT: return "fnearbyint";
-  case ISD::FEXP:   return "fexp";
-  case ISD::FEXP2:  return "fexp2";
-  case ISD::FLOG:   return "flog";
-  case ISD::FLOG2:  return "flog2";
-  case ISD::FLOG10: return "flog10";
-
-  // Binary operators
-  case ISD::ADD:    return "add";
-  case ISD::SUB:    return "sub";
-  case ISD::MUL:    return "mul";
-  case ISD::MULHU:  return "mulhu";
-  case ISD::MULHS:  return "mulhs";
-  case ISD::SDIV:   return "sdiv";
-  case ISD::UDIV:   return "udiv";
-  case ISD::SREM:   return "srem";
-  case ISD::UREM:   return "urem";
-  case ISD::SMUL_LOHI:  return "smul_lohi";
-  case ISD::UMUL_LOHI:  return "umul_lohi";
-  case ISD::SDIVREM:    return "sdivrem";
-  case ISD::UDIVREM:    return "udivrem";
-  case ISD::AND:    return "and";
-  case ISD::OR:     return "or";
-  case ISD::XOR:    return "xor";
-  case ISD::SHL:    return "shl";
-  case ISD::SRA:    return "sra";
-  case ISD::SRL:    return "srl";
-  case ISD::ROTL:   return "rotl";
-  case ISD::ROTR:   return "rotr";
-  case ISD::FADD:   return "fadd";
-  case ISD::FSUB:   return "fsub";
-  case ISD::FMUL:   return "fmul";
-  case ISD::FDIV:   return "fdiv";
-  case ISD::FMA:    return "fma";
-  case ISD::FREM:   return "frem";
-  case ISD::FCOPYSIGN: return "fcopysign";
-  case ISD::FGETSIGN:  return "fgetsign";
-  case ISD::FPOW:   return "fpow";
-
-  case ISD::FPOWI:  return "fpowi";
-  case ISD::SETCC:       return "setcc";
-  case ISD::SELECT:      return "select";
-  case ISD::VSELECT:     return "vselect";
-  case ISD::SELECT_CC:   return "select_cc";
-  case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
-  case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
-  case ISD::CONCAT_VECTORS:      return "concat_vectors";
-  case ISD::INSERT_SUBVECTOR:    return "insert_subvector";
-  case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
-  case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
-  case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
-  case ISD::CARRY_FALSE:         return "carry_false";
-  case ISD::ADDC:        return "addc";
-  case ISD::ADDE:        return "adde";
-  case ISD::SADDO:       return "saddo";
-  case ISD::UADDO:       return "uaddo";
-  case ISD::SSUBO:       return "ssubo";
-  case ISD::USUBO:       return "usubo";
-  case ISD::SMULO:       return "smulo";
-  case ISD::UMULO:       return "umulo";
-  case ISD::SUBC:        return "subc";
-  case ISD::SUBE:        return "sube";
-  case ISD::SHL_PARTS:   return "shl_parts";
-  case ISD::SRA_PARTS:   return "sra_parts";
-  case ISD::SRL_PARTS:   return "srl_parts";
-
-  // Conversion operators.
-  case ISD::SIGN_EXTEND: return "sign_extend";
-  case ISD::ZERO_EXTEND: return "zero_extend";
-  case ISD::ANY_EXTEND:  return "any_extend";
-  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
-  case ISD::TRUNCATE:    return "truncate";
-  case ISD::FP_ROUND:    return "fp_round";
-  case ISD::FLT_ROUNDS_: return "flt_rounds";
-  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
-  case ISD::FP_EXTEND:   return "fp_extend";
-
-  case ISD::SINT_TO_FP:  return "sint_to_fp";
-  case ISD::UINT_TO_FP:  return "uint_to_fp";
-  case ISD::FP_TO_SINT:  return "fp_to_sint";
-  case ISD::FP_TO_UINT:  return "fp_to_uint";
-  case ISD::BITCAST:     return "bitcast";
-  case ISD::FP16_TO_FP32: return "fp16_to_fp32";
-  case ISD::FP32_TO_FP16: return "fp32_to_fp16";
-
-  case ISD::CONVERT_RNDSAT: {
-    switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
-    default: llvm_unreachable("Unknown cvt code!");
-    case ISD::CVT_FF:  return "cvt_ff";
-    case ISD::CVT_FS:  return "cvt_fs";
-    case ISD::CVT_FU:  return "cvt_fu";
-    case ISD::CVT_SF:  return "cvt_sf";
-    case ISD::CVT_UF:  return "cvt_uf";
-    case ISD::CVT_SS:  return "cvt_ss";
-    case ISD::CVT_SU:  return "cvt_su";
-    case ISD::CVT_US:  return "cvt_us";
-    case ISD::CVT_UU:  return "cvt_uu";
-    }
-  }
-
-    // Control flow instructions
-  case ISD::BR:      return "br";
-  case ISD::BRIND:   return "brind";
-  case ISD::BR_JT:   return "br_jt";
-  case ISD::BRCOND:  return "brcond";
-  case ISD::BR_CC:   return "br_cc";
-  case ISD::CALLSEQ_START:  return "callseq_start";
-  case ISD::CALLSEQ_END:    return "callseq_end";
-
-    // Other operators
-  case ISD::LOAD:               return "load";
-  case ISD::STORE:              return "store";
-  case ISD::VAARG:              return "vaarg";
-  case ISD::VACOPY:             return "vacopy";
-  case ISD::VAEND:              return "vaend";
-  case ISD::VASTART:            return "vastart";
-  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
-  case ISD::EXTRACT_ELEMENT:    return "extract_element";
-  case ISD::BUILD_PAIR:         return "build_pair";
-  case ISD::STACKSAVE:          return "stacksave";
-  case ISD::STACKRESTORE:       return "stackrestore";
-  case ISD::TRAP:               return "trap";
-
-  // Bit manipulation
-  case ISD::BSWAP:   return "bswap";
-  case ISD::CTPOP:   return "ctpop";
-  case ISD::CTTZ:    return "cttz";
-  case ISD::CTLZ:    return "ctlz";
-
-  // Trampolines
-  case ISD::INIT_TRAMPOLINE: return "init_trampoline";
-  case ISD::ADJUST_TRAMPOLINE: return "adjust_trampoline";
-
-  case ISD::CONDCODE:
-    switch (cast<CondCodeSDNode>(this)->get()) {
-    default: llvm_unreachable("Unknown setcc condition!");
-    case ISD::SETOEQ:  return "setoeq";
-    case ISD::SETOGT:  return "setogt";
-    case ISD::SETOGE:  return "setoge";
-    case ISD::SETOLT:  return "setolt";
-    case ISD::SETOLE:  return "setole";
-    case ISD::SETONE:  return "setone";
-
-    case ISD::SETO:    return "seto";
-    case ISD::SETUO:   return "setuo";
-    case ISD::SETUEQ:  return "setue";
-    case ISD::SETUGT:  return "setugt";
-    case ISD::SETUGE:  return "setuge";
-    case ISD::SETULT:  return "setult";
-    case ISD::SETULE:  return "setule";
-    case ISD::SETUNE:  return "setune";
-
-    case ISD::SETEQ:   return "seteq";
-    case ISD::SETGT:   return "setgt";
-    case ISD::SETGE:   return "setge";
-    case ISD::SETLT:   return "setlt";
-    case ISD::SETLE:   return "setle";
-    case ISD::SETNE:   return "setne";
-    }
-  }
-}
-
-const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
-  switch (AM) {
-  default:
-    return "";
-  case ISD::PRE_INC:
-    return "<pre-inc>";
-  case ISD::PRE_DEC:
-    return "<pre-dec>";
-  case ISD::POST_INC:
-    return "<post-inc>";
-  case ISD::POST_DEC:
-    return "<post-dec>";
-  }
-}
-
-std::string ISD::ArgFlagsTy::getArgFlagsString() {
-  std::string S =3D "< ";
-
-  if (isZExt())
-    S +=3D "zext ";
-  if (isSExt())
-    S +=3D "sext ";
-  if (isInReg())
-    S +=3D "inreg ";
-  if (isSRet())
-    S +=3D "sret ";
-  if (isByVal())
-    S +=3D "byval ";
-  if (isNest())
-    S +=3D "nest ";
-  if (getByValAlign())
-    S +=3D "byval-align:" + utostr(getByValAlign()) + " ";
-  if (getOrigAlign())
-    S +=3D "orig-align:" + utostr(getOrigAlign()) + " ";
-  if (getByValSize())
-    S +=3D "byval-size:" + utostr(getByValSize()) + " ";
-  return S + ">";
-}
-
-void SDNode::dump() const { dump(0); }
-void SDNode::dump(const SelectionDAG *G) const {
-  print(dbgs(), G);
-  dbgs() << '\n';
-}
-
-void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
-  OS << (void*)this << ": ";
-
-  for (unsigned i =3D 0, e =3D getNumValues(); i !=3D e; ++i) {
-    if (i) OS << ",";
-    if (getValueType(i) =3D=3D MVT::Other)
-      OS << "ch";
-    else
-      OS << getValueType(i).getEVTString();
-  }
-  OS << " =3D " << getOperationName(G);
-}
-
-void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
-  if (const MachineSDNode *MN =3D dyn_cast<MachineSDNode>(this)) {
-    if (!MN->memoperands_empty()) {
-      OS << "<";
-      OS << "Mem:";
-      for (MachineSDNode::mmo_iterator i =3D MN->memoperands_begin(),
-           e =3D MN->memoperands_end(); i !=3D e; ++i) {
-        OS << **i;
-        if (llvm::next(i) !=3D e)
-          OS << " ";
-      }
-      OS << ">";
-    }
-  } else if (const ShuffleVectorSDNode *SVN =3D
-               dyn_cast<ShuffleVectorSDNode>(this)) {
-    OS << "<";
-    for (unsigned i =3D 0, e =3D ValueList[0].getVectorNumElements(); i !=
=3D e; ++i) {
-      int Idx =3D SVN->getMaskElt(i);
-      if (i) OS << ",";
-      if (Idx < 0)
-        OS << "u";
-      else
-        OS << Idx;
-    }
-    OS << ">";
-  } else if (const ConstantSDNode *CSDN =3D dyn_cast<ConstantSDNode>(this)=
) {
-    OS << '<' << CSDN->getAPIntValue() << '>';
-  } else if (const ConstantFPSDNode *CSDN =3D dyn_cast<ConstantFPSDNode>(t=
his)) {
-    if (&CSDN->getValueAPF().getSemantics()=3D=3D&APFloat::IEEEsingle)
-      OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
-    else if (&CSDN->getValueAPF().getSemantics()=3D=3D&APFloat::IEEEdouble)
-      OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
-    else {
-      OS << "<APFloat(";
-      CSDN->getValueAPF().bitcastToAPInt().dump();
-      OS << ")>";
-    }
-  } else if (const GlobalAddressSDNode *GADN =3D
-             dyn_cast<GlobalAddressSDNode>(this)) {
-    int64_t offset =3D GADN->getOffset();
-    OS << '<';
-    WriteAsOperand(OS, GADN->getGlobal());
-    OS << '>';
-    if (offset > 0)
-      OS << " + " << offset;
-    else
-      OS << " " << offset;
-    if (unsigned int TF =3D GADN->getTargetFlags())
-      OS << " [TF=3D" << TF << ']';
-  } else if (const FrameIndexSDNode *FIDN =3D dyn_cast<FrameIndexSDNode>(t=
his)) {
-    OS << "<" << FIDN->getIndex() << ">";
-  } else if (const JumpTableSDNode *JTDN =3D dyn_cast<JumpTableSDNode>(thi=
s)) {
-    OS << "<" << JTDN->getIndex() << ">";
-    if (unsigned int TF =3D JTDN->getTargetFlags())
-      OS << " [TF=3D" << TF << ']';
-  } else if (const ConstantPoolSDNode *CP =3D dyn_cast<ConstantPoolSDNode>=
(this)){
-    int offset =3D CP->getOffset();
-    if (CP->isMachineConstantPoolEntry())
-      OS << "<" << *CP->getMachineCPVal() << ">";
-    else
-      OS << "<" << *CP->getConstVal() << ">";
-    if (offset > 0)
-      OS << " + " << offset;
-    else
-      OS << " " << offset;
-    if (unsigned int TF =3D CP->getTargetFlags())
-      OS << " [TF=3D" << TF << ']';
-  } else if (const BasicBlockSDNode *BBDN =3D dyn_cast<BasicBlockSDNode>(t=
his)) {
-    OS << "<";
-    const Value *LBB =3D (const Value*)BBDN->getBasicBlock()->getBasicBloc=
k();
-    if (LBB)
-      OS << LBB->getName() << " ";
-    OS << (const void*)BBDN->getBasicBlock() << ">";
-  } else if (const RegisterSDNode *R =3D dyn_cast<RegisterSDNode>(this)) {
-    OS << ' ' << PrintReg(R->getReg(), G ? G->getTarget().getRegisterInfo(=
) :0);
-  } else if (const ExternalSymbolSDNode *ES =3D
-             dyn_cast<ExternalSymbolSDNode>(this)) {
-    OS << "'" << ES->getSymbol() << "'";
-    if (unsigned int TF =3D ES->getTargetFlags())
-      OS << " [TF=3D" << TF << ']';
-  } else if (const SrcValueSDNode *M =3D dyn_cast<SrcValueSDNode>(this)) {
-    if (M->getValue())
-      OS << "<" << M->getValue() << ">";
-    else
-      OS << "<null>";
-  } else if (const MDNodeSDNode *MD =3D dyn_cast<MDNodeSDNode>(this)) {
-    if (MD->getMD())
-      OS << "<" << MD->getMD() << ">";
-    else
-      OS << "<null>";
-  } else if (const VTSDNode *N =3D dyn_cast<VTSDNode>(this)) {
-    OS << ":" << N->getVT().getEVTString();
-  }
-  else if (const LoadSDNode *LD =3D dyn_cast<LoadSDNode>(this)) {
-    OS << "<" << *LD->getMemOperand();
-
-    bool doExt =3D true;
-    switch (LD->getExtensionType()) {
-    default: doExt =3D false; break;
-    case ISD::EXTLOAD: OS << ", anyext"; break;
-    case ISD::SEXTLOAD: OS << ", sext"; break;
-    case ISD::ZEXTLOAD: OS << ", zext"; break;
-    }
-    if (doExt)
-      OS << " from " << LD->getMemoryVT().getEVTString();
-
-    const char *AM =3D getIndexedModeName(LD->getAddressingMode());
-    if (*AM)
-      OS << ", " << AM;
-
-    OS << ">";
-  } else if (const StoreSDNode *ST =3D dyn_cast<StoreSDNode>(this)) {
-    OS << "<" << *ST->getMemOperand();
-
-    if (ST->isTruncatingStore())
-      OS << ", trunc to " << ST->getMemoryVT().getEVTString();
-
-    const char *AM =3D getIndexedModeName(ST->getAddressingMode());
-    if (*AM)
-      OS << ", " << AM;
-
-    OS << ">";
-  } else if (const MemSDNode* M =3D dyn_cast<MemSDNode>(this)) {
-    OS << "<" << *M->getMemOperand() << ">";
-  } else if (const BlockAddressSDNode *BA =3D
-               dyn_cast<BlockAddressSDNode>(this)) {
-    OS << "<";
-    WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
-    OS << ", ";
-    WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
-    OS << ">";
-    if (unsigned int TF =3D BA->getTargetFlags())
-      OS << " [TF=3D" << TF << ']';
-  }
-
-  if (G)
-    if (unsigned Order =3D G->GetOrdering(this))
-      OS << " [ORD=3D" << Order << ']';
-
-  if (getNodeId() !=3D -1)
-    OS << " [ID=3D" << getNodeId() << ']';
-
-  DebugLoc dl =3D getDebugLoc();
-  if (G && !dl.isUnknown()) {
-    DIScope
-      Scope(dl.getScope(G->getMachineFunction().getFunction()->getContext(=
)));
-    OS << " dbg:";
-    // Omit the directory, since it's usually long and uninteresting.
-    if (Scope.Verify())
-      OS << Scope.getFilename();
-    else
-      OS << "<unknown>";
-    OS << ':' << dl.getLine();
-    if (dl.getCol() !=3D 0)
-      OS << ':' << dl.getCol();
-  }
-}
-
-void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
-  print_types(OS, G);
-  for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i) {
-    if (i) OS << ", "; else OS << " ";
-    OS << (void*)getOperand(i).getNode();
-    if (unsigned RN =3D getOperand(i).getResNo())
-      OS << ":" << RN;
-  }
-  print_details(OS, G);
-}
-
-static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
-                                  const SelectionDAG *G, unsigned depth,
-                                  unsigned indent) {
-  if (depth =3D=3D 0)
-    return;
-
-  OS.indent(indent);
-
-  N->print(OS, G);
-
-  if (depth < 1)
-    return;
-
-  for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i) {
-    // Don't follow chain operands.
-    if (N->getOperand(i).getValueType() =3D=3D MVT::Other)
-      continue;
-    OS << '\n';
-    printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, inde=
nt+2);
-  }
-}
-
-void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
-                            unsigned depth) const {
-  printrWithDepthHelper(OS, this, G, depth, 0);
-}
-
-void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
-  // Don't print impossibly deep things.
-  printrWithDepth(OS, G, 10);
-}
-
-void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
-  printrWithDepth(dbgs(), G, depth);
-}
-
-void SDNode::dumprFull(const SelectionDAG *G) const {
-  // Don't print impossibly deep things.
-  dumprWithDepth(G, 10);
-}
-
-static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG=
 *G) {
-  for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i)
-    if (N->getOperand(i).getNode()->hasOneUse())
-      DumpNodes(N->getOperand(i).getNode(), indent+2, G);
-    else
-      dbgs() << "\n" << std::string(indent+2, ' ')
-           << (void*)N->getOperand(i).getNode() << ": <multiple use>";
-
-
-  dbgs() << "\n";
-  dbgs().indent(indent);
-  N->dump(G);
-}
-
 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
   assert(N->getNumValues() =3D=3D 1 &&
          "Can't unroll a vector with multiple results!");
@@ -6527,20 +6003,14 @@
   const GlobalValue *GV;
   int64_t GVOffset =3D 0;
   if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
-    // If GV has specified alignment, then use it. Otherwise, use the pref=
erred
-    // alignment.
-    unsigned Align =3D GV->getAlignment();
-    if (!Align) {
-      if (const GlobalVariable *GVar =3D dyn_cast<GlobalVariable>(GV)) {
-        if (GVar->hasInitializer()) {
-          const TargetData *TD =3D TLI.getTargetData();
-          Align =3D TD->getPreferredAlignment(GVar);
-        }
-      }
-      if (!Align)
-        Align =3D TLI.getTargetData()->getABITypeAlignment(GV->getType());
-    }
-    return MinAlign(Align, GVOffset);
+    unsigned PtrWidth =3D TLI.getPointerTy().getSizeInBits();
+    APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
+    llvm::ComputeMaskedBits(const_cast<GlobalValue*>(GV), KnownZero, Known=
One,
+                            TLI.getTargetData());
+    unsigned AlignBits =3D KnownZero.countTrailingOnes();
+    unsigned Align =3D AlignBits ? 1 << std::min(31U, AlignBits) : 0;
+    if (Align)
+      return MinAlign(Align, GVOffset);
   }
=20
   // If this is a direct reference to a stack slot, use information about =
the
@@ -6566,74 +6036,6 @@
   return 0;
 }
=20
-void SelectionDAG::dump() const {
-  dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
-
-  for (allnodes_const_iterator I =3D allnodes_begin(), E =3D allnodes_end(=
);
-       I !=3D E; ++I) {
-    const SDNode *N =3D I;
-    if (!N->hasOneUse() && N !=3D getRoot().getNode())
-      DumpNodes(N, 2, this);
-  }
-
-  if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
-
-  dbgs() << "\n\n";
-}
-
-void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
-  print_types(OS, G);
-  print_details(OS, G);
-}
-
-typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
-static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
-                       const SelectionDAG *G, VisitedSDNodeSet &once) {
-  if (!once.insert(N))          // If we've been here before, return now.
-    return;
-
-  // Dump the current SDNode, but don't end the line yet.
-  OS << std::string(indent, ' ');
-  N->printr(OS, G);
-
-  // Having printed this SDNode, walk the children:
-  for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i) {
-    const SDNode *child =3D N->getOperand(i).getNode();
-
-    if (i) OS << ",";
-    OS << " ";
-
-    if (child->getNumOperands() =3D=3D 0) {
-      // This child has no grandchildren; print it inline right here.
-      child->printr(OS, G);
-      once.insert(child);
-    } else {         // Just the address. FIXME: also print the child's op=
code.
-      OS << (void*)child;
-      if (unsigned RN =3D N->getOperand(i).getResNo())
-        OS << ":" << RN;
-    }
-  }
-
-  OS << "\n";
-
-  // Dump children that have grandchildren on their own line(s).
-  for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i) {
-    const SDNode *child =3D N->getOperand(i).getNode();
-    DumpNodesr(OS, child, indent+2, G, once);
-  }
-}
-
-void SDNode::dumpr() const {
-  VisitedSDNodeSet once;
-  DumpNodesr(dbgs(), this, 0, 0, once);
-}
-
-void SDNode::dumpr(const SelectionDAG *G) const {
-  VisitedSDNodeSet once;
-  DumpNodesr(dbgs(), this, 0, G, once);
-}
-
-
 // getAddressSpace - Return the address space this GlobalAddress belongs t=
o.
 unsigned GlobalAddressSDNode::getAddressSpace() const {
   return getGlobal()->getType()->getAddressSpace();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/SelectionDAGBuilder.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -41,13 +41,13 @@
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetFrameLowering.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetIntrinsicInfo.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Support/CommandLine.h"
@@ -197,7 +197,7 @@
     // FP_ROUND's are always exact here.
     if (ValueVT.bitsLT(Val.getValueType()))
       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
-                         DAG.getIntPtrConstant(1));
+                         DAG.getTargetConstant(1, TLI.getPointerTy()));
=20
     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
   }
@@ -206,7 +206,6 @@
     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
=20
   llvm_unreachable("Unknown mismatch!");
-  return SDValue();
 }
=20
 /// getCopyFromParts - Create a value that contains the specified legal pa=
rts
@@ -353,10 +352,13 @@
       assert(NumParts =3D=3D 1 && "Do not know what to promote to!");
       Val =3D DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
     } else {
-      assert(PartVT.isInteger() && ValueVT.isInteger() &&
+      assert((PartVT.isInteger() || PartVT =3D=3D MVT::x86mmx) &&
+             ValueVT.isInteger() &&
              "Unknown mismatch!");
       ValueVT =3D EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits=
);
       Val =3D DAG.getNode(ExtendKind, DL, ValueVT, Val);
+      if (PartVT =3D=3D MVT::x86mmx)
+        Val =3D DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
     }
   } else if (PartBits =3D=3D ValueVT.getSizeInBits()) {
     // Different types of the same size.
@@ -364,10 +366,13 @@
     Val =3D DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
     // If the parts cover less bits than value has, truncate the value.
-    assert(PartVT.isInteger() && ValueVT.isInteger() &&
+    assert((PartVT.isInteger() || PartVT =3D=3D MVT::x86mmx) &&
+           ValueVT.isInteger() &&
            "Unknown mismatch!");
     ValueVT =3D EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
     Val =3D DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
+    if (PartVT =3D=3D MVT::x86mmx)
+      Val =3D DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
   }
=20
   // The value may have changed - recompute ValueVT.
@@ -813,9 +818,11 @@
   }
 }
=20
-void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
+void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
+                               const TargetLibraryInfo *li) {
   AA =3D &aa;
   GFI =3D gfi;
+  LibInfo =3D li;
   TD =3D DAG.getTarget().getTargetData();
   LPadToCallSiteMap.clear();
 }
@@ -964,7 +971,7 @@
         DAG.AddDbgValue(SDV, Val.getNode(), false);
       }
     } else
-      DEBUG(dbgs() << "Dropping debug info for " << DI);
+      DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
     DanglingDebugInfoMap[V] =3D DanglingDebugInfo();
   }
 }
@@ -1054,6 +1061,23 @@
       return DAG.getMergeValues(&Constants[0], Constants.size(),
                                 getCurDebugLoc());
     }
+   =20
+    if (const ConstantDataSequential *CDS =3D
+          dyn_cast<ConstantDataSequential>(C)) {
+      SmallVector<SDValue, 4> Ops;
+      for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i) {
+        SDNode *Val =3D getValue(CDS->getElementAsConstant(i)).getNode();
+        // Add each leaf value from the operand to the Constants list
+        // to form a flattened list of all the values.
+        for (unsigned i =3D 0, e =3D Val->getNumValues(); i !=3D e; ++i)
+          Ops.push_back(SDValue(Val, i));
+      }
+
+      if (isa<ArrayType>(CDS->getType()))
+        return DAG.getMergeValues(&Ops[0], Ops.size(), getCurDebugLoc());
+      return NodeMap[V] =3D DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(=
),
+                                      VT, &Ops[0], Ops.size());
+    }
=20
     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
@@ -1088,9 +1112,9 @@
     // Now that we know the number and type of the elements, get that numb=
er of
     // elements into the Ops array based on what kind of constant it is.
     SmallVector<SDValue, 16> Ops;
-    if (const ConstantVector *CP =3D dyn_cast<ConstantVector>(C)) {
+    if (const ConstantVector *CV =3D dyn_cast<ConstantVector>(C)) {
       for (unsigned i =3D 0; i !=3D NumElements; ++i)
-        Ops.push_back(getValue(CP->getOperand(i)));
+        Ops.push_back(getValue(CV->getOperand(i)));
     } else {
       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
       EVT EltVT =3D TLI.getValueType(VecTy->getElementType());
@@ -1126,7 +1150,6 @@
   }
=20
   llvm_unreachable("Can't get register for value!");
-  return SDValue();
 }
=20
 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
@@ -1285,8 +1308,8 @@
 }
=20
 /// Return branch probability calculated by BranchProbabilityInfo for IR b=
locks.
-uint32_t SelectionDAGBuilder::getEdgeWeight(MachineBasicBlock *Src,
-                                            MachineBasicBlock *Dst) {
+uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
+                                            const MachineBasicBlock *Dst) =
const {
   BranchProbabilityInfo *BPI =3D FuncInfo.BPI;
   if (!BPI)
     return 0;
@@ -1336,6 +1359,8 @@
         Condition =3D getICmpCondCode(IC->getPredicate());
       } else if (const FCmpInst *FC =3D dyn_cast<FCmpInst>(Cond)) {
         Condition =3D getFCmpCondCode(FC->getPredicate());
+        if (TM.Options.NoNaNsFPMath)
+          Condition =3D getFCmpCodeWithoutNaN(Condition);
       } else {
         Condition =3D ISD::SETEQ; // silence warning.
         llvm_unreachable("Unknown compare instruction");
@@ -1811,8 +1836,8 @@
   CopyToExportRegsIfNeeded(&I);
=20
   // Update successor info
-  InvokeMBB->addSuccessor(Return);
-  InvokeMBB->addSuccessor(LandingPad);
+  addSuccessorWithWeight(InvokeMBB, Return);
+  addSuccessorWithWeight(InvokeMBB, LandingPad);
=20
   // Drop into normal successor.
   DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
@@ -1820,9 +1845,6 @@
                           DAG.getBasicBlock(Return)));
 }
=20
-void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
-}
-
 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instruction=
s!");
 }
@@ -1835,6 +1857,12 @@
   MachineModuleInfo &MMI =3D DAG.getMachineFunction().getMMI();
   AddLandingPadInfo(LP, MMI, MBB);
=20
+  // If there aren't registers to copy the values into (e.g., during SjLj
+  // exceptions), then don't bother to create these DAG nodes.
+  if (TLI.getExceptionPointerRegister() =3D=3D 0 &&
+      TLI.getExceptionSelectorRegister() =3D=3D 0)
+    return;
+
   SmallVector<EVT, 2> ValueVTs;
   ComputeValueVTs(TLI, LP.getType(), ValueVTs);
=20
@@ -2003,7 +2031,7 @@
 }
=20
 static inline bool areJTsAllowed(const TargetLowering &TLI) {
-  return !DisableJumpTables &&
+  return !TLI.getTargetMachine().Options.DisableJumpTables &&
           (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
            TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
 }
@@ -2190,7 +2218,7 @@
=20
   CaseRange LHSR(CR.Range.first, Pivot);
   CaseRange RHSR(Pivot, CR.Range.second);
-  Constant *C =3D Pivot->Low;
+  const Constant *C =3D Pivot->Low;
   MachineBasicBlock *FalseBB =3D 0, *TrueBB =3D 0;
=20
   // We know that we branch to the LHS if the Value being switched on is
@@ -2383,14 +2411,14 @@
=20
   BranchProbabilityInfo *BPI =3D FuncInfo.BPI;
   // Start with "simple" cases
-  for (size_t i =3D 1; i < SI.getNumSuccessors(); ++i) {
-    BasicBlock *SuccBB =3D SI.getSuccessor(i);
+  for (SwitchInst::ConstCaseIt i =3D SI.case_begin(), e =3D SI.case_end();
+       i !=3D e; ++i) {
+    const BasicBlock *SuccBB =3D i.getCaseSuccessor();
     MachineBasicBlock *SMBB =3D FuncInfo.MBBMap[SuccBB];
=20
     uint32_t ExtraWeight =3D BPI ? BPI->getEdgeWeight(SI.getParent(), Succ=
BB) : 0;
=20
-    Cases.push_back(Case(SI.getSuccessorValue(i),
-                         SI.getSuccessorValue(i),
+    Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
                          SMBB, ExtraWeight));
   }
   std::sort(Cases.begin(), Cases.end(), CaseCmp());
@@ -2457,7 +2485,7 @@
=20
   // If there is only the default destination, branch to it if it is not t=
he
   // next basic block.  Otherwise, just fall through.
-  if (SI.getNumCases() =3D=3D 1) {
+  if (!SI.getNumCases()) {
     // Update machine-CFG edges.
=20
     // If this is not a fall-through branch, emit the branch.
@@ -2626,6 +2654,8 @@
   SDValue Op1 =3D getValue(I.getOperand(0));
   SDValue Op2 =3D getValue(I.getOperand(1));
   ISD::CondCode Condition =3D getFCmpCondCode(predicate);
+  if (TM.Options.NoNaNsFPMath)
+    Condition =3D getFCmpCodeWithoutNaN(Condition);
   EVT DestVT =3D TLI.getValueType(I.getType());
   setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition)=
);
 }
@@ -2685,11 +2715,12 @@
   SDValue N =3D getValue(I.getOperand(0));
   EVT DestVT =3D TLI.getValueType(I.getType());
   setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
-                           DestVT, N, DAG.getIntPtrConstant(0)));
+                           DestVT, N,
+                           DAG.getTargetConstant(0, TLI.getPointerTy())));
 }
=20
 void SelectionDAGBuilder::visitFPExt(const User &I){
-  // FPTrunc is never a no-op cast, no need to check
+  // FPExt is never a no-op cast, no need to check
   SDValue N =3D getValue(I.getOperand(0));
   EVT DestVT =3D TLI.getValueType(I.getType());
   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
@@ -2772,33 +2803,25 @@
                            TLI.getValueType(I.getType()), InVec, InIdx));
 }
=20
-// Utility for visitShuffleVector - Returns true if the mask is mask start=
ing
-// from SIndx and increasing to the element length (undefs are allowed).
-static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
-  unsigned MaskNumElts =3D Mask.size();
-  for (unsigned i =3D 0; i !=3D MaskNumElts; ++i)
-    if ((Mask[i] >=3D 0) && (Mask[i] !=3D (int)(i + SIndx)))
+// Utility for visitShuffleVector - Return true if every element in Mask,
+// begining from position Pos and ending in Pos+Size, falls within the
+// specified sequential range [L, L+Pos). or is undef.
+static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
+                                unsigned Pos, unsigned Size, int Low) {
+  for (unsigned i =3D Pos, e =3D Pos+Size; i !=3D e; ++i, ++Low)
+    if (Mask[i] >=3D 0 && Mask[i] !=3D Low)
       return false;
   return true;
 }
=20
 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
-  SmallVector<int, 8> Mask;
   SDValue Src1 =3D getValue(I.getOperand(0));
   SDValue Src2 =3D getValue(I.getOperand(1));
=20
-  // Convert the ConstantVector mask operand into an array of ints, with -1
-  // representing undef values.
-  SmallVector<Constant*, 8> MaskElts;
-  cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
-  unsigned MaskNumElts =3D MaskElts.size();
-  for (unsigned i =3D 0; i !=3D MaskNumElts; ++i) {
-    if (isa<UndefValue>(MaskElts[i]))
-      Mask.push_back(-1);
-    else
-      Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
-  }
-
+  SmallVector<int, 8> Mask;
+  ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
+  unsigned MaskNumElts =3D Mask.size();
+ =20
   EVT VT =3D TLI.getValueType(I.getType());
   EVT SrcVT =3D Src1.getValueType();
   unsigned SrcNumElts =3D SrcVT.getVectorNumElements();
@@ -2814,11 +2837,23 @@
     // Mask is longer than the source vectors and is a multiple of the sou=
rce
     // vectors.  We can use concatenate vector to make the mask and vectors
     // lengths match.
-    if (SrcNumElts*2 =3D=3D MaskNumElts && SequentialMask(Mask, 0)) {
-      // The shuffle is concatenating two vectors together.
-      setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
-                               VT, Src1, Src2));
-      return;
+    if (SrcNumElts*2 =3D=3D MaskNumElts) {
+      // First check for Src1 in low and Src2 in high
+      if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
+          isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
+        // The shuffle is concatenating two vectors together.
+        setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
+                                 VT, Src1, Src2));
+        return;
+      }
+      // Then check for Src2 in low and Src1 in high
+      if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
+          isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
+        // The shuffle is concatenating two vectors together.
+        setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
+                                 VT, Src2, Src1));
+        return;
+      }
     }
=20
     // Pad both vectors with undefs to make them the same length as the ma=
sk.
@@ -2843,10 +2878,9 @@
     SmallVector<int, 8> MappedOps;
     for (unsigned i =3D 0; i !=3D MaskNumElts; ++i) {
       int Idx =3D Mask[i];
-      if (Idx < (int)SrcNumElts)
-        MappedOps.push_back(Idx);
-      else
-        MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
+      if (Idx >=3D (int)SrcNumElts)
+        Idx -=3D SrcNumElts - MaskNumElts;
+      MappedOps.push_back(Idx);
     }
=20
     setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
@@ -2858,13 +2892,13 @@
     // Analyze the access pattern of the vector to see if we can extract
     // two subvectors and do the shuffle. The analysis is done by calculat=
ing
     // the range of elements the mask access on both vectors.
-    int MinRange[2] =3D { static_cast<int>(SrcNumElts+1),
-                        static_cast<int>(SrcNumElts+1)};
+    int MinRange[2] =3D { static_cast<int>(SrcNumElts),
+                        static_cast<int>(SrcNumElts)};
     int MaxRange[2] =3D {-1, -1};
=20
     for (unsigned i =3D 0; i !=3D MaskNumElts; ++i) {
       int Idx =3D Mask[i];
-      int Input =3D 0;
+      unsigned Input =3D 0;
       if (Idx < 0)
         continue;
=20
@@ -2880,35 +2914,31 @@
=20
     // Check if the access is smaller than the vector size and can we find
     // a reasonable extract index.
-    int RangeUse[2] =3D { 2, 2 };  // 0 =3D Unused, 1 =3D Extract, 2 =3D C=
an not
-                                 // Extract.
+    int RangeUse[2] =3D { -1, -1 };  // 0 =3D Unused, 1 =3D Extract, -1 =
=3D Can not
+                                   // Extract.
     int StartIdx[2];  // StartIdx to extract from
-    for (int Input=3D0; Input < 2; ++Input) {
-      if (MinRange[Input] =3D=3D (int)(SrcNumElts+1) && MaxRange[Input] =
=3D=3D -1) {
+    for (unsigned Input =3D 0; Input < 2; ++Input) {
+      if (MinRange[Input] >=3D (int)SrcNumElts && MaxRange[Input] < 0) {
         RangeUse[Input] =3D 0; // Unused
         StartIdx[Input] =3D 0;
-      } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
-        // Fits within range but we should see if we can find a good
-        // start index that is a multiple of the mask length.
-        if (MaxRange[Input] < (int)MaskNumElts) {
-          RangeUse[Input] =3D 1; // Extract from beginning of the vector
-          StartIdx[Input] =3D 0;
-        } else {
-          StartIdx[Input] =3D (MinRange[Input]/MaskNumElts)*MaskNumElts;
-          if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
-              StartIdx[Input] + MaskNumElts <=3D SrcNumElts)
-            RangeUse[Input] =3D 1; // Extract from a multiple of the mask =
length.
-        }
+        continue;
       }
+
+      // Find a good start index that is a multiple of the mask length. Th=
en
+      // see if the rest of the elements are in range.
+      StartIdx[Input] =3D (MinRange[Input]/MaskNumElts)*MaskNumElts;
+      if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
+          StartIdx[Input] + MaskNumElts <=3D SrcNumElts)
+        RangeUse[Input] =3D 1; // Extract from a multiple of the mask leng=
th.
     }
=20
     if (RangeUse[0] =3D=3D 0 && RangeUse[1] =3D=3D 0) {
       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
       return;
     }
-    else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
+    if (RangeUse[0] >=3D 0 && RangeUse[1] >=3D 0) {
       // Extract appropriate subvector and generate a vector shuffle
-      for (int Input=3D0; Input < 2; ++Input) {
+      for (unsigned Input =3D 0; Input < 2; ++Input) {
         SDValue &Src =3D Input =3D=3D 0 ? Src1 : Src2;
         if (RangeUse[Input] =3D=3D 0)
           Src =3D DAG.getUNDEF(VT);
@@ -2921,12 +2951,13 @@
       SmallVector<int, 8> MappedOps;
       for (unsigned i =3D 0; i !=3D MaskNumElts; ++i) {
         int Idx =3D Mask[i];
-        if (Idx < 0)
-          MappedOps.push_back(Idx);
-        else if (Idx < (int)SrcNumElts)
-          MappedOps.push_back(Idx - StartIdx[0]);
-        else
-          MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts=
);
+        if (Idx >=3D 0) {
+          if (Idx < (int)SrcNumElts)
+            Idx -=3D StartIdx[0];
+          else
+            Idx -=3D SrcNumElts + StartIdx[1] - MaskNumElts;
+        }
+        MappedOps.push_back(Idx);
       }
=20
       setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
@@ -2942,22 +2973,20 @@
   EVT PtrVT =3D TLI.getPointerTy();
   SmallVector<SDValue,8> Ops;
   for (unsigned i =3D 0; i !=3D MaskNumElts; ++i) {
-    if (Mask[i] < 0) {
-      Ops.push_back(DAG.getUNDEF(EltVT));
+    int Idx =3D Mask[i];
+    SDValue Res;
+
+    if (Idx < 0) {
+      Res =3D DAG.getUNDEF(EltVT);
     } else {
-      int Idx =3D Mask[i];
-      SDValue Res;
-
-      if (Idx < (int)SrcNumElts)
-        Res =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
-                          EltVT, Src1, DAG.getConstant(Idx, PtrVT));
-      else
-        Res =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
-                          EltVT, Src2,
-                          DAG.getConstant(Idx - SrcNumElts, PtrVT));
-
-      Ops.push_back(Res);
+      SDValue &Src =3D Idx < (int)SrcNumElts ? Src1 : Src2;
+      if (Idx >=3D (int)SrcNumElts) Idx -=3D SrcNumElts;
+
+      Res =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
+                        EltVT, Src, DAG.getConstant(Idx, PtrVT));
     }
+
+    Ops.push_back(Res);
   }
=20
   setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
@@ -3042,7 +3071,9 @@
=20
 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
   SDValue N =3D getValue(I.getOperand(0));
-  Type *Ty =3D I.getOperand(0)->getType();
+  // Note that the pointer operand may be a vector of pointers. Take the s=
calar
+  // element which holds a pointer.
+  Type *Ty =3D I.getOperand(0)->getType()->getScalarType();
=20
   for (GetElementPtrInst::const_op_iterator OI =3D I.op_begin()+1, E =3D I=
.op_end();
        OI !=3D E; ++OI) {
@@ -3096,7 +3127,7 @@
           unsigned Amt =3D ElementSize.logBase2();
           IdxN =3D DAG.getNode(ISD::SHL, getCurDebugLoc(),
                              N.getValueType(), IdxN,
-                             DAG.getConstant(Amt, TLI.getPointerTy()));
+                             DAG.getConstant(Amt, IdxN.getValueType()));
         } else {
           SDValue Scale =3D DAG.getConstant(ElementSize, TLI.getPointerTy(=
));
           IdxN =3D DAG.getNode(ISD::MUL, getCurDebugLoc(),
@@ -3175,8 +3206,10 @@
=20
   bool isVolatile =3D I.isVolatile();
   bool isNonTemporal =3D I.getMetadata("nontemporal") !=3D 0;
+  bool isInvariant =3D I.getMetadata("invariant.load") !=3D 0;
   unsigned Alignment =3D I.getAlignment();
   const MDNode *TBAAInfo =3D I.getMetadata(LLVMContext::MD_tbaa);
+  const MDNode *Ranges =3D I.getMetadata(LLVMContext::MD_range);
=20
   SmallVector<EVT, 4> ValueVTs;
   SmallVector<uint64_t, 4> Offsets;
@@ -3224,7 +3257,8 @@
                             DAG.getConstant(Offsets[i], PtrVT));
     SDValue L =3D DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
                             A, MachinePointerInfo(SV, Offsets[i]), isVolat=
ile,
-                            isNonTemporal, Alignment, TBAAInfo);
+                            isNonTemporal, isInvariant, Alignment, TBAAInf=
o,
+                            Ranges);
=20
     Values[i] =3D L;
     Chains[ChainI] =3D L.getValue(1);
@@ -3358,7 +3392,7 @@
   DebugLoc dl =3D getCurDebugLoc();
   ISD::NodeType NT;
   switch (I.getOperation()) {
-  default: llvm_unreachable("Unknown atomicrmw operation"); return;
+  default: llvm_unreachable("Unknown atomicrmw operation");
   case AtomicRMWInst::Xchg: NT =3D ISD::ATOMIC_SWAP; break;
   case AtomicRMWInst::Add:  NT =3D ISD::ATOMIC_LOAD_ADD; break;
   case AtomicRMWInst::Sub:  NT =3D ISD::ATOMIC_LOAD_SUB; break;
@@ -3496,24 +3530,16 @@
   // Add the intrinsic ID as an integer operand if it's not a target intri=
nsic.
   if (!IsTgtIntrinsic || Info.opc =3D=3D ISD::INTRINSIC_VOID ||
       Info.opc =3D=3D ISD::INTRINSIC_W_CHAIN)
-    Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
+    Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
=20
   // Add all operands of the call to the operand list.
   for (unsigned i =3D 0, e =3D I.getNumArgOperands(); i !=3D e; ++i) {
     SDValue Op =3D getValue(I.getArgOperand(i));
-    assert(TLI.isTypeLegal(Op.getValueType()) &&
-           "Intrinsic uses a non-legal type?");
     Ops.push_back(Op);
   }
=20
   SmallVector<EVT, 4> ValueVTs;
   ComputeValueVTs(TLI, I.getType(), ValueVTs);
-#ifndef NDEBUG
-  for (unsigned Val =3D 0, E =3D ValueVTs.size(); Val !=3D E; ++Val) {
-    assert(TLI.isTypeLegal(ValueVTs[Val]) &&
-           "Intrinsic uses a non-legal type?");
-  }
-#endif // NDEBUG
=20
   if (HasChain)
     ValueVTs.push_back(MVT::Other);
@@ -3556,6 +3582,12 @@
     }
=20
     setValue(&I, Result);
+  } else {
+    // Assign order to result here. If the intrinsic does not produce a re=
sult,
+    // it won't be mapped to a SDNode and visit() will not assign it an or=
der
+    // number.
+    ++SDNodeOrder;
+    AssignOrderingToNode(Result.getNode());
   }
 }
=20
@@ -3597,17 +3629,6 @@
   return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
 }
=20
-// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
-const char *
-SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType=
 Op) {
-  SDValue Op1 =3D getValue(I.getArgOperand(0));
-  SDValue Op2 =3D getValue(I.getArgOperand(1));
-
-  SDVTList VTs =3D DAG.getVTList(Op1.getValueType(), MVT::i1);
-  setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
-  return 0;
-}
-
 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
 /// limited-precision mode.
 void
@@ -4367,9 +4388,8 @@
     const SDValue &CFR =3D Ext.getOperand(0);
     if (CFR.getOpcode() =3D=3D ISD::CopyFromReg)
       return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
-    else
-      if (CFR.getOpcode() =3D=3D ISD::TRUNCATE)
-        return getTruncatedArgReg(CFR);
+    if (CFR.getOpcode() =3D=3D ISD::TRUNCATE)
+      return getTruncatedArgReg(CFR);
   }
   return 0;
 }
@@ -4398,7 +4418,7 @@
   // Some arguments' frame index is recorded during argument lowering.
   Offset =3D FuncInfo.getArgumentFrameIndex(Arg);
   if (Offset)
-      Reg =3D TRI->getFrameRegister(MF);
+    Reg =3D TRI->getFrameRegister(MF);
=20
   if (!Reg && N.getNode()) {
     if (N.getOpcode() =3D=3D ISD::CopyFromReg)
@@ -4473,9 +4493,9 @@
                              getValue(I.getArgOperand(0))));
     return 0;
   case Intrinsic::setjmp:
-    return "_setjmp"+!TLI.usesUnderscoreSetJmp();
+    return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
   case Intrinsic::longjmp:
-    return "_longjmp"+!TLI.usesUnderscoreLongJmp();
+    return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
   case Intrinsic::memcpy: {
     // Assert for address < 256 since we support only user defined address
     // spaces.
@@ -4531,8 +4551,10 @@
     const DbgDeclareInst &DI =3D cast<DbgDeclareInst>(I);
     MDNode *Variable =3D DI.getVariable();
     const Value *Address =3D DI.getAddress();
-    if (!Address || !DIVariable(Variable).Verify())
+    if (!Address || !DIVariable(Variable).Verify()) {
+      DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
       return 0;
+    }
=20
     // Build an entry in DbgOrdering.  Debug info input nodes get an SDNod=
eOrder
     // but do not always have a corresponding SDNode built.  The SDNodeOrd=
er
@@ -4543,7 +4565,7 @@
     // Check if address has undef value.
     if (isa<UndefValue>(Address) ||
         (Address->use_empty() && !isa<Argument>(Address))) {
-      DEBUG(dbgs() << "Dropping debug info for " << DI);
+      DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
       return 0;
     }
=20
@@ -4553,11 +4575,13 @@
       N =3D UnusedArgNodeMap[Address];
     SDDbgValue *SDV;
     if (N.getNode()) {
+      if (const BitCastInst *BCI =3D dyn_cast<BitCastInst>(Address))
+        Address =3D BCI->getOperand(0);
       // Parameters are handled specially.
       bool isParameter =3D
-        DIVariable(Variable).getTag() =3D=3D dwarf::DW_TAG_arg_variable;
-      if (const BitCastInst *BCI =3D dyn_cast<BitCastInst>(Address))
-        Address =3D BCI->getOperand(0);
+        (DIVariable(Variable).getTag() =3D=3D dwarf::DW_TAG_arg_variable ||
+         isa<Argument>(Address));
+
       const AllocaInst *AI =3D dyn_cast<AllocaInst>(Address);
=20
       if (isParameter && !AI) {
@@ -4577,7 +4601,9 @@
                               0, dl, SDNodeOrder);
       else {
         // Can't do anything with other non-AI cases yet.
-        DEBUG(dbgs() << "Dropping debug info for " << DI);
+        DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
+        DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
+        DEBUG(Address->dump());
         return 0;
       }
       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
@@ -4599,7 +4625,7 @@
             }
           }
         }
-        DEBUG(dbgs() << "Dropping debug info for " << DI);
+        DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
       }
     }
     return 0;
@@ -4645,7 +4671,7 @@
       } else {
         // We may expand this to cover more cases.  One case where we have=
 no
         // data available is an unreferenced parameter.
-        DEBUG(dbgs() << "Dropping debug info for " << DI);
+        DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
       }
     }
=20
@@ -4654,8 +4680,11 @@
       V =3D BCI->getOperand(0);
     const AllocaInst *AI =3D dyn_cast<AllocaInst>(V);
     // Don't handle byval struct arguments or VLAs, for example.
-    if (!AI)
+    if (!AI) {
+      DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n=
");
+      DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
       return 0;
+    }
     DenseMap<const AllocaInst*, int>::iterator SI =3D
       FuncInfo.StaticAllocaMap.find(AI);
     if (SI =3D=3D FuncInfo.StaticAllocaMap.end())
@@ -4667,43 +4696,6 @@
       MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
     return 0;
   }
-  case Intrinsic::eh_exception: {
-    // Insert the EXCEPTIONADDR instruction.
-    assert(FuncInfo.MBB->isLandingPad() &&
-           "Call to eh.exception not in landing pad!");
-    SDVTList VTs =3D DAG.getVTList(TLI.getPointerTy(), MVT::Other);
-    SDValue Ops[1];
-    Ops[0] =3D DAG.getRoot();
-    SDValue Op =3D DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
-    setValue(&I, Op);
-    DAG.setRoot(Op.getValue(1));
-    return 0;
-  }
-
-  case Intrinsic::eh_selector: {
-    MachineBasicBlock *CallMBB =3D FuncInfo.MBB;
-    MachineModuleInfo &MMI =3D DAG.getMachineFunction().getMMI();
-    if (CallMBB->isLandingPad())
-      AddCatchInfo(I, &MMI, CallMBB);
-    else {
-#ifndef NDEBUG
-      FuncInfo.CatchInfoLost.insert(&I);
-#endif
-      // FIXME: Mark exception selector register as live in.  Hack for PR1=
508.
-      unsigned Reg =3D TLI.getExceptionSelectorRegister();
-      if (Reg) FuncInfo.MBB->addLiveIn(Reg);
-    }
-
-    // Insert the EHSELECTION instruction.
-    SDVTList VTs =3D DAG.getVTList(TLI.getPointerTy(), MVT::Other);
-    SDValue Ops[2];
-    Ops[0] =3D getValue(I.getArgOperand(0));
-    Ops[1] =3D getRoot();
-    SDValue Op =3D DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
-    DAG.setRoot(Op.getValue(1));
-    setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
-    return 0;
-  }
=20
   case Intrinsic::eh_typeid_for: {
     // Find the type id for the given typeinfo.
@@ -4775,11 +4767,6 @@
                             getRoot(), getValue(I.getArgOperand(0))));
     return 0;
   }
-  case Intrinsic::eh_sjlj_dispatch_setup: {
-    DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
-                            getRoot(), getValue(I.getArgOperand(0))));
-    return 0;
-  }
=20
   case Intrinsic::x86_mmx_pslli_w:
   case Intrinsic::x86_mmx_pslli_d:
@@ -4841,6 +4828,22 @@
     setValue(&I, Res);
     return 0;
   }
+  case Intrinsic::x86_avx_vinsertf128_pd_256:
+  case Intrinsic::x86_avx_vinsertf128_ps_256:
+  case Intrinsic::x86_avx_vinsertf128_si_256:
+  case Intrinsic::x86_avx2_vinserti128: {
+    DebugLoc dl =3D getCurDebugLoc();
+    EVT DestVT =3D TLI.getValueType(I.getType());
+    EVT ElVT =3D TLI.getValueType(I.getArgOperand(1)->getType());
+    uint64_t Idx =3D (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(=
) & 1) *
+                   ElVT.getVectorNumElements();
+    Res =3D DAG.getNode(ISD::INSERT_SUBVECTOR, dl, DestVT,
+                      getValue(I.getArgOperand(0)),
+                      getValue(I.getArgOperand(1)),
+                      DAG.getConstant(Idx, MVT::i32));
+    setValue(&I, Res);
+    return 0;
+  }
   case Intrinsic::convertff:
   case Intrinsic::convertfsi:
   case Intrinsic::convertfui:
@@ -4852,6 +4855,7 @@
   case Intrinsic::convertuu: {
     ISD::CvtCode Code =3D ISD::CVT_INVALID;
     switch (Intrinsic) {
+    default: llvm_unreachable("Impossible intrinsic");  // Can't reach her=
e.
     case Intrinsic::convertff:  Code =3D ISD::CVT_FF; break;
     case Intrinsic::convertfsi: Code =3D ISD::CVT_FS; break;
     case Intrinsic::convertfui: Code =3D ISD::CVT_FU; break;
@@ -4946,14 +4950,18 @@
     return 0;
   case Intrinsic::cttz: {
     SDValue Arg =3D getValue(I.getArgOperand(0));
+    ConstantInt *CI =3D cast<ConstantInt>(I.getArgOperand(1));
     EVT Ty =3D Arg.getValueType();
-    setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
+    setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UND=
EF,
+                             dl, Ty, Arg));
     return 0;
   }
   case Intrinsic::ctlz: {
     SDValue Arg =3D getValue(I.getArgOperand(0));
+    ConstantInt *CI =3D cast<ConstantInt>(I.getArgOperand(1));
     EVT Ty =3D Arg.getValueType();
-    setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
+    setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UND=
EF,
+                             dl, Ty, Arg));
     return 0;
   }
   case Intrinsic::ctpop: {
@@ -5052,7 +5060,6 @@
   case Intrinsic::gcread:
   case Intrinsic::gcwrite:
     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
-    return 0;
   case Intrinsic::flt_rounds:
     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
     return 0;
@@ -5064,7 +5071,7 @@
   }
=20
   case Intrinsic::trap: {
-    StringRef TrapFuncName =3D getTrapFunctionName();
+    StringRef TrapFuncName =3D TM.Options.getTrapFunctionName();
     if (TrapFuncName.empty()) {
       DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
       return 0;
@@ -5073,25 +5080,36 @@
     std::pair<SDValue, SDValue> Result =3D
       TLI.LowerCallTo(getRoot(), I.getType(),
                  false, false, false, false, 0, CallingConv::C,
-                 /*isTailCall=3D*/false, /*isReturnValueUsed=3D*/true,
+                 /*isTailCall=3D*/false,
+                 /*doesNotRet=3D*/false, /*isReturnValueUsed=3D*/true,
                  DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointer=
Ty()),
                  Args, DAG, getCurDebugLoc());
     DAG.setRoot(Result.second);
     return 0;
   }
   case Intrinsic::uadd_with_overflow:
-    return implVisitAluOverflow(I, ISD::UADDO);
   case Intrinsic::sadd_with_overflow:
-    return implVisitAluOverflow(I, ISD::SADDO);
   case Intrinsic::usub_with_overflow:
-    return implVisitAluOverflow(I, ISD::USUBO);
   case Intrinsic::ssub_with_overflow:
-    return implVisitAluOverflow(I, ISD::SSUBO);
   case Intrinsic::umul_with_overflow:
-    return implVisitAluOverflow(I, ISD::UMULO);
-  case Intrinsic::smul_with_overflow:
-    return implVisitAluOverflow(I, ISD::SMULO);
-
+  case Intrinsic::smul_with_overflow: {
+    ISD::NodeType Op;
+    switch (Intrinsic) {
+    default: llvm_unreachable("Impossible intrinsic");  // Can't reach her=
e.
+    case Intrinsic::uadd_with_overflow: Op =3D ISD::UADDO; break;
+    case Intrinsic::sadd_with_overflow: Op =3D ISD::SADDO; break;
+    case Intrinsic::usub_with_overflow: Op =3D ISD::USUBO; break;
+    case Intrinsic::ssub_with_overflow: Op =3D ISD::SSUBO; break;
+    case Intrinsic::umul_with_overflow: Op =3D ISD::UMULO; break;
+    case Intrinsic::smul_with_overflow: Op =3D ISD::SMULO; break;
+    }
+    SDValue Op1 =3D getValue(I.getArgOperand(0));
+    SDValue Op2 =3D getValue(I.getArgOperand(1));
+
+    SDVTList VTs =3D DAG.getVTList(Op1.getValueType(), MVT::i1);
+    setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
+    return 0;
+  }
   case Intrinsic::prefetch: {
     SDValue Ops[5];
     unsigned rw =3D cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
@@ -5226,7 +5244,7 @@
=20
   // If there's a possibility that fast-isel has already selected some amo=
unt
   // of the current basic block, don't emit a tail call.
-  if (isTailCall && EnableFastISel)
+  if (isTailCall && TM.Options.EnableFastISel)
     isTailCall =3D false;
=20
   std::pair<SDValue,SDValue> Result =3D
@@ -5236,6 +5254,7 @@
                     CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParam=
s(),
                     CS.getCallingConv(),
                     isTailCall,
+                    CS.doesNotReturn(),
                     !CS.getInstruction()->use_empty(),
                     Callee, Args, DAG, getCurDebugLoc());
   assert((isTailCall || Result.second.getNode()) &&
@@ -5264,7 +5283,7 @@
       SDValue L =3D DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.secon=
d,
                               Add,
                   MachinePointerInfo::getFixedStack(DemoteStackIdx, Offset=
s[i]),
-                              false, false, 1);
+                              false, false, false, 1);
       Values[i] =3D L;
       Chains[i] =3D L.getValue(1);
     }
@@ -5375,7 +5394,8 @@
   SDValue LoadVal =3D Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc()=
, Root,
                                         Ptr, MachinePointerInfo(PtrVal),
                                         false /*volatile*/,
-                                        false /*nontemporal*/, 1 /* align=
=3D1 */);
+                                        false /*nontemporal*/,=20
+                                        false /*isinvariant*/, 1 /* align=
=3D1 */);
=20
   if (!ConstantMemory)
     Builder.PendingLoads.push_back(LoadVal.getValue(1));
@@ -5470,23 +5490,8 @@
     return;
   }
=20
-  // See if any floating point values are being passed to this function. T=
his is
-  // used to emit an undefined reference to fltused on Windows.
-  FunctionType *FT =3D
-    cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
   MachineModuleInfo &MMI =3D DAG.getMachineFunction().getMMI();
-  if (FT->isVarArg() &&
-      !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
-    for (unsigned i =3D 0, e =3D I.getNumArgOperands(); i !=3D e; ++i) {
-      Type* T =3D I.getArgOperand(i)->getType();
-      for (po_iterator<Type*> i =3D po_begin(T), e =3D po_end(T);
-           i !=3D e; ++i) {
-        if (!i->isFloatingPointTy()) continue;
-        MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
-        break;
-      }
-    }
-  }
+  ComputeUsesVAFloatArgument(I, &MMI);
=20
   const char *RenameFn =3D 0;
   if (Function *F =3D I.getCalledFunction()) {
@@ -5509,7 +5514,9 @@
     // can't be a library call.
     if (!F->hasLocalLinkage() && F->hasName()) {
       StringRef Name =3D F->getName();
-      if (Name =3D=3D "copysign" || Name =3D=3D "copysignf" || Name =3D=3D=
 "copysignl") {
+      if ((LibInfo->has(LibFunc::copysign) && Name =3D=3D "copysign") ||
+          (LibInfo->has(LibFunc::copysignf) && Name =3D=3D "copysignf") ||
+          (LibInfo->has(LibFunc::copysignl) && Name =3D=3D "copysignl")) {
         if (I.getNumArgOperands() =3D=3D 2 &&   // Basic sanity checks.
             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
             I.getType() =3D=3D I.getArgOperand(0)->getType() &&
@@ -5520,7 +5527,9 @@
                                    LHS.getValueType(), LHS, RHS));
           return;
         }
-      } else if (Name =3D=3D "fabs" || Name =3D=3D "fabsf" || Name =3D=3D =
"fabsl") {
+      } else if ((LibInfo->has(LibFunc::fabs) && Name =3D=3D "fabs") ||
+                 (LibInfo->has(LibFunc::fabsf) && Name =3D=3D "fabsf") ||
+                 (LibInfo->has(LibFunc::fabsl) && Name =3D=3D "fabsl")) {
         if (I.getNumArgOperands() =3D=3D 1 &&   // Basic sanity checks.
             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
             I.getType() =3D=3D I.getArgOperand(0)->getType()) {
@@ -5529,7 +5538,9 @@
                                    Tmp.getValueType(), Tmp));
           return;
         }
-      } else if (Name =3D=3D "sin" || Name =3D=3D "sinf" || Name =3D=3D "s=
inl") {
+      } else if ((LibInfo->has(LibFunc::sin) && Name =3D=3D "sin") ||
+                 (LibInfo->has(LibFunc::sinf) && Name =3D=3D "sinf") ||
+                 (LibInfo->has(LibFunc::sinl) && Name =3D=3D "sinl")) {
         if (I.getNumArgOperands() =3D=3D 1 &&   // Basic sanity checks.
             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
             I.getType() =3D=3D I.getArgOperand(0)->getType() &&
@@ -5539,7 +5550,9 @@
                                    Tmp.getValueType(), Tmp));
           return;
         }
-      } else if (Name =3D=3D "cos" || Name =3D=3D "cosf" || Name =3D=3D "c=
osl") {
+      } else if ((LibInfo->has(LibFunc::cos) && Name =3D=3D "cos") ||
+                 (LibInfo->has(LibFunc::cosf) && Name =3D=3D "cosf") ||
+                 (LibInfo->has(LibFunc::cosl) && Name =3D=3D "cosl")) {
         if (I.getNumArgOperands() =3D=3D 1 &&   // Basic sanity checks.
             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
             I.getType() =3D=3D I.getArgOperand(0)->getType() &&
@@ -5549,7 +5562,9 @@
                                    Tmp.getValueType(), Tmp));
           return;
         }
-      } else if (Name =3D=3D "sqrt" || Name =3D=3D "sqrtf" || Name =3D=3D =
"sqrtl") {
+      } else if ((LibInfo->has(LibFunc::sqrt) && Name =3D=3D "sqrt") ||
+                 (LibInfo->has(LibFunc::sqrtf) && Name =3D=3D "sqrtf") ||
+                 (LibInfo->has(LibFunc::sqrtl) && Name =3D=3D "sqrtl")) {
         if (I.getNumArgOperands() =3D=3D 1 &&   // Basic sanity checks.
             I.getArgOperand(0)->getType()->isFloatingPointTy() &&
             I.getType() =3D=3D I.getArgOperand(0)->getType() &&
@@ -5559,6 +5574,85 @@
                                    Tmp.getValueType(), Tmp));
           return;
         }
+      } else if ((LibInfo->has(LibFunc::floor) && Name =3D=3D "floor") ||
+                 (LibInfo->has(LibFunc::floorf) && Name =3D=3D "floorf") ||
+                 (LibInfo->has(LibFunc::floorl) && Name =3D=3D "floorl")) {
+        if (I.getNumArgOperands() =3D=3D 1 && // Basic sanity checks.
+            I.getArgOperand(0)->getType()->isFloatingPointTy() &&
+            I.getType() =3D=3D I.getArgOperand(0)->getType()) {
+          SDValue Tmp =3D getValue(I.getArgOperand(0));
+          setValue(&I, DAG.getNode(ISD::FFLOOR, getCurDebugLoc(),
+                                   Tmp.getValueType(), Tmp));
+          return;
+        }
+      } else if ((LibInfo->has(LibFunc::nearbyint) && Name =3D=3D "nearbyi=
nt") ||
+                 (LibInfo->has(LibFunc::nearbyintf) && Name =3D=3D "nearby=
intf") ||
+                 (LibInfo->has(LibFunc::nearbyintl) && Name =3D=3D "nearby=
intl")) {
+        if (I.getNumArgOperands() =3D=3D 1 && // Basic sanity checks.
+            I.getArgOperand(0)->getType()->isFloatingPointTy() &&
+            I.getType() =3D=3D I.getArgOperand(0)->getType()) {
+          SDValue Tmp =3D getValue(I.getArgOperand(0));
+          setValue(&I, DAG.getNode(ISD::FNEARBYINT, getCurDebugLoc(),
+                                   Tmp.getValueType(), Tmp));
+          return;
+        }
+      } else if ((LibInfo->has(LibFunc::ceil) && Name =3D=3D "ceil") ||
+                 (LibInfo->has(LibFunc::ceilf) && Name =3D=3D "ceilf") ||
+                 (LibInfo->has(LibFunc::ceill) && Name =3D=3D "ceill")) {
+        if (I.getNumArgOperands() =3D=3D 1 && // Basic sanity checks.
+            I.getArgOperand(0)->getType()->isFloatingPointTy() &&
+            I.getType() =3D=3D I.getArgOperand(0)->getType()) {
+          SDValue Tmp =3D getValue(I.getArgOperand(0));
+          setValue(&I, DAG.getNode(ISD::FCEIL, getCurDebugLoc(),
+                                   Tmp.getValueType(), Tmp));
+          return;
+        }
+      } else if ((LibInfo->has(LibFunc::rint) && Name =3D=3D "rint") ||
+                 (LibInfo->has(LibFunc::rintf) && Name =3D=3D "rintf") ||
+                 (LibInfo->has(LibFunc::rintl) && Name =3D=3D "rintl")) {
+        if (I.getNumArgOperands() =3D=3D 1 && // Basic sanity checks.
+            I.getArgOperand(0)->getType()->isFloatingPointTy() &&
+            I.getType() =3D=3D I.getArgOperand(0)->getType()) {
+          SDValue Tmp =3D getValue(I.getArgOperand(0));
+          setValue(&I, DAG.getNode(ISD::FRINT, getCurDebugLoc(),
+                                   Tmp.getValueType(), Tmp));
+          return;
+        }
+      } else if ((LibInfo->has(LibFunc::trunc) && Name =3D=3D "trunc") ||
+                 (LibInfo->has(LibFunc::truncf) && Name =3D=3D "truncf") ||
+                 (LibInfo->has(LibFunc::truncl) && Name =3D=3D "truncl")) {
+        if (I.getNumArgOperands() =3D=3D 1 && // Basic sanity checks.
+            I.getArgOperand(0)->getType()->isFloatingPointTy() &&
+            I.getType() =3D=3D I.getArgOperand(0)->getType()) {
+          SDValue Tmp =3D getValue(I.getArgOperand(0));
+          setValue(&I, DAG.getNode(ISD::FTRUNC, getCurDebugLoc(),
+                                   Tmp.getValueType(), Tmp));
+          return;
+        }
+      } else if ((LibInfo->has(LibFunc::log2) && Name =3D=3D "log2") ||
+                 (LibInfo->has(LibFunc::log2f) && Name =3D=3D "log2f") ||
+                 (LibInfo->has(LibFunc::log2l) && Name =3D=3D "log2l")) {
+        if (I.getNumArgOperands() =3D=3D 1 && // Basic sanity checks.
+            I.getArgOperand(0)->getType()->isFloatingPointTy() &&
+            I.getType() =3D=3D I.getArgOperand(0)->getType() &&
+            I.onlyReadsMemory()) {
+          SDValue Tmp =3D getValue(I.getArgOperand(0));
+          setValue(&I, DAG.getNode(ISD::FLOG2, getCurDebugLoc(),
+                                   Tmp.getValueType(), Tmp));
+          return;
+        }
+      } else if ((LibInfo->has(LibFunc::exp2) && Name =3D=3D "exp2") ||
+                 (LibInfo->has(LibFunc::exp2f) && Name =3D=3D "exp2f") ||
+                 (LibInfo->has(LibFunc::exp2l) && Name =3D=3D "exp2l")) {
+        if (I.getNumArgOperands() =3D=3D 1 && // Basic sanity checks.
+            I.getArgOperand(0)->getType()->isFloatingPointTy() &&
+            I.getType() =3D=3D I.getArgOperand(0)->getType() &&
+            I.onlyReadsMemory()) {
+          SDValue Tmp =3D getValue(I.getArgOperand(0));
+          setValue(&I, DAG.getNode(ISD::FEXP2, getCurDebugLoc(),
+                                   Tmp.getValueType(), Tmp));
+          return;
+        }
       } else if (Name =3D=3D "memcmp") {
         if (visitMemCmpCall(I))
           return;
@@ -5596,22 +5690,6 @@
     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
   }
=20
-  /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned regi=
sters
-  /// busy in OutputRegs/InputRegs.
-  void MarkAllocatedRegs(bool isOutReg, bool isInReg,
-                         std::set<unsigned> &OutputRegs,
-                         std::set<unsigned> &InputRegs,
-                         const TargetRegisterInfo &TRI) const {
-    if (isOutReg) {
-      for (unsigned i =3D 0, e =3D AssignedRegs.Regs.size(); i !=3D e; ++i)
-        MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
-    }
-    if (isInReg) {
-      for (unsigned i =3D 0, e =3D AssignedRegs.Regs.size(); i !=3D e; ++i)
-        MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
-    }
-  }
-
   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
   /// corresponds to.  If there is no Value* for this operand, it returns
   /// MVT::Other.
@@ -5659,18 +5737,6 @@
=20
     return TLI.getValueType(OpTy, true);
   }
-
-private:
-  /// MarkRegAndAliases - Mark the specified register and all aliases in t=
he
-  /// specified set.
-  static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
-                                const TargetRegisterInfo &TRI) {
-    assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg=
");
-    Regs.insert(Reg);
-    if (const unsigned *Aliases =3D TRI.getAliasSet(Reg))
-      for (; *Aliases; ++Aliases)
-        Regs.insert(*Aliases);
-  }
 };
=20
 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
@@ -5684,39 +5750,13 @@
 /// allocation.  This produces generally horrible, but correct, code.
 ///
 ///   OpInfo describes the operand.
-///   Input and OutputRegs are the set of already allocated physical regis=
ters.
 ///
 static void GetRegistersForValue(SelectionDAG &DAG,
                                  const TargetLowering &TLI,
                                  DebugLoc DL,
-                                 SDISelAsmOperandInfo &OpInfo,
-                                 std::set<unsigned> &OutputRegs,
-                                 std::set<unsigned> &InputRegs) {
+                                 SDISelAsmOperandInfo &OpInfo) {
   LLVMContext &Context =3D *DAG.getContext();
=20
-  // Compute whether this value requires an input register, an output regi=
ster,
-  // or both.
-  bool isOutReg =3D false;
-  bool isInReg =3D false;
-  switch (OpInfo.Type) {
-  case InlineAsm::isOutput:
-    isOutReg =3D true;
-
-    // If there is an input constraint that matches this, we need to reser=
ve
-    // the input register so no other inputs allocate to it.
-    isInReg =3D OpInfo.hasMatchingInput();
-    break;
-  case InlineAsm::isInput:
-    isInReg =3D true;
-    isOutReg =3D false;
-    break;
-  case InlineAsm::isClobber:
-    isOutReg =3D true;
-    isInReg =3D true;
-    break;
-  }
-
-
   MachineFunction &MF =3D DAG.getMachineFunction();
   SmallVector<unsigned, 4> Regs;
=20
@@ -5790,8 +5830,6 @@
     }
=20
     OpInfo.AssignedRegs =3D RegsForValue(Regs, RegVT, ValueVT);
-    const TargetRegisterInfo *TRI =3D DAG.getTarget().getRegisterInfo();
-    OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TR=
I);
     return;
   }
=20
@@ -5822,8 +5860,6 @@
   /// ConstraintOperands - Information about all of the constraints.
   SDISelAsmOperandInfoVector ConstraintOperands;
=20
-  std::set<unsigned> OutputRegs, InputRegs;
-
   TargetLowering::AsmOperandInfoVector
     TargetConstraints =3D TLI.ParseConstraints(CS);
=20
@@ -5956,7 +5992,7 @@
       // constant pool entry to get its address.
       const Value *OpVal =3D OpInfo.CallOperandVal;
       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
-          isa<ConstantVector>(OpVal)) {
+          isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
         OpInfo.CallOperand =3D DAG.getConstantPool(cast<Constant>(OpVal),
                                                  TLI.getPointerTy());
       } else {
@@ -5985,8 +6021,7 @@
     // If this constraint is for a specific register, allocate it before
     // anything else.
     if (OpInfo.ConstraintType =3D=3D TargetLowering::C_Register)
-      GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
-                           InputRegs);
+      GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
   }
=20
   // Second pass - Loop over all of the operands, assigning virtual or phy=
sregs
@@ -5997,8 +6032,7 @@
     // C_Register operands have already been allocated, Other/Memory don't=
 need
     // to be.
     if (OpInfo.ConstraintType =3D=3D TargetLowering::C_RegisterClass)
-      GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
-                           InputRegs);
+      GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
   }
=20
   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
@@ -6052,9 +6086,13 @@
=20
       // Copy the output from the appropriate register.  Find a register t=
hat
       // we can use.
-      if (OpInfo.AssignedRegs.Regs.empty())
-        report_fatal_error("Couldn't allocate output reg for constraint '"=
 +
-                           Twine(OpInfo.ConstraintCode) + "'!");
+      if (OpInfo.AssignedRegs.Regs.empty()) {
+        LLVMContext &Ctx =3D *DAG.getContext();
+        Ctx.emitError(CS.getInstruction(), =20
+                      "couldn't allocate output register for constraint '"=
 +
+                           Twine(OpInfo.ConstraintCode) + "'");
+        break;
+      }
=20
       // If this is an indirect operand, store through the pointer after t=
he
       // asm.
@@ -6154,9 +6192,13 @@
         std::vector<SDValue> Ops;
         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCo=
de,
                                          Ops, DAG);
-        if (Ops.empty())
-          report_fatal_error("Invalid operand for inline asm constraint '"=
 +
-                             Twine(OpInfo.ConstraintCode) + "'!");
+        if (Ops.empty()) {
+          LLVMContext &Ctx =3D *DAG.getContext();
+          Ctx.emitError(CS.getInstruction(),
+                        "invalid operand for inline asm constraint '" +
+                        Twine(OpInfo.ConstraintCode) + "'");
+          break;
+        }
=20
         // Add information to the INLINEASM node to know about this input.
         unsigned ResOpType =3D
@@ -6187,9 +6229,13 @@
              "Don't know how to handle indirect register inputs yet!");
=20
       // Copy the input into the appropriate registers.
-      if (OpInfo.AssignedRegs.Regs.empty())
-        report_fatal_error("Couldn't allocate input reg for constraint '" +
-                           Twine(OpInfo.ConstraintCode) + "'!");
+      if (OpInfo.AssignedRegs.Regs.empty()) {
+        LLVMContext &Ctx =3D *DAG.getContext();
+        Ctx.emitError(CS.getInstruction(),=20
+                      "couldn't allocate input reg for constraint '" +
+                           Twine(OpInfo.ConstraintCode) + "'");
+        break;
+      }
=20
       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(=
),
                                         Chain, &Flag);
@@ -6327,7 +6373,7 @@
                             bool RetSExt, bool RetZExt, bool isVarArg,
                             bool isInreg, unsigned NumFixedArgs,
                             CallingConv::ID CallConv, bool isTailCall,
-                            bool isReturnValueUsed,
+                            bool doesNotRet, bool isReturnValueUsed,
                             SDValue Callee,
                             ArgListTy &Args, SelectionDAG &DAG,
                             DebugLoc dl) const {
@@ -6424,7 +6470,7 @@
   }
=20
   SmallVector<SDValue, 4> InVals;
-  Chain =3D LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
+  Chain =3D LowerCall(Chain, Callee, CallConv, isVarArg, doesNotRet, isTai=
lCall,
                     Outs, OutVals, Ins, dl, DAG, InVals);
=20
   // Verify that the target's LowerCall behaved as expected.
@@ -6493,7 +6539,6 @@
=20
 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) cons=
t {
   llvm_unreachable("LowerOperation not implemented for this target!");
-  return SDValue();
 }
=20
 void
@@ -6515,10 +6560,10 @@
 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
 /// entry block, return true.  This includes arguments used by switches, s=
ince
 /// the switch may expand into multiple basic blocks.
-static bool isOnlyUsedInEntryBlock(const Argument *A) {
+static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
   // With FastISel active, we may be splitting blocks, so force creation
   // of virtual registers for all non-dead arguments.
-  if (EnableFastISel)
+  if (FastISel)
     return A->use_empty();
=20
   const BasicBlock *Entry =3D A->getParent()->begin();
@@ -6708,7 +6753,7 @@
                                      SDB->getCurDebugLoc());
=20
     SDB->setValue(I, Res);
-    if (!EnableFastISel && Res.getOpcode() =3D=3D ISD::BUILD_PAIR) {
+    if (!TM.Options.EnableFastISel && Res.getOpcode() =3D=3D ISD::BUILD_PA=
IR) {
       if (LoadSDNode *LNode =3D=20
           dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
         if (FrameIndexSDNode *FI =3D
@@ -6718,7 +6763,7 @@
=20
     // If this argument is live outside of the entry block, insert a copy =
from
     // wherever we got it to the vreg that other BB's will reference it as.
-    if (!EnableFastISel && Res.getOpcode() =3D=3D ISD::CopyFromReg) {
+    if (!TM.Options.EnableFastISel && Res.getOpcode() =3D=3D ISD::CopyFrom=
Reg) {
       // If we can, though, try to skip creating an unnecessary vreg.
       // FIXME: This isn't very clean... it would be nice to make this more
       // general.  It's also subtly incompatible with the hacks FastISel
@@ -6729,7 +6774,7 @@
         continue;
       }
     }
-    if (!isOnlyUsedInEntryBlock(I)) {
+    if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
       FuncInfo->InitializeRegForValue(I);
       SDB->CopyToExportRegsIfNeeded(I);
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/SelectionDAGBuilder.h
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -67,11 +67,11 @@
 class StoreInst;
 class SwitchInst;
 class TargetData;
+class TargetLibraryInfo;
 class TargetLowering;
 class TruncInst;
 class UIToFPInst;
 class UnreachableInst;
-class UnwindInst;
 class VAArgInst;
 class ZExtInst;
=20
@@ -129,13 +129,13 @@
   /// Case - A struct to record the Value for a switch case, and the
   /// case's target basic block.
   struct Case {
-    Constant* Low;
-    Constant* High;
+    const Constant *Low;
+    const Constant *High;
     MachineBasicBlock* BB;
     uint32_t ExtraWeight;
=20
     Case() : Low(0), High(0), BB(0), ExtraWeight(0) { }
-    Case(Constant* low, Constant* high, MachineBasicBlock* bb,
+    Case(const Constant *low, const Constant *high, MachineBasicBlock *bb,
          uint32_t extraweight) : Low(low), High(high), BB(bb),
          ExtraWeight(extraweight) { }
=20
@@ -294,6 +294,7 @@
   SelectionDAG &DAG;
   const TargetData *TD;
   AliasAnalysis *AA;
+  const TargetLibraryInfo *LibInfo;
=20
   /// SwitchCases - Vector of CaseBlock structures used to communicate
   /// SwitchInst code generation information.
@@ -338,7 +339,8 @@
       HasTailCall(false), Context(dag.getContext()) {
   }
=20
-  void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
+  void init(GCFunctionInfo *gfi, AliasAnalysis &aa,
+            const TargetLibraryInfo *li);
=20
   /// clear - Clear out the current SelectionDAG and the associated
   /// state and prepare this SelectionDAGBuilder object to be used
@@ -451,7 +453,8 @@
                                 MachineBasicBlock* Default,
                                 MachineBasicBlock *SwitchBB);
=20
-  uint32_t getEdgeWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst);
+  uint32_t getEdgeWeight(const MachineBasicBlock *Src,
+                         const MachineBasicBlock *Dst) const;
   void addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *D=
st,
                               uint32_t Weight =3D 0);
 public:
@@ -471,7 +474,6 @@
   // These all get lowered before this pass.
   void visitInvoke(const InvokeInst &I);
   void visitResume(const ResumeInst &I);
-  void visitUnwind(const UnwindInst &I);
=20
   void visitBinary(const User &I, unsigned OpCode);
   void visitShift(const User &I, unsigned Opcode);
@@ -554,8 +556,6 @@
   void visitUserOp2(const Instruction &I) {
     llvm_unreachable("UserOp2 should not exist at instruction selection ti=
me!");
   }
- =20
-  const char *implVisitAluOverflow(const CallInst &I, ISD::NodeType Op);
=20
   void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/SelectionDAGISel.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -41,6 +41,7 @@
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetIntrinsicInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
@@ -61,6 +62,80 @@
 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another p=
ath");
=20
+#ifndef NDEBUG
+static cl::opt<bool>
+EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
+          cl::desc("Enable extra verbose messages in the \"fast\" "
+                   "instruction selector"));
+  // Terminators
+STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
+STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
+STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
+STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
+STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
+STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
+STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
+
+  // Standard binary operators...
+STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
+STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
+STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
+STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
+STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
+STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
+STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
+STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
+STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
+STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
+STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
+STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
+
+  // Logical operators...
+STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
+STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
+STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
+
+  // Memory instructions...
+STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
+STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
+STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
+STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
+STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
+STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
+STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
+
+  // Convert instructions...
+STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
+STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
+STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
+STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
+STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
+STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
+STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
+STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
+STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
+STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
+STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
+STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
+
+  // Other instructions...
+STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
+STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
+STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
+STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
+STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
+STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
+STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
+STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
+STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
+STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement=
");
+STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
+STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
+STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
+STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
+STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
+#endif
+
 static cl::opt<bool>
 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
           cl::desc("Enable verbose messages in the \"fast\" "
@@ -142,14 +217,15 @@
                                              CodeGenOpt::Level OptLevel) {
     const TargetLowering &TLI =3D IS->getTargetLowering();
=20
-    if (OptLevel =3D=3D CodeGenOpt::None)
+    if (OptLevel =3D=3D CodeGenOpt::None ||
+        TLI.getSchedulingPreference() =3D=3D Sched::Source)
       return createSourceListDAGScheduler(IS, OptLevel);
-    if (TLI.getSchedulingPreference() =3D=3D Sched::Latency)
-      return createTDListDAGScheduler(IS, OptLevel);
     if (TLI.getSchedulingPreference() =3D=3D Sched::RegPressure)
       return createBURRListDAGScheduler(IS, OptLevel);
     if (TLI.getSchedulingPreference() =3D=3D Sched::Hybrid)
       return createHybridListDAGScheduler(IS, OptLevel);
+    if (TLI.getSchedulingPreference() =3D=3D Sched::VLIW)
+      return createVLIWDAGScheduler(IS, OptLevel);
     assert(TLI.getSchedulingPreference() =3D=3D Sched::ILP &&
            "Unknown sched type!");
     return createILPListDAGScheduler(IS, OptLevel);
@@ -174,12 +250,11 @@
           "TargetLowering::EmitInstrWithCustomInserter!";
 #endif
   llvm_unreachable(0);
-  return 0;
 }
=20
 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
                                                    SDNode *Node) const {
-  assert(!MI->getDesc().hasPostISelHook() &&
+  assert(!MI->hasPostISelHook() &&
          "If a target marks an instruction with 'hasPostISelHook', "
          "it must implement TargetLowering::AdjustInstrPostInstrSelection!=
");
 }
@@ -188,11 +263,13 @@
 // SelectionDAGISel code
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void SelectionDAGISel::ISelUpdater::anchor() { }
+
 SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm,
                                    CodeGenOpt::Level OL) :
   MachineFunctionPass(ID), TM(tm), TLI(*tm.getTargetLowering()),
   FuncInfo(new FunctionLoweringInfo(TLI)),
-  CurDAG(new SelectionDAG(tm)),
+  CurDAG(new SelectionDAG(tm, OL)),
   SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
   GFI(),
   OptLevel(OL),
@@ -200,6 +277,7 @@
     initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
     initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
     initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
+    initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
   }
=20
 SelectionDAGISel::~SelectionDAGISel() {
@@ -213,6 +291,7 @@
   AU.addPreserved<AliasAnalysis>();
   AU.addRequired<GCModuleInfo>();
   AU.addPreserved<GCModuleInfo>();
+  AU.addRequired<TargetLibraryInfo>();
   if (UseMBPI && OptLevel !=3D CodeGenOpt::None)
     AU.addRequired<BranchProbabilityInfo>();
   MachineFunctionPass::getAnalysisUsage(AU);
@@ -258,9 +337,9 @@
=20
 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
   // Do some sanity-checking on the command-line options.
-  assert((!EnableFastISelVerbose || EnableFastISel) &&
+  assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
          "-fast-isel-verbose requires -fast-isel");
-  assert((!EnableFastISelAbort || EnableFastISel) &&
+  assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
          "-fast-isel-abort requires -fast-isel");
=20
   const Function &Fn =3D *mf.getFunction();
@@ -270,6 +349,7 @@
   MF =3D &mf;
   RegInfo =3D &MF->getRegInfo();
   AA =3D &getAnalysis<AliasAnalysis>();
+  LibInfo =3D &getAnalysis<TargetLibraryInfo>();
   GFI =3D Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : =
0;
=20
   DEBUG(dbgs() << "\n\n\n=3D=3D=3D " << Fn.getName() << "\n");
@@ -284,7 +364,7 @@
   else
     FuncInfo->BPI =3D 0;
=20
-  SDB->init(GFI, *AA);
+  SDB->init(GFI, *AA, LibInfo);
=20
   SelectAllBasicBlocks(Fn);
=20
@@ -348,7 +428,8 @@
                   TII.get(TargetOpcode::DBG_VALUE))
           .addReg(CopyUseMI->getOperand(0).getReg(), RegState::Debug)
           .addImm(Offset).addMetadata(Variable);
-        EntryMBB->insertAfter(CopyUseMI, NewMI);
+        MachineBasicBlock::iterator Pos =3D CopyUseMI;
+        EntryMBB->insertAfter(Pos, NewMI);
       }
     }
   }
@@ -374,7 +455,7 @@
   }
=20
   // Determine if there is a call to setjmp in the machine function.
-  MF->setCallsSetJmp(Fn.callsFunctionThatReturnsTwice());
+  MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
=20
   // Replace forward-declared registers with the registers containing
   // the desired value.
@@ -427,7 +508,6 @@
=20
   Worklist.push_back(CurDAG->getRoot().getNode());
=20
-  APInt Mask;
   APInt KnownZero;
   APInt KnownOne;
=20
@@ -458,8 +538,7 @@
       continue;
=20
     unsigned NumSignBits =3D CurDAG->ComputeNumSignBits(Src);
-    Mask =3D APInt::getAllOnesValue(SrcVT.getSizeInBits());
-    CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
+    CurDAG->ComputeMaskedBits(Src, KnownZero, KnownOne);
     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
   } while (!Worklist.empty());
 }
@@ -478,8 +557,8 @@
 #endif
   {
     BlockNumber =3D FuncInfo->MBB->getNumber();
-    BlockName =3D MF->getFunction()->getNameStr() + ":" +
-                FuncInfo->MBB->getBasicBlock()->getNameStr();
+    BlockName =3D MF->getFunction()->getName().str() + ":" +
+                FuncInfo->MBB->getBasicBlock()->getName().str();
   }
   DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
         << " '" << BlockName << "'\n"; CurDAG->dump());
@@ -489,7 +568,7 @@
   // Run the DAG combiner in pre-legalize mode.
   {
     NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
-    CurDAG->Combine(Unrestricted, *AA, OptLevel);
+    CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
   }
=20
   DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
@@ -517,7 +596,7 @@
     {
       NamedRegionTimer T("DAG Combining after legalize types", GroupName,
                          TimePassesIsEnabled);
-      CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
+      CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
     }
=20
     DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << Block=
Number
@@ -542,7 +621,7 @@
     {
       NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
                          TimePassesIsEnabled);
-      CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
+      CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
     }
=20
     DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
@@ -564,7 +643,7 @@
   // Run the DAG combiner in post-legalize mode.
   {
     NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
-    CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
+    CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
   }
=20
   DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
@@ -592,7 +671,7 @@
   {
     NamedRegionTimer T("Instruction Scheduling", GroupName,
                        TimePassesIsEnabled);
-    Scheduler->Run(CurDAG, FuncInfo->MBB, FuncInfo->InsertPt);
+    Scheduler->Run(CurDAG, FuncInfo->MBB);
   }
=20
   if (ViewSUnitDAGs) Scheduler->viewGraph();
@@ -603,8 +682,9 @@
   {
     NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnab=
led);
=20
-    LastMBB =3D FuncInfo->MBB =3D Scheduler->EmitSchedule();
-    FuncInfo->InsertPt =3D Scheduler->InsertPos;
+    // FuncInfo->InsertPt is passed by reference and set to the end of the
+    // scheduled instructions.
+    LastMBB =3D FuncInfo->MBB =3D Scheduler->EmitSchedule(FuncInfo->Insert=
Pt);
   }
=20
   // If the block was split, make sure we update any references that are u=
sed to
@@ -693,43 +773,18 @@
=20
   // Assign the call site to the landing pad's begin label.
   MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
-   =20
+
   const MCInstrDesc &II =3D TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
     .addSym(Label);
=20
   // Mark exception register as live in.
-  unsigned Reg =3D TLI.getExceptionAddressRegister();
+  unsigned Reg =3D TLI.getExceptionPointerRegister();
   if (Reg) MBB->addLiveIn(Reg);
=20
   // Mark exception selector register as live in.
   Reg =3D TLI.getExceptionSelectorRegister();
   if (Reg) MBB->addLiveIn(Reg);
-
-  // FIXME: Hack around an exception handling flaw (PR1508): the personali=
ty
-  // function and list of typeids logically belong to the invoke (or, if y=
ou
-  // like, the basic block containing the invoke), and need to be associat=
ed
-  // with it in the dwarf exception handling tables.  Currently however the
-  // information is provided by an intrinsic (eh.selector) that can be mov=
ed
-  // to unexpected places by the optimizers: if the unwind edge is critica=
l,
-  // then breaking it can result in the intrinsics being in the successor =
of
-  // the landing pad, not the landing pad itself.  This results
-  // in exceptions not being caught because no typeids are associated with
-  // the invoke.  This may not be the only way things can go wrong, but it
-  // is the only way we try to work around for the moment.
-  const BasicBlock *LLVMBB =3D MBB->getBasicBlock();
-  const BranchInst *Br =3D dyn_cast<BranchInst>(LLVMBB->getTerminator());
-
-  if (Br && Br->isUnconditional()) { // Critical edge?
-    BasicBlock::const_iterator I, E;
-    for (I =3D LLVMBB->begin(), E =3D --LLVMBB->end(); I !=3D E; ++I)
-      if (isa<EHSelectorInst>(I))
-        break;
-
-    if (I =3D=3D E)
-      // No catch info found - try to extract some from the successor.
-      CopyCatchInfo(Br->getSuccessor(0), LLVMBB, &MF->getMMI(), *FuncInfo);
-  }
 }
=20
 /// TryToFoldFastISelLoad - We're checking to see if we can fold the speci=
fied
@@ -822,10 +877,90 @@
          !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
 }
=20
+#ifndef NDEBUG
+// Collect per Instruction statistics for fast-isel misses.  Only those
+// instructions that cause the bail are accounted for.  It does not accoun=
t for
+// instructions higher in the block.  Thus, summing the per instructions s=
tats
+// will not add up to what is reported by NumFastIselFailures.
+static void collectFailStats(const Instruction *I) {
+  switch (I->getOpcode()) {
+  default: assert (0 && "<Invalid operator> ");
+
+  // Terminators
+  case Instruction::Ret:         NumFastIselFailRet++; return;
+  case Instruction::Br:          NumFastIselFailBr++; return;
+  case Instruction::Switch:      NumFastIselFailSwitch++; return;
+  case Instruction::IndirectBr:  NumFastIselFailIndirectBr++; return;
+  case Instruction::Invoke:      NumFastIselFailInvoke++; return;
+  case Instruction::Resume:      NumFastIselFailResume++; return;
+  case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
+
+  // Standard binary operators...
+  case Instruction::Add:  NumFastIselFailAdd++; return;
+  case Instruction::FAdd: NumFastIselFailFAdd++; return;
+  case Instruction::Sub:  NumFastIselFailSub++; return;
+  case Instruction::FSub: NumFastIselFailFSub++; return;
+  case Instruction::Mul:  NumFastIselFailMul++; return;
+  case Instruction::FMul: NumFastIselFailFMul++; return;
+  case Instruction::UDiv: NumFastIselFailUDiv++; return;
+  case Instruction::SDiv: NumFastIselFailSDiv++; return;
+  case Instruction::FDiv: NumFastIselFailFDiv++; return;
+  case Instruction::URem: NumFastIselFailURem++; return;
+  case Instruction::SRem: NumFastIselFailSRem++; return;
+  case Instruction::FRem: NumFastIselFailFRem++; return;
+
+  // Logical operators...
+  case Instruction::And: NumFastIselFailAnd++; return;
+  case Instruction::Or:  NumFastIselFailOr++; return;
+  case Instruction::Xor: NumFastIselFailXor++; return;
+
+  // Memory instructions...
+  case Instruction::Alloca:        NumFastIselFailAlloca++; return;
+  case Instruction::Load:          NumFastIselFailLoad++; return;
+  case Instruction::Store:         NumFastIselFailStore++; return;
+  case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
+  case Instruction::AtomicRMW:     NumFastIselFailAtomicRMW++; return;
+  case Instruction::Fence:         NumFastIselFailFence++; return;
+  case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
+
+  // Convert instructions...
+  case Instruction::Trunc:    NumFastIselFailTrunc++; return;
+  case Instruction::ZExt:     NumFastIselFailZExt++; return;
+  case Instruction::SExt:     NumFastIselFailSExt++; return;
+  case Instruction::FPTrunc:  NumFastIselFailFPTrunc++; return;
+  case Instruction::FPExt:    NumFastIselFailFPExt++; return;
+  case Instruction::FPToUI:   NumFastIselFailFPToUI++; return;
+  case Instruction::FPToSI:   NumFastIselFailFPToSI++; return;
+  case Instruction::UIToFP:   NumFastIselFailUIToFP++; return;
+  case Instruction::SIToFP:   NumFastIselFailSIToFP++; return;
+  case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
+  case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
+  case Instruction::BitCast:  NumFastIselFailBitCast++; return;
+
+  // Other instructions...
+  case Instruction::ICmp:           NumFastIselFailICmp++; return;
+  case Instruction::FCmp:           NumFastIselFailFCmp++; return;
+  case Instruction::PHI:            NumFastIselFailPHI++; return;
+  case Instruction::Select:         NumFastIselFailSelect++; return;
+  case Instruction::Call:           NumFastIselFailCall++; return;
+  case Instruction::Shl:            NumFastIselFailShl++; return;
+  case Instruction::LShr:           NumFastIselFailLShr++; return;
+  case Instruction::AShr:           NumFastIselFailAShr++; return;
+  case Instruction::VAArg:          NumFastIselFailVAArg++; return;
+  case Instruction::ExtractElement: NumFastIselFailExtractElement++; retur=
n;
+  case Instruction::InsertElement:  NumFastIselFailInsertElement++; return;
+  case Instruction::ShuffleVector:  NumFastIselFailShuffleVector++; return;
+  case Instruction::ExtractValue:   NumFastIselFailExtractValue++; return;
+  case Instruction::InsertValue:    NumFastIselFailInsertValue++; return;
+  case Instruction::LandingPad:     NumFastIselFailLandingPad++; return;
+  }
+}
+#endif
+
 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
   // Initialize the Fast-ISel state, if needed.
   FastISel *FastIS =3D 0;
-  if (EnableFastISel)
+  if (TM.Options.EnableFastISel)
     FastIS =3D TLI.createFastISel(*FuncInfo);
=20
   // Iterate over all basic blocks in the function.
@@ -894,13 +1029,16 @@
           FastIS->setLastLocalValue(0);
       }
=20
+      unsigned NumFastIselRemaining =3D std::distance(Begin, End);
       // Do FastISel on as many instructions as possible.
       for (; BI !=3D Begin; --BI) {
         const Instruction *Inst =3D llvm::prior(BI);
=20
         // If we no longer require this instruction, skip it.
-        if (isFoldedOrDeadInstruction(Inst, FuncInfo))
+        if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
+          --NumFastIselRemaining;
           continue;
+        }
=20
         // Bottom-up: reset the insert pos at the top, after any local-val=
ue
         // instructions.
@@ -908,6 +1046,7 @@
=20
         // Try to select the instruction with FastISel.
         if (FastIS->SelectInstruction(Inst)) {
+          --NumFastIselRemaining;
           ++NumFastIselSuccess;
           // If fast isel succeeded, skip over all the folded instructions=
, and
           // then see if there is a load right before the selected instruc=
tions.
@@ -920,15 +1059,23 @@
           }
           if (BeforeInst !=3D Inst && isa<LoadInst>(BeforeInst) &&
               BeforeInst->hasOneUse() &&
-              TryToFoldFastISelLoad(cast<LoadInst>(BeforeInst), Inst, Fast=
IS))
+              TryToFoldFastISelLoad(cast<LoadInst>(BeforeInst), Inst, Fast=
IS)) {
             // If we succeeded, don't re-select the load.
             BI =3D llvm::next(BasicBlock::const_iterator(BeforeInst));
+            --NumFastIselRemaining;
+            ++NumFastIselSuccess;
+          }
           continue;
         }
=20
+#ifndef NDEBUG
+        if (EnableFastISelVerbose2)
+          collectFailStats(Inst);
+#endif
+
         // Then handle certain instructions as single-LLVM-Instruction blo=
cks.
         if (isa<CallInst>(Inst)) {
-          ++NumFastIselFailures;
+
           if (EnableFastISelVerbose || EnableFastISelAbort) {
             dbgs() << "FastISel missed call: ";
             Inst->dump();
@@ -943,24 +1090,30 @@
           bool HadTailCall =3D false;
           SelectBasicBlock(Inst, BI, HadTailCall);
=20
+          // Recompute NumFastIselRemaining as Selection DAG instruction
+          // selection may have handled the call, input args, etc.
+          unsigned RemainingNow =3D std::distance(Begin, BI);
+          NumFastIselFailures +=3D NumFastIselRemaining - RemainingNow;
+
           // If the call was emitted as a tail call, we're done with the b=
lock.
           if (HadTailCall) {
             --BI;
             break;
           }
=20
+          NumFastIselRemaining =3D RemainingNow;
           continue;
         }
=20
         if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
           // Don't abort, and use a different message for terminator misse=
s.
-          ++NumFastIselFailures;
+          NumFastIselFailures +=3D NumFastIselRemaining;
           if (EnableFastISelVerbose || EnableFastISelAbort) {
             dbgs() << "FastISel missed terminator: ";
             Inst->dump();
           }
         } else {
-          ++NumFastIselFailures;
+          NumFastIselFailures +=3D NumFastIselRemaining;
           if (EnableFastISelVerbose || EnableFastISelAbort) {
             dbgs() << "FastISel miss: ";
             Inst->dump();
@@ -1289,7 +1442,7 @@
   APInt NeededMask =3D DesiredMask & ~ActualMask;
=20
   APInt KnownZero, KnownOne;
-  CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
+  CurDAG->ComputeMaskedBits(LHS, KnownZero, KnownOne);
=20
   // If all the missing bits in the or are already known to be set, match!
   if ((NeededMask & KnownOne) =3D=3D NeededMask)
@@ -2025,6 +2178,7 @@
   case ISD::EntryToken:       // These nodes remain the same.
   case ISD::BasicBlock:
   case ISD::Register:
+  case ISD::RegisterMask:
   //case ISD::VALUETYPE:
   //case ISD::CONDCODE:
   case ISD::HANDLENODE:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/SelectionDAGPrinter.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/SelectionDAGPrinter.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -19,7 +19,6 @@
 #include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetMachine.h"
@@ -28,7 +27,6 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/StringExtras.h"
-#include "llvm/Config/config.h"
 using namespace llvm;
=20
 namespace llvm {
@@ -148,7 +146,7 @@
 void SelectionDAG::viewGraph(const std::string &Title) {
 // This code is only for debugging!
 #ifndef NDEBUG
-  ViewGraph(this, "dag." + getMachineFunction().getFunction()->getNameStr(=
),
+  ViewGraph(this, "dag." + getMachineFunction().getFunction()->getName(),
             false, Title);
 #else
   errs() << "SelectionDAG::viewGraph is only available in debug builds on "
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Selectio=
nDAG/TargetLowering.cpp
--- a/head/contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -36,31 +36,9 @@
 /// - the promotion of vector elements. This feature is disabled by default
 /// and only enabled using this flag.
 static cl::opt<bool>
-AllowPromoteIntElem("promote-elements", cl::Hidden,
+AllowPromoteIntElem("promote-elements", cl::Hidden, cl::init(true),
   cl::desc("Allow promotion of integer vector element types"));
=20
-namespace llvm {
-TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc) {
-  bool isLocal =3D GV->hasLocalLinkage();
-  bool isDeclaration =3D GV->isDeclaration();
-  // FIXME: what should we do for protected and internal visibility?
-  // For variables, is internal different from hidden?
-  bool isHidden =3D GV->hasHiddenVisibility();
-
-  if (reloc =3D=3D Reloc::PIC_) {
-    if (isLocal || isHidden)
-      return TLSModel::LocalDynamic;
-    else
-      return TLSModel::GeneralDynamic;
-  } else {
-    if (!isDeclaration || isHidden)
-      return TLSModel::LocalExec;
-    else
-      return TLSModel::InitialExec;
-  }
-}
-}
-
 /// InitLibcallNames - Set default libcall names.
 ///
 static void InitLibcallNames(const char **Names) {
@@ -572,21 +550,42 @@
   // ConstantFP nodes default to expand.  Targets can either change this to
   // Legal, in which case all fp constants are legal, or use isFPImmLegal()
   // to optimize expansions for certain constants.
+  setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
   setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
=20
   // These library functions default to expand.
-  setOperationAction(ISD::FLOG , MVT::f64, Expand);
-  setOperationAction(ISD::FLOG2, MVT::f64, Expand);
-  setOperationAction(ISD::FLOG10,MVT::f64, Expand);
-  setOperationAction(ISD::FEXP , MVT::f64, Expand);
-  setOperationAction(ISD::FEXP2, MVT::f64, Expand);
-  setOperationAction(ISD::FLOG , MVT::f32, Expand);
-  setOperationAction(ISD::FLOG2, MVT::f32, Expand);
-  setOperationAction(ISD::FLOG10,MVT::f32, Expand);
-  setOperationAction(ISD::FEXP , MVT::f32, Expand);
-  setOperationAction(ISD::FEXP2, MVT::f32, Expand);
+  setOperationAction(ISD::FLOG ,  MVT::f16, Expand);
+  setOperationAction(ISD::FLOG2,  MVT::f16, Expand);
+  setOperationAction(ISD::FLOG10, MVT::f16, Expand);
+  setOperationAction(ISD::FEXP ,  MVT::f16, Expand);
+  setOperationAction(ISD::FEXP2,  MVT::f16, Expand);
+  setOperationAction(ISD::FFLOOR, MVT::f16, Expand);
+  setOperationAction(ISD::FNEARBYINT, MVT::f16, Expand);
+  setOperationAction(ISD::FCEIL,  MVT::f16, Expand);
+  setOperationAction(ISD::FRINT,  MVT::f16, Expand);
+  setOperationAction(ISD::FTRUNC, MVT::f16, Expand);
+  setOperationAction(ISD::FLOG ,  MVT::f32, Expand);
+  setOperationAction(ISD::FLOG2,  MVT::f32, Expand);
+  setOperationAction(ISD::FLOG10, MVT::f32, Expand);
+  setOperationAction(ISD::FEXP ,  MVT::f32, Expand);
+  setOperationAction(ISD::FEXP2,  MVT::f32, Expand);
+  setOperationAction(ISD::FFLOOR, MVT::f32, Expand);
+  setOperationAction(ISD::FNEARBYINT, MVT::f32, Expand);
+  setOperationAction(ISD::FCEIL,  MVT::f32, Expand);
+  setOperationAction(ISD::FRINT,  MVT::f32, Expand);
+  setOperationAction(ISD::FTRUNC, MVT::f32, Expand);
+  setOperationAction(ISD::FLOG ,  MVT::f64, Expand);
+  setOperationAction(ISD::FLOG2,  MVT::f64, Expand);
+  setOperationAction(ISD::FLOG10, MVT::f64, Expand);
+  setOperationAction(ISD::FEXP ,  MVT::f64, Expand);
+  setOperationAction(ISD::FEXP2,  MVT::f64, Expand);
+  setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
+  setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
+  setOperationAction(ISD::FCEIL,  MVT::f64, Expand);
+  setOperationAction(ISD::FRINT,  MVT::f64, Expand);
+  setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
=20
   // Default ISD::TRAP to expand (which turns it into abort).
   setOperationAction(ISD::TRAP, MVT::Other, Expand);
@@ -610,7 +609,7 @@
   ExceptionSelectorRegister =3D 0;
   BooleanContents =3D UndefinedBooleanContent;
   BooleanVectorContents =3D UndefinedBooleanContent;
-  SchedPreferenceInfo =3D Sched::Latency;
+  SchedPreferenceInfo =3D Sched::ILP;
   JumpBufSize =3D 0;
   JumpBufAlignment =3D 0;
   MinFunctionAlignment =3D 0;
@@ -1080,8 +1079,12 @@
 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
                                                  SelectionDAG &DAG) const {
   // If our PIC model is GP relative, use the global offset table as the b=
ase.
-  if (getJumpTableEncoding() =3D=3D MachineJumpTableInfo::EK_GPRel32BlockA=
ddress)
+  unsigned JTEncoding =3D getJumpTableEncoding();
+
+  if ((JTEncoding =3D=3D MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
+      (JTEncoding =3D=3D MachineJumpTableInfo::EK_GPRel32BlockAddress))
     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
+
   return Table;
 }
=20
@@ -1223,7 +1226,7 @@
     if (Depth !=3D 0) {
       // If not at the root, Just compute the KnownZero/KnownOne bits to
       // simplify things downstream.
-      TLO.DAG.ComputeMaskedBits(Op, DemandedMask, KnownZero, KnownOne, Dep=
th);
+      TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
       return false;
     }
     // If this is the root being simplified, allow it to have multiple use=
s,
@@ -1242,8 +1245,8 @@
   switch (Op.getOpcode()) {
   case ISD::Constant:
     // We know all of the bits for a constant!
-    KnownOne =3D cast<ConstantSDNode>(Op)->getAPIntValue() & NewMask;
-    KnownZero =3D ~KnownOne & NewMask;
+    KnownOne =3D cast<ConstantSDNode>(Op)->getAPIntValue();
+    KnownZero =3D ~KnownOne;
     return false;   // Don't fall through, will infinitely loop.
   case ISD::AND:
     // If the RHS is a constant, check to see if the LHS would be zero wit=
hout
@@ -1253,8 +1256,7 @@
     if (ConstantSDNode *RHSC =3D dyn_cast<ConstantSDNode>(Op.getOperand(1)=
)) {
       APInt LHSZero, LHSOne;
       // Do not increment Depth here; that can cause an infinite loop.
-      TLO.DAG.ComputeMaskedBits(Op.getOperand(0), NewMask,
-                                LHSZero, LHSOne, Depth);
+      TLO.DAG.ComputeMaskedBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
       // If the LHS already has zeros where RHSC does, this and is dead.
       if ((LHSZero & NewMask) =3D=3D (~RHSC->getAPIntValue() & NewMask))
         return TLO.CombineTo(Op, Op.getOperand(0));
@@ -1473,9 +1475,8 @@
       if (InOp.getNode()->getOpcode() =3D=3D ISD::ANY_EXTEND) {
         SDValue InnerOp =3D InOp.getNode()->getOperand(0);
         EVT InnerVT =3D InnerOp.getValueType();
-        if ((APInt::getHighBitsSet(BitWidth,
-                                   BitWidth - InnerVT.getSizeInBits()) &
-               DemandedMask) =3D=3D 0 &&
+        unsigned InnerBits =3D InnerVT.getSizeInBits();
+        if (ShAmt < InnerBits && NewMask.lshr(InnerBits) =3D=3D 0 &&
             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
           EVT ShTy =3D getShiftAmountTy(InnerVT);
           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
@@ -1545,7 +1546,7 @@
     // always convert this into a logical shr, even if the shift amount is
     // variable.  The low bit of the shift cannot be an input sign bit unl=
ess
     // the shift amount is >=3D the size of the datatype, which is undefin=
ed.
-    if (DemandedMask =3D=3D 1)
+    if (NewMask =3D=3D 1)
       return TLO.CombineTo(Op,
                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
                                            Op.getOperand(0), Op.getOperand=
(1)));
@@ -1588,23 +1589,40 @@
     }
     break;
   case ISD::SIGN_EXTEND_INREG: {
-    EVT EVT =3D cast<VTSDNode>(Op.getOperand(1))->getVT();
+    EVT ExVT =3D cast<VTSDNode>(Op.getOperand(1))->getVT();
+
+    APInt MsbMask =3D APInt::getHighBitsSet(BitWidth, 1);
+    // If we only care about the highest bit, don't bother shifting right.
+    if (MsbMask =3D=3D DemandedMask) {
+      unsigned ShAmt =3D ExVT.getScalarType().getSizeInBits();
+      SDValue InOp =3D Op.getOperand(0);
+
+      // Compute the correct shift amount type, which must be getShiftAmou=
ntTy
+      // for scalar types after legalization.
+      EVT ShiftAmtTy =3D Op.getValueType();
+      if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
+        ShiftAmtTy =3D getShiftAmountTy(ShiftAmtTy);
+
+      SDValue ShiftAmt =3D TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtT=
y);
+      return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
+                                            Op.getValueType(), InOp, Shift=
Amt));
+    }
=20
     // Sign extension.  Compute the demanded bits in the result that are n=
ot
     // present in the input.
     APInt NewBits =3D
       APInt::getHighBitsSet(BitWidth,
-                            BitWidth - EVT.getScalarType().getSizeInBits()=
);
+                            BitWidth - ExVT.getScalarType().getSizeInBits(=
));
=20
     // If none of the extended bits are demanded, eliminate the sextinreg.
     if ((NewBits & NewMask) =3D=3D 0)
       return TLO.CombineTo(Op, Op.getOperand(0));
=20
     APInt InSignBit =3D
-      APInt::getSignBit(EVT.getScalarType().getSizeInBits()).zext(BitWidth=
);
+      APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidt=
h);
     APInt InputDemandedBits =3D
       APInt::getLowBitsSet(BitWidth,
-                           EVT.getScalarType().getSizeInBits()) &
+                           ExVT.getScalarType().getSizeInBits()) &
       NewMask;
=20
     // Since the sign extended bits are demanded, we know that the sign
@@ -1622,7 +1640,7 @@
     // If the input sign bit is known zero, convert this into a zero exten=
sion.
     if (KnownZero.intersects(InSignBit))
       return TLO.CombineTo(Op,
-                           TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,=
EVT));
+                          TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,E=
xVT));
=20
     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
       KnownOne |=3D NewBits;
@@ -1688,11 +1706,11 @@
=20
     // If the sign bit is known one, the top bits match.
     if (KnownOne.intersects(InSignBit)) {
-      KnownOne  |=3D NewBits;
-      KnownZero &=3D ~NewBits;
+      KnownOne |=3D NewBits;
+      assert((KnownZero & NewBits) =3D=3D 0);
     } else {   // Otherwise, top bits aren't known.
-      KnownOne  &=3D ~NewBits;
-      KnownZero &=3D ~NewBits;
+      assert((KnownOne & NewBits) =3D=3D 0);
+      assert((KnownZero & NewBits) =3D=3D 0);
     }
     break;
   }
@@ -1783,7 +1801,9 @@
   case ISD::BITCAST:
     // If this is an FP->Int bitcast and if the sign bit is the only
     // thing demanded, turn this into a FGETSIGN.
-    if (!Op.getOperand(0).getValueType().isVector() &&
+    if (!TLO.LegalOperations() &&
+        !Op.getValueType().isVector() &&
+        !Op.getOperand(0).getValueType().isVector() &&
         NewMask =3D=3D APInt::getSignBit(Op.getValueType().getSizeInBits()=
) &&
         Op.getOperand(0).getValueType().isFloatingPoint()) {
       bool OpVTLegal =3D isOperationLegalOrCustom(ISD::FGETSIGN, Op.getVal=
ueType());
@@ -1824,7 +1844,7 @@
   // FALL THROUGH
   default:
     // Just use ComputeMaskedBits to compute output bits.
-    TLO.DAG.ComputeMaskedBits(Op, NewMask, KnownZero, KnownOne, Depth);
+    TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
     break;
   }
=20
@@ -1840,7 +1860,6 @@
 /// in Mask are known to be either zero or one and return them in the
 /// KnownZero/KnownOne bitsets.
 void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
-                                                    const APInt &Mask,
                                                     APInt &KnownZero,
                                                     APInt &KnownOne,
                                                     const SelectionDAG &DA=
G,
@@ -1851,7 +1870,7 @@
           Op.getOpcode() =3D=3D ISD::INTRINSIC_VOID) &&
          "Should use MaskedValueIsZero if you don't know whether Op"
          " is a target node!");
-  KnownZero =3D KnownOne =3D APInt(Mask.getBitWidth(), 0);
+  KnownZero =3D KnownOne =3D APInt(KnownOne.getBitWidth(), 0);
 }
=20
 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
@@ -1895,9 +1914,8 @@
   // Fall back to ComputeMaskedBits to catch other known cases.
   EVT OpVT =3D Val.getValueType();
   unsigned BitWidth =3D OpVT.getScalarType().getSizeInBits();
-  APInt Mask =3D APInt::getAllOnesValue(BitWidth);
   APInt KnownZero, KnownOne;
-  DAG.ComputeMaskedBits(Val, Mask, KnownZero, KnownOne);
+  DAG.ComputeMaskedBits(Val, KnownZero, KnownOne);
   return (KnownZero.countPopulation() =3D=3D BitWidth - 1) &&
          (KnownOne.countPopulation() =3D=3D 1);
 }
@@ -2060,7 +2078,7 @@
           unsigned NewAlign =3D MinAlign(Lod->getAlignment(), bestOffset);
           SDValue NewLoad =3D DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
                                 Lod->getPointerInfo().getWithOffset(bestOf=
fset),
-                                        false, false, NewAlign);
+                                        false, false, false, NewAlign);
           return DAG.getSetCC(dl, VT,
                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
                                       DAG.getConstant(bestMask.trunc(bestW=
idth),
@@ -2393,8 +2411,15 @@
=20
   if (N0 =3D=3D N1) {
     // We can always fold X =3D=3D X for integer setcc's.
-    if (N0.getValueType().isInteger())
-      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
+    if (N0.getValueType().isInteger()) {
+      switch (getBooleanContents(N0.getValueType().isVector())) {
+      case UndefinedBooleanContent:=20
+      case ZeroOrOneBooleanContent:=20
+        return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
+      case ZeroOrNegativeOneBooleanContent:
+        return DAG.getConstant(ISD::isTrueWhenEqual(Cond) ? -1 : 0, VT);
+      }
+    }
     unsigned UOF =3D ISD::getUnorderedFlavor(Cond);
     if (UOF =3D=3D 2)   // FP operators that are undefined on NaNs.
       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
@@ -2428,6 +2453,10 @@
         }
       }
=20
+      // If RHS is a legal immediate value for a compare instruction, we n=
eed
+      // to be careful about increasing register pressure needlessly.
+      bool LegalRHSImm =3D false;
+
       if (ConstantSDNode *RHSC =3D dyn_cast<ConstantSDNode>(N1)) {
         if (ConstantSDNode *LHSR =3D dyn_cast<ConstantSDNode>(N0.getOperan=
d(1))) {
           // Turn (X+C1) =3D=3D C2 --> X =3D=3D C2-C1
@@ -2462,25 +2491,33 @@
                            Cond);
           }
         }
+
+        // Could RHSC fold directly into a compare?
+        if (RHSC->getValueType(0).getSizeInBits() <=3D 64)
+          LegalRHSImm =3D isLegalICmpImmediate(RHSC->getSExtValue());
       }
=20
       // Simplify (X+Z) =3D=3D X -->  Z =3D=3D 0
-      if (N0.getOperand(0) =3D=3D N1)
-        return DAG.getSetCC(dl, VT, N0.getOperand(1),
-                        DAG.getConstant(0, N0.getValueType()), Cond);
-      if (N0.getOperand(1) =3D=3D N1) {
-        if (DAG.isCommutativeBinOp(N0.getOpcode()))
-          return DAG.getSetCC(dl, VT, N0.getOperand(0),
-                          DAG.getConstant(0, N0.getValueType()), Cond);
-        else if (N0.getNode()->hasOneUse()) {
-          assert(N0.getOpcode() =3D=3D ISD::SUB && "Unexpected operation!"=
);
-          // (Z-X) =3D=3D X  --> Z =3D=3D X<<1
-          SDValue SH =3D DAG.getNode(ISD::SHL, dl, N1.getValueType(),
-                                     N1,
+      // Don't do this if X is an immediate that can fold into a cmp
+      // instruction and X+Z has other uses. It could be an induction vari=
able
+      // chain, and the transform would increase register pressure.
+      if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
+        if (N0.getOperand(0) =3D=3D N1)
+          return DAG.getSetCC(dl, VT, N0.getOperand(1),
+                              DAG.getConstant(0, N0.getValueType()), Cond);
+        if (N0.getOperand(1) =3D=3D N1) {
+          if (DAG.isCommutativeBinOp(N0.getOpcode()))
+            return DAG.getSetCC(dl, VT, N0.getOperand(0),
+                                DAG.getConstant(0, N0.getValueType()), Con=
d);
+          else if (N0.getNode()->hasOneUse()) {
+            assert(N0.getOpcode() =3D=3D ISD::SUB && "Unexpected operation=
!");
+            // (Z-X) =3D=3D X  --> Z =3D=3D X<<1
+            SDValue SH =3D DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
                        DAG.getConstant(1, getShiftAmountTy(N1.getValueType=
())));
-          if (!DCI.isCalledByLegalizer())
-            DCI.AddToWorklist(SH.getNode());
-          return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
+            if (!DCI.isCalledByLegalizer())
+              DCI.AddToWorklist(SH.getNode());
+            return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
+          }
         }
       }
     }
@@ -2984,7 +3021,6 @@
 /// is.
 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT)=
 {
   switch (CT) {
-  default: llvm_unreachable("Unknown constraint type!");
   case TargetLowering::C_Other:
   case TargetLowering::C_Unknown:
     return 0;
@@ -2995,6 +3031,7 @@
   case TargetLowering::C_Memory:
     return 3;
   }
+  llvm_unreachable("Invalid constraint type");
 }
=20
 /// Examine constraint type and operand type and determine a weight value.
@@ -3242,8 +3279,9 @@
 /// return a DAG expression to select that will generate the same value by
 /// multiplying by a magic number.  See:
 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
-SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
-                                  std::vector<SDNode*>* Created) const {
+SDValue TargetLowering::
+BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
+          std::vector<SDNode*>* Created) const {
   EVT VT =3D N->getValueType(0);
   DebugLoc dl=3D N->getDebugLoc();
=20
@@ -3258,10 +3296,12 @@
   // Multiply the numerator (operand 0) by the magic value
   // FIXME: We should support doing a MUL in a wider type
   SDValue Q;
-  if (isOperationLegalOrCustom(ISD::MULHS, VT))
+  if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
+                            isOperationLegalOrCustom(ISD::MULHS, VT))
     Q =3D DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
                     DAG.getConstant(magics.m, VT));
-  else if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
+  else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
+                                 isOperationLegalOrCustom(ISD::SMUL_LOHI, =
VT))
     Q =3D SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
                               N->getOperand(0),
                               DAG.getConstant(magics.m, VT)).getNode(), 1);
@@ -3299,8 +3339,9 @@
 /// return a DAG expression to select that will generate the same value by
 /// multiplying by a magic number.  See:
 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
-SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
-                                  std::vector<SDNode*>* Created) const {
+SDValue TargetLowering::
+BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
+          std::vector<SDNode*>* Created) const {
   EVT VT =3D N->getValueType(0);
   DebugLoc dl =3D N->getDebugLoc();
=20
@@ -3332,9 +3373,11 @@
=20
   // Multiply the numerator (operand 0) by the magic value
   // FIXME: We should support doing a MUL in a wider type
-  if (isOperationLegalOrCustom(ISD::MULHU, VT))
+  if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
+                            isOperationLegalOrCustom(ISD::MULHU, VT))
     Q =3D DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT)=
);
-  else if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
+  else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
+                                 isOperationLegalOrCustom(ISD::UMUL_LOHI, =
VT))
     Q =3D SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
                             DAG.getConstant(magics.m, VT)).getNode(), 1);
   else
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/ShadowSt=
ackGC.cpp
--- a/head/contrib/llvm/lib/CodeGen/ShadowStackGC.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ShadowStackGC.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -116,8 +116,7 @@
           // Branches and invokes do not escape, only unwind, resume, and =
return
           // do.
           TerminatorInst *TI =3D CurBB->getTerminator();
-          if (!isa<UnwindInst>(TI) && !isa<ReturnInst>(TI) &&
-              !isa<ResumeInst>(TI))
+          if (!isa<ReturnInst>(TI) && !isa<ResumeInst>(TI))
             continue;
=20
           Builder.SetInsertPoint(TI->getParent(), TI);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/ShrinkWr=
apping.cpp
--- a/head/contrib/llvm/lib/CodeGen/ShrinkWrapping.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/ShrinkWrapping.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -93,6 +93,7 @@
   }
   AU.addPreserved<MachineLoopInfo>();
   AU.addPreserved<MachineDominatorTree>();
+  AU.addRequired<TargetPassConfig>();
   MachineFunctionPass::getAnalysisUsage(AU);
 }
=20
@@ -124,7 +125,7 @@
 }
=20
 bool PEI::isReturnBlock(MachineBasicBlock* MBB) {
-  return (MBB && !MBB->empty() && MBB->back().getDesc().isReturn());
+  return (MBB && !MBB->empty() && MBB->back().isReturn());
 }
=20
 // Initialize shrink wrapping DFA sets, called before iterations.
@@ -158,7 +159,7 @@
   // via --shrink-wrap-func=3D<funcname>.
 #ifndef NDEBUG
   if (ShrinkWrapFunc !=3D "") {
-    std::string MFName =3D MF->getFunction()->getNameStr();
+    std::string MFName =3D MF->getFunction()->getName().str();
     ShrinkWrapThisFunction =3D (MFName =3D=3D ShrinkWrapFunc);
   }
 #endif
@@ -1045,7 +1046,7 @@
     return "";
=20
   if (MBB->getBasicBlock())
-    return MBB->getBasicBlock()->getNameStr();
+    return MBB->getBasicBlock()->getName().str();
=20
   std::ostringstream name;
   name << "_MBB_" << MBB->getNumber();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/SjLjEHPr=
epare.cpp
--- a/head/contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SjLjEHPrepare.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----=
------=3D=3D=3D//
+//=3D=3D=3D- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions --=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -29,21 +29,20 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/IRBuilder.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
 #include <set>
 using namespace llvm;
=20
-static cl::opt<bool> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
-    cl::desc("Disable the old SjLj EH preparation pass"));
-
 STATISTIC(NumInvokes, "Number of invokes replaced");
-STATISTIC(NumUnwinds, "Number of unwinds replaced");
 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
=20
 namespace {
-  class SjLjEHPass : public FunctionPass {
+  class SjLjEHPrepare : public FunctionPass {
     const TargetLowering *TLI;
     Type *FunctionContextTy;
     Constant *RegisterFn;
@@ -54,16 +53,12 @@
     Constant *StackRestoreFn;
     Constant *LSDAAddrFn;
     Value *PersonalityFn;
-    Constant *SelectorFn;
-    Constant *ExceptionFn;
     Constant *CallSiteFn;
-    Constant *DispatchSetupFn;
     Constant *FuncCtxFn;
-    Value *CallSite;
-    DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
+    AllocaInst *FuncCtx;
   public:
     static char ID; // Pass identification, replacement for typeid
-    explicit SjLjEHPass(const TargetLowering *tli =3D NULL)
+    explicit SjLjEHPrepare(const TargetLowering *tli =3D NULL)
       : FunctionPass(ID), TLI(tli) { }
     bool doInitialization(Module &M);
     bool runOnFunction(Function &F);
@@ -75,28 +70,24 @@
=20
   private:
     bool setupEntryBlockAndCallSites(Function &F);
+    void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
+                              Value *SelVal);
     Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPa=
ds);
     void lowerIncomingArguments(Function &F);
     void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes=
);
-
-    void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
-    void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
-                            SwitchInst *CatchSwitch);
-    void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes=
);
-    void splitLandingPad(InvokeInst *II);
-    bool insertSjLjEHSupport(Function &F);
+    void insertCallSiteStore(Instruction *I, int Number);
   };
 } // end anonymous namespace
=20
-char SjLjEHPass::ID =3D 0;
+char SjLjEHPrepare::ID =3D 0;
=20
-// Public Interface To the SjLjEHPass pass.
-FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
-  return new SjLjEHPass(TLI);
+// Public Interface To the SjLjEHPrepare pass.
+FunctionPass *llvm::createSjLjEHPreparePass(const TargetLowering *TLI) {
+  return new SjLjEHPrepare(TLI);
 }
 // doInitialization - Set up decalarations and types needed to process
 // exceptions.
-bool SjLjEHPass::doInitialization(Module &M) {
+bool SjLjEHPrepare::doInitialization(Module &M) {
   // Build the function context structure.
   // builtin_setjmp uses a five word jbuf
   Type *VoidPtrTy =3D Type::getInt8PtrTy(M.getContext());
@@ -123,11 +114,7 @@
   StackRestoreFn =3D Intrinsic::getDeclaration(&M, Intrinsic::stackrestore=
);
   BuiltinSetjmpFn =3D Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_set=
jmp);
   LSDAAddrFn =3D Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
-  SelectorFn =3D Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
-  ExceptionFn =3D Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
   CallSiteFn =3D Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite=
);
-  DispatchSetupFn
-    =3D Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
   FuncCtxFn =3D Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functionc=
ontext);
   PersonalityFn =3D 0;
=20
@@ -136,583 +123,67 @@
=20
 /// insertCallSiteStore - Insert a store of the call-site value to the
 /// function context
-void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
-                                     Value *CallSite) {
+void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
+  IRBuilder<> Builder(I);
+
+  // Get a reference to the call_site field.
+  Type *Int32Ty =3D Type::getInt32Ty(I->getContext());
+  Value *Zero =3D ConstantInt::get(Int32Ty, 0);
+  Value *One =3D ConstantInt::get(Int32Ty, 1);
+  Value *Idxs[2] =3D { Zero, One };
+  Value *CallSite =3D Builder.CreateGEP(FuncCtx, Idxs, "call_site");
+
+  // Insert a store of the call-site number
   ConstantInt *CallSiteNoC =3D ConstantInt::get(Type::getInt32Ty(I->getCon=
text()),
                                               Number);
-  // Insert a store of the call-site number
-  new StoreInst(CallSiteNoC, CallSite, true, I);  // volatile
-}
-
-/// splitLandingPad - Split a landing pad. This takes considerable care be=
cause
-/// of PHIs and other nasties. The problem is that the jump table needs to=
 jump
-/// to the landing pad block. However, the landing pad block can be jumped=
 to
-/// only by an invoke instruction. So we clone the landingpad instruction =
into
-/// its own basic block, have the invoke jump to there. The landingpad
-/// instruction's basic block's successor is now the target for the jump t=
able.
-///
-/// But because of PHI nodes, we need to create another basic block for th=
e jump
-/// table to jump to. This is definitely a hack, because the values for th=
e PHI
-/// nodes may not be defined on the edge from the jump table. But that's o=
kay,
-/// because the jump table is simply a construct to mimic what is happenin=
g in
-/// the CFG. So the values are mysteriously there, even though there is no=
 value
-/// for the PHI from the jump table's edge (hence calling this a hack).
-void SjLjEHPass::splitLandingPad(InvokeInst *II) {
-  SmallVector<BasicBlock*, 2> NewBBs;
-  SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
-                              ".1", ".2", this, NewBBs);
-
-  // Create an empty block so that the jump table has something to jump to
-  // which doesn't have any PHI nodes.
-  BasicBlock *LPad =3D NewBBs[0];
-  BasicBlock *Succ =3D *succ_begin(LPad);
-  BasicBlock *JumpTo =3D BasicBlock::Create(II->getContext(), "jt.land",
-                                          LPad->getParent(), Succ);
-  LPad->getTerminator()->eraseFromParent();
-  BranchInst::Create(JumpTo, LPad);
-  BranchInst::Create(Succ, JumpTo);
-  LPadSuccMap[II] =3D JumpTo;
-
-  for (BasicBlock::iterator I =3D Succ->begin(); isa<PHINode>(I); ++I) {
-    PHINode *PN =3D cast<PHINode>(I);
-    Value *Val =3D PN->removeIncomingValue(LPad, false);
-    PN->addIncoming(Val, JumpTo);
-  }
-}
-
-/// markInvokeCallSite - Insert code to mark the call_site for this invoke
-void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
-                                    Value *CallSite,
-                                    SwitchInst *CatchSwitch) {
-  ConstantInt *CallSiteNoC=3D ConstantInt::get(Type::getInt32Ty(II->getCon=
text()),
-                                              InvokeNo);
-  // The runtime comes back to the dispatcher with the call_site - 1 in
-  // the context. Odd, but there it is.
-  ConstantInt *SwitchValC =3D ConstantInt::get(Type::getInt32Ty(II->getCon=
text()),
-                                             InvokeNo - 1);
-
-  // If the unwind edge has phi nodes, split the edge.
-  if (isa<PHINode>(II->getUnwindDest()->begin())) {
-    // FIXME: New EH - This if-condition will be always true in the new sc=
heme.
-    if (II->getUnwindDest()->isLandingPad())
-      splitLandingPad(II);
-    else
-      SplitCriticalEdge(II, 1, this);
-
-    // If there are any phi nodes left, they must have a single predecesso=
r.
-    while (PHINode *PN =3D dyn_cast<PHINode>(II->getUnwindDest()->begin())=
) {
-      PN->replaceAllUsesWith(PN->getIncomingValue(0));
-      PN->eraseFromParent();
-    }
-  }
-
-  // Insert the store of the call site value
-  insertCallSiteStore(II, InvokeNo, CallSite);
-
-  // Record the call site value for the back end so it stays associated wi=
th
-  // the invoke.
-  CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
-
-  // Add a switch case to our unwind block.
-  if (BasicBlock *SuccBB =3D LPadSuccMap[II]) {
-    CatchSwitch->addCase(SwitchValC, SuccBB);
-  } else {
-    CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
-  }
-
-  // We still want this to look like an invoke so we emit the LSDA properl=
y,
-  // so we don't transform the invoke into a call here.
+  Builder.CreateStore(CallSiteNoC, CallSite, true/*volatile*/);
 }
=20
 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs=
 until
 /// we reach blocks we've already seen.
-static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBB=
s) {
-  if (!LiveBBs.insert(BB).second) return; // already been here.
+static void MarkBlocksLiveIn(BasicBlock *BB,
+                             SmallPtrSet<BasicBlock*, 64> &LiveBBs) {
+  if (!LiveBBs.insert(BB)) return; // already been here.
=20
   for (pred_iterator PI =3D pred_begin(BB), E =3D pred_end(BB); PI !=3D E;=
 ++PI)
     MarkBlocksLiveIn(*PI, LiveBBs);
 }
=20
-/// splitLiveRangesAcrossInvokes - Each value that is live across an unwin=
d edge
-/// we spill into a stack location, guaranteeing that there is nothing live
-/// across the unwind edge.  This process also splits all critical edges
-/// coming out of invoke's.
-/// FIXME: Move this function to a common utility file (Local.cpp?) so
-/// both SjLj and LowerInvoke can use it.
-void SjLjEHPass::
-splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
-  // First step, split all critical edges from invoke instructions.
-  for (unsigned i =3D 0, e =3D Invokes.size(); i !=3D e; ++i) {
-    InvokeInst *II =3D Invokes[i];
-    SplitCriticalEdge(II, 0, this);
-
-    // FIXME: New EH - This if-condition will be always true in the new sc=
heme.
-    if (II->getUnwindDest()->isLandingPad())
-      splitLandingPad(II);
-    else
-      SplitCriticalEdge(II, 1, this);
-
-    assert(!isa<PHINode>(II->getNormalDest()) &&
-           !isa<PHINode>(II->getUnwindDest()) &&
-           "Critical edge splitting left single entry phi nodes?");
+/// substituteLPadValues - Substitute the values returned by the landingpad
+/// instruction with those returned by the personality function.
+void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVa=
l,
+                                         Value *SelVal) {
+  SmallVector<Value*, 8> UseWorkList(LPI->use_begin(), LPI->use_end());
+  while (!UseWorkList.empty()) {
+    Value *Val =3D UseWorkList.pop_back_val();
+    ExtractValueInst *EVI =3D dyn_cast<ExtractValueInst>(Val);
+    if (!EVI) continue;
+    if (EVI->getNumIndices() !=3D 1) continue;
+    if (*EVI->idx_begin() =3D=3D 0)
+      EVI->replaceAllUsesWith(ExnVal);
+    else if (*EVI->idx_begin() =3D=3D 1)
+      EVI->replaceAllUsesWith(SelVal);
+    if (EVI->getNumUses() =3D=3D 0)
+      EVI->eraseFromParent();
   }
=20
-  Function *F =3D Invokes.back()->getParent()->getParent();
+  if (LPI->getNumUses() =3D=3D 0)  return;
=20
-  // To avoid having to handle incoming arguments specially, we lower each=
 arg
-  // to a copy instruction in the entry block.  This ensures that the argu=
ment
-  // value itself cannot be live across the entry block.
-  BasicBlock::iterator AfterAllocaInsertPt =3D F->begin()->begin();
-  while (isa<AllocaInst>(AfterAllocaInsertPt) &&
-        isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySi=
ze()))
-    ++AfterAllocaInsertPt;
-  for (Function::arg_iterator AI =3D F->arg_begin(), E =3D F->arg_end();
-       AI !=3D E; ++AI) {
-    Type *Ty =3D AI->getType();
-    // Aggregate types can't be cast, but are legal argument types, so we =
have
-    // to handle them differently. We use an extract/insert pair as a
-    // lightweight method to achieve the same goal.
-    if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
-      Instruction *EI =3D ExtractValueInst::Create(AI, 0, "",AfterAllocaIn=
sertPt);
-      Instruction *NI =3D InsertValueInst::Create(AI, EI, 0);
-      NI->insertAfter(EI);
-      AI->replaceAllUsesWith(NI);
-      // Set the operand of the instructions back to the AllocaInst.
-      EI->setOperand(0, AI);
-      NI->setOperand(0, AI);
-    } else {
-      // This is always a no-op cast because we're casting AI to AI->getTy=
pe()
-      // so src and destination types are identical. BitCast is the only
-      // possibility.
-      CastInst *NC =3D new BitCastInst(
-        AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
-      AI->replaceAllUsesWith(NC);
-      // Set the operand of the cast instruction back to the AllocaInst.
-      // Normally it's forbidden to replace a CastInst's operand because it
-      // could cause the opcode to reflect an illegal conversion. However,
-      // we're replacing it here with the same value it was constructed wi=
th.
-      // We do this because the above replaceAllUsesWith() clobbered the
-      // operand, but we want this one to remain.
-      NC->setOperand(0, AI);
-    }
-  }
+  // There are still some uses of LPI. Construct an aggregate with the exc=
eption
+  // values and replace the LPI with that aggregate.
+  Type *LPadType =3D LPI->getType();
+  Value *LPadVal =3D UndefValue::get(LPadType);
+  IRBuilder<>
+    Builder(llvm::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
+  LPadVal =3D Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
+  LPadVal =3D Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
=20
-  // Finally, scan the code looking for instructions with bad live ranges.
-  for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D E; ++=
BB)
-    for (BasicBlock::iterator II =3D BB->begin(), E =3D BB->end(); II !=3D=
 E; ++II) {
-      // Ignore obvious cases we don't have to handle.  In particular, most
-      // instructions either have no uses or only have a single use inside=
 the
-      // current block.  Ignore them quickly.
-      Instruction *Inst =3D II;
-      if (Inst->use_empty()) continue;
-      if (Inst->hasOneUse() &&
-          cast<Instruction>(Inst->use_back())->getParent() =3D=3D BB &&
-          !isa<PHINode>(Inst->use_back())) continue;
-
-      // If this is an alloca in the entry block, it's not a real register
-      // value.
-      if (AllocaInst *AI =3D dyn_cast<AllocaInst>(Inst))
-        if (isa<ConstantInt>(AI->getArraySize()) && BB =3D=3D F->begin())
-          continue;
-
-      // Avoid iterator invalidation by copying users to a temporary vecto=
r.
-      SmallVector<Instruction*,16> Users;
-      for (Value::use_iterator UI =3D Inst->use_begin(), E =3D Inst->use_e=
nd();
-           UI !=3D E; ++UI) {
-        Instruction *User =3D cast<Instruction>(*UI);
-        if (User->getParent() !=3D BB || isa<PHINode>(User))
-          Users.push_back(User);
-      }
-
-      // Find all of the blocks that this value is live in.
-      std::set<BasicBlock*> LiveBBs;
-      LiveBBs.insert(Inst->getParent());
-      while (!Users.empty()) {
-        Instruction *U =3D Users.back();
-        Users.pop_back();
-
-        if (!isa<PHINode>(U)) {
-          MarkBlocksLiveIn(U->getParent(), LiveBBs);
-        } else {
-          // Uses for a PHI node occur in their predecessor block.
-          PHINode *PN =3D cast<PHINode>(U);
-          for (unsigned i =3D 0, e =3D PN->getNumIncomingValues(); i !=3D =
e; ++i)
-            if (PN->getIncomingValue(i) =3D=3D Inst)
-              MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
-        }
-      }
-
-      // Now that we know all of the blocks that this thing is live in, se=
e if
-      // it includes any of the unwind locations.
-      bool NeedsSpill =3D false;
-      for (unsigned i =3D 0, e =3D Invokes.size(); i !=3D e; ++i) {
-        BasicBlock *UnwindBlock =3D Invokes[i]->getUnwindDest();
-        if (UnwindBlock !=3D BB && LiveBBs.count(UnwindBlock))
-          NeedsSpill =3D true;
-      }
-
-      // If we decided we need a spill, do it.
-      // FIXME: Spilling this way is overkill, as it forces all uses of
-      // the value to be reloaded from the stack slot, even those that are=
n't
-      // in the unwind blocks. We should be more selective.
-      if (NeedsSpill) {
-        ++NumSpilled;
-        DemoteRegToStack(*Inst, true);
-      }
-    }
-}
-
-/// CreateLandingPadLoad - Load the exception handling values and insert t=
hem
-/// into a structure.
-static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
-                                         Value *SelAddr,
-                                         BasicBlock::iterator InsertPt) {
-  Value *Exn =3D new LoadInst(ExnAddr, "exn", false,
-                            InsertPt);
-  Type *Ty =3D Type::getInt8PtrTy(F.getContext());
-  Exn =3D CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
-  Value *Sel =3D new LoadInst(SelAddr, "sel", false, InsertPt);
-
-  Ty =3D StructType::get(Exn->getType(), Sel->getType(), NULL);
-  InsertValueInst *LPadVal =3D InsertValueInst::Create(llvm::UndefValue::g=
et(Ty),
-                                                     Exn, 0,
-                                                     "lpad.val", InsertPt);
-  return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
-}
-
-/// ReplaceLandingPadVal - Replace the landingpad instruction's value with=
 a
-/// load from the stored values (via CreateLandingPadLoad). This looks thr=
ough
-/// PHI nodes, and removes them if they are dead.
-static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *Ex=
nAddr,
-                                 Value *SelAddr) {
-  if (Inst->use_empty()) return;
-
-  while (!Inst->use_empty()) {
-    Instruction *I =3D cast<Instruction>(Inst->use_back());
-
-    if (PHINode *PN =3D dyn_cast<PHINode>(I)) {
-      ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
-      if (PN->use_empty()) PN->eraseFromParent();
-      continue;
-    }
-
-    I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I=
));
-  }
-}
-
-bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
-  SmallVector<ReturnInst*,16> Returns;
-  SmallVector<UnwindInst*,16> Unwinds;
-  SmallVector<InvokeInst*,16> Invokes;
-
-  // Look through the terminators of the basic blocks to find invokes, ret=
urns
-  // and unwinds.
-  for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB=
) {
-    if (ReturnInst *RI =3D dyn_cast<ReturnInst>(BB->getTerminator())) {
-      // Remember all return instructions in case we insert an invoke into=
 this
-      // function.
-      Returns.push_back(RI);
-    } else if (InvokeInst *II =3D dyn_cast<InvokeInst>(BB->getTerminator()=
)) {
-      Invokes.push_back(II);
-    } else if (UnwindInst *UI =3D dyn_cast<UnwindInst>(BB->getTerminator()=
)) {
-      Unwinds.push_back(UI);
-    }
-  }
-
-  NumInvokes +=3D Invokes.size();
-  NumUnwinds +=3D Unwinds.size();
-
-  // If we don't have any invokes, there's nothing to do.
-  if (Invokes.empty()) return false;
-
-  // Find the eh.selector.*, eh.exception and alloca calls.
-  //
-  // Remember any allocas() that aren't in the entry block, as the
-  // jmpbuf saved SP will need to be updated for them.
-  //
-  // We'll use the first eh.selector to determine the right personality
-  // function to use. For SJLJ, we always use the same personality for the
-  // whole function, not on a per-selector basis.
-  // FIXME: That's a bit ugly. Better way?
-  SmallVector<CallInst*,16> EH_Selectors;
-  SmallVector<CallInst*,16> EH_Exceptions;
-  SmallVector<Instruction*,16> JmpbufUpdatePoints;
-
-  for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB=
) {
-    // Note: Skip the entry block since there's nothing there that interes=
ts
-    // us. eh.selector and eh.exception shouldn't ever be there, and we
-    // want to disregard any allocas that are there.
-    //=20
-    // FIXME: This is awkward. The new EH scheme won't need to skip the en=
try
-    //        block.
-    if (BB =3D=3D F.begin()) {
-      if (InvokeInst *II =3D dyn_cast<InvokeInst>(F.begin()->getTerminator=
())) {
-        // FIXME: This will be always non-NULL in the new EH.
-        if (LandingPadInst *LPI =3D II->getUnwindDest()->getLandingPadInst=
())
-          if (!PersonalityFn) PersonalityFn =3D LPI->getPersonalityFn();
-      }
-
-      continue;
-    }
-
-    for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E=
; ++I) {
-      if (CallInst *CI =3D dyn_cast<CallInst>(I)) {
-        if (CI->getCalledFunction() =3D=3D SelectorFn) {
-          if (!PersonalityFn) PersonalityFn =3D CI->getArgOperand(1);
-          EH_Selectors.push_back(CI);
-        } else if (CI->getCalledFunction() =3D=3D ExceptionFn) {
-          EH_Exceptions.push_back(CI);
-        } else if (CI->getCalledFunction() =3D=3D StackRestoreFn) {
-          JmpbufUpdatePoints.push_back(CI);
-        }
-      } else if (AllocaInst *AI =3D dyn_cast<AllocaInst>(I)) {
-        JmpbufUpdatePoints.push_back(AI);
-      } else if (InvokeInst *II =3D dyn_cast<InvokeInst>(I)) {
-        // FIXME: This will be always non-NULL in the new EH.
-        if (LandingPadInst *LPI =3D II->getUnwindDest()->getLandingPadInst=
())
-          if (!PersonalityFn) PersonalityFn =3D LPI->getPersonalityFn();
-      }
-    }
-  }
-
-  // If we don't have any eh.selector calls, we can't determine the person=
ality
-  // function. Without a personality function, we can't process exceptions.
-  if (!PersonalityFn) return false;
-
-  // We have invokes, so we need to add register/unregister calls to get t=
his
-  // function onto the global unwind stack.
-  //
-  // First thing we need to do is scan the whole function for values that =
are
-  // live across unwind edges.  Each value that is live across an unwind e=
dge we
-  // spill into a stack location, guaranteeing that there is nothing live =
across
-  // the unwind edge.  This process also splits all critical edges coming =
out of
-  // invoke's.
-  splitLiveRangesAcrossInvokes(Invokes);
-
-
-  SmallVector<LandingPadInst*, 16> LandingPads;
-  for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB=
) {
-    if (InvokeInst *II =3D dyn_cast<InvokeInst>(BB->getTerminator()))
-      // FIXME: This will be always non-NULL in the new EH.
-      if (LandingPadInst *LPI =3D II->getUnwindDest()->getLandingPadInst())
-        LandingPads.push_back(LPI);
-  }
-
-
-  BasicBlock *EntryBB =3D F.begin();
-  // Create an alloca for the incoming jump buffer ptr and the new jump bu=
ffer
-  // that needs to be restored on all exits from the function.  This is an
-  // alloca because the value needs to be added to the global context list.
-  unsigned Align =3D 4; // FIXME: Should be a TLI check?
-  AllocaInst *FunctionContext =3D
-    new AllocaInst(FunctionContextTy, 0, Align,
-                   "fcn_context", F.begin()->begin());
-
-  Value *Idxs[2];
-  Type *Int32Ty =3D Type::getInt32Ty(F.getContext());
-  Value *Zero =3D ConstantInt::get(Int32Ty, 0);
-  // We need to also keep around a reference to the call_site field
-  Idxs[0] =3D Zero;
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 1);
-  CallSite =3D GetElementPtrInst::Create(FunctionContext, Idxs, "call_site=
",
-                                       EntryBB->getTerminator());
-
-  // The exception selector comes back in context->data[1]
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 2);
-  Value *FCData =3D GetElementPtrInst::Create(FunctionContext, Idxs, "fc_d=
ata",
-                                            EntryBB->getTerminator());
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 1);
-  Value *SelectorAddr =3D GetElementPtrInst::Create(FCData, Idxs,
-                                                  "exc_selector_gep",
-                                                  EntryBB->getTerminator()=
);
-  // The exception value comes back in context->data[0]
-  Idxs[1] =3D Zero;
-  Value *ExceptionAddr =3D GetElementPtrInst::Create(FCData, Idxs,
-                                                   "exception_gep",
-                                                   EntryBB->getTerminator(=
));
-
-  // The result of the eh.selector call will be replaced with a a referenc=
e to
-  // the selector value returned in the function context. We leave the sel=
ector
-  // itself so the EH analysis later can use it.
-  for (int i =3D 0, e =3D EH_Selectors.size(); i < e; ++i) {
-    CallInst *I =3D EH_Selectors[i];
-    Value *SelectorVal =3D new LoadInst(SelectorAddr, "select_val", true, =
I);
-    I->replaceAllUsesWith(SelectorVal);
-  }
-
-  // eh.exception calls are replaced with references to the proper locatio=
n in
-  // the context. Unlike eh.selector, the eh.exception calls are removed
-  // entirely.
-  for (int i =3D 0, e =3D EH_Exceptions.size(); i < e; ++i) {
-    CallInst *I =3D EH_Exceptions[i];
-    // Possible for there to be duplicates, so check to make sure the
-    // instruction hasn't already been removed.
-    if (!I->getParent()) continue;
-    Value *Val =3D new LoadInst(ExceptionAddr, "exception", true, I);
-    Type *Ty =3D Type::getInt8PtrTy(F.getContext());
-    Val =3D CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
-
-    I->replaceAllUsesWith(Val);
-    I->eraseFromParent();
-  }
-
-  for (unsigned i =3D 0, e =3D LandingPads.size(); i !=3D e; ++i)
-    ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
-
-  // The entry block changes to have the eh.sjlj.setjmp, with a conditional
-  // branch to a dispatch block for non-zero returns. If we return normall=
y,
-  // we're not handling an exception and just register the function contex=
t and
-  // continue.
-
-  // Create the dispatch block.  The dispatch block is basically a big swi=
tch
-  // statement that goes to all of the invoke landing pads.
-  BasicBlock *DispatchBlock =3D
-    BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
-
-  // Insert a load of the callsite in the dispatch block, and a switch on =
its
-  // value. By default, we issue a trap statement.
-  BasicBlock *TrapBlock =3D
-    BasicBlock::Create(F.getContext(), "trapbb", &F);
-  CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::tra=
p),
-                   "", TrapBlock);
-  new UnreachableInst(F.getContext(), TrapBlock);
-
-  Value *DispatchLoad =3D new LoadInst(CallSite, "invoke.num", true,
-                                     DispatchBlock);
-  SwitchInst *DispatchSwitch =3D
-    SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
-                       DispatchBlock);
-  // Split the entry block to insert the conditional branch for the setjmp.
-  BasicBlock *ContBlock =3D EntryBB->splitBasicBlock(EntryBB->getTerminato=
r(),
-                                                   "eh.sjlj.setjmp.cont");
-
-  // Populate the Function Context
-  //   1. LSDA address
-  //   2. Personality function address
-  //   3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
-
-  // LSDA address
-  Idxs[0] =3D Zero;
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 4);
-  Value *LSDAFieldPtr =3D
-    GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
-                              EntryBB->getTerminator());
-  Value *LSDA =3D CallInst::Create(LSDAAddrFn, "lsda_addr",
-                                 EntryBB->getTerminator());
-  new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
-
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 3);
-  Value *PersonalityFieldPtr =3D
-    GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
-                              EntryBB->getTerminator());
-  new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
-                EntryBB->getTerminator());
-
-  // Save the frame pointer.
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 5);
-  Value *JBufPtr
-    =3D GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
-                                EntryBB->getTerminator());
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 0);
-  Value *FramePtr =3D
-    GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
-                              EntryBB->getTerminator());
-
-  Value *Val =3D CallInst::Create(FrameAddrFn,
-                                ConstantInt::get(Int32Ty, 0),
-                                "fp",
-                                EntryBB->getTerminator());
-  new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
-
-  // Save the stack pointer.
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 2);
-  Value *StackPtr =3D
-    GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
-                              EntryBB->getTerminator());
-
-  Val =3D CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
-  new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
-
-  // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
-  Value *SetjmpArg =3D
-    CastInst::Create(Instruction::BitCast, JBufPtr,
-                     Type::getInt8PtrTy(F.getContext()), "",
-                     EntryBB->getTerminator());
-  Value *DispatchVal =3D CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
-                                        "",
-                                        EntryBB->getTerminator());
-
-  // Add a call to dispatch_setup after the setjmp call. This is expanded =
to any
-  // target-specific setup that needs to be done.
-  CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminato=
r());
-
-  // check the return value of the setjmp. non-zero goes to dispatcher.
-  Value *IsNormal =3D new ICmpInst(EntryBB->getTerminator(),
-                                 ICmpInst::ICMP_EQ, DispatchVal, Zero,
-                                 "notunwind");
-  // Nuke the uncond branch.
-  EntryBB->getTerminator()->eraseFromParent();
-
-  // Put in a new condbranch in its place.
-  BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
-
-  // Register the function context and make sure it's known to not throw
-  CallInst *Register =3D
-    CallInst::Create(RegisterFn, FunctionContext, "",
-                     ContBlock->getTerminator());
-  Register->setDoesNotThrow();
-
-  // At this point, we are all set up, update the invoke instructions to m=
ark
-  // their call_site values, and fill in the dispatch switch accordingly.
-  for (unsigned i =3D 0, e =3D Invokes.size(); i !=3D e; ++i)
-    markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
-
-  // Mark call instructions that aren't nounwind as no-action (call_site =
=3D=3D
-  // -1). Skip the entry block, as prior to then, no function context has =
been
-  // created for this function and any unexpected exceptions thrown will go
-  // directly to the caller's context, which is what we want anyway, so no=
 need
-  // to do anything here.
-  for (Function::iterator BB =3D F.begin(), E =3D F.end(); ++BB !=3D E;) {
-    for (BasicBlock::iterator I =3D BB->begin(), end =3D BB->end(); I !=3D=
 end; ++I)
-      if (CallInst *CI =3D dyn_cast<CallInst>(I)) {
-        // Ignore calls to the EH builtins (eh.selector, eh.exception)
-        Constant *Callee =3D CI->getCalledFunction();
-        if (Callee !=3D SelectorFn && Callee !=3D ExceptionFn
-            && !CI->doesNotThrow())
-          insertCallSiteStore(CI, -1, CallSite);
-      } else if (ResumeInst *RI =3D dyn_cast<ResumeInst>(I)) {
-        insertCallSiteStore(RI, -1, CallSite);
-      }
-  }
-
-  // Replace all unwinds with a branch to the unwind handler.
-  // ??? Should this ever happen with sjlj exceptions?
-  for (unsigned i =3D 0, e =3D Unwinds.size(); i !=3D e; ++i) {
-    BranchInst::Create(TrapBlock, Unwinds[i]);
-    Unwinds[i]->eraseFromParent();
-  }
-
-  // Following any allocas not in the entry block, update the saved SP in =
the
-  // jmpbuf to the new value.
-  for (unsigned i =3D 0, e =3D JmpbufUpdatePoints.size(); i !=3D e; ++i) {
-    Instruction *AI =3D JmpbufUpdatePoints[i];
-    Instruction *StackAddr =3D CallInst::Create(StackAddrFn, "sp");
-    StackAddr->insertAfter(AI);
-    Instruction *StoreStackAddr =3D new StoreInst(StackAddr, StackPtr, tru=
e);
-    StoreStackAddr->insertAfter(StackAddr);
-  }
-
-  // Finally, for any returns from this function, if this function contain=
s an
-  // invoke, add a call to unregister the function context.
-  for (unsigned i =3D 0, e =3D Returns.size(); i !=3D e; ++i)
-    CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
-
-  return true;
+  LPI->replaceAllUsesWith(LPadVal);
 }
=20
 /// setupFunctionContext - Allocate the function context on the stack and =
fill
 /// it with all of the data that we know at this point.
-Value *SjLjEHPass::
+Value *SjLjEHPrepare::
 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
   BasicBlock *EntryBB =3D F.begin();
=20
@@ -721,56 +192,42 @@
   // because the value needs to be added to the global context list.
   unsigned Align =3D
     TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
-  AllocaInst *FuncCtx =3D
+  FuncCtx =3D
     new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->beg=
in());
=20
   // Fill in the function context structure.
-  Value *Idxs[2];
   Type *Int32Ty =3D Type::getInt32Ty(F.getContext());
   Value *Zero =3D ConstantInt::get(Int32Ty, 0);
   Value *One =3D ConstantInt::get(Int32Ty, 1);
+  Value *Two =3D ConstantInt::get(Int32Ty, 2);
+  Value *Three =3D ConstantInt::get(Int32Ty, 3);
+  Value *Four =3D ConstantInt::get(Int32Ty, 4);
=20
-  // Keep around a reference to the call_site field.
-  Idxs[0] =3D Zero;
-  Idxs[1] =3D One;
-  CallSite =3D GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
-                                       EntryBB->getTerminator());
-
-  // Reference the __data field.
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 2);
-  Value *FCData =3D GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
-                                            EntryBB->getTerminator());
-
-  // The exception value comes back in context->__data[0].
-  Idxs[1] =3D Zero;
-  Value *ExceptionAddr =3D GetElementPtrInst::Create(FCData, Idxs,
-                                                   "exception_gep",
-                                                   EntryBB->getTerminator(=
));
-
-  // The exception selector comes back in context->__data[1].
-  Idxs[1] =3D One;
-  Value *SelectorAddr =3D GetElementPtrInst::Create(FCData, Idxs,
-                                                  "exn_selector_gep",
-                                                  EntryBB->getTerminator()=
);
+  Value *Idxs[2] =3D { Zero, 0 };
=20
   for (unsigned I =3D 0, E =3D LPads.size(); I !=3D E; ++I) {
     LandingPadInst *LPI =3D LPads[I];
     IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
=20
+    // Reference the __data field.
+    Idxs[1] =3D Two;
+    Value *FCData =3D Builder.CreateGEP(FuncCtx, Idxs, "__data");
+
+    // The exception values come back in context->__data[0].
+    Idxs[1] =3D Zero;
+    Value *ExceptionAddr =3D Builder.CreateGEP(FCData, Idxs, "exception_ge=
p");
     Value *ExnVal =3D Builder.CreateLoad(ExceptionAddr, true, "exn_val");
     ExnVal =3D Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getCont=
ext()));
+
+    Idxs[1] =3D One;
+    Value *SelectorAddr =3D Builder.CreateGEP(FCData, Idxs, "exn_selector_=
gep");
     Value *SelVal =3D Builder.CreateLoad(SelectorAddr, true, "exn_selector=
_val");
=20
-    Type *LPadType =3D LPI->getType();
-    Value *LPadVal =3D UndefValue::get(LPadType);
-    LPadVal =3D Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
-    LPadVal =3D Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
-
-    LPI->replaceAllUsesWith(LPadVal);
+    substituteLPadValues(LPI, ExnVal, SelVal);
   }
=20
   // Personality function
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 3);
+  Idxs[1] =3D Three;
   if (!PersonalityFn)
     PersonalityFn =3D LPads[0]->getPersonalityFn();
   Value *PersonalityFieldPtr =3D
@@ -780,11 +237,11 @@
                 EntryBB->getTerminator());
=20
   // LSDA address
-  Idxs[1] =3D ConstantInt::get(Int32Ty, 4);
+  Value *LSDA =3D CallInst::Create(LSDAAddrFn, "lsda_addr",
+                                 EntryBB->getTerminator());
+  Idxs[1] =3D Four;
   Value *LSDAFieldPtr =3D GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_g=
ep",
                                                   EntryBB->getTerminator()=
);
-  Value *LSDA =3D CallInst::Create(LSDAAddrFn, "lsda_addr",
-                                 EntryBB->getTerminator());
   new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
=20
   return FuncCtx;
@@ -794,7 +251,7 @@
 /// specially, we lower each arg to a copy instruction in the entry block.=
 This
 /// ensures that the argument value itself cannot be live out of the entry
 /// block.
-void SjLjEHPass::lowerIncomingArguments(Function &F) {
+void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
   BasicBlock::iterator AfterAllocaInsPt =3D F.begin()->begin();
   while (isa<AllocaInst>(AfterAllocaInsPt) &&
          isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize=
()))
@@ -838,8 +295,8 @@
=20
 /// lowerAcrossUnwindEdges - Find all variables which are alive across an =
unwind
 /// edge and spill them.
-void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
-                                        ArrayRef<InvokeInst*> Invokes) {
+void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
+                                           ArrayRef<InvokeInst*> Invokes) {
   // Finally, scan the code looking for instructions with bad live ranges.
   for (Function::iterator
          BB =3D F.begin(), BBE =3D F.end(); BB !=3D BBE; ++BB) {
@@ -870,7 +327,7 @@
       }
=20
       // Find all of the blocks that this value is live in.
-      std::set<BasicBlock*> LiveBBs;
+      SmallPtrSet<BasicBlock*, 64> LiveBBs;
       LiveBBs.insert(Inst->getParent());
       while (!Users.empty()) {
         Instruction *U =3D Users.back();
@@ -893,7 +350,10 @@
       for (unsigned i =3D 0, e =3D Invokes.size(); i !=3D e; ++i) {
         BasicBlock *UnwindBlock =3D Invokes[i]->getUnwindDest();
         if (UnwindBlock !=3D BB && LiveBBs.count(UnwindBlock)) {
+          DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
+                << UnwindBlock->getName() << "\n");
           NeedsSpill =3D true;
+          break;
         }
       }
=20
@@ -902,36 +362,60 @@
       // the value to be reloaded from the stack slot, even those that are=
n't
       // in the unwind blocks. We should be more selective.
       if (NeedsSpill) {
+        DemoteRegToStack(*Inst, true);
         ++NumSpilled;
-        DemoteRegToStack(*Inst, true);
       }
     }
   }
+
+  // Go through the landing pads and remove any PHIs there.
+  for (unsigned i =3D 0, e =3D Invokes.size(); i !=3D e; ++i) {
+    BasicBlock *UnwindBlock =3D Invokes[i]->getUnwindDest();
+    LandingPadInst *LPI =3D UnwindBlock->getLandingPadInst();
+
+    // Place PHIs into a set to avoid invalidating the iterator.
+    SmallPtrSet<PHINode*, 8> PHIsToDemote;
+    for (BasicBlock::iterator
+           PN =3D UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
+      PHIsToDemote.insert(cast<PHINode>(PN));
+    if (PHIsToDemote.empty()) continue;
+
+    // Demote the PHIs to the stack.
+    for (SmallPtrSet<PHINode*, 8>::iterator
+           I =3D PHIsToDemote.begin(), E =3D PHIsToDemote.end(); I !=3D E;=
 ++I)
+      DemotePHIToStack(*I);
+
+    // Move the landingpad instruction back to the top of the landing pad =
block.
+    LPI->moveBefore(UnwindBlock->begin());
+  }
 }
=20
 /// setupEntryBlockAndCallSites - Setup the entry block by creating and fi=
lling
 /// the function context and marking the call sites with the appropriate
 /// values. These values are used by the DWARF EH emitter.
-bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
+bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
   SmallVector<ReturnInst*,     16> Returns;
   SmallVector<InvokeInst*,     16> Invokes;
-  SmallVector<LandingPadInst*, 16> LPads;
+  SmallSetVector<LandingPadInst*, 16> LPads;
=20
   // Look through the terminators of the basic blocks to find invokes.
   for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB)
     if (InvokeInst *II =3D dyn_cast<InvokeInst>(BB->getTerminator())) {
       Invokes.push_back(II);
-      LPads.push_back(II->getUnwindDest()->getLandingPadInst());
+      LPads.insert(II->getUnwindDest()->getLandingPadInst());
     } else if (ReturnInst *RI =3D dyn_cast<ReturnInst>(BB->getTerminator()=
)) {
       Returns.push_back(RI);
     }
=20
   if (Invokes.empty()) return false;
=20
+  NumInvokes +=3D Invokes.size();
+
   lowerIncomingArguments(F);
   lowerAcrossUnwindEdges(F, Invokes);
=20
-  Value *FuncCtx =3D setupFunctionContext(F, LPads);
+  Value *FuncCtx =3D
+    setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
   BasicBlock *EntryBB =3D F.begin();
   Type *Int32Ty =3D Type::getInt32Ty(F.getContext());
=20
@@ -979,7 +463,7 @@
   // At this point, we are all set up, update the invoke instructions to m=
ark
   // their call_site values.
   for (unsigned I =3D 0, E =3D Invokes.size(); I !=3D E; ++I) {
-    insertCallSiteStore(Invokes[I], I + 1, CallSite);
+    insertCallSiteStore(Invokes[I], I + 1);
=20
     ConstantInt *CallSiteNum =3D
       ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
@@ -998,9 +482,9 @@
     for (BasicBlock::iterator I =3D BB->begin(), end =3D BB->end(); I !=3D=
 end; ++I)
       if (CallInst *CI =3D dyn_cast<CallInst>(I)) {
         if (!CI->doesNotThrow())
-          insertCallSiteStore(CI, -1, CallSite);
+          insertCallSiteStore(CI, -1);
       } else if (ResumeInst *RI =3D dyn_cast<ResumeInst>(I)) {
-        insertCallSiteStore(RI, -1, CallSite);
+        insertCallSiteStore(RI, -1);
       }
=20
   // Register the function context and make sure it's known to not throw
@@ -1008,6 +492,25 @@
                                         EntryBB->getTerminator());
   Register->setDoesNotThrow();
=20
+  // Following any allocas not in the entry block, update the saved SP in =
the
+  // jmpbuf to the new value.
+  for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB=
) {
+    if (BB =3D=3D F.begin())
+      continue;
+    for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E=
; ++I) {
+      if (CallInst *CI =3D dyn_cast<CallInst>(I)) {
+        if (CI->getCalledFunction() !=3D StackRestoreFn)
+          continue;
+      } else if (!isa<AllocaInst>(I)) {
+        continue;
+      }
+      Instruction *StackAddr =3D CallInst::Create(StackAddrFn, "sp");
+      StackAddr->insertAfter(I);
+      Instruction *StoreStackAddr =3D new StoreInst(StackAddr, StackPtr, t=
rue);
+      StoreStackAddr->insertAfter(StackAddr);
+    }
+  }
+
   // Finally, for any returns from this function, if this function contain=
s an
   // invoke, add a call to unregister the function context.
   for (unsigned I =3D 0, E =3D Returns.size(); I !=3D E; ++I)
@@ -1016,11 +519,7 @@
   return true;
 }
=20
-bool SjLjEHPass::runOnFunction(Function &F) {
-  bool Res =3D false;
-  if (!DisableOldSjLjEH)
-    Res =3D insertSjLjEHSupport(F);
-  else
-    Res =3D setupEntryBlockAndCallSites(F);
+bool SjLjEHPrepare::runOnFunction(Function &F) {
+  bool Res =3D setupEntryBlockAndCallSites(F);
   return Res;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/SlotInde=
xes.cpp
--- a/head/contrib/llvm/lib/CodeGen/SlotIndexes.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/CodeGen/SlotIndexes.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -76,7 +76,7 @@
     MachineBasicBlock *mbb =3D &*mbbItr;
=20
     // Insert an index for the MBB start.
-    SlotIndex blockStartIndex(back(), SlotIndex::LOAD);
+    SlotIndex blockStartIndex(back(), SlotIndex::Slot_Block);
=20
     for (MachineBasicBlock::iterator miItr =3D mbb->begin(), miEnd =3D mbb=
->end();
          miItr !=3D miEnd; ++miItr) {
@@ -88,7 +88,8 @@
       push_back(createEntry(mi, index +=3D SlotIndex::InstrDist));
=20
       // Save this base index in the maps.
-      mi2iMap.insert(std::make_pair(mi, SlotIndex(back(), SlotIndex::LOAD)=
));
+      mi2iMap.insert(std::make_pair(mi, SlotIndex(back(),
+                                                  SlotIndex::Slot_Block)));
 =20
       ++functionSize;
     }
@@ -97,14 +98,15 @@
     push_back(createEntry(0, index +=3D SlotIndex::InstrDist));
=20
     MBBRanges[mbb->getNumber()].first =3D blockStartIndex;
-    MBBRanges[mbb->getNumber()].second =3D SlotIndex(back(), SlotIndex::LO=
AD);
+    MBBRanges[mbb->getNumber()].second =3D SlotIndex(back(),
+                                                   SlotIndex::Slot_Block);
     idx2MBBMap.push_back(IdxMBBPair(blockStartIndex, mbb));
   }
=20
   // Sort the Idx2MBBMap
   std::sort(idx2MBBMap.begin(), idx2MBBMap.end(), Idx2MBBCompare());
=20
-  DEBUG(dump());
+  DEBUG(mf->print(dbgs(), this));
=20
   // And we're done!
   return false;
@@ -166,7 +168,7 @@
 // Print a SlotIndex to a raw_ostream.
 void SlotIndex::print(raw_ostream &os) const {
   if (isValid())
-    os << entry().getIndex() << "LudS"[getSlot()];
+    os << entry().getIndex() << "Berd"[getSlot()];
   else
     os << "invalid";
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Spiller.=
cpp
--- a/head/contrib/llvm/lib/CodeGen/Spiller.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/CodeGen/Spiller.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -11,8 +11,8 @@
=20
 #include "Spiller.h"
 #include "VirtRegMap.h"
-#include "LiveRangeEdit.h"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "llvm/CodeGen/LiveRangeEdit.h"
 #include "llvm/CodeGen/LiveStackAnalysis.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
@@ -29,7 +29,7 @@
 using namespace llvm;
=20
 namespace {
-  enum SpillerName { trivial, standard, inline_ };
+  enum SpillerName { trivial, inline_ };
 }
=20
 static cl::opt<SpillerName>
@@ -37,10 +37,9 @@
            cl::desc("Spiller to use: (default: standard)"),
            cl::Prefix,
            cl::values(clEnumVal(trivial,   "trivial spiller"),
-                      clEnumVal(standard,  "default spiller"),
                       clEnumValN(inline_,  "inline", "inline spiller"),
                       clEnumValEnd),
-           cl::init(standard));
+           cl::init(trivial));
=20
 // Spiller virtual destructor implementation.
 Spiller::~Spiller() {}
@@ -73,8 +72,9 @@
   /// Add spill ranges for every use/def of the live interval, inserting l=
oads
   /// immediately before each use, and stores after each def. No folding or
   /// remat is attempted.
-  void trivialSpillEverywhere(LiveInterval *li,
-                              SmallVectorImpl<LiveInterval*> &newIntervals=
) {
+  void trivialSpillEverywhere(LiveRangeEdit& LRE) {
+    LiveInterval* li =3D &LRE.getParent();
+
     DEBUG(dbgs() << "Spilling everywhere " << *li << "\n");
=20
     assert(li->weight !=3D HUGE_VALF &&
@@ -116,17 +116,14 @@
       }
=20
       // Create a new vreg & interval for this instr.
-      unsigned newVReg =3D mri->createVirtualRegister(trc);
-      vrm->grow();
-      vrm->assignVirt2StackSlot(newVReg, ss);
-      LiveInterval *newLI =3D &lis->getOrCreateInterval(newVReg);
+      LiveInterval *newLI =3D &LRE.create();
       newLI->weight =3D HUGE_VALF;
=20
       // Update the reg operands & kill flags.
       for (unsigned i =3D 0; i < indices.size(); ++i) {
         unsigned mopIdx =3D indices[i];
         MachineOperand &mop =3D mi->getOperand(mopIdx);
-        mop.setReg(newVReg);
+        mop.setReg(newLI->reg);
         if (mop.isUse() && !mi->isRegTiedToDefOperand(mopIdx)) {
           mop.setIsKill(true);
         }
@@ -136,33 +133,29 @@
       // Insert reload if necessary.
       MachineBasicBlock::iterator miItr(mi);
       if (hasUse) {
-        tii->loadRegFromStackSlot(*mi->getParent(), miItr, newVReg, ss, tr=
c,
+        tii->loadRegFromStackSlot(*mi->getParent(), miItr, newLI->reg, ss,=
 trc,
                                   tri);
         MachineInstr *loadInstr(prior(miItr));
         SlotIndex loadIndex =3D
-          lis->InsertMachineInstrInMaps(loadInstr).getDefIndex();
-        vrm->addSpillSlotUse(ss, loadInstr);
+          lis->InsertMachineInstrInMaps(loadInstr).getRegSlot();
         SlotIndex endIndex =3D loadIndex.getNextIndex();
         VNInfo *loadVNI =3D
-          newLI->getNextValue(loadIndex, 0, lis->getVNInfoAllocator());
+          newLI->getNextValue(loadIndex, lis->getVNInfoAllocator());
         newLI->addRange(LiveRange(loadIndex, endIndex, loadVNI));
       }
=20
       // Insert store if necessary.
       if (hasDef) {
-        tii->storeRegToStackSlot(*mi->getParent(), llvm::next(miItr), newV=
Reg,
+        tii->storeRegToStackSlot(*mi->getParent(), llvm::next(miItr),newLI=
->reg,
                                  true, ss, trc, tri);
         MachineInstr *storeInstr(llvm::next(miItr));
         SlotIndex storeIndex =3D
-          lis->InsertMachineInstrInMaps(storeInstr).getDefIndex();
-        vrm->addSpillSlotUse(ss, storeInstr);
+          lis->InsertMachineInstrInMaps(storeInstr).getRegSlot();
         SlotIndex beginIndex =3D storeIndex.getPrevIndex();
         VNInfo *storeVNI =3D
-          newLI->getNextValue(beginIndex, 0, lis->getVNInfoAllocator());
+          newLI->getNextValue(beginIndex, lis->getVNInfoAllocator());
         newLI->addRange(LiveRange(beginIndex, storeIndex, storeVNI));
       }
-
-      newIntervals.push_back(newLI);
     }
   }
 };
@@ -182,60 +175,20 @@
=20
   void spill(LiveRangeEdit &LRE) {
     // Ignore spillIs - we don't use it.
-    trivialSpillEverywhere(&LRE.getParent(), *LRE.getNewVRegs());
+    trivialSpillEverywhere(LRE);
   }
 };
=20
 } // end anonymous namespace
=20
-namespace {
-
-/// Falls back on LiveIntervals::addIntervalsForSpills.
-class StandardSpiller : public Spiller {
-protected:
-  MachineFunction *mf;
-  LiveIntervals *lis;
-  LiveStacks *lss;
-  MachineLoopInfo *loopInfo;
-  VirtRegMap *vrm;
-public:
-  StandardSpiller(MachineFunctionPass &pass, MachineFunction &mf,
-                  VirtRegMap &vrm)
-    : mf(&mf),
-      lis(&pass.getAnalysis<LiveIntervals>()),
-      lss(&pass.getAnalysis<LiveStacks>()),
-      loopInfo(pass.getAnalysisIfAvailable<MachineLoopInfo>()),
-      vrm(&vrm) {}
-
-  /// Falls back on LiveIntervals::addIntervalsForSpills.
-  void spill(LiveRangeEdit &LRE) {
-    std::vector<LiveInterval*> added =3D
-      lis->addIntervalsForSpills(LRE.getParent(), LRE.getUselessVRegs(),
-                                 loopInfo, *vrm);
-    LRE.getNewVRegs()->insert(LRE.getNewVRegs()->end(),
-                              added.begin(), added.end());
-
-    // Update LiveStacks.
-    int SS =3D vrm->getStackSlot(LRE.getReg());
-    if (SS =3D=3D VirtRegMap::NO_STACK_SLOT)
-      return;
-    const TargetRegisterClass *RC =3D mf->getRegInfo().getRegClass(LRE.get=
Reg());
-    LiveInterval &SI =3D lss->getOrCreateInterval(SS, RC);
-    if (!SI.hasAtLeastOneValue())
-      SI.getNextValue(SlotIndex(), 0, lss->getVNInfoAllocator());
-    SI.MergeRangesInAsValue(LRE.getParent(), SI.getValNumInfo(0));
-  }
-};
-
-} // end anonymous namespace
+void Spiller::anchor() { }
=20
 llvm::Spiller* llvm::createSpiller(MachineFunctionPass &pass,
                                    MachineFunction &mf,
                                    VirtRegMap &vrm) {
   switch (spillerOpt) {
-  default: assert(0 && "unknown spiller");
   case trivial: return new TrivialSpiller(pass, mf, vrm);
-  case standard: return new StandardSpiller(pass, mf, vrm);
   case inline_: return createInlineSpiller(pass, mf, vrm);
   }
+  llvm_unreachable("Invalid spiller optimization");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/Spiller.h
--- a/head/contrib/llvm/lib/CodeGen/Spiller.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/Spiller.h	Tue Apr 17 11:51:51 2012 +0300
@@ -22,6 +22,7 @@
   /// Implementations are utility classes which insert spill or remat code=
 on
   /// demand.
   class Spiller {
+    virtual void anchor();
   public:
     virtual ~Spiller() =3D 0;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/SplitKit=
.cpp
--- a/head/contrib/llvm/lib/CodeGen/SplitKit.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/CodeGen/SplitKit.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -14,10 +14,10 @@
=20
 #define DEBUG_TYPE "regalloc"
 #include "SplitKit.h"
-#include "LiveRangeEdit.h"
 #include "VirtRegMap.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
+#include "llvm/CodeGen/LiveRangeEdit.h"
 #include "llvm/CodeGen/MachineDominators.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineLoopInfo.h"
@@ -62,13 +62,14 @@
   const MachineBasicBlock *MBB =3D MF.getBlockNumbered(Num);
   const MachineBasicBlock *LPad =3D MBB->getLandingPadSuccessor();
   std::pair<SlotIndex, SlotIndex> &LSP =3D LastSplitPoint[Num];
+  SlotIndex MBBEnd =3D LIS.getMBBEndIdx(MBB);
=20
   // Compute split points on the first call. The pair is independent of the
   // current live interval.
   if (!LSP.first.isValid()) {
     MachineBasicBlock::const_iterator FirstTerm =3D MBB->getFirstTerminato=
r();
     if (FirstTerm =3D=3D MBB->end())
-      LSP.first =3D LIS.getMBBEndIdx(MBB);
+      LSP.first =3D MBBEnd;
     else
       LSP.first =3D LIS.getInstructionIndex(FirstTerm);
=20
@@ -80,7 +81,7 @@
     for (MachineBasicBlock::const_iterator I =3D MBB->end(), E =3D MBB->be=
gin();
          I !=3D E;) {
       --I;
-      if (I->getDesc().isCall()) {
+      if (I->isCall()) {
         LSP.second =3D LIS.getInstructionIndex(I);
         break;
       }
@@ -89,10 +90,32 @@
=20
   // If CurLI is live into a landing pad successor, move the last split po=
int
   // back to the call that may throw.
-  if (LPad && LSP.second.isValid() && LIS.isLiveInToMBB(*CurLI, LPad))
-    return LSP.second;
-  else
+  if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad))
     return LSP.first;
+
+  // Find the value leaving MBB.
+  const VNInfo *VNI =3D CurLI->getVNInfoBefore(MBBEnd);
+  if (!VNI)
+    return LSP.first;
+
+  // If the value leaving MBB was defined after the call in MBB, it can't
+  // really be live-in to the landing pad.  This can happen if the landing=
 pad
+  // has a PHI, and this register is undef on the exceptional edge.
+  // <rdar://problem/10664933>
+  if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEn=
d)
+    return LSP.first;
+
+  // Value is properly live-in to the landing pad.
+  // Only allow splits before the call.
+  return LSP.second;
+}
+
+MachineBasicBlock::iterator
+SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) {
+  SlotIndex LSP =3D getLastSplitPoint(MBB->getNumber());
+  if (LSP =3D=3D LIS.getMBBEndIdx(MBB))
+    return MBB->end();
+  return LIS.getInstructionFromIndex(LSP);
 }
=20
 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
@@ -112,7 +135,7 @@
        I =3D MRI.use_nodbg_begin(CurLI->reg), E =3D MRI.use_nodbg_end(); I=
 !=3D E;
        ++I)
     if (!I.getOperand().isUndef())
-      UseSlots.push_back(LIS.getInstructionIndex(&*I).getDefIndex());
+      UseSlots.push_back(LIS.getInstructionIndex(&*I).getRegSlot());
=20
   array_pod_sort(UseSlots.begin(), UseSlots.end());
=20
@@ -328,7 +351,7 @@
=20
   // We don't need an AliasAnalysis since we will only be performing
   // cheap-as-a-copy remats anyway.
-  Edit->anyRematerializable(LIS, TII, 0);
+  Edit->anyRematerializable(0);
 }
=20
 void SplitEditor::dump() const {
@@ -351,7 +374,7 @@
   LiveInterval *LI =3D Edit->get(RegIdx);
=20
   // Create a new value.
-  VNInfo *VNI =3D LI->getNextValue(Idx, 0, LIS.getVNInfoAllocator());
+  VNInfo *VNI =3D LI->getNextValue(Idx, LIS.getVNInfoAllocator());
=20
   // Use insert for lookup, so we can add missing values with a second loo=
kup.
   std::pair<ValueMap::iterator, bool> InsP =3D
@@ -366,14 +389,14 @@
   // If the previous value was a simple mapping, add liveness for it now.
   if (VNInfo *OldVNI =3D InsP.first->second.getPointer()) {
     SlotIndex Def =3D OldVNI->def;
-    LI->addRange(LiveRange(Def, Def.getNextSlot(), OldVNI));
+    LI->addRange(LiveRange(Def, Def.getDeadSlot(), OldVNI));
     // No longer a simple mapping.  Switch to a complex, non-forced mappin=
g.
     InsP.first->second =3D ValueForcePair();
   }
=20
   // This is a complex mapping, add liveness for VNI
   SlotIndex Def =3D VNI->def;
-  LI->addRange(LiveRange(Def, Def.getNextSlot(), VNI));
+  LI->addRange(LiveRange(Def, Def.getDeadSlot(), VNI));
=20
   return VNI;
 }
@@ -393,7 +416,7 @@
   // This was previously a single mapping. Make sure the old def is repres=
ented
   // by a trivial live range.
   SlotIndex Def =3D VNI->def;
-  Edit->get(RegIdx)->addRange(LiveRange(Def, Def.getNextSlot(), VNI));
+  Edit->get(RegIdx)->addRange(LiveRange(Def, Def.getDeadSlot(), VNI));
   // Mark as complex mapped, forced.
   VFP =3D ValueForcePair(0, true);
 }
@@ -413,33 +436,31 @@
=20
   // Attempt cheap-as-a-copy rematerialization.
   LiveRangeEdit::Remat RM(ParentVNI);
-  if (Edit->canRematerializeAt(RM, UseIdx, true, LIS)) {
-    Def =3D Edit->rematerializeAt(MBB, I, LI->reg, RM, LIS, TII, TRI, Late=
);
+  if (Edit->canRematerializeAt(RM, UseIdx, true)) {
+    Def =3D Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
     ++NumRemats;
   } else {
     // Can't remat, just insert a copy from parent.
     CopyMI =3D BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI=
->reg)
                .addReg(Edit->getReg());
     Def =3D LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late)
-            .getDefIndex();
+            .getRegSlot();
     ++NumCopies;
   }
=20
   // Define the value in Reg.
-  VNInfo *VNI =3D defValue(RegIdx, ParentVNI, Def);
-  VNI->setCopy(CopyMI);
-  return VNI;
+  return defValue(RegIdx, ParentVNI, Def);
 }
=20
 /// Create a new virtual register and live interval.
 unsigned SplitEditor::openIntv() {
   // Create the complement as index 0.
   if (Edit->empty())
-    Edit->create(LIS, VRM);
+    Edit->create();
=20
   // Create the open interval.
   OpenIdx =3D Edit->size();
-  Edit->create(LIS, VRM);
+  Edit->create();
   return OpenIdx;
 }
=20
@@ -497,7 +518,7 @@
   }
   DEBUG(dbgs() << ": valno " << ParentVNI->id);
   VNInfo *VNI =3D defFromParent(OpenIdx, ParentVNI, Last, MBB,
-                              LIS.getLastSplitPoint(Edit->getParent(), &MB=
B));
+                              SA.getLastSplitPointIter(&MBB));
   RegAssign.insert(VNI->def, End, OpenIdx);
   DEBUG(dump());
   return VNI->def;
@@ -586,7 +607,7 @@
 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
   assert(OpenIdx && "openIntv not called before overlapIntv");
   const VNInfo *ParentVNI =3D Edit->getParent().getVNInfoAt(Start);
-  assert(ParentVNI =3D=3D Edit->getParent().getVNInfoAt(End.getPrevSlot())=
 &&
+  assert(ParentVNI =3D=3D Edit->getParent().getVNInfoBefore(End) &&
          "Parent changes value in extended range");
   assert(LIS.getMBBFromIndex(Start) =3D=3D LIS.getMBBFromIndex(End) &&
          "Range cannot span basic blocks");
@@ -640,7 +661,7 @@
       DEBUG(dbgs() << "  cannot find simple kill of RegIdx " << RegIdx << =
'\n');
       forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
     } else {
-      SlotIndex Kill =3D LIS.getInstructionIndex(MBBI).getDefIndex();
+      SlotIndex Kill =3D LIS.getInstructionIndex(MBBI).getRegSlot();
       DEBUG(dbgs() << "  move kill to " << Kill << '\t' << *MBBI);
       AssignI.setStop(Kill);
     }
@@ -780,7 +801,7 @@
     SlotIndex Last =3D LIS.getMBBEndIdx(Dom.first).getPrevSlot();
     Dom.second =3D
       defFromParent(0, ParentVNI, Last, *Dom.first,
-                    LIS.getLastSplitPoint(Edit->getParent(), Dom.first))->=
def;
+                    SA.getLastSplitPointIter(Dom.first))->def;
   }
=20
   // Remove redundant back-copies that are now known to be dominated by an=
other
@@ -958,7 +979,7 @@
     // use the same register as the def, so just do that always.
     SlotIndex Idx =3D LIS.getInstructionIndex(MI);
     if (MO.isDef() || MO.isUndef())
-      Idx =3D MO.isEarlyClobber() ? Idx.getUseIndex() : Idx.getDefIndex();
+      Idx =3D Idx.getRegSlot(MO.isEarlyClobber());
=20
     // Rewrite to the mapped register at Idx.
     unsigned RegIdx =3D RegAssign.lookup(Idx);
@@ -981,7 +1002,7 @@
       if (!Edit->getParent().liveAt(Idx))
         continue;
     } else
-      Idx =3D Idx.getUseIndex();
+      Idx =3D Idx.getRegSlot(true);
=20
     getLRCalc(RegIdx).extend(LI, Idx.getNextSlot(), LIS.getSlotIndexes(),
                              &MDT, &LIS.getVNInfoAllocator());
@@ -994,8 +1015,8 @@
     LiveInterval *LI =3D *I;
     for (LiveInterval::const_iterator LII =3D LI->begin(), LIE =3D LI->end=
();
            LII !=3D LIE; ++LII) {
-      // Dead defs end at the store slot.
-      if (LII->end !=3D LII->valno->def.getNextSlot())
+      // Dead defs end at the dead slot.
+      if (LII->end !=3D LII->valno->def.getDeadSlot())
         continue;
       MachineInstr *MI =3D LIS.getInstructionFromIndex(LII->valno->def);
       assert(MI && "Missing instruction for dead def");
@@ -1012,7 +1033,7 @@
   if (Dead.empty())
     return;
=20
-  Edit->eliminateDeadDefs(Dead, LIS, VRM, TII);
+  Edit->eliminateDeadDefs(Dead);
 }
=20
 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
@@ -1030,7 +1051,6 @@
     unsigned RegIdx =3D RegAssign.lookup(ParentVNI->def);
     VNInfo *VNI =3D defValue(RegIdx, ParentVNI, ParentVNI->def);
     VNI->setIsPHIDef(ParentVNI->isPHIDef());
-    VNI->setCopy(ParentVNI->getCopy());
=20
     // Force rematted values to be recomputed everywhere.
     // The new live ranges may be truncated.
@@ -1049,7 +1069,6 @@
     break;
   case SM_Speed:
     llvm_unreachable("Spill mode 'speed' not implemented yet");
-    break;
   }
=20
   // Transfer the simply mapped values, check if any are skipped.
@@ -1089,7 +1108,7 @@
     SmallVector<LiveInterval*, 8> dups;
     dups.push_back(li);
     for (unsigned j =3D 1; j !=3D NumComp; ++j)
-      dups.push_back(&Edit->create(LIS, VRM));
+      dups.push_back(&Edit->create());
     ConEQ.Distribute(&dups[0], MRI);
     // The new intervals all map back to i.
     if (LRMap)
@@ -1097,7 +1116,7 @@
   }
=20
   // Calculate spill weight and allocation hints for new intervals.
-  Edit->calculateRegClassAndHint(VRM.getMachineFunction(), LIS, SA.Loops);
+  Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops);
=20
   assert(!LRMap || LRMap->size() =3D=3D Edit->size());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/SplitKit=
.h
--- a/head/contrib/llvm/lib/CodeGen/SplitKit.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/CodeGen/SplitKit.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -46,9 +46,6 @@
   const MachineLoopInfo &Loops;
   const TargetInstrInfo &TII;
=20
-  // Sorted slot indexes of using instructions.
-  SmallVector<SlotIndex, 8> UseSlots;
-
   /// Additional information about basic blocks where the current variable=
 is
   /// live. Such a block will look like one of these templates:
   ///
@@ -85,6 +82,9 @@
   // Current live interval.
   const LiveInterval *CurLI;
=20
+  // Sorted slot indexes of using instructions.
+  SmallVector<SlotIndex, 8> UseSlots;
+
   /// LastSplitPoint - Last legal split point in each basic block in the c=
urrent
   /// function. The first entry is the first terminator, the second entry =
is the
   /// last valid split point for a variable that is live in to a landing p=
ad
@@ -135,7 +135,7 @@
   /// getParent - Return the last analyzed interval.
   const LiveInterval &getParent() const { return *CurLI; }
=20
-  /// getLastSplitPoint - Return that base index of the last valid split p=
oint
+  /// getLastSplitPoint - Return the base index of the last valid split po=
int
   /// in the basic block numbered Num.
   SlotIndex getLastSplitPoint(unsigned Num) {
     // Inline the common simple case.
@@ -145,6 +145,9 @@
     return computeLastSplitPoint(Num);
   }
=20
+  /// getLastSplitPointIter - Returns the last split point as an iterator.
+  MachineBasicBlock::iterator getLastSplitPointIter(MachineBasicBlock*);
+
   /// isOriginalEndpoint - Return true if the original live range was kill=
ed or
   /// (re-)defined at Idx. Idx should be the 'def' slot for a normal kill/=
def,
   /// and 'use' for an early-clobber def.
@@ -152,6 +155,10 @@
   /// splitting.
   bool isOriginalEndpoint(SlotIndex Idx) const;
=20
+  /// getUseSlots - Return an array of SlotIndexes of instructions using C=
urLI.
+  /// This include both use and def operands, at most one entry per instru=
ction.
+  ArrayRef<SlotIndex> getUseSlots() const { return UseSlots; }
+
   /// getUseBlocks - Return an array of BlockInfo objects for the basic bl=
ocks
   /// where CurLI has uses.
   ArrayRef<BlockInfo> getUseBlocks() const { return UseBlocks; }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/StackPro=
tector.cpp
--- a/head/contrib/llvm/lib/CodeGen/StackProtector.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/StackProtector.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -123,16 +123,11 @@
           // protectors.
           return true;
=20
-        if (ArrayType *AT =3D dyn_cast<ArrayType>(AI->getAllocatedType()))=
 {
-          // We apparently only care about character arrays.
-          if (!AT->getElementType()->isIntegerTy(8))
-            continue;
-
+        if (ArrayType *AT =3D dyn_cast<ArrayType>(AI->getAllocatedType()))
           // If an array has more than SSPBufferSize bytes of allocated sp=
ace,
           // then we emit stack protectors.
           if (SSPBufferSize <=3D TD->getTypeAllocSize(AT))
             return true;
-        }
       }
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/StackSlo=
tColoring.cpp
--- a/head/contrib/llvm/lib/CodeGen/StackSlotColoring.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/StackSlotColoring.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -12,7 +12,6 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "stackcoloring"
-#include "VirtRegMap.h"
 #include "llvm/Function.h"
 #include "llvm/Module.h"
 #include "llvm/CodeGen/Passes.h"
@@ -40,29 +39,17 @@
              cl::init(false), cl::Hidden,
              cl::desc("Suppress slot sharing during stack coloring"));
=20
-static cl::opt<bool>
-ColorWithRegsOpt("color-ss-with-regs",
-                 cl::init(false), cl::Hidden,
-                 cl::desc("Color stack slots with free registers"));
-
-
 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
=20
 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring=
");
-STATISTIC(NumRegRepl,    "Number of stack slot refs replaced with reg refs=
");
-STATISTIC(NumLoadElim,   "Number of loads eliminated");
-STATISTIC(NumStoreElim,  "Number of stores eliminated");
 STATISTIC(NumDead,       "Number of trivially dead stack accesses eliminat=
ed");
=20
 namespace {
   class StackSlotColoring : public MachineFunctionPass {
     bool ColorWithRegs;
     LiveStacks* LS;
-    VirtRegMap* VRM;
     MachineFrameInfo *MFI;
-    MachineRegisterInfo *MRI;
     const TargetInstrInfo  *TII;
-    const TargetRegisterInfo *TRI;
     const MachineLoopInfo *loopInfo;
=20
     // SSIntervals - Spill slot intervals.
@@ -98,18 +85,12 @@
       MachineFunctionPass(ID), ColorWithRegs(false), NextColor(-1) {
         initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
       }
-    StackSlotColoring(bool RegColor) :
-      MachineFunctionPass(ID), ColorWithRegs(RegColor), NextColor(-1) {
-        initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
-      }
-   =20
+
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
       AU.addRequired<SlotIndexes>();
       AU.addPreserved<SlotIndexes>();
       AU.addRequired<LiveStacks>();
-      AU.addRequired<VirtRegMap>();
-      AU.addPreserved<VirtRegMap>();     =20
       AU.addRequired<MachineLoopInfo>();
       AU.addPreserved<MachineLoopInfo>();
       AU.addPreservedID(MachineDominatorsID);
@@ -117,9 +98,6 @@
     }
=20
     virtual bool runOnMachineFunction(MachineFunction &MF);
-    virtual const char* getPassName() const {
-      return "Stack Slot Coloring";
-    }
=20
   private:
     void InitializeSlots();
@@ -127,41 +105,23 @@
     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
     int ColorSlot(LiveInterval *li);
     bool ColorSlots(MachineFunction &MF);
-    bool ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
-                                SmallVector<SmallVector<int, 4>, 16> &RevM=
ap,
-                                BitVector &SlotIsReg);
     void RewriteInstruction(MachineInstr *MI, int OldFI, int NewFI,
                             MachineFunction &MF);
-    bool PropagateBackward(MachineBasicBlock::iterator MII,
-                           MachineBasicBlock *MBB,
-                           unsigned OldReg, unsigned NewReg);
-    bool PropagateForward(MachineBasicBlock::iterator MII,
-                          MachineBasicBlock *MBB,
-                          unsigned OldReg, unsigned NewReg);
-    void UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
-                                    unsigned Reg, const TargetRegisterClas=
s *RC,
-                                    SmallSet<unsigned, 4> &Defs,
-                                    MachineFunction &MF);
-    bool AllMemRefsCanBeUnfolded(int SS);
     bool RemoveDeadStores(MachineBasicBlock* MBB);
   };
 } // end anonymous namespace
=20
 char StackSlotColoring::ID =3D 0;
+char &llvm::StackSlotColoringID =3D StackSlotColoring::ID;
=20
 INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
                 "Stack Slot Coloring", false, false)
 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
-INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
 INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
                 "Stack Slot Coloring", false, false)
=20
-FunctionPass *llvm::createStackSlotColoringPass(bool RegColor) {
-  return new StackSlotColoring(RegColor);
-}
-
 namespace {
   // IntervalSorter - Comparison predicate that sort live intervals by
   // their weight.
@@ -248,79 +208,6 @@
   return false;
 }
=20
-/// ColorSlotsWithFreeRegs - If there are any free registers available, try
-/// replacing spill slots references with registers instead.
-bool
-StackSlotColoring::ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMappin=
g,
-                                   SmallVector<SmallVector<int, 4>, 16> &R=
evMap,
-                                   BitVector &SlotIsReg) {
-  if (!(ColorWithRegs || ColorWithRegsOpt) || !VRM->HasUnusedRegisters())
-    return false;
-
-  bool Changed =3D false;
-  DEBUG(dbgs() << "Assigning unused registers to spill slots:\n");
-  for (unsigned i =3D 0, e =3D SSIntervals.size(); i !=3D e; ++i) {
-    LiveInterval *li =3D SSIntervals[i];
-    int SS =3D TargetRegisterInfo::stackSlot2Index(li->reg);
-    if (!UsedColors[SS] || li->weight < 20)
-      // If the weight is < 20, i.e. two references in a loop with depth 1,
-      // don't bother with it.
-      continue;
-
-    // These slots allow to share the same registers.
-    bool AllColored =3D true;
-    SmallVector<unsigned, 4> ColoredRegs;
-    for (unsigned j =3D 0, ee =3D RevMap[SS].size(); j !=3D ee; ++j) {
-      int RSS =3D RevMap[SS][j];
-      const TargetRegisterClass *RC =3D LS->getIntervalRegClass(RSS);
-      // If it's not colored to another stack slot, try coloring it
-      // to a "free" register.
-      if (!RC) {
-        AllColored =3D false;
-        continue;
-      }
-      unsigned Reg =3D VRM->getFirstUnusedRegister(RC);
-      if (!Reg) {
-        AllColored =3D false;
-        continue;
-      }
-      if (!AllMemRefsCanBeUnfolded(RSS)) {
-        AllColored =3D false;
-        continue;
-      } else {
-        DEBUG(dbgs() << "Assigning fi#" << RSS << " to "
-                     << TRI->getName(Reg) << '\n');
-        ColoredRegs.push_back(Reg);
-        SlotMapping[RSS] =3D Reg;
-        SlotIsReg.set(RSS);
-        Changed =3D true;
-      }
-    }
-
-    // Register and its sub-registers are no longer free.
-    while (!ColoredRegs.empty()) {
-      unsigned Reg =3D ColoredRegs.back();
-      ColoredRegs.pop_back();
-      VRM->setRegisterUsed(Reg);
-      // If reg is a callee-saved register, it will have to be spilled in
-      // the prologue.
-      MRI->setPhysRegUsed(Reg);
-      for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS) {
-        VRM->setRegisterUsed(*AS);
-        MRI->setPhysRegUsed(*AS);
-      }
-    }
-    // This spill slot is dead after the rewrites
-    if (AllColored) {
-      MFI->RemoveStackObject(SS);
-      ++NumEliminated;
-    }
-  }
-  DEBUG(dbgs() << '\n');
-
-  return Changed;
-}
-
 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
 ///
 int StackSlotColoring::ColorSlot(LiveInterval *li) {
@@ -372,7 +259,6 @@
   SmallVector<int, 16> SlotMapping(NumObjs, -1);
   SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
   SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
-  BitVector SlotIsReg(NumObjs);
   BitVector UsedColors(NumObjs);
=20
   DEBUG(dbgs() << "Color spill slot intervals:\n");
@@ -404,31 +290,19 @@
   DEBUG(dbgs() << '\n');
 #endif
=20
-  // Can we "color" a stack slot with a unused register?
-  Changed |=3D ColorSlotsWithFreeRegs(SlotMapping, RevMap, SlotIsReg);
-
   if (!Changed)
     return false;
=20
   // Rewrite all MO_FrameIndex operands.
   SmallVector<SmallSet<unsigned, 4>, 4> NewDefs(MF.getNumBlockIDs());
   for (unsigned SS =3D 0, SE =3D SSRefs.size(); SS !=3D SE; ++SS) {
-    bool isReg =3D SlotIsReg[SS];
     int NewFI =3D SlotMapping[SS];
-    if (NewFI =3D=3D -1 || (NewFI =3D=3D (int)SS && !isReg))
+    if (NewFI =3D=3D -1 || (NewFI =3D=3D (int)SS))
       continue;
=20
-    const TargetRegisterClass *RC =3D LS->getIntervalRegClass(SS);
     SmallVector<MachineInstr*, 8> &RefMIs =3D SSRefs[SS];
     for (unsigned i =3D 0, e =3D RefMIs.size(); i !=3D e; ++i)
-      if (!isReg)
-        RewriteInstruction(RefMIs[i], SS, NewFI, MF);
-      else {
-        // Rewrite to use a register instead.
-        unsigned MBBId =3D RefMIs[i]->getParent()->getNumber();
-        SmallSet<unsigned, 4> &Defs =3D NewDefs[MBBId];
-        UnfoldAndRewriteInstruction(RefMIs[i], SS, NewFI, RC, Defs, MF);
-      }
+      RewriteInstruction(RefMIs[i], SS, NewFI, MF);
   }
=20
   // Delete unused stack slots.
@@ -441,28 +315,6 @@
   return true;
 }
=20
-/// AllMemRefsCanBeUnfolded - Return true if all references of the specifi=
ed
-/// spill slot index can be unfolded.
-bool StackSlotColoring::AllMemRefsCanBeUnfolded(int SS) {
-  SmallVector<MachineInstr*, 8> &RefMIs =3D SSRefs[SS];
-  for (unsigned i =3D 0, e =3D RefMIs.size(); i !=3D e; ++i) {
-    MachineInstr *MI =3D RefMIs[i];
-    if (TII->isLoadFromStackSlot(MI, SS) ||
-        TII->isStoreToStackSlot(MI, SS))
-      // Restore and spill will become copies.
-      return true;
-    if (!TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(), false, false))
-      return false;
-    for (unsigned j =3D 0, ee =3D MI->getNumOperands(); j !=3D ee; ++j) {
-      MachineOperand &MO =3D MI->getOperand(j);
-      if (MO.isFI() && MO.getIndex() !=3D SS)
-        // If it uses another frameindex, we can, currently* unfold it.
-        return false;
-    }
-  }
-  return true;
-}
-
 /// RewriteInstruction - Rewrite specified instruction by replacing refere=
nces
 /// to old frame index with new one.
 void StackSlotColoring::RewriteInstruction(MachineInstr *MI, int OldFI,
@@ -489,179 +341,6 @@
       (*I)->setValue(NewSV);
 }
=20
-/// PropagateBackward - Traverse backward and look for the definition of
-/// OldReg. If it can successfully update all of the references with NewRe=
g,
-/// do so and return true.
-bool StackSlotColoring::PropagateBackward(MachineBasicBlock::iterator MII,
-                                          MachineBasicBlock *MBB,
-                                          unsigned OldReg, unsigned NewReg=
) {
-  if (MII =3D=3D MBB->begin())
-    return false;
-
-  SmallVector<MachineOperand*, 4> Uses;
-  SmallVector<MachineOperand*, 4> Refs;
-  while (--MII !=3D MBB->begin()) {
-    bool FoundDef =3D false;  // Not counting 2address def.
-
-    Uses.clear();
-    const MCInstrDesc &MCID =3D MII->getDesc();
-    for (unsigned i =3D 0, e =3D MII->getNumOperands(); i !=3D e; ++i) {
-      MachineOperand &MO =3D MII->getOperand(i);
-      if (!MO.isReg())
-        continue;
-      unsigned Reg =3D MO.getReg();
-      if (Reg =3D=3D 0)
-        continue;
-      if (Reg =3D=3D OldReg) {
-        if (MO.isImplicit())
-          return false;
-
-        // Abort the use is actually a sub-register def. We don't have eno=
ugh
-        // information to figure out if it is really legal.
-        if (MO.getSubReg() || MII->isSubregToReg())
-          return false;
-
-        const TargetRegisterClass *RC =3D TII->getRegClass(MCID, i, TRI);
-        if (RC && !RC->contains(NewReg))
-          return false;
-
-        if (MO.isUse()) {
-          Uses.push_back(&MO);
-        } else {
-          Refs.push_back(&MO);
-          if (!MII->isRegTiedToUseOperand(i))
-            FoundDef =3D true;
-        }
-      } else if (TRI->regsOverlap(Reg, NewReg)) {
-        return false;
-      } else if (TRI->regsOverlap(Reg, OldReg)) {
-        if (!MO.isUse() || !MO.isKill())
-          return false;
-      }
-    }
-
-    if (FoundDef) {
-      // Found non-two-address def. Stop here.
-      for (unsigned i =3D 0, e =3D Refs.size(); i !=3D e; ++i)
-        Refs[i]->setReg(NewReg);
-      return true;
-    }
-
-    // Two-address uses must be updated as well.
-    for (unsigned i =3D 0, e =3D Uses.size(); i !=3D e; ++i)
-      Refs.push_back(Uses[i]);
-  }
-  return false;
-}
-
-/// PropagateForward - Traverse forward and look for the kill of OldReg. If
-/// it can successfully update all of the uses with NewReg, do so and
-/// return true.
-bool StackSlotColoring::PropagateForward(MachineBasicBlock::iterator MII,
-                                         MachineBasicBlock *MBB,
-                                         unsigned OldReg, unsigned NewReg)=
 {
-  if (MII =3D=3D MBB->end())
-    return false;
-
-  SmallVector<MachineOperand*, 4> Uses;
-  while (++MII !=3D MBB->end()) {
-    bool FoundKill =3D false;
-    const MCInstrDesc &MCID =3D MII->getDesc();
-    for (unsigned i =3D 0, e =3D MII->getNumOperands(); i !=3D e; ++i) {
-      MachineOperand &MO =3D MII->getOperand(i);
-      if (!MO.isReg())
-        continue;
-      unsigned Reg =3D MO.getReg();
-      if (Reg =3D=3D 0)
-        continue;
-      if (Reg =3D=3D OldReg) {
-        if (MO.isDef() || MO.isImplicit())
-          return false;
-
-        // Abort the use is actually a sub-register use. We don't have eno=
ugh
-        // information to figure out if it is really legal.
-        if (MO.getSubReg())
-          return false;
-
-        const TargetRegisterClass *RC =3D TII->getRegClass(MCID, i, TRI);
-        if (RC && !RC->contains(NewReg))
-          return false;
-        if (MO.isKill())
-          FoundKill =3D true;
-
-        Uses.push_back(&MO);
-      } else if (TRI->regsOverlap(Reg, NewReg) ||
-                 TRI->regsOverlap(Reg, OldReg))
-        return false;
-    }
-    if (FoundKill) {
-      for (unsigned i =3D 0, e =3D Uses.size(); i !=3D e; ++i)
-        Uses[i]->setReg(NewReg);
-      return true;
-    }
-  }
-  return false;
-}
-
-/// UnfoldAndRewriteInstruction - Rewrite specified instruction by unfoldi=
ng
-/// folded memory references and replacing those references with register
-/// references instead.
-void
-StackSlotColoring::UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
-                                               unsigned Reg,
-                                               const TargetRegisterClass *=
RC,
-                                               SmallSet<unsigned, 4> &Defs,
-                                               MachineFunction &MF) {
-  MachineBasicBlock *MBB =3D MI->getParent();
-  if (unsigned DstReg =3D TII->isLoadFromStackSlot(MI, OldFI)) {
-    if (PropagateForward(MI, MBB, DstReg, Reg)) {
-      DEBUG(dbgs() << "Eliminated load: ");
-      DEBUG(MI->dump());
-      ++NumLoadElim;
-    } else {
-      BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY),
-              DstReg).addReg(Reg);
-      ++NumRegRepl;
-    }
-
-    if (!Defs.count(Reg)) {
-      // If this is the first use of Reg in this MBB and it wasn't previou=
sly
-      // defined in MBB, add it to livein.
-      MBB->addLiveIn(Reg);
-      Defs.insert(Reg);
-    }
-  } else if (unsigned SrcReg =3D TII->isStoreToStackSlot(MI, OldFI)) {
-    if (MI->killsRegister(SrcReg) && PropagateBackward(MI, MBB, SrcReg, Re=
g)) {
-      DEBUG(dbgs() << "Eliminated store: ");
-      DEBUG(MI->dump());
-      ++NumStoreElim;
-    } else {
-      BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY), R=
eg)
-        .addReg(SrcReg);
-      ++NumRegRepl;
-    }
-
-    // Remember reg has been defined in MBB.
-    Defs.insert(Reg);
-  } else {
-    SmallVector<MachineInstr*, 4> NewMIs;
-    bool Success =3D TII->unfoldMemoryOperand(MF, MI, Reg, false, false, N=
ewMIs);
-    (void)Success; // Silence compiler warning.
-    assert(Success && "Failed to unfold!");
-    MachineInstr *NewMI =3D NewMIs[0];
-    MBB->insert(MI, NewMI);
-    ++NumRegRepl;
-
-    if (NewMI->readsRegister(Reg)) {
-      if (!Defs.count(Reg))
-        // If this is the first use of Reg in this MBB and it wasn't previ=
ously
-        // defined in MBB, add it to livein.
-        MBB->addLiveIn(Reg);
-      Defs.insert(Reg);
-    }
-  }
-  MBB->erase(MI);
-}
=20
 /// RemoveDeadStores - Scan through a basic block and look for loads follo=
wed
 /// by stores.  If they're both using the same stack slot, then the store =
is
@@ -679,33 +358,33 @@
        I !=3D E; ++I) {
     if (DCELimit !=3D -1 && (int)NumDead >=3D DCELimit)
       break;
-   =20
+
     MachineBasicBlock::iterator NextMI =3D llvm::next(I);
     if (NextMI =3D=3D MBB->end()) continue;
-   =20
+
     int FirstSS, SecondSS;
     unsigned LoadReg =3D 0;
     unsigned StoreReg =3D 0;
     if (!(LoadReg =3D TII->isLoadFromStackSlot(I, FirstSS))) continue;
     if (!(StoreReg =3D TII->isStoreToStackSlot(NextMI, SecondSS))) continu=
e;
     if (FirstSS !=3D SecondSS || LoadReg !=3D StoreReg || FirstSS =3D=3D -=
1) continue;
-   =20
+
     ++NumDead;
     changed =3D true;
-   =20
+
     if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) !=3D -1) {
       ++NumDead;
       toErase.push_back(I);
     }
-   =20
+
     toErase.push_back(NextMI);
     ++I;
   }
- =20
+
   for (SmallVector<MachineInstr*, 4>::iterator I =3D toErase.begin(),
        E =3D toErase.end(); I !=3D E; ++I)
     (*I)->eraseFromParent();
- =20
+
   return changed;
 }
=20
@@ -713,32 +392,27 @@
 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
   DEBUG({
       dbgs() << "********** Stack Slot Coloring **********\n"
-             << "********** Function: "=20
+             << "********** Function: "
              << MF.getFunction()->getName() << '\n';
     });
=20
   MFI =3D MF.getFrameInfo();
-  MRI =3D &MF.getRegInfo();=20
   TII =3D MF.getTarget().getInstrInfo();
-  TRI =3D MF.getTarget().getRegisterInfo();
   LS =3D &getAnalysis<LiveStacks>();
-  VRM =3D &getAnalysis<VirtRegMap>();
   loopInfo =3D &getAnalysis<MachineLoopInfo>();
=20
   bool Changed =3D false;
=20
   unsigned NumSlots =3D LS->getNumIntervals();
-  if (NumSlots < 2) {
-    if (NumSlots =3D=3D 0 || !VRM->HasUnusedRegisters())
-      // Nothing to do!
-      return false;
-  }
+  if (NumSlots =3D=3D 0)
+    // Nothing to do!
+    return false;
=20
   // If there are calls to setjmp or sigsetjmp, don't perform stack slot
   // coloring. The stack could be modified before the longjmp is executed,
   // resulting in the wrong value being used afterwards. (See
   // <rdar://problem/8007500>.)
-  if (MF.callsSetJmp())
+  if (MF.exposesReturnsTwice())
     return false;
=20
   // Gather spill slot references
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/StrongPH=
IElimination.cpp
--- a/head/contrib/llvm/lib/CodeGen/StrongPHIElimination.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/StrongPHIElimination.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -228,7 +228,6 @@
         return &MO;
     }
   }
-  return NULL;
 }
=20
 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &MF) {
@@ -390,12 +389,10 @@
     MachineOperand *LastUse =3D findLastUse(MBB, SrcReg);
     assert(LastUse);
     SlotIndex LastUseIndex =3D LI->getInstructionIndex(LastUse->getParent(=
));
-    SrcLI.removeRange(LastUseIndex.getDefIndex(), LI->getMBBEndIdx(MBB));
+    SrcLI.removeRange(LastUseIndex.getRegSlot(), LI->getMBBEndIdx(MBB));
     LastUse->setIsKill(true);
   }
=20
-  LI->renumber();
-
   Allocator.Reset();
   RegNodeMap.clear();
   PHISrcDefs.clear();
@@ -745,7 +742,7 @@
=20
     // Set the phi-def flag for the VN at this PHI.
     SlotIndex PHIIndex =3D LI->getInstructionIndex(PHI);
-    VNInfo *DestVNI =3D DestLI.getVNInfoAt(PHIIndex.getDefIndex());
+    VNInfo *DestVNI =3D DestLI.getVNInfoAt(PHIIndex.getRegSlot());
     assert(DestVNI);
     DestVNI->setIsPHIDef(true);
  =20
@@ -756,7 +753,7 @@
     SlotIndex MBBStartIndex =3D LI->getMBBStartIdx(MBB);
     DestVNI->def =3D MBBStartIndex;
     DestLI.addRange(LiveRange(MBBStartIndex,
-                              PHIIndex.getDefIndex(),
+                              PHIIndex.getRegSlot(),
                               DestVNI));
     return;
   }
@@ -779,22 +776,21 @@
   SlotIndex MBBStartIndex =3D LI->getMBBStartIdx(MBB);
   SlotIndex DestCopyIndex =3D LI->getInstructionIndex(CopyInstr);
   VNInfo *CopyVNI =3D CopyLI.getNextValue(MBBStartIndex,
-                                        CopyInstr,
                                         LI->getVNInfoAllocator());
   CopyVNI->setIsPHIDef(true);
   CopyLI.addRange(LiveRange(MBBStartIndex,
-                            DestCopyIndex.getDefIndex(),
+                            DestCopyIndex.getRegSlot(),
                             CopyVNI));
=20
   // Adjust DestReg's live interval to adjust for its new definition at
   // CopyInstr.
   LiveInterval &DestLI =3D LI->getOrCreateInterval(DestReg);
   SlotIndex PHIIndex =3D LI->getInstructionIndex(PHI);
-  DestLI.removeRange(PHIIndex.getDefIndex(), DestCopyIndex.getDefIndex());
+  DestLI.removeRange(PHIIndex.getRegSlot(), DestCopyIndex.getRegSlot());
=20
-  VNInfo *DestVNI =3D DestLI.getVNInfoAt(DestCopyIndex.getDefIndex());
+  VNInfo *DestVNI =3D DestLI.getVNInfoAt(DestCopyIndex.getRegSlot());
   assert(DestVNI);
-  DestVNI->def =3D DestCopyIndex.getDefIndex();
+  DestVNI->def =3D DestCopyIndex.getRegSlot();
=20
   InsertedDestCopies[CopyReg] =3D CopyInstr;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/TailDupl=
ication.cpp
--- a/head/contrib/llvm/lib/CodeGen/TailDuplication.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/TailDuplication.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -56,10 +56,10 @@
 namespace {
   /// TailDuplicatePass - Perform tail duplication.
   class TailDuplicatePass : public MachineFunctionPass {
-    bool PreRegAlloc;
     const TargetInstrInfo *TII;
     MachineModuleInfo *MMI;
     MachineRegisterInfo *MRI;
+    bool PreRegAlloc;
=20
     // SSAUpdateVRs - A list of virtual registers for which to update SSA =
form.
     SmallVector<unsigned, 16> SSAUpdateVRs;
@@ -70,11 +70,10 @@
=20
   public:
     static char ID;
-    explicit TailDuplicatePass(bool PreRA) :
-      MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
+    explicit TailDuplicatePass() :
+      MachineFunctionPass(ID), PreRegAlloc(false) {}
=20
     virtual bool runOnMachineFunction(MachineFunction &MF);
-    virtual const char *getPassName() const { return "Tail Duplication"; }
=20
   private:
     void AddSSAUpdateEntry(unsigned OrigReg, unsigned NewReg,
@@ -118,14 +117,16 @@
   char TailDuplicatePass::ID =3D 0;
 }
=20
-FunctionPass *llvm::createTailDuplicatePass(bool PreRegAlloc) {
-  return new TailDuplicatePass(PreRegAlloc);
-}
+char &llvm::TailDuplicateID =3D TailDuplicatePass::ID;
+
+INITIALIZE_PASS(TailDuplicatePass, "tailduplication", "Tail Duplication",
+                false, false)
=20
 bool TailDuplicatePass::runOnMachineFunction(MachineFunction &MF) {
   TII =3D MF.getTarget().getInstrInfo();
   MRI =3D &MF.getRegInfo();
   MMI =3D getAnalysisIfAvailable<MachineModuleInfo>();
+  PreRegAlloc =3D MRI->isSSA();
=20
   bool MadeChange =3D false;
   while (TailDuplicateBlocks(MF))
@@ -432,7 +433,7 @@
         MO.setReg(VI->second);
     }
   }
-  PredBB->insert(PredBB->end(), NewMI);
+  PredBB->insert(PredBB->instr_end(), NewMI);
 }
=20
 /// UpdateSuccessorsPHIs - After FromBB is tail duplicated into its predec=
essor
@@ -553,7 +554,7 @@
=20
   bool HasIndirectbr =3D false;
   if (!TailBB.empty())
-    HasIndirectbr =3D TailBB.back().getDesc().isIndirectBranch();
+    HasIndirectbr =3D TailBB.back().isIndirectBranch();
=20
   if (HasIndirectbr && PreRegAlloc)
     MaxDuplicateCount =3D 20;
@@ -561,22 +562,21 @@
   // Check the instructions in the block to determine whether tail-duplica=
tion
   // is invalid or unlikely to be profitable.
   unsigned InstrCount =3D 0;
-  for (MachineBasicBlock::const_iterator I =3D TailBB.begin(); I !=3D Tail=
BB.end();
-       ++I) {
+  for (MachineBasicBlock::iterator I =3D TailBB.begin(); I !=3D TailBB.end=
(); ++I) {
     // Non-duplicable things shouldn't be tail-duplicated.
-    if (I->getDesc().isNotDuplicable())
+    if (I->isNotDuplicable())
       return false;
=20
     // Do not duplicate 'return' instructions if this is a pre-regalloc ru=
n.
     // A return may expand into a lot more instructions (e.g. reload of ca=
llee
     // saved registers) after PEI.
-    if (PreRegAlloc && I->getDesc().isReturn())
+    if (PreRegAlloc && I->isReturn())
       return false;
=20
     // Avoid duplicating calls before register allocation. Calls presents a
     // barrier to register allocation so duplicating them may end up incre=
asing
     // spills.
-    if (PreRegAlloc && I->getDesc().isCall())
+    if (PreRegAlloc && I->isCall())
       return false;
=20
     if (!I->isPHI() && !I->isDebugValue())
@@ -611,7 +611,7 @@
     ++I;
   if (I =3D=3D E)
     return true;
-  return I->getDesc().isUnconditionalBranch();
+  return I->isUnconditionalBranch();
 }
=20
 static bool
@@ -778,8 +778,10 @@
     // Clone the contents of TailBB into PredBB.
     DenseMap<unsigned, unsigned> LocalVRMap;
     SmallVector<std::pair<unsigned,unsigned>, 4> CopyInfos;
-    MachineBasicBlock::iterator I =3D TailBB->begin();
-    while (I !=3D TailBB->end()) {
+    // Use instr_iterator here to properly handle bundles, e.g.
+    // ARM Thumb2 IT block.
+    MachineBasicBlock::instr_iterator I =3D TailBB->instr_begin();
+    while (I !=3D TailBB->instr_end()) {
       MachineInstr *MI =3D &*I;
       ++I;
       if (MI->isPHI()) {
@@ -824,7 +826,7 @@
   SmallVector<MachineOperand, 4> PriorCond;
   // This has to check PrevBB->succ_size() because EH edges are ignored by
   // AnalyzeBranch.
-  if (PrevBB->succ_size() =3D=3D 1 &&=20
+  if (PrevBB->succ_size() =3D=3D 1 &&
       !TII->AnalyzeBranch(*PrevBB, PriorTBB, PriorFBB, PriorCond, true) &&
       PriorCond.empty() && !PriorTBB && TailBB->pred_size() =3D=3D 1 &&
       !TailBB->hasAddressTaken()) {
@@ -849,6 +851,7 @@
         // Replace def of virtual registers with new registers, and update
         // uses with PHI source register or the new registers.
         MachineInstr *MI =3D &*I++;
+        assert(!MI->isBundle() && "Not expecting bundles before regalloc!"=
);
         DuplicateInstruction(MI, TailBB, PrevBB, MF, LocalVRMap, UsedByPhi=
);
         MI->eraseFromParent();
       }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/TargetIn=
strInfoImpl.cpp
--- a/head/contrib/llvm/lib/CodeGen/TargetInstrInfoImpl.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/TargetInstrInfoImpl.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -24,6 +24,7 @@
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
 #include "llvm/CodeGen/PseudoSourceValue.h"
+#include "llvm/MC/MCInstrItineraries.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -77,6 +78,9 @@
   unsigned Reg0 =3D HasDef ? MI->getOperand(0).getReg() : 0;
   unsigned Reg1 =3D MI->getOperand(Idx1).getReg();
   unsigned Reg2 =3D MI->getOperand(Idx2).getReg();
+  unsigned SubReg0 =3D HasDef ? MI->getOperand(0).getSubReg() : 0;
+  unsigned SubReg1 =3D MI->getOperand(Idx1).getSubReg();
+  unsigned SubReg2 =3D MI->getOperand(Idx2).getSubReg();
   bool Reg1IsKill =3D MI->getOperand(Idx1).isKill();
   bool Reg2IsKill =3D MI->getOperand(Idx2).isKill();
   // If destination is tied to either of the commuted source register, then
@@ -85,10 +89,12 @@
       MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) =3D=3D 0) {
     Reg2IsKill =3D false;
     Reg0 =3D Reg2;
+    SubReg0 =3D SubReg2;
   } else if (HasDef && Reg0 =3D=3D Reg2 &&
              MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) =3D=
=3D 0) {
     Reg1IsKill =3D false;
     Reg0 =3D Reg1;
+    SubReg0 =3D SubReg1;
   }
=20
   if (NewMI) {
@@ -97,19 +103,23 @@
     MachineFunction &MF =3D *MI->getParent()->getParent();
     if (HasDef)
       return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
-        .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
-        .addReg(Reg2, getKillRegState(Reg2IsKill))
-        .addReg(Reg1, getKillRegState(Reg2IsKill));
+        .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead), SubR=
eg0)
+        .addReg(Reg2, getKillRegState(Reg2IsKill), SubReg2)
+        .addReg(Reg1, getKillRegState(Reg1IsKill), SubReg1);
     else
       return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
-        .addReg(Reg2, getKillRegState(Reg2IsKill))
-        .addReg(Reg1, getKillRegState(Reg2IsKill));
+        .addReg(Reg2, getKillRegState(Reg2IsKill), SubReg2)
+        .addReg(Reg1, getKillRegState(Reg1IsKill), SubReg1);
   }
=20
-  if (HasDef)
+  if (HasDef) {
     MI->getOperand(0).setReg(Reg0);
+    MI->getOperand(0).setSubReg(SubReg0);
+  }
   MI->getOperand(Idx2).setReg(Reg1);
   MI->getOperand(Idx1).setReg(Reg2);
+  MI->getOperand(Idx2).setSubReg(SubReg1);
+  MI->getOperand(Idx1).setSubReg(SubReg2);
   MI->getOperand(Idx2).setIsKill(Reg1IsKill);
   MI->getOperand(Idx1).setIsKill(Reg2IsKill);
   return MI;
@@ -121,6 +131,9 @@
 bool TargetInstrInfoImpl::findCommutedOpIndices(MachineInstr *MI,
                                                 unsigned &SrcOpIdx1,
                                                 unsigned &SrcOpIdx2) const=
 {
+  assert(!MI->isBundle() &&
+         "TargetInstrInfoImpl::findCommutedOpIndices() can't handle bundle=
s");
+
   const MCInstrDesc &MCID =3D MI->getDesc();
   if (!MCID.isCommutable())
     return false;
@@ -136,11 +149,28 @@
 }
=20
=20
+bool
+TargetInstrInfoImpl::isUnpredicatedTerminator(const MachineInstr *MI) cons=
t {
+  if (!MI->isTerminator()) return false;
+
+  // Conditional branch is a special case.
+  if (MI->isBranch() && !MI->isBarrier())
+    return true;
+  if (!MI->isPredicable())
+    return true;
+  return !isPredicated(MI);
+}
+
+
 bool TargetInstrInfoImpl::PredicateInstruction(MachineInstr *MI,
                             const SmallVectorImpl<MachineOperand> &Pred) c=
onst {
   bool MadeChange =3D false;
+
+  assert(!MI->isBundle() &&
+         "TargetInstrInfoImpl::PredicateInstruction() can't handle bundles=
");
+
   const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.isPredicable())
+  if (!MI->isPredicable())
     return false;
=20
   for (unsigned j =3D 0, i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++=
i) {
@@ -218,7 +248,7 @@
=20
 MachineInstr *TargetInstrInfoImpl::duplicate(MachineInstr *Orig,
                                              MachineFunction &MF) const {
-  assert(!Orig->getDesc().isNotDuplicable() &&
+  assert(!Orig->isNotDuplicable() &&
          "Instruction cannot be duplicated");
   return MF.CloneMachineInstr(Orig);
 }
@@ -288,16 +318,15 @@
   if (MachineInstr *NewMI =3D foldMemoryOperandImpl(MF, MI, Ops, FI)) {
     // Add a memory operand, foldMemoryOperandImpl doesn't do that.
     assert((!(Flags & MachineMemOperand::MOStore) ||
-            NewMI->getDesc().mayStore()) &&
+            NewMI->mayStore()) &&
            "Folded a def to a non-store!");
     assert((!(Flags & MachineMemOperand::MOLoad) ||
-            NewMI->getDesc().mayLoad()) &&
+            NewMI->mayLoad()) &&
            "Folded a use to a non-load!");
     const MachineFrameInfo &MFI =3D *MF.getFrameInfo();
     assert(MFI.getObjectOffset(FI) !=3D -1);
     MachineMemOperand *MMO =3D
-      MF.getMachineMemOperand(
-                    MachinePointerInfo(PseudoSourceValue::getFixedStack(FI=
)),
+      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
                               Flags, MFI.getObjectSize(FI),
                               MFI.getObjectAlignment(FI));
     NewMI->addMemOperand(MF, MMO);
@@ -332,7 +361,7 @@
 TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
                                    const SmallVectorImpl<unsigned> &Ops,
                                    MachineInstr* LoadMI) const {
-  assert(LoadMI->getDesc().canFoldAsLoad() && "LoadMI isn't foldable!");
+  assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
 #ifndef NDEBUG
   for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i)
     assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
@@ -360,7 +389,6 @@
   const MachineRegisterInfo &MRI =3D MF.getRegInfo();
   const TargetMachine &TM =3D MF.getTarget();
   const TargetInstrInfo &TII =3D *TM.getInstrInfo();
-  const TargetRegisterInfo &TRI =3D *TM.getRegisterInfo();
=20
   // Remat clients assume operand 0 is the defined register.
   if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
@@ -383,10 +411,8 @@
       MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
     return true;
=20
-  const MCInstrDesc &MCID =3D MI->getDesc();
-
   // Avoid instructions obviously unsafe for remat.
-  if (MCID.isNotDuplicable() || MCID.mayStore() ||
+  if (MI->isNotDuplicable() || MI->mayStore() ||
       MI->hasUnmodeledSideEffects())
     return false;
=20
@@ -396,7 +422,7 @@
     return false;
=20
   // Avoid instructions which load from potentially varying memory.
-  if (MCID.mayLoad() && !MI->isInvariantLoad(AA))
+  if (MI->mayLoad() && !MI->isInvariantLoad(AA))
     return false;
=20
   // If any of the registers accessed are non-constant, conservatively ass=
ume
@@ -414,19 +440,8 @@
         // If the physreg has no defs anywhere, it's just an ambient regis=
ter
         // and we can freely move its uses. Alternatively, if it's allocat=
able,
         // it could get allocated to something with a def during allocatio=
n.
-        if (!MRI.def_empty(Reg))
+        if (!MRI.isConstantPhysReg(Reg, MF))
           return false;
-        BitVector AllocatableRegs =3D TRI.getAllocatableSet(MF, 0);
-        if (AllocatableRegs.test(Reg))
-          return false;
-        // Check for a def among the register's aliases too.
-        for (const unsigned *Alias =3D TRI.getAliasSet(Reg); *Alias; ++Ali=
as) {
-          unsigned AliasReg =3D *Alias;
-          if (!MRI.def_empty(AliasReg))
-            return false;
-          if (AllocatableRegs.test(AliasReg))
-            return false;
-        }
       } else {
         // A physreg def. We can't remat it.
         return false;
@@ -457,7 +472,7 @@
                                                const MachineBasicBlock *MB=
B,
                                                const MachineFunction &MF) =
const{
   // Terminators and labels can't be scheduled around.
-  if (MI->getDesc().isTerminator() || MI->isLabel())
+  if (MI->isTerminator() || MI->isLabel())
     return true;
=20
   // Don't attempt to schedule around any instruction that defines
@@ -493,3 +508,32 @@
   return (ScheduleHazardRecognizer *)
     new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
 }
+
+int
+TargetInstrInfoImpl::getOperandLatency(const InstrItineraryData *ItinData,
+                                       SDNode *DefNode, unsigned DefIdx,
+                                       SDNode *UseNode, unsigned UseIdx) c=
onst {
+  if (!ItinData || ItinData->isEmpty())
+    return -1;
+
+  if (!DefNode->isMachineOpcode())
+    return -1;
+
+  unsigned DefClass =3D get(DefNode->getMachineOpcode()).getSchedClass();
+  if (!UseNode->isMachineOpcode())
+    return ItinData->getOperandCycle(DefClass, DefIdx);
+  unsigned UseClass =3D get(UseNode->getMachineOpcode()).getSchedClass();
+  return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
+}
+
+int TargetInstrInfoImpl::getInstrLatency(const InstrItineraryData *ItinDat=
a,
+                                         SDNode *N) const {
+  if (!ItinData || ItinData->isEmpty())
+    return 1;
+
+  if (!N->isMachineOpcode())
+    return 1;
+
+  return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClas=
s());
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/TargetLo=
weringObjectFileImpl.cpp
--- a/head/contrib/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/TargetLoweringObjectFileImpl.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
 #include "llvm/GlobalVariable.h"
+#include "llvm/Module.h"
 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCExpr.h"
@@ -53,11 +54,9 @@
     report_fatal_error("We do not support this DWARF encoding yet!");
   case dwarf::DW_EH_PE_absptr:
     return  Mang->getSymbol(GV);
-    break;
   case dwarf::DW_EH_PE_pcrel: {
     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
                                           Mang->getSymbol(GV)->getName());
-    break;
   }
   }
 }
@@ -78,14 +77,14 @@
                                                     Flags,
                                                     SectionKind::getDataRe=
l(),
                                                     0, Label->getName());
+  unsigned Size =3D TM.getTargetData()->getPointerSize();
   Streamer.SwitchSection(Sec);
-  Streamer.EmitValueToAlignment(8);
+  Streamer.EmitValueToAlignment(TM.getTargetData()->getPointerABIAlignment=
());
   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
-  const MCExpr *E =3D MCConstantExpr::Create(8, getContext());
+  const MCExpr *E =3D MCConstantExpr::Create(Size, getContext());
   Streamer.EmitELFSize(Label, E);
   Streamer.EmitLabel(Label);
=20
-  unsigned Size =3D TM.getTargetData()->getPointerSize();
   Streamer.EmitSymbolValue(Sym, Size);
 }
=20
@@ -189,6 +188,7 @@
 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
   if (Kind.isText())                 return ".text.";
   if (Kind.isReadOnly())             return ".rodata.";
+  if (Kind.isBSS())                  return ".bss.";
=20
   if (Kind.isThreadData())           return ".tdata.";
   if (Kind.isThreadBSS())            return ".tbss.";
@@ -217,7 +217,7 @@
   // If this global is linkonce/weak and the target handles this by emitti=
ng it
   // into a 'uniqued' section name, create and return the section now.
   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
-      !Kind.isCommon() && !Kind.isBSS()) {
+      !Kind.isCommon()) {
     const char *Prefix;
     Prefix =3D getSectionPrefixForGlobal(Kind);
=20
@@ -342,10 +342,92 @@
     getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
 }
=20
+const MCSection *
+TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const=
 {
+  // The default scheme is .ctor / .dtor, so we have to invert the priority
+  // numbering.
+  if (Priority =3D=3D 65535)
+    return StaticCtorSection;
+
+  std::string Name =3D std::string(".ctors.") + utostr(65535 - Priority);
+  return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
+                                    ELF::SHF_ALLOC |ELF::SHF_WRITE,
+                                    SectionKind::getDataRel());
+}
+
+const MCSection *
+TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const=
 {
+  // The default scheme is .ctor / .dtor, so we have to invert the priority
+  // numbering.
+  if (Priority =3D=3D 65535)
+    return StaticDtorSection;
+
+  std::string Name =3D std::string(".dtors.") + utostr(65535 - Priority);
+  return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
+                                    ELF::SHF_ALLOC |ELF::SHF_WRITE,
+                                    SectionKind::getDataRel());
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                                 MachO
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+/// emitModuleFlags - Emit the module flags that specify the garbage colle=
ction
+/// information.
+void TargetLoweringObjectFileMachO::
+emitModuleFlags(MCStreamer &Streamer,
+                ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
+                Mangler *Mang, const TargetMachine &TM) const {
+  unsigned VersionVal =3D 0;
+  unsigned GCFlags =3D 0;
+  StringRef SectionVal;
+
+  for (ArrayRef<Module::ModuleFlagEntry>::iterator
+         i =3D ModuleFlags.begin(), e =3D ModuleFlags.end(); i !=3D e; ++i=
) {
+    const Module::ModuleFlagEntry &MFE =3D *i;
+
+    // Ignore flags with 'Require' behavior.
+    if (MFE.Behavior =3D=3D Module::Require)
+      continue;
+
+    StringRef Key =3D MFE.Key->getString();
+    Value *Val =3D MFE.Val;
+
+    if (Key =3D=3D "Objective-C Image Info Version")
+      VersionVal =3D cast<ConstantInt>(Val)->getZExtValue();
+    else if (Key =3D=3D "Objective-C Garbage Collection" ||
+             Key =3D=3D "Objective-C GC Only")
+      GCFlags |=3D cast<ConstantInt>(Val)->getZExtValue();
+    else if (Key =3D=3D "Objective-C Image Info Section")
+      SectionVal =3D cast<MDString>(Val)->getString();
+  }
+
+  // The section is mandatory. If we don't have it, then we don't have GC =
info.
+  if (SectionVal.empty()) return;
+
+  StringRef Segment, Section;
+  unsigned TAA =3D 0, StubSize =3D 0;
+  bool TAAParsed;
+  std::string ErrorCode =3D
+    MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
+                                          TAA, TAAParsed, StubSize);
+  if (!ErrorCode.empty())
+    // If invalid, report the error with report_fatal_error.
+    report_fatal_error("Invalid section specifier '" + Section + "': " +
+                       ErrorCode + ".");
+
+  // Get the section.
+  const MCSectionMachO *S =3D
+    getContext().getMachOSection(Segment, Section, TAA, StubSize,
+                                 SectionKind::getDataNoRel());
+  Streamer.SwitchSection(S);
+  Streamer.EmitLabel(getContext().
+                     GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
+  Streamer.EmitIntValue(VersionVal, 4);
+  Streamer.EmitIntValue(GCFlags, 4);
+  Streamer.AddBlankLine();
+}
+
 const MCSection *TargetLoweringObjectFileMachO::
 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
                          Mangler *Mang, const TargetMachine &TM) const {
@@ -358,11 +440,9 @@
                                           TAA, TAAParsed, StubSize);
   if (!ErrorCode.empty()) {
     // If invalid, report the error with report_fatal_error.
-    report_fatal_error("Global variable '" + GV->getNameStr() +
-                      "' has an invalid section specifier '" + GV->getSect=
ion()+
-                      "': " + ErrorCode + ".");
-    // Fall back to dropping it into the data section.
-    return DataSection;
+    report_fatal_error("Global variable '" + GV->getName() +
+                       "' has an invalid section specifier '" +
+                       GV->getSection() + "': " + ErrorCode + ".");
   }
=20
   // Get the section.
@@ -379,9 +459,9 @@
   // to reject it here.
   if (S->getTypeAndAttributes() !=3D TAA || S->getStubSize() !=3D StubSize=
) {
     // If invalid, report the error with report_fatal_error.
-    report_fatal_error("Global variable '" + GV->getNameStr() +
-                      "' section type or attributes does not match previou=
s"
-                      " section specifier");
+    report_fatal_error("Global variable '" + GV->getName() +
+                       "' section type or attributes does not match previo=
us"
+                       " section specifier");
   }
=20
   return S;
@@ -536,9 +616,7 @@
   // Add information about the stub reference to MachOMMI so that the stub
   // gets emitted by the asmprinter.
   MCSymbol *SSym =3D getContext().GetOrCreateSymbol(Name.str());
-  MachineModuleInfoImpl::StubValueTy &StubSym =3D
-      GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
-                                  MachOMMI.getGVStubEntry(SSym);
+  MachineModuleInfoImpl::StubValueTy &StubSym =3D MachOMMI.getGVStubEntry(=
SSym);
   if (StubSym.getPointer() =3D=3D 0) {
     MCSymbol *Sym =3D Mang->getSymbol(GV);
     StubSym =3D MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinka=
ge());
@@ -568,6 +646,11 @@
       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
       COFF::IMAGE_SCN_MEM_READ |
       COFF::IMAGE_SCN_MEM_WRITE;
+  else if (K.isThreadLocal())
+    Flags |=3D
+      COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
+      COFF::IMAGE_SCN_MEM_READ |
+      COFF::IMAGE_SCN_MEM_WRITE;
   else if (K.isReadOnly())
     Flags |=3D
       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
@@ -594,6 +677,8 @@
     return ".text$";
   if (Kind.isBSS ())
     return ".bss$";
+  if (Kind.isThreadLocal())
+    return ".tls$";
   if (Kind.isWriteable())
     return ".data$";
   return ".rdata$";
@@ -603,7 +688,6 @@
 const MCSection *TargetLoweringObjectFileCOFF::
 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
                        Mangler *Mang, const TargetMachine &TM) const {
-  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
=20
   // If this global is linkonce/weak and the target handles this by emitti=
ng it
   // into a 'uniqued' section name, create and return the section now.
@@ -624,6 +708,9 @@
   if (Kind.isText())
     return getTextSection();
=20
+  if (Kind.isThreadLocal())
+    return getTLSDataSection();
+
   return getDataSection();
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/TwoAddre=
ssInstructionPass.cpp
--- a/head/contrib/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/CodeGen/TwoAddressInstructionPass.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -36,6 +36,7 @@
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/MC/MCInstrItineraries.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetMachine.h"
@@ -56,14 +57,18 @@
 STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
 STATISTIC(NumReMats,           "Number of instructions re-materialized");
 STATISTIC(NumDeletes,          "Number of dead instructions deleted");
+STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
+STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
=20
 namespace {
   class TwoAddressInstructionPass : public MachineFunctionPass {
     const TargetInstrInfo *TII;
     const TargetRegisterInfo *TRI;
+    const InstrItineraryData *InstrItins;
     MachineRegisterInfo *MRI;
     LiveVariables *LV;
     AliasAnalysis *AA;
+    CodeGenOpt::Level OptLevel;
=20
     // DistanceMap - Keep track the distance of a MI from the start of the
     // current basic block.
@@ -120,6 +125,18 @@
                            MachineBasicBlock::iterator &nmi,
                            MachineFunction::iterator &mbbi, unsigned Dist);
=20
+    bool isDefTooClose(unsigned Reg, unsigned Dist,
+                       MachineInstr *MI, MachineBasicBlock *MBB);
+
+    bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
+                               MachineBasicBlock::iterator &mi,
+                               MachineBasicBlock::iterator &nmi,
+                               unsigned Reg);
+    bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
+                               MachineBasicBlock::iterator &mi,
+                               MachineBasicBlock::iterator &nmi,
+                               unsigned Reg);
+
     bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
                                  MachineBasicBlock::iterator &nmi,
                                  MachineFunction::iterator &mbbi,
@@ -152,7 +169,6 @@
       AU.addPreserved<LiveVariables>();
       AU.addPreservedID(MachineLoopInfoID);
       AU.addPreservedID(MachineDominatorsID);
-      AU.addPreservedID(PHIEliminationID);
       MachineFunctionPass::getAnalysisUsage(AU);
     }
=20
@@ -225,12 +241,12 @@
   // appropriate location, we can try to sink the current instruction
   // past it.
   if (!KillMI || KillMI->getParent() !=3D MBB || KillMI =3D=3D MI ||
-      KillMI->getDesc().isTerminator())
+      KillMI->isTerminator())
     return false;
=20
   // If any of the definitions are used by another instruction between the
   // position and the kill use, then it's not safe to sink it.
-  //=20
+  //
   // FIXME: This can be sped up if there is an easy way to query whether an
   // instruction is before or after another instruction. Then we can use
   // MachineRegisterInfo def / use instead.
@@ -273,7 +289,7 @@
   KillMO->setIsKill(false);
   KillMO =3D MI->findRegisterUseOperand(SavedReg, false, TRI);
   KillMO->setIsKill(true);
- =20
+
   if (LV)
     LV->replaceKillInstruction(SavedReg, KillMI, MI);
=20
@@ -319,7 +335,7 @@
         continue;  // Current use.
       OtherUse =3D true;
       // There is at least one other use in the MBB that will clobber the
-      // register.=20
+      // register.
       if (isTwoAddrUse(UseMI, Reg))
         return true;
     }
@@ -467,6 +483,32 @@
   return false;
 }
=20
+/// findLocalKill - Look for an instruction below MI in the MBB that kills=
 the
+/// specified register. Returns null if there are any other Reg use betwee=
n the
+/// instructions.
+static
+MachineInstr *findLocalKill(unsigned Reg, MachineBasicBlock *MBB,
+                            MachineInstr *MI, MachineRegisterInfo *MRI,
+                            DenseMap<MachineInstr*, unsigned> &DistanceMap=
) {
+  MachineInstr *KillMI =3D 0;
+  for (MachineRegisterInfo::use_nodbg_iterator
+         UI =3D MRI->use_nodbg_begin(Reg),
+         UE =3D MRI->use_nodbg_end(); UI !=3D UE; ++UI) {
+    MachineInstr *UseMI =3D &*UI;
+    if (UseMI =3D=3D MI || UseMI->getParent() !=3D MBB)
+      continue;
+    if (DistanceMap.count(UseMI))
+      continue;
+    if (!UI.getOperand().isKill())
+      return 0;
+    if (KillMI)
+      return 0;  // -O0 kill markers cannot be trusted?
+    KillMI =3D UseMI;
+  }
+
+  return KillMI;
+}
+
 /// findOnlyInterestingUse - Given a register, if has a single in-basic bl=
ock
 /// use, return the use instruction if it's a copy or a two-address use.
 static
@@ -528,6 +570,9 @@
 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned r=
egC,
                                        MachineInstr *MI, MachineBasicBlock=
 *MBB,
                                        unsigned Dist) {
+  if (OptLevel =3D=3D CodeGenOpt::None)
+    return false;
+
   // Determine if it's profitable to commute this two address instruction.=
 In
   // general, we want no uses between this instruction and the definition =
of
   // the two-address register.
@@ -544,7 +589,7 @@
   // %reg1029<def> =3D MOV8rr %reg1028
   // %reg1029<def> =3D SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
   // insert =3D> %reg1030<def> =3D MOV8rr %reg1029
-  // %reg1030<def> =3D ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-=
def,dead> =20
+  // %reg1030<def> =3D ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-=
def,dead>
=20
   if (!MI->killsRegister(regC))
     return false;
@@ -770,10 +815,9 @@
 static bool isSafeToDelete(MachineInstr *MI,
                            const TargetInstrInfo *TII,
                            SmallVector<unsigned, 4> &Kills) {
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (MCID.mayStore() || MCID.isCall())
+  if (MI->mayStore() || MI->isCall())
     return false;
-  if (MCID.isTerminator() || MI->hasUnmodeledSideEffects())
+  if (MI->isTerminator() || MI->hasUnmodeledSideEffects())
     return false;
=20
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
@@ -852,28 +896,316 @@
   return true;
 }
=20
+/// RescheduleMIBelowKill - If there is one more local instruction that re=
ads
+/// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
+/// instruction in order to eliminate the need for the copy.
+bool
+TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
+                                     MachineBasicBlock::iterator &mi,
+                                     MachineBasicBlock::iterator &nmi,
+                                     unsigned Reg) {
+  MachineInstr *MI =3D &*mi;
+  DenseMap<MachineInstr*, unsigned>::iterator DI =3D DistanceMap.find(MI);
+  if (DI =3D=3D DistanceMap.end())
+    // Must be created from unfolded load. Don't waste time trying this.
+    return false;
+
+  MachineInstr *KillMI =3D findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
+  if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
+    // Don't mess with copies, they may be coalesced later.
+    return false;
+
+  if (KillMI->hasUnmodeledSideEffects() || KillMI->isCall() ||
+      KillMI->isBranch() || KillMI->isTerminator())
+    // Don't move pass calls, etc.
+    return false;
+
+  unsigned DstReg;
+  if (isTwoAddrUse(*KillMI, Reg, DstReg))
+    return false;
+
+  bool SeenStore =3D true;
+  if (!MI->isSafeToMove(TII, AA, SeenStore))
+    return false;
+
+  if (TII->getInstrLatency(InstrItins, MI) > 1)
+    // FIXME: Needs more sophisticated heuristics.
+    return false;
+
+  SmallSet<unsigned, 2> Uses;
+  SmallSet<unsigned, 2> Kills;
+  SmallSet<unsigned, 2> Defs;
+  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
+    const MachineOperand &MO =3D MI->getOperand(i);
+    if (!MO.isReg())
+      continue;
+    unsigned MOReg =3D MO.getReg();
+    if (!MOReg)
+      continue;
+    if (MO.isDef())
+      Defs.insert(MOReg);
+    else {
+      Uses.insert(MOReg);
+      if (MO.isKill() && MOReg !=3D Reg)
+        Kills.insert(MOReg);
+    }
+  }
+
+  // Move the copies connected to MI down as well.
+  MachineBasicBlock::iterator From =3D MI;
+  MachineBasicBlock::iterator To =3D llvm::next(From);
+  while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
+    Defs.insert(To->getOperand(0).getReg());
+    ++To;
+  }
+
+  // Check if the reschedule will not break depedencies.
+  unsigned NumVisited =3D 0;
+  MachineBasicBlock::iterator KillPos =3D KillMI;
+  ++KillPos;
+  for (MachineBasicBlock::iterator I =3D To; I !=3D KillPos; ++I) {
+    MachineInstr *OtherMI =3D I;
+    // DBG_VALUE cannot be counted against the limit.
+    if (OtherMI->isDebugValue())
+      continue;
+    if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time=
 cost.
+      return false;
+    ++NumVisited;
+    if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
+        OtherMI->isBranch() || OtherMI->isTerminator())
+      // Don't move pass calls, etc.
+      return false;
+    for (unsigned i =3D 0, e =3D OtherMI->getNumOperands(); i !=3D e; ++i)=
 {
+      const MachineOperand &MO =3D OtherMI->getOperand(i);
+      if (!MO.isReg())
+        continue;
+      unsigned MOReg =3D MO.getReg();
+      if (!MOReg)
+        continue;
+      if (MO.isDef()) {
+        if (Uses.count(MOReg))
+          // Physical register use would be clobbered.
+          return false;
+        if (!MO.isDead() && Defs.count(MOReg))
+          // May clobber a physical register def.
+          // FIXME: This may be too conservative. It's ok if the instructi=
on
+          // is sunken completely below the use.
+          return false;
+      } else {
+        if (Defs.count(MOReg))
+          return false;
+        if (MOReg !=3D Reg &&
+            ((MO.isKill() && Uses.count(MOReg)) || Kills.count(MOReg)))
+          // Don't want to extend other live ranges and update kills.
+          return false;
+      }
+    }
+  }
+
+  // Move debug info as well.
+  while (From !=3D MBB->begin() && llvm::prior(From)->isDebugValue())
+    --From;
+
+  // Copies following MI may have been moved as well.
+  nmi =3D To;
+  MBB->splice(KillPos, MBB, From, To);
+  DistanceMap.erase(DI);
+
+  if (LV) {
+    // Update live variables
+    LV->removeVirtualRegisterKilled(Reg, KillMI);
+    LV->addVirtualRegisterKilled(Reg, MI);
+  } else {
+    for (unsigned i =3D 0, e =3D KillMI->getNumOperands(); i !=3D e; ++i) {
+      MachineOperand &MO =3D KillMI->getOperand(i);
+      if (!MO.isReg() || !MO.isUse() || MO.getReg() !=3D Reg)
+        continue;
+      MO.setIsKill(false);
+    }
+    MI->addRegisterKilled(Reg, 0);
+  }
+
+  return true;
+}
+
+/// isDefTooClose - Return true if the re-scheduling will put the given
+/// instruction too close to the defs of its register dependencies.
+bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
+                                              MachineInstr *MI,
+                                              MachineBasicBlock *MBB) {
+  for (MachineRegisterInfo::def_iterator DI =3D MRI->def_begin(Reg),
+         DE =3D MRI->def_end(); DI !=3D DE; ++DI) {
+    MachineInstr *DefMI =3D &*DI;
+    if (DefMI->getParent() !=3D MBB || DefMI->isCopy() || DefMI->isCopyLik=
e())
+      continue;
+    if (DefMI =3D=3D MI)
+      return true; // MI is defining something KillMI uses
+    DenseMap<MachineInstr*, unsigned>::iterator DDI =3D DistanceMap.find(D=
efMI);
+    if (DDI =3D=3D DistanceMap.end())
+      return true;  // Below MI
+    unsigned DefDist =3D DDI->second;
+    assert(Dist > DefDist && "Visited def already?");
+    if (TII->getInstrLatency(InstrItins, DefMI) > (int)(Dist - DefDist))
+      return true;
+  }
+  return false;
+}
+
+/// RescheduleKillAboveMI - If there is one more local instruction that re=
ads
+/// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
+/// current two-address instruction in order to eliminate the need for the
+/// copy.
+bool
+TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
+                                     MachineBasicBlock::iterator &mi,
+                                     MachineBasicBlock::iterator &nmi,
+                                     unsigned Reg) {
+  MachineInstr *MI =3D &*mi;
+  DenseMap<MachineInstr*, unsigned>::iterator DI =3D DistanceMap.find(MI);
+  if (DI =3D=3D DistanceMap.end())
+    // Must be created from unfolded load. Don't waste time trying this.
+    return false;
+
+  MachineInstr *KillMI =3D findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
+  if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
+    // Don't mess with copies, they may be coalesced later.
+    return false;
+
+  unsigned DstReg;
+  if (isTwoAddrUse(*KillMI, Reg, DstReg))
+    return false;
+
+  bool SeenStore =3D true;
+  if (!KillMI->isSafeToMove(TII, AA, SeenStore))
+    return false;
+
+  SmallSet<unsigned, 2> Uses;
+  SmallSet<unsigned, 2> Kills;
+  SmallSet<unsigned, 2> Defs;
+  SmallSet<unsigned, 2> LiveDefs;
+  for (unsigned i =3D 0, e =3D KillMI->getNumOperands(); i !=3D e; ++i) {
+    const MachineOperand &MO =3D KillMI->getOperand(i);
+    if (!MO.isReg())
+      continue;
+    unsigned MOReg =3D MO.getReg();
+    if (MO.isUse()) {
+      if (!MOReg)
+        continue;
+      if (isDefTooClose(MOReg, DI->second, MI, MBB))
+        return false;
+      Uses.insert(MOReg);
+      if (MO.isKill() && MOReg !=3D Reg)
+        Kills.insert(MOReg);
+    } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
+      Defs.insert(MOReg);
+      if (!MO.isDead())
+        LiveDefs.insert(MOReg);
+    }
+  }
+
+  // Check if the reschedule will not break depedencies.
+  unsigned NumVisited =3D 0;
+  MachineBasicBlock::iterator KillPos =3D KillMI;
+  for (MachineBasicBlock::iterator I =3D mi; I !=3D KillPos; ++I) {
+    MachineInstr *OtherMI =3D I;
+    // DBG_VALUE cannot be counted against the limit.
+    if (OtherMI->isDebugValue())
+      continue;
+    if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time=
 cost.
+      return false;
+    ++NumVisited;
+    if (OtherMI->hasUnmodeledSideEffects() || OtherMI->isCall() ||
+        OtherMI->isBranch() || OtherMI->isTerminator())
+      // Don't move pass calls, etc.
+      return false;
+    SmallVector<unsigned, 2> OtherDefs;
+    for (unsigned i =3D 0, e =3D OtherMI->getNumOperands(); i !=3D e; ++i)=
 {
+      const MachineOperand &MO =3D OtherMI->getOperand(i);
+      if (!MO.isReg())
+        continue;
+      unsigned MOReg =3D MO.getReg();
+      if (!MOReg)
+        continue;
+      if (MO.isUse()) {
+        if (Defs.count(MOReg))
+          // Moving KillMI can clobber the physical register if the def has
+          // not been seen.
+          return false;
+        if (Kills.count(MOReg))
+          // Don't want to extend other live ranges and update kills.
+          return false;
+      } else {
+        OtherDefs.push_back(MOReg);
+      }
+    }
+
+    for (unsigned i =3D 0, e =3D OtherDefs.size(); i !=3D e; ++i) {
+      unsigned MOReg =3D OtherDefs[i];
+      if (Uses.count(MOReg))
+        return false;
+      if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
+          LiveDefs.count(MOReg))
+        return false;
+      // Physical register def is seen.
+      Defs.erase(MOReg);
+    }
+  }
+
+  // Move the old kill above MI, don't forget to move debug info as well.
+  MachineBasicBlock::iterator InsertPos =3D mi;
+  while (InsertPos !=3D MBB->begin() && llvm::prior(InsertPos)->isDebugVal=
ue())
+    --InsertPos;
+  MachineBasicBlock::iterator From =3D KillMI;
+  MachineBasicBlock::iterator To =3D llvm::next(From);
+  while (llvm::prior(From)->isDebugValue())
+    --From;
+  MBB->splice(InsertPos, MBB, From, To);
+
+  nmi =3D llvm::prior(InsertPos); // Backtrack so we process the moved ins=
tr.
+  DistanceMap.erase(DI);
+
+  if (LV) {
+    // Update live variables
+    LV->removeVirtualRegisterKilled(Reg, KillMI);
+    LV->addVirtualRegisterKilled(Reg, MI);
+  } else {
+    for (unsigned i =3D 0, e =3D KillMI->getNumOperands(); i !=3D e; ++i) {
+      MachineOperand &MO =3D KillMI->getOperand(i);
+      if (!MO.isReg() || !MO.isUse() || MO.getReg() !=3D Reg)
+        continue;
+      MO.setIsKill(false);
+    }
+    MI->addRegisterKilled(Reg, 0);
+  }
+  return true;
+}
+
 /// TryInstructionTransform - For the case where an instruction has a sing=
le
 /// pair of tied register operands, attempt some transformations that may
 /// either eliminate the tied operands or improve the opportunities for
-/// coalescing away the register copy.  Returns true if the tied operands
-/// are eliminated altogether.
+/// coalescing away the register copy.  Returns true if no copy needs to be
+/// inserted to untie mi's operands (either because they were untied, or
+/// because mi was rescheduled, and will be visited again later).
 bool TwoAddressInstructionPass::
 TryInstructionTransform(MachineBasicBlock::iterator &mi,
                         MachineBasicBlock::iterator &nmi,
                         MachineFunction::iterator &mbbi,
                         unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
                         SmallPtrSet<MachineInstr*, 8> &Processed) {
-  const MCInstrDesc &MCID =3D mi->getDesc();
-  unsigned regA =3D mi->getOperand(DstIdx).getReg();
-  unsigned regB =3D mi->getOperand(SrcIdx).getReg();
+  if (OptLevel =3D=3D CodeGenOpt::None)
+    return false;
+
+  MachineInstr &MI =3D *mi;
+  unsigned regA =3D MI.getOperand(DstIdx).getReg();
+  unsigned regB =3D MI.getOperand(SrcIdx).getReg();
=20
   assert(TargetRegisterInfo::isVirtualRegister(regB) &&
          "cannot make instruction into two-address form");
=20
   // If regA is dead and the instruction can be deleted, just delete
   // it so it doesn't clobber regB.
-  bool regBKilled =3D isKilled(*mi, regB, MRI, TII);
-  if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
+  bool regBKilled =3D isKilled(MI, regB, MRI, TII);
+  if (!regBKilled && MI.getOperand(DstIdx).isDead() &&
       DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
     ++NumDeletes;
     return true; // Done with this instruction.
@@ -885,20 +1217,20 @@
   unsigned regCIdx =3D ~0U;
   bool TryCommute =3D false;
   bool AggressiveCommute =3D false;
-  if (MCID.isCommutable() && mi->getNumOperands() >=3D 3 &&
-      TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
+  if (MI.isCommutable() && MI.getNumOperands() >=3D 3 &&
+      TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
     if (SrcIdx =3D=3D SrcOp1)
       regCIdx =3D SrcOp2;
     else if (SrcIdx =3D=3D SrcOp2)
       regCIdx =3D SrcOp1;
=20
     if (regCIdx !=3D ~0U) {
-      regC =3D mi->getOperand(regCIdx).getReg();
-      if (!regBKilled && isKilled(*mi, regC, MRI, TII))
+      regC =3D MI.getOperand(regCIdx).getReg();
+      if (!regBKilled && isKilled(MI, regC, MRI, TII))
         // If C dies but B does not, swap the B and C operands.
         // This makes the live ranges of A and C joinable.
         TryCommute =3D true;
-      else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
+      else if (isProfitableToCommute(regB, regC, &MI, mbbi, Dist)) {
         TryCommute =3D true;
         AggressiveCommute =3D true;
       }
@@ -913,10 +1245,17 @@
     return false;
   }
=20
+  // If there is one more use of regB later in the same MBB, consider
+  // re-schedule this MI below it.
+  if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
+    ++NumReSchedDowns;
+    return true;
+  }
+
   if (TargetRegisterInfo::isVirtualRegister(regA))
     ScanUses(regA, &*mbbi, Processed);
=20
-  if (MCID.isConvertibleTo3Addr()) {
+  if (MI.isConvertibleTo3Addr()) {
     // This instruction is potentially convertible to a true
     // three-address instruction.  Check if it is profitable.
     if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
@@ -928,6 +1267,13 @@
     }
   }
=20
+  // If there is one more use of regB later in the same MBB, consider
+  // re-schedule it before this MI if it's legal.
+  if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
+    ++NumReSchedUps;
+    return true;
+  }
+
   // If this is an instruction with a load folded into it, try unfolding
   // the load, e.g. avoid this:
   //   movq %rdx, %rcx
@@ -936,11 +1282,11 @@
   //   movq (%rax), %rcx
   //   addq %rdx, %rcx
   // because it's preferable to schedule a load than a register copy.
-  if (MCID.mayLoad() && !regBKilled) {
+  if (MI.mayLoad() && !regBKilled) {
     // Determine if a load can be unfolded.
     unsigned LoadRegIndex;
     unsigned NewOpc =3D
-      TII->getOpcodeAfterMemoryUnfold(mi->getOpcode(),
+      TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
                                       /*UnfoldLoad=3D*/true,
                                       /*UnfoldStore=3D*/false,
                                       &LoadRegIndex);
@@ -950,12 +1296,12 @@
         MachineFunction &MF =3D *mbbi->getParent();
=20
         // Unfold the load.
-        DEBUG(dbgs() << "2addr:   UNFOLDING: " << *mi);
+        DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
         const TargetRegisterClass *RC =3D
           TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI);
         unsigned Reg =3D MRI->createVirtualRegister(RC);
         SmallVector<MachineInstr *, 2> NewMIs;
-        if (!TII->unfoldMemoryOperand(MF, mi, Reg,
+        if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
                                       /*UnfoldLoad=3D*/true,/*UnfoldStore=
=3D*/false,
                                       NewMIs)) {
           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
@@ -986,21 +1332,21 @@
           // Success, or at least we made an improvement. Keep the unfolded
           // instructions and discard the original.
           if (LV) {
-            for (unsigned i =3D 0, e =3D mi->getNumOperands(); i !=3D e; +=
+i) {
-              MachineOperand &MO =3D mi->getOperand(i);
-              if (MO.isReg() &&=20
+            for (unsigned i =3D 0, e =3D MI.getNumOperands(); i !=3D e; ++=
i) {
+              MachineOperand &MO =3D MI.getOperand(i);
+              if (MO.isReg() &&
                   TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
                 if (MO.isUse()) {
                   if (MO.isKill()) {
                     if (NewMIs[0]->killsRegister(MO.getReg()))
-                      LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[0=
]);
+                      LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[=
0]);
                     else {
                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
                              "Kill missing after load unfold!");
-                      LV->replaceKillInstruction(MO.getReg(), mi, NewMIs[1=
]);
+                      LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[=
1]);
                     }
                   }
-                } else if (LV->removeVirtualRegisterDead(MO.getReg(), mi))=
 {
+                } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)=
) {
                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
                   else {
@@ -1013,7 +1359,7 @@
             }
             LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
           }
-          mi->eraseFromParent();
+          MI.eraseFromParent();
           mi =3D NewMIs[1];
           if (TransformSuccess)
             return true;
@@ -1035,18 +1381,19 @@
 /// runOnMachineFunction - Reduce two-address instructions to two operands.
 ///
 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
-  DEBUG(dbgs() << "Machine Function\n");
   const TargetMachine &TM =3D MF.getTarget();
   MRI =3D &MF.getRegInfo();
   TII =3D TM.getInstrInfo();
   TRI =3D TM.getRegisterInfo();
+  InstrItins =3D TM.getInstrItineraryData();
   LV =3D getAnalysisIfAvailable<LiveVariables>();
   AA =3D &getAnalysis<AliasAnalysis>();
+  OptLevel =3D TM.getOptLevel();
=20
   bool MadeChange =3D false;
=20
   DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
-  DEBUG(dbgs() << "********** Function: "=20
+  DEBUG(dbgs() << "********** Function: "
         << MF.getFunction()->getName() << '\n');
=20
   // This pass takes the function out of SSA form.
@@ -1177,7 +1524,7 @@
           // If it's safe and profitable, remat the definition instead of
           // copying it.
           if (DefMI &&
-              DefMI->getDesc().isAsCheapAsAMove() &&
+              DefMI->isAsCheapAsAMove() &&
               DefMI->isSafeToReMat(TII, AA, regB) &&
               isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
             DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
@@ -1248,19 +1595,19 @@
         MadeChange =3D true;
=20
         DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
-      }
=20
-      // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
-      if (mi->isInsertSubreg()) {
-        // From %reg =3D INSERT_SUBREG %reg, %subreg, subidx
-        // To   %reg:subidx =3D COPY %subreg
-        unsigned SubIdx =3D mi->getOperand(3).getImm();
-        mi->RemoveOperand(3);
-        assert(mi->getOperand(0).getSubReg() =3D=3D 0 && "Unexpected subre=
g idx");
-        mi->getOperand(0).setSubReg(SubIdx);
-        mi->RemoveOperand(1);
-        mi->setDesc(TII->get(TargetOpcode::COPY));
-        DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
+        // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA fo=
rm.
+        if (mi->isInsertSubreg()) {
+          // From %reg =3D INSERT_SUBREG %reg, %subreg, subidx
+          // To   %reg:subidx =3D COPY %subreg
+          unsigned SubIdx =3D mi->getOperand(3).getImm();
+          mi->RemoveOperand(3);
+          assert(mi->getOperand(0).getSubReg() =3D=3D 0 && "Unexpected sub=
reg idx");
+          mi->getOperand(0).setSubReg(SubIdx);
+          mi->RemoveOperand(1);
+          mi->setDesc(TII->get(TargetOpcode::COPY));
+          DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
+        }
       }
=20
       // Clear TiedOperands here instead of at the top of the loop
@@ -1298,6 +1645,36 @@
   }
 }
=20
+// Find the first def of Reg, assuming they are all in the same basic bloc=
k.
+static MachineInstr *findFirstDef(unsigned Reg, MachineRegisterInfo *MRI) {
+  SmallPtrSet<MachineInstr*, 8> Defs;
+  MachineInstr *First =3D 0;
+  for (MachineRegisterInfo::def_iterator RI =3D MRI->def_begin(Reg);
+       MachineInstr *MI =3D RI.skipInstruction(); Defs.insert(MI))
+    First =3D MI;
+  if (!First)
+    return 0;
+
+  MachineBasicBlock *MBB =3D First->getParent();
+  MachineBasicBlock::iterator A =3D First, B =3D First;
+  bool Moving;
+  do {
+    Moving =3D false;
+    if (A !=3D MBB->begin()) {
+      Moving =3D true;
+      --A;
+      if (Defs.erase(A)) First =3D A;
+    }
+    if (B !=3D MBB->end()) {
+      Defs.erase(B);
+      ++B;
+      Moving =3D true;
+    }
+  } while (Moving && !Defs.empty());
+  assert(Defs.empty() && "Instructions outside basic block!");
+  return First;
+}
+
 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
 /// EXTRACT_SUBREG from the same register and to the same virtual register
 /// with different sub-register indices, attempt to combine the
@@ -1380,8 +1757,10 @@
         CanCoalesce =3D false;
         break;
       }
-      // Keep track of one of the uses.
-      SomeMI =3D UseMI;
+      // Keep track of one of the uses.  Preferably the first one which ha=
s a
+      // <def,undef> flag.
+      if (!SomeMI || UseMI->getOperand(0).isUndef())
+        SomeMI =3D UseMI;
     }
     if (!CanCoalesce)
       continue;
@@ -1390,7 +1769,9 @@
     MachineInstr *CopyMI =3D BuildMI(*SomeMI->getParent(), SomeMI,
                                    SomeMI->getDebugLoc(),
                                    TII->get(TargetOpcode::COPY))
-      .addReg(DstReg, RegState::Define, NewDstSubIdx)
+      .addReg(DstReg, RegState::Define |
+                      getUndefRegState(SomeMI->getOperand(0).isUndef()),
+              NewDstSubIdx)
       .addReg(SrcReg, 0, NewSrcSubIdx);
=20
     // Remove all the old extract instructions.
@@ -1452,26 +1833,30 @@
     SmallSet<unsigned, 4> Seen;
     for (unsigned i =3D 1, e =3D MI->getNumOperands(); i < e; i +=3D 2) {
       unsigned SrcReg =3D MI->getOperand(i).getReg();
+      unsigned SrcSubIdx =3D MI->getOperand(i).getSubReg();
       unsigned SubIdx =3D MI->getOperand(i+1).getImm();
-      if (MI->getOperand(i).getSubReg() ||
-          TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
-        DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
-        llvm_unreachable(0);
+      // DefMI of NULL means the value does not have a vreg in this block
+      // i.e., its a physical register or a subreg.
+      // In either case we force a copy to be generated.
+      MachineInstr *DefMI =3D NULL;
+      if (!MI->getOperand(i).getSubReg() &&
+          !TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
+        DefMI =3D MRI->getVRegDef(SrcReg);
       }
=20
-      MachineInstr *DefMI =3D MRI->getVRegDef(SrcReg);
-      if (DefMI->isImplicitDef()) {
+      if (DefMI && DefMI->isImplicitDef()) {
         DefMI->eraseFromParent();
         continue;
       }
       IsImpDef =3D false;
=20
       // Remember COPY sources. These might be candidate for coalescing.
-      if (DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
+      if (DefMI && DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
         RealSrcs.push_back(DefMI->getOperand(1).getReg());
=20
       bool isKill =3D MI->getOperand(i).isKill();
-      if (!Seen.insert(SrcReg) || MI->getParent() !=3D DefMI->getParent() =
||
+      if (!DefMI || !Seen.insert(SrcReg) ||
+          MI->getParent() !=3D DefMI->getParent() ||
           !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
           !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
                                          MRI->getRegClass(SrcReg), SubIdx)=
) {
@@ -1504,9 +1889,9 @@
         MachineInstr *CopyMI =3D BuildMI(*MI->getParent(), InsertLoc,
                                 MI->getDebugLoc(), TII->get(TargetOpcode::=
COPY))
             .addReg(DstReg, RegState::Define, SubIdx)
-            .addReg(SrcReg, getKillRegState(isKill));
+            .addReg(SrcReg, getKillRegState(isKill), SrcSubIdx);
         MI->getOperand(i).setReg(0);
-        if (LV && isKill)
+        if (LV && isKill && !TargetRegisterInfo::isPhysicalRegister(SrcReg=
))
           LV->replaceKillInstruction(SrcReg, MI, CopyMI);
         DEBUG(dbgs() << "Inserted: " << *CopyMI);
       }
@@ -1519,11 +1904,27 @@
       UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
     }
=20
+    // Set <def,undef> flags on the first DstReg def in the basic block.
+    // It marks the beginning of the live range. All the other defs are
+    // read-modify-write.
+    if (MachineInstr *Def =3D findFirstDef(DstReg, MRI)) {
+      for (unsigned i =3D 0, e =3D Def->getNumOperands(); i !=3D e; ++i) {
+        MachineOperand &MO =3D Def->getOperand(i);
+        if (MO.isReg() && MO.isDef() && MO.getReg() =3D=3D DstReg)
+          MO.setIsUndef();
+      }
+      // Make sure there is a full non-subreg imp-def operand on the
+      // instruction.  This shouldn't be necessary, but it seems that at l=
east
+      // RAFast requires it.
+      Def->addRegisterDefined(DstReg, TRI);
+      DEBUG(dbgs() << "First def: " << *Def);
+    }
+
     if (IsImpDef) {
       DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
       MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
       for (int j =3D MI->getNumOperands() - 1, ee =3D 0; j > ee; --j)
-        MI->RemoveOperand(j);     =20
+        MI->RemoveOperand(j);
     } else {
       DEBUG(dbgs() << "Eliminated: " << *MI);
       MI->eraseFromParent();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/VirtRegM=
ap.cpp
--- a/head/contrib/llvm/lib/CodeGen/VirtRegMap.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/CodeGen/VirtRegMap.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -16,10 +16,9 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#define DEBUG_TYPE "virtregmap"
+#define DEBUG_TYPE "regalloc"
 #include "VirtRegMap.h"
 #include "llvm/Function.h"
-#include "llvm/CodeGen/LiveIntervalAnalysis.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
@@ -32,12 +31,8 @@
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/BitVector.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/DepthFirstIterator.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/STLExtras.h"
-#include "llvm/ADT/SmallSet.h"
 #include <algorithm>
 using namespace llvm;
=20
@@ -58,34 +53,11 @@
   TRI =3D mf.getTarget().getRegisterInfo();
   MF =3D &mf;
=20
-  ReMatId =3D MAX_STACK_SLOT+1;
-  LowSpillSlot =3D HighSpillSlot =3D NO_STACK_SLOT;
- =20
   Virt2PhysMap.clear();
   Virt2StackSlotMap.clear();
-  Virt2ReMatIdMap.clear();
   Virt2SplitMap.clear();
-  Virt2SplitKillMap.clear();
-  ReMatMap.clear();
-  ImplicitDefed.clear();
-  SpillSlotToUsesMap.clear();
-  MI2VirtMap.clear();
-  SpillPt2VirtMap.clear();
-  RestorePt2VirtMap.clear();
-  EmergencySpillMap.clear();
-  EmergencySpillSlots.clear();
- =20
-  SpillSlotToUsesMap.resize(8);
-  ImplicitDefed.resize(MF->getRegInfo().getNumVirtRegs());
-
-  allocatableRCRegs.clear();
-  for (TargetRegisterInfo::regclass_iterator I =3D TRI->regclass_begin(),
-         E =3D TRI->regclass_end(); I !=3D E; ++I)
-    allocatableRCRegs.insert(std::make_pair(*I,
-                                            TRI->getAllocatableSet(mf, *I)=
));
=20
   grow();
- =20
   return false;
 }
=20
@@ -93,24 +65,12 @@
   unsigned NumRegs =3D MF->getRegInfo().getNumVirtRegs();
   Virt2PhysMap.resize(NumRegs);
   Virt2StackSlotMap.resize(NumRegs);
-  Virt2ReMatIdMap.resize(NumRegs);
   Virt2SplitMap.resize(NumRegs);
-  Virt2SplitKillMap.resize(NumRegs);
-  ReMatMap.resize(NumRegs);
-  ImplicitDefed.resize(NumRegs);
 }
=20
 unsigned VirtRegMap::createSpillSlot(const TargetRegisterClass *RC) {
   int SS =3D MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
                                                       RC->getAlignment());
-  if (LowSpillSlot =3D=3D NO_STACK_SLOT)
-    LowSpillSlot =3D SS;
-  if (HighSpillSlot =3D=3D NO_STACK_SLOT || SS > HighSpillSlot)
-    HighSpillSlot =3D SS;
-  assert(SS >=3D LowSpillSlot && "Unexpected low spill slot");
-  unsigned Idx =3D SS-LowSpillSlot;
-  while (Idx >=3D SpillSlotToUsesMap.size())
-    SpillSlotToUsesMap.resize(SpillSlotToUsesMap.size()*2);
   ++NumSpillSlots;
   return SS;
 }
@@ -144,118 +104,6 @@
   Virt2StackSlotMap[virtReg] =3D SS;
 }
=20
-int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
-  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
-  assert(Virt2ReMatIdMap[virtReg] =3D=3D NO_STACK_SLOT &&
-         "attempt to assign re-mat id to already spilled register");
-  Virt2ReMatIdMap[virtReg] =3D ReMatId;
-  return ReMatId++;
-}
-
-void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
-  assert(TargetRegisterInfo::isVirtualRegister(virtReg));
-  assert(Virt2ReMatIdMap[virtReg] =3D=3D NO_STACK_SLOT &&
-         "attempt to assign re-mat id to already spilled register");
-  Virt2ReMatIdMap[virtReg] =3D id;
-}
-
-int VirtRegMap::getEmergencySpillSlot(const TargetRegisterClass *RC) {
-  std::map<const TargetRegisterClass*, int>::iterator I =3D
-    EmergencySpillSlots.find(RC);
-  if (I !=3D EmergencySpillSlots.end())
-    return I->second;
-  return EmergencySpillSlots[RC] =3D createSpillSlot(RC);
-}
-
-void VirtRegMap::addSpillSlotUse(int FI, MachineInstr *MI) {
-  if (!MF->getFrameInfo()->isFixedObjectIndex(FI)) {
-    // If FI < LowSpillSlot, this stack reference was produced by
-    // instruction selection and is not a spill
-    if (FI >=3D LowSpillSlot) {
-      assert(FI >=3D 0 && "Spill slot index should not be negative!");
-      assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
-             && "Invalid spill slot");
-      SpillSlotToUsesMap[FI-LowSpillSlot].insert(MI);
-    }
-  }
-}
-
-void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
-                            MachineInstr *NewMI, ModRef MRInfo) {
-  // Move previous memory references folded to new instruction.
-  MI2VirtMapTy::iterator IP =3D MI2VirtMap.lower_bound(NewMI);
-  for (MI2VirtMapTy::iterator I =3D MI2VirtMap.lower_bound(OldMI),
-         E =3D MI2VirtMap.end(); I !=3D E && I->first =3D=3D OldMI; ) {
-    MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
-    MI2VirtMap.erase(I++);
-  }
-
-  // add new memory reference
-  MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRIn=
fo)));
-}
-
-void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRI=
nfo) {
-  MI2VirtMapTy::iterator IP =3D MI2VirtMap.lower_bound(MI);
-  MI2VirtMap.insert(IP, std::make_pair(MI, std::make_pair(VirtReg, MRInfo)=
));
-}
-
-void VirtRegMap::RemoveMachineInstrFromMaps(MachineInstr *MI) {
-  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
-    MachineOperand &MO =3D MI->getOperand(i);
-    if (!MO.isFI())
-      continue;
-    int FI =3D MO.getIndex();
-    if (MF->getFrameInfo()->isFixedObjectIndex(FI))
-      continue;
-    // This stack reference was produced by instruction selection and
-    // is not a spill
-    if (FI < LowSpillSlot)
-      continue;
-    assert((unsigned)FI-LowSpillSlot < SpillSlotToUsesMap.size()
-           && "Invalid spill slot");
-    SpillSlotToUsesMap[FI-LowSpillSlot].erase(MI);
-  }
-  MI2VirtMap.erase(MI);
-  SpillPt2VirtMap.erase(MI);
-  RestorePt2VirtMap.erase(MI);
-  EmergencySpillMap.erase(MI);
-}
-
-/// FindUnusedRegisters - Gather a list of allocatable registers that
-/// have not been allocated to any virtual register.
-bool VirtRegMap::FindUnusedRegisters(LiveIntervals* LIs) {
-  unsigned NumRegs =3D TRI->getNumRegs();
-  UnusedRegs.reset();
-  UnusedRegs.resize(NumRegs);
-
-  BitVector Used(NumRegs);
-  for (unsigned i =3D 0, e =3D MRI->getNumVirtRegs(); i !=3D e; ++i) {
-    unsigned Reg =3D TargetRegisterInfo::index2VirtReg(i);
-    if (Virt2PhysMap[Reg] !=3D (unsigned)VirtRegMap::NO_PHYS_REG)
-      Used.set(Virt2PhysMap[Reg]);
-  }
-
-  BitVector Allocatable =3D TRI->getAllocatableSet(*MF);
-  bool AnyUnused =3D false;
-  for (unsigned Reg =3D 1; Reg < NumRegs; ++Reg) {
-    if (Allocatable[Reg] && !Used[Reg] && !LIs->hasInterval(Reg)) {
-      bool ReallyUnused =3D true;
-      for (const unsigned *AS =3D TRI->getAliasSet(Reg); *AS; ++AS) {
-        if (Used[*AS] || LIs->hasInterval(*AS)) {
-          ReallyUnused =3D false;
-          break;
-        }
-      }
-      if (ReallyUnused) {
-        AnyUnused =3D true;
-        UnusedRegs.set(Reg);
-      }
-    }
-  }
-
-  return AnyUnused;
-}
-
 void VirtRegMap::rewrite(SlotIndexes *Indexes) {
   DEBUG(dbgs() << "********** REWRITE VIRTUAL REGISTERS **********\n"
                << "********** Function: "
@@ -264,23 +112,32 @@
   SmallVector<unsigned, 8> SuperDeads;
   SmallVector<unsigned, 8> SuperDefs;
   SmallVector<unsigned, 8> SuperKills;
+#ifndef NDEBUG
+  BitVector Reserved =3D TRI->getReservedRegs(*MF);
+#endif
=20
   for (MachineFunction::iterator MBBI =3D MF->begin(), MBBE =3D MF->end();
        MBBI !=3D MBBE; ++MBBI) {
     DEBUG(MBBI->print(dbgs(), Indexes));
-    for (MachineBasicBlock::iterator MII =3D MBBI->begin(), MIE =3D MBBI->=
end();
-         MII !=3D MIE;) {
+    for (MachineBasicBlock::instr_iterator
+           MII =3D MBBI->instr_begin(), MIE =3D MBBI->instr_end(); MII !=
=3D MIE;) {
       MachineInstr *MI =3D MII;
       ++MII;
=20
       for (MachineInstr::mop_iterator MOI =3D MI->operands_begin(),
            MOE =3D MI->operands_end(); MOI !=3D MOE; ++MOI) {
         MachineOperand &MO =3D *MOI;
+
+        // Make sure MRI knows about registers clobbered by regmasks.
+        if (MO.isRegMask())
+          MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
+
         if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getRe=
g()))
           continue;
         unsigned VirtReg =3D MO.getReg();
         unsigned PhysReg =3D getPhys(VirtReg);
         assert(PhysReg !=3D NO_PHYS_REG && "Instruction uses unmapped Virt=
Reg");
+        assert(!Reserved.test(PhysReg) && "Reserved register assignment");
=20
         // Preserve semantics of sub-register operands.
         if (MO.getSubReg()) {
@@ -332,7 +189,6 @@
         ++NumIdCopies;
         if (MI->getNumOperands() =3D=3D 2) {
           DEBUG(dbgs() << "Deleting identity copy.\n");
-          RemoveMachineInstrFromMaps(MI);
           if (Indexes)
             Indexes->removeMachineInstrFromMaps(MI);
           // It's safe to erase MI because MII has already been incremente=
d.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/CodeGen/VirtRegM=
ap.h
--- a/head/contrib/llvm/lib/CodeGen/VirtRegMap.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/CodeGen/VirtRegMap.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -18,22 +18,14 @@
 #define LLVM_CODEGEN_VIRTREGMAP_H
=20
 #include "llvm/CodeGen/MachineFunctionPass.h"
-#include "llvm/CodeGen/LiveInterval.h"
 #include "llvm/Target/TargetRegisterInfo.h"
-#include "llvm/ADT/BitVector.h"
-#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/IndexedMap.h"
-#include "llvm/ADT/SmallPtrSet.h"
-#include "llvm/ADT/SmallVector.h"
-#include <map>
=20
 namespace llvm {
-  class LiveIntervals;
   class MachineInstr;
   class MachineFunction;
   class MachineRegisterInfo;
   class TargetInstrInfo;
-  class TargetRegisterInfo;
   class raw_ostream;
   class SlotIndexes;
=20
@@ -45,18 +37,12 @@
       MAX_STACK_SLOT =3D (1L << 18)-1
     };
=20
-    enum ModRef { isRef =3D 1, isMod =3D 2, isModRef =3D 3 };
-    typedef std::multimap<MachineInstr*,
-                          std::pair<unsigned, ModRef> > MI2VirtMapTy;
-
   private:
     MachineRegisterInfo *MRI;
     const TargetInstrInfo *TII;
     const TargetRegisterInfo *TRI;
     MachineFunction *MF;
=20
-    DenseMap<const TargetRegisterClass*, BitVector> allocatableRCRegs;
-
     /// Virt2PhysMap - This is a virtual to physical register
     /// mapping. Each virtual register is required to have an entry in
     /// it; even spilled virtual registers (the register mapped to a
@@ -70,71 +56,10 @@
     /// at.
     IndexedMap<int, VirtReg2IndexFunctor> Virt2StackSlotMap;
=20
-    /// Virt2ReMatIdMap - This is virtual register to rematerialization id
-    /// mapping. Each spilled virtual register that should be remat'd has =
an
-    /// entry in it which corresponds to the remat id.
-    IndexedMap<int, VirtReg2IndexFunctor> Virt2ReMatIdMap;
-
     /// Virt2SplitMap - This is virtual register to splitted virtual regis=
ter
     /// mapping.
     IndexedMap<unsigned, VirtReg2IndexFunctor> Virt2SplitMap;
=20
-    /// Virt2SplitKillMap - This is splitted virtual register to its last =
use
-    /// (kill) index mapping.
-    IndexedMap<SlotIndex, VirtReg2IndexFunctor> Virt2SplitKillMap;
-
-    /// ReMatMap - This is virtual register to re-materialized instruction
-    /// mapping. Each virtual register whose definition is going to be
-    /// re-materialized has an entry in it.
-    IndexedMap<MachineInstr*, VirtReg2IndexFunctor> ReMatMap;
-
-    /// MI2VirtMap - This is MachineInstr to virtual register
-    /// mapping. In the case of memory spill code being folded into
-    /// instructions, we need to know which virtual register was
-    /// read/written by this instruction.
-    MI2VirtMapTy MI2VirtMap;
-
-    /// SpillPt2VirtMap - This records the virtual registers which should
-    /// be spilled right after the MachineInstr due to live interval
-    /// splitting.
-    std::map<MachineInstr*, std::vector<std::pair<unsigned,bool> > >
-    SpillPt2VirtMap;
-
-    /// RestorePt2VirtMap - This records the virtual registers which should
-    /// be restored right before the MachineInstr due to live interval
-    /// splitting.
-    std::map<MachineInstr*, std::vector<unsigned> > RestorePt2VirtMap;
-
-    /// EmergencySpillMap - This records the physical registers that should
-    /// be spilled / restored around the MachineInstr since the register
-    /// allocator has run out of registers.
-    std::map<MachineInstr*, std::vector<unsigned> > EmergencySpillMap;
-
-    /// EmergencySpillSlots - This records emergency spill slots used to
-    /// spill physical registers when the register allocator runs out of
-    /// registers. Ideally only one stack slot is used per function per
-    /// register class.
-    std::map<const TargetRegisterClass*, int> EmergencySpillSlots;
-
-    /// ReMatId - Instead of assigning a stack slot to a to be remateriali=
zed
-    /// virtual register, an unique id is being assigned. This keeps track=
 of
-    /// the highest id used so far. Note, this starts at (1<<18) to avoid
-    /// conflicts with stack slot numbers.
-    int ReMatId;
-
-    /// LowSpillSlot, HighSpillSlot - Lowest and highest spill slot indexe=
s.
-    int LowSpillSlot, HighSpillSlot;
-
-    /// SpillSlotToUsesMap - Records uses for each register spill slot.
-    SmallVector<SmallPtrSet<MachineInstr*, 4>, 8> SpillSlotToUsesMap;
-
-    /// ImplicitDefed - One bit for each virtual register. If set it indic=
ates
-    /// the register is implicitly defined.
-    BitVector ImplicitDefed;
-
-    /// UnusedRegs - A list of physical registers that have not been used.
-    BitVector UnusedRegs;
-
     /// createSpillSlot - Allocate a spill slot for RC from MFI.
     unsigned createSpillSlot(const TargetRegisterClass *RC);
=20
@@ -144,11 +69,7 @@
   public:
     static char ID;
     VirtRegMap() : MachineFunctionPass(ID), Virt2PhysMap(NO_PHYS_REG),
-                   Virt2StackSlotMap(NO_STACK_SLOT),=20
-                   Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0),
-                   Virt2SplitKillMap(SlotIndex()), ReMatMap(NULL),
-                   ReMatId(MAX_STACK_SLOT+1),
-                   LowSpillSlot(NO_STACK_SLOT), HighSpillSlot(NO_STACK_SLO=
T) { }
+                   Virt2StackSlotMap(NO_STACK_SLOT), Virt2SplitMap(0) { }
     virtual bool runOnMachineFunction(MachineFunction &MF);
=20
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
@@ -235,8 +156,7 @@
     /// @brief returns true if the specified virtual register is not
     /// mapped to a stack slot or rematerialized.
     bool isAssignedReg(unsigned virtReg) const {
-      if (getStackSlot(virtReg) =3D=3D NO_STACK_SLOT &&
-          getReMatId(virtReg) =3D=3D NO_STACK_SLOT)
+      if (getStackSlot(virtReg) =3D=3D NO_STACK_SLOT)
         return true;
       // Split register can be assigned a physical register as well as a
       // stack slot or remat id.
@@ -250,13 +170,6 @@
       return Virt2StackSlotMap[virtReg];
     }
=20
-    /// @brief returns the rematerialization id mapped to the specified vi=
rtual
-    /// register
-    int getReMatId(unsigned virtReg) const {
-      assert(TargetRegisterInfo::isVirtualRegister(virtReg));
-      return Virt2ReMatIdMap[virtReg];
-    }
-
     /// @brief create a mapping for the specifed virtual register to
     /// the next available stack slot
     int assignVirt2StackSlot(unsigned virtReg);
@@ -264,250 +177,6 @@
     /// the specified stack slot
     void assignVirt2StackSlot(unsigned virtReg, int frameIndex);
=20
-    /// @brief assign an unique re-materialization id to the specified
-    /// virtual register.
-    int assignVirtReMatId(unsigned virtReg);
-    /// @brief assign an unique re-materialization id to the specified
-    /// virtual register.
-    void assignVirtReMatId(unsigned virtReg, int id);
-
-    /// @brief returns true if the specified virtual register is being
-    /// re-materialized.
-    bool isReMaterialized(unsigned virtReg) const {
-      return ReMatMap[virtReg] !=3D NULL;
-    }
-
-    /// @brief returns the original machine instruction being re-issued
-    /// to re-materialize the specified virtual register.
-    MachineInstr *getReMaterializedMI(unsigned virtReg) const {
-      return ReMatMap[virtReg];
-    }
-
-    /// @brief records the specified virtual register will be
-    /// re-materialized and the original instruction which will be re-issed
-    /// for this purpose.  If parameter all is true, then all uses of the
-    /// registers are rematerialized and it's safe to delete the definitio=
n.
-    void setVirtIsReMaterialized(unsigned virtReg, MachineInstr *def) {
-      ReMatMap[virtReg] =3D def;
-    }
-
-    /// @brief record the last use (kill) of a split virtual register.
-    void addKillPoint(unsigned virtReg, SlotIndex index) {
-      Virt2SplitKillMap[virtReg] =3D index;
-    }
-
-    SlotIndex getKillPoint(unsigned virtReg) const {
-      return Virt2SplitKillMap[virtReg];
-    }
-
-    /// @brief remove the last use (kill) of a split virtual register.
-    void removeKillPoint(unsigned virtReg) {
-      Virt2SplitKillMap[virtReg] =3D SlotIndex();
-    }
-
-    /// @brief returns true if the specified MachineInstr is a spill point.
-    bool isSpillPt(MachineInstr *Pt) const {
-      return SpillPt2VirtMap.find(Pt) !=3D SpillPt2VirtMap.end();
-    }
-
-    /// @brief returns the virtual registers that should be spilled due to
-    /// splitting right after the specified MachineInstr.
-    std::vector<std::pair<unsigned,bool> > &getSpillPtSpills(MachineInstr =
*Pt) {
-      return SpillPt2VirtMap[Pt];
-    }
-
-    /// @brief records the specified MachineInstr as a spill point for vir=
tReg.
-    void addSpillPoint(unsigned virtReg, bool isKill, MachineInstr *Pt) {
-      std::map<MachineInstr*, std::vector<std::pair<unsigned,bool> > >::it=
erator
-        I =3D SpillPt2VirtMap.find(Pt);
-      if (I !=3D SpillPt2VirtMap.end())
-        I->second.push_back(std::make_pair(virtReg, isKill));
-      else {
-        std::vector<std::pair<unsigned,bool> > Virts;
-        Virts.push_back(std::make_pair(virtReg, isKill));
-        SpillPt2VirtMap.insert(std::make_pair(Pt, Virts));
-      }
-    }
-
-    /// @brief - transfer spill point information from one instruction to
-    /// another.
-    void transferSpillPts(MachineInstr *Old, MachineInstr *New) {
-      std::map<MachineInstr*, std::vector<std::pair<unsigned,bool> > >::it=
erator
-        I =3D SpillPt2VirtMap.find(Old);
-      if (I =3D=3D SpillPt2VirtMap.end())
-        return;
-      while (!I->second.empty()) {
-        unsigned virtReg =3D I->second.back().first;
-        bool isKill =3D I->second.back().second;
-        I->second.pop_back();
-        addSpillPoint(virtReg, isKill, New);
-      }
-      SpillPt2VirtMap.erase(I);
-    }
-
-    /// @brief returns true if the specified MachineInstr is a restore poi=
nt.
-    bool isRestorePt(MachineInstr *Pt) const {
-      return RestorePt2VirtMap.find(Pt) !=3D RestorePt2VirtMap.end();
-    }
-
-    /// @brief returns the virtual registers that should be restoreed due =
to
-    /// splitting right after the specified MachineInstr.
-    std::vector<unsigned> &getRestorePtRestores(MachineInstr *Pt) {
-      return RestorePt2VirtMap[Pt];
-    }
-
-    /// @brief records the specified MachineInstr as a restore point for v=
irtReg.
-    void addRestorePoint(unsigned virtReg, MachineInstr *Pt) {
-      std::map<MachineInstr*, std::vector<unsigned> >::iterator I =3D
-        RestorePt2VirtMap.find(Pt);
-      if (I !=3D RestorePt2VirtMap.end())
-        I->second.push_back(virtReg);
-      else {
-        std::vector<unsigned> Virts;
-        Virts.push_back(virtReg);
-        RestorePt2VirtMap.insert(std::make_pair(Pt, Virts));
-      }
-    }
-
-    /// @brief - transfer restore point information from one instruction to
-    /// another.
-    void transferRestorePts(MachineInstr *Old, MachineInstr *New) {
-      std::map<MachineInstr*, std::vector<unsigned> >::iterator I =3D
-        RestorePt2VirtMap.find(Old);
-      if (I =3D=3D RestorePt2VirtMap.end())
-        return;
-      while (!I->second.empty()) {
-        unsigned virtReg =3D I->second.back();
-        I->second.pop_back();
-        addRestorePoint(virtReg, New);
-      }
-      RestorePt2VirtMap.erase(I);
-    }
-
-    /// @brief records that the specified physical register must be spilled
-    /// around the specified machine instr.
-    void addEmergencySpill(unsigned PhysReg, MachineInstr *MI) {
-      if (EmergencySpillMap.find(MI) !=3D EmergencySpillMap.end())
-        EmergencySpillMap[MI].push_back(PhysReg);
-      else {
-        std::vector<unsigned> PhysRegs;
-        PhysRegs.push_back(PhysReg);
-        EmergencySpillMap.insert(std::make_pair(MI, PhysRegs));
-      }
-    }
-
-    /// @brief returns true if one or more physical registers must be spil=
led
-    /// around the specified instruction.
-    bool hasEmergencySpills(MachineInstr *MI) const {
-      return EmergencySpillMap.find(MI) !=3D EmergencySpillMap.end();
-    }
-
-    /// @brief returns the physical registers to be spilled and restored a=
round
-    /// the instruction.
-    std::vector<unsigned> &getEmergencySpills(MachineInstr *MI) {
-      return EmergencySpillMap[MI];
-    }
-
-    /// @brief - transfer emergency spill information from one instruction=
 to
-    /// another.
-    void transferEmergencySpills(MachineInstr *Old, MachineInstr *New) {
-      std::map<MachineInstr*,std::vector<unsigned> >::iterator I =3D
-        EmergencySpillMap.find(Old);
-      if (I =3D=3D EmergencySpillMap.end())
-        return;
-      while (!I->second.empty()) {
-        unsigned virtReg =3D I->second.back();
-        I->second.pop_back();
-        addEmergencySpill(virtReg, New);
-      }
-      EmergencySpillMap.erase(I);
-    }
-
-    /// @brief return or get a emergency spill slot for the register class.
-    int getEmergencySpillSlot(const TargetRegisterClass *RC);
-
-    /// @brief Return lowest spill slot index.
-    int getLowSpillSlot() const {
-      return LowSpillSlot;
-    }
-
-    /// @brief Return highest spill slot index.
-    int getHighSpillSlot() const {
-      return HighSpillSlot;
-    }
-
-    /// @brief Records a spill slot use.
-    void addSpillSlotUse(int FrameIndex, MachineInstr *MI);
-
-    /// @brief Returns true if spill slot has been used.
-    bool isSpillSlotUsed(int FrameIndex) const {
-      assert(FrameIndex >=3D 0 && "Spill slot index should not be negative=
!");
-      return !SpillSlotToUsesMap[FrameIndex-LowSpillSlot].empty();
-    }
-
-    /// @brief Mark the specified register as being implicitly defined.
-    void setIsImplicitlyDefined(unsigned VirtReg) {
-      ImplicitDefed.set(TargetRegisterInfo::virtReg2Index(VirtReg));
-    }
-
-    /// @brief Returns true if the virtual register is implicitly defined.
-    bool isImplicitlyDefined(unsigned VirtReg) const {
-      return ImplicitDefed[TargetRegisterInfo::virtReg2Index(VirtReg)];
-    }
-
-    /// @brief Updates information about the specified virtual register's =
value
-    /// folded into newMI machine instruction.
-    void virtFolded(unsigned VirtReg, MachineInstr *OldMI, MachineInstr *N=
ewMI,
-                    ModRef MRInfo);
-
-    /// @brief Updates information about the specified virtual register's =
value
-    /// folded into the specified machine instruction.
-    void virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo);
-
-    /// @brief returns the virtual registers' values folded in memory
-    /// operands of this instruction
-    std::pair<MI2VirtMapTy::const_iterator, MI2VirtMapTy::const_iterator>
-    getFoldedVirts(MachineInstr* MI) const {
-      return MI2VirtMap.equal_range(MI);
-    }
-   =20
-    /// RemoveMachineInstrFromMaps - MI is being erased, remove it from the
-    /// the folded instruction map and spill point map.
-    void RemoveMachineInstrFromMaps(MachineInstr *MI);
-
-    /// FindUnusedRegisters - Gather a list of allocatable registers that
-    /// have not been allocated to any virtual register.
-    bool FindUnusedRegisters(LiveIntervals* LIs);
-
-    /// HasUnusedRegisters - Return true if there are any allocatable regi=
sters
-    /// that have not been allocated to any virtual register.
-    bool HasUnusedRegisters() const {
-      return !UnusedRegs.none();
-    }
-
-    /// setRegisterUsed - Remember the physical register is now used.
-    void setRegisterUsed(unsigned Reg) {
-      UnusedRegs.reset(Reg);
-    }
-
-    /// isRegisterUnused - Return true if the physical register has not be=
en
-    /// used.
-    bool isRegisterUnused(unsigned Reg) const {
-      return UnusedRegs[Reg];
-    }
-
-    /// getFirstUnusedRegister - Return the first physical register that h=
as not
-    /// been used.
-    unsigned getFirstUnusedRegister(const TargetRegisterClass *RC) {
-      int Reg =3D UnusedRegs.find_first();
-      while (Reg !=3D -1) {
-        if (allocatableRCRegs[RC][Reg])
-          return (unsigned)Reg;
-        Reg =3D UnusedRegs.find_next(Reg);
-      }
-      return 0;
-    }
-
     /// rewrite - Rewrite all instructions in MF to use only physical regi=
sters
     /// by mapping all virtual register operands to their assigned physical
     /// registers.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFC=
ontext.cpp
--- a/head/contrib/llvm/lib/DebugInfo/DWARFContext.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFContext.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -165,3 +165,5 @@
=20
   return DILineInfo(fileName.c_str(), row.Line, row.Column);
 }
+
+void DWARFContextInMemory::anchor() { }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFC=
ontext.h
--- a/head/contrib/llvm/lib/DebugInfo/DWARFContext.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFContext.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -86,6 +86,7 @@
 /// DWARFContext. It assumes all content is available in memory and stores
 /// pointers to it.
 class DWARFContextInMemory : public DWARFContext {
+  virtual void anchor();
   StringRef InfoSection;
   StringRef AbbrevSection;
   StringRef ARangeSection;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFD=
ebugAbbrev.cpp
--- a/head/contrib/llvm/lib/DebugInfo/DWARFDebugAbbrev.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFDebugAbbrev.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -83,7 +83,7 @@
=20
   DWARFAbbreviationDeclarationCollMapConstIter pos;
   for (pos =3D AbbrevCollMap.begin(); pos !=3D AbbrevCollMap.end(); ++pos)=
 {
-    OS << format("Abbrev table for offset: 0x%8.8x\n", pos->first);
+    OS << format("Abbrev table for offset: 0x%8.8" PRIx64 "\n", pos->first=
);
     pos->second.dump(OS);
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFD=
ebugAbbrev.h
--- a/head/contrib/llvm/lib/DebugInfo/DWARFDebugAbbrev.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFDebugAbbrev.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -25,21 +25,21 @@
   DWARFAbbreviationDeclarationCollConstIter;
=20
 class DWARFAbbreviationDeclarationSet {
-  uint64_t Offset;
+  uint32_t Offset;
   uint32_t IdxOffset;
   std::vector<DWARFAbbreviationDeclaration> Decls;
   public:
   DWARFAbbreviationDeclarationSet()
     : Offset(0), IdxOffset(0) {}
=20
-  DWARFAbbreviationDeclarationSet(uint64_t offset, uint32_t idxOffset)
+  DWARFAbbreviationDeclarationSet(uint32_t offset, uint32_t idxOffset)
     : Offset(offset), IdxOffset(idxOffset) {}
=20
   void clear() {
     IdxOffset =3D 0;
     Decls.clear();
   }
-  uint64_t getOffset() const { return Offset; }
+  uint32_t getOffset() const { return Offset; }
   void dump(raw_ostream &OS) const;
   bool extract(DataExtractor data, uint32_t* offset_ptr);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFD=
ebugArangeSet.cpp
--- a/head/contrib/llvm/lib/DebugInfo/DWARFDebugArangeSet.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFDebugArangeSet.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -122,8 +122,9 @@
   const uint32_t hex_width =3D Header.AddrSize * 2;
   for (DescriptorConstIter pos =3D ArangeDescriptors.begin(),
        end =3D ArangeDescriptors.end(); pos !=3D end; ++pos)
-    OS << format("[0x%*.*llx -", hex_width, hex_width, pos->Address)
-       << format(" 0x%*.*llx)\n", hex_width, hex_width, pos->getEndAddress=
());
+    OS << format("[0x%*.*" PRIx64 " -", hex_width, hex_width, pos->Address)
+       << format(" 0x%*.*" PRIx64 ")\n",
+                 hex_width, hex_width, pos->getEndAddress());
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFD=
ebugAranges.cpp
--- a/head/contrib/llvm/lib/DebugInfo/DWARFDebugAranges.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFDebugAranges.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -100,13 +100,14 @@
   const uint32_t num_ranges =3D getNumRanges();
   for (uint32_t i =3D 0; i < num_ranges; ++i) {
     const Range &range =3D Aranges[i];
-    OS << format("0x%8.8x: [0x%8.8llx - 0x%8.8llx)\n", range.Offset,
-                 (uint64_t)range.LoPC, (uint64_t)range.HiPC());
+    OS << format("0x%8.8x: [0x%8.8" PRIx64 " - 0x%8.8" PRIx64 ")\n",
+                 range.Offset, (uint64_t)range.LoPC, (uint64_t)range.HiPC(=
));
   }
 }
=20
 void DWARFDebugAranges::Range::dump(raw_ostream &OS) const {
-  OS << format("{0x%8.8x}: [0x%8.8llx - 0x%8.8llx)\n", Offset, LoPC, HiPC(=
));
+  OS << format("{0x%8.8x}: [0x%8.8" PRIx64 " - 0x%8.8" PRIx64 ")\n",
+               Offset, LoPC, HiPC());
 }
=20
 void DWARFDebugAranges::appendRange(uint32_t offset, uint64_t low_pc,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFD=
ebugInfoEntry.cpp
--- a/head/contrib/llvm/lib/DebugInfo/DWARFDebugInfoEntry.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFDebugInfoEntry.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -26,7 +26,7 @@
   uint32_t offset =3D Offset;
=20
   if (debug_info_data.isValidOffset(offset)) {
-    uint64_t abbrCode =3D debug_info_data.getULEB128(&offset);
+    uint32_t abbrCode =3D debug_info_data.getULEB128(&offset);
=20
     OS << format("\n0x%8.8x: ", Offset);
     if (abbrCode) {
@@ -203,8 +203,6 @@
     AbbrevDecl =3D NULL;
     return true; // NULL debug tag entry
   }
-
-  return false;
 }
=20
 bool
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFD=
ebugInfoEntry.h
--- a/head/contrib/llvm/lib/DebugInfo/DWARFDebugInfoEntry.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFDebugInfoEntry.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -23,7 +23,7 @@
 /// DWARFDebugInfoEntryMinimal - A DIE with only the minimum required data.
 class DWARFDebugInfoEntryMinimal {
   /// Offset within the .debug_info of the start of this entry.
-  uint64_t Offset;
+  uint32_t Offset;
=20
   /// How many to subtract from "this" to get the parent.
   /// If zero this die has no parent.
@@ -52,7 +52,7 @@
=20
   uint32_t getTag() const { return AbbrevDecl ? AbbrevDecl->getTag() : 0; }
   bool isNULL() const { return AbbrevDecl =3D=3D 0; }
-  uint64_t getOffset() const { return Offset; }
+  uint32_t getOffset() const { return Offset; }
   uint32_t getNumAttributes() const {
     return !isNULL() ? AbbrevDecl->getNumAttributes() : 0;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFD=
ebugLine.cpp
--- a/head/contrib/llvm/lib/DebugInfo/DWARFDebugLine.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFDebugLine.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -41,8 +41,9 @@
           "----------------\n";
     for (uint32_t i =3D 0; i < FileNames.size(); ++i) {
       const FileNameEntry& fileEntry =3D FileNames[i];
-      OS << format("file_names[%3u] %4u ", i+1, fileEntry.DirIdx)
-         << format("0x%8.8x 0x%8.8x ", fileEntry.ModTime, fileEntry.Length)
+      OS << format("file_names[%3u] %4" PRIu64 " ", i+1, fileEntry.DirIdx)
+         << format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ",
+                   fileEntry.ModTime, fileEntry.Length)
          << fileEntry.Name << '\n';
     }
   }
@@ -68,7 +69,7 @@
 }
=20
 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
-  OS << format("0x%16.16llx %6u %6u", Address, Line, Column)
+  OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
      << format(" %6u %3u ", File, Isa)
      << (IsStmt ? " is_stmt" : "")
      << (BasicBlock ? " basic_block" : "")
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/DebugInfo/DWARFF=
ormValue.cpp
--- a/head/contrib/llvm/lib/DebugInfo/DWARFFormValue.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/DebugInfo/DWARFFormValue.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -263,12 +263,12 @@
   bool cu_relative_offset =3D false;
=20
   switch (Form) {
-  case DW_FORM_addr:      OS << format("0x%016x", uvalue); break;
+  case DW_FORM_addr:      OS << format("0x%016" PRIx64, uvalue); break;
   case DW_FORM_flag:
-  case DW_FORM_data1:     OS << format("0x%02x", uvalue);  break;
-  case DW_FORM_data2:     OS << format("0x%04x", uvalue);  break;
-  case DW_FORM_data4:     OS << format("0x%08x", uvalue);  break;
-  case DW_FORM_data8:     OS << format("0x%016x", uvalue); break;
+  case DW_FORM_data1:     OS << format("0x%02x", (uint8_t)uvalue); break;
+  case DW_FORM_data2:     OS << format("0x%04x", (uint16_t)uvalue); break;
+  case DW_FORM_data4:     OS << format("0x%08x", (uint32_t)uvalue); break;
+  case DW_FORM_data8:     OS << format("0x%016" PRIx64, uvalue); break;
   case DW_FORM_string:
     OS << '"';
     OS.write_escaped(getAsCString(NULL));
@@ -280,7 +280,7 @@
   case DW_FORM_block4:
     if (uvalue > 0) {
       switch (Form) {
-      case DW_FORM_block:  OS << format("<0x%llx> ", uvalue);            b=
reak;
+      case DW_FORM_block:  OS << format("<0x%" PRIx64 "> ", uvalue);     b=
reak;
       case DW_FORM_block1: OS << format("<0x%2.2x> ", (uint8_t)uvalue);  b=
reak;
       case DW_FORM_block2: OS << format("<0x%4.4x> ", (uint16_t)uvalue); b=
reak;
       case DW_FORM_block4: OS << format("<0x%8.8x> ", (uint32_t)uvalue); b=
reak;
@@ -314,7 +314,7 @@
     break;
   }
   case DW_FORM_ref_addr:
-    OS << format("0x%016x", uvalue);
+    OS << format("0x%016" PRIx64, uvalue);
     break;
   case DW_FORM_ref1:
     cu_relative_offset =3D true;
@@ -330,11 +330,11 @@
     break;
   case DW_FORM_ref8:
     cu_relative_offset =3D true;
-    OS << format("cu + 0x%8.8llx", uvalue);
+    OS << format("cu + 0x%8.8" PRIx64, uvalue);
     break;
   case DW_FORM_ref_udata:
     cu_relative_offset =3D true;
-    OS << format("cu + 0x%llx", uvalue);
+    OS << format("cu + 0x%" PRIx64, uvalue);
     break;
=20
     // All DW_FORM_indirect attributes should be resolved prior to calling
@@ -348,7 +348,7 @@
   }
=20
   if (cu_relative_offset)
-    OS << format(" =3D> {0x%8.8x}", (uvalue + (cu ? cu->getOffset() : 0)));
+    OS << format(" =3D> {0x%8.8" PRIx64 "}", uvalue + (cu ? cu->getOffset(=
) : 0));
 }
=20
 const char*
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
ExecutionEngine.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/ExecutionEngine.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/ExecutionEngine.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -28,6 +28,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/DynamicLibrary.h"
 #include "llvm/Support/Host.h"
+#include "llvm/Support/TargetRegistry.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetMachine.h"
 #include <cmath>
@@ -41,14 +42,12 @@
   Module *M,
   std::string *ErrorStr,
   JITMemoryManager *JMM,
-  CodeGenOpt::Level OptLevel,
   bool GVsWithCode,
   TargetMachine *TM) =3D 0;
 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
   Module *M,
   std::string *ErrorStr,
   JITMemoryManager *JMM,
-  CodeGenOpt::Level OptLevel,
   bool GVsWithCode,
   TargetMachine *TM) =3D 0;
 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
@@ -308,13 +307,12 @@
=20
   // Should be an array of '{ i32, void ()* }' structs.  The first value is
   // the init priority, which we ignore.
-  if (isa<ConstantAggregateZero>(GV->getInitializer()))
+  ConstantArray *InitList =3D dyn_cast<ConstantArray>(GV->getInitializer()=
);
+  if (InitList =3D=3D 0)
     return;
-  ConstantArray *InitList =3D cast<ConstantArray>(GV->getInitializer());
   for (unsigned i =3D 0, e =3D InitList->getNumOperands(); i !=3D e; ++i) {
-    if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
-      continue;
-    ConstantStruct *CS =3D cast<ConstantStruct>(InitList->getOperand(i));
+    ConstantStruct *CS =3D dyn_cast<ConstantStruct>(InitList->getOperand(i=
));
+    if (CS =3D=3D 0) continue;
=20
     Constant *FP =3D CS->getOperand(1);
     if (FP->isNullValue())
@@ -404,14 +402,15 @@
                                          std::string *ErrorStr,
                                          CodeGenOpt::Level OptLevel,
                                          bool GVsWithCode) {
-  return EngineBuilder(M)
+  EngineBuilder EB =3D  EngineBuilder(M)
       .setEngineKind(ForceInterpreter
                      ? EngineKind::Interpreter
                      : EngineKind::JIT)
       .setErrorStr(ErrorStr)
       .setOptLevel(OptLevel)
-      .setAllocateGVsWithCode(GVsWithCode)
-      .create();
+      .setAllocateGVsWithCode(GVsWithCode);
+
+  return EB.create();
 }
=20
 /// createJIT - This is the factory method for creating a JIT for the curr=
ent
@@ -420,7 +419,7 @@
 ExecutionEngine *ExecutionEngine::createJIT(Module *M,
                                             std::string *ErrorStr,
                                             JITMemoryManager *JMM,
-                                            CodeGenOpt::Level OptLevel,
+                                            CodeGenOpt::Level OL,
                                             bool GVsWithCode,
                                             Reloc::Model RM,
                                             CodeModel::Model CMM) {
@@ -432,18 +431,25 @@
=20
   // Use the defaults for extra parameters.  Users can use EngineBuilder to
   // set them.
-  StringRef MArch =3D "";
-  StringRef MCPU =3D "";
-  SmallVector<std::string, 1> MAttrs;
+  EngineBuilder EB(M);
+  EB.setEngineKind(EngineKind::JIT);
+  EB.setErrorStr(ErrorStr);
+  EB.setRelocationModel(RM);
+  EB.setCodeModel(CMM);
+  EB.setAllocateGVsWithCode(GVsWithCode);
+  EB.setOptLevel(OL);
+  EB.setJITMemoryManager(JMM);
=20
-  TargetMachine *TM =3D
-    EngineBuilder::selectTarget(M, MArch, MCPU, MAttrs, RM, CMM, ErrorStr);
+  // TODO: permit custom TargetOptions here
+  TargetMachine *TM =3D EB.selectTarget();
   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
=20
-  return ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel, GVsWithCode,=
 TM);
+  return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
 }
=20
-ExecutionEngine *EngineBuilder::create() {
+ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
+  OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
+
   // Make sure we can resolve symbols in the program as well. The zero arg
   // to the function tells DynamicLibrary to load the program, not a libra=
ry.
   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
@@ -464,21 +470,24 @@
=20
   // Unless the interpreter was explicitly selected or the JIT is not link=
ed,
   // try making a JIT.
-  if (WhichEngine & EngineKind::JIT) {
-    if (TargetMachine *TM =3D EngineBuilder::selectTarget(M, MArch, MCPU, =
MAttrs,
-                                                        RelocModel, CMMode=
l,
-                                                        ErrorStr)) {
-      if (UseMCJIT && ExecutionEngine::MCJITCtor) {
-        ExecutionEngine *EE =3D
-          ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
-                                     AllocateGVsWithCode, TM);
-        if (EE) return EE;
-      } else if (ExecutionEngine::JITCtor) {
-        ExecutionEngine *EE =3D
-          ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
-                                   AllocateGVsWithCode, TM);
-        if (EE) return EE;
-      }
+  if ((WhichEngine & EngineKind::JIT) && TheTM) {
+    Triple TT(M->getTargetTriple());
+    if (!TM->getTarget().hasJIT()) {
+      errs() << "WARNING: This target JIT is not designed for the host"
+             << " you are running.  If bad things happen, please choose"
+             << " a different -march switch.\n";
+    }
+
+    if (UseMCJIT && ExecutionEngine::MCJITCtor) {
+      ExecutionEngine *EE =3D
+        ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
+                                   AllocateGVsWithCode, TheTM.take());
+      if (EE) return EE;
+    } else if (ExecutionEngine::JITCtor) {
+      ExecutionEngine *EE =3D
+        ExecutionEngine::JITCtor(M, ErrorStr, JMM,
+                                 AllocateGVsWithCode, TheTM.take());
+      if (EE) return EE;
     }
   }
=20
@@ -944,30 +953,47 @@
 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
   DEBUG(Init->dump());
-  if (isa<UndefValue>(Init)) {
+  if (isa<UndefValue>(Init))
     return;
-  } else if (const ConstantVector *CP =3D dyn_cast<ConstantVector>(Init)) {
+ =20
+  if (const ConstantVector *CP =3D dyn_cast<ConstantVector>(Init)) {
     unsigned ElementSize =3D
       getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
     for (unsigned i =3D 0, e =3D CP->getNumOperands(); i !=3D e; ++i)
       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
     return;
-  } else if (isa<ConstantAggregateZero>(Init)) {
+  }
+ =20
+  if (isa<ConstantAggregateZero>(Init)) {
     memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getTyp=
e()));
     return;
-  } else if (const ConstantArray *CPA =3D dyn_cast<ConstantArray>(Init)) {
+  }
+ =20
+  if (const ConstantArray *CPA =3D dyn_cast<ConstantArray>(Init)) {
     unsigned ElementSize =3D
       getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
     for (unsigned i =3D 0, e =3D CPA->getNumOperands(); i !=3D e; ++i)
       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
     return;
-  } else if (const ConstantStruct *CPS =3D dyn_cast<ConstantStruct>(Init))=
 {
+  }
+ =20
+  if (const ConstantStruct *CPS =3D dyn_cast<ConstantStruct>(Init)) {
     const StructLayout *SL =3D
       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
     for (unsigned i =3D 0, e =3D CPS->getNumOperands(); i !=3D e; ++i)
       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffse=
t(i));
     return;
-  } else if (Init->getType()->isFirstClassType()) {
+  }
+
+  if (const ConstantDataSequential *CDS =3D
+               dyn_cast<ConstantDataSequential>(Init)) {
+    // CDS is already laid out in host memory order.
+    StringRef Data =3D CDS->getRawDataValues();
+    memcpy(Addr, Data.data(), Data.size());
+    return;
+  }
+
+  if (Init->getType()->isFirstClassType()) {
     GenericValue Val =3D getConstantValue(Init);
     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
     return;
@@ -1123,6 +1149,6 @@
 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
                                                     const GlobalValue *,
                                                     const GlobalValue *) {
-  assert(false && "The ExecutionEngine doesn't know how to handle a"
-         " RAUW on a value it has a global mapping for.");
+  llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
+                   " RAUW on a value it has a global mapping for.");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
ExecutionEngineBindings.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/ExecutionEngineBindings.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -76,9 +76,7 @@
     return unwrap(GenVal)->DoubleVal;
   default:
     llvm_unreachable("LLVMGenericValueToFloat supports only float and doub=
le.");
-    break;
   }
-  return 0; // Not reached
 }
=20
 void LLVMDisposeGenericValue(LLVMGenericValueRef GenVal) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
Interpreter/Execution.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/Interpreter/Execution.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/Interpreter/Execution.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -625,24 +625,6 @@
   popStackAndReturnValueToCaller(RetTy, Result);
 }
=20
-void Interpreter::visitUnwindInst(UnwindInst &I) {
-  // Unwind stack
-  Instruction *Inst;
-  do {
-    ECStack.pop_back();
-    if (ECStack.empty())
-      report_fatal_error("Empty stack during unwind!");
-    Inst =3D ECStack.back().Caller.getInstruction();
-  } while (!(Inst && isa<InvokeInst>(Inst)));
-
-  // Return from invoke
-  ExecutionContext &InvokingSF =3D ECStack.back();
-  InvokingSF.Caller =3D CallSite();
-
-  // Go to exceptional destination BB of invoke instruction
-  SwitchToNewBasicBlock(cast<InvokeInst>(Inst)->getUnwindDest(), InvokingS=
F);
-}
-
 void Interpreter::visitUnreachableInst(UnreachableInst &I) {
   report_fatal_error("Program executed an 'unreachable' instruction!");
 }
@@ -668,12 +650,10 @@
=20
   // Check to see if any of the cases match...
   BasicBlock *Dest =3D 0;
-  unsigned NumCases =3D I.getNumCases();
-  // Skip the first item since that's the default case.
-  for (unsigned i =3D 1; i < NumCases; ++i) {
-    GenericValue CaseVal =3D getOperandValue(I.getCaseValue(i), SF);
+  for (SwitchInst::CaseIt i =3D I.case_begin(), e =3D I.case_end(); i !=3D=
 e; ++i) {
+    GenericValue CaseVal =3D getOperandValue(i.getCaseValue(), SF);
     if (executeICMP_EQ(CondVal, CaseVal, ElTy).IntVal !=3D 0) {
-      Dest =3D cast<BasicBlock>(I.getSuccessor(i));
+      Dest =3D cast<BasicBlock>(i.getCaseSuccessor());
       break;
     }
   }
@@ -1253,8 +1233,7 @@
     break;
   default:
     dbgs() << "Unhandled ConstantExpr: " << *CE << "\n";
-    llvm_unreachable(0);
-    return GenericValue();
+    llvm_unreachable("Unhandled ConstantExpr");
   }
   return Dest;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
Interpreter/ExternalFunctions.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/Interpreter/ExternalFunctions.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -94,15 +94,16 @@
   FunctionType *FT =3D F->getFunctionType();
   for (unsigned i =3D 0, e =3D FT->getNumContainedTypes(); i !=3D e; ++i)
     ExtName +=3D getTypeID(FT->getContainedType(i));
-  ExtName + "_" + F->getNameStr();
+  ExtName +=3D "_" + F->getName().str();
=20
   sys::ScopedLock Writer(*FunctionsLock);
   ExFunc FnPtr =3D FuncNames[ExtName];
   if (FnPtr =3D=3D 0)
-    FnPtr =3D FuncNames["lle_X_" + F->getNameStr()];
+    FnPtr =3D FuncNames["lle_X_" + F->getName().str()];
   if (FnPtr =3D=3D 0)  // Try calling a generic function... if it exists...
     FnPtr =3D (ExFunc)(intptr_t)
-      sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_"+F->getNameStr=
());
+      sys::DynamicLibrary::SearchForAddressOfSymbol("lle_X_" +
+                                                    F->getName().str());
   if (FnPtr !=3D 0)
     ExportedFunctions->insert(std::make_pair(F, FnPtr));  // Cache for lat=
er
   return FnPtr;
@@ -296,14 +297,8 @@
 //  Functions "exported" to the running application...
 //
=20
-// Visual Studio warns about returning GenericValue in extern "C" linkage
-#ifdef _MSC_VER
-    #pragma warning(disable : 4190)
-#endif
-
-extern "C" {  // Don't add C++ manglings to llvm mangling :)
-
 // void atexit(Function*)
+static
 GenericValue lle_X_atexit(FunctionType *FT,
                           const std::vector<GenericValue> &Args) {
   assert(Args.size() =3D=3D 1);
@@ -314,6 +309,7 @@
 }
=20
 // void exit(int)
+static
 GenericValue lle_X_exit(FunctionType *FT,
                         const std::vector<GenericValue> &Args) {
   TheInterpreter->exitCalled(Args[0]);
@@ -321,6 +317,7 @@
 }
=20
 // void abort(void)
+static
 GenericValue lle_X_abort(FunctionType *FT,
                          const std::vector<GenericValue> &Args) {
   //FIXME: should we report or raise here?
@@ -331,6 +328,7 @@
=20
 // int sprintf(char *, const char *, ...) - a very rough implementation to=
 make
 // output useful.
+static
 GenericValue lle_X_sprintf(FunctionType *FT,
                            const std::vector<GenericValue> &Args) {
   char *OutputBuffer =3D (char *)GVTOP(Args[0]);
@@ -408,11 +406,11 @@
       break;
     }
   }
-  return GV;
 }
=20
 // int printf(const char *, ...) - a very rough implementation to make out=
put
 // useful.
+static
 GenericValue lle_X_printf(FunctionType *FT,
                           const std::vector<GenericValue> &Args) {
   char Buffer[10000];
@@ -425,6 +423,7 @@
 }
=20
 // int sscanf(const char *format, ...);
+static
 GenericValue lle_X_sscanf(FunctionType *FT,
                           const std::vector<GenericValue> &args) {
   assert(args.size() < 10 && "Only handle up to 10 args to sscanf right no=
w!");
@@ -440,6 +439,7 @@
 }
=20
 // int scanf(const char *format, ...);
+static
 GenericValue lle_X_scanf(FunctionType *FT,
                          const std::vector<GenericValue> &args) {
   assert(args.size() < 10 && "Only handle up to 10 args to scanf right now=
!");
@@ -456,6 +456,7 @@
=20
 // int fprintf(FILE *, const char *, ...) - a very rough implementation to=
 make
 // output useful.
+static
 GenericValue lle_X_fprintf(FunctionType *FT,
                            const std::vector<GenericValue> &Args) {
   assert(Args.size() >=3D 2);
@@ -469,14 +470,6 @@
   return GV;
 }
=20
-} // End extern "C"
-
-// Done with externals; turn the warning back on
-#ifdef _MSC_VER
-    #pragma warning(default: 4190)
-#endif
-
-
 void Interpreter::initializeExternalFunctions() {
   sys::ScopedLock Writer(*FunctionsLock);
   FuncNames["lle_X_atexit"]       =3D lle_X_atexit;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
Interpreter/Interpreter.h
--- a/head/contrib/llvm/lib/ExecutionEngine/Interpreter/Interpreter.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/Interpreter/Interpreter.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -115,6 +115,12 @@
   virtual GenericValue runFunction(Function *F,
                                    const std::vector<GenericValue> &ArgVal=
ues);
=20
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true) {
+    // FIXME: not implemented.
+    return 0;
+  }
+
   /// recompileAndRelinkFunction - For the interpreter, functions are alwa=
ys
   /// up-to-date.
   ///
@@ -165,7 +171,6 @@
   void visitCallSite(CallSite CS);
   void visitCallInst(CallInst &I) { visitCallSite (CallSite (&I)); }
   void visitInvokeInst(InvokeInst &I) { visitCallSite (CallSite (&I)); }
-  void visitUnwindInst(UnwindInst &I);
   void visitUnreachableInst(UnreachableInst &I);
=20
   void visitShl(BinaryOperator &I);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
JIT/JIT.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/JIT/JIT.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/JIT/JIT.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -23,6 +23,7 @@
 #include "llvm/CodeGen/MachineCodeInfo.h"
 #include "llvm/ExecutionEngine/GenericValue.h"
 #include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITMemoryManager.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetJITInfo.h"
@@ -206,7 +207,6 @@
 ExecutionEngine *JIT::createJIT(Module *M,
                                 std::string *ErrorStr,
                                 JITMemoryManager *JMM,
-                                CodeGenOpt::Level OptLevel,
                                 bool GVsWithCode,
                                 TargetMachine *TM) {
   // Try to register the program as a source of symbols to resolve against.
@@ -216,7 +216,7 @@
=20
   // If the target supports JIT code generation, create the JIT.
   if (TargetJITInfo *TJ =3D TM->getJITInfo()) {
-    return new JIT(M, *TM, *TJ, JMM, OptLevel, GVsWithCode);
+    return new JIT(M, *TM, *TJ, JMM, GVsWithCode);
   } else {
     if (ErrorStr)
       *ErrorStr =3D "target does not support JIT code generation";
@@ -268,9 +268,10 @@
 }
=20
 JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
-         JITMemoryManager *JMM, CodeGenOpt::Level OptLevel, bool GVsWithCo=
de)
-  : ExecutionEngine(M), TM(tm), TJI(tji), AllocateGVsWithCode(GVsWithCode),
-    isAlreadyCodeGenerating(false) {
+         JITMemoryManager *jmm, bool GVsWithCode)
+  : ExecutionEngine(M), TM(tm), TJI(tji),
+    JMM(jmm ? jmm : JITMemoryManager::CreateDefaultMemManager()),
+    AllocateGVsWithCode(GVsWithCode), isAlreadyCodeGenerating(false) {
   setTargetData(TM.getTargetData());
=20
   jitstate =3D new JITState(M);
@@ -288,7 +289,7 @@
=20
   // Turn the machine code intermediate representation into bytes in memor=
y that
   // may be executed.
-  if (TM.addPassesToEmitMachineCode(PM, *JCE, OptLevel)) {
+  if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
     report_fatal_error("Target does not support machine code emission!");
   }
=20
@@ -323,6 +324,7 @@
   AllJits->Remove(this);
   delete jitstate;
   delete JCE;
+  // JMM is a ownership of JCE, so we no need delete JMM here.
   delete &TM;
 }
=20
@@ -341,7 +343,7 @@
=20
     // Turn the machine code intermediate representation into bytes in mem=
ory
     // that may be executed.
-    if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
+    if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
       report_fatal_error("Target does not support machine code emission!");
     }
=20
@@ -372,7 +374,7 @@
=20
     // Turn the machine code intermediate representation into bytes in mem=
ory
     // that may be executed.
-    if (TM.addPassesToEmitMachineCode(PM, *JCE, CodeGenOpt::Default)) {
+    if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
       report_fatal_error("Target does not support machine code emission!");
     }
=20
@@ -476,7 +478,6 @@
     case Type::FP128TyID:
     case Type::PPC_FP128TyID:
       llvm_unreachable("long double not supported yet");
-      return rv;
     case Type::PointerTyID:
       return PTOGV(((void*(*)())(intptr_t)FPtr)());
     }
@@ -708,12 +709,32 @@
   if (I !=3D getBasicBlockAddressMap(locked).end()) {
     return I->second;
   } else {
-    assert(0 && "JIT does not have BB address for address-of-label, was"
-           " it eliminated by optimizer?");
-    return 0;
+    llvm_unreachable("JIT does not have BB address for address-of-label, w=
as"
+                     " it eliminated by optimizer?");
   }
 }
=20
+void *JIT::getPointerToNamedFunction(const std::string &Name,
+                                     bool AbortOnFailure){
+  if (!isSymbolSearchingDisabled()) {
+    void *ptr =3D JMM->getPointerToNamedFunction(Name, false);
+    if (ptr)
+      return ptr;
+  }
+
+  /// If a LazyFunctionCreator is installed, use it to get/create the func=
tion.
+  if (LazyFunctionCreator)
+    if (void *RP =3D LazyFunctionCreator(Name))
+      return RP;
+
+  if (AbortOnFailure) {
+    report_fatal_error("Program used external function '"+Name+
+                      "' which could not be resolved!");
+  }
+  return 0;
+}
+
+
 /// getOrEmitGlobalVariable - Return the address of the specified global
 /// variable, possibly emitting it to memory if needed.  This is used by t=
he
 /// Emitter.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
JIT/JIT.h
--- a/head/contrib/llvm/lib/ExecutionEngine/JIT/JIT.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/JIT/JIT.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -58,6 +58,7 @@
   TargetMachine &TM;       // The current target we are compiling to
   TargetJITInfo &TJI;      // The JITInfo for the target we are compiling =
to
   JITCodeEmitter *JCE;     // JCE object
+  JITMemoryManager *JMM;
   std::vector<JITEventListener*> EventListeners;
=20
   /// AllocateGVsWithCode - Some applications require that global variable=
s and
@@ -78,8 +79,7 @@
=20
=20
   JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
-      JITMemoryManager *JMM, CodeGenOpt::Level OptLevel,
-      bool AllocateGVsWithCode);
+      JITMemoryManager *JMM, bool AllocateGVsWithCode);
 public:
   ~JIT();
=20
@@ -118,15 +118,15 @@
                                    const std::vector<GenericValue> &ArgVal=
ues);
=20
   /// getPointerToNamedFunction - This method returns the address of the
-  /// specified function by using the dlsym function call.  As such it is =
only
+  /// specified function by using the MemoryManager. As such it is only
   /// useful for resolving library symbols, not code generated symbols.
   ///
   /// If AbortOnFailure is false and no function with the given name is
   /// found, this function silently returns a null pointer. Otherwise,
   /// it prints a message to stderr and aborts.
   ///
-  void *getPointerToNamedFunction(const std::string &Name,
-                                  bool AbortOnFailure =3D true);
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true);
=20
   // CompilationCallback - Invoked the first time that a call site is foun=
d,
   // which causes lazy compilation of the target function.
@@ -185,7 +185,6 @@
   static ExecutionEngine *createJIT(Module *M,
                                     std::string *ErrorStr,
                                     JITMemoryManager *JMM,
-                                    CodeGenOpt::Level OptLevel,
                                     bool GVsWithCode,
                                     TargetMachine *TM);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
JIT/JITDwarfEmitter.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/JIT/JITDwarfEmitter.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/JIT/JITDwarfEmitter.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -313,7 +313,7 @@
     for (MachineBasicBlock::const_iterator MI =3D I->begin(), E =3D I->end=
();
           MI !=3D E; ++MI) {
       if (!MI->isLabel()) {
-        MayThrow |=3D MI->getDesc().isCall();
+        MayThrow |=3D MI->isCall();
         continue;
       }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
JIT/JITEmitter.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/JIT/JITEmitter.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/JIT/JITEmitter.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -14,7 +14,6 @@
=20
 #define DEBUG_TYPE "jit"
 #include "JIT.h"
-#include "JITDebugRegisterer.h"
 #include "JITDwarfEmitter.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/Constants.h"
@@ -77,8 +76,8 @@
   struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
     typedef JITResolverState *ExtraData;
     static void onRAUW(JITResolverState *, Value *Old, Value *New) {
-      assert(false && "The JIT doesn't know how to handle a"
-             " RAUW on a value it has emitted.");
+      llvm_unreachable("The JIT doesn't know how to handle a"
+                       " RAUW on a value it has emitted.");
     }
   };
=20
@@ -324,9 +323,6 @@
     /// DE - The dwarf emitter for the jit.
     OwningPtr<JITDwarfEmitter> DE;
=20
-    /// DR - The debug registerer for the jit.
-    OwningPtr<JITDebugRegisterer> DR;
-
     /// LabelLocations - This vector is a mapping from Label ID's to their
     /// address.
     DenseMap<MCSymbol*, uintptr_t> LabelLocations;
@@ -362,22 +358,22 @@
     /// Instance of the JIT
     JIT *TheJIT;
=20
+    bool JITExceptionHandling;
+
   public:
     JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
       : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
-        EmittedFunctions(this), TheJIT(&jit) {
+        EmittedFunctions(this), TheJIT(&jit),
+        JITExceptionHandling(TM.Options.JITExceptionHandling) {
       MemMgr =3D JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
       if (jit.getJITInfo().needsGOT()) {
         MemMgr->AllocateGOT();
         DEBUG(dbgs() << "JIT is managing a GOT\n");
       }
=20
-      if (JITExceptionHandling || JITEmitDebugInfo) {
+      if (JITExceptionHandling) {
         DE.reset(new JITDwarfEmitter(jit));
       }
-      if (JITEmitDebugInfo) {
-        DR.reset(new JITDebugRegisterer(TM));
-      }
     }
     ~JITEmitter() {
       delete MemMgr;
@@ -968,7 +964,7 @@
       }
     });
=20
-  if (JITExceptionHandling || JITEmitDebugInfo) {
+  if (JITExceptionHandling) {
     uintptr_t ActualSize =3D 0;
     SavedBufferBegin =3D BufferBegin;
     SavedBufferEnd =3D BufferEnd;
@@ -983,7 +979,6 @@
                                                 EhStart);
     MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
                               FrameRegister);
-    uint8_t *EhEnd =3D CurBufferPtr;
     BufferBegin =3D SavedBufferBegin;
     BufferEnd =3D SavedBufferEnd;
     CurBufferPtr =3D SavedCurBufferPtr;
@@ -991,15 +986,6 @@
     if (JITExceptionHandling) {
       TheJIT->RegisterTable(F.getFunction(), FrameRegister);
     }
-
-    if (JITEmitDebugInfo) {
-      DebugInfo I;
-      I.FnStart =3D FnStart;
-      I.FnEnd =3D FnEnd;
-      I.EhStart =3D EhStart;
-      I.EhEnd =3D EhEnd;
-      DR->RegisterFunction(F.getFunction(), I);
-    }
   }
=20
   if (MMI)
@@ -1037,17 +1023,13 @@
     EmittedFunctions.erase(Emitted);
   }
=20
-  if(JITExceptionHandling) {
+  if (JITExceptionHandling) {
     TheJIT->DeregisterTable(F);
   }
-
-  if (JITEmitDebugInfo) {
-    DR->UnregisterFunction(F);
-  }
 }
=20
=20
-void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
+void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
   if (BufferBegin)
     return JITCodeEmitter::allocateSpace(Size, Alignment);
=20
@@ -1059,7 +1041,7 @@
   return CurBufferPtr;
 }
=20
-void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
+void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
   // Delegate this call through the memory manager.
   return MemMgr->allocateGlobal(Size, Alignment);
 }
@@ -1179,6 +1161,9 @@
     }
     break;
   }
+  case MachineJumpTableInfo::EK_GPRel64BlockAddress:
+    llvm_unreachable(
+           "JT Info emission not implemented for GPRel64BlockAddress yet."=
);
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
JIT/JITMemoryManager.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/JIT/JITMemoryManager.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -23,10 +23,22 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Memory.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/DynamicLibrary.h"
+#include "llvm/Config/config.h"
 #include <vector>
 #include <cassert>
 #include <climits>
 #include <cstring>
+
+#if defined(__linux__)
+#if defined(HAVE_SYS_STAT_H)
+#include <sys/stat.h>
+#endif
+#include <fcntl.h>
+#include <unistd.h>
+#endif
+
 using namespace llvm;
=20
 STATISTIC(NumSlabs, "Number of slabs of memory allocated by the JIT");
@@ -314,6 +326,11 @@
     /// should allocate a separate slab.
     static const size_t DefaultSizeThreshold;
=20
+    /// getPointerToNamedFunction - This method returns the address of the
+    /// specified function by using the dlsym function call.
+    virtual void *getPointerToNamedFunction(const std::string &Name,
+                                            bool AbortOnFailure =3D true);
+
     void AllocateGOT();
=20
     // Testing methods.
@@ -441,6 +458,50 @@
       return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
     }
=20
+    /// allocateCodeSection - Allocate memory for a code section.
+    uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+                                 unsigned SectionID) {
+      // FIXME: Alignement handling.
+      FreeRangeHeader* candidateBlock =3D FreeMemoryList;
+      FreeRangeHeader* head =3D FreeMemoryList;
+      FreeRangeHeader* iter =3D head->Next;
+
+      uintptr_t largest =3D candidateBlock->BlockSize;
+
+      // Search for the largest free block.
+      while (iter !=3D head) {
+        if (iter->BlockSize > largest) {
+          largest =3D iter->BlockSize;
+          candidateBlock =3D iter;
+        }
+        iter =3D iter->Next;
+      }
+
+      largest =3D largest - sizeof(MemoryRangeHeader);
+
+      // If this block isn't big enough for the allocation desired, alloca=
te
+      // another block of memory and add it to the free list.
+      if (largest < Size || largest <=3D FreeRangeHeader::getMinBlockSize(=
)) {
+        DEBUG(dbgs() << "JIT: Allocating another slab of memory for functi=
on.");
+        candidateBlock =3D allocateNewCodeSlab((size_t)Size);
+      }
+
+      // Select this candidate block for allocation
+      CurBlock =3D candidateBlock;
+
+      // Allocate the entire memory block.
+      FreeMemoryList =3D candidateBlock->AllocateBlock();
+      // Release the memory at the end of this block that isn't needed.
+      FreeMemoryList =3D CurBlock->TrimAllocationToSize(FreeMemoryList, Si=
ze);
+      return (uint8_t *)(CurBlock + 1);
+    }
+
+    /// allocateDataSection - Allocate memory for a data section.
+    uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+                                 unsigned SectionID) {
+      return (uint8_t*)DataAllocator.Allocate(Size, Alignment);
+    }
+
     /// startExceptionTable - Use startFunctionBody to allocate memory for=
 the
     /// function's exception table.
     uint8_t* startExceptionTable(const Function* F, uintptr_t &ActualSize)=
 {
@@ -713,6 +774,139 @@
   return true;
 }
=20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// getPointerToNamedFunction() implementation.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+// AtExitHandlers - List of functions to call when the program exits,
+// registered with the atexit() library function.
+static std::vector<void (*)()> AtExitHandlers;
+
+/// runAtExitHandlers - Run any functions registered by the program's
+/// calls to atexit(3), which we intercept and store in
+/// AtExitHandlers.
+///
+static void runAtExitHandlers() {
+  while (!AtExitHandlers.empty()) {
+    void (*Fn)() =3D AtExitHandlers.back();
+    AtExitHandlers.pop_back();
+    Fn();
+  }
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Function stubs that are invoked instead of certain library calls
+//
+// Force the following functions to be linked in to anything that uses the
+// JIT. This is a hack designed to work around the all-too-clever Glibc
+// strategy of making these functions work differently when inlined vs. wh=
en
+// not inlined, and hiding their real definitions in a separate archive fi=
le
+// that the dynamic linker can't see. For more info, search for
+// 'libc_nonshared.a' on Google, or read http://llvm.org/PR274.
+#if defined(__linux__)
+/* stat functions are redirecting to __xstat with a version number.  On x8=
6-64
+ * linking with libc_nonshared.a and -Wl,--export-dynamic doesn't make 'st=
at'
+ * available as an exported symbol, so we have to add it explicitly.
+ */
+namespace {
+class StatSymbols {
+public:
+  StatSymbols() {
+    sys::DynamicLibrary::AddSymbol("stat", (void*)(intptr_t)stat);
+    sys::DynamicLibrary::AddSymbol("fstat", (void*)(intptr_t)fstat);
+    sys::DynamicLibrary::AddSymbol("lstat", (void*)(intptr_t)lstat);
+    sys::DynamicLibrary::AddSymbol("stat64", (void*)(intptr_t)stat64);
+    sys::DynamicLibrary::AddSymbol("\x1stat64", (void*)(intptr_t)stat64);
+    sys::DynamicLibrary::AddSymbol("\x1open64", (void*)(intptr_t)open64);
+    sys::DynamicLibrary::AddSymbol("\x1lseek64", (void*)(intptr_t)lseek64);
+    sys::DynamicLibrary::AddSymbol("fstat64", (void*)(intptr_t)fstat64);
+    sys::DynamicLibrary::AddSymbol("lstat64", (void*)(intptr_t)lstat64);
+    sys::DynamicLibrary::AddSymbol("atexit", (void*)(intptr_t)atexit);
+    sys::DynamicLibrary::AddSymbol("mknod", (void*)(intptr_t)mknod);
+  }
+};
+}
+static StatSymbols initStatSymbols;
+#endif // __linux__
+
+// jit_exit - Used to intercept the "exit" library call.
+static void jit_exit(int Status) {
+  runAtExitHandlers();   // Run atexit handlers...
+  exit(Status);
+}
+
+// jit_atexit - Used to intercept the "atexit" library call.
+static int jit_atexit(void (*Fn)()) {
+  AtExitHandlers.push_back(Fn);    // Take note of atexit handler...
+  return 0;  // Always successful
+}
+
+static int jit_noop() {
+  return 0;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//
+/// getPointerToNamedFunction - This method returns the address of the spe=
cified
+/// function by using the dynamic loader interface.  As such it is only us=
eful
+/// for resolving library symbols, not code generated symbols.
+///
+void *DefaultJITMemoryManager::getPointerToNamedFunction(const std::string=
 &Name,
+                                     bool AbortOnFailure) {
+  // Check to see if this is one of the functions we want to intercept.  N=
ote,
+  // we cast to intptr_t here to silence a -pedantic warning that complains
+  // about casting a function pointer to a normal pointer.
+  if (Name =3D=3D "exit") return (void*)(intptr_t)&jit_exit;
+  if (Name =3D=3D "atexit") return (void*)(intptr_t)&jit_atexit;
+
+  // We should not invoke parent's ctors/dtors from generated main()!
+  // On Mingw and Cygwin, the symbol __main is resolved to
+  // callee's(eg. tools/lli) one, to invoke wrong duplicated ctors
+  // (and register wrong callee's dtors with atexit(3)).
+  // We expect ExecutionEngine::runStaticConstructorsDestructors()
+  // is called before ExecutionEngine::runFunctionAsMain() is called.
+  if (Name =3D=3D "__main") return (void*)(intptr_t)&jit_noop;
+
+  const char *NameStr =3D Name.c_str();
+  // If this is an asm specifier, skip the sentinal.
+  if (NameStr[0] =3D=3D 1) ++NameStr;
+
+  // If it's an external function, look it up in the process image...
+  void *Ptr =3D sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr);
+  if (Ptr) return Ptr;
+
+  // If it wasn't found and if it starts with an underscore ('_') characte=
r,
+  // try again without the underscore.
+  if (NameStr[0] =3D=3D '_') {
+    Ptr =3D sys::DynamicLibrary::SearchForAddressOfSymbol(NameStr+1);
+    if (Ptr) return Ptr;
+  }
+
+  // Darwin/PPC adds $LDBLStub suffixes to various symbols like printf.  T=
hese
+  // are references to hidden visibility symbols that dlsym cannot resolve.
+  // If we have one of these, strip off $LDBLStub and try again.
+#if defined(__APPLE__) && defined(__ppc__)
+  if (Name.size() > 9 && Name[Name.size()-9] =3D=3D '$' &&
+      memcmp(&Name[Name.size()-8], "LDBLStub", 8) =3D=3D 0) {
+    // First try turning $LDBLStub into $LDBL128. If that fails, strip it =
off.
+    // This mirrors logic in libSystemStubs.a.
+    std::string Prefix =3D std::string(Name.begin(), Name.end()-9);
+    if (void *Ptr =3D getPointerToNamedFunction(Prefix+"$LDBL128", false))
+      return Ptr;
+    if (void *Ptr =3D getPointerToNamedFunction(Prefix, false))
+      return Ptr;
+  }
+#endif
+
+  if (AbortOnFailure) {
+    report_fatal_error("Program used external function '"+Name+
+                      "' which could not be resolved!");
+  }
+  return 0;
+}
+
+
+
 JITMemoryManager *JITMemoryManager::CreateDefaultMemManager() {
   return new DefaultJITMemoryManager();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
MCJIT/MCJIT.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJIT.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -36,7 +36,6 @@
 ExecutionEngine *MCJIT::createJIT(Module *M,
                                   std::string *ErrorStr,
                                   JITMemoryManager *JMM,
-                                  CodeGenOpt::Level OptLevel,
                                   bool GVsWithCode,
                                   TargetMachine *TM) {
   // Try to register the program as a source of symbols to resolve against.
@@ -46,8 +45,7 @@
=20
   // If the target supports JIT code generation, create the JIT.
   if (TargetJITInfo *TJ =3D TM->getJITInfo())
-    return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM, M), OptLevel,
-                     GVsWithCode);
+    return new MCJIT(M, TM, *TJ, new MCJITMemoryManager(JMM, M), GVsWithCo=
de);
=20
   if (ErrorStr)
     *ErrorStr =3D "target does not support JIT code generation";
@@ -55,8 +53,7 @@
 }
=20
 MCJIT::MCJIT(Module *m, TargetMachine *tm, TargetJITInfo &tji,
-             RTDyldMemoryManager *MM, CodeGenOpt::Level OptLevel,
-             bool AllocateGVsWithCode)
+             RTDyldMemoryManager *MM, bool AllocateGVsWithCode)
   : ExecutionEngine(m), TM(tm), MemMgr(MM), M(m), OS(Buffer), Dyld(MM) {
=20
   setTargetData(TM->getTargetData());
@@ -64,7 +61,7 @@
=20
   // Turn the machine code intermediate representation into bytes in memory
   // that may be executed.
-  if (TM->addPassesToEmitMC(PM, Ctx, OS, CodeGenOpt::Default, false)) {
+  if (TM->addPassesToEmitMC(PM, Ctx, OS, false)) {
     report_fatal_error("Target does not support MC emission!");
   }
=20
@@ -77,9 +74,9 @@
   OS.flush();
=20
   // Load the object into the dynamic linker.
-  // FIXME: It would be nice to avoid making yet another copy.
-  MemoryBuffer *MB =3D MemoryBuffer::getMemBufferCopy(StringRef(Buffer.dat=
a(),
-                                                              Buffer.size(=
)));
+  MemoryBuffer *MB =3D MemoryBuffer::getMemBuffer(StringRef(Buffer.data(),
+                                                          Buffer.size()),
+                                                "", false);
   if (Dyld.loadObject(MB))
     report_fatal_error(Dyld.getErrorString());
   // Resolve any relocations.
@@ -88,11 +85,11 @@
=20
 MCJIT::~MCJIT() {
   delete MemMgr;
+  delete TM;
 }
=20
 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
   report_fatal_error("not yet implemented");
-  return 0;
 }
=20
 void *MCJIT::getPointerToFunction(Function *F) {
@@ -211,12 +208,30 @@
     case Type::FP128TyID:
     case Type::PPC_FP128TyID:
       llvm_unreachable("long double not supported yet");
-      return rv;
     case Type::PointerTyID:
       return PTOGV(((void*(*)())(intptr_t)FPtr)());
     }
   }
=20
-  assert(0 && "Full-featured argument passing not supported yet!");
-  return GenericValue();
+  llvm_unreachable("Full-featured argument passing not supported yet!");
 }
+
+void *MCJIT::getPointerToNamedFunction(const std::string &Name,
+                                       bool AbortOnFailure){
+  if (!isSymbolSearchingDisabled() && MemMgr) {
+    void *ptr =3D MemMgr->getPointerToNamedFunction(Name, false);
+    if (ptr)
+      return ptr;
+  }
+
+  /// If a LazyFunctionCreator is installed, use it to get/create the func=
tion.
+  if (LazyFunctionCreator)
+    if (void *RP =3D LazyFunctionCreator(Name))
+      return RP;
+
+  if (AbortOnFailure) {
+    report_fatal_error("Program used external function '"+Name+
+                      "' which could not be resolved!");
+  }
+  return 0;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
MCJIT/MCJIT.h
--- a/head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJIT.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -24,8 +24,7 @@
=20
 class MCJIT : public ExecutionEngine {
   MCJIT(Module *M, TargetMachine *tm, TargetJITInfo &tji,
-        RTDyldMemoryManager *MemMgr, CodeGenOpt::Level OptLevel,
-        bool AllocateGVsWithCode);
+        RTDyldMemoryManager *MemMgr, bool AllocateGVsWithCode);
=20
   TargetMachine *TM;
   MCContext *Ctx;
@@ -66,8 +65,17 @@
   /// found, this function silently returns a null pointer. Otherwise,
   /// it prints a message to stderr and aborts.
   ///
-  void *getPointerToNamedFunction(const std::string &Name,
-                                  bool AbortOnFailure =3D true);
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true);
+
+  /// mapSectionAddress - map a section to its target address space value.
+  /// Map the address of a JIT section as returned from the memory manager
+  /// to the address in the target process as the running code will see it.
+  /// This is the address which will be used for relocation resolution.
+  virtual void mapSectionAddress(void *LocalAddress, uint64_t TargetAddres=
s) {
+    Dyld.mapSectionAddress(LocalAddress, TargetAddress);
+  }
+
   /// @}
   /// @name (Private) Registration Interfaces
   /// @{
@@ -79,7 +87,6 @@
   static ExecutionEngine *createJIT(Module *M,
                                     std::string *ErrorStr,
                                     JITMemoryManager *JMM,
-                                    CodeGenOpt::Level OptLevel,
                                     bool GVsWithCode,
                                     TargetMachine *TM);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
MCJIT/MCJITMemoryManager.h
--- a/head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJITMemoryManager.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/MCJIT/MCJITMemoryManager.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -21,45 +21,30 @@
 // and the RuntimeDyld interface that maps objects, by name, onto their
 // matching LLVM IR counterparts in the module(s) being compiled.
 class MCJITMemoryManager : public RTDyldMemoryManager {
+  virtual void anchor();
   JITMemoryManager *JMM;
=20
   // FIXME: Multiple modules.
   Module *M;
 public:
-  MCJITMemoryManager(JITMemoryManager *jmm, Module *m) : JMM(jmm), M(m) {}
+  MCJITMemoryManager(JITMemoryManager *jmm, Module *m) :
+    JMM(jmm?jmm:JITMemoryManager::CreateDefaultMemManager()), M(m) {}
+  // We own the JMM, so make sure to delete it.
+  ~MCJITMemoryManager() { delete JMM; }
=20
-  // Allocate ActualSize bytes, or more, for the named function. Return
-  // a pointer to the allocated memory and update Size to reflect how much
-  // memory was acutally allocated.
-  uint8_t *startFunctionBody(const char *Name, uintptr_t &Size) {
-    // FIXME: This should really reference the MCAsmInfo to get the global
-    //        prefix.
-    if (Name[0] =3D=3D '_') ++Name;
-    Function *F =3D M->getFunction(Name);
-    // Some ObjC names have a prefixed \01 in the IR. If we failed to find
-    // the symbol and it's of the ObjC conventions (starts with "-"), try
-    // prepending a \01 and see if we can find it that way.
-    if (!F && Name[0] =3D=3D '-')
-      F =3D M->getFunction((Twine("\1") + Name).str());
-    assert(F && "No matching function in JIT IR Module!");
-    return JMM->startFunctionBody(F, Size);
+  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+                               unsigned SectionID) {
+    return JMM->allocateSpace(Size, Alignment);
   }
=20
-  // Mark the end of the function, including how much of the allocated
-  // memory was actually used.
-  void endFunctionBody(const char *Name, uint8_t *FunctionStart,
-                       uint8_t *FunctionEnd) {
-    // FIXME: This should really reference the MCAsmInfo to get the global
-    //        prefix.
-    if (Name[0] =3D=3D '_') ++Name;
-    Function *F =3D M->getFunction(Name);
-    // Some ObjC names have a prefixed \01 in the IR. If we failed to find
-    // the symbol and it's of the ObjC conventions (starts with "-"), try
-    // prepending a \01 and see if we can find it that way.
-    if (!F && Name[0] =3D=3D '-')
-      F =3D M->getFunction((Twine("\1") + Name).str());
-    assert(F && "No matching function in JIT IR Module!");
-    JMM->endFunctionBody(F, FunctionStart, FunctionEnd);
+  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+                               unsigned SectionID) {
+    return JMM->allocateSpace(Size, Alignment);
+  }
+
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true) {
+    return JMM->getPointerToNamedFunction(Name, AbortOnFailure);
   }
=20
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
RuntimeDyld/RuntimeDyld.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyld.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ------*=
- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,6 +13,10 @@
=20
 #define DEBUG_TYPE "dyld"
 #include "RuntimeDyldImpl.h"
+#include "RuntimeDyldELF.h"
+#include "RuntimeDyldMachO.h"
+#include "llvm/Support/Path.h"
+
 using namespace llvm;
 using namespace llvm::object;
=20
@@ -22,35 +26,383 @@
=20
 namespace llvm {
=20
-void RuntimeDyldImpl::extractFunction(StringRef Name, uint8_t *StartAddres=
s,
-                                      uint8_t *EndAddress) {
-  // Allocate memory for the function via the memory manager.
-  uintptr_t Size =3D EndAddress - StartAddress + 1;
-  uintptr_t AllocSize =3D Size;
-  uint8_t *Mem =3D MemMgr->startFunctionBody(Name.data(), AllocSize);
-  assert(Size >=3D (uint64_t)(EndAddress - StartAddress + 1) &&
-         "Memory manager failed to allocate enough memory!");
-  // Copy the function payload into the memory block.
-  memcpy(Mem, StartAddress, Size);
-  MemMgr->endFunctionBody(Name.data(), Mem, Mem + Size);
-  // Remember where we put it.
-  Functions[Name] =3D sys::MemoryBlock(Mem, Size);
-  // Default the assigned address for this symbol to wherever this
-  // allocated it.
-  SymbolTable[Name] =3D Mem;
-  DEBUG(dbgs() << "    allocated to [" << Mem << ", " << Mem + Size << "]\=
n");
-}
+namespace {
+  // Helper for extensive error checking in debug builds.
+  error_code Check(error_code Err) {
+    if (Err) {
+      report_fatal_error(Err.message());
+    }
+    return Err;
+  }
+} // end anonymous namespace
=20
 // Resolve the relocations for all symbols we currently know about.
 void RuntimeDyldImpl::resolveRelocations() {
-  // Just iterate over the symbols in our symbol table and assign their
-  // addresses.
-  StringMap<uint8_t*>::iterator i =3D SymbolTable.begin();
-  StringMap<uint8_t*>::iterator e =3D SymbolTable.end();
-  for (;i !=3D e; ++i)
-    reassignSymbolAddress(i->getKey(), i->getValue());
+  // First, resolve relocations associated with external symbols.
+  resolveSymbols();
+
+  // Just iterate over the sections we have and resolve all the relocations
+  // in them. Gross overkill, but it gets the job done.
+  for (int i =3D 0, e =3D Sections.size(); i !=3D e; ++i) {
+    reassignSectionAddress(i, Sections[i].LoadAddress);
+  }
 }
=20
+void RuntimeDyldImpl::mapSectionAddress(void *LocalAddress,
+                                        uint64_t TargetAddress) {
+  for (unsigned i =3D 0, e =3D Sections.size(); i !=3D e; ++i) {
+    if (Sections[i].Address =3D=3D LocalAddress) {
+      reassignSectionAddress(i, TargetAddress);
+      return;
+    }
+  }
+  llvm_unreachable("Attempting to remap address of unknown section!");
+}
+
+bool RuntimeDyldImpl::loadObject(const MemoryBuffer *InputBuffer) {
+  // FIXME: ObjectFile don't modify MemoryBuffer.
+  //        It should use const MemoryBuffer as parameter.
+  OwningPtr<ObjectFile> obj(ObjectFile::createObjectFile(
+                                       const_cast<MemoryBuffer*>(InputBuff=
er)));
+  if (!obj)
+    report_fatal_error("Unable to create object image from memory buffer!"=
);
+
+  Arch =3D (Triple::ArchType)obj->getArch();
+
+  LocalSymbolMap LocalSymbols;     // Functions and data symbols from the
+                                   // object file.
+  ObjSectionToIDMap LocalSections; // Used sections from the object file
+  CommonSymbolMap   CommonSymbols; // Common symbols requiring allocation
+  uint64_t          CommonSize =3D 0;
+
+  error_code err;
+  // Parse symbols
+  DEBUG(dbgs() << "Parse symbols:\n");
+  for (symbol_iterator i =3D obj->begin_symbols(), e =3D obj->end_symbols(=
);
+       i !=3D e; i.increment(err)) {
+    Check(err);
+    object::SymbolRef::Type SymType;
+    StringRef Name;
+    Check(i->getType(SymType));
+    Check(i->getName(Name));
+
+    uint32_t flags;
+    Check(i->getFlags(flags));
+
+    bool isCommon =3D flags & SymbolRef::SF_Common;
+    if (isCommon) {
+      // Add the common symbols to a list.  We'll allocate them all below.
+      uint64_t Size =3D 0;
+      Check(i->getSize(Size));
+      CommonSize +=3D Size;
+      CommonSymbols[*i] =3D Size;
+    } else {
+      if (SymType =3D=3D object::SymbolRef::ST_Function ||
+          SymType =3D=3D object::SymbolRef::ST_Data) {
+        uint64_t FileOffset;
+        StringRef sData;
+        section_iterator si =3D obj->end_sections();
+        Check(i->getFileOffset(FileOffset));
+        Check(i->getSection(si));
+        if (si =3D=3D obj->end_sections()) continue;
+        Check(si->getContents(sData));
+        const uint8_t* SymPtr =3D (const uint8_t*)InputBuffer->getBufferSt=
art() +
+                                (uintptr_t)FileOffset;
+        uintptr_t SectOffset =3D (uintptr_t)(SymPtr - (const uint8_t*)sDat=
a.begin());
+        unsigned SectionID =3D
+          findOrEmitSection(*si,
+                            SymType =3D=3D object::SymbolRef::ST_Function,
+                            LocalSections);
+        bool isGlobal =3D flags & SymbolRef::SF_Global;
+        LocalSymbols[Name.data()] =3D SymbolLoc(SectionID, SectOffset);
+        DEBUG(dbgs() << "\tFileOffset: " << format("%p", (uintptr_t)FileOf=
fset)
+                     << " flags: " << flags
+                     << " SID: " << SectionID
+                     << " Offset: " << format("%p", SectOffset));
+        if (isGlobal)
+          SymbolTable[Name] =3D SymbolLoc(SectionID, SectOffset);
+      }
+    }
+    DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name << "\n");
+  }
+
+  // Allocate common symbols
+  if (CommonSize !=3D 0)
+    emitCommonSymbols(CommonSymbols, CommonSize, LocalSymbols);
+
+  // Parse and proccess relocations
+  DEBUG(dbgs() << "Parse relocations:\n");
+  for (section_iterator si =3D obj->begin_sections(),
+       se =3D obj->end_sections(); si !=3D se; si.increment(err)) {
+    Check(err);
+    bool isFirstRelocation =3D true;
+    unsigned SectionID =3D 0;
+    StubMap Stubs;
+
+    for (relocation_iterator i =3D si->begin_relocations(),
+         e =3D si->end_relocations(); i !=3D e; i.increment(err)) {
+      Check(err);
+
+      // If it's first relocation in this section, find its SectionID
+      if (isFirstRelocation) {
+        SectionID =3D findOrEmitSection(*si, true, LocalSections);
+        DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
+        isFirstRelocation =3D false;
+      }
+
+      ObjRelocationInfo RI;
+      RI.SectionID =3D SectionID;
+      Check(i->getAdditionalInfo(RI.AdditionalInfo));
+      Check(i->getOffset(RI.Offset));
+      Check(i->getSymbol(RI.Symbol));
+      Check(i->getType(RI.Type));
+
+      DEBUG(dbgs() << "\t\tAddend: " << RI.AdditionalInfo
+                   << " Offset: " << format("%p", (uintptr_t)RI.Offset)
+                   << " Type: " << (uint32_t)(RI.Type & 0xffffffffL)
+                   << "\n");
+      processRelocationRef(RI, *obj, LocalSections, LocalSymbols, Stubs);
+    }
+  }
+  return false;
+}
+
+unsigned RuntimeDyldImpl::emitCommonSymbols(const CommonSymbolMap &Map,
+                                            uint64_t TotalSize,
+                                            LocalSymbolMap &LocalSymbols) {
+  // Allocate memory for the section
+  unsigned SectionID =3D Sections.size();
+  uint8_t *Addr =3D MemMgr->allocateDataSection(TotalSize, sizeof(void*),
+                                              SectionID);
+  if (!Addr)
+    report_fatal_error("Unable to allocate memory for common symbols!");
+  uint64_t Offset =3D 0;
+  Sections.push_back(SectionEntry(Addr, TotalSize, TotalSize, 0));
+  memset(Addr, 0, TotalSize);
+
+  DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
+               << " new addr: " << format("%p", Addr)
+               << " DataSize: " << TotalSize
+               << "\n");
+
+  // Assign the address of each symbol
+  for (CommonSymbolMap::const_iterator it =3D Map.begin(), itEnd =3D Map.e=
nd();
+       it !=3D itEnd; it++) {
+    uint64_t Size =3D it->second;
+    StringRef Name;
+    it->first.getName(Name);
+    LocalSymbols[Name.data()] =3D SymbolLoc(SectionID, Offset);
+    Offset +=3D Size;
+    Addr +=3D Size;
+  }
+
+  return SectionID;
+}
+
+unsigned RuntimeDyldImpl::emitSection(const SectionRef &Section,
+                                      bool IsCode) {
+
+  unsigned StubBufSize =3D 0,
+           StubSize =3D getMaxStubSize();
+  error_code err;
+  if (StubSize > 0) {
+    for (relocation_iterator i =3D Section.begin_relocations(),
+         e =3D Section.end_relocations(); i !=3D e; i.increment(err), Chec=
k(err))
+      StubBufSize +=3D StubSize;
+  }
+  StringRef data;
+  uint64_t Alignment64;
+  Check(Section.getContents(data));
+  Check(Section.getAlignment(Alignment64));
+
+  unsigned Alignment =3D (unsigned)Alignment64 & 0xffffffffL;
+  bool IsRequired;
+  bool IsVirtual;
+  bool IsZeroInit;
+  uint64_t DataSize;
+  Check(Section.isRequiredForExecution(IsRequired));
+  Check(Section.isVirtual(IsVirtual));
+  Check(Section.isZeroInit(IsZeroInit));
+  Check(Section.getSize(DataSize));
+
+  unsigned Allocate;
+  unsigned SectionID =3D Sections.size();
+  uint8_t *Addr;
+  const char *pData =3D 0;
+
+  // Some sections, such as debug info, don't need to be loaded for execut=
ion.
+  // Leave those where they are.
+  if (IsRequired) {
+    Allocate =3D DataSize + StubBufSize;
+    Addr =3D IsCode
+      ? MemMgr->allocateCodeSection(Allocate, Alignment, SectionID)
+      : MemMgr->allocateDataSection(Allocate, Alignment, SectionID);
+    if (!Addr)
+      report_fatal_error("Unable to allocate section memory!");
+
+    // Virtual sections have no data in the object image, so leave pData =
=3D 0
+    if (!IsVirtual)
+      pData =3D data.data();
+
+    // Zero-initialize or copy the data from the image
+    if (IsZeroInit || IsVirtual)
+      memset(Addr, 0, DataSize);
+    else
+      memcpy(Addr, pData, DataSize);
+
+    DEBUG(dbgs() << "emitSection SectionID: " << SectionID
+                 << " obj addr: " << format("%p", pData)
+                 << " new addr: " << format("%p", Addr)
+                 << " DataSize: " << DataSize
+                 << " StubBufSize: " << StubBufSize
+                 << " Allocate: " << Allocate
+                 << "\n");
+  }
+  else {
+    // Even if we didn't load the section, we need to record an entry for =
it
+    //   to handle later processing (and by 'handle' I mean don't do anyth=
ing
+    //   with these sections).
+    Allocate =3D 0;
+    Addr =3D 0;
+    DEBUG(dbgs() << "emitSection SectionID: " << SectionID
+                 << " obj addr: " << format("%p", data.data())
+                 << " new addr: 0"
+                 << " DataSize: " << DataSize
+                 << " StubBufSize: " << StubBufSize
+                 << " Allocate: " << Allocate
+                 << "\n");
+  }
+
+  Sections.push_back(SectionEntry(Addr, Allocate, DataSize,(uintptr_t)pDat=
a));
+  return SectionID;
+}
+
+unsigned RuntimeDyldImpl::findOrEmitSection(const SectionRef &Section,
+                                            bool IsCode,
+                                            ObjSectionToIDMap &LocalSectio=
ns) {
+
+  unsigned SectionID =3D 0;
+  ObjSectionToIDMap::iterator i =3D LocalSections.find(Section);
+  if (i !=3D LocalSections.end())
+    SectionID =3D i->second;
+  else {
+    SectionID =3D emitSection(Section, IsCode);
+    LocalSections[Section] =3D SectionID;
+  }
+  return SectionID;
+}
+
+void RuntimeDyldImpl::AddRelocation(const RelocationValueRef &Value,
+                                   unsigned SectionID, uintptr_t Offset,
+                                   uint32_t RelType) {
+  DEBUG(dbgs() << "AddRelocation SymNamePtr: " << format("%p", Value.Symbo=
lName)
+               << " SID: " << Value.SectionID
+               << " Addend: " << format("%p", Value.Addend)
+               << " Offset: " << format("%p", Offset)
+               << " RelType: " << format("%x", RelType)
+               << "\n");
+
+  if (Value.SymbolName =3D=3D 0) {
+    Relocations[Value.SectionID].push_back(RelocationEntry(
+      SectionID,
+      Offset,
+      RelType,
+      Value.Addend));
+  } else
+    SymbolRelocations[Value.SymbolName].push_back(RelocationEntry(
+      SectionID,
+      Offset,
+      RelType,
+      Value.Addend));
+}
+
+uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr) {
+  // TODO: There is only ARM far stub now. We should add the Thumb stub,
+  // and stubs for branches Thumb - ARM and ARM - Thumb.
+  if (Arch =3D=3D Triple::arm) {
+    uint32_t *StubAddr =3D (uint32_t*)Addr;
+    *StubAddr =3D 0xe51ff004; // ldr pc,<label>
+    return (uint8_t*)++StubAddr;
+  }
+  else
+    return Addr;
+}
+
+// Assign an address to a symbol name and resolve all the relocations
+// associated with it.
+void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
+                                             uint64_t Addr) {
+  // The address to use for relocation resolution is not
+  // the address of the local section buffer. We must be doing
+  // a remote execution environment of some sort. Re-apply any
+  // relocations referencing this section with the given address.
+  //
+  // Addr is a uint64_t because we can't assume the pointer width
+  // of the target is the same as that of the host. Just use a generic
+  // "big enough" type.
+  Sections[SectionID].LoadAddress =3D Addr;
+  DEBUG(dbgs() << "Resolving relocations Section #" << SectionID
+          << "\t" << format("%p", (uint8_t *)Addr)
+          << "\n");
+  resolveRelocationList(Relocations[SectionID], Addr);
+}
+
+void RuntimeDyldImpl::resolveRelocationEntry(const RelocationEntry &RE,
+                                             uint64_t Value) {
+    // Ignore relocations for sections that were not loaded
+    if (Sections[RE.SectionID].Address !=3D 0) {
+      uint8_t *Target =3D Sections[RE.SectionID].Address + RE.Offset;
+      DEBUG(dbgs() << "\tSectionID: " << RE.SectionID
+            << " + " << RE.Offset << " (" << format("%p", Target) << ")"
+            << " Data: " << RE.Data
+            << " Addend: " << RE.Addend
+            << "\n");
+
+      resolveRelocation(Target, Sections[RE.SectionID].LoadAddress + RE.Of=
fset,
+                        Value, RE.Data, RE.Addend);
+  }
+}
+
+void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
+                                            uint64_t Value) {
+  for (unsigned i =3D 0, e =3D Relocs.size(); i !=3D e; ++i) {
+    resolveRelocationEntry(Relocs[i], Value);
+  }
+}
+
+// resolveSymbols - Resolve any relocations to the specified symbols if
+// we know where it lives.
+void RuntimeDyldImpl::resolveSymbols() {
+  StringMap<RelocationList>::iterator i =3D SymbolRelocations.begin(),
+                                      e =3D SymbolRelocations.end();
+  for (; i !=3D e; i++) {
+    StringRef Name =3D i->first();
+    RelocationList &Relocs =3D i->second;
+    StringMap<SymbolLoc>::const_iterator Loc =3D SymbolTable.find(Name);
+    if (Loc =3D=3D SymbolTable.end()) {
+      // This is an external symbol, try to get it address from
+      // MemoryManager.
+      uint8_t *Addr =3D (uint8_t*) MemMgr->getPointerToNamedFunction(Name.=
data(),
+                                                                   true);
+      DEBUG(dbgs() << "Resolving relocations Name: " << Name
+              << "\t" << format("%p", Addr)
+              << "\n");
+      resolveRelocationList(Relocs, (uintptr_t)Addr);
+    } else {
+      // Change the relocation to be section relative rather than symbol
+      // relative and move it to the resolved relocation list.
+      DEBUG(dbgs() << "Resolving symbol '" << Name << "'\n");
+      for (int i =3D 0, e =3D Relocs.size(); i !=3D e; ++i) {
+        RelocationEntry Entry =3D Relocs[i];
+        Entry.Addend +=3D Loc->second.second;
+        Relocations[Loc->second.first].push_back(Entry);
+      }
+      Relocs.clear();
+    }
+  }
+}
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // RuntimeDyld class implementation
 RuntimeDyld::RuntimeDyld(RTDyldMemoryManager *mm) {
@@ -64,12 +416,36 @@
=20
 bool RuntimeDyld::loadObject(MemoryBuffer *InputBuffer) {
   if (!Dyld) {
-    if (RuntimeDyldMachO::isKnownFormat(InputBuffer))
-      Dyld =3D new RuntimeDyldMachO(MM);
-    else
-      report_fatal_error("Unknown object format!");
+    sys::LLVMFileType type =3D sys::IdentifyFileType(
+            InputBuffer->getBufferStart(),
+            static_cast<unsigned>(InputBuffer->getBufferSize()));
+    switch (type) {
+      case sys::ELF_Relocatable_FileType:
+      case sys::ELF_Executable_FileType:
+      case sys::ELF_SharedObject_FileType:
+      case sys::ELF_Core_FileType:
+        Dyld =3D new RuntimeDyldELF(MM);
+        break;
+      case sys::Mach_O_Object_FileType:
+      case sys::Mach_O_Executable_FileType:
+      case sys::Mach_O_FixedVirtualMemorySharedLib_FileType:
+      case sys::Mach_O_Core_FileType:
+      case sys::Mach_O_PreloadExecutable_FileType:
+      case sys::Mach_O_DynamicallyLinkedSharedLib_FileType:
+      case sys::Mach_O_DynamicLinker_FileType:
+      case sys::Mach_O_Bundle_FileType:
+      case sys::Mach_O_DynamicallyLinkedSharedLibStub_FileType:
+      case sys::Mach_O_DSYMCompanion_FileType:
+        Dyld =3D new RuntimeDyldMachO(MM);
+        break;
+      case sys::Unknown_FileType:
+      case sys::Bitcode_FileType:
+      case sys::Archive_FileType:
+      case sys::COFF_FileType:
+        report_fatal_error("Incompatible object format!");
+    }
   } else {
-    if(!Dyld->isCompatibleFormat(InputBuffer))
+    if (!Dyld->isCompatibleFormat(InputBuffer))
       report_fatal_error("Incompatible object format!");
   }
=20
@@ -84,8 +460,14 @@
   Dyld->resolveRelocations();
 }
=20
-void RuntimeDyld::reassignSymbolAddress(StringRef Name, uint8_t *Addr) {
-  Dyld->reassignSymbolAddress(Name, Addr);
+void RuntimeDyld::reassignSectionAddress(unsigned SectionID,
+                                         uint64_t Addr) {
+  Dyld->reassignSectionAddress(SectionID, Addr);
+}
+
+void RuntimeDyld::mapSectionAddress(void *LocalAddress,
+                                    uint64_t TargetAddress) {
+  Dyld->mapSectionAddress(LocalAddress, TargetAddress);
 }
=20
 StringRef RuntimeDyld::getErrorString() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
RuntimeDyld/RuntimeDyldImpl.h
--- a/head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldImpl.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- RuntimeDyldImpl.h - Run-time dynamic linker for MC-JIT -----=
-*- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- RuntimeDyldImpl.h - Run-time dynamic linker for MC-JIT --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,42 +15,128 @@
 #define LLVM_RUNTIME_DYLD_IMPL_H
=20
 #include "llvm/ExecutionEngine/RuntimeDyld.h"
-#include "llvm/Object/MachOObject.h"
+#include "llvm/Object/ObjectFile.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ExecutionEngine/ExecutionEngine.h"
-#include "llvm/Support/Format.h"
 #include "llvm/Support/Memory.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/system_error.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/ADT/Triple.h"
+#include <map>
+#include "llvm/Support/Format.h"
=20
 using namespace llvm;
 using namespace llvm::object;
=20
 namespace llvm {
+
+class SectionEntry {
+public:
+  uint8_t* Address;
+  size_t Size;
+  uint64_t LoadAddress;   // For each section, the address it will be
+                          // considered to live at for relocations. The sa=
me
+                          // as the pointer to the above memory block for
+                          // hosted JITs.
+  uintptr_t StubOffset;   // It's used for architecturies with stub
+                          // functions for far relocations like ARM.
+  uintptr_t ObjAddress;   // Section address in object file. It's use for
+                          // calculate MachO relocation addend
+  SectionEntry(uint8_t* address, size_t size, uintptr_t stubOffset,
+               uintptr_t objAddress)
+    : Address(address), Size(size), LoadAddress((uintptr_t)address),
+      StubOffset(stubOffset), ObjAddress(objAddress) {}
+};
+
+class RelocationEntry {
+public:
+  unsigned    SectionID;  // Section the relocation is contained in.
+  uintptr_t   Offset;     // Offset into the section for the relocation.
+  uint32_t    Data;       // Relocatino data. Including type of relocation
+                          // and another flags and parameners from
+  intptr_t    Addend;     // Addend encoded in the instruction itself, if =
any,
+                          // plus the offset into the source section for
+                          // the symbol once the relocation is resolvable.
+  RelocationEntry(unsigned id, uint64_t offset, uint32_t data, int64_t add=
end)
+    : SectionID(id), Offset(offset), Data(data), Addend(addend) {}
+};
+
+// Raw relocation data from object file
+class ObjRelocationInfo {
+public:
+  unsigned  SectionID;
+  uint64_t  Offset;
+  SymbolRef Symbol;
+  uint64_t  Type;
+  int64_t   AdditionalInfo;
+};
+
+class RelocationValueRef {
+public:
+  unsigned  SectionID;
+  intptr_t  Addend;
+  const char *SymbolName;
+  RelocationValueRef(): SectionID(0), Addend(0), SymbolName(0) {}
+
+  inline bool operator=3D=3D(const RelocationValueRef &Other) const {
+    return std::memcmp(this, &Other, sizeof(RelocationValueRef)) =3D=3D 0;
+  }
+  inline bool operator <(const RelocationValueRef &Other) const {
+    return std::memcmp(this, &Other, sizeof(RelocationValueRef)) < 0;
+  }
+};
+
 class RuntimeDyldImpl {
 protected:
-  unsigned CPUType;
-  unsigned CPUSubtype;
-
   // The MemoryManager to load objects into.
   RTDyldMemoryManager *MemMgr;
=20
-  // FIXME: This all assumes we're dealing with external symbols for anyth=
ing
-  //        explicitly referenced. I.e., we can index by name and things
-  //        will work out. In practice, this may not be the case, so we
-  //        should find a way to effectively generalize.
+  // A list of emmitted sections.
+  typedef SmallVector<SectionEntry, 64> SectionList;
+  SectionList Sections;
=20
-  // For each function, we have a MemoryBlock of it's instruction data.
-  StringMap<sys::MemoryBlock> Functions;
+  // Keep a map of sections from object file to the SectionID which
+  // references it.
+  typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
=20
   // Master symbol table. As modules are loaded and external symbols are
-  // resolved, their addresses are stored here.
-  StringMap<uint8_t*> SymbolTable;
+  // resolved, their addresses are stored here as a SectionID/Offset pair.
+  typedef std::pair<unsigned, uintptr_t> SymbolLoc;
+  StringMap<SymbolLoc> SymbolTable;
+  typedef DenseMap<const char*, SymbolLoc> LocalSymbolMap;
+
+  // Keep a map of common symbols to their sizes
+  typedef std::map<SymbolRef, unsigned> CommonSymbolMap;
+
+  // For each symbol, keep a list of relocations based on it. Anytime
+  // its address is reassigned (the JIT re-compiled the function, e.g.),
+  // the relocations get re-resolved.
+  // The symbol (or section) the relocation is sourced from is the Key
+  // in the relocation list where it's stored.
+  typedef SmallVector<RelocationEntry, 64> RelocationList;
+  // Relocations to sections already loaded. Indexed by SectionID which is=
 the
+  // source of the address. The target where the address will be writen is
+  // SectionID/Offset in the relocation itself.
+  DenseMap<unsigned, RelocationList> Relocations;
+  // Relocations to external symbols that are not yet resolved.
+  // Indexed by symbol name.
+  StringMap<RelocationList> SymbolRelocations;
+
+  typedef std::map<RelocationValueRef, uintptr_t> StubMap;
+
+  Triple::ArchType Arch;
+
+  inline unsigned getMaxStubSize() {
+    if (Arch =3D=3D Triple::arm || Arch =3D=3D Triple::thumb)
+      return 8; // 32-bit instruction and 32-bit address
+    else
+      return 0;
+  }
=20
   bool HasError;
   std::string ErrorStr;
@@ -62,25 +148,84 @@
     return true;
   }
=20
-  void extractFunction(StringRef Name, uint8_t *StartAddress,
-                       uint8_t *EndAddress);
+  uint8_t *getSectionAddress(unsigned SectionID) {
+    return (uint8_t*)Sections[SectionID].Address;
+  }
=20
+  /// \brief Emits a section containing common symbols.
+  /// \return SectionID.
+  unsigned emitCommonSymbols(const CommonSymbolMap &Map,
+                             uint64_t TotalSize,
+                             LocalSymbolMap &Symbols);
+
+  /// \brief Emits section data from the object file to the MemoryManager.
+  /// \param IsCode if it's true then allocateCodeSection() will be
+  ///        used for emmits, else allocateDataSection() will be used.
+  /// \return SectionID.
+  unsigned emitSection(const SectionRef &Section, bool IsCode);
+
+  /// \brief Find Section in LocalSections. If the secton is not found - e=
mit
+  ///        it and store in LocalSections.
+  /// \param IsCode if it's true then allocateCodeSection() will be
+  ///        used for emmits, else allocateDataSection() will be used.
+  /// \return SectionID.
+  unsigned findOrEmitSection(const SectionRef &Section, bool IsCode,
+                             ObjSectionToIDMap &LocalSections);
+
+  /// \brief If Value.SymbolName is NULL then store relocation to the
+  ///        Relocations, else store it in the SymbolRelocations.
+  void AddRelocation(const RelocationValueRef &Value, unsigned SectionID,
+                     uintptr_t Offset, uint32_t RelType);
+
+  /// \brief Emits long jump instruction to Addr.
+  /// \return Pointer to the memory area for emitting target address.
+  uint8_t* createStubFunction(uint8_t *Addr);
+
+  /// \brief Resolves relocations from Relocs list with address from Value.
+  void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
+  void resolveRelocationEntry(const RelocationEntry &RE, uint64_t Value);
+
+  /// \brief A object file specific relocation resolver
+  /// \param Address Address to apply the relocation action
+  /// \param Value Target symbol address to apply the relocation action
+  /// \param Type object file specific relocation type
+  /// \param Addend A constant addend used to compute the value to be stor=
ed
+  ///        into the relocatable field
+  virtual void resolveRelocation(uint8_t *LocalAddress,
+                                 uint64_t FinalAddress,
+                                 uint64_t Value,
+                                 uint32_t Type,
+                                 int64_t Addend) =3D 0;
+
+  /// \brief Parses the object file relocation and store it to Relocations
+  ///        or SymbolRelocations. Its depend from object file type.
+  virtual void processRelocationRef(const ObjRelocationInfo &Rel,
+                                    const ObjectFile &Obj,
+                                    ObjSectionToIDMap &ObjSectionToID,
+                                    LocalSymbolMap &Symbols, StubMap &Stub=
s) =3D 0;
+
+  void resolveSymbols();
 public:
   RuntimeDyldImpl(RTDyldMemoryManager *mm) : MemMgr(mm), HasError(false) {}
=20
   virtual ~RuntimeDyldImpl();
=20
-  virtual bool loadObject(MemoryBuffer *InputBuffer) =3D 0;
+  bool loadObject(const MemoryBuffer *InputBuffer);
=20
   void *getSymbolAddress(StringRef Name) {
     // FIXME: Just look up as a function for now. Overly simple of course.
     // Work in progress.
-    return SymbolTable.lookup(Name);
+    if (SymbolTable.find(Name) =3D=3D SymbolTable.end())
+      return 0;
+    SymbolLoc Loc =3D SymbolTable.lookup(Name);
+    return getSectionAddress(Loc.first) + Loc.second;
   }
=20
   void resolveRelocations();
=20
-  virtual void reassignSymbolAddress(StringRef Name, uint8_t *Addr) =3D 0;
+  void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
+
+  void mapSectionAddress(void *LocalAddress, uint64_t TargetAddress);
=20
   // Is the linker in an error state?
   bool hasError() { return HasError; }
@@ -92,58 +237,7 @@
   StringRef getErrorString() { return ErrorStr; }
=20
   virtual bool isCompatibleFormat(const MemoryBuffer *InputBuffer) const =
=3D 0;
-};
=20
-
-class RuntimeDyldMachO : public RuntimeDyldImpl {
-
-  // For each symbol, keep a list of relocations based on it. Anytime
-  // its address is reassigned (the JIT re-compiled the function, e.g.),
-  // the relocations get re-resolved.
-  struct RelocationEntry {
-    std::string Target;     // Object this relocation is contained in.
-    uint64_t    Offset;     // Offset into the object for the relocation.
-    uint32_t    Data;       // Second word of the raw macho relocation ent=
ry.
-    int64_t     Addend;     // Addend encoded in the instruction itself, i=
f any.
-    bool        isResolved; // Has this relocation been resolved previousl=
y?
-
-    RelocationEntry(StringRef t, uint64_t offset, uint32_t data, int64_t a=
ddend)
-      : Target(t), Offset(offset), Data(data), Addend(addend),
-        isResolved(false) {}
-  };
-  typedef SmallVector<RelocationEntry, 4> RelocationList;
-  StringMap<RelocationList> Relocations;
-
-  // FIXME: Also keep a map of all the relocations contained in an object.=
 Use
-  // this to dynamically answer whether all of the relocations in it have
-  // been resolved or not.
-
-  bool resolveRelocation(uint8_t *Address, uint8_t *Value, bool isPCRel,
-                         unsigned Type, unsigned Size);
-  bool resolveX86_64Relocation(uintptr_t Address, uintptr_t Value, bool is=
PCRel,
-                               unsigned Type, unsigned Size);
-  bool resolveARMRelocation(uintptr_t Address, uintptr_t Value, bool isPCR=
el,
-                            unsigned Type, unsigned Size);
-
-  bool loadSegment32(const MachOObject *Obj,
-                     const MachOObject::LoadCommandInfo *SegmentLCI,
-                     const InMemoryStruct<macho::SymtabLoadCommand> &Symta=
bLC);
-  bool loadSegment64(const MachOObject *Obj,
-                     const MachOObject::LoadCommandInfo *SegmentLCI,
-                     const InMemoryStruct<macho::SymtabLoadCommand> &Symta=
bLC);
-
-public:
-  RuntimeDyldMachO(RTDyldMemoryManager *mm) : RuntimeDyldImpl(mm) {}
-
-  bool loadObject(MemoryBuffer *InputBuffer);
-
-  void reassignSymbolAddress(StringRef Name, uint8_t *Addr);
-
-  static bool isKnownFormat(const MemoryBuffer *InputBuffer);
-
-  bool isCompatibleFormat(const MemoryBuffer *InputBuffer) const {
-    return isKnownFormat(InputBuffer);
-  }
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
RuntimeDyld/RuntimeDyldMachO.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cp=
p	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.cp=
p	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT --=
----*- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT -*=
- C++ -*-=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,73 +15,147 @@
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/STLExtras.h"
-#include "RuntimeDyldImpl.h"
+#include "RuntimeDyldMachO.h"
 using namespace llvm;
 using namespace llvm::object;
=20
 namespace llvm {
=20
-bool RuntimeDyldMachO::
-resolveRelocation(uint8_t *Address, uint8_t *Value, bool isPCRel,
-                  unsigned Type, unsigned Size) {
+void RuntimeDyldMachO::resolveRelocation(uint8_t *LocalAddress,
+                                         uint64_t FinalAddress,
+                                         uint64_t Value,
+                                         uint32_t Type,
+                                         int64_t Addend) {
+  bool isPCRel =3D (Type >> 24) & 1;
+  unsigned MachoType =3D (Type >> 28) & 0xf;
+  unsigned Size =3D 1 << ((Type >> 25) & 3);
+
+  DEBUG(dbgs() << "resolveRelocation LocalAddress: " << format("%p", Local=
Address)
+        << " FinalAddress: " << format("%p", FinalAddress)
+        << " Value: " << format("%p", Value)
+        << " Addend: " << Addend
+        << " isPCRel: " << isPCRel
+        << " MachoType: " << MachoType
+        << " Size: " << Size
+        << "\n");
+
   // This just dispatches to the proper target specific routine.
-  switch (CPUType) {
-  default: assert(0 && "Unsupported CPU type!");
-  case mach::CTM_x86_64:
-    return resolveX86_64Relocation((uintptr_t)Address, (uintptr_t)Value,
-                                   isPCRel, Type, Size);
-  case mach::CTM_ARM:
-    return resolveARMRelocation((uintptr_t)Address, (uintptr_t)Value,
-                                isPCRel, Type, Size);
+  switch (Arch) {
+  default: llvm_unreachable("Unsupported CPU type!");
+  case Triple::x86_64:
+    resolveX86_64Relocation(LocalAddress,
+                            FinalAddress,
+                            (uintptr_t)Value,
+                            isPCRel,
+                            MachoType,
+                            Size,
+                            Addend);
+    break;
+  case Triple::x86:
+    resolveI386Relocation(LocalAddress,
+                                 FinalAddress,
+                                 (uintptr_t)Value,
+                                 isPCRel,
+                                 Type,
+                                 Size,
+                                 Addend);
+    break;
+  case Triple::arm:    // Fall through.
+  case Triple::thumb:
+    resolveARMRelocation(LocalAddress,
+                         FinalAddress,
+                         (uintptr_t)Value,
+                         isPCRel,
+                         MachoType,
+                         Size,
+                         Addend);
+    break;
   }
-  llvm_unreachable("");
 }
=20
 bool RuntimeDyldMachO::
-resolveX86_64Relocation(uintptr_t Address, uintptr_t Value,
-                        bool isPCRel, unsigned Type,
-                        unsigned Size) {
+resolveI386Relocation(uint8_t *LocalAddress,
+                      uint64_t FinalAddress,
+                      uint64_t Value,
+                      bool isPCRel,
+                      unsigned Type,
+                      unsigned Size,
+                      int64_t Addend) {
+  if (isPCRel)
+    Value -=3D FinalAddress + 4; // see resolveX86_64Relocation
+
+  switch (Type) {
+  default:
+    llvm_unreachable("Invalid relocation type!");
+  case macho::RIT_Vanilla: {
+    uint8_t *p =3D LocalAddress;
+    uint64_t ValueToWrite =3D Value + Addend;
+    for (unsigned i =3D 0; i < Size; ++i) {
+      *p++ =3D (uint8_t)(ValueToWrite & 0xff);
+      ValueToWrite >>=3D 8;
+    }
+  }
+  case macho::RIT_Difference:
+  case macho::RIT_Generic_LocalDifference:
+  case macho::RIT_Generic_PreboundLazyPointer:
+    return Error("Relocation type not implemented yet!");
+  }
+}
+
+bool RuntimeDyldMachO::
+resolveX86_64Relocation(uint8_t *LocalAddress,
+                        uint64_t FinalAddress,
+                        uint64_t Value,
+                        bool isPCRel,
+                        unsigned Type,
+                        unsigned Size,
+                        int64_t Addend) {
   // If the relocation is PC-relative, the value to be encoded is the
   // pointer difference.
   if (isPCRel)
     // FIXME: It seems this value needs to be adjusted by 4 for an effecti=
ve PC
     // address. Is that expected? Only for branches, perhaps?
-    Value -=3D Address + 4;
+    Value -=3D FinalAddress + 4;
=20
   switch(Type) {
   default:
     llvm_unreachable("Invalid relocation type!");
+  case macho::RIT_X86_64_Signed1:
+  case macho::RIT_X86_64_Signed2:
+  case macho::RIT_X86_64_Signed4:
+  case macho::RIT_X86_64_Signed:
   case macho::RIT_X86_64_Unsigned:
   case macho::RIT_X86_64_Branch: {
+    Value +=3D Addend;
     // Mask in the target value a byte at a time (we don't have an alignme=
nt
     // guarantee for the target address, so this is safest).
-    uint8_t *p =3D (uint8_t*)Address;
+    uint8_t *p =3D (uint8_t*)LocalAddress;
     for (unsigned i =3D 0; i < Size; ++i) {
       *p++ =3D (uint8_t)Value;
       Value >>=3D 8;
     }
     return false;
   }
-  case macho::RIT_X86_64_Signed:
   case macho::RIT_X86_64_GOTLoad:
   case macho::RIT_X86_64_GOT:
   case macho::RIT_X86_64_Subtractor:
-  case macho::RIT_X86_64_Signed1:
-  case macho::RIT_X86_64_Signed2:
-  case macho::RIT_X86_64_Signed4:
   case macho::RIT_X86_64_TLV:
     return Error("Relocation type not implemented yet!");
   }
-  return false;
 }
=20
-bool RuntimeDyldMachO::resolveARMRelocation(uintptr_t Address, uintptr_t V=
alue,
-                                         bool isPCRel, unsigned Type,
-                                         unsigned Size) {
+bool RuntimeDyldMachO::
+resolveARMRelocation(uint8_t *LocalAddress,
+                     uint64_t FinalAddress,
+                     uint64_t Value,
+                     bool isPCRel,
+                     unsigned Type,
+                     unsigned Size,
+                     int64_t Addend) {
   // If the relocation is PC-relative, the value to be encoded is the
   // pointer difference.
   if (isPCRel) {
-    Value -=3D Address;
+    Value -=3D FinalAddress;
     // ARM PCRel relocations have an effective-PC offset of two instructio=
ns
     // (four bytes in Thumb mode, 8 bytes in ARM mode).
     // FIXME: For now, assume ARM mode.
@@ -92,10 +166,9 @@
   default:
     llvm_unreachable("Invalid relocation type!");
   case macho::RIT_Vanilla: {
-    llvm_unreachable("Invalid relocation type!");
     // Mask in the target value a byte at a time (we don't have an alignme=
nt
     // guarantee for the target address, so this is safest).
-    uint8_t *p =3D (uint8_t*)Address;
+    uint8_t *p =3D (uint8_t*)LocalAddress;
     for (unsigned i =3D 0; i < Size; ++i) {
       *p++ =3D (uint8_t)Value;
       Value >>=3D 8;
@@ -105,7 +178,7 @@
   case macho::RIT_ARM_Branch24Bit: {
     // Mask the value into the target address. We know instructions are
     // 32-bit aligned, so we can do it all at once.
-    uint32_t *p =3D (uint32_t*)Address;
+    uint32_t *p =3D (uint32_t*)LocalAddress;
     // The low two bits of the value are not encoded.
     Value >>=3D 2;
     // Mask the value to 24 bits.
@@ -131,388 +204,84 @@
   return false;
 }
=20
-bool RuntimeDyldMachO::
-loadSegment32(const MachOObject *Obj,
-              const MachOObject::LoadCommandInfo *SegmentLCI,
-              const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
-  InMemoryStruct<macho::SegmentLoadCommand> SegmentLC;
-  Obj->ReadSegmentLoadCommand(*SegmentLCI, SegmentLC);
-  if (!SegmentLC)
-    return Error("unable to load segment load command");
+void RuntimeDyldMachO::processRelocationRef(const ObjRelocationInfo &Rel,
+                                            const ObjectFile &Obj,
+                                            ObjSectionToIDMap &ObjSectionT=
oID,
+                                            LocalSymbolMap &Symbols,
+                                            StubMap &Stubs) {
=20
-  for (unsigned SectNum =3D 0; SectNum !=3D SegmentLC->NumSections; ++Sect=
Num) {
-    InMemoryStruct<macho::Section> Sect;
-    Obj->ReadSection(*SegmentLCI, SectNum, Sect);
-    if (!Sect)
-      return Error("unable to load section: '" + Twine(SectNum) + "'");
+  uint32_t RelType =3D (uint32_t) (Rel.Type & 0xffffffffL);
+  RelocationValueRef Value;
+  SectionEntry &Section =3D Sections[Rel.SectionID];
+  uint8_t *Target =3D Section.Address + Rel.Offset;
=20
-    // FIXME: For the time being, we're only loading text segments.
-    if (Sect->Flags !=3D 0x80000400)
-      continue;
-
-    // Address and names of symbols in the section.
-    typedef std::pair<uint64_t, StringRef> SymbolEntry;
-    SmallVector<SymbolEntry, 64> Symbols;
-    // Index of all the names, in this section or not. Used when we're
-    // dealing with relocation entries.
-    SmallVector<StringRef, 64> SymbolNames;
-    for (unsigned i =3D 0; i !=3D SymtabLC->NumSymbolTableEntries; ++i) {
-      InMemoryStruct<macho::SymbolTableEntry> STE;
-      Obj->ReadSymbolTableEntry(SymtabLC->SymbolTableOffset, i, STE);
-      if (!STE)
-        return Error("unable to read symbol: '" + Twine(i) + "'");
-      if (STE->SectionIndex > SegmentLC->NumSections)
-        return Error("invalid section index for symbol: '" + Twine(i) + "'=
");
-      // Get the symbol name.
-      StringRef Name =3D Obj->getStringAtIndex(STE->StringIndex);
-      SymbolNames.push_back(Name);
-
-      // Just skip symbols not defined in this section.
-      if ((unsigned)STE->SectionIndex - 1 !=3D SectNum)
-        continue;
-
-      // FIXME: Check the symbol type and flags.
-      if (STE->Type !=3D 0xF)  // external, defined in this section.
-        continue;
-      // Flags =3D=3D 0x8 marks a thumb function for ARM, which is fine as=
 it
-      // doesn't require any special handling here.
-      if (STE->Flags !=3D 0x0 && STE->Flags !=3D 0x8)
-        continue;
-
-      // Remember the symbol.
-      Symbols.push_back(SymbolEntry(STE->Value, Name));
-
-      DEBUG(dbgs() << "Function sym: '" << Name << "' @ " <<
-            (Sect->Address + STE->Value) << "\n");
+  bool isExtern =3D (RelType >> 27) & 1;
+  if (isExtern) {
+    StringRef TargetName;
+    const SymbolRef &Symbol =3D Rel.Symbol;
+    Symbol.getName(TargetName);
+    // First look the symbol in object file symbols.
+    LocalSymbolMap::iterator lsi =3D Symbols.find(TargetName.data());
+    if (lsi !=3D Symbols.end()) {
+      Value.SectionID =3D lsi->second.first;
+      Value.Addend =3D lsi->second.second;
+    } else {
+      // Second look the symbol in global symbol table.
+      StringMap<SymbolLoc>::iterator gsi =3D SymbolTable.find(TargetName.d=
ata());
+      if (gsi !=3D SymbolTable.end()) {
+        Value.SectionID =3D gsi->second.first;
+        Value.Addend =3D gsi->second.second;
+      } else
+        Value.SymbolName =3D TargetName.data();
     }
-    // Sort the symbols by address, just in case they didn't come in that =
way.
-    array_pod_sort(Symbols.begin(), Symbols.end());
-
-    // If there weren't any functions (odd, but just in case...)
-    if (!Symbols.size())
-      continue;
-
-    // Extract the function data.
-    uint8_t *Base =3D (uint8_t*)Obj->getData(SegmentLC->FileOffset,
-                                           SegmentLC->FileSize).data();
-    for (unsigned i =3D 0, e =3D Symbols.size() - 1; i !=3D e; ++i) {
-      uint64_t StartOffset =3D Sect->Address + Symbols[i].first;
-      uint64_t EndOffset =3D Symbols[i + 1].first - 1;
-      DEBUG(dbgs() << "Extracting function: " << Symbols[i].second
-                   << " from [" << StartOffset << ", " << EndOffset << "]\=
n");
-      extractFunction(Symbols[i].second, Base + StartOffset, Base + EndOff=
set);
+  } else {
+    error_code err;
+    uint8_t sectionIndex =3D static_cast<uint8_t>(RelType & 0xFF);
+    section_iterator si =3D Obj.begin_sections(),
+                     se =3D Obj.end_sections();
+    for (uint8_t i =3D 1; i < sectionIndex; i++) {
+      error_code err;
+      si.increment(err);
+      if (si =3D=3D se)
+        break;
     }
-    // The last symbol we do after since the end address is calculated
-    // differently because there is no next symbol to reference.
-    uint64_t StartOffset =3D Symbols[Symbols.size() - 1].first;
-    uint64_t EndOffset =3D Sect->Size - 1;
-    DEBUG(dbgs() << "Extracting function: " << Symbols[Symbols.size()-1].s=
econd
-                 << " from [" << StartOffset << ", " << EndOffset << "]\n"=
);
-    extractFunction(Symbols[Symbols.size()-1].second,
-                    Base + StartOffset, Base + EndOffset);
-
-    // Now extract the relocation information for each function and proces=
s it.
-    for (unsigned j =3D 0; j !=3D Sect->NumRelocationTableEntries; ++j) {
-      InMemoryStruct<macho::RelocationEntry> RE;
-      Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
-      if (RE->Word0 & macho::RF_Scattered)
-        return Error("NOT YET IMPLEMENTED: scattered relocations.");
-      // Word0 of the relocation is the offset into the section where the
-      // relocation should be applied. We need to translate that into an
-      // offset into a function since that's our atom.
-      uint32_t Offset =3D RE->Word0;
-      // Look for the function containing the address. This is used for JIT
-      // code, so the number of functions in section is almost always going
-      // to be very small (usually just one), so until we have use cases
-      // where that's not true, just use a trivial linear search.
-      unsigned SymbolNum;
-      unsigned NumSymbols =3D Symbols.size();
-      assert(NumSymbols > 0 && Symbols[0].first <=3D Offset &&
-             "No symbol containing relocation!");
-      for (SymbolNum =3D 0; SymbolNum < NumSymbols - 1; ++SymbolNum)
-        if (Symbols[SymbolNum + 1].first > Offset)
-          break;
-      // Adjust the offset to be relative to the symbol.
-      Offset -=3D Symbols[SymbolNum].first;
-      // Get the name of the symbol containing the relocation.
-      StringRef TargetName =3D SymbolNames[SymbolNum];
-
-      bool isExtern =3D (RE->Word1 >> 27) & 1;
-      // Figure out the source symbol of the relocation. If isExtern is tr=
ue,
-      // this relocation references the symbol table, otherwise it referen=
ces
-      // a section in the same object, numbered from 1 through NumSections
-      // (SectionBases is [0, NumSections-1]).
-      // FIXME: Some targets (ARM) use internal relocations even for
-      // externally visible symbols, if the definition is in the same
-      // file as the reference. We need to convert those back to by-name
-      // references. We can resolve the address based on the section
-      // offset and see if we have a symbol at that address. If we do,
-      // use that; otherwise, puke.
-      if (!isExtern)
-        return Error("Internal relocations not supported.");
-      uint32_t SourceNum =3D RE->Word1 & 0xffffff; // 24-bit value
-      StringRef SourceName =3D SymbolNames[SourceNum];
-
-      // FIXME: Get the relocation addend from the target address.
-
-      // Now store the relocation information. Associate it with the source
-      // symbol.
-      Relocations[SourceName].push_back(RelocationEntry(TargetName,
-                                                        Offset,
-                                                        RE->Word1,
-                                                        0 /*Addend*/));
-      DEBUG(dbgs() << "Relocation at '" << TargetName << "' + " << Offset
-                   << " from '" << SourceName << "(Word1: "
-                   << format("0x%x", RE->Word1) << ")\n");
-    }
-  }
-  return false;
-}
-
-
-bool RuntimeDyldMachO::
-loadSegment64(const MachOObject *Obj,
-              const MachOObject::LoadCommandInfo *SegmentLCI,
-              const InMemoryStruct<macho::SymtabLoadCommand> &SymtabLC) {
-  InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
-  Obj->ReadSegment64LoadCommand(*SegmentLCI, Segment64LC);
-  if (!Segment64LC)
-    return Error("unable to load segment load command");
-
-  for (unsigned SectNum =3D 0; SectNum !=3D Segment64LC->NumSections; ++Se=
ctNum) {
-    InMemoryStruct<macho::Section64> Sect;
-    Obj->ReadSection64(*SegmentLCI, SectNum, Sect);
-    if (!Sect)
-      return Error("unable to load section: '" + Twine(SectNum) + "'");
-
-    // FIXME: For the time being, we're only loading text segments.
-    if (Sect->Flags !=3D 0x80000400)
-      continue;
-
-    // Address and names of symbols in the section.
-    typedef std::pair<uint64_t, StringRef> SymbolEntry;
-    SmallVector<SymbolEntry, 64> Symbols;
-    // Index of all the names, in this section or not. Used when we're
-    // dealing with relocation entries.
-    SmallVector<StringRef, 64> SymbolNames;
-    for (unsigned i =3D 0; i !=3D SymtabLC->NumSymbolTableEntries; ++i) {
-      InMemoryStruct<macho::Symbol64TableEntry> STE;
-      Obj->ReadSymbol64TableEntry(SymtabLC->SymbolTableOffset, i, STE);
-      if (!STE)
-        return Error("unable to read symbol: '" + Twine(i) + "'");
-      if (STE->SectionIndex > Segment64LC->NumSections)
-        return Error("invalid section index for symbol: '" + Twine(i) + "'=
");
-      // Get the symbol name.
-      StringRef Name =3D Obj->getStringAtIndex(STE->StringIndex);
-      SymbolNames.push_back(Name);
-
-      // Just skip symbols not defined in this section.
-      if ((unsigned)STE->SectionIndex - 1 !=3D SectNum)
-        continue;
-
-      // FIXME: Check the symbol type and flags.
-      if (STE->Type !=3D 0xF)  // external, defined in this section.
-        continue;
-      if (STE->Flags !=3D 0x0)
-        continue;
-
-      // Remember the symbol.
-      Symbols.push_back(SymbolEntry(STE->Value, Name));
-
-      DEBUG(dbgs() << "Function sym: '" << Name << "' @ " <<
-            (Sect->Address + STE->Value) << "\n");
-    }
-    // Sort the symbols by address, just in case they didn't come in that =
way.
-    array_pod_sort(Symbols.begin(), Symbols.end());
-
-    // If there weren't any functions (odd, but just in case...)
-    if (!Symbols.size())
-      continue;
-
-    // Extract the function data.
-    uint8_t *Base =3D (uint8_t*)Obj->getData(Segment64LC->FileOffset,
-                                           Segment64LC->FileSize).data();
-    for (unsigned i =3D 0, e =3D Symbols.size() - 1; i !=3D e; ++i) {
-      uint64_t StartOffset =3D Sect->Address + Symbols[i].first;
-      uint64_t EndOffset =3D Symbols[i + 1].first - 1;
-      DEBUG(dbgs() << "Extracting function: " << Symbols[i].second
-                   << " from [" << StartOffset << ", " << EndOffset << "]\=
n");
-      extractFunction(Symbols[i].second, Base + StartOffset, Base + EndOff=
set);
-    }
-    // The last symbol we do after since the end address is calculated
-    // differently because there is no next symbol to reference.
-    uint64_t StartOffset =3D Symbols[Symbols.size() - 1].first;
-    uint64_t EndOffset =3D Sect->Size - 1;
-    DEBUG(dbgs() << "Extracting function: " << Symbols[Symbols.size()-1].s=
econd
-                 << " from [" << StartOffset << ", " << EndOffset << "]\n"=
);
-    extractFunction(Symbols[Symbols.size()-1].second,
-                    Base + StartOffset, Base + EndOffset);
-
-    // Now extract the relocation information for each function and proces=
s it.
-    for (unsigned j =3D 0; j !=3D Sect->NumRelocationTableEntries; ++j) {
-      InMemoryStruct<macho::RelocationEntry> RE;
-      Obj->ReadRelocationEntry(Sect->RelocationTableOffset, j, RE);
-      if (RE->Word0 & macho::RF_Scattered)
-        return Error("NOT YET IMPLEMENTED: scattered relocations.");
-      // Word0 of the relocation is the offset into the section where the
-      // relocation should be applied. We need to translate that into an
-      // offset into a function since that's our atom.
-      uint32_t Offset =3D RE->Word0;
-      // Look for the function containing the address. This is used for JIT
-      // code, so the number of functions in section is almost always going
-      // to be very small (usually just one), so until we have use cases
-      // where that's not true, just use a trivial linear search.
-      unsigned SymbolNum;
-      unsigned NumSymbols =3D Symbols.size();
-      assert(NumSymbols > 0 && Symbols[0].first <=3D Offset &&
-             "No symbol containing relocation!");
-      for (SymbolNum =3D 0; SymbolNum < NumSymbols - 1; ++SymbolNum)
-        if (Symbols[SymbolNum + 1].first > Offset)
-          break;
-      // Adjust the offset to be relative to the symbol.
-      Offset -=3D Symbols[SymbolNum].first;
-      // Get the name of the symbol containing the relocation.
-      StringRef TargetName =3D SymbolNames[SymbolNum];
-
-      bool isExtern =3D (RE->Word1 >> 27) & 1;
-      // Figure out the source symbol of the relocation. If isExtern is tr=
ue,
-      // this relocation references the symbol table, otherwise it referen=
ces
-      // a section in the same object, numbered from 1 through NumSections
-      // (SectionBases is [0, NumSections-1]).
-      if (!isExtern)
-        return Error("Internal relocations not supported.");
-      uint32_t SourceNum =3D RE->Word1 & 0xffffff; // 24-bit value
-      StringRef SourceName =3D SymbolNames[SourceNum];
-
-      // FIXME: Get the relocation addend from the target address.
-
-      // Now store the relocation information. Associate it with the source
-      // symbol.
-      Relocations[SourceName].push_back(RelocationEntry(TargetName,
-                                                        Offset,
-                                                        RE->Word1,
-                                                        0 /*Addend*/));
-      DEBUG(dbgs() << "Relocation at '" << TargetName << "' + " << Offset
-                   << " from '" << SourceName << "(Word1: "
-                   << format("0x%x", RE->Word1) << ")\n");
-    }
-  }
-  return false;
-}
-
-bool RuntimeDyldMachO::loadObject(MemoryBuffer *InputBuffer) {
-  // If the linker is in an error state, don't do anything.
-  if (hasError())
-    return true;
-  // Load the Mach-O wrapper object.
-  std::string ErrorStr;
-  OwningPtr<MachOObject> Obj(
-    MachOObject::LoadFromBuffer(InputBuffer, &ErrorStr));
-  if (!Obj)
-    return Error("unable to load object: '" + ErrorStr + "'");
-
-  // Get the CPU type information from the header.
-  const macho::Header &Header =3D Obj->getHeader();
-
-  // FIXME: Error checking that the loaded object is compatible with
-  //        the system we're running on.
-  CPUType =3D Header.CPUType;
-  CPUSubtype =3D Header.CPUSubtype;
-
-  // Validate that the load commands match what we expect.
-  const MachOObject::LoadCommandInfo *SegmentLCI =3D 0, *SymtabLCI =3D 0,
-    *DysymtabLCI =3D 0;
-  for (unsigned i =3D 0; i !=3D Header.NumLoadCommands; ++i) {
-    const MachOObject::LoadCommandInfo &LCI =3D Obj->getLoadCommandInfo(i);
-    switch (LCI.Command.Type) {
-    case macho::LCT_Segment:
-    case macho::LCT_Segment64:
-      if (SegmentLCI)
-        return Error("unexpected input object (multiple segments)");
-      SegmentLCI =3D &LCI;
-      break;
-    case macho::LCT_Symtab:
-      if (SymtabLCI)
-        return Error("unexpected input object (multiple symbol tables)");
-      SymtabLCI =3D &LCI;
-      break;
-    case macho::LCT_Dysymtab:
-      if (DysymtabLCI)
-        return Error("unexpected input object (multiple symbol tables)");
-      DysymtabLCI =3D &LCI;
-      break;
-    default:
-      return Error("unexpected input object (unexpected load command");
+    assert(si !=3D se && "No section containing relocation!");
+    Value.SectionID =3D findOrEmitSection(*si, true, ObjSectionToID);
+    Value.Addend =3D *(const intptr_t *)Target;
+    if (Value.Addend) {
+      // The MachO addend is offset from the current section, we need set =
it
+      // as offset from destination section
+      Value.Addend +=3D Section.ObjAddress - Sections[Value.SectionID].Obj=
Address;
     }
   }
=20
-  if (!SymtabLCI)
-    return Error("no symbol table found in object");
-  if (!SegmentLCI)
-    return Error("no symbol table found in object");
+  if (Arch =3D=3D Triple::arm && RelType =3D=3D macho::RIT_ARM_Branch24Bit=
) {
+    // This is an ARM branch relocation, need to use a stub function.
=20
-  // Read and register the symbol table data.
-  InMemoryStruct<macho::SymtabLoadCommand> SymtabLC;
-  Obj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
-  if (!SymtabLC)
-    return Error("unable to load symbol table load command");
-  Obj->RegisterStringTable(*SymtabLC);
-
-  // Read the dynamic link-edit information, if present (not present in st=
atic
-  // objects).
-  if (DysymtabLCI) {
-    InMemoryStruct<macho::DysymtabLoadCommand> DysymtabLC;
-    Obj->ReadDysymtabLoadCommand(*DysymtabLCI, DysymtabLC);
-    if (!DysymtabLC)
-      return Error("unable to load dynamic link-exit load command");
-
-    // FIXME: We don't support anything interesting yet.
-//    if (DysymtabLC->LocalSymbolsIndex !=3D 0)
-//      return Error("NOT YET IMPLEMENTED: local symbol entries");
-//    if (DysymtabLC->ExternalSymbolsIndex !=3D 0)
-//      return Error("NOT YET IMPLEMENTED: non-external symbol entries");
-//    if (DysymtabLC->UndefinedSymbolsIndex !=3D SymtabLC->NumSymbolTableE=
ntries)
-//      return Error("NOT YET IMPLEMENTED: undefined symbol entries");
-  }
-
-  // Load the segment load command.
-  if (SegmentLCI->Command.Type =3D=3D macho::LCT_Segment) {
-    if (loadSegment32(Obj.get(), SegmentLCI, SymtabLC))
-      return true;
-  } else {
-    if (loadSegment64(Obj.get(), SegmentLCI, SymtabLC))
-      return true;
-  }
-
-  return false;
+    //  Look up for existing stub.
+    StubMap::const_iterator i =3D Stubs.find(Value);
+    if (i !=3D Stubs.end())
+      resolveRelocation(Target, (uint64_t)Target,
+                        (uint64_t)Section.Address + i->second,
+                        RelType, 0);
+    else {
+      // Create a new stub function.
+      Stubs[Value] =3D Section.StubOffset;
+      uint8_t *StubTargetAddr =3D createStubFunction(Section.Address +
+                                                   Section.StubOffset);
+      AddRelocation(Value, Rel.SectionID, StubTargetAddr - Section.Address,
+                    macho::RIT_Vanilla);
+      resolveRelocation(Target, (uint64_t)Target,
+                        (uint64_t)Section.Address + Section.StubOffset,
+                        RelType, 0);
+      Section.StubOffset +=3D getMaxStubSize();
+    }
+  } else
+    AddRelocation(Value, Rel.SectionID, Rel.Offset, RelType);
 }
=20
-// Assign an address to a symbol name and resolve all the relocations
-// associated with it.
-void RuntimeDyldMachO::reassignSymbolAddress(StringRef Name, uint8_t *Addr=
) {
-  // Assign the address in our symbol table.
-  SymbolTable[Name] =3D Addr;
=20
-  RelocationList &Relocs =3D Relocations[Name];
-  for (unsigned i =3D 0, e =3D Relocs.size(); i !=3D e; ++i) {
-    RelocationEntry &RE =3D Relocs[i];
-    uint8_t *Target =3D SymbolTable[RE.Target] + RE.Offset;
-    bool isPCRel =3D (RE.Data >> 24) & 1;
-    unsigned Type =3D (RE.Data >> 28) & 0xf;
-    unsigned Size =3D 1 << ((RE.Data >> 25) & 3);
-
-    DEBUG(dbgs() << "Resolving relocation at '" << RE.Target
-          << "' + " << RE.Offset << " (" << format("%p", Target) << ")"
-          << " from '" << Name << " (" << format("%p", Addr) << ")"
-          << "(" << (isPCRel ? "pcrel" : "absolute")
-          << ", type: " << Type << ", Size: " << Size << ").\n");
-
-    resolveRelocation(Target, Addr, isPCRel, Type, Size);
-    RE.isResolved =3D true;
-  }
-}
-
-bool RuntimeDyldMachO::isKnownFormat(const MemoryBuffer *InputBuffer) {
+bool RuntimeDyldMachO::isCompatibleFormat(const MemoryBuffer *InputBuffer)=
 const {
   StringRef Magic =3D InputBuffer->getBuffer().slice(0, 4);
   if (Magic =3D=3D "\xFE\xED\xFA\xCE") return true;
   if (Magic =3D=3D "\xCE\xFA\xED\xFE") return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/ExecutionEngine/=
TargetSelect.cpp
--- a/head/contrib/llvm/lib/ExecutionEngine/TargetSelect.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/ExecutionEngine/TargetSelect.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -7,9 +7,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-// This just asks the TargetRegistry for the appropriate JIT to use, and a=
llows
-// the user to specify a specific one on the commandline with -march=3Dx. =
Clients
-// should initialize targets prior to calling createJIT.
+// This just asks the TargetRegistry for the appropriate target to use, and
+// allows the user to specify a specific one on the commandline with -marc=
h=3Dx,
+// -mcpu=3Dy, and -mattr=3Da,-b,+c. Clients should initialize targets prio=
r to
+// calling selectTarget().
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -21,21 +22,27 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Host.h"
 #include "llvm/Support/TargetRegistry.h"
-#include "llvm/Support/raw_ostream.h"
+
 using namespace llvm;
=20
+TargetMachine *EngineBuilder::selectTarget() {
+  StringRef MArch =3D "";
+  StringRef MCPU =3D "";
+  SmallVector<std::string, 1> MAttrs;
+  Triple TT(M->getTargetTriple());
+
+  return selectTarget(TT, MArch, MCPU, MAttrs);
+}
+
 /// selectTarget - Pick a target either via -march or by guessing the nati=
ve
 /// arch.  Add any CPU features specified via -mcpu or -mattr.
-TargetMachine *EngineBuilder::selectTarget(Module *Mod,
+TargetMachine *EngineBuilder::selectTarget(const Triple &TargetTriple,
                               StringRef MArch,
                               StringRef MCPU,
-                              const SmallVectorImpl<std::string>& MAttrs,
-                              Reloc::Model RM,
-                              CodeModel::Model CM,
-                              std::string *ErrorStr) {
-  Triple TheTriple(Mod->getTargetTriple());
+                              const SmallVectorImpl<std::string>& MAttrs) {
+  Triple TheTriple(TargetTriple);
   if (TheTriple.getTriple().empty())
-    TheTriple.setTriple(sys::getHostTriple());
+    TheTriple.setTriple(sys::getDefaultTargetTriple());
=20
   // Adjust the triple to match what the user requested.
   const Target *TheTarget =3D 0;
@@ -55,7 +62,7 @@
     }
=20
     // Adjust the triple to match (if known), otherwise stick with the
-    // module/host triple.
+    // requested/host triple.
     Triple::ArchType Type =3D Triple::getArchTypeForLLVMName(MArch);
     if (Type !=3D Triple::UnknownArch)
       TheTriple.setArch(Type);
@@ -69,12 +76,6 @@
     }
   }
=20
-  if (!TheTarget->hasJIT()) {
-    errs() << "WARNING: This target JIT is not designed for the host you a=
re"
-           << " running.  If bad things happen, please choose a different "
-           << "-march switch.\n";
-  }
-
   // Package up features to be passed to target/subtarget
   std::string FeaturesStr;
   if (!MAttrs.empty()) {
@@ -87,7 +88,9 @@
   // Allocate a target...
   TargetMachine *Target =3D TheTarget->createTargetMachine(TheTriple.getTr=
iple(),
                                                          MCPU, FeaturesStr,
-                                                         RM, CM);
+                                                         Options,
+                                                         RelocModel, CMMod=
el,
+                                                         OptLevel);
   assert(Target && "Could not allocate target machine!");
   return Target;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Linker/LinkArchi=
ves.cpp
--- a/head/contrib/llvm/lib/Linker/LinkArchives.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Linker/LinkArchives.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -16,7 +16,6 @@
 #include "llvm/Module.h"
 #include "llvm/ADT/SetOperations.h"
 #include "llvm/Bitcode/Archive.h"
-#include "llvm/Config/config.h"
 #include <memory>
 #include <set>
 using namespace llvm;
@@ -141,7 +140,7 @@
     // Find the modules we need to link into the target module.  Note that=
 arch
     // keeps ownership of these modules and may return the same Module* fr=
om a
     // subsequent call.
-    std::set<Module*> Modules;
+    SmallVector<Module*, 16> Modules;
     if (!arch->findModulesDefiningSymbols(UndefinedSymbols, Modules, &ErrM=
sg))
       return error("Cannot find symbols in '" + Filename.str() +=20
                    "': " + ErrMsg);
@@ -158,7 +157,7 @@
         UndefinedSymbols.end());
=20
     // Loop over all the Modules that we got back from the archive
-    for (std::set<Module*>::iterator I=3DModules.begin(), E=3DModules.end(=
);
+    for (SmallVectorImpl<Module*>::iterator I=3DModules.begin(), E=3DModul=
es.end();
          I !=3D E; ++I) {
=20
       // Get the module we must link in.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Linker/LinkModul=
es.cpp
--- a/head/contrib/llvm/lib/Linker/LinkModules.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/Linker/LinkModules.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -16,11 +16,16 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/Instructions.h"
 #include "llvm/Module.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/Path.h"
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Transforms/Utils/ValueMapper.h"
+#include <cctype>
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -38,11 +43,16 @@
   /// case we need to roll back.
   SmallVector<Type*, 16> SpeculativeTypes;
  =20
-  /// DefinitionsToResolve - This is a list of non-opaque structs in the s=
ource
-  /// module that are mapped to an opaque struct in the destination module.
-  SmallVector<StructType*, 16> DefinitionsToResolve;
+  /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
+  /// source module that are mapped to an opaque struct in the destination
+  /// module.
+  SmallVector<StructType*, 16> SrcDefinitionsToResolve;
+ =20
+  /// DstResolvedOpaqueTypes - This is the set of opaque types in the
+  /// destination modules who are getting a body from the source module.
+  SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
+
 public:
- =20
   /// addTypeMapping - Indicate that the specified type in the destination
   /// module is conceptually equivalent to the specified type in the source
   /// module.
@@ -58,6 +68,18 @@
=20
   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*=
)T));}
=20
+  /// dump - Dump out the type map for debugging purposes.
+  void dump() const {
+    for (DenseMap<Type*, Type*>::const_iterator
+           I =3D MappedTypes.begin(), E =3D MappedTypes.end(); I !=3D E; +=
+I) {
+      dbgs() << "TypeMap: ";
+      I->first->dump();
+      dbgs() << " =3D> ";
+      I->second->dump();
+      dbgs() << '\n';
+    }
+  }
+
 private:
   Type *getImpl(Type *T);
   /// remapType - Implement the ValueMapTypeRemapper interface.
@@ -118,11 +140,17 @@
       return true;
     }
=20
-    // Mapping a non-opaque source type to an opaque dest.  Keep the dest,=
 but
-    // fill it in later.  This doesn't need to be speculative.
+    // Mapping a non-opaque source type to an opaque dest.  If this is the=
 first
+    // type that we're mapping onto this destination type then we succeed.=
  Keep
+    // the dest, but fill it in later.  This doesn't need to be speculativ=
e.  If
+    // this is the second (different) type that we're trying to map onto t=
he
+    // same opaque type then we fail.
     if (cast<StructType>(DstTy)->isOpaque()) {
+      // We can only map one source type onto the opaque destination type.
+      if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
+        return false;
+      SrcDefinitionsToResolve.push_back(SSTy);
       Entry =3D DstTy;
-      DefinitionsToResolve.push_back(SSTy);
       return true;
     }
   }
@@ -137,6 +165,7 @@
   if (PointerType *PT =3D dyn_cast<PointerType>(DstTy)) {
     if (PT->getAddressSpace() !=3D cast<PointerType>(SrcTy)->getAddressSpa=
ce())
       return false;
+   =20
   } else if (FunctionType *FT =3D dyn_cast<FunctionType>(DstTy)) {
     if (FT->isVarArg() !=3D cast<FunctionType>(SrcTy)->isVarArg())
       return false;
@@ -174,9 +203,9 @@
   SmallString<16> TmpName;
  =20
   // Note that processing entries in this loop (calling 'get') can add new
-  // entries to the DefinitionsToResolve vector.
-  while (!DefinitionsToResolve.empty()) {
-    StructType *SrcSTy =3D DefinitionsToResolve.pop_back_val();
+  // entries to the SrcDefinitionsToResolve vector.
+  while (!SrcDefinitionsToResolve.empty()) {
+    StructType *SrcSTy =3D SrcDefinitionsToResolve.pop_back_val();
     StructType *DstSTy =3D cast<StructType>(MappedTypes[SrcSTy]);
    =20
     // TypeMap is a many-to-one mapping, if there were multiple types that
@@ -204,16 +233,17 @@
       TmpName.clear();
     }
   }
+ =20
+  DstResolvedOpaqueTypes.clear();
 }
=20
-
 /// get - Return the mapped type to use for the specified input type from =
the
 /// source module.
 Type *TypeMapTy::get(Type *Ty) {
   Type *Result =3D getImpl(Ty);
  =20
   // If this caused a reference to any struct type, resolve it before retu=
rning.
-  if (!DefinitionsToResolve.empty())
+  if (!SrcDefinitionsToResolve.empty())
     linkDefinedTypeBodies();
   return Result;
 }
@@ -252,7 +282,7 @@
    =20
     // Otherwise, rebuild a modified type.
     switch (Ty->getTypeID()) {
-    default: assert(0 && "unknown derived type to remap");
+    default: llvm_unreachable("unknown derived type to remap");
     case Type::ArrayTyID:
       return *Entry =3D ArrayType::get(ElementTypes[0],
                                      cast<ArrayType>(Ty)->getNumElements()=
);
@@ -304,12 +334,12 @@
  =20
   // Otherwise we create a new type and resolve its body later.  This will=
 be
   // resolved by the top level of get().
-  DefinitionsToResolve.push_back(STy);
-  return *Entry =3D StructType::create(STy->getContext());
+  SrcDefinitionsToResolve.push_back(STy);
+  StructType *DTy =3D StructType::create(STy->getContext());
+  DstResolvedOpaqueTypes.insert(DTy);
+  return *Entry =3D DTy;
 }
=20
-
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ModuleLinker implementation.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -341,6 +371,9 @@
     // Set of items not to link in from source.
     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
    =20
+    // Vector of functions to lazily link in.
+    std::vector<Function*> LazilyLinkFunctions;
+   =20
   public:
     std::string ErrorMsg;
    =20
@@ -360,7 +393,9 @@
     /// getLinkageResult - This analyzes the two global values and determi=
nes
     /// what the result will look like in the destination module.
     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
-                          GlobalValue::LinkageTypes &LT, bool &LinkFromSrc=
);
+                          GlobalValue::LinkageTypes &LT,
+                          GlobalValue::VisibilityTypes &Vis,
+                          bool &LinkFromSrc);
=20
     /// getLinkedToGlobal - Given a global in the source module, return the
     /// global in the destination module that is being linked to, if any.
@@ -384,11 +419,19 @@
     }
    =20
     void computeTypeMapping();
+    bool categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
+                                   DenseMap<MDString*, MDNode*> &ErrorNode,
+                                   DenseMap<MDString*, MDNode*> &WarningNo=
de,
+                                   DenseMap<MDString*, MDNode*> &OverrideN=
ode,
+                                   DenseMap<MDString*,
+                                   SmallSetVector<MDNode*, 8> > &RequireNo=
des,
+                                   SmallSetVector<MDString*, 16> &SeenIDs);
    =20
     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcG=
V);
     bool linkGlobalProto(GlobalVariable *SrcGV);
     bool linkFunctionProto(Function *SrcF);
     bool linkAliasProto(GlobalAlias *SrcA);
+    bool linkModuleFlagsMetadata();
    =20
     void linkAppendingVarInit(const AppendingVarInfo &AVI);
     void linkGlobalInits();
@@ -398,8 +441,6 @@
   };
 }
=20
-
-
 /// forceRenaming - The LLVM SymbolTable class autorenames globals that co=
nflict
 /// in the symbol table.  This is good for all clients except for us.  Go
 /// through the trouble to force this back.
@@ -421,9 +462,9 @@
   }
 }
=20
-/// CopyGVAttributes - copy additional attributes (those not needed to con=
struct
+/// copyGVAttributes - copy additional attributes (those not needed to con=
struct
 /// a GlobalValue) from the SrcGV to the DestGV.
-static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV=
) {
+static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV=
) {
   // Use the maximum alignment, rather than just copying the alignment of =
SrcGV.
   unsigned Alignment =3D std::max(DestGV->getAlignment(), SrcGV->getAlignm=
ent());
   DestGV->copyAttributesFrom(SrcGV);
@@ -432,21 +473,33 @@
   forceRenaming(DestGV, SrcGV->getName());
 }
=20
+static bool isLessConstraining(GlobalValue::VisibilityTypes a,
+                               GlobalValue::VisibilityTypes b) {
+  if (a =3D=3D GlobalValue::HiddenVisibility)
+    return false;
+  if (b =3D=3D GlobalValue::HiddenVisibility)
+    return true;
+  if (a =3D=3D GlobalValue::ProtectedVisibility)
+    return false;
+  if (b =3D=3D GlobalValue::ProtectedVisibility)
+    return true;
+  return false;
+}
+
 /// getLinkageResult - This analyzes the two global values and determines =
what
 /// the result will look like in the destination module.  In particular, it
-/// computes the resultant linkage type, computes whether the global in the
-/// source should be copied over to the destination (replacing the existing
-/// one), and computes whether this linkage is an error or not. It also pe=
rforms
-/// visibility checks: we cannot link together two symbols with different
-/// visibilities.
+/// computes the resultant linkage type and visibility, computes whether t=
he
+/// global in the source should be copied over to the destination (replaci=
ng
+/// the existing one), and computes whether this linkage is an error or no=
t.
 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *=
Src,
-                                    GlobalValue::LinkageTypes &LT,=20
+                                    GlobalValue::LinkageTypes &LT,
+                                    GlobalValue::VisibilityTypes &Vis,
                                     bool &LinkFromSrc) {
   assert(Dest && "Must have two globals being queried");
   assert(!Src->hasLocalLinkage() &&
          "If Src has internal linkage, Dest shouldn't be set!");
  =20
-  bool SrcIsDeclaration =3D Src->isDeclaration();
+  bool SrcIsDeclaration =3D Src->isDeclaration() && !Src->isMaterializable=
();
   bool DestIsDeclaration =3D Dest->isDeclaration();
  =20
   if (SrcIsDeclaration) {
@@ -502,13 +555,10 @@
                  "': symbol multiply defined!");
   }
=20
-  // Check visibility
-  if (Src->getVisibility() !=3D Dest->getVisibility() &&
-      !SrcIsDeclaration && !DestIsDeclaration &&
-      !Src->hasAvailableExternallyLinkage() &&
-      !Dest->hasAvailableExternallyLinkage())
-    return emitError("Linking globals named '" + Src->getName() +
-                   "': symbols have different visibilities!");
+  // Compute the visibility. We follow the rules in the System V Applicati=
on
+  // Binary Interface.
+  Vis =3D isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
+    Dest->getVisibility() : Src->getVisibility();
   return false;
 }
=20
@@ -539,7 +589,54 @@
     if (GlobalValue *DGV =3D getLinkedToGlobal(I))
       TypeMap.addTypeMapping(DGV->getType(), I->getType());
   }
- =20
+
+  // Incorporate types by name, scanning all the types in the source modul=
e.
+  // At this point, the destination module may have a type "%foo =3D { i32=
 }" for
+  // example.  When the source module got loaded into the same LLVMContext=
, if
+  // it had the same type, it would have been renamed to "%foo.42 =3D { i3=
2 }".
+  std::vector<StructType*> SrcStructTypes;
+  SrcM->findUsedStructTypes(SrcStructTypes);
+  SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
+                                                 SrcStructTypes.end());
+
+  std::vector<StructType*> DstStructTypes;
+  DstM->findUsedStructTypes(DstStructTypes);
+  SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
+                                                 DstStructTypes.end());
+
+  for (unsigned i =3D 0, e =3D SrcStructTypes.size(); i !=3D e; ++i) {
+    StructType *ST =3D SrcStructTypes[i];
+    if (!ST->hasName()) continue;
+   =20
+    // Check to see if there is a dot in the name followed by a digit.
+    size_t DotPos =3D ST->getName().rfind('.');
+    if (DotPos =3D=3D 0 || DotPos =3D=3D StringRef::npos ||
+        ST->getName().back() =3D=3D '.' || !isdigit(ST->getName()[DotPos+1=
]))
+      continue;
+   =20
+    // Check to see if the destination module has a struct with the prefix=
 name.
+    if (StructType *DST =3D DstM->getTypeByName(ST->getName().substr(0, Do=
tPos)))
+      // Don't use it if this actually came from the source module. They'r=
e in
+      // the same LLVMContext after all. Also don't use it unless the type=
 is
+      // actually used in the destination module. This can happen in situa=
tions
+      // like this:
+      //
+      //      Module A                         Module B
+      //      --------                         --------
+      //   %Z =3D type { %A }                %B =3D type { %C.1 }
+      //   %A =3D type { %B.1, [7 x i8] }    %C.1 =3D type { i8* }
+      //   %B.1 =3D type { %C }              %A.2 =3D type { %B.3, [5 x i8=
] }
+      //   %C =3D type { i8* }               %B.3 =3D type { %C.1 }
+      //
+      // When we link Module B with Module A, the '%B' in Module B is
+      // used. However, that would then use '%C.1'. But when we process '%=
C.1',
+      // we prefer to take the '%C' version. So we are then left with both
+      // '%C.1' and '%C' being used for the same types. This leads to some
+      // variables using one type and some using the other.
+      if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
+        TypeMap.addTypeMapping(DST, ST);
+  }
+
   // Don't bother incorporating aliases, they aren't generally typed well.
  =20
   // Now that we have discovered all of the type equivalences, get a body =
for
@@ -590,7 +687,7 @@
                        DstGV->getType()->getAddressSpace());
  =20
   // Propagate alignment, visibility and section info.
-  CopyGVAttributes(NG, DstGV);
+  copyGVAttributes(NG, DstGV);
  =20
   AppendingVarInfo AVI;
   AVI.NewGV =3D NG;
@@ -615,6 +712,7 @@
 /// merge them into the dest module.
 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
   GlobalValue *DGV =3D getLinkedToGlobal(SGV);
+  llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
=20
   if (DGV) {
     // Concatenation of appending linkage variables is magic and handled l=
ater.
@@ -624,9 +722,11 @@
     // Determine whether linkage of these two globals follows the source
     // module's definition or the destination module's definition.
     GlobalValue::LinkageTypes NewLinkage =3D GlobalValue::InternalLinkage;
+    GlobalValue::VisibilityTypes NV;
     bool LinkFromSrc =3D false;
-    if (getLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc))
+    if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
       return true;
+    NewVisibility =3D NV;
=20
     // If we're not linking from the source, then keep the definition that=
 we
     // have.
@@ -636,9 +736,10 @@
         if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConst=
ant())
           DGVar->setConstant(true);
      =20
-      // Set calculated linkage.
+      // Set calculated linkage and visibility.
       DGV->setLinkage(NewLinkage);
-     =20
+      DGV->setVisibility(*NewVisibility);
+
       // Make sure to remember this mapping.
       ValueMap[SGV] =3D ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getT=
ype()));
      =20
@@ -660,7 +761,9 @@
                        SGV->isThreadLocal(),
                        SGV->getType()->getAddressSpace());
   // Propagate alignment, visibility and section info.
-  CopyGVAttributes(NewDGV, SGV);
+  copyGVAttributes(NewDGV, SGV);
+  if (NewVisibility)
+    NewDGV->setVisibility(*NewVisibility);
=20
   if (DGV) {
     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType(=
)));
@@ -676,17 +779,21 @@
 /// destination module if needed, setting up mapping information.
 bool ModuleLinker::linkFunctionProto(Function *SF) {
   GlobalValue *DGV =3D getLinkedToGlobal(SF);
+  llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
=20
   if (DGV) {
     GlobalValue::LinkageTypes NewLinkage =3D GlobalValue::InternalLinkage;
     bool LinkFromSrc =3D false;
-    if (getLinkageResult(DGV, SF, NewLinkage, LinkFromSrc))
+    GlobalValue::VisibilityTypes NV;
+    if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
       return true;
-   =20
+    NewVisibility =3D NV;
+
     if (!LinkFromSrc) {
       // Set calculated linkage
       DGV->setLinkage(NewLinkage);
-     =20
+      DGV->setVisibility(*NewVisibility);
+
       // Make sure to remember this mapping.
       ValueMap[SF] =3D ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getTy=
pe()));
      =20
@@ -702,12 +809,21 @@
   // bring SF over.
   Function *NewDF =3D Function::Create(TypeMap.get(SF->getFunctionType()),
                                      SF->getLinkage(), SF->getName(), DstM=
);
-  CopyGVAttributes(NewDF, SF);
+  copyGVAttributes(NewDF, SF);
+  if (NewVisibility)
+    NewDF->setVisibility(*NewVisibility);
=20
   if (DGV) {
     // Any uses of DF need to change to NewDF, with cast.
     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()=
));
     DGV->eraseFromParent();
+  } else {
+    // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily=
 link.
+    if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
+        SF->hasAvailableExternallyLinkage()) {
+      DoNotLinkFromSource.insert(SF);
+      LazilyLinkFunctions.push_back(SF);
+    }
   }
  =20
   ValueMap[SF] =3D NewDF;
@@ -718,17 +834,21 @@
 /// source module.
 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
   GlobalValue *DGV =3D getLinkedToGlobal(SGA);
- =20
+  llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
+
   if (DGV) {
     GlobalValue::LinkageTypes NewLinkage =3D GlobalValue::InternalLinkage;
+    GlobalValue::VisibilityTypes NV;
     bool LinkFromSrc =3D false;
-    if (getLinkageResult(DGV, SGA, NewLinkage, LinkFromSrc))
+    if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
       return true;
-   =20
+    NewVisibility =3D NV;
+
     if (!LinkFromSrc) {
       // Set calculated linkage.
       DGV->setLinkage(NewLinkage);
-     =20
+      DGV->setVisibility(*NewVisibility);
+
       // Make sure to remember this mapping.
       ValueMap[SGA] =3D ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getT=
ype()));
      =20
@@ -744,7 +864,9 @@
   GlobalAlias *NewDA =3D new GlobalAlias(TypeMap.get(SGA->getType()),
                                        SGA->getLinkage(), SGA->getName(),
                                        /*aliasee*/0, DstM);
-  CopyGVAttributes(NewDA, SGA);
+  copyGVAttributes(NewDA, SGA);
+  if (NewVisibility)
+    NewDA->setVisibility(*NewVisibility);
=20
   if (DGV) {
     // Any uses of DGV need to change to NewDA, with cast.
@@ -756,36 +878,27 @@
   return false;
 }
=20
+static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest=
) {
+  unsigned NumElements =3D cast<ArrayType>(C->getType())->getNumElements();
+
+  for (unsigned i =3D 0; i !=3D NumElements; ++i)
+    Dest.push_back(C->getAggregateElement(i));
+}
+                            =20
 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
   // Merge the initializer.
   SmallVector<Constant*, 16> Elements;
-  if (ConstantArray *I =3D dyn_cast<ConstantArray>(AVI.DstInit)) {
-    for (unsigned i =3D 0, e =3D I->getNumOperands(); i !=3D e; ++i)
-      Elements.push_back(I->getOperand(i));
-  } else {
-    assert(isa<ConstantAggregateZero>(AVI.DstInit));
-    ArrayType *DstAT =3D cast<ArrayType>(AVI.DstInit->getType());
-    Type *EltTy =3D DstAT->getElementType();
-    Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy)=
);
-  }
+  getArrayElements(AVI.DstInit, Elements);
  =20
   Constant *SrcInit =3D MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
-  if (const ConstantArray *I =3D dyn_cast<ConstantArray>(SrcInit)) {
-    for (unsigned i =3D 0, e =3D I->getNumOperands(); i !=3D e; ++i)
-      Elements.push_back(I->getOperand(i));
-  } else {
-    assert(isa<ConstantAggregateZero>(SrcInit));
-    ArrayType *SrcAT =3D cast<ArrayType>(SrcInit->getType());
-    Type *EltTy =3D SrcAT->getElementType();
-    Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy)=
);
-  }
+  getArrayElements(SrcInit, Elements);
+ =20
   ArrayType *NewType =3D cast<ArrayType>(AVI.NewGV->getType()->getElementT=
ype());
   AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
 }
=20
-
-// linkGlobalInits - Update the initializers in the Dest module now that a=
ll
-// globals that may be referenced are in Dest.
+/// linkGlobalInits - Update the initializers in the Dest module now that =
all
+/// globals that may be referenced are in Dest.
 void ModuleLinker::linkGlobalInits() {
   // Loop over all of the globals in the src module, mapping them over as =
we go
   for (Module::const_global_iterator I =3D SrcM->global_begin(),
@@ -802,9 +915,9 @@
   }
 }
=20
-// linkFunctionBody - Copy the source function over into the dest function=
 and
-// fix up references to values.  At this point we know that Dest is an ext=
ernal
-// function, and that Src is not.
+/// linkFunctionBody - Copy the source function over into the dest functio=
n and
+/// fix up references to values.  At this point we know that Dest is an ex=
ternal
+/// function, and that Src is not.
 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
=20
@@ -833,7 +946,7 @@
   } else {
     // Clone the body of the function into the dest function.
     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
-    CloneFunctionInto(Dst, Src, ValueMap, false, Returns);
+    CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeM=
ap);
   }
  =20
   // There is no need to map the arguments anymore.
@@ -843,7 +956,7 @@
  =20
 }
=20
-
+/// linkAliasBodies - Insert all of the aliases in Src into the Dest modul=
e.
 void ModuleLinker::linkAliasBodies() {
   for (Module::alias_iterator I =3D SrcM->alias_begin(), E =3D SrcM->alias=
_end();
        I !=3D E; ++I) {
@@ -856,11 +969,14 @@
   }
 }
=20
-/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
+/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
 /// module.
 void ModuleLinker::linkNamedMDNodes() {
+  const NamedMDNode *SrcModFlags =3D SrcM->getModuleFlagsMetadata();
   for (Module::const_named_metadata_iterator I =3D SrcM->named_metadata_be=
gin(),
        E =3D SrcM->named_metadata_end(); I !=3D E; ++I) {
+    // Don't link module flags here. Do them separately.
+    if (&*I =3D=3D SrcModFlags) continue;
     NamedMDNode *DestNMD =3D DstM->getOrInsertNamedMetadata(I->getName());
     // Add Src elements into Dest node.
     for (unsigned i =3D 0, e =3D I->getNumOperands(); i !=3D e; ++i)
@@ -868,10 +984,176 @@
                                    RF_None, &TypeMap));
   }
 }
+
+/// categorizeModuleFlagNodes - Categorize the module flags according to t=
heir
+/// type: Error, Warning, Override, and Require.
+bool ModuleLinker::
+categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
+                          DenseMap<MDString*, MDNode*> &ErrorNode,
+                          DenseMap<MDString*, MDNode*> &WarningNode,
+                          DenseMap<MDString*, MDNode*> &OverrideNode,
+                          DenseMap<MDString*,
+                            SmallSetVector<MDNode*, 8> > &RequireNodes,
+                          SmallSetVector<MDString*, 16> &SeenIDs) {
+  bool HasErr =3D false;
+
+  for (unsigned I =3D 0, E =3D ModFlags->getNumOperands(); I !=3D E; ++I) {
+    MDNode *Op =3D ModFlags->getOperand(I);
+    assert(Op->getNumOperands() =3D=3D 3 && "Invalid module flag metadata!=
");
+    assert(isa<ConstantInt>(Op->getOperand(0)) &&
+           "Module flag's first operand must be an integer!");
+    assert(isa<MDString>(Op->getOperand(1)) &&
+           "Module flag's second operand must be an MDString!");
+
+    ConstantInt *Behavior =3D cast<ConstantInt>(Op->getOperand(0));
+    MDString *ID =3D cast<MDString>(Op->getOperand(1));
+    Value *Val =3D Op->getOperand(2);
+    switch (Behavior->getZExtValue()) {
+    default:
+      assert(false && "Invalid behavior in module flag metadata!");
+      break;
+    case Module::Error: {
+      MDNode *&ErrNode =3D ErrorNode[ID];
+      if (!ErrNode) ErrNode =3D Op;
+      if (ErrNode->getOperand(2) !=3D Val)
+        HasErr =3D emitError("linking module flags '" + ID->getString() +
+                           "': IDs have conflicting values");
+      break;
+    }
+    case Module::Warning: {
+      MDNode *&WarnNode =3D WarningNode[ID];
+      if (!WarnNode) WarnNode =3D Op;
+      if (WarnNode->getOperand(2) !=3D Val)
+        errs() << "WARNING: linking module flags '" << ID->getString()
+               << "': IDs have conflicting values";
+      break;
+    }
+    case Module::Require:  RequireNodes[ID].insert(Op);     break;
+    case Module::Override: {
+      MDNode *&OvrNode =3D OverrideNode[ID];
+      if (!OvrNode) OvrNode =3D Op;
+      if (OvrNode->getOperand(2) !=3D Val)
+        HasErr =3D emitError("linking module flags '" + ID->getString() +
+                           "': IDs have conflicting override values");
+      break;
+    }
+    }
+
+    SeenIDs.insert(ID);
+  }
+
+  return HasErr;
+}
+
+/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
+/// module.
+bool ModuleLinker::linkModuleFlagsMetadata() {
+  const NamedMDNode *SrcModFlags =3D SrcM->getModuleFlagsMetadata();
+  if (!SrcModFlags) return false;
+
+  NamedMDNode *DstModFlags =3D DstM->getOrInsertModuleFlagsMetadata();
+
+  // If the destination module doesn't have module flags yet, then just co=
py
+  // over the source module's flags.
+  if (DstModFlags->getNumOperands() =3D=3D 0) {
+    for (unsigned I =3D 0, E =3D SrcModFlags->getNumOperands(); I !=3D E; =
++I)
+      DstModFlags->addOperand(SrcModFlags->getOperand(I));
+
+    return false;
+  }
+
+  bool HasErr =3D false;
+
+  // Otherwise, we have to merge them based on their behaviors. First,
+  // categorize all of the nodes in the modules' module flags. If an error=
 or
+  // warning occurs, then emit the appropriate message(s).
+  DenseMap<MDString*, MDNode*> ErrorNode;
+  DenseMap<MDString*, MDNode*> WarningNode;
+  DenseMap<MDString*, MDNode*> OverrideNode;
+  DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes;
+  SmallSetVector<MDString*, 16> SeenIDs;
+
+  HasErr |=3D categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNod=
e,
+                                      OverrideNode, RequireNodes, SeenIDs);
+  HasErr |=3D categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNod=
e,
+                                      OverrideNode, RequireNodes, SeenIDs);
+
+  // Check that there isn't both an error and warning node for a flag.
+  for (SmallSetVector<MDString*, 16>::iterator
+         I =3D SeenIDs.begin(), E =3D SeenIDs.end(); I !=3D E; ++I) {
+    MDString *ID =3D *I;
+    if (ErrorNode[ID] && WarningNode[ID])
+      HasErr =3D emitError("linking module flags '" + ID->getString() +
+                         "': IDs have conflicting behaviors");
+  }
+
+  // Early exit if we had an error.
+  if (HasErr) return true;
+
+  // Get the destination's module flags ready for new operands.
+  DstModFlags->dropAllReferences();
+
+  // Add all of the module flags to the destination module.
+  DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes;
+  for (SmallSetVector<MDString*, 16>::iterator
+         I =3D SeenIDs.begin(), E =3D SeenIDs.end(); I !=3D E; ++I) {
+    MDString *ID =3D *I;
+    if (OverrideNode[ID]) {
+      DstModFlags->addOperand(OverrideNode[ID]);
+      AddedNodes[ID].push_back(OverrideNode[ID]);
+    } else if (ErrorNode[ID]) {
+      DstModFlags->addOperand(ErrorNode[ID]);
+      AddedNodes[ID].push_back(ErrorNode[ID]);
+    } else if (WarningNode[ID]) {
+      DstModFlags->addOperand(WarningNode[ID]);
+      AddedNodes[ID].push_back(WarningNode[ID]);
+    }
+
+    for (SmallSetVector<MDNode*, 8>::iterator
+           II =3D RequireNodes[ID].begin(), IE =3D RequireNodes[ID].end();
+         II !=3D IE; ++II)
+      DstModFlags->addOperand(*II);
+  }
+
+  // Now check that all of the requirements have been satisfied.
+  for (SmallSetVector<MDString*, 16>::iterator
+         I =3D SeenIDs.begin(), E =3D SeenIDs.end(); I !=3D E; ++I) {
+    MDString *ID =3D *I;
+    SmallSetVector<MDNode*, 8> &Set =3D RequireNodes[ID];
+
+    for (SmallSetVector<MDNode*, 8>::iterator
+           II =3D Set.begin(), IE =3D Set.end(); II !=3D IE; ++II) {
+      MDNode *Node =3D *II;
+      assert(isa<MDNode>(Node->getOperand(2)) &&
+             "Module flag's third operand must be an MDNode!");
+      MDNode *Val =3D cast<MDNode>(Node->getOperand(2));
+
+      MDString *ReqID =3D cast<MDString>(Val->getOperand(0));
+      Value *ReqVal =3D Val->getOperand(1);
+
+      bool HasValue =3D false;
+      for (SmallVectorImpl<MDNode*>::iterator
+             RI =3D AddedNodes[ReqID].begin(), RE =3D AddedNodes[ReqID].en=
d();
+           RI !=3D RE; ++RI) {
+        MDNode *ReqNode =3D *RI;
+        if (ReqNode->getOperand(2) =3D=3D ReqVal) {
+          HasValue =3D true;
+          break;
+        }
+      }
+
+      if (!HasValue)
+        HasErr =3D emitError("linking module flags '" + ReqID->getString()=
 +
+                           "': does not have the required value");
+    }
+  }
+
+  return HasErr;
+}
  =20
 bool ModuleLinker::run() {
-  assert(DstM && "Null Destination module");
-  assert(SrcM && "Null Source Module");
+  assert(DstM && "Null destination module");
+  assert(SrcM && "Null source module");
=20
   // Inherit the target data from the source module if the destination mod=
ule
   // doesn't have one already.
@@ -951,7 +1233,6 @@
   // Link in the function bodies that are defined in the source module into
   // DstM.
   for (Module::iterator SF =3D SrcM->begin(), E =3D SrcM->end(); SF !=3D E=
; ++SF) {
-   =20
     // Skip if not linking from source.
     if (DoNotLinkFromSource.count(SF)) continue;
    =20
@@ -964,16 +1245,70 @@
     }
    =20
     linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
+    SF->Dematerialize();
   }
=20
   // Resolve all uses of aliases with aliasees.
   linkAliasBodies();
=20
-  // Remap all of the named mdnoes in Src into the DstM module. We do this
+  // Remap all of the named MDNodes in Src into the DstM module. We do this
   // after linking GlobalValues so that MDNodes that reference GlobalValues
   // are properly remapped.
   linkNamedMDNodes();
=20
+  // Merge the module flags into the DstM module.
+  if (linkModuleFlagsMetadata())
+    return true;
+
+  // Process vector of lazily linked in functions.
+  bool LinkedInAnyFunctions;
+  do {
+    LinkedInAnyFunctions =3D false;
+   =20
+    for(std::vector<Function*>::iterator I =3D LazilyLinkFunctions.begin(),
+        E =3D LazilyLinkFunctions.end(); I !=3D E; ++I) {
+      if (!*I)
+        continue;
+     =20
+      Function *SF =3D *I;
+      Function *DF =3D cast<Function>(ValueMap[SF]);
+     =20
+      if (!DF->use_empty()) {
+       =20
+        // Materialize if necessary.
+        if (SF->isDeclaration()) {
+          if (!SF->isMaterializable())
+            continue;
+          if (SF->Materialize(&ErrorMsg))
+            return true;
+        }
+       =20
+        // Link in function body.
+        linkFunctionBody(DF, SF);
+        SF->Dematerialize();
+
+        // "Remove" from vector by setting the element to 0.
+        *I =3D 0;
+       =20
+        // Set flag to indicate we may have more functions to lazily link =
in
+        // since we linked in a function.
+        LinkedInAnyFunctions =3D true;
+      }
+    }
+  } while (LinkedInAnyFunctions);
+ =20
+  // Remove any prototypes of functions that were not actually linked in.
+  for(std::vector<Function*>::iterator I =3D LazilyLinkFunctions.begin(),
+      E =3D LazilyLinkFunctions.end(); I !=3D E; ++I) {
+    if (!*I)
+      continue;
+   =20
+    Function *SF =3D *I;
+    Function *DF =3D cast<Function>(ValueMap[SF]);
+    if (DF->use_empty())
+      DF->eraseFromParent();
+  }
+ =20
   // Now that all of the types from the source are used, resolve any struc=
ts
   // copied over to the dest that didn't exist there.
   TypeMap.linkDefinedTypeBodies();
@@ -985,11 +1320,11 @@
 // LinkModules entrypoint.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-// LinkModules - This function links two modules together, with the result=
ing
-// left module modified to be the composite of the two input modules.  If =
an
-// error occurs, true is returned and ErrorMsg (if not null) is set to ind=
icate
-// the problem.  Upon failure, the Dest module could be in a modified stat=
e, and
-// shouldn't be relied on to be consistent.
+/// LinkModules - This function links two modules together, with the resul=
ting
+/// left module modified to be the composite of the two input modules.  If=
 an
+/// error occurs, true is returned and ErrorMsg (if not null) is set to in=
dicate
+/// the problem.  Upon failure, the Dest module could be in a modified sta=
te,
+/// and shouldn't be relied on to be consistent.
 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,=20
                          std::string *ErrorMsg) {
   ModuleLinker TheLinker(Dest, Src, Mode);
@@ -997,6 +1332,6 @@
     if (ErrorMsg) *ErrorMsg =3D TheLinker.ErrorMsg;
     return true;
   }
- =20
+
   return false;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Linker/Linker.cpp
--- a/head/contrib/llvm/lib/Linker/Linker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Linker/Linker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,6 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/Config/config.h"
 #include "llvm/Support/system_error.h"
 using namespace llvm;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/ELFObjectWrit=
er.cpp
--- a/head/contrib/llvm/lib/MC/ELFObjectWriter.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/MC/ELFObjectWriter.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -11,26 +11,26 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "ELFObjectWriter.h"
+#include "MCELF.h"
+#include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringMap.h"
-#include "llvm/ADT/Twine.h"
 #include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCAsmLayout.h"
+#include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCELFObjectWriter.h"
+#include "llvm/MC/MCELFSymbolFlags.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCFixupKindInfo.h"
+#include "llvm/MC/MCObjectWriter.h"
 #include "llvm/MC/MCSectionELF.h"
 #include "llvm/MC/MCValue.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/ELF.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/ADT/Statistic.h"
-#include "llvm/ADT/StringSwitch.h"
-
-#include "../Target/X86/MCTargetDesc/X86FixupKinds.h"
-#include "../Target/ARM/MCTargetDesc/ARMFixupKinds.h"
-#include "../Target/PowerPC/MCTargetDesc/PPCFixupKinds.h"
=20
 #include <vector>
 using namespace llvm;
@@ -38,6 +38,304 @@
 #undef  DEBUG_TYPE
 #define DEBUG_TYPE "reloc-info"
=20
+namespace {
+class ELFObjectWriter : public MCObjectWriter {
+  protected:
+
+    static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
+    static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
+    static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Lay=
out);
+    static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Dat=
a,
+                           bool Used, bool Renamed);
+    static bool isLocal(const MCSymbolData &Data, bool isSignature,
+                        bool isUsedInReloc);
+    static bool IsELFMetaDataSection(const MCSectionData &SD);
+    static uint64_t DataSectionSize(const MCSectionData &SD);
+    static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
+                                       const MCSectionData &SD);
+    static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
+                                          const MCSectionData &SD);
+
+    void WriteDataSectionData(MCAssembler &Asm,
+                              const MCAsmLayout &Layout,
+                              const MCSectionELF &Section);
+
+    /*static bool isFixupKindX86RIPRel(unsigned Kind) {
+      return Kind =3D=3D X86::reloc_riprel_4byte ||
+        Kind =3D=3D X86::reloc_riprel_4byte_movq_load;
+    }*/
+
+    /// ELFSymbolData - Helper struct for containing some precomputed
+    /// information on symbols.
+    struct ELFSymbolData {
+      MCSymbolData *SymbolData;
+      uint64_t StringIndex;
+      uint32_t SectionIndex;
+
+      // Support lexicographic sorting.
+      bool operator<(const ELFSymbolData &RHS) const {
+        if (MCELF::GetType(*SymbolData) =3D=3D ELF::STT_FILE)
+          return true;
+        if (MCELF::GetType(*RHS.SymbolData) =3D=3D ELF::STT_FILE)
+          return false;
+        return SymbolData->getSymbol().getName() <
+               RHS.SymbolData->getSymbol().getName();
+      }
+    };
+
+    /// The target specific ELF writer instance.
+    llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
+
+    SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
+    SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
+    DenseMap<const MCSymbol *, const MCSymbol *> Renames;
+
+    llvm::DenseMap<const MCSectionData*,
+                   std::vector<ELFRelocationEntry> > Relocations;
+    DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
+
+    /// @}
+    /// @name Symbol Table Data
+    /// @{
+
+    SmallString<256> StringTable;
+    std::vector<ELFSymbolData> LocalSymbolData;
+    std::vector<ELFSymbolData> ExternalSymbolData;
+    std::vector<ELFSymbolData> UndefinedSymbolData;
+
+    /// @}
+
+    bool NeedsGOT;
+
+    bool NeedsSymtabShndx;
+
+    // This holds the symbol table index of the last local symbol.
+    unsigned LastLocalSymbolIndex;
+    // This holds the .strtab section index.
+    unsigned StringTableIndex;
+    // This holds the .symtab section index.
+    unsigned SymbolTableIndex;
+
+    unsigned ShstrtabIndex;
+
+
+    const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
+                                  const MCValue &Target,
+                                  const MCFragment &F,
+                                  const MCFixup &Fixup,
+                                  bool IsPCRel) const;
+
+    // TargetObjectWriter wrappers.
+    const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
+                                   const MCValue &Target,
+                                   const MCFragment &F,
+                                   const MCFixup &Fixup,
+                                   bool IsPCRel) const {
+      return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsP=
CRel);
+    }
+
+    bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
+    bool hasRelocationAddend() const {
+      return TargetObjectWriter->hasRelocationAddend();
+    }
+    unsigned getEFlags() const {
+      return TargetObjectWriter->getEFlags();
+    }
+    unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
+                          bool IsPCRel, bool IsRelocWithSymbol,
+                          int64_t Addend) const {
+      return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
+                                              IsRelocWithSymbol, Addend);
+    }
+
+
+  public:
+    ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
+                    raw_ostream &_OS, bool IsLittleEndian)
+      : MCObjectWriter(_OS, IsLittleEndian),
+        TargetObjectWriter(MOTW),
+        NeedsGOT(false), NeedsSymtabShndx(false){
+    }
+
+    virtual ~ELFObjectWriter();
+
+    void WriteWord(uint64_t W) {
+      if (is64Bit())
+        Write64(W);
+      else
+        Write32(W);
+    }
+
+    void StringLE16(char *buf, uint16_t Value) {
+      buf[0] =3D char(Value >> 0);
+      buf[1] =3D char(Value >> 8);
+    }
+
+    void StringLE32(char *buf, uint32_t Value) {
+      StringLE16(buf, uint16_t(Value >> 0));
+      StringLE16(buf + 2, uint16_t(Value >> 16));
+    }
+
+    void StringLE64(char *buf, uint64_t Value) {
+      StringLE32(buf, uint32_t(Value >> 0));
+      StringLE32(buf + 4, uint32_t(Value >> 32));
+    }
+
+    void StringBE16(char *buf ,uint16_t Value) {
+      buf[0] =3D char(Value >> 8);
+      buf[1] =3D char(Value >> 0);
+    }
+
+    void StringBE32(char *buf, uint32_t Value) {
+      StringBE16(buf, uint16_t(Value >> 16));
+      StringBE16(buf + 2, uint16_t(Value >> 0));
+    }
+
+    void StringBE64(char *buf, uint64_t Value) {
+      StringBE32(buf, uint32_t(Value >> 32));
+      StringBE32(buf + 4, uint32_t(Value >> 0));
+    }
+
+    void String8(MCDataFragment &F, uint8_t Value) {
+      char buf[1];
+      buf[0] =3D Value;
+      F.getContents() +=3D StringRef(buf, 1);
+    }
+
+    void String16(MCDataFragment &F, uint16_t Value) {
+      char buf[2];
+      if (isLittleEndian())
+        StringLE16(buf, Value);
+      else
+        StringBE16(buf, Value);
+      F.getContents() +=3D StringRef(buf, 2);
+    }
+
+    void String32(MCDataFragment &F, uint32_t Value) {
+      char buf[4];
+      if (isLittleEndian())
+        StringLE32(buf, Value);
+      else
+        StringBE32(buf, Value);
+      F.getContents() +=3D StringRef(buf, 4);
+    }
+
+    void String64(MCDataFragment &F, uint64_t Value) {
+      char buf[8];
+      if (isLittleEndian())
+        StringLE64(buf, Value);
+      else
+        StringBE64(buf, Value);
+      F.getContents() +=3D StringRef(buf, 8);
+    }
+
+    void WriteHeader(uint64_t SectionDataSize,
+                     unsigned NumberOfSections);
+
+    void WriteSymbolEntry(MCDataFragment *SymtabF,
+                          MCDataFragment *ShndxF,
+                          uint64_t name, uint8_t info,
+                          uint64_t value, uint64_t size,
+                          uint8_t other, uint32_t shndx,
+                          bool Reserved);
+
+    void WriteSymbol(MCDataFragment *SymtabF,  MCDataFragment *ShndxF,
+                     ELFSymbolData &MSD,
+                     const MCAsmLayout &Layout);
+
+    typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
+    void WriteSymbolTable(MCDataFragment *SymtabF,
+                          MCDataFragment *ShndxF,
+                          const MCAssembler &Asm,
+                          const MCAsmLayout &Layout,
+                          const SectionIndexMapTy &SectionIndexMap);
+
+    virtual void RecordRelocation(const MCAssembler &Asm,
+                                  const MCAsmLayout &Layout,
+                                  const MCFragment *Fragment,
+                                  const MCFixup &Fixup,
+                                  MCValue Target, uint64_t &FixedValue);
+
+    uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
+                                         const MCSymbol *S);
+
+    // Map from a group section to the signature symbol
+    typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
+    // Map from a signature symbol to the group section
+    typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
+    // Map from a section to the section with the relocations
+    typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
+    // Map from a section to its offset
+    typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
+
+    /// ComputeSymbolTable - Compute the symbol table data
+    ///
+    /// \param StringTable [out] - The string table data.
+    /// \param StringIndexMap [out] - Map from symbol names to offsets in =
the
+    /// string table.
+    void ComputeSymbolTable(MCAssembler &Asm,
+                            const SectionIndexMapTy &SectionIndexMap,
+                            RevGroupMapTy RevGroupMap,
+                            unsigned NumRegularSections);
+
+    void ComputeIndexMap(MCAssembler &Asm,
+                         SectionIndexMapTy &SectionIndexMap,
+                         const RelMapTy &RelMap);
+
+    void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
+                                  RelMapTy &RelMap);
+
+    void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
+                          const RelMapTy &RelMap);
+
+    void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
+                                SectionIndexMapTy &SectionIndexMap,
+                                const RelMapTy &RelMap);
+
+    // Create the sections that show up in the symbol table. Currently
+    // those are the .note.GNU-stack section and the group sections.
+    void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
+                               GroupMapTy &GroupMap,
+                               RevGroupMapTy &RevGroupMap,
+                               SectionIndexMapTy &SectionIndexMap,
+                               const RelMapTy &RelMap);
+
+    virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
+                                          const MCAsmLayout &Layout);
+
+    void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
+                            const MCAsmLayout &Layout,
+                            const SectionIndexMapTy &SectionIndexMap,
+                            const SectionOffsetMapTy &SectionOffsetMap);
+
+    void ComputeSectionOrder(MCAssembler &Asm,
+                             std::vector<const MCSectionELF*> &Sections);
+
+    void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
+                          uint64_t Address, uint64_t Offset,
+                          uint64_t Size, uint32_t Link, uint32_t Info,
+                          uint64_t Alignment, uint64_t EntrySize);
+
+    void WriteRelocationsFragment(const MCAssembler &Asm,
+                                  MCDataFragment *F,
+                                  const MCSectionData *SD);
+
+    virtual bool
+    IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
+                                           const MCSymbolData &DataA,
+                                           const MCFragment &FB,
+                                           bool InSet,
+                                           bool IsPCRel) const;
+
+    virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
+    void WriteSection(MCAssembler &Asm,
+                      const SectionIndexMapTy &SectionIndexMap,
+                      uint32_t GroupSymbolIndex,
+                      uint64_t Offset, uint64_t Size, uint64_t Alignment,
+                      const MCSectionELF &Section);
+  };
+}
+
 bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Ki=
nd) {
   const MCFixupKindInfo &FKI =3D
     Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
@@ -92,11 +390,7 @@
=20
   Write8(ELF::EV_CURRENT);        // e_ident[EI_VERSION]
   // e_ident[EI_OSABI]
-  switch (TargetObjectWriter->getOSType()) {
-    case Triple::FreeBSD:  Write8(ELF::ELFOSABI_FREEBSD); break;
-    case Triple::Linux:    Write8(ELF::ELFOSABI_LINUX); break;
-    default:               Write8(ELF::ELFOSABI_NONE); break;
-  }
+  Write8(TargetObjectWriter->getOSABI());
   Write8(0);                  // e_ident[EI_ABIVERSION]
=20
   WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
@@ -112,7 +406,7 @@
             sizeof(ELF::Elf32_Ehdr)));  // e_shoff =3D sec hdr table off i=
n bytes
=20
   // e_flags =3D whatever the target wants
-  WriteEFlags();
+  Write32(getEFlags());
=20
   // e_ehsize =3D ELF header size
   Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
@@ -181,7 +475,7 @@
     if (const MCExpr *Value =3D Symbol.getVariableValue()) {
       int64_t IntValue;
       if (Value->EvaluateAsAbsolute(IntValue, Layout))
-	return (uint64_t)IntValue;
+        return (uint64_t)IntValue;
     }
   }
=20
@@ -277,7 +571,7 @@
                                        MCDataFragment *ShndxF,
                                        const MCAssembler &Asm,
                                        const MCAsmLayout &Layout,
-                                     const SectionIndexMapTy &SectionIndex=
Map) {
+                                    const SectionIndexMapTy &SectionIndexM=
ap) {
   // The string table must be emitted first because we need the index
   // into the string table for all the symbol names.
   assert(StringTable.size() && "Missing string table");
@@ -306,7 +600,8 @@
         Section.getType() =3D=3D ELF::SHT_SYMTAB_SHNDX)
       continue;
     WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
-                     ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section), f=
alse);
+                     ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
+                     false);
     LastLocalSymbolIndex++;
   }
=20
@@ -416,7 +711,7 @@
       // Offset of the symbol in the section
       int64_t a =3D Layout.getSymbolOffset(&SDB);
=20
-      // Ofeset of the relocation in the section
+      // Offset of the relocation in the section
       int64_t b =3D Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
       Value +=3D b - a;
     }
@@ -445,11 +740,16 @@
   FixedValue =3D Value;
   unsigned Type =3D GetRelocType(Target, Fixup, IsPCRel,
                                (RelocSymbol !=3D 0), Addend);
+  MCSymbolRefExpr::VariantKind Modifier =3D Target.isAbsolute() ?
+    MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
+  if (RelocNeedsGOT(Modifier))
+    NeedsGOT =3D true;
=20
   uint64_t RelocOffset =3D Layout.getFragmentOffset(Fragment) +
     Fixup.getOffset();
=20
-  adjustFixupOffset(Fixup, RelocOffset);
+  // FIXME: no tests cover this. Is adjustFixupOffset dead code?
+  TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
=20
   if (!hasRelocationAddend())
     Addend =3D 0;
@@ -459,7 +759,7 @@
   else
     assert(isInt<32>(Addend));
=20
-  ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
+  ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fi=
xup);
   Relocations[Fragment->getParent()].push_back(ERE);
 }
=20
@@ -745,8 +1045,10 @@
                                                MCDataFragment *F,
                                                const MCSectionData *SD) {
   std::vector<ELFRelocationEntry> &Relocs =3D Relocations[SD];
-  // sort by the r_offset just like gnu as does
-  array_pod_sort(Relocs.begin(), Relocs.end());
+
+  // Sort the relocation entries. Most targets just sort by r_offset, but =
some
+  // (e.g., MIPS) have additional constraints.
+  TargetObjectWriter->sortRelocs(Asm, Relocs);
=20
   for (unsigned i =3D 0, e =3D Relocs.size(); i !=3D e; ++i) {
     ELFRelocationEntry entry =3D Relocs[e - i - 1];
@@ -1053,14 +1355,10 @@
 void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
                                            const MCAsmLayout &Layout,
                                            const MCSectionELF &Section) {
-  uint64_t FileOff =3D OS.tell();
   const MCSectionData &SD =3D Asm.getOrCreateSectionData(Section);
=20
-  uint64_t Padding =3D OffsetToAlignment(FileOff, SD.getAlignment());
+  uint64_t Padding =3D OffsetToAlignment(OS.tell(), SD.getAlignment());
   WriteZeros(Padding);
-  FileOff +=3D Padding;
-
-  FileOff +=3D GetSectionFileSize(Layout, SD);
=20
   if (IsELFMetaDataSection(SD)) {
     for (MCSectionData::const_iterator i =3D SD.begin(), e =3D SD.end(); i=
 !=3D e;
@@ -1070,7 +1368,7 @@
       WriteBytes(cast<MCDataFragment>(F).getContents().str());
     }
   } else {
-    Asm.WriteSectionData(&SD, Layout);
+    Asm.writeSectionData(&SD, Layout);
   }
 }
=20
@@ -1226,16 +1524,13 @@
   for (unsigned i =3D 0; i < NumRegularSections + 1; ++i)
     WriteDataSectionData(Asm, Layout, *Sections[i]);
=20
-  FileOff =3D OS.tell();
-  uint64_t Padding =3D OffsetToAlignment(FileOff, NaturalAlignment);
+  uint64_t Padding =3D OffsetToAlignment(OS.tell(), NaturalAlignment);
   WriteZeros(Padding);
=20
   // ... then the section header table ...
   WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
                      SectionOffsetMap);
=20
-  FileOff =3D OS.tell();
-
   // ... and then the remaining sections ...
   for (unsigned i =3D NumRegularSections + 1; i < NumSections; ++i)
     WriteDataSectionData(Asm, Layout, *Sections[i]);
@@ -1256,577 +1551,5 @@
 MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
                                             raw_ostream &OS,
                                             bool IsLittleEndian) {
-  switch (MOTW->getEMachine()) {
-    case ELF::EM_386:
-    case ELF::EM_X86_64:
-      return new X86ELFObjectWriter(MOTW, OS, IsLittleEndian); break;
-    case ELF::EM_ARM:
-      return new ARMELFObjectWriter(MOTW, OS, IsLittleEndian); break;
-    case ELF::EM_MBLAZE:
-      return new MBlazeELFObjectWriter(MOTW, OS, IsLittleEndian); break;
-    case ELF::EM_PPC:
-    case ELF::EM_PPC64:
-      return new PPCELFObjectWriter(MOTW, OS, IsLittleEndian); break;
-    case ELF::EM_MIPS:
-      return new MipsELFObjectWriter(MOTW, OS, IsLittleEndian); break;
-    default: llvm_unreachable("Unsupported architecture"); break;
-  }
+  return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
 }
-
-
-/// START OF SUBCLASSES for ELFObjectWriter
-//=3D=3D=3D- ARMELFObjectWriter ------------------------------------------=
-=3D=3D=3D//
-
-ARMELFObjectWriter::ARMELFObjectWriter(MCELFObjectTargetWriter *MOTW,
-                                       raw_ostream &_OS,
-                                       bool IsLittleEndian)
-  : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
-{}
-
-ARMELFObjectWriter::~ARMELFObjectWriter()
-{}
-
-// FIXME: get the real EABI Version from the Triple.
-void ARMELFObjectWriter::WriteEFlags() {
-  Write32(ELF::EF_ARM_EABIMASK & DefaultEABIVersion);
-}
-
-// In ARM, _MergedGlobals and other most symbols get emitted directly.
-// I.e. not as an offset to a section symbol.
-// This code is an approximation of what ARM/gcc does.
-
-STATISTIC(PCRelCount, "Total number of PIC Relocations");
-STATISTIC(NonPCRelCount, "Total number of non-PIC relocations");
-
-const MCSymbol *ARMELFObjectWriter::ExplicitRelSym(const MCAssembler &Asm,
-                                                   const MCValue &Target,
-                                                   const MCFragment &F,
-                                                   const MCFixup &Fixup,
-                                                   bool IsPCRel) const {
-  const MCSymbol &Symbol =3D Target.getSymA()->getSymbol();
-  bool EmitThisSym =3D false;
-
-  const MCSectionELF &Section =3D
-    static_cast<const MCSectionELF&>(Symbol.getSection());
-  bool InNormalSection =3D true;
-  unsigned RelocType =3D 0;
-  RelocType =3D GetRelocTypeInner(Target, Fixup, IsPCRel);
-
-  DEBUG(
-      const MCSymbolRefExpr::VariantKind Kind =3D Target.getSymA()->getKin=
d();
-      MCSymbolRefExpr::VariantKind Kind2;
-      Kind2 =3D Target.getSymB() ?  Target.getSymB()->getKind() :
-        MCSymbolRefExpr::VK_None;
-      dbgs() << "considering symbol "
-        << Section.getSectionName() << "/"
-        << Symbol.getName() << "/"
-        << " Rel:" << (unsigned)RelocType
-        << " Kind: " << (int)Kind << "/" << (int)Kind2
-        << " Tmp:"
-        << Symbol.isAbsolute() << "/" << Symbol.isDefined() << "/"
-        << Symbol.isVariable() << "/" << Symbol.isTemporary()
-        << " Counts:" << PCRelCount << "/" << NonPCRelCount << "\n");
-
-  if (IsPCRel) { ++PCRelCount;
-    switch (RelocType) {
-    default:
-      // Most relocation types are emitted as explicit symbols
-      InNormalSection =3D
-        StringSwitch<bool>(Section.getSectionName())
-        .Case(".data.rel.ro.local", false)
-        .Case(".data.rel", false)
-        .Case(".bss", false)
-        .Default(true);
-      EmitThisSym =3D true;
-      break;
-    case ELF::R_ARM_ABS32:
-      // But things get strange with R_ARM_ABS32
-      // In this case, most things that go in .rodata show up
-      // as section relative relocations
-      InNormalSection =3D
-        StringSwitch<bool>(Section.getSectionName())
-        .Case(".data.rel.ro.local", false)
-        .Case(".data.rel", false)
-        .Case(".rodata", false)
-        .Case(".bss", false)
-        .Default(true);
-      EmitThisSym =3D false;
-      break;
-    }
-  } else {
-    NonPCRelCount++;
-    InNormalSection =3D
-      StringSwitch<bool>(Section.getSectionName())
-      .Case(".data.rel.ro.local", false)
-      .Case(".rodata", false)
-      .Case(".data.rel", false)
-      .Case(".bss", false)
-      .Default(true);
-
-    switch (RelocType) {
-    default: EmitThisSym =3D true; break;
-    case ELF::R_ARM_ABS32: EmitThisSym =3D false; break;
-    }
-  }
-
-  if (EmitThisSym)
-    return &Symbol;
-  if (! Symbol.isTemporary() && InNormalSection) {
-    return &Symbol;
-  }
-  return NULL;
-}
-
-// Need to examine the Fixup when determining whether to=20
-// emit the relocation as an explicit symbol or as a section relative
-// offset
-unsigned ARMELFObjectWriter::GetRelocType(const MCValue &Target,
-                                          const MCFixup &Fixup,
-                                          bool IsPCRel,
-                                          bool IsRelocWithSymbol,
-                                          int64_t Addend) {
-  MCSymbolRefExpr::VariantKind Modifier =3D Target.isAbsolute() ?
-    MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
-
-  unsigned Type =3D GetRelocTypeInner(Target, Fixup, IsPCRel);
-
-  if (RelocNeedsGOT(Modifier))
-    NeedsGOT =3D true;
- =20
-  return Type;
-}
-
-unsigned ARMELFObjectWriter::GetRelocTypeInner(const MCValue &Target,
-                                               const MCFixup &Fixup,
-                                               bool IsPCRel) const  {
-  MCSymbolRefExpr::VariantKind Modifier =3D Target.isAbsolute() ?
-    MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
-
-  unsigned Type =3D 0;
-  if (IsPCRel) {
-    switch ((unsigned)Fixup.getKind()) {
-    default: assert(0 && "Unimplemented");
-    case FK_Data_4:
-      switch (Modifier) {
-      default: llvm_unreachable("Unsupported Modifier");
-      case MCSymbolRefExpr::VK_None:
-        Type =3D ELF::R_ARM_REL32;
-        break;
-      case MCSymbolRefExpr::VK_ARM_TLSGD:
-        assert(0 && "unimplemented");
-        break;
-      case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
-        Type =3D ELF::R_ARM_TLS_IE32;
-        break;
-      }
-      break;
-    case ARM::fixup_arm_uncondbranch:
-      switch (Modifier) {
-      case MCSymbolRefExpr::VK_ARM_PLT:
-        Type =3D ELF::R_ARM_PLT32;
-        break;
-      default:
-        Type =3D ELF::R_ARM_CALL;
-        break;
-      }
-      break;
-    case ARM::fixup_arm_condbranch:
-      Type =3D ELF::R_ARM_JUMP24;
-      break;
-    case ARM::fixup_arm_movt_hi16:
-    case ARM::fixup_arm_movt_hi16_pcrel:
-      Type =3D ELF::R_ARM_MOVT_PREL;
-      break;
-    case ARM::fixup_arm_movw_lo16:
-    case ARM::fixup_arm_movw_lo16_pcrel:
-      Type =3D ELF::R_ARM_MOVW_PREL_NC;
-      break;
-    case ARM::fixup_t2_movt_hi16:
-    case ARM::fixup_t2_movt_hi16_pcrel:
-      Type =3D ELF::R_ARM_THM_MOVT_PREL;
-      break;
-    case ARM::fixup_t2_movw_lo16:
-    case ARM::fixup_t2_movw_lo16_pcrel:
-      Type =3D ELF::R_ARM_THM_MOVW_PREL_NC;
-      break;
-    case ARM::fixup_arm_thumb_bl:
-    case ARM::fixup_arm_thumb_blx:
-      switch (Modifier) {
-      case MCSymbolRefExpr::VK_ARM_PLT:
-        Type =3D ELF::R_ARM_THM_CALL;
-        break;
-      default:
-        Type =3D ELF::R_ARM_NONE;
-        break;
-      }
-      break;
-    }
-  } else {
-    switch ((unsigned)Fixup.getKind()) {
-    default: llvm_unreachable("invalid fixup kind!");
-    case FK_Data_4:
-      switch (Modifier) {
-      default: llvm_unreachable("Unsupported Modifier"); break;
-      case MCSymbolRefExpr::VK_ARM_GOT:
-        Type =3D ELF::R_ARM_GOT_BREL;
-        break;
-      case MCSymbolRefExpr::VK_ARM_TLSGD:
-        Type =3D ELF::R_ARM_TLS_GD32;
-        break;
-      case MCSymbolRefExpr::VK_ARM_TPOFF:
-        Type =3D ELF::R_ARM_TLS_LE32;
-        break;
-      case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
-        Type =3D ELF::R_ARM_TLS_IE32;
-        break;
-      case MCSymbolRefExpr::VK_None:
-        Type =3D ELF::R_ARM_ABS32;
-        break;
-      case MCSymbolRefExpr::VK_ARM_GOTOFF:
-        Type =3D ELF::R_ARM_GOTOFF32;
-        break;
-      }
-      break;
-    case ARM::fixup_arm_ldst_pcrel_12:
-    case ARM::fixup_arm_pcrel_10:
-    case ARM::fixup_arm_adr_pcrel_12:
-    case ARM::fixup_arm_thumb_bl:
-    case ARM::fixup_arm_thumb_cb:
-    case ARM::fixup_arm_thumb_cp:
-    case ARM::fixup_arm_thumb_br:
-      assert(0 && "Unimplemented");
-      break;
-    case ARM::fixup_arm_uncondbranch:
-      Type =3D ELF::R_ARM_CALL;
-      break;
-    case ARM::fixup_arm_condbranch:
-      Type =3D ELF::R_ARM_JUMP24;
-      break;
-    case ARM::fixup_arm_movt_hi16:
-      Type =3D ELF::R_ARM_MOVT_ABS;
-      break;
-    case ARM::fixup_arm_movw_lo16:
-      Type =3D ELF::R_ARM_MOVW_ABS_NC;
-      break;
-    case ARM::fixup_t2_movt_hi16:
-      Type =3D ELF::R_ARM_THM_MOVT_ABS;
-      break;
-    case ARM::fixup_t2_movw_lo16:
-      Type =3D ELF::R_ARM_THM_MOVW_ABS_NC;
-      break;
-    }
-  }
-
-  return Type;
-}
-
-//=3D=3D=3D- PPCELFObjectWriter ------------------------------------------=
-=3D=3D=3D//
-
-PPCELFObjectWriter::PPCELFObjectWriter(MCELFObjectTargetWriter *MOTW,
-                                             raw_ostream &_OS,
-                                             bool IsLittleEndian)
-  : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
-}
-
-PPCELFObjectWriter::~PPCELFObjectWriter() {
-}
-
-unsigned PPCELFObjectWriter::GetRelocType(const MCValue &Target,
-                                             const MCFixup &Fixup,
-                                             bool IsPCRel,
-                                             bool IsRelocWithSymbol,
-                                             int64_t Addend) {
-  // determine the type of the relocation
-  unsigned Type;
-  if (IsPCRel) {
-    switch ((unsigned)Fixup.getKind()) {
-    default:
-      llvm_unreachable("Unimplemented");
-    case PPC::fixup_ppc_br24:
-      Type =3D ELF::R_PPC_REL24;
-      break;
-    case FK_PCRel_4:
-      Type =3D ELF::R_PPC_REL32;
-      break;
-    }
-  } else {
-    switch ((unsigned)Fixup.getKind()) {
-      default: llvm_unreachable("invalid fixup kind!");
-    case PPC::fixup_ppc_br24:
-      Type =3D ELF::R_PPC_ADDR24;
-      break;
-    case PPC::fixup_ppc_brcond14:
-      Type =3D ELF::R_PPC_ADDR14_BRTAKEN; // XXX: or BRNTAKEN?_
-      break;
-    case PPC::fixup_ppc_ha16:
-      Type =3D ELF::R_PPC_ADDR16_HA;
-      break;
-    case PPC::fixup_ppc_lo16:
-      Type =3D ELF::R_PPC_ADDR16_LO;
-      break;
-    case PPC::fixup_ppc_lo14:
-      Type =3D ELF::R_PPC_ADDR14;
-      break;
-    case FK_Data_4:
-      Type =3D ELF::R_PPC_ADDR32;
-      break;
-    case FK_Data_2:
-      Type =3D ELF::R_PPC_ADDR16;
-      break;
-    }
-  }
-  return Type;
-}
-
-void
-PPCELFObjectWriter::adjustFixupOffset(const MCFixup &Fixup, uint64_t &Relo=
cOffset) {
-  switch ((unsigned)Fixup.getKind()) {
-    case PPC::fixup_ppc_ha16:
-    case PPC::fixup_ppc_lo16:
-      RelocOffset +=3D 2;
-      break;
-    default:
-      break;
-  }
-}
-
-//=3D=3D=3D- MBlazeELFObjectWriter ---------------------------------------=
----=3D=3D=3D//
-
-MBlazeELFObjectWriter::MBlazeELFObjectWriter(MCELFObjectTargetWriter *MOTW,
-                                             raw_ostream &_OS,
-                                             bool IsLittleEndian)
-  : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {
-}
-
-MBlazeELFObjectWriter::~MBlazeELFObjectWriter() {
-}
-
-unsigned MBlazeELFObjectWriter::GetRelocType(const MCValue &Target,
-                                             const MCFixup &Fixup,
-                                             bool IsPCRel,
-                                             bool IsRelocWithSymbol,
-                                             int64_t Addend) {
-  // determine the type of the relocation
-  unsigned Type;
-  if (IsPCRel) {
-    switch ((unsigned)Fixup.getKind()) {
-    default:
-      llvm_unreachable("Unimplemented");
-    case FK_PCRel_4:
-      Type =3D ELF::R_MICROBLAZE_64_PCREL;
-      break;
-    case FK_PCRel_2:
-      Type =3D ELF::R_MICROBLAZE_32_PCREL;
-      break;
-    }
-  } else {
-    switch ((unsigned)Fixup.getKind()) {
-    default: llvm_unreachable("invalid fixup kind!");
-    case FK_Data_4:
-      Type =3D ((IsRelocWithSymbol || Addend !=3D0)
-              ? ELF::R_MICROBLAZE_32
-              : ELF::R_MICROBLAZE_64);
-      break;
-    case FK_Data_2:
-      Type =3D ELF::R_MICROBLAZE_32;
-      break;
-    }
-  }
-  return Type;
-}
-
-//=3D=3D=3D- X86ELFObjectWriter ------------------------------------------=
-=3D=3D=3D//
-
-
-X86ELFObjectWriter::X86ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
-                                       raw_ostream &_OS,
-                                       bool IsLittleEndian)
-  : ELFObjectWriter(MOTW, _OS, IsLittleEndian)
-{}
-
-X86ELFObjectWriter::~X86ELFObjectWriter()
-{}
-
-unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
-                                          const MCFixup &Fixup,
-                                          bool IsPCRel,
-                                          bool IsRelocWithSymbol,
-                                          int64_t Addend) {
-  // determine the type of the relocation
-
-  MCSymbolRefExpr::VariantKind Modifier =3D Target.isAbsolute() ?
-    MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
-  unsigned Type;
-  if (is64Bit()) {
-    if (IsPCRel) {
-      switch ((unsigned)Fixup.getKind()) {
-      default: llvm_unreachable("invalid fixup kind!");
-
-      case FK_Data_8: Type =3D ELF::R_X86_64_PC64; break;
-      case FK_Data_4: Type =3D ELF::R_X86_64_PC32; break;
-      case FK_Data_2: Type =3D ELF::R_X86_64_PC16; break;
-
-      case FK_PCRel_8:
-        assert(Modifier =3D=3D MCSymbolRefExpr::VK_None);
-        Type =3D ELF::R_X86_64_PC64;
-        break;
-      case X86::reloc_signed_4byte:
-      case X86::reloc_riprel_4byte_movq_load:
-      case X86::reloc_riprel_4byte:
-      case FK_PCRel_4:
-        switch (Modifier) {
-        default:
-          llvm_unreachable("Unimplemented");
-        case MCSymbolRefExpr::VK_None:
-          Type =3D ELF::R_X86_64_PC32;
-          break;
-        case MCSymbolRefExpr::VK_PLT:
-          Type =3D ELF::R_X86_64_PLT32;
-          break;
-        case MCSymbolRefExpr::VK_GOTPCREL:
-          Type =3D ELF::R_X86_64_GOTPCREL;
-          break;
-        case MCSymbolRefExpr::VK_GOTTPOFF:
-          Type =3D ELF::R_X86_64_GOTTPOFF;
-        break;
-        case MCSymbolRefExpr::VK_TLSGD:
-          Type =3D ELF::R_X86_64_TLSGD;
-          break;
-        case MCSymbolRefExpr::VK_TLSLD:
-          Type =3D ELF::R_X86_64_TLSLD;
-          break;
-        }
-        break;
-      case FK_PCRel_2:
-        assert(Modifier =3D=3D MCSymbolRefExpr::VK_None);
-        Type =3D ELF::R_X86_64_PC16;
-        break;
-      case FK_PCRel_1:
-        assert(Modifier =3D=3D MCSymbolRefExpr::VK_None);
-        Type =3D ELF::R_X86_64_PC8;
-        break;
-      }
-    } else {
-      switch ((unsigned)Fixup.getKind()) {
-      default: llvm_unreachable("invalid fixup kind!");
-      case FK_Data_8: Type =3D ELF::R_X86_64_64; break;
-      case X86::reloc_signed_4byte:
-        switch (Modifier) {
-        default:
-          llvm_unreachable("Unimplemented");
-        case MCSymbolRefExpr::VK_None:
-          Type =3D ELF::R_X86_64_32S;
-          break;
-        case MCSymbolRefExpr::VK_GOT:
-          Type =3D ELF::R_X86_64_GOT32;
-          break;
-        case MCSymbolRefExpr::VK_GOTPCREL:
-          Type =3D ELF::R_X86_64_GOTPCREL;
-          break;
-        case MCSymbolRefExpr::VK_TPOFF:
-          Type =3D ELF::R_X86_64_TPOFF32;
-          break;
-        case MCSymbolRefExpr::VK_DTPOFF:
-          Type =3D ELF::R_X86_64_DTPOFF32;
-          break;
-        }
-        break;
-      case FK_Data_4:
-        Type =3D ELF::R_X86_64_32;
-        break;
-      case FK_Data_2: Type =3D ELF::R_X86_64_16; break;
-      case FK_PCRel_1:
-      case FK_Data_1: Type =3D ELF::R_X86_64_8; break;
-      }
-    }
-  } else {
-    if (IsPCRel) {
-      switch (Modifier) {
-      default:
-        llvm_unreachable("Unimplemented");
-      case MCSymbolRefExpr::VK_None:
-        Type =3D ELF::R_386_PC32;
-        break;
-      case MCSymbolRefExpr::VK_PLT:
-        Type =3D ELF::R_386_PLT32;
-        break;
-      }
-    } else {
-      switch ((unsigned)Fixup.getKind()) {
-      default: llvm_unreachable("invalid fixup kind!");
-
-      case X86::reloc_global_offset_table:
-        Type =3D ELF::R_386_GOTPC;
-        break;
-
-      // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
-      // instead?
-      case X86::reloc_signed_4byte:
-      case FK_PCRel_4:
-      case FK_Data_4:
-        switch (Modifier) {
-        default:
-          llvm_unreachable("Unimplemented");
-        case MCSymbolRefExpr::VK_None:
-          Type =3D ELF::R_386_32;
-          break;
-        case MCSymbolRefExpr::VK_GOT:
-          Type =3D ELF::R_386_GOT32;
-          break;
-        case MCSymbolRefExpr::VK_GOTOFF:
-          Type =3D ELF::R_386_GOTOFF;
-          break;
-        case MCSymbolRefExpr::VK_TLSGD:
-          Type =3D ELF::R_386_TLS_GD;
-          break;
-        case MCSymbolRefExpr::VK_TPOFF:
-          Type =3D ELF::R_386_TLS_LE_32;
-          break;
-        case MCSymbolRefExpr::VK_INDNTPOFF:
-          Type =3D ELF::R_386_TLS_IE;
-          break;
-        case MCSymbolRefExpr::VK_NTPOFF:
-          Type =3D ELF::R_386_TLS_LE;
-          break;
-        case MCSymbolRefExpr::VK_GOTNTPOFF:
-          Type =3D ELF::R_386_TLS_GOTIE;
-          break;
-        case MCSymbolRefExpr::VK_TLSLDM:
-          Type =3D ELF::R_386_TLS_LDM;
-          break;
-        case MCSymbolRefExpr::VK_DTPOFF:
-          Type =3D ELF::R_386_TLS_LDO_32;
-          break;
-        case MCSymbolRefExpr::VK_GOTTPOFF:
-          Type =3D ELF::R_386_TLS_IE_32;
-          break;
-        }
-        break;
-      case FK_Data_2: Type =3D ELF::R_386_16; break;
-      case FK_PCRel_1:
-      case FK_Data_1: Type =3D ELF::R_386_8; break;
-      }
-    }
-  }
-
-  if (RelocNeedsGOT(Modifier))
-    NeedsGOT =3D true;
-
-  return Type;
-}
-
-MipsELFObjectWriter::MipsELFObjectWriter(MCELFObjectTargetWriter *MOTW,
-                                         raw_ostream &_OS,
-                                         bool IsLittleEndian)
-  : ELFObjectWriter(MOTW, _OS, IsLittleEndian) {}
-
-MipsELFObjectWriter::~MipsELFObjectWriter() {}
-
-unsigned MipsELFObjectWriter::GetRelocType(const MCValue &Target,
-                                           const MCFixup &Fixup,
-                                           bool IsPCRel,
-                                           bool IsRelocWithSymbol,
-                                           int64_t Addend) {
-  // tbd
-  return 1;
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCAsmBackend.=
cpp
--- a/head/contrib/llvm/lib/MC/MCAsmBackend.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/MC/MCAsmBackend.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -8,6 +8,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/MC/MCAsmBackend.h"
+#include "llvm/MC/MCFixupKindInfo.h"
 using namespace llvm;
=20
 MCAsmBackend::MCAsmBackend()
@@ -21,14 +22,22 @@
 const MCFixupKindInfo &
 MCAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
   static const MCFixupKindInfo Builtins[] =3D {
-    { "FK_Data_1", 0, 8, 0 },
-    { "FK_Data_2", 0, 16, 0 },
-    { "FK_Data_4", 0, 32, 0 },
-    { "FK_Data_8", 0, 64, 0 },
-    { "FK_PCRel_1", 0, 8, MCFixupKindInfo::FKF_IsPCRel },
+    { "FK_Data_1",  0,  8, 0 },
+    { "FK_Data_2",  0, 16, 0 },
+    { "FK_Data_4",  0, 32, 0 },
+    { "FK_Data_8",  0, 64, 0 },
+    { "FK_PCRel_1", 0,  8, MCFixupKindInfo::FKF_IsPCRel },
     { "FK_PCRel_2", 0, 16, MCFixupKindInfo::FKF_IsPCRel },
     { "FK_PCRel_4", 0, 32, MCFixupKindInfo::FKF_IsPCRel },
-    { "FK_PCRel_8", 0, 64, MCFixupKindInfo::FKF_IsPCRel }
+    { "FK_PCRel_8", 0, 64, MCFixupKindInfo::FKF_IsPCRel },
+    { "FK_GPRel_1", 0,  8, 0 },
+    { "FK_GPRel_2", 0, 16, 0 },
+    { "FK_GPRel_4", 0, 32, 0 },
+    { "FK_GPRel_8", 0, 64, 0 },
+    { "FK_SecRel_1", 0,  8, 0 },
+    { "FK_SecRel_2", 0, 16, 0 },
+    { "FK_SecRel_4", 0, 32, 0 },
+    { "FK_SecRel_8", 0, 64, 0 }
   };
  =20
   assert((size_t)Kind <=3D sizeof(Builtins) / sizeof(Builtins[0]) &&
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCAsmInfo.cpp
--- a/head/contrib/llvm/lib/MC/MCAsmInfo.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCAsmInfo.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,6 @@
   HasSubsectionsViaSymbols =3D false;
   HasMachoZeroFillDirective =3D false;
   HasMachoTBSSDirective =3D false;
-  StructorOutputOrder =3D Structors::ReversePriorityOrder;
   HasStaticCtorDtorReferenceInStaticMode =3D false;
   LinkerRequiresNonEmptyDwarfLines =3D false;
   MaxInstLength =3D 4;
@@ -50,6 +49,7 @@
   AllowQuotesInName =3D false;
   AllowNameToStartWithDigit =3D false;
   AllowPeriodsInName =3D true;
+  AllowUTF8 =3D true;
   ZeroDirective =3D "\t.zero\t";
   AsciiDirective =3D "\t.ascii\t";
   AscizDirective =3D "\t.asciz\t";
@@ -68,6 +68,7 @@
   AlignDirective =3D "\t.align\t";
   AlignmentIsInBytes =3D true;
   TextAlignFillValue =3D 0;
+  GPRel64Directive =3D 0;
   GPRel32Directive =3D 0;
   GlobalDirective =3D "\t.globl\t";
   HasSetDirective =3D true;
@@ -91,6 +92,7 @@
   DwarfRequiresRelocationForSectionOffset =3D true;
   DwarfSectionOffsetDirective =3D 0;
   DwarfUsesLabelOffsetForRanges =3D true;
+  DwarfUsesRelocationsForStringPool =3D true;
   DwarfRegNumForCFI =3D false;
   HasMicrosoftFastStdCallMangling =3D false;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCAsmInfoCOFF=
.cpp
--- a/head/contrib/llvm/lib/MC/MCAsmInfoCOFF.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/MC/MCAsmInfoCOFF.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -13,9 +13,10 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/MC/MCAsmInfoCOFF.h"
-#include "llvm/ADT/SmallVector.h"
 using namespace llvm;
=20
+void MCAsmInfoCOFF::anchor() { }
+
 MCAsmInfoCOFF::MCAsmInfoCOFF() {
   GlobalPrefix =3D "_";
   COMMDirectiveAlignmentIsInBytes =3D false;
@@ -38,3 +39,15 @@
=20
   SupportsDataRegions =3D false;
 }
+
+void MCAsmInfoMicrosoft::anchor() { }
+
+MCAsmInfoMicrosoft::MCAsmInfoMicrosoft() {
+  AllowQuotesInName =3D true;
+}
+
+void MCAsmInfoGNUCOFF::anchor() { }
+
+MCAsmInfoGNUCOFF::MCAsmInfoGNUCOFF() {
+
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCAsmInfoDarw=
in.cpp
--- a/head/contrib/llvm/lib/MC/MCAsmInfoDarwin.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/MC/MCAsmInfoDarwin.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -18,6 +18,8 @@
 #include "llvm/MC/MCStreamer.h"
 using namespace llvm;
=20
+void MCAsmInfoDarwin::anchor() { }=20
+
 MCAsmInfoDarwin::MCAsmInfoDarwin() {
   // Common settings for all Darwin targets.
   // Syntax:
@@ -39,7 +41,6 @@
   ZeroDirective =3D "\t.space\t";  // ".space N" emits N zeros.
   HasMachoZeroFillDirective =3D true;  // Uses .zerofill
   HasMachoTBSSDirective =3D true; // Uses .tbss
-  StructorOutputOrder =3D Structors::PriorityOrder;
   HasStaticCtorDtorReferenceInStaticMode =3D true;
=20
   CodeBegin =3D "L$start$code$";
@@ -57,8 +58,9 @@
=20
   HiddenVisibilityAttr =3D MCSA_PrivateExtern;
   HiddenDeclarationVisibilityAttr =3D MCSA_Invalid;
+
   // Doesn't support protected visibility.
-  ProtectedVisibilityAttr =3D MCSA_Global;
+  ProtectedVisibilityAttr =3D MCSA_Invalid;
  =20
   HasDotTypeDotSizeDirective =3D false;
   HasNoDeadStrip =3D true;
@@ -66,4 +68,5 @@
=20
   DwarfRequiresRelocationForSectionOffset =3D false;
   DwarfUsesLabelOffsetForRanges =3D false;
+  DwarfUsesRelocationsForStringPool =3D false;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCAsmStreamer=
.cpp
--- a/head/contrib/llvm/lib/MC/MCAsmStreamer.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/MC/MCAsmStreamer.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -29,6 +29,7 @@
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/FormattedStream.h"
+#include "llvm/Support/PathV2.h"
 #include <cctype>
 using namespace llvm;
=20
@@ -50,6 +51,7 @@
   unsigned ShowInst : 1;
   unsigned UseLoc : 1;
   unsigned UseCFI : 1;
+  unsigned UseDwarfDirectory : 1;
=20
   enum EHSymbolFlags { EHGlobal         =3D 1,
                        EHWeakDefinition =3D 1 << 1,
@@ -59,17 +61,21 @@
   bool needsSet(const MCExpr *Value);
=20
   void EmitRegisterName(int64_t Register);
+  virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
+  virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame);
=20
 public:
   MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
                 bool isVerboseAsm, bool useLoc, bool useCFI,
+                bool useDwarfDirectory,
                 MCInstPrinter *printer, MCCodeEmitter *emitter,
                 MCAsmBackend *asmbackend,
                 bool showInst)
     : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
       InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
       CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
-      ShowInst(showInst), UseLoc(useLoc), UseCFI(useCFI) {
+      ShowInst(showInst), UseLoc(useLoc), UseCFI(useCFI),
+      UseDwarfDirectory(useDwarfDirectory) {
     if (InstPrinter && IsVerboseAsm)
       InstPrinter->setCommentStream(CommentStream);
   }
@@ -150,6 +156,7 @@
   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
   virtual void EmitCOFFSymbolType(int Type);
   virtual void EndCOFFSymbolDef();
+  virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
                                 unsigned ByteAlignment);
@@ -179,6 +186,8 @@
=20
   virtual void EmitSLEB128Value(const MCExpr *Value);
=20
+  virtual void EmitGPRel64Value(const MCExpr *Value);
+
   virtual void EmitGPRel32Value(const MCExpr *Value);
=20
=20
@@ -192,19 +201,18 @@
   virtual void EmitCodeAlignment(unsigned ByteAlignment,
                                  unsigned MaxBytesToEmit =3D 0);
=20
-  virtual void EmitValueToOffset(const MCExpr *Offset,
+  virtual bool EmitValueToOffset(const MCExpr *Offset,
                                  unsigned char Value =3D 0);
=20
   virtual void EmitFileDirective(StringRef Filename);
-  virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
+  virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
+                                      StringRef Filename);
   virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
                                      unsigned Column, unsigned Flags,
                                      unsigned Isa, unsigned Discriminator,
                                      StringRef FileName);
=20
   virtual void EmitCFISections(bool EH, bool Debug);
-  virtual void EmitCFIStartProc();
-  virtual void EmitCFIEndProc();
   virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
   virtual void EmitCFIDefCfaOffset(int64_t Offset);
   virtual void EmitCFIDefCfaRegister(int64_t Register);
@@ -216,6 +224,7 @@
   virtual void EmitCFISameValue(int64_t Register);
   virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
   virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
+  virtual void EmitCFISignalFrame();
=20
   virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
   virtual void EmitWin64EHEndProc();
@@ -249,7 +258,7 @@
   /// indicated by the hasRawTextSupport() predicate.
   virtual void EmitRawText(StringRef String);
=20
-  virtual void Finish();
+  virtual void FinishImpl();
=20
   /// @}
 };
@@ -334,7 +343,6 @@
=20
 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
   switch (Flag) {
-  default: assert(0 && "Invalid flag!");
   case MCAF_SyntaxUnified:         OS << "\t.syntax unified"; break;
   case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
   case MCAF_Code16:                OS << '\t'<< MAI.getCode16Directive(); =
break;
@@ -386,7 +394,7 @@
 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
                                         MCSymbolAttr Attribute) {
   switch (Attribute) {
-  case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
+  case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute");
   case MCSA_ELF_TypeFunction:    /// .type _foo, STT_FUNC  # aka @function
   case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
   case MCSA_ELF_TypeObject:      /// .type _foo, STT_OBJECT  # aka @object
@@ -398,7 +406,7 @@
     OS << "\t.type\t" << *Symbol << ','
        << ((MAI.getCommentString()[0] !=3D '@') ? '@' : '%');
     switch (Attribute) {
-    default: assert(0 && "Unknown ELF .type");
+    default: llvm_unreachable("Unknown ELF .type");
     case MCSA_ELF_TypeFunction:    OS << "function"; break;
     case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
     case MCSA_ELF_TypeObject:      OS << "object"; break;
@@ -465,6 +473,11 @@
   EmitEOL();
 }
=20
+void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
+  OS << "\t.secrel32\t" << *Symbol << '\n';
+  EmitEOL();
+}
+
 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
   assert(MAI.hasDotTypeDotSizeDirective());
   OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
@@ -652,6 +665,12 @@
   EmitEOL();
 }
=20
+void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) {
+  assert(MAI.getGPRel64Directive() !=3D 0);
+  OS << MAI.getGPRel64Directive() << *Value;
+  EmitEOL();
+}
+
 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
   assert(MAI.getGPRel32Directive() !=3D 0);
   OS << MAI.getGPRel32Directive() << *Value;
@@ -733,11 +752,12 @@
                        1, MaxBytesToEmit);
 }
=20
-void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
+bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
                                       unsigned char Value) {
   // FIXME: Verify that Offset is associated with the current section.
   OS << ".org " << *Offset << ", " << (unsigned) Value;
   EmitEOL();
+  return false;
 }
=20
=20
@@ -748,13 +768,27 @@
   EmitEOL();
 }
=20
-bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef File=
name){
+bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Dire=
ctory,
+                                           StringRef Filename) {
+  if (!UseDwarfDirectory && !Directory.empty()) {
+    if (sys::path::is_absolute(Filename))
+      return EmitDwarfFileDirective(FileNo, "", Filename);
+
+    SmallString<128> FullPathName =3D Directory;
+    sys::path::append(FullPathName, Filename);
+    return EmitDwarfFileDirective(FileNo, "", FullPathName);
+  }
+
   if (UseLoc) {
     OS << "\t.file\t" << FileNo << ' ';
+    if (!Directory.empty()) {
+      PrintQuotedString(Directory, OS);
+      OS << ' ';
+    }
     PrintQuotedString(Filename, OS);
     EmitEOL();
   }
-  return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
+  return this->MCStreamer::EmitDwarfFileDirective(FileNo, Directory, Filen=
ame);
 }
=20
 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
@@ -816,21 +850,25 @@
   EmitEOL();
 }
=20
-void MCAsmStreamer::EmitCFIStartProc() {
-  MCStreamer::EmitCFIStartProc();
-
-  if (!UseCFI)
+void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
+  if (!UseCFI) {
+    RecordProcStart(Frame);
     return;
+  }
=20
   OS << "\t.cfi_startproc";
   EmitEOL();
 }
=20
-void MCAsmStreamer::EmitCFIEndProc() {
-  MCStreamer::EmitCFIEndProc();
+void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
+  if (!UseCFI) {
+    RecordProcEnd(Frame);
+    return;
+  }
=20
-  if (!UseCFI)
-    return;
+  // Put a dummy non-null value in Frame.End to mark that this frame has b=
een
+  // closed.
+  Frame.End =3D (MCSymbol *) 1;
=20
   OS << "\t.cfi_endproc";
   EmitEOL();
@@ -965,6 +1003,16 @@
   EmitEOL();
 }
=20
+void MCAsmStreamer::EmitCFISignalFrame() {
+  MCStreamer::EmitCFISignalFrame();
+
+  if (!UseCFI)
+    return;
+
+  OS << "\t.cif_signal_frame";
+  EmitEOL();
+}
+
 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
   MCStreamer::EmitWin64EHStartProc(Symbol);
=20
@@ -1260,10 +1308,16 @@
   EmitEOL();
 }
=20
-void MCAsmStreamer::Finish() {
+void MCAsmStreamer::FinishImpl() {
+  // FIXME: This header is duplicated with MCObjectStreamer
   // Dump out the dwarf file & directory tables and line tables.
+  const MCSymbol *LineSectionSymbol =3D NULL;
   if (getContext().hasDwarfFiles() && !UseLoc)
-    MCDwarfFileTable::Emit(this);
+    LineSectionSymbol =3D MCDwarfFileTable::Emit(this);
+
+  // If we are generating dwarf for assembly source files dump out the sec=
tions.
+  if (getContext().getGenDwarfForAssembly())
+    MCGenDwarfInfo::Emit(this, LineSectionSymbol);
=20
   if (!UseCFI)
     EmitFrames(false);
@@ -1271,9 +1325,9 @@
 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
                                     formatted_raw_ostream &OS,
                                     bool isVerboseAsm, bool useLoc,
-                                    bool useCFI, MCInstPrinter *IP,
-                                    MCCodeEmitter *CE, MCAsmBackend *MAB,
-                                    bool ShowInst) {
+                                    bool useCFI, bool useDwarfDirectory,
+                                    MCInstPrinter *IP, MCCodeEmitter *CE,
+                                    MCAsmBackend *MAB, bool ShowInst) {
   return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc, useCFI,
-                           IP, CE, MAB, ShowInst);
+                           useDwarfDirectory, IP, CE, MAB, ShowInst);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCAssembler.c=
pp
--- a/head/contrib/llvm/lib/MC/MCAssembler.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/MC/MCAssembler.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,13 +13,13 @@
 #include "llvm/MC/MCCodeEmitter.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCFixupKindInfo.h"
 #include "llvm/MC/MCObjectWriter.h"
 #include "llvm/MC/MCSection.h"
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/MC/MCValue.h"
 #include "llvm/MC/MCDwarf.h"
 #include "llvm/MC/MCAsmBackend.h"
-#include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/Twine.h"
@@ -33,7 +33,7 @@
 namespace {
 namespace stats {
 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
-STATISTIC(EvaluateFixup, "Number of evaluated fixups");
+STATISTIC(evaluateFixup, "Number of evaluated fixups");
 STATISTIC(FragmentLayouts, "Number of fragment layouts");
 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation step=
s");
@@ -118,7 +118,7 @@
     if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
       report_fatal_error("unable to evaluate offset to undefined symbol '"=
 +
                          Target.getSymB()->getSymbol().getName() + "'");
-     =20
+
     uint64_t Offset =3D Target.getConstant();
     if (Target.getSymA())
       Offset +=3D getSymbolOffset(&Assembler.getSymbolData(
@@ -136,7 +136,7 @@
 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const=
 {
   // The size is the last fragment's end offset.
   const MCFragment &F =3D SD->getFragmentList().back();
-  return getFragmentOffset(&F) + getAssembler().ComputeFragmentSize(*this,=
 F);
+  return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this,=
 F);
 }
=20
 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
@@ -237,13 +237,13 @@
   return SD->getFragment()->getAtom();
 }
=20
-bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout,
+bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
                                 const MCFixup &Fixup, const MCFragment *DF,
                                 MCValue &Target, uint64_t &Value) const {
-  ++stats::EvaluateFixup;
+  ++stats::evaluateFixup;
=20
   if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
-    report_fatal_error("expected relocatable expression");
+    getContext().FatalError(Fixup.getLoc(), "expected relocatable expressi=
on");
=20
   bool IsPCRel =3D Backend.getFixupKindInfo(
     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
@@ -273,13 +273,10 @@
=20
   Value =3D Target.getConstant();
=20
-  bool IsThumb =3D false;
   if (const MCSymbolRefExpr *A =3D Target.getSymA()) {
     const MCSymbol &Sym =3D A->getSymbol().AliasedSymbol();
     if (Sym.isDefined())
       Value +=3D Layout.getSymbolOffset(&getSymbolData(Sym));
-    if (isThumbFunc(&Sym))
-      IsThumb =3D true;
   }
   if (const MCSymbolRefExpr *B =3D Target.getSymB()) {
     const MCSymbol &Sym =3D B->getSymbol().AliasedSymbol();
@@ -295,24 +292,22 @@
=20
   if (IsPCRel) {
     uint32_t Offset =3D Layout.getFragmentOffset(DF) + Fixup.getOffset();
-   =20
+
     // A number of ARM fixups in Thumb mode require that the effective PC
     // address be determined as the 32-bit aligned version of the actual o=
ffset.
     if (ShouldAlignPC) Offset &=3D ~0x3;
     Value -=3D Offset;
   }
=20
-  // ARM fixups based from a thumb function address need to have the low
-  // bit set. The actual value is always at least 16-bit aligned, so the
-  // low bit is normally clear and available for use as an ISA flag for
-  // interworking.
-  if (IsThumb)
-    Value |=3D 1;
+  // Let the backend adjust the fixup value if necessary, including whether
+  // we need a relocation.
+  Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
+                            IsResolved);
=20
   return IsResolved;
 }
=20
-uint64_t MCAssembler::ComputeFragmentSize(const MCAsmLayout &Layout,
+uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
                                           const MCFragment &F) const {
   switch (F.getKind()) {
   case MCFragment::FT_Data:
@@ -355,8 +350,7 @@
     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
   }
=20
-  assert(0 && "invalid fragment kind");
-  return 0;
+  llvm_unreachable("invalid fragment kind");
 }
=20
 void MCAsmLayout::LayoutFragment(MCFragment *F) {
@@ -374,7 +368,7 @@
   // Compute fragment offset and size.
   uint64_t Offset =3D 0;
   if (Prev)
-    Offset +=3D Prev->Offset + getAssembler().ComputeFragmentSize(*this, *=
Prev);
+    Offset +=3D Prev->Offset + getAssembler().computeFragmentSize(*this, *=
Prev);
=20
   F->Offset =3D Offset;
   LastValidFragment[F->getParent()] =3D F;
@@ -390,7 +384,7 @@
   ++stats::EmittedFragments;
=20
   // FIXME: Embed in fragments instead?
-  uint64_t FragmentSize =3D Asm.ComputeFragmentSize(Layout, F);
+  uint64_t FragmentSize =3D Asm.computeFragmentSize(Layout, F);
   switch (F.getKind()) {
   case MCFragment::FT_Align: {
     MCAlignFragment &AF =3D cast<MCAlignFragment>(F);
@@ -412,7 +406,7 @@
     // bytes left to fill use the the Value and ValueSize to fill the rest.
     // If we are aligning with nops, ask that target to emit the right dat=
a.
     if (AF.hasEmitNops()) {
-      if (!Asm.getBackend().WriteNopData(Count, OW))
+      if (!Asm.getBackend().writeNopData(Count, OW))
         report_fatal_error("unable to write nop sequence of " +
                           Twine(Count) + " bytes");
       break;
@@ -421,8 +415,7 @@
     // Otherwise, write out in multiples of the value size.
     for (uint64_t i =3D 0; i !=3D Count; ++i) {
       switch (AF.getValueSize()) {
-      default:
-        assert(0 && "Invalid size!");
+      default: llvm_unreachable("Invalid size!");
       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
       case 2: OW->Write16(uint16_t(AF.getValue())); break;
       case 4: OW->Write32(uint32_t(AF.getValue())); break;
@@ -446,8 +439,7 @@
=20
     for (uint64_t i =3D 0, e =3D FF.getSize() / FF.getValueSize(); i !=3D =
e; ++i) {
       switch (FF.getValueSize()) {
-      default:
-        assert(0 && "Invalid size!");
+      default: llvm_unreachable("Invalid size!");
       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
       case 2: OW->Write16(uint16_t(FF.getValue())); break;
       case 4: OW->Write32(uint32_t(FF.getValue())); break;
@@ -493,7 +485,7 @@
   assert(OW->getStream().tell() - Start =3D=3D FragmentSize);
 }
=20
-void MCAssembler::WriteSectionData(const MCSectionData *SD,
+void MCAssembler::writeSectionData(const MCSectionData *SD,
                                    const MCAsmLayout &Layout) const {
   // Ignore virtual sections.
   if (SD->getSection().isVirtualSection()) {
@@ -503,8 +495,7 @@
     for (MCSectionData::const_iterator it =3D SD->begin(),
            ie =3D SD->end(); it !=3D ie; ++it) {
       switch (it->getKind()) {
-      default:
-        assert(0 && "Invalid fragment in virtual section!");
+      default: llvm_unreachable("Invalid fragment in virtual section!");
       case MCFragment::FT_Data: {
         // Check that we aren't trying to write a non-zero contents (or fi=
xups)
         // into a virtual section. This is to support clients which use st=
andard
@@ -546,13 +537,13 @@
 }
=20
=20
-uint64_t MCAssembler::HandleFixup(const MCAsmLayout &Layout,
+uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
                                   MCFragment &F,
                                   const MCFixup &Fixup) {
    // Evaluate the fixup.
    MCValue Target;
    uint64_t FixedValue;
-   if (!EvaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
+   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
      // The fixup was unresolved, we need a relocation. Inform the object
      // writer of the relocation, and give it an opportunity to adjust the
      // fixup value if need be.
@@ -592,7 +583,7 @@
   }
=20
   // Layout until everything fits.
-  while (LayoutOnce(Layout))
+  while (layoutOnce(Layout))
     continue;
=20
   DEBUG_WITH_TYPE("mc-dump", {
@@ -600,7 +591,7 @@
       dump(); });
=20
   // Finalize the layout, including fragment lowering.
-  FinishLayout(Layout);
+  finishLayout(Layout);
=20
   DEBUG_WITH_TYPE("mc-dump", {
       llvm::errs() << "assembler backend - final-layout\n--\n";
@@ -621,8 +612,8 @@
         for (MCDataFragment::fixup_iterator it3 =3D DF->fixup_begin(),
                ie3 =3D DF->fixup_end(); it3 !=3D ie3; ++it3) {
           MCFixup &Fixup =3D *it3;
-          uint64_t FixedValue =3D HandleFixup(Layout, *DF, Fixup);
-          getBackend().ApplyFixup(Fixup, DF->getContents().data(),
+          uint64_t FixedValue =3D handleFixup(Layout, *DF, Fixup);
+          getBackend().applyFixup(Fixup, DF->getContents().data(),
                                   DF->getContents().size(), FixedValue);
         }
       }
@@ -631,8 +622,8 @@
         for (MCInstFragment::fixup_iterator it3 =3D IF->fixup_begin(),
                ie3 =3D IF->fixup_end(); it3 !=3D ie3; ++it3) {
           MCFixup &Fixup =3D *it3;
-          uint64_t FixedValue =3D HandleFixup(Layout, *IF, Fixup);
-          getBackend().ApplyFixup(Fixup, IF->getCode().data(),
+          uint64_t FixedValue =3D handleFixup(Layout, *IF, Fixup);
+          getBackend().applyFixup(Fixup, IF->getCode().data(),
                                   IF->getCode().size(), FixedValue);
         }
       }
@@ -645,8 +636,8 @@
   stats::ObjectBytes +=3D OS.tell() - StartOffset;
 }
=20
-bool MCAssembler::FixupNeedsRelaxation(const MCFixup &Fixup,
-                                       const MCFragment *DF,
+bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
+                                       const MCInstFragment *DF,
                                        const MCAsmLayout &Layout) const {
   if (getRelaxAll())
     return true;
@@ -654,34 +645,31 @@
   // If we cannot resolve the fixup value, it requires relaxation.
   MCValue Target;
   uint64_t Value;
-  if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
+  if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
     return true;
=20
-  // Otherwise, relax if the value is too big for a (signed) i8.
-  //
-  // FIXME: This is target dependent!
-  return int64_t(Value) !=3D int64_t(int8_t(Value));
+  return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
 }
=20
-bool MCAssembler::FragmentNeedsRelaxation(const MCInstFragment *IF,
+bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
                                           const MCAsmLayout &Layout) const=
 {
   // If this inst doesn't ever need relaxation, ignore it. This occurs whe=
n we
   // are intentionally pushing out inst fragments, or because we relaxed a
   // previous instruction to one that doesn't need relaxation.
-  if (!getBackend().MayNeedRelaxation(IF->getInst()))
+  if (!getBackend().mayNeedRelaxation(IF->getInst()))
     return false;
=20
   for (MCInstFragment::const_fixup_iterator it =3D IF->fixup_begin(),
          ie =3D IF->fixup_end(); it !=3D ie; ++it)
-    if (FixupNeedsRelaxation(*it, IF, Layout))
+    if (fixupNeedsRelaxation(*it, IF, Layout))
       return true;
=20
   return false;
 }
=20
-bool MCAssembler::RelaxInstruction(MCAsmLayout &Layout,
+bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
                                    MCInstFragment &IF) {
-  if (!FragmentNeedsRelaxation(&IF, Layout))
+  if (!fragmentNeedsRelaxation(&IF, Layout))
     return false;
=20
   ++stats::RelaxedInstructions;
@@ -692,7 +680,7 @@
   // Relax the fragment.
=20
   MCInst Relaxed;
-  getBackend().RelaxInstruction(IF.getInst(), Relaxed);
+  getBackend().relaxInstruction(IF.getInst(), Relaxed);
=20
   // Encode the new instruction.
   //
@@ -715,7 +703,7 @@
   return true;
 }
=20
-bool MCAssembler::RelaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
+bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
   int64_t Value =3D 0;
   uint64_t OldSize =3D LF.getContents().size();
   bool IsAbs =3D LF.getValue().EvaluateAsAbsolute(Value, Layout);
@@ -732,8 +720,8 @@
   return OldSize !=3D LF.getContents().size();
 }
=20
-bool MCAssembler::RelaxDwarfLineAddr(MCAsmLayout &Layout,
-				     MCDwarfLineAddrFragment &DF) {
+bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
+                                     MCDwarfLineAddrFragment &DF) {
   int64_t AddrDelta =3D 0;
   uint64_t OldSize =3D DF.getContents().size();
   bool IsAbs =3D DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
@@ -749,7 +737,7 @@
   return OldSize !=3D Data.size();
 }
=20
-bool MCAssembler::RelaxDwarfCallFrameFragment(MCAsmLayout &Layout,
+bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
                                               MCDwarfCallFrameFragment &DF=
) {
   int64_t AddrDelta =3D 0;
   uint64_t OldSize =3D DF.getContents().size();
@@ -764,7 +752,7 @@
   return OldSize !=3D Data.size();
 }
=20
-bool MCAssembler::LayoutSectionOnce(MCAsmLayout &Layout,
+bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
                                     MCSectionData &SD) {
   MCFragment *FirstInvalidFragment =3D NULL;
   // Scan for fragments that need relaxation.
@@ -776,19 +764,19 @@
     default:
           break;
     case MCFragment::FT_Inst:
-      relaxedFrag =3D RelaxInstruction(Layout, *cast<MCInstFragment>(it2));
+      relaxedFrag =3D relaxInstruction(Layout, *cast<MCInstFragment>(it2));
       break;
     case MCFragment::FT_Dwarf:
-      relaxedFrag =3D RelaxDwarfLineAddr(Layout,
+      relaxedFrag =3D relaxDwarfLineAddr(Layout,
                                        *cast<MCDwarfLineAddrFragment>(it2)=
);
       break;
     case MCFragment::FT_DwarfFrame:
       relaxedFrag =3D
-        RelaxDwarfCallFrameFragment(Layout,
+        relaxDwarfCallFrameFragment(Layout,
                                     *cast<MCDwarfCallFrameFragment>(it2));
       break;
     case MCFragment::FT_LEB:
-      relaxedFrag =3D RelaxLEB(Layout, *cast<MCLEBFragment>(it2));
+      relaxedFrag =3D relaxLEB(Layout, *cast<MCLEBFragment>(it2));
       break;
     }
     // Update the layout, and remember that we relaxed.
@@ -802,20 +790,20 @@
   return false;
 }
=20
-bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
+bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
   ++stats::RelaxationSteps;
=20
   bool WasRelaxed =3D false;
   for (iterator it =3D begin(), ie =3D end(); it !=3D ie; ++it) {
     MCSectionData &SD =3D *it;
-    while(LayoutSectionOnce(Layout, SD))
+    while(layoutSectionOnce(Layout, SD))
       WasRelaxed =3D true;
   }
=20
   return WasRelaxed;
 }
=20
-void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
+void MCAssembler::finishLayout(MCAsmLayout &Layout) {
   // The layout is done. Mark every fragment as valid.
   for (unsigned int i =3D 0, n =3D Layout.getSectionOrder().size(); i !=3D=
 n; ++i) {
     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
@@ -975,3 +963,13 @@
   }
   OS << "]>\n";
 }
+
+// anchors for MC*Fragment vtables
+void MCDataFragment::anchor() { }
+void MCInstFragment::anchor() { }
+void MCAlignFragment::anchor() { }
+void MCFillFragment::anchor() { }
+void MCOrgFragment::anchor() { }
+void MCLEBFragment::anchor() { }
+void MCDwarfLineAddrFragment::anchor() { }
+void MCDwarfCallFrameFragment::anchor() { }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCCodeGenInfo=
.cpp
--- a/head/contrib/llvm/lib/MC/MCCodeGenInfo.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/MC/MCCodeGenInfo.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,9 @@
 #include "llvm/MC/MCCodeGenInfo.h"
 using namespace llvm;
=20
-void MCCodeGenInfo::InitMCCodeGenInfo(Reloc::Model RM, CodeModel::Model CM=
) {
+void MCCodeGenInfo::InitMCCodeGenInfo(Reloc::Model RM, CodeModel::Model CM,
+                                      CodeGenOpt::Level OL) {
   RelocationModel =3D RM;
   CMModel =3D CM;
+  OptLevel =3D OL;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCContext.cpp
--- a/head/contrib/llvm/lib/MC/MCContext.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCContext.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -20,6 +20,9 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/ELF.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/SourceMgr.h"
+#include "llvm/Support/Signals.h"
 using namespace llvm;
=20
 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
@@ -28,8 +31,8 @@
=20
=20
 MCContext::MCContext(const MCAsmInfo &mai, const MCRegisterInfo &mri,
-                     const MCObjectFileInfo *mofi) :
-  MAI(mai), MRI(mri), MOFI(mofi),
+                     const MCObjectFileInfo *mofi, const SourceMgr *mgr) :
+  SrcMgr(mgr), MAI(mai), MRI(mri), MOFI(mofi),
   Allocator(), Symbols(Allocator), UsedNames(Allocator),
   NextUniqueID(0),
   CurrentDwarfLoc(0,0,0,DWARF2_FLAG_IS_STMT,0,0),
@@ -43,6 +46,8 @@
   SecureLogUsed =3D false;
=20
   DwarfLocSeen =3D false;
+  GenDwarfForAssembly =3D false;
+  GenDwarfFileNumber =3D 0;
 }
=20
 MCContext::~MCContext() {
@@ -248,7 +253,8 @@
 /// directory tables.  If the file number has already been allocated it is=
 an
 /// error and zero is returned and the client reports the error, else the
 /// allocated file number is returned.  The file numbers may be in any ord=
er.
-unsigned MCContext::GetDwarfFile(StringRef FileName, unsigned FileNumber) {
+unsigned MCContext::GetDwarfFile(StringRef Directory, StringRef FileName,
+                                 unsigned FileNumber) {
   // TODO: a FileNumber of zero says to use the next available file number.
   // Note: in GenericAsmParser::ParseDirectiveFile() FileNumber was checked
   // to not be less than one.  This needs to be change to be not less than=
 zero.
@@ -266,19 +272,23 @@
   // Get the new MCDwarfFile slot for this FileNumber.
   MCDwarfFile *&File =3D MCDwarfFiles[FileNumber];
=20
-  // Separate the directory part from the basename of the FileName.
-  std::pair<StringRef, StringRef> Slash =3D FileName.rsplit('/');
+  if (Directory.empty()) {
+    // Separate the directory part from the basename of the FileName.
+    std::pair<StringRef, StringRef> Slash =3D FileName.rsplit('/');
+    Directory =3D Slash.second;
+    if (!Directory.empty()) {
+      Directory =3D Slash.first;
+      FileName =3D Slash.second;
+    }
+  }
=20
   // Find or make a entry in the MCDwarfDirs vector for this Directory.
-  StringRef Name;
+  // Capture directory name.
   unsigned DirIndex;
-  // Capture directory name.
-  if (Slash.second.empty()) {
-    Name =3D Slash.first;
-    DirIndex =3D 0; // For FileNames with no directories a DirIndex of 0 i=
s used.
+  if (Directory.empty()) {
+    // For FileNames with no directories a DirIndex of 0 is used.
+    DirIndex =3D 0;
   } else {
-    StringRef Directory =3D Slash.first;
-    Name =3D Slash.second;
     DirIndex =3D 0;
     for (unsigned End =3D MCDwarfDirs.size(); DirIndex < End; DirIndex++) {
       if (Directory =3D=3D MCDwarfDirs[DirIndex])
@@ -291,16 +301,16 @@
     }
     // The DirIndex is one based, as DirIndex of 0 is used for FileNames w=
ith
     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
-    // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNam=
es are
-    // stored at MCDwarfFiles[FileNumber].Name .
+    // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNam=
es
+    // are stored at MCDwarfFiles[FileNumber].Name .
     DirIndex++;
   }
=20
   // Now make the MCDwarfFile entry and place it in the slot in the MCDwar=
fFiles
   // vector.
-  char *Buf =3D static_cast<char *>(Allocate(Name.size()));
-  memcpy(Buf, Name.data(), Name.size());
-  File =3D new (*this) MCDwarfFile(StringRef(Buf, Name.size()), DirIndex);
+  char *Buf =3D static_cast<char *>(Allocate(FileName.size()));
+  memcpy(Buf, FileName.data(), FileName.size());
+  File =3D new (*this) MCDwarfFile(StringRef(Buf, FileName.size()), DirInd=
ex);
=20
   // return the allocated FileNumber.
   return FileNumber;
@@ -314,3 +324,19 @@
=20
   return MCDwarfFiles[FileNumber] !=3D 0;
 }
+
+void MCContext::FatalError(SMLoc Loc, const Twine &Msg) {
+  // If we have a source manager and a location, use it. Otherwise just
+  // use the generic report_fatal_error().
+  if (!SrcMgr || Loc =3D=3D SMLoc())
+    report_fatal_error(Msg);
+
+  // Use the source manager to print the message.
+  SrcMgr->PrintMessage(Loc, SourceMgr::DK_Error, Msg);
+
+  // If we reached here, we are failing ungracefully. Run the interrupt ha=
ndlers
+  // to make sure any special cleanups get done, in particular that we rem=
ove
+  // files registered with RemoveFileOnSignal.
+  sys::RunInterruptHandlers();
+  exit(1);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCDisassemble=
r/Disassembler.cpp
--- a/head/contrib/llvm/lib/MC/MCDisassembler/Disassembler.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCDisassembler/Disassembler.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,10 +15,13 @@
 #include "llvm/MC/MCDisassembler.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCInstPrinter.h"
+#include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCRegisterInfo.h"
+#include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/Support/MemoryObject.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/TargetSelect.h"
+#include "llvm/Support/ErrorHandling.h"
=20
 namespace llvm {
 class Target;
@@ -36,6 +39,12 @@
                                       int TagType, LLVMOpInfoCallback GetO=
pInfo,
                                       LLVMSymbolLookupCallback SymbolLookU=
p) {
   // Initialize targets and assembly printers/parsers.
+  // FIXME: Clients are responsible for initializing the targets. And this
+  // would be done by calling routines in "llvm-c/Target.h" which are stat=
ic
+  // line functions. But the current use of LLVMCreateDisasm() is to dynam=
ically
+  // load libLTO with dlopen() and then lookup the symbols using dlsym().
+  // And since these initialize routines are static that does not work whi=
ch
+  // is why the call to them in this 'C' library API was added back.
   llvm::InitializeAllTargetInfos();
   llvm::InitializeAllTargetMCs();
   llvm::InitializeAllAsmParsers();
@@ -50,6 +59,9 @@
   const MCAsmInfo *MAI =3D TheTarget->createMCAsmInfo(TripleName);
   assert(MAI && "Unable to create target asm info!");
=20
+  const MCInstrInfo *MII =3D TheTarget->createMCInstrInfo();
+  assert(MII && "Unable to create target instruction info!");
+
   const MCRegisterInfo *MRI =3D TheTarget->createMCRegInfo(TripleName);
   assert(MRI && "Unable to create target register info!");
=20
@@ -73,13 +85,13 @@
   // Set up the instruction printer.
   int AsmPrinterVariant =3D MAI->getAssemblerDialect();
   MCInstPrinter *IP =3D TheTarget->createMCInstPrinter(AsmPrinterVariant,
-                                                     *MAI, *STI);
+                                                     *MAI, *MII, *MRI, *ST=
I);
   assert(IP && "Unable to create instruction printer!");
=20
   LLVMDisasmContext *DC =3D new LLVMDisasmContext(TripleName, DisInfo, Tag=
Type,
                                                 GetOpInfo, SymbolLookUp,
                                                 TheTarget, MAI, MRI,
-                                                Ctx, DisAsm, IP);
+                                                STI, MII, Ctx, DisAsm, IP);
   assert(DC && "Allocation failure!");
=20
   return DC;
@@ -170,5 +182,5 @@
     return Size;
   }
   }
-  return 0;
+  llvm_unreachable("Invalid DecodeStatus!");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCDisassemble=
r/Disassembler.h
--- a/head/contrib/llvm/lib/MC/MCDisassembler/Disassembler.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCDisassembler/Disassembler.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -28,7 +28,9 @@
 class MCAsmInfo;
 class MCDisassembler;
 class MCInstPrinter;=20
+class MCInstrInfo;
 class MCRegisterInfo;
+class MCSubtargetInfo;
 class Target;
=20
 //
@@ -61,6 +63,10 @@
   llvm::OwningPtr<const llvm::MCAsmInfo> MAI;
   // The register information for the target architecture.
   llvm::OwningPtr<const llvm::MCRegisterInfo> MRI;
+  // The subtarget information for the target architecture.
+  llvm::OwningPtr<const llvm::MCSubtargetInfo> MSI;
+  // The instruction information for the target architecture.
+  llvm::OwningPtr<const llvm::MCInstrInfo> MII;
   // The assembly context for creating symbols and MCExprs.
   llvm::OwningPtr<const llvm::MCContext> Ctx;
   // The disassembler for the target architecture.
@@ -78,6 +84,8 @@
                     LLVMSymbolLookupCallback symbolLookUp,
                     const Target *theTarget, const MCAsmInfo *mAI,
                     const MCRegisterInfo *mRI,
+                    const MCSubtargetInfo *mSI,
+                    const MCInstrInfo *mII,
                     llvm::MCContext *ctx, const MCDisassembler *disAsm,
                     MCInstPrinter *iP) : TripleName(tripleName),
                     DisInfo(disInfo), TagType(tagType), GetOpInfo(getOpInf=
o),
@@ -85,6 +93,8 @@
                     CommentStream(CommentsToEmit) {
     MAI.reset(mAI);
     MRI.reset(mRI);
+    MSI.reset(mSI);
+    MII.reset(mII);
     Ctx.reset(ctx);
     DisAsm.reset(disAsm);
     IP.reset(iP);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCDisassemble=
r/EDDisassembler.cpp
--- a/head/contrib/llvm/lib/MC/MCDisassembler/EDDisassembler.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCDisassembler/EDDisassembler.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -22,6 +22,7 @@
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCInstPrinter.h"
+#include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSubtargetInfo.h"
@@ -34,10 +35,8 @@
 #include "llvm/Support/MemoryObject.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
-#include "llvm/Support/TargetSelect.h"
 using namespace llvm;
=20
-bool EDDisassembler::sInitialized =3D false;
 EDDisassembler::DisassemblerMap_t EDDisassembler::sDisassemblers;
=20
 struct TripleMap {
@@ -49,8 +48,7 @@
   { Triple::x86,          "i386-unknown-unknown"    },
   { Triple::x86_64,       "x86_64-unknown-unknown"  },
   { Triple::arm,          "arm-unknown-unknown"     },
-  { Triple::thumb,        "thumb-unknown-unknown"   },
-  { Triple::InvalidArch,  NULL,                     }
+  { Triple::thumb,        "thumb-unknown-unknown"   }
 };
=20
 /// infoFromArch - Returns the TripleMap corresponding to a given architec=
ture,
@@ -77,90 +75,69 @@
 static int getLLVMSyntaxVariant(Triple::ArchType arch,
                                 EDDisassembler::AssemblySyntax syntax) {
   switch (syntax) {
-  default:
-    return -1;
   // Mappings below from X86AsmPrinter.cpp
   case EDDisassembler::kEDAssemblySyntaxX86ATT:
     if (arch =3D=3D Triple::x86 || arch =3D=3D Triple::x86_64)
       return 0;
-    else
-      return -1;
+    break;
   case EDDisassembler::kEDAssemblySyntaxX86Intel:
     if (arch =3D=3D Triple::x86 || arch =3D=3D Triple::x86_64)
       return 1;
-    else
-      return -1;
+    break;
   case EDDisassembler::kEDAssemblySyntaxARMUAL:
     if (arch =3D=3D Triple::arm || arch =3D=3D Triple::thumb)
       return 0;
-    else
-      return -1;
+    break;
   }
+
+  return -1;
 }
=20
-void EDDisassembler::initialize() {
-  if (sInitialized)
-    return;
- =20
-  sInitialized =3D true;
- =20
-  InitializeAllTargetInfos();
-  InitializeAllTargetMCs();
-  InitializeAllAsmParsers();
-  InitializeAllDisassemblers();
-}
-
-#undef BRINGUP_TARGET
-
 EDDisassembler *EDDisassembler::getDisassembler(Triple::ArchType arch,
                                                 AssemblySyntax syntax) {
-  CPUKey key;
-  key.Arch =3D arch;
-  key.Syntax =3D syntax;
- =20
-  EDDisassembler::DisassemblerMap_t::iterator i =3D sDisassemblers.find(ke=
y);
- =20
-  if (i !=3D sDisassemblers.end()) {
-    return i->second;
-  } else {
-    EDDisassembler* sdd =3D new EDDisassembler(key);
-    if (!sdd->valid()) {
-      delete sdd;
-      return NULL;
-    }
-   =20
-    sDisassemblers[key] =3D sdd;
-   =20
-    return sdd;
-  }
- =20
-  return NULL;
+  const char *triple =3D tripleFromArch(arch);
+  return getDisassembler(StringRef(triple), syntax);
 }
=20
 EDDisassembler *EDDisassembler::getDisassembler(StringRef str,
                                                 AssemblySyntax syntax) {
-  return getDisassembler(Triple(str).getArch(), syntax);
+  CPUKey key;
+  key.Triple =3D str.str();
+  key.Syntax =3D syntax;
+
+  EDDisassembler::DisassemblerMap_t::iterator i =3D sDisassemblers.find(ke=
y);
+
+  if (i !=3D sDisassemblers.end()) {
+    return i->second; =20
+  }
+
+  EDDisassembler *sdd =3D new EDDisassembler(key);
+  if (!sdd->valid()) {
+    delete sdd;
+    return NULL;
+  }
+
+  sDisassemblers[key] =3D sdd;
+
+  return sdd;
 }
=20
 EDDisassembler::EDDisassembler(CPUKey &key) :=20
   Valid(false),=20
   HasSemantics(false),=20
   ErrorStream(nulls()),=20
-  Key(key) {
-  const char *triple =3D tripleFromArch(key.Arch);
-   =20
-  if (!triple)
-    return;
+  Key(key),
+  TgtTriple(key.Triple.c_str()) {       =20
  =20
-  LLVMSyntaxVariant =3D getLLVMSyntaxVariant(key.Arch, key.Syntax);
+  LLVMSyntaxVariant =3D getLLVMSyntaxVariant(TgtTriple.getArch(), key.Synt=
ax);
  =20
   if (LLVMSyntaxVariant < 0)
     return;
  =20
-  std::string tripleString(triple);
+  std::string tripleString(key.Triple);
   std::string errorString;
  =20
-  Tgt =3D TargetRegistry::lookupTarget(tripleString,=20
+  Tgt =3D TargetRegistry::lookupTarget(key.Triple,=20
                                      errorString);
  =20
   if (!Tgt)
@@ -189,10 +166,16 @@
     return;
    =20
   InstInfos =3D Disassembler->getEDInfo();
- =20
+
+  MII.reset(Tgt->createMCInstrInfo());
+
+  if (!MII)
+    return;
+
   InstString.reset(new std::string);
   InstStream.reset(new raw_string_ostream(*InstString));
-  InstPrinter.reset(Tgt->createMCInstPrinter(LLVMSyntaxVariant, *AsmInfo, =
*STI));
+  InstPrinter.reset(Tgt->createMCInstPrinter(LLVMSyntaxVariant, *AsmInfo,
+                                             *MII, *MRI, *STI));
  =20
   if (!InstPrinter)
     return;
@@ -279,7 +262,7 @@
     RegRMap[registerName] =3D registerIndex;
   }
  =20
-  switch (Key.Arch) {
+  switch (TgtTriple.getArch()) {
   default:
     break;
   case Triple::x86:
@@ -337,13 +320,9 @@
   return 0;
 }
=20
-static void diag_handler(const SMDiagnostic &diag,
-                         void *context)
-{
-  if (context) {
-    EDDisassembler *disassembler =3D static_cast<EDDisassembler*>(context);
-    diag.Print("", disassembler->ErrorStream);
-  }
+static void diag_handler(const SMDiagnostic &diag, void *context) {
+  if (context)
+    diag.print("", static_cast<EDDisassembler*>(context)->ErrorStream);
 }
=20
 int EDDisassembler::parseInst(SmallVectorImpl<MCParsedAsmOperand*> &operan=
ds,
@@ -351,7 +330,7 @@
                               const std::string &str) {
   int ret =3D 0;
  =20
-  switch (Key.Arch) {
+  switch (TgtTriple.getArch()) {
   default:
     return -1;
   case Triple::x86:
@@ -376,8 +355,7 @@
                                                          context, *streame=
r,
                                                          *AsmInfo));
=20
-  StringRef triple =3D tripleFromArch(Key.Arch);
-  OwningPtr<MCSubtargetInfo> STI(Tgt->createMCSubtargetInfo(triple, "", ""=
));
+  OwningPtr<MCSubtargetInfo> STI(Tgt->createMCSubtargetInfo(Key.Triple.c_s=
tr(), "", ""));
   OwningPtr<MCTargetAsmParser>
     TargetParser(Tgt->createMCAsmParser(*STI, *genericParser));
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCDisassemble=
r/EDDisassembler.h
--- a/head/contrib/llvm/lib/MC/MCDisassembler/EDDisassembler.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCDisassembler/EDDisassembler.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -25,6 +25,7 @@
=20
 #include <map>
 #include <set>
+#include <string>
 #include <vector>
=20
 namespace llvm {
@@ -35,8 +36,9 @@
 class MCAsmInfo;
 class MCAsmLexer;
 class MCDisassembler;
+class MCInst;
 class MCInstPrinter;
-class MCInst;
+class MCInstrInfo;
 class MCParsedAsmOperand;
 class MCRegisterInfo;
 class MCStreamer;
@@ -74,28 +76,26 @@
   ///   pair
   struct CPUKey {
     /// The architecture type
-    llvm::Triple::ArchType Arch;
+    std::string Triple;
    =20
     /// The assembly syntax
     AssemblySyntax Syntax;
    =20
     /// operator=3D=3D - Equality operator
     bool operator=3D=3D(const CPUKey &key) const {
-      return (Arch =3D=3D key.Arch &&
+      return (Triple =3D=3D key.Triple &&
               Syntax =3D=3D key.Syntax);
     }
    =20
     /// operator< - Less-than operator
     bool operator<(const CPUKey &key) const {
-      return ((Arch < key.Arch) ||
-              ((Arch =3D=3D key.Arch) && Syntax < (key.Syntax)));
+      return ((Triple < key.Triple) ||
+              ((Triple =3D=3D key.Triple) && Syntax < (key.Syntax)));
     }
   };
  =20
   typedef std::map<CPUKey, EDDisassembler*> DisassemblerMap_t;
  =20
-  /// True if the disassembler registry has been initialized; false if not
-  static bool sInitialized;
   /// A map from disassembler specifications to disassemblers.  Populated
   ///   lazily.
   static DisassemblerMap_t sDisassemblers;
@@ -116,9 +116,6 @@
   static EDDisassembler *getDisassembler(llvm::StringRef str,
                                          AssemblySyntax syntax);
  =20
-  /// initialize - Initializes the disassembler registry and the LLVM back=
end
-  static void initialize();
- =20
   ////////////////////////
   // Per-object members //
   ////////////////////////
@@ -131,14 +128,18 @@
   /// The stream to write errors to
   llvm::raw_ostream &ErrorStream;
=20
-  /// The architecture/syntax pair for the current architecture
+  /// The triple/syntax pair for the current architecture
   CPUKey Key;
+  /// The Triple fur the current architecture
+  Triple TgtTriple;
   /// The LLVM target corresponding to the disassembler
   const llvm::Target *Tgt;
   /// The assembly information for the target architecture
   llvm::OwningPtr<const llvm::MCAsmInfo> AsmInfo;
   /// The subtarget information for the target architecture
   llvm::OwningPtr<const llvm::MCSubtargetInfo> STI;
+  // The instruction information for the target architecture.
+  llvm::OwningPtr<const llvm::MCInstrInfo> MII;
   // The register information for the target architecture.
   llvm::OwningPtr<const llvm::MCRegisterInfo> MRI;
   /// The disassembler for the target architecture
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCDisassemble=
r/EDOperand.cpp
--- a/head/contrib/llvm/lib/MC/MCDisassembler/EDOperand.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCDisassembler/EDOperand.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -30,8 +30,10 @@
   MCOpIndex(mcOpIndex) {
   unsigned int numMCOperands =3D 0;
    =20
-  if (Disassembler.Key.Arch =3D=3D Triple::x86 ||
-      Disassembler.Key.Arch =3D=3D Triple::x86_64) {
+  Triple::ArchType arch =3D Disassembler.TgtTriple.getArch();
+   =20
+  if (arch =3D=3D Triple::x86 ||
+      arch =3D=3D Triple::x86_64) {
     uint8_t operandType =3D inst.ThisInstInfo->operandTypes[opIndex];
    =20
     switch (operandType) {
@@ -54,8 +56,8 @@
       break;
     }
   }
-  else if (Disassembler.Key.Arch =3D=3D Triple::arm ||
-           Disassembler.Key.Arch =3D=3D Triple::thumb) {
+  else if (arch =3D=3D Triple::arm ||
+           arch =3D=3D Triple::thumb) {
     uint8_t operandType =3D inst.ThisInstInfo->operandTypes[opIndex];
    =20
     switch (operandType) {
@@ -126,7 +128,9 @@
                         void *arg) {
   uint8_t operandType =3D Inst.ThisInstInfo->operandTypes[OpIndex];
  =20
-  switch (Disassembler.Key.Arch) {
+  Triple::ArchType arch =3D Disassembler.TgtTriple.getArch();
+ =20
+  switch (arch) {
   default:
     return -1; =20
   case Triple::x86:
@@ -168,7 +172,7 @@
        =20
       unsigned segmentReg =3D Inst.Inst->getOperand(MCOpIndex+4).getReg();
        =20
-      if (segmentReg !=3D 0 && Disassembler.Key.Arch =3D=3D Triple::x86_64=
) {
+      if (segmentReg !=3D 0 && arch =3D=3D Triple::x86_64) {
         unsigned fsID =3D Disassembler.registerIDWithName("FS");
         unsigned gsID =3D Disassembler.registerIDWithName("GS");
        =20
@@ -200,7 +204,6 @@
       return 0;
     }
     } // switch (operandType)
-    break;
   case Triple::arm:
   case Triple::thumb:
     switch (operandType) {
@@ -236,10 +239,7 @@
       return 0;
     }
     }
-    break;
   }
- =20
-  return -1;
 }
=20
 int EDOperand::isRegister() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCDwarf.cpp
--- a/head/contrib/llvm/lib/MC/MCDwarf.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCDwarf.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -19,10 +19,12 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/FoldingSet.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/SourceMgr.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/Twine.h"
+#include "llvm/Config/config.h"
 using namespace llvm;
=20
 // Given a special op, return the address skip amount (in units of
@@ -207,7 +209,7 @@
 //
 // This emits the Dwarf file and the line tables.
 //
-void MCDwarfFileTable::Emit(MCStreamer *MCOS) {
+const MCSymbol *MCDwarfFileTable::Emit(MCStreamer *MCOS) {
   MCContext &context =3D MCOS->getContext();
   // Switch to the section where the table will be emitted into.
   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
@@ -320,6 +322,8 @@
   // This is the end of the section, so set the value of the symbol at the=
 end
   // of this section (that was used in a previous expression).
   MCOS->EmitLabel(LineEndSym);
+
+  return LineStartSym;
 }
=20
 /// Utility function to write the encoding to an object writer.
@@ -372,10 +376,7 @@
   // it with DW_LNS_advance_line.
   if (Temp >=3D DWARF2_LINE_RANGE) {
     OS << char(dwarf::DW_LNS_advance_line);
-    SmallString<32> Tmp;
-    raw_svector_ostream OSE(Tmp);
-    MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
-    OS << OSE.str();
+    MCObjectWriter::EncodeSLEB128(LineDelta, OS);
=20
     LineDelta =3D 0;
     Temp =3D 0 - DWARF2_LINE_BASE;
@@ -411,10 +412,7 @@
=20
   // Otherwise use DW_LNS_advance_pc.
   OS << char(dwarf::DW_LNS_advance_pc);
-  SmallString<32> Tmp;
-  raw_svector_ostream OSE(Tmp);
-  MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
-  OS << OSE.str();
+  MCObjectWriter::EncodeULEB128(AddrDelta, OS);
=20
   if (NeedCopy)
     OS << char(dwarf::DW_LNS_copy);
@@ -430,6 +428,349 @@
   print(dbgs());
 }
=20
+// Utility function to write a tuple for .debug_abbrev.
+static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
+  MCOS->EmitULEB128IntValue(Name);
+  MCOS->EmitULEB128IntValue(Form);
+}
+
+// When generating dwarf for assembly source files this emits
+// the data for .debug_abbrev section which contains three DIEs.
+static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
+  MCContext &context =3D MCOS->getContext();
+  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()=
);
+
+  // DW_TAG_compile_unit DIE abbrev (1).
+  MCOS->EmitULEB128IntValue(1);
+  MCOS->EmitULEB128IntValue(dwarf::DW_TAG_compile_unit);
+  MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
+  EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4);
+  EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
+  EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
+  EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
+  EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
+  StringRef DwarfDebugFlags =3D context.getDwarfDebugFlags();
+  if (!DwarfDebugFlags.empty())
+    EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
+  EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
+  EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
+  EmitAbbrev(MCOS, 0, 0);
+
+  // DW_TAG_label DIE abbrev (2).
+  MCOS->EmitULEB128IntValue(2);
+  MCOS->EmitULEB128IntValue(dwarf::DW_TAG_label);
+  MCOS->EmitIntValue(dwarf::DW_CHILDREN_yes, 1);
+  EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
+  EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
+  EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
+  EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
+  EmitAbbrev(MCOS, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag);
+  EmitAbbrev(MCOS, 0, 0);
+
+  // DW_TAG_unspecified_parameters DIE abbrev (3).
+  MCOS->EmitULEB128IntValue(3);
+  MCOS->EmitULEB128IntValue(dwarf::DW_TAG_unspecified_parameters);
+  MCOS->EmitIntValue(dwarf::DW_CHILDREN_no, 1);
+  EmitAbbrev(MCOS, 0, 0);
+
+  // Terminate the abbreviations for this compilation unit.
+  MCOS->EmitIntValue(0, 1);
+}
+
+// When generating dwarf for assembly source files this emits the data for
+// .debug_aranges section.  Which contains a header and a table of pairs of
+// PointerSize'ed values for the address and size of section(s) with line =
table
+// entries (just the default .text in our case) and a terminating pair of =
zeros.
+static void EmitGenDwarfAranges(MCStreamer *MCOS) {
+  MCContext &context =3D MCOS->getContext();
+
+  // Create a symbol at the end of the section that we are creating the dw=
arf
+  // debugging info to use later in here as part of the expression to calc=
ulate
+  // the size of the section for the table.
+  MCOS->SwitchSection(context.getGenDwarfSection());
+  MCSymbol *SectionEndSym =3D context.CreateTempSymbol();
+  MCOS->EmitLabel(SectionEndSym);
+  context.setGenDwarfSectionEndSym(SectionEndSym);
+
+  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection(=
));
+
+  // This will be the length of the .debug_aranges section, first account =
for
+  // the size of each item in the header (see below where we emit these it=
ems).
+  int Length =3D 4 + 2 + 4 + 1 + 1;
+
+  // Figure the padding after the header before the table of address and s=
ize
+  // pairs who's values are PointerSize'ed.
+  const MCAsmInfo &asmInfo =3D context.getAsmInfo();
+  int AddrSize =3D asmInfo.getPointerSize();
+  int Pad =3D 2 * AddrSize - (Length & (2 * AddrSize - 1));
+  if (Pad =3D=3D 2 * AddrSize)
+    Pad =3D 0;
+  Length +=3D Pad;
+
+  // Add the size of the pair of PointerSize'ed values for the address and=
 size
+  // of the one default .text section we have in the table.
+  Length +=3D 2 * AddrSize;
+  // And the pair of terminating zeros.
+  Length +=3D 2 * AddrSize;
+
+
+  // Emit the header for this section.
+  // The 4 byte length not including the 4 byte value for the length.
+  MCOS->EmitIntValue(Length - 4, 4);
+  // The 2 byte version, which is 2.
+  MCOS->EmitIntValue(2, 2);
+  // The 4 byte offset to the compile unit in the .debug_info from the sta=
rt
+  // of the .debug_info, it is at the start of that section so this is zer=
o.
+  MCOS->EmitIntValue(0, 4);
+  // The 1 byte size of an address.
+  MCOS->EmitIntValue(AddrSize, 1);
+  // The 1 byte size of a segment descriptor, we use a value of zero.
+  MCOS->EmitIntValue(0, 1);
+  // Align the header with the padding if needed, before we put out the ta=
ble.
+  for(int i =3D 0; i < Pad; i++)
+    MCOS->EmitIntValue(0, 1);
+
+  // Now emit the table of pairs of PointerSize'ed values for the section(=
s)
+  // address and size, in our case just the one default .text section.
+  const MCExpr *Addr =3D MCSymbolRefExpr::Create(
+    context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, contex=
t);
+  const MCExpr *Size =3D MakeStartMinusEndExpr(*MCOS,
+    *context.getGenDwarfSectionStartSym(), *SectionEndSym, 0);
+  MCOS->EmitAbsValue(Addr, AddrSize);
+  MCOS->EmitAbsValue(Size, AddrSize);
+
+  // And finally the pair of terminating zeros.
+  MCOS->EmitIntValue(0, AddrSize);
+  MCOS->EmitIntValue(0, AddrSize);
+}
+
+// When generating dwarf for assembly source files this emits the data for
+// .debug_info section which contains three parts.  The header, the compil=
e_unit
+// DIE and a list of label DIEs.
+static void EmitGenDwarfInfo(MCStreamer *MCOS,
+                             const MCSymbol *AbbrevSectionSymbol,
+                             const MCSymbol *LineSectionSymbol) {
+  MCContext &context =3D MCOS->getContext();
+
+  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());=20
+
+  // Create a symbol at the start and end of this section used in here for=
 the
+  // expression to calculate the length in the header.
+  MCSymbol *InfoStart =3D context.CreateTempSymbol();
+  MCOS->EmitLabel(InfoStart);
+  MCSymbol *InfoEnd =3D context.CreateTempSymbol();
+
+  // First part: the header.
+
+  // The 4 byte total length of the information for this compilation unit,=
 not
+  // including these 4 bytes.
+  const MCExpr *Length =3D MakeStartMinusEndExpr(*MCOS, *InfoStart, *InfoE=
nd, 4);
+  MCOS->EmitAbsValue(Length, 4);
+
+  // The 2 byte DWARF version, which is 2.
+  MCOS->EmitIntValue(2, 2);
+
+  // The 4 byte offset to the debug abbrevs from the start of the .debug_a=
bbrev,
+  // it is at the start of that section so this is zero.
+  if (AbbrevSectionSymbol) {
+    MCOS->EmitSymbolValue(AbbrevSectionSymbol, 4);
+  } else {
+    MCOS->EmitIntValue(0, 4);
+  }
+
+  const MCAsmInfo &asmInfo =3D context.getAsmInfo();
+  int AddrSize =3D asmInfo.getPointerSize();
+  // The 1 byte size of an address.
+  MCOS->EmitIntValue(AddrSize, 1);
+
+  // Second part: the compile_unit DIE.
+
+  // The DW_TAG_compile_unit DIE abbrev (1).
+  MCOS->EmitULEB128IntValue(1);
+
+  // DW_AT_stmt_list, a 4 byte offset from the start of the .debug_line se=
ction,
+  // which is at the start of that section so this is zero.
+  if (LineSectionSymbol) {
+    MCOS->EmitSymbolValue(LineSectionSymbol, 4);
+  } else {
+    MCOS->EmitIntValue(0, 4);
+  }
+
+  // AT_low_pc, the first address of the default .text section.
+  const MCExpr *Start =3D MCSymbolRefExpr::Create(
+    context.getGenDwarfSectionStartSym(), MCSymbolRefExpr::VK_None, contex=
t);
+  MCOS->EmitAbsValue(Start, AddrSize);
+
+  // AT_high_pc, the last address of the default .text section.
+  const MCExpr *End =3D MCSymbolRefExpr::Create(
+    context.getGenDwarfSectionEndSym(), MCSymbolRefExpr::VK_None, context);
+  MCOS->EmitAbsValue(End, AddrSize);
+
+  // AT_name, the name of the source file.  Reconstruct from the first dir=
ectory
+  // and file table entries.
+  const std::vector<StringRef> &MCDwarfDirs =3D
+    context.getMCDwarfDirs();
+  if (MCDwarfDirs.size() > 0) {
+    MCOS->EmitBytes(MCDwarfDirs[0], 0);
+    MCOS->EmitBytes("/", 0);
+  }
+  const std::vector<MCDwarfFile *> &MCDwarfFiles =3D
+    MCOS->getContext().getMCDwarfFiles();
+  MCOS->EmitBytes(MCDwarfFiles[1]->getName(), 0);
+  MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
+
+  // AT_comp_dir, the working directory the assembly was done in.
+  llvm::sys::Path CWD =3D llvm::sys::Path::GetCurrentDirectory();
+  MCOS->EmitBytes(StringRef(CWD.c_str()), 0);
+  MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
+
+  // AT_APPLE_flags, the command line arguments of the assembler tool.
+  StringRef DwarfDebugFlags =3D context.getDwarfDebugFlags();
+  if (!DwarfDebugFlags.empty()){
+    MCOS->EmitBytes(DwarfDebugFlags, 0);
+    MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
+  }
+
+  // AT_producer, the version of the assembler tool.
+  MCOS->EmitBytes(StringRef("llvm-mc (based on LLVM "), 0);
+  MCOS->EmitBytes(StringRef(PACKAGE_VERSION), 0);
+  MCOS->EmitBytes(StringRef(")"), 0);
+  MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
+
+  // AT_language, a 4 byte value.  We use DW_LANG_Mips_Assembler as the dw=
arf2
+  // draft has no standard code for assembler.
+  MCOS->EmitIntValue(dwarf::DW_LANG_Mips_Assembler, 2);
+
+  // Third part: the list of label DIEs.
+
+  // Loop on saved info for dwarf labels and create the DIEs for them.
+  const std::vector<const MCGenDwarfLabelEntry *> &Entries =3D
+    MCOS->getContext().getMCGenDwarfLabelEntries();
+  for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =3D
+       Entries.begin(), ie =3D Entries.end(); it !=3D ie;
+       ++it) {
+    const MCGenDwarfLabelEntry *Entry =3D *it;
+
+    // The DW_TAG_label DIE abbrev (2).
+    MCOS->EmitULEB128IntValue(2);
+
+    // AT_name, of the label without any leading underbar.
+    MCOS->EmitBytes(Entry->getName(), 0);
+    MCOS->EmitIntValue(0, 1); // NULL byte to terminate the string.
+
+    // AT_decl_file, index into the file table.
+    MCOS->EmitIntValue(Entry->getFileNumber(), 4);
+
+    // AT_decl_line, source line number.
+    MCOS->EmitIntValue(Entry->getLineNumber(), 4);
+
+    // AT_low_pc, start address of the label.
+    const MCExpr *AT_low_pc =3D MCSymbolRefExpr::Create(Entry->getLabel(),
+                                             MCSymbolRefExpr::VK_None, con=
text);
+    MCOS->EmitAbsValue(AT_low_pc, AddrSize);
+
+    // DW_AT_prototyped, a one byte flag value of 0 saying we have no prot=
otype.
+    MCOS->EmitIntValue(0, 1);
+
+    // The DW_TAG_unspecified_parameters DIE abbrev (3).
+    MCOS->EmitULEB128IntValue(3);
+
+    // Add the NULL DIE terminating the DW_TAG_unspecified_parameters DIE'=
s.
+    MCOS->EmitIntValue(0, 1);
+  }
+  // Deallocate the MCGenDwarfLabelEntry classes that saved away the info
+  // for the dwarf labels.
+  for (std::vector<const MCGenDwarfLabelEntry *>::const_iterator it =3D
+       Entries.begin(), ie =3D Entries.end(); it !=3D ie;
+       ++it) {
+    const MCGenDwarfLabelEntry *Entry =3D *it;
+    delete Entry;
+  }
+
+  // Add the NULL DIE terminating the Compile Unit DIE's.
+  MCOS->EmitIntValue(0, 1);
+
+  // Now set the value of the symbol at the end of the info section.
+  MCOS->EmitLabel(InfoEnd);
+}
+
+//
+// When generating dwarf for assembly source files this emits the Dwarf
+// sections.
+//
+void MCGenDwarfInfo::Emit(MCStreamer *MCOS, const MCSymbol *LineSectionSym=
bol) {
+  // Create the dwarf sections in this order (.debug_line already created).
+  MCContext &context =3D MCOS->getContext();
+  const MCAsmInfo &AsmInfo =3D context.getAsmInfo();
+  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
+  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection()=
);
+  MCSymbol *AbbrevSectionSymbol;
+  if (AsmInfo.doesDwarfRequireRelocationForSectionOffset()) {
+    AbbrevSectionSymbol =3D context.CreateTempSymbol();
+    MCOS->EmitLabel(AbbrevSectionSymbol);
+  } else {
+    AbbrevSectionSymbol =3D NULL;
+    LineSectionSymbol =3D NULL;
+  }
+  MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection(=
));
+
+  // If there are no line table entries then do not emit any section conte=
nts.
+  if (context.getMCLineSections().empty())
+    return;
+
+  // Output the data for .debug_aranges section.
+  EmitGenDwarfAranges(MCOS);
+
+  // Output the data for .debug_abbrev section.
+  EmitGenDwarfAbbrev(MCOS);
+
+  // Output the data for .debug_info section.
+  EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol);
+}
+
+//
+// When generating dwarf for assembly source files this is called when sym=
bol
+// for a label is created.  If this symbol is not a temporary and is in the
+// section that dwarf is being generated for, save the needed info to crea=
te
+// a dwarf label.
+//
+void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
+                                     SourceMgr &SrcMgr, SMLoc &Loc) {
+  // We won't create dwarf labels for temporary symbols or symbols not in
+  // the default text.
+  if (Symbol->isTemporary())
+    return;
+  MCContext &context =3D MCOS->getContext();
+  if (context.getGenDwarfSection() !=3D MCOS->getCurrentSection())
+    return;
+
+  // The dwarf label's name does not have the symbol name's leading
+  // underbar if any.
+  StringRef Name =3D Symbol->getName();
+  if (Name.startswith("_"))
+    Name =3D Name.substr(1, Name.size()-1);
+
+  // Get the dwarf file number to be used for the dwarf label.
+  unsigned FileNumber =3D context.getGenDwarfFileNumber();
+
+  // Finding the line number is the expensive part which is why we just do=
n't
+  // pass it in as for some symbols we won't create a dwarf label.
+  int CurBuffer =3D SrcMgr.FindBufferContainingLoc(Loc);
+  unsigned LineNumber =3D SrcMgr.FindLineNumber(Loc, CurBuffer);
+
+  // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
+  // values so that they don't have things like an ARM thumb bit from the
+  // original symbol. So when used they won't get a low bit set after
+  // relocation.
+  MCSymbol *Label =3D context.CreateTempSymbol();
+  MCOS->EmitLabel(Label);
+
+  // Create and entry for the info and add it to the other entries.
+  MCGenDwarfLabelEntry *Entry =3D=20
+    new MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label);
+  MCOS->getContext().addMCGenDwarfLabelEntry(Entry);
+}
+
 static int getDataAlignmentFactor(MCStreamer &streamer) {
   MCContext &context =3D streamer.getContext();
   const MCAsmInfo &asmInfo =3D context.getAsmInfo();
@@ -445,8 +786,7 @@
   MCContext &context =3D streamer.getContext();
   unsigned format =3D symbolEncoding & 0x0f;
   switch (format) {
-  default:
-    assert(0 && "Unknown Encoding");
+  default: llvm_unreachable("Unknown Encoding");
   case dwarf::DW_EH_PE_absptr:
   case dwarf::DW_EH_PE_signed:
     return context.getAsmInfo().getPointerSize();
@@ -520,6 +860,7 @@
                             const MCSymbol *personality,
                             unsigned personalityEncoding,
                             const MCSymbol *lsda,
+                            bool IsSignalFrame,
                             unsigned lsdaEncoding);
     MCSymbol *EmitFDE(MCStreamer &streamer,
                       const MCSymbol &cieStart,
@@ -536,28 +877,40 @@
 static void EmitEncodingByte(MCStreamer &Streamer, unsigned Encoding,
                              StringRef Prefix) {
   if (Streamer.isVerboseAsm()) {
-    const char *EncStr =3D 0;
+    const char *EncStr;
     switch (Encoding) {
-    default: EncStr =3D "<unknown encoding>";
-    case dwarf::DW_EH_PE_absptr: EncStr =3D "absptr";
-    case dwarf::DW_EH_PE_omit:   EncStr =3D "omit";
-    case dwarf::DW_EH_PE_pcrel:  EncStr =3D "pcrel";
-    case dwarf::DW_EH_PE_udata4: EncStr =3D "udata4";
-    case dwarf::DW_EH_PE_udata8: EncStr =3D "udata8";
-    case dwarf::DW_EH_PE_sdata4: EncStr =3D "sdata4";
-    case dwarf::DW_EH_PE_sdata8: EncStr =3D "sdata8";
-    case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: EncStr =3D "pcrel =
udata4";
-    case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: EncStr =3D "pcrel =
sdata4";
-    case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: EncStr =3D "pcrel =
udata8";
-    case dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: EncStr =3D "pcrel =
sdata8";
+    default: EncStr =3D "<unknown encoding>"; break;
+    case dwarf::DW_EH_PE_absptr: EncStr =3D "absptr"; break;
+    case dwarf::DW_EH_PE_omit:   EncStr =3D "omit"; break;
+    case dwarf::DW_EH_PE_pcrel:  EncStr =3D "pcrel"; break;
+    case dwarf::DW_EH_PE_udata4: EncStr =3D "udata4"; break;
+    case dwarf::DW_EH_PE_udata8: EncStr =3D "udata8"; break;
+    case dwarf::DW_EH_PE_sdata4: EncStr =3D "sdata4"; break;
+    case dwarf::DW_EH_PE_sdata8: EncStr =3D "sdata8"; break;
+    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
+      EncStr =3D "pcrel udata4";
+      break;
+    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
+      EncStr =3D "pcrel sdata4";
+      break;
+    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
+      EncStr =3D "pcrel udata8";
+      break;
+    case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
+      EncStr =3D "screl sdata8";
+      break;
     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_u=
data4:
       EncStr =3D "indirect pcrel udata4";
+      break;
     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_s=
data4:
       EncStr =3D "indirect pcrel sdata4";
+      break;
     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_u=
data8:
       EncStr =3D "indirect pcrel udata8";
+      break;
     case dwarf::DW_EH_PE_indirect |dwarf::DW_EH_PE_pcrel|dwarf::DW_EH_PE_s=
data8:
       EncStr =3D "indirect pcrel sdata8";
+      break;
     }
=20
     Streamer.AddComment(Twine(Prefix) + " =3D " + EncStr);
@@ -639,11 +992,11 @@
     }
     return;
   }
-  case MCCFIInstruction::Remember:
+  case MCCFIInstruction::RememberState:
     if (VerboseAsm) Streamer.AddComment("DW_CFA_remember_state");
     Streamer.EmitIntValue(dwarf::DW_CFA_remember_state, 1);
     return;
-  case MCCFIInstruction::Restore:
+  case MCCFIInstruction::RestoreState:
     if (VerboseAsm) Streamer.AddComment("DW_CFA_restore_state");
     Streamer.EmitIntValue(dwarf::DW_CFA_restore_state, 1);
     return;
@@ -655,6 +1008,19 @@
     Streamer.EmitULEB128IntValue(Reg);
     return;
   }
+  case MCCFIInstruction::Restore: {
+    unsigned Reg =3D Instr.getDestination().getReg();
+    if (VerboseAsm) {
+      Streamer.AddComment("DW_CFA_restore");
+      Streamer.AddComment(Twine("Reg ") + Twine(Reg));
+    }
+    Streamer.EmitIntValue(dwarf::DW_CFA_restore | Reg, 1);
+    return;
+  }
+  case MCCFIInstruction::Escape:
+    if (VerboseAsm) Streamer.AddComment("Escape bytes");
+    Streamer.EmitBytes(Instr.getValues(), 0);
+    return;
   }
   llvm_unreachable("Unhandled case in switch");
 }
@@ -738,8 +1104,8 @@
=20
   // Compact Encoding
   Size =3D getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
-  if (VerboseAsm) Streamer.AddComment(Twine("Compact Unwind Encoding: 0x")=
 +
-                                      Twine(llvm::utohexstr(Encoding)));
+  if (VerboseAsm) Streamer.AddComment("Compact Unwind Encoding: 0x" +
+                                      Twine::utohexstr(Encoding));
   Streamer.EmitIntValue(Encoding, Size);
=20
=20
@@ -766,6 +1132,7 @@
                                           const MCSymbol *personality,
                                           unsigned personalityEncoding,
                                           const MCSymbol *lsda,
+                                          bool IsSignalFrame,
                                           unsigned lsdaEncoding) {
   MCContext &context =3D streamer.getContext();
   const MCRegisterInfo &MRI =3D context.getRegisterInfo();
@@ -808,6 +1175,8 @@
     if (lsda)
       Augmentation +=3D "L";
     Augmentation +=3D "R";
+    if (IsSignalFrame)
+      Augmentation +=3D "S";
     streamer.EmitBytes(Augmentation.str(), 0);
   }
   streamer.EmitIntValue(0, 1);
@@ -967,17 +1336,18 @@
=20
 namespace {
   struct CIEKey {
-    static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1); }
-    static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0); }
+    static const CIEKey getEmptyKey() { return CIEKey(0, 0, -1, false); }
+    static const CIEKey getTombstoneKey() { return CIEKey(0, -1, 0, false)=
; }
=20
     CIEKey(const MCSymbol* Personality_, unsigned PersonalityEncoding_,
-           unsigned LsdaEncoding_) : Personality(Personality_),
-                                     PersonalityEncoding(PersonalityEncodi=
ng_),
-                                     LsdaEncoding(LsdaEncoding_) {
+           unsigned LsdaEncoding_, bool IsSignalFrame_) :
+      Personality(Personality_), PersonalityEncoding(PersonalityEncoding_),
+      LsdaEncoding(LsdaEncoding_), IsSignalFrame(IsSignalFrame_) {
     }
     const MCSymbol* Personality;
     unsigned PersonalityEncoding;
     unsigned LsdaEncoding;
+    bool IsSignalFrame;
   };
 }
=20
@@ -991,17 +1361,17 @@
       return CIEKey::getTombstoneKey();
     }
     static unsigned getHashValue(const CIEKey &Key) {
-      FoldingSetNodeID ID;
-      ID.AddPointer(Key.Personality);
-      ID.AddInteger(Key.PersonalityEncoding);
-      ID.AddInteger(Key.LsdaEncoding);
-      return ID.ComputeHash();
+      return static_cast<unsigned>(hash_combine(Key.Personality,
+                                                Key.PersonalityEncoding,
+                                                Key.LsdaEncoding,
+                                                Key.IsSignalFrame));
     }
     static bool isEqual(const CIEKey &LHS,
                         const CIEKey &RHS) {
       return LHS.Personality =3D=3D RHS.Personality &&
         LHS.PersonalityEncoding =3D=3D RHS.PersonalityEncoding &&
-        LHS.LsdaEncoding =3D=3D RHS.LsdaEncoding;
+        LHS.LsdaEncoding =3D=3D RHS.LsdaEncoding &&
+        LHS.IsSignalFrame =3D=3D RHS.IsSignalFrame;
     }
   };
 }
@@ -1016,12 +1386,10 @@
   ArrayRef<MCDwarfFrameInfo> FrameArray =3D Streamer.getFrameInfos();
=20
   // Emit the compact unwind info if available.
-  // FIXME: This emits both the compact unwind and the old CIE/FDE
-  //        information. Only one of those is needed.
   if (IsEH && MOFI->getCompactUnwindSection())
     for (unsigned i =3D 0, n =3D Streamer.getNumFrameInfos(); i < n; ++i) {
       const MCDwarfFrameInfo &Frame =3D Streamer.getFrameInfo(i);
-      if (!Frame.CompactUnwindEncoding)
+      if (Frame.CompactUnwindEncoding)
         Emitter.EmitCompactUnwind(Streamer, Frame);
     }
=20
@@ -1039,11 +1407,12 @@
   for (unsigned i =3D 0, n =3D FrameArray.size(); i < n; ++i) {
     const MCDwarfFrameInfo &Frame =3D FrameArray[i];
     CIEKey Key(Frame.Personality, Frame.PersonalityEncoding,
-               Frame.LsdaEncoding);
+               Frame.LsdaEncoding, Frame.IsSignalFrame);
     const MCSymbol *&CIEStart =3D IsEH ? CIEStarts[Key] : DummyDebugKey;
     if (!CIEStart)
       CIEStart =3D &Emitter.EmitCIE(Streamer, Frame.Personality,
                                   Frame.PersonalityEncoding, Frame.Lsda,
+                                  Frame.IsSignalFrame,
                                   Frame.LsdaEncoding);
=20
     FDEEnd =3D Emitter.EmitFDE(Streamer, *CIEStart, Frame);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCELF.cpp
--- a/head/contrib/llvm/lib/MC/MCELF.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCELF.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -37,7 +37,7 @@
   assert(Type =3D=3D ELF::STT_NOTYPE || Type =3D=3D ELF::STT_OBJECT ||
          Type =3D=3D ELF::STT_FUNC || Type =3D=3D ELF::STT_SECTION ||
          Type =3D=3D ELF::STT_FILE || Type =3D=3D ELF::STT_COMMON ||
-         Type =3D=3D ELF::STT_TLS);
+         Type =3D=3D ELF::STT_TLS || Type =3D=3D ELF::STT_GNU_IFUNC);
=20
   uint32_t OtherFlags =3D SD.getFlags() & ~(0xf << ELF_STT_Shift);
   SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
@@ -48,7 +48,7 @@
   assert(Type =3D=3D ELF::STT_NOTYPE || Type =3D=3D ELF::STT_OBJECT ||
          Type =3D=3D ELF::STT_FUNC || Type =3D=3D ELF::STT_SECTION ||
          Type =3D=3D ELF::STT_FILE || Type =3D=3D ELF::STT_COMMON ||
-         Type =3D=3D ELF::STT_TLS);
+         Type =3D=3D ELF::STT_TLS || Type =3D=3D ELF::STT_GNU_IFUNC);
   return Type;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCELFObjectTa=
rgetWriter.cpp
--- a/head/contrib/llvm/lib/MC/MCELFObjectTargetWriter.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCELFObjectTargetWriter.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -7,17 +7,40 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/MC/MCELFObjectWriter.h"
=20
 using namespace llvm;
=20
 MCELFObjectTargetWriter::MCELFObjectTargetWriter(bool Is64Bit_,
-                                                 Triple::OSType OSType_,
+                                                 uint8_t OSABI_,
                                                  uint16_t EMachine_,
                                                  bool HasRelocationAddend_)
-  : OSType(OSType_), EMachine(EMachine_),
+  : OSABI(OSABI_), EMachine(EMachine_),
     HasRelocationAddend(HasRelocationAddend_), Is64Bit(Is64Bit_) {
 }
=20
-MCELFObjectTargetWriter::~MCELFObjectTargetWriter() {
+/// Default e_flags =3D 0
+unsigned MCELFObjectTargetWriter::getEFlags() const {
+  return 0;
 }
+
+const MCSymbol *MCELFObjectTargetWriter::ExplicitRelSym(const MCAssembler =
&Asm,
+                                                        const MCValue &Tar=
get,
+                                                        const MCFragment &=
F,
+                                                        const MCFixup &Fix=
up,
+                                                        bool IsPCRel) cons=
t {
+  return NULL;
+}
+
+
+void MCELFObjectTargetWriter::adjustFixupOffset(const MCFixup &Fixup,
+                                                uint64_t &RelocOffset) {
+}
+
+void
+MCELFObjectTargetWriter::sortRelocs(const MCAssembler &Asm,
+                                    std::vector<ELFRelocationEntry> &Reloc=
s) {
+  // Sort by the r_offset, just like gnu as does.
+  array_pod_sort(Relocs.begin(), Relocs.end());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCELFStreamer=
.cpp
--- a/head/contrib/llvm/lib/MC/MCELFStreamer.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/MC/MCELFStreamer.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -11,13 +11,17 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "MCELFStreamer.h"
 #include "MCELF.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/MC/MCAssembler.h"
+#include "llvm/MC/MCCodeEmitter.h"
+#include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCSectionELF.h"
 #include "llvm/MC/MCStreamer.h"
-#include "llvm/MC/MCCodeEmitter.h"
 #include "llvm/MC/MCELFSymbolFlags.h"
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCObjectStreamer.h"
 #include "llvm/MC/MCSection.h"
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/MC/MCValue.h"
@@ -29,6 +33,123 @@
=20
 using namespace llvm;
=20
+namespace {
+class MCELFStreamer : public MCObjectStreamer {
+public:
+  MCELFStreamer(MCContext &Context, MCAsmBackend &TAB,
+                  raw_ostream &OS, MCCodeEmitter *Emitter)
+    : MCObjectStreamer(Context, TAB, OS, Emitter) {}
+
+  MCELFStreamer(MCContext &Context, MCAsmBackend &TAB,
+                raw_ostream &OS, MCCodeEmitter *Emitter,
+                MCAssembler *Assembler)
+    : MCObjectStreamer(Context, TAB, OS, Emitter, Assembler) {}
+
+
+  ~MCELFStreamer() {}
+
+  /// @name MCStreamer Interface
+  /// @{
+
+  virtual void InitSections();
+  virtual void ChangeSection(const MCSection *Section);
+  virtual void EmitLabel(MCSymbol *Symbol);
+  virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
+  virtual void EmitThumbFunc(MCSymbol *Func);
+  virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
+  virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
+  virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribut=
e);
+  virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
+    llvm_unreachable("ELF doesn't support this directive");
+  }
+  virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                unsigned ByteAlignment);
+  virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
+    llvm_unreachable("ELF doesn't support this directive");
+  }
+
+  virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
+    llvm_unreachable("ELF doesn't support this directive");
+  }
+
+  virtual void EmitCOFFSymbolType(int Type) {
+    llvm_unreachable("ELF doesn't support this directive");
+  }
+
+  virtual void EndCOFFSymbolDef() {
+    llvm_unreachable("ELF doesn't support this directive");
+  }
+
+  virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
+     MCSymbolData &SD =3D getAssembler().getOrCreateSymbolData(*Symbol);
+     SD.setSize(Value);
+  }
+
+  virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                     unsigned ByteAlignment);
+
+  virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol =3D=
 0,
+                            unsigned Size =3D 0, unsigned ByteAlignment =
=3D 0) {
+    llvm_unreachable("ELF doesn't support this directive");
+  }
+  virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
+                              uint64_t Size, unsigned ByteAlignment =3D 0)=
 {
+    llvm_unreachable("ELF doesn't support this directive");
+  }
+  virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
+  virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value =
=3D 0,
+                                    unsigned ValueSize =3D 1,
+                                    unsigned MaxBytesToEmit =3D 0);
+  virtual void EmitCodeAlignment(unsigned ByteAlignment,
+                                 unsigned MaxBytesToEmit =3D 0);
+  virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
+                             unsigned AddrSpace);
+
+  virtual void EmitFileDirective(StringRef Filename);
+
+  virtual void FinishImpl();
+
+private:
+  virtual void EmitInstToFragment(const MCInst &Inst);
+  virtual void EmitInstToData(const MCInst &Inst);
+
+  void fixSymbolsInTLSFixups(const MCExpr *expr);
+
+  struct LocalCommon {
+    MCSymbolData *SD;
+    uint64_t Size;
+    unsigned ByteAlignment;
+  };
+  std::vector<LocalCommon> LocalCommons;
+
+  SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
+  /// @}
+  void SetSection(StringRef Section, unsigned Type, unsigned Flags,
+                  SectionKind Kind) {
+    SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
+  }
+
+  void SetSectionData() {
+    SetSection(".data", ELF::SHT_PROGBITS,
+               ELF::SHF_WRITE |ELF::SHF_ALLOC,
+               SectionKind::getDataRel());
+    EmitCodeAlignment(4, 0);
+  }
+  void SetSectionText() {
+    SetSection(".text", ELF::SHT_PROGBITS,
+               ELF::SHF_EXECINSTR |
+               ELF::SHF_ALLOC, SectionKind::getText());
+    EmitCodeAlignment(4, 0);
+  }
+  void SetSectionBss() {
+    SetSection(".bss", ELF::SHT_NOBITS,
+               ELF::SHF_WRITE |
+               ELF::SHF_ALLOC, SectionKind::getBSS());
+    EmitCodeAlignment(4, 0);
+  }
+};
+}
+
 void MCELFStreamer::InitSections() {
   // This emulates the same behavior of GNU as. This makes it easier
   // to compare the output as the major sections are in the same order.
@@ -61,7 +182,7 @@
     return;
   }
=20
-  assert(0 && "invalid assembler flag!");
+  llvm_unreachable("invalid assembler flag!");
 }
=20
 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
@@ -130,10 +251,8 @@
   case MCSA_WeakDefinition:
   case MCSA_WeakDefAutoPrivate:
   case MCSA_Invalid:
-  case MCSA_ELF_TypeIndFunction:
   case MCSA_IndirectSymbol:
-    assert(0 && "Invalid symbol attribute for ELF!");
-    break;
+    llvm_unreachable("Invalid symbol attribute for ELF!");
=20
   case MCSA_ELF_TypeGnuUniqueObject:
     // Ignore for now.
@@ -162,6 +281,10 @@
     MCELF::SetType(SD, ELF::STT_FUNC);
     break;
=20
+  case MCSA_ELF_TypeIndFunction:
+    MCELF::SetType(SD, ELF::STT_GNU_IFUNC);
+    break;
+
   case MCSA_ELF_TypeObject:
     MCELF::SetType(SD, ELF::STT_OBJECT);
     break;
@@ -205,10 +328,10 @@
=20
   if (MCELF::GetBinding(SD) =3D=3D ELF_STB_Local) {
     const MCSection *Section =3D getAssembler().getContext().getELFSection=
(".bss",
-                                                                    ELF::S=
HT_NOBITS,
-                                                                    ELF::S=
HF_WRITE |
-                                                                    ELF::S=
HF_ALLOC,
-                                                                    Sectio=
nKind::getBSS());
+                                                         ELF::SHT_NOBITS,
+                                                         ELF::SHF_WRITE |
+                                                         ELF::SHF_ALLOC,
+                                                         SectionKind::getB=
SS());
     Symbol->setSection(*Section);
=20
     struct LocalCommon L =3D {&SD, Size, ByteAlignment};
@@ -266,6 +389,13 @@
     getCurrentSectionData()->setAlignment(ByteAlignment);
 }
=20
+void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
+                                  unsigned AddrSpace) {
+  fixSymbolsInTLSFixups(Value);
+  MCObjectStreamer::EmitValueImpl(Value, Size, AddrSpace);
+}
+
+
 // Add a symbol for the file name of this module. This is the second
 // entry in the module's symbol table (the first being the null symbol).
 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
@@ -308,6 +438,10 @@
     case MCSymbolRefExpr::VK_ARM_TLSGD:
     case MCSymbolRefExpr::VK_ARM_TPOFF:
     case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
+    case MCSymbolRefExpr::VK_Mips_TLSGD:
+    case MCSymbolRefExpr::VK_Mips_GOTTPREL:
+    case MCSymbolRefExpr::VK_Mips_TPREL_HI:
+    case MCSymbolRefExpr::VK_Mips_TPREL_LO:
       break;
     }
     MCSymbolData &SD =3D getAssembler().getOrCreateSymbolData(symRef.getSy=
mbol());
@@ -349,7 +483,7 @@
   DF->getContents().append(Code.begin(), Code.end());
 }
=20
-void MCELFStreamer::Finish() {
+void MCELFStreamer::FinishImpl() {
   EmitFrames(true);
=20
   for (std::vector<LocalCommon>::const_iterator i =3D LocalCommons.begin(),
@@ -372,7 +506,7 @@
       SectData.setAlignment(ByteAlignment);
   }
=20
-  this->MCObjectStreamer::Finish();
+  this->MCObjectStreamer::FinishImpl();
 }
=20
 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCExpr.cpp
--- a/head/contrib/llvm/lib/MC/MCExpr.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCExpr.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -14,9 +14,11 @@
 #include "llvm/MC/MCAsmLayout.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCObjectWriter.h"
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/MC/MCValue.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
=20
@@ -57,7 +59,8 @@
         SRE.getKind() =3D=3D MCSymbolRefExpr::VK_ARM_GOT ||
         SRE.getKind() =3D=3D MCSymbolRefExpr::VK_ARM_GOTOFF ||
         SRE.getKind() =3D=3D MCSymbolRefExpr::VK_ARM_TPOFF ||
-        SRE.getKind() =3D=3D MCSymbolRefExpr::VK_ARM_GOTTPOFF)
+        SRE.getKind() =3D=3D MCSymbolRefExpr::VK_ARM_GOTTPOFF ||
+        SRE.getKind() =3D=3D MCSymbolRefExpr::VK_ARM_TARGET1)
       OS << MCSymbolRefExpr::getVariantKindName(SRE.getKind());
     else if (SRE.getKind() !=3D MCSymbolRefExpr::VK_None &&
              SRE.getKind() !=3D MCSymbolRefExpr::VK_PPC_DARWIN_HA16 &&
@@ -70,7 +73,6 @@
   case MCExpr::Unary: {
     const MCUnaryExpr &UE =3D cast<MCUnaryExpr>(*this);
     switch (UE.getOpcode()) {
-    default: assert(0 && "Invalid opcode!");
     case MCUnaryExpr::LNot:  OS << '!'; break;
     case MCUnaryExpr::Minus: OS << '-'; break;
     case MCUnaryExpr::Not:   OS << '~'; break;
@@ -91,7 +93,6 @@
     }
=20
     switch (BE.getOpcode()) {
-    default: assert(0 && "Invalid opcode!");
     case MCBinaryExpr::Add:
       // Print "X-42" instead of "X+-42".
       if (const MCConstantExpr *RHSC =3D dyn_cast<MCConstantExpr>(BE.getRH=
S())) {
@@ -132,7 +133,7 @@
   }
   }
=20
-  assert(0 && "Invalid expression kind!");
+  llvm_unreachable("Invalid expression kind!");
 }
=20
 void MCExpr::dump() const {
@@ -171,7 +172,6 @@
=20
 StringRef MCSymbolRefExpr::getVariantKindName(VariantKind Kind) {
   switch (Kind) {
-  default:
   case VK_Invalid: return "<<invalid>>";
   case VK_None: return "<<none>>";
=20
@@ -189,18 +189,39 @@
   case VK_TPOFF: return "TPOFF";
   case VK_DTPOFF: return "DTPOFF";
   case VK_TLVP: return "TLVP";
+  case VK_SECREL: return "SECREL";
   case VK_ARM_PLT: return "(PLT)";
   case VK_ARM_GOT: return "(GOT)";
   case VK_ARM_GOTOFF: return "(GOTOFF)";
   case VK_ARM_TPOFF: return "(tpoff)";
   case VK_ARM_GOTTPOFF: return "(gottpoff)";
   case VK_ARM_TLSGD: return "(tlsgd)";
+  case VK_ARM_TARGET1: return "(target1)";
   case VK_PPC_TOC: return "toc";
   case VK_PPC_DARWIN_HA16: return "ha16";
   case VK_PPC_DARWIN_LO16: return "lo16";
   case VK_PPC_GAS_HA16: return "ha";
   case VK_PPC_GAS_LO16: return "l";
+  case VK_Mips_GPREL: return "GPREL";
+  case VK_Mips_GOT_CALL: return "GOT_CALL";
+  case VK_Mips_GOT16: return "GOT16";
+  case VK_Mips_GOT: return "GOT";
+  case VK_Mips_ABS_HI: return "ABS_HI";
+  case VK_Mips_ABS_LO: return "ABS_LO";
+  case VK_Mips_TLSGD: return "TLSGD";
+  case VK_Mips_TLSLDM: return "TLSLDM";
+  case VK_Mips_DTPREL_HI: return "DTPREL_HI";
+  case VK_Mips_DTPREL_LO: return "DTPREL_LO";
+  case VK_Mips_GOTTPREL: return "GOTTPREL";
+  case VK_Mips_TPREL_HI: return "TPREL_HI";
+  case VK_Mips_TPREL_LO: return "TPREL_LO";
+  case VK_Mips_GPOFF_HI: return "GPOFF_HI";
+  case VK_Mips_GPOFF_LO: return "GPOFF_LO";
+  case VK_Mips_GOT_DISP: return "GOT_DISP";
+  case VK_Mips_GOT_PAGE: return "GOT_PAGE";
+  case VK_Mips_GOT_OFST: return "GOT_OFST";
   }
+  llvm_unreachable("Invalid variant kind");
 }
=20
 MCSymbolRefExpr::VariantKind
@@ -337,6 +358,11 @@
   if (Addrs && (&SecA !=3D &SecB))
     Addend +=3D (Addrs->lookup(&SecA) - Addrs->lookup(&SecB));
=20
+  // Pointers to Thumb symbols need to have their low-bit set to allow
+  // for interworking.
+  if (Asm->isThumbFunc(&SA))
+    Addend |=3D 1;
+
   // Clear the symbol expr pointers to indicate we have folded these
   // operands.
   A =3D B =3D 0;
@@ -557,8 +583,7 @@
   }
   }
=20
-  assert(0 && "Invalid assembly expression kind!");
-  return false;
+  llvm_unreachable("Invalid assembly expression kind!");
 }
=20
 const MCSection *MCExpr::FindAssociatedSection() const {
@@ -599,6 +624,5 @@
   }
   }
=20
-  assert(0 && "Invalid assembly expression kind!");
-  return 0;
+  llvm_unreachable("Invalid assembly expression kind!");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCInst.cpp
--- a/head/contrib/llvm/lib/MC/MCInst.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCInst.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,6 +25,8 @@
     OS << "Imm:" << getImm();
   else if (isExpr()) {
     OS << "Expr:(" << *getExpr() << ")";
+  } else if (isInst()) {
+    OS << "Inst:(" << *getInst() << ")";
   } else
     OS << "UNDEFINED";
   OS << ">";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCInstPrinter=
.cpp
--- a/head/contrib/llvm/lib/MC/MCInstPrinter.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/MC/MCInstPrinter.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -8,8 +8,10 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/MC/MCInstPrinter.h"
+#include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
=20
@@ -19,11 +21,11 @@
 /// getOpcodeName - Return the name of the specified opcode enum (e.g.
 /// "MOV32ri") or empty if we can't resolve it.
 StringRef MCInstPrinter::getOpcodeName(unsigned Opcode) const {
-  return "";
+  return MII.getName(Opcode);
 }
=20
 void MCInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
-  assert(0 && "Target should implement this");
+  llvm_unreachable("Target should implement this");
 }
=20
 void MCInstPrinter::printAnnotation(raw_ostream &OS, StringRef Annot) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCMachOStream=
er.cpp
--- a/head/contrib/llvm/lib/MC/MCMachOStreamer.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/MC/MCMachOStreamer.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -53,23 +53,23 @@
   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
                                 unsigned ByteAlignment);
   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
-    assert(0 && "macho doesn't support this directive");
+    llvm_unreachable("macho doesn't support this directive");
   }
   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
-    assert(0 && "macho doesn't support this directive");
+    llvm_unreachable("macho doesn't support this directive");
   }
   virtual void EmitCOFFSymbolType(int Type) {
-    assert(0 && "macho doesn't support this directive");
+    llvm_unreachable("macho doesn't support this directive");
   }
   virtual void EndCOFFSymbolDef() {
-    assert(0 && "macho doesn't support this directive");
+    llvm_unreachable("macho doesn't support this directive");
   }
   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
-    assert(0 && "macho doesn't support this directive");
+    llvm_unreachable("macho doesn't support this directive");
   }
   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
                                      unsigned ByteAlignment) {
-    assert(0 && "macho doesn't support this directive");
+    llvm_unreachable("macho doesn't support this directive");
   }
   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol =3D=
 0,
                             unsigned Size =3D 0, unsigned ByteAlignment =
=3D 0);
@@ -89,7 +89,7 @@
     //report_fatal_error("unsupported directive: '.file'");
   }
=20
-  virtual void Finish();
+  virtual void FinishImpl();
=20
   /// @}
 };
@@ -140,7 +140,7 @@
=20
 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
   // Let the target do whatever target specific stuff it needs to do.
-  getAssembler().getBackend().HandleAssemblerFlag(Flag);
+  getAssembler().getBackend().handleAssemblerFlag(Flag);
   // Do any generic stuff we need to do.
   switch (Flag) {
   case MCAF_SyntaxUnified: return; // no-op here.
@@ -150,14 +150,10 @@
   case MCAF_SubsectionsViaSymbols:
     getAssembler().setSubsectionsViaSymbols(true);
     return;
-  default:
-    llvm_unreachable("invalid assembler flag!");
   }
 }
=20
 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
-  // FIXME: Flag the function ISA as thumb with DW_AT_APPLE_isa.
-
   // Remember that the function is a thumb function. Fixup and relocation
   // values will need adjusted.
   getAssembler().setIsThumbFunc(Symbol);
@@ -215,8 +211,7 @@
   case MCSA_Protected:
   case MCSA_Weak:
   case MCSA_Local:
-    assert(0 && "Invalid symbol attribute for Mach-O!");
-    break;
+    llvm_unreachable("Invalid symbol attribute for Mach-O!");
=20
   case MCSA_Global:
     SD.setExternal(true);
@@ -377,7 +372,7 @@
   DF->getContents().append(Code.begin(), Code.end());
 }
=20
-void MCMachOStreamer::Finish() {
+void MCMachOStreamer::FinishImpl() {
   EmitFrames(true);
=20
   // We have to set the fragment atom associations so we can relax properl=
y for
@@ -409,7 +404,7 @@
     }
   }
=20
-  this->MCObjectStreamer::Finish();
+  this->MCObjectStreamer::FinishImpl();
 }
=20
 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MA=
B,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCModule.cpp
--- a/head/contrib/llvm/lib/MC/MCModule.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCModule.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- lib/MC/MCModule.cpp - MCModule implementation ---------------=
-----------=3D=3D=3D//
+//=3D=3D=3D- lib/MC/MCModule.cpp - MCModule implementation ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCNullStreame=
r.cpp
--- a/head/contrib/llvm/lib/MC/MCNullStreamer.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/MC/MCNullStreamer.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -55,6 +55,7 @@
     virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
     virtual void EmitCOFFSymbolType(int Type) {}
     virtual void EndCOFFSymbolDef() {}
+    virtual void EmitCOFFSecRel32(MCSymbol const *Symbol) {}
=20
     virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
     virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
@@ -79,11 +80,12 @@
     virtual void EmitCodeAlignment(unsigned ByteAlignment,
                                    unsigned MaxBytesToEmit =3D 0) {}
=20
-    virtual void EmitValueToOffset(const MCExpr *Offset,
-                                   unsigned char Value =3D 0) {}
+    virtual bool EmitValueToOffset(const MCExpr *Offset,
+                                   unsigned char Value =3D 0) { return fal=
se; }
    =20
     virtual void EmitFileDirective(StringRef Filename) {}
-    virtual bool EmitDwarfFileDirective(unsigned FileNo,StringRef Filename=
) {
+    virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directo=
ry,
+                                        StringRef Filename) {
       return false;
     }
     virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
@@ -92,7 +94,11 @@
                                        StringRef FileName) {}
     virtual void EmitInstruction(const MCInst &Inst) {}
=20
-    virtual void Finish() {}
+    virtual void FinishImpl() {}
+
+    virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
+      RecordProcEnd(Frame);
+    }
    =20
     /// @}
   };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCObjectFileI=
nfo.cpp
--- a/head/contrib/llvm/lib/MC/MCObjectFileInfo.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/MC/MCObjectFileInfo.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -56,8 +56,8 @@
=20
   TLSThreadInitSection
     =3D Ctx->getMachOSection("__DATA", "__thread_init",
-                           MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_PO=
INTERS,
-                           SectionKind::getDataRel());
+                          MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POI=
NTERS,
+                          SectionKind::getDataRel());
=20
   CStringSection // .cstring
     =3D Ctx->getMachOSection("__TEXT", "__cstring",
@@ -152,6 +152,24 @@
                            SectionKind::getReadOnly());
=20
   // Debug Information.
+  DwarfAccelNamesSection =3D
+    Ctx->getMachOSection("__DWARF", "__apple_names",
+                         MCSectionMachO::S_ATTR_DEBUG,
+                         SectionKind::getMetadata());
+  DwarfAccelObjCSection =3D
+    Ctx->getMachOSection("__DWARF", "__apple_objc",
+                         MCSectionMachO::S_ATTR_DEBUG,
+                         SectionKind::getMetadata());
+  // 16 character section limit...
+  DwarfAccelNamespaceSection =3D
+    Ctx->getMachOSection("__DWARF", "__apple_namespac",
+                         MCSectionMachO::S_ATTR_DEBUG,
+                         SectionKind::getMetadata());
+  DwarfAccelTypesSection =3D
+    Ctx->getMachOSection("__DWARF", "__apple_types",
+                         MCSectionMachO::S_ATTR_DEBUG,
+                         SectionKind::getMetadata());
+   =20
   DwarfAbbrevSection =3D
     Ctx->getMachOSection("__DWARF", "__debug_abbrev",
                          MCSectionMachO::S_ATTR_DEBUG,
@@ -168,10 +186,6 @@
     Ctx->getMachOSection("__DWARF", "__debug_frame",
                          MCSectionMachO::S_ATTR_DEBUG,
                          SectionKind::getMetadata());
-  DwarfPubNamesSection =3D
-    Ctx->getMachOSection("__DWARF", "__debug_pubnames",
-                         MCSectionMachO::S_ATTR_DEBUG,
-                         SectionKind::getMetadata());
   DwarfPubTypesSection =3D
     Ctx->getMachOSection("__DWARF", "__debug_pubtypes",
                          MCSectionMachO::S_ATTR_DEBUG,
@@ -207,8 +221,8 @@
 void MCObjectFileInfo::InitELFMCObjectFileInfo(Triple T) {
   if (T.getArch() =3D=3D Triple::x86) {
     PersonalityEncoding =3D (RelocM =3D=3D Reloc::PIC_)
-      ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE=
_sdata4
-      : dwarf::DW_EH_PE_absptr;
+     ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_=
sdata4
+     : dwarf::DW_EH_PE_absptr;
     LSDAEncoding =3D (RelocM =3D=3D Reloc::PIC_)
       ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
       : dwarf::DW_EH_PE_absptr;
@@ -216,8 +230,8 @@
       ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
       : dwarf::DW_EH_PE_absptr;
     TTypeEncoding =3D (RelocM =3D=3D Reloc::PIC_)
-      ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE=
_sdata4
-      : dwarf::DW_EH_PE_absptr;
+     ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_=
sdata4
+     : dwarf::DW_EH_PE_absptr;
   } else if (T.getArch() =3D=3D Triple::x86_64) {
     FDECFIEncoding =3D dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
=20
@@ -244,10 +258,22 @@
     }
   }
=20
+  // Solaris requires different flags for .eh_frame to seemingly every oth=
er
+  // platform.
+  EHSectionType =3D ELF::SHT_PROGBITS;
+  EHSectionFlags =3D ELF::SHF_ALLOC;
+  if (T.getOS() =3D=3D Triple::Solaris) {
+    if (T.getArch() =3D=3D Triple::x86_64)
+      EHSectionType =3D ELF::SHT_X86_64_UNWIND;
+    else
+      EHSectionFlags |=3D ELF::SHF_WRITE;
+  }
+
+
   // ELF
   BSSSection =3D
     Ctx->getELFSection(".bss", ELF::SHT_NOBITS,
-                       ELF::SHF_WRITE |ELF::SHF_ALLOC,
+                       ELF::SHF_WRITE | ELF::SHF_ALLOC,
                        SectionKind::getBSS());
=20
   TextSection =3D
@@ -347,15 +373,13 @@
   DwarfFrameSection =3D
     Ctx->getELFSection(".debug_frame", ELF::SHT_PROGBITS, 0,
                        SectionKind::getMetadata());
-  DwarfPubNamesSection =3D
-    Ctx->getELFSection(".debug_pubnames", ELF::SHT_PROGBITS, 0,
-                       SectionKind::getMetadata());
   DwarfPubTypesSection =3D
     Ctx->getELFSection(".debug_pubtypes", ELF::SHT_PROGBITS, 0,
                        SectionKind::getMetadata());
   DwarfStrSection =3D
-    Ctx->getELFSection(".debug_str", ELF::SHT_PROGBITS, 0,
-                       SectionKind::getMetadata());
+    Ctx->getELFSection(".debug_str", ELF::SHT_PROGBITS,
+                       ELF::SHF_MERGE | ELF::SHF_STRINGS,
+                       SectionKind::getMergeable1ByteCString());
   DwarfLocSection =3D
     Ctx->getELFSection(".debug_loc", ELF::SHT_PROGBITS, 0,
                        SectionKind::getMetadata());
@@ -390,12 +414,22 @@
                         COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
                         COFF::IMAGE_SCN_MEM_READ,
                         SectionKind::getReadOnly());
-  StaticCtorSection =3D
-    Ctx->getCOFFSection(".ctors",
-                        COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
-                        COFF::IMAGE_SCN_MEM_READ |
-                        COFF::IMAGE_SCN_MEM_WRITE,
-                        SectionKind::getDataRel());
+  if (T.getOS() =3D=3D Triple::Win32) {
+    StaticCtorSection =3D
+      Ctx->getCOFFSection(".CRT$XCU",
+                          COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
+                          COFF::IMAGE_SCN_MEM_READ,
+                          SectionKind::getReadOnly());
+  } else {
+    StaticCtorSection =3D
+      Ctx->getCOFFSection(".ctors",
+                          COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
+                          COFF::IMAGE_SCN_MEM_READ |
+                          COFF::IMAGE_SCN_MEM_WRITE,
+                          SectionKind::getDataRel());
+  }
+
+
   StaticDtorSection =3D
     Ctx->getCOFFSection(".dtors",
                         COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
@@ -434,11 +468,6 @@
                         COFF::IMAGE_SCN_MEM_DISCARDABLE |
                         COFF::IMAGE_SCN_MEM_READ,
                         SectionKind::getMetadata());
-  DwarfPubNamesSection =3D
-    Ctx->getCOFFSection(".debug_pubnames",
-                        COFF::IMAGE_SCN_MEM_DISCARDABLE |
-                        COFF::IMAGE_SCN_MEM_READ,
-                        SectionKind::getMetadata());
   DwarfPubTypesSection =3D
     Ctx->getCOFFSection(".debug_pubtypes",
                         COFF::IMAGE_SCN_MEM_DISCARDABLE |
@@ -488,6 +517,12 @@
                         COFF::IMAGE_SCN_MEM_READ |
                         COFF::IMAGE_SCN_MEM_WRITE,
                         SectionKind::getDataRel());
+  TLSDataSection =3D
+    Ctx->getCOFFSection(".tls$",
+                        COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
+                        COFF::IMAGE_SCN_MEM_READ |
+                        COFF::IMAGE_SCN_MEM_WRITE,
+                        SectionKind::getDataRel());
 }
=20
 void MCObjectFileInfo::InitMCObjectFileInfo(StringRef TT, Reloc::Model rel=
ocm,
@@ -505,8 +540,12 @@
   PersonalityEncoding =3D LSDAEncoding =3D FDEEncoding =3D FDECFIEncoding =
=3D
     TTypeEncoding =3D dwarf::DW_EH_PE_absptr;
=20
-  EHFrameSection =3D 0;           // Created on demand.
-  CompactUnwindSection =3D 0;     // Used only by selected targets.
+  EHFrameSection =3D 0;             // Created on demand.
+  CompactUnwindSection =3D 0;       // Used only by selected targets.
+  DwarfAccelNamesSection =3D 0;     // Used only by selected targets.
+  DwarfAccelObjCSection =3D 0;      // Used only by selected targets.
+  DwarfAccelNamespaceSection =3D 0; // Used only by selected targets.
+  DwarfAccelTypesSection =3D 0;     // Used only by selected targets.
=20
   Triple T(TT);
   Triple::ArchType Arch =3D T.getArch();
@@ -541,8 +580,8 @@
                            SectionKind::getReadOnly());
   else if (Env =3D=3D IsELF)
     EHFrameSection =3D
-      Ctx->getELFSection(".eh_frame", ELF::SHT_PROGBITS,
-                         ELF::SHF_ALLOC,
+      Ctx->getELFSection(".eh_frame", EHSectionType,
+                         EHSectionFlags,
                          SectionKind::getDataRel());
   else
     EHFrameSection =3D
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCObjectStrea=
mer.cpp
--- a/head/contrib/llvm/lib/MC/MCObjectStreamer.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/MC/MCObjectStreamer.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -7,17 +7,17 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "llvm/MC/MCObjectStreamer.h"
+#include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCAsmInfo.h"
-#include "llvm/MC/MCObjectStreamer.h"
-
-#include "llvm/Support/ErrorHandling.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCCodeEmitter.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCDwarf.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCObjectWriter.h"
 #include "llvm/MC/MCSymbol.h"
-#include "llvm/MC/MCAsmBackend.h"
+#include "llvm/Support/ErrorHandling.h"
 using namespace llvm;
=20
 MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
@@ -105,6 +105,14 @@
   DF->getContents().resize(DF->getContents().size() + Size, 0);
 }
=20
+void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
+  RecordProcStart(Frame);
+}
+
+void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
+  RecordProcEnd(Frame);
+}
+
 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
   MCStreamer::EmitLabel(Symbol);
=20
@@ -164,7 +172,7 @@
   MCLineEntry::Make(this, getCurrentSection());
=20
   // If this instruction doesn't need relaxation, just emit it as data.
-  if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
+  if (!getAssembler().getBackend().mayNeedRelaxation(Inst)) {
     EmitInstToData(Inst);
     return;
   }
@@ -173,9 +181,9 @@
   // possible and emit it as data.
   if (getAssembler().getRelaxAll()) {
     MCInst Relaxed;
-    getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
-    while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
-      getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
+    getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
+    while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
+      getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
     EmitInstToData(Relaxed);
     return;
   }
@@ -224,12 +232,12 @@
   new MCDwarfCallFrameFragment(*AddrDelta, getCurrentSectionData());
 }
=20
-void MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
-                                        unsigned char Value) {
+bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
+                                         unsigned char Value) {
   int64_t Res;
   if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
     new MCOrgFragment(*Offset, Value, getCurrentSectionData());
-    return;
+    return false;
   }
=20
   MCSymbol *CurrentPos =3D getContext().CreateTempSymbol();
@@ -241,14 +249,30 @@
     MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
=20
   if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
-    report_fatal_error("expected assembly-time absolute expression");
+    return true;
   EmitFill(Res, Value, 0);
+  return false;
 }
=20
-void MCObjectStreamer::Finish() {
+// Associate GPRel32 fixup with data and resize data area
+void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
+  MCDataFragment *DF =3D getOrCreateDataFragment();
+
+  DF->addFixup(MCFixup::Create(DF->getContents().size(),
+                               Value,
+                               FK_GPRel_4));
+  DF->getContents().resize(DF->getContents().size() + 4, 0);
+}
+
+void MCObjectStreamer::FinishImpl() {
   // Dump out the dwarf file & directory tables and line tables.
+  const MCSymbol *LineSectionSymbol =3D NULL;
   if (getContext().hasDwarfFiles())
-    MCDwarfFileTable::Emit(this);
+    LineSectionSymbol =3D MCDwarfFileTable::Emit(this);
+
+  // If we are generating dwarf for assembly source files dump out the sec=
tions.
+  if (getContext().getGenDwarfForAssembly())
+    MCGenDwarfInfo::Emit(this, LineSectionSymbol);
=20
   getAssembler().Finish();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCObjectWrite=
r.cpp
--- a/head/contrib/llvm/lib/MC/MCObjectWriter.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/MC/MCObjectWriter.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -33,14 +33,22 @@
 }
=20
 /// Utility function to encode a ULEB128 value.
-void MCObjectWriter::EncodeULEB128(uint64_t Value, raw_ostream &OS) {
+void MCObjectWriter::EncodeULEB128(uint64_t Value, raw_ostream &OS,
+                                   unsigned Padding) {
   do {
     uint8_t Byte =3D Value & 0x7f;
     Value >>=3D 7;
-    if (Value !=3D 0)
+    if (Value !=3D 0 || Padding !=3D 0)
       Byte |=3D 0x80; // Mark this byte that that more bytes will follow.
     OS << char(Byte);
   } while (Value !=3D 0);
+
+  // Pad with 0x80 and emit a null byte at the end.
+  if (Padding !=3D 0) {
+    for (; Padding !=3D 1; --Padding)
+      OS << '\x80';
+    OS << '\x00';
+  }
 }
=20
 bool
@@ -60,6 +68,8 @@
=20
   const MCSymbolData &DataA =3D Asm.getSymbolData(SA);
   const MCSymbolData &DataB =3D Asm.getSymbolData(SB);
+  if(!DataA.getFragment() || !DataB.getFragment())
+    return false;
=20
   return IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA,
                                                 *DataB.getFragment(),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCParser/AsmP=
arser.cpp
--- a/head/contrib/llvm/lib/MC/MCParser/AsmParser.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/MC/MCParser/AsmParser.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -14,7 +14,6 @@
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
-#include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCContext.h"
@@ -30,6 +29,7 @@
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/MC/MCTargetAsmParser.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
@@ -122,6 +122,9 @@
   int64_t CppHashLineNumber;
   SMLoc CppHashLoc;
=20
+  /// AssemblerDialect. ~OU means unset value and use value provided by MA=
I.
+  unsigned AssemblerDialect;
+
 public:
   AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
             const MCAsmInfo &MAI);
@@ -143,9 +146,20 @@
   virtual MCAsmLexer &getLexer() { return Lexer; }
   virtual MCContext &getContext() { return Ctx; }
   virtual MCStreamer &getStreamer() { return Out; }
-
-  virtual bool Warning(SMLoc L, const Twine &Msg);
-  virtual bool Error(SMLoc L, const Twine &Msg);
+  virtual unsigned getAssemblerDialect() {=20
+    if (AssemblerDialect =3D=3D ~0U)
+      return MAI.getAssemblerDialect();=20
+    else
+      return AssemblerDialect;
+  }
+  virtual void setAssemblerDialect(unsigned i) {
+    AssemblerDialect =3D i;
+  }
+
+  virtual bool Warning(SMLoc L, const Twine &Msg,
+                       ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>());
+  virtual bool Error(SMLoc L, const Twine &Msg,
+                     ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>());
=20
   const AsmToken &Lex();
=20
@@ -171,14 +185,17 @@
   void HandleMacroExit();
=20
   void PrintMacroInstantiations();
-  void PrintMessage(SMLoc Loc, const Twine &Msg, const char *Type,
-                    bool ShowLine =3D true) const {
-    SrcMgr.PrintMessage(Loc, Msg, Type, ShowLine);
+  void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
+                    ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>()) cons=
t {
+    SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
   }
   static void DiagHandler(const SMDiagnostic &Diag, void *Context);
=20
   /// EnterIncludeFile - Enter the specified file. This returns true on fa=
ilure.
   bool EnterIncludeFile(const std::string &Filename);
+  /// ProcessIncbinFile - Process the specified file for the .incbin direc=
tive.
+  /// This returns true on failure.
+  bool ProcessIncbinFile(const std::string &Filename);
=20
   /// \brief Reset the current lexer position to that given by \arg Loc. T=
he
   /// current token is not set; clients should ensure Lex() is called
@@ -225,6 +242,7 @@
=20
   bool ParseDirectiveAbort(); // ".abort"
   bool ParseDirectiveInclude(); // ".include"
+  bool ParseDirectiveIncbin(); // ".incbin"
=20
   bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
   // ".ifdef" or ".ifndef", depending on expect_defined
@@ -295,6 +313,12 @@
       &GenericAsmParser::ParseDirectiveCFIRestoreState>(".cfi_restore_stat=
e");
     AddDirectiveHandler<
       &GenericAsmParser::ParseDirectiveCFISameValue>(".cfi_same_value");
+    AddDirectiveHandler<
+      &GenericAsmParser::ParseDirectiveCFIRestore>(".cfi_restore");
+    AddDirectiveHandler<
+      &GenericAsmParser::ParseDirectiveCFIEscape>(".cfi_escape");
+    AddDirectiveHandler<
+      &GenericAsmParser::ParseDirectiveCFISignalFrame>(".cfi_signal_frame"=
);
=20
     // Macro directives.
     AddDirectiveHandler<&GenericAsmParser::ParseDirectiveMacrosOnOff>(
@@ -328,6 +352,9 @@
   bool ParseDirectiveCFIRememberState(StringRef, SMLoc DirectiveLoc);
   bool ParseDirectiveCFIRestoreState(StringRef, SMLoc DirectiveLoc);
   bool ParseDirectiveCFISameValue(StringRef, SMLoc DirectiveLoc);
+  bool ParseDirectiveCFIRestore(StringRef, SMLoc DirectiveLoc);
+  bool ParseDirectiveCFIEscape(StringRef, SMLoc DirectiveLoc);
+  bool ParseDirectiveCFISignalFrame(StringRef, SMLoc DirectiveLoc);
=20
   bool ParseDirectiveMacrosOnOff(StringRef, SMLoc DirectiveLoc);
   bool ParseDirectiveMacro(StringRef, SMLoc DirectiveLoc);
@@ -352,7 +379,8 @@
                      MCStreamer &_Out, const MCAsmInfo &_MAI)
   : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
     GenericParser(new GenericAsmParser), PlatformParser(0),
-    CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0) {
+    CurBuffer(0), MacrosEnabled(true), CppHashLineNumber(0),=20
+    AssemblerDialect(~0U) {
   // Save the old handler.
   SavedDiagHandler =3D SrcMgr.getDiagHandler();
   SavedDiagContext =3D SrcMgr.getDiagContext();
@@ -395,21 +423,21 @@
   // Print the active macro instantiation stack.
   for (std::vector<MacroInstantiation*>::const_reverse_iterator
          it =3D ActiveMacros.rbegin(), ie =3D ActiveMacros.rend(); it !=3D=
 ie; ++it)
-    PrintMessage((*it)->InstantiationLoc, "while in macro instantiation",
-                 "note");
+    PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
+                 "while in macro instantiation");
 }
=20
-bool AsmParser::Warning(SMLoc L, const Twine &Msg) {
+bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Range=
s) {
   if (FatalAssemblerWarnings)
-    return Error(L, Msg);
-  PrintMessage(L, Msg, "warning");
+    return Error(L, Msg, Ranges);
+  PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
   PrintMacroInstantiations();
   return false;
 }
=20
-bool AsmParser::Error(SMLoc L, const Twine &Msg) {
+bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges)=
 {
   HadError =3D true;
-  PrintMessage(L, Msg, "error");
+  PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
   PrintMacroInstantiations();
   return true;
 }
@@ -427,6 +455,21 @@
   return false;
 }
=20
+/// Process the specified .incbin file by seaching for it in the include p=
aths
+/// then just emiting the byte contents of the file to the streamer. This=20
+/// returns true on failure.
+bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
+  std::string IncludedFile;
+  int NewBuf =3D SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedF=
ile);
+  if (NewBuf =3D=3D -1)
+    return true;
+
+  // Pick up the bytes from the file and emit them.
+  getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
+                          DEFAULT_ADDRSPACE);
+  return false;
+}
+
 void AsmParser::JumpToLoc(SMLoc Loc) {
   CurBuffer =3D SrcMgr.FindBufferContainingLoc(Loc);
   Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
@@ -462,6 +505,17 @@
   HadError =3D false;
   AsmCond StartingCondState =3D TheCondState;
=20
+  // If we are generating dwarf for assembly source files save the initial=
 text
+  // section and generate a .file directive.
+  if (getContext().getGenDwarfForAssembly()) {
+    getContext().setGenDwarfSection(getStreamer().getCurrentSection());
+    MCSymbol *SectionStartSym =3D getContext().CreateTempSymbol();
+    getStreamer().EmitLabel(SectionStartSym);
+    getContext().setGenDwarfSectionStartSym(SectionStartSym);
+    getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumb=
er(),
+      StringRef(), SrcMgr.getMemoryBuffer(CurBuffer)->getBufferIdentifier(=
));
+  }
+
   // While we have input, parse each statement.
   while (Lexer.isNot(AsmToken::Eof)) {
     if (!ParseStatement()) continue;
@@ -501,8 +555,9 @@
         // FIXME: We would really like to refer back to where the symbol w=
as
         // first referenced for a source location. We need to add something
         // to track that. Currently, we just point to the end of the file.
-        PrintMessage(getLexer().getLoc(), "assembler local symbol '" +
-                     Sym->getName() + "' not defined", "error", false);
+        PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
+                     "assembler local symbol '" + Sym->getName() +
+                     "' not defined");
     }
   }
=20
@@ -749,8 +804,7 @@
   }
   }
=20
-  assert(0 && "Invalid expression kind!");
-  return 0;
+  llvm_unreachable("Invalid expression kind!");
 }
=20
 /// ParseExpression - Parse an expression and return it.
@@ -787,7 +841,6 @@
     if (!ModifiedRes) {
       return TokError("invalid modifier '" + getTok().getIdentifier() +
                       "' (no symbols present)");
-      return true;
     }
=20
     Res =3D ModifiedRes;
@@ -1036,6 +1089,12 @@
     // Emit the label.
     Out.EmitLabel(Sym);
=20
+    // If we are generating dwarf for assembly source files then gather the
+    // info to make a dwarf label entry for this label if needed.
+    if (getContext().getGenDwarfForAssembly())
+      MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
+                                 IDLoc);
+
     // Consume any end of statement token, if present, to avoid spurious
     // AddBlankLine calls().
     if (Lexer.is(AsmToken::EndOfStatement)) {
@@ -1163,6 +1222,8 @@
       return ParseDirectiveAbort();
     if (IDVal =3D=3D ".include")
       return ParseDirectiveInclude();
+    if (IDVal =3D=3D ".incbin")
+      return ParseDirectiveIncbin();
=20
     if (IDVal =3D=3D ".code16")
       return TokError(Twine(IDVal) + " not supported yet");
@@ -1205,7 +1266,19 @@
     }
     OS << "]";
=20
-    PrintMessage(IDLoc, OS.str(), "note");
+    PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
+  }
+
+  // If we are generating dwarf for assembly source files and the current
+  // section is the initial text section then generate a .loc directive for
+  // the instruction.
+  if (!HadError && getContext().getGenDwarfForAssembly() &&
+      getContext().getGenDwarfSection() =3D=3D getStreamer().getCurrentSec=
tion() ) {
+    getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber=
(),
+                                        SrcMgr.FindLineNumber(IDLoc, CurBu=
ffer),
+                                        0, DWARF2_LINE_DEFAULT_IS_STMT ?
+                                        DWARF2_FLAG_IS_STMT : 0, 0, 0,
+                                        StringRef());
   }
=20
   // If parsing succeeded, match the instruction.
@@ -1294,7 +1367,7 @@
     if (Parser->SavedDiagHandler)
       Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
     else
-      Diag.Print(0, OS);
+      Diag.print(0, OS);
     return;
   }
=20
@@ -1309,19 +1382,15 @@
   int LineNo =3D Parser->CppHashLineNumber - 1 +
                (DiagLocLineNo - CppHashLocLineNo);
=20
-  SMDiagnostic NewDiag(*Diag.getSourceMgr(),
-                       Diag.getLoc(),
-                       Filename,
-                       LineNo,
-                       Diag.getColumnNo(),
-                       Diag.getMessage(),
-                       Diag.getLineContents(),
-                       Diag.getShowLine());
+  SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
+                       Filename, LineNo, Diag.getColumnNo(),
+                       Diag.getKind(), Diag.getMessage(),
+                       Diag.getLineContents(), Diag.getRanges());
=20
   if (Parser->SavedDiagHandler)
     Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
   else
-    NewDiag.Print(0, OS);
+    NewDiag.print(0, OS);
 }
=20
 bool AsmParser::expandMacro(SmallString<256> &Buf, StringRef Body,
@@ -1458,6 +1527,11 @@
     }
     Lex();
   }
+  // If there weren't any arguments, erase the token vector so everything
+  // else knows that. Leaving around the vestigal empty token list confuses
+  // things.
+  if (MacroArguments.size() =3D=3D 1 && MacroArguments.back().empty())
+    MacroArguments.clear();
=20
   // Macro instantiation is lexical, unfortunately. We construct a new buf=
fer
   // to hold the macro body with substitutions.
@@ -1495,23 +1569,27 @@
   ActiveMacros.pop_back();
 }
=20
-static void MarkUsed(const MCExpr *Value) {
+static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
   switch (Value->getKind()) {
-  case MCExpr::Binary:
-    MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getLHS());
-    MarkUsed(static_cast<const MCBinaryExpr*>(Value)->getRHS());
+  case MCExpr::Binary: {
+    const MCBinaryExpr *BE =3D static_cast<const MCBinaryExpr*>(Value);
+    return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
     break;
+  }
   case MCExpr::Target:
   case MCExpr::Constant:
-    break;
+    return false;
   case MCExpr::SymbolRef: {
-    static_cast<const MCSymbolRefExpr*>(Value)->getSymbol().setUsed(true);
-    break;
+    const MCSymbol &S =3D static_cast<const MCSymbolRefExpr*>(Value)->getS=
ymbol();
+    if (S.isVariable())
+      return IsUsedIn(Sym, S.getVariableValue());
+    return &S =3D=3D Sym;
   }
   case MCExpr::Unary:
-    MarkUsed(static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
-    break;
+    return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExp=
r());
   }
+
+  llvm_unreachable("Unknown expr kind!");
 }
=20
 bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef) {
@@ -1522,7 +1600,9 @@
   if (ParseExpression(Value))
     return true;
=20
-  MarkUsed(Value);
+  // Note: we don't count b as used in "a =3D b". This is to allow
+  // a =3D b
+  // b =3D c
=20
   if (Lexer.isNot(AsmToken::EndOfStatement))
     return TokError("unexpected token in assignment");
@@ -1544,8 +1624,12 @@
     //
     // FIXME: Diagnostics. Note the location of the definition as a label.
     // FIXME: Diagnose assignment to protected identifier (e.g., register =
name).
-    if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
+    if (IsUsedIn(Sym, Value))
+      return Error(EqualLoc, "Recursive use of '" + Name + "'");
+    else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
       ; // Allow redefinitions of undefined symbols only used in directive=
s.
+    else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
+      ; // Allow redefinitions of variables that haven't yet been used.
     else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
       return Error(EqualLoc, "redefinition of '" + Name + "'");
     else if (!Sym->isVariable())
@@ -1912,6 +1996,7 @@
   CheckForValidSection();
=20
   const MCExpr *Offset;
+  SMLoc Loc =3D getTok().getLoc();
   if (ParseExpression(Offset))
     return true;
=20
@@ -1931,9 +2016,11 @@
=20
   Lex();
=20
-  // FIXME: Only limited forms of relocatable expressions are accepted her=
e, it
-  // has to be relative to the current section.
-  getStreamer().EmitValueToOffset(Offset, FillExpr);
+  // Only limited forms of relocatable expressions are accepted here, it
+  // has to be relative to the current section. The streamer will return
+  // 'true' if the expression wasn't evaluatable.
+  if (getStreamer().EmitValueToOffset(Offset, FillExpr))
+    return Error(Loc, "expected assembly-time absolute expression");
=20
   return false;
 }
@@ -2178,6 +2265,31 @@
   return false;
 }
=20
+/// ParseDirectiveIncbin
+///  ::=3D .incbin "filename"
+bool AsmParser::ParseDirectiveIncbin() {
+  if (getLexer().isNot(AsmToken::String))
+    return TokError("expected string in '.incbin' directive");
+
+  std::string Filename =3D getTok().getString();
+  SMLoc IncbinLoc =3D getLexer().getLoc();
+  Lex();
+
+  if (getLexer().isNot(AsmToken::EndOfStatement))
+    return TokError("unexpected token in '.incbin' directive");
+
+  // Strip the quotes.
+  Filename =3D Filename.substr(1, Filename.size()-2);
+
+  // Attempt to process the included file.
+  if (ProcessIncbinFile(Filename)) {
+    Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
+    return true;
+  }
+
+  return false;
+}
+
 /// ParseDirectiveIf
 /// ::=3D .if expression
 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
@@ -2305,7 +2417,8 @@
 }
=20
 /// ParseDirectiveFile
-/// ::=3D .file [number] string
+/// ::=3D .file [number] filename
+/// ::=3D .file number directory filename
 bool GenericAsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
   // FIXME: I'm not sure what this is.
   int64_t FileNumber =3D -1;
@@ -2321,17 +2434,35 @@
   if (getLexer().isNot(AsmToken::String))
     return TokError("unexpected token in '.file' directive");
=20
-  StringRef Filename =3D getTok().getString();
-  Filename =3D Filename.substr(1, Filename.size()-2);
+  // Usually the directory and filename together, otherwise just the direc=
tory.
+  StringRef Path =3D getTok().getString();
+  Path =3D Path.substr(1, Path.size()-2);
   Lex();
=20
+  StringRef Directory;
+  StringRef Filename;
+  if (getLexer().is(AsmToken::String)) {
+    if (FileNumber =3D=3D -1)
+      return TokError("explicit path specified, but no file number");
+    Filename =3D getTok().getString();
+    Filename =3D Filename.substr(1, Filename.size()-2);
+    Directory =3D Path;
+    Lex();
+  } else {
+    Filename =3D Path;
+  }
+
   if (getLexer().isNot(AsmToken::EndOfStatement))
     return TokError("unexpected token in '.file' directive");
=20
   if (FileNumber =3D=3D -1)
     getStreamer().EmitFileDirective(Filename);
   else {
-    if (getStreamer().EmitDwarfFileDirective(FileNumber, Filename))
+    if (getContext().getGenDwarfForAssembly() =3D=3D true)
+      Error(DirectiveLoc, "input can't have .file dwarf directives when -g=
 is "
+                        "used to generate dwarf debug info for assembly co=
de");
+
+    if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filena=
me))
       Error(FileNumberLoc, "file number already allocated");
   }
=20
@@ -2719,6 +2850,56 @@
   return false;
 }
=20
+/// ParseDirectiveCFIRestore
+/// ::=3D .cfi_restore register
+bool GenericAsmParser::ParseDirectiveCFIRestore(StringRef IDVal,
+						SMLoc DirectiveLoc) {
+  int64_t Register =3D 0;
+  if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
+    return true;
+
+  getStreamer().EmitCFIRestore(Register);
+
+  return false;
+}
+
+/// ParseDirectiveCFIEscape
+/// ::=3D .cfi_escape expression[,...]
+bool GenericAsmParser::ParseDirectiveCFIEscape(StringRef IDVal,
+					       SMLoc DirectiveLoc) {
+  std::string Values;
+  int64_t CurrValue;
+  if (getParser().ParseAbsoluteExpression(CurrValue))
+    return true;
+
+  Values.push_back((uint8_t)CurrValue);
+
+  while (getLexer().is(AsmToken::Comma)) {
+    Lex();
+
+    if (getParser().ParseAbsoluteExpression(CurrValue))
+      return true;
+
+    Values.push_back((uint8_t)CurrValue);
+  }
+
+  getStreamer().EmitCFIEscape(Values);
+  return false;
+}
+
+/// ParseDirectiveCFISignalFrame
+/// ::=3D .cfi_signal_frame
+bool GenericAsmParser::ParseDirectiveCFISignalFrame(StringRef Directive,
+                                                    SMLoc DirectiveLoc) {
+  if (getLexer().isNot(AsmToken::EndOfStatement))
+    return Error(getLexer().getLoc(),
+                 "unexpected token in '" + Directive + "' directive");
+
+  getStreamer().EmitCFISignalFrame();
+
+  return false;
+}
+
 /// ParseDirectiveMacrosOnOff
 /// ::=3D .macros_on
 /// ::=3D .macros_off
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCParser/COFF=
AsmParser.cpp
--- a/head/contrib/llvm/lib/MC/MCParser/COFFAsmParser.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCParser/COFFAsmParser.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -45,6 +45,7 @@
     AddDirectiveHandler<&COFFAsmParser::ParseDirectiveScl>(".scl");
     AddDirectiveHandler<&COFFAsmParser::ParseDirectiveType>(".type");
     AddDirectiveHandler<&COFFAsmParser::ParseDirectiveEndef>(".endef");
+    AddDirectiveHandler<&COFFAsmParser::ParseDirectiveSecRel32>(".secrel32=
");
=20
     // Win64 EH directives.
     AddDirectiveHandler<&COFFAsmParser::ParseSEHDirectiveStartProc>(
@@ -102,6 +103,7 @@
   bool ParseDirectiveScl(StringRef, SMLoc);
   bool ParseDirectiveType(StringRef, SMLoc);
   bool ParseDirectiveEndef(StringRef, SMLoc);
+  bool ParseDirectiveSecRel32(StringRef, SMLoc);
=20
   // Win64 EH directives.
   bool ParseSEHDirectiveStartProc(StringRef, SMLoc);
@@ -217,6 +219,21 @@
   return false;
 }
=20
+bool COFFAsmParser::ParseDirectiveSecRel32(StringRef, SMLoc) {
+  StringRef SymbolID;
+  if (getParser().ParseIdentifier(SymbolID))
+    return true;
+
+  if (getLexer().isNot(AsmToken::EndOfStatement))
+    return TokError("unexpected token in directive");
+
+  MCSymbol *Symbol =3D getContext().GetOrCreateSymbol(SymbolID);
+
+  Lex();
+  getStreamer().EmitCOFFSecRel32(Symbol);
+  return false;
+}
+
 bool COFFAsmParser::ParseSEHDirectiveStartProc(StringRef, SMLoc) {
   StringRef SymbolID;
   if (getParser().ParseIdentifier(SymbolID))
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCParser/ELFA=
smParser.cpp
--- a/head/contrib/llvm/lib/MC/MCParser/ELFAsmParser.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCParser/ELFAsmParser.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -476,6 +476,7 @@
     .Case("common", MCSA_ELF_TypeCommon)
     .Case("notype", MCSA_ELF_TypeNoType)
     .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
+    .Case("gnu_indirect_function", MCSA_ELF_TypeIndFunction)
     .Default(MCSA_Invalid);
=20
   if (Attr =3D=3D MCSA_Invalid)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCParser/MCAs=
mLexer.cpp
--- a/head/contrib/llvm/lib/MC/MCParser/MCAsmLexer.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCParser/MCAsmLexer.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -25,3 +25,7 @@
 SMLoc AsmToken::getLoc() const {
   return SMLoc::getFromPointer(Str.data());
 }
+
+SMLoc AsmToken::getEndLoc() const {
+  return SMLoc::getFromPointer(Str.data() + Str.size() - 1);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCParser/MCAs=
mParser.cpp
--- a/head/contrib/llvm/lib/MC/MCParser/MCAsmParser.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCParser/MCAsmParser.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -33,8 +33,8 @@
   return getLexer().getTok();
 }
=20
-bool MCAsmParser::TokError(const Twine &Msg) {
-  Error(getLexer().getLoc(), Msg);
+bool MCAsmParser::TokError(const Twine &Msg, ArrayRef<SMRange> Ranges) {
+  Error(getLexer().getLoc(), Msg, Ranges);
   return true;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCPureStreame=
r.cpp
--- a/head/contrib/llvm/lib/MC/MCPureStreamer.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/MC/MCPureStreamer.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -46,9 +46,9 @@
                                     unsigned MaxBytesToEmit =3D 0);
   virtual void EmitCodeAlignment(unsigned ByteAlignment,
                                  unsigned MaxBytesToEmit =3D 0);
-  virtual void EmitValueToOffset(const MCExpr *Offset,
+  virtual bool EmitValueToOffset(const MCExpr *Offset,
                                  unsigned char Value =3D 0);
-  virtual void Finish();
+  virtual void FinishImpl();
=20
=20
   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribut=
e) {
@@ -93,9 +93,9 @@
   virtual void EmitFileDirective(StringRef Filename) {
     report_fatal_error("unsupported directive in pure streamer");
   }
-  virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename)=
 {
+  virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
+                                      StringRef Filename) {
     report_fatal_error("unsupported directive in pure streamer");
-    return false;
   }
=20
   /// @}
@@ -184,9 +184,10 @@
     getCurrentSectionData()->setAlignment(ByteAlignment);
 }
=20
-void MCPureStreamer::EmitValueToOffset(const MCExpr *Offset,
+bool MCPureStreamer::EmitValueToOffset(const MCExpr *Offset,
                                        unsigned char Value) {
   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
+  return false;
 }
=20
 void MCPureStreamer::EmitInstToFragment(const MCInst &Inst) {
@@ -223,10 +224,10 @@
   DF->getContents().append(Code.begin(), Code.end());
 }
=20
-void MCPureStreamer::Finish() {
+void MCPureStreamer::FinishImpl() {
   // FIXME: Handle DWARF tables?
=20
-  this->MCObjectStreamer::Finish();
+  this->MCObjectStreamer::FinishImpl();
 }
=20
 MCStreamer *llvm::createPureStreamer(MCContext &Context, MCAsmBackend &MAB,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCStreamer.cpp
--- a/head/contrib/llvm/lib/MC/MCStreamer.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCStreamer.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,6 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/Twine.h"
 #include <cstdlib>
 using namespace llvm;
@@ -94,17 +93,18 @@
=20
 /// EmitULEB128Value - Special case of EmitULEB128Value that avoids the
 /// client having to pass in a MCExpr for constant integers.
-void MCStreamer::EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace) {
-  SmallString<32> Tmp;
+void MCStreamer::EmitULEB128IntValue(uint64_t Value, unsigned AddrSpace,
+                                     unsigned Padding) {
+  SmallString<128> Tmp;
   raw_svector_ostream OSE(Tmp);
-  MCObjectWriter::EncodeULEB128(Value, OSE);
+  MCObjectWriter::EncodeULEB128(Value, OSE, Padding);
   EmitBytes(OSE.str(), AddrSpace);
 }
=20
 /// EmitSLEB128Value - Special case of EmitSLEB128Value that avoids the
 /// client having to pass in a MCExpr for constant integers.
 void MCStreamer::EmitSLEB128IntValue(int64_t Value, unsigned AddrSpace) {
-  SmallString<32> Tmp;
+  SmallString<128> Tmp;
   raw_svector_ostream OSE(Tmp);
   MCObjectWriter::EncodeSLEB128(Value, OSE);
   EmitBytes(OSE.str(), AddrSpace);
@@ -128,6 +128,10 @@
                 AddrSpace);
 }
=20
+void MCStreamer::EmitGPRel64Value(const MCExpr *Value) {
+  report_fatal_error("unsupported directive in streamer");
+}
+
 void MCStreamer::EmitGPRel32Value(const MCExpr *Value) {
   report_fatal_error("unsupported directive in streamer");
 }
@@ -142,8 +146,9 @@
 }
=20
 bool MCStreamer::EmitDwarfFileDirective(unsigned FileNo,
+                                        StringRef Directory,
                                         StringRef Filename) {
-  return getContext().GetDwarfFile(Filename, FileNo) =3D=3D 0;
+  return getContext().GetDwarfFile(Directory, Filename, FileNo) =3D=3D 0;
 }
=20
 void MCStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
@@ -186,9 +191,8 @@
   if (!MAI.getSupportsDataRegions()) return;
=20
   // Generate a unique symbol name.
-  MCSymbol *NewSym =3D Context.GetOrCreateSymbol(
-      Twine(MAI.getDataBeginLabelName()) +
-        utostr(UniqueDataBeginSuffix++));
+  MCSymbol *NewSym =3D Context.GetOrCreateSymbol(MAI.getDataBeginLabelName=
() +
+                                               Twine(UniqueDataBeginSuffix=
++));
   EmitLabel(NewSym);
=20
   RegionIndicator =3D Data;
@@ -202,9 +206,8 @@
   if (!MAI.getSupportsDataRegions()) return;
=20
   // Generate a unique symbol name.
-  MCSymbol *NewSym =3D Context.GetOrCreateSymbol(
-      Twine(MAI.getCodeBeginLabelName()) +
-        utostr(UniqueCodeBeginSuffix++));
+  MCSymbol *NewSym =3D Context.GetOrCreateSymbol(MAI.getCodeBeginLabelName=
() +
+                                               Twine(UniqueCodeBeginSuffix=
++));
   EmitLabel(NewSym);
=20
   RegionIndicator =3D Code;
@@ -218,9 +221,9 @@
   if (!MAI.getSupportsDataRegions()) return;
=20
   // Generate a unique symbol name.
-  MCSymbol *NewSym =3D Context.GetOrCreateSymbol(
-      Twine(MAI.getJumpTable8BeginLabelName()) +
-        utostr(UniqueDataBeginSuffix++));
+  MCSymbol *NewSym =3D
+    Context.GetOrCreateSymbol(MAI.getJumpTable8BeginLabelName() +
+                              Twine(UniqueDataBeginSuffix++));
   EmitLabel(NewSym);
=20
   RegionIndicator =3D JumpTable8;
@@ -234,9 +237,9 @@
   if (!MAI.getSupportsDataRegions()) return;
=20
   // Generate a unique symbol name.
-  MCSymbol *NewSym =3D Context.GetOrCreateSymbol(
-      Twine(MAI.getJumpTable16BeginLabelName()) +
-        utostr(UniqueDataBeginSuffix++));
+  MCSymbol *NewSym =3D
+    Context.GetOrCreateSymbol(MAI.getJumpTable16BeginLabelName() +
+                              Twine(UniqueDataBeginSuffix++));
   EmitLabel(NewSym);
=20
   RegionIndicator =3D JumpTable16;
@@ -251,9 +254,9 @@
   if (!MAI.getSupportsDataRegions()) return;
=20
   // Generate a unique symbol name.
-  MCSymbol *NewSym =3D Context.GetOrCreateSymbol(
-      Twine(MAI.getJumpTable32BeginLabelName()) +
-        utostr(UniqueDataBeginSuffix++));
+  MCSymbol *NewSym =3D
+    Context.GetOrCreateSymbol(MAI.getJumpTable32BeginLabelName() +
+                              Twine(UniqueDataBeginSuffix++));
   EmitLabel(NewSym);
=20
   RegionIndicator =3D JumpTable32;
@@ -277,8 +280,17 @@
     report_fatal_error("Starting a frame before finishing the previous one=
!");
=20
   MCDwarfFrameInfo Frame;
+  EmitCFIStartProcImpl(Frame);
+
+  FrameInfos.push_back(Frame);
+  RegionIndicator =3D Code;
+}
+
+void MCStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
+}
+
+void MCStreamer::RecordProcStart(MCDwarfFrameInfo &Frame) {
   Frame.Function =3D LastSymbol;
-
   // If the function is externally visible, we need to create a local
   // symbol to avoid relocations.
   StringRef Prefix =3D getContext().getAsmInfo().getPrivateGlobalPrefix();
@@ -288,16 +300,20 @@
     Frame.Begin =3D getContext().CreateTempSymbol();
     EmitLabel(Frame.Begin);
   }
-
-  FrameInfos.push_back(Frame);
-  RegionIndicator =3D Code;
 }
=20
 void MCStreamer::EmitCFIEndProc() {
   EnsureValidFrame();
   MCDwarfFrameInfo *CurFrame =3D getCurrentFrameInfo();
-  CurFrame->End =3D getContext().CreateTempSymbol();
-  EmitLabel(CurFrame->End);
+  EmitCFIEndProcImpl(*CurFrame);
+}
+
+void MCStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
+}
+
+void MCStreamer::RecordProcEnd(MCDwarfFrameInfo &Frame) {
+  Frame.End =3D getContext().CreateTempSymbol();
+  EmitLabel(Frame.End);
 }
=20
 void MCStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
@@ -386,7 +402,7 @@
   MCDwarfFrameInfo *CurFrame =3D getCurrentFrameInfo();
   MCSymbol *Label =3D getContext().CreateTempSymbol();
   EmitLabel(Label);
-  MCCFIInstruction Instruction(MCCFIInstruction::Remember, Label);
+  MCCFIInstruction Instruction(MCCFIInstruction::RememberState, Label);
   CurFrame->Instructions.push_back(Instruction);
 }
=20
@@ -396,7 +412,7 @@
   MCDwarfFrameInfo *CurFrame =3D getCurrentFrameInfo();
   MCSymbol *Label =3D getContext().CreateTempSymbol();
   EmitLabel(Label);
-  MCCFIInstruction Instruction(MCCFIInstruction::Restore, Label);
+  MCCFIInstruction Instruction(MCCFIInstruction::RestoreState, Label);
   CurFrame->Instructions.push_back(Instruction);
 }
=20
@@ -409,6 +425,30 @@
   CurFrame->Instructions.push_back(Instruction);
 }
=20
+void MCStreamer::EmitCFIRestore(int64_t Register) {
+  EnsureValidFrame();
+  MCDwarfFrameInfo *CurFrame =3D getCurrentFrameInfo();
+  MCSymbol *Label =3D getContext().CreateTempSymbol();
+  EmitLabel(Label);
+  MCCFIInstruction Instruction(MCCFIInstruction::Restore, Label, Register);
+  CurFrame->Instructions.push_back(Instruction);
+}
+
+void MCStreamer::EmitCFIEscape(StringRef Values) {
+  EnsureValidFrame();
+  MCDwarfFrameInfo *CurFrame =3D getCurrentFrameInfo();
+  MCSymbol *Label =3D getContext().CreateTempSymbol();
+  EmitLabel(Label);
+  MCCFIInstruction Instruction(MCCFIInstruction::Escape, Label, Values);
+  CurFrame->Instructions.push_back(Instruction);
+}
+
+void MCStreamer::EmitCFISignalFrame() {
+  EnsureValidFrame();
+  MCDwarfFrameInfo *CurFrame =3D getCurrentFrameInfo();
+  CurFrame->IsSignalFrame =3D true;
+}
+
 void MCStreamer::setCurrentW64UnwindInfo(MCWin64EHUnwindInfo *Frame) {
   W64UnwindInfos.push_back(Frame);
   CurrentW64UnwindInfo =3D W64UnwindInfos.back();
@@ -559,6 +599,10 @@
   EmitLabel(CurFrame->PrologEnd);
 }
=20
+void MCStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) {
+  llvm_unreachable("This file format doesn't support this directive");
+}
+
 void MCStreamer::EmitFnStart() {
   errs() << "Not implemented yet\n";
   abort();
@@ -631,3 +675,10 @@
=20
   MCWin64EHUnwindEmitter::Emit(*this);
 }
+
+void MCStreamer::Finish() {
+  if (!FrameInfos.empty() && !FrameInfos.back().End)
+    report_fatal_error("Unfinished frame!");
+
+  FinishImpl();
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MCSymbol.cpp
--- a/head/contrib/llvm/lib/MC/MCSymbol.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/MC/MCSymbol.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -54,17 +54,14 @@
 void MCSymbol::setVariableValue(const MCExpr *Value) {
   assert(!IsUsed && "Cannot set a variable that has already been used.");
   assert(Value && "Invalid variable value!");
-  assert((isUndefined() || (isAbsolute() && isa<MCConstantExpr>(Value))) &&
-         "Invalid redefinition!");
   this->Value =3D Value;
=20
   // Variables should always be marked as in the same "section" as the val=
ue.
   const MCSection *Section =3D Value->FindAssociatedSection();
-  if (Section) {
+  if (Section)
     setSection(*Section);
-  } else {
+  else
     setUndefined();
-  }
 }
=20
 void MCSymbol::print(raw_ostream &OS) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/MachObjectWri=
ter.cpp
--- a/head/contrib/llvm/lib/MC/MachObjectWriter.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/MC/MachObjectWriter.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -8,13 +8,13 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/MC/MCMachObjectWriter.h"
-#include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCAsmLayout.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCFixupKindInfo.h"
 #include "llvm/MC/MCObjectWriter.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/MC/MCSymbol.h"
@@ -584,9 +584,16 @@
     // requires the compiler to use .set to absolutize the differences bet=
ween
     // symbols which the compiler knows to be assembly time constants, so =
we
     // don't need to worry about considering symbol differences fully reso=
lved.
+    //
+    // If the file isn't using sub-sections-via-symbols, we can make the
+    // same assumptions about any symbol that we normally make about
+    // assembler locals.
=20
     if (!Asm.getBackend().hasReliableSymbolDifference()) {
-      if (!SA.isTemporary() || !SA.isInSection() || &SecA !=3D &SecB)
+      if (!SA.isInSection() || &SecA !=3D &SecB ||
+          (!SA.isTemporary() &&
+           FB.getAtom() !=3D Asm.getSymbolData(SA).getFragment()->getAtom(=
) &&
+           Asm.getSubsectionsViaSymbols()))
         return false;
       return true;
     }
@@ -628,7 +635,7 @@
 }
=20
 void MachObjectWriter::WriteObject(MCAssembler &Asm,
-				   const MCAsmLayout &Layout) {
+                                   const MCAsmLayout &Layout) {
   unsigned NumSections =3D Asm.size();
=20
   // The section data starts after the header, the segment load command (a=
nd
@@ -731,7 +738,7 @@
   // Write the actual section data.
   for (MCAssembler::const_iterator it =3D Asm.begin(),
          ie =3D Asm.end(); it !=3D ie; ++it) {
-    Asm.WriteSectionData(it, Layout);
+    Asm.writeSectionData(it, Layout);
=20
     uint64_t Pad =3D getPaddingSize(it, Layout);
     for (unsigned int i =3D 0; i < Pad; ++i)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/SubtargetFeat=
ure.cpp
--- a/head/contrib/llvm/lib/MC/SubtargetFeature.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/MC/SubtargetFeature.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -13,8 +13,8 @@
=20
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Format.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/StringExtras.h"
 #include <algorithm>
 #include <cassert>
 #include <cctype>
@@ -114,7 +114,7 @@
   // Don't add empty features
   if (!String.empty()) {
     // Convert to lowercase, prepend flag and add to vector
-    Features.push_back(PrependFlag(LowercaseString(String), IsEnabled));
+    Features.push_back(PrependFlag(String.lower(), IsEnabled));
   }
 }
=20
@@ -154,21 +154,19 @@
   // Print the CPU table.
   errs() << "Available CPUs for this target:\n\n";
   for (size_t i =3D 0; i !=3D CPUTableSize; i++)
-    errs() << "  " << CPUTable[i].Key
-         << std::string(MaxCPULen - std::strlen(CPUTable[i].Key), ' ')
-         << " - " << CPUTable[i].Desc << ".\n";
-  errs() << "\n";
- =20
+    errs() << format("  %-*s - %s.\n",
+                     MaxCPULen, CPUTable[i].Key, CPUTable[i].Desc);
+  errs() << '\n';
+
   // Print the Feature table.
   errs() << "Available features for this target:\n\n";
   for (size_t i =3D 0; i !=3D FeatTableSize; i++)
-    errs() << "  " << FeatTable[i].Key
-         << std::string(MaxFeatLen - std::strlen(FeatTable[i].Key), ' ')
-         << " - " << FeatTable[i].Desc << ".\n";
-  errs() << "\n";
- =20
+    errs() << format("  %-*s - %s.\n",
+                     MaxFeatLen, FeatTable[i].Key, FeatTable[i].Desc);
+  errs() << '\n';
+
   errs() << "Use +feature to enable a feature, or -feature to disable it.\=
n"
-       << "For example, llc -mcpu=3Dmycpu -mattr=3D+feature1,-feature2\n";
+            "For example, llc -mcpu=3Dmycpu -mattr=3D+feature1,-feature2\n=
";
   std::exit(1);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/WinCOFFObject=
Writer.cpp
--- a/head/contrib/llvm/lib/MC/WinCOFFObjectWriter.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/MC/WinCOFFObjectWriter.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -22,8 +22,10 @@
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCAsmLayout.h"
 #include "llvm/MC/MCSectionCOFF.h"
+#include "llvm/MC/MCWinCOFFObjectWriter.h"
=20
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
=20
@@ -33,8 +35,6 @@
=20
 #include "llvm/Support/TimeValue.h"
=20
-#include "../Target/X86/MCTargetDesc/X86FixupKinds.h"
-
 #include <cstdio>
=20
 using namespace llvm;
@@ -128,8 +128,9 @@
   typedef DenseMap<MCSymbol  const *, COFFSymbol *>   symbol_map;
   typedef DenseMap<MCSection const *, COFFSection *> section_map;
=20
+  llvm::OwningPtr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
+
   // Root level file contents.
-  bool Is64Bit;
   COFF::header Header;
   sections     Sections;
   symbols      Symbols;
@@ -139,7 +140,7 @@
   section_map SectionMap;
   symbol_map  SymbolMap;
=20
-  WinCOFFObjectWriter(raw_ostream &OS, bool is64Bit);
+  WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
   ~WinCOFFObjectWriter();
=20
   COFFSymbol *createSymbol(StringRef Name);
@@ -281,6 +282,7 @@
   // The string table data begins with the length of the entire string tab=
le
   // including the length header. Allocate space for this header.
   Data.resize(4);
+  update_length();
 }
=20
 size_t StringTable::size() const {
@@ -313,13 +315,13 @@
 //------------------------------------------------------------------------=
------
 // WinCOFFObjectWriter class implementation
=20
-WinCOFFObjectWriter::WinCOFFObjectWriter(raw_ostream &OS, bool is64Bit)
+WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
+                                         raw_ostream &OS)
   : MCObjectWriter(OS, true)
-  , Is64Bit(is64Bit) {
+  , TargetObjectWriter(MOTW) {
   memset(&Header, 0, sizeof(Header));
=20
-  Is64Bit ? Header.Machine =3D COFF::IMAGE_FILE_MACHINE_AMD64
-          : Header.Machine =3D COFF::IMAGE_FILE_MACHINE_I386;
+  Header.Machine =3D TargetObjectWriter->getMachine();
 }
=20
 WinCOFFObjectWriter::~WinCOFFObjectWriter() {
@@ -694,30 +696,13 @@
   if (CrossSection)
     FixupKind =3D FK_PCRel_4;
=20
-  switch (FixupKind) {
-  case FK_PCRel_4:
-  case X86::reloc_riprel_4byte:
-  case X86::reloc_riprel_4byte_movq_load:
-    Reloc.Data.Type =3D Is64Bit ? COFF::IMAGE_REL_AMD64_REL32
-                              : COFF::IMAGE_REL_I386_REL32;
-    // FIXME: Can anyone explain what this does other than adjust for the =
size
-    // of the offset?
+  Reloc.Data.Type =3D TargetObjectWriter->getRelocType(FixupKind);
+
+  // FIXME: Can anyone explain what this does other than adjust for the si=
ze
+  // of the offset?
+  if (Reloc.Data.Type =3D=3D COFF::IMAGE_REL_AMD64_REL32 ||
+      Reloc.Data.Type =3D=3D COFF::IMAGE_REL_I386_REL32)
     FixedValue +=3D 4;
-    break;
-  case FK_Data_4:
-  case X86::reloc_signed_4byte:
-    Reloc.Data.Type =3D Is64Bit ? COFF::IMAGE_REL_AMD64_ADDR32
-                              : COFF::IMAGE_REL_I386_DIR32;
-    break;
-  case FK_Data_8:
-    if (Is64Bit)
-      Reloc.Data.Type =3D COFF::IMAGE_REL_AMD64_ADDR64;
-    else
-      llvm_unreachable("unsupported relocation type");
-    break;
-  default:
-    llvm_unreachable("unsupported relocation type");
-  }
=20
   coff_section->Relocations.push_back(Reloc);
 }
@@ -798,9 +783,22 @@
     }
=20
     if (Sec->Relocations.size() > 0) {
-      Sec->Header.NumberOfRelocations =3D Sec->Relocations.size();
+      bool RelocationsOverflow =3D Sec->Relocations.size() >=3D 0xffff;
+
+      if (RelocationsOverflow) {
+        // Signal overflow by setting NumberOfSections to max value. Actual
+        // size is found in reloc #0. Microsoft tools understand this.
+        Sec->Header.NumberOfRelocations =3D 0xffff;
+      } else {
+        Sec->Header.NumberOfRelocations =3D Sec->Relocations.size();
+      }
       Sec->Header.PointerToRelocations =3D offset;
=20
+      if (RelocationsOverflow) {
+        // Reloc #0 will contain actual count, so make room for it.
+        offset +=3D COFF::RelocationSize;
+      }
+
       offset +=3D COFF::RelocationSize * Sec->Relocations.size();
=20
       for (relocations::iterator cr =3D Sec->Relocations.begin(),
@@ -835,8 +833,12 @@
     MCAssembler::const_iterator j, je;
=20
     for (i =3D Sections.begin(), ie =3D Sections.end(); i !=3D ie; i++)
-      if ((*i)->Number !=3D -1)
+      if ((*i)->Number !=3D -1) {
+        if ((*i)->Relocations.size() >=3D 0xffff) {
+          (*i)->Header.Characteristics |=3D COFF::IMAGE_SCN_LNK_NRELOC_OVF=
L;
+        }
         WriteSectionHeader((*i)->Header);
+      }
=20
     for (i =3D Sections.begin(), ie =3D Sections.end(),
          j =3D Asm.begin(), je =3D Asm.end();
@@ -849,13 +851,23 @@
         assert(OS.tell() =3D=3D (*i)->Header.PointerToRawData &&
                "Section::PointerToRawData is insane!");
=20
-        Asm.WriteSectionData(j, Layout);
+        Asm.writeSectionData(j, Layout);
       }
=20
       if ((*i)->Relocations.size() > 0) {
         assert(OS.tell() =3D=3D (*i)->Header.PointerToRelocations &&
                "Section::PointerToRelocations is insane!");
=20
+        if ((*i)->Relocations.size() >=3D 0xffff) {
+          // In case of overflow, write actual relocation count as first
+          // relocation. Including the synthetic reloc itself (+ 1).
+          COFF::relocation r;
+          r.VirtualAddress =3D (*i)->Relocations.size() + 1;
+          r.SymbolTableIndex =3D 0;
+          r.Type =3D 0;
+          WriteRelocation(r);
+        }
+
         for (relocations::const_iterator k =3D (*i)->Relocations.begin(),
                                                ke =3D (*i)->Relocations.en=
d();
                                                k !=3D ke; k++) {
@@ -877,11 +889,16 @@
   OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
 }
=20
+MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_=
) :
+  Machine(Machine_) {
+}
+
 //------------------------------------------------------------------------=
------
 // WinCOFFObjectWriter factory function
=20
 namespace llvm {
-  MCObjectWriter *createWinCOFFObjectWriter(raw_ostream &OS, bool is64Bit)=
 {
-    return new WinCOFFObjectWriter(OS, is64Bit);
+  MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *M=
OTW,
+                                            raw_ostream &OS) {
+    return new WinCOFFObjectWriter(MOTW, OS);
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/MC/WinCOFFStream=
er.cpp
--- a/head/contrib/llvm/lib/MC/WinCOFFStreamer.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/MC/WinCOFFStreamer.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -25,13 +25,13 @@
 #include "llvm/MC/MCSectionCOFF.h"
 #include "llvm/MC/MCWin64EH.h"
 #include "llvm/MC/MCAsmBackend.h"
-#include "llvm/ADT/StringMap.h"
=20
 #include "llvm/Support/COFF.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/raw_ostream.h"
+
 using namespace llvm;
=20
 namespace {
@@ -60,6 +60,7 @@
   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
   virtual void EmitCOFFSymbolType(int Type);
   virtual void EndCOFFSymbolDef();
+  virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
                                 unsigned ByteAlignment);
@@ -77,7 +78,7 @@
   virtual void EmitFileDirective(StringRef Filename);
   virtual void EmitInstruction(const MCInst &Instruction);
   virtual void EmitWin64EHHandlerData();
-  virtual void Finish();
+  virtual void FinishImpl();
=20
 private:
   virtual void EmitInstToFragment(const MCInst &Inst) {
@@ -251,7 +252,6 @@
=20
   default:
     llvm_unreachable("unsupported attribute");
-    break;
   }
 }
=20
@@ -293,6 +293,16 @@
   CurSymbol =3D NULL;
 }
=20
+void WinCOFFStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol)
+{
+  MCDataFragment *DF =3D getOrCreateDataFragment();
+
+  DF->addFixup(MCFixup::Create(DF->getContents().size(),
+                               MCSymbolRefExpr::Create (Symbol, getContext=
 ()),
+                               FK_SecRel_4));
+  DF->getContents().resize(DF->getContents().size() + 4, 0);
+}
+
 void WinCOFFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
   llvm_unreachable("not implemented");
 }
@@ -389,9 +399,9 @@
   MCWin64EHUnwindEmitter::EmitUnwindInfo(*this, getCurrentW64UnwindInfo());
 }
=20
-void WinCOFFStreamer::Finish() {
+void WinCOFFStreamer::FinishImpl() {
   EmitW64Tables();
-  MCObjectStreamer::Finish();
+  MCObjectStreamer::FinishImpl();
 }
=20
 namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Object/Archive.c=
pp
--- a/head/contrib/llvm/lib/Object/Archive.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Object/Archive.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,14 +13,15 @@
=20
 #include "llvm/Object/Archive.h"
 #include "llvm/ADT/APInt.h"
+#include "llvm/Support/Endian.h"
 #include "llvm/Support/MemoryBuffer.h"
=20
 using namespace llvm;
 using namespace object;
=20
+static const char *Magic =3D "!<arch>\n";
+
 namespace {
-const StringRef Magic =3D "!<arch>\n";
-
 struct ArchiveMemberHeader {
   char Name[16];
   char LastModified[12];
@@ -32,7 +33,11 @@
=20
   ///! Get the name without looking up long names.
   StringRef getName() const {
-    char EndCond =3D Name[0] =3D=3D '/' ? ' ' : '/';
+    char EndCond;
+    if (Name[0] =3D=3D '/' || Name[0] =3D=3D '#')
+      EndCond =3D ' ';
+    else
+      EndCond =3D '/';
     StringRef::size_type end =3D StringRef(Name, sizeof(Name)).find(EndCon=
d);
     if (end =3D=3D StringRef::npos)
       end =3D sizeof(Name);
@@ -47,12 +52,30 @@
     return ret.getZExtValue();
   }
 };
+}
=20
-const ArchiveMemberHeader *ToHeader(const char *base) {
+static const ArchiveMemberHeader *ToHeader(const char *base) {
   return reinterpret_cast<const ArchiveMemberHeader *>(base);
 }
+
+
+static bool isInternalMember(const ArchiveMemberHeader &amh) {
+  const char *internals[] =3D {
+    "/",
+    "//",
+    "#_LLVM_SYM_TAB_#"
+    };
+
+  StringRef name =3D amh.getName();
+  for (std::size_t i =3D 0; i < sizeof(internals) / sizeof(*internals); ++=
i) {
+    if (name =3D=3D internals[i])
+      return true;
+  }
+  return false;
 }
=20
+void Archive::anchor() { }
+
 Archive::Child Archive::Child::getNext() const {
   size_t SpaceToSkip =3D sizeof(ArchiveMemberHeader) +
     ToHeader(Data.data())->getSize();
@@ -101,6 +124,11 @@
       return object_error::parse_failed;
     Result =3D addr;
     return object_error::success;
+  } else if (name.startswith("#1/")) {
+    APInt name_size;
+    name.substr(3).getAsInteger(10, name_size);
+    Result =3D Data.substr(0, name_size.getZExtValue());
+    return object_error::success;
   }
   // It's a simple name.
   if (name[name.size() - 1] =3D=3D '/')
@@ -111,14 +139,27 @@
 }
=20
 uint64_t Archive::Child::getSize() const {
-  return ToHeader(Data.data())->getSize();
+  uint64_t size =3D ToHeader(Data.data())->getSize();
+  // Don't include attached name.
+  StringRef name =3D  ToHeader(Data.data())->getName();
+  if (name.startswith("#1/")) {
+    APInt name_size;
+    name.substr(3).getAsInteger(10, name_size);
+    size -=3D name_size.getZExtValue();
+  }
+  return size;
 }
=20
 MemoryBuffer *Archive::Child::getBuffer() const {
   StringRef name;
   if (getName(name)) return NULL;
-  return MemoryBuffer::getMemBuffer(Data.substr(sizeof(ArchiveMemberHeader=
),
-                                                getSize()),
+  int size =3D sizeof(ArchiveMemberHeader);
+  if (name.startswith("#1/")) {
+    APInt name_size;
+    name.substr(3).getAsInteger(10, name_size);
+    size +=3D name_size.getZExtValue();
+  }
+  return MemoryBuffer::getMemBuffer(Data.substr(size, getSize()),
                                     name,
                                     false);
 }
@@ -133,8 +174,7 @@
 }
=20
 Archive::Archive(MemoryBuffer *source, error_code &ec)
-  : Binary(Binary::isArchive, source)
-  , StringTable(Child(this, StringRef(0, 0))) {
+  : Binary(Binary::ID_Archive, source) {
   // Check for sufficient magic.
   if (!source || source->getBufferSize()
                  < (8 + sizeof(ArchiveMemberHeader) + 2) // Smallest archi=
ve.
@@ -143,30 +183,90 @@
     return;
   }
=20
-  // Get the string table. It's the 3rd member.
-  child_iterator StrTable =3D begin_children();
+  // Get the special members.
+  child_iterator i =3D begin_children(false);
   child_iterator e =3D end_children();
-  for (int i =3D 0; StrTable !=3D e && i < 2; ++StrTable, ++i) {}
=20
-  // Check to see if there were 3 members, or the 3rd member wasn't named =
"//".
-  StringRef name;
-  if (StrTable !=3D e && !StrTable->getName(name) && name =3D=3D "//")
-    StringTable =3D StrTable;
+  if (i !=3D e) ++i; // Nobody cares about the first member.
+  if (i !=3D e) {
+    SymbolTable =3D i;
+    ++i;
+  }
+  if (i !=3D e) {
+    StringTable =3D i;
+  }
=20
   ec =3D object_error::success;
 }
=20
-Archive::child_iterator Archive::begin_children() const {
-  const char *Loc =3D Data->getBufferStart() + Magic.size();
+Archive::child_iterator Archive::begin_children(bool skip_internal) const {
+  const char *Loc =3D Data->getBufferStart() + strlen(Magic);
   size_t Size =3D sizeof(ArchiveMemberHeader) +
     ToHeader(Loc)->getSize();
-  return Child(this, StringRef(Loc, Size));
+  Child c(this, StringRef(Loc, Size));
+  // Skip internals at the beginning of an archive.
+  if (skip_internal && isInternalMember(*ToHeader(Loc)))
+    return c.getNext();
+  return c;
 }
=20
 Archive::child_iterator Archive::end_children() const {
   return Child(this, StringRef(0, 0));
 }
=20
-namespace llvm {
+error_code Archive::Symbol::getName(StringRef &Result) const {
+  Result =3D
+    StringRef(Parent->SymbolTable->getBuffer()->getBufferStart() + StringI=
ndex);
+  return object_error::success;
+}
=20
-} // end namespace llvm
+error_code Archive::Symbol::getMember(child_iterator &Result) const {
+  const char *buf =3D Parent->SymbolTable->getBuffer()->getBufferStart();
+  uint32_t member_count =3D *reinterpret_cast<const support::ulittle32_t*>=
(buf);
+  const char *offsets =3D buf + 4;
+  buf +=3D 4 + (member_count * 4); // Skip offsets.
+  const char *indicies =3D buf + 4;
+
+  uint16_t offsetindex =3D
+    *(reinterpret_cast<const support::ulittle16_t*>(indicies)
+      + SymbolIndex);
+
+  uint32_t offset =3D *(reinterpret_cast<const support::ulittle32_t*>(offs=
ets)
+                      + (offsetindex - 1));
+
+  const char *Loc =3D Parent->getData().begin() + offset;
+  size_t Size =3D sizeof(ArchiveMemberHeader) +
+    ToHeader(Loc)->getSize();
+  Result =3D Child(Parent, StringRef(Loc, Size));
+
+  return object_error::success;
+}
+
+Archive::Symbol Archive::Symbol::getNext() const {
+  Symbol t(*this);
+  // Go to one past next null.
+  t.StringIndex =3D
+    Parent->SymbolTable->getBuffer()->getBuffer().find('\0', t.StringIndex=
) + 1;
+  ++t.SymbolIndex;
+  return t;
+}
+
+Archive::symbol_iterator Archive::begin_symbols() const {
+  const char *buf =3D SymbolTable->getBuffer()->getBufferStart();
+  uint32_t member_count =3D *reinterpret_cast<const support::ulittle32_t*>=
(buf);
+  buf +=3D 4 + (member_count * 4); // Skip offsets.
+  uint32_t symbol_count =3D *reinterpret_cast<const support::ulittle32_t*>=
(buf);
+  buf +=3D 4 + (symbol_count * 2); // Skip indices.
+  uint32_t string_start_offset =3D
+    buf - SymbolTable->getBuffer()->getBufferStart();
+  return symbol_iterator(Symbol(this, 0, string_start_offset));
+}
+
+Archive::symbol_iterator Archive::end_symbols() const {
+  const char *buf =3D SymbolTable->getBuffer()->getBufferStart();
+  uint32_t member_count =3D *reinterpret_cast<const support::ulittle32_t*>=
(buf);
+  buf +=3D 4 + (member_count * 4); // Skip offsets.
+  uint32_t symbol_count =3D *reinterpret_cast<const support::ulittle32_t*>=
(buf);
+  return symbol_iterator(
+    Symbol(this, symbol_count, 0));
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Object/COFFObjec=
tFile.cpp
--- a/head/contrib/llvm/lib/Object/COFFObjectFile.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Object/COFFObjectFile.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -12,6 +12,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Object/COFF.h"
+#include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Triple.h"
@@ -98,24 +99,28 @@
  error_code COFFObjectFile::getSymbolName(DataRefImpl Symb,
                                           StringRef &Result) const {
   const coff_symbol *symb =3D toSymb(Symb);
-  // Check for string table entry. First 4 bytes are 0.
-  if (symb->Name.Offset.Zeroes =3D=3D 0) {
-    uint32_t Offset =3D symb->Name.Offset.Offset;
-    if (error_code ec =3D getString(Offset, Result))
-      return ec;
-    return object_error::success;
-  }
+  return getSymbolName(symb, Result);
+}
=20
-  if (symb->Name.ShortName[7] =3D=3D 0)
-    // Null terminated, let ::strlen figure out the length.
-    Result =3D StringRef(symb->Name.ShortName);
+error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Symb,
+                                            uint64_t &Result) const {
+  const coff_symbol *symb =3D toSymb(Symb);
+  const coff_section *Section =3D NULL;
+  if (error_code ec =3D getSection(symb->SectionNumber, Section))
+    return ec;
+  char Type;
+  if (error_code ec =3D getSymbolNMTypeChar(Symb, Type))
+    return ec;
+  if (Type =3D=3D 'U' || Type =3D=3D 'w')
+    Result =3D UnknownAddressOrSize;
+  else if (Section)
+    Result =3D Section->PointerToRawData + symb->Value;
   else
-    // Not null terminated, use all 8 bytes.
-    Result =3D StringRef(symb->Name.ShortName, 8);
+    Result =3D symb->Value;
   return object_error::success;
 }
=20
-error_code COFFObjectFile::getSymbolOffset(DataRefImpl Symb,
+error_code COFFObjectFile::getSymbolAddress(DataRefImpl Symb,
                                             uint64_t &Result) const {
   const coff_symbol *symb =3D toSymb(Symb);
   const coff_section *Section =3D NULL;
@@ -133,35 +138,15 @@
   return object_error::success;
 }
=20
-error_code COFFObjectFile::getSymbolAddress(DataRefImpl Symb,
-                                            uint64_t &Result) const {
-  const coff_symbol *symb =3D toSymb(Symb);
-  const coff_section *Section =3D NULL;
-  if (error_code ec =3D getSection(symb->SectionNumber, Section))
-    return ec;
-  char Type;
-  if (error_code ec =3D getSymbolNMTypeChar(Symb, Type))
-    return ec;
-  if (Type =3D=3D 'U' || Type =3D=3D 'w')
-    Result =3D UnknownAddressOrSize;
-  else if (Section)
-    Result =3D reinterpret_cast<uintptr_t>(base() +
-                                         Section->PointerToRawData +
-                                         symb->Value);
-  else
-    Result =3D reinterpret_cast<uintptr_t>(base() + symb->Value);
-  return object_error::success;
-}
-
 error_code COFFObjectFile::getSymbolType(DataRefImpl Symb,
-                                         SymbolRef::SymbolType &Result) co=
nst {
+                                         SymbolRef::Type &Result) const {
   const coff_symbol *symb =3D toSymb(Symb);
   Result =3D SymbolRef::ST_Other;
   if (symb->StorageClass =3D=3D COFF::IMAGE_SYM_CLASS_EXTERNAL &&
       symb->SectionNumber =3D=3D COFF::IMAGE_SYM_UNDEFINED) {
-    Result =3D SymbolRef::ST_External;
+    Result =3D SymbolRef::ST_Unknown;
   } else {
-    if (symb->Type.ComplexType =3D=3D COFF::IMAGE_SYM_DTYPE_FUNCTION) {
+    if (symb->getComplexType() =3D=3D COFF::IMAGE_SYM_DTYPE_FUNCTION) {
       Result =3D SymbolRef::ST_Function;
     } else {
       char Type;
@@ -175,10 +160,27 @@
   return object_error::success;
 }
=20
-error_code COFFObjectFile::isSymbolGlobal(DataRefImpl Symb,
-                                          bool &Result) const {
+error_code COFFObjectFile::getSymbolFlags(DataRefImpl Symb,
+                                          uint32_t &Result) const {
   const coff_symbol *symb =3D toSymb(Symb);
-  Result =3D (symb->StorageClass =3D=3D COFF::IMAGE_SYM_CLASS_EXTERNAL);
+  Result =3D SymbolRef::SF_None;
+
+  // TODO: Correctly set SF_FormatSpecific, SF_ThreadLocal, SF_Common
+
+  if (symb->StorageClass =3D=3D COFF::IMAGE_SYM_CLASS_EXTERNAL &&
+      symb->SectionNumber =3D=3D COFF::IMAGE_SYM_UNDEFINED)
+    Result |=3D SymbolRef::SF_Undefined;
+
+  // TODO: This are certainly too restrictive.
+  if (symb->StorageClass =3D=3D COFF::IMAGE_SYM_CLASS_EXTERNAL)
+    Result |=3D SymbolRef::SF_Global;
+
+  if (symb->StorageClass =3D=3D COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
+    Result |=3D SymbolRef::SF_Weak;
+
+  if (symb->SectionNumber =3D=3D COFF::IMAGE_SYM_ABSOLUTE)
+    Result |=3D SymbolRef::SF_Absolute;
+
   return object_error::success;
 }
=20
@@ -233,7 +235,9 @@
     if (symb->StorageClass =3D=3D COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) {
       Result =3D 'w';
       return object_error::success; // Don't do ::toupper.
-    } else
+    } else if (symb->Value !=3D 0) // Check for common symbols.
+      ret =3D 'c';
+    else
       ret =3D 'u';
     break;
   case COFF::IMAGE_SYM_ABSOLUTE:
@@ -269,9 +273,18 @@
   return object_error::success;
 }
=20
-error_code COFFObjectFile::isSymbolInternal(DataRefImpl Symb,
-                                            bool &Result) const {
-  Result =3D false;
+error_code COFFObjectFile::getSymbolSection(DataRefImpl Symb,
+                                            section_iterator &Result) cons=
t {
+  const coff_symbol *symb =3D toSymb(Symb);
+  if (symb->SectionNumber <=3D COFF::IMAGE_SYM_UNDEFINED)
+    Result =3D end_sections();
+  else {
+    const coff_section *sec =3D 0;
+    if (error_code ec =3D getSection(symb->SectionNumber, sec)) return ec;
+    DataRefImpl Sec;
+    Sec.p =3D reinterpret_cast<uintptr_t>(sec);
+    Result =3D section_iterator(SectionRef(Sec, this));
+  }
   return object_error::success;
 }
=20
@@ -287,24 +300,7 @@
 error_code COFFObjectFile::getSectionName(DataRefImpl Sec,
                                           StringRef &Result) const {
   const coff_section *sec =3D toSec(Sec);
-  StringRef name;
-  if (sec->Name[7] =3D=3D 0)
-    // Null terminated, let ::strlen figure out the length.
-    name =3D sec->Name;
-  else
-    // Not null terminated, use all 8 bytes.
-    name =3D StringRef(sec->Name, 8);
-
-  // Check for string table entry. First byte is '/'.
-  if (name[0] =3D=3D '/') {
-    uint32_t Offset;
-    name.substr(1).getAsInteger(10, Offset);
-    if (error_code ec =3D getString(Offset, name))
-      return ec;
-  }
-
-  Result =3D name;
-  return object_error::success;
+  return getSectionName(sec, Result);
 }
=20
 error_code COFFObjectFile::getSectionAddress(DataRefImpl Sec,
@@ -324,16 +320,10 @@
 error_code COFFObjectFile::getSectionContents(DataRefImpl Sec,
                                               StringRef &Result) const {
   const coff_section *sec =3D toSec(Sec);
-  // The only thing that we need to verify is that the contents is contain=
ed
-  // within the file bounds. We don't need to make sure it doesn't cover o=
ther
-  // data, as there's nothing that says that is not allowed.
-  uintptr_t con_start =3D uintptr_t(base()) + sec->PointerToRawData;
-  uintptr_t con_end =3D con_start + sec->SizeOfRawData;
-  if (con_end >=3D uintptr_t(Data->getBufferEnd()))
-    return object_error::parse_failed;
-  Result =3D StringRef(reinterpret_cast<const char*>(con_start),
-                     sec->SizeOfRawData);
-  return object_error::success;
+  ArrayRef<uint8_t> Res;
+  error_code EC =3D getSectionContents(sec, Res);
+  Result =3D StringRef(reinterpret_cast<const char*>(Res.data()), Res.size=
());
+  return EC;
 }
=20
 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Sec,
@@ -366,12 +356,33 @@
   return object_error::success;
 }
=20
+error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
+                                                         bool &Result) con=
st {
+  // FIXME: Unimplemented
+  Result =3D true;
+  return object_error::success;
+}
+
+error_code COFFObjectFile::isSectionVirtual(DataRefImpl Sec,
+                                           bool &Result) const {
+  const coff_section *sec =3D toSec(Sec);
+  Result =3D sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
+  return object_error::success;
+}
+
+error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Sec,
+                                             bool &Result) const {
+  // FIXME: Unimplemented
+  Result =3D false;
+  return object_error::success;
+}
+
 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl Sec,
                                                  DataRefImpl Symb,
                                                  bool &Result) const {
   const coff_section *sec =3D toSec(Sec);
   const coff_symbol *symb =3D toSymb(Symb);
-  const coff_section *symb_sec;
+  const coff_section *symb_sec =3D 0;
   if (error_code ec =3D getSection(symb->SectionNumber, symb_sec)) return =
ec;
   if (symb_sec =3D=3D sec)
     Result =3D true;
@@ -383,7 +394,6 @@
 relocation_iterator COFFObjectFile::getSectionRelBegin(DataRefImpl Sec) co=
nst {
   const coff_section *sec =3D toSec(Sec);
   DataRefImpl ret;
-  std::memset(&ret, 0, sizeof(ret));
   if (sec->NumberOfRelocations =3D=3D 0)
     ret.p =3D 0;
   else
@@ -395,7 +405,6 @@
 relocation_iterator COFFObjectFile::getSectionRelEnd(DataRefImpl Sec) cons=
t {
   const coff_section *sec =3D toSec(Sec);
   DataRefImpl ret;
-  std::memset(&ret, 0, sizeof(ret));
   if (sec->NumberOfRelocations =3D=3D 0)
     ret.p =3D 0;
   else
@@ -408,7 +417,12 @@
 }
=20
 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &ec)
-  : ObjectFile(Binary::isCOFF, Object, ec) {
+  : ObjectFile(Binary::ID_COFF, Object, ec)
+  , Header(0)
+  , SectionTable(0)
+  , SymbolTable(0)
+  , StringTable(0)
+  , StringTableSize(0) {
   // Check that we at least have enough room for a header.
   if (!checkSize(Data, ec, sizeof(coff_file_header))) return;
=20
@@ -421,7 +435,7 @@
     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
     // PE signature to find 'normal' COFF header.
     if (!checkSize(Data, ec, 0x3c + 8)) return;
-    HeaderStart +=3D *reinterpret_cast<const ulittle32_t *>(base() + 0x3c);
+    HeaderStart =3D *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
     // Check the PE header. ("PE\0\0")
     if (std::memcmp(base() + HeaderStart, "PE\0\0", 4) !=3D 0) {
       ec =3D object_error::parse_failed;
@@ -443,28 +457,30 @@
                  Header->NumberOfSections * sizeof(coff_section)))
     return;
=20
-  SymbolTable =3D
-    reinterpret_cast<const coff_symbol *>(base()
-                                          + Header->PointerToSymbolTable);
-  if (!checkAddr(Data, ec, uintptr_t(SymbolTable),
-                 Header->NumberOfSymbols * sizeof(coff_symbol)))
-    return;
+  if (Header->PointerToSymbolTable !=3D 0) {
+    SymbolTable =3D
+      reinterpret_cast<const coff_symbol *>(base()
+                                            + Header->PointerToSymbolTable=
);
+    if (!checkAddr(Data, ec, uintptr_t(SymbolTable),
+                   Header->NumberOfSymbols * sizeof(coff_symbol)))
+      return;
=20
-  // Find string table.
-  StringTable =3D reinterpret_cast<const char *>(base())
-                + Header->PointerToSymbolTable
-                + Header->NumberOfSymbols * sizeof(coff_symbol);
-  if (!checkAddr(Data, ec, uintptr_t(StringTable), sizeof(ulittle32_t)))
-    return;
+    // Find string table.
+    StringTable =3D reinterpret_cast<const char *>(base())
+                  + Header->PointerToSymbolTable
+                  + Header->NumberOfSymbols * sizeof(coff_symbol);
+    if (!checkAddr(Data, ec, uintptr_t(StringTable), sizeof(ulittle32_t)))
+      return;
=20
-  StringTableSize =3D *reinterpret_cast<const ulittle32_t *>(StringTable);
-  if (!checkAddr(Data, ec, uintptr_t(StringTable), StringTableSize))
-    return;
-  // Check that the string table is null terminated if has any in it.
-  if (StringTableSize < 4
-      || (StringTableSize > 4 && StringTable[StringTableSize - 1] !=3D 0))=
 {
-    ec =3D object_error::parse_failed;
-    return;
+    StringTableSize =3D *reinterpret_cast<const ulittle32_t *>(StringTable=
);
+    if (!checkAddr(Data, ec, uintptr_t(StringTable), StringTableSize))
+      return;
+    // Check that the string table is null terminated if has any in it.
+    if (StringTableSize < 4
+        || (StringTableSize > 4 && StringTable[StringTableSize - 1] !=3D 0=
)) {
+      ec =3D object_error::parse_failed;
+      return;
+    }
   }
=20
   ec =3D object_error::success;
@@ -472,7 +488,6 @@
=20
 symbol_iterator COFFObjectFile::begin_symbols() const {
   DataRefImpl ret;
-  std::memset(&ret, 0, sizeof(DataRefImpl));
   ret.p =3D reinterpret_cast<intptr_t>(SymbolTable);
   return symbol_iterator(SymbolRef(ret, this));
 }
@@ -480,21 +495,44 @@
 symbol_iterator COFFObjectFile::end_symbols() const {
   // The symbol table ends where the string table begins.
   DataRefImpl ret;
-  std::memset(&ret, 0, sizeof(DataRefImpl));
   ret.p =3D reinterpret_cast<intptr_t>(StringTable);
   return symbol_iterator(SymbolRef(ret, this));
 }
=20
+symbol_iterator COFFObjectFile::begin_dynamic_symbols() const {
+  // TODO: implement
+  report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
+}
+
+symbol_iterator COFFObjectFile::end_dynamic_symbols() const {
+  // TODO: implement
+  report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
+}
+
+library_iterator COFFObjectFile::begin_libraries_needed() const {
+  // TODO: implement
+  report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
+}
+
+library_iterator COFFObjectFile::end_libraries_needed() const {
+  // TODO: implement
+  report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
+}
+
+StringRef COFFObjectFile::getLoadName() const {
+  // COFF does not have this field.
+  return "";
+}
+
+
 section_iterator COFFObjectFile::begin_sections() const {
   DataRefImpl ret;
-  std::memset(&ret, 0, sizeof(DataRefImpl));
   ret.p =3D reinterpret_cast<intptr_t>(SectionTable);
   return section_iterator(SectionRef(ret, this));
 }
=20
 section_iterator COFFObjectFile::end_sections() const {
   DataRefImpl ret;
-  std::memset(&ret, 0, sizeof(DataRefImpl));
   ret.p =3D reinterpret_cast<intptr_t>(SectionTable + Header->NumberOfSect=
ions);
   return section_iterator(SectionRef(ret, this));
 }
@@ -525,6 +563,11 @@
   }
 }
=20
+error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
+  Res =3D Header;
+  return object_error::success;
+}
+
 error_code COFFObjectFile::getSection(int32_t index,
                                       const coff_section *&Result) const {
   // Check for special index values.
@@ -553,13 +596,69 @@
=20
 error_code COFFObjectFile::getSymbol(uint32_t index,
                                      const coff_symbol *&Result) const {
-  if (index > 0 && index < Header->NumberOfSymbols)
+  if (index < Header->NumberOfSymbols)
     Result =3D SymbolTable + index;
   else
     return object_error::parse_failed;
   return object_error::success;
 }
=20
+error_code COFFObjectFile::getSymbolName(const coff_symbol *symbol,
+                                         StringRef &Res) const {
+  // Check for string table entry. First 4 bytes are 0.
+  if (symbol->Name.Offset.Zeroes =3D=3D 0) {
+    uint32_t Offset =3D symbol->Name.Offset.Offset;
+    if (error_code ec =3D getString(Offset, Res))
+      return ec;
+    return object_error::success;
+  }
+
+  if (symbol->Name.ShortName[7] =3D=3D 0)
+    // Null terminated, let ::strlen figure out the length.
+    Res =3D StringRef(symbol->Name.ShortName);
+  else
+    // Not null terminated, use all 8 bytes.
+    Res =3D StringRef(symbol->Name.ShortName, 8);
+  return object_error::success;
+}
+
+error_code COFFObjectFile::getSectionName(const coff_section *Sec,
+                                          StringRef &Res) const {
+  StringRef Name;
+  if (Sec->Name[7] =3D=3D 0)
+    // Null terminated, let ::strlen figure out the length.
+    Name =3D Sec->Name;
+  else
+    // Not null terminated, use all 8 bytes.
+    Name =3D StringRef(Sec->Name, 8);
+
+  // Check for string table entry. First byte is '/'.
+  if (Name[0] =3D=3D '/') {
+    uint32_t Offset;
+    if (Name.substr(1).getAsInteger(10, Offset))
+      return object_error::parse_failed;
+    if (error_code ec =3D getString(Offset, Name))
+      return ec;
+  }
+
+  Res =3D Name;
+  return object_error::success;
+}
+
+error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
+                                              ArrayRef<uint8_t> &Res) cons=
t {
+  // The only thing that we need to verify is that the contents is contain=
ed
+  // within the file bounds. We don't need to make sure it doesn't cover o=
ther
+  // data, as there's nothing that says that is not allowed.
+  uintptr_t ConStart =3D uintptr_t(base()) + Sec->PointerToRawData;
+  uintptr_t ConEnd =3D ConStart + Sec->SizeOfRawData;
+  if (ConEnd > uintptr_t(Data->getBufferEnd()))
+    return object_error::parse_failed;
+  Res =3D ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStar=
t),
+                          Sec->SizeOfRawData);
+  return object_error::success;
+}
+
 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
   return reinterpret_cast<const coff_relocation*>(Rel.p);
 }
@@ -575,6 +674,11 @@
   Res =3D toRel(Rel)->VirtualAddress;
   return object_error::success;
 }
+error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
+                                               uint64_t &Res) const {
+  Res =3D toRel(Rel)->VirtualAddress;
+  return object_error::success;
+}
 error_code COFFObjectFile::getRelocationSymbol(DataRefImpl Rel,
                                                SymbolRef &Res) const {
   const coff_relocation* R =3D toRel(Rel);
@@ -584,7 +688,7 @@
   return object_error::success;
 }
 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
-                                             uint32_t &Res) const {
+                                             uint64_t &Res) const {
   const coff_relocation* R =3D toRel(Rel);
   Res =3D R->Type;
   return object_error::success;
@@ -658,7 +762,6 @@
   const coff_symbol *symb =3D 0;
   if (error_code ec =3D getSymbol(reloc->SymbolTableIndex, symb)) return e=
c;
   DataRefImpl sym;
-  ::memset(&sym, 0, sizeof(sym));
   sym.p =3D reinterpret_cast<uintptr_t>(symb);
   StringRef symname;
   if (error_code ec =3D getSymbolName(sym, symname)) return ec;
@@ -666,6 +769,16 @@
   return object_error::success;
 }
=20
+error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
+                                          LibraryRef &Result) const {
+  report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
+}
+
+error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
+                                          StringRef &Result) const {
+  report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
+}
+
 namespace llvm {
=20
   ObjectFile *ObjectFile::createCOFFObjectFile(MemoryBuffer *Object) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Object/ELFObject=
File.cpp
--- a/head/contrib/llvm/lib/Object/ELFObjectFile.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Object/ELFObjectFile.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -7,1405 +7,44 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-// This file defines the ELFObjectFile class.
+// Part of the ELFObjectFile class implementation.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringSwitch.h"
-#include "llvm/ADT/Triple.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/Object/ObjectFile.h"
-#include "llvm/Support/ELF.h"
-#include "llvm/Support/Endian.h"
-#include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/raw_ostream.h"
-#include <algorithm>
-#include <limits>
-#include <utility>
+#include "llvm/Object/ELF.h"
=20
-using namespace llvm;
+namespace llvm {
+
 using namespace object;
=20
-// Templates to choose Elf_Addr and Elf_Off depending on is64Bits.
 namespace {
-template<support::endianness target_endianness>
-struct ELFDataTypeTypedefHelperCommon {
-  typedef support::detail::packed_endian_specific_integral
-    <uint16_t, target_endianness, support::aligned> Elf_Half;
-  typedef support::detail::packed_endian_specific_integral
-    <uint32_t, target_endianness, support::aligned> Elf_Word;
-  typedef support::detail::packed_endian_specific_integral
-    <int32_t, target_endianness, support::aligned> Elf_Sword;
-  typedef support::detail::packed_endian_specific_integral
-    <uint64_t, target_endianness, support::aligned> Elf_Xword;
-  typedef support::detail::packed_endian_specific_integral
-    <int64_t, target_endianness, support::aligned> Elf_Sxword;
-};
-}
-
-namespace {
-template<support::endianness target_endianness, bool is64Bits>
-struct ELFDataTypeTypedefHelper;
-
-/// ELF 32bit types.
-template<support::endianness target_endianness>
-struct ELFDataTypeTypedefHelper<target_endianness, false>
-  : ELFDataTypeTypedefHelperCommon<target_endianness> {
-  typedef support::detail::packed_endian_specific_integral
-    <uint32_t, target_endianness, support::aligned> Elf_Addr;
-  typedef support::detail::packed_endian_specific_integral
-    <uint32_t, target_endianness, support::aligned> Elf_Off;
-};
-
-/// ELF 64bit types.
-template<support::endianness target_endianness>
-struct ELFDataTypeTypedefHelper<target_endianness, true>
-  : ELFDataTypeTypedefHelperCommon<target_endianness>{
-  typedef support::detail::packed_endian_specific_integral
-    <uint64_t, target_endianness, support::aligned> Elf_Addr;
-  typedef support::detail::packed_endian_specific_integral
-    <uint64_t, target_endianness, support::aligned> Elf_Off;
-};
-}
-
-// I really don't like doing this, but the alternative is copypasta.
-#define LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits) \
-typedef typename \
-  ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Addr Elf_Addr=
; \
-typedef typename \
-  ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Off Elf_Off; \
-typedef typename \
-  ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Half Elf_Half=
; \
-typedef typename \
-  ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Word Elf_Word=
; \
-typedef typename \
-  ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sword Elf_Swo=
rd; \
-typedef typename \
-  ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Xword Elf_Xwo=
rd; \
-typedef typename \
-  ELFDataTypeTypedefHelper<target_endianness, is64Bits>::Elf_Sxword Elf_Sx=
word;
-
-  // Section header.
-namespace {
-template<support::endianness target_endianness, bool is64Bits>
-struct Elf_Shdr_Base;
-
-template<support::endianness target_endianness>
-struct Elf_Shdr_Base<target_endianness, false> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, false)
-  Elf_Word sh_name;     // Section name (index into string table)
-  Elf_Word sh_type;     // Section type (SHT_*)
-  Elf_Word sh_flags;    // Section flags (SHF_*)
-  Elf_Addr sh_addr;     // Address where section is to be loaded
-  Elf_Off  sh_offset;   // File offset of section data, in bytes
-  Elf_Word sh_size;     // Size of section, in bytes
-  Elf_Word sh_link;     // Section type-specific header table index link
-  Elf_Word sh_info;     // Section type-specific extra information
-  Elf_Word sh_addralign;// Section address alignment
-  Elf_Word sh_entsize;  // Size of records contained within the section
-};
-
-template<support::endianness target_endianness>
-struct Elf_Shdr_Base<target_endianness, true> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, true)
-  Elf_Word  sh_name;     // Section name (index into string table)
-  Elf_Word  sh_type;     // Section type (SHT_*)
-  Elf_Xword sh_flags;    // Section flags (SHF_*)
-  Elf_Addr  sh_addr;     // Address where section is to be loaded
-  Elf_Off   sh_offset;   // File offset of section data, in bytes
-  Elf_Xword sh_size;     // Size of section, in bytes
-  Elf_Word  sh_link;     // Section type-specific header table index link
-  Elf_Word  sh_info;     // Section type-specific extra information
-  Elf_Xword sh_addralign;// Section address alignment
-  Elf_Xword sh_entsize;  // Size of records contained within the section
-};
-
-template<support::endianness target_endianness, bool is64Bits>
-struct Elf_Shdr_Impl : Elf_Shdr_Base<target_endianness, is64Bits> {
-  using Elf_Shdr_Base<target_endianness, is64Bits>::sh_entsize;
-  using Elf_Shdr_Base<target_endianness, is64Bits>::sh_size;
-
-  /// @brief Get the number of entities this section contains if it has an=
y.
-  unsigned getEntityCount() const {
-    if (sh_entsize =3D=3D 0)
-      return 0;
-    return sh_size / sh_entsize;
-  }
-};
-}
-
-namespace {
-template<support::endianness target_endianness, bool is64Bits>
-struct Elf_Sym_Base;
-
-template<support::endianness target_endianness>
-struct Elf_Sym_Base<target_endianness, false> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, false)
-  Elf_Word      st_name;  // Symbol name (index into string table)
-  Elf_Addr      st_value; // Value or address associated with the symbol
-  Elf_Word      st_size;  // Size of the symbol
-  unsigned char st_info;  // Symbol's type and binding attributes
-  unsigned char st_other; // Must be zero; reserved
-  Elf_Half      st_shndx; // Which section (header table index) it's defin=
ed in
-};
-
-template<support::endianness target_endianness>
-struct Elf_Sym_Base<target_endianness, true> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, true)
-  Elf_Word      st_name;  // Symbol name (index into string table)
-  unsigned char st_info;  // Symbol's type and binding attributes
-  unsigned char st_other; // Must be zero; reserved
-  Elf_Half      st_shndx; // Which section (header table index) it's defin=
ed in
-  Elf_Addr      st_value; // Value or address associated with the symbol
-  Elf_Xword     st_size;  // Size of the symbol
-};
-
-template<support::endianness target_endianness, bool is64Bits>
-struct Elf_Sym_Impl : Elf_Sym_Base<target_endianness, is64Bits> {
-  using Elf_Sym_Base<target_endianness, is64Bits>::st_info;
-
-  // These accessors and mutators correspond to the ELF32_ST_BIND,
-  // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specificat=
ion:
-  unsigned char getBinding() const { return st_info >> 4; }
-  unsigned char getType() const { return st_info & 0x0f; }
-  void setBinding(unsigned char b) { setBindingAndType(b, getType()); }
-  void setType(unsigned char t) { setBindingAndType(getBinding(), t); }
-  void setBindingAndType(unsigned char b, unsigned char t) {
-    st_info =3D (b << 4) + (t & 0x0f);
-  }
-};
-}
-
-namespace {
-template<support::endianness target_endianness, bool is64Bits, bool isRela>
-struct Elf_Rel_Base;
-
-template<support::endianness target_endianness>
-struct Elf_Rel_Base<target_endianness, false, false> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, false)
-  Elf_Addr      r_offset; // Location (file byte offset, or program virtua=
l addr)
-  Elf_Word      r_info;  // Symbol table index and type of relocation to a=
pply
-};
-
-template<support::endianness target_endianness>
-struct Elf_Rel_Base<target_endianness, true, false> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, true)
-  Elf_Addr      r_offset; // Location (file byte offset, or program virtua=
l addr)
-  Elf_Xword     r_info;   // Symbol table index and type of relocation to =
apply
-};
-
-template<support::endianness target_endianness>
-struct Elf_Rel_Base<target_endianness, false, true> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, false)
-  Elf_Addr      r_offset; // Location (file byte offset, or program virtua=
l addr)
-  Elf_Word      r_info;   // Symbol table index and type of relocation to =
apply
-  Elf_Sword     r_addend; // Compute value for relocatable field by adding=
 this
-};
-
-template<support::endianness target_endianness>
-struct Elf_Rel_Base<target_endianness, true, true> {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, true)
-  Elf_Addr      r_offset; // Location (file byte offset, or program virtua=
l addr)
-  Elf_Xword     r_info;   // Symbol table index and type of relocation to =
apply
-  Elf_Sxword    r_addend; // Compute value for relocatable field by adding=
 this.
-};
-
-template<support::endianness target_endianness, bool is64Bits, bool isRela>
-struct Elf_Rel_Impl;
-
-template<support::endianness target_endianness, bool isRela>
-struct Elf_Rel_Impl<target_endianness, true, isRela>
-       : Elf_Rel_Base<target_endianness, true, isRela> {
-  using Elf_Rel_Base<target_endianness, true, isRela>::r_info;
-  LLVM_ELF_IMPORT_TYPES(target_endianness, true)
-
-  // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_T=
YPE,
-  // and ELF64_R_INFO macros defined in the ELF specification:
-  uint64_t getSymbol() const { return (r_info >> 32); }
-  unsigned char getType() const {
-    return (unsigned char) (r_info & 0xffffffffL);
-  }
-  void setSymbol(uint64_t s) { setSymbolAndType(s, getType()); }
-  void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
-  void setSymbolAndType(uint64_t s, unsigned char t) {
-    r_info =3D (s << 32) + (t&0xffffffffL);
-  }
-};
-
-template<support::endianness target_endianness, bool isRela>
-struct Elf_Rel_Impl<target_endianness, false, isRela>
-       : Elf_Rel_Base<target_endianness, false, isRela> {
-  using Elf_Rel_Base<target_endianness, false, isRela>::r_info;
-  LLVM_ELF_IMPORT_TYPES(target_endianness, false)
-
-  // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_T=
YPE,
-  // and ELF32_R_INFO macros defined in the ELF specification:
-  uint32_t getSymbol() const { return (r_info >> 8); }
-  unsigned char getType() const { return (unsigned char) (r_info & 0x0ff);=
 }
-  void setSymbol(uint32_t s) { setSymbolAndType(s, getType()); }
-  void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); }
-  void setSymbolAndType(uint32_t s, unsigned char t) {
-    r_info =3D (s << 8) + t;
-  }
-};
-
-}
-
-namespace {
-template<support::endianness target_endianness, bool is64Bits>
-class ELFObjectFile : public ObjectFile {
-  LLVM_ELF_IMPORT_TYPES(target_endianness, is64Bits)
-
-  typedef Elf_Shdr_Impl<target_endianness, is64Bits> Elf_Shdr;
-  typedef Elf_Sym_Impl<target_endianness, is64Bits> Elf_Sym;
-  typedef Elf_Rel_Impl<target_endianness, is64Bits, false> Elf_Rel;
-  typedef Elf_Rel_Impl<target_endianness, is64Bits, true> Elf_Rela;
-
-  struct Elf_Ehdr {
-    unsigned char e_ident[ELF::EI_NIDENT]; // ELF Identification bytes
-    Elf_Half e_type;     // Type of file (see ET_*)
-    Elf_Half e_machine;  // Required architecture for this file (see EM_*)
-    Elf_Word e_version;  // Must be equal to 1
-    Elf_Addr e_entry;    // Address to jump to in order to start program
-    Elf_Off  e_phoff;    // Program header table's file offset, in bytes
-    Elf_Off  e_shoff;    // Section header table's file offset, in bytes
-    Elf_Word e_flags;    // Processor-specific flags
-    Elf_Half e_ehsize;   // Size of ELF header, in bytes
-    Elf_Half e_phentsize;// Size of an entry in the program header table
-    Elf_Half e_phnum;    // Number of entries in the program header table
-    Elf_Half e_shentsize;// Size of an entry in the section header table
-    Elf_Half e_shnum;    // Number of entries in the section header table
-    Elf_Half e_shstrndx; // Section header table index of section name
-                                  // string table
-    bool checkMagic() const {
-      return (memcmp(e_ident, ELF::ElfMagic, strlen(ELF::ElfMagic))) =3D=
=3D 0;
-    }
-    unsigned char getFileClass() const { return e_ident[ELF::EI_CLASS]; }
-    unsigned char getDataEncoding() const { return e_ident[ELF::EI_DATA]; }
-  };
-
-  typedef SmallVector<const Elf_Shdr*, 1> Sections_t;
-  typedef DenseMap<unsigned, unsigned> IndexMap_t;
-  typedef DenseMap<const Elf_Shdr*, SmallVector<uint32_t, 1> > RelocMap_t;
-
-  const Elf_Ehdr *Header;
-  const Elf_Shdr *SectionHeaderTable;
-  const Elf_Shdr *dot_shstrtab_sec; // Section header string table.
-  const Elf_Shdr *dot_strtab_sec;   // Symbol header string table.
-  Sections_t SymbolTableSections;
-  IndexMap_t SymbolTableSectionsIndexMap;
-  DenseMap<const Elf_Sym*, ELF::Elf64_Word> ExtendedSymbolTable;
-
-  /// @brief Map sections to an array of relocation sections that reference
-  ///        them sorted by section index.
-  RelocMap_t SectionRelocMap;
-
-  /// @brief Get the relocation section that contains \a Rel.
-  const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
-    return getSection(Rel.w.b);
-  }
-
-  void            validateSymbol(DataRefImpl Symb) const;
-  bool            isRelocationHasAddend(DataRefImpl Rel) const;
-  template<typename T>
-  const T        *getEntry(uint16_t Section, uint32_t Entry) const;
-  template<typename T>
-  const T        *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
-  const Elf_Sym  *getSymbol(DataRefImpl Symb) const;
-  const Elf_Shdr *getSection(DataRefImpl index) const;
-  const Elf_Shdr *getSection(uint32_t index) const;
-  const Elf_Rel  *getRel(DataRefImpl Rel) const;
-  const Elf_Rela *getRela(DataRefImpl Rela) const;
-  const char     *getString(uint32_t section, uint32_t offset) const;
-  const char     *getString(const Elf_Shdr *section, uint32_t offset) cons=
t;
-  error_code      getSymbolName(const Elf_Sym *Symb, StringRef &Res) const;
-
-protected:
-  virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
-  virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
-  virtual error_code getSymbolOffset(DataRefImpl Symb, uint64_t &Res) cons=
t;
-  virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) con=
st;
-  virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
-  virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) cons=
t;
-  virtual error_code isSymbolInternal(DataRefImpl Symb, bool &Res) const;
-  virtual error_code isSymbolGlobal(DataRefImpl Symb, bool &Res) const;
-  virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::SymbolType=
 &Res) const;
-
-  virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) cons=
t;
-  virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
-  virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) con=
st;
-  virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
-  virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) c=
onst;
-  virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) c=
onst;
-  virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
-  virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
-  virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
-  virtual error_code sectionContainsSymbol(DataRefImpl Sec, DataRefImpl Sy=
mb,
-                                           bool &Result) const;
-  virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
-  virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;
-
-  virtual error_code getRelocationNext(DataRefImpl Rel,
-                                       RelocationRef &Res) const;
-  virtual error_code getRelocationAddress(DataRefImpl Rel,
-                                          uint64_t &Res) const;
-  virtual error_code getRelocationSymbol(DataRefImpl Rel,
-                                         SymbolRef &Res) const;
-  virtual error_code getRelocationType(DataRefImpl Rel,
-                                       uint32_t &Res) const;
-  virtual error_code getRelocationTypeName(DataRefImpl Rel,
-                                           SmallVectorImpl<char> &Result) =
const;
-  virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
-                                                 int64_t &Res) const;
-  virtual error_code getRelocationValueString(DataRefImpl Rel,
-                                           SmallVectorImpl<char> &Result) =
const;
-
-public:
-  ELFObjectFile(MemoryBuffer *Object, error_code &ec);
-  virtual symbol_iterator begin_symbols() const;
-  virtual symbol_iterator end_symbols() const;
-  virtual section_iterator begin_sections() const;
-  virtual section_iterator end_sections() const;
-
-  virtual uint8_t getBytesInAddress() const;
-  virtual StringRef getFileFormatName() const;
-  virtual unsigned getArch() const;
-
-  uint64_t getNumSections() const;
-  uint64_t getStringTableIndex() const;
-  ELF::Elf64_Word getSymbolTableIndex(const Elf_Sym *symb) const;
-  const Elf_Shdr *getSection(const Elf_Sym *symb) const;
-};
-} // end namespace
-
-template<support::endianness target_endianness, bool is64Bits>
-void ELFObjectFile<target_endianness, is64Bits>
-                  ::validateSymbol(DataRefImpl Symb) const {
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-  const Elf_Shdr *SymbolTableSection =3D SymbolTableSections[Symb.d.b];
-  // FIXME: We really need to do proper error handling in the case of an i=
nvalid
-  //        input file. Because we don't use exceptions, I think we'll jus=
t pass
-  //        an error object around.
-  if (!(  symb
-        && SymbolTableSection
-        && symb >=3D (const Elf_Sym*)(base()
-                   + SymbolTableSection->sh_offset)
-        && symb <  (const Elf_Sym*)(base()
-                   + SymbolTableSection->sh_offset
-                   + SymbolTableSection->sh_size)))
-    // FIXME: Proper error handling.
-    report_fatal_error("Symb must point to a valid symbol!");
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolNext(DataRefImpl Symb,
-                                        SymbolRef &Result) const {
-  validateSymbol(Symb);
-  const Elf_Shdr *SymbolTableSection =3D SymbolTableSections[Symb.d.b];
-
-  ++Symb.d.a;
-  // Check to see if we are at the end of this symbol table.
-  if (Symb.d.a >=3D SymbolTableSection->getEntityCount()) {
-    // We are at the end. If there are other symbol tables, jump to them.
-    ++Symb.d.b;
-    Symb.d.a =3D 1; // The 0th symbol in ELF is fake.
-    // Otherwise return the terminator.
-    if (Symb.d.b >=3D SymbolTableSections.size()) {
-      Symb.d.a =3D std::numeric_limits<uint32_t>::max();
-      Symb.d.b =3D std::numeric_limits<uint32_t>::max();
-    }
-  }
-
-  Result =3D SymbolRef(Symb, this);
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolName(DataRefImpl Symb,
-                                        StringRef &Result) const {
-  validateSymbol(Symb);
-  const Elf_Sym *symb =3D getSymbol(Symb);
-  return getSymbolName(symb, Result);
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-ELF::Elf64_Word ELFObjectFile<target_endianness, is64Bits>
-                      ::getSymbolTableIndex(const Elf_Sym *symb) const {
-  if (symb->st_shndx =3D=3D ELF::SHN_XINDEX)
-    return ExtendedSymbolTable.lookup(symb);
-  return symb->st_shndx;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
-ELFObjectFile<target_endianness, is64Bits>
-                             ::getSection(const Elf_Sym *symb) const {
-  if (symb->st_shndx =3D=3D ELF::SHN_XINDEX)
-    return getSection(ExtendedSymbolTable.lookup(symb));
-  if (symb->st_shndx >=3D ELF::SHN_LORESERVE)
-    return 0;
-  return getSection(symb->st_shndx);
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolOffset(DataRefImpl Symb,
-                                          uint64_t &Result) const {
-  validateSymbol(Symb);
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-  const Elf_Shdr *Section;
-  switch (getSymbolTableIndex(symb)) {
-  case ELF::SHN_COMMON:
-   // Undefined symbols have no address yet.
-  case ELF::SHN_UNDEF:
-    Result =3D UnknownAddressOrSize;
-    return object_error::success;
-  case ELF::SHN_ABS:
-    Result =3D symb->st_value;
-    return object_error::success;
-  default: Section =3D getSection(symb);
-  }
-
-  switch (symb->getType()) {
-  case ELF::STT_SECTION:
-    Result =3D Section ? Section->sh_addr : UnknownAddressOrSize;
-    return object_error::success;
-  case ELF::STT_FUNC:
-  case ELF::STT_OBJECT:
-  case ELF::STT_NOTYPE:
-    Result =3D symb->st_value;
-    return object_error::success;
-  default:
-    Result =3D UnknownAddressOrSize;
-    return object_error::success;
+  std::pair<unsigned char, unsigned char>
+  getElfArchType(MemoryBuffer *Object) {
+    if (Object->getBufferSize() < ELF::EI_NIDENT)
+      return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDA=
TANONE);
+    return std::make_pair( (uint8_t)Object->getBufferStart()[ELF::EI_CLASS]
+                         , (uint8_t)Object->getBufferStart()[ELF::EI_DATA]=
);
   }
 }
=20
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolAddress(DataRefImpl Symb,
-                                           uint64_t &Result) const {
-  validateSymbol(Symb);
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-  const Elf_Shdr *Section;
-  switch (getSymbolTableIndex(symb)) {
-  case ELF::SHN_COMMON: // Fall through.
-   // Undefined symbols have no address yet.
-  case ELF::SHN_UNDEF:
-    Result =3D UnknownAddressOrSize;
-    return object_error::success;
-  case ELF::SHN_ABS:
-    Result =3D reinterpret_cast<uintptr_t>(base()+symb->st_value);
-    return object_error::success;
-  default: Section =3D getSection(symb);
+// Creates an in-memory object-file by default: createELFObjectFile(Buffer)
+ObjectFile *ObjectFile::createELFObjectFile(MemoryBuffer *Object) {
+  std::pair<unsigned char, unsigned char> Ident =3D getElfArchType(Object);
+  error_code ec;
+
+  if (Ident.first =3D=3D ELF::ELFCLASS32 && Ident.second =3D=3D ELF::ELFDA=
TA2LSB)
+    return new ELFObjectFile<support::little, false>(Object, ec);
+  else if (Ident.first =3D=3D ELF::ELFCLASS32 && Ident.second =3D=3D ELF::=
ELFDATA2MSB)
+    return new ELFObjectFile<support::big, false>(Object, ec);
+  else if (Ident.first =3D=3D ELF::ELFCLASS64 && Ident.second =3D=3D ELF::=
ELFDATA2MSB)
+    return new ELFObjectFile<support::big, true>(Object, ec);
+  else if (Ident.first =3D=3D ELF::ELFCLASS64 && Ident.second =3D=3D ELF::=
ELFDATA2LSB) {
+    ELFObjectFile<support::little, true> *result =3D
+          new ELFObjectFile<support::little, true>(Object, ec);
+    return result;
   }
-  const uint8_t* addr =3D base();
-  if (Section)
-    addr +=3D Section->sh_offset;
-  switch (symb->getType()) {
-  case ELF::STT_SECTION:
-    Result =3D reinterpret_cast<uintptr_t>(addr);
-    return object_error::success;
-  case ELF::STT_FUNC: // Fall through.
-  case ELF::STT_OBJECT: // Fall through.
-  case ELF::STT_NOTYPE:
-    addr +=3D symb->st_value;
-    Result =3D reinterpret_cast<uintptr_t>(addr);
-    return object_error::success;
-  default:
-    Result =3D UnknownAddressOrSize;
-    return object_error::success;
-  }
+
+  report_fatal_error("Buffer is not an ELF object file!");
 }
=20
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolSize(DataRefImpl Symb,
-                                        uint64_t &Result) const {
-  validateSymbol(Symb);
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-  if (symb->st_size =3D=3D 0)
-    Result =3D UnknownAddressOrSize;
-  Result =3D symb->st_size;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolNMTypeChar(DataRefImpl Symb,
-                                              char &Result) const {
-  validateSymbol(Symb);
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-  const Elf_Shdr *Section =3D getSection(symb);
-
-  char ret =3D '?';
-
-  if (Section) {
-    switch (Section->sh_type) {
-    case ELF::SHT_PROGBITS:
-    case ELF::SHT_DYNAMIC:
-      switch (Section->sh_flags) {
-      case (ELF::SHF_ALLOC | ELF::SHF_EXECINSTR):
-        ret =3D 't'; break;
-      case (ELF::SHF_ALLOC | ELF::SHF_WRITE):
-        ret =3D 'd'; break;
-      case ELF::SHF_ALLOC:
-      case (ELF::SHF_ALLOC | ELF::SHF_MERGE):
-      case (ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS):
-        ret =3D 'r'; break;
-      }
-      break;
-    case ELF::SHT_NOBITS: ret =3D 'b';
-    }
-  }
-
-  switch (getSymbolTableIndex(symb)) {
-  case ELF::SHN_UNDEF:
-    if (ret =3D=3D '?')
-      ret =3D 'U';
-    break;
-  case ELF::SHN_ABS: ret =3D 'a'; break;
-  case ELF::SHN_COMMON: ret =3D 'c'; break;
-  }
-
-  switch (symb->getBinding()) {
-  case ELF::STB_GLOBAL: ret =3D ::toupper(ret); break;
-  case ELF::STB_WEAK:
-    if (getSymbolTableIndex(symb) =3D=3D ELF::SHN_UNDEF)
-      ret =3D 'w';
-    else
-      if (symb->getType() =3D=3D ELF::STT_OBJECT)
-        ret =3D 'V';
-      else
-        ret =3D 'W';
-  }
-
-  if (ret =3D=3D '?' && symb->getType() =3D=3D ELF::STT_SECTION) {
-    StringRef name;
-    if (error_code ec =3D getSymbolName(Symb, name))
-      return ec;
-    Result =3D StringSwitch<char>(name)
-      .StartsWith(".debug", 'N')
-      .StartsWith(".note", 'n')
-      .Default('?');
-    return object_error::success;
-  }
-
-  Result =3D ret;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolType(DataRefImpl Symb,
-                                        SymbolRef::SymbolType &Result) con=
st {
-  validateSymbol(Symb);
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-
-  if (getSymbolTableIndex(symb) =3D=3D ELF::SHN_UNDEF) {
-    Result =3D SymbolRef::ST_External;
-    return object_error::success;
-  }
-
-  switch (symb->getType()) {
-  case ELF::STT_FUNC:
-    Result =3D SymbolRef::ST_Function;
-    break;
-  case ELF::STT_OBJECT:
-    Result =3D SymbolRef::ST_Data;
-    break;
-  default:
-    Result =3D SymbolRef::ST_Other;
-    break;
-  }
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::isSymbolGlobal(DataRefImpl Symb,
-                                        bool &Result) const {
-  validateSymbol(Symb);
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-
-  Result =3D symb->getBinding() =3D=3D ELF::STB_GLOBAL;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::isSymbolInternal(DataRefImpl Symb,
-                                           bool &Result) const {
-  validateSymbol(Symb);
-  const Elf_Sym  *symb =3D getSymbol(Symb);
-
-  if (  symb->getType() =3D=3D ELF::STT_FILE
-     || symb->getType() =3D=3D ELF::STT_SECTION)
-    Result =3D true;
-  Result =3D false;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSectionNext(DataRefImpl Sec, SectionRef &Resu=
lt) const {
-  const uint8_t *sec =3D reinterpret_cast<const uint8_t *>(Sec.p);
-  sec +=3D Header->e_shentsize;
-  Sec.p =3D reinterpret_cast<intptr_t>(sec);
-  Result =3D SectionRef(Sec, this);
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSectionName(DataRefImpl Sec,
-                                         StringRef &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  Result =3D StringRef(getString(dot_shstrtab_sec, sec->sh_name));
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSectionAddress(DataRefImpl Sec,
-                                            uint64_t &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  Result =3D sec->sh_addr;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSectionSize(DataRefImpl Sec,
-                                         uint64_t &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  Result =3D sec->sh_size;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSectionContents(DataRefImpl Sec,
-                                             StringRef &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  const char *start =3D (const char*)base() + sec->sh_offset;
-  Result =3D StringRef(start, sec->sh_size);
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSectionAlignment(DataRefImpl Sec,
-                                              uint64_t &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  Result =3D sec->sh_addralign;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::isSectionText(DataRefImpl Sec,
-                                        bool &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  if (sec->sh_flags & ELF::SHF_EXECINSTR)
-    Result =3D true;
-  else
-    Result =3D false;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::isSectionData(DataRefImpl Sec,
-                                        bool &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
-      && sec->sh_type =3D=3D ELF::SHT_PROGBITS)
-    Result =3D true;
-  else
-    Result =3D false;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::isSectionBSS(DataRefImpl Sec,
-                                       bool &Result) const {
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  if (sec->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE)
-      && sec->sh_type =3D=3D ELF::SHT_NOBITS)
-    Result =3D true;
-  else
-    Result =3D false;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                          ::sectionContainsSymbol(DataRefImpl Sec,
-                                                  DataRefImpl Symb,
-                                                  bool &Result) const {
-  // FIXME: Unimplemented.
-  Result =3D false;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-relocation_iterator ELFObjectFile<target_endianness, is64Bits>
-                                 ::getSectionRelBegin(DataRefImpl Sec) con=
st {
-  DataRefImpl RelData;
-  memset(&RelData, 0, sizeof(RelData));
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  typename RelocMap_t::const_iterator ittr =3D SectionRelocMap.find(sec);
-  if (sec !=3D 0 && ittr !=3D SectionRelocMap.end()) {
-    RelData.w.a =3D getSection(ittr->second[0])->sh_info;
-    RelData.w.b =3D ittr->second[0];
-    RelData.w.c =3D 0;
-  }
-  return relocation_iterator(RelocationRef(RelData, this));
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-relocation_iterator ELFObjectFile<target_endianness, is64Bits>
-                                 ::getSectionRelEnd(DataRefImpl Sec) const=
 {
-  DataRefImpl RelData;
-  memset(&RelData, 0, sizeof(RelData));
-  const Elf_Shdr *sec =3D reinterpret_cast<const Elf_Shdr *>(Sec.p);
-  typename RelocMap_t::const_iterator ittr =3D SectionRelocMap.find(sec);
-  if (sec !=3D 0 && ittr !=3D SectionRelocMap.end()) {
-    // Get the index of the last relocation section for this section.
-    std::size_t relocsecindex =3D ittr->second[ittr->second.size() - 1];
-    const Elf_Shdr *relocsec =3D getSection(relocsecindex);
-    RelData.w.a =3D relocsec->sh_info;
-    RelData.w.b =3D relocsecindex;
-    RelData.w.c =3D relocsec->sh_size / relocsec->sh_entsize;
-  }
-  return relocation_iterator(RelocationRef(RelData, this));
-}
-
-// Relocations
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getRelocationNext(DataRefImpl Rel,
-                                            RelocationRef &Result) const {
-  ++Rel.w.c;
-  const Elf_Shdr *relocsec =3D getSection(Rel.w.b);
-  if (Rel.w.c >=3D (relocsec->sh_size / relocsec->sh_entsize)) {
-    // We have reached the end of the relocations for this section. See if=
 there
-    // is another relocation section.
-    typename RelocMap_t::mapped_type relocseclist =3D
-      SectionRelocMap.lookup(getSection(Rel.w.a));
-
-    // Do a binary search for the current reloc section index (which must =
be
-    // present). Then get the next one.
-    typename RelocMap_t::mapped_type::const_iterator loc =3D
-      std::lower_bound(relocseclist.begin(), relocseclist.end(), Rel.w.b);
-    ++loc;
-
-    // If there is no next one, don't do anything. The ++Rel.w.c above set=
s Rel
-    // to the end iterator.
-    if (loc !=3D relocseclist.end()) {
-      Rel.w.b =3D *loc;
-      Rel.w.a =3D 0;
-    }
-  }
-  Result =3D RelocationRef(Rel, this);
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getRelocationSymbol(DataRefImpl Rel,
-                                              SymbolRef &Result) const {
-  uint32_t symbolIdx;
-  const Elf_Shdr *sec =3D getSection(Rel.w.b);
-  switch (sec->sh_type) {
-    default :
-      report_fatal_error("Invalid section type in Rel!");
-    case ELF::SHT_REL : {
-      symbolIdx =3D getRel(Rel)->getSymbol();
-      break;
-    }
-    case ELF::SHT_RELA : {
-      symbolIdx =3D getRela(Rel)->getSymbol();
-      break;
-    }
-  }
-  DataRefImpl SymbolData;
-  IndexMap_t::const_iterator it =3D SymbolTableSectionsIndexMap.find(sec->=
sh_link);
-  if (it =3D=3D SymbolTableSectionsIndexMap.end())
-    report_fatal_error("Relocation symbol table not found!");
-  SymbolData.d.a =3D symbolIdx;
-  SymbolData.d.b =3D it->second;
-  Result =3D SymbolRef(SymbolData, this);
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getRelocationAddress(DataRefImpl Rel,
-                                               uint64_t &Result) const {
-  uint64_t offset;
-  const Elf_Shdr *sec =3D getSection(Rel.w.b);
-  switch (sec->sh_type) {
-    default :
-      report_fatal_error("Invalid section type in Rel!");
-    case ELF::SHT_REL : {
-      offset =3D getRel(Rel)->r_offset;
-      break;
-    }
-    case ELF::SHT_RELA : {
-      offset =3D getRela(Rel)->r_offset;
-      break;
-    }
-  }
-
-  Result =3D offset;
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getRelocationType(DataRefImpl Rel,
-                                            uint32_t &Result) const {
-  const Elf_Shdr *sec =3D getSection(Rel.w.b);
-  switch (sec->sh_type) {
-    default :
-      report_fatal_error("Invalid section type in Rel!");
-    case ELF::SHT_REL : {
-      Result =3D getRel(Rel)->getType();
-      break;
-    }
-    case ELF::SHT_RELA : {
-      Result =3D getRela(Rel)->getType();
-      break;
-    }
-  }
-  return object_error::success;
-}
-
-#define LLVM_ELF_SWITCH_RELOC_TYPE_NAME(enum) \
-  case ELF::enum: res =3D #enum; break;
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getRelocationTypeName(DataRefImpl Rel,
-                                          SmallVectorImpl<char> &Result) c=
onst {
-  const Elf_Shdr *sec =3D getSection(Rel.w.b);
-  uint8_t type;
-  StringRef res;
-  switch (sec->sh_type) {
-    default :
-      return object_error::parse_failed;
-    case ELF::SHT_REL : {
-      type =3D getRel(Rel)->getType();
-      break;
-    }
-    case ELF::SHT_RELA : {
-      type =3D getRela(Rel)->getType();
-      break;
-    }
-  }
-  switch (Header->e_machine) {
-  case ELF::EM_X86_64:
-    switch (type) {
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_NONE);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_64);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOT32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PLT32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_COPY);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GLOB_DAT);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_JUMP_SLOT);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_RELATIVE);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPCREL);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_32S);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_16);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC16);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_8);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC8);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPMOD64);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF64);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF64);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSGD);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSLD);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_DTPOFF32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTTPOFF);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TPOFF32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_PC64);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTOFF64);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_SIZE64);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_GOTPC32_TLSDESC);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC_CALL);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_X86_64_TLSDESC);
-    default:
-      res =3D "Unknown";
-    }
-    break;
-  case ELF::EM_386:
-    switch (type) {
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_NONE);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOT32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PLT32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_COPY);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GLOB_DAT);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_JUMP_SLOT);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_RELATIVE);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTOFF);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_GOTPC);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_32PLT);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTIE);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_16);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC16);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_8);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_PC8);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_PUSH);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_CALL);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GD_POP);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_PUSH);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_CALL);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDM_POP);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LDO_32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_IE_32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_LE_32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPMOD32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DTPOFF32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_TPOFF32);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_GOTDESC);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC_CALL);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_TLS_DESC);
-      LLVM_ELF_SWITCH_RELOC_TYPE_NAME(R_386_IRELATIVE);
-    default:
-      res =3D "Unknown";
-    }
-    break;
-  default:
-    res =3D "Unknown";
-  }
-  Result.append(res.begin(), res.end());
-  return object_error::success;
-}
-
-#undef LLVM_ELF_SWITCH_RELOC_TYPE_NAME
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getRelocationAdditionalInfo(DataRefImpl Rel,
-                                                      int64_t &Result) con=
st {
-  const Elf_Shdr *sec =3D getSection(Rel.w.b);
-  switch (sec->sh_type) {
-    default :
-      report_fatal_error("Invalid section type in Rel!");
-    case ELF::SHT_REL : {
-      Result =3D 0;
-      return object_error::success;
-    }
-    case ELF::SHT_RELA : {
-      Result =3D getRela(Rel)->r_addend;
-      return object_error::success;
-    }
-  }
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getRelocationValueString(DataRefImpl Rel,
-                                          SmallVectorImpl<char> &Result) c=
onst {
-  const Elf_Shdr *sec =3D getSection(Rel.w.b);
-  uint8_t type;
-  StringRef res;
-  int64_t addend =3D 0;
-  uint16_t symbol_index =3D 0;
-  switch (sec->sh_type) {
-    default :
-      return object_error::parse_failed;
-    case ELF::SHT_REL : {
-      type =3D getRel(Rel)->getType();
-      symbol_index =3D getRel(Rel)->getSymbol();
-      // TODO: Read implicit addend from section data.
-      break;
-    }
-    case ELF::SHT_RELA : {
-      type =3D getRela(Rel)->getType();
-      symbol_index =3D getRela(Rel)->getSymbol();
-      addend =3D getRela(Rel)->r_addend;
-      break;
-    }
-  }
-  const Elf_Sym *symb =3D getEntry<Elf_Sym>(sec->sh_link, symbol_index);
-  StringRef symname;
-  if (error_code ec =3D getSymbolName(symb, symname))
-    return ec;
-  switch (Header->e_machine) {
-  case ELF::EM_X86_64:
-    switch (type) {
-    case ELF::R_X86_64_32S:
-      res =3D symname;
-      break;
-    case ELF::R_X86_64_PC32: {
-        std::string fmtbuf;
-        raw_string_ostream fmt(fmtbuf);
-        fmt << symname << (addend < 0 ? "" : "+") << addend << "-P";
-        fmt.flush();
-        Result.append(fmtbuf.begin(), fmtbuf.end());
-      }
-      break;
-    default:
-      res =3D "Unknown";
-    }
-    break;
-  default:
-    res =3D "Unknown";
-  }
-  if (Result.empty())
-    Result.append(res.begin(), res.end());
-  return object_error::success;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-ELFObjectFile<target_endianness, is64Bits>::ELFObjectFile(MemoryBuffer *Ob=
ject
-                                                          , error_code &ec)
-  : ObjectFile(Binary::isELF, Object, ec)
-  , SectionHeaderTable(0)
-  , dot_shstrtab_sec(0)
-  , dot_strtab_sec(0) {
-  Header =3D reinterpret_cast<const Elf_Ehdr *>(base());
-
-  if (Header->e_shoff =3D=3D 0)
-    return;
-
-  SectionHeaderTable =3D
-    reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
-  uint64_t SectionTableSize =3D getNumSections() * Header->e_shentsize;
-  if (!(  (const uint8_t *)SectionHeaderTable + SectionTableSize
-         <=3D base() + Data->getBufferSize()))
-    // FIXME: Proper error handling.
-    report_fatal_error("Section table goes past end of file!");
-
-
-  // To find the symbol tables we walk the section table to find SHT_SYMTA=
B.
-  const Elf_Shdr* SymbolTableSectionHeaderIndex =3D 0;
-  const Elf_Shdr* sh =3D reinterpret_cast<const Elf_Shdr*>(SectionHeaderTa=
ble);
-  for (uint64_t i =3D 0, e =3D getNumSections(); i !=3D e; ++i) {
-    if (sh->sh_type =3D=3D ELF::SHT_SYMTAB_SHNDX) {
-      if (SymbolTableSectionHeaderIndex)
-        // FIXME: Proper error handling.
-        report_fatal_error("More than one .symtab_shndx!");
-      SymbolTableSectionHeaderIndex =3D sh;
-    }
-    if (sh->sh_type =3D=3D ELF::SHT_SYMTAB) {
-      SymbolTableSectionsIndexMap[i] =3D SymbolTableSections.size();
-      SymbolTableSections.push_back(sh);
-    }
-    if (sh->sh_type =3D=3D ELF::SHT_REL || sh->sh_type =3D=3D ELF::SHT_REL=
A) {
-      SectionRelocMap[getSection(sh->sh_info)].push_back(i);
-    }
-    ++sh;
-  }
-
-  // Sort section relocation lists by index.
-  for (typename RelocMap_t::iterator i =3D SectionRelocMap.begin(),
-                                     e =3D SectionRelocMap.end(); i !=3D e=
; ++i) {
-    std::sort(i->second.begin(), i->second.end());
-  }
-
-  // Get string table sections.
-  dot_shstrtab_sec =3D getSection(getStringTableIndex());
-  if (dot_shstrtab_sec) {
-    // Verify that the last byte in the string table in a null.
-    if (((const char*)base() + dot_shstrtab_sec->sh_offset)
-        [dot_shstrtab_sec->sh_size - 1] !=3D 0)
-      // FIXME: Proper error handling.
-      report_fatal_error("String table must end with a null terminator!");
-  }
-
-  // Merge this into the above loop.
-  for (const char *i =3D reinterpret_cast<const char *>(SectionHeaderTable=
),
-                  *e =3D i + getNumSections() * Header->e_shentsize;
-                   i !=3D e; i +=3D Header->e_shentsize) {
-    const Elf_Shdr *sh =3D reinterpret_cast<const Elf_Shdr*>(i);
-    if (sh->sh_type =3D=3D ELF::SHT_STRTAB) {
-      StringRef SectionName(getString(dot_shstrtab_sec, sh->sh_name));
-      if (SectionName =3D=3D ".strtab") {
-        if (dot_strtab_sec !=3D 0)
-          // FIXME: Proper error handling.
-          report_fatal_error("Already found section named .strtab!");
-        dot_strtab_sec =3D sh;
-        const char *dot_strtab =3D (const char*)base() + sh->sh_offset;
-          if (dot_strtab[sh->sh_size - 1] !=3D 0)
-            // FIXME: Proper error handling.
-            report_fatal_error("String table must end with a null terminat=
or!");
-      }
-    }
-  }
-
-  // Build symbol name side-mapping if there is one.
-  if (SymbolTableSectionHeaderIndex) {
-    const Elf_Word *ShndxTable =3D reinterpret_cast<const Elf_Word*>(base(=
) +
-                                      SymbolTableSectionHeaderIndex->sh_of=
fset);
-    error_code ec;
-    for (symbol_iterator si =3D begin_symbols(),
-                         se =3D end_symbols(); si !=3D se; si.increment(ec=
)) {
-      if (ec)
-        report_fatal_error("Fewer extended symbol table entries than symbo=
ls!");
-      if (*ShndxTable !=3D ELF::SHN_UNDEF)
-        ExtendedSymbolTable[getSymbol(si->getRawDataRefImpl())] =3D *Shndx=
Table;
-      ++ShndxTable;
-    }
-  }
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-symbol_iterator ELFObjectFile<target_endianness, is64Bits>
-                             ::begin_symbols() const {
-  DataRefImpl SymbolData;
-  memset(&SymbolData, 0, sizeof(SymbolData));
-  if (SymbolTableSections.size() =3D=3D 0) {
-    SymbolData.d.a =3D std::numeric_limits<uint32_t>::max();
-    SymbolData.d.b =3D std::numeric_limits<uint32_t>::max();
-  } else {
-    SymbolData.d.a =3D 1; // The 0th symbol in ELF is fake.
-    SymbolData.d.b =3D 0;
-  }
-  return symbol_iterator(SymbolRef(SymbolData, this));
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-symbol_iterator ELFObjectFile<target_endianness, is64Bits>
-                             ::end_symbols() const {
-  DataRefImpl SymbolData;
-  memset(&SymbolData, 0, sizeof(SymbolData));
-  SymbolData.d.a =3D std::numeric_limits<uint32_t>::max();
-  SymbolData.d.b =3D std::numeric_limits<uint32_t>::max();
-  return symbol_iterator(SymbolRef(SymbolData, this));
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-section_iterator ELFObjectFile<target_endianness, is64Bits>
-                              ::begin_sections() const {
-  DataRefImpl ret;
-  memset(&ret, 0, sizeof(DataRefImpl));
-  ret.p =3D reinterpret_cast<intptr_t>(base() + Header->e_shoff);
-  return section_iterator(SectionRef(ret, this));
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-section_iterator ELFObjectFile<target_endianness, is64Bits>
-                              ::end_sections() const {
-  DataRefImpl ret;
-  memset(&ret, 0, sizeof(DataRefImpl));
-  ret.p =3D reinterpret_cast<intptr_t>(base()
-                                     + Header->e_shoff
-                                     + (Header->e_shentsize*getNumSections=
()));
-  return section_iterator(SectionRef(ret, this));
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-uint8_t ELFObjectFile<target_endianness, is64Bits>::getBytesInAddress() co=
nst {
-  return is64Bits ? 8 : 4;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-StringRef ELFObjectFile<target_endianness, is64Bits>
-                       ::getFileFormatName() const {
-  switch(Header->e_ident[ELF::EI_CLASS]) {
-  case ELF::ELFCLASS32:
-    switch(Header->e_machine) {
-    case ELF::EM_386:
-      return "ELF32-i386";
-    case ELF::EM_X86_64:
-      return "ELF32-x86-64";
-    case ELF::EM_ARM:
-      return "ELF32-arm";
-    default:
-      return "ELF32-unknown";
-    }
-  case ELF::ELFCLASS64:
-    switch(Header->e_machine) {
-    case ELF::EM_386:
-      return "ELF64-i386";
-    case ELF::EM_X86_64:
-      return "ELF64-x86-64";
-    default:
-      return "ELF64-unknown";
-    }
-  default:
-    // FIXME: Proper error handling.
-    report_fatal_error("Invalid ELFCLASS!");
-  }
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-unsigned ELFObjectFile<target_endianness, is64Bits>::getArch() const {
-  switch(Header->e_machine) {
-  case ELF::EM_386:
-    return Triple::x86;
-  case ELF::EM_X86_64:
-    return Triple::x86_64;
-  case ELF::EM_ARM:
-    return Triple::arm;
-  default:
-    return Triple::UnknownArch;
-  }
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-uint64_t ELFObjectFile<target_endianness, is64Bits>::getNumSections() cons=
t {
-  if (Header->e_shnum =3D=3D ELF::SHN_UNDEF)
-    return SectionHeaderTable->sh_size;
-  return Header->e_shnum;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-uint64_t
-ELFObjectFile<target_endianness, is64Bits>::getStringTableIndex() const {
-  if (Header->e_shnum =3D=3D ELF::SHN_UNDEF) {
-    if (Header->e_shstrndx =3D=3D ELF::SHN_HIRESERVE)
-      return SectionHeaderTable->sh_link;
-    if (Header->e_shstrndx >=3D getNumSections())
-      return 0;
-  }
-  return Header->e_shstrndx;
-}
-
-
-template<support::endianness target_endianness, bool is64Bits>
-template<typename T>
-inline const T *
-ELFObjectFile<target_endianness, is64Bits>::getEntry(uint16_t Section,
-                                                     uint32_t Entry) const=
 {
-  return getEntry<T>(getSection(Section), Entry);
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-template<typename T>
-inline const T *
-ELFObjectFile<target_endianness, is64Bits>::getEntry(const Elf_Shdr * Sect=
ion,
-                                                     uint32_t Entry) const=
 {
-  return reinterpret_cast<const T *>(
-           base()
-           + Section->sh_offset
-           + (Entry * Section->sh_entsize));
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Sym *
-ELFObjectFile<target_endianness, is64Bits>::getSymbol(DataRefImpl Symb) co=
nst {
-  return getEntry<Elf_Sym>(SymbolTableSections[Symb.d.b], Symb.d.a);
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rel *
-ELFObjectFile<target_endianness, is64Bits>::getRel(DataRefImpl Rel) const {
-  return getEntry<Elf_Rel>(Rel.w.b, Rel.w.c);
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Rela *
-ELFObjectFile<target_endianness, is64Bits>::getRela(DataRefImpl Rela) cons=
t {
-  return getEntry<Elf_Rela>(Rela.w.b, Rela.w.c);
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
-ELFObjectFile<target_endianness, is64Bits>::getSection(DataRefImpl Symb) c=
onst {
-  const Elf_Shdr *sec =3D getSection(Symb.d.b);
-  if (sec->sh_type !=3D ELF::SHT_SYMTAB || sec->sh_type !=3D ELF::SHT_DYNS=
YM)
-    // FIXME: Proper error handling.
-    report_fatal_error("Invalid symbol table section!");
-  return sec;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const typename ELFObjectFile<target_endianness, is64Bits>::Elf_Shdr *
-ELFObjectFile<target_endianness, is64Bits>::getSection(uint32_t index) con=
st {
-  if (index =3D=3D 0)
-    return 0;
-  if (!SectionHeaderTable || index >=3D getNumSections())
-    // FIXME: Proper error handling.
-    report_fatal_error("Invalid section index!");
-
-  return reinterpret_cast<const Elf_Shdr *>(
-         reinterpret_cast<const char *>(SectionHeaderTable)
-         + (index * Header->e_shentsize));
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const char *ELFObjectFile<target_endianness, is64Bits>
-                         ::getString(uint32_t section,
-                                     ELF::Elf32_Word offset) const {
-  return getString(getSection(section), offset);
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-const char *ELFObjectFile<target_endianness, is64Bits>
-                         ::getString(const Elf_Shdr *section,
-                                     ELF::Elf32_Word offset) const {
-  assert(section && section->sh_type =3D=3D ELF::SHT_STRTAB && "Invalid se=
ction!");
-  if (offset >=3D section->sh_size)
-    // FIXME: Proper error handling.
-    report_fatal_error("Symbol name offset outside of string table!");
-  return (const char *)base() + section->sh_offset + offset;
-}
-
-template<support::endianness target_endianness, bool is64Bits>
-error_code ELFObjectFile<target_endianness, is64Bits>
-                        ::getSymbolName(const Elf_Sym *symb,
-                                        StringRef &Result) const {
-  if (symb->st_name =3D=3D 0) {
-    const Elf_Shdr *section =3D getSection(symb);
-    if (!section)
-      Result =3D "";
-    else
-      Result =3D getString(dot_shstrtab_sec, section->sh_name);
-    return object_error::success;
-  }
-
-  // Use the default symbol table name section.
-  Result =3D getString(dot_strtab_sec, symb->st_name);
-  return object_error::success;
-}
-
-// EI_CLASS, EI_DATA.
-static std::pair<unsigned char, unsigned char>
-getElfArchType(MemoryBuffer *Object) {
-  if (Object->getBufferSize() < ELF::EI_NIDENT)
-    return std::make_pair((uint8_t)ELF::ELFCLASSNONE,(uint8_t)ELF::ELFDATA=
NONE);
-  return std::make_pair( (uint8_t)Object->getBufferStart()[ELF::EI_CLASS]
-                       , (uint8_t)Object->getBufferStart()[ELF::EI_DATA]);
-}
-
-namespace llvm {
-
-  ObjectFile *ObjectFile::createELFObjectFile(MemoryBuffer *Object) {
-    std::pair<unsigned char, unsigned char> Ident =3D getElfArchType(Objec=
t);
-    error_code ec;
-    if (Ident.first =3D=3D ELF::ELFCLASS32 && Ident.second =3D=3D ELF::ELF=
DATA2LSB)
-      return new ELFObjectFile<support::little, false>(Object, ec);
-    else if (Ident.first =3D=3D ELF::ELFCLASS32 && Ident.second =3D=3D ELF=
::ELFDATA2MSB)
-      return new ELFObjectFile<support::big, false>(Object, ec);
-    else if (Ident.first =3D=3D ELF::ELFCLASS64 && Ident.second =3D=3D ELF=
::ELFDATA2LSB)
-      return new ELFObjectFile<support::little, true>(Object, ec);
-    else if (Ident.first =3D=3D ELF::ELFCLASS64 && Ident.second =3D=3D ELF=
::ELFDATA2MSB)
-      return new ELFObjectFile<support::big, true>(Object, ec);
-    // FIXME: Proper error handling.
-    report_fatal_error("Not an ELF object file!");
-  }
-
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Object/MachOObje=
ct.cpp
--- a/head/contrib/llvm/lib/Object/MachOObject.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/Object/MachOObject.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -10,11 +10,12 @@
 #include "llvm/Object/MachOObject.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/DataExtractor.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/Host.h"
 #include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/Host.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/SwapByteOrder.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/Debug.h"
=20
 using namespace llvm;
 using namespace llvm::object;
@@ -359,25 +360,13 @@
=20
 void MachOObject::ReadULEB128s(uint64_t Index,
                                SmallVectorImpl<uint64_t> &Out) const {
-  const char *ptr =3D Buffer->getBufferStart() + Index;
+  DataExtractor extractor(Buffer->getBuffer(), true, 0);
+
+  uint32_t offset =3D Index;
   uint64_t data =3D 0;
-  uint64_t delta =3D 0;
-  uint32_t shift =3D 0;
-  while (true) {
-    assert(ptr < Buffer->getBufferEnd() && "index out of bounds");
-    assert(shift < 64 && "too big for uint64_t");
-
-    uint8_t byte =3D *ptr++;
-    delta |=3D ((byte & 0x7F) << shift);
-    shift +=3D 7;
-    if (byte < 0x80) {
-      if (delta =3D=3D 0)
-        break;
-      data +=3D delta;
-      Out.push_back(data);
-      delta =3D 0;
-      shift =3D 0;
-    }
+  while (uint64_t delta =3D extractor.getULEB128(&offset)) {
+    data +=3D delta;
+    Out.push_back(data);
   }
 }
=20
@@ -393,7 +382,7 @@
   O << "('num_load_commands', " << Header.NumLoadCommands << ")\n";
   O << "('load_commands_size', " << Header.SizeOfLoadCommands << ")\n";
   O << "('flag', " << Header.Flags << ")\n";
- =20
+
   // Print extended header if 64-bit.
   if (is64Bit())
     O << "('reserved', " << Header64Ext.Reserved << ")\n";
@@ -403,6 +392,6 @@
   O << "Header:\n";
   printHeader(O);
   O << "Load Commands:\n";
- =20
+
   O << "Buffer:\n";
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Object/MachOObje=
ctFile.cpp
--- a/head/contrib/llvm/lib/Object/MachOObjectFile.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Object/MachOObjectFile.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -15,6 +15,7 @@
 #include "llvm/ADT/Triple.h"
 #include "llvm/Object/MachO.h"
 #include "llvm/Object/MachOFormat.h"
+#include "llvm/Support/Format.h"
 #include "llvm/Support/MemoryBuffer.h"
=20
 #include <cctype>
@@ -29,11 +30,10 @@
=20
 MachOObjectFile::MachOObjectFile(MemoryBuffer *Object, MachOObject *MOO,
                                  error_code &ec)
-    : ObjectFile(Binary::isMachO, Object, ec),
+    : ObjectFile(Binary::ID_MachO, Object, ec),
       MachOObj(MOO),
       RegisteredStringTable(std::numeric_limits<uint32_t>::max()) {
   DataRefImpl DRI;
-  DRI.d.a =3D DRI.d.b =3D 0;
   moveToNextSection(DRI);
   uint32_t LoadCommandCount =3D MachOObj->getHeader().NumLoadCommands;
   while (DRI.d.a < LoadCommandCount) {
@@ -124,23 +124,27 @@
   return object_error::success;
 }
=20
-error_code MachOObjectFile::getSymbolOffset(DataRefImpl DRI,
-                                             uint64_t &Result) const {
-  uint64_t SectionOffset;
-  uint8_t SectionIndex;
+error_code MachOObjectFile::getSymbolFileOffset(DataRefImpl DRI,
+                                                uint64_t &Result) const {
   if (MachOObj->is64Bit()) {
     InMemoryStruct<macho::Symbol64TableEntry> Entry;
     getSymbol64TableEntry(DRI, Entry);
     Result =3D Entry->Value;
-    SectionIndex =3D Entry->SectionIndex;
+    if (Entry->SectionIndex) {
+      InMemoryStruct<macho::Section64> Section;
+      getSection64(Sections[Entry->SectionIndex-1], Section);
+      Result +=3D Section->Offset - Section->Address;
+    }
   } else {
     InMemoryStruct<macho::SymbolTableEntry> Entry;
     getSymbolTableEntry(DRI, Entry);
     Result =3D Entry->Value;
-    SectionIndex =3D Entry->SectionIndex;
+    if (Entry->SectionIndex) {
+      InMemoryStruct<macho::Section> Section;
+      getSection(Sections[Entry->SectionIndex-1], Section);
+      Result +=3D Section->Offset - Section->Address;
+    }
   }
-  getSectionAddress(Sections[SectionIndex-1], SectionOffset);
-  Result -=3D SectionOffset;
=20
   return object_error::success;
 }
@@ -161,7 +165,74 @@
=20
 error_code MachOObjectFile::getSymbolSize(DataRefImpl DRI,
                                           uint64_t &Result) const {
-  Result =3D UnknownAddressOrSize;
+  uint32_t LoadCommandCount =3D MachOObj->getHeader().NumLoadCommands;
+  uint64_t BeginOffset;
+  uint64_t EndOffset =3D 0;
+  uint8_t SectionIndex;
+  if (MachOObj->is64Bit()) {
+    InMemoryStruct<macho::Symbol64TableEntry> Entry;
+    getSymbol64TableEntry(DRI, Entry);
+    BeginOffset =3D Entry->Value;
+    SectionIndex =3D Entry->SectionIndex;
+    if (!SectionIndex) {
+      uint32_t flags =3D SymbolRef::SF_None;
+      getSymbolFlags(DRI, flags);
+      if (flags & SymbolRef::SF_Common)
+        Result =3D Entry->Value;
+      else
+        Result =3D UnknownAddressOrSize;
+      return object_error::success;
+    }
+    // Unfortunately symbols are unsorted so we need to touch all
+    // symbols from load command
+    DRI.d.b =3D 0;
+    uint32_t Command =3D DRI.d.a;
+    while (Command =3D=3D DRI.d.a) {
+      moveToNextSymbol(DRI);
+      if (DRI.d.a < LoadCommandCount) {
+        getSymbol64TableEntry(DRI, Entry);
+        if (Entry->SectionIndex =3D=3D SectionIndex && Entry->Value > Begi=
nOffset)
+          if (!EndOffset || Entry->Value < EndOffset)
+            EndOffset =3D Entry->Value;
+      }
+      DRI.d.b++;
+    }
+  } else {
+    InMemoryStruct<macho::SymbolTableEntry> Entry;
+    getSymbolTableEntry(DRI, Entry);
+    BeginOffset =3D Entry->Value;
+    SectionIndex =3D Entry->SectionIndex;
+    if (!SectionIndex) {
+      uint32_t flags =3D SymbolRef::SF_None;
+      getSymbolFlags(DRI, flags);
+      if (flags & SymbolRef::SF_Common)
+        Result =3D Entry->Value;
+      else
+        Result =3D UnknownAddressOrSize;
+      return object_error::success;
+    }
+    // Unfortunately symbols are unsorted so we need to touch all
+    // symbols from load command
+    DRI.d.b =3D 0;
+    uint32_t Command =3D DRI.d.a;
+    while (Command =3D=3D DRI.d.a) {
+      moveToNextSymbol(DRI);
+      if (DRI.d.a < LoadCommandCount) {
+        getSymbolTableEntry(DRI, Entry);
+        if (Entry->SectionIndex =3D=3D SectionIndex && Entry->Value > Begi=
nOffset)
+          if (!EndOffset || Entry->Value < EndOffset)
+            EndOffset =3D Entry->Value;
+      }
+      DRI.d.b++;
+    }
+  }
+  if (!EndOffset) {
+    uint64_t Size;
+    getSectionSize(Sections[SectionIndex-1], Size);
+    getSectionAddress(Sections[SectionIndex-1], EndOffset);
+    EndOffset +=3D Size;
+  }
+  Result =3D EndOffset - BeginOffset;
   return object_error::success;
 }
=20
@@ -200,36 +271,69 @@
   return object_error::success;
 }
=20
-error_code MachOObjectFile::isSymbolInternal(DataRefImpl DRI,
-                                             bool &Result) const {
+error_code MachOObjectFile::getSymbolFlags(DataRefImpl DRI,
+                                           uint32_t &Result) const {
+  uint16_t MachOFlags;
+  uint8_t MachOType;
   if (MachOObj->is64Bit()) {
     InMemoryStruct<macho::Symbol64TableEntry> Entry;
     getSymbol64TableEntry(DRI, Entry);
-    Result =3D Entry->Flags & macho::STF_StabsEntryMask;
+    MachOFlags =3D Entry->Flags;
+    MachOType =3D Entry->Type;
   } else {
     InMemoryStruct<macho::SymbolTableEntry> Entry;
     getSymbolTableEntry(DRI, Entry);
-    Result =3D Entry->Flags & macho::STF_StabsEntryMask;
+    MachOFlags =3D Entry->Flags;
+    MachOType =3D Entry->Type;
   }
+
+  // TODO: Correctly set SF_ThreadLocal
+  Result =3D SymbolRef::SF_None;
+
+  if ((MachOType & MachO::NlistMaskType) =3D=3D MachO::NListTypeUndefined)
+    Result |=3D SymbolRef::SF_Undefined;
+
+  if (MachOFlags & macho::STF_StabsEntryMask)
+    Result |=3D SymbolRef::SF_FormatSpecific;
+
+  if (MachOType & MachO::NlistMaskExternal) {
+    Result |=3D SymbolRef::SF_Global;
+    if ((MachOType & MachO::NlistMaskType) =3D=3D MachO::NListTypeUndefine=
d)
+      Result |=3D SymbolRef::SF_Common;
+  }
+
+  if (MachOFlags & (MachO::NListDescWeakRef | MachO::NListDescWeakDef))
+    Result |=3D SymbolRef::SF_Weak;
+
+  if ((MachOType & MachO::NlistMaskType) =3D=3D MachO::NListTypeAbsolute)
+    Result |=3D SymbolRef::SF_Absolute;
+
   return object_error::success;
 }
=20
-error_code MachOObjectFile::isSymbolGlobal(DataRefImpl Symb, bool &Res) co=
nst {
-
+error_code MachOObjectFile::getSymbolSection(DataRefImpl Symb,
+                                             section_iterator &Res) const {
+  uint8_t index;
   if (MachOObj->is64Bit()) {
     InMemoryStruct<macho::Symbol64TableEntry> Entry;
     getSymbol64TableEntry(Symb, Entry);
-    Res =3D Entry->Type & MachO::NlistMaskExternal;
+    index =3D Entry->SectionIndex;
   } else {
     InMemoryStruct<macho::SymbolTableEntry> Entry;
     getSymbolTableEntry(Symb, Entry);
-    Res =3D Entry->Type & MachO::NlistMaskExternal;
+    index =3D Entry->SectionIndex;
   }
+
+  if (index =3D=3D 0)
+    Res =3D end_sections();
+  else
+    Res =3D section_iterator(SectionRef(Sections[index-1], this));
+
   return object_error::success;
 }
=20
 error_code MachOObjectFile::getSymbolType(DataRefImpl Symb,
-                                          SymbolRef::SymbolType &Res) cons=
t {
+                                          SymbolRef::Type &Res) const {
   uint8_t n_type;
   if (MachOObj->is64Bit()) {
     InMemoryStruct<macho::Symbol64TableEntry> Entry;
@@ -243,12 +347,14 @@
   Res =3D SymbolRef::ST_Other;
=20
   // If this is a STAB debugging symbol, we can do nothing more.
-  if (n_type & MachO::NlistMaskStab)
+  if (n_type & MachO::NlistMaskStab) {
+    Res =3D SymbolRef::ST_Debug;
     return object_error::success;
+  }
=20
   switch (n_type & MachO::NlistMaskType) {
     case MachO::NListTypeUndefined :
-      Res =3D SymbolRef::ST_External;
+      Res =3D SymbolRef::ST_Unknown;
       break;
     case MachO::NListTypeSection :
       Res =3D SymbolRef::ST_Function;
@@ -261,7 +367,6 @@
 symbol_iterator MachOObjectFile::begin_symbols() const {
   // DRI.d.a =3D segment number; DRI.d.b =3D symbol index.
   DataRefImpl DRI;
-  DRI.d.a =3D DRI.d.b =3D 0;
   moveToNextSymbol(DRI);
   return symbol_iterator(SymbolRef(DRI, this));
 }
@@ -269,10 +374,33 @@
 symbol_iterator MachOObjectFile::end_symbols() const {
   DataRefImpl DRI;
   DRI.d.a =3D MachOObj->getHeader().NumLoadCommands;
-  DRI.d.b =3D 0;
   return symbol_iterator(SymbolRef(DRI, this));
 }
=20
+symbol_iterator MachOObjectFile::begin_dynamic_symbols() const {
+  // TODO: implement
+  report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
+}
+
+symbol_iterator MachOObjectFile::end_dynamic_symbols() const {
+  // TODO: implement
+  report_fatal_error("Dynamic symbols unimplemented in MachOObjectFile");
+}
+
+library_iterator MachOObjectFile::begin_libraries_needed() const {
+  // TODO: implement
+  report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
+}
+
+library_iterator MachOObjectFile::end_libraries_needed() const {
+  // TODO: implement
+  report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
+}
+
+StringRef MachOObjectFile::getLoadName() const {
+  // TODO: Implement
+  report_fatal_error("get_load_name() unimplemented in MachOObjectFile");
+}
=20
 /*=3D=3D=3D-- Sections ---------------------------------------------------=
-------=3D=3D=3D*/
=20
@@ -451,12 +579,43 @@
   return object_error::success;
 }
=20
+error_code MachOObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
+                                                          bool &Result) co=
nst {
+  // FIXME: Unimplemented
+  Result =3D true;
+  return object_error::success;
+}
+
+error_code MachOObjectFile::isSectionVirtual(DataRefImpl Sec,
+                                            bool &Result) const {
+  // FIXME: Unimplemented
+  Result =3D false;
+  return object_error::success;
+}
+
+error_code MachOObjectFile::isSectionZeroInit(DataRefImpl DRI,
+                                              bool &Result) const {
+  if (MachOObj->is64Bit()) {
+    InMemoryStruct<macho::Section64> Sect;
+    getSection64(DRI, Sect);
+    Result =3D (Sect->Flags & MachO::SectionTypeZeroFill ||
+              Sect->Flags & MachO::SectionTypeZeroFillLarge);
+  } else {
+    InMemoryStruct<macho::Section> Sect;
+    getSection(DRI, Sect);
+    Result =3D (Sect->Flags & MachO::SectionTypeZeroFill ||
+              Sect->Flags & MachO::SectionTypeZeroFillLarge);
+  }
+
+  return object_error::success;
+}
+
 error_code MachOObjectFile::sectionContainsSymbol(DataRefImpl Sec,
                                                   DataRefImpl Symb,
                                                   bool &Result) const {
-  SymbolRef::SymbolType ST;
+  SymbolRef::Type ST;
   getSymbolType(Symb, ST);
-  if (ST =3D=3D SymbolRef::ST_External) {
+  if (ST =3D=3D SymbolRef::ST_Unknown) {
     Result =3D false;
     return object_error::success;
   }
@@ -483,7 +642,6 @@
=20
 relocation_iterator MachOObjectFile::getSectionRelBegin(DataRefImpl Sec) c=
onst {
   DataRefImpl ret;
-  ret.d.a =3D 0;
   ret.d.b =3D getSectionIndex(Sec);
   return relocation_iterator(RelocationRef(ret, this));
 }
@@ -506,7 +664,6 @@
=20
 section_iterator MachOObjectFile::begin_sections() const {
   DataRefImpl DRI;
-  DRI.d.a =3D DRI.d.b =3D 0;
   moveToNextSection(DRI);
   return section_iterator(SectionRef(DRI, this));
 }
@@ -514,7 +671,6 @@
 section_iterator MachOObjectFile::end_sections() const {
   DataRefImpl DRI;
   DRI.d.a =3D MachOObj->getHeader().NumLoadCommands;
-  DRI.d.b =3D 0;
   return section_iterator(SectionRef(DRI, this));
 }
=20
@@ -543,19 +699,43 @@
 }
 error_code MachOObjectFile::getRelocationAddress(DataRefImpl Rel,
                                                  uint64_t &Res) const {
-  const uint8_t* sectAddress =3D base();
+  const uint8_t* sectAddress =3D 0;
   if (MachOObj->is64Bit()) {
     InMemoryStruct<macho::Section64> Sect;
     getSection64(Sections[Rel.d.b], Sect);
-    sectAddress +=3D Sect->Offset;
+    sectAddress +=3D Sect->Address;
   } else {
     InMemoryStruct<macho::Section> Sect;
     getSection(Sections[Rel.d.b], Sect);
-    sectAddress +=3D Sect->Offset;
+    sectAddress +=3D Sect->Address;
   }
   InMemoryStruct<macho::RelocationEntry> RE;
   getRelocation(Rel, RE);
-  Res =3D reinterpret_cast<uintptr_t>(sectAddress + RE->Word0);
+
+  unsigned Arch =3D getArch();
+  bool isScattered =3D (Arch !=3D Triple::x86_64) &&
+                     (RE->Word0 & macho::RF_Scattered);
+  uint64_t RelAddr =3D 0;
+  if (isScattered)
+    RelAddr =3D RE->Word0 & 0xFFFFFF;
+  else
+    RelAddr =3D RE->Word0;
+
+  Res =3D reinterpret_cast<uintptr_t>(sectAddress + RelAddr);
+  return object_error::success;
+}
+error_code MachOObjectFile::getRelocationOffset(DataRefImpl Rel,
+                                                uint64_t &Res) const {
+  InMemoryStruct<macho::RelocationEntry> RE;
+  getRelocation(Rel, RE);
+
+  unsigned Arch =3D getArch();
+  bool isScattered =3D (Arch !=3D Triple::x86_64) &&
+                     (RE->Word0 & macho::RF_Scattered);
+  if (isScattered)
+    Res =3D RE->Word0 & 0xFFFFFF;
+  else
+    Res =3D RE->Word0;
   return object_error::success;
 }
 error_code MachOObjectFile::getRelocationSymbol(DataRefImpl Rel,
@@ -566,7 +746,6 @@
   bool isExtern =3D (RE->Word1 >> 27) & 1;
=20
   DataRefImpl Sym;
-  Sym.d.a =3D Sym.d.b =3D 0;
   moveToNextSymbol(Sym);
   if (isExtern) {
     for (unsigned i =3D 0; i < SymbolIdx; i++) {
@@ -580,14 +759,112 @@
   return object_error::success;
 }
 error_code MachOObjectFile::getRelocationType(DataRefImpl Rel,
-                                              uint32_t &Res) const {
+                                              uint64_t &Res) const {
   InMemoryStruct<macho::RelocationEntry> RE;
   getRelocation(Rel, RE);
-  Res =3D RE->Word1;
+  Res =3D RE->Word0;
+  Res <<=3D 32;
+  Res |=3D RE->Word1;
   return object_error::success;
 }
 error_code MachOObjectFile::getRelocationTypeName(DataRefImpl Rel,
                                           SmallVectorImpl<char> &Result) c=
onst {
+  // TODO: Support scattered relocations.
+  StringRef res;
+  InMemoryStruct<macho::RelocationEntry> RE;
+  getRelocation(Rel, RE);
+
+  unsigned Arch =3D getArch();
+  bool isScattered =3D (Arch !=3D Triple::x86_64) &&
+                     (RE->Word0 & macho::RF_Scattered);
+
+  unsigned r_type;
+  if (isScattered)
+    r_type =3D (RE->Word0 >> 24) & 0xF;
+  else
+    r_type =3D (RE->Word1 >> 28) & 0xF;
+
+  switch (Arch) {
+    case Triple::x86: {
+      const char* Table[] =3D  {
+        "GENERIC_RELOC_VANILLA",
+        "GENERIC_RELOC_PAIR",
+        "GENERIC_RELOC_SECTDIFF",
+        "GENERIC_RELOC_PB_LA_PTR",
+        "GENERIC_RELOC_LOCAL_SECTDIFF",
+        "GENERIC_RELOC_TLV" };
+
+      if (r_type > 6)
+        res =3D "Unknown";
+      else
+        res =3D Table[r_type];
+      break;
+    }
+    case Triple::x86_64: {
+      const char* Table[] =3D  {
+        "X86_64_RELOC_UNSIGNED",
+        "X86_64_RELOC_SIGNED",
+        "X86_64_RELOC_BRANCH",
+        "X86_64_RELOC_GOT_LOAD",
+        "X86_64_RELOC_GOT",
+        "X86_64_RELOC_SUBTRACTOR",
+        "X86_64_RELOC_SIGNED_1",
+        "X86_64_RELOC_SIGNED_2",
+        "X86_64_RELOC_SIGNED_4",
+        "X86_64_RELOC_TLV" };
+
+      if (r_type > 9)
+        res =3D "Unknown";
+      else
+        res =3D Table[r_type];
+      break;
+    }
+    case Triple::arm: {
+      const char* Table[] =3D  {
+        "ARM_RELOC_VANILLA",
+        "ARM_RELOC_PAIR",
+        "ARM_RELOC_SECTDIFF",
+        "ARM_RELOC_LOCAL_SECTDIFF",
+        "ARM_RELOC_PB_LA_PTR",
+        "ARM_RELOC_BR24",
+        "ARM_THUMB_RELOC_BR22",
+        "ARM_THUMB_32BIT_BRANCH",
+        "ARM_RELOC_HALF",
+        "ARM_RELOC_HALF_SECTDIFF" };
+
+      if (r_type > 9)
+        res =3D "Unknown";
+      else
+        res =3D Table[r_type];
+      break;
+    }
+    case Triple::ppc: {
+      const char* Table[] =3D  {
+        "PPC_RELOC_VANILLA",
+        "PPC_RELOC_PAIR",
+        "PPC_RELOC_BR14",
+        "PPC_RELOC_BR24",
+        "PPC_RELOC_HI16",
+        "PPC_RELOC_LO16",
+        "PPC_RELOC_HA16",
+        "PPC_RELOC_LO14",
+        "PPC_RELOC_SECTDIFF",
+        "PPC_RELOC_PB_LA_PTR",
+        "PPC_RELOC_HI16_SECTDIFF",
+        "PPC_RELOC_LO16_SECTDIFF",
+        "PPC_RELOC_HA16_SECTDIFF",
+        "PPC_RELOC_JBSR",
+        "PPC_RELOC_LO14_SECTDIFF",
+        "PPC_RELOC_LOCAL_SECTDIFF" };
+
+      res =3D Table[r_type];
+      break;
+    }
+    case Triple::UnknownArch:
+      res =3D "Unknown";
+      break;
+  }
+  Result.append(res.begin(), res.end());
   return object_error::success;
 }
 error_code MachOObjectFile::getRelocationAdditionalInfo(DataRefImpl Rel,
@@ -611,11 +888,356 @@
   }
   return object_error::success;
 }
+
+// Helper to advance a section or symbol iterator multiple increments at a=
 time.
+template<class T>
+error_code advance(T &it, size_t Val) {
+  error_code ec;
+  while (Val--) {
+    it.increment(ec);
+  }
+  return ec;
+}
+
+template<class T>
+void advanceTo(T &it, size_t Val) {
+  if (error_code ec =3D advance(it, Val))
+    report_fatal_error(ec.message());
+}
+
+void MachOObjectFile::printRelocationTargetName(
+                                     InMemoryStruct<macho::RelocationEntry=
>& RE,
+                                     raw_string_ostream &fmt) const {
+  unsigned Arch =3D getArch();
+  bool isScattered =3D (Arch !=3D Triple::x86_64) &&
+                     (RE->Word0 & macho::RF_Scattered);
+
+  // Target of a scattered relocation is an address.  In the interest of
+  // generating pretty output, scan through the symbol table looking for a
+  // symbol that aligns with that address.  If we find one, print it.
+  // Otherwise, we just print the hex address of the target.
+  if (isScattered) {
+    uint32_t Val =3D RE->Word1;
+
+    error_code ec;
+    for (symbol_iterator SI =3D begin_symbols(), SE =3D end_symbols(); SI =
!=3D SE;
+        SI.increment(ec)) {
+      if (ec) report_fatal_error(ec.message());
+
+      uint64_t Addr;
+      StringRef Name;
+
+      if ((ec =3D SI->getAddress(Addr)))
+        report_fatal_error(ec.message());
+      if (Addr !=3D Val) continue;
+      if ((ec =3D SI->getName(Name)))
+        report_fatal_error(ec.message());
+      fmt << Name;
+      return;
+    }
+
+    // If we couldn't find a symbol that this relocation refers to, try
+    // to find a section beginning instead.
+    for (section_iterator SI =3D begin_sections(), SE =3D end_sections(); =
SI !=3D SE;
+         SI.increment(ec)) {
+      if (ec) report_fatal_error(ec.message());
+
+      uint64_t Addr;
+      StringRef Name;
+
+      if ((ec =3D SI->getAddress(Addr)))
+        report_fatal_error(ec.message());
+      if (Addr !=3D Val) continue;
+      if ((ec =3D SI->getName(Name)))
+        report_fatal_error(ec.message());
+      fmt << Name;
+      return;
+    }
+
+    fmt << format("0x%x", Val);
+    return;
+  }
+
+  StringRef S;
+  bool isExtern =3D (RE->Word1 >> 27) & 1;
+  uint32_t Val =3D RE->Word1 & 0xFFFFFF;
+
+  if (isExtern) {
+    symbol_iterator SI =3D begin_symbols();
+    advanceTo(SI, Val);
+    SI->getName(S);
+  } else {
+    section_iterator SI =3D begin_sections();
+    advanceTo(SI, Val);
+    SI->getName(S);
+  }
+
+  fmt << S;
+}
+
 error_code MachOObjectFile::getRelocationValueString(DataRefImpl Rel,
                                           SmallVectorImpl<char> &Result) c=
onst {
+  InMemoryStruct<macho::RelocationEntry> RE;
+  getRelocation(Rel, RE);
+
+  unsigned Arch =3D getArch();
+  bool isScattered =3D (Arch !=3D Triple::x86_64) &&
+                     (RE->Word0 & macho::RF_Scattered);
+
+  std::string fmtbuf;
+  raw_string_ostream fmt(fmtbuf);
+
+  unsigned Type;
+  if (isScattered)
+    Type =3D (RE->Word0 >> 24) & 0xF;
+  else
+    Type =3D (RE->Word1 >> 28) & 0xF;
+
+  bool isPCRel;
+  if (isScattered)
+    isPCRel =3D ((RE->Word0 >> 30) & 1);
+  else
+    isPCRel =3D ((RE->Word1 >> 24) & 1);
+
+  // Determine any addends that should be displayed with the relocation.
+  // These require decoding the relocation type, which is triple-specific.
+
+  // X86_64 has entirely custom relocation types.
+  if (Arch =3D=3D Triple::x86_64) {
+    bool isPCRel =3D ((RE->Word1 >> 24) & 1);
+
+    switch (Type) {
+      case macho::RIT_X86_64_GOTLoad:   // X86_64_RELOC_GOT_LOAD
+      case macho::RIT_X86_64_GOT: {     // X86_64_RELOC_GOT
+        printRelocationTargetName(RE, fmt);
+        fmt << "@GOT";
+        if (isPCRel) fmt << "PCREL";
+        break;
+      }
+      case macho::RIT_X86_64_Subtractor: { // X86_64_RELOC_SUBTRACTOR
+        InMemoryStruct<macho::RelocationEntry> RENext;
+        DataRefImpl RelNext =3D Rel;
+        RelNext.d.a++;
+        getRelocation(RelNext, RENext);
+
+        // X86_64_SUBTRACTOR must be followed by a relocation of type
+        // X86_64_RELOC_UNSIGNED.
+        // NOTE: Scattered relocations don't exist on x86_64.
+        unsigned RType =3D (RENext->Word1 >> 28) & 0xF;
+        if (RType !=3D 0)
+          report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
+                             "X86_64_RELOC_SUBTRACTOR.");
+
+        // The X86_64_RELOC_UNSIGNED contains the minuend symbol,
+        // X86_64_SUBTRACTOR contains to the subtrahend.
+        printRelocationTargetName(RENext, fmt);
+        fmt << "-";
+        printRelocationTargetName(RE, fmt);
+      }
+      case macho::RIT_X86_64_TLV:
+        printRelocationTargetName(RE, fmt);
+        fmt << "@TLV";
+        if (isPCRel) fmt << "P";
+        break;
+      case macho::RIT_X86_64_Signed1: // X86_64_RELOC_SIGNED1
+        printRelocationTargetName(RE, fmt);
+        fmt << "-1";
+        break;
+      case macho::RIT_X86_64_Signed2: // X86_64_RELOC_SIGNED2
+        printRelocationTargetName(RE, fmt);
+        fmt << "-2";
+        break;
+      case macho::RIT_X86_64_Signed4: // X86_64_RELOC_SIGNED4
+        printRelocationTargetName(RE, fmt);
+        fmt << "-4";
+        break;
+      default:
+        printRelocationTargetName(RE, fmt);
+        break;
+    }
+  // X86 and ARM share some relocation types in common.
+  } else if (Arch =3D=3D Triple::x86 || Arch =3D=3D Triple::arm) {
+    // Generic relocation types...
+    switch (Type) {
+      case macho::RIT_Pair: // GENERIC_RELOC_PAIR - prints no info
+        return object_error::success;
+      case macho::RIT_Difference: { // GENERIC_RELOC_SECTDIFF
+        InMemoryStruct<macho::RelocationEntry> RENext;
+        DataRefImpl RelNext =3D Rel;
+        RelNext.d.a++;
+        getRelocation(RelNext, RENext);
+
+        // X86 sect diff's must be followed by a relocation of type
+        // GENERIC_RELOC_PAIR.
+        bool isNextScattered =3D (Arch !=3D Triple::x86_64) &&
+                               (RENext->Word0 & macho::RF_Scattered);
+        unsigned RType;
+        if (isNextScattered)
+          RType =3D (RENext->Word0 >> 24) & 0xF;
+        else
+          RType =3D (RENext->Word1 >> 28) & 0xF;
+        if (RType !=3D 1)
+          report_fatal_error("Expected GENERIC_RELOC_PAIR after "
+                             "GENERIC_RELOC_SECTDIFF.");
+
+        printRelocationTargetName(RE, fmt);
+        fmt << "-";
+        printRelocationTargetName(RENext, fmt);
+        break;
+      }
+    }
+
+    if (Arch =3D=3D Triple::x86) {
+      // All X86 relocations that need special printing were already
+      // handled in the generic code.
+      switch (Type) {
+        case macho::RIT_Generic_LocalDifference:{// GENERIC_RELOC_LOCAL_SE=
CTDIFF
+          InMemoryStruct<macho::RelocationEntry> RENext;
+          DataRefImpl RelNext =3D Rel;
+          RelNext.d.a++;
+          getRelocation(RelNext, RENext);
+
+          // X86 sect diff's must be followed by a relocation of type
+          // GENERIC_RELOC_PAIR.
+          bool isNextScattered =3D (Arch !=3D Triple::x86_64) &&
+                               (RENext->Word0 & macho::RF_Scattered);
+          unsigned RType;
+          if (isNextScattered)
+            RType =3D (RENext->Word0 >> 24) & 0xF;
+          else
+            RType =3D (RENext->Word1 >> 28) & 0xF;
+          if (RType !=3D 1)
+            report_fatal_error("Expected GENERIC_RELOC_PAIR after "
+                               "GENERIC_RELOC_LOCAL_SECTDIFF.");
+
+          printRelocationTargetName(RE, fmt);
+          fmt << "-";
+          printRelocationTargetName(RENext, fmt);
+          break;
+        }
+        case macho::RIT_Generic_TLV: {
+          printRelocationTargetName(RE, fmt);
+          fmt << "@TLV";
+          if (isPCRel) fmt << "P";
+          break;
+        }
+        default:
+          printRelocationTargetName(RE, fmt);
+      }
+    } else { // ARM-specific relocations
+      switch (Type) {
+        case macho::RIT_ARM_Half:             // ARM_RELOC_HALF
+        case macho::RIT_ARM_HalfDifference: { // ARM_RELOC_HALF_SECTDIFF
+          // Half relocations steal a bit from the length field to encode
+          // whether this is an upper16 or a lower16 relocation.
+          bool isUpper;
+          if (isScattered)
+            isUpper =3D (RE->Word0 >> 28) & 1;
+          else
+            isUpper =3D (RE->Word1 >> 25) & 1;
+
+          if (isUpper)
+            fmt << ":upper16:(";
+          else
+            fmt << ":lower16:(";
+          printRelocationTargetName(RE, fmt);
+
+          InMemoryStruct<macho::RelocationEntry> RENext;
+          DataRefImpl RelNext =3D Rel;
+          RelNext.d.a++;
+          getRelocation(RelNext, RENext);
+
+          // ARM half relocs must be followed by a relocation of type
+          // ARM_RELOC_PAIR.
+          bool isNextScattered =3D (Arch !=3D Triple::x86_64) &&
+                                 (RENext->Word0 & macho::RF_Scattered);
+          unsigned RType;
+          if (isNextScattered)
+            RType =3D (RENext->Word0 >> 24) & 0xF;
+          else
+            RType =3D (RENext->Word1 >> 28) & 0xF;
+
+          if (RType !=3D 1)
+            report_fatal_error("Expected ARM_RELOC_PAIR after "
+                               "GENERIC_RELOC_HALF");
+
+          // NOTE: The half of the target virtual address is stashed in the
+          // address field of the secondary relocation, but we can't rever=
se
+          // engineer the constant offset from it without decoding the mov=
w/movt
+          // instruction to find the other half in its immediate field.
+
+          // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
+          // symbol/section pointer of the follow-on relocation.
+          if (Type =3D=3D macho::RIT_ARM_HalfDifference) {
+            fmt << "-";
+            printRelocationTargetName(RENext, fmt);
+          }
+
+          fmt << ")";
+          break;
+        }
+        default: {
+          printRelocationTargetName(RE, fmt);
+        }
+      }
+    }
+  } else
+    printRelocationTargetName(RE, fmt);
+
+  fmt.flush();
+  Result.append(fmtbuf.begin(), fmtbuf.end());
   return object_error::success;
 }
=20
+error_code MachOObjectFile::getRelocationHidden(DataRefImpl Rel,
+                                                bool &Result) const {
+  InMemoryStruct<macho::RelocationEntry> RE;
+  getRelocation(Rel, RE);
+
+  unsigned Arch =3D getArch();
+  bool isScattered =3D (Arch !=3D Triple::x86_64) &&
+                     (RE->Word0 & macho::RF_Scattered);
+  unsigned Type;
+  if (isScattered)
+    Type =3D (RE->Word0 >> 24) & 0xF;
+  else
+    Type =3D (RE->Word1 >> 28) & 0xF;
+
+  Result =3D false;
+
+  // On arches that use the generic relocations, GENERIC_RELOC_PAIR
+  // is always hidden.
+  if (Arch =3D=3D Triple::x86 || Arch =3D=3D Triple::arm) {
+    if (Type =3D=3D macho::RIT_Pair) Result =3D true;
+  } else if (Arch =3D=3D Triple::x86_64) {
+    // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
+    // an X864_64_RELOC_SUBTRACTOR.
+    if (Type =3D=3D macho::RIT_X86_64_Unsigned && Rel.d.a > 0) {
+      DataRefImpl RelPrev =3D Rel;
+      RelPrev.d.a--;
+      InMemoryStruct<macho::RelocationEntry> REPrev;
+      getRelocation(RelPrev, REPrev);
+
+      unsigned PrevType =3D (REPrev->Word1 >> 28) & 0xF;
+
+      if (PrevType =3D=3D macho::RIT_X86_64_Subtractor) Result =3D true;
+    }
+  }
+
+  return object_error::success;
+}
+
+error_code MachOObjectFile::getLibraryNext(DataRefImpl LibData,
+                                           LibraryRef &Res) const {
+  report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
+}
+
+error_code MachOObjectFile::getLibraryPath(DataRefImpl LibData,
+                                           StringRef &Res) const {
+  report_fatal_error("Needed libraries unimplemented in MachOObjectFile");
+}
+
+
 /*=3D=3D=3D-- Miscellaneous ----------------------------------------------=
-------=3D=3D=3D*/
=20
 uint8_t MachOObjectFile::getBytesInAddress() const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Object/Object.cpp
--- a/head/contrib/llvm/lib/Object/Object.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Object/Object.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 using namespace llvm;
 using namespace object;
=20
+// ObjectFile creation
 LLVMObjectFileRef LLVMCreateObjectFile(LLVMMemoryBufferRef MemBuf) {
   return wrap(ObjectFile::createObjectFile(unwrap(MemBuf)));
 }
@@ -26,6 +27,7 @@
   delete unwrap(ObjectFile);
 }
=20
+// ObjectFile Section iterators
 LLVMSectionIteratorRef LLVMGetSections(LLVMObjectFileRef ObjectFile) {
   section_iterator SI =3D unwrap(ObjectFile)->begin_sections();
   return wrap(new section_iterator(SI));
@@ -46,6 +48,34 @@
   if (ec) report_fatal_error("LLVMMoveToNextSection failed: " + ec.message=
());
 }
=20
+void LLVMMoveToContainingSection(LLVMSectionIteratorRef Sect,
+                                 LLVMSymbolIteratorRef Sym) {
+  if (error_code ec =3D (*unwrap(Sym))->getSection(*unwrap(Sect)))
+    report_fatal_error(ec.message());
+}
+
+// ObjectFile Symbol iterators
+LLVMSymbolIteratorRef LLVMGetSymbols(LLVMObjectFileRef ObjectFile) {
+  symbol_iterator SI =3D unwrap(ObjectFile)->begin_symbols();
+  return wrap(new symbol_iterator(SI));
+}
+
+void LLVMDisposeSymbolIterator(LLVMSymbolIteratorRef SI) {
+  delete unwrap(SI);
+}
+
+LLVMBool LLVMIsSymbolIteratorAtEnd(LLVMObjectFileRef ObjectFile,
+                                LLVMSymbolIteratorRef SI) {
+  return (*unwrap(SI) =3D=3D unwrap(ObjectFile)->end_symbols()) ? 1 : 0;
+}
+
+void LLVMMoveToNextSymbol(LLVMSymbolIteratorRef SI) {
+  error_code ec;
+  unwrap(SI)->increment(ec);
+  if (ec) report_fatal_error("LLVMMoveToNextSymbol failed: " + ec.message(=
));
+}
+
+// SectionRef accessors
 const char *LLVMGetSectionName(LLVMSectionIteratorRef SI) {
   StringRef ret;
   if (error_code ec =3D (*unwrap(SI))->getName(ret))
@@ -66,3 +96,123 @@
     report_fatal_error(ec.message());
   return ret.data();
 }
+
+uint64_t LLVMGetSectionAddress(LLVMSectionIteratorRef SI) {
+  uint64_t ret;
+  if (error_code ec =3D (*unwrap(SI))->getAddress(ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+LLVMBool LLVMGetSectionContainsSymbol(LLVMSectionIteratorRef SI,
+                                 LLVMSymbolIteratorRef Sym) {
+  bool ret;
+  if (error_code ec =3D (*unwrap(SI))->containsSymbol(**unwrap(Sym), ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+// Section Relocation iterators
+LLVMRelocationIteratorRef LLVMGetRelocations(LLVMSectionIteratorRef Sectio=
n) {
+  relocation_iterator SI =3D (*unwrap(Section))->begin_relocations();
+  return wrap(new relocation_iterator(SI));
+}
+
+void LLVMDisposeRelocationIterator(LLVMRelocationIteratorRef SI) {
+  delete unwrap(SI);
+}
+
+LLVMBool LLVMIsRelocationIteratorAtEnd(LLVMSectionIteratorRef Section,
+                                       LLVMRelocationIteratorRef SI) {
+  return (*unwrap(SI) =3D=3D (*unwrap(Section))->end_relocations()) ? 1 : =
0;
+}
+
+void LLVMMoveToNextRelocation(LLVMRelocationIteratorRef SI) {
+  error_code ec;
+  unwrap(SI)->increment(ec);
+  if (ec) report_fatal_error("LLVMMoveToNextRelocation failed: " +
+                             ec.message());
+}
+
+
+// SymbolRef accessors
+const char *LLVMGetSymbolName(LLVMSymbolIteratorRef SI) {
+  StringRef ret;
+  if (error_code ec =3D (*unwrap(SI))->getName(ret))
+    report_fatal_error(ec.message());
+  return ret.data();
+}
+
+uint64_t LLVMGetSymbolAddress(LLVMSymbolIteratorRef SI) {
+  uint64_t ret;
+  if (error_code ec =3D (*unwrap(SI))->getAddress(ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+uint64_t LLVMGetSymbolFileOffset(LLVMSymbolIteratorRef SI) {
+  uint64_t ret;
+  if (error_code ec =3D (*unwrap(SI))->getFileOffset(ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+uint64_t LLVMGetSymbolSize(LLVMSymbolIteratorRef SI) {
+  uint64_t ret;
+  if (error_code ec =3D (*unwrap(SI))->getSize(ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+// RelocationRef accessors
+uint64_t LLVMGetRelocationAddress(LLVMRelocationIteratorRef RI) {
+  uint64_t ret;
+  if (error_code ec =3D (*unwrap(RI))->getAddress(ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+uint64_t LLVMGetRelocationOffset(LLVMRelocationIteratorRef RI) {
+  uint64_t ret;
+  if (error_code ec =3D (*unwrap(RI))->getOffset(ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+LLVMSymbolIteratorRef LLVMGetRelocationSymbol(LLVMRelocationIteratorRef RI=
) {
+  SymbolRef ret;
+  if (error_code ec =3D (*unwrap(RI))->getSymbol(ret))
+    report_fatal_error(ec.message());
+
+  return wrap(new symbol_iterator(ret));
+}
+
+uint64_t LLVMGetRelocationType(LLVMRelocationIteratorRef RI) {
+  uint64_t ret;
+  if (error_code ec =3D (*unwrap(RI))->getType(ret))
+    report_fatal_error(ec.message());
+  return ret;
+}
+
+// NOTE: Caller takes ownership of returned string.
+const char *LLVMGetRelocationTypeName(LLVMRelocationIteratorRef RI) {
+  SmallVector<char, 0> ret;
+  if (error_code ec =3D (*unwrap(RI))->getTypeName(ret))
+    report_fatal_error(ec.message());
+
+  char *str =3D static_cast<char*>(malloc(ret.size()));
+  std::copy(ret.begin(), ret.end(), str);
+  return str;
+}
+
+// NOTE: Caller takes ownership of returned string.
+const char *LLVMGetRelocationValueString(LLVMRelocationIteratorRef RI) {
+  SmallVector<char, 0> ret;
+  if (error_code ec =3D (*unwrap(RI))->getValueString(ret))
+    report_fatal_error(ec.message());
+
+  char *str =3D static_cast<char*>(malloc(ret.size()));
+  std::copy(ret.begin(), ret.end(), str);
+  return str;
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Object/ObjectFil=
e.cpp
--- a/head/contrib/llvm/lib/Object/ObjectFile.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Object/ObjectFile.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -21,6 +21,8 @@
 using namespace llvm;
 using namespace object;
=20
+void ObjectFile::anchor() { }
+
 ObjectFile::ObjectFile(unsigned int Type, MemoryBuffer *source, error_code=
 &ec)
   : Binary(Type, source) {
 }
@@ -56,7 +58,7 @@
=20
 ObjectFile *ObjectFile::createObjectFile(StringRef ObjectPath) {
   OwningPtr<MemoryBuffer> File;
-  if (error_code ec =3D MemoryBuffer::getFile(ObjectPath, File))
+  if (MemoryBuffer::getFile(ObjectPath, File))
     return NULL;
   return createObjectFile(File.take());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/APFloat.=
cpp
--- a/head/contrib/llvm/lib/Support/APFloat.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/Support/APFloat.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -14,8 +14,9 @@
=20
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/APSInt.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/ADT/FoldingSet.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include <limits.h>
@@ -1150,9 +1151,6 @@
   assert(lost_fraction !=3D lfExactlyZero);
=20
   switch (rounding_mode) {
-  default:
-    llvm_unreachable(0);
-
   case rmNearestTiesToAway:
     return lost_fraction =3D=3D lfExactlyHalf || lost_fraction =3D=3D lfMo=
reThanHalf;
=20
@@ -1175,6 +1173,7 @@
   case rmTowardNegative:
     return sign =3D=3D true;
   }
+  llvm_unreachable("Invalid rounding mode found");
 }
=20
 APFloat::opStatus
@@ -1854,20 +1853,33 @@
   lostFraction lostFraction;
   unsigned int newPartCount, oldPartCount;
   opStatus fs;
-
-  assertArithmeticOK(*semantics);
+  int shift;
+  const fltSemantics &fromSemantics =3D *semantics;
+
+  assertArithmeticOK(fromSemantics);
   assertArithmeticOK(toSemantics);
   lostFraction =3D lfExactlyZero;
   newPartCount =3D partCountForBits(toSemantics.precision + 1);
   oldPartCount =3D partCount();
-
-  /* Handle storage complications.  If our new form is wider,
-     re-allocate our bit pattern into wider storage.  If it is
-     narrower, we ignore the excess parts, but if narrowing to a
-     single part we need to free the old storage.
-     Be careful not to reference significandParts for zeroes
-     and infinities, since it aborts.  */
+  shift =3D toSemantics.precision - fromSemantics.precision;
+
+  bool X86SpecialNan =3D false;
+  if (&fromSemantics =3D=3D &APFloat::x87DoubleExtended &&
+      &toSemantics !=3D &APFloat::x87DoubleExtended && category =3D=3D fcN=
aN &&
+      (!(*significandParts() & 0x8000000000000000ULL) ||
+       !(*significandParts() & 0x4000000000000000ULL))) {
+    // x86 has some unusual NaNs which cannot be represented in any other
+    // format; note them here.
+    X86SpecialNan =3D true;
+  }
+
+  // If this is a truncation, perform the shift before we narrow the stora=
ge.
+  if (shift < 0 && (category=3D=3DfcNormal || category=3D=3DfcNaN))
+    lostFraction =3D shiftRight(significandParts(), oldPartCount, -shift);
+
+  // Fix the storage so it can hold to new value.
   if (newPartCount > oldPartCount) {
+    // The new type requires more storage; make it available.
     integerPart *newParts;
     newParts =3D new integerPart[newPartCount];
     APInt::tcSet(newParts, 0, newPartCount);
@@ -1875,61 +1887,36 @@
       APInt::tcAssign(newParts, significandParts(), oldPartCount);
     freeSignificand();
     significand.parts =3D newParts;
-  } else if (newPartCount < oldPartCount) {
-    /* Capture any lost fraction through truncation of parts so we get
-       correct rounding whilst normalizing.  */
-    if (category=3D=3DfcNormal)
-      lostFraction =3D lostFractionThroughTruncation
-        (significandParts(), oldPartCount, toSemantics.precision);
-    if (newPartCount =3D=3D 1) {
-        integerPart newPart =3D 0;
-        if (category=3D=3DfcNormal || category=3D=3DfcNaN)
-          newPart =3D significandParts()[0];
-        freeSignificand();
-        significand.part =3D newPart;
-    }
+  } else if (newPartCount =3D=3D 1 && oldPartCount !=3D 1) {
+    // Switch to built-in storage for a single part.
+    integerPart newPart =3D 0;
+    if (category=3D=3DfcNormal || category=3D=3DfcNaN)
+      newPart =3D significandParts()[0];
+    freeSignificand();
+    significand.part =3D newPart;
   }
=20
+  // Now that we have the right storage, switch the semantics.
+  semantics =3D &toSemantics;
+
+  // If this is an extension, perform the shift now that the storage is
+  // available.
+  if (shift > 0 && (category=3D=3DfcNormal || category=3D=3DfcNaN))
+    APInt::tcShiftLeft(significandParts(), newPartCount, shift);
+
   if (category =3D=3D fcNormal) {
-    /* Re-interpret our bit-pattern.  */
-    exponent +=3D toSemantics.precision - semantics->precision;
-    semantics =3D &toSemantics;
     fs =3D normalize(rounding_mode, lostFraction);
     *losesInfo =3D (fs !=3D opOK);
   } else if (category =3D=3D fcNaN) {
-    int shift =3D toSemantics.precision - semantics->precision;
-    // Do this now so significandParts gets the right answer
-    const fltSemantics *oldSemantics =3D semantics;
-    semantics =3D &toSemantics;
-    *losesInfo =3D false;
-    // No normalization here, just truncate
-    if (shift>0)
-      APInt::tcShiftLeft(significandParts(), newPartCount, shift);
-    else if (shift < 0) {
-      unsigned ushift =3D -shift;
-      // Figure out if we are losing information.  This happens
-      // if are shifting out something other than 0s, or if the x87 long
-      // double input did not have its integer bit set (pseudo-NaN), or if=
 the
-      // x87 long double input did not have its QNan bit set (because the =
x87
-      // hardware sets this bit when converting a lower-precision NaN to
-      // x87 long double).
-      if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
-        *losesInfo =3D true;
-      if (oldSemantics =3D=3D &APFloat::x87DoubleExtended &&
-          (!(*significandParts() & 0x8000000000000000ULL) ||
-           !(*significandParts() & 0x4000000000000000ULL)))
-        *losesInfo =3D true;
-      APInt::tcShiftRight(significandParts(), newPartCount, ushift);
-    }
+    *losesInfo =3D lostFraction !=3D lfExactlyZero || X86SpecialNan;
     // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
     // does not give you back the same bits.  This is dubious, and we
     // don't currently do it.  You're really supposed to get
     // an invalid operation signal at runtime, but nobody does that.
     fs =3D opOK;
   } else {
-    semantics =3D &toSemantics;
+    *losesInfo =3D false;
     fs =3D opOK;
-    *losesInfo =3D false;
   }
=20
   return fs;
@@ -2695,21 +2682,19 @@
   return writeSignedDecimal (dst, exponent);
 }
=20
-// For good performance it is desirable for different APFloats
-// to produce different integers.
-uint32_t
-APFloat::getHashValue() const
-{
-  if (category=3D=3DfcZero) return sign<<8 | semantics->precision ;
-  else if (category=3D=3DfcInfinity) return sign<<9 | semantics->precision;
-  else if (category=3D=3DfcNaN) return 1<<10 | semantics->precision;
-  else {
-    uint32_t hash =3D sign<<11 | semantics->precision | exponent<<12;
-    const integerPart* p =3D significandParts();
-    for (int i=3DpartCount(); i>0; i--, p++)
-      hash ^=3D ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
-    return hash;
-  }
+hash_code llvm::hash_value(const APFloat &Arg) {
+  if (Arg.category !=3D APFloat::fcNormal)
+    return hash_combine((uint8_t)Arg.category,
+                        // NaN has no sign, fix it at zero.
+                        Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
+                        Arg.semantics->precision);
+
+  // Normal floats need their exponent and significand hashed.
+  return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
+                      Arg.semantics->precision, Arg.exponent,
+                      hash_combine_range(
+                        Arg.significandParts(),
+                        Arg.significandParts() + Arg.partCount()));
 }
=20
 // Conversion from APFloat to/from host float/double.  It may eventually be
@@ -3354,7 +3339,7 @@
     // Rounding down is just a truncation, except we also want to drop
     // trailing zeros from the new result.
     if (buffer[FirstSignificant - 1] < '5') {
-      while (buffer[FirstSignificant] =3D=3D '0')
+      while (FirstSignificant < N && buffer[FirstSignificant] =3D=3D '0')
         FirstSignificant++;
=20
       exp +=3D FirstSignificant;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/APInt.cpp
--- a/head/contrib/llvm/lib/Support/APInt.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/APInt.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -14,9 +14,10 @@
=20
 #define DEBUG_TYPE "apint"
 #include "llvm/ADT/APInt.h"
+#include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/ADT/FoldingSet.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
@@ -456,16 +457,6 @@
   return APInt(val, getBitWidth()).clearUnusedBits();
 }
=20
-bool APInt::operator !() const {
-  if (isSingleWord())
-    return !VAL;
-
-  for (unsigned i =3D 0; i < getNumWords(); ++i)
-    if (pVal[i])
-      return false;
-  return true;
-}
-
 APInt APInt::operator*(const APInt& RHS) const {
   assert(BitWidth =3D=3D RHS.BitWidth && "Bit widths must be the same");
   if (isSingleWord())
@@ -493,12 +484,6 @@
   return Result.clearUnusedBits();
 }
=20
-bool APInt::operator[](unsigned bitPosition) const {
-  assert(bitPosition < getBitWidth() && "Bit position out of bounds!");
-  return (maskBit(bitPosition) &
-          (isSingleWord() ?  VAL : pVal[whichWord(bitPosition)])) !=3D 0;
-}
-
 bool APInt::EqualSlowCase(const APInt& RHS) const {
   // Get some facts about the number of bits used in the two operands.
   unsigned n1 =3D getActiveBits();
@@ -675,93 +660,11 @@
   }
 }
=20
-// From http://www.burtleburtle.net, byBob Jenkins.
-// When targeting x86, both GCC and LLVM seem to recognize this as a
-// rotate instruction.
-#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
-
-// From http://www.burtleburtle.net, by Bob Jenkins.
-#define mix(a,b,c) \
-  { \
-    a -=3D c;  a ^=3D rot(c, 4);  c +=3D b; \
-    b -=3D a;  b ^=3D rot(a, 6);  a +=3D c; \
-    c -=3D b;  c ^=3D rot(b, 8);  b +=3D a; \
-    a -=3D c;  a ^=3D rot(c,16);  c +=3D b; \
-    b -=3D a;  b ^=3D rot(a,19);  a +=3D c; \
-    c -=3D b;  c ^=3D rot(b, 4);  b +=3D a; \
-  }
-
-// From http://www.burtleburtle.net, by Bob Jenkins.
-#define final(a,b,c) \
-  { \
-    c ^=3D b; c -=3D rot(b,14); \
-    a ^=3D c; a -=3D rot(c,11); \
-    b ^=3D a; b -=3D rot(a,25); \
-    c ^=3D b; c -=3D rot(b,16); \
-    a ^=3D c; a -=3D rot(c,4);  \
-    b ^=3D a; b -=3D rot(a,14); \
-    c ^=3D b; c -=3D rot(b,24); \
-  }
-
-// hashword() was adapted from http://www.burtleburtle.net, by Bob
-// Jenkins.  k is a pointer to an array of uint32_t values; length is
-// the length of the key, in 32-bit chunks.  This version only handles
-// keys that are a multiple of 32 bits in size.
-static inline uint32_t hashword(const uint64_t *k64, size_t length)
-{
-  const uint32_t *k =3D reinterpret_cast<const uint32_t *>(k64);
-  uint32_t a,b,c;
-
-  /* Set up the internal state */
-  a =3D b =3D c =3D 0xdeadbeef + (((uint32_t)length)<<2);
-
-  /*------------------------------------------------- handle most of the k=
ey */
-  while (length > 3) {
-    a +=3D k[0];
-    b +=3D k[1];
-    c +=3D k[2];
-    mix(a,b,c);
-    length -=3D 3;
-    k +=3D 3;
-  }
-
-  /*------------------------------------------- handle the last 3 uint32_t=
's */
-  switch (length) {                  /* all the case statements fall throu=
gh */
-  case 3 : c+=3Dk[2];
-  case 2 : b+=3Dk[1];
-  case 1 : a+=3Dk[0];
-    final(a,b,c);
-    case 0:     /* case 0: nothing left to add */
-      break;
-    }
-  /*------------------------------------------------------ report the resu=
lt */
-  return c;
-}
-
-// hashword8() was adapted from http://www.burtleburtle.net, by Bob
-// Jenkins.  This computes a 32-bit hash from one 64-bit word.  When
-// targeting x86 (32 or 64 bit), both LLVM and GCC compile this
-// function into about 35 instructions when inlined.
-static inline uint32_t hashword8(const uint64_t k64)
-{
-  uint32_t a,b,c;
-  a =3D b =3D c =3D 0xdeadbeef + 4;
-  b +=3D k64 >> 32;
-  a +=3D k64 & 0xffffffff;
-  final(a,b,c);
-  return c;
-}
-#undef final
-#undef mix
-#undef rot
-
-uint64_t APInt::getHashValue() const {
-  uint64_t hash;
-  if (isSingleWord())
-    hash =3D hashword8(VAL);
-  else
-    hash =3D hashword(pVal, getNumWords()*2);
-  return hash;
+hash_code llvm::hash_value(const APInt &Arg) {
+  if (Arg.isSingleWord())
+    return hash_combine(Arg.VAL);
+
+  return hash_combine_range(Arg.pVal, Arg.pVal + Arg.getNumWords());
 }
=20
 /// HiBits - This function returns the high "numBits" bits of this APInt.
@@ -803,20 +706,9 @@
   return Count;
 }
=20
-static unsigned countLeadingOnes_64(uint64_t V, unsigned skip) {
-  unsigned Count =3D 0;
-  if (skip)
-    V <<=3D skip;
-  while (V && (V & (1ULL << 63))) {
-    Count++;
-    V <<=3D 1;
-  }
-  return Count;
-}
-
 unsigned APInt::countLeadingOnes() const {
   if (isSingleWord())
-    return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth);
+    return CountLeadingOnes_64(VAL << (APINT_BITS_PER_WORD - BitWidth));
=20
   unsigned highWordBits =3D BitWidth % APINT_BITS_PER_WORD;
   unsigned shift;
@@ -827,13 +719,13 @@
     shift =3D APINT_BITS_PER_WORD - highWordBits;
   }
   int i =3D getNumWords() - 1;
-  unsigned Count =3D countLeadingOnes_64(pVal[i], shift);
+  unsigned Count =3D CountLeadingOnes_64(pVal[i] << shift);
   if (Count =3D=3D highWordBits) {
     for (i--; i >=3D 0; --i) {
       if (pVal[i] =3D=3D -1ULL)
         Count +=3D APINT_BITS_PER_WORD;
       else {
-        Count +=3D countLeadingOnes_64(pVal[i], 0);
+        Count +=3D CountLeadingOnes_64(pVal[i]);
         break;
       }
     }
@@ -870,30 +762,43 @@
   return Count;
 }
=20
+/// Perform a logical right-shift from Src to Dst, which must be equal or
+/// non-overlapping, of Words words, by Shift, which must be less than 64.
+static void lshrNear(uint64_t *Dst, uint64_t *Src, unsigned Words,
+                     unsigned Shift) {
+  uint64_t Carry =3D 0;
+  for (int I =3D Words - 1; I >=3D 0; --I) {
+    uint64_t Tmp =3D Src[I];
+    Dst[I] =3D (Tmp >> Shift) | Carry;
+    Carry =3D Tmp << (64 - Shift);
+  }
+}
+
 APInt APInt::byteSwap() const {
   assert(BitWidth >=3D 16 && BitWidth % 16 =3D=3D 0 && "Cannot byteswap!");
   if (BitWidth =3D=3D 16)
     return APInt(BitWidth, ByteSwap_16(uint16_t(VAL)));
-  else if (BitWidth =3D=3D 32)
+  if (BitWidth =3D=3D 32)
     return APInt(BitWidth, ByteSwap_32(unsigned(VAL)));
-  else if (BitWidth =3D=3D 48) {
+  if (BitWidth =3D=3D 48) {
     unsigned Tmp1 =3D unsigned(VAL >> 16);
     Tmp1 =3D ByteSwap_32(Tmp1);
     uint16_t Tmp2 =3D uint16_t(VAL);
     Tmp2 =3D ByteSwap_16(Tmp2);
     return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1);
-  } else if (BitWidth =3D=3D 64)
+  }
+  if (BitWidth =3D=3D 64)
     return APInt(BitWidth, ByteSwap_64(VAL));
-  else {
-    APInt Result(BitWidth, 0);
-    char *pByte =3D (char*)Result.pVal;
-    for (unsigned i =3D 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) {
-      char Tmp =3D pByte[i];
-      pByte[i] =3D pByte[BitWidth / APINT_WORD_SIZE - 1 - i];
-      pByte[BitWidth / APINT_WORD_SIZE - i - 1] =3D Tmp;
-    }
-    return Result;
+
+  APInt Result(getNumWords() * APINT_BITS_PER_WORD, 0);
+  for (unsigned I =3D 0, N =3D getNumWords(); I !=3D N; ++I)
+    Result.pVal[I] =3D ByteSwap_64(pVal[N - I - 1]);
+  if (Result.BitWidth !=3D BitWidth) {
+    lshrNear(Result.pVal, Result.pVal, getNumWords(),
+             Result.BitWidth - BitWidth);
+    Result.BitWidth =3D BitWidth;
   }
+  return Result;
 }
=20
 APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1,
@@ -1110,6 +1015,18 @@
   return *this;
 }
=20
+APInt APInt::zextOrSelf(unsigned width) const {
+  if (BitWidth < width)
+    return zext(width);
+  return *this;
+}
+
+APInt APInt::sextOrSelf(unsigned width) const {
+  if (BitWidth < width)
+    return sext(width);
+  return *this;
+}
+
 /// Arithmetic right-shift this APInt by shiftAmt.
 /// @brief Arithmetic right-shift function.
 APInt APInt::ashr(const APInt &shiftAmt) const {
@@ -1209,7 +1126,7 @@
 /// @brief Logical right-shift function.
 APInt APInt::lshr(unsigned shiftAmt) const {
   if (isSingleWord()) {
-    if (shiftAmt =3D=3D BitWidth)
+    if (shiftAmt >=3D BitWidth)
       return APInt(BitWidth, 0);
     else
       return APInt(BitWidth, this->VAL >> shiftAmt);
@@ -1232,11 +1149,7 @@
=20
   // If we are shifting less than a word, compute the shift with a simple =
carry
   if (shiftAmt < APINT_BITS_PER_WORD) {
-    uint64_t carry =3D 0;
-    for (int i =3D getNumWords()-1; i >=3D 0; --i) {
-      val[i] =3D (pVal[i] >> shiftAmt) | carry;
-      carry =3D pVal[i] << (APINT_BITS_PER_WORD - shiftAmt);
-    }
+    lshrNear(val, pVal, getNumWords(), shiftAmt);
     return APInt(val, BitWidth).clearUnusedBits();
   }
=20
@@ -1329,14 +1242,10 @@
 }
=20
 APInt APInt::rotl(unsigned rotateAmt) const {
+  rotateAmt %=3D BitWidth;
   if (rotateAmt =3D=3D 0)
     return *this;
-  // Don't get too fancy, just use existing shift/or facilities
-  APInt hi(*this);
-  APInt lo(*this);
-  hi.shl(rotateAmt);
-  lo.lshr(BitWidth - rotateAmt);
-  return hi | lo;
+  return shl(rotateAmt) | lshr(BitWidth - rotateAmt);
 }
=20
 APInt APInt::rotr(const APInt &rotateAmt) const {
@@ -1344,14 +1253,10 @@
 }
=20
 APInt APInt::rotr(unsigned rotateAmt) const {
+  rotateAmt %=3D BitWidth;
   if (rotateAmt =3D=3D 0)
     return *this;
-  // Don't get too fancy, just use existing shift/or facilities
-  APInt hi(*this);
-  APInt lo(*this);
-  lo.lshr(rotateAmt);
-  hi.shl(BitWidth - rotateAmt);
-  return hi | lo;
+  return lshr(rotateAmt) | shl(BitWidth - rotateAmt);
 }
=20
 // Square Root - this method computes and returns the square root of "this=
".
@@ -1431,15 +1336,11 @@
   APInt nextSquare((x_old + 1) * (x_old +1));
   if (this->ult(square))
     return x_old;
-  else if (this->ule(nextSquare)) {
-    APInt midpoint((nextSquare - square).udiv(two));
-    APInt offset(*this - square);
-    if (offset.ult(midpoint))
-      return x_old;
-    else
-      return x_old + 1;
-  } else
-    llvm_unreachable("Error in APInt::sqrt computation");
+  assert(this->ule(nextSquare) && "Error in APInt::sqrt computation");
+  APInt midpoint((nextSquare - square).udiv(two));
+  APInt offset(*this - square);
+  if (offset.ult(midpoint))
+    return x_old;
   return x_old + 1;
 }
=20
@@ -2184,7 +2085,7 @@
                      bool Signed, bool formatAsCLiteral) const {
   assert((Radix =3D=3D 10 || Radix =3D=3D 8 || Radix =3D=3D 16 || Radix =
=3D=3D 2 ||=20
           Radix =3D=3D 36) &&
-         "Radix should be 2, 8, 10, or 16!");
+         "Radix should be 2, 8, 10, 16, or 36!");
=20
   const char *Prefix =3D "";
   if (formatAsCLiteral) {
@@ -2197,9 +2098,13 @@
       case 8:
         Prefix =3D "0";
         break;
+      case 10:
+        break; // No prefix
       case 16:
         Prefix =3D "0x";
         break;
+      default:
+        llvm_unreachable("Invalid radix!");
     }
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Allocato=
r.cpp
--- a/head/contrib/llvm/lib/Support/Allocator.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/Allocator.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -22,8 +22,8 @@
=20
 BumpPtrAllocator::BumpPtrAllocator(size_t size, size_t threshold,
                                    SlabAllocator &allocator)
-    : SlabSize(size), SizeThreshold(threshold), Allocator(allocator),
-      CurSlab(0), BytesAllocated(0) { }
+    : SlabSize(size), SizeThreshold(std::min(size, threshold)),
+      Allocator(allocator), CurSlab(0), BytesAllocated(0) { }
=20
 BumpPtrAllocator::~BumpPtrAllocator() {
   DeallocateSlabs(CurSlab);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Atomic.c=
pp
--- a/head/contrib/llvm/lib/Support/Atomic.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Support/Atomic.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -12,7 +12,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Support/Atomic.h"
-#include "llvm/Config/config.h"
+#include "llvm/Config/llvm-config.h"
=20
 using namespace llvm;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/BlockFre=
quency.cpp
--- a/head/contrib/llvm/lib/Support/BlockFrequency.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Support/BlockFrequency.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -70,8 +70,13 @@
=20
   assert(n <=3D d && "Probability must be less or equal to 1.");
=20
-  // If we can overflow use 96-bit operations.
-  if (n > 0 && Frequency > UINT64_MAX / n) {
+  // Calculate Frequency * n.
+  uint64_t mulLo =3D (Frequency & UINT32_MAX) * n;
+  uint64_t mulHi =3D (Frequency >> 32) * n;
+  uint64_t mulRes =3D (mulHi << 32) + mulLo;
+
+  // If there was overflow use 96-bit operations.
+  if (mulHi > UINT32_MAX || mulRes < mulLo) {
     // 96-bit value represented as W[1]:W[0].
     uint64_t W[2];
=20
@@ -82,8 +87,7 @@
     return *this;
   }
=20
-  Frequency *=3D n;
-  Frequency /=3D d;
+  Frequency =3D mulRes / d;
   return *this;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/BranchPr=
obability.cpp
--- a/head/contrib/llvm/lib/Support/BranchProbability.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/BranchProbability.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -13,24 +13,17 @@
=20
 #include "llvm/Support/BranchProbability.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Format.h"
 #include "llvm/Support/raw_ostream.h"
=20
 using namespace llvm;
=20
-BranchProbability::BranchProbability(uint32_t n, uint32_t d) {
-  assert(d > 0 && "Denomiator cannot be 0!");
-  assert(n <=3D d && "Probability cannot be bigger than 1!");
-  N =3D n;
-  D =3D d;
-}
-
 void BranchProbability::print(raw_ostream &OS) const {
-  OS << N << " / " << D << " =3D " << ((double)N / D);
+  OS << N << " / " << D << " =3D " << format("%g%%", ((double)N / D) * 100=
.0);
 }
=20
 void BranchProbability::dump() const {
-  print(dbgs());
-  dbgs() << "\n";
+  dbgs() << *this << '\n';
 }
=20
 namespace llvm {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/CommandL=
ine.cpp
--- a/head/contrib/llvm/lib/Support/CommandLine.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Support/CommandLine.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -57,6 +57,9 @@
 TEMPLATE_INSTANTIATION(class opt<bool>);
 } } // end namespace llvm::cl
=20
+void GenericOptionValue::anchor() {}
+void OptionValue<boolOrDefault>::anchor() {}
+void OptionValue<std::string>::anchor() {}
 void Option::anchor() {}
 void basic_parser_impl::anchor() {}
 void parser<bool>::anchor() {}
@@ -263,8 +266,8 @@
 /// and a null value (StringRef()).  The later is accepted for arguments t=
hat
 /// don't allow a value (-foo) the former is rejected (-foo=3D).
 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
-                                 StringRef Value, int argc, char **argv,
-                                 int &i) {
+                                 StringRef Value, int argc,
+                                 const char *const *argv, int &i) {
   // Is this a multi-argument option?
   unsigned NumAdditionalVals =3D Handler->getNumAdditionalVals();
=20
@@ -289,12 +292,6 @@
     break;
   case ValueOptional:
     break;
-
-  default:
-    errs() << ProgramName
-         << ": Bad ValueMask flag! CommandLine usage error:"
-         << Handler->getValueExpectedFlag() << "\n";
-    llvm_unreachable(0);
   }
=20
   // If this isn't a multi-arg option, just run the handler.
@@ -498,10 +495,10 @@
 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
 /// substituting the contents of the response files for the arguments
 /// of type @file.
-static void ExpandResponseFiles(unsigned argc, char** argv,
+static void ExpandResponseFiles(unsigned argc, const char*const* argv,
                                 std::vector<char*>& newArgv) {
   for (unsigned i =3D 1; i !=3D argc; ++i) {
-    char *arg =3D argv[i];
+    const char *arg =3D argv[i];
=20
     if (arg[0] =3D=3D '@') {
       sys::PathWithStatus respFile(++arg);
@@ -531,7 +528,7 @@
   }
 }
=20
-void cl::ParseCommandLineOptions(int argc, char **argv,
+void cl::ParseCommandLineOptions(int argc, const char * const *argv,
                                  const char *Overview, bool ReadResponseFi=
les) {
   // Process all registered options.
   SmallVector<Option*, 4> PositionalOpts;
@@ -885,7 +882,6 @@
   case OneOrMore:
   case ZeroOrMore:
   case ConsumeAfter: break;
-  default: return error("bad num occurrences flag value!");
   }
=20
   return handleOccurrence(pos, ArgName, Value);
@@ -1195,7 +1191,7 @@
 static int OptNameCompare(const void *LHS, const void *RHS) {
   typedef std::pair<const char *, Option*> pair_ty;
=20
-  return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first);
+  return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first=
);
 }
=20
 // Copy Options into a vector so we can sort them as we like.
@@ -1349,7 +1345,7 @@
 public:
   void print() {
     raw_ostream &OS =3D outs();
-    OS << "Low Level Virtual Machine (http://llvm.org/):\n"
+    OS << "LLVM (http://llvm.org/):\n"
        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
 #ifdef LLVM_VERSION_INFO
     OS << LLVM_VERSION_INFO;
@@ -1369,7 +1365,7 @@
 #if (ENABLE_TIMESTAMPS =3D=3D 1)
        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
 #endif
-       << "  Host: " << sys::getHostTriple() << '\n'
+       << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
        << "  Host CPU: " << CPU << '\n';
   }
   void operator=3D(bool OptionWasSpecified) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Constant=
Range.cpp
--- a/head/contrib/llvm/lib/Support/ConstantRange.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Support/ConstantRange.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -55,7 +55,7 @@
=20
   uint32_t W =3D CR.getBitWidth();
   switch (Pred) {
-    default: assert(0 && "Invalid ICmp predicate to makeICmpRegion()");
+    default: llvm_unreachable("Invalid ICmp predicate to makeICmpRegion()"=
);
     case CmpInst::ICMP_EQ:
       return CR;
     case CmpInst::ICMP_NE:
@@ -161,8 +161,7 @@
 APInt ConstantRange::getUnsignedMax() const {
   if (isFullSet() || isWrappedSet())
     return APInt::getMaxValue(getBitWidth());
-  else
-    return getUpper() - 1;
+  return getUpper() - 1;
 }
=20
 /// getUnsignedMin - Return the smallest unsigned value contained in the
@@ -171,8 +170,7 @@
 APInt ConstantRange::getUnsignedMin() const {
   if (isFullSet() || (isWrappedSet() && getUpper() !=3D 0))
     return APInt::getMinValue(getBitWidth());
-  else
-    return getLower();
+  return getLower();
 }
=20
 /// getSignedMax - Return the largest signed value contained in the
@@ -183,14 +181,11 @@
   if (!isWrappedSet()) {
     if (getLower().sle(getUpper() - 1))
       return getUpper() - 1;
-    else
-      return SignedMax;
-  } else {
-    if (getLower().isNegative() =3D=3D getUpper().isNegative())
-      return SignedMax;
-    else
-      return getUpper() - 1;
+    return SignedMax;
   }
+  if (getLower().isNegative() =3D=3D getUpper().isNegative())
+    return SignedMax;
+  return getUpper() - 1;
 }
=20
 /// getSignedMin - Return the smallest signed value contained in the
@@ -201,18 +196,13 @@
   if (!isWrappedSet()) {
     if (getLower().sle(getUpper() - 1))
       return getLower();
-    else
+    return SignedMin;
+  }
+  if ((getUpper() - 1).slt(getLower())) {
+    if (getUpper() !=3D SignedMin)
       return SignedMin;
-  } else {
-    if ((getUpper() - 1).slt(getLower())) {
-      if (getUpper() !=3D SignedMin)
-        return SignedMin;
-      else
-        return getLower();
-    } else {
-      return getLower();
-    }
   }
+  return getLower();
 }
=20
 /// contains - Return true if the specified value is in the set.
@@ -223,8 +213,7 @@
=20
   if (!isWrappedSet())
     return Lower.ule(V) && V.ult(Upper);
-  else
-    return Lower.ule(V) || V.ult(Upper);
+  return Lower.ule(V) || V.ult(Upper);
 }
=20
 /// contains - Return true if the argument is a subset of this range.
@@ -284,15 +273,14 @@
         return ConstantRange(CR.Lower, Upper);
=20
       return CR;
-    } else {
-      if (Upper.ult(CR.Upper))
-        return *this;
+    }
+    if (Upper.ult(CR.Upper))
+      return *this;
=20
-      if (Lower.ult(CR.Upper))
-        return ConstantRange(Lower, CR.Upper);
+    if (Lower.ult(CR.Upper))
+      return ConstantRange(Lower, CR.Upper);
=20
-      return ConstantRange(getBitWidth(), false);
-    }
+    return ConstantRange(getBitWidth(), false);
   }
=20
   if (isWrappedSet() && !CR.isWrappedSet()) {
@@ -305,9 +293,9 @@
=20
       if (getSetSize().ult(CR.getSetSize()))
         return *this;
-      else
-        return CR;
-    } else if (CR.Lower.ult(Lower)) {
+      return CR;
+    }
+    if (CR.Lower.ult(Lower)) {
       if (CR.Upper.ule(Lower))
         return ConstantRange(getBitWidth(), false);
=20
@@ -320,15 +308,15 @@
     if (CR.Lower.ult(Upper)) {
       if (getSetSize().ult(CR.getSetSize()))
         return *this;
-      else
-        return CR;
+      return CR;
     }
=20
     if (CR.Lower.ult(Lower))
       return ConstantRange(Lower, CR.Upper);
=20
     return CR;
-  } else if (CR.Upper.ult(Lower)) {
+  }
+  if (CR.Upper.ult(Lower)) {
     if (CR.Lower.ult(Lower))
       return *this;
=20
@@ -336,8 +324,7 @@
   }
   if (getSetSize().ult(CR.getSetSize()))
     return *this;
-  else
-    return CR;
+  return CR;
 }
=20
=20
@@ -362,8 +349,7 @@
       APInt d1 =3D CR.Lower - Upper, d2 =3D Lower - CR.Upper;
       if (d1.ult(d2))
         return ConstantRange(Lower, CR.Upper);
-      else
-        return ConstantRange(CR.Lower, Upper);
+      return ConstantRange(CR.Lower, Upper);
     }
=20
     APInt L =3D Lower, U =3D Upper;
@@ -396,8 +382,7 @@
       APInt d1 =3D CR.Lower - Upper, d2 =3D Lower - CR.Upper;
       if (d1.ult(d2))
         return ConstantRange(Lower, CR.Upper);
-      else
-        return ConstantRange(CR.Lower, Upper);
+      return ConstantRange(CR.Lower, Upper);
     }
=20
     // ----U     L----- : this
@@ -407,13 +392,11 @@
=20
     // ------U    L---- : this
     //    L-----U       : CR
-    if (CR.Lower.ult(Upper) && CR.Upper.ult(Lower))
-      return ConstantRange(Lower, CR.Upper);
+    assert(CR.Lower.ult(Upper) && CR.Upper.ult(Lower) &&
+           "ConstantRange::unionWith missed a case with one range wrapped"=
);
+    return ConstantRange(Lower, CR.Upper);
   }
=20
-  assert(isWrappedSet() && CR.isWrappedSet() &&
-         "ConstantRange::unionWith missed wrapped union unwrapped case");
-
   // ------U    L----  and  ------U    L---- : this
   // -U  L-----------  and  ------------U  L : CR
   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
@@ -466,10 +449,8 @@
 /// correspond to the possible range of values as if the source range had =
been
 /// truncated to the specified type.
 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
-  unsigned SrcTySize =3D getBitWidth();
-  assert(SrcTySize > DstTySize && "Not a value truncation");
-  APInt Size(APInt::getLowBitsSet(SrcTySize, DstTySize));
-  if (isFullSet() || getSetSize().ugt(Size))
+  assert(getBitWidth() > DstTySize && "Not a value truncation");
+  if (isFullSet() || getSetSize().getActiveBits() > DstTySize)
     return ConstantRange(DstTySize, /*isFullSet=3D*/true);
=20
   return ConstantRange(Lower.trunc(DstTySize), Upper.trunc(DstTySize));
@@ -481,10 +462,9 @@
   unsigned SrcTySize =3D getBitWidth();
   if (SrcTySize > DstTySize)
     return truncate(DstTySize);
-  else if (SrcTySize < DstTySize)
+  if (SrcTySize < DstTySize)
     return zeroExtend(DstTySize);
-  else
-    return *this;
+  return *this;
 }
=20
 /// sextOrTrunc - make this range have the bit width given by \p DstTySize=
. The
@@ -493,10 +473,9 @@
   unsigned SrcTySize =3D getBitWidth();
   if (SrcTySize > DstTySize)
     return truncate(DstTySize);
-  else if (SrcTySize < DstTySize)
+  if (SrcTySize < DstTySize)
     return signExtend(DstTySize);
-  else
-    return *this;
+  return *this;
 }
=20
 ConstantRange
@@ -675,11 +654,10 @@
 }
=20
 ConstantRange ConstantRange::inverse() const {
-  if (isFullSet()) {
+  if (isFullSet())
     return ConstantRange(getBitWidth(), /*isFullSet=3D*/false);
-  } else if (isEmptySet()) {
+  if (isEmptySet())
     return ConstantRange(getBitWidth(), /*isFullSet=3D*/true);
-  }
   return ConstantRange(Upper, Lower);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/CrashRec=
overyContext.cpp
--- a/head/contrib/llvm/lib/Support/CrashRecoveryContext.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/CrashRecoveryContext.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -165,7 +165,6 @@
   // Note that we don't actually get here because HandleCrash calls
   // longjmp, which means the HandleCrash function never returns.
   llvm_unreachable("Handled the crash, should have longjmp'ed out of here"=
);
-  return EXCEPTION_CONTINUE_SEARCH;
 }
=20
 // Because the Enable and Disable calls are static, it means that
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/DAGDelta=
Algorithm.cpp
--- a/head/contrib/llvm/lib/Support/DAGDeltaAlgorithm.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/DAGDeltaAlgorithm.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -350,6 +350,9 @@
   return Required;
 }
=20
+void DAGDeltaAlgorithm::anchor() {
+}
+
 DAGDeltaAlgorithm::changeset_ty
 DAGDeltaAlgorithm::Run(const changeset_ty &Changes,
                        const std::vector<edge_ty> &Dependencies) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/DataExtr=
actor.cpp
--- a/head/contrib/llvm/lib/Support/DataExtractor.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Support/DataExtractor.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -75,7 +75,7 @@
 uint32_t *DataExtractor::getU32(uint32_t *offset_ptr, uint32_t *dst,
                                 uint32_t count) const {
   return getUs<uint32_t>(offset_ptr, dst, count, this, IsLittleEndian,
-                        Data.data());;
+                        Data.data());
 }
=20
 uint64_t DataExtractor::getU64(uint32_t *offset_ptr) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Dwarf.cpp
--- a/head/contrib/llvm/lib/Support/Dwarf.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Dwarf.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -95,6 +95,7 @@
     return "DW_TAG_GNU_template_parameter_pack";
   case DW_TAG_GNU_formal_parameter_pack:
     return "DW_TAG_GNU_formal_parameter_pack";
+  case DW_TAG_APPLE_property:            return "DW_TAG_APPLE_property";
   }
   return 0;
 }
@@ -245,6 +246,7 @@
   case DW_AT_APPLE_property_getter:      return "DW_AT_APPLE_property_gett=
er";
   case DW_AT_APPLE_property_setter:      return "DW_AT_APPLE_property_sett=
er";
   case DW_AT_APPLE_property_attribute:   return "DW_AT_APPLE_property_attr=
ibute";
+  case DW_AT_APPLE_property:             return "DW_AT_APPLE_property";
   case DW_AT_APPLE_objc_complete_type:   return "DW_AT_APPLE_objc_complete=
_type";
   }
   return 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/FileUtil=
ities.cpp
--- a/head/contrib/llvm/lib/Support/FileUtilities.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Support/FileUtilities.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -200,7 +200,6 @@
=20
   // Now its safe to mmap the files into memory because both files
   // have a non-zero size.
-  error_code ec;
   OwningPtr<MemoryBuffer> F1;
   if (error_code ec =3D MemoryBuffer::getFile(FileA.c_str(), F1)) {
     if (Error)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/FoldingS=
et.cpp
--- a/head/contrib/llvm/lib/Support/FoldingSet.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/Support/FoldingSet.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -15,6 +15,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
@@ -29,24 +30,7 @@
 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
 /// used to lookup the node in the FoldingSetImpl.
 unsigned FoldingSetNodeIDRef::ComputeHash() const {
-  // This is adapted from SuperFastHash by Paul Hsieh.
-  unsigned Hash =3D static_cast<unsigned>(Size);
-  for (const unsigned *BP =3D Data, *E =3D BP+Size; BP !=3D E; ++BP) {
-    unsigned Data =3D *BP;
-    Hash         +=3D Data & 0xFFFF;
-    unsigned Tmp  =3D ((Data >> 16) << 11) ^ Hash;
-    Hash          =3D (Hash << 16) ^ Tmp;
-    Hash         +=3D Hash >> 11;
-  }
- =20
-  // Force "avalanching" of final 127 bits.
-  Hash ^=3D Hash << 3;
-  Hash +=3D Hash >> 5;
-  Hash ^=3D Hash << 4;
-  Hash +=3D Hash >> 17;
-  Hash ^=3D Hash << 25;
-  Hash +=3D Hash >> 6;
-  return Hash;
+  return static_cast<unsigned>(hash_combine_range(Data, Data+Size));
 }
=20
 bool FoldingSetNodeIDRef::operator=3D=3D(FoldingSetNodeIDRef RHS) const {
@@ -281,15 +265,15 @@
 FoldingSetImpl::Node
 *FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
                                      void *&InsertPos) {
- =20
-  void **Bucket =3D GetBucketFor(ID.ComputeHash(), Buckets, NumBuckets);
+  unsigned IDHash =3D ID.ComputeHash();
+  void **Bucket =3D GetBucketFor(IDHash, Buckets, NumBuckets);
   void *Probe =3D *Bucket;
  =20
   InsertPos =3D 0;
  =20
   FoldingSetNodeID TempID;
   while (Node *NodeInBucket =3D GetNextPtr(Probe)) {
-    if (NodeEquals(NodeInBucket, ID, TempID))
+    if (NodeEquals(NodeInBucket, ID, IDHash, TempID))
       return NodeInBucket;
     TempID.clear();
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/GraphWri=
ter.cpp
--- a/head/contrib/llvm/lib/Support/GraphWriter.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Support/GraphWriter.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -11,12 +11,16 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/GraphWriter.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Config/config.h"
 using namespace llvm;
=20
+static cl::opt<bool> ViewBackground("view-background", cl::Hidden,
+  cl::desc("Execute graph viewer in the background. Creates tmp file litte=
r."));
+
 std::string llvm::DOT::EscapeString(const std::string &Label) {
   std::string Str(Label);
   for (unsigned i =3D 0; i !=3D Str.length(); ++i)
@@ -49,10 +53,28 @@
   return Str;
 }
=20
-
+// Execute the graph viewer. Return true if successful.
+static bool LLVM_ATTRIBUTE_UNUSED
+ExecGraphViewer(const sys::Path &ExecPath, std::vector<const char*> &args,
+                const sys::Path &Filename, bool wait, std::string &ErrMsg)=
 {
+  if (wait) {
+    if (sys::Program::ExecuteAndWait(ExecPath, &args[0],0,0,0,0,&ErrMsg)) {
+      errs() << "Error: " << ErrMsg << "\n";
+      return false;
+    }
+    Filename.eraseFromDisk();
+    errs() << " done. \n";
+  }
+  else {
+    sys::Program::ExecuteNoWait(ExecPath, &args[0],0,0,0,&ErrMsg);
+    errs() << "Remember to erase graph file: " << Filename.str() << "\n";
+  }
+  return true;
+}
=20
 void llvm::DisplayGraph(const sys::Path &Filename, bool wait,
                         GraphProgram::Name program) {
+  wait &=3D !ViewBackground;
   std::string ErrMsg;
 #if HAVE_GRAPHVIZ
   sys::Path Graphviz(LLVM_PATH_GRAPHVIZ);
@@ -61,14 +83,10 @@
   args.push_back(Graphviz.c_str());
   args.push_back(Filename.c_str());
   args.push_back(0);
- =20
+
   errs() << "Running 'Graphviz' program... ";
-  if (sys::Program::ExecuteAndWait(Graphviz, &args[0],0,0,0,0,&ErrMsg)) {
-    errs() << "Error: " << ErrMsg << "\n";
+  if (!ExecGraphViewer(Graphviz, args, Filename, wait, ErrMsg))
     return;
-  }
-  Filename.eraseFromDisk();
-  errs() << " done. \n";
=20
 #elif HAVE_XDOT_PY
   std::vector<const char*> args;
@@ -83,17 +101,12 @@
   case GraphProgram::CIRCO: args.push_back("-f"); args.push_back("circo");=
break;
   default: errs() << "Unknown graph layout name; using default.\n";
   }
- =20
+
   args.push_back(0);
=20
   errs() << "Running 'xdot.py' program... ";
-  if (sys::Program::ExecuteAndWait(sys::Path(LLVM_PATH_XDOT_PY),
-                                   &args[0],0,0,0,0,&ErrMsg)) {
-    errs() << "Error: " << ErrMsg << "\n";
+  if (!ExecGraphViewer(sys::Path(LLVM_PATH_XDOT_PY), args, Filename, wait,=
 ErrMsg))
     return;
-  }
-  Filename.eraseFromDisk();
-  errs() << " done. \n";
=20
 #elif (HAVE_GV && (HAVE_DOT || HAVE_FDP || HAVE_NEATO || \
                    HAVE_TWOPI || HAVE_CIRCO))
@@ -150,14 +163,11 @@
   args.push_back("-o");
   args.push_back(PSFilename.c_str());
   args.push_back(0);
- =20
+
   errs() << "Running '" << prog.str() << "' program... ";
=20
-  if (sys::Program::ExecuteAndWait(prog, &args[0], 0, 0, 0, 0, &ErrMsg)) {
-    errs() << "Error: " << ErrMsg << "\n";
+  if (!ExecGraphViewer(prog, args, Filename, wait, ErrMsg))
     return;
-  }
-  errs() << " done. \n";
=20
   sys::Path gv(LLVM_PATH_GV);
   args.clear();
@@ -165,19 +175,11 @@
   args.push_back(PSFilename.c_str());
   args.push_back("--spartan");
   args.push_back(0);
- =20
+
   ErrMsg.clear();
-  if (wait) {
-     if (sys::Program::ExecuteAndWait(gv, &args[0],0,0,0,0,&ErrMsg))
-        errs() << "Error: " << ErrMsg << "\n";
-     Filename.eraseFromDisk();
-     PSFilename.eraseFromDisk();
-  }
-  else {
-     sys::Program::ExecuteNoWait(gv, &args[0],0,0,0,&ErrMsg);
-     errs() << "Remember to erase graph files: " << Filename.str() << " "
-            << PSFilename.str() << "\n";
-  }
+  if (!ExecGraphViewer(gv, args, PSFilename, wait, ErrMsg))
+    return;
+
 #elif HAVE_DOTTY
   sys::Path dotty(LLVM_PATH_DOTTY);
=20
@@ -185,16 +187,13 @@
   args.push_back(dotty.c_str());
   args.push_back(Filename.c_str());
   args.push_back(0);
- =20
-  errs() << "Running 'dotty' program... ";
-  if (sys::Program::ExecuteAndWait(dotty, &args[0],0,0,0,0,&ErrMsg)) {
-     errs() << "Error: " << ErrMsg << "\n";
-  } else {
+
 // Dotty spawns another app and doesn't wait until it returns
 #if defined (__MINGW32__) || defined (_WINDOWS)
+  wait =3D false;
+#endif
+  errs() << "Running 'dotty' program... ";
+  if (!ExecGraphViewer(dotty, args, Filename, wait, ErrMsg))
     return;
 #endif
-    Filename.eraseFromDisk();
-  }
-#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Host.cpp
--- a/head/contrib/llvm/lib/Support/Host.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Host.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -61,6 +61,8 @@
     *rECX =3D registers[2];
     *rEDX =3D registers[3];
     return false;
+  #else
+    return true;
   #endif
 #elif defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M=
_IX86)
   #if defined(__GNUC__)
@@ -87,9 +89,14 @@
       mov   dword ptr [esi],edx
     }
     return false;
+// pedantic #else returns to appease -Wunreachable-code (so we don't gener=
ate
+// postprocessed code that looks like "return true; return false;")
+  #else
+    return true;
   #endif
+#else
+  return true;
 #endif
-  return true;
 }
=20
 static void DetectX86FamilyModel(unsigned EAX, unsigned &Family,
@@ -298,6 +305,10 @@
         }
       case 16:
         return "amdfam10";
+      case 20:
+        return "btver1";
+      case 21:
+        return "bdver1";
     default:
       return "generic";
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/ManagedS=
tatic.cpp
--- a/head/contrib/llvm/lib/Support/ManagedStatic.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Support/ManagedStatic.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -27,8 +27,15 @@
     if (Ptr =3D=3D 0) {
       void* tmp =3D Creator ? Creator() : 0;
=20
+      TsanHappensBefore(this);
       sys::MemoryFence();
+
+      // This write is racy against the first read in the ManagedStatic
+      // accessors. The race is benign because it does a second read after=
 a
+      // memory fence, at which point it isn't possible to get a partial v=
alue.
+      TsanIgnoreWritesBegin();
       Ptr =3D tmp;
+      TsanIgnoreWritesEnd();
       DeleterFn =3D Deleter;
      =20
       // Add to list of managed statics.
@@ -72,4 +79,3 @@
=20
   if (llvm_is_multithreaded()) llvm_stop_multithreaded();
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/MemoryBu=
ffer.cpp
--- a/head/contrib/llvm/lib/Support/MemoryBuffer.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Support/MemoryBuffer.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,6 +14,7 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/Config/config.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Errno.h"
 #include "llvm/Support/Path.h"
@@ -29,15 +30,12 @@
 #include <sys/stat.h>
 #if !defined(_MSC_VER) && !defined(__MINGW32__)
 #include <unistd.h>
-#include <sys/uio.h>
 #else
 #include <io.h>
 #endif
 #include <fcntl.h>
 using namespace llvm;
=20
-namespace { const llvm::error_code success; }
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // MemoryBuffer implementation itself.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -306,7 +304,17 @@
                                                       RealMapOffset)) {
       result.reset(GetNamedBuffer<MemoryBufferMMapFile>(
           StringRef(Pages + Delta, MapSize), Filename, RequiresNullTermina=
tor));
-      return success;
+
+      if (RequiresNullTerminator && result->getBufferEnd()[0] !=3D '\0') {
+        // There could be a racing issue that resulted in the file being l=
arger
+        // than the FileSize passed by the caller. We already have an asse=
rtion
+        // for this in MemoryBuffer::init() but have a runtime guarantee t=
hat
+        // the buffer will be null-terminated here, so do a copy that adds=
 a
+        // null-terminator.
+        result.reset(MemoryBuffer::getMemBufferCopy(result->getBuffer(),
+                                                    Filename));
+      }
+      return error_code::success();
     }
   }
=20
@@ -321,29 +329,35 @@
   char *BufPtr =3D const_cast<char*>(SB->getBufferStart());
=20
   size_t BytesLeft =3D MapSize;
+#ifndef HAVE_PREAD
   if (lseek(FD, Offset, SEEK_SET) =3D=3D -1)
     return error_code(errno, posix_category());
+#endif
=20
   while (BytesLeft) {
+#ifdef HAVE_PREAD
+    ssize_t NumRead =3D ::pread(FD, BufPtr, BytesLeft, MapSize-BytesLeft+O=
ffset);
+#else
     ssize_t NumRead =3D ::read(FD, BufPtr, BytesLeft);
+#endif
     if (NumRead =3D=3D -1) {
       if (errno =3D=3D EINTR)
         continue;
       // Error while reading.
       return error_code(errno, posix_category());
-    } else if (NumRead =3D=3D 0) {
-      // We hit EOF early, truncate and terminate buffer.
-      Buf->BufferEnd =3D BufPtr;
-      *BufPtr =3D 0;
-      result.swap(SB);
-      return success;
+    }
+    if (NumRead =3D=3D 0) {
+      assert(0 && "We got inaccurate FileSize value or fstat reported an "
+                   "invalid file size.");
+      *BufPtr =3D '\0'; // null-terminate at the actual size.
+      break;
     }
     BytesLeft -=3D NumRead;
     BufPtr +=3D NumRead;
   }
=20
   result.swap(SB);
-  return success;
+  return error_code::success();
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -372,5 +386,5 @@
   } while (ReadBytes !=3D 0);
=20
   result.reset(getMemBufferCopy(Buffer, "<stdin>"));
-  return success;
+  return error_code::success();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Mutex.cpp
--- a/head/contrib/llvm/lib/Support/Mutex.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Mutex.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -19,7 +19,7 @@
 //=3D=3D=3D          independent code.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#if !defined(ENABLE_THREADS) || ENABLE_THREADS =3D=3D 0
+#if !defined(LLVM_ENABLE_THREADS) || LLVM_ENABLE_THREADS =3D=3D 0
 // Define all methods as no-ops if threading is explicitly disabled
 namespace llvm {
 using namespace sys;
@@ -40,109 +40,80 @@
 namespace llvm {
 using namespace sys;
=20
-
-// This variable is useful for situations where the pthread library has be=
en
-// compiled with weak linkage for its interface symbols. This allows the
-// threading support to be turned off by simply not linking against -lpthr=
ead.
-// In that situation, the value of pthread_mutex_init will be 0 and
-// consequently pthread_enabled will be false. In such situations, all the
-// pthread operations become no-ops and the functions all return false. If
-// pthread_mutex_init does have an address, then mutex support is enabled.
-// Note: all LLVM tools will link against -lpthread if its available since=
 it
-//       is configured into the LIBS variable.
-// Note: this line of code generates a warning if pthread_mutex_init is not
-//       declared with weak linkage. It's safe to ignore the warning.
-static const bool pthread_enabled =3D true;
-
 // Construct a Mutex using pthread calls
 MutexImpl::MutexImpl( bool recursive)
   : data_(0)
 {
-  if (pthread_enabled)
-  {
-    // Declare the pthread_mutex data structures
-    pthread_mutex_t* mutex =3D
-      static_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));
-    pthread_mutexattr_t attr;
+  // Declare the pthread_mutex data structures
+  pthread_mutex_t* mutex =3D
+    static_cast<pthread_mutex_t*>(malloc(sizeof(pthread_mutex_t)));
+  pthread_mutexattr_t attr;
=20
-    // Initialize the mutex attributes
-    int errorcode =3D pthread_mutexattr_init(&attr);
-    assert(errorcode =3D=3D 0);
+  // Initialize the mutex attributes
+  int errorcode =3D pthread_mutexattr_init(&attr);
+  assert(errorcode =3D=3D 0); (void)errorcode;
=20
-    // Initialize the mutex as a recursive mutex, if requested, or normal
-    // otherwise.
-    int kind =3D ( recursive  ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_NO=
RMAL );
-    errorcode =3D pthread_mutexattr_settype(&attr, kind);
-    assert(errorcode =3D=3D 0);
+  // Initialize the mutex as a recursive mutex, if requested, or normal
+  // otherwise.
+  int kind =3D ( recursive  ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_NORM=
AL );
+  errorcode =3D pthread_mutexattr_settype(&attr, kind);
+  assert(errorcode =3D=3D 0);
=20
 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)=
 && !defined(__DragonFly__)
-    // Make it a process local mutex
-    errorcode =3D pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIV=
ATE);
-    assert(errorcode =3D=3D 0);
+  // Make it a process local mutex
+  errorcode =3D pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVAT=
E);
+  assert(errorcode =3D=3D 0);
 #endif
=20
-    // Initialize the mutex
-    errorcode =3D pthread_mutex_init(mutex, &attr);
-    assert(errorcode =3D=3D 0);
+  // Initialize the mutex
+  errorcode =3D pthread_mutex_init(mutex, &attr);
+  assert(errorcode =3D=3D 0);
=20
-    // Destroy the attributes
-    errorcode =3D pthread_mutexattr_destroy(&attr);
-    assert(errorcode =3D=3D 0);
+  // Destroy the attributes
+  errorcode =3D pthread_mutexattr_destroy(&attr);
+  assert(errorcode =3D=3D 0);
=20
-    // Assign the data member
-    data_ =3D mutex;
-  }
+  // Assign the data member
+  data_ =3D mutex;
 }
=20
 // Destruct a Mutex
 MutexImpl::~MutexImpl()
 {
-  if (pthread_enabled)
-  {
-    pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
-    assert(mutex !=3D 0);
-    pthread_mutex_destroy(mutex);
-    free(mutex);
-  }
+  pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
+  assert(mutex !=3D 0);
+  pthread_mutex_destroy(mutex);
+  free(mutex);
 }
=20
 bool
 MutexImpl::acquire()
 {
-  if (pthread_enabled)
-  {
-    pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
-    assert(mutex !=3D 0);
+  pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
+  assert(mutex !=3D 0);
=20
-    int errorcode =3D pthread_mutex_lock(mutex);
-    return errorcode =3D=3D 0;
-  } else return false;
+  int errorcode =3D pthread_mutex_lock(mutex);
+  return errorcode =3D=3D 0;
 }
=20
 bool
 MutexImpl::release()
 {
-  if (pthread_enabled)
-  {
-    pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
-    assert(mutex !=3D 0);
+  pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
+  assert(mutex !=3D 0);
=20
-    int errorcode =3D pthread_mutex_unlock(mutex);
-    return errorcode =3D=3D 0;
-  } else return false;
+  int errorcode =3D pthread_mutex_unlock(mutex);
+  return errorcode =3D=3D 0;
 }
=20
 bool
 MutexImpl::tryacquire()
 {
-  if (pthread_enabled)
-  {
-    pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
-    assert(mutex !=3D 0);
+  pthread_mutex_t* mutex =3D static_cast<pthread_mutex_t*>(data_);
+  assert(mutex !=3D 0);
=20
-    int errorcode =3D pthread_mutex_trylock(mutex);
-    return errorcode =3D=3D 0;
-  } else return false;
+  int errorcode =3D pthread_mutex_trylock(mutex);
+  return errorcode =3D=3D 0;
 }
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Path.cpp
--- a/head/contrib/llvm/lib/Support/Path.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Path.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -38,16 +38,6 @@
   return path < that.path;
 }
=20
-Path
-Path::GetLLVMConfigDir() {
-  Path result;
-#ifdef LLVM_ETCDIR
-  if (result.set(LLVM_ETCDIR))
-    return result;
-#endif
-  return GetLLVMDefaultConfigDir();
-}
-
 LLVMFileType
 sys::IdentifyFileType(const char *magic, unsigned length) {
   assert(magic && "Invalid magic number string");
@@ -100,7 +90,7 @@
     case 0xCF: {
       uint16_t type =3D 0;
       if (magic[0] =3D=3D char(0xFE) && magic[1] =3D=3D char(0xED) &&
-          magic[2] =3D=3D char(0xFA) &&=20
+          magic[2] =3D=3D char(0xFA) &&
           (magic[3] =3D=3D char(0xCE) || magic[3] =3D=3D char(0xCF))) {
         /* Native endian */
         if (length >=3D 16) type =3D magic[14] << 8 | magic[15];
@@ -162,31 +152,31 @@
=20
 bool
 Path::isArchive() const {
-  LLVMFileType type;
+  fs::file_magic type;
   if (fs::identify_magic(str(), type))
     return false;
-  return type =3D=3D Archive_FileType;
+  return type =3D=3D fs::file_magic::archive;
 }
=20
 bool
 Path::isDynamicLibrary() const {
-  LLVMFileType type;
+  fs::file_magic type;
   if (fs::identify_magic(str(), type))
     return false;
   switch (type) {
     default: return false;
-    case Mach_O_FixedVirtualMemorySharedLib_FileType:
-    case Mach_O_DynamicallyLinkedSharedLib_FileType:
-    case Mach_O_DynamicallyLinkedSharedLibStub_FileType:
-    case ELF_SharedObject_FileType:
-    case COFF_FileType:  return true;
+    case fs::file_magic::macho_fixed_virtual_memory_shared_lib:
+    case fs::file_magic::macho_dynamically_linked_shared_lib:
+    case fs::file_magic::macho_dynamically_linked_shared_lib_stub:
+    case fs::file_magic::elf_shared_object:
+    case fs::file_magic::pecoff_executable:  return true;
   }
 }
=20
 bool
 Path::isObjectFile() const {
-  LLVMFileType type;
-  if (fs::identify_magic(str(), type) || type =3D=3D Unknown_FileType)
+  fs::file_magic type;
+  if (fs::identify_magic(str(), type) || type =3D=3D fs::file_magic::unkno=
wn)
     return false;
   return true;
 }
@@ -222,10 +212,10 @@
=20
 bool
 Path::isBitcodeFile() const {
-  LLVMFileType type;
+  fs::file_magic type;
   if (fs::identify_magic(str(), type))
     return false;
-  return type =3D=3D Bitcode_FileType;
+  return type =3D=3D fs::file_magic::bitcode;
 }
=20
 bool Path::hasMagicNumber(StringRef Magic) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/PathV2.c=
pp
--- a/head/contrib/llvm/lib/Support/PathV2.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Support/PathV2.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -13,6 +13,7 @@
=20
 #include "llvm/Support/PathV2.h"
 #include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Endian.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <cctype>
 #include <cstdio>
@@ -23,15 +24,13 @@
   using llvm::sys::path::is_separator;
=20
 #ifdef LLVM_ON_WIN32
-  const StringRef separators =3D "\\/";
-  const char      prefered_separator =3D '\\';
+  const char *separators =3D "\\/";
+  const char  prefered_separator =3D '\\';
 #else
-  const StringRef separators =3D "/";
-  const char      prefered_separator =3D '/';
+  const char  separators =3D '/';
+  const char  prefered_separator =3D '/';
 #endif
=20
-  const llvm::error_code success;
-
   StringRef find_first_component(StringRef path) {
     // Look for this first component in the following order.
     // * empty (in this case we return an empty string)
@@ -347,7 +346,7 @@
=20
 const StringRef relative_path(StringRef path) {
   StringRef root =3D root_path(path);
-  return root.substr(root.size());
+  return path.substr(root.size());
 }
=20
 void append(SmallVectorImpl<char> &path, const Twine &a,
@@ -492,7 +491,7 @@
=20
 void system_temp_directory(bool erasedOnReboot, SmallVectorImpl<char> &res=
ult) {
   result.clear();
- =20
+
   // Check whether the temporary directory is specified by an environment
   // variable.
   const char *EnvironmentVariable;
@@ -505,7 +504,7 @@
     result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
     return;
   }
-   =20
+
   // Fall back to a system default.
   const char *DefaultResult;
 #ifdef LLVM_ON_WIN32
@@ -519,7 +518,7 @@
 #endif
   result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
 }
- =20
+
 bool has_root_name(const Twine &path) {
   SmallString<128> path_storage;
   StringRef p =3D path.toStringRef(path_storage);
@@ -601,12 +600,16 @@
 error_code make_absolute(SmallVectorImpl<char> &path) {
   StringRef p(path.data(), path.size());
=20
-  bool rootName      =3D path::has_root_name(p),
-       rootDirectory =3D path::has_root_directory(p);
+  bool rootDirectory =3D path::has_root_directory(p),
+#ifdef LLVM_ON_WIN32
+       rootName =3D path::has_root_name(p);
+#else
+       rootName =3D true;
+#endif
=20
   // Already absolute.
   if (rootName && rootDirectory)
-    return success;
+    return error_code::success();
=20
   // All of the following conditions will need the current directory.
   SmallString<128> current_dir;
@@ -618,7 +621,7 @@
     path::append(current_dir, p);
     // Set path to the result.
     path.swap(current_dir);
-    return success;
+    return error_code::success();
   }
=20
   if (!rootName && rootDirectory) {
@@ -627,7 +630,7 @@
     path::append(curDirRootName, p);
     // Set path to the result.
     path.swap(curDirRootName);
-    return success;
+    return error_code::success();
   }
=20
   if (rootName && !rootDirectory) {
@@ -639,7 +642,7 @@
     SmallString<128> res;
     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativeP=
ath);
     path.swap(res);
-    return success;
+    return error_code::success();
   }
=20
   llvm_unreachable("All rootName and rootDirectory combinations should hav=
e "
@@ -651,12 +654,13 @@
   StringRef p =3D path.toStringRef(path_storage);
=20
   StringRef parent =3D path::parent_path(p);
-  bool parent_exists;
+  if (!parent.empty()) {
+    bool parent_exists;
+    if (error_code ec =3D fs::exists(parent, parent_exists)) return ec;
=20
-  if (error_code ec =3D fs::exists(parent, parent_exists)) return ec;
-
-  if (!parent_exists)
-    if (error_code ec =3D create_directories(parent, existed)) return ec;
+    if (!parent_exists)
+      if (error_code ec =3D create_directories(parent, existed)) return ec;
+  }
=20
   return create_directory(p, existed);
 }
@@ -678,7 +682,7 @@
   if (error_code ec =3D status(path, st))
     return ec;
   result =3D is_directory(st);
-  return success;
+  return error_code::success();
 }
=20
 bool is_regular_file(file_status status) {
@@ -690,7 +694,7 @@
   if (error_code ec =3D status(path, st))
     return ec;
   result =3D is_regular_file(st);
-  return success;
+  return error_code::success();
 }
=20
 bool is_symlink(file_status status) {
@@ -702,7 +706,7 @@
   if (error_code ec =3D status(path, st))
     return ec;
   result =3D is_symlink(st);
-  return success;
+  return error_code::success();
 }
=20
 bool is_other(file_status status) {
@@ -729,23 +733,134 @@
     if (ec =3D=3D errc::value_too_large) {
       // Magic.size() > file_size(Path).
       result =3D false;
-      return success;
+      return error_code::success();
     }
     return ec;
   }
=20
   result =3D Magic =3D=3D Buffer;
-  return success;
+  return error_code::success();
 }
=20
-error_code identify_magic(const Twine &path, LLVMFileType &result) {
+/// @brief Identify the magic in magic.
+file_magic identify_magic(StringRef magic) {
+  switch ((unsigned char)magic[0]) {
+    case 0xDE:  // 0x0B17C0DE =3D BC wraper
+      if (magic[1] =3D=3D (char)0xC0 && magic[2] =3D=3D (char)0x17 &&
+          magic[3] =3D=3D (char)0x0B)
+        return file_magic::bitcode;
+      break;
+    case 'B':
+      if (magic[1] =3D=3D 'C' && magic[2] =3D=3D (char)0xC0 && magic[3] =
=3D=3D (char)0xDE)
+        return file_magic::bitcode;
+      break;
+    case '!':
+      if (magic.size() >=3D 8)
+        if (memcmp(magic.data(),"!<arch>\n",8) =3D=3D 0)
+          return file_magic::archive;
+      break;
+
+    case '\177':
+      if (magic[1] =3D=3D 'E' && magic[2] =3D=3D 'L' && magic[3] =3D=3D 'F=
') {
+        if (magic.size() >=3D 18 && magic[17] =3D=3D 0)
+          switch (magic[16]) {
+            default: break;
+            case 1: return file_magic::elf_relocatable;
+            case 2: return file_magic::elf_executable;
+            case 3: return file_magic::elf_shared_object;
+            case 4: return file_magic::elf_core;
+          }
+      }
+      break;
+
+    case 0xCA:
+      if (magic[1] =3D=3D char(0xFE) && magic[2] =3D=3D char(0xBA) &&
+          magic[3] =3D=3D char(0xBE)) {
+        // This is complicated by an overlap with Java class files.
+        // See the Mach-O section in /usr/share/file/magic for details.
+        if (magic.size() >=3D 8 && magic[7] < 43)
+          // FIXME: Universal Binary of any type.
+          return file_magic::macho_dynamically_linked_shared_lib;
+      }
+      break;
+
+      // The two magic numbers for mach-o are:
+      // 0xfeedface - 32-bit mach-o
+      // 0xfeedfacf - 64-bit mach-o
+    case 0xFE:
+    case 0xCE:
+    case 0xCF: {
+      uint16_t type =3D 0;
+      if (magic[0] =3D=3D char(0xFE) && magic[1] =3D=3D char(0xED) &&
+          magic[2] =3D=3D char(0xFA) &&
+          (magic[3] =3D=3D char(0xCE) || magic[3] =3D=3D char(0xCF))) {
+        /* Native endian */
+        if (magic.size() >=3D 16) type =3D magic[14] << 8 | magic[15];
+      } else if ((magic[0] =3D=3D char(0xCE) || magic[0] =3D=3D char(0xCF)=
) &&
+                 magic[1] =3D=3D char(0xFA) && magic[2] =3D=3D char(0xED) =
&&
+                 magic[3] =3D=3D char(0xFE)) {
+        /* Reverse endian */
+        if (magic.size() >=3D 14) type =3D magic[13] << 8 | magic[12];
+      }
+      switch (type) {
+        default: break;
+        case 1: return file_magic::macho_object;
+        case 2: return file_magic::macho_executable;
+        case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
+        case 4: return file_magic::macho_core;
+        case 5: return file_magic::macho_preload_executabl;
+        case 6: return file_magic::macho_dynamically_linked_shared_lib;
+        case 7: return file_magic::macho_dynamic_linker;
+        case 8: return file_magic::macho_bundle;
+        case 9: return file_magic::macho_dynamic_linker;
+        case 10: return file_magic::macho_dsym_companion;
+      }
+      break;
+    }
+    case 0xF0: // PowerPC Windows
+    case 0x83: // Alpha 32-bit
+    case 0x84: // Alpha 64-bit
+    case 0x66: // MPS R4000 Windows
+    case 0x50: // mc68K
+    case 0x4c: // 80386 Windows
+      if (magic[1] =3D=3D 0x01)
+        return file_magic::coff_object;
+
+    case 0x90: // PA-RISC Windows
+    case 0x68: // mc68K Windows
+      if (magic[1] =3D=3D 0x02)
+        return file_magic::coff_object;
+      break;
+
+    case 0x4d: // Possible MS-DOS stub on Windows PE file
+      if (magic[1] =3D=3D 0x5a) {
+        uint32_t off =3D
+          *reinterpret_cast<const support::ulittle32_t*>(magic.data() + 0x=
3c);
+        // PE/COFF file, either EXE or DLL.
+        if (off < magic.size() && memcmp(magic.data() + off, "PE\0\0",4) =
=3D=3D 0)
+          return file_magic::pecoff_executable;
+      }
+      break;
+
+    case 0x64: // x86-64 Windows.
+      if (magic[1] =3D=3D char(0x86))
+        return file_magic::coff_object;
+      break;
+
+    default:
+      break;
+  }
+  return file_magic::unknown;
+}
+
+error_code identify_magic(const Twine &path, file_magic &result) {
   SmallString<32> Magic;
   error_code ec =3D get_magic(path, Magic.capacity(), Magic);
   if (ec && ec !=3D errc::value_too_large)
     return ec;
=20
-  result =3D IdentifyFileType(Magic.data(), Magic.size());
-  return success;
+  result =3D identify_magic(Magic);
+  return error_code::success();
 }
=20
 namespace {
@@ -753,7 +868,9 @@
   if (ft =3D=3D file_type::directory_file) {
     // This code would be a lot better with exceptions ;/.
     error_code ec;
-    for (directory_iterator i(path, ec), e; i !=3D e; i.increment(ec)) {
+    directory_iterator i(path, ec);
+    if (ec) return ec;
+    for (directory_iterator e; i !=3D e; i.increment(ec)) {
       if (ec) return ec;
       file_status st;
       if (error_code ec =3D i->status(st)) return ec;
@@ -770,7 +887,7 @@
     ++count;
   }
=20
-  return success;
+  return error_code::success();
 }
 } // end unnamed namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Program.=
cpp
--- a/head/contrib/llvm/lib/Support/Program.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/Support/Program.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -13,6 +13,7 @@
=20
 #include "llvm/Support/Program.h"
 #include "llvm/Config/config.h"
+#include "llvm/Support/system_error.h"
 using namespace llvm;
 using namespace sys;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/RWMutex.=
cpp
--- a/head/contrib/llvm/lib/Support/RWMutex.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/Support/RWMutex.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -20,7 +20,7 @@
 //=3D=3D=3D          independent code.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#if !defined(ENABLE_THREADS) || ENABLE_THREADS =3D=3D 0
+#if !defined(LLVM_ENABLE_THREADS) || LLVM_ENABLE_THREADS =3D=3D 0
 // Define all methods as no-ops if threading is explicitly disabled
 namespace llvm {
 using namespace sys;
@@ -42,107 +42,75 @@
 namespace llvm {
 using namespace sys;
=20
-
-// This variable is useful for situations where the pthread library has be=
en
-// compiled with weak linkage for its interface symbols. This allows the
-// threading support to be turned off by simply not linking against -lpthr=
ead.
-// In that situation, the value of pthread_mutex_init will be 0 and
-// consequently pthread_enabled will be false. In such situations, all the
-// pthread operations become no-ops and the functions all return false. If
-// pthread_rwlock_init does have an address, then rwlock support is enable=
d.
-// Note: all LLVM tools will link against -lpthread if its available since=
 it
-//       is configured into the LIBS variable.
-// Note: this line of code generates a warning if pthread_rwlock_init is n=
ot
-//       declared with weak linkage. It's safe to ignore the warning.
-static const bool pthread_enabled =3D true;
-
 // Construct a RWMutex using pthread calls
 RWMutexImpl::RWMutexImpl()
   : data_(0)
 {
-  if (pthread_enabled)
-  {
-    // Declare the pthread_rwlock data structures
-    pthread_rwlock_t* rwlock =3D
-      static_cast<pthread_rwlock_t*>(malloc(sizeof(pthread_rwlock_t)));
+  // Declare the pthread_rwlock data structures
+  pthread_rwlock_t* rwlock =3D
+    static_cast<pthread_rwlock_t*>(malloc(sizeof(pthread_rwlock_t)));
=20
 #ifdef __APPLE__
-    // Workaround a bug/mis-feature in Darwin's pthread_rwlock_init.
-    bzero(rwlock, sizeof(pthread_rwlock_t));
+  // Workaround a bug/mis-feature in Darwin's pthread_rwlock_init.
+  bzero(rwlock, sizeof(pthread_rwlock_t));
 #endif
=20
-    // Initialize the rwlock
-    int errorcode =3D pthread_rwlock_init(rwlock, NULL);
-    (void)errorcode;
-    assert(errorcode =3D=3D 0);
+  // Initialize the rwlock
+  int errorcode =3D pthread_rwlock_init(rwlock, NULL);
+  (void)errorcode;
+  assert(errorcode =3D=3D 0);
=20
-    // Assign the data member
-    data_ =3D rwlock;
-  }
+  // Assign the data member
+  data_ =3D rwlock;
 }
=20
 // Destruct a RWMutex
 RWMutexImpl::~RWMutexImpl()
 {
-  if (pthread_enabled)
-  {
-    pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
-    assert(rwlock !=3D 0);
-    pthread_rwlock_destroy(rwlock);
-    free(rwlock);
-  }
+  pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
+  assert(rwlock !=3D 0);
+  pthread_rwlock_destroy(rwlock);
+  free(rwlock);
 }
=20
 bool
 RWMutexImpl::reader_acquire()
 {
-  if (pthread_enabled)
-  {
-    pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
-    assert(rwlock !=3D 0);
+  pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
+  assert(rwlock !=3D 0);
=20
-    int errorcode =3D pthread_rwlock_rdlock(rwlock);
-    return errorcode =3D=3D 0;
-  } else return false;
+  int errorcode =3D pthread_rwlock_rdlock(rwlock);
+  return errorcode =3D=3D 0;
 }
=20
 bool
 RWMutexImpl::reader_release()
 {
-  if (pthread_enabled)
-  {
-    pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
-    assert(rwlock !=3D 0);
+  pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
+  assert(rwlock !=3D 0);
=20
-    int errorcode =3D pthread_rwlock_unlock(rwlock);
-    return errorcode =3D=3D 0;
-  } else return false;
+  int errorcode =3D pthread_rwlock_unlock(rwlock);
+  return errorcode =3D=3D 0;
 }
=20
 bool
 RWMutexImpl::writer_acquire()
 {
-  if (pthread_enabled)
-  {
-    pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
-    assert(rwlock !=3D 0);
+  pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
+  assert(rwlock !=3D 0);
=20
-    int errorcode =3D pthread_rwlock_wrlock(rwlock);
-    return errorcode =3D=3D 0;
-  } else return false;
+  int errorcode =3D pthread_rwlock_wrlock(rwlock);
+  return errorcode =3D=3D 0;
 }
=20
 bool
 RWMutexImpl::writer_release()
 {
-  if (pthread_enabled)
-  {
-    pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
-    assert(rwlock !=3D 0);
+  pthread_rwlock_t* rwlock =3D static_cast<pthread_rwlock_t*>(data_);
+  assert(rwlock !=3D 0);
=20
-    int errorcode =3D pthread_rwlock_unlock(rwlock);
-    return errorcode =3D=3D 0;
-  } else return false;
+  int errorcode =3D pthread_rwlock_unlock(rwlock);
+  return errorcode =3D=3D 0;
 }
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/SmallPtr=
Set.cpp
--- a/head/contrib/llvm/lib/Support/SmallPtrSet.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Support/SmallPtrSet.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,6 +14,7 @@
=20
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/MathExtras.h"
+#include <algorithm>
 #include <cstdlib>
=20
 using namespace llvm;
@@ -223,6 +224,56 @@
   NumTombstones =3D RHS.NumTombstones;
 }
=20
+void SmallPtrSetImpl::swap(SmallPtrSetImpl &RHS) {
+  if (this =3D=3D &RHS) return;
+
+  // We can only avoid copying elements if neither set is small.
+  if (!this->isSmall() && !RHS.isSmall()) {
+    std::swap(this->CurArray, RHS.CurArray);
+    std::swap(this->CurArraySize, RHS.CurArraySize);
+    std::swap(this->NumElements, RHS.NumElements);
+    std::swap(this->NumTombstones, RHS.NumTombstones);
+    return;
+  }
+
+  // FIXME: From here on we assume that both sets have the same small size.
+
+  // If only RHS is small, copy the small elements into LHS and move the p=
ointer
+  // from LHS to RHS.
+  if (!this->isSmall() && RHS.isSmall()) {
+    std::copy(RHS.SmallArray, RHS.SmallArray+RHS.CurArraySize,
+              this->SmallArray);
+    std::swap(this->NumElements, RHS.NumElements);
+    std::swap(this->CurArraySize, RHS.CurArraySize);
+    RHS.CurArray =3D this->CurArray;
+    RHS.NumTombstones =3D this->NumTombstones;
+    this->CurArray =3D this->SmallArray;
+    this->NumTombstones =3D 0;
+    return;
+  }
+
+  // If only LHS is small, copy the small elements into RHS and move the p=
ointer
+  // from RHS to LHS.
+  if (this->isSmall() && !RHS.isSmall()) {
+    std::copy(this->SmallArray, this->SmallArray+this->CurArraySize,
+              RHS.SmallArray);
+    std::swap(RHS.NumElements, this->NumElements);
+    std::swap(RHS.CurArraySize, this->CurArraySize);
+    this->CurArray =3D RHS.CurArray;
+    this->NumTombstones =3D RHS.NumTombstones;
+    RHS.CurArray =3D RHS.SmallArray;
+    RHS.NumTombstones =3D 0;
+    return;
+  }
+
+  // Both a small, just swap the small elements.
+  assert(this->isSmall() && RHS.isSmall());
+  assert(this->CurArraySize =3D=3D RHS.CurArraySize);
+  std::swap_ranges(this->SmallArray, this->SmallArray+this->CurArraySize,
+                   RHS.SmallArray);
+  std::swap(this->NumElements, RHS.NumElements);
+}
+
 SmallPtrSetImpl::~SmallPtrSetImpl() {
   if (!isSmall())
     free(CurArray);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/SourceMg=
r.cpp
--- a/head/contrib/llvm/lib/Support/SourceMgr.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/SourceMgr.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -140,8 +140,9 @@
 ///
 /// @param Type - If non-null, the kind of message (e.g., "error") which is
 /// prefixed to the message.
-SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, const Twine &Msg,
-                                   const char *Type, bool ShowLine) const {
+SMDiagnostic SourceMgr::GetMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
+                                   const Twine &Msg,
+                                   ArrayRef<SMRange> Ranges) const {
=20
   // First thing to do: find the current buffer containing the specified
   // location.
@@ -156,33 +157,48 @@
          LineStart[-1] !=3D '\n' && LineStart[-1] !=3D '\r')
     --LineStart;
=20
-  std::string LineStr;
-  if (ShowLine) {
-    // Get the end of the line.
-    const char *LineEnd =3D Loc.getPointer();
-    while (LineEnd !=3D CurMB->getBufferEnd() &&
-           LineEnd[0] !=3D '\n' && LineEnd[0] !=3D '\r')
-      ++LineEnd;
-    LineStr =3D std::string(LineStart, LineEnd);
+  // Get the end of the line.
+  const char *LineEnd =3D Loc.getPointer();
+  while (LineEnd !=3D CurMB->getBufferEnd() &&
+         LineEnd[0] !=3D '\n' && LineEnd[0] !=3D '\r')
+    ++LineEnd;
+  std::string LineStr(LineStart, LineEnd);
+
+  // Convert any ranges to column ranges that only intersect the line of t=
he
+  // location.
+  SmallVector<std::pair<unsigned, unsigned>, 4> ColRanges;
+  for (unsigned i =3D 0, e =3D Ranges.size(); i !=3D e; ++i) {
+    SMRange R =3D Ranges[i];
+    if (!R.isValid()) continue;
+   =20
+    // If the line doesn't contain any part of the range, then ignore it.
+    if (R.Start.getPointer() > LineEnd || R.End.getPointer() < LineStart)
+      continue;
+  =20
+    // Ignore pieces of the range that go onto other lines.
+    if (R.Start.getPointer() < LineStart)
+      R.Start =3D SMLoc::getFromPointer(LineStart);
+    if (R.End.getPointer() > LineEnd)
+      R.End =3D SMLoc::getFromPointer(LineEnd);
+   =20
+    // Translate from SMLoc ranges to column ranges.
+    ColRanges.push_back(std::make_pair(R.Start.getPointer()-LineStart,
+                                       R.End.getPointer()-LineStart));
   }
-
-  std::string PrintedMsg;
-  raw_string_ostream OS(PrintedMsg);
-  if (Type)
-    OS << Type << ": ";
-  OS << Msg;
-
+ =20
   return SMDiagnostic(*this, Loc,
                       CurMB->getBufferIdentifier(), FindLineNumber(Loc, Cu=
rBuf),
-                      Loc.getPointer()-LineStart, OS.str(),
-                      LineStr, ShowLine);
+                      Loc.getPointer()-LineStart, Kind, Msg.str(),
+                      LineStr, ColRanges);
 }
=20
-void SourceMgr::PrintMessage(SMLoc Loc, const Twine &Msg,
-                             const char *Type, bool ShowLine) const {
+void SourceMgr::PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind,
+                             const Twine &Msg, ArrayRef<SMRange> Ranges) c=
onst {
+  SMDiagnostic Diagnostic =3D GetMessage(Loc, Kind, Msg, Ranges);
+ =20
   // Report the message with the diagnostic handler if present.
   if (DiagHandler) {
-    DiagHandler(GetMessage(Loc, Msg, Type, ShowLine), DiagContext);
+    DiagHandler(Diagnostic, DiagContext);
     return;
   }
=20
@@ -192,14 +208,24 @@
   assert(CurBuf !=3D -1 && "Invalid or unspecified location!");
   PrintIncludeStack(getBufferInfo(CurBuf).IncludeLoc, OS);
=20
-  GetMessage(Loc, Msg, Type, ShowLine).Print(0, OS);
+  Diagnostic.print(0, OS);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SMDiagnostic Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-void SMDiagnostic::Print(const char *ProgName, raw_ostream &S) const {
+SMDiagnostic::SMDiagnostic(const SourceMgr &sm, SMLoc L, const std::string=
 &FN,
+                           int Line, int Col, SourceMgr::DiagKind Kind,
+                           const std::string &Msg,
+                           const std::string &LineStr,
+                           ArrayRef<std::pair<unsigned,unsigned> > Ranges)
+  : SM(&sm), Loc(L), Filename(FN), LineNo(Line), ColumnNo(Col), Kind(Kind),
+    Message(Msg), LineContents(LineStr), Ranges(Ranges.vec()) {
+}
+
+
+void SMDiagnostic::print(const char *ProgName, raw_ostream &S) const {
   if (ProgName && ProgName[0])
     S << ProgName << ": ";
=20
@@ -217,16 +243,71 @@
     S << ": ";
   }
=20
+  switch (Kind) {
+  case SourceMgr::DK_Error: S << "error: "; break;
+  case SourceMgr::DK_Warning: S << "warning: "; break;
+  case SourceMgr::DK_Note: S << "note: "; break;
+  }
+ =20
   S << Message << '\n';
=20
-  if (LineNo !=3D -1 && ColumnNo !=3D -1 && ShowLine) {
-    S << LineContents << '\n';
+  if (LineNo =3D=3D -1 || ColumnNo =3D=3D -1)
+    return;
=20
-    // Print out spaces/tabs before the caret.
-    for (unsigned i =3D 0; i !=3D unsigned(ColumnNo); ++i)
-      S << (LineContents[i] =3D=3D '\t' ? '\t' : ' ');
-    S << "^\n";
+  // Build the line with the caret and ranges.
+  std::string CaretLine(LineContents.size()+1, ' ');
+ =20
+  // Expand any ranges.
+  for (unsigned r =3D 0, e =3D Ranges.size(); r !=3D e; ++r) {
+    std::pair<unsigned, unsigned> R =3D Ranges[r];
+    for (unsigned i =3D R.first,
+         e =3D std::min(R.second, (unsigned)LineContents.size())+1; i !=3D=
 e; ++i)
+      CaretLine[i] =3D '~';
   }
+   =20
+  // Finally, plop on the caret.
+  if (unsigned(ColumnNo) <=3D LineContents.size())
+    CaretLine[ColumnNo] =3D '^';
+  else=20
+    CaretLine[LineContents.size()] =3D '^';
+ =20
+  // ... and remove trailing whitespace so the output doesn't wrap for it.=
  We
+  // know that the line isn't completely empty because it has the caret in=
 it at
+  // least.
+  CaretLine.erase(CaretLine.find_last_not_of(' ')+1);
+ =20
+  // Print out the source line one character at a time, so we can expand t=
abs.
+  for (unsigned i =3D 0, e =3D LineContents.size(), OutCol =3D 0; i !=3D e=
; ++i) {
+    if (LineContents[i] !=3D '\t') {
+      S << LineContents[i];
+      ++OutCol;
+      continue;
+    }
+   =20
+    // If we have a tab, emit at least one space, then round up to 8 colum=
ns.
+    do {
+      S << ' ';
+      ++OutCol;
+    } while (OutCol & 7);
+  }
+  S << '\n';
+
+  // Print out the caret line, matching tabs in the source line.
+  for (unsigned i =3D 0, e =3D CaretLine.size(), OutCol =3D 0; i !=3D e; +=
+i) {
+    if (i >=3D LineContents.size() || LineContents[i] !=3D '\t') {
+      S << CaretLine[i];
+      ++OutCol;
+      continue;
+    }
+   =20
+    // Okay, we have a tab.  Insert the appropriate number of characters.
+    do {
+      S << CaretLine[i];
+      ++OutCol;
+    } while (OutCol & 7);
+  }
+ =20
+  S << '\n';
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Statisti=
c.cpp
--- a/head/contrib/llvm/lib/Support/Statistic.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/Statistic.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -24,6 +24,7 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Format.h"
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Mutex.h"
@@ -72,9 +73,12 @@
     if (Enabled)
       StatInfo->addStatistic(this);
=20
+    TsanHappensBefore(this);
     sys::MemoryFence();
     // Remember we have been registered.
+    TsanIgnoreWritesBegin();
     Initialized =3D true;
+    TsanIgnoreWritesEnd();
   }
 }
=20
@@ -126,13 +130,11 @@
      << "=3D=3D=3D" << std::string(73, '-') << "=3D=3D=3D\n\n";
=20
   // Print all of the statistics.
-  for (size_t i =3D 0, e =3D Stats.Stats.size(); i !=3D e; ++i) {
-    std::string CountStr =3D utostr(Stats.Stats[i]->getValue());
-    OS << std::string(MaxValLen-CountStr.size(), ' ')
-       << CountStr << " " << Stats.Stats[i]->getName()
-       << std::string(MaxNameLen-std::strlen(Stats.Stats[i]->getName()), '=
 ')
-       << " - " << Stats.Stats[i]->getDesc() << "\n";
-  }
+  for (size_t i =3D 0, e =3D Stats.Stats.size(); i !=3D e; ++i)
+    OS << format("%*u %-*s - %s\n",
+                 MaxValLen, Stats.Stats[i]->getValue(),
+                 MaxNameLen, Stats.Stats[i]->getName(),
+                 Stats.Stats[i]->getDesc());
=20
   OS << '\n';  // Flush the output stream.
   OS.flush();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/StringEx=
tras.cpp
--- a/head/contrib/llvm/lib/Support/StringExtras.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Support/StringExtras.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -57,24 +57,3 @@
     S =3D getToken(S.second, Delimiters);
   }
 }
-
-void llvm::StringRef::split(SmallVectorImpl<StringRef> &A,
-                            StringRef Separators, int MaxSplit,
-                            bool KeepEmpty) const {
-  StringRef rest =3D *this;
-
-  // rest.data() is used to distinguish cases like "a," that splits into
-  // "a" + "" and "a" that splits into "a" + 0.
-  for (int splits =3D 0;
-       rest.data() !=3D NULL && (MaxSplit < 0 || splits < MaxSplit);
-       ++splits) {
-    std::pair<llvm::StringRef, llvm::StringRef> p =3D rest.split(Separator=
s);
-
-    if (p.first.size() !=3D 0 || KeepEmpty)
-      A.push_back(p.first);
-    rest =3D p.second;
-  }
-  // If we have a tail left, add it.
-  if (rest.data() !=3D NULL && (rest.size() !=3D 0 || KeepEmpty))
-    A.push_back(rest);
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/StringMa=
p.cpp
--- a/head/contrib/llvm/lib/Support/StringMap.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/StringMap.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -39,11 +39,13 @@
   NumItems =3D 0;
   NumTombstones =3D 0;
  =20
-  TheTable =3D (ItemBucket*)calloc(NumBuckets+1, sizeof(ItemBucket));
- =20
+  TheTable =3D (StringMapEntryBase **)calloc(NumBuckets+1,
+                                           sizeof(StringMapEntryBase **) +
+                                           sizeof(unsigned));
+
   // Allocate one extra bucket, set it to look filled so the iterators sto=
p at
   // end.
-  TheTable[NumBuckets].Item =3D (StringMapEntryBase*)2;
+  TheTable[NumBuckets] =3D (StringMapEntryBase*)2;
 }
=20
=20
@@ -60,29 +62,29 @@
   }
   unsigned FullHashValue =3D HashString(Name);
   unsigned BucketNo =3D FullHashValue & (HTSize-1);
- =20
+  unsigned *HashTable =3D (unsigned *)(TheTable + NumBuckets + 1);
+
   unsigned ProbeAmt =3D 1;
   int FirstTombstone =3D -1;
   while (1) {
-    ItemBucket &Bucket =3D TheTable[BucketNo];
-    StringMapEntryBase *BucketItem =3D Bucket.Item;
+    StringMapEntryBase *BucketItem =3D TheTable[BucketNo];
     // If we found an empty bucket, this key isn't in the table yet, retur=
n it.
     if (BucketItem =3D=3D 0) {
       // If we found a tombstone, we want to reuse the tombstone instead o=
f an
       // empty bucket.  This reduces probing.
       if (FirstTombstone !=3D -1) {
-        TheTable[FirstTombstone].FullHashValue =3D FullHashValue;
+        HashTable[FirstTombstone] =3D FullHashValue;
         return FirstTombstone;
       }
      =20
-      Bucket.FullHashValue =3D FullHashValue;
+      HashTable[BucketNo] =3D FullHashValue;
       return BucketNo;
     }
    =20
     if (BucketItem =3D=3D getTombstoneVal()) {
       // Skip over tombstones.  However, remember the first one we see.
       if (FirstTombstone =3D=3D -1) FirstTombstone =3D BucketNo;
-    } else if (Bucket.FullHashValue =3D=3D FullHashValue) {
+    } else if (HashTable[BucketNo] =3D=3D FullHashValue) {
       // If the full hash value matches, check deeply for a match.  The co=
mmon
       // case here is that we are only looking at the buckets (for item in=
fo
       // being non-null and for the full hash value) not at the items.  Th=
is
@@ -115,18 +117,18 @@
   if (HTSize =3D=3D 0) return -1;  // Really empty table?
   unsigned FullHashValue =3D HashString(Key);
   unsigned BucketNo =3D FullHashValue & (HTSize-1);
- =20
+  unsigned *HashTable =3D (unsigned *)(TheTable + NumBuckets + 1);
+
   unsigned ProbeAmt =3D 1;
   while (1) {
-    ItemBucket &Bucket =3D TheTable[BucketNo];
-    StringMapEntryBase *BucketItem =3D Bucket.Item;
+    StringMapEntryBase *BucketItem =3D TheTable[BucketNo];
     // If we found an empty bucket, this key isn't in the table yet, retur=
n.
     if (BucketItem =3D=3D 0)
       return -1;
    =20
     if (BucketItem =3D=3D getTombstoneVal()) {
       // Ignore tombstones.
-    } else if (Bucket.FullHashValue =3D=3D FullHashValue) {
+    } else if (HashTable[BucketNo] =3D=3D FullHashValue) {
       // If the full hash value matches, check deeply for a match.  The co=
mmon
       // case here is that we are only looking at the buckets (for item in=
fo
       // being non-null and for the full hash value) not at the items.  Th=
is
@@ -165,8 +167,8 @@
   int Bucket =3D FindKey(Key);
   if (Bucket =3D=3D -1) return 0;
  =20
-  StringMapEntryBase *Result =3D TheTable[Bucket].Item;
-  TheTable[Bucket].Item =3D getTombstoneVal();
+  StringMapEntryBase *Result =3D TheTable[Bucket];
+  TheTable[Bucket] =3D getTombstoneVal();
   --NumItems;
   ++NumTombstones;
   assert(NumItems + NumTombstones <=3D NumBuckets);
@@ -180,6 +182,7 @@
 /// the appropriate mod-of-hashtable-size.
 void StringMapImpl::RehashTable() {
   unsigned NewSize;
+  unsigned *HashTable =3D (unsigned *)(TheTable + NumBuckets + 1);
=20
   // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
   // the buckets are empty (meaning that many are filled with tombstones),
@@ -194,19 +197,23 @@
=20
   // Allocate one extra bucket which will always be non-empty.  This allow=
s the
   // iterators to stop at end.
-  ItemBucket *NewTableArray =3D(ItemBucket*)calloc(NewSize+1, sizeof(ItemB=
ucket));
-  NewTableArray[NewSize].Item =3D (StringMapEntryBase*)2;
- =20
+  StringMapEntryBase **NewTableArray =3D
+    (StringMapEntryBase **)calloc(NewSize+1, sizeof(StringMapEntryBase *) +
+                                             sizeof(unsigned));
+  unsigned *NewHashArray =3D (unsigned *)(NewTableArray + NewSize + 1);
+  NewTableArray[NewSize] =3D (StringMapEntryBase*)2;
+
   // Rehash all the items into their new buckets.  Luckily :) we already h=
ave
   // the hash values available, so we don't have to rehash any strings.
-  for (ItemBucket *IB =3D TheTable, *E =3D TheTable+NumBuckets; IB !=3D E;=
 ++IB) {
-    if (IB->Item && IB->Item !=3D getTombstoneVal()) {
+  for (unsigned I =3D 0, E =3D NumBuckets; I !=3D E; ++I) {
+    StringMapEntryBase *Bucket =3D TheTable[I];
+    if (Bucket && Bucket !=3D getTombstoneVal()) {
       // Fast case, bucket available.
-      unsigned FullHash =3D IB->FullHashValue;
+      unsigned FullHash =3D HashTable[I];
       unsigned NewBucket =3D FullHash & (NewSize-1);
-      if (NewTableArray[NewBucket].Item =3D=3D 0) {
-        NewTableArray[FullHash & (NewSize-1)].Item =3D IB->Item;
-        NewTableArray[FullHash & (NewSize-1)].FullHashValue =3D FullHash;
+      if (NewTableArray[NewBucket] =3D=3D 0) {
+        NewTableArray[FullHash & (NewSize-1)] =3D Bucket;
+        NewHashArray[FullHash & (NewSize-1)] =3D FullHash;
         continue;
       }
      =20
@@ -214,11 +221,11 @@
       unsigned ProbeSize =3D 1;
       do {
         NewBucket =3D (NewBucket + ProbeSize++) & (NewSize-1);
-      } while (NewTableArray[NewBucket].Item);
+      } while (NewTableArray[NewBucket]);
      =20
       // Finally found a slot.  Fill it in.
-      NewTableArray[NewBucket].Item =3D IB->Item;
-      NewTableArray[NewBucket].FullHashValue =3D FullHash;
+      NewTableArray[NewBucket] =3D Bucket;
+      NewHashArray[NewBucket] =3D FullHash;
     }
   }
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/StringRe=
f.cpp
--- a/head/contrib/llvm/lib/Support/StringRef.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/StringRef.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -10,6 +10,8 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/edit_distance.h"
 #include <bitset>
=20
 using namespace llvm;
@@ -25,6 +27,12 @@
   return x;
 }
=20
+static char ascii_toupper(char x) {
+  if (x >=3D 'a' && x <=3D 'z')
+    return x - 'a' + 'A';
+  return x;
+}
+
 static bool ascii_isdigit(char x) {
   return x >=3D '0' && x <=3D '9';
 }
@@ -78,56 +86,29 @@
 unsigned StringRef::edit_distance(llvm::StringRef Other,
                                   bool AllowReplacements,
                                   unsigned MaxEditDistance) {
-  // The algorithm implemented below is the "classic"
-  // dynamic-programming algorithm for computing the Levenshtein
-  // distance, which is described here:
-  //
-  //   http://en.wikipedia.org/wiki/Levenshtein_distance
-  //
-  // Although the algorithm is typically described using an m x n
-  // array, only two rows are used at a time, so this implemenation
-  // just keeps two separate vectors for those two rows.
-  size_type m =3D size();
-  size_type n =3D Other.size();
+  return llvm::ComputeEditDistance(
+      llvm::ArrayRef<char>(data(), size()),
+      llvm::ArrayRef<char>(Other.data(), Other.size()),
+      AllowReplacements, MaxEditDistance);
+}
=20
-  const unsigned SmallBufferSize =3D 64;
-  unsigned SmallBuffer[SmallBufferSize];
-  llvm::OwningArrayPtr<unsigned> Allocated;
-  unsigned *previous =3D SmallBuffer;
-  if (2*(n + 1) > SmallBufferSize) {
-    previous =3D new unsigned [2*(n+1)];
-    Allocated.reset(previous);
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// String Operations
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+std::string StringRef::lower() const {
+  std::string Result(size(), char());
+  for (size_type i =3D 0, e =3D size(); i !=3D e; ++i) {
+    Result[i] =3D ascii_tolower(Data[i]);
   }
-  unsigned *current =3D previous + (n + 1);
+  return Result;
+}
=20
-  for (unsigned i =3D 0; i <=3D n; ++i)
-    previous[i] =3D i;
-
-  for (size_type y =3D 1; y <=3D m; ++y) {
-    current[0] =3D y;
-    unsigned BestThisRow =3D current[0];
-
-    for (size_type x =3D 1; x <=3D n; ++x) {
-      if (AllowReplacements) {
-        current[x] =3D min(previous[x-1] + ((*this)[y-1] =3D=3D Other[x-1]=
? 0u:1u),
-                         min(current[x-1], previous[x])+1);
-      }
-      else {
-        if ((*this)[y-1] =3D=3D Other[x-1]) current[x] =3D previous[x-1];
-        else current[x] =3D min(current[x-1], previous[x]) + 1;
-      }
-      BestThisRow =3D min(BestThisRow, current[x]);
-    }
-
-    if (MaxEditDistance && BestThisRow > MaxEditDistance)
-      return MaxEditDistance + 1;
-
-    unsigned *tmp =3D current;
-    current =3D previous;
-    previous =3D tmp;
+std::string StringRef::upper() const {
+  std::string Result(size(), char());
+  for (size_type i =3D 0, e =3D size(); i !=3D e; ++i) {
+    Result[i] =3D ascii_toupper(Data[i]);
   }
-
-  unsigned Result =3D previous[n];
   return Result;
 }
=20
@@ -144,9 +125,35 @@
   size_t N =3D Str.size();
   if (N > Length)
     return npos;
-  for (size_t e =3D Length - N + 1, i =3D min(From, e); i !=3D e; ++i)
-    if (substr(i, N).equals(Str))
-      return i;
+
+  // For short haystacks or unsupported needles fall back to the naive alg=
orithm
+  if (Length < 16 || N > 255 || N =3D=3D 0) {
+    for (size_t e =3D Length - N + 1, i =3D min(From, e); i !=3D e; ++i)
+      if (substr(i, N).equals(Str))
+        return i;
+    return npos;
+  }
+
+  if (From >=3D Length)
+    return npos;
+
+  // Build the bad char heuristic table, with uint8_t to reduce cache thra=
shing.
+  uint8_t BadCharSkip[256];
+  std::memset(BadCharSkip, N, 256);
+  for (unsigned i =3D 0; i !=3D N-1; ++i)
+    BadCharSkip[(uint8_t)Str[i]] =3D N-1-i;
+
+  unsigned Len =3D Length-From, Pos =3D From;
+  while (Len >=3D N) {
+    if (substr(Pos, N).equals(Str)) // See if this is the correct substrin=
g.
+      return Pos;
+
+    // Otherwise skip the appropriate number of bytes.
+    uint8_t Skip =3D BadCharSkip[(uint8_t)(*this)[Pos+N-1]];
+    Len -=3D Skip;
+    Pos +=3D Skip;
+  }
+
   return npos;
 }
=20
@@ -223,6 +230,27 @@
   return npos;
 }
=20
+void StringRef::split(SmallVectorImpl<StringRef> &A,
+                      StringRef Separators, int MaxSplit,
+                      bool KeepEmpty) const {
+  StringRef rest =3D *this;
+
+  // rest.data() is used to distinguish cases like "a," that splits into
+  // "a" + "" and "a" that splits into "a" + 0.
+  for (int splits =3D 0;
+       rest.data() !=3D NULL && (MaxSplit < 0 || splits < MaxSplit);
+       ++splits) {
+    std::pair<StringRef, StringRef> p =3D rest.split(Separators);
+
+    if (KeepEmpty || p.first.size() !=3D 0)
+      A.push_back(p.first);
+    rest =3D p.second;
+  }
+  // If we have a tail left, add it.
+  if (rest.data() !=3D NULL && (rest.size() !=3D 0 || KeepEmpty))
+    A.push_back(rest);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Helpful Algorithms
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -257,8 +285,8 @@
=20
 /// GetAsUnsignedInteger - Workhorse method that converts a integer charac=
ter
 /// sequence of radix up to 36 to an unsigned long long value.
-static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
-                                 unsigned long long &Result) {
+bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
+                                unsigned long long &Result) {
   // Autosense radix if not specified.
   if (Radix =3D=3D 0)
     Radix =3D GetAutoSenseRadix(Str);
@@ -298,17 +326,13 @@
   return false;
 }
=20
-bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) c=
onst {
-  return GetAsUnsignedInteger(*this, Radix, Result);
-}
-
-
-bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
+bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
+                              long long &Result) {
   unsigned long long ULLVal;
=20
   // Handle positive strings first.
-  if (empty() || front() !=3D '-') {
-    if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
+  if (Str.empty() || Str.front() !=3D '-') {
+    if (getAsUnsignedInteger(Str, Radix, ULLVal) ||
         // Check for value so large it overflows a signed value.
         (long long)ULLVal < 0)
       return true;
@@ -317,7 +341,7 @@
   }
=20
   // Get the positive part of the value.
-  if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
+  if (getAsUnsignedInteger(Str.substr(1), Radix, ULLVal) ||
       // Reject values so large they'd overflow as negative signed, but al=
low
       // "-0".  This negates the unsigned so that the negative isn't undef=
ined
       // on signed overflow.
@@ -328,24 +352,6 @@
   return false;
 }
=20
-bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
-  long long Val;
-  if (getAsInteger(Radix, Val) ||
-      (int)Val !=3D Val)
-    return true;
-  Result =3D Val;
-  return false;
-}
-
-bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
-  unsigned long long Val;
-  if (getAsInteger(Radix, Val) ||
-      (unsigned)Val !=3D Val)
-    return true;
-  Result =3D Val;
-  return false;
-}
-
 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
   StringRef Str =3D *this;
=20
@@ -420,3 +426,9 @@
=20
   return false;
 }
+
+
+// Implementation of StringRef hashing.
+hash_code llvm::hash_value(StringRef S) {
+  return hash_combine_range(S.begin(), S.end());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/TargetRe=
gistry.cpp
--- a/head/contrib/llvm/lib/Support/TargetRegistry.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Support/TargetRegistry.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -84,7 +84,7 @@
 }
=20
 const Target *TargetRegistry::getClosestTargetForJIT(std::string &Error) {
-  const Target *TheTarget =3D lookupTarget(sys::getHostTriple(), Error);
+  const Target *TheTarget =3D lookupTarget(sys::getDefaultTargetTriple(), =
Error);
=20
   if (TheTarget && !TheTarget->hasJIT()) {
     Error =3D "No JIT compatible target available for this host";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/ThreadLo=
cal.cpp
--- a/head/contrib/llvm/lib/Support/ThreadLocal.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Support/ThreadLocal.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -19,7 +19,7 @@
 //=3D=3D=3D          independent code.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#if !defined(ENABLE_THREADS) || ENABLE_THREADS =3D=3D 0
+#if !defined(LLVM_ENABLE_THREADS) || LLVM_ENABLE_THREADS =3D=3D 0
 // Define all methods as no-ops if threading is explicitly disabled
 namespace llvm {
 using namespace sys;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Threadin=
g.cpp
--- a/head/contrib/llvm/lib/Support/Threading.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/Threading.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -24,7 +24,7 @@
 static sys::Mutex* global_lock =3D 0;
=20
 bool llvm::llvm_start_multithreaded() {
-#if ENABLE_THREADS !=3D 0
+#if LLVM_ENABLE_THREADS !=3D 0
   assert(!multithreaded_mode && "Already multithreaded!");
   multithreaded_mode =3D true;
   global_lock =3D new sys::Mutex(true);
@@ -39,7 +39,7 @@
 }
=20
 void llvm::llvm_stop_multithreaded() {
-#if ENABLE_THREADS !=3D 0
+#if LLVM_ENABLE_THREADS !=3D 0
   assert(multithreaded_mode && "Not currently multithreaded!");
=20
   // We fence here to insure that all threaded operations are complete BEF=
ORE we
@@ -63,7 +63,7 @@
   if (multithreaded_mode) global_lock->release();
 }
=20
-#if ENABLE_THREADS !=3D 0 && defined(HAVE_PTHREAD_H)
+#if LLVM_ENABLE_THREADS !=3D 0 && defined(HAVE_PTHREAD_H)
 #include <pthread.h>
=20
 struct ThreadInfo {
@@ -102,7 +102,7 @@
  error:
   ::pthread_attr_destroy(&Attr);
 }
-#elif ENABLE_THREADS!=3D0 && defined(LLVM_ON_WIN32)
+#elif LLVM_ENABLE_THREADS!=3D0 && defined(LLVM_ON_WIN32)
 #include "Windows/Windows.h"
 #include <process.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Timer.cpp
--- a/head/contrib/llvm/lib/Support/Timer.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Timer.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -168,10 +168,8 @@
 static void printVal(double Val, double Total, raw_ostream &OS) {
   if (Total < 1e-7)   // Avoid dividing by zero.
     OS << "        -----     ";
-  else {
-    OS << "  " << format("%7.4f", Val) << " (";
-    OS << format("%5.1f", Val*100/Total) << "%)";
-  }
+  else
+    OS << format("  %7.4f (%5.1f%%)", Val, Val*100/Total);
 }
=20
 void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
@@ -186,7 +184,7 @@
   OS << "  ";
  =20
   if (Total.getMemUsed())
-    OS << format("%9lld", (long long)getMemUsed()) << "  ";
+    OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
 }
=20
=20
@@ -332,11 +330,9 @@
   // If this is not an collection of ungrouped times, print the total time.
   // Ungrouped timers don't really make sense to add up.  We still print t=
he
   // TOTAL line to make the percentages make sense.
-  if (this !=3D DefaultTimerGroup) {
-    OS << "  Total Execution Time: ";
-    OS << format("%5.4f", Total.getProcessTime()) << " seconds (";
-    OS << format("%5.4f", Total.getWallTime()) << " wall clock)\n";
-  }
+  if (this !=3D DefaultTimerGroup)
+    OS << format("  Total Execution Time: %5.4f seconds (%5.4f wall clock)=
\n",
+                 Total.getProcessTime(), Total.getWallTime());
   OS << '\n';
  =20
   if (Total.getUserTime())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Triple.c=
pp
--- a/head/contrib/llvm/lib/Support/Triple.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Support/Triple.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -9,19 +9,19 @@
=20
 #include "llvm/ADT/Triple.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cstring>
 using namespace llvm;
=20
 const char *Triple::getArchTypeName(ArchType Kind) {
   switch (Kind) {
-  case InvalidArch: return "<invalid>";
   case UnknownArch: return "unknown";
=20
-  case alpha:   return "alpha";
   case arm:     return "arm";
-  case bfin:    return "bfin";
   case cellspu: return "cellspu";
+  case hexagon: return "hexagon";
   case mips:    return "mips";
   case mipsel:  return "mipsel";
   case mips64:  return "mips64";
@@ -29,9 +29,9 @@
   case msp430:  return "msp430";
   case ppc64:   return "powerpc64";
   case ppc:     return "powerpc";
+  case r600:    return "r600";
   case sparc:   return "sparc";
   case sparcv9: return "sparcv9";
-  case systemz: return "s390x";
   case tce:     return "tce";
   case thumb:   return "thumb";
   case x86:     return "i386";
@@ -44,7 +44,7 @@
   case amdil:   return "amdil";
   }
=20
-  return "<invalid>";
+  llvm_unreachable("Invalid ArchType!");
 }
=20
 const char *Triple::getArchTypePrefix(ArchType Kind) {
@@ -52,13 +52,9 @@
   default:
     return 0;
=20
-  case alpha:   return "alpha";
-
   case arm:
   case thumb:   return "arm";
=20
-  case bfin:    return "bfin";
-
   case cellspu: return "spu";
=20
   case ppc64:
@@ -66,6 +62,10 @@
=20
   case mblaze:  return "mblaze";
=20
+  case hexagon:   return "hexagon";
+
+  case r600:    return "r600";
+
   case sparcv9:
   case sparc:   return "sparc";
=20
@@ -88,9 +88,11 @@
   case Apple: return "apple";
   case PC: return "pc";
   case SCEI: return "scei";
+  case BGP: return "bgp";
+  case BGQ: return "bgq";
   }
=20
-  return "<invalid>";
+  llvm_unreachable("Invalid VendorType!");
 }
=20
 const char *Triple::getOSTypeName(OSType Kind) {
@@ -110,83 +112,59 @@
   case MinGW32: return "mingw32";
   case NetBSD: return "netbsd";
   case OpenBSD: return "openbsd";
-  case Psp: return "psp";
   case Solaris: return "solaris";
   case Win32: return "win32";
   case Haiku: return "haiku";
   case Minix: return "minix";
   case RTEMS: return "rtems";
   case NativeClient: return "nacl";
+  case CNK: return "cnk";
   }
=20
-  return "<invalid>";
+  llvm_unreachable("Invalid OSType");
 }
=20
 const char *Triple::getEnvironmentTypeName(EnvironmentType Kind) {
   switch (Kind) {
   case UnknownEnvironment: return "unknown";
   case GNU: return "gnu";
+  case GNUEABIHF: return "gnueabihf";
   case GNUEABI: return "gnueabi";
   case EABI: return "eabi";
   case MachO: return "macho";
+  case ANDROIDEABI: return "androideabi";
   }
=20
-  return "<invalid>";
+  llvm_unreachable("Invalid EnvironmentType!");
 }
=20
 Triple::ArchType Triple::getArchTypeForLLVMName(StringRef Name) {
-  if (Name =3D=3D "alpha")
-    return alpha;
-  if (Name =3D=3D "arm")
-    return arm;
-  if (Name =3D=3D "bfin")
-    return bfin;
-  if (Name =3D=3D "cellspu")
-    return cellspu;
-  if (Name =3D=3D "mips")
-    return mips;
-  if (Name =3D=3D "mipsel")
-    return mipsel;
-  if (Name =3D=3D "mips64")
-    return mips64;
-  if (Name =3D=3D "mips64el")
-    return mips64el;
-  if (Name =3D=3D "msp430")
-    return msp430;
-  if (Name =3D=3D "ppc64")
-    return ppc64;
-  if (Name =3D=3D "ppc32")
-    return ppc;
-  if (Name =3D=3D "ppc")
-    return ppc;
-  if (Name =3D=3D "mblaze")
-    return mblaze;
-  if (Name =3D=3D "sparc")
-    return sparc;
-  if (Name =3D=3D "sparcv9")
-    return sparcv9;
-  if (Name =3D=3D "systemz")
-    return systemz;
-  if (Name =3D=3D "tce")
-    return tce;
-  if (Name =3D=3D "thumb")
-    return thumb;
-  if (Name =3D=3D "x86")
-    return x86;
-  if (Name =3D=3D "x86-64")
-    return x86_64;
-  if (Name =3D=3D "xcore")
-    return xcore;
-  if (Name =3D=3D "ptx32")
-    return ptx32;
-  if (Name =3D=3D "ptx64")
-    return ptx64;
-  if (Name =3D=3D "le32")
-    return le32;
-  if (Name =3D=3D "amdil")
-      return amdil;
-
-  return UnknownArch;
+  return StringSwitch<Triple::ArchType>(Name)
+    .Case("arm", arm)
+    .Case("cellspu", cellspu)
+    .Case("mips", mips)
+    .Case("mipsel", mipsel)
+    .Case("mips64", mips64)
+    .Case("mips64el", mips64el)
+    .Case("msp430", msp430)
+    .Case("ppc64", ppc64)
+    .Case("ppc32", ppc)
+    .Case("ppc", ppc)
+    .Case("mblaze", mblaze)
+    .Case("r600", r600)
+    .Case("hexagon", hexagon)
+    .Case("sparc", sparc)
+    .Case("sparcv9", sparcv9)
+    .Case("tce", tce)
+    .Case("thumb", thumb)
+    .Case("x86", x86)
+    .Case("x86-64", x86_64)
+    .Case("xcore", xcore)
+    .Case("ptx32", ptx32)
+    .Case("ptx64", ptx64)
+    .Case("le32", le32)
+    .Case("amdil", amdil)
+    .Default(UnknownArch);
 }
=20
 Triple::ArchType Triple::getArchTypeForDarwinArchName(StringRef Str) {
@@ -202,36 +180,22 @@
   // This code must be kept in sync with Clang's Darwin specific argument
   // translation.
=20
-  if (Str =3D=3D "ppc" || Str =3D=3D "ppc601" || Str =3D=3D "ppc603" || St=
r =3D=3D "ppc604" ||
-      Str =3D=3D "ppc604e" || Str =3D=3D "ppc750" || Str =3D=3D "ppc7400" =
||
-      Str =3D=3D "ppc7450" || Str =3D=3D "ppc970")
-    return Triple::ppc;
-
-  if (Str =3D=3D "ppc64")
-    return Triple::ppc64;
-
-  if (Str =3D=3D "i386" || Str =3D=3D "i486" || Str =3D=3D "i486SX" || Str=
 =3D=3D "pentium" ||
-      Str =3D=3D "i586" || Str =3D=3D "pentpro" || Str =3D=3D "i686" || St=
r =3D=3D "pentIIm3" ||
-      Str =3D=3D "pentIIm5" || Str =3D=3D "pentium4")
-    return Triple::x86;
-
-  if (Str =3D=3D "x86_64")
-    return Triple::x86_64;
-
-  // This is derived from the driver driver.
-  if (Str =3D=3D "arm" || Str =3D=3D "armv4t" || Str =3D=3D "armv5" || Str=
 =3D=3D "xscale" ||
-      Str =3D=3D "armv6" || Str =3D=3D "armv7" || Str =3D=3D "armv7f" || S=
tr =3D=3D "armv7k" ||
-      Str =3D=3D "armv7s")
-    return Triple::arm;
-
-  if (Str =3D=3D "ptx32")
-    return Triple::ptx32;
-  if (Str =3D=3D "ptx64")
-    return Triple::ptx64;
-  if (Str =3D=3D "amdil")
-      return Triple::amdil;
-
-  return Triple::UnknownArch;
+  return StringSwitch<ArchType>(Str)
+    .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", Triple::ppc)
+    .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", Triple::ppc)
+    .Case("ppc64", Triple::ppc64)
+    .Cases("i386", "i486", "i486SX", "i586", "i686", Triple::x86)
+    .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
+           Triple::x86)
+    .Case("x86_64", Triple::x86_64)
+    // This is derived from the driver driver.
+    .Cases("arm", "armv4t", "armv5", "armv6", Triple::arm)
+    .Cases("armv7", "armv7f", "armv7k", "armv7s", "xscale", Triple::arm)
+    .Case("r600", Triple::r600)
+    .Case("ptx32", Triple::ptx32)
+    .Case("ptx64", Triple::ptx64)
+    .Case("amdil", Triple::amdil)
+    .Default(Triple::UnknownArch);
 }
=20
 // Returns architecture name that is understood by the target assembler.
@@ -239,188 +203,150 @@
   if (!isOSDarwin() && getVendor() !=3D Triple::Apple)
     return NULL;
=20
-  StringRef Str =3D getArchName();
-  if (Str =3D=3D "i386")
-    return "i386";
-  if (Str =3D=3D "x86_64")
-    return "x86_64";
-  if (Str =3D=3D "powerpc")
-    return "ppc";
-  if (Str =3D=3D "powerpc64")
-    return "ppc64";
-  if (Str =3D=3D "mblaze" || Str =3D=3D "microblaze")
-    return "mblaze";
-  if (Str =3D=3D "arm")
-    return "arm";
-  if (Str =3D=3D "armv4t" || Str =3D=3D "thumbv4t")
-    return "armv4t";
-  if (Str =3D=3D "armv5" || Str =3D=3D "armv5e" || Str =3D=3D "thumbv5"
-      || Str =3D=3D "thumbv5e")
-    return "armv5";
-  if (Str =3D=3D "armv6" || Str =3D=3D "thumbv6")
-    return "armv6";
-  if (Str =3D=3D "armv7" || Str =3D=3D "thumbv7")
-    return "armv7";
-  if (Str =3D=3D "ptx32")
-    return "ptx32";
-  if (Str =3D=3D "ptx64")
-    return "ptx64";
-  if (Str =3D=3D "le32")
-    return "le32";
-  if (Str =3D=3D "amdil")
-      return "amdil";
-  return NULL;
+  return StringSwitch<const char*>(getArchName())
+    .Case("i386", "i386")
+    .Case("x86_64", "x86_64")
+    .Case("powerpc", "ppc")
+    .Case("powerpc64", "ppc64")
+    .Cases("mblaze", "microblaze", "mblaze")
+    .Case("arm", "arm")
+    .Cases("armv4t", "thumbv4t", "armv4t")
+    .Cases("armv5", "armv5e", "thumbv5", "thumbv5e", "armv5")
+    .Cases("armv6", "thumbv6", "armv6")
+    .Cases("armv7", "thumbv7", "armv7")
+    .Case("r600", "r600")
+    .Case("ptx32", "ptx32")
+    .Case("ptx64", "ptx64")
+    .Case("le32", "le32")
+    .Case("amdil", "amdil")
+    .Default(NULL);
 }
=20
-//
-
-Triple::ArchType Triple::ParseArch(StringRef ArchName) {
-  if (ArchName.size() =3D=3D 4 && ArchName[0] =3D=3D 'i' &&
-      ArchName[2] =3D=3D '8' && ArchName[3] =3D=3D '6' &&
-      ArchName[1] - '3' < 6) // i[3-9]86
-    return x86;
-  else if (ArchName =3D=3D "amd64" || ArchName =3D=3D "x86_64")
-    return x86_64;
-  else if (ArchName =3D=3D "bfin")
-    return bfin;
-  else if (ArchName =3D=3D "powerpc")
-    return ppc;
-  else if ((ArchName =3D=3D "powerpc64") || (ArchName =3D=3D "ppu"))
-    return ppc64;
-  else if (ArchName =3D=3D "mblaze")
-    return mblaze;
-  else if (ArchName =3D=3D "arm" ||
-           ArchName.startswith("armv") ||
-           ArchName =3D=3D "xscale")
-    return arm;
-  else if (ArchName =3D=3D "thumb" ||
-           ArchName.startswith("thumbv"))
-    return thumb;
-  else if (ArchName.startswith("alpha"))
-    return alpha;
-  else if (ArchName =3D=3D "spu" || ArchName =3D=3D "cellspu")
-    return cellspu;
-  else if (ArchName =3D=3D "msp430")
-    return msp430;
-  else if (ArchName =3D=3D "mips" || ArchName =3D=3D "mipseb" ||
-           ArchName =3D=3D "mipsallegrex")
-    return mips;
-  else if (ArchName =3D=3D "mipsel" || ArchName =3D=3D "mipsallegrexel" ||
-           ArchName =3D=3D "psp")
-    return mipsel;
-  else if (ArchName =3D=3D "mips64" || ArchName =3D=3D "mips64eb")
-    return mips64;
-  else if (ArchName =3D=3D "mips64el")
-    return mips64el;
-  else if (ArchName =3D=3D "sparc")
-    return sparc;
-  else if (ArchName =3D=3D "sparcv9")
-    return sparcv9;
-  else if (ArchName =3D=3D "s390x")
-    return systemz;
-  else if (ArchName =3D=3D "tce")
-    return tce;
-  else if (ArchName =3D=3D "xcore")
-    return xcore;
-  else if (ArchName =3D=3D "ptx32")
-    return ptx32;
-  else if (ArchName =3D=3D "ptx64")
-    return ptx64;
-  else if (ArchName =3D=3D "le32")
-    return le32;
-  else if (ArchName =3D=3D "amdil")
-      return amdil;
-  else
-    return UnknownArch;
+static Triple::ArchType parseArch(StringRef ArchName) {
+  return StringSwitch<Triple::ArchType>(ArchName)
+    .Cases("i386", "i486", "i586", "i686", Triple::x86)
+    // FIXME: Do we need to support these?
+    .Cases("i786", "i886", "i986", Triple::x86)
+    .Cases("amd64", "x86_64", Triple::x86_64)
+    .Case("powerpc", Triple::ppc)
+    .Cases("powerpc64", "ppu", Triple::ppc64)
+    .Case("mblaze", Triple::mblaze)
+    .Cases("arm", "xscale", Triple::arm)
+    // FIXME: It would be good to replace these with explicit names for al=
l the
+    // various suffixes supported.
+    .StartsWith("armv", Triple::arm)
+    .Case("thumb", Triple::thumb)
+    .StartsWith("thumbv", Triple::thumb)
+    .Cases("spu", "cellspu", Triple::cellspu)
+    .Case("msp430", Triple::msp430)
+    .Cases("mips", "mipseb", "mipsallegrex", Triple::mips)
+    .Cases("mipsel", "mipsallegrexel", Triple::mipsel)
+    .Cases("mips64", "mips64eb", Triple::mips64)
+    .Case("mips64el", Triple::mips64el)
+    .Case("r600", Triple::r600)
+    .Case("hexagon", Triple::hexagon)
+    .Case("sparc", Triple::sparc)
+    .Case("sparcv9", Triple::sparcv9)
+    .Case("tce", Triple::tce)
+    .Case("xcore", Triple::xcore)
+    .Case("ptx32", Triple::ptx32)
+    .Case("ptx64", Triple::ptx64)
+    .Case("le32", Triple::le32)
+    .Case("amdil", Triple::amdil)
+    .Default(Triple::UnknownArch);
 }
=20
-Triple::VendorType Triple::ParseVendor(StringRef VendorName) {
-  if (VendorName =3D=3D "apple")
-    return Apple;
-  else if (VendorName =3D=3D "pc")
-    return PC;
-  else if (VendorName =3D=3D "scei")
-    return SCEI;
-  else
-    return UnknownVendor;
+static Triple::VendorType parseVendor(StringRef VendorName) {
+  return StringSwitch<Triple::VendorType>(VendorName)
+    .Case("apple", Triple::Apple)
+    .Case("pc", Triple::PC)
+    .Case("scei", Triple::SCEI)
+    .Case("bgp", Triple::BGP)
+    .Case("bgq", Triple::BGQ)
+    .Default(Triple::UnknownVendor);
 }
=20
-Triple::OSType Triple::ParseOS(StringRef OSName) {
-  if (OSName.startswith("auroraux"))
-    return AuroraUX;
-  else if (OSName.startswith("cygwin"))
-    return Cygwin;
-  else if (OSName.startswith("darwin"))
-    return Darwin;
-  else if (OSName.startswith("dragonfly"))
-    return DragonFly;
-  else if (OSName.startswith("freebsd"))
-    return FreeBSD;
-  else if (OSName.startswith("ios"))
-    return IOS;
-  else if (OSName.startswith("kfreebsd"))
-    return KFreeBSD;
-  else if (OSName.startswith("linux"))
-    return Linux;
-  else if (OSName.startswith("lv2"))
-    return Lv2;
-  else if (OSName.startswith("macosx"))
-    return MacOSX;
-  else if (OSName.startswith("mingw32"))
-    return MinGW32;
-  else if (OSName.startswith("netbsd"))
-    return NetBSD;
-  else if (OSName.startswith("openbsd"))
-    return OpenBSD;
-  else if (OSName.startswith("psp"))
-    return Psp;
-  else if (OSName.startswith("solaris"))
-    return Solaris;
-  else if (OSName.startswith("win32"))
-    return Win32;
-  else if (OSName.startswith("haiku"))
-    return Haiku;
-  else if (OSName.startswith("minix"))
-    return Minix;
-  else if (OSName.startswith("rtems"))
-    return RTEMS;
-  else if (OSName.startswith("nacl"))
-    return NativeClient;
-  else
-    return UnknownOS;
+static Triple::OSType parseOS(StringRef OSName) {
+  return StringSwitch<Triple::OSType>(OSName)
+    .StartsWith("auroraux", Triple::AuroraUX)
+    .StartsWith("cygwin", Triple::Cygwin)
+    .StartsWith("darwin", Triple::Darwin)
+    .StartsWith("dragonfly", Triple::DragonFly)
+    .StartsWith("freebsd", Triple::FreeBSD)
+    .StartsWith("ios", Triple::IOS)
+    .StartsWith("kfreebsd", Triple::KFreeBSD)
+    .StartsWith("linux", Triple::Linux)
+    .StartsWith("lv2", Triple::Lv2)
+    .StartsWith("macosx", Triple::MacOSX)
+    .StartsWith("mingw32", Triple::MinGW32)
+    .StartsWith("netbsd", Triple::NetBSD)
+    .StartsWith("openbsd", Triple::OpenBSD)
+    .StartsWith("solaris", Triple::Solaris)
+    .StartsWith("win32", Triple::Win32)
+    .StartsWith("haiku", Triple::Haiku)
+    .StartsWith("minix", Triple::Minix)
+    .StartsWith("rtems", Triple::RTEMS)
+    .StartsWith("nacl", Triple::NativeClient)
+    .StartsWith("cnk", Triple::CNK)
+    .Default(Triple::UnknownOS);
 }
=20
-Triple::EnvironmentType Triple::ParseEnvironment(StringRef EnvironmentName=
) {
-  if (EnvironmentName.startswith("eabi"))
-    return EABI;
-  else if (EnvironmentName.startswith("gnueabi"))
-    return GNUEABI;
-  else if (EnvironmentName.startswith("gnu"))
-    return GNU;
-  else if (EnvironmentName.startswith("macho"))
-    return MachO;
-  else
-    return UnknownEnvironment;
+static Triple::EnvironmentType parseEnvironment(StringRef EnvironmentName)=
 {
+  return StringSwitch<Triple::EnvironmentType>(EnvironmentName)
+    .StartsWith("eabi", Triple::EABI)
+    .StartsWith("gnueabihf", Triple::GNUEABIHF)
+    .StartsWith("gnueabi", Triple::GNUEABI)
+    .StartsWith("gnu", Triple::GNU)
+    .StartsWith("macho", Triple::MachO)
+    .StartsWith("androideabi", Triple::ANDROIDEABI)
+    .Default(Triple::UnknownEnvironment);
 }
=20
-void Triple::Parse() const {
-  assert(!isInitialized() && "Invalid parse call.");
+/// \brief Construct a triple from the string representation provided.
+///
+/// This stores the string representation and parses the various pieces in=
to
+/// enum members.
+Triple::Triple(const Twine &Str)
+    : Data(Str.str()),
+      Arch(parseArch(getArchName())),
+      Vendor(parseVendor(getVendorName())),
+      OS(parseOS(getOSName())),
+      Environment(parseEnvironment(getEnvironmentName())) {
+}
=20
-  Arch =3D ParseArch(getArchName());
-  Vendor =3D ParseVendor(getVendorName());
-  OS =3D ParseOS(getOSName());
-  Environment =3D ParseEnvironment(getEnvironmentName());
+/// \brief Construct a triple from string representations of the architect=
ure,
+/// vendor, and OS.
+///
+/// This joins each argument into a canonical string representation and pa=
rses
+/// them into enum members. It leaves the environment unknown and omits it=
 from
+/// the string representation.
+Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &=
OSStr)
+    : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr).str()),
+      Arch(parseArch(ArchStr.str())),
+      Vendor(parseVendor(VendorStr.str())),
+      OS(parseOS(OSStr.str())),
+      Environment() {
+}
=20
-  assert(isInitialized() && "Failed to initialize!");
+/// \brief Construct a triple from string representations of the architect=
ure,
+/// vendor, OS, and environment.
+///
+/// This joins each argument into a canonical string representation and pa=
rses
+/// them into enum members.
+Triple::Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &=
OSStr,
+               const Twine &EnvironmentStr)
+    : Data((ArchStr + Twine('-') + VendorStr + Twine('-') + OSStr + Twine(=
'-') +
+            EnvironmentStr).str()),
+      Arch(parseArch(ArchStr.str())),
+      Vendor(parseVendor(VendorStr.str())),
+      OS(parseOS(OSStr.str())),
+      Environment(parseEnvironment(EnvironmentStr.str())) {
 }
=20
 std::string Triple::normalize(StringRef Str) {
   // Parse into components.
   SmallVector<StringRef, 4> Components;
-  for (size_t First =3D 0, Last =3D 0; Last !=3D StringRef::npos; First =
=3D Last + 1) {
-    Last =3D Str.find('-', First);
-    Components.push_back(Str.slice(First, Last));
-  }
+  Str.split(Components, "-");
=20
   // If the first component corresponds to a known architecture, preferent=
ially
   // use it for the architecture.  If the second component corresponds to a
@@ -429,16 +355,16 @@
   // valid os.
   ArchType Arch =3D UnknownArch;
   if (Components.size() > 0)
-    Arch =3D ParseArch(Components[0]);
+    Arch =3D parseArch(Components[0]);
   VendorType Vendor =3D UnknownVendor;
   if (Components.size() > 1)
-    Vendor =3D ParseVendor(Components[1]);
+    Vendor =3D parseVendor(Components[1]);
   OSType OS =3D UnknownOS;
   if (Components.size() > 2)
-    OS =3D ParseOS(Components[2]);
+    OS =3D parseOS(Components[2]);
   EnvironmentType Environment =3D UnknownEnvironment;
   if (Components.size() > 3)
-    Environment =3D ParseEnvironment(Components[3]);
+    Environment =3D parseEnvironment(Components[3]);
=20
   // Note which components are already in their final position.  These wil=
l not
   // be moved.
@@ -464,22 +390,21 @@
       bool Valid =3D false;
       StringRef Comp =3D Components[Idx];
       switch (Pos) {
-      default:
-        assert(false && "unexpected component type!");
+      default: llvm_unreachable("unexpected component type!");
       case 0:
-        Arch =3D ParseArch(Comp);
+        Arch =3D parseArch(Comp);
         Valid =3D Arch !=3D UnknownArch;
         break;
       case 1:
-        Vendor =3D ParseVendor(Comp);
+        Vendor =3D parseVendor(Comp);
         Valid =3D Vendor !=3D UnknownVendor;
         break;
       case 2:
-        OS =3D ParseOS(Comp);
+        OS =3D parseOS(Comp);
         Valid =3D OS !=3D UnknownOS;
         break;
       case 3:
-        Environment =3D ParseEnvironment(Comp);
+        Environment =3D parseEnvironment(Comp);
         Valid =3D Environment !=3D UnknownEnvironment;
         break;
       }
@@ -500,7 +425,8 @@
         // components to the right.
         for (unsigned i =3D Pos; !CurrentComponent.empty(); ++i) {
           // Skip over any fixed components.
-          while (i < array_lengthof(Found) && Found[i]) ++i;
+          while (i < array_lengthof(Found) && Found[i])
+            ++i;
           // Place the component at the new position, getting the component
           // that was at this position - it will be moved right.
           std::swap(CurrentComponent, Components[i]);
@@ -528,7 +454,8 @@
             Components.push_back(CurrentComponent);
=20
           // Advance Idx to the component's new position.
-          while (++Idx < array_lengthof(Found) && Found[Idx]) {}
+          while (++Idx < array_lengthof(Found) && Found[Idx])
+            ;
         } while (Idx < Pos); // Add more until the final position is reach=
ed.
       }
       assert(Pos < Components.size() && Components[Pos] =3D=3D Comp &&
@@ -618,9 +545,47 @@
   }
 }
=20
+bool Triple::getMacOSXVersion(unsigned &Major, unsigned &Minor,
+                              unsigned &Micro) const {
+  getOSVersion(Major, Minor, Micro);
+
+  switch (getOS()) {
+  default: llvm_unreachable("unexpected OS for Darwin triple");
+  case Darwin:
+    // Default to darwin8, i.e., MacOSX 10.4.
+    if (Major =3D=3D 0)
+      Major =3D 8;
+    // Darwin version numbers are skewed from OS X versions.
+    if (Major < 4)
+      return false;
+    Micro =3D 0;
+    Minor =3D Major - 4;
+    Major =3D 10;
+    break;
+  case MacOSX:
+    // Default to 10.4.
+    if (Major =3D=3D 0) {
+      Major =3D 10;
+      Minor =3D 4;
+    }
+    if (Major !=3D 10)
+      return false;
+    break;
+  case IOS:
+    // Ignore the version from the triple.  This is only handled because t=
he
+    // the clang driver combines OS X and IOS support into a common Darwin
+    // toolchain that wants to know the OS X version number even when targ=
eting
+    // IOS.
+    Major =3D 10;
+    Minor =3D 4;
+    Micro =3D 0;
+    break;
+  }
+  return true;
+}
+
 void Triple::setTriple(const Twine &Str) {
-  Data =3D Str.str();
-  Arch =3D InvalidArch;
+  *this =3D Triple(Str);
 }
=20
 void Triple::setArch(ArchType Kind) {
@@ -670,3 +635,126 @@
 void Triple::setOSAndEnvironmentName(StringRef Str) {
   setTriple(getArchName() + "-" + getVendorName() + "-" + Str);
 }
+
+static unsigned getArchPointerBitWidth(llvm::Triple::ArchType Arch) {
+  switch (Arch) {
+  case llvm::Triple::UnknownArch:
+    return 0;
+
+  case llvm::Triple::msp430:
+    return 16;
+
+  case llvm::Triple::amdil:
+  case llvm::Triple::arm:
+  case llvm::Triple::cellspu:
+  case llvm::Triple::hexagon:
+  case llvm::Triple::le32:
+  case llvm::Triple::mblaze:
+  case llvm::Triple::mips:
+  case llvm::Triple::mipsel:
+  case llvm::Triple::ppc:
+  case llvm::Triple::ptx32:
+  case llvm::Triple::r600:
+  case llvm::Triple::sparc:
+  case llvm::Triple::tce:
+  case llvm::Triple::thumb:
+  case llvm::Triple::x86:
+  case llvm::Triple::xcore:
+    return 32;
+
+  case llvm::Triple::mips64:
+  case llvm::Triple::mips64el:
+  case llvm::Triple::ppc64:
+  case llvm::Triple::ptx64:
+  case llvm::Triple::sparcv9:
+  case llvm::Triple::x86_64:
+    return 64;
+  }
+  llvm_unreachable("Invalid architecture value");
+}
+
+bool Triple::isArch64Bit() const {
+  return getArchPointerBitWidth(getArch()) =3D=3D 64;
+}
+
+bool Triple::isArch32Bit() const {
+  return getArchPointerBitWidth(getArch()) =3D=3D 32;
+}
+
+bool Triple::isArch16Bit() const {
+  return getArchPointerBitWidth(getArch()) =3D=3D 16;
+}
+
+Triple Triple::get32BitArchVariant() const {
+  Triple T(*this);
+  switch (getArch()) {
+  case Triple::UnknownArch:
+  case Triple::msp430:
+    T.setArch(UnknownArch);
+    break;
+
+  case Triple::amdil:
+  case Triple::arm:
+  case Triple::cellspu:
+  case Triple::hexagon:
+  case Triple::le32:
+  case Triple::mblaze:
+  case Triple::mips:
+  case Triple::mipsel:
+  case Triple::ppc:
+  case Triple::ptx32:
+  case Triple::r600:
+  case Triple::sparc:
+  case Triple::tce:
+  case Triple::thumb:
+  case Triple::x86:
+  case Triple::xcore:
+    // Already 32-bit.
+    break;
+
+  case Triple::mips64:    T.setArch(Triple::mips);    break;
+  case Triple::mips64el:  T.setArch(Triple::mipsel);  break;
+  case Triple::ppc64:     T.setArch(Triple::ppc);   break;
+  case Triple::ptx64:     T.setArch(Triple::ptx32);   break;
+  case Triple::sparcv9:   T.setArch(Triple::sparc);   break;
+  case Triple::x86_64:    T.setArch(Triple::x86);     break;
+  }
+  return T;
+}
+
+Triple Triple::get64BitArchVariant() const {
+  Triple T(*this);
+  switch (getArch()) {
+  case Triple::UnknownArch:
+  case Triple::amdil:
+  case Triple::arm:
+  case Triple::cellspu:
+  case Triple::hexagon:
+  case Triple::le32:
+  case Triple::mblaze:
+  case Triple::msp430:
+  case Triple::r600:
+  case Triple::tce:
+  case Triple::thumb:
+  case Triple::xcore:
+    T.setArch(UnknownArch);
+    break;
+
+  case Triple::mips64:
+  case Triple::mips64el:
+  case Triple::ppc64:
+  case Triple::ptx64:
+  case Triple::sparcv9:
+  case Triple::x86_64:
+    // Already 64-bit.
+    break;
+
+  case Triple::mips:    T.setArch(Triple::mips64);    break;
+  case Triple::mipsel:  T.setArch(Triple::mips64el);  break;
+  case Triple::ppc:     T.setArch(Triple::ppc64);     break;
+  case Triple::ptx32:   T.setArch(Triple::ptx64);     break;
+  case Triple::sparc:   T.setArch(Triple::sparcv9);   break;
+  case Triple::x86:     T.setArch(Triple::x86_64);    break;
+  }
+  return T;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Unix/Hos=
t.inc
--- a/head/contrib/llvm/lib/Support/Unix/Host.inc	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/Unix/Host.inc	Tue Apr 17 11:51:51 2012 =
+0300
@@ -26,6 +26,11 @@
=20
 using namespace llvm;
=20
+#ifdef __FreeBSD__
+std::string sys::getDefaultTargetTriple() {
+  return LLVM_DEFAULT_TARGET_TRIPLE;
+}
+#else // __FreeBSD__
 static std::string getOSVersion() {
   struct utsname info;
=20
@@ -35,17 +40,11 @@
   return info.release;
 }
=20
-std::string sys::getHostTriple() {
-#ifdef __FreeBSD__
-  return LLVM_HOSTTRIPLE;
-#else
-  // FIXME: Derive directly instead of relying on the autoconf generated
-  // variable.
+std::string sys::getDefaultTargetTriple() {
+  StringRef TargetTripleString(LLVM_DEFAULT_TARGET_TRIPLE);
+  std::pair<StringRef, StringRef> ArchSplit =3D TargetTripleString.split('=
-');
=20
-  StringRef HostTripleString(LLVM_HOSTTRIPLE);
-  std::pair<StringRef, StringRef> ArchSplit =3D HostTripleString.split('-'=
);
-
-  // Normalize the arch, since the host triple may not actually match the =
host.
+  // Normalize the arch, since the target triple may not actually match th=
e target.
   std::string Arch =3D ArchSplit.first;
=20
   std::string Triple(Arch);
@@ -58,7 +57,7 @@
     Triple[1] =3D '3';
=20
   // On darwin, we want to update the version to match that of the
-  // host.
+  // target.
   std::string::size_type DarwinDashIdx =3D Triple.find("-darwin");
   if (DarwinDashIdx !=3D std::string::npos) {
     Triple.resize(DarwinDashIdx + strlen("-darwin"));
@@ -66,5 +65,5 @@
   }
=20
   return Triple;
-#endif
 }
+#endif // __FreeBSD__
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Unix/Pat=
h.inc
--- a/head/contrib/llvm/lib/Support/Unix/Path.inc	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Support/Unix/Path.inc	Tue Apr 17 11:51:51 2012 =
+0300
@@ -60,6 +60,11 @@
 #include <mach-o/dyld.h>
 #endif
=20
+// For GNU Hurd
+#if defined(__GNU__) && !defined(MAXPATHLEN)
+# define MAXPATHLEN 4096
+#endif
+
 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
 // is available when it is not.
 #ifdef __CYGWIN__
@@ -235,11 +240,6 @@
 }
=20
 Path
-Path::GetLLVMDefaultConfigDir() {
-  return Path("/etc/llvm/");
-}
-
-Path
 Path::GetUserHomeDirectory() {
   const char* home =3D getenv("HOME");
   Path result;
@@ -261,7 +261,7 @@
 }
=20
 #if defined(__FreeBSD__) || defined (__NetBSD__) || \
-    defined(__OpenBSD__) || defined(__minix)
+    defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
 static int
 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
     const char *dir, const char *bin)
@@ -313,7 +313,7 @@
   free(pv);
   return (NULL);
 }
-#endif // __FreeBSD__ || __NetBSD__
+#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
=20
 /// GetMainExecutable - Return the path to the main executable, given the
 /// value of argv[0] from program startup.
@@ -330,7 +330,7 @@
       return Path(link_path);
   }
 #elif defined(__FreeBSD__) || defined (__NetBSD__) || \
-      defined(__OpenBSD__) || defined(__minix)
+      defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel=
__)
   char exe_path[PATH_MAX];
=20
   if (getprogpath(exe_path, argv0) !=3D NULL)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Unix/Pat=
hV2.inc
--- a/head/contrib/llvm/lib/Support/Unix/PathV2.inc	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Support/Unix/PathV2.inc	Tue Apr 17 11:51:51 201=
2 +0300
@@ -46,6 +46,11 @@
 #include <limits.h>
 #endif
=20
+// For GNU Hurd
+#if defined(__GNU__) && !defined(PATH_MAX)
+# define PATH_MAX 4096
+#endif
+
 using namespace llvm;
=20
 namespace {
@@ -87,7 +92,7 @@
     result.clear();
     StringRef d(dir);
     result.append(d.begin(), d.end());
-    return success;
+    return error_code::success();
   }
 }
=20
@@ -96,7 +101,12 @@
 namespace fs {
=20
 error_code current_path(SmallVectorImpl<char> &result) {
+#ifdef MAXPATHLEN
   result.reserve(MAXPATHLEN);
+#else
+// For GNU Hurd
+  result.reserve(1024);
+#endif
=20
   while (true) {
     if (::getcwd(result.data(), result.capacity()) =3D=3D 0) {
@@ -110,7 +120,7 @@
   }
=20
   result.set_size(strlen(result.data()));
-  return success;
+  return error_code::success();
 }
=20
 error_code copy_file(const Twine &from, const Twine &to, copy_option copt)=
 {
@@ -169,7 +179,7 @@
   if (sz_read < 0)
     return error_code(errno, system_category());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code create_directory(const Twine &path, bool &existed) {
@@ -183,7 +193,7 @@
   } else
     existed =3D false;
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code create_hard_link(const Twine &to, const Twine &from) {
@@ -196,7 +206,7 @@
   if (::link(t.begin(), f.begin()) =3D=3D -1)
     return error_code(errno, system_category());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code create_symlink(const Twine &to, const Twine &from) {
@@ -209,7 +219,7 @@
   if (::symlink(t.begin(), f.begin()) =3D=3D -1)
     return error_code(errno, system_category());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code remove(const Twine &path, bool &existed) {
@@ -223,7 +233,7 @@
   } else
     existed =3D true;
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code rename(const Twine &from, const Twine &to) {
@@ -245,7 +255,7 @@
       return error_code(errno, system_category());
   }
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code resize_file(const Twine &path, uint64_t size) {
@@ -255,7 +265,7 @@
   if (::truncate(p.begin(), size) =3D=3D -1)
     return error_code(errno, system_category());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code exists(const Twine &path, bool &result) {
@@ -270,32 +280,21 @@
   } else
     result =3D true;
=20
-  return success;
+  return error_code::success();
+}
+
+bool equivalent(file_status A, file_status B) {
+  assert(status_known(A) && status_known(B));
+  return A.st_dev =3D=3D B.st_dev &&
+         A.st_ino =3D=3D B.st_ino;
 }
=20
 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
-  // Get arguments.
-  SmallString<128> a_storage;
-  SmallString<128> b_storage;
-  StringRef a =3D A.toNullTerminatedStringRef(a_storage);
-  StringRef b =3D B.toNullTerminatedStringRef(b_storage);
-
-  struct stat stat_a, stat_b;
-  int error_b =3D ::stat(b.begin(), &stat_b);
-  int error_a =3D ::stat(a.begin(), &stat_a);
-
-  // If both are invalid, it's an error. If only one is, the result is fal=
se.
-  if (error_a !=3D 0 || error_b !=3D 0) {
-    if (error_a =3D=3D error_b)
-      return error_code(errno, system_category());
-    result =3D false;
-  } else {
-    result =3D
-      stat_a.st_dev =3D=3D stat_b.st_dev &&
-      stat_a.st_ino =3D=3D stat_b.st_ino;
-  }
-
-  return success;
+  file_status fsA, fsB;
+  if (error_code ec =3D status(A, fsA)) return ec;
+  if (error_code ec =3D status(B, fsB)) return ec;
+  result =3D equivalent(fsA, fsB);
+  return error_code::success();
 }
=20
 error_code file_size(const Twine &path, uint64_t &result) {
@@ -309,7 +308,7 @@
     return make_error_code(errc::operation_not_permitted);
=20
   result =3D status.st_size;
-  return success;
+  return error_code::success();
 }
=20
 error_code status(const Twine &path, file_status &result) {
@@ -341,7 +340,10 @@
   else
     result =3D file_status(file_type::type_unknown);
=20
-  return success;
+  result.st_dev =3D status.st_dev;
+  result.st_ino =3D status.st_ino;
+
+  return error_code::success();
 }
=20
 error_code unique_file(const Twine &model, int &result_fd,
@@ -436,10 +438,11 @@
   result_path.append(d.begin(), d.end());
=20
   result_fd =3D RandomFD;
-  return success;
+  return error_code::success();
 }
=20
-error_code directory_iterator_construct(directory_iterator &it, StringRef =
path){
+error_code detail::directory_iterator_construct(detail::DirIterState &it,
+                                                StringRef path){
   SmallString<128> path_null(path);
   DIR *directory =3D ::opendir(path_null.c_str());
   if (directory =3D=3D 0)
@@ -452,15 +455,15 @@
   return directory_iterator_increment(it);
 }
=20
-error_code directory_iterator_destruct(directory_iterator& it) {
+error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
   if (it.IterationHandle)
     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
   it.IterationHandle =3D 0;
   it.CurrentEntry =3D directory_entry();
-  return success;
+  return error_code::success();
 }
=20
-error_code directory_iterator_increment(directory_iterator& it) {
+error_code detail::directory_iterator_increment(detail::DirIterState &it) {
   errno =3D 0;
   dirent *cur_dir =3D ::readdir(reinterpret_cast<DIR *>(it.IterationHandle=
));
   if (cur_dir =3D=3D 0 && errno !=3D 0) {
@@ -474,7 +477,7 @@
   } else
     return directory_iterator_destruct(it);
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code get_magic(const Twine &path, uint32_t len,
@@ -505,7 +508,7 @@
   }
   std::fclose(file);
   result.set_size(len);
-  return success;
+  return error_code::success();
 }
=20
 } // end namespace fs
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Unix/Pro=
cess.inc
--- a/head/contrib/llvm/lib/Support/Unix/Process.inc	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Support/Unix/Process.inc	Tue Apr 17 11:51:51 20=
12 +0300
@@ -136,7 +136,7 @@
   return getgid();
 }
=20
-#ifdef HAVE_MACH_MACH_H
+#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
 #include <mach/mach.h>
 #endif
=20
@@ -150,7 +150,7 @@
   setrlimit(RLIMIT_CORE, &rlim);
 #endif
=20
-#ifdef HAVE_MACH_MACH_H
+#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
   // Disable crash reporting on Mac OS X 10.0-10.4
=20
   // get information about the original set of exception ports for the task
@@ -293,7 +293,3 @@
 const char *Process::ResetColor() {
   return "\033[0m";
 }
-
-void Process::SetWorkingDirectory(std::string Path) {
-  ::chdir(Path.c_str());
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Unix/Pro=
gram.inc
--- a/head/contrib/llvm/lib/Support/Unix/Program.inc	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Support/Unix/Program.inc	Tue Apr 17 11:51:51 20=
12 +0300
@@ -412,19 +412,19 @@
   return false;
 }
=20
-bool Program::ChangeStdinToBinary(){
+error_code Program::ChangeStdinToBinary(){
   // Do nothing, as Unix doesn't differentiate between text and binary.
-  return false;
+  return make_error_code(errc::success);
 }
=20
-bool Program::ChangeStdoutToBinary(){
+error_code Program::ChangeStdoutToBinary(){
   // Do nothing, as Unix doesn't differentiate between text and binary.
-  return false;
+  return make_error_code(errc::success);
 }
=20
-bool Program::ChangeStderrToBinary(){
+error_code Program::ChangeStderrToBinary(){
   // Do nothing, as Unix doesn't differentiate between text and binary.
-  return false;
+  return make_error_code(errc::success);
 }
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Unix/Sig=
nals.inc
--- a/head/contrib/llvm/lib/Support/Unix/Signals.inc	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Support/Unix/Signals.inc	Tue Apr 17 11:51:51 20=
12 +0300
@@ -30,6 +30,10 @@
 #include <dlfcn.h>
 #include <cxxabi.h>
 #endif
+#if HAVE_MACH_MACH_H
+#include <mach/mach.h>
+#endif
+
 using namespace llvm;
=20
 static RETSIGTYPE SignalHandler(int Sig);  // defined below.
@@ -261,6 +265,22 @@
 /// SIGSEGV) is delivered to the process, print a stack trace and then exi=
t.
 void llvm::sys::PrintStackTraceOnErrorSignal() {
   AddSignalHandler(PrintStackTrace, 0);
+
+#if defined(__APPLE__)
+  // Environment variable to disable any kind of crash dialog.
+  if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
+    mach_port_t self =3D mach_task_self();
+
+    exception_mask_t mask =3D EXC_MASK_CRASH;
+
+    kern_return_t ret =3D task_set_exception_ports(self,=20
+                             mask,
+                             MACH_PORT_NULL,
+                             EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_COD=
ES,=20
+                             THREAD_STATE_NONE);
+    (void)ret;
+  }
+#endif
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Valgrind=
.cpp
--- a/head/contrib/llvm/lib/Support/Valgrind.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/Support/Valgrind.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -52,3 +52,16 @@
 }
=20
 #endif  // !HAVE_VALGRIND_VALGRIND_H
+
+#if LLVM_ENABLE_THREADS !=3D 0 && !defined(NDEBUG)
+// These functions require no implementation, tsan just looks at the argum=
ents
+// they're called with.
+extern "C" {
+void AnnotateHappensBefore(const char *file, int line,
+                           const volatile void *cv) {}
+void AnnotateHappensAfter(const char *file, int line,
+                          const volatile void *cv) {}
+void AnnotateIgnoreWritesBegin(const char *file, int line) {}
+void AnnotateIgnoreWritesEnd(const char *file, int line) {}
+}
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Windows/=
Host.inc
--- a/head/contrib/llvm/lib/Support/Windows/Host.inc	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Support/Windows/Host.inc	Tue Apr 17 11:51:51 20=
12 +0300
@@ -17,7 +17,6 @@
=20
 using namespace llvm;
=20
-std::string sys::getHostTriple() {
-  // FIXME: Adapt to running version.
-  return LLVM_HOSTTRIPLE;
+std::string sys::getDefaultTargetTriple() {
+  return LLVM_DEFAULT_TARGET_TRIPLE;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Windows/=
Path.inc
--- a/head/contrib/llvm/lib/Support/Windows/Path.inc	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Support/Windows/Path.inc	Tue Apr 17 11:51:51 20=
12 +0300
@@ -66,29 +66,20 @@
   return *this;
 }
=20
-// push_back 0 on create, and pop_back on delete.
-struct ScopedNullTerminator {
-  std::string &str;
-  ScopedNullTerminator(std::string &s) : str(s) { str.push_back(0); }
-  ~ScopedNullTerminator() {
-    // str.pop_back(); But wait, C++03 doesn't have this...
-    assert(!str.empty() && str[str.size() - 1] =3D=3D 0
-      && "Null char not present!");
-    str.resize(str.size() - 1);
-  }
-};
-
 bool
 Path::isValid() const {
   if (path.empty())
     return false;
=20
+  size_t len =3D path.size();
+  // If there is a null character, it and all its successors are ignored.
+  size_t pos =3D path.find_first_of('\0');
+  if (pos !=3D std::string::npos)
+    len =3D pos;
+
   // If there is a colon, it must be the second character, preceded by a l=
etter
   // and followed by something.
-  size_t len =3D path.size();
-  // This code assumes that path is null terminated, so make sure it is.
-  ScopedNullTerminator snt(path);
-  size_t pos =3D path.rfind(':',len);
+  pos =3D path.rfind(':',len);
   size_t rootslash =3D 0;
   if (pos !=3D std::string::npos) {
     if (pos !=3D 1 || !isalpha(path[0]) || len < 3)
@@ -118,13 +109,13 @@
   for (pos =3D 0; pos < len; ++pos) {
     // A component may not end in a space.
     if (path[pos] =3D=3D ' ') {
-      if (path[pos+1] =3D=3D '/' || path[pos+1] =3D=3D '\0')
+      if (pos+1 =3D=3D len || path[pos+1] =3D=3D '/' || path[pos+1] =3D=3D=
 '\0')
         return false;
     }
=20
     // A component may not end in a period.
     if (path[pos] =3D=3D '.') {
-      if (path[pos+1] =3D=3D '/' || path[pos+1] =3D=3D '\0') {
+      if (pos+1 =3D=3D len || path[pos+1] =3D=3D '/') {
         // Unless it is the pseudo-directory "."...
         if (pos =3D=3D 0 || path[pos-1] =3D=3D '/' || path[pos-1] =3D=3D '=
:')
           return true;
@@ -286,14 +277,6 @@
 }
=20
 Path
-Path::GetLLVMDefaultConfigDir() {
-  Path ret =3D GetUserHomeDirectory();
-  if (!ret.appendComponent(".llvm"))
-    assert(0 && "Failed to append .llvm");
-  return ret;
-}
-
-Path
 Path::GetUserHomeDirectory() {
   char buff[MAX_PATH];
   HRESULT res =3D SHGetFolderPathA(NULL,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Windows/=
PathV2.inc
--- a/head/contrib/llvm/lib/Support/Windows/PathV2.inc	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Support/Windows/PathV2.inc	Tue Apr 17 11:51:51 =
2012 +0300
@@ -17,7 +17,6 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "Windows.h"
-#include <wincrypt.h>
 #include <fcntl.h>
 #include <io.h>
 #include <sys/stat.h>
@@ -63,7 +62,7 @@
     utf16.push_back(0);
     utf16.pop_back();
=20
-    return success;
+    return error_code::success();
   }
=20
   error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
@@ -93,7 +92,7 @@
     utf8.push_back(0);
     utf8.pop_back();
=20
-    return success;
+    return error_code::success();
   }
=20
   error_code TempDir(SmallVectorImpl<wchar_t> &result) {
@@ -109,17 +108,9 @@
     }
=20
     result.set_size(len);
-    return success;
+    return error_code::success();
   }
=20
-  // Forwarder for ScopedHandle.
-  BOOL WINAPI CryptReleaseContext(HCRYPTPROV Provider) {
-    return ::CryptReleaseContext(Provider, 0);
-  }
-
-  typedef ScopedHandle<HCRYPTPROV, uintptr_t(-1),
-                       BOOL (WINAPI*)(HCRYPTPROV), CryptReleaseContext>
-    ScopedCryptContext;
   bool is_separator(const wchar_t value) {
     switch (value) {
     case L'\\':
@@ -176,7 +167,7 @@
   if (len =3D=3D 0)
     return windows_error(::GetLastError());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code copy_file(const Twine &from, const Twine &to, copy_option copt)=
 {
@@ -199,7 +190,7 @@
   if (res =3D=3D 0)
     return windows_error(::GetLastError());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code create_directory(const Twine &path, bool &existed) {
@@ -219,7 +210,7 @@
   } else
     existed =3D false;
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code create_hard_link(const Twine &to, const Twine &from) {
@@ -238,7 +229,7 @@
   if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
     return windows_error(::GetLastError());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code create_symlink(const Twine &to, const Twine &from) {
@@ -261,7 +252,7 @@
   if (!create_symbolic_link_api(wide_from.begin(), wide_to.begin(), 0))
     return windows_error(::GetLastError());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code remove(const Twine &path, bool &existed) {
@@ -294,7 +285,7 @@
       existed =3D true;
   }
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code rename(const Twine &from, const Twine &to) {
@@ -314,7 +305,7 @@
                      MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
     return windows_error(::GetLastError());
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code resize_file(const Twine &path, uint64_t size) {
@@ -356,72 +347,26 @@
     result =3D false;
   } else
     result =3D true;
-  return success;
+  return error_code::success();
+}
+
+bool equivalent(file_status A, file_status B) {
+  assert(status_known(A) && status_known(B));
+  return A.FileIndexHigh      =3D=3D B.FileIndexHigh &&
+         A.FileIndexLow       =3D=3D B.FileIndexLow &&
+         A.FileSizeHigh       =3D=3D B.FileSizeHigh &&
+         A.FileSizeLow        =3D=3D B.FileSizeLow &&
+         A.LastWriteTimeHigh  =3D=3D B.LastWriteTimeHigh &&
+         A.LastWriteTimeLow   =3D=3D B.LastWriteTimeLow &&
+         A.VolumeSerialNumber =3D=3D B.VolumeSerialNumber;
 }
=20
 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
-  // Get arguments.
-  SmallString<128> a_storage;
-  SmallString<128> b_storage;
-  StringRef a =3D A.toStringRef(a_storage);
-  StringRef b =3D B.toStringRef(b_storage);
-
-  // Convert to utf-16.
-  SmallVector<wchar_t, 128> wide_a;
-  SmallVector<wchar_t, 128> wide_b;
-  if (error_code ec =3D UTF8ToUTF16(a, wide_a)) return ec;
-  if (error_code ec =3D UTF8ToUTF16(b, wide_b)) return ec;
-
-  AutoHandle HandleB(
-    ::CreateFileW(wide_b.begin(),
-                  0,
-                  FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
-                  0,
-                  OPEN_EXISTING,
-                  FILE_FLAG_BACKUP_SEMANTICS,
-                  0));
-
-  AutoHandle HandleA(
-    ::CreateFileW(wide_a.begin(),
-                  0,
-                  FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
-                  0,
-                  OPEN_EXISTING,
-                  FILE_FLAG_BACKUP_SEMANTICS,
-                  0));
-
-  // If both handles are invalid, it's an error.
-  if (HandleA =3D=3D INVALID_HANDLE_VALUE &&
-      HandleB =3D=3D INVALID_HANDLE_VALUE)
-    return windows_error(::GetLastError());
-
-  // If only one is invalid, it's false.
-  if (HandleA =3D=3D INVALID_HANDLE_VALUE &&
-      HandleB =3D=3D INVALID_HANDLE_VALUE) {
-    result =3D false;
-    return success;
-  }
-
-  // Get file information.
-  BY_HANDLE_FILE_INFORMATION InfoA, InfoB;
-  if (!::GetFileInformationByHandle(HandleA, &InfoA))
-    return windows_error(::GetLastError());
-  if (!::GetFileInformationByHandle(HandleB, &InfoB))
-    return windows_error(::GetLastError());
-
-  // See if it's all the same.
-  result =3D
-    InfoA.dwVolumeSerialNumber           =3D=3D InfoB.dwVolumeSerialNumber=
 &&
-    InfoA.nFileIndexHigh                 =3D=3D InfoB.nFileIndexHigh &&
-    InfoA.nFileIndexLow                  =3D=3D InfoB.nFileIndexLow &&
-    InfoA.nFileSizeHigh                  =3D=3D InfoB.nFileSizeHigh &&
-    InfoA.nFileSizeLow                   =3D=3D InfoB.nFileSizeLow &&
-    InfoA.ftLastWriteTime.dwLowDateTime  =3D=3D
-      InfoB.ftLastWriteTime.dwLowDateTime &&
-    InfoA.ftLastWriteTime.dwHighDateTime =3D=3D
-      InfoB.ftLastWriteTime.dwHighDateTime;
-
-  return success;
+  file_status fsA, fsB;
+  if (error_code ec =3D status(A, fsA)) return ec;
+  if (error_code ec =3D status(B, fsB)) return ec;
+  result =3D equivalent(fsA, fsB);
+  return error_code::success();
 }
=20
 error_code file_size(const Twine &path, uint64_t &result) {
@@ -442,7 +387,7 @@
     (uint64_t(FileData.nFileSizeHigh) << (sizeof(FileData.nFileSizeLow) * =
8))
     + FileData.nFileSizeLow;
=20
-  return success;
+  return error_code::success();
 }
=20
 static bool isReservedName(StringRef path) {
@@ -475,11 +420,10 @@
   StringRef path8 =3D path.toStringRef(path_storage);
   if (isReservedName(path8)) {
     result =3D file_status(file_type::character_file);
-    return success;
+    return error_code::success();
   }
=20
-  if (error_code ec =3D UTF8ToUTF16(path8,
-                                  path_utf16))
+  if (error_code ec =3D UTF8ToUTF16(path8, path_utf16))
     return ec;
=20
   DWORD attr =3D ::GetFileAttributesW(path_utf16.begin());
@@ -488,7 +432,7 @@
=20
   // Handle reparse points.
   if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
-    AutoHandle h(
+    ScopedFileHandle h(
       ::CreateFileW(path_utf16.begin(),
                     0, // Attributes only.
                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
@@ -496,16 +440,37 @@
                     OPEN_EXISTING,
                     FILE_FLAG_BACKUP_SEMANTICS,
                     0));
-    if (h =3D=3D INVALID_HANDLE_VALUE)
+    if (!h)
       goto handle_status_error;
   }
=20
   if (attr & FILE_ATTRIBUTE_DIRECTORY)
     result =3D file_status(file_type::directory_file);
-  else
+  else {
     result =3D file_status(file_type::regular_file);
+    ScopedFileHandle h(
+      ::CreateFileW(path_utf16.begin(),
+                    0, // Attributes only.
+                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
+                    NULL,
+                    OPEN_EXISTING,
+                    FILE_FLAG_BACKUP_SEMANTICS,
+                    0));
+    if (!h)
+      goto handle_status_error;
+    BY_HANDLE_FILE_INFORMATION Info;
+    if (!::GetFileInformationByHandle(h, &Info))
+      goto handle_status_error;
+    result.FileIndexHigh      =3D Info.nFileIndexHigh;
+    result.FileIndexLow       =3D Info.nFileIndexLow;
+    result.FileSizeHigh       =3D Info.nFileSizeHigh;
+    result.FileSizeLow        =3D Info.nFileSizeLow;
+    result.LastWriteTimeHigh  =3D Info.ftLastWriteTime.dwHighDateTime;
+    result.LastWriteTimeLow   =3D Info.ftLastWriteTime.dwLowDateTime;
+    result.VolumeSerialNumber =3D Info.dwVolumeSerialNumber;
+  }
=20
-  return success;
+  return error_code::success();
=20
 handle_status_error:
   error_code ec =3D windows_error(::GetLastError());
@@ -519,7 +484,7 @@
     return ec;
   }
=20
-  return success;
+  return error_code::success();
 }
=20
 error_code unique_file(const Twine &model, int &result_fd,
@@ -535,7 +500,7 @@
   if (makeAbsolute) {
     // Make model absolute by prepending a temp directory if it's not alre=
ady.
     bool absolute =3D path::is_absolute(m);
- =20
+
     if (!absolute) {
       SmallVector<wchar_t, 64> temp_dir;
       if (error_code ec =3D TempDir(temp_dir)) return ec;
@@ -646,7 +611,7 @@
   }
=20
   result_fd =3D fd;
-  return success;
+  return error_code::success();
 }
=20
 error_code get_magic(const Twine &path, uint32_t len,
@@ -688,10 +653,11 @@
   }
=20
   result.set_size(len);
-  return success;
+  return error_code::success();
 }
=20
-error_code directory_iterator_construct(directory_iterator &it, StringRef =
path){
+error_code detail::directory_iterator_construct(detail::DirIterState &it,
+                                                StringRef path){
   SmallVector<wchar_t, 128> path_utf16;
=20
   if (error_code ec =3D UTF8ToUTF16(path,
@@ -722,7 +688,7 @@
       error_code ec =3D windows_error(::GetLastError());
       // Check for end.
       if (ec =3D=3D windows_error::no_more_files)
-        return directory_iterator_destruct(it);
+        return detail::directory_iterator_destruct(it);
       return ec;
     } else
       FilenameLen =3D ::wcslen(FirstFind.cFileName);
@@ -739,25 +705,25 @@
   path::append(directory_entry_path, directory_entry_name_utf8.str());
   it.CurrentEntry =3D directory_entry(directory_entry_path.str());
=20
-  return success;
+  return error_code::success();
 }
=20
-error_code directory_iterator_destruct(directory_iterator& it) {
+error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
   if (it.IterationHandle !=3D 0)
     // Closes the handle if it's valid.
     ScopedFindHandle close(HANDLE(it.IterationHandle));
   it.IterationHandle =3D 0;
   it.CurrentEntry =3D directory_entry();
-  return success;
+  return error_code::success();
 }
=20
-error_code directory_iterator_increment(directory_iterator& it) {
+error_code detail::directory_iterator_increment(detail::DirIterState &it) {
   WIN32_FIND_DATAW FindData;
   if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
     error_code ec =3D windows_error(::GetLastError());
     // Check for end.
     if (ec =3D=3D windows_error::no_more_files)
-      return directory_iterator_destruct(it);
+      return detail::directory_iterator_destruct(it);
     return ec;
   }
=20
@@ -774,7 +740,7 @@
     return ec;
=20
   it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
-  return success;
+  return error_code::success();
 }
=20
 } // end namespace fs
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Windows/=
Process.inc
--- a/head/contrib/llvm/lib/Support/Windows/Process.inc	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Windows/Process.inc	Tue Apr 17 11:51:51=
 2012 +0300
@@ -220,8 +220,4 @@
   return 0;
 }
=20
-void Process::SetWorkingDirectory(std::string Path) {
-  ::_chdir(Path.c_str());
 }
-
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Windows/=
Program.inc
--- a/head/contrib/llvm/lib/Support/Windows/Program.inc	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Windows/Program.inc	Tue Apr 17 11:51:51=
 2012 +0300
@@ -299,14 +299,14 @@
   Data_ =3D wpi;
=20
   // Make sure these get closed no matter what.
-  AutoHandle hThread(pi.hThread);
+  ScopedCommonHandle hThread(pi.hThread);
=20
   // Assign the process to a job if a memory limit is defined.
-  AutoHandle hJob(0);
+  ScopedJobHandle hJob;
   if (memoryLimit !=3D 0) {
     hJob =3D CreateJobObject(0, 0);
     bool success =3D false;
-    if (hJob !=3D 0) {
+    if (hJob) {
       JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
       memset(&jeli, 0, sizeof(jeli));
       jeli.BasicLimitInformation.LimitFlags =3D JOB_OBJECT_LIMIT_PROCESS_M=
EMORY;
@@ -367,7 +367,17 @@
     return -2;
   }
=20
-  return status;
+  if (!status)
+    return 0;
+
+  // Pass 10(Warning) and 11(Error) to the callee as negative value.
+  if ((status & 0xBFFF0000U) =3D=3D 0x80000000U)
+    return (int)status;
+
+  if (status & 0xFF)
+    return status & 0x7FFFFFFF;
+
+  return 1;
 }
=20
 bool
@@ -387,19 +397,25 @@
   return false;
 }
=20
-bool Program::ChangeStdinToBinary(){
+error_code Program::ChangeStdinToBinary(){
   int result =3D _setmode( _fileno(stdin), _O_BINARY );
-  return result =3D=3D -1;
+  if (result =3D=3D -1)
+    return error_code(errno, generic_category());
+  return make_error_code(errc::success);
 }
=20
-bool Program::ChangeStdoutToBinary(){
+error_code Program::ChangeStdoutToBinary(){
   int result =3D _setmode( _fileno(stdout), _O_BINARY );
-  return result =3D=3D -1;
+  if (result =3D=3D -1)
+    return error_code(errno, generic_category());
+  return make_error_code(errc::success);
 }
=20
-bool Program::ChangeStderrToBinary(){
+error_code Program::ChangeStderrToBinary(){
   int result =3D _setmode( _fileno(stderr), _O_BINARY );
-  return result =3D=3D -1;
+  if (result =3D=3D -1)
+    return error_code(errno, generic_category());
+  return make_error_code(errc::success);
 }
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Windows/=
Signals.inc
--- a/head/contrib/llvm/lib/Support/Windows/Signals.inc	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Support/Windows/Signals.inc	Tue Apr 17 11:51:51=
 2012 +0300
@@ -239,7 +239,7 @@
   SetConsoleCtrlHandler(LLVMConsoleCtrlHandler, TRUE);
=20
   // Environment variable to disable any kind of crash dialog.
-  if (getenv("LLVM_DISABLE_CRT_DEBUG")) {
+  if (getenv("LLVM_DISABLE_CRASH_REPORT")) {
 #ifdef _MSC_VER
     _CrtSetReportHook(CRTReportHook);
 #endif
@@ -446,7 +446,7 @@
   }
=20
   if (ExitOnUnhandledExceptions)
-    _exit(-3);
+    _exit(ep->ExceptionRecord->ExceptionCode);
=20
   // Allow dialog box to pop up allowing choice to start debugger.
   if (OldFilter)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/Windows/=
Windows.h
--- a/head/contrib/llvm/lib/Support/Windows/Windows.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Support/Windows/Windows.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -26,6 +26,7 @@
=20
 #include "llvm/Config/config.h" // Get build system configuration settings
 #include <windows.h>
+#include <wincrypt.h>
 #include <shlobj.h>
 #include <cassert>
 #include <string>
@@ -41,70 +42,99 @@
   return true;
 }
=20
-class AutoHandle {
-  HANDLE handle;
+template <typename HandleTraits>
+class ScopedHandle {
+  typedef typename HandleTraits::handle_type handle_type;
+  handle_type Handle;
=20
+  ScopedHandle(const ScopedHandle &other); // =3D delete;
+  void operator=3D(const ScopedHandle &other); // =3D delete;
 public:
-  AutoHandle(HANDLE h) : handle(h) {}
+  ScopedHandle()
+    : Handle(HandleTraits::GetInvalid()) {}
=20
-  ~AutoHandle() {
-    if (handle)
-      CloseHandle(handle);
+  explicit ScopedHandle(handle_type h)
+    : Handle(h) {}
+
+  ~ScopedHandle() {
+    if (HandleTraits::IsValid(Handle))
+      HandleTraits::Close(Handle);
   }
=20
-  operator HANDLE() {
-    return handle;
+  handle_type take() {
+    handle_type t =3D Handle;
+    Handle =3D HandleTraits::GetInvalid();
+    return t;
   }
=20
-  AutoHandle &operator=3D(HANDLE h) {
-    handle =3D h;
+  ScopedHandle &operator=3D(handle_type h) {
+    if (HandleTraits::IsValid(Handle))
+      HandleTraits::Close(Handle);
+    Handle =3D h;
     return *this;
   }
+
+  // True if Handle is valid.
+  operator bool() const {
+    return HandleTraits::IsValid(Handle) ? true : false;
+  }
+
+  operator handle_type() const {
+    return Handle;
+  }
 };
=20
-template <class HandleType, uintptr_t InvalidHandle,
-          class DeleterType, DeleterType D>
-class ScopedHandle {
-  HandleType Handle;
+struct CommonHandleTraits {
+  typedef HANDLE handle_type;
=20
-public:
-  ScopedHandle() : Handle(InvalidHandle) {}
-  ScopedHandle(HandleType handle) : Handle(handle) {}
-
-  ~ScopedHandle() {
-    if (Handle !=3D HandleType(InvalidHandle))
-      D(Handle);
+  static handle_type GetInvalid() {
+    return INVALID_HANDLE_VALUE;
   }
=20
-  HandleType take() {
-    HandleType temp =3D Handle;
-    Handle =3D HandleType(InvalidHandle);
-    return temp;
+  static void Close(handle_type h) {
+    ::CloseHandle(h);
   }
=20
-  operator HandleType() const { return Handle; }
-
-  ScopedHandle &operator=3D(HandleType handle) {
-    Handle =3D handle;
-    return *this;
-  }
-
-  typedef void (*unspecified_bool_type)();
-  static void unspecified_bool_true() {}
-
-  // True if Handle is valid.
-  operator unspecified_bool_type() const {
-    return Handle =3D=3D HandleType(InvalidHandle) ? 0 : unspecified_bool_=
true;
-  }
-
-  bool operator!() const {
-    return Handle =3D=3D HandleType(InvalidHandle);
+  static bool IsValid(handle_type h) {
+    return h !=3D GetInvalid();
   }
 };
=20
-typedef ScopedHandle<HANDLE, uintptr_t(-1),
-                      BOOL (WINAPI*)(HANDLE), ::FindClose>
-  ScopedFindHandle;
+struct JobHandleTraits : CommonHandleTraits {
+  static handle_type GetInvalid() {
+    return NULL;
+  }
+};
+
+struct CryptContextTraits : CommonHandleTraits {
+  typedef HCRYPTPROV handle_type;
+
+  static handle_type GetInvalid() {
+    return 0;
+  }
+
+  static void Close(handle_type h) {
+    ::CryptReleaseContext(h, 0);
+  }
+
+  static bool IsValid(handle_type h) {
+    return h !=3D GetInvalid();
+  }
+};
+
+struct FindHandleTraits : CommonHandleTraits {
+  static void Close(handle_type h) {
+    ::FindClose(h);
+  }
+};
+
+struct FileHandleTraits : CommonHandleTraits {};
+
+typedef ScopedHandle<CommonHandleTraits> ScopedCommonHandle;
+typedef ScopedHandle<FileHandleTraits>   ScopedFileHandle;
+typedef ScopedHandle<CryptContextTraits> ScopedCryptContext;
+typedef ScopedHandle<FindHandleTraits>   ScopedFindHandle;
+typedef ScopedHandle<JobHandleTraits>    ScopedJobHandle;
=20
 namespace llvm {
 template <class T>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Support/raw_ostr=
eam.cpp
--- a/head/contrib/llvm/lib/Support/raw_ostream.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Support/raw_ostream.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -20,6 +20,7 @@
 #include "llvm/Config/config.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/system_error.h"
 #include "llvm/ADT/STLExtras.h"
 #include <cctype>
 #include <cerrno>
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/TableGen/Error.c=
pp
--- a/head/contrib/llvm/lib/TableGen/Error.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/TableGen/Error.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -21,11 +21,11 @@
 SourceMgr SrcMgr;
=20
 void PrintError(SMLoc ErrorLoc, const Twine &Msg) {
-  SrcMgr.PrintMessage(ErrorLoc, Msg, "error");
+  SrcMgr.PrintMessage(ErrorLoc, SourceMgr::DK_Error, Msg);
 }
=20
 void PrintError(const char *Loc, const Twine &Msg) {
-  SrcMgr.PrintMessage(SMLoc::getFromPointer(Loc), Msg, "error");
+  SrcMgr.PrintMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg=
);
 }
=20
 void PrintError(const Twine &Msg) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/TableGen/Record.=
cpp
--- a/head/contrib/llvm/lib/TableGen/Record.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/TableGen/Record.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -18,6 +18,7 @@
 #include "llvm/Support/Format.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
@@ -29,6 +30,8 @@
 //    std::string wrapper for DenseMap purposes
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+namespace llvm {
+
 /// TableGenStringKey - This is a wrapper for std::string suitable for
 /// using as a key to a DenseMap.  Because there isn't a particularly
 /// good way to indicate tombstone or empty keys for strings, we want
@@ -43,14 +46,16 @@
   TableGenStringKey(const char *str) : data(str) {}
=20
   const std::string &str() const { return data; }
- =20
+
+  friend hash_code hash_value(const TableGenStringKey &Value) {
+    using llvm::hash_value;
+    return hash_value(Value.str());
+  }
 private:
   std::string data;
 };
=20
 /// Specialize DenseMapInfo for TableGenStringKey.
-namespace llvm {
-
 template<> struct DenseMapInfo<TableGenStringKey> {
   static inline TableGenStringKey getEmptyKey() {
     TableGenStringKey Empty("<<<EMPTY KEY>>>");
@@ -61,7 +66,8 @@
     return Tombstone;
   }
   static unsigned getHashValue(const TableGenStringKey& Val) {
-    return HashString(Val.str());
+    using llvm::hash_value;
+    return hash_value(Val);
   }
   static bool isEqual(const TableGenStringKey& LHS,
                       const TableGenStringKey& RHS) {
@@ -69,7 +75,7 @@
   }
 };
=20
-}
+} // namespace llvm
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //    Type implementations
@@ -78,9 +84,9 @@
 BitRecTy BitRecTy::Shared;
 IntRecTy IntRecTy::Shared;
 StringRecTy StringRecTy::Shared;
-CodeRecTy CodeRecTy::Shared;
 DagRecTy DagRecTy::Shared;
=20
+void RecTy::anchor() { }
 void RecTy::dump() const { print(errs()); }
=20
 ListRecTy *RecTy::getListTy() {
@@ -315,12 +321,6 @@
   return 0;
 }
=20
-Init *CodeRecTy::convertValue(TypedInit *TI) {
-  if (TI->getType()->typeIsConvertibleTo(this))
-    return TI;
-  return 0;
-}
-
 Init *DagRecTy::convertValue(TypedInit *TI) {
   if (TI->getType()->typeIsConvertibleTo(this))
     return TI;
@@ -444,13 +444,18 @@
 //    Initializer implementations
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void Init::anchor() { }
 void Init::dump() const { return print(errs()); }
=20
+void UnsetInit::anchor() { }
+
 UnsetInit *UnsetInit::get() {
   static UnsetInit TheInit;
   return &TheInit;
 }
=20
+void BitInit::anchor() { }
+
 BitInit *BitInit::get(bool V) {
   static BitInit True(true);
   static BitInit False(false);
@@ -565,7 +570,9 @@
   return BitsInit::get(NewBits);
 }
=20
-StringInit *StringInit::get(const std::string &V) {
+void StringInit::anchor() { }
+
+StringInit *StringInit::get(StringRef V) {
   typedef StringMap<StringInit *> Pool;
   static Pool ThePool;
=20
@@ -574,15 +581,6 @@
   return I;
 }
=20
-CodeInit *CodeInit::get(const std::string &V) {
-  typedef StringMap<CodeInit *> Pool;
-  static Pool ThePool;
-
-  CodeInit *&I =3D ThePool[V];
-  if (!I) I =3D new CodeInit(V);
-  return I;
-}
-
 static void ProfileListInit(FoldingSetNodeID &ID,
                             ArrayRef<Init *> Range,
                             RecTy *EltTy) {
@@ -735,7 +733,6 @@
=20
 Init *UnOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
   switch (getOpcode()) {
-  default: assert(0 && "Unknown unop");
   case CAST: {
     if (getType()->getAsString() =3D=3D "string") {
       StringInit *LHSs =3D dynamic_cast<StringInit*>(LHS);
@@ -747,6 +744,11 @@
       if (LHSd) {
         return StringInit::get(LHSd->getDef()->getName());
       }
+
+      IntInit *LHSi =3D dynamic_cast<IntInit*>(LHS);
+      if (LHSi) {
+        return StringInit::get(LHSi->getAsString());
+      }
     } else {
       StringInit *LHSs =3D dynamic_cast<StringInit*>(LHS);
       if (LHSs) {
@@ -760,7 +762,9 @@
             return VarInit::get(Name, RV->getType());
           }
=20
-          std::string TemplateArgName =3D CurRec->getName()+":"+Name;
+          Init *TemplateArgName =3D QualifyName(*CurRec, CurMultiClass, Na=
me,
+                                              ":");
+     =20
           if (CurRec->isTemplateArg(TemplateArgName)) {
             const RecordVal *RV =3D CurRec->getValue(TemplateArgName);
             assert(RV && "Template arg doesn't exist??");
@@ -773,7 +777,8 @@
         }
=20
         if (CurMultiClass) {
-          std::string MCName =3D CurMultiClass->Rec.getName()+"::"+Name;
+          Init *MCName =3D QualifyName(CurMultiClass->Rec, CurMultiClass, =
Name, "::");
+
           if (CurMultiClass->Rec.isTemplateArg(MCName)) {
             const RecordVal *RV =3D CurMultiClass->Rec.getValue(MCName);
             assert(RV && "Template arg doesn't exist??");
@@ -885,7 +890,6 @@
=20
 Init *BinOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
   switch (getOpcode()) {
-  default: assert(0 && "Unknown binop");
   case CONCAT: {
     DagInit *LHSs =3D dynamic_cast<DagInit*>(LHS);
     DagInit *RHSs =3D dynamic_cast<DagInit*>(RHS);
@@ -944,7 +948,7 @@
       int64_t LHSv =3D LHSi->getValue(), RHSv =3D RHSi->getValue();
       int64_t Result;
       switch (getOpcode()) {
-      default: assert(0 && "Bad opcode!");
+      default: llvm_unreachable("Bad opcode!");
       case SHL: Result =3D LHSv << RHSv; break;
       case SRA: Result =3D LHSv >> RHSv; break;
       case SRL: Result =3D (uint64_t)LHSv >> (uint64_t)RHSv; break;
@@ -1134,7 +1138,6 @@
=20
 Init *TernOpInit::Fold(Record *CurRec, MultiClass *CurMultiClass) const {
   switch (getOpcode()) {
-  default: assert(0 && "Unknown binop");
   case SUBST: {
     DefInit *LHSd =3D dynamic_cast<DefInit*>(LHS);
     VarInit *LHSv =3D dynamic_cast<VarInit*>(LHS);
@@ -1298,7 +1301,12 @@
=20
=20
 VarInit *VarInit::get(const std::string &VN, RecTy *T) {
-  typedef std::pair<RecTy *, TableGenStringKey> Key;
+  Init *Value =3D StringInit::get(VN);
+  return VarInit::get(Value, T);
+}
+
+VarInit *VarInit::get(Init *VN, RecTy *T) {
+  typedef std::pair<RecTy *, Init *> Key;
   typedef DenseMap<Key, VarInit *> Pool;
   static Pool ThePool;
=20
@@ -1309,12 +1317,19 @@
   return I;
 }
=20
+const std::string &VarInit::getName() const {
+  StringInit *NameString =3D
+    dynamic_cast<StringInit *>(getNameInit());
+  assert(NameString && "VarInit name is not a string!");
+  return NameString->getValue();
+}
+
 Init *VarInit::resolveBitReference(Record &R, const RecordVal *IRV,
                                    unsigned Bit) const {
-  if (R.isTemplateArg(getName())) return 0;
-  if (IRV && IRV->getName() !=3D getName()) return 0;
+  if (R.isTemplateArg(getNameInit())) return 0;
+  if (IRV && IRV->getNameInit() !=3D getNameInit()) return 0;
=20
-  RecordVal *RV =3D R.getValue(getName());
+  RecordVal *RV =3D R.getValue(getNameInit());
   assert(RV && "Reference to a non-existent variable?");
   assert(dynamic_cast<BitsInit*>(RV->getValue()));
   BitsInit *BI =3D (BitsInit*)RV->getValue();
@@ -1333,10 +1348,10 @@
 Init *VarInit::resolveListElementReference(Record &R,
                                            const RecordVal *IRV,
                                            unsigned Elt) const {
-  if (R.isTemplateArg(getName())) return 0;
-  if (IRV && IRV->getName() !=3D getName()) return 0;
+  if (R.isTemplateArg(getNameInit())) return 0;
+  if (IRV && IRV->getNameInit() !=3D getNameInit()) return 0;
=20
-  RecordVal *RV =3D R.getValue(getName());
+  RecordVal *RV =3D R.getValue(getNameInit());
   assert(RV && "Reference to a non-existent variable?");
   ListInit *LI =3D dynamic_cast<ListInit*>(RV->getValue());
   if (!LI) {
@@ -1659,7 +1674,7 @@
=20
 void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
   if (getPrefix()) OS << "field ";
-  OS << *getType() << " " << getName();
+  OS << *getType() << " " << getNameInitAsString();
=20
   if (getValue())
     OS << " =3D " << *getValue();
@@ -1669,13 +1684,22 @@
=20
 unsigned Record::LastID =3D 0;
=20
+void Record::init() {
+  checkName();
+
+  // Every record potentially has a def at the top.  This value is
+  // replaced with the top-level def name at instantiation time.
+  RecordVal DN("NAME", StringRecTy::get(), 0);
+  addValue(DN);
+}
+
 void Record::checkName() {
   // Ensure the record name has string type.
   const TypedInit *TypedName =3D dynamic_cast<const TypedInit *>(Name);
   assert(TypedName && "Record name is not typed!");
   RecTy *Type =3D TypedName->getType();
   if (dynamic_cast<StringRecTy *>(Type) =3D=3D 0) {
-    llvm_unreachable("Record name is not a string!");
+    throw "Record name is not a string!";
   }
 }
=20
@@ -1695,20 +1719,13 @@
 void Record::setName(Init *NewName) {
   if (TrackedRecords.getDef(Name->getAsUnquotedString()) =3D=3D this) {
     TrackedRecords.removeDef(Name->getAsUnquotedString());
-    Name =3D NewName;
     TrackedRecords.addDef(this);
-  } else {
+  } else if (TrackedRecords.getClass(Name->getAsUnquotedString()) =3D=3D t=
his) {
     TrackedRecords.removeClass(Name->getAsUnquotedString());
-    Name =3D NewName;
     TrackedRecords.addClass(this);
-  }
+  }  // Otherwise this isn't yet registered.
+  Name =3D NewName;
   checkName();
-  // Since the Init for the name was changed, see if we can resolve
-  // any of it using members of the Record.
-  Init *ComputedName =3D Name->resolveReferences(*this, 0);
-  if (ComputedName !=3D Name) {
-    setName(ComputedName);
-  }
   // DO NOT resolve record values to the name at this point because
   // there might be default values for arguments of this def.  Those
   // arguments might not have been resolved yet so we don't want to
@@ -1731,17 +1748,25 @@
 /// references.
 void Record::resolveReferencesTo(const RecordVal *RV) {
   for (unsigned i =3D 0, e =3D Values.size(); i !=3D e; ++i) {
+    if (RV =3D=3D &Values[i]) // Skip resolve the same field as the given =
one
+      continue;
     if (Init *V =3D Values[i].getValue())
       Values[i].setValue(V->resolveReferences(*this, RV));
   }
+  Init *OldName =3D getNameInit();
+  Init *NewName =3D Name->resolveReferences(*this, RV);
+  if (NewName !=3D OldName) {
+    // Re-register with RecordKeeper.
+    setName(NewName);
+  }
 }
=20
 void Record::dump() const { errs() << *this; }
=20
 raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
-  OS << R.getName();
+  OS << R.getNameInitAsString();
=20
-  const std::vector<std::string> &TArgs =3D R.getTemplateArgs();
+  const std::vector<Init *> &TArgs =3D R.getTemplateArgs();
   if (!TArgs.empty()) {
     OS << "<";
     for (unsigned i =3D 0, e =3D TArgs.size(); i !=3D e; ++i) {
@@ -1758,7 +1783,7 @@
   if (!SC.empty()) {
     OS << "\t//";
     for (unsigned i =3D 0, e =3D SC.size(); i !=3D e; ++i)
-      OS << " " << SC[i]->getName();
+      OS << " " << SC[i]->getNameInitAsString();
   }
   OS << "\n";
=20
@@ -1954,18 +1979,6 @@
         "' does not have a dag initializer!";
 }
=20
-std::string Record::getValueAsCode(StringRef FieldName) const {
-  const RecordVal *R =3D getValue(FieldName);
-  if (R =3D=3D 0 || R->getValue() =3D=3D 0)
-    throw "Record `" + getName() + "' does not have a field named `" +
-      FieldName.str() + "'!\n";
-
-  if (CodeInit *CI =3D dynamic_cast<CodeInit*>(R->getValue()))
-    return CI->getValue();
-  throw "Record `" + getName() + "', field `" + FieldName.str() +
-    "' does not have a code initializer!";
-}
-
=20
 void MultiClass::dump() const {
   errs() << "Record:\n";
@@ -2017,3 +2030,39 @@
   return Defs;
 }
=20
+/// QualifyName - Return an Init with a qualifier prefix referring
+/// to CurRec's name.
+Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
+                        Init *Name, const std::string &Scoper) {
+  RecTy *Type =3D dynamic_cast<TypedInit *>(Name)->getType();
+
+  BinOpInit *NewName =3D
+    BinOpInit::get(BinOpInit::STRCONCAT,=20
+                      BinOpInit::get(BinOpInit::STRCONCAT,
+                                        CurRec.getNameInit(),
+                                        StringInit::get(Scoper),
+                                        Type)->Fold(&CurRec, CurMultiClass=
),
+                      Name,
+                      Type);
+
+  if (CurMultiClass && Scoper !=3D "::") {
+    NewName =3D
+      BinOpInit::get(BinOpInit::STRCONCAT,=20
+                        BinOpInit::get(BinOpInit::STRCONCAT,
+                                          CurMultiClass->Rec.getNameInit(),
+                                          StringInit::get("::"),
+                                          Type)->Fold(&CurRec, CurMultiCla=
ss),
+                        NewName->Fold(&CurRec, CurMultiClass),
+                        Type);
+  }
+
+  return NewName->Fold(&CurRec, CurMultiClass);
+}
+
+/// QualifyName - Return an Init with a qualifier prefix referring
+/// to CurRec's name.
+Init *llvm::QualifyName(Record &CurRec, MultiClass *CurMultiClass,
+                        const std::string &Name,
+                        const std::string &Scoper) {
+  return QualifyName(CurRec, CurMultiClass, StringInit::get(Name), Scoper);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/TableGen/TGLexer=
.cpp
--- a/head/contrib/llvm/lib/TableGen/TGLexer.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/TableGen/TGLexer.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -15,7 +15,6 @@
 #include "llvm/TableGen/Error.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Config/config.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 #include <cctype>
@@ -23,6 +22,9 @@
 #include <cstdlib>
 #include <cstring>
 #include <cerrno>
+
+#include "llvm/Config/config.h" // for strtoull()/strtoll() define
+
 using namespace llvm;
=20
 TGLexer::TGLexer(SourceMgr &SM) : SrcMgr(SM) {
@@ -80,6 +82,10 @@
   } =20
 }
=20
+int TGLexer::peekNextChar(int Index) {
+  return *(CurPtr + Index);
+}
+
 tgtok::TokKind TGLexer::LexToken() {
   TokStart =3D CurPtr;
   // This always consumes at least one character.
@@ -87,10 +93,10 @@
=20
   switch (CurChar) {
   default:
-    // Handle letters: [a-zA-Z_#]
-    if (isalpha(CurChar) || CurChar =3D=3D '_' || CurChar =3D=3D '#')
+    // Handle letters: [a-zA-Z_]
+    if (isalpha(CurChar) || CurChar =3D=3D '_')
       return LexIdentifier();
-     =20
+
     // Unknown character, emit an error.
     return ReturnError(TokStart, "Unexpected character");
   case EOF: return tgtok::Eof;
@@ -107,6 +113,7 @@
   case ')': return tgtok::r_paren;
   case '=3D': return tgtok::equal;
   case '?': return tgtok::question;
+  case '#': return tgtok::paste;
      =20
   case 0:
   case ' ':
@@ -128,8 +135,44 @@
     return LexToken();
   case '-': case '+':
   case '0': case '1': case '2': case '3': case '4': case '5': case '6':
-  case '7': case '8': case '9': =20
+  case '7': case '8': case '9': {
+    int NextChar =3D 0;
+    if (isdigit(CurChar)) {
+      // Allow identifiers to start with a number if it is followed by
+      // an identifier.  This can happen with paste operations like
+      // foo#8i.
+      int i =3D 0;
+      do {
+        NextChar =3D peekNextChar(i++);
+      } while (isdigit(NextChar));
+
+      if (NextChar =3D=3D 'x' || NextChar =3D=3D 'b') {
+        // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most
+        // likely a number.
+        int NextNextChar =3D peekNextChar(i);
+        switch (NextNextChar) {
+        default:
+          break;
+        case '0': case '1':=20
+          if (NextChar =3D=3D 'b')
+            return LexNumber();
+          // Fallthrough
+        case '2': case '3': case '4': case '5':
+        case '6': case '7': case '8': case '9':
+        case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
+        case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+          if (NextChar =3D=3D 'x')
+            return LexNumber();
+          break;
+        }
+      }
+    }
+
+    if (isalpha(NextChar) || NextChar =3D=3D '_')
+      return LexIdentifier();
+
     return LexNumber();
+  }
   case '"': return LexString();
   case '$': return LexVarName();
   case '[': return LexBracket();
@@ -210,8 +253,7 @@
   const char *IdentStart =3D TokStart;
=20
   // Match the rest of the identifier regex: [0-9a-zA-Z_#]*
-  while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr =3D=3D '_' ||
-         *CurPtr =3D=3D '#')
+  while (isalpha(*CurPtr) || isdigit(*CurPtr) || *CurPtr =3D=3D '_')
     ++CurPtr;
=20
   // Check to see if this identifier is a keyword.
@@ -232,6 +274,7 @@
     .Case("dag", tgtok::Dag)
     .Case("class", tgtok::Class)
     .Case("def", tgtok::Def)
+    .Case("foreach", tgtok::Foreach)
     .Case("defm", tgtok::Defm)
     .Case("multiclass", tgtok::MultiClass)
     .Case("field", tgtok::Field)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/TableGen/TGLexer=
.h
--- a/head/contrib/llvm/lib/TableGen/TGLexer.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/TableGen/TGLexer.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -39,9 +39,10 @@
     colon, semi,        // : ;
     comma, period,      // , .
     equal, question,    // =3D ?
-   =20
+    paste,              // #
+
     // Keywords.
-    Bit, Bits, Class, Code, Dag, Def, Defm, Field, In, Int, Let, List,
+    Bit, Bits, Class, Code, Dag, Def, Foreach, Defm, Field, In, Int, Let, =
List,
     MultiClass, String,
    =20
     // !keywords.
@@ -109,6 +110,7 @@
   tgtok::TokKind ReturnError(const char *Loc, const Twine &Msg);
  =20
   int getNextChar();
+  int peekNextChar(int Index);
   void SkipBCPLComment();
   bool SkipCComment();
   tgtok::TokKind LexIdentifier();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/TableGen/TGParse=
r.cpp
--- a/head/contrib/llvm/lib/TableGen/TGParser.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/TableGen/TGParser.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -64,7 +64,7 @@
   if (CurRec =3D=3D 0)
     CurRec =3D &CurMultiClass->Rec;
=20
-  if (RecordVal *ERV =3D CurRec->getValue(RV.getName())) {
+  if (RecordVal *ERV =3D CurRec->getValue(RV.getNameInit())) {
     // The value already exists in the class, treat this as a set.
     if (ERV->setValue(RV.getValue()))
       return Error(Loc, "New definition of '" + RV.getName() + "' of type =
'" +
@@ -79,7 +79,7 @@
=20
 /// SetValue -
 /// Return true on error, false on success.
-bool TGParser::SetValue(Record *CurRec, SMLoc Loc, const std::string &ValN=
ame,
+bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
                         const std::vector<unsigned> &BitList, Init *V) {
   if (!V) return false;
=20
@@ -87,13 +87,14 @@
=20
   RecordVal *RV =3D CurRec->getValue(ValName);
   if (RV =3D=3D 0)
-    return Error(Loc, "Value '" + ValName + "' unknown!");
+    return Error(Loc, "Value '" + ValName->getAsUnquotedString()
+                 + "' unknown!");
=20
   // Do not allow assignments like 'X =3D X'.  This will just cause infini=
te loops
   // in the resolution machinery.
   if (BitList.empty())
     if (VarInit *VI =3D dynamic_cast<VarInit*>(V))
-      if (VI->getName() =3D=3D ValName)
+      if (VI->getNameInit() =3D=3D ValName)
         return false;
=20
   // If we are assigning to a subset of the bits in the value... then we m=
ust be
@@ -103,7 +104,8 @@
   if (!BitList.empty()) {
     BitsInit *CurVal =3D dynamic_cast<BitsInit*>(RV->getValue());
     if (CurVal =3D=3D 0)
-      return Error(Loc, "Value '" + ValName + "' is not a bits type");
+      return Error(Loc, "Value '" + ValName->getAsUnquotedString()
+                   + "' is not a bits type");
=20
     // Convert the incoming value to a bits type of the appropriate size...
     Init *BI =3D V->convertInitializerTo(BitsRecTy::get(BitList.size()));
@@ -123,7 +125,7 @@
       unsigned Bit =3D BitList[i];
       if (NewBits[Bit])
         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '"=
 +
-                     ValName + "' more than once");
+                     ValName->getAsUnquotedString() + "' more than once");
       NewBits[Bit] =3D BInit->getBit(i);
     }
=20
@@ -135,9 +137,10 @@
   }
=20
   if (RV->setValue(V))
-   return Error(Loc, "Value '" + ValName + "' of type '" +
-                RV->getType()->getAsString() +
-                "' is incompatible with initializer '" + V->getAsString() =
+"'");
+    return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of t=
ype '"
+                 + RV->getType()->getAsString() +
+                 "' is incompatible with initializer '" + V->getAsString()
+                 + "'");
   return false;
 }
=20
@@ -151,7 +154,7 @@
     if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
       return true;
=20
-  const std::vector<std::string> &TArgs =3D SC->getTemplateArgs();
+  const std::vector<Init *> &TArgs =3D SC->getTemplateArgs();
=20
   // Ensure that an appropriate number of template arguments are specified.
   if (TArgs.size() < SubClass.TemplateArgs.size())
@@ -174,8 +177,8 @@
=20
     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
       return Error(SubClass.RefLoc,"Value not specified for template argum=
ent #"
-                   + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
-                   SC->getName() + "'!");
+                   + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
+                   + ") of subclass '" + SC->getNameInitAsString() + "'!");
     }
   }
=20
@@ -230,7 +233,7 @@
     CurMC->DefPrototypes.push_back(NewDef);
   }
=20
-  const std::vector<std::string> &SMCTArgs =3D SMC->Rec.getTemplateArgs();
+  const std::vector<Init *> &SMCTArgs =3D SMC->Rec.getTemplateArgs();
=20
   // Ensure that an appropriate number of template arguments are
   // specified.
@@ -278,14 +281,121 @@
     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
       return Error(SubMultiClass.RefLoc,
                    "Value not specified for template argument #"
-                   + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
-                   SMC->Rec.getName() + "'!");
+                   + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
+                   + ") of subclass '" + SMC->Rec.getNameInitAsString() + =
"'!");
     }
   }
=20
   return false;
 }
=20
+/// ProcessForeachDefs - Given a record, apply all of the variable
+/// values in all surrounding foreach loops, creating new records for
+/// each combination of values.
+bool TGParser::ProcessForeachDefs(Record *CurRec, MultiClass *CurMultiClas=
s,
+                                  SMLoc Loc) {
+  // We want to instantiate a new copy of CurRec for each combination
+  // of nested loop iterator values.  We don't want top instantiate
+  // any copies until we have values for each loop iterator.
+  IterSet IterVals;
+  for (LoopVector::iterator Loop =3D Loops.begin(), LoopEnd =3D Loops.end(=
);
+       Loop !=3D LoopEnd;
+       ++Loop) {
+    // Process this loop.
+    if (ProcessForeachDefs(CurRec, CurMultiClass, Loc,
+                           IterVals, *Loop, Loop+1)) {
+      Error(Loc,
+            "Could not process loops for def " + CurRec->getNameInitAsStri=
ng());
+      return true;
+    }
+  }
+
+  return false;
+}
+
+/// ProcessForeachDefs - Given a record, a loop and a loop iterator,
+/// apply each of the variable values in this loop and then process
+/// subloops.
+bool TGParser::ProcessForeachDefs(Record *CurRec, MultiClass *CurMultiClas=
s,
+                                  SMLoc Loc, IterSet &IterVals,
+                                  ForeachLoop &CurLoop,
+                                  LoopVector::iterator NextLoop) {
+  Init *IterVar =3D CurLoop.IterVar;
+  ListInit *List =3D dynamic_cast<ListInit *>(CurLoop.ListValue);
+
+  if (List =3D=3D 0) {
+    Error(Loc, "Loop list is not a list");
+    return true;
+  }
+
+  // Process each value.
+  for (int64_t i =3D 0; i < List->getSize(); ++i) {
+    Init *ItemVal =3D List->resolveListElementReference(*CurRec, 0, i);
+    IterVals.push_back(IterRecord(IterVar, ItemVal));
+
+    if (IterVals.size() =3D=3D Loops.size()) {
+      // Ok, we have all of the iterator values for this point in the
+      // iteration space.  Instantiate a new record to reflect this
+      // combination of values.
+      Record *IterRec =3D new Record(*CurRec);
+
+      // Set the iterator values now.
+      for (IterSet::iterator i =3D IterVals.begin(), iend =3D IterVals.end=
();
+           i !=3D iend;
+           ++i) {
+        VarInit *IterVar =3D dynamic_cast<VarInit *>(i->IterVar);
+        if (IterVar =3D=3D 0) {
+          Error(Loc, "foreach iterator is unresolved");
+          return true;
+        }
+
+        TypedInit *IVal  =3D dynamic_cast<TypedInit *>(i->IterValue);
+        if (IVal =3D=3D 0) {
+          Error(Loc, "foreach iterator value is untyped");
+          return true;
+        }
+
+        IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), f=
alse));
+
+        if (SetValue(IterRec, Loc, IterVar->getName(),
+                     std::vector<unsigned>(), IVal)) {
+          Error(Loc, "when instantiating this def");
+          return true;
+        }
+
+        // Resolve it next.
+        IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName())=
);
+
+        // Remove it.
+        IterRec->removeValue(IterVar->getName());
+      }
+
+      if (Records.getDef(IterRec->getNameInitAsString())) {
+        Error(Loc, "def already exists: " + IterRec->getNameInitAsString()=
);
+        return true;
+      }
+
+      Records.addDef(IterRec);
+      IterRec->resolveReferences();
+    }
+
+    if (NextLoop !=3D Loops.end()) {
+      // Process nested loops.
+      if (ProcessForeachDefs(CurRec, CurMultiClass, Loc, IterVals, *NextLo=
op,
+                             NextLoop+1)) {
+        Error(Loc,
+              "Could not process loops for def " +
+              CurRec->getNameInitAsString());
+        return true;
+      }
+    }
+
+    // We're done with this iterator.
+    IterVals.pop_back();
+  }
+  return false;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Parser Code
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -293,7 +403,8 @@
 /// isObjectStart - Return true if this is a valid first token for an Obje=
ct.
 static bool isObjectStart(tgtok::TokKind K) {
   return K =3D=3D tgtok::Class || K =3D=3D tgtok::Def ||
-         K =3D=3D tgtok::Defm || K =3D=3D tgtok::Let || K =3D=3D tgtok::Mu=
ltiClass;
+         K =3D=3D tgtok::Defm || K =3D=3D tgtok::Let ||
+         K =3D=3D tgtok::MultiClass || K =3D=3D tgtok::Foreach;
 }
=20
 static std::string GetNewAnonymousName() {
@@ -303,19 +414,40 @@
=20
 /// ParseObjectName - If an object name is specified, return it.  Otherwis=
e,
 /// return an anonymous name.
-///   ObjectName ::=3D ID
+///   ObjectName ::=3D Value [ '#' Value ]*
 ///   ObjectName ::=3D /*empty*/
 ///
-std::string TGParser::ParseObjectName() {
-  if (Lex.getCode() !=3D tgtok::Id)
-    return GetNewAnonymousName();
+Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
+  switch (Lex.getCode()) {
+  case tgtok::colon:
+  case tgtok::semi:
+  case tgtok::l_brace:
+    // These are all of the tokens that can begin an object body.
+    // Some of these can also begin values but we disallow those cases
+    // because they are unlikely to be useful.
+    return StringInit::get(GetNewAnonymousName());
+  default:
+    break;
+  }
=20
-  std::string Ret =3D Lex.getCurStrVal();
-  Lex.Lex();
-  return Ret;
+  Record *CurRec =3D 0;
+  if (CurMultiClass)
+    CurRec =3D &CurMultiClass->Rec;
+
+  RecTy *Type =3D 0;
+  if (CurRec) {
+    const TypedInit *CurRecName =3D
+      dynamic_cast<const TypedInit *>(CurRec->getNameInit());
+    if (!CurRecName) {
+      TokError("Record name is not typed!");
+      return 0;
+    }
+    Type =3D CurRecName->getType();
+  }
+
+  return ParseValue(CurRec, Type, ParseNameMode);
 }
=20
-
 /// ParseClassID - Parse and resolve a reference to a class name.  This re=
turns
 /// null on error.
 ///
@@ -570,11 +702,11 @@
 /// ParseType - Parse and return a tblgen type.  This returns null on erro=
r.
 ///
 ///   Type ::=3D STRING                       // string type
+///   Type ::=3D CODE                         // code type
 ///   Type ::=3D BIT                          // bit type
 ///   Type ::=3D BITS '<' INTVAL '>'          // bits<x> type
 ///   Type ::=3D INT                          // int type
 ///   Type ::=3D LIST '<' Type '>'            // list<x> type
-///   Type ::=3D CODE                         // code type
 ///   Type ::=3D DAG                          // dag type
 ///   Type ::=3D ClassID                      // Record Type
 ///
@@ -582,9 +714,9 @@
   switch (Lex.getCode()) {
   default: TokError("Unknown token when expecting a type"); return 0;
   case tgtok::String: Lex.Lex(); return StringRecTy::get();
+  case tgtok::Code:   Lex.Lex(); return StringRecTy::get();
   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
-  case tgtok::Code:   Lex.Lex(); return CodeRecTy::get();
   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
   case tgtok::Id:
     if (Record *R =3D ParseClassID()) return RecordRecTy::get(R);
@@ -633,7 +765,7 @@
 ///  IDValue ::=3D ID [multiclass template argument]
 ///  IDValue ::=3D ID [def name]
 ///
-Init *TGParser::ParseIDValue(Record *CurRec) {
+Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
   assert(Lex.getCode() =3D=3D tgtok::Id && "Expected ID in ParseIDValue");
   std::string Name =3D Lex.getCurStrVal();
   SMLoc Loc =3D Lex.getLoc();
@@ -644,14 +776,17 @@
 /// ParseIDValue - This is just like ParseIDValue above, but it assumes th=
e ID
 /// has already been read.
 Init *TGParser::ParseIDValue(Record *CurRec,
-                             const std::string &Name, SMLoc NameLoc) {
+                             const std::string &Name, SMLoc NameLoc,
+                             IDParseMode Mode) {
   if (CurRec) {
     if (const RecordVal *RV =3D CurRec->getValue(Name))
       return VarInit::get(Name, RV->getType());
=20
-    std::string TemplateArgName =3D CurRec->getName()+":"+Name;
+    Init *TemplateArgName =3D QualifyName(*CurRec, CurMultiClass, Name, ":=
");
+
     if (CurMultiClass)
-      TemplateArgName =3D CurMultiClass->Rec.getName()+"::"+TemplateArgNam=
e;
+      TemplateArgName =3D QualifyName(CurMultiClass->Rec, CurMultiClass, N=
ame,
+                                    "::");
=20
     if (CurRec->isTemplateArg(TemplateArgName)) {
       const RecordVal *RV =3D CurRec->getValue(TemplateArgName);
@@ -661,7 +796,9 @@
   }
=20
   if (CurMultiClass) {
-    std::string MCName =3D CurMultiClass->Rec.getName()+"::"+Name;
+    Init *MCName =3D QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
+                               "::");
+
     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
       const RecordVal *RV =3D CurMultiClass->Rec.getValue(MCName);
       assert(RV && "Template arg doesn't exist??");
@@ -669,11 +806,27 @@
     }
   }
=20
+  // If this is in a foreach loop, make sure it's not a loop iterator
+  for (LoopVector::iterator i =3D Loops.begin(), iend =3D Loops.end();
+       i !=3D iend;
+       ++i) {
+    VarInit *IterVar =3D dynamic_cast<VarInit *>(i->IterVar);
+    if (IterVar && IterVar->getName() =3D=3D Name)
+      return IterVar;
+  }
+
+  if (Mode =3D=3D ParseNameMode)
+    return StringInit::get(Name);
+
   if (Record *D =3D Records.getDef(Name))
     return DefInit::get(D);
=20
-  Error(NameLoc, "Variable not defined: '" + Name + "'");
-  return 0;
+  if (Mode =3D=3D ParseValueMode) {
+    Error(NameLoc, "Variable not defined: '" + Name + "'");
+    return 0;
+  }
+ =20
+  return StringInit::get(Name);
 }
=20
 /// ParseOperation - Parse an operator.  This returns null on error.
@@ -685,7 +838,6 @@
   default:
     TokError("unknown operation");
     return 0;
-    break;
   case tgtok::XHead:
   case tgtok::XTail:
   case tgtok::XEmpty:
@@ -694,7 +846,7 @@
     RecTy *Type =3D 0;
=20
     switch (Lex.getCode()) {
-    default: assert(0 && "Unhandled code!");
+    default: llvm_unreachable("Unhandled code!");
     case tgtok::XCast:
       Lex.Lex();  // eat the operation
       Code =3D UnOpInit::CAST;
@@ -810,7 +962,7 @@
     RecTy *Type =3D 0;
=20
     switch (OpTok) {
-    default: assert(0 && "Unhandled code!");
+    default: llvm_unreachable("Unhandled code!");
     case tgtok::XConcat: Code =3D BinOpInit::CONCAT;Type =3D DagRecTy::get=
(); break;
     case tgtok::XSRA:    Code =3D BinOpInit::SRA;   Type =3D IntRecTy::get=
(); break;
     case tgtok::XSRL:    Code =3D BinOpInit::SRL;   Type =3D IntRecTy::get=
(); break;
@@ -874,7 +1026,7 @@
     tgtok::TokKind LexCode =3D Lex.getCode();
     Lex.Lex();  // eat the operation
     switch (LexCode) {
-    default: assert(0 && "Unhandled code!");
+    default: llvm_unreachable("Unhandled code!");
     case tgtok::XIf:
       Code =3D TernOpInit::IF;
       break;
@@ -919,7 +1071,7 @@
     Lex.Lex();  // eat the ')'
=20
     switch (LexCode) {
-    default: assert(0 && "Unhandled code!");
+    default: llvm_unreachable("Unhandled code!");
     case tgtok::XIf: {
       // FIXME: The `!if' operator doesn't handle non-TypedInit well at
       // all. This can be made much more robust.
@@ -989,8 +1141,6 @@
                                                              CurMultiClass=
);
   }
   }
-  TokError("could not parse operation");
-  return 0;
 }
=20
 /// ParseOperatorType - Parse a type for an operator.  This returns
@@ -1041,10 +1191,16 @@
 ///   SimpleValue ::=3D SRLTOK '(' Value ',' Value ')'
 ///   SimpleValue ::=3D STRCONCATTOK '(' Value ',' Value ')'
 ///
-Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
+Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
+                                 IDParseMode Mode) {
   Init *R =3D 0;
   switch (Lex.getCode()) {
   default: TokError("Unknown token when parsing a value"); break;
+  case tgtok::paste:
+    // This is a leading paste operation.  This is deprecated but
+    // still exists in some .td files.  Ignore it.
+    Lex.Lex();  // Skip '#'.
+    return ParseSimpleValue(CurRec, ItemType, Mode);
   case tgtok::IntVal: R =3D IntInit::get(Lex.getCurIntVal()); Lex.Lex(); b=
reak;
   case tgtok::StrVal: {
     std::string Val =3D Lex.getCurStrVal();
@@ -1060,7 +1216,7 @@
     break;
   }
   case tgtok::CodeFragment:
-    R =3D CodeInit::get(Lex.getCurStrVal());
+    R =3D StringInit::get(Lex.getCurStrVal());
     Lex.Lex();
     break;
   case tgtok::question:
@@ -1071,7 +1227,7 @@
     SMLoc NameLoc =3D Lex.getLoc();
     std::string Name =3D Lex.getCurStrVal();
     if (Lex.Lex() !=3D tgtok::less)  // consume the Id.
-      return ParseIDValue(CurRec, Name, NameLoc);    // Value ::=3D IDValue
+      return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::=3D =
IDValue
=20
     // Value ::=3D ID '<' ValueListNE '>'
     if (Lex.Lex() =3D=3D tgtok::greater) {
@@ -1305,8 +1461,8 @@
 ///   ValueSuffix ::=3D '[' BitList ']'
 ///   ValueSuffix ::=3D '.' ID
 ///
-Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
-  Init *Result =3D ParseSimpleValue(CurRec, ItemType);
+Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mo=
de) {
+  Init *Result =3D ParseSimpleValue(CurRec, ItemType, Mode);
   if (Result =3D=3D 0) return 0;
=20
   // Parse the suffixes now if present.
@@ -1314,6 +1470,10 @@
     switch (Lex.getCode()) {
     default: return Result;
     case tgtok::l_brace: {
+      if (Mode =3D=3D ParseNameMode || Mode =3D=3D ParseForeachMode)
+        // This is the beginning of the object body.
+        return Result;
+
       SMLoc CurlyLoc =3D Lex.getLoc();
       Lex.Lex(); // eat the '{'
       std::vector<unsigned> Ranges =3D ParseRangeList();
@@ -1368,6 +1528,56 @@
       Result =3D FieldInit::get(Result, Lex.getCurStrVal());
       Lex.Lex();  // eat field name
       break;
+
+    case tgtok::paste:
+      SMLoc PasteLoc =3D Lex.getLoc();
+
+      // Create a !strconcat() operation, first casting each operand to
+      // a string if necessary.
+
+      TypedInit *LHS =3D dynamic_cast<TypedInit *>(Result);
+      if (!LHS) {
+        Error(PasteLoc, "LHS of paste is not typed!");
+        return 0;
+      }
+ =20
+      if (LHS->getType() !=3D StringRecTy::get()) {
+        LHS =3D UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
+      }
+
+      TypedInit *RHS =3D 0;
+
+      Lex.Lex();  // Eat the '#'.
+      switch (Lex.getCode()) {=20
+      case tgtok::colon:
+      case tgtok::semi:
+      case tgtok::l_brace:
+        // These are all of the tokens that can begin an object body.
+        // Some of these can also begin values but we disallow those cases
+        // because they are unlikely to be useful.
+      =20
+        // Trailing paste, concat with an empty string.
+        RHS =3D StringInit::get("");
+        break;
+
+      default:
+        Init *RHSResult =3D ParseValue(CurRec, ItemType, ParseNameMode);
+        RHS =3D dynamic_cast<TypedInit *>(RHSResult);
+        if (!RHS) {
+          Error(PasteLoc, "RHS of paste is not typed!");
+          return 0;
+        }
+
+        if (RHS->getType() !=3D StringRecTy::get()) {
+          RHS =3D UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
+        }
+ =20
+        break;
+      }
+
+      Result =3D BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
+                              StringRecTy::get())->Fold(CurRec, CurMultiCl=
ass);
+      break;
     }
   }
 }
@@ -1417,7 +1627,11 @@
   RecTy *ItemType =3D EltTy;
   unsigned int ArgN =3D 0;
   if (ArgsRec !=3D 0 && EltTy =3D=3D 0) {
-    const std::vector<std::string> &TArgs =3D ArgsRec->getTemplateArgs();
+    const std::vector<Init *> &TArgs =3D ArgsRec->getTemplateArgs();
+    if (!TArgs.size()) {
+      TokError("template argument provided to non-template class");
+      return std::vector<Init*>();
+    }
     const RecordVal *RV =3D ArgsRec->getValue(TArgs[ArgN]);
     if (!RV) {
       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
@@ -1434,7 +1648,7 @@
     Lex.Lex();  // Eat the comma
=20
     if (ArgsRec !=3D 0 && EltTy =3D=3D 0) {
-      const std::vector<std::string> &TArgs =3D ArgsRec->getTemplateArgs();
+      const std::vector<Init *> &TArgs =3D ArgsRec->getTemplateArgs();
       if (ArgN >=3D TArgs.size()) {
         TokError("too many template arguments");
         return std::vector<Init*>();
@@ -1462,37 +1676,38 @@
 ///
 ///  Declaration ::=3D FIELD? Type ID ('=3D' Value)?
 ///
-std::string TGParser::ParseDeclaration(Record *CurRec,
+Init *TGParser::ParseDeclaration(Record *CurRec,
                                        bool ParsingTemplateArgs) {
   // Read the field prefix if present.
   bool HasField =3D Lex.getCode() =3D=3D tgtok::Field;
   if (HasField) Lex.Lex();
=20
   RecTy *Type =3D ParseType();
-  if (Type =3D=3D 0) return "";
+  if (Type =3D=3D 0) return 0;
=20
   if (Lex.getCode() !=3D tgtok::Id) {
     TokError("Expected identifier in declaration");
-    return "";
+    return 0;
   }
=20
   SMLoc IdLoc =3D Lex.getLoc();
-  std::string DeclName =3D Lex.getCurStrVal();
+  Init *DeclName =3D StringInit::get(Lex.getCurStrVal());
   Lex.Lex();
=20
   if (ParsingTemplateArgs) {
     if (CurRec) {
-      DeclName =3D CurRec->getName() + ":" + DeclName;
+      DeclName =3D QualifyName(*CurRec, CurMultiClass, DeclName, ":");
     } else {
       assert(CurMultiClass);
     }
     if (CurMultiClass)
-      DeclName =3D CurMultiClass->Rec.getName() + "::" + DeclName;
+      DeclName =3D QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
+                             "::");
   }
=20
   // Add the value.
   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
-    return "";
+    return 0;
=20
   // If a value is present, parse it.
   if (Lex.getCode() =3D=3D tgtok::equal) {
@@ -1501,12 +1716,56 @@
     Init *Val =3D ParseValue(CurRec, Type);
     if (Val =3D=3D 0 ||
         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
-      return "";
+      return 0;
   }
=20
   return DeclName;
 }
=20
+/// ParseForeachDeclaration - Read a foreach declaration, returning
+/// the name of the declared object or a NULL Init on error.  Return
+/// the name of the parsed initializer list through ForeachListName.
+///
+///  ForeachDeclaration ::=3D ID '=3D' Value
+///
+Init *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
+  if (Lex.getCode() !=3D tgtok::Id) {
+    TokError("Expected identifier in foreach declaration");
+    return 0;
+  }
+
+  Init *DeclName =3D StringInit::get(Lex.getCurStrVal());
+  Lex.Lex();
+
+  // If a value is present, parse it.
+  if (Lex.getCode() !=3D tgtok::equal) {
+    TokError("Expected '=3D' in foreach declaration");
+    return 0;
+  }
+  Lex.Lex();  // Eat the '=3D'
+
+  // Expect a list initializer.
+  ForeachListValue =3D ParseValue(0, 0, ParseForeachMode);
+
+  TypedInit *TypedList =3D dynamic_cast<TypedInit *>(ForeachListValue);
+  if (TypedList =3D=3D 0) {
+    TokError("Value list is untyped");
+    return 0;
+  }
+
+  RecTy *ValueType =3D TypedList->getType();
+  ListRecTy *ListType =3D dynamic_cast<ListRecTy *>(ValueType);
+  if (ListType =3D=3D 0) {
+    TokError("Value list is not of list type");
+    return 0;
+  }
+
+  RecTy *IterType =3D ListType->getElementType();
+  VarInit *IterVar =3D VarInit::get(DeclName, IterType);
+
+  return IterVar;
+}
+
 /// ParseTemplateArgList - Read a template argument list, which is a non-e=
mpty
 /// sequence of template-declarations in <>'s.  If CurRec is non-null, the=
se are
 /// template args for a def, which may or may not be in a multiclass.  If =
null,
@@ -1521,8 +1780,8 @@
   Record *TheRecToAddTo =3D CurRec ? CurRec : &CurMultiClass->Rec;
=20
   // Read the first declaration.
-  std::string TemplArg =3D ParseDeclaration(CurRec, true/*templateargs*/);
-  if (TemplArg.empty())
+  Init *TemplArg =3D ParseDeclaration(CurRec, true/*templateargs*/);
+  if (TemplArg =3D=3D 0)
     return true;
=20
   TheRecToAddTo->addTemplateArg(TemplArg);
@@ -1532,7 +1791,7 @@
=20
     // Read the following declarations.
     TemplArg =3D ParseDeclaration(CurRec, true/*templateargs*/);
-    if (TemplArg.empty())
+    if (TemplArg =3D=3D 0)
       return true;
     TheRecToAddTo->addTemplateArg(TemplArg);
   }
@@ -1550,7 +1809,7 @@
 ///   BodyItem ::=3D LET ID OptionalBitList '=3D' Value ';'
 bool TGParser::ParseBodyItem(Record *CurRec) {
   if (Lex.getCode() !=3D tgtok::Let) {
-    if (ParseDeclaration(CurRec, false).empty())
+    if (ParseDeclaration(CurRec, false) =3D=3D 0)
       return true;
=20
     if (Lex.getCode() !=3D tgtok::semi)
@@ -1671,22 +1930,24 @@
   Lex.Lex();  // Eat the 'def' token.
=20
   // Parse ObjectName and make a record for it.
-  Record *CurRec =3D new Record(ParseObjectName(), DefLoc, Records);
+  Record *CurRec =3D new Record(ParseObjectName(CurMultiClass), DefLoc, Re=
cords);
=20
   if (!CurMultiClass) {
     // Top-level def definition.
=20
     // Ensure redefinition doesn't happen.
-    if (Records.getDef(CurRec->getName())) {
-      Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
+    if (Records.getDef(CurRec->getNameInitAsString())) {
+      Error(DefLoc, "def '" + CurRec->getNameInitAsString()
+            + "' already defined");
       return true;
     }
     Records.addDef(CurRec);
   } else {
     // Otherwise, a def inside a multiclass, add it to the multiclass.
     for (unsigned i =3D 0, e =3D CurMultiClass->DefPrototypes.size(); i !=
=3D e; ++i)
-      if (CurMultiClass->DefPrototypes[i]->getName() =3D=3D CurRec->getNam=
e()) {
-        Error(DefLoc, "def '" + CurRec->getName() +
+      if (CurMultiClass->DefPrototypes[i]->getNameInit()
+          =3D=3D CurRec->getNameInit()) {
+        Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
               "' already defined in this multiclass!");
         return true;
       }
@@ -1707,7 +1968,7 @@
=20
   if (CurMultiClass) {
     // Copy the template arguments for the multiclass into the def.
-    const std::vector<std::string> &TArgs =3D
+    const std::vector<Init *> &TArgs =3D
                                 CurMultiClass->Rec.getTemplateArgs();
=20
     for (unsigned i =3D 0, e =3D TArgs.size(); i !=3D e; ++i) {
@@ -1717,6 +1978,63 @@
     }
   }
=20
+  if (ProcessForeachDefs(CurRec, CurMultiClass, DefLoc)) {
+    Error(DefLoc,
+          "Could not process loops for def" + CurRec->getNameInitAsString(=
));
+    return true;
+  }
+
+  return false;
+}
+
+/// ParseForeach - Parse a for statement.  Return the record corresponding
+/// to it.  This returns true on error.
+///
+///   Foreach ::=3D FOREACH Declaration IN '{ ObjectList '}'
+///   Foreach ::=3D FOREACH Declaration IN Object
+///
+bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
+  assert(Lex.getCode() =3D=3D tgtok::Foreach && "Unknown tok");
+  Lex.Lex();  // Eat the 'for' token.
+
+  // Make a temporary object to record items associated with the for
+  // loop.
+  Init *ListValue =3D 0;
+  Init *IterName =3D ParseForeachDeclaration(ListValue);
+  if (IterName =3D=3D 0)
+    return TokError("expected declaration in for");
+
+  if (Lex.getCode() !=3D tgtok::In)
+    return TokError("Unknown tok");
+  Lex.Lex();  // Eat the in
+
+  // Create a loop object and remember it.
+  Loops.push_back(ForeachLoop(IterName, ListValue));
+
+  if (Lex.getCode() !=3D tgtok::l_brace) {
+    // FOREACH Declaration IN Object
+    if (ParseObject(CurMultiClass))
+      return true;
+  }
+  else {
+    SMLoc BraceLoc =3D Lex.getLoc();
+    // Otherwise, this is a group foreach.
+    Lex.Lex();  // eat the '{'.
+
+    // Parse the object list.
+    if (ParseObjectList(CurMultiClass))
+      return true;
+
+    if (Lex.getCode() !=3D tgtok::r_brace) {
+      TokError("expected '}' at end of foreach command");
+      return Error(BraceLoc, "to match this '{'");
+    }
+    Lex.Lex();  // Eat the }
+  }
+
+  // We've processed everything in this loop.
+  Loops.pop_back();
+
   return false;
 }
=20
@@ -1734,10 +2052,11 @@
   Record *CurRec =3D Records.getClass(Lex.getCurStrVal());
   if (CurRec) {
     // If the body was previously defined, this is an error.
-    if (!CurRec->getValues().empty() ||
+    if (CurRec->getValues().size() > 1 ||  // Account for NAME.
         !CurRec->getSuperClasses().empty() ||
         !CurRec->getTemplateArgs().empty())
-      return TokError("Class '" + CurRec->getName() + "' already defined");
+      return TokError("Class '" + CurRec->getNameInitAsString()
+                      + "' already defined");
   } else {
     // If this is the first reference to this class, create and add it.
     CurRec =3D new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
@@ -1909,6 +2228,7 @@
         case tgtok::Let:
         case tgtok::Def:
         case tgtok::Defm:
+        case tgtok::Foreach:
           if (ParseObject(CurMultiClass))
             return true;
          break;
@@ -1924,23 +2244,31 @@
 Record *TGParser::
 InstantiateMulticlassDef(MultiClass &MC,
                          Record *DefProto,
-                         const std::string &DefmPrefix,
+                         Init *DefmPrefix,
                          SMLoc DefmPrefixLoc) {
+  // We need to preserve DefProto so it can be reused for later
+  // instantiations, so create a new Record to inherit from it.
+
   // Add in the defm name.  If the defm prefix is empty, give each
   // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
   // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
   // as a prefix.
-  std::string DefName =3D DefProto->getName();
-  if (DefmPrefix.empty()) {
-    DefName =3D GetNewAnonymousName();
-  } else {
-    std::string::size_type idx =3D DefName.find("#NAME#");
-    if (idx !=3D std::string::npos) {
-      DefName.replace(idx, 6, DefmPrefix);
-    } else {
-      // Add the suffix to the defm name to get the new name.
-      DefName =3D DefmPrefix + DefName;
-    }
+
+  if (DefmPrefix =3D=3D 0)
+    DefmPrefix =3D StringInit::get(GetNewAnonymousName());
+
+  Init *DefName =3D DefProto->getNameInit();
+
+  StringInit *DefNameString =3D dynamic_cast<StringInit *>(DefName);
+
+  if (DefNameString !=3D 0) {
+    // We have a fully expanded string so there are no operators to
+    // resolve.  We should concatenate the given prefix and name.
+    DefName =3D
+      BinOpInit::get(BinOpInit::STRCONCAT,
+                     UnOpInit::get(UnOpInit::CAST, DefmPrefix,
+                                   StringRecTy::get())->Fold(DefProto, &MC=
),
+                     DefName, StringRecTy::get())->Fold(DefProto, &MC);
   }
=20
   Record *CurRec =3D new Record(DefName, DefmPrefixLoc, Records);
@@ -1950,6 +2278,41 @@
   Ref.Rec =3D DefProto;
   AddSubClass(CurRec, Ref);
=20
+  if (DefNameString =3D=3D 0) {
+    // We must resolve references to NAME.
+    if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
+                 DefmPrefix)) {
+      Error(DefmPrefixLoc, "Could not resolve "
+            + CurRec->getNameInitAsString() + ":NAME to '"
+            + DefmPrefix->getAsUnquotedString() + "'");
+      return 0;
+    }
+
+    RecordVal *DefNameRV =3D CurRec->getValue("NAME");
+    CurRec->resolveReferencesTo(DefNameRV);
+  }
+
+  if (!CurMultiClass) {
+    // We do this after resolving NAME because before resolution, many
+    // multiclass defs will have the same name expression.  If we are
+    // currently in a multiclass, it means this defm appears inside a
+    // multiclass and its name won't be fully resolvable until we see
+    // the top-level defm.  Therefore, we don't add this to the
+    // RecordKeeper at this point.  If we did we could get duplicate
+    // defs as more than one probably refers to NAME or some other
+    // common internal placeholder.
+
+    // Ensure redefinition doesn't happen.
+    if (Records.getDef(CurRec->getNameInitAsString())) {
+      Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() +=20
+            "' already defined, instantiating defm with subdef '" +=20
+            DefProto->getNameInitAsString() + "'");
+      return 0;
+    }
+
+    Records.addDef(CurRec);
+  }
+
   return CurRec;
 }
=20
@@ -1957,7 +2320,7 @@
                                         Record *CurRec,
                                         SMLoc DefmPrefixLoc,
                                         SMLoc SubClassLoc,
-                                        const std::vector<std::string> &TA=
rgs,
+                                        const std::vector<Init *> &TArgs,
                                         std::vector<Init *> &TemplateVals,
                                         bool DeleteArgs) {
   // Loop over all of the template arguments, setting them to the specified
@@ -1979,8 +2342,9 @@
        =20
     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
       return Error(SubClassLoc, "value not specified for template argument=
 #"+
-                   utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
-                   MC.Rec.getName() + "'");
+                   utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
+                   + ") of multiclassclass '" + MC.Rec.getNameInitAsString=
()
+                   + "'");
     }
   }
   return false;
@@ -1997,25 +2361,20 @@
                    LetStack[i][j].Bits, LetStack[i][j].Value))
         return Error(DefmPrefixLoc, "when instantiating this defm");
=20
-  // Ensure redefinition doesn't happen.
-  if (Records.getDef(CurRec->getName()))
-    return Error(DefmPrefixLoc, "def '" + CurRec->getName() +=20
-                 "' already defined, instantiating defm with subdef '" +=20
-                 DefProto->getName() + "'");
-
   // Don't create a top level definition for defm inside multiclasses,
   // instead, only update the prototypes and bind the template args
   // with the new created definition.
   if (CurMultiClass) {
     for (unsigned i =3D 0, e =3D CurMultiClass->DefPrototypes.size();
          i !=3D e; ++i)
-      if (CurMultiClass->DefPrototypes[i]->getName() =3D=3D CurRec->getNam=
e())
-        return Error(DefmPrefixLoc, "defm '" + CurRec->getName() +
+      if (CurMultiClass->DefPrototypes[i]->getNameInit()
+          =3D=3D CurRec->getNameInit())
+        return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString=
() +
                      "' already defined in this multiclass!");
     CurMultiClass->DefPrototypes.push_back(CurRec);
=20
     // Copy the template arguments for the multiclass into the new def.
-    const std::vector<std::string> &TA =3D
+    const std::vector<Init *> &TA =3D
       CurMultiClass->Rec.getTemplateArgs();
=20
     for (unsigned i =3D 0, e =3D TA.size(); i !=3D e; ++i) {
@@ -2023,8 +2382,6 @@
       assert(RV && "Template arg doesn't exist?");
       CurRec->addValue(*RV);
     }
-  } else {
-    Records.addDef(CurRec);
   }
=20
   return false;
@@ -2037,10 +2394,10 @@
 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
   assert(Lex.getCode() =3D=3D tgtok::Defm && "Unexpected token!");
=20
-  std::string DefmPrefix;
+  Init *DefmPrefix =3D 0;
+
   if (Lex.Lex() =3D=3D tgtok::Id) {  // eat the defm.
-    DefmPrefix =3D Lex.getCurStrVal();
-    Lex.Lex();  // Eat the defm prefix.
+    DefmPrefix =3D ParseObjectName(CurMultiClass);
   }
=20
   SMLoc DefmPrefixLoc =3D Lex.getLoc();
@@ -2070,7 +2427,7 @@
     std::vector<Init*> &TemplateVals =3D Ref.TemplateArgs;
=20
     // Verify that the correct number of template arguments were specified.
-    const std::vector<std::string> &TArgs =3D MC->Rec.getTemplateArgs();
+    const std::vector<Init *> &TArgs =3D MC->Rec.getTemplateArgs();
     if (TArgs.size() < TemplateVals.size())
       return Error(SubClassLoc,
                    "more template args specified than multiclass expects");
@@ -2080,6 +2437,8 @@
       Record *DefProto =3D MC->DefPrototypes[i];
=20
       Record *CurRec =3D InstantiateMulticlassDef(*MC, DefProto, DefmPrefi=
x, DefmPrefixLoc);
+      if (!CurRec)
+        return true;
=20
       if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
                                    TArgs, TemplateVals, true/*Delete args*=
/))
@@ -2165,6 +2524,7 @@
     return TokError("Expected class, def, defm, multiclass or let definiti=
on");
   case tgtok::Let:   return ParseTopLevelLet(MC);
   case tgtok::Def:   return ParseDef(MC);
+  case tgtok::Foreach:   return ParseForeach(MC);
   case tgtok::Defm:  return ParseDefm(MC);
   case tgtok::Class: return ParseClass();
   case tgtok::MultiClass: return ParseMultiClass();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/TableGen/TGParse=
r.h
--- a/head/contrib/llvm/lib/TableGen/TGParser.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/TableGen/TGParser.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -14,6 +14,7 @@
 #ifndef TGPARSER_H
 #define TGPARSER_H
=20
+#include "llvm/TableGen/Record.h"
 #include "TGLexer.h"
 #include "llvm/TableGen/Error.h"
 #include "llvm/ADT/Twine.h"
@@ -41,17 +42,44 @@
     }
   };
  =20
+  /// ForeachLoop - Record the iteration state associated with a for loop.
+  /// This is used to instantiate items in the loop body.
+  struct ForeachLoop {
+    Init *IterVar;
+    Init *ListValue;
+
+    ForeachLoop(Init *IVar, Init *LValue) : IterVar(IVar), ListValue(LValu=
e) {}
+  };
+
 class TGParser {
   TGLexer Lex;
   std::vector<std::vector<LetRecord> > LetStack;
   std::map<std::string, MultiClass*> MultiClasses;
  =20
+  /// Loops - Keep track of any foreach loops we are within.
+  ///
+  typedef std::vector<ForeachLoop> LoopVector;
+  LoopVector Loops;
+
   /// CurMultiClass - If we are parsing a 'multiclass' definition, this is=
 the=20
   /// current value.
   MultiClass *CurMultiClass;
=20
   // Record tracker
   RecordKeeper &Records;
+
+  // A "named boolean" indicating how to parse identifiers.  Usually
+  // identifiers map to some existing object but in special cases
+  // (e.g. parsing def names) no such object exists yet because we are
+  // in the middle of creating in.  For those situations, allow the
+  // parser to ignore missing object errors.
+  enum IDParseMode {
+    ParseValueMode,   // We are parsing a value we expect to look up.
+    ParseNameMode,    // We are parsing a name of an object that does not =
yet
+                      // exist.
+    ParseForeachMode  // We are parsing a foreach init.
+  };
+
 public:
   TGParser(SourceMgr &SrcMgr, RecordKeeper &records) :=20
     Lex(SrcMgr), CurMultiClass(0), Records(records) {}
@@ -70,14 +98,36 @@
   const std::vector<std::string> &getDependencies() const {
     return Lex.getDependencies();
   }
+
 private:  // Semantic analysis methods.
   bool AddValue(Record *TheRec, SMLoc Loc, const RecordVal &RV);
+  bool SetValue(Record *TheRec, SMLoc Loc, Init *ValName,=20
+                const std::vector<unsigned> &BitList, Init *V);
   bool SetValue(Record *TheRec, SMLoc Loc, const std::string &ValName,=20
-                const std::vector<unsigned> &BitList, Init *V);
+                const std::vector<unsigned> &BitList, Init *V) {
+    return SetValue(TheRec, Loc, StringInit::get(ValName), BitList, V);
+  }
   bool AddSubClass(Record *Rec, SubClassReference &SubClass);
   bool AddSubMultiClass(MultiClass *CurMC,
                         SubMultiClassReference &SubMultiClass);
=20
+  // IterRecord: Map an iterator name to a value.
+  struct IterRecord {
+    Init *IterVar;
+    Init *IterValue;
+    IterRecord(Init *Var, Init *Val) : IterVar(Var), IterValue(Val) {}
+  };
+
+  // IterSet: The set of all iterator values at some point in the
+  // iteration space.
+  typedef std::vector<IterRecord> IterSet;
+
+  bool ProcessForeachDefs(Record *CurRec, MultiClass *CurMultiClass,
+                          SMLoc Loc);
+  bool ProcessForeachDefs(Record *CurRec, MultiClass *CurMultiClass,
+                          SMLoc Loc, IterSet &IterVals, ForeachLoop &CurLo=
op,
+                          LoopVector::iterator NextLoop);
+
 private:  // Parser methods.
   bool ParseObjectList(MultiClass *MC =3D 0);
   bool ParseObject(MultiClass *MC);
@@ -85,13 +135,13 @@
   bool ParseMultiClass();
   Record *InstantiateMulticlassDef(MultiClass &MC,
                                    Record *DefProto,
-                                   const std::string &DefmPrefix,
+                                   Init *DefmPrefix,
                                    SMLoc DefmPrefixLoc);
   bool ResolveMulticlassDefArgs(MultiClass &MC,
                                 Record *DefProto,
                                 SMLoc DefmPrefixLoc,
                                 SMLoc SubClassLoc,
-                                const std::vector<std::string> &TArgs,
+                                const std::vector<Init *> &TArgs,
                                 std::vector<Init *> &TemplateVals,
                                 bool DeleteArgs);
   bool ResolveMulticlassDef(MultiClass &MC,
@@ -100,6 +150,7 @@
                             SMLoc DefmPrefixLoc);
   bool ParseDefm(MultiClass *CurMultiClass);
   bool ParseDef(MultiClass *CurMultiClass);
+  bool ParseForeach(MultiClass *CurMultiClass);
   bool ParseTopLevelLet(MultiClass *CurMultiClass);
   std::vector<LetRecord> ParseLetList();
=20
@@ -108,15 +159,19 @@
   bool ParseBodyItem(Record *CurRec);
=20
   bool ParseTemplateArgList(Record *CurRec);
-  std::string ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
+  Init *ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
+  Init *ParseForeachDeclaration(Init *&ForeachListValue);
=20
   SubClassReference ParseSubClassReference(Record *CurRec, bool isDefm);
   SubMultiClassReference ParseSubMultiClassReference(MultiClass *CurMC);
=20
-  Init *ParseIDValue(Record *CurRec);
-  Init *ParseIDValue(Record *CurRec, const std::string &Name, SMLoc NameLo=
c);
-  Init *ParseSimpleValue(Record *CurRec, RecTy *ItemType =3D 0);
-  Init *ParseValue(Record *CurRec, RecTy *ItemType =3D 0);
+  Init *ParseIDValue(Record *CurRec, IDParseMode Mode =3D ParseValueMode);
+  Init *ParseIDValue(Record *CurRec, const std::string &Name, SMLoc NameLo=
c,
+                     IDParseMode Mode =3D ParseValueMode);
+  Init *ParseSimpleValue(Record *CurRec, RecTy *ItemType =3D 0,
+                         IDParseMode Mode =3D ParseValueMode);
+  Init *ParseValue(Record *CurRec, RecTy *ItemType =3D 0,
+                   IDParseMode Mode =3D ParseValueMode);
   std::vector<Init*> ParseValueList(Record *CurRec, Record *ArgsRec =3D 0,=
 RecTy *EltTy =3D 0);
   std::vector<std::pair<llvm::Init*, std::string> > ParseDagArgList(Record=
 *);
   bool ParseOptionalRangeList(std::vector<unsigned> &Ranges);
@@ -126,7 +181,7 @@
   RecTy *ParseType();
   Init *ParseOperation(Record *CurRec);
   RecTy *ParseOperatorType();
-  std::string ParseObjectName();
+  Init *ParseObjectName(MultiClass *CurMultiClass);
   Record *ParseClassID();
   MultiClass *ParseMultiClassID();
   Record *ParseDefmID();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/TableGen/TableGe=
nBackend.cpp
--- a/head/contrib/llvm/lib/TableGen/TableGenBackend.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/TableGen/TableGenBackend.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,7 +15,9 @@
 #include "llvm/TableGen/Record.h"
 using namespace llvm;
=20
-void TableGenBackend::EmitSourceFileHeader(const std::string &Desc,
+void TableGenBackend::anchor() { }
+
+void TableGenBackend::EmitSourceFileHeader(StringRef Desc,
                                            raw_ostream &OS) const {
   OS << "//=3D=3D=3D- TableGen'erated file -------------------------------=
------*-"
        " C++ -*-=3D=3D=3D//\n//\n// " << Desc << "\n//\n// Automatically g=
enerate"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARM.h
--- a/head/contrib/llvm/lib/Target/ARM/ARM.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARM.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARM.h - Top-level interface for ARM representation---- --*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARM.h - Top-level interface for ARM representation ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,9 +18,7 @@
 #include "MCTargetDesc/ARMBaseInfo.h"
 #include "MCTargetDesc/ARMMCTargetDesc.h"
 #include "llvm/Support/DataTypes.h"
-#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Target/TargetMachine.h"
-#include <cassert>
=20
 namespace llvm {
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARM.td
--- a/head/contrib/llvm/lib/Target/ARM/ARM.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARM.td	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARM.td - Describe the ARM Target Machine ------------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- ARM.td - Describe the ARM Target Machine -----------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,9 +23,6 @@
 def ModeThumb  : SubtargetFeature<"thumb-mode", "InThumbMode", "true",
                                   "Thumb mode">;
=20
-def ModeNaCl   : SubtargetFeature<"nacl-mode", "InNaClMode", "true",
-                                  "Native client mode">;
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ARM Subtarget features.
 //
@@ -35,6 +32,9 @@
 def FeatureVFP3 : SubtargetFeature<"vfp3", "HasVFPv3", "true",
                                    "Enable VFP3 instructions",
                                    [FeatureVFP2]>;
+def FeatureVFP4 : SubtargetFeature<"vfp4", "HasVFPv4", "true",
+                                   "Enable VFP4 instructions",
+                                   [FeatureVFP3]>;
 def FeatureNEON : SubtargetFeature<"neon", "HasNEON", "true",
                                    "Enable NEON instructions",
                                    [FeatureVFP3]>;
@@ -86,6 +86,11 @@
                                                "AvoidCPSRPartialUpdate", "=
true",
                                  "Avoid CPSR partial update for OOO execut=
ion">;
=20
+// Some processors perform return stack prediction. CodeGen should avoid i=
ssue
+// "normal" call instructions to callees which do not return.
+def FeatureHasRAS : SubtargetFeature<"ras", "HasRAS", "true",
+                                     "Has return address stack">;
+
 /// Some M architectures don't have the DSP extension (v7E-M vs. v7M)
 def FeatureDSPThumb2 : SubtargetFeature<"t2dsp", "Thumb2DSP", "true",
                                  "Supports v7 DSP instructions in Thumb2">;
@@ -201,13 +206,14 @@
 // V7a Processors.
 def : Processor<"cortex-a8",        CortexA8Itineraries,
                                     [ProcA8, HasV7Ops, FeatureNEON, Featur=
eDB,
-                                     FeatureDSPThumb2]>;
+                                     FeatureDSPThumb2, FeatureHasRAS]>;
 def : Processor<"cortex-a9",        CortexA9Itineraries,
                                     [ProcA9, HasV7Ops, FeatureNEON, Featur=
eDB,
-                                     FeatureDSPThumb2]>;
+                                     FeatureDSPThumb2, FeatureHasRAS]>;
 def : Processor<"cortex-a9-mp",     CortexA9Itineraries,
                                     [ProcA9, HasV7Ops, FeatureNEON, Featur=
eDB,
-                                     FeatureDSPThumb2, FeatureMP]>;
+                                     FeatureDSPThumb2, FeatureMP,
+                                     FeatureHasRAS]>;
=20
 // V7M Processors.
 def : ProcNoItin<"cortex-m3",       [HasV7Ops,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMAs=
mPrinter.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMAsmPrinter.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMAsmPrinter.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -13,10 +13,9 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "asm-printer"
+#include "ARMAsmPrinter.h"
 #include "ARM.h"
-#include "ARMAsmPrinter.h"
 #include "ARMBuildAttrs.h"
-#include "ARMBaseRegisterInfo.h"
 #include "ARMConstantPoolValue.h"
 #include "ARMMachineFunctionInfo.h"
 #include "ARMTargetMachine.h"
@@ -35,7 +34,6 @@
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCContext.h"
-#include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/MC/MCObjectStreamer.h"
@@ -44,10 +42,7 @@
 #include "llvm/Target/Mangler.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetMachine.h"
-#include "llvm/Target/TargetOptions.h"
-#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -85,15 +80,15 @@
=20
     void EmitTextAttribute(unsigned Attribute, StringRef String) {
       switch (Attribute) {
+      default: llvm_unreachable("Unsupported Text attribute in ASM Mode");
       case ARMBuildAttrs::CPU_name:
-        Streamer.EmitRawText(StringRef("\t.cpu ") + LowercaseString(String=
));
+        Streamer.EmitRawText(StringRef("\t.cpu ") + String.lower());
         break;
       /* GAS requires .fpu to be emitted regardless of EABI attribute */
       case ARMBuildAttrs::Advanced_SIMD_arch:
       case ARMBuildAttrs::VFP_arch:
-        Streamer.EmitRawText(StringRef("\t.fpu ") + LowercaseString(String=
));
+        Streamer.EmitRawText(StringRef("\t.fpu ") + String.lower());
         break;
-      default: assert(0 && "Unsupported Text attribute in ASM Mode"); brea=
k;
       }
     }
     void Finish() { }
@@ -197,15 +192,14 @@
         AttributeItemType item =3D Contents[i];
         Streamer.EmitULEB128IntValue(item.Tag, 0);
         switch (item.Type) {
+        default: llvm_unreachable("Invalid attribute type");
         case AttributeItemType::NumericAttribute:
           Streamer.EmitULEB128IntValue(item.IntValue, 0);
           break;
         case AttributeItemType::TextAttribute:
-          Streamer.EmitBytes(UppercaseString(item.StringValue), 0);
+          Streamer.EmitBytes(item.StringValue.upper(), 0);
           Streamer.EmitIntValue(0, 1); // '\0'
           break;
-        default:
-          assert(0 && "Invalid attribute type");
         }
       }
=20
@@ -300,6 +294,22 @@
   OutStreamer.EmitLabel(CurrentFnSym);
 }
=20
+void ARMAsmPrinter::EmitXXStructor(const Constant *CV) {
+  uint64_t Size =3D TM.getTargetData()->getTypeAllocSize(CV->getType());
+  assert(Size && "C++ constructor pointer had zero size!");
+
+  const GlobalValue *GV =3D dyn_cast<GlobalValue>(CV->stripPointerCasts());
+  assert(GV && "C++ constructor pointer was not a GlobalValue!");
+
+  const MCExpr *E =3D MCSymbolRefExpr::Create(Mang->getSymbol(GV),
+                                            (Subtarget->isTargetDarwin()
+                                             ? MCSymbolRefExpr::VK_None
+                                             : MCSymbolRefExpr::VK_ARM_TAR=
GET1),
+                                            OutContext);
+ =20
+  OutStreamer.EmitValue(E, Size);
+}
+
 /// runOnMachineFunction - This uses the EmitInstruction()
 /// method to print assembly for each instruction.
 ///
@@ -316,8 +326,7 @@
   unsigned TF =3D MO.getTargetFlags();
=20
   switch (MO.getType()) {
-  default:
-    assert(0 && "<unknown operand type>");
+  default: llvm_unreachable("<unknown operand type>");
   case MachineOperand::MO_Register: {
     unsigned Reg =3D MO.getReg();
     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
@@ -494,11 +503,21 @@
       return false;
     }
=20
+    case 'e': // The low doubleword register of a NEON quad register.
+    case 'f': { // The high doubleword register of a NEON quad register.
+      if (!MI->getOperand(OpNum).isReg())
+        return true;
+      unsigned Reg =3D MI->getOperand(OpNum).getReg();
+      if (!ARM::QPRRegClass.contains(Reg))
+        return true;
+      const TargetRegisterInfo *TRI =3D MF->getTarget().getRegisterInfo();
+      unsigned SubReg =3D TRI->getSubReg(Reg, ExtraCode[0] =3D=3D 'e' ?
+                                       ARM::dsub_0 : ARM::dsub_1);
+      O << ARMInstPrinter::getRegisterName(SubReg);
+      return false;
+    }
+
     // These modifiers are not yet supported.
-    case 'p': // The high single-precision register of a VFP double-precis=
ion
-              // register.
-    case 'e': // The low doubleword register of a NEON quad register.
-    case 'f': // The high doubleword register of a NEON quad register.
     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
     case 'H': // The highest-numbered register of a pair.
       return true;
@@ -576,10 +595,8 @@
   OutStreamer.EmitAssemblerFlag(MCAF_SyntaxUnified);
=20
   // Emit ARM Build Attributes
-  if (Subtarget->isTargetELF()) {
-
+  if (Subtarget->isTargetELF())
     emitAttributes();
-  }
 }
=20
=20
@@ -710,15 +727,26 @@
=20
   if (Subtarget->hasNEON() && emitFPU) {
     /* NEON is not exactly a VFP architecture, but GAS emit one of
-     * neon/vfpv3/vfpv2 for .fpu parameters */
-    AttrEmitter->EmitTextAttribute(ARMBuildAttrs::Advanced_SIMD_arch, "neo=
n");
+     * neon/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
+    if (Subtarget->hasVFP4())
+      AttrEmitter->EmitTextAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
+                                     "neon-vfpv4");
+    else
+      AttrEmitter->EmitTextAttribute(ARMBuildAttrs::Advanced_SIMD_arch, "n=
eon");
     /* If emitted for NEON, omit from VFP below, since you can have both
      * NEON and VFP in build attributes but only one .fpu */
     emitFPU =3D false;
   }
=20
+  /* VFPv4 + .fpu */
+  if (Subtarget->hasVFP4()) {
+    AttrEmitter->EmitAttribute(ARMBuildAttrs::VFP_arch,
+                               ARMBuildAttrs::AllowFPv4A);
+    if (emitFPU)
+      AttrEmitter->EmitTextAttribute(ARMBuildAttrs::VFP_arch, "vfpv4");
+
   /* VFPv3 + .fpu */
-  if (Subtarget->hasVFP3()) {
+  } else if (Subtarget->hasVFP3()) {
     AttrEmitter->EmitAttribute(ARMBuildAttrs::VFP_arch,
                                ARMBuildAttrs::AllowFPv3A);
     if (emitFPU)
@@ -740,14 +768,14 @@
   }
=20
   // Signal various FP modes.
-  if (!UnsafeFPMath) {
+  if (!TM.Options.UnsafeFPMath) {
     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_FP_denormal,
                                ARMBuildAttrs::Allowed);
     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
                                ARMBuildAttrs::Allowed);
   }
=20
-  if (NoInfsFPMath && NoNaNsFPMath)
+  if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_FP_number_model,
                                ARMBuildAttrs::Allowed);
   else
@@ -760,7 +788,7 @@
   AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_align8_preserved, 1);
=20
   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
-  if (Subtarget->isAAPCS_ABI() && FloatABIType =3D=3D FloatABI::Hard) {
+  if (Subtarget->isAAPCS_ABI() && TM.Options.FloatABIType =3D=3D FloatABI:=
:Hard) {
     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_HardFP_use, 3);
     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_VFP_args, 1);
   }
@@ -808,7 +836,6 @@
 static MCSymbolRefExpr::VariantKind
 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
   switch (Modifier) {
-  default: llvm_unreachable("Unknown modifier!");
   case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
   case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_ARM_TLSGD;
   case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_ARM_TPOFF;
@@ -816,7 +843,7 @@
   case ARMCP::GOT:         return MCSymbolRefExpr::VK_ARM_GOT;
   case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_ARM_GOTOFF;
   }
-  return MCSymbolRefExpr::VK_None;
+  llvm_unreachable("Invalid ARMCPModifier!");
 }
=20
 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV) {
@@ -1070,7 +1097,7 @@
   }
=20
   // Try to figure out the unwinding opcode out of src / dst regs.
-  if (MI->getDesc().mayStore()) {
+  if (MI->mayStore()) {
     // Register saves.
     assert(DstReg =3D=3D ARM::SP &&
            "Only stack pointer as a destination reg is supported");
@@ -1084,7 +1111,7 @@
     switch (Opc) {
     default:
       MI->dump();
-      assert(0 && "Unsupported opcode for unwinding information");
+      llvm_unreachable("Unsupported opcode for unwinding information");
     case ARM::tPUSH:
       // Special case here: no src & dst reg, but two extra imp ops.
       StartOp =3D 2; NumOffset =3D 2;
@@ -1099,6 +1126,7 @@
       break;
     case ARM::STR_PRE_IMM:
     case ARM::STR_PRE_REG:
+    case ARM::t2STR_PRE:
       assert(MI->getOperand(2).getReg() =3D=3D ARM::SP &&
              "Only stack pointer as a source reg is supported");
       RegList.push_back(SrcReg);
@@ -1112,14 +1140,16 @@
       switch (Opc) {
       default:
         MI->dump();
-        assert(0 && "Unsupported opcode for unwinding information");
+        llvm_unreachable("Unsupported opcode for unwinding information");
       case ARM::MOVr:
+      case ARM::tMOVr:
         Offset =3D 0;
         break;
       case ARM::ADDri:
         Offset =3D -MI->getOperand(2).getImm();
         break;
       case ARM::SUBri:
+      case ARM::t2SUBri:
         Offset =3D MI->getOperand(2).getImm();
         break;
       case ARM::tSUBspi:
@@ -1157,16 +1187,16 @@
         OutStreamer.EmitPad(Offset);
       } else {
         MI->dump();
-        assert(0 && "Unsupported opcode for unwinding information");
+        llvm_unreachable("Unsupported opcode for unwinding information");
       }
     } else if (DstReg =3D=3D ARM::SP) {
       // FIXME: .movsp goes here
       MI->dump();
-      assert(0 && "Unsupported opcode for unwinding information");
+      llvm_unreachable("Unsupported opcode for unwinding information");
     }
     else {
       MI->dump();
-      assert(0 && "Unsupported opcode for unwinding information");
+      llvm_unreachable("Unsupported opcode for unwinding information");
     }
   }
 }
@@ -1195,7 +1225,7 @@
   // Check for manual lowerings.
   unsigned Opc =3D MI->getOpcode();
   switch (Opc) {
-  case ARM::t2MOVi32imm: assert(0 && "Should be lowered by thumb2it pass");
+  case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it p=
ass");
   case ARM::DBG_VALUE: {
     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
       SmallString<128> TmpStr;
@@ -1237,7 +1267,6 @@
   }
   // Darwin call instructions are just normal call instructions with diffe=
rent
   // clobber semantics (they clobber R9).
-  case ARM::BXr9_CALL:
   case ARM::BX_CALL: {
     {
       MCInst TmpInst;
@@ -1259,7 +1288,6 @@
     }
     return;
   }
-  case ARM::tBXr9_CALL:
   case ARM::tBX_CALL: {
     {
       MCInst TmpInst;
@@ -1282,7 +1310,6 @@
     }
     return;
   }
-  case ARM::BMOVPCRXr9_CALL:
   case ARM::BMOVPCRX_CALL: {
     {
       MCInst TmpInst;
@@ -1310,6 +1337,58 @@
     }
     return;
   }
+  case ARM::BMOVPCB_CALL: {
+    {
+      MCInst TmpInst;
+      TmpInst.setOpcode(ARM::MOVr);
+      TmpInst.addOperand(MCOperand::CreateReg(ARM::LR));
+      TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
+      // Add predicate operands.
+      TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+      TmpInst.addOperand(MCOperand::CreateReg(0));
+      // Add 's' bit operand (always reg0 for this)
+      TmpInst.addOperand(MCOperand::CreateReg(0));
+      OutStreamer.EmitInstruction(TmpInst);
+    }
+    {
+      MCInst TmpInst;
+      TmpInst.setOpcode(ARM::Bcc);
+      const GlobalValue *GV =3D MI->getOperand(0).getGlobal();
+      MCSymbol *GVSym =3D Mang->getSymbol(GV);
+      const MCExpr *GVSymExpr =3D MCSymbolRefExpr::Create(GVSym, OutContex=
t);
+      TmpInst.addOperand(MCOperand::CreateExpr(GVSymExpr));
+      // Add predicate operands.
+      TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+      TmpInst.addOperand(MCOperand::CreateReg(0));
+      OutStreamer.EmitInstruction(TmpInst);
+    }
+    return;
+  }
+  case ARM::t2BMOVPCB_CALL: {
+    {
+      MCInst TmpInst;
+      TmpInst.setOpcode(ARM::tMOVr);
+      TmpInst.addOperand(MCOperand::CreateReg(ARM::LR));
+      TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
+      // Add predicate operands.
+      TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+      TmpInst.addOperand(MCOperand::CreateReg(0));
+      OutStreamer.EmitInstruction(TmpInst);
+    }
+    {
+      MCInst TmpInst;
+      TmpInst.setOpcode(ARM::t2B);
+      const GlobalValue *GV =3D MI->getOperand(0).getGlobal();
+      MCSymbol *GVSym =3D Mang->getSymbol(GV);
+      const MCExpr *GVSymExpr =3D MCSymbolRefExpr::Create(GVSym, OutContex=
t);
+      TmpInst.addOperand(MCOperand::CreateExpr(GVSymExpr));
+      // Add predicate operands.
+      TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+      TmpInst.addOperand(MCOperand::CreateReg(0));
+      OutStreamer.EmitInstruction(TmpInst);
+    }
+    return;
+  }
   case ARM::MOVi16_ga_pcrel:
   case ARM::t2MOVi16_ga_pcrel: {
     MCInst TmpInst;
@@ -1482,11 +1561,10 @@
     /// in the function.  The first operand is the ID# for this instructio=
n, the
     /// second is the index into the MachineConstantPool that this is, the=
 third
     /// is the size in bytes of this constant pool entry.
+    /// The required alignment is specified on the basic block holding thi=
s MI.
     unsigned LabelId =3D (unsigned)MI->getOperand(0).getImm();
     unsigned CPIdx   =3D (unsigned)MI->getOperand(1).getIndex();
=20
-    EmitAlignment(2);
-
     // Mark the constant pool entry as data if we're not already in a data
     // region.
     OutStreamer.EmitDataRegion();
@@ -1898,10 +1976,10 @@
     }
     {
       MCInst TmpInst;
-      TmpInst.setOpcode(ARM::tLDRr);
+      TmpInst.setOpcode(ARM::tLDRi);
       TmpInst.addOperand(MCOperand::CreateReg(ARM::R7));
       TmpInst.addOperand(MCOperand::CreateReg(SrcReg));
-      TmpInst.addOperand(MCOperand::CreateReg(0));
+      TmpInst.addOperand(MCOperand::CreateImm(0));
       // Predicate.
       TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
       TmpInst.addOperand(MCOperand::CreateReg(0));
@@ -1935,4 +2013,3 @@
   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMAs=
mPrinter.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMAsmPrinter.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMAsmPrinter.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMAsmPrinter.h - Print machine code to an ARM .s file -----=
-------=3D=3D=3D//
+//=3D=3D=3D-- ARMAsmPrinter.h - Print machine code to an ARM .s file --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -73,6 +73,7 @@
   virtual void EmitFunctionEntryLabel();
   void EmitStartOfAsmFile(Module &M);
   void EmitEndOfAsmFile(Module &M);
+  void EmitXXStructor(const Constant *CV);
=20
   // lowerOperand - Convert a MachineOperand into the equivalent MCOperand.
   bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp);
@@ -106,7 +107,7 @@
     if (!Subtarget->isTargetDarwin())
       return 0;
     return Subtarget->isThumb() ?
-      llvm::ARM::DW_ISA_ARM_thumb : llvm::ARM::DW_ISA_ARM_arm;
+      ARM::DW_ISA_ARM_thumb : ARM::DW_ISA_ARM_arm;
   }
=20
   MCOperand GetSymbolRef(const MachineOperand &MO, const MCSymbol *Symbol);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMBa=
seInstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMBaseInstrInfo.cpp - ARM Instruction Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMBaseInstrInfo.cpp - ARM Instruction Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,10 +13,10 @@
=20
 #include "ARMBaseInstrInfo.h"
 #include "ARM.h"
+#include "ARMBaseRegisterInfo.h"
 #include "ARMConstantPoolValue.h"
 #include "ARMHazardRecognizer.h"
 #include "ARMMachineFunctionInfo.h"
-#include "ARMRegisterInfo.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/Constants.h"
 #include "llvm/Function.h"
@@ -28,7 +28,6 @@
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/CodeGen/SelectionDAGNodes.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/Support/BranchProbability.h"
@@ -47,7 +46,7 @@
                cl::desc("Enable ARM 2-addr to 3-addr conv"));
=20
 static cl::opt<bool>
-WidenVMOVS("widen-vmovs", cl::Hidden,
+WidenVMOVS("widen-vmovs", cl::Hidden, cl::init(true),
            cl::desc("Widen ARM vmovs to vmovd when possible"));
=20
 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
@@ -147,7 +146,7 @@
   unsigned AddrMode =3D (TSFlags & ARMII::AddrModeMask);
   const MCInstrDesc &MCID =3D MI->getDesc();
   unsigned NumOps =3D MCID.getNumOperands();
-  bool isLoad =3D !MCID.mayStore();
+  bool isLoad =3D !MI->mayStore();
   const MachineOperand &WB =3D isLoad ? MI->getOperand(1) : MI->getOperand=
(0);
   const MachineOperand &Base =3D MI->getOperand(2);
   const MachineOperand &Offset =3D MI->getOperand(NumOps-3);
@@ -157,9 +156,7 @@
   unsigned OffImm =3D MI->getOperand(NumOps-2).getImm();
   ARMCC::CondCodes Pred =3D (ARMCC::CondCodes)MI->getOperand(NumOps-1).get=
Imm();
   switch (AddrMode) {
-  default:
-    assert(false && "Unknown indexed op!");
-    return NULL;
+  default: llvm_unreachable("Unknown indexed op!");
   case ARMII::AddrMode2: {
     bool isSub =3D ARM_AM::getAM2Op(OffImm) =3D=3D ARM_AM::sub;
     unsigned Amt =3D ARM_AM::getAM2Offset(OffImm);
@@ -440,6 +437,22 @@
   return false;
 }
=20
+bool ARMBaseInstrInfo::isPredicated(const MachineInstr *MI) const {
+  if (MI->isBundle()) {
+    MachineBasicBlock::const_instr_iterator I =3D MI;
+    MachineBasicBlock::const_instr_iterator E =3D MI->getParent()->instr_e=
nd();
+    while (++I !=3D E && I->isInsideBundle()) {
+      int PIdx =3D I->findFirstPredOperandIdx();
+      if (PIdx !=3D -1 && I->getOperand(PIdx).getImm() !=3D ARMCC::AL)
+        return true;
+    }
+    return false;
+  }
+
+  int PIdx =3D MI->findFirstPredOperandIdx();
+  return PIdx !=3D -1 && MI->getOperand(PIdx).getImm() !=3D ARMCC::AL;
+}
+
 bool ARMBaseInstrInfo::
 PredicateInstruction(MachineInstr *MI,
                      const SmallVectorImpl<MachineOperand> &Pred) const {
@@ -490,15 +503,11 @@
=20
 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
                                     std::vector<MachineOperand> &Pred) con=
st {
-  // FIXME: This confuses implicit_def with optional CPSR def.
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.getImplicitDefs() && !MCID.hasOptionalDef())
-    return false;
-
   bool Found =3D false;
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D MI->getOperand(i);
-    if (MO.isReg() && MO.getReg() =3D=3D ARM::CPSR) {
+    if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) ||
+        (MO.isReg() && MO.isDef() && MO.getReg() =3D=3D ARM::CPSR)) {
       Pred.push_back(MO);
       Found =3D true;
     }
@@ -511,11 +520,10 @@
 /// By default, this returns true for every instruction with a
 /// PredicateOperand.
 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.isPredicable())
+  if (!MI->isPredicable())
     return false;
=20
-  if ((MCID.TSFlags & ARMII::DomainMask) =3D=3D ARMII::DomainNEON) {
+  if ((MI->getDesc().TSFlags & ARMII::DomainMask) =3D=3D ARMII::DomainNEON=
) {
     ARMFunctionInfo *AFI =3D
       MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
     return AFI->isThumb2Function();
@@ -544,83 +552,95 @@
   if (MCID.getSize())
     return MCID.getSize();
=20
-    // If this machine instr is an inline asm, measure it.
-    if (MI->getOpcode() =3D=3D ARM::INLINEASM)
-      return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
-    if (MI->isLabel())
-      return 0;
+  // If this machine instr is an inline asm, measure it.
+  if (MI->getOpcode() =3D=3D ARM::INLINEASM)
+    return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
+  if (MI->isLabel())
+    return 0;
   unsigned Opc =3D MI->getOpcode();
-    switch (Opc) {
-    case TargetOpcode::IMPLICIT_DEF:
-    case TargetOpcode::KILL:
-    case TargetOpcode::PROLOG_LABEL:
-    case TargetOpcode::EH_LABEL:
-    case TargetOpcode::DBG_VALUE:
-      return 0;
-    case ARM::MOVi16_ga_pcrel:
-    case ARM::MOVTi16_ga_pcrel:
-    case ARM::t2MOVi16_ga_pcrel:
-    case ARM::t2MOVTi16_ga_pcrel:
-      return 4;
-    case ARM::MOVi32imm:
-    case ARM::t2MOVi32imm:
-      return 8;
-    case ARM::CONSTPOOL_ENTRY:
-      // If this machine instr is a constant pool entry, its size is recor=
ded as
-      // operand #2.
-      return MI->getOperand(2).getImm();
-    case ARM::Int_eh_sjlj_longjmp:
-      return 16;
-    case ARM::tInt_eh_sjlj_longjmp:
-      return 10;
-    case ARM::Int_eh_sjlj_setjmp:
-    case ARM::Int_eh_sjlj_setjmp_nofp:
-      return 20;
-    case ARM::tInt_eh_sjlj_setjmp:
-    case ARM::t2Int_eh_sjlj_setjmp:
-    case ARM::t2Int_eh_sjlj_setjmp_nofp:
-      return 12;
-    case ARM::BR_JTr:
-    case ARM::BR_JTm:
-    case ARM::BR_JTadd:
-    case ARM::tBR_JTr:
-    case ARM::t2BR_JT:
-    case ARM::t2TBB_JT:
-    case ARM::t2TBH_JT: {
-      // These are jumptable branches, i.e. a branch followed by an inlined
-      // jumptable. The size is 4 + 4 * number of entries. For TBB, each
-      // entry is one byte; TBH two byte each.
-      unsigned EntrySize =3D (Opc =3D=3D ARM::t2TBB_JT)
-        ? 1 : ((Opc =3D=3D ARM::t2TBH_JT) ? 2 : 4);
-      unsigned NumOps =3D MCID.getNumOperands();
-      MachineOperand JTOP =3D
-        MI->getOperand(NumOps - (MCID.isPredicable() ? 3 : 2));
-      unsigned JTI =3D JTOP.getIndex();
-      const MachineJumpTableInfo *MJTI =3D MF->getJumpTableInfo();
-      assert(MJTI !=3D 0);
-      const std::vector<MachineJumpTableEntry> &JT =3D MJTI->getJumpTables=
();
-      assert(JTI < JT.size());
-      // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
-      // 4 aligned. The assembler / linker may add 2 byte padding just bef=
ore
-      // the JT entries.  The size does not include this padding; the
-      // constant islands pass does separate bookkeeping for it.
-      // FIXME: If we know the size of the function is less than (1 << 16)=
 *2
-      // bytes, we can use 16-bit entries instead. Then there won't be an
-      // alignment issue.
-      unsigned InstSize =3D (Opc =3D=3D ARM::tBR_JTr || Opc =3D=3D ARM::t2=
BR_JT) ? 2 : 4;
-      unsigned NumEntries =3D getNumJTEntries(JT, JTI);
-      if (Opc =3D=3D ARM::t2TBB_JT && (NumEntries & 1))
-        // Make sure the instruction that follows TBB is 2-byte aligned.
-        // FIXME: Constant island pass should insert an "ALIGN" instruction
-        // instead.
-        ++NumEntries;
-      return NumEntries * EntrySize + InstSize;
-    }
-    default:
-      // Otherwise, pseudo-instruction sizes are zero.
-      return 0;
-    }
-  return 0; // Not reached
+  switch (Opc) {
+  case TargetOpcode::IMPLICIT_DEF:
+  case TargetOpcode::KILL:
+  case TargetOpcode::PROLOG_LABEL:
+  case TargetOpcode::EH_LABEL:
+  case TargetOpcode::DBG_VALUE:
+    return 0;
+  case TargetOpcode::BUNDLE:
+    return getInstBundleLength(MI);
+  case ARM::MOVi16_ga_pcrel:
+  case ARM::MOVTi16_ga_pcrel:
+  case ARM::t2MOVi16_ga_pcrel:
+  case ARM::t2MOVTi16_ga_pcrel:
+    return 4;
+  case ARM::MOVi32imm:
+  case ARM::t2MOVi32imm:
+    return 8;
+  case ARM::CONSTPOOL_ENTRY:
+    // If this machine instr is a constant pool entry, its size is recorde=
d as
+    // operand #2.
+    return MI->getOperand(2).getImm();
+  case ARM::Int_eh_sjlj_longjmp:
+    return 16;
+  case ARM::tInt_eh_sjlj_longjmp:
+    return 10;
+  case ARM::Int_eh_sjlj_setjmp:
+  case ARM::Int_eh_sjlj_setjmp_nofp:
+    return 20;
+  case ARM::tInt_eh_sjlj_setjmp:
+  case ARM::t2Int_eh_sjlj_setjmp:
+  case ARM::t2Int_eh_sjlj_setjmp_nofp:
+    return 12;
+  case ARM::BR_JTr:
+  case ARM::BR_JTm:
+  case ARM::BR_JTadd:
+  case ARM::tBR_JTr:
+  case ARM::t2BR_JT:
+  case ARM::t2TBB_JT:
+  case ARM::t2TBH_JT: {
+    // These are jumptable branches, i.e. a branch followed by an inlined
+    // jumptable. The size is 4 + 4 * number of entries. For TBB, each
+    // entry is one byte; TBH two byte each.
+    unsigned EntrySize =3D (Opc =3D=3D ARM::t2TBB_JT)
+      ? 1 : ((Opc =3D=3D ARM::t2TBH_JT) ? 2 : 4);
+    unsigned NumOps =3D MCID.getNumOperands();
+    MachineOperand JTOP =3D
+      MI->getOperand(NumOps - (MI->isPredicable() ? 3 : 2));
+    unsigned JTI =3D JTOP.getIndex();
+    const MachineJumpTableInfo *MJTI =3D MF->getJumpTableInfo();
+    assert(MJTI !=3D 0);
+    const std::vector<MachineJumpTableEntry> &JT =3D MJTI->getJumpTables();
+    assert(JTI < JT.size());
+    // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
+    // 4 aligned. The assembler / linker may add 2 byte padding just before
+    // the JT entries.  The size does not include this padding; the
+    // constant islands pass does separate bookkeeping for it.
+    // FIXME: If we know the size of the function is less than (1 << 16) *2
+    // bytes, we can use 16-bit entries instead. Then there won't be an
+    // alignment issue.
+    unsigned InstSize =3D (Opc =3D=3D ARM::tBR_JTr || Opc =3D=3D ARM::t2BR=
_JT) ? 2 : 4;
+    unsigned NumEntries =3D getNumJTEntries(JT, JTI);
+    if (Opc =3D=3D ARM::t2TBB_JT && (NumEntries & 1))
+      // Make sure the instruction that follows TBB is 2-byte aligned.
+      // FIXME: Constant island pass should insert an "ALIGN" instruction
+      // instead.
+      ++NumEntries;
+    return NumEntries * EntrySize + InstSize;
+  }
+  default:
+    // Otherwise, pseudo-instruction sizes are zero.
+    return 0;
+  }
+}
+
+unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr *MI) con=
st {
+  unsigned Size =3D 0;
+  MachineBasicBlock::const_instr_iterator I =3D MI;
+  MachineBasicBlock::const_instr_iterator E =3D MI->getParent()->instr_end=
();
+  while (++I !=3D E && I->isInsideBundle()) {
+    assert(!I->isBundle() && "No nested bundle!");
+    Size +=3D GetInstSizeInBytes(&*I);
+  }
+  return Size;
 }
=20
 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
@@ -660,29 +680,51 @@
     return;
   }
=20
-  // Generate instructions for VMOVQQ and VMOVQQQQ pseudos in place.
-  if (ARM::QQPRRegClass.contains(DestReg, SrcReg) ||
-      ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
+  // Handle register classes that require multiple instructions.
+  unsigned BeginIdx =3D 0;
+  unsigned SubRegs =3D 0;
+  unsigned Spacing =3D 1;
+
+  // Use VORRq when possible.
+  if (ARM::QQPRRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VORRq, BeginIdx =3D ARM::qsub_0, SubRegs =3D 2;
+  else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VORRq, BeginIdx =3D ARM::qsub_0, SubRegs =3D 4;
+  // Fall back to VMOVD.
+  else if (ARM::DPairRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VMOVD, BeginIdx =3D ARM::dsub_0, SubRegs =3D 2;
+  else if (ARM::DTripleRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VMOVD, BeginIdx =3D ARM::dsub_0, SubRegs =3D 3;
+  else if (ARM::DQuadRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VMOVD, BeginIdx =3D ARM::dsub_0, SubRegs =3D 4;
+
+  else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VMOVD, BeginIdx =3D ARM::dsub_0, SubRegs =3D 2, Spacing =
=3D 2;
+  else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VMOVD, BeginIdx =3D ARM::dsub_0, SubRegs =3D 3, Spacing =
=3D 2;
+  else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg))
+    Opc =3D ARM::VMOVD, BeginIdx =3D ARM::dsub_0, SubRegs =3D 4, Spacing =
=3D 2;
+
+  if (Opc) {
     const TargetRegisterInfo *TRI =3D &getRegisterInfo();
-    assert(ARM::qsub_0 + 3 =3D=3D ARM::qsub_3 && "Expected contiguous enum=
.");
-    unsigned EndSubReg =3D ARM::QQPRRegClass.contains(DestReg, SrcReg) ?
-      ARM::qsub_1 : ARM::qsub_3;
-    for (unsigned i =3D ARM::qsub_0, e =3D EndSubReg + 1; i !=3D e; ++i) {
-      unsigned Dst =3D TRI->getSubReg(DestReg, i);
-      unsigned Src =3D TRI->getSubReg(SrcReg, i);
-      MachineInstrBuilder Mov =3D
-        AddDefaultPred(BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VORRq))
-                       .addReg(Dst, RegState::Define)
-                       .addReg(Src, getKillRegState(KillSrc))
-                       .addReg(Src, getKillRegState(KillSrc)));
-      if (i =3D=3D EndSubReg) {
-        Mov->addRegisterDefined(DestReg, TRI);
-        if (KillSrc)
-          Mov->addRegisterKilled(SrcReg, TRI);
-      }
+    MachineInstrBuilder Mov;
+    for (unsigned i =3D 0; i !=3D SubRegs; ++i) {
+      unsigned Dst =3D TRI->getSubReg(DestReg, BeginIdx + i*Spacing);
+      unsigned Src =3D TRI->getSubReg(SrcReg,  BeginIdx + i*Spacing);
+      assert(Dst && Src && "Bad sub-register");
+      Mov =3D AddDefaultPred(BuildMI(MBB, I, I->getDebugLoc(), get(Opc), D=
st)
+                             .addReg(Src));
+      // VORR takes two source operands.
+      if (Opc =3D=3D ARM::VORRq)
+        Mov.addReg(Src);
     }
+    // Add implicit super-register defs and kills to the last instruction.
+    Mov->addRegisterDefined(DestReg, TRI);
+    if (KillSrc)
+      Mov->addRegisterKilled(SrcReg, TRI);
     return;
   }
+
   llvm_unreachable("Impossible reg-to-reg copy");
 }
=20
@@ -710,8 +752,7 @@
   unsigned Align =3D MFI.getObjectAlignment(FI);
=20
   MachineMemOperand *MMO =3D
-    MF.getMachineMemOperand(MachinePointerInfo(
-                                         PseudoSourceValue::getFixedStack(=
FI)),
+    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
                             MachineMemOperand::MOStore,
                             MFI.getObjectSize(FI),
                             Align);
@@ -738,9 +779,10 @@
         llvm_unreachable("Unknown reg class!");
       break;
     case 16:
-      if (ARM::QPRRegClass.hasSubClassEq(RC)) {
-        if (Align >=3D 16 && getRegisterInfo().needsStackRealignment(MF)) {
-          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64Pseudo))
+      if (ARM::DPairRegClass.hasSubClassEq(RC)) {
+        // Use aligned spills if the stack can be realigned.
+        if (Align >=3D 16 && getRegisterInfo().canRealignStack(MF)) {
+          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64))
                      .addFrameIndex(FI).addImm(16)
                      .addReg(SrcReg, getKillRegState(isKill))
                      .addMemOperand(MMO));
@@ -825,7 +867,7 @@
       return MI->getOperand(0).getReg();
     }
     break;
-  case ARM::VST1q64Pseudo:
+  case ARM::VST1q64:
     if (MI->getOperand(0).isFI() &&
         MI->getOperand(2).getSubReg() =3D=3D 0) {
       FrameIndex =3D MI->getOperand(0).getIndex();
@@ -847,7 +889,7 @@
 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
                                                     int &FrameIndex) const=
 {
   const MachineMemOperand *Dummy;
-  return MI->getDesc().mayStore() && hasStoreToStackSlot(MI, Dummy, FrameI=
ndex);
+  return MI->mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
 }
=20
 void ARMBaseInstrInfo::
@@ -862,7 +904,7 @@
   unsigned Align =3D MFI.getObjectAlignment(FI);
   MachineMemOperand *MMO =3D
     MF.getMachineMemOperand(
-                    MachinePointerInfo(PseudoSourceValue::getFixedStack(FI=
)),
+                    MachinePointerInfo::getFixedStack(FI),
                             MachineMemOperand::MOLoad,
                             MFI.getObjectSize(FI),
                             Align);
@@ -887,9 +929,9 @@
       llvm_unreachable("Unknown reg class!");
     break;
   case 16:
-    if (ARM::QPRRegClass.hasSubClassEq(RC)) {
-      if (Align >=3D 16 && getRegisterInfo().needsStackRealignment(MF)) {
-        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64Pseudo), DestRe=
g)
+    if (ARM::DPairRegClass.hasSubClassEq(RC)) {
+      if (Align >=3D 16 && getRegisterInfo().canRealignStack(MF)) {
+        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
                      .addFrameIndex(FI).addImm(16)
                      .addMemOperand(MMO));
       } else {
@@ -911,11 +953,12 @@
         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
                        .addFrameIndex(FI))
                        .addMemOperand(MMO);
-        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
-        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
-        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
-        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
-        MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
+        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead,=
 TRI);
+        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead,=
 TRI);
+        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead,=
 TRI);
+        MIB =3D AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead,=
 TRI);
+        if (TargetRegisterInfo::isPhysicalRegister(DestReg))
+          MIB.addReg(DestReg, RegState::ImplicitDefine);
       }
     } else
       llvm_unreachable("Unknown reg class!");
@@ -926,15 +969,16 @@
       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
                      .addFrameIndex(FI))
                      .addMemOperand(MMO);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_4, RegState::Define, TRI);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_5, RegState::Define, TRI);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_6, RegState::Define, TRI);
-      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_7, RegState::Define, TRI);
-      MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, T=
RI);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, T=
RI);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, T=
RI);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, T=
RI);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, T=
RI);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, T=
RI);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, T=
RI);
+      MIB =3D AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, T=
RI);
+      if (TargetRegisterInfo::isPhysicalRegister(DestReg))
+        MIB.addReg(DestReg, RegState::ImplicitDefine);
     } else
       llvm_unreachable("Unknown reg class!");
     break;
@@ -971,7 +1015,7 @@
       return MI->getOperand(0).getReg();
     }
     break;
-  case ARM::VLD1q64Pseudo:
+  case ARM::VLD1q64:
     if (MI->getOperand(1).isFI() &&
         MI->getOperand(0).getSubReg() =3D=3D 0) {
       FrameIndex =3D MI->getOperand(1).getIndex();
@@ -993,7 +1037,7 @@
 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *M=
I,
                                              int &FrameIndex) const {
   const MachineMemOperand *Dummy;
-  return MI->getDesc().mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameI=
ndex);
+  return MI->mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
 }
=20
 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) =
const{
@@ -1359,7 +1403,7 @@
     return false;
=20
   // Terminators and labels can't be scheduled around.
-  if (MI->getDesc().isTerminator() || MI->isLabel())
+  if (MI->isTerminator() || MI->isLabel())
     return true;
=20
   // Treat the start of the IT block as a scheduling boundary, but schedule
@@ -1380,7 +1424,10 @@
   // saves compile time, because it doesn't require every single
   // stack slot reference to depend on the instruction that does the
   // modification.
-  if (MI->definesRegister(ARM::SP))
+  // Calls don't actually change the stack pointer, even if they have imp-=
defs.
+  // No ARM calling conventions change the stack pointer. (X86 calling
+  // conventions sometimes do).
+  if (!MI->isCall() && MI->definesRegister(ARM::SP))
     return true;
=20
   return false;
@@ -1445,15 +1492,37 @@
 int llvm::getMatchingCondBranchOpcode(int Opc) {
   if (Opc =3D=3D ARM::B)
     return ARM::Bcc;
-  else if (Opc =3D=3D ARM::tB)
+  if (Opc =3D=3D ARM::tB)
     return ARM::tBcc;
-  else if (Opc =3D=3D ARM::t2B)
-      return ARM::t2Bcc;
+  if (Opc =3D=3D ARM::t2B)
+    return ARM::t2Bcc;
=20
   llvm_unreachable("Unknown unconditional branch opcode!");
-  return 0;
 }
=20
+/// commuteInstruction - Handle commutable instructions.
+MachineInstr *
+ARMBaseInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
+  switch (MI->getOpcode()) {
+  case ARM::MOVCCr:
+  case ARM::t2MOVCCr: {
+    // MOVCC can be commuted by inverting the condition.
+    unsigned PredReg =3D 0;
+    ARMCC::CondCodes CC =3D getInstrPredicate(MI, PredReg);
+    // MOVCC AL can't be inverted. Shouldn't happen.
+    if (CC =3D=3D ARMCC::AL || PredReg !=3D ARM::CPSR)
+      return NULL;
+    MI =3D TargetInstrInfoImpl::commuteInstruction(MI, NewMI);
+    if (!MI)
+      return NULL;
+    // After swapping the MOVCC operands, also invert the condition.
+    MI->getOperand(MI->findFirstPredOperandIdx())
+      .setImm(ARMCC::getOppositeCondition(CC));
+    return MI;
+  }
+  }
+  return TargetInstrInfoImpl::commuteInstruction(MI, NewMI);
+}
=20
 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Wheth=
er the
 /// instruction is encoded with an 'S' bit is determined by the optional C=
PSR
@@ -1478,7 +1547,6 @@
   {ARM::SUBSrsr, ARM::SUBrsr},
=20
   {ARM::RSBSri, ARM::RSBri},
-  {ARM::RSBSrr, ARM::RSBrr},
   {ARM::RSBSrsi, ARM::RSBrsi},
   {ARM::RSBSrsr, ARM::RSBrsr},
=20
@@ -1625,7 +1693,6 @@
     }
     default:
       llvm_unreachable("Unsupported addressing mode!");
-      break;
     }
=20
     Offset +=3D InstrOffs * Scale;
@@ -1765,8 +1832,7 @@
=20
   // Check that CPSR isn't set between the comparison instruction and the =
one we
   // want to change.
-  MachineBasicBlock::const_iterator I =3D CmpInstr, E =3D MI,
-    B =3D MI->getParent()->begin();
+  MachineBasicBlock::iterator I =3D CmpInstr,E =3D MI, B =3D MI->getParent=
()->begin();
=20
   // Early exit if CmpInstr is at the beginning of the BB.
   if (I =3D=3D B) return false;
@@ -1777,6 +1843,8 @@
=20
     for (unsigned IO =3D 0, EO =3D Instr.getNumOperands(); IO !=3D EO; ++I=
O) {
       const MachineOperand &MO =3D Instr.getOperand(IO);
+      if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR))
+        return false;
       if (!MO.isReg()) continue;
=20
       // This instruction modifies or uses CPSR after the one we want to
@@ -1838,6 +1906,10 @@
       for (unsigned IO =3D 0, EO =3D Instr.getNumOperands();
            !isSafe && IO !=3D EO; ++IO) {
         const MachineOperand &MO =3D Instr.getOperand(IO);
+        if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
+          isSafe =3D true;
+          break;
+        }
         if (!MO.isReg() || MO.getReg() !=3D ARM::CPSR)
           continue;
         if (MO.isDef()) {
@@ -1889,6 +1961,25 @@
   if (!MRI->hasOneNonDBGUse(Reg))
     return false;
=20
+  const MCInstrDesc &DefMCID =3D DefMI->getDesc();
+  if (DefMCID.hasOptionalDef()) {
+    unsigned NumOps =3D DefMCID.getNumOperands();
+    const MachineOperand &MO =3D DefMI->getOperand(NumOps-1);
+    if (MO.getReg() =3D=3D ARM::CPSR && !MO.isDead())
+      // If DefMI defines CPSR and it is not dead, it's obviously not safe
+      // to delete DefMI.
+      return false;
+  }
+
+  const MCInstrDesc &UseMCID =3D UseMI->getDesc();
+  if (UseMCID.hasOptionalDef()) {
+    unsigned NumOps =3D UseMCID.getNumOperands();
+    if (UseMI->getOperand(NumOps-1).getReg() =3D=3D ARM::CPSR)
+      // If the instruction sets the flag, do not attempt this optimization
+      // since it may change the semantics of the code.
+      return false;
+  }
+
   unsigned UseOpc =3D UseMI->getOpcode();
   unsigned NewUseOpc =3D 0;
   uint32_t ImmVal =3D (uint32_t)DefMI->getOperand(1).getImm();
@@ -1960,7 +2051,7 @@
   bool isKill =3D UseMI->getOperand(OpIdx).isKill();
   unsigned NewReg =3D MRI->createVirtualRegister(MRI->getRegClass(Reg));
   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
-                                      *UseMI, UseMI->getDebugLoc(),
+                                      UseMI, UseMI->getDebugLoc(),
                                       get(NewUseOpc), NewReg)
                               .addReg(Reg1, getKillRegState(isKill))
                               .addImm(SOImmValV1)));
@@ -1988,7 +2079,6 @@
   switch (Opc) {
   default:
     llvm_unreachable("Unexpected multi-uops instruction!");
-    break;
   case ARM::VLDMQIA:
   case ARM::VSTMQIA:
     return 2;
@@ -2335,6 +2425,59 @@
   return UseCycle;
 }
=20
+static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
+                                           const MachineInstr *MI, unsigne=
d Reg,
+                                           unsigned &DefIdx, unsigned &Dis=
t) {
+  Dist =3D 0;
+
+  MachineBasicBlock::const_iterator I =3D MI; ++I;
+  MachineBasicBlock::const_instr_iterator II =3D
+    llvm::prior(I.getInstrIterator());
+  assert(II->isInsideBundle() && "Empty bundle?");
+
+  int Idx =3D -1;
+  while (II->isInsideBundle()) {
+    Idx =3D II->findRegisterDefOperandIdx(Reg, false, true, TRI);
+    if (Idx !=3D -1)
+      break;
+    --II;
+    ++Dist;
+  }
+
+  assert(Idx !=3D -1 && "Cannot find bundled definition!");
+  DefIdx =3D Idx;
+  return II;
+}
+
+static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
+                                           const MachineInstr *MI, unsigne=
d Reg,
+                                           unsigned &UseIdx, unsigned &Dis=
t) {
+  Dist =3D 0;
+
+  MachineBasicBlock::const_instr_iterator II =3D MI; ++II;
+  assert(II->isInsideBundle() && "Empty bundle?");
+  MachineBasicBlock::const_instr_iterator E =3D MI->getParent()->instr_end=
();
+
+  // FIXME: This doesn't properly handle multiple uses.
+  int Idx =3D -1;
+  while (II !=3D E && II->isInsideBundle()) {
+    Idx =3D II->findRegisterUseOperandIdx(Reg, false, TRI);
+    if (Idx !=3D -1)
+      break;
+    if (II->getOpcode() !=3D ARM::t2IT)
+      ++Dist;
+    ++II;
+  }
+
+  if (Idx =3D=3D -1) {
+    Dist =3D 0;
+    return 0;
+  }
+
+  UseIdx =3D Idx;
+  return II;
+}
+
 int
 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
                              const MachineInstr *DefMI, unsigned DefIdx,
@@ -2343,35 +2486,77 @@
       DefMI->isRegSequence() || DefMI->isImplicitDef())
     return 1;
=20
-  const MCInstrDesc &DefMCID =3D DefMI->getDesc();
   if (!ItinData || ItinData->isEmpty())
-    return DefMCID.mayLoad() ? 3 : 1;
+    return DefMI->mayLoad() ? 3 : 1;
=20
-  const MCInstrDesc &UseMCID =3D UseMI->getDesc();
+  const MCInstrDesc *DefMCID =3D &DefMI->getDesc();
+  const MCInstrDesc *UseMCID =3D &UseMI->getDesc();
   const MachineOperand &DefMO =3D DefMI->getOperand(DefIdx);
-  if (DefMO.getReg() =3D=3D ARM::CPSR) {
+  unsigned Reg =3D DefMO.getReg();
+  if (Reg =3D=3D ARM::CPSR) {
     if (DefMI->getOpcode() =3D=3D ARM::FMSTAT) {
       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
       return Subtarget.isCortexA9() ? 1 : 20;
     }
=20
     // CPSR set and branch can be paired in the same cycle.
-    if (UseMCID.isBranch())
+    if (UseMI->isBranch())
       return 0;
+
+    // Otherwise it takes the instruction latency (generally one).
+    int Latency =3D getInstrLatency(ItinData, DefMI);
+
+    // For Thumb2 and -Os, prefer scheduling CPSR setting instruction clos=
e to
+    // its uses. Instructions which are otherwise scheduled between them m=
ay
+    // incur a code size penalty (not able to use the CPSR setting 16-bit
+    // instructions).
+    if (Latency > 0 && Subtarget.isThumb2()) {
+      const MachineFunction *MF =3D DefMI->getParent()->getParent();
+      if (MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize))
+        --Latency;
+    }
+    return Latency;
   }
=20
   unsigned DefAlign =3D DefMI->hasOneMemOperand()
     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
   unsigned UseAlign =3D UseMI->hasOneMemOperand()
     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
-  int Latency =3D getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
-                                  UseMCID, UseIdx, UseAlign);
+
+  unsigned DefAdj =3D 0;
+  if (DefMI->isBundle()) {
+    DefMI =3D getBundledDefMI(&getRegisterInfo(), DefMI, Reg, DefIdx, DefA=
dj);
+    if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
+        DefMI->isRegSequence() || DefMI->isImplicitDef())
+      return 1;
+    DefMCID =3D &DefMI->getDesc();
+  }
+  unsigned UseAdj =3D 0;
+  if (UseMI->isBundle()) {
+    unsigned NewUseIdx;
+    const MachineInstr *NewUseMI =3D getBundledUseMI(&getRegisterInfo(), U=
seMI,
+                                                   Reg, NewUseIdx, UseAdj);
+    if (NewUseMI) {
+      UseMI =3D NewUseMI;
+      UseIdx =3D NewUseIdx;
+      UseMCID =3D &UseMI->getDesc();
+    }
+  }
+
+  int Latency =3D getOperandLatency(ItinData, *DefMCID, DefIdx, DefAlign,
+                                  *UseMCID, UseIdx, UseAlign);
+  int Adj =3D DefAdj + UseAdj;
+  if (Adj) {
+    Latency -=3D (int)(DefAdj + UseAdj);
+    if (Latency < 1)
+      return 1;
+  }
=20
   if (Latency > 1 &&
       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
     // variants are one cycle cheaper.
-    switch (DefMCID.getOpcode()) {
+    switch (DefMCID->getOpcode()) {
     default: break;
     case ARM::LDRrs:
     case ARM::LDRBrs: {
@@ -2396,28 +2581,38 @@
   }
=20
   if (DefAlign < 8 && Subtarget.isCortexA9())
-    switch (DefMCID.getOpcode()) {
+    switch (DefMCID->getOpcode()) {
     default: break;
     case ARM::VLD1q8:
     case ARM::VLD1q16:
     case ARM::VLD1q32:
     case ARM::VLD1q64:
-    case ARM::VLD1q8_UPD:
-    case ARM::VLD1q16_UPD:
-    case ARM::VLD1q32_UPD:
-    case ARM::VLD1q64_UPD:
+    case ARM::VLD1q8wb_fixed:
+    case ARM::VLD1q16wb_fixed:
+    case ARM::VLD1q32wb_fixed:
+    case ARM::VLD1q64wb_fixed:
+    case ARM::VLD1q8wb_register:
+    case ARM::VLD1q16wb_register:
+    case ARM::VLD1q32wb_register:
+    case ARM::VLD1q64wb_register:
     case ARM::VLD2d8:
     case ARM::VLD2d16:
     case ARM::VLD2d32:
     case ARM::VLD2q8:
     case ARM::VLD2q16:
     case ARM::VLD2q32:
-    case ARM::VLD2d8_UPD:
-    case ARM::VLD2d16_UPD:
-    case ARM::VLD2d32_UPD:
-    case ARM::VLD2q8_UPD:
-    case ARM::VLD2q16_UPD:
-    case ARM::VLD2q32_UPD:
+    case ARM::VLD2d8wb_fixed:
+    case ARM::VLD2d16wb_fixed:
+    case ARM::VLD2d32wb_fixed:
+    case ARM::VLD2q8wb_fixed:
+    case ARM::VLD2q16wb_fixed:
+    case ARM::VLD2q32wb_fixed:
+    case ARM::VLD2d8wb_register:
+    case ARM::VLD2d16wb_register:
+    case ARM::VLD2d32wb_register:
+    case ARM::VLD2q8wb_register:
+    case ARM::VLD2q16wb_register:
+    case ARM::VLD2q32wb_register:
     case ARM::VLD3d8:
     case ARM::VLD3d16:
     case ARM::VLD3d32:
@@ -2425,7 +2620,8 @@
     case ARM::VLD3d8_UPD:
     case ARM::VLD3d16_UPD:
     case ARM::VLD3d32_UPD:
-    case ARM::VLD1d64T_UPD:
+    case ARM::VLD1d64Twb_fixed:
+    case ARM::VLD1d64Twb_register:
     case ARM::VLD3q8_UPD:
     case ARM::VLD3q16_UPD:
     case ARM::VLD3q32_UPD:
@@ -2436,22 +2632,29 @@
     case ARM::VLD4d8_UPD:
     case ARM::VLD4d16_UPD:
     case ARM::VLD4d32_UPD:
-    case ARM::VLD1d64Q_UPD:
+    case ARM::VLD1d64Qwb_fixed:
+    case ARM::VLD1d64Qwb_register:
     case ARM::VLD4q8_UPD:
     case ARM::VLD4q16_UPD:
     case ARM::VLD4q32_UPD:
     case ARM::VLD1DUPq8:
     case ARM::VLD1DUPq16:
     case ARM::VLD1DUPq32:
-    case ARM::VLD1DUPq8_UPD:
-    case ARM::VLD1DUPq16_UPD:
-    case ARM::VLD1DUPq32_UPD:
+    case ARM::VLD1DUPq8wb_fixed:
+    case ARM::VLD1DUPq16wb_fixed:
+    case ARM::VLD1DUPq32wb_fixed:
+    case ARM::VLD1DUPq8wb_register:
+    case ARM::VLD1DUPq16wb_register:
+    case ARM::VLD1DUPq32wb_register:
     case ARM::VLD2DUPd8:
     case ARM::VLD2DUPd16:
     case ARM::VLD2DUPd32:
-    case ARM::VLD2DUPd8_UPD:
-    case ARM::VLD2DUPd16_UPD:
-    case ARM::VLD2DUPd32_UPD:
+    case ARM::VLD2DUPd8wb_fixed:
+    case ARM::VLD2DUPd16wb_fixed:
+    case ARM::VLD2DUPd32wb_fixed:
+    case ARM::VLD2DUPd8wb_register:
+    case ARM::VLD2DUPd16wb_register:
+    case ARM::VLD2DUPd32wb_register:
     case ARM::VLD4DUPd8:
     case ARM::VLD4DUPd16:
     case ARM::VLD4DUPd32:
@@ -2559,26 +2762,36 @@
   if (DefAlign < 8 && Subtarget.isCortexA9())
     switch (DefMCID.getOpcode()) {
     default: break;
-    case ARM::VLD1q8Pseudo:
-    case ARM::VLD1q16Pseudo:
-    case ARM::VLD1q32Pseudo:
-    case ARM::VLD1q64Pseudo:
-    case ARM::VLD1q8Pseudo_UPD:
-    case ARM::VLD1q16Pseudo_UPD:
-    case ARM::VLD1q32Pseudo_UPD:
-    case ARM::VLD1q64Pseudo_UPD:
-    case ARM::VLD2d8Pseudo:
-    case ARM::VLD2d16Pseudo:
-    case ARM::VLD2d32Pseudo:
+    case ARM::VLD1q8:
+    case ARM::VLD1q16:
+    case ARM::VLD1q32:
+    case ARM::VLD1q64:
+    case ARM::VLD1q8wb_register:
+    case ARM::VLD1q16wb_register:
+    case ARM::VLD1q32wb_register:
+    case ARM::VLD1q64wb_register:
+    case ARM::VLD1q8wb_fixed:
+    case ARM::VLD1q16wb_fixed:
+    case ARM::VLD1q32wb_fixed:
+    case ARM::VLD1q64wb_fixed:
+    case ARM::VLD2d8:
+    case ARM::VLD2d16:
+    case ARM::VLD2d32:
     case ARM::VLD2q8Pseudo:
     case ARM::VLD2q16Pseudo:
     case ARM::VLD2q32Pseudo:
-    case ARM::VLD2d8Pseudo_UPD:
-    case ARM::VLD2d16Pseudo_UPD:
-    case ARM::VLD2d32Pseudo_UPD:
-    case ARM::VLD2q8Pseudo_UPD:
-    case ARM::VLD2q16Pseudo_UPD:
-    case ARM::VLD2q32Pseudo_UPD:
+    case ARM::VLD2d8wb_fixed:
+    case ARM::VLD2d16wb_fixed:
+    case ARM::VLD2d32wb_fixed:
+    case ARM::VLD2q8PseudoWB_fixed:
+    case ARM::VLD2q16PseudoWB_fixed:
+    case ARM::VLD2q32PseudoWB_fixed:
+    case ARM::VLD2d8wb_register:
+    case ARM::VLD2d16wb_register:
+    case ARM::VLD2d32wb_register:
+    case ARM::VLD2q8PseudoWB_register:
+    case ARM::VLD2q16PseudoWB_register:
+    case ARM::VLD2q32PseudoWB_register:
     case ARM::VLD3d8Pseudo:
     case ARM::VLD3d16Pseudo:
     case ARM::VLD3d32Pseudo:
@@ -2586,7 +2799,6 @@
     case ARM::VLD3d8Pseudo_UPD:
     case ARM::VLD3d16Pseudo_UPD:
     case ARM::VLD3d32Pseudo_UPD:
-    case ARM::VLD1d64TPseudo_UPD:
     case ARM::VLD3q8Pseudo_UPD:
     case ARM::VLD3q16Pseudo_UPD:
     case ARM::VLD3q32Pseudo_UPD:
@@ -2603,7 +2815,6 @@
     case ARM::VLD4d8Pseudo_UPD:
     case ARM::VLD4d16Pseudo_UPD:
     case ARM::VLD4d32Pseudo_UPD:
-    case ARM::VLD1d64QPseudo_UPD:
     case ARM::VLD4q8Pseudo_UPD:
     case ARM::VLD4q16Pseudo_UPD:
     case ARM::VLD4q32Pseudo_UPD:
@@ -2613,18 +2824,24 @@
     case ARM::VLD4q8oddPseudo_UPD:
     case ARM::VLD4q16oddPseudo_UPD:
     case ARM::VLD4q32oddPseudo_UPD:
-    case ARM::VLD1DUPq8Pseudo:
-    case ARM::VLD1DUPq16Pseudo:
-    case ARM::VLD1DUPq32Pseudo:
-    case ARM::VLD1DUPq8Pseudo_UPD:
-    case ARM::VLD1DUPq16Pseudo_UPD:
-    case ARM::VLD1DUPq32Pseudo_UPD:
-    case ARM::VLD2DUPd8Pseudo:
-    case ARM::VLD2DUPd16Pseudo:
-    case ARM::VLD2DUPd32Pseudo:
-    case ARM::VLD2DUPd8Pseudo_UPD:
-    case ARM::VLD2DUPd16Pseudo_UPD:
-    case ARM::VLD2DUPd32Pseudo_UPD:
+    case ARM::VLD1DUPq8:
+    case ARM::VLD1DUPq16:
+    case ARM::VLD1DUPq32:
+    case ARM::VLD1DUPq8wb_fixed:
+    case ARM::VLD1DUPq16wb_fixed:
+    case ARM::VLD1DUPq32wb_fixed:
+    case ARM::VLD1DUPq8wb_register:
+    case ARM::VLD1DUPq16wb_register:
+    case ARM::VLD1DUPq32wb_register:
+    case ARM::VLD2DUPd8:
+    case ARM::VLD2DUPd16:
+    case ARM::VLD2DUPd32:
+    case ARM::VLD2DUPd8wb_fixed:
+    case ARM::VLD2DUPd16wb_fixed:
+    case ARM::VLD2DUPd32wb_fixed:
+    case ARM::VLD2DUPd8wb_register:
+    case ARM::VLD2DUPd16wb_register:
+    case ARM::VLD2DUPd32wb_register:
     case ARM::VLD4DUPd8Pseudo:
     case ARM::VLD4DUPd16Pseudo:
     case ARM::VLD4DUPd32Pseudo:
@@ -2666,6 +2883,19 @@
   return Latency;
 }
=20
+unsigned
+ARMBaseInstrInfo::getOutputLatency(const InstrItineraryData *ItinData,
+                                   const MachineInstr *DefMI, unsigned Def=
Idx,
+                                   const MachineInstr *DepMI) const {
+  unsigned Reg =3D DefMI->getOperand(DefIdx).getReg();
+  if (DepMI->readsRegister(Reg, &getRegisterInfo()) || !isPredicated(DepMI=
))
+    return 1;
+
+  // If the second MI is predicated, then there is an implicit use depende=
ncy.
+  return getOperandLatency(ItinData, DefMI, DefIdx, DepMI,
+                           DepMI->getNumOperands());
+}
+
 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
                                       const MachineInstr *MI,
                                       unsigned *PredCost) const {
@@ -2676,10 +2906,21 @@
   if (!ItinData || ItinData->isEmpty())
     return 1;
=20
+  if (MI->isBundle()) {
+    int Latency =3D 0;
+    MachineBasicBlock::const_instr_iterator I =3D MI;
+    MachineBasicBlock::const_instr_iterator E =3D MI->getParent()->instr_e=
nd();
+    while (++I !=3D E && I->isInsideBundle()) {
+      if (I->getOpcode() !=3D ARM::t2IT)
+        Latency +=3D getInstrLatency(ItinData, I, PredCost);
+    }
+    return Latency;
+  }
+
   const MCInstrDesc &MCID =3D MI->getDesc();
   unsigned Class =3D MCID.getSchedClass();
   unsigned UOps =3D ItinData->Itineraries[Class].NumMicroOps;
-  if (PredCost && MCID.hasImplicitDefOfPhysReg(ARM::CPSR))
+  if (PredCost && (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR=
)))
     // When predicated, CPSR is an additional source operand for CPSR upda=
ting
     // instructions, this apparently increases their latencies.
     *PredCost =3D 1;
@@ -2828,3 +3069,7 @@
   // This will go before any implicit ops.
   AddDefaultPred(MachineInstrBuilder(MI).addOperand(MI->getOperand(1)));
 }
+
+bool ARMBaseInstrInfo::hasNOP() const {
+  return (Subtarget.getFeatureBits() & ARM::HasV6T2Ops) !=3D 0;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMBa=
seInstrInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMBaseInstrInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMBaseInstrInfo.h - ARM Base Instruction Information ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMBaseInstrInfo.h - ARM Base Instruction Information ---*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -35,6 +35,9 @@
   explicit ARMBaseInstrInfo(const ARMSubtarget &STI);
=20
 public:
+  // Return whether the target has an explicit NOP encoding.
+  bool hasNOP() const;
+
   // Return the non-pre/post incrementing version of 'Opc'. Return 0
   // if there is not such an opcode.
   virtual unsigned getUnindexedOpcode(unsigned Opc) const =3D0;
@@ -69,10 +72,7 @@
   bool ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const;
=20
   // Predication support.
-  bool isPredicated(const MachineInstr *MI) const {
-    int PIdx =3D MI->findFirstPredOperandIdx();
-    return PIdx !=3D -1 && MI->getOperand(PIdx).getImm() !=3D ARMCC::AL;
-  }
+  bool isPredicated(const MachineInstr *MI) const;
=20
   ARMCC::CondCodes getPredicate(const MachineInstr *MI) const {
     int PIdx =3D MI->findFirstPredOperandIdx();
@@ -139,6 +139,8 @@
=20
   MachineInstr *duplicate(MachineInstr *Orig, MachineFunction &MF) const;
=20
+  MachineInstr *commuteInstruction(MachineInstr*, bool=3Dfalse) const;
+
   virtual bool produceSameValue(const MachineInstr *MI0,
                                 const MachineInstr *MI1,
                                 const MachineRegisterInfo *MRI) const;
@@ -213,12 +215,18 @@
                         SDNode *DefNode, unsigned DefIdx,
                         SDNode *UseNode, unsigned UseIdx) const;
=20
+  virtual unsigned getOutputLatency(const InstrItineraryData *ItinData,
+                                    const MachineInstr *DefMI, unsigned De=
fIdx,
+                                    const MachineInstr *DepMI) const;
+
   /// VFP/NEON execution domains.
   std::pair<uint16_t, uint16_t>
   getExecutionDomain(const MachineInstr *MI) const;
   void setExecutionDomain(MachineInstr *MI, unsigned Domain) const;
=20
 private:
+  unsigned getInstBundleLength(const MachineInstr *MI) const;
+
   int getVLDMDefCycle(const InstrItineraryData *ItinData,
                       const MCInstrDesc &DefMCID,
                       unsigned DefClass,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMBa=
seRegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMBaseRegisterInfo.cpp - ARM Register Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMBaseRegisterInfo.cpp - ARM Register Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,11 +11,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "ARMBaseRegisterInfo.h"
 #include "ARM.h"
 #include "ARMBaseInstrInfo.h"
-#include "ARMBaseRegisterInfo.h"
 #include "ARMFrameLowering.h"
-#include "ARMInstrInfo.h"
 #include "ARMMachineFunctionInfo.h"
 #include "ARMSubtarget.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
@@ -61,41 +60,14 @@
     BasePtr(ARM::R6) {
 }
=20
-const unsigned*
+const uint16_t*
 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
-  bool ghcCall =3D false;
+  return (STI.isTargetIOS()) ? CSR_iOS_SaveList : CSR_AAPCS_SaveList;
+}
=20
-  if (MF) {
-    const Function *F =3D MF->getFunction();
-    ghcCall =3D (F ? F->getCallingConv() =3D=3D CallingConv::GHC : false);
-  }
-
-  static const unsigned CalleeSavedRegs[] =3D {
-    ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
-    ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
-
-    ARM::D15, ARM::D14, ARM::D13, ARM::D12,
-    ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
-    0
-  };
-
-  static const unsigned DarwinCalleeSavedRegs[] =3D {
-    // Darwin ABI deviates from ARM standard ABI. R9 is not a callee-saved
-    // register.
-    ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
-    ARM::R11, ARM::R10, ARM::R8,
-
-    ARM::D15, ARM::D14, ARM::D13, ARM::D12,
-    ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
-    0
-  };
-
-  static const unsigned GhcCalleeSavedRegs[] =3D {
-    0
-  };
-
-  return ghcCall ? GhcCalleeSavedRegs :
-         STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
+const uint32_t*
+ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID) const {
+  return (STI.isTargetIOS()) ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
 }
=20
 BitVector ARMBaseRegisterInfo::
@@ -148,104 +120,6 @@
   return false;
 }
=20
-const TargetRegisterClass *
-ARMBaseRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
-                                              const TargetRegisterClass *B,
-                                              unsigned SubIdx) const {
-  switch (SubIdx) {
-  default: return 0;
-  case ARM::ssub_0:
-  case ARM::ssub_1:
-  case ARM::ssub_2:
-  case ARM::ssub_3: {
-    // S sub-registers.
-    if (A->getSize() =3D=3D 8) {
-      if (B =3D=3D &ARM::SPR_8RegClass)
-        return &ARM::DPR_8RegClass;
-      assert(B =3D=3D &ARM::SPRRegClass && "Expecting SPR register class!"=
);
-      if (A =3D=3D &ARM::DPR_8RegClass)
-        return A;
-      return &ARM::DPR_VFP2RegClass;
-    }
-
-    if (A->getSize() =3D=3D 16) {
-      if (B =3D=3D &ARM::SPR_8RegClass)
-        return &ARM::QPR_8RegClass;
-      return &ARM::QPR_VFP2RegClass;
-    }
-
-    if (A->getSize() =3D=3D 32) {
-      if (B =3D=3D &ARM::SPR_8RegClass)
-        return 0;  // Do not allow coalescing!
-      return &ARM::QQPR_VFP2RegClass;
-    }
-
-    assert(A->getSize() =3D=3D 64 && "Expecting a QQQQ register class!");
-    return 0;  // Do not allow coalescing!
-  }
-  case ARM::dsub_0:
-  case ARM::dsub_1:
-  case ARM::dsub_2:
-  case ARM::dsub_3: {
-    // D sub-registers.
-    if (A->getSize() =3D=3D 16) {
-      if (B =3D=3D &ARM::DPR_VFP2RegClass)
-        return &ARM::QPR_VFP2RegClass;
-      if (B =3D=3D &ARM::DPR_8RegClass)
-        return 0;  // Do not allow coalescing!
-      return A;
-    }
-
-    if (A->getSize() =3D=3D 32) {
-      if (B =3D=3D &ARM::DPR_VFP2RegClass)
-        return &ARM::QQPR_VFP2RegClass;
-      if (B =3D=3D &ARM::DPR_8RegClass)
-        return 0;  // Do not allow coalescing!
-      return A;
-    }
-
-    assert(A->getSize() =3D=3D 64 && "Expecting a QQQQ register class!");
-    if (B !=3D &ARM::DPRRegClass)
-      return 0;  // Do not allow coalescing!
-    return A;
-  }
-  case ARM::dsub_4:
-  case ARM::dsub_5:
-  case ARM::dsub_6:
-  case ARM::dsub_7: {
-    // D sub-registers of QQQQ registers.
-    if (A->getSize() =3D=3D 64 && B =3D=3D &ARM::DPRRegClass)
-      return A;
-    return 0;  // Do not allow coalescing!
-  }
-
-  case ARM::qsub_0:
-  case ARM::qsub_1: {
-    // Q sub-registers.
-    if (A->getSize() =3D=3D 32) {
-      if (B =3D=3D &ARM::QPR_VFP2RegClass)
-        return &ARM::QQPR_VFP2RegClass;
-      if (B =3D=3D &ARM::QPR_8RegClass)
-        return 0;  // Do not allow coalescing!
-      return A;
-    }
-
-    assert(A->getSize() =3D=3D 64 && "Expecting a QQQQ register class!");
-    if (B =3D=3D &ARM::QPRRegClass)
-      return A;
-    return 0;  // Do not allow coalescing!
-  }
-  case ARM::qsub_2:
-  case ARM::qsub_3: {
-    // Q sub-registers of QQQQ registers.
-    if (A->getSize() =3D=3D 64 && B =3D=3D &ARM::QPRRegClass)
-      return A;
-    return 0;  // Do not allow coalescing!
-  }
-  }
-  return 0;
-}
-
 bool
 ARMBaseRegisterInfo::canCombineSubRegIndices(const TargetRegisterClass *RC,
                                           SmallVectorImpl<unsigned> &SubIn=
dices,
@@ -416,7 +290,7 @@
=20
 /// getRawAllocationOrder - Returns the register allocation order for a
 /// specified register class with a target-dependent hint.
-ArrayRef<unsigned>
+ArrayRef<uint16_t>
 ARMBaseRegisterInfo::getRawAllocationOrder(const TargetRegisterClass *RC,
                                            unsigned HintType, unsigned Hin=
tReg,
                                            const MachineFunction &MF) cons=
t {
@@ -425,71 +299,71 @@
   // of register pairs.
=20
   // No FP, R9 is available.
-  static const unsigned GPREven1[] =3D {
+  static const uint16_t GPREven1[] =3D {
     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
     ARM::R9, ARM::R11
   };
-  static const unsigned GPROdd1[] =3D {
+  static const uint16_t GPROdd1[] =3D {
     ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
     ARM::R8, ARM::R10
   };
=20
   // FP is R7, R9 is available.
-  static const unsigned GPREven2[] =3D {
+  static const uint16_t GPREven2[] =3D {
     ARM::R0, ARM::R2, ARM::R4,          ARM::R8, ARM::R10,
     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
     ARM::R9, ARM::R11
   };
-  static const unsigned GPROdd2[] =3D {
+  static const uint16_t GPROdd2[] =3D {
     ARM::R1, ARM::R3, ARM::R5,          ARM::R9, ARM::R11,
     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
     ARM::R8, ARM::R10
   };
=20
   // FP is R11, R9 is available.
-  static const unsigned GPREven3[] =3D {
+  static const uint16_t GPREven3[] =3D {
     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
     ARM::R9
   };
-  static const unsigned GPROdd3[] =3D {
+  static const uint16_t GPROdd3[] =3D {
     ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
     ARM::R8
   };
=20
   // No FP, R9 is not available.
-  static const unsigned GPREven4[] =3D {
+  static const uint16_t GPREven4[] =3D {
     ARM::R0, ARM::R2, ARM::R4, ARM::R6,          ARM::R10,
     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
     ARM::R11
   };
-  static const unsigned GPROdd4[] =3D {
+  static const uint16_t GPROdd4[] =3D {
     ARM::R1, ARM::R3, ARM::R5, ARM::R7,          ARM::R11,
     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
     ARM::R10
   };
=20
   // FP is R7, R9 is not available.
-  static const unsigned GPREven5[] =3D {
+  static const uint16_t GPREven5[] =3D {
     ARM::R0, ARM::R2, ARM::R4,                   ARM::R10,
     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
     ARM::R11
   };
-  static const unsigned GPROdd5[] =3D {
+  static const uint16_t GPROdd5[] =3D {
     ARM::R1, ARM::R3, ARM::R5,                   ARM::R11,
     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
     ARM::R10
   };
=20
   // FP is R11, R9 is not available.
-  static const unsigned GPREven6[] =3D {
+  static const uint16_t GPREven6[] =3D {
     ARM::R0, ARM::R2, ARM::R4, ARM::R6,
     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
   };
-  static const unsigned GPROdd6[] =3D {
+  static const uint16_t GPROdd6[] =3D {
     ARM::R1, ARM::R3, ARM::R5, ARM::R7,
     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
   };
@@ -610,11 +484,15 @@
 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
   const ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
+  const TargetFrameLowering *TFI =3D MF.getTarget().getFrameLowering();
=20
   if (!EnableBasePointer)
     return false;
=20
-  if (needsStackRealignment(MF) && MFI->hasVarSizedObjects())
+  // When outgoing call frames are so large that we adjust the stack point=
er
+  // around the call, we can no longer use the stack pointer to reach the
+  // emergency spill slot.
+  if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
     return true;
=20
   // Thumb has trouble with negative offsets from the FP. Thumb2 has a lim=
ited
@@ -638,14 +516,29 @@
 }
=20
 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const=
 {
-  const MachineFrameInfo *MFI =3D MF.getFrameInfo();
+  const MachineRegisterInfo *MRI =3D &MF.getRegInfo();
   const ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
   // We can't realign the stack if:
   // 1. Dynamic stack realignment is explicitly disabled,
   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
   // 3. There are VLAs in the function and the base pointer is disabled.
-  return (RealignStack && !AFI->isThumb1OnlyFunction() &&
-          (!MFI->hasVarSizedObjects() || EnableBasePointer));
+  if (!MF.getTarget().Options.RealignStack)
+    return false;
+  if (AFI->isThumb1OnlyFunction())
+    return false;
+  // Stack realignment requires a frame pointer.  If we already started
+  // register allocation with frame pointer elimination, it is too late no=
w.
+  if (!MRI->canReserveReg(FramePtr))
+    return false;
+  // We may also need a base pointer if there are dynamic allocas or stack
+  // pointer adjustments around calls.
+  if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
+    return true;
+  if (!EnableBasePointer)
+    return false;
+  // A base pointer is required and allowed.  Check that it isn't too late=
 to
+  // reserve it.
+  return MRI->canReserveReg(BasePtr);
 }
=20
 bool ARMBaseRegisterInfo::
@@ -653,7 +546,7 @@
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
   const Function *F =3D MF.getFunction();
   unsigned StackAlign =3D MF.getTarget().getFrameLowering()->getStackAlign=
ment();
-  bool requiresRealignment =3D ((MFI->getLocalFrameMaxAlign() > StackAlign=
) ||
+  bool requiresRealignment =3D ((MFI->getMaxAlignment() > StackAlign) ||
                                F->hasFnAttr(Attribute::StackAlignment));
=20
   return requiresRealignment && canRealignStack(MF);
@@ -662,7 +555,7 @@
 bool ARMBaseRegisterInfo::
 cannotEliminateFrame(const MachineFunction &MF) const {
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
-  if (DisableFramePointerElim(MF) && MFI->adjustsStack())
+  if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsSt=
ack())
     return true;
   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
     || needsStackRealignment(MF);
@@ -679,12 +572,10 @@
=20
 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
   llvm_unreachable("What is the exception register");
-  return 0;
 }
=20
 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
   llvm_unreachable("What is the exception handler register");
-  return 0;
 }
=20
 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
@@ -892,7 +783,7 @@
 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
   const MCInstrDesc &Desc =3D MI->getDesc();
   unsigned AddrMode =3D (Desc.TSFlags & ARMII::AddrModeMask);
-  int64_t InstrOffs =3D 0;;
+  int64_t InstrOffs =3D 0;
   int Scale =3D 1;
   unsigned ImmIdx =3D 0;
   switch (AddrMode) {
@@ -933,7 +824,6 @@
   }
   default:
     llvm_unreachable("Unsupported addressing mode!");
-    break;
   }
=20
   return InstrOffs * Scale;
@@ -1129,7 +1019,6 @@
     break;
   default:
     llvm_unreachable("Unsupported addressing mode!");
-    break;
   }
=20
   Offset +=3D getFrameIndexInstrOffset(MI, i);
@@ -1171,6 +1060,21 @@
=20
   int Offset =3D TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg,=
 SPAdj);
=20
+  // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because=
 the
+  // call frame setup/destroy instructions have already been eliminated.  =
That
+  // means the stack pointer cannot be used to access the emergency spill =
slot
+  // when !hasReservedCallFrame().
+#ifndef NDEBUG
+  if (RS && FrameReg =3D=3D ARM::SP && FrameIndex =3D=3D RS->getScavenging=
FrameIndex()){
+    assert(TFI->hasReservedCallFrame(MF) &&
+           "Cannot use SP to access the emergency spill slot in "
+           "functions without a reserved call frame");
+    assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
+           "Cannot use SP to access the emergency spill slot in "
+           "functions with variable sized frame objects");
+  }
+#endif // NDEBUG
+
   // Special handling of dbg_value instructions.
   if (MI.isDebugValue()) {
     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMBa=
seRegisterInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMBaseRegisterInfo.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMBaseRegisterInfo.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMBaseRegisterInfo.h - ARM Register Information Impl ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMBaseRegisterInfo.h - ARM Register Information Impl ---*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -35,7 +35,7 @@
=20
 /// isARMArea1Register - Returns true if the register is a low register (r=
0-r7)
 /// or a stack/pc register that we should push/pop.
-static inline bool isARMArea1Register(unsigned Reg, bool isDarwin) {
+static inline bool isARMArea1Register(unsigned Reg, bool isIOS) {
   using namespace ARM;
   switch (Reg) {
     case R0:  case R1:  case R2:  case R3:
@@ -43,25 +43,25 @@
     case LR:  case SP:  case PC:
       return true;
     case R8:  case R9:  case R10: case R11:
-      // For darwin we want r7 and lr to be next to each other.
-      return !isDarwin;
+      // For iOS we want r7 and lr to be next to each other.
+      return !isIOS;
     default:
       return false;
   }
 }
=20
-static inline bool isARMArea2Register(unsigned Reg, bool isDarwin) {
+static inline bool isARMArea2Register(unsigned Reg, bool isIOS) {
   using namespace ARM;
   switch (Reg) {
     case R8: case R9: case R10: case R11:
-      // Darwin has this second area.
-      return isDarwin;
+      // iOS has this second area.
+      return isIOS;
     default:
       return false;
   }
 }
=20
-static inline bool isARMArea3Register(unsigned Reg, bool isDarwin) {
+static inline bool isARMArea3Register(unsigned Reg, bool isIOS) {
   using namespace ARM;
   switch (Reg) {
     case D15: case D14: case D13: case D12:
@@ -94,17 +94,11 @@
=20
 public:
   /// Code Generation virtual methods...
-  const unsigned *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
+  const uint32_t *getCallPreservedMask(CallingConv::ID) const;
=20
   BitVector getReservedRegs(const MachineFunction &MF) const;
=20
-  /// getMatchingSuperRegClass - Return a subclass of the specified regist=
er
-  /// class A so that each register in it has a sub-register of the
-  /// specified sub-register index which is in the specified register clas=
s B.
-  virtual const TargetRegisterClass *
-  getMatchingSuperRegClass(const TargetRegisterClass *A,
-                           const TargetRegisterClass *B, unsigned Idx) con=
st;
-
   /// canCombineSubRegIndices - Given a register class and a list of
   /// subregister indices, return true if it's possible to combine the
   /// subregister indices into one that corresponds to a larger
@@ -125,7 +119,7 @@
   unsigned getRegPressureLimit(const TargetRegisterClass *RC,
                                MachineFunction &MF) const;
=20
-  ArrayRef<unsigned> getRawAllocationOrder(const TargetRegisterClass *RC,
+  ArrayRef<uint16_t> getRawAllocationOrder(const TargetRegisterClass *RC,
                                            unsigned HintType, unsigned Hin=
tReg,
                                            const MachineFunction &MF) cons=
t;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMBu=
ildAttrs.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMBuildAttrs.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMBuildAttrs.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-------- ARMBuildAttrs.h - ARM Build Attributes ------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMBuildAttrs.h - ARM Build Attributes ------------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMCa=
llingConv.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMCallingConv.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMCallingConv.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMCallingConv.h - ARM Custom Calling Convention Routines --=
-------=3D=3D=3D//
+//=3D=3D=3D ARMCallingConv.h - ARM Custom Calling Convention Routines -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,13 +15,12 @@
 #ifndef ARMCALLINGCONV_H
 #define ARMCALLINGCONV_H
=20
+#include "ARM.h"
+#include "ARMBaseInstrInfo.h"
+#include "ARMSubtarget.h"
 #include "llvm/CallingConv.h"
 #include "llvm/CodeGen/CallingConvLower.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "ARMBaseInstrInfo.h"
-#include "ARMRegisterInfo.h"
-#include "ARMSubtarget.h"
-#include "ARM.h"
=20
 namespace llvm {
=20
@@ -29,7 +28,7 @@
 static bool f64AssignAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
                           CCValAssign::LocInfo &LocInfo,
                           CCState &State, bool CanFail) {
-  static const unsigned RegList[] =3D { ARM::R0, ARM::R1, ARM::R2, ARM::R3=
 };
+  static const uint16_t RegList[] =3D { ARM::R0, ARM::R1, ARM::R2, ARM::R3=
 };
=20
   // Try to get the first register.
   if (unsigned Reg =3D State.AllocateReg(RegList, 4))
@@ -72,9 +71,9 @@
 static bool f64AssignAAPCS(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
                            CCValAssign::LocInfo &LocInfo,
                            CCState &State, bool CanFail) {
-  static const unsigned HiRegList[] =3D { ARM::R0, ARM::R2 };
-  static const unsigned LoRegList[] =3D { ARM::R1, ARM::R3 };
-  static const unsigned ShadowRegList[] =3D { ARM::R0, ARM::R1 };
+  static const uint16_t HiRegList[] =3D { ARM::R0, ARM::R2 };
+  static const uint16_t LoRegList[] =3D { ARM::R1, ARM::R3 };
+  static const uint16_t ShadowRegList[] =3D { ARM::R0, ARM::R1 };
=20
   unsigned Reg =3D State.AllocateReg(HiRegList, ShadowRegList, 2);
   if (Reg =3D=3D 0) {
@@ -118,8 +117,8 @@
=20
 static bool f64RetAssign(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
                          CCValAssign::LocInfo &LocInfo, CCState &State) {
-  static const unsigned HiRegList[] =3D { ARM::R0, ARM::R2 };
-  static const unsigned LoRegList[] =3D { ARM::R1, ARM::R3 };
+  static const uint16_t HiRegList[] =3D { ARM::R0, ARM::R2 };
+  static const uint16_t LoRegList[] =3D { ARM::R1, ARM::R3 };
=20
   unsigned Reg =3D State.AllocateReg(HiRegList, LoRegList, 2);
   if (Reg =3D=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMCa=
llingConv.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMCallingConv.td	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMCallingConv.td	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMCallingConv.td - Calling Conventions for ARM -----*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMCallingConv.td - Calling Conventions for ARM ----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -25,7 +25,7 @@
   // Handles byval parameters.
   CCIfByVal<CCPassByVal<4, 4>>,
    =20
-  CCIfType<[i8, i16], CCPromoteToType<i32>>,
+  CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
=20
   // Handle all vector types as either f64 or v2f64.
   CCIfType<[v1i64, v2i32, v4i16, v8i8, v2f32], CCBitConvertToType<f64>>,
@@ -43,6 +43,7 @@
 ]>;
=20
 def RetCC_ARM_APCS : CallingConv<[
+  CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
   CCIfType<[f32], CCBitConvertToType<i32>>,
=20
   // Handle all vector types as either f64 or v2f64.
@@ -82,25 +83,6 @@
   CCDelegateTo<RetCC_ARM_APCS>
 ]>;
=20
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// ARM APCS Calling Convention for GHC
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-def CC_ARM_APCS_GHC : CallingConv<[
-  // Handle all vector types as either f64 or v2f64.
-  CCIfType<[v1i64, v2i32, v4i16, v8i8, v2f32], CCBitConvertToType<f64>>,
-  CCIfType<[v2i64, v4i32, v8i16, v16i8, v4f32], CCBitConvertToType<v2f64>>,
-
-  CCIfType<[v2f64], CCAssignToReg<[Q4, Q5]>>,
-  CCIfType<[f64], CCAssignToReg<[D8, D9, D10, D11]>>,
-  CCIfType<[f32], CCAssignToReg<[S16, S17, S18, S19, S20, S21, S22, S23]>>,
-
-  // Promote i8/i16 arguments to i32.
-  CCIfType<[i8, i16], CCPromoteToType<i32>>,
-
-  // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, SpLim
-  CCIfType<[i32], CCAssignToReg<[R4, R5, R6, R7, R8, R9, R10, R11]>>
-]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ARM AAPCS (EABI) Calling Convention, common parts
@@ -108,7 +90,7 @@
=20
 def CC_ARM_AAPCS_Common : CallingConv<[
=20
-  CCIfType<[i8, i16], CCPromoteToType<i32>>,
+  CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
=20
   // i64/f64 is passed in even pairs of GPRs
   // i64 is 8-aligned i32 here, so we may need to eat R1 as a pad register
@@ -125,6 +107,7 @@
 ]>;
=20
 def RetCC_ARM_AAPCS_Common : CallingConv<[
+  CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
   CCIfType<[i32], CCAssignToReg<[R0, R1, R2, R3]>>,
   CCIfType<[i64], CCAssignToRegWithShadow<[R0, R2], [R1, R3]>>
 ]>;
@@ -181,3 +164,14 @@
                                  S9, S10, S11, S12, S13, S14, S15]>>,
   CCDelegateTo<RetCC_ARM_AAPCS_Common>
 ]>;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Callee-saved register lists.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+def CSR_AAPCS : CalleeSavedRegs<(add LR, R11, R10, R9, R8, R7, R6, R5, R4,
+                                     (sequence "D%u", 15, 8))>;
+
+// iOS ABI deviates from ARM standard ABI. R9 is not a callee-saved regist=
er.
+// Also save R7-R4 first to match the stack frame fixed spill areas.
+def CSR_iOS : CalleeSavedRegs<(add LR, R7, R6, R5, R4, (sub CSR_AAPCS, R9)=
)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMCo=
deEmitter.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMCodeEmitter.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMCodeEmitter.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,7 @@
 #define DEBUG_TYPE "jit"
 #include "ARM.h"
 #include "ARMConstantPoolValue.h"
-#include "ARMInstrInfo.h"
+#include "ARMBaseInstrInfo.h"
 #include "ARMRelocations.h"
 #include "ARMSubtarget.h"
 #include "ARMTargetMachine.h"
@@ -46,7 +46,7 @@
=20
   class ARMCodeEmitter : public MachineFunctionPass {
     ARMJITInfo                *JTI;
-    const ARMInstrInfo        *II;
+    const ARMBaseInstrInfo    *II;
     const TargetData          *TD;
     const ARMSubtarget        *Subtarget;
     TargetMachine             &TM;
@@ -66,7 +66,7 @@
   public:
     ARMCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce)
       : MachineFunctionPass(ID), JTI(0),
-        II((const ARMInstrInfo *)tm.getInstrInfo()),
+        II((const ARMBaseInstrInfo *)tm.getInstrInfo()),
         TD(tm.getTargetData()), TM(tm),
         MCE(mce), MCPEs(0), MJTEs(0),
         IsPIC(TM.getRelocationModel() =3D=3D Reloc::PIC_), IsThumb(false) =
{}
@@ -74,7 +74,7 @@
     /// getBinaryCodeForInstr - This function, generated by the
     /// CodeEmitterGenerator using TableGen, produces the binary encoding =
for
     /// machine instructions.
-    unsigned getBinaryCodeForInstr(const MachineInstr &MI) const;
+    uint64_t getBinaryCodeForInstr(const MachineInstr &MI) const;
=20
     bool runOnMachineFunction(MachineFunction &MF);
=20
@@ -189,6 +189,8 @@
       unsigned Op) const { return 0; }
     unsigned getARMBranchTargetOpValue(const MachineInstr &MI, unsigned Op)
       const { return 0; }
+    unsigned getARMBLTargetOpValue(const MachineInstr &MI, unsigned Op)
+      const { return 0; }
     unsigned getARMBLXTargetOpValue(const MachineInstr &MI, unsigned Op)
       const { return 0; }
     unsigned getCCOutOpValue(const MachineInstr &MI, unsigned Op)
@@ -366,9 +368,9 @@
   assert((MF.getTarget().getRelocationModel() !=3D Reloc::Default ||
           MF.getTarget().getRelocationModel() !=3D Reloc::Static) &&
          "JIT relocation model must be set to static or default!");
-  JTI =3D ((ARMTargetMachine &)MF.getTarget()).getJITInfo();
-  II =3D ((const ARMTargetMachine &)MF.getTarget()).getInstrInfo();
-  TD =3D ((const ARMTargetMachine &)MF.getTarget()).getTargetData();
+  JTI =3D ((ARMBaseTargetMachine &)MF.getTarget()).getJITInfo();
+  II =3D (const ARMBaseInstrInfo *)MF.getTarget().getInstrInfo();
+  TD =3D MF.getTarget().getTargetData();
   Subtarget =3D &TM.getSubtarget<ARMSubtarget>();
   MCPEs =3D &MF.getConstantPool()->getConstants();
   MJTEs =3D 0;
@@ -386,7 +388,7 @@
     for (MachineFunction::iterator MBB =3D MF.begin(), E =3D MF.end();
          MBB !=3D E; ++MBB) {
       MCE.StartMachineBasicBlock(MBB);
-      for (MachineBasicBlock::const_iterator I =3D MBB->begin(), E =3D MBB=
->end();
+      for (MachineBasicBlock::iterator I =3D MBB->begin(), E =3D MBB->end(=
);
            I !=3D E; ++I)
         emitInstruction(*I);
     }
@@ -406,7 +408,6 @@
   case ARM_AM::ror:
   case ARM_AM::rrx: return 3;
   }
-  return 0;
 }
=20
 /// getMovi32Value - Return binary encoding of operand for movw/movt. If t=
he
@@ -532,7 +533,6 @@
   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
   default: {
     llvm_unreachable("Unhandled instruction encoding format!");
-    break;
   }
   case ARMII::MiscFrm:
     if (MI.getOpcode() =3D=3D ARM::LEApcrelJT) {
@@ -541,7 +541,6 @@
       break;
     }
     llvm_unreachable("Unhandled instruction encoding!");
-    break;
   case ARMII::Pseudo:
     emitPseudoInstruction(MI);
     break;
@@ -837,9 +836,7 @@
   default:
     llvm_unreachable("ARMCodeEmitter::emitPseudoInstruction");
   case ARM::BX_CALL:
-  case ARM::BMOVPCRX_CALL:
-  case ARM::BXr9_CALL:
-  case ARM::BMOVPCRXr9_CALL: {
+  case ARM::BMOVPCRX_CALL: {
     // First emit mov lr, pc
     unsigned Binary =3D 0x01a0e00f;
     Binary |=3D II->getPredicate(&MI) << ARMII::CondShift;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMCo=
nstantIslandPass.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMConstantIslandPass.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMConstantIslandPass.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -16,16 +16,17 @@
 #define DEBUG_TYPE "arm-cp-islands"
 #include "ARM.h"
 #include "ARMMachineFunctionInfo.h"
-#include "ARMInstrInfo.h"
 #include "Thumb2InstrInfo.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
+#include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/Format.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
@@ -51,6 +52,44 @@
 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
           cl::desc("Adjust basic block layout to better use TB[BH]"));
=20
+// FIXME: This option should be removed once it has received sufficient te=
sting.
+static cl::opt<bool>
+AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(tr=
ue),
+          cl::desc("Align constant islands in code"));
+
+/// UnknownPadding - Return the worst case padding that could result from
+/// unknown offset bits.  This does not include alignment padding caused by
+/// known offset bits.
+///
+/// @param LogAlign log2(alignment)
+/// @param KnownBits Number of known low offset bits.
+static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBit=
s) {
+  if (KnownBits < LogAlign)
+    return (1u << LogAlign) - (1u << KnownBits);
+  return 0;
+}
+
+/// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are ex=
act,
+/// add padding such that:
+///
+/// 1. The result is aligned to 1 << LogAlign.
+///
+/// 2. No other value of the unknown bits would require more padding.
+///
+/// This may add more padding than is required to satisfy just one of the
+/// constraints.  It is necessary to compute alignment this way to guarant=
ee
+/// that we don't underestimate the padding before an aligned block.  If t=
he
+/// real padding before a block is larger than we think, constant pool ent=
ries
+/// may go out of range.
+static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
+                                      unsigned KnownBits) {
+  // Add the worst possible padding that the unknown bits could cause.
+  Offset +=3D UnknownPadding(LogAlign, KnownBits);
+
+  // Then align the result.
+  return RoundUpToAlignment(Offset, 1u << LogAlign);
+}
+
 namespace {
   /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
   /// requires constant pool entries to be scattered among the instructions
@@ -64,16 +103,70 @@
   ///   CPE     - A constant pool entry that has been placed somewhere, wh=
ich
   ///             tracks a list of users.
   class ARMConstantIslands : public MachineFunctionPass {
-    /// BBSizes - The size of each MachineBasicBlock in bytes of code, ind=
exed
-    /// by MBB Number.  The two-byte pads required for Thumb alignment are
-    /// counted as part of the following block (i.e., the offset and size =
for
-    /// a padded block will both be =3D=3D2 mod 4).
-    std::vector<unsigned> BBSizes;
+    /// BasicBlockInfo - Information about the offset and size of a single
+    /// basic block.
+    struct BasicBlockInfo {
+      /// Offset - Distance from the beginning of the function to the begi=
nning
+      /// of this basic block.
+      ///
+      /// The offset is always aligned as required by the basic block.
+      unsigned Offset;
=20
-    /// BBOffsets - the offset of each MBB in bytes, starting from 0.
-    /// The two-byte pads required for Thumb alignment are counted as part=
 of
-    /// the following block.
-    std::vector<unsigned> BBOffsets;
+      /// Size - Size of the basic block in bytes.  If the block contains
+      /// inline assembly, this is a worst case estimate.
+      ///
+      /// The size does not include any alignment padding whether from the
+      /// beginning of the block, or from an aligned jump table at the end.
+      unsigned Size;
+
+      /// KnownBits - The number of low bits in Offset that are known to be
+      /// exact.  The remaining bits of Offset are an upper bound.
+      uint8_t KnownBits;
+
+      /// Unalign - When non-zero, the block contains instructions (inline=
 asm)
+      /// of unknown size.  The real size may be smaller than Size bytes b=
y a
+      /// multiple of 1 << Unalign.
+      uint8_t Unalign;
+
+      /// PostAlign - When non-zero, the block terminator contains a .align
+      /// directive, so the end of the block is aligned to 1 << PostAlign
+      /// bytes.
+      uint8_t PostAlign;
+
+      BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
+        PostAlign(0) {}
+
+      /// Compute the number of known offset bits internally to this block.
+      /// This number should be used to predict worst case padding when
+      /// splitting the block.
+      unsigned internalKnownBits() const {
+        return Unalign ? Unalign : KnownBits;
+      }
+
+      /// Compute the offset immediately following this block.  If LogAlig=
n is
+      /// specified, return the offset the successor block will get if it =
has
+      /// this alignment.
+      unsigned postOffset(unsigned LogAlign =3D 0) const {
+        unsigned PO =3D Offset + Size;
+        unsigned LA =3D std::max(unsigned(PostAlign), LogAlign);
+        if (!LA)
+          return PO;
+        // Add alignment padding from the terminator.
+        return WorstCaseAlign(PO, LA, internalKnownBits());
+      }
+
+      /// Compute the number of known low bits of postOffset.  If this blo=
ck
+      /// contains inline asm, the number of known bits drops to the
+      /// instruction alignment.  An aligned terminator may increase the n=
umber
+      /// of know bits.
+      /// If LogAlign is given, also consider the alignment of the next bl=
ock.
+      unsigned postKnownBits(unsigned LogAlign =3D 0) const {
+        return std::max(std::max(unsigned(PostAlign), LogAlign),
+                        internalKnownBits());
+      }
+    };
+
+    std::vector<BasicBlockInfo> BBInfo;
=20
     /// WaterList - A sorted list of basic blocks where islands could be p=
laced
     /// (i.e. blocks that don't fall through to the following block, due
@@ -102,14 +195,24 @@
       MachineInstr *MI;
       MachineInstr *CPEMI;
       MachineBasicBlock *HighWaterMark;
+    private:
       unsigned MaxDisp;
+    public:
       bool NegOk;
       bool IsSoImm;
+      bool KnownAlignment;
       CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
              bool neg, bool soimm)
-        : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soim=
m) {
+        : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soim=
m),
+          KnownAlignment(false) {
         HighWaterMark =3D CPEMI->getParent();
       }
+      /// getMaxDisp - Returns the maximum displacement supported by MI.
+      /// Correct for unknown alignment.
+      /// Conservatively subtract 2 bytes to handle weird alignment effect=
s.
+      unsigned getMaxDisp() const {
+        return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
+      }
     };
=20
     /// CPUsers - Keep track of all of the machine instructions that use v=
arious
@@ -162,10 +265,9 @@
     /// the branch fix up pass.
     bool HasFarJump;
=20
-    /// HasInlineAsm - True if the function contains inline assembly.
-    bool HasInlineAsm;
-
-    const ARMInstrInfo *TII;
+    MachineFunction *MF;
+    MachineConstantPool *MCP;
+    const ARMBaseInstrInfo *TII;
     const ARMSubtarget *STI;
     ARMFunctionInfo *AFI;
     bool isThumb;
@@ -182,85 +284,100 @@
     }
=20
   private:
-    void DoInitialPlacement(MachineFunction &MF,
-                            std::vector<MachineInstr*> &CPEMIs);
+    void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
     CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
-    void JumpTableFunctionScan(MachineFunction &MF);
-    void InitialFunctionScan(MachineFunction &MF,
-                             const std::vector<MachineInstr*> &CPEMIs);
-    MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
-    void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
-    void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
-    bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
-    int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
-    bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &Water=
Iter);
-    void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
+    unsigned getCPELogAlign(const MachineInstr *CPEMI);
+    void scanFunctionJumpTables();
+    void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
+    MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
+    void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
+    void adjustBBOffsetsAfter(MachineBasicBlock *BB);
+    bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
+    int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
+    bool findAvailableWater(CPUser&U, unsigned UserOffset,
+                            water_iterator &WaterIter);
+    void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
                         MachineBasicBlock *&NewMBB);
-    bool HandleConstantPoolUser(MachineFunction &MF, unsigned CPUserIndex);
-    void RemoveDeadCPEMI(MachineInstr *CPEMI);
-    bool RemoveUnusedCPEntries();
-    bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
-                      MachineInstr *CPEMI, unsigned Disp, bool NegOk,
-                      bool DoDump =3D false);
-    bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
-                        CPUser &U);
-    bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
-                         unsigned Disp, bool NegativeOK, bool IsSoImm =3D =
false);
-    bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Dis=
p);
-    bool FixUpImmediateBr(MachineFunction &MF, ImmBranch &Br);
-    bool FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br);
-    bool FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &Br);
-    bool UndoLRSpillRestore();
-    bool OptimizeThumb2Instructions(MachineFunction &MF);
-    bool OptimizeThumb2Branches(MachineFunction &MF);
-    bool ReorderThumb2JumpTables(MachineFunction &MF);
-    bool OptimizeThumb2JumpTables(MachineFunction &MF);
-    MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
+    bool handleConstantPoolUser(unsigned CPUserIndex);
+    void removeDeadCPEMI(MachineInstr *CPEMI);
+    bool removeUnusedCPEntries();
+    bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
+                          MachineInstr *CPEMI, unsigned Disp, bool NegOk,
+                          bool DoDump =3D false);
+    bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
+                        CPUser &U, unsigned &Growth);
+    bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Dis=
p);
+    bool fixupImmediateBr(ImmBranch &Br);
+    bool fixupConditionalBr(ImmBranch &Br);
+    bool fixupUnconditionalBr(ImmBranch &Br);
+    bool undoLRSpillRestore();
+    bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
+    bool optimizeThumb2Instructions();
+    bool optimizeThumb2Branches();
+    bool reorderThumb2JumpTables();
+    bool optimizeThumb2JumpTables();
+    MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
                                                   MachineBasicBlock *JTBB);
=20
-    unsigned GetOffsetOf(MachineInstr *MI) const;
+    void computeBlockSize(MachineBasicBlock *MBB);
+    unsigned getOffsetOf(MachineInstr *MI) const;
+    unsigned getUserOffset(CPUser&) const;
     void dumpBBs();
-    void verify(MachineFunction &MF);
+    void verify();
+
+    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
+                         unsigned Disp, bool NegativeOK, bool IsSoImm =3D =
false);
+    bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
+                         const CPUser &U) {
+      return isOffsetInRange(UserOffset, TrialOffset,
+                             U.getMaxDisp(), U.NegOk, U.IsSoImm);
+    }
   };
   char ARMConstantIslands::ID =3D 0;
 }
=20
 /// verify - check BBOffsets, BBSizes, alignment of islands
-void ARMConstantIslands::verify(MachineFunction &MF) {
-  assert(BBOffsets.size() =3D=3D BBSizes.size());
-  for (unsigned i =3D 1, e =3D BBOffsets.size(); i !=3D e; ++i)
-    assert(BBOffsets[i-1]+BBSizes[i-1] =3D=3D BBOffsets[i]);
-  if (!isThumb)
-    return;
+void ARMConstantIslands::verify() {
 #ifndef NDEBUG
-  for (MachineFunction::iterator MBBI =3D MF.begin(), E =3D MF.end();
+  for (MachineFunction::iterator MBBI =3D MF->begin(), E =3D MF->end();
        MBBI !=3D E; ++MBBI) {
     MachineBasicBlock *MBB =3D MBBI;
-    if (!MBB->empty() &&
-        MBB->begin()->getOpcode() =3D=3D ARM::CONSTPOOL_ENTRY) {
-      unsigned MBBId =3D MBB->getNumber();
-      assert(HasInlineAsm ||
-             (BBOffsets[MBBId]%4 =3D=3D 0 && BBSizes[MBBId]%4 =3D=3D 0) ||
-             (BBOffsets[MBBId]%4 !=3D 0 && BBSizes[MBBId]%4 !=3D 0));
-    }
+    unsigned Align =3D MBB->getAlignment();
+    unsigned MBBId =3D MBB->getNumber();
+    assert(BBInfo[MBBId].Offset % (1u << Align) =3D=3D 0);
+    assert(!MBBId || BBInfo[MBBId - 1].postOffset() <=3D BBInfo[MBBId].Off=
set);
   }
+  DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
   for (unsigned i =3D 0, e =3D CPUsers.size(); i !=3D e; ++i) {
     CPUser &U =3D CPUsers[i];
-    unsigned UserOffset =3D GetOffsetOf(U.MI) + (isThumb ? 4 : 8);
-    unsigned CPEOffset  =3D GetOffsetOf(U.CPEMI);
-    unsigned Disp =3D UserOffset < CPEOffset ? CPEOffset - UserOffset :
-      UserOffset - CPEOffset;
-    assert(Disp <=3D U.MaxDisp || "Constant pool entry out of range!");
+    unsigned UserOffset =3D getUserOffset(U);
+    // Verify offset using the real max displacement without the safety
+    // adjustment.
+    if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.Ne=
gOk,
+                         /* DoDump =3D */ true)) {
+      DEBUG(dbgs() << "OK\n");
+      continue;
+    }
+    DEBUG(dbgs() << "Out of range.\n");
+    dumpBBs();
+    DEBUG(MF->dump());
+    llvm_unreachable("Constant pool entry out of range!");
   }
 #endif
 }
=20
 /// print block size and offset information - debugging
 void ARMConstantIslands::dumpBBs() {
-  for (unsigned J =3D 0, E =3D BBOffsets.size(); J !=3DE; ++J) {
-    DEBUG(errs() << "block " << J << " offset " << BBOffsets[J]
-                 << " size " << BBSizes[J] << "\n");
-  }
+  DEBUG({
+    for (unsigned J =3D 0, E =3D BBInfo.size(); J !=3DE; ++J) {
+      const BasicBlockInfo &BBI =3D BBInfo[J];
+      dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
+             << " kb=3D" << unsigned(BBI.KnownBits)
+             << " ua=3D" << unsigned(BBI.Unalign)
+             << " pa=3D" << unsigned(BBI.PostAlign)
+             << format(" size=3D%#x\n", BBInfo[J].Size);
+    }
+  });
 }
=20
 /// createARMConstantIslandPass - returns an instance of the constpool
@@ -269,34 +386,41 @@
   return new ARMConstantIslands();
 }
=20
-bool ARMConstantIslands::runOnMachineFunction(MachineFunction &MF) {
-  MachineConstantPool &MCP =3D *MF.getConstantPool();
+bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
+  MF =3D &mf;
+  MCP =3D mf.getConstantPool();
=20
-  TII =3D (const ARMInstrInfo*)MF.getTarget().getInstrInfo();
-  AFI =3D MF.getInfo<ARMFunctionInfo>();
-  STI =3D &MF.getTarget().getSubtarget<ARMSubtarget>();
+  DEBUG(dbgs() << "***** ARMConstantIslands: "
+               << MCP->getConstants().size() << " CP entries, aligned to "
+               << MCP->getConstantPoolAlignment() << " bytes *****\n");
+
+  TII =3D (const ARMBaseInstrInfo*)MF->getTarget().getInstrInfo();
+  AFI =3D MF->getInfo<ARMFunctionInfo>();
+  STI =3D &MF->getTarget().getSubtarget<ARMSubtarget>();
=20
   isThumb =3D AFI->isThumbFunction();
   isThumb1 =3D AFI->isThumb1OnlyFunction();
   isThumb2 =3D AFI->isThumb2Function();
=20
   HasFarJump =3D false;
-  HasInlineAsm =3D false;
+
+  // This pass invalidates liveness information when it splits basic block=
s.
+  MF->getRegInfo().invalidateLiveness();
=20
   // Renumber all of the machine basic blocks in the function, guaranteein=
g that
   // the numbers agree with the position of the block in the function.
-  MF.RenumberBlocks();
+  MF->RenumberBlocks();
=20
   // Try to reorder and otherwise adjust the block layout to make good use
   // of the TB[BH] instructions.
   bool MadeChange =3D false;
   if (isThumb2 && AdjustJumpTableBlocks) {
-    JumpTableFunctionScan(MF);
-    MadeChange |=3D ReorderThumb2JumpTables(MF);
+    scanFunctionJumpTables();
+    MadeChange |=3D reorderThumb2JumpTables();
     // Data is out of date, so clear it. It'll be re-computed later.
     T2JumpTables.clear();
     // Blocks may have shifted around. Keep the numbering up to date.
-    MF.RenumberBlocks();
+    MF->RenumberBlocks();
   }
=20
   // Thumb1 functions containing constant pools get 4-byte alignment.
@@ -304,16 +428,13 @@
=20
   // ARM and Thumb2 functions need to be 4-byte aligned.
   if (!isThumb1)
-    MF.EnsureAlignment(2);  // 2 =3D log2(4)
+    MF->EnsureAlignment(2);  // 2 =3D log2(4)
=20
   // Perform the initial placement of the constant pool entries.  To start=
 with,
   // we put them all at the end of the function.
   std::vector<MachineInstr*> CPEMIs;
-  if (!MCP.isEmpty()) {
-    DoInitialPlacement(MF, CPEMIs);
-    if (isThumb1)
-      MF.EnsureAlignment(2);  // 2 =3D log2(4)
-  }
+  if (!MCP->isEmpty())
+    doInitialPlacement(CPEMIs);
=20
   /// The next UID to take is the first unused one.
   AFI->initPICLabelUId(CPEMIs.size());
@@ -321,34 +442,36 @@
   // Do the initial scan of the function, building up information about the
   // sizes of each block, the location of all the water, and finding all o=
f the
   // constant pool users.
-  InitialFunctionScan(MF, CPEMIs);
+  initializeFunctionInfo(CPEMIs);
   CPEMIs.clear();
   DEBUG(dumpBBs());
=20
=20
   /// Remove dead constant pool entries.
-  MadeChange |=3D RemoveUnusedCPEntries();
+  MadeChange |=3D removeUnusedCPEntries();
=20
   // Iteratively place constant pool entries and fix up branches until the=
re
   // is no change.
   unsigned NoCPIters =3D 0, NoBRIters =3D 0;
   while (true) {
+    DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
     bool CPChange =3D false;
     for (unsigned i =3D 0, e =3D CPUsers.size(); i !=3D e; ++i)
-      CPChange |=3D HandleConstantPoolUser(MF, i);
+      CPChange |=3D handleConstantPoolUser(i);
     if (CPChange && ++NoCPIters > 30)
-      llvm_unreachable("Constant Island pass failed to converge!");
+      report_fatal_error("Constant Island pass failed to converge!");
     DEBUG(dumpBBs());
=20
     // Clear NewWaterList now.  If we split a block for branches, it should
     // appear as "new water" for the next iteration of constant pool place=
ment.
     NewWaterList.clear();
=20
+    DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
     bool BRChange =3D false;
     for (unsigned i =3D 0, e =3D ImmBranches.size(); i !=3D e; ++i)
-      BRChange |=3D FixUpImmediateBr(MF, ImmBranches[i]);
+      BRChange |=3D fixupImmediateBr(ImmBranches[i]);
     if (BRChange && ++NoBRIters > 30)
-      llvm_unreachable("Branch Fix Up pass failed to converge!");
+      report_fatal_error("Branch Fix Up pass failed to converge!");
     DEBUG(dumpBBs());
=20
     if (!CPChange && !BRChange)
@@ -358,15 +481,15 @@
=20
   // Shrink 32-bit Thumb2 branch, load, and store instructions.
   if (isThumb2 && !STI->prefers32BitThumb())
-    MadeChange |=3D OptimizeThumb2Instructions(MF);
+    MadeChange |=3D optimizeThumb2Instructions();
=20
   // After a while, this might be made debug-only, but it is not expensive.
-  verify(MF);
+  verify();
=20
   // If LR has been forced spilled and no far jump (i.e. BL) has been issu=
ed,
   // undo the spill / restore of LR if possible.
   if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
-    MadeChange |=3D UndoLRSpillRestore();
+    MadeChange |=3D undoLRSpillRestore();
=20
   // Save the mapping between original and cloned constpool entries.
   for (unsigned i =3D 0, e =3D CPEntries.size(); i !=3D e; ++i) {
@@ -376,10 +499,9 @@
     }
   }
=20
-  DEBUG(errs() << '\n'; dumpBBs());
+  DEBUG(dbgs() << '\n'; dumpBBs());
=20
-  BBSizes.clear();
-  BBOffsets.clear();
+  BBInfo.clear();
   WaterList.clear();
   CPUsers.clear();
   CPEntries.clear();
@@ -390,39 +512,68 @@
   return MadeChange;
 }
=20
-/// DoInitialPlacement - Perform the initial placement of the constant pool
+/// doInitialPlacement - Perform the initial placement of the constant pool
 /// entries.  To start with, we put them all at the end of the function.
-void ARMConstantIslands::DoInitialPlacement(MachineFunction &MF,
-                                        std::vector<MachineInstr*> &CPEMIs=
) {
+void
+ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs)=
 {
   // Create the basic block to hold the CPE's.
-  MachineBasicBlock *BB =3D MF.CreateMachineBasicBlock();
-  MF.push_back(BB);
+  MachineBasicBlock *BB =3D MF->CreateMachineBasicBlock();
+  MF->push_back(BB);
+
+  // MachineConstantPool measures alignment in bytes. We measure in log2(b=
ytes).
+  unsigned MaxAlign =3D Log2_32(MCP->getConstantPoolAlignment());
+
+  // Mark the basic block as required by the const-pool.
+  // If AlignConstantIslands isn't set, use 4-byte alignment for everythin=
g.
+  BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
+
+  // The function needs to be as aligned as the basic blocks. The linker m=
ay
+  // move functions around based on their alignment.
+  MF->EnsureAlignment(BB->getAlignment());
+
+  // Order the entries in BB by descending alignment.  That ensures correct
+  // alignment of all entries as long as BB is sufficiently aligned.  Keep
+  // track of the insertion point for each alignment.  We are going to buc=
ket
+  // sort the entries as they are created.
+  SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->e=
nd());
=20
   // Add all of the constants from the constant pool to the end block, use=
 an
   // identity mapping of CPI's to CPE's.
-  const std::vector<MachineConstantPoolEntry> &CPs =3D
-    MF.getConstantPool()->getConstants();
+  const std::vector<MachineConstantPoolEntry> &CPs =3D MCP->getConstants();
=20
-  const TargetData &TD =3D *MF.getTarget().getTargetData();
+  const TargetData &TD =3D *MF->getTarget().getTargetData();
   for (unsigned i =3D 0, e =3D CPs.size(); i !=3D e; ++i) {
     unsigned Size =3D TD.getTypeAllocSize(CPs[i].getType());
-    // Verify that all constant pool entries are a multiple of 4 bytes.  I=
f not,
-    // we would have to pad them out or something so that instructions stay
-    // aligned.
-    assert((Size & 3) =3D=3D 0 && "CP Entry not multiple of 4 bytes!");
+    assert(Size >=3D 4 && "Too small constant pool entry");
+    unsigned Align =3D CPs[i].getAlignment();
+    assert(isPowerOf2_32(Align) && "Invalid alignment");
+    // Verify that all constant pool entries are a multiple of their align=
ment.
+    // If not, we would have to pad them out so that instructions stay ali=
gned.
+    assert((Size % Align) =3D=3D 0 && "CP Entry not multiple of 4 bytes!");
+
+    // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
+    unsigned LogAlign =3D Log2_32(Align);
+    MachineBasicBlock::iterator InsAt =3D InsPoint[LogAlign];
     MachineInstr *CPEMI =3D
-      BuildMI(BB, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
+      BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
         .addImm(i).addConstantPoolIndex(i).addImm(Size);
     CPEMIs.push_back(CPEMI);
=20
+    // Ensure that future entries with higher alignment get inserted before
+    // CPEMI. This is bucket sort with iterators.
+    for (unsigned a =3D LogAlign + 1; a <=3D MaxAlign; ++a)
+      if (InsPoint[a] =3D=3D InsAt)
+        InsPoint[a] =3D CPEMI;
+
     // Add a new CPEntry, but no corresponding CPUser yet.
     std::vector<CPEntry> CPEs;
     CPEs.push_back(CPEntry(CPEMI, i));
     CPEntries.push_back(CPEs);
     ++NumCPEs;
-    DEBUG(errs() << "Moved CPI#" << i << " to end of function as #" << i
-                 << "\n");
+    DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size =3D "
+                 << Size << ", align =3D " << Align <<'\n');
   }
+  DEBUG(BB->dump());
 }
=20
 /// BBHasFallthrough - Return true if the specified basic block can fallth=
rough
@@ -458,41 +609,61 @@
   return NULL;
 }
=20
-/// JumpTableFunctionScan - Do a scan of the function, building up
+/// getCPELogAlign - Returns the required alignment of the constant pool e=
ntry
+/// represented by CPEMI.  Alignment is measured in log2(bytes) units.
+unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
+  assert(CPEMI && CPEMI->getOpcode() =3D=3D ARM::CONSTPOOL_ENTRY);
+
+  // Everything is 4-byte aligned unless AlignConstantIslands is set.
+  if (!AlignConstantIslands)
+    return 2;
+
+  unsigned CPI =3D CPEMI->getOperand(1).getIndex();
+  assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.=
");
+  unsigned Align =3D MCP->getConstants()[CPI].getAlignment();
+  assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
+  return Log2_32(Align);
+}
+
+/// scanFunctionJumpTables - Do a scan of the function, building up
 /// information about the sizes of each block and the locations of all
 /// the jump tables.
-void ARMConstantIslands::JumpTableFunctionScan(MachineFunction &MF) {
-  for (MachineFunction::iterator MBBI =3D MF.begin(), E =3D MF.end();
+void ARMConstantIslands::scanFunctionJumpTables() {
+  for (MachineFunction::iterator MBBI =3D MF->begin(), E =3D MF->end();
        MBBI !=3D E; ++MBBI) {
     MachineBasicBlock &MBB =3D *MBBI;
=20
     for (MachineBasicBlock::iterator I =3D MBB.begin(), E =3D MBB.end();
          I !=3D E; ++I)
-      if (I->getDesc().isBranch() && I->getOpcode() =3D=3D ARM::t2BR_JT)
+      if (I->isBranch() && I->getOpcode() =3D=3D ARM::t2BR_JT)
         T2JumpTables.push_back(I);
   }
 }
=20
-/// InitialFunctionScan - Do the initial scan of the function, building up
+/// initializeFunctionInfo - Do the initial scan of the function, building=
 up
 /// information about the sizes of each block, the location of all the wat=
er,
 /// and finding all of the constant pool users.
-void ARMConstantIslands::InitialFunctionScan(MachineFunction &MF,
-                                 const std::vector<MachineInstr*> &CPEMIs)=
 {
-  // First thing, see if the function has any inline assembly in it. If so,
-  // we have to be conservative about alignment assumptions, as we don't
-  // know for sure the size of any instructions in the inline assembly.
-  for (MachineFunction::iterator MBBI =3D MF.begin(), E =3D MF.end();
-       MBBI !=3D E; ++MBBI) {
-    MachineBasicBlock &MBB =3D *MBBI;
-    for (MachineBasicBlock::iterator I =3D MBB.begin(), E =3D MBB.end();
-         I !=3D E; ++I)
-      if (I->getOpcode() =3D=3D ARM::INLINEASM)
-        HasInlineAsm =3D true;
-  }
+void ARMConstantIslands::
+initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
+  BBInfo.clear();
+  BBInfo.resize(MF->getNumBlockIDs());
+
+  // First thing, compute the size of all basic blocks, and see if the fun=
ction
+  // has any inline assembly in it. If so, we have to be conservative about
+  // alignment assumptions, as we don't know for sure the size of any
+  // instructions in the inline assembly.
+  for (MachineFunction::iterator I =3D MF->begin(), E =3D MF->end(); I !=
=3D E; ++I)
+    computeBlockSize(I);
+
+  // The known bits of the entry block offset are determined by the functi=
on
+  // alignment.
+  BBInfo.front().KnownBits =3D MF->getAlignment();
+
+  // Compute block offsets and known bits.
+  adjustBBOffsetsAfter(MF->begin());
=20
   // Now go back through the instructions and build up our data structures.
-  unsigned Offset =3D 0;
-  for (MachineFunction::iterator MBBI =3D MF.begin(), E =3D MF.end();
+  for (MachineFunction::iterator MBBI =3D MF->begin(), E =3D MF->end();
        MBBI !=3D E; ++MBBI) {
     MachineBasicBlock &MBB =3D *MBBI;
=20
@@ -501,16 +672,13 @@
     if (!BBHasFallthrough(&MBB))
       WaterList.push_back(&MBB);
=20
-    unsigned MBBSize =3D 0;
     for (MachineBasicBlock::iterator I =3D MBB.begin(), E =3D MBB.end();
          I !=3D E; ++I) {
       if (I->isDebugValue())
         continue;
-      // Add instruction size to MBBSize.
-      MBBSize +=3D TII->GetInstSizeInBytes(I);
=20
       int Opc =3D I->getOpcode();
-      if (I->getDesc().isBranch()) {
+      if (I->isBranch()) {
         bool isCond =3D false;
         unsigned Bits =3D 0;
         unsigned Scale =3D 1;
@@ -518,18 +686,6 @@
         switch (Opc) {
         default:
           continue;  // Ignore other JT branches
-        case ARM::tBR_JTr:
-          // A Thumb1 table jump may involve padding; for the offsets to
-          // be right, functions containing these must be 4-byte aligned.
-          // tBR_JTr expands to a mov pc followed by .align 2 and then the=
 jump
-          // table entries. So this code checks whether offset of tBR_JTr =
+ 2
-          // is aligned.  That is held in Offset+MBBSize, which already has
-          // 2 added in for the size of the mov pc instruction.
-          MF.EnsureAlignment(2U);
-          if ((Offset+MBBSize)%4 !=3D 0 || HasInlineAsm)
-            // FIXME: Add a pseudo ALIGN instruction instead.
-            MBBSize +=3D 2;           // padding
-          continue;   // Does not get an entry in ImmBranches
         case ARM::t2BR_JT:
           T2JumpTables.push_back(I);
           continue;   // Does not get an entry in ImmBranches
@@ -589,7 +745,6 @@
           switch (Opc) {
           default:
             llvm_unreachable("Unknown addressing mode for CP reference!");
-            break;
=20
           // Taking the address of a CP entry.
           case ARM::LEApcrel:
@@ -647,45 +802,53 @@
           break;
         }
     }
-
-    // In thumb mode, if this block is a constpool island, we may need pad=
ding
-    // so it's aligned on 4 byte boundary.
-    if (isThumb &&
-        !MBB.empty() &&
-        MBB.begin()->getOpcode() =3D=3D ARM::CONSTPOOL_ENTRY &&
-        ((Offset%4) !=3D 0 || HasInlineAsm))
-      MBBSize +=3D 2;
-
-    BBSizes.push_back(MBBSize);
-    BBOffsets.push_back(Offset);
-    Offset +=3D MBBSize;
   }
 }
=20
-/// GetOffsetOf - Return the current offset of the specified machine instr=
uction
+/// computeBlockSize - Compute the size and some alignment information for=
 MBB.
+/// This function updates BBInfo directly.
+void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
+  BasicBlockInfo &BBI =3D BBInfo[MBB->getNumber()];
+  BBI.Size =3D 0;
+  BBI.Unalign =3D 0;
+  BBI.PostAlign =3D 0;
+
+  for (MachineBasicBlock::iterator I =3D MBB->begin(), E =3D MBB->end(); I=
 !=3D E;
+       ++I) {
+    BBI.Size +=3D TII->GetInstSizeInBytes(I);
+    // For inline asm, GetInstSizeInBytes returns a conservative estimate.
+    // The actual size may be smaller, but still a multiple of the instr s=
ize.
+    if (I->isInlineAsm())
+      BBI.Unalign =3D isThumb ? 1 : 2;
+    // Also consider instructions that may be shrunk later.
+    else if (isThumb && mayOptimizeThumb2Instruction(I))
+      BBI.Unalign =3D 1;
+  }
+
+  // tBR_JTr contains a .align 2 directive.
+  if (!MBB->empty() && MBB->back().getOpcode() =3D=3D ARM::tBR_JTr) {
+    BBI.PostAlign =3D 2;
+    MBB->getParent()->EnsureAlignment(2);
+  }
+}
+
+/// getOffsetOf - Return the current offset of the specified machine instr=
uction
 /// from the start of the function.  This offset changes as stuff is moved
 /// around inside the function.
-unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
+unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
   MachineBasicBlock *MBB =3D MI->getParent();
=20
   // The offset is composed of two things: the sum of the sizes of all MBB=
's
   // before this instruction's block, and the offset from the start of the=
 block
   // it is in.
-  unsigned Offset =3D BBOffsets[MBB->getNumber()];
-
-  // If we're looking for a CONSTPOOL_ENTRY in Thumb, see if this block has
-  // alignment padding, and compensate if so.
-  if (isThumb &&
-      MI->getOpcode() =3D=3D ARM::CONSTPOOL_ENTRY &&
-      (Offset%4 !=3D 0 || HasInlineAsm))
-    Offset +=3D 2;
+  unsigned Offset =3D BBInfo[MBB->getNumber()].Offset;
=20
   // Sum instructions before MI in MBB.
-  for (MachineBasicBlock::iterator I =3D MBB->begin(); ; ++I) {
+  for (MachineBasicBlock::iterator I =3D MBB->begin(); &*I !=3D MI; ++I) {
     assert(I !=3D MBB->end() && "Didn't find MI in its own basic block?");
-    if (&*I =3D=3D MI) return Offset;
     Offset +=3D TII->GetInstSizeInBytes(I);
   }
+  return Offset;
 }
=20
 /// CompareMBBNumbers - Little predicate function to sort the WaterList by=
 MBB
@@ -695,19 +858,16 @@
   return LHS->getNumber() < RHS->getNumber();
 }
=20
-/// UpdateForInsertedWaterBlock - When a block is newly inserted into the
+/// updateForInsertedWaterBlock - When a block is newly inserted into the
 /// machine function, it upsets all of the block numbers.  Renumber the bl=
ocks
 /// and update the arrays that parallel this numbering.
-void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *Ne=
wBB) {
+void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *Ne=
wBB) {
   // Renumber the MBB's to keep them consecutive.
   NewBB->getParent()->RenumberBlocks(NewBB);
=20
-  // Insert a size into BBSizes to align it properly with the (newly
+  // Insert an entry into BBInfo to align it properly with the (newly
   // renumbered) block numbers.
-  BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
-
-  // Likewise for BBOffsets.
-  BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
+  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
=20
   // Next, update WaterList.  Specifically, we need to add NewMBB as having
   // available water after it.
@@ -721,15 +881,14 @@
 /// Split the basic block containing MI into two blocks, which are joined =
by
 /// an unconditional branch.  Update data structures and renumber blocks to
 /// account for this change and returns the newly created block.
-MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr =
*MI) {
+MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr =
*MI) {
   MachineBasicBlock *OrigBB =3D MI->getParent();
-  MachineFunction &MF =3D *OrigBB->getParent();
=20
   // Create a new MBB for the code after the OrigBB.
   MachineBasicBlock *NewBB =3D
-    MF.CreateMachineBasicBlock(OrigBB->getBasicBlock());
+    MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
   MachineFunction::iterator MBBI =3D OrigBB; ++MBBI;
-  MF.insert(MBBI, NewBB);
+  MF->insert(MBBI, NewBB);
=20
   // Splice the instructions starting with MI over to NewBB.
   NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
@@ -747,31 +906,19 @@
   ++NumSplit;
=20
   // Update the CFG.  All succs of OrigBB are now succs of NewBB.
-  while (!OrigBB->succ_empty()) {
-    MachineBasicBlock *Succ =3D *OrigBB->succ_begin();
-    OrigBB->removeSuccessor(Succ);
-    NewBB->addSuccessor(Succ);
-
-    // This pass should be run after register allocation, so there should =
be no
-    // PHI nodes to update.
-    assert((Succ->empty() || !Succ->begin()->isPHI())
-           && "PHI nodes should be eliminated by now!");
-  }
+  NewBB->transferSuccessors(OrigBB);
=20
   // OrigBB branches to NewBB.
   OrigBB->addSuccessor(NewBB);
=20
   // Update internal data structures to account for the newly inserted MBB.
-  // This is almost the same as UpdateForInsertedWaterBlock, except that
+  // This is almost the same as updateForInsertedWaterBlock, except that
   // the Water goes after OrigBB, not NewBB.
-  MF.RenumberBlocks(NewBB);
+  MF->RenumberBlocks(NewBB);
=20
-  // Insert a size into BBSizes to align it properly with the (newly
+  // Insert an entry into BBInfo to align it properly with the (newly
   // renumbered) block numbers.
-  BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
-
-  // Likewise for BBOffsets.
-  BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
+  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
=20
   // Next, update WaterList.  Specifically, we need to add OrigMBB as havi=
ng
   // available water after it (but not if it's already there, which happens
@@ -787,86 +934,56 @@
     WaterList.insert(IP, OrigBB);
   NewWaterList.insert(OrigBB);
=20
-  unsigned OrigBBI =3D OrigBB->getNumber();
-  unsigned NewBBI =3D NewBB->getNumber();
-
-  int delta =3D isThumb1 ? 2 : 4;
-
   // Figure out how large the OrigBB is.  As the first half of the original
   // block, it cannot contain a tablejump.  The size includes
   // the new jump we added.  (It should be possible to do this without
   // recounting everything, but it's very confusing, and this is rarely
   // executed.)
-  unsigned OrigBBSize =3D 0;
-  for (MachineBasicBlock::iterator I =3D OrigBB->begin(), E =3D OrigBB->en=
d();
-       I !=3D E; ++I)
-    OrigBBSize +=3D TII->GetInstSizeInBytes(I);
-  BBSizes[OrigBBI] =3D OrigBBSize;
-
-  // ...and adjust BBOffsets for NewBB accordingly.
-  BBOffsets[NewBBI] =3D BBOffsets[OrigBBI] + BBSizes[OrigBBI];
+  computeBlockSize(OrigBB);
=20
   // Figure out how large the NewMBB is.  As the second half of the origin=
al
   // block, it may contain a tablejump.
-  unsigned NewBBSize =3D 0;
-  for (MachineBasicBlock::iterator I =3D NewBB->begin(), E =3D NewBB->end(=
);
-       I !=3D E; ++I)
-    NewBBSize +=3D TII->GetInstSizeInBytes(I);
-  // Set the size of NewBB in BBSizes.  It does not include any padding no=
w.
-  BBSizes[NewBBI] =3D NewBBSize;
-
-  MachineInstr* ThumbJTMI =3D prior(NewBB->end());
-  if (ThumbJTMI->getOpcode() =3D=3D ARM::tBR_JTr) {
-    // We've added another 2-byte instruction before this tablejump, which
-    // means we will always need padding if we didn't before, and vice ver=
sa.
-
-    // The original offset of the jump instruction was:
-    unsigned OrigOffset =3D BBOffsets[OrigBBI] + BBSizes[OrigBBI] - delta;
-    if (OrigOffset%4 =3D=3D 0) {
-      // We had padding before and now we don't.  No net change in code si=
ze.
-      delta =3D 0;
-    } else {
-      // We didn't have padding before and now we do.
-      BBSizes[NewBBI] +=3D 2;
-      delta =3D 4;
-    }
-  }
+  computeBlockSize(NewBB);
=20
   // All BBOffsets following these blocks must be modified.
-  if (delta)
-    AdjustBBOffsetsAfter(NewBB, delta);
+  adjustBBOffsetsAfter(OrigBB);
=20
   return NewBB;
 }
=20
-/// OffsetIsInRange - Checks whether UserOffset (the location of a constan=
t pool
+/// getUserOffset - Compute the offset of U.MI as seen by the hardware
+/// displacement computation.  Update U.KnownAlignment to match its current
+/// basic block location.
+unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
+  unsigned UserOffset =3D getOffsetOf(U.MI);
+  const BasicBlockInfo &BBI =3D BBInfo[U.MI->getParent()->getNumber()];
+  unsigned KnownBits =3D BBI.internalKnownBits();
+
+  // The value read from PC is offset from the actual instruction address.
+  UserOffset +=3D (isThumb ? 4 : 8);
+
+  // Because of inline assembly, we may not know the alignment (mod 4) of =
U.MI.
+  // Make sure U.getMaxDisp() returns a constrained range.
+  U.KnownAlignment =3D (KnownBits >=3D 2);
+
+  // On Thumb, offsets=3D=3D2 mod 4 are rounded down by the hardware for
+  // purposes of the displacement computation; compensate for that here.
+  // For unknown alignments, getMaxDisp() constrains the range instead.
+  if (isThumb && U.KnownAlignment)
+    UserOffset &=3D ~3u;
+
+  return UserOffset;
+}
+
+/// isOffsetInRange - Checks whether UserOffset (the location of a constan=
t pool
 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
 /// constant pool entry).
-bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
+/// UserOffset is computed by getUserOffset above to include PC adjustment=
s. If
+/// the mod 4 alignment of UserOffset is not known, the uncertainty must be
+/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
+bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
                                          unsigned TrialOffset, unsigned Ma=
xDisp,
                                          bool NegativeOK, bool IsSoImm) {
-  // On Thumb offsets=3D=3D2 mod 4 are rounded down by the hardware for
-  // purposes of the displacement computation; compensate for that here.
-  // Effectively, the valid range of displacements is 2 bytes smaller for =
such
-  // references.
-  unsigned TotalAdj =3D 0;
-  if (isThumb && UserOffset%4 !=3D0) {
-    UserOffset -=3D 2;
-    TotalAdj =3D 2;
-  }
-  // CPEs will be rounded up to a multiple of 4.
-  if (isThumb && TrialOffset%4 !=3D 0) {
-    TrialOffset +=3D 2;
-    TotalAdj +=3D 2;
-  }
-
-  // In Thumb2 mode, later branch adjustments can shift instructions up and
-  // cause alignment change. In the worst case scenario this can cause the
-  // user's effective address to be subtracted by 2 and the CPE's address =
to
-  // be plus 2.
-  if (isThumb2 && TotalAdj !=3D 4)
-    MaxDisp -=3D (4 - TotalAdj);
-
   if (UserOffset <=3D TrialOffset) {
     // User before the Trial.
     if (TrialOffset - UserOffset <=3D MaxDisp)
@@ -880,40 +997,71 @@
   return false;
 }
=20
-/// WaterIsInRange - Returns true if a CPE placed after the specified
+/// isWaterInRange - Returns true if a CPE placed after the specified
 /// Water (a basic block) will be in range for the specific MI.
+///
+/// Compute how much the function will grow by inserting a CPE after Water.
+bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
+                                        MachineBasicBlock* Water, CPUser &=
U,
+                                        unsigned &Growth) {
+  unsigned CPELogAlign =3D getCPELogAlign(U.CPEMI);
+  unsigned CPEOffset =3D BBInfo[Water->getNumber()].postOffset(CPELogAlign=
);
+  unsigned NextBlockOffset, NextBlockAlignment;
+  MachineFunction::const_iterator NextBlock =3D Water;
+  if (++NextBlock =3D=3D MF->end()) {
+    NextBlockOffset =3D BBInfo[Water->getNumber()].postOffset();
+    NextBlockAlignment =3D 0;
+  } else {
+    NextBlockOffset =3D BBInfo[NextBlock->getNumber()].Offset;
+    NextBlockAlignment =3D NextBlock->getAlignment();
+  }
+  unsigned Size =3D U.CPEMI->getOperand(2).getImm();
+  unsigned CPEEnd =3D CPEOffset + Size;
=20
-bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
-                                        MachineBasicBlock* Water, CPUser &=
U) {
-  unsigned MaxDisp =3D U.MaxDisp;
-  unsigned CPEOffset =3D BBOffsets[Water->getNumber()] +
-                       BBSizes[Water->getNumber()];
+  // The CPE may be able to hide in the alignment padding before the next
+  // block. It may also cause more padding to be required if it is more al=
igned
+  // that the next block.
+  if (CPEEnd > NextBlockOffset) {
+    Growth =3D CPEEnd - NextBlockOffset;
+    // Compute the padding that would go at the end of the CPE to align th=
e next
+    // block.
+    Growth +=3D OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
=20
-  // If the CPE is to be inserted before the instruction, that will raise
-  // the offset of the instruction.
-  if (CPEOffset < UserOffset)
-    UserOffset +=3D U.CPEMI->getOperand(2).getImm();
+    // If the CPE is to be inserted before the instruction, that will raise
+    // the offset of the instruction. Also account for unknown alignment p=
adding
+    // in blocks between CPE and the user.
+    if (CPEOffset < UserOffset)
+      UserOffset +=3D Growth + UnknownPadding(MF->getAlignment(), CPELogAl=
ign);
+  } else
+    // CPE fits in existing padding.
+    Growth =3D 0;
=20
-  return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, U.NegOk, U.IsSoIm=
m);
+  return isOffsetInRange(UserOffset, CPEOffset, U);
 }
=20
-/// CPEIsInRange - Returns true if the distance between specific MI and
+/// isCPEntryInRange - Returns true if the distance between specific MI and
 /// specific ConstPool entry instruction can fit in MI's displacement fiel=
d.
-bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffse=
t,
+bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserO=
ffset,
                                       MachineInstr *CPEMI, unsigned MaxDis=
p,
                                       bool NegOk, bool DoDump) {
-  unsigned CPEOffset  =3D GetOffsetOf(CPEMI);
-  assert((CPEOffset%4 =3D=3D 0 || HasInlineAsm) && "Misaligned CPE");
+  unsigned CPEOffset  =3D getOffsetOf(CPEMI);
+  assert(CPEOffset % 4 =3D=3D 0 && "Misaligned CPE");
=20
   if (DoDump) {
-    DEBUG(errs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
-                 << " max delta=3D" << MaxDisp
-                 << " insn address=3D" << UserOffset
-                 << " CPE address=3D" << CPEOffset
-                 << " offset=3D" << int(CPEOffset-UserOffset) << "\t" << *=
MI);
+    DEBUG({
+      unsigned Block =3D MI->getParent()->getNumber();
+      const BasicBlockInfo &BBI =3D BBInfo[Block];
+      dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
+             << " max delta=3D" << MaxDisp
+             << format(" insn address=3D%#x", UserOffset)
+             << " in BB#" << Block << ": "
+             << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
+             << format("CPE address=3D%#x offset=3D%+d: ", CPEOffset,
+                       int(CPEOffset-UserOffset));
+    });
   }
=20
-  return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
+  return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
 }
=20
 #ifndef NDEBUG
@@ -933,69 +1081,40 @@
 }
 #endif // NDEBUG
=20
-void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB,
-                                              int delta) {
-  MachineFunction::iterator MBBI =3D BB; MBBI =3D llvm::next(MBBI);
-  for(unsigned i =3D BB->getNumber()+1, e =3D BB->getParent()->getNumBlock=
IDs();
-      i < e; ++i) {
-    BBOffsets[i] +=3D delta;
-    // If some existing blocks have padding, adjust the padding as needed,=
 a
-    // bit tricky.  delta can be negative so don't use % on that.
-    if (!isThumb)
-      continue;
-    MachineBasicBlock *MBB =3D MBBI;
-    if (!MBB->empty() && !HasInlineAsm) {
-      // Constant pool entries require padding.
-      if (MBB->begin()->getOpcode() =3D=3D ARM::CONSTPOOL_ENTRY) {
-        unsigned OldOffset =3D BBOffsets[i] - delta;
-        if ((OldOffset%4) =3D=3D 0 && (BBOffsets[i]%4) !=3D 0) {
-          // add new padding
-          BBSizes[i] +=3D 2;
-          delta +=3D 2;
-        } else if ((OldOffset%4) !=3D 0 && (BBOffsets[i]%4) =3D=3D 0) {
-          // remove existing padding
-          BBSizes[i] -=3D 2;
-          delta -=3D 2;
-        }
-      }
-      // Thumb1 jump tables require padding.  They should be at the end;
-      // following unconditional branches are removed by AnalyzeBranch.
-      // tBR_JTr expands to a mov pc followed by .align 2 and then the jump
-      // table entries. So this code checks whether offset of tBR_JTr
-      // is aligned; if it is, the offset of the jump table following the
-      // instruction will not be aligned, and we need padding.
-      MachineInstr *ThumbJTMI =3D prior(MBB->end());
-      if (ThumbJTMI->getOpcode() =3D=3D ARM::tBR_JTr) {
-        unsigned NewMIOffset =3D GetOffsetOf(ThumbJTMI);
-        unsigned OldMIOffset =3D NewMIOffset - delta;
-        if ((OldMIOffset%4) =3D=3D 0 && (NewMIOffset%4) !=3D 0) {
-          // remove existing padding
-          BBSizes[i] -=3D 2;
-          delta -=3D 2;
-        } else if ((OldMIOffset%4) !=3D 0 && (NewMIOffset%4) =3D=3D 0) {
-          // add new padding
-          BBSizes[i] +=3D 2;
-          delta +=3D 2;
-        }
-      }
-      if (delta=3D=3D0)
-        return;
-    }
-    MBBI =3D llvm::next(MBBI);
+void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
+  unsigned BBNum =3D BB->getNumber();
+  for(unsigned i =3D BBNum + 1, e =3D MF->getNumBlockIDs(); i < e; ++i) {
+    // Get the offset and known bits at the end of the layout predecessor.
+    // Include the alignment of the current block.
+    unsigned LogAlign =3D MF->getBlockNumbered(i)->getAlignment();
+    unsigned Offset =3D BBInfo[i - 1].postOffset(LogAlign);
+    unsigned KnownBits =3D BBInfo[i - 1].postKnownBits(LogAlign);
+
+    // This is where block i begins.  Stop if the offset is already correc=
t,
+    // and we have updated 2 blocks.  This is the maximum number of blocks
+    // changed before calling this function.
+    if (i > BBNum + 2 &&
+        BBInfo[i].Offset =3D=3D Offset &&
+        BBInfo[i].KnownBits =3D=3D KnownBits)
+      break;
+
+    BBInfo[i].Offset =3D Offset;
+    BBInfo[i].KnownBits =3D KnownBits;
   }
 }
=20
-/// DecrementOldEntry - find the constant pool entry with index CPI
+/// decrementCPEReferenceCount - find the constant pool entry with index C=
PI
 /// and instruction CPEMI, and decrement its refcount.  If the refcount
 /// becomes 0 remove the entry and instruction.  Returns true if we removed
 /// the entry, false if we didn't.
=20
-bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPE=
MI) {
+bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
+                                                    MachineInstr *CPEMI) {
   // Find the old entry. Eliminate it if it is no longer used.
   CPEntry *CPE =3D findConstPoolEntry(CPI, CPEMI);
   assert(CPE && "Unexpected!");
   if (--CPE->RefCount =3D=3D 0) {
-    RemoveDeadCPEMI(CPEMI);
+    removeDeadCPEMI(CPEMI);
     CPE->CPEMI =3D NULL;
     --NumCPEs;
     return true;
@@ -1009,14 +1128,15 @@
 /// 0 =3D no existing entry found
 /// 1 =3D entry found, and there were no code insertions or deletions
 /// 2 =3D entry found, and there were code insertions or deletions
-int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOff=
set)
+int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
 {
   MachineInstr *UserMI =3D U.MI;
   MachineInstr *CPEMI  =3D U.CPEMI;
=20
   // Check to see if the CPE is already in-range.
-  if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, U.NegOk, true)) {
-    DEBUG(errs() << "In range\n");
+  if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
+                       true)) {
+    DEBUG(dbgs() << "In range\n");
     return 1;
   }
=20
@@ -1030,8 +1150,9 @@
     // Removing CPEs can leave empty entries, skip
     if (CPEs[i].CPEMI =3D=3D NULL)
       continue;
-    if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, U.NegOk=
)) {
-      DEBUG(errs() << "Replacing CPE#" << CPI << " with CPE#"
+    if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
+                     U.NegOk)) {
+      DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
                    << CPEs[i].CPI << "\n");
       // Point the CPUser node to the replacement
       U.CPEMI =3D CPEs[i].CPEMI;
@@ -1045,7 +1166,7 @@
       CPEs[i].RefCount++;
       // ...and the original.  If we didn't remove the old entry, none of =
the
       // addresses changed, so we don't need another pass.
-      return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
+      return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
     }
   }
   return 0;
@@ -1066,7 +1187,7 @@
   return ((1<<23)-1)*4;
 }
=20
-/// LookForWater - Look for an existing entry in the WaterList in which
+/// findAvailableWater - Look for an existing entry in the WaterList in wh=
ich
 /// we can place the CPE referenced from U so it's within range of U's MI.
 /// Returns true if found, false if not.  If it returns true, WaterIter
 /// is set to the WaterList entry.  For Thumb, prefer water that will not
@@ -1074,15 +1195,14 @@
 /// terminates, the CPE location for a particular CPUser is only allowed to
 /// move to a lower address, so search backward from the end of the list a=
nd
 /// prefer the first water that is in range.
-bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
+bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
                                       water_iterator &WaterIter) {
   if (WaterList.empty())
     return false;
=20
-  bool FoundWaterThatWouldPad =3D false;
-  water_iterator IPThatWouldPad;
-  for (water_iterator IP =3D prior(WaterList.end()),
-         B =3D WaterList.begin();; --IP) {
+  unsigned BestGrowth =3D ~0u;
+  for (water_iterator IP =3D prior(WaterList.end()), B =3D WaterList.begin=
();;
+       --IP) {
     MachineBasicBlock* WaterBB =3D *IP;
     // Check if water is in range and is either at a lower address than the
     // current "high water mark" or a new water block that was created sin=
ce
@@ -1092,166 +1212,186 @@
     // should be relatively uncommon and when it does happen, we want to be
     // sure to take advantage of it for all the CPEs near that block, so t=
hat
     // we don't insert more branches than necessary.
-    if (WaterIsInRange(UserOffset, WaterBB, U) &&
+    unsigned Growth;
+    if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
         (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
-         NewWaterList.count(WaterBB))) {
-      unsigned WBBId =3D WaterBB->getNumber();
-      if (isThumb &&
-          (BBOffsets[WBBId] + BBSizes[WBBId])%4 !=3D 0) {
-        // This is valid Water, but would introduce padding.  Remember
-        // it in case we don't find any Water that doesn't do this.
-        if (!FoundWaterThatWouldPad) {
-          FoundWaterThatWouldPad =3D true;
-          IPThatWouldPad =3D IP;
-        }
-      } else {
-        WaterIter =3D IP;
+         NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
+      // This is the least amount of required padding seen so far.
+      BestGrowth =3D Growth;
+      WaterIter =3D IP;
+      DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
+                   << " Growth=3D" << Growth << '\n');
+
+      // Keep looking unless it is perfect.
+      if (BestGrowth =3D=3D 0)
         return true;
-      }
     }
     if (IP =3D=3D B)
       break;
   }
-  if (FoundWaterThatWouldPad) {
-    WaterIter =3D IPThatWouldPad;
-    return true;
-  }
-  return false;
+  return BestGrowth !=3D ~0u;
 }
=20
-/// CreateNewWater - No existing WaterList entry will work for
+/// createNewWater - No existing WaterList entry will work for
 /// CPUsers[CPUserIndex], so create a place to put the CPE.  The end of the
 /// block is used if in range, and the conditional branch munged so control
 /// flow is correct.  Otherwise the block is split to create a hole with an
 /// unconditional branch around it.  In either case NewMBB is set to a
 /// block following which the new island can be inserted (the WaterList
 /// is not adjusted).
-void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
+void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
                                         unsigned UserOffset,
                                         MachineBasicBlock *&NewMBB) {
   CPUser &U =3D CPUsers[CPUserIndex];
   MachineInstr *UserMI =3D U.MI;
   MachineInstr *CPEMI  =3D U.CPEMI;
+  unsigned CPELogAlign =3D getCPELogAlign(CPEMI);
   MachineBasicBlock *UserMBB =3D UserMI->getParent();
-  unsigned OffsetOfNextBlock =3D BBOffsets[UserMBB->getNumber()] +
-                               BBSizes[UserMBB->getNumber()];
-  assert(OffsetOfNextBlock=3D=3D BBOffsets[UserMBB->getNumber()+1]);
+  const BasicBlockInfo &UserBBI =3D BBInfo[UserMBB->getNumber()];
=20
   // If the block does not end in an unconditional branch already, and if =
the
   // end of the block is within range, make new water there.  (The addition
   // below is for the unconditional branch we will be adding: 4 bytes on A=
RM +
-  // Thumb2, 2 on Thumb1.  Possible Thumb1 alignment padding is allowed for
-  // inside OffsetIsInRange.
-  if (BBHasFallthrough(UserMBB) &&
-      OffsetIsInRange(UserOffset, OffsetOfNextBlock + (isThumb1 ? 2: 4),
-                      U.MaxDisp, U.NegOk, U.IsSoImm)) {
-    DEBUG(errs() << "Split at end of block\n");
-    if (&UserMBB->back() =3D=3D UserMI)
-      assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
-    NewMBB =3D llvm::next(MachineFunction::iterator(UserMBB));
-    // Add an unconditional branch from UserMBB to fallthrough block.
-    // Record it for branch lengthening; this new branch will not get out =
of
-    // range, but if the preceding conditional branch is out of range, the
-    // targets will be exchanged, and the altered branch may be out of
-    // range, so the machinery has to know about it.
-    int UncondBr =3D isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
-    if (!isThumb)
-      BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
-    else
-      BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
-              .addImm(ARMCC::AL).addReg(0);
-    unsigned MaxDisp =3D getUnconditionalBrDisp(UncondBr);
-    ImmBranches.push_back(ImmBranch(&UserMBB->back(),
-                          MaxDisp, false, UncondBr));
-    int delta =3D isThumb1 ? 2 : 4;
-    BBSizes[UserMBB->getNumber()] +=3D delta;
-    AdjustBBOffsetsAfter(UserMBB, delta);
-  } else {
-    // What a big block.  Find a place within the block to split it.
-    // This is a little tricky on Thumb1 since instructions are 2 bytes
-    // and constant pool entries are 4 bytes: if instruction I references
-    // island CPE, and instruction I+1 references CPE', it will
-    // not work well to put CPE as far forward as possible, since then
-    // CPE' cannot immediately follow it (that location is 2 bytes
-    // farther away from I+1 than CPE was from I) and we'd need to create
-    // a new island.  So, we make a first guess, then walk through the
-    // instructions between the one currently being looked at and the
-    // possible insertion point, and make sure any other instructions
-    // that reference CPEs will be able to use the same island area;
-    // if not, we back up the insertion point.
+  // Thumb2, 2 on Thumb1.
+  if (BBHasFallthrough(UserMBB)) {
+    // Size of branch to insert.
+    unsigned Delta =3D isThumb1 ? 2 : 4;
+    // End of UserBlock after adding a branch.
+    unsigned UserBlockEnd =3D UserBBI.postOffset() + Delta;
+    // Compute the offset where the CPE will begin.
+    unsigned CPEOffset =3D WorstCaseAlign(UserBlockEnd, CPELogAlign,
+                                        UserBBI.postKnownBits());
=20
-    // The 4 in the following is for the unconditional branch we'll be
-    // inserting (allows for long branch on Thumb1).  Alignment of the
-    // island is handled inside OffsetIsInRange.
-    unsigned BaseInsertOffset =3D UserOffset + U.MaxDisp -4;
-    // This could point off the end of the block if we've already got
-    // constant pool entries following this block; only the last one is
-    // in the water list.  Back past any possible branches (allow for a
-    // conditional and a maximally long unconditional).
-    if (BaseInsertOffset >=3D BBOffsets[UserMBB->getNumber()+1])
-      BaseInsertOffset =3D BBOffsets[UserMBB->getNumber()+1] -
-                              (isThumb1 ? 6 : 8);
-    unsigned EndInsertOffset =3D BaseInsertOffset +
-           CPEMI->getOperand(2).getImm();
-    MachineBasicBlock::iterator MI =3D UserMI;
-    ++MI;
-    unsigned CPUIndex =3D CPUserIndex+1;
-    unsigned NumCPUsers =3D CPUsers.size();
-    MachineInstr *LastIT =3D 0;
-    for (unsigned Offset =3D UserOffset+TII->GetInstSizeInBytes(UserMI);
-         Offset < BaseInsertOffset;
-         Offset +=3D TII->GetInstSizeInBytes(MI),
-           MI =3D llvm::next(MI)) {
-      if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI =3D=3D MI) {
-        CPUser &U =3D CPUsers[CPUIndex];
-        if (!OffsetIsInRange(Offset, EndInsertOffset,
-                             U.MaxDisp, U.NegOk, U.IsSoImm)) {
-          BaseInsertOffset -=3D (isThumb1 ? 2 : 4);
-          EndInsertOffset  -=3D (isThumb1 ? 2 : 4);
-        }
-        // This is overly conservative, as we don't account for CPEMIs
-        // being reused within the block, but it doesn't matter much.
-        EndInsertOffset +=3D CPUsers[CPUIndex].CPEMI->getOperand(2).getImm=
();
-        CPUIndex++;
+    if (isOffsetInRange(UserOffset, CPEOffset, U)) {
+      DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
+            << format(", expected CPE offset %#x\n", CPEOffset));
+      NewMBB =3D llvm::next(MachineFunction::iterator(UserMBB));
+      // Add an unconditional branch from UserMBB to fallthrough block.  R=
ecord
+      // it for branch lengthening; this new branch will not get out of ra=
nge,
+      // but if the preceding conditional branch is out of range, the targ=
ets
+      // will be exchanged, and the altered branch may be out of range, so=
 the
+      // machinery has to know about it.
+      int UncondBr =3D isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::=
B;
+      if (!isThumb)
+        BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
+      else
+        BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
+          .addImm(ARMCC::AL).addReg(0);
+      unsigned MaxDisp =3D getUnconditionalBrDisp(UncondBr);
+      ImmBranches.push_back(ImmBranch(&UserMBB->back(),
+                                      MaxDisp, false, UncondBr));
+      BBInfo[UserMBB->getNumber()].Size +=3D Delta;
+      adjustBBOffsetsAfter(UserMBB);
+      return;
+    }
+  }
+
+  // What a big block.  Find a place within the block to split it.  This i=
s a
+  // little tricky on Thumb1 since instructions are 2 bytes and constant p=
ool
+  // entries are 4 bytes: if instruction I references island CPE, and
+  // instruction I+1 references CPE', it will not work well to put CPE as =
far
+  // forward as possible, since then CPE' cannot immediately follow it (th=
at
+  // location is 2 bytes farther away from I+1 than CPE was from I) and we=
'd
+  // need to create a new island.  So, we make a first guess, then walk th=
rough
+  // the instructions between the one currently being looked at and the
+  // possible insertion point, and make sure any other instructions that
+  // reference CPEs will be able to use the same island area; if not, we b=
ack
+  // up the insertion point.
+
+  // Try to split the block so it's fully aligned.  Compute the latest spl=
it
+  // point where we can add a 4-byte branch instruction, and then
+  // WorstCaseAlign to LogAlign.
+  unsigned LogAlign =3D MF->getAlignment();
+  assert(LogAlign >=3D CPELogAlign && "Over-aligned constant pool entry");
+  unsigned KnownBits =3D UserBBI.internalKnownBits();
+  unsigned UPad =3D UnknownPadding(LogAlign, KnownBits);
+  unsigned BaseInsertOffset =3D UserOffset + U.getMaxDisp();
+  DEBUG(dbgs() << format("Split in middle of big block before %#x",
+                         BaseInsertOffset));
+
+  // Account for alignment and unknown padding.
+  BaseInsertOffset &=3D ~((1u << LogAlign) - 1);
+  BaseInsertOffset -=3D UPad;
+
+  // The 4 in the following is for the unconditional branch we'll be inser=
ting
+  // (allows for long branch on Thumb1).  Alignment of the island is handl=
ed
+  // inside isOffsetInRange.
+  BaseInsertOffset -=3D 4;
+
+  DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
+               << " la=3D" << LogAlign
+               << " kb=3D" << KnownBits
+               << " up=3D" << UPad << '\n');
+
+  // This could point off the end of the block if we've already got consta=
nt
+  // pool entries following this block; only the last one is in the water =
list.
+  // Back past any possible branches (allow for a conditional and a maxima=
lly
+  // long unconditional).
+  if (BaseInsertOffset >=3D BBInfo[UserMBB->getNumber()+1].Offset)
+    BaseInsertOffset =3D BBInfo[UserMBB->getNumber()+1].Offset -
+      (isThumb1 ? 6 : 8);
+  unsigned EndInsertOffset =3D
+    WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
+    CPEMI->getOperand(2).getImm();
+  MachineBasicBlock::iterator MI =3D UserMI;
+  ++MI;
+  unsigned CPUIndex =3D CPUserIndex+1;
+  unsigned NumCPUsers =3D CPUsers.size();
+  MachineInstr *LastIT =3D 0;
+  for (unsigned Offset =3D UserOffset+TII->GetInstSizeInBytes(UserMI);
+       Offset < BaseInsertOffset;
+       Offset +=3D TII->GetInstSizeInBytes(MI),
+       MI =3D llvm::next(MI)) {
+    if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI =3D=3D MI) {
+      CPUser &U =3D CPUsers[CPUIndex];
+      if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
+        // Shift intertion point by one unit of alignment so it is within =
reach.
+        BaseInsertOffset -=3D 1u << LogAlign;
+        EndInsertOffset  -=3D 1u << LogAlign;
       }
-
-      // Remember the last IT instruction.
-      if (MI->getOpcode() =3D=3D ARM::t2IT)
-        LastIT =3D MI;
+      // This is overly conservative, as we don't account for CPEMIs being
+      // reused within the block, but it doesn't matter much.  Also assume=
 CPEs
+      // are added in order with alignment padding.  We may eventually be =
able
+      // to pack the aligned CPEs better.
+      EndInsertOffset =3D RoundUpToAlignment(EndInsertOffset,
+                                           1u << getCPELogAlign(U.CPEMI)) +
+        U.CPEMI->getOperand(2).getImm();
+      CPUIndex++;
     }
=20
-    DEBUG(errs() << "Split in middle of big block\n");
-    --MI;
+    // Remember the last IT instruction.
+    if (MI->getOpcode() =3D=3D ARM::t2IT)
+      LastIT =3D MI;
+  }
=20
-    // Avoid splitting an IT block.
-    if (LastIT) {
-      unsigned PredReg =3D 0;
-      ARMCC::CondCodes CC =3D llvm::getITInstrPredicate(MI, PredReg);
-      if (CC !=3D ARMCC::AL)
-        MI =3D LastIT;
-    }
-    NewMBB =3D SplitBlockBeforeInstr(MI);
+  --MI;
+
+  // Avoid splitting an IT block.
+  if (LastIT) {
+    unsigned PredReg =3D 0;
+    ARMCC::CondCodes CC =3D getITInstrPredicate(MI, PredReg);
+    if (CC !=3D ARMCC::AL)
+      MI =3D LastIT;
   }
+  NewMBB =3D splitBlockBeforeInstr(MI);
 }
=20
-/// HandleConstantPoolUser - Analyze the specified user, checking to see i=
f it
+/// handleConstantPoolUser - Analyze the specified user, checking to see i=
f it
 /// is out-of-range.  If so, pick up the constant pool value and move it s=
ome
 /// place in-range.  Return true if we changed any addresses (thus must run
 /// another pass of branch lengthening), false otherwise.
-bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &MF,
-                                                unsigned CPUserIndex) {
+bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
   CPUser &U =3D CPUsers[CPUserIndex];
   MachineInstr *UserMI =3D U.MI;
   MachineInstr *CPEMI  =3D U.CPEMI;
   unsigned CPI =3D CPEMI->getOperand(1).getIndex();
   unsigned Size =3D CPEMI->getOperand(2).getImm();
-  // Compute this only once, it's expensive.  The 4 or 8 is the value the
-  // hardware keeps in the PC.
-  unsigned UserOffset =3D GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
+  // Compute this only once, it's expensive.
+  unsigned UserOffset =3D getUserOffset(U);
=20
   // See if the current entry is within range, or there is a clone of it
   // in range.
-  int result =3D LookForExistingCPEntry(U, UserOffset);
+  int result =3D findInRangeCPEntry(U, UserOffset);
   if (result=3D=3D1) return false;
   else if (result=3D=3D2) return true;
=20
@@ -1260,11 +1400,11 @@
   unsigned ID =3D AFI->createPICLabelUId();
=20
   // Look for water where we can place this CPE.
-  MachineBasicBlock *NewIsland =3D MF.CreateMachineBasicBlock();
+  MachineBasicBlock *NewIsland =3D MF->CreateMachineBasicBlock();
   MachineBasicBlock *NewMBB;
   water_iterator IP;
-  if (LookForWater(U, UserOffset, IP)) {
-    DEBUG(errs() << "found water in range\n");
+  if (findAvailableWater(U, UserOffset, IP)) {
+    DEBUG(dbgs() << "Found water in range\n");
     MachineBasicBlock *WaterBB =3D *IP;
=20
     // If the original WaterList entry was "new water" on this iteration,
@@ -1279,10 +1419,10 @@
=20
   } else {
     // No water found.
-    DEBUG(errs() << "No water found\n");
-    CreateNewWater(CPUserIndex, UserOffset, NewMBB);
+    DEBUG(dbgs() << "No water found\n");
+    createNewWater(CPUserIndex, UserOffset, NewMBB);
=20
-    // SplitBlockBeforeInstr adds to WaterList, which is important when it=
 is
+    // splitBlockBeforeInstr adds to WaterList, which is important when it=
 is
     // called while handling branches so that the water will be seen on the
     // next iteration for constant pools, but in this context, we don't wa=
nt
     // it.  Check for this so it will be removed from the WaterList.
@@ -1304,13 +1444,13 @@
     WaterList.erase(IP);
=20
   // Okay, we know we can put an island before NewMBB now, do it!
-  MF.insert(NewMBB, NewIsland);
+  MF->insert(NewMBB, NewIsland);
=20
   // Update internal data structures to account for the newly inserted MBB.
-  UpdateForInsertedWaterBlock(NewIsland);
+  updateForInsertedWaterBlock(NewIsland);
=20
   // Decrement the old entry, and remove it if refcount becomes 0.
-  DecrementOldEntry(CPI, CPEMI);
+  decrementCPEReferenceCount(CPI, CPEMI);
=20
   // Now that we have an island to add the CPE to, clone the original CPE =
and
   // add it to the island.
@@ -1320,13 +1460,12 @@
   CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
   ++NumCPEs;
=20
-  BBOffsets[NewIsland->getNumber()] =3D BBOffsets[NewMBB->getNumber()];
-  // Compensate for .align 2 in thumb mode.
-  if (isThumb && (BBOffsets[NewIsland->getNumber()]%4 !=3D 0 || HasInlineA=
sm))
-    Size +=3D 2;
+  // Mark the basic block as aligned as required by the const-pool entry.
+  NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
+
   // Increase the size of the island block to account for the new entry.
-  BBSizes[NewIsland->getNumber()] +=3D Size;
-  AdjustBBOffsetsAfter(NewIsland, Size);
+  BBInfo[NewIsland->getNumber()].Size +=3D Size;
+  adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
=20
   // Finally, change the CPI in the instruction operand to be ID.
   for (unsigned i =3D 0, e =3D UserMI->getNumOperands(); i !=3D e; ++i)
@@ -1335,31 +1474,30 @@
       break;
     }
=20
-  DEBUG(errs() << "  Moved CPE to #" << ID << " CPI=3D" << CPI
-           << '\t' << *UserMI);
+  DEBUG(dbgs() << "  Moved CPE to #" << ID << " CPI=3D" << CPI
+        << format(" offset=3D%#x\n", BBInfo[NewIsland->getNumber()].Offset=
));
=20
   return true;
 }
=20
-/// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
+/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
 /// sizes and offsets of impacted basic blocks.
-void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
+void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
   MachineBasicBlock *CPEBB =3D CPEMI->getParent();
   unsigned Size =3D CPEMI->getOperand(2).getImm();
   CPEMI->eraseFromParent();
-  BBSizes[CPEBB->getNumber()] -=3D Size;
+  BBInfo[CPEBB->getNumber()].Size -=3D Size;
   // All succeeding offsets have the current size value added in, fix this.
   if (CPEBB->empty()) {
-    // In thumb1 mode, the size of island may be padded by two to compensa=
te for
-    // the alignment requirement.  Then it will now be 2 when the block is
-    // empty, so fix this.
-    // All succeeding offsets have the current size value added in, fix th=
is.
-    if (BBSizes[CPEBB->getNumber()] !=3D 0) {
-      Size +=3D BBSizes[CPEBB->getNumber()];
-      BBSizes[CPEBB->getNumber()] =3D 0;
-    }
-  }
-  AdjustBBOffsetsAfter(CPEBB, -Size);
+    BBInfo[CPEBB->getNumber()].Size =3D 0;
+
+    // This block no longer needs to be aligned. <rdar://problem/10534709>.
+    CPEBB->setAlignment(0);
+  } else
+    // Entries are sorted by descending alignment, so realign from the fro=
nt.
+    CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
+
+  adjustBBOffsetsAfter(CPEBB);
   // An island has only one predecessor BB and one successor BB. Check if
   // this BB's predecessor jumps directly to this BB's successor. This
   // shouldn't happen currently.
@@ -1367,15 +1505,15 @@
   // FIXME: remove the empty blocks after all the work is done?
 }
=20
-/// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
+/// removeUnusedCPEntries - Remove constant pool entries whose refcounts
 /// are zero.
-bool ARMConstantIslands::RemoveUnusedCPEntries() {
+bool ARMConstantIslands::removeUnusedCPEntries() {
   unsigned MadeChange =3D false;
   for (unsigned i =3D 0, e =3D CPEntries.size(); i !=3D e; ++i) {
       std::vector<CPEntry> &CPEs =3D CPEntries[i];
       for (unsigned j =3D 0, ee =3D CPEs.size(); j !=3D ee; ++j) {
         if (CPEs[j].RefCount =3D=3D 0 && CPEs[j].CPEMI) {
-          RemoveDeadCPEMI(CPEs[j].CPEMI);
+          removeDeadCPEMI(CPEs[j].CPEMI);
           CPEs[j].CPEMI =3D NULL;
           MadeChange =3D true;
         }
@@ -1384,18 +1522,18 @@
   return MadeChange;
 }
=20
-/// BBIsInRange - Returns true if the distance between specific MI and
+/// isBBInRange - Returns true if the distance between specific MI and
 /// specific BB can fit in MI's displacement field.
-bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *D=
estBB,
+bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *D=
estBB,
                                      unsigned MaxDisp) {
   unsigned PCAdj      =3D isThumb ? 4 : 8;
-  unsigned BrOffset   =3D GetOffsetOf(MI) + PCAdj;
-  unsigned DestOffset =3D BBOffsets[DestBB->getNumber()];
+  unsigned BrOffset   =3D getOffsetOf(MI) + PCAdj;
+  unsigned DestOffset =3D BBInfo[DestBB->getNumber()].Offset;
=20
-  DEBUG(errs() << "Branch of destination BB#" << DestBB->getNumber()
+  DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
                << " from BB#" << MI->getParent()->getNumber()
                << " max delta=3D" << MaxDisp
-               << " from " << GetOffsetOf(MI) << " to " << DestOffset
+               << " from " << getOffsetOf(MI) << " to " << DestOffset
                << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
=20
   if (BrOffset <=3D DestOffset) {
@@ -1409,50 +1547,50 @@
   return false;
 }
=20
-/// FixUpImmediateBr - Fix up an immediate branch whose destination is too=
 far
+/// fixupImmediateBr - Fix up an immediate branch whose destination is too=
 far
 /// away to fit in its displacement field.
-bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &MF, ImmBranch &=
Br) {
+bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
   MachineInstr *MI =3D Br.MI;
   MachineBasicBlock *DestBB =3D MI->getOperand(0).getMBB();
=20
   // Check to see if the DestBB is already in-range.
-  if (BBIsInRange(MI, DestBB, Br.MaxDisp))
+  if (isBBInRange(MI, DestBB, Br.MaxDisp))
     return false;
=20
   if (!Br.isCond)
-    return FixUpUnconditionalBr(MF, Br);
-  return FixUpConditionalBr(MF, Br);
+    return fixupUnconditionalBr(Br);
+  return fixupConditionalBr(Br);
 }
=20
-/// FixUpUnconditionalBr - Fix up an unconditional branch whose destinatio=
n is
+/// fixupUnconditionalBr - Fix up an unconditional branch whose destinatio=
n is
 /// too far away to fit in its displacement field. If the LR register has =
been
 /// spilled in the epilogue, then we can use BL to implement a far jump.
 /// Otherwise, add an intermediate branch instruction to a branch.
 bool
-ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &MF, ImmBranch &B=
r) {
+ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
   MachineInstr *MI =3D Br.MI;
   MachineBasicBlock *MBB =3D MI->getParent();
   if (!isThumb1)
-    llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
+    llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
=20
   // Use BL to implement far jump.
   Br.MaxDisp =3D (1 << 21) * 2;
   MI->setDesc(TII->get(ARM::tBfar));
-  BBSizes[MBB->getNumber()] +=3D 2;
-  AdjustBBOffsetsAfter(MBB, 2);
+  BBInfo[MBB->getNumber()].Size +=3D 2;
+  adjustBBOffsetsAfter(MBB);
   HasFarJump =3D true;
   ++NumUBrFixed;
=20
-  DEBUG(errs() << "  Changed B to long jump " << *MI);
+  DEBUG(dbgs() << "  Changed B to long jump " << *MI);
=20
   return true;
 }
=20
-/// FixUpConditionalBr - Fix up a conditional branch whose destination is =
too
+/// fixupConditionalBr - Fix up a conditional branch whose destination is =
too
 /// far away to fit in its displacement field. It is converted to an inver=
se
 /// conditional branch + an unconditional branch to the destination.
 bool
-ARMConstantIslands::FixUpConditionalBr(MachineFunction &MF, ImmBranch &Br)=
 {
+ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
   MachineInstr *MI =3D Br.MI;
   MachineBasicBlock *DestBB =3D MI->getOperand(0).getMBB();
=20
@@ -1486,8 +1624,8 @@
       // bne L2
       // b   L1
       MachineBasicBlock *NewDest =3D BMI->getOperand(0).getMBB();
-      if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
-        DEBUG(errs() << "  Invert Bcc condition and swap its destination w=
ith "
+      if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
+        DEBUG(dbgs() << "  Invert Bcc condition and swap its destination w=
ith "
                      << *BMI);
         BMI->getOperand(0).setMBB(DestBB);
         MI->getOperand(0).setMBB(NewDest);
@@ -1498,19 +1636,17 @@
   }
=20
   if (NeedSplit) {
-    SplitBlockBeforeInstr(MI);
+    splitBlockBeforeInstr(MI);
     // No need for the branch to the next block. We're adding an unconditi=
onal
     // branch to the destination.
     int delta =3D TII->GetInstSizeInBytes(&MBB->back());
-    BBSizes[MBB->getNumber()] -=3D delta;
-    MachineBasicBlock* SplitBB =3D llvm::next(MachineFunction::iterator(MB=
B));
-    AdjustBBOffsetsAfter(SplitBB, -delta);
+    BBInfo[MBB->getNumber()].Size -=3D delta;
     MBB->back().eraseFromParent();
-    // BBOffsets[SplitBB] is wrong temporarily, fixed below
+    // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
   }
   MachineBasicBlock *NextBB =3D llvm::next(MachineFunction::iterator(MBB));
=20
-  DEBUG(errs() << "  Insert B to BB#" << DestBB->getNumber()
+  DEBUG(dbgs() << "  Insert B to BB#" << DestBB->getNumber()
                << " also invert condition and change dest. to BB#"
                << NextBB->getNumber() << "\n");
=20
@@ -1519,30 +1655,27 @@
   BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
     .addMBB(NextBB).addImm(CC).addReg(CCReg);
   Br.MI =3D &MBB->back();
-  BBSizes[MBB->getNumber()] +=3D TII->GetInstSizeInBytes(&MBB->back());
+  BBInfo[MBB->getNumber()].Size +=3D TII->GetInstSizeInBytes(&MBB->back());
   if (isThumb)
     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
             .addImm(ARMCC::AL).addReg(0);
   else
     BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
-  BBSizes[MBB->getNumber()] +=3D TII->GetInstSizeInBytes(&MBB->back());
+  BBInfo[MBB->getNumber()].Size +=3D TII->GetInstSizeInBytes(&MBB->back());
   unsigned MaxDisp =3D getUnconditionalBrDisp(Br.UncondBr);
   ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondB=
r));
=20
   // Remove the old conditional branch.  It may or may not still be in MBB.
-  BBSizes[MI->getParent()->getNumber()] -=3D TII->GetInstSizeInBytes(MI);
+  BBInfo[MI->getParent()->getNumber()].Size -=3D TII->GetInstSizeInBytes(M=
I);
   MI->eraseFromParent();
-
-  // The net size change is an addition of one unconditional branch.
-  int delta =3D TII->GetInstSizeInBytes(&MBB->back());
-  AdjustBBOffsetsAfter(MBB, delta);
+  adjustBBOffsetsAfter(MBB);
   return true;
 }
=20
-/// UndoLRSpillRestore - Remove Thumb push / pop instructions that only sp=
ills
+/// undoLRSpillRestore - Remove Thumb push / pop instructions that only sp=
ills
 /// LR / restores LR to pc. FIXME: This is done here because it's only pos=
sible
 /// to do this if tBfar is not used.
-bool ARMConstantIslands::UndoLRSpillRestore() {
+bool ARMConstantIslands::undoLRSpillRestore() {
   bool MadeChange =3D false;
   for (unsigned i =3D 0, e =3D PushPopMIs.size(); i !=3D e; ++i) {
     MachineInstr *MI =3D PushPopMIs[i];
@@ -1561,7 +1694,26 @@
   return MadeChange;
 }
=20
-bool ARMConstantIslands::OptimizeThumb2Instructions(MachineFunction &MF) {
+// mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructio=
ns
+// below may shrink MI.
+bool
+ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) c=
onst {
+  switch(MI->getOpcode()) {
+    // optimizeThumb2Instructions.
+    case ARM::t2LEApcrel:
+    case ARM::t2LDRpci:
+    // optimizeThumb2Branches.
+    case ARM::t2B:
+    case ARM::t2Bcc:
+    case ARM::tBcc:
+    // optimizeThumb2JumpTables.
+    case ARM::t2BR_JT:
+      return true;
+  }
+  return false;
+}
+
+bool ARMConstantIslands::optimizeThumb2Instructions() {
   bool MadeChange =3D false;
=20
   // Shrink ADR and LDR from constantpool.
@@ -1592,25 +1744,31 @@
     if (!NewOpc)
       continue;
=20
-    unsigned UserOffset =3D GetOffsetOf(U.MI) + 4;
+    unsigned UserOffset =3D getUserOffset(U);
     unsigned MaxOffs =3D ((1 << Bits) - 1) * Scale;
+
+    // Be conservative with inline asm.
+    if (!U.KnownAlignment)
+      MaxOffs -=3D 2;
+
     // FIXME: Check if offset is multiple of scale if scale is not 4.
-    if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
+    if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true))=
 {
+      DEBUG(dbgs() << "Shrink: " << *U.MI);
       U.MI->setDesc(TII->get(NewOpc));
       MachineBasicBlock *MBB =3D U.MI->getParent();
-      BBSizes[MBB->getNumber()] -=3D 2;
-      AdjustBBOffsetsAfter(MBB, -2);
+      BBInfo[MBB->getNumber()].Size -=3D 2;
+      adjustBBOffsetsAfter(MBB);
       ++NumT2CPShrunk;
       MadeChange =3D true;
     }
   }
=20
-  MadeChange |=3D OptimizeThumb2Branches(MF);
-  MadeChange |=3D OptimizeThumb2JumpTables(MF);
+  MadeChange |=3D optimizeThumb2Branches();
+  MadeChange |=3D optimizeThumb2JumpTables();
   return MadeChange;
 }
=20
-bool ARMConstantIslands::OptimizeThumb2Branches(MachineFunction &MF) {
+bool ARMConstantIslands::optimizeThumb2Branches() {
   bool MadeChange =3D false;
=20
   for (unsigned i =3D 0, e =3D ImmBranches.size(); i !=3D e; ++i) {
@@ -1636,11 +1794,12 @@
     if (NewOpc) {
       unsigned MaxOffs =3D ((1 << (Bits-1))-1) * Scale;
       MachineBasicBlock *DestBB =3D Br.MI->getOperand(0).getMBB();
-      if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
+      if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
+        DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
         Br.MI->setDesc(TII->get(NewOpc));
         MachineBasicBlock *MBB =3D Br.MI->getParent();
-        BBSizes[MBB->getNumber()] -=3D 2;
-        AdjustBBOffsetsAfter(MBB, -2);
+        BBInfo[MBB->getNumber()].Size -=3D 2;
+        adjustBBOffsetsAfter(MBB);
         ++NumT2BrShrunk;
         MadeChange =3D true;
       }
@@ -1650,9 +1809,14 @@
     if (Opcode !=3D ARM::tBcc)
       continue;
=20
+    // If the conditional branch doesn't kill CPSR, then CPSR can be liveo=
ut
+    // so this transformation is not safe.
+    if (!Br.MI->killsRegister(ARM::CPSR))
+      continue;
+
     NewOpc =3D 0;
     unsigned PredReg =3D 0;
-    ARMCC::CondCodes Pred =3D llvm::getInstrPredicate(Br.MI, PredReg);
+    ARMCC::CondCodes Pred =3D getInstrPredicate(Br.MI, PredReg);
     if (Pred =3D=3D ARMCC::EQ)
       NewOpc =3D ARM::tCBZ;
     else if (Pred =3D=3D ARMCC::NE)
@@ -1662,27 +1826,28 @@
     MachineBasicBlock *DestBB =3D Br.MI->getOperand(0).getMBB();
     // Check if the distance is within 126. Subtract starting offset by 2
     // because the cmp will be eliminated.
-    unsigned BrOffset =3D GetOffsetOf(Br.MI) + 4 - 2;
-    unsigned DestOffset =3D BBOffsets[DestBB->getNumber()];
+    unsigned BrOffset =3D getOffsetOf(Br.MI) + 4 - 2;
+    unsigned DestOffset =3D BBInfo[DestBB->getNumber()].Offset;
     if (BrOffset < DestOffset && (DestOffset - BrOffset) <=3D 126) {
       MachineBasicBlock::iterator CmpMI =3D Br.MI;
       if (CmpMI !=3D Br.MI->getParent()->begin()) {
         --CmpMI;
         if (CmpMI->getOpcode() =3D=3D ARM::tCMPi8) {
           unsigned Reg =3D CmpMI->getOperand(0).getReg();
-          Pred =3D llvm::getInstrPredicate(CmpMI, PredReg);
+          Pred =3D getInstrPredicate(CmpMI, PredReg);
           if (Pred =3D=3D ARMCC::AL &&
               CmpMI->getOperand(1).getImm() =3D=3D 0 &&
               isARMLowRegister(Reg)) {
             MachineBasicBlock *MBB =3D Br.MI->getParent();
+            DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
             MachineInstr *NewBR =3D
               BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
               .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFla=
gs());
             CmpMI->eraseFromParent();
             Br.MI->eraseFromParent();
             Br.MI =3D NewBR;
-            BBSizes[MBB->getNumber()] -=3D 2;
-            AdjustBBOffsetsAfter(MBB, -2);
+            BBInfo[MBB->getNumber()].Size -=3D 2;
+            adjustBBOffsetsAfter(MBB);
             ++NumCBZ;
             MadeChange =3D true;
           }
@@ -1694,14 +1859,14 @@
   return MadeChange;
 }
=20
-/// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smal=
ler
+/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smal=
ler
 /// jumptables when it's possible.
-bool ARMConstantIslands::OptimizeThumb2JumpTables(MachineFunction &MF) {
+bool ARMConstantIslands::optimizeThumb2JumpTables() {
   bool MadeChange =3D false;
=20
   // FIXME: After the tables are shrunk, can we get rid some of the
   // constantpool tables?
-  MachineJumpTableInfo *MJTI =3D MF.getJumpTableInfo();
+  MachineJumpTableInfo *MJTI =3D MF->getJumpTableInfo();
   if (MJTI =3D=3D 0) return false;
=20
   const std::vector<MachineJumpTableEntry> &JT =3D MJTI->getJumpTables();
@@ -1709,18 +1874,18 @@
     MachineInstr *MI =3D T2JumpTables[i];
     const MCInstrDesc &MCID =3D MI->getDesc();
     unsigned NumOps =3D MCID.getNumOperands();
-    unsigned JTOpIdx =3D NumOps - (MCID.isPredicable() ? 3 : 2);
+    unsigned JTOpIdx =3D NumOps - (MI->isPredicable() ? 3 : 2);
     MachineOperand JTOP =3D MI->getOperand(JTOpIdx);
     unsigned JTI =3D JTOP.getIndex();
     assert(JTI < JT.size());
=20
     bool ByteOk =3D true;
     bool HalfWordOk =3D true;
-    unsigned JTOffset =3D GetOffsetOf(MI) + 4;
+    unsigned JTOffset =3D getOffsetOf(MI) + 4;
     const std::vector<MachineBasicBlock*> &JTBBs =3D JT[JTI].MBBs;
     for (unsigned j =3D 0, ee =3D JTBBs.size(); j !=3D ee; ++j) {
       MachineBasicBlock *MBB =3D JTBBs[j];
-      unsigned DstOffset =3D BBOffsets[MBB->getNumber()];
+      unsigned DstOffset =3D BBInfo[MBB->getNumber()].Offset;
       // Negative offset is not ok. FIXME: We should change BB layout to m=
ake
       // sure all the branches are forward.
       if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
@@ -1791,11 +1956,14 @@
       if (!OptOk)
         continue;
=20
+      DEBUG(dbgs() << "Shrink JT: " << *MI << "     addr: " << *AddrMI
+                   << "      lea: " << *LeaMI);
       unsigned Opc =3D ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
       MachineInstr *NewJTMI =3D BuildMI(MBB, MI->getDebugLoc(), TII->get(O=
pc))
         .addReg(IdxReg, getKillRegState(IdxRegKill))
         .addJumpTableIndex(JTI, JTOP.getTargetFlags())
         .addImm(MI->getOperand(JTOpIdx+1).getImm());
+      DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
       // FIXME: Insert an "ALIGN" instruction to ensure the next instructi=
on
       // is 2-byte aligned. For now, asm printer will fix it up.
       unsigned NewSize =3D TII->GetInstSizeInBytes(NewJTMI);
@@ -1808,8 +1976,8 @@
       MI->eraseFromParent();
=20
       int delta =3D OrigSize - NewSize;
-      BBSizes[MBB->getNumber()] -=3D delta;
-      AdjustBBOffsetsAfter(MBB, -delta);
+      BBInfo[MBB->getNumber()].Size -=3D delta;
+      adjustBBOffsetsAfter(MBB);
=20
       ++NumTBs;
       MadeChange =3D true;
@@ -1819,12 +1987,12 @@
   return MadeChange;
 }
=20
-/// ReorderThumb2JumpTables - Adjust the function's block layout to ensure=
 that
+/// reorderThumb2JumpTables - Adjust the function's block layout to ensure=
 that
 /// jump tables always branch forwards, since that's what tbb and tbh need.
-bool ARMConstantIslands::ReorderThumb2JumpTables(MachineFunction &MF) {
+bool ARMConstantIslands::reorderThumb2JumpTables() {
   bool MadeChange =3D false;
=20
-  MachineJumpTableInfo *MJTI =3D MF.getJumpTableInfo();
+  MachineJumpTableInfo *MJTI =3D MF->getJumpTableInfo();
   if (MJTI =3D=3D 0) return false;
=20
   const std::vector<MachineJumpTableEntry> &JT =3D MJTI->getJumpTables();
@@ -1832,7 +2000,7 @@
     MachineInstr *MI =3D T2JumpTables[i];
     const MCInstrDesc &MCID =3D MI->getDesc();
     unsigned NumOps =3D MCID.getNumOperands();
-    unsigned JTOpIdx =3D NumOps - (MCID.isPredicable() ? 3 : 2);
+    unsigned JTOpIdx =3D NumOps - (MI->isPredicable() ? 3 : 2);
     MachineOperand JTOP =3D MI->getOperand(JTOpIdx);
     unsigned JTI =3D JTOP.getIndex();
     assert(JTI < JT.size());
@@ -1850,7 +2018,7 @@
         // The destination precedes the switch. Try to move the block forw=
ard
         // so we have a positive offset.
         MachineBasicBlock *NewBB =3D
-          AdjustJTTargetBlockForward(MBB, MI->getParent());
+          adjustJTTargetBlockForward(MBB, MI->getParent());
         if (NewBB)
           MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
         MadeChange =3D true;
@@ -1862,10 +2030,7 @@
 }
=20
 MachineBasicBlock *ARMConstantIslands::
-AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
-{
-  MachineFunction &MF =3D *BB->getParent();
-
+adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)=
 {
   // If the destination block is terminated by an unconditional branch,
   // try to move it; otherwise, create a new block following the jump
   // table that branches back to the actual target. This is a very simple
@@ -1882,22 +2047,22 @@
   // If the block ends in an unconditional branch, move it. The prior block
   // has to have an analyzable terminator for us to move this one. Be para=
noid
   // and make sure we're not trying to move the entry block of the functio=
n.
-  if (!B && Cond.empty() && BB !=3D MF.begin() &&
+  if (!B && Cond.empty() && BB !=3D MF->begin() &&
       !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
     BB->moveAfter(JTBB);
     OldPrior->updateTerminator();
     BB->updateTerminator();
     // Update numbering to account for the block being moved.
-    MF.RenumberBlocks();
+    MF->RenumberBlocks();
     ++NumJTMoved;
     return NULL;
   }
=20
   // Create a new MBB for the code after the jump BB.
   MachineBasicBlock *NewBB =3D
-    MF.CreateMachineBasicBlock(JTBB->getBasicBlock());
+    MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
   MachineFunction::iterator MBBI =3D JTBB; ++MBBI;
-  MF.insert(MBBI, NewBB);
+  MF->insert(MBBI, NewBB);
=20
   // Add an unconditional branch from NewBB to BB.
   // There doesn't seem to be meaningful DebugInfo available; this doesn't
@@ -1907,7 +2072,7 @@
           .addImm(ARMCC::AL).addReg(0);
=20
   // Update internal data structures to account for the newly inserted MBB.
-  MF.RenumberBlocks(NewBB);
+  MF->RenumberBlocks(NewBB);
=20
   // Update the CFG.
   NewBB->addSuccessor(BB);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMCo=
nstantPoolValue.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMConstantPoolValue.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMConstantPoolValue.cpp - ARM constantpool value --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMConstantPoolValue.cpp - ARM constantpool value ----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -48,7 +48,6 @@
=20
 const char *ARMConstantPoolValue::getModifierText() const {
   switch (Modifier) {
-  default: llvm_unreachable("Unknown modifier!");
     // FIXME: Are these case sensitive? It'd be nice to lower-case all the
     // strings if that's legal.
   case ARMCP::no_modifier: return "none";
@@ -58,12 +57,12 @@
   case ARMCP::GOTTPOFF:    return "gottpoff";
   case ARMCP::TPOFF:       return "tpoff";
   }
+  llvm_unreachable("Unknown modifier!");
 }
=20
 int ARMConstantPoolValue::getExistingMachineCPValue(MachineConstantPool *C=
P,
                                                     unsigned Alignment) {
-  assert(false && "Shouldn't be calling this directly!");
-  return -1;
+  llvm_unreachable("Shouldn't be calling this directly!");
 }
=20
 void
@@ -315,5 +314,6 @@
 }
=20
 void ARMConstantPoolMBB::print(raw_ostream &O) const {
+  O << "BB#" << MBB->getNumber();
   ARMConstantPoolValue::print(O);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMCo=
nstantPoolValue.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMConstantPoolValue.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMConstantPoolValue.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMConstantPoolValue.h - ARM constantpool value ----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMConstantPoolValue.h - ARM constantpool value ---------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMEL=
FWriterInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMELFWriterInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMELFWriterInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -41,43 +41,38 @@
   case ARM::reloc_arm_machine_cp_entry:
   case ARM::reloc_arm_jt_base:
   case ARM::reloc_arm_pic_jt:
-    assert(0 && "unsupported ARM relocation type"); break;
-   =20
-  case ARM::reloc_arm_branch: return ELF::R_ARM_CALL; break;
-  case ARM::reloc_arm_movt:   return ELF::R_ARM_MOVT_ABS; break;
-  case ARM::reloc_arm_movw:   return ELF::R_ARM_MOVW_ABS_NC; break;
+    llvm_unreachable("unsupported ARM relocation type");
+
+  case ARM::reloc_arm_branch: return ELF::R_ARM_CALL;
+  case ARM::reloc_arm_movt:   return ELF::R_ARM_MOVT_ABS;
+  case ARM::reloc_arm_movw:   return ELF::R_ARM_MOVW_ABS_NC;
   default:
-    llvm_unreachable("unknown ARM relocation type"); break;
+    llvm_unreachable("unknown ARM relocation type");
   }
-  return 0;
 }
=20
 long int ARMELFWriterInfo::getDefaultAddendForRelTy(unsigned RelTy,
                                                     long int Modifier) con=
st {
-  assert(0 && "ARMELFWriterInfo::getDefaultAddendForRelTy() not implemente=
d");
-  return 0;
+  llvm_unreachable("ARMELFWriterInfo::getDefaultAddendForRelTy() not "
+                   "implemented");
 }
=20
 unsigned ARMELFWriterInfo::getRelocationTySize(unsigned RelTy) const {
-  assert(0 && "ARMELFWriterInfo::getRelocationTySize() not implemented");
-  return 0;
+  llvm_unreachable("ARMELFWriterInfo::getRelocationTySize() not implemente=
d");
 }
=20
 bool ARMELFWriterInfo::isPCRelativeRel(unsigned RelTy) const {
-  assert(0 && "ARMELFWriterInfo::isPCRelativeRel() not implemented");
-  return 1;
+  llvm_unreachable("ARMELFWriterInfo::isPCRelativeRel() not implemented");
 }
=20
 unsigned ARMELFWriterInfo::getAbsoluteLabelMachineRelTy() const {
-  assert(0 &&
-         "ARMELFWriterInfo::getAbsoluteLabelMachineRelTy() not implemented=
");
-  return 0;
+  llvm_unreachable("ARMELFWriterInfo::getAbsoluteLabelMachineRelTy() not "
+                   "implemented");
 }
=20
 long int ARMELFWriterInfo::computeRelocation(unsigned SymOffset,
                                              unsigned RelOffset,
                                              unsigned RelTy) const {
-  assert(0 &&
-         "ARMELFWriterInfo::getAbsoluteLabelMachineRelTy() not implemented=
");
-  return 0;
+  llvm_unreachable("ARMELFWriterInfo::getAbsoluteLabelMachineRelTy() not "
+                   "implemented");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMEL=
FWriterInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMELFWriterInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMELFWriterInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -17,6 +17,7 @@
 #include "llvm/Target/TargetELFWriterInfo.h"
=20
 namespace llvm {
+  class TargetMachine;
=20
   class ARMELFWriterInfo : public TargetELFWriterInfo {
   public:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMEx=
pandPseudoInsts.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMExpandPseudoInsts.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMExpandPseudoInsts.cpp - Expand pseudo instructions -----*=
- C++ -*-=3D//
+//=3D=3D=3D-- ARMExpandPseudoInsts.cpp - Expand pseudo instructions ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -19,7 +19,6 @@
 #include "ARMBaseInstrInfo.h"
 #include "ARMBaseRegisterInfo.h"
 #include "ARMMachineFunctionInfo.h"
-#include "ARMRegisterInfo.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
@@ -61,7 +60,7 @@
     void ExpandVST(MachineBasicBlock::iterator &MBBI);
     void ExpandLaneOp(MachineBasicBlock::iterator &MBBI);
     void ExpandVTBL(MachineBasicBlock::iterator &MBBI,
-                    unsigned Opc, bool IsExt, unsigned NumRegs);
+                    unsigned Opc, bool IsExt);
     void ExpandMOV32BitImm(MachineBasicBlock &MBB,
                            MachineBasicBlock::iterator &MBBI);
   };
@@ -99,13 +98,20 @@
   // Entries for NEON load/store information table.  The table is sorted by
   // PseudoOpc for fast binary-search lookups.
   struct NEONLdStTableEntry {
-    unsigned PseudoOpc;
-    unsigned RealOpc;
+    uint16_t PseudoOpc;
+    uint16_t RealOpc;
     bool IsLoad;
-    bool HasWriteBack;
+    bool isUpdating;
+    bool hasWritebackOperand;
     NEONRegSpacing RegSpacing;
     unsigned char NumRegs; // D registers loaded or stored
     unsigned char RegElts; // elements per D register; used for lane ops
+    // FIXME: Temporary flag to denote whether the real instruction takes
+    // a single register (like the encoding) or all of the registers in
+    // the list (like the asm syntax and the isel DAG). When all definitio=
ns
+    // are converted to take only the single encoded register, this will
+    // go away.
+    bool copyAllListRegs;
=20
     // Comparison methods for binary search of the table.
     bool operator<(const NEONLdStTableEntry &TE) const {
@@ -122,243 +128,203 @@
 }
=20
 static const NEONLdStTableEntry NEONLdStTable[] =3D {
-{ ARM::VLD1DUPq16Pseudo,     ARM::VLD1DUPq16,     true, false, SingleSpc, =
2, 4},
-{ ARM::VLD1DUPq16Pseudo_UPD, ARM::VLD1DUPq16_UPD, true, true,  SingleSpc, =
2, 4},
-{ ARM::VLD1DUPq32Pseudo,     ARM::VLD1DUPq32,     true, false, SingleSpc, =
2, 2},
-{ ARM::VLD1DUPq32Pseudo_UPD, ARM::VLD1DUPq32_UPD, true, true,  SingleSpc, =
2, 2},
-{ ARM::VLD1DUPq8Pseudo,      ARM::VLD1DUPq8,      true, false, SingleSpc, =
2, 8},
-{ ARM::VLD1DUPq8Pseudo_UPD,  ARM::VLD1DUPq8_UPD,  true, true,  SingleSpc, =
2, 8},
+{ ARM::VLD1LNq16Pseudo,     ARM::VLD1LNd16,     true, false, false, EvenDb=
lSpc, 1, 4 ,true},
+{ ARM::VLD1LNq16Pseudo_UPD, ARM::VLD1LNd16_UPD, true, true, true,  EvenDbl=
Spc, 1, 4 ,true},
+{ ARM::VLD1LNq32Pseudo,     ARM::VLD1LNd32,     true, false, false, EvenDb=
lSpc, 1, 2 ,true},
+{ ARM::VLD1LNq32Pseudo_UPD, ARM::VLD1LNd32_UPD, true, true, true,  EvenDbl=
Spc, 1, 2 ,true},
+{ ARM::VLD1LNq8Pseudo,      ARM::VLD1LNd8,      true, false, false, EvenDb=
lSpc, 1, 8 ,true},
+{ ARM::VLD1LNq8Pseudo_UPD,  ARM::VLD1LNd8_UPD, true, true, true,  EvenDblS=
pc, 1, 8 ,true},
=20
-{ ARM::VLD1LNq16Pseudo,     ARM::VLD1LNd16,     true, false, EvenDblSpc, 1=
, 4 },
-{ ARM::VLD1LNq16Pseudo_UPD, ARM::VLD1LNd16_UPD, true, true,  EvenDblSpc, 1=
, 4 },
-{ ARM::VLD1LNq32Pseudo,     ARM::VLD1LNd32,     true, false, EvenDblSpc, 1=
, 2 },
-{ ARM::VLD1LNq32Pseudo_UPD, ARM::VLD1LNd32_UPD, true, true,  EvenDblSpc, 1=
, 2 },
-{ ARM::VLD1LNq8Pseudo,      ARM::VLD1LNd8,      true, false, EvenDblSpc, 1=
, 8 },
-{ ARM::VLD1LNq8Pseudo_UPD,  ARM::VLD1LNd8_UPD,  true, true,  EvenDblSpc, 1=
, 8 },
+{ ARM::VLD1d64QPseudo,      ARM::VLD1d64Q,     true,  false, false, Single=
Spc,  4, 1 ,false},
+{ ARM::VLD1d64TPseudo,      ARM::VLD1d64T,     true,  false, false, Single=
Spc,  3, 1 ,false},
=20
-{ ARM::VLD1d64QPseudo,      ARM::VLD1d64Q,     true,  false, SingleSpc,  4=
, 1 },
-{ ARM::VLD1d64QPseudo_UPD,  ARM::VLD1d64Q_UPD, true,  true,  SingleSpc,  4=
, 1 },
-{ ARM::VLD1d64TPseudo,      ARM::VLD1d64T,     true,  false, SingleSpc,  3=
, 1 },
-{ ARM::VLD1d64TPseudo_UPD,  ARM::VLD1d64T_UPD, true,  true,  SingleSpc,  3=
, 1 },
+{ ARM::VLD2LNd16Pseudo,     ARM::VLD2LNd16,     true, false, false, Single=
Spc,  2, 4 ,true},
+{ ARM::VLD2LNd16Pseudo_UPD, ARM::VLD2LNd16_UPD, true, true, true,  SingleS=
pc,  2, 4 ,true},
+{ ARM::VLD2LNd32Pseudo,     ARM::VLD2LNd32,     true, false, false, Single=
Spc,  2, 2 ,true},
+{ ARM::VLD2LNd32Pseudo_UPD, ARM::VLD2LNd32_UPD, true, true, true,  SingleS=
pc,  2, 2 ,true},
+{ ARM::VLD2LNd8Pseudo,      ARM::VLD2LNd8,      true, false, false, Single=
Spc,  2, 8 ,true},
+{ ARM::VLD2LNd8Pseudo_UPD,  ARM::VLD2LNd8_UPD, true, true, true,  SingleSp=
c,  2, 8 ,true},
+{ ARM::VLD2LNq16Pseudo,     ARM::VLD2LNq16,     true, false, false, EvenDb=
lSpc, 2, 4 ,true},
+{ ARM::VLD2LNq16Pseudo_UPD, ARM::VLD2LNq16_UPD, true, true, true,  EvenDbl=
Spc, 2, 4 ,true},
+{ ARM::VLD2LNq32Pseudo,     ARM::VLD2LNq32,     true, false, false, EvenDb=
lSpc, 2, 2 ,true},
+{ ARM::VLD2LNq32Pseudo_UPD, ARM::VLD2LNq32_UPD, true, true, true,  EvenDbl=
Spc, 2, 2 ,true},
=20
-{ ARM::VLD1q16Pseudo,       ARM::VLD1q16,      true,  false, SingleSpc,  2=
, 4 },
-{ ARM::VLD1q16Pseudo_UPD,   ARM::VLD1q16_UPD,  true,  true,  SingleSpc,  2=
, 4 },
-{ ARM::VLD1q32Pseudo,       ARM::VLD1q32,      true,  false, SingleSpc,  2=
, 2 },
-{ ARM::VLD1q32Pseudo_UPD,   ARM::VLD1q32_UPD,  true,  true,  SingleSpc,  2=
, 2 },
-{ ARM::VLD1q64Pseudo,       ARM::VLD1q64,      true,  false, SingleSpc,  2=
, 1 },
-{ ARM::VLD1q64Pseudo_UPD,   ARM::VLD1q64_UPD,  true,  true,  SingleSpc,  2=
, 1 },
-{ ARM::VLD1q8Pseudo,        ARM::VLD1q8,       true,  false, SingleSpc,  2=
, 8 },
-{ ARM::VLD1q8Pseudo_UPD,    ARM::VLD1q8_UPD,   true,  true,  SingleSpc,  2=
, 8 },
+{ ARM::VLD2q16Pseudo,       ARM::VLD2q16,      true,  false, false, Single=
Spc,  4, 4 ,false},
+{ ARM::VLD2q16PseudoWB_fixed,   ARM::VLD2q16wb_fixed, true, true, false,  =
SingleSpc,  4, 4 ,false},
+{ ARM::VLD2q16PseudoWB_register,   ARM::VLD2q16wb_register, true, true, tr=
ue,  SingleSpc,  4, 4 ,false},
+{ ARM::VLD2q32Pseudo,       ARM::VLD2q32,      true,  false, false, Single=
Spc,  4, 2 ,false},
+{ ARM::VLD2q32PseudoWB_fixed,   ARM::VLD2q32wb_fixed, true, true, false,  =
SingleSpc,  4, 2 ,false},
+{ ARM::VLD2q32PseudoWB_register,   ARM::VLD2q32wb_register, true, true, tr=
ue,  SingleSpc,  4, 2 ,false},
+{ ARM::VLD2q8Pseudo,        ARM::VLD2q8,       true,  false, false, Single=
Spc,  4, 8 ,false},
+{ ARM::VLD2q8PseudoWB_fixed,    ARM::VLD2q8wb_fixed, true, true, false,  S=
ingleSpc,  4, 8 ,false},
+{ ARM::VLD2q8PseudoWB_register,    ARM::VLD2q8wb_register, true, true, tru=
e,  SingleSpc,  4, 8 ,false},
=20
-{ ARM::VLD2DUPd16Pseudo,     ARM::VLD2DUPd16,     true, false, SingleSpc, =
2, 4},
-{ ARM::VLD2DUPd16Pseudo_UPD, ARM::VLD2DUPd16_UPD, true, true,  SingleSpc, =
2, 4},
-{ ARM::VLD2DUPd32Pseudo,     ARM::VLD2DUPd32,     true, false, SingleSpc, =
2, 2},
-{ ARM::VLD2DUPd32Pseudo_UPD, ARM::VLD2DUPd32_UPD, true, true,  SingleSpc, =
2, 2},
-{ ARM::VLD2DUPd8Pseudo,      ARM::VLD2DUPd8,      true, false, SingleSpc, =
2, 8},
-{ ARM::VLD2DUPd8Pseudo_UPD,  ARM::VLD2DUPd8_UPD,  true, true,  SingleSpc, =
2, 8},
+{ ARM::VLD3DUPd16Pseudo,     ARM::VLD3DUPd16,     true, false, false, Sing=
leSpc, 3, 4,true},
+{ ARM::VLD3DUPd16Pseudo_UPD, ARM::VLD3DUPd16_UPD, true, true, true,  Singl=
eSpc, 3, 4,true},
+{ ARM::VLD3DUPd32Pseudo,     ARM::VLD3DUPd32,     true, false, false, Sing=
leSpc, 3, 2,true},
+{ ARM::VLD3DUPd32Pseudo_UPD, ARM::VLD3DUPd32_UPD, true, true, true,  Singl=
eSpc, 3, 2,true},
+{ ARM::VLD3DUPd8Pseudo,      ARM::VLD3DUPd8,      true, false, false, Sing=
leSpc, 3, 8,true},
+{ ARM::VLD3DUPd8Pseudo_UPD,  ARM::VLD3DUPd8_UPD, true, true, true,  Single=
Spc, 3, 8,true},
=20
-{ ARM::VLD2LNd16Pseudo,     ARM::VLD2LNd16,     true, false, SingleSpc,  2=
, 4 },
-{ ARM::VLD2LNd16Pseudo_UPD, ARM::VLD2LNd16_UPD, true, true,  SingleSpc,  2=
, 4 },
-{ ARM::VLD2LNd32Pseudo,     ARM::VLD2LNd32,     true, false, SingleSpc,  2=
, 2 },
-{ ARM::VLD2LNd32Pseudo_UPD, ARM::VLD2LNd32_UPD, true, true,  SingleSpc,  2=
, 2 },
-{ ARM::VLD2LNd8Pseudo,      ARM::VLD2LNd8,      true, false, SingleSpc,  2=
, 8 },
-{ ARM::VLD2LNd8Pseudo_UPD,  ARM::VLD2LNd8_UPD,  true, true,  SingleSpc,  2=
, 8 },
-{ ARM::VLD2LNq16Pseudo,     ARM::VLD2LNq16,     true, false, EvenDblSpc, 2=
, 4 },
-{ ARM::VLD2LNq16Pseudo_UPD, ARM::VLD2LNq16_UPD, true, true,  EvenDblSpc, 2=
, 4 },
-{ ARM::VLD2LNq32Pseudo,     ARM::VLD2LNq32,     true, false, EvenDblSpc, 2=
, 2 },
-{ ARM::VLD2LNq32Pseudo_UPD, ARM::VLD2LNq32_UPD, true, true,  EvenDblSpc, 2=
, 2 },
+{ ARM::VLD3LNd16Pseudo,     ARM::VLD3LNd16,     true, false, false, Single=
Spc,  3, 4 ,true},
+{ ARM::VLD3LNd16Pseudo_UPD, ARM::VLD3LNd16_UPD, true, true, true,  SingleS=
pc,  3, 4 ,true},
+{ ARM::VLD3LNd32Pseudo,     ARM::VLD3LNd32,     true, false, false, Single=
Spc,  3, 2 ,true},
+{ ARM::VLD3LNd32Pseudo_UPD, ARM::VLD3LNd32_UPD, true, true, true,  SingleS=
pc,  3, 2 ,true},
+{ ARM::VLD3LNd8Pseudo,      ARM::VLD3LNd8,      true, false, false, Single=
Spc,  3, 8 ,true},
+{ ARM::VLD3LNd8Pseudo_UPD,  ARM::VLD3LNd8_UPD, true, true, true,  SingleSp=
c,  3, 8 ,true},
+{ ARM::VLD3LNq16Pseudo,     ARM::VLD3LNq16,     true, false, false, EvenDb=
lSpc, 3, 4 ,true},
+{ ARM::VLD3LNq16Pseudo_UPD, ARM::VLD3LNq16_UPD, true, true, true,  EvenDbl=
Spc, 3, 4 ,true},
+{ ARM::VLD3LNq32Pseudo,     ARM::VLD3LNq32,     true, false, false, EvenDb=
lSpc, 3, 2 ,true},
+{ ARM::VLD3LNq32Pseudo_UPD, ARM::VLD3LNq32_UPD, true, true, true,  EvenDbl=
Spc, 3, 2 ,true},
=20
-{ ARM::VLD2d16Pseudo,       ARM::VLD2d16,      true,  false, SingleSpc,  2=
, 4 },
-{ ARM::VLD2d16Pseudo_UPD,   ARM::VLD2d16_UPD,  true,  true,  SingleSpc,  2=
, 4 },
-{ ARM::VLD2d32Pseudo,       ARM::VLD2d32,      true,  false, SingleSpc,  2=
, 2 },
-{ ARM::VLD2d32Pseudo_UPD,   ARM::VLD2d32_UPD,  true,  true,  SingleSpc,  2=
, 2 },
-{ ARM::VLD2d8Pseudo,        ARM::VLD2d8,       true,  false, SingleSpc,  2=
, 8 },
-{ ARM::VLD2d8Pseudo_UPD,    ARM::VLD2d8_UPD,   true,  true,  SingleSpc,  2=
, 8 },
+{ ARM::VLD3d16Pseudo,       ARM::VLD3d16,      true,  false, false, Single=
Spc,  3, 4 ,true},
+{ ARM::VLD3d16Pseudo_UPD,   ARM::VLD3d16_UPD, true, true, true,  SingleSpc=
,  3, 4 ,true},
+{ ARM::VLD3d32Pseudo,       ARM::VLD3d32,      true,  false, false, Single=
Spc,  3, 2 ,true},
+{ ARM::VLD3d32Pseudo_UPD,   ARM::VLD3d32_UPD, true, true, true,  SingleSpc=
,  3, 2 ,true},
+{ ARM::VLD3d8Pseudo,        ARM::VLD3d8,       true,  false, false, Single=
Spc,  3, 8 ,true},
+{ ARM::VLD3d8Pseudo_UPD,    ARM::VLD3d8_UPD, true, true, true,  SingleSpc,=
  3, 8 ,true},
=20
-{ ARM::VLD2q16Pseudo,       ARM::VLD2q16,      true,  false, SingleSpc,  4=
, 4 },
-{ ARM::VLD2q16Pseudo_UPD,   ARM::VLD2q16_UPD,  true,  true,  SingleSpc,  4=
, 4 },
-{ ARM::VLD2q32Pseudo,       ARM::VLD2q32,      true,  false, SingleSpc,  4=
, 2 },
-{ ARM::VLD2q32Pseudo_UPD,   ARM::VLD2q32_UPD,  true,  true,  SingleSpc,  4=
, 2 },
-{ ARM::VLD2q8Pseudo,        ARM::VLD2q8,       true,  false, SingleSpc,  4=
, 8 },
-{ ARM::VLD2q8Pseudo_UPD,    ARM::VLD2q8_UPD,   true,  true,  SingleSpc,  4=
, 8 },
+{ ARM::VLD3q16Pseudo_UPD,    ARM::VLD3q16_UPD, true, true, true,  EvenDblS=
pc, 3, 4 ,true},
+{ ARM::VLD3q16oddPseudo,     ARM::VLD3q16,     true,  false, false, OddDbl=
Spc,  3, 4 ,true},
+{ ARM::VLD3q16oddPseudo_UPD, ARM::VLD3q16_UPD, true, true, true,  OddDblSp=
c,  3, 4 ,true},
+{ ARM::VLD3q32Pseudo_UPD,    ARM::VLD3q32_UPD, true, true, true,  EvenDblS=
pc, 3, 2 ,true},
+{ ARM::VLD3q32oddPseudo,     ARM::VLD3q32,     true,  false, false, OddDbl=
Spc,  3, 2 ,true},
+{ ARM::VLD3q32oddPseudo_UPD, ARM::VLD3q32_UPD, true, true, true,  OddDblSp=
c,  3, 2 ,true},
+{ ARM::VLD3q8Pseudo_UPD,     ARM::VLD3q8_UPD, true, true, true,  EvenDblSp=
c, 3, 8 ,true},
+{ ARM::VLD3q8oddPseudo,      ARM::VLD3q8,      true,  false, false, OddDbl=
Spc,  3, 8 ,true},
+{ ARM::VLD3q8oddPseudo_UPD,  ARM::VLD3q8_UPD, true, true, true,  OddDblSpc=
,  3, 8 ,true},
=20
-{ ARM::VLD3DUPd16Pseudo,     ARM::VLD3DUPd16,     true, false, SingleSpc, =
3, 4},
-{ ARM::VLD3DUPd16Pseudo_UPD, ARM::VLD3DUPd16_UPD, true, true,  SingleSpc, =
3, 4},
-{ ARM::VLD3DUPd32Pseudo,     ARM::VLD3DUPd32,     true, false, SingleSpc, =
3, 2},
-{ ARM::VLD3DUPd32Pseudo_UPD, ARM::VLD3DUPd32_UPD, true, true,  SingleSpc, =
3, 2},
-{ ARM::VLD3DUPd8Pseudo,      ARM::VLD3DUPd8,      true, false, SingleSpc, =
3, 8},
-{ ARM::VLD3DUPd8Pseudo_UPD,  ARM::VLD3DUPd8_UPD,  true, true,  SingleSpc, =
3, 8},
+{ ARM::VLD4DUPd16Pseudo,     ARM::VLD4DUPd16,     true, false, false, Sing=
leSpc, 4, 4,true},
+{ ARM::VLD4DUPd16Pseudo_UPD, ARM::VLD4DUPd16_UPD, true, true, true,  Singl=
eSpc, 4, 4,true},
+{ ARM::VLD4DUPd32Pseudo,     ARM::VLD4DUPd32,     true, false, false, Sing=
leSpc, 4, 2,true},
+{ ARM::VLD4DUPd32Pseudo_UPD, ARM::VLD4DUPd32_UPD, true, true, true,  Singl=
eSpc, 4, 2,true},
+{ ARM::VLD4DUPd8Pseudo,      ARM::VLD4DUPd8,      true, false, false, Sing=
leSpc, 4, 8,true},
+{ ARM::VLD4DUPd8Pseudo_UPD,  ARM::VLD4DUPd8_UPD, true, true, true,  Single=
Spc, 4, 8,true},
=20
-{ ARM::VLD3LNd16Pseudo,     ARM::VLD3LNd16,     true, false, SingleSpc,  3=
, 4 },
-{ ARM::VLD3LNd16Pseudo_UPD, ARM::VLD3LNd16_UPD, true, true,  SingleSpc,  3=
, 4 },
-{ ARM::VLD3LNd32Pseudo,     ARM::VLD3LNd32,     true, false, SingleSpc,  3=
, 2 },
-{ ARM::VLD3LNd32Pseudo_UPD, ARM::VLD3LNd32_UPD, true, true,  SingleSpc,  3=
, 2 },
-{ ARM::VLD3LNd8Pseudo,      ARM::VLD3LNd8,      true, false, SingleSpc,  3=
, 8 },
-{ ARM::VLD3LNd8Pseudo_UPD,  ARM::VLD3LNd8_UPD,  true, true,  SingleSpc,  3=
, 8 },
-{ ARM::VLD3LNq16Pseudo,     ARM::VLD3LNq16,     true, false, EvenDblSpc, 3=
, 4 },
-{ ARM::VLD3LNq16Pseudo_UPD, ARM::VLD3LNq16_UPD, true, true,  EvenDblSpc, 3=
, 4 },
-{ ARM::VLD3LNq32Pseudo,     ARM::VLD3LNq32,     true, false, EvenDblSpc, 3=
, 2 },
-{ ARM::VLD3LNq32Pseudo_UPD, ARM::VLD3LNq32_UPD, true, true,  EvenDblSpc, 3=
, 2 },
+{ ARM::VLD4LNd16Pseudo,     ARM::VLD4LNd16,     true, false, false, Single=
Spc,  4, 4 ,true},
+{ ARM::VLD4LNd16Pseudo_UPD, ARM::VLD4LNd16_UPD, true, true, true,  SingleS=
pc,  4, 4 ,true},
+{ ARM::VLD4LNd32Pseudo,     ARM::VLD4LNd32,     true, false, false, Single=
Spc,  4, 2 ,true},
+{ ARM::VLD4LNd32Pseudo_UPD, ARM::VLD4LNd32_UPD, true, true, true,  SingleS=
pc,  4, 2 ,true},
+{ ARM::VLD4LNd8Pseudo,      ARM::VLD4LNd8,      true, false, false, Single=
Spc,  4, 8 ,true},
+{ ARM::VLD4LNd8Pseudo_UPD,  ARM::VLD4LNd8_UPD, true, true, true,  SingleSp=
c,  4, 8 ,true},
+{ ARM::VLD4LNq16Pseudo,     ARM::VLD4LNq16,     true, false, false, EvenDb=
lSpc, 4, 4 ,true},
+{ ARM::VLD4LNq16Pseudo_UPD, ARM::VLD4LNq16_UPD, true, true, true,  EvenDbl=
Spc, 4, 4 ,true},
+{ ARM::VLD4LNq32Pseudo,     ARM::VLD4LNq32,     true, false, false, EvenDb=
lSpc, 4, 2 ,true},
+{ ARM::VLD4LNq32Pseudo_UPD, ARM::VLD4LNq32_UPD, true, true, true,  EvenDbl=
Spc, 4, 2 ,true},
=20
-{ ARM::VLD3d16Pseudo,       ARM::VLD3d16,      true,  false, SingleSpc,  3=
, 4 },
-{ ARM::VLD3d16Pseudo_UPD,   ARM::VLD3d16_UPD,  true,  true,  SingleSpc,  3=
, 4 },
-{ ARM::VLD3d32Pseudo,       ARM::VLD3d32,      true,  false, SingleSpc,  3=
, 2 },
-{ ARM::VLD3d32Pseudo_UPD,   ARM::VLD3d32_UPD,  true,  true,  SingleSpc,  3=
, 2 },
-{ ARM::VLD3d8Pseudo,        ARM::VLD3d8,       true,  false, SingleSpc,  3=
, 8 },
-{ ARM::VLD3d8Pseudo_UPD,    ARM::VLD3d8_UPD,   true,  true,  SingleSpc,  3=
, 8 },
+{ ARM::VLD4d16Pseudo,       ARM::VLD4d16,      true,  false, false, Single=
Spc,  4, 4 ,true},
+{ ARM::VLD4d16Pseudo_UPD,   ARM::VLD4d16_UPD, true, true, true,  SingleSpc=
,  4, 4 ,true},
+{ ARM::VLD4d32Pseudo,       ARM::VLD4d32,      true,  false, false, Single=
Spc,  4, 2 ,true},
+{ ARM::VLD4d32Pseudo_UPD,   ARM::VLD4d32_UPD, true, true, true,  SingleSpc=
,  4, 2 ,true},
+{ ARM::VLD4d8Pseudo,        ARM::VLD4d8,       true,  false, false, Single=
Spc,  4, 8 ,true},
+{ ARM::VLD4d8Pseudo_UPD,    ARM::VLD4d8_UPD, true, true, true,  SingleSpc,=
  4, 8 ,true},
=20
-{ ARM::VLD3q16Pseudo_UPD,    ARM::VLD3q16_UPD, true,  true,  EvenDblSpc, 3=
, 4 },
-{ ARM::VLD3q16oddPseudo,     ARM::VLD3q16,     true,  false, OddDblSpc,  3=
, 4 },
-{ ARM::VLD3q16oddPseudo_UPD, ARM::VLD3q16_UPD, true,  true,  OddDblSpc,  3=
, 4 },
-{ ARM::VLD3q32Pseudo_UPD,    ARM::VLD3q32_UPD, true,  true,  EvenDblSpc, 3=
, 2 },
-{ ARM::VLD3q32oddPseudo,     ARM::VLD3q32,     true,  false, OddDblSpc,  3=
, 2 },
-{ ARM::VLD3q32oddPseudo_UPD, ARM::VLD3q32_UPD, true,  true,  OddDblSpc,  3=
, 2 },
-{ ARM::VLD3q8Pseudo_UPD,     ARM::VLD3q8_UPD,  true,  true,  EvenDblSpc, 3=
, 8 },
-{ ARM::VLD3q8oddPseudo,      ARM::VLD3q8,      true,  false, OddDblSpc,  3=
, 8 },
-{ ARM::VLD3q8oddPseudo_UPD,  ARM::VLD3q8_UPD,  true,  true,  OddDblSpc,  3=
, 8 },
+{ ARM::VLD4q16Pseudo_UPD,    ARM::VLD4q16_UPD, true, true, true,  EvenDblS=
pc, 4, 4 ,true},
+{ ARM::VLD4q16oddPseudo,     ARM::VLD4q16,     true,  false, false, OddDbl=
Spc,  4, 4 ,true},
+{ ARM::VLD4q16oddPseudo_UPD, ARM::VLD4q16_UPD, true, true, true,  OddDblSp=
c,  4, 4 ,true},
+{ ARM::VLD4q32Pseudo_UPD,    ARM::VLD4q32_UPD, true, true, true,  EvenDblS=
pc, 4, 2 ,true},
+{ ARM::VLD4q32oddPseudo,     ARM::VLD4q32,     true,  false, false, OddDbl=
Spc,  4, 2 ,true},
+{ ARM::VLD4q32oddPseudo_UPD, ARM::VLD4q32_UPD, true, true, true,  OddDblSp=
c,  4, 2 ,true},
+{ ARM::VLD4q8Pseudo_UPD,     ARM::VLD4q8_UPD, true, true, true,  EvenDblSp=
c, 4, 8 ,true},
+{ ARM::VLD4q8oddPseudo,      ARM::VLD4q8,      true,  false, false, OddDbl=
Spc,  4, 8 ,true},
+{ ARM::VLD4q8oddPseudo_UPD,  ARM::VLD4q8_UPD, true, true, true,  OddDblSpc=
,  4, 8 ,true},
=20
-{ ARM::VLD4DUPd16Pseudo,     ARM::VLD4DUPd16,     true, false, SingleSpc, =
4, 4},
-{ ARM::VLD4DUPd16Pseudo_UPD, ARM::VLD4DUPd16_UPD, true, true,  SingleSpc, =
4, 4},
-{ ARM::VLD4DUPd32Pseudo,     ARM::VLD4DUPd32,     true, false, SingleSpc, =
4, 2},
-{ ARM::VLD4DUPd32Pseudo_UPD, ARM::VLD4DUPd32_UPD, true, true,  SingleSpc, =
4, 2},
-{ ARM::VLD4DUPd8Pseudo,      ARM::VLD4DUPd8,      true, false, SingleSpc, =
4, 8},
-{ ARM::VLD4DUPd8Pseudo_UPD,  ARM::VLD4DUPd8_UPD,  true, true,  SingleSpc, =
4, 8},
+{ ARM::VST1LNq16Pseudo,     ARM::VST1LNd16,    false, false, false, EvenDb=
lSpc, 1, 4 ,true},
+{ ARM::VST1LNq16Pseudo_UPD, ARM::VST1LNd16_UPD, false, true, true,  EvenDb=
lSpc, 1, 4 ,true},
+{ ARM::VST1LNq32Pseudo,     ARM::VST1LNd32,    false, false, false, EvenDb=
lSpc, 1, 2 ,true},
+{ ARM::VST1LNq32Pseudo_UPD, ARM::VST1LNd32_UPD, false, true, true,  EvenDb=
lSpc, 1, 2 ,true},
+{ ARM::VST1LNq8Pseudo,      ARM::VST1LNd8,     false, false, false, EvenDb=
lSpc, 1, 8 ,true},
+{ ARM::VST1LNq8Pseudo_UPD,  ARM::VST1LNd8_UPD, false, true, true,  EvenDbl=
Spc, 1, 8 ,true},
=20
-{ ARM::VLD4LNd16Pseudo,     ARM::VLD4LNd16,     true, false, SingleSpc,  4=
, 4 },
-{ ARM::VLD4LNd16Pseudo_UPD, ARM::VLD4LNd16_UPD, true, true,  SingleSpc,  4=
, 4 },
-{ ARM::VLD4LNd32Pseudo,     ARM::VLD4LNd32,     true, false, SingleSpc,  4=
, 2 },
-{ ARM::VLD4LNd32Pseudo_UPD, ARM::VLD4LNd32_UPD, true, true,  SingleSpc,  4=
, 2 },
-{ ARM::VLD4LNd8Pseudo,      ARM::VLD4LNd8,      true, false, SingleSpc,  4=
, 8 },
-{ ARM::VLD4LNd8Pseudo_UPD,  ARM::VLD4LNd8_UPD,  true, true,  SingleSpc,  4=
, 8 },
-{ ARM::VLD4LNq16Pseudo,     ARM::VLD4LNq16,     true, false, EvenDblSpc, 4=
, 4 },
-{ ARM::VLD4LNq16Pseudo_UPD, ARM::VLD4LNq16_UPD, true, true,  EvenDblSpc, 4=
, 4 },
-{ ARM::VLD4LNq32Pseudo,     ARM::VLD4LNq32,     true, false, EvenDblSpc, 4=
, 2 },
-{ ARM::VLD4LNq32Pseudo_UPD, ARM::VLD4LNq32_UPD, true, true,  EvenDblSpc, 4=
, 2 },
+{ ARM::VST1d64QPseudo,      ARM::VST1d64Q,     false, false, false, Single=
Spc,  4, 1 ,false},
+{ ARM::VST1d64QPseudoWB_fixed,  ARM::VST1d64Qwb_fixed, false, true, false,=
  SingleSpc,  4, 1 ,false},
+{ ARM::VST1d64QPseudoWB_register, ARM::VST1d64Qwb_register, false, true, t=
rue,  SingleSpc,  4, 1 ,false},
+{ ARM::VST1d64TPseudo,      ARM::VST1d64T,     false, false, false, Single=
Spc,  3, 1 ,false},
+{ ARM::VST1d64TPseudoWB_fixed,  ARM::VST1d64Twb_fixed, false, true, false,=
  SingleSpc,  3, 1 ,false},
+{ ARM::VST1d64TPseudoWB_register,  ARM::VST1d64Twb_register, false, true, =
true,  SingleSpc,  3, 1 ,false},
=20
-{ ARM::VLD4d16Pseudo,       ARM::VLD4d16,      true,  false, SingleSpc,  4=
, 4 },
-{ ARM::VLD4d16Pseudo_UPD,   ARM::VLD4d16_UPD,  true,  true,  SingleSpc,  4=
, 4 },
-{ ARM::VLD4d32Pseudo,       ARM::VLD4d32,      true,  false, SingleSpc,  4=
, 2 },
-{ ARM::VLD4d32Pseudo_UPD,   ARM::VLD4d32_UPD,  true,  true,  SingleSpc,  4=
, 2 },
-{ ARM::VLD4d8Pseudo,        ARM::VLD4d8,       true,  false, SingleSpc,  4=
, 8 },
-{ ARM::VLD4d8Pseudo_UPD,    ARM::VLD4d8_UPD,   true,  true,  SingleSpc,  4=
, 8 },
+{ ARM::VST2LNd16Pseudo,     ARM::VST2LNd16,     false, false, false, Singl=
eSpc, 2, 4 ,true},
+{ ARM::VST2LNd16Pseudo_UPD, ARM::VST2LNd16_UPD, false, true, true,  Single=
Spc, 2, 4 ,true},
+{ ARM::VST2LNd32Pseudo,     ARM::VST2LNd32,     false, false, false, Singl=
eSpc, 2, 2 ,true},
+{ ARM::VST2LNd32Pseudo_UPD, ARM::VST2LNd32_UPD, false, true, true,  Single=
Spc, 2, 2 ,true},
+{ ARM::VST2LNd8Pseudo,      ARM::VST2LNd8,      false, false, false, Singl=
eSpc, 2, 8 ,true},
+{ ARM::VST2LNd8Pseudo_UPD,  ARM::VST2LNd8_UPD, false, true, true,  SingleS=
pc, 2, 8 ,true},
+{ ARM::VST2LNq16Pseudo,     ARM::VST2LNq16,     false, false, false, EvenD=
blSpc, 2, 4,true},
+{ ARM::VST2LNq16Pseudo_UPD, ARM::VST2LNq16_UPD, false, true, true,  EvenDb=
lSpc, 2, 4,true},
+{ ARM::VST2LNq32Pseudo,     ARM::VST2LNq32,     false, false, false, EvenD=
blSpc, 2, 2,true},
+{ ARM::VST2LNq32Pseudo_UPD, ARM::VST2LNq32_UPD, false, true, true,  EvenDb=
lSpc, 2, 2,true},
=20
-{ ARM::VLD4q16Pseudo_UPD,    ARM::VLD4q16_UPD, true,  true,  EvenDblSpc, 4=
, 4 },
-{ ARM::VLD4q16oddPseudo,     ARM::VLD4q16,     true,  false, OddDblSpc,  4=
, 4 },
-{ ARM::VLD4q16oddPseudo_UPD, ARM::VLD4q16_UPD, true,  true,  OddDblSpc,  4=
, 4 },
-{ ARM::VLD4q32Pseudo_UPD,    ARM::VLD4q32_UPD, true,  true,  EvenDblSpc, 4=
, 2 },
-{ ARM::VLD4q32oddPseudo,     ARM::VLD4q32,     true,  false, OddDblSpc,  4=
, 2 },
-{ ARM::VLD4q32oddPseudo_UPD, ARM::VLD4q32_UPD, true,  true,  OddDblSpc,  4=
, 2 },
-{ ARM::VLD4q8Pseudo_UPD,     ARM::VLD4q8_UPD,  true,  true,  EvenDblSpc, 4=
, 8 },
-{ ARM::VLD4q8oddPseudo,      ARM::VLD4q8,      true,  false, OddDblSpc,  4=
, 8 },
-{ ARM::VLD4q8oddPseudo_UPD,  ARM::VLD4q8_UPD,  true,  true,  OddDblSpc,  4=
, 8 },
+{ ARM::VST2q16Pseudo,       ARM::VST2q16,      false, false, false, Single=
Spc,  4, 4 ,false},
+{ ARM::VST2q16PseudoWB_fixed,   ARM::VST2q16wb_fixed, false, true, false, =
 SingleSpc,  4, 4 ,false},
+{ ARM::VST2q16PseudoWB_register,   ARM::VST2q16wb_register, false, true, t=
rue,  SingleSpc,  4, 4 ,false},
+{ ARM::VST2q32Pseudo,       ARM::VST2q32,      false, false, false, Single=
Spc,  4, 2 ,false},
+{ ARM::VST2q32PseudoWB_fixed,   ARM::VST2q32wb_fixed, false, true, false, =
 SingleSpc,  4, 2 ,false},
+{ ARM::VST2q32PseudoWB_register,   ARM::VST2q32wb_register, false, true, t=
rue,  SingleSpc,  4, 2 ,false},
+{ ARM::VST2q8Pseudo,        ARM::VST2q8,       false, false, false, Single=
Spc,  4, 8 ,false},
+{ ARM::VST2q8PseudoWB_fixed,    ARM::VST2q8wb_fixed, false, true, false,  =
SingleSpc,  4, 8 ,false},
+{ ARM::VST2q8PseudoWB_register,    ARM::VST2q8wb_register, false, true, tr=
ue,  SingleSpc,  4, 8 ,false},
=20
-{ ARM::VST1LNq16Pseudo,     ARM::VST1LNd16,    false, false, EvenDblSpc, 1=
, 4 },
-{ ARM::VST1LNq16Pseudo_UPD, ARM::VST1LNd16_UPD,false, true,  EvenDblSpc, 1=
, 4 },
-{ ARM::VST1LNq32Pseudo,     ARM::VST1LNd32,    false, false, EvenDblSpc, 1=
, 2 },
-{ ARM::VST1LNq32Pseudo_UPD, ARM::VST1LNd32_UPD,false, true,  EvenDblSpc, 1=
, 2 },
-{ ARM::VST1LNq8Pseudo,      ARM::VST1LNd8,     false, false, EvenDblSpc, 1=
, 8 },
-{ ARM::VST1LNq8Pseudo_UPD,  ARM::VST1LNd8_UPD, false, true,  EvenDblSpc, 1=
, 8 },
+{ ARM::VST3LNd16Pseudo,     ARM::VST3LNd16,     false, false, false, Singl=
eSpc, 3, 4 ,true},
+{ ARM::VST3LNd16Pseudo_UPD, ARM::VST3LNd16_UPD, false, true, true,  Single=
Spc, 3, 4 ,true},
+{ ARM::VST3LNd32Pseudo,     ARM::VST3LNd32,     false, false, false, Singl=
eSpc, 3, 2 ,true},
+{ ARM::VST3LNd32Pseudo_UPD, ARM::VST3LNd32_UPD, false, true, true,  Single=
Spc, 3, 2 ,true},
+{ ARM::VST3LNd8Pseudo,      ARM::VST3LNd8,      false, false, false, Singl=
eSpc, 3, 8 ,true},
+{ ARM::VST3LNd8Pseudo_UPD,  ARM::VST3LNd8_UPD, false, true, true,  SingleS=
pc, 3, 8 ,true},
+{ ARM::VST3LNq16Pseudo,     ARM::VST3LNq16,     false, false, false, EvenD=
blSpc, 3, 4,true},
+{ ARM::VST3LNq16Pseudo_UPD, ARM::VST3LNq16_UPD, false, true, true,  EvenDb=
lSpc, 3, 4,true},
+{ ARM::VST3LNq32Pseudo,     ARM::VST3LNq32,     false, false, false, EvenD=
blSpc, 3, 2,true},
+{ ARM::VST3LNq32Pseudo_UPD, ARM::VST3LNq32_UPD, false, true, true,  EvenDb=
lSpc, 3, 2,true},
=20
-{ ARM::VST1d64QPseudo,      ARM::VST1d64Q,     false, false, SingleSpc,  4=
, 1 },
-{ ARM::VST1d64QPseudo_UPD,  ARM::VST1d64Q_UPD, false, true,  SingleSpc,  4=
, 1 },
-{ ARM::VST1d64TPseudo,      ARM::VST1d64T,     false, false, SingleSpc,  3=
, 1 },
-{ ARM::VST1d64TPseudo_UPD,  ARM::VST1d64T_UPD, false, true,  SingleSpc,  3=
, 1 },
+{ ARM::VST3d16Pseudo,       ARM::VST3d16,      false, false, false, Single=
Spc,  3, 4 ,true},
+{ ARM::VST3d16Pseudo_UPD,   ARM::VST3d16_UPD, false, true, true,  SingleSp=
c,  3, 4 ,true},
+{ ARM::VST3d32Pseudo,       ARM::VST3d32,      false, false, false, Single=
Spc,  3, 2 ,true},
+{ ARM::VST3d32Pseudo_UPD,   ARM::VST3d32_UPD, false, true, true,  SingleSp=
c,  3, 2 ,true},
+{ ARM::VST3d8Pseudo,        ARM::VST3d8,       false, false, false, Single=
Spc,  3, 8 ,true},
+{ ARM::VST3d8Pseudo_UPD,    ARM::VST3d8_UPD, false, true, true,  SingleSpc=
,  3, 8 ,true},
=20
-{ ARM::VST1q16Pseudo,       ARM::VST1q16,      false, false, SingleSpc,  2=
, 4 },
-{ ARM::VST1q16Pseudo_UPD,   ARM::VST1q16_UPD,  false, true,  SingleSpc,  2=
, 4 },
-{ ARM::VST1q32Pseudo,       ARM::VST1q32,      false, false, SingleSpc,  2=
, 2 },
-{ ARM::VST1q32Pseudo_UPD,   ARM::VST1q32_UPD,  false, true,  SingleSpc,  2=
, 2 },
-{ ARM::VST1q64Pseudo,       ARM::VST1q64,      false, false, SingleSpc,  2=
, 1 },
-{ ARM::VST1q64Pseudo_UPD,   ARM::VST1q64_UPD,  false, true,  SingleSpc,  2=
, 1 },
-{ ARM::VST1q8Pseudo,        ARM::VST1q8,       false, false, SingleSpc,  2=
, 8 },
-{ ARM::VST1q8Pseudo_UPD,    ARM::VST1q8_UPD,   false, true,  SingleSpc,  2=
, 8 },
+{ ARM::VST3q16Pseudo_UPD,    ARM::VST3q16_UPD, false, true, true,  EvenDbl=
Spc, 3, 4 ,true},
+{ ARM::VST3q16oddPseudo,     ARM::VST3q16,     false, false, false, OddDbl=
Spc,  3, 4 ,true},
+{ ARM::VST3q16oddPseudo_UPD, ARM::VST3q16_UPD, false, true, true,  OddDblS=
pc,  3, 4 ,true},
+{ ARM::VST3q32Pseudo_UPD,    ARM::VST3q32_UPD, false, true, true,  EvenDbl=
Spc, 3, 2 ,true},
+{ ARM::VST3q32oddPseudo,     ARM::VST3q32,     false, false, false, OddDbl=
Spc,  3, 2 ,true},
+{ ARM::VST3q32oddPseudo_UPD, ARM::VST3q32_UPD, false, true, true,  OddDblS=
pc,  3, 2 ,true},
+{ ARM::VST3q8Pseudo_UPD,     ARM::VST3q8_UPD, false, true, true,  EvenDblS=
pc, 3, 8 ,true},
+{ ARM::VST3q8oddPseudo,      ARM::VST3q8,      false, false, false, OddDbl=
Spc,  3, 8 ,true},
+{ ARM::VST3q8oddPseudo_UPD,  ARM::VST3q8_UPD, false, true, true,  OddDblSp=
c,  3, 8 ,true},
=20
-{ ARM::VST2LNd16Pseudo,     ARM::VST2LNd16,     false, false, SingleSpc, 2=
, 4 },
-{ ARM::VST2LNd16Pseudo_UPD, ARM::VST2LNd16_UPD, false, true,  SingleSpc, 2=
, 4 },
-{ ARM::VST2LNd32Pseudo,     ARM::VST2LNd32,     false, false, SingleSpc, 2=
, 2 },
-{ ARM::VST2LNd32Pseudo_UPD, ARM::VST2LNd32_UPD, false, true,  SingleSpc, 2=
, 2 },
-{ ARM::VST2LNd8Pseudo,      ARM::VST2LNd8,      false, false, SingleSpc, 2=
, 8 },
-{ ARM::VST2LNd8Pseudo_UPD,  ARM::VST2LNd8_UPD,  false, true,  SingleSpc, 2=
, 8 },
-{ ARM::VST2LNq16Pseudo,     ARM::VST2LNq16,     false, false, EvenDblSpc, =
2, 4},
-{ ARM::VST2LNq16Pseudo_UPD, ARM::VST2LNq16_UPD, false, true,  EvenDblSpc, =
2, 4},
-{ ARM::VST2LNq32Pseudo,     ARM::VST2LNq32,     false, false, EvenDblSpc, =
2, 2},
-{ ARM::VST2LNq32Pseudo_UPD, ARM::VST2LNq32_UPD, false, true,  EvenDblSpc, =
2, 2},
+{ ARM::VST4LNd16Pseudo,     ARM::VST4LNd16,     false, false, false, Singl=
eSpc, 4, 4 ,true},
+{ ARM::VST4LNd16Pseudo_UPD, ARM::VST4LNd16_UPD, false, true, true,  Single=
Spc, 4, 4 ,true},
+{ ARM::VST4LNd32Pseudo,     ARM::VST4LNd32,     false, false, false, Singl=
eSpc, 4, 2 ,true},
+{ ARM::VST4LNd32Pseudo_UPD, ARM::VST4LNd32_UPD, false, true, true,  Single=
Spc, 4, 2 ,true},
+{ ARM::VST4LNd8Pseudo,      ARM::VST4LNd8,      false, false, false, Singl=
eSpc, 4, 8 ,true},
+{ ARM::VST4LNd8Pseudo_UPD,  ARM::VST4LNd8_UPD, false, true, true,  SingleS=
pc, 4, 8 ,true},
+{ ARM::VST4LNq16Pseudo,     ARM::VST4LNq16,     false, false, false, EvenD=
blSpc, 4, 4,true},
+{ ARM::VST4LNq16Pseudo_UPD, ARM::VST4LNq16_UPD, false, true, true,  EvenDb=
lSpc, 4, 4,true},
+{ ARM::VST4LNq32Pseudo,     ARM::VST4LNq32,     false, false, false, EvenD=
blSpc, 4, 2,true},
+{ ARM::VST4LNq32Pseudo_UPD, ARM::VST4LNq32_UPD, false, true, true,  EvenDb=
lSpc, 4, 2,true},
=20
-{ ARM::VST2d16Pseudo,       ARM::VST2d16,      false, false, SingleSpc,  2=
, 4 },
-{ ARM::VST2d16Pseudo_UPD,   ARM::VST2d16_UPD,  false, true,  SingleSpc,  2=
, 4 },
-{ ARM::VST2d32Pseudo,       ARM::VST2d32,      false, false, SingleSpc,  2=
, 2 },
-{ ARM::VST2d32Pseudo_UPD,   ARM::VST2d32_UPD,  false, true,  SingleSpc,  2=
, 2 },
-{ ARM::VST2d8Pseudo,        ARM::VST2d8,       false, false, SingleSpc,  2=
, 8 },
-{ ARM::VST2d8Pseudo_UPD,    ARM::VST2d8_UPD,   false, true,  SingleSpc,  2=
, 8 },
+{ ARM::VST4d16Pseudo,       ARM::VST4d16,      false, false, false, Single=
Spc,  4, 4 ,true},
+{ ARM::VST4d16Pseudo_UPD,   ARM::VST4d16_UPD, false, true, true,  SingleSp=
c,  4, 4 ,true},
+{ ARM::VST4d32Pseudo,       ARM::VST4d32,      false, false, false, Single=
Spc,  4, 2 ,true},
+{ ARM::VST4d32Pseudo_UPD,   ARM::VST4d32_UPD, false, true, true,  SingleSp=
c,  4, 2 ,true},
+{ ARM::VST4d8Pseudo,        ARM::VST4d8,       false, false, false, Single=
Spc,  4, 8 ,true},
+{ ARM::VST4d8Pseudo_UPD,    ARM::VST4d8_UPD, false, true, true,  SingleSpc=
,  4, 8 ,true},
=20
-{ ARM::VST2q16Pseudo,       ARM::VST2q16,      false, false, SingleSpc,  4=
, 4 },
-{ ARM::VST2q16Pseudo_UPD,   ARM::VST2q16_UPD,  false, true,  SingleSpc,  4=
, 4 },
-{ ARM::VST2q32Pseudo,       ARM::VST2q32,      false, false, SingleSpc,  4=
, 2 },
-{ ARM::VST2q32Pseudo_UPD,   ARM::VST2q32_UPD,  false, true,  SingleSpc,  4=
, 2 },
-{ ARM::VST2q8Pseudo,        ARM::VST2q8,       false, false, SingleSpc,  4=
, 8 },
-{ ARM::VST2q8Pseudo_UPD,    ARM::VST2q8_UPD,   false, true,  SingleSpc,  4=
, 8 },
-
-{ ARM::VST3LNd16Pseudo,     ARM::VST3LNd16,     false, false, SingleSpc, 3=
, 4 },
-{ ARM::VST3LNd16Pseudo_UPD, ARM::VST3LNd16_UPD, false, true,  SingleSpc, 3=
, 4 },
-{ ARM::VST3LNd32Pseudo,     ARM::VST3LNd32,     false, false, SingleSpc, 3=
, 2 },
-{ ARM::VST3LNd32Pseudo_UPD, ARM::VST3LNd32_UPD, false, true,  SingleSpc, 3=
, 2 },
-{ ARM::VST3LNd8Pseudo,      ARM::VST3LNd8,      false, false, SingleSpc, 3=
, 8 },
-{ ARM::VST3LNd8Pseudo_UPD,  ARM::VST3LNd8_UPD,  false, true,  SingleSpc, 3=
, 8 },
-{ ARM::VST3LNq16Pseudo,     ARM::VST3LNq16,     false, false, EvenDblSpc, =
3, 4},
-{ ARM::VST3LNq16Pseudo_UPD, ARM::VST3LNq16_UPD, false, true,  EvenDblSpc, =
3, 4},
-{ ARM::VST3LNq32Pseudo,     ARM::VST3LNq32,     false, false, EvenDblSpc, =
3, 2},
-{ ARM::VST3LNq32Pseudo_UPD, ARM::VST3LNq32_UPD, false, true,  EvenDblSpc, =
3, 2},
-
-{ ARM::VST3d16Pseudo,       ARM::VST3d16,      false, false, SingleSpc,  3=
, 4 },
-{ ARM::VST3d16Pseudo_UPD,   ARM::VST3d16_UPD,  false, true,  SingleSpc,  3=
, 4 },
-{ ARM::VST3d32Pseudo,       ARM::VST3d32,      false, false, SingleSpc,  3=
, 2 },
-{ ARM::VST3d32Pseudo_UPD,   ARM::VST3d32_UPD,  false, true,  SingleSpc,  3=
, 2 },
-{ ARM::VST3d8Pseudo,        ARM::VST3d8,       false, false, SingleSpc,  3=
, 8 },
-{ ARM::VST3d8Pseudo_UPD,    ARM::VST3d8_UPD,   false, true,  SingleSpc,  3=
, 8 },
-
-{ ARM::VST3q16Pseudo_UPD,    ARM::VST3q16_UPD, false, true,  EvenDblSpc, 3=
, 4 },
-{ ARM::VST3q16oddPseudo,     ARM::VST3q16,     false, false, OddDblSpc,  3=
, 4 },
-{ ARM::VST3q16oddPseudo_UPD, ARM::VST3q16_UPD, false, true,  OddDblSpc,  3=
, 4 },
-{ ARM::VST3q32Pseudo_UPD,    ARM::VST3q32_UPD, false, true,  EvenDblSpc, 3=
, 2 },
-{ ARM::VST3q32oddPseudo,     ARM::VST3q32,     false, false, OddDblSpc,  3=
, 2 },
-{ ARM::VST3q32oddPseudo_UPD, ARM::VST3q32_UPD, false, true,  OddDblSpc,  3=
, 2 },
-{ ARM::VST3q8Pseudo_UPD,     ARM::VST3q8_UPD,  false, true,  EvenDblSpc, 3=
, 8 },
-{ ARM::VST3q8oddPseudo,      ARM::VST3q8,      false, false, OddDblSpc,  3=
, 8 },
-{ ARM::VST3q8oddPseudo_UPD,  ARM::VST3q8_UPD,  false, true,  OddDblSpc,  3=
, 8 },
-
-{ ARM::VST4LNd16Pseudo,     ARM::VST4LNd16,     false, false, SingleSpc, 4=
, 4 },
-{ ARM::VST4LNd16Pseudo_UPD, ARM::VST4LNd16_UPD, false, true,  SingleSpc, 4=
, 4 },
-{ ARM::VST4LNd32Pseudo,     ARM::VST4LNd32,     false, false, SingleSpc, 4=
, 2 },
-{ ARM::VST4LNd32Pseudo_UPD, ARM::VST4LNd32_UPD, false, true,  SingleSpc, 4=
, 2 },
-{ ARM::VST4LNd8Pseudo,      ARM::VST4LNd8,      false, false, SingleSpc, 4=
, 8 },
-{ ARM::VST4LNd8Pseudo_UPD,  ARM::VST4LNd8_UPD,  false, true,  SingleSpc, 4=
, 8 },
-{ ARM::VST4LNq16Pseudo,     ARM::VST4LNq16,     false, false, EvenDblSpc, =
4, 4},
-{ ARM::VST4LNq16Pseudo_UPD, ARM::VST4LNq16_UPD, false, true,  EvenDblSpc, =
4, 4},
-{ ARM::VST4LNq32Pseudo,     ARM::VST4LNq32,     false, false, EvenDblSpc, =
4, 2},
-{ ARM::VST4LNq32Pseudo_UPD, ARM::VST4LNq32_UPD, false, true,  EvenDblSpc, =
4, 2},
-
-{ ARM::VST4d16Pseudo,       ARM::VST4d16,      false, false, SingleSpc,  4=
, 4 },
-{ ARM::VST4d16Pseudo_UPD,   ARM::VST4d16_UPD,  false, true,  SingleSpc,  4=
, 4 },
-{ ARM::VST4d32Pseudo,       ARM::VST4d32,      false, false, SingleSpc,  4=
, 2 },
-{ ARM::VST4d32Pseudo_UPD,   ARM::VST4d32_UPD,  false, true,  SingleSpc,  4=
, 2 },
-{ ARM::VST4d8Pseudo,        ARM::VST4d8,       false, false, SingleSpc,  4=
, 8 },
-{ ARM::VST4d8Pseudo_UPD,    ARM::VST4d8_UPD,   false, true,  SingleSpc,  4=
, 8 },
-
-{ ARM::VST4q16Pseudo_UPD,    ARM::VST4q16_UPD, false, true,  EvenDblSpc, 4=
, 4 },
-{ ARM::VST4q16oddPseudo,     ARM::VST4q16,     false, false, OddDblSpc,  4=
, 4 },
-{ ARM::VST4q16oddPseudo_UPD, ARM::VST4q16_UPD, false, true,  OddDblSpc,  4=
, 4 },
-{ ARM::VST4q32Pseudo_UPD,    ARM::VST4q32_UPD, false, true,  EvenDblSpc, 4=
, 2 },
-{ ARM::VST4q32oddPseudo,     ARM::VST4q32,     false, false, OddDblSpc,  4=
, 2 },
-{ ARM::VST4q32oddPseudo_UPD, ARM::VST4q32_UPD, false, true,  OddDblSpc,  4=
, 2 },
-{ ARM::VST4q8Pseudo_UPD,     ARM::VST4q8_UPD,  false, true,  EvenDblSpc, 4=
, 8 },
-{ ARM::VST4q8oddPseudo,      ARM::VST4q8,      false, false, OddDblSpc,  4=
, 8 },
-{ ARM::VST4q8oddPseudo_UPD,  ARM::VST4q8_UPD,  false, true,  OddDblSpc,  4=
, 8 }
+{ ARM::VST4q16Pseudo_UPD,    ARM::VST4q16_UPD, false, true, true,  EvenDbl=
Spc, 4, 4 ,true},
+{ ARM::VST4q16oddPseudo,     ARM::VST4q16,     false, false, false, OddDbl=
Spc,  4, 4 ,true},
+{ ARM::VST4q16oddPseudo_UPD, ARM::VST4q16_UPD, false, true, true,  OddDblS=
pc,  4, 4 ,true},
+{ ARM::VST4q32Pseudo_UPD,    ARM::VST4q32_UPD, false, true, true,  EvenDbl=
Spc, 4, 2 ,true},
+{ ARM::VST4q32oddPseudo,     ARM::VST4q32,     false, false, false, OddDbl=
Spc,  4, 2 ,true},
+{ ARM::VST4q32oddPseudo_UPD, ARM::VST4q32_UPD, false, true, true,  OddDblS=
pc,  4, 2 ,true},
+{ ARM::VST4q8Pseudo_UPD,     ARM::VST4q8_UPD, false, true, true,  EvenDblS=
pc, 4, 8 ,true},
+{ ARM::VST4q8oddPseudo,      ARM::VST4q8,      false, false, false, OddDbl=
Spc,  4, 8 ,true},
+{ ARM::VST4q8oddPseudo_UPD,  ARM::VST4q8_UPD, false, true, true,  OddDblSp=
c,  4, 8 ,true}
 };
=20
 /// LookupNEONLdSt - Search the NEONLdStTable for information about a NEON
 /// load or store pseudo instruction.
 static const NEONLdStTableEntry *LookupNEONLdSt(unsigned Opcode) {
-  unsigned NumEntries =3D array_lengthof(NEONLdStTable);
+  const unsigned NumEntries =3D array_lengthof(NEONLdStTable);
=20
 #ifndef NDEBUG
   // Make sure the table is sorted.
@@ -422,21 +388,22 @@
   unsigned DstReg =3D MI.getOperand(OpIdx++).getReg();
   unsigned D0, D1, D2, D3;
   GetDSubRegs(DstReg, RegSpc, TRI, D0, D1, D2, D3);
-  MIB.addReg(D0, RegState::Define | getDeadRegState(DstIsDead))
-    .addReg(D1, RegState::Define | getDeadRegState(DstIsDead));
-  if (NumRegs > 2)
+  MIB.addReg(D0, RegState::Define | getDeadRegState(DstIsDead));
+  if (NumRegs > 1 && TableEntry->copyAllListRegs)
+    MIB.addReg(D1, RegState::Define | getDeadRegState(DstIsDead));
+  if (NumRegs > 2 && TableEntry->copyAllListRegs)
     MIB.addReg(D2, RegState::Define | getDeadRegState(DstIsDead));
-  if (NumRegs > 3)
+  if (NumRegs > 3 && TableEntry->copyAllListRegs)
     MIB.addReg(D3, RegState::Define | getDeadRegState(DstIsDead));
=20
-  if (TableEntry->HasWriteBack)
+  if (TableEntry->isUpdating)
     MIB.addOperand(MI.getOperand(OpIdx++));
=20
   // Copy the addrmode6 operands.
   MIB.addOperand(MI.getOperand(OpIdx++));
   MIB.addOperand(MI.getOperand(OpIdx++));
   // Copy the am6offset operand.
-  if (TableEntry->HasWriteBack)
+  if (TableEntry->hasWritebackOperand)
     MIB.addOperand(MI.getOperand(OpIdx++));
=20
   // For an instruction writing double-spaced subregs, the pseudo instruct=
ion
@@ -481,24 +448,26 @@
   MachineInstrBuilder MIB =3D BuildMI(MBB, MBBI, MI.getDebugLoc(),
                                     TII->get(TableEntry->RealOpc));
   unsigned OpIdx =3D 0;
-  if (TableEntry->HasWriteBack)
+  if (TableEntry->isUpdating)
     MIB.addOperand(MI.getOperand(OpIdx++));
=20
   // Copy the addrmode6 operands.
   MIB.addOperand(MI.getOperand(OpIdx++));
   MIB.addOperand(MI.getOperand(OpIdx++));
   // Copy the am6offset operand.
-  if (TableEntry->HasWriteBack)
+  if (TableEntry->hasWritebackOperand)
     MIB.addOperand(MI.getOperand(OpIdx++));
=20
   bool SrcIsKill =3D MI.getOperand(OpIdx).isKill();
   unsigned SrcReg =3D MI.getOperand(OpIdx++).getReg();
   unsigned D0, D1, D2, D3;
   GetDSubRegs(SrcReg, RegSpc, TRI, D0, D1, D2, D3);
-  MIB.addReg(D0).addReg(D1);
-  if (NumRegs > 2)
+  MIB.addReg(D0);
+  if (NumRegs > 1 && TableEntry->copyAllListRegs)
+    MIB.addReg(D1);
+  if (NumRegs > 2 && TableEntry->copyAllListRegs)
     MIB.addReg(D2);
-  if (NumRegs > 3)
+  if (NumRegs > 3 && TableEntry->copyAllListRegs)
     MIB.addReg(D3);
=20
   // Copy the predicate operands.
@@ -558,14 +527,14 @@
       MIB.addReg(D3, RegState::Define | getDeadRegState(DstIsDead));
   }
=20
-  if (TableEntry->HasWriteBack)
+  if (TableEntry->isUpdating)
     MIB.addOperand(MI.getOperand(OpIdx++));
=20
   // Copy the addrmode6 operands.
   MIB.addOperand(MI.getOperand(OpIdx++));
   MIB.addOperand(MI.getOperand(OpIdx++));
   // Copy the am6offset operand.
-  if (TableEntry->HasWriteBack)
+  if (TableEntry->hasWritebackOperand)
     MIB.addOperand(MI.getOperand(OpIdx++));
=20
   // Grab the super-register source.
@@ -599,13 +568,15 @@
     // Add an implicit def for the super-register.
     MIB.addReg(DstReg, RegState::ImplicitDefine | getDeadRegState(DstIsDea=
d));
   TransferImpOps(MI, MIB, MIB);
+  // Transfer memoperands.
+  MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
   MI.eraseFromParent();
 }
=20
 /// ExpandVTBL - Translate VTBL and VTBX pseudo instructions with Q or QQ
 /// register operands to real instructions with D register operands.
 void ARMExpandPseudo::ExpandVTBL(MachineBasicBlock::iterator &MBBI,
-                                 unsigned Opc, bool IsExt, unsigned NumReg=
s) {
+                                 unsigned Opc, bool IsExt) {
   MachineInstr &MI =3D *MBBI;
   MachineBasicBlock &MBB =3D *MI.getParent();
=20
@@ -621,11 +592,7 @@
   unsigned SrcReg =3D MI.getOperand(OpIdx++).getReg();
   unsigned D0, D1, D2, D3;
   GetDSubRegs(SrcReg, SingleSpc, TRI, D0, D1, D2, D3);
-  MIB.addReg(D0).addReg(D1);
-  if (NumRegs > 2)
-    MIB.addReg(D2);
-  if (NumRegs > 3)
-    MIB.addReg(D3);
+  MIB.addReg(D0);
=20
   // Copy the other source register operand.
   MIB.addOperand(MI.getOperand(OpIdx++));
@@ -645,7 +612,7 @@
   MachineInstr &MI =3D *MBBI;
   unsigned Opcode =3D MI.getOpcode();
   unsigned PredReg =3D 0;
-  ARMCC::CondCodes Pred =3D llvm::getInstrPredicate(&MI, PredReg);
+  ARMCC::CondCodes Pred =3D getInstrPredicate(&MI, PredReg);
   unsigned DstReg =3D MI.getOperand(0).getReg();
   bool DstIsDead =3D MI.getOperand(0).isDead();
   bool isCC =3D Opcode =3D=3D ARM::MOVCCi32imm || Opcode =3D=3D ARM::t2MOV=
CCi32imm;
@@ -809,7 +776,9 @@
       MI.eraseFromParent();
       return true;
     }
-    case ARM::Int_eh_sjlj_dispatchsetup: {
+    case ARM::Int_eh_sjlj_dispatchsetup:
+    case ARM::Int_eh_sjlj_dispatchsetup_nofp:
+    case ARM::tInt_eh_sjlj_dispatchsetup: {
       MachineFunction &MF =3D *MI.getParent()->getParent();
       const ARMBaseInstrInfo *AII =3D
         static_cast<const ARMBaseInstrInfo*>(TII);
@@ -824,15 +793,15 @@
                "base pointer without frame pointer?");
=20
         if (AFI->isThumb2Function()) {
-          llvm::emitT2RegPlusImmediate(MBB, MBBI, MI.getDebugLoc(), ARM::R=
6,
-                                       FramePtr, -NumBytes, ARMCC::AL, 0, =
*TII);
+          emitT2RegPlusImmediate(MBB, MBBI, MI.getDebugLoc(), ARM::R6,
+                                 FramePtr, -NumBytes, ARMCC::AL, 0, *TII);
         } else if (AFI->isThumbFunction()) {
-          llvm::emitThumbRegPlusImmediate(MBB, MBBI, MI.getDebugLoc(), ARM=
::R6,
-                                          FramePtr, -NumBytes, *TII, RI);
+          emitThumbRegPlusImmediate(MBB, MBBI, MI.getDebugLoc(), ARM::R6,
+                                    FramePtr, -NumBytes, *TII, RI);
         } else {
-          llvm::emitARMRegPlusImmediate(MBB, MBBI, MI.getDebugLoc(), ARM::=
R6,
-                                        FramePtr, -NumBytes, ARMCC::AL, 0,
-                                        *TII);
+          emitARMRegPlusImmediate(MBB, MBBI, MI.getDebugLoc(), ARM::R6,
+                                  FramePtr, -NumBytes, ARMCC::AL, 0,
+                                  *TII);
         }
         // If there's dynamic realignment, adjust for it.
         if (RI.needsStackRealignment(MF)) {
@@ -996,6 +965,7 @@
       // Add an implicit def for the super-register.
       MIB.addReg(DstReg, RegState::ImplicitDefine | getDeadRegState(DstIsD=
ead));
       TransferImpOps(MI, MIB, MIB);
+      MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
       MI.eraseFromParent();
       return true;
     }
@@ -1026,6 +996,7 @@
         MIB->addRegisterKilled(SrcReg, TRI, true);
=20
       TransferImpOps(MI, MIB, MIB);
+      MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
       MI.eraseFromParent();
       return true;
     }
@@ -1057,26 +1028,15 @@
       return true;
     }
=20
-    case ARM::VLD1q8Pseudo:
-    case ARM::VLD1q16Pseudo:
-    case ARM::VLD1q32Pseudo:
-    case ARM::VLD1q64Pseudo:
-    case ARM::VLD1q8Pseudo_UPD:
-    case ARM::VLD1q16Pseudo_UPD:
-    case ARM::VLD1q32Pseudo_UPD:
-    case ARM::VLD1q64Pseudo_UPD:
-    case ARM::VLD2d8Pseudo:
-    case ARM::VLD2d16Pseudo:
-    case ARM::VLD2d32Pseudo:
     case ARM::VLD2q8Pseudo:
     case ARM::VLD2q16Pseudo:
     case ARM::VLD2q32Pseudo:
-    case ARM::VLD2d8Pseudo_UPD:
-    case ARM::VLD2d16Pseudo_UPD:
-    case ARM::VLD2d32Pseudo_UPD:
-    case ARM::VLD2q8Pseudo_UPD:
-    case ARM::VLD2q16Pseudo_UPD:
-    case ARM::VLD2q32Pseudo_UPD:
+    case ARM::VLD2q8PseudoWB_fixed:
+    case ARM::VLD2q16PseudoWB_fixed:
+    case ARM::VLD2q32PseudoWB_fixed:
+    case ARM::VLD2q8PseudoWB_register:
+    case ARM::VLD2q16PseudoWB_register:
+    case ARM::VLD2q32PseudoWB_register:
     case ARM::VLD3d8Pseudo:
     case ARM::VLD3d16Pseudo:
     case ARM::VLD3d32Pseudo:
@@ -1084,7 +1044,6 @@
     case ARM::VLD3d8Pseudo_UPD:
     case ARM::VLD3d16Pseudo_UPD:
     case ARM::VLD3d32Pseudo_UPD:
-    case ARM::VLD1d64TPseudo_UPD:
     case ARM::VLD3q8Pseudo_UPD:
     case ARM::VLD3q16Pseudo_UPD:
     case ARM::VLD3q32Pseudo_UPD:
@@ -1101,7 +1060,6 @@
     case ARM::VLD4d8Pseudo_UPD:
     case ARM::VLD4d16Pseudo_UPD:
     case ARM::VLD4d32Pseudo_UPD:
-    case ARM::VLD1d64QPseudo_UPD:
     case ARM::VLD4q8Pseudo_UPD:
     case ARM::VLD4q16Pseudo_UPD:
     case ARM::VLD4q32Pseudo_UPD:
@@ -1111,18 +1069,6 @@
     case ARM::VLD4q8oddPseudo_UPD:
     case ARM::VLD4q16oddPseudo_UPD:
     case ARM::VLD4q32oddPseudo_UPD:
-    case ARM::VLD1DUPq8Pseudo:
-    case ARM::VLD1DUPq16Pseudo:
-    case ARM::VLD1DUPq32Pseudo:
-    case ARM::VLD1DUPq8Pseudo_UPD:
-    case ARM::VLD1DUPq16Pseudo_UPD:
-    case ARM::VLD1DUPq32Pseudo_UPD:
-    case ARM::VLD2DUPd8Pseudo:
-    case ARM::VLD2DUPd16Pseudo:
-    case ARM::VLD2DUPd32Pseudo:
-    case ARM::VLD2DUPd8Pseudo_UPD:
-    case ARM::VLD2DUPd16Pseudo_UPD:
-    case ARM::VLD2DUPd32Pseudo_UPD:
     case ARM::VLD3DUPd8Pseudo:
     case ARM::VLD3DUPd16Pseudo:
     case ARM::VLD3DUPd32Pseudo:
@@ -1138,26 +1084,15 @@
       ExpandVLD(MBBI);
       return true;
=20
-    case ARM::VST1q8Pseudo:
-    case ARM::VST1q16Pseudo:
-    case ARM::VST1q32Pseudo:
-    case ARM::VST1q64Pseudo:
-    case ARM::VST1q8Pseudo_UPD:
-    case ARM::VST1q16Pseudo_UPD:
-    case ARM::VST1q32Pseudo_UPD:
-    case ARM::VST1q64Pseudo_UPD:
-    case ARM::VST2d8Pseudo:
-    case ARM::VST2d16Pseudo:
-    case ARM::VST2d32Pseudo:
     case ARM::VST2q8Pseudo:
     case ARM::VST2q16Pseudo:
     case ARM::VST2q32Pseudo:
-    case ARM::VST2d8Pseudo_UPD:
-    case ARM::VST2d16Pseudo_UPD:
-    case ARM::VST2d32Pseudo_UPD:
-    case ARM::VST2q8Pseudo_UPD:
-    case ARM::VST2q16Pseudo_UPD:
-    case ARM::VST2q32Pseudo_UPD:
+    case ARM::VST2q8PseudoWB_fixed:
+    case ARM::VST2q16PseudoWB_fixed:
+    case ARM::VST2q32PseudoWB_fixed:
+    case ARM::VST2q8PseudoWB_register:
+    case ARM::VST2q16PseudoWB_register:
+    case ARM::VST2q32PseudoWB_register:
     case ARM::VST3d8Pseudo:
     case ARM::VST3d16Pseudo:
     case ARM::VST3d32Pseudo:
@@ -1165,7 +1100,8 @@
     case ARM::VST3d8Pseudo_UPD:
     case ARM::VST3d16Pseudo_UPD:
     case ARM::VST3d32Pseudo_UPD:
-    case ARM::VST1d64TPseudo_UPD:
+    case ARM::VST1d64TPseudoWB_fixed:
+    case ARM::VST1d64TPseudoWB_register:
     case ARM::VST3q8Pseudo_UPD:
     case ARM::VST3q16Pseudo_UPD:
     case ARM::VST3q32Pseudo_UPD:
@@ -1182,7 +1118,8 @@
     case ARM::VST4d8Pseudo_UPD:
     case ARM::VST4d16Pseudo_UPD:
     case ARM::VST4d32Pseudo_UPD:
-    case ARM::VST1d64QPseudo_UPD:
+    case ARM::VST1d64QPseudoWB_fixed:
+    case ARM::VST1d64QPseudoWB_register:
     case ARM::VST4q8Pseudo_UPD:
     case ARM::VST4q16Pseudo_UPD:
     case ARM::VST4q32Pseudo_UPD:
@@ -1270,15 +1207,11 @@
       ExpandLaneOp(MBBI);
       return true;
=20
-    case ARM::VTBL2Pseudo: ExpandVTBL(MBBI, ARM::VTBL2, false, 2); return =
true;
-    case ARM::VTBL3Pseudo: ExpandVTBL(MBBI, ARM::VTBL3, false, 3); return =
true;
-    case ARM::VTBL4Pseudo: ExpandVTBL(MBBI, ARM::VTBL4, false, 4); return =
true;
-    case ARM::VTBX2Pseudo: ExpandVTBL(MBBI, ARM::VTBX2, true, 2); return t=
rue;
-    case ARM::VTBX3Pseudo: ExpandVTBL(MBBI, ARM::VTBX3, true, 3); return t=
rue;
-    case ARM::VTBX4Pseudo: ExpandVTBL(MBBI, ARM::VTBX4, true, 4); return t=
rue;
+    case ARM::VTBL3Pseudo: ExpandVTBL(MBBI, ARM::VTBL3, false); return tru=
e;
+    case ARM::VTBL4Pseudo: ExpandVTBL(MBBI, ARM::VTBL4, false); return tru=
e;
+    case ARM::VTBX3Pseudo: ExpandVTBL(MBBI, ARM::VTBX3, true); return true;
+    case ARM::VTBX4Pseudo: ExpandVTBL(MBBI, ARM::VTBX4, true); return true;
   }
-
-  return false;
 }
=20
 bool ARMExpandPseudo::ExpandMBB(MachineBasicBlock &MBB) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMFa=
stISel.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMFastISel.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMFastISel.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -16,7 +16,6 @@
 #include "ARM.h"
 #include "ARMBaseInstrInfo.h"
 #include "ARMCallingConv.h"
-#include "ARMRegisterInfo.h"
 #include "ARMTargetMachine.h"
 #include "ARMSubtarget.h"
 #include "ARMConstantPoolValue.h"
@@ -37,7 +36,6 @@
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Support/CallSite.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -90,7 +88,7 @@
   ARMFunctionInfo *AFI;
=20
   // Convenience variables to avoid some queries.
-  bool isThumb;
+  bool isThumb2;
   LLVMContext *Context;
=20
   public:
@@ -101,7 +99,7 @@
       TLI(*TM.getTargetLowering()) {
       Subtarget =3D &TM.getSubtarget<ARMSubtarget>();
       AFI =3D funcInfo.MF->getInfo<ARMFunctionInfo>();
-      isThumb =3D AFI->isThumbFunction();
+      isThumb2 =3D AFI->isThumbFunction();
       Context =3D &funcInfo.Fn->getContext();
     }
=20
@@ -148,6 +146,8 @@
     virtual bool TargetSelectInstruction(const Instruction *I);
     virtual unsigned TargetMaterializeConstant(const Constant *C);
     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
+    virtual bool TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
+                               const LoadInst *LI);
=20
   #include "ARMGenFastISel.inc"
=20
@@ -156,27 +156,40 @@
     bool SelectLoad(const Instruction *I);
     bool SelectStore(const Instruction *I);
     bool SelectBranch(const Instruction *I);
+    bool SelectIndirectBr(const Instruction *I);
     bool SelectCmp(const Instruction *I);
     bool SelectFPExt(const Instruction *I);
     bool SelectFPTrunc(const Instruction *I);
-    bool SelectBinaryOp(const Instruction *I, unsigned ISDOpcode);
-    bool SelectSIToFP(const Instruction *I);
-    bool SelectFPToSI(const Instruction *I);
-    bool SelectSDiv(const Instruction *I);
-    bool SelectSRem(const Instruction *I);
-    bool SelectCall(const Instruction *I);
+    bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
+    bool SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode);
+    bool SelectIToFP(const Instruction *I, bool isSigned);
+    bool SelectFPToI(const Instruction *I, bool isSigned);
+    bool SelectDiv(const Instruction *I, bool isSigned);
+    bool SelectRem(const Instruction *I, bool isSigned);
+    bool SelectCall(const Instruction *I, const char *IntrMemName);
+    bool SelectIntrinsicCall(const IntrinsicInst &I);
     bool SelectSelect(const Instruction *I);
     bool SelectRet(const Instruction *I);
-    bool SelectIntCast(const Instruction *I);
+    bool SelectTrunc(const Instruction *I);
+    bool SelectIntExt(const Instruction *I);
=20
     // Utility routines.
   private:
     bool isTypeLegal(Type *Ty, MVT &VT);
     bool isLoadTypeLegal(Type *Ty, MVT &VT);
-    bool ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr);
-    bool ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr);
+    bool ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
+                    bool isZExt);
+    bool ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr,
+                     unsigned Alignment =3D 0, bool isZExt =3D true,
+                     bool allocReg =3D true);
+                    =20
+    bool ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr,
+                      unsigned Alignment =3D 0);
     bool ARMComputeAddress(const Value *Obj, Address &Addr);
-    void ARMSimplifyAddress(Address &Addr, EVT VT);
+    void ARMSimplifyAddress(Address &Addr, EVT VT, bool useAM3);
+    bool ARMIsMemCpySmall(uint64_t Len);
+    bool ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len);
+    unsigned ARMEmitIntExt(EVT SrcVT, unsigned SrcReg, EVT DestVT, bool is=
ZExt);
     unsigned ARMMaterializeFP(const ConstantFP *CFP, EVT VT);
     unsigned ARMMaterializeInt(const Constant *C, EVT VT);
     unsigned ARMMaterializeGV(const GlobalValue *GV, EVT VT);
@@ -186,8 +199,6 @@
=20
     // Call handling routines.
   private:
-    bool FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT Sr=
cVT,
-                        unsigned &ResultReg);
     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool Return);
     bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
                          SmallVectorImpl<unsigned> &ArgRegs,
@@ -208,7 +219,7 @@
     const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &=
MIB);
     void AddLoadStoreOperands(EVT VT, Address &Addr,
                               const MachineInstrBuilder &MIB,
-                              unsigned Flags);
+                              unsigned Flags, bool useAM3);
 };
=20
 } // end anonymous namespace
@@ -219,8 +230,7 @@
 // we don't care about implicit defs here, just places we'll need to add a
 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.hasOptionalDef())
+  if (!MI->hasOptionalDef())
     return false;
=20
   // Look to see if our OptionalDef is defining CPSR or CCR.
@@ -290,10 +300,10 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                    .addReg(Op0, Op0IsKill * RegState::Kill));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                    .addReg(Op0, Op0IsKill * RegState::Kill));
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
@@ -310,11 +320,11 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addReg(Op1, Op1IsKill * RegState::Kill));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addReg(Op1, Op1IsKill * RegState::Kill));
@@ -333,12 +343,12 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addReg(Op1, Op1IsKill * RegState::Kill)
                    .addReg(Op2, Op2IsKill * RegState::Kill));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addReg(Op1, Op1IsKill * RegState::Kill)
@@ -357,11 +367,11 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addImm(Imm));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addImm(Imm));
@@ -379,11 +389,11 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addFPImm(FPImm));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addFPImm(FPImm));
@@ -402,12 +412,12 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addReg(Op1, Op1IsKill * RegState::Kill)
                    .addImm(Imm));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                    .addReg(Op0, Op0IsKill * RegState::Kill)
                    .addReg(Op1, Op1IsKill * RegState::Kill)
@@ -425,10 +435,10 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                    .addImm(Imm));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                    .addImm(Imm));
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
@@ -444,10 +454,10 @@
   unsigned ResultReg =3D createResultReg(RC);
   const MCInstrDesc &II =3D TII.get(MachineInstOpcode);
=20
-  if (II.getNumDefs() >=3D 1)
+  if (II.getNumDefs() >=3D 1) {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, Resu=
ltReg)
                     .addImm(Imm1).addImm(Imm2));
-  else {
+  } else {
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
                     .addImm(Imm1).addImm(Imm2));
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
@@ -464,9 +474,10 @@
   unsigned ResultReg =3D createResultReg(TLI.getRegClassFor(RetVT));
   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
          "Cannot yet extract from physregs");
+
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
-                         DL, TII.get(TargetOpcode::COPY), ResultReg)
-                 .addReg(Op0, getKillRegState(Op0IsKill), Idx));
+                          DL, TII.get(TargetOpcode::COPY), ResultReg)
+                  .addReg(Op0, getKillRegState(Op0IsKill), Idx));
   return ResultReg;
 }
=20
@@ -477,7 +488,7 @@
=20
   unsigned MoveReg =3D createResultReg(TLI.getRegClassFor(VT));
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                          TII.get(ARM::VMOVRS), MoveReg)
+                          TII.get(ARM::VMOVSR), MoveReg)
                   .addReg(SrcReg));
   return MoveReg;
 }
@@ -487,7 +498,7 @@
=20
   unsigned MoveReg =3D createResultReg(TLI.getRegClassFor(VT));
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                          TII.get(ARM::VMOVSR), MoveReg)
+                          TII.get(ARM::VMOVRS), MoveReg)
                   .addReg(SrcReg));
   return MoveReg;
 }
@@ -541,22 +552,42 @@
=20
 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, EVT VT) {
=20
-  // For now 32-bit only.
-  if (VT !=3D MVT::i32) return false;
-
-  unsigned DestReg =3D createResultReg(TLI.getRegClassFor(VT));
+  if (VT !=3D MVT::i32 && VT !=3D MVT::i16 && VT !=3D MVT::i8 && VT !=3D M=
VT::i1)
+    return false;
=20
   // If we can do this in a single instruction without a constant pool ent=
ry
   // do so now.
   const ConstantInt *CI =3D cast<ConstantInt>(C);
-  if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getSExtValue())) {
-    unsigned Opc =3D isThumb ? ARM::t2MOVi16 : ARM::MOVi16;
+  if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getZExtValue())) {
+    unsigned Opc =3D isThumb2 ? ARM::t2MOVi16 : ARM::MOVi16;
+    unsigned ImmReg =3D createResultReg(TLI.getRegClassFor(MVT::i32));
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                            TII.get(Opc), DestReg)
-                    .addImm(CI->getSExtValue()));
-    return DestReg;
+                            TII.get(Opc), ImmReg)
+                    .addImm(CI->getZExtValue()));
+    return ImmReg;
   }
=20
+  // Use MVN to emit negative constants.
+  if (VT =3D=3D MVT::i32 && Subtarget->hasV6T2Ops() && CI->isNegative()) {
+    unsigned Imm =3D (unsigned)~(CI->getSExtValue());
+    bool UseImm =3D isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) !=3D -1) :
+      (ARM_AM::getSOImmVal(Imm) !=3D -1);
+    if (UseImm) {
+      unsigned Opc =3D isThumb2 ? ARM::t2MVNi : ARM::MVNi;
+      unsigned ImmReg =3D createResultReg(TLI.getRegClassFor(MVT::i32));
+      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                              TII.get(Opc), ImmReg)
+                      .addImm(Imm));
+      return ImmReg;
+    }
+  }
+
+  // Load from constant pool.  For now 32-bit only.
+  if (VT !=3D MVT::i32)
+    return false;
+
+  unsigned DestReg =3D createResultReg(TLI.getRegClassFor(VT));
+
   // MachineConstantPool wants an explicit alignment.
   unsigned Align =3D TD.getPrefTypeAlignment(C->getType());
   if (Align =3D=3D 0) {
@@ -565,7 +596,7 @@
   }
   unsigned Idx =3D MCP.getConstantPoolIndex(C, Align);
=20
-  if (isThumb)
+  if (isThumb2)
     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                             TII.get(ARM::t2LDRpci), DestReg)
                     .addConstantPoolIndex(Idx));
@@ -586,44 +617,69 @@
   Reloc::Model RelocM =3D TM.getRelocationModel();
=20
   // TODO: Need more magic for ARM PIC.
-  if (!isThumb && (RelocM =3D=3D Reloc::PIC_)) return 0;
+  if (!isThumb2 && (RelocM =3D=3D Reloc::PIC_)) return 0;
=20
-  // MachineConstantPool wants an explicit alignment.
-  unsigned Align =3D TD.getPrefTypeAlignment(GV->getType());
-  if (Align =3D=3D 0) {
-    // TODO: Figure out if this is correct.
-    Align =3D TD.getTypeAllocSize(GV->getType());
+  unsigned DestReg =3D createResultReg(TLI.getRegClassFor(VT));
+
+  // Use movw+movt when possible, it avoids constant pool entries.
+  // Darwin targets don't support movt with Reloc::Static, see
+  // ARMTargetLowering::LowerGlobalAddressDarwin.  Other targets only supp=
ort
+  // static movt relocations.
+  if (Subtarget->useMovt() &&
+      Subtarget->isTargetDarwin() =3D=3D (RelocM !=3D Reloc::Static)) {
+    unsigned Opc;
+    switch (RelocM) {
+    case Reloc::PIC_:
+      Opc =3D isThumb2 ? ARM::t2MOV_ga_pcrel : ARM::MOV_ga_pcrel;
+      break;
+    case Reloc::DynamicNoPIC:
+      Opc =3D isThumb2 ? ARM::t2MOV_ga_dyn : ARM::MOV_ga_dyn;
+      break;
+    default:
+      Opc =3D isThumb2 ? ARM::t2MOVi32imm : ARM::MOVi32imm;
+      break;
+    }
+    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(=
Opc),
+                            DestReg).addGlobalAddress(GV));
+  } else {
+    // MachineConstantPool wants an explicit alignment.
+    unsigned Align =3D TD.getPrefTypeAlignment(GV->getType());
+    if (Align =3D=3D 0) {
+      // TODO: Figure out if this is correct.
+      Align =3D TD.getTypeAllocSize(GV->getType());
+    }
+
+    // Grab index.
+    unsigned PCAdj =3D (RelocM !=3D Reloc::PIC_) ? 0 :
+      (Subtarget->isThumb() ? 4 : 8);
+    unsigned Id =3D AFI->createPICLabelUId();
+    ARMConstantPoolValue *CPV =3D ARMConstantPoolConstant::Create(GV, Id,
+                                                                ARMCP::CPV=
alue,
+                                                                PCAdj);
+    unsigned Idx =3D MCP.getConstantPoolIndex(CPV, Align);
+
+    // Load value.
+    MachineInstrBuilder MIB;
+    if (isThumb2) {
+      unsigned Opc =3D (RelocM!=3DReloc::PIC_) ? ARM::t2LDRpci : ARM::t2LD=
Rpci_pic;
+      MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), =
DestReg)
+        .addConstantPoolIndex(Idx);
+      if (RelocM =3D=3D Reloc::PIC_)
+        MIB.addImm(Id);
+    } else {
+      // The extra immediate is for addrmode2.
+      MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::L=
DRcp),
+                    DestReg)
+        .addConstantPoolIndex(Idx)
+        .addImm(0);
+    }
+    AddOptionalDefs(MIB);
   }
=20
-  // Grab index.
-  unsigned PCAdj =3D (RelocM !=3D Reloc::PIC_) ? 0 : (Subtarget->isThumb()=
 ? 4 : 8);
-  unsigned Id =3D AFI->createPICLabelUId();
-  ARMConstantPoolValue *CPV =3D ARMConstantPoolConstant::Create(GV, Id,
-                                                              ARMCP::CPVal=
ue,
-                                                              PCAdj);
-  unsigned Idx =3D MCP.getConstantPoolIndex(CPV, Align);
-
-  // Load value.
-  MachineInstrBuilder MIB;
-  unsigned DestReg =3D createResultReg(TLI.getRegClassFor(VT));
-  if (isThumb) {
-    unsigned Opc =3D (RelocM !=3D Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LD=
Rpci_pic;
-    MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), De=
stReg)
-          .addConstantPoolIndex(Idx);
-    if (RelocM =3D=3D Reloc::PIC_)
-      MIB.addImm(Id);
-  } else {
-    // The extra immediate is for addrmode2.
-    MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDR=
cp),
-                  DestReg)
-          .addConstantPoolIndex(Idx)
-          .addImm(0);
-  }
-  AddOptionalDefs(MIB);
-
   if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) {
+    MachineInstrBuilder MIB;
     unsigned NewDestReg =3D createResultReg(TLI.getRegClassFor(VT));
-    if (isThumb)
+    if (isThumb2)
       MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                     TII.get(ARM::t2LDRi12), NewDestReg)
             .addReg(DestReg)
@@ -656,6 +712,8 @@
   return 0;
 }
=20
+// TODO: unsigned ARMFastISel::TargetMaterializeFloatZero(const ConstantFP=
 *CF);
+
 unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
   // Don't handle dynamic allocas.
   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
@@ -669,10 +727,10 @@
   // This will get lowered later into the correct offsets and registers
   // via rewriteXFrameIndex.
   if (SI !=3D FuncInfo.StaticAllocaMap.end()) {
-    TargetRegisterClass* RC =3D TLI.getRegClassFor(VT);
+    const TargetRegisterClass* RC =3D TLI.getRegClassFor(VT);
     unsigned ResultReg =3D createResultReg(RC);
-    unsigned Opc =3D isThumb ? ARM::t2ADDri : ARM::ADDri;
-    AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
+    unsigned Opc =3D isThumb2 ? ARM::t2ADDri : ARM::ADDri;
+    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                             TII.get(Opc), ResultReg)
                             .addFrameIndex(SI->second)
                             .addImm(0));
@@ -699,7 +757,7 @@
=20
   // If this is a type than can be sign or zero-extended to a basic operat=
ion
   // go ahead and accept it now.
-  if (VT =3D=3D MVT::i8 || VT =3D=3D MVT::i16)
+  if (VT =3D=3D MVT::i1 || VT =3D=3D MVT::i8 || VT =3D=3D MVT::i16)
     return true;
=20
   return false;
@@ -813,35 +871,33 @@
     }
   }
=20
-  // Materialize the global variable's address into a reg which can
-  // then be used later to load the variable.
-  if (const GlobalValue *GV =3D dyn_cast<GlobalValue>(Obj)) {
-    unsigned Tmp =3D ARMMaterializeGV(GV, TLI.getValueType(Obj->getType())=
);
-    if (Tmp =3D=3D 0) return false;
-
-    Addr.Base.Reg =3D Tmp;
-    return true;
-  }
-
   // Try to get this in a register if nothing else has worked.
   if (Addr.Base.Reg =3D=3D 0) Addr.Base.Reg =3D getRegForValue(Obj);
   return Addr.Base.Reg !=3D 0;
 }
=20
-void ARMFastISel::ARMSimplifyAddress(Address &Addr, EVT VT) {
+void ARMFastISel::ARMSimplifyAddress(Address &Addr, EVT VT, bool useAM3) {
=20
   assert(VT.isSimple() && "Non-simple types are invalid here!");
=20
   bool needsLowering =3D false;
   switch (VT.getSimpleVT().SimpleTy) {
-    default:
-      assert(false && "Unhandled load/store type!");
+    default: llvm_unreachable("Unhandled load/store type!");
     case MVT::i1:
     case MVT::i8:
     case MVT::i16:
     case MVT::i32:
-      // Integer loads/stores handle 12-bit offsets.
-      needsLowering =3D ((Addr.Offset & 0xfff) !=3D Addr.Offset);
+      if (!useAM3) {
+        // Integer loads/stores handle 12-bit offsets.
+        needsLowering =3D ((Addr.Offset & 0xfff) !=3D Addr.Offset);
+        // Handle negative offsets.
+        if (needsLowering && isThumb2)
+          needsLowering =3D !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
+                            Addr.Offset > -256);
+      } else {
+        // ARM halfword load/stores and signed byte loads use +/-imm8 offs=
ets.
+        needsLowering =3D (Addr.Offset > 255 || Addr.Offset < -255);
+      }
       break;
     case MVT::f32:
     case MVT::f64:
@@ -854,11 +910,11 @@
   // put the alloca address into a register, set the base type back to
   // register and continue. This should almost never happen.
   if (needsLowering && Addr.BaseType =3D=3D Address::FrameIndexBase) {
-    TargetRegisterClass *RC =3D isThumb ? ARM::tGPRRegisterClass :
-                              ARM::GPRRegisterClass;
+    const TargetRegisterClass *RC =3D isThumb2 ? ARM::tGPRRegisterClass
+                                             : ARM::GPRRegisterClass;
     unsigned ResultReg =3D createResultReg(RC);
-    unsigned Opc =3D isThumb ? ARM::t2ADDri : ARM::ADDri;
-    AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
+    unsigned Opc =3D isThumb2 ? ARM::t2ADDri : ARM::ADDri;
+    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                             TII.get(Opc), ResultReg)
                             .addFrameIndex(Addr.Base.FI)
                             .addImm(0));
@@ -877,7 +933,7 @@
=20
 void ARMFastISel::AddLoadStoreOperands(EVT VT, Address &Addr,
                                        const MachineInstrBuilder &MIB,
-                                       unsigned Flags) {
+                                       unsigned Flags, bool useAM3) {
   // addrmode5 output depends on the selection dag addressing dividing the
   // offset by 4 that it then later multiplies. Do this here as well.
   if (VT.getSimpleVT().SimpleTy =3D=3D MVT::f32 ||
@@ -897,60 +953,127 @@
     // Now add the rest of the operands.
     MIB.addFrameIndex(FI);
=20
-    // ARM halfword load/stores need an additional operand.
-    if (!isThumb && VT.getSimpleVT().SimpleTy =3D=3D MVT::i16) MIB.addReg(=
0);
-
-    MIB.addImm(Addr.Offset);
+    // ARM halfword load/stores and signed byte loads need an additional
+    // operand.
+    if (useAM3) {
+      signed Imm =3D (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Off=
set;
+      MIB.addReg(0);
+      MIB.addImm(Imm);
+    } else {
+      MIB.addImm(Addr.Offset);
+    }
     MIB.addMemOperand(MMO);
   } else {
     // Now add the rest of the operands.
     MIB.addReg(Addr.Base.Reg);
=20
-    // ARM halfword load/stores need an additional operand.
-    if (!isThumb && VT.getSimpleVT().SimpleTy =3D=3D MVT::i16) MIB.addReg(=
0);
-
-    MIB.addImm(Addr.Offset);
+    // ARM halfword load/stores and signed byte loads need an additional
+    // operand.
+    if (useAM3) {
+      signed Imm =3D (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Off=
set;
+      MIB.addReg(0);
+      MIB.addImm(Imm);
+    } else {
+      MIB.addImm(Addr.Offset);
+    }
   }
   AddOptionalDefs(MIB);
 }
=20
-bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr) {
-
+bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr,
+                              unsigned Alignment, bool isZExt, bool allocR=
eg) {
   assert(VT.isSimple() && "Non-simple types are invalid here!");
   unsigned Opc;
-  TargetRegisterClass *RC;
+  bool useAM3 =3D false;
+  bool needVMOV =3D false;
+  const TargetRegisterClass *RC;
   switch (VT.getSimpleVT().SimpleTy) {
     // This is mostly going to be Neon/vector support.
     default: return false;
-    case MVT::i16:
-      Opc =3D isThumb ? ARM::t2LDRHi12 : ARM::LDRH;
+    case MVT::i1:
+    case MVT::i8:
+      if (isThumb2) {
+        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops=
())
+          Opc =3D isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
+        else
+          Opc =3D isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
+      } else {
+        if (isZExt) {
+          Opc =3D ARM::LDRBi12;
+        } else {
+          Opc =3D ARM::LDRSB;
+          useAM3 =3D true;
+        }
+      }
       RC =3D ARM::GPRRegisterClass;
       break;
-    case MVT::i8:
-      Opc =3D isThumb ? ARM::t2LDRBi12 : ARM::LDRBi12;
+    case MVT::i16:
+      if (isThumb2) {
+        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops=
())
+          Opc =3D isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
+        else
+          Opc =3D isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
+      } else {
+        Opc =3D isZExt ? ARM::LDRH : ARM::LDRSH;
+        useAM3 =3D true;
+      }
       RC =3D ARM::GPRRegisterClass;
       break;
     case MVT::i32:
-      Opc =3D isThumb ? ARM::t2LDRi12 : ARM::LDRi12;
+      if (isThumb2) {
+        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops=
())
+          Opc =3D ARM::t2LDRi8;
+        else
+          Opc =3D ARM::t2LDRi12;
+      } else {
+        Opc =3D ARM::LDRi12;
+      }
       RC =3D ARM::GPRRegisterClass;
       break;
     case MVT::f32:
-      Opc =3D ARM::VLDRS;
-      RC =3D TLI.getRegClassFor(VT);
+      if (!Subtarget->hasVFP2()) return false;
+      // Unaligned loads need special handling. Floats require word-alignm=
ent.
+      if (Alignment && Alignment < 4) {
+        needVMOV =3D true;
+        VT =3D MVT::i32;
+        Opc =3D isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
+        RC =3D ARM::GPRRegisterClass;
+      } else {
+        Opc =3D ARM::VLDRS;
+        RC =3D TLI.getRegClassFor(VT);
+      }
       break;
     case MVT::f64:
+      if (!Subtarget->hasVFP2()) return false;
+      // FIXME: Unaligned loads need special handling.  Doublewords require
+      // word-alignment.
+      if (Alignment && Alignment < 4)
+        return false;
+
       Opc =3D ARM::VLDRD;
       RC =3D TLI.getRegClassFor(VT);
       break;
   }
   // Simplify this down to something we can handle.
-  ARMSimplifyAddress(Addr, VT);
+  ARMSimplifyAddress(Addr, VT, useAM3);
=20
   // Create the base instruction, then add the operands.
-  ResultReg =3D createResultReg(RC);
+  if (allocReg)
+    ResultReg =3D createResultReg(RC);
+  assert (ResultReg > 255 && "Expected an allocated virtual register.");
   MachineInstrBuilder MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                                     TII.get(Opc), ResultReg);
-  AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad);
+  AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
+
+  // If we had an unaligned load of a float we've converted it to an regul=
ar
+  // load.  Now we must move from the GRP to the FP register.
+  if (needVMOV) {
+    unsigned MoveReg =3D createResultReg(TLI.getRegClassFor(MVT::f32));
+    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                            TII.get(ARM::VMOVSR), MoveReg)
+                    .addReg(ResultReg));
+    ResultReg =3D MoveReg;
+  }
   return true;
 }
=20
@@ -969,51 +1092,92 @@
   if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
=20
   unsigned ResultReg;
-  if (!ARMEmitLoad(VT, ResultReg, Addr)) return false;
+  if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
+    return false;
   UpdateValueMap(I, ResultReg);
   return true;
 }
=20
-bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr) {
+bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr,
+                               unsigned Alignment) {
   unsigned StrOpc;
+  bool useAM3 =3D false;
   switch (VT.getSimpleVT().SimpleTy) {
     // This is mostly going to be Neon/vector support.
     default: return false;
     case MVT::i1: {
-      unsigned Res =3D createResultReg(isThumb ? ARM::tGPRRegisterClass :
+      unsigned Res =3D createResultReg(isThumb2 ? ARM::tGPRRegisterClass :
                                                ARM::GPRRegisterClass);
-      unsigned Opc =3D isThumb ? ARM::t2ANDri : ARM::ANDri;
+      unsigned Opc =3D isThumb2 ? ARM::t2ANDri : ARM::ANDri;
       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                               TII.get(Opc), Res)
                       .addReg(SrcReg).addImm(1));
       SrcReg =3D Res;
     } // Fallthrough here.
     case MVT::i8:
-      StrOpc =3D isThumb ? ARM::t2STRBi12 : ARM::STRBi12;
+      if (isThumb2) {
+        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops=
())
+          StrOpc =3D ARM::t2STRBi8;
+        else
+          StrOpc =3D ARM::t2STRBi12;
+      } else {
+        StrOpc =3D ARM::STRBi12;
+      }
       break;
     case MVT::i16:
-      StrOpc =3D isThumb ? ARM::t2STRHi12 : ARM::STRH;
+      if (isThumb2) {
+        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops=
())
+          StrOpc =3D ARM::t2STRHi8;
+        else
+          StrOpc =3D ARM::t2STRHi12;
+      } else {
+        StrOpc =3D ARM::STRH;
+        useAM3 =3D true;
+      }
       break;
     case MVT::i32:
-      StrOpc =3D isThumb ? ARM::t2STRi12 : ARM::STRi12;
+      if (isThumb2) {
+        if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops=
())
+          StrOpc =3D ARM::t2STRi8;
+        else
+          StrOpc =3D ARM::t2STRi12;
+      } else {
+        StrOpc =3D ARM::STRi12;
+      }
       break;
     case MVT::f32:
       if (!Subtarget->hasVFP2()) return false;
-      StrOpc =3D ARM::VSTRS;
+      // Unaligned stores need special handling. Floats require word-align=
ment.
+      if (Alignment && Alignment < 4) {
+        unsigned MoveReg =3D createResultReg(TLI.getRegClassFor(MVT::i32));
+        AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                                TII.get(ARM::VMOVRS), MoveReg)
+                        .addReg(SrcReg));
+        SrcReg =3D MoveReg;
+        VT =3D MVT::i32;
+        StrOpc =3D isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
+      } else {
+        StrOpc =3D ARM::VSTRS;
+      }
       break;
     case MVT::f64:
       if (!Subtarget->hasVFP2()) return false;
+      // FIXME: Unaligned stores need special handling.  Doublewords requi=
re
+      // word-alignment.
+      if (Alignment && Alignment < 4)
+          return false;
+
       StrOpc =3D ARM::VSTRD;
       break;
   }
   // Simplify this down to something we can handle.
-  ARMSimplifyAddress(Addr, VT);
+  ARMSimplifyAddress(Addr, VT, useAM3);
=20
   // Create the base instruction, then add the operands.
   MachineInstrBuilder MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                                     TII.get(StrOpc))
-                            .addReg(SrcReg, getKillRegState(true));
-  AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore);
+                            .addReg(SrcReg);
+  AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
   return true;
 }
=20
@@ -1039,7 +1203,8 @@
   if (!ARMComputeAddress(I->getOperand(1), Addr))
     return false;
=20
-  if (!ARMEmitStore(VT, SrcReg, Addr)) return false;
+  if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
+    return false;
   return true;
 }
=20
@@ -1099,30 +1264,8 @@
=20
   // If we can, avoid recomputing the compare - redoing it could lead to w=
onky
   // behavior.
-  // TODO: Factor this out.
   if (const CmpInst *CI =3D dyn_cast<CmpInst>(BI->getCondition())) {
-    MVT SourceVT;
-    Type *Ty =3D CI->getOperand(0)->getType();
-    if (CI->hasOneUse() && (CI->getParent() =3D=3D I->getParent())
-        && isTypeLegal(Ty, SourceVT)) {
-      bool isFloat =3D (Ty->isDoubleTy() || Ty->isFloatTy());
-      if (isFloat && !Subtarget->hasVFP2())
-        return false;
-
-      unsigned CmpOpc;
-      switch (SourceVT.SimpleTy) {
-        default: return false;
-        // TODO: Verify compares.
-        case MVT::f32:
-          CmpOpc =3D ARM::VCMPES;
-          break;
-        case MVT::f64:
-          CmpOpc =3D ARM::VCMPED;
-          break;
-        case MVT::i32:
-          CmpOpc =3D isThumb ? ARM::t2CMPrr : ARM::CMPrr;
-          break;
-      }
+    if (CI->hasOneUse() && (CI->getParent() =3D=3D I->getParent())) {
=20
       // Get the compare predicate.
       // Try to take advantage of fallthrough opportunities.
@@ -1137,23 +1280,11 @@
       // We may not handle every CC for now.
       if (ARMPred =3D=3D ARMCC::AL) return false;
=20
-      unsigned Arg1 =3D getRegForValue(CI->getOperand(0));
-      if (Arg1 =3D=3D 0) return false;
+      // Emit the compare.
+      if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned=
()))
+        return false;
=20
-      unsigned Arg2 =3D getRegForValue(CI->getOperand(1));
-      if (Arg2 =3D=3D 0) return false;
-
-      AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                              TII.get(CmpOpc))
-                      .addReg(Arg1).addReg(Arg2));
-
-      // For floating point we need to move the result to a comparison reg=
ister
-      // that we can then use for branches.
-      if (isFloat)
-        AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                                TII.get(ARM::FMSTAT)));
-
-      unsigned BrOpc =3D isThumb ? ARM::t2Bcc : ARM::Bcc;
+      unsigned BrOpc =3D isThumb2 ? ARM::t2Bcc : ARM::Bcc;
       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
       .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
       FastEmitBranch(FBB, DL);
@@ -1164,7 +1295,7 @@
     MVT SourceVT;
     if (TI->hasOneUse() && TI->getParent() =3D=3D I->getParent() &&
         (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
-      unsigned TstOpc =3D isThumb ? ARM::t2TSTri : ARM::TSTri;
+      unsigned TstOpc =3D isThumb2 ? ARM::t2TSTri : ARM::TSTri;
       unsigned OpReg =3D getRegForValue(TI->getOperand(0));
       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                               TII.get(TstOpc))
@@ -1176,7 +1307,7 @@
         CCMode =3D ARMCC::EQ;
       }
=20
-      unsigned BrOpc =3D isThumb ? ARM::t2Bcc : ARM::Bcc;
+      unsigned BrOpc =3D isThumb2 ? ARM::t2Bcc : ARM::Bcc;
       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
       .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
=20
@@ -1184,6 +1315,12 @@
       FuncInfo.MBB->addSuccessor(TBB);
       return true;
     }
+  } else if (const ConstantInt *CI =3D
+             dyn_cast<ConstantInt>(BI->getCondition())) {
+    uint64_t Imm =3D CI->getZExtValue();
+    MachineBasicBlock *Target =3D (Imm =3D=3D 0) ? FBB : TBB;
+    FastEmitBranch(Target, DL);
+    return true;
   }
=20
   unsigned CmpReg =3D getRegForValue(BI->getCondition());
@@ -1196,7 +1333,7 @@
   // Regardless, the compare has been done in the predecessor block,
   // and it left a value for us in a virtual register.  Ergo, we test
   // the one-bit value left in the virtual register.
-  unsigned TstOpc =3D isThumb ? ARM::t2TSTri : ARM::TSTri;
+  unsigned TstOpc =3D isThumb2 ? ARM::t2TSTri : ARM::TSTri;
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Ts=
tOpc))
                   .addReg(CmpReg).addImm(1));
=20
@@ -1206,7 +1343,7 @@
     CCMode =3D ARMCC::EQ;
   }
=20
-  unsigned BrOpc =3D isThumb ? ARM::t2Bcc : ARM::Bcc;
+  unsigned BrOpc =3D isThumb2 ? ARM::t2Bcc : ARM::Bcc;
   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
                   .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
   FastEmitBranch(FBB, DL);
@@ -1214,70 +1351,155 @@
   return true;
 }
=20
-bool ARMFastISel::SelectCmp(const Instruction *I) {
-  const CmpInst *CI =3D cast<CmpInst>(I);
+bool ARMFastISel::SelectIndirectBr(const Instruction *I) {
+  unsigned AddrReg =3D getRegForValue(I->getOperand(0));
+  if (AddrReg =3D=3D 0) return false;
=20
-  MVT VT;
-  Type *Ty =3D CI->getOperand(0)->getType();
-  if (!isTypeLegal(Ty, VT))
-    return false;
+  unsigned Opc =3D isThumb2 ? ARM::tBRIND : ARM::BX;
+  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Op=
c))
+                  .addReg(AddrReg));
+  return true; =20
+}
=20
-  bool isFloat =3D (Ty->isDoubleTy() || Ty->isFloatTy());
+bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Valu=
e,
+                             bool isZExt) {
+  Type *Ty =3D Src1Value->getType();
+  EVT SrcVT =3D TLI.getValueType(Ty, true);
+  if (!SrcVT.isSimple()) return false;
+
+  bool isFloat =3D (Ty->isFloatTy() || Ty->isDoubleTy());
   if (isFloat && !Subtarget->hasVFP2())
     return false;
=20
+  // Check to see if the 2nd operand is a constant that we can encode dire=
ctly
+  // in the compare.
+  int Imm =3D 0;
+  bool UseImm =3D false;
+  bool isNegativeImm =3D false;
+  // FIXME: At -O0 we don't have anything that canonicalizes operand order.
+  // Thus, Src1Value may be a ConstantInt, but we're missing it.
+  if (const ConstantInt *ConstInt =3D dyn_cast<ConstantInt>(Src2Value)) {
+    if (SrcVT =3D=3D MVT::i32 || SrcVT =3D=3D MVT::i16 || SrcVT =3D=3D MVT=
::i8 ||
+        SrcVT =3D=3D MVT::i1) {
+      const APInt &CIVal =3D ConstInt->getValue();
+      Imm =3D (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtVal=
ue();
+      // For INT_MIN/LONG_MIN (i.e., 0x80000000) we need to use a cmp, rat=
her
+      // then a cmn, because there is no way to represent 2147483648 as a=20
+      // signed 32-bit int.
+      if (Imm < 0 && Imm !=3D (int)0x80000000) {
+        isNegativeImm =3D true;
+        Imm =3D -Imm;
+      }
+      UseImm =3D isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) !=3D -1) :
+        (ARM_AM::getSOImmVal(Imm) !=3D -1);
+    }
+  } else if (const ConstantFP *ConstFP =3D dyn_cast<ConstantFP>(Src2Value)=
) {
+    if (SrcVT =3D=3D MVT::f32 || SrcVT =3D=3D MVT::f64)
+      if (ConstFP->isZero() && !ConstFP->isNegative())
+        UseImm =3D true;
+  }
+
   unsigned CmpOpc;
-  unsigned CondReg;
-  switch (VT.SimpleTy) {
+  bool isICmp =3D true;
+  bool needsExt =3D false;
+  switch (SrcVT.getSimpleVT().SimpleTy) {
     default: return false;
     // TODO: Verify compares.
     case MVT::f32:
-      CmpOpc =3D ARM::VCMPES;
-      CondReg =3D ARM::FPSCR;
+      isICmp =3D false;
+      CmpOpc =3D UseImm ? ARM::VCMPEZS : ARM::VCMPES;
       break;
     case MVT::f64:
-      CmpOpc =3D ARM::VCMPED;
-      CondReg =3D ARM::FPSCR;
+      isICmp =3D false;
+      CmpOpc =3D UseImm ? ARM::VCMPEZD : ARM::VCMPED;
       break;
+    case MVT::i1:
+    case MVT::i8:
+    case MVT::i16:
+      needsExt =3D true;
+    // Intentional fall-through.
     case MVT::i32:
-      CmpOpc =3D isThumb ? ARM::t2CMPrr : ARM::CMPrr;
-      CondReg =3D ARM::CPSR;
+      if (isThumb2) {
+        if (!UseImm)
+          CmpOpc =3D ARM::t2CMPrr;
+        else
+          CmpOpc =3D isNegativeImm ? ARM::t2CMNzri : ARM::t2CMPri;
+      } else {
+        if (!UseImm)
+          CmpOpc =3D ARM::CMPrr;
+        else
+          CmpOpc =3D isNegativeImm ? ARM::CMNzri : ARM::CMPri;
+      }
       break;
   }
=20
+  unsigned SrcReg1 =3D getRegForValue(Src1Value);
+  if (SrcReg1 =3D=3D 0) return false;
+
+  unsigned SrcReg2 =3D 0;
+  if (!UseImm) {
+    SrcReg2 =3D getRegForValue(Src2Value);
+    if (SrcReg2 =3D=3D 0) return false;
+  }
+
+  // We have i1, i8, or i16, we need to either zero extend or sign extend.
+  if (needsExt) {
+    SrcReg1 =3D ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
+    if (SrcReg1 =3D=3D 0) return false;
+    if (!UseImm) {
+      SrcReg2 =3D ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
+      if (SrcReg2 =3D=3D 0) return false;
+    }
+  }
+
+  if (!UseImm) {
+    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                            TII.get(CmpOpc))
+                    .addReg(SrcReg1).addReg(SrcReg2));
+  } else {
+    MachineInstrBuilder MIB;
+    MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
+      .addReg(SrcReg1);
+
+    // Only add immediate for icmp as the immediate for fcmp is an implici=
t 0.0.
+    if (isICmp)
+      MIB.addImm(Imm);
+    AddOptionalDefs(MIB);
+  }
+
+  // For floating point we need to move the result to a comparison register
+  // that we can then use for branches.
+  if (Ty->isFloatTy() || Ty->isDoubleTy())
+    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                            TII.get(ARM::FMSTAT)));
+  return true;
+}
+
+bool ARMFastISel::SelectCmp(const Instruction *I) {
+  const CmpInst *CI =3D cast<CmpInst>(I);
+
   // Get the compare predicate.
   ARMCC::CondCodes ARMPred =3D getComparePred(CI->getPredicate());
=20
   // We may not handle every CC for now.
   if (ARMPred =3D=3D ARMCC::AL) return false;
=20
-  unsigned Arg1 =3D getRegForValue(CI->getOperand(0));
-  if (Arg1 =3D=3D 0) return false;
-
-  unsigned Arg2 =3D getRegForValue(CI->getOperand(1));
-  if (Arg2 =3D=3D 0) return false;
-
-  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Cm=
pOpc))
-                  .addReg(Arg1).addReg(Arg2));
-
-  // For floating point we need to move the result to a comparison register
-  // that we can then use for branches.
-  if (isFloat)
-    AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                            TII.get(ARM::FMSTAT)));
+  // Emit the compare.
+  if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
+    return false;
=20
   // Now set a register based on the comparison. Explicitly set the predic=
ates
   // here.
-  unsigned MovCCOpc =3D isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
-  TargetRegisterClass *RC =3D isThumb ? ARM::rGPRRegisterClass
-                                    : ARM::GPRRegisterClass;
+  unsigned MovCCOpc =3D isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
+  const TargetRegisterClass *RC =3D isThumb2 ? ARM::rGPRRegisterClass
+                                           : ARM::GPRRegisterClass;
   unsigned DestReg =3D createResultReg(RC);
-  Constant *Zero
-    =3D ConstantInt::get(Type::getInt32Ty(*Context), 0);
+  Constant *Zero =3D ConstantInt::get(Type::getInt32Ty(*Context), 0);
   unsigned ZeroReg =3D TargetMaterializeConstant(Zero);
+  // ARMEmitCmp emits a FMSTAT when necessary, so it's always safe to use =
CPSR.
   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
           .addReg(ZeroReg).addImm(1)
-          .addImm(ARMPred).addReg(CondReg);
+          .addImm(ARMPred).addReg(ARM::CPSR);
=20
   UpdateValueMap(I, DestReg);
   return true;
@@ -1321,7 +1543,7 @@
   return true;
 }
=20
-bool ARMFastISel::SelectSIToFP(const Instruction *I) {
+bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
   // Make sure we have VFP.
   if (!Subtarget->hasVFP2()) return false;
=20
@@ -1330,21 +1552,30 @@
   if (!isTypeLegal(Ty, DstVT))
     return false;
=20
-  // FIXME: Handle sign-extension where necessary.
-  if (!I->getOperand(0)->getType()->isIntegerTy(32))
+  Value *Src =3D I->getOperand(0);
+  EVT SrcVT =3D TLI.getValueType(Src->getType(), true);
+  if (SrcVT !=3D MVT::i32 && SrcVT !=3D MVT::i16 && SrcVT !=3D MVT::i8)
     return false;
=20
-  unsigned Op =3D getRegForValue(I->getOperand(0));
-  if (Op =3D=3D 0) return false;
+  unsigned SrcReg =3D getRegForValue(Src);
+  if (SrcReg =3D=3D 0) return false;
+
+  // Handle sign-extension.
+  if (SrcVT =3D=3D MVT::i16 || SrcVT =3D=3D MVT::i8) {
+    EVT DestVT =3D MVT::i32;
+    SrcReg =3D ARMEmitIntExt(SrcVT, SrcReg, DestVT,
+                                       /*isZExt*/!isSigned);
+    if (SrcReg =3D=3D 0) return false;
+  }
=20
   // The conversion routine works on fp-reg to fp-reg and the operand above
   // was an integer, move it to the fp registers if possible.
-  unsigned FP =3D ARMMoveToFPReg(MVT::f32, Op);
+  unsigned FP =3D ARMMoveToFPReg(MVT::f32, SrcReg);
   if (FP =3D=3D 0) return false;
=20
   unsigned Opc;
-  if (Ty->isFloatTy()) Opc =3D ARM::VSITOS;
-  else if (Ty->isDoubleTy()) Opc =3D ARM::VSITOD;
+  if (Ty->isFloatTy()) Opc =3D isSigned ? ARM::VSITOS : ARM::VUITOS;
+  else if (Ty->isDoubleTy()) Opc =3D isSigned ? ARM::VSITOD : ARM::VUITOD;
   else return false;
=20
   unsigned ResultReg =3D createResultReg(TLI.getRegClassFor(DstVT));
@@ -1355,7 +1586,7 @@
   return true;
 }
=20
-bool ARMFastISel::SelectFPToSI(const Instruction *I) {
+bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
   // Make sure we have VFP.
   if (!Subtarget->hasVFP2()) return false;
=20
@@ -1369,11 +1600,11 @@
=20
   unsigned Opc;
   Type *OpTy =3D I->getOperand(0)->getType();
-  if (OpTy->isFloatTy()) Opc =3D ARM::VTOSIZS;
-  else if (OpTy->isDoubleTy()) Opc =3D ARM::VTOSIZD;
+  if (OpTy->isFloatTy()) Opc =3D isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
+  else if (OpTy->isDoubleTy()) Opc =3D isSigned ? ARM::VTOSIZD : ARM::VTOU=
IZD;
   else return false;
=20
-  // f64->s32 or f32->s32 both need an intermediate f32 reg.
+  // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
   unsigned ResultReg =3D createResultReg(TLI.getRegClassFor(MVT::f32));
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Op=
c),
                           ResultReg)
@@ -1401,22 +1632,54 @@
   if (CondReg =3D=3D 0) return false;
   unsigned Op1Reg =3D getRegForValue(I->getOperand(1));
   if (Op1Reg =3D=3D 0) return false;
-  unsigned Op2Reg =3D getRegForValue(I->getOperand(2));
-  if (Op2Reg =3D=3D 0) return false;
=20
-  unsigned CmpOpc =3D isThumb ? ARM::t2TSTri : ARM::TSTri;
+  // Check to see if we can use an immediate in the conditional move.
+  int Imm =3D 0;
+  bool UseImm =3D false;
+  bool isNegativeImm =3D false;
+  if (const ConstantInt *ConstInt =3D dyn_cast<ConstantInt>(I->getOperand(=
2))) {
+    assert (VT =3D=3D MVT::i32 && "Expecting an i32.");
+    Imm =3D (int)ConstInt->getValue().getZExtValue();
+    if (Imm < 0) {
+      isNegativeImm =3D true;
+      Imm =3D ~Imm;
+    }
+    UseImm =3D isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) !=3D -1) :
+      (ARM_AM::getSOImmVal(Imm) !=3D -1);
+  }
+
+  unsigned Op2Reg =3D 0;
+  if (!UseImm) {
+    Op2Reg =3D getRegForValue(I->getOperand(2));
+    if (Op2Reg =3D=3D 0) return false;
+  }
+
+  unsigned CmpOpc =3D isThumb2 ? ARM::t2CMPri : ARM::CMPri;
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Cm=
pOpc))
-                  .addReg(CondReg).addImm(1));
+                  .addReg(CondReg).addImm(0));
+
+  unsigned MovCCOpc;
+  if (!UseImm) {
+    MovCCOpc =3D isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
+  } else {
+    if (!isNegativeImm) {
+      MovCCOpc =3D isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
+    } else {
+      MovCCOpc =3D isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
+    }
+  }
   unsigned ResultReg =3D createResultReg(RC);
-  unsigned MovCCOpc =3D isThumb ? ARM::t2MOVCCr : ARM::MOVCCr;
-  BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultR=
eg)
-    .addReg(Op1Reg).addReg(Op2Reg)
-    .addImm(ARMCC::EQ).addReg(ARM::CPSR);
+  if (!UseImm)
+    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), Resul=
tReg)
+    .addReg(Op2Reg).addReg(Op1Reg).addImm(ARMCC::NE).addReg(ARM::CPSR);
+  else
+    BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), Resul=
tReg)
+    .addReg(Op1Reg).addImm(Imm).addImm(ARMCC::EQ).addReg(ARM::CPSR);
   UpdateValueMap(I, ResultReg);
   return true;
 }
=20
-bool ARMFastISel::SelectSDiv(const Instruction *I) {
+bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
   MVT VT;
   Type *Ty =3D I->getType();
   if (!isTypeLegal(Ty, VT))
@@ -1430,21 +1693,21 @@
   // Otherwise emit a libcall.
   RTLIB::Libcall LC =3D RTLIB::UNKNOWN_LIBCALL;
   if (VT =3D=3D MVT::i8)
-    LC =3D RTLIB::SDIV_I8;
+    LC =3D isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
   else if (VT =3D=3D MVT::i16)
-    LC =3D RTLIB::SDIV_I16;
+    LC =3D isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
   else if (VT =3D=3D MVT::i32)
-    LC =3D RTLIB::SDIV_I32;
+    LC =3D isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
   else if (VT =3D=3D MVT::i64)
-    LC =3D RTLIB::SDIV_I64;
+    LC =3D isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
   else if (VT =3D=3D MVT::i128)
-    LC =3D RTLIB::SDIV_I128;
+    LC =3D isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
   assert(LC !=3D RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
=20
   return ARMEmitLibcall(I, LC);
 }
=20
-bool ARMFastISel::SelectSRem(const Instruction *I) {
+bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
   MVT VT;
   Type *Ty =3D I->getType();
   if (!isTypeLegal(Ty, VT))
@@ -1452,21 +1715,59 @@
=20
   RTLIB::Libcall LC =3D RTLIB::UNKNOWN_LIBCALL;
   if (VT =3D=3D MVT::i8)
-    LC =3D RTLIB::SREM_I8;
+    LC =3D isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
   else if (VT =3D=3D MVT::i16)
-    LC =3D RTLIB::SREM_I16;
+    LC =3D isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
   else if (VT =3D=3D MVT::i32)
-    LC =3D RTLIB::SREM_I32;
+    LC =3D isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
   else if (VT =3D=3D MVT::i64)
-    LC =3D RTLIB::SREM_I64;
+    LC =3D isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
   else if (VT =3D=3D MVT::i128)
-    LC =3D RTLIB::SREM_I128;
+    LC =3D isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
   assert(LC !=3D RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
=20
   return ARMEmitLibcall(I, LC);
 }
=20
-bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode)=
 {
+bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpco=
de) {
+  EVT DestVT  =3D TLI.getValueType(I->getType(), true);
+
+  // We can get here in the case when we have a binary operation on a non-=
legal
+  // type and the target independent selector doesn't know how to handle i=
t.
+  if (DestVT !=3D MVT::i16 && DestVT !=3D MVT::i8 && DestVT !=3D MVT::i1)
+    return false;
+ =20
+  unsigned Opc;
+  switch (ISDOpcode) {
+    default: return false;
+    case ISD::ADD:
+      Opc =3D isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
+      break;
+    case ISD::OR:
+      Opc =3D isThumb2 ? ARM::t2ORRrr : ARM::ORRrr;
+      break;
+    case ISD::SUB:
+      Opc =3D isThumb2 ? ARM::t2SUBrr : ARM::SUBrr;
+      break;
+  }
+
+  unsigned SrcReg1 =3D getRegForValue(I->getOperand(0));
+  if (SrcReg1 =3D=3D 0) return false;
+
+  // TODO: Often the 2nd operand is an immediate, which can be encoded dir=
ectly
+  // in the instruction, rather then materializing the value in a register.
+  unsigned SrcReg2 =3D getRegForValue(I->getOperand(1));
+  if (SrcReg2 =3D=3D 0) return false;
+
+  unsigned ResultReg =3D createResultReg(TLI.getRegClassFor(MVT::i32));
+  AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                          TII.get(Opc), ResultReg)
+                  .addReg(SrcReg1).addReg(SrcReg2));
+  UpdateValueMap(I, ResultReg);
+  return true;
+}
+
+bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcod=
e) {
   EVT VT  =3D TLI.getValueType(I->getType(), true);
=20
   // We can get here in the case when we want to use NEON for our fp
@@ -1478,12 +1779,6 @@
   if (isFloat && !Subtarget->hasVFP2())
     return false;
=20
-  unsigned Op1 =3D getRegForValue(I->getOperand(0));
-  if (Op1 =3D=3D 0) return false;
-
-  unsigned Op2 =3D getRegForValue(I->getOperand(1));
-  if (Op2 =3D=3D 0) return false;
-
   unsigned Opc;
   bool is64bit =3D VT =3D=3D MVT::f64 || VT =3D=3D MVT::i64;
   switch (ISDOpcode) {
@@ -1498,6 +1793,12 @@
       Opc =3D is64bit ? ARM::VMULD : ARM::VMULS;
       break;
   }
+  unsigned Op1 =3D getRegForValue(I->getOperand(0));
+  if (Op1 =3D=3D 0) return false;
+
+  unsigned Op2 =3D getRegForValue(I->getOperand(1));
+  if (Op2 =3D=3D 0) return false;
+
   unsigned ResultReg =3D createResultReg(TLI.getRegClassFor(VT));
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                           TII.get(Opc), ResultReg)
@@ -1508,18 +1809,6 @@
=20
 // Call Handling Code
=20
-bool ARMFastISel::FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Sr=
c,
-                                 EVT SrcVT, unsigned &ResultReg) {
-  unsigned RR =3D FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
-                           Src, /*TODO: Kill=3D*/false);
-
-  if (RR !=3D 0) {
-    ResultReg =3D RR;
-    return true;
-  } else
-    return false;
-}
-
 // This is largely taken directly from CCAssignFnForNode - we don't support
 // varargs in FastISel so that part has been removed.
 // TODO: We may not support all of this.
@@ -1536,7 +1825,7 @@
     // Use target triple & subtarget features to do actual dispatch.
     if (Subtarget->isAAPCS_ABI()) {
       if (Subtarget->hasVFP2() &&
-          FloatABIType =3D=3D FloatABI::Hard)
+          TM.Options.FloatABIType =3D=3D FloatABI::Hard)
         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
       else
         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
@@ -1548,11 +1837,6 @@
     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
   case CallingConv::ARM_APCS:
     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
-  case CallingConv::GHC:
-    if (Return)
-      llvm_unreachable("Can't return in GHC call convention");
-    else
-      return CC_ARM_APCS_GHC;
   }
 }
=20
@@ -1567,6 +1851,48 @@
   CCState CCInfo(CC, false, *FuncInfo.MF, TM, ArgLocs, *Context);
   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false=
));
=20
+  // Check that we can handle all of the arguments. If we can't, then bail=
 out
+  // now before we add code to the MBB.
+  for (unsigned i =3D 0, e =3D ArgLocs.size(); i !=3D e; ++i) {
+    CCValAssign &VA =3D ArgLocs[i];
+    MVT ArgVT =3D ArgVTs[VA.getValNo()];
+
+    // We don't handle NEON/vector parameters yet.
+    if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
+      return false;
+
+    // Now copy/store arg to correct locations.
+    if (VA.isRegLoc() && !VA.needsCustom()) {
+      continue;
+    } else if (VA.needsCustom()) {
+      // TODO: We need custom lowering for vector (v2f64) args.
+      if (VA.getLocVT() !=3D MVT::f64 ||
+          // TODO: Only handle register args for now.
+          !VA.isRegLoc() || !ArgLocs[++i].isRegLoc())
+        return false;
+    } else {
+      switch (static_cast<EVT>(ArgVT).getSimpleVT().SimpleTy) {
+      default:
+        return false;
+      case MVT::i1:
+      case MVT::i8:
+      case MVT::i16:
+      case MVT::i32:
+        break;
+      case MVT::f32:
+        if (!Subtarget->hasVFP2())
+          return false;
+        break;
+      case MVT::f64:
+        if (!Subtarget->hasVFP2())
+          return false;
+        break;
+      }
+    }
+  }
+
+  // At the point, we are able to handle the call's arguments in fast isel.
+
   // Get a count of how many bytes are to be pushed on the stack.
   NumBytes =3D CCInfo.getNextStackOffset();
=20
@@ -1582,41 +1908,26 @@
     unsigned Arg =3D ArgRegs[VA.getValNo()];
     MVT ArgVT =3D ArgVTs[VA.getValNo()];
=20
-    // We don't handle NEON/vector parameters yet.
-    if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
-      return false;
+    assert((!ArgVT.isVector() && ArgVT.getSizeInBits() <=3D 64) &&
+           "We don't handle NEON/vector parameters yet.");
=20
     // Handle arg promotion, etc.
     switch (VA.getLocInfo()) {
       case CCValAssign::Full: break;
       case CCValAssign::SExt: {
-        bool Emitted =3D FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
-                                         Arg, ArgVT, Arg);
-        assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
-        Emitted =3D true;
-        ArgVT =3D VA.getLocVT();
+        MVT DestVT =3D VA.getLocVT();
+        Arg =3D ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/false);
+        assert (Arg !=3D 0 && "Failed to emit a sext");
+        ArgVT =3D DestVT;
         break;
       }
+      case CCValAssign::AExt:
+        // Intentional fall-through.  Handle AExt and ZExt.
       case CCValAssign::ZExt: {
-        bool Emitted =3D FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
-                                         Arg, ArgVT, Arg);
-        assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
-        Emitted =3D true;
-        ArgVT =3D VA.getLocVT();
-        break;
-      }
-      case CCValAssign::AExt: {
-        bool Emitted =3D FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
-                                         Arg, ArgVT, Arg);
-        if (!Emitted)
-          Emitted =3D FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
-                                      Arg, ArgVT, Arg);
-        if (!Emitted)
-          Emitted =3D FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
-                                      Arg, ArgVT, Arg);
-
-        assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
-        ArgVT =3D VA.getLocVT();
+        MVT DestVT =3D VA.getLocVT();
+        Arg =3D ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/true);
+        assert (Arg !=3D 0 && "Failed to emit a sext");
+        ArgVT =3D DestVT;
         break;
       }
       case CCValAssign::BCvt: {
@@ -1634,16 +1945,17 @@
     if (VA.isRegLoc() && !VA.needsCustom()) {
       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::=
COPY),
               VA.getLocReg())
-      .addReg(Arg);
+        .addReg(Arg);
       RegArgs.push_back(VA.getLocReg());
     } else if (VA.needsCustom()) {
       // TODO: We need custom lowering for vector (v2f64) args.
-      if (VA.getLocVT() !=3D MVT::f64) return false;
+      assert(VA.getLocVT() =3D=3D MVT::f64 &&
+             "Custom lowering for v2f64 args not available");
=20
       CCValAssign &NextVA =3D ArgLocs[++i];
=20
-      // TODO: Only handle register args for now.
-      if(!(VA.isRegLoc() && NextVA.isRegLoc())) return false;
+      assert(VA.isRegLoc() && NextVA.isRegLoc() &&
+             "We only handle register args!");
=20
       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                               TII.get(ARM::VMOVRRD), VA.getLocReg())
@@ -1659,9 +1971,11 @@
       Addr.Base.Reg =3D ARM::SP;
       Addr.Offset =3D VA.getLocMemOffset();
=20
-      if (!ARMEmitStore(ArgVT, Arg, Addr)) return false;
+      bool EmitRet =3D ARMEmitStore(ArgVT, Arg, Addr); (void)EmitRet;
+      assert(EmitRet && "Could not emit a store for argument!");
     }
   }
+
   return true;
 }
=20
@@ -1685,7 +1999,7 @@
       // For this move we copy into two registers and then move into the
       // double fp reg we want.
       EVT DestVT =3D RVLocs[0].getValVT();
-      TargetRegisterClass* DstRC =3D TLI.getRegClassFor(DestVT);
+      const TargetRegisterClass* DstRC =3D TLI.getRegClassFor(DestVT);
       unsigned ResultReg =3D createResultReg(DstRC);
       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                               TII.get(ARM::VMOVDRR), ResultReg)
@@ -1700,7 +2014,12 @@
     } else {
       assert(RVLocs.size() =3D=3D 1 &&"Can't handle non-double multi-reg r=
etvals!");
       EVT CopyVT =3D RVLocs[0].getValVT();
-      TargetRegisterClass* DstRC =3D TLI.getRegClassFor(CopyVT);
+
+      // Special handling for extended integers.
+      if (RetVT =3D=3D MVT::i1 || RetVT =3D=3D MVT::i8 || RetVT =3D=3D MVT=
::i16)
+        CopyVT =3D MVT::i32;
+
+      const TargetRegisterClass* DstRC =3D TLI.getRegClassFor(CopyVT);
=20
       unsigned ResultReg =3D createResultReg(DstRC);
       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::=
COPY),
@@ -1753,13 +2072,26 @@
     // Only handle register returns for now.
     if (!VA.isRegLoc())
       return false;
-    // TODO: For now, don't try to handle cases where getLocInfo()
-    // says Full but the types don't match.
-    if (TLI.getValueType(RV->getType()) !=3D VA.getValVT())
-      return false;
+
+    unsigned SrcReg =3D Reg + VA.getValNo();
+    EVT RVVT =3D TLI.getValueType(RV->getType());
+    EVT DestVT =3D VA.getValVT();
+    // Special handling for extended integers.
+    if (RVVT !=3D DestVT) {
+      if (RVVT !=3D MVT::i1 && RVVT !=3D MVT::i8 && RVVT !=3D MVT::i16)
+        return false;
+
+      assert(DestVT =3D=3D MVT::i32 && "ARM should always ext to i32");
+
+      // Perform extension if flagged as either zext or sext.  Otherwise, =
do
+      // nothing.
+      if (Outs[0].Flags.isZExt() || Outs[0].Flags.isSExt()) {
+        SrcReg =3D ARMEmitIntExt(RVVT, SrcReg, DestVT, Outs[0].Flags.isZEx=
t());
+        if (SrcReg =3D=3D 0) return false;
+      }
+    }
=20
     // Make the copy.
-    unsigned SrcReg =3D Reg + VA.getValNo();
     unsigned DstReg =3D VA.getLocReg();
     const TargetRegisterClass* SrcRC =3D MRI.getRegClass(SrcReg);
     // Avoid a cross-class copy. This is very unlikely.
@@ -1772,20 +2104,17 @@
     MRI.addLiveOut(VA.getLocReg());
   }
=20
-  unsigned RetOpc =3D isThumb ? ARM::tBX_RET : ARM::BX_RET;
+  unsigned RetOpc =3D isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                           TII.get(RetOpc)));
   return true;
 }
=20
 unsigned ARMFastISel::ARMSelectCallOp(const GlobalValue *GV) {
-
-  // Darwin needs the r9 versions of the opcodes.
-  bool isDarwin =3D Subtarget->isTargetDarwin();
-  if (isThumb) {
-    return isDarwin ? ARM::tBLr9 : ARM::tBL;
+  if (isThumb2) {
+    return ARM::tBL;
   } else  {
-    return isDarwin ? ARM::BLr9 : ARM::BL;
+    return ARM::BL;
   }
 }
=20
@@ -1844,11 +2173,10 @@
   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBy=
tes))
     return false;
=20
-  // Issue the call, BLr9 for darwin, BL otherwise.
-  // TODO: Turn this into the table of arm call ops.
+  // Issue the call.
   MachineInstrBuilder MIB;
   unsigned CallOpc =3D ARMSelectCallOp(NULL);
-  if(isThumb)
+  if (isThumb2)
     // Explicitly adding the predicate here.
     MIB =3D AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                          TII.get(CallOpc)))
@@ -1863,6 +2191,10 @@
   for (unsigned i =3D 0, e =3D RegArgs.size(); i !=3D e; ++i)
     MIB.addReg(RegArgs[i]);
=20
+  // Add a register mask with the call-preserved registers.
+  // Proper defs for return values will be added by setPhysRegsDeadExcept(=
).
+  MIB.addRegMask(TRI.getCallPreservedMask(CC));
+
   // Finish off the call including any return values.
   SmallVector<unsigned, 4> UsedRegs;
   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
@@ -1873,12 +2205,13 @@
   return true;
 }
=20
-bool ARMFastISel::SelectCall(const Instruction *I) {
+bool ARMFastISel::SelectCall(const Instruction *I,
+                             const char *IntrMemName =3D 0) {
   const CallInst *CI =3D cast<CallInst>(I);
   const Value *Callee =3D CI->getCalledValue();
=20
-  // Can't handle inline asm or worry about intrinsics yet.
-  if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
+  // Can't handle inline asm.
+  if (isa<InlineAsm>(Callee)) return false;
=20
   // Only handle global variable Callees.
   const GlobalValue *GV =3D dyn_cast<GlobalValue>(Callee);
@@ -1902,7 +2235,8 @@
   MVT RetVT;
   if (RetTy->isVoidTy())
     RetVT =3D MVT::isVoid;
-  else if (!isTypeLegal(RetTy, RetVT))
+  else if (!isTypeLegal(RetTy, RetVT) && RetVT !=3D MVT::i16 &&
+           RetVT !=3D MVT::i8  && RetVT !=3D MVT::i1)
     return false;
=20
   // TODO: For now if we have long calls specified we don't handle the cal=
l.
@@ -1913,16 +2247,18 @@
   SmallVector<unsigned, 8> ArgRegs;
   SmallVector<MVT, 8> ArgVTs;
   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
-  Args.reserve(CS.arg_size());
-  ArgRegs.reserve(CS.arg_size());
-  ArgVTs.reserve(CS.arg_size());
-  ArgFlags.reserve(CS.arg_size());
+  unsigned arg_size =3D CS.arg_size();
+  Args.reserve(arg_size);
+  ArgRegs.reserve(arg_size);
+  ArgVTs.reserve(arg_size);
+  ArgFlags.reserve(arg_size);
   for (ImmutableCallSite::arg_iterator i =3D CS.arg_begin(), e =3D CS.arg_=
end();
        i !=3D e; ++i) {
-    unsigned Arg =3D getRegForValue(*i);
+    // If we're lowering a memory intrinsic instead of a regular call, ski=
p the
+    // last two arguments, which shouldn't be passed to the underlying fun=
ction.
+    if (IntrMemName && e-i <=3D 2)
+      break;
=20
-    if (Arg =3D=3D 0)
-      return false;
     ISD::ArgFlagsTy Flags;
     unsigned AttrInd =3D i - CS.arg_begin() + 1;
     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
@@ -1930,7 +2266,7 @@
     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
       Flags.setZExt();
=20
-         // FIXME: Only handle *easy* calls for now.
+    // FIXME: Only handle *easy* calls for now.
     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
@@ -1939,8 +2275,14 @@
=20
     Type *ArgTy =3D (*i)->getType();
     MVT ArgVT;
-    if (!isTypeLegal(ArgTy, ArgVT))
+    if (!isTypeLegal(ArgTy, ArgVT) && ArgVT !=3D MVT::i16 && ArgVT !=3D MV=
T::i8 &&
+        ArgVT !=3D MVT::i1)
       return false;
+
+    unsigned Arg =3D getRegForValue(*i);
+    if (Arg =3D=3D 0)
+      return false;
+
     unsigned OriginalAlignment =3D TD.getABITypeAlignment(ArgTy);
     Flags.setOrigAlign(OriginalAlignment);
=20
@@ -1956,26 +2298,38 @@
   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBy=
tes))
     return false;
=20
-  // Issue the call, BLr9 for darwin, BL otherwise.
-  // TODO: Turn this into the table of arm call ops.
+  // Issue the call.
   MachineInstrBuilder MIB;
   unsigned CallOpc =3D ARMSelectCallOp(GV);
   // Explicitly adding the predicate here.
-  if(isThumb)
+  if(isThumb2) {
     // Explicitly adding the predicate here.
     MIB =3D AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                         TII.get(CallOpc)))
-          .addGlobalAddress(GV, 0, 0);
-  else
-    // Explicitly adding the predicate here.
-    MIB =3D AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
-                         TII.get(CallOpc))
-          .addGlobalAddress(GV, 0, 0));
-
+                                 TII.get(CallOpc)));
+    if (!IntrMemName)
+      MIB.addGlobalAddress(GV, 0, 0);
+    else=20
+      MIB.addExternalSymbol(IntrMemName, 0);
+  } else {
+    if (!IntrMemName)
+      // Explicitly adding the predicate here.
+      MIB =3D AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                                   TII.get(CallOpc))
+            .addGlobalAddress(GV, 0, 0));
+    else
+      MIB =3D AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
+                                   TII.get(CallOpc))
+            .addExternalSymbol(IntrMemName, 0));
+  }
+ =20
   // Add implicit physical register uses to the call.
   for (unsigned i =3D 0, e =3D RegArgs.size(); i !=3D e; ++i)
     MIB.addReg(RegArgs[i]);
=20
+  // Add a register mask with the call-preserved registers.
+  // Proper defs for return values will be added by setPhysRegsDeadExcept(=
).
+  MIB.addRegMask(TRI.getCallPreservedMask(CC));
+
   // Finish off the call including any return values.
   SmallVector<unsigned, 4> UsedRegs;
   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
@@ -1984,83 +2338,187 @@
   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
=20
   return true;
-
 }
=20
-bool ARMFastISel::SelectIntCast(const Instruction *I) {
-  // On ARM, in general, integer casts don't involve legal types; this code
-  // handles promotable integers.  The high bits for a type smaller than
-  // the register size are assumed to be undefined.
-  Type *DestTy =3D I->getType();
+bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
+  return Len <=3D 16;
+}
+
+bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src,
+                                        uint64_t Len) {
+  // Make sure we don't bloat code by inlining very large memcpy's.
+  if (!ARMIsMemCpySmall(Len))
+    return false;
+
+  // We don't care about alignment here since we just emit integer accesse=
s.
+  while (Len) {
+    MVT VT;
+    if (Len >=3D 4)
+      VT =3D MVT::i32;
+    else if (Len >=3D 2)
+      VT =3D MVT::i16;
+    else {
+      assert(Len =3D=3D 1);
+      VT =3D MVT::i8;
+    }
+
+    bool RV;
+    unsigned ResultReg;
+    RV =3D ARMEmitLoad(VT, ResultReg, Src);
+    assert (RV =3D=3D true && "Should be able to handle this load.");
+    RV =3D ARMEmitStore(VT, ResultReg, Dest);
+    assert (RV =3D=3D true && "Should be able to handle this store.");
+    (void)RV;
+
+    unsigned Size =3D VT.getSizeInBits()/8;
+    Len -=3D Size;
+    Dest.Offset +=3D Size;
+    Src.Offset +=3D Size;
+  }
+
+  return true;
+}
+
+bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
+  // FIXME: Handle more intrinsics.
+  switch (I.getIntrinsicID()) {
+  default: return false;
+  case Intrinsic::memcpy:
+  case Intrinsic::memmove: {
+    const MemTransferInst &MTI =3D cast<MemTransferInst>(I);
+    // Don't handle volatile.
+    if (MTI.isVolatile())
+      return false;
+
+    // Disable inlining for memmove before calls to ComputeAddress.  Other=
wise,
+    // we would emit dead code because we don't currently handle memmoves.
+    bool isMemCpy =3D (I.getIntrinsicID() =3D=3D Intrinsic::memcpy);
+    if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
+      // Small memcpy's are common enough that we want to do them without =
a call
+      // if possible.
+      uint64_t Len =3D cast<ConstantInt>(MTI.getLength())->getZExtValue();
+      if (ARMIsMemCpySmall(Len)) {
+        Address Dest, Src;
+        if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
+            !ARMComputeAddress(MTI.getRawSource(), Src))
+          return false;
+        if (ARMTryEmitSmallMemCpy(Dest, Src, Len))
+          return true;
+      }
+    }
+   =20
+    if (!MTI.getLength()->getType()->isIntegerTy(32))
+      return false;
+   =20
+    if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 2=
55)
+      return false;
+
+    const char *IntrMemName =3D isa<MemCpyInst>(I) ? "memcpy" : "memmove";
+    return SelectCall(&I, IntrMemName);
+  }
+  case Intrinsic::memset: {
+    const MemSetInst &MSI =3D cast<MemSetInst>(I);
+    // Don't handle volatile.
+    if (MSI.isVolatile())
+      return false;
+   =20
+    if (!MSI.getLength()->getType()->isIntegerTy(32))
+      return false;
+   =20
+    if (MSI.getDestAddressSpace() > 255)
+      return false;
+   =20
+    return SelectCall(&I, "memset");
+  }
+  }
+}
+
+bool ARMFastISel::SelectTrunc(const Instruction *I) {
+  // The high bits for a type smaller than the register size are assumed t=
o be=20
+  // undefined.
   Value *Op =3D I->getOperand(0);
-  Type *SrcTy =3D Op->getType();
=20
   EVT SrcVT, DestVT;
-  SrcVT =3D TLI.getValueType(SrcTy, true);
-  DestVT =3D TLI.getValueType(DestTy, true);
+  SrcVT =3D TLI.getValueType(Op->getType(), true);
+  DestVT =3D TLI.getValueType(I->getType(), true);
=20
-  if (isa<TruncInst>(I)) {
-    if (SrcVT !=3D MVT::i32 && SrcVT !=3D MVT::i16 && SrcVT !=3D MVT::i8)
-      return false;
-    if (DestVT !=3D MVT::i16 && DestVT !=3D MVT::i8 && DestVT !=3D MVT::i1)
-      return false;
-
-    unsigned SrcReg =3D getRegForValue(Op);
-    if (!SrcReg) return false;
-
-    // Because the high bits are undefined, a truncate doesn't generate
-    // any code.
-    UpdateValueMap(I, SrcReg);
-    return true;
-  }
-  if (DestVT !=3D MVT::i32 && DestVT !=3D MVT::i16 && DestVT !=3D MVT::i8)
+  if (SrcVT !=3D MVT::i32 && SrcVT !=3D MVT::i16 && SrcVT !=3D MVT::i8)
+    return false;
+  if (DestVT !=3D MVT::i16 && DestVT !=3D MVT::i8 && DestVT !=3D MVT::i1)
     return false;
=20
+  unsigned SrcReg =3D getRegForValue(Op);
+  if (!SrcReg) return false;
+
+  // Because the high bits are undefined, a truncate doesn't generate
+  // any code.
+  UpdateValueMap(I, SrcReg);
+  return true;
+}
+
+unsigned ARMFastISel::ARMEmitIntExt(EVT SrcVT, unsigned SrcReg, EVT DestVT,
+                                    bool isZExt) {
+  if (DestVT !=3D MVT::i32 && DestVT !=3D MVT::i16 && DestVT !=3D MVT::i8)
+    return 0;
+
   unsigned Opc;
-  bool isZext =3D isa<ZExtInst>(I);
   bool isBoolZext =3D false;
-  if (!SrcVT.isSimple())
-    return false;
+  if (!SrcVT.isSimple()) return 0;
   switch (SrcVT.getSimpleVT().SimpleTy) {
-  default: return false;
+  default: return 0;
   case MVT::i16:
-    if (!Subtarget->hasV6Ops()) return false;
-    if (isZext)
-      Opc =3D isThumb ? ARM::t2UXTH : ARM::UXTH;
+    if (!Subtarget->hasV6Ops()) return 0;
+    if (isZExt)
+      Opc =3D isThumb2 ? ARM::t2UXTH : ARM::UXTH;
     else
-      Opc =3D isThumb ? ARM::t2SXTH : ARM::SXTH;
+      Opc =3D isThumb2 ? ARM::t2SXTH : ARM::SXTH;
     break;
   case MVT::i8:
-    if (!Subtarget->hasV6Ops()) return false;
-    if (isZext)
-      Opc =3D isThumb ? ARM::t2UXTB : ARM::UXTB;
+    if (!Subtarget->hasV6Ops()) return 0;
+    if (isZExt)
+      Opc =3D isThumb2 ? ARM::t2UXTB : ARM::UXTB;
     else
-      Opc =3D isThumb ? ARM::t2SXTB : ARM::SXTB;
+      Opc =3D isThumb2 ? ARM::t2SXTB : ARM::SXTB;
     break;
   case MVT::i1:
-    if (isZext) {
-      Opc =3D isThumb ? ARM::t2ANDri : ARM::ANDri;
+    if (isZExt) {
+      Opc =3D isThumb2 ? ARM::t2ANDri : ARM::ANDri;
       isBoolZext =3D true;
       break;
     }
-    return false;
+    return 0;
   }
=20
-  // FIXME: We could save an instruction in many cases by special-casing
-  // load instructions.
-  unsigned SrcReg =3D getRegForValue(Op);
-  if (!SrcReg) return false;
-
-  unsigned DestReg =3D createResultReg(TLI.getRegClassFor(MVT::i32));
+  unsigned ResultReg =3D createResultReg(TLI.getRegClassFor(MVT::i32));
   MachineInstrBuilder MIB;
-  MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), Dest=
Reg)
+  MIB =3D BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), Resu=
ltReg)
         .addReg(SrcReg);
   if (isBoolZext)
     MIB.addImm(1);
   else
     MIB.addImm(0);
   AddOptionalDefs(MIB);
-  UpdateValueMap(I, DestReg);
+  return ResultReg;
+}
+
+bool ARMFastISel::SelectIntExt(const Instruction *I) {
+  // On ARM, in general, integer casts don't involve legal types; this code
+  // handles promotable integers.
+  Type *DestTy =3D I->getType();
+  Value *Src =3D I->getOperand(0);
+  Type *SrcTy =3D Src->getType();
+
+  EVT SrcVT, DestVT;
+  SrcVT =3D TLI.getValueType(SrcTy, true);
+  DestVT =3D TLI.getValueType(DestTy, true);
+
+  bool isZExt =3D isa<ZExtInst>(I);
+  unsigned SrcReg =3D getRegForValue(Src);
+  if (!SrcReg) return false;
+
+  unsigned ResultReg =3D ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
+  if (ResultReg =3D=3D 0) return false;
+  UpdateValueMap(I, ResultReg);
   return true;
 }
=20
@@ -2074,6 +2532,8 @@
       return SelectStore(I);
     case Instruction::Br:
       return SelectBranch(I);
+    case Instruction::IndirectBr:
+      return SelectIndirectBr(I);
     case Instruction::ICmp:
     case Instruction::FCmp:
       return SelectCmp(I);
@@ -2082,42 +2542,105 @@
     case Instruction::FPTrunc:
       return SelectFPTrunc(I);
     case Instruction::SIToFP:
-      return SelectSIToFP(I);
+      return SelectIToFP(I, /*isSigned*/ true);
+    case Instruction::UIToFP:
+      return SelectIToFP(I, /*isSigned*/ false);
     case Instruction::FPToSI:
-      return SelectFPToSI(I);
+      return SelectFPToI(I, /*isSigned*/ true);
+    case Instruction::FPToUI:
+      return SelectFPToI(I, /*isSigned*/ false);
+    case Instruction::Add:
+      return SelectBinaryIntOp(I, ISD::ADD);
+    case Instruction::Or:
+      return SelectBinaryIntOp(I, ISD::OR);
+    case Instruction::Sub:
+      return SelectBinaryIntOp(I, ISD::SUB);
     case Instruction::FAdd:
-      return SelectBinaryOp(I, ISD::FADD);
+      return SelectBinaryFPOp(I, ISD::FADD);
     case Instruction::FSub:
-      return SelectBinaryOp(I, ISD::FSUB);
+      return SelectBinaryFPOp(I, ISD::FSUB);
     case Instruction::FMul:
-      return SelectBinaryOp(I, ISD::FMUL);
+      return SelectBinaryFPOp(I, ISD::FMUL);
     case Instruction::SDiv:
-      return SelectSDiv(I);
+      return SelectDiv(I, /*isSigned*/ true);
+    case Instruction::UDiv:
+      return SelectDiv(I, /*isSigned*/ false);
     case Instruction::SRem:
-      return SelectSRem(I);
+      return SelectRem(I, /*isSigned*/ true);
+    case Instruction::URem:
+      return SelectRem(I, /*isSigned*/ false);
     case Instruction::Call:
+      if (const IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(I))
+        return SelectIntrinsicCall(*II);
       return SelectCall(I);
     case Instruction::Select:
       return SelectSelect(I);
     case Instruction::Ret:
       return SelectRet(I);
     case Instruction::Trunc:
+      return SelectTrunc(I);
     case Instruction::ZExt:
     case Instruction::SExt:
-      return SelectIntCast(I);
+      return SelectIntExt(I);
     default: break;
   }
   return false;
 }
=20
+/// TryToFoldLoad - The specified machine instr operand is a vreg, and that
+/// vreg is being provided by the specified load instruction.  If possible,
+/// try to fold the load as an operand to the instruction, returning true =
if
+/// successful.
+bool ARMFastISel::TryToFoldLoad(MachineInstr *MI, unsigned OpNo,
+                                const LoadInst *LI) {
+  // Verify we have a legal type before going any further.
+  MVT VT;
+  if (!isLoadTypeLegal(LI->getType(), VT))
+    return false;
+
+  // Combine load followed by zero- or sign-extend.
+  // ldrb r1, [r0]       ldrb r1, [r0]
+  // uxtb r2, r1     =3D>
+  // mov  r3, r2         mov  r3, r1
+  bool isZExt =3D true;
+  switch(MI->getOpcode()) {
+    default: return false;
+    case ARM::SXTH:
+    case ARM::t2SXTH:
+      isZExt =3D false;
+    case ARM::UXTH:
+    case ARM::t2UXTH:
+      if (VT !=3D MVT::i16)
+        return false;
+    break;
+    case ARM::SXTB:
+    case ARM::t2SXTB:
+      isZExt =3D false;
+    case ARM::UXTB:
+    case ARM::t2UXTB:
+      if (VT !=3D MVT::i8)
+        return false;
+    break;
+  }
+  // See if we can handle this address.
+  Address Addr;
+  if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
+ =20
+  unsigned ResultReg =3D MI->getOperand(0).getReg();
+  if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
+    return false;
+  MI->eraseFromParent();
+  return true;
+}
+
 namespace llvm {
-  llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
-    // Completely untested on non-darwin.
+  FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
+    // Completely untested on non-iOS.
     const TargetMachine &TM =3D funcInfo.MF->getTarget();
=20
     // Darwin and thumb1 only for now.
     const ARMSubtarget *Subtarget =3D &TM.getSubtarget<ARMSubtarget>();
-    if (Subtarget->isTargetDarwin() && !Subtarget->isThumb1Only() &&
+    if (Subtarget->isTargetIOS() && !Subtarget->isThumb1Only() &&
         !DisableARMFastISel)
       return new ARMFastISel(funcInfo);
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMFr=
ameLowering.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMFrameLowering.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMFrameLowering.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D=3D=3D- ARMFrameLowering.cpp - ARM Frame Information ----=
----*- C++ -*-=3D=3D=3D=3D//
+//=3D=3D=3D-- ARMFrameLowering.cpp - ARM Frame Information ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,31 +15,40 @@
 #include "ARMBaseInstrInfo.h"
 #include "ARMBaseRegisterInfo.h"
 #include "ARMMachineFunctionInfo.h"
-#include "llvm/CallingConv.h"
+#include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/Function.h"
-#include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/RegisterScavenging.h"
 #include "llvm/Target/TargetOptions.h"
+#include "llvm/Support/CommandLine.h"
=20
 using namespace llvm;
=20
+static cl::opt<bool>
+SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
+                     cl::desc("Align ARM NEON spills in prolog and epilog"=
));
+
+static MachineBasicBlock::iterator
+skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
+                        unsigned NumAlignedDPRCS2Regs);
+
 /// hasFP - Return true if the specified function should have a dedicated =
frame
 /// pointer register.  This is true if the function has variable sized all=
ocas
 /// or if frame pointer elimination is disabled.
 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
   const TargetRegisterInfo *RegInfo =3D MF.getTarget().getRegisterInfo();
=20
-  // Mac OS X requires FP not to be clobbered for backtracing purpose.
-  if (STI.isTargetDarwin())
+  // iOS requires FP not to be clobbered for backtracing purpose.
+  if (STI.isTargetIOS())
     return true;
=20
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
   // Always eliminate non-leaf frame pointers.
-  return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
+  return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
+           MFI->hasCalls()) ||
           RegInfo->needsStackRealignment(MF) ||
           MFI->hasVarSizedObjects() ||
           MFI->isFrameAddressTaken());
@@ -72,7 +81,7 @@
   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects=
();
 }
=20
-static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
+static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
   for (unsigned i =3D 0; CSRegs[i]; ++i)
     if (Reg =3D=3D CSRegs[i])
       return true;
@@ -81,7 +90,7 @@
=20
 static bool isCSRestore(MachineInstr *MI,
                         const ARMBaseInstrInfo &TII,
-                        const unsigned *CSRegs) {
+                        const uint16_t *CSRegs) {
   // Integer spill area is handled with "pop".
   if (MI->getOpcode() =3D=3D ARM::LDMIA_RET ||
       MI->getOpcode() =3D=3D ARM::t2LDMIA_RET ||
@@ -140,10 +149,7 @@
   // belongs to which callee-save spill areas.
   unsigned GPRCS1Size =3D 0, GPRCS2Size =3D 0, DPRCSSize =3D 0;
   int FramePtrSpillFI =3D 0;
-
-  // All calls are tail calls in GHC calling conv, and functions have no p=
rologue/epilogue.
-  if (MF.getFunction()->getCallingConv() =3D=3D CallingConv::GHC)
-    return;
+  int D8SpillFI =3D 0;
=20
   // Allocate the vararg register save area. This is not counted in NumByt=
es.
   if (VARegSaveSize)
@@ -177,7 +183,7 @@
     case ARM::R11:
       if (Reg =3D=3D FramePtr)
         FramePtrSpillFI =3D FI;
-      if (STI.isTargetDarwin()) {
+      if (STI.isTargetIOS()) {
         AFI->addGPRCalleeSavedArea2Frame(FI);
         GPRCS2Size +=3D 4;
       } else {
@@ -186,8 +192,13 @@
       }
       break;
     default:
-      AFI->addDPRCalleeSavedAreaFrame(FI);
-      DPRCSSize +=3D 8;
+      // This is a DPR. Exclude the aligned DPRCS2 spills.
+      if (Reg =3D=3D ARM::D8)
+        D8SpillFI =3D FI;
+      if (Reg < ARM::D8 || Reg >=3D ARM::D8 + AFI->getNumAlignedDPRCS2Regs=
()) {
+        AFI->addDPRCalleeSavedAreaFrame(FI);
+        DPRCSSize +=3D 8;
+      }
     }
   }
=20
@@ -195,8 +206,8 @@
   if (GPRCS1Size > 0) MBBI++;
=20
   // Set FP to point to the stack slot that contains the previous FP.
-  // For Darwin, FP is R7, which has now been stored in spill area 1.
-  // Otherwise, if this is not Darwin, all the callee-saved registers go
+  // For iOS, FP is R7, which has now been stored in spill area 1.
+  // Otherwise, if this is not iOS, all the callee-saved registers go
   // into spill area 1, including the FP in R11.  In either case, it is
   // now safe to emit this assignment.
   bool HasFP =3D hasFP(MF);
@@ -232,7 +243,17 @@
       MBBI++;
   }
=20
-  NumBytes =3D DPRCSOffset;
+  // Move past the aligned DPRCS2 area.
+  if (AFI->getNumAlignedDPRCS2Regs() > 0) {
+    MBBI =3D skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
+    // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
+    // leaves the stack pointer pointing to the DPRCS2 area.
+    //
+    // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
+    NumBytes +=3D MFI->getObjectOffset(D8SpillFI);
+  } else
+    NumBytes =3D DPRCSOffset;
+
   if (NumBytes) {
     // Adjust SP after all the callee-save spills.
     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
@@ -259,7 +280,9 @@
=20
   // If we need dynamic stack realignment, do it here. Be paranoid and make
   // sure if we also have VLAs, we have a base pointer for frame access.
-  if (RegInfo->needsStackRealignment(MF)) {
+  // If aligned NEON registers were spilled, the stack has already been
+  // realigned.
+  if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF=
)) {
     unsigned MaxAlign =3D MFI->getMaxAlignment();
     assert (!AFI->isThumb1OnlyFunction());
     if (!AFI->isThumbFunction()) {
@@ -315,8 +338,7 @@
 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
                                     MachineBasicBlock &MBB) const {
   MachineBasicBlock::iterator MBBI =3D MBB.getLastNonDebugInstr();
-  assert(MBBI->getDesc().isReturn() &&
-         "Can only insert epilog into returning blocks");
+  assert(MBBI->isReturn() && "Can only insert epilog into returning blocks=
");
   unsigned RetOpcode =3D MBBI->getOpcode();
   DebugLoc dl =3D MBBI->getDebugLoc();
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
@@ -332,16 +354,12 @@
   int NumBytes =3D (int)MFI->getStackSize();
   unsigned FramePtr =3D RegInfo->getFrameRegister(MF);
=20
-  // All calls are tail calls in GHC calling conv, and functions have no p=
rologue/epilogue.
-  if (MF.getFunction()->getCallingConv() =3D=3D CallingConv::GHC)
-    return;
-
   if (!AFI->hasStackFrame()) {
     if (NumBytes !=3D 0)
       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
   } else {
     // Unwind MBBI to point to first LDR / VLDRD.
-    const unsigned *CSRegs =3D RegInfo->getCalleeSavedRegs();
+    const uint16_t *CSRegs =3D RegInfo->getCalleeSavedRegs();
     if (MBBI !=3D MBB.begin()) {
       do
         --MBBI;
@@ -365,7 +383,7 @@
                                   ARMCC::AL, 0, TII);
         else {
           // It's not possible to restore SP from FP in a single instructi=
on.
-          // For Darwin, this looks like:
+          // For iOS, this looks like:
           // mov sp, r7
           // sub sp, #24
           // This is bad, if an interrupt is taken after the mov, sp is in=
 an
@@ -404,17 +422,16 @@
     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
   }
=20
-  if (RetOpcode =3D=3D ARM::TCRETURNdi || RetOpcode =3D=3D ARM::TCRETURNdi=
ND ||
-      RetOpcode =3D=3D ARM::TCRETURNri || RetOpcode =3D=3D ARM::TCRETURNri=
ND) {
+  if (RetOpcode =3D=3D ARM::TCRETURNdi || RetOpcode =3D=3D ARM::TCRETURNri=
) {
     // Tail call return: adjust the stack pointer and jump to callee.
     MBBI =3D MBB.getLastNonDebugInstr();
     MachineOperand &JumpTarget =3D MBBI->getOperand(0);
=20
     // Jump to label or value in register.
-    if (RetOpcode =3D=3D ARM::TCRETURNdi || RetOpcode =3D=3D ARM::TCRETURN=
diND) {
-      unsigned TCOpcode =3D (RetOpcode =3D=3D ARM::TCRETURNdi)
-        ? (STI.isThumb() ? ARM::tTAILJMPd : ARM::TAILJMPd)
-        : (STI.isThumb() ? ARM::tTAILJMPdND : ARM::TAILJMPdND);
+    if (RetOpcode =3D=3D ARM::TCRETURNdi) {
+      unsigned TCOpcode =3D STI.isThumb() ?
+               (STI.isTargetIOS() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
+               ARM::TAILJMPd;
       MachineInstrBuilder MIB =3D BuildMI(MBB, MBBI, dl, TII.get(TCOpcode)=
);
       if (JumpTarget.isGlobal())
         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(=
),
@@ -431,10 +448,6 @@
       BuildMI(MBB, MBBI, dl,
               TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
         addReg(JumpTarget.getReg(), RegState::Kill);
-    } else if (RetOpcode =3D=3D ARM::TCRETURNriND) {
-      BuildMI(MBB, MBBI, dl,
-              TII.get(STI.isThumb() ? ARM::tTAILJMPrND : ARM::TAILJMPrND)).
-        addReg(JumpTarget.getReg(), RegState::Kill);
     }
=20
     MachineInstr *NewMI =3D prior(MBBI);
@@ -481,6 +494,10 @@
   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
     return Offset - AFI->getDPRCalleeSavedAreaOffset();
=20
+  // SP can move around if there are allocas.  We may also lose track of SP
+  // when emergency spilling inside a non-reserved call frame setup.
+  bool hasMovingSP =3D !hasReservedCallFrame(MF);
+
   // When dynamically realigning the stack, use the frame pointer for
   // parameters, and the stack/base pointer for locals.
   if (RegInfo->needsStackRealignment(MF)) {
@@ -488,7 +505,7 @@
     if (isFixed) {
       FrameReg =3D RegInfo->getFrameRegister(MF);
       Offset =3D FPOffset;
-    } else if (MFI->hasVarSizedObjects()) {
+    } else if (hasMovingSP) {
       assert(RegInfo->hasBasePointer(MF) &&
              "VLAs and dynamic stack alignment, but missing base pointer!"=
);
       FrameReg =3D RegInfo->getBaseRegister();
@@ -500,11 +517,10 @@
   if (hasFP(MF) && AFI->hasStackFrame()) {
     // Use frame pointer to reference fixed objects. Use it for locals if
     // there are VLAs (and thus the SP isn't reliable as a base).
-    if (isFixed || (MFI->hasVarSizedObjects() &&
-                    !RegInfo->hasBasePointer(MF))) {
+    if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
       FrameReg =3D RegInfo->getFrameRegister(MF);
       return FPOffset;
-    } else if (MFI->hasVarSizedObjects()) {
+    } else if (hasMovingSP) {
       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
       if (AFI->isThumb2Function()) {
         // Try to use the frame pointer if we can, else use the base point=
er
@@ -551,6 +567,7 @@
                                     unsigned StmOpc, unsigned StrOpc,
                                     bool NoGap,
                                     bool(*Func)(unsigned, bool),
+                                    unsigned NumAlignedDPRCS2Regs,
                                     unsigned MIFlags) const {
   MachineFunction &MF =3D *MBB.getParent();
   const TargetInstrInfo &TII =3D *MF.getTarget().getInstrInfo();
@@ -564,7 +581,11 @@
     unsigned LastReg =3D 0;
     for (; i !=3D 0; --i) {
       unsigned Reg =3D CSI[i-1].getReg();
-      if (!(Func)(Reg, STI.isTargetDarwin())) continue;
+      if (!(Func)(Reg, STI.isTargetIOS())) continue;
+
+      // D-registers in the aligned area DPRCS2 are NOT spilled here.
+      if (Reg >=3D ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
+        continue;
=20
       // Add the callee-saved register as live-in unless it's LR and
       // @llvm.returnaddress is called. If LR is returned for
@@ -614,16 +635,15 @@
                                    const std::vector<CalleeSavedInfo> &CSI,
                                    unsigned LdmOpc, unsigned LdrOpc,
                                    bool isVarArg, bool NoGap,
-                                   bool(*Func)(unsigned, bool)) const {
+                                   bool(*Func)(unsigned, bool),
+                                   unsigned NumAlignedDPRCS2Regs) const {
   MachineFunction &MF =3D *MBB.getParent();
   const TargetInstrInfo &TII =3D *MF.getTarget().getInstrInfo();
   ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
   DebugLoc DL =3D MI->getDebugLoc();
   unsigned RetOpcode =3D MI->getOpcode();
   bool isTailCall =3D (RetOpcode =3D=3D ARM::TCRETURNdi ||
-                     RetOpcode =3D=3D ARM::TCRETURNdiND ||
-                     RetOpcode =3D=3D ARM::TCRETURNri ||
-                     RetOpcode =3D=3D ARM::TCRETURNriND);
+                     RetOpcode =3D=3D ARM::TCRETURNri);
=20
   SmallVector<unsigned, 4> Regs;
   unsigned i =3D CSI.size();
@@ -632,7 +652,11 @@
     bool DeleteRet =3D false;
     for (; i !=3D 0; --i) {
       unsigned Reg =3D CSI[i-1].getReg();
-      if (!(Func)(Reg, STI.isTargetDarwin())) continue;
+      if (!(Func)(Reg, STI.isTargetIOS())) continue;
+
+      // The aligned reloads from area DPRCS2 are not inserted here.
+      if (Reg >=3D ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
+        continue;
=20
       if (Reg =3D=3D ARM::LR && !isTailCall && !isVarArg && STI.hasV5TOps(=
)) {
         Reg =3D ARM::PC;
@@ -686,6 +710,247 @@
   }
 }
=20
+/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
+/// starting from d8.  Also insert stack realignment code and leave the st=
ack
+/// pointer pointing to the d8 spill slot.
+static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
+                                    MachineBasicBlock::iterator MI,
+                                    unsigned NumAlignedDPRCS2Regs,
+                                    const std::vector<CalleeSavedInfo> &CS=
I,
+                                    const TargetRegisterInfo *TRI) {
+  MachineFunction &MF =3D *MBB.getParent();
+  ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
+  DebugLoc DL =3D MI->getDebugLoc();
+  const TargetInstrInfo &TII =3D *MF.getTarget().getInstrInfo();
+  MachineFrameInfo &MFI =3D *MF.getFrameInfo();
+
+  // Mark the D-register spill slots as properly aligned.  Since MFI compu=
tes
+  // stack slot layout backwards, this can actually mean that the d-reg st=
ack
+  // slot offsets can be wrong. The offset for d8 will always be correct.
+  for (unsigned i =3D 0, e =3D CSI.size(); i !=3D e; ++i) {
+    unsigned DNum =3D CSI[i].getReg() - ARM::D8;
+    if (DNum >=3D 8)
+      continue;
+    int FI =3D CSI[i].getFrameIdx();
+    // The even-numbered registers will be 16-byte aligned, the odd-number=
ed
+    // registers will be 8-byte aligned.
+    MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
+
+    // The stack slot for D8 needs to be maximally aligned because this is
+    // actually the point where we align the stack pointer.  MachineFrameI=
nfo
+    // computes all offsets relative to the incoming stack pointer which i=
s a
+    // bit weird when realigning the stack.  Any extra padding for this
+    // over-alignment is not realized because the code inserted below adju=
sts
+    // the stack pointer by numregs * 8 before aligning the stack pointer.
+    if (DNum =3D=3D 0)
+      MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
+  }
+
+  // Move the stack pointer to the d8 spill slot, and align it at the same
+  // time. Leave the stack slot address in the scratch register r4.
+  //
+  //   sub r4, sp, #numregs * 8
+  //   bic r4, r4, #align - 1
+  //   mov sp, r4
+  //
+  bool isThumb =3D AFI->isThumbFunction();
+  assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
+  AFI->setShouldRestoreSPFromFP(true);
+
+  // sub r4, sp, #numregs * 8
+  // The immediate is <=3D 64, so it doesn't need any special encoding.
+  unsigned Opc =3D isThumb ? ARM::t2SUBri : ARM::SUBri;
+  AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
+                              .addReg(ARM::SP)
+                              .addImm(8 * NumAlignedDPRCS2Regs)));
+
+  // bic r4, r4, #align-1
+  Opc =3D isThumb ? ARM::t2BICri : ARM::BICri;
+  unsigned MaxAlign =3D MF.getFrameInfo()->getMaxAlignment();
+  AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
+                              .addReg(ARM::R4, RegState::Kill)
+                              .addImm(MaxAlign - 1)));
+
+  // mov sp, r4
+  // The stack pointer must be adjusted before spilling anything, otherwise
+  // the stack slots could be clobbered by an interrupt handler.
+  // Leave r4 live, it is used below.
+  Opc =3D isThumb ? ARM::tMOVr : ARM::MOVr;
+  MachineInstrBuilder MIB =3D BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
+                            .addReg(ARM::R4);
+  MIB =3D AddDefaultPred(MIB);
+  if (!isThumb)
+    AddDefaultCC(MIB);
+
+  // Now spill NumAlignedDPRCS2Regs registers starting from d8.
+  // r4 holds the stack slot address.
+  unsigned NextReg =3D ARM::D8;
+
+  // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
+  // The writeback is only needed when emitting two vst1.64 instructions.
+  if (NumAlignedDPRCS2Regs >=3D 6) {
+    unsigned SupReg =3D TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
+                                               ARM::QQPRRegisterClass);
+    MBB.addLiveIn(SupReg);
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
+                           ARM::R4)
+                   .addReg(ARM::R4, RegState::Kill).addImm(16)
+                   .addReg(NextReg)
+                   .addReg(SupReg, RegState::ImplicitKill));
+    NextReg +=3D 4;
+    NumAlignedDPRCS2Regs -=3D 4;
+  }
+
+  // We won't modify r4 beyond this point.  It currently points to the next
+  // register to be spilled.
+  unsigned R4BaseReg =3D NextReg;
+
+  // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
+  if (NumAlignedDPRCS2Regs >=3D 4) {
+    unsigned SupReg =3D TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
+                                               ARM::QQPRRegisterClass);
+    MBB.addLiveIn(SupReg);
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
+                   .addReg(ARM::R4).addImm(16).addReg(NextReg)
+                   .addReg(SupReg, RegState::ImplicitKill));
+    NextReg +=3D 4;
+    NumAlignedDPRCS2Regs -=3D 4;
+  }
+
+  // 16-byte aligned vst1.64 with 2 d-regs.
+  if (NumAlignedDPRCS2Regs >=3D 2) {
+    unsigned SupReg =3D TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
+                                               ARM::QPRRegisterClass);
+    MBB.addLiveIn(SupReg);
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
+                   .addReg(ARM::R4).addImm(16).addReg(SupReg));
+    NextReg +=3D 2;
+    NumAlignedDPRCS2Regs -=3D 2;
+  }
+
+  // Finally, use a vanilla vstr.64 for the odd last register.
+  if (NumAlignedDPRCS2Regs) {
+    MBB.addLiveIn(NextReg);
+    // vstr.64 uses addrmode5 which has an offset scale of 4.
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
+                   .addReg(NextReg)
+                   .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
+  }
+
+  // The last spill instruction inserted should kill the scratch register =
r4.
+  llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
+}
+
+/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
+/// iterator to the following instruction.
+static MachineBasicBlock::iterator
+skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
+                        unsigned NumAlignedDPRCS2Regs) {
+  //   sub r4, sp, #numregs * 8
+  //   bic r4, r4, #align - 1
+  //   mov sp, r4
+  ++MI; ++MI; ++MI;
+  assert(MI->mayStore() && "Expecting spill instruction");
+
+  // These switches all fall through.
+  switch(NumAlignedDPRCS2Regs) {
+  case 7:
+    ++MI;
+    assert(MI->mayStore() && "Expecting spill instruction");
+  default:
+    ++MI;
+    assert(MI->mayStore() && "Expecting spill instruction");
+  case 1:
+  case 2:
+  case 4:
+    assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
+    ++MI;
+  }
+  return MI;
+}
+
+/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
+/// starting from d8.  These instructions are assumed to execute while the
+/// stack is still aligned, unlike the code inserted by emitPopInst.
+static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
+                                      MachineBasicBlock::iterator MI,
+                                      unsigned NumAlignedDPRCS2Regs,
+                                      const std::vector<CalleeSavedInfo> &=
CSI,
+                                      const TargetRegisterInfo *TRI) {
+  MachineFunction &MF =3D *MBB.getParent();
+  ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
+  DebugLoc DL =3D MI->getDebugLoc();
+  const TargetInstrInfo &TII =3D *MF.getTarget().getInstrInfo();
+
+  // Find the frame index assigned to d8.
+  int D8SpillFI =3D 0;
+  for (unsigned i =3D 0, e =3D CSI.size(); i !=3D e; ++i)
+    if (CSI[i].getReg() =3D=3D ARM::D8) {
+      D8SpillFI =3D CSI[i].getFrameIdx();
+      break;
+    }
+
+  // Materialize the address of the d8 spill slot into the scratch registe=
r r4.
+  // This can be fairly complicated if the stack frame is large, so just u=
se
+  // the normal frame index elimination mechanism to do it.  This code run=
s as
+  // the initial part of the epilog where the stack and base pointers have=
n't
+  // been changed yet.
+  bool isThumb =3D AFI->isThumbFunction();
+  assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
+
+  unsigned Opc =3D isThumb ? ARM::t2ADDri : ARM::ADDri;
+  AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
+                              .addFrameIndex(D8SpillFI).addImm(0)));
+
+  // Now restore NumAlignedDPRCS2Regs registers starting from d8.
+  unsigned NextReg =3D ARM::D8;
+
+  // 16-byte aligned vld1.64 with 4 d-regs and writeback.
+  if (NumAlignedDPRCS2Regs >=3D 6) {
+    unsigned SupReg =3D TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
+                                               ARM::QQPRRegisterClass);
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), Ne=
xtReg)
+                   .addReg(ARM::R4, RegState::Define)
+                   .addReg(ARM::R4, RegState::Kill).addImm(16)
+                   .addReg(SupReg, RegState::ImplicitDefine));
+    NextReg +=3D 4;
+    NumAlignedDPRCS2Regs -=3D 4;
+  }
+
+  // We won't modify r4 beyond this point.  It currently points to the next
+  // register to be spilled.
+  unsigned R4BaseReg =3D NextReg;
+
+  // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
+  if (NumAlignedDPRCS2Regs >=3D 4) {
+    unsigned SupReg =3D TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
+                                               ARM::QQPRRegisterClass);
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
+                   .addReg(ARM::R4).addImm(16)
+                   .addReg(SupReg, RegState::ImplicitDefine));
+    NextReg +=3D 4;
+    NumAlignedDPRCS2Regs -=3D 4;
+  }
+
+  // 16-byte aligned vld1.64 with 2 d-regs.
+  if (NumAlignedDPRCS2Regs >=3D 2) {
+    unsigned SupReg =3D TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
+                                               ARM::QPRRegisterClass);
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
+                   .addReg(ARM::R4).addImm(16));
+    NextReg +=3D 2;
+    NumAlignedDPRCS2Regs -=3D 2;
+  }
+
+  // Finally, use a vanilla vldr.64 for the remaining odd register.
+  if (NumAlignedDPRCS2Regs)
+    AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
+                   .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
+
+  // Last store kills r4.
+  llvm::prior(MI)->addRegisterKilled(ARM::R4, TRI);
+}
+
 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
                                         MachineBasicBlock::iterator MI,
                                         const std::vector<CalleeSavedInfo>=
 &CSI,
@@ -700,12 +965,19 @@
   unsigned PushOneOpc =3D AFI->isThumbFunction() ?
     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
   unsigned FltOpc =3D ARM::VSTMDDB_UPD;
-  emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Regist=
er,
+  unsigned NumAlignedDPRCS2Regs =3D AFI->getNumAlignedDPRCS2Regs();
+  emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Regist=
er, 0,
                MachineInstr::FrameSetup);
-  emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Regist=
er,
+  emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Regist=
er, 0,
                MachineInstr::FrameSetup);
   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
-               MachineInstr::FrameSetup);
+               NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
+
+  // The code above does not insert spill code for the aligned DPRCS2 regi=
sters.
+  // The stack realignment code will be inserted between the push instruct=
ions
+  // and these spills.
+  if (NumAlignedDPRCS2Regs)
+    emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
=20
   return true;
 }
@@ -720,15 +992,22 @@
   MachineFunction &MF =3D *MBB.getParent();
   ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
   bool isVarArg =3D AFI->getVarArgsRegSaveSize() > 0;
+  unsigned NumAlignedDPRCS2Regs =3D AFI->getNumAlignedDPRCS2Regs();
+
+  // The emitPopInst calls below do not insert reloads for the aligned DPR=
CS2
+  // registers. Do that here instead.
+  if (NumAlignedDPRCS2Regs)
+    emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
=20
   unsigned PopOpc =3D AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDM=
IA_UPD;
   unsigned LdrOpc =3D AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_P=
OST_IMM;
   unsigned FltOpc =3D ARM::VLDMDIA_UPD;
-  emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register=
);
+  emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
+              NumAlignedDPRCS2Regs);
   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
-              &isARMArea2Register);
+              &isARMArea2Register, 0);
   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
-              &isARMArea1Register);
+              &isARMArea1Register, 0);
=20
   return true;
 }
@@ -852,6 +1131,55 @@
   return Limit;
 }
=20
+// In functions that realign the stack, it can be an advantage to spill the
+// callee-saved vector registers after realigning the stack. The vst1 and =
vld1
+// instructions take alignment hints that can improve performance.
+//
+static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
+  MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
+  if (!SpillAlignedNEONRegs)
+    return;
+
+  // Naked functions don't spill callee-saved registers.
+  if (MF.getFunction()->hasFnAttr(Attribute::Naked))
+    return;
+
+  // We are planning to use NEON instructions vst1 / vld1.
+  if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
+    return;
+
+  // Don't bother if the default stack alignment is sufficiently high.
+  if (MF.getTarget().getFrameLowering()->getStackAlignment() >=3D 8)
+    return;
+
+  // Aligned spills require stack realignment.
+  const ARMBaseRegisterInfo *RegInfo =3D
+    static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo=
());
+  if (!RegInfo->canRealignStack(MF))
+    return;
+
+  // We always spill contiguous d-registers starting from d8. Count how ma=
ny
+  // needs spilling.  The register allocator will almost always use the
+  // callee-saved registers in order, but it can happen that there are hol=
es in
+  // the range.  Registers above the hole will be spilled to the standard =
DPRCS
+  // area.
+  MachineRegisterInfo &MRI =3D MF.getRegInfo();
+  unsigned NumSpills =3D 0;
+  for (; NumSpills < 8; ++NumSpills)
+    if (!MRI.isPhysRegOrOverlapUsed(ARM::D8 + NumSpills))
+      break;
+
+  // Don't do this for just one d-register. It's not worth it.
+  if (NumSpills < 2)
+    return;
+
+  // Spill the first NumSpills D-registers after realigning the stack.
+  MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
+
+  // A scratch register is required for the vst1 / vld1 instructions.
+  MF.getRegInfo().setPhysRegUsed(ARM::R4);
+}
+
 void
 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
                                                        RegScavenger *RS) c=
onst {
@@ -898,28 +1226,22 @@
       MF.getRegInfo().setPhysRegUsed(ARM::R4);
   }
=20
+  // See if we can spill vector registers to aligned stack.
+  checkNumAlignedDPRCS2Regs(MF);
+
   // Spill the BasePtr if it's used.
   if (RegInfo->hasBasePointer(MF))
     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
=20
   // Don't spill FP if the frame can be eliminated. This is determined
   // by scanning the callee-save registers to see if any is used.
-  const unsigned *CSRegs =3D RegInfo->getCalleeSavedRegs();
+  const uint16_t *CSRegs =3D RegInfo->getCalleeSavedRegs();
   for (unsigned i =3D 0; CSRegs[i]; ++i) {
     unsigned Reg =3D CSRegs[i];
     bool Spilled =3D false;
-    if (MF.getRegInfo().isPhysRegUsed(Reg)) {
+    if (MF.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
       Spilled =3D true;
       CanEliminateFrame =3D false;
-    } else {
-      // Check alias registers too.
-      for (const unsigned *Aliases =3D
-             RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) {
-        if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
-          Spilled =3D true;
-          CanEliminateFrame =3D false;
-        }
-      }
     }
=20
     if (!ARM::GPRRegisterClass->contains(Reg))
@@ -928,7 +1250,7 @@
     if (Spilled) {
       NumGPRSpills++;
=20
-      if (!STI.isTargetDarwin()) {
+      if (!STI.isTargetIOS()) {
         if (Reg =3D=3D ARM::LR)
           LRSpilled =3D true;
         CS1Spilled =3D true;
@@ -948,7 +1270,7 @@
         break;
       }
     } else {
-      if (!STI.isTargetDarwin()) {
+      if (!STI.isTargetIOS()) {
         UnspilledCS1GPRs.push_back(Reg);
         continue;
       }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMFr=
ameLowering.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMFrameLowering.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMFrameLowering.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -63,12 +63,13 @@
   void emitPushInst(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
                     const std::vector<CalleeSavedInfo> &CSI, unsigned StmO=
pc,
                     unsigned StrOpc, bool NoGap,
-                    bool(*Func)(unsigned, bool),
+                    bool(*Func)(unsigned, bool), unsigned NumAlignedDPRCS2=
Regs,
                     unsigned MIFlags =3D 0) const;
   void emitPopInst(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
                    const std::vector<CalleeSavedInfo> &CSI, unsigned LdmOp=
c,
                    unsigned LdrOpc, bool isVarArg, bool NoGap,
-                   bool(*Func)(unsigned, bool)) const;
+                   bool(*Func)(unsigned, bool),
+                   unsigned NumAlignedDPRCS2Regs) const;
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMHa=
zardRecognizer.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMHazardRecognizer.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMHazardRecognizer.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -21,7 +21,7 @@
   // FIXME: Detect integer instructions properly.
   const MCInstrDesc &MCID =3D MI->getDesc();
   unsigned Domain =3D MCID.TSFlags & ARMII::DomainMask;
-  if (MCID.mayStore())
+  if (MI->mayStore())
     return false;
   unsigned Opcode =3D MCID.getOpcode();
   if (Opcode =3D=3D ARM::VMOVRS || Opcode =3D=3D ARM::VMOVRRD)
@@ -38,9 +38,6 @@
   MachineInstr *MI =3D SU->getInstr();
=20
   if (!MI->isDebugValue()) {
-    if (ITBlockSize && MI !=3D ITBlockMIs[ITBlockSize-1])
-      return Hazard;
-
     // Look for special VMLA / VMLS hazards. A VMUL / VADD / VSUB following
     // a VMLA / VMLS will cause 4 cycle stall.
     const MCInstrDesc &MCID =3D MI->getDesc();
@@ -48,9 +45,9 @@
       MachineInstr *DefMI =3D LastMI;
       const MCInstrDesc &LastMCID =3D LastMI->getDesc();
       // Skip over one non-VFP / NEON instruction.
-      if (!LastMCID.isBarrier() &&
+      if (!LastMI->isBarrier() &&
           // On A9, AGU and NEON/FPU are muxed.
-          !(STI.isCortexA9() && (LastMCID.mayLoad() || LastMCID.mayStore()=
)) &&
+          !(STI.isCortexA9() && (LastMI->mayLoad() || LastMI->mayStore()))=
 &&
           (LastMCID.TSFlags & ARMII::DomainMask) =3D=3D ARMII::DomainGener=
al) {
         MachineBasicBlock::iterator I =3D LastMI;
         if (I !=3D LastMI->getParent()->begin()) {
@@ -76,30 +73,11 @@
 void ARMHazardRecognizer::Reset() {
   LastMI =3D 0;
   FpMLxStalls =3D 0;
-  ITBlockSize =3D 0;
   ScoreboardHazardRecognizer::Reset();
 }
=20
 void ARMHazardRecognizer::EmitInstruction(SUnit *SU) {
   MachineInstr *MI =3D SU->getInstr();
-  unsigned Opcode =3D MI->getOpcode();
-  if (ITBlockSize) {
-    --ITBlockSize;
-  } else if (Opcode =3D=3D ARM::t2IT) {
-    unsigned Mask =3D MI->getOperand(1).getImm();
-    unsigned NumTZ =3D CountTrailingZeros_32(Mask);
-    assert(NumTZ <=3D 3 && "Invalid IT mask!");
-    ITBlockSize =3D 4 - NumTZ;
-    MachineBasicBlock::iterator I =3D MI;
-    for (unsigned i =3D 0; i < ITBlockSize; ++i) {
-      // Advance to the next instruction, skipping any dbg_value instructi=
ons.
-      do {
-        ++I;
-      } while (I->isDebugValue());
-      ITBlockMIs[ITBlockSize-1-i] =3D &*I;
-    }
-  }
-
   if (!MI->isDebugValue()) {
     LastMI =3D MI;
     FpMLxStalls =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMHa=
zardRecognizer.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMHazardRecognizer.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMHazardRecognizer.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -23,6 +23,10 @@
 class ARMSubtarget;
 class MachineInstr;
=20
+/// ARMHazardRecognizer handles special constraints that are not expressed=
 in
+/// the scheduling itinerary. This is only used during postRA scheduling. =
The
+/// ARM preRA scheduler uses an unspecialized instance of the
+/// ScoreboardHazardRecognizer.
 class ARMHazardRecognizer : public ScoreboardHazardRecognizer {
   const ARMBaseInstrInfo &TII;
   const ARMBaseRegisterInfo &TRI;
@@ -30,8 +34,6 @@
=20
   MachineInstr *LastMI;
   unsigned FpMLxStalls;
-  unsigned ITBlockSize;  // No. of MIs in current IT block yet to be sched=
uled.
-  MachineInstr *ITBlockMIs[4];
=20
 public:
   ARMHazardRecognizer(const InstrItineraryData *ItinData,
@@ -40,7 +42,7 @@
                       const ARMSubtarget &sti,
                       const ScheduleDAG *DAG) :
     ScoreboardHazardRecognizer(ItinData, DAG, "post-RA-sched"), TII(tii),
-    TRI(tri), STI(sti), LastMI(0), ITBlockSize(0) {}
+    TRI(tri), STI(sti), LastMI(0) {}
=20
   virtual HazardType getHazardType(SUnit *SU, int Stalls);
   virtual void Reset();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIS=
elDAGToDAG.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -244,6 +244,7 @@
=20
   /// SelectCMOVOp - Select CMOV instructions for ARM.
   SDNode *SelectCMOVOp(SDNode *N);
+  SDNode *SelectConditionalOp(SDNode *N);
   SDNode *SelectT2CMOVShiftOp(SDNode *N, SDValue FalseVal, SDValue TrueVal,
                               ARMCC::CondCodes CCVal, SDValue CCR,
                               SDValue InFlag);
@@ -923,7 +924,7 @@
     // The maximum alignment is equal to the memory size being referenced.
     unsigned LSNAlign =3D LSN->getAlignment();
     unsigned MemSize =3D LSN->getMemoryVT().getSizeInBits() / 8;
-    if (LSNAlign > MemSize && MemSize > 1)
+    if (LSNAlign >=3D MemSize && MemSize > 1)
       Alignment =3D MemSize;
   } else {
     // All other uses of addrmode6 are for intrinsics.  For now just record
@@ -1549,6 +1550,52 @@
   return CurDAG->getTargetConstant(Alignment, MVT::i32);
 }
=20
+// Get the register stride update opcode of a VLD/VST instruction that
+// is otherwise equivalent to the given fixed stride updating instruction.
+static unsigned getVLDSTRegisterUpdateOpcode(unsigned Opc) {
+  switch (Opc) {
+  default: break;
+  case ARM::VLD1d8wb_fixed: return ARM::VLD1d8wb_register;
+  case ARM::VLD1d16wb_fixed: return ARM::VLD1d16wb_register;
+  case ARM::VLD1d32wb_fixed: return ARM::VLD1d32wb_register;
+  case ARM::VLD1d64wb_fixed: return ARM::VLD1d64wb_register;
+  case ARM::VLD1q8wb_fixed: return ARM::VLD1q8wb_register;
+  case ARM::VLD1q16wb_fixed: return ARM::VLD1q16wb_register;
+  case ARM::VLD1q32wb_fixed: return ARM::VLD1q32wb_register;
+  case ARM::VLD1q64wb_fixed: return ARM::VLD1q64wb_register;
+
+  case ARM::VST1d8wb_fixed: return ARM::VST1d8wb_register;
+  case ARM::VST1d16wb_fixed: return ARM::VST1d16wb_register;
+  case ARM::VST1d32wb_fixed: return ARM::VST1d32wb_register;
+  case ARM::VST1d64wb_fixed: return ARM::VST1d64wb_register;
+  case ARM::VST1q8wb_fixed: return ARM::VST1q8wb_register;
+  case ARM::VST1q16wb_fixed: return ARM::VST1q16wb_register;
+  case ARM::VST1q32wb_fixed: return ARM::VST1q32wb_register;
+  case ARM::VST1q64wb_fixed: return ARM::VST1q64wb_register;
+  case ARM::VST1d64TPseudoWB_fixed: return ARM::VST1d64TPseudoWB_register;
+  case ARM::VST1d64QPseudoWB_fixed: return ARM::VST1d64QPseudoWB_register;
+
+  case ARM::VLD2d8wb_fixed: return ARM::VLD2d8wb_register;
+  case ARM::VLD2d16wb_fixed: return ARM::VLD2d16wb_register;
+  case ARM::VLD2d32wb_fixed: return ARM::VLD2d32wb_register;
+  case ARM::VLD2q8PseudoWB_fixed: return ARM::VLD2q8PseudoWB_register;
+  case ARM::VLD2q16PseudoWB_fixed: return ARM::VLD2q16PseudoWB_register;
+  case ARM::VLD2q32PseudoWB_fixed: return ARM::VLD2q32PseudoWB_register;
+
+  case ARM::VST2d8wb_fixed: return ARM::VST2d8wb_register;
+  case ARM::VST2d16wb_fixed: return ARM::VST2d16wb_register;
+  case ARM::VST2d32wb_fixed: return ARM::VST2d32wb_register;
+  case ARM::VST2q8PseudoWB_fixed: return ARM::VST2q8PseudoWB_register;
+  case ARM::VST2q16PseudoWB_fixed: return ARM::VST2q16PseudoWB_register;
+  case ARM::VST2q32PseudoWB_fixed: return ARM::VST2q32PseudoWB_register;
+
+  case ARM::VLD2DUPd8wb_fixed: return ARM::VLD2DUPd8wb_register;
+  case ARM::VLD2DUPd16wb_fixed: return ARM::VLD2DUPd16wb_register;
+  case ARM::VLD2DUPd32wb_fixed: return ARM::VLD2DUPd32wb_register;
+  }
+  return Opc; // If not one we handle, return it unchanged.
+}
+
 SDNode *ARMDAGToDAGISel::SelectVLD(SDNode *N, bool isUpdating, unsigned Nu=
mVecs,
                                    unsigned *DOpcodes, unsigned *QOpcodes0,
                                    unsigned *QOpcodes1) {
@@ -1612,7 +1659,15 @@
     Ops.push_back(Align);
     if (isUpdating) {
       SDValue Inc =3D N->getOperand(AddrOpIdx + 1);
-      Ops.push_back(isa<ConstantSDNode>(Inc.getNode()) ? Reg0 : Inc);
+      // FIXME: VLD1/VLD2 fixed increment doesn't need Reg0. Remove the re=
g0
+      // case entirely when the rest are updated to that form, too.
+      if ((NumVecs =3D=3D 1 || NumVecs =3D=3D 2) && !isa<ConstantSDNode>(I=
nc.getNode()))
+        Opc =3D getVLDSTRegisterUpdateOpcode(Opc);
+      // We use a VLD1 for v1i64 even if the pseudo says vld2/3/4, so
+      // check for that explicitly too. Horribly hacky, but temporary.
+      if ((NumVecs !=3D 1 && NumVecs !=3D 2 && Opc !=3D ARM::VLD1q64wb_fix=
ed) ||
+          !isa<ConstantSDNode>(Inc.getNode()))
+        Ops.push_back(isa<ConstantSDNode>(Inc.getNode()) ? Reg0 : Inc);
     }
     Ops.push_back(Pred);
     Ops.push_back(Reg0);
@@ -1754,7 +1809,15 @@
     Ops.push_back(Align);
     if (isUpdating) {
       SDValue Inc =3D N->getOperand(AddrOpIdx + 1);
-      Ops.push_back(isa<ConstantSDNode>(Inc.getNode()) ? Reg0 : Inc);
+      // FIXME: VST1/VST2 fixed increment doesn't need Reg0. Remove the re=
g0
+      // case entirely when the rest are updated to that form, too.
+      if (NumVecs <=3D 2 && !isa<ConstantSDNode>(Inc.getNode()))
+        Opc =3D getVLDSTRegisterUpdateOpcode(Opc);
+      // We use a VST1 for v1i64 even if the pseudo says vld2/3/4, so
+      // check for that explicitly too. Horribly hacky, but temporary.
+      if ((NumVecs > 2 && Opc !=3D ARM::VST1q64wb_fixed) ||
+          !isa<ConstantSDNode>(Inc.getNode()))
+        Ops.push_back(isa<ConstantSDNode>(Inc.getNode()) ? Reg0 : Inc);
     }
     Ops.push_back(SrcReg);
     Ops.push_back(Pred);
@@ -1977,8 +2040,14 @@
   Ops.push_back(MemAddr);
   Ops.push_back(Align);
   if (isUpdating) {
+    // fixed-stride update instructions don't have an explicit writeback
+    // operand. It's implicit in the opcode itself.
     SDValue Inc =3D N->getOperand(2);
-    Ops.push_back(isa<ConstantSDNode>(Inc.getNode()) ? Reg0 : Inc);
+    if (!isa<ConstantSDNode>(Inc.getNode()))
+      Ops.push_back(Inc);
+    // FIXME: VLD3 and VLD4 haven't been updated to that form yet.
+    else if (NumVecs > 2)
+      Ops.push_back(Reg0);
   }
   Ops.push_back(Pred);
   Ops.push_back(Reg0);
@@ -2116,7 +2185,6 @@
     case ARM_AM::ror: Opc =3D ARM::t2MOVCCror; break;
     default:
       llvm_unreachable("Unknown so_reg opcode!");
-      break;
     }
     SDValue SOShImm =3D
       CurDAG->getTargetConstant(ARM_AM::getSORegOffset(SOVal), MVT::i32);
@@ -2227,9 +2295,6 @@
     // Pattern: (ARMcmov:i32 GPR:i32:$false, so_reg:i32:$true, (imm:i32):$=
cc)
     // Emits: (MOVCCs:i32 GPR:i32:$false, so_reg:i32:$true, (imm:i32):$cc)
     // Pattern complexity =3D 18  cost =3D 1  size =3D 0
-    SDValue CPTmp0;
-    SDValue CPTmp1;
-    SDValue CPTmp2;
     if (Subtarget->isThumb()) {
       SDNode *Res =3D SelectT2CMOVShiftOp(N, FalseVal, TrueVal,
                                         CCVal, CCR, InFlag);
@@ -2286,8 +2351,7 @@
   SDValue Ops[] =3D { FalseVal, TrueVal, Tmp2, CCR, InFlag };
   unsigned Opc =3D 0;
   switch (VT.getSimpleVT().SimpleTy) {
-  default: assert(false && "Illegal conditional move type!");
-    break;
+  default: llvm_unreachable("Illegal conditional move type!");
   case MVT::i32:
     Opc =3D Subtarget->isThumb()
       ? (Subtarget->hasThumb2() ? ARM::t2MOVCCr : ARM::tMOVCCr_pseudo)
@@ -2303,6 +2367,115 @@
   return CurDAG->SelectNodeTo(N, Opc, VT, Ops, 5);
 }
=20
+SDNode *ARMDAGToDAGISel::SelectConditionalOp(SDNode *N) {
+  SDValue FalseVal =3D N->getOperand(0);
+  SDValue TrueVal  =3D N->getOperand(1);
+  ARMCC::CondCodes CCVal =3D
+    (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue=
();
+  SDValue CCR =3D N->getOperand(3);
+  assert(CCR.getOpcode() =3D=3D ISD::Register);
+  SDValue InFlag =3D N->getOperand(4);
+  SDValue CC =3D CurDAG->getTargetConstant(CCVal, MVT::i32);
+  SDValue Reg0 =3D CurDAG->getRegister(0, MVT::i32);
+
+  if (Subtarget->isThumb()) {
+    SDValue CPTmp0;
+    SDValue CPTmp1;
+    if (SelectT2ShifterOperandReg(TrueVal, CPTmp0, CPTmp1)) {
+      unsigned Opc;
+      switch (N->getOpcode()) {
+      default: llvm_unreachable("Unexpected node");
+      case ARMISD::CAND: Opc =3D ARM::t2ANDCCrs; break;
+      case ARMISD::COR:  Opc =3D ARM::t2ORRCCrs; break;
+      case ARMISD::CXOR: Opc =3D ARM::t2EORCCrs; break;
+      }
+      SDValue Ops[] =3D { FalseVal, CPTmp0, CPTmp1, CC, CCR, Reg0, InFlag =
};
+      return CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops, 7);
+    }
+
+    ConstantSDNode *T =3D dyn_cast<ConstantSDNode>(TrueVal);
+    if (T) {
+      unsigned TrueImm =3D T->getZExtValue();
+      if (is_t2_so_imm(TrueImm)) {
+        unsigned Opc;
+        switch (N->getOpcode()) {
+        default: llvm_unreachable("Unexpected node");
+        case ARMISD::CAND: Opc =3D ARM::t2ANDCCri; break;
+        case ARMISD::COR:  Opc =3D ARM::t2ORRCCri; break;
+        case ARMISD::CXOR: Opc =3D ARM::t2EORCCri; break;
+        }
+        SDValue True =3D CurDAG->getTargetConstant(TrueImm, MVT::i32);
+        SDValue Ops[] =3D { FalseVal, True, CC, CCR, Reg0, InFlag };
+        return CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops, 6);
+      }
+    }
+
+    unsigned Opc;
+    switch (N->getOpcode()) {
+    default: llvm_unreachable("Unexpected node");
+    case ARMISD::CAND: Opc =3D ARM::t2ANDCCrr; break;
+    case ARMISD::COR:  Opc =3D ARM::t2ORRCCrr; break;
+    case ARMISD::CXOR: Opc =3D ARM::t2EORCCrr; break;
+    }
+    SDValue Ops[] =3D { FalseVal, TrueVal, CC, CCR, Reg0, InFlag };
+    return CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops, 6);
+  }
+
+  SDValue CPTmp0;
+  SDValue CPTmp1;
+  SDValue CPTmp2;
+  if (SelectImmShifterOperand(TrueVal, CPTmp0, CPTmp2)) {
+    unsigned Opc;
+    switch (N->getOpcode()) {
+    default: llvm_unreachable("Unexpected node");
+    case ARMISD::CAND: Opc =3D ARM::ANDCCrsi; break;
+    case ARMISD::COR:  Opc =3D ARM::ORRCCrsi; break;
+    case ARMISD::CXOR: Opc =3D ARM::EORCCrsi; break;
+    }
+    SDValue Ops[] =3D { FalseVal, CPTmp0, CPTmp2, CC, CCR, Reg0, InFlag };
+    return CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops, 7);
+  }
+
+  if (SelectRegShifterOperand(TrueVal, CPTmp0, CPTmp1, CPTmp2)) {
+    unsigned Opc;
+    switch (N->getOpcode()) {
+    default: llvm_unreachable("Unexpected node");
+    case ARMISD::CAND: Opc =3D ARM::ANDCCrsr; break;
+    case ARMISD::COR:  Opc =3D ARM::ORRCCrsr; break;
+    case ARMISD::CXOR: Opc =3D ARM::EORCCrsr; break;
+    }
+    SDValue Ops[] =3D { FalseVal, CPTmp0, CPTmp1, CPTmp2, CC, CCR, Reg0, I=
nFlag };
+    return CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops, 8);
+  }
+
+  ConstantSDNode *T =3D dyn_cast<ConstantSDNode>(TrueVal);
+  if (T) {
+    unsigned TrueImm =3D T->getZExtValue();
+    if (is_so_imm(TrueImm)) {
+      unsigned Opc;
+      switch (N->getOpcode()) {
+      default: llvm_unreachable("Unexpected node");
+      case ARMISD::CAND: Opc =3D ARM::ANDCCri; break;
+      case ARMISD::COR:  Opc =3D ARM::ORRCCri; break;
+      case ARMISD::CXOR: Opc =3D ARM::EORCCri; break;
+      }
+      SDValue True =3D CurDAG->getTargetConstant(TrueImm, MVT::i32);
+      SDValue Ops[] =3D { FalseVal, True, CC, CCR, Reg0, InFlag };
+      return CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops, 6);
+    }
+  }
+
+  unsigned Opc;
+  switch (N->getOpcode()) {
+  default: llvm_unreachable("Unexpected node");
+  case ARMISD::CAND: Opc =3D ARM::ANDCCrr; break;
+  case ARMISD::COR:  Opc =3D ARM::ORRCCrr; break;
+  case ARMISD::CXOR: Opc =3D ARM::EORCCrr; break;
+  }
+  SDValue Ops[] =3D { FalseVal, TrueVal, CC, CCR, Reg0, InFlag };
+  return CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops, 6);
+}
+
 /// Target-specific DAG combining for ISD::XOR.
 /// Target-independent combining lowers SELECT_CC nodes of the form
 /// select_cc setg[ge] X,  0,  X, -X
@@ -2316,7 +2489,6 @@
 SDNode *ARMDAGToDAGISel::SelectABSOp(SDNode *N){
   SDValue XORSrc0 =3D N->getOperand(0);
   SDValue XORSrc1 =3D N->getOperand(1);
-  DebugLoc DL =3D N->getDebugLoc();
   EVT VT =3D N->getValueType(0);
=20
   if (DisableARMIntABS)
@@ -2641,6 +2813,10 @@
   }
   case ARMISD::CMOV:
     return SelectCMOVOp(N);
+  case ARMISD::CAND:
+  case ARMISD::COR:
+  case ARMISD::CXOR:
+    return SelectConditionalOp(N);
   case ARMISD::VZIP: {
     unsigned Opc =3D 0;
     EVT VT =3D N->getValueType(0);
@@ -2649,7 +2825,8 @@
     case MVT::v8i8:  Opc =3D ARM::VZIPd8; break;
     case MVT::v4i16: Opc =3D ARM::VZIPd16; break;
     case MVT::v2f32:
-    case MVT::v2i32: Opc =3D ARM::VZIPd32; break;
+    // vzip.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
+    case MVT::v2i32: Opc =3D ARM::VTRNd32; break;
     case MVT::v16i8: Opc =3D ARM::VZIPq8; break;
     case MVT::v8i16: Opc =3D ARM::VZIPq16; break;
     case MVT::v4f32:
@@ -2668,7 +2845,8 @@
     case MVT::v8i8:  Opc =3D ARM::VUZPd8; break;
     case MVT::v4i16: Opc =3D ARM::VUZPd16; break;
     case MVT::v2f32:
-    case MVT::v2i32: Opc =3D ARM::VUZPd32; break;
+    // vuzp.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
+    case MVT::v2i32: Opc =3D ARM::VTRNd32; break;
     case MVT::v16i8: Opc =3D ARM::VUZPq8; break;
     case MVT::v8i16: Opc =3D ARM::VUZPq16; break;
     case MVT::v4f32:
@@ -2715,8 +2893,8 @@
   }
=20
   case ARMISD::VLD2DUP: {
-    unsigned Opcodes[] =3D { ARM::VLD2DUPd8Pseudo, ARM::VLD2DUPd16Pseudo,
-                           ARM::VLD2DUPd32Pseudo };
+    unsigned Opcodes[] =3D { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
+                           ARM::VLD2DUPd32 };
     return SelectVLDDup(N, false, 2, Opcodes);
   }
=20
@@ -2733,8 +2911,8 @@
   }
=20
   case ARMISD::VLD2DUP_UPD: {
-    unsigned Opcodes[] =3D { ARM::VLD2DUPd8Pseudo_UPD, ARM::VLD2DUPd16Pseu=
do_UPD,
-                           ARM::VLD2DUPd32Pseudo_UPD };
+    unsigned Opcodes[] =3D { ARM::VLD2DUPd8wb_fixed, ARM::VLD2DUPd16wb_fix=
ed,
+                           ARM::VLD2DUPd32wb_fixed };
     return SelectVLDDup(N, true, 2, Opcodes);
   }
=20
@@ -2751,24 +2929,29 @@
   }
=20
   case ARMISD::VLD1_UPD: {
-    unsigned DOpcodes[] =3D { ARM::VLD1d8_UPD, ARM::VLD1d16_UPD,
-                            ARM::VLD1d32_UPD, ARM::VLD1d64_UPD };
-    unsigned QOpcodes[] =3D { ARM::VLD1q8Pseudo_UPD, ARM::VLD1q16Pseudo_UP=
D,
-                            ARM::VLD1q32Pseudo_UPD, ARM::VLD1q64Pseudo_UPD=
 };
+    unsigned DOpcodes[] =3D { ARM::VLD1d8wb_fixed, ARM::VLD1d16wb_fixed,
+                            ARM::VLD1d32wb_fixed, ARM::VLD1d64wb_fixed };
+    unsigned QOpcodes[] =3D { ARM::VLD1q8wb_fixed,
+                            ARM::VLD1q16wb_fixed,
+                            ARM::VLD1q32wb_fixed,
+                            ARM::VLD1q64wb_fixed };
     return SelectVLD(N, true, 1, DOpcodes, QOpcodes, 0);
   }
=20
   case ARMISD::VLD2_UPD: {
-    unsigned DOpcodes[] =3D { ARM::VLD2d8Pseudo_UPD, ARM::VLD2d16Pseudo_UP=
D,
-                            ARM::VLD2d32Pseudo_UPD, ARM::VLD1q64Pseudo_UPD=
 };
-    unsigned QOpcodes[] =3D { ARM::VLD2q8Pseudo_UPD, ARM::VLD2q16Pseudo_UP=
D,
-                            ARM::VLD2q32Pseudo_UPD };
+    unsigned DOpcodes[] =3D { ARM::VLD2d8wb_fixed,
+                            ARM::VLD2d16wb_fixed,
+                            ARM::VLD2d32wb_fixed,
+                            ARM::VLD1q64wb_fixed};
+    unsigned QOpcodes[] =3D { ARM::VLD2q8PseudoWB_fixed,
+                            ARM::VLD2q16PseudoWB_fixed,
+                            ARM::VLD2q32PseudoWB_fixed };
     return SelectVLD(N, true, 2, DOpcodes, QOpcodes, 0);
   }
=20
   case ARMISD::VLD3_UPD: {
     unsigned DOpcodes[] =3D { ARM::VLD3d8Pseudo_UPD, ARM::VLD3d16Pseudo_UP=
D,
-                            ARM::VLD3d32Pseudo_UPD, ARM::VLD1d64TPseudo_UP=
D };
+                            ARM::VLD3d32Pseudo_UPD, ARM::VLD1q64wb_fixed};
     unsigned QOpcodes0[] =3D { ARM::VLD3q8Pseudo_UPD,
                              ARM::VLD3q16Pseudo_UPD,
                              ARM::VLD3q32Pseudo_UPD };
@@ -2780,7 +2963,7 @@
=20
   case ARMISD::VLD4_UPD: {
     unsigned DOpcodes[] =3D { ARM::VLD4d8Pseudo_UPD, ARM::VLD4d16Pseudo_UP=
D,
-                            ARM::VLD4d32Pseudo_UPD, ARM::VLD1d64QPseudo_UP=
D };
+                            ARM::VLD4d32Pseudo_UPD, ARM::VLD1q64wb_fixed};
     unsigned QOpcodes0[] =3D { ARM::VLD4q8Pseudo_UPD,
                              ARM::VLD4q16Pseudo_UPD,
                              ARM::VLD4q32Pseudo_UPD };
@@ -2815,24 +2998,29 @@
   }
=20
   case ARMISD::VST1_UPD: {
-    unsigned DOpcodes[] =3D { ARM::VST1d8_UPD, ARM::VST1d16_UPD,
-                            ARM::VST1d32_UPD, ARM::VST1d64_UPD };
-    unsigned QOpcodes[] =3D { ARM::VST1q8Pseudo_UPD, ARM::VST1q16Pseudo_UP=
D,
-                            ARM::VST1q32Pseudo_UPD, ARM::VST1q64Pseudo_UPD=
 };
+    unsigned DOpcodes[] =3D { ARM::VST1d8wb_fixed, ARM::VST1d16wb_fixed,
+                            ARM::VST1d32wb_fixed, ARM::VST1d64wb_fixed };
+    unsigned QOpcodes[] =3D { ARM::VST1q8wb_fixed,
+                            ARM::VST1q16wb_fixed,
+                            ARM::VST1q32wb_fixed,
+                            ARM::VST1q64wb_fixed };
     return SelectVST(N, true, 1, DOpcodes, QOpcodes, 0);
   }
=20
   case ARMISD::VST2_UPD: {
-    unsigned DOpcodes[] =3D { ARM::VST2d8Pseudo_UPD, ARM::VST2d16Pseudo_UP=
D,
-                            ARM::VST2d32Pseudo_UPD, ARM::VST1q64Pseudo_UPD=
 };
-    unsigned QOpcodes[] =3D { ARM::VST2q8Pseudo_UPD, ARM::VST2q16Pseudo_UP=
D,
-                            ARM::VST2q32Pseudo_UPD };
+    unsigned DOpcodes[] =3D { ARM::VST2d8wb_fixed,
+                            ARM::VST2d16wb_fixed,
+                            ARM::VST2d32wb_fixed,
+                            ARM::VST1q64wb_fixed};
+    unsigned QOpcodes[] =3D { ARM::VST2q8PseudoWB_fixed,
+                            ARM::VST2q16PseudoWB_fixed,
+                            ARM::VST2q32PseudoWB_fixed };
     return SelectVST(N, true, 2, DOpcodes, QOpcodes, 0);
   }
=20
   case ARMISD::VST3_UPD: {
     unsigned DOpcodes[] =3D { ARM::VST3d8Pseudo_UPD, ARM::VST3d16Pseudo_UP=
D,
-                            ARM::VST3d32Pseudo_UPD, ARM::VST1d64TPseudo_UP=
D };
+                            ARM::VST3d32Pseudo_UPD,ARM::VST1d64TPseudoWB_f=
ixed};
     unsigned QOpcodes0[] =3D { ARM::VST3q8Pseudo_UPD,
                              ARM::VST3q16Pseudo_UPD,
                              ARM::VST3q32Pseudo_UPD };
@@ -2844,7 +3032,7 @@
=20
   case ARMISD::VST4_UPD: {
     unsigned DOpcodes[] =3D { ARM::VST4d8Pseudo_UPD, ARM::VST4d16Pseudo_UP=
D,
-                            ARM::VST4d32Pseudo_UPD, ARM::VST1d64QPseudo_UP=
D };
+                            ARM::VST4d32Pseudo_UPD,ARM::VST1d64QPseudoWB_f=
ixed};
     unsigned QOpcodes0[] =3D { ARM::VST4q8Pseudo_UPD,
                              ARM::VST4q16Pseudo_UPD,
                              ARM::VST4q32Pseudo_UPD };
@@ -2993,14 +3181,14 @@
     case Intrinsic::arm_neon_vld1: {
       unsigned DOpcodes[] =3D { ARM::VLD1d8, ARM::VLD1d16,
                               ARM::VLD1d32, ARM::VLD1d64 };
-      unsigned QOpcodes[] =3D { ARM::VLD1q8Pseudo, ARM::VLD1q16Pseudo,
-                              ARM::VLD1q32Pseudo, ARM::VLD1q64Pseudo };
+      unsigned QOpcodes[] =3D { ARM::VLD1q8, ARM::VLD1q16,
+                              ARM::VLD1q32, ARM::VLD1q64};
       return SelectVLD(N, false, 1, DOpcodes, QOpcodes, 0);
     }
=20
     case Intrinsic::arm_neon_vld2: {
-      unsigned DOpcodes[] =3D { ARM::VLD2d8Pseudo, ARM::VLD2d16Pseudo,
-                              ARM::VLD2d32Pseudo, ARM::VLD1q64Pseudo };
+      unsigned DOpcodes[] =3D { ARM::VLD2d8, ARM::VLD2d16,
+                              ARM::VLD2d32, ARM::VLD1q64 };
       unsigned QOpcodes[] =3D { ARM::VLD2q8Pseudo, ARM::VLD2q16Pseudo,
                               ARM::VLD2q32Pseudo };
       return SelectVLD(N, false, 2, DOpcodes, QOpcodes, 0);
@@ -3054,14 +3242,14 @@
     case Intrinsic::arm_neon_vst1: {
       unsigned DOpcodes[] =3D { ARM::VST1d8, ARM::VST1d16,
                               ARM::VST1d32, ARM::VST1d64 };
-      unsigned QOpcodes[] =3D { ARM::VST1q8Pseudo, ARM::VST1q16Pseudo,
-                              ARM::VST1q32Pseudo, ARM::VST1q64Pseudo };
+      unsigned QOpcodes[] =3D { ARM::VST1q8, ARM::VST1q16,
+                              ARM::VST1q32, ARM::VST1q64 };
       return SelectVST(N, false, 1, DOpcodes, QOpcodes, 0);
     }
=20
     case Intrinsic::arm_neon_vst2: {
-      unsigned DOpcodes[] =3D { ARM::VST2d8Pseudo, ARM::VST2d16Pseudo,
-                              ARM::VST2d32Pseudo, ARM::VST1q64Pseudo };
+      unsigned DOpcodes[] =3D { ARM::VST2d8, ARM::VST2d16,
+                              ARM::VST2d32, ARM::VST1q64 };
       unsigned QOpcodes[] =3D { ARM::VST2q8Pseudo, ARM::VST2q16Pseudo,
                               ARM::VST2q32Pseudo };
       return SelectVST(N, false, 2, DOpcodes, QOpcodes, 0);
@@ -3122,14 +3310,14 @@
       break;
=20
     case Intrinsic::arm_neon_vtbl2:
-      return SelectVTBL(N, false, 2, ARM::VTBL2Pseudo);
+      return SelectVTBL(N, false, 2, ARM::VTBL2);
     case Intrinsic::arm_neon_vtbl3:
       return SelectVTBL(N, false, 3, ARM::VTBL3Pseudo);
     case Intrinsic::arm_neon_vtbl4:
       return SelectVTBL(N, false, 4, ARM::VTBL4Pseudo);
=20
     case Intrinsic::arm_neon_vtbx2:
-      return SelectVTBL(N, true, 2, ARM::VTBX2Pseudo);
+      return SelectVTBL(N, true, 2, ARM::VTBX2);
     case Intrinsic::arm_neon_vtbx3:
       return SelectVTBL(N, true, 3, ARM::VTBX3Pseudo);
     case Intrinsic::arm_neon_vtbx4:
@@ -3163,7 +3351,7 @@
     Ops.push_back(N->getOperand(2));
     Ops.push_back(getAL(CurDAG));                    // Predicate
     Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // Predicate Register
-    return CurDAG->getMachineNode(ARM::VTBL2Pseudo, dl, VT,
+    return CurDAG->getMachineNode(ARM::VTBL2, dl, VT,
                                   Ops.data(), Ops.size());
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIS=
elLowering.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMISelLowering.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -13,13 +13,12 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "arm-isel"
+#include "ARMISelLowering.h"
 #include "ARM.h"
 #include "ARMCallingConv.h"
 #include "ARMConstantPoolValue.h"
-#include "ARMISelLowering.h"
 #include "ARMMachineFunctionInfo.h"
 #include "ARMPerfectShuffle.h"
-#include "ARMRegisterInfo.h"
 #include "ARMSubtarget.h"
 #include "ARMTargetMachine.h"
 #include "ARMTargetObjectFile.h"
@@ -40,18 +39,15 @@
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/Target/TargetOptions.h"
-#include "llvm/ADT/VectorExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
-#include <sstream>
 using namespace llvm;
=20
 STATISTIC(NumTailCalls, "Number of tail calls");
@@ -73,7 +69,7 @@
   cl::desc("Enable / disable ARM interworking (for debugging only)"),
   cl::init(true));
=20
-namespace llvm {
+namespace {
   class ARMCCState : public CCState {
   public:
     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
@@ -89,7 +85,7 @@
 }
=20
 // The APCS parameter registers.
-static const unsigned GPRArgRegs[] =3D {
+static const uint16_t GPRArgRegs[] =3D {
   ARM::R0, ARM::R1, ARM::R2, ARM::R3
 };
=20
@@ -108,8 +104,14 @@
   EVT ElemTy =3D VT.getVectorElementType();
   if (ElemTy !=3D MVT::i64 && ElemTy !=3D MVT::f64)
     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
+  setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
-  if (ElemTy !=3D MVT::i32) {
+  if (ElemTy =3D=3D MVT::i32) {
+    setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
+    setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
+    setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
+    setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
+  } else {
     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
@@ -121,18 +123,12 @@
   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
+  setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
   if (VT.isInteger()) {
     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
-    setLoadExtAction(ISD::SEXTLOAD, VT.getSimpleVT(), Expand);
-    setLoadExtAction(ISD::ZEXTLOAD, VT.getSimpleVT(), Expand);
-    for (unsigned InnerVT =3D (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
-         InnerVT <=3D (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
-      setTruncStoreAction(VT.getSimpleVT(),
-                          (MVT::SimpleValueType)InnerVT, Expand);
-  }
-  setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
+  }
=20
   // Promote all bit-wise operations.
   if (VT.isInteger() && VT !=3D PromotedBitwiseVT) {
@@ -263,7 +259,7 @@
   setLibcallName(RTLIB::SRL_I128, 0);
   setLibcallName(RTLIB::SRA_I128, 0);
=20
-  if (Subtarget->isAAPCS_ABI()) {
+  if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
     // Double-precision floating-point arithmetic helper functions
     // RTABI chapter 4.1.2, Table 2
     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
@@ -388,8 +384,6 @@
     // Long long helper functions
     // RTABI chapter 4.2, Table 9
     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
-    setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
-    setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
@@ -405,21 +399,28 @@
     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
+    setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
+    setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
+    setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
+    setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
=20
     // Memory operations
     // RTABI chapter 4.3.4
     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
+    setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
+    setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
+    setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
   }
=20
   // Use divmod compiler-rt calls for iOS 5.0 and later.
@@ -433,7 +434,8 @@
     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
   else
     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
-  if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())=
 {
+  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
+      !Subtarget->isThumb1Only()) {
     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
     if (!Subtarget->isFPOnlySP())
       addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
@@ -441,6 +443,19 @@
     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
   }
=20
+  for (unsigned VT =3D (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
+       VT <=3D (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
+    for (unsigned InnerVT =3D (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
+         InnerVT <=3D (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
+      setTruncStoreAction((MVT::SimpleValueType)VT,
+                          (MVT::SimpleValueType)InnerVT, Expand);
+    setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
+    setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
+    setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
+  }
+
+  setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
+
   if (Subtarget->hasNEON()) {
     addDRTypeForNEON(MVT::v2f32);
     addDRTypeForNEON(MVT::v8i8);
@@ -457,13 +472,23 @@
=20
     // v2f64 is legal so that QR subregs can be extracted as f64 elements,=
 but
     // neither Neon nor VFP support any arithmetic operations on it.
+    // The same with v4f32. But keep in mind that vadd, vsub, vmul are nat=
ively
+    // supported for v4f32.
     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
+    // FIXME: Code duplication: FDIV and FREM are expanded always, see
+    // ARMTargetLowering::addTypeForNEON method for details.
     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
+    // FIXME: Create unittest.
+    // In another words, find a way when "copysign" appears in DAG with ve=
ctor
+    // operands.
     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
+    // FIXME: Code duplication: SETCC has custom operation action, see
+    // ARMTargetLowering::addTypeForNEON method for details.
     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
+    // FIXME: Create unittest for FNEG and for FABS.
     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
@@ -476,13 +501,23 @@
     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
+    // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
=20
-    setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
+    setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
+    setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
+    setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
+    setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
+    setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
+    setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
+    setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
+    setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
+    setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
+    setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
=20
     // Neon does not support some operations on v1i64 and v2i64 types.
     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
@@ -498,9 +533,13 @@
     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
-    // a destination type that is wider than the source.
+    // a destination type that is wider than the source, and nor does
+    // it have a FP_TO_[SU]INT instruction with a narrower destination than
+    // source.
     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
+    setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
+    setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
=20
     setTargetDAGCombine(ISD::INTRINSIC_VOID);
     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
@@ -519,6 +558,16 @@
     setTargetDAGCombine(ISD::FP_TO_SINT);
     setTargetDAGCombine(ISD::FP_TO_UINT);
     setTargetDAGCombine(ISD::FDIV);
+
+    // It is legal to extload from v4i8 to v4i16 or v4i32.
+    MVT Tys[6] =3D {MVT::v8i8, MVT::v4i8, MVT::v2i8,
+                  MVT::v4i16, MVT::v2i16,
+                  MVT::v2i32};
+    for (unsigned i =3D 0; i < 6; ++i) {
+      setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
+      setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
+      setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
+    }
   }
=20
   computeRegisterProperties();
@@ -576,6 +625,10 @@
   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
=20
+  // These just redirect to CTTZ and CTLZ on ARM.
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
+
   // Only ARMv6 has BSWAP.
   if (!Subtarget->hasV6Ops())
     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
@@ -606,10 +659,15 @@
   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
-  setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
-  setOperationAction(ISD::EXCEPTIONADDR,      MVT::i32,   Expand);
-  setExceptionPointerRegister(ARM::R0);
-  setExceptionSelectorRegister(ARM::R1);
+
+  if (!Subtarget->isTargetDarwin()) {
+    // Non-Darwin platforms may return values in these registers via the
+    // personality function.
+    setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
+    setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
+    setExceptionPointerRegister(ARM::R0);
+    setExceptionSelectorRegister(ARM::R1);
+  }
=20
   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
@@ -664,7 +722,8 @@
   }
   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
=20
-  if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())=
 {
+  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
+      !Subtarget->isThumb1Only()) {
     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
     // iff target supports vfp2.
     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
@@ -676,7 +735,6 @@
   if (Subtarget->isTargetDarwin()) {
     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
-    setOperationAction(ISD::EH_SJLJ_DISPATCHSETUP, MVT::Other, Custom);
     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
   }
=20
@@ -703,18 +761,21 @@
   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
   setOperationAction(ISD::FREM,      MVT::f64, Expand);
   setOperationAction(ISD::FREM,      MVT::f32, Expand);
-  if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())=
 {
+  if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
+      !Subtarget->isThumb1Only()) {
     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
   }
   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
=20
-  setOperationAction(ISD::FMA, MVT::f64, Expand);
-  setOperationAction(ISD::FMA, MVT::f32, Expand);
+  if (!Subtarget->hasVFP4()) {
+    setOperationAction(ISD::FMA, MVT::f64, Expand);
+    setOperationAction(ISD::FMA, MVT::f32, Expand);
+  }
=20
   // Various VFP goodness
-  if (!UseSoftFloat && !Subtarget->isThumb1Only()) {
+  if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
     if (Subtarget->hasVFP2()) {
       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
@@ -735,20 +796,27 @@
   setTargetDAGCombine(ISD::SUB);
   setTargetDAGCombine(ISD::MUL);
=20
-  if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON())
+  if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
+    setTargetDAGCombine(ISD::AND);
     setTargetDAGCombine(ISD::OR);
-  if (Subtarget->hasNEON())
-    setTargetDAGCombine(ISD::AND);
+    setTargetDAGCombine(ISD::XOR);
+  }
+
+  if (Subtarget->hasV6Ops())
+    setTargetDAGCombine(ISD::SRL);
=20
   setStackPointerRegisterToSaveRestore(ARM::SP);
=20
-  if (UseSoftFloat || Subtarget->isThumb1Only() || !Subtarget->hasVFP2())
+  if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
+      !Subtarget->hasVFP2())
     setSchedulingPreference(Sched::RegPressure);
   else
     setSchedulingPreference(Sched::Hybrid);
=20
   //// temporary - rewrite interface to use type
   maxStoresPerMemcpy =3D maxStoresPerMemcpyOptSize =3D 1;
+  maxStoresPerMemset =3D 16;
+  maxStoresPerMemsetOptSize =3D Subtarget->isTargetDarwin() ? 8 : 4;
=20
   // On ARM arguments smaller than 4 bytes are extended, so all arguments
   // are at least 4 bytes aligned.
@@ -828,7 +896,11 @@
   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
+
   case ARMISD::CMOV:          return "ARMISD::CMOV";
+  case ARMISD::CAND:          return "ARMISD::CAND";
+  case ARMISD::COR:           return "ARMISD::COR";
+  case ARMISD::CXOR:          return "ARMISD::CXOR";
=20
   case ARMISD::RBIT:          return "ARMISD::RBIT";
=20
@@ -851,7 +923,6 @@
=20
   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
-  case ARMISD::EH_SJLJ_DISPATCHSETUP:return "ARMISD::EH_SJLJ_DISPATCHSETUP=
";
=20
   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
=20
@@ -899,6 +970,7 @@
   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
+  case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
   case ARMISD::VDUP:          return "ARMISD::VDUP";
   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
   case ARMISD::VEXT:          return "ARMISD::VEXT";
@@ -949,7 +1021,7 @@
=20
 /// getRegClassFor - Return the register class that should be used for the
 /// specified value type.
-TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
+const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const=
 {
   // Map v4i64 to QQ registers but do not make the type legal. Similarly m=
ap
   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUEN=
CE to
   // load / store 4 to 8 consecutive D registers.
@@ -984,7 +1056,7 @@
     if (VT =3D=3D MVT::Glue || VT =3D=3D MVT::Other)
       continue;
     if (VT.isFloatingPoint() || VT.isVector())
-      return Sched::Latency;
+      return Sched::ILP;
   }
=20
   if (!N->isMachineOpcode())
@@ -999,7 +1071,7 @@
     return Sched::RegPressure;
   if (!Itins->isEmpty() &&
       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
-    return Sched::Latency;
+    return Sched::ILP;
=20
   return Sched::RegPressure;
 }
@@ -1081,18 +1153,19 @@
     if (!Subtarget->isAAPCS_ABI())
       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
     else if (Subtarget->hasVFP2() &&
-             FloatABIType =3D=3D FloatABI::Hard && !isVarArg)
+             getTargetMachine().Options.FloatABIType =3D=3D FloatABI::Hard=
 &&
+             !isVarArg)
       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
   }
   case CallingConv::ARM_AAPCS_VFP:
-    return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
+    if (!isVarArg)
+      return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
+    // Fallthrough
   case CallingConv::ARM_AAPCS:
     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
   case CallingConv::ARM_APCS:
     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
-  case CallingConv::GHC:
-    return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
   }
 }
=20
@@ -1215,7 +1288,7 @@
 SDValue
 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                              CallingConv::ID CallConv, bool isVarArg,
-                             bool &isTailCall,
+                             bool doesNotRet, bool &isTailCall,
                              const SmallVectorImpl<ISD::OutputArg> &Outs,
                              const SmallVectorImpl<SDValue> &OutVals,
                              const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -1334,7 +1407,7 @@
           SDValue AddArg =3D DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
           SDValue Load =3D DAG.getLoad(PtrVT, dl, Chain, AddArg,
                                      MachinePointerInfo(),
-                                     false, false, 0);
+                                     false, false, false, 0);
           MemOpChains.push_back(Load.getValue(1));
           RegsToPass.push_back(std::make_pair(j, Load));
         }
@@ -1350,12 +1423,10 @@
       SDValue Src =3D DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOf=
fset);
       SDValue SizeNode =3D DAG.getConstant(Flags.getByValSize() - 4*offset,
                                          MVT::i32);
-      // TODO: Disable AlwaysInline when it becomes possible
-      //       to emit a nested call sequence.
       MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
                                           Flags.getByValAlign(),
                                           /*isVolatile=3D*/false,
-                                          /*AlwaysInline=3D*/true,
+                                          /*AlwaysInline=3D*/false,
                                           MachinePointerInfo(0),
                                           MachinePointerInfo(0)));
=20
@@ -1429,7 +1500,7 @@
       Callee =3D DAG.getLoad(getPointerTy(), dl,
                            DAG.getEntryNode(), CPAddr,
                            MachinePointerInfo::getConstantPool(),
-                           false, false, 0);
+                           false, false, false, 0);
     } else if (ExternalSymbolSDNode *S=3Ddyn_cast<ExternalSymbolSDNode>(Ca=
llee)) {
       const char *Sym =3D S->getSymbol();
=20
@@ -1444,7 +1515,7 @@
       Callee =3D DAG.getLoad(getPointerTy(), dl,
                            DAG.getEntryNode(), CPAddr,
                            MachinePointerInfo::getConstantPool(),
-                           false, false, 0);
+                           false, false, false, 0);
     }
   } else if (GlobalAddressSDNode *G =3D dyn_cast<GlobalAddressSDNode>(Call=
ee)) {
     const GlobalValue *GV =3D G->getGlobal();
@@ -1465,7 +1536,7 @@
       Callee =3D DAG.getLoad(getPointerTy(), dl,
                            DAG.getEntryNode(), CPAddr,
                            MachinePointerInfo::getConstantPool(),
-                           false, false, 0);
+                           false, false, false, 0);
       SDValue PICLabel =3D DAG.getConstant(ARMPCLabelIndex, MVT::i32);
       Callee =3D DAG.getNode(ARMISD::PIC_ADD, dl,
                            getPointerTy(), Callee, PICLabel);
@@ -1494,7 +1565,7 @@
       Callee =3D DAG.getLoad(getPointerTy(), dl,
                            DAG.getEntryNode(), CPAddr,
                            MachinePointerInfo::getConstantPool(),
-                           false, false, 0);
+                           false, false, false, 0);
       SDValue PICLabel =3D DAG.getConstant(ARMPCLabelIndex, MVT::i32);
       Callee =3D DAG.getNode(ARMISD::PIC_ADD, dl,
                            getPointerTy(), Callee, PICLabel);
@@ -1513,12 +1584,20 @@
   if (Subtarget->isThumb()) {
     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
       CallOpc =3D ARMISD::CALL_NOLINK;
+    else if (doesNotRet && isDirect && !isARMFunc &&
+             Subtarget->hasRAS() && !Subtarget->isThumb1Only())
+      // "mov lr, pc; b _foo" to avoid confusing the RSP
+      CallOpc =3D ARMISD::CALL_NOLINK;
     else
       CallOpc =3D isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
   } else {
-    CallOpc =3D (isDirect || Subtarget->hasV5TOps())
-      ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
-      : ARMISD::CALL_NOLINK;
+    if (!isDirect && !Subtarget->hasV5TOps()) {
+      CallOpc =3D ARMISD::CALL_NOLINK;
+    } else if (doesNotRet && isDirect && Subtarget->hasRAS())
+      // "mov lr, pc; b _foo" to avoid confusing the RSP
+      CallOpc =3D ARMISD::CALL_NOLINK;
+    else
+      CallOpc =3D isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
   }
=20
   std::vector<SDValue> Ops;
@@ -1531,6 +1610,12 @@
     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
                                   RegsToPass[i].second.getValueType()));
=20
+  // Add a register mask operand representing the call-preserved registers.
+  const TargetRegisterInfo *TRI =3D getTargetMachine().getRegisterInfo();
+  const uint32_t *Mask =3D TRI->getCallPreservedMask(CallConv);
+  assert(Mask && "Missing call preserved mask for calling convention");
+  Ops.push_back(DAG.getRegisterMask(Mask));
+
   if (InFlag.getNode())
     Ops.push_back(InFlag);
=20
@@ -1558,7 +1643,7 @@
 /// and then confiscate the rest of the parameter registers to insure
 /// this.
 void
-llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const=
 {
+ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
   unsigned reg =3D State->AllocateReg(GPRArgRegs, 4);
   assert((State->getCallOrPrologue() =3D=3D Prologue ||
           State->getCallOrPrologue() =3D=3D Call) &&
@@ -1588,7 +1673,7 @@
 static
 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Fla=
gs,
                          MachineFrameInfo *MFI, const MachineRegisterInfo =
*MRI,
-                         const ARMInstrInfo *TII) {
+                         const TargetInstrInfo *TII) {
   unsigned Bytes =3D Arg.getValueType().getSizeInBits() / 8;
   int FI =3D INT_MAX;
   if (Arg.getOpcode() =3D=3D ISD::CopyFromReg) {
@@ -1723,8 +1808,7 @@
       // the caller's fixed stack objects.
       MachineFrameInfo *MFI =3D MF.getFrameInfo();
       const MachineRegisterInfo *MRI =3D &MF.getRegInfo();
-      const ARMInstrInfo *TII =3D
-        ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
+      const TargetInstrInfo *TII =3D getTargetMachine().getInstrInfo();
       for (unsigned i =3D 0, realArgIdx =3D 0, e =3D ArgLocs.size();
            i !=3D e;
            ++i, ++realArgIdx) {
@@ -1852,63 +1936,72 @@
   return result;
 }
=20
-bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
+bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) cons=
t {
   if (N->getNumValues() !=3D 1)
     return false;
   if (!N->hasNUsesOfValue(1, 0))
     return false;
=20
-  unsigned NumCopies =3D 0;
-  SDNode* Copies[2];
-  SDNode *Use =3D *N->use_begin();
-  if (Use->getOpcode() =3D=3D ISD::CopyToReg) {
-    Copies[NumCopies++] =3D Use;
-  } else if (Use->getOpcode() =3D=3D ARMISD::VMOVRRD) {
+  SDValue TCChain =3D Chain;
+  SDNode *Copy =3D *N->use_begin();
+  if (Copy->getOpcode() =3D=3D ISD::CopyToReg) {
+    // If the copy has a glue operand, we conservatively assume it isn't s=
afe to
+    // perform a tail call.
+    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() =3D=3D M=
VT::Glue)
+      return false;
+    TCChain =3D Copy->getOperand(0);
+  } else if (Copy->getOpcode() =3D=3D ARMISD::VMOVRRD) {
+    SDNode *VMov =3D Copy;
     // f64 returned in a pair of GPRs.
-    for (SDNode::use_iterator UI =3D Use->use_begin(), UE =3D Use->use_end=
();
+    SmallPtrSet<SDNode*, 2> Copies;
+    for (SDNode::use_iterator UI =3D VMov->use_begin(), UE =3D VMov->use_e=
nd();
          UI !=3D UE; ++UI) {
       if (UI->getOpcode() !=3D ISD::CopyToReg)
         return false;
-      Copies[UI.getUse().getResNo()] =3D *UI;
-      ++NumCopies;
-    }
-  } else if (Use->getOpcode() =3D=3D ISD::BITCAST) {
+      Copies.insert(*UI);
+    }
+    if (Copies.size() > 2)
+      return false;
+
+    for (SDNode::use_iterator UI =3D VMov->use_begin(), UE =3D VMov->use_e=
nd();
+         UI !=3D UE; ++UI) {
+      SDValue UseChain =3D UI->getOperand(0);
+      if (Copies.count(UseChain.getNode()))
+        // Second CopyToReg
+        Copy =3D *UI;
+      else
+        // First CopyToReg
+        TCChain =3D UseChain;
+    }
+  } else if (Copy->getOpcode() =3D=3D ISD::BITCAST) {
     // f32 returned in a single GPR.
-    if (!Use->hasNUsesOfValue(1, 0))
+    if (!Copy->hasOneUse())
       return false;
-    Use =3D *Use->use_begin();
-    if (Use->getOpcode() !=3D ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0=
))
+    Copy =3D *Copy->use_begin();
+    if (Copy->getOpcode() !=3D ISD::CopyToReg || !Copy->hasNUsesOfValue(1,=
 0))
       return false;
-    Copies[NumCopies++] =3D Use;
+    Chain =3D Copy->getOperand(0);
   } else {
     return false;
   }
=20
-  if (NumCopies !=3D 1 && NumCopies !=3D 2)
+  bool HasRet =3D false;
+  for (SDNode::use_iterator UI =3D Copy->use_begin(), UE =3D Copy->use_end=
();
+       UI !=3D UE; ++UI) {
+    if (UI->getOpcode() !=3D ARMISD::RET_FLAG)
+      return false;
+    HasRet =3D true;
+  }
+
+  if (!HasRet)
     return false;
=20
-  bool HasRet =3D false;
-  for (unsigned i =3D 0; i < NumCopies; ++i) {
-    SDNode *Copy =3D Copies[i];
-    for (SDNode::use_iterator UI =3D Copy->use_begin(), UE =3D Copy->use_e=
nd();
-         UI !=3D UE; ++UI) {
-      if (UI->getOpcode() =3D=3D ISD::CopyToReg) {
-        SDNode *Use =3D *UI;
-        if (Use =3D=3D Copies[0] || Use =3D=3D Copies[1])
-          continue;
-        return false;
-      }
-      if (UI->getOpcode() !=3D ARMISD::RET_FLAG)
-        return false;
-      HasRet =3D true;
-    }
-  }
-
-  return HasRet;
+  Chain =3D TCChain;
+  return true;
 }
=20
 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
-  if (!EnableARMTailCalls)
+  if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
     return false;
=20
   if (!CI->isTailCall())
@@ -1965,7 +2058,7 @@
   CPAddr =3D DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
   SDValue Result =3D DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
                                MachinePointerInfo::getConstantPool(),
-                               false, false, 0);
+                               false, false, false, 0);
   if (RelocM =3D=3D Reloc::Static)
     return Result;
   SDValue PICLabel =3D DAG.getConstant(ARMPCLabelIndex, MVT::i32);
@@ -1989,7 +2082,7 @@
   Argument =3D DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
   Argument =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
                          MachinePointerInfo::getConstantPool(),
-                         false, false, 0);
+                         false, false, false, 0);
   SDValue Chain =3D Argument.getValue(1);
=20
   SDValue PICLabel =3D DAG.getConstant(ARMPCLabelIndex, MVT::i32);
@@ -2005,7 +2098,8 @@
   std::pair<SDValue, SDValue> CallResult =3D
     LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
                 false, false, false, false,
-                0, CallingConv::C, false, /*isReturnValueUsed=3D*/true,
+                0, CallingConv::C, /*isTailCall=3D*/false,
+                /*doesNotRet=3D*/false, /*isReturnValueUsed=3D*/true,
                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,=
 dl);
   return CallResult.first;
 }
@@ -2037,7 +2131,7 @@
     Offset =3D DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
     Offset =3D DAG.getLoad(PtrVT, dl, Chain, Offset,
                          MachinePointerInfo::getConstantPool(),
-                         false, false, 0);
+                         false, false, false, 0);
     Chain =3D Offset.getValue(1);
=20
     SDValue PICLabel =3D DAG.getConstant(ARMPCLabelIndex, MVT::i32);
@@ -2045,7 +2139,7 @@
=20
     Offset =3D DAG.getLoad(PtrVT, dl, Chain, Offset,
                          MachinePointerInfo::getConstantPool(),
-                         false, false, 0);
+                         false, false, false, 0);
   } else {
     // local exec model
     ARMConstantPoolValue *CPV =3D
@@ -2054,7 +2148,7 @@
     Offset =3D DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
     Offset =3D DAG.getLoad(PtrVT, dl, Chain, Offset,
                          MachinePointerInfo::getConstantPool(),
-                         false, false, 0);
+                         false, false, false, 0);
   }
=20
   // The address of the thread local variable is the add of the thread
@@ -2092,13 +2186,14 @@
     SDValue Result =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
                                  CPAddr,
                                  MachinePointerInfo::getConstantPool(),
-                                 false, false, 0);
+                                 false, false, false, 0);
     SDValue Chain =3D Result.getValue(1);
     SDValue GOT =3D DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
     Result =3D DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
     if (!UseGOTOFF)
       Result =3D DAG.getLoad(PtrVT, dl, Chain, Result,
-                           MachinePointerInfo::getGOT(), false, false, 0);
+                           MachinePointerInfo::getGOT(),
+                           false, false, false, 0);
     return Result;
   }
=20
@@ -2115,7 +2210,7 @@
     CPAddr =3D DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
                        MachinePointerInfo::getConstantPool(),
-                       false, false, 0);
+                       false, false, false, 0);
   }
 }
=20
@@ -2128,7 +2223,8 @@
   MachineFunction &MF =3D DAG.getMachineFunction();
   ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
=20
-  // FIXME: Enable this for static codegen when tool issues are fixed.
+  // FIXME: Enable this for static codegen when tool issues are fixed.  Al=
so
+  // update ARMFastISel::ARMMaterializeGV.
   if (Subtarget->useMovt() && RelocM !=3D Reloc::Static) {
     ++NumMovwMovt;
     // FIXME: Once remat is capable of dealing with instructions with regi=
ster
@@ -2143,7 +2239,8 @@
                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT)=
);
     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
       Result =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
-                           MachinePointerInfo::getGOT(), false, false, 0);
+                           MachinePointerInfo::getGOT(),
+                           false, false, false, 0);
     return Result;
   }
=20
@@ -2163,7 +2260,7 @@
=20
   SDValue Result =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
                                MachinePointerInfo::getConstantPool(),
-                               false, false, 0);
+                               false, false, false, 0);
   SDValue Chain =3D Result.getValue(1);
=20
   if (RelocM =3D=3D Reloc::PIC_) {
@@ -2173,7 +2270,7 @@
=20
   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
     Result =3D DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::g=
etGOT(),
-                         false, false, 0);
+                         false, false, false, 0);
=20
   return Result;
 }
@@ -2195,20 +2292,12 @@
   CPAddr =3D DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
   SDValue Result =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
                                MachinePointerInfo::getConstantPool(),
-                               false, false, 0);
+                               false, false, false, 0);
   SDValue PICLabel =3D DAG.getConstant(ARMPCLabelIndex, MVT::i32);
   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
 }
=20
 SDValue
-ARMTargetLowering::LowerEH_SJLJ_DISPATCHSETUP(SDValue Op, SelectionDAG &DA=
G)
-  const {
-  DebugLoc dl =3D Op.getDebugLoc();
-  return DAG.getNode(ARMISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
-                     Op.getOperand(0), Op.getOperand(1));
-}
-
-SDValue
 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) cons=
t {
   DebugLoc dl =3D Op.getDebugLoc();
   SDValue Val =3D DAG.getConstant(0, MVT::i32);
@@ -2253,7 +2342,7 @@
     SDValue Result =3D
       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
                   MachinePointerInfo::getConstantPool(),
-                  false, false, 0);
+                  false, false, false, 0);
=20
     if (RelocM =3D=3D Reloc::PIC_) {
       SDValue PICLabel =3D DAG.getConstant(ARMPCLabelIndex, MVT::i32);
@@ -2366,7 +2455,7 @@
   MachineFunction &MF =3D DAG.getMachineFunction();
   ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
=20
-  TargetRegisterClass *RC;
+  const TargetRegisterClass *RC;
   if (AFI->isThumb1OnlyFunction())
     RC =3D ARM::tGPRRegisterClass;
   else
@@ -2385,7 +2474,7 @@
     SDValue FIN =3D DAG.getFrameIndex(FI, getPointerTy());
     ArgValue2 =3D DAG.getLoad(MVT::i32, dl, Root, FIN,
                             MachinePointerInfo::getFixedStack(FI),
-                            false, false, 0);
+                            false, false, false, 0);
   } else {
     Reg =3D MF.addLiveIn(NextVA.getLocReg(), RC);
     ArgValue2 =3D DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
@@ -2452,7 +2541,7 @@
=20
     SmallVector<SDValue, 4> MemOps;
     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
-      TargetRegisterClass *RC;
+      const TargetRegisterClass *RC;
       if (AFI->isThumb1OnlyFunction())
         RC =3D ARM::tGPRRegisterClass;
       else
@@ -2521,7 +2610,7 @@
             SDValue FIN =3D DAG.getFrameIndex(FI, getPointerTy());
             ArgValue2 =3D DAG.getLoad(MVT::f64, dl, Chain, FIN,
                                     MachinePointerInfo::getFixedStack(FI),
-                                    false, false, 0);
+                                    false, false, false, 0);
           } else {
             ArgValue2 =3D GetF64FormalArgument(VA, ArgLocs[++i],
                                              Chain, DAG, dl);
@@ -2535,7 +2624,7 @@
           ArgValue =3D GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, =
dl);
=20
       } else {
-        TargetRegisterClass *RC;
+        const TargetRegisterClass *RC;
=20
         if (RegVT =3D=3D MVT::f32)
           RC =3D ARM::SPRRegisterClass;
@@ -2612,7 +2701,7 @@
             SDValue FIN =3D DAG.getFrameIndex(FI, getPointerTy());
             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
                                          MachinePointerInfo::getFixedStack=
(FI),
-                                         false, false, 0));
+                                         false, false, false, 0));
           }
           lastInsIndex =3D index;
         }
@@ -2777,6 +2866,11 @@
     }
   }
=20
+  // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
+  // undefined bits before doing a full-word comparison with zero.
+  Cond =3D DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
+                     DAG.getConstant(1, Cond.getValueType()));
+
   return DAG.getSelectCC(dl, Cond,
                          DAG.getConstant(0, Cond.getValueType()),
                          SelectTrue, SelectFalse, ISD::SETNE);
@@ -2847,7 +2941,7 @@
     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInf=
o(),
                        Ld->isVolatile(), Ld->isNonTemporal(),
-                       Ld->getAlignment());
+                       Ld->isInvariant(), Ld->getAlignment());
=20
   llvm_unreachable("Unknown VFP cmp argument!");
 }
@@ -2866,7 +2960,7 @@
                           Ld->getChain(), Ptr,
                           Ld->getPointerInfo(),
                           Ld->isVolatile(), Ld->isNonTemporal(),
-                          Ld->getAlignment());
+                          Ld->isInvariant(), Ld->getAlignment());
=20
     EVT PtrType =3D Ptr.getValueType();
     unsigned NewAlign =3D MinAlign(Ld->getAlignment(), 4);
@@ -2876,7 +2970,7 @@
                           Ld->getChain(), NewPtr,
                           Ld->getPointerInfo().getWithOffset(4),
                           Ld->isVolatile(), Ld->isNonTemporal(),
-                          NewAlign);
+                          Ld->isInvariant(), NewAlign);
     return;
   }
=20
@@ -2894,12 +2988,11 @@
   SDValue Dest =3D Op.getOperand(4);
   DebugLoc dl =3D Op.getDebugLoc();
=20
-  bool SeenZero =3D false;
-  if (canChangeToInt(LHS, SeenZero, Subtarget) &&
-      canChangeToInt(RHS, SeenZero, Subtarget) &&
-      // If one of the operand is zero, it's safe to ignore the NaN case s=
ince
-      // we only care about equality comparisons.
-      (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))=
) {
+  bool LHSSeenZero =3D false;
+  bool LHSOk =3D canChangeToInt(LHS, LHSSeenZero, Subtarget);
+  bool RHSSeenZero =3D false;
+  bool RHSOk =3D canChangeToInt(RHS, RHSSeenZero, Subtarget);
+  if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
     // If unsafe fp math optimization is enabled and there are no other us=
es of
     // the CMP operands, and the condition code is EQ or NE, we can optimi=
ze it
     // to an integer comparison.
@@ -2908,10 +3001,13 @@
     else if (CC =3D=3D ISD::SETUNE)
       CC =3D ISD::SETNE;
=20
+    SDValue Mask =3D DAG.getConstant(0x7fffffff, MVT::i32);
     SDValue ARMcc;
     if (LHS.getValueType() =3D=3D MVT::f32) {
-      LHS =3D bitcastf32Toi32(LHS, DAG);
-      RHS =3D bitcastf32Toi32(RHS, DAG);
+      LHS =3D DAG.getNode(ISD::AND, dl, MVT::i32,
+                        bitcastf32Toi32(LHS, DAG), Mask);
+      RHS =3D DAG.getNode(ISD::AND, dl, MVT::i32,
+                        bitcastf32Toi32(RHS, DAG), Mask);
       SDValue Cmp =3D getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
       SDValue CCR =3D DAG.getRegister(ARM::CPSR, MVT::i32);
       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
@@ -2922,6 +3018,8 @@
     SDValue RHS1, RHS2;
     expandf64Toi32(LHS, DAG, LHS1, LHS2);
     expandf64Toi32(RHS, DAG, RHS1, RHS2);
+    LHS2 =3D DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
+    RHS2 =3D DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
     ARMCC::CondCodes CondCode =3D IntCCToARMCC(CC);
     ARMcc =3D DAG.getConstant(CondCode, MVT::i32);
     SDVTList VTList =3D DAG.getVTList(MVT::Other, MVT::Glue);
@@ -2950,7 +3048,7 @@
=20
   assert(LHS.getValueType() =3D=3D MVT::f32 || LHS.getValueType() =3D=3D M=
VT::f64);
=20
-  if (UnsafeFPMath &&
+  if (getTargetMachine().Options.UnsafeFPMath &&
       (CC =3D=3D ISD::SETEQ || CC =3D=3D ISD::SETOEQ ||
        CC =3D=3D ISD::SETNE || CC =3D=3D ISD::SETUNE)) {
     SDValue Result =3D OptimizeVFPBrcond(Op, DAG);
@@ -3000,25 +3098,48 @@
   if (getTargetMachine().getRelocationModel() =3D=3D Reloc::PIC_) {
     Addr =3D DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
                        MachinePointerInfo::getJumpTable(),
-                       false, false, 0);
+                       false, false, false, 0);
     Chain =3D Addr.getValue(1);
     Addr =3D DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UI=
d);
   } else {
     Addr =3D DAG.getLoad(PTy, dl, Chain, Addr,
-                       MachinePointerInfo::getJumpTable(), false, false, 0=
);
+                       MachinePointerInfo::getJumpTable(),
+                       false, false, false, 0);
     Chain =3D Addr.getValue(1);
     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UI=
d);
   }
 }
=20
+static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
+  EVT VT =3D Op.getValueType();
+  DebugLoc dl =3D Op.getDebugLoc();
+
+  if (Op.getValueType().getVectorElementType() =3D=3D MVT::i32) {
+    if (Op.getOperand(0).getValueType().getVectorElementType() =3D=3D MVT:=
:f32)
+      return Op;
+    return DAG.UnrollVectorOp(Op.getNode());
+  }
+
+  assert(Op.getOperand(0).getValueType() =3D=3D MVT::v4f32 &&
+         "Invalid type for custom lowering!");
+  if (VT !=3D MVT::v4i16)
+    return DAG.UnrollVectorOp(Op.getNode());
+
+  Op =3D DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
+  return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
+}
+
 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
+  EVT VT =3D Op.getValueType();
+  if (VT.isVector())
+    return LowerVectorFP_TO_INT(Op, DAG);
+
   DebugLoc dl =3D Op.getDebugLoc();
   unsigned Opc;
=20
   switch (Op.getOpcode()) {
-  default:
-    assert(0 && "Invalid opcode!");
+  default: llvm_unreachable("Invalid opcode!");
   case ISD::FP_TO_SINT:
     Opc =3D ARMISD::FTOSI;
     break;
@@ -3034,6 +3155,12 @@
   EVT VT =3D Op.getValueType();
   DebugLoc dl =3D Op.getDebugLoc();
=20
+  if (Op.getOperand(0).getValueType().getVectorElementType() =3D=3D MVT::i=
32) {
+    if (VT.getVectorElementType() =3D=3D MVT::f32)
+      return Op;
+    return DAG.UnrollVectorOp(Op.getNode());
+  }
+
   assert(Op.getOperand(0).getValueType() =3D=3D MVT::v4i16 &&
          "Invalid type for custom lowering!");
   if (VT !=3D MVT::v4f32)
@@ -3042,8 +3169,7 @@
   unsigned CastOpc;
   unsigned Opc;
   switch (Op.getOpcode()) {
-  default:
-    assert(0 && "Invalid opcode!");
+  default: llvm_unreachable("Invalid opcode!");
   case ISD::SINT_TO_FP:
     CastOpc =3D ISD::SIGN_EXTEND;
     Opc =3D ISD::SINT_TO_FP;
@@ -3067,8 +3193,7 @@
   unsigned Opc;
=20
   switch (Op.getOpcode()) {
-  default:
-    assert(0 && "Invalid opcode!");
+  default: llvm_unreachable("Invalid opcode!");
   case ISD::SINT_TO_FP:
     Opc =3D ARMISD::SITOF;
     break;
@@ -3176,7 +3301,7 @@
     SDValue Offset =3D DAG.getConstant(4, MVT::i32);
     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
-                       MachinePointerInfo(), false, false, 0);
+                       MachinePointerInfo(), false, false, false, 0);
   }
=20
   // Return LR, which contains the return address. Mark it an implicit liv=
e-in.
@@ -3197,7 +3322,7 @@
   while (Depth--)
     FrameAddr =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
                             MachinePointerInfo(),
-                            false, false, 0);
+                            false, false, false, 0);
   return FrameAddr;
 }
=20
@@ -3442,7 +3567,7 @@
=20
   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
     switch (SetCCOpcode) {
-    default: llvm_unreachable("Illegal FP comparison"); break;
+    default: llvm_unreachable("Illegal FP comparison");
     case ISD::SETUNE:
     case ISD::SETNE:  Invert =3D true; // Fallthrough
     case ISD::SETOEQ:
@@ -3481,7 +3606,7 @@
   } else {
     // Integer comparisons.
     switch (SetCCOpcode) {
-    default: llvm_unreachable("Illegal integer comparison"); break;
+    default: llvm_unreachable("Illegal integer comparison");
     case ISD::SETNE:  Invert =3D true;
     case ISD::SETEQ:  Opc =3D ARMISD::VCEQ; break;
     case ISD::SETLT:  Swap =3D true;
@@ -3688,14 +3813,65 @@
=20
   default:
     llvm_unreachable("unexpected size for isNEONModifiedImm");
-    return SDValue();
   }
=20
   unsigned EncodedVal =3D ARM_AM::createNEONModImm(OpCmode, Imm);
   return DAG.getTargetConstant(EncodedVal, MVT::i32);
 }
=20
-static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
+SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
+                                           const ARMSubtarget *ST) const {
+  if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
+    return SDValue();
+
+  ConstantFPSDNode *CFP =3D cast<ConstantFPSDNode>(Op);
+  assert(Op.getValueType() =3D=3D MVT::f32 &&
+         "ConstantFP custom lowering should only occur for f32.");
+
+  // Try splatting with a VMOV.f32...
+  APFloat FPVal =3D CFP->getValueAPF();
+  int ImmVal =3D ARM_AM::getFP32Imm(FPVal);
+  if (ImmVal !=3D -1) {
+    DebugLoc DL =3D Op.getDebugLoc();
+    SDValue NewVal =3D DAG.getTargetConstant(ImmVal, MVT::i32);
+    SDValue VecConstant =3D DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
+                                      NewVal);
+    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
+                       DAG.getConstant(0, MVT::i32));
+  }
+
+  // If that fails, try a VMOV.i32
+  EVT VMovVT;
+  unsigned iVal =3D FPVal.bitcastToAPInt().getZExtValue();
+  SDValue NewVal =3D isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
+                                     VMOVModImm);
+  if (NewVal !=3D SDValue()) {
+    DebugLoc DL =3D Op.getDebugLoc();
+    SDValue VecConstant =3D DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
+                                      NewVal);
+    SDValue VecFConstant =3D DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
+                                       VecConstant);
+    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
+                       DAG.getConstant(0, MVT::i32));
+  }
+
+  // Finally, try a VMVN.i32
+  NewVal =3D isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, fal=
se,
+                             VMVNModImm);
+  if (NewVal !=3D SDValue()) {
+    DebugLoc DL =3D Op.getDebugLoc();
+    SDValue VecConstant =3D DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVa=
l);
+    SDValue VecFConstant =3D DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
+                                       VecConstant);
+    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
+                       DAG.getConstant(0, MVT::i32));
+  }
+
+  return SDValue();
+}
+
+
+static bool isVEXTMask(ArrayRef<int> M, EVT VT,
                        bool &ReverseVEXT, unsigned &Imm) {
   unsigned NumElts =3D VT.getVectorNumElements();
   ReverseVEXT =3D false;
@@ -3734,8 +3910,7 @@
 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
 /// instruction with the specified blocksize.  (The order of the elements
 /// within each block of the vector is reversed.)
-static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
-                       unsigned BlockSize) {
+static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
   assert((BlockSize=3D=3D16 || BlockSize=3D=3D32 || BlockSize=3D=3D64) &&
          "Only possible block sizes for VREV are: 16, 32, 64");
=20
@@ -3761,15 +3936,14 @@
   return true;
 }
=20
-static bool isVTBLMask(const SmallVectorImpl<int> &M, EVT VT) {
+static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
   // We can handle <8 x i8> vector shuffles. If the index in the mask is o=
ut of
   // range, then 0 is placed into the resulting vector. So pretty much any=
 mask
   // of 8 elements can work here.
   return VT =3D=3D MVT::v8i8 && M.size() =3D=3D 8;
 }
=20
-static bool isVTRNMask(const SmallVectorImpl<int> &M, EVT VT,
-                       unsigned &WhichResult) {
+static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
   unsigned EltSz =3D VT.getVectorElementType().getSizeInBits();
   if (EltSz =3D=3D 64)
     return false;
@@ -3787,8 +3961,7 @@
 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
-static bool isVTRN_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
-                                unsigned &WhichResult) {
+static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichRe=
sult){
   unsigned EltSz =3D VT.getVectorElementType().getSizeInBits();
   if (EltSz =3D=3D 64)
     return false;
@@ -3803,8 +3976,7 @@
   return true;
 }
=20
-static bool isVUZPMask(const SmallVectorImpl<int> &M, EVT VT,
-                       unsigned &WhichResult) {
+static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
   unsigned EltSz =3D VT.getVectorElementType().getSizeInBits();
   if (EltSz =3D=3D 64)
     return false;
@@ -3827,8 +3999,7 @@
 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
-static bool isVUZP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
-                                unsigned &WhichResult) {
+static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichRe=
sult){
   unsigned EltSz =3D VT.getVectorElementType().getSizeInBits();
   if (EltSz =3D=3D 64)
     return false;
@@ -3852,8 +4023,7 @@
   return true;
 }
=20
-static bool isVZIPMask(const SmallVectorImpl<int> &M, EVT VT,
-                       unsigned &WhichResult) {
+static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
   unsigned EltSz =3D VT.getVectorElementType().getSizeInBits();
   if (EltSz =3D=3D 64)
     return false;
@@ -3878,8 +4048,7 @@
 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
-static bool isVZIP_v_undef_Mask(const SmallVectorImpl<int> &M, EVT VT,
-                                unsigned &WhichResult) {
+static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichRe=
sult){
   unsigned EltSz =3D VT.getVectorElementType().getSizeInBits();
   if (EltSz =3D=3D 64)
     return false;
@@ -3955,6 +4124,15 @@
         SDValue Vmov =3D DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
       }
+
+      // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
+      if ((VT =3D=3D MVT::v2f32 || VT =3D=3D MVT::v4f32) && SplatBitSize =
=3D=3D 32) {
+        int ImmVal =3D ARM_AM::getFP32Imm(SplatBits);
+        if (ImmVal !=3D -1) {
+          SDValue Val =3D DAG.getTargetConstant(ImmVal, MVT::i32);
+          return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
+        }
+      }
     }
   }
=20
@@ -4302,7 +4480,7 @@
 }
=20
 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
-                                       SmallVectorImpl<int> &ShuffleMask,
+                                       ArrayRef<int> ShuffleMask,
                                        SelectionDAG &DAG) {
   // Check to see if we can use the VTBL instruction.
   SDValue V1 =3D Op.getOperand(0);
@@ -4310,7 +4488,7 @@
   DebugLoc DL =3D Op.getDebugLoc();
=20
   SmallVector<SDValue, 8> VTBLMask;
-  for (SmallVectorImpl<int>::iterator
+  for (ArrayRef<int>::iterator
          I =3D ShuffleMask.begin(), E =3D ShuffleMask.end(); I !=3D E; ++I)
     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
=20
@@ -4330,7 +4508,6 @@
   DebugLoc dl =3D Op.getDebugLoc();
   EVT VT =3D Op.getValueType();
   ShuffleVectorSDNode *SVN =3D cast<ShuffleVectorSDNode>(Op.getNode());
-  SmallVector<int, 8> ShuffleMask;
=20
   // Convert shuffles that are directly supported on NEON to target-specif=
ic
   // DAG nodes, instead of keeping them as shuffles and matching them again
@@ -4338,7 +4515,7 @@
   // of inconsistencies between legalization and selection.
   // FIXME: floating-point vectors should be canonicalized to integer vect=
ors
   // of the same time so that they get CSEd properly.
-  SVN->getMask(ShuffleMask);
+  ArrayRef<int> ShuffleMask =3D SVN->getMask();
=20
   unsigned EltSize =3D VT.getVectorElementType().getSizeInBits();
   if (EltSize <=3D 32) {
@@ -4347,9 +4524,24 @@
       // If this is undef splat, generate it via "just" vdup, if possible.
       if (Lane =3D=3D -1) Lane =3D 0;
=20
+      // Test if V1 is a SCALAR_TO_VECTOR.
       if (Lane =3D=3D 0 && V1.getOpcode() =3D=3D ISD::SCALAR_TO_VECTOR) {
         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
       }
+      // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_V=
ECTOR
+      // (and probably will turn into a SCALAR_TO_VECTOR once legalization
+      // reaches it).
+      if (Lane =3D=3D 0 && V1.getOpcode() =3D=3D ISD::BUILD_VECTOR &&
+          !isa<ConstantSDNode>(V1.getOperand(0))) {
+        bool IsScalarToVector =3D true;
+        for (unsigned i =3D 1, e =3D V1.getNumOperands(); i !=3D e; ++i)
+          if (V1.getOperand(i).getOpcode() !=3D ISD::UNDEF) {
+            IsScalarToVector =3D false;
+            break;
+          }
+        if (IsScalarToVector)
+          return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
+      }
       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
                          DAG.getConstant(Lane, MVT::i32));
     }
@@ -4450,6 +4642,15 @@
   return SDValue();
 }
=20
+static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
+  // INSERT_VECTOR_ELT is legal only for immediate indexes.
+  SDValue Lane =3D Op.getOperand(2);
+  if (!isa<ConstantSDNode>(Lane))
+    return SDValue();
+
+  return Op;
+}
+
 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
   SDValue Lane =3D Op.getOperand(1);
@@ -4526,11 +4727,10 @@
       unsigned EltSize =3D VT.getVectorElementType().getSizeInBits();
       unsigned HalfSize =3D EltSize / 2;
       if (isSigned) {
-        int64_t SExtVal =3D C->getSExtValue();
-        if ((SExtVal >> HalfSize) !=3D (SExtVal >> EltSize))
+        if (!isIntN(HalfSize, C->getSExtValue()))
           return false;
       } else {
-        if ((C->getZExtValue() >> HalfSize) !=3D 0)
+        if (!isUIntN(HalfSize, C->getZExtValue()))
           return false;
       }
       continue;
@@ -4569,7 +4769,8 @@
   if (LoadSDNode *LD =3D dyn_cast<LoadSDNode>(N))
     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolat=
ile(),
-                       LD->isNonTemporal(), LD->getAlignment());
+                       LD->isNonTemporal(), LD->isInvariant(),
+                       LD->getAlignment());
   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
   // have been legalized as a BITCAST from v4i32.
   if (N->getOpcode() =3D=3D ISD::BITCAST) {
@@ -4874,7 +5075,7 @@
   unsigned Opc;
   bool ExtraOp =3D false;
   switch (Op.getOpcode()) {
-  default: assert(0 && "Invalid code");
+  default: llvm_unreachable("Invalid code");
   case ISD::ADDC: Opc =3D ARMISD::ADDC; break;
   case ISD::ADDE: Opc =3D ARMISD::ADDE; ExtraOp =3D true; break;
   case ISD::SUBC: Opc =3D ARMISD::SUBC; break;
@@ -4959,7 +5160,6 @@
   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
-  case ISD::EH_SJLJ_DISPATCHSETUP: return LowerEH_SJLJ_DISPATCHSETUP(Op, D=
AG);
   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
                                                                Subtarget);
   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
@@ -4971,8 +5171,10 @@
   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
+  case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
+  case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
@@ -4986,7 +5188,6 @@
   case ISD::ATOMIC_LOAD:
   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
   }
-  return SDValue();
 }
=20
 /// ReplaceNodeResults - Replace the results of node with an illegal result
@@ -4998,7 +5199,6 @@
   switch (N->getOpcode()) {
   default:
     llvm_unreachable("Don't know how to custom expand this!");
-    break;
   case ISD::BITCAST:
     Res =3D ExpandBITCAST(N, DAG);
     break;
@@ -5194,7 +5394,7 @@
                   BB->end());
   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
=20
-  TargetRegisterClass *TRC =3D
+  const TargetRegisterClass *TRC =3D
     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
   unsigned scratch =3D MRI.createVirtualRegister(TRC);
   unsigned scratch2 =3D (!BinOpcode) ? incr : MRI.createVirtualRegister(TR=
C);
@@ -5304,7 +5504,7 @@
                   BB->end());
   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
=20
-  TargetRegisterClass *TRC =3D
+  const TargetRegisterClass *TRC =3D
     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
   unsigned scratch =3D MRI.createVirtualRegister(TRC);
   unsigned scratch2 =3D MRI.createVirtualRegister(TRC);
@@ -5414,7 +5614,7 @@
                   BB->end());
   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
=20
-  TargetRegisterClass *TRC =3D
+  const TargetRegisterClass *TRC =3D
     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
   unsigned storesuccess =3D MRI.createVirtualRegister(TRC);
=20
@@ -5500,52 +5700,6 @@
   return BB;
 }
=20
-/// EmitBasePointerRecalculation - For functions using a base pointer, we
-/// rematerialize it (via the frame pointer).
-void ARMTargetLowering::
-EmitBasePointerRecalculation(MachineInstr *MI, MachineBasicBlock *MBB,
-                             MachineBasicBlock *DispatchBB) const {
-  const TargetInstrInfo *TII =3D getTargetMachine().getInstrInfo();
-  const ARMBaseInstrInfo *AII =3D static_cast<const ARMBaseInstrInfo*>(TII=
);
-  MachineFunction &MF =3D *MI->getParent()->getParent();
-  ARMFunctionInfo *AFI =3D MF.getInfo<ARMFunctionInfo>();
-  const ARMBaseRegisterInfo &RI =3D AII->getRegisterInfo();
-
-  if (!RI.hasBasePointer(MF)) return;
-
-  MachineBasicBlock::iterator MBBI =3D MI;
-
-  int32_t NumBytes =3D AFI->getFramePtrSpillOffset();
-  unsigned FramePtr =3D RI.getFrameRegister(MF);
-  assert(MF.getTarget().getFrameLowering()->hasFP(MF) &&
-         "Base pointer without frame pointer?");
-
-  if (AFI->isThumb2Function())
-    llvm::emitT2RegPlusImmediate(*MBB, MBBI, MI->getDebugLoc(), ARM::R6,
-                                 FramePtr, -NumBytes, ARMCC::AL, 0, *AII);
-  else if (AFI->isThumbFunction())
-    llvm::emitThumbRegPlusImmediate(*MBB, MBBI, MI->getDebugLoc(), ARM::R6,
-                                    FramePtr, -NumBytes, *AII, RI);
-  else
-    llvm::emitARMRegPlusImmediate(*MBB, MBBI, MI->getDebugLoc(), ARM::R6,
-                                  FramePtr, -NumBytes, ARMCC::AL, 0, *AII);
-
-  if (!RI.needsStackRealignment(MF)) return;
-
-  // If there's dynamic realignment, adjust for it.
-  MachineFrameInfo *MFI =3D MF.getFrameInfo();
-  unsigned MaxAlign =3D MFI->getMaxAlignment();
-  assert(!AFI->isThumb1OnlyFunction());
-
-  // Emit bic r6, r6, MaxAlign
-  unsigned bicOpc =3D AFI->isThumbFunction() ? ARM::t2BICri : ARM::BICri;
-  AddDefaultCC(
-    AddDefaultPred(
-      BuildMI(*MBB, MBBI, MI->getDebugLoc(), TII->get(bicOpc), ARM::R6)
-      .addReg(ARM::R6, RegState::Kill)
-      .addImm(MaxAlign - 1)));
-}
-
 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates=
 and
 /// registers the function context.
 void ARMTargetLowering::
@@ -5580,8 +5734,6 @@
     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
                              MachineMemOperand::MOStore, 4, 4);
=20
-  EmitBasePointerRecalculation(MI, MBB, DispatchBB);
-
   // Load the address of the dispatch MBB into the jump buffer.
   if (isThumb2) {
     // Incoming value: jbuf
@@ -5683,7 +5835,8 @@
   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPa=
d;
   unsigned MaxCSNum =3D 0;
   MachineModuleInfo &MMI =3D MF->getMMI();
-  for (MachineFunction::iterator BB =3D MF->begin(), E =3D MF->end(); BB !=
=3D E; ++BB) {
+  for (MachineFunction::iterator BB =3D MF->begin(), E =3D MF->end(); BB !=
=3D E;
+       ++BB) {
     if (!BB->isLandingPad()) continue;
=20
     // FIXME: We should assert that the EH_LABEL is the first MI in the la=
nding
@@ -5741,12 +5894,10 @@
   MachineBasicBlock *DispContBB =3D MF->CreateMachineBasicBlock();
   DispatchBB->addSuccessor(DispContBB);
=20
-  // Insert and renumber MBBs.
-  MachineBasicBlock *Last =3D &MF->back();
+  // Insert and MBBs.
   MF->insert(MF->end(), DispatchBB);
   MF->insert(MF->end(), DispContBB);
   MF->insert(MF->end(), TrapBB);
-  MF->RenumberBlocks(Last);
=20
   // Insert code into the entry block that creates and registers the funct=
ion
   // context.
@@ -5757,35 +5908,63 @@
                              MachineMemOperand::MOLoad |
                              MachineMemOperand::MOVolatile, 4, 4);
=20
+  if (AFI->isThumb1OnlyFunction())
+    BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
+  else if (!Subtarget->hasVFP2())
+    BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
+  else
+    BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
+
+  unsigned NumLPads =3D LPadList.size();
   if (Subtarget->isThumb2()) {
     unsigned NewVReg1 =3D MRI->createVirtualRegister(TRC);
     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVRe=
g1)
                    .addFrameIndex(FI)
                    .addImm(4)
                    .addMemOperand(FIMMOLd));
-    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
-                   .addReg(NewVReg1)
-                   .addImm(LPadList.size()));
+
+    if (NumLPads < 256) {
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
+                     .addReg(NewVReg1)
+                     .addImm(LPadList.size()));
+    } else {
+      unsigned VReg1 =3D MRI->createVirtualRegister(TRC);
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg=
1)
+                     .addImm(NumLPads & 0xFFFF));
+
+      unsigned VReg2 =3D VReg1;
+      if ((NumLPads & 0xFFFF0000) !=3D 0) {
+        VReg2 =3D MRI->createVirtualRegister(TRC);
+        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), V=
Reg2)
+                       .addReg(VReg1)
+                       .addImm(NumLPads >> 16));
+      }
+
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
+                     .addReg(NewVReg1)
+                     .addReg(VReg2));
+    }
+
     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
       .addMBB(TrapBB)
       .addImm(ARMCC::HI)
       .addReg(ARM::CPSR);
=20
-    unsigned NewVReg2 =3D MRI->createVirtualRegister(TRC);
-    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),New=
VReg2)
+    unsigned NewVReg3 =3D MRI->createVirtualRegister(TRC);
+    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),New=
VReg3)
                    .addJumpTableIndex(MJTI)
                    .addImm(UId));
=20
-    unsigned NewVReg3 =3D MRI->createVirtualRegister(TRC);
+    unsigned NewVReg4 =3D MRI->createVirtualRegister(TRC);
     AddDefaultCC(
       AddDefaultPred(
-        BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg3)
-        .addReg(NewVReg2, RegState::Kill)
+        BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
+        .addReg(NewVReg3, RegState::Kill)
         .addReg(NewVReg1)
         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
=20
     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
-      .addReg(NewVReg3, RegState::Kill)
+      .addReg(NewVReg4, RegState::Kill)
       .addReg(NewVReg1)
       .addJumpTableIndex(MJTI)
       .addImm(UId);
@@ -5796,9 +5975,30 @@
                    .addImm(1)
                    .addMemOperand(FIMMOLd));
=20
-    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
-                   .addReg(NewVReg1)
-                   .addImm(LPadList.size()));
+    if (NumLPads < 256) {
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
+                     .addReg(NewVReg1)
+                     .addImm(NumLPads));
+    } else {
+      MachineConstantPool *ConstantPool =3D MF->getConstantPool();
+      Type *Int32Ty =3D Type::getInt32Ty(MF->getFunction()->getContext());
+      const Constant *C =3D ConstantInt::get(Int32Ty, NumLPads);
+
+      // MachineConstantPool wants an explicit alignment.
+      unsigned Align =3D getTargetData()->getPrefTypeAlignment(Int32Ty);
+      if (Align =3D=3D 0)
+        Align =3D getTargetData()->getTypeAllocSize(C->getType());
+      unsigned Idx =3D ConstantPool->getConstantPoolIndex(C, Align);
+
+      unsigned VReg1 =3D MRI->createVirtualRegister(TRC);
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
+                     .addReg(VReg1, RegState::Define)
+                     .addConstantPoolIndex(Idx));
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
+                     .addReg(NewVReg1)
+                     .addReg(VReg1));
+    }
+
     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
       .addMBB(TrapBB)
       .addImm(ARMCC::HI)
@@ -5847,38 +6047,77 @@
                    .addFrameIndex(FI)
                    .addImm(4)
                    .addMemOperand(FIMMOLd));
-    AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
-                   .addReg(NewVReg1)
-                   .addImm(LPadList.size()));
+
+    if (NumLPads < 256) {
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
+                     .addReg(NewVReg1)
+                     .addImm(NumLPads));
+    } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
+      unsigned VReg1 =3D MRI->createVirtualRegister(TRC);
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
+                     .addImm(NumLPads & 0xFFFF));
+
+      unsigned VReg2 =3D VReg1;
+      if ((NumLPads & 0xFFFF0000) !=3D 0) {
+        VReg2 =3D MRI->createVirtualRegister(TRC);
+        AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VRe=
g2)
+                       .addReg(VReg1)
+                       .addImm(NumLPads >> 16));
+      }
+
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
+                     .addReg(NewVReg1)
+                     .addReg(VReg2));
+    } else {
+      MachineConstantPool *ConstantPool =3D MF->getConstantPool();
+      Type *Int32Ty =3D Type::getInt32Ty(MF->getFunction()->getContext());
+      const Constant *C =3D ConstantInt::get(Int32Ty, NumLPads);
+
+      // MachineConstantPool wants an explicit alignment.
+      unsigned Align =3D getTargetData()->getPrefTypeAlignment(Int32Ty);
+      if (Align =3D=3D 0)
+        Align =3D getTargetData()->getTypeAllocSize(C->getType());
+      unsigned Idx =3D ConstantPool->getConstantPoolIndex(C, Align);
+
+      unsigned VReg1 =3D MRI->createVirtualRegister(TRC);
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
+                     .addReg(VReg1, RegState::Define)
+                     .addConstantPoolIndex(Idx)
+                     .addImm(0));
+      AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
+                     .addReg(NewVReg1)
+                     .addReg(VReg1, RegState::Kill));
+    }
+
     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
       .addMBB(TrapBB)
       .addImm(ARMCC::HI)
       .addReg(ARM::CPSR);
=20
-    unsigned NewVReg2 =3D MRI->createVirtualRegister(TRC);
+    unsigned NewVReg3 =3D MRI->createVirtualRegister(TRC);
     AddDefaultCC(
-      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg=
2)
+      AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg=
3)
                      .addReg(NewVReg1)
                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
-    unsigned NewVReg3 =3D MRI->createVirtualRegister(TRC);
-    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewV=
Reg3)
+    unsigned NewVReg4 =3D MRI->createVirtualRegister(TRC);
+    AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewV=
Reg4)
                    .addJumpTableIndex(MJTI)
                    .addImm(UId));
=20
     MachineMemOperand *JTMMOLd =3D
       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
                                MachineMemOperand::MOLoad, 4, 4);
-    unsigned NewVReg4 =3D MRI->createVirtualRegister(TRC);
+    unsigned NewVReg5 =3D MRI->createVirtualRegister(TRC);
     AddDefaultPred(
-      BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg4)
-      .addReg(NewVReg2, RegState::Kill)
-      .addReg(NewVReg3)
+      BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
+      .addReg(NewVReg3, RegState::Kill)
+      .addReg(NewVReg4)
       .addImm(0)
       .addMemOperand(JTMMOLd));
=20
     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
-      .addReg(NewVReg4, RegState::Kill)
-      .addReg(NewVReg3)
+      .addReg(NewVReg5, RegState::Kill)
+      .addReg(NewVReg4)
       .addJumpTableIndex(MJTI)
       .addImm(UId);
   }
@@ -5893,21 +6132,24 @@
     PrevMBB =3D CurMBB;
   }
=20
+  // N.B. the order the invoke BBs are processed in doesn't matter here.
   const ARMBaseInstrInfo *AII =3D static_cast<const ARMBaseInstrInfo*>(TII=
);
   const ARMBaseRegisterInfo &RI =3D AII->getRegisterInfo();
-  const unsigned *SavedRegs =3D RI.getCalleeSavedRegs(MF);
+  const uint16_t *SavedRegs =3D RI.getCalleeSavedRegs(MF);
+  SmallVector<MachineBasicBlock*, 64> MBBLPads;
   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
          I =3D InvokeBBs.begin(), E =3D InvokeBBs.end(); I !=3D E; ++I) {
     MachineBasicBlock *BB =3D *I;
=20
     // Remove the landing pad successor from the invoke block and replace =
it
     // with the new dispatch block.
-    for (MachineBasicBlock::succ_iterator
-           SI =3D BB->succ_begin(), SE =3D BB->succ_end(); SI !=3D SE; ++S=
I) {
-      MachineBasicBlock *SMBB =3D *SI;
+    SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
+                                                  BB->succ_end());
+    while (!Successors.empty()) {
+      MachineBasicBlock *SMBB =3D Successors.pop_back_val();
       if (SMBB->isLandingPad()) {
         BB->removeSuccessor(SMBB);
-        SMBB->setIsLandingPad(false);
+        MBBLPads.push_back(SMBB);
       }
     }
=20
@@ -5919,7 +6161,7 @@
     // executed.
     for (MachineBasicBlock::reverse_iterator
            II =3D BB->rbegin(), IE =3D BB->rend(); II !=3D IE; ++II) {
-      if (!II->getDesc().isCall()) continue;
+      if (!II->isCall()) continue;
=20
       DenseMap<unsigned, bool> DefRegs;
       for (MachineInstr::mop_iterator
@@ -5932,15 +6174,31 @@
       MachineInstrBuilder MIB(&*II);
=20
       for (unsigned i =3D 0; SavedRegs[i] !=3D 0; ++i) {
-        if (!TRC->contains(SavedRegs[i])) continue;
-        if (!DefRegs[SavedRegs[i]])
-          MIB.addReg(SavedRegs[i], RegState::ImplicitDefine | RegState::De=
ad);
+        unsigned Reg =3D SavedRegs[i];
+        if (Subtarget->isThumb2() &&
+            !ARM::tGPRRegisterClass->contains(Reg) &&
+            !ARM::hGPRRegisterClass->contains(Reg))
+          continue;
+        else if (Subtarget->isThumb1Only() &&
+                 !ARM::tGPRRegisterClass->contains(Reg))
+          continue;
+        else if (!Subtarget->isThumb() &&
+                 !ARM::GPRRegisterClass->contains(Reg))
+          continue;
+        if (!DefRegs[Reg])
+          MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
       }
=20
       break;
     }
   }
=20
+  // Mark all former landing pads as non-landing pads. The dispatch is the=
 only
+  // landing pad now.
+  for (SmallVectorImpl<MachineBasicBlock*>::iterator
+         I =3D MBBLPads.begin(), E =3D MBBLPads.end(); I !=3D E; ++I)
+    (*I)->setIsLandingPad(false);
+
   // The instruction is gone now.
   MI->eraseFromParent();
=20
@@ -6222,20 +6480,28 @@
     return BB;
   }
=20
+  case ARM::Int_eh_sjlj_setjmp:
+  case ARM::Int_eh_sjlj_setjmp_nofp:
+  case ARM::tInt_eh_sjlj_setjmp:
+  case ARM::t2Int_eh_sjlj_setjmp:
+  case ARM::t2Int_eh_sjlj_setjmp_nofp:
+    EmitSjLjDispatchBlock(MI, BB);
+    return BB;
+
   case ARM::ABS:
   case ARM::t2ABS: {
     // To insert an ABS instruction, we have to insert the
     // diamond control-flow pattern.  The incoming instruction knows the
     // source vreg to test against 0, the destination vreg to set,
     // the condition code register to branch on, the
-    // true/false values to select between, and a branch opcode to use.=20
+    // true/false values to select between, and a branch opcode to use.
     // It transforms
     //     V1 =3D ABS V0
     // into
     //     V2 =3D MOVS V0
     //     BCC                      (branch to SinkBB if V0 >=3D 0)
     //     RSBBB: V3 =3D RSBri V2, 0  (compute ABS if V2 < 0)
-    //     SinkBB: V1 =3D PHI(V2, V3)    =20
+    //     SinkBB: V1 =3D PHI(V2, V3)
     const BasicBlock *LLVM_BB =3D BB->getBasicBlock();
     MachineFunction::iterator BBI =3D BB;
     ++BBI;
@@ -6276,19 +6542,19 @@
       .addReg(ARM::CPSR, RegState::Define);
=20
     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
-    BuildMI(BB, dl,=20
+    BuildMI(BB, dl,
       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
=20
     // insert rsbri in RSBBB
     // Note: BCC and rsbri will be converted into predicated rsbmi
     // by if-conversion pass
-    BuildMI(*RSBBB, RSBBB->begin(), dl,=20
+    BuildMI(*RSBBB, RSBBB->begin(), dl,
       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
       .addReg(NewMovDstReg, RegState::Kill)
       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
=20
-    // insert PHI in SinkBB,=20
+    // insert PHI in SinkBB,
     // reuse ABSDstReg to not change uses of ABS instruction
     BuildMI(*SinkBB, SinkBB->begin(), dl,
       TII->get(ARM::PHI), ABSDstReg)
@@ -6296,7 +6562,7 @@
       .addReg(NewMovDstReg).addMBB(BB);
=20
     // remove ABS instruction
-    MI->eraseFromParent();=20
+    MI->eraseFromParent();
=20
     // return last added BB
     return SinkBB;
@@ -6306,32 +6572,40 @@
=20
 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
                                                       SDNode *Node) const {
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.hasPostISelHook()) {
+  if (!MI->hasPostISelHook()) {
     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHo=
ok'");
     return;
   }
=20
+  const MCInstrDesc *MCID =3D &MI->getDesc();
   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC=
, RSB,
   // RSC. Coming out of isel, they have an implicit CPSR def, but the opti=
onal
   // operand is still set to noreg. If needed, set the optional operand's
   // register to CPSR, and remove the redundant implicit def.
   //
-  // e.g. ADCS (...opt:%noreg, CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
+  // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
=20
   // Rename pseudo opcodes.
   unsigned NewOpc =3D convertAddSubFlagsOpcode(MI->getOpcode());
   if (NewOpc) {
     const ARMBaseInstrInfo *TII =3D
       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo=
());
-    MI->setDesc(TII->get(NewOpc));
-  }
-  unsigned ccOutIdx =3D MCID.getNumOperands() - 1;
+    MCID =3D &TII->get(NewOpc);
+
+    assert(MCID->getNumOperands() =3D=3D MI->getDesc().getNumOperands() + =
1 &&
+           "converted opcode should be the same except for cc_out");
+
+    MI->setDesc(*MCID);
+
+    // Add the optional cc_out operand
+    MI->addOperand(MachineOperand::CreateReg(0, /*isDef=3D*/true));
+  }
+  unsigned ccOutIdx =3D MCID->getNumOperands() - 1;
=20
   // Any ARM instruction that sets the 's' bit should specify an optional
   // "cc_out" operand in the last operand position.
-  if (!MCID.hasOptionalDef() || !MCID.OpInfo[ccOutIdx].isOptionalDef()) {
+  if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
     assert(!NewOpc && "Optional cc_out operand required");
     return;
   }
@@ -6339,7 +6613,7 @@
   // since we already have an optional CPSR def.
   bool definesCPSR =3D false;
   bool deadCPSR =3D false;
-  for (unsigned i =3D MCID.getNumOperands(), e =3D MI->getNumOperands();
+  for (unsigned i =3D MCID->getNumOperands(), e =3D MI->getNumOperands();
        i !=3D e; ++i) {
     const MachineOperand &MO =3D MI->getOperand(i);
     if (MO.isReg() && MO.isDef() && MO.getReg() =3D=3D ARM::CPSR) {
@@ -6513,7 +6787,7 @@
     case MVT::i16: widenType =3D MVT::getVectorVT(MVT::i32, numElem); brea=
k;
     case MVT::i32: widenType =3D MVT::getVectorVT(MVT::i64, numElem); brea=
k;
     default:
-      assert(0 && "Invalid vector element type for padd optimization.");
+      llvm_unreachable("Invalid vector element type for padd optimization.=
");
   }
=20
   SDValue tmp =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
@@ -6632,41 +6906,115 @@
   if (!C)
     return SDValue();
=20
-  uint64_t MulAmt =3D C->getZExtValue();
+  int64_t MulAmt =3D C->getSExtValue();
   unsigned ShiftAmt =3D CountTrailingZeros_64(MulAmt);
+
   ShiftAmt =3D ShiftAmt & (32 - 1);
   SDValue V =3D N->getOperand(0);
   DebugLoc DL =3D N->getDebugLoc();
=20
   SDValue Res;
   MulAmt >>=3D ShiftAmt;
-  if (isPowerOf2_32(MulAmt - 1)) {
-    // (mul x, 2^N + 1) =3D> (add (shl x, N), x)
-    Res =3D DAG.getNode(ISD::ADD, DL, VT,
-                      V, DAG.getNode(ISD::SHL, DL, VT,
-                                     V, DAG.getConstant(Log2_32(MulAmt-1),
-                                                        MVT::i32)));
-  } else if (isPowerOf2_32(MulAmt + 1)) {
-    // (mul x, 2^N - 1) =3D> (sub (shl x, N), x)
-    Res =3D DAG.getNode(ISD::SUB, DL, VT,
-                      DAG.getNode(ISD::SHL, DL, VT,
-                                  V, DAG.getConstant(Log2_32(MulAmt+1),
-                                                     MVT::i32)),
-                                                     V);
-  } else
-    return SDValue();
+
+  if (MulAmt >=3D 0) {
+    if (isPowerOf2_32(MulAmt - 1)) {
+      // (mul x, 2^N + 1) =3D> (add (shl x, N), x)
+      Res =3D DAG.getNode(ISD::ADD, DL, VT,
+                        V,
+                        DAG.getNode(ISD::SHL, DL, VT,
+                                    V,
+                                    DAG.getConstant(Log2_32(MulAmt - 1),
+                                                    MVT::i32)));
+    } else if (isPowerOf2_32(MulAmt + 1)) {
+      // (mul x, 2^N - 1) =3D> (sub (shl x, N), x)
+      Res =3D DAG.getNode(ISD::SUB, DL, VT,
+                        DAG.getNode(ISD::SHL, DL, VT,
+                                    V,
+                                    DAG.getConstant(Log2_32(MulAmt + 1),
+                                                    MVT::i32)),
+                        V);
+    } else
+      return SDValue();
+  } else {
+    uint64_t MulAmtAbs =3D -MulAmt;
+    if (isPowerOf2_32(MulAmtAbs + 1)) {
+      // (mul x, -(2^N - 1)) =3D> (sub x, (shl x, N))
+      Res =3D DAG.getNode(ISD::SUB, DL, VT,
+                        V,
+                        DAG.getNode(ISD::SHL, DL, VT,
+                                    V,
+                                    DAG.getConstant(Log2_32(MulAmtAbs + 1),
+                                                    MVT::i32)));
+    } else if (isPowerOf2_32(MulAmtAbs - 1)) {
+      // (mul x, -(2^N + 1)) =3D> - (add (shl x, N), x)
+      Res =3D DAG.getNode(ISD::ADD, DL, VT,
+                        V,
+                        DAG.getNode(ISD::SHL, DL, VT,
+                                    V,
+                                    DAG.getConstant(Log2_32(MulAmtAbs-1),
+                                                    MVT::i32)));
+      Res =3D DAG.getNode(ISD::SUB, DL, VT,
+                        DAG.getConstant(0, MVT::i32),Res);
+
+    } else
+      return SDValue();
+  }
=20
   if (ShiftAmt !=3D 0)
-    Res =3D DAG.getNode(ISD::SHL, DL, VT, Res,
-                      DAG.getConstant(ShiftAmt, MVT::i32));
+    Res =3D DAG.getNode(ISD::SHL, DL, VT,
+                      Res, DAG.getConstant(ShiftAmt, MVT::i32));
=20
   // Do not add new nodes to DAG combiner worklist.
   DCI.CombineTo(N, Res, false);
   return SDValue();
 }
=20
+static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
+  if (N.getOpcode() !=3D ARMISD::CMOV || !N.getNode()->hasOneUse())
+    return false;
+
+  SDValue FalseVal =3D N.getOperand(0);
+  ConstantSDNode *C =3D dyn_cast<ConstantSDNode>(FalseVal);
+  if (!C)
+    return false;
+  if (AllOnes)
+    return C->isAllOnesValue();
+  return C->isNullValue();
+}
+
+/// formConditionalOp - Combine an operation with a conditional move opera=
nd
+/// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) =3D> (or.cond=
 x, y)
+/// (and x, (cmov -1, y, cond)) =3D> (and.cond, x, y)
+static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
+                                 bool Commutable) {
+  SDValue N0 =3D N->getOperand(0);
+  SDValue N1 =3D N->getOperand(1);
+
+  bool isAND =3D N->getOpcode() =3D=3D ISD::AND;
+  bool isCand =3D isCMOVWithZeroOrAllOnesLHS(N1, isAND);
+  if (!isCand && Commutable) {
+    isCand =3D isCMOVWithZeroOrAllOnesLHS(N0, isAND);
+    if (isCand)
+      std::swap(N0, N1);
+  }
+  if (!isCand)
+    return SDValue();
+
+  unsigned Opc =3D 0;
+  switch (N->getOpcode()) {
+  default: llvm_unreachable("Unexpected node");
+  case ISD::AND: Opc =3D ARMISD::CAND; break;
+  case ISD::OR:  Opc =3D ARMISD::COR; break;
+  case ISD::XOR: Opc =3D ARMISD::CXOR; break;
+  }
+  return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
+                     N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
+                     N1.getOperand(4));
+}
+
 static SDValue PerformANDCombine(SDNode *N,
-                                TargetLowering::DAGCombinerInfo &DCI) {
+                                 TargetLowering::DAGCombinerInfo &DCI,
+                                 const ARMSubtarget *Subtarget) {
=20
   // Attempt to use immediate-form VBIC
   BuildVectorSDNode *BVN =3D dyn_cast<BuildVectorSDNode>(N->getOperand(1));
@@ -6697,6 +7045,13 @@
     }
   }
=20
+  if (!Subtarget->isThumb1Only()) {
+    // (and x, (cmov -1, y, cond)) =3D> (and.cond x, y)
+    SDValue CAND =3D formConditionalOp(N, DAG, true);
+    if (CAND.getNode())
+      return CAND;
+  }
+
   return SDValue();
 }
=20
@@ -6733,6 +7088,13 @@
     }
   }
=20
+  if (!Subtarget->isThumb1Only()) {
+    // (or x, (cmov 0, y, cond)) =3D> (or.cond x, y)
+    SDValue COR =3D formConditionalOp(N, DAG, true);
+    if (COR.getNode())
+      return COR;
+  }
+
   SDValue N0 =3D N->getOperand(0);
   if (N0.getOpcode() !=3D ISD::AND)
     return SDValue();
@@ -6881,6 +7243,25 @@
   return SDValue();
 }
=20
+static SDValue PerformXORCombine(SDNode *N,
+                                 TargetLowering::DAGCombinerInfo &DCI,
+                                 const ARMSubtarget *Subtarget) {
+  EVT VT =3D N->getValueType(0);
+  SelectionDAG &DAG =3D DCI.DAG;
+
+  if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
+    return SDValue();
+
+  if (!Subtarget->isThumb1Only()) {
+    // (xor x, (cmov 0, y, cond)) =3D> (xor.cond x, y)
+    SDValue CXOR =3D formConditionalOp(N, DAG, true);
+    if (CXOR.getNode())
+      return CXOR;
+  }
+
+  return SDValue();
+}
+
 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2=
) iff
 /// the bits being cleared by the AND are not demanded by the BFI.
 static SDValue PerformBFICombine(SDNode *N,
@@ -6926,13 +7307,14 @@
     SDValue BasePtr =3D LD->getBasePtr();
     SDValue NewLD1 =3D DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
                                  LD->getPointerInfo(), LD->isVolatile(),
-                                 LD->isNonTemporal(), LD->getAlignment());
+                                 LD->isNonTemporal(), LD->isInvariant(),
+                                 LD->getAlignment());
=20
     SDValue OffsetPtr =3D DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
                                     DAG.getConstant(4, MVT::i32));
     SDValue NewLD2 =3D DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), Offse=
tPtr,
                                  LD->getPointerInfo(), LD->isVolatile(),
-                                 LD->isNonTemporal(),
+                                 LD->isNonTemporal(), LD->isInvariant(),
                                  std::min(4U, LD->getAlignment() / 2));
=20
     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
@@ -6967,15 +7349,99 @@
 /// ISD::STORE.
 static SDValue PerformSTORECombine(SDNode *N,
                                    TargetLowering::DAGCombinerInfo &DCI) {
-  // Bitcast an i64 store extracted from a vector to f64.
-  // Otherwise, the i64 value will be legalized to a pair of i32 values.
   StoreSDNode *St =3D cast<StoreSDNode>(N);
+  if (St->isVolatile())
+    return SDValue();
+
+  // Optimize trunc store (of multiple scalars) to shuffle and store.  Fir=
st,=20
+  // pack all of the elements in one place.  Next, store to memory in fewer
+  // chunks.
   SDValue StVal =3D St->getValue();
-  if (!ISD::isNormalStore(St) || St->isVolatile())
+  EVT VT =3D StVal.getValueType();
+  if (St->isTruncatingStore() && VT.isVector()) {
+    SelectionDAG &DAG =3D DCI.DAG;
+    const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
+    EVT StVT =3D St->getMemoryVT();
+    unsigned NumElems =3D VT.getVectorNumElements();
+    assert(StVT !=3D VT && "Cannot truncate to the same type");
+    unsigned FromEltSz =3D VT.getVectorElementType().getSizeInBits();
+    unsigned ToEltSz =3D StVT.getVectorElementType().getSizeInBits();
+
+    // From, To sizes and ElemCount must be pow of two
+    if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
+
+    // We are going to use the original vector elt for storing.
+    // Accumulated smaller vector elements must be a multiple of the store=
 size.
+    if (0 !=3D (NumElems * FromEltSz) % ToEltSz) return SDValue();
+
+    unsigned SizeRatio  =3D FromEltSz / ToEltSz;
+    assert(SizeRatio * NumElems * ToEltSz =3D=3D VT.getSizeInBits());
+
+    // Create a type on which we perform the shuffle.
+    EVT WideVecVT =3D EVT::getVectorVT(*DAG.getContext(), StVT.getScalarTy=
pe(),
+                                     NumElems*SizeRatio);
+    assert(WideVecVT.getSizeInBits() =3D=3D VT.getSizeInBits());
+
+    DebugLoc DL =3D St->getDebugLoc();
+    SDValue WideVec =3D DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
+    SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
+    for (unsigned i =3D 0; i < NumElems; ++i) ShuffleVec[i] =3D i * SizeRa=
tio;
+
+    // Can't shuffle using an illegal type.
+    if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
+
+    SDValue Shuff =3D DAG.getVectorShuffle(WideVecVT, DL, WideVec,
+                                DAG.getUNDEF(WideVec.getValueType()),
+                                ShuffleVec.data());
+    // At this point all of the data is stored at the bottom of the
+    // register. We now need to save it to mem.
+
+    // Find the largest store unit
+    MVT StoreType =3D MVT::i8;
+    for (unsigned tp =3D MVT::FIRST_INTEGER_VALUETYPE;
+         tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
+      MVT Tp =3D (MVT::SimpleValueType)tp;
+      if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <=3D NumElems * ToEltS=
z)
+        StoreType =3D Tp;
+    }
+    // Didn't find a legal store type.
+    if (!TLI.isTypeLegal(StoreType))
+      return SDValue();
+
+    // Bitcast the original vector into a vector of store-size units
+    EVT StoreVecVT =3D EVT::getVectorVT(*DAG.getContext(),
+            StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
+    assert(StoreVecVT.getSizeInBits() =3D=3D VT.getSizeInBits());
+    SDValue ShuffWide =3D DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
+    SmallVector<SDValue, 8> Chains;
+    SDValue Increment =3D DAG.getConstant(StoreType.getSizeInBits()/8,
+                                        TLI.getPointerTy());
+    SDValue BasePtr =3D St->getBasePtr();
+
+    // Perform one or more big stores into memory.
+    unsigned E =3D (ToEltSz*NumElems)/StoreType.getSizeInBits();
+    for (unsigned I =3D 0; I < E; I++) {
+      SDValue SubVec =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
+                                   StoreType, ShuffWide,
+                                   DAG.getIntPtrConstant(I));
+      SDValue Ch =3D DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
+                                St->getPointerInfo(), St->isVolatile(),
+                                St->isNonTemporal(), St->getAlignment());
+      BasePtr =3D DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePt=
r,
+                            Increment);
+      Chains.push_back(Ch);
+    }
+    return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
+                       Chains.size());
+  }
+
+  if (!ISD::isNormalStore(St))
     return SDValue();
=20
+  // Split a store of a VMOVDRR into two integer stores to avoid mixing NE=
ON and
+  // ARM stores of arguments in the same cache line.
   if (StVal.getNode()->getOpcode() =3D=3D ARMISD::VMOVDRR &&
-      StVal.getNode()->hasOneUse() && !St->isVolatile()) {
+      StVal.getNode()->hasOneUse()) {
     SelectionDAG  &DAG =3D DCI.DAG;
     DebugLoc DL =3D St->getDebugLoc();
     SDValue BasePtr =3D St->getBasePtr();
@@ -6996,6 +7462,8 @@
       StVal.getNode()->getOpcode() !=3D ISD::EXTRACT_VECTOR_ELT)
     return SDValue();
=20
+  // Bitcast an i64 store extracted from a vector to f64.
+  // Otherwise, the i64 value will be legalized to a pair of i32 values.
   SelectionDAG &DAG =3D DCI.DAG;
   DebugLoc dl =3D StVal.getDebugLoc();
   SDValue IntVec =3D StVal.getOperand(0);
@@ -7177,7 +7645,7 @@
     if (isIntrinsic) {
       unsigned IntNo =3D cast<ConstantSDNode>(N->getOperand(1))->getZExtVa=
lue();
       switch (IntNo) {
-      default: assert(0 && "unexpected intrinsic for Neon base update");
+      default: llvm_unreachable("unexpected intrinsic for Neon base update=
");
       case Intrinsic::arm_neon_vld1:     NewOpc =3D ARMISD::VLD1_UPD;
         NumVecs =3D 1; break;
       case Intrinsic::arm_neon_vld2:     NewOpc =3D ARMISD::VLD2_UPD;
@@ -7210,7 +7678,7 @@
     } else {
       isLaneOp =3D true;
       switch (N->getOpcode()) {
-      default: assert(0 && "unexpected opcode for Neon base update");
+      default: llvm_unreachable("unexpected opcode for Neon base update");
       case ARMISD::VLD2DUP: NewOpc =3D ARMISD::VLD2DUP_UPD; NumVecs =3D 2;=
 break;
       case ARMISD::VLD3DUP: NewOpc =3D ARMISD::VLD3DUP_UPD; NumVecs =3D 3;=
 break;
       case ARMISD::VLD4DUP: NewOpc =3D ARMISD::VLD4DUP_UPD; NumVecs =3D 4;=
 break;
@@ -7703,6 +8171,18 @@
 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
                                    const ARMSubtarget *ST) {
   EVT VT =3D N->getValueType(0);
+  if (N->getOpcode() =3D=3D ISD::SRL && VT =3D=3D MVT::i32 && ST->hasV6Ops=
()) {
+    // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
+    // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
+    SDValue N1 =3D N->getOperand(1);
+    if (ConstantSDNode *C =3D dyn_cast<ConstantSDNode>(N1)) {
+      SDValue N0 =3D N->getOperand(0);
+      if (C->getZExtValue() =3D=3D 16 && N0.getOpcode() =3D=3D ISD::BSWAP =
&&
+          DAG.MaskedValueIsZero(N0.getOperand(0),
+                                APInt::getHighBitsSet(32, 16)))
+        return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
+    }
+  }
=20
   // Nothing to be done for scalar shifts.
   const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
@@ -7824,7 +8304,7 @@
     // will return -0, so vmin can only be used for unsafe math or if one =
of
     // the operands is known to be nonzero.
     if ((CC =3D=3D ISD::SETLE || CC =3D=3D ISD::SETOLE || CC =3D=3D ISD::S=
ETULE) &&
-        !UnsafeFPMath &&
+        !DAG.getTarget().Options.UnsafeFPMath &&
         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
       break;
     Opcode =3D IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
@@ -7846,7 +8326,7 @@
     // will return +0, so vmax can only be used for unsafe math or if one =
of
     // the operands is known to be nonzero.
     if ((CC =3D=3D ISD::SETGE || CC =3D=3D ISD::SETOGE || CC =3D=3D ISD::S=
ETUGE) &&
-        !UnsafeFPMath &&
+        !DAG.getTarget().Options.UnsafeFPMath &&
         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
       break;
     Opcode =3D IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
@@ -7906,8 +8386,7 @@
=20
   if (Res.getNode()) {
     APInt KnownZero, KnownOne;
-    APInt Mask =3D APInt::getAllOnesValue(VT.getScalarType().getSizeInBits=
());
-    DAG.ComputeMaskedBits(SDValue(N,0), Mask, KnownZero, KnownOne);
+    DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
     // Capture demanded bits information that would be otherwise lost.
     if (KnownZero =3D=3D 0xfffffffe)
       Res =3D DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
@@ -7931,7 +8410,8 @@
   case ISD::SUB:        return PerformSUBCombine(N, DCI);
   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
-  case ISD::AND:        return PerformANDCombine(N, DCI);
+  case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
+  case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
@@ -8001,6 +8481,41 @@
   }
 }
=20
+static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
+                       unsigned AlignCheck) {
+  return ((SrcAlign =3D=3D 0 || SrcAlign % AlignCheck =3D=3D 0) &&
+          (DstAlign =3D=3D 0 || DstAlign % AlignCheck =3D=3D 0));
+}
+
+EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
+                                           unsigned DstAlign, unsigned Src=
Align,
+                                           bool IsZeroVal,
+                                           bool MemcpyStrSrc,
+                                           MachineFunction &MF) const {
+  const Function *F =3D MF.getFunction();
+
+  // See if we can use NEON instructions for this...
+  if (IsZeroVal &&
+      !F->hasFnAttr(Attribute::NoImplicitFloat) &&
+      Subtarget->hasNEON()) {
+    if (memOpAlign(SrcAlign, DstAlign, 16) && Size >=3D 16) {
+      return MVT::v4i32;
+    } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >=3D 8) {
+      return MVT::v2i32;
+    }
+  }
+
+  // Lowering to i32/i16 if the size permits.
+  if (Size >=3D 4) {
+    return MVT::i32;
+  } else if (Size >=3D 2) {
+    return MVT::i16;
+  }
+
+  // Let the target-independent logic figure it out.
+  return MVT::Other;
+}
+
 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
   if (V < 0)
     return false;
@@ -8188,7 +8703,6 @@
       if (Scale & 1) return false;
       return isPowerOf2_32(Scale);
     }
-    break;
   }
   return true;
 }
@@ -8198,10 +8712,12 @@
 /// a register against the immediate without having to materialize the
 /// immediate into a register.
 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
+  // Thumb2 and ARM modes can use cmn for negative immediates.
   if (!Subtarget->isThumb())
-    return ARM_AM::getSOImmVal(Imm) !=3D -1;
+    return ARM_AM::getSOImmVal(llvm::abs64(Imm)) !=3D -1;
   if (Subtarget->isThumb2())
-    return ARM_AM::getT2SOImmVal(Imm) !=3D -1;
+    return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) !=3D -1;
+  // Thumb1 doesn't have cmn, and only 8-bit immediates.
   return Imm >=3D 0 && Imm <=3D 255;
 }
=20
@@ -8388,22 +8904,20 @@
 }
=20
 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
-                                                       const APInt &Mask,
                                                        APInt &KnownZero,
                                                        APInt &KnownOne,
                                                        const SelectionDAG =
&DAG,
                                                        unsigned Depth) con=
st {
-  KnownZero =3D KnownOne =3D APInt(Mask.getBitWidth(), 0);
+  KnownZero =3D KnownOne =3D APInt(KnownOne.getBitWidth(), 0);
   switch (Op.getOpcode()) {
   default: break;
   case ARMISD::CMOV: {
     // Bits are known zero/one if known on the LHS and RHS.
-    DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Dep=
th+1);
+    DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
     if (KnownZero =3D=3D 0 && KnownOne =3D=3D 0) return;
=20
     APInt KnownZeroRHS, KnownOneRHS;
-    DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
-                          KnownZeroRHS, KnownOneRHS, Depth+1);
+    DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Dep=
th+1);
     KnownZero &=3D KnownZeroRHS;
     KnownOne  &=3D KnownOneRHS;
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIS=
elLowering.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMISelLowering.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMISelLowering.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -15,6 +15,7 @@
 #ifndef ARMISELLOWERING_H
 #define ARMISELLOWERING_H
=20
+#include "ARM.h"
 #include "ARMSubtarget.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetRegisterInfo.h"
@@ -56,7 +57,11 @@
       CMPFP,        // ARM VFP compare instruction, sets FPSCR.
       CMPFPw0,      // ARM VFP compare against zero instruction, sets FPSC=
R.
       FMSTAT,       // ARM fmstat instruction.
+
       CMOV,         // ARM conditional move instructions.
+      CAND,         // ARM conditional and instructions.
+      COR,          // ARM conditional or instructions.
+      CXOR,         // ARM conditional xor instructions.
=20
       BCC_i64,
=20
@@ -81,7 +86,6 @@
=20
       EH_SJLJ_SETJMP,         // SjLj exception handling setjmp.
       EH_SJLJ_LONGJMP,        // SjLj exception handling longjmp.
-      EH_SJLJ_DISPATCHSETUP,  // SjLj exception handling dispatch setup.
=20
       TC_RETURN,    // Tail call return pseudo.
=20
@@ -146,6 +150,9 @@
       VMOVIMM,
       VMVNIMM,
=20
+      // Vector move f32 immediate:
+      VMOVFPIMM,
+
       // Vector duplicate:
       VDUP,
       VDUPLANE,
@@ -266,9 +273,14 @@
=20
     /// allowsUnalignedMemoryAccesses - Returns true if the target allows
     /// unaligned memory accesses. of the specified type.
-    /// FIXME: Add getOptimalMemOpType to implement memcpy with NEON?
     virtual bool allowsUnalignedMemoryAccesses(EVT VT) const;
=20
+    virtual EVT getOptimalMemOpType(uint64_t Size,
+                                    unsigned DstAlign, unsigned SrcAlign,
+                                    bool IsZeroVal,
+                                    bool MemcpyStrSrc,
+                                    MachineFunction &MF) const;
+
     /// isLegalAddressingMode - Return true if the addressing mode represe=
nted
     /// by AM is legal for this target, for a load/store of the specified =
type.
     virtual bool isLegalAddressingMode(const AddrMode &AM, Type *Ty)const;
@@ -303,7 +315,6 @@
                                             SelectionDAG &DAG) const;
=20
     virtual void computeMaskedBitsForTargetNode(const SDValue Op,
-                                                const APInt &Mask,
                                                 APInt &KnownZero,
                                                 APInt &KnownOne,
                                                 const SelectionDAG &DAG,
@@ -338,7 +349,7 @@
=20
     /// getRegClassFor - Return the register class that should be used for=
 the
     /// specified value type.
-    virtual TargetRegisterClass *getRegClassFor(EVT VT) const;
+    virtual const TargetRegisterClass *getRegClassFor(EVT VT) const;
=20
     /// getMaximalGlobalOffset - Returns the maximal possible offset which=
 can
     /// be used for loads / stores from the global.
@@ -402,7 +413,6 @@
                              ISD::ArgFlagsTy Flags) const;
     SDValue LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const;
-    SDValue LowerEH_SJLJ_DISPATCHSETUP(SDValue Op, SelectionDAG &DAG) cons=
t;
     SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
                                     const ARMSubtarget *Subtarget) const;
     SDValue LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const;
@@ -424,6 +434,8 @@
     SDValue LowerShiftRightParts(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) const;
+    SDValue LowerConstantFP(SDValue Op, SelectionDAG &DAG,
+                            const ARMSubtarget *ST) const;
     SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
                               const ARMSubtarget *ST) const;
=20
@@ -452,7 +464,7 @@
     virtual SDValue
       LowerCall(SDValue Chain, SDValue Callee,
                 CallingConv::ID CallConv, bool isVarArg,
-                bool &isTailCall,
+                bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -481,7 +493,7 @@
                   const SmallVectorImpl<SDValue> &OutVals,
                   DebugLoc dl, SelectionDAG &DAG) const;
=20
-    virtual bool isUsedByReturnOnly(SDNode *N) const;
+    virtual bool isUsedByReturnOnly(SDNode *N, SDValue &Chain) const;
=20
     virtual bool mayBeEmittedAsTailCall(CallInst *CI) const;
=20
@@ -512,9 +524,6 @@
                                                bool signExtend,
                                                ARMCC::CondCodes Cond) cons=
t;
=20
-    void EmitBasePointerRecalculation(MachineInstr *MI, MachineBasicBlock =
*MBB,
-                                      MachineBasicBlock *DispatchBB) const;
-
     void SetupEntryBlockForSjLj(MachineInstr *MI,
                                 MachineBasicBlock *MBB,
                                 MachineBasicBlock *DispatchBB, int FI) con=
st;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strFormats.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrFormats.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrFormats.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMInstrFormats.td - ARM Instruction Formats ----------*- tab=
legen -*-=3D//
+//=3D=3D=3D-- ARMInstrFormats.td - ARM Instruction Formats -------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -174,7 +174,7 @@
=20
 // ARM special operands for disassembly only.
 //
-def SetEndAsmOperand : AsmOperandClass {
+def SetEndAsmOperand : ImmAsmOperand {
   let Name =3D "SetEndImm";
   let ParserMethod =3D "parseSetEndImm";
 }
@@ -201,21 +201,29 @@
 //     16       imm6<5:4> =3D '01', 16 - <imm> is encoded in imm6<3:0>
 //     32       imm6<5> =3D '1', 32 - <imm> is encoded in imm6<4:0>
 //     64       64 - <imm> is encoded in imm6<5:0>
+def shr_imm8_asm_operand : ImmAsmOperand { let Name =3D "ShrImm8"; }
 def shr_imm8  : Operand<i32> {
   let EncoderMethod =3D "getShiftRight8Imm";
   let DecoderMethod =3D "DecodeShiftRight8Imm";
+  let ParserMatchClass =3D shr_imm8_asm_operand;
 }
+def shr_imm16_asm_operand : ImmAsmOperand { let Name =3D "ShrImm16"; }
 def shr_imm16 : Operand<i32> {
   let EncoderMethod =3D "getShiftRight16Imm";
   let DecoderMethod =3D "DecodeShiftRight16Imm";
+  let ParserMatchClass =3D shr_imm16_asm_operand;
 }
+def shr_imm32_asm_operand : ImmAsmOperand { let Name =3D "ShrImm32"; }
 def shr_imm32 : Operand<i32> {
   let EncoderMethod =3D "getShiftRight32Imm";
   let DecoderMethod =3D "DecodeShiftRight32Imm";
+  let ParserMatchClass =3D shr_imm32_asm_operand;
 }
+def shr_imm64_asm_operand : ImmAsmOperand { let Name =3D "ShrImm64"; }
 def shr_imm64 : Operand<i32> {
   let EncoderMethod =3D "getShiftRight64Imm";
   let DecoderMethod =3D "DecodeShiftRight64Imm";
+  let ParserMatchClass =3D shr_imm64_asm_operand;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -231,6 +239,14 @@
       : InstAlias<Asm, Result, Emit>, Requires<[HasVFP2]>;
 class VFP3InstAlias<string Asm, dag Result, bit Emit =3D 0b1>
       : InstAlias<Asm, Result, Emit>, Requires<[HasVFP3]>;
+class NEONInstAlias<string Asm, dag Result, bit Emit =3D 0b1>
+      : InstAlias<Asm, Result, Emit>, Requires<[HasNEON]>;
+
+
+class VFP2MnemonicAlias<string src, string dst> : MnemonicAlias<src, dst>,
+          Requires<[HasVFP2]>;
+class NEONMnemonicAlias<string src, string dst> : MnemonicAlias<src, dst>,
+          Requires<[HasNEON]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ARM Instruction templates.
@@ -274,6 +290,14 @@
=20
 class Encoding {
   field bits<32> Inst;
+  // Mask of bits that cause an encoding to be UNPREDICTABLE.
+  // If a bit is set, then if the corresponding bit in the
+  // target encoding differs from its value in the "Inst" field,
+  // the instruction is UNPREDICTABLE (SoftFail in abstract parlance).
+  field bits<32> Unpredictable =3D 0;
+  // SoftFail is the generic name for this field, but we alias it so
+  // as to make it more obvious what it means in ARM-land.
+  field bits<32> SoftFail =3D Unpredictable;
 }
=20
 class InstARM<AddrMode am, int sz, IndexMode im,
@@ -290,6 +314,32 @@
   let DecoderNamespace =3D "Thumb";
 }
=20
+// Pseudo-instructions for alternate assembly syntax (never used by codege=
n).
+// These are aliases that require C++ handling to convert to the target
+// instruction, while InstAliases can be handled directly by tblgen.
+class AsmPseudoInst<string asm, dag iops>
+  : InstTemplate<AddrModeNone, 0, IndexModeNone, Pseudo, GenericDomain,
+                 "", NoItinerary> {
+  let OutOperandList =3D (outs);
+  let InOperandList =3D iops;
+  let Pattern =3D [];
+  let isCodeGenOnly =3D 0; // So we get asm matcher for it.
+  let AsmString =3D asm;
+  let isPseudo =3D 1;
+}
+
+class ARMAsmPseudo<string asm, dag iops> : AsmPseudoInst<asm, iops>,
+        Requires<[IsARM]>;
+class tAsmPseudo<string asm, dag iops> : AsmPseudoInst<asm, iops>,
+        Requires<[IsThumb]>;
+class t2AsmPseudo<string asm, dag iops> : AsmPseudoInst<asm, iops>,
+        Requires<[IsThumb2]>;
+class VFP2AsmPseudo<string asm, dag iops> : AsmPseudoInst<asm, iops>,
+        Requires<[HasVFP2]>;
+class NEONAsmPseudo<string asm, dag iops> : AsmPseudoInst<asm, iops>,
+        Requires<[HasNEON]>;
+
+// Pseudo instructions for the code generator.
 class PseudoInst<dag oops, dag iops, InstrItinClass itin, list<dag> patter=
n>
   : InstTemplate<AddrModeNone, 0, IndexModeNone, Pseudo,
                  GenericDomain, "", itin> {
@@ -481,6 +531,8 @@
   let Inst{15-12} =3D Rt;
   let Inst{11-4} =3D 0b00001001;
   let Inst{3-0} =3D Rt2;
+
+  let DecoderMethod =3D "DecodeSwap";
 }
=20
 // addrmode1 instructions
@@ -792,7 +844,7 @@
 }
=20
 // PKH instructions
-def PKHLSLAsmOperand : AsmOperandClass {
+def PKHLSLAsmOperand : ImmAsmOperand {
   let Name =3D "PKHLSLImm";
   let ParserMethod =3D "parsePKHLSLImm";
 }
@@ -1550,8 +1602,11 @@
                 dag oops, dag iops, InstrItinClass itin, string opc, strin=
g asm,
                 list<dag> pattern>
   : AVConv1I<op1, op2, op3, op4, oops, iops, itin, opc, asm, pattern> {
+  bits<5> fbits;
   // size (fixed-point number): sx =3D=3D 0 ? 16 : 32
   let Inst{7} =3D op5; // sx
+  let Inst{5} =3D fbits{0};
+  let Inst{3-0} =3D fbits{4-1};
 }
=20
 // VFP conversion instructions, if no NEON
@@ -1963,3 +2018,54 @@
 class NEONFPPat<dag pattern, dag result> : Pat<pattern, result> {
   list<Predicate> Predicates =3D [HasNEON,UseNEONForFP];
 }
+
+// VFP/NEON Instruction aliases for type suffices.
+class VFPDataTypeInstAlias<string opc, string dt, string asm, dag Result> :
+  InstAlias<!strconcat(opc, dt, "\t", asm), Result>, Requires<[HasVFP2]>;
+
+multiclass VFPDTAnyInstAlias<string opc, string asm, dag Result> {
+  def : VFPDataTypeInstAlias<opc, ".8", asm, Result>;
+  def : VFPDataTypeInstAlias<opc, ".16", asm, Result>;
+  def : VFPDataTypeInstAlias<opc, ".32", asm, Result>;
+  def : VFPDataTypeInstAlias<opc, ".64", asm, Result>;
+}
+
+multiclass NEONDTAnyInstAlias<string opc, string asm, dag Result> {
+  let Predicates =3D [HasNEON] in {
+  def : VFPDataTypeInstAlias<opc, ".8", asm, Result>;
+  def : VFPDataTypeInstAlias<opc, ".16", asm, Result>;
+  def : VFPDataTypeInstAlias<opc, ".32", asm, Result>;
+  def : VFPDataTypeInstAlias<opc, ".64", asm, Result>;
+}
+}
+
+// The same alias classes using AsmPseudo instead, for the more complex
+// stuff in NEON that InstAlias can't quite handle.
+// Note that we can't use anonymous defm references here like we can
+// above, as we care about the ultimate instruction enum names generated, =
unlike
+// for instalias defs.
+class NEONDataTypeAsmPseudoInst<string opc, string dt, string asm, dag iop=
s> :
+  AsmPseudoInst<!strconcat(opc, dt, "\t", asm), iops>, Requires<[HasNEON]>;
+
+// Data type suffix token aliases. Implements Table A7-3 in the ARM ARM.
+def : TokenAlias<".s8", ".i8">;
+def : TokenAlias<".u8", ".i8">;
+def : TokenAlias<".s16", ".i16">;
+def : TokenAlias<".u16", ".i16">;
+def : TokenAlias<".s32", ".i32">;
+def : TokenAlias<".u32", ".i32">;
+def : TokenAlias<".s64", ".i64">;
+def : TokenAlias<".u64", ".i64">;
+
+def : TokenAlias<".i8", ".8">;
+def : TokenAlias<".i16", ".16">;
+def : TokenAlias<".i32", ".32">;
+def : TokenAlias<".i64", ".64">;
+
+def : TokenAlias<".p8", ".8">;
+def : TokenAlias<".p16", ".16">;
+
+def : TokenAlias<".f32", ".32">;
+def : TokenAlias<".f64", ".64">;
+def : TokenAlias<".f", ".f32">;
+def : TokenAlias<".d", ".f64">;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMInstrInfo.cpp - ARM Instruction Information -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMInstrInfo.cpp - ARM Instruction Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -21,12 +21,29 @@
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
 #include "llvm/MC/MCAsmInfo.h"
+#include "llvm/MC/MCInst.h"
 using namespace llvm;
=20
 ARMInstrInfo::ARMInstrInfo(const ARMSubtarget &STI)
   : ARMBaseInstrInfo(STI), RI(*this, STI) {
 }
=20
+/// getNoopForMachoTarget - Return the noop instruction to use for a noop.
+void ARMInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
+  if (hasNOP()) {
+    NopInst.setOpcode(ARM::NOP);
+    NopInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+    NopInst.addOperand(MCOperand::CreateReg(0));
+  } else {
+    NopInst.setOpcode(ARM::MOVr);
+    NopInst.addOperand(MCOperand::CreateReg(ARM::R0));
+    NopInst.addOperand(MCOperand::CreateReg(ARM::R0));
+    NopInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+    NopInst.addOperand(MCOperand::CreateReg(0));
+    NopInst.addOperand(MCOperand::CreateReg(0));
+  }
+}
+
 unsigned ARMInstrInfo::getUnindexedOpcode(unsigned Opc) const {
   switch (Opc) {
   default: break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMInstrInfo.h - ARM Instruction Information -------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMInstrInfo.h - ARM Instruction Information ------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,11 +14,10 @@
 #ifndef ARMINSTRUCTIONINFO_H
 #define ARMINSTRUCTIONINFO_H
=20
-#include "llvm/Target/TargetInstrInfo.h"
+#include "ARM.h"
 #include "ARMBaseInstrInfo.h"
 #include "ARMRegisterInfo.h"
 #include "ARMSubtarget.h"
-#include "ARM.h"
=20
 namespace llvm {
   class ARMSubtarget;
@@ -28,6 +27,9 @@
 public:
   explicit ARMInstrInfo(const ARMSubtarget &STI);
=20
+  /// getNoopForMachoTarget - Return the noop instruction to use for a noo=
p.
+  void getNoopForMachoTarget(MCInst &NopInst) const;
+
   // Return the non-pre/post incrementing version of 'Opc'. Return 0
   // if there is not such an opcode.
   unsigned getUnindexedOpcode(unsigned Opc) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strInfo.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.td	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrInfo.td	Tue Apr 17 11:51:51 =
2012 +0300
@@ -58,8 +58,6 @@
                                                  SDTCisInt<2>]>;
 def SDT_ARMEH_SJLJ_Longjmp: SDTypeProfile<0, 2, [SDTCisPtrTy<0>, SDTCisInt=
<1>]>;
=20
-def SDT_ARMEH_SJLJ_DispatchSetup: SDTypeProfile<0, 1, [SDTCisInt<0>]>;
-
 def SDT_ARMMEMBARRIER     : SDTypeProfile<0, 1, [SDTCisInt<0>]>;
=20
 def SDT_ARMPREFETCH : SDTypeProfile<0, 3, [SDTCisPtrTy<0>, SDTCisSameAs<1,=
 2>,
@@ -143,9 +141,6 @@
                                SDT_ARMEH_SJLJ_Setjmp, [SDNPHasChain]>;
 def ARMeh_sjlj_longjmp: SDNode<"ARMISD::EH_SJLJ_LONGJMP",
                                SDT_ARMEH_SJLJ_Longjmp, [SDNPHasChain]>;
-def ARMeh_sjlj_dispatchsetup: SDNode<"ARMISD::EH_SJLJ_DISPATCHSETUP",
-                               SDT_ARMEH_SJLJ_DispatchSetup, [SDNPHasChain=
]>;
-
=20
 def ARMMemBarrier     : SDNode<"ARMISD::MEMBARRIER", SDT_ARMMEMBARRIER,
                                [SDNPHasChain]>;
@@ -184,6 +179,8 @@
                                  AssemblerPredicate<"FeatureVFP2">;
 def HasVFP3          : Predicate<"Subtarget->hasVFP3()">,
                                  AssemblerPredicate<"FeatureVFP3">;
+def HasVFP4          : Predicate<"Subtarget->hasVFP4()">,
+                                 AssemblerPredicate<"FeatureVFP4">;
 def HasNEON          : Predicate<"Subtarget->hasNEON()">,
                                  AssemblerPredicate<"FeatureNEON">;
 def HasFP16          : Predicate<"Subtarget->hasFP16()">,
@@ -211,16 +208,20 @@
                                  AssemblerPredicate<"!FeatureMClass">;
 def IsARM            : Predicate<"!Subtarget->isThumb()">,
                                  AssemblerPredicate<"!ModeThumb">;
-def IsDarwin         : Predicate<"Subtarget->isTargetDarwin()">;
-def IsNotDarwin      : Predicate<"!Subtarget->isTargetDarwin()">;
-def IsNaCl           : Predicate<"Subtarget->isTargetNaCl()">,
-                                 AssemblerPredicate<"ModeNaCl">;
+def IsIOS            : Predicate<"Subtarget->isTargetIOS()">;
+def IsNotIOS         : Predicate<"!Subtarget->isTargetIOS()">;
+def IsNaCl           : Predicate<"Subtarget->isTargetNaCl()">;
=20
 // FIXME: Eventually this will be just "hasV6T2Ops".
 def UseMovt          : Predicate<"Subtarget->useMovt()">;
 def DontUseMovt      : Predicate<"!Subtarget->useMovt()">;
 def UseFPVMLx        : Predicate<"Subtarget->useFPVMLx()">;
=20
+// Prefer fused MAC for fp mul + add over fp VMLA / VMLS if they are avail=
able.
+// But only select them if more precision in FP computation is allowed.
+def UseFusedMAC      : Predicate<"!TM.Options.NoExcessFPPrecision">;
+def DontUseFusedMAC  : Predicate<"!Subtarget->hasVFP4()">;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ARM Flag Definitions.
=20
@@ -244,25 +245,28 @@
   return CurDAG->getTargetConstant(~(int)N->getZExtValue(), MVT::i32);
 }]>;
=20
-/// imm1_15 predicate - True if the 32-bit immediate is in the range [1,15=
].
-def imm1_15 : ImmLeaf<i32, [{
-  return (int32_t)Imm >=3D 1 && (int32_t)Imm < 16;
-}]>;
-
 /// imm16_31 predicate - True if the 32-bit immediate is in the range [16,=
31].
 def imm16_31 : ImmLeaf<i32, [{
   return (int32_t)Imm >=3D 16 && (int32_t)Imm < 32;
 }]>;
=20
-def so_imm_neg :
-  PatLeaf<(imm), [{
-    return ARM_AM::getSOImmVal(-(uint32_t)N->getZExtValue()) !=3D -1;
-  }], so_imm_neg_XFORM>;
-
-def so_imm_not :
-  PatLeaf<(imm), [{
+def so_imm_neg_asmoperand : AsmOperandClass { let Name =3D "ARMSOImmNeg"; }
+def so_imm_neg : Operand<i32>, PatLeaf<(imm), [{
+    int64_t Value =3D -(int)N->getZExtValue();
+    return Value && ARM_AM::getSOImmVal(Value) !=3D -1;
+  }], so_imm_neg_XFORM> {
+  let ParserMatchClass =3D so_imm_neg_asmoperand;
+}
+
+// Note: this pattern doesn't require an encoder method and such, as it's
+// only used on aliases (Pat<> and InstAlias<>). The actual encoding
+// is handled by the destination instructions, which use so_imm.
+def so_imm_not_asmoperand : AsmOperandClass { let Name =3D "ARMSOImmNot"; }
+def so_imm_not : Operand<i32>, PatLeaf<(imm), [{
     return ARM_AM::getSOImmVal(~(uint32_t)N->getZExtValue()) !=3D -1;
-  }], so_imm_not_XFORM>;
+  }], so_imm_not_XFORM> {
+  let ParserMatchClass =3D so_imm_not_asmoperand;
+}
=20
 // sext_16_node predicate - True if the SDNode is sign-extended 16 or more=
 bits.
 def sext_16_node : PatLeaf<(i32 GPR:$a), [{
@@ -279,14 +283,6 @@
   return (((uint32_t)N->getZExtValue()) & 0xFFFFUL) =3D=3D 0;
 }], hi16>;
=20
-/// imm0_65535 - An immediate is in the range [0.65535].
-def Imm0_65535AsmOperand: AsmOperandClass { let Name =3D "Imm0_65535"; }
-def imm0_65535 : Operand<i32>, ImmLeaf<i32, [{
-  return Imm >=3D 0 && Imm < 65536;
-}]> {
-  let ParserMatchClass =3D Imm0_65535AsmOperand;
-}
-
 class BinOpWithFlagFrag<dag res> :
       PatFrag<(ops node:$LHS, node:$RHS, node:$FLAG), res>;
 class BinOpFrag<dag res> : PatFrag<(ops node:$LHS, node:$RHS), res>;
@@ -321,6 +317,9 @@
 // Operand Definitions.
 //
=20
+// Immediate operands with a shared generic asm render method.
+class ImmAsmOperand : AsmOperandClass { let RenderMethod =3D "addImmOperan=
ds"; }
+
 // Branch target.
 // FIXME: rename brtarget to t2_brtarget
 def brtarget : Operand<OtherVT> {
@@ -352,13 +351,11 @@
 // Call target for ARM. Handles conditional/unconditional
 // FIXME: rename bl_target to t2_bltarget?
 def bl_target : Operand<i32> {
-  // Encoded the same as branch targets.
-  let EncoderMethod =3D "getARMBranchTargetOpValue";
+  let EncoderMethod =3D "getARMBLTargetOpValue";
   let OperandType =3D "OPERAND_PCREL";
 }
=20
 def blx_target : Operand<i32> {
-  // Encoded the same as branch targets.
   let EncoderMethod =3D "getARMBLXTargetOpValue";
   let OperandType =3D "OPERAND_PCREL";
 }
@@ -475,6 +472,7 @@
   let EncoderMethod =3D "getSORegRegOpValue";
   let PrintMethod =3D "printSORegRegOperand";
   let DecoderMethod =3D "DecodeSORegRegOperand";
+  let ParserMatchClass =3D ShiftedRegAsmOperand;
   let MIOperandInfo =3D (ops GPR, GPR, i32imm);
 }
=20
@@ -485,13 +483,14 @@
   let EncoderMethod =3D "getSORegImmOpValue";
   let PrintMethod =3D "printSORegImmOperand";
   let DecoderMethod =3D "DecodeSORegImmOperand";
+  let ParserMatchClass =3D ShiftedImmAsmOperand;
   let MIOperandInfo =3D (ops GPR, i32imm);
 }
=20
=20
 // so_imm - Match a 32-bit shifter_operand immediate operand, which is an
 // 8-bit immediate rotated by an arbitrary number of bits.
-def SOImmAsmOperand: AsmOperandClass { let Name =3D "ARMSOImm"; }
+def SOImmAsmOperand: ImmAsmOperand { let Name =3D "ARMSOImm"; }
 def so_imm : Operand<i32>, ImmLeaf<i32, [{
     return ARM_AM::getSOImmVal(Imm) !=3D -1;
   }]> {
@@ -515,16 +514,60 @@
   return ARM_AM::isSOImmTwoPartVal((unsigned)N->getZExtValue());
 }]>;
=20
+/// imm0_1 predicate - Immediate in the range [0,1].
+def Imm0_1AsmOperand: ImmAsmOperand { let Name =3D "Imm0_1"; }
+def imm0_1 : Operand<i32> { let ParserMatchClass =3D Imm0_1AsmOperand; }
+
+/// imm0_3 predicate - Immediate in the range [0,3].
+def Imm0_3AsmOperand: ImmAsmOperand { let Name =3D "Imm0_3"; }
+def imm0_3 : Operand<i32> { let ParserMatchClass =3D Imm0_3AsmOperand; }
+
 /// imm0_7 predicate - Immediate in the range [0,7].
-def Imm0_7AsmOperand: AsmOperandClass { let Name =3D "Imm0_7"; }
+def Imm0_7AsmOperand: ImmAsmOperand { let Name =3D "Imm0_7"; }
 def imm0_7 : Operand<i32>, ImmLeaf<i32, [{
   return Imm >=3D 0 && Imm < 8;
 }]> {
   let ParserMatchClass =3D Imm0_7AsmOperand;
 }
=20
+/// imm8 predicate - Immediate is exactly 8.
+def Imm8AsmOperand: ImmAsmOperand { let Name =3D "Imm8"; }
+def imm8 : Operand<i32>, ImmLeaf<i32, [{ return Imm =3D=3D 8; }]> {
+  let ParserMatchClass =3D Imm8AsmOperand;
+}
+
+/// imm16 predicate - Immediate is exactly 16.
+def Imm16AsmOperand: ImmAsmOperand { let Name =3D "Imm16"; }
+def imm16 : Operand<i32>, ImmLeaf<i32, [{ return Imm =3D=3D 16; }]> {
+  let ParserMatchClass =3D Imm16AsmOperand;
+}
+
+/// imm32 predicate - Immediate is exactly 32.
+def Imm32AsmOperand: ImmAsmOperand { let Name =3D "Imm32"; }
+def imm32 : Operand<i32>, ImmLeaf<i32, [{ return Imm =3D=3D 32; }]> {
+  let ParserMatchClass =3D Imm32AsmOperand;
+}
+
+/// imm1_7 predicate - Immediate in the range [1,7].
+def Imm1_7AsmOperand: ImmAsmOperand { let Name =3D "Imm1_7"; }
+def imm1_7 : Operand<i32>, ImmLeaf<i32, [{ return Imm > 0 && Imm < 8; }]> {
+  let ParserMatchClass =3D Imm1_7AsmOperand;
+}
+
+/// imm1_15 predicate - Immediate in the range [1,15].
+def Imm1_15AsmOperand: ImmAsmOperand { let Name =3D "Imm1_15"; }
+def imm1_15 : Operand<i32>, ImmLeaf<i32, [{ return Imm > 0 && Imm < 16; }]=
> {
+  let ParserMatchClass =3D Imm1_15AsmOperand;
+}
+
+/// imm1_31 predicate - Immediate in the range [1,31].
+def Imm1_31AsmOperand: ImmAsmOperand { let Name =3D "Imm1_31"; }
+def imm1_31 : Operand<i32>, ImmLeaf<i32, [{ return Imm > 0 && Imm < 32; }]=
> {
+  let ParserMatchClass =3D Imm1_31AsmOperand;
+}
+
 /// imm0_15 predicate - Immediate in the range [0,15].
-def Imm0_15AsmOperand: AsmOperandClass { let Name =3D "Imm0_15"; }
+def Imm0_15AsmOperand: ImmAsmOperand { let Name =3D "Imm0_15"; }
 def imm0_15 : Operand<i32>, ImmLeaf<i32, [{
   return Imm >=3D 0 && Imm < 16;
 }]> {
@@ -532,33 +575,57 @@
 }
=20
 /// imm0_31 predicate - True if the 32-bit immediate is in the range [0,31=
].
-def Imm0_31AsmOperand: AsmOperandClass { let Name =3D "Imm0_31"; }
+def Imm0_31AsmOperand: ImmAsmOperand { let Name =3D "Imm0_31"; }
 def imm0_31 : Operand<i32>, ImmLeaf<i32, [{
   return Imm >=3D 0 && Imm < 32;
 }]> {
   let ParserMatchClass =3D Imm0_31AsmOperand;
 }
=20
+/// imm0_32 predicate - True if the 32-bit immediate is in the range [0,32=
].
+def Imm0_32AsmOperand: ImmAsmOperand { let Name =3D "Imm0_32"; }
+def imm0_32 : Operand<i32>, ImmLeaf<i32, [{
+  return Imm >=3D 0 && Imm < 32;
+}]> {
+  let ParserMatchClass =3D Imm0_32AsmOperand;
+}
+
+/// imm0_63 predicate - True if the 32-bit immediate is in the range [0,63=
].
+def Imm0_63AsmOperand: ImmAsmOperand { let Name =3D "Imm0_63"; }
+def imm0_63 : Operand<i32>, ImmLeaf<i32, [{
+  return Imm >=3D 0 && Imm < 64;
+}]> {
+  let ParserMatchClass =3D Imm0_63AsmOperand;
+}
+
 /// imm0_255 predicate - Immediate in the range [0,255].
-def Imm0_255AsmOperand : AsmOperandClass { let Name =3D "Imm0_255"; }
+def Imm0_255AsmOperand : ImmAsmOperand { let Name =3D "Imm0_255"; }
 def imm0_255 : Operand<i32>, ImmLeaf<i32, [{ return Imm >=3D 0 && Imm < 25=
6; }]> {
   let ParserMatchClass =3D Imm0_255AsmOperand;
 }
=20
+/// imm0_65535 - An immediate is in the range [0.65535].
+def Imm0_65535AsmOperand: ImmAsmOperand { let Name =3D "Imm0_65535"; }
+def imm0_65535 : Operand<i32>, ImmLeaf<i32, [{
+  return Imm >=3D 0 && Imm < 65536;
+}]> {
+  let ParserMatchClass =3D Imm0_65535AsmOperand;
+}
+
 // imm0_65535_expr - For movt/movw - 16-bit immediate that can also refere=
nce
 // a relocatable expression.
 //
 // FIXME: This really needs a Thumb version separate from the ARM version.
 // While the range is the same, and can thus use the same match class,
 // the encoding is different so it should have a different encoder method.
-def Imm0_65535ExprAsmOperand: AsmOperandClass { let Name =3D "Imm0_65535Ex=
pr"; }
+def Imm0_65535ExprAsmOperand: ImmAsmOperand { let Name =3D "Imm0_65535Expr=
"; }
 def imm0_65535_expr : Operand<i32> {
   let EncoderMethod =3D "getHiLo16ImmOpValue";
   let ParserMatchClass =3D Imm0_65535ExprAsmOperand;
 }
=20
 /// imm24b - True if the 32-bit immediate is encodable in 24 bits.
-def Imm24bitAsmOperand: AsmOperandClass { let Name =3D "Imm24bit"; }
+def Imm24bitAsmOperand: ImmAsmOperand { let Name =3D "Imm24bit"; }
 def imm24b : Operand<i32>, ImmLeaf<i32, [{
   return Imm >=3D 0 && Imm <=3D 0xffffff;
 }]> {
@@ -572,6 +639,7 @@
   let Name =3D "Bitfield";
   let ParserMethod =3D "parseBitfield";
 }
+
 def bf_inv_mask_imm : Operand<i32>,
                       PatLeaf<(imm), [{
   return ARM::isBitFieldInvertedMask(N->getZExtValue());
@@ -670,7 +738,7 @@
   let DecoderMethod =3D "DecodePostIdxReg";
   let PrintMethod =3D "printPostIdxRegOperand";
   let ParserMatchClass =3D PostIdxRegAsmOperand;
-  let MIOperandInfo =3D (ops GPR, i32imm);
+  let MIOperandInfo =3D (ops GPRnopc, i32imm);
 }
=20
=20
@@ -699,7 +767,7 @@
   let PrintMethod =3D "printAddrMode2OffsetOperand";
   // When using this for assembly, it's always as a post-index offset.
   let ParserMatchClass =3D PostIdxRegShiftedAsmOperand;
-  let MIOperandInfo =3D (ops GPR, i32imm);
+  let MIOperandInfo =3D (ops GPRnopc, i32imm);
 }
=20
 // FIXME: am2offset_imm should only need the immediate, not the GPR. Having
@@ -711,7 +779,7 @@
   let EncoderMethod =3D "getAddrMode2OffsetOpValue";
   let PrintMethod =3D "printAddrMode2OffsetOperand";
   let ParserMatchClass =3D AM2OffsetImmAsmOperand;
-  let MIOperandInfo =3D (ops GPR, i32imm);
+  let MIOperandInfo =3D (ops GPRnopc, i32imm);
 }
=20
=20
@@ -799,6 +867,9 @@
   let PrintMethod =3D "printAddrMode6Operand";
   let MIOperandInfo =3D (ops GPR:$addr, i32imm);
   let EncoderMethod =3D "getAddrMode6DupAddressOpValue";
+  // FIXME: This is close, but not quite right. The alignment specifier is
+  // different.
+  let ParserMatchClass =3D AddrMode6AsmOperand;
 }
=20
 // addrmodepc :=3D pc + reg
@@ -1041,69 +1112,58 @@
=20
 }
=20
-/// AsI1_rbin_s_is - Same as AsI1_rbin_s_is except it sets 's' bit by defa=
ult.
-///
-/// These opcodes will be converted to the real non-S opcodes by
-/// AdjustInstrPostInstrSelection after giving then an optional CPSR opera=
nd.
-let hasPostISelHook =3D 1, isCodeGenOnly =3D 1, isPseudo =3D 1, Defs =3D [=
CPSR] in {
-multiclass AsI1_rbin_s_is<bits<4> opcod, string opc,
-                     InstrItinClass iii, InstrItinClass iir, InstrItinClas=
s iis,
-                        PatFrag opnode, bit Commutable =3D 0> {
-  def ri : AsI1<opcod, (outs GPR:$Rd), (ins GPR:$Rn, so_imm:$imm), DPFrm,
-               iii, opc, "\t$Rd, $Rn, $imm",
-               [(set GPR:$Rd, CPSR, (opnode so_imm:$imm, GPR:$Rn))]>;
-
-  def rr : AsI1<opcod, (outs GPR:$Rd), (ins GPR:$Rn, GPR:$Rm), DPFrm,
-               iir, opc, "\t$Rd, $Rn, $Rm",
-               [/* pattern left blank */]>;
-
-  def rsi : AsI1<opcod, (outs GPR:$Rd),
-               (ins GPR:$Rn, so_reg_imm:$shift), DPSoRegImmFrm,
-               iis, opc, "\t$Rd, $Rn, $shift",
-               [(set GPR:$Rd, CPSR, (opnode so_reg_imm:$shift, GPR:$Rn))]>;
-
-  def rsr : AsI1<opcod, (outs GPR:$Rd),
-               (ins GPR:$Rn, so_reg_reg:$shift), DPSoRegRegFrm,
-               iis, opc, "\t$Rd, $Rn, $shift",
-               [(set GPR:$Rd, CPSR, (opnode so_reg_reg:$shift, GPR:$Rn))]>=
 {
-    bits<4> Rd;
-    bits<4> Rn;
-    bits<12> shift;
-    let Inst{25} =3D 0;
-    let Inst{19-16} =3D Rn;
-    let Inst{15-12} =3D Rd;
-    let Inst{11-8} =3D shift{11-8};
-    let Inst{7} =3D 0;
-    let Inst{6-5} =3D shift{6-5};
-    let Inst{4} =3D 1;
-    let Inst{3-0} =3D shift{3-0};
-  }
-}
-}
-
 /// AsI1_bin_s_irs - Same as AsI1_bin_irs except it sets the 's' bit by de=
fault.
 ///
 /// These opcodes will be converted to the real non-S opcodes by
-/// AdjustInstrPostInstrSelection after giving then an optional CPSR opera=
nd.
-let hasPostISelHook =3D 1, isCodeGenOnly =3D 1, isPseudo =3D 1, Defs =3D [=
CPSR] in {
-multiclass AsI1_bin_s_irs<bits<4> opcod, string opc,
-                     InstrItinClass iii, InstrItinClass iir, InstrItinClas=
s iis,
-                         PatFrag opnode, bit Commutable =3D 0> {
-  def ri : AsI1<opcod, (outs GPR:$Rd), (ins GPR:$Rn, so_imm:$imm), DPFrm,
-               iii, opc, "\t$Rd, $Rn, $imm",
-               [(set GPR:$Rd, CPSR, (opnode GPR:$Rn, so_imm:$imm))]>;
-  def rr : AsI1<opcod, (outs GPR:$Rd), (ins GPR:$Rn, GPR:$Rm), DPFrm,
-               iir, opc, "\t$Rd, $Rn, $Rm",
-               [(set GPR:$Rd, CPSR, (opnode GPR:$Rn, GPR:$Rm))]>;
-  def rsi : AsI1<opcod, (outs GPR:$Rd),
-               (ins GPR:$Rn, so_reg_imm:$shift), DPSoRegImmFrm,
-               iis, opc, "\t$Rd, $Rn, $shift",
-               [(set GPR:$Rd, CPSR, (opnode GPR:$Rn, so_reg_imm:$shift))]>;
-
-  def rsr : AsI1<opcod, (outs GPR:$Rd),
-               (ins GPR:$Rn, so_reg_reg:$shift), DPSoRegRegFrm,
-               iis, opc, "\t$Rd, $Rn, $shift",
-               [(set GPR:$Rd, CPSR, (opnode GPR:$Rn, so_reg_reg:$shift))]>;
+/// AdjustInstrPostInstrSelection after giving them an optional CPSR opera=
nd.
+let hasPostISelHook =3D 1, Defs =3D [CPSR] in {
+multiclass AsI1_bin_s_irs<InstrItinClass iii, InstrItinClass iir,
+                          InstrItinClass iis, PatFrag opnode,
+                          bit Commutable =3D 0> {
+  def ri : ARMPseudoInst<(outs GPR:$Rd), (ins GPR:$Rn, so_imm:$imm, pred:$=
p),
+                         4, iii,
+                         [(set GPR:$Rd, CPSR, (opnode GPR:$Rn, so_imm:$imm=
))]>;
+
+  def rr : ARMPseudoInst<(outs GPR:$Rd), (ins GPR:$Rn, GPR:$Rm, pred:$p),
+                         4, iir,
+                         [(set GPR:$Rd, CPSR, (opnode GPR:$Rn, GPR:$Rm))]>=
 {
+    let isCommutable =3D Commutable;
+  }
+  def rsi : ARMPseudoInst<(outs GPR:$Rd),
+                          (ins GPR:$Rn, so_reg_imm:$shift, pred:$p),
+                          4, iis,
+                          [(set GPR:$Rd, CPSR, (opnode GPR:$Rn,
+                                                so_reg_imm:$shift))]>;
+
+  def rsr : ARMPseudoInst<(outs GPR:$Rd),
+                          (ins GPR:$Rn, so_reg_reg:$shift, pred:$p),
+                          4, iis,
+                          [(set GPR:$Rd, CPSR, (opnode GPR:$Rn,
+                                                so_reg_reg:$shift))]>;
+}
+}
+
+/// AsI1_rbin_s_is - Same as AsI1_bin_s_irs, except selection DAG
+/// operands are reversed.
+let hasPostISelHook =3D 1, Defs =3D [CPSR] in {
+multiclass AsI1_rbin_s_is<InstrItinClass iii, InstrItinClass iir,
+                          InstrItinClass iis, PatFrag opnode,
+                          bit Commutable =3D 0> {
+  def ri : ARMPseudoInst<(outs GPR:$Rd), (ins GPR:$Rn, so_imm:$imm, pred:$=
p),
+                         4, iii,
+                         [(set GPR:$Rd, CPSR, (opnode so_imm:$imm, GPR:$Rn=
))]>;
+
+  def rsi : ARMPseudoInst<(outs GPR:$Rd),
+                          (ins GPR:$Rn, so_reg_imm:$shift, pred:$p),
+                          4, iis,
+                          [(set GPR:$Rd, CPSR, (opnode so_reg_imm:$shift,
+                                             GPR:$Rn))]>;
+
+  def rsr : ARMPseudoInst<(outs GPR:$Rd),
+                          (ins GPR:$Rn, so_reg_reg:$shift, pred:$p),
+                          4, iis,
+                          [(set GPR:$Rd, CPSR, (opnode so_reg_reg:$shift,
+                                             GPR:$Rn))]>;
 }
 }
=20
@@ -1272,10 +1332,10 @@
     let Inst{4} =3D 0;
     let Inst{3-0} =3D shift{3-0};
   }
-  def rsr : AsI1<opcod, (outs GPR:$Rd),
-                (ins GPR:$Rn, so_reg_reg:$shift),
+  def rsr : AsI1<opcod, (outs GPRnopc:$Rd),
+                (ins GPRnopc:$Rn, so_reg_reg:$shift),
                 DPSoRegRegFrm, IIC_iALUsr, opc, "\t$Rd, $Rn, $shift",
-              [(set GPR:$Rd, CPSR, (opnode GPR:$Rn, so_reg_reg:$shift, CPS=
R))]>,
+              [(set GPRnopc:$Rd, CPSR, (opnode GPRnopc:$Rn, so_reg_reg:$sh=
ift, CPSR))]>,
                Requires<[IsARM]> {
     bits<4> Rd;
     bits<4> Rn;
@@ -1309,7 +1369,7 @@
                                                     cc_out:$s)>,
      Requires<[IsARM]>;
   def : InstAlias<!strconcat(opc, "${s}${p} $Rdn, $shift"),
-     (!cast<Instruction>(!strconcat(baseOpc, "rsr")) GPR:$Rdn, GPR:$Rdn,
+     (!cast<Instruction>(!strconcat(baseOpc, "rsr")) GPRnopc:$Rdn, GPRnopc=
:$Rdn,
                                                     so_reg_reg:$shift, pre=
d:$p,
                                                     cc_out:$s)>,
      Requires<[IsARM]>;
@@ -1550,7 +1610,7 @@
 }
=20
 // Atomic pseudo-insts which will be lowered to ldrexd/strexd loops.
-// (These psuedos use a hand-written selection code).
+// (These pseudos use a hand-written selection code).
 let usesCustomInserter =3D 1, Defs =3D [CPSR], mayLoad =3D 1, mayStore =3D=
 1 in {
 def ATOMOR6432   : PseudoInst<(outs GPR:$dst1, GPR:$dst2),
                               (ins GPR:$addr, GPR:$src1, GPR:$src2),
@@ -1652,7 +1712,7 @@
   let Inst{27-20} =3D 0b00010000;
   let Inst{19-18} =3D imod;
   let Inst{17}    =3D M; // Enabled if mode is set;
-  let Inst{16}    =3D 0;
+  let Inst{16-9}  =3D 0b00000000;
   let Inst{8-6}   =3D iflags;
   let Inst{5}     =3D 0;
   let Inst{4-0}   =3D mode;
@@ -1839,20 +1899,17 @@
   }
 }
=20
-// All calls clobber the non-callee saved registers. SP is marked as
-// a use to prevent stack-pointer assignments that appear immediately
-// before calls from potentially appearing dead.
+// SP is marked as a use to prevent stack-pointer assignments that appear
+// immediately before calls from potentially appearing dead.
 let isCall =3D 1,
-  // On non-Darwin platforms R9 is callee-saved.
   // FIXME:  Do we really need a non-predicated version? If so, it should
   // at least be a pseudo instruction expanding to the predicated version
   // at MC lowering time.
-  Defs =3D [R0,  R1,  R2,  R3,  R12, LR, QQQQ0, QQQQ2, QQQQ3, CPSR, FPSCR],
-  Uses =3D [SP] in {
+  Defs =3D [LR], Uses =3D [SP] in {
   def BL  : ABXI<0b1011, (outs), (ins bl_target:$func, variable_ops),
                 IIC_Br, "bl\t$func",
                 [(ARMcall tglobaladdr:$func)]>,
-            Requires<[IsARM, IsNotDarwin]> {
+            Requires<[IsARM]> {
     let Inst{31-28} =3D 0b1110;
     bits<24> func;
     let Inst{23-0} =3D func;
@@ -1862,7 +1919,7 @@
   def BL_pred : ABI<0b1011, (outs), (ins bl_target:$func, variable_ops),
                    IIC_Br, "bl", "\t$func",
                    [(ARMcall_pred tglobaladdr:$func)]>,
-                Requires<[IsARM, IsNotDarwin]> {
+                Requires<[IsARM]> {
     bits<24> func;
     let Inst{23-0} =3D func;
     let DecoderMethod =3D "DecodeBranchImmInstruction";
@@ -1872,7 +1929,7 @@
   def BLX : AXI<(outs), (ins GPR:$func, variable_ops), BrMiscFrm,
                 IIC_Br, "blx\t$func",
                 [(ARMcall GPR:$func)]>,
-            Requires<[IsARM, HasV5T, IsNotDarwin]> {
+            Requires<[IsARM, HasV5T]> {
     bits<4> func;
     let Inst{31-4} =3D 0b1110000100101111111111110011;
     let Inst{3-0}  =3D func;
@@ -1881,7 +1938,7 @@
   def BLX_pred : AI<(outs), (ins GPR:$func, variable_ops), BrMiscFrm,
                     IIC_Br, "blx", "\t$func",
                     [(ARMcall_pred GPR:$func)]>,
-                 Requires<[IsARM, HasV5T, IsNotDarwin]> {
+                 Requires<[IsARM, HasV5T]> {
     bits<4> func;
     let Inst{27-4} =3D 0b000100101111111111110011;
     let Inst{3-0}  =3D func;
@@ -1891,55 +1948,19 @@
   // Note: Restrict $func to the tGPR regclass to prevent it being in LR.
   def BX_CALL : ARMPseudoInst<(outs), (ins tGPR:$func, variable_ops),
                    8, IIC_Br, [(ARMcall_nolink tGPR:$func)]>,
-                   Requires<[IsARM, HasV4T, IsNotDarwin]>;
+                   Requires<[IsARM, HasV4T]>;
=20
   // ARMv4
   def BMOVPCRX_CALL : ARMPseudoInst<(outs), (ins tGPR:$func, variable_ops),
                    8, IIC_Br, [(ARMcall_nolink tGPR:$func)]>,
-                   Requires<[IsARM, NoV4T, IsNotDarwin]>;
-}
-
-let isCall =3D 1,
-  // On Darwin R9 is call-clobbered.
-  // R7 is marked as a use to prevent frame-pointer assignments from being
-  // moved above / below calls.
-  Defs =3D [R0,  R1,  R2,  R3,  R9,  R12, LR, QQQQ0, QQQQ2, QQQQ3, CPSR, F=
PSCR],
-  Uses =3D [R7, SP] in {
-  def BLr9  : ARMPseudoExpand<(outs), (ins bl_target:$func, variable_ops),
-                4, IIC_Br,
-                [(ARMcall tglobaladdr:$func)], (BL bl_target:$func)>,
-              Requires<[IsARM, IsDarwin]>;
-
-  def BLr9_pred : ARMPseudoExpand<(outs),
-                   (ins bl_target:$func, pred:$p, variable_ops),
-                   4, IIC_Br,
-                   [(ARMcall_pred tglobaladdr:$func)],
-                   (BL_pred bl_target:$func, pred:$p)>,
-                  Requires<[IsARM, IsDarwin]>;
-
-  // ARMv5T and above
-  def BLXr9 : ARMPseudoExpand<(outs), (ins GPR:$func, variable_ops),
-                4, IIC_Br,
-                [(ARMcall GPR:$func)],
-                (BLX GPR:$func)>,
-               Requires<[IsARM, HasV5T, IsDarwin]>;
-
-  def BLXr9_pred: ARMPseudoExpand<(outs), (ins GPR:$func, pred:$p,variable=
_ops),
-                4, IIC_Br,
-                [(ARMcall_pred GPR:$func)],
-                (BLX_pred GPR:$func, pred:$p)>,
-                   Requires<[IsARM, HasV5T, IsDarwin]>;
-
-  // ARMv4T
-  // Note: Restrict $func to the tGPR regclass to prevent it being in LR.
-  def BXr9_CALL : ARMPseudoInst<(outs), (ins tGPR:$func, variable_ops),
-                  8, IIC_Br, [(ARMcall_nolink tGPR:$func)]>,
-                  Requires<[IsARM, HasV4T, IsDarwin]>;
-
-  // ARMv4
-  def BMOVPCRXr9_CALL : ARMPseudoInst<(outs), (ins tGPR:$func, variable_op=
s),
-                  8, IIC_Br, [(ARMcall_nolink tGPR:$func)]>,
-                  Requires<[IsARM, NoV4T, IsDarwin]>;
+                   Requires<[IsARM, NoV4T]>;
+
+  // mov lr, pc; b if callee is marked noreturn to avoid confusing the
+  // return stack predictor.
+  def BMOVPCB_CALL : ARMPseudoInst<(outs),
+                                   (ins bl_target:$func, variable_ops),
+                               8, IIC_Br, [(ARMcall_nolink tglobaladdr:$fu=
nc)]>,
+                      Requires<[IsARM]>;
 }
=20
 let isBranch =3D 1, isTerminator =3D 1 in {
@@ -2006,47 +2027,22 @@
=20
 // Tail calls.
=20
-let isCall =3D 1, isTerminator =3D 1, isReturn =3D 1, isBarrier =3D 1 in {
-  // Darwin versions.
-  let Defs =3D [R0, R1, R2, R3, R9, R12, QQQQ0, QQQQ2, QQQQ3, PC],
-      Uses =3D [SP] in {
-    def TCRETURNdi : PseudoInst<(outs), (ins i32imm:$dst, variable_ops),
-                       IIC_Br, []>, Requires<[IsDarwin]>;
-
-    def TCRETURNri : PseudoInst<(outs), (ins tcGPR:$dst, variable_ops),
-                       IIC_Br, []>, Requires<[IsDarwin]>;
-
-    def TAILJMPd : ARMPseudoExpand<(outs), (ins br_target:$dst, variable_o=
ps),
-                   4, IIC_Br, [],
-                   (Bcc br_target:$dst, (ops 14, zero_reg))>,
-                   Requires<[IsARM, IsDarwin]>;
-
-    def TAILJMPr : ARMPseudoExpand<(outs), (ins tcGPR:$dst, variable_ops),
-                   4, IIC_Br, [],
-                   (BX GPR:$dst)>,
-                   Requires<[IsARM, IsDarwin]>;
-
-  }
-
-  // Non-Darwin versions (the difference is R9).
-  let Defs =3D [R0, R1, R2, R3, R12, QQQQ0, QQQQ2, QQQQ3, PC],
-      Uses =3D [SP] in {
-    def TCRETURNdiND : PseudoInst<(outs), (ins i32imm:$dst, variable_ops),
-                       IIC_Br, []>, Requires<[IsNotDarwin]>;
-
-    def TCRETURNriND : PseudoInst<(outs), (ins tcGPR:$dst, variable_ops),
-                       IIC_Br, []>, Requires<[IsNotDarwin]>;
-
-    def TAILJMPdND : ARMPseudoExpand<(outs), (ins brtarget:$dst, variable_=
ops),
-                   4, IIC_Br, [],
-                   (Bcc br_target:$dst, (ops 14, zero_reg))>,
-                   Requires<[IsARM, IsNotDarwin]>;
-
-    def TAILJMPrND : ARMPseudoExpand<(outs), (ins tcGPR:$dst, variable_ops=
),
-                     4, IIC_Br, [],
-                     (BX GPR:$dst)>,
-                     Requires<[IsARM, IsNotDarwin]>;
-  }
+let isCall =3D 1, isTerminator =3D 1, isReturn =3D 1, isBarrier =3D 1, Use=
s =3D [SP] in {
+  def TCRETURNdi : PseudoInst<(outs), (ins i32imm:$dst, variable_ops),
+                              IIC_Br, []>;
+
+  def TCRETURNri : PseudoInst<(outs), (ins tcGPR:$dst, variable_ops),
+                              IIC_Br, []>;
+
+  def TAILJMPd : ARMPseudoExpand<(outs), (ins br_target:$dst, variable_ops=
),
+                                 4, IIC_Br, [],
+                                 (Bcc br_target:$dst, (ops 14, zero_reg))>,
+                                 Requires<[IsARM]>;
+
+  def TAILJMPr : ARMPseudoExpand<(outs), (ins tcGPR:$dst, variable_ops),
+                                 4, IIC_Br, [],
+                                 (BX GPR:$dst)>,
+                                 Requires<[IsARM]>;
 }
=20
 // Secure Monitor Call is a system instruction.
@@ -2145,7 +2141,7 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//  Load / store Instructions.
+//  Load / Store Instructions.
 //
=20
 // Load
@@ -2197,9 +2193,10 @@
 }
=20
 // Indexed loads
-multiclass AI2_ldridx<bit isByte, string opc, InstrItinClass itin> {
+multiclass AI2_ldridx<bit isByte, string opc,
+                      InstrItinClass iii, InstrItinClass iir> {
   def _PRE_IMM  : AI2ldstidx<1, isByte, 1, (outs GPR:$Rt, GPR:$Rn_wb),
-                      (ins addrmode_imm12:$addr), IndexModePre, LdFrm, iti=
n,
+                      (ins addrmode_imm12:$addr), IndexModePre, LdFrm, iii,
                       opc, "\t$Rt, $addr!", "$addr.base =3D $Rn_wb", []> {
     bits<17> addr;
     let Inst{25} =3D 0;
@@ -2211,7 +2208,7 @@
   }
=20
   def _PRE_REG  : AI2ldstidx<1, isByte, 1, (outs GPR:$Rt, GPR:$Rn_wb),
-                      (ins ldst_so_reg:$addr), IndexModePre, LdFrm, itin,
+                      (ins ldst_so_reg:$addr), IndexModePre, LdFrm, iir,
                       opc, "\t$Rt, $addr!", "$addr.base =3D $Rn_wb", []> {
     bits<17> addr;
     let Inst{25} =3D 1;
@@ -2225,7 +2222,7 @@
=20
   def _POST_REG : AI2ldstidx<1, isByte, 0, (outs GPR:$Rt, GPR:$Rn_wb),
                        (ins addr_offset_none:$addr, am2offset_reg:$offset),
-                       IndexModePost, LdFrm, itin,
+                       IndexModePost, LdFrm, iir,
                        opc, "\t$Rt, $addr, $offset",
                        "$addr.base =3D $Rn_wb", []> {
      // {12}     isAdd
@@ -2242,7 +2239,7 @@
=20
    def _POST_IMM : AI2ldstidx<1, isByte, 0, (outs GPR:$Rt, GPR:$Rn_wb),
                        (ins addr_offset_none:$addr, am2offset_imm:$offset),
-                      IndexModePost, LdFrm, itin,
+                      IndexModePost, LdFrm, iii,
                       opc, "\t$Rt, $addr, $offset",
                       "$addr.base =3D $Rn_wb", []> {
     // {12}     isAdd
@@ -2260,8 +2257,10 @@
 }
=20
 let mayLoad =3D 1, neverHasSideEffects =3D 1 in {
-defm LDR  : AI2_ldridx<0, "ldr", IIC_iLoad_ru>;
-defm LDRB : AI2_ldridx<1, "ldrb", IIC_iLoad_bh_ru>;
+// FIXME: for LDR_PRE_REG etc. the itineray should be either IIC_iLoad_ru =
or
+// IIC_iLoad_siu depending on whether it the offset register is shifted.
+defm LDR  : AI2_ldridx<0, "ldr", IIC_iLoad_iu, IIC_iLoad_ru>;
+defm LDRB : AI2_ldridx<1, "ldrb", IIC_iLoad_bh_iu, IIC_iLoad_bh_ru>;
 }
=20
 multiclass AI3_ldridx<bits<4> op, string opc, InstrItinClass itin> {
@@ -2416,7 +2415,7 @@
     let Inst{3-0} =3D offset{3-0};
     let AsmMatchConverter =3D "cvtLdExtTWriteBackImm";
   }
-  def r : AI3ldstidxT<op, 1, (outs GPR:$Rt, GPR:$base_wb),
+  def r : AI3ldstidxT<op, 1, (outs GPRnopc:$Rt, GPRnopc:$base_wb),
                       (ins addr_offset_none:$addr, postidx_reg:$Rm),
                       IndexModePost, LdMiscFrm, IIC_iLoad_bh_ru, opc,
                       "\t$Rt, $addr, $Rm", "$addr.base =3D $base_wb", []> {
@@ -2424,8 +2423,10 @@
     let Inst{23} =3D Rm{4};
     let Inst{22} =3D 0;
     let Inst{11-8} =3D 0;
+    let Unpredictable{11-8} =3D 0b1111;
     let Inst{3-0} =3D Rm{3-0};
     let AsmMatchConverter =3D "cvtLdExtTWriteBackReg";
+    let DecoderMethod =3D "DecodeLDR";
   }
 }
=20
@@ -2451,10 +2452,11 @@
 }
=20
 // Indexed stores
-multiclass AI2_stridx<bit isByte, string opc, InstrItinClass itin> {
+multiclass AI2_stridx<bit isByte, string opc,
+                      InstrItinClass iii, InstrItinClass iir> {
   def _PRE_IMM : AI2ldstidx<0, isByte, 1, (outs GPR:$Rn_wb),
                             (ins GPR:$Rt, addrmode_imm12:$addr), IndexMode=
Pre,
-                            StFrm, itin,
+                            StFrm, iii,
                             opc, "\t$Rt, $addr!", "$addr.base =3D $Rn_wb",=
 []> {
     bits<17> addr;
     let Inst{25} =3D 0;
@@ -2467,7 +2469,7 @@
=20
   def _PRE_REG  : AI2ldstidx<0, isByte, 1, (outs GPR:$Rn_wb),
                       (ins GPR:$Rt, ldst_so_reg:$addr),
-                      IndexModePre, StFrm, itin,
+                      IndexModePre, StFrm, iir,
                       opc, "\t$Rt, $addr!", "$addr.base =3D $Rn_wb", []> {
     bits<17> addr;
     let Inst{25} =3D 1;
@@ -2480,7 +2482,7 @@
   }
   def _POST_REG : AI2ldstidx<0, isByte, 0, (outs GPR:$Rn_wb),
                 (ins GPR:$Rt, addr_offset_none:$addr, am2offset_reg:$offse=
t),
-                IndexModePost, StFrm, itin,
+                IndexModePost, StFrm, iir,
                 opc, "\t$Rt, $addr, $offset",
                 "$addr.base =3D $Rn_wb", []> {
      // {12}     isAdd
@@ -2497,7 +2499,7 @@
=20
    def _POST_IMM : AI2ldstidx<0, isByte, 0, (outs GPR:$Rn_wb),
                 (ins GPR:$Rt, addr_offset_none:$addr, am2offset_imm:$offse=
t),
-                IndexModePost, StFrm, itin,
+                IndexModePost, StFrm, iii,
                 opc, "\t$Rt, $addr, $offset",
                 "$addr.base =3D $Rn_wb", []> {
     // {12}     isAdd
@@ -2514,8 +2516,10 @@
 }
=20
 let mayStore =3D 1, neverHasSideEffects =3D 1 in {
-defm STR  : AI2_stridx<0, "str", IIC_iStore_ru>;
-defm STRB : AI2_stridx<1, "strb", IIC_iStore_bh_ru>;
+// FIXME: for STR_PRE_REG etc. the itineray should be either IIC_iStore_ru=
 or
+// IIC_iStore_siu depending on whether it the offset register is shifted.
+defm STR  : AI2_stridx<0, "str", IIC_iStore_iu, IIC_iStore_ru>;
+defm STRB : AI2_stridx<1, "strb", IIC_iStore_bh_iu, IIC_iStore_bh_ru>;
 }
=20
 def : ARMPat<(post_store GPR:$Rt, addr_offset_none:$addr,
@@ -2745,23 +2749,25 @@
 //  Load / store multiple Instructions.
 //
=20
-multiclass arm_ldst_mult<string asm, bit L_bit, Format f,
+multiclass arm_ldst_mult<string asm, string sfx, bit L_bit, bit P_bit, For=
mat f,
                          InstrItinClass itin, InstrItinClass itin_upd> {
   // IA is the default, so no need for an explicit suffix on the
   // mnemonic here. Without it is the cannonical spelling.
   def IA :
     AXI4<(outs), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_ops),
          IndexModeNone, f, itin,
-         !strconcat(asm, "${p}\t$Rn, $regs"), "", []> {
+         !strconcat(asm, "${p}\t$Rn, $regs", sfx), "", []> {
     let Inst{24-23} =3D 0b01;       // Increment After
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 0;          // No writeback
     let Inst{20}    =3D L_bit;
   }
   def IA_UPD :
     AXI4<(outs GPR:$wb), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_op=
s),
          IndexModeUpd, f, itin_upd,
-         !strconcat(asm, "${p}\t$Rn!, $regs"), "$Rn =3D $wb", []> {
+         !strconcat(asm, "${p}\t$Rn!, $regs", sfx), "$Rn =3D $wb", []> {
     let Inst{24-23} =3D 0b01;       // Increment After
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 1;          // Writeback
     let Inst{20}    =3D L_bit;
=20
@@ -2770,16 +2776,18 @@
   def DA :
     AXI4<(outs), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_ops),
          IndexModeNone, f, itin,
-         !strconcat(asm, "da${p}\t$Rn, $regs"), "", []> {
+         !strconcat(asm, "da${p}\t$Rn, $regs", sfx), "", []> {
     let Inst{24-23} =3D 0b00;       // Decrement After
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 0;          // No writeback
     let Inst{20}    =3D L_bit;
   }
   def DA_UPD :
     AXI4<(outs GPR:$wb), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_op=
s),
          IndexModeUpd, f, itin_upd,
-         !strconcat(asm, "da${p}\t$Rn!, $regs"), "$Rn =3D $wb", []> {
+         !strconcat(asm, "da${p}\t$Rn!, $regs", sfx), "$Rn =3D $wb", []> {
     let Inst{24-23} =3D 0b00;       // Decrement After
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 1;          // Writeback
     let Inst{20}    =3D L_bit;
=20
@@ -2788,16 +2796,18 @@
   def DB :
     AXI4<(outs), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_ops),
          IndexModeNone, f, itin,
-         !strconcat(asm, "db${p}\t$Rn, $regs"), "", []> {
+         !strconcat(asm, "db${p}\t$Rn, $regs", sfx), "", []> {
     let Inst{24-23} =3D 0b10;       // Decrement Before
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 0;          // No writeback
     let Inst{20}    =3D L_bit;
   }
   def DB_UPD :
     AXI4<(outs GPR:$wb), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_op=
s),
          IndexModeUpd, f, itin_upd,
-         !strconcat(asm, "db${p}\t$Rn!, $regs"), "$Rn =3D $wb", []> {
+         !strconcat(asm, "db${p}\t$Rn!, $regs", sfx), "$Rn =3D $wb", []> {
     let Inst{24-23} =3D 0b10;       // Decrement Before
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 1;          // Writeback
     let Inst{20}    =3D L_bit;
=20
@@ -2806,16 +2816,18 @@
   def IB :
     AXI4<(outs), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_ops),
          IndexModeNone, f, itin,
-         !strconcat(asm, "ib${p}\t$Rn, $regs"), "", []> {
+         !strconcat(asm, "ib${p}\t$Rn, $regs", sfx), "", []> {
     let Inst{24-23} =3D 0b11;       // Increment Before
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 0;          // No writeback
     let Inst{20}    =3D L_bit;
   }
   def IB_UPD :
     AXI4<(outs GPR:$wb), (ins GPR:$Rn, pred:$p, reglist:$regs, variable_op=
s),
          IndexModeUpd, f, itin_upd,
-         !strconcat(asm, "ib${p}\t$Rn!, $regs"), "$Rn =3D $wb", []> {
+         !strconcat(asm, "ib${p}\t$Rn!, $regs", sfx), "$Rn =3D $wb", []> {
     let Inst{24-23} =3D 0b11;       // Increment Before
+    let Inst{22}    =3D P_bit;
     let Inst{21}    =3D 1;          // Writeback
     let Inst{20}    =3D L_bit;
=20
@@ -2826,10 +2838,12 @@
 let neverHasSideEffects =3D 1 in {
=20
 let mayLoad =3D 1, hasExtraDefRegAllocReq =3D 1 in
-defm LDM : arm_ldst_mult<"ldm", 1, LdStMulFrm, IIC_iLoad_m, IIC_iLoad_mu>;
+defm LDM : arm_ldst_mult<"ldm", "", 1, 0, LdStMulFrm, IIC_iLoad_m,
+                         IIC_iLoad_mu>;
=20
 let mayStore =3D 1, hasExtraSrcRegAllocReq =3D 1 in
-defm STM : arm_ldst_mult<"stm", 0, LdStMulFrm, IIC_iStore_m, IIC_iStore_mu=
>;
+defm STM : arm_ldst_mult<"stm", "", 0, 0, LdStMulFrm, IIC_iStore_m,
+                         IIC_iStore_mu>;
=20
 } // neverHasSideEffects
=20
@@ -2843,6 +2857,16 @@
                      (LDMIA_UPD GPR:$wb, GPR:$Rn, pred:$p, reglist:$regs)>,
       RegConstraint<"$Rn =3D $wb">;
=20
+let mayLoad =3D 1, hasExtraDefRegAllocReq =3D 1 in
+defm sysLDM : arm_ldst_mult<"ldm", " ^", 1, 1, LdStMulFrm, IIC_iLoad_m,
+                               IIC_iLoad_mu>;
+
+let mayStore =3D 1, hasExtraSrcRegAllocReq =3D 1 in
+defm sysSTM : arm_ldst_mult<"stm", " ^", 0, 1, LdStMulFrm, IIC_iStore_m,
+                               IIC_iStore_mu>;
+
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Move Instructions.
 //
@@ -2860,7 +2884,7 @@
   let Inst{15-12} =3D Rd;
 }
=20
-def : ARMInstAlias<"movs${p} $Rd, $Rm",=20
+def : ARMInstAlias<"movs${p} $Rd, $Rm",
                    (MOVr GPR:$Rd, GPR:$Rm, pred:$p, CPSR)>;
=20
 // A version for the smaller set of tail call registers.
@@ -3080,20 +3104,18 @@
=20
 // ADD and SUB with 's' bit set.
 //
-// Currently, t2ADDS/t2SUBS are pseudo opcodes that exist only in the
-// selection DAG. They are "lowered" to real t2ADD/t2SUB opcodes by
+// Currently, ADDS/SUBS are pseudo opcodes that exist only in the
+// selection DAG. They are "lowered" to real ADD/SUB opcodes by
 // AdjustInstrPostInstrSelection where we determine whether or not to
 // set the "s" bit based on CPSR liveness.
 //
-// FIXME: Eliminate t2ADDS/t2SUBS pseudo opcodes after adding tablegen
+// FIXME: Eliminate ADDS/SUBS pseudo opcodes after adding tablegen
 // support for an optional CPSR definition that corresponds to the DAG
 // node's second value. We can then eliminate the implicit def of CPSR.
-defm ADDS : AsI1_bin_s_irs<0b0100, "add",
-                          IIC_iALUi, IIC_iALUr, IIC_iALUsr,
-                          BinOpFrag<(ARMaddc node:$LHS, node:$RHS)>, 1>;
-defm SUBS : AsI1_bin_s_irs<0b0010, "sub",
-                          IIC_iALUi, IIC_iALUr, IIC_iALUsr,
-                          BinOpFrag<(ARMsubc node:$LHS, node:$RHS)>>;
+defm ADDS : AsI1_bin_s_irs<IIC_iALUi, IIC_iALUr, IIC_iALUsr,
+                           BinOpFrag<(ARMaddc node:$LHS, node:$RHS)>, 1>;
+defm SUBS : AsI1_bin_s_irs<IIC_iALUi, IIC_iALUr, IIC_iALUsr,
+                           BinOpFrag<(ARMsubc node:$LHS, node:$RHS)>>;
=20
 defm ADC : AI1_adde_sube_irs<0b0101, "adc",
                   BinOpWithFlagFrag<(ARMadde node:$LHS, node:$RHS, node:$F=
LAG)>,
@@ -3108,9 +3130,8 @@
=20
 // FIXME: Eliminate them if we can write def : Pat patterns which defines
 // CPSR and the implicit def of CPSR is not needed.
-defm RSBS : AsI1_rbin_s_is<0b0011, "rsb",
-                         IIC_iALUi, IIC_iALUr, IIC_iALUsr,
-                         BinOpFrag<(ARMsubc node:$LHS, node:$RHS)>>;
+defm RSBS : AsI1_rbin_s_is<IIC_iALUi, IIC_iALUr, IIC_iALUsr,
+                           BinOpFrag<(ARMsubc node:$LHS, node:$RHS)>>;
=20
 defm RSC : AI1_rsc_irs<0b0111, "rsc",
                   BinOpWithFlagFrag<(ARMsube node:$LHS, node:$RHS, node:$F=
LAG)>,
@@ -3153,6 +3174,8 @@
   let Inst{19-16} =3D Rn;
   let Inst{15-12} =3D Rd;
   let Inst{3-0}   =3D Rm;
+ =20
+  let Unpredictable{11-8} =3D 0b1111;
 }
=20
 // Saturating add/subtract
@@ -3445,19 +3468,20 @@
 //        property. Remove them when it's possible to add those properties
 //        on an individual MachineInstr, not just an instuction descriptio=
n.
 let isCommutable =3D 1 in {
-def MUL  : AsMul1I32<0b0000000, (outs GPR:$Rd), (ins GPR:$Rn, GPR:$Rm),
+def MUL  : AsMul1I32<0b0000000, (outs GPRnopc:$Rd), (ins GPRnopc:$Rn, GPRn=
opc:$Rm),
                    IIC_iMUL32, "mul", "\t$Rd, $Rn, $Rm",
-                   [(set GPR:$Rd, (mul GPR:$Rn, GPR:$Rm))]>,
+                   [(set GPRnopc:$Rd, (mul GPRnopc:$Rn, GPRnopc:$Rm))]>,
                    Requires<[IsARM, HasV6]> {
   let Inst{15-12} =3D 0b0000;
+  let Unpredictable{15-12} =3D 0b1111;
 }
=20
 let Constraints =3D "@earlyclobber $Rd" in
-def MULv5: ARMPseudoExpand<(outs GPR:$Rd), (ins GPR:$Rn, GPR:$Rm,
+def MULv5: ARMPseudoExpand<(outs GPRnopc:$Rd), (ins GPRnopc:$Rn, GPRnopc:$=
Rm,
                                             pred:$p, cc_out:$s),
                           4, IIC_iMUL32,
-                         [(set GPR:$Rd, (mul GPR:$Rn, GPR:$Rm))],
-                         (MUL GPR:$Rd, GPR:$Rn, GPR:$Rm, pred:$p, cc_out:$=
s)>,
+                         [(set GPRnopc:$Rd, (mul GPRnopc:$Rn, GPRnopc:$Rm)=
)],
+                         (MUL GPRnopc:$Rd, GPRnopc:$Rn, GPRnopc:$Rm, pred:=
$p, cc_out:$s)>,
                         Requires<[IsARM, NoV6]>;
 }
=20
@@ -3952,10 +3976,13 @@
 // FIXME: should be able to write a pattern for ARMcmov, but can't use
 // a two-value operand where a dag node expects two operands. :(
 let neverHasSideEffects =3D 1 in {
+
+let isCommutable =3D 1 in
 def MOVCCr : ARMPseudoInst<(outs GPR:$Rd), (ins GPR:$false, GPR:$Rm, pred:=
$p),
                            4, IIC_iCMOVr,
   [/*(set GPR:$Rd, (ARMcmov GPR:$false, GPR:$Rm, imm:$cc, CCR:$ccr))*/]>,
       RegConstraint<"$false =3D $Rd">;
+
 def MOVCCsi : ARMPseudoInst<(outs GPR:$Rd),
                            (ins GPR:$false, so_reg_imm:$shift, pred:$p),
                            4, IIC_iCMOVsr,
@@ -3996,8 +4023,44 @@
                            4, IIC_iCMOVi,
  [/*(set GPR:$Rd, (ARMcmov GPR:$false, so_imm_not:$imm, imm:$cc, CCR:$ccr)=
)*/]>,
                 RegConstraint<"$false =3D $Rd">;
+
+// Conditional instructions
+multiclass AsI1_bincc_irs<Instruction iri, Instruction irr, Instruction ir=
si,
+                          Instruction irsr,
+                          InstrItinClass iii, InstrItinClass iir,
+                          InstrItinClass iis> {
+  def ri  : ARMPseudoExpand<(outs GPR:$Rd),
+                            (ins GPR:$Rn, so_imm:$imm, pred:$p, cc_out:$s),
+                            4, iii, [],
+                       (iri GPR:$Rd, GPR:$Rn, so_imm:$imm, pred:$p, cc_out=
:$s)>,
+                            RegConstraint<"$Rn =3D $Rd">;
+  def rr  : ARMPseudoExpand<(outs GPR:$Rd),
+                            (ins GPR:$Rn, GPR:$Rm, pred:$p, cc_out:$s),
+                            4, iir, [],
+                           (irr GPR:$Rd, GPR:$Rn, GPR:$Rm, pred:$p, cc_out=
:$s)>,
+                            RegConstraint<"$Rn =3D $Rd">;
+  def rsi : ARMPseudoExpand<(outs GPR:$Rd),
+                           (ins GPR:$Rn, so_reg_imm:$shift, pred:$p, cc_ou=
t:$s),
+                            4, iis, [],
+                (irsi GPR:$Rd, GPR:$Rn, so_reg_imm:$shift, pred:$p, cc_out=
:$s)>,
+                            RegConstraint<"$Rn =3D $Rd">;
+  def rsr : ARMPseudoExpand<(outs GPRnopc:$Rd),
+                       (ins GPRnopc:$Rn, so_reg_reg:$shift, pred:$p, cc_ou=
t:$s),
+                            4, iis, [],
+                (irsr GPR:$Rd, GPR:$Rn, so_reg_reg:$shift, pred:$p, cc_out=
:$s)>,
+                            RegConstraint<"$Rn =3D $Rd">;
+}
+
+defm ANDCC : AsI1_bincc_irs<ANDri, ANDrr, ANDrsi, ANDrsr,
+                            IIC_iBITi, IIC_iBITr, IIC_iBITsr>;
+defm ORRCC : AsI1_bincc_irs<ORRri, ORRrr, ORRrsi, ORRrsr,
+                            IIC_iBITi, IIC_iBITr, IIC_iBITsr>;
+defm EORCC : AsI1_bincc_irs<EORri, EORrr, EORrsi, EORrsr,
+                            IIC_iBITi, IIC_iBITr, IIC_iBITsr>;
+
 } // neverHasSideEffects
=20
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Atomic operations intrinsics
 //
@@ -4076,10 +4139,10 @@
       [(set GPR:$dst, (atomic_load_max_8 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_UMIN_I8 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$val), NoItinerary,
-      [(set GPR:$dst, (atomic_load_min_8 GPR:$ptr, GPR:$val))]>;
+      [(set GPR:$dst, (atomic_load_umin_8 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_UMAX_I8 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$val), NoItinerary,
-      [(set GPR:$dst, (atomic_load_max_8 GPR:$ptr, GPR:$val))]>;
+      [(set GPR:$dst, (atomic_load_umax_8 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_ADD_I16 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$incr), NoItinerary,
       [(set GPR:$dst, (atomic_load_add_16 GPR:$ptr, GPR:$incr))]>;
@@ -4106,10 +4169,10 @@
       [(set GPR:$dst, (atomic_load_max_16 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_UMIN_I16 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$val), NoItinerary,
-      [(set GPR:$dst, (atomic_load_min_16 GPR:$ptr, GPR:$val))]>;
+      [(set GPR:$dst, (atomic_load_umin_16 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_UMAX_I16 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$val), NoItinerary,
-      [(set GPR:$dst, (atomic_load_max_16 GPR:$ptr, GPR:$val))]>;
+      [(set GPR:$dst, (atomic_load_umax_16 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_ADD_I32 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$incr), NoItinerary,
       [(set GPR:$dst, (atomic_load_add_32 GPR:$ptr, GPR:$incr))]>;
@@ -4136,10 +4199,10 @@
       [(set GPR:$dst, (atomic_load_max_32 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_UMIN_I32 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$val), NoItinerary,
-      [(set GPR:$dst, (atomic_load_min_32 GPR:$ptr, GPR:$val))]>;
+      [(set GPR:$dst, (atomic_load_umin_32 GPR:$ptr, GPR:$val))]>;
     def ATOMIC_LOAD_UMAX_I32 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$val), NoItinerary,
-      [(set GPR:$dst, (atomic_load_max_32 GPR:$ptr, GPR:$val))]>;
+      [(set GPR:$dst, (atomic_load_umax_32 GPR:$ptr, GPR:$val))]>;
=20
     def ATOMIC_SWAP_I8 : PseudoInst<
       (outs GPR:$dst), (ins GPR:$ptr, GPR:$new), NoItinerary,
@@ -4185,14 +4248,14 @@
                     NoItinerary, "strexh", "\t$Rd, $Rt, $addr", []>;
 def STREX : AIstrex<0b00, (outs GPR:$Rd), (ins GPR:$Rt, addr_offset_none:$=
addr),
                     NoItinerary, "strex", "\t$Rd, $Rt, $addr", []>;
-}
-
-let hasExtraSrcRegAllocReq =3D 1, Constraints =3D "@earlyclobber $Rd" in
+let hasExtraSrcRegAllocReq =3D 1 in
 def STREXD : AIstrex<0b01, (outs GPR:$Rd),
                     (ins GPR:$Rt, GPR:$Rt2, addr_offset_none:$addr),
                     NoItinerary, "strexd", "\t$Rd, $Rt, $Rt2, $addr", []> {
   let DecoderMethod =3D "DecodeDoubleRegStore";
 }
+}
+
=20
 def CLREX : AXI<(outs), (ins), MiscFrm, NoItinerary, "clrex", []>,
             Requires<[IsARM, HasV7]>  {
@@ -4451,10 +4514,16 @@
                          c_imm:$CRm, imm0_7:$opc2),
                     [(int_arm_mcr imm:$cop, imm:$opc1, GPR:$Rt, imm:$CRn,
                                   imm:$CRm, imm:$opc2)]>;
+def : ARMInstAlias<"mcr${p} $cop, $opc1, $Rt, $CRn, $CRm",
+                   (MCR p_imm:$cop, imm0_7:$opc1, GPR:$Rt, c_imm:$CRn,
+                        c_imm:$CRm, 0, pred:$p)>;
 def MRC : MovRCopro<"mrc", 1 /* from coprocessor to ARM core register */,
                     (outs GPR:$Rt),
                     (ins p_imm:$cop, imm0_7:$opc1, c_imm:$CRn, c_imm:$CRm,
                          imm0_7:$opc2), []>;
+def : ARMInstAlias<"mrc${p} $cop, $opc1, $Rt, $CRn, $CRm",
+                   (MRC GPR:$Rt, p_imm:$cop, imm0_7:$opc1, c_imm:$CRn,
+                        c_imm:$CRm, 0, pred:$p)>;
=20
 def : ARMPat<(int_arm_mrc imm:$cop, imm:$opc1, imm:$CRn, imm:$CRm, imm:$op=
c2),
              (MRC imm:$cop, imm:$opc1, imm:$CRn, imm:$CRm, imm:$opc2)>;
@@ -4488,10 +4557,16 @@
                            c_imm:$CRm, imm0_7:$opc2),
                       [(int_arm_mcr2 imm:$cop, imm:$opc1, GPR:$Rt, imm:$CR=
n,
                                      imm:$CRm, imm:$opc2)]>;
+def : ARMInstAlias<"mcr2$ $cop, $opc1, $Rt, $CRn, $CRm",
+                   (MCR2 p_imm:$cop, imm0_7:$opc1, GPR:$Rt, c_imm:$CRn,
+                         c_imm:$CRm, 0)>;
 def MRC2 : MovRCopro2<"mrc2", 1 /* from coprocessor to ARM core register *=
/,
                       (outs GPR:$Rt),
                       (ins p_imm:$cop, imm0_7:$opc1, c_imm:$CRn, c_imm:$CR=
m,
                            imm0_7:$opc2), []>;
+def : ARMInstAlias<"mrc2$ $cop, $opc1, $Rt, $CRn, $CRm",
+                   (MRC2 GPR:$Rt, p_imm:$cop, imm0_7:$opc1, c_imm:$CRn,
+                         c_imm:$CRm, 0)>;
=20
 def : ARMV5TPat<(int_arm_mrc2 imm:$cop, imm:$opc1, imm:$CRn,
                               imm:$CRm, imm:$opc2),
@@ -4635,7 +4710,8 @@
 // no encoding information is necessary.
 let Defs =3D
   [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7,  R8,  R9,  R10, R11, R12, LR, C=
PSR,
-    QQQQ0, QQQQ1, QQQQ2, QQQQ3 ], hasSideEffects =3D 1, isBarrier =3D 1 in=
 {
+    Q0, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15 ],
+  hasSideEffects =3D 1, isBarrier =3D 1, usesCustomInserter =3D 1 in {
   def Int_eh_sjlj_setjmp : PseudoInst<(outs), (ins GPR:$src, GPR:$val),
                                NoItinerary,
                          [(set R0, (ARMeh_sjlj_setjmp GPR:$src, GPR:$val))=
]>,
@@ -4644,31 +4720,37 @@
=20
 let Defs =3D
   [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7,  R8,  R9,  R10, R11, R12, LR, C=
PSR ],
-  hasSideEffects =3D 1, isBarrier =3D 1 in {
+  hasSideEffects =3D 1, isBarrier =3D 1, usesCustomInserter =3D 1 in {
   def Int_eh_sjlj_setjmp_nofp : PseudoInst<(outs), (ins GPR:$src, GPR:$val=
),
                                    NoItinerary,
                          [(set R0, (ARMeh_sjlj_setjmp GPR:$src, GPR:$val))=
]>,
                                 Requires<[IsARM, NoVFP]>;
 }
=20
-// FIXME: Non-Darwin version(s)
+// FIXME: Non-IOS version(s)
 let isBarrier =3D 1, hasSideEffects =3D 1, isTerminator =3D 1,
     Defs =3D [ R7, LR, SP ] in {
 def Int_eh_sjlj_longjmp : PseudoInst<(outs), (ins GPR:$src, GPR:$scratch),
                              NoItinerary,
                          [(ARMeh_sjlj_longjmp GPR:$src, GPR:$scratch)]>,
-                                Requires<[IsARM, IsDarwin]>;
-}
-
-// eh.sjlj.dispatchsetup pseudo-instruction.
-// This pseudo is used for ARM, Thumb1 and Thumb2. Any differences are
+                                Requires<[IsARM, IsIOS]>;
+}
+
+// eh.sjlj.dispatchsetup pseudo-instructions.
+// These pseudos are used for both ARM and Thumb2. Any differences are
 // handled when the pseudo is expanded (which happens before any passes
 // that need the instruction size).
-let isBarrier =3D 1, hasSideEffects =3D 1 in
-def Int_eh_sjlj_dispatchsetup :
- PseudoInst<(outs), (ins GPR:$src), NoItinerary,
-            [(ARMeh_sjlj_dispatchsetup GPR:$src)]>,
-              Requires<[IsDarwin]>;
+let Defs =3D
+  [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7,  R8,  R9,  R10, R11, R12, LR, C=
PSR,
+    Q0, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15 ],
+  isBarrier =3D 1 in
+def Int_eh_sjlj_dispatchsetup : PseudoInst<(outs), (ins), NoItinerary, []>;
+
+let Defs =3D
+  [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7,  R8,  R9,  R10, R11, R12, LR, C=
PSR ],
+  isBarrier =3D 1 in
+def Int_eh_sjlj_dispatchsetup_nofp : PseudoInst<(outs), (ins), NoItinerary=
, []>;
+
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Non-Instruction Patterns
@@ -4725,30 +4807,15 @@
=20
 // TODO: add,sub,and, 3-instr forms?
=20
-// Tail calls
-def : ARMPat<(ARMtcret tcGPR:$dst),
-          (TCRETURNri tcGPR:$dst)>, Requires<[IsDarwin]>;
-
-def : ARMPat<(ARMtcret (i32 tglobaladdr:$dst)),
-          (TCRETURNdi texternalsym:$dst)>, Requires<[IsDarwin]>;
-
-def : ARMPat<(ARMtcret (i32 texternalsym:$dst)),
-          (TCRETURNdi texternalsym:$dst)>, Requires<[IsDarwin]>;
-
-def : ARMPat<(ARMtcret tcGPR:$dst),
-          (TCRETURNriND tcGPR:$dst)>, Requires<[IsNotDarwin]>;
-
-def : ARMPat<(ARMtcret (i32 tglobaladdr:$dst)),
-          (TCRETURNdiND texternalsym:$dst)>, Requires<[IsNotDarwin]>;
-
-def : ARMPat<(ARMtcret (i32 texternalsym:$dst)),
-          (TCRETURNdiND texternalsym:$dst)>, Requires<[IsNotDarwin]>;
+// Tail calls. These patterns also apply to Thumb mode.
+def : Pat<(ARMtcret tcGPR:$dst), (TCRETURNri tcGPR:$dst)>;
+def : Pat<(ARMtcret (i32 tglobaladdr:$dst)), (TCRETURNdi texternalsym:$dst=
)>;
+def : Pat<(ARMtcret (i32 texternalsym:$dst)), (TCRETURNdi texternalsym:$ds=
t)>;
=20
 // Direct calls
-def : ARMPat<(ARMcall texternalsym:$func), (BL texternalsym:$func)>,
-      Requires<[IsARM, IsNotDarwin]>;
-def : ARMPat<(ARMcall texternalsym:$func), (BLr9 texternalsym:$func)>,
-      Requires<[IsARM, IsDarwin]>;
+def : ARMPat<(ARMcall texternalsym:$func), (BL texternalsym:$func)>;
+def : ARMPat<(ARMcall_nolink texternalsym:$func),
+             (BMOVPCB_CALL texternalsym:$func)>;
=20
 // zextload i1 -> zextload i8
 def : ARMPat<(zextloadi1 addrmode_imm12:$addr), (LDRBi12 addrmode_imm12:$a=
ddr)>;
@@ -4992,13 +5059,113 @@
 // USAX =3D=3D USUBADDX
 def : MnemonicAlias<"usubaddx", "usax">;
=20
-// LDRSBT/LDRHT/LDRSHT post-index offset if optional.
-// Note that the write-back output register is a dummy operand for MC (it's
-// only meaningful for codegen), so we just pass zero here.
-// FIXME: tblgen not cooperating with argument conversions.
-//def : InstAlias<"ldrsbt${p} $Rt, $addr",
-//                (LDRSBTi GPR:$Rt, GPR:$Rt, addr_offset_none:$addr, 0,pre=
d:$p)>;
-//def : InstAlias<"ldrht${p} $Rt, $addr",
-//                (LDRHTi GPR:$Rt, GPR:$Rt, addr_offset_none:$addr, 0, pre=
d:$p)>;
-//def : InstAlias<"ldrsht${p} $Rt, $addr",
-//                (LDRSHTi GPR:$Rt, GPR:$Rt, addr_offset_none:$addr, 0, pr=
ed:$p)>;
+// "mov Rd, so_imm_not" can be handled via "mvn" in assembly, just like
+// for isel.
+def : ARMInstAlias<"mov${s}${p} $Rd, $imm",
+                   (MVNi rGPR:$Rd, so_imm_not:$imm, pred:$p, cc_out:$s)>;
+def : ARMInstAlias<"mvn${s}${p} $Rd, $imm",
+                   (MOVi rGPR:$Rd, so_imm_not:$imm, pred:$p, cc_out:$s)>;
+// Same for AND <--> BIC
+def : ARMInstAlias<"bic${s}${p} $Rd, $Rn, $imm",
+                   (ANDri rGPR:$Rd, rGPR:$Rn, so_imm_not:$imm,
+                          pred:$p, cc_out:$s)>;
+def : ARMInstAlias<"bic${s}${p} $Rdn, $imm",
+                   (ANDri rGPR:$Rdn, rGPR:$Rdn, so_imm_not:$imm,
+                          pred:$p, cc_out:$s)>;
+def : ARMInstAlias<"and${s}${p} $Rd, $Rn, $imm",
+                   (BICri rGPR:$Rd, rGPR:$Rn, so_imm_not:$imm,
+                          pred:$p, cc_out:$s)>;
+def : ARMInstAlias<"and${s}${p} $Rdn, $imm",
+                   (BICri rGPR:$Rdn, rGPR:$Rdn, so_imm_not:$imm,
+                          pred:$p, cc_out:$s)>;
+
+// Likewise, "add Rd, so_imm_neg" -> sub
+def : ARMInstAlias<"add${s}${p} $Rd, $Rn, $imm",
+                 (SUBri GPR:$Rd, GPR:$Rn, so_imm_neg:$imm, pred:$p, cc_out=
:$s)>;
+def : ARMInstAlias<"add${s}${p} $Rd, $imm",
+                 (SUBri GPR:$Rd, GPR:$Rd, so_imm_neg:$imm, pred:$p, cc_out=
:$s)>;
+// Same for CMP <--> CMN via so_imm_neg
+def : ARMInstAlias<"cmp${p} $Rd, $imm",
+                   (CMNzri rGPR:$Rd, so_imm_neg:$imm, pred:$p)>;
+def : ARMInstAlias<"cmn${p} $Rd, $imm",
+                   (CMPri rGPR:$Rd, so_imm_neg:$imm, pred:$p)>;
+
+// The shifter forms of the MOV instruction are aliased to the ASR, LSL,
+// LSR, ROR, and RRX instructions.
+// FIXME: We need C++ parser hooks to map the alias to the MOV
+//        encoding. It seems we should be able to do that sort of thing
+//        in tblgen, but it could get ugly.
+def ASRi : ARMAsmPseudo<"asr${s}${p} $Rd, $Rm, $imm",
+                        (ins GPR:$Rd, GPR:$Rm, imm0_32:$imm, pred:$p,
+                             cc_out:$s)>;
+def LSRi : ARMAsmPseudo<"lsr${s}${p} $Rd, $Rm, $imm",
+                        (ins GPR:$Rd, GPR:$Rm, imm0_32:$imm, pred:$p,
+                             cc_out:$s)>;
+def LSLi : ARMAsmPseudo<"lsl${s}${p} $Rd, $Rm, $imm",
+                        (ins GPR:$Rd, GPR:$Rm, imm0_31:$imm, pred:$p,
+                             cc_out:$s)>;
+def RORi : ARMAsmPseudo<"ror${s}${p} $Rd, $Rm, $imm",
+                        (ins GPR:$Rd, GPR:$Rm, imm0_31:$imm, pred:$p,
+                             cc_out:$s)>;
+def RRXi : ARMAsmPseudo<"rrx${s}${p} $Rd, $Rm",
+                        (ins GPRnopc:$Rd, GPRnopc:$Rm, pred:$p, cc_out:$s)=
>;
+def ASRr : ARMAsmPseudo<"asr${s}${p} $Rd, $Rn, $Rm",
+                        (ins GPRnopc:$Rd, GPRnopc:$Rn, GPRnopc:$Rm, pred:$=
p,
+                             cc_out:$s)>;
+def LSRr : ARMAsmPseudo<"lsr${s}${p} $Rd, $Rn, $Rm",
+                        (ins GPRnopc:$Rd, GPRnopc:$Rn, GPRnopc:$Rm, pred:$=
p,
+                             cc_out:$s)>;
+def LSLr : ARMAsmPseudo<"lsl${s}${p} $Rd, $Rn, $Rm",
+                        (ins GPRnopc:$Rd, GPRnopc:$Rn, GPRnopc:$Rm, pred:$=
p,
+                             cc_out:$s)>;
+def RORr : ARMAsmPseudo<"ror${s}${p} $Rd, $Rn, $Rm",
+                        (ins GPRnopc:$Rd, GPRnopc:$Rn, GPRnopc:$Rm, pred:$=
p,
+                             cc_out:$s)>;
+// shifter instructions also support a two-operand form.
+def : ARMInstAlias<"asr${s}${p} $Rm, $imm",
+                   (ASRi GPR:$Rm, GPR:$Rm, imm0_32:$imm, pred:$p, cc_out:$=
s)>;
+def : ARMInstAlias<"lsr${s}${p} $Rm, $imm",
+                   (LSRi GPR:$Rm, GPR:$Rm, imm0_32:$imm, pred:$p, cc_out:$=
s)>;
+def : ARMInstAlias<"lsl${s}${p} $Rm, $imm",
+                   (LSLi GPR:$Rm, GPR:$Rm, imm0_31:$imm, pred:$p, cc_out:$=
s)>;
+def : ARMInstAlias<"ror${s}${p} $Rm, $imm",
+                   (RORi GPR:$Rm, GPR:$Rm, imm0_31:$imm, pred:$p, cc_out:$=
s)>;
+def : ARMInstAlias<"asr${s}${p} $Rn, $Rm",
+                   (ASRr GPRnopc:$Rn, GPRnopc:$Rn, GPRnopc:$Rm, pred:$p,
+                         cc_out:$s)>;
+def : ARMInstAlias<"lsr${s}${p} $Rn, $Rm",
+                   (LSRr GPRnopc:$Rn, GPRnopc:$Rn, GPRnopc:$Rm, pred:$p,
+                         cc_out:$s)>;
+def : ARMInstAlias<"lsl${s}${p} $Rn, $Rm",
+                   (LSLr GPRnopc:$Rn, GPRnopc:$Rn, GPRnopc:$Rm, pred:$p,
+                         cc_out:$s)>;
+def : ARMInstAlias<"ror${s}${p} $Rn, $Rm",
+                   (RORr GPRnopc:$Rn, GPRnopc:$Rn, GPRnopc:$Rm, pred:$p,
+                         cc_out:$s)>;
+
+
+// 'mul' instruction can be specified with only two operands.
+def : ARMInstAlias<"mul${s}${p} $Rn, $Rm",
+                   (MUL rGPR:$Rn, rGPR:$Rm, rGPR:$Rn, pred:$p, cc_out:$s)>;
+
+// "neg" is and alias for "rsb rd, rn, #0"
+def : ARMInstAlias<"neg${s}${p} $Rd, $Rm",
+                   (RSBri GPR:$Rd, GPR:$Rm, 0, pred:$p, cc_out:$s)>;
+
+// Pre-v6, 'mov r0, r0' was used as a NOP encoding.
+def : InstAlias<"nop${p}", (MOVr R0, R0, pred:$p, zero_reg)>,
+         Requires<[IsARM, NoV6]>;
+
+// UMULL/SMULL are available on all arches, but the instruction definitions
+// need difference constraints pre-v6. Use these aliases for the assembly
+// parsing on pre-v6.
+def : InstAlias<"smull${s}${p} $RdLo, $RdHi, $Rn, $Rm",
+            (SMULL GPR:$RdLo, GPR:$RdHi, GPR:$Rn, GPR:$Rm, pred:$p, cc_out=
:$s)>,
+         Requires<[IsARM, NoV6]>;
+def : InstAlias<"umull${s}${p} $RdLo, $RdHi, $Rn, $Rm",
+            (UMULL GPR:$RdLo, GPR:$RdHi, GPR:$Rn, GPR:$Rm, pred:$p, cc_out=
:$s)>,
+         Requires<[IsARM, NoV6]>;
+
+// 'it' blocks in ARM mode just validate the predicates. The IT itself
+// is discarded.
+def ITasm : ARMAsmPseudo<"it$mask $cc", (ins it_pred:$cc, it_mask:$mask)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strNEON.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrNEON.td	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrNEON.td	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMInstrNEON.td - NEON support for ARM ----------------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- ARMInstrNEON.td - NEON support for ARM -------------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,6 +15,45 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // NEON-specific Operands.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+def nModImm : Operand<i32> {
+  let PrintMethod =3D "printNEONModImmOperand";
+}
+
+def nImmSplatI8AsmOperand : AsmOperandClass { let Name =3D "NEONi8splat"; }
+def nImmSplatI8 : Operand<i32> {
+  let PrintMethod =3D "printNEONModImmOperand";
+  let ParserMatchClass =3D nImmSplatI8AsmOperand;
+}
+def nImmSplatI16AsmOperand : AsmOperandClass { let Name =3D "NEONi16splat"=
; }
+def nImmSplatI16 : Operand<i32> {
+  let PrintMethod =3D "printNEONModImmOperand";
+  let ParserMatchClass =3D nImmSplatI16AsmOperand;
+}
+def nImmSplatI32AsmOperand : AsmOperandClass { let Name =3D "NEONi32splat"=
; }
+def nImmSplatI32 : Operand<i32> {
+  let PrintMethod =3D "printNEONModImmOperand";
+  let ParserMatchClass =3D nImmSplatI32AsmOperand;
+}
+def nImmVMOVI32AsmOperand : AsmOperandClass { let Name =3D "NEONi32vmov"; }
+def nImmVMOVI32 : Operand<i32> {
+  let PrintMethod =3D "printNEONModImmOperand";
+  let ParserMatchClass =3D nImmVMOVI32AsmOperand;
+}
+def nImmVMOVI32NegAsmOperand : AsmOperandClass { let Name =3D "NEONi32vmov=
Neg"; }
+def nImmVMOVI32Neg : Operand<i32> {
+  let PrintMethod =3D "printNEONModImmOperand";
+  let ParserMatchClass =3D nImmVMOVI32NegAsmOperand;
+}
+def nImmVMOVF32 : Operand<i32> {
+  let PrintMethod =3D "printFPImmOperand";
+  let ParserMatchClass =3D FPImmOperand;
+}
+def nImmSplatI64AsmOperand : AsmOperandClass { let Name =3D "NEONi64splat"=
; }
+def nImmSplatI64 : Operand<i32> {
+  let PrintMethod =3D "printNEONModImmOperand";
+  let ParserMatchClass =3D nImmSplatI64AsmOperand;
+}
+
 def VectorIndex8Operand  : AsmOperandClass { let Name =3D "VectorIndex8"; }
 def VectorIndex16Operand : AsmOperandClass { let Name =3D "VectorIndex16";=
 }
 def VectorIndex32Operand : AsmOperandClass { let Name =3D "VectorIndex32";=
 }
@@ -40,6 +79,326 @@
   let MIOperandInfo =3D (ops i32imm);
 }
=20
+// Register list of one D register.
+def VecListOneDAsmOperand : AsmOperandClass {
+  let Name =3D "VecListOneD";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListOneD : RegisterOperand<DPR, "printVectorListOne"> {
+  let ParserMatchClass =3D VecListOneDAsmOperand;
+}
+// Register list of two sequential D registers.
+def VecListDPairAsmOperand : AsmOperandClass {
+  let Name =3D "VecListDPair";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListDPair : RegisterOperand<DPair, "printVectorListTwo"> {
+  let ParserMatchClass =3D VecListDPairAsmOperand;
+}
+// Register list of three sequential D registers.
+def VecListThreeDAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeD";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListThreeD : RegisterOperand<DPR, "printVectorListThree"> {
+  let ParserMatchClass =3D VecListThreeDAsmOperand;
+}
+// Register list of four sequential D registers.
+def VecListFourDAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourD";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListFourD : RegisterOperand<DPR, "printVectorListFour"> {
+  let ParserMatchClass =3D VecListFourDAsmOperand;
+}
+// Register list of two D registers spaced by 2 (two sequential Q register=
s).
+def VecListDPairSpacedAsmOperand : AsmOperandClass {
+  let Name =3D "VecListDPairSpaced";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListDPairSpaced : RegisterOperand<DPair, "printVectorListTwoSpaced"=
> {
+  let ParserMatchClass =3D VecListDPairSpacedAsmOperand;
+}
+// Register list of three D registers spaced by 2 (three Q registers).
+def VecListThreeQAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeQ";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListThreeQ : RegisterOperand<DPR, "printVectorListThreeSpaced"> {
+  let ParserMatchClass =3D VecListThreeQAsmOperand;
+}
+// Register list of three D registers spaced by 2 (three Q registers).
+def VecListFourQAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourQ";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListFourQ : RegisterOperand<DPR, "printVectorListFourSpaced"> {
+  let ParserMatchClass =3D VecListFourQAsmOperand;
+}
+
+// Register list of one D register, with "all lanes" subscripting.
+def VecListOneDAllLanesAsmOperand : AsmOperandClass {
+  let Name =3D "VecListOneDAllLanes";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListOneDAllLanes : RegisterOperand<DPR, "printVectorListOneAllLanes=
"> {
+  let ParserMatchClass =3D VecListOneDAllLanesAsmOperand;
+}
+// Register list of two D registers, with "all lanes" subscripting.
+def VecListDPairAllLanesAsmOperand : AsmOperandClass {
+  let Name =3D "VecListDPairAllLanes";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListDPairAllLanes : RegisterOperand<DPair,
+                                           "printVectorListTwoAllLanes"> {
+  let ParserMatchClass =3D VecListDPairAllLanesAsmOperand;
+}
+// Register list of two D registers spaced by 2 (two sequential Q register=
s).
+def VecListDPairSpacedAllLanesAsmOperand : AsmOperandClass {
+  let Name =3D "VecListDPairSpacedAllLanes";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListDPairSpacedAllLanes : RegisterOperand<DPair,
+                                         "printVectorListTwoSpacedAllLanes=
"> {
+  let ParserMatchClass =3D VecListDPairSpacedAllLanesAsmOperand;
+}
+// Register list of three D registers, with "all lanes" subscripting.
+def VecListThreeDAllLanesAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeDAllLanes";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListThreeDAllLanes : RegisterOperand<DPR,
+                                            "printVectorListThreeAllLanes"=
> {
+  let ParserMatchClass =3D VecListThreeDAllLanesAsmOperand;
+}
+// Register list of three D registers spaced by 2 (three sequential Q regs=
).
+def VecListThreeQAllLanesAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeQAllLanes";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListThreeQAllLanes : RegisterOperand<DPR,
+                                         "printVectorListThreeSpacedAllLan=
es"> {
+  let ParserMatchClass =3D VecListThreeQAllLanesAsmOperand;
+}
+// Register list of four D registers, with "all lanes" subscripting.
+def VecListFourDAllLanesAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourDAllLanes";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListFourDAllLanes : RegisterOperand<DPR, "printVectorListFourAllLan=
es"> {
+  let ParserMatchClass =3D VecListFourDAllLanesAsmOperand;
+}
+// Register list of four D registers spaced by 2 (four sequential Q regs).
+def VecListFourQAllLanesAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourQAllLanes";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListOperands";
+}
+def VecListFourQAllLanes : RegisterOperand<DPR,
+                                         "printVectorListFourSpacedAllLane=
s"> {
+  let ParserMatchClass =3D VecListFourQAllLanesAsmOperand;
+}
+
+
+// Register list of one D register, with byte lane subscripting.
+def VecListOneDByteIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListOneDByteIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListOneDByteIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListOneDByteIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with half-word lane subscripting.
+def VecListOneDHWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListOneDHWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListOneDHWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListOneDHWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with word lane subscripting.
+def VecListOneDWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListOneDWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListOneDWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListOneDWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+
+// Register list of two D registers with byte lane subscripting.
+def VecListTwoDByteIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListTwoDByteIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListTwoDByteIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListTwoDByteIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with half-word lane subscripting.
+def VecListTwoDHWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListTwoDHWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListTwoDHWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListTwoDHWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with word lane subscripting.
+def VecListTwoDWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListTwoDWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListTwoDWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListTwoDWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// Register list of two Q registers with half-word lane subscripting.
+def VecListTwoQHWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListTwoQHWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListTwoQHWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListTwoQHWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with word lane subscripting.
+def VecListTwoQWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListTwoQWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListTwoQWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListTwoQWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+
+
+// Register list of three D registers with byte lane subscripting.
+def VecListThreeDByteIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeDByteIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListThreeDByteIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListThreeDByteIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with half-word lane subscripting.
+def VecListThreeDHWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeDHWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListThreeDHWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListThreeDHWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with word lane subscripting.
+def VecListThreeDWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeDWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListThreeDWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListThreeDWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// Register list of three Q registers with half-word lane subscripting.
+def VecListThreeQHWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeQHWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListThreeQHWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListThreeQHWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with word lane subscripting.
+def VecListThreeQWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListThreeQWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListThreeQWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListThreeQWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+
+// Register list of four D registers with byte lane subscripting.
+def VecListFourDByteIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourDByteIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListFourDByteIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListFourDByteIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with half-word lane subscripting.
+def VecListFourDHWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourDHWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListFourDHWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListFourDHWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with word lane subscripting.
+def VecListFourDWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourDWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListFourDWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListFourDWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// Register list of four Q registers with half-word lane subscripting.
+def VecListFourQHWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourQHWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListFourQHWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListFourQHWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+// ...with word lane subscripting.
+def VecListFourQWordIndexAsmOperand : AsmOperandClass {
+  let Name =3D "VecListFourQWordIndexed";
+  let ParserMethod =3D "parseVectorList";
+  let RenderMethod =3D "addVecListIndexedOperands";
+}
+def VecListFourQWordIndexed : Operand<i32> {
+  let ParserMatchClass =3D VecListFourQWordIndexAsmOperand;
+  let MIOperandInfo =3D (ops DPR:$Vd, i32imm:$idx);
+}
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // NEON-specific DAG Nodes.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -103,6 +462,7 @@
 def SDTARMVMOVIMM : SDTypeProfile<1, 1, [SDTCisVec<0>, SDTCisVT<1, i32>]>;
 def NEONvmovImm   : SDNode<"ARMISD::VMOVIMM", SDTARMVMOVIMM>;
 def NEONvmvnImm   : SDNode<"ARMISD::VMVNIMM", SDTARMVMOVIMM>;
+def NEONvmovFPImm : SDNode<"ARMISD::VMOVFPIMM", SDTARMVMOVIMM>;
=20
 def SDTARMVORRIMM : SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisSameAs<0, 1>,
                                            SDTCisVT<2, i32>]>;
@@ -164,30 +524,22 @@
 }]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// NEON operand definitions
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-def nModImm : Operand<i32> {
-  let PrintMethod =3D "printNEONModImmOperand";
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // NEON load / store instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 // Use VLDM to load a Q register as a D register pair.
 // This is a pseudo instruction that is expanded to VLDMD after reg alloc.
 def VLDMQIA
-  : PseudoVFPLdStM<(outs QPR:$dst), (ins GPR:$Rn),
+  : PseudoVFPLdStM<(outs DPair:$dst), (ins GPR:$Rn),
                     IIC_fpLoad_m, "",
-                   [(set QPR:$dst, (v2f64 (load GPR:$Rn)))]>;
+                   [(set DPair:$dst, (v2f64 (load GPR:$Rn)))]>;
=20
 // Use VSTM to store a Q register as a D register pair.
 // This is a pseudo instruction that is expanded to VSTMD after reg alloc.
 def VSTMQIA
-  : PseudoVFPLdStM<(outs), (ins QPR:$src, GPR:$Rn),
+  : PseudoVFPLdStM<(outs), (ins DPair:$src, GPR:$Rn),
                     IIC_fpStore_m, "",
-                   [(store (v2f64 QPR:$src), GPR:$Rn)]>;
+                   [(store (v2f64 DPair:$src), GPR:$Rn)]>;
=20
 // Classes for VLD* pseudo-instructions with multi-register operands.
 // These are expanded to real instructions after register allocation.
@@ -197,12 +549,31 @@
   : PseudoNLdSt<(outs QPR:$dst, GPR:$wb),
                 (ins addrmode6:$addr, am6offset:$offset), itin,
                 "$addr.addr =3D $wb">;
+class VLDQWBfixedPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs QPR:$dst, GPR:$wb),
+                (ins addrmode6:$addr), itin,
+                "$addr.addr =3D $wb">;
+class VLDQWBregisterPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs QPR:$dst, GPR:$wb),
+                (ins addrmode6:$addr, rGPR:$offset), itin,
+                "$addr.addr =3D $wb">;
+
 class VLDQQPseudo<InstrItinClass itin>
   : PseudoNLdSt<(outs QQPR:$dst), (ins addrmode6:$addr), itin, "">;
 class VLDQQWBPseudo<InstrItinClass itin>
   : PseudoNLdSt<(outs QQPR:$dst, GPR:$wb),
                 (ins addrmode6:$addr, am6offset:$offset), itin,
                 "$addr.addr =3D $wb">;
+class VLDQQWBfixedPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs QQPR:$dst, GPR:$wb),
+                (ins addrmode6:$addr), itin,
+                "$addr.addr =3D $wb">;
+class VLDQQWBregisterPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs QQPR:$dst, GPR:$wb),
+                (ins addrmode6:$addr, rGPR:$offset), itin,
+                "$addr.addr =3D $wb">;
+
+
 class VLDQQQQPseudo<InstrItinClass itin>
   : PseudoNLdSt<(outs QQQQPR:$dst), (ins addrmode6:$addr, QQQQPR:$src),iti=
n,
                 "$src =3D $dst">;
@@ -215,17 +586,17 @@
=20
 //   VLD1     : Vector Load (multiple single elements)
 class VLD1D<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b0111,op7_4, (outs DPR:$Vd),
+  : NLdSt<0,0b10,0b0111,op7_4, (outs VecListOneD:$Vd),
           (ins addrmode6:$Rn), IIC_VLD1,
-          "vld1", Dt, "\\{$Vd\\}, $Rn", "", []> {
+          "vld1", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVLDInstruction";
 }
 class VLD1Q<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b1010,op7_4, (outs DPR:$Vd, DPR:$dst2),
+  : NLdSt<0,0b10,0b1010,op7_4, (outs VecListDPair:$Vd),
           (ins addrmode6:$Rn), IIC_VLD1x2,
-          "vld1", Dt, "\\{$Vd, $dst2\\}, $Rn", "", []> {
+          "vld1", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{5-4} =3D Rn{5-4};
   let DecoderMethod =3D "DecodeVLDInstruction";
@@ -241,59 +612,82 @@
 def  VLD1q32  : VLD1Q<{1,0,?,?}, "32">;
 def  VLD1q64  : VLD1Q<{1,1,?,?}, "64">;
=20
-def  VLD1q8Pseudo  : VLDQPseudo<IIC_VLD1x2>;
-def  VLD1q16Pseudo : VLDQPseudo<IIC_VLD1x2>;
-def  VLD1q32Pseudo : VLDQPseudo<IIC_VLD1x2>;
-def  VLD1q64Pseudo : VLDQPseudo<IIC_VLD1x2>;
-
 // ...with address register writeback:
-class VLD1DWB<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b0111,op7_4, (outs DPR:$Vd, GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm), IIC_VLD1u,
-          "vld1", Dt, "\\{$Vd\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{4} =3D Rn{4};
-  let DecoderMethod =3D "DecodeVLDInstruction";
-}
-class VLD1QWB<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b1010,op7_4, (outs DPR:$Vd, DPR:$dst2, GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm), IIC_VLD1x2u,
-          "vld1", Dt, "\\{$Vd, $dst2\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVLDInstruction";
-}
-
-def VLD1d8_UPD  : VLD1DWB<{0,0,0,?}, "8">;
-def VLD1d16_UPD : VLD1DWB<{0,1,0,?}, "16">;
-def VLD1d32_UPD : VLD1DWB<{1,0,0,?}, "32">;
-def VLD1d64_UPD : VLD1DWB<{1,1,0,?}, "64">;
-
-def VLD1q8_UPD  : VLD1QWB<{0,0,?,?}, "8">;
-def VLD1q16_UPD : VLD1QWB<{0,1,?,?}, "16">;
-def VLD1q32_UPD : VLD1QWB<{1,0,?,?}, "32">;
-def VLD1q64_UPD : VLD1QWB<{1,1,?,?}, "64">;
-
-def VLD1q8Pseudo_UPD  : VLDQWBPseudo<IIC_VLD1x2u>;
-def VLD1q16Pseudo_UPD : VLDQWBPseudo<IIC_VLD1x2u>;
-def VLD1q32Pseudo_UPD : VLDQWBPseudo<IIC_VLD1x2u>;
-def VLD1q64Pseudo_UPD : VLDQWBPseudo<IIC_VLD1x2u>;
-
-// ...with 3 registers (some of these are only for the disassembler):
+multiclass VLD1DWB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b10, 0b0111,op7_4, (outs VecListOneD:$Vd, GPR:$wb),
+                     (ins addrmode6:$Rn), IIC_VLD1u,
+                     "vld1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<0,0b10,0b0111,op7_4, (outs VecListOneD:$Vd, GPR:$w=
b),
+                        (ins addrmode6:$Rn, rGPR:$Rm), IIC_VLD1u,
+                        "vld1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
+}
+multiclass VLD1QWB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b10,0b1010,op7_4, (outs VecListDPair:$Vd, GPR:$wb),
+                    (ins addrmode6:$Rn), IIC_VLD1x2u,
+                     "vld1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<0,0b10,0b1010,op7_4, (outs VecListDPair:$Vd, GPR:$=
wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm), IIC_VLD1x2u,
+                        "vld1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
+}
+
+defm VLD1d8wb  : VLD1DWB<{0,0,0,?}, "8">;
+defm VLD1d16wb : VLD1DWB<{0,1,0,?}, "16">;
+defm VLD1d32wb : VLD1DWB<{1,0,0,?}, "32">;
+defm VLD1d64wb : VLD1DWB<{1,1,0,?}, "64">;
+defm VLD1q8wb  : VLD1QWB<{0,0,?,?}, "8">;
+defm VLD1q16wb : VLD1QWB<{0,1,?,?}, "16">;
+defm VLD1q32wb : VLD1QWB<{1,0,?,?}, "32">;
+defm VLD1q64wb : VLD1QWB<{1,1,?,?}, "64">;
+
+// ...with 3 registers
 class VLD1D3<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b0110,op7_4, (outs DPR:$Vd, DPR:$dst2, DPR:$dst3),
+  : NLdSt<0,0b10,0b0110,op7_4, (outs VecListThreeD:$Vd),
           (ins addrmode6:$Rn), IIC_VLD1x3, "vld1", Dt,
-          "\\{$Vd, $dst2, $dst3\\}, $Rn", "", []> {
+          "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVLDInstruction";
 }
-class VLD1D3WB<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b0110,op7_4, (outs DPR:$Vd, DPR:$dst2, DPR:$dst3, GPR:$w=
b),
-          (ins addrmode6:$Rn, am6offset:$Rm), IIC_VLD1x3u, "vld1", Dt,
-          "\\{$Vd, $dst2, $dst3\\}, $Rn$Rm", "$Rn.addr =3D $wb", []> {
-  let Inst{4} =3D Rn{4};
-  let DecoderMethod =3D "DecodeVLDInstruction";
+multiclass VLD1D3WB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b10,0b0110, op7_4, (outs VecListThreeD:$Vd, GPR:$w=
b),
+                    (ins addrmode6:$Rn), IIC_VLD1x2u,
+                     "vld1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<0,0b10,0b0110,op7_4, (outs VecListThreeD:$Vd, GPR:=
$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm), IIC_VLD1x2u,
+                        "vld1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
 }
=20
 def VLD1d8T      : VLD1D3<{0,0,0,?}, "8">;
@@ -301,31 +695,40 @@
 def VLD1d32T     : VLD1D3<{1,0,0,?}, "32">;
 def VLD1d64T     : VLD1D3<{1,1,0,?}, "64">;
=20
-def VLD1d8T_UPD  : VLD1D3WB<{0,0,0,?}, "8">;
-def VLD1d16T_UPD : VLD1D3WB<{0,1,0,?}, "16">;
-def VLD1d32T_UPD : VLD1D3WB<{1,0,0,?}, "32">;
-def VLD1d64T_UPD : VLD1D3WB<{1,1,0,?}, "64">;
-
-def VLD1d64TPseudo     : VLDQQPseudo<IIC_VLD1x3>;
-def VLD1d64TPseudo_UPD : VLDQQWBPseudo<IIC_VLD1x3u>;
-
-// ...with 4 registers (some of these are only for the disassembler):
+defm VLD1d8Twb  : VLD1D3WB<{0,0,0,?}, "8">;
+defm VLD1d16Twb : VLD1D3WB<{0,1,0,?}, "16">;
+defm VLD1d32Twb : VLD1D3WB<{1,0,0,?}, "32">;
+defm VLD1d64Twb : VLD1D3WB<{1,1,0,?}, "64">;
+
+def VLD1d64TPseudo : VLDQQPseudo<IIC_VLD1x3>;
+
+// ...with 4 registers
 class VLD1D4<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b0010,op7_4,(outs DPR:$Vd, DPR:$dst2, DPR:$dst3, DPR:$ds=
t4),
+  : NLdSt<0, 0b10, 0b0010, op7_4, (outs VecListFourD:$Vd),
           (ins addrmode6:$Rn), IIC_VLD1x4, "vld1", Dt,
-          "\\{$Vd, $dst2, $dst3, $dst4\\}, $Rn", "", []> {
+          "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{5-4} =3D Rn{5-4};
   let DecoderMethod =3D "DecodeVLDInstruction";
 }
-class VLD1D4WB<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b10,0b0010,op7_4,
-          (outs DPR:$Vd, DPR:$dst2, DPR:$dst3, DPR:$dst4, GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm), IIC_VLD1x4u, "vld1", Dt,
-          "\\{$Vd, $dst2, $dst3, $dst4\\}, $Rn$Rm", "$Rn.addr =3D $wb",
-          []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVLDInstruction";
+multiclass VLD1D4WB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b10,0b0010, op7_4, (outs VecListFourD:$Vd, GPR:$wb=
),
+                    (ins addrmode6:$Rn), IIC_VLD1x2u,
+                     "vld1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<0,0b10,0b0010,op7_4, (outs VecListFourD:$Vd, GPR:$=
wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm), IIC_VLD1x2u,
+                        "vld1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
 }
=20
 def VLD1d8Q      : VLD1D4<{0,0,?,?}, "8">;
@@ -333,91 +736,80 @@
 def VLD1d32Q     : VLD1D4<{1,0,?,?}, "32">;
 def VLD1d64Q     : VLD1D4<{1,1,?,?}, "64">;
=20
-def VLD1d8Q_UPD  : VLD1D4WB<{0,0,?,?}, "8">;
-def VLD1d16Q_UPD : VLD1D4WB<{0,1,?,?}, "16">;
-def VLD1d32Q_UPD : VLD1D4WB<{1,0,?,?}, "32">;
-def VLD1d64Q_UPD : VLD1D4WB<{1,1,?,?}, "64">;
-
-def VLD1d64QPseudo     : VLDQQPseudo<IIC_VLD1x4>;
-def VLD1d64QPseudo_UPD : VLDQQWBPseudo<IIC_VLD1x4u>;
+defm VLD1d8Qwb   : VLD1D4WB<{0,0,?,?}, "8">;
+defm VLD1d16Qwb  : VLD1D4WB<{0,1,?,?}, "16">;
+defm VLD1d32Qwb  : VLD1D4WB<{1,0,?,?}, "32">;
+defm VLD1d64Qwb  : VLD1D4WB<{1,1,?,?}, "64">;
+
+def VLD1d64QPseudo : VLDQQPseudo<IIC_VLD1x4>;
=20
 //   VLD2     : Vector Load (multiple 2-element structures)
-class VLD2D<bits<4> op11_8, bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b10, op11_8, op7_4, (outs DPR:$Vd, DPR:$dst2),
-          (ins addrmode6:$Rn), IIC_VLD2,
-          "vld2", Dt, "\\{$Vd, $dst2\\}, $Rn", "", []> {
+class VLD2<bits<4> op11_8, bits<4> op7_4, string Dt, RegisterOperand VdTy,
+           InstrItinClass itin>
+  : NLdSt<0, 0b10, op11_8, op7_4, (outs VdTy:$Vd),
+          (ins addrmode6:$Rn), itin,
+          "vld2", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{5-4} =3D Rn{5-4};
   let DecoderMethod =3D "DecodeVLDInstruction";
 }
-class VLD2Q<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b10, 0b0011, op7_4,
-          (outs DPR:$Vd, DPR:$dst2, DPR:$dst3, DPR:$dst4),
-          (ins addrmode6:$Rn), IIC_VLD2x2,
-          "vld2", Dt, "\\{$Vd, $dst2, $dst3, $dst4\\}, $Rn", "", []> {
-  let Rm =3D 0b1111;
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVLDInstruction";
-}
-
-def  VLD2d8   : VLD2D<0b1000, {0,0,?,?}, "8">;
-def  VLD2d16  : VLD2D<0b1000, {0,1,?,?}, "16">;
-def  VLD2d32  : VLD2D<0b1000, {1,0,?,?}, "32">;
-
-def  VLD2q8   : VLD2Q<{0,0,?,?}, "8">;
-def  VLD2q16  : VLD2Q<{0,1,?,?}, "16">;
-def  VLD2q32  : VLD2Q<{1,0,?,?}, "32">;
-
-def  VLD2d8Pseudo  : VLDQPseudo<IIC_VLD2>;
-def  VLD2d16Pseudo : VLDQPseudo<IIC_VLD2>;
-def  VLD2d32Pseudo : VLDQPseudo<IIC_VLD2>;
+
+def  VLD2d8   : VLD2<0b1000, {0,0,?,?}, "8", VecListDPair, IIC_VLD2>;
+def  VLD2d16  : VLD2<0b1000, {0,1,?,?}, "16", VecListDPair, IIC_VLD2>;
+def  VLD2d32  : VLD2<0b1000, {1,0,?,?}, "32", VecListDPair, IIC_VLD2>;
+
+def  VLD2q8   : VLD2<0b0011, {0,0,?,?}, "8", VecListFourD, IIC_VLD2x2>;
+def  VLD2q16  : VLD2<0b0011, {0,1,?,?}, "16", VecListFourD, IIC_VLD2x2>;
+def  VLD2q32  : VLD2<0b0011, {1,0,?,?}, "32", VecListFourD, IIC_VLD2x2>;
=20
 def  VLD2q8Pseudo  : VLDQQPseudo<IIC_VLD2x2>;
 def  VLD2q16Pseudo : VLDQQPseudo<IIC_VLD2x2>;
 def  VLD2q32Pseudo : VLDQQPseudo<IIC_VLD2x2>;
=20
 // ...with address register writeback:
-class VLD2DWB<bits<4> op11_8, bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b10, op11_8, op7_4, (outs DPR:$Vd, DPR:$dst2, GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm), IIC_VLD2u,
-          "vld2", Dt, "\\{$Vd, $dst2\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVLDInstruction";
-}
-class VLD2QWB<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b10, 0b0011, op7_4,
-          (outs DPR:$Vd, DPR:$dst2, DPR:$dst3, DPR:$dst4, GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm), IIC_VLD2x2u,
-          "vld2", Dt, "\\{$Vd, $dst2, $dst3, $dst4\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVLDInstruction";
-}
-
-def VLD2d8_UPD  : VLD2DWB<0b1000, {0,0,?,?}, "8">;
-def VLD2d16_UPD : VLD2DWB<0b1000, {0,1,?,?}, "16">;
-def VLD2d32_UPD : VLD2DWB<0b1000, {1,0,?,?}, "32">;
-
-def VLD2q8_UPD  : VLD2QWB<{0,0,?,?}, "8">;
-def VLD2q16_UPD : VLD2QWB<{0,1,?,?}, "16">;
-def VLD2q32_UPD : VLD2QWB<{1,0,?,?}, "32">;
-
-def VLD2d8Pseudo_UPD  : VLDQWBPseudo<IIC_VLD2u>;
-def VLD2d16Pseudo_UPD : VLDQWBPseudo<IIC_VLD2u>;
-def VLD2d32Pseudo_UPD : VLDQWBPseudo<IIC_VLD2u>;
-
-def VLD2q8Pseudo_UPD  : VLDQQWBPseudo<IIC_VLD2x2u>;
-def VLD2q16Pseudo_UPD : VLDQQWBPseudo<IIC_VLD2x2u>;
-def VLD2q32Pseudo_UPD : VLDQQWBPseudo<IIC_VLD2x2u>;
-
-// ...with double-spaced registers (for disassembly only):
-def VLD2b8      : VLD2D<0b1001, {0,0,?,?}, "8">;
-def VLD2b16     : VLD2D<0b1001, {0,1,?,?}, "16">;
-def VLD2b32     : VLD2D<0b1001, {1,0,?,?}, "32">;
-def VLD2b8_UPD  : VLD2DWB<0b1001, {0,0,?,?}, "8">;
-def VLD2b16_UPD : VLD2DWB<0b1001, {0,1,?,?}, "16">;
-def VLD2b32_UPD : VLD2DWB<0b1001, {1,0,?,?}, "32">;
+multiclass VLD2WB<bits<4> op11_8, bits<4> op7_4, string Dt,
+                  RegisterOperand VdTy, InstrItinClass itin> {
+  def _fixed : NLdSt<0, 0b10, op11_8, op7_4, (outs VdTy:$Vd, GPR:$wb),
+                     (ins addrmode6:$Rn), itin,
+                     "vld2", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<0, 0b10, op11_8, op7_4, (outs VdTy:$Vd, GPR:$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm), itin,
+                        "vld2", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVLDInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
+}
+
+defm VLD2d8wb  : VLD2WB<0b1000, {0,0,?,?}, "8", VecListDPair, IIC_VLD2u>;
+defm VLD2d16wb : VLD2WB<0b1000, {0,1,?,?}, "16", VecListDPair, IIC_VLD2u>;
+defm VLD2d32wb : VLD2WB<0b1000, {1,0,?,?}, "32", VecListDPair, IIC_VLD2u>;
+
+defm VLD2q8wb  : VLD2WB<0b0011, {0,0,?,?}, "8", VecListFourD, IIC_VLD2x2u>;
+defm VLD2q16wb : VLD2WB<0b0011, {0,1,?,?}, "16", VecListFourD, IIC_VLD2x2u=
>;
+defm VLD2q32wb : VLD2WB<0b0011, {1,0,?,?}, "32", VecListFourD, IIC_VLD2x2u=
>;
+
+def VLD2q8PseudoWB_fixed     : VLDQQWBfixedPseudo<IIC_VLD2x2u>;
+def VLD2q16PseudoWB_fixed    : VLDQQWBfixedPseudo<IIC_VLD2x2u>;
+def VLD2q32PseudoWB_fixed    : VLDQQWBfixedPseudo<IIC_VLD2x2u>;
+def VLD2q8PseudoWB_register  : VLDQQWBregisterPseudo<IIC_VLD2x2u>;
+def VLD2q16PseudoWB_register : VLDQQWBregisterPseudo<IIC_VLD2x2u>;
+def VLD2q32PseudoWB_register : VLDQQWBregisterPseudo<IIC_VLD2x2u>;
+
+// ...with double-spaced registers
+def  VLD2b8    : VLD2<0b1001, {0,0,?,?}, "8", VecListDPairSpaced, IIC_VLD2=
>;
+def  VLD2b16   : VLD2<0b1001, {0,1,?,?}, "16", VecListDPairSpaced, IIC_VLD=
2>;
+def  VLD2b32   : VLD2<0b1001, {1,0,?,?}, "32", VecListDPairSpaced, IIC_VLD=
2>;
+defm VLD2b8wb  : VLD2WB<0b1001, {0,0,?,?}, "8", VecListDPairSpaced, IIC_VL=
D2u>;
+defm VLD2b16wb : VLD2WB<0b1001, {0,1,?,?}, "16", VecListDPairSpaced, IIC_V=
LD2u>;
+defm VLD2b32wb : VLD2WB<0b1001, {1,0,?,?}, "32", VecListDPairSpaced, IIC_V=
LD2u>;
=20
 //   VLD3     : Vector Load (multiple 3-element structures)
 class VLD3D<bits<4> op11_8, bits<4> op7_4, string Dt>
@@ -601,12 +993,11 @@
 }
 def VLD1LNd16 : VLD1LN<0b0100, {?,?,0,?}, "16", v4i16, extloadi16> {
   let Inst{7-6} =3D lane{1-0};
-  let Inst{4}   =3D Rn{4};
+  let Inst{5-4} =3D Rn{5-4};
 }
 def VLD1LNd32 : VLD1LN32<0b1000, {?,0,?,?}, "32", v2i32, load> {
   let Inst{7} =3D lane{0};
-  let Inst{5} =3D Rn{4};
-  let Inst{4} =3D Rn{4};
+  let Inst{5-4} =3D Rn{5-4};
 }
=20
 def VLD1LNq8Pseudo  : VLD1QLNPseudo<v16i8, extloadi8>;
@@ -776,7 +1167,7 @@
   let Inst{7-6} =3D lane{1-0};
 }
 def VLD3LNd32_UPD : VLD3LNWB<0b1010, {?,0,0,0}, "32"> {
-  let Inst{7}   =3D lane{0};
+  let Inst{7} =3D lane{0};
 }
=20
 def VLD3LNd8Pseudo_UPD  : VLDQQLNWBPseudo<IIC_VLD3lnu>;
@@ -787,7 +1178,7 @@
   let Inst{7-6} =3D lane{1-0};
 }
 def VLD3LNq32_UPD : VLD3LNWB<0b1010, {?,1,0,0}, "32"> {
-  let Inst{7}   =3D lane{0};
+  let Inst{7} =3D lane{0};
 }
=20
 def VLD3LNq16Pseudo_UPD : VLDQQQQLNWBPseudo<IIC_VLD3lnu>;
@@ -802,7 +1193,7 @@
           "\\{$Vd[$lane], $dst2[$lane], $dst3[$lane], $dst4[$lane]\\}, $Rn=
",
           "$src1 =3D $Vd, $src2 =3D $dst2, $src3 =3D $dst3, $src4 =3D $dst=
4", []> {
   let Rm =3D 0b1111;
-  let Inst{4}   =3D Rn{4};
+  let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVLD4LN";
 }
=20
@@ -813,7 +1204,7 @@
   let Inst{7-6} =3D lane{1-0};
 }
 def VLD4LNd32 : VLD4LN<0b1011, {?,0,?,?}, "32"> {
-  let Inst{7}   =3D lane{0};
+  let Inst{7} =3D lane{0};
   let Inst{5} =3D Rn{5};
 }
=20
@@ -826,7 +1217,7 @@
   let Inst{7-6} =3D lane{1-0};
 }
 def VLD4LNq32 : VLD4LN<0b1011, {?,1,?,?}, "32"> {
-  let Inst{7}   =3D lane{0};
+  let Inst{7} =3D lane{0};
   let Inst{5} =3D Rn{5};
 }
=20
@@ -854,7 +1245,7 @@
   let Inst{7-6} =3D lane{1-0};
 }
 def VLD4LNd32_UPD : VLD4LNWB<0b1011, {?,0,?,?}, "32"> {
-  let Inst{7}   =3D lane{0};
+  let Inst{7} =3D lane{0};
   let Inst{5} =3D Rn{5};
 }
=20
@@ -866,7 +1257,7 @@
   let Inst{7-6} =3D lane{1-0};
 }
 def VLD4LNq32_UPD : VLD4LNWB<0b1011, {?,1,?,?}, "32"> {
-  let Inst{7}   =3D lane{0};
+  let Inst{7} =3D lane{0};
   let Inst{5} =3D Rn{5};
 }
=20
@@ -877,117 +1268,142 @@
=20
 //   VLD1DUP  : Vector Load (single element to all lanes)
 class VLD1DUP<bits<4> op7_4, string Dt, ValueType Ty, PatFrag LoadOp>
-  : NLdSt<1, 0b10, 0b1100, op7_4, (outs DPR:$Vd), (ins addrmode6dup:$Rn),
-          IIC_VLD1dup, "vld1", Dt, "\\{$Vd[]\\}, $Rn", "",
-          [(set DPR:$Vd, (Ty (NEONvdup (i32 (LoadOp addrmode6dup:$Rn)))))]=
> {
+  : NLdSt<1, 0b10, 0b1100, op7_4, (outs VecListOneDAllLanes:$Vd),
+          (ins addrmode6dup:$Rn),
+          IIC_VLD1dup, "vld1", Dt, "$Vd, $Rn", "",
+          [(set VecListOneDAllLanes:$Vd,
+                (Ty (NEONvdup (i32 (LoadOp addrmode6dup:$Rn)))))]> {
   let Rm =3D 0b1111;
   let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVLD1DupInstruction";
 }
-class VLD1QDUPPseudo<ValueType Ty, PatFrag LoadOp> : VLDQPseudo<IIC_VLD1du=
p> {
-  let Pattern =3D [(set QPR:$dst,
-                      (Ty (NEONvdup (i32 (LoadOp addrmode6dup:$addr)))))];
-}
-
 def VLD1DUPd8  : VLD1DUP<{0,0,0,?}, "8", v8i8, extloadi8>;
 def VLD1DUPd16 : VLD1DUP<{0,1,0,?}, "16", v4i16, extloadi16>;
 def VLD1DUPd32 : VLD1DUP<{1,0,0,?}, "32", v2i32, load>;
=20
-def VLD1DUPq8Pseudo  : VLD1QDUPPseudo<v16i8, extloadi8>;
-def VLD1DUPq16Pseudo : VLD1QDUPPseudo<v8i16, extloadi16>;
-def VLD1DUPq32Pseudo : VLD1QDUPPseudo<v4i32, load>;
-
 def : Pat<(v2f32 (NEONvdup (f32 (load addrmode6dup:$addr)))),
           (VLD1DUPd32 addrmode6:$addr)>;
-def : Pat<(v4f32 (NEONvdup (f32 (load addrmode6dup:$addr)))),
-          (VLD1DUPq32Pseudo addrmode6:$addr)>;
-
-let mayLoad =3D 1, neverHasSideEffects =3D 1, hasExtraDefRegAllocReq =3D 1=
 in {
-
-class VLD1QDUP<bits<4> op7_4, string Dt>
-  : NLdSt<1, 0b10, 0b1100, op7_4, (outs DPR:$Vd, DPR:$dst2),
+
+class VLD1QDUP<bits<4> op7_4, string Dt, ValueType Ty, PatFrag LoadOp>
+  : NLdSt<1, 0b10, 0b1100, op7_4, (outs VecListDPairAllLanes:$Vd),
           (ins addrmode6dup:$Rn), IIC_VLD1dup,
-          "vld1", Dt, "\\{$Vd[], $dst2[]\\}, $Rn", "", []> {
+          "vld1", Dt, "$Vd, $Rn", "",
+          [(set VecListDPairAllLanes:$Vd,
+                (Ty (NEONvdup (i32 (LoadOp addrmode6dup:$Rn)))))]> {
   let Rm =3D 0b1111;
   let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVLD1DupInstruction";
 }
=20
-def VLD1DUPq8  : VLD1QDUP<{0,0,1,0}, "8">;
-def VLD1DUPq16 : VLD1QDUP<{0,1,1,?}, "16">;
-def VLD1DUPq32 : VLD1QDUP<{1,0,1,?}, "32">;
-
+def VLD1DUPq8  : VLD1QDUP<{0,0,1,0}, "8", v16i8, extloadi8>;
+def VLD1DUPq16 : VLD1QDUP<{0,1,1,?}, "16", v8i16, extloadi16>;
+def VLD1DUPq32 : VLD1QDUP<{1,0,1,?}, "32", v4i32, load>;
+
+def : Pat<(v4f32 (NEONvdup (f32 (load addrmode6dup:$addr)))),
+          (VLD1DUPq32 addrmode6:$addr)>;
+
+let mayLoad =3D 1, neverHasSideEffects =3D 1, hasExtraDefRegAllocReq =3D 1=
 in {
 // ...with address register writeback:
-class VLD1DUPWB<bits<4> op7_4, string Dt>
-  : NLdSt<1, 0b10, 0b1100, op7_4, (outs DPR:$Vd, GPR:$wb),
-          (ins addrmode6dup:$Rn, am6offset:$Rm), IIC_VLD1dupu,
-          "vld1", Dt, "\\{$Vd[]\\}, $Rn$Rm", "$Rn.addr =3D $wb", []> {
-  let Inst{4} =3D Rn{4};
-  let DecoderMethod =3D "DecodeVLD1DupInstruction";
-}
-class VLD1QDUPWB<bits<4> op7_4, string Dt>
-  : NLdSt<1, 0b10, 0b1100, op7_4, (outs DPR:$Vd, DPR:$dst2, GPR:$wb),
-          (ins addrmode6dup:$Rn, am6offset:$Rm), IIC_VLD1dupu,
-          "vld1", Dt, "\\{$Vd[], $dst2[]\\}, $Rn$Rm", "$Rn.addr =3D $wb", =
[]> {
-  let Inst{4} =3D Rn{4};
-  let DecoderMethod =3D "DecodeVLD1DupInstruction";
-}
-
-def VLD1DUPd8_UPD  : VLD1DUPWB<{0,0,0,0}, "8">;
-def VLD1DUPd16_UPD : VLD1DUPWB<{0,1,0,?}, "16">;
-def VLD1DUPd32_UPD : VLD1DUPWB<{1,0,0,?}, "32">;
-
-def VLD1DUPq8_UPD  : VLD1QDUPWB<{0,0,1,0}, "8">;
-def VLD1DUPq16_UPD : VLD1QDUPWB<{0,1,1,?}, "16">;
-def VLD1DUPq32_UPD : VLD1QDUPWB<{1,0,1,?}, "32">;
-
-def VLD1DUPq8Pseudo_UPD  : VLDQWBPseudo<IIC_VLD1dupu>;
-def VLD1DUPq16Pseudo_UPD : VLDQWBPseudo<IIC_VLD1dupu>;
-def VLD1DUPq32Pseudo_UPD : VLDQWBPseudo<IIC_VLD1dupu>;
+multiclass VLD1DUPWB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<1, 0b10, 0b1100, op7_4,
+                     (outs VecListOneDAllLanes:$Vd, GPR:$wb),
+                     (ins addrmode6dup:$Rn), IIC_VLD1dupu,
+                     "vld1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLD1DupInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<1, 0b10, 0b1100, op7_4,
+                        (outs VecListOneDAllLanes:$Vd, GPR:$wb),
+                        (ins addrmode6dup:$Rn, rGPR:$Rm), IIC_VLD1dupu,
+                        "vld1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLD1DupInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
+}
+multiclass VLD1QDUPWB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<1, 0b10, 0b1100, op7_4,
+                     (outs VecListDPairAllLanes:$Vd, GPR:$wb),
+                     (ins addrmode6dup:$Rn), IIC_VLD1dupu,
+                     "vld1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLD1DupInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<1, 0b10, 0b1100, op7_4,
+                        (outs VecListDPairAllLanes:$Vd, GPR:$wb),
+                        (ins addrmode6dup:$Rn, rGPR:$Rm), IIC_VLD1dupu,
+                        "vld1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLD1DupInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
+}
+
+defm VLD1DUPd8wb  : VLD1DUPWB<{0,0,0,0}, "8">;
+defm VLD1DUPd16wb : VLD1DUPWB<{0,1,0,?}, "16">;
+defm VLD1DUPd32wb : VLD1DUPWB<{1,0,0,?}, "32">;
+
+defm VLD1DUPq8wb  : VLD1QDUPWB<{0,0,1,0}, "8">;
+defm VLD1DUPq16wb : VLD1QDUPWB<{0,1,1,?}, "16">;
+defm VLD1DUPq32wb : VLD1QDUPWB<{1,0,1,?}, "32">;
=20
 //   VLD2DUP  : Vector Load (single 2-element structure to all lanes)
-class VLD2DUP<bits<4> op7_4, string Dt>
-  : NLdSt<1, 0b10, 0b1101, op7_4, (outs DPR:$Vd, DPR:$dst2),
+class VLD2DUP<bits<4> op7_4, string Dt, RegisterOperand VdTy>
+  : NLdSt<1, 0b10, 0b1101, op7_4, (outs VdTy:$Vd),
           (ins addrmode6dup:$Rn), IIC_VLD2dup,
-          "vld2", Dt, "\\{$Vd[], $dst2[]\\}, $Rn", "", []> {
+          "vld2", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVLD2DupInstruction";
 }
=20
-def VLD2DUPd8  : VLD2DUP<{0,0,0,?}, "8">;
-def VLD2DUPd16 : VLD2DUP<{0,1,0,?}, "16">;
-def VLD2DUPd32 : VLD2DUP<{1,0,0,?}, "32">;
-
-def VLD2DUPd8Pseudo  : VLDQPseudo<IIC_VLD2dup>;
-def VLD2DUPd16Pseudo : VLDQPseudo<IIC_VLD2dup>;
-def VLD2DUPd32Pseudo : VLDQPseudo<IIC_VLD2dup>;
-
-// ...with double-spaced registers (not used for codegen):
-def VLD2DUPd8x2  : VLD2DUP<{0,0,1,?}, "8">;
-def VLD2DUPd16x2 : VLD2DUP<{0,1,1,?}, "16">;
-def VLD2DUPd32x2 : VLD2DUP<{1,0,1,?}, "32">;
+def VLD2DUPd8  : VLD2DUP<{0,0,0,?}, "8",  VecListDPairAllLanes>;
+def VLD2DUPd16 : VLD2DUP<{0,1,0,?}, "16", VecListDPairAllLanes>;
+def VLD2DUPd32 : VLD2DUP<{1,0,0,?}, "32", VecListDPairAllLanes>;
+
+// ...with double-spaced registers
+def VLD2DUPd8x2  : VLD2DUP<{0,0,1,?}, "8",  VecListDPairSpacedAllLanes>;
+def VLD2DUPd16x2 : VLD2DUP<{0,1,1,?}, "16", VecListDPairSpacedAllLanes>;
+def VLD2DUPd32x2 : VLD2DUP<{1,0,1,?}, "32", VecListDPairSpacedAllLanes>;
=20
 // ...with address register writeback:
-class VLD2DUPWB<bits<4> op7_4, string Dt>
-  : NLdSt<1, 0b10, 0b1101, op7_4, (outs DPR:$Vd, DPR:$dst2, GPR:$wb),
-          (ins addrmode6dup:$Rn, am6offset:$Rm), IIC_VLD2dupu,
-          "vld2", Dt, "\\{$Vd[], $dst2[]\\}, $Rn$Rm", "$Rn.addr =3D $wb", =
[]> {
-  let Inst{4} =3D Rn{4};
-  let DecoderMethod =3D "DecodeVLD2DupInstruction";
-}
-
-def VLD2DUPd8_UPD  : VLD2DUPWB<{0,0,0,0}, "8">;
-def VLD2DUPd16_UPD : VLD2DUPWB<{0,1,0,?}, "16">;
-def VLD2DUPd32_UPD : VLD2DUPWB<{1,0,0,?}, "32">;
-
-def VLD2DUPd8x2_UPD  : VLD2DUPWB<{0,0,1,0}, "8">;
-def VLD2DUPd16x2_UPD : VLD2DUPWB<{0,1,1,?}, "16">;
-def VLD2DUPd32x2_UPD : VLD2DUPWB<{1,0,1,?}, "32">;
-
-def VLD2DUPd8Pseudo_UPD  : VLDQWBPseudo<IIC_VLD2dupu>;
-def VLD2DUPd16Pseudo_UPD : VLDQWBPseudo<IIC_VLD2dupu>;
-def VLD2DUPd32Pseudo_UPD : VLDQWBPseudo<IIC_VLD2dupu>;
+multiclass VLD2DUPWB<bits<4> op7_4, string Dt, RegisterOperand VdTy> {
+  def _fixed : NLdSt<1, 0b10, 0b1101, op7_4,
+                     (outs VdTy:$Vd, GPR:$wb),
+                     (ins addrmode6dup:$Rn), IIC_VLD2dupu,
+                     "vld2", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLD2DupInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbFixed";
+  }
+  def _register : NLdSt<1, 0b10, 0b1101, op7_4,
+                        (outs VdTy:$Vd, GPR:$wb),
+                        (ins addrmode6dup:$Rn, rGPR:$Rm), IIC_VLD2dupu,
+                        "vld2", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVLD2DupInstruction";
+    let AsmMatchConverter =3D "cvtVLDwbRegister";
+  }
+}
+
+defm VLD2DUPd8wb    : VLD2DUPWB<{0,0,0,0}, "8",  VecListDPairAllLanes>;
+defm VLD2DUPd16wb   : VLD2DUPWB<{0,1,0,?}, "16", VecListDPairAllLanes>;
+defm VLD2DUPd32wb   : VLD2DUPWB<{1,0,0,?}, "32", VecListDPairAllLanes>;
+
+defm VLD2DUPd8x2wb  : VLD2DUPWB<{0,0,1,0}, "8",  VecListDPairSpacedAllLane=
s>;
+defm VLD2DUPd16x2wb : VLD2DUPWB<{0,1,1,?}, "16", VecListDPairSpacedAllLane=
s>;
+defm VLD2DUPd32x2wb : VLD2DUPWB<{1,0,1,?}, "32", VecListDPairSpacedAllLane=
s>;
=20
 //   VLD3DUP  : Vector Load (single 3-element structure to all lanes)
 class VLD3DUP<bits<4> op7_4, string Dt>
@@ -1008,9 +1424,9 @@
 def VLD3DUPd32Pseudo : VLDQQPseudo<IIC_VLD3dup>;
=20
 // ...with double-spaced registers (not used for codegen):
-def VLD3DUPd8x2  : VLD3DUP<{0,0,1,?}, "8">;
-def VLD3DUPd16x2 : VLD3DUP<{0,1,1,?}, "16">;
-def VLD3DUPd32x2 : VLD3DUP<{1,0,1,?}, "32">;
+def VLD3DUPq8  : VLD3DUP<{0,0,1,?}, "8">;
+def VLD3DUPq16 : VLD3DUP<{0,1,1,?}, "16">;
+def VLD3DUPq32 : VLD3DUP<{1,0,1,?}, "32">;
=20
 // ...with address register writeback:
 class VLD3DUPWB<bits<4> op7_4, string Dt>
@@ -1026,9 +1442,9 @@
 def VLD3DUPd16_UPD : VLD3DUPWB<{0,1,0,?}, "16">;
 def VLD3DUPd32_UPD : VLD3DUPWB<{1,0,0,?}, "32">;
=20
-def VLD3DUPd8x2_UPD  : VLD3DUPWB<{0,0,1,0}, "8">;
-def VLD3DUPd16x2_UPD : VLD3DUPWB<{0,1,1,?}, "16">;
-def VLD3DUPd32x2_UPD : VLD3DUPWB<{1,0,1,?}, "32">;
+def VLD3DUPq8_UPD  : VLD3DUPWB<{0,0,1,0}, "8">;
+def VLD3DUPq16_UPD : VLD3DUPWB<{0,1,1,?}, "16">;
+def VLD3DUPq32_UPD : VLD3DUPWB<{1,0,1,?}, "32">;
=20
 def VLD3DUPd8Pseudo_UPD  : VLDQQWBPseudo<IIC_VLD3dupu>;
 def VLD3DUPd16Pseudo_UPD : VLDQQWBPseudo<IIC_VLD3dupu>;
@@ -1054,9 +1470,9 @@
 def VLD4DUPd32Pseudo : VLDQQPseudo<IIC_VLD4dup>;
=20
 // ...with double-spaced registers (not used for codegen):
-def VLD4DUPd8x2  : VLD4DUP<{0,0,1,?}, "8">;
-def VLD4DUPd16x2 : VLD4DUP<{0,1,1,?}, "16">;
-def VLD4DUPd32x2 : VLD4DUP<{1,?,1,?}, "32"> { let Inst{6} =3D Rn{5}; }
+def VLD4DUPq8  : VLD4DUP<{0,0,1,?}, "8">;
+def VLD4DUPq16 : VLD4DUP<{0,1,1,?}, "16">;
+def VLD4DUPq32 : VLD4DUP<{1,?,1,?}, "32"> { let Inst{6} =3D Rn{5}; }
=20
 // ...with address register writeback:
 class VLD4DUPWB<bits<4> op7_4, string Dt>
@@ -1073,9 +1489,9 @@
 def VLD4DUPd16_UPD : VLD4DUPWB<{0,1,0,?}, "16">;
 def VLD4DUPd32_UPD : VLD4DUPWB<{1,?,0,?}, "32"> { let Inst{6} =3D Rn{5}; }
=20
-def VLD4DUPd8x2_UPD  : VLD4DUPWB<{0,0,1,0}, "8">;
-def VLD4DUPd16x2_UPD : VLD4DUPWB<{0,1,1,?}, "16">;
-def VLD4DUPd32x2_UPD : VLD4DUPWB<{1,?,1,?}, "32"> { let Inst{6} =3D Rn{5};=
 }
+def VLD4DUPq8_UPD  : VLD4DUPWB<{0,0,1,0}, "8">;
+def VLD4DUPq16_UPD : VLD4DUPWB<{0,1,1,?}, "16">;
+def VLD4DUPq32_UPD : VLD4DUPWB<{1,?,1,?}, "32"> { let Inst{6} =3D Rn{5}; }
=20
 def VLD4DUPd8Pseudo_UPD  : VLDQQWBPseudo<IIC_VLD4dupu>;
 def VLD4DUPd16Pseudo_UPD : VLDQQWBPseudo<IIC_VLD4dupu>;
@@ -1093,12 +1509,29 @@
   : PseudoNLdSt<(outs GPR:$wb),
                 (ins addrmode6:$addr, am6offset:$offset, QPR:$src), itin,
                 "$addr.addr =3D $wb">;
+class VSTQWBfixedPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs GPR:$wb),
+                (ins addrmode6:$addr, QPR:$src), itin,
+                "$addr.addr =3D $wb">;
+class VSTQWBregisterPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs GPR:$wb),
+                (ins addrmode6:$addr, rGPR:$offset, QPR:$src), itin,
+                "$addr.addr =3D $wb">;
 class VSTQQPseudo<InstrItinClass itin>
   : PseudoNLdSt<(outs), (ins addrmode6:$addr, QQPR:$src), itin, "">;
 class VSTQQWBPseudo<InstrItinClass itin>
   : PseudoNLdSt<(outs GPR:$wb),
                 (ins addrmode6:$addr, am6offset:$offset, QQPR:$src), itin,
                 "$addr.addr =3D $wb">;
+class VSTQQWBfixedPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs GPR:$wb),
+                (ins addrmode6:$addr, QQPR:$src), itin,
+                "$addr.addr =3D $wb">;
+class VSTQQWBregisterPseudo<InstrItinClass itin>
+  : PseudoNLdSt<(outs GPR:$wb),
+                (ins addrmode6:$addr, rGPR:$offset, QQPR:$src), itin,
+                "$addr.addr =3D $wb">;
+
 class VSTQQQQPseudo<InstrItinClass itin>
   : PseudoNLdSt<(outs), (ins addrmode6:$addr, QQQQPR:$src), itin, "">;
 class VSTQQQQWBPseudo<InstrItinClass itin>
@@ -1108,16 +1541,15 @@
=20
 //   VST1     : Vector Store (multiple single elements)
 class VST1D<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b00,0b0111,op7_4, (outs), (ins addrmode6:$Rn, DPR:$Vd),
-          IIC_VST1, "vst1", Dt, "\\{$Vd\\}, $Rn", "", []> {
+  : NLdSt<0,0b00,0b0111,op7_4, (outs), (ins addrmode6:$Rn, VecListOneD:$Vd=
),
+          IIC_VST1, "vst1", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVSTInstruction";
 }
 class VST1Q<bits<4> op7_4, string Dt>
-  : NLdSt<0,0b00,0b1010,op7_4, (outs),
-          (ins addrmode6:$Rn, DPR:$Vd, DPR:$src2), IIC_VST1x2,
-          "vst1", Dt, "\\{$Vd, $src2\\}, $Rn", "", []> {
+  : NLdSt<0,0b00,0b1010,op7_4, (outs), (ins addrmode6:$Rn, VecListDPair:$V=
d),
+          IIC_VST1x2, "vst1", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{5-4} =3D Rn{5-4};
   let DecoderMethod =3D "DecodeVSTInstruction";
@@ -1133,185 +1565,233 @@
 def  VST1q32  : VST1Q<{1,0,?,?}, "32">;
 def  VST1q64  : VST1Q<{1,1,?,?}, "64">;
=20
-def  VST1q8Pseudo  : VSTQPseudo<IIC_VST1x2>;
-def  VST1q16Pseudo : VSTQPseudo<IIC_VST1x2>;
-def  VST1q32Pseudo : VSTQPseudo<IIC_VST1x2>;
-def  VST1q64Pseudo : VSTQPseudo<IIC_VST1x2>;
-
 // ...with address register writeback:
-class VST1DWB<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, 0b0111, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm, DPR:$Vd), IIC_VST1u,
-          "vst1", Dt, "\\{$Vd\\}, $Rn$Rm", "$Rn.addr =3D $wb", []> {
-  let Inst{4} =3D Rn{4};
-  let DecoderMethod =3D "DecodeVSTInstruction";
-}
-class VST1QWB<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, 0b1010, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm, DPR:$Vd, DPR:$src2),
-          IIC_VST1x2u, "vst1", Dt, "\\{$Vd, $src2\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVSTInstruction";
-}
-
-def VST1d8_UPD  : VST1DWB<{0,0,0,?}, "8">;
-def VST1d16_UPD : VST1DWB<{0,1,0,?}, "16">;
-def VST1d32_UPD : VST1DWB<{1,0,0,?}, "32">;
-def VST1d64_UPD : VST1DWB<{1,1,0,?}, "64">;
-
-def VST1q8_UPD  : VST1QWB<{0,0,?,?}, "8">;
-def VST1q16_UPD : VST1QWB<{0,1,?,?}, "16">;
-def VST1q32_UPD : VST1QWB<{1,0,?,?}, "32">;
-def VST1q64_UPD : VST1QWB<{1,1,?,?}, "64">;
-
-def VST1q8Pseudo_UPD  : VSTQWBPseudo<IIC_VST1x2u>;
-def VST1q16Pseudo_UPD : VSTQWBPseudo<IIC_VST1x2u>;
-def VST1q32Pseudo_UPD : VSTQWBPseudo<IIC_VST1x2u>;
-def VST1q64Pseudo_UPD : VSTQWBPseudo<IIC_VST1x2u>;
-
-// ...with 3 registers (some of these are only for the disassembler):
+multiclass VST1DWB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b00, 0b0111,op7_4, (outs GPR:$wb),
+                     (ins addrmode6:$Rn, VecListOneD:$Vd), IIC_VLD1u,
+                     "vst1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbFixed";
+  }
+  def _register : NLdSt<0,0b00,0b0111,op7_4, (outs GPR:$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm, VecListOneD:$Vd),
+                        IIC_VLD1u,
+                        "vst1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{4} =3D Rn{4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbRegister";
+  }
+}
+multiclass VST1QWB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b00,0b1010,op7_4, (outs GPR:$wb),
+                    (ins addrmode6:$Rn, VecListDPair:$Vd), IIC_VLD1x2u,
+                     "vst1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbFixed";
+  }
+  def _register : NLdSt<0,0b00,0b1010,op7_4, (outs GPR:$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm, VecListDPair:$Vd),
+                        IIC_VLD1x2u,
+                        "vst1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbRegister";
+  }
+}
+
+defm VST1d8wb  : VST1DWB<{0,0,0,?}, "8">;
+defm VST1d16wb : VST1DWB<{0,1,0,?}, "16">;
+defm VST1d32wb : VST1DWB<{1,0,0,?}, "32">;
+defm VST1d64wb : VST1DWB<{1,1,0,?}, "64">;
+
+defm VST1q8wb  : VST1QWB<{0,0,?,?}, "8">;
+defm VST1q16wb : VST1QWB<{0,1,?,?}, "16">;
+defm VST1q32wb : VST1QWB<{1,0,?,?}, "32">;
+defm VST1q64wb : VST1QWB<{1,1,?,?}, "64">;
+
+// ...with 3 registers
 class VST1D3<bits<4> op7_4, string Dt>
   : NLdSt<0, 0b00, 0b0110, op7_4, (outs),
-          (ins addrmode6:$Rn, DPR:$Vd, DPR:$src2, DPR:$src3),
-          IIC_VST1x3, "vst1", Dt, "\\{$Vd, $src2, $src3\\}, $Rn", "", []> {
+          (ins addrmode6:$Rn, VecListThreeD:$Vd),
+          IIC_VST1x3, "vst1", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{4} =3D Rn{4};
   let DecoderMethod =3D "DecodeVSTInstruction";
 }
-class VST1D3WB<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, 0b0110, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm,
-           DPR:$Vd, DPR:$src2, DPR:$src3),
-          IIC_VST1x3u, "vst1", Dt, "\\{$Vd, $src2, $src3\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{4} =3D Rn{4};
-  let DecoderMethod =3D "DecodeVSTInstruction";
-}
-
-def VST1d8T      : VST1D3<{0,0,0,?}, "8">;
-def VST1d16T     : VST1D3<{0,1,0,?}, "16">;
-def VST1d32T     : VST1D3<{1,0,0,?}, "32">;
-def VST1d64T     : VST1D3<{1,1,0,?}, "64">;
-
-def VST1d8T_UPD  : VST1D3WB<{0,0,0,?}, "8">;
-def VST1d16T_UPD : VST1D3WB<{0,1,0,?}, "16">;
-def VST1d32T_UPD : VST1D3WB<{1,0,0,?}, "32">;
-def VST1d64T_UPD : VST1D3WB<{1,1,0,?}, "64">;
-
-def VST1d64TPseudo     : VSTQQPseudo<IIC_VST1x3>;
-def VST1d64TPseudo_UPD : VSTQQWBPseudo<IIC_VST1x3u>;
-
-// ...with 4 registers (some of these are only for the disassembler):
+multiclass VST1D3WB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b00,0b0110,op7_4, (outs GPR:$wb),
+                    (ins addrmode6:$Rn, VecListThreeD:$Vd), IIC_VLD1x3u,
+                     "vst1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbFixed";
+  }
+  def _register : NLdSt<0,0b00,0b0110,op7_4, (outs GPR:$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm, VecListThreeD:$Vd),
+                        IIC_VLD1x3u,
+                        "vst1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbRegister";
+  }
+}
+
+def VST1d8T     : VST1D3<{0,0,0,?}, "8">;
+def VST1d16T    : VST1D3<{0,1,0,?}, "16">;
+def VST1d32T    : VST1D3<{1,0,0,?}, "32">;
+def VST1d64T    : VST1D3<{1,1,0,?}, "64">;
+
+defm VST1d8Twb  : VST1D3WB<{0,0,0,?}, "8">;
+defm VST1d16Twb : VST1D3WB<{0,1,0,?}, "16">;
+defm VST1d32Twb : VST1D3WB<{1,0,0,?}, "32">;
+defm VST1d64Twb : VST1D3WB<{1,1,0,?}, "64">;
+
+def VST1d64TPseudo            : VSTQQPseudo<IIC_VST1x3>;
+def VST1d64TPseudoWB_fixed    : VSTQQWBPseudo<IIC_VST1x3u>;
+def VST1d64TPseudoWB_register : VSTQQWBPseudo<IIC_VST1x3u>;
+
+// ...with 4 registers
 class VST1D4<bits<4> op7_4, string Dt>
   : NLdSt<0, 0b00, 0b0010, op7_4, (outs),
-          (ins addrmode6:$Rn, DPR:$Vd, DPR:$src2, DPR:$src3, DPR:$src4),
-          IIC_VST1x4, "vst1", Dt, "\\{$Vd, $src2, $src3, $src4\\}, $Rn", "=
",
+          (ins addrmode6:$Rn, VecListFourD:$Vd),
+          IIC_VST1x4, "vst1", Dt, "$Vd, $Rn", "",
           []> {
   let Rm =3D 0b1111;
   let Inst{5-4} =3D Rn{5-4};
   let DecoderMethod =3D "DecodeVSTInstruction";
 }
-class VST1D4WB<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, 0b0010, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm,
-           DPR:$Vd, DPR:$src2, DPR:$src3, DPR:$src4), IIC_VST1x4u,
-          "vst1", Dt, "\\{$Vd, $src2, $src3, $src4\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVSTInstruction";
-}
-
-def VST1d8Q      : VST1D4<{0,0,?,?}, "8">;
-def VST1d16Q     : VST1D4<{0,1,?,?}, "16">;
-def VST1d32Q     : VST1D4<{1,0,?,?}, "32">;
-def VST1d64Q     : VST1D4<{1,1,?,?}, "64">;
-
-def VST1d8Q_UPD  : VST1D4WB<{0,0,?,?}, "8">;
-def VST1d16Q_UPD : VST1D4WB<{0,1,?,?}, "16">;
-def VST1d32Q_UPD : VST1D4WB<{1,0,?,?}, "32">;
-def VST1d64Q_UPD : VST1D4WB<{1,1,?,?}, "64">;
-
-def VST1d64QPseudo     : VSTQQPseudo<IIC_VST1x4>;
-def VST1d64QPseudo_UPD : VSTQQWBPseudo<IIC_VST1x4u>;
+multiclass VST1D4WB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0,0b00,0b0010,op7_4, (outs GPR:$wb),
+                    (ins addrmode6:$Rn, VecListFourD:$Vd), IIC_VLD1x4u,
+                     "vst1", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbFixed";
+  }
+  def _register : NLdSt<0,0b00,0b0010,op7_4, (outs GPR:$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm, VecListFourD:$Vd),
+                        IIC_VLD1x4u,
+                        "vst1", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbRegister";
+  }
+}
+
+def VST1d8Q     : VST1D4<{0,0,?,?}, "8">;
+def VST1d16Q    : VST1D4<{0,1,?,?}, "16">;
+def VST1d32Q    : VST1D4<{1,0,?,?}, "32">;
+def VST1d64Q    : VST1D4<{1,1,?,?}, "64">;
+
+defm VST1d8Qwb  : VST1D4WB<{0,0,?,?}, "8">;
+defm VST1d16Qwb : VST1D4WB<{0,1,?,?}, "16">;
+defm VST1d32Qwb : VST1D4WB<{1,0,?,?}, "32">;
+defm VST1d64Qwb : VST1D4WB<{1,1,?,?}, "64">;
+
+def VST1d64QPseudo            : VSTQQPseudo<IIC_VST1x4>;
+def VST1d64QPseudoWB_fixed    : VSTQQWBPseudo<IIC_VST1x4u>;
+def VST1d64QPseudoWB_register : VSTQQWBPseudo<IIC_VST1x4u>;
=20
 //   VST2     : Vector Store (multiple 2-element structures)
-class VST2D<bits<4> op11_8, bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, op11_8, op7_4, (outs),
-          (ins addrmode6:$Rn, DPR:$Vd, DPR:$src2),
-          IIC_VST2, "vst2", Dt, "\\{$Vd, $src2\\}, $Rn", "", []> {
+class VST2<bits<4> op11_8, bits<4> op7_4, string Dt, RegisterOperand VdTy,
+            InstrItinClass itin>
+  : NLdSt<0, 0b00, op11_8, op7_4, (outs), (ins addrmode6:$Rn, VdTy:$Vd),
+          itin, "vst2", Dt, "$Vd, $Rn", "", []> {
   let Rm =3D 0b1111;
   let Inst{5-4} =3D Rn{5-4};
   let DecoderMethod =3D "DecodeVSTInstruction";
 }
-class VST2Q<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, 0b0011, op7_4, (outs),
-          (ins addrmode6:$Rn, DPR:$Vd, DPR:$src2, DPR:$src3, DPR:$src4),
-          IIC_VST2x2, "vst2", Dt, "\\{$Vd, $src2, $src3, $src4\\}, $Rn",
-          "", []> {
-  let Rm =3D 0b1111;
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVSTInstruction";
-}
-
-def  VST2d8   : VST2D<0b1000, {0,0,?,?}, "8">;
-def  VST2d16  : VST2D<0b1000, {0,1,?,?}, "16">;
-def  VST2d32  : VST2D<0b1000, {1,0,?,?}, "32">;
-
-def  VST2q8   : VST2Q<{0,0,?,?}, "8">;
-def  VST2q16  : VST2Q<{0,1,?,?}, "16">;
-def  VST2q32  : VST2Q<{1,0,?,?}, "32">;
-
-def  VST2d8Pseudo  : VSTQPseudo<IIC_VST2>;
-def  VST2d16Pseudo : VSTQPseudo<IIC_VST2>;
-def  VST2d32Pseudo : VSTQPseudo<IIC_VST2>;
+
+def  VST2d8   : VST2<0b1000, {0,0,?,?}, "8",  VecListDPair, IIC_VST2>;
+def  VST2d16  : VST2<0b1000, {0,1,?,?}, "16", VecListDPair, IIC_VST2>;
+def  VST2d32  : VST2<0b1000, {1,0,?,?}, "32", VecListDPair, IIC_VST2>;
+
+def  VST2q8   : VST2<0b0011, {0,0,?,?}, "8",  VecListFourD, IIC_VST2x2>;
+def  VST2q16  : VST2<0b0011, {0,1,?,?}, "16", VecListFourD, IIC_VST2x2>;
+def  VST2q32  : VST2<0b0011, {1,0,?,?}, "32", VecListFourD, IIC_VST2x2>;
=20
 def  VST2q8Pseudo  : VSTQQPseudo<IIC_VST2x2>;
 def  VST2q16Pseudo : VSTQQPseudo<IIC_VST2x2>;
 def  VST2q32Pseudo : VSTQQPseudo<IIC_VST2x2>;
=20
 // ...with address register writeback:
-class VST2DWB<bits<4> op11_8, bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, op11_8, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm, DPR:$Vd, DPR:$src2),
-          IIC_VST2u, "vst2", Dt, "\\{$Vd, $src2\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVSTInstruction";
-}
-class VST2QWB<bits<4> op7_4, string Dt>
-  : NLdSt<0, 0b00, 0b0011, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm,
-           DPR:$Vd, DPR:$src2, DPR:$src3, DPR:$src4), IIC_VST2x2u,
-          "vst2", Dt, "\\{$Vd, $src2, $src3, $src4\\}, $Rn$Rm",
-          "$Rn.addr =3D $wb", []> {
-  let Inst{5-4} =3D Rn{5-4};
-  let DecoderMethod =3D "DecodeVSTInstruction";
-}
-
-def VST2d8_UPD  : VST2DWB<0b1000, {0,0,?,?}, "8">;
-def VST2d16_UPD : VST2DWB<0b1000, {0,1,?,?}, "16">;
-def VST2d32_UPD : VST2DWB<0b1000, {1,0,?,?}, "32">;
-
-def VST2q8_UPD  : VST2QWB<{0,0,?,?}, "8">;
-def VST2q16_UPD : VST2QWB<{0,1,?,?}, "16">;
-def VST2q32_UPD : VST2QWB<{1,0,?,?}, "32">;
-
-def VST2d8Pseudo_UPD  : VSTQWBPseudo<IIC_VST2u>;
-def VST2d16Pseudo_UPD : VSTQWBPseudo<IIC_VST2u>;
-def VST2d32Pseudo_UPD : VSTQWBPseudo<IIC_VST2u>;
-
-def VST2q8Pseudo_UPD  : VSTQQWBPseudo<IIC_VST2x2u>;
-def VST2q16Pseudo_UPD : VSTQQWBPseudo<IIC_VST2x2u>;
-def VST2q32Pseudo_UPD : VSTQQWBPseudo<IIC_VST2x2u>;
-
-// ...with double-spaced registers (for disassembly only):
-def VST2b8      : VST2D<0b1001, {0,0,?,?}, "8">;
-def VST2b16     : VST2D<0b1001, {0,1,?,?}, "16">;
-def VST2b32     : VST2D<0b1001, {1,0,?,?}, "32">;
-def VST2b8_UPD  : VST2DWB<0b1001, {0,0,?,?}, "8">;
-def VST2b16_UPD : VST2DWB<0b1001, {0,1,?,?}, "16">;
-def VST2b32_UPD : VST2DWB<0b1001, {1,0,?,?}, "32">;
+multiclass VST2DWB<bits<4> op11_8, bits<4> op7_4, string Dt,
+                   RegisterOperand VdTy> {
+  def _fixed : NLdSt<0, 0b00, op11_8, op7_4, (outs GPR:$wb),
+                     (ins addrmode6:$Rn, VdTy:$Vd), IIC_VLD1u,
+                     "vst2", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbFixed";
+  }
+  def _register : NLdSt<0, 0b00, op11_8, op7_4, (outs GPR:$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm, VdTy:$Vd), IIC_VLD1u,
+                        "vst2", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbRegister";
+  }
+}
+multiclass VST2QWB<bits<4> op7_4, string Dt> {
+  def _fixed : NLdSt<0, 0b00, 0b0011, op7_4, (outs GPR:$wb),
+                     (ins addrmode6:$Rn, VecListFourD:$Vd), IIC_VLD1u,
+                     "vst2", Dt, "$Vd, $Rn!",
+                     "$Rn.addr =3D $wb", []> {
+    let Rm =3D 0b1101; // NLdSt will assign to the right encoding bits.
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbFixed";
+  }
+  def _register : NLdSt<0, 0b00, 0b0011, op7_4, (outs GPR:$wb),
+                        (ins addrmode6:$Rn, rGPR:$Rm, VecListFourD:$Vd),
+                        IIC_VLD1u,
+                        "vst2", Dt, "$Vd, $Rn, $Rm",
+                        "$Rn.addr =3D $wb", []> {
+    let Inst{5-4} =3D Rn{5-4};
+    let DecoderMethod =3D "DecodeVSTInstruction";
+    let AsmMatchConverter =3D "cvtVSTwbRegister";
+  }
+}
+
+defm VST2d8wb    : VST2DWB<0b1000, {0,0,?,?}, "8",  VecListDPair>;
+defm VST2d16wb   : VST2DWB<0b1000, {0,1,?,?}, "16", VecListDPair>;
+defm VST2d32wb   : VST2DWB<0b1000, {1,0,?,?}, "32", VecListDPair>;
+
+defm VST2q8wb    : VST2QWB<{0,0,?,?}, "8">;
+defm VST2q16wb   : VST2QWB<{0,1,?,?}, "16">;
+defm VST2q32wb   : VST2QWB<{1,0,?,?}, "32">;
+
+def VST2q8PseudoWB_fixed     : VSTQQWBfixedPseudo<IIC_VST2x2u>;
+def VST2q16PseudoWB_fixed    : VSTQQWBfixedPseudo<IIC_VST2x2u>;
+def VST2q32PseudoWB_fixed    : VSTQQWBfixedPseudo<IIC_VST2x2u>;
+def VST2q8PseudoWB_register  : VSTQQWBregisterPseudo<IIC_VST2x2u>;
+def VST2q16PseudoWB_register : VSTQQWBregisterPseudo<IIC_VST2x2u>;
+def VST2q32PseudoWB_register : VSTQQWBregisterPseudo<IIC_VST2x2u>;
+
+// ...with double-spaced registers
+def VST2b8      : VST2<0b1001, {0,0,?,?}, "8",  VecListDPairSpaced, IIC_VS=
T2>;
+def VST2b16     : VST2<0b1001, {0,1,?,?}, "16", VecListDPairSpaced, IIC_VS=
T2>;
+def VST2b32     : VST2<0b1001, {1,0,?,?}, "32", VecListDPairSpaced, IIC_VS=
T2>;
+defm VST2b8wb   : VST2DWB<0b1001, {0,0,?,?}, "8",  VecListDPairSpaced>;
+defm VST2b16wb  : VST2DWB<0b1001, {0,1,?,?}, "16", VecListDPairSpaced>;
+defm VST2b32wb  : VST2DWB<0b1001, {1,0,?,?}, "32", VecListDPairSpaced>;
=20
 //   VST3     : Vector Store (multiple 3-element structures)
 class VST3D<bits<4> op11_8, bits<4> op7_4, string Dt>
@@ -1458,20 +1938,11 @@
=20
 //   VST1LN   : Vector Store (single element from one lane)
 class VST1LN<bits<4> op11_8, bits<4> op7_4, string Dt, ValueType Ty,
-             PatFrag StoreOp, SDNode ExtractOp>
+             PatFrag StoreOp, SDNode ExtractOp, Operand AddrMode>
   : NLdStLn<1, 0b00, op11_8, op7_4, (outs),
-          (ins addrmode6:$Rn, DPR:$Vd, nohash_imm:$lane),
+          (ins AddrMode:$Rn, DPR:$Vd, nohash_imm:$lane),
           IIC_VST1ln, "vst1", Dt, "\\{$Vd[$lane]\\}, $Rn", "",
-          [(StoreOp (ExtractOp (Ty DPR:$Vd), imm:$lane), addrmode6:$Rn)]> {
-  let Rm =3D 0b1111;
-  let DecoderMethod =3D "DecodeVST1LN";
-}
-class VST1LN32<bits<4> op11_8, bits<4> op7_4, string Dt, ValueType Ty,
-             PatFrag StoreOp, SDNode ExtractOp>
-  : NLdStLn<1, 0b00, op11_8, op7_4, (outs),
-          (ins addrmode6oneL32:$Rn, DPR:$Vd, nohash_imm:$lane),
-          IIC_VST1ln, "vst1", Dt, "\\{$Vd[$lane]\\}, $Rn", "",
-          [(StoreOp (ExtractOp (Ty DPR:$Vd), imm:$lane), addrmode6oneL32:$=
Rn)]>{
+          [(StoreOp (ExtractOp (Ty DPR:$Vd), imm:$lane), AddrMode:$Rn)]> {
   let Rm =3D 0b1111;
   let DecoderMethod =3D "DecodeVST1LN";
 }
@@ -1482,16 +1953,17 @@
 }
=20
 def VST1LNd8  : VST1LN<0b0000, {?,?,?,0}, "8", v8i8, truncstorei8,
-                       NEONvgetlaneu> {
+                       NEONvgetlaneu, addrmode6> {
   let Inst{7-5} =3D lane{2-0};
 }
 def VST1LNd16 : VST1LN<0b0100, {?,?,0,?}, "16", v4i16, truncstorei16,
-                       NEONvgetlaneu> {
+                       NEONvgetlaneu, addrmode6> {
   let Inst{7-6} =3D lane{1-0};
   let Inst{4}   =3D Rn{5};
 }
=20
-def VST1LNd32 : VST1LN32<0b1000, {?,0,?,?}, "32", v2i32, store, extractelt=
> {
+def VST1LNd32 : VST1LN<0b1000, {?,0,?,?}, "32", v2i32, store, extractelt,=20
+                       addrmode6oneL32> {
   let Inst{7}   =3D lane{0};
   let Inst{5-4} =3D Rn{5-4};
 }
@@ -1507,14 +1979,14 @@
=20
 // ...with address register writeback:
 class VST1LNWB<bits<4> op11_8, bits<4> op7_4, string Dt, ValueType Ty,
-               PatFrag StoreOp, SDNode ExtractOp>
+               PatFrag StoreOp, SDNode ExtractOp, Operand AdrMode>
   : NLdStLn<1, 0b00, op11_8, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$Rn, am6offset:$Rm,
+          (ins AdrMode:$Rn, am6offset:$Rm,
            DPR:$Vd, nohash_imm:$lane), IIC_VST1lnu, "vst1", Dt,
           "\\{$Vd[$lane]\\}, $Rn$Rm",
           "$Rn.addr =3D $wb",
           [(set GPR:$wb, (StoreOp (ExtractOp (Ty DPR:$Vd), imm:$lane),
-                                  addrmode6:$Rn, am6offset:$Rm))]> {
+                                  AdrMode:$Rn, am6offset:$Rm))]> {
   let DecoderMethod =3D "DecodeVST1LN";
 }
 class VST1QLNWBPseudo<ValueType Ty, PatFrag StoreOp, SDNode ExtractOp>
@@ -1524,16 +1996,16 @@
 }
=20
 def VST1LNd8_UPD  : VST1LNWB<0b0000, {?,?,?,0}, "8", v8i8, post_truncsti8,
-                             NEONvgetlaneu> {
+                             NEONvgetlaneu, addrmode6> {
   let Inst{7-5} =3D lane{2-0};
 }
 def VST1LNd16_UPD : VST1LNWB<0b0100, {?,?,0,?}, "16", v4i16, post_truncsti=
16,
-                             NEONvgetlaneu> {
+                             NEONvgetlaneu, addrmode6> {
   let Inst{7-6} =3D lane{1-0};
   let Inst{4}   =3D Rn{5};
 }
 def VST1LNd32_UPD : VST1LNWB<0b1000, {?,0,?,?}, "32", v2i32, post_store,
-                             extractelt> {
+                             extractelt, addrmode6oneL32> {
   let Inst{7}   =3D lane{0};
   let Inst{5-4} =3D Rn{5-4};
 }
@@ -1585,10 +2057,10 @@
 // ...with address register writeback:
 class VST2LNWB<bits<4> op11_8, bits<4> op7_4, string Dt>
   : NLdStLn<1, 0b00, op11_8, op7_4, (outs GPR:$wb),
-          (ins addrmode6:$addr, am6offset:$offset,
-           DPR:$src1, DPR:$src2, nohash_imm:$lane), IIC_VST2lnu, "vst2", D=
t,
-          "\\{$src1[$lane], $src2[$lane]\\}, $addr$offset",
-          "$addr.addr =3D $wb", []> {
+          (ins addrmode6:$Rn, am6offset:$Rm,
+           DPR:$Vd, DPR:$src2, nohash_imm:$lane), IIC_VST2lnu, "vst2", Dt,
+          "\\{$Vd[$lane], $src2[$lane]\\}, $Rn$Rm",
+          "$Rn.addr =3D $wb", []> {
   let Inst{4}   =3D Rn{4};
   let DecoderMethod =3D "DecodeVST2LN";
 }
@@ -1914,8 +2386,8 @@
              InstrItinClass itin, string OpcodeStr, string Dt,
              ValueType Ty, SDNode ShOp>
   : N3VLane32<0, 1, op21_20, op11_8, 1, 0,
-        (outs DPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs DPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (Ty DPR:$Vd),
               (Ty (ShOp (Ty DPR:$Vn),
                         (Ty (NEONvduplane (Ty DPR_VFP2:$Vm),imm:$lane)))))=
]> {
@@ -1924,8 +2396,8 @@
 class N3VDSL16<bits<2> op21_20, bits<4> op11_8,
                string OpcodeStr, string Dt, ValueType Ty, SDNode ShOp>
   : N3VLane16<0, 1, op21_20, op11_8, 1, 0,
-        (outs DPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, IIC_VMULi16D, OpcodeStr, Dt,"$Vd, $Vn, $Vm[$lane]","",
+        (outs DPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
+        NVMulSLFrm, IIC_VMULi16D, OpcodeStr, Dt,"$Vd, $Vn, $Vm$lane","",
         [(set (Ty DPR:$Vd),
               (Ty (ShOp (Ty DPR:$Vn),
                         (Ty (NEONvduplane (Ty DPR_8:$Vm), imm:$lane)))))]>=
 {
@@ -1954,8 +2426,8 @@
              InstrItinClass itin, string OpcodeStr, string Dt,
              ValueType ResTy, ValueType OpTy, SDNode ShOp>
   : N3VLane32<1, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins QPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs QPR:$Vd), (ins QPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (ResTy QPR:$Vd),
               (ResTy (ShOp (ResTy QPR:$Vn),
                            (ResTy (NEONvduplane (OpTy DPR_VFP2:$Vm),
@@ -1965,8 +2437,8 @@
 class N3VQSL16<bits<2> op21_20, bits<4> op11_8, string OpcodeStr, string D=
t,
                ValueType ResTy, ValueType OpTy, SDNode ShOp>
   : N3VLane16<1, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins QPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, IIC_VMULi16Q, OpcodeStr, Dt,"$Vd, $Vn, $Vm[$lane]","",
+        (outs QPR:$Vd), (ins QPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
+        NVMulSLFrm, IIC_VMULi16Q, OpcodeStr, Dt,"$Vd, $Vn, $Vm$lane", "",
         [(set (ResTy QPR:$Vd),
               (ResTy (ShOp (ResTy QPR:$Vn),
                            (ResTy (NEONvduplane (OpTy DPR_8:$Vm),
@@ -1987,8 +2459,8 @@
 class N3VDIntSL<bits<2> op21_20, bits<4> op11_8, InstrItinClass itin,
                 string OpcodeStr, string Dt, ValueType Ty, Intrinsic IntOp>
   : N3VLane32<0, 1, op21_20, op11_8, 1, 0,
-        (outs DPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs DPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (Ty DPR:$Vd),
               (Ty (IntOp (Ty DPR:$Vn),
                          (Ty (NEONvduplane (Ty DPR_VFP2:$Vm),
@@ -1998,8 +2470,8 @@
 class N3VDIntSL16<bits<2> op21_20, bits<4> op11_8, InstrItinClass itin,
                   string OpcodeStr, string Dt, ValueType Ty, Intrinsic Int=
Op>
   : N3VLane16<0, 1, op21_20, op11_8, 1, 0,
-        (outs DPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs DPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (Ty DPR:$Vd),
               (Ty (IntOp (Ty DPR:$Vn),
                          (Ty (NEONvduplane (Ty DPR_8:$Vm), imm:$lane)))))]=
> {
@@ -2028,8 +2500,8 @@
                 string OpcodeStr, string Dt,
                 ValueType ResTy, ValueType OpTy, Intrinsic IntOp>
   : N3VLane32<1, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins QPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs QPR:$Vd), (ins QPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (ResTy QPR:$Vd),
               (ResTy (IntOp (ResTy QPR:$Vn),
                             (ResTy (NEONvduplane (OpTy DPR_VFP2:$Vm),
@@ -2040,8 +2512,8 @@
                   string OpcodeStr, string Dt,
                   ValueType ResTy, ValueType OpTy, Intrinsic IntOp>
   : N3VLane16<1, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins QPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs QPR:$Vd), (ins QPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (ResTy QPR:$Vd),
               (ResTy (IntOp (ResTy QPR:$Vn),
                             (ResTy (NEONvduplane (OpTy DPR_8:$Vm),
@@ -2073,9 +2545,9 @@
                   ValueType Ty, SDPatternOperator MulOp, SDPatternOperator=
 ShOp>
   : N3VLane32<0, 1, op21_20, op11_8, 1, 0,
         (outs DPR:$Vd),
-        (ins DPR:$src1, DPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
+        (ins DPR:$src1, DPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set (Ty DPR:$Vd),
               (Ty (ShOp (Ty DPR:$src1),
                         (Ty (MulOp DPR:$Vn,
@@ -2086,9 +2558,9 @@
                     ValueType Ty, SDNode MulOp, SDNode ShOp>
   : N3VLane16<0, 1, op21_20, op11_8, 1, 0,
         (outs DPR:$Vd),
-        (ins DPR:$src1, DPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
+        (ins DPR:$src1, DPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set (Ty DPR:$Vd),
               (Ty (ShOp (Ty DPR:$src1),
                         (Ty (MulOp DPR:$Vn,
@@ -2108,9 +2580,9 @@
                   SDPatternOperator MulOp, SDPatternOperator ShOp>
   : N3VLane32<1, 1, op21_20, op11_8, 1, 0,
         (outs QPR:$Vd),
-        (ins QPR:$src1, QPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
+        (ins QPR:$src1, QPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set (ResTy QPR:$Vd),
               (ResTy (ShOp (ResTy QPR:$src1),
                            (ResTy (MulOp QPR:$Vn,
@@ -2122,9 +2594,9 @@
                     SDNode MulOp, SDNode ShOp>
   : N3VLane16<1, 1, op21_20, op11_8, 1, 0,
         (outs QPR:$Vd),
-        (ins QPR:$src1, QPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
+        (ins QPR:$src1, QPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set (ResTy QPR:$Vd),
               (ResTy (ShOp (ResTy QPR:$src1),
                            (ResTy (MulOp QPR:$Vn,
@@ -2182,9 +2654,9 @@
                   InstrItinClass itin, string OpcodeStr, string Dt,
                   ValueType TyQ, ValueType TyD, SDNode MulOp, SDNode OpNod=
e>
   : N3VLane32<op24, 1, op21_20, op11_8, 1, 0, (outs QPR:$Vd),
-        (ins QPR:$src1, DPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
+        (ins QPR:$src1, DPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set QPR:$Vd,
           (OpNode (TyQ QPR:$src1),
                   (TyQ (MulOp (TyD DPR:$Vn),
@@ -2194,9 +2666,9 @@
                     InstrItinClass itin, string OpcodeStr, string Dt,
                     ValueType TyQ, ValueType TyD, SDNode MulOp, SDNode OpN=
ode>
   : N3VLane16<op24, 1, op21_20, op11_8, 1, 0, (outs QPR:$Vd),
-        (ins QPR:$src1, DPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
+        (ins QPR:$src1, DPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set QPR:$Vd,
           (OpNode (TyQ QPR:$src1),
                   (TyQ (MulOp (TyD DPR:$Vn),
@@ -2230,9 +2702,9 @@
                  ValueType ResTy, ValueType OpTy, Intrinsic IntOp>
   : N3VLane32<op24, 1, op21_20, op11_8, 1, 0,
         (outs QPR:$Vd),
-        (ins QPR:$src1, DPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
+        (ins QPR:$src1, DPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set (ResTy QPR:$Vd),
               (ResTy (IntOp (ResTy QPR:$src1),
                             (OpTy DPR:$Vn),
@@ -2243,9 +2715,9 @@
                    ValueType ResTy, ValueType OpTy, Intrinsic IntOp>
   : N3VLane16<op24, 1, op21_20, op11_8, 1, 0,
         (outs QPR:$Vd),
-        (ins QPR:$src1, DPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
+        (ins QPR:$src1, DPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
         NVMulSLFrm, itin,
-        OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "$src1 =3D $Vd",
+        OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "$src1 =3D $Vd",
         [(set (ResTy QPR:$Vd),
               (ResTy (IntOp (ResTy QPR:$src1),
                             (OpTy DPR:$Vn),
@@ -2277,8 +2749,8 @@
              InstrItinClass itin, string OpcodeStr, string Dt,
              ValueType TyQ, ValueType TyD, SDNode OpNode>
   : N3VLane32<op24, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs QPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set QPR:$Vd,
           (TyQ (OpNode (TyD DPR:$Vn),
                        (TyD (NEONvduplane (TyD DPR_VFP2:$Vm),imm:$lane))))=
)]>;
@@ -2286,8 +2758,8 @@
                InstrItinClass itin, string OpcodeStr, string Dt,
                ValueType TyQ, ValueType TyD, SDNode OpNode>
   : N3VLane16<op24, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs QPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set QPR:$Vd,
           (TyQ (OpNode (TyD DPR:$Vn),
                        (TyD (NEONvduplane (TyD DPR_8:$Vm), imm:$lane)))))]=
>;
@@ -2332,8 +2804,8 @@
                 string OpcodeStr, string Dt,
                 ValueType ResTy, ValueType OpTy, Intrinsic IntOp>
   : N3VLane32<op24, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs QPR:$Vd), (ins DPR:$Vn, DPR_VFP2:$Vm, VectorIndex32:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (ResTy QPR:$Vd),
               (ResTy (IntOp (OpTy DPR:$Vn),
                             (OpTy (NEONvduplane (OpTy DPR_VFP2:$Vm),
@@ -2342,8 +2814,8 @@
                   InstrItinClass itin, string OpcodeStr, string Dt,
                   ValueType ResTy, ValueType OpTy, Intrinsic IntOp>
   : N3VLane16<op24, 1, op21_20, op11_8, 1, 0,
-        (outs QPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, nohash_imm:$lane),
-        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm[$lane]", "",
+        (outs QPR:$Vd), (ins DPR:$Vn, DPR_8:$Vm, VectorIndex16:$lane),
+        NVMulSLFrm, itin, OpcodeStr, Dt, "$Vd, $Vn, $Vm$lane", "",
         [(set (ResTy QPR:$Vd),
               (ResTy (IntOp (OpTy DPR:$Vn),
                             (OpTy (NEONvduplane (OpTy DPR_8:$Vm),
@@ -2417,9 +2889,9 @@
 // Long shift by immediate.
 class N2VLSh<bit op24, bit op23, bits<4> op11_8, bit op7, bit op6, bit op4,
              string OpcodeStr, string Dt,
-             ValueType ResTy, ValueType OpTy, SDNode OpNode>
+             ValueType ResTy, ValueType OpTy, Operand ImmTy, SDNode OpNode>
   : N2VImm<op24, op23, op11_8, op7, op6, op4,
-           (outs QPR:$Vd), (ins DPR:$Vm, i32imm:$SIMM), N2RegVShLFrm,
+           (outs QPR:$Vd), (ins DPR:$Vm, ImmTy:$SIMM), N2RegVShLFrm,
            IIC_VSHLiD, OpcodeStr, Dt, "$Vd, $Vm, $SIMM", "",
            [(set QPR:$Vd, (ResTy (OpNode (OpTy DPR:$Vm),
                                           (i32 imm:$SIMM))))]>;
@@ -2649,14 +3121,11 @@
                    v4i32, v4i32, OpNode, Commutable>;
 }
=20
-multiclass N3VSL_HS<bits<4> op11_8, string OpcodeStr, string Dt, SDNode Sh=
Op> {
-  def v4i16 : N3VDSL16<0b01, op11_8, OpcodeStr, !strconcat(Dt, "16"),
-                       v4i16, ShOp>;
-  def v2i32 : N3VDSL<0b10, op11_8, IIC_VMULi32D, OpcodeStr, !strconcat(Dt,=
"32"),
-                     v2i32, ShOp>;
-  def v8i16 : N3VQSL16<0b01, op11_8, OpcodeStr, !strconcat(Dt, "16"),
-                       v8i16, v4i16, ShOp>;
-  def v4i32 : N3VQSL<0b10, op11_8, IIC_VMULi32Q, OpcodeStr, !strconcat(Dt,=
"32"),
+multiclass N3VSL_HS<bits<4> op11_8, string OpcodeStr, SDNode ShOp> {
+  def v4i16 : N3VDSL16<0b01, op11_8, OpcodeStr, "i16", v4i16, ShOp>;
+  def v2i32 : N3VDSL<0b10, op11_8, IIC_VMULi32D, OpcodeStr, "i32", v2i32, =
ShOp>;
+  def v8i16 : N3VQSL16<0b01, op11_8, OpcodeStr, "i16", v8i16, v4i16, ShOp>;
+  def v4i32 : N3VQSL<0b10, op11_8, IIC_VMULi32Q, OpcodeStr, "i32",
                      v4i32, v2i32, ShOp>;
 }
=20
@@ -3165,7 +3634,7 @@
 }
 multiclass N2VShR_QHSD<bit op24, bit op23, bits<4> op11_8, bit op4,
                        InstrItinClass itin, string OpcodeStr, string Dt,
-                       SDNode OpNode> {
+                       string baseOpc, SDNode OpNode> {
   // 64-bit vector types.
   def v8i8  : N2VDSh<op24, op23, op11_8, 0, op4, N2RegVShRFrm, itin, shr_i=
mm8,
                      OpcodeStr, !strconcat(Dt, "8"), v8i8, OpNode> {
@@ -3199,6 +3668,33 @@
   def v2i64 : N2VQSh<op24, op23, op11_8, 1, op4, N2RegVShRFrm, itin, shr_i=
mm64,
                      OpcodeStr, !strconcat(Dt, "64"), v2i64, OpNode>;
                              // imm6 =3D xxxxxx
+
+  // Aliases for two-operand forms (source and dest regs the same).
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "8 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v8i8"))
+                          DPR:$Vdn, DPR:$Vdn, shr_imm8:$imm, pred:$p)>;
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "16 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v4i16"))
+                          DPR:$Vdn, DPR:$Vdn, shr_imm16:$imm, pred:$p)>;
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "32 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v2i32"))
+                          DPR:$Vdn, DPR:$Vdn, shr_imm32:$imm, pred:$p)>;
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "64 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v1i64"))
+                          DPR:$Vdn, DPR:$Vdn, shr_imm64:$imm, pred:$p)>;
+
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "8 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v16i8"))
+                          QPR:$Vdn, QPR:$Vdn, shr_imm8:$imm, pred:$p)>;
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "16 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v8i16"))
+                          QPR:$Vdn, QPR:$Vdn, shr_imm16:$imm, pred:$p)>;
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "32 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v4i32"))
+                          QPR:$Vdn, QPR:$Vdn, shr_imm32:$imm, pred:$p)>;
+  def : NEONInstAlias<!strconcat(OpcodeStr, "${p}.", Dt, "64 $Vdn, $imm"),
+                      (!cast<Instruction>(!strconcat(baseOpc, "v2i64"))
+                          QPR:$Vdn, QPR:$Vdn, shr_imm64:$imm, pred:$p)>;
 }
=20
 // Neon Shift-Accumulate vector operations,
@@ -3321,15 +3817,15 @@
 multiclass N2VLSh_QHS<bit op24, bit op23, bits<4> op11_8, bit op7, bit op6,
                       bit op4, string OpcodeStr, string Dt, SDNode OpNode>=
 {
   def v8i16 : N2VLSh<op24, op23, op11_8, op7, op6, op4,
-                 OpcodeStr, !strconcat(Dt, "8"), v8i16, v8i8, OpNode> {
+              OpcodeStr, !strconcat(Dt, "8"), v8i16, v8i8, imm1_7, OpNode>=
 {
     let Inst{21-19} =3D 0b001; // imm6 =3D 001xxx
   }
   def v4i32 : N2VLSh<op24, op23, op11_8, op7, op6, op4,
-                  OpcodeStr, !strconcat(Dt, "16"), v4i32, v4i16, OpNode> {
+               OpcodeStr, !strconcat(Dt, "16"), v4i32, v4i16, imm1_15, OpN=
ode> {
     let Inst{21-20} =3D 0b01;  // imm6 =3D 01xxxx
   }
   def v2i64 : N2VLSh<op24, op23, op11_8, op7, op6, op4,
-                  OpcodeStr, !strconcat(Dt, "32"), v2i64, v2i32, OpNode> {
+               OpcodeStr, !strconcat(Dt, "32"), v2i64, v2i32, imm1_31, OpN=
ode> {
     let Inst{21} =3D 0b1;      // imm6 =3D 1xxxxx
   }
 }
@@ -3418,7 +3914,7 @@
                      v2f32, v2f32, fmul, 1>;
 def  VMULfq   : N3VQ<1, 0, 0b00, 0b1101, 1, IIC_VFMULQ, "vmul", "f32",
                      v4f32, v4f32, fmul, 1>;
-defm VMULsl   : N3VSL_HS<0b1000, "vmul", "i", mul>;
+defm VMULsl   : N3VSL_HS<0b1000, "vmul", mul>;
 def  VMULslfd : N3VDSL<0b10, 0b1001, IIC_VBIND, "vmul", "f32", v2f32, fmul=
>;
 def  VMULslfq : N3VQSL<0b10, 0b1001, IIC_VBINQ, "vmul", "f32", v4f32,
                        v2f32, fmul>;
@@ -3509,10 +4005,10 @@
                              IIC_VMACi16Q, IIC_VMACi32Q, "vmla", "i", add>;
 def  VMLAfd   : N3VDMulOp<0, 0, 0b00, 0b1101, 1, IIC_VMACD, "vmla", "f32",
                           v2f32, fmul_su, fadd_mlx>,
-                Requires<[HasNEON, UseFPVMLx]>;
+                Requires<[HasNEON, UseFPVMLx, DontUseFusedMAC]>;
 def  VMLAfq   : N3VQMulOp<0, 0, 0b00, 0b1101, 1, IIC_VMACQ, "vmla", "f32",
                           v4f32, fmul_su, fadd_mlx>,
-                Requires<[HasNEON, UseFPVMLx]>;
+                Requires<[HasNEON, UseFPVMLx, DontUseFusedMAC]>;
 defm VMLAsl   : N3VMulOpSL_HS<0b0000, IIC_VMACi16D, IIC_VMACi32D,
                               IIC_VMACi16Q, IIC_VMACi32Q, "vmla", "i", add=
>;
 def  VMLAslfd : N3VDMulOpSL<0b10, 0b0001, IIC_VMACD, "vmla", "f32",
@@ -3567,10 +4063,10 @@
                              IIC_VMACi16Q, IIC_VMACi32Q, "vmls", "i", sub>;
 def  VMLSfd   : N3VDMulOp<0, 0, 0b10, 0b1101, 1, IIC_VMACD, "vmls", "f32",
                           v2f32, fmul_su, fsub_mlx>,
-                Requires<[HasNEON, UseFPVMLx]>;
+                Requires<[HasNEON, UseFPVMLx, DontUseFusedMAC]>;
 def  VMLSfq   : N3VQMulOp<0, 0, 0b10, 0b1101, 1, IIC_VMACQ, "vmls", "f32",
                           v4f32, fmul_su, fsub_mlx>,
-                Requires<[HasNEON, UseFPVMLx]>;
+                Requires<[HasNEON, UseFPVMLx, DontUseFusedMAC]>;
 defm VMLSsl   : N3VMulOpSL_HS<0b0100, IIC_VMACi16D, IIC_VMACi32D,
                               IIC_VMACi16Q, IIC_VMACi32Q, "vmls", "i", sub=
>;
 def  VMLSslfd : N3VDMulOpSL<0b10, 0b0101, IIC_VMACD, "vmls", "f32",
@@ -3619,6 +4115,37 @@
                             "vqdmlsl", "s", int_arm_neon_vqdmlsl>;
 defm VQDMLSLsl: N3VLInt3SL_HS<0, 0b111, "vqdmlsl", "s", int_arm_neon_vqdml=
sl>;
=20
+// Fused Vector Multiply-Accumulate and Fused Multiply-Subtract Operations.
+def  VFMAfd   : N3VDMulOp<0, 0, 0b00, 0b1100, 1, IIC_VFMACD, "vfma", "f32",
+                          v2f32, fmul_su, fadd_mlx>,
+                Requires<[HasVFP4,UseFusedMAC]>;
+
+def  VFMAfq   : N3VQMulOp<0, 0, 0b00, 0b1100, 1, IIC_VFMACQ, "vfma", "f32",
+                          v4f32, fmul_su, fadd_mlx>,
+                Requires<[HasVFP4,UseFusedMAC]>;
+
+//   Fused Vector Multiply Subtract (floating-point)
+def  VFMSfd   : N3VDMulOp<0, 0, 0b10, 0b1100, 1, IIC_VFMACD, "vfms", "f32",
+                          v2f32, fmul_su, fsub_mlx>,
+                Requires<[HasVFP4,UseFusedMAC]>;
+def  VFMSfq   : N3VQMulOp<0, 0, 0b10, 0b1100, 1, IIC_VFMACQ, "vfms", "f32",
+                          v4f32, fmul_su, fsub_mlx>,
+                Requires<[HasVFP4,UseFusedMAC]>;
+
+// Match @llvm.fma.* intrinsics
+def : Pat<(v2f32 (fma DPR:$src1, DPR:$Vn, DPR:$Vm)),
+          (VFMAfd DPR:$src1, DPR:$Vn, DPR:$Vm)>,
+          Requires<[HasVFP4]>;
+def : Pat<(v4f32 (fma QPR:$src1, QPR:$Vn, QPR:$Vm)),
+          (VFMAfq QPR:$src1, QPR:$Vn, QPR:$Vm)>,
+          Requires<[HasVFP4]>;
+def : Pat<(v2f32 (fma (fneg DPR:$src1), DPR:$Vn, DPR:$Vm)),
+          (VFMSfd DPR:$src1, DPR:$Vn, DPR:$Vm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(v4f32 (fma (fneg QPR:$src1), QPR:$Vn, QPR:$Vm)),
+          (VFMSfq QPR:$src1, QPR:$Vn, QPR:$Vm)>,
+      Requires<[HasVFP4]>;
+
 // Vector Subtract Operations.
=20
 //   VSUB     : Vector Subtract (integer and floating-point)
@@ -3741,7 +4268,7 @@
                       v4i32, v4i32, or, 1>;
=20
 def VORRiv4i16 : N1ModImm<1, 0b000, {1,0,?,1}, 0, 0, 0, 1,
-                          (outs DPR:$Vd), (ins nModImm:$SIMM, DPR:$src),
+                          (outs DPR:$Vd), (ins nImmSplatI16:$SIMM, DPR:$sr=
c),
                           IIC_VMOVImm,
                           "vorr", "i16", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set DPR:$Vd,
@@ -3750,7 +4277,7 @@
 }
=20
 def VORRiv2i32 : N1ModImm<1, 0b000, {0,?,?,1}, 0, 0, 0, 1,
-                          (outs DPR:$Vd), (ins nModImm:$SIMM, DPR:$src),
+                          (outs DPR:$Vd), (ins nImmSplatI32:$SIMM, DPR:$sr=
c),
                           IIC_VMOVImm,
                           "vorr", "i32", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set DPR:$Vd,
@@ -3759,7 +4286,7 @@
 }
=20
 def VORRiv8i16 : N1ModImm<1, 0b000, {1,0,?,1}, 0, 1, 0, 1,
-                          (outs QPR:$Vd), (ins nModImm:$SIMM, QPR:$src),
+                          (outs QPR:$Vd), (ins nImmSplatI16:$SIMM, QPR:$sr=
c),
                           IIC_VMOVImm,
                           "vorr", "i16", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set QPR:$Vd,
@@ -3768,7 +4295,7 @@
 }
=20
 def VORRiv4i32 : N1ModImm<1, 0b000, {0,?,?,1}, 0, 1, 0, 1,
-                          (outs QPR:$Vd), (ins nModImm:$SIMM, QPR:$src),
+                          (outs QPR:$Vd), (ins nImmSplatI32:$SIMM, QPR:$sr=
c),
                           IIC_VMOVImm,
                           "vorr", "i32", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set QPR:$Vd,
@@ -3790,7 +4317,7 @@
                                                  (vnotq QPR:$Vm))))]>;
=20
 def VBICiv4i16 : N1ModImm<1, 0b000, {1,0,?,1}, 0, 0, 1, 1,
-                          (outs DPR:$Vd), (ins nModImm:$SIMM, DPR:$src),
+                          (outs DPR:$Vd), (ins nImmSplatI16:$SIMM, DPR:$sr=
c),
                           IIC_VMOVImm,
                           "vbic", "i16", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set DPR:$Vd,
@@ -3799,7 +4326,7 @@
 }
=20
 def VBICiv2i32 : N1ModImm<1, 0b000, {0,?,?,1}, 0, 0, 1, 1,
-                          (outs DPR:$Vd), (ins nModImm:$SIMM, DPR:$src),
+                          (outs DPR:$Vd), (ins nImmSplatI32:$SIMM, DPR:$sr=
c),
                           IIC_VMOVImm,
                           "vbic", "i32", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set DPR:$Vd,
@@ -3808,7 +4335,7 @@
 }
=20
 def VBICiv8i16 : N1ModImm<1, 0b000, {1,0,?,1}, 0, 1, 1, 1,
-                          (outs QPR:$Vd), (ins nModImm:$SIMM, QPR:$src),
+                          (outs QPR:$Vd), (ins nImmSplatI16:$SIMM, QPR:$sr=
c),
                           IIC_VMOVImm,
                           "vbic", "i16", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set QPR:$Vd,
@@ -3817,7 +4344,7 @@
 }
=20
 def VBICiv4i32 : N1ModImm<1, 0b000, {0,?,?,1}, 0, 1, 1, 1,
-                          (outs QPR:$Vd), (ins nModImm:$SIMM, QPR:$src),
+                          (outs QPR:$Vd), (ins nImmSplatI32:$SIMM, QPR:$sr=
c),
                           IIC_VMOVImm,
                           "vbic", "i32", "$Vd, $SIMM", "$src =3D $Vd",
                           [(set QPR:$Vd,
@@ -3842,28 +4369,28 @@
 let isReMaterializable =3D 1 in {
=20
 def VMVNv4i16 : N1ModImm<1, 0b000, {1,0,?,0}, 0, 0, 1, 1, (outs DPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI16:$SIMM), IIC_VMOVImm,
                          "vmvn", "i16", "$Vd, $SIMM", "",
                          [(set DPR:$Vd, (v4i16 (NEONvmvnImm timm:$SIMM)))]=
> {
   let Inst{9} =3D SIMM{9};
 }
=20
 def VMVNv8i16 : N1ModImm<1, 0b000, {1,0,?,0}, 0, 1, 1, 1, (outs QPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI16:$SIMM), IIC_VMOVImm,
                          "vmvn", "i16", "$Vd, $SIMM", "",
                          [(set QPR:$Vd, (v8i16 (NEONvmvnImm timm:$SIMM)))]=
> {
   let Inst{9} =3D SIMM{9};
 }
=20
 def VMVNv2i32 : N1ModImm<1, 0b000, {?,?,?,?}, 0, 0, 1, 1, (outs DPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmVMOVI32:$SIMM), IIC_VMOVImm,
                          "vmvn", "i32", "$Vd, $SIMM", "",
                          [(set DPR:$Vd, (v2i32 (NEONvmvnImm timm:$SIMM)))]=
> {
   let Inst{11-8} =3D SIMM{11-8};
 }
=20
 def VMVNv4i32 : N1ModImm<1, 0b000, {?,?,?,?}, 0, 1, 1, 1, (outs QPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmVMOVI32:$SIMM), IIC_VMOVImm,
                          "vmvn", "i32", "$Vd, $SIMM", "",
                          [(set QPR:$Vd, (v4i32 (NEONvmvnImm timm:$SIMM)))]=
> {
   let Inst{11-8} =3D SIMM{11-8};
@@ -3912,12 +4439,12 @@
                      (outs DPR:$Vd), (ins DPR:$src1, DPR:$Vn, DPR:$Vm),
                      N3RegFrm, IIC_VBINiD,
                      "vbif", "$Vd, $Vn, $Vm", "$src1 =3D $Vd",
-                     [/* For disassembly only; pattern left blank */]>;
+                     []>;
 def  VBIFq    : N3VX<1, 0, 0b11, 0b0001, 1, 1,
                      (outs QPR:$Vd), (ins QPR:$src1, QPR:$Vn, QPR:$Vm),
                      N3RegFrm, IIC_VBINiQ,
                      "vbif", "$Vd, $Vn, $Vm", "$src1 =3D $Vd",
-                     [/* For disassembly only; pattern left blank */]>;
+                     []>;
=20
 //   VBIT     : Vector Bitwise Insert if True
 //              like VBSL but with: "vbit $dst, $src2, $src1", "$src3 =3D =
$dst",
@@ -3926,12 +4453,12 @@
                      (outs DPR:$Vd), (ins DPR:$src1, DPR:$Vn, DPR:$Vm),
                      N3RegFrm, IIC_VBINiD,
                      "vbit", "$Vd, $Vn, $Vm", "$src1 =3D $Vd",
-                     [/* For disassembly only; pattern left blank */]>;
+                     []>;
 def  VBITq    : N3VX<1, 0, 0b10, 0b0001, 1, 1,
                      (outs QPR:$Vd), (ins QPR:$src1, QPR:$Vn, QPR:$Vm),
                      N3RegFrm, IIC_VBINiQ,
                      "vbit", "$Vd, $Vn, $Vm", "$src1 =3D $Vd",
-                     [/* For disassembly only; pattern left blank */]>;
+                     []>;
=20
 // VBIT/VBIF are not yet implemented.  The TwoAddress pass will not go loo=
king
 // for equivalent operations with different register constraints; it just
@@ -4119,8 +4646,10 @@
 defm VSHLi    : N2VShL_QHSD<0, 1, 0b0101, 1, IIC_VSHLiD, "vshl", "i", NEON=
vshl>;
=20
 //   VSHR     : Vector Shift Right (Immediate)
-defm VSHRs    : N2VShR_QHSD<0, 1, 0b0000, 1, IIC_VSHLiD, "vshr", "s",NEONv=
shrs>;
-defm VSHRu    : N2VShR_QHSD<1, 1, 0b0000, 1, IIC_VSHLiD, "vshr", "u",NEONv=
shru>;
+defm VSHRs    : N2VShR_QHSD<0, 1, 0b0000, 1, IIC_VSHLiD, "vshr", "s", "VSH=
Rs",
+                            NEONvshrs>;
+defm VSHRu    : N2VShR_QHSD<1, 1, 0b0000, 1, IIC_VSHLiD, "vshr", "u", "VSH=
Ru",
+                            NEONvshru>;
=20
 //   VSHLL    : Vector Shift Left Long
 defm VSHLLs   : N2VLSh_QHS<0, 1, 0b1010, 0, 0, 1, "vshll", "s", NEONvshlls=
>;
@@ -4129,18 +4658,18 @@
 //   VSHLL    : Vector Shift Left Long (with maximum shift count)
 class N2VLShMax<bit op24, bit op23, bits<6> op21_16, bits<4> op11_8, bit o=
p7,
                 bit op6, bit op4, string OpcodeStr, string Dt, ValueType R=
esTy,
-                ValueType OpTy, SDNode OpNode>
+                ValueType OpTy, Operand ImmTy, SDNode OpNode>
   : N2VLSh<op24, op23, op11_8, op7, op6, op4, OpcodeStr, Dt,
-           ResTy, OpTy, OpNode> {
+           ResTy, OpTy, ImmTy, OpNode> {
   let Inst{21-16} =3D op21_16;
   let DecoderMethod =3D "DecodeVSHLMaxInstruction";
 }
 def  VSHLLi8  : N2VLShMax<1, 1, 0b110010, 0b0011, 0, 0, 0, "vshll", "i8",
-                          v8i16, v8i8, NEONvshlli>;
+                          v8i16, v8i8, imm8, NEONvshlli>;
 def  VSHLLi16 : N2VLShMax<1, 1, 0b110110, 0b0011, 0, 0, 0, "vshll", "i16",
-                          v4i32, v4i16, NEONvshlli>;
+                          v4i32, v4i16, imm16, NEONvshlli>;
 def  VSHLLi32 : N2VLShMax<1, 1, 0b111010, 0b0011, 0, 0, 0, "vshll", "i32",
-                          v2i64, v2i32, NEONvshlli>;
+                          v2i64, v2i32, imm32, NEONvshlli>;
=20
 //   VSHRN    : Vector Shift Right and Narrow
 defm VSHRN    : N2VNSh_HSD<0,1,0b1000,0,0,1, IIC_VSHLiD, "vshrn", "i",
@@ -4154,8 +4683,10 @@
                             IIC_VSHLi4D, IIC_VSHLi4D, IIC_VSHLi4Q, IIC_VSH=
Li4Q,
                             "vrshl", "u", int_arm_neon_vrshiftu>;
 //   VRSHR    : Vector Rounding Shift Right
-defm VRSHRs   : N2VShR_QHSD<0,1,0b0010,1, IIC_VSHLi4D, "vrshr", "s",NEONvr=
shrs>;
-defm VRSHRu   : N2VShR_QHSD<1,1,0b0010,1, IIC_VSHLi4D, "vrshr", "u",NEONvr=
shru>;
+defm VRSHRs   : N2VShR_QHSD<0,1,0b0010,1, IIC_VSHLi4D, "vrshr", "s", "VRSH=
Rs",
+                            NEONvrshrs>;
+defm VRSHRu   : N2VShR_QHSD<1,1,0b0010,1, IIC_VSHLi4D, "vrshr", "u", "VRSH=
Ru",
+                            NEONvrshru>;
=20
 //   VRSHRN   : Vector Rounding Shift Right and Narrow
 defm VRSHRN   : N2VNSh_HSD<0, 1, 0b1000, 0, 1, 1, IIC_VSHLi4D, "vrshrn", "=
i",
@@ -4298,13 +4829,15 @@
                         IIC_VCNTiQ, "vcnt", "8",
                         v16i8, v16i8, int_arm_neon_vcnt>;
=20
-// Vector Swap -- for disassembly only.
+// Vector Swap
 def  VSWPd    : N2VX<0b11, 0b11, 0b00, 0b10, 0b00000, 0, 0,
-                     (outs DPR:$Vd), (ins DPR:$Vm), NoItinerary,
-                     "vswp", "$Vd, $Vm", "", []>;
+                     (outs DPR:$Vd, DPR:$Vm), (ins DPR:$in1, DPR:$in2),
+                     NoItinerary, "vswp", "$Vd, $Vm", "$in1 =3D $Vd, $in2 =
=3D $Vm",
+                     []>;
 def  VSWPq    : N2VX<0b11, 0b11, 0b00, 0b10, 0b00000, 1, 0,
-                     (outs QPR:$Vd), (ins QPR:$Vm), NoItinerary,
-                     "vswp", "$Vd, $Vm", "", []>;
+                     (outs QPR:$Vd, QPR:$Vm), (ins QPR:$in1, QPR:$in2),
+                     NoItinerary, "vswp", "$Vd, $Vm", "$in1 =3D $Vd, $in2 =
=3D $Vm",
+                     []>;
=20
 // Vector Move Operations.
=20
@@ -4318,89 +4851,98 @@
=20
 let isReMaterializable =3D 1 in {
 def VMOVv8i8  : N1ModImm<1, 0b000, 0b1110, 0, 0, 0, 1, (outs DPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI8:$SIMM), IIC_VMOVImm,
                          "vmov", "i8", "$Vd, $SIMM", "",
                          [(set DPR:$Vd, (v8i8 (NEONvmovImm timm:$SIMM)))]>;
 def VMOVv16i8 : N1ModImm<1, 0b000, 0b1110, 0, 1, 0, 1, (outs QPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI8:$SIMM), IIC_VMOVImm,
                          "vmov", "i8", "$Vd, $SIMM", "",
                          [(set QPR:$Vd, (v16i8 (NEONvmovImm timm:$SIMM)))]=
>;
=20
 def VMOVv4i16 : N1ModImm<1, 0b000, {1,0,?,0}, 0, 0, 0, 1, (outs DPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI16:$SIMM), IIC_VMOVImm,
                          "vmov", "i16", "$Vd, $SIMM", "",
                          [(set DPR:$Vd, (v4i16 (NEONvmovImm timm:$SIMM)))]=
> {
   let Inst{9} =3D SIMM{9};
 }
=20
 def VMOVv8i16 : N1ModImm<1, 0b000, {1,0,?,0}, 0, 1, 0, 1, (outs QPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI16:$SIMM), IIC_VMOVImm,
                          "vmov", "i16", "$Vd, $SIMM", "",
                          [(set QPR:$Vd, (v8i16 (NEONvmovImm timm:$SIMM)))]=
> {
  let Inst{9} =3D SIMM{9};
 }
=20
 def VMOVv2i32 : N1ModImm<1, 0b000, {?,?,?,?}, 0, 0, 0, 1, (outs DPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmVMOVI32:$SIMM), IIC_VMOVImm,
                          "vmov", "i32", "$Vd, $SIMM", "",
                          [(set DPR:$Vd, (v2i32 (NEONvmovImm timm:$SIMM)))]=
> {
   let Inst{11-8} =3D SIMM{11-8};
 }
=20
 def VMOVv4i32 : N1ModImm<1, 0b000, {?,?,?,?}, 0, 1, 0, 1, (outs QPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmVMOVI32:$SIMM), IIC_VMOVImm,
                          "vmov", "i32", "$Vd, $SIMM", "",
                          [(set QPR:$Vd, (v4i32 (NEONvmovImm timm:$SIMM)))]=
> {
   let Inst{11-8} =3D SIMM{11-8};
 }
=20
 def VMOVv1i64 : N1ModImm<1, 0b000, 0b1110, 0, 0, 1, 1, (outs DPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI64:$SIMM), IIC_VMOVImm,
                          "vmov", "i64", "$Vd, $SIMM", "",
                          [(set DPR:$Vd, (v1i64 (NEONvmovImm timm:$SIMM)))]=
>;
 def VMOVv2i64 : N1ModImm<1, 0b000, 0b1110, 0, 1, 1, 1, (outs QPR:$Vd),
-                         (ins nModImm:$SIMM), IIC_VMOVImm,
+                         (ins nImmSplatI64:$SIMM), IIC_VMOVImm,
                          "vmov", "i64", "$Vd, $SIMM", "",
                          [(set QPR:$Vd, (v2i64 (NEONvmovImm timm:$SIMM)))]=
>;
+
+def VMOVv2f32 : N1ModImm<1, 0b000, 0b1111, 0, 0, 0, 1, (outs DPR:$Vd),
+                         (ins nImmVMOVF32:$SIMM), IIC_VMOVImm,
+                         "vmov", "f32", "$Vd, $SIMM", "",
+                         [(set DPR:$Vd, (v2f32 (NEONvmovFPImm timm:$SIMM))=
)]>;
+def VMOVv4f32 : N1ModImm<1, 0b000, 0b1111, 0, 1, 0, 1, (outs QPR:$Vd),
+                         (ins nImmVMOVF32:$SIMM), IIC_VMOVImm,
+                         "vmov", "f32", "$Vd, $SIMM", "",
+                         [(set QPR:$Vd, (v4f32 (NEONvmovFPImm timm:$SIMM))=
)]>;
 } // isReMaterializable
=20
 //   VMOV     : Vector Get Lane (move scalar to ARM core register)
=20
 def VGETLNs8  : NVGetLane<{1,1,1,0,0,1,?,1}, 0b1011, {?,?},
-                          (outs GPR:$R), (ins DPR:$V, nohash_imm:$lane),
-                          IIC_VMOVSI, "vmov", "s8", "$R, $V[$lane]",
+                          (outs GPR:$R), (ins DPR:$V, VectorIndex8:$lane),
+                          IIC_VMOVSI, "vmov", "s8", "$R, $V$lane",
                           [(set GPR:$R, (NEONvgetlanes (v8i8 DPR:$V),
                                            imm:$lane))]> {
   let Inst{21}  =3D lane{2};
   let Inst{6-5} =3D lane{1-0};
 }
 def VGETLNs16 : NVGetLane<{1,1,1,0,0,0,?,1}, 0b1011, {?,1},
-                          (outs GPR:$R), (ins DPR:$V, nohash_imm:$lane),
-                          IIC_VMOVSI, "vmov", "s16", "$R, $V[$lane]",
+                          (outs GPR:$R), (ins DPR:$V, VectorIndex16:$lane),
+                          IIC_VMOVSI, "vmov", "s16", "$R, $V$lane",
                           [(set GPR:$R, (NEONvgetlanes (v4i16 DPR:$V),
                                            imm:$lane))]> {
   let Inst{21} =3D lane{1};
   let Inst{6}  =3D lane{0};
 }
 def VGETLNu8  : NVGetLane<{1,1,1,0,1,1,?,1}, 0b1011, {?,?},
-                          (outs GPR:$R), (ins DPR:$V, nohash_imm:$lane),
-                          IIC_VMOVSI, "vmov", "u8", "$R, $V[$lane]",
+                          (outs GPR:$R), (ins DPR:$V, VectorIndex8:$lane),
+                          IIC_VMOVSI, "vmov", "u8", "$R, $V$lane",
                           [(set GPR:$R, (NEONvgetlaneu (v8i8 DPR:$V),
                                            imm:$lane))]> {
   let Inst{21}  =3D lane{2};
   let Inst{6-5} =3D lane{1-0};
 }
 def VGETLNu16 : NVGetLane<{1,1,1,0,1,0,?,1}, 0b1011, {?,1},
-                          (outs GPR:$R), (ins DPR:$V, nohash_imm:$lane),
-                          IIC_VMOVSI, "vmov", "u16", "$R, $V[$lane]",
+                          (outs GPR:$R), (ins DPR:$V, VectorIndex16:$lane),
+                          IIC_VMOVSI, "vmov", "u16", "$R, $V$lane",
                           [(set GPR:$R, (NEONvgetlaneu (v4i16 DPR:$V),
                                            imm:$lane))]> {
   let Inst{21} =3D lane{1};
   let Inst{6}  =3D lane{0};
 }
 def VGETLNi32 : NVGetLane<{1,1,1,0,0,0,?,1}, 0b1011, 0b00,
-                          (outs GPR:$R), (ins DPR:$V, nohash_imm:$lane),
-                          IIC_VMOVSI, "vmov", "32", "$R, $V[$lane]",
+                          (outs GPR:$R), (ins DPR:$V, VectorIndex32:$lane),
+                          IIC_VMOVSI, "vmov", "32", "$R, $V$lane",
                           [(set GPR:$R, (extractelt (v2i32 DPR:$V),
                                            imm:$lane))]> {
   let Inst{21} =3D lane{0};
@@ -4442,24 +4984,24 @@
=20
 let Constraints =3D "$src1 =3D $V" in {
 def VSETLNi8  : NVSetLane<{1,1,1,0,0,1,?,0}, 0b1011, {?,?}, (outs DPR:$V),
-                          (ins DPR:$src1, GPR:$R, nohash_imm:$lane),
-                          IIC_VMOVISL, "vmov", "8", "$V[$lane], $R",
+                          (ins DPR:$src1, GPR:$R, VectorIndex8:$lane),
+                          IIC_VMOVISL, "vmov", "8", "$V$lane, $R",
                           [(set DPR:$V, (vector_insert (v8i8 DPR:$src1),
                                            GPR:$R, imm:$lane))]> {
   let Inst{21}  =3D lane{2};
   let Inst{6-5} =3D lane{1-0};
 }
 def VSETLNi16 : NVSetLane<{1,1,1,0,0,0,?,0}, 0b1011, {?,1}, (outs DPR:$V),
-                          (ins DPR:$src1, GPR:$R, nohash_imm:$lane),
-                          IIC_VMOVISL, "vmov", "16", "$V[$lane], $R",
+                          (ins DPR:$src1, GPR:$R, VectorIndex16:$lane),
+                          IIC_VMOVISL, "vmov", "16", "$V$lane, $R",
                           [(set DPR:$V, (vector_insert (v4i16 DPR:$src1),
                                            GPR:$R, imm:$lane))]> {
   let Inst{21} =3D lane{1};
   let Inst{6}  =3D lane{0};
 }
 def VSETLNi32 : NVSetLane<{1,1,1,0,0,0,?,0}, 0b1011, 0b00, (outs DPR:$V),
-                          (ins DPR:$src1, GPR:$R, nohash_imm:$lane),
-                          IIC_VMOVISL, "vmov", "32", "$V[$lane], $R",
+                          (ins DPR:$src1, GPR:$R, VectorIndex32:$lane),
+                          IIC_VMOVISL, "vmov", "32", "$V$lane, $R",
                           [(set DPR:$V, (insertelt (v2i32 DPR:$src1),
                                            GPR:$R, imm:$lane))]> {
   let Inst{21} =3D lane{0};
@@ -4627,6 +5169,9 @@
 //   VMOVL    : Vector Lengthening Move
 defm VMOVLs   : N2VL_QHS<0b01,0b10100,0,1, "vmovl", "s", sext>;
 defm VMOVLu   : N2VL_QHS<0b11,0b10100,0,1, "vmovl", "u", zext>;
+def : Pat<(v8i16 (anyext (v8i8 DPR:$Vm))), (VMOVLuv8i16 DPR:$Vm)>;
+def : Pat<(v4i32 (anyext (v4i16 DPR:$Vm))), (VMOVLuv4i32 DPR:$Vm)>;
+def : Pat<(v2i64 (anyext (v2i32 DPR:$Vm))), (VMOVLuv2i64 DPR:$Vm)>;
=20
 // Vector Conversions.
=20
@@ -4650,6 +5195,7 @@
                      v4f32, v4i32, uint_to_fp>;
=20
 //   VCVT     : Vector Convert Between Floating-Point and Fixed-Point.
+let DecoderMethod =3D "DecodeVCVTD" in {
 def VCVTf2xsd : N2VCvtD<0, 1, 0b1111, 0, 1, "vcvt", "s32.f32",
                         v2i32, v2f32, int_arm_neon_vcvtfp2fxs>;
 def VCVTf2xud : N2VCvtD<1, 1, 0b1111, 0, 1, "vcvt", "u32.f32",
@@ -4658,7 +5204,9 @@
                         v2f32, v2i32, int_arm_neon_vcvtfxs2fp>;
 def VCVTxu2fd : N2VCvtD<1, 1, 0b1110, 0, 1, "vcvt", "f32.u32",
                         v2f32, v2i32, int_arm_neon_vcvtfxu2fp>;
-
+}
+
+let DecoderMethod =3D "DecodeVCVTQ" in {
 def VCVTf2xsq : N2VCvtQ<0, 1, 0b1111, 0, 1, "vcvt", "s32.f32",
                         v4i32, v4f32, int_arm_neon_vcvtfp2fxs>;
 def VCVTf2xuq : N2VCvtQ<1, 1, 0b1111, 0, 1, "vcvt", "u32.f32",
@@ -4667,6 +5215,7 @@
                         v4f32, v4i32, int_arm_neon_vcvtfxs2fp>;
 def VCVTxu2fq : N2VCvtQ<1, 1, 0b1110, 0, 1, "vcvt", "f32.u32",
                         v4f32, v4i32, int_arm_neon_vcvtfxu2fp>;
+}
=20
 //   VCVT     : Vector Convert Between Half-Precision and Single-Precision.
 def  VCVTf2h  : N2VNInt<0b11, 0b11, 0b01, 0b10, 0b01100, 0, 0,
@@ -4759,34 +5308,34 @@
=20
 //   VEXT     : Vector Extract
=20
-class VEXTd<string OpcodeStr, string Dt, ValueType Ty>
+class VEXTd<string OpcodeStr, string Dt, ValueType Ty, Operand immTy>
   : N3V<0,1,0b11,{?,?,?,?},0,0, (outs DPR:$Vd),
-        (ins DPR:$Vn, DPR:$Vm, i32imm:$index), NVExtFrm,
+        (ins DPR:$Vn, DPR:$Vm, immTy:$index), NVExtFrm,
         IIC_VEXTD, OpcodeStr, Dt, "$Vd, $Vn, $Vm, $index", "",
         [(set DPR:$Vd, (Ty (NEONvext (Ty DPR:$Vn),
-                                      (Ty DPR:$Vm), imm:$index)))]> {
+                                     (Ty DPR:$Vm), imm:$index)))]> {
   bits<4> index;
   let Inst{11-8} =3D index{3-0};
 }
=20
-class VEXTq<string OpcodeStr, string Dt, ValueType Ty>
+class VEXTq<string OpcodeStr, string Dt, ValueType Ty, Operand immTy>
   : N3V<0,1,0b11,{?,?,?,?},1,0, (outs QPR:$Vd),
-        (ins QPR:$Vn, QPR:$Vm, i32imm:$index), NVExtFrm,
+        (ins QPR:$Vn, QPR:$Vm, imm0_15:$index), NVExtFrm,
         IIC_VEXTQ, OpcodeStr, Dt, "$Vd, $Vn, $Vm, $index", "",
         [(set QPR:$Vd, (Ty (NEONvext (Ty QPR:$Vn),
-                                      (Ty QPR:$Vm), imm:$index)))]> {
+                                     (Ty QPR:$Vm), imm:$index)))]> {
   bits<4> index;
   let Inst{11-8} =3D index{3-0};
 }
=20
-def VEXTd8  : VEXTd<"vext", "8",  v8i8> {
+def VEXTd8  : VEXTd<"vext", "8",  v8i8, imm0_7> {
   let Inst{11-8} =3D index{3-0};
 }
-def VEXTd16 : VEXTd<"vext", "16", v4i16> {
+def VEXTd16 : VEXTd<"vext", "16", v4i16, imm0_3> {
   let Inst{11-9} =3D index{2-0};
   let Inst{8}    =3D 0b0;
 }
-def VEXTd32 : VEXTd<"vext", "32", v2i32> {
+def VEXTd32 : VEXTd<"vext", "32", v2i32, imm0_1> {
   let Inst{11-10} =3D index{1-0};
   let Inst{9-8}    =3D 0b00;
 }
@@ -4795,17 +5344,21 @@
                            (i32 imm:$index))),
           (VEXTd32 DPR:$Vn, DPR:$Vm, imm:$index)>;
=20
-def VEXTq8  : VEXTq<"vext", "8",  v16i8> {
+def VEXTq8  : VEXTq<"vext", "8",  v16i8, imm0_15> {
   let Inst{11-8} =3D index{3-0};
 }
-def VEXTq16 : VEXTq<"vext", "16", v8i16> {
+def VEXTq16 : VEXTq<"vext", "16", v8i16, imm0_7> {
   let Inst{11-9} =3D index{2-0};
   let Inst{8}    =3D 0b0;
 }
-def VEXTq32 : VEXTq<"vext", "32", v4i32> {
+def VEXTq32 : VEXTq<"vext", "32", v4i32, imm0_3> {
   let Inst{11-10} =3D index{1-0};
   let Inst{9-8}    =3D 0b00;
 }
+def VEXTq64 : VEXTq<"vext", "64", v2i64, imm0_1> {
+  let Inst{11} =3D index{0};
+  let Inst{10-8}    =3D 0b000;
+}
 def : Pat<(v4f32 (NEONvext (v4f32 QPR:$Vn),
                            (v4f32 QPR:$Vm),
                            (i32 imm:$index))),
@@ -4825,7 +5378,9 @@
=20
 def  VUZPd8   : N2VDShuffle<0b00, 0b00010, "vuzp", "8">;
 def  VUZPd16  : N2VDShuffle<0b01, 0b00010, "vuzp", "16">;
-def  VUZPd32  : N2VDShuffle<0b10, 0b00010, "vuzp", "32">;
+// vuzp.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
+def : NEONInstAlias<"vuzp${p}.32 $Dd, $Dm",
+                    (VTRNd32 DPR:$Dd, DPR:$Dm, pred:$p)>;
=20
 def  VUZPq8   : N2VQShuffle<0b00, 0b00010, IIC_VPERMQ3, "vuzp", "8">;
 def  VUZPq16  : N2VQShuffle<0b01, 0b00010, IIC_VPERMQ3, "vuzp", "16">;
@@ -4835,7 +5390,9 @@
=20
 def  VZIPd8   : N2VDShuffle<0b00, 0b00011, "vzip", "8">;
 def  VZIPd16  : N2VDShuffle<0b01, 0b00011, "vzip", "16">;
-def  VZIPd32  : N2VDShuffle<0b10, 0b00011, "vzip", "32">;
+// vzip.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
+def : NEONInstAlias<"vzip${p}.32 $Dd, $Dm",
+                    (VTRNd32 DPR:$Dd, DPR:$Dm, pred:$p)>;
=20
 def  VZIPq8   : N2VQShuffle<0b00, 0b00011, IIC_VPERMQ3, "vzip", "8">;
 def  VZIPq16  : N2VQShuffle<0b01, 0b00011, IIC_VPERMQ3, "vzip", "16">;
@@ -4847,27 +5404,25 @@
 let DecoderMethod =3D "DecodeTBLInstruction" in {
 def  VTBL1
   : N3V<1,1,0b11,0b1000,0,0, (outs DPR:$Vd),
-        (ins DPR:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTB1,
-        "vtbl", "8", "$Vd, \\{$Vn\\}, $Vm", "",
-        [(set DPR:$Vd, (v8i8 (int_arm_neon_vtbl1 DPR:$Vn, DPR:$Vm)))]>;
+        (ins VecListOneD:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTB1,
+        "vtbl", "8", "$Vd, $Vn, $Vm", "",
+        [(set DPR:$Vd, (v8i8 (int_arm_neon_vtbl1 VecListOneD:$Vn, DPR:$Vm)=
))]>;
 let hasExtraSrcRegAllocReq =3D 1 in {
 def  VTBL2
   : N3V<1,1,0b11,0b1001,0,0, (outs DPR:$Vd),
-        (ins DPR:$Vn, DPR:$tbl2, DPR:$Vm), NVTBLFrm, IIC_VTB2,
-        "vtbl", "8", "$Vd, \\{$Vn, $tbl2\\}, $Vm", "", []>;
+        (ins VecListDPair:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTB2,
+        "vtbl", "8", "$Vd, $Vn, $Vm", "", []>;
 def  VTBL3
   : N3V<1,1,0b11,0b1010,0,0, (outs DPR:$Vd),
-        (ins DPR:$Vn, DPR:$tbl2, DPR:$tbl3, DPR:$Vm), NVTBLFrm, IIC_VTB3,
-        "vtbl", "8", "$Vd, \\{$Vn, $tbl2, $tbl3\\}, $Vm", "", []>;
+        (ins VecListThreeD:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTB3,
+        "vtbl", "8", "$Vd, $Vn, $Vm", "", []>;
 def  VTBL4
   : N3V<1,1,0b11,0b1011,0,0, (outs DPR:$Vd),
-        (ins DPR:$Vn, DPR:$tbl2, DPR:$tbl3, DPR:$tbl4, DPR:$Vm),
+        (ins VecListFourD:$Vn, DPR:$Vm),
         NVTBLFrm, IIC_VTB4,
-        "vtbl", "8", "$Vd, \\{$Vn, $tbl2, $tbl3, $tbl4\\}, $Vm", "", []>;
+        "vtbl", "8", "$Vd, $Vn, $Vm", "", []>;
 } // hasExtraSrcRegAllocReq =3D 1
=20
-def  VTBL2Pseudo
-  : PseudoNeonI<(outs DPR:$dst), (ins QPR:$tbl, DPR:$src), IIC_VTB2, "", [=
]>;
 def  VTBL3Pseudo
   : PseudoNeonI<(outs DPR:$dst), (ins QQPR:$tbl, DPR:$src), IIC_VTB3, "", =
[]>;
 def  VTBL4Pseudo
@@ -4876,31 +5431,28 @@
 //   VTBX     : Vector Table Extension
 def  VTBX1
   : N3V<1,1,0b11,0b1000,1,0, (outs DPR:$Vd),
-        (ins DPR:$orig, DPR:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTBX1,
-        "vtbx", "8", "$Vd, \\{$Vn\\}, $Vm", "$orig =3D $Vd",
+        (ins DPR:$orig, VecListOneD:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTBX1,
+        "vtbx", "8", "$Vd, $Vn, $Vm", "$orig =3D $Vd",
         [(set DPR:$Vd, (v8i8 (int_arm_neon_vtbx1
-                               DPR:$orig, DPR:$Vn, DPR:$Vm)))]>;
+                               DPR:$orig, VecListOneD:$Vn, DPR:$Vm)))]>;
 let hasExtraSrcRegAllocReq =3D 1 in {
 def  VTBX2
   : N3V<1,1,0b11,0b1001,1,0, (outs DPR:$Vd),
-        (ins DPR:$orig, DPR:$Vn, DPR:$tbl2, DPR:$Vm), NVTBLFrm, IIC_VTBX2,
-        "vtbx", "8", "$Vd, \\{$Vn, $tbl2\\}, $Vm", "$orig =3D $Vd", []>;
+        (ins DPR:$orig, VecListDPair:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTBX2,
+        "vtbx", "8", "$Vd, $Vn, $Vm", "$orig =3D $Vd", []>;
 def  VTBX3
   : N3V<1,1,0b11,0b1010,1,0, (outs DPR:$Vd),
-        (ins DPR:$orig, DPR:$Vn, DPR:$tbl2, DPR:$tbl3, DPR:$Vm),
+        (ins DPR:$orig, VecListThreeD:$Vn, DPR:$Vm),
         NVTBLFrm, IIC_VTBX3,
-        "vtbx", "8", "$Vd, \\{$Vn, $tbl2, $tbl3\\}, $Vm",
+        "vtbx", "8", "$Vd, $Vn, $Vm",
         "$orig =3D $Vd", []>;
 def  VTBX4
-  : N3V<1,1,0b11,0b1011,1,0, (outs DPR:$Vd), (ins DPR:$orig, DPR:$Vn,
-        DPR:$tbl2, DPR:$tbl3, DPR:$tbl4, DPR:$Vm), NVTBLFrm, IIC_VTBX4,
-        "vtbx", "8", "$Vd, \\{$Vn, $tbl2, $tbl3, $tbl4\\}, $Vm",
+  : N3V<1,1,0b11,0b1011,1,0, (outs DPR:$Vd),
+        (ins DPR:$orig, VecListFourD:$Vn, DPR:$Vm), NVTBLFrm, IIC_VTBX4,
+        "vtbx", "8", "$Vd, $Vn, $Vm",
         "$orig =3D $Vd", []>;
 } // hasExtraSrcRegAllocReq =3D 1
=20
-def  VTBX2Pseudo
-  : PseudoNeonI<(outs DPR:$dst), (ins DPR:$orig, QPR:$tbl, DPR:$src),
-                IIC_VTBX2, "$orig =3D $dst", []>;
 def  VTBX3Pseudo
   : PseudoNeonI<(outs DPR:$dst), (ins DPR:$orig, QQPR:$tbl, DPR:$src),
                 IIC_VTBX3, "$orig =3D $dst", []>;
@@ -4950,9 +5502,13 @@
 def : N3VSPat<fsub, VSUBfd>;
 def : N3VSPat<fmul, VMULfd>;
 def : N3VSMulOpPat<fmul, fadd, VMLAfd>,
-      Requires<[HasNEON, UseNEONForFP, UseFPVMLx]>;
+      Requires<[HasNEON, UseNEONForFP, UseFPVMLx, DontUseFusedMAC]>;
 def : N3VSMulOpPat<fmul, fsub, VMLSfd>,
-      Requires<[HasNEON, UseNEONForFP, UseFPVMLx]>;
+      Requires<[HasNEON, UseNEONForFP, UseFPVMLx, DontUseFusedMAC]>;
+def : N3VSMulOpPat<fmul, fadd, VFMAfd>,
+      Requires<[HasVFP4, UseNEONForFP, UseFusedMAC]>;
+def : N3VSMulOpPat<fmul, fsub, VFMSfd>,
+      Requires<[HasVFP4, UseNEONForFP, UseFusedMAC]>;
 def : N2VSPat<fabs, VABSfd>;
 def : N2VSPat<fneg, VNEGfd>;
 def : N3VSPat<NEONfmax, VMAXfd>;
@@ -5028,3 +5584,1448 @@
 def : Pat<(v2f64 (bitconvert (v8i16 QPR:$src))), (v2f64 QPR:$src)>;
 def : Pat<(v2f64 (bitconvert (v16i8 QPR:$src))), (v2f64 QPR:$src)>;
 def : Pat<(v2f64 (bitconvert (v4f32 QPR:$src))), (v2f64 QPR:$src)>;
+
+// Vector lengthening move with load, matching extending loads.
+
+// extload, zextload and sextload for a standard lengthening load. Example:
+// Lengthen_Single<"8", "i16", "i8"> =3D Pat<(v8i16 (extloadvi8 addrmode5:=
$addr))
+//                                         (VMOVLuv8i16 (VLDRD addrmode5:$=
addr))>;
+multiclass Lengthen_Single<string DestLanes, string DestTy, string SrcTy> {
+  def _Any : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                    (!cast<PatFrag>("extloadv" # SrcTy) addrmode5:$addr)),
+                  (!cast<Instruction>("VMOVLuv" # DestLanes # DestTy)
+                    (VLDRD addrmode5:$addr))>;
+  def _Z : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                  (!cast<PatFrag>("zextloadv" # SrcTy) addrmode5:$addr)),
+                (!cast<Instruction>("VMOVLuv" # DestLanes # DestTy)
+                  (VLDRD addrmode5:$addr))>;
+  def _S : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                  (!cast<PatFrag>("sextloadv" # SrcTy) addrmode5:$addr)),
+                (!cast<Instruction>("VMOVLsv" # DestLanes # DestTy)
+                  (VLDRD addrmode5:$addr))>;
+}
+
+// extload, zextload and sextload for a lengthening load which only uses
+// half the lanes available. Example:
+// Lengthen_HalfSingle<"4", "i16", "8", "i16", "i8"> =3D
+//     Pat<(v4i16 (extloadvi8 addrmode5:$addr))
+//         (EXTRACT_SUBREG (VMOVLuv8i16 (INSERT_SUBREG (f64 (IMPLICIT_DEF)=
),
+//                                                     (VLDRS addrmode5:$a=
ddr),
+//                                                     ssub_0)),
+//                         dsub_0)>;
+multiclass Lengthen_HalfSingle<string DestLanes, string DestTy, string Src=
Ty,
+                               string InsnLanes, string InsnTy> {
+  def _Any : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                   (!cast<PatFrag>("extloadv" # SrcTy) addrmode5:$addr)),
+       (EXTRACT_SUBREG (!cast<Instruction>("VMOVLuv" # InsnLanes # InsnTy)
+         (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr), ssu=
b_0)),
+         dsub_0)>;
+  def _Z   : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                   (!cast<PatFrag>("zextloadv" # SrcTy) addrmode5:$addr)),
+       (EXTRACT_SUBREG (!cast<Instruction>("VMOVLuv" # InsnLanes # InsnTy)
+         (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr), ssu=
b_0)),
+         dsub_0)>;
+  def _S   : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                   (!cast<PatFrag>("sextloadv" # SrcTy) addrmode5:$addr)),
+       (EXTRACT_SUBREG (!cast<Instruction>("VMOVLsv" # InsnLanes # InsnTy)
+         (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr), ssu=
b_0)),
+         dsub_0)>;
+}
+
+// extload, zextload and sextload for a lengthening load followed by anoth=
er
+// lengthening load, to quadruple the initial length.
+// Lengthen_Double<"4", "i32", "i8", "8", "i16", "4", "i32", qsub_0> =3D
+//     Pat<(v4i32 (extloadvi8 addrmode5:$addr))
+//         (EXTRACT_SUBREG (VMOVLuv4i32=20
+//           (EXTRACT_SUBREG (VMOVLuv8i16 (INSERT_SUBREG (f64 (IMPLICIT_DE=
F)),
+//                                                       (VLDRS addrmode5:=
$addr),
+//                                                       ssub_0)),
+//                           dsub_0)),
+//           qsub_0)>;
+multiclass Lengthen_Double<string DestLanes, string DestTy, string SrcTy,
+                           string Insn1Lanes, string Insn1Ty, string Insn2=
Lanes,
+                           string Insn2Ty, SubRegIndex RegType> {
+  def _Any : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                   (!cast<PatFrag>("extloadv" # SrcTy) addrmode5:$addr)),
+         (EXTRACT_SUBREG (!cast<Instruction>("VMOVLuv" # Insn2Lanes # Insn=
2Ty)
+           (EXTRACT_SUBREG (!cast<Instruction>("VMOVLuv" # Insn1Lanes # In=
sn1Ty)
+             (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr),
+              ssub_0)), dsub_0)),
+          RegType)>;
+  def _Z   : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                   (!cast<PatFrag>("zextloadv" # SrcTy) addrmode5:$addr)),
+         (EXTRACT_SUBREG (!cast<Instruction>("VMOVLuv" # Insn2Lanes # Insn=
2Ty)
+           (EXTRACT_SUBREG (!cast<Instruction>("VMOVLuv" # Insn1Lanes # In=
sn1Ty)
+             (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr),
+              ssub_0)), dsub_0)),
+          RegType)>;
+  def _S   : Pat<(!cast<ValueType>("v" # DestLanes # DestTy)
+                   (!cast<PatFrag>("sextloadv" # SrcTy) addrmode5:$addr)),
+         (EXTRACT_SUBREG (!cast<Instruction>("VMOVLsv" # Insn2Lanes # Insn=
2Ty)
+           (EXTRACT_SUBREG (!cast<Instruction>("VMOVLsv" # Insn1Lanes # In=
sn1Ty)
+             (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr),
+              ssub_0)), dsub_0)),
+          RegType)>;
+}
+
+defm : Lengthen_Single<"8", "i16", "i8">; // v8i8 -> v8i16
+defm : Lengthen_Single<"4", "i32", "i16">; // v4i16 -> v4i32
+defm : Lengthen_Single<"2", "i64", "i32">; // v2i32 -> v2i64
+
+defm : Lengthen_HalfSingle<"4", "i16", "i8", "8", "i16">; // v4i8 -> v4i16
+defm : Lengthen_HalfSingle<"2", "i16", "i8", "8", "i16">; // v2i8 -> v2i16
+defm : Lengthen_HalfSingle<"2", "i32", "i16", "4", "i32">; // v2i16 -> v2i=
32
+
+// Double lengthening - v4i8 -> v4i16 -> v4i32=20
+defm : Lengthen_Double<"4", "i32", "i8", "8", "i16", "4", "i32", qsub_0>;
+// v2i8 -> v2i16 -> v2i32
+defm : Lengthen_Double<"2", "i32", "i8", "8", "i16", "4", "i32", dsub_0>;
+// v2i16 -> v2i32 -> v2i64
+defm : Lengthen_Double<"2", "i64", "i16", "4", "i32", "2", "i64", qsub_0>;
+
+// Triple lengthening - v2i8 -> v2i16 -> v2i32 -> v2i64
+def : Pat<(v2i64 (extloadvi8 addrmode5:$addr)),
+      (VMOVLuv2i64 (EXTRACT_SUBREG (VMOVLuv4i32 (EXTRACT_SUBREG (VMOVLuv8i=
16
+         (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr), ssu=
b_0)),
+         dsub_0)), dsub_0))>;
+def : Pat<(v2i64 (zextloadvi8 addrmode5:$addr)),
+      (VMOVLuv2i64 (EXTRACT_SUBREG (VMOVLuv4i32 (EXTRACT_SUBREG (VMOVLuv8i=
16
+         (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr), ssu=
b_0)),
+         dsub_0)), dsub_0))>;
+def : Pat<(v2i64 (sextloadvi8 addrmode5:$addr)),
+      (VMOVLsv2i64 (EXTRACT_SUBREG (VMOVLsv4i32 (EXTRACT_SUBREG (VMOVLsv8i=
16
+         (INSERT_SUBREG (f64 (IMPLICIT_DEF)), (VLDRS addrmode5:$addr), ssu=
b_0)),
+         dsub_0)), dsub_0))>;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Assembler aliases
+//
+
+def : VFP2InstAlias<"fmdhr${p} $Dd, $Rn",
+                    (VSETLNi32 DPR:$Dd, GPR:$Rn, 1, pred:$p)>;
+def : VFP2InstAlias<"fmdlr${p} $Dd, $Rn",
+                    (VSETLNi32 DPR:$Dd, GPR:$Rn, 0, pred:$p)>;
+
+
+// VADD two-operand aliases.
+def : NEONInstAlias<"vadd${p}.i8 $Vdn, $Vm",
+                    (VADDv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vadd${p}.i16 $Vdn, $Vm",
+                    (VADDv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vadd${p}.i32 $Vdn, $Vm",
+                    (VADDv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vadd${p}.i64 $Vdn, $Vm",
+                    (VADDv2i64 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vadd${p}.i8 $Vdn, $Vm",
+                    (VADDv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vadd${p}.i16 $Vdn, $Vm",
+                    (VADDv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vadd${p}.i32 $Vdn, $Vm",
+                    (VADDv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vadd${p}.i64 $Vdn, $Vm",
+                    (VADDv1i64 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vadd${p}.f32 $Vdn, $Vm",
+                    (VADDfd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vadd${p}.f32 $Vdn, $Vm",
+                    (VADDfq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// VSUB two-operand aliases.
+def : NEONInstAlias<"vsub${p}.i8 $Vdn, $Vm",
+                    (VSUBv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vsub${p}.i16 $Vdn, $Vm",
+                    (VSUBv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vsub${p}.i32 $Vdn, $Vm",
+                    (VSUBv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vsub${p}.i64 $Vdn, $Vm",
+                    (VSUBv2i64 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vsub${p}.i8 $Vdn, $Vm",
+                    (VSUBv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vsub${p}.i16 $Vdn, $Vm",
+                    (VSUBv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vsub${p}.i32 $Vdn, $Vm",
+                    (VSUBv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vsub${p}.i64 $Vdn, $Vm",
+                    (VSUBv1i64 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vsub${p}.f32 $Vdn, $Vm",
+                    (VSUBfd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vsub${p}.f32 $Vdn, $Vm",
+                    (VSUBfq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// VADDW two-operand aliases.
+def : NEONInstAlias<"vaddw${p}.s8 $Vdn, $Vm",
+                    (VADDWsv8i16 QPR:$Vdn, QPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vaddw${p}.s16 $Vdn, $Vm",
+                    (VADDWsv4i32 QPR:$Vdn, QPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vaddw${p}.s32 $Vdn, $Vm",
+                    (VADDWsv2i64 QPR:$Vdn, QPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vaddw${p}.u8 $Vdn, $Vm",
+                    (VADDWuv8i16 QPR:$Vdn, QPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vaddw${p}.u16 $Vdn, $Vm",
+                    (VADDWuv4i32 QPR:$Vdn, QPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vaddw${p}.u32 $Vdn, $Vm",
+                    (VADDWuv2i64 QPR:$Vdn, QPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+// VAND/VBIC/VEOR/VORR accept but do not require a type suffix.
+defm : NEONDTAnyInstAlias<"vand${p}", "$Vd, $Vn, $Vm",
+                         (VANDd DPR:$Vd, DPR:$Vn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vand${p}", "$Vd, $Vn, $Vm",
+                         (VANDq QPR:$Vd, QPR:$Vn, QPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vbic${p}", "$Vd, $Vn, $Vm",
+                         (VBICd DPR:$Vd, DPR:$Vn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vbic${p}", "$Vd, $Vn, $Vm",
+                         (VBICq QPR:$Vd, QPR:$Vn, QPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"veor${p}", "$Vd, $Vn, $Vm",
+                         (VEORd DPR:$Vd, DPR:$Vn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"veor${p}", "$Vd, $Vn, $Vm",
+                         (VEORq QPR:$Vd, QPR:$Vn, QPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vorr${p}", "$Vd, $Vn, $Vm",
+                         (VORRd DPR:$Vd, DPR:$Vn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vorr${p}", "$Vd, $Vn, $Vm",
+                         (VORRq QPR:$Vd, QPR:$Vn, QPR:$Vm, pred:$p)>;
+// ... two-operand aliases
+def : NEONInstAlias<"vand${p} $Vdn, $Vm",
+                    (VANDd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vand${p} $Vdn, $Vm",
+                    (VANDq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vbic${p} $Vdn, $Vm",
+                    (VBICd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vbic${p} $Vdn, $Vm",
+                    (VBICq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"veor${p} $Vdn, $Vm",
+                    (VEORd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"veor${p} $Vdn, $Vm",
+                    (VEORq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vorr${p} $Vdn, $Vm",
+                    (VORRd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vorr${p} $Vdn, $Vm",
+                    (VORRq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+defm : NEONDTAnyInstAlias<"vand${p}", "$Vdn, $Vm",
+                         (VANDd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vand${p}", "$Vdn, $Vm",
+                         (VANDq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"veor${p}", "$Vdn, $Vm",
+                         (VEORd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"veor${p}", "$Vdn, $Vm",
+                         (VEORq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vorr${p}", "$Vdn, $Vm",
+                         (VORRd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vorr${p}", "$Vdn, $Vm",
+                         (VORRq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// VMUL two-operand aliases.
+def : NEONInstAlias<"vmul${p}.p8 $Qdn, $Qm",
+                    (VMULpq QPR:$Qdn, QPR:$Qdn, QPR:$Qm, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i8 $Qdn, $Qm",
+                    (VMULv16i8 QPR:$Qdn, QPR:$Qdn, QPR:$Qm, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i16 $Qdn, $Qm",
+                    (VMULv8i16 QPR:$Qdn, QPR:$Qdn, QPR:$Qm, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i32 $Qdn, $Qm",
+                    (VMULv4i32 QPR:$Qdn, QPR:$Qdn, QPR:$Qm, pred:$p)>;
+
+def : NEONInstAlias<"vmul${p}.p8 $Ddn, $Dm",
+                    (VMULpd DPR:$Ddn, DPR:$Ddn, DPR:$Dm, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i8 $Ddn, $Dm",
+                    (VMULv8i8 DPR:$Ddn, DPR:$Ddn, DPR:$Dm, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i16 $Ddn, $Dm",
+                    (VMULv4i16 DPR:$Ddn, DPR:$Ddn, DPR:$Dm, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i32 $Ddn, $Dm",
+                    (VMULv2i32 DPR:$Ddn, DPR:$Ddn, DPR:$Dm, pred:$p)>;
+
+def : NEONInstAlias<"vmul${p}.f32 $Qdn, $Qm",
+                    (VMULfq QPR:$Qdn, QPR:$Qdn, QPR:$Qm, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.f32 $Ddn, $Dm",
+                    (VMULfd DPR:$Ddn, DPR:$Ddn, DPR:$Dm, pred:$p)>;
+
+def : NEONInstAlias<"vmul${p}.i16 $Ddn, $Dm$lane",
+                    (VMULslv4i16 DPR:$Ddn, DPR:$Ddn, DPR_8:$Dm,
+                                 VectorIndex16:$lane, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i16 $Qdn, $Dm$lane",
+                    (VMULslv8i16 QPR:$Qdn, QPR:$Qdn, DPR_8:$Dm,
+                                 VectorIndex16:$lane, pred:$p)>;
+
+def : NEONInstAlias<"vmul${p}.i32 $Ddn, $Dm$lane",
+                    (VMULslv2i32 DPR:$Ddn, DPR:$Ddn, DPR_VFP2:$Dm,
+                                 VectorIndex32:$lane, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.i32 $Qdn, $Dm$lane",
+                    (VMULslv4i32 QPR:$Qdn, QPR:$Qdn, DPR_VFP2:$Dm,
+                                 VectorIndex32:$lane, pred:$p)>;
+
+def : NEONInstAlias<"vmul${p}.f32 $Ddn, $Dm$lane",
+                    (VMULslfd DPR:$Ddn, DPR:$Ddn, DPR_VFP2:$Dm,
+                              VectorIndex32:$lane, pred:$p)>;
+def : NEONInstAlias<"vmul${p}.f32 $Qdn, $Dm$lane",
+                    (VMULslfq QPR:$Qdn, QPR:$Qdn, DPR_VFP2:$Dm,
+                              VectorIndex32:$lane, pred:$p)>;
+
+// VQADD (register) two-operand aliases.
+def : NEONInstAlias<"vqadd${p}.s8 $Vdn, $Vm",
+                    (VQADDsv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.s16 $Vdn, $Vm",
+                    (VQADDsv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.s32 $Vdn, $Vm",
+                    (VQADDsv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.s64 $Vdn, $Vm",
+                    (VQADDsv1i64 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u8 $Vdn, $Vm",
+                    (VQADDuv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u16 $Vdn, $Vm",
+                    (VQADDuv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u32 $Vdn, $Vm",
+                    (VQADDuv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u64 $Vdn, $Vm",
+                    (VQADDuv1i64 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vqadd${p}.s8 $Vdn, $Vm",
+                    (VQADDsv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.s16 $Vdn, $Vm",
+                    (VQADDsv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.s32 $Vdn, $Vm",
+                    (VQADDsv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.s64 $Vdn, $Vm",
+                    (VQADDsv2i64 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u8 $Vdn, $Vm",
+                    (VQADDuv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u16 $Vdn, $Vm",
+                    (VQADDuv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u32 $Vdn, $Vm",
+                    (VQADDuv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqadd${p}.u64 $Vdn, $Vm",
+                    (VQADDuv2i64 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// VSHL (immediate) two-operand aliases.
+def : NEONInstAlias<"vshl${p}.i8 $Vdn, $imm",
+                    (VSHLiv8i8 DPR:$Vdn, DPR:$Vdn, imm0_7:$imm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.i16 $Vdn, $imm",
+                    (VSHLiv4i16 DPR:$Vdn, DPR:$Vdn, imm0_15:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vshl${p}.i32 $Vdn, $imm",
+                    (VSHLiv2i32 DPR:$Vdn, DPR:$Vdn, imm0_31:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vshl${p}.i64 $Vdn, $imm",
+                    (VSHLiv1i64 DPR:$Vdn, DPR:$Vdn, imm0_63:$imm, pred:$p)=
>;
+
+def : NEONInstAlias<"vshl${p}.i8 $Vdn, $imm",
+                    (VSHLiv16i8 QPR:$Vdn, QPR:$Vdn, imm0_7:$imm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.i16 $Vdn, $imm",
+                    (VSHLiv8i16 QPR:$Vdn, QPR:$Vdn, imm0_15:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vshl${p}.i32 $Vdn, $imm",
+                    (VSHLiv4i32 QPR:$Vdn, QPR:$Vdn, imm0_31:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vshl${p}.i64 $Vdn, $imm",
+                    (VSHLiv2i64 QPR:$Vdn, QPR:$Vdn, imm0_63:$imm, pred:$p)=
>;
+
+// VSHL (register) two-operand aliases.
+def : NEONInstAlias<"vshl${p}.s8 $Vdn, $Vm",
+                    (VSHLsv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.s16 $Vdn, $Vm",
+                    (VSHLsv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.s32 $Vdn, $Vm",
+                    (VSHLsv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.s64 $Vdn, $Vm",
+                    (VSHLsv1i64 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u8 $Vdn, $Vm",
+                    (VSHLuv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u16 $Vdn, $Vm",
+                    (VSHLuv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u32 $Vdn, $Vm",
+                    (VSHLuv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u64 $Vdn, $Vm",
+                    (VSHLuv1i64 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vshl${p}.s8 $Vdn, $Vm",
+                    (VSHLsv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.s16 $Vdn, $Vm",
+                    (VSHLsv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.s32 $Vdn, $Vm",
+                    (VSHLsv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.s64 $Vdn, $Vm",
+                    (VSHLsv2i64 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u8 $Vdn, $Vm",
+                    (VSHLuv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u16 $Vdn, $Vm",
+                    (VSHLuv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u32 $Vdn, $Vm",
+                    (VSHLuv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vshl${p}.u64 $Vdn, $Vm",
+                    (VSHLuv2i64 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// VSHL (immediate) two-operand aliases.
+def : NEONInstAlias<"vshr${p}.s8 $Vdn, $imm",
+                    (VSHRsv8i8 DPR:$Vdn, DPR:$Vdn, shr_imm8:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vshr${p}.s16 $Vdn, $imm",
+                    (VSHRsv4i16 DPR:$Vdn, DPR:$Vdn, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.s32 $Vdn, $imm",
+                    (VSHRsv2i32 DPR:$Vdn, DPR:$Vdn, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.s64 $Vdn, $imm",
+                    (VSHRsv1i64 DPR:$Vdn, DPR:$Vdn, shr_imm64:$imm, pred:$=
p)>;
+
+def : NEONInstAlias<"vshr${p}.s8 $Vdn, $imm",
+                    (VSHRsv16i8 QPR:$Vdn, QPR:$Vdn, shr_imm8:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vshr${p}.s16 $Vdn, $imm",
+                    (VSHRsv8i16 QPR:$Vdn, QPR:$Vdn, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.s32 $Vdn, $imm",
+                    (VSHRsv4i32 QPR:$Vdn, QPR:$Vdn, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.s64 $Vdn, $imm",
+                    (VSHRsv2i64 QPR:$Vdn, QPR:$Vdn, shr_imm64:$imm, pred:$=
p)>;
+
+def : NEONInstAlias<"vshr${p}.u8 $Vdn, $imm",
+                    (VSHRuv8i8 DPR:$Vdn, DPR:$Vdn, shr_imm8:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vshr${p}.u16 $Vdn, $imm",
+                    (VSHRuv4i16 DPR:$Vdn, DPR:$Vdn, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.u32 $Vdn, $imm",
+                    (VSHRuv2i32 DPR:$Vdn, DPR:$Vdn, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.u64 $Vdn, $imm",
+                    (VSHRuv1i64 DPR:$Vdn, DPR:$Vdn, shr_imm64:$imm, pred:$=
p)>;
+
+def : NEONInstAlias<"vshr${p}.u8 $Vdn, $imm",
+                    (VSHRuv16i8 QPR:$Vdn, QPR:$Vdn, shr_imm8:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vshr${p}.u16 $Vdn, $imm",
+                    (VSHRuv8i16 QPR:$Vdn, QPR:$Vdn, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.u32 $Vdn, $imm",
+                    (VSHRuv4i32 QPR:$Vdn, QPR:$Vdn, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vshr${p}.u64 $Vdn, $imm",
+                    (VSHRuv2i64 QPR:$Vdn, QPR:$Vdn, shr_imm64:$imm, pred:$=
p)>;
+
+// VLD1 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VLD1LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vld1${p}", ".8", "$list, $ad=
dr",
+                 (ins VecListOneDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD1LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vld1${p}", ".16", "$list, $=
addr",
+                 (ins VecListOneDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD1LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vld1${p}", ".32", "$list, $=
addr",
+                 (ins VecListOneDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+
+def VLD1LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld1${p}", ".8", "$list, $addr!",
+                 (ins VecListOneDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD1LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld1${p}", ".16", "$list, $addr!",
+                 (ins VecListOneDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD1LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld1${p}", ".32", "$list, $addr!",
+                 (ins VecListOneDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD1LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld1${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListOneDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD1LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld1${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListOneDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD1LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld1${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListOneDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+
+// VST1 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VST1LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vst1${p}", ".8", "$list, $ad=
dr",
+                 (ins VecListOneDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST1LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vst1${p}", ".16", "$list, $=
addr",
+                 (ins VecListOneDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST1LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vst1${p}", ".32", "$list, $=
addr",
+                 (ins VecListOneDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+
+def VST1LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst1${p}", ".8", "$list, $addr!",
+                 (ins VecListOneDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST1LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst1${p}", ".16", "$list, $addr!",
+                 (ins VecListOneDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST1LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst1${p}", ".32", "$list, $addr!",
+                 (ins VecListOneDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST1LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst1${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListOneDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST1LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst1${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListOneDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST1LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst1${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListOneDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+// VLD2 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VLD2LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vld2${p}", ".8", "$list, $ad=
dr",
+                 (ins VecListTwoDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD2LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vld2${p}", ".16", "$list, $=
addr",
+                 (ins VecListTwoDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD2LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vld2${p}", ".32", "$list, $=
addr",
+                 (ins VecListTwoDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD2LNqAsm_16 : NEONDataTypeAsmPseudoInst<"vld2${p}", ".16", "$list, $=
addr",
+                 (ins VecListTwoQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD2LNqAsm_32 : NEONDataTypeAsmPseudoInst<"vld2${p}", ".32", "$list, $=
addr",
+                 (ins VecListTwoQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+
+def VLD2LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".8", "$list, $addr!",
+                 (ins VecListTwoDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD2LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".16", "$list, $addr!",
+                 (ins VecListTwoDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD2LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".32", "$list, $addr!",
+                 (ins VecListTwoDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD2LNqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".16", "$list, $addr!",
+                 (ins VecListTwoQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD2LNqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".32", "$list, $addr!",
+                 (ins VecListTwoQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD2LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListTwoDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD2LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListTwoDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD2LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListTwoDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD2LNqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListTwoQHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD2LNqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld2${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListTwoQWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+
+// VST2 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VST2LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vst2${p}", ".8", "$list, $ad=
dr",
+                 (ins VecListTwoDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST2LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vst2${p}", ".16", "$list, $=
addr",
+                 (ins VecListTwoDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST2LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vst2${p}", ".32", "$list, $=
addr",
+                 (ins VecListTwoDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST2LNqAsm_16 : NEONDataTypeAsmPseudoInst<"vst2${p}", ".16", "$list, $=
addr",
+                 (ins VecListTwoQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST2LNqAsm_32 : NEONDataTypeAsmPseudoInst<"vst2${p}", ".32", "$list, $=
addr",
+                 (ins VecListTwoQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+
+def VST2LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".8", "$list, $addr!",
+                 (ins VecListTwoDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST2LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".16", "$list, $addr!",
+                 (ins VecListTwoDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST2LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".32", "$list, $addr!",
+                 (ins VecListTwoDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST2LNqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".16", "$list, $addr!",
+                 (ins VecListTwoQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST2LNqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".32", "$list, $addr!",
+                 (ins VecListTwoQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST2LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListTwoDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST2LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".16","$list, $addr, $Rm",
+                  (ins VecListTwoDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST2LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListTwoDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST2LNqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".16","$list, $addr, $Rm",
+                  (ins VecListTwoQHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST2LNqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst2${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListTwoQWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+// VLD3 all-lanes pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VLD3DUPdAsm_8  : NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $=
addr",
+               (ins VecListThreeDAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPdAsm_16 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, =
$addr",
+               (ins VecListThreeDAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPdAsm_32 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, =
$addr",
+               (ins VecListThreeDAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPqAsm_8  : NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $=
addr",
+               (ins VecListThreeQAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPqAsm_16 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, =
$addr",
+               (ins VecListThreeQAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPqAsm_32 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, =
$addr",
+               (ins VecListThreeQAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+
+def VLD3DUPdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeDAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeDAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeDAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPqWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeQAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeQAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeQAllLanes:$list, addrmode6:$addr, pred:$p)=
>;
+def VLD3DUPdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeDAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3DUPdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeDAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3DUPdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeDAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3DUPqWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeQAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3DUPqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeQAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3DUPqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeQAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+
+// VLD3 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VLD3LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $ad=
dr",
+               (ins VecListThreeDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD3LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $=
addr",
+               (ins VecListThreeDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD3LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $=
addr",
+               (ins VecListThreeDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD3LNqAsm_16 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $=
addr",
+               (ins VecListThreeQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD3LNqAsm_32 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $=
addr",
+               (ins VecListThreeQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+
+def VLD3LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD3LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD3LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD3LNqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VLD3LNqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD3LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3LNqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeQHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3LNqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeQWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+// VLD3 multiple structure pseudo-instructions. These need special handlin=
g for
+// the vector operands that the normal instructions don't yet model.
+// FIXME: Remove these when the register classes and instructions are upda=
ted.
+def VLD3dAsm_8 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr=
",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VLD3dAsm_16 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $ad=
dr",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VLD3dAsm_32 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $ad=
dr",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VLD3qAsm_8 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr=
",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD3qAsm_16 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $ad=
dr",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD3qAsm_32 : NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $ad=
dr",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+
+def VLD3dWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VLD3dWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VLD3dWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VLD3qWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD3qWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD3qWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD3dWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3dWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3dWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3qWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3qWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD3qWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+// VST3 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VST3LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $ad=
dr",
+               (ins VecListThreeDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST3LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $=
addr",
+               (ins VecListThreeDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST3LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $=
addr",
+               (ins VecListThreeDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST3LNqAsm_16 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $=
addr",
+               (ins VecListThreeQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST3LNqAsm_32 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $=
addr",
+               (ins VecListThreeQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+
+def VST3LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeDByteIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST3LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeDHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST3LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeDWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST3LNqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeQHWordIndexed:$list, addrmode6:$addr, pred=
:$p)>;
+def VST3LNqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeQWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST3LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3LNqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeQHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3LNqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeQWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+
+// VST3 multiple structure pseudo-instructions. These need special handlin=
g for
+// the vector operands that the normal instructions don't yet model.
+// FIXME: Remove these when the register classes and instructions are upda=
ted.
+def VST3dAsm_8 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr=
",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VST3dAsm_16 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $ad=
dr",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VST3dAsm_32 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $ad=
dr",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VST3qAsm_8 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr=
",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VST3qAsm_16 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $ad=
dr",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VST3qAsm_32 : NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $ad=
dr",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+
+def VST3dWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VST3dWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VST3dWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeD:$list, addrmode6:$addr, pred:$p)>;
+def VST3qWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr!",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VST3qWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr!",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VST3qWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr!",
+               (ins VecListThreeQ:$list, addrmode6:$addr, pred:$p)>;
+def VST3dWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3dWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3dWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3qWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListThreeQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3qWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListThreeQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST3qWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst3${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListThreeQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+// VLD4 all-lanes pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VLD4DUPdAsm_8  : NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $=
addr",
+               (ins VecListFourDAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPdAsm_16 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, =
$addr",
+               (ins VecListFourDAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPdAsm_32 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, =
$addr",
+               (ins VecListFourDAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPqAsm_8  : NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $=
addr",
+               (ins VecListFourQAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPqAsm_16 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, =
$addr",
+               (ins VecListFourQAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPqAsm_32 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, =
$addr",
+               (ins VecListFourQAllLanes:$list, addrmode6:$addr, pred:$p)>;
+
+def VLD4DUPdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr!",
+               (ins VecListFourDAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr!",
+               (ins VecListFourDAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr!",
+               (ins VecListFourDAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPqWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr!",
+               (ins VecListFourQAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr!",
+               (ins VecListFourQAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr!",
+               (ins VecListFourQAllLanes:$list, addrmode6:$addr, pred:$p)>;
+def VLD4DUPdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourDAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4DUPdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourDAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4DUPdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourDAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4DUPqWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourQAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4DUPqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourQAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4DUPqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourQAllLanes:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+
+// VLD4 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VLD4LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $ad=
dr",
+               (ins VecListFourDByteIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VLD4LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $=
addr",
+               (ins VecListFourDHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD4LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $=
addr",
+               (ins VecListFourDWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VLD4LNqAsm_16 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $=
addr",
+               (ins VecListFourQHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD4LNqAsm_32 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $=
addr",
+               (ins VecListFourQWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+
+def VLD4LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr!",
+               (ins VecListFourDByteIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VLD4LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr!",
+               (ins VecListFourDHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD4LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr!",
+               (ins VecListFourDWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VLD4LNqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr!",
+               (ins VecListFourQHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VLD4LNqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr!",
+               (ins VecListFourQWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VLD4LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4LNqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourQHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4LNqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourQWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+
+
+// VLD4 multiple structure pseudo-instructions. These need special handlin=
g for
+// the vector operands that the normal instructions don't yet model.
+// FIXME: Remove these when the register classes and instructions are upda=
ted.
+def VLD4dAsm_8 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr=
",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VLD4dAsm_16 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $ad=
dr",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VLD4dAsm_32 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $ad=
dr",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VLD4qAsm_8 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr=
",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD4qAsm_16 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $ad=
dr",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD4qAsm_32 : NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $ad=
dr",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+
+def VLD4dWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr!",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VLD4dWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr!",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VLD4dWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr!",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VLD4qWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr!",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD4qWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr!",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD4qWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr!",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VLD4dWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4dWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4dWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4qWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4qWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VLD4qWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vld4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+// VST4 single-lane pseudo-instructions. These need special handling for
+// the lane index that an InstAlias can't handle, so we use these instead.
+def VST4LNdAsm_8 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $ad=
dr",
+               (ins VecListFourDByteIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VST4LNdAsm_16 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $=
addr",
+               (ins VecListFourDHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST4LNdAsm_32 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $=
addr",
+               (ins VecListFourDWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VST4LNqAsm_16 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $=
addr",
+               (ins VecListFourQHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST4LNqAsm_32 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $=
addr",
+               (ins VecListFourQWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+
+def VST4LNdWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr!",
+               (ins VecListFourDByteIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VST4LNdWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr!",
+               (ins VecListFourDHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST4LNdWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr!",
+               (ins VecListFourDWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VST4LNqWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr!",
+               (ins VecListFourQHWordIndexed:$list, addrmode6:$addr, pred:=
$p)>;
+def VST4LNqWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr!",
+               (ins VecListFourQWordIndexed:$list, addrmode6:$addr, pred:$=
p)>;
+def VST4LNdWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourDByteIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4LNdWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourDHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4LNdWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourDWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4LNqWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourQHWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4LNqWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourQWordIndexed:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+
+// VST4 multiple structure pseudo-instructions. These need special handlin=
g for
+// the vector operands that the normal instructions don't yet model.
+// FIXME: Remove these when the register classes and instructions are upda=
ted.
+def VST4dAsm_8 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr=
",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VST4dAsm_16 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $ad=
dr",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VST4dAsm_32 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $ad=
dr",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VST4qAsm_8 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr=
",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VST4qAsm_16 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $ad=
dr",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VST4qAsm_32 : NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $ad=
dr",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+
+def VST4dWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr!",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VST4dWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr!",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VST4dWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr!",
+               (ins VecListFourD:$list, addrmode6:$addr, pred:$p)>;
+def VST4qWB_fixed_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr!",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VST4qWB_fixed_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr!",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VST4qWB_fixed_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr!",
+               (ins VecListFourQ:$list, addrmode6:$addr, pred:$p)>;
+def VST4dWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4dWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4dWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourD:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4qWB_register_Asm_8 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".8", "$list, $addr, $Rm",
+                  (ins VecListFourQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4qWB_register_Asm_16 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".16", "$list, $addr, $Rm",
+                  (ins VecListFourQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+def VST4qWB_register_Asm_32 :
+        NEONDataTypeAsmPseudoInst<"vst4${p}", ".32", "$list, $addr, $Rm",
+                  (ins VecListFourQ:$list, addrmode6:$addr,
+                       rGPR:$Rm, pred:$p)>;
+
+// VMOV takes an optional datatype suffix
+defm : NEONDTAnyInstAlias<"vmov${p}", "$Vd, $Vm",
+                         (VORRd DPR:$Vd, DPR:$Vm, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vmov${p}", "$Vd, $Vm",
+                         (VORRq QPR:$Vd, QPR:$Vm, QPR:$Vm, pred:$p)>;
+
+// VCLT (register) is an assembler alias for VCGT w/ the operands reversed.
+// D-register versions.
+def : NEONInstAlias<"vcle${p}.s8 $Dd, $Dn, $Dm",
+                    (VCGEsv8i8 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.s16 $Dd, $Dn, $Dm",
+                    (VCGEsv4i16 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.s32 $Dd, $Dn, $Dm",
+                    (VCGEsv2i32 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.u8 $Dd, $Dn, $Dm",
+                    (VCGEuv8i8 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.u16 $Dd, $Dn, $Dm",
+                    (VCGEuv4i16 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.u32 $Dd, $Dn, $Dm",
+                    (VCGEuv2i32 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.f32 $Dd, $Dn, $Dm",
+                    (VCGEfd DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+// Q-register versions.
+def : NEONInstAlias<"vcle${p}.s8 $Qd, $Qn, $Qm",
+                    (VCGEsv16i8 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.s16 $Qd, $Qn, $Qm",
+                    (VCGEsv8i16 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.s32 $Qd, $Qn, $Qm",
+                    (VCGEsv4i32 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.u8 $Qd, $Qn, $Qm",
+                    (VCGEuv16i8 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.u16 $Qd, $Qn, $Qm",
+                    (VCGEuv8i16 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.u32 $Qd, $Qn, $Qm",
+                    (VCGEuv4i32 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vcle${p}.f32 $Qd, $Qn, $Qm",
+                    (VCGEfq QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+
+// VCLT (register) is an assembler alias for VCGT w/ the operands reversed.
+// D-register versions.
+def : NEONInstAlias<"vclt${p}.s8 $Dd, $Dn, $Dm",
+                    (VCGTsv8i8 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.s16 $Dd, $Dn, $Dm",
+                    (VCGTsv4i16 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.s32 $Dd, $Dn, $Dm",
+                    (VCGTsv2i32 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.u8 $Dd, $Dn, $Dm",
+                    (VCGTuv8i8 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.u16 $Dd, $Dn, $Dm",
+                    (VCGTuv4i16 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.u32 $Dd, $Dn, $Dm",
+                    (VCGTuv2i32 DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.f32 $Dd, $Dn, $Dm",
+                    (VCGTfd DPR:$Dd, DPR:$Dm, DPR:$Dn, pred:$p)>;
+// Q-register versions.
+def : NEONInstAlias<"vclt${p}.s8 $Qd, $Qn, $Qm",
+                    (VCGTsv16i8 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.s16 $Qd, $Qn, $Qm",
+                    (VCGTsv8i16 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.s32 $Qd, $Qn, $Qm",
+                    (VCGTsv4i32 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.u8 $Qd, $Qn, $Qm",
+                    (VCGTuv16i8 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.u16 $Qd, $Qn, $Qm",
+                    (VCGTuv8i16 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.u32 $Qd, $Qn, $Qm",
+                    (VCGTuv4i32 QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+def : NEONInstAlias<"vclt${p}.f32 $Qd, $Qn, $Qm",
+                    (VCGTfq QPR:$Qd, QPR:$Qm, QPR:$Qn, pred:$p)>;
+
+// Two-operand variants for VEXT
+def : NEONInstAlias<"vext${p}.8 $Vdn, $Vm, $imm",
+                  (VEXTd8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, imm0_7:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vext${p}.16 $Vdn, $Vm, $imm",
+                  (VEXTd16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, imm0_3:$imm, pred:=
$p)>;
+def : NEONInstAlias<"vext${p}.32 $Vdn, $Vm, $imm",
+                  (VEXTd32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, imm0_1:$imm, pred:=
$p)>;
+
+def : NEONInstAlias<"vext${p}.8 $Vdn, $Vm, $imm",
+                  (VEXTq8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, imm0_15:$imm, pred:=
$p)>;
+def : NEONInstAlias<"vext${p}.16 $Vdn, $Vm, $imm",
+                  (VEXTq16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, imm0_7:$imm, pred:=
$p)>;
+def : NEONInstAlias<"vext${p}.32 $Vdn, $Vm, $imm",
+                  (VEXTq32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, imm0_3:$imm, pred:=
$p)>;
+def : NEONInstAlias<"vext${p}.64 $Vdn, $Vm, $imm",
+                  (VEXTq64 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, imm0_1:$imm, pred:=
$p)>;
+
+// Two-operand variants for VQDMULH
+def : NEONInstAlias<"vqdmulh${p}.s16 $Vdn, $Vm",
+                    (VQDMULHv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqdmulh${p}.s32 $Vdn, $Vm",
+                    (VQDMULHv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vqdmulh${p}.s16 $Vdn, $Vm",
+                    (VQDMULHv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vqdmulh${p}.s32 $Vdn, $Vm",
+                    (VQDMULHv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// Two-operand variants for VMAX.
+def : NEONInstAlias<"vmax${p}.s8 $Vdn, $Vm",
+                    (VMAXsv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.s16 $Vdn, $Vm",
+                    (VMAXsv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.s32 $Vdn, $Vm",
+                    (VMAXsv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.u8 $Vdn, $Vm",
+                    (VMAXuv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.u16 $Vdn, $Vm",
+                    (VMAXuv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.u32 $Vdn, $Vm",
+                    (VMAXuv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.f32 $Vdn, $Vm",
+                    (VMAXfd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vmax${p}.s8 $Vdn, $Vm",
+                    (VMAXsv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.s16 $Vdn, $Vm",
+                    (VMAXsv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.s32 $Vdn, $Vm",
+                    (VMAXsv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.u8 $Vdn, $Vm",
+                    (VMAXuv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.u16 $Vdn, $Vm",
+                    (VMAXuv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.u32 $Vdn, $Vm",
+                    (VMAXuv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmax${p}.f32 $Vdn, $Vm",
+                    (VMAXfq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// Two-operand variants for VMIN.
+def : NEONInstAlias<"vmin${p}.s8 $Vdn, $Vm",
+                    (VMINsv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.s16 $Vdn, $Vm",
+                    (VMINsv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.s32 $Vdn, $Vm",
+                    (VMINsv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.u8 $Vdn, $Vm",
+                    (VMINuv8i8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.u16 $Vdn, $Vm",
+                    (VMINuv4i16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.u32 $Vdn, $Vm",
+                    (VMINuv2i32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.f32 $Vdn, $Vm",
+                    (VMINfd DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+def : NEONInstAlias<"vmin${p}.s8 $Vdn, $Vm",
+                    (VMINsv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.s16 $Vdn, $Vm",
+                    (VMINsv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.s32 $Vdn, $Vm",
+                    (VMINsv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.u8 $Vdn, $Vm",
+                    (VMINuv16i8 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.u16 $Vdn, $Vm",
+                    (VMINuv8i16 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.u32 $Vdn, $Vm",
+                    (VMINuv4i32 QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vmin${p}.f32 $Vdn, $Vm",
+                    (VMINfq QPR:$Vdn, QPR:$Vdn, QPR:$Vm, pred:$p)>;
+
+// Two-operand variants for VPADD.
+def : NEONInstAlias<"vpadd${p}.i8 $Vdn, $Vm",
+                    (VPADDi8 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vpadd${p}.i16 $Vdn, $Vm",
+                    (VPADDi16 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vpadd${p}.i32 $Vdn, $Vm",
+                    (VPADDi32 DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+def : NEONInstAlias<"vpadd${p}.f32 $Vdn, $Vm",
+                    (VPADDf DPR:$Vdn, DPR:$Vdn, DPR:$Vm, pred:$p)>;
+
+// Two-operand variants for VSRA.
+    // Signed.
+def : NEONInstAlias<"vsra${p}.s8 $Vdm, $imm",
+                    (VSRAsv8i8 DPR:$Vdm, DPR:$Vdm, shr_imm8:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vsra${p}.s16 $Vdm, $imm",
+                    (VSRAsv4i16 DPR:$Vdm, DPR:$Vdm, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.s32 $Vdm, $imm",
+                    (VSRAsv2i32 DPR:$Vdm, DPR:$Vdm, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.s64 $Vdm, $imm",
+                    (VSRAsv1i64 DPR:$Vdm, DPR:$Vdm, shr_imm64:$imm, pred:$=
p)>;
+
+def : NEONInstAlias<"vsra${p}.s8 $Vdm, $imm",
+                    (VSRAsv16i8 QPR:$Vdm, QPR:$Vdm, shr_imm8:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsra${p}.s16 $Vdm, $imm",
+                    (VSRAsv8i16 QPR:$Vdm, QPR:$Vdm, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.s32 $Vdm, $imm",
+                    (VSRAsv4i32 QPR:$Vdm, QPR:$Vdm, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.s64 $Vdm, $imm",
+                    (VSRAsv2i64 QPR:$Vdm, QPR:$Vdm, shr_imm64:$imm, pred:$=
p)>;
+
+    // Unsigned.
+def : NEONInstAlias<"vsra${p}.u8 $Vdm, $imm",
+                    (VSRAuv8i8 DPR:$Vdm, DPR:$Vdm, shr_imm8:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vsra${p}.u16 $Vdm, $imm",
+                    (VSRAuv4i16 DPR:$Vdm, DPR:$Vdm, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.u32 $Vdm, $imm",
+                    (VSRAuv2i32 DPR:$Vdm, DPR:$Vdm, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.u64 $Vdm, $imm",
+                    (VSRAuv1i64 DPR:$Vdm, DPR:$Vdm, shr_imm64:$imm, pred:$=
p)>;
+
+def : NEONInstAlias<"vsra${p}.u8 $Vdm, $imm",
+                    (VSRAuv16i8 QPR:$Vdm, QPR:$Vdm, shr_imm8:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsra${p}.u16 $Vdm, $imm",
+                    (VSRAuv8i16 QPR:$Vdm, QPR:$Vdm, shr_imm16:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.u32 $Vdm, $imm",
+                    (VSRAuv4i32 QPR:$Vdm, QPR:$Vdm, shr_imm32:$imm, pred:$=
p)>;
+def : NEONInstAlias<"vsra${p}.u64 $Vdm, $imm",
+                    (VSRAuv2i64 QPR:$Vdm, QPR:$Vdm, shr_imm64:$imm, pred:$=
p)>;
+
+// Two-operand variants for VSRI.
+def : NEONInstAlias<"vsri${p}.8 $Vdm, $imm",
+                    (VSRIv8i8 DPR:$Vdm, DPR:$Vdm, shr_imm8:$imm, pred:$p)>;
+def : NEONInstAlias<"vsri${p}.16 $Vdm, $imm",
+                    (VSRIv4i16 DPR:$Vdm, DPR:$Vdm, shr_imm16:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsri${p}.32 $Vdm, $imm",
+                    (VSRIv2i32 DPR:$Vdm, DPR:$Vdm, shr_imm32:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsri${p}.64 $Vdm, $imm",
+                    (VSRIv1i64 DPR:$Vdm, DPR:$Vdm, shr_imm64:$imm, pred:$p=
)>;
+
+def : NEONInstAlias<"vsri${p}.8 $Vdm, $imm",
+                    (VSRIv16i8 QPR:$Vdm, QPR:$Vdm, shr_imm8:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vsri${p}.16 $Vdm, $imm",
+                    (VSRIv8i16 QPR:$Vdm, QPR:$Vdm, shr_imm16:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsri${p}.32 $Vdm, $imm",
+                    (VSRIv4i32 QPR:$Vdm, QPR:$Vdm, shr_imm32:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsri${p}.64 $Vdm, $imm",
+                    (VSRIv2i64 QPR:$Vdm, QPR:$Vdm, shr_imm64:$imm, pred:$p=
)>;
+
+// Two-operand variants for VSLI.
+def : NEONInstAlias<"vsli${p}.8 $Vdm, $imm",
+                    (VSLIv8i8 DPR:$Vdm, DPR:$Vdm, shr_imm8:$imm, pred:$p)>;
+def : NEONInstAlias<"vsli${p}.16 $Vdm, $imm",
+                    (VSLIv4i16 DPR:$Vdm, DPR:$Vdm, shr_imm16:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsli${p}.32 $Vdm, $imm",
+                    (VSLIv2i32 DPR:$Vdm, DPR:$Vdm, shr_imm32:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsli${p}.64 $Vdm, $imm",
+                    (VSLIv1i64 DPR:$Vdm, DPR:$Vdm, shr_imm64:$imm, pred:$p=
)>;
+
+def : NEONInstAlias<"vsli${p}.8 $Vdm, $imm",
+                    (VSLIv16i8 QPR:$Vdm, QPR:$Vdm, shr_imm8:$imm, pred:$p)=
>;
+def : NEONInstAlias<"vsli${p}.16 $Vdm, $imm",
+                    (VSLIv8i16 QPR:$Vdm, QPR:$Vdm, shr_imm16:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsli${p}.32 $Vdm, $imm",
+                    (VSLIv4i32 QPR:$Vdm, QPR:$Vdm, shr_imm32:$imm, pred:$p=
)>;
+def : NEONInstAlias<"vsli${p}.64 $Vdm, $imm",
+                    (VSLIv2i64 QPR:$Vdm, QPR:$Vdm, shr_imm64:$imm, pred:$p=
)>;
+
+// VSWP allows, but does not require, a type suffix.
+defm : NEONDTAnyInstAlias<"vswp${p}", "$Vd, $Vm",
+                         (VSWPd DPR:$Vd, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vswp${p}", "$Vd, $Vm",
+                         (VSWPq QPR:$Vd, QPR:$Vm, pred:$p)>;
+
+// VBIF, VBIT, and VBSL allow, but do not require, a type suffix.
+defm : NEONDTAnyInstAlias<"vbif${p}", "$Vd, $Vn, $Vm",
+                         (VBIFd DPR:$Vd, DPR:$Vn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vbit${p}", "$Vd, $Vn, $Vm",
+                         (VBITd DPR:$Vd, DPR:$Vn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vbsl${p}", "$Vd, $Vn, $Vm",
+                         (VBSLd DPR:$Vd, DPR:$Vn, DPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vbif${p}", "$Vd, $Vn, $Vm",
+                         (VBIFq QPR:$Vd, QPR:$Vn, QPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vbit${p}", "$Vd, $Vn, $Vm",
+                         (VBITq QPR:$Vd, QPR:$Vn, QPR:$Vm, pred:$p)>;
+defm : NEONDTAnyInstAlias<"vbsl${p}", "$Vd, $Vn, $Vm",
+                         (VBSLq QPR:$Vd, QPR:$Vn, QPR:$Vm, pred:$p)>;
+
+// "vmov Rd, #-imm" can be handled via "vmvn".
+def : NEONInstAlias<"vmov${p}.i32 $Vd, $imm",
+                    (VMVNv2i32 DPR:$Vd, nImmVMOVI32Neg:$imm, pred:$p)>;
+def : NEONInstAlias<"vmov${p}.i32 $Vd, $imm",
+                    (VMVNv4i32 QPR:$Vd, nImmVMOVI32Neg:$imm, pred:$p)>;
+def : NEONInstAlias<"vmvn${p}.i32 $Vd, $imm",
+                    (VMOVv2i32 DPR:$Vd, nImmVMOVI32Neg:$imm, pred:$p)>;
+def : NEONInstAlias<"vmvn${p}.i32 $Vd, $imm",
+                    (VMOVv4i32 QPR:$Vd, nImmVMOVI32Neg:$imm, pred:$p)>;
+
+// 'gas' compatibility aliases for quad-word instructions. Strictly speaki=
ng,
+// these should restrict to just the Q register variants, but the register
+// classes are enough to match correctly regardless, so we keep it simple
+// and just use MnemonicAlias.
+def : NEONMnemonicAlias<"vbicq", "vbic">;
+def : NEONMnemonicAlias<"vandq", "vand">;
+def : NEONMnemonicAlias<"veorq", "veor">;
+def : NEONMnemonicAlias<"vorrq", "vorr">;
+
+def : NEONMnemonicAlias<"vmovq", "vmov">;
+def : NEONMnemonicAlias<"vmvnq", "vmvn">;
+// Explicit versions for floating point so that the FPImm variants get
+// handled early. The parser gets confused otherwise.
+def : NEONMnemonicAlias<"vmovq.f32", "vmov.f32">;
+def : NEONMnemonicAlias<"vmovq.f64", "vmov.f64">;
+
+def : NEONMnemonicAlias<"vaddq", "vadd">;
+def : NEONMnemonicAlias<"vsubq", "vsub">;
+
+def : NEONMnemonicAlias<"vminq", "vmin">;
+def : NEONMnemonicAlias<"vmaxq", "vmax">;
+
+def : NEONMnemonicAlias<"vmulq", "vmul">;
+
+def : NEONMnemonicAlias<"vabsq", "vabs">;
+
+def : NEONMnemonicAlias<"vshlq", "vshl">;
+def : NEONMnemonicAlias<"vshrq", "vshr">;
+
+def : NEONMnemonicAlias<"vcvtq", "vcvt">;
+
+def : NEONMnemonicAlias<"vcleq", "vcle">;
+def : NEONMnemonicAlias<"vceqq", "vceq">;
+
+def : NEONMnemonicAlias<"vzipq", "vzip">;
+def : NEONMnemonicAlias<"vswpq", "vswp">;
+
+def : NEONMnemonicAlias<"vrecpeq.f32", "vrecpe.f32">;
+def : NEONMnemonicAlias<"vrecpeq.u32", "vrecpe.u32">;
+
+
+// Alias for loading floating point immediates that aren't representable
+// using the vmov.f32 encoding but the bitpattern is representable using
+// the .i32 encoding.
+def : NEONInstAlias<"vmov${p}.f32 $Vd, $imm",
+                     (VMOVv4i32 QPR:$Vd, nImmVMOVI32:$imm, pred:$p)>;
+def : NEONInstAlias<"vmov${p}.f32 $Vd, $imm",
+                     (VMOVv2i32 DPR:$Vd, nImmVMOVI32:$imm, pred:$p)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strThumb.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrThumb.td	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrThumb.td	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMInstrThumb.td - Thumb support for ARM ------------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMInstrThumb.td - Thumb support for ARM -----------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -91,6 +91,12 @@
   let ParserMatchClass =3D t_imm0_508s4_asmoperand;
   let OperandType =3D "OPERAND_IMMEDIATE";
 }
+// Alias use only, so no printer is necessary.
+def t_imm0_508s4_neg_asmoperand: AsmOperandClass { let Name =3D "Imm0_508s=
4Neg"; }
+def t_imm0_508s4_neg : Operand<i32> {
+  let ParserMatchClass =3D t_imm0_508s4_neg_asmoperand;
+  let OperandType =3D "OPERAND_IMMEDIATE";
+}
=20
 // Define Thumb specific addressing modes.
=20
@@ -345,6 +351,11 @@
   let DecoderMethod =3D "DecodeThumbAddSPImm";
 }
=20
+def : tInstAlias<"add${p} sp, $imm",
+                 (tSUBspi SP, t_imm0_508s4_neg:$imm, pred:$p)>;
+def : tInstAlias<"add${p} sp, sp, $imm",
+                 (tSUBspi SP, t_imm0_508s4_neg:$imm, pred:$p)>;
+
 // Can optionally specify SP as a three operand instruction.
 def : tInstAlias<"add${p} sp, sp, $imm",
                  (tADDspi SP, t_imm0_508s4:$imm, pred:$p)>;
@@ -387,6 +398,7 @@
     bits<4> Rm;
     let Inst{6-3} =3D Rm;
     let Inst{2-0} =3D 0b000;
+    let Unpredictable{2-0} =3D 0b111;
   }
 }
=20
@@ -404,15 +416,13 @@
 // prevent stack-pointer assignments that appear immediately before calls =
from
 // potentially appearing dead.
 let isCall =3D 1,
-  // On non-Darwin platforms R9 is callee-saved.
-  Defs =3D [R0,  R1,  R2,  R3,  R12, LR, QQQQ0, QQQQ2, QQQQ3, CPSR, FPSCR],
-  Uses =3D [SP] in {
+  Defs =3D [LR], Uses =3D [SP] in {
   // Also used for Thumb2
   def tBL  : TIx2<0b11110, 0b11, 1,
                   (outs), (ins pred:$p, t_bltarget:$func, variable_ops), I=
IC_Br,
                   "bl${p}\t$func",
                   [(ARMtcall tglobaladdr:$func)]>,
-             Requires<[IsThumb, IsNotDarwin]> {
+             Requires<[IsThumb]> {
     bits<22> func;
     let Inst{26} =3D func{21};
     let Inst{25-16} =3D func{20-11};
@@ -426,7 +436,7 @@
                  (outs), (ins pred:$p, t_blxtarget:$func, variable_ops), I=
IC_Br,
                    "blx${p}\t$func",
                    [(ARMcall tglobaladdr:$func)]>,
-              Requires<[IsThumb, HasV5T, IsNotDarwin]> {
+              Requires<[IsThumb, HasV5T]> {
     bits<21> func;
     let Inst{25-16} =3D func{20-11};
     let Inst{13} =3D 1;
@@ -439,7 +449,7 @@
   def tBLXr : TI<(outs), (ins pred:$p, GPR:$func, variable_ops), IIC_Br,
                   "blx${p}\t$func",
                   [(ARMtcall GPR:$func)]>,
-              Requires<[IsThumb, HasV5T, IsNotDarwin]>,
+              Requires<[IsThumb, HasV5T]>,
               T1Special<{1,1,1,?}> { // A6.2.3 & A8.6.24;
     bits<4> func;
     let Inst{6-3} =3D func;
@@ -450,38 +460,7 @@
   def tBX_CALL : tPseudoInst<(outs), (ins tGPR:$func, variable_ops),
                   4, IIC_Br,
                   [(ARMcall_nolink tGPR:$func)]>,
-            Requires<[IsThumb, IsThumb1Only, IsNotDarwin]>;
-}
-
-let isCall =3D 1,
-  // On Darwin R9 is call-clobbered.
-  // R7 is marked as a use to prevent frame-pointer assignments from being
-  // moved above / below calls.
-  Defs =3D [R0,  R1,  R2,  R3,  R9,  R12, LR, QQQQ0, QQQQ2, QQQQ3, CPSR, F=
PSCR],
-  Uses =3D [R7, SP] in {
-  // Also used for Thumb2
-  def tBLr9 : tPseudoExpand<(outs), (ins pred:$p, t_bltarget:$func, variab=
le_ops),
-                          4, IIC_Br, [(ARMtcall tglobaladdr:$func)],
-                          (tBL pred:$p, t_bltarget:$func)>,
-              Requires<[IsThumb, IsDarwin]>;
-
-  // ARMv5T and above, also used for Thumb2
-  def tBLXi_r9 : tPseudoExpand<(outs), (ins pred:$p, t_blxtarget:$func, va=
riable_ops),
-                      4, IIC_Br, [(ARMcall tglobaladdr:$func)],
-                      (tBLXi pred:$p, t_blxtarget:$func)>,
-                 Requires<[IsThumb, HasV5T, IsDarwin]>;
-
-  // Also used for Thumb2
-  def tBLXr_r9 : tPseudoExpand<(outs), (ins pred:$p, GPR:$func, variable_o=
ps),
-                    2, IIC_Br, [(ARMtcall GPR:$func)],
-                    (tBLXr pred:$p, GPR:$func)>,
-                 Requires<[IsThumb, HasV5T, IsDarwin]>;
-
-  // ARMv4T
-  def tBXr9_CALL : tPseudoInst<(outs), (ins tGPR:$func, variable_ops),
-                   4, IIC_Br,
-                   [(ARMcall_nolink tGPR:$func)]>,
-              Requires<[IsThumb, IsThumb1Only, IsDarwin]>;
+            Requires<[IsThumb, IsThumb1Only]>;
 }
=20
 let isBranch =3D 1, isTerminator =3D 1, isBarrier =3D 1 in {
@@ -523,28 +502,22 @@
=20
 // Tail calls
 let isCall =3D 1, isTerminator =3D 1, isReturn =3D 1, isBarrier =3D 1 in {
-  // Darwin versions.
-  let Defs =3D [R0, R1, R2, R3, R9, R12, QQQQ0, QQQQ2, QQQQ3, PC],
-      Uses =3D [SP] in {
-    // tTAILJMPd: Darwin version uses a Thumb2 branch (no Thumb1 tail calls
-    // on Darwin), so it's in ARMInstrThumb2.td.
+  // IOS versions.
+  let Uses =3D [SP] in {
     def tTAILJMPr : tPseudoExpand<(outs), (ins tcGPR:$dst, variable_ops),
                      4, IIC_Br, [],
                      (tBX GPR:$dst, (ops 14, zero_reg))>,
-                     Requires<[IsThumb, IsDarwin]>;
+                     Requires<[IsThumb]>;
   }
-  // Non-Darwin versions (the difference is R9).
-  let Defs =3D [R0, R1, R2, R3, R12, QQQQ0, QQQQ2, QQQQ3, PC],
-      Uses =3D [SP] in {
+  // tTAILJMPd: IOS version uses a Thumb2 branch (no Thumb1 tail calls
+  // on IOS), so it's in ARMInstrThumb2.td.
+  // Non-IOS version:
+  let Uses =3D [SP] in {
     def tTAILJMPdND : tPseudoExpand<(outs),
                    (ins t_brtarget:$dst, pred:$p, variable_ops),
                    4, IIC_Br, [],
                    (tB t_brtarget:$dst, pred:$p)>,
-                 Requires<[IsThumb, IsNotDarwin]>;
-    def tTAILJMPrND : tPseudoExpand<(outs), (ins tcGPR:$dst, variable_ops),
-                     4, IIC_Br, [],
-                     (tBX GPR:$dst, (ops 14, zero_reg))>,
-                     Requires<[IsThumb, IsNotDarwin]>;
+                 Requires<[IsThumb, IsNotIOS]>;
   }
 }
=20
@@ -652,7 +625,7 @@
 }
=20
 // Load tconstpool
-// FIXME: Use ldr.n to work around a Darwin assembler bug.
+// FIXME: Use ldr.n to work around a darwin assembler bug.
 let canFoldAsLoad =3D 1, isReMaterializable =3D 1, isCodeGenOnly =3D 1 in
 def tLDRpci : T1pIs<(outs tGPR:$Rt), (ins t_addrmode_pc:$addr), IIC_iLoad_=
i,
                   "ldr", ".n\t$Rt, $addr",
@@ -666,10 +639,9 @@
 }
=20
 // FIXME: Remove this entry when the above ldr.n workaround is fixed.
-// For disassembly use only.
-def tLDRpciDIS : T1pIs<(outs tGPR:$Rt), (ins t_addrmode_pc:$addr), IIC_iLo=
ad_i,
-                       "ldr", "\t$Rt, $addr",
-                       [/* disassembly only */]>,
+// For assembly/disassembly use only.
+def tLDRpciASM : T1pIs<(outs tGPR:$Rt), (ins t_addrmode_pc:$addr), IIC_iLo=
ad_i,
+                       "ldr", "\t$Rt, $addr", []>,
                  T1Encoding<{0,1,0,0,1,?}> {
   // A6.2 & A8.6.59
   bits<3> Rt;
@@ -1131,9 +1103,6 @@
                "rsb", "\t$Rd, $Rn, #0",
                [(set tGPR:$Rd, (ineg tGPR:$Rn))]>;
=20
-def : tInstAlias<"neg${s}${p} $Rd, $Rm",
-                 (tRSB tGPR:$Rd, s_cc_out:$s, tGPR:$Rm, pred:$p)>;
-
 // Subtract with carry register
 let Uses =3D [CPSR] in
 def tSBC :                      // A8.6.151
@@ -1259,19 +1228,24 @@
 // preserve all of the callee-saved resgisters, which is exactly what we w=
ant.
 // $val is a scratch register for our use.
 let Defs =3D [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7, R12, CPSR ],
-    hasSideEffects =3D 1, isBarrier =3D 1, isCodeGenOnly =3D 1 in
+    hasSideEffects =3D 1, isBarrier =3D 1, isCodeGenOnly =3D 1,
+    usesCustomInserter =3D 1 in
 def tInt_eh_sjlj_setjmp : ThumbXI<(outs),(ins tGPR:$src, tGPR:$val),
                                   AddrModeNone, 0, NoItinerary, "","",
                           [(set R0, (ARMeh_sjlj_setjmp tGPR:$src, tGPR:$va=
l))]>;
=20
-// FIXME: Non-Darwin version(s)
+// FIXME: Non-IOS version(s)
 let isBarrier =3D 1, hasSideEffects =3D 1, isTerminator =3D 1, isCodeGenOn=
ly =3D 1,
     Defs =3D [ R7, LR, SP ] in
 def tInt_eh_sjlj_longjmp : XI<(outs), (ins GPR:$src, GPR:$scratch),
                               AddrModeNone, 0, IndexModeNone,
                               Pseudo, NoItinerary, "", "",
                               [(ARMeh_sjlj_longjmp GPR:$src, GPR:$scratch)=
]>,
-                             Requires<[IsThumb, IsDarwin]>;
+                             Requires<[IsThumb, IsIOS]>;
+
+let Defs =3D [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7, R12, CPSR ],
+    isBarrier =3D 1 in
+def tInt_eh_sjlj_dispatchsetup : PseudoInst<(outs), (ins), NoItinerary, []=
>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Non-Instruction Patterns
@@ -1309,20 +1283,14 @@
=20
 // Direct calls
 def : T1Pat<(ARMtcall texternalsym:$func), (tBL texternalsym:$func)>,
-      Requires<[IsThumb, IsNotDarwin]>;
-def : T1Pat<(ARMtcall texternalsym:$func), (tBLr9 texternalsym:$func)>,
-      Requires<[IsThumb, IsDarwin]>;
+      Requires<[IsThumb]>;
=20
 def : Tv5Pat<(ARMcall texternalsym:$func), (tBLXi texternalsym:$func)>,
-      Requires<[IsThumb, HasV5T, IsNotDarwin]>;
-def : Tv5Pat<(ARMcall texternalsym:$func), (tBLXi_r9 texternalsym:$func)>,
-      Requires<[IsThumb, HasV5T, IsDarwin]>;
+      Requires<[IsThumb, HasV5T]>;
=20
 // Indirect calls to ARM routines
 def : Tv5Pat<(ARMcall GPR:$dst), (tBLXr GPR:$dst)>,
-      Requires<[IsThumb, HasV5T, IsNotDarwin]>;
-def : Tv5Pat<(ARMcall GPR:$dst), (tBLXr_r9 GPR:$dst)>,
-      Requires<[IsThumb, HasV5T, IsDarwin]>;
+      Requires<[IsThumb, HasV5T]>;
=20
 // zextload i1 -> zextload i8
 def : T1Pat<(zextloadi1 t_addrmode_rrs1:$addr),
@@ -1434,3 +1402,16 @@
 // nothing).
 def : tInstAlias<"cps$imod", (tCPS imod_op:$imod, 0)>;
 def : tInstAlias<"cps$imod", (tCPS imod_op:$imod, 0)>;
+
+// "neg" is and alias for "rsb rd, rn, #0"
+def : tInstAlias<"neg${s}${p} $Rd, $Rm",
+                 (tRSB tGPR:$Rd, s_cc_out:$s, tGPR:$Rm, pred:$p)>;
+
+
+// Implied destination operand forms for shifts.
+def : tInstAlias<"lsl${s}${p} $Rdm, $imm",
+             (tLSLri tGPR:$Rdm, cc_out:$s, tGPR:$Rdm, imm0_31:$imm, pred:$=
p)>;
+def : tInstAlias<"lsr${s}${p} $Rdm, $imm",
+             (tLSRri tGPR:$Rdm, cc_out:$s, tGPR:$Rdm, imm_sr:$imm, pred:$p=
)>;
+def : tInstAlias<"asr${s}${p} $Rdm, $imm",
+             (tASRri tGPR:$Rdm, cc_out:$s, tGPR:$Rdm, imm_sr:$imm, pred:$p=
)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strThumb2.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrThumb2.td	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrThumb2.td	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMInstrThumb2.td - Thumb2 support for ARM ------------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- ARMInstrThumb2.td - Thumb2 support for ARM ---------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -65,7 +65,7 @@
 // t2_so_imm - Match a 32-bit immediate operand, which is an
 // 8-bit immediate rotated by an arbitrary number of bits, or an 8-bit
 // immediate splatted into multiple bytes of the word.
-def t2_so_imm_asmoperand : AsmOperandClass { let Name =3D "T2SOImm"; }
+def t2_so_imm_asmoperand : ImmAsmOperand { let Name =3D "T2SOImm"; }
 def t2_so_imm : Operand<i32>, ImmLeaf<i32, [{
     return ARM_AM::getT2SOImmVal(Imm) !=3D -1;
   }]> {
@@ -76,26 +76,39 @@
=20
 // t2_so_imm_not - Match an immediate that is a complement
 // of a t2_so_imm.
-def t2_so_imm_not : Operand<i32>,
-                    PatLeaf<(imm), [{
+// Note: this pattern doesn't require an encoder method and such, as it's
+// only used on aliases (Pat<> and InstAlias<>). The actual encoding
+// is handled by the destination instructions, which use t2_so_imm.
+def t2_so_imm_not_asmoperand : AsmOperandClass { let Name =3D "T2SOImmNot"=
; }
+def t2_so_imm_not : Operand<i32>, PatLeaf<(imm), [{
   return ARM_AM::getT2SOImmVal(~((uint32_t)N->getZExtValue())) !=3D -1;
-}], t2_so_imm_not_XFORM>;
+}], t2_so_imm_not_XFORM> {
+  let ParserMatchClass =3D t2_so_imm_not_asmoperand;
+}
=20
 // t2_so_imm_neg - Match an immediate that is a negation of a t2_so_imm.
-def t2_so_imm_neg : Operand<i32>,
-                    PatLeaf<(imm), [{
-  return ARM_AM::getT2SOImmVal(-((uint32_t)N->getZExtValue())) !=3D -1;
-}], t2_so_imm_neg_XFORM>;
+def t2_so_imm_neg_asmoperand : AsmOperandClass { let Name =3D "T2SOImmNeg"=
; }
+def t2_so_imm_neg : Operand<i32>, PatLeaf<(imm), [{
+  int64_t Value =3D -(int)N->getZExtValue();
+  return Value && ARM_AM::getT2SOImmVal(Value) !=3D -1;
+}], t2_so_imm_neg_XFORM> {
+  let ParserMatchClass =3D t2_so_imm_neg_asmoperand;
+}
=20
 /// imm0_4095 predicate - True if the 32-bit immediate is in the range [0.=
4095].
-def imm0_4095 : Operand<i32>,
-                ImmLeaf<i32, [{
+def imm0_4095_asmoperand: ImmAsmOperand { let Name =3D "Imm0_4095"; }
+def imm0_4095 : Operand<i32>, ImmLeaf<i32, [{
   return Imm >=3D 0 && Imm < 4096;
-}]>;
-
-def imm0_4095_neg : PatLeaf<(i32 imm), [{
+}]> {
+  let ParserMatchClass =3D imm0_4095_asmoperand;
+}
+
+def imm0_4095_neg_asmoperand: AsmOperandClass { let Name =3D "Imm0_4095Neg=
"; }
+def imm0_4095_neg : Operand<i32>, PatLeaf<(i32 imm), [{
  return (uint32_t)(-N->getZExtValue()) < 4096;
-}], imm_neg_XFORM>;
+}], imm_neg_XFORM> {
+  let ParserMatchClass =3D imm0_4095_neg_asmoperand;
+}
=20
 def imm0_255_neg : PatLeaf<(i32 imm), [{
   return (uint32_t)(-N->getZExtValue()) < 255;
@@ -129,6 +142,12 @@
   let PrintMethod =3D "printT2LdrLabelOperand";
 }
=20
+def t2ldr_pcrel_imm12_asmoperand : AsmOperandClass {let Name =3D "MemPCRel=
Imm12";}
+def t2ldr_pcrel_imm12 : Operand<i32> {
+  let ParserMatchClass =3D t2ldr_pcrel_imm12_asmoperand;
+  // used for assembler pseudo instruction and maps to t2ldrlabel, so
+  // doesn't need encoder or print methods of its own.
+}
=20
 // ADR instruction labels.
 def t2adrlabel : Operand<i32> {
@@ -545,6 +564,11 @@
                      InstrItinClass iii, InstrItinClass iir, InstrItinClas=
s iis,
                          PatFrag opnode, string baseOpc, bit Commutable =
=3D 0> :
     T2I_bin_irs<opcod, opc, iii, iir, iis, opnode, baseOpc, Commutable, ".=
w"> {
+  // Assembler aliases w/ the ".w" suffix.
+  def : t2InstAlias<!strconcat(opc, "${s}${p}.w", " $Rd, $Rn, $imm"),
+     (!cast<Instruction>(!strconcat(baseOpc, "ri")) rGPR:$Rd, rGPR:$Rn,
+                                                    t2_so_imm:$imm, pred:$=
p,
+                                                    cc_out:$s)>;
   // Assembler aliases w/o the ".w" suffix.
   def : t2InstAlias<!strconcat(opc, "${s}${p}", " $Rd, $Rn, $Rm"),
      (!cast<Instruction>(!strconcat(baseOpc, "rr")) rGPR:$Rd, rGPR:$Rn,
@@ -556,6 +580,10 @@
                                                     cc_out:$s)>;
=20
   // and with the optional destination operand, too.
+  def : t2InstAlias<!strconcat(opc, "${s}${p}.w", " $Rdn, $imm"),
+     (!cast<Instruction>(!strconcat(baseOpc, "ri")) rGPR:$Rdn, rGPR:$Rdn,
+                                                    t2_so_imm:$imm, pred:$=
p,
+                                                    cc_out:$s)>;
   def : t2InstAlias<!strconcat(opc, "${s}${p}", " $Rdn, $Rm"),
      (!cast<Instruction>(!strconcat(baseOpc, "rr")) rGPR:$Rdn, rGPR:$Rdn,
                                                     rGPR:$Rm, pred:$p,
@@ -608,25 +636,48 @@
 ///
 /// These opcodes will be converted to the real non-S opcodes by
 /// AdjustInstrPostInstrSelection after giving then an optional CPSR opera=
nd.
-let hasPostISelHook =3D 1, isCodeGenOnly =3D 1, isPseudo =3D 1, Defs =3D [=
CPSR] in {
-multiclass T2I_bin_s_irs<bits<4> opcod, string opc,
-                     InstrItinClass iii, InstrItinClass iir, InstrItinClas=
s iis,
-                         PatFrag opnode, bit Commutable =3D 0> {
+let hasPostISelHook =3D 1, Defs =3D [CPSR] in {
+multiclass T2I_bin_s_irs<InstrItinClass iii, InstrItinClass iir,
+                         InstrItinClass iis, PatFrag opnode,
+                         bit Commutable =3D 0> {
    // shifted imm
-   def ri : T2sTwoRegImm<
-                (outs rGPR:$Rd), (ins GPR:$Rn, t2_so_imm:$imm), iii,
-                opc, ".w\t$Rd, $Rn, $imm",
-                [(set rGPR:$Rd, CPSR, (opnode GPR:$Rn, t2_so_imm:$imm))]>;
+   def ri : t2PseudoInst<(outs rGPR:$Rd),
+                         (ins GPRnopc:$Rn, t2_so_imm:$imm, pred:$p),
+                         4, iii,
+                         [(set rGPR:$Rd, CPSR, (opnode GPRnopc:$Rn,
+                                                t2_so_imm:$imm))]>;
    // register
-   def rr : T2sThreeReg<
-                (outs rGPR:$Rd), (ins GPR:$Rn, rGPR:$Rm), iir,
-                opc, ".w\t$Rd, $Rn, $Rm",
-                [(set rGPR:$Rd, CPSR, (opnode GPR:$Rn, rGPR:$Rm))]>;
+   def rr : t2PseudoInst<(outs rGPR:$Rd), (ins GPRnopc:$Rn, rGPR:$Rm, pred=
:$p),
+                         4, iir,
+                         [(set rGPR:$Rd, CPSR, (opnode GPRnopc:$Rn,
+                                                rGPR:$Rm))]> {
+     let isCommutable =3D Commutable;
+   }
    // shifted register
-   def rs : T2sTwoRegShiftedReg<
-                (outs rGPR:$Rd), (ins GPR:$Rn, t2_so_reg:$ShiftedRm), iis,
-                opc, ".w\t$Rd, $Rn, $ShiftedRm",
-               [(set rGPR:$Rd, CPSR, (opnode GPR:$Rn, t2_so_reg:$ShiftedRm=
))]>;
+   def rs : t2PseudoInst<(outs rGPR:$Rd),
+                         (ins GPRnopc:$Rn, t2_so_reg:$ShiftedRm, pred:$p),
+                         4, iis,
+                         [(set rGPR:$Rd, CPSR, (opnode GPRnopc:$Rn,
+                                                t2_so_reg:$ShiftedRm))]>;
+}
+}
+
+/// T2I_rbin_s_is -  Same as T2I_bin_s_irs, except selection DAG
+/// operands are reversed.
+let hasPostISelHook =3D 1, Defs =3D [CPSR] in {
+multiclass T2I_rbin_s_is<PatFrag opnode> {
+   // shifted imm
+   def ri : t2PseudoInst<(outs rGPR:$Rd),
+                         (ins GPRnopc:$Rn, t2_so_imm:$imm, pred:$p),
+                         4, IIC_iALUi,
+                         [(set rGPR:$Rd, CPSR, (opnode t2_so_imm:$imm,
+                                                GPRnopc:$Rn))]>;
+   // shifted register
+   def rs : t2PseudoInst<(outs rGPR:$Rd),
+                         (ins GPRnopc:$Rn, t2_so_reg:$ShiftedRm, pred:$p),
+                         4, IIC_iALUsi,
+                         [(set rGPR:$Rd, CPSR, (opnode t2_so_reg:$ShiftedR=
m,
+                                                GPRnopc:$Rn))]>;
 }
 }
=20
@@ -735,26 +786,6 @@
 }
 }
=20
-/// T2I_rbin_s_is - Same as T2I_rbin_irs except sets 's' bit and the regis=
ter
-/// version is not needed since this is only for codegen.
-///
-/// These opcodes will be converted to the real non-S opcodes by
-/// AdjustInstrPostInstrSelection after giving then an optional CPSR opera=
nd.
-let hasPostISelHook =3D 1, isCodeGenOnly =3D 1, isPseudo =3D 1, Defs =3D [=
CPSR] in {
-multiclass T2I_rbin_s_is<bits<4> opcod, string opc, PatFrag opnode> {
-   // shifted imm
-   def ri : T2sTwoRegImm<
-                (outs rGPR:$Rd), (ins rGPR:$Rn, t2_so_imm:$imm), IIC_iALUi,
-                opc, ".w\t$Rd, $Rn, $imm",
-                [(set rGPR:$Rd, CPSR, (opnode t2_so_imm:$imm, rGPR:$Rn))]>;
-   // shifted register
-   def rs : T2sTwoRegShiftedReg<
-                (outs rGPR:$Rd), (ins rGPR:$Rn, t2_so_reg:$ShiftedRm),
-                IIC_iALUsi, opc, "\t$Rd, $Rn, $ShiftedRm",
-              [(set rGPR:$Rd, CPSR, (opnode t2_so_reg:$ShiftedRm, rGPR:$Rn=
))]>;
-}
-}
-
 /// T2I_sh_ir - Defines a set of (op reg, {so_imm|r}) patterns for a shift=
 /
 //  rotate operation that produces a value.
 multiclass T2I_sh_ir<bits<2> opcod, string opc, Operand ty, PatFrag opnode,
@@ -930,7 +961,8 @@
     let DecoderMethod =3D "DecodeT2LoadShift";
   }
=20
-  // FIXME: Is the pci variant actually needed?
+  // pci variant is very similar to i12, but supports negative offsets
+  // from the PC.
   def pci : T2Ipc <(outs target:$Rt), (ins t2ldrlabel:$addr), iii,
                    opc, ".w\t$Rt, $addr",
                    [(set target:$Rt, (opnode (ARMWrapper tconstpool:$addr)=
))]> {
@@ -1315,14 +1347,16 @@
                    rGPR, BinOpFrag<(truncstorei16 node:$LHS, node:$RHS)>>;
=20
 // Store doubleword
-let mayLoad =3D 1, neverHasSideEffects =3D 1, hasExtraSrcRegAllocReq =3D 1=
 in
+let mayStore =3D 1, neverHasSideEffects =3D 1, hasExtraSrcRegAllocReq =3D =
1 in
 def t2STRDi8 : T2Ii8s4<1, 0, 0, (outs),
                        (ins GPR:$Rt, GPR:$Rt2, t2addrmode_imm8s4:$addr),
                IIC_iStore_d_r, "strd", "\t$Rt, $Rt2, $addr", "", []>;
=20
 // Indexed stores
+
+let mayStore =3D 1, neverHasSideEffects =3D 1 in {
 def t2STR_PRE  : T2Ipreldst<0, 0b10, 0, 1, (outs GPRnopc:$Rn_wb),
-                            (ins rGPR:$Rt, t2addrmode_imm8:$addr),
+                            (ins GPRnopc:$Rt, t2addrmode_imm8:$addr),
                             AddrModeT2_i8, IndexModePre, IIC_iStore_iu,
                             "str", "\t$Rt, $addr!",
                             "$addr.base =3D $Rn_wb, at earlyclobber $Rn_wb", =
[]> {
@@ -1343,15 +1377,16 @@
                         "$addr.base =3D $Rn_wb, at earlyclobber $Rn_wb", []> {
   let AsmMatchConverter =3D "cvtStWriteBackRegT2AddrModeImm8";
 }
+} // mayStore =3D 1, neverHasSideEffects =3D 1
=20
 def t2STR_POST : T2Ipostldst<0, 0b10, 0, 0, (outs GPRnopc:$Rn_wb),
-                            (ins rGPR:$Rt, addr_offset_none:$Rn,
+                            (ins GPRnopc:$Rt, addr_offset_none:$Rn,
                                  t2am_imm8_offset:$offset),
                             AddrModeT2_i8, IndexModePost, IIC_iStore_iu,
                           "str", "\t$Rt, $Rn$offset",
                           "$Rn =3D $Rn_wb, at earlyclobber $Rn_wb",
              [(set GPRnopc:$Rn_wb,
-                  (post_store rGPR:$Rt, addr_offset_none:$Rn,
+                  (post_store GPRnopc:$Rt, addr_offset_none:$Rn,
                               t2am_imm8_offset:$offset))]>;
=20
 def t2STRH_POST : T2Ipostldst<0, 0b01, 0, 0, (outs GPRnopc:$Rn_wb),
@@ -1398,7 +1433,6 @@
             (pre_truncsti16 rGPR:$Rt, GPRnopc:$Rn, t2am_imm8_offset:$offse=
t))]>;
 }
=20
-
 // STRT, STRBT, STRHT all have offset mode (PUW=3D0b110) and are for disas=
sembly
 // only.
 // Ref: A8.6.193 STR (immediate, Thumb) Encoding T4
@@ -1455,7 +1489,7 @@
                  "$addr.base =3D $wb", []>;
=20
 // T2Ipl (Preload Data/Instruction) signals the memory system of possible =
future
-// data/instruction access.  These are for disassembly only.
+// data/instruction access.
 // instr_write is inverted for Thumb mode: (prefetch 3) -> (preload 0),
 // (prefetch 1) -> (preload 2),  (prefetch 2) -> (preload 1).
 multiclass T2Ipl<bits<1> write, bits<1> instr, string opc> {
@@ -1513,6 +1547,10 @@
=20
     let DecoderMethod =3D "DecodeT2LoadShift";
   }
+  // FIXME: We should have a separate 'pci' variant here. As-is we represe=
nt
+  // it via the i12 variant, which it's related to, but that means we can
+  // represent negative immediates, which aren't legal for anything except
+  // the 'pci' case (Rn =3D=3D 15).
 }
=20
 defm t2PLD  : T2Ipl<0, 0, "pld">,  Requires<[IsThumb2]>;
@@ -1689,6 +1727,8 @@
   let Inst{14-12} =3D 0b000;
   let Inst{7-4} =3D 0b0000;
 }
+def : t2InstAlias<"mov${p}.w $Rd, $Rm", (t2MOVr GPRnopc:$Rd, GPR:$Rm,
+                                                pred:$p, zero_reg)>;
 def : t2InstAlias<"movs${p}.w $Rd, $Rm", (t2MOVr GPRnopc:$Rd, GPR:$Rm,
                                                  pred:$p, CPSR)>;
 def : t2InstAlias<"movs${p} $Rd, $Rm", (t2MOVr GPRnopc:$Rd, GPR:$Rm,
@@ -1837,11 +1877,9 @@
 // FIXME: Eliminate t2ADDS/t2SUBS pseudo opcodes after adding tablegen
 // support for an optional CPSR definition that corresponds to the DAG
 // node's second value. We can then eliminate the implicit def of CPSR.
-defm t2ADDS : T2I_bin_s_irs <0b1000, "add",
-                             IIC_iALUi, IIC_iALUr, IIC_iALUsi,
+defm t2ADDS : T2I_bin_s_irs <IIC_iALUi, IIC_iALUr, IIC_iALUsi,
                              BinOpFrag<(ARMaddc node:$LHS, node:$RHS)>, 1>;
-defm t2SUBS : T2I_bin_s_irs <0b1101, "sub",
-                             IIC_iALUi, IIC_iALUr, IIC_iALUsi,
+defm t2SUBS : T2I_bin_s_irs <IIC_iALUi, IIC_iALUr, IIC_iALUsi,
                              BinOpFrag<(ARMsubc node:$LHS, node:$RHS)>>;
=20
 let hasPostISelHook =3D 1 in {
@@ -1857,8 +1895,7 @@
=20
 // FIXME: Eliminate them if we can write def : Pat patterns which defines
 // CPSR and the implicit def of CPSR is not needed.
-defm t2RSBS : T2I_rbin_s_is <0b1110, "rsb",
-                             BinOpFrag<(ARMsubc node:$LHS, node:$RHS)>>;
+defm t2RSBS : T2I_rbin_s_is <BinOpFrag<(ARMsubc node:$LHS, node:$RHS)>>;
=20
 // (sub X, imm) gets canonicalized to (add X, -imm).  Match this form.
 // The assume-no-carry-in form uses the negation of the input since add/sub
@@ -2840,6 +2877,8 @@
 // FIXME: should be able to write a pattern for ARMcmov, but can't use
 // a two-value operand where a dag node expects two operands. :(
 let neverHasSideEffects =3D 1 in {
+
+let isCommutable =3D 1 in
 def t2MOVCCr : t2PseudoInst<(outs rGPR:$Rd),
                             (ins rGPR:$false, rGPR:$Rm, pred:$p),
                             4, IIC_iCMOVr,
@@ -2883,7 +2922,7 @@
=20
 let isMoveImm =3D 1 in
 def t2MVNCCi : T2OneRegImm<(outs rGPR:$Rd), (ins rGPR:$false, t2_so_imm:$i=
mm),
-                   IIC_iCMOVi, "mvn", ".w\t$Rd, $imm",
+                   IIC_iCMOVi, "mvn", "\t$Rd, $imm",
 [/*(set rGPR:$Rd,(ARMcmov rGPR:$false,t2_so_imm_not:$imm,
                    imm:$cc, CCR:$ccr))*/]>,
                    RegConstraint<"$false =3D $Rd"> {
@@ -2922,6 +2961,35 @@
                              IIC_iCMOVsi, "ror", ".w\t$Rd, $Rm, $imm", []>,
                  RegConstraint<"$false =3D $Rd">;
 } // isCodeGenOnly =3D 1
+
+multiclass T2I_bincc_irs<Instruction iri, Instruction irr, Instruction irs,
+                   InstrItinClass iii, InstrItinClass iir, InstrItinClass =
iis> {
+   // shifted imm
+   def ri : t2PseudoExpand<(outs rGPR:$Rd),
+                           (ins rGPR:$Rn, t2_so_imm:$imm, pred:$p, cc_out:=
$s),
+                           4, iii, [],
+                  (iri rGPR:$Rd, rGPR:$Rn, t2_so_imm:$imm, pred:$p, cc_out=
:$s)>,
+                           RegConstraint<"$Rn =3D $Rd">;
+   // register
+   def rr : t2PseudoExpand<(outs rGPR:$Rd),
+                           (ins rGPR:$Rn, rGPR:$Rm, pred:$p, cc_out:$s),
+                           4, iir, [],
+                        (irr rGPR:$Rd, rGPR:$Rn, rGPR:$Rm, pred:$p, cc_out=
:$s)>,
+                           RegConstraint<"$Rn =3D $Rd">;
+   // shifted register
+   def rs : t2PseudoExpand<(outs rGPR:$Rd),
+                       (ins rGPR:$Rn, t2_so_reg:$ShiftedRm, pred:$p, cc_ou=
t:$s),
+                           4, iis, [],
+            (irs rGPR:$Rd, rGPR:$Rn, t2_so_reg:$ShiftedRm, pred:$p, cc_out=
:$s)>,
+                           RegConstraint<"$Rn =3D $Rd">;
+} // T2I_bincc_irs
+
+defm t2ANDCC : T2I_bincc_irs<t2ANDri, t2ANDrr, t2ANDrs,
+                             IIC_iBITi, IIC_iBITr, IIC_iBITsi>;
+defm t2ORRCC : T2I_bincc_irs<t2ORRri, t2ORRrr, t2ORRrs,
+                             IIC_iBITi, IIC_iBITr, IIC_iBITsi>;
+defm t2EORCC : T2I_bincc_irs<t2EORri, t2EORrr, t2EORrs,
+                             IIC_iBITi, IIC_iBITr, IIC_iBITsi>;
 } // neverHasSideEffects
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -3043,9 +3111,7 @@
   let Inst{11-8}  =3D Rd;
   let Inst{7-0} =3D addr{7-0};
 }
-}
-
-let hasExtraSrcRegAllocReq =3D 1, Constraints =3D "@earlyclobber $Rd" in
+let hasExtraSrcRegAllocReq =3D 1 in
 def t2STREXD : T2I_strex<0b11, (outs rGPR:$Rd),
                          (ins rGPR:$Rt, rGPR:$Rt2, addr_offset_none:$addr),
                          AddrModeNone, 4, NoItinerary,
@@ -3054,6 +3120,7 @@
   bits<4> Rt2;
   let Inst{11-8} =3D Rt2;
 }
+}
=20
 def t2CLREX : T2I<(outs), (ins), NoItinerary, "clrex", "", []>,
             Requires<[IsThumb2, HasV7]>  {
@@ -3081,8 +3148,9 @@
 //   $val is a scratch register for our use.
 let Defs =3D
   [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7,  R8,  R9,  R10, R11, R12, LR, C=
PSR,
-    QQQQ0, QQQQ1, QQQQ2, QQQQ3 ],
-  hasSideEffects =3D 1, isBarrier =3D 1, isCodeGenOnly =3D 1 in {
+    Q0, Q1, Q2, Q3, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15],
+  hasSideEffects =3D 1, isBarrier =3D 1, isCodeGenOnly =3D 1,
+  usesCustomInserter =3D 1 in {
   def t2Int_eh_sjlj_setjmp : Thumb2XI<(outs), (ins tGPR:$src, tGPR:$val),
                                AddrModeNone, 0, NoItinerary, "", "",
                           [(set R0, (ARMeh_sjlj_setjmp tGPR:$src, tGPR:$va=
l))]>,
@@ -3091,7 +3159,8 @@
=20
 let Defs =3D
   [ R0,  R1,  R2,  R3,  R4,  R5,  R6,  R7,  R8,  R9,  R10, R11, R12, LR, C=
PSR ],
-  hasSideEffects =3D 1, isBarrier =3D 1, isCodeGenOnly =3D 1 in {
+  hasSideEffects =3D 1, isBarrier =3D 1, isCodeGenOnly =3D 1,
+  usesCustomInserter =3D 1 in {
   def t2Int_eh_sjlj_setjmp_nofp : Thumb2XI<(outs), (ins tGPR:$src, tGPR:$v=
al),
                                AddrModeNone, 0, NoItinerary, "", "",
                           [(set R0, (ARMeh_sjlj_setjmp tGPR:$src, tGPR:$va=
l))]>,
@@ -3128,6 +3197,7 @@
   let Inst{13} =3D target{17};
   let Inst{21-16} =3D target{16-11};
   let Inst{10-0} =3D target{10-0};
+  let DecoderMethod =3D "DecodeT2BInstruction";
 }
=20
 let isNotDuplicable =3D 1, isIndirectBranch =3D 1 in {
@@ -3195,19 +3265,32 @@
   let DecoderMethod =3D "DecodeThumb2BCCInstruction";
 }
=20
-// Tail calls. The Darwin version of thumb tail calls uses a t2 branch, so
+// Tail calls. The IOS version of thumb tail calls uses a t2 branch, so
 // it goes here.
 let isCall =3D 1, isTerminator =3D 1, isReturn =3D 1, isBarrier =3D 1 in {
-  // Darwin version.
-  let Defs =3D [R0, R1, R2, R3, R9, R12, QQQQ0, QQQQ2, QQQQ3, PC],
-      Uses =3D [SP] in
+  // IOS version.
+  let Uses =3D [SP] in
   def tTAILJMPd: tPseudoExpand<(outs),
                    (ins uncondbrtarget:$dst, pred:$p, variable_ops),
                    4, IIC_Br, [],
                    (t2B uncondbrtarget:$dst, pred:$p)>,
-                 Requires<[IsThumb2, IsDarwin]>;
+                 Requires<[IsThumb2, IsIOS]>;
 }
=20
+let isCall =3D 1, Defs =3D [LR], Uses =3D [SP] in {
+  // mov lr, pc; b if callee is marked noreturn to avoid confusing the
+  // return stack predictor.
+  def t2BMOVPCB_CALL : tPseudoInst<(outs),
+                                   (ins t_bltarget:$func, variable_ops),
+                               6, IIC_Br, [(ARMcall_nolink tglobaladdr:$fu=
nc)]>,
+                        Requires<[IsThumb]>;
+}
+
+// Direct calls
+def : T2Pat<(ARMcall_nolink texternalsym:$func),
+            (t2BMOVPCB_CALL texternalsym:$func)>,
+      Requires<[IsThumb]>;
+
 // IT block
 let Defs =3D [ITSTATE] in
 def t2IT : Thumb2XI<(outs), (ins it_pred:$cc, it_mask:$mask),
@@ -3430,7 +3513,7 @@
                                            imm:$cp))]>,
                Requires<[IsThumb2]>;
=20
-// Pseudo isntruction that combines movs + predicated rsbmi=20
+// Pseudo isntruction that combines movs + predicated rsbmi
 // to implement integer ABS
 let usesCustomInserter =3D 1, Defs =3D [CPSR] in {
 def t2ABS : PseudoInst<(outs rGPR:$dst), (ins rGPR:$src),
@@ -3667,20 +3750,32 @@
                 c_imm:$CRm, imm0_7:$opc2),
            [(int_arm_mcr imm:$cop, imm:$opc1, GPR:$Rt, imm:$CRn,
                          imm:$CRm, imm:$opc2)]>;
+def : t2InstAlias<"mcr $cop, $opc1, $Rt, $CRn, $CRm",
+                  (t2MCR p_imm:$cop, imm0_7:$opc1, GPR:$Rt, c_imm:$CRn,
+                         c_imm:$CRm, 0)>;
 def t2MCR2 : t2MovRCopro<0b1111, "mcr2", 0,
              (outs), (ins p_imm:$cop, imm0_7:$opc1, GPR:$Rt, c_imm:$CRn,
                           c_imm:$CRm, imm0_7:$opc2),
              [(int_arm_mcr2 imm:$cop, imm:$opc1, GPR:$Rt, imm:$CRn,
                             imm:$CRm, imm:$opc2)]>;
+def : t2InstAlias<"mcr2 $cop, $opc1, $Rt, $CRn, $CRm",
+                  (t2MCR2 p_imm:$cop, imm0_7:$opc1, GPR:$Rt, c_imm:$CRn,
+                          c_imm:$CRm, 0)>;
=20
 /* from coprocessor to ARM core register */
 def t2MRC : t2MovRCopro<0b1110, "mrc", 1,
              (outs GPR:$Rt), (ins p_imm:$cop, imm0_7:$opc1, c_imm:$CRn,
                                   c_imm:$CRm, imm0_7:$opc2), []>;
+def : t2InstAlias<"mrc $cop, $opc1, $Rt, $CRn, $CRm",
+                  (t2MRC GPR:$Rt, p_imm:$cop, imm0_7:$opc1, c_imm:$CRn,
+                         c_imm:$CRm, 0)>;
=20
 def t2MRC2 : t2MovRCopro<0b1111, "mrc2", 1,
              (outs GPR:$Rt), (ins p_imm:$cop, imm0_7:$opc1, c_imm:$CRn,
                                   c_imm:$CRm, imm0_7:$opc2), []>;
+def : t2InstAlias<"mrc2 $cop, $opc1, $Rt, $CRn, $CRm",
+                  (t2MRC2 GPR:$Rt, p_imm:$cop, imm0_7:$opc1, c_imm:$CRn,
+                          c_imm:$CRm, 0)>;
=20
 def : T2v6Pat<(int_arm_mrc  imm:$cop, imm:$opc1, imm:$CRn, imm:$CRm, imm:$=
opc2),
               (t2MRC imm:$cop, imm:$opc1, imm:$CRn, imm:$CRm, imm:$opc2)>;
@@ -3851,6 +3946,29 @@
 def : t2InstAlias<"add${s}${p} $Rd, $Rn, $ShiftedRm",
                   (t2ADDrs GPRnopc:$Rd, GPRnopc:$Rn, t2_so_reg:$ShiftedRm,
                            pred:$p, cc_out:$s)>;
+// ... and with the destination and source register combined.
+def : t2InstAlias<"add${s}${p} $Rdn, $imm",
+      (t2ADDri GPRnopc:$Rdn, GPRnopc:$Rdn, t2_so_imm:$imm, pred:$p, cc_out=
:$s)>;
+def : t2InstAlias<"add${p} $Rdn, $imm",
+           (t2ADDri12 GPRnopc:$Rdn, GPRnopc:$Rdn, imm0_4095:$imm, pred:$p)=
>;
+def : t2InstAlias<"add${s}${p} $Rdn, $Rm",
+            (t2ADDrr GPRnopc:$Rdn, GPRnopc:$Rdn, rGPR:$Rm, pred:$p, cc_out=
:$s)>;
+def : t2InstAlias<"add${s}${p} $Rdn, $ShiftedRm",
+                  (t2ADDrs GPRnopc:$Rdn, GPRnopc:$Rdn, t2_so_reg:$ShiftedR=
m,
+                           pred:$p, cc_out:$s)>;
+
+// add w/ negative immediates is just a sub.
+def : t2InstAlias<"add${s}${p} $Rd, $Rn, $imm",
+        (t2SUBri GPRnopc:$Rd, GPRnopc:$Rn, t2_so_imm_neg:$imm, pred:$p,
+                 cc_out:$s)>;
+def : t2InstAlias<"add${p} $Rd, $Rn, $imm",
+           (t2SUBri12 GPRnopc:$Rd, GPR:$Rn, imm0_4095_neg:$imm, pred:$p)>;
+def : t2InstAlias<"add${s}${p} $Rdn, $imm",
+      (t2SUBri GPRnopc:$Rdn, GPRnopc:$Rdn, t2_so_imm_neg:$imm, pred:$p,
+               cc_out:$s)>;
+def : t2InstAlias<"add${p} $Rdn, $imm",
+           (t2SUBri12 GPRnopc:$Rdn, GPRnopc:$Rdn, imm0_4095_neg:$imm, pred=
:$p)>;
+
=20
 // Aliases for SUB without the ".w" optional width specifier.
 def : t2InstAlias<"sub${s}${p} $Rd, $Rn, $imm",
@@ -3862,6 +3980,18 @@
 def : t2InstAlias<"sub${s}${p} $Rd, $Rn, $ShiftedRm",
                   (t2SUBrs GPRnopc:$Rd, GPRnopc:$Rn, t2_so_reg:$ShiftedRm,
                            pred:$p, cc_out:$s)>;
+// ... and with the destination and source register combined.
+def : t2InstAlias<"sub${s}${p} $Rdn, $imm",
+      (t2SUBri GPRnopc:$Rdn, GPRnopc:$Rdn, t2_so_imm:$imm, pred:$p, cc_out=
:$s)>;
+def : t2InstAlias<"sub${p} $Rdn, $imm",
+           (t2SUBri12 GPRnopc:$Rdn, GPRnopc:$Rdn, imm0_4095:$imm, pred:$p)=
>;
+def : t2InstAlias<"sub${s}${p}.w $Rdn, $Rm",
+            (t2SUBrr GPRnopc:$Rdn, GPRnopc:$Rdn, rGPR:$Rm, pred:$p, cc_out=
:$s)>;
+def : t2InstAlias<"sub${s}${p} $Rdn, $Rm",
+            (t2SUBrr GPRnopc:$Rdn, GPRnopc:$Rdn, rGPR:$Rm, pred:$p, cc_out=
:$s)>;
+def : t2InstAlias<"sub${s}${p} $Rdn, $ShiftedRm",
+                  (t2SUBrs GPRnopc:$Rdn, GPRnopc:$Rdn, t2_so_reg:$ShiftedR=
m,
+                           pred:$p, cc_out:$s)>;
=20
 // Alias for compares without the ".w" optional width specifier.
 def : t2InstAlias<"cmn${p} $Rn, $Rm",
@@ -3900,7 +4030,20 @@
 def : t2InstAlias<"ldrsh${p} $Rt, $addr",
                   (t2LDRSHs rGPR:$Rt, t2addrmode_so_reg:$addr, pred:$p)>;
=20
-// Alias for MVN without the ".w" optional width specifier.
+def : t2InstAlias<"ldr${p} $Rt, $addr",
+                  (t2LDRpci GPR:$Rt, t2ldrlabel:$addr, pred:$p)>;
+def : t2InstAlias<"ldrb${p} $Rt, $addr",
+                  (t2LDRBpci rGPR:$Rt, t2ldrlabel:$addr, pred:$p)>;
+def : t2InstAlias<"ldrh${p} $Rt, $addr",
+                  (t2LDRHpci rGPR:$Rt, t2ldrlabel:$addr, pred:$p)>;
+def : t2InstAlias<"ldrsb${p} $Rt, $addr",
+                  (t2LDRSBpci rGPR:$Rt, t2ldrlabel:$addr, pred:$p)>;
+def : t2InstAlias<"ldrsh${p} $Rt, $addr",
+                  (t2LDRSHpci rGPR:$Rt, t2ldrlabel:$addr, pred:$p)>;
+
+// Alias for MVN with(out) the ".w" optional width specifier.
+def : t2InstAlias<"mvn${s}${p}.w $Rd, $imm",
+           (t2MVNi rGPR:$Rd, t2_so_imm:$imm, pred:$p, cc_out:$s)>;
 def : t2InstAlias<"mvn${s}${p} $Rd, $Rm",
            (t2MVNr rGPR:$Rd, rGPR:$Rm, pred:$p, cc_out:$s)>;
 def : t2InstAlias<"mvn${s}${p} $Rd, $ShiftedRm",
@@ -3921,6 +4064,30 @@
 def : t2InstAlias<"pop${p}.w $regs", (t2LDMIA_UPD SP, pred:$p, reglist:$re=
gs)>;
 def : t2InstAlias<"pop${p} $regs", (t2LDMIA_UPD SP, pred:$p, reglist:$regs=
)>;
=20
+// STMIA/STMIA_UPD aliases w/o the optional .w suffix
+def : t2InstAlias<"stm${p} $Rn, $regs",
+                  (t2STMIA GPR:$Rn, pred:$p, reglist:$regs)>;
+def : t2InstAlias<"stm${p} $Rn!, $regs",
+                  (t2STMIA_UPD GPR:$Rn, pred:$p, reglist:$regs)>;
+
+// LDMIA/LDMIA_UPD aliases w/o the optional .w suffix
+def : t2InstAlias<"ldm${p} $Rn, $regs",
+                  (t2LDMIA GPR:$Rn, pred:$p, reglist:$regs)>;
+def : t2InstAlias<"ldm${p} $Rn!, $regs",
+                  (t2LDMIA_UPD GPR:$Rn, pred:$p, reglist:$regs)>;
+
+// STMDB/STMDB_UPD aliases w/ the optional .w suffix
+def : t2InstAlias<"stmdb${p}.w $Rn, $regs",
+                  (t2STMDB GPR:$Rn, pred:$p, reglist:$regs)>;
+def : t2InstAlias<"stmdb${p}.w $Rn!, $regs",
+                  (t2STMDB_UPD GPR:$Rn, pred:$p, reglist:$regs)>;
+
+// LDMDB/LDMDB_UPD aliases w/ the optional .w suffix
+def : t2InstAlias<"ldmdb${p}.w $Rn, $regs",
+                  (t2LDMDB GPR:$Rn, pred:$p, reglist:$regs)>;
+def : t2InstAlias<"ldmdb${p}.w $Rn!, $regs",
+                  (t2LDMDB_UPD GPR:$Rn, pred:$p, reglist:$regs)>;
+
 // Alias for REV/REV16/REVSH without the ".w" optional width specifier.
 def : t2InstAlias<"rev${p} $Rd, $Rm", (t2REV rGPR:$Rd, rGPR:$Rm, pred:$p)>;
 def : t2InstAlias<"rev16${p} $Rd, $Rm", (t2REV16 rGPR:$Rd, rGPR:$Rm, pred:=
$p)>;
@@ -4016,3 +4183,87 @@
                   (t2SXTB16 rGPR:$Rd, rGPR:$Rm, rot_imm:$rot, pred:$p)>;
 def : t2InstAlias<"sxth${p} $Rd, $Rm$rot",
                   (t2SXTH rGPR:$Rd, rGPR:$Rm, rot_imm:$rot, pred:$p)>;
+
+
+// "mov Rd, t2_so_imm_not" can be handled via "mvn" in assembly, just like
+// for isel.
+def : t2InstAlias<"mov${p} $Rd, $imm",
+                  (t2MVNi rGPR:$Rd, t2_so_imm_not:$imm, pred:$p, zero_reg)=
>;
+def : t2InstAlias<"mvn${p} $Rd, $imm",
+                  (t2MOVi rGPR:$Rd, t2_so_imm_not:$imm, pred:$p, zero_reg)=
>;
+// Same for AND <--> BIC
+def : t2InstAlias<"bic${s}${p} $Rd, $Rn, $imm",
+                  (t2ANDri rGPR:$Rd, rGPR:$Rn, so_imm_not:$imm,
+                           pred:$p, cc_out:$s)>;
+def : t2InstAlias<"bic${s}${p} $Rdn, $imm",
+                  (t2ANDri rGPR:$Rdn, rGPR:$Rdn, so_imm_not:$imm,
+                           pred:$p, cc_out:$s)>;
+def : t2InstAlias<"and${s}${p} $Rd, $Rn, $imm",
+                  (t2BICri rGPR:$Rd, rGPR:$Rn, so_imm_not:$imm,
+                           pred:$p, cc_out:$s)>;
+def : t2InstAlias<"and${s}${p} $Rdn, $imm",
+                  (t2BICri rGPR:$Rdn, rGPR:$Rdn, so_imm_not:$imm,
+                           pred:$p, cc_out:$s)>;
+// Likewise, "add Rd, t2_so_imm_neg" -> sub
+def : t2InstAlias<"add${s}${p} $Rd, $Rn, $imm",
+                  (t2SUBri GPRnopc:$Rd, GPRnopc:$Rn, t2_so_imm_neg:$imm,
+                           pred:$p, cc_out:$s)>;
+def : t2InstAlias<"add${s}${p} $Rd, $imm",
+                  (t2SUBri GPRnopc:$Rd, GPRnopc:$Rd, t2_so_imm_neg:$imm,
+                           pred:$p, cc_out:$s)>;
+// Same for CMP <--> CMN via t2_so_imm_neg
+def : t2InstAlias<"cmp${p} $Rd, $imm",
+                  (t2CMNzri rGPR:$Rd, t2_so_imm_neg:$imm, pred:$p)>;
+def : t2InstAlias<"cmn${p} $Rd, $imm",
+                  (t2CMPri rGPR:$Rd, t2_so_imm_neg:$imm, pred:$p)>;
+
+
+// Wide 'mul' encoding can be specified with only two operands.
+def : t2InstAlias<"mul${p} $Rn, $Rm",
+                  (t2MUL rGPR:$Rn, rGPR:$Rm, rGPR:$Rn, pred:$p)>;
+
+// "neg" is and alias for "rsb rd, rn, #0"
+def : t2InstAlias<"neg${s}${p} $Rd, $Rm",
+                  (t2RSBri rGPR:$Rd, rGPR:$Rm, 0, pred:$p, cc_out:$s)>;
+
+// MOV so_reg assembler pseudos. InstAlias isn't expressive enough for
+// these, unfortunately.
+def t2MOVsi: t2AsmPseudo<"mov${p} $Rd, $shift",
+                         (ins rGPR:$Rd, t2_so_reg:$shift, pred:$p)>;
+def t2MOVSsi: t2AsmPseudo<"movs${p} $Rd, $shift",
+                          (ins rGPR:$Rd, t2_so_reg:$shift, pred:$p)>;
+
+def t2MOVsr: t2AsmPseudo<"mov${p} $Rd, $shift",
+                         (ins rGPR:$Rd, so_reg_reg:$shift, pred:$p)>;
+def t2MOVSsr: t2AsmPseudo<"movs${p} $Rd, $shift",
+                          (ins rGPR:$Rd, so_reg_reg:$shift, pred:$p)>;
+
+// ADR w/o the .w suffix
+def : t2InstAlias<"adr${p} $Rd, $addr",
+                  (t2ADR rGPR:$Rd, t2adrlabel:$addr, pred:$p)>;
+
+// LDR(literal) w/ alternate [pc, #imm] syntax.
+def t2LDRpcrel   : t2AsmPseudo<"ldr${p} $Rt, $addr",
+                         (ins GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:$=
p)>;
+def t2LDRBpcrel  : t2AsmPseudo<"ldrb${p} $Rt, $addr",
+                         (ins GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:$=
p)>;
+def t2LDRHpcrel  : t2AsmPseudo<"ldrh${p} $Rt, $addr",
+                         (ins GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:$=
p)>;
+def t2LDRSBpcrel  : t2AsmPseudo<"ldrsb${p} $Rt, $addr",
+                         (ins GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:$=
p)>;
+def t2LDRSHpcrel  : t2AsmPseudo<"ldrsh${p} $Rt, $addr",
+                         (ins GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:$=
p)>;
+    // Version w/ the .w suffix.
+def : t2InstAlias<"ldr${p}.w $Rt, $addr",
+                  (t2LDRpcrel GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:$=
p)>;
+def : t2InstAlias<"ldrb${p}.w $Rt, $addr",
+                  (t2LDRBpcrel GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:=
$p)>;
+def : t2InstAlias<"ldrh${p}.w $Rt, $addr",
+                  (t2LDRHpcrel GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred:=
$p)>;
+def : t2InstAlias<"ldrsb${p}.w $Rt, $addr",
+                  (t2LDRSBpcrel GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred=
:$p)>;
+def : t2InstAlias<"ldrsh${p}.w $Rt, $addr",
+                  (t2LDRSHpcrel GPRnopc:$Rt, t2ldr_pcrel_imm12:$addr, pred=
:$p)>;
+
+def : t2InstAlias<"add${p} $Rd, pc, $imm",
+                  (t2ADR rGPR:$Rd, imm0_4095:$imm, pred:$p)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMIn=
strVFP.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMInstrVFP.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMInstrVFP.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMInstrVFP.td - VFP support for ARM ----------------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMInstrVFP.td - VFP support for ARM ---------------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -61,6 +61,22 @@
   let ParserMatchClass =3D FPImmOperand;
 }
=20
+// The VCVT to/from fixed-point instructions encode the 'fbits' operand
+// (the number of fixed bits) differently than it appears in the assembly
+// source. It's encoded as "Size - fbits" where Size is the size of the
+// fixed-point representation (32 or 16) and fbits is the value appearing
+// in the assembly source, an integer in [0,16] or (0,32], depending on si=
ze.
+def fbits32_asm_operand : AsmOperandClass { let Name =3D "FBits32"; }
+def fbits32 : Operand<i32> {
+  let PrintMethod =3D "printFBits32";
+  let ParserMatchClass =3D fbits32_asm_operand;
+}
+
+def fbits16_asm_operand : AsmOperandClass { let Name =3D "FBits16"; }
+def fbits16 : Operand<i32> {
+  let PrintMethod =3D "printFBits16";
+  let ParserMatchClass =3D fbits16_asm_operand;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Load / store Instructions.
@@ -69,11 +85,11 @@
 let canFoldAsLoad =3D 1, isReMaterializable =3D 1 in {
=20
 def VLDRD : ADI5<0b1101, 0b01, (outs DPR:$Dd), (ins addrmode5:$addr),
-                 IIC_fpLoad64, "vldr", ".64\t$Dd, $addr",
+                 IIC_fpLoad64, "vldr", "\t$Dd, $addr",
                  [(set DPR:$Dd, (f64 (load addrmode5:$addr)))]>;
=20
 def VLDRS : ASI5<0b1101, 0b01, (outs SPR:$Sd), (ins addrmode5:$addr),
-                 IIC_fpLoad32, "vldr", ".32\t$Sd, $addr",
+                 IIC_fpLoad32, "vldr", "\t$Sd, $addr",
                  [(set SPR:$Sd, (load addrmode5:$addr))]> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd VFP
   // pipelines.
@@ -83,11 +99,11 @@
 } // End of 'let canFoldAsLoad =3D 1, isReMaterializable =3D 1 in'
=20
 def VSTRD : ADI5<0b1101, 0b00, (outs), (ins DPR:$Dd, addrmode5:$addr),
-                 IIC_fpStore64, "vstr", ".64\t$Dd, $addr",
+                 IIC_fpStore64, "vstr", "\t$Dd, $addr",
                  [(store (f64 DPR:$Dd), addrmode5:$addr)]>;
=20
 def VSTRS : ASI5<0b1101, 0b00, (outs), (ins SPR:$Sd, addrmode5:$addr),
-                 IIC_fpStore32, "vstr", ".32\t$Sd, $addr",
+                 IIC_fpStore32, "vstr", "\t$Sd, $addr",
                  [(store SPR:$Sd, addrmode5:$addr)]> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd VFP
   // pipelines.
@@ -190,6 +206,14 @@
                 Requires<[HasVFP2]>;
 def : InstAlias<"vpop${p} $r",  (VLDMSIA_UPD SP, pred:$p, spr_reglist:$r)>,
                 Requires<[HasVFP2]>;
+defm : VFPDTAnyInstAlias<"vpush${p}", "$r",
+                         (VSTMSDB_UPD SP, pred:$p, spr_reglist:$r)>;
+defm : VFPDTAnyInstAlias<"vpush${p}", "$r",
+                         (VSTMDDB_UPD SP, pred:$p, dpr_reglist:$r)>;
+defm : VFPDTAnyInstAlias<"vpop${p}", "$r",
+                         (VLDMSIA_UPD SP, pred:$p, spr_reglist:$r)>;
+defm : VFPDTAnyInstAlias<"vpop${p}", "$r",
+                         (VLDMDIA_UPD SP, pred:$p, dpr_reglist:$r)>;
=20
 // FLDMX, FSTMX - mixing S/D registers for pre-armv6 cores
=20
@@ -270,7 +294,7 @@
           (VNMULS SPR:$a, SPR:$b)>, Requires<[NoHonorSignDependentRounding=
]>;
=20
 // These are encoded as unary instructions.
-let Defs =3D [FPSCR] in {
+let Defs =3D [FPSCR_NZCV] in {
 def VCMPED : ADuI<0b11101, 0b11, 0b0100, 0b11, 0,
                   (outs), (ins DPR:$Dd, DPR:$Dm),
                   IIC_fpCMP64, "vcmpe", ".f64\t$Dd, $Dm",
@@ -299,7 +323,7 @@
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
-} // Defs =3D [FPSCR]
+} // Defs =3D [FPSCR_NZCV]
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // FP Unary Operations.
@@ -319,7 +343,7 @@
   let D =3D VFPNeonA8Domain;
 }
=20
-let Defs =3D [FPSCR] in {
+let Defs =3D [FPSCR_NZCV] in {
 def VCMPEZD : ADuI<0b11101, 0b11, 0b0101, 0b11, 0,
                    (outs), (ins DPR:$Dd),
                    IIC_fpCMP64, "vcmpe", ".f64\t$Dd, #0",
@@ -360,7 +384,7 @@
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
-} // Defs =3D [FPSCR]
+} // Defs =3D [FPSCR_NZCV]
=20
 def VCVTDS  : ASuI<0b11101, 0b11, 0b0111, 0b11, 0,
                    (outs DPR:$Dd), (ins SPR:$Sm),
@@ -790,127 +814,131 @@
 //   S32 (U=3D0, sx=3D1) -> SL
 //   U32 (U=3D1, sx=3D1) -> UL
=20
-// FIXME: Marking these as codegen only seems wrong. They are real
-//        instructions(?)
-let Constraints =3D "$a =3D $dst", isCodeGenOnly =3D 1 in {
+let Constraints =3D "$a =3D $dst" in {
=20
 // FP to Fixed-Point:
=20
-def VTOSHS : AVConv1XI<0b11101, 0b11, 0b1110, 0b1010, 0,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTSI, "vcvt", ".s16.f32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+// Single Precision register
+class AVConv1XInsS_Encode<bits<5> op1, bits<2> op2, bits<4> op3, bits<4> o=
p4, bit op5,=20
+                dag oops, dag iops, InstrItinClass itin, string opc, strin=
g asm,
+                list<dag> pattern>
+  : AVConv1XI<op1, op2, op3, op4, op5, oops, iops, itin, opc, asm, pattern=
> {
+  bits<5> dst;
+  // if dp_operation then UInt(D:Vd) else UInt(Vd:D);
+  let Inst{22} =3D dst{0};
+  let Inst{15-12} =3D dst{4-1};
+}
+
+// Double Precision register
+class AVConv1XInsD_Encode<bits<5> op1, bits<2> op2, bits<4> op3, bits<4> o=
p4, bit op5,=20
+                dag oops, dag iops, InstrItinClass itin, string opc, strin=
g asm,
+                list<dag> pattern>
+  : AVConv1XI<op1, op2, op3, op4, op5, oops, iops, itin, opc, asm, pattern=
> {
+  bits<5> dst;
+  // if dp_operation then UInt(D:Vd) else UInt(Vd:D);
+  let Inst{22} =3D dst{4};
+  let Inst{15-12} =3D dst{3-0};
+}
+
+def VTOSHS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1110, 0b1010, 0,
+                       (outs SPR:$dst), (ins SPR:$a, fbits16:$fbits),
+                 IIC_fpCVTSI, "vcvt", ".s16.f32\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VTOUHS : AVConv1XI<0b11101, 0b11, 0b1111, 0b1010, 0,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTSI, "vcvt", ".u16.f32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+def VTOUHS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1111, 0b1010, 0,
+                       (outs SPR:$dst), (ins SPR:$a, fbits16:$fbits),
+                 IIC_fpCVTSI, "vcvt", ".u16.f32\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VTOSLS : AVConv1XI<0b11101, 0b11, 0b1110, 0b1010, 1,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTSI, "vcvt", ".s32.f32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+def VTOSLS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1110, 0b1010, 1,
+                       (outs SPR:$dst), (ins SPR:$a, fbits32:$fbits),
+                 IIC_fpCVTSI, "vcvt", ".s32.f32\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VTOULS : AVConv1XI<0b11101, 0b11, 0b1111, 0b1010, 1,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTSI, "vcvt", ".u32.f32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+def VTOULS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1111, 0b1010, 1,
+                       (outs SPR:$dst), (ins SPR:$a, fbits32:$fbits),
+                 IIC_fpCVTSI, "vcvt", ".u32.f32\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VTOSHD : AVConv1XI<0b11101, 0b11, 0b1110, 0b1011, 0,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTDI, "vcvt", ".s16.f64\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VTOSHD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1110, 0b1011, 0,
+                       (outs DPR:$dst), (ins DPR:$a, fbits16:$fbits),
+                 IIC_fpCVTDI, "vcvt", ".s16.f64\t$dst, $a, $fbits", []>;
=20
-def VTOUHD : AVConv1XI<0b11101, 0b11, 0b1111, 0b1011, 0,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTDI, "vcvt", ".u16.f64\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VTOUHD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1111, 0b1011, 0,
+                       (outs DPR:$dst), (ins DPR:$a, fbits16:$fbits),
+                 IIC_fpCVTDI, "vcvt", ".u16.f64\t$dst, $a, $fbits", []>;
=20
-def VTOSLD : AVConv1XI<0b11101, 0b11, 0b1110, 0b1011, 1,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTDI, "vcvt", ".s32.f64\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VTOSLD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1110, 0b1011, 1,
+                       (outs DPR:$dst), (ins DPR:$a, fbits32:$fbits),
+                 IIC_fpCVTDI, "vcvt", ".s32.f64\t$dst, $a, $fbits", []>;
=20
-def VTOULD : AVConv1XI<0b11101, 0b11, 0b1111, 0b1011, 1,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTDI, "vcvt", ".u32.f64\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VTOULD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1111, 0b1011, 1,
+                       (outs DPR:$dst), (ins DPR:$a, fbits32:$fbits),
+                 IIC_fpCVTDI, "vcvt", ".u32.f64\t$dst, $a, $fbits", []>;
=20
 // Fixed-Point to FP:
=20
-def VSHTOS : AVConv1XI<0b11101, 0b11, 0b1010, 0b1010, 0,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTIS, "vcvt", ".f32.s16\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+def VSHTOS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1010, 0b1010, 0,
+                       (outs SPR:$dst), (ins SPR:$a, fbits16:$fbits),
+                 IIC_fpCVTIS, "vcvt", ".f32.s16\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VUHTOS : AVConv1XI<0b11101, 0b11, 0b1011, 0b1010, 0,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTIS, "vcvt", ".f32.u16\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+def VUHTOS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1011, 0b1010, 0,
+                       (outs SPR:$dst), (ins SPR:$a, fbits16:$fbits),
+                 IIC_fpCVTIS, "vcvt", ".f32.u16\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VSLTOS : AVConv1XI<0b11101, 0b11, 0b1010, 0b1010, 1,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTIS, "vcvt", ".f32.s32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+def VSLTOS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1010, 0b1010, 1,
+                       (outs SPR:$dst), (ins SPR:$a, fbits32:$fbits),
+                 IIC_fpCVTIS, "vcvt", ".f32.s32\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VULTOS : AVConv1XI<0b11101, 0b11, 0b1011, 0b1010, 1,
-                       (outs SPR:$dst), (ins SPR:$a, i32imm:$fbits),
-                 IIC_fpCVTIS, "vcvt", ".f32.u32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]> {
+def VULTOS : AVConv1XInsS_Encode<0b11101, 0b11, 0b1011, 0b1010, 1,
+                       (outs SPR:$dst), (ins SPR:$a, fbits32:$fbits),
+                 IIC_fpCVTIS, "vcvt", ".f32.u32\t$dst, $a, $fbits", []> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
 }
=20
-def VSHTOD : AVConv1XI<0b11101, 0b11, 0b1010, 0b1011, 0,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTID, "vcvt", ".f64.s16\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VSHTOD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1010, 0b1011, 0,
+                       (outs DPR:$dst), (ins DPR:$a, fbits16:$fbits),
+                 IIC_fpCVTID, "vcvt", ".f64.s16\t$dst, $a, $fbits", []>;
=20
-def VUHTOD : AVConv1XI<0b11101, 0b11, 0b1011, 0b1011, 0,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTID, "vcvt", ".f64.u16\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VUHTOD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1011, 0b1011, 0,
+                       (outs DPR:$dst), (ins DPR:$a, fbits16:$fbits),
+                 IIC_fpCVTID, "vcvt", ".f64.u16\t$dst, $a, $fbits", []>;
=20
-def VSLTOD : AVConv1XI<0b11101, 0b11, 0b1010, 0b1011, 1,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTID, "vcvt", ".f64.s32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VSLTOD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1010, 0b1011, 1,
+                       (outs DPR:$dst), (ins DPR:$a, fbits32:$fbits),
+                 IIC_fpCVTID, "vcvt", ".f64.s32\t$dst, $a, $fbits", []>;
=20
-def VULTOD : AVConv1XI<0b11101, 0b11, 0b1011, 0b1011, 1,
-                       (outs DPR:$dst), (ins DPR:$a, i32imm:$fbits),
-                 IIC_fpCVTID, "vcvt", ".f64.u32\t$dst, $a, $fbits",
-                 [/* For disassembly only; pattern left blank */]>;
+def VULTOD : AVConv1XInsD_Encode<0b11101, 0b11, 0b1011, 0b1011, 1,
+                       (outs DPR:$dst), (ins DPR:$a, fbits32:$fbits),
+                 IIC_fpCVTID, "vcvt", ".f64.u32\t$dst, $a, $fbits", []>;
=20
-} // End of 'let Constraints =3D "$a =3D $dst", isCodeGenOnly =3D 1 in'
+} // End of 'let Constraints =3D "$a =3D $dst" in'
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // FP Multiply-Accumulate Operations.
@@ -922,7 +950,7 @@
                  [(set DPR:$Dd, (fadd_mlx (fmul_su DPR:$Dn, DPR:$Dm),
                                           (f64 DPR:$Ddin)))]>,
               RegConstraint<"$Ddin =3D $Dd">,
-              Requires<[HasVFP2,UseFPVMLx]>;
+              Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
=20
 def VMLAS : ASbIn<0b11100, 0b00, 0, 0,
                   (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
@@ -930,7 +958,7 @@
                   [(set SPR:$Sd, (fadd_mlx (fmul_su SPR:$Sn, SPR:$Sm),
                                            SPR:$Sdin))]>,
               RegConstraint<"$Sdin =3D $Sd">,
-              Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx]> {
+              Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx,DontUseFusedMAC=
]> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
@@ -938,10 +966,10 @@
=20
 def : Pat<(fadd_mlx DPR:$dstin, (fmul_su DPR:$a, (f64 DPR:$b))),
           (VMLAD DPR:$dstin, DPR:$a, DPR:$b)>,
-          Requires<[HasVFP2,UseFPVMLx]>;
+          Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
 def : Pat<(fadd_mlx SPR:$dstin, (fmul_su SPR:$a, SPR:$b)),
           (VMLAS SPR:$dstin, SPR:$a, SPR:$b)>,
-          Requires<[HasVFP2,DontUseNEONForFP, UseFPVMLx]>;
+          Requires<[HasVFP2,DontUseNEONForFP, UseFPVMLx,DontUseFusedMAC]>;
=20
 def VMLSD : ADbI<0b11100, 0b00, 1, 0,
                  (outs DPR:$Dd), (ins DPR:$Ddin, DPR:$Dn, DPR:$Dm),
@@ -949,7 +977,7 @@
                  [(set DPR:$Dd, (fadd_mlx (fneg (fmul_su DPR:$Dn,DPR:$Dm)),
                                           (f64 DPR:$Ddin)))]>,
               RegConstraint<"$Ddin =3D $Dd">,
-              Requires<[HasVFP2,UseFPVMLx]>;
+              Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
=20
 def VMLSS : ASbIn<0b11100, 0b00, 1, 0,
                   (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
@@ -957,7 +985,7 @@
                   [(set SPR:$Sd, (fadd_mlx (fneg (fmul_su SPR:$Sn, SPR:$Sm=
)),
                                            SPR:$Sdin))]>,
               RegConstraint<"$Sdin =3D $Sd">,
-              Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx]> {
+              Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx,DontUseFusedMAC=
]> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
@@ -965,10 +993,10 @@
=20
 def : Pat<(fsub_mlx DPR:$dstin, (fmul_su DPR:$a, (f64 DPR:$b))),
           (VMLSD DPR:$dstin, DPR:$a, DPR:$b)>,
-          Requires<[HasVFP2,UseFPVMLx]>;
+          Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
 def : Pat<(fsub_mlx SPR:$dstin, (fmul_su SPR:$a, SPR:$b)),
           (VMLSS SPR:$dstin, SPR:$a, SPR:$b)>,
-          Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx]>;
+          Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx,DontUseFusedMAC]>;
=20
 def VNMLAD : ADbI<0b11100, 0b01, 1, 0,
                   (outs DPR:$Dd), (ins DPR:$Ddin, DPR:$Dn, DPR:$Dm),
@@ -976,7 +1004,7 @@
                   [(set DPR:$Dd,(fsub_mlx (fneg (fmul_su DPR:$Dn,DPR:$Dm)),
                                           (f64 DPR:$Ddin)))]>,
                 RegConstraint<"$Ddin =3D $Dd">,
-                Requires<[HasVFP2,UseFPVMLx]>;
+                Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
=20
 def VNMLAS : ASbI<0b11100, 0b01, 1, 0,
                   (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
@@ -984,7 +1012,7 @@
                   [(set SPR:$Sd, (fsub_mlx (fneg (fmul_su SPR:$Sn, SPR:$Sm=
)),
                                            SPR:$Sdin))]>,
                 RegConstraint<"$Sdin =3D $Sd">,
-                Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx]> {
+                Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx,DontUseFusedM=
AC]> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
@@ -992,10 +1020,10 @@
=20
 def : Pat<(fsub_mlx (fneg (fmul_su DPR:$a, (f64 DPR:$b))), DPR:$dstin),
           (VNMLAD DPR:$dstin, DPR:$a, DPR:$b)>,
-          Requires<[HasVFP2,UseFPVMLx]>;
+          Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
 def : Pat<(fsub_mlx (fneg (fmul_su SPR:$a, SPR:$b)), SPR:$dstin),
           (VNMLAS SPR:$dstin, SPR:$a, SPR:$b)>,
-          Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx]>;
+          Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx,DontUseFusedMAC]>;
=20
 def VNMLSD : ADbI<0b11100, 0b01, 0, 0,
                   (outs DPR:$Dd), (ins DPR:$Ddin, DPR:$Dn, DPR:$Dm),
@@ -1003,14 +1031,14 @@
                   [(set DPR:$Dd, (fsub_mlx (fmul_su DPR:$Dn, DPR:$Dm),
                                            (f64 DPR:$Ddin)))]>,
                RegConstraint<"$Ddin =3D $Dd">,
-               Requires<[HasVFP2,UseFPVMLx]>;
+               Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
=20
 def VNMLSS : ASbI<0b11100, 0b01, 0, 0,
                   (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
                   IIC_fpMAC32, "vnmls", ".f32\t$Sd, $Sn, $Sm",
              [(set SPR:$Sd, (fsub_mlx (fmul_su SPR:$Sn, SPR:$Sm), SPR:$Sdi=
n))]>,
                          RegConstraint<"$Sdin =3D $Sd">,
-                  Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx]> {
+                Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx,DontUseFusedM=
AC]> {
   // Some single precision VFP instructions may be executed on both NEON a=
nd
   // VFP pipelines on A8.
   let D =3D VFPNeonA8Domain;
@@ -1018,11 +1046,172 @@
=20
 def : Pat<(fsub_mlx (fmul_su DPR:$a, (f64 DPR:$b)), DPR:$dstin),
           (VNMLSD DPR:$dstin, DPR:$a, DPR:$b)>,
-          Requires<[HasVFP2,UseFPVMLx]>;
+          Requires<[HasVFP2,UseFPVMLx,DontUseFusedMAC]>;
 def : Pat<(fsub_mlx (fmul_su SPR:$a, SPR:$b), SPR:$dstin),
           (VNMLSS SPR:$dstin, SPR:$a, SPR:$b)>,
-          Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx]>;
+          Requires<[HasVFP2,DontUseNEONForFP,UseFPVMLx,DontUseFusedMAC]>;
=20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Fused FP Multiply-Accumulate Operations.
+//
+def VFMAD : ADbI<0b11101, 0b10, 0, 0,
+                 (outs DPR:$Dd), (ins DPR:$Ddin, DPR:$Dn, DPR:$Dm),
+                 IIC_fpFMAC64, "vfma", ".f64\t$Dd, $Dn, $Dm",
+                 [(set DPR:$Dd, (fadd_mlx (fmul_su DPR:$Dn, DPR:$Dm),
+                                          (f64 DPR:$Ddin)))]>,
+              RegConstraint<"$Ddin =3D $Dd">,
+              Requires<[HasVFP4,UseFusedMAC]>;
+
+def VFMAS : ASbIn<0b11101, 0b10, 0, 0,
+                  (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
+                  IIC_fpFMAC32, "vfma", ".f32\t$Sd, $Sn, $Sm",
+                  [(set SPR:$Sd, (fadd_mlx (fmul_su SPR:$Sn, SPR:$Sm),
+                                           SPR:$Sdin))]>,
+              RegConstraint<"$Sdin =3D $Sd">,
+              Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]> {
+  // Some single precision VFP instructions may be executed on both NEON a=
nd
+  // VFP pipelines.
+}
+
+def : Pat<(fadd_mlx DPR:$dstin, (fmul_su DPR:$a, (f64 DPR:$b))),
+          (VFMAD DPR:$dstin, DPR:$a, DPR:$b)>,
+          Requires<[HasVFP4,UseFusedMAC]>;
+def : Pat<(fadd_mlx SPR:$dstin, (fmul_su SPR:$a, SPR:$b)),
+          (VFMAS SPR:$dstin, SPR:$a, SPR:$b)>,
+          Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]>;
+
+// Match @llvm.fma.* intrinsics
+def : Pat<(f64 (fma DPR:$Ddin, DPR:$Dn, DPR:$Dm)),
+          (VFMAD DPR:$Ddin, DPR:$Dn, DPR:$Dm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(f32 (fma SPR:$Sdin, SPR:$Sn, SPR:$Sm)),
+          (VFMAS SPR:$Sdin, SPR:$Sn, SPR:$Sm)>,
+      Requires<[HasVFP4]>;
+
+def VFMSD : ADbI<0b11101, 0b10, 1, 0,
+                 (outs DPR:$Dd), (ins DPR:$Ddin, DPR:$Dn, DPR:$Dm),
+                 IIC_fpFMAC64, "vfms", ".f64\t$Dd, $Dn, $Dm",
+                 [(set DPR:$Dd, (fadd_mlx (fneg (fmul_su DPR:$Dn,DPR:$Dm)),
+                                          (f64 DPR:$Ddin)))]>,
+              RegConstraint<"$Ddin =3D $Dd">,
+              Requires<[HasVFP4,UseFusedMAC]>;
+
+def VFMSS : ASbIn<0b11101, 0b10, 1, 0,
+                  (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
+                  IIC_fpFMAC32, "vfms", ".f32\t$Sd, $Sn, $Sm",
+                  [(set SPR:$Sd, (fadd_mlx (fneg (fmul_su SPR:$Sn, SPR:$Sm=
)),
+                                           SPR:$Sdin))]>,
+              RegConstraint<"$Sdin =3D $Sd">,
+              Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]> {
+  // Some single precision VFP instructions may be executed on both NEON a=
nd
+  // VFP pipelines.
+}
+
+def : Pat<(fsub_mlx DPR:$dstin, (fmul_su DPR:$a, (f64 DPR:$b))),
+          (VFMSD DPR:$dstin, DPR:$a, DPR:$b)>,
+          Requires<[HasVFP4,UseFusedMAC]>;
+def : Pat<(fsub_mlx SPR:$dstin, (fmul_su SPR:$a, SPR:$b)),
+          (VFMSS SPR:$dstin, SPR:$a, SPR:$b)>,
+          Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]>;
+
+// Match @llvm.fma.* intrinsics
+// (fma (fneg x), y, z) -> (vfms x, y, z)
+def : Pat<(f64 (fma (fneg DPR:$Ddin), DPR:$Dn, DPR:$Dm)),
+          (VFMSD DPR:$Ddin, DPR:$Dn, DPR:$Dm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(f32 (fma (fneg SPR:$Sdin), SPR:$Sn, SPR:$Sm)),
+          (VFMSS SPR:$Sdin, SPR:$Sn, SPR:$Sm)>,
+      Requires<[HasVFP4]>;
+// (fneg (fma x, (fneg y), z) -> (vfms x, y, z)
+def : Pat<(fneg (f64 (fma DPR:$Ddin, (fneg DPR:$Dn), DPR:$Dm))),
+          (VFMSD DPR:$Ddin, DPR:$Dn, DPR:$Dm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(fneg (f32 (fma SPR:$Sdin, (fneg SPR:$Sn), SPR:$Sm))),
+          (VFMSS SPR:$Sdin, SPR:$Sn, SPR:$Sm)>,
+      Requires<[HasVFP4]>;
+
+def VFNMAD : ADbI<0b11101, 0b01, 1, 0,
+                  (outs DPR:$Dd), (ins DPR:$Ddin, DPR:$Dn, DPR:$Dm),
+                  IIC_fpFMAC64, "vfnma", ".f64\t$Dd, $Dn, $Dm",
+                  [(set DPR:$Dd,(fsub_mlx (fneg (fmul_su DPR:$Dn,DPR:$Dm)),
+                                          (f64 DPR:$Ddin)))]>,
+                RegConstraint<"$Ddin =3D $Dd">,
+                Requires<[HasVFP4,UseFusedMAC]>;
+
+def VFNMAS : ASbI<0b11101, 0b01, 1, 0,
+                  (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
+                  IIC_fpFMAC32, "vfnma", ".f32\t$Sd, $Sn, $Sm",
+                  [(set SPR:$Sd, (fsub_mlx (fneg (fmul_su SPR:$Sn, SPR:$Sm=
)),
+                                           SPR:$Sdin))]>,
+                RegConstraint<"$Sdin =3D $Sd">,
+                Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]> {
+  // Some single precision VFP instructions may be executed on both NEON a=
nd
+  // VFP pipelines.
+}
+
+def : Pat<(fsub_mlx (fneg (fmul_su DPR:$a, (f64 DPR:$b))), DPR:$dstin),
+          (VFNMAD DPR:$dstin, DPR:$a, DPR:$b)>,
+          Requires<[HasVFP4,UseFusedMAC]>;
+def : Pat<(fsub_mlx (fneg (fmul_su SPR:$a, SPR:$b)), SPR:$dstin),
+          (VFNMAS SPR:$dstin, SPR:$a, SPR:$b)>,
+          Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]>;
+
+// Match @llvm.fma.* intrinsics
+// (fneg (fma x, y, z)) -> (vfnma x, y, z)
+def : Pat<(fneg (fma (f64 DPR:$Ddin), (f64 DPR:$Dn), (f64 DPR:$Dm))),
+          (VFNMAD DPR:$Ddin, DPR:$Dn, DPR:$Dm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(fneg (fma (f32 SPR:$Sdin), (f32 SPR:$Sn), (f32 SPR:$Sm))),
+          (VFNMAS SPR:$Sdin, SPR:$Sn, SPR:$Sm)>,
+      Requires<[HasVFP4]>;
+// (fma (fneg x), y, (fneg z)) -> (vfnma x, y, z)
+def : Pat<(f64 (fma (fneg DPR:$Ddin), DPR:$Dn, (fneg DPR:$Dm))),
+          (VFNMAD DPR:$Ddin, DPR:$Dn, DPR:$Dm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(f32 (fma (fneg SPR:$Sdin), SPR:$Sn, (fneg SPR:$Sm))),
+          (VFNMAS SPR:$Sdin, SPR:$Sn, SPR:$Sm)>,
+      Requires<[HasVFP4]>;
+
+def VFNMSD : ADbI<0b11101, 0b01, 0, 0,
+                  (outs DPR:$Dd), (ins DPR:$Ddin, DPR:$Dn, DPR:$Dm),
+                  IIC_fpFMAC64, "vfnms", ".f64\t$Dd, $Dn, $Dm",
+                  [(set DPR:$Dd, (fsub_mlx (fmul_su DPR:$Dn, DPR:$Dm),
+                                           (f64 DPR:$Ddin)))]>,
+               RegConstraint<"$Ddin =3D $Dd">,
+               Requires<[HasVFP4,UseFusedMAC]>;
+
+def VFNMSS : ASbI<0b11101, 0b01, 0, 0,
+                  (outs SPR:$Sd), (ins SPR:$Sdin, SPR:$Sn, SPR:$Sm),
+                  IIC_fpFMAC32, "vfnms", ".f32\t$Sd, $Sn, $Sm",
+             [(set SPR:$Sd, (fsub_mlx (fmul_su SPR:$Sn, SPR:$Sm), SPR:$Sdi=
n))]>,
+                         RegConstraint<"$Sdin =3D $Sd">,
+                  Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]> {
+  // Some single precision VFP instructions may be executed on both NEON a=
nd
+  // VFP pipelines.
+}
+
+def : Pat<(fsub_mlx (fmul_su DPR:$a, (f64 DPR:$b)), DPR:$dstin),
+          (VFNMSD DPR:$dstin, DPR:$a, DPR:$b)>,
+          Requires<[HasVFP4,UseFusedMAC]>;
+def : Pat<(fsub_mlx (fmul_su SPR:$a, SPR:$b), SPR:$dstin),
+          (VFNMSS SPR:$dstin, SPR:$a, SPR:$b)>,
+          Requires<[HasVFP4,DontUseNEONForFP,UseFusedMAC]>;
+
+// Match @llvm.fma.* intrinsics
+// (fneg (fma (fneg x), y, z)) -> (vnfms x, y, z)
+def : Pat<(fneg (f64 (fma (fneg DPR:$Ddin), DPR:$Dn, DPR:$Dm))),
+          (VFNMSD DPR:$Ddin, DPR:$Dn, DPR:$Dm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(fneg (f32 (fma (fneg SPR:$Sdin), SPR:$Sn, SPR:$Sm))),
+          (VFNMSS SPR:$Sdin, SPR:$Sn, SPR:$Sm)>,
+      Requires<[HasVFP4]>;
+// (fma x, (fneg y), z) -> (vnfms x, y, z)
+def : Pat<(f64 (fma DPR:$Ddin, (fneg DPR:$Dn), DPR:$Dm)),
+          (VFNMSD DPR:$Ddin, DPR:$Dn, DPR:$Dm)>,
+      Requires<[HasVFP4]>;
+def : Pat<(f32 (fma SPR:$Sdin, (fneg SPR:$Sn), SPR:$Sm)),
+          (VFNMSS SPR:$Sdin, SPR:$Sn, SPR:$Sm)>,
+      Requires<[HasVFP4]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // FP Conditional moves.
@@ -1063,9 +1252,9 @@
=20
 // APSR is the application level alias of CPSR. This FPSCR N, Z, C, V flags
 // to APSR.
-let Defs =3D [CPSR], Uses =3D [FPSCR], Rt =3D 0b1111 /* apsr_nzcv */ in
+let Defs =3D [CPSR], Uses =3D [FPSCR_NZCV], Rt =3D 0b1111 /* apsr_nzcv */ =
in
 def FMSTAT : MovFromVFP<0b0001 /* fpscr */, (outs), (ins),
-                        "vmrs", "\tapsr_nzcv, fpscr", [(arm_fmstat)]>;
+                        "vmrs", "\tAPSR_nzcv, fpscr", [(arm_fmstat)]>;
=20
 // Application level FPSCR -> GPR
 let hasSideEffects =3D 1, Uses =3D [FPSCR] in
@@ -1079,6 +1268,10 @@
                               "vmrs", "\t$Rt, fpexc", []>;
   def VMRS_FPSID : MovFromVFP<0b0000 /* fpsid */, (outs GPR:$Rt), (ins),
                               "vmrs", "\t$Rt, fpsid", []>;
+  def VMRS_MVFR0 : MovFromVFP<0b0111 /* mvfr0 */, (outs GPR:$Rt), (ins),
+                              "vmrs", "\t$Rt, mvfr0", []>;
+  def VMRS_MVFR1 : MovFromVFP<0b0110 /* mvfr1 */, (outs GPR:$Rt), (ins),
+                              "vmrs", "\t$Rt, mvfr1", []>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1160,6 +1353,115 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Assembler aliases.
 //
+// A few mnemnoic aliases for pre-unifixed syntax. We don't guarantee to
+// support them all, but supporting at least some of the basics is
+// good to be friendly.
+def : VFP2MnemonicAlias<"flds", "vldr">;
+def : VFP2MnemonicAlias<"fldd", "vldr">;
+def : VFP2MnemonicAlias<"fmrs", "vmov">;
+def : VFP2MnemonicAlias<"fmsr", "vmov">;
+def : VFP2MnemonicAlias<"fsqrts", "vsqrt">;
+def : VFP2MnemonicAlias<"fsqrtd", "vsqrt">;
+def : VFP2MnemonicAlias<"fadds", "vadd.f32">;
+def : VFP2MnemonicAlias<"faddd", "vadd.f64">;
+def : VFP2MnemonicAlias<"fmrdd", "vmov">;
+def : VFP2MnemonicAlias<"fmrds", "vmov">;
+def : VFP2MnemonicAlias<"fmrrd", "vmov">;
+def : VFP2MnemonicAlias<"fmdrr", "vmov">;
+def : VFP2MnemonicAlias<"fmuls", "vmul.f32">;
+def : VFP2MnemonicAlias<"fmuld", "vmul.f64">;
+def : VFP2MnemonicAlias<"fnegs", "vneg.f32">;
+def : VFP2MnemonicAlias<"fnegd", "vneg.f64">;
+def : VFP2MnemonicAlias<"ftosizd", "vcvt.s32.f64">;
+def : VFP2MnemonicAlias<"ftosid", "vcvtr.s32.f64">;
+def : VFP2MnemonicAlias<"ftosizs", "vcvt.s32.f32">;
+def : VFP2MnemonicAlias<"ftosis", "vcvtr.s32.f32">;
+def : VFP2MnemonicAlias<"ftouizd", "vcvt.u32.f64">;
+def : VFP2MnemonicAlias<"ftouid", "vcvtr.u32.f64">;
+def : VFP2MnemonicAlias<"ftouizs", "vcvt.u32.f32">;
+def : VFP2MnemonicAlias<"ftouis", "vcvtr.u32.f32">;
+def : VFP2MnemonicAlias<"fsitod", "vcvt.f64.s32">;
+def : VFP2MnemonicAlias<"fsitos", "vcvt.f32.s32">;
+def : VFP2MnemonicAlias<"fuitod", "vcvt.f64.u32">;
+def : VFP2MnemonicAlias<"fuitos", "vcvt.f32.u32">;
+def : VFP2MnemonicAlias<"fsts", "vstr">;
+def : VFP2MnemonicAlias<"fstd", "vstr">;
+def : VFP2MnemonicAlias<"fmacd", "vmla.f64">;
+def : VFP2MnemonicAlias<"fmacs", "vmla.f32">;
+def : VFP2MnemonicAlias<"fcpys", "vmov.f32">;
+def : VFP2MnemonicAlias<"fcpyd", "vmov.f64">;
+def : VFP2MnemonicAlias<"fcmps", "vcmp.f32">;
+def : VFP2MnemonicAlias<"fcmpd", "vcmp.f64">;
+def : VFP2MnemonicAlias<"fdivs", "vdiv.f32">;
+def : VFP2MnemonicAlias<"fdivd", "vdiv.f64">;
+def : VFP2MnemonicAlias<"fmrx", "vmrs">;
+def : VFP2MnemonicAlias<"fmxr", "vmsr">;
+
+// Be friendly and accept the old form of zero-compare
+def : VFP2InstAlias<"fcmpzd${p} $val", (VCMPZD DPR:$val, pred:$p)>;
+def : VFP2InstAlias<"fcmpzs${p} $val", (VCMPZS SPR:$val, pred:$p)>;
+
=20
 def : VFP2InstAlias<"fmstat${p}", (FMSTAT pred:$p)>;
+def : VFP2InstAlias<"fadds${p} $Sd, $Sn, $Sm",
+                    (VADDS SPR:$Sd, SPR:$Sn, SPR:$Sm, pred:$p)>;
+def : VFP2InstAlias<"faddd${p} $Dd, $Dn, $Dm",
+                    (VADDD DPR:$Dd, DPR:$Dn, DPR:$Dm, pred:$p)>;
+def : VFP2InstAlias<"fsubs${p} $Sd, $Sn, $Sm",
+                    (VSUBS SPR:$Sd, SPR:$Sn, SPR:$Sm, pred:$p)>;
+def : VFP2InstAlias<"fsubd${p} $Dd, $Dn, $Dm",
+                    (VSUBD DPR:$Dd, DPR:$Dn, DPR:$Dm, pred:$p)>;
=20
+// No need for the size suffix on VSQRT. It's implied by the register clas=
ses.
+def : VFP2InstAlias<"vsqrt${p} $Sd, $Sm", (VSQRTS SPR:$Sd, SPR:$Sm, pred:$=
p)>;
+def : VFP2InstAlias<"vsqrt${p} $Dd, $Dm", (VSQRTD DPR:$Dd, DPR:$Dm, pred:$=
p)>;
+
+// VLDR/VSTR accept an optional type suffix.
+def : VFP2InstAlias<"vldr${p}.32 $Sd, $addr",
+                    (VLDRS SPR:$Sd, addrmode5:$addr, pred:$p)>;
+def : VFP2InstAlias<"vstr${p}.32 $Sd, $addr",
+                    (VSTRS SPR:$Sd, addrmode5:$addr, pred:$p)>;
+def : VFP2InstAlias<"vldr${p}.64 $Dd, $addr",
+                    (VLDRD DPR:$Dd, addrmode5:$addr, pred:$p)>;
+def : VFP2InstAlias<"vstr${p}.64 $Dd, $addr",
+                    (VSTRD DPR:$Dd, addrmode5:$addr, pred:$p)>;
+
+// VMUL has a two-operand form (implied destination operand)
+def : VFP2InstAlias<"vmul${p}.f64 $Dn, $Dm",
+                    (VMULD DPR:$Dn, DPR:$Dn, DPR:$Dm, pred:$p)>;
+def : VFP2InstAlias<"vmul${p}.f32 $Sn, $Sm",
+                    (VMULS SPR:$Sn, SPR:$Sn, SPR:$Sm, pred:$p)>;
+// VADD has a two-operand form (implied destination operand)
+def : VFP2InstAlias<"vadd${p}.f64 $Dn, $Dm",
+                    (VADDD DPR:$Dn, DPR:$Dn, DPR:$Dm, pred:$p)>;
+def : VFP2InstAlias<"vadd${p}.f32 $Sn, $Sm",
+                    (VADDS SPR:$Sn, SPR:$Sn, SPR:$Sm, pred:$p)>;
+// VSUB has a two-operand form (implied destination operand)
+def : VFP2InstAlias<"vsub${p}.f64 $Dn, $Dm",
+                    (VSUBD DPR:$Dn, DPR:$Dn, DPR:$Dm, pred:$p)>;
+def : VFP2InstAlias<"vsub${p}.f32 $Sn, $Sm",
+                    (VSUBS SPR:$Sn, SPR:$Sn, SPR:$Sm, pred:$p)>;
+
+// VMOV can accept optional 32-bit or less data type suffix suffix.
+def : VFP2InstAlias<"vmov${p}.8 $Rt, $Sn",
+                    (VMOVRS GPR:$Rt, SPR:$Sn, pred:$p)>;
+def : VFP2InstAlias<"vmov${p}.16 $Rt, $Sn",
+                    (VMOVRS GPR:$Rt, SPR:$Sn, pred:$p)>;
+def : VFP2InstAlias<"vmov${p}.32 $Rt, $Sn",
+                    (VMOVRS GPR:$Rt, SPR:$Sn, pred:$p)>;
+def : VFP2InstAlias<"vmov${p}.8 $Sn, $Rt",
+                    (VMOVSR SPR:$Sn, GPR:$Rt, pred:$p)>;
+def : VFP2InstAlias<"vmov${p}.16 $Sn, $Rt",
+                    (VMOVSR SPR:$Sn, GPR:$Rt, pred:$p)>;
+def : VFP2InstAlias<"vmov${p}.32 $Sn, $Rt",
+                    (VMOVSR SPR:$Sn, GPR:$Rt, pred:$p)>;
+
+def : VFP2InstAlias<"vmov${p}.f64 $Rt, $Rt2, $Dn",
+                    (VMOVRRD GPR:$Rt, GPR:$Rt2, DPR:$Dn, pred:$p)>;
+def : VFP2InstAlias<"vmov${p}.f64 $Dn, $Rt, $Rt2",
+                    (VMOVDRR DPR:$Dn, GPR:$Rt, GPR:$Rt2, pred:$p)>;
+
+// VMOVS doesn't need the .f32 to disambiguate from the NEON encoding the =
way
+// VMOVD does.
+def : VFP2InstAlias<"vmov${p} $Sd, $Sm",
+                    (VMOVS SPR:$Sd, SPR:$Sm, pred:$p)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMJI=
TInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMJITInfo.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMJITInfo.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -13,7 +13,7 @@
=20
 #define DEBUG_TYPE "jit"
 #include "ARMJITInfo.h"
-#include "ARMInstrInfo.h"
+#include "ARM.h"
 #include "ARMConstantPoolValue.h"
 #include "ARMRelocations.h"
 #include "ARMSubtarget.h"
@@ -61,7 +61,7 @@
     // concerned, so we can't just preserve the callee saved regs.
     "stmdb sp!, {r0, r1, r2, r3, lr}\n"
 #if (defined(__VFP_FP__) && !defined(__SOFTFP__))
-    "fstmfdd sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
+    "vstmdb sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
 #endif
     // The LR contains the address of the stub function on entry.
     // pass it as the argument to the C part of the callback
@@ -85,7 +85,7 @@
     //
 #if (defined(__VFP_FP__) && !defined(__SOFTFP__))
     // Restore VFP caller-saved registers.
-    "fldmfdd sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
+    "vldmia sp!, {d0, d1, d2, d3, d4, d5, d6, d7}\n"
 #endif
     //
     //      We need to exchange the values in slots 0 and 1 so we can
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMJI=
TInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMJITInfo.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMJITInfo.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMJITInfo.h - ARM implementation of the JIT interface  --*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMJITInfo.h - ARM implementation of the JIT interface  -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMLo=
adStoreOptimizer.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMLoadStoreOptimizer.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass ----*=
- C++ -*-=3D//
+//=3D=3D=3D-- ARMLoadStoreOptimizer.cpp - ARM load / store opt. pass -----=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,8 +15,8 @@
 #define DEBUG_TYPE "arm-ldst-opt"
 #include "ARM.h"
 #include "ARMBaseInstrInfo.h"
+#include "ARMBaseRegisterInfo.h"
 #include "ARMMachineFunctionInfo.h"
-#include "ARMRegisterInfo.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
@@ -32,6 +32,8 @@
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -62,6 +64,7 @@
=20
     const TargetInstrInfo *TII;
     const TargetRegisterInfo *TRI;
+    const ARMSubtarget *STI;
     ARMFunctionInfo *AFI;
     RegScavenger *RS;
     bool isThumb2;
@@ -90,7 +93,9 @@
     bool MergeOps(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
                   int Offset, unsigned Base, bool BaseKill, int Opcode,
                   ARMCC::CondCodes Pred, unsigned PredReg, unsigned Scratc=
h,
-                  DebugLoc dl, SmallVector<std::pair<unsigned, bool>, 8> &=
Regs);
+                  DebugLoc dl,
+                  ArrayRef<std::pair<unsigned, bool> > Regs,
+                  ArrayRef<unsigned> ImpDefs);
     void MergeOpsUpdate(MachineBasicBlock &MBB,
                         MemOpQueue &MemOps,
                         unsigned memOpsBegin,
@@ -141,7 +146,6 @@
     case ARM_AM::db: return ARM::LDMDB;
     case ARM_AM::ib: return ARM::LDMIB;
     }
-    break;
   case ARM::STRi12:
     ++NumSTMGened;
     switch (Mode) {
@@ -151,7 +155,6 @@
     case ARM_AM::db: return ARM::STMDB;
     case ARM_AM::ib: return ARM::STMIB;
     }
-    break;
   case ARM::t2LDRi8:
   case ARM::t2LDRi12:
     ++NumLDMGened;
@@ -160,7 +163,6 @@
     case ARM_AM::ia: return ARM::t2LDMIA;
     case ARM_AM::db: return ARM::t2LDMDB;
     }
-    break;
   case ARM::t2STRi8:
   case ARM::t2STRi12:
     ++NumSTMGened;
@@ -169,7 +171,6 @@
     case ARM_AM::ia: return ARM::t2STMIA;
     case ARM_AM::db: return ARM::t2STMDB;
     }
-    break;
   case ARM::VLDRS:
     ++NumVLDMGened;
     switch (Mode) {
@@ -177,7 +178,6 @@
     case ARM_AM::ia: return ARM::VLDMSIA;
     case ARM_AM::db: return 0; // Only VLDMSDB_UPD exists.
     }
-    break;
   case ARM::VSTRS:
     ++NumVSTMGened;
     switch (Mode) {
@@ -185,7 +185,6 @@
     case ARM_AM::ia: return ARM::VSTMSIA;
     case ARM_AM::db: return 0; // Only VSTMSDB_UPD exists.
     }
-    break;
   case ARM::VLDRD:
     ++NumVLDMGened;
     switch (Mode) {
@@ -193,7 +192,6 @@
     case ARM_AM::ia: return ARM::VLDMDIA;
     case ARM_AM::db: return 0; // Only VLDMDDB_UPD exists.
     }
-    break;
   case ARM::VSTRD:
     ++NumVSTMGened;
     switch (Mode) {
@@ -201,10 +199,7 @@
     case ARM_AM::ia: return ARM::VSTMDIA;
     case ARM_AM::db: return 0; // Only VSTMDDB_UPD exists.
     }
-    break;
   }
-
-  return 0;
 }
=20
 namespace llvm {
@@ -259,8 +254,6 @@
   case ARM::STMIB_UPD:
     return ARM_AM::ib;
   }
-
-  return ARM_AM::bad_am_submode;
 }
=20
   } // end namespace ARM_AM
@@ -291,7 +284,8 @@
                           int Offset, unsigned Base, bool BaseKill,
                           int Opcode, ARMCC::CondCodes Pred,
                           unsigned PredReg, unsigned Scratch, DebugLoc dl,
-                          SmallVector<std::pair<unsigned, bool>, 8> &Regs)=
 {
+                          ArrayRef<std::pair<unsigned, bool> > Regs,
+                          ArrayRef<unsigned> ImpDefs) {
   // Only a single register to load / store. Don't bother.
   unsigned NumRegs =3D Regs.size();
   if (NumRegs <=3D 1)
@@ -359,6 +353,10 @@
     MIB =3D MIB.addReg(Regs[i].first, getDefRegState(isDef)
                      | getKillRegState(Regs[i].second));
=20
+  // Add implicit defs for super-registers.
+  for (unsigned i =3D 0, e =3D ImpDefs.size(); i !=3D e; ++i)
+    MIB.addReg(ImpDefs[i], RegState::ImplicitDefine);
+
   return true;
 }
=20
@@ -393,19 +391,29 @@
   }
=20
   SmallVector<std::pair<unsigned, bool>, 8> Regs;
+  SmallVector<unsigned, 8> ImpDefs;
   for (unsigned i =3D memOpsBegin; i < memOpsEnd; ++i) {
     unsigned Reg =3D memOps[i].Reg;
     // If we are inserting the merged operation after an operation that
     // uses the same register, make sure to transfer any kill flag.
     bool isKill =3D memOps[i].isKill || KilledRegs.count(Reg);
     Regs.push_back(std::make_pair(Reg, isKill));
+
+    // Collect any implicit defs of super-registers. They must be preserve=
d.
+    for (MIOperands MO(memOps[i].MBBI); MO.isValid(); ++MO) {
+      if (!MO->isReg() || !MO->isDef() || !MO->isImplicit() || MO->isDead(=
))
+        continue;
+      unsigned DefReg =3D MO->getReg();
+      if (std::find(ImpDefs.begin(), ImpDefs.end(), DefReg) =3D=3D ImpDefs=
.end())
+        ImpDefs.push_back(DefReg);
+    }
   }
=20
   // Try to do the merge.
   MachineBasicBlock::iterator Loc =3D memOps[insertAfter].MBBI;
   ++Loc;
   if (!MergeOps(MBB, Loc, Offset, Base, BaseKill, Opcode,
-                Pred, PredReg, Scratch, dl, Regs))
+                Pred, PredReg, Scratch, dl, Regs, ImpDefs))
     return;
=20
   // Merge succeeded, update records.
@@ -506,50 +514,84 @@
   return;
 }
=20
-static inline bool isMatchingDecrement(MachineInstr *MI, unsigned Base,
-                                       unsigned Bytes, unsigned Limit,
-                                       ARMCC::CondCodes Pred, unsigned Pre=
dReg){
+static bool definesCPSR(MachineInstr *MI) {
+  for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
+    const MachineOperand &MO =3D MI->getOperand(i);
+    if (!MO.isReg())
+      continue;
+    if (MO.isDef() && MO.getReg() =3D=3D ARM::CPSR && !MO.isDead())
+      // If the instruction has live CPSR def, then it's not safe to fold =
it
+      // into load / store.
+      return true;
+  }
+
+  return false;
+}
+
+static bool isMatchingDecrement(MachineInstr *MI, unsigned Base,
+                                unsigned Bytes, unsigned Limit,
+                                ARMCC::CondCodes Pred, unsigned PredReg) {
   unsigned MyPredReg =3D 0;
   if (!MI)
     return false;
-  if (MI->getOpcode() !=3D ARM::t2SUBri &&
-      MI->getOpcode() !=3D ARM::tSUBspi &&
-      MI->getOpcode() !=3D ARM::SUBri)
-    return false;
+
+  bool CheckCPSRDef =3D false;
+  switch (MI->getOpcode()) {
+  default: return false;
+  case ARM::t2SUBri:
+  case ARM::SUBri:
+    CheckCPSRDef =3D true;
+  // fallthrough
+  case ARM::tSUBspi:
+    break;
+  }
=20
   // Make sure the offset fits in 8 bits.
   if (Bytes =3D=3D 0 || (Limit && Bytes >=3D Limit))
     return false;
=20
   unsigned Scale =3D (MI->getOpcode() =3D=3D ARM::tSUBspi) ? 4 : 1; // FIX=
ME
-  return (MI->getOperand(0).getReg() =3D=3D Base &&
-          MI->getOperand(1).getReg() =3D=3D Base &&
-          (MI->getOperand(2).getImm()*Scale) =3D=3D Bytes &&
-          llvm::getInstrPredicate(MI, MyPredReg) =3D=3D Pred &&
-          MyPredReg =3D=3D PredReg);
+  if (!(MI->getOperand(0).getReg() =3D=3D Base &&
+        MI->getOperand(1).getReg() =3D=3D Base &&
+        (MI->getOperand(2).getImm()*Scale) =3D=3D Bytes &&
+        getInstrPredicate(MI, MyPredReg) =3D=3D Pred &&
+        MyPredReg =3D=3D PredReg))
+    return false;
+
+  return CheckCPSRDef ? !definesCPSR(MI) : true;
 }
=20
-static inline bool isMatchingIncrement(MachineInstr *MI, unsigned Base,
-                                       unsigned Bytes, unsigned Limit,
-                                       ARMCC::CondCodes Pred, unsigned Pre=
dReg){
+static bool isMatchingIncrement(MachineInstr *MI, unsigned Base,
+                                unsigned Bytes, unsigned Limit,
+                                ARMCC::CondCodes Pred, unsigned PredReg) {
   unsigned MyPredReg =3D 0;
   if (!MI)
     return false;
-  if (MI->getOpcode() !=3D ARM::t2ADDri &&
-      MI->getOpcode() !=3D ARM::tADDspi &&
-      MI->getOpcode() !=3D ARM::ADDri)
-    return false;
+
+  bool CheckCPSRDef =3D false;
+  switch (MI->getOpcode()) {
+  default: return false;
+  case ARM::t2ADDri:
+  case ARM::ADDri:
+    CheckCPSRDef =3D true;
+  // fallthrough
+  case ARM::tADDspi:
+    break;
+  }
=20
   if (Bytes =3D=3D 0 || (Limit && Bytes >=3D Limit))
     // Make sure the offset fits in 8 bits.
     return false;
=20
   unsigned Scale =3D (MI->getOpcode() =3D=3D ARM::tADDspi) ? 4 : 1; // FIX=
ME
-  return (MI->getOperand(0).getReg() =3D=3D Base &&
-          MI->getOperand(1).getReg() =3D=3D Base &&
-          (MI->getOperand(2).getImm()*Scale) =3D=3D Bytes &&
-          llvm::getInstrPredicate(MI, MyPredReg) =3D=3D Pred &&
-          MyPredReg =3D=3D PredReg);
+  if (!(MI->getOperand(0).getReg() =3D=3D Base &&
+        MI->getOperand(1).getReg() =3D=3D Base &&
+        (MI->getOperand(2).getImm()*Scale) =3D=3D Bytes &&
+        getInstrPredicate(MI, MyPredReg) =3D=3D Pred &&
+        MyPredReg =3D=3D PredReg))
+    return false;
+
+  return CheckCPSRDef ? !definesCPSR(MI) : true;
 }
=20
 static inline unsigned getLSMultipleTransferSize(MachineInstr *MI) {
@@ -603,7 +645,6 @@
     case ARM_AM::da: return ARM::LDMDA_UPD;
     case ARM_AM::db: return ARM::LDMDB_UPD;
     }
-    break;
   case ARM::STMIA:
   case ARM::STMDA:
   case ARM::STMDB:
@@ -615,7 +656,6 @@
     case ARM_AM::da: return ARM::STMDA_UPD;
     case ARM_AM::db: return ARM::STMDB_UPD;
     }
-    break;
   case ARM::t2LDMIA:
   case ARM::t2LDMDB:
     switch (Mode) {
@@ -623,7 +663,6 @@
     case ARM_AM::ia: return ARM::t2LDMIA_UPD;
     case ARM_AM::db: return ARM::t2LDMDB_UPD;
     }
-    break;
   case ARM::t2STMIA:
   case ARM::t2STMDB:
     switch (Mode) {
@@ -631,38 +670,31 @@
     case ARM_AM::ia: return ARM::t2STMIA_UPD;
     case ARM_AM::db: return ARM::t2STMDB_UPD;
     }
-    break;
   case ARM::VLDMSIA:
     switch (Mode) {
     default: llvm_unreachable("Unhandled submode!");
     case ARM_AM::ia: return ARM::VLDMSIA_UPD;
     case ARM_AM::db: return ARM::VLDMSDB_UPD;
     }
-    break;
   case ARM::VLDMDIA:
     switch (Mode) {
     default: llvm_unreachable("Unhandled submode!");
     case ARM_AM::ia: return ARM::VLDMDIA_UPD;
     case ARM_AM::db: return ARM::VLDMDDB_UPD;
     }
-    break;
   case ARM::VSTMSIA:
     switch (Mode) {
     default: llvm_unreachable("Unhandled submode!");
     case ARM_AM::ia: return ARM::VSTMSIA_UPD;
     case ARM_AM::db: return ARM::VSTMSDB_UPD;
     }
-    break;
   case ARM::VSTMDIA:
     switch (Mode) {
     default: llvm_unreachable("Unhandled submode!");
     case ARM_AM::ia: return ARM::VSTMDIA_UPD;
     case ARM_AM::db: return ARM::VSTMDDB_UPD;
     }
-    break;
   }
-
-  return 0;
 }
=20
 /// MergeBaseUpdateLSMultiple - Fold proceeding/trailing inc/dec of base
@@ -686,7 +718,7 @@
   bool BaseKill =3D MI->getOperand(0).isKill();
   unsigned Bytes =3D getLSMultipleTransferSize(MI);
   unsigned PredReg =3D 0;
-  ARMCC::CondCodes Pred =3D llvm::getInstrPredicate(MI, PredReg);
+  ARMCC::CondCodes Pred =3D getInstrPredicate(MI, PredReg);
   int Opcode =3D MI->getOpcode();
   DebugLoc dl =3D MI->getDebugLoc();
=20
@@ -783,7 +815,6 @@
     return ARM::t2STR_PRE;
   default: llvm_unreachable("Unhandled opcode!");
   }
-  return 0;
 }
=20
 static unsigned getPostIndexedLoadStoreOpcode(unsigned Opc,
@@ -809,7 +840,6 @@
     return ARM::t2STR_POST;
   default: llvm_unreachable("Unhandled opcode!");
   }
-  return 0;
 }
=20
 /// MergeBaseUpdateLoadStore - Fold proceeding/trailing inc/dec of base
@@ -841,7 +871,7 @@
     return false;
=20
   unsigned PredReg =3D 0;
-  ARMCC::CondCodes Pred =3D llvm::getInstrPredicate(MI, PredReg);
+  ARMCC::CondCodes Pred =3D getInstrPredicate(MI, PredReg);
   bool DoMerge =3D false;
   ARM_AM::AddrOpc AddSub =3D ARM_AM::add;
   unsigned NewOpc =3D 0;
@@ -1071,11 +1101,17 @@
   unsigned Opcode =3D MI->getOpcode();
   if (Opcode =3D=3D ARM::LDRD || Opcode =3D=3D ARM::STRD ||
       Opcode =3D=3D ARM::t2LDRDi8 || Opcode =3D=3D ARM::t2STRDi8) {
+    const MachineOperand &BaseOp =3D MI->getOperand(2);
+    unsigned BaseReg =3D BaseOp.getReg();
     unsigned EvenReg =3D MI->getOperand(0).getReg();
     unsigned OddReg  =3D MI->getOperand(1).getReg();
     unsigned EvenRegNum =3D TRI->getDwarfRegNum(EvenReg, false);
     unsigned OddRegNum  =3D TRI->getDwarfRegNum(OddReg, false);
-    if ((EvenRegNum & 1) =3D=3D 0 && (EvenRegNum + 1) =3D=3D OddRegNum)
+    // ARM errata 602117: LDRD with base in list may result in incorrect b=
ase
+    // register when interrupted or faulted.
+    bool Errata602117 =3D EvenReg =3D=3D BaseReg && STI->isCortexM3();
+    if (!Errata602117 &&
+        ((EvenRegNum & 1) =3D=3D 0 && (EvenRegNum + 1) =3D=3D OddRegNum))
       return false;
=20
     MachineBasicBlock::iterator NewBBI =3D MBBI;
@@ -1087,15 +1123,13 @@
     bool OddDeadKill  =3D isLd ?
       MI->getOperand(1).isDead() : MI->getOperand(1).isKill();
     bool OddUndef =3D MI->getOperand(1).isUndef();
-    const MachineOperand &BaseOp =3D MI->getOperand(2);
-    unsigned BaseReg =3D BaseOp.getReg();
     bool BaseKill =3D BaseOp.isKill();
     bool BaseUndef =3D BaseOp.isUndef();
     bool OffKill =3D isT2 ? false : MI->getOperand(3).isKill();
     bool OffUndef =3D isT2 ? false : MI->getOperand(3).isUndef();
     int OffImm =3D getMemoryOpOffset(MI);
     unsigned PredReg =3D 0;
-    ARMCC::CondCodes Pred =3D llvm::getInstrPredicate(MI, PredReg);
+    ARMCC::CondCodes Pred =3D getInstrPredicate(MI, PredReg);
=20
     if (OddRegNum > EvenRegNum && OffImm =3D=3D 0) {
       // Ascending register numbers and no offset. It's safe to change it =
to a
@@ -1126,6 +1160,11 @@
       unsigned NewOpc =3D (isLd)
         ? (isT2 ? (OffImm < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDRi1=
2)
         : (isT2 ? (OffImm < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STRi1=
2);
+      // Be extra careful for thumb2. t2LDRi8 can't reference a zero offse=
t,
+      // so adjust and use t2LDRi12 here for that.
+      unsigned NewOpc2 =3D (isLd)
+        ? (isT2 ? (OffImm+4 < 0 ? ARM::t2LDRi8 : ARM::t2LDRi12) : ARM::LDR=
i12)
+        : (isT2 ? (OffImm+4 < 0 ? ARM::t2STRi8 : ARM::t2STRi12) : ARM::STR=
i12);
       DebugLoc dl =3D MBBI->getDebugLoc();
       // If this is a load and base register is killed, it may have been
       // re-defed by the load, make sure the first load does not clobber i=
t.
@@ -1133,11 +1172,13 @@
           (BaseKill || OffKill) &&
           (TRI->regsOverlap(EvenReg, BaseReg))) {
         assert(!TRI->regsOverlap(OddReg, BaseReg));
-        InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc,
+        InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
                       OddReg, OddDeadKill, false,
                       BaseReg, false, BaseUndef, false, OffUndef,
                       Pred, PredReg, TII, isT2);
         NewBBI =3D llvm::prior(MBBI);
+        if (isT2 && NewOpc =3D=3D ARM::t2LDRi8 && OffImm+4 >=3D 0)
+          NewOpc =3D ARM::t2LDRi12;
         InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
                       EvenReg, EvenDeadKill, false,
                       BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
@@ -1150,12 +1191,16 @@
           EvenDeadKill =3D false;
           OddDeadKill =3D true;
         }
+        // Never kill the base register in the first instruction.
+        // <rdar://problem/11101911>
+        if (EvenReg =3D=3D BaseReg)
+          EvenDeadKill =3D false;
         InsertLDR_STR(MBB, MBBI, OffImm, isLd, dl, NewOpc,
                       EvenReg, EvenDeadKill, EvenUndef,
                       BaseReg, false, BaseUndef, false, OffUndef,
                       Pred, PredReg, TII, isT2);
         NewBBI =3D llvm::prior(MBBI);
-        InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc,
+        InsertLDR_STR(MBB, MBBI, OffImm+4, isLd, dl, NewOpc2,
                       OddReg, OddDeadKill, OddUndef,
                       BaseReg, BaseKill, BaseUndef, OffKill, OffUndef,
                       Pred, PredReg, TII, isT2);
@@ -1206,7 +1251,7 @@
       bool isKill =3D MO.isDef() ? false : MO.isKill();
       unsigned Base =3D MBBI->getOperand(1).getReg();
       unsigned PredReg =3D 0;
-      ARMCC::CondCodes Pred =3D llvm::getInstrPredicate(MBBI, PredReg);
+      ARMCC::CondCodes Pred =3D getInstrPredicate(MBBI, PredReg);
       int Offset =3D getMemoryOpOffset(MBBI);
       // Watch out for:
       // r4 :=3D ldr [r5]
@@ -1380,6 +1425,7 @@
   AFI =3D Fn.getInfo<ARMFunctionInfo>();
   TII =3D TM.getInstrInfo();
   TRI =3D TM.getRegisterInfo();
+  STI =3D &TM.getSubtarget<ARMSubtarget>();
   RS =3D new RegScavenger();
   isThumb2 =3D AFI->isThumb2Function();
=20
@@ -1464,19 +1510,18 @@
   while (++I !=3D E) {
     if (I->isDebugValue() || MemOps.count(&*I))
       continue;
-    const MCInstrDesc &MCID =3D I->getDesc();
-    if (MCID.isCall() || MCID.isTerminator() || I->hasUnmodeledSideEffects=
())
+    if (I->isCall() || I->isTerminator() || I->hasUnmodeledSideEffects())
       return false;
-    if (isLd && MCID.mayStore())
+    if (isLd && I->mayStore())
       return false;
     if (!isLd) {
-      if (MCID.mayLoad())
+      if (I->mayLoad())
         return false;
       // It's not safe to move the first 'str' down.
       // str r1, [r0]
       // strh r5, [r0]
       // str r4, [r0, #+4]
-      if (MCID.mayStore())
+      if (I->mayStore())
         return false;
     }
     for (unsigned j =3D 0, NumOps =3D I->getNumOperands(); j !=3D NumOps; =
++j) {
@@ -1498,6 +1543,23 @@
   return AddedRegPressure.size() <=3D MemRegs.size() * 2;
 }
=20
+
+/// Copy Op0 and Op1 operands into a new array assigned to MI.
+static void concatenateMemOperands(MachineInstr *MI, MachineInstr *Op0,
+                                   MachineInstr *Op1) {
+  assert(MI->memoperands_empty() && "expected a new machineinstr");
+  size_t numMemRefs =3D (Op0->memoperands_end() - Op0->memoperands_begin())
+    + (Op1->memoperands_end() - Op1->memoperands_begin());
+
+  MachineFunction *MF =3D MI->getParent()->getParent();
+  MachineSDNode::mmo_iterator MemBegin =3D MF->allocateMemRefsArray(numMem=
Refs);
+  MachineSDNode::mmo_iterator MemEnd =3D
+    std::copy(Op0->memoperands_begin(), Op0->memoperands_end(), MemBegin);
+  MemEnd =3D
+    std::copy(Op1->memoperands_begin(), Op1->memoperands_end(), MemEnd);
+  MI->setMemRefs(MemBegin, MemEnd);
+}
+
 bool
 ARMPreAllocLoadStoreOpt::CanFormLdStDWord(MachineInstr *Op0, MachineInstr =
*Op1,
                                           DebugLoc &dl,
@@ -1565,7 +1627,7 @@
   if (EvenReg =3D=3D OddReg)
     return false;
   BaseReg =3D Op0->getOperand(1).getReg();
-  Pred =3D llvm::getInstrPredicate(Op0, PredReg);
+  Pred =3D getInstrPredicate(Op0, PredReg);
   dl =3D Op0->getDebugLoc();
   return true;
 }
@@ -1615,8 +1677,9 @@
         LastOp =3D Op;
       }
=20
-      unsigned Opcode =3D Op->getOpcode();
-      if (LastOpcode && Opcode !=3D LastOpcode)
+      unsigned LSMOpcode
+        =3D getLoadStoreMultipleOpcode(Op->getOpcode(), ARM_AM::ia);
+      if (LastOpcode && LSMOpcode !=3D LastOpcode)
         break;
=20
       int Offset =3D getMemoryOpOffset(Op);
@@ -1627,7 +1690,7 @@
       }
       LastOffset =3D Offset;
       LastBytes =3D Bytes;
-      LastOpcode =3D Opcode;
+      LastOpcode =3D LSMOpcode;
       if (++NumMove =3D=3D 8) // FIXME: Tune this limit.
         break;
     }
@@ -1692,6 +1755,8 @@
             if (!isT2)
               MIB.addReg(0);
             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
+            concatenateMemOperands(MIB, Op0, Op1);
+            DEBUG(dbgs() << "Formed " << *MIB << "\n");
             ++NumLDRDFormed;
           } else {
             MachineInstrBuilder MIB =3D BuildMI(*MBB, InsertPos, dl, MCID)
@@ -1704,6 +1769,8 @@
             if (!isT2)
               MIB.addReg(0);
             MIB.addImm(Offset).addImm(Pred).addReg(PredReg);
+            concatenateMemOperands(MIB, Op0, Op1);
+            DEBUG(dbgs() << "Formed " << *MIB << "\n");
             ++NumSTRDFormed;
           }
           MBB->erase(Op0);
@@ -1745,8 +1812,7 @@
   while (MBBI !=3D E) {
     for (; MBBI !=3D E; ++MBBI) {
       MachineInstr *MI =3D MBBI;
-      const MCInstrDesc &MCID =3D MI->getDesc();
-      if (MCID.isCall() || MCID.isTerminator()) {
+      if (MI->isCall() || MI->isTerminator()) {
         // Stop at barriers.
         ++MBBI;
         break;
@@ -1758,7 +1824,7 @@
       if (!isMemoryOp(MI))
         continue;
       unsigned PredReg =3D 0;
-      if (llvm::getInstrPredicate(MI, PredReg) !=3D ARMCC::AL)
+      if (getInstrPredicate(MI, PredReg) !=3D ARMCC::AL)
         continue;
=20
       int Opc =3D MI->getOpcode();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMMC=
InstLower.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMMCInstLower.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMMCInstLower.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -31,8 +31,7 @@
     Expr =3D MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
                                    OutContext);
     switch (MO.getTargetFlags()) {
-    default:
-      assert(0 && "Unknown target flag on symbol operand");
+    default: llvm_unreachable("Unknown target flag on symbol operand");
     case 0:
       break;
     case ARMII::MO_LO16:
@@ -67,9 +66,7 @@
 bool ARMAsmPrinter::lowerOperand(const MachineOperand &MO,
                                  MCOperand &MCOp) {
   switch (MO.getType()) {
-  default:
-    assert(0 && "unknown operand type");
-    return false;
+  default: llvm_unreachable("unknown operand type");
   case MachineOperand::MO_Register:
     // Ignore all non-CPSR implicit register operands.
     if (MO.isImplicit() && MO.getReg() !=3D ARM::CPSR)
@@ -107,6 +104,9 @@
     MCOp =3D MCOperand::CreateFPImm(Val.convertToDouble());
     break;
   }
+  case MachineOperand::MO_RegisterMask:
+    // Ignore call clobbers.
+    return false;
   }
   return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMMa=
chineFunctionInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMMachineFunctionInfo.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMMachineFunctionInfo.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D- ARMMachineFuctionInfo.h - ARM machine function info -----*=
- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMMachineFuctionInfo.h - ARM machine function info -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -25,6 +25,7 @@
 /// ARMFunctionInfo - This class is derived from MachineFunctionInfo and
 /// contains private ARM-specific information for each MachineFunction.
 class ARMFunctionInfo : public MachineFunctionInfo {
+  virtual void anchor();
=20
   /// isThumb - True if this function is compiled under Thumb mode.
   /// Used to initialized Align, so must precede it.
@@ -63,6 +64,9 @@
   /// GPR callee-saved (2) : r8, r10, r11
   /// --------------------------------------------
   /// DPR callee-saved : d8 - d15
+  ///
+  /// Also see AlignedDPRCSRegs below. Not all D-regs need to go in area 3.
+  /// Some may be spilled after the stack has been realigned.
   unsigned GPRCS1Offset;
   unsigned GPRCS2Offset;
   unsigned DPRCSOffset;
@@ -79,6 +83,15 @@
   BitVector GPRCS2Frames;
   BitVector DPRCSFrames;
=20
+  /// NumAlignedDPRCS2Regs - The number of callee-saved DPRs that are save=
d in
+  /// the aligned portion of the stack frame.  This is always a contiguous
+  /// sequence of D-registers starting from d8.
+  ///
+  /// We do not keep track of the frame indices used for these registers -=
 they
+  /// behave like any other frame index in the aligned stack frame.  These
+  /// registers also aren't included in DPRCSSize above.
+  unsigned NumAlignedDPRCS2Regs;
+
   /// JumpTableUId - Unique id for jumptables.
   ///
   unsigned JumpTableUId;
@@ -104,6 +117,7 @@
     FramePtrSpillOffset(0), GPRCS1Offset(0), GPRCS2Offset(0), DPRCSOffset(=
0),
     GPRCS1Size(0), GPRCS2Size(0), DPRCSSize(0),
     GPRCS1Frames(0), GPRCS2Frames(0), DPRCSFrames(0),
+    NumAlignedDPRCS2Regs(0),
     JumpTableUId(0), PICLabelUId(0),
     VarArgsFrameIndex(0), HasITBlocks(false) {}
=20
@@ -137,6 +151,9 @@
   unsigned getFramePtrSpillOffset() const { return FramePtrSpillOffset; }
   void setFramePtrSpillOffset(unsigned o) { FramePtrSpillOffset =3D o; }
=20
+  unsigned getNumAlignedDPRCS2Regs() const { return NumAlignedDPRCS2Regs; }
+  void setNumAlignedDPRCS2Regs(unsigned n) { NumAlignedDPRCS2Regs =3D n; }
+
   unsigned getGPRCalleeSavedArea1Offset() const { return GPRCS1Offset; }
   unsigned getGPRCalleeSavedArea2Offset() const { return GPRCS2Offset; }
   unsigned getDPRCalleeSavedAreaOffset()  const { return DPRCSOffset; }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMPe=
rfectShuffle.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMPerfectShuffle.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMPerfectShuffle.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMPerfectShuffle.h - NEON Perfect Shuffle Table -----------=
-------=3D=3D=3D//
+//=3D=3D=3D-- ARMPerfectShuffle.h - NEON Perfect Shuffle Table --------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMRe=
gisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMRegisterInfo.cpp - ARM Register Information -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMRegisterInfo.cpp - ARM Register Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,11 +11,13 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "ARMRegisterInfo.h"
 #include "ARM.h"
 #include "ARMBaseInstrInfo.h"
-#include "ARMRegisterInfo.h"
 using namespace llvm;
=20
+void ARMRegisterInfo::anchor() { }
+
 ARMRegisterInfo::ARMRegisterInfo(const ARMBaseInstrInfo &tii,
                                  const ARMSubtarget &sti)
   : ARMBaseRegisterInfo(tii, sti) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMRe=
gisterInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMRegisterInfo.h - ARM Register Information Impl --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMRegisterInfo.h - ARM Register Information Impl -------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,15 +15,15 @@
 #define ARMREGISTERINFO_H
=20
 #include "ARM.h"
+#include "ARMBaseRegisterInfo.h"
 #include "llvm/Target/TargetRegisterInfo.h"
-#include "ARMBaseRegisterInfo.h"
=20
 namespace llvm {
   class ARMSubtarget;
   class ARMBaseInstrInfo;
-  class Type;
=20
 struct ARMRegisterInfo : public ARMBaseRegisterInfo {
+  virtual void anchor();
 public:
   ARMRegisterInfo(const ARMBaseInstrInfo &tii, const ARMSubtarget &STI);
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMRe=
gisterInfo.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMRegisterInfo.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMRegisterInfo.td - ARM Register defs --------------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMRegisterInfo.td - ARM Register defs -------------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -16,6 +16,8 @@
   field bits<4> Num;
   let Namespace =3D "ARM";
   let SubRegs =3D subregs;
+  // All bits of ARM registers with sub-registers are covered by sub-regis=
ters.
+  let CoveredBySubRegs =3D 1;
 }
=20
 class ARMFReg<bits<6> num, string n> : Register<n> {
@@ -25,28 +27,30 @@
=20
 // Subregister indices.
 let Namespace =3D "ARM" in {
+def qqsub_0 : SubRegIndex;
+def qqsub_1 : SubRegIndex;
+
 // Note: Code depends on these having consecutive numbers.
-def ssub_0  : SubRegIndex;
-def ssub_1  : SubRegIndex;
-def ssub_2  : SubRegIndex; // In a Q reg.
-def ssub_3  : SubRegIndex;
+def qsub_0 : SubRegIndex;
+def qsub_1 : SubRegIndex;
+def qsub_2 : SubRegIndex<[qqsub_1, qsub_0]>;
+def qsub_3 : SubRegIndex<[qqsub_1, qsub_1]>;
=20
 def dsub_0 : SubRegIndex;
 def dsub_1 : SubRegIndex;
-def dsub_2 : SubRegIndex;
-def dsub_3 : SubRegIndex;
-def dsub_4 : SubRegIndex;
-def dsub_5 : SubRegIndex;
-def dsub_6 : SubRegIndex;
-def dsub_7 : SubRegIndex;
+def dsub_2 : SubRegIndex<[qsub_1, dsub_0]>;
+def dsub_3 : SubRegIndex<[qsub_1, dsub_1]>;
+def dsub_4 : SubRegIndex<[qsub_2, dsub_0]>;
+def dsub_5 : SubRegIndex<[qsub_2, dsub_1]>;
+def dsub_6 : SubRegIndex<[qsub_3, dsub_0]>;
+def dsub_7 : SubRegIndex<[qsub_3, dsub_1]>;
=20
-def qsub_0 : SubRegIndex;
-def qsub_1 : SubRegIndex;
-def qsub_2 : SubRegIndex;
-def qsub_3 : SubRegIndex;
-
-def qqsub_0 : SubRegIndex;
-def qqsub_1 : SubRegIndex;
+def ssub_0  : SubRegIndex;
+def ssub_1  : SubRegIndex;
+def ssub_2  : SubRegIndex<[dsub_1, ssub_0]>;
+def ssub_3  : SubRegIndex<[dsub_1, ssub_1]>;
+// Let TableGen synthesize the remaining 12 ssub_* indices.
+// We don't need to name them.
 }
=20
 // Integer registers
@@ -127,9 +131,7 @@
 def D31 : ARMFReg<31, "d31">, DwarfRegNum<[287]>;
=20
 // Advanced SIMD (NEON) defines 16 quad-word aliases
-let SubRegIndices =3D [dsub_0, dsub_1],
- CompositeIndices =3D [(ssub_2 dsub_1, ssub_0),
-                     (ssub_3 dsub_1, ssub_1)] in {
+let SubRegIndices =3D [dsub_0, dsub_1] in {
 def Q0  : ARMReg< 0,  "q0", [D0,   D1]>;
 def Q1  : ARMReg< 1,  "q1", [D2,   D3]>;
 def Q2  : ARMReg< 2,  "q2", [D4,   D5]>;
@@ -150,45 +152,22 @@
 def Q15 : ARMReg<15, "q15", [D30, D31]>;
 }
=20
-// Pseudo 256-bit registers to represent pairs of Q registers. These should
-// never be present in the emitted code.
-// These are used for NEON load / store instructions, e.g., vld4, vst3.
-// NOTE: It's possible to define more QQ registers since technically the
-// starting D register number doesn't have to be multiple of 4, e.g.,
-// D1, D2, D3, D4 would be a legal quad, but that would make the subregist=
er
-// stuff very messy.
-let SubRegIndices =3D [qsub_0, qsub_1],
- CompositeIndices =3D [(dsub_2 qsub_1, dsub_0), (dsub_3 qsub_1, dsub_1)] i=
n {
-def QQ0 : ARMReg<0, "qq0", [Q0,  Q1]>;
-def QQ1 : ARMReg<1, "qq1", [Q2,  Q3]>;
-def QQ2 : ARMReg<2, "qq2", [Q4,  Q5]>;
-def QQ3 : ARMReg<3, "qq3", [Q6,  Q7]>;
-def QQ4 : ARMReg<4, "qq4", [Q8,  Q9]>;
-def QQ5 : ARMReg<5, "qq5", [Q10, Q11]>;
-def QQ6 : ARMReg<6, "qq6", [Q12, Q13]>;
-def QQ7 : ARMReg<7, "qq7", [Q14, Q15]>;
+// Current Program Status Register.
+// We model fpscr with two registers: FPSCR models the control bits and wi=
ll be
+// reserved. FPSCR_NZCV models the flag bits and will be unreserved.=20
+def CPSR       : ARMReg<0, "cpsr">;
+def APSR       : ARMReg<1, "apsr">;
+def SPSR       : ARMReg<2, "spsr">;
+def FPSCR      : ARMReg<3, "fpscr">;
+def FPSCR_NZCV : ARMReg<3, "fpscr_nzcv"> {
+  let Aliases =3D [FPSCR];
 }
-
-// Pseudo 512-bit registers to represent four consecutive Q registers.
-let SubRegIndices =3D [qqsub_0, qqsub_1],
- CompositeIndices =3D [(qsub_2  qqsub_1, qsub_0), (qsub_3  qqsub_1, qsub_1=
),
-                     (dsub_4  qqsub_1, dsub_0), (dsub_5  qqsub_1, dsub_1),
-                     (dsub_6  qqsub_1, dsub_2), (dsub_7  qqsub_1, dsub_3)]=
 in {
-def QQQQ0 : ARMReg<0, "qqqq0", [QQ0, QQ1]>;
-def QQQQ1 : ARMReg<1, "qqqq1", [QQ2, QQ3]>;
-def QQQQ2 : ARMReg<2, "qqqq2", [QQ4, QQ5]>;
-def QQQQ3 : ARMReg<3, "qqqq3", [QQ6, QQ7]>;
-}
-
-// Current Program Status Register.
-def CPSR    : ARMReg<0, "cpsr">;
-def APSR    : ARMReg<1, "apsr">;
-def SPSR    : ARMReg<2, "spsr">;
-def FPSCR   : ARMReg<3, "fpscr">;
-def ITSTATE : ARMReg<4, "itstate">;
+def ITSTATE    : ARMReg<4, "itstate">;
=20
 // Special Registers - only available in privileged mode.
 def FPSID   : ARMReg<0, "fpsid">;
+def MVFR1   : ARMReg<6, "mvfr1">;
+def MVFR0   : ARMReg<7, "mvfr0">;
 def FPEXC   : ARMReg<8, "fpexc">;
=20
 // Register classes.
@@ -261,6 +240,12 @@
   }];
 }
=20
+// Condition code registers.
+def CCR : RegisterClass<"ARM", [i32], 32, (add CPSR)> {
+  let CopyCost =3D -1;  // Don't allow copying of status registers.
+  let isAllocatable =3D 0;
+}
+
 // Scalar single precision floating point register class..
 def SPR : RegisterClass<"ARM", [f32], 32, (sequence "S%u", 0, 31)>;
=20
@@ -316,37 +301,100 @@
                        (DPR_8 dsub_0, dsub_1)];
 }
=20
+// Pseudo-registers representing odd-even pairs of D registers. The even-o=
dd
+// pairs are already represented by the Q registers.
+// These are needed by NEON instructions requiring two consecutive D regis=
ters.
+// There is no D31_D0 register as that is always an UNPREDICTABLE encoding.
+def TuplesOE2D : RegisterTuples<[dsub_0, dsub_1],
+                                [(decimate (shl DPR, 1), 2),
+                                 (decimate (shl DPR, 2), 2)]>;
+
+// Register class representing a pair of consecutive D registers.
+// Use the Q registers for the even-odd pairs.
+def DPair : RegisterClass<"ARM", [v16i8, v8i16, v4i32, v2i64, v4f32, v2f64=
],
+                          128, (interleave QPR, TuplesOE2D)> {
+  // Allocate starting at non-VFP2 registers D16-D31 first.
+  // Prefer even-odd pairs as they are easier to copy.
+  let AltOrders =3D [(add (rotl QPR, 8), (rotl DPair, 16))];
+  let AltOrderSelect =3D [{ return 1; }];
+}
+
+// Pseudo-registers representing 3 consecutive D registers.
+def Tuples3D : RegisterTuples<[dsub_0, dsub_1, dsub_2],
+                              [(shl DPR, 0),
+                               (shl DPR, 1),
+                               (shl DPR, 2)]>;
+
+// 3 consecutive D registers.
+def DTriple : RegisterClass<"ARM", [untyped], 64, (add Tuples3D)> {
+  let Size =3D 192; // 3 x 64 bits, we have no predefined type of that siz=
e.
+}
+
+// Pseudo 256-bit registers to represent pairs of Q registers. These should
+// never be present in the emitted code.
+// These are used for NEON load / store instructions, e.g., vld4, vst3.
+def Tuples2Q : RegisterTuples<[qsub_0, qsub_1], [(shl QPR, 0), (shl QPR, 1=
)]>;
+
 // Pseudo 256-bit vector register class to model pairs of Q registers
 // (4 consecutive D registers).
-def QQPR : RegisterClass<"ARM", [v4i64], 256, (sequence "QQ%u", 0, 7)> {
+def QQPR : RegisterClass<"ARM", [v4i64], 256, (add Tuples2Q)> {
   let SubRegClasses =3D [(DPR dsub_0, dsub_1, dsub_2, dsub_3),
                        (QPR qsub_0, qsub_1)];
   // Allocate non-VFP2 aliases first.
-  let AltOrders =3D [(rotl QQPR, 4)];
+  let AltOrders =3D [(rotl QQPR, 8)];
   let AltOrderSelect =3D [{ return 1; }];
 }
=20
-// Subset of QQPR that have 32-bit SPR subregs.
-def QQPR_VFP2 : RegisterClass<"ARM", [v4i64], 256, (trunc QQPR, 4)> {
-  let SubRegClasses =3D [(SPR      ssub_0, ssub_1, ssub_2, ssub_3),
-                       (DPR_VFP2 dsub_0, dsub_1, dsub_2, dsub_3),
-                       (QPR_VFP2 qsub_0, qsub_1)];
+// Tuples of 4 D regs that isn't also a pair of Q regs.
+def TuplesOE4D : RegisterTuples<[dsub_0, dsub_1, dsub_2, dsub_3],
+                                [(decimate (shl DPR, 1), 2),
+                                 (decimate (shl DPR, 2), 2),
+                                 (decimate (shl DPR, 3), 2),
+                                 (decimate (shl DPR, 4), 2)]>;
=20
-}
+// 4 consecutive D registers.
+def DQuad : RegisterClass<"ARM", [v4i64], 256,
+                          (interleave Tuples2Q, TuplesOE4D)>;
+
+// Pseudo 512-bit registers to represent four consecutive Q registers.
+def Tuples2QQ : RegisterTuples<[qqsub_0, qqsub_1],
+                               [(shl QQPR, 0), (shl QQPR, 2)]>;
=20
 // Pseudo 512-bit vector register class to model 4 consecutive Q registers
 // (8 consecutive D registers).
-def QQQQPR : RegisterClass<"ARM", [v8i64], 256, (sequence "QQQQ%u", 0, 3)>=
 {
+def QQQQPR : RegisterClass<"ARM", [v8i64], 256, (add Tuples2QQ)> {
   let SubRegClasses =3D [(DPR dsub_0, dsub_1, dsub_2, dsub_3,
                             dsub_4, dsub_5, dsub_6, dsub_7),
                        (QPR qsub_0, qsub_1, qsub_2, qsub_3)];
   // Allocate non-VFP2 aliases first.
-  let AltOrders =3D [(rotl QQQQPR, 2)];
+  let AltOrders =3D [(rotl QQQQPR, 8)];
   let AltOrderSelect =3D [{ return 1; }];
 }
=20
-// Condition code registers.
-def CCR : RegisterClass<"ARM", [i32], 32, (add CPSR)> {
-  let CopyCost =3D -1;  // Don't allow copying of status registers.
-  let isAllocatable =3D 0;
+
+// Pseudo-registers representing 2-spaced consecutive D registers.
+def Tuples2DSpc : RegisterTuples<[dsub_0, dsub_2],
+                                 [(shl DPR, 0),
+                                  (shl DPR, 2)]>;
+
+// Spaced pairs of D registers.
+def DPairSpc : RegisterClass<"ARM", [v2i64], 64, (add Tuples2DSpc)>;
+
+def Tuples3DSpc : RegisterTuples<[dsub_0, dsub_2, dsub_4],
+                                 [(shl DPR, 0),
+                                  (shl DPR, 2),
+                                  (shl DPR, 4)]>;
+
+// Spaced triples of D registers.
+def DTripleSpc : RegisterClass<"ARM", [untyped], 64, (add Tuples3DSpc)> {
+  let Size =3D 192; // 3 x 64 bits, we have no predefined type of that siz=
e.
 }
+
+def Tuples4DSpc : RegisterTuples<[dsub_0, dsub_2, dsub_4, dsub_6],
+                                 [(shl DPR, 0),
+                                  (shl DPR, 2),
+                                  (shl DPR, 4),
+                                  (shl DPR, 6)]>;
+
+// Spaced quads of D registers.
+def DQuadSpc : RegisterClass<"ARM", [v4i64], 64, (add Tuples3DSpc)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMRe=
locations.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMRelocations.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMRelocations.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMRelocations.h - ARM Code Relocations ------------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMRelocations.h - ARM Code Relocations -----------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMSc=
hedule.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMSchedule.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMSchedule.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- ARMSchedule.td - ARM Scheduling Definitions ---------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- ARMSchedule.td - ARM Scheduling Definitions --------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -118,6 +118,8 @@
 def IIC_fpMUL64    : InstrItinClass;
 def IIC_fpMAC32    : InstrItinClass;
 def IIC_fpMAC64    : InstrItinClass;
+def IIC_fpFMAC32   : InstrItinClass;
+def IIC_fpFMAC64   : InstrItinClass;
 def IIC_fpDIV32    : InstrItinClass;
 def IIC_fpDIV64    : InstrItinClass;
 def IIC_fpSQRT32   : InstrItinClass;
@@ -208,6 +210,8 @@
 def IIC_VPERMQ3    : InstrItinClass;
 def IIC_VMACD      : InstrItinClass;
 def IIC_VMACQ      : InstrItinClass;
+def IIC_VFMACD     : InstrItinClass;
+def IIC_VFMACQ     : InstrItinClass;
 def IIC_VRECSD     : InstrItinClass;
 def IIC_VRECSQ     : InstrItinClass;
 def IIC_VCNTiD     : InstrItinClass;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMSc=
heduleA8.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMScheduleA8.td	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMScheduleA8.td	Tue Apr 17 11:51:51=
 2012 +0300
@@ -324,6 +324,15 @@
                                InstrStage<19, [A8_NPipe], 0>,
                                InstrStage<19, [A8_NLSPipe]>], [19, 2, 1, 1=
]>,
   //
+  // Single-precision Fused FP MAC
+  InstrItinData<IIC_fpFMAC32, [InstrStage<1, [A8_Pipe0, A8_Pipe1], 0>,
+                               InstrStage<1, [A8_NPipe]>], [7, 2, 1, 1]>,
+  //
+  // Double-precision Fused FP MAC
+  InstrItinData<IIC_fpFMAC64, [InstrStage<1, [A8_Pipe0, A8_Pipe1], 0>,
+                               InstrStage<19, [A8_NPipe], 0>,
+                               InstrStage<19, [A8_NLSPipe]>], [19, 2, 1, 1=
]>,
+  //
   // Single-precision FP DIV
   InstrItinData<IIC_fpDIV32 , [InstrStage<1, [A8_Pipe0, A8_Pipe1], 0>,
                                InstrStage<20, [A8_NPipe], 0>,
@@ -860,6 +869,16 @@
   InstrItinData<IIC_VMACQ,    [InstrStage<1, [A8_Pipe0, A8_Pipe1], 0>,
                                InstrStage<2, [A8_NPipe]>], [10, 3, 2, 2]>,
   //
+  // Double-register Fused FP Multiple-Accumulate
+  InstrItinData<IIC_VFMACD,   [InstrStage<1, [A8_Pipe0, A8_Pipe1], 0>,
+                               InstrStage<1, [A8_NPipe]>], [9, 3, 2, 2]>,
+  //
+  // Quad-register Fused FP Multiple-Accumulate
+  // Result written in N9, but that is relative to the last cycle of multi=
cycle,
+  // so we use 10 for those cases
+  InstrItinData<IIC_VFMACQ,   [InstrStage<1, [A8_Pipe0, A8_Pipe1], 0>,
+                               InstrStage<2, [A8_NPipe]>], [10, 3, 2, 2]>,
+  //
   // Double-register Reciprical Step
   InstrItinData<IIC_VRECSD,   [InstrStage<1, [A8_Pipe0, A8_Pipe1], 0>,
                                InstrStage<1, [A8_NPipe]>], [9, 2, 2]>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMSc=
heduleA9.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMScheduleA9.td	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMScheduleA9.td	Tue Apr 17 11:51:51=
 2012 +0300
@@ -604,6 +604,22 @@
                                InstrStage<2,  [A9_NPipe]>],
                               [9, 1, 1, 1]>,
   //
+  // Single-precision Fused FP MAC
+  InstrItinData<IIC_fpFMAC32, [InstrStage<1, [A9_Issue0, A9_Issue1], 0>,
+                               InstrStage<1, [A9_MUX0], 0>,
+                               InstrStage<1, [A9_DRegsVFP], 0, Required>,
+                               InstrStage<9, [A9_DRegsN],   0, Reserved>,
+                               InstrStage<1, [A9_NPipe]>],
+                              [8, 1, 1, 1]>,
+  //
+  // Double-precision Fused FP MAC
+  InstrItinData<IIC_fpFMAC64, [InstrStage<1,  [A9_Issue0, A9_Issue1], 0>,
+                               InstrStage<1,  [A9_MUX0], 0>,
+                               InstrStage<1,  [A9_DRegsVFP], 0, Required>,
+                               InstrStage<10, [A9_DRegsN],  0, Reserved>,
+                               InstrStage<2,  [A9_NPipe]>],
+                              [9, 1, 1, 1]>,
+  //
   // Single-precision FP DIV
   InstrItinData<IIC_fpDIV32 , [InstrStage<1,  [A9_Issue0, A9_Issue1], 0>,
                                InstrStage<1,  [A9_MUX0], 0>,
@@ -1697,6 +1713,26 @@
                                InstrStage<4, [A9_NPipe]>],
                               [8, 4, 2, 1]>,
   //
+  // Double-register Fused FP Multiple-Accumulate
+  InstrItinData<IIC_VFMACD,   [InstrStage<1, [A9_Issue0, A9_Issue1], 0>,
+                               InstrStage<1, [A9_MUX0], 0>,
+                               InstrStage<1, [A9_DRegsN],   0, Required>,
+                               // Extra latency cycles since wbck is 7 cyc=
les
+                               InstrStage<8, [A9_DRegsVFP], 0, Reserved>,
+                               InstrStage<2, [A9_NPipe]>],
+                              [6, 3, 2, 1]>,
+  //
+  // Quad-register Fused FP Multiple-Accumulate
+  // Result written in N9, but that is relative to the last cycle of multi=
cycle,
+  // so we use 10 for those cases
+  InstrItinData<IIC_VFMACQ,   [InstrStage<1, [A9_Issue0, A9_Issue1], 0>,
+                               InstrStage<1, [A9_MUX0], 0>,
+                               InstrStage<1, [A9_DRegsN],   0, Required>,
+                               // Extra latency cycles since wbck is 9 cyc=
les
+                               InstrStage<10, [A9_DRegsVFP], 0, Reserved>,
+                               InstrStage<4, [A9_NPipe]>],
+                              [8, 4, 2, 1]>,
+  //
   // Double-register Reciprical Step
   InstrItinData<IIC_VRECSD,   [InstrStage<1, [A9_Issue0, A9_Issue1], 0>,
                                InstrStage<1, [A9_MUX0], 0>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMSc=
heduleV6.td
--- a/head/contrib/llvm/lib/Target/ARM/ARMScheduleV6.td	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMScheduleV6.td	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- ARMScheduleV6.td - ARM v6 Scheduling Definitions ----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- ARMScheduleV6.td - ARM v6 Scheduling Definitions ---*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file defines the itinerary class data for the ARM v6 processors.
@@ -243,6 +243,12 @@
   // Double-precision FP MAC
   InstrItinData<IIC_fpMAC64 , [InstrStage<2, [V6_Pipe]>], [9, 2, 2, 2]>,
   //
+  // Single-precision Fused FP MAC
+  InstrItinData<IIC_fpFMAC32, [InstrStage<1, [V6_Pipe]>], [9, 2, 2, 2]>,
+  //
+  // Double-precision Fused FP MAC
+  InstrItinData<IIC_fpFMAC64, [InstrStage<2, [V6_Pipe]>], [9, 2, 2, 2]>,
+  //
   // Single-precision FP DIV
   InstrItinData<IIC_fpDIV32 , [InstrStage<15, [V6_Pipe]>], [20, 2, 2]>,
   //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMSe=
lectionDAGInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMSelectionDAGInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -67,7 +67,7 @@
                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
                                          DAG.getConstant(SrcOff, MVT::i32)=
),
                              SrcPtrInfo.getWithOffset(SrcOff), isVolatile,
-                             false, 0);
+                             false, false, 0);
       TFOps[i] =3D Loads[i].getValue(1);
       SrcOff +=3D VTSize;
     }
@@ -105,7 +105,8 @@
     Loads[i] =3D DAG.getLoad(VT, dl, Chain,
                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
                                        DAG.getConstant(SrcOff, MVT::i32)),
-                           SrcPtrInfo.getWithOffset(SrcOff), false, false,=
 0);
+                           SrcPtrInfo.getWithOffset(SrcOff),
+                           false, false, false, 0);
     TFOps[i] =3D Loads[i].getValue(1);
     ++i;
     SrcOff +=3D VTSize;
@@ -144,8 +145,8 @@
                         SDValue Src, SDValue Size,
                         unsigned Align, bool isVolatile,
                         MachinePointerInfo DstPtrInfo) const {
-  // Use default for non AAPCS subtargets
-  if (!Subtarget->isAAPCS_ABI())
+  // Use default for non AAPCS (or Darwin) subtargets
+  if (!Subtarget->isAAPCS_ABI() || Subtarget->isTargetDarwin())
     return SDValue();
=20
   const ARMTargetLowering &TLI =3D
@@ -188,6 +189,7 @@
                     0,     // number of fixed arguments
                     TLI.getLibcallCallingConv(RTLIB::MEMSET), // call conv
                     false, // is tail call
+                    false, // does not return
                     false, // is return val used
                     DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET=
),
                                           TLI.getPointerTy()), // callee
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMSu=
btarget.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMSubtarget.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMSubtarget.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMSubtarget.cpp - ARM Subtarget Information ------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMSubtarget.cpp - ARM Subtarget Information ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -16,7 +16,6 @@
 #include "llvm/GlobalValue.h"
 #include "llvm/Target/TargetSubtargetInfo.h"
 #include "llvm/Support/CommandLine.h"
-#include "llvm/ADT/SmallVector.h"
=20
 #define GET_SUBTARGETINFO_TARGET_DESC
 #define GET_SUBTARGETINFO_CTOR
@@ -47,13 +46,13 @@
   , HasV7Ops(false)
   , HasVFPv2(false)
   , HasVFPv3(false)
+  , HasVFPv4(false)
   , HasNEON(false)
   , UseNEONForSinglePrecisionFP(false)
   , SlowFPVMLx(false)
   , HasVMLxForwarding(false)
   , SlowFPBrcc(false)
   , InThumbMode(false)
-  , InNaClMode(false)
   , HasThumb2(false)
   , IsMClass(false)
   , NoARM(false)
@@ -104,18 +103,19 @@
   computeIssueWidth();
=20
   if (TT.find("eabi") !=3D std::string::npos)
+    // FIXME: We might want to separate AAPCS and EABI. Some systems, e.g.
+    // Darwin-EABI conforms to AACPS but not the rest of EABI.
     TargetABI =3D ARM_ABI_AAPCS;
=20
   if (isAAPCS_ABI())
     stackAlignment =3D 8;
=20
-  if (!isTargetDarwin())
+  if (!isTargetIOS())
     UseMovt =3D hasV6T2Ops();
   else {
     IsR9Reserved =3D ReserveR9 | !HasV6Ops;
     UseMovt =3D DarwinUseMOVT && hasV6T2Ops();
-    const Triple &T =3D getTargetTriple();
-    SupportsTailCall =3D T.getOS() =3D=3D Triple::IOS && !T.isOSVersionLT(=
5, 0);
+    SupportsTailCall =3D !getTargetTriple().isOSVersionLT(5, 0);
   }
=20
   if (!isThumb() || hasThumb2())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMSu=
btarget.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMSubtarget.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMSubtarget.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D---- ARMSubtarget.h - Define Subtarget for the ARM -----*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- ARMSubtarget.h - Define Subtarget for the ARM ----------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -45,10 +45,11 @@
   bool HasV6T2Ops;
   bool HasV7Ops;
=20
-  /// HasVFPv2, HasVFPv3, HasNEON - Specify what floating point ISAs are
-  /// supported.
+  /// HasVFPv2, HasVFPv3, HasVFPv4, HasNEON - Specify what
+  /// floating point ISAs are supported.
   bool HasVFPv2;
   bool HasVFPv3;
+  bool HasVFPv4;
   bool HasNEON;
=20
   /// UseNEONForSinglePrecisionFP - if the NEONFP attribute has been
@@ -70,9 +71,6 @@
   /// InThumbMode - True if compiling for Thumb, false for ARM.
   bool InThumbMode;
=20
-  /// InNaClMode - True if targeting Native Client
-  bool InNaClMode;
-
   /// HasThumb2 - True if Thumb2 instructions are supported.
   bool HasThumb2;
=20
@@ -126,6 +124,10 @@
   /// CPSR setting instruction.
   bool AvoidCPSRPartialUpdate;
=20
+  /// HasRAS - Some processors perform return stack prediction. CodeGen sh=
ould
+  /// avoid issue "normal" call instructions to callees which do not retur=
n.
+  bool HasRAS;
+
   /// HasMPExtension - True if the subtarget supports Multiprocessing
   /// extension (ARMv7 only).
   bool HasMPExtension;
@@ -194,11 +196,13 @@
=20
   bool isCortexA8() const { return ARMProcFamily =3D=3D CortexA8; }
   bool isCortexA9() const { return ARMProcFamily =3D=3D CortexA9; }
+  bool isCortexM3() const { return CPUString =3D=3D "cortex-m3"; }
=20
   bool hasARMOps() const { return !NoARM; }
=20
   bool hasVFP2() const { return HasVFPv2; }
   bool hasVFP3() const { return HasVFPv3; }
+  bool hasVFP4() const { return HasVFPv4; }
   bool hasNEON() const { return HasNEON;  }
   bool useNEONForSinglePrecisionFP() const {
     return hasNEON() && UseNEONForSinglePrecisionFP; }
@@ -212,6 +216,7 @@
   bool isFPOnlySP() const { return FPOnlySP; }
   bool prefers32BitThumb() const { return Pref32BitThumb; }
   bool avoidCPSRPartialUpdate() const { return AvoidCPSRPartialUpdate; }
+  bool hasRAS() const { return HasRAS; }
   bool hasMPExtension() const { return HasMPExtension; }
   bool hasThumb2DSP() const { return Thumb2DSP; }
=20
@@ -220,6 +225,7 @@
=20
   const Triple &getTargetTriple() const { return TargetTriple; }
=20
+  bool isTargetIOS() const { return TargetTriple.getOS() =3D=3D Triple::IO=
S; }
   bool isTargetDarwin() const { return TargetTriple.isOSDarwin(); }
   bool isTargetNaCl() const {
     return TargetTriple.getOS() =3D=3D Triple::NativeClient;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMTa=
rgetMachine.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMTargetMachine.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "llvm/Support/FormattedStream.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Target/TargetOptions.h"
+#include "llvm/Transforms/Scalar.h"
 using namespace llvm;
=20
 static cl::opt<bool>
@@ -33,24 +34,32 @@
   RegisterTargetMachine<ThumbTargetMachine> Y(TheThumbTarget);
 }
=20
+
 /// TargetMachine ctor - Create an ARM architecture model.
 ///
 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, StringRef TT,
                                            StringRef CPU, StringRef FS,
-                                           Reloc::Model RM, CodeModel::Mod=
el CM)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
+                                           const TargetOptions &Options,
+                                           Reloc::Model RM, CodeModel::Mod=
el CM,
+                                           CodeGenOpt::Level OL)
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     Subtarget(TT, CPU, FS),
     JITInfo(),
     InstrItins(Subtarget.getInstrItineraryData()) {
   // Default to soft float ABI
-  if (FloatABIType =3D=3D FloatABI::Default)
-    FloatABIType =3D FloatABI::Soft;
+  if (Options.FloatABIType =3D=3D FloatABI::Default)
+    this->Options.FloatABIType =3D FloatABI::Soft;
 }
=20
+void ARMTargetMachine::anchor() { }
+
 ARMTargetMachine::ARMTargetMachine(const Target &T, StringRef TT,
                                    StringRef CPU, StringRef FS,
-                                   Reloc::Model RM, CodeModel::Model CM)
-  : ARMBaseTargetMachine(T, TT, CPU, FS, RM, CM), InstrInfo(Subtarget),
+                                   const TargetOptions &Options,
+                                   Reloc::Model RM, CodeModel::Model CM,
+                                   CodeGenOpt::Level OL)
+  : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
+    InstrInfo(Subtarget),
     DataLayout(Subtarget.isAPCS_ABI() ?
                std::string("e-p:32:32-f64:32:64-i64:32:64-"
                            "v128:32:128-v64:32:64-n32-S32") :
@@ -68,10 +77,14 @@
                        "support ARM mode execution!");
 }
=20
+void ThumbTargetMachine::anchor() { }
+
 ThumbTargetMachine::ThumbTargetMachine(const Target &T, StringRef TT,
                                        StringRef CPU, StringRef FS,
-                                       Reloc::Model RM, CodeModel::Model C=
M)
-  : ARMBaseTargetMachine(T, TT, CPU, FS, RM, CM),
+                                       const TargetOptions &Options,
+                                       Reloc::Model RM, CodeModel::Model C=
M,
+                                       CodeGenOpt::Level OL)
+  : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     InstrInfo(Subtarget.hasThumb2()
               ? ((ARMBaseInstrInfo*)new Thumb2InstrInfo(Subtarget))
               : ((ARMBaseInstrInfo*)new Thumb1InstrInfo(Subtarget))),
@@ -94,37 +107,62 @@
               : (ARMFrameLowering*)new Thumb1FrameLowering(Subtarget)) {
 }
=20
-bool ARMBaseTargetMachine::addPreISel(PassManagerBase &PM,
-                                      CodeGenOpt::Level OptLevel) {
-  if (OptLevel !=3D CodeGenOpt::None && EnableGlobalMerge)
-    PM.add(createARMGlobalMergePass(getTargetLowering()));
+namespace {
+/// ARM Code Generator Pass Configuration Options.
+class ARMPassConfig : public TargetPassConfig {
+public:
+  ARMPassConfig(ARMBaseTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  ARMBaseTargetMachine &getARMTargetMachine() const {
+    return getTM<ARMBaseTargetMachine>();
+  }
+
+  const ARMSubtarget &getARMSubtarget() const {
+    return *getARMTargetMachine().getSubtargetImpl();
+  }
+
+  virtual bool addPreISel();
+  virtual bool addInstSelector();
+  virtual bool addPreRegAlloc();
+  virtual bool addPreSched2();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &=
PM) {
+  return new ARMPassConfig(this, PM);
+}
+
+bool ARMPassConfig::addPreISel() {
+  if (TM->getOptLevel() !=3D CodeGenOpt::None && EnableGlobalMerge)
+    PM.add(createGlobalMergePass(TM->getTargetLowering()));
=20
   return false;
 }
=20
-bool ARMBaseTargetMachine::addInstSelector(PassManagerBase &PM,
-                                           CodeGenOpt::Level OptLevel) {
-  PM.add(createARMISelDag(*this, OptLevel));
+bool ARMPassConfig::addInstSelector() {
+  PM.add(createARMISelDag(getARMTargetMachine(), getOptLevel()));
   return false;
 }
=20
-bool ARMBaseTargetMachine::addPreRegAlloc(PassManagerBase &PM,
-                                          CodeGenOpt::Level OptLevel) {
+bool ARMPassConfig::addPreRegAlloc() {
   // FIXME: temporarily disabling load / store optimization pass for Thumb=
1.
-  if (OptLevel !=3D CodeGenOpt::None && !Subtarget.isThumb1Only())
+  if (getOptLevel() !=3D CodeGenOpt::None && !getARMSubtarget().isThumb1On=
ly())
     PM.add(createARMLoadStoreOptimizationPass(true));
-  if (OptLevel !=3D CodeGenOpt::None && Subtarget.isCortexA9())
+  if (getOptLevel() !=3D CodeGenOpt::None && getARMSubtarget().isCortexA9(=
))
     PM.add(createMLxExpansionPass());
   return true;
 }
=20
-bool ARMBaseTargetMachine::addPreSched2(PassManagerBase &PM,
-                                        CodeGenOpt::Level OptLevel) {
+bool ARMPassConfig::addPreSched2() {
   // FIXME: temporarily disabling load / store optimization pass for Thumb=
1.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    if (!Subtarget.isThumb1Only())
+  if (getOptLevel() !=3D CodeGenOpt::None) {
+    if (!getARMSubtarget().isThumb1Only()) {
       PM.add(createARMLoadStoreOptimizationPass());
-    if (Subtarget.hasNEON())
+      printAndVerify("After ARM load / store optimizer");
+    }
+    if (getARMSubtarget().hasNEON())
       PM.add(createExecutionDependencyFixPass(&ARM::DPRRegClass));
   }
=20
@@ -132,27 +170,31 @@
   // proper scheduling.
   PM.add(createARMExpandPseudoPass());
=20
-  if (OptLevel !=3D CodeGenOpt::None) {
-    if (!Subtarget.isThumb1Only())
-      PM.add(createIfConverterPass());
+  if (getOptLevel() !=3D CodeGenOpt::None) {
+    if (!getARMSubtarget().isThumb1Only())
+      addPass(IfConverterID);
   }
-  if (Subtarget.isThumb2())
+  if (getARMSubtarget().isThumb2())
     PM.add(createThumb2ITBlockPass());
=20
   return true;
 }
=20
-bool ARMBaseTargetMachine::addPreEmitPass(PassManagerBase &PM,
-                                          CodeGenOpt::Level OptLevel) {
-  if (Subtarget.isThumb2() && !Subtarget.prefers32BitThumb())
-    PM.add(createThumb2SizeReductionPass());
+bool ARMPassConfig::addPreEmitPass() {
+  if (getARMSubtarget().isThumb2()) {
+    if (!getARMSubtarget().prefers32BitThumb())
+      PM.add(createThumb2SizeReductionPass());
+
+    // Constant island pass work on unbundled instructions.
+    addPass(UnpackMachineBundlesID);
+  }
=20
   PM.add(createARMConstantIslandPass());
+
   return true;
 }
=20
 bool ARMBaseTargetMachine::addCodeEmitter(PassManagerBase &PM,
-                                          CodeGenOpt::Level OptLevel,
                                           JITCodeEmitter &JCE) {
   // Machine code emitter pass for ARM.
   PM.add(createARMJITCodeEmitterPass(*this, JCE));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMTa=
rgetMachine.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMTargetMachine.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMTargetMachine.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -41,7 +41,9 @@
 public:
   ARMBaseTargetMachine(const Target &T, StringRef TT,
                        StringRef CPU, StringRef FS,
-                       Reloc::Model RM, CodeModel::Model CM);
+                       const TargetOptions &Options,
+                       Reloc::Model RM, CodeModel::Model CM,
+                       CodeGenOpt::Level OL);
=20
   virtual       ARMJITInfo       *getJITInfo()         { return &JITInfo; }
   virtual const ARMSubtarget  *getSubtargetImpl() const { return &Subtarge=
t; }
@@ -50,18 +52,15 @@
   }
=20
   // Pass Pipeline Configuration
-  virtual bool addPreISel(PassManagerBase &PM, CodeGenOpt::Level OptLevel);
-  virtual bool addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptL=
evel);
-  virtual bool addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel);
-  virtual bool addPreSched2(PassManagerBase &PM, CodeGenOpt::Level OptLeve=
l);
-  virtual bool addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel);
-  virtual bool addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel,
-                              JITCodeEmitter &MCE);
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
+
+  virtual bool addCodeEmitter(PassManagerBase &PM, JITCodeEmitter &MCE);
 };
=20
 /// ARMTargetMachine - ARM target machine.
 ///
 class ARMTargetMachine : public ARMBaseTargetMachine {
+  virtual void anchor();
   ARMInstrInfo        InstrInfo;
   const TargetData    DataLayout;       // Calculates type size & alignment
   ARMELFWriterInfo    ELFWriterInfo;
@@ -71,7 +70,9 @@
  public:
   ARMTargetMachine(const Target &T, StringRef TT,
                    StringRef CPU, StringRef FS,
-                   Reloc::Model RM, CodeModel::Model CM);
+                   const TargetOptions &Options,
+                   Reloc::Model RM, CodeModel::Model CM,
+                   CodeGenOpt::Level OL);
=20
   virtual const ARMRegisterInfo  *getRegisterInfo() const {
     return &InstrInfo.getRegisterInfo();
@@ -100,6 +101,7 @@
 ///   Thumb-1 and Thumb-2.
 ///
 class ThumbTargetMachine : public ARMBaseTargetMachine {
+  virtual void anchor();
   // Either Thumb1InstrInfo or Thumb2InstrInfo.
   OwningPtr<ARMBaseInstrInfo> InstrInfo;
   const TargetData    DataLayout;   // Calculates type size & alignment
@@ -111,7 +113,9 @@
 public:
   ThumbTargetMachine(const Target &T, StringRef TT,
                      StringRef CPU, StringRef FS,
-                     Reloc::Model RM, CodeModel::Model CM);
+                     const TargetOptions &Options,
+                     Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL);
=20
   /// returns either Thumb1RegisterInfo or Thumb2RegisterInfo
   virtual const ARMBaseRegisterInfo *getRegisterInfo() const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMTa=
rgetObjectFile.cpp
--- a/head/contrib/llvm/lib/Target/ARM/ARMTargetObjectFile.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMTargetObjectFile.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #include "llvm/Support/Dwarf.h"
 #include "llvm/Support/ELF.h"
 #include "llvm/Target/TargetMachine.h"
+#include "llvm/ADT/StringExtras.h"
 using namespace llvm;
 using namespace dwarf;
=20
@@ -24,8 +25,9 @@
 void ARMElfTargetObjectFile::Initialize(MCContext &Ctx,
                                         const TargetMachine &TM) {
   TargetLoweringObjectFileELF::Initialize(Ctx, TM);
+  isAAPCS_ABI =3D TM.getSubtarget<ARMSubtarget>().isAAPCS_ABI();
=20
-  if (TM.getSubtarget<ARMSubtarget>().isAAPCS_ABI()) {
+  if (isAAPCS_ABI) {
     StaticCtorSection =3D
       getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
                                  ELF::SHF_WRITE |
@@ -45,3 +47,33 @@
                                0,
                                SectionKind::getMetadata());
 }
+
+const MCSection *
+ARMElfTargetObjectFile::getStaticCtorSection(unsigned Priority) const {
+  if (!isAAPCS_ABI)
+    return TargetLoweringObjectFileELF::getStaticCtorSection(Priority);
+
+  if (Priority =3D=3D 65535)
+    return StaticCtorSection;
+
+  // Emit ctors in priority order.
+  std::string Name =3D std::string(".init_array.") + utostr(Priority);
+  return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
+                                    ELF::SHF_ALLOC | ELF::SHF_WRITE,
+                                    SectionKind::getDataRel());
+}
+
+const MCSection *
+ARMElfTargetObjectFile::getStaticDtorSection(unsigned Priority) const {
+  if (!isAAPCS_ABI)
+    return TargetLoweringObjectFileELF::getStaticDtorSection(Priority);
+
+  if (Priority =3D=3D 65535)
+    return StaticDtorSection;
+
+  // Emit dtors in priority order.
+  std::string Name =3D std::string(".fini_array.") + utostr(Priority);
+  return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
+                                    ELF::SHF_ALLOC | ELF::SHF_WRITE,
+                                    SectionKind::getDataRel());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/ARMTa=
rgetObjectFile.h
--- a/head/contrib/llvm/lib/Target/ARM/ARMTargetObjectFile.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/ARMTargetObjectFile.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -20,6 +20,7 @@
 class ARMElfTargetObjectFile : public TargetLoweringObjectFileELF {
 protected:
   const MCSection *AttributesSection;
+  bool isAAPCS_ABI;
 public:
   ARMElfTargetObjectFile() :
     TargetLoweringObjectFileELF(),
@@ -31,6 +32,9 @@
   virtual const MCSection *getAttributesSection() const {
     return AttributesSection;
   }
+
+  const MCSection * getStaticCtorSection(unsigned Priority) const;
+  const MCSection * getStaticDtorSection(unsigned Priority) const;
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/AsmPa=
rser/ARMAsmLexer.cpp
--- a/head/contrib/llvm/lib/Target/ARM/AsmParser/ARMAsmLexer.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/AsmParser/ARMAsmLexer.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -17,9 +17,6 @@
=20
 #include "llvm/Support/TargetRegistry.h"
=20
-#include "llvm/ADT/OwningPtr.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
=20
 #include <string>
@@ -107,11 +104,9 @@
     SetError(Lexer->getErrLoc(), Lexer->getErr());
     break;
   case AsmToken::Identifier: {
-    std::string upperCase =3D lexedToken.getString().str();
-    std::string lowerCase =3D LowercaseString(upperCase);
-    StringRef lowerRef(lowerCase);
+    std::string lowerCase =3D lexedToken.getString().lower();
=20
-    unsigned regID =3D MatchRegisterName(lowerRef);
+    unsigned regID =3D MatchRegisterName(lowerCase);
     // Check for register aliases.
     //   r13 -> sp
     //   r14 -> lr
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/AsmPa=
rser/ARMAsmParser.cpp
--- a/head/contrib/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -30,7 +30,6 @@
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
=20
@@ -40,9 +39,15 @@
=20
 class ARMOperand;
=20
+enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
+
 class ARMAsmParser : public MCTargetAsmParser {
   MCSubtargetInfo &STI;
   MCAsmParser &Parser;
+  const MCRegisterInfo *MRI;
+
+  // Map of register aliases registers via the .req directive.
+  StringMap<unsigned> RegisterReqs;
=20
   struct {
     ARMCC::CondCodes Cond;    // Condition for IT block.
@@ -91,9 +96,14 @@
                               unsigned &ShiftAmount);
   bool parseDirectiveWord(unsigned Size, SMLoc L);
   bool parseDirectiveThumb(SMLoc L);
+  bool parseDirectiveARM(SMLoc L);
   bool parseDirectiveThumbFunc(SMLoc L);
   bool parseDirectiveCode(SMLoc L);
   bool parseDirectiveSyntax(SMLoc L);
+  bool parseDirectiveReq(StringRef Name, SMLoc L);
+  bool parseDirectiveUnreq(SMLoc L);
+  bool parseDirectiveArch(SMLoc L);
+  bool parseDirectiveEabiAttr(SMLoc L);
=20
   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
                           bool &CarrySetting, unsigned &ProcessorIMod,
@@ -161,6 +171,8 @@
   OperandMatchResultTy parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*=
>&);
   OperandMatchResultTy parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*>=
&);
   OperandMatchResultTy parseFPImm(SmallVectorImpl<MCParsedAsmOperand*>&);
+  OperandMatchResultTy parseVectorList(SmallVectorImpl<MCParsedAsmOperand*=
>&);
+  OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &I=
ndex);
=20
   // Asm Match Converter Methods
   bool cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
@@ -197,10 +209,18 @@
                                   const SmallVectorImpl<MCParsedAsmOperand=
*> &);
   bool cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
                         const SmallVectorImpl<MCParsedAsmOperand*> &);
+  bool cvtVLDwbFixed(MCInst &Inst, unsigned Opcode,
+                     const SmallVectorImpl<MCParsedAsmOperand*> &);
+  bool cvtVLDwbRegister(MCInst &Inst, unsigned Opcode,
+                        const SmallVectorImpl<MCParsedAsmOperand*> &);
+  bool cvtVSTwbFixed(MCInst &Inst, unsigned Opcode,
+                     const SmallVectorImpl<MCParsedAsmOperand*> &);
+  bool cvtVSTwbRegister(MCInst &Inst, unsigned Opcode,
+                        const SmallVectorImpl<MCParsedAsmOperand*> &);
=20
   bool validateInstruction(MCInst &Inst,
                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops=
);
-  void processInstruction(MCInst &Inst,
+  bool processInstruction(MCInst &Inst,
                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
   bool shouldOmitCCOutOperand(StringRef Mnemonic,
                               SmallVectorImpl<MCParsedAsmOperand*> &Operan=
ds);
@@ -217,6 +237,9 @@
     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
     MCAsmParserExtension::Initialize(_Parser);
=20
+    // Cache the MCRegisterInfo.
+    MRI =3D &getContext().getRegisterInfo();
+
     // Initialize the set of available features.
     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
=20
@@ -251,7 +274,6 @@
     k_CoprocReg,
     k_CoprocOption,
     k_Immediate,
-    k_FPImmediate,
     k_MemBarrierOpt,
     k_Memory,
     k_PostIndexRegister,
@@ -262,6 +284,9 @@
     k_RegisterList,
     k_DPRRegisterList,
     k_SPRRegisterList,
+    k_VectorList,
+    k_VectorListAllLanes,
+    k_VectorListIndexed,
     k_ShiftedRegister,
     k_ShiftedImmediate,
     k_ShifterImmediate,
@@ -311,6 +336,14 @@
       unsigned RegNum;
     } Reg;
=20
+    // A vector register list is a sequential list of 1 to 4 registers.
+    struct {
+      unsigned RegNum;
+      unsigned Count;
+      unsigned LaneIndex;
+      bool isDoubleSpaced;
+    } VectorList;
+
     struct {
       unsigned Val;
     } VectorIndex;
@@ -319,10 +352,6 @@
       const MCExpr *Val;
     } Imm;
=20
-    struct {
-      unsigned Val;       // encoded 8-bit representation
-    } FPImm;
-
     /// Combined record for all forms of ARM address expressions.
     struct {
       unsigned BaseRegNum;
@@ -333,7 +362,7 @@
       ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
       unsigned ShiftImm;        // shift for OffsetReg.
       unsigned Alignment;       // 0 =3D no alignment specified
-                                // n =3D alignment in bytes (8, 16, or 32)
+                                // n =3D alignment in bytes (2, 4, 8, 16, =
or 32)
       unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
     } Memory;
=20
@@ -393,6 +422,11 @@
     case k_SPRRegisterList:
       Registers =3D o.Registers;
       break;
+    case k_VectorList:
+    case k_VectorListAllLanes:
+    case k_VectorListIndexed:
+      VectorList =3D o.VectorList;
+      break;
     case k_CoprocNum:
     case k_CoprocReg:
       Cop =3D o.Cop;
@@ -403,9 +437,6 @@
     case k_Immediate:
       Imm =3D o.Imm;
       break;
-    case k_FPImmediate:
-      FPImm =3D o.FPImm;
-      break;
     case k_MemBarrierOpt:
       MBOpt =3D o.MBOpt;
       break;
@@ -474,15 +505,10 @@
   }
=20
   const MCExpr *getImm() const {
-    assert(Kind =3D=3D k_Immediate && "Invalid access!");
+    assert(isImm() && "Invalid access!");
     return Imm.Val;
   }
=20
-  unsigned getFPImm() const {
-    assert(Kind =3D=3D k_FPImmediate && "Invalid access!");
-    return FPImm.Val;
-  }
-
   unsigned getVectorIndex() const {
     assert(Kind =3D=3D k_VectorIndex && "Invalid access!");
     return VectorIndex.Val;
@@ -511,90 +537,219 @@
   bool isITMask() const { return Kind =3D=3D k_ITCondMask; }
   bool isITCondCode() const { return Kind =3D=3D k_CondCode; }
   bool isImm() const { return Kind =3D=3D k_Immediate; }
-  bool isFPImm() const { return Kind =3D=3D k_FPImmediate; }
+  bool isFPImm() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int Val =3D ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
+    return Val !=3D -1;
+  }
+  bool isFBits16() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value >=3D 0 && Value <=3D 16;
+  }
+  bool isFBits32() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value >=3D 1 && Value <=3D 32;
+  }
   bool isImm8s4() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return ((Value & 3) =3D=3D 0) && Value >=3D -1020 && Value <=3D 1020;
   }
   bool isImm0_1020s4() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return ((Value & 3) =3D=3D 0) && Value >=3D 0 && Value <=3D 1020;
   }
   bool isImm0_508s4() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return ((Value & 3) =3D=3D 0) && Value >=3D 0 && Value <=3D 508;
   }
+  bool isImm0_508s4Neg() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D -CE->getValue();
+    // explicitly exclude zero. we want that to use the normal 0_508 versi=
on.
+    return ((Value & 3) =3D=3D 0) && Value > 0 && Value <=3D 508;
+  }
   bool isImm0_255() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value >=3D 0 && Value < 256;
   }
+  bool isImm0_4095() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value >=3D 0 && Value < 4096;
+  }
+  bool isImm0_4095Neg() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D -CE->getValue();
+    return Value > 0 && Value < 4096;
+  }
+  bool isImm0_1() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value >=3D 0 && Value < 2;
+  }
+  bool isImm0_3() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value >=3D 0 && Value < 4;
+  }
   bool isImm0_7() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value >=3D 0 && Value < 8;
   }
   bool isImm0_15() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value >=3D 0 && Value < 16;
   }
   bool isImm0_31() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value >=3D 0 && Value < 32;
   }
+  bool isImm0_63() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value >=3D 0 && Value < 64;
+  }
+  bool isImm8() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value =3D=3D 8;
+  }
+  bool isImm16() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value =3D=3D 16;
+  }
+  bool isImm32() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value =3D=3D 32;
+  }
+  bool isShrImm8() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value > 0 && Value <=3D 8;
+  }
+  bool isShrImm16() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value > 0 && Value <=3D 16;
+  }
+  bool isShrImm32() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value > 0 && Value <=3D 32;
+  }
+  bool isShrImm64() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value > 0 && Value <=3D 64;
+  }
+  bool isImm1_7() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value > 0 && Value < 8;
+  }
+  bool isImm1_15() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value > 0 && Value < 16;
+  }
+  bool isImm1_31() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value > 0 && Value < 32;
+  }
   bool isImm1_16() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value > 0 && Value < 17;
   }
   bool isImm1_32() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value > 0 && Value < 33;
   }
+  bool isImm0_32() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return Value >=3D 0 && Value < 33;
+  }
   bool isImm0_65535() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value >=3D 0 && Value < 65536;
   }
   bool isImm0_65535Expr() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     // If it's not a constant expression, it'll generate a fixup and be
     // handled later.
@@ -603,56 +758,81 @@
     return Value >=3D 0 && Value < 65536;
   }
   bool isImm24bit() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value >=3D 0 && Value <=3D 0xffffff;
   }
   bool isImmThumbSR() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value > 0 && Value < 33;
   }
   bool isPKHLSLImm() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value >=3D 0 && Value < 32;
   }
   bool isPKHASRImm() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return Value > 0 && Value <=3D 32;
   }
   bool isARMSOImm() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return ARM_AM::getSOImmVal(Value) !=3D -1;
   }
+  bool isARMSOImmNot() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return ARM_AM::getSOImmVal(~Value) !=3D -1;
+  }
+  bool isARMSOImmNeg() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    // Only use this when not representable as a plain so_imm.
+    return ARM_AM::getSOImmVal(Value) =3D=3D -1 &&
+      ARM_AM::getSOImmVal(-Value) !=3D -1;
+  }
   bool isT2SOImm() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
     return ARM_AM::getT2SOImmVal(Value) !=3D -1;
   }
+  bool isT2SOImmNot() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    return ARM_AM::getT2SOImmVal(~Value) !=3D -1;
+  }
+  bool isT2SOImmNeg() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    // Only use this when not representable as a plain so_imm.
+    return ARM_AM::getT2SOImmVal(Value) =3D=3D -1 &&
+      ARM_AM::getT2SOImmVal(-Value) !=3D -1;
+  }
   bool isSetEndImm() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Value =3D CE->getValue();
@@ -672,7 +852,7 @@
   bool isBitfield() const { return Kind =3D=3D k_BitfieldDescriptor; }
   bool isPostIdxRegShifted() const { return Kind =3D=3D k_PostIndexRegiste=
r; }
   bool isPostIdxReg() const {
-    return Kind =3D=3D k_PostIndexRegister && PostIdxReg.ShiftTy =3D=3D AR=
M_AM::no_shift;
+    return Kind =3D=3D k_PostIndexRegister && PostIdxReg.ShiftTy =3D=3DARM=
_AM::no_shift;
   }
   bool isMemNoOffset(bool alignOK =3D false) const {
     if (!isMemory())
@@ -681,6 +861,17 @@
     return Memory.OffsetRegNum =3D=3D 0 && Memory.OffsetImm =3D=3D 0 &&
      (alignOK || Memory.Alignment =3D=3D 0);
   }
+  bool isMemPCRelImm12() const {
+    if (!isMemory() || Memory.OffsetRegNum !=3D 0 || Memory.Alignment !=3D=
 0)
+      return false;
+    // Base register must be PC.
+    if (Memory.BaseRegNum !=3D ARM::PC)
+      return false;
+    // Immediate offset in range [-4095, 4095].
+    if (!Memory.OffsetImm) return true;
+    int64_t Val =3D Memory.OffsetImm->getValue();
+    return (Val > -4096 && Val < 4096) || (Val =3D=3D INT32_MIN);
+  }
   bool isAlignedMemory() const {
     return isMemNoOffset(true);
   }
@@ -694,8 +885,7 @@
     return Val > -4096 && Val < 4096;
   }
   bool isAM2OffsetImm() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     // Immediate offset in range [-4095, 4095].
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
@@ -703,6 +893,11 @@
     return Val > -4096 && Val < 4096;
   }
   bool isAddrMode3() const {
+    // If we have an immediate that's not a constant, treat it as a label
+    // reference needing a fixup. If it is a constant, it's something else
+    // and we reject it.
+    if (isImm() && !isa<MCConstantExpr>(getImm()))
+      return true;
     if (!isMemory() || Memory.Alignment !=3D 0) return false;
     // No shifts are legal for AM3.
     if (Memory.ShiftType !=3D ARM_AM::no_shift) return false;
@@ -726,6 +921,11 @@
     return (Val > -256 && Val < 256) || Val =3D=3D INT32_MIN;
   }
   bool isAddrMode5() const {
+    // If we have an immediate that's not a constant, treat it as a label
+    // reference needing a fixup. If it is a constant, it's something else
+    // and we reject it.
+    if (isImm() && !isa<MCConstantExpr>(getImm()))
+      return true;
     if (!isMemory() || Memory.Alignment !=3D 0) return false;
     // Check for register offset.
     if (Memory.OffsetRegNum) return false;
@@ -733,7 +933,7 @@
     if (!Memory.OffsetImm) return true;
     int64_t Val =3D Memory.OffsetImm->getValue();
     return (Val >=3D -1020 && Val <=3D 1020 && ((Val & 3) =3D=3D 0)) ||
-           Val =3D=3D INT32_MIN;
+      Val =3D=3D INT32_MIN;
   }
   bool isMemTBB() const {
     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
@@ -810,6 +1010,11 @@
     return Val >=3D 0 && Val <=3D 1020 && (Val % 4) =3D=3D 0;
   }
   bool isMemImm8s4Offset() const {
+    // If we have an immediate that's not a constant, treat it as a label
+    // reference needing a fixup. If it is a constant, it's something else
+    // and we reject it.
+    if (isImm() && !isa<MCConstantExpr>(getImm()))
+      return true;
     if (!isMemory() || Memory.OffsetRegNum !=3D 0 || Memory.Alignment !=3D=
 0)
       return false;
     // Immediate offset a multiple of 4 in range [-1020, 1020].
@@ -828,6 +1033,8 @@
   bool isMemImm8Offset() const {
     if (!isMemory() || Memory.OffsetRegNum !=3D 0 || Memory.Alignment !=3D=
 0)
       return false;
+    // Base reg of PC isn't allowed for these encodings.
+    if (Memory.BaseRegNum =3D=3D ARM::PC) return false;
     // Immediate offset in range [-255, 255].
     if (!Memory.OffsetImm) return true;
     int64_t Val =3D Memory.OffsetImm->getValue();
@@ -844,18 +1051,14 @@
   bool isMemNegImm8Offset() const {
     if (!isMemory() || Memory.OffsetRegNum !=3D 0 || Memory.Alignment !=3D=
 0)
       return false;
+    // Base reg of PC isn't allowed for these encodings.
+    if (Memory.BaseRegNum =3D=3D ARM::PC) return false;
     // Immediate offset in range [-255, -1].
-    if (!Memory.OffsetImm) return true;
+    if (!Memory.OffsetImm) return false;
     int64_t Val =3D Memory.OffsetImm->getValue();
-    return Val > -256 && Val < 0;
+    return (Val =3D=3D INT32_MIN) || (Val > -256 && Val < 0);
   }
   bool isMemUImm12Offset() const {
-    // If we have an immediate that's not a constant, treat it as a label
-    // reference needing a fixup. If it is a constant, it's something else
-    // and we reject it.
-    if (Kind =3D=3D k_Immediate && !isa<MCConstantExpr>(getImm()))
-      return true;
-
     if (!isMemory() || Memory.OffsetRegNum !=3D 0 || Memory.Alignment !=3D=
 0)
       return false;
     // Immediate offset in range [0, 4095].
@@ -867,7 +1070,7 @@
     // If we have an immediate that's not a constant, treat it as a label
     // reference needing a fixup. If it is a constant, it's something else
     // and we reject it.
-    if (Kind =3D=3D k_Immediate && !isa<MCConstantExpr>(getImm()))
+    if (isImm() && !isa<MCConstantExpr>(getImm()))
       return true;
=20
     if (!isMemory() || Memory.OffsetRegNum !=3D 0 || Memory.Alignment !=3D=
 0)
@@ -878,16 +1081,14 @@
     return (Val > -4096 && Val < 4096) || (Val =3D=3D INT32_MIN);
   }
   bool isPostIdxImm8() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Val =3D CE->getValue();
     return (Val > -256 && Val < 256) || (Val =3D=3D INT32_MIN);
   }
   bool isPostIdxImm8s4() const {
-    if (Kind !=3D k_Immediate)
-      return false;
+    if (!isImm()) return false;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
     if (!CE) return false;
     int64_t Val =3D CE->getValue();
@@ -898,6 +1099,188 @@
   bool isMSRMask() const { return Kind =3D=3D k_MSRMask; }
   bool isProcIFlags() const { return Kind =3D=3D k_ProcIFlags; }
=20
+  // NEON operands.
+  bool isSingleSpacedVectorList() const {
+    return Kind =3D=3D k_VectorList && !VectorList.isDoubleSpaced;
+  }
+  bool isDoubleSpacedVectorList() const {
+    return Kind =3D=3D k_VectorList && VectorList.isDoubleSpaced;
+  }
+  bool isVecListOneD() const {
+    if (!isSingleSpacedVectorList()) return false;
+    return VectorList.Count =3D=3D 1;
+  }
+
+  bool isVecListDPair() const {
+    if (!isSingleSpacedVectorList()) return false;
+    return (ARMMCRegisterClasses[ARM::DPairRegClassID]
+              .contains(VectorList.RegNum));
+  }
+
+  bool isVecListThreeD() const {
+    if (!isSingleSpacedVectorList()) return false;
+    return VectorList.Count =3D=3D 3;
+  }
+
+  bool isVecListFourD() const {
+    if (!isSingleSpacedVectorList()) return false;
+    return VectorList.Count =3D=3D 4;
+  }
+
+  bool isVecListDPairSpaced() const {
+    if (isSingleSpacedVectorList()) return false;
+    return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
+              .contains(VectorList.RegNum));
+  }
+
+  bool isVecListThreeQ() const {
+    if (!isDoubleSpacedVectorList()) return false;
+    return VectorList.Count =3D=3D 3;
+  }
+
+  bool isVecListFourQ() const {
+    if (!isDoubleSpacedVectorList()) return false;
+    return VectorList.Count =3D=3D 4;
+  }
+
+  bool isSingleSpacedVectorAllLanes() const {
+    return Kind =3D=3D k_VectorListAllLanes && !VectorList.isDoubleSpaced;
+  }
+  bool isDoubleSpacedVectorAllLanes() const {
+    return Kind =3D=3D k_VectorListAllLanes && VectorList.isDoubleSpaced;
+  }
+  bool isVecListOneDAllLanes() const {
+    if (!isSingleSpacedVectorAllLanes()) return false;
+    return VectorList.Count =3D=3D 1;
+  }
+
+  bool isVecListDPairAllLanes() const {
+    if (!isSingleSpacedVectorAllLanes()) return false;
+    return (ARMMCRegisterClasses[ARM::DPairRegClassID]
+              .contains(VectorList.RegNum));
+  }
+
+  bool isVecListDPairSpacedAllLanes() const {
+    if (!isDoubleSpacedVectorAllLanes()) return false;
+    return VectorList.Count =3D=3D 2;
+  }
+
+  bool isVecListThreeDAllLanes() const {
+    if (!isSingleSpacedVectorAllLanes()) return false;
+    return VectorList.Count =3D=3D 3;
+  }
+
+  bool isVecListThreeQAllLanes() const {
+    if (!isDoubleSpacedVectorAllLanes()) return false;
+    return VectorList.Count =3D=3D 3;
+  }
+
+  bool isVecListFourDAllLanes() const {
+    if (!isSingleSpacedVectorAllLanes()) return false;
+    return VectorList.Count =3D=3D 4;
+  }
+
+  bool isVecListFourQAllLanes() const {
+    if (!isDoubleSpacedVectorAllLanes()) return false;
+    return VectorList.Count =3D=3D 4;
+  }
+
+  bool isSingleSpacedVectorIndexed() const {
+    return Kind =3D=3D k_VectorListIndexed && !VectorList.isDoubleSpaced;
+  }
+  bool isDoubleSpacedVectorIndexed() const {
+    return Kind =3D=3D k_VectorListIndexed && VectorList.isDoubleSpaced;
+  }
+  bool isVecListOneDByteIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 1 && VectorList.LaneIndex <=3D 7;
+  }
+
+  bool isVecListOneDHWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 1 && VectorList.LaneIndex <=3D 3;
+  }
+
+  bool isVecListOneDWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 1 && VectorList.LaneIndex <=3D 1;
+  }
+
+  bool isVecListTwoDByteIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 2 && VectorList.LaneIndex <=3D 7;
+  }
+
+  bool isVecListTwoDHWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 2 && VectorList.LaneIndex <=3D 3;
+  }
+
+  bool isVecListTwoQWordIndexed() const {
+    if (!isDoubleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 2 && VectorList.LaneIndex <=3D 1;
+  }
+
+  bool isVecListTwoQHWordIndexed() const {
+    if (!isDoubleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 2 && VectorList.LaneIndex <=3D 3;
+  }
+
+  bool isVecListTwoDWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 2 && VectorList.LaneIndex <=3D 1;
+  }
+
+  bool isVecListThreeDByteIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 3 && VectorList.LaneIndex <=3D 7;
+  }
+
+  bool isVecListThreeDHWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 3 && VectorList.LaneIndex <=3D 3;
+  }
+
+  bool isVecListThreeQWordIndexed() const {
+    if (!isDoubleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 3 && VectorList.LaneIndex <=3D 1;
+  }
+
+  bool isVecListThreeQHWordIndexed() const {
+    if (!isDoubleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 3 && VectorList.LaneIndex <=3D 3;
+  }
+
+  bool isVecListThreeDWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 3 && VectorList.LaneIndex <=3D 1;
+  }
+
+  bool isVecListFourDByteIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 4 && VectorList.LaneIndex <=3D 7;
+  }
+
+  bool isVecListFourDHWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 4 && VectorList.LaneIndex <=3D 3;
+  }
+
+  bool isVecListFourQWordIndexed() const {
+    if (!isDoubleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 4 && VectorList.LaneIndex <=3D 1;
+  }
+
+  bool isVecListFourQHWordIndexed() const {
+    if (!isDoubleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 4 && VectorList.LaneIndex <=3D 3;
+  }
+
+  bool isVecListFourDWordIndexed() const {
+    if (!isSingleSpacedVectorIndexed()) return false;
+    return VectorList.Count =3D=3D 4 && VectorList.LaneIndex <=3D 1;
+  }
+
   bool isVectorIndex8() const {
     if (Kind !=3D k_VectorIndex) return false;
     return VectorIndex.Val < 8;
@@ -911,7 +1294,82 @@
     return VectorIndex.Val < 2;
   }
=20
-
+  bool isNEONi8splat() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    // Must be a constant.
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    // i8 value splatted across 8 bytes. The immediate is just the 8 byte
+    // value.
+    return Value >=3D 0 && Value < 256;
+  }
+
+  bool isNEONi16splat() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    // Must be a constant.
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    // i16 value in the range [0,255] or [0x0100, 0xff00]
+    return (Value >=3D 0 && Value < 256) || (Value >=3D 0x0100 && Value <=
=3D 0xff00);
+  }
+
+  bool isNEONi32splat() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    // Must be a constant.
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X.
+    return (Value >=3D 0 && Value < 256) ||
+      (Value >=3D 0x0100 && Value <=3D 0xff00) ||
+      (Value >=3D 0x010000 && Value <=3D 0xff0000) ||
+      (Value >=3D 0x01000000 && Value <=3D 0xff000000);
+  }
+
+  bool isNEONi32vmov() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    // Must be a constant.
+    if (!CE) return false;
+    int64_t Value =3D CE->getValue();
+    // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
+    // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
+    return (Value >=3D 0 && Value < 256) ||
+      (Value >=3D 0x0100 && Value <=3D 0xff00) ||
+      (Value >=3D 0x010000 && Value <=3D 0xff0000) ||
+      (Value >=3D 0x01000000 && Value <=3D 0xff000000) ||
+      (Value >=3D 0x01ff && Value <=3D 0xffff && (Value & 0xff) =3D=3D 0xf=
f) ||
+      (Value >=3D 0x01ffff && Value <=3D 0xffffff && (Value & 0xffff) =3D=
=3D 0xffff);
+  }
+  bool isNEONi32vmovNeg() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    // Must be a constant.
+    if (!CE) return false;
+    int64_t Value =3D ~CE->getValue();
+    // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
+    // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
+    return (Value >=3D 0 && Value < 256) ||
+      (Value >=3D 0x0100 && Value <=3D 0xff00) ||
+      (Value >=3D 0x010000 && Value <=3D 0xff0000) ||
+      (Value >=3D 0x01000000 && Value <=3D 0xff000000) ||
+      (Value >=3D 0x01ff && Value <=3D 0xffff && (Value & 0xff) =3D=3D 0xf=
f) ||
+      (Value >=3D 0x01ffff && Value <=3D 0xffffff && (Value & 0xffff) =3D=
=3D 0xffff);
+  }
+
+  bool isNEONi64splat() const {
+    if (!isImm()) return false;
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    // Must be a constant.
+    if (!CE) return false;
+    uint64_t Value =3D CE->getValue();
+    // i64 value with each byte being either 0 or 0xff.
+    for (unsigned i =3D 0; i < 8; ++i)
+      if ((Value & 0xff) !=3D 0 && (Value & 0xff) !=3D 0xff) return false;
+    return true;
+  }
=20
   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
     // Add as immediates when possible.  Null MCExpr =3D 0.
@@ -967,7 +1425,8 @@
=20
   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 3 && "Invalid number of operands!");
-    assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShif=
tedReg!");
+    assert(isRegShiftedReg() &&
+           "addRegShiftedRegOperands() on non RegShiftedReg!");
     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
     Inst.addOperand(MCOperand::CreateImm(
@@ -976,7 +1435,8 @@
=20
   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 2 && "Invalid number of operands!");
-    assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShif=
tedImm!");
+    assert(isRegShiftedImm() &&
+           "addRegShiftedImmOperands() on non RegShiftedImm!");
     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
     Inst.addOperand(MCOperand::CreateImm(
       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
@@ -1026,9 +1486,23 @@
     addExpr(Inst, getImm());
   }
=20
+  void addFBits16Operands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(16 - CE->getValue()));
+  }
+
+  void addFBits32Operands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(32 - CE->getValue()));
+  }
+
   void addFPImmOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
-    Inst.addOperand(MCOperand::CreateImm(getFPImm()));
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    int Val =3D ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
+    Inst.addOperand(MCOperand::CreateImm(Val));
   }
=20
   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
@@ -1047,6 +1521,14 @@
     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
   }
=20
+  void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The immediate is scaled by four in the encoding and is stored
+    // in the MCInst as such. Lop off the low two bits here.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(-(CE->getValue() / 4)));
+  }
+
   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
     // The immediate is scaled by four in the encoding and is stored
@@ -1055,26 +1537,6 @@
     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
   }
=20
-  void addImm0_255Operands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
-  void addImm0_7Operands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
-  void addImm0_15Operands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
-  void addImm0_31Operands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
     // The constant encodes as the immediate-1, and we store in the instru=
ction
@@ -1091,21 +1553,6 @@
     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
   }
=20
-  void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
-  void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
-  void addImm24bitOperands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
     // The constant encodes as the immediate, except for 32, which encodes=
 as
@@ -1115,11 +1562,6 @@
     Inst.addOperand(MCOperand::CreateImm((Imm =3D=3D 32 ? 0 : Imm)));
   }
=20
-  void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
-    assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
     // An ASR value of 32 encodes as 0, so that's how we want to add it to
@@ -1129,19 +1571,44 @@
     Inst.addOperand(MCOperand::CreateImm(Val =3D=3D 32 ? 0 : Val));
   }
=20
-  void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
+  void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
-  void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
+    // The operand is actually a t2_so_imm, but we have its bitwise
+    // negation in the assembly source, so twiddle it here.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
+  }
+
+  void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
-  }
-
-  void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
+    // The operand is actually a t2_so_imm, but we have its
+    // negation in the assembly source, so twiddle it here.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
+  }
+
+  void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
-    addExpr(Inst, getImm());
+    // The operand is actually an imm0_4095, but we have its
+    // negation in the assembly source, so twiddle it here.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
+  }
+
+  void addARMSOImmNotOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The operand is actually a so_imm, but we have its bitwise
+    // negation in the assembly source, so twiddle it here.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
+  }
+
+  void addARMSOImmNegOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The operand is actually a so_imm, but we have its
+    // negation in the assembly source, so twiddle it here.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
   }
=20
   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
@@ -1154,6 +1621,14 @@
     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
   }
=20
+  void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    int32_t Imm =3D Memory.OffsetImm->getValue();
+    // FIXME: Handle #-0
+    if (Imm =3D=3D INT32_MIN) Imm =3D 0;
+    Inst.addOperand(MCOperand::CreateImm(Imm));
+  }
+
   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 2 && "Invalid number of operands!");
     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
@@ -1196,6 +1671,16 @@
=20
   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 3 && "Invalid number of operands!");
+    // If we have an immediate that's not a constant, treat it as a label
+    // reference needing a fixup. If it is a constant, it's something else
+    // and we reject it.
+    if (isImm()) {
+      Inst.addOperand(MCOperand::CreateExpr(getImm()));
+      Inst.addOperand(MCOperand::CreateReg(0));
+      Inst.addOperand(MCOperand::CreateImm(0));
+      return;
+    }
+
     int32_t Val =3D Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
     if (!Memory.OffsetRegNum) {
       ARM_AM::AddrOpc AddSub =3D Val < 0 ? ARM_AM::sub : ARM_AM::add;
@@ -1237,6 +1722,15 @@
=20
   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 2 && "Invalid number of operands!");
+    // If we have an immediate that's not a constant, treat it as a label
+    // reference needing a fixup. If it is a constant, it's something else
+    // and we reject it.
+    if (isImm()) {
+      Inst.addOperand(MCOperand::CreateExpr(getImm()));
+      Inst.addOperand(MCOperand::CreateImm(0));
+      return;
+    }
+
     // The lower two bits are always zero and as such are not encoded.
     int32_t Val =3D Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : =
0;
     ARM_AM::AddrOpc AddSub =3D Val < 0 ? ARM_AM::sub : ARM_AM::add;
@@ -1250,6 +1744,15 @@
=20
   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 2 && "Invalid number of operands!");
+    // If we have an immediate that's not a constant, treat it as a label
+    // reference needing a fixup. If it is a constant, it's something else
+    // and we reject it.
+    if (isImm()) {
+      Inst.addOperand(MCOperand::CreateExpr(getImm()));
+      Inst.addOperand(MCOperand::CreateImm(0));
+      return;
+    }
+
     int64_t Val =3D Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
     Inst.addOperand(MCOperand::CreateImm(Val));
@@ -1281,7 +1784,7 @@
   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 2 && "Invalid number of operands!");
     // If this is an immediate, it's a label reference.
-    if (Kind =3D=3D k_Immediate) {
+    if (isImm()) {
       addExpr(Inst, getImm());
       Inst.addOperand(MCOperand::CreateImm(0));
       return;
@@ -1296,7 +1799,7 @@
   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 2 && "Invalid number of operands!");
     // If this is an immediate, it's a label reference.
-    if (Kind =3D=3D k_Immediate) {
+    if (isImm()) {
       addExpr(Inst, getImm());
       Inst.addOperand(MCOperand::CreateImm(0));
       return;
@@ -1322,8 +1825,9 @@
=20
   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 3 && "Invalid number of operands!");
-    unsigned Val =3D ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : A=
RM_AM::add,
-                                     Memory.ShiftImm, Memory.ShiftType);
+    unsigned Val =3D
+      ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
+                        Memory.ShiftImm, Memory.ShiftType);
     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
     Inst.addOperand(MCOperand::CreateImm(Val));
@@ -1420,6 +1924,17 @@
     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
   }
=20
+  void addVecListOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
+  }
+
+  void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 2 && "Invalid number of operands!");
+    Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
+    Inst.addOperand(MCOperand::CreateImm(VectorList.LaneIndex));
+  }
+
   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
     assert(N =3D=3D 1 && "Invalid number of operands!");
     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
@@ -1435,6 +1950,80 @@
     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
   }
=20
+  void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The immediate encodes the type of constant as well as the value.
+    // Mask in that this is an i8 splat.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    Inst.addOperand(MCOperand::CreateImm(CE->getValue() | 0xe00));
+  }
+
+  void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The immediate encodes the type of constant as well as the value.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    unsigned Value =3D CE->getValue();
+    if (Value >=3D 256)
+      Value =3D (Value >> 8) | 0xa00;
+    else
+      Value |=3D 0x800;
+    Inst.addOperand(MCOperand::CreateImm(Value));
+  }
+
+  void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The immediate encodes the type of constant as well as the value.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    unsigned Value =3D CE->getValue();
+    if (Value >=3D 256 && Value <=3D 0xff00)
+      Value =3D (Value >> 8) | 0x200;
+    else if (Value > 0xffff && Value <=3D 0xff0000)
+      Value =3D (Value >> 16) | 0x400;
+    else if (Value > 0xffffff)
+      Value =3D (Value >> 24) | 0x600;
+    Inst.addOperand(MCOperand::CreateImm(Value));
+  }
+
+  void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The immediate encodes the type of constant as well as the value.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    unsigned Value =3D CE->getValue();
+    if (Value >=3D 256 && Value <=3D 0xffff)
+      Value =3D (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
+    else if (Value > 0xffff && Value <=3D 0xffffff)
+      Value =3D (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
+    else if (Value > 0xffffff)
+      Value =3D (Value >> 24) | 0x600;
+    Inst.addOperand(MCOperand::CreateImm(Value));
+  }
+
+  void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The immediate encodes the type of constant as well as the value.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    unsigned Value =3D ~CE->getValue();
+    if (Value >=3D 256 && Value <=3D 0xffff)
+      Value =3D (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
+    else if (Value > 0xffff && Value <=3D 0xffffff)
+      Value =3D (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
+    else if (Value > 0xffffff)
+      Value =3D (Value >> 24) | 0x600;
+    Inst.addOperand(MCOperand::CreateImm(Value));
+  }
+
+  void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
+    assert(N =3D=3D 1 && "Invalid number of operands!");
+    // The immediate encodes the type of constant as well as the value.
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getImm());
+    uint64_t Value =3D CE->getValue();
+    unsigned Imm =3D 0;
+    for (unsigned i =3D 0; i < 8; ++i, Value >>=3D 8) {
+      Imm |=3D (Value & 1) << i;
+    }
+    Inst.addOperand(MCOperand::CreateImm(Imm | 0x1e00));
+  }
+
   virtual void print(raw_ostream &OS) const;
=20
   static ARMOperand *CreateITMask(unsigned Mask, SMLoc S) {
@@ -1579,6 +2168,43 @@
     return Op;
   }
=20
+  static ARMOperand *CreateVectorList(unsigned RegNum, unsigned Count,
+                                      bool isDoubleSpaced, SMLoc S, SMLoc =
E) {
+    ARMOperand *Op =3D new ARMOperand(k_VectorList);
+    Op->VectorList.RegNum =3D RegNum;
+    Op->VectorList.Count =3D Count;
+    Op->VectorList.isDoubleSpaced =3D isDoubleSpaced;
+    Op->StartLoc =3D S;
+    Op->EndLoc =3D E;
+    return Op;
+  }
+
+  static ARMOperand *CreateVectorListAllLanes(unsigned RegNum, unsigned Co=
unt,
+                                              bool isDoubleSpaced,
+                                              SMLoc S, SMLoc E) {
+    ARMOperand *Op =3D new ARMOperand(k_VectorListAllLanes);
+    Op->VectorList.RegNum =3D RegNum;
+    Op->VectorList.Count =3D Count;
+    Op->VectorList.isDoubleSpaced =3D isDoubleSpaced;
+    Op->StartLoc =3D S;
+    Op->EndLoc =3D E;
+    return Op;
+  }
+
+  static ARMOperand *CreateVectorListIndexed(unsigned RegNum, unsigned Cou=
nt,
+                                             unsigned Index,
+                                             bool isDoubleSpaced,
+                                             SMLoc S, SMLoc E) {
+    ARMOperand *Op =3D new ARMOperand(k_VectorListIndexed);
+    Op->VectorList.RegNum =3D RegNum;
+    Op->VectorList.Count =3D Count;
+    Op->VectorList.LaneIndex =3D Index;
+    Op->VectorList.isDoubleSpaced =3D isDoubleSpaced;
+    Op->StartLoc =3D S;
+    Op->EndLoc =3D E;
+    return Op;
+  }
+
   static ARMOperand *CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E,
                                        MCContext &Ctx) {
     ARMOperand *Op =3D new ARMOperand(k_VectorIndex);
@@ -1596,14 +2222,6 @@
     return Op;
   }
=20
-  static ARMOperand *CreateFPImm(unsigned Val, SMLoc S, MCContext &Ctx) {
-    ARMOperand *Op =3D new ARMOperand(k_FPImmediate);
-    Op->FPImm.Val =3D Val;
-    Op->StartLoc =3D S;
-    Op->EndLoc =3D S;
-    return Op;
-  }
-
   static ARMOperand *CreateMem(unsigned BaseRegNum,
                                const MCConstantExpr *OffsetImm,
                                unsigned OffsetRegNum,
@@ -1668,10 +2286,6 @@
=20
 void ARMOperand::print(raw_ostream &OS) const {
   switch (Kind) {
-  case k_FPImmediate:
-    OS << "<fpimm " << getFPImm() << "(" << ARM_AM::getFPImmFloat(getFPImm=
())
-       << ") >";
-    break;
   case k_CondCode:
     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
     break;
@@ -1679,9 +2293,10 @@
     OS << "<ccout " << getReg() << ">";
     break;
   case k_ITCondMask: {
-    static char MaskStr[][6] =3D { "()", "(t)", "(e)", "(tt)", "(et)", "(t=
e)",
-      "(ee)", "(ttt)", "(ett)", "(tet)", "(eet)", "(tte)", "(ete)",
-      "(tee)", "(eee)" };
+    static const char *MaskStr[] =3D {
+      "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
+      "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
+    };
     assert((ITMask.Mask & 0xf) =3D=3D ITMask.Mask);
     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
     break;
@@ -1735,18 +2350,15 @@
     break;
   case k_ShiftedRegister:
     OS << "<so_reg_reg "
-       << RegShiftedReg.SrcReg
-       << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftI=
mm))
-       << ", " << RegShiftedReg.ShiftReg << ", "
-       << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
-       << ">";
+       << RegShiftedReg.SrcReg << " "
+       << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
+       << " " << RegShiftedReg.ShiftReg << ">";
     break;
   case k_ShiftedImmediate:
     OS << "<so_reg_imm "
-       << RegShiftedImm.SrcReg
-       << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftI=
mm))
-       << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
-       << ">";
+       << RegShiftedImm.SrcReg << " "
+       << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
+       << " #" << RegShiftedImm.ShiftImm << ">";
     break;
   case k_RotateImmediate:
     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
@@ -1770,6 +2382,18 @@
     OS << ">";
     break;
   }
+  case k_VectorList:
+    OS << "<vector_list " << VectorList.Count << " * "
+       << VectorList.RegNum << ">";
+    break;
+  case k_VectorListAllLanes:
+    OS << "<vector_list(all lanes) " << VectorList.Count << " * "
+       << VectorList.RegNum << ">";
+    break;
+  case k_VectorListIndexed:
+    OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
+       << VectorList.Count << " * " << VectorList.RegNum << ">";
+    break;
   case k_Token:
     OS << "'" << getToken() << "'";
     break;
@@ -1788,7 +2412,9 @@
=20
 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
                                  SMLoc &StartLoc, SMLoc &EndLoc) {
+  StartLoc =3D Parser.getTok().getLoc();
   RegNo =3D tryParseRegister();
+  EndLoc =3D Parser.getTok().getLoc();
=20
   return (RegNo =3D=3D (unsigned)-1);
 }
@@ -1801,10 +2427,7 @@
   const AsmToken &Tok =3D Parser.getTok();
   if (Tok.isNot(AsmToken::Identifier)) return -1;
=20
-  // FIXME: Validate register for the current architecture; we have to do
-  // validation later, so maybe there is no need for this here.
-  std::string upperCase =3D Tok.getString().str();
-  std::string lowerCase =3D LowercaseString(upperCase);
+  std::string lowerCase =3D Tok.getString().lower();
   unsigned RegNum =3D MatchRegisterName(lowerCase);
   if (!RegNum) {
     RegNum =3D StringSwitch<unsigned>(lowerCase)
@@ -1812,44 +2435,38 @@
       .Case("r14", ARM::LR)
       .Case("r15", ARM::PC)
       .Case("ip", ARM::R12)
+      // Additional register name aliases for 'gas' compatibility.
+      .Case("a1", ARM::R0)
+      .Case("a2", ARM::R1)
+      .Case("a3", ARM::R2)
+      .Case("a4", ARM::R3)
+      .Case("v1", ARM::R4)
+      .Case("v2", ARM::R5)
+      .Case("v3", ARM::R6)
+      .Case("v4", ARM::R7)
+      .Case("v5", ARM::R8)
+      .Case("v6", ARM::R9)
+      .Case("v7", ARM::R10)
+      .Case("v8", ARM::R11)
+      .Case("sb", ARM::R9)
+      .Case("sl", ARM::R10)
+      .Case("fp", ARM::R11)
       .Default(0);
   }
-  if (!RegNum) return -1;
+  if (!RegNum) {
+    // Check for aliases registered via .req. Canonicalize to lower case.
+    // That's more consistent since register names are case insensitive, a=
nd
+    // it's how the original entry was passed in from MC/MCParser/AsmParse=
r.
+    StringMap<unsigned>::const_iterator Entry =3D RegisterReqs.find(lowerC=
ase);
+    // If no match, return failure.
+    if (Entry =3D=3D RegisterReqs.end())
+      return -1;
+    Parser.Lex(); // Eat identifier token.
+    return Entry->getValue();
+  }
=20
   Parser.Lex(); // Eat identifier token.
=20
-#if 0
-  // Also check for an index operand. This is only legal for vector regist=
ers,
-  // but that'll get caught OK in operand matching, so we don't need to
-  // explicitly filter everything else out here.
-  if (Parser.getTok().is(AsmToken::LBrac)) {
-    SMLoc SIdx =3D Parser.getTok().getLoc();
-    Parser.Lex(); // Eat left bracket token.
-
-    const MCExpr *ImmVal;
-    SMLoc ExprLoc =3D Parser.getTok().getLoc();
-    if (getParser().ParseExpression(ImmVal))
-      return MatchOperand_ParseFail;
-    const MCConstantExpr *MCE =3D dyn_cast<MCConstantExpr>(ImmVal);
-    if (!MCE) {
-      TokError("immediate value expected for vector index");
-      return MatchOperand_ParseFail;
-    }
-
-    SMLoc E =3D Parser.getTok().getLoc();
-    if (Parser.getTok().isNot(AsmToken::RBrac)) {
-      Error(E, "']' expected");
-      return MatchOperand_ParseFail;
-    }
-
-    Parser.Lex(); // Eat right bracket token.
-
-    Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
-                                                     SIdx, E,
-                                                     getContext()));
-  }
-#endif
-
   return RegNum;
 }
=20
@@ -1864,9 +2481,9 @@
   const AsmToken &Tok =3D Parser.getTok();
   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
=20
-  std::string upperCase =3D Tok.getString().str();
-  std::string lowerCase =3D LowercaseString(upperCase);
+  std::string lowerCase =3D Tok.getString().lower();
   ARM_AM::ShiftOpc ShiftTy =3D StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
+      .Case("asl", ARM_AM::lsl)
       .Case("lsl", ARM_AM::lsl)
       .Case("lsr", ARM_AM::lsr)
       .Case("asr", ARM_AM::asr)
@@ -1895,7 +2512,8 @@
     ShiftReg =3D SrcReg;
   } else {
     // Figure out if this is shifted by a constant or a register (for non-=
RRX).
-    if (Parser.getTok().is(AsmToken::Hash)) {
+    if (Parser.getTok().is(AsmToken::Hash) ||
+        Parser.getTok().is(AsmToken::Dollar)) {
       Parser.Lex(); // Eat hash.
       SMLoc ImmLoc =3D Parser.getTok().getLoc();
       const MCExpr *ShiftExpr =3D 0;
@@ -1919,6 +2537,10 @@
         Error(ImmLoc, "immediate shift value out of range");
         return -1;
       }
+      // shift by zero is a nop. Always send it through as lsl.
+      // ('as' compatibility)
+      if (Imm =3D=3D 0)
+        ShiftTy =3D ARM_AM::lsl;
     } else if (Parser.getTok().is(AsmToken::Identifier)) {
       ShiftReg =3D tryParseRegister();
       SMLoc L =3D Parser.getTok().getLoc();
@@ -1976,20 +2598,15 @@
     Parser.Lex(); // Eat left bracket token.
=20
     const MCExpr *ImmVal;
-    SMLoc ExprLoc =3D Parser.getTok().getLoc();
     if (getParser().ParseExpression(ImmVal))
-      return MatchOperand_ParseFail;
+      return true;
     const MCConstantExpr *MCE =3D dyn_cast<MCConstantExpr>(ImmVal);
-    if (!MCE) {
-      TokError("immediate value expected for vector index");
-      return MatchOperand_ParseFail;
-    }
+    if (!MCE)
+      return TokError("immediate value expected for vector index");
=20
     SMLoc E =3D Parser.getTok().getLoc();
-    if (Parser.getTok().isNot(AsmToken::RBrac)) {
-      Error(E, "']' expected");
-      return MatchOperand_ParseFail;
-    }
+    if (Parser.getTok().isNot(AsmToken::RBrac))
+      return Error(E, "']' expected");
=20
     Parser.Lex(); // Eat right bracket token.
=20
@@ -2008,7 +2625,7 @@
   // Use the same layout as the tablegen'erated register name matcher. Ugl=
y,
   // but efficient.
   switch (Name.size()) {
-  default: break;
+  default: return -1;
   case 2:
     if (Name[0] !=3D CoprocOp)
       return -1;
@@ -2025,7 +2642,6 @@
     case '8': return 8;
     case '9': return 9;
     }
-    break;
   case 3:
     if (Name[0] !=3D CoprocOp || Name[1] !=3D '1')
       return -1;
@@ -2038,10 +2654,7 @@
     case '4': return 14;
     case '5': return 15;
     }
-    break;
-  }
-
-  return -1;
+  }
 }
=20
 /// parseITCondCode - Try to parse a condition code for an IT instruction.
@@ -2161,7 +2774,7 @@
   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
     return Reg + 1;
   switch(Reg) {
-  default: assert(0 && "Invalid GPR number!");
+  default: llvm_unreachable("Invalid GPR number!");
   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
@@ -2173,6 +2786,29 @@
   }
 }
=20
+// Return the low-subreg of a given Q register.
+static unsigned getDRegFromQReg(unsigned QReg) {
+  switch (QReg) {
+  default: llvm_unreachable("expected a Q register!");
+  case ARM::Q0:  return ARM::D0;
+  case ARM::Q1:  return ARM::D2;
+  case ARM::Q2:  return ARM::D4;
+  case ARM::Q3:  return ARM::D6;
+  case ARM::Q4:  return ARM::D8;
+  case ARM::Q5:  return ARM::D10;
+  case ARM::Q6:  return ARM::D12;
+  case ARM::Q7:  return ARM::D14;
+  case ARM::Q8:  return ARM::D16;
+  case ARM::Q9:  return ARM::D18;
+  case ARM::Q10: return ARM::D20;
+  case ARM::Q11: return ARM::D22;
+  case ARM::Q12: return ARM::D24;
+  case ARM::Q13: return ARM::D26;
+  case ARM::Q14: return ARM::D28;
+  case ARM::Q15: return ARM::D30;
+  }
+}
+
 /// Parse a register list.
 bool ARMAsmParser::
 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
@@ -2188,7 +2824,17 @@
   if (Reg =3D=3D -1)
     return Error(RegLoc, "register expected");
=20
-  MCRegisterClass *RC;
+  // The reglist instructions have at most 16 registers, so reserve
+  // space for that many.
+  SmallVector<std::pair<unsigned, SMLoc>, 16> Registers;
+
+  // Allow Q regs and just interpret them as the two D sub-registers.
+  if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
+    Reg =3D getDRegFromQReg(Reg);
+    Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
+    ++Reg;
+  }
+  const MCRegisterClass *RC;
   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
     RC =3D &ARMMCRegisterClasses[ARM::GPRRegClassID];
   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
@@ -2198,10 +2844,7 @@
   else
     return Error(RegLoc, "invalid register in register list");
=20
-  // The reglist instructions have at most 16 registers, so reserve
-  // space for that many.
-  SmallVector<std::pair<unsigned, SMLoc>, 16> Registers;
-  // Store the first register.
+  // Store the register.
   Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
=20
   // This starts immediately after the first register token in the list,
@@ -2210,11 +2853,14 @@
   while (Parser.getTok().is(AsmToken::Comma) ||
          Parser.getTok().is(AsmToken::Minus)) {
     if (Parser.getTok().is(AsmToken::Minus)) {
-      Parser.Lex(); // Eat the comma.
+      Parser.Lex(); // Eat the minus.
       SMLoc EndLoc =3D Parser.getTok().getLoc();
       int EndReg =3D tryParseRegister();
       if (EndReg =3D=3D -1)
         return Error(EndLoc, "register expected");
+      // Allow Q regs and just interpret them as the two D sub-registers.
+      if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
+        EndReg =3D getDRegFromQReg(EndReg) + 1;
       // If the register is the same as the start reg, there's nothing
       // more to do.
       if (Reg =3D=3D EndReg)
@@ -2236,15 +2882,31 @@
     Parser.Lex(); // Eat the comma.
     RegLoc =3D Parser.getTok().getLoc();
     int OldReg =3D Reg;
+    const AsmToken RegTok =3D Parser.getTok();
     Reg =3D tryParseRegister();
     if (Reg =3D=3D -1)
       return Error(RegLoc, "register expected");
+    // Allow Q regs and just interpret them as the two D sub-registers.
+    bool isQReg =3D false;
+    if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
+      Reg =3D getDRegFromQReg(Reg);
+      isQReg =3D true;
+    }
     // The register must be in the same register class as the first.
     if (!RC->contains(Reg))
       return Error(RegLoc, "invalid register in register list");
     // List must be monotonically increasing.
-    if (getARMRegisterNumbering(Reg) <=3D getARMRegisterNumbering(OldReg))
-      return Error(RegLoc, "register list not in ascending order");
+    if (getARMRegisterNumbering(Reg) < getARMRegisterNumbering(OldReg)) {
+      if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
+        Warning(RegLoc, "register list not in ascending order");
+      else
+        return Error(RegLoc, "register list not in ascending order");
+    }
+    if (getARMRegisterNumbering(Reg) =3D=3D getARMRegisterNumbering(OldReg=
)) {
+      Warning(RegLoc, "duplicated register (" + RegTok.getString() +
+              ") in register list");
+      continue;
+    }
     // VFP register lists must also be contiguous.
     // It's OK to use the enumeration values directly here rather, as the
     // VFP register classes have the enum sorted properly.
@@ -2252,6 +2914,8 @@
         Reg !=3D OldReg + 1)
       return Error(RegLoc, "non-contiguous register range");
     Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
+    if (isQReg)
+      Registers.push_back(std::pair<unsigned, SMLoc>(++Reg, RegLoc));
   }
=20
   SMLoc E =3D Parser.getTok().getLoc();
@@ -2259,10 +2923,319 @@
     return Error(E, "'}' expected");
   Parser.Lex(); // Eat '}' token.
=20
+  // Push the register list operand.
   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
+
+  // The ARM system instruction variants for LDM/STM have a '^' token here.
+  if (Parser.getTok().is(AsmToken::Caret)) {
+    Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc(=
)));
+    Parser.Lex(); // Eat '^' token.
+  }
+
   return false;
 }
=20
+// Helper function to parse the lane index for vector lists.
+ARMAsmParser::OperandMatchResultTy ARMAsmParser::
+parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index) {
+  Index =3D 0; // Always return a defined index value.
+  if (Parser.getTok().is(AsmToken::LBrac)) {
+    Parser.Lex(); // Eat the '['.
+    if (Parser.getTok().is(AsmToken::RBrac)) {
+      // "Dn[]" is the 'all lanes' syntax.
+      LaneKind =3D AllLanes;
+      Parser.Lex(); // Eat the ']'.
+      return MatchOperand_Success;
+    }
+
+    // There's an optional '#' token here. Normally there wouldn't be, but
+    // inline assemble puts one in, and it's friendly to accept that.
+    if (Parser.getTok().is(AsmToken::Hash))
+      Parser.Lex(); // Eat the '#'
+
+    const MCExpr *LaneIndex;
+    SMLoc Loc =3D Parser.getTok().getLoc();
+    if (getParser().ParseExpression(LaneIndex)) {
+      Error(Loc, "illegal expression");
+      return MatchOperand_ParseFail;
+    }
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(LaneIndex);
+    if (!CE) {
+      Error(Loc, "lane index must be empty or an integer");
+      return MatchOperand_ParseFail;
+    }
+    if (Parser.getTok().isNot(AsmToken::RBrac)) {
+      Error(Parser.getTok().getLoc(), "']' expected");
+      return MatchOperand_ParseFail;
+    }
+    Parser.Lex(); // Eat the ']'.
+    int64_t Val =3D CE->getValue();
+
+    // FIXME: Make this range check context sensitive for .8, .16, .32.
+    if (Val < 0 || Val > 7) {
+      Error(Parser.getTok().getLoc(), "lane index out of range");
+      return MatchOperand_ParseFail;
+    }
+    Index =3D Val;
+    LaneKind =3D IndexedLane;
+    return MatchOperand_Success;
+  }
+  LaneKind =3D NoLanes;
+  return MatchOperand_Success;
+}
+
+// parse a vector register list
+ARMAsmParser::OperandMatchResultTy ARMAsmParser::
+parseVectorList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
+  VectorLaneTy LaneKind;
+  unsigned LaneIndex;
+  SMLoc S =3D Parser.getTok().getLoc();
+  // As an extension (to match gas), support a plain D register or Q regis=
ter
+  // (without encosing curly braces) as a single or double entry list,
+  // respectively.
+  if (Parser.getTok().is(AsmToken::Identifier)) {
+    int Reg =3D tryParseRegister();
+    if (Reg =3D=3D -1)
+      return MatchOperand_NoMatch;
+    SMLoc E =3D Parser.getTok().getLoc();
+    if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
+      OperandMatchResultTy Res =3D parseVectorLane(LaneKind, LaneIndex);
+      if (Res !=3D MatchOperand_Success)
+        return Res;
+      switch (LaneKind) {
+      case NoLanes:
+        E =3D Parser.getTok().getLoc();
+        Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, =
E));
+        break;
+      case AllLanes:
+        E =3D Parser.getTok().getLoc();
+        Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, fa=
lse,
+                                                                S, E));
+        break;
+      case IndexedLane:
+        Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
+                                                               LaneIndex,
+                                                               false, S, E=
));
+        break;
+      }
+      return MatchOperand_Success;
+    }
+    if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
+      Reg =3D getDRegFromQReg(Reg);
+      OperandMatchResultTy Res =3D parseVectorLane(LaneKind, LaneIndex);
+      if (Res !=3D MatchOperand_Success)
+        return Res;
+      switch (LaneKind) {
+      case NoLanes:
+        E =3D Parser.getTok().getLoc();
+        Reg =3D MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
+                                   &ARMMCRegisterClasses[ARM::DPairRegClas=
sID]);
+        Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, =
E));
+        break;
+      case AllLanes:
+        E =3D Parser.getTok().getLoc();
+        Reg =3D MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
+                                   &ARMMCRegisterClasses[ARM::DPairRegClas=
sID]);
+        Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, fa=
lse,
+                                                                S, E));
+        break;
+      case IndexedLane:
+        Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
+                                                               LaneIndex,
+                                                               false, S, E=
));
+        break;
+      }
+      return MatchOperand_Success;
+    }
+    Error(S, "vector register expected");
+    return MatchOperand_ParseFail;
+  }
+
+  if (Parser.getTok().isNot(AsmToken::LCurly))
+    return MatchOperand_NoMatch;
+
+  Parser.Lex(); // Eat '{' token.
+  SMLoc RegLoc =3D Parser.getTok().getLoc();
+
+  int Reg =3D tryParseRegister();
+  if (Reg =3D=3D -1) {
+    Error(RegLoc, "register expected");
+    return MatchOperand_ParseFail;
+  }
+  unsigned Count =3D 1;
+  int Spacing =3D 0;
+  unsigned FirstReg =3D Reg;
+  // The list is of D registers, but we also allow Q regs and just interpr=
et
+  // them as the two D sub-registers.
+  if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
+    FirstReg =3D Reg =3D getDRegFromQReg(Reg);
+    Spacing =3D 1; // double-spacing requires explicit D registers, otherw=
ise
+                 // it's ambiguous with four-register single spaced.
+    ++Reg;
+    ++Count;
+  }
+  if (parseVectorLane(LaneKind, LaneIndex) !=3D MatchOperand_Success)
+    return MatchOperand_ParseFail;
+
+  while (Parser.getTok().is(AsmToken::Comma) ||
+         Parser.getTok().is(AsmToken::Minus)) {
+    if (Parser.getTok().is(AsmToken::Minus)) {
+      if (!Spacing)
+        Spacing =3D 1; // Register range implies a single spaced list.
+      else if (Spacing =3D=3D 2) {
+        Error(Parser.getTok().getLoc(),
+              "sequential registers in double spaced list");
+        return MatchOperand_ParseFail;
+      }
+      Parser.Lex(); // Eat the minus.
+      SMLoc EndLoc =3D Parser.getTok().getLoc();
+      int EndReg =3D tryParseRegister();
+      if (EndReg =3D=3D -1) {
+        Error(EndLoc, "register expected");
+        return MatchOperand_ParseFail;
+      }
+      // Allow Q regs and just interpret them as the two D sub-registers.
+      if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
+        EndReg =3D getDRegFromQReg(EndReg) + 1;
+      // If the register is the same as the start reg, there's nothing
+      // more to do.
+      if (Reg =3D=3D EndReg)
+        continue;
+      // The register must be in the same register class as the first.
+      if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
+        Error(EndLoc, "invalid register in register list");
+        return MatchOperand_ParseFail;
+      }
+      // Ranges must go from low to high.
+      if (Reg > EndReg) {
+        Error(EndLoc, "bad range in register list");
+        return MatchOperand_ParseFail;
+      }
+      // Parse the lane specifier if present.
+      VectorLaneTy NextLaneKind;
+      unsigned NextLaneIndex;
+      if (parseVectorLane(NextLaneKind, NextLaneIndex) !=3D MatchOperand_S=
uccess)
+        return MatchOperand_ParseFail;
+      if (NextLaneKind !=3D LaneKind || LaneIndex !=3D NextLaneIndex) {
+        Error(EndLoc, "mismatched lane index in register list");
+        return MatchOperand_ParseFail;
+      }
+      EndLoc =3D Parser.getTok().getLoc();
+
+      // Add all the registers in the range to the register list.
+      Count +=3D EndReg - Reg;
+      Reg =3D EndReg;
+      continue;
+    }
+    Parser.Lex(); // Eat the comma.
+    RegLoc =3D Parser.getTok().getLoc();
+    int OldReg =3D Reg;
+    Reg =3D tryParseRegister();
+    if (Reg =3D=3D -1) {
+      Error(RegLoc, "register expected");
+      return MatchOperand_ParseFail;
+    }
+    // vector register lists must be contiguous.
+    // It's OK to use the enumeration values directly here rather, as the
+    // VFP register classes have the enum sorted properly.
+    //
+    // The list is of D registers, but we also allow Q regs and just inter=
pret
+    // them as the two D sub-registers.
+    if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
+      if (!Spacing)
+        Spacing =3D 1; // Register range implies a single spaced list.
+      else if (Spacing =3D=3D 2) {
+        Error(RegLoc,
+              "invalid register in double-spaced list (must be 'D' registe=
r')");
+        return MatchOperand_ParseFail;
+      }
+      Reg =3D getDRegFromQReg(Reg);
+      if (Reg !=3D OldReg + 1) {
+        Error(RegLoc, "non-contiguous register range");
+        return MatchOperand_ParseFail;
+      }
+      ++Reg;
+      Count +=3D 2;
+      // Parse the lane specifier if present.
+      VectorLaneTy NextLaneKind;
+      unsigned NextLaneIndex;
+      SMLoc EndLoc =3D Parser.getTok().getLoc();
+      if (parseVectorLane(NextLaneKind, NextLaneIndex) !=3D MatchOperand_S=
uccess)
+        return MatchOperand_ParseFail;
+      if (NextLaneKind !=3D LaneKind || LaneIndex !=3D NextLaneIndex) {
+        Error(EndLoc, "mismatched lane index in register list");
+        return MatchOperand_ParseFail;
+      }
+      continue;
+    }
+    // Normal D register.
+    // Figure out the register spacing (single or double) of the list if
+    // we don't know it already.
+    if (!Spacing)
+      Spacing =3D 1 + (Reg =3D=3D OldReg + 2);
+
+    // Just check that it's contiguous and keep going.
+    if (Reg !=3D OldReg + Spacing) {
+      Error(RegLoc, "non-contiguous register range");
+      return MatchOperand_ParseFail;
+    }
+    ++Count;
+    // Parse the lane specifier if present.
+    VectorLaneTy NextLaneKind;
+    unsigned NextLaneIndex;
+    SMLoc EndLoc =3D Parser.getTok().getLoc();
+    if (parseVectorLane(NextLaneKind, NextLaneIndex) !=3D MatchOperand_Suc=
cess)
+      return MatchOperand_ParseFail;
+    if (NextLaneKind !=3D LaneKind || LaneIndex !=3D NextLaneIndex) {
+      Error(EndLoc, "mismatched lane index in register list");
+      return MatchOperand_ParseFail;
+    }
+  }
+
+  SMLoc E =3D Parser.getTok().getLoc();
+  if (Parser.getTok().isNot(AsmToken::RCurly)) {
+    Error(E, "'}' expected");
+    return MatchOperand_ParseFail;
+  }
+  Parser.Lex(); // Eat '}' token.
+
+  switch (LaneKind) {
+  case NoLanes:
+    // Two-register operands have been converted to the
+    // composite register classes.
+    if (Count =3D=3D 2) {
+      const MCRegisterClass *RC =3D (Spacing =3D=3D 1) ?
+        &ARMMCRegisterClasses[ARM::DPairRegClassID] :
+        &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
+      FirstReg =3D MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
+    }
+
+    Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
+                                                    (Spacing =3D=3D 2), S,=
 E));
+    break;
+  case AllLanes:
+    // Two-register operands have been converted to the
+    // composite register classes.
+    if (Count =3D=3D 2) {
+      const MCRegisterClass *RC =3D (Spacing =3D=3D 1) ?
+        &ARMMCRegisterClasses[ARM::DPairRegClassID] :
+        &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
+      FirstReg =3D MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
+    }
+    Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Coun=
t,
+                                                            (Spacing =3D=
=3D 2),
+                                                            S, E));
+    break;
+  case IndexedLane:
+    Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
+                                                           LaneIndex,
+                                                           (Spacing =3D=3D=
 2),
+                                                           S, E));
+    break;
+  }
+  return MatchOperand_Success;
+}
+
 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
@@ -2337,7 +3310,8 @@
=20
   if (isMClass()) {
     // See ARMv6-M 10.1.1
-    unsigned FlagsVal =3D StringSwitch<unsigned>(Mask)
+    std::string Name =3D Mask.lower();
+    unsigned FlagsVal =3D StringSwitch<unsigned>(Name)
       .Case("apsr", 0)
       .Case("iapsr", 1)
       .Case("eapsr", 2)
@@ -2353,14 +3327,14 @@
       .Case("faultmask", 19)
       .Case("control", 20)
       .Default(~0U);
-   =20
+
     if (FlagsVal =3D=3D ~0U)
       return MatchOperand_NoMatch;
=20
     if (!hasV7Ops() && FlagsVal >=3D 17 && FlagsVal <=3D 19)
       // basepri, basepri_max and faultmask only valid for V7m.
       return MatchOperand_NoMatch;
-   =20
+
     Parser.Lex(); // Eat identifier token.
     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
     return MatchOperand_Success;
@@ -2369,7 +3343,7 @@
   // Split spec_reg from flag, example: CPSR_sxf =3D> "CPSR" and "sxf"
   size_t Start =3D 0, Next =3D Mask.find('_');
   StringRef Flags =3D "";
-  std::string SpecReg =3D LowercaseString(Mask.slice(Start, Next));
+  std::string SpecReg =3D Mask.slice(Start, Next).lower();
   if (Next !=3D StringRef::npos)
     Flags =3D Mask.slice(Next+1, Mask.size());
=20
@@ -2392,7 +3366,8 @@
         FlagsVal =3D 8; // No flag
     }
   } else if (SpecReg =3D=3D "cpsr" || SpecReg =3D=3D "spsr") {
-    if (Flags =3D=3D "all") // cpsr_all is an alias for cpsr_fc
+    // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
+    if (Flags =3D=3D "all" || Flags =3D=3D "")
       Flags =3D "fc";
     for (int i =3D 0, e =3D Flags.size(); i !=3D e; ++i) {
       unsigned Flag =3D StringSwitch<unsigned>(Flags.substr(i, 1))
@@ -2411,9 +3386,13 @@
   } else // No match for special register.
     return MatchOperand_NoMatch;
=20
-  // Special register without flags are equivalent to "fc" flags.
-  if (!FlagsVal)
-    FlagsVal =3D 0x9;
+  // Special register without flags is NOT equivalent to "fc" flags.
+  // NOTE: This is a divergence from gas' behavior.  Uncommenting the foll=
owing
+  // two lines would enable gas compatibility at the expense of breaking
+  // round-tripping.
+  //
+  // if (!FlagsVal)
+  //  FlagsVal =3D 0x9;
=20
   // Bit 4: Special Reg (cpsr, apsr =3D> 0; spsr =3D> 1)
   if (SpecReg =3D=3D "spsr")
@@ -2433,8 +3412,8 @@
     return MatchOperand_ParseFail;
   }
   StringRef ShiftName =3D Tok.getString();
-  std::string LowerOp =3D LowercaseString(Op);
-  std::string UpperOp =3D UppercaseString(Op);
+  std::string LowerOp =3D Op.lower();
+  std::string UpperOp =3D Op.upper();
   if (ShiftName !=3D LowerOp && ShiftName !=3D UpperOp) {
     Error(Parser.getTok().getLoc(), Op + " operand expected.");
     return MatchOperand_ParseFail;
@@ -2442,7 +3421,8 @@
   Parser.Lex(); // Eat shift type token.
=20
   // There must be a '#' and a shift amount.
-  if (Parser.getTok().isNot(AsmToken::Hash)) {
+  if (Parser.getTok().isNot(AsmToken::Hash) &&
+      Parser.getTok().isNot(AsmToken::Dollar)) {
     Error(Parser.getTok().getLoc(), "'#' expected");
     return MatchOperand_ParseFail;
   }
@@ -2520,7 +3500,8 @@
   Parser.Lex(); // Eat the operator.
=20
   // A '#' and a shift amount.
-  if (Parser.getTok().isNot(AsmToken::Hash)) {
+  if (Parser.getTok().isNot(AsmToken::Hash) &&
+      Parser.getTok().isNot(AsmToken::Dollar)) {
     Error(Parser.getTok().getLoc(), "'#' expected");
     return MatchOperand_ParseFail;
   }
@@ -2580,7 +3561,8 @@
   Parser.Lex(); // Eat the operator.
=20
   // A '#' and a rotate amount.
-  if (Parser.getTok().isNot(AsmToken::Hash)) {
+  if (Parser.getTok().isNot(AsmToken::Hash) &&
+      Parser.getTok().isNot(AsmToken::Dollar)) {
     Error(Parser.getTok().getLoc(), "'#' expected");
     return MatchOperand_ParseFail;
   }
@@ -2617,7 +3599,8 @@
 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
   SMLoc S =3D Parser.getTok().getLoc();
   // The bitfield descriptor is really two operands, the LSB and the width.
-  if (Parser.getTok().isNot(AsmToken::Hash)) {
+  if (Parser.getTok().isNot(AsmToken::Hash) &&
+      Parser.getTok().isNot(AsmToken::Dollar)) {
     Error(Parser.getTok().getLoc(), "'#' expected");
     return MatchOperand_ParseFail;
   }
@@ -2649,7 +3632,8 @@
     return MatchOperand_ParseFail;
   }
   Parser.Lex(); // Eat hash token.
-  if (Parser.getTok().isNot(AsmToken::Hash)) {
+  if (Parser.getTok().isNot(AsmToken::Hash) &&
+      Parser.getTok().isNot(AsmToken::Dollar)) {
     Error(Parser.getTok().getLoc(), "'#' expected");
     return MatchOperand_ParseFail;
   }
@@ -2743,7 +3727,8 @@
   SMLoc S =3D Tok.getLoc();
=20
   // Do immediates first, as we always parse those if we have a '#'.
-  if (Parser.getTok().is(AsmToken::Hash)) {
+  if (Parser.getTok().is(AsmToken::Hash) ||
+      Parser.getTok().is(AsmToken::Dollar)) {
     Parser.Lex(); // Eat the '#'.
     // Explicitly look for a '-', as we need to encode negative zero
     // differently.
@@ -3082,18 +4067,80 @@
   }
   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
   ((ARMOperand*)Operands[1])->addCCOutOperands(Inst, 1);
-  ((ARMOperand*)Operands[4])->addRegOperands(Inst, 1);
-  // If we have a three-operand form, use that, else the second source ope=
rand
-  // is just the destination operand again.
-  if (Operands.size() =3D=3D 6)
-    ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
-  else
-    Inst.addOperand(Inst.getOperand(0));
+  // If we have a three-operand form, make sure to set Rn to be the operand
+  // that isn't the same as Rd.
+  unsigned RegOp =3D 4;
+  if (Operands.size() =3D=3D 6 &&
+      ((ARMOperand*)Operands[4])->getReg() =3D=3D
+        ((ARMOperand*)Operands[3])->getReg())
+    RegOp =3D 5;
+  ((ARMOperand*)Operands[RegOp])->addRegOperands(Inst, 1);
+  Inst.addOperand(Inst.getOperand(0));
   ((ARMOperand*)Operands[2])->addCondCodeOperands(Inst, 2);
=20
   return true;
 }
=20
+bool ARMAsmParser::
+cvtVLDwbFixed(MCInst &Inst, unsigned Opcode,
+              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
+  // Vd
+  ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
+  // Create a writeback register dummy placeholder.
+  Inst.addOperand(MCOperand::CreateImm(0));
+  // Vn
+  ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
+  // pred
+  ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
+  return true;
+}
+
+bool ARMAsmParser::
+cvtVLDwbRegister(MCInst &Inst, unsigned Opcode,
+                 const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
+  // Vd
+  ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
+  // Create a writeback register dummy placeholder.
+  Inst.addOperand(MCOperand::CreateImm(0));
+  // Vn
+  ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
+  // Vm
+  ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
+  // pred
+  ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
+  return true;
+}
+
+bool ARMAsmParser::
+cvtVSTwbFixed(MCInst &Inst, unsigned Opcode,
+              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
+  // Create a writeback register dummy placeholder.
+  Inst.addOperand(MCOperand::CreateImm(0));
+  // Vn
+  ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
+  // Vt
+  ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
+  // pred
+  ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
+  return true;
+}
+
+bool ARMAsmParser::
+cvtVSTwbRegister(MCInst &Inst, unsigned Opcode,
+                 const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
+  // Create a writeback register dummy placeholder.
+  Inst.addOperand(MCOperand::CreateImm(0));
+  // Vn
+  ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
+  // Vm
+  ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
+  // Vt
+  ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
+  // pred
+  ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
+  return true;
+}
+
 /// Parse an ARM memory expression, return false if successful else return=
 true
 /// or an error.  The first token must be a '[' when called.
 bool ARMAsmParser::
@@ -3153,7 +4200,10 @@
     unsigned Align =3D 0;
     switch (CE->getValue()) {
     default:
-      return Error(E, "alignment specifier must be 64, 128, or 256 bits");
+      return Error(E,
+                   "alignment specifier must be 16, 32, 64, 128, or 256 bi=
ts");
+    case 16:  Align =3D 2; break;
+    case 32:  Align =3D 4; break;
     case 64:  Align =3D 8; break;
     case 128: Align =3D 16; break;
     case 256: Align =3D 32; break;
@@ -3182,9 +4232,13 @@
   }
=20
   // If we have a '#', it's an immediate offset, else assume it's a regist=
er
-  // offset.
-  if (Parser.getTok().is(AsmToken::Hash)) {
-    Parser.Lex(); // Eat the '#'.
+  // offset. Be friendly and also accept a plain integer (without a leading
+  // hash) for gas compatibility.
+  if (Parser.getTok().is(AsmToken::Hash) ||
+      Parser.getTok().is(AsmToken::Dollar) ||
+      Parser.getTok().is(AsmToken::Integer)) {
+    if (Parser.getTok().isNot(AsmToken::Integer))
+      Parser.Lex(); // Eat the '#'.
     E =3D Parser.getTok().getLoc();
=20
     bool isNegative =3D getParser().getTok().is(AsmToken::Minus);
@@ -3281,7 +4335,8 @@
   if (Tok.isNot(AsmToken::Identifier))
     return true;
   StringRef ShiftName =3D Tok.getString();
-  if (ShiftName =3D=3D "lsl" || ShiftName =3D=3D "LSL")
+  if (ShiftName =3D=3D "lsl" || ShiftName =3D=3D "LSL" ||
+      ShiftName =3D=3D "asl" || ShiftName =3D=3D "ASL")
     St =3D ARM_AM::lsl;
   else if (ShiftName =3D=3D "lsr" || ShiftName =3D=3D "LSR")
     St =3D ARM_AM::lsr;
@@ -3301,7 +4356,8 @@
     Loc =3D Parser.getTok().getLoc();
     // A '#' and a shift amount.
     const AsmToken &HashTok =3D Parser.getTok();
-    if (HashTok.isNot(AsmToken::Hash))
+    if (HashTok.isNot(AsmToken::Hash) &&
+        HashTok.isNot(AsmToken::Dollar))
       return Error(HashTok.getLoc(), "'#' expected");
     Parser.Lex(); // Eat hash token.
=20
@@ -3328,10 +4384,36 @@
 /// parseFPImm - A floating point immediate expression operand.
 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
 parseFPImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
+  // Anything that can accept a floating point constant as an operand
+  // needs to go through here, as the regular ParseExpression is
+  // integer only.
+  //
+  // This routine still creates a generic Immediate operand, containing
+  // a bitcast of the 64-bit floating point value. The various operands
+  // that accept floats can check whether the value is valid for them
+  // via the standard is*() predicates.
+
   SMLoc S =3D Parser.getTok().getLoc();
=20
-  if (Parser.getTok().isNot(AsmToken::Hash))
+  if (Parser.getTok().isNot(AsmToken::Hash) &&
+      Parser.getTok().isNot(AsmToken::Dollar))
     return MatchOperand_NoMatch;
+
+  // Disambiguate the VMOV forms that can accept an FP immediate.
+  // vmov.f32 <sreg>, #imm
+  // vmov.f64 <dreg>, #imm
+  // vmov.f32 <dreg>, #imm  @ vector f32x2
+  // vmov.f32 <qreg>, #imm  @ vector f32x4
+  //
+  // There are also the NEON VMOV instructions which expect an
+  // integer constant. Make sure we don't try to parse an FPImm
+  // for these:
+  // vmov.i{8|16|32|64} <dreg|qreg>, #imm
+  ARMOperand *TyOp =3D static_cast<ARMOperand*>(Operands[2]);
+  if (!TyOp->isToken() || (TyOp->getToken() !=3D ".f32" &&
+                           TyOp->getToken() !=3D ".f64"))
+    return MatchOperand_NoMatch;
+
   Parser.Lex(); // Eat the '#'.
=20
   // Handle negation, as that still comes through as a separate token.
@@ -3341,34 +4423,39 @@
     Parser.Lex();
   }
   const AsmToken &Tok =3D Parser.getTok();
+  SMLoc Loc =3D Tok.getLoc();
   if (Tok.is(AsmToken::Real)) {
-    APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
+    APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
     uint64_t IntVal =3D RealVal.bitcastToAPInt().getZExtValue();
     // If we had a '-' in front, toggle the sign bit.
-    IntVal ^=3D (uint64_t)isNegative << 63;
-    int Val =3D ARM_AM::getFP64Imm(APInt(64, IntVal));
+    IntVal ^=3D (uint64_t)isNegative << 31;
     Parser.Lex(); // Eat the token.
-    if (Val =3D=3D -1) {
-      TokError("floating point value out of range");
-      return MatchOperand_ParseFail;
-    }
-    Operands.push_back(ARMOperand::CreateFPImm(Val, S, getContext()));
+    Operands.push_back(ARMOperand::CreateImm(
+          MCConstantExpr::Create(IntVal, getContext()),
+          S, Parser.getTok().getLoc()));
     return MatchOperand_Success;
   }
+  // Also handle plain integers. Instructions which allow floating point
+  // immediates also allow a raw encoded 8-bit value.
   if (Tok.is(AsmToken::Integer)) {
     int64_t Val =3D Tok.getIntVal();
     Parser.Lex(); // Eat the token.
     if (Val > 255 || Val < 0) {
-      TokError("encoded floating point value out of range");
+      Error(Loc, "encoded floating point value out of range");
       return MatchOperand_ParseFail;
     }
-    Operands.push_back(ARMOperand::CreateFPImm(Val, S, getContext()));
+    double RealVal =3D ARM_AM::getFPImmFloat(Val);
+    Val =3D APFloat(APFloat::IEEEdouble, RealVal).bitcastToAPInt().getZExt=
Value();
+    Operands.push_back(ARMOperand::CreateImm(
+        MCConstantExpr::Create(Val, getContext()), S,
+        Parser.getTok().getLoc()));
     return MatchOperand_Success;
   }
=20
-  TokError("invalid floating point immediate");
+  Error(Loc, "invalid floating point immediate");
   return MatchOperand_ParseFail;
 }
+
 /// Parse a arm instruction operand.  For now this parses the operand rega=
rdless
 /// of the mnemonic.
 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Oper=
ands,
@@ -3391,7 +4478,6 @@
     Error(Parser.getTok().getLoc(), "unexpected token in operand");
     return true;
   case AsmToken::Identifier: {
-    // If this is VMRS, check for the apsr_nzcv operand.
     if (!tryParseRegisterWithWriteBack(Operands))
       return false;
     int Res =3D tryParseShiftRegister(Operands);
@@ -3399,17 +4485,21 @@
       return false;
     else if (Res =3D=3D -1) // irrecoverable error
       return true;
-    if (Mnemonic =3D=3D "vmrs" && Parser.getTok().getString() =3D=3D "apsr=
_nzcv") {
+    // If this is VMRS, check for the apsr_nzcv operand.
+    if (Mnemonic =3D=3D "vmrs" &&
+        Parser.getTok().getString().equals_lower("apsr_nzcv")) {
       S =3D Parser.getTok().getLoc();
       Parser.Lex();
-      Operands.push_back(ARMOperand::CreateToken("apsr_nzcv", S));
+      Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
       return false;
     }
=20
     // Fall though for the Identifier case that is not a register or a
     // special name.
   }
+  case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
   case AsmToken::Integer: // things like 1f and 2b as a branch targets
+  case AsmToken::String:  // quoted label names.
   case AsmToken::Dot: {   // . as a branch target
     // This was not a register so parse other operands that start with an
     // identifier (like labels) as expressions and create them as immediat=
es.
@@ -3425,6 +4515,7 @@
     return parseMemory(Operands);
   case AsmToken::LCurly:
     return parseRegisterList(Operands);
+  case AsmToken::Dollar:
   case AsmToken::Hash: {
     // #42 -> immediate.
     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
@@ -3435,13 +4526,11 @@
     if (getParser().ParseExpression(ImmVal))
       return true;
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(ImmVal);
-    if (!CE) {
-      Error(S, "constant expression expected");
-      return MatchOperand_ParseFail;
+    if (CE) {
+      int32_t Val =3D CE->getValue();
+      if (isNegative && Val =3D=3D 0)
+        ImmVal =3D MCConstantExpr::Create(INT32_MIN, getContext());
     }
-    int32_t Val =3D CE->getValue();
-    if (isNegative && Val =3D=3D 0)
-      ImmVal =3D MCConstantExpr::Create(INT32_MIN, getContext());
     E =3D SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
     return false;
@@ -3524,7 +4613,8 @@
       Mnemonic =3D=3D "vcge"  || Mnemonic =3D=3D "vclt"   || Mnemonic =3D=
=3D "vacgt" ||
       Mnemonic =3D=3D "vcgt"  || Mnemonic =3D=3D "vcle"   || Mnemonic =3D=
=3D "smlal" ||
       Mnemonic =3D=3D "umaal" || Mnemonic =3D=3D "umlal"  || Mnemonic =3D=
=3D "vabal" ||
-      Mnemonic =3D=3D "vmlal" || Mnemonic =3D=3D "vpadal" || Mnemonic =3D=
=3D "vqdmlal")
+      Mnemonic =3D=3D "vmlal" || Mnemonic =3D=3D "vpadal" || Mnemonic =3D=
=3D "vqdmlal" ||
+      Mnemonic =3D=3D "fmuls")
     return Mnemonic;
=20
   // First, split out any predication code. Ignore mnemonics we know aren't
@@ -3565,7 +4655,11 @@
         Mnemonic =3D=3D "mrs" || Mnemonic =3D=3D "smmls" || Mnemonic =3D=
=3D "vabs" ||
         Mnemonic =3D=3D "vcls" || Mnemonic =3D=3D "vmls" || Mnemonic =3D=
=3D "vmrs" ||
         Mnemonic =3D=3D "vnmls" || Mnemonic =3D=3D "vqabs" || Mnemonic =3D=
=3D "vrecps" ||
-        Mnemonic =3D=3D "vrsqrts" || Mnemonic =3D=3D "srs" ||
+        Mnemonic =3D=3D "vrsqrts" || Mnemonic =3D=3D "srs" || Mnemonic =3D=
=3D "flds" ||
+        Mnemonic =3D=3D "fmrs" || Mnemonic =3D=3D "fsqrts" || Mnemonic =3D=
=3D "fsubs" ||
+        Mnemonic =3D=3D "fsts" || Mnemonic =3D=3D "fcpys" || Mnemonic =3D=
=3D "fdivs" ||
+        Mnemonic =3D=3D "fmuls" || Mnemonic =3D=3D "fcmps" || Mnemonic =3D=
=3D "fcmpzs" ||
+        Mnemonic =3D=3D "vfms" || Mnemonic =3D=3D "vfnms" ||
         (Mnemonic =3D=3D "movs" && isThumb()))) {
     Mnemonic =3D Mnemonic.slice(0, Mnemonic.size() - 1);
     CarrySetting =3D true;
@@ -3609,6 +4703,7 @@
       Mnemonic =3D=3D "orr" || Mnemonic =3D=3D "mvn" ||
       Mnemonic =3D=3D "rsb" || Mnemonic =3D=3D "rsc" || Mnemonic =3D=3D "o=
rn" ||
       Mnemonic =3D=3D "sbc" || Mnemonic =3D=3D "eor" || Mnemonic =3D=3D "n=
eg" ||
+      Mnemonic =3D=3D "vfm" || Mnemonic =3D=3D "vfnm" ||
       (!isThumb() && (Mnemonic =3D=3D "smull" || Mnemonic =3D=3D "mov" ||
                       Mnemonic =3D=3D "mla" || Mnemonic =3D=3D "smlal" ||
                       Mnemonic =3D=3D "umlal" || Mnemonic =3D=3D "umull"))=
) {
@@ -3677,7 +4772,7 @@
       static_cast<ARMOperand*>(Operands[4])->isReg() &&
       static_cast<ARMOperand*>(Operands[4])->getReg() =3D=3D ARM::SP &&
       static_cast<ARMOperand*>(Operands[1])->getReg() =3D=3D 0 &&
-      (static_cast<ARMOperand*>(Operands[5])->isReg() ||
+      ((Mnemonic =3D=3D "add" &&static_cast<ARMOperand*>(Operands[5])->isR=
eg()) ||
        static_cast<ARMOperand*>(Operands[5])->isImm0_1020s4()))
     return true;
   // For Thumb2, add/sub immediate does not have a cc_out operand for the
@@ -3694,9 +4789,11 @@
     //
     // If either register is a high reg, it's either one of the SP
     // variants (handled above) or a 32-bit encoding, so we just
-    // check against T3.
+    // check against T3. If the second register is the PC, this is an
+    // alternate form of ADR, which uses encoding T4, so check for that to=
o.
     if ((!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()=
) ||
          !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()=
)) &&
+        static_cast<ARMOperand*>(Operands[4])->getReg() !=3D ARM::PC &&
         static_cast<ARMOperand*>(Operands[5])->isT2SOImm())
       return false;
     // If both registers are low, we're in an IT block, and the immediate =
is
@@ -3726,6 +4823,7 @@
       // remove the cc_out operand.
       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) =
||
        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) =
||
+       !isARMLowRegister(static_cast<ARMOperand*>(Operands[5])->getReg()) =
||
        !inITBlock() ||
        (static_cast<ARMOperand*>(Operands[3])->getReg() !=3D
         static_cast<ARMOperand*>(Operands[5])->getReg() &&
@@ -3733,6 +4831,20 @@
         static_cast<ARMOperand*>(Operands[4])->getReg())))
     return true;
=20
+  // Also check the 'mul' syntax variant that doesn't specify an explicit
+  // destination register.
+  if (isThumbTwo() && Mnemonic =3D=3D "mul" && Operands.size() =3D=3D 5 &&
+      static_cast<ARMOperand*>(Operands[1])->getReg() =3D=3D 0 &&
+      static_cast<ARMOperand*>(Operands[3])->isReg() &&
+      static_cast<ARMOperand*>(Operands[4])->isReg() &&
+      // If the registers aren't low regs  or the cc_out operand is zero
+      // outside of an IT block, we have to use the 32-bit encoding, so
+      // remove the cc_out operand.
+      (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) =
||
+       !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) =
||
+       !inITBlock()))
+    return true;
+
=20
=20
   // Register-register 'add/sub' for thumb does not have a cc_out operand
@@ -3744,15 +4856,52 @@
       (Operands.size() =3D=3D 5 || Operands.size() =3D=3D 6) &&
       static_cast<ARMOperand*>(Operands[3])->isReg() &&
       static_cast<ARMOperand*>(Operands[3])->getReg() =3D=3D ARM::SP &&
-      static_cast<ARMOperand*>(Operands[1])->getReg() =3D=3D 0)
+      static_cast<ARMOperand*>(Operands[1])->getReg() =3D=3D 0 &&
+      (static_cast<ARMOperand*>(Operands[4])->isImm() ||
+       (Operands.size() =3D=3D 6 &&
+        static_cast<ARMOperand*>(Operands[5])->isImm())))
     return true;
=20
   return false;
 }
=20
+static bool isDataTypeToken(StringRef Tok) {
+  return Tok =3D=3D ".8" || Tok =3D=3D ".16" || Tok =3D=3D ".32" || Tok =
=3D=3D ".64" ||
+    Tok =3D=3D ".i8" || Tok =3D=3D ".i16" || Tok =3D=3D ".i32" || Tok =3D=
=3D ".i64" ||
+    Tok =3D=3D ".u8" || Tok =3D=3D ".u16" || Tok =3D=3D ".u32" || Tok =3D=
=3D ".u64" ||
+    Tok =3D=3D ".s8" || Tok =3D=3D ".s16" || Tok =3D=3D ".s32" || Tok =3D=
=3D ".s64" ||
+    Tok =3D=3D ".p8" || Tok =3D=3D ".p16" || Tok =3D=3D ".f32" || Tok =3D=
=3D ".f64" ||
+    Tok =3D=3D ".f" || Tok =3D=3D ".d";
+}
+
+// FIXME: This bit should probably be handled via an explicit match class
+// in the .td files that matches the suffix instead of having it be
+// a literal string token the way it is now.
+static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
+  return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
+}
+
+static void applyMnemonicAliases(StringRef &Mnemonic, unsigned Features);
 /// Parse an arm instruction mnemonic followed by its operands.
 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
                                SmallVectorImpl<MCParsedAsmOperand*> &Opera=
nds) {
+  // Apply mnemonic aliases before doing anything else, as the destination
+  // mnemnonic may include suffices and we want to handle them normally.
+  // The generic tblgen'erated code does this later, at the start of
+  // MatchInstructionImpl(), but that's too late for aliases that include
+  // any sort of suffix.
+  unsigned AvailableFeatures =3D getAvailableFeatures();
+  applyMnemonicAliases(Name, AvailableFeatures);
+
+  // First check for the ARM-specific .req directive.
+  if (Parser.getTok().is(AsmToken::Identifier) &&
+      Parser.getTok().getIdentifier() =3D=3D ".req") {
+    parseDirectiveReq(Name, NameLoc);
+    // We always return 'error' for this, as we're done with this
+    // statement and don't need to match the 'instruction."
+    return true;
+  }
+
   // Create the leading tokens for the mnemonic, split by '.' characters.
   size_t Start =3D 0, Next =3D Name.find('.');
   StringRef Mnemonic =3D Name.slice(Start, Next);
@@ -3854,9 +5003,12 @@
     Next =3D Name.find('.', Start + 1);
     StringRef ExtraToken =3D Name.slice(Start, Next);
=20
-    // For now, we're only parsing Thumb1 (for the most part), so
-    // just ignore ".n" qualifiers. We'll use them to restrict
-    // matching when we do Thumb2.
+    // Some NEON instructions have an optional datatype suffix that is
+    // completely ignored. Check for that.
+    if (isDataTypeToken(ExtraToken) &&
+        doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
+      continue;
+
     if (ExtraToken !=3D ".n") {
       SMLoc Loc =3D SMLoc::getFromPointer(NameLoc.getPointer() + Start);
       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
@@ -3941,12 +5093,21 @@
     }
   }
   // Similarly, the Thumb1 "RSB" instruction has a literal "#0" on the
-  // end. Convert it to a token here.
+  // end. Convert it to a token here. Take care not to convert those
+  // that should hit the Thumb2 encoding.
   if (Mnemonic =3D=3D "rsb" && isThumb() && Operands.size() =3D=3D 6 &&
+      static_cast<ARMOperand*>(Operands[3])->isReg() &&
+      static_cast<ARMOperand*>(Operands[4])->isReg() &&
       static_cast<ARMOperand*>(Operands[5])->isImm()) {
     ARMOperand *Op =3D static_cast<ARMOperand*>(Operands[5]);
     const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(Op->getImm());
-    if (CE && CE->getValue() =3D=3D 0) {
+    if (CE && CE->getValue() =3D=3D 0 &&
+        (isThumbOne() ||
+         // The cc_out operand matches the IT block.
+         ((inITBlock() !=3D CarrySetting) &&
+         // Neither register operand is a high register.
+         (isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()=
) &&
+          isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()=
))))){
       Operands.erase(Operands.begin() + 5);
       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
       delete Op;
@@ -3990,9 +5151,9 @@
 // the ARMInsts array) instead. Getting that here requires awkward
 // API changes, though. Better way?
 namespace llvm {
-extern MCInstrDesc ARMInsts[];
+extern const MCInstrDesc ARMInsts[];
 }
-static MCInstrDesc &getInstDesc(unsigned Opcode) {
+static const MCInstrDesc &getInstDesc(unsigned Opcode) {
   return ARMInsts[Opcode];
 }
=20
@@ -4000,13 +5161,14 @@
 bool ARMAsmParser::
 validateInstruction(MCInst &Inst,
                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
-  MCInstrDesc &MCID =3D getInstDesc(Inst.getOpcode());
+  const MCInstrDesc &MCID =3D getInstDesc(Inst.getOpcode());
   SMLoc Loc =3D Operands[0]->getStartLoc();
   // Check the IT block state first.
-  // NOTE: In Thumb mode, the BKPT instruction has the interesting propert=
y of
-  // being allowed in IT blocks, but not being predicable.  It just always
+  // NOTE: BKPT instruction has the interesting property of being
+  // allowed in IT blocks, but not being predicable.  It just always
   // executes.
-  if (inITBlock() && Inst.getOpcode() !=3D ARM::tBKPT) {
+  if (inITBlock() && Inst.getOpcode() !=3D ARM::tBKPT &&
+      Inst.getOpcode() !=3D ARM::BKPT) {
     unsigned bit =3D 1;
     if (ITState.FirstCond)
       ITState.FirstCond =3D false;
@@ -4115,16 +5277,21 @@
                    "in register list");
     break;
   }
+  // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
+  // so only issue a diagnostic for thumb1. The instructions will be
+  // switched to the t2 encodings in processInstruction() if necessary.
   case ARM::tPOP: {
     bool listContainsBase;
-    if (checkLowRegisterList(Inst, 3, 0, ARM::PC, listContainsBase))
+    if (checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase) &&
+        !isThumbTwo())
       return Error(Operands[2]->getStartLoc(),
                    "registers must be in range r0-r7 or pc");
     break;
   }
   case ARM::tPUSH: {
     bool listContainsBase;
-    if (checkLowRegisterList(Inst, 3, 0, ARM::LR, listContainsBase))
+    if (checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase) &&
+        !isThumbTwo())
       return Error(Operands[2]->getStartLoc(),
                    "registers must be in range r0-r7 or lr");
     break;
@@ -4141,10 +5308,1553 @@
   return false;
 }
=20
-void ARMAsmParser::
+static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
+  switch(Opc) {
+  default: llvm_unreachable("unexpected opcode!");
+  // VST1LN
+  case ARM::VST1LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VST1LNd8_UP=
D;
+  case ARM::VST1LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST1LNd16_U=
PD;
+  case ARM::VST1LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VST1LNd32_U=
PD;
+  case ARM::VST1LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VST1LNd8=
_UPD;
+  case ARM::VST1LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VST1LNd1=
6_UPD;
+  case ARM::VST1LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VST1LNd3=
2_UPD;
+  case ARM::VST1LNdAsm_8:  Spacing =3D 1; return ARM::VST1LNd8;
+  case ARM::VST1LNdAsm_16: Spacing =3D 1; return ARM::VST1LNd16;
+  case ARM::VST1LNdAsm_32: Spacing =3D 1; return ARM::VST1LNd32;
+
+  // VST2LN
+  case ARM::VST2LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VST2LNd8_UP=
D;
+  case ARM::VST2LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST2LNd16_U=
PD;
+  case ARM::VST2LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VST2LNd32_U=
PD;
+  case ARM::VST2LNqWB_fixed_Asm_16: Spacing =3D 2; return ARM::VST2LNq16_U=
PD;
+  case ARM::VST2LNqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VST2LNq32_U=
PD;
+
+  case ARM::VST2LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VST2LNd8=
_UPD;
+  case ARM::VST2LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VST2LNd1=
6_UPD;
+  case ARM::VST2LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VST2LNd3=
2_UPD;
+  case ARM::VST2LNqWB_register_Asm_16: Spacing =3D 2; return ARM::VST2LNq1=
6_UPD;
+  case ARM::VST2LNqWB_register_Asm_32: Spacing =3D 2; return ARM::VST2LNq3=
2_UPD;
+
+  case ARM::VST2LNdAsm_8:  Spacing =3D 1; return ARM::VST2LNd8;
+  case ARM::VST2LNdAsm_16: Spacing =3D 1; return ARM::VST2LNd16;
+  case ARM::VST2LNdAsm_32: Spacing =3D 1; return ARM::VST2LNd32;
+  case ARM::VST2LNqAsm_16: Spacing =3D 2; return ARM::VST2LNq16;
+  case ARM::VST2LNqAsm_32: Spacing =3D 2; return ARM::VST2LNq32;
+
+  // VST3LN
+  case ARM::VST3LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VST3LNd8_UP=
D;
+  case ARM::VST3LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST3LNd16_U=
PD;
+  case ARM::VST3LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VST3LNd32_U=
PD;
+  case ARM::VST3LNqWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST3LNq16_U=
PD;
+  case ARM::VST3LNqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VST3LNq32_U=
PD;
+  case ARM::VST3LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VST3LNd8=
_UPD;
+  case ARM::VST3LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VST3LNd1=
6_UPD;
+  case ARM::VST3LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VST3LNd3=
2_UPD;
+  case ARM::VST3LNqWB_register_Asm_16: Spacing =3D 2; return ARM::VST3LNq1=
6_UPD;
+  case ARM::VST3LNqWB_register_Asm_32: Spacing =3D 2; return ARM::VST3LNq3=
2_UPD;
+  case ARM::VST3LNdAsm_8:  Spacing =3D 1; return ARM::VST3LNd8;
+  case ARM::VST3LNdAsm_16: Spacing =3D 1; return ARM::VST3LNd16;
+  case ARM::VST3LNdAsm_32: Spacing =3D 1; return ARM::VST3LNd32;
+  case ARM::VST3LNqAsm_16: Spacing =3D 2; return ARM::VST3LNq16;
+  case ARM::VST3LNqAsm_32: Spacing =3D 2; return ARM::VST3LNq32;
+
+  // VST3
+  case ARM::VST3dWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VST3d8_UPD;
+  case ARM::VST3dWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST3d16_UPD;
+  case ARM::VST3dWB_fixed_Asm_32: Spacing =3D 1; return ARM::VST3d32_UPD;
+  case ARM::VST3qWB_fixed_Asm_8:  Spacing =3D 2; return ARM::VST3q8_UPD;
+  case ARM::VST3qWB_fixed_Asm_16: Spacing =3D 2; return ARM::VST3q16_UPD;
+  case ARM::VST3qWB_fixed_Asm_32: Spacing =3D 2; return ARM::VST3q32_UPD;
+  case ARM::VST3dWB_register_Asm_8:  Spacing =3D 1; return ARM::VST3d8_UPD;
+  case ARM::VST3dWB_register_Asm_16: Spacing =3D 1; return ARM::VST3d16_UP=
D;
+  case ARM::VST3dWB_register_Asm_32: Spacing =3D 1; return ARM::VST3d32_UP=
D;
+  case ARM::VST3qWB_register_Asm_8:  Spacing =3D 2; return ARM::VST3q8_UPD;
+  case ARM::VST3qWB_register_Asm_16: Spacing =3D 2; return ARM::VST3q16_UP=
D;
+  case ARM::VST3qWB_register_Asm_32: Spacing =3D 2; return ARM::VST3q32_UP=
D;
+  case ARM::VST3dAsm_8:  Spacing =3D 1; return ARM::VST3d8;
+  case ARM::VST3dAsm_16: Spacing =3D 1; return ARM::VST3d16;
+  case ARM::VST3dAsm_32: Spacing =3D 1; return ARM::VST3d32;
+  case ARM::VST3qAsm_8:  Spacing =3D 2; return ARM::VST3q8;
+  case ARM::VST3qAsm_16: Spacing =3D 2; return ARM::VST3q16;
+  case ARM::VST3qAsm_32: Spacing =3D 2; return ARM::VST3q32;
+
+  // VST4LN
+  case ARM::VST4LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VST4LNd8_UP=
D;
+  case ARM::VST4LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST4LNd16_U=
PD;
+  case ARM::VST4LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VST4LNd32_U=
PD;
+  case ARM::VST4LNqWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST4LNq16_U=
PD;
+  case ARM::VST4LNqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VST4LNq32_U=
PD;
+  case ARM::VST4LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VST4LNd8=
_UPD;
+  case ARM::VST4LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VST4LNd1=
6_UPD;
+  case ARM::VST4LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VST4LNd3=
2_UPD;
+  case ARM::VST4LNqWB_register_Asm_16: Spacing =3D 2; return ARM::VST4LNq1=
6_UPD;
+  case ARM::VST4LNqWB_register_Asm_32: Spacing =3D 2; return ARM::VST4LNq3=
2_UPD;
+  case ARM::VST4LNdAsm_8:  Spacing =3D 1; return ARM::VST4LNd8;
+  case ARM::VST4LNdAsm_16: Spacing =3D 1; return ARM::VST4LNd16;
+  case ARM::VST4LNdAsm_32: Spacing =3D 1; return ARM::VST4LNd32;
+  case ARM::VST4LNqAsm_16: Spacing =3D 2; return ARM::VST4LNq16;
+  case ARM::VST4LNqAsm_32: Spacing =3D 2; return ARM::VST4LNq32;
+
+  // VST4
+  case ARM::VST4dWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VST4d8_UPD;
+  case ARM::VST4dWB_fixed_Asm_16: Spacing =3D 1; return ARM::VST4d16_UPD;
+  case ARM::VST4dWB_fixed_Asm_32: Spacing =3D 1; return ARM::VST4d32_UPD;
+  case ARM::VST4qWB_fixed_Asm_8:  Spacing =3D 2; return ARM::VST4q8_UPD;
+  case ARM::VST4qWB_fixed_Asm_16: Spacing =3D 2; return ARM::VST4q16_UPD;
+  case ARM::VST4qWB_fixed_Asm_32: Spacing =3D 2; return ARM::VST4q32_UPD;
+  case ARM::VST4dWB_register_Asm_8:  Spacing =3D 1; return ARM::VST4d8_UPD;
+  case ARM::VST4dWB_register_Asm_16: Spacing =3D 1; return ARM::VST4d16_UP=
D;
+  case ARM::VST4dWB_register_Asm_32: Spacing =3D 1; return ARM::VST4d32_UP=
D;
+  case ARM::VST4qWB_register_Asm_8:  Spacing =3D 2; return ARM::VST4q8_UPD;
+  case ARM::VST4qWB_register_Asm_16: Spacing =3D 2; return ARM::VST4q16_UP=
D;
+  case ARM::VST4qWB_register_Asm_32: Spacing =3D 2; return ARM::VST4q32_UP=
D;
+  case ARM::VST4dAsm_8:  Spacing =3D 1; return ARM::VST4d8;
+  case ARM::VST4dAsm_16: Spacing =3D 1; return ARM::VST4d16;
+  case ARM::VST4dAsm_32: Spacing =3D 1; return ARM::VST4d32;
+  case ARM::VST4qAsm_8:  Spacing =3D 2; return ARM::VST4q8;
+  case ARM::VST4qAsm_16: Spacing =3D 2; return ARM::VST4q16;
+  case ARM::VST4qAsm_32: Spacing =3D 2; return ARM::VST4q32;
+  }
+}
+
+static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
+  switch(Opc) {
+  default: llvm_unreachable("unexpected opcode!");
+  // VLD1LN
+  case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD1LNd8_UP=
D;
+  case ARM::VLD1LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD1LNd16_U=
PD;
+  case ARM::VLD1LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD1LNd32_U=
PD;
+  case ARM::VLD1LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD1LNd8=
_UPD;
+  case ARM::VLD1LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VLD1LNd1=
6_UPD;
+  case ARM::VLD1LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VLD1LNd3=
2_UPD;
+  case ARM::VLD1LNdAsm_8:  Spacing =3D 1; return ARM::VLD1LNd8;
+  case ARM::VLD1LNdAsm_16: Spacing =3D 1; return ARM::VLD1LNd16;
+  case ARM::VLD1LNdAsm_32: Spacing =3D 1; return ARM::VLD1LNd32;
+
+  // VLD2LN
+  case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD2LNd8_UP=
D;
+  case ARM::VLD2LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD2LNd16_U=
PD;
+  case ARM::VLD2LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD2LNd32_U=
PD;
+  case ARM::VLD2LNqWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD2LNq16_U=
PD;
+  case ARM::VLD2LNqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VLD2LNq32_U=
PD;
+  case ARM::VLD2LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD2LNd8=
_UPD;
+  case ARM::VLD2LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VLD2LNd1=
6_UPD;
+  case ARM::VLD2LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VLD2LNd3=
2_UPD;
+  case ARM::VLD2LNqWB_register_Asm_16: Spacing =3D 2; return ARM::VLD2LNq1=
6_UPD;
+  case ARM::VLD2LNqWB_register_Asm_32: Spacing =3D 2; return ARM::VLD2LNq3=
2_UPD;
+  case ARM::VLD2LNdAsm_8:  Spacing =3D 1; return ARM::VLD2LNd8;
+  case ARM::VLD2LNdAsm_16: Spacing =3D 1; return ARM::VLD2LNd16;
+  case ARM::VLD2LNdAsm_32: Spacing =3D 1; return ARM::VLD2LNd32;
+  case ARM::VLD2LNqAsm_16: Spacing =3D 2; return ARM::VLD2LNq16;
+  case ARM::VLD2LNqAsm_32: Spacing =3D 2; return ARM::VLD2LNq32;
+
+  // VLD3DUP
+  case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD3DUPd8_=
UPD;
+  case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD3DUPd16=
_UPD;
+  case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD3DUPd32=
_UPD;
+  case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing =3D 1; return ARM::VLD3DUPq8_U=
PD;
+  case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD3DUPq16=
_UPD;
+  case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VLD3DUPq32=
_UPD;
+  case ARM::VLD3DUPdWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD3DUP=
d8_UPD;
+  case ARM::VLD3DUPdWB_register_Asm_16: Spacing =3D 1; return ARM::VLD3DUP=
d16_UPD;
+  case ARM::VLD3DUPdWB_register_Asm_32: Spacing =3D 1; return ARM::VLD3DUP=
d32_UPD;
+  case ARM::VLD3DUPqWB_register_Asm_8: Spacing =3D 2; return ARM::VLD3DUPq=
8_UPD;
+  case ARM::VLD3DUPqWB_register_Asm_16: Spacing =3D 2; return ARM::VLD3DUP=
q16_UPD;
+  case ARM::VLD3DUPqWB_register_Asm_32: Spacing =3D 2; return ARM::VLD3DUP=
q32_UPD;
+  case ARM::VLD3DUPdAsm_8:  Spacing =3D 1; return ARM::VLD3DUPd8;
+  case ARM::VLD3DUPdAsm_16: Spacing =3D 1; return ARM::VLD3DUPd16;
+  case ARM::VLD3DUPdAsm_32: Spacing =3D 1; return ARM::VLD3DUPd32;
+  case ARM::VLD3DUPqAsm_8: Spacing =3D 2; return ARM::VLD3DUPq8;
+  case ARM::VLD3DUPqAsm_16: Spacing =3D 2; return ARM::VLD3DUPq16;
+  case ARM::VLD3DUPqAsm_32: Spacing =3D 2; return ARM::VLD3DUPq32;
+
+  // VLD3LN
+  case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD3LNd8_UP=
D;
+  case ARM::VLD3LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD3LNd16_U=
PD;
+  case ARM::VLD3LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD3LNd32_U=
PD;
+  case ARM::VLD3LNqWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD3LNq16_U=
PD;
+  case ARM::VLD3LNqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VLD3LNq32_U=
PD;
+  case ARM::VLD3LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD3LNd8=
_UPD;
+  case ARM::VLD3LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VLD3LNd1=
6_UPD;
+  case ARM::VLD3LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VLD3LNd3=
2_UPD;
+  case ARM::VLD3LNqWB_register_Asm_16: Spacing =3D 2; return ARM::VLD3LNq1=
6_UPD;
+  case ARM::VLD3LNqWB_register_Asm_32: Spacing =3D 2; return ARM::VLD3LNq3=
2_UPD;
+  case ARM::VLD3LNdAsm_8:  Spacing =3D 1; return ARM::VLD3LNd8;
+  case ARM::VLD3LNdAsm_16: Spacing =3D 1; return ARM::VLD3LNd16;
+  case ARM::VLD3LNdAsm_32: Spacing =3D 1; return ARM::VLD3LNd32;
+  case ARM::VLD3LNqAsm_16: Spacing =3D 2; return ARM::VLD3LNq16;
+  case ARM::VLD3LNqAsm_32: Spacing =3D 2; return ARM::VLD3LNq32;
+
+  // VLD3
+  case ARM::VLD3dWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD3d8_UPD;
+  case ARM::VLD3dWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD3d16_UPD;
+  case ARM::VLD3dWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD3d32_UPD;
+  case ARM::VLD3qWB_fixed_Asm_8:  Spacing =3D 2; return ARM::VLD3q8_UPD;
+  case ARM::VLD3qWB_fixed_Asm_16: Spacing =3D 2; return ARM::VLD3q16_UPD;
+  case ARM::VLD3qWB_fixed_Asm_32: Spacing =3D 2; return ARM::VLD3q32_UPD;
+  case ARM::VLD3dWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD3d8_UPD;
+  case ARM::VLD3dWB_register_Asm_16: Spacing =3D 1; return ARM::VLD3d16_UP=
D;
+  case ARM::VLD3dWB_register_Asm_32: Spacing =3D 1; return ARM::VLD3d32_UP=
D;
+  case ARM::VLD3qWB_register_Asm_8:  Spacing =3D 2; return ARM::VLD3q8_UPD;
+  case ARM::VLD3qWB_register_Asm_16: Spacing =3D 2; return ARM::VLD3q16_UP=
D;
+  case ARM::VLD3qWB_register_Asm_32: Spacing =3D 2; return ARM::VLD3q32_UP=
D;
+  case ARM::VLD3dAsm_8:  Spacing =3D 1; return ARM::VLD3d8;
+  case ARM::VLD3dAsm_16: Spacing =3D 1; return ARM::VLD3d16;
+  case ARM::VLD3dAsm_32: Spacing =3D 1; return ARM::VLD3d32;
+  case ARM::VLD3qAsm_8:  Spacing =3D 2; return ARM::VLD3q8;
+  case ARM::VLD3qAsm_16: Spacing =3D 2; return ARM::VLD3q16;
+  case ARM::VLD3qAsm_32: Spacing =3D 2; return ARM::VLD3q32;
+
+  // VLD4LN
+  case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD4LNd8_UP=
D;
+  case ARM::VLD4LNdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD4LNd16_U=
PD;
+  case ARM::VLD4LNdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD4LNd32_U=
PD;
+  case ARM::VLD4LNqWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD4LNq16_U=
PD;
+  case ARM::VLD4LNqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VLD4LNq32_U=
PD;
+  case ARM::VLD4LNdWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD4LNd8=
_UPD;
+  case ARM::VLD4LNdWB_register_Asm_16: Spacing =3D 1; return ARM::VLD4LNd1=
6_UPD;
+  case ARM::VLD4LNdWB_register_Asm_32: Spacing =3D 1; return ARM::VLD4LNd3=
2_UPD;
+  case ARM::VLD4LNqWB_register_Asm_16: Spacing =3D 2; return ARM::VLD4LNq1=
6_UPD;
+  case ARM::VLD4LNqWB_register_Asm_32: Spacing =3D 2; return ARM::VLD4LNq3=
2_UPD;
+  case ARM::VLD4LNdAsm_8:  Spacing =3D 1; return ARM::VLD4LNd8;
+  case ARM::VLD4LNdAsm_16: Spacing =3D 1; return ARM::VLD4LNd16;
+  case ARM::VLD4LNdAsm_32: Spacing =3D 1; return ARM::VLD4LNd32;
+  case ARM::VLD4LNqAsm_16: Spacing =3D 2; return ARM::VLD4LNq16;
+  case ARM::VLD4LNqAsm_32: Spacing =3D 2; return ARM::VLD4LNq32;
+
+  // VLD4DUP
+  case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD4DUPd8_=
UPD;
+  case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD4DUPd16=
_UPD;
+  case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD4DUPd32=
_UPD;
+  case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing =3D 1; return ARM::VLD4DUPq8_U=
PD;
+  case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD4DUPq16=
_UPD;
+  case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing =3D 2; return ARM::VLD4DUPq32=
_UPD;
+  case ARM::VLD4DUPdWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD4DUP=
d8_UPD;
+  case ARM::VLD4DUPdWB_register_Asm_16: Spacing =3D 1; return ARM::VLD4DUP=
d16_UPD;
+  case ARM::VLD4DUPdWB_register_Asm_32: Spacing =3D 1; return ARM::VLD4DUP=
d32_UPD;
+  case ARM::VLD4DUPqWB_register_Asm_8: Spacing =3D 2; return ARM::VLD4DUPq=
8_UPD;
+  case ARM::VLD4DUPqWB_register_Asm_16: Spacing =3D 2; return ARM::VLD4DUP=
q16_UPD;
+  case ARM::VLD4DUPqWB_register_Asm_32: Spacing =3D 2; return ARM::VLD4DUP=
q32_UPD;
+  case ARM::VLD4DUPdAsm_8:  Spacing =3D 1; return ARM::VLD4DUPd8;
+  case ARM::VLD4DUPdAsm_16: Spacing =3D 1; return ARM::VLD4DUPd16;
+  case ARM::VLD4DUPdAsm_32: Spacing =3D 1; return ARM::VLD4DUPd32;
+  case ARM::VLD4DUPqAsm_8: Spacing =3D 2; return ARM::VLD4DUPq8;
+  case ARM::VLD4DUPqAsm_16: Spacing =3D 2; return ARM::VLD4DUPq16;
+  case ARM::VLD4DUPqAsm_32: Spacing =3D 2; return ARM::VLD4DUPq32;
+
+  // VLD4
+  case ARM::VLD4dWB_fixed_Asm_8:  Spacing =3D 1; return ARM::VLD4d8_UPD;
+  case ARM::VLD4dWB_fixed_Asm_16: Spacing =3D 1; return ARM::VLD4d16_UPD;
+  case ARM::VLD4dWB_fixed_Asm_32: Spacing =3D 1; return ARM::VLD4d32_UPD;
+  case ARM::VLD4qWB_fixed_Asm_8:  Spacing =3D 2; return ARM::VLD4q8_UPD;
+  case ARM::VLD4qWB_fixed_Asm_16: Spacing =3D 2; return ARM::VLD4q16_UPD;
+  case ARM::VLD4qWB_fixed_Asm_32: Spacing =3D 2; return ARM::VLD4q32_UPD;
+  case ARM::VLD4dWB_register_Asm_8:  Spacing =3D 1; return ARM::VLD4d8_UPD;
+  case ARM::VLD4dWB_register_Asm_16: Spacing =3D 1; return ARM::VLD4d16_UP=
D;
+  case ARM::VLD4dWB_register_Asm_32: Spacing =3D 1; return ARM::VLD4d32_UP=
D;
+  case ARM::VLD4qWB_register_Asm_8:  Spacing =3D 2; return ARM::VLD4q8_UPD;
+  case ARM::VLD4qWB_register_Asm_16: Spacing =3D 2; return ARM::VLD4q16_UP=
D;
+  case ARM::VLD4qWB_register_Asm_32: Spacing =3D 2; return ARM::VLD4q32_UP=
D;
+  case ARM::VLD4dAsm_8:  Spacing =3D 1; return ARM::VLD4d8;
+  case ARM::VLD4dAsm_16: Spacing =3D 1; return ARM::VLD4d16;
+  case ARM::VLD4dAsm_32: Spacing =3D 1; return ARM::VLD4d32;
+  case ARM::VLD4qAsm_8:  Spacing =3D 2; return ARM::VLD4q8;
+  case ARM::VLD4qAsm_16: Spacing =3D 2; return ARM::VLD4q16;
+  case ARM::VLD4qAsm_32: Spacing =3D 2; return ARM::VLD4q32;
+  }
+}
+
+bool ARMAsmParser::
 processInstruction(MCInst &Inst,
                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
   switch (Inst.getOpcode()) {
+  // Aliases for alternate PC+imm syntax of LDR instructions.
+  case ARM::t2LDRpcrel:
+    Inst.setOpcode(ARM::t2LDRpci);
+    return true;
+  case ARM::t2LDRBpcrel:
+    Inst.setOpcode(ARM::t2LDRBpci);
+    return true;
+  case ARM::t2LDRHpcrel:
+    Inst.setOpcode(ARM::t2LDRHpci);
+    return true;
+  case ARM::t2LDRSBpcrel:
+    Inst.setOpcode(ARM::t2LDRSBpci);
+    return true;
+  case ARM::t2LDRSHpcrel:
+    Inst.setOpcode(ARM::t2LDRSHpci);
+    return true;
+  // Handle NEON VST complex aliases.
+  case ARM::VST1LNdWB_register_Asm_8:
+  case ARM::VST1LNdWB_register_Asm_16:
+  case ARM::VST1LNdWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST2LNdWB_register_Asm_8:
+  case ARM::VST2LNdWB_register_Asm_16:
+  case ARM::VST2LNdWB_register_Asm_32:
+  case ARM::VST2LNqWB_register_Asm_16:
+  case ARM::VST2LNqWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST3LNdWB_register_Asm_8:
+  case ARM::VST3LNdWB_register_Asm_16:
+  case ARM::VST3LNdWB_register_Asm_32:
+  case ARM::VST3LNqWB_register_Asm_16:
+  case ARM::VST3LNqWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST4LNdWB_register_Asm_8:
+  case ARM::VST4LNdWB_register_Asm_16:
+  case ARM::VST4LNdWB_register_Asm_32:
+  case ARM::VST4LNqWB_register_Asm_16:
+  case ARM::VST4LNqWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST1LNdWB_fixed_Asm_8:
+  case ARM::VST1LNdWB_fixed_Asm_16:
+  case ARM::VST1LNdWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST2LNdWB_fixed_Asm_8:
+  case ARM::VST2LNdWB_fixed_Asm_16:
+  case ARM::VST2LNdWB_fixed_Asm_32:
+  case ARM::VST2LNqWB_fixed_Asm_16:
+  case ARM::VST2LNqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST3LNdWB_fixed_Asm_8:
+  case ARM::VST3LNdWB_fixed_Asm_16:
+  case ARM::VST3LNdWB_fixed_Asm_32:
+  case ARM::VST3LNqWB_fixed_Asm_16:
+  case ARM::VST3LNqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST4LNdWB_fixed_Asm_8:
+  case ARM::VST4LNdWB_fixed_Asm_16:
+  case ARM::VST4LNdWB_fixed_Asm_32:
+  case ARM::VST4LNqWB_fixed_Asm_16:
+  case ARM::VST4LNqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST1LNdAsm_8:
+  case ARM::VST1LNdAsm_16:
+  case ARM::VST1LNdAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST2LNdAsm_8:
+  case ARM::VST2LNdAsm_16:
+  case ARM::VST2LNdAsm_32:
+  case ARM::VST2LNqAsm_16:
+  case ARM::VST2LNqAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST3LNdAsm_8:
+  case ARM::VST3LNdAsm_16:
+  case ARM::VST3LNdAsm_32:
+  case ARM::VST3LNqAsm_16:
+  case ARM::VST3LNqAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST4LNdAsm_8:
+  case ARM::VST4LNdAsm_16:
+  case ARM::VST4LNdAsm_32:
+  case ARM::VST4LNqAsm_16:
+  case ARM::VST4LNqAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // Handle NEON VLD complex aliases.
+  case ARM::VLD1LNdWB_register_Asm_8:
+  case ARM::VLD1LNdWB_register_Asm_16:
+  case ARM::VLD1LNdWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD2LNdWB_register_Asm_8:
+  case ARM::VLD2LNdWB_register_Asm_16:
+  case ARM::VLD2LNdWB_register_Asm_32:
+  case ARM::VLD2LNqWB_register_Asm_16:
+  case ARM::VLD2LNqWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD3LNdWB_register_Asm_8:
+  case ARM::VLD3LNdWB_register_Asm_16:
+  case ARM::VLD3LNdWB_register_Asm_32:
+  case ARM::VLD3LNqWB_register_Asm_16:
+  case ARM::VLD3LNqWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD4LNdWB_register_Asm_8:
+  case ARM::VLD4LNdWB_register_Asm_16:
+  case ARM::VLD4LNdWB_register_Asm_32:
+  case ARM::VLD4LNqWB_register_Asm_16:
+  case ARM::VLD4LNqWB_register_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(4)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(5)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(6));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD1LNdWB_fixed_Asm_8:
+  case ARM::VLD1LNdWB_fixed_Asm_16:
+  case ARM::VLD1LNdWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD2LNdWB_fixed_Asm_8:
+  case ARM::VLD2LNdWB_fixed_Asm_16:
+  case ARM::VLD2LNdWB_fixed_Asm_32:
+  case ARM::VLD2LNqWB_fixed_Asm_16:
+  case ARM::VLD2LNqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD3LNdWB_fixed_Asm_8:
+  case ARM::VLD3LNdWB_fixed_Asm_16:
+  case ARM::VLD3LNdWB_fixed_Asm_32:
+  case ARM::VLD3LNqWB_fixed_Asm_16:
+  case ARM::VLD3LNqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD4LNdWB_fixed_Asm_8:
+  case ARM::VLD4LNdWB_fixed_Asm_16:
+  case ARM::VLD4LNdWB_fixed_Asm_32:
+  case ARM::VLD4LNqWB_fixed_Asm_16:
+  case ARM::VLD4LNqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD1LNdAsm_8:
+  case ARM::VLD1LNdAsm_16:
+  case ARM::VLD1LNdAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD2LNdAsm_8:
+  case ARM::VLD2LNdAsm_16:
+  case ARM::VLD2LNdAsm_32:
+  case ARM::VLD2LNqAsm_16:
+  case ARM::VLD2LNqAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD3LNdAsm_8:
+  case ARM::VLD3LNdAsm_16:
+  case ARM::VLD3LNdAsm_32:
+  case ARM::VLD3LNqAsm_16:
+  case ARM::VLD3LNqAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD4LNdAsm_8:
+  case ARM::VLD4LNdAsm_16:
+  case ARM::VLD4LNdAsm_32:
+  case ARM::VLD4LNqAsm_16:
+  case ARM::VLD4LNqAsm_32: {
+    MCInst TmpInst;
+    // Shuffle the operands around so the lane index operand is in the
+    // right place.
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(2)); // Rn
+    TmpInst.addOperand(Inst.getOperand(3)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (=3D=3D Vd)
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // lane
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // VLD3DUP single 3-element structure to all lanes instructions.
+  case ARM::VLD3DUPdAsm_8:
+  case ARM::VLD3DUPdAsm_16:
+  case ARM::VLD3DUPdAsm_32:
+  case ARM::VLD3DUPqAsm_8:
+  case ARM::VLD3DUPqAsm_16:
+  case ARM::VLD3DUPqAsm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD3DUPdWB_fixed_Asm_8:
+  case ARM::VLD3DUPdWB_fixed_Asm_16:
+  case ARM::VLD3DUPdWB_fixed_Asm_32:
+  case ARM::VLD3DUPqWB_fixed_Asm_8:
+  case ARM::VLD3DUPqWB_fixed_Asm_16:
+  case ARM::VLD3DUPqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD3DUPdWB_register_Asm_8:
+  case ARM::VLD3DUPdWB_register_Asm_16:
+  case ARM::VLD3DUPdWB_register_Asm_32:
+  case ARM::VLD3DUPqWB_register_Asm_8:
+  case ARM::VLD3DUPqWB_register_Asm_16:
+  case ARM::VLD3DUPqWB_register_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // Rm
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // VLD3 multiple 3-element structure instructions.
+  case ARM::VLD3dAsm_8:
+  case ARM::VLD3dAsm_16:
+  case ARM::VLD3dAsm_32:
+  case ARM::VLD3qAsm_8:
+  case ARM::VLD3qAsm_16:
+  case ARM::VLD3qAsm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD3dWB_fixed_Asm_8:
+  case ARM::VLD3dWB_fixed_Asm_16:
+  case ARM::VLD3dWB_fixed_Asm_32:
+  case ARM::VLD3qWB_fixed_Asm_8:
+  case ARM::VLD3qWB_fixed_Asm_16:
+  case ARM::VLD3qWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD3dWB_register_Asm_8:
+  case ARM::VLD3dWB_register_Asm_16:
+  case ARM::VLD3dWB_register_Asm_32:
+  case ARM::VLD3qWB_register_Asm_8:
+  case ARM::VLD3qWB_register_Asm_16:
+  case ARM::VLD3qWB_register_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // Rm
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // VLD4DUP single 3-element structure to all lanes instructions.
+  case ARM::VLD4DUPdAsm_8:
+  case ARM::VLD4DUPdAsm_16:
+  case ARM::VLD4DUPdAsm_32:
+  case ARM::VLD4DUPqAsm_8:
+  case ARM::VLD4DUPqAsm_16:
+  case ARM::VLD4DUPqAsm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD4DUPdWB_fixed_Asm_8:
+  case ARM::VLD4DUPdWB_fixed_Asm_16:
+  case ARM::VLD4DUPdWB_fixed_Asm_32:
+  case ARM::VLD4DUPqWB_fixed_Asm_8:
+  case ARM::VLD4DUPqWB_fixed_Asm_16:
+  case ARM::VLD4DUPqWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD4DUPdWB_register_Asm_8:
+  case ARM::VLD4DUPdWB_register_Asm_16:
+  case ARM::VLD4DUPdWB_register_Asm_32:
+  case ARM::VLD4DUPqWB_register_Asm_8:
+  case ARM::VLD4DUPqWB_register_Asm_16:
+  case ARM::VLD4DUPqWB_register_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // Rm
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // VLD4 multiple 4-element structure instructions.
+  case ARM::VLD4dAsm_8:
+  case ARM::VLD4dAsm_16:
+  case ARM::VLD4dAsm_32:
+  case ARM::VLD4qAsm_8:
+  case ARM::VLD4qAsm_16:
+  case ARM::VLD4qAsm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD4dWB_fixed_Asm_8:
+  case ARM::VLD4dWB_fixed_Asm_16:
+  case ARM::VLD4dWB_fixed_Asm_32:
+  case ARM::VLD4qWB_fixed_Asm_8:
+  case ARM::VLD4qWB_fixed_Asm_16:
+  case ARM::VLD4qWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VLD4dWB_register_Asm_8:
+  case ARM::VLD4dWB_register_Asm_16:
+  case ARM::VLD4dWB_register_Asm_32:
+  case ARM::VLD4qWB_register_Asm_8:
+  case ARM::VLD4qWB_register_Asm_16:
+  case ARM::VLD4qWB_register_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // Rm
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // VST3 multiple 3-element structure instructions.
+  case ARM::VST3dAsm_8:
+  case ARM::VST3dAsm_16:
+  case ARM::VST3dAsm_32:
+  case ARM::VST3qAsm_8:
+  case ARM::VST3qAsm_16:
+  case ARM::VST3qAsm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST3dWB_fixed_Asm_8:
+  case ARM::VST3dWB_fixed_Asm_16:
+  case ARM::VST3dWB_fixed_Asm_32:
+  case ARM::VST3qWB_fixed_Asm_8:
+  case ARM::VST3qWB_fixed_Asm_16:
+  case ARM::VST3qWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST3dWB_register_Asm_8:
+  case ARM::VST3dWB_register_Asm_16:
+  case ARM::VST3dWB_register_Asm_32:
+  case ARM::VST3qWB_register_Asm_8:
+  case ARM::VST3qWB_register_Asm_16:
+  case ARM::VST3qWB_register_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // VST4 multiple 3-element structure instructions.
+  case ARM::VST4dAsm_8:
+  case ARM::VST4dAsm_16:
+  case ARM::VST4dAsm_32:
+  case ARM::VST4qAsm_8:
+  case ARM::VST4qAsm_16:
+  case ARM::VST4qAsm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST4dWB_fixed_Asm_8:
+  case ARM::VST4dWB_fixed_Asm_16:
+  case ARM::VST4dWB_fixed_Asm_32:
+  case ARM::VST4qWB_fixed_Asm_8:
+  case ARM::VST4qWB_fixed_Asm_16:
+  case ARM::VST4qWB_fixed_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  case ARM::VST4dWB_register_Asm_8:
+  case ARM::VST4dWB_register_Asm_16:
+  case ARM::VST4dWB_register_Asm_32:
+  case ARM::VST4qWB_register_Asm_8:
+  case ARM::VST4qWB_register_Asm_16:
+  case ARM::VST4qWB_register_Asm_32: {
+    MCInst TmpInst;
+    unsigned Spacing;
+    TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb =3D=3D tied Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // alignment
+    TmpInst.addOperand(Inst.getOperand(3)); // Rm
+    TmpInst.addOperand(Inst.getOperand(0)); // Vd
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 2));
+    TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
+                                            Spacing * 3));
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    Inst =3D TmpInst;
+    return true;
+  }
+
+  // Handle encoding choice for the shift-immediate instructions.
+  case ARM::t2LSLri:
+  case ARM::t2LSRri:
+  case ARM::t2ASRri: {
+    if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
+        Inst.getOperand(0).getReg() =3D=3D Inst.getOperand(1).getReg() &&
+        Inst.getOperand(5).getReg() =3D=3D (inITBlock() ? 0 : ARM::CPSR) &&
+        !(static_cast<ARMOperand*>(Operands[3])->isToken() &&
+         static_cast<ARMOperand*>(Operands[3])->getToken() =3D=3D ".w")) {
+      unsigned NewOpc;
+      switch (Inst.getOpcode()) {
+      default: llvm_unreachable("unexpected opcode");
+      case ARM::t2LSLri: NewOpc =3D ARM::tLSLri; break;
+      case ARM::t2LSRri: NewOpc =3D ARM::tLSRri; break;
+      case ARM::t2ASRri: NewOpc =3D ARM::tASRri; break;
+      }
+      // The Thumb1 operands aren't in the same order. Awesome, eh?
+      MCInst TmpInst;
+      TmpInst.setOpcode(NewOpc);
+      TmpInst.addOperand(Inst.getOperand(0));
+      TmpInst.addOperand(Inst.getOperand(5));
+      TmpInst.addOperand(Inst.getOperand(1));
+      TmpInst.addOperand(Inst.getOperand(2));
+      TmpInst.addOperand(Inst.getOperand(3));
+      TmpInst.addOperand(Inst.getOperand(4));
+      Inst =3D TmpInst;
+      return true;
+    }
+    return false;
+  }
+
+  // Handle the Thumb2 mode MOV complex aliases.
+  case ARM::t2MOVsr:
+  case ARM::t2MOVSsr: {
+    // Which instruction to expand to depends on the CCOut operand and
+    // whether we're in an IT block if the register operands are low
+    // registers.
+    bool isNarrow =3D false;
+    if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
+        isARMLowRegister(Inst.getOperand(1).getReg()) &&
+        isARMLowRegister(Inst.getOperand(2).getReg()) &&
+        Inst.getOperand(0).getReg() =3D=3D Inst.getOperand(1).getReg() &&
+        inITBlock() =3D=3D (Inst.getOpcode() =3D=3D ARM::t2MOVsr))
+      isNarrow =3D true;
+    MCInst TmpInst;
+    unsigned newOpc;
+    switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
+    default: llvm_unreachable("unexpected opcode!");
+    case ARM_AM::asr: newOpc =3D isNarrow ? ARM::tASRrr : ARM::t2ASRrr; br=
eak;
+    case ARM_AM::lsr: newOpc =3D isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; br=
eak;
+    case ARM_AM::lsl: newOpc =3D isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; br=
eak;
+    case ARM_AM::ror: newOpc =3D isNarrow ? ARM::tROR   : ARM::t2RORrr; br=
eak;
+    }
+    TmpInst.setOpcode(newOpc);
+    TmpInst.addOperand(Inst.getOperand(0)); // Rd
+    if (isNarrow)
+      TmpInst.addOperand(MCOperand::CreateReg(
+          Inst.getOpcode() =3D=3D ARM::t2MOVSsr ? ARM::CPSR : 0));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // Rm
+    TmpInst.addOperand(Inst.getOperand(4)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(5));
+    if (!isNarrow)
+      TmpInst.addOperand(MCOperand::CreateReg(
+          Inst.getOpcode() =3D=3D ARM::t2MOVSsr ? ARM::CPSR : 0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case ARM::t2MOVsi:
+  case ARM::t2MOVSsi: {
+    // Which instruction to expand to depends on the CCOut operand and
+    // whether we're in an IT block if the register operands are low
+    // registers.
+    bool isNarrow =3D false;
+    if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
+        isARMLowRegister(Inst.getOperand(1).getReg()) &&
+        inITBlock() =3D=3D (Inst.getOpcode() =3D=3D ARM::t2MOVsi))
+      isNarrow =3D true;
+    MCInst TmpInst;
+    unsigned newOpc;
+    switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
+    default: llvm_unreachable("unexpected opcode!");
+    case ARM_AM::asr: newOpc =3D isNarrow ? ARM::tASRri : ARM::t2ASRri; br=
eak;
+    case ARM_AM::lsr: newOpc =3D isNarrow ? ARM::tLSRri : ARM::t2LSRri; br=
eak;
+    case ARM_AM::lsl: newOpc =3D isNarrow ? ARM::tLSLri : ARM::t2LSLri; br=
eak;
+    case ARM_AM::ror: newOpc =3D ARM::t2RORri; isNarrow =3D false; break;
+    case ARM_AM::rrx: isNarrow =3D false; newOpc =3D ARM::t2RRX; break;
+    }
+    unsigned Ammount =3D ARM_AM::getSORegOffset(Inst.getOperand(2).getImm(=
));
+    if (Ammount =3D=3D 32) Ammount =3D 0;
+    TmpInst.setOpcode(newOpc);
+    TmpInst.addOperand(Inst.getOperand(0)); // Rd
+    if (isNarrow)
+      TmpInst.addOperand(MCOperand::CreateReg(
+          Inst.getOpcode() =3D=3D ARM::t2MOVSsi ? ARM::CPSR : 0));
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    if (newOpc !=3D ARM::t2RRX)
+      TmpInst.addOperand(MCOperand::CreateImm(Ammount));
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    if (!isNarrow)
+      TmpInst.addOperand(MCOperand::CreateReg(
+          Inst.getOpcode() =3D=3D ARM::t2MOVSsi ? ARM::CPSR : 0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  // Handle the ARM mode MOV complex aliases.
+  case ARM::ASRr:
+  case ARM::LSRr:
+  case ARM::LSLr:
+  case ARM::RORr: {
+    ARM_AM::ShiftOpc ShiftTy;
+    switch(Inst.getOpcode()) {
+    default: llvm_unreachable("unexpected opcode!");
+    case ARM::ASRr: ShiftTy =3D ARM_AM::asr; break;
+    case ARM::LSRr: ShiftTy =3D ARM_AM::lsr; break;
+    case ARM::LSLr: ShiftTy =3D ARM_AM::lsl; break;
+    case ARM::RORr: ShiftTy =3D ARM_AM::ror; break;
+    }
+    unsigned Shifter =3D ARM_AM::getSORegOpc(ShiftTy, 0);
+    MCInst TmpInst;
+    TmpInst.setOpcode(ARM::MOVsr);
+    TmpInst.addOperand(Inst.getOperand(0)); // Rd
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(Inst.getOperand(2)); // Rm
+    TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and =
ty
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    TmpInst.addOperand(Inst.getOperand(5)); // cc_out
+    Inst =3D TmpInst;
+    return true;
+  }
+  case ARM::ASRi:
+  case ARM::LSRi:
+  case ARM::LSLi:
+  case ARM::RORi: {
+    ARM_AM::ShiftOpc ShiftTy;
+    switch(Inst.getOpcode()) {
+    default: llvm_unreachable("unexpected opcode!");
+    case ARM::ASRi: ShiftTy =3D ARM_AM::asr; break;
+    case ARM::LSRi: ShiftTy =3D ARM_AM::lsr; break;
+    case ARM::LSLi: ShiftTy =3D ARM_AM::lsl; break;
+    case ARM::RORi: ShiftTy =3D ARM_AM::ror; break;
+    }
+    // A shift by zero is a plain MOVr, not a MOVsi.
+    unsigned Amt =3D Inst.getOperand(2).getImm();
+    unsigned Opc =3D Amt =3D=3D 0 ? ARM::MOVr : ARM::MOVsi;
+    unsigned Shifter =3D ARM_AM::getSORegOpc(ShiftTy, Amt);
+    MCInst TmpInst;
+    TmpInst.setOpcode(Opc);
+    TmpInst.addOperand(Inst.getOperand(0)); // Rd
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    if (Opc =3D=3D ARM::MOVsi)
+      TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value an=
d ty
+    TmpInst.addOperand(Inst.getOperand(3)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(4));
+    TmpInst.addOperand(Inst.getOperand(5)); // cc_out
+    Inst =3D TmpInst;
+    return true;
+  }
+  case ARM::RRXi: {
+    unsigned Shifter =3D ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
+    MCInst TmpInst;
+    TmpInst.setOpcode(ARM::MOVsi);
+    TmpInst.addOperand(Inst.getOperand(0)); // Rd
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and =
ty
+    TmpInst.addOperand(Inst.getOperand(2)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(3));
+    TmpInst.addOperand(Inst.getOperand(4)); // cc_out
+    Inst =3D TmpInst;
+    return true;
+  }
+  case ARM::t2LDMIA_UPD: {
+    // If this is a load of a single register, then we should use
+    // a post-indexed LDR instruction instead, per the ARM ARM.
+    if (Inst.getNumOperands() !=3D 5)
+      return false;
+    MCInst TmpInst;
+    TmpInst.setOpcode(ARM::t2LDR_POST);
+    TmpInst.addOperand(Inst.getOperand(4)); // Rt
+    TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(MCOperand::CreateImm(4));
+    TmpInst.addOperand(Inst.getOperand(2)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(3));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case ARM::t2STMDB_UPD: {
+    // If this is a store of a single register, then we should use
+    // a pre-indexed STR instruction instead, per the ARM ARM.
+    if (Inst.getNumOperands() !=3D 5)
+      return false;
+    MCInst TmpInst;
+    TmpInst.setOpcode(ARM::t2STR_PRE);
+    TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
+    TmpInst.addOperand(Inst.getOperand(4)); // Rt
+    TmpInst.addOperand(Inst.getOperand(1)); // Rn
+    TmpInst.addOperand(MCOperand::CreateImm(-4));
+    TmpInst.addOperand(Inst.getOperand(2)); // CondCode
+    TmpInst.addOperand(Inst.getOperand(3));
+    Inst =3D TmpInst;
+    return true;
+  }
   case ARM::LDMIA_UPD:
     // If this is a load of a single register via a 'pop', then we should =
use
     // a post-indexed LDR instruction instead, per the ARM ARM.
@@ -4160,6 +6870,7 @@
       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
       TmpInst.addOperand(Inst.getOperand(3));
       Inst =3D TmpInst;
+      return true;
     }
     break;
   case ARM::STMDB_UPD:
@@ -4178,41 +6889,117 @@
       Inst =3D TmpInst;
     }
     break;
+  case ARM::t2ADDri12:
+    // If the immediate fits for encoding T3 (t2ADDri) and the generic "ad=
d"
+    // mnemonic was used (not "addw"), encoding T3 is preferred.
+    if (static_cast<ARMOperand*>(Operands[0])->getToken() !=3D "add" ||
+        ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) =3D=3D -1)
+      break;
+    Inst.setOpcode(ARM::t2ADDri);
+    Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
+    break;
+  case ARM::t2SUBri12:
+    // If the immediate fits for encoding T3 (t2SUBri) and the generic "su=
b"
+    // mnemonic was used (not "subw"), encoding T3 is preferred.
+    if (static_cast<ARMOperand*>(Operands[0])->getToken() !=3D "sub" ||
+        ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) =3D=3D -1)
+      break;
+    Inst.setOpcode(ARM::t2SUBri);
+    Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
+    break;
   case ARM::tADDi8:
     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
     // to encoding T1 if <Rd> is omitted."
-    if (Inst.getOperand(3).getImm() < 8 && Operands.size() =3D=3D 6)
+    if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() =3D=
=3D 6) {
       Inst.setOpcode(ARM::tADDi3);
+      return true;
+    }
     break;
   case ARM::tSUBi8:
     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
     // to encoding T1 if <Rd> is omitted."
-    if (Inst.getOperand(3).getImm() < 8 && Operands.size() =3D=3D 6)
+    if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() =3D=
=3D 6) {
       Inst.setOpcode(ARM::tSUBi3);
+      return true;
+    }
     break;
+  case ARM::t2ADDri:
+  case ARM::t2SUBri: {
+    // If the destination and first source operand are the same, and
+    // the flags are compatible with the current IT status, use encoding T2
+    // instead of T3. For compatibility with the system 'as'. Make sure the
+    // wide encoding wasn't explicit.
+    if (Inst.getOperand(0).getReg() !=3D Inst.getOperand(1).getReg() ||
+        !isARMLowRegister(Inst.getOperand(0).getReg()) ||
+        (unsigned)Inst.getOperand(2).getImm() > 255 ||
+        ((!inITBlock() && Inst.getOperand(5).getReg() !=3D ARM::CPSR) ||
+        (inITBlock() && Inst.getOperand(5).getReg() !=3D 0)) ||
+        (static_cast<ARMOperand*>(Operands[3])->isToken() &&
+         static_cast<ARMOperand*>(Operands[3])->getToken() =3D=3D ".w"))
+      break;
+    MCInst TmpInst;
+    TmpInst.setOpcode(Inst.getOpcode() =3D=3D ARM::t2ADDri ?
+                      ARM::tADDi8 : ARM::tSUBi8);
+    TmpInst.addOperand(Inst.getOperand(0));
+    TmpInst.addOperand(Inst.getOperand(5));
+    TmpInst.addOperand(Inst.getOperand(0));
+    TmpInst.addOperand(Inst.getOperand(2));
+    TmpInst.addOperand(Inst.getOperand(3));
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case ARM::t2ADDrr: {
+    // If the destination and first source operand are the same, and
+    // there's no setting of the flags, use encoding T2 instead of T3.
+    // Note that this is only for ADD, not SUB. This mirrors the system
+    // 'as' behaviour. Make sure the wide encoding wasn't explicit.
+    if (Inst.getOperand(0).getReg() !=3D Inst.getOperand(1).getReg() ||
+        Inst.getOperand(5).getReg() !=3D 0 ||
+        (static_cast<ARMOperand*>(Operands[3])->isToken() &&
+         static_cast<ARMOperand*>(Operands[3])->getToken() =3D=3D ".w"))
+      break;
+    MCInst TmpInst;
+    TmpInst.setOpcode(ARM::tADDhirr);
+    TmpInst.addOperand(Inst.getOperand(0));
+    TmpInst.addOperand(Inst.getOperand(0));
+    TmpInst.addOperand(Inst.getOperand(2));
+    TmpInst.addOperand(Inst.getOperand(3));
+    TmpInst.addOperand(Inst.getOperand(4));
+    Inst =3D TmpInst;
+    return true;
+  }
   case ARM::tB:
     // A Thumb conditional branch outside of an IT block is a tBcc.
-    if (Inst.getOperand(1).getImm() !=3D ARMCC::AL && !inITBlock())
+    if (Inst.getOperand(1).getImm() !=3D ARMCC::AL && !inITBlock()) {
       Inst.setOpcode(ARM::tBcc);
+      return true;
+    }
     break;
   case ARM::t2B:
     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
-    if (Inst.getOperand(1).getImm() !=3D ARMCC::AL && !inITBlock())
+    if (Inst.getOperand(1).getImm() !=3D ARMCC::AL && !inITBlock()){
       Inst.setOpcode(ARM::t2Bcc);
+      return true;
+    }
     break;
   case ARM::t2Bcc:
     // If the conditional is AL or we're in an IT block, we really want t2=
B.
-    if (Inst.getOperand(1).getImm() =3D=3D ARMCC::AL || inITBlock())
+    if (Inst.getOperand(1).getImm() =3D=3D ARMCC::AL || inITBlock()) {
       Inst.setOpcode(ARM::t2B);
+      return true;
+    }
     break;
   case ARM::tBcc:
     // If the conditional is AL, we really want tB.
-    if (Inst.getOperand(1).getImm() =3D=3D ARMCC::AL)
+    if (Inst.getOperand(1).getImm() =3D=3D ARMCC::AL) {
       Inst.setOpcode(ARM::tB);
+      return true;
+    }
     break;
   case ARM::tLDMIA: {
     // If the register list contains any high registers, or if the writeba=
ck
@@ -4235,6 +7022,7 @@
       if (hasWritebackToken)
         Inst.insert(Inst.begin(),
                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
+      return true;
     }
     break;
   }
@@ -4248,14 +7036,40 @@
       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
       assert (isThumbTwo());
       Inst.setOpcode(ARM::t2STMIA_UPD);
+      return true;
     }
     break;
   }
+  case ARM::tPOP: {
+    bool listContainsBase;
+    // If the register list contains any high registers, we need to use
+    // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
+    // should have generated an error in validateInstruction().
+    if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
+      return false;
+    assert (isThumbTwo());
+    Inst.setOpcode(ARM::t2LDMIA_UPD);
+    // Add the base register and writeback operands.
+    Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
+    Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
+    return true;
+  }
+  case ARM::tPUSH: {
+    bool listContainsBase;
+    if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
+      return false;
+    assert (isThumbTwo());
+    Inst.setOpcode(ARM::t2STMDB_UPD);
+    // Add the base register and writeback operands.
+    Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
+    Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
+    return true;
+  }
   case ARM::t2MOVi: {
     // If we can use the 16-bit encoding and the user didn't explicitly
     // request the 32-bit variant, transform it here.
     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
-        Inst.getOperand(1).getImm() <=3D 255 &&
+        (unsigned)Inst.getOperand(1).getImm() <=3D 255 &&
         ((!inITBlock() && Inst.getOperand(2).getImm() =3D=3D ARMCC::AL &&
          Inst.getOperand(4).getReg() =3D=3D ARM::CPSR) ||
         (inITBlock() && Inst.getOperand(4).getReg() =3D=3D 0)) &&
@@ -4270,6 +7084,7 @@
       TmpInst.addOperand(Inst.getOperand(2));
       TmpInst.addOperand(Inst.getOperand(3));
       Inst =3D TmpInst;
+      return true;
     }
     break;
   }
@@ -4290,6 +7105,7 @@
       TmpInst.addOperand(Inst.getOperand(2));
       TmpInst.addOperand(Inst.getOperand(3));
       Inst =3D TmpInst;
+      return true;
     }
     break;
   }
@@ -4320,9 +7136,61 @@
       TmpInst.addOperand(Inst.getOperand(3));
       TmpInst.addOperand(Inst.getOperand(4));
       Inst =3D TmpInst;
+      return true;
     }
     break;
   }
+  case ARM::MOVsi: {
+    ARM_AM::ShiftOpc SOpc =3D ARM_AM::getSORegShOp(Inst.getOperand(2).getI=
mm());
+    if (SOpc =3D=3D ARM_AM::rrx) return false;
+    if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) =3D=3D 0) {
+      // Shifting by zero is accepted as a vanilla 'MOVr'
+      MCInst TmpInst;
+      TmpInst.setOpcode(ARM::MOVr);
+      TmpInst.addOperand(Inst.getOperand(0));
+      TmpInst.addOperand(Inst.getOperand(1));
+      TmpInst.addOperand(Inst.getOperand(3));
+      TmpInst.addOperand(Inst.getOperand(4));
+      TmpInst.addOperand(Inst.getOperand(5));
+      Inst =3D TmpInst;
+      return true;
+    }
+    return false;
+  }
+  case ARM::ANDrsi:
+  case ARM::ORRrsi:
+  case ARM::EORrsi:
+  case ARM::BICrsi:
+  case ARM::SUBrsi:
+  case ARM::ADDrsi: {
+    unsigned newOpc;
+    ARM_AM::ShiftOpc SOpc =3D ARM_AM::getSORegShOp(Inst.getOperand(3).getI=
mm());
+    if (SOpc =3D=3D ARM_AM::rrx) return false;
+    switch (Inst.getOpcode()) {
+    default: llvm_unreachable("unexpected opcode!");
+    case ARM::ANDrsi: newOpc =3D ARM::ANDrr; break;
+    case ARM::ORRrsi: newOpc =3D ARM::ORRrr; break;
+    case ARM::EORrsi: newOpc =3D ARM::EORrr; break;
+    case ARM::BICrsi: newOpc =3D ARM::BICrr; break;
+    case ARM::SUBrsi: newOpc =3D ARM::SUBrr; break;
+    case ARM::ADDrsi: newOpc =3D ARM::ADDrr; break;
+    }
+    // If the shift is by zero, use the non-shifted instruction definition.
+    if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) =3D=3D 0) {
+      MCInst TmpInst;
+      TmpInst.setOpcode(newOpc);
+      TmpInst.addOperand(Inst.getOperand(0));
+      TmpInst.addOperand(Inst.getOperand(1));
+      TmpInst.addOperand(Inst.getOperand(2));
+      TmpInst.addOperand(Inst.getOperand(4));
+      TmpInst.addOperand(Inst.getOperand(5));
+      TmpInst.addOperand(Inst.getOperand(6));
+      Inst =3D TmpInst;
+      return true;
+    }
+    return false;
+  }
+  case ARM::ITasm:
   case ARM::t2IT: {
     // The mask bits for all but the first condition are represented as
     // the low bit of the condition code value implies 't'. We currently
@@ -4352,13 +7220,14 @@
     break;
   }
   }
+  return false;
 }
=20
 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
   // 16-bit thumb arithmetic instructions either require or preclude the '=
S'
   // suffix depending on whether they're in an IT block or not.
   unsigned Opc =3D Inst.getOpcode();
-  MCInstrDesc &MCID =3D getInstDesc(Opc);
+  const MCInstrDesc &MCID =3D getInstDesc(Opc);
   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
     assert(MCID.hasOptionalDef() &&
            "optionally flag setting instruction missing optional def opera=
nd");
@@ -4417,14 +7286,23 @@
     }
=20
     // Some instructions need post-processing to, for example, tweak which
-    // encoding is selected.
-    processInstruction(Inst, Operands);
+    // encoding is selected. Loop on it while changes happen so the
+    // individual transformations can chain off each other. E.g.,
+    // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
+    while (processInstruction(Inst, Operands))
+      ;
=20
     // Only move forward at the very end so that everything in validate
     // and process gets a consistent answer about whether we're in an IT
     // block.
     forwardITPosition();
=20
+    // ITasm is an ARM mode pseudo-instruction that just sets the ITblock =
and
+    // doesn't actually encode.
+    if (Inst.getOpcode() =3D=3D ARM::ITasm)
+      return false;
+
+    Inst.setLoc(IDLoc);
     Out.EmitInstruction(Inst);
     return false;
   case Match_MissingFeature:
@@ -4458,7 +7336,6 @@
   }
=20
   llvm_unreachable("Implement any new match types added!");
-  return true;
 }
=20
 /// parseDirective parses the arm specific directives
@@ -4468,12 +7345,20 @@
     return parseDirectiveWord(4, DirectiveID.getLoc());
   else if (IDVal =3D=3D ".thumb")
     return parseDirectiveThumb(DirectiveID.getLoc());
+  else if (IDVal =3D=3D ".arm")
+    return parseDirectiveARM(DirectiveID.getLoc());
   else if (IDVal =3D=3D ".thumb_func")
     return parseDirectiveThumbFunc(DirectiveID.getLoc());
   else if (IDVal =3D=3D ".code")
     return parseDirectiveCode(DirectiveID.getLoc());
   else if (IDVal =3D=3D ".syntax")
     return parseDirectiveSyntax(DirectiveID.getLoc());
+  else if (IDVal =3D=3D ".unreq")
+    return parseDirectiveUnreq(DirectiveID.getLoc());
+  else if (IDVal =3D=3D ".arch")
+    return parseDirectiveArch(DirectiveID.getLoc());
+  else if (IDVal =3D=3D ".eabi_attribute")
+    return parseDirectiveEabiAttr(DirectiveID.getLoc());
   return true;
 }
=20
@@ -4509,9 +7394,22 @@
     return Error(L, "unexpected token in directive");
   Parser.Lex();
=20
-  // TODO: set thumb mode
-  // TODO: tell the MC streamer the mode
-  // getParser().getStreamer().Emit???();
+  if (!isThumb())
+    SwitchMode();
+  getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
+  return false;
+}
+
+/// parseDirectiveARM
+///  ::=3D .arm
+bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
+  if (getLexer().isNot(AsmToken::EndOfStatement))
+    return Error(L, "unexpected token in directive");
+  Parser.Lex();
+
+  if (isThumb())
+    SwitchMode();
+  getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
   return false;
 }
=20
@@ -4521,24 +7419,33 @@
   const MCAsmInfo &MAI =3D getParser().getStreamer().getContext().getAsmIn=
fo();
   bool isMachO =3D MAI.hasSubsectionsViaSymbols();
   StringRef Name;
-
-  // Darwin asm has function name after .thumb_func direction
+  bool needFuncName =3D true;
+
+  // Darwin asm has (optionally) function name after .thumb_func direction
   // ELF doesn't
   if (isMachO) {
     const AsmToken &Tok =3D Parser.getTok();
-    if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
-      return Error(L, "unexpected token in .thumb_func directive");
-    Name =3D Tok.getString();
-    Parser.Lex(); // Consume the identifier token.
+    if (Tok.isNot(AsmToken::EndOfStatement)) {
+      if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
+        return Error(L, "unexpected token in .thumb_func directive");
+      Name =3D Tok.getIdentifier();
+      Parser.Lex(); // Consume the identifier token.
+      needFuncName =3D false;
+    }
   }
=20
   if (getLexer().isNot(AsmToken::EndOfStatement))
     return Error(L, "unexpected token in directive");
-  Parser.Lex();
+
+  // Eat the end of statement and any blank lines that follow.
+  while (getLexer().is(AsmToken::EndOfStatement))
+    Parser.Lex();
=20
   // FIXME: assuming function name will be the line following .thumb_func
-  if (!isMachO) {
-    Name =3D Parser.getTok().getString();
+  // We really should be checking the next symbol definition even if there=
's
+  // stuff in between.
+  if (needFuncName) {
+    Name =3D Parser.getTok().getIdentifier();
   }
=20
   // Mark symbol as a thumb symbol.
@@ -4601,6 +7508,57 @@
   return false;
 }
=20
+/// parseDirectiveReq
+///  ::=3D name .req registername
+bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
+  Parser.Lex(); // Eat the '.req' token.
+  unsigned Reg;
+  SMLoc SRegLoc, ERegLoc;
+  if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
+    Parser.EatToEndOfStatement();
+    return Error(SRegLoc, "register name expected");
+  }
+
+  // Shouldn't be anything else.
+  if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
+    Parser.EatToEndOfStatement();
+    return Error(Parser.getTok().getLoc(),
+                 "unexpected input in .req directive.");
+  }
+
+  Parser.Lex(); // Consume the EndOfStatement
+
+  if (RegisterReqs.GetOrCreateValue(Name, Reg).getValue() !=3D Reg)
+    return Error(SRegLoc, "redefinition of '" + Name +
+                          "' does not match original.");
+
+  return false;
+}
+
+/// parseDirectiveUneq
+///  ::=3D .unreq registername
+bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
+  if (Parser.getTok().isNot(AsmToken::Identifier)) {
+    Parser.EatToEndOfStatement();
+    return Error(L, "unexpected input in .unreq directive.");
+  }
+  RegisterReqs.erase(Parser.getTok().getIdentifier());
+  Parser.Lex(); // Eat the identifier.
+  return false;
+}
+
+/// parseDirectiveArch
+///  ::=3D .arch token
+bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
+  return true;
+}
+
+/// parseDirectiveEabiAttr
+///  ::=3D .eabi_attribute int, int
+bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
+  return true;
+}
+
 extern "C" void LLVMInitializeARMAsmLexer();
=20
 /// Force static initialization.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Disas=
sembler/ARMDisassembler.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Disassembler/ARMDisassembler.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMDisassembler.cpp - Disassembler for ARM/Thumb ISA -----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMDisassembler.cpp - Disassembler for ARM/Thumb ISA -------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -9,17 +9,16 @@
=20
 #define DEBUG_TYPE "arm-disassembler"
=20
-#include "ARM.h"
-#include "ARMRegisterInfo.h"
-#include "ARMSubtarget.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
 #include "MCTargetDesc/ARMMCExpr.h"
 #include "MCTargetDesc/ARMBaseInfo.h"
 #include "llvm/MC/EDInstInfo.h"
 #include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCInstrDesc.h"
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCDisassembler.h"
+#include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MemoryObject.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -52,7 +51,7 @@
                               raw_ostream &cStream) const;
=20
   /// getEDInfo - See MCDisassembler.
-  EDInstInfo *getEDInfo() const;
+  const EDInstInfo *getEDInfo() const;
 private:
 };
=20
@@ -77,7 +76,7 @@
                               raw_ostream &cStream) const;
=20
   /// getEDInfo - See MCDisassembler.
-  EDInstInfo *getEDInfo() const;
+  const EDInstInfo *getEDInfo() const;
 private:
   mutable std::vector<unsigned> ITBlock;
   DecodeStatus AddThumbPredicate(MCInst&) const;
@@ -97,224 +96,236 @@
       Out =3D In;
       return false;
   }
-  return false;
+  llvm_unreachable("Invalid DecodeStatus!");
 }
=20
=20
 // Forward declare these because the autogenerated code will reference the=
m.
 // Definitions are further down.
-static DecodeStatus DecodeGPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeGPRnopcRegisterClass(llvm::MCInst &Inst,
+static DecodeStatus DecodeGPRnopcRegisterClass(MCInst &Inst,
                                                unsigned RegNo, uint64_t Ad=
dress,
                                                const void *Decoder);
-static DecodeStatus DecodetGPRRegisterClass(llvm::MCInst &Inst, unsigned R=
egNo,
+static DecodeStatus DecodetGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-static DecodeStatus DecodetcGPRRegisterClass(llvm::MCInst &Inst, unsigned =
RegNo,
+static DecodeStatus DecodetcGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-static DecodeStatus DecoderGPRRegisterClass(llvm::MCInst &Inst, unsigned R=
egNo,
+static DecodeStatus DecoderGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeSPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeDPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeDPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeDPR_8RegisterClass(llvm::MCInst &Inst, unsigned =
RegNo,
+static DecodeStatus DecodeDPR_8RegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeDPR_VFP2RegisterClass(llvm::MCInst &Inst,
+static DecodeStatus DecodeDPR_VFP2RegisterClass(MCInst &Inst,
                                                 unsigned RegNo,
                                                 uint64_t Address,
                                                 const void *Decoder);
-static DecodeStatus DecodeQPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeQPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder);
-
-static DecodeStatus DecodePredicateOperand(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeDPairRegisterClass(MCInst &Inst, unsigned RegNo,
+                                   uint64_t Address, const void *Decoder);
+static DecodeStatus DecodeDPairSpacedRegisterClass(MCInst &Inst,
+                               unsigned RegNo, uint64_t Address,
+                               const void *Decoder);
+
+static DecodeStatus DecodePredicateOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeCCOutOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeCCOutOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSOImmOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeSOImmOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeRegListOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeRegListOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSPRRegListOperand(llvm::MCInst &Inst, unsigned V=
al,
+static DecodeStatus DecodeSPRRegListOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeDPRRegListOperand(llvm::MCInst &Inst, unsigned V=
al,
+static DecodeStatus DecodeDPRRegListOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
=20
-static DecodeStatus DecodeBitfieldMaskOperand(llvm::MCInst &Inst, unsigned=
 Insn,
+static DecodeStatus DecodeBitfieldMaskOperand(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeCopMemInstruction(llvm::MCInst &Inst, unsigned I=
nsn,
+static DecodeStatus DecodeCopMemInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeAddrMode2IdxInstruction(llvm::MCInst &Inst,
+static DecodeStatus DecodeAddrMode2IdxInstruction(MCInst &Inst,
                                                   unsigned Insn,
                                                   uint64_t Address,
                                                   const void *Decoder);
-static DecodeStatus DecodeSORegMemOperand(llvm::MCInst &Inst, unsigned Ins=
n,
+static DecodeStatus DecodeSORegMemOperand(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeAddrMode3Instruction(llvm::MCInst &Inst,unsigned=
 Insn,
+static DecodeStatus DecodeAddrMode3Instruction(MCInst &Inst,unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSORegImmOperand(llvm::MCInst &Inst, unsigned Ins=
n,
+static DecodeStatus DecodeSORegImmOperand(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSORegRegOperand(llvm::MCInst &Inst, unsigned Ins=
n,
+static DecodeStatus DecodeSORegRegOperand(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
=20
-static DecodeStatus DecodeMemMultipleWritebackInstruction(llvm::MCInst & I=
nst,
+static DecodeStatus DecodeMemMultipleWritebackInstruction(MCInst & Inst,
                                                   unsigned Insn,
                                                   uint64_t Adddress,
                                                   const void *Decoder);
-static DecodeStatus DecodeT2MOVTWInstruction(llvm::MCInst &Inst, unsigned =
Insn,
+static DecodeStatus DecodeT2MOVTWInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeArmMOVTWInstruction(llvm::MCInst &Inst, unsigned=
 Insn,
+static DecodeStatus DecodeArmMOVTWInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSMLAInstruction(llvm::MCInst &Inst, unsigned Ins=
n,
+static DecodeStatus DecodeSMLAInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeCPSInstruction(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeCPSInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2CPSInstruction(llvm::MCInst &Inst, unsigned In=
sn,
+static DecodeStatus DecodeT2CPSInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeAddrModeImm12Operand(llvm::MCInst &Inst, unsigne=
d Val,
+static DecodeStatus DecodeAddrModeImm12Operand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeAddrMode5Operand(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeAddrMode5Operand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeAddrMode7Operand(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeAddrMode7Operand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeBranchImmInstruction(llvm::MCInst &Inst,unsigned=
 Insn,
+static DecodeStatus DecodeT2BInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVCVTImmOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeBranchImmInstruction(MCInst &Inst,unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeAddrMode6Operand(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeAddrMode6Operand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLDInstruction(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeVLDInstruction(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVSTInstruction(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeVSTInstruction(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD1DupInstruction(llvm::MCInst &Inst, unsigned =
Val,
+static DecodeStatus DecodeVLD1DupInstruction(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD2DupInstruction(llvm::MCInst &Inst, unsigned =
Val,
+static DecodeStatus DecodeVLD2DupInstruction(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD3DupInstruction(llvm::MCInst &Inst, unsigned =
Val,
+static DecodeStatus DecodeVLD3DupInstruction(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD4DupInstruction(llvm::MCInst &Inst, unsigned =
Val,
+static DecodeStatus DecodeVLD4DupInstruction(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeNEONModImmInstruction(llvm::MCInst &Inst,unsigne=
d Val,
+static DecodeStatus DecodeNEONModImmInstruction(MCInst &Inst,unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVSHLMaxInstruction(llvm::MCInst &Inst, unsigned =
Val,
+static DecodeStatus DecodeVSHLMaxInstruction(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeShiftRight8Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight8Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeShiftRight16Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight16Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeShiftRight32Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight32Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeShiftRight64Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight64Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeTBLInstruction(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeTBLInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodePostIdxReg(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodePostIdxReg(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeCoprocessor(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeCoprocessor(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeMemBarrierOption(llvm::MCInst &Inst, unsigned In=
sn,
+static DecodeStatus DecodeMemBarrierOption(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeMSRMask(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeMSRMask(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeDoubleRegLoad(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeDoubleRegLoad(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeDoubleRegStore(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeDoubleRegStore(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeLDRPreImm(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeLDRPreImm(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeLDRPreReg(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeLDRPreReg(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSTRPreImm(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeSTRPreImm(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeSTRPreReg(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeSTRPreReg(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD1LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD1LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD2LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD2LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD3LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD3LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVLD4LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD4LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVST1LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST1LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVST2LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST2LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVST3LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST3LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVST4LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST4LN(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVMOVSRR(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVMOVSRR(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeVMOVRRS(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVMOVRRS(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-
-static DecodeStatus DecodeThumbAddSpecialReg(llvm::MCInst &Inst, uint16_t =
Insn,
+static DecodeStatus DecodeSwap(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbBROperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeVCVTD(MCInst &Inst, unsigned Insn,
+                                uint64_t Address, const void *Decoder);
+static DecodeStatus DecodeVCVTQ(MCInst &Inst, unsigned Insn,
+                                uint64_t Address, const void *Decoder);
+
+
+static DecodeStatus DecodeThumbAddSpecialReg(MCInst &Inst, uint16_t Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2BROperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbBROperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbCmpBROperand(llvm::MCInst &Inst, unsigned V=
al,
+static DecodeStatus DecodeT2BROperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbAddrModeRR(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbCmpBROperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbAddrModeIS(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModeRR(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbAddrModePC(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModeIS(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbAddrModeSP(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModePC(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2AddrModeSOReg(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModeSP(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2LoadShift(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2AddrModeSOReg(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2Imm8S4(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2LoadShift(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2AddrModeImm8s4(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeT2Imm8S4(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2AddrModeImm0_1020s4(llvm::MCInst &Inst,unsigne=
d Val,
+static DecodeStatus DecodeT2AddrModeImm8s4(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2Imm8(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2AddrModeImm0_1020s4(MCInst &Inst,unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2AddrModeImm8(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2Imm8(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbAddSPImm(llvm::MCInst &Inst, uint16_t Val,
+static DecodeStatus DecodeT2AddrModeImm8(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbAddSPReg(llvm::MCInst &Inst, uint16_t Insn,
+static DecodeStatus DecodeThumbAddSPImm(MCInst &Inst, uint16_t Val,
+                               uint64_t Address, const void *Decoder);
+static DecodeStatus DecodeThumbAddSPReg(MCInst &Inst, uint16_t Insn,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbCPS(llvm::MCInst &Inst, uint16_t Insn,
+static DecodeStatus DecodeThumbCPS(MCInst &Inst, uint16_t Insn,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbBLXOffset(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeThumbBLXOffset(MCInst &Inst, unsigned Insn,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2AddrModeImm12(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2AddrModeImm12(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbTableBranch(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeThumbTableBranch(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumb2BCCInstruction(llvm::MCInst &Inst, unsigne=
d Val,
+static DecodeStatus DecodeThumb2BCCInstruction(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2SOImm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2SOImm(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbBCCTargetOperand(llvm::MCInst &Inst,unsigne=
d Val,
+static DecodeStatus DecodeThumbBCCTargetOperand(MCInst &Inst,unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeThumbBLTargetOperand(llvm::MCInst &Inst, unsigne=
d Val,
+static DecodeStatus DecodeThumbBLTargetOperand(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeIT(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeIT(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2LDRDPreInstruction(llvm::MCInst &Inst,unsigned=
 Insn,
+static DecodeStatus DecodeT2LDRDPreInstruction(MCInst &Inst,unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2STRDPreInstruction(llvm::MCInst &Inst,unsigned=
 Insn,
+static DecodeStatus DecodeT2STRDPreInstruction(MCInst &Inst,unsigned Insn,
                                uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2Adr(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2Adr(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2LdStPre(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2LdStPre(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
-static DecodeStatus DecodeT2ShifterImmOperand(llvm::MCInst &Inst, unsigned=
 Val,
+static DecodeStatus DecodeT2ShifterImmOperand(MCInst &Inst, unsigned Val,
                                 uint64_t Address, const void *Decoder);
=20
-
-
+static DecodeStatus DecodeLDR(MCInst &Inst, unsigned Val,
+                                uint64_t Address, const void *Decoder);
 #include "ARMGenDisassemblerTables.inc"
 #include "ARMGenInstrInfo.inc"
 #include "ARMGenEDInfo.inc"
@@ -327,11 +338,11 @@
   return new ThumbDisassembler(STI);
 }
=20
-EDInstInfo *ARMDisassembler::getEDInfo() const {
+const EDInstInfo *ARMDisassembler::getEDInfo() const {
   return instInfoARM;
 }
=20
-EDInstInfo *ThumbDisassembler::getEDInfo() const {
+const EDInstInfo *ThumbDisassembler::getEDInfo() const {
   return instInfoARM;
 }
=20
@@ -415,7 +426,7 @@
 }
=20
 namespace llvm {
-extern MCInstrDesc ARMInsts[];
+extern const MCInstrDesc ARMInsts[];
 }
=20
 /// tryAddingSymbolicOperand - trys to add a symbolic operand in place of =
the
@@ -435,40 +446,38 @@
                                      MCInst &MI, const void *Decoder) {
   const MCDisassembler *Dis =3D static_cast<const MCDisassembler*>(Decoder=
);
   LLVMOpInfoCallback getOpInfo =3D Dis->getLLVMOpInfoCallback();
-  if (!getOpInfo)
-    return false;
-
   struct LLVMOpInfo1 SymbolicOp;
+  memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
   SymbolicOp.Value =3D Value;
   void *DisInfo =3D Dis->getDisInfoBlock();
-  if (!getOpInfo(DisInfo, Address, 0 /* Offset */, InstSize, 1, &SymbolicO=
p)) {
-    if (isBranch) {
-      LLVMSymbolLookupCallback SymbolLookUp =3D
-                                            Dis->getLLVMSymbolLookupCallba=
ck();
-      if (SymbolLookUp) {
-        uint64_t ReferenceType;
-        ReferenceType =3D LLVMDisassembler_ReferenceType_In_Branch;
-        const char *ReferenceName;
-        const char *Name =3D SymbolLookUp(DisInfo, Value, &ReferenceType, =
Address,
-                                        &ReferenceName);
-        if (Name) {
-          SymbolicOp.AddSymbol.Name =3D Name;
-          SymbolicOp.AddSymbol.Present =3D true;
-          SymbolicOp.Value =3D 0;
-        }
-        else {
-          SymbolicOp.Value =3D Value;
-        }
-        if(ReferenceType =3D=3D LLVMDisassembler_ReferenceType_Out_SymbolS=
tub)
-          (*Dis->CommentStream) << "symbol stub for: " << ReferenceName;
-      }
-      else {
-        return false;
-      }
+
+  if (!getOpInfo ||
+      !getOpInfo(DisInfo, Address, 0 /* Offset */, InstSize, 1, &SymbolicO=
p)) {
+    // Clear SymbolicOp.Value from above and also all other fields.
+    memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
+    LLVMSymbolLookupCallback SymbolLookUp =3D Dis->getLLVMSymbolLookupCall=
back();
+    if (!SymbolLookUp)
+      return false;
+    uint64_t ReferenceType;
+    if (isBranch)
+       ReferenceType =3D LLVMDisassembler_ReferenceType_In_Branch;
+    else
+       ReferenceType =3D LLVMDisassembler_ReferenceType_InOut_None;
+    const char *ReferenceName;
+    const char *Name =3D SymbolLookUp(DisInfo, Value, &ReferenceType, Addr=
ess,
+                                    &ReferenceName);
+    if (Name) {
+      SymbolicOp.AddSymbol.Name =3D Name;
+      SymbolicOp.AddSymbol.Present =3D true;
     }
-    else {
+    // For branches always create an MCExpr so it gets printed as hex addr=
ess.
+    else if (isBranch) {
+      SymbolicOp.Value =3D Value;
+    }
+    if(ReferenceType =3D=3D LLVMDisassembler_ReferenceType_Out_SymbolStub)
+      (*Dis->CommentStream) << "symbol stub for: " << ReferenceName;
+    if (!Name && !isBranch)
       return false;
-    }
   }
=20
   MCContext *Ctx =3D Dis->getMCContext();
@@ -527,8 +536,8 @@
     MI.addOperand(MCOperand::CreateExpr(ARMMCExpr::CreateLower16(Expr, *Ct=
x)));
   else if (SymbolicOp.VariantKind =3D=3D LLVMDisassembler_VariantKind_None)
     MI.addOperand(MCOperand::CreateExpr(Expr));
-  else=20
-    assert(0 && "bad SymbolicOp.VariantKind");
+  else
+    llvm_unreachable("bad SymbolicOp.VariantKind");
=20
   return true;
 }
@@ -543,7 +552,7 @@
 /// a literal 'C' string if the referenced address of the literal pool's e=
ntry
 /// is an address into a section with 'C' string literals.
 static void tryAddingPcLoadReferenceComment(uint64_t Address, int Value,
-					    const void *Decoder) {
+                                            const void *Decoder) {
   const MCDisassembler *Dis =3D static_cast<const MCDisassembler*>(Decoder=
);
   LLVMSymbolLookupCallback SymbolLookUp =3D Dis->getLLVMSymbolLookupCallba=
ck();
   if (SymbolLookUp) {
@@ -841,14 +850,14 @@
                                          createThumbDisassembler);
 }
=20
-static const unsigned GPRDecoderTable[] =3D {
+static const uint16_t GPRDecoderTable[] =3D {
   ARM::R0, ARM::R1, ARM::R2, ARM::R3,
   ARM::R4, ARM::R5, ARM::R6, ARM::R7,
   ARM::R8, ARM::R9, ARM::R10, ARM::R11,
   ARM::R12, ARM::SP, ARM::LR, ARM::PC
 };
=20
-static DecodeStatus DecodeGPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   if (RegNo > 15)
     return MCDisassembler::Fail;
@@ -859,20 +868,26 @@
 }
=20
 static DecodeStatus
-DecodeGPRnopcRegisterClass(llvm::MCInst &Inst, unsigned RegNo,
+DecodeGPRnopcRegisterClass(MCInst &Inst, unsigned RegNo,
                            uint64_t Address, const void *Decoder) {
-  if (RegNo =3D=3D 15) return MCDisassembler::Fail;
-  return DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder);
+  DecodeStatus S =3D MCDisassembler::Success;
+ =20
+  if (RegNo =3D=3D 15)=20
+    S =3D MCDisassembler::SoftFail;
+
+  Check(S, DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder));
+
+  return S;
 }
=20
-static DecodeStatus DecodetGPRRegisterClass(llvm::MCInst &Inst, unsigned R=
egNo,
+static DecodeStatus DecodetGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   if (RegNo > 7)
     return MCDisassembler::Fail;
   return DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder);
 }
=20
-static DecodeStatus DecodetcGPRRegisterClass(llvm::MCInst &Inst, unsigned =
RegNo,
+static DecodeStatus DecodetcGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   unsigned Register =3D 0;
   switch (RegNo) {
@@ -902,13 +917,13 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecoderGPRRegisterClass(llvm::MCInst &Inst, unsigned R=
egNo,
+static DecodeStatus DecoderGPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   if (RegNo =3D=3D 13 || RegNo =3D=3D 15) return MCDisassembler::Fail;
   return DecodeGPRRegisterClass(Inst, RegNo, Address, Decoder);
 }
=20
-static const unsigned SPRDecoderTable[] =3D {
+static const uint16_t SPRDecoderTable[] =3D {
      ARM::S0,  ARM::S1,  ARM::S2,  ARM::S3,
      ARM::S4,  ARM::S5,  ARM::S6,  ARM::S7,
      ARM::S8,  ARM::S9, ARM::S10, ARM::S11,
@@ -919,7 +934,7 @@
     ARM::S28, ARM::S29, ARM::S30, ARM::S31
 };
=20
-static DecodeStatus DecodeSPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeSPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   if (RegNo > 31)
     return MCDisassembler::Fail;
@@ -929,7 +944,7 @@
   return MCDisassembler::Success;
 }
=20
-static const unsigned DPRDecoderTable[] =3D {
+static const uint16_t DPRDecoderTable[] =3D {
      ARM::D0,  ARM::D1,  ARM::D2,  ARM::D3,
      ARM::D4,  ARM::D5,  ARM::D6,  ARM::D7,
      ARM::D8,  ARM::D9, ARM::D10, ARM::D11,
@@ -940,7 +955,7 @@
     ARM::D28, ARM::D29, ARM::D30, ARM::D31
 };
=20
-static DecodeStatus DecodeDPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeDPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   if (RegNo > 31)
     return MCDisassembler::Fail;
@@ -950,7 +965,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeDPR_8RegisterClass(llvm::MCInst &Inst, unsigned =
RegNo,
+static DecodeStatus DecodeDPR_8RegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   if (RegNo > 7)
     return MCDisassembler::Fail;
@@ -958,14 +973,14 @@
 }
=20
 static DecodeStatus
-DecodeDPR_VFP2RegisterClass(llvm::MCInst &Inst, unsigned RegNo,
+DecodeDPR_VFP2RegisterClass(MCInst &Inst, unsigned RegNo,
                             uint64_t Address, const void *Decoder) {
   if (RegNo > 15)
     return MCDisassembler::Fail;
   return DecodeDPRRegisterClass(Inst, RegNo, Address, Decoder);
 }
=20
-static const unsigned QPRDecoderTable[] =3D {
+static const uint16_t QPRDecoderTable[] =3D {
      ARM::Q0,  ARM::Q1,  ARM::Q2,  ARM::Q3,
      ARM::Q4,  ARM::Q5,  ARM::Q6,  ARM::Q7,
      ARM::Q8,  ARM::Q9, ARM::Q10, ARM::Q11,
@@ -973,7 +988,7 @@
 };
=20
=20
-static DecodeStatus DecodeQPRRegisterClass(llvm::MCInst &Inst, unsigned Re=
gNo,
+static DecodeStatus DecodeQPRRegisterClass(MCInst &Inst, unsigned RegNo,
                                    uint64_t Address, const void *Decoder) {
   if (RegNo > 31)
     return MCDisassembler::Fail;
@@ -984,7 +999,49 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodePredicateOperand(llvm::MCInst &Inst, unsigned Va=
l,
+static const uint16_t DPairDecoderTable[] =3D {
+  ARM::Q0,  ARM::D1_D2,   ARM::Q1,  ARM::D3_D4,   ARM::Q2,  ARM::D5_D6,
+  ARM::Q3,  ARM::D7_D8,   ARM::Q4,  ARM::D9_D10,  ARM::Q5,  ARM::D11_D12,
+  ARM::Q6,  ARM::D13_D14, ARM::Q7,  ARM::D15_D16, ARM::Q8,  ARM::D17_D18,
+  ARM::Q9,  ARM::D19_D20, ARM::Q10, ARM::D21_D22, ARM::Q11, ARM::D23_D24,
+  ARM::Q12, ARM::D25_D26, ARM::Q13, ARM::D27_D28, ARM::Q14, ARM::D29_D30,
+  ARM::Q15
+};
+
+static DecodeStatus DecodeDPairRegisterClass(MCInst &Inst, unsigned RegNo,
+                                   uint64_t Address, const void *Decoder) {
+  if (RegNo > 30)
+    return MCDisassembler::Fail;
+
+  unsigned Register =3D DPairDecoderTable[RegNo];
+  Inst.addOperand(MCOperand::CreateReg(Register));
+  return MCDisassembler::Success;
+}
+
+static const uint16_t DPairSpacedDecoderTable[] =3D {
+  ARM::D0_D2,   ARM::D1_D3,   ARM::D2_D4,   ARM::D3_D5,
+  ARM::D4_D6,   ARM::D5_D7,   ARM::D6_D8,   ARM::D7_D9,
+  ARM::D8_D10,  ARM::D9_D11,  ARM::D10_D12, ARM::D11_D13,
+  ARM::D12_D14, ARM::D13_D15, ARM::D14_D16, ARM::D15_D17,
+  ARM::D16_D18, ARM::D17_D19, ARM::D18_D20, ARM::D19_D21,
+  ARM::D20_D22, ARM::D21_D23, ARM::D22_D24, ARM::D23_D25,
+  ARM::D24_D26, ARM::D25_D27, ARM::D26_D28, ARM::D27_D29,
+  ARM::D28_D30, ARM::D29_D31
+};
+
+static DecodeStatus DecodeDPairSpacedRegisterClass(MCInst &Inst,
+                                                   unsigned RegNo,
+                                                   uint64_t Address,
+                                                   const void *Decoder) {
+  if (RegNo > 29)
+    return MCDisassembler::Fail;
+
+  unsigned Register =3D DPairSpacedDecoderTable[RegNo];
+  Inst.addOperand(MCOperand::CreateReg(Register));
+  return MCDisassembler::Success;
+}
+
+static DecodeStatus DecodePredicateOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   if (Val =3D=3D 0xF) return MCDisassembler::Fail;
   // AL predicate is not allowed on Thumb1 branches.
@@ -998,7 +1055,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeCCOutOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeCCOutOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   if (Val)
     Inst.addOperand(MCOperand::CreateReg(ARM::CPSR));
@@ -1007,7 +1064,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeSOImmOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeSOImmOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   uint32_t imm =3D Val & 0xFF;
   uint32_t rot =3D (Val & 0xF00) >> 7;
@@ -1016,7 +1073,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeSORegImmOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeSORegImmOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1053,7 +1110,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeSORegRegOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeSORegRegOperand(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1088,7 +1145,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeRegListOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeRegListOperand(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1123,7 +1180,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeSPRRegListOperand(llvm::MCInst &Inst, unsigned V=
al,
+static DecodeStatus DecodeSPRRegListOperand(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1140,7 +1197,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeDPRRegListOperand(llvm::MCInst &Inst, unsigned V=
al,
+static DecodeStatus DecodeDPRRegListOperand(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1157,7 +1214,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeBitfieldMaskOperand(llvm::MCInst &Inst, unsigned=
 Val,
+static DecodeStatus DecodeBitfieldMaskOperand(MCInst &Inst, unsigned Val,
                                       uint64_t Address, const void *Decode=
r) {
   // This operand encodes a mask of contiguous zeros between a specified M=
SB
   // and LSB.  To decode it, we create the mask of all bits MSB-and-lower,
@@ -1178,7 +1235,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeCopMemInstruction(llvm::MCInst &Inst, unsigned I=
nsn,
+static DecodeStatus DecodeCopMemInstruction(MCInst &Inst, unsigned Insn,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1234,16 +1291,6 @@
   if (!Check(S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
     return MCDisassembler::Fail;
=20
-  unsigned P =3D fieldFromInstruction32(Insn, 24, 1);
-  unsigned W =3D fieldFromInstruction32(Insn, 21, 1);
-
-  bool writeback =3D (P =3D=3D 0) || (W =3D=3D 1);
-  unsigned idx_mode =3D 0;
-  if (P && writeback)
-    idx_mode =3D ARMII::IndexModePre;
-  else if (!P && writeback)
-    idx_mode =3D ARMII::IndexModePost;
-
   switch (Inst.getOpcode()) {
     case ARM::t2LDC2_OFFSET:
     case ARM::t2LDC2L_OFFSET:
@@ -1333,7 +1380,7 @@
 }
=20
 static DecodeStatus
-DecodeAddrMode2IdxInstruction(llvm::MCInst &Inst, unsigned Insn,
+DecodeAddrMode2IdxInstruction(MCInst &Inst, unsigned Insn,
                               uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1436,7 +1483,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeSORegMemOperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeSORegMemOperand(MCInst &Inst, unsigned Val,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1477,7 +1524,7 @@
 }
=20
 static DecodeStatus
-DecodeAddrMode3Instruction(llvm::MCInst &Inst, unsigned Insn,
+DecodeAddrMode3Instruction(MCInst &Inst, unsigned Insn,
                            uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1490,6 +1537,7 @@
   unsigned pred =3D fieldFromInstruction32(Insn, 28, 4);
   unsigned W =3D fieldFromInstruction32(Insn, 21, 1);
   unsigned P =3D fieldFromInstruction32(Insn, 24, 1);
+  unsigned Rt2 =3D Rt + 1;
=20
   bool writeback =3D (W =3D=3D 1) | (P =3D=3D 0);
=20
@@ -1501,7 +1549,86 @@
     case ARM::LDRD:
     case ARM::LDRD_PRE:
     case ARM::LDRD_POST:
-      if (Rt & 0x1) return MCDisassembler::Fail;
+      if (Rt & 0x1) S =3D MCDisassembler::SoftFail;
+      break;
+    default:
+      break;
+  }
+  switch (Inst.getOpcode()) {
+    case ARM::STRD:
+    case ARM::STRD_PRE:
+    case ARM::STRD_POST:
+      if (P =3D=3D 0 && W =3D=3D 1)
+        S =3D MCDisassembler::SoftFail;
+     =20
+      if (writeback && (Rn =3D=3D 15 || Rn =3D=3D Rt || Rn =3D=3D Rt2))
+        S =3D MCDisassembler::SoftFail;
+      if (type && Rm =3D=3D 15)
+        S =3D MCDisassembler::SoftFail;
+      if (Rt2 =3D=3D 15)
+        S =3D MCDisassembler::SoftFail;
+      if (!type && fieldFromInstruction32(Insn, 8, 4))
+        S =3D MCDisassembler::SoftFail;
+      break;
+    case ARM::STRH:
+    case ARM::STRH_PRE:
+    case ARM::STRH_POST:
+      if (Rt =3D=3D 15)
+        S =3D MCDisassembler::SoftFail;
+      if (writeback && (Rn =3D=3D 15 || Rn =3D=3D Rt))
+        S =3D MCDisassembler::SoftFail;
+      if (!type && Rm =3D=3D 15)
+        S =3D MCDisassembler::SoftFail;
+      break;
+    case ARM::LDRD:
+    case ARM::LDRD_PRE:
+    case ARM::LDRD_POST:
+      if (type && Rn =3D=3D 15){
+        if (Rt2 =3D=3D 15)
+          S =3D MCDisassembler::SoftFail;
+        break;
+      }
+      if (P =3D=3D 0 && W =3D=3D 1)
+        S =3D MCDisassembler::SoftFail;
+      if (!type && (Rt2 =3D=3D 15 || Rm =3D=3D 15 || Rm =3D=3D Rt || Rm =
=3D=3D Rt2))
+        S =3D MCDisassembler::SoftFail;
+      if (!type && writeback && Rn =3D=3D 15)
+        S =3D MCDisassembler::SoftFail;
+      if (writeback && (Rn =3D=3D Rt || Rn =3D=3D Rt2))
+        S =3D MCDisassembler::SoftFail;
+      break;
+    case ARM::LDRH:
+    case ARM::LDRH_PRE:
+    case ARM::LDRH_POST:
+      if (type && Rn =3D=3D 15){
+        if (Rt =3D=3D 15)
+          S =3D MCDisassembler::SoftFail;
+        break;
+      }
+      if (Rt =3D=3D 15)
+        S =3D MCDisassembler::SoftFail;
+      if (!type && Rm =3D=3D 15)
+        S =3D MCDisassembler::SoftFail;
+      if (!type && writeback && (Rn =3D=3D 15 || Rn =3D=3D Rt))
+        S =3D MCDisassembler::SoftFail;
+      break;
+    case ARM::LDRSH:
+    case ARM::LDRSH_PRE:
+    case ARM::LDRSH_POST:
+    case ARM::LDRSB:
+    case ARM::LDRSB_PRE:
+    case ARM::LDRSB_POST:
+      if (type && Rn =3D=3D 15){
+        if (Rt =3D=3D 15)
+          S =3D MCDisassembler::SoftFail;
+        break;
+      }
+      if (type && (Rt =3D=3D 15 || (writeback && Rn =3D=3D Rt)))
+        S =3D MCDisassembler::SoftFail;
+      if (!type && (Rt =3D=3D 15 || Rm =3D=3D 15))
+        S =3D MCDisassembler::SoftFail;
+      if (!type && writeback && (Rn =3D=3D 15 || Rn =3D=3D Rt))
+        S =3D MCDisassembler::SoftFail;
       break;
     default:
       break;
@@ -1588,7 +1715,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeRFEInstruction(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeRFEInstruction(MCInst &Inst, unsigned Insn,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1617,7 +1744,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeMemMultipleWritebackInstruction(llvm::MCInst &In=
st,
+static DecodeStatus DecodeMemMultipleWritebackInstruction(MCInst &Inst,
                                   unsigned Insn,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
@@ -1702,7 +1829,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeCPSInstruction(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeCPSInstruction(MCInst &Inst, unsigned Insn,
                                  uint64_t Address, const void *Decoder) {
   unsigned imod =3D fieldFromInstruction32(Insn, 18, 2);
   unsigned M =3D fieldFromInstruction32(Insn, 17, 1);
@@ -1742,7 +1869,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2CPSInstruction(llvm::MCInst &Inst, unsigned In=
sn,
+static DecodeStatus DecodeT2CPSInstruction(MCInst &Inst, unsigned Insn,
                                  uint64_t Address, const void *Decoder) {
   unsigned imod =3D fieldFromInstruction32(Insn, 9, 2);
   unsigned M =3D fieldFromInstruction32(Insn, 8, 1);
@@ -1782,7 +1909,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2MOVTWInstruction(llvm::MCInst &Inst, unsigned =
Insn,
+static DecodeStatus DecodeT2MOVTWInstruction(MCInst &Inst, unsigned Insn,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1806,7 +1933,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeArmMOVTWInstruction(llvm::MCInst &Inst, unsigned=
 Insn,
+static DecodeStatus DecodeArmMOVTWInstruction(MCInst &Inst, unsigned Insn,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1832,7 +1959,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeSMLAInstruction(llvm::MCInst &Inst, unsigned Ins=
n,
+static DecodeStatus DecodeSMLAInstruction(MCInst &Inst, unsigned Insn,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1860,7 +1987,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeAddrModeImm12Operand(llvm::MCInst &Inst, unsigne=
d Val,
+static DecodeStatus DecodeAddrModeImm12Operand(MCInst &Inst, unsigned Val,
                            uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1880,7 +2007,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeAddrMode5Operand(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeAddrMode5Operand(MCInst &Inst, unsigned Val,
                                    uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1899,13 +2026,28 @@
   return S;
 }
=20
-static DecodeStatus DecodeAddrMode7Operand(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeAddrMode7Operand(MCInst &Inst, unsigned Val,
                                    uint64_t Address, const void *Decoder) {
   return DecodeGPRRegisterClass(Inst, Val, Address, Decoder);
 }
=20
 static DecodeStatus
-DecodeBranchImmInstruction(llvm::MCInst &Inst, unsigned Insn,
+DecodeT2BInstruction(MCInst &Inst, unsigned Insn,
+                     uint64_t Address, const void *Decoder) {
+  DecodeStatus S =3D MCDisassembler::Success;
+  unsigned imm =3D (fieldFromInstruction32(Insn, 0, 11) << 0) |
+                 (fieldFromInstruction32(Insn, 11, 1) << 18) |
+                 (fieldFromInstruction32(Insn, 13, 1) << 17) |
+                 (fieldFromInstruction32(Insn, 16, 6) << 11) |
+                 (fieldFromInstruction32(Insn, 26, 1) << 19);
+  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<20>(imm<<1=
) + 4,
+                                true, 4, Inst, Decoder))
+    Inst.addOperand(MCOperand::CreateImm(SignExtend32<20>(imm << 1)));
+  return S;
+}
+
+static DecodeStatus
+DecodeBranchImmInstruction(MCInst &Inst, unsigned Insn,
                            uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1915,12 +2057,14 @@
   if (pred =3D=3D 0xF) {
     Inst.setOpcode(ARM::BLXi);
     imm |=3D fieldFromInstruction32(Insn, 24, 1) << 1;
+    if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<26>(imm)=
 + 8,
+                                  true, 4, Inst, Decoder))
     Inst.addOperand(MCOperand::CreateImm(SignExtend32<26>(imm)));
     return S;
   }
=20
-  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<26>(imm) +=
 8, true,
-                                4, Inst, Decoder))
+  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<26>(imm) +=
 8,
+                                true, 4, Inst, Decoder))
     Inst.addOperand(MCOperand::CreateImm(SignExtend32<26>(imm)));
   if (!Check(S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
     return MCDisassembler::Fail;
@@ -1929,13 +2073,7 @@
 }
=20
=20
-static DecodeStatus DecodeVCVTImmOperand(llvm::MCInst &Inst, unsigned Val,
-                                 uint64_t Address, const void *Decoder) {
-  Inst.addOperand(MCOperand::CreateImm(64 - Val));
-  return MCDisassembler::Success;
-}
-
-static DecodeStatus DecodeAddrMode6Operand(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeAddrMode6Operand(MCInst &Inst, unsigned Val,
                                    uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1952,7 +2090,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVLDInstruction(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLDInstruction(MCInst &Inst, unsigned Insn,
                                    uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -1964,47 +2102,38 @@
   unsigned Rm =3D fieldFromInstruction32(Insn, 0, 4);
=20
   // First output register
-  if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
-    return MCDisassembler::Fail;
+  switch (Inst.getOpcode()) {
+  case ARM::VLD1q16: case ARM::VLD1q32: case ARM::VLD1q64: case ARM::VLD1q=
8:
+  case ARM::VLD1q16wb_fixed: case ARM::VLD1q16wb_register:
+  case ARM::VLD1q32wb_fixed: case ARM::VLD1q32wb_register:
+  case ARM::VLD1q64wb_fixed: case ARM::VLD1q64wb_register:
+  case ARM::VLD1q8wb_fixed: case ARM::VLD1q8wb_register:
+  case ARM::VLD2d16: case ARM::VLD2d32: case ARM::VLD2d8:
+  case ARM::VLD2d16wb_fixed: case ARM::VLD2d16wb_register:
+  case ARM::VLD2d32wb_fixed: case ARM::VLD2d32wb_register:
+  case ARM::VLD2d8wb_fixed: case ARM::VLD2d8wb_register:
+    if (!Check(S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
+      return MCDisassembler::Fail;
+    break;
+  case ARM::VLD2b16:
+  case ARM::VLD2b32:
+  case ARM::VLD2b8:
+  case ARM::VLD2b16wb_fixed:
+  case ARM::VLD2b16wb_register:
+  case ARM::VLD2b32wb_fixed:
+  case ARM::VLD2b32wb_register:
+  case ARM::VLD2b8wb_fixed:
+  case ARM::VLD2b8wb_register:
+    if (!Check(S, DecodeDPairSpacedRegisterClass(Inst, Rd, Address, Decode=
r)))
+      return MCDisassembler::Fail;
+    break;
+  default:
+    if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
+      return MCDisassembler::Fail;
+  }
=20
   // Second output register
   switch (Inst.getOpcode()) {
-    case ARM::VLD1q8:
-    case ARM::VLD1q16:
-    case ARM::VLD1q32:
-    case ARM::VLD1q64:
-    case ARM::VLD1q8_UPD:
-    case ARM::VLD1q16_UPD:
-    case ARM::VLD1q32_UPD:
-    case ARM::VLD1q64_UPD:
-    case ARM::VLD1d8T:
-    case ARM::VLD1d16T:
-    case ARM::VLD1d32T:
-    case ARM::VLD1d64T:
-    case ARM::VLD1d8T_UPD:
-    case ARM::VLD1d16T_UPD:
-    case ARM::VLD1d32T_UPD:
-    case ARM::VLD1d64T_UPD:
-    case ARM::VLD1d8Q:
-    case ARM::VLD1d16Q:
-    case ARM::VLD1d32Q:
-    case ARM::VLD1d64Q:
-    case ARM::VLD1d8Q_UPD:
-    case ARM::VLD1d16Q_UPD:
-    case ARM::VLD1d32Q_UPD:
-    case ARM::VLD1d64Q_UPD:
-    case ARM::VLD2d8:
-    case ARM::VLD2d16:
-    case ARM::VLD2d32:
-    case ARM::VLD2d8_UPD:
-    case ARM::VLD2d16_UPD:
-    case ARM::VLD2d32_UPD:
-    case ARM::VLD2q8:
-    case ARM::VLD2q16:
-    case ARM::VLD2q32:
-    case ARM::VLD2q8_UPD:
-    case ARM::VLD2q16_UPD:
-    case ARM::VLD2q32_UPD:
     case ARM::VLD3d8:
     case ARM::VLD3d16:
     case ARM::VLD3d32:
@@ -2020,12 +2149,6 @@
       if (!Check(S, DecodeDPRRegisterClass(Inst, (Rd+1)%32, Address, Decod=
er)))
         return MCDisassembler::Fail;
       break;
-    case ARM::VLD2b8:
-    case ARM::VLD2b16:
-    case ARM::VLD2b32:
-    case ARM::VLD2b8_UPD:
-    case ARM::VLD2b16_UPD:
-    case ARM::VLD2b32_UPD:
     case ARM::VLD3q8:
     case ARM::VLD3q16:
     case ARM::VLD3q32:
@@ -2046,28 +2169,6 @@
=20
   // Third output register
   switch(Inst.getOpcode()) {
-    case ARM::VLD1d8T:
-    case ARM::VLD1d16T:
-    case ARM::VLD1d32T:
-    case ARM::VLD1d64T:
-    case ARM::VLD1d8T_UPD:
-    case ARM::VLD1d16T_UPD:
-    case ARM::VLD1d32T_UPD:
-    case ARM::VLD1d64T_UPD:
-    case ARM::VLD1d8Q:
-    case ARM::VLD1d16Q:
-    case ARM::VLD1d32Q:
-    case ARM::VLD1d64Q:
-    case ARM::VLD1d8Q_UPD:
-    case ARM::VLD1d16Q_UPD:
-    case ARM::VLD1d32Q_UPD:
-    case ARM::VLD1d64Q_UPD:
-    case ARM::VLD2q8:
-    case ARM::VLD2q16:
-    case ARM::VLD2q32:
-    case ARM::VLD2q8_UPD:
-    case ARM::VLD2q16_UPD:
-    case ARM::VLD2q32_UPD:
     case ARM::VLD3d8:
     case ARM::VLD3d16:
     case ARM::VLD3d32:
@@ -2104,20 +2205,6 @@
=20
   // Fourth output register
   switch (Inst.getOpcode()) {
-    case ARM::VLD1d8Q:
-    case ARM::VLD1d16Q:
-    case ARM::VLD1d32Q:
-    case ARM::VLD1d64Q:
-    case ARM::VLD1d8Q_UPD:
-    case ARM::VLD1d16Q_UPD:
-    case ARM::VLD1d32Q_UPD:
-    case ARM::VLD1d64Q_UPD:
-    case ARM::VLD2q8:
-    case ARM::VLD2q16:
-    case ARM::VLD2q32:
-    case ARM::VLD2q8_UPD:
-    case ARM::VLD2q16_UPD:
-    case ARM::VLD2q32_UPD:
     case ARM::VLD4d8:
     case ARM::VLD4d16:
     case ARM::VLD4d32:
@@ -2142,31 +2229,58 @@
=20
   // Writeback operand
   switch (Inst.getOpcode()) {
-    case ARM::VLD1d8_UPD:
-    case ARM::VLD1d16_UPD:
-    case ARM::VLD1d32_UPD:
-    case ARM::VLD1d64_UPD:
-    case ARM::VLD1q8_UPD:
-    case ARM::VLD1q16_UPD:
-    case ARM::VLD1q32_UPD:
-    case ARM::VLD1q64_UPD:
-    case ARM::VLD1d8T_UPD:
-    case ARM::VLD1d16T_UPD:
-    case ARM::VLD1d32T_UPD:
-    case ARM::VLD1d64T_UPD:
-    case ARM::VLD1d8Q_UPD:
-    case ARM::VLD1d16Q_UPD:
-    case ARM::VLD1d32Q_UPD:
-    case ARM::VLD1d64Q_UPD:
-    case ARM::VLD2d8_UPD:
-    case ARM::VLD2d16_UPD:
-    case ARM::VLD2d32_UPD:
-    case ARM::VLD2q8_UPD:
-    case ARM::VLD2q16_UPD:
-    case ARM::VLD2q32_UPD:
-    case ARM::VLD2b8_UPD:
-    case ARM::VLD2b16_UPD:
-    case ARM::VLD2b32_UPD:
+    case ARM::VLD1d8wb_fixed:
+    case ARM::VLD1d16wb_fixed:
+    case ARM::VLD1d32wb_fixed:
+    case ARM::VLD1d64wb_fixed:
+    case ARM::VLD1d8wb_register:
+    case ARM::VLD1d16wb_register:
+    case ARM::VLD1d32wb_register:
+    case ARM::VLD1d64wb_register:
+    case ARM::VLD1q8wb_fixed:
+    case ARM::VLD1q16wb_fixed:
+    case ARM::VLD1q32wb_fixed:
+    case ARM::VLD1q64wb_fixed:
+    case ARM::VLD1q8wb_register:
+    case ARM::VLD1q16wb_register:
+    case ARM::VLD1q32wb_register:
+    case ARM::VLD1q64wb_register:
+    case ARM::VLD1d8Twb_fixed:
+    case ARM::VLD1d8Twb_register:
+    case ARM::VLD1d16Twb_fixed:
+    case ARM::VLD1d16Twb_register:
+    case ARM::VLD1d32Twb_fixed:
+    case ARM::VLD1d32Twb_register:
+    case ARM::VLD1d64Twb_fixed:
+    case ARM::VLD1d64Twb_register:
+    case ARM::VLD1d8Qwb_fixed:
+    case ARM::VLD1d8Qwb_register:
+    case ARM::VLD1d16Qwb_fixed:
+    case ARM::VLD1d16Qwb_register:
+    case ARM::VLD1d32Qwb_fixed:
+    case ARM::VLD1d32Qwb_register:
+    case ARM::VLD1d64Qwb_fixed:
+    case ARM::VLD1d64Qwb_register:
+    case ARM::VLD2d8wb_fixed:
+    case ARM::VLD2d16wb_fixed:
+    case ARM::VLD2d32wb_fixed:
+    case ARM::VLD2q8wb_fixed:
+    case ARM::VLD2q16wb_fixed:
+    case ARM::VLD2q32wb_fixed:
+    case ARM::VLD2d8wb_register:
+    case ARM::VLD2d16wb_register:
+    case ARM::VLD2d32wb_register:
+    case ARM::VLD2q8wb_register:
+    case ARM::VLD2q16wb_register:
+    case ARM::VLD2q32wb_register:
+    case ARM::VLD2b8wb_fixed:
+    case ARM::VLD2b16wb_fixed:
+    case ARM::VLD2b32wb_fixed:
+    case ARM::VLD2b8wb_register:
+    case ARM::VLD2b16wb_register:
+    case ARM::VLD2b32wb_register:
+      Inst.addOperand(MCOperand::CreateImm(0));
+      break;
     case ARM::VLD3d8_UPD:
     case ARM::VLD3d16_UPD:
     case ARM::VLD3d32_UPD:
@@ -2191,17 +2305,66 @@
     return MCDisassembler::Fail;
=20
   // AddrMode6 Offset (register)
-  if (Rm =3D=3D 0xD)
-    Inst.addOperand(MCOperand::CreateReg(0));
-  else if (Rm !=3D 0xF) {
-    if (!Check(S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
+  switch (Inst.getOpcode()) {
+  default:
+    // The below have been updated to have explicit am6offset split
+    // between fixed and register offset. For those instructions not
+    // yet updated, we need to add an additional reg0 operand for the
+    // fixed variant.
+    //
+    // The fixed offset encodes as Rm =3D=3D 0xd, so we check for that.
+    if (Rm =3D=3D 0xd) {
+      Inst.addOperand(MCOperand::CreateReg(0));
+      break;
+    }
+    // Fall through to handle the register offset variant.
+  case ARM::VLD1d8wb_fixed:
+  case ARM::VLD1d16wb_fixed:
+  case ARM::VLD1d32wb_fixed:
+  case ARM::VLD1d64wb_fixed:
+  case ARM::VLD1d8Twb_fixed:
+  case ARM::VLD1d16Twb_fixed:
+  case ARM::VLD1d32Twb_fixed:
+  case ARM::VLD1d64Twb_fixed:
+  case ARM::VLD1d8Qwb_fixed:
+  case ARM::VLD1d16Qwb_fixed:
+  case ARM::VLD1d32Qwb_fixed:
+  case ARM::VLD1d64Qwb_fixed:
+  case ARM::VLD1d8wb_register:
+  case ARM::VLD1d16wb_register:
+  case ARM::VLD1d32wb_register:
+  case ARM::VLD1d64wb_register:
+  case ARM::VLD1q8wb_fixed:
+  case ARM::VLD1q16wb_fixed:
+  case ARM::VLD1q32wb_fixed:
+  case ARM::VLD1q64wb_fixed:
+  case ARM::VLD1q8wb_register:
+  case ARM::VLD1q16wb_register:
+  case ARM::VLD1q32wb_register:
+  case ARM::VLD1q64wb_register:
+    // The fixed offset post-increment encodes Rm =3D=3D 0xd. The no-write=
back
+    // variant encodes Rm =3D=3D 0xf. Anything else is a register offset p=
ost-
+    // increment and we need to add the register operand to the instructio=
n.
+    if (Rm !=3D 0xD && Rm !=3D 0xF &&
+        !Check(S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
       return MCDisassembler::Fail;
+    break;
+  case ARM::VLD2d8wb_fixed:
+  case ARM::VLD2d16wb_fixed:
+  case ARM::VLD2d32wb_fixed:
+  case ARM::VLD2b8wb_fixed:
+  case ARM::VLD2b16wb_fixed:
+  case ARM::VLD2b32wb_fixed:
+  case ARM::VLD2q8wb_fixed:
+  case ARM::VLD2q16wb_fixed:
+  case ARM::VLD2q32wb_fixed:
+    break;
   }
=20
   return S;
 }
=20
-static DecodeStatus DecodeVSTInstruction(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVSTInstruction(MCInst &Inst, unsigned Insn,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2214,31 +2377,60 @@
=20
   // Writeback Operand
   switch (Inst.getOpcode()) {
-    case ARM::VST1d8_UPD:
-    case ARM::VST1d16_UPD:
-    case ARM::VST1d32_UPD:
-    case ARM::VST1d64_UPD:
-    case ARM::VST1q8_UPD:
-    case ARM::VST1q16_UPD:
-    case ARM::VST1q32_UPD:
-    case ARM::VST1q64_UPD:
-    case ARM::VST1d8T_UPD:
-    case ARM::VST1d16T_UPD:
-    case ARM::VST1d32T_UPD:
-    case ARM::VST1d64T_UPD:
-    case ARM::VST1d8Q_UPD:
-    case ARM::VST1d16Q_UPD:
-    case ARM::VST1d32Q_UPD:
-    case ARM::VST1d64Q_UPD:
-    case ARM::VST2d8_UPD:
-    case ARM::VST2d16_UPD:
-    case ARM::VST2d32_UPD:
-    case ARM::VST2q8_UPD:
-    case ARM::VST2q16_UPD:
-    case ARM::VST2q32_UPD:
-    case ARM::VST2b8_UPD:
-    case ARM::VST2b16_UPD:
-    case ARM::VST2b32_UPD:
+    case ARM::VST1d8wb_fixed:
+    case ARM::VST1d16wb_fixed:
+    case ARM::VST1d32wb_fixed:
+    case ARM::VST1d64wb_fixed:
+    case ARM::VST1d8wb_register:
+    case ARM::VST1d16wb_register:
+    case ARM::VST1d32wb_register:
+    case ARM::VST1d64wb_register:
+    case ARM::VST1q8wb_fixed:
+    case ARM::VST1q16wb_fixed:
+    case ARM::VST1q32wb_fixed:
+    case ARM::VST1q64wb_fixed:
+    case ARM::VST1q8wb_register:
+    case ARM::VST1q16wb_register:
+    case ARM::VST1q32wb_register:
+    case ARM::VST1q64wb_register:
+    case ARM::VST1d8Twb_fixed:
+    case ARM::VST1d16Twb_fixed:
+    case ARM::VST1d32Twb_fixed:
+    case ARM::VST1d64Twb_fixed:
+    case ARM::VST1d8Twb_register:
+    case ARM::VST1d16Twb_register:
+    case ARM::VST1d32Twb_register:
+    case ARM::VST1d64Twb_register:
+    case ARM::VST1d8Qwb_fixed:
+    case ARM::VST1d16Qwb_fixed:
+    case ARM::VST1d32Qwb_fixed:
+    case ARM::VST1d64Qwb_fixed:
+    case ARM::VST1d8Qwb_register:
+    case ARM::VST1d16Qwb_register:
+    case ARM::VST1d32Qwb_register:
+    case ARM::VST1d64Qwb_register:
+    case ARM::VST2d8wb_fixed:
+    case ARM::VST2d16wb_fixed:
+    case ARM::VST2d32wb_fixed:
+    case ARM::VST2d8wb_register:
+    case ARM::VST2d16wb_register:
+    case ARM::VST2d32wb_register:
+    case ARM::VST2q8wb_fixed:
+    case ARM::VST2q16wb_fixed:
+    case ARM::VST2q32wb_fixed:
+    case ARM::VST2q8wb_register:
+    case ARM::VST2q16wb_register:
+    case ARM::VST2q32wb_register:
+    case ARM::VST2b8wb_fixed:
+    case ARM::VST2b16wb_fixed:
+    case ARM::VST2b32wb_fixed:
+    case ARM::VST2b8wb_register:
+    case ARM::VST2b16wb_register:
+    case ARM::VST2b32wb_register:
+      if (Rm =3D=3D 0xF)
+        return MCDisassembler::Fail;
+      Inst.addOperand(MCOperand::CreateImm(0));
+      break;
     case ARM::VST3d8_UPD:
     case ARM::VST3d16_UPD:
     case ARM::VST3d32_UPD:
@@ -2263,55 +2455,89 @@
     return MCDisassembler::Fail;
=20
   // AddrMode6 Offset (register)
-  if (Rm =3D=3D 0xD)
-    Inst.addOperand(MCOperand::CreateReg(0));
-  else if (Rm !=3D 0xF) {
-    if (!Check(S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
-    return MCDisassembler::Fail;
+  switch (Inst.getOpcode()) {
+    default:
+      if (Rm =3D=3D 0xD)
+        Inst.addOperand(MCOperand::CreateReg(0));
+      else if (Rm !=3D 0xF) {
+        if (!Check(S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
+          return MCDisassembler::Fail;
+      }
+      break;
+    case ARM::VST1d8wb_fixed:
+    case ARM::VST1d16wb_fixed:
+    case ARM::VST1d32wb_fixed:
+    case ARM::VST1d64wb_fixed:
+    case ARM::VST1q8wb_fixed:
+    case ARM::VST1q16wb_fixed:
+    case ARM::VST1q32wb_fixed:
+    case ARM::VST1q64wb_fixed:
+    case ARM::VST1d8Twb_fixed:
+    case ARM::VST1d16Twb_fixed:
+    case ARM::VST1d32Twb_fixed:
+    case ARM::VST1d64Twb_fixed:
+    case ARM::VST1d8Qwb_fixed:
+    case ARM::VST1d16Qwb_fixed:
+    case ARM::VST1d32Qwb_fixed:
+    case ARM::VST1d64Qwb_fixed:
+    case ARM::VST2d8wb_fixed:
+    case ARM::VST2d16wb_fixed:
+    case ARM::VST2d32wb_fixed:
+    case ARM::VST2q8wb_fixed:
+    case ARM::VST2q16wb_fixed:
+    case ARM::VST2q32wb_fixed:
+    case ARM::VST2b8wb_fixed:
+    case ARM::VST2b16wb_fixed:
+    case ARM::VST2b32wb_fixed:
+      break;
   }
=20
+
   // First input register
-  if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
-    return MCDisassembler::Fail;
+  switch (Inst.getOpcode()) {
+  case ARM::VST1q16:
+  case ARM::VST1q32:
+  case ARM::VST1q64:
+  case ARM::VST1q8:
+  case ARM::VST1q16wb_fixed:
+  case ARM::VST1q16wb_register:
+  case ARM::VST1q32wb_fixed:
+  case ARM::VST1q32wb_register:
+  case ARM::VST1q64wb_fixed:
+  case ARM::VST1q64wb_register:
+  case ARM::VST1q8wb_fixed:
+  case ARM::VST1q8wb_register:
+  case ARM::VST2d16:
+  case ARM::VST2d32:
+  case ARM::VST2d8:
+  case ARM::VST2d16wb_fixed:
+  case ARM::VST2d16wb_register:
+  case ARM::VST2d32wb_fixed:
+  case ARM::VST2d32wb_register:
+  case ARM::VST2d8wb_fixed:
+  case ARM::VST2d8wb_register:
+    if (!Check(S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
+      return MCDisassembler::Fail;
+    break;
+  case ARM::VST2b16:
+  case ARM::VST2b32:
+  case ARM::VST2b8:
+  case ARM::VST2b16wb_fixed:
+  case ARM::VST2b16wb_register:
+  case ARM::VST2b32wb_fixed:
+  case ARM::VST2b32wb_register:
+  case ARM::VST2b8wb_fixed:
+  case ARM::VST2b8wb_register:
+    if (!Check(S, DecodeDPairSpacedRegisterClass(Inst, Rd, Address, Decode=
r)))
+      return MCDisassembler::Fail;
+    break;
+  default:
+    if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
+      return MCDisassembler::Fail;
+  }
=20
   // Second input register
   switch (Inst.getOpcode()) {
-    case ARM::VST1q8:
-    case ARM::VST1q16:
-    case ARM::VST1q32:
-    case ARM::VST1q64:
-    case ARM::VST1q8_UPD:
-    case ARM::VST1q16_UPD:
-    case ARM::VST1q32_UPD:
-    case ARM::VST1q64_UPD:
-    case ARM::VST1d8T:
-    case ARM::VST1d16T:
-    case ARM::VST1d32T:
-    case ARM::VST1d64T:
-    case ARM::VST1d8T_UPD:
-    case ARM::VST1d16T_UPD:
-    case ARM::VST1d32T_UPD:
-    case ARM::VST1d64T_UPD:
-    case ARM::VST1d8Q:
-    case ARM::VST1d16Q:
-    case ARM::VST1d32Q:
-    case ARM::VST1d64Q:
-    case ARM::VST1d8Q_UPD:
-    case ARM::VST1d16Q_UPD:
-    case ARM::VST1d32Q_UPD:
-    case ARM::VST1d64Q_UPD:
-    case ARM::VST2d8:
-    case ARM::VST2d16:
-    case ARM::VST2d32:
-    case ARM::VST2d8_UPD:
-    case ARM::VST2d16_UPD:
-    case ARM::VST2d32_UPD:
-    case ARM::VST2q8:
-    case ARM::VST2q16:
-    case ARM::VST2q32:
-    case ARM::VST2q8_UPD:
-    case ARM::VST2q16_UPD:
-    case ARM::VST2q32_UPD:
     case ARM::VST3d8:
     case ARM::VST3d16:
     case ARM::VST3d32:
@@ -2327,12 +2553,6 @@
       if (!Check(S, DecodeDPRRegisterClass(Inst, (Rd+1)%32, Address, Decod=
er)))
         return MCDisassembler::Fail;
       break;
-    case ARM::VST2b8:
-    case ARM::VST2b16:
-    case ARM::VST2b32:
-    case ARM::VST2b8_UPD:
-    case ARM::VST2b16_UPD:
-    case ARM::VST2b32_UPD:
     case ARM::VST3q8:
     case ARM::VST3q16:
     case ARM::VST3q32:
@@ -2354,28 +2574,6 @@
=20
   // Third input register
   switch (Inst.getOpcode()) {
-    case ARM::VST1d8T:
-    case ARM::VST1d16T:
-    case ARM::VST1d32T:
-    case ARM::VST1d64T:
-    case ARM::VST1d8T_UPD:
-    case ARM::VST1d16T_UPD:
-    case ARM::VST1d32T_UPD:
-    case ARM::VST1d64T_UPD:
-    case ARM::VST1d8Q:
-    case ARM::VST1d16Q:
-    case ARM::VST1d32Q:
-    case ARM::VST1d64Q:
-    case ARM::VST1d8Q_UPD:
-    case ARM::VST1d16Q_UPD:
-    case ARM::VST1d32Q_UPD:
-    case ARM::VST1d64Q_UPD:
-    case ARM::VST2q8:
-    case ARM::VST2q16:
-    case ARM::VST2q32:
-    case ARM::VST2q8_UPD:
-    case ARM::VST2q16_UPD:
-    case ARM::VST2q32_UPD:
     case ARM::VST3d8:
     case ARM::VST3d16:
     case ARM::VST3d32:
@@ -2412,20 +2610,6 @@
=20
   // Fourth input register
   switch (Inst.getOpcode()) {
-    case ARM::VST1d8Q:
-    case ARM::VST1d16Q:
-    case ARM::VST1d32Q:
-    case ARM::VST1d64Q:
-    case ARM::VST1d8Q_UPD:
-    case ARM::VST1d16Q_UPD:
-    case ARM::VST1d32Q_UPD:
-    case ARM::VST1d64Q_UPD:
-    case ARM::VST2q8:
-    case ARM::VST2q16:
-    case ARM::VST2q32:
-    case ARM::VST2q8_UPD:
-    case ARM::VST2q16_UPD:
-    case ARM::VST2q32_UPD:
     case ARM::VST4d8:
     case ARM::VST4d16:
     case ARM::VST4d32:
@@ -2451,7 +2635,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVLD1DupInstruction(llvm::MCInst &Inst, unsigned =
Insn,
+static DecodeStatus DecodeVLD1DupInstruction(MCInst &Inst, unsigned Insn,
                                     uint64_t Address, const void *Decoder)=
 {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2461,15 +2645,21 @@
   unsigned Rm =3D fieldFromInstruction32(Insn, 0, 4);
   unsigned align =3D fieldFromInstruction32(Insn, 4, 1);
   unsigned size =3D fieldFromInstruction32(Insn, 6, 2);
-  unsigned regs =3D fieldFromInstruction32(Insn, 5, 1) + 1;
=20
   align *=3D (1 << size);
=20
-  if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
-    return MCDisassembler::Fail;
-  if (regs =3D=3D 2) {
-    if (!Check(S, DecodeDPRRegisterClass(Inst, (Rd+1)%32, Address, Decoder=
)))
+  switch (Inst.getOpcode()) {
+  case ARM::VLD1DUPq16: case ARM::VLD1DUPq32: case ARM::VLD1DUPq8:
+  case ARM::VLD1DUPq16wb_fixed: case ARM::VLD1DUPq16wb_register:
+  case ARM::VLD1DUPq32wb_fixed: case ARM::VLD1DUPq32wb_register:
+  case ARM::VLD1DUPq8wb_fixed: case ARM::VLD1DUPq8wb_register:
+    if (!Check(S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
       return MCDisassembler::Fail;
+    break;
+  default:
+    if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
+      return MCDisassembler::Fail;
+    break;
   }
   if (Rm !=3D 0xF) {
     if (!Check(S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
@@ -2480,6 +2670,57 @@
     return MCDisassembler::Fail;
   Inst.addOperand(MCOperand::CreateImm(align));
=20
+  // The fixed offset post-increment encodes Rm =3D=3D 0xd. The no-writeba=
ck
+  // variant encodes Rm =3D=3D 0xf. Anything else is a register offset pos=
t-
+  // increment and we need to add the register operand to the instruction.
+  if (Rm !=3D 0xD && Rm !=3D 0xF &&
+      !Check(S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
+    return MCDisassembler::Fail;
+
+  return S;
+}
+
+static DecodeStatus DecodeVLD2DupInstruction(MCInst &Inst, unsigned Insn,
+                                    uint64_t Address, const void *Decoder)=
 {
+  DecodeStatus S =3D MCDisassembler::Success;
+
+  unsigned Rd =3D fieldFromInstruction32(Insn, 12, 4);
+  Rd |=3D fieldFromInstruction32(Insn, 22, 1) << 4;
+  unsigned Rn =3D fieldFromInstruction32(Insn, 16, 4);
+  unsigned Rm =3D fieldFromInstruction32(Insn, 0, 4);
+  unsigned align =3D fieldFromInstruction32(Insn, 4, 1);
+  unsigned size =3D 1 << fieldFromInstruction32(Insn, 6, 2);
+  unsigned pred =3D fieldFromInstruction32(Insn, 22, 4);
+  align *=3D 2*size;
+
+  switch (Inst.getOpcode()) {
+  case ARM::VLD2DUPd16: case ARM::VLD2DUPd32: case ARM::VLD2DUPd8:
+  case ARM::VLD2DUPd16wb_fixed: case ARM::VLD2DUPd16wb_register:
+  case ARM::VLD2DUPd32wb_fixed: case ARM::VLD2DUPd32wb_register:
+  case ARM::VLD2DUPd8wb_fixed: case ARM::VLD2DUPd8wb_register:
+    if (!Check(S, DecodeDPairRegisterClass(Inst, Rd, Address, Decoder)))
+      return MCDisassembler::Fail;
+    break;
+  case ARM::VLD2DUPd16x2: case ARM::VLD2DUPd32x2: case ARM::VLD2DUPd8x2:
+  case ARM::VLD2DUPd16x2wb_fixed: case ARM::VLD2DUPd16x2wb_register:
+  case ARM::VLD2DUPd32x2wb_fixed: case ARM::VLD2DUPd32x2wb_register:
+  case ARM::VLD2DUPd8x2wb_fixed: case ARM::VLD2DUPd8x2wb_register:
+    if (!Check(S, DecodeDPairSpacedRegisterClass(Inst, Rd, Address, Decode=
r)))
+      return MCDisassembler::Fail;
+    break;
+  default:
+    if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
+      return MCDisassembler::Fail;
+    break;
+  }
+
+  if (Rm !=3D 0xF)
+    Inst.addOperand(MCOperand::CreateImm(0));
+
+  if (!Check(S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
+    return MCDisassembler::Fail;
+  Inst.addOperand(MCOperand::CreateImm(align));
+
   if (Rm =3D=3D 0xD)
     Inst.addOperand(MCOperand::CreateReg(0));
   else if (Rm !=3D 0xF) {
@@ -2487,46 +2728,13 @@
       return MCDisassembler::Fail;
   }
=20
+  if (!Check(S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
+    return MCDisassembler::Fail;
+
   return S;
 }
=20
-static DecodeStatus DecodeVLD2DupInstruction(llvm::MCInst &Inst, unsigned =
Insn,
-                                    uint64_t Address, const void *Decoder)=
 {
-  DecodeStatus S =3D MCDisassembler::Success;
-
-  unsigned Rd =3D fieldFromInstruction32(Insn, 12, 4);
-  Rd |=3D fieldFromInstruction32(Insn, 22, 1) << 4;
-  unsigned Rn =3D fieldFromInstruction32(Insn, 16, 4);
-  unsigned Rm =3D fieldFromInstruction32(Insn, 0, 4);
-  unsigned align =3D fieldFromInstruction32(Insn, 4, 1);
-  unsigned size =3D 1 << fieldFromInstruction32(Insn, 6, 2);
-  unsigned inc =3D fieldFromInstruction32(Insn, 5, 1) + 1;
-  align *=3D 2*size;
-
-  if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
-    return MCDisassembler::Fail;
-  if (!Check(S, DecodeDPRRegisterClass(Inst, (Rd+inc)%32, Address, Decoder=
)))
-    return MCDisassembler::Fail;
-  if (Rm !=3D 0xF) {
-    if (!Check(S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
-      return MCDisassembler::Fail;
-  }
-
-  if (!Check(S, DecodeGPRRegisterClass(Inst, Rn, Address, Decoder)))
-    return MCDisassembler::Fail;
-  Inst.addOperand(MCOperand::CreateImm(align));
-
-  if (Rm =3D=3D 0xD)
-    Inst.addOperand(MCOperand::CreateReg(0));
-  else if (Rm !=3D 0xF) {
-    if (!Check(S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
-      return MCDisassembler::Fail;
-  }
-
-  return S;
-}
-
-static DecodeStatus DecodeVLD3DupInstruction(llvm::MCInst &Inst, unsigned =
Insn,
+static DecodeStatus DecodeVLD3DupInstruction(MCInst &Inst, unsigned Insn,
                                     uint64_t Address, const void *Decoder)=
 {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2561,7 +2769,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVLD4DupInstruction(llvm::MCInst &Inst, unsigned =
Insn,
+static DecodeStatus DecodeVLD4DupInstruction(MCInst &Inst, unsigned Insn,
                                     uint64_t Address, const void *Decoder)=
 {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2614,7 +2822,7 @@
 }
=20
 static DecodeStatus
-DecodeNEONModImmInstruction(llvm::MCInst &Inst, unsigned Insn,
+DecodeNEONModImmInstruction(MCInst &Inst, unsigned Insn,
                             uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2659,7 +2867,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVSHLMaxInstruction(llvm::MCInst &Inst, unsigned =
Insn,
+static DecodeStatus DecodeVSHLMaxInstruction(MCInst &Inst, unsigned Insn,
                                         uint64_t Address, const void *Deco=
der) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2678,31 +2886,31 @@
   return S;
 }
=20
-static DecodeStatus DecodeShiftRight8Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight8Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   Inst.addOperand(MCOperand::CreateImm(8 - Val));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeShiftRight16Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight16Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   Inst.addOperand(MCOperand::CreateImm(16 - Val));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeShiftRight32Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight32Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   Inst.addOperand(MCOperand::CreateImm(32 - Val));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeShiftRight64Imm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeShiftRight64Imm(MCInst &Inst, unsigned Val,
                                uint64_t Address, const void *Decoder) {
   Inst.addOperand(MCOperand::CreateImm(64 - Val));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeTBLInstruction(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeTBLInstruction(MCInst &Inst, unsigned Insn,
                                uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2713,7 +2921,6 @@
   unsigned Rm =3D fieldFromInstruction32(Insn, 0, 4);
   Rm |=3D fieldFromInstruction32(Insn, 5, 1) << 4;
   unsigned op =3D fieldFromInstruction32(Insn, 6, 1);
-  unsigned length =3D fieldFromInstruction32(Insn, 8, 2) + 1;
=20
   if (!Check(S, DecodeDPRRegisterClass(Inst, Rd, Address, Decoder)))
     return MCDisassembler::Fail;
@@ -2722,9 +2929,15 @@
     return MCDisassembler::Fail; // Writeback
   }
=20
-  for (unsigned i =3D 0; i < length; ++i) {
-    if (!Check(S, DecodeDPRRegisterClass(Inst, (Rn+i)%32, Address, Decoder=
)))
-    return MCDisassembler::Fail;
+  switch (Inst.getOpcode()) {
+  case ARM::VTBL2:
+  case ARM::VTBX2:
+    if (!Check(S, DecodeDPairRegisterClass(Inst, Rn, Address, Decoder)))
+      return MCDisassembler::Fail;
+    break;
+  default:
+    if (!Check(S, DecodeDPRRegisterClass(Inst, Rn, Address, Decoder)))
+      return MCDisassembler::Fail;
   }
=20
   if (!Check(S, DecodeDPRRegisterClass(Inst, Rm, Address, Decoder)))
@@ -2733,7 +2946,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeThumbAddSpecialReg(llvm::MCInst &Inst, uint16_t =
Insn,
+static DecodeStatus DecodeThumbAddSpecialReg(MCInst &Inst, uint16_t Insn,
                                      uint64_t Address, const void *Decoder=
) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2757,25 +2970,31 @@
   return S;
 }
=20
-static DecodeStatus DecodeThumbBROperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbBROperand(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
-  Inst.addOperand(MCOperand::CreateImm(SignExtend32<12>(Val << 1)));
+  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<12>(Val<<1=
) + 4,
+                                true, 2, Inst, Decoder))
+    Inst.addOperand(MCOperand::CreateImm(SignExtend32<12>(Val << 1)));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeT2BROperand(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2BROperand(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
-  Inst.addOperand(MCOperand::CreateImm(SignExtend32<21>(Val)));
+  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<22>(Val<<1=
) + 4,
+                                true, 4, Inst, Decoder))
+    Inst.addOperand(MCOperand::CreateImm(SignExtend32<21>(Val)));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeThumbCmpBROperand(llvm::MCInst &Inst, unsigned V=
al,
+static DecodeStatus DecodeThumbCmpBROperand(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
-  Inst.addOperand(MCOperand::CreateImm(SignExtend32<7>(Val << 1)));
+  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<7>(Val<<1)=
 + 4,
+                                true, 2, Inst, Decoder))
+    Inst.addOperand(MCOperand::CreateImm(SignExtend32<7>(Val << 1)));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeThumbAddrModeRR(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModeRR(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2790,7 +3009,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeThumbAddrModeIS(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModeIS(MCInst &Inst, unsigned Val,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2804,7 +3023,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeThumbAddrModePC(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModePC(MCInst &Inst, unsigned Val,
                                   uint64_t Address, const void *Decoder) {
   unsigned imm =3D Val << 2;
=20
@@ -2814,7 +3033,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeThumbAddrModeSP(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbAddrModeSP(MCInst &Inst, unsigned Val,
                                   uint64_t Address, const void *Decoder) {
   Inst.addOperand(MCOperand::CreateReg(ARM::SP));
   Inst.addOperand(MCOperand::CreateImm(Val));
@@ -2822,7 +3041,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeT2AddrModeSOReg(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2AddrModeSOReg(MCInst &Inst, unsigned Val,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2839,7 +3058,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2LoadShift(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeT2LoadShift(MCInst &Inst, unsigned Insn,
                               uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2894,7 +3113,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2Imm8S4(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2Imm8S4(MCInst &Inst, unsigned Val,
                            uint64_t Address, const void *Decoder) {
   int imm =3D Val & 0xFF;
   if (!(Val & 0x100)) imm *=3D -1;
@@ -2903,7 +3122,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeT2AddrModeImm8s4(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeT2AddrModeImm8s4(MCInst &Inst, unsigned Val,
                                    uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2918,7 +3137,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2AddrModeImm0_1020s4(llvm::MCInst &Inst,unsigne=
d Val,
+static DecodeStatus DecodeT2AddrModeImm0_1020s4(MCInst &Inst,unsigned Val,
                                    uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2933,7 +3152,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2Imm8(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2Imm8(MCInst &Inst, unsigned Val,
                          uint64_t Address, const void *Decoder) {
   int imm =3D Val & 0xFF;
   if (Val =3D=3D 0)
@@ -2946,7 +3165,7 @@
 }
=20
=20
-static DecodeStatus DecodeT2AddrModeImm8(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2AddrModeImm8(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -2977,7 +3196,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2LdStPre(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeT2LdStPre(MCInst &Inst, unsigned Insn,
                                     uint64_t Address, const void *Decoder)=
 {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3007,7 +3226,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2AddrModeImm12(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2AddrModeImm12(MCInst &Inst, unsigned Val,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3022,7 +3241,7 @@
 }
=20
=20
-static DecodeStatus DecodeThumbAddSPImm(llvm::MCInst &Inst, uint16_t Insn,
+static DecodeStatus DecodeThumbAddSPImm(MCInst &Inst, uint16_t Insn,
                                 uint64_t Address, const void *Decoder) {
   unsigned imm =3D fieldFromInstruction16(Insn, 0, 7);
=20
@@ -3033,7 +3252,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeThumbAddSPReg(llvm::MCInst &Inst, uint16_t Insn,
+static DecodeStatus DecodeThumbAddSPReg(MCInst &Inst, uint16_t Insn,
                                 uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3058,7 +3277,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeThumbCPS(llvm::MCInst &Inst, uint16_t Insn,
+static DecodeStatus DecodeThumbCPS(MCInst &Inst, uint16_t Insn,
                            uint64_t Address, const void *Decoder) {
   unsigned imod =3D fieldFromInstruction16(Insn, 4, 1) | 0x2;
   unsigned flags =3D fieldFromInstruction16(Insn, 0, 3);
@@ -3069,29 +3288,29 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodePostIdxReg(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodePostIdxReg(MCInst &Inst, unsigned Insn,
                              uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
   unsigned Rm =3D fieldFromInstruction32(Insn, 0, 4);
   unsigned add =3D fieldFromInstruction32(Insn, 4, 1);
=20
-  if (!Check(S, DecodeGPRRegisterClass(Inst, Rm, Address, Decoder)))
+  if (!Check(S, DecodeGPRnopcRegisterClass(Inst, Rm, Address, Decoder)))
     return MCDisassembler::Fail;
   Inst.addOperand(MCOperand::CreateImm(add));
=20
   return S;
 }
=20
-static DecodeStatus DecodeThumbBLXOffset(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeThumbBLXOffset(MCInst &Inst, unsigned Val,
                                  uint64_t Address, const void *Decoder) {
-  if (!tryAddingSymbolicOperand(Address,=20
+  if (!tryAddingSymbolicOperand(Address,
                                 (Address & ~2u) + SignExtend32<22>(Val << =
1) + 4,
                                 true, 4, Inst, Decoder))
     Inst.addOperand(MCOperand::CreateImm(SignExtend32<22>(Val << 1)));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeCoprocessor(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeCoprocessor(MCInst &Inst, unsigned Val,
                               uint64_t Address, const void *Decoder) {
   if (Val =3D=3D 0xA || Val =3D=3D 0xB)
     return MCDisassembler::Fail;
@@ -3101,7 +3320,7 @@
 }
=20
 static DecodeStatus
-DecodeThumbTableBranch(llvm::MCInst &Inst, unsigned Insn,
+DecodeThumbTableBranch(MCInst &Inst, unsigned Insn,
                        uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3117,7 +3336,7 @@
 }
=20
 static DecodeStatus
-DecodeThumb2BCCInstruction(llvm::MCInst &Inst, unsigned Insn,
+DecodeThumb2BCCInstruction(MCInst &Inst, unsigned Insn,
                            uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3159,7 +3378,7 @@
 // Decode a shifted immediate operand.  These basically consist
 // of an 8-bit value, and a 4-bit directive that specifies either
 // a splat operation or a rotation.
-static DecodeStatus DecodeT2SOImm(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeT2SOImm(MCInst &Inst, unsigned Val,
                           uint64_t Address, const void *Decoder) {
   unsigned ctrl =3D fieldFromInstruction32(Val, 10, 2);
   if (ctrl =3D=3D 0) {
@@ -3191,19 +3410,23 @@
 }
=20
 static DecodeStatus
-DecodeThumbBCCTargetOperand(llvm::MCInst &Inst, unsigned Val,
+DecodeThumbBCCTargetOperand(MCInst &Inst, unsigned Val,
                             uint64_t Address, const void *Decoder){
-  Inst.addOperand(MCOperand::CreateImm(Val << 1));
+  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<8>(Val<<1)=
 + 4,
+                                true, 2, Inst, Decoder))
+    Inst.addOperand(MCOperand::CreateImm(SignExtend32<8>(Val << 1)));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeThumbBLTargetOperand(llvm::MCInst &Inst, unsigne=
d Val,
+static DecodeStatus DecodeThumbBLTargetOperand(MCInst &Inst, unsigned Val,
                                        uint64_t Address, const void *Decod=
er){
-  Inst.addOperand(MCOperand::CreateImm(SignExtend32<22>(Val << 1)));
+  if (!tryAddingSymbolicOperand(Address, Address + SignExtend32<22>(Val<<1=
) + 4,
+                                true, 4, Inst, Decoder))
+    Inst.addOperand(MCOperand::CreateImm(SignExtend32<22>(Val << 1)));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeMemBarrierOption(llvm::MCInst &Inst, unsigned Va=
l,
+static DecodeStatus DecodeMemBarrierOption(MCInst &Inst, unsigned Val,
                                    uint64_t Address, const void *Decoder) {
   switch (Val) {
   default:
@@ -3223,14 +3446,14 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeMSRMask(llvm::MCInst &Inst, unsigned Val,
+static DecodeStatus DecodeMSRMask(MCInst &Inst, unsigned Val,
                           uint64_t Address, const void *Decoder) {
   if (!Val) return MCDisassembler::Fail;
   Inst.addOperand(MCOperand::CreateImm(Val));
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeDoubleRegLoad(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeDoubleRegLoad(MCInst &Inst, unsigned Insn,
                                         uint64_t Address, const void *Deco=
der) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3253,7 +3476,7 @@
 }
=20
=20
-static DecodeStatus DecodeDoubleRegStore(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeDoubleRegStore(MCInst &Inst, unsigned Insn,
                                          uint64_t Address, const void *Dec=
oder){
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3280,7 +3503,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeLDRPreImm(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeLDRPreImm(MCInst &Inst, unsigned Insn,
                             uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3305,7 +3528,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeLDRPreReg(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeLDRPreReg(MCInst &Inst, unsigned Insn,
                             uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3333,7 +3556,7 @@
 }
=20
=20
-static DecodeStatus DecodeSTRPreImm(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeSTRPreImm(MCInst &Inst, unsigned Insn,
                             uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3358,7 +3581,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeSTRPreReg(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeSTRPreReg(MCInst &Inst, unsigned Insn,
                             uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3383,7 +3606,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVLD1LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD1LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3442,7 +3665,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVST1LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST1LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3500,7 +3723,7 @@
 }
=20
=20
-static DecodeStatus DecodeVLD2LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD2LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3567,7 +3790,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVST2LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST2LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3631,7 +3854,7 @@
 }
=20
=20
-static DecodeStatus DecodeVLD3LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD3LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3701,7 +3924,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVST3LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST3LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3765,7 +3988,7 @@
 }
=20
=20
-static DecodeStatus DecodeVLD4LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVLD4LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3839,7 +4062,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVST4LN(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVST4LN(MCInst &Inst, unsigned Insn,
                          uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -3904,7 +4127,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVMOVSRR(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVMOVSRR(MCInst &Inst, unsigned Insn,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
   unsigned Rt  =3D fieldFromInstruction32(Insn, 12, 4);
@@ -3930,7 +4153,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeVMOVRRS(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeVMOVRRS(MCInst &Inst, unsigned Insn,
                                   uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
   unsigned Rt  =3D fieldFromInstruction32(Insn, 12, 4);
@@ -3956,7 +4179,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeIT(llvm::MCInst &Inst, unsigned Insn,
+static DecodeStatus DecodeIT(MCInst &Inst, unsigned Insn,
                              uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
   unsigned pred =3D fieldFromInstruction16(Insn, 4, 4);
@@ -3983,7 +4206,7 @@
 }
=20
 static DecodeStatus
-DecodeT2LDRDPreInstruction(llvm::MCInst &Inst, unsigned Insn,
+DecodeT2LDRDPreInstruction(MCInst &Inst, unsigned Insn,
                            uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -4020,7 +4243,7 @@
 }
=20
 static DecodeStatus
-DecodeT2STRDPreInstruction(llvm::MCInst &Inst, unsigned Insn,
+DecodeT2STRDPreInstruction(MCInst &Inst, unsigned Insn,
                            uint64_t Address, const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
=20
@@ -4054,7 +4277,7 @@
   return S;
 }
=20
-static DecodeStatus DecodeT2Adr(llvm::MCInst &Inst, uint32_t Insn,
+static DecodeStatus DecodeT2Adr(MCInst &Inst, uint32_t Insn,
                                 uint64_t Address, const void *Decoder) {
   unsigned sign1 =3D fieldFromInstruction32(Insn, 21, 1);
   unsigned sign2 =3D fieldFromInstruction32(Insn, 23, 1);
@@ -4069,7 +4292,7 @@
   return MCDisassembler::Success;
 }
=20
-static DecodeStatus DecodeT2ShifterImmOperand(llvm::MCInst &Inst, uint32_t=
 Val,
+static DecodeStatus DecodeT2ShifterImmOperand(MCInst &Inst, uint32_t Val,
                                               uint64_t Address,
                                               const void *Decoder) {
   DecodeStatus S =3D MCDisassembler::Success;
@@ -4080,3 +4303,109 @@
   return S;
 }
=20
+static DecodeStatus DecodeSwap(MCInst &Inst, unsigned Insn,
+                               uint64_t Address, const void *Decoder) {
+  unsigned Rt   =3D fieldFromInstruction32(Insn, 12, 4);
+  unsigned Rt2  =3D fieldFromInstruction32(Insn, 0,  4);
+  unsigned Rn   =3D fieldFromInstruction32(Insn, 16, 4);
+  unsigned pred =3D fieldFromInstruction32(Insn, 28, 4);
+
+  if (pred =3D=3D 0xF)
+    return DecodeCPSInstruction(Inst, Insn, Address, Decoder);
+
+  DecodeStatus S =3D MCDisassembler::Success;
+  if (!Check(S, DecodeGPRnopcRegisterClass(Inst, Rt, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodeGPRnopcRegisterClass(Inst, Rt2, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodeGPRnopcRegisterClass(Inst, Rn, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodePredicateOperand(Inst, pred, Address, Decoder)))
+    return MCDisassembler::Fail;
+
+  return S;
+}
+
+static DecodeStatus DecodeVCVTD(MCInst &Inst, unsigned Insn,
+                                uint64_t Address, const void *Decoder) {
+  unsigned Vd =3D (fieldFromInstruction32(Insn, 12, 4) << 0);
+  Vd |=3D (fieldFromInstruction32(Insn, 22, 1) << 4);
+  unsigned Vm =3D (fieldFromInstruction32(Insn, 0, 4) << 0);
+  Vm |=3D (fieldFromInstruction32(Insn, 5, 1) << 4);
+  unsigned imm =3D fieldFromInstruction32(Insn, 16, 6);
+  unsigned cmode =3D fieldFromInstruction32(Insn, 8, 4);
+
+  DecodeStatus S =3D MCDisassembler::Success;
+
+  // VMOVv2f32 is ambiguous with these decodings.
+  if (!(imm & 0x38) && cmode =3D=3D 0xF) {
+    Inst.setOpcode(ARM::VMOVv2f32);
+    return DecodeNEONModImmInstruction(Inst, Insn, Address, Decoder);
+  }
+
+  if (!(imm & 0x20)) Check(S, MCDisassembler::SoftFail);
+
+  if (!Check(S, DecodeDPRRegisterClass(Inst, Vd, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodeDPRRegisterClass(Inst, Vm, Address, Decoder)))
+    return MCDisassembler::Fail;
+  Inst.addOperand(MCOperand::CreateImm(64 - imm));
+
+  return S;
+}
+
+static DecodeStatus DecodeVCVTQ(MCInst &Inst, unsigned Insn,
+                                uint64_t Address, const void *Decoder) {
+  unsigned Vd =3D (fieldFromInstruction32(Insn, 12, 4) << 0);
+  Vd |=3D (fieldFromInstruction32(Insn, 22, 1) << 4);
+  unsigned Vm =3D (fieldFromInstruction32(Insn, 0, 4) << 0);
+  Vm |=3D (fieldFromInstruction32(Insn, 5, 1) << 4);
+  unsigned imm =3D fieldFromInstruction32(Insn, 16, 6);
+  unsigned cmode =3D fieldFromInstruction32(Insn, 8, 4);
+
+  DecodeStatus S =3D MCDisassembler::Success;
+
+  // VMOVv4f32 is ambiguous with these decodings.
+  if (!(imm & 0x38) && cmode =3D=3D 0xF) {
+    Inst.setOpcode(ARM::VMOVv4f32);
+    return DecodeNEONModImmInstruction(Inst, Insn, Address, Decoder);
+  }
+
+  if (!(imm & 0x20)) Check(S, MCDisassembler::SoftFail);
+
+  if (!Check(S, DecodeQPRRegisterClass(Inst, Vd, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodeQPRRegisterClass(Inst, Vm, Address, Decoder)))
+    return MCDisassembler::Fail;
+  Inst.addOperand(MCOperand::CreateImm(64 - imm));
+
+  return S;
+}
+
+static DecodeStatus DecodeLDR(MCInst &Inst, unsigned Val,
+                                uint64_t Address, const void *Decoder) {
+  DecodeStatus S =3D MCDisassembler::Success;
+
+  unsigned Rn =3D fieldFromInstruction32(Val, 16, 4);
+  unsigned Rt =3D fieldFromInstruction32(Val, 12, 4);
+  unsigned Rm =3D fieldFromInstruction32(Val, 0, 4);
+  Rm |=3D (fieldFromInstruction32(Val, 23, 1) << 4);
+  unsigned Cond =3D fieldFromInstruction32(Val, 28, 4);
+=20
+  if (fieldFromInstruction32(Val, 8, 4) !=3D 0 || Rn =3D=3D Rt)
+    S =3D MCDisassembler::SoftFail;
+
+  if (!Check(S, DecodeGPRnopcRegisterClass(Inst, Rt, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodeGPRnopcRegisterClass(Inst, Rn, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodeAddrMode7Operand(Inst, Rn, Address, Decoder)))=20
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodePostIdxReg(Inst, Rm, Address, Decoder)))
+    return MCDisassembler::Fail;
+  if (!Check(S, DecodePredicateOperand(Inst, Cond, Address, Decoder)))
+    return MCDisassembler::Fail;
+
+  return S;
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/InstP=
rinter/ARMInstPrinter.cpp
--- a/head/contrib/llvm/lib/Target/ARM/InstPrinter/ARMInstPrinter.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/InstPrinter/ARMInstPrinter.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -18,11 +18,11 @@
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCExpr.h"
-#include "llvm/ADT/StringExtras.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
=20
-#define GET_INSTRUCTION_NAME
 #include "ARMGenAsmWriter.inc"
=20
 /// translateShiftImm - Convert shift immediate from 0-31 to 1-32 for prin=
ting.
@@ -36,16 +36,14 @@
=20
=20
 ARMInstPrinter::ARMInstPrinter(const MCAsmInfo &MAI,
+                               const MCInstrInfo &MII,
+                               const MCRegisterInfo &MRI,
                                const MCSubtargetInfo &STI) :
-  MCInstPrinter(MAI) {
+  MCInstPrinter(MAI, MII, MRI) {
   // Initialize the set of available features.
   setAvailableFeatures(STI.getFeatureBits());
 }
=20
-StringRef ARMInstPrinter::getOpcodeName(unsigned Opcode) const {
-  return getInstructionName(Opcode);
-}
-
 void ARMInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
   OS << getRegisterName(RegNo);
 }
@@ -101,7 +99,9 @@
=20
   // A8.6.123 PUSH
   if ((Opcode =3D=3D ARM::STMDB_UPD || Opcode =3D=3D ARM::t2STMDB_UPD) &&
-      MI->getOperand(0).getReg() =3D=3D ARM::SP) {
+      MI->getOperand(0).getReg() =3D=3D ARM::SP &&
+      MI->getNumOperands() > 5) {
+    // Should only print PUSH if there are at least two registers in the l=
ist.
     O << '\t' << "push";
     printPredicateOperand(MI, 2, O);
     if (Opcode =3D=3D ARM::t2STMDB_UPD)
@@ -122,7 +122,9 @@
=20
   // A8.6.122 POP
   if ((Opcode =3D=3D ARM::LDMIA_UPD || Opcode =3D=3D ARM::t2LDMIA_UPD) &&
-      MI->getOperand(0).getReg() =3D=3D ARM::SP) {
+      MI->getOperand(0).getReg() =3D=3D ARM::SP &&
+      MI->getNumOperands() > 5) {
+    // Should only print POP if there are at least two registers in the li=
st.
     O << '\t' << "pop";
     printPredicateOperand(MI, 2, O);
     if (Opcode =3D=3D ARM::t2LDMIA_UPD)
@@ -250,7 +252,7 @@
   O << ", " << ARM_AM::getShiftOpcStr(ShOpc);
   if (ShOpc =3D=3D ARM_AM::rrx)
     return;
- =20
+
   O << ' ' << getRegisterName(MO2.getReg());
   assert(ARM_AM::getSORegOffset(MO3.getImm()) =3D=3D 0);
 }
@@ -433,6 +435,12 @@
=20
 void ARMInstPrinter::printAddrMode3Operand(const MCInst *MI, unsigned Op,
                                            raw_ostream &O) {
+  const MCOperand &MO1 =3D MI->getOperand(Op);
+  if (!MO1.isReg()) {   //  For label symbolic references.
+    printOperand(MI, Op, O);
+    return;
+  }
+
   const MCOperand &MO3 =3D MI->getOperand(Op+2);
   unsigned IdxMode =3D ARM_AM::getAM3IdxMode(MO3.getImm());
=20
@@ -636,7 +644,7 @@
=20
   if (getAvailableFeatures() & ARM::FeatureMClass) {
     switch (Op.getImm()) {
-    default: assert(0 && "Unexpected mask value!");
+    default: llvm_unreachable("Unexpected mask value!");
     case 0: O << "apsr"; return;
     case 1: O << "iapsr"; return;
     case 2: O << "eapsr"; return;
@@ -659,12 +667,11 @@
   if (!SpecRegRBit && (Mask =3D=3D 8 || Mask =3D=3D 4 || Mask =3D=3D 12)) {
     O << "APSR_";
     switch (Mask) {
-    default: assert(0);
+    default: llvm_unreachable("Unexpected mask value!");
     case 4:  O << "g"; return;
     case 8:  O << "nzcvq"; return;
     case 12: O << "nzcvqg"; return;
     }
-    llvm_unreachable("Unexpected mask value!");
   }
=20
   if (SpecRegRBit)
@@ -684,7 +691,10 @@
 void ARMInstPrinter::printPredicateOperand(const MCInst *MI, unsigned OpNu=
m,
                                            raw_ostream &O) {
   ARMCC::CondCodes CC =3D (ARMCC::CondCodes)MI->getOperand(OpNum).getImm();
-  if (CC !=3D ARMCC::AL)
+  // Handle the undefined 15 CC value here for printing so we don't abort(=
).
+  if ((unsigned)CC =3D=3D 15)
+    O << "<und>";
+  else if (CC !=3D ARMCC::AL)
     O << ARMCondCodeToString(CC);
 }
=20
@@ -882,6 +892,11 @@
   const MCOperand &MO1 =3D MI->getOperand(OpNum);
   const MCOperand &MO2 =3D MI->getOperand(OpNum+1);
=20
+  if (!MO1.isReg()) {   //  For label symbolic references.
+    printOperand(MI, OpNum, O);
+    return;
+  }
+
   O << "[" << getRegisterName(MO1.getReg());
=20
   int32_t OffImm =3D (int32_t)MO2.getImm() / 4;
@@ -963,7 +978,8 @@
   unsigned EncodedImm =3D MI->getOperand(OpNum).getImm();
   unsigned EltBits;
   uint64_t Val =3D ARM_AM::decodeNEONModImm(EncodedImm, EltBits);
-  O << "#0x" << utohexstr(Val);
+  O << "#0x";
+  O.write_hex(Val);
 }
=20
 void ARMInstPrinter::printImmPlusOneOperand(const MCInst *MI, unsigned OpN=
um,
@@ -986,7 +1002,153 @@
   }
 }
=20
+void ARMInstPrinter::printFBits16(const MCInst *MI, unsigned OpNum,
+                                  raw_ostream &O) {
+  O << "#" << 16 - MI->getOperand(OpNum).getImm();
+}
+
+void ARMInstPrinter::printFBits32(const MCInst *MI, unsigned OpNum,
+                                  raw_ostream &O) {
+  O << "#" << 32 - MI->getOperand(OpNum).getImm();
+}
+
 void ARMInstPrinter::printVectorIndex(const MCInst *MI, unsigned OpNum,
                                       raw_ostream &O) {
   O << "[" << MI->getOperand(OpNum).getImm() << "]";
 }
+
+void ARMInstPrinter::printVectorListOne(const MCInst *MI, unsigned OpNum,
+                                        raw_ostream &O) {
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << "}";
+}
+
+void ARMInstPrinter::printVectorListTwo(const MCInst *MI, unsigned OpNum,
+                                          raw_ostream &O) {
+  unsigned Reg =3D MI->getOperand(OpNum).getReg();
+  unsigned Reg0 =3D MRI.getSubReg(Reg, ARM::dsub_0);
+  unsigned Reg1 =3D MRI.getSubReg(Reg, ARM::dsub_1);
+  O << "{" << getRegisterName(Reg0) << ", " << getRegisterName(Reg1) << "}=
";
+}
+
+void ARMInstPrinter::printVectorListTwoSpaced(const MCInst *MI,
+                                              unsigned OpNum,
+                                              raw_ostream &O) {
+  unsigned Reg =3D MI->getOperand(OpNum).getReg();
+  unsigned Reg0 =3D MRI.getSubReg(Reg, ARM::dsub_0);
+  unsigned Reg1 =3D MRI.getSubReg(Reg, ARM::dsub_2);
+  O << "{" << getRegisterName(Reg0) << ", " << getRegisterName(Reg1) << "}=
";
+}
+
+void ARMInstPrinter::printVectorListThree(const MCInst *MI, unsigned OpNum,
+                                          raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 1) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << "}";
+}
+
+void ARMInstPrinter::printVectorListFour(const MCInst *MI, unsigned OpNum,
+                                         raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 1) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 3) << "}";
+}
+
+void ARMInstPrinter::printVectorListOneAllLanes(const MCInst *MI,
+                                                unsigned OpNum,
+                                                raw_ostream &O) {
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << "[]}";
+}
+
+void ARMInstPrinter::printVectorListTwoAllLanes(const MCInst *MI,
+                                                unsigned OpNum,
+                                                raw_ostream &O) {
+  unsigned Reg =3D MI->getOperand(OpNum).getReg();
+  unsigned Reg0 =3D MRI.getSubReg(Reg, ARM::dsub_0);
+  unsigned Reg1 =3D MRI.getSubReg(Reg, ARM::dsub_1);
+  O << "{" << getRegisterName(Reg0) << "[], " << getRegisterName(Reg1) << =
"[]}";
+}
+
+void ARMInstPrinter::printVectorListThreeAllLanes(const MCInst *MI,
+                                                  unsigned OpNum,
+                                                  raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 1) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << "[]}";
+}
+
+void ARMInstPrinter::printVectorListFourAllLanes(const MCInst *MI,
+                                                  unsigned OpNum,
+                                                  raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 1) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 3) << "[]}";
+}
+
+void ARMInstPrinter::printVectorListTwoSpacedAllLanes(const MCInst *MI,
+                                                      unsigned OpNum,
+                                                      raw_ostream &O) {
+  unsigned Reg =3D MI->getOperand(OpNum).getReg();
+  unsigned Reg0 =3D MRI.getSubReg(Reg, ARM::dsub_0);
+  unsigned Reg1 =3D MRI.getSubReg(Reg, ARM::dsub_2);
+  O << "{" << getRegisterName(Reg0) << "[], " << getRegisterName(Reg1) << =
"[]}";
+}
+
+void ARMInstPrinter::printVectorListThreeSpacedAllLanes(const MCInst *MI,
+                                                        unsigned OpNum,
+                                                        raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 4) << "[]}";
+}
+
+void ARMInstPrinter::printVectorListFourSpacedAllLanes(const MCInst *MI,
+                                                       unsigned OpNum,
+                                                       raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 4) << "[], "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 6) << "[]}";
+}
+
+void ARMInstPrinter::printVectorListThreeSpaced(const MCInst *MI,
+                                                unsigned OpNum,
+                                                raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 4) << "}";
+}
+
+void ARMInstPrinter::printVectorListFourSpaced(const MCInst *MI,
+                                                unsigned OpNum,
+                                                raw_ostream &O) {
+  // Normally, it's not safe to use register enum values directly with
+  // addition to get the next register, but for VFP registers, the
+  // sort order is guaranteed because they're all of the form D<n>.
+  O << "{" << getRegisterName(MI->getOperand(OpNum).getReg()) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 2) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 4) << ", "
+    << getRegisterName(MI->getOperand(OpNum).getReg() + 6) << "}";
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/InstP=
rinter/ARMInstPrinter.h
--- a/head/contrib/llvm/lib/Target/ARM/InstPrinter/ARMInstPrinter.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/InstPrinter/ARMInstPrinter.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMInstPrinter.h - Convert ARM MCInst to assembly syntax ---=
-------=3D=3D=3D//
+//=3D=3D=3D- ARMInstPrinter.h - Convert ARM MCInst to assembly syntax -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,14 +23,12 @@
=20
 class ARMInstPrinter : public MCInstPrinter {
 public:
-    ARMInstPrinter(const MCAsmInfo &MAI, const MCSubtargetInfo &STI);
+  ARMInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                 const MCRegisterInfo &MRI, const MCSubtargetInfo &STI);
=20
   virtual void printInst(const MCInst *MI, raw_ostream &O, StringRef Annot=
);
-  virtual StringRef getOpcodeName(unsigned Opcode) const;
   virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
=20
-  static const char *getInstructionName(unsigned Opcode);
-
   // Autogenerated by tblgen.
   void printInstruction(const MCInst *MI, raw_ostream &O);
   static const char *getRegisterName(unsigned RegNo);
@@ -128,7 +126,33 @@
=20
   void printPCLabel(const MCInst *MI, unsigned OpNum, raw_ostream &O);
   void printT2LdrLabelOperand(const MCInst *MI, unsigned OpNum, raw_ostrea=
m &O);
+  void printFBits16(const MCInst *MI, unsigned OpNum, raw_ostream &O);
+  void printFBits32(const MCInst *MI, unsigned OpNum, raw_ostream &O);
   void printVectorIndex(const MCInst *MI, unsigned OpNum, raw_ostream &O);
+  void printVectorListOne(const MCInst *MI, unsigned OpNum, raw_ostream &O=
);
+  void printVectorListTwo(const MCInst *MI, unsigned OpNum, raw_ostream &O=
);
+  void printVectorListTwoSpaced(const MCInst *MI, unsigned OpNum,
+                               raw_ostream &O);
+  void printVectorListThree(const MCInst *MI, unsigned OpNum, raw_ostream =
&O);
+  void printVectorListFour(const MCInst *MI, unsigned OpNum, raw_ostream &=
O);
+  void printVectorListOneAllLanes(const MCInst *MI, unsigned OpNum,
+                                  raw_ostream &O);
+  void printVectorListTwoAllLanes(const MCInst *MI, unsigned OpNum,
+                                  raw_ostream &O);
+  void printVectorListThreeAllLanes(const MCInst *MI, unsigned OpNum,
+                                    raw_ostream &O);
+  void printVectorListFourAllLanes(const MCInst *MI, unsigned OpNum,
+                                   raw_ostream &O);
+  void printVectorListTwoSpacedAllLanes(const MCInst *MI, unsigned OpNum,
+                                        raw_ostream &O);
+  void printVectorListThreeSpacedAllLanes(const MCInst *MI, unsigned OpNum,
+                                          raw_ostream &O);
+  void printVectorListFourSpacedAllLanes(const MCInst *MI, unsigned OpNum,
+                                         raw_ostream &O);
+  void printVectorListThreeSpaced(const MCInst *MI, unsigned OpNum,
+                                  raw_ostream &O);
+  void printVectorListFourSpaced(const MCInst *MI, unsigned OpNum,
+                                  raw_ostream &O);
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMAddressingModes.h
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMAddressingModes.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- ARMAddressingModes.h - ARM Addressing Modes --------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMAddressingModes.h - ARM Addressing Modes -------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -16,6 +16,7 @@
=20
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/APInt.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include <cassert>
=20
@@ -43,7 +44,7 @@
=20
   static inline const char *getShiftOpcStr(ShiftOpc Op) {
     switch (Op) {
-    default: assert(0 && "Unknown shift opc!");
+    default: llvm_unreachable("Unknown shift opc!");
     case ARM_AM::asr: return "asr";
     case ARM_AM::lsl: return "lsl";
     case ARM_AM::lsr: return "lsr";
@@ -54,7 +55,7 @@
=20
   static inline unsigned getShiftOpcEncoding(ShiftOpc Op) {
     switch (Op) {
-    default: assert(0 && "Unknown shift opc!");
+    default: llvm_unreachable("Unknown shift opc!");
     case ARM_AM::asr: return 2;
     case ARM_AM::lsl: return 0;
     case ARM_AM::lsr: return 1;
@@ -72,7 +73,7 @@
=20
   static inline const char *getAMSubModeStr(AMSubMode Mode) {
     switch (Mode) {
-    default: assert(0 && "Unknown addressing sub-mode!");
+    default: llvm_unreachable("Unknown addressing sub-mode!");
     case ARM_AM::ia: return "ia";
     case ARM_AM::ib: return "ib";
     case ARM_AM::da: return "da";
@@ -569,7 +570,7 @@
       }
       EltBits =3D 64;
     } else {
-      assert(false && "Unsupported NEON immediate");
+      llvm_unreachable("Unsupported NEON immediate");
     }
     return Val;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMAsmBackend.cpp
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMAsmBackend.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -11,17 +11,18 @@
 #include "MCTargetDesc/ARMBaseInfo.h"
 #include "MCTargetDesc/ARMFixupKinds.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
-#include "llvm/ADT/Twine.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCDirectives.h"
 #include "llvm/MC/MCELFObjectWriter.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCFixupKindInfo.h"
 #include "llvm/MC/MCMachObjectWriter.h"
 #include "llvm/MC/MCObjectWriter.h"
 #include "llvm/MC/MCSectionELF.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/MC/MCValue.h"
 #include "llvm/Object/MachOFormat.h"
 #include "llvm/Support/ELF.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -31,8 +32,8 @@
 namespace {
 class ARMELFObjectWriter : public MCELFObjectTargetWriter {
 public:
-  ARMELFObjectWriter(Triple::OSType OSType)
-    : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSType, ELF::EM_ARM,
+  ARMELFObjectWriter(uint8_t OSABI)
+    : MCELFObjectTargetWriter(/*Is64Bit*/ false, OSABI, ELF::EM_ARM,
                               /*HasRelocationAddend*/ false) {}
 };
=20
@@ -60,15 +61,16 @@
 // ARMFixupKinds.h.
 //
 // Name                      Offset (bits) Size (bits)     Flags
-{ "fixup_arm_ldst_pcrel_12", 1,            24,  MCFixupKindInfo::FKF_IsPCR=
el },
+{ "fixup_arm_ldst_pcrel_12", 0,            32,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_t2_ldst_pcrel_12",  0,            32,  MCFixupKindInfo::FKF_IsPCR=
el |
                                    MCFixupKindInfo::FKF_IsAlignedDownTo32B=
its},
-{ "fixup_arm_pcrel_10",      1,            24,  MCFixupKindInfo::FKF_IsPCR=
el },
+{ "fixup_arm_pcrel_10_unscaled", 0,        32,  MCFixupKindInfo::FKF_IsPCR=
el },
+{ "fixup_arm_pcrel_10",      0,            32,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_t2_pcrel_10",       0,            32,  MCFixupKindInfo::FKF_IsPCR=
el |
                                    MCFixupKindInfo::FKF_IsAlignedDownTo32B=
its},
 { "fixup_thumb_adr_pcrel_10",0,            8,   MCFixupKindInfo::FKF_IsPCR=
el |
                                    MCFixupKindInfo::FKF_IsAlignedDownTo32B=
its},
-{ "fixup_arm_adr_pcrel_12",  1,            24,  MCFixupKindInfo::FKF_IsPCR=
el },
+{ "fixup_arm_adr_pcrel_12",  0,            32,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_t2_adr_pcrel_12",   0,            32,  MCFixupKindInfo::FKF_IsPCR=
el |
                                    MCFixupKindInfo::FKF_IsAlignedDownTo32B=
its},
 { "fixup_arm_condbranch",    0,            24,  MCFixupKindInfo::FKF_IsPCR=
el },
@@ -76,6 +78,9 @@
 { "fixup_t2_condbranch",     0,            32,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_t2_uncondbranch",   0,            32,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_arm_thumb_br",      0,            16,  MCFixupKindInfo::FKF_IsPCR=
el },
+{ "fixup_arm_uncondbl",      0,            24,  MCFixupKindInfo::FKF_IsPCR=
el },
+{ "fixup_arm_condbl",        0,            24,  MCFixupKindInfo::FKF_IsPCR=
el },
+{ "fixup_arm_blx",           0,            24,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_arm_thumb_bl",      0,            32,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_arm_thumb_blx",     0,            32,  MCFixupKindInfo::FKF_IsPCR=
el },
 { "fixup_arm_thumb_cb",      0,            16,  MCFixupKindInfo::FKF_IsPCR=
el },
@@ -100,13 +105,50 @@
     return Infos[Kind - FirstTargetFixupKind];
   }
=20
-  bool MayNeedRelaxation(const MCInst &Inst) const;
+  /// processFixupValue - Target hook to process the literal value of a fi=
xup
+  /// if necessary.
+  void processFixupValue(const MCAssembler &Asm, const MCAsmLayout &Layout,
+                         const MCFixup &Fixup, const MCFragment *DF,
+                         MCValue &Target, uint64_t &Value,
+                         bool &IsResolved) {
+    const MCSymbolRefExpr *A =3D Target.getSymA();
+    // Some fixups to thumb function symbols need the low bit (thumb bit)
+    // twiddled.
+    if ((unsigned)Fixup.getKind() !=3D ARM::fixup_arm_ldst_pcrel_12 &&
+        (unsigned)Fixup.getKind() !=3D ARM::fixup_t2_ldst_pcrel_12 &&
+        (unsigned)Fixup.getKind() !=3D ARM::fixup_arm_adr_pcrel_12 &&
+        (unsigned)Fixup.getKind() !=3D ARM::fixup_thumb_adr_pcrel_10 &&
+        (unsigned)Fixup.getKind() !=3D ARM::fixup_t2_adr_pcrel_12 &&
+        (unsigned)Fixup.getKind() !=3D ARM::fixup_arm_thumb_cp) {
+      if (A) {
+        const MCSymbol &Sym =3D A->getSymbol().AliasedSymbol();
+        if (Asm.isThumbFunc(&Sym))
+          Value |=3D 1;
+      }
+    }
+    // We must always generate a relocation for BL/BLX instructions if we =
have
+    // a symbol to reference, as the linker relies on knowing the destinat=
ion
+    // symbol's thumb-ness to get interworking right.
+    if (A && ((unsigned)Fixup.getKind() =3D=3D ARM::fixup_arm_thumb_blx ||
+              (unsigned)Fixup.getKind() =3D=3D ARM::fixup_arm_thumb_bl ||
+              (unsigned)Fixup.getKind() =3D=3D ARM::fixup_arm_blx ||
+              (unsigned)Fixup.getKind() =3D=3D ARM::fixup_arm_uncondbl ||
+              (unsigned)Fixup.getKind() =3D=3D ARM::fixup_arm_condbl))
+      IsResolved =3D false;
+  }
=20
-  void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
+  bool mayNeedRelaxation(const MCInst &Inst) const;
=20
-  bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
+  bool fixupNeedsRelaxation(const MCFixup &Fixup,
+                            uint64_t Value,
+                            const MCInstFragment *DF,
+                            const MCAsmLayout &Layout) const;
=20
-  void HandleAssemblerFlag(MCAssemblerFlag Flag) {
+  void relaxInstruction(const MCInst &Inst, MCInst &Res) const;
+
+  bool writeNopData(uint64_t Count, MCObjectWriter *OW) const;
+
+  void handleAssemblerFlag(MCAssemblerFlag Flag) {
     switch (Flag) {
     default: break;
     case MCAF_Code16:
@@ -124,21 +166,81 @@
 };
 } // end anonymous namespace
=20
-bool ARMAsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
-  // FIXME: Thumb targets, different move constant targets..
+static unsigned getRelaxedOpcode(unsigned Op) {
+  switch (Op) {
+  default: return Op;
+  case ARM::tBcc:       return ARM::t2Bcc;
+  case ARM::tLDRpciASM: return ARM::t2LDRpci;
+  case ARM::tADR:       return ARM::t2ADR;
+  case ARM::tB:         return ARM::t2B;
+  }
+}
+
+bool ARMAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
+  if (getRelaxedOpcode(Inst.getOpcode()) !=3D Inst.getOpcode())
+    return true;
   return false;
 }
=20
-void ARMAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) cons=
t {
-  assert(0 && "ARMAsmBackend::RelaxInstruction() unimplemented");
-  return;
+bool ARMAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
+                                         uint64_t Value,
+                                         const MCInstFragment *DF,
+                                         const MCAsmLayout &Layout) const {
+  switch ((unsigned)Fixup.getKind()) {
+  case ARM::fixup_arm_thumb_br: {
+    // Relaxing tB to t2B. tB has a signed 12-bit displacement with the
+    // low bit being an implied zero. There's an implied +4 offset for the
+    // branch, so we adjust the other way here to determine what's
+    // encodable.
+    //
+    // Relax if the value is too big for a (signed) i8.
+    int64_t Offset =3D int64_t(Value) - 4;
+    return Offset > 2046 || Offset < -2048;
+  }
+  case ARM::fixup_arm_thumb_bcc: {
+    // Relaxing tBcc to t2Bcc. tBcc has a signed 9-bit displacement with t=
he
+    // low bit being an implied zero. There's an implied +4 offset for the
+    // branch, so we adjust the other way here to determine what's
+    // encodable.
+    //
+    // Relax if the value is too big for a (signed) i8.
+    int64_t Offset =3D int64_t(Value) - 4;
+    return Offset > 254 || Offset < -256;
+  }
+  case ARM::fixup_thumb_adr_pcrel_10:
+  case ARM::fixup_arm_thumb_cp: {
+    // If the immediate is negative, greater than 1020, or not a multiple
+    // of four, the wide version of the instruction must be used.
+    int64_t Offset =3D int64_t(Value) - 4;
+    return Offset > 1020 || Offset < 0 || Offset & 3;
+  }
+  }
+  llvm_unreachable("Unexpected fixup kind in fixupNeedsRelaxation()!");
 }
=20
-bool ARMAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const=
 {
+void ARMAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) cons=
t {
+  unsigned RelaxedOp =3D getRelaxedOpcode(Inst.getOpcode());
+
+  // Sanity check w/ diagnostic if we get here w/ a bogus instruction.
+  if (RelaxedOp =3D=3D Inst.getOpcode()) {
+    SmallString<256> Tmp;
+    raw_svector_ostream OS(Tmp);
+    Inst.dump_pretty(OS);
+    OS << "\n";
+    report_fatal_error("unexpected instruction to relax: " + OS.str());
+  }
+
+  // The instructions we're relaxing have (so far) the same operands.
+  // We just need to update to the proper opcode.
+  Res =3D Inst;
+  Res.setOpcode(RelaxedOp);
+}
+
+bool ARMAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const=
 {
   const uint16_t Thumb1_16bitNopEncoding =3D 0x46c0; // using MOV r8,r8
   const uint16_t Thumb2_16bitNopEncoding =3D 0xbf00; // NOP
   const uint32_t ARMv4_NopEncoding =3D 0xe1a0000; // using MOV r0,r0
-  const uint32_t ARMv6T2_NopEncoding =3D 0xe3207800; // NOP
+  const uint32_t ARMv6T2_NopEncoding =3D 0xe320f000; // NOP
   if (isThumb()) {
     const uint16_t nopEncoding =3D hasNOP() ? Thumb2_16bitNopEncoding
                                           : Thumb1_16bitNopEncoding;
@@ -269,6 +371,9 @@
=20
   case ARM::fixup_arm_condbranch:
   case ARM::fixup_arm_uncondbranch:
+  case ARM::fixup_arm_uncondbl:
+  case ARM::fixup_arm_condbl:
+  case ARM::fixup_arm_blx:
     // These values don't encode the low two bits since they're always zer=
o.
     // Offset by 8 just as above.
     return 0xffffff & ((Value - 8) >> 2);
@@ -359,6 +464,19 @@
   case ARM::fixup_arm_thumb_bcc:
     // Offset by 4 and don't encode the lower bit, which is always 0.
     return ((Value - 4) >> 1) & 0xff;
+  case ARM::fixup_arm_pcrel_10_unscaled: {
+    Value =3D Value - 8; // ARM fixups offset by an additional word and do=
n't
+                       // need to adjust for the half-word ordering.
+    bool isAdd =3D true;
+    if ((int64_t)Value < 0) {
+      Value =3D -Value;
+      isAdd =3D false;
+    }
+    // The value has the low 4 bits encoded in [3:0] and the high 4 in [11=
:8].
+    assert ((Value < 256) && "Out of range pc-relative fixup value!");
+    Value =3D (Value & 0xf) | ((Value & 0xf0) << 4);
+    return Value | (isAdd << 23);
+  }
   case ARM::fixup_arm_pcrel_10:
     Value =3D Value - 4; // ARM fixups offset by an additional word and do=
n't
                        // need to adjust for the half-word ordering.
@@ -376,8 +494,8 @@
     assert ((Value < 256) && "Out of range pc-relative fixup value!");
     Value |=3D isAdd << 23;
=20
-    // Same addressing mode as fixup_arm_pcrel_10,
-    // but with 16-bit halfwords swapped.
+    // Same addressing mode as fixup_arm_pcrel_10, but with 16-bit halfwor=
ds
+    // swapped.
     if (Kind =3D=3D ARM::fixup_t2_pcrel_10) {
       uint32_t swapped =3D (Value & 0xFFFF0000) >> 16;
       swapped |=3D (Value & 0x0000FFFF) << 16;
@@ -395,22 +513,21 @@
 // ELF is an ELF of course...
 class ELFARMAsmBackend : public ARMAsmBackend {
 public:
-  Triple::OSType OSType;
+  uint8_t OSABI;
   ELFARMAsmBackend(const Target &T, const StringRef TT,
-                   Triple::OSType _OSType)
-    : ARMAsmBackend(T, TT), OSType(_OSType) { }
+                   uint8_t _OSABI)
+    : ARMAsmBackend(T, TT), OSABI(_OSABI) { }
=20
-  void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+  void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
                   uint64_t Value) const;
=20
   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
-    return createELFObjectWriter(new ARMELFObjectWriter(OSType), OS,
-                              /*IsLittleEndian*/ true);
+    return createARMELFObjectWriter(OS, OSABI);
   }
 };
=20
 // FIXME: Raise this to share code between Darwin and ELF.
-void ELFARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
+void ELFARMAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
                                   unsigned DataSize, uint64_t Value) const=
 {
   unsigned NumBytes =3D 4;        // FIXME: 2 for Thumb
   Value =3D adjustFixupValue(Fixup.getKind(), Value);
@@ -439,7 +556,7 @@
                                      Subtype);
   }
=20
-  void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+  void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
                   uint64_t Value) const;
=20
   virtual bool doesSectionRequireSymbols(const MCSection &Section) const {
@@ -464,9 +581,13 @@
   case ARM::fixup_arm_thumb_cb:
     return 2;
=20
+  case ARM::fixup_arm_pcrel_10_unscaled:
   case ARM::fixup_arm_ldst_pcrel_12:
   case ARM::fixup_arm_pcrel_10:
   case ARM::fixup_arm_adr_pcrel_12:
+  case ARM::fixup_arm_uncondbl:
+  case ARM::fixup_arm_condbl:
+  case ARM::fixup_arm_blx:
   case ARM::fixup_arm_condbranch:
   case ARM::fixup_arm_uncondbranch:
     return 3;
@@ -491,7 +612,7 @@
   }
 }
=20
-void DarwinARMAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
+void DarwinARMAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
                                      unsigned DataSize, uint64_t Value) co=
nst {
   unsigned NumBytes =3D getFixupKindNumBytes(Fixup.getKind());
   Value =3D adjustFixupValue(Fixup.getKind(), Value);
@@ -527,5 +648,6 @@
   if (TheTriple.isOSWindows())
     assert(0 && "Windows not supported on ARM");
=20
-  return new ELFARMAsmBackend(T, TT, Triple(TT).getOS());
+  uint8_t OSABI =3D MCELFObjectTargetWriter::getOSABI(Triple(TT).getOS());
+  return new ELFARMAsmBackend(T, TT, OSABI);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMBaseInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMBaseInfo.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -67,7 +67,6 @@
=20
 inline static const char *ARMCondCodeToString(ARMCC::CondCodes CC) {
   switch (CC) {
-  default: llvm_unreachable("Unknown condition code");
   case ARMCC::EQ:  return "eq";
   case ARMCC::NE:  return "ne";
   case ARMCC::HS:  return "hs";
@@ -84,6 +83,7 @@
   case ARMCC::LE:  return "le";
   case ARMCC::AL:  return "al";
   }
+  llvm_unreachable("Unknown condition code");
 }
=20
 namespace ARM_PROC {
@@ -185,6 +185,39 @@
   case S29: case D29: return 29;
   case S30: case D30: return 30;
   case S31: case D31: return 31;
+
+  // Composite registers use the regnum of the first register in the list.
+  /* Q0  */     case D0_D2:   return 0;
+  case D1_D2:   case D1_D3:   return 1;
+  /* Q1  */     case D2_D4:   return 2;
+  case D3_D4:   case D3_D5:   return 3;
+  /* Q2  */     case D4_D6:   return 4;
+  case D5_D6:   case D5_D7:   return 5;
+  /* Q3  */     case D6_D8:   return 6;
+  case D7_D8:   case D7_D9:   return 7;
+  /* Q4  */     case D8_D10:  return 8;
+  case D9_D10:  case D9_D11:  return 9;
+  /* Q5  */     case D10_D12: return 10;
+  case D11_D12: case D11_D13: return 11;
+  /* Q6  */     case D12_D14: return 12;
+  case D13_D14: case D13_D15: return 13;
+  /* Q7  */     case D14_D16: return 14;
+  case D15_D16: case D15_D17: return 15;
+  /* Q8  */     case D16_D18: return 16;
+  case D17_D18: case D17_D19: return 17;
+  /* Q9  */     case D18_D20: return 18;
+  case D19_D20: case D19_D21: return 19;
+  /* Q10 */     case D20_D22: return 20;
+  case D21_D22: case D21_D23: return 21;
+  /* Q11 */     case D22_D24: return 22;
+  case D23_D24: case D23_D25: return 23;
+  /* Q12 */     case D24_D26: return 24;
+  case D25_D26: case D25_D27: return 25;
+  /* Q13 */     case D26_D28: return 26;
+  case D27_D28: case D27_D29: return 27;
+  /* Q14 */     case D28_D30: return 28;
+  case D29_D30: case D29_D31: return 29;
+  /* Q15 */
   }
 }
=20
@@ -237,7 +270,6 @@
=20
   inline static const char *AddrModeToString(AddrMode addrmode) {
     switch (addrmode) {
-    default: llvm_unreachable("Unknown memory operation");
     case AddrModeNone:    return "AddrModeNone";
     case AddrMode1:       return "AddrMode1";
     case AddrMode2:       return "AddrMode2";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMFixupKinds.h
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMFixupKinds.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARM/ARMFixupKinds.h - ARM Specific Fixup Entries --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMFixupKinds.h - ARM Specific Fixup Entries ------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,6 +23,9 @@
   // the 16-bit halfwords reordered.
   fixup_t2_ldst_pcrel_12,
=20
+  // fixup_arm_pcrel_10_unscaled - 10-bit PC relative relocation for symbol
+  // addresses used in LDRD/LDRH/LDRB/etc. instructions. All bits are enco=
ded.
+  fixup_arm_pcrel_10_unscaled,
   // fixup_arm_pcrel_10 - 10-bit PC relative relocation for symbol address=
es
   // used in VFP instructions where the lower 2 bits are not encoded
   // (so it's encoded as an 8-bit immediate).
@@ -56,6 +59,25 @@
   // fixup_arm_thumb_br - 12-bit fixup for Thumb B instructions.
   fixup_arm_thumb_br,
=20
+  // The following fixups handle the ARM BL instructions. These can be
+  // conditionalised; however, the ARM ELF ABI requires a different reloca=
tion
+  // in that case: R_ARM_JUMP24 instead of R_ARM_CALL. The difference is t=
hat
+  // R_ARM_CALL is allowed to change the instruction to a BLX inline, whic=
h has
+  // no conditional version; R_ARM_JUMP24 would have to insert a veneer.
+  //
+  // MachO does not draw a distinction between the two cases, so it will t=
reat
+  // fixup_arm_uncondbl and fixup_arm_condbl as identical fixups.
+
+  // fixup_arm_uncondbl - Fixup for unconditional ARM BL instructions.
+  fixup_arm_uncondbl,
+
+  // fixup_arm_condbl - Fixup for ARM BL instructions with nontrivial
+  // conditionalisation.
+  fixup_arm_condbl,
+
+  // fixup_arm_blx - Fixup for ARM BLX instructions.
+  fixup_arm_blx,
+
   // fixup_arm_thumb_bl - Fixup for Thumb BL instructions.
   fixup_arm_thumb_bl,
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMMCAsmInfo.cpp - ARM asm properties -------------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMMCAsmInfo.cpp - ARM asm properties ----------------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -48,6 +48,8 @@
   0,0
 };
=20
+void ARMMCAsmInfoDarwin::anchor() { }
+
 ARMMCAsmInfoDarwin::ARMMCAsmInfoDarwin() {
   AsmTransCBE =3D arm_asm_table;
   Data64bitsDirective =3D 0;
@@ -61,6 +63,8 @@
   ExceptionsType =3D ExceptionHandling::SjLj;
 }
=20
+void ARMELFMCAsmInfo::anchor() { }
+
 ARMELFMCAsmInfo::ARMELFMCAsmInfo() {
   // ".comm align is in bytes but .align is pow-2."
   AlignmentIsInBytes =3D false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCAsmInfo.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- ARMMCAsmInfo.h - ARM asm properties -------------*- C+=
+ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- ARMMCAsmInfo.h - ARM asm properties --------------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,11 +18,15 @@
=20
 namespace llvm {
=20
-  struct ARMMCAsmInfoDarwin : public MCAsmInfoDarwin {
+  class ARMMCAsmInfoDarwin : public MCAsmInfoDarwin {
+    virtual void anchor();
+  public:
     explicit ARMMCAsmInfoDarwin();
   };
=20
-  struct ARMELFMCAsmInfo : public MCAsmInfo {
+  class ARMELFMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit ARMELFMCAsmInfo();
   };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMCCodeEmitter.cpp
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCCodeEmitter.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -64,7 +64,7 @@
=20
   // getBinaryCodeForInstr - TableGen'erated function for getting the
   // binary encoding for an instruction.
-  unsigned getBinaryCodeForInstr(const MCInst &MI,
+  uint64_t getBinaryCodeForInstr(const MCInst &MI,
                                  SmallVectorImpl<MCFixup> &Fixups) const;
=20
   /// getMachineOpValue - Return binary encoding of operand. If the machine
@@ -118,8 +118,10 @@
   /// branch target.
   uint32_t getARMBranchTargetOpValue(const MCInst &MI, unsigned OpIdx,
                                      SmallVectorImpl<MCFixup> &Fixups) con=
st;
+  uint32_t getARMBLTargetOpValue(const MCInst &MI, unsigned OpIdx,
+                                 SmallVectorImpl<MCFixup> &Fixups) const;
   uint32_t getARMBLXTargetOpValue(const MCInst &MI, unsigned OpIdx,
-                                     SmallVectorImpl<MCFixup> &Fixups) con=
st;
+                                  SmallVectorImpl<MCFixup> &Fixups) const;
=20
   /// getAdrLabelOpValue - Return encoding info for 12-bit immediate
   /// ADR label target.
@@ -166,7 +168,7 @@
                                SmallVectorImpl<MCFixup> &Fixups) const {
     ARM_AM::AMSubMode Mode =3D (ARM_AM::AMSubMode)MI.getOperand(OpIdx).get=
Imm();
     switch (Mode) {
-    default: assert(0 && "Unknown addressing sub-mode!");
+    default: llvm_unreachable("Unknown addressing sub-mode!");
     case ARM_AM::da: return 0;
     case ARM_AM::ia: return 1;
     case ARM_AM::db: return 2;
@@ -177,7 +179,6 @@
   ///
   unsigned getShiftOp(ARM_AM::ShiftOpc ShOpc) const {
     switch (ShOpc) {
-    default: llvm_unreachable("Unknown shift opc!");
     case ARM_AM::no_shift:
     case ARM_AM::lsl: return 0;
     case ARM_AM::lsr: return 1;
@@ -185,7 +186,7 @@
     case ARM_AM::ror:
     case ARM_AM::rrx: return 3;
     }
-    return 0;
+    llvm_unreachable("Invalid ShiftOpc!");
   }
=20
   /// getAddrMode2OpValue - Return encoding for addrmode2 operands.
@@ -423,7 +424,6 @@
   }
=20
   llvm_unreachable("Unable to encode MCOperand!");
-  return 0;
 }
=20
 /// getAddrModeImmOpValue - Return encoding info for 'reg +/- imm' operand.
@@ -466,7 +466,7 @@
   assert(MO.isExpr() && "Unexpected branch target type!");
   const MCExpr *Expr =3D MO.getExpr();
   MCFixupKind Kind =3D MCFixupKind(FixupKind);
-  Fixups.push_back(MCFixup::Create(0, Expr, Kind));
+  Fixups.push_back(MCFixup::Create(0, Expr, Kind, MI.getLoc()));
=20
   // All of the information is in the fixup.
   return 0;
@@ -594,17 +594,26 @@
 }
=20
 uint32_t ARMMCCodeEmitter::
-getARMBLXTargetOpValue(const MCInst &MI, unsigned OpIdx,
+getARMBLTargetOpValue(const MCInst &MI, unsigned OpIdx,
                           SmallVectorImpl<MCFixup> &Fixups) const {
   const MCOperand MO =3D MI.getOperand(OpIdx);
   if (MO.isExpr()) {
     if (HasConditionalBranch(MI))
-      return ::getBranchTargetOpValue(MI, OpIdx,
-                                      ARM::fixup_arm_condbranch, Fixups);
-    return ::getBranchTargetOpValue(MI, OpIdx,
-                                    ARM::fixup_arm_uncondbranch, Fixups);
+      return ::getBranchTargetOpValue(MI, OpIdx,=20
+                                      ARM::fixup_arm_condbl, Fixups);
+    return ::getBranchTargetOpValue(MI, OpIdx, ARM::fixup_arm_uncondbl, Fi=
xups);
   }
=20
+  return MO.getImm() >> 2;
+}
+
+uint32_t ARMMCCodeEmitter::
+getARMBLXTargetOpValue(const MCInst &MI, unsigned OpIdx,
+                          SmallVectorImpl<MCFixup> &Fixups) const {
+  const MCOperand MO =3D MI.getOperand(OpIdx);
+  if (MO.isExpr())
+    return ::getBranchTargetOpValue(MI, OpIdx, ARM::fixup_arm_blx, Fixups);
+
   return MO.getImm() >> 1;
 }
=20
@@ -718,12 +727,13 @@
         Kind =3D MCFixupKind(ARM::fixup_t2_ldst_pcrel_12);
       else
         Kind =3D MCFixupKind(ARM::fixup_arm_ldst_pcrel_12);
-      Fixups.push_back(MCFixup::Create(0, Expr, Kind));
+      Fixups.push_back(MCFixup::Create(0, Expr, Kind, MI.getLoc()));
=20
       ++MCNumCPRelocations;
     } else {
       Reg =3D ARM::PC;
       int32_t Offset =3D MO.getImm();
+      // FIXME: Handle #-0.
       if (Offset < 0) {
         Offset *=3D -1;
         isAdd =3D false;
@@ -791,8 +801,8 @@
=20
     assert(MO.isExpr() && "Unexpected machine operand type!");
     const MCExpr *Expr =3D MO.getExpr();
-    MCFixupKind Kind =3D MCFixupKind(ARM::fixup_arm_pcrel_10);
-    Fixups.push_back(MCFixup::Create(0, Expr, Kind));
+    MCFixupKind Kind =3D MCFixupKind(ARM::fixup_t2_pcrel_10);
+    Fixups.push_back(MCFixup::Create(0, Expr, Kind, MI.getLoc()));
=20
     ++MCNumCPRelocations;
   } else
@@ -833,7 +843,7 @@
 // but this is good enough for now.
 static bool EvaluateAsPCRel(const MCExpr *Expr) {
   switch (Expr->getKind()) {
-  default: assert(0 && "Unexpected expression type");
+  default: llvm_unreachable("Unexpected expression type");
   case MCExpr::SymbolRef: return false;
   case MCExpr::Binary: return true;
   }
@@ -857,7 +867,7 @@
=20
     MCFixupKind Kind;
     switch (ARM16Expr->getKind()) {
-    default: assert(0 && "Unsupported ARMFixup");
+    default: llvm_unreachable("Unsupported ARMFixup");
     case ARMMCExpr::VK_ARM_HI16:
       if (!isTargetDarwin() && EvaluateAsPCRel(E))
         Kind =3D MCFixupKind(isThumb2()
@@ -879,12 +889,11 @@
                            : ARM::fixup_arm_movw_lo16);
       break;
     }
-    Fixups.push_back(MCFixup::Create(0, E, Kind));
+    Fixups.push_back(MCFixup::Create(0, E, Kind, MI.getLoc()));
     return 0;
   };
=20
   llvm_unreachable("Unsupported MCExpr type in MCOperand!");
-  return 0;
 }
=20
 uint32_t ARMMCCodeEmitter::
@@ -993,6 +1002,19 @@
   const MCOperand &MO =3D MI.getOperand(OpIdx);
   const MCOperand &MO1 =3D MI.getOperand(OpIdx+1);
   const MCOperand &MO2 =3D MI.getOperand(OpIdx+2);
+
+  // If The first operand isn't a register, we have a label reference.
+  if (!MO.isReg()) {
+    unsigned Rn =3D getARMRegisterNumbering(ARM::PC);   // Rn is PC.
+
+    assert(MO.isExpr() && "Unexpected machine operand type!");
+    const MCExpr *Expr =3D MO.getExpr();
+    MCFixupKind Kind =3D MCFixupKind(ARM::fixup_arm_pcrel_10_unscaled);
+    Fixups.push_back(MCFixup::Create(0, Expr, Kind, MI.getLoc()));
+
+    ++MCNumCPRelocations;
+    return (Rn << 9) | (1 << 13);
+  }
   unsigned Rn =3D getARMRegisterNumbering(MO.getReg());
   unsigned Imm =3D MO2.getImm();
   bool isAdd =3D ARM_AM::getAM3Op(Imm) =3D=3D ARM_AM::add;
@@ -1066,7 +1088,7 @@
       Kind =3D MCFixupKind(ARM::fixup_t2_pcrel_10);
     else
       Kind =3D MCFixupKind(ARM::fixup_arm_pcrel_10);
-    Fixups.push_back(MCFixup::Create(0, Expr, Kind));
+    Fixups.push_back(MCFixup::Create(0, Expr, Kind, MI.getLoc()));
=20
     ++MCNumCPRelocations;
   } else {
@@ -1312,8 +1334,8 @@
   // LDM/STM:
   //   {15-0}  =3D Bitfield of GPRs.
   unsigned Reg =3D MI.getOperand(Op).getReg();
-  bool SPRRegs =3D llvm::ARMMCRegisterClasses[ARM::SPRRegClassID].contains=
(Reg);
-  bool DPRRegs =3D llvm::ARMMCRegisterClasses[ARM::DPRRegClassID].contains=
(Reg);
+  bool SPRRegs =3D ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg);
+  bool DPRRegs =3D ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg);
=20
   unsigned Binary =3D 0;
=20
@@ -1372,11 +1394,11 @@
=20
   switch (Imm.getImm()) {
   default: break;
-  case 2:
-  case 4:
   case 8:
-  case 16: Align =3D 0x00; break;
-  case 32: Align =3D 0x03; break;
+  case 16:
+  case 32: // Default '0' value for invalid alignments of 8, 16, 32 bytes.
+  case 2: Align =3D 0x00; break;
+  case 4: Align =3D 0x03; break;
   }
=20
   return RegNo | (Align << 4);
@@ -1412,7 +1434,7 @@
                           SmallVectorImpl<MCFixup> &Fixups) const {
   const MCOperand &MO =3D MI.getOperand(Op);
   if (MO.getReg() =3D=3D 0) return 0x0D;
-  return MO.getReg();
+  return getARMRegisterNumbering(MO.getReg());
 }
=20
 unsigned ARMMCCodeEmitter::
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMCExpr.cpp
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
=20
 void ARMMCExpr::PrintImpl(raw_ostream &OS) const {
   switch (Kind) {
-  default: assert(0 && "Invalid kind!");
+  default: llvm_unreachable("Invalid kind!");
   case VK_ARM_HI16: OS << ":upper16:"; break;
   case VK_ARM_LO16: OS << ":lower16:"; break;
   }
@@ -45,8 +45,7 @@
 static void AddValueSymbols_(const MCExpr *Value, MCAssembler *Asm) {
   switch (Value->getKind()) {
   case MCExpr::Target:
-    assert(0 && "Can't handle nested target expr!");
-    break;
+    llvm_unreachable("Can't handle nested target expr!");
=20
   case MCExpr::Constant:
     break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMCExpr.h
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCExpr.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMMCExpr.h - ARM specific MC expression classes -----------=
-------=3D=3D=3D//
+//=3D=3D=3D-- ARMMCExpr.h - ARM specific MC expression classes --------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- ARMMCTargetDesc.cpp - ARM Target Descriptions -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- ARMMCTargetDesc.cpp - ARM Target Descriptions --------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -89,14 +89,6 @@
       ARMArchFeature +=3D ",+thumb-mode";
   }
=20
-  Triple TheTriple(TT);
-  if (TheTriple.getOS() =3D=3D Triple::NativeClient) {
-    if (ARMArchFeature.empty())
-      ARMArchFeature =3D "+nacl-mode";
-    else
-      ARMArchFeature +=3D ",+nacl-mode";
-  }
-
   return ARMArchFeature;
 }
=20
@@ -137,14 +129,15 @@
 }
=20
 static MCCodeGenInfo *createARMMCCodeGenInfo(StringRef TT, Reloc::Model RM,
-                                             CodeModel::Model CM) {
+                                             CodeModel::Model CM,
+                                             CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
   if (RM =3D=3D Reloc::Default) {
     Triple TheTriple(TT);
     // Default relocation model on Darwin is PIC, not DynamicNoPIC.
     RM =3D TheTriple.isOSDarwin() ? Reloc::PIC_ : Reloc::DynamicNoPIC;
   }
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
@@ -158,22 +151,23 @@
   Triple TheTriple(TT);
=20
   if (TheTriple.isOSDarwin())
-    return createMachOStreamer(Ctx, MAB, OS, Emitter, RelaxAll);
+    return createMachOStreamer(Ctx, MAB, OS, Emitter, false);
=20
   if (TheTriple.isOSWindows()) {
     llvm_unreachable("ARM does not support Windows COFF format");
-    return NULL;
   }
=20
-  return createELFStreamer(Ctx, MAB, OS, Emitter, RelaxAll, NoExecStack);
+  return createELFStreamer(Ctx, MAB, OS, Emitter, false, NoExecStack);
 }
=20
 static MCInstPrinter *createARMMCInstPrinter(const Target &T,
                                              unsigned SyntaxVariant,
                                              const MCAsmInfo &MAI,
+                                             const MCInstrInfo &MII,
+                                             const MCRegisterInfo &MRI,
                                              const MCSubtargetInfo &STI) {
   if (SyntaxVariant =3D=3D 0)
-    return new ARMInstPrinter(MAI, STI);
+    return new ARMInstPrinter(MAI, MII, MRI, STI);
   return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -46,6 +46,10 @@
=20
 MCAsmBackend *createARMAsmBackend(const Target &T, StringRef TT);
=20
+/// createARMELFObjectWriter - Construct an ELF Mach-O object writer.
+MCObjectWriter *createARMELFObjectWriter(raw_ostream &OS,
+                                         uint8_t OSABI);
+
 /// createARMMachObjectWriter - Construct an ARM Mach-O object writer.
 MCObjectWriter *createARMMachObjectWriter(raw_ostream &OS,
                                           bool Is64Bit,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MCTar=
getDesc/ARMMachObjectWriter.cpp
--- a/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MCTargetDesc/ARMMachObjectWriter.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -13,9 +13,11 @@
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCAsmLayout.h"
 #include "llvm/MC/MCMachObjectWriter.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCFixup.h"
 #include "llvm/MC/MCFixupKindInfo.h"
+#include "llvm/MC/MCMachOSymbolFlags.h"
 #include "llvm/MC/MCValue.h"
 #include "llvm/Object/MachOFormat.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -32,12 +34,12 @@
                                     MCValue Target,
                                     unsigned Log2Size,
                                     uint64_t &FixedValue);
-  void RecordARMMovwMovtRelocation(MachObjectWriter *Writer,
-                                   const MCAssembler &Asm,
-                                   const MCAsmLayout &Layout,
-                                   const MCFragment *Fragment,
-                                   const MCFixup &Fixup, MCValue Target,
-                                   uint64_t &FixedValue);
+  void RecordARMScatteredHalfRelocation(MachObjectWriter *Writer,
+                                        const MCAssembler &Asm,
+                                        const MCAsmLayout &Layout,
+                                        const MCFragment *Fragment,
+                                        const MCFixup &Fixup, MCValue Targ=
et,
+                                        uint64_t &FixedValue);
=20
 public:
   ARMMachObjectWriter(bool Is64Bit, uint32_t CPUType,
@@ -80,6 +82,9 @@
   case ARM::fixup_arm_adr_pcrel_12:
   case ARM::fixup_arm_condbranch:
   case ARM::fixup_arm_uncondbranch:
+  case ARM::fixup_arm_uncondbl:
+  case ARM::fixup_arm_condbl:
+  case ARM::fixup_arm_blx:
     RelocType =3D unsigned(macho::RIT_ARM_Branch24Bit);
     // Report as 'long', even though that is not quite accurate.
     Log2Size =3D llvm::Log2_32(4);
@@ -98,34 +103,47 @@
     Log2Size =3D llvm::Log2_32(4);
     return true;
=20
+  // For movw/movt r_type relocations they always have a pair following th=
em and
+  // the r_length bits are used differently.  The encoding of the r_length=
 is as
+  // follows:
+  //   low bit of r_length:
+  //      0 - :lower16: for movw instructions
+  //      1 - :upper16: for movt instructions
+  //   high bit of r_length:
+  //      0 - arm instructions
+  //      1 - thumb instructions
   case ARM::fixup_arm_movt_hi16:
   case ARM::fixup_arm_movt_hi16_pcrel:
+    RelocType =3D unsigned(macho::RIT_ARM_Half);
+    Log2Size =3D 1;
+    return true;
   case ARM::fixup_t2_movt_hi16:
   case ARM::fixup_t2_movt_hi16_pcrel:
-    RelocType =3D unsigned(macho::RIT_ARM_HalfDifference);
-    // Report as 'long', even though that is not quite accurate.
-    Log2Size =3D llvm::Log2_32(4);
+    RelocType =3D unsigned(macho::RIT_ARM_Half);
+    Log2Size =3D 3;
     return true;
=20
   case ARM::fixup_arm_movw_lo16:
   case ARM::fixup_arm_movw_lo16_pcrel:
+    RelocType =3D unsigned(macho::RIT_ARM_Half);
+    Log2Size =3D 0;
+    return true;
   case ARM::fixup_t2_movw_lo16:
   case ARM::fixup_t2_movw_lo16_pcrel:
     RelocType =3D unsigned(macho::RIT_ARM_Half);
-    // Report as 'long', even though that is not quite accurate.
-    Log2Size =3D llvm::Log2_32(4);
+    Log2Size =3D 2;
     return true;
   }
 }
=20
 void ARMMachObjectWriter::
-RecordARMMovwMovtRelocation(MachObjectWriter *Writer,
-                            const MCAssembler &Asm,
-                            const MCAsmLayout &Layout,
-                            const MCFragment *Fragment,
-                            const MCFixup &Fixup,
-                            MCValue Target,
-                            uint64_t &FixedValue) {
+RecordARMScatteredHalfRelocation(MachObjectWriter *Writer,
+                                 const MCAssembler &Asm,
+                                 const MCAsmLayout &Layout,
+                                 const MCFragment *Fragment,
+                                 const MCFixup &Fixup,
+                                 MCValue Target,
+                                 uint64_t &FixedValue) {
   uint32_t FixupOffset =3D Layout.getFragmentOffset(Fragment)+Fixup.getOff=
set();
   unsigned IsPCRel =3D Writer->isFixupKindPCRel(Asm, Fixup.getKind());
   unsigned Type =3D macho::RIT_ARM_Half;
@@ -135,7 +153,8 @@
   MCSymbolData *A_SD =3D &Asm.getSymbolData(*A);
=20
   if (!A_SD->getFragment())
-    report_fatal_error("symbol '" + A->getName() +
+    Asm.getContext().FatalError(Fixup.getLoc(),
+                       "symbol '" + A->getName() +
                        "' can not be undefined in a subtraction expression=
");
=20
   uint32_t Value =3D Writer->getSymbolAddress(A_SD, Layout);
@@ -148,7 +167,8 @@
     MCSymbolData *B_SD =3D &Asm.getSymbolData(B->getSymbol());
=20
     if (!B_SD->getFragment())
-      report_fatal_error("symbol '" + B->getSymbol().getName() +
+      Asm.getContext().FatalError(Fixup.getLoc(),
+                         "symbol '" + B->getSymbol().getName() +
                          "' can not be undefined in a subtraction expressi=
on");
=20
     // Select the appropriate difference relocation type.
@@ -178,9 +198,16 @@
   case ARM::fixup_arm_movt_hi16:
   case ARM::fixup_arm_movt_hi16_pcrel:
     MovtBit =3D 1;
+    // The thumb bit shouldn't be set in the 'other-half' bit of the
+    // relocation, but it will be set in FixedValue if the base symbol
+    // is a thumb function. Clear it out here.
+    if (A_SD->getFlags() & SF_ThumbFunc)
+      FixedValue &=3D 0xfffffffe;
     break;
   case ARM::fixup_t2_movt_hi16:
   case ARM::fixup_t2_movt_hi16_pcrel:
+    if (A_SD->getFlags() & SF_ThumbFunc)
+      FixedValue &=3D 0xfffffffe;
     MovtBit =3D 1;
     // Fallthrough
   case ARM::fixup_t2_movw_lo16:
@@ -189,7 +216,6 @@
     break;
   }
=20
-
   if (Type =3D=3D macho::RIT_ARM_HalfDifference) {
     uint32_t OtherHalf =3D MovtBit
       ? (FixedValue & 0xffff) : ((FixedValue & 0xffff0000) >> 16);
@@ -233,7 +259,8 @@
   MCSymbolData *A_SD =3D &Asm.getSymbolData(*A);
=20
   if (!A_SD->getFragment())
-    report_fatal_error("symbol '" + A->getName() +
+    Asm.getContext().FatalError(Fixup.getLoc(),
+                       "symbol '" + A->getName() +
                        "' can not be undefined in a subtraction expression=
");
=20
   uint32_t Value =3D Writer->getSymbolAddress(A_SD, Layout);
@@ -245,7 +272,8 @@
     MCSymbolData *B_SD =3D &Asm.getSymbolData(B->getSymbol());
=20
     if (!B_SD->getFragment())
-      report_fatal_error("symbol '" + B->getSymbol().getName() +
+      Asm.getContext().FatalError(Fixup.getLoc(),
+                         "symbol '" + B->getSymbol().getName() +
                          "' can not be undefined in a subtraction expressi=
on");
=20
     // Select the appropriate difference relocation type.
@@ -287,19 +315,21 @@
   unsigned IsPCRel =3D Writer->isFixupKindPCRel(Asm, Fixup.getKind());
   unsigned Log2Size;
   unsigned RelocType =3D macho::RIT_Vanilla;
-  if (!getARMFixupKindMachOInfo(Fixup.getKind(), RelocType, Log2Size)) {
-    report_fatal_error("unknown ARM fixup kind!");
-    return;
-  }
+  if (!getARMFixupKindMachOInfo(Fixup.getKind(), RelocType, Log2Size))
+    // If we failed to get fixup kind info, it's because there's no legal
+    // relocation type for the fixup kind. This happens when it's a fixup =
that's
+    // expected to always be resolvable at assembly time and not have any
+    // relocations needed.
+    Asm.getContext().FatalError(Fixup.getLoc(),
+                                "unsupported relocation on symbol");
=20
   // If this is a difference or a defined symbol plus an offset, then we n=
eed a
   // scattered relocation entry.  Differences always require scattered
   // relocations.
   if (Target.getSymB()) {
-    if (RelocType =3D=3D macho::RIT_ARM_Half ||
-        RelocType =3D=3D macho::RIT_ARM_HalfDifference)
-      return RecordARMMovwMovtRelocation(Writer, Asm, Layout, Fragment, Fi=
xup,
-                                         Target, FixedValue);
+    if (RelocType =3D=3D macho::RIT_ARM_Half)
+      return RecordARMScatteredHalfRelocation(Writer, Asm, Layout, Fragmen=
t,
+                                              Fixup, Target, FixedValue);
     return RecordARMScatteredRelocation(Writer, Asm, Layout, Fragment, Fix=
up,
                                         Target, Log2Size, FixedValue);
   }
@@ -374,6 +404,30 @@
                (Log2Size  << 25) |
                (IsExtern  << 27) |
                (Type      << 28));
+
+  // Even when it's not a scattered relocation, movw/movt always uses
+  // a PAIR relocation.
+  if (Type =3D=3D macho::RIT_ARM_Half) {
+    // The other-half value only gets populated for the movt relocation.
+    uint32_t Value =3D 0;;
+    switch ((unsigned)Fixup.getKind()) {
+    default: break;
+    case ARM::fixup_arm_movt_hi16:
+    case ARM::fixup_arm_movt_hi16_pcrel:
+    case ARM::fixup_t2_movt_hi16:
+    case ARM::fixup_t2_movt_hi16_pcrel:
+      Value =3D FixedValue;
+      break;
+    }
+    macho::RelocationEntry MREPair;
+    MREPair.Word0 =3D Value;
+    MREPair.Word1 =3D ((0xffffff) |
+                     (Log2Size << 25) |
+                     (macho::RIT_Pair << 28));
+
+    Writer->addRelocation(Fragment->getParent(), MREPair);
+  }
+
   Writer->addRelocation(Fragment->getParent(), MRE);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/MLxEx=
pansionPass.cpp
--- a/head/contrib/llvm/lib/Target/ARM/MLxExpansionPass.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/MLxExpansionPass.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MLxExpansionPass.cpp - Expand MLx instrs to avoid hazards --=
--------=3D//
+//=3D=3D=3D-- MLxExpansionPass.cpp - Expand MLx instrs to avoid hazards --=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -139,7 +139,7 @@
   // FIXME: Detect integer instructions properly.
   const MCInstrDesc &MCID =3D MI->getDesc();
   unsigned Domain =3D MCID.TSFlags & ARMII::DomainMask;
-  if (MCID.mayStore())
+  if (MI->mayStore())
     return false;
   unsigned Opcode =3D MCID.getOpcode();
   if (Opcode =3D=3D ARM::VMOVRS || Opcode =3D=3D ARM::VMOVRRD)
@@ -222,14 +222,14 @@
   const MCInstrDesc &MCID2 =3D TII->get(AddSubOpc);
   unsigned TmpReg =3D MRI->createVirtualRegister(TII->getRegClass(MCID1, 0=
, TRI));
=20
-  MachineInstrBuilder MIB =3D BuildMI(MBB, *MI, MI->getDebugLoc(), MCID1, =
TmpReg)
+  MachineInstrBuilder MIB =3D BuildMI(MBB, MI, MI->getDebugLoc(), MCID1, T=
mpReg)
     .addReg(Src1Reg, getKillRegState(Src1Kill))
     .addReg(Src2Reg, getKillRegState(Src2Kill));
   if (HasLane)
     MIB.addImm(LaneImm);
   MIB.addImm(Pred).addReg(PredReg);
=20
-  MIB =3D BuildMI(MBB, *MI, MI->getDebugLoc(), MCID2)
+  MIB =3D BuildMI(MBB, MI, MI->getDebugLoc(), MCID2)
     .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstDead));
=20
   if (NegAcc) {
@@ -274,7 +274,7 @@
     }
=20
     const MCInstrDesc &MCID =3D MI->getDesc();
-    if (MCID.isBarrier()) {
+    if (MI->isBarrier()) {
       clearStack();
       Skip =3D 0;
       ++MII;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
1FrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Thumb1FrameLowering.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb1FrameLowering.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D=3D- Thumb1FrameLowering.cpp - Thumb1 Frame Information -=
--*- C++ -*-=3D=3D=3D=3D//
+//=3D=3D=3D-- Thumb1FrameLowering.cpp - Thumb1 Frame Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,7 +12,6 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "Thumb1FrameLowering.h"
-#include "ARMBaseInstrInfo.h"
 #include "ARMMachineFunctionInfo.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
@@ -101,7 +100,7 @@
     case ARM::R11:
       if (Reg =3D=3D FramePtr)
         FramePtrSpillFI =3D FI;
-      if (STI.isTargetDarwin()) {
+      if (STI.isTargetIOS()) {
         AFI->addGPRCalleeSavedArea2Frame(FI);
         GPRCS2Size +=3D 4;
       } else {
@@ -175,14 +174,14 @@
     AFI->setShouldRestoreSPFromFP(true);
 }
=20
-static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
+static bool isCalleeSavedRegister(unsigned Reg, const uint16_t *CSRegs) {
   for (unsigned i =3D 0; CSRegs[i]; ++i)
     if (Reg =3D=3D CSRegs[i])
       return true;
   return false;
 }
=20
-static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
+static bool isCSRestore(MachineInstr *MI, const uint16_t *CSRegs) {
   if (MI->getOpcode() =3D=3D ARM::tLDRspi &&
       MI->getOperand(1).isFI() &&
       isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs))
@@ -214,7 +213,7 @@
=20
   unsigned VARegSaveSize =3D AFI->getVarArgsRegSaveSize();
   int NumBytes =3D (int)MFI->getStackSize();
-  const unsigned *CSRegs =3D RegInfo->getCalleeSavedRegs();
+  const uint16_t *CSRegs =3D RegInfo->getCalleeSavedRegs();
   unsigned FramePtr =3D RegInfo->getFrameRegister(MF);
=20
   if (!AFI->hasStackFrame()) {
@@ -278,8 +277,11 @@
=20
     emitSPUpdate(MBB, MBBI, TII, dl, *RegInfo, VARegSaveSize);
=20
-    AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX_RET_vararg))
-      .addReg(ARM::R3, RegState::Kill));
+    MachineInstrBuilder MIB =3D
+      BuildMI(MBB, MBBI, dl, TII.get(ARM::tBX_RET_vararg))
+      .addReg(ARM::R3, RegState::Kill);
+    AddDefaultPred(MIB);
+    MIB->copyImplicitOps(&*MBBI);
     // erase the old tBX_RET instruction
     MBB.erase(MBBI);
   }
@@ -350,6 +352,7 @@
         continue;
       Reg =3D ARM::PC;
       (*MIB).setDesc(TII.get(ARM::tPOP_RET));
+      MIB->copyImplicitOps(&*MI);
       MI =3D MBB.erase(MI);
     }
     MIB.addReg(Reg, getDefRegState(true));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
1InstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Thumb1InstrInfo.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb1InstrInfo.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- Thumb1InstrInfo.cpp - Thumb-1 Instruction Information ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- Thumb1InstrInfo.cpp - Thumb-1 Instruction Information ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,14 +13,11 @@
=20
 #include "Thumb1InstrInfo.h"
 #include "ARM.h"
-#include "ARMMachineFunctionInfo.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
-#include "llvm/ADT/SmallVector.h"
-#include "Thumb1InstrInfo.h"
+#include "llvm/MC/MCInst.h"
=20
 using namespace llvm;
=20
@@ -28,6 +25,15 @@
   : ARMBaseInstrInfo(STI), RI(*this, STI) {
 }
=20
+/// getNoopForMachoTarget - Return the noop instruction to use for a noop.
+void Thumb1InstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
+  NopInst.setOpcode(ARM::tMOVr);
+  NopInst.addOperand(MCOperand::CreateReg(ARM::R8));
+  NopInst.addOperand(MCOperand::CreateReg(ARM::R8));
+  NopInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+  NopInst.addOperand(MCOperand::CreateReg(0));
+}
+
 unsigned Thumb1InstrInfo::getUnindexedOpcode(unsigned Opc) const {
   return 0;
 }
@@ -60,8 +66,7 @@
     MachineFunction &MF =3D *MBB.getParent();
     MachineFrameInfo &MFI =3D *MF.getFrameInfo();
     MachineMemOperand *MMO =3D
-      MF.getMachineMemOperand(
-                    MachinePointerInfo(PseudoSourceValue::getFixedStack(FI=
)),
+      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
                               MachineMemOperand::MOStore,
                               MFI.getObjectSize(FI),
                               MFI.getObjectAlignment(FI));
@@ -89,8 +94,7 @@
     MachineFunction &MF =3D *MBB.getParent();
     MachineFrameInfo &MFI =3D *MF.getFrameInfo();
     MachineMemOperand *MMO =3D
-      MF.getMachineMemOperand(
-                    MachinePointerInfo(PseudoSourceValue::getFixedStack(FI=
)),
+      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
                               MachineMemOperand::MOLoad,
                               MFI.getObjectSize(FI),
                               MFI.getObjectAlignment(FI));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
1InstrInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/Thumb1InstrInfo.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb1InstrInfo.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- Thumb1InstrInfo.h - Thumb-1 Instruction Information ------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- Thumb1InstrInfo.h - Thumb-1 Instruction Information -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,9 +14,8 @@
 #ifndef THUMB1INSTRUCTIONINFO_H
 #define THUMB1INSTRUCTIONINFO_H
=20
-#include "llvm/Target/TargetInstrInfo.h"
 #include "ARM.h"
-#include "ARMInstrInfo.h"
+#include "ARMBaseInstrInfo.h"
 #include "Thumb1RegisterInfo.h"
=20
 namespace llvm {
@@ -27,6 +26,9 @@
 public:
   explicit Thumb1InstrInfo(const ARMSubtarget &STI);
=20
+  /// getNoopForMachoTarget - Return the noop instruction to use for a noo=
p.
+  void getNoopForMachoTarget(MCInst &NopInst) const;
+
   // Return the non-pre/post incrementing version of 'Opc'. Return 0
   // if there is not such an opcode.
   unsigned getUnindexedOpcode(unsigned Opc) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
1RegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Thumb1RegisterInfo.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb1RegisterInfo.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- Thumb1RegisterInfo.cpp - Thumb-1 Register Information ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- Thumb1RegisterInfo.cpp - Thumb-1 Register Information ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,12 +12,11 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "Thumb1RegisterInfo.h"
 #include "ARM.h"
 #include "ARMBaseInstrInfo.h"
 #include "ARMMachineFunctionInfo.h"
 #include "ARMSubtarget.h"
-#include "Thumb1InstrInfo.h"
-#include "Thumb1RegisterInfo.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
@@ -28,6 +27,7 @@
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
+#include "llvm/CodeGen/RegisterScavenging.h"
 #include "llvm/Target/TargetFrameLowering.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Support/CommandLine.h"
@@ -570,6 +570,11 @@
     // If this instruction affects R12, adjust our restore point.
     for (unsigned i =3D 0, e =3D II->getNumOperands(); i !=3D e; ++i) {
       const MachineOperand &MO =3D II->getOperand(i);
+      if (MO.isRegMask() && MO.clobbersPhysReg(ARM::R12)) {
+        UseMI =3D II;
+        done =3D true;
+        break;
+      }
       if (!MO.isReg() || MO.isUndef() || !MO.getReg() ||
           TargetRegisterInfo::isVirtualRegister(MO.getReg()))
         continue;
@@ -624,6 +629,21 @@
       FrameReg =3D BasePtr;
   }
=20
+  // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because=
 the
+  // call frame setup/destroy instructions have already been eliminated.  =
That
+  // means the stack pointer cannot be used to access the emergency spill =
slot
+  // when !hasReservedCallFrame().
+#ifndef NDEBUG
+  if (RS && FrameReg =3D=3D ARM::SP && FrameIndex =3D=3D RS->getScavenging=
FrameIndex()){
+    assert(MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF) &&
+           "Cannot use SP to access the emergency spill slot in "
+           "functions without a reserved call frame");
+    assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
+           "Cannot use SP to access the emergency spill slot in "
+           "functions with variable sized frame objects");
+  }
+#endif // NDEBUG
+
   // Special handling of dbg_value instructions.
   if (MI.isDebugValue()) {
     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
@@ -643,14 +663,13 @@
   assert(Offset && "This code isn't needed if offset already handled!");
=20
   unsigned Opcode =3D MI.getOpcode();
-  const MCInstrDesc &Desc =3D MI.getDesc();
=20
   // Remove predicate first.
   int PIdx =3D MI.findFirstPredOperandIdx();
   if (PIdx !=3D -1)
     removeOperands(MI, PIdx);
=20
-  if (Desc.mayLoad()) {
+  if (MI.mayLoad()) {
     // Use the destination register to materialize sp + offset.
     unsigned TmpReg =3D MI.getOperand(0).getReg();
     bool UseRR =3D false;
@@ -673,7 +692,7 @@
       // Use [reg, reg] addrmode. Replace the immediate operand w/ the fra=
me
       // register. The offset is already handled in the vreg value.
       MI.getOperand(i+1).ChangeToRegister(FrameReg, false, false, false);
-  } else if (Desc.mayStore()) {
+  } else if (MI.mayStore()) {
       VReg =3D MF.getRegInfo().createVirtualRegister(ARM::tGPRRegisterClas=
s);
       bool UseRR =3D false;
=20
@@ -695,11 +714,11 @@
         // register. The offset is already handled in the vreg value.
         MI.getOperand(i+1).ChangeToRegister(FrameReg, false, false, false);
   } else {
-    assert(false && "Unexpected opcode!");
+    llvm_unreachable("Unexpected opcode!");
   }
=20
   // Add predicate back if it's needed.
-  if (MI.getDesc().isPredicable()) {
+  if (MI.isPredicable()) {
     MachineInstrBuilder MIB(&MI);
     AddDefaultPred(MIB);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
1RegisterInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/Thumb1RegisterInfo.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb1RegisterInfo.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -16,13 +16,12 @@
 #define THUMB1REGISTERINFO_H
=20
 #include "ARM.h"
-#include "ARMRegisterInfo.h"
+#include "ARMBaseRegisterInfo.h"
 #include "llvm/Target/TargetRegisterInfo.h"
=20
 namespace llvm {
   class ARMSubtarget;
   class ARMBaseInstrInfo;
-  class Type;
=20
 struct Thumb1RegisterInfo : public ARMBaseRegisterInfo {
 public:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
2ITBlockPass.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Thumb2ITBlockPass.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb2ITBlockPass.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- Thumb2ITBlockPass.cpp - Insert Thumb IT blocks ----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- Thumb2ITBlockPass.cpp - Insert Thumb-2 IT blocks -----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,6 +13,7 @@
 #include "Thumb2InstrInfo.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
+#include "llvm/CodeGen/MachineInstrBundle.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/Statistic.h"
@@ -75,7 +76,7 @@
   for (unsigned i =3D 0, e =3D LocalUses.size(); i !=3D e; ++i) {
     unsigned Reg =3D LocalUses[i];
     Uses.insert(Reg);
-    for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+    for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
          *Subreg; ++Subreg)
       Uses.insert(*Subreg);
   }
@@ -83,7 +84,7 @@
   for (unsigned i =3D 0, e =3D LocalDefs.size(); i !=3D e; ++i) {
     unsigned Reg =3D LocalDefs[i];
     Defs.insert(Reg);
-    for (const unsigned *Subreg =3D TRI->getSubRegisters(Reg);
+    for (const uint16_t *Subreg =3D TRI->getSubRegisters(Reg);
          *Subreg; ++Subreg)
       Defs.insert(*Subreg);
     if (Reg =3D=3D ARM::CPSR)
@@ -141,7 +142,7 @@
   //   rsb   r2, 0
   //
   const MCInstrDesc &MCID =3D MI->getDesc();
-  if (MCID.hasOptionalDef() &&
+  if (MI->hasOptionalDef() &&
       MI->getOperand(MCID.getNumOperands() - 1).getReg() =3D=3D ARM::CPSR)
     return false;
=20
@@ -153,7 +154,7 @@
     ++I;
   if (I !=3D E) {
     unsigned NPredReg =3D 0;
-    ARMCC::CondCodes NCC =3D llvm::getITInstrPredicate(I, NPredReg);
+    ARMCC::CondCodes NCC =3D getITInstrPredicate(I, NPredReg);
     if (NCC =3D=3D CC || NCC =3D=3D OCC)
       return true;
   }
@@ -170,7 +171,7 @@
     MachineInstr *MI =3D &*MBBI;
     DebugLoc dl =3D MI->getDebugLoc();
     unsigned PredReg =3D 0;
-    ARMCC::CondCodes CC =3D llvm::getITInstrPredicate(MI, PredReg);
+    ARMCC::CondCodes CC =3D getITInstrPredicate(MI, PredReg);
     if (CC =3D=3D ARMCC::AL) {
       ++MBBI;
       continue;
@@ -198,7 +199,7 @@
     // Branches, including tricky ones like LDM_RET, need to end an IT
     // block so check the instruction we just put in the block.
     for (; MBBI !=3D E && Pos &&
-           (!MI->getDesc().isBranch() && !MI->getDesc().isReturn()) ; ++MB=
BI) {
+           (!MI->isBranch() && !MI->isReturn()) ; ++MBBI) {
       if (MBBI->isDebugValue())
         continue;
=20
@@ -206,7 +207,7 @@
       MI =3D NMI;
=20
       unsigned NPredReg =3D 0;
-      ARMCC::CondCodes NCC =3D llvm::getITInstrPredicate(NMI, NPredReg);
+      ARMCC::CondCodes NCC =3D getITInstrPredicate(NMI, NPredReg);
       if (NCC =3D=3D CC || NCC =3D=3D OCC) {
         Mask |=3D (NCC & 1) << Pos;
         // Add implicit use of ITSTATE.
@@ -237,6 +238,10 @@
     // Last instruction in IT block kills ITSTATE.
     LastITMI->findRegisterUseOperand(ARM::ITSTATE)->setIsKill();
=20
+    // Finalize the bundle.
+    MachineBasicBlock::instr_iterator LI =3D LastITMI;
+    finalizeBundle(MBB, InsertPos.getInstrIterator(), llvm::next(LI));
+
     Modified =3D true;
     ++NumITs;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
2InstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Thumb2InstrInfo.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb2InstrInfo.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- Thumb2InstrInfo.cpp - Thumb-2 Instruction Information ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- Thumb2InstrInfo.cpp - Thumb-2 Instruction Information ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,13 +15,11 @@
 #include "ARM.h"
 #include "ARMConstantPoolValue.h"
 #include "ARMMachineFunctionInfo.h"
-#include "Thumb2InstrInfo.h"
 #include "MCTargetDesc/ARMAddressingModes.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
-#include "llvm/ADT/SmallVector.h"
+#include "llvm/MC/MCInst.h"
 #include "llvm/Support/CommandLine.h"
=20
 using namespace llvm;
@@ -35,6 +33,13 @@
   : ARMBaseInstrInfo(STI), RI(*this, STI) {
 }
=20
+/// getNoopForMachoTarget - Return the noop instruction to use for a noop.
+void Thumb2InstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
+  NopInst.setOpcode(ARM::tNOP);
+  NopInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
+  NopInst.addOperand(MCOperand::CreateReg(0));
+}
+
 unsigned Thumb2InstrInfo::getUnindexedOpcode(unsigned Opc) const {
   // FIXME
   return 0;
@@ -53,7 +58,7 @@
   // If the first instruction of Tail is predicated, we may have to update
   // the IT instruction.
   unsigned PredReg =3D 0;
-  ARMCC::CondCodes CC =3D llvm::getInstrPredicate(Tail, PredReg);
+  ARMCC::CondCodes CC =3D getInstrPredicate(Tail, PredReg);
   MachineBasicBlock::iterator MBBI =3D Tail;
   if (CC !=3D ARMCC::AL)
     // Expecting at least the t2IT instruction before it.
@@ -101,7 +106,7 @@
   }
=20
   unsigned PredReg =3D 0;
-  return llvm::getITInstrPredicate(MBBI, PredReg) =3D=3D ARMCC::AL;
+  return getITInstrPredicate(MBBI, PredReg) =3D=3D ARMCC::AL;
 }
=20
 void Thumb2InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
@@ -130,8 +135,7 @@
     MachineFunction &MF =3D *MBB.getParent();
     MachineFrameInfo &MFI =3D *MF.getFrameInfo();
     MachineMemOperand *MMO =3D
-      MF.getMachineMemOperand(
-                      MachinePointerInfo(PseudoSourceValue::getFixedStack(=
FI)),
+      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
                               MachineMemOperand::MOStore,
                               MFI.getObjectSize(FI),
                               MFI.getObjectAlignment(FI));
@@ -158,8 +162,7 @@
     MachineFunction &MF =3D *MBB.getParent();
     MachineFrameInfo &MFI =3D *MF.getFrameInfo();
     MachineMemOperand *MMO =3D
-      MF.getMachineMemOperand(
-                      MachinePointerInfo(PseudoSourceValue::getFixedStack(=
FI)),
+      MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
                               MachineMemOperand::MOLoad,
                               MFI.getObjectSize(FI),
                               MFI.getObjectAlignment(FI));
@@ -570,7 +573,7 @@
     return;
=20
   unsigned PredReg =3D 0;
-  ARMCC::CondCodes CC =3D llvm::getInstrPredicate(UseMI, PredReg);
+  ARMCC::CondCodes CC =3D getInstrPredicate(UseMI, PredReg);
   if (CC =3D=3D ARMCC::AL || PredReg !=3D ARM::CPSR)
     return;
=20
@@ -586,10 +589,10 @@
       continue;
=20
     MachineInstr *NMI =3D &*MBBI;
-    ARMCC::CondCodes NCC =3D llvm::getInstrPredicate(NMI, PredReg);
+    ARMCC::CondCodes NCC =3D getInstrPredicate(NMI, PredReg);
     if (!(NCC =3D=3D CC || NCC =3D=3D OCC) ||
         NMI->modifiesRegister(SrcReg, &TRI) ||
-        NMI->definesRegister(ARM::CPSR))
+        NMI->modifiesRegister(ARM::CPSR, &TRI))
       break;
     if (++NumInsts =3D=3D 4)
       // Too many in a row!
@@ -607,5 +610,5 @@
   unsigned Opc =3D MI->getOpcode();
   if (Opc =3D=3D ARM::tBcc || Opc =3D=3D ARM::t2Bcc)
     return ARMCC::AL;
-  return llvm::getInstrPredicate(MI, PredReg);
+  return getInstrPredicate(MI, PredReg);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
2InstrInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/Thumb2InstrInfo.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb2InstrInfo.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- Thumb2InstrInfo.h - Thumb-2 Instruction Information ------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- Thumb2InstrInfo.h - Thumb-2 Instruction Information -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,9 +14,8 @@
 #ifndef THUMB2INSTRUCTIONINFO_H
 #define THUMB2INSTRUCTIONINFO_H
=20
-#include "llvm/Target/TargetInstrInfo.h"
 #include "ARM.h"
-#include "ARMInstrInfo.h"
+#include "ARMBaseInstrInfo.h"
 #include "Thumb2RegisterInfo.h"
=20
 namespace llvm {
@@ -28,6 +27,9 @@
 public:
   explicit Thumb2InstrInfo(const ARMSubtarget &STI);
=20
+  /// getNoopForMachoTarget - Return the noop instruction to use for a noo=
p.
+  void getNoopForMachoTarget(MCInst &NopInst) const;
+
   // Return the non-pre/post incrementing version of 'Opc'. Return 0
   // if there is not such an opcode.
   unsigned getUnindexedOpcode(unsigned Opc) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
2RegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Thumb2RegisterInfo.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb2RegisterInfo.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- Thumb2RegisterInfo.cpp - Thumb-2 Register Information ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- Thumb2RegisterInfo.cpp - Thumb-2 Register Information ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,10 +12,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "Thumb2RegisterInfo.h"
 #include "ARM.h"
+#include "ARMBaseInstrInfo.h"
 #include "ARMSubtarget.h"
-#include "Thumb2InstrInfo.h"
-#include "Thumb2RegisterInfo.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
2RegisterInfo.h
--- a/head/contrib/llvm/lib/Target/ARM/Thumb2RegisterInfo.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb2RegisterInfo.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -16,13 +16,12 @@
 #define THUMB2REGISTERINFO_H
=20
 #include "ARM.h"
-#include "ARMRegisterInfo.h"
+#include "ARMBaseRegisterInfo.h"
 #include "llvm/Target/TargetRegisterInfo.h"
=20
 namespace llvm {
   class ARMSubtarget;
   class ARMBaseInstrInfo;
-  class Type;
=20
 struct Thumb2RegisterInfo : public ARMBaseRegisterInfo {
 public:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/ARM/Thumb=
2SizeReduction.cpp
--- a/head/contrib/llvm/lib/Target/ARM/Thumb2SizeReduction.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/ARM/Thumb2SizeReduction.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -39,9 +39,9 @@
   /// ReduceTable - A static table with information on mapping from wide
   /// opcodes to narrow
   struct ReduceEntry {
-    unsigned WideOpc;      // Wide opcode
-    unsigned NarrowOpc1;   // Narrow opcode to transform to
-    unsigned NarrowOpc2;   // Narrow opcode when it's two-address
+    uint16_t WideOpc;      // Wide opcode
+    uint16_t NarrowOpc1;   // Narrow opcode to transform to
+    uint16_t NarrowOpc2;   // Narrow opcode when it's two-address
     uint8_t  Imm1Limit;    // Limit of immediate field (bits)
     uint8_t  Imm2Limit;    // Limit of immediate field when it's two-addre=
ss
     unsigned LowRegs1 : 1; // Only possible if low-registers are used
@@ -146,7 +146,8 @@
     /// ReduceOpcodeMap - Maps wide opcode to index of entry in ReduceTabl=
e.
     DenseMap<unsigned, unsigned> ReduceOpcodeMap;
=20
-    bool canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use);
+    bool canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use,
+                             bool IsSelfLoop);
=20
     bool VerifyPredAndCC(MachineInstr *MI, const ReduceEntry &Entry,
                          bool is2Addr, ARMCC::CondCodes Pred,
@@ -157,19 +158,21 @@
=20
     bool ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
                        const ReduceEntry &Entry, bool LiveCPSR,
-                       MachineInstr *CPSRDef);
+                       MachineInstr *CPSRDef, bool IsSelfLoop);
=20
     /// ReduceTo2Addr - Reduce a 32-bit instruction to a 16-bit two-address
     /// instruction.
     bool ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
                        const ReduceEntry &Entry,
-                       bool LiveCPSR, MachineInstr *CPSRDef);
+                       bool LiveCPSR, MachineInstr *CPSRDef,
+                       bool IsSelfLoop);
=20
     /// ReduceToNarrow - Reduce a 32-bit instruction to a 16-bit
     /// non-two-address instruction.
     bool ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
                         const ReduceEntry &Entry,
-                        bool LiveCPSR, MachineInstr *CPSRDef);
+                        bool LiveCPSR, MachineInstr *CPSRDef,
+                        bool IsSelfLoop);
=20
     /// ReduceMBB - Reduce width of instructions in the specified basic bl=
ock.
     bool ReduceMBB(MachineBasicBlock &MBB);
@@ -186,7 +189,7 @@
 }
=20
 static bool HasImplicitCPSRDef(const MCInstrDesc &MCID) {
-  for (const unsigned *Regs =3D MCID.ImplicitDefs; *Regs; ++Regs)
+  for (const uint16_t *Regs =3D MCID.getImplicitDefs(); *Regs; ++Regs)
     if (*Regs =3D=3D ARM::CPSR)
       return true;
   return false;
@@ -210,10 +213,17 @@
 /// In this case it would have been ok to narrow the mul.w to muls since t=
here
 /// are indirect RAW dependency between the muls and the mul.w
 bool
-Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use=
) {
-  if (!Def || !STI->avoidCPSRPartialUpdate())
+Thumb2SizeReduce::canAddPseudoFlagDep(MachineInstr *Def, MachineInstr *Use,
+                                      bool FirstInSelfLoop) {
+  // FIXME: Disable check for -Oz (aka OptimizeForSizeHarder).
+  if (!STI->avoidCPSRPartialUpdate())
     return false;
=20
+  if (!Def)
+    // If this BB loops back to itself, conservatively avoid narrowing the
+    // first instruction that does partial flag update.
+    return FirstInSelfLoop;
+
   SmallSet<unsigned, 2> Defs;
   for (unsigned i =3D 0, e =3D Def->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D Def->getOperand(i);
@@ -442,7 +452,7 @@
=20
   // Add the 16-bit load / store instruction.
   DebugLoc dl =3D MI->getDebugLoc();
-  MachineInstrBuilder MIB =3D BuildMI(MBB, *MI, dl, TII->get(Opc));
+  MachineInstrBuilder MIB =3D BuildMI(MBB, MI, dl, TII->get(Opc));
   if (!isLdStMul) {
     MIB.addOperand(MI->getOperand(0));
     MIB.addOperand(MI->getOperand(1));
@@ -468,7 +478,7 @@
=20
   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *=
MIB);
=20
-  MBB.erase(MI);
+  MBB.erase_instr(MI);
   ++NumLdSts;
   return true;
 }
@@ -476,15 +486,16 @@
 bool
 Thumb2SizeReduce::ReduceSpecial(MachineBasicBlock &MBB, MachineInstr *MI,
                                 const ReduceEntry &Entry,
-                                bool LiveCPSR, MachineInstr *CPSRDef) {
+                                bool LiveCPSR, MachineInstr *CPSRDef,
+                                bool IsSelfLoop) {
   unsigned Opc =3D MI->getOpcode();
   if (Opc =3D=3D ARM::t2ADDri) {
     // If the source register is SP, try to reduce to tADDrSPi, otherwise
     // it's a normal reduce.
     if (MI->getOperand(1).getReg() !=3D ARM::SP) {
-      if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef))
+      if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop))
         return true;
-      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
+      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
     }
     // Try to reduce to tADDrSPi.
     unsigned Imm =3D MI->getOperand(2).getImm();
@@ -502,7 +513,7 @@
         MI->getOperand(MCID.getNumOperands()-1).getReg() =3D=3D ARM::CPSR)
       return false;
=20
-    MachineInstrBuilder MIB =3D BuildMI(MBB, *MI, MI->getDebugLoc(),
+    MachineInstrBuilder MIB =3D BuildMI(MBB, MI, MI->getDebugLoc(),
                                       TII->get(ARM::tADDrSPi))
       .addOperand(MI->getOperand(0))
       .addOperand(MI->getOperand(1))
@@ -514,7 +525,7 @@
=20
     DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " <<=
*MIB);
=20
-    MBB.erase(MI);
+    MBB.erase_instr(MI);
     ++NumNarrows;
     return true;
   }
@@ -522,8 +533,7 @@
   if (Entry.LowRegs1 && !VerifyLowRegs(MI))
     return false;
=20
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (MCID.mayLoad() || MCID.mayStore())
+  if (MI->mayLoad() || MI->mayStore())
     return ReduceLoadStore(MBB, MI, Entry);
=20
   switch (Opc) {
@@ -535,12 +545,12 @@
       switch (Opc) {
       default: break;
       case ARM::t2ADDSri: {
-        if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef))
+        if (ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop))
           return true;
         // fallthrough
       }
       case ARM::t2ADDSrr:
-        return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
+        return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoo=
p);
       }
     }
     break;
@@ -552,13 +562,13 @@
   case ARM::t2UXTB:
   case ARM::t2UXTH:
     if (MI->getOperand(2).getImm() =3D=3D 0)
-      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
+      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
     break;
   case ARM::t2MOVi16:
     // Can convert only 'pure' immediate operands, not immediates obtained=
 as
     // globals' addresses.
     if (MI->getOperand(1).isImm())
-      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
+      return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
     break;
   case ARM::t2CMPrr: {
     // Try to reduce to the lo-reg only version first. Why there are two
@@ -568,9 +578,9 @@
     // source insn opcode. So for now, we hack a local entry record to use.
     static const ReduceEntry NarrowEntry =3D
       { ARM::t2CMPrr,ARM::tCMPr, 0, 0, 0, 1, 1,2, 0, 0,1 };
-    if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, CPSRDef))
+    if (ReduceToNarrow(MBB, MI, NarrowEntry, LiveCPSR, CPSRDef, IsSelfLoop=
))
       return true;
-    return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef);
+    return ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop);
   }
   }
   return false;
@@ -579,14 +589,32 @@
 bool
 Thumb2SizeReduce::ReduceTo2Addr(MachineBasicBlock &MBB, MachineInstr *MI,
                                 const ReduceEntry &Entry,
-                                bool LiveCPSR, MachineInstr *CPSRDef) {
+                                bool LiveCPSR, MachineInstr *CPSRDef,
+                                bool IsSelfLoop) {
=20
   if (ReduceLimit2Addr !=3D -1 && ((int)Num2Addrs >=3D ReduceLimit2Addr))
     return false;
=20
   unsigned Reg0 =3D MI->getOperand(0).getReg();
   unsigned Reg1 =3D MI->getOperand(1).getReg();
-  if (Reg0 !=3D Reg1) {
+  // t2MUL is "special". The tied source operand is second, not first.
+  if (MI->getOpcode() =3D=3D ARM::t2MUL) {
+    unsigned Reg2 =3D MI->getOperand(2).getReg();
+    // Early exit if the regs aren't all low regs.
+    if (!isARMLowRegister(Reg0) || !isARMLowRegister(Reg1)
+        || !isARMLowRegister(Reg2))
+      return false;
+    if (Reg0 !=3D Reg2) {
+      // If the other operand also isn't the same as the destination, we
+      // can't reduce.
+      if (Reg1 !=3D Reg0)
+        return false;
+      // Try to commute the operands to make it a 2-address instruction.
+      MachineInstr *CommutedMI =3D TII->commuteInstruction(MI);
+      if (!CommutedMI)
+        return false;
+    }
+  } else if (Reg0 !=3D Reg1) {
     // Try to commute the operands to make it a 2-address instruction.
     unsigned CommOpIdx1, CommOpIdx2;
     if (!TII->findCommutedOpIndices(MI, CommOpIdx1, CommOpIdx2) ||
@@ -637,12 +665,12 @@
   // Avoid adding a false dependency on partial flag update by some 16-bit
   // instructions which has the 's' bit set.
   if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
-      canAddPseudoFlagDep(CPSRDef, MI))
+      canAddPseudoFlagDep(CPSRDef, MI, IsSelfLoop))
     return false;
=20
   // Add the 16-bit instruction.
   DebugLoc dl =3D MI->getDebugLoc();
-  MachineInstrBuilder MIB =3D BuildMI(MBB, *MI, dl, NewMCID);
+  MachineInstrBuilder MIB =3D BuildMI(MBB, MI, dl, NewMCID);
   MIB.addOperand(MI->getOperand(0));
   if (NewMCID.hasOptionalDef()) {
     if (HasCC)
@@ -666,7 +694,7 @@
=20
   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *=
MIB);
=20
-  MBB.erase(MI);
+  MBB.erase_instr(MI);
   ++Num2Addrs;
   return true;
 }
@@ -674,7 +702,8 @@
 bool
 Thumb2SizeReduce::ReduceToNarrow(MachineBasicBlock &MBB, MachineInstr *MI,
                                  const ReduceEntry &Entry,
-                                 bool LiveCPSR, MachineInstr *CPSRDef) {
+                                 bool LiveCPSR, MachineInstr *CPSRDef,
+                                 bool IsSelfLoop) {
   if (ReduceLimit !=3D -1 && ((int)NumNarrows >=3D ReduceLimit))
     return false;
=20
@@ -727,12 +756,12 @@
   // Avoid adding a false dependency on partial flag update by some 16-bit
   // instructions which has the 's' bit set.
   if (Entry.PartFlag && NewMCID.hasOptionalDef() && HasCC &&
-      canAddPseudoFlagDep(CPSRDef, MI))
+      canAddPseudoFlagDep(CPSRDef, MI, IsSelfLoop))
     return false;
=20
   // Add the 16-bit instruction.
   DebugLoc dl =3D MI->getDebugLoc();
-  MachineInstrBuilder MIB =3D BuildMI(MBB, *MI, dl, NewMCID);
+  MachineInstrBuilder MIB =3D BuildMI(MBB, MI, dl, NewMCID);
   MIB.addOperand(MI->getOperand(0));
   if (NewMCID.hasOptionalDef()) {
     if (HasCC)
@@ -772,7 +801,7 @@
=20
   DEBUG(errs() << "Converted 32-bit: " << *MI << "       to 16-bit: " << *=
MIB);
=20
-  MBB.erase(MI);
+  MBB.erase_instr(MI);
   ++NumNarrows;
   return true;
 }
@@ -817,13 +846,22 @@
   // Yes, CPSR could be livein.
   bool LiveCPSR =3D MBB.isLiveIn(ARM::CPSR);
   MachineInstr *CPSRDef =3D 0;
+  MachineInstr *BundleMI =3D 0;
=20
-  MachineBasicBlock::iterator MII =3D MBB.begin(), E =3D MBB.end();
-  MachineBasicBlock::iterator NextMII;
+  // If this BB loops back to itself, conservatively avoid narrowing the
+  // first instruction that does partial flag update.
+  bool IsSelfLoop =3D MBB.isSuccessor(&MBB);
+  MachineBasicBlock::instr_iterator MII =3D MBB.instr_begin(),E =3D MBB.in=
str_end();
+  MachineBasicBlock::instr_iterator NextMII;
   for (; MII !=3D E; MII =3D NextMII) {
     NextMII =3D llvm::next(MII);
=20
     MachineInstr *MI =3D &*MII;
+    if (MI->isBundle()) {
+      BundleMI =3D MI;
+      continue;
+    }
+
     LiveCPSR =3D UpdateCPSRUse(*MI, LiveCPSR);
=20
     unsigned Opcode =3D MI->getOpcode();
@@ -832,9 +870,9 @@
       const ReduceEntry &Entry =3D ReduceTable[OPI->second];
       // Ignore "special" cases for now.
       if (Entry.Special) {
-        if (ReduceSpecial(MBB, MI, Entry, LiveCPSR, CPSRDef)) {
+        if (ReduceSpecial(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop)) {
           Modified =3D true;
-          MachineBasicBlock::iterator I =3D prior(NextMII);
+          MachineBasicBlock::instr_iterator I =3D prior(NextMII);
           MI =3D &*I;
         }
         goto ProcessNext;
@@ -842,31 +880,46 @@
=20
       // Try to transform to a 16-bit two-address instruction.
       if (Entry.NarrowOpc2 &&
-          ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef)) {
+          ReduceTo2Addr(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop)) {
         Modified =3D true;
-        MachineBasicBlock::iterator I =3D prior(NextMII);
+        MachineBasicBlock::instr_iterator I =3D prior(NextMII);
         MI =3D &*I;
         goto ProcessNext;
       }
=20
       // Try to transform to a 16-bit non-two-address instruction.
       if (Entry.NarrowOpc1 &&
-          ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef)) {
+          ReduceToNarrow(MBB, MI, Entry, LiveCPSR, CPSRDef, IsSelfLoop)) {
         Modified =3D true;
-        MachineBasicBlock::iterator I =3D prior(NextMII);
+        MachineBasicBlock::instr_iterator I =3D prior(NextMII);
         MI =3D &*I;
       }
     }
=20
   ProcessNext:
+    if (NextMII !=3D E && MI->isInsideBundle() && !NextMII->isInsideBundle=
()) {
+      // FIXME: Since post-ra scheduler operates on bundles, the CPSR kill
+      // marker is only on the BUNDLE instruction. Process the BUNDLE
+      // instruction as we finish with the bundled instruction to work aro=
und
+      // the inconsistency.
+      if (BundleMI->killsRegister(ARM::CPSR))
+        LiveCPSR =3D false;
+      MachineOperand *MO =3D BundleMI->findRegisterDefOperand(ARM::CPSR);
+      if (MO && !MO->isDead())
+        LiveCPSR =3D true;
+    }
+
     bool DefCPSR =3D false;
     LiveCPSR =3D UpdateCPSRDef(*MI, LiveCPSR, DefCPSR);
-    if (MI->getDesc().isCall())
+    if (MI->isCall()) {
       // Calls don't really set CPSR.
       CPSRDef =3D 0;
-    else if (DefCPSR)
+      IsSelfLoop =3D false;
+    } else if (DefCPSR) {
       // This is the last CPSR defining instruction.
       CPSRDef =3D MI;
+      IsSelfLoop =3D false;
+    }
   }
=20
   return Modified;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/C=
ellSDKIntrinsics.td
--- a/head/contrib/llvm/lib/Target/CellSPU/CellSDKIntrinsics.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/CellSDKIntrinsics.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 //=3D=3D=3D-- CellSDKIntrinsics.td - Cell SDK Intrinsics ---------*- table=
gen -*-=3D=3D=3D//
-//=20
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/M=
CTargetDesc/SPUMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,8 @@
 #include "SPUMCAsmInfo.h"
 using namespace llvm;
=20
+void SPULinuxMCAsmInfo::anchor() { }
+
 SPULinuxMCAsmInfo::SPULinuxMCAsmInfo(const Target &T, StringRef TT) {
   IsLittleEndian =3D false;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/M=
CTargetDesc/SPUMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCAsmInfo.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -20,7 +20,9 @@
 namespace llvm {
   class Target;
  =20
-  struct SPULinuxMCAsmInfo : public MCAsmInfo {
+  class SPULinuxMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit SPULinuxMCAsmInfo(const Target &T, StringRef TT);
   };
 } // namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/M=
CTargetDesc/SPUMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- SPUMCTargetDesc.cpp - Cell SPU Target Descriptions -----*- C=
++ -*-=3D=3D=3D//
+//=3D=3D=3D-- SPUMCTargetDesc.cpp - Cell SPU Target Descriptions ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,6 +18,7 @@
 #include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 #define GET_INSTRINFO_MC_DESC
@@ -62,11 +63,12 @@
 }
=20
 static MCCodeGenInfo *createSPUMCCodeGenInfo(StringRef TT, Reloc::Model RM,
-                                      CodeModel::Model CM) {
+                                             CodeModel::Model CM,
+                                             CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
   // For the time being, use static relocations, since there's really no
   // support for PIC yet.
-  X->InitMCCodeGenInfo(Reloc::Static, CM);
+  X->InitMCCodeGenInfo(Reloc::Static, CM, OL);
   return X;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/M=
CTargetDesc/SPUMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/MCTargetDesc/SPUMCTargetDesc.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,7 @@
 #define SPUMCTARGETDESC_H
=20
 namespace llvm {
-class MCSubtargetInfo;
 class Target;
-class StringRef;
=20
 extern Target TheCellSPUTarget;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PU.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPU.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPU.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- SPU.h - Top-level interface for Cell SPU Target ----------*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- SPU.h - Top-level interface for Cell SPU Target ---------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PU.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPU.td	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPU.td	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
-//=3D=3D=3D- SPU.td - Describe the STI Cell SPU Target Machine ----*- tabl=
egen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SPU.td - Describe the STI Cell SPU Target Machine --*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PU128InstrInfo.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPU128InstrInfo.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPU128InstrInfo.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,9 +1,9 @@
-//=3D=3D=3D--- SPU128InstrInfo.td - Cell SPU 128-bit operations -*- tableg=
en -*--=3D=3D=3D//
+//=3D=3D=3D-- SPU128InstrInfo.td - Cell SPU 128-bit operations --*- tableg=
en -*--=3D=3D=3D//
 //
 //                     Cell SPU 128-bit operations
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-                                 =20
+
 // zext 32->128: Zero extend 32-bit to 128-bit
 def : Pat<(i128 (zext R32C:$rSrc)),
           (ROTQMBYIr128_zext_r32 R32C:$rSrc, 12)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PU64InstrInfo.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPU64InstrInfo.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPU64InstrInfo.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D--- SPU64InstrInfo.td - Cell SPU 64-bit operations -*- table=
gen -*--=3D=3D=3D=3D//
+//=3D=3D=3D=3D-- SPU64InstrInfo.td - Cell SPU 64-bit operations ---*- tabl=
egen -*--=3D=3D=3D//
 //
 //                     Cell SPU 64-bit operations
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUAsmPrinter.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUAsmPrinter.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUAsmPrinter.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- SPUAsmPrinter.cpp - Print machine instrs to Cell SPU assembl=
y -------=3D//
+//=3D=3D=3D-- SPUAsmPrinter.cpp - Print machine instrs to Cell SPU assembl=
y -----=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -248,7 +248,6 @@
   switch (MO.getType()) {
   case MachineOperand::MO_Immediate:
     report_fatal_error("printOp() does not handle immediate values");
-    return;
=20
   case MachineOperand::MO_MachineBasicBlock:
     O << *MO.getMBB()->getSymbol();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUCallingConv.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUCallingConv.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUCallingConv.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,10 +1,10 @@
 //=3D=3D=3D- SPUCallingConv.td - Calling Conventions for CellSPU -*- table=
gen -*-=3D=3D=3D//
-//=20
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This describes the calling conventions for the STI Cell SPU architectur=
e.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUFrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUFrameLowering.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUFrameLowering.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "SPUFrameLowering.h"
 #include "SPU.h"
-#include "SPUFrameLowering.h"
 #include "SPUInstrBuilder.h"
 #include "SPUInstrInfo.h"
 #include "llvm/Function.h"
@@ -47,7 +47,8 @@
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
=20
   return MFI->getStackSize() &&
-    (DisableFramePointerElim(MF) || MFI->hasVarSizedObjects());
+    (MF.getTarget().Options.DisableFramePointerElim(MF) ||
+     MFI->hasVarSizedObjects());
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUFrameLowering.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUFrameLowering.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUFrameLowering.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- SPUFrameLowering.h - SPU Frame Lowering stuff -*- C++ =
-*----=3D=3D=3D=3D=3D=3D=3D=3D//
+//=3D=3D=3D-- SPUFrameLowering.h - SPU Frame Lowering stuff ----------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUISelDAGToDAG.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUISelDAGToDAG.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUISelDAGToDAG.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -22,7 +22,6 @@
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/SelectionDAGISel.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Constants.h"
@@ -91,8 +90,6 @@
       short s_val =3D (short) i_val;
       return i_val =3D=3D s_val;
     }
-
-    return false;
   }
=20
   //! ConstantFPSDNode predicate for representing floats as 16-bit sign ex=
t.
@@ -216,7 +213,7 @@
       HandleSDNode Dummy(CurDAG->getLoad(vecVT, dl,
                                          CurDAG->getEntryNode(), CGPoolOff=
set,
                                          MachinePointerInfo::getConstantPo=
ol(),
-                                         false, false, Alignment));
+                                         false, false, false, Alignment));
       CurDAG->ReplaceAllUsesWith(SDValue(bvNode, 0), Dummy.getValue());
       if (SDNode *N =3D SelectCode(Dummy.getValue().getNode()))
         return N;
@@ -287,8 +284,8 @@
         llvm_unreachable("InlineAsmMemoryOperand 'v' constraint not handle=
d.");
 #else
         SelectAddrIdxOnly(Op, Op, Op0, Op1);
+        break;
 #endif
-        break;
       }
=20
       OutOps.push_back(Op0);
@@ -327,7 +324,7 @@
     val =3D dyn_cast<ConstantSDNode>(N.getNode())->getSExtValue();
     Base =3D CurDAG->getTargetConstant( val , MVT::i32);
     Index =3D Zero;
-    return true; break;
+    return true;
   case ISD::ConstantPool:
   case ISD::GlobalAddress:
     report_fatal_error("SPU SelectAFormAddr: Pool/Global not lowered.");
@@ -579,22 +576,16 @@
   switch( VT.SimpleTy ) {
   case MVT::i8:
     return CurDAG->getTargetConstant(SPU::R8CRegClass.getID(), MVT::i32);
-    break;
   case MVT::i16:
     return CurDAG->getTargetConstant(SPU::R16CRegClass.getID(), MVT::i32);
-    break;
   case MVT::i32:
     return CurDAG->getTargetConstant(SPU::R32CRegClass.getID(), MVT::i32);
-    break;
   case MVT::f32:
     return CurDAG->getTargetConstant(SPU::R32FPRegClass.getID(), MVT::i32);
-    break;
   case MVT::i64:
     return CurDAG->getTargetConstant(SPU::R64CRegClass.getID(), MVT::i32);
-    break;
   case MVT::i128:
     return CurDAG->getTargetConstant(SPU::GPRCRegClass.getID(), MVT::i32);
-    break;
   case MVT::v16i8:
   case MVT::v8i16:
   case MVT::v4i32:
@@ -602,11 +593,10 @@
   case MVT::v2i64:
   case MVT::v2f64:
     return CurDAG->getTargetConstant(SPU::VECREGRegClass.getID(), MVT::i32=
);
-    break;
   default:
     assert( false && "add a new case here" );
+    return SDValue();
   }
-  return SDValue();
 }
=20
 //! Convert the operand from a target-independent to a target-specific node
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUISelLowering.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUISelLowering.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUISelLowering.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -27,19 +27,14 @@
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
 #include "llvm/Target/TargetOptions.h"
-#include "llvm/ADT/VectorExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
-#include <map>
=20
 using namespace llvm;
=20
-// Used in getTargetNodeName() below
 namespace {
-  std::map<unsigned, const char *> node_names;
-
   // Byte offset of the preferred slot (counted from the MSB)
   int prefslotOffset(EVT VT) {
     int retval=3D0;
@@ -84,8 +79,9 @@
                 Op.getNode()->getValueType(0).getTypeForEVT(*DAG.getContex=
t());
     std::pair<SDValue, SDValue> CallInfo =3D
             TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, fa=
lse,
-                            0, TLI.getLibcallCallingConv(LC), false,
-                            /*isReturnValueUsed=3D*/true,
+                            0, TLI.getLibcallCallingConv(LC),
+                            /*isTailCall=3D*/false,
+                            /*doesNotRet=3D*/false, /*isReturnValueUsed=3D=
*/true,
                             Callee, Args, DAG, Op.getDebugLoc());
=20
     return CallInfo.first;
@@ -296,12 +292,22 @@
   setOperationAction(ISD::CTTZ , MVT::i32,   Expand);
   setOperationAction(ISD::CTTZ , MVT::i64,   Expand);
   setOperationAction(ISD::CTTZ , MVT::i128,  Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i8,    Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16,   Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32,   Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64,   Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i128,  Expand);
=20
   setOperationAction(ISD::CTLZ , MVT::i8,    Promote);
   setOperationAction(ISD::CTLZ , MVT::i16,   Promote);
   setOperationAction(ISD::CTLZ , MVT::i32,   Legal);
   setOperationAction(ISD::CTLZ , MVT::i64,   Expand);
   setOperationAction(ISD::CTLZ , MVT::i128,  Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8,    Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16,   Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32,   Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64,   Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i128,  Expand);
=20
   // SPU has a version of select that implements (a&~c)|(b&c), just like
   // select ought to work:
@@ -424,6 +430,13 @@
     setOperationAction(ISD::UDIV,    VT, Expand);
     setOperationAction(ISD::UREM,    VT, Expand);
=20
+    // Expand all trunc stores
+    for (unsigned j =3D (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
+         j <=3D (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
+      MVT::SimpleValueType TargetVT =3D (MVT::SimpleValueType)j;
+    setTruncStoreAction(VT, TargetVT, Expand);
+    }
+
     // Custom lower build_vector, constant pool spills, insert and
     // extract vector elements:
     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
@@ -434,6 +447,8 @@
     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
   }
=20
+  setOperationAction(ISD::SHL, MVT::v2i64, Expand);
+
   setOperationAction(ISD::AND, MVT::v16i8, Custom);
   setOperationAction(ISD::OR,  MVT::v16i8, Custom);
   setOperationAction(ISD::XOR, MVT::v16i8, Custom);
@@ -462,40 +477,34 @@
   setSchedulingPreference(Sched::RegPressure);
 }
=20
-const char *
-SPUTargetLowering::getTargetNodeName(unsigned Opcode) const
-{
-  if (node_names.empty()) {
-    node_names[(unsigned) SPUISD::RET_FLAG] =3D "SPUISD::RET_FLAG";
-    node_names[(unsigned) SPUISD::Hi] =3D "SPUISD::Hi";
-    node_names[(unsigned) SPUISD::Lo] =3D "SPUISD::Lo";
-    node_names[(unsigned) SPUISD::PCRelAddr] =3D "SPUISD::PCRelAddr";
-    node_names[(unsigned) SPUISD::AFormAddr] =3D "SPUISD::AFormAddr";
-    node_names[(unsigned) SPUISD::IndirectAddr] =3D "SPUISD::IndirectAddr";
-    node_names[(unsigned) SPUISD::LDRESULT] =3D "SPUISD::LDRESULT";
-    node_names[(unsigned) SPUISD::CALL] =3D "SPUISD::CALL";
-    node_names[(unsigned) SPUISD::SHUFB] =3D "SPUISD::SHUFB";
-    node_names[(unsigned) SPUISD::SHUFFLE_MASK] =3D "SPUISD::SHUFFLE_MASK";
-    node_names[(unsigned) SPUISD::CNTB] =3D "SPUISD::CNTB";
-    node_names[(unsigned) SPUISD::PREFSLOT2VEC] =3D "SPUISD::PREFSLOT2VEC";
-    node_names[(unsigned) SPUISD::VEC2PREFSLOT] =3D "SPUISD::VEC2PREFSLOT";
-    node_names[(unsigned) SPUISD::SHL_BITS] =3D "SPUISD::SHL_BITS";
-    node_names[(unsigned) SPUISD::SHL_BYTES] =3D "SPUISD::SHL_BYTES";
-    node_names[(unsigned) SPUISD::VEC_ROTL] =3D "SPUISD::VEC_ROTL";
-    node_names[(unsigned) SPUISD::VEC_ROTR] =3D "SPUISD::VEC_ROTR";
-    node_names[(unsigned) SPUISD::ROTBYTES_LEFT] =3D "SPUISD::ROTBYTES_LEF=
T";
-    node_names[(unsigned) SPUISD::ROTBYTES_LEFT_BITS] =3D
-            "SPUISD::ROTBYTES_LEFT_BITS";
-    node_names[(unsigned) SPUISD::SELECT_MASK] =3D "SPUISD::SELECT_MASK";
-    node_names[(unsigned) SPUISD::SELB] =3D "SPUISD::SELB";
-    node_names[(unsigned) SPUISD::ADD64_MARKER] =3D "SPUISD::ADD64_MARKER";
-    node_names[(unsigned) SPUISD::SUB64_MARKER] =3D "SPUISD::SUB64_MARKER";
-    node_names[(unsigned) SPUISD::MUL64_MARKER] =3D "SPUISD::MUL64_MARKER";
+const char *SPUTargetLowering::getTargetNodeName(unsigned Opcode) const {
+  switch (Opcode) {
+  default: return 0;
+  case SPUISD::RET_FLAG: return "SPUISD::RET_FLAG";
+  case SPUISD::Hi: return "SPUISD::Hi";
+  case SPUISD::Lo: return "SPUISD::Lo";
+  case SPUISD::PCRelAddr: return "SPUISD::PCRelAddr";
+  case SPUISD::AFormAddr: return "SPUISD::AFormAddr";
+  case SPUISD::IndirectAddr: return "SPUISD::IndirectAddr";
+  case SPUISD::LDRESULT: return "SPUISD::LDRESULT";
+  case SPUISD::CALL: return "SPUISD::CALL";
+  case SPUISD::SHUFB: return "SPUISD::SHUFB";
+  case SPUISD::SHUFFLE_MASK: return "SPUISD::SHUFFLE_MASK";
+  case SPUISD::CNTB: return "SPUISD::CNTB";
+  case SPUISD::PREFSLOT2VEC: return "SPUISD::PREFSLOT2VEC";
+  case SPUISD::VEC2PREFSLOT: return "SPUISD::VEC2PREFSLOT";
+  case SPUISD::SHL_BITS: return "SPUISD::SHL_BITS";
+  case SPUISD::SHL_BYTES: return "SPUISD::SHL_BYTES";
+  case SPUISD::VEC_ROTL: return "SPUISD::VEC_ROTL";
+  case SPUISD::VEC_ROTR: return "SPUISD::VEC_ROTR";
+  case SPUISD::ROTBYTES_LEFT: return "SPUISD::ROTBYTES_LEFT";
+  case SPUISD::ROTBYTES_LEFT_BITS: return "SPUISD::ROTBYTES_LEFT_BITS";
+  case SPUISD::SELECT_MASK: return "SPUISD::SELECT_MASK";
+  case SPUISD::SELB: return "SPUISD::SELB";
+  case SPUISD::ADD64_MARKER: return "SPUISD::ADD64_MARKER";
+  case SPUISD::SUB64_MARKER: return "SPUISD::SUB64_MARKER";
+  case SPUISD::MUL64_MARKER: return "SPUISD::MUL64_MARKER";
   }
-
-  std::map<unsigned, const char *>::iterator i =3D node_names.find(Opcode);
-
-  return ((i !=3D node_names.end()) ? i->second : 0);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -658,7 +667,7 @@
   // Do the load as a i128 to allow possible shifting
   SDValue low =3D DAG.getLoad(MVT::i128, dl, the_chain, basePtr,
                        lowMemPtr,
-                       LN->isVolatile(), LN->isNonTemporal(), 16);
+                       LN->isVolatile(), LN->isNonTemporal(), false, 16);
=20
   // When the size is not greater than alignment we get all data with just
   // one load
@@ -695,7 +704,8 @@
                                            basePtr,
                                            DAG.getConstant(16, PtrVT)),
                                highMemPtr,
-                               LN->isVolatile(), LN->isNonTemporal(), 16);
+                               LN->isVolatile(), LN->isNonTemporal(), fals=
e,=20
+                               16);
=20
     the_chain =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other, low.getVal=
ue(1),
                                                               high.getValu=
e(1));
@@ -850,7 +860,8 @@
=20
   // Load the lower part of the memory to which to store.
   SDValue low =3D DAG.getLoad(vecVT, dl, the_chain, basePtr,
-                          lowMemPtr, SN->isVolatile(), SN->isNonTemporal()=
, 16);
+                          lowMemPtr, SN->isVolatile(), SN->isNonTemporal(),
+                            false, 16);
=20
   // if we don't need to store over the 16 byte boundary, one store suffic=
es
   if (alignment >=3D StVT.getSizeInBits()/8) {
@@ -950,7 +961,8 @@
                                DAG.getNode(ISD::ADD, dl, PtrVT, basePtr,
                                            DAG.getConstant( 16, PtrVT)),
                                highMemPtr,
-                               SN->isVolatile(), SN->isNonTemporal(), 16);
+                               SN->isVolatile(), SN->isNonTemporal(),=20
+                               false, 16);
     the_chain =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other, low.getVal=
ue(1),
                                                               hi.getValue(=
1));
=20
@@ -1017,7 +1029,6 @@
=20
   llvm_unreachable("LowerConstantPool: Relocation model other than static"
                    " not supported.");
-  return SDValue();
 }
=20
 //! Alternate entry point for generating the address of a constant pool en=
try
@@ -1048,7 +1059,6 @@
=20
   llvm_unreachable("LowerJumpTable: Relocation model other than static"
                    " not supported.");
-  return SDValue();
 }
=20
 static SDValue
@@ -1076,8 +1086,6 @@
                       "not supported.");
     /*NOTREACHED*/
   }
-
-  return SDValue();
 }
=20
 //! Custom lower double precision floating point constants
@@ -1185,7 +1193,7 @@
       int FI =3D MFI->CreateFixedObject(ObjSize, ArgOffset, true);
       SDValue FIN =3D DAG.getFrameIndex(FI, PtrVT);
       ArgVal =3D DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(=
),
-                           false, false, 0);
+                           false, false, false, 0);
       ArgOffset +=3D StackSlotSize;
     }
=20
@@ -1198,7 +1206,7 @@
   if (isVarArg) {
     // FIXME: we should be able to query the argument registers from
     //        tablegen generated code.
-    static const unsigned ArgRegs[] =3D {
+    static const uint16_t ArgRegs[] =3D {
       SPU::R3,  SPU::R4,  SPU::R5,  SPU::R6,  SPU::R7,  SPU::R8,  SPU::R9,
       SPU::R10, SPU::R11, SPU::R12, SPU::R13, SPU::R14, SPU::R15, SPU::R16,
       SPU::R17, SPU::R18, SPU::R19, SPU::R20, SPU::R21, SPU::R22, SPU::R23,
@@ -1212,7 +1220,7 @@
       SPU::R73, SPU::R74, SPU::R75, SPU::R76, SPU::R77, SPU::R78, SPU::R79
     };
     // size of ArgRegs array
-    unsigned NumArgRegs =3D 77;
+    const unsigned NumArgRegs =3D 77;
=20
     // We will spill (79-3)+1 registers to the stack
     SmallVector<SDValue, 79-3+1> MemOps;
@@ -1257,7 +1265,7 @@
 SDValue
 SPUTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                              CallingConv::ID CallConv, bool isVarArg,
-                             bool &isTailCall,
+                             bool doesNotRet, bool &isTailCall,
                              const SmallVectorImpl<ISD::OutputArg> &Outs,
                              const SmallVectorImpl<SDValue> &OutVals,
                              const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -1675,7 +1683,6 @@
     SDValue T =3D DAG.getConstant(Value32, MVT::i32);
     return DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,
                        DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, T,T,=
T,T));
-    break;
   }
   case MVT::v2f64: {
     uint64_t f64val =3D uint64_t(SplatBits);
@@ -1685,7 +1692,6 @@
     SDValue T =3D DAG.getConstant(f64val, MVT::i64);
     return DAG.getNode(ISD::BITCAST, dl, MVT::v2f64,
                        DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, T, T=
));
-    break;
   }
   case MVT::v16i8: {
    // 8-bit constants have to be expanded to 16-bits
@@ -1712,8 +1718,6 @@
     return SPU::LowerV2I64Splat(VT, DAG, SplatBits, dl);
   }
   }
-
-  return SDValue();
 }
=20
 /*!
@@ -1743,9 +1747,11 @@
=20
     // Both upper and lower are special, lower to a constant pool load:
     if (lower_special && upper_special) {
-      SDValue SplatValCN =3D DAG.getConstant(SplatVal, MVT::i64);
-      return DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64,
-                         SplatValCN, SplatValCN);
+      SDValue UpperVal =3D DAG.getConstant(upper, MVT::i32);
+      SDValue LowerVal =3D DAG.getConstant(lower, MVT::i32);
+      SDValue BV =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
+                         UpperVal, LowerVal, UpperVal, LowerVal);
+      return DAG.getNode(ISD::BITCAST, dl, OpVT, BV);
     }
=20
     SDValue LO32;
@@ -1985,8 +1991,6 @@
       return DAG.getNode(SPUISD::PREFSLOT2VEC, dl, Op.getValueType(), Op0,=
 Op0);
     }
   }
-
-  return SDValue();
 }
=20
 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
@@ -2020,8 +2024,7 @@
     int elt_byte =3D EltNo * VT.getSizeInBits() / 8;
=20
     switch (VT.getSimpleVT().SimpleTy) {
-    default:
-      assert(false && "Invalid value type!");
+    default: llvm_unreachable("Invalid value type!");
     case MVT::i8: {
       prefslot_begin =3D prefslot_end =3D 3;
       break;
@@ -2199,8 +2202,6 @@
   switch (Opc) {
   default:
     llvm_unreachable("Unhandled i8 math operator");
-    /*NOTREACHED*/
-    break;
   case ISD::ADD: {
     // 8-bit addition: Promote the arguments up to 16-bits and truncate
     // the result:
@@ -2285,11 +2286,8 @@
     N1 =3D DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i16, N1);
     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
                        DAG.getNode(Opc, dl, MVT::i16, N0, N1));
-    break;
   }
   }
-
-  return SDValue();
 }
=20
 //! Lower byte immediate operations for v16i8 vectors:
@@ -2354,8 +2352,7 @@
   DebugLoc dl =3D Op.getDebugLoc();
=20
   switch (VT.getSimpleVT().SimpleTy) {
-  default:
-    assert(false && "Invalid value type!");
+  default: llvm_unreachable("Invalid value type!");
   case MVT::i8: {
     SDValue N =3D Op.getOperand(0);
     SDValue Elt0 =3D DAG.getConstant(0, MVT::i32);
@@ -3161,7 +3158,6 @@
 //! Compute used/known bits for a SPU operand
 void
 SPUTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
-                                                  const APInt &Mask,
                                                   APInt &KnownZero,
                                                   APInt &KnownOne,
                                                   const SelectionDAG &DAG,
@@ -3227,7 +3223,7 @@
   return (V > -(1 << 18) && V < (1 << 18) - 1);
 }
=20
-bool SPUTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) con=
st {
+bool SPUTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
   return false;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUISelLowering.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUISelLowering.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUISelLowering.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,9 +15,9 @@
 #ifndef SPU_ISELLOWERING_H
 #define SPU_ISELLOWERING_H
=20
+#include "SPU.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/CodeGen/SelectionDAG.h"
-#include "SPU.h"
=20
 namespace llvm {
   namespace SPUISD {
@@ -121,7 +121,6 @@
     virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) con=
st;
=20
     virtual void computeMaskedBitsForTargetNode(const SDValue Op,
-                                                const APInt &Mask,
                                                 APInt &KnownZero,
                                                 APInt &KnownOne,
                                                 const SelectionDAG &DAG,
@@ -162,7 +161,7 @@
     virtual SDValue
       LowerCall(SDValue Chain, SDValue Callee,
                 CallingConv::ID CallConv, bool isVarArg,
-                bool &isTailCall,
+                bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUInstrBuilder.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUInstrBuilder.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUInstrBuilder.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D-- SPUInstrBuilder.h - Aides for building Cell SPU insts -----*- C=
++ -*-=3D=3D//
+//=3D=3D=3D-- SPUInstrBuilder.h - Aides for building Cell SPU insts ---*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUInstrFormats.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUInstrFormats.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUInstrFormats.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D=3D SPUInstrFormats.td - Cell SPU Instruction Formats ---*- tab=
legen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SPUInstrFormats.td - Cell SPU Instruction Formats --*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUInstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUInstrInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUInstrInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SPUInstrInfo.cpp - Cell SPU Instruction Information ---------=
-------=3D=3D=3D//
+//=3D=3D=3D-- SPUInstrInfo.cpp - Cell SPU Instruction Information --------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUInstrInfo.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUInstrInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUInstrInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SPUInstrInfo.h - Cell SPU Instruction Information --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- SPUInstrInfo.h - Cell SPU Instruction Information -------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,8 +15,8 @@
 #define SPU_INSTRUCTIONINFO_H
=20
 #include "SPU.h"
+#include "SPURegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "SPURegisterInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "SPUGenInstrInfo.inc"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUMachineFunction.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUMachineFunction.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUMachineFunction.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -21,7 +21,8 @@
 /// SPUFunctionInfo - Cell SPU target-specific information for each
 /// MachineFunction
 class SPUFunctionInfo : public MachineFunctionInfo {
-private:
+  virtual void anchor();
+
   /// UsesLR - Indicates whether LR is used in the current function.
   ///
   bool UsesLR;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUMathInstr.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUMathInstr.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUMathInstr.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D=3D--- SPUMathInst.td - Cell SPU math operations -*- tabl=
egen -*---=3D=3D=3D=3D=3D=3D//
+//=3D=3D=3D-- SPUMathInst.td - Cell SPU math operations ---------*- tableg=
en -*--=3D=3D=3D//
 //
 //                     Cell SPU math operations
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUNodes.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUNodes.td	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUNodes.td	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SPUNodes.td - Specialized SelectionDAG nodes used for CellSPU=
 ------=3D=3D=3D//
+//=3D=3D=3D SPUNodes.td - Specialized SelectionDAG nodes by CellSPU -*- ta=
blegen -*-//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUNopFiller.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUNopFiller.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUNopFiller.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- SPUNopFiller.cpp - Add nops/lnops to align the pipelines---=
=3D=3D=3D//
+//=3D=3D=3D-- SPUNopFiller.cpp - Add nops/lnops to align the pipelines ---=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUOperands.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUOperands.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUOperands.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- SPUOperands.td - Cell SPU Instruction Operands ------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SPUOperands.td - Cell SPU Instruction Operands -----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Cell SPU Instruction Operands:
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PURegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SPURegisterInfo.cpp - Cell SPU Register Information ---------=
-------=3D=3D=3D//
+//=3D=3D=3D-- SPURegisterInfo.cpp - Cell SPU Register Information --------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,8 +12,8 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "reginfo"
+#include "SPURegisterInfo.h"
 #include "SPU.h"
-#include "SPURegisterInfo.h"
 #include "SPUInstrBuilder.h"
 #include "SPUSubtarget.h"
 #include "SPUMachineFunction.h"
@@ -197,11 +197,11 @@
   return &SPU::R32CRegClass;
 }
=20
-const unsigned *
+const uint16_t *
 SPURegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const
 {
   // Cell ABI calling convention
-  static const unsigned SPU_CalleeSaveRegs[] =3D {
+  static const uint16_t SPU_CalleeSaveRegs[] =3D {
     SPU::R80, SPU::R81, SPU::R82, SPU::R83,
     SPU::R84, SPU::R85, SPU::R86, SPU::R87,
     SPU::R88, SPU::R89, SPU::R90, SPU::R91,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PURegisterInfo.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SPURegisterInfo.h - Cell SPU Register Information Impl ----*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- SPURegisterInfo.h - Cell SPU Register Information Impl --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -57,7 +57,7 @@
     }
=20
     //! Return the array of callee-saved registers
-    virtual const unsigned* getCalleeSavedRegs(const MachineFunction *MF) =
const;
+    virtual const uint16_t* getCalleeSavedRegs(const MachineFunction *MF) =
const;
=20
     //! Allow for scavenging, so we can get scratch registers when needed.
     virtual bool requiresRegisterScavenging(const MachineFunction &MF) con=
st
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PURegisterInfo.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPURegisterInfo.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- SPURegisterInfo.td - The Cell SPU Register File -----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SPURegisterInfo.td - The Cell SPU Register File ----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUSchedule.td
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUSchedule.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUSchedule.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- SPUSchedule.td - Cell Scheduling Definitions --------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SPUSchedule.td - Cell Scheduling Definitions -------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUSubtarget.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUSubtarget.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUSubtarget.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SPUSubtarget.cpp - STI Cell SPU Subtarget Information -------=
-------=3D=3D=3D//
+//=3D=3D=3D-- SPUSubtarget.cpp - STI Cell SPU Subtarget Information ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,7 +15,6 @@
 #include "SPU.h"
 #include "SPURegisterInfo.h"
 #include "llvm/Support/TargetRegistry.h"
-#include "llvm/ADT/SmallVector.h"
=20
 #define GET_SUBTARGETINFO_TARGET_DESC
 #define GET_SUBTARGETINFO_CTOR
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUTargetMachine.cpp
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUTargetMachine.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUTargetMachine.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -11,17 +11,16 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "SPUTargetMachine.h"
 #include "SPU.h"
-#include "SPUTargetMachine.h"
 #include "llvm/PassManager.h"
-#include "llvm/CodeGen/RegAllocRegistry.h"
 #include "llvm/CodeGen/SchedulerRegistry.h"
 #include "llvm/Support/DynamicLibrary.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 using namespace llvm;
=20
-extern "C" void LLVMInitializeCellSPUTarget() {=20
+extern "C" void LLVMInitializeCellSPUTarget() {
   // Register the target.
   RegisterTargetMachine<SPUTargetMachine> X(TheCellSPUTarget);
 }
@@ -34,8 +33,10 @@
=20
 SPUTargetMachine::SPUTargetMachine(const Target &T, StringRef TT,
                                    StringRef CPU, StringRef FS,
-                                   Reloc::Model RM, CodeModel::Model CM)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
+                                   const TargetOptions &Options,
+                                   Reloc::Model RM, CodeModel::Model CM,
+                                   CodeGenOpt::Level OL)
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     Subtarget(TT, CPU, FS),
     DataLayout(Subtarget.getTargetDataString()),
     InstrInfo(*this),
@@ -49,16 +50,34 @@
 // Pass Pipeline Configuration
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-bool SPUTargetMachine::addInstSelector(PassManagerBase &PM,
-                                       CodeGenOpt::Level OptLevel) {
+namespace {
+/// SPU Code Generator Pass Configuration Options.
+class SPUPassConfig : public TargetPassConfig {
+public:
+  SPUPassConfig(SPUTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  SPUTargetMachine &getSPUTargetMachine() const {
+    return getTM<SPUTargetMachine>();
+  }
+
+  virtual bool addInstSelector();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *SPUTargetMachine::createPassConfig(PassManagerBase &PM) {
+  return new SPUPassConfig(this, PM);
+}
+
+bool SPUPassConfig::addInstSelector() {
   // Install an instruction selector.
-  PM.add(createSPUISelDag(*this));
+  PM.add(createSPUISelDag(getSPUTargetMachine()));
   return false;
 }
=20
 // passes to run just before printing the assembly
-bool SPUTargetMachine::
-addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel) {
+bool SPUPassConfig::addPreEmitPass() {
   // load the TCE instruction scheduler, if available via
   // loaded plugins
   typedef llvm::FunctionPass* (*BuilderFunc)(const char*);
@@ -69,6 +88,6 @@
       PM.add(schedulerCreator("cellspu"));
=20
   //align instructions with nops/lnops for dual issue
-  PM.add(createSPUNopFillerPass(*this));
+  PM.add(createSPUNopFillerPass(getSPUTargetMachine()));
   return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CellSPU/S=
PUTargetMachine.h
--- a/head/contrib/llvm/lib/Target/CellSPU/SPUTargetMachine.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CellSPU/SPUTargetMachine.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- SPUTargetMachine.h - Define TargetMachine for Cell SPU ----*=
- C++ -*-=3D//
+//=3D=3D=3D-- SPUTargetMachine.h - Define TargetMachine for Cell SPU --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,9 +23,6 @@
 #include "llvm/Target/TargetData.h"
=20
 namespace llvm {
-class PassManager;
-class GlobalValue;
-class TargetFrameLowering;
=20
 /// SPUTargetMachine
 ///
@@ -39,8 +36,9 @@
   InstrItineraryData  InstrItins;
 public:
   SPUTargetMachine(const Target &T, StringRef TT,
-                   StringRef CPU, StringRef FS,
-                   Reloc::Model RM, CodeModel::Model CM);
+                   StringRef CPU, StringRef FS, const TargetOptions &Optio=
ns,
+                   Reloc::Model RM, CodeModel::Model CM,
+                   CodeGenOpt::Level OL);
=20
   /// Return the subtarget implementation object
   virtual const SPUSubtarget     *getSubtargetImpl() const {
@@ -60,7 +58,7 @@
     return NULL;
   }
=20
-  virtual const SPUTargetLowering *getTargetLowering() const {=20
+  virtual const SPUTargetLowering *getTargetLowering() const {
    return &TLInfo;
   }
=20
@@ -71,7 +69,7 @@
   virtual const SPURegisterInfo *getRegisterInfo() const {
     return &InstrInfo.getRegisterInfo();
   }
- =20
+
   virtual const TargetData *getTargetData() const {
     return &DataLayout;
   }
@@ -79,11 +77,9 @@
   virtual const InstrItineraryData *getInstrItineraryData() const {
     return &InstrItins;
   }
- =20
+
   // Pass Pipeline Configuration
-  virtual bool addInstSelector(PassManagerBase &PM,
-                               CodeGenOpt::Level OptLevel);
-  virtual bool addPreEmitPass(PassManagerBase &, CodeGenOpt::Level);=09
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CppBacken=
d/CPPBackend.cpp
--- a/head/contrib/llvm/lib/Target/CppBackend/CPPBackend.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CppBackend/CPPBackend.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -33,8 +33,9 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Config/config.h"
 #include <algorithm>
+#include <cstdio>
+#include <map>
 #include <set>
-#include <map>
 using namespace llvm;
=20
 static cl::opt<std::string>
@@ -189,13 +190,24 @@
   case Type::VectorTyID:   return "packed_";
   default:                 return "other_";
   }
-  return "unknown_";
 }
=20
 void CppWriter::error(const std::string& msg) {
   report_fatal_error(msg);
 }
=20
+static inline std::string ftostr(const APFloat& V) {
+  std::string Buf;
+  if (&V.getSemantics() =3D=3D &APFloat::IEEEdouble) {
+    raw_string_ostream(Buf) << V.convertToDouble();
+    return Buf;
+  } else if (&V.getSemantics() =3D=3D &APFloat::IEEEsingle) {
+    raw_string_ostream(Buf) << (double)V.convertToFloat();
+    return Buf;
+  }
+  return "<unknown format in ftostr>"; // error
+}
+
 // printCFP - Print a floating point constant .. very carefully :)
 // This makes sure that conversion to/from floating yields the same binary
 // result so that we don't lose precision.
@@ -301,7 +313,6 @@
=20
 void CppWriter::printVisibilityType(GlobalValue::VisibilityTypes VisType) {
   switch (VisType) {
-  default: llvm_unreachable("Unknown GVar visibility");
   case GlobalValue::DefaultVisibility:
     Out << "GlobalValue::DefaultVisibility";
     break;
@@ -443,7 +454,7 @@
     for (unsigned i =3D 0; i < PAL.getNumSlots(); ++i) {
       unsigned index =3D PAL.getSlot(i).Index;
       Attributes attrs =3D PAL.getSlot(i).Attrs;
-      Out << "PAWI.Index =3D " << index << "U; PAWI.Attrs =3D 0 ";
+      Out << "PAWI.Index =3D " << index << "U; PAWI.Attrs =3D Attribute::N=
one ";
 #define HANDLE_ATTR(X)                 \
       if (attrs & Attribute::X)      \
         Out << " | Attribute::" #X;  \
@@ -678,11 +689,6 @@
   std::string constName(getCppName(CV));
   std::string typeName(getCppName(CV->getType()));
=20
-  if (isa<GlobalValue>(CV)) {
-    // Skip variables and functions, we emit them elsewhere
-    return;
-  }
-
   if (const ConstantInt *CI =3D dyn_cast<ConstantInt>(CV)) {
     std::string constValue =3D CI->getValue().toString(10, true);
     Out << "ConstantInt* " << constName
@@ -700,38 +706,17 @@
     printCFP(CFP);
     Out << ";";
   } else if (const ConstantArray *CA =3D dyn_cast<ConstantArray>(CV)) {
-    if (CA->isString() &&
-        CA->getType()->getElementType() =3D=3D
-            Type::getInt8Ty(CA->getContext())) {
-      Out << "Constant* " << constName <<
-             " =3D ConstantArray::get(mod->getContext(), \"";
-      std::string tmp =3D CA->getAsString();
-      bool nullTerminate =3D false;
-      if (tmp[tmp.length()-1] =3D=3D 0) {
-        tmp.erase(tmp.length()-1);
-        nullTerminate =3D true;
-      }
-      printEscapedString(tmp);
-      // Determine if we want null termination or not.
-      if (nullTerminate)
-        Out << "\", true"; // Indicate that the null terminator should be
-                           // added.
-      else
-        Out << "\", false";// No null terminator
-      Out << ");";
-    } else {
-      Out << "std::vector<Constant*> " << constName << "_elems;";
+    Out << "std::vector<Constant*> " << constName << "_elems;";
+    nl(Out);
+    unsigned N =3D CA->getNumOperands();
+    for (unsigned i =3D 0; i < N; ++i) {
+      printConstant(CA->getOperand(i)); // recurse to print operands
+      Out << constName << "_elems.push_back("
+          << getCppName(CA->getOperand(i)) << ");";
       nl(Out);
-      unsigned N =3D CA->getNumOperands();
-      for (unsigned i =3D 0; i < N; ++i) {
-        printConstant(CA->getOperand(i)); // recurse to print operands
-        Out << constName << "_elems.push_back("
-            << getCppName(CA->getOperand(i)) << ");";
-        nl(Out);
-      }
-      Out << "Constant* " << constName << " =3D ConstantArray::get("
-          << typeName << ", " << constName << "_elems);";
     }
+    Out << "Constant* " << constName << " =3D ConstantArray::get("
+        << typeName << ", " << constName << "_elems);";
   } else if (const ConstantStruct *CS =3D dyn_cast<ConstantStruct>(CV)) {
     Out << "std::vector<Constant*> " << constName << "_fields;";
     nl(Out);
@@ -744,14 +729,14 @@
     }
     Out << "Constant* " << constName << " =3D ConstantStruct::get("
         << typeName << ", " << constName << "_fields);";
-  } else if (const ConstantVector *CP =3D dyn_cast<ConstantVector>(CV)) {
+  } else if (const ConstantVector *CVec =3D dyn_cast<ConstantVector>(CV)) {
     Out << "std::vector<Constant*> " << constName << "_elems;";
     nl(Out);
-    unsigned N =3D CP->getNumOperands();
+    unsigned N =3D CVec->getNumOperands();
     for (unsigned i =3D 0; i < N; ++i) {
-      printConstant(CP->getOperand(i));
+      printConstant(CVec->getOperand(i));
       Out << constName << "_elems.push_back("
-          << getCppName(CP->getOperand(i)) << ");";
+          << getCppName(CVec->getOperand(i)) << ");";
       nl(Out);
     }
     Out << "Constant* " << constName << " =3D ConstantVector::get("
@@ -759,6 +744,41 @@
   } else if (isa<UndefValue>(CV)) {
     Out << "UndefValue* " << constName << " =3D UndefValue::get("
         << typeName << ");";
+  } else if (const ConstantDataSequential *CDS =3D
+               dyn_cast<ConstantDataSequential>(CV)) {
+    if (CDS->isString()) {
+      Out << "Constant *" << constName <<
+      " =3D ConstantDataArray::getString(mod->getContext(), \"";
+      StringRef Str =3D CDS->getAsString();
+      bool nullTerminate =3D false;
+      if (Str.back() =3D=3D 0) {
+        Str =3D Str.drop_back();
+        nullTerminate =3D true;
+      }
+      printEscapedString(Str);
+      // Determine if we want null termination or not.
+      if (nullTerminate)
+        Out << "\", true);";
+      else
+        Out << "\", false);";// No null terminator
+    } else {
+      // TODO: Could generate more efficient code generating CDS calls ins=
tead.
+      Out << "std::vector<Constant*> " << constName << "_elems;";
+      nl(Out);
+      for (unsigned i =3D 0; i !=3D CDS->getNumElements(); ++i) {
+        Constant *Elt =3D CDS->getElementAsConstant(i);
+        printConstant(Elt);
+        Out << constName << "_elems.push_back(" << getCppName(Elt) << ");";
+        nl(Out);
+      }
+      Out << "Constant* " << constName;
+     =20
+      if (isa<ArrayType>(CDS->getType()))
+        Out << " =3D ConstantArray::get(";
+      else
+        Out << " =3D ConstantVector::get(";
+      Out << typeName << ", " << constName << "_elems);";
+    }
   } else if (const ConstantExpr *CE =3D dyn_cast<ConstantExpr>(CV)) {
     if (CE->getOpcode() =3D=3D Instruction::GetElementPtr) {
       Out << "std::vector<Constant*> " << constName << "_indices;";
@@ -1083,10 +1103,10 @@
         << getOpName(SI->getDefaultDest()) << ", "
         << SI->getNumCases() << ", " << bbname << ");";
     nl(Out);
-    unsigned NumCases =3D SI->getNumCases();
-    for (unsigned i =3D 1; i < NumCases; ++i) {
-      const ConstantInt* CaseVal =3D SI->getCaseValue(i);
-      const BasicBlock* BB =3D SI->getSuccessor(i);
+    for (SwitchInst::ConstCaseIt i =3D SI->case_begin(), e =3D SI->case_en=
d();
+         i !=3D e; ++i) {
+      const ConstantInt* CaseVal =3D i.getCaseValue();
+      const BasicBlock *BB =3D i.getCaseSuccessor();
       Out << iName << "->addCase("
           << getOpName(CaseVal) << ", "
           << getOpName(BB) << ");";
@@ -1135,11 +1155,6 @@
     nl(Out);
     break;
   }
-  case Instruction::Unwind: {
-    Out << "new UnwindInst("
-        << bbname << ");";
-    break;
-  }
   case Instruction::Unreachable: {
     Out << "new UnreachableInst("
         << "mod->getContext(), "
@@ -1354,7 +1369,7 @@
     case Instruction::PtrToInt: Out << "PtrToIntInst"; break;
     case Instruction::IntToPtr: Out << "IntToPtrInst"; break;
     case Instruction::BitCast:  Out << "BitCastInst"; break;
-    default: assert(0 && "Unreachable"); break;
+    default: llvm_unreachable("Unreachable");
     }
     Out << "(" << opNames[0] << ", "
         << getCppName(cst->getType()) << ", \"";
@@ -2049,8 +2064,6 @@
       fname =3D "makeLLVMType";
     printType(fname,tgtname);
     break;
-   default:
-    error("Invalid generation option");
   }
=20
   return false;
@@ -2065,7 +2078,6 @@
 bool CPPTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
                                            formatted_raw_ostream &o,
                                            CodeGenFileType FileType,
-                                           CodeGenOpt::Level OptLevel,
                                            bool DisableVerify) {
   if (FileType !=3D TargetMachine::CGFT_AssemblyFile) return true;
   PM.add(new CppWriter(o));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/CppBacken=
d/CPPTargetMachine.h
--- a/head/contrib/llvm/lib/Target/CppBackend/CPPTargetMachine.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/CppBackend/CPPTargetMachine.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -23,14 +23,14 @@
=20
 struct CPPTargetMachine : public TargetMachine {
   CPPTargetMachine(const Target &T, StringRef TT,
-                   StringRef CPU, StringRef FS,
-                   Reloc::Model RM, CodeModel::Model CM)
-    : TargetMachine(T, TT, CPU, FS) {}
+                   StringRef CPU, StringRef FS, const TargetOptions &Optio=
ns,
+                   Reloc::Model RM, CodeModel::Model CM,
+                   CodeGenOpt::Level OL)
+    : TargetMachine(T, TT, CPU, FS, Options) {}
=20
   virtual bool addPassesToEmitFile(PassManagerBase &PM,
                                    formatted_raw_ostream &Out,
                                    CodeGenFileType FileType,
-                                   CodeGenOpt::Level OptLevel,
                                    bool DisableVerify);
=20
   virtual const TargetData *getTargetData() const { return 0; }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/As=
mParser/MBlazeAsmLexer.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/AsmParser/MBlazeAsmLexer.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/AsmParser/MBlazeAsmLexer.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -9,10 +9,6 @@
=20
 #include "MCTargetDesc/MBlazeBaseInfo.h"
=20
-#include "llvm/ADT/OwningPtr.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
-
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCParser/MCAsmLexer.h"
 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
@@ -100,11 +96,7 @@
     return AsmToken(lexedToken);
   case AsmToken::Identifier:
   {
-    std::string upperCase =3D lexedToken.getString().str();
-    std::string lowerCase =3D LowercaseString(upperCase);
-    StringRef lowerRef(lowerCase);
-   =20
-    unsigned regID =3D MatchRegisterName(lowerRef);
+    unsigned regID =3D MatchRegisterName(lexedToken.getString().lower());
    =20
     if (regID) {
       return AsmToken(AsmToken::Register,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/As=
mParser/MBlazeAsmParser.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/AsmParser/MBlazeAsmParser.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/AsmParser/MBlazeAsmParser.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -18,9 +18,7 @@
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 using namespace llvm;
=20
@@ -347,7 +345,6 @@
   }
=20
   llvm_unreachable("Implement any new match types added!");
-  return true;
 }
=20
 MBlazeOperand *MBlazeAsmParser::
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/Di=
sassembler/MBlazeDisassembler.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/Disassembler/MBlazeDisassembler.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/Disassembler/MBlazeDisassembler.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeDisassembler.cpp - Disassembler for MicroBlaze  ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeDisassembler.cpp - Disassembler for MicroBlaze  ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,13 +13,12 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "MBlaze.h"
-#include "MBlazeInstrInfo.h"
 #include "MBlazeDisassembler.h"
=20
 #include "llvm/MC/EDInstInfo.h"
 #include "llvm/MC/MCDisassembler.h"
-#include "llvm/MC/MCDisassembler.h"
 #include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCInstrDesc.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MemoryObject.h"
 #include "llvm/Support/TargetRegistry.h"
@@ -30,14 +29,14 @@
 #include "MBlazeGenEDInfo.inc"
=20
 namespace llvm {
-extern MCInstrDesc MBlazeInsts[];
+extern const MCInstrDesc MBlazeInsts[];
 }
=20
 using namespace llvm;
=20
-const unsigned UNSUPPORTED =3D -1;
+const uint16_t UNSUPPORTED =3D -1;
=20
-static unsigned mblazeBinary2Opcode[] =3D {
+static const uint16_t mblazeBinary2Opcode[] =3D {
   MBlaze::ADD,   MBlaze::RSUB,   MBlaze::ADDC,   MBlaze::RSUBC,   //00,01,=
02,03
   MBlaze::ADDK,  MBlaze::RSUBK,  MBlaze::ADDKC,  MBlaze::RSUBKC,  //04,05,=
06,07
   MBlaze::ADDI,  MBlaze::RSUBI,  MBlaze::ADDIC,  MBlaze::RSUBIC,  //08,09,=
0A,0B
@@ -124,6 +123,7 @@
     case 0x41: return MBlaze::SRL;
     case 0x21: return MBlaze::SRC;
     case 0x01: return MBlaze::SRA;
+    case 0xE0: return MBlaze::CLZ;
     }
 }
=20
@@ -177,6 +177,13 @@
 }
=20
 static unsigned decodeBRI(uint32_t insn) {
+    switch (insn&0x3FFFFFF) {
+    default:        break;
+    case 0x0020004: return MBlaze::IDMEMBAR;
+    case 0x0220004: return MBlaze::DMEMBAR;
+    case 0x0420004: return MBlaze::IMEMBAR;
+    }
+
     switch ((insn>>16)&0x1F) {
     default:   return UNSUPPORTED;
     case 0x00: return MBlaze::BRI;
@@ -485,7 +492,7 @@
   }
 }
=20
-EDInstInfo *MBlazeDisassembler::getEDInfo() const {
+const EDInstInfo *MBlazeDisassembler::getEDInfo() const {
   return instInfoMBlaze;
 }
=20
@@ -532,6 +539,9 @@
   default:=20
     return Fail;
=20
+  case MBlazeII::FC:
+    break;
+
   case MBlazeII::FRRRR:
     if (RD =3D=3D UNSUPPORTED || RA =3D=3D UNSUPPORTED || RB =3D=3D UNSUPP=
ORTED)
       return Fail;
@@ -548,6 +558,13 @@
     instr.addOperand(MCOperand::CreateReg(RB));
     break;
=20
+  case MBlazeII::FRR:
+    if (RD =3D=3D UNSUPPORTED || RA =3D=3D UNSUPPORTED)
+      return Fail;
+    instr.addOperand(MCOperand::CreateReg(RD));
+    instr.addOperand(MCOperand::CreateReg(RA));
+    break;
+
   case MBlazeII::FRI:
     switch (opcode) {
     default:=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/Di=
sassembler/MBlazeDisassembler.h
--- a/head/contrib/llvm/lib/Target/MBlaze/Disassembler/MBlazeDisassembler.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/Disassembler/MBlazeDisassembler.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeDisassembler.h - Disassembler for MicroBlaze  ------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeDisassembler.h - Disassembler for MicroBlaze  -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -17,8 +17,6 @@
=20
 #include "llvm/MC/MCDisassembler.h"
=20
-struct InternalInstruction;
-
 namespace llvm {
  =20
 class MCInst;
@@ -48,7 +46,7 @@
                       raw_ostream &cStream) const;
=20
   /// getEDInfo - See MCDisassembler.
-  EDInstInfo *getEDInfo() const;
+  const EDInstInfo *getEDInfo() const;
 };
=20
 } // namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/In=
stPrinter/MBlazeInstPrinter.h
--- a/head/contrib/llvm/lib/Target/MBlaze/InstPrinter/MBlazeInstPrinter.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/InstPrinter/MBlazeInstPrinter.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MBLazeInstPrinter.h - Convert MBlaze MCInst to assembly synt=
ax ----=3D=3D=3D//
+//=3D MBlazeInstPrinter.h - Convert MBlaze MCInst to assembly syntax -*- C=
++ -*-//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -21,15 +21,15 @@
=20
   class MBlazeInstPrinter : public MCInstPrinter {
   public:
-    MBlazeInstPrinter(const MCAsmInfo &MAI)
-      : MCInstPrinter(MAI) {}
+    MBlazeInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                      const MCRegisterInfo &MRI)
+      : MCInstPrinter(MAI, MII, MRI) {}
=20
     virtual void printInst(const MCInst *MI, raw_ostream &O, StringRef Ann=
ot);
=20
     // Autogenerated by tblgen.
     void printInstruction(const MCInst *MI, raw_ostream &O);
     static const char *getRegisterName(unsigned RegNo);
-    static const char *getInstructionName(unsigned Opcode);
=20
     void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O,
                       const char *Modifier =3D 0);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
laze.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlaze.td	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlaze.td	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlaze.td - Describe the MBlaze Target Machine ------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlaze.td - Describe the MBlaze Target Machine -----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeAsmPrinter.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeAsmPrinter.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeAsmPrinter.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -38,8 +38,6 @@
 #include "llvm/Target/TargetLoweringObjectFile.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
-#include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/raw_ostream.h"
@@ -119,7 +117,7 @@
 static void printHex32(unsigned int Value, raw_ostream &O) {
   O << "0x";
   for (int i =3D 7; i >=3D 0; i--)
-    O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
+    O.write_hex((Value & (0xF << (i*4))) >> (i*4));
 }
=20
 // Create a bitmask with all callee saved registers for CPU or Floating Po=
int
@@ -311,9 +309,9 @@
=20
   // Check if the last terminator is an unconditional branch.
   MachineBasicBlock::const_iterator I =3D Pred->end();
-  while (I !=3D Pred->begin() && !(--I)->getDesc().isTerminator())
+  while (I !=3D Pred->begin() && !(--I)->isTerminator())
     ; // Noop
-  return I =3D=3D Pred->end() || !I->getDesc().isBarrier();
+  return I =3D=3D Pred->end() || !I->isBarrier();
 }
=20
 // Force static initialization.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeDelaySlotFiller.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeDelaySlotFiller.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeDelaySlotFiller.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -29,13 +29,11 @@
=20
 STATISTIC(FilledSlots, "Number of delay slots filled");
=20
-namespace llvm {
-cl::opt<bool> DisableDelaySlotFiller(
+static cl::opt<bool> MBDisableDelaySlotFiller(
   "disable-mblaze-delay-filler",
   cl::init(false),
   cl::desc("Disable the MBlaze delay slot filter."),
   cl::Hidden);
-}
=20
 namespace {
   struct Filler : public MachineFunctionPass {
@@ -109,7 +107,6 @@
   // Hazard check
   MachineBasicBlock::iterator a =3D candidate;
   MachineBasicBlock::iterator b =3D slot;
-  MCInstrDesc desc =3D candidate->getDesc();
=20
   // MBB layout:-
   //    candidate :=3D a0 =3D operation(a1, a2)
@@ -123,7 +120,7 @@
   // 4. b0 is one or more of {a1, a2}
   // 5. a accesses memory, and the middle bit
   //    contains a store operation.
-  bool a_is_memory =3D desc.mayLoad() || desc.mayStore();
+  bool a_is_memory =3D candidate->mayLoad() || candidate->mayStore();
=20
   // Determine the number of operands in the slot instruction and in the
   // candidate instruction.
@@ -156,7 +153,7 @@
     }
=20
     // Check hazard type 5
-    if (a_is_memory && m->getDesc().mayStore())
+    if (a_is_memory && m->mayStore())
       return true;
   }
=20
@@ -183,8 +180,8 @@
   if (candidate =3D=3D MBB.begin())
     return false;
=20
-  MCInstrDesc brdesc =3D (--candidate)->getDesc();
-  return (brdesc.hasDelaySlot());
+  --candidate;
+  return (candidate->hasDelaySlot());
 }
=20
 static bool hasUnknownSideEffects(MachineBasicBlock::iterator &I) {
@@ -211,9 +208,8 @@
       break;
=20
     --I;
-    MCInstrDesc desc =3D I->getDesc();
-    if (desc.hasDelaySlot() || desc.isBranch() || isDelayFiller(MBB,I) ||
-        desc.isCall() || desc.isReturn() || desc.isBarrier() ||
+    if (I->hasDelaySlot() || I->isBranch() || isDelayFiller(MBB,I) ||
+        I->isCall() || I->isReturn() || I->isBarrier() ||
         hasUnknownSideEffects(I))
       break;
=20
@@ -232,11 +228,11 @@
 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
   bool Changed =3D false;
   for (MachineBasicBlock::iterator I =3D MBB.begin(); I !=3D MBB.end(); ++=
I)
-    if (I->getDesc().hasDelaySlot()) {
+    if (I->hasDelaySlot()) {
       MachineBasicBlock::iterator D =3D MBB.end();
       MachineBasicBlock::iterator J =3D I;
=20
-      if (!DisableDelaySlotFiller)
+      if (!MBDisableDelaySlotFiller)
         D =3D findDelayInstr(MBB,I);
=20
       ++FilledSlots;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeELFWriterInfo.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeELFWriterInfo.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeELFWriterInfo.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -41,7 +41,6 @@
   default:
     llvm_unreachable("unknown mblaze machine relocation type");
   }
-  return 0;
 }
=20
 long int MBlazeELFWriterInfo::getDefaultAddendForRelTy(unsigned RelTy,
@@ -54,7 +53,6 @@
   default:
     llvm_unreachable("unknown mblaze relocation type");
   }
-  return 0;
 }
=20
 unsigned MBlazeELFWriterInfo::getRelocationTySize(unsigned RelTy) const {
@@ -102,10 +100,8 @@
 long int MBlazeELFWriterInfo::computeRelocation(unsigned SymOffset,
                                                 unsigned RelOffset,
                                                 unsigned RelTy) const {
-  if (RelTy =3D=3D ELF::R_MICROBLAZE_32_PCREL || ELF::R_MICROBLAZE_64_PCRE=
L)
-    return SymOffset - (RelOffset + 4);
-  else
-    assert("computeRelocation unknown for this relocation type");
-
-  return 0;
+  assert((RelTy =3D=3D ELF::R_MICROBLAZE_32_PCREL ||
+          RelTy =3D=3D ELF::R_MICROBLAZE_64_PCREL) &&
+         "computeRelocation unknown for this relocation type");
+  return SymOffset - (RelOffset + 4);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeELFWriterInfo.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeELFWriterInfo.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeELFWriterInfo.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "llvm/Target/TargetELFWriterInfo.h"
=20
 namespace llvm {
+  class TargetMachine;
=20
   class MBlazeELFWriterInfo : public TargetELFWriterInfo {
   public:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeFrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeFrameLowering.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeFrameLowering.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeFrameLowering.cpp - MBlaze Frame Information ------*- C=
++ -*-=3D=3D=3D=3D//
+//=3D=3D=3D-- MBlazeFrameLowering.cpp - MBlaze Frame Information ---------=
------=3D=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -32,13 +32,11 @@
=20
 using namespace llvm;
=20
-namespace llvm {
-  cl::opt<bool> DisableStackAdjust(
-    "disable-mblaze-stack-adjust",
-    cl::init(false),
-    cl::desc("Disable MBlaze stack layout adjustment."),
-    cl::Hidden);
-}
+static cl::opt<bool> MBDisableStackAdjust(
+  "disable-mblaze-stack-adjust",
+  cl::init(false),
+  cl::desc("Disable MBlaze stack layout adjustment."),
+  cl::Hidden);
=20
 static void replaceFrameIndexes(MachineFunction &MF,=20
                                 SmallVector<std::pair<int,int64_t>, 16> &F=
R) {
@@ -85,7 +83,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 static void analyzeFrameIndexes(MachineFunction &MF) {
-  if (DisableStackAdjust) return;
+  if (MBDisableStackAdjust) return;
=20
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
   MBlazeFunctionInfo *MBlazeFI =3D MF.getInfo<MBlazeFunctionInfo>();
@@ -213,13 +211,13 @@
=20
 static void interruptFrameLayout(MachineFunction &MF) {
   const Function *F =3D MF.getFunction();
-  llvm::CallingConv::ID CallConv =3D F->getCallingConv();
+  CallingConv::ID CallConv =3D F->getCallingConv();
=20
   // If this function is not using either the interrupt_handler
   // calling convention or the save_volatiles calling convention
   // then we don't need to do any additional frame layout.
-  if (CallConv !=3D llvm::CallingConv::MBLAZE_INTR &&
-      CallConv !=3D llvm::CallingConv::MBLAZE_SVOL)
+  if (CallConv !=3D CallingConv::MBLAZE_INTR &&
+      CallConv !=3D CallingConv::MBLAZE_SVOL)
       return;
=20
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
@@ -230,7 +228,7 @@
   // Determine if the calling convention is the interrupt_handler
   // calling convention. Some pieces of the prologue and epilogue
   // only need to be emitted if we are lowering and interrupt handler.
-  bool isIntr =3D CallConv =3D=3D llvm::CallingConv::MBLAZE_INTR;
+  bool isIntr =3D CallConv =3D=3D CallingConv::MBLAZE_INTR;
=20
   // Determine where to put prologue and epilogue additions
   MachineBasicBlock &MENT   =3D MF.front();
@@ -336,7 +334,8 @@
 // if frame pointer elimination is disabled.
 bool MBlazeFrameLowering::hasFP(const MachineFunction &MF) const {
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
-  return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects();
+  return MF.getTarget().Options.DisableFramePointerElim(MF) ||
+         MFI->hasVarSizedObjects();
 }
=20
 void MBlazeFrameLowering::emitPrologue(MachineFunction &MF) const {
@@ -348,8 +347,8 @@
   MachineBasicBlock::iterator MBBI =3D MBB.begin();
   DebugLoc DL =3D MBBI !=3D MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
=20
-  llvm::CallingConv::ID CallConv =3D MF.getFunction()->getCallingConv();
-  bool requiresRA =3D CallConv =3D=3D llvm::CallingConv::MBLAZE_INTR;
+  CallingConv::ID CallConv =3D MF.getFunction()->getCallingConv();
+  bool requiresRA =3D CallConv =3D=3D CallingConv::MBLAZE_INTR;
=20
   // Determine the correct frame layout
   determineFrameLayout(MF);
@@ -394,8 +393,8 @@
=20
   DebugLoc dl =3D MBBI->getDebugLoc();
=20
-  llvm::CallingConv::ID CallConv =3D MF.getFunction()->getCallingConv();
-  bool requiresRA =3D CallConv =3D=3D llvm::CallingConv::MBLAZE_INTR;
+  CallingConv::ID CallConv =3D MF.getFunction()->getCallingConv();
+  bool requiresRA =3D CallConv =3D=3D CallingConv::MBLAZE_INTR;
=20
   // Get the FI's where RA and FP are saved.
   int FPOffset =3D MBlazeFI->getFPStackOffset();
@@ -432,8 +431,8 @@
                                      RegScavenger *RS) const {
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
   MBlazeFunctionInfo *MBlazeFI =3D MF.getInfo<MBlazeFunctionInfo>();
-  llvm::CallingConv::ID CallConv =3D MF.getFunction()->getCallingConv();
-  bool requiresRA =3D CallConv =3D=3D llvm::CallingConv::MBLAZE_INTR;
+  CallingConv::ID CallConv =3D MF.getFunction()->getCallingConv();
+  bool requiresRA =3D CallConv =3D=3D CallingConv::MBLAZE_INTR;
=20
   if (MFI->adjustsStack() || requiresRA) {
     MBlazeFI->setRAStackOffset(0);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeFrameLowering.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeFrameLowering.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeFrameLowering.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -15,11 +15,10 @@
 #define MBLAZE_FRAMEINFO_H
=20
 #include "MBlaze.h"
-#include "MBlazeSubtarget.h"
 #include "llvm/Target/TargetFrameLowering.h"
=20
 namespace llvm {
-  class MBlazeSubtarget;
+class MBlazeSubtarget;
=20
 class MBlazeFrameLowering : public TargetFrameLowering {
 protected:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeISelLowering.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeISelLowering.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeISelLowering.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -167,7 +167,9 @@
   setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Expand);
   setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Expand);
   setOperationAction(ISD::CTLZ,               MVT::i32,   Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF,    MVT::i32,   Expand);
   setOperationAction(ISD::CTTZ,               MVT::i32,   Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF,    MVT::i32,   Expand);
   setOperationAction(ISD::CTPOP,              MVT::i32,   Expand);
   setOperationAction(ISD::BSWAP,              MVT::i32,   Expand);
=20
@@ -214,7 +216,7 @@
                                                   MachineBasicBlock *MBB)
                                                   const {
   switch (MI->getOpcode()) {
-  default: assert(false && "Unexpected instr type to insert");
+  default: llvm_unreachable("Unexpected instr type to insert");
=20
   case MBlaze::ShiftRL:
   case MBlaze::ShiftRA:
@@ -600,7 +602,6 @@
 SDValue MBlazeTargetLowering::
 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
   llvm_unreachable("TLS not implemented for MicroBlaze.");
-  return SDValue(); // Not reached
 }
=20
 SDValue MBlazeTargetLowering::
@@ -656,7 +657,7 @@
                                 CCValAssign::LocInfo &LocInfo,
                                 ISD::ArgFlagsTy &ArgFlags,
                                 CCState &State) {
-  static const unsigned ArgRegs[] =3D {
+  static const uint16_t ArgRegs[] =3D {
     MBlaze::R5, MBlaze::R6, MBlaze::R7,
     MBlaze::R8, MBlaze::R9, MBlaze::R10
   };
@@ -681,7 +682,7 @@
 /// TODO: isVarArg, isTailCall.
 SDValue MBlazeTargetLowering::
 LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
-          bool isVarArg, bool &isTailCall,
+          bool isVarArg, bool doesNotRet, bool &isTailCall,
           const SmallVectorImpl<ISD::OutputArg> &Outs,
           const SmallVectorImpl<SDValue> &OutVals,
           const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -895,7 +896,7 @@
     if (VA.isRegLoc()) {
       MVT RegVT =3D VA.getLocVT();
       ArgRegEnd =3D VA.getLocReg();
-      TargetRegisterClass *RC =3D 0;
+      const TargetRegisterClass *RC;
=20
       if (RegVT =3D=3D MVT::i32)
         RC =3D MBlaze::GPRRegisterClass;
@@ -951,7 +952,7 @@
       SDValue FIN =3D DAG.getFrameIndex(FI, getPointerTy());
       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
                                    MachinePointerInfo::getFixedStack(FI),
-                                   false, false, 0));
+                                   false, false, false, 0));
     }
   }
=20
@@ -963,7 +964,7 @@
       StackPtr =3D DAG.getRegister(StackReg, getPointerTy());
=20
     // The last register argument that must be saved is MBlaze::R10
-    TargetRegisterClass *RC =3D MBlaze::GPRRegisterClass;
+    const TargetRegisterClass *RC =3D MBlaze::GPRRegisterClass;
=20
     unsigned Begin =3D getMBlazeRegisterNumbering(MBlaze::R5);
     unsigned Start =3D getMBlazeRegisterNumbering(ArgRegEnd+1);
@@ -1045,10 +1046,10 @@
=20
   // If this function is using the interrupt_handler calling convention
   // then use "rtid r14, 0" otherwise use "rtsd r15, 8"
-  unsigned Ret =3D (CallConv =3D=3D llvm::CallingConv::MBLAZE_INTR) ? MBla=
zeISD::IRet
-                                                              : MBlazeISD:=
:Ret;
-  unsigned Reg =3D (CallConv =3D=3D llvm::CallingConv::MBLAZE_INTR) ? MBla=
ze::R14
-                                                              : MBlaze::R1=
5;
+  unsigned Ret =3D (CallConv =3D=3D CallingConv::MBLAZE_INTR) ? MBlazeISD:=
:IRet
+                                                        : MBlazeISD::Ret;
+  unsigned Reg =3D (CallConv =3D=3D CallingConv::MBLAZE_INTR) ? MBlaze::R14
+                                                        : MBlaze::R15;
   SDValue DReg =3D DAG.getRegister(Reg, MVT::i32);
=20
   if (Flag.getNode())
@@ -1079,7 +1080,6 @@
       case 'y':
       case 'f':
         return C_RegisterClass;
-        break;
     }
   }
   return TargetLowering::getConstraintType(Constraint);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeISelLowering.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeISelLowering.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeISelLowering.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,11 +15,11 @@
 #ifndef MBlazeISELLOWERING_H
 #define MBlazeISELLOWERING_H
=20
+#include "MBlaze.h"
+#include "MBlazeSubtarget.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/Target/TargetLowering.h"
-#include "MBlaze.h"
-#include "MBlazeSubtarget.h"
=20
 namespace llvm {
   namespace MBlazeCC {
@@ -134,7 +134,7 @@
     virtual SDValue
       LowerCall(SDValue Chain, SDValue Callee,
                 CallingConv::ID CallConv, bool isVarArg,
-                bool &isTailCall,
+                bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeInstrFPU.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFPU.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFPU.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeInstrFPU.td - MBlaze FPU Instruction defs -----*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeInstrFPU.td - MBlaze FPU Instruction defs ----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeInstrFSL.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFSL.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFSL.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeInstrFSL.td - MBlaze FSL Instruction defs -----*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeInstrFSL.td - MBlaze FSL Instruction defs ----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeInstrFormats.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFormats.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrFormats.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeInstrFormats.td - MB Instruction defs ---------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeInstrFormats.td - MB Instruction defs --------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -35,6 +35,7 @@
 def FRRRR   : Format<18>; // RSUB, FRSUB
 def FRI     : Format<19>; // RSUB, FRSUB
 def FC      : Format<20>; // NOP
+def FRR     : Format<21>; // CLZ
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Describe MBlaze instructions format
@@ -202,3 +203,26 @@
   let Inst{11-16} =3D flags;
   let Inst{17-31} =3D imm15;
 }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// TCLZ instruction class in MBlaze : <|opcode|rd|imm15|>
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+class TCLZ<bits<6> op, bits<16> flags, dag outs, dag ins, string asmstr,
+           list<dag> pattern, InstrItinClass itin> :
+           MBlazeInst<op, FRR, outs, ins, asmstr, pattern, itin> {
+  bits<5>  rd;
+  bits<5>  ra;
+
+  let Inst{6-10}  =3D rd;
+  let Inst{11-15}  =3D ra;
+  let Inst{16-31}  =3D flags;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// MBAR instruction class in MBlaze : <|opcode|rd|imm15|>
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+class MBAR<bits<6> op, bits<26> flags, dag outs, dag ins, string asmstr,
+           list<dag> pattern, InstrItinClass itin> :
+           MBlazeInst<op, FC, outs, ins, asmstr, pattern, itin> {
+  let Inst{6-31}  =3D flags;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeInstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeInstrInfo.cpp - MBlaze Instruction Information -----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeInstrInfo.cpp - MBlaze Instruction Information -------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeInstrInfo.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeInstrInfo.h - MBlaze Instruction Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeInstrInfo.h - MBlaze Instruction Information ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,9 +15,9 @@
 #define MBLAZEINSTRUCTIONINFO_H
=20
 #include "MBlaze.h"
+#include "MBlazeRegisterInfo.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "MBlazeRegisterInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "MBlazeGenInstrInfo.inc"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeInstrInfo.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeInstrInfo.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeInstrInfo.td - MBlaze Instruction defs --------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeInstrInfo.td - MBlaze Instruction defs -------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -594,9 +594,18 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 let neverHasSideEffects =3D 1 in {
-  def NOP :  MBlazeInst< 0x20, FC, (outs), (ins), "nop    ", [], IIC_ALU>;
+  def NOP :  MBlazeInst<0x20, FC, (outs), (ins), "nop    ", [], IIC_ALU>;
 }
=20
+let Predicates=3D[HasPatCmp] in {
+  def CLZ :  TCLZ<0x24, 0x00E0, (outs GPR:$dst), (ins GPR:$src),
+                  "clz    $dst, $src", [], IIC_ALU>;
+}
+
+def IMEMBAR  : MBAR<0x2E, 0x0420004, (outs), (ins), "mbar   2", [], IIC_AL=
U>;
+def DMEMBAR  : MBAR<0x2E, 0x0220004, (outs), (ins), "mbar   1", [], IIC_AL=
U>;
+def IDMEMBAR : MBAR<0x2E, 0x0020004, (outs), (ins), "mbar   0", [], IIC_AL=
U>;
+
 let usesCustomInserter =3D 1 in {
   def Select_CC : MBlazePseudo<(outs GPR:$dst),
     (ins GPR:$T, GPR:$F, GPR:$CMP, i32imm:$CC), // F T reversed
@@ -751,6 +760,56 @@
 def : Pat<(srl GPR:$L, GPR:$R), (ShiftRL GPR:$L, GPR:$R)>;
=20
 // SET_CC operations
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETEQ),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$L, 1)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETNE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$L, 2)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETGT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$L, 3)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETLT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$L, 4)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETGE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$L, 5)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETLE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$L, 6)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETUGT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU (i32 R0), GPR:$L), 3)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETULT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU (i32 R0), GPR:$L), 4)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETUGE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU (i32 R0), GPR:$L), 5)>;
+def : Pat<(setcc (i32 GPR:$L), (i32 0), SETULE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU (i32 R0), GPR:$L), 6)>;
+
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETEQ),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$R, 1)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETNE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$R, 2)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETGT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$R, 3)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETLT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$R, 4)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETGE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$R, 5)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETLE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0), GPR:$R, 6)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETUGT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU GPR:$R, (i32 R0)), 3)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETULT),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU GPR:$R, (i32 R0)), 4)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETUGE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU GPR:$R, (i32 R0)), 5)>;
+def : Pat<(setcc (i32 0), (i32 GPR:$R), SETULE),
+          (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
+                     (CMPU GPR:$R, (i32 R0)), 6)>;
+
 def : Pat<(setcc (i32 GPR:$L), (i32 GPR:$R), SETEQ),
           (Select_CC (ADDIK (i32 R0), 1), (ADDIK (i32 R0), 0),
                      (CMP GPR:$R, GPR:$L), 1)>;
@@ -787,6 +846,68 @@
           (Select_CC GPR:$T, GPR:$F, GPR:$C, 2)>;
=20
 // SELECT_CC
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETEQ),
+          (Select_CC GPR:$T, GPR:$F, GPR:$L, 1)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETNE),
+          (Select_CC GPR:$T, GPR:$F, GPR:$L, 2)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETGT),
+          (Select_CC GPR:$T, GPR:$F, GPR:$L, 3)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETLT),
+          (Select_CC GPR:$T, GPR:$F, GPR:$L, 4)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETGE),
+          (Select_CC GPR:$T, GPR:$F, GPR:$L, 5)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETLE),
+          (Select_CC GPR:$T, GPR:$F, GPR:$L, 6)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETUGT),
+          (Select_CC GPR:$T, GPR:$F, (CMPU (i32 R0), GPR:$L), 3)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETULT),
+          (Select_CC GPR:$T, GPR:$F, (CMPU (i32 R0), GPR:$L), 4)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETUGE),
+          (Select_CC GPR:$T, GPR:$F, (CMPU (i32 R0), GPR:$L), 5)>;
+def : Pat<(selectcc (i32 GPR:$L), (i32 0),
+                    (i32 GPR:$T), (i32 GPR:$F), SETULE),
+          (Select_CC GPR:$T, GPR:$F, (CMPU (i32 R0), GPR:$L), 6)>;
+
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETEQ),
+          (Select_CC GPR:$T, GPR:$F, GPR:$R, 1)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETNE),
+          (Select_CC GPR:$T, GPR:$F, GPR:$R, 2)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETGT),
+          (Select_CC GPR:$T, GPR:$F, GPR:$R, 3)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETLT),
+          (Select_CC GPR:$T, GPR:$F, GPR:$R, 4)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETGE),
+          (Select_CC GPR:$T, GPR:$F, GPR:$R, 5)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETLE),
+          (Select_CC GPR:$T, GPR:$F, GPR:$R, 6)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETUGT),
+          (Select_CC GPR:$T, GPR:$F, (CMPU GPR:$R, (i32 R0)), 3)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETULT),
+          (Select_CC GPR:$T, GPR:$F, (CMPU GPR:$R, (i32 R0)), 4)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETUGE),
+          (Select_CC GPR:$T, GPR:$F, (CMPU GPR:$R, (i32 R0)), 5)>;
+def : Pat<(selectcc (i32 0), (i32 GPR:$R),
+                    (i32 GPR:$T), (i32 GPR:$F), SETULE),
+          (Select_CC GPR:$T, GPR:$F, (CMPU GPR:$R, (i32 R0)), 6)>;
+
 def : Pat<(selectcc (i32 GPR:$L), (i32 GPR:$R),
                     (i32 GPR:$T), (i32 GPR:$F), SETEQ),
           (Select_CC GPR:$T, GPR:$F, (CMP GPR:$R, GPR:$L), 1)>;
@@ -827,6 +948,48 @@
 def : Pat<(brind GPR:$T), (BRAD GPR:$T)>;
=20
 // BRCOND instructions
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETEQ), bb:$T),
+          (BEQID GPR:$L, bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETNE), bb:$T),
+          (BNEID GPR:$L, bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETGT), bb:$T),
+          (BGTID GPR:$L, bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETLT), bb:$T),
+          (BLTID GPR:$L, bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETGE), bb:$T),
+          (BGEID GPR:$L, bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETLE), bb:$T),
+          (BLEID GPR:$L, bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETUGT), bb:$T),
+          (BGTID (CMPU (i32 R0), GPR:$L), bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETULT), bb:$T),
+          (BLTID (CMPU (i32 R0), GPR:$L), bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETUGE), bb:$T),
+          (BGEID (CMPU (i32 R0), GPR:$L), bb:$T)>;
+def : Pat<(brcond (setcc (i32 GPR:$L), (i32 0), SETULE), bb:$T),
+          (BLEID (CMPU (i32 R0), GPR:$L), bb:$T)>;
+
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETEQ), bb:$T),
+          (BEQID GPR:$R, bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETNE), bb:$T),
+          (BNEID GPR:$R, bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETGT), bb:$T),
+          (BGTID GPR:$R, bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETLT), bb:$T),
+          (BLTID GPR:$R, bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETGE), bb:$T),
+          (BGEID GPR:$R, bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETLE), bb:$T),
+          (BLEID GPR:$R, bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETUGT), bb:$T),
+          (BGTID (CMPU GPR:$R, (i32 R0)), bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETULT), bb:$T),
+          (BLTID (CMPU GPR:$R, (i32 R0)), bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETUGE), bb:$T),
+          (BGEID (CMPU GPR:$R, (i32 R0)), bb:$T)>;
+def : Pat<(brcond (setcc (i32 0), (i32 GPR:$R), SETULE), bb:$T),
+          (BLEID (CMPU GPR:$R, (i32 R0)), bb:$T)>;
+
 def : Pat<(brcond (setcc (i32 GPR:$L), (i32 GPR:$R), SETEQ), bb:$T),
           (BEQID (CMP GPR:$R, GPR:$L), bb:$T)>;
 def : Pat<(brcond (setcc (i32 GPR:$L), (i32 GPR:$R), SETNE), bb:$T),
@@ -869,11 +1032,11 @@
 def : Pat<(load xaddr:$addr), (i32 (LW xaddr:$addr))>;
=20
 // 16-bit load and store
-def : Pat<(truncstorei16 (i32 GPR:$dst), xaddr:$addr), (SH GPR:$dst, xaddr=
:$addr)>;
+def : Pat<(truncstorei16 (i32 GPR:$dst), xaddr:$ad), (SH GPR:$dst, xaddr:$=
ad)>;
 def : Pat<(zextloadi16 xaddr:$addr), (i32 (LHU xaddr:$addr))>;
=20
 // 8-bit load and store
-def : Pat<(truncstorei8 (i32 GPR:$dst), xaddr:$addr), (SB GPR:$dst, xaddr:=
$addr)>;
+def : Pat<(truncstorei8 (i32 GPR:$dst), xaddr:$ad), (SB GPR:$dst, xaddr:$a=
d)>;
 def : Pat<(zextloadi8 xaddr:$addr), (i32 (LBU xaddr:$addr))>;
=20
 // Peepholes
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeIntrinsicInfo.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsicInfo.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsicInfo.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeIntrinsicInfo.cpp - Intrinsic Information -00-------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeIntrinsicInfo.cpp - Intrinsic Information ------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,6 +18,7 @@
 #include "llvm/Module.h"
 #include "llvm/Type.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cstring>
=20
 using namespace llvm;
@@ -73,16 +74,13 @@
 }
=20
 bool MBlazeIntrinsicInfo::isOverloaded(unsigned IntrID) const {
-  // Overload Table
-  const bool OTable[] =3D {
+  if (IntrID =3D=3D 0)
+    return false;
+
+  unsigned id =3D IntrID - Intrinsic::num_intrinsics + 1;
 #define GET_INTRINSIC_OVERLOAD_TABLE
 #include "MBlazeGenIntrinsics.inc"
 #undef GET_INTRINSIC_OVERLOAD_TABLE
-  };
-  if (IntrID =3D=3D 0)
-    return false;
-  else
-    return OTable[IntrID - Intrinsic::num_intrinsics];
 }
=20
 /// This defines the "getAttributes(ID id)" method.
@@ -92,7 +90,7 @@
=20
 static FunctionType *getType(LLVMContext &Context, unsigned id) {
   Type *ResultTy =3D NULL;
-  std::vector<Type*> ArgTys;
+  SmallVector<Type*, 8> ArgTys;
   bool IsVarArg =3D false;
=20
 #define GET_INTRINSIC_GENERATOR
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeIntrinsicInfo.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsicInfo.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsicInfo.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeIntrinsicInfo.h - MBlaze Intrinsic Information -----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeIntrinsicInfo.h - MBlaze Intrinsic Information ----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeIntrinsics.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsics.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeIntrinsics.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- IntrinsicsMBlaze.td - Defines MBlaze intrinsics -----*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- IntrinsicsMBlaze.td - Defines MBlaze intrinsics ----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeMCInstLower.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeMCInstLower.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeMCInstLower.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MBLazeMCInstLower.cpp - Convert MBlaze MachineInstr to an MC=
Inst---=3D=3D=3D//
+//=3D=3D=3D-- MBlazeMCInstLower.cpp - Convert MBlaze MachineInstr to an MC=
Inst---=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -85,9 +85,7 @@
 MCSymbol *MBlazeMCInstLower::
 GetBlockAddressSymbol(const MachineOperand &MO) const {
   switch (MO.getTargetFlags()) {
-  default:
-      assert(0 && "Unknown target flag on GV operand");
-
+  default: llvm_unreachable("Unknown target flag on GV operand");
   case 0: break;
   }
=20
@@ -150,7 +148,7 @@
     case MachineOperand::MO_BlockAddress:
       MCOp =3D LowerSymbolOperand(MO, GetBlockAddressSymbol(MO));
       break;
-    case MachineOperand::MO_FPImmediate:
+    case MachineOperand::MO_FPImmediate: {
       bool ignored;
       APFloat FVal =3D MO.getFPImm()->getValueAPF();
       FVal.convert(APFloat::IEEEsingle, APFloat::rmTowardZero, &ignored);
@@ -160,6 +158,9 @@
       MCOp =3D MCOperand::CreateImm(Val);
       break;
     }
+    case MachineOperand::MO_RegisterMask:
+      continue;
+    }
=20
     OutMI.addOperand(MCOp);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeMCInstLower.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeMCInstLower.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeMCInstLower.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MBlazeMCInstLower.h - Lower MachineInstr to MCInst ---------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MBlazeMCInstLower.h - Lower MachineInstr to MCInst ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,7 +14,6 @@
=20
 namespace llvm {
   class AsmPrinter;
-  class MCAsmInfo;
   class MCContext;
   class MCInst;
   class MCOperand;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeMachineFunction.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeMachineFunction.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeMachineFunction.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MBlazeMachineFunctionInfo.h - Private data ----------------*=
- C++ -*-=3D//
+//=3D=3D=3D-- MBlazeMachineFunctionInfo.h - Private data --------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -16,7 +16,6 @@
=20
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/VectorExtras.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
=20
@@ -25,8 +24,8 @@
 /// MBlazeFunctionInfo - This class is derived from MachineFunction private
 /// MBlaze target-specific information for each MachineFunction.
 class MBlazeFunctionInfo : public MachineFunctionInfo {
+  virtual void anchor();
=20
-private:
   /// Holds for each function where on the stack the Frame Pointer must be
   /// saved. This is used on Prologue and Epilogue to emit FP save/restore
   int FPStackOffset;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeRegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeRegisterInfo.cpp - MBlaze Register Information -=3D=3D =
-*- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeRegisterInfo.cpp - MBlaze Register Information -------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,9 +14,9 @@
=20
 #define DEBUG_TYPE "mblaze-frame-info"
=20
+#include "MBlazeRegisterInfo.h"
 #include "MBlaze.h"
 #include "MBlazeSubtarget.h"
-#include "MBlazeRegisterInfo.h"
 #include "MBlazeMachineFunction.h"
 #include "llvm/Constants.h"
 #include "llvm/Type.h"
@@ -54,10 +54,10 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 /// MBlaze Callee Saved Registers
-const unsigned* MBlazeRegisterInfo::
+const uint16_t* MBlazeRegisterInfo::
 getCalleeSavedRegs(const MachineFunction *MF) const {
   // MBlaze callee-save register range is R20 - R31
-  static const unsigned CalleeSavedRegs[] =3D {
+  static const uint16_t CalleeSavedRegs[] =3D {
     MBlaze::R20, MBlaze::R21, MBlaze::R22, MBlaze::R23,
     MBlaze::R24, MBlaze::R25, MBlaze::R26, MBlaze::R27,
     MBlaze::R28, MBlaze::R29, MBlaze::R30, MBlaze::R31,
@@ -184,10 +184,8 @@
=20
 unsigned MBlazeRegisterInfo::getEHExceptionRegister() const {
   llvm_unreachable("What is the exception register");
-  return 0;
 }
=20
 unsigned MBlazeRegisterInfo::getEHHandlerRegister() const {
   llvm_unreachable("What is the exception handler register");
-  return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeRegisterInfo.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeRegisterInfo.h - MBlaze Register Information Impl --*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeRegisterInfo.h - MBlaze Register Information Impl -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -46,7 +46,7 @@
   static unsigned getPICCallReg();
=20
   /// Code Generation virtual methods...
-  const unsigned *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
=20
   BitVector getReservedRegs(const MachineFunction &MF) const;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeRegisterInfo.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeRegisterInfo.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeRegisterInfo.td - MBlaze Register defs --------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeRegisterInfo.td - MBlaze Register defs -------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeRelocations.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeRelocations.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeRelocations.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeRelocations.h - MBlaze Code Relocations ------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeRelocations.h - MBlaze Code Relocations -----------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeSchedule.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeSchedule.td - MBlaze Scheduling Definitions ---*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeSchedule.td - MBlaze Scheduling Definitions --*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeSchedule3.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule3.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule3.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeSchedule3.td - MBlaze Scheduling Definitions --*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeSchedule3.td - MBlaze Scheduling Definitions -*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeSchedule5.td
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule5.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeSchedule5.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeSchedule5.td - MBlaze Scheduling Definitions --*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeSchedule5.td - MBlaze Scheduling Definitions -*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeSubtarget.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeSubtarget.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeSubtarget.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MBlazeSubtarget.cpp - MBlaze Subtarget Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeSubtarget.cpp - MBlaze Subtarget Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeSubtarget.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeSubtarget.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeSubtarget.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- MBlazeSubtarget.h - Define Subtarget for the MBlaze -*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- MBlazeSubtarget.h - Define Subtarget for the MBlaze ----*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeTargetMachine.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeTargetMachine.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeTargetMachine.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "MBlazeTargetMachine.h"
 #include "MBlaze.h"
-#include "MBlazeTargetMachine.h"
 #include "llvm/PassManager.h"
 #include "llvm/CodeGen/Passes.h"
 #include "llvm/Support/FormattedStream.h"
@@ -33,30 +33,49 @@
 // an easier handling.
 MBlazeTargetMachine::
 MBlazeTargetMachine(const Target &T, StringRef TT,
-                    StringRef CPU, StringRef FS,
-                    Reloc::Model RM, CodeModel::Model CM):
-  LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
-  Subtarget(TT, CPU, FS),
-  DataLayout("E-p:32:32:32-i8:8:8-i16:16:16"),
-  InstrInfo(*this),
-  FrameLowering(Subtarget),
-  TLInfo(*this), TSInfo(*this), ELFWriterInfo(*this),
-  InstrItins(Subtarget.getInstrItineraryData()) {
+                    StringRef CPU, StringRef FS, const TargetOptions &Opti=
ons,
+                    Reloc::Model RM, CodeModel::Model CM,
+                    CodeGenOpt::Level OL)
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
+    Subtarget(TT, CPU, FS),
+    DataLayout("E-p:32:32:32-i8:8:8-i16:16:16"),
+    InstrInfo(*this),
+    FrameLowering(Subtarget),
+    TLInfo(*this), TSInfo(*this), ELFWriterInfo(*this),
+    InstrItins(Subtarget.getInstrItineraryData()) {
+}
+
+namespace {
+/// MBlaze Code Generator Pass Configuration Options.
+class MBlazePassConfig : public TargetPassConfig {
+public:
+  MBlazePassConfig(MBlazeTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  MBlazeTargetMachine &getMBlazeTargetMachine() const {
+    return getTM<MBlazeTargetMachine>();
+  }
+
+  virtual bool addInstSelector();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *MBlazeTargetMachine::createPassConfig(PassManagerBase &P=
M) {
+  return new MBlazePassConfig(this, PM);
 }
=20
 // Install an instruction selector pass using
 // the ISelDag to gen MBlaze code.
-bool MBlazeTargetMachine::addInstSelector(PassManagerBase &PM,
-                                          CodeGenOpt::Level OptLevel) {
-  PM.add(createMBlazeISelDag(*this));
+bool MBlazePassConfig::addInstSelector() {
+  PM.add(createMBlazeISelDag(getMBlazeTargetMachine()));
   return false;
 }
=20
 // Implemented by targets that want to run passes immediately before
 // machine code is emitted. return true if -print-machineinstrs should
 // print out the code after the passes.
-bool MBlazeTargetMachine::addPreEmitPass(PassManagerBase &PM,
-                                         CodeGenOpt::Level OptLevel) {
-  PM.add(createMBlazeDelaySlotFillerPass(*this));
+bool MBlazePassConfig::addPreEmitPass() {
+  PM.add(createMBlazeDelaySlotFillerPass(getMBlazeTargetMachine()));
   return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MB=
lazeTargetMachine.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MBlazeTargetMachine.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MBlazeTargetMachine.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MBlazeTargetMachine.h - Define TargetMachine for MBlaze --- =
C++ ---=3D=3D=3D//
+//=3D=3D=3D-- MBlazeTargetMachine.h - Define TargetMachine for MBlaze -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -43,7 +43,9 @@
   public:
     MBlazeTargetMachine(const Target &T, StringRef TT,
                         StringRef CPU, StringRef FS,
-                        Reloc::Model RM, CodeModel::Model CM);
+                        const TargetOptions &Options,
+                        Reloc::Model RM, CodeModel::Model CM,
+                        CodeGenOpt::Level OL);
=20
     virtual const MBlazeInstrInfo *getInstrInfo() const
     { return &InstrInfo; }
@@ -77,8 +79,7 @@
     }
=20
     // Pass Pipeline Configuration
-    virtual bool addInstSelector(PassManagerBase &PM, CodeGenOpt::Level Op=
t);
-    virtual bool addPreEmitPass(PassManagerBase &PM,CodeGenOpt::Level Opt);
+    virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
   };
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MC=
TargetDesc/MBlazeAsmBackend.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeAsmBackend.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeAsmBackend.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
=20
 static unsigned getFixupKindSize(unsigned Kind) {
   switch (Kind) {
-  default: assert(0 && "invalid fixup kind!");
+  default: llvm_unreachable("invalid fixup kind!");
   case FK_Data_1: return 1;
   case FK_PCRel_2:
   case FK_Data_2: return 2;
@@ -39,12 +39,6 @@
=20
=20
 namespace {
-class MBlazeELFObjectWriter : public MCELFObjectTargetWriter {
-public:
-  MBlazeELFObjectWriter(Triple::OSType OSType)
-    : MCELFObjectTargetWriter(/*is64Bit*/ false, OSType, ELF::EM_MBLAZE,
-                              /*HasRelocationAddend*/ true) {}
-};
=20
 class MBlazeAsmBackend : public MCAsmBackend {
 public:
@@ -56,11 +50,16 @@
     return 2;
   }
=20
-  bool MayNeedRelaxation(const MCInst &Inst) const;
+  bool mayNeedRelaxation(const MCInst &Inst) const;
=20
-  void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
+  bool fixupNeedsRelaxation(const MCFixup &Fixup,
+                            uint64_t Value,
+                            const MCInstFragment *DF,
+                            const MCAsmLayout &Layout) const;
=20
-  bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
+  void relaxInstruction(const MCInst &Inst, MCInst &Res) const;
+
+  bool writeNopData(uint64_t Count, MCObjectWriter *OW) const;
=20
   unsigned getPointerSize() const {
     return 4;
@@ -76,7 +75,7 @@
     }
 }
=20
-bool MBlazeAsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
+bool MBlazeAsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
   if (getRelaxedOpcode(Inst.getOpcode()) =3D=3D Inst.getOpcode())
     return false;
=20
@@ -87,12 +86,24 @@
   return hasExprOrImm;
 }
=20
-void MBlazeAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) c=
onst {
+bool MBlazeAsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
+                                            uint64_t Value,
+                                            const MCInstFragment *DF,
+                                            const MCAsmLayout &Layout) con=
st {
+  // FIXME: Is this right? It's what the "generic" code was doing before,
+  // but is X86 specific. Is it actually true for MBlaze also, or was it
+  // just close enough to not be a big deal?
+  //
+  // Relax if the value is too big for a (signed) i8.
+  return int64_t(Value) !=3D int64_t(int8_t(Value));
+}
+
+void MBlazeAsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) c=
onst {
   Res =3D Inst;
   Res.setOpcode(getRelaxedOpcode(Inst.getOpcode()));
 }
=20
-bool MBlazeAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) co=
nst {
+bool MBlazeAsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) co=
nst {
   if ((Count % 4) !=3D 0)
     return false;
=20
@@ -106,20 +117,19 @@
 namespace {
 class ELFMBlazeAsmBackend : public MBlazeAsmBackend {
 public:
-  Triple::OSType OSType;
-  ELFMBlazeAsmBackend(const Target &T, Triple::OSType _OSType)
-    : MBlazeAsmBackend(T), OSType(_OSType) { }
+  uint8_t OSABI;
+  ELFMBlazeAsmBackend(const Target &T, uint8_t _OSABI)
+    : MBlazeAsmBackend(T), OSABI(_OSABI) { }
=20
-  void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+  void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
                   uint64_t Value) const;
=20
   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
-    return createELFObjectWriter(new MBlazeELFObjectWriter(OSType), OS,
-                                 /*IsLittleEndian*/ false);
+    return createMBlazeELFObjectWriter(OS, OSABI);
   }
 };
=20
-void ELFMBlazeAsmBackend::ApplyFixup(const MCFixup &Fixup, char *Data,
+void ELFMBlazeAsmBackend::applyFixup(const MCFixup &Fixup, char *Data,
                                      unsigned DataSize, uint64_t Value) co=
nst {
   unsigned Size =3D getFixupKindSize(Fixup.getKind());
=20
@@ -155,5 +165,6 @@
   if (TheTriple.isOSWindows())
     assert(0 && "Windows not supported on MBlaze");
=20
-  return new ELFMBlazeAsmBackend(T, TheTriple.getOS());
+  uint8_t OSABI =3D MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
+  return new ELFMBlazeAsmBackend(T, OSABI);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MC=
TargetDesc/MBlazeBaseInfo.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeBaseInfo.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeBaseInfo.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -51,6 +51,7 @@
     FRRRR,
     FRI,
     FC,
+    FRR,
     FormMask =3D 63
=20
     //=3D=3D=3D-----------------------------------------------------------=
-------=3D=3D=3D//
@@ -95,7 +96,6 @@
     default:
       return false;
   }
-  return false; // Not reached
 }
=20
 /// getMBlazeRegisterNumbering - Given the enum value for some register, e=
.g.
@@ -160,7 +160,6 @@
     case MBlaze::RPVR11 : return 0x200B;
     default: llvm_unreachable("Unknown register number!");
   }
-  return 0; // Not reached
 }
=20
 /// getRegisterFromNumbering - Given the enum value for some register, e.g.
@@ -201,7 +200,6 @@
     case 31 : return MBlaze::R31;
     default: llvm_unreachable("Unknown register number!");
   }
-  return 0; // Not reached
 }
=20
 static inline unsigned getSpecialMBlazeRegisterFromNumbering(unsigned Reg)=
 {
@@ -232,7 +230,6 @@
     case 0x200B : return MBlaze::RPVR11;
     default: llvm_unreachable("Unknown register number!");
   }
-  return 0; // Not reached
 }
=20
 } // end namespace llvm;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MC=
TargetDesc/MBlazeMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,8 @@
 #include "MBlazeMCAsmInfo.h"
 using namespace llvm;
=20
+void MBlazeMCAsmInfo::anchor() { }
+
 MBlazeMCAsmInfo::MBlazeMCAsmInfo() {
   IsLittleEndian              =3D false;
   StackGrowsUp                =3D false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MC=
TargetDesc/MBlazeMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCAsmInfo.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- MBlazeMCAsmInfo.h - MBlaze asm properties -----------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- MBlazeMCAsmInfo.h - MBlaze asm properties --------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,13 +14,13 @@
 #ifndef MBLAZETARGETASMINFO_H
 #define MBLAZETARGETASMINFO_H
=20
-#include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MCAsmInfo.h"
=20
 namespace llvm {
   class Target;
=20
   class MBlazeMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
   public:
     explicit MBlazeMCAsmInfo();
   };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MC=
TargetDesc/MBlazeMCCodeEmitter.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCCodeEmitter.=
cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCCodeEmitter.=
cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -43,7 +43,7 @@
=20
   // getBinaryCodeForInstr - TableGen'erated function for getting the
   // binary encoding for an instruction.
-  unsigned getBinaryCodeForInstr(const MCInst &MI) const;
+  uint64_t getBinaryCodeForInstr(const MCInst &MI) const;
=20
   /// getMachineOpValue - Return binary encoding of operand. If the machine
   /// operand requires relocation, record the relocation and return zero.
@@ -54,8 +54,8 @@
=20
   static unsigned GetMBlazeRegNum(const MCOperand &MO) {
     // FIXME: getMBlazeRegisterNumbering() is sufficient?
-    assert(0 && "MBlazeMCCodeEmitter::GetMBlazeRegNum() not yet implemente=
d.");
-    return 0;
+    llvm_unreachable("MBlazeMCCodeEmitter::GetMBlazeRegNum() not yet "
+                     "implemented.");
   }
=20
   void EmitByte(unsigned char C, unsigned &CurByte, raw_ostream &OS) const=
 {
@@ -109,17 +109,14 @@
                                              const MCOperand &MO) const {
   if (MO.isReg())
     return getMBlazeRegisterNumbering(MO.getReg());
-  else if (MO.isImm())
+  if (MO.isImm())
     return static_cast<unsigned>(MO.getImm());
-  else if (MO.isExpr())
-      return 0; // The relocation has already been recorded at this point.
-  else {
+  if (MO.isExpr())
+    return 0; // The relocation has already been recorded at this point.
 #ifndef NDEBUG
-    errs() << MO;
+  errs() << MO;
 #endif
-    llvm_unreachable(0);
-  }
-  return 0;
+  llvm_unreachable(0);
 }
=20
 void MBlazeMCCodeEmitter::
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MC=
TargetDesc/MBlazeMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MBlazeMCTargetDesc.cpp - MBlaze Target Descriptions -----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MBlazeMCTargetDesc.cpp - MBlaze Target Descriptions --------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -62,13 +62,14 @@
 }
=20
 static MCCodeGenInfo *createMBlazeMCCodeGenInfo(StringRef TT, Reloc::Model=
 RM,
-                                                CodeModel::Model CM) {
+                                                CodeModel::Model CM,
+                                                CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
   if (RM =3D=3D Reloc::Default)
     RM =3D Reloc::Static;
   if (CM =3D=3D CodeModel::Default)
     CM =3D CodeModel::Small;
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
@@ -82,12 +83,10 @@
=20
   if (TheTriple.isOSDarwin()) {
     llvm_unreachable("MBlaze does not support Darwin MACH-O format");
-    return NULL;
   }
=20
   if (TheTriple.isOSWindows()) {
     llvm_unreachable("MBlaze does not support Windows COFF format");
-    return NULL;
   }
=20
   return createELFStreamer(Ctx, MAB, _OS, _Emitter, RelaxAll, NoExecStack);
@@ -96,9 +95,11 @@
 static MCInstPrinter *createMBlazeMCInstPrinter(const Target &T,
                                                 unsigned SyntaxVariant,
                                                 const MCAsmInfo &MAI,
+                                                const MCInstrInfo &MII,
+                                                const MCRegisterInfo &MRI,
                                                 const MCSubtargetInfo &STI=
) {
   if (SyntaxVariant =3D=3D 0)
-    return new MBlazeInstPrinter(MAI);
+    return new MBlazeInstPrinter(MAI, MII, MRI);
   return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MBlaze/MC=
TargetDesc/MBlazeMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MBlaze/MCTargetDesc/MBlazeMCTargetDesc.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -14,24 +14,28 @@
 #ifndef MBLAZEMCTARGETDESC_H
 #define MBLAZEMCTARGETDESC_H
=20
+#include "llvm/Support/DataTypes.h"
+
 namespace llvm {
 class MCAsmBackend;
 class MCContext;
 class MCCodeEmitter;
 class MCInstrInfo;
+class MCObjectWriter;
 class MCSubtargetInfo;
 class Target;
 class StringRef;
-class formatted_raw_ostream;
+class raw_ostream;
=20
 extern Target TheMBlazeTarget;
=20
 MCCodeEmitter *createMBlazeMCCodeEmitter(const MCInstrInfo &MCII,
                                          const MCSubtargetInfo &STI,
                                          MCContext &Ctx);
- =20
+
 MCAsmBackend *createMBlazeAsmBackend(const Target &T, StringRef TT);
=20
+MCObjectWriter *createMBlazeELFObjectWriter(raw_ostream &OS, uint8_t OSABI=
);
 } // End llvm namespace
=20
 // Defines symbolic names for MBlaze registers.  This defines a mapping fr=
om
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/In=
stPrinter/MSP430InstPrinter.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/InstPrinter/MSP430InstPrinter.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/InstPrinter/MSP430InstPrinter.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -92,7 +92,6 @@
   switch (CC) {
   default:
    llvm_unreachable("Unsupported CC code");
-   break;
   case MSP430CC::COND_E:
    O << "eq";
    break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/In=
stPrinter/MSP430InstPrinter.h
--- a/head/contrib/llvm/lib/Target/MSP430/InstPrinter/MSP430InstPrinter.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/InstPrinter/MSP430InstPrinter.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MSP430InstPrinter.h - Convert MSP430 MCInst to assembly synt=
ax ----=3D=3D=3D//
+//=3D MSP430InstPrinter.h - Convert MSP430 MCInst to assembly syntax -*- C=
++ -*-//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -21,8 +21,9 @@
=20
   class MSP430InstPrinter : public MCInstPrinter {
   public:
-    MSP430InstPrinter(const MCAsmInfo &MAI)
-        : MCInstPrinter(MAI) {}
+    MSP430InstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                      const MCRegisterInfo &MRI)
+      : MCInstPrinter(MAI, MII, MRI) {}
=20
     virtual void printInst(const MCInst *MI, raw_ostream &O, StringRef Ann=
ot);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MC=
TargetDesc/MSP430MCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -12,8 +12,11 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "MSP430MCAsmInfo.h"
+#include "llvm/ADT/StringRef.h"
 using namespace llvm;
=20
+void MSP430MCAsmInfo::anchor() { }
+
 MSP430MCAsmInfo::MSP430MCAsmInfo(const Target &T, StringRef TT) {
   PointerSize =3D 2;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MC=
TargetDesc/MSP430MCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCAsmInfo.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- MSP430MCAsmInfo.h - MSP430 asm properties -----------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- MSP430MCAsmInfo.h - MSP430 asm properties --------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,13 +14,15 @@
 #ifndef MSP430TARGETASMINFO_H
 #define MSP430TARGETASMINFO_H
=20
-#include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MCAsmInfo.h"
=20
 namespace llvm {
+  class StringRef;
   class Target;
=20
-  struct MSP430MCAsmInfo : public MCAsmInfo {
+  class MSP430MCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit MSP430MCAsmInfo(const Target &T, StringRef TT);
   };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MC=
TargetDesc/MSP430MCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MSP430MCTargetDesc.cpp - MSP430 Target Descriptions -----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MSP430MCTargetDesc.cpp - MSP430 Target Descriptions --------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -51,18 +51,21 @@
 }
=20
 static MCCodeGenInfo *createMSP430MCCodeGenInfo(StringRef TT, Reloc::Model=
 RM,
-                                                CodeModel::Model CM) {
+                                                CodeModel::Model CM,
+                                                CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
 static MCInstPrinter *createMSP430MCInstPrinter(const Target &T,
                                                 unsigned SyntaxVariant,
                                                 const MCAsmInfo &MAI,
+                                                const MCInstrInfo &MII,
+                                                const MCRegisterInfo &MRI,
                                                 const MCSubtargetInfo &STI=
) {
   if (SyntaxVariant =3D=3D 0)
-    return new MSP430InstPrinter(MAI);
+    return new MSP430InstPrinter(MAI, MII, MRI);
   return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MC=
TargetDesc/MSP430MCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MCTargetDesc/MSP430MCTargetDesc.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,7 @@
 #define MSP430MCTARGETDESC_H
=20
 namespace llvm {
-class MCSubtargetInfo;
 class Target;
-class StringRef;
=20
 extern Target TheMSP430Target;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430.td
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430.td	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430.td	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430.td - Describe the MSP430 Target Machine ---------*- tb=
lgen -*-=3D=3D//
+//=3D=3D=3D-- MSP430.td - Describe the MSP430 Target Machine -----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430AsmPrinter.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430AsmPrinter.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430AsmPrinter.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -65,7 +65,7 @@
                                     raw_ostream &O, const char *Modifier) {
   const MachineOperand &MO =3D MI->getOperand(OpNum);
   switch (MO.getType()) {
-  default: assert(0 && "Not implemented yet!");
+  default: llvm_unreachable("Not implemented yet!");
   case MachineOperand::MO_Register:
     O << MSP430InstPrinter::getRegisterName(MO.getReg());
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430BranchSelector.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430BranchSelector.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430BranchSelector.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MSP430BranchSelector.cpp - Emit long conditional branches--*=
- C++ -*-=3D//
+//=3D=3D=3D-- MSP430BranchSelector.cpp - Emit long conditional branches --=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430FrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430FrameLowering.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D=3D-- MSP430FrameLowering.cpp - MSP430 Frame Information =
-------=3D=3D=3D=3D=3D=3D=3D=3D=3D//
+//=3D=3D=3D-- MSP430FrameLowering.cpp - MSP430 Frame Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -29,7 +29,7 @@
 bool MSP430FrameLowering::hasFP(const MachineFunction &MF) const {
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
=20
-  return (DisableFramePointerElim(MF) ||
+  return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
           MF.getFrameInfo()->hasVarSizedObjects() ||
           MFI->isFrameAddressTaken());
 }
@@ -140,7 +140,7 @@
   while (MBBI !=3D MBB.begin()) {
     MachineBasicBlock::iterator PI =3D prior(MBBI);
     unsigned Opc =3D PI->getOpcode();
-    if (Opc !=3D MSP430::POP16r && !PI->getDesc().isTerminator())
+    if (Opc !=3D MSP430::POP16r && !PI->isTerminator())
       break;
     --MBBI;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430ISelLowering.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -29,7 +29,6 @@
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/CodeGen/SelectionDAGISel.h"
 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
 #include "llvm/CodeGen/ValueTypes.h"
@@ -37,7 +36,6 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/VectorExtras.h"
 using namespace llvm;
=20
 typedef enum {
@@ -80,7 +78,6 @@
   setStackPointerRegisterToSaveRestore(MSP430::SPW);
   setBooleanContents(ZeroOrOneBooleanContent);
   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this cor=
rect?
-  setSchedulingPreference(Sched::Latency);
=20
   // We have post-incremented loads / stores.
   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
@@ -124,8 +121,12 @@
=20
   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::i8,    Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::i16,   Expand);
   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::i8,    Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::i16,   Expand);
   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
=20
@@ -193,7 +194,6 @@
   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
   default:
     llvm_unreachable("unimplemented operand");
-    return SDValue();
   }
 }
=20
@@ -259,19 +259,16 @@
   case CallingConv::Fast:
     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVa=
ls);
   case CallingConv::MSP430_INTR:
-   if (Ins.empty())
-     return Chain;
-   else {
+    if (Ins.empty())
+      return Chain;
     report_fatal_error("ISRs cannot have arguments");
-    return SDValue();
-   }
   }
 }
=20
 SDValue
 MSP430TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                                 CallingConv::ID CallConv, bool isVarArg,
-                                bool &isTailCall,
+                                bool doesNotRet, bool &isTailCall,
                                 const SmallVectorImpl<ISD::OutputArg> &Out=
s,
                                 const SmallVectorImpl<SDValue> &OutVals,
                                 const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -289,7 +286,6 @@
                           Outs, OutVals, Ins, dl, DAG, InVals);
   case CallingConv::MSP430_INTR:
     report_fatal_error("ISRs cannot be called directly");
-    return SDValue();
   }
 }
=20
@@ -372,7 +368,7 @@
       SDValue FIN =3D DAG.getFrameIndex(FI, MVT::i16);
       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
                                    MachinePointerInfo::getFixedStack(FI),
-                                   false, false, 0));
+                                   false, false, false, 0));
     }
   }
=20
@@ -390,10 +386,8 @@
   SmallVector<CCValAssign, 16> RVLocs;
=20
   // ISRs cannot return any value.
-  if (CallConv =3D=3D CallingConv::MSP430_INTR && !Outs.empty()) {
+  if (CallConv =3D=3D CallingConv::MSP430_INTR && !Outs.empty())
     report_fatal_error("ISRs cannot return any value");
-    return SDValue();
-  }
=20
   // CCState - Info about the registers and stack slot.
   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
@@ -599,8 +593,7 @@
   // Expand non-constant shifts to loops:
   if (!isa<ConstantSDNode>(N->getOperand(1)))
     switch (Opc) {
-    default:
-      assert(0 && "Invalid shift opcode!");
+    default: llvm_unreachable("Invalid shift opcode!");
     case ISD::SHL:
       return DAG.getNode(MSP430ISD::SHL, dl,
                          VT, N->getOperand(0), N->getOperand(1));
@@ -651,7 +644,7 @@
   const char *Sym =3D cast<ExternalSymbolSDNode>(Op)->getSymbol();
   SDValue Result =3D DAG.getTargetExternalSymbol(Sym, getPointerTy());
=20
-  return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);;
+  return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
 }
=20
 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
@@ -660,7 +653,7 @@
   const BlockAddress *BA =3D cast<BlockAddressSDNode>(Op)->getBlockAddress=
();
   SDValue Result =3D DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=3D=
*/true);
=20
-  return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);;
+  return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
 }
=20
 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
@@ -908,13 +901,13 @@
     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
                                    FrameAddr, Offset),
-                       MachinePointerInfo(), false, false, 0);
+                       MachinePointerInfo(), false, false, false, 0);
   }
=20
   // Just load the return address.
   SDValue RetAddrFI =3D getReturnAddressFrameIndex(DAG);
   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
-                     RetAddrFI, MachinePointerInfo(), false, false, 0);
+                     RetAddrFI, MachinePointerInfo(), false, false, false,=
 0);
 }
=20
 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
@@ -930,7 +923,7 @@
   while (Depth--)
     FrameAddr =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
                             MachinePointerInfo(),
-                            false, false, 0);
+                            false, false, false, 0);
   return FrameAddr;
 }
=20
@@ -1028,8 +1021,7 @@
   unsigned Opc;
   const TargetRegisterClass * RC;
   switch (MI->getOpcode()) {
-  default:
-    assert(0 && "Invalid shift opcode!");
+  default: llvm_unreachable("Invalid shift opcode!");
   case MSP430::Shl8:
    Opc =3D MSP430::SHL8r1;
    RC =3D MSP430::GR8RegisterClass;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430ISelLowering.h
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430ISelLowering.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D-- MSP430ISelLowering.h - MSP430 DAG Lowering Interface ------*- C=
++ -*-=3D=3D//
+//=3D=3D=3D-- MSP430ISelLowering.h - MSP430 DAG Lowering Interface ----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -152,8 +152,8 @@
                            DebugLoc dl, SelectionDAG &DAG,
                            SmallVectorImpl<SDValue> &InVals) const;
     virtual SDValue
-      LowerCall(SDValue Chain, SDValue Callee,
-                CallingConv::ID CallConv, bool isVarArg, bool &isTailCall,
+      LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
+                bool isVarArg, bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430InstrFormats.td
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430InstrFormats.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430InstrFormats.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430InstrFormats.td - MSP430 Instruction Formats-----*- tbl=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MSP430InstrFormats.td - MSP430 Instruction Formats -*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430InstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430InstrInfo.cpp - MSP430 Instruction Information --------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MSP430InstrInfo.cpp - MSP430 Instruction Information -------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,15 +11,14 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "MSP430InstrInfo.h"
 #include "MSP430.h"
-#include "MSP430InstrInfo.h"
 #include "MSP430MachineFunctionInfo.h"
 #include "MSP430TargetMachine.h"
 #include "llvm/Function.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
=20
@@ -43,8 +42,7 @@
   MachineFrameInfo &MFI =3D *MF.getFrameInfo();
=20
   MachineMemOperand *MMO =3D
-    MF.getMachineMemOperand(
-              MachinePointerInfo(PseudoSourceValue::getFixedStack(FrameIdx=
)),
+    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
                             MachineMemOperand::MOStore,
                             MFI.getObjectSize(FrameIdx),
                             MFI.getObjectAlignment(FrameIdx));
@@ -72,8 +70,7 @@
   MachineFrameInfo &MFI =3D *MF.getFrameInfo();
=20
   MachineMemOperand *MMO =3D
-    MF.getMachineMemOperand(
-              MachinePointerInfo(PseudoSourceValue::getFixedStack(FrameIdx=
)),
+    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
                             MachineMemOperand::MOLoad,
                             MFI.getObjectSize(FrameIdx),
                             MFI.getObjectAlignment(FrameIdx));
@@ -133,9 +130,7 @@
   MSP430CC::CondCodes CC =3D static_cast<MSP430CC::CondCodes>(Cond[0].getI=
mm());
=20
   switch (CC) {
-  default:
-    assert(0 && "Invalid branch condition!");
-    break;
+  default: llvm_unreachable("Invalid branch condition!");
   case MSP430CC::COND_E:
     CC =3D MSP430CC::COND_NE;
     break;
@@ -161,13 +156,12 @@
 }
=20
 bool MSP430InstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) con=
st {
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.isTerminator()) return false;
+  if (!MI->isTerminator()) return false;
=20
   // Conditional branch is a special case.
-  if (MCID.isBranch() && !MCID.isBarrier())
+  if (MI->isBranch() && !MI->isBarrier())
     return true;
-  if (!MCID.isPredicable())
+  if (!MI->isPredicable())
     return true;
   return !isPredicated(MI);
 }
@@ -192,7 +186,7 @@
=20
     // A terminator that isn't a branch can't easily be handled
     // by this analysis.
-    if (!I->getDesc().isBranch())
+    if (!I->isBranch())
       return true;
=20
     // Cannot handle indirect branches.
@@ -301,8 +295,7 @@
   switch (Desc.TSFlags & MSP430II::SizeMask) {
   default:
     switch (Desc.getOpcode()) {
-    default:
-      assert(0 && "Unknown instruction size!");
+    default: llvm_unreachable("Unknown instruction size!");
     case TargetOpcode::PROLOG_LABEL:
     case TargetOpcode::EH_LABEL:
     case TargetOpcode::IMPLICIT_DEF:
@@ -318,8 +311,7 @@
     }
   case MSP430II::SizeSpecial:
     switch (MI->getOpcode()) {
-    default:
-      assert(0 && "Unknown instruction size!");
+    default: llvm_unreachable("Unknown instruction size!");
     case MSP430::SAR8r1c:
     case MSP430::SAR16r1c:
       return 4;
@@ -331,6 +323,4 @@
   case MSP430II::Size6Bytes:
     return 6;
   }
-
-  return 6;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430InstrInfo.h
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430InstrInfo.h - MSP430 Instruction Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MSP430InstrInfo.h - MSP430 Instruction Information ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,8 +14,8 @@
 #ifndef LLVM_TARGET_MSP430INSTRINFO_H
 #define LLVM_TARGET_MSP430INSTRINFO_H
=20
+#include "MSP430RegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "MSP430RegisterInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "MSP430GenInstrInfo.inc"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430InstrInfo.td
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430InstrInfo.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430InstrInfo.td - MSP430 Instruction defs -----------*- tb=
lgen-*-=3D=3D=3D//
+//=3D=3D=3D-- MSP430InstrInfo.td - MSP430 Instruction defs -------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430MCInstLower.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430MCInstLower.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430MCInstLower.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MSP430MCInstLower.cpp - Convert MSP430 MachineInstr to an MC=
Inst---=3D=3D=3D//
+//=3D=3D=3D-- MSP430MCInstLower.cpp - Convert MSP430 MachineInstr to an MC=
Inst --=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -39,7 +39,7 @@
 MCSymbol *MSP430MCInstLower::
 GetExternalSymbolSymbol(const MachineOperand &MO) const {
   switch (MO.getTargetFlags()) {
-  default: assert(0 && "Unknown target flag on GV operand");
+  default: llvm_unreachable("Unknown target flag on GV operand");
   case 0: break;
   }
=20
@@ -81,7 +81,7 @@
 MCSymbol *MSP430MCInstLower::
 GetBlockAddressSymbol(const MachineOperand &MO) const {
   switch (MO.getTargetFlags()) {
-  default: assert(0 && "Unknown target flag on GV operand");
+  default: llvm_unreachable("Unknown target flag on GV operand");
   case 0: break;
   }
=20
@@ -116,7 +116,7 @@
     switch (MO.getType()) {
     default:
       MI->dump();
-      assert(0 && "unknown operand type");
+      llvm_unreachable("unknown operand type");
     case MachineOperand::MO_Register:
       // Ignore all implicit register operands.
       if (MO.isImplicit()) continue;
@@ -143,6 +143,9 @@
       break;
     case MachineOperand::MO_BlockAddress:
       MCOp =3D LowerSymbolOperand(MO, GetBlockAddressSymbol(MO));
+      break;
+    case MachineOperand::MO_RegisterMask:
+      continue;
     }
=20
     OutMI.addOperand(MCOp);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430MCInstLower.h
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430MCInstLower.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430MCInstLower.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MSP430MCInstLower.h - Lower MachineInstr to MCInst ---------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MSP430MCInstLower.h - Lower MachineInstr to MCInst ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,7 +14,6 @@
=20
 namespace llvm {
   class AsmPrinter;
-  class MCAsmInfo;
   class MCContext;
   class MCInst;
   class MCOperand;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430MachineFunctionInfo.h
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430MachineFunctionInfo.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430MachineFunctionInfo.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -21,6 +21,8 @@
 /// MSP430MachineFunctionInfo - This class is derived from MachineFunction=
 and
 /// contains private MSP430 target-specific information for each MachineFu=
nction.
 class MSP430MachineFunctionInfo : public MachineFunctionInfo {
+  virtual void anchor();
+
   /// CalleeSavedFrameSize - Size of the callee-saved register portion of =
the
   /// stack frame in bytes.
   unsigned CalleeSavedFrameSize;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430RegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430RegisterInfo.cpp - MSP430 Register Information --------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MSP430RegisterInfo.cpp - MSP430 Register Information -------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,9 +13,9 @@
=20
 #define DEBUG_TYPE "msp430-reg-info"
=20
+#include "MSP430RegisterInfo.h"
 #include "MSP430.h"
 #include "MSP430MachineFunctionInfo.h"
-#include "MSP430RegisterInfo.h"
 #include "MSP430TargetMachine.h"
 #include "llvm/Function.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
@@ -38,27 +38,27 @@
   StackAlign =3D TM.getFrameLowering()->getStackAlignment();
 }
=20
-const unsigned*
+const uint16_t*
 MSP430RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
   const TargetFrameLowering *TFI =3D MF->getTarget().getFrameLowering();
   const Function* F =3D MF->getFunction();
-  static const unsigned CalleeSavedRegs[] =3D {
+  static const uint16_t CalleeSavedRegs[] =3D {
     MSP430::FPW, MSP430::R5W, MSP430::R6W, MSP430::R7W,
     MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W,
     0
   };
-  static const unsigned CalleeSavedRegsFP[] =3D {
+  static const uint16_t CalleeSavedRegsFP[] =3D {
     MSP430::R5W, MSP430::R6W, MSP430::R7W,
     MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W,
     0
   };
-  static const unsigned CalleeSavedRegsIntr[] =3D {
+  static const uint16_t CalleeSavedRegsIntr[] =3D {
     MSP430::FPW,  MSP430::R5W,  MSP430::R6W,  MSP430::R7W,
     MSP430::R8W,  MSP430::R9W,  MSP430::R10W, MSP430::R11W,
     MSP430::R12W, MSP430::R13W, MSP430::R14W, MSP430::R15W,
     0
   };
-  static const unsigned CalleeSavedRegsIntrFP[] =3D {
+  static const uint16_t CalleeSavedRegsIntrFP[] =3D {
     MSP430::R5W,  MSP430::R6W,  MSP430::R7W,
     MSP430::R8W,  MSP430::R9W,  MSP430::R10W, MSP430::R11W,
     MSP430::R12W, MSP430::R13W, MSP430::R14W, MSP430::R15W,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430RegisterInfo.h
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430RegisterInfo.h - MSP430 Register Information Impl --*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MSP430RegisterInfo.h - MSP430 Register Information Impl -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -36,18 +36,11 @@
   MSP430RegisterInfo(MSP430TargetMachine &tm, const TargetInstrInfo &tii);
=20
   /// Code Generation virtual methods...
-  const unsigned *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
=20
   BitVector getReservedRegs(const MachineFunction &MF) const;
   const TargetRegisterClass* getPointerRegClass(unsigned Kind =3D 0) const;
=20
-  const TargetRegisterClass *
-  getMatchingSuperRegClass(const TargetRegisterClass *A,
-                           const TargetRegisterClass *B, unsigned Idx) con=
st {
-    // No sub-classes makes this really easy.
-    return A;
-  }
-
   void eliminateCallFramePseudoInstr(MachineFunction &MF,
                                      MachineBasicBlock &MBB,
                                      MachineBasicBlock::iterator I) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430RegisterInfo.td
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430RegisterInfo.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430RegisterInfo.td - MSP430 Register defs ----------*- tbl=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MSP430RegisterInfo.td - MSP430 Register defs -------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430Subtarget.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430Subtarget.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430Subtarget.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MSP430Subtarget.cpp - MSP430 Subtarget Information ---------*=
- C++ -*-=3D//
+//=3D=3D=3D-- MSP430Subtarget.cpp - MSP430 Subtarget Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -21,6 +21,8 @@
=20
 using namespace llvm;
=20
+void MSP430Subtarget::anchor() { }
+
 MSP430Subtarget::MSP430Subtarget(const std::string &TT,
                                  const std::string &CPU,
                                  const std::string &FS) :
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430Subtarget.h
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430Subtarget.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430Subtarget.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D-- MSP430Subtarget.h - Define Subtarget for the MSP430 ---*-=
 C++ -*--=3D=3D=3D//
+//=3D=3D=3D-- MSP430Subtarget.h - Define Subtarget for the MSP430 ----*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,16 +15,16 @@
 #define LLVM_TARGET_MSP430_SUBTARGET_H
=20
 #include "llvm/Target/TargetSubtargetInfo.h"
+#include <string>
=20
 #define GET_SUBTARGETINFO_HEADER
 #include "MSP430GenSubtargetInfo.inc"
=20
-#include <string>
-
 namespace llvm {
 class StringRef;
=20
 class MSP430Subtarget : public MSP430GenSubtargetInfo {
+  virtual void anchor();
   bool ExtendedInsts;
 public:
   /// This constructor initializes the data members to match that
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430TargetMachine.cpp
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430TargetMachine.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430TargetMachine.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "MSP430TargetMachine.h"
 #include "MSP430.h"
-#include "MSP430TargetMachine.h"
 #include "llvm/PassManager.h"
 #include "llvm/CodeGen/Passes.h"
 #include "llvm/MC/MCAsmInfo.h"
@@ -28,24 +28,43 @@
                                          StringRef TT,
                                          StringRef CPU,
                                          StringRef FS,
-                                         Reloc::Model RM, CodeModel::Model=
 CM)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
+                                         const TargetOptions &Options,
+                                         Reloc::Model RM, CodeModel::Model=
 CM,
+                                         CodeGenOpt::Level OL)
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     Subtarget(TT, CPU, FS),
     // FIXME: Check TargetData string.
     DataLayout("e-p:16:16:16-i8:8:8-i16:16:16-i32:16:32-n8:16"),
     InstrInfo(*this), TLInfo(*this), TSInfo(*this),
     FrameLowering(Subtarget) { }
=20
+namespace {
+/// MSP430 Code Generator Pass Configuration Options.
+class MSP430PassConfig : public TargetPassConfig {
+public:
+  MSP430PassConfig(MSP430TargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
=20
-bool MSP430TargetMachine::addInstSelector(PassManagerBase &PM,
-                                          CodeGenOpt::Level OptLevel) {
+  MSP430TargetMachine &getMSP430TargetMachine() const {
+    return getTM<MSP430TargetMachine>();
+  }
+
+  virtual bool addInstSelector();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *MSP430TargetMachine::createPassConfig(PassManagerBase &P=
M) {
+  return new MSP430PassConfig(this, PM);
+}
+
+bool MSP430PassConfig::addInstSelector() {
   // Install an instruction selector.
-  PM.add(createMSP430ISelDag(*this, OptLevel));
+  PM.add(createMSP430ISelDag(getMSP430TargetMachine(), getOptLevel()));
   return false;
 }
=20
-bool MSP430TargetMachine::addPreEmitPass(PassManagerBase &PM,
-                                         CodeGenOpt::Level OptLevel) {
+bool MSP430PassConfig::addPreEmitPass() {
   // Must run branch selection immediately preceding the asm printer.
   PM.add(createMSP430BranchSelectionPass());
   return false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/MSP430/MS=
P430TargetMachine.h
--- a/head/contrib/llvm/lib/Target/MSP430/MSP430TargetMachine.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/MSP430/MSP430TargetMachine.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D-- MSP430TargetMachine.h - Define TargetMachine for MSP430 ---*- C=
++ -*-=3D=3D//
+//=3D=3D=3D-- MSP430TargetMachine.h - Define TargetMachine for MSP430 -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -39,8 +39,9 @@
=20
 public:
   MSP430TargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
-                      Reloc::Model RM, CodeModel::Model CM);
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
+                      Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL);
=20
   virtual const TargetFrameLowering *getFrameLowering() const {
     return &FrameLowering;
@@ -61,8 +62,7 @@
     return &TSInfo;
   }
=20
-  virtual bool addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptL=
evel);
-  virtual bool addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel);
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
 }; // MSP430TargetMachine.
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mangler.c=
pp
--- a/head/contrib/llvm/lib/Target/Mangler.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Target/Mangler.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -22,12 +22,13 @@
 #include "llvm/ADT/Twine.h"
 using namespace llvm;
=20
-static bool isAcceptableChar(char C, bool AllowPeriod) {
+static bool isAcceptableChar(char C, bool AllowPeriod, bool AllowUTF8) {
   if ((C < 'a' || C > 'z') &&
       (C < 'A' || C > 'Z') &&
       (C < '0' || C > '9') &&
       C !=3D '_' && C !=3D '$' && C !=3D '@' &&
-      !(AllowPeriod && C =3D=3D '.'))
+      !(AllowPeriod && C =3D=3D '.') &&
+      !(AllowUTF8 && (C & 0x80)))
     return false;
   return true;
 }
@@ -56,8 +57,9 @@
   // If any of the characters in the string is an unacceptable character, =
force
   // quotes.
   bool AllowPeriod =3D MAI.doesAllowPeriodsInName();
+  bool AllowUTF8 =3D MAI.doesAllowUTF8();
   for (unsigned i =3D 0, e =3D Str.size(); i !=3D e; ++i)
-    if (!isAcceptableChar(Str[i], AllowPeriod))
+    if (!isAcceptableChar(Str[i], AllowPeriod, AllowUTF8))
       return true;
   return false;
 }
@@ -74,8 +76,9 @@
   }
=20
   bool AllowPeriod =3D MAI.doesAllowPeriodsInName();
+  bool AllowUTF8 =3D MAI.doesAllowUTF8();
   for (unsigned i =3D 0, e =3D Str.size(); i !=3D e; ++i) {
-    if (!isAcceptableChar(Str[i], AllowPeriod))
+    if (!isAcceptableChar(Str[i], AllowPeriod, AllowUTF8))
       MangleLetter(OutName, Str[i]);
     else
       OutName.push_back(Str[i]);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Inst=
Printer/MipsInstPrinter.cpp
--- a/head/contrib/llvm/lib/Target/Mips/InstPrinter/MipsInstPrinter.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/InstPrinter/MipsInstPrinter.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -13,14 +13,15 @@
=20
 #define DEBUG_TYPE "asm-printer"
 #include "MipsInstPrinter.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCSymbol.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/StringExtras.h"
 using namespace llvm;
=20
-#define GET_INSTRUCTION_NAME
 #include "MipsGenAsmWriter.inc"
=20
 const char* Mips::MipsFCCToString(Mips::CondCode CC) {
@@ -61,12 +62,8 @@
   llvm_unreachable("Impossible condition code!");
 }
=20
-StringRef MipsInstPrinter::getOpcodeName(unsigned Opcode) const {
-  return getInstructionName(Opcode);
-}
-
 void MipsInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
-  OS << '$' << LowercaseString(getRegisterName(RegNo));
+  OS << '$' << StringRef(getRegisterName(RegNo)).lower();
 }
=20
 void MipsInstPrinter::printInst(const MCInst *MI, raw_ostream &O,
@@ -75,6 +72,59 @@
   printAnnotation(O, Annot);
 }
=20
+static void printExpr(const MCExpr *Expr, raw_ostream &OS) {
+  int Offset =3D 0;
+  const MCSymbolRefExpr *SRE;
+
+  if (const MCBinaryExpr *BE =3D dyn_cast<MCBinaryExpr>(Expr)) {
+    SRE =3D dyn_cast<MCSymbolRefExpr>(BE->getLHS());
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(BE->getRHS());
+    assert(SRE && CE && "Binary expression must be sym+const.");
+    Offset =3D CE->getValue();
+  }
+  else if (!(SRE =3D dyn_cast<MCSymbolRefExpr>(Expr)))
+    assert(false && "Unexpected MCExpr type.");
+
+  MCSymbolRefExpr::VariantKind Kind =3D SRE->getKind();
+
+  switch (Kind) {
+  default:                                 llvm_unreachable("Invalid kind!=
");
+  case MCSymbolRefExpr::VK_None:           break;
+  case MCSymbolRefExpr::VK_Mips_GPREL:     OS << "%gp_rel("; break;
+  case MCSymbolRefExpr::VK_Mips_GOT_CALL:  OS << "%call16("; break;
+  case MCSymbolRefExpr::VK_Mips_GOT16:     OS << "%got(";    break;
+  case MCSymbolRefExpr::VK_Mips_GOT:       OS << "%got(";    break;
+  case MCSymbolRefExpr::VK_Mips_ABS_HI:    OS << "%hi(";     break;
+  case MCSymbolRefExpr::VK_Mips_ABS_LO:    OS << "%lo(";     break;
+  case MCSymbolRefExpr::VK_Mips_TLSGD:     OS << "%tlsgd(";  break;
+  case MCSymbolRefExpr::VK_Mips_TLSLDM:    OS << "%tlsldm(";  break;
+  case MCSymbolRefExpr::VK_Mips_DTPREL_HI: OS << "%dtprel_hi(";  break;
+  case MCSymbolRefExpr::VK_Mips_DTPREL_LO: OS << "%dtprel_lo(";  break;
+  case MCSymbolRefExpr::VK_Mips_GOTTPREL:  OS << "%gottprel("; break;
+  case MCSymbolRefExpr::VK_Mips_TPREL_HI:  OS << "%tprel_hi("; break;
+  case MCSymbolRefExpr::VK_Mips_TPREL_LO:  OS << "%tprel_lo("; break;
+  case MCSymbolRefExpr::VK_Mips_GPOFF_HI:  OS << "%hi(%neg(%gp_rel("; brea=
k;
+  case MCSymbolRefExpr::VK_Mips_GPOFF_LO:  OS << "%lo(%neg(%gp_rel("; brea=
k;
+  case MCSymbolRefExpr::VK_Mips_GOT_DISP:  OS << "%got_disp("; break;
+  case MCSymbolRefExpr::VK_Mips_GOT_PAGE:  OS << "%got_page("; break;
+  case MCSymbolRefExpr::VK_Mips_GOT_OFST:  OS << "%got_ofst("; break;
+  }
+
+  OS << SRE->getSymbol();
+
+  if (Offset) {
+    if (Offset > 0)
+      OS << '+';
+    OS << Offset;
+  }
+
+  if ((Kind =3D=3D MCSymbolRefExpr::VK_Mips_GPOFF_HI) ||
+      (Kind =3D=3D MCSymbolRefExpr::VK_Mips_GPOFF_LO))
+    OS << ")))";
+  else if (Kind !=3D MCSymbolRefExpr::VK_None)
+    OS << ')';
+}
+
 void MipsInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
                                    raw_ostream &O) {
   const MCOperand &Op =3D MI->getOperand(OpNo);
@@ -82,14 +132,14 @@
     printRegName(O, Op.getReg());
     return;
   }
- =20
+
   if (Op.isImm()) {
     O << Op.getImm();
     return;
   }
- =20
+
   assert(Op.isExpr() && "unknown operand kind in printOperand");
-  O << *Op.getExpr();
+  printExpr(Op.getExpr(), O);
 }
=20
 void MipsInstPrinter::printUnsignedImm(const MCInst *MI, int opNum,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Inst=
Printer/MipsInstPrinter.h
--- a/head/contrib/llvm/lib/Target/Mips/InstPrinter/MipsInstPrinter.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/InstPrinter/MipsInstPrinter.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsInstPrinter.h - Convert Mips MCInst to assembly syntax -=
-------=3D=3D=3D//
+//=3D=3D=3D MipsInstPrinter.h - Convert Mips MCInst to assembly syntax -*-=
 C++ -*-=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,7 +18,7 @@
 namespace llvm {
 // These enumeration declarations were orignally in MipsInstrInfo.h but
 // had to be moved here to avoid circular dependencies between
-// LLVMMipsCodeGen and LLVMMipsAsmPrinter.=20
+// LLVMMipsCodeGen and LLVMMipsAsmPrinter.
 namespace Mips {
 // Mips Branch Codes
 enum FPBranchCode {
@@ -77,17 +77,17 @@
=20
 class MipsInstPrinter : public MCInstPrinter {
 public:
-  MipsInstPrinter(const MCAsmInfo &MAI) : MCInstPrinter(MAI) {}
- =20
+  MipsInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                  const MCRegisterInfo &MRI)
+    : MCInstPrinter(MAI, MII, MRI) {}
+
   // Autogenerated by tblgen.
   void printInstruction(const MCInst *MI, raw_ostream &O);
-  static const char *getInstructionName(unsigned Opcode);
   static const char *getRegisterName(unsigned RegNo);
- =20
-  virtual StringRef getOpcodeName(unsigned Opcode) const;
+
   virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
   virtual void printInst(const MCInst *MI, raw_ostream &O, StringRef Annot=
);
- =20
+
 private:
   void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O);
   void printUnsignedImm(const MCInst *MI, int opNum, raw_ostream &O);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsAsmBackend.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsAsmBackend.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,172 @@
+//=3D=3D=3D-- MipsASMBackend.cpp - Mips Asm Backend  ---------------------=
-------=3D=3D=3D//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//
+// This file implements the MipsAsmBackend and MipsELFObjectWriter classes.
+//
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//
+
+#include "MipsBaseInfo.h"
+#include "MipsFixupKinds.h"
 #include "MCTargetDesc/MipsMCTargetDesc.h"
-#include "llvm/ADT/Twine.h"
+#include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCDirectives.h"
 #include "llvm/MC/MCELFObjectWriter.h"
-#include "llvm/MC/MCExpr.h"
-#include "llvm/MC/MCMachObjectWriter.h"
+#include "llvm/MC/MCFixupKindInfo.h"
 #include "llvm/MC/MCObjectWriter.h"
-#include "llvm/MC/MCSectionELF.h"
-#include "llvm/MC/MCSectionMachO.h"
-#include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCSubtargetInfo.h"
-#include "llvm/Object/MachOFormat.h"
-#include "llvm/Support/ELF.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
+
 using namespace llvm;
=20
+// Prepare value for the target space for it
+static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) {
+
+  // Add/subtract and shift
+  switch (Kind) {
+  default:
+    return 0;
+  case FK_GPRel_4:
+  case FK_Data_4:
+  case Mips::fixup_Mips_LO16:
+    break;
+  case Mips::fixup_Mips_PC16:
+    // So far we are only using this type for branches.
+    // For branches we start 1 instruction after the branch
+    // so the displacement will be one instruction size less.
+    Value -=3D 4;
+    // The displacement is then divided by 4 to give us an 18 bit
+    // address range.
+    Value >>=3D 2;
+    break;
+  case Mips::fixup_Mips_26:
+    // So far we are only using this type for jumps.
+    // The displacement is then divided by 4 to give us an 28 bit
+    // address range.
+    Value >>=3D 2;
+    break;
+  case Mips::fixup_Mips_HI16:
+  case Mips::fixup_Mips_GOT_Local:
+    // Get the higher 16-bits. Also add 1 if bit 15 is 1.
+    Value =3D ((Value + 0x8000) >> 16) & 0xffff;
+    break;
+  }
+
+  return Value;
+}
+
 namespace {
-class MipsELFObjectWriter : public MCELFObjectTargetWriter {
+class MipsAsmBackend : public MCAsmBackend {
+  Triple::OSType OSType;
+  bool IsLittle; // Big or little endian
+  bool Is64Bit;  // 32 or 64 bit words
+
 public:
-  MipsELFObjectWriter(bool is64Bit, Triple::OSType OSType, uint16_t EMachi=
ne,
-                      bool HasRelocationAddend)
-    : MCELFObjectTargetWriter(is64Bit, OSType, EMachine,
-                              HasRelocationAddend) {}
-};
+  MipsAsmBackend(const Target &T,  Triple::OSType _OSType,
+                 bool _isLittle, bool _is64Bit)
+    :MCAsmBackend(), OSType(_OSType), IsLittle(_isLittle), Is64Bit(_is64Bi=
t) {}
=20
-class MipsAsmBackend : public MCAsmBackend {
-public:
-  MipsAsmBackend(const Target &T)
-    : MCAsmBackend() {}
-
-  unsigned getNumFixupKinds() const {
-    return 1;   //tbd
+  MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
+    return createMipsELFObjectWriter(OS, OSType, IsLittle, Is64Bit);
   }
=20
   /// ApplyFixup - Apply the \arg Value for given \arg Fixup into the prov=
ided
   /// data fragment, at the offset specified by the fixup and following the
   /// fixup kind as appropriate.
-  void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+  void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
                   uint64_t Value) const {
+    MCFixupKind Kind =3D Fixup.getKind();
+    Value =3D adjustFixupValue((unsigned)Kind, Value);
+    int64_t SymOffset =3D MipsGetSymAndOffset(Fixup).second;
+
+    if (!Value && !SymOffset)
+      return; // Doesn't change encoding.
+
+    // Where do we start in the object
+    unsigned Offset =3D Fixup.getOffset();
+    // Number of bytes we need to fixup
+    unsigned NumBytes =3D (getFixupKindInfo(Kind).TargetSize + 7) / 8;
+    // Used to point to big endian bytes
+    unsigned FullSize;
+
+    switch ((unsigned)Kind) {
+    case Mips::fixup_Mips_16:
+      FullSize =3D 2;
+      break;
+    case Mips::fixup_Mips_64:
+      FullSize =3D 8;
+      break;
+    default:
+      FullSize =3D 4;
+      break;
+    }
+
+    // Grab current value, if any, from bits.
+    uint64_t CurVal =3D 0;
+
+    for (unsigned i =3D 0; i !=3D NumBytes; ++i) {
+      unsigned Idx =3D IsLittle ? i : (FullSize - 1 - i);
+      CurVal |=3D (uint64_t)((uint8_t)Data[Offset + Idx]) << (i*8);
+    }
+
+    uint64_t Mask =3D ((uint64_t)(-1) >> (64 - getFixupKindInfo(Kind).Targ=
etSize));
+    CurVal |=3D (Value + SymOffset) & Mask;
+
+    // Write out the fixed up bytes back to the code/data bits.
+    for (unsigned i =3D 0; i !=3D NumBytes; ++i) {
+      unsigned Idx =3D IsLittle ? i : (FullSize - 1 - i);
+      Data[Offset + Idx] =3D (uint8_t)((CurVal >> (i*8)) & 0xff);
+    }
+  }
+
+  unsigned getNumFixupKinds() const { return Mips::NumTargetFixupKinds; }
+
+  const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const {
+    const static MCFixupKindInfo Infos[Mips::NumTargetFixupKinds] =3D {
+      // This table *must* be in same the order of fixup_* kinds in
+      // MipsFixupKinds.h.
+      //
+      // name                    offset  bits  flags
+      { "fixup_Mips_16",           0,     16,   0 },
+      { "fixup_Mips_32",           0,     32,   0 },
+      { "fixup_Mips_REL32",        0,     32,   0 },
+      { "fixup_Mips_26",           0,     26,   0 },
+      { "fixup_Mips_HI16",         0,     16,   0 },
+      { "fixup_Mips_LO16",         0,     16,   0 },
+      { "fixup_Mips_GPREL16",      0,     16,   0 },
+      { "fixup_Mips_LITERAL",      0,     16,   0 },
+      { "fixup_Mips_GOT_Global",   0,     16,   0 },
+      { "fixup_Mips_GOT_Local",    0,     16,   0 },
+      { "fixup_Mips_PC16",         0,     16,  MCFixupKindInfo::FKF_IsPCRe=
l },
+      { "fixup_Mips_CALL16",       0,     16,   0 },
+      { "fixup_Mips_GPREL32",      0,     32,   0 },
+      { "fixup_Mips_SHIFT5",       6,      5,   0 },
+      { "fixup_Mips_SHIFT6",       6,      5,   0 },
+      { "fixup_Mips_64",           0,     64,   0 },
+      { "fixup_Mips_TLSGD",        0,     16,   0 },
+      { "fixup_Mips_GOTTPREL",     0,     16,   0 },
+      { "fixup_Mips_TPREL_HI",     0,     16,   0 },
+      { "fixup_Mips_TPREL_LO",     0,     16,   0 },
+      { "fixup_Mips_TLSLDM",       0,     16,   0 },
+      { "fixup_Mips_DTPREL_HI",    0,     16,   0 },
+      { "fixup_Mips_DTPREL_LO",    0,     16,   0 },
+      { "fixup_Mips_Branch_PCRel", 0,     16,  MCFixupKindInfo::FKF_IsPCRe=
l }
+    };
+
+    if (Kind < FirstTargetFixupKind)
+      return MCAsmBackend::getFixupKindInfo(Kind);
+
+    assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
+           "Invalid kind!");
+    return Infos[Kind - FirstTargetFixupKind];
   }
=20
   /// @name Target Relaxation Interfaces
@@ -48,70 +176,62 @@
   /// relaxation.
   ///
   /// \param Inst - The instruction to test.
-  bool MayNeedRelaxation(const MCInst &Inst) const {
+  bool mayNeedRelaxation(const MCInst &Inst) const {
     return false;
   }
=20
-  /// RelaxInstruction - Relax the instruction in the given fragment to th=
e next
-  /// wider instruction.
+  /// fixupNeedsRelaxation - Target specific predicate for whether a given
+  /// fixup requires the associated instruction to be relaxed.
+  bool fixupNeedsRelaxation(const MCFixup &Fixup,
+                            uint64_t Value,
+                            const MCInstFragment *DF,
+                            const MCAsmLayout &Layout) const {
+    // FIXME.
+    assert(0 && "RelaxInstruction() unimplemented");
+    return false;
+  }
+
+  /// RelaxInstruction - Relax the instruction in the given fragment
+  /// to the next wider instruction.
   ///
-  /// \param Inst - The instruction to relax, which may be the same as the
-  /// output.
+  /// \param Inst - The instruction to relax, which may be the same
+  /// as the output.
   /// \parm Res [output] - On return, the relaxed instruction.
-  void RelaxInstruction(const MCInst &Inst, MCInst &Res) const {
+  void relaxInstruction(const MCInst &Inst, MCInst &Res) const {
   }
- =20
+
   /// @}
=20
-  /// WriteNopData - Write an (optimal) nop sequence of Count bytes to the=
 given
-  /// output. If the target cannot generate such a sequence, it should ret=
urn an
-  /// error.
+  /// WriteNopData - Write an (optimal) nop sequence of Count bytes
+  /// to the given output. If the target cannot generate such a sequence,
+  /// it should return an error.
   ///
   /// \return - True on success.
-  bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const {
-    return false;
+  bool writeNopData(uint64_t Count, MCObjectWriter *OW) const {
+    return true;
   }
-};
+}; // class MipsAsmBackend
=20
-class MipsEB_AsmBackend : public MipsAsmBackend {
-public:
-  Triple::OSType OSType;
+} // namespace
=20
-  MipsEB_AsmBackend(const Target &T, Triple::OSType _OSType)
-    : MipsAsmBackend(T), OSType(_OSType) {}
-
-  MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
-    return createELFObjectWriter(createELFObjectTargetWriter(),
-                                 OS, /*IsLittleEndian*/ false);
-  }
-
-  MCELFObjectTargetWriter *createELFObjectTargetWriter() const {
-    return new MipsELFObjectWriter(false, OSType, ELF::EM_MIPS, false);
-  }
-};
-
-class MipsEL_AsmBackend : public MipsAsmBackend {
-public:
-  Triple::OSType OSType;
-
-  MipsEL_AsmBackend(const Target &T, Triple::OSType _OSType)
-    : MipsAsmBackend(T), OSType(_OSType) {}
-
-  MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
-    return createELFObjectWriter(createELFObjectTargetWriter(),
-                                 OS, /*IsLittleEndian*/ true);
-  }
-
-  MCELFObjectTargetWriter *createELFObjectTargetWriter() const {
-    return new MipsELFObjectWriter(false, OSType, ELF::EM_MIPS, false);
-  }
-};
+// MCAsmBackend
+MCAsmBackend *llvm::createMipsAsmBackendEL32(const Target &T, StringRef TT=
) {
+  return new MipsAsmBackend(T, Triple(TT).getOS(),
+                            /*IsLittle*/true, /*Is64Bit*/false);
 }
=20
-MCAsmBackend *llvm::createMipsAsmBackend(const Target &T, StringRef TT) {
-  Triple TheTriple(TT);
+MCAsmBackend *llvm::createMipsAsmBackendEB32(const Target &T, StringRef TT=
) {
+  return new MipsAsmBackend(T, Triple(TT).getOS(),
+                            /*IsLittle*/false, /*Is64Bit*/false);
+}
=20
-  // just return little endian for now
-  //
-  return new MipsEL_AsmBackend(T, Triple(TT).getOS());
+MCAsmBackend *llvm::createMipsAsmBackendEL64(const Target &T, StringRef TT=
) {
+  return new MipsAsmBackend(T, Triple(TT).getOS(),
+                            /*IsLittle*/true, /*Is64Bit*/true);
 }
+
+MCAsmBackend *llvm::createMipsAsmBackendEB64(const Target &T, StringRef TT=
) {
+  return new MipsAsmBackend(T, Triple(TT).getOS(),
+                            /*IsLittle*/false, /*Is64Bit*/true);
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsBaseInfo.h
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsBaseInfo.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsBaseInfo.h - Top level definitions for ARM ------- --*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsBaseInfo.h - Top level definitions for MIPS MC ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,11 +14,103 @@
 #ifndef MIPSBASEINFO_H
 #define MIPSBASEINFO_H
=20
+#include "MipsFixupKinds.h"
 #include "MipsMCTargetDesc.h"
+#include "llvm/MC/MCExpr.h"
 #include "llvm/Support/DataTypes.h"
 #include "llvm/Support/ErrorHandling.h"
=20
 namespace llvm {
+
+/// MipsII - This namespace holds all of the target specific flags that
+/// instruction info tracks.
+///
+namespace MipsII {
+  /// Target Operand Flag enum.
+  enum TOF {
+    //=3D=3D=3D-----------------------------------------------------------=
-------=3D=3D=3D//
+    // Mips Specific MachineOperand flags.
+
+    MO_NO_FLAG,
+
+    /// MO_GOT16 - Represents the offset into the global offset table at w=
hich
+    /// the address the relocation entry symbol resides during execution.
+    MO_GOT16,
+    MO_GOT,
+
+    /// MO_GOT_CALL - Represents the offset into the global offset table at
+    /// which the address of a call site relocation entry symbol resides
+    /// during execution. This is different from the above since this flag
+    /// can only be present in call instructions.
+    MO_GOT_CALL,
+
+    /// MO_GPREL - Represents the offset from the current gp value to be u=
sed
+    /// for the relocatable object file being produced.
+    MO_GPREL,
+
+    /// MO_ABS_HI/LO - Represents the hi or low part of an absolute symbol
+    /// address.
+    MO_ABS_HI,
+    MO_ABS_LO,
+
+    /// MO_TLSGD - Represents the offset into the global offset table at w=
hich
+    // the module ID and TSL block offset reside during execution (General
+    // Dynamic TLS).
+    MO_TLSGD,
+
+    /// MO_TLSLDM - Represents the offset into the global offset table at =
which
+    // the module ID and TSL block offset reside during execution (Local
+    // Dynamic TLS).
+    MO_TLSLDM,
+    MO_DTPREL_HI,
+    MO_DTPREL_LO,
+
+    /// MO_GOTTPREL - Represents the offset from the thread pointer (Initi=
al
+    // Exec TLS).
+    MO_GOTTPREL,
+
+    /// MO_TPREL_HI/LO - Represents the hi and low part of the offset from
+    // the thread pointer (Local Exec TLS).
+    MO_TPREL_HI,
+    MO_TPREL_LO,
+
+    // N32/64 Flags.
+    MO_GPOFF_HI,
+    MO_GPOFF_LO,
+    MO_GOT_DISP,
+    MO_GOT_PAGE,
+    MO_GOT_OFST
+  };
+
+  enum {
+    //=3D=3D=3D-----------------------------------------------------------=
-------=3D=3D=3D//
+    // Instruction encodings.  These are the standard/most common forms for
+    // Mips instructions.
+    //
+
+    // Pseudo - This represents an instruction that is a pseudo instruction
+    // or one that has not been implemented yet.  It is illegal to code ge=
nerate
+    // it, but tolerated for intermediate implementation stages.
+    Pseudo   =3D 0,
+
+    /// FrmR - This form is for instructions of the format R.
+    FrmR  =3D 1,
+    /// FrmI - This form is for instructions of the format I.
+    FrmI  =3D 2,
+    /// FrmJ - This form is for instructions of the format J.
+    FrmJ  =3D 3,
+    /// FrmFR - This form is for instructions of the format FR.
+    FrmFR =3D 4,
+    /// FrmFI - This form is for instructions of the format FI.
+    FrmFI =3D 5,
+    /// FrmOther - This form is for instructions that have no specific for=
mat.
+    FrmOther =3D 6,
+
+    FormMask =3D 15
+  };
+}
+
+
 /// getMipsRegisterNumbering - Given the enum value for some register,
 /// return the number that it corresponds to.
 inline static unsigned getMipsRegisterNumbering(unsigned RegEnum)
@@ -98,15 +190,43 @@
   case Mips::D14:
     return 28;
   case Mips::SP: case Mips::SP_64: case Mips::F29: case Mips::D29_64:
+  case Mips::HWR29:
     return 29;
   case Mips::FP: case Mips::FP_64: case Mips::F30: case Mips::D30_64:
-  case Mips::D15:=20
+  case Mips::D15:
     return 30;
   case Mips::RA: case Mips::RA_64: case Mips::F31: case Mips::D31_64:
     return 31;
   default: llvm_unreachable("Unknown register number!");
   }
-  return 0; // Not reached
+}
+
+inline static std::pair<const MCSymbolRefExpr*, int64_t>
+MipsGetSymAndOffset(const MCFixup &Fixup) {
+  MCFixupKind FixupKind =3D Fixup.getKind();
+
+  if ((FixupKind < FirstTargetFixupKind) ||
+      (FixupKind >=3D MCFixupKind(Mips::LastTargetFixupKind)))
+    return std::make_pair((const MCSymbolRefExpr*)0, (int64_t)0);
+
+  const MCExpr *Expr =3D Fixup.getValue();
+  MCExpr::ExprKind Kind =3D Expr->getKind();
+
+  if (Kind =3D=3D MCExpr::Binary) {
+    const MCBinaryExpr *BE =3D static_cast<const MCBinaryExpr*>(Expr);
+    const MCExpr *LHS =3D BE->getLHS();
+    const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(BE->getRHS());
+
+    if ((LHS->getKind() !=3D MCExpr::SymbolRef) || !CE)
+      return std::make_pair((const MCSymbolRefExpr*)0, (int64_t)0);
+
+    return std::make_pair(cast<MCSymbolRefExpr>(LHS), CE->getValue());
+  }
+
+  if (Kind !=3D MCExpr::SymbolRef)
+    return std::make_pair((const MCSymbolRefExpr*)0, (int64_t)0);
+
+  return std::make_pair(cast<MCSymbolRefExpr>(Expr), 0);
 }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsFixupKinds.h
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsFixupKinds.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -1,7 +1,4 @@
-#ifndef LLVM_Mips_MipsFIXUPKINDS_H
-#define LLVM_Mips_MipsFIXUPKINDS_H
-
-//=3D=3D=3D-- Mips/MipsFixupKinds.h - Mips Specific Fixup Entries --------=
*- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsFixupKinds.h - Mips Specific Fixup Entries ----------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -10,81 +7,100 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#ifndef LLVM_MIPS_MIPSFIXUPKINDS_H
+#define LLVM_MIPS_MIPSFIXUPKINDS_H
=20
 #include "llvm/MC/MCFixup.h"
=20
 namespace llvm {
 namespace Mips {
-    enum Fixups {
-        // fixup_Mips_xxx - R_MIPS_NONE
-        fixup_Mips_NONE =3D FirstTargetFixupKind,
+  // Although most of the current fixup types reflect a unique relocation
+  // one can have multiple fixup types for a given relocation and thus need
+  // to be uniquely named.
+  //
+  // This table *must* be in the save order of
+  // MCFixupKindInfo Infos[Mips::NumTargetFixupKinds]
+  // in MipsAsmBackend.cpp.
+  //
+  enum Fixups {
+    // Branch fixups resulting in R_MIPS_16.
+    fixup_Mips_16 =3D FirstTargetFixupKind,
=20
-        // fixup_Mips_xxx - R_MIPS_16.
-        fixup_Mips_16,
+    // Pure 32 bit data fixup resulting in - R_MIPS_32.
+    fixup_Mips_32,
=20
-        // fixup_Mips_xxx - R_MIPS_32.
-        fixup_Mips_32,
+    // Full 32 bit data relative data fixup resulting in - R_MIPS_REL32.
+    fixup_Mips_REL32,
=20
-        // fixup_Mips_xxx - R_MIPS_REL32.
-        fixup_Mips_REL32,
+    // Jump 26 bit fixup resulting in - R_MIPS_26.
+    fixup_Mips_26,
=20
-        // fixup_Mips_xxx - R_MIPS_26.
-        fixup_Mips_26,
+    // Pure upper 16 bit fixup resulting in - R_MIPS_HI16.
+    fixup_Mips_HI16,
=20
-        // fixup_Mips_xxx - R_MIPS_HI16.
-        fixup_Mips_HI16,
+    // Pure lower 16 bit fixup resulting in - R_MIPS_LO16.
+    fixup_Mips_LO16,
=20
-        // fixup_Mips_xxx - R_MIPS_LO16.
-        fixup_Mips_LO16,
+    // 16 bit fixup for GP offest resulting in - R_MIPS_GPREL16.
+    fixup_Mips_GPREL16,
=20
-        // fixup_Mips_xxx - R_MIPS_GPREL16.
-        fixup_Mips_GPREL16,
+    // 16 bit literal fixup resulting in - R_MIPS_LITERAL.
+    fixup_Mips_LITERAL,
=20
-        // fixup_Mips_xxx - R_MIPS_LITERAL.
-        fixup_Mips_LITERAL,
+    // Global symbol fixup resulting in - R_MIPS_GOT16.
+    fixup_Mips_GOT_Global,
=20
-        // fixup_Mips_xxx - R_MIPS_GOT16.
-        fixup_Mips_GOT16,
+    // Local symbol fixup resulting in - R_MIPS_GOT16.
+    fixup_Mips_GOT_Local,
=20
-        // fixup_Mips_xxx - R_MIPS_PC16.
-        fixup_Mips_PC16,
+    // PC relative branch fixup resulting in - R_MIPS_PC16.
+    fixup_Mips_PC16,
=20
-        // fixup_Mips_xxx - R_MIPS_CALL16.
-        fixup_Mips_CALL16,
+    // resulting in - R_MIPS_CALL16.
+    fixup_Mips_CALL16,
=20
-        // fixup_Mips_xxx - R_MIPS_GPREL32.
-        fixup_Mips_GPREL32,
+    // resulting in - R_MIPS_GPREL32.
+    fixup_Mips_GPREL32,
=20
-        // fixup_Mips_xxx - R_MIPS_SHIFT5.
-        fixup_Mips_SHIFT5,
+    // resulting in - R_MIPS_SHIFT5.
+    fixup_Mips_SHIFT5,
=20
-        // fixup_Mips_xxx - R_MIPS_SHIFT6.
-        fixup_Mips_SHIFT6,
+    // resulting in - R_MIPS_SHIFT6.
+    fixup_Mips_SHIFT6,
=20
-        // fixup_Mips_xxx - R_MIPS_64.
-        fixup_Mips_64,
+    // Pure 64 bit data fixup resulting in - R_MIPS_64.
+    fixup_Mips_64,
=20
-        // fixup_Mips_xxx - R_MIPS_TLS_GD.
-        fixup_Mips_TLSGD,
+    // resulting in - R_MIPS_TLS_GD.
+    fixup_Mips_TLSGD,
=20
-        // fixup_Mips_xxx - R_MIPS_TLS_GOTTPREL.
-        fixup_Mips_GOTTPREL,
+    // resulting in - R_MIPS_TLS_GOTTPREL.
+    fixup_Mips_GOTTPREL,
=20
-        // fixup_Mips_xxx - R_MIPS_TLS_TPREL_HI16.
-        fixup_Mips_TPREL_HI,
+    // resulting in - R_MIPS_TLS_TPREL_HI16.
+    fixup_Mips_TPREL_HI,
=20
-        // fixup_Mips_xxx - R_MIPS_TLS_TPREL_LO16.
-        fixup_Mips_TPREL_LO,
+    // resulting in - R_MIPS_TLS_TPREL_LO16.
+    fixup_Mips_TPREL_LO,
=20
-        // fixup_Mips_xxx - yyy. // This should become R_MIPS_PC16
-        fixup_Mips_Branch_PCRel,
+    // resulting in - R_MIPS_TLS_LDM.
+    fixup_Mips_TLSLDM,
=20
-        // Marker
-        LastTargetFixupKind,
-        NumTargetFixupKinds =3D LastTargetFixupKind - FirstTargetFixupKind
-    };
+    // resulting in - R_MIPS_TLS_DTPREL_HI16.
+    fixup_Mips_DTPREL_HI,
+
+    // resulting in - R_MIPS_TLS_DTPREL_LO16.
+    fixup_Mips_DTPREL_LO,
+
+    // PC relative branch fixup resulting in - R_MIPS_PC16
+    fixup_Mips_Branch_PCRel,
+
+    // Marker
+    LastTargetFixupKind,
+    NumTargetFixupKinds =3D LastTargetFixupKind - FirstTargetFixupKind
+  };
+} // namespace Mips
 } // namespace llvm
-} // namespace Mips
=20
=20
-#endif /* LLVM_Mips_MipsFIXUPKINDS_H */
+#endif // LLVM_MIPS_MIPSFIXUPKINDS_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsMCAsmInfo.cpp - Mips asm properties --------------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MipsMCAsmInfo.cpp - Mips Asm Properties --------------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -16,6 +16,8 @@
=20
 using namespace llvm;
=20
+void MipsMCAsmInfo::anchor() { }
+
 MipsMCAsmInfo::MipsMCAsmInfo(const Target &T, StringRef TT) {
   Triple TheTriple(TT);
   if ((TheTriple.getArch() =3D=3D Triple::mips) ||
@@ -25,11 +27,12 @@
   AlignmentIsInBytes          =3D false;
   Data16bitsDirective         =3D "\t.2byte\t";
   Data32bitsDirective         =3D "\t.4byte\t";
-  Data64bitsDirective         =3D 0;
+  Data64bitsDirective         =3D "\t.8byte\t";
   PrivateGlobalPrefix         =3D "$";
   CommentString               =3D "#";
   ZeroDirective               =3D "\t.space\t";
   GPRel32Directive            =3D "\t.gpword\t";
+  GPRel64Directive            =3D "\t.gpdword\t";
   WeakRefDirective            =3D "\t.weak\t";
=20
   SupportsDebugInformation =3D true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCAsmInfo.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- MipsMCAsmInfo.h - Mips asm properties ---------------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- MipsMCAsmInfo.h - Mips Asm Info ------------------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,13 +14,14 @@
 #ifndef MIPSTARGETASMINFO_H
 #define MIPSTARGETASMINFO_H
=20
-#include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MCAsmInfo.h"
=20
 namespace llvm {
+  class StringRef;
   class Target;
=20
   class MipsMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
   public:
     explicit MipsMCAsmInfo(const Target &T, StringRef TT);
   };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsMCCodeEmitter.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCCodeEmitter.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsMCCodeEmitter.cpp - Convert Mips code to machine code --=
-------=3D=3D=3D//
+//=3D=3D=3D-- MipsMCCodeEmitter.cpp - Convert Mips Code to Machine Code --=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,16 +12,18 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 #define DEBUG_TYPE "mccodeemitter"
+#include "MCTargetDesc/MipsBaseInfo.h"
+#include "MCTargetDesc/MipsFixupKinds.h"
+#include "MCTargetDesc/MipsMCTargetDesc.h"
+#include "llvm/ADT/APFloat.h"
+#include "llvm/ADT/Statistic.h"
 #include "llvm/MC/MCCodeEmitter.h"
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
-#include "llvm/ADT/APFloat.h"
-#include "llvm/ADT/Statistic.h"
 #include "llvm/Support/raw_ostream.h"
-#include "MCTargetDesc/MipsMCTargetDesc.h"
=20
 using namespace llvm;
=20
@@ -31,22 +33,252 @@
   void operator=3D(const MipsMCCodeEmitter &); // DO NOT IMPLEMENT
   const MCInstrInfo &MCII;
   const MCSubtargetInfo &STI;
+  MCContext &Ctx;
+  bool IsLittleEndian;
=20
 public:
   MipsMCCodeEmitter(const MCInstrInfo &mcii, const MCSubtargetInfo &sti,
-                    MCContext &ctx)
-    : MCII(mcii), STI(sti) {}
+                    MCContext &ctx, bool IsLittle) :
+            MCII(mcii), STI(sti) , Ctx(ctx), IsLittleEndian(IsLittle) {}
=20
   ~MipsMCCodeEmitter() {}
=20
+  void EmitByte(unsigned char C, raw_ostream &OS) const {
+    OS << (char)C;
+  }
+
+  void EmitInstruction(uint64_t Val, unsigned Size, raw_ostream &OS) const=
 {
+    // Output the instruction encoding in little endian byte order.
+    for (unsigned i =3D 0; i < Size; ++i) {
+      unsigned Shift =3D IsLittleEndian ? i * 8 : (Size - 1 - i) * 8;
+      EmitByte((Val >> Shift) & 0xff, OS);
+    }
+  }
+
   void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
-                         SmallVectorImpl<MCFixup> &Fixups) const {
-  }
+                         SmallVectorImpl<MCFixup> &Fixups) const;
+
+  // getBinaryCodeForInstr - TableGen'erated function for getting the
+  // binary encoding for an instruction.
+  uint64_t getBinaryCodeForInstr(const MCInst &MI,
+                                 SmallVectorImpl<MCFixup> &Fixups) const;
+
+  // getBranchJumpOpValue - Return binary encoding of the jump
+  // target operand. If the machine operand requires relocation,
+  // record the relocation and return zero.
+   unsigned getJumpTargetOpValue(const MCInst &MI, unsigned OpNo,
+                                 SmallVectorImpl<MCFixup> &Fixups) const;
+
+   // getBranchTargetOpValue - Return binary encoding of the branch
+   // target operand. If the machine operand requires relocation,
+   // record the relocation and return zero.
+  unsigned getBranchTargetOpValue(const MCInst &MI, unsigned OpNo,
+                                  SmallVectorImpl<MCFixup> &Fixups) const;
+
+   // getMachineOpValue - Return binary encoding of operand. If the machin
+   // operand requires relocation, record the relocation and return zero.
+  unsigned getMachineOpValue(const MCInst &MI,const MCOperand &MO,
+                             SmallVectorImpl<MCFixup> &Fixups) const;
+
+  unsigned getMemEncoding(const MCInst &MI, unsigned OpNo,
+                          SmallVectorImpl<MCFixup> &Fixups) const;
+  unsigned getSizeExtEncoding(const MCInst &MI, unsigned OpNo,
+                              SmallVectorImpl<MCFixup> &Fixups) const;
+  unsigned getSizeInsEncoding(const MCInst &MI, unsigned OpNo,
+                              SmallVectorImpl<MCFixup> &Fixups) const;
+
 }; // class MipsMCCodeEmitter
 }  // namespace
=20
-MCCodeEmitter *llvm::createMipsMCCodeEmitter(const MCInstrInfo &MCII,
-                                             const MCSubtargetInfo &STI,
-                                             MCContext &Ctx) {
-  return new MipsMCCodeEmitter(MCII, STI, Ctx);
+MCCodeEmitter *llvm::createMipsMCCodeEmitterEB(const MCInstrInfo &MCII,
+                                               const MCSubtargetInfo &STI,
+                                               MCContext &Ctx)
+{
+  return new MipsMCCodeEmitter(MCII, STI, Ctx, false);
 }
+
+MCCodeEmitter *llvm::createMipsMCCodeEmitterEL(const MCInstrInfo &MCII,
+                                               const MCSubtargetInfo &STI,
+                                               MCContext &Ctx)
+{
+  return new MipsMCCodeEmitter(MCII, STI, Ctx, true);
+}
+
+/// EncodeInstruction - Emit the instruction.
+/// Size the instruction (currently only 4 bytes
+void MipsMCCodeEmitter::
+EncodeInstruction(const MCInst &MI, raw_ostream &OS,
+                  SmallVectorImpl<MCFixup> &Fixups) const
+{
+  uint32_t Binary =3D getBinaryCodeForInstr(MI, Fixups);
+
+  // Check for unimplemented opcodes.
+  // Unfortunately in MIPS both NOT and SLL will come in with Binary =3D=
=3D 0
+  // so we have to special check for them.
+  unsigned Opcode =3D MI.getOpcode();
+  if ((Opcode !=3D Mips::NOP) && (Opcode !=3D Mips::SLL) && !Binary)
+    llvm_unreachable("unimplemented opcode in EncodeInstruction()");
+
+  const MCInstrDesc &Desc =3D MCII.get(MI.getOpcode());
+  uint64_t TSFlags =3D Desc.TSFlags;
+
+  // Pseudo instructions don't get encoded and shouldn't be here
+  // in the first place!
+  if ((TSFlags & MipsII::FormMask) =3D=3D MipsII::Pseudo)
+    llvm_unreachable("Pseudo opcode found in EncodeInstruction()");
+
+  // For now all instructions are 4 bytes
+  int Size =3D 4; // FIXME: Have Desc.getSize() return the correct value!
+
+  EmitInstruction(Binary, Size, OS);
+}
+
+/// getBranchTargetOpValue - Return binary encoding of the branch
+/// target operand. If the machine operand requires relocation,
+/// record the relocation and return zero.
+unsigned MipsMCCodeEmitter::
+getBranchTargetOpValue(const MCInst &MI, unsigned OpNo,
+                       SmallVectorImpl<MCFixup> &Fixups) const {
+
+  const MCOperand &MO =3D MI.getOperand(OpNo);
+  assert(MO.isExpr() && "getBranchTargetOpValue expects only expressions");
+
+  const MCExpr *Expr =3D MO.getExpr();
+  Fixups.push_back(MCFixup::Create(0, Expr,
+                                   MCFixupKind(Mips::fixup_Mips_PC16)));
+  return 0;
+}
+
+/// getJumpTargetOpValue - Return binary encoding of the jump
+/// target operand. If the machine operand requires relocation,
+/// record the relocation and return zero.
+unsigned MipsMCCodeEmitter::
+getJumpTargetOpValue(const MCInst &MI, unsigned OpNo,
+                     SmallVectorImpl<MCFixup> &Fixups) const {
+
+  const MCOperand &MO =3D MI.getOperand(OpNo);
+  assert(MO.isExpr() && "getJumpTargetOpValue expects only expressions");
+
+  const MCExpr *Expr =3D MO.getExpr();
+  Fixups.push_back(MCFixup::Create(0, Expr,
+                                   MCFixupKind(Mips::fixup_Mips_26)));
+  return 0;
+}
+
+/// getMachineOpValue - Return binary encoding of operand. If the machine
+/// operand requires relocation, record the relocation and return zero.
+unsigned MipsMCCodeEmitter::
+getMachineOpValue(const MCInst &MI, const MCOperand &MO,
+                  SmallVectorImpl<MCFixup> &Fixups) const {
+  if (MO.isReg()) {
+    unsigned Reg =3D MO.getReg();
+    unsigned RegNo =3D getMipsRegisterNumbering(Reg);
+    return RegNo;
+  } else if (MO.isImm()) {
+    return static_cast<unsigned>(MO.getImm());
+  } else if (MO.isFPImm()) {
+    return static_cast<unsigned>(APFloat(MO.getFPImm())
+        .bitcastToAPInt().getHiBits(32).getLimitedValue());
+  }=20
+
+  // MO must be an Expr.
+  assert(MO.isExpr());
+
+  const MCExpr *Expr =3D MO.getExpr();
+  MCExpr::ExprKind Kind =3D Expr->getKind();
+
+  if (Kind =3D=3D MCExpr::Binary) {
+    Expr =3D static_cast<const MCBinaryExpr*>(Expr)->getLHS();
+    Kind =3D Expr->getKind();
+  }
+
+  assert (Kind =3D=3D MCExpr::SymbolRef);
+   =20
+  Mips::Fixups FixupKind;
+
+  switch(cast<MCSymbolRefExpr>(Expr)->getKind()) {
+  case MCSymbolRefExpr::VK_Mips_GPREL:
+    FixupKind =3D Mips::fixup_Mips_GPREL16;
+    break;
+  case MCSymbolRefExpr::VK_Mips_GOT_CALL:
+    FixupKind =3D Mips::fixup_Mips_CALL16;
+    break;
+  case MCSymbolRefExpr::VK_Mips_GOT16:
+    FixupKind =3D Mips::fixup_Mips_GOT_Global;
+    break;
+  case MCSymbolRefExpr::VK_Mips_GOT:
+    FixupKind =3D Mips::fixup_Mips_GOT_Local;
+    break;
+  case MCSymbolRefExpr::VK_Mips_ABS_HI:
+    FixupKind =3D Mips::fixup_Mips_HI16;
+    break;
+  case MCSymbolRefExpr::VK_Mips_ABS_LO:
+    FixupKind =3D Mips::fixup_Mips_LO16;
+    break;
+  case MCSymbolRefExpr::VK_Mips_TLSGD:
+    FixupKind =3D Mips::fixup_Mips_TLSGD;
+    break;
+  case MCSymbolRefExpr::VK_Mips_TLSLDM:
+    FixupKind =3D Mips::fixup_Mips_TLSLDM;
+    break;
+  case MCSymbolRefExpr::VK_Mips_DTPREL_HI:
+    FixupKind =3D Mips::fixup_Mips_DTPREL_HI;
+    break;
+  case MCSymbolRefExpr::VK_Mips_DTPREL_LO:
+    FixupKind =3D Mips::fixup_Mips_DTPREL_LO;
+    break;
+  case MCSymbolRefExpr::VK_Mips_GOTTPREL:
+    FixupKind =3D Mips::fixup_Mips_GOTTPREL;
+    break;
+  case MCSymbolRefExpr::VK_Mips_TPREL_HI:
+    FixupKind =3D Mips::fixup_Mips_TPREL_HI;
+    break;
+  case MCSymbolRefExpr::VK_Mips_TPREL_LO:
+    FixupKind =3D Mips::fixup_Mips_TPREL_LO;
+    break;
+  default:
+    break;
+  } // switch
+
+  Fixups.push_back(MCFixup::Create(0, MO.getExpr(), MCFixupKind(FixupKind)=
));
+
+  // All of the information is in the fixup.
+  return 0;
+}
+
+/// getMemEncoding - Return binary encoding of memory related operand.
+/// If the offset operand requires relocation, record the relocation.
+unsigned
+MipsMCCodeEmitter::getMemEncoding(const MCInst &MI, unsigned OpNo,
+                                  SmallVectorImpl<MCFixup> &Fixups) const {
+  // Base register is encoded in bits 20-16, offset is encoded in bits 15-=
0.
+  assert(MI.getOperand(OpNo).isReg());
+  unsigned RegBits =3D getMachineOpValue(MI, MI.getOperand(OpNo),Fixups) <=
< 16;
+  unsigned OffBits =3D getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups=
);
+
+  return (OffBits & 0xFFFF) | RegBits;
+}
+
+unsigned
+MipsMCCodeEmitter::getSizeExtEncoding(const MCInst &MI, unsigned OpNo,
+                                      SmallVectorImpl<MCFixup> &Fixups) co=
nst {
+  assert(MI.getOperand(OpNo).isImm());
+  unsigned SizeEncoding =3D getMachineOpValue(MI, MI.getOperand(OpNo), Fix=
ups);
+  return SizeEncoding - 1;
+}
+
+// FIXME: should be called getMSBEncoding
+//
+unsigned
+MipsMCCodeEmitter::getSizeInsEncoding(const MCInst &MI, unsigned OpNo,
+                                      SmallVectorImpl<MCFixup> &Fixups) co=
nst {
+  assert(MI.getOperand(OpNo-1).isImm());
+  assert(MI.getOperand(OpNo).isImm());
+  unsigned Position =3D getMachineOpValue(MI, MI.getOperand(OpNo-1), Fixup=
s);
+  unsigned Size =3D getMachineOpValue(MI, MI.getOperand(OpNo), Fixups);
+
+  return Position + Size - 1;
+}
+
+#include "MipsGenMCCodeEmitter.inc"
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsMCTargetDesc.cpp - Mips Target Descriptions ---------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsMCTargetDesc.cpp - Mips Target Descriptions ------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "MipsMCAsmInfo.h"
 #include "MipsMCTargetDesc.h"
-#include "MipsMCAsmInfo.h"
 #include "InstPrinter/MipsInstPrinter.h"
 #include "llvm/MC/MachineLocation.h"
 #include "llvm/MC/MCCodeGenInfo.h"
@@ -20,6 +20,7 @@
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 #define GET_INSTRINFO_MC_DESC
@@ -63,19 +64,24 @@
 }
=20
 static MCCodeGenInfo *createMipsMCCodeGenInfo(StringRef TT, Reloc::Model R=
M,
-                                              CodeModel::Model CM) {
+                                              CodeModel::Model CM,
+                                              CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
-  if (RM =3D=3D Reloc::Default)
+  if (CM =3D=3D CodeModel::JITDefault)
+    RM =3D Reloc::Static;
+  else if (RM =3D=3D Reloc::Default)
     RM =3D Reloc::PIC_;
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
 static MCInstPrinter *createMipsMCInstPrinter(const Target &T,
                                               unsigned SyntaxVariant,
                                               const MCAsmInfo &MAI,
+                                              const MCInstrInfo &MII,
+                                              const MCRegisterInfo &MRI,
                                               const MCSubtargetInfo &STI) {
-  return new MipsInstPrinter(MAI);
+  return new MipsInstPrinter(MAI, MII, MRI);
 }
=20
 static MCStreamer *createMCStreamer(const Target &T, StringRef TT,
@@ -110,7 +116,8 @@
   TargetRegistry::RegisterMCInstrInfo(TheMipsTarget, createMipsMCInstrInfo=
);
   TargetRegistry::RegisterMCInstrInfo(TheMipselTarget, createMipsMCInstrIn=
fo);
   TargetRegistry::RegisterMCInstrInfo(TheMips64Target, createMipsMCInstrIn=
fo);
-  TargetRegistry::RegisterMCInstrInfo(TheMips64elTarget, createMipsMCInstr=
Info);
+  TargetRegistry::RegisterMCInstrInfo(TheMips64elTarget,
+                                      createMipsMCInstrInfo);
=20
   // Register the MC register info.
   TargetRegistry::RegisterMCRegInfo(TheMipsTarget, createMipsMCRegisterInf=
o);
@@ -120,25 +127,31 @@
                                     createMipsMCRegisterInfo);
=20
   // Register the MC Code Emitter
-  TargetRegistry::RegisterMCCodeEmitter(TheMipsTarget, createMipsMCCodeEmi=
tter);
+  TargetRegistry::RegisterMCCodeEmitter(TheMipsTarget,
+                                        createMipsMCCodeEmitterEB);
   TargetRegistry::RegisterMCCodeEmitter(TheMipselTarget,
-                                        createMipsMCCodeEmitter);
+                                        createMipsMCCodeEmitterEL);
   TargetRegistry::RegisterMCCodeEmitter(TheMips64Target,
-                                        createMipsMCCodeEmitter);
+                                        createMipsMCCodeEmitterEB);
   TargetRegistry::RegisterMCCodeEmitter(TheMips64elTarget,
-                                        createMipsMCCodeEmitter);
+                                        createMipsMCCodeEmitterEL);
=20
   // Register the object streamer.
   TargetRegistry::RegisterMCObjectStreamer(TheMipsTarget, createMCStreamer=
);
   TargetRegistry::RegisterMCObjectStreamer(TheMipselTarget, createMCStream=
er);
   TargetRegistry::RegisterMCObjectStreamer(TheMips64Target, createMCStream=
er);
-  TargetRegistry::RegisterMCObjectStreamer(TheMips64elTarget, createMCStre=
amer);
+  TargetRegistry::RegisterMCObjectStreamer(TheMips64elTarget,
+                                           createMCStreamer);
=20
   // Register the asm backend.
-  TargetRegistry::RegisterMCAsmBackend(TheMipsTarget, createMipsAsmBackend=
);
-  TargetRegistry::RegisterMCAsmBackend(TheMipselTarget, createMipsAsmBacke=
nd);
-  TargetRegistry::RegisterMCAsmBackend(TheMips64Target, createMipsAsmBacke=
nd);
-  TargetRegistry::RegisterMCAsmBackend(TheMips64elTarget, createMipsAsmBac=
kend);
+  TargetRegistry::RegisterMCAsmBackend(TheMipsTarget,
+                                       createMipsAsmBackendEB32);
+  TargetRegistry::RegisterMCAsmBackend(TheMipselTarget,
+                                       createMipsAsmBackendEL32);
+  TargetRegistry::RegisterMCAsmBackend(TheMips64Target,
+                                       createMipsAsmBackendEB64);
+  TargetRegistry::RegisterMCAsmBackend(TheMips64elTarget,
+                                       createMipsAsmBackendEL64);
=20
   // Register the MC subtarget info.
   TargetRegistry::RegisterMCSubtargetInfo(TheMipsTarget,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/MCTa=
rgetDesc/MipsMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -14,25 +14,40 @@
 #ifndef MIPSMCTARGETDESC_H
 #define MIPSMCTARGETDESC_H
=20
+#include "llvm/Support/DataTypes.h"
+
 namespace llvm {
 class MCAsmBackend;
-class MCInstrInfo;
 class MCCodeEmitter;
 class MCContext;
+class MCInstrInfo;
+class MCObjectWriter;
 class MCSubtargetInfo;
 class StringRef;
 class Target;
+class raw_ostream;
=20
 extern Target TheMipsTarget;
 extern Target TheMipselTarget;
 extern Target TheMips64Target;
 extern Target TheMips64elTarget;
=20
-MCCodeEmitter *createMipsMCCodeEmitter(const MCInstrInfo &MCII,
-                                       const MCSubtargetInfo &STI,
-                                       MCContext &Ctx);
+MCCodeEmitter *createMipsMCCodeEmitterEB(const MCInstrInfo &MCII,
+                                         const MCSubtargetInfo &STI,
+                                         MCContext &Ctx);
+MCCodeEmitter *createMipsMCCodeEmitterEL(const MCInstrInfo &MCII,
+                                         const MCSubtargetInfo &STI,
+                                         MCContext &Ctx);
=20
-MCAsmBackend *createMipsAsmBackend(const Target &T, StringRef TT);
+MCAsmBackend *createMipsAsmBackendEB32(const Target &T, StringRef TT);
+MCAsmBackend *createMipsAsmBackendEL32(const Target &T, StringRef TT);
+MCAsmBackend *createMipsAsmBackendEB64(const Target &T, StringRef TT);
+MCAsmBackend *createMipsAsmBackendEL64(const Target &T, StringRef TT);
+
+MCObjectWriter *createMipsELFObjectWriter(raw_ostream &OS,
+                                          uint8_t OSABI,
+                                          bool IsLittleEndian,
+                                          bool Is64Bit);
 } // End llvm namespace
=20
 // Defines symbolic names for Mips registers.  This defines a mapping from
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
.h
--- a/head/contrib/llvm/lib/Target/Mips/Mips.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/lib/Target/Mips/Mips.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -21,8 +21,6 @@
 namespace llvm {
   class MipsTargetMachine;
   class FunctionPass;
-  class MachineCodeEmitter;
-  class formatted_raw_ostream;
=20
   FunctionPass *createMipsISelDag(MipsTargetMachine &TM);
   FunctionPass *createMipsDelaySlotFillerPass(MipsTargetMachine &TM);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
.td
--- a/head/contrib/llvm/lib/Target/Mips/Mips.td	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/Target/Mips/Mips.td	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- Mips.td - Describe the Mips Target Machine ----------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- Mips.td - Describe the Mips Target Machine ---------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -63,7 +63,7 @@
                                 [FeatureCondMov, FeatureBitCount]>;
 def FeatureMips32r2    : SubtargetFeature<"mips32r2", "MipsArchVersion",
                                 "Mips32r2", "Mips32r2 ISA Support",
-                                [FeatureMips32, FeatureSEInReg]>;
+                                [FeatureMips32, FeatureSEInReg, FeatureSwa=
p]>;
 def FeatureMips64      : SubtargetFeature<"mips64", "MipsArchVersion",
                                 "Mips64", "Mips64 ISA Support",
                                 [FeatureGP64Bit, FeatureFP64Bit,
@@ -79,9 +79,9 @@
 class Proc<string Name, list<SubtargetFeature> Features>
  : Processor<Name, MipsGenericItineraries, Features>;
=20
-def : Proc<"mips32r1", [FeatureMips32]>;
-def : Proc<"4ke", [FeatureMips32r2]>;
-def : Proc<"mips64r1", [FeatureMips64]>;
+def : Proc<"mips32", [FeatureMips32]>;
+def : Proc<"mips32r2", [FeatureMips32r2]>;
+def : Proc<"mips64", [FeatureMips64]>;
 def : Proc<"mips64r2", [FeatureMips64r2]>;
=20
 def MipsAsmWriter : AsmWriter {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
64InstrInfo.td
--- a/head/contrib/llvm/lib/Target/Mips/Mips64InstrInfo.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/Mips64InstrInfo.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -25,68 +25,48 @@
=20
 // Transformation Function - get Imm - 32.
 def Subtract32 : SDNodeXForm<imm, [{
-  return getI32Imm((unsigned)N->getZExtValue() - 32);
+  return getImm(N, (unsigned)N->getZExtValue() - 32);
 }]>;
=20
-// imm32_63 predicate - True if imm is in range [32, 63].
-def imm32_63 : ImmLeaf<i64,
-                       [{return (int32_t)Imm >=3D 32 && (int32_t)Imm < 64;=
}],
-                       Subtract32>;
+// shamt must fit in 6 bits.
+def immZExt6 : ImmLeaf<i32, [{return Imm =3D=3D (Imm & 0x3f);}]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Instructions specific format
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Shifts
-class LogicR_shift_rotate_imm64<bits<6> func, bits<5> _rs, string instr_as=
m,
-                                SDNode OpNode, PatFrag PF>:
-  FR<0x00, func, (outs CPU64Regs:$rd), (ins CPU64Regs:$rt, shamt_64:$shamt=
),
-     !strconcat(instr_asm, "\t$rd, $rt, $shamt"),
-     [(set CPU64Regs:$rd, (OpNode CPU64Regs:$rt, (i64 PF:$shamt)))],
-     IIAlu> {
-  let rs =3D _rs;
+// 64-bit shift instructions.
+class shift_rotate_imm64<bits<6> func, bits<5> isRotate, string instr_asm,
+                         SDNode OpNode>:
+  shift_rotate_imm<func, isRotate, instr_asm, OpNode, immZExt6, shamt,
+                   CPU64Regs>;
+
+// Mul, Div
+class Mult64<bits<6> func, string instr_asm, InstrItinClass itin>:
+  Mult<func, instr_asm, itin, CPU64Regs, [HI64, LO64]>;
+class Div64<SDNode op, bits<6> func, string instr_asm, InstrItinClass itin=
>:
+  Div<op, func, instr_asm, itin, CPU64Regs, [HI64, LO64]>;
+
+multiclass Atomic2Ops64<PatFrag Op, string Opstr> {
+  def #NAME# : Atomic2Ops<Op, Opstr, CPU64Regs, CPURegs>, Requires<[NotN64=
]>;
+  def _P8    : Atomic2Ops<Op, Opstr, CPU64Regs, CPU64Regs>, Requires<[IsN6=
4]>;
 }
=20
-class LogicR_shift_rotate_reg64<bits<6> func, bits<5> _shamt, string instr=
_asm,
-                                SDNode OpNode>:
-  FR<0x00, func, (outs CPU64Regs:$rd), (ins CPU64Regs:$rs, CPU64Regs:$rt),
-     !strconcat(instr_asm, "\t$rd, $rt, $rs"),
-     [(set CPU64Regs:$rd, (OpNode CPU64Regs:$rt, CPU64Regs:$rs))], IIAlu> {
-  let shamt =3D _shamt;
+multiclass AtomicCmpSwap64<PatFrag Op, string Width>  {
+  def #NAME# : AtomicCmpSwap<Op, Width, CPU64Regs, CPURegs>, Requires<[Not=
N64]>;
+  def _P8    : AtomicCmpSwap<Op, Width, CPU64Regs, CPU64Regs>,
+               Requires<[IsN64]>;
 }
=20
-// Mul, Div
-let rd =3D 0, shamt =3D 0, Defs =3D [HI64, LO64] in {
-  let isCommutable =3D 1 in
-  class Mul64<bits<6> func, string instr_asm, InstrItinClass itin>:
-    FR<0x00, func, (outs), (ins CPU64Regs:$rs, CPU64Regs:$rt),
-       !strconcat(instr_asm, "\t$rs, $rt"), [], itin>;
-
-  class Div64<SDNode op, bits<6> func, string instr_asm, InstrItinClass it=
in>:
-              FR<0x00, func, (outs), (ins CPU64Regs:$rs, CPU64Regs:$rt),
-              !strconcat(instr_asm, "\t$$zero, $rs, $rt"),
-              [(op CPU64Regs:$rs, CPU64Regs:$rt)], itin>;
-}
-
-// Move from Hi/Lo
-let shamt =3D 0 in {
-let rs =3D 0, rt =3D 0 in
-class MoveFromLOHI64<bits<6> func, string instr_asm>:
-  FR<0x00, func, (outs CPU64Regs:$rd), (ins),
-     !strconcat(instr_asm, "\t$rd"), [], IIHiLo>;
-
-let rt =3D 0, rd =3D 0 in
-class MoveToLOHI64<bits<6> func, string instr_asm>:
-  FR<0x00, func, (outs), (ins CPU64Regs:$rs),
-     !strconcat(instr_asm, "\t$rs"), [], IIHiLo>;
-}
-
-// Count Leading Ones/Zeros in Word
-class CountLeading64<bits<6> func, string instr_asm, list<dag> pattern>:
-  FR<0x1c, func, (outs CPU64Regs:$rd), (ins CPU64Regs:$rs),
-     !strconcat(instr_asm, "\t$rd, $rs"), pattern, IIAlu>,
-     Requires<[HasBitCount]> {
-  let shamt =3D 0;
-  let rt =3D rd;
+let usesCustomInserter =3D 1, Predicates =3D [HasMips64] in {
+  defm ATOMIC_LOAD_ADD_I64  : Atomic2Ops64<atomic_load_add_64, "load_add_6=
4">;
+  defm ATOMIC_LOAD_SUB_I64  : Atomic2Ops64<atomic_load_sub_64, "load_sub_6=
4">;
+  defm ATOMIC_LOAD_AND_I64  : Atomic2Ops64<atomic_load_and_64, "load_and_6=
4">;
+  defm ATOMIC_LOAD_OR_I64   : Atomic2Ops64<atomic_load_or_64, "load_or_64"=
>;
+  defm ATOMIC_LOAD_XOR_I64  : Atomic2Ops64<atomic_load_xor_64, "load_xor_6=
4">;
+  defm ATOMIC_LOAD_NAND_I64 : Atomic2Ops64<atomic_load_nand_64, "load_nand=
_64">;
+  defm ATOMIC_SWAP_I64      : Atomic2Ops64<atomic_swap_64, "swap_64">;
+  defm ATOMIC_CMP_SWAP_I64  : AtomicCmpSwap64<atomic_cmp_swap_64, "64">;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -101,6 +81,7 @@
 def SLTiu64  : SetCC_I<0x0b, "sltiu", setult, simm16_64, immSExt16, CPU64R=
egs>;
 def ORi64    : ArithLogicI<0x0d, "ori", or, uimm16_64, immZExt16, CPU64Reg=
s>;
 def XORi64   : ArithLogicI<0x0e, "xori", xor, uimm16_64, immZExt16, CPU64R=
egs>;
+def LUi64    : LoadUpper<0x0f, "lui", CPU64Regs, uimm16_64>;
=20
 /// Arithmetic Instructions (3-Operand, R-Type)
 def DADDu    : ArithLogicR<0x00, 0x2d, "daddu", add, IIAlu, CPU64Regs, 1>;
@@ -113,26 +94,21 @@
 def NOR64    : LogicNOR<0x00, 0x27, "nor", CPU64Regs>;
=20
 /// Shift Instructions
-def DSLL     : LogicR_shift_rotate_imm64<0x38, 0x00, "dsll", shl, immZExt5=
>;
-def DSRL     : LogicR_shift_rotate_imm64<0x3a, 0x00, "dsrl", srl, immZExt5=
>;
-def DSRA     : LogicR_shift_rotate_imm64<0x3b, 0x00, "dsra", sra, immZExt5=
>;
-def DSLL32   : LogicR_shift_rotate_imm64<0x3c, 0x00, "dsll32", shl, imm32_=
63>;
-def DSRL32   : LogicR_shift_rotate_imm64<0x3e, 0x00, "dsrl32", srl, imm32_=
63>;
-def DSRA32   : LogicR_shift_rotate_imm64<0x3f, 0x00, "dsra32", sra, imm32_=
63>;
-def DSLLV    : LogicR_shift_rotate_reg64<0x24, 0x00, "dsllv", shl>;
-def DSRLV    : LogicR_shift_rotate_reg64<0x26, 0x00, "dsrlv", srl>;
-def DSRAV    : LogicR_shift_rotate_reg64<0x27, 0x00, "dsrav", sra>;
+def DSLL     : shift_rotate_imm64<0x38, 0x00, "dsll", shl>;
+def DSRL     : shift_rotate_imm64<0x3a, 0x00, "dsrl", srl>;
+def DSRA     : shift_rotate_imm64<0x3b, 0x00, "dsra", sra>;
+def DSLLV    : shift_rotate_reg<0x24, 0x00, "dsllv", shl, CPU64Regs>;
+def DSRLV    : shift_rotate_reg<0x26, 0x00, "dsrlv", srl, CPU64Regs>;
+def DSRAV    : shift_rotate_reg<0x27, 0x00, "dsrav", sra, CPU64Regs>;
=20
 // Rotate Instructions
 let Predicates =3D [HasMips64r2] in {
-  def DROTR    : LogicR_shift_rotate_imm64<0x3a, 0x01, "drotr", rotr, immZ=
Ext5>;
-  def DROTR32  : LogicR_shift_rotate_imm64<0x3e, 0x01, "drotr32", rotr,
-                                           imm32_63>;
-  def DROTRV   : LogicR_shift_rotate_reg64<0x16, 0x01, "drotrv", rotr>;
+  def DROTR    : shift_rotate_imm64<0x3a, 0x01, "drotr", rotr>;
+  def DROTRV   : shift_rotate_reg<0x16, 0x01, "drotrv", rotr, CPU64Regs>;
 }
=20
 /// Load and Store Instructions
-///  aligned=20
+///  aligned
 defm LB64    : LoadM64<0x20, "lb",  sextloadi8>;
 defm LBu64   : LoadM64<0x24, "lbu", zextloadi8>;
 defm LH64    : LoadM64<0x21, "lh",  sextloadi16_a>;
@@ -154,7 +130,14 @@
 defm ULD       : LoadM64<0x37, "uld",  load_u, 1>;
 defm USD       : StoreM64<0x3f, "usd", store_u, 1>;
=20
+/// Load-linked, Store-conditional
+def LLD    : LLBase<0x34, "lld", CPU64Regs, mem>, Requires<[NotN64]>;
+def LLD_P8 : LLBase<0x34, "lld", CPU64Regs, mem64>, Requires<[IsN64]>;
+def SCD    : SCBase<0x3c, "scd", CPU64Regs, mem>, Requires<[NotN64]>;
+def SCD_P8 : SCBase<0x3c, "scd", CPU64Regs, mem64>, Requires<[IsN64]>;
+
 /// Jump and Branch Instructions
+def JR64   : JumpFR<0x00, 0x08, "jr", CPU64Regs>;
 def BEQ64  : CBranch<0x04, "beq", seteq, CPU64Regs>;
 def BNE64  : CBranch<0x05, "bne", setne, CPU64Regs>;
 def BGEZ64 : CBranchZero<0x01, 1, "bgez", setge, CPU64Regs>;
@@ -162,46 +145,104 @@
 def BLEZ64 : CBranchZero<0x07, 0, "blez", setle, CPU64Regs>;
 def BLTZ64 : CBranchZero<0x01, 0, "bltz", setlt, CPU64Regs>;
=20
+def JALR64 : JumpLinkReg<0x00, 0x09, "jalr", CPU64Regs>;
+
 /// Multiply and Divide Instructions.
-def DMULT    : Mul64<0x1c, "dmult", IIImul>;
-def DMULTu   : Mul64<0x1d, "dmultu", IIImul>;
+def DMULT    : Mult64<0x1c, "dmult", IIImul>;
+def DMULTu   : Mult64<0x1d, "dmultu", IIImul>;
 def DSDIV    : Div64<MipsDivRem, 0x1e, "ddiv", IIIdiv>;
 def DUDIV    : Div64<MipsDivRemU, 0x1f, "ddivu", IIIdiv>;
=20
-let Defs =3D [HI64] in
-  def MTHI64  : MoveToLOHI64<0x11, "mthi">;
-let Defs =3D [LO64] in
-  def MTLO64  : MoveToLOHI64<0x13, "mtlo">;
+def MTHI64 : MoveToLOHI<0x11, "mthi", CPU64Regs, [HI64]>;
+def MTLO64 : MoveToLOHI<0x13, "mtlo", CPU64Regs, [LO64]>;
+def MFHI64 : MoveFromLOHI<0x10, "mfhi", CPU64Regs, [HI64]>;
+def MFLO64 : MoveFromLOHI<0x12, "mflo", CPU64Regs, [LO64]>;
=20
-let Uses =3D [HI64] in
-  def MFHI64  : MoveFromLOHI64<0x10, "mfhi">;
-let Uses =3D [LO64] in
-  def MFLO64  : MoveFromLOHI64<0x12, "mflo">;
+/// Sign Ext In Register Instructions.
+def SEB64 : SignExtInReg<0x10, "seb", i8, CPU64Regs>;
+def SEH64 : SignExtInReg<0x18, "seh", i16, CPU64Regs>;
=20
 /// Count Leading
-def DCLZ : CountLeading64<0x24, "dclz",
-                          [(set CPU64Regs:$rd, (ctlz CPU64Regs:$rs))]>;
-def DCLO : CountLeading64<0x25, "dclo",
-                          [(set CPU64Regs:$rd, (ctlz (not CPU64Regs:$rs)))=
]>;
+def DCLZ : CountLeading0<0x24, "dclz", CPU64Regs>;
+def DCLO : CountLeading1<0x25, "dclo", CPU64Regs>;
+
+/// Double Word Swap Bytes/HalfWords
+def DSBH : SubwordSwap<0x24, 0x2, "dsbh", CPU64Regs>;
+def DSHD : SubwordSwap<0x24, 0x5, "dshd", CPU64Regs>;
+
+def LEA_ADDiu64 : EffectiveAddress<"daddiu\t$rt, $addr", CPU64Regs, mem_ea=
_64>;
+
+let Uses =3D [SP_64] in
+def DynAlloc64 : EffectiveAddress<"daddiu\t$rt, $addr", CPU64Regs, mem_ea_=
64>,
+                 Requires<[IsN64]>;
+
+def RDHWR64 : ReadHardware<CPU64Regs, HWRegs64>;
+
+def DEXT : ExtBase<3, "dext", CPU64Regs>;
+def DINS : InsBase<7, "dins", CPU64Regs>;
+
+def DSLL64_32 : FR<0x3c, 0x00, (outs CPU64Regs:$rd), (ins CPURegs:$rt),
+                   "dsll\t$rd, $rt, 32", [], IIAlu>;
+
+def SLL64_32 : FR<0x0, 0x00, (outs CPU64Regs:$rd), (ins CPURegs:$rt),
+                  "sll\t$rd, $rt, 0", [], IIAlu>;
+def SLL64_64 : FR<0x0, 0x00, (outs CPU64Regs:$rd), (ins CPU64Regs:$rt),
+                  "sll\t$rd, $rt, 0", [], IIAlu>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Arbitrary patterns that map to one or more instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-// Small immediates
-def : Pat<(i64 immSExt16:$in),
-          (DADDiu ZERO_64, imm:$in)>;
-def : Pat<(i64 immZExt16:$in),
-          (ORi64 ZERO_64, imm:$in)>;
-
-// zextloadi32_u
-def : Pat<(zextloadi32_u addr:$a), (DSRL (DSLL (ULW64_P8 addr:$a), 32), 32=
)>,
-      Requires<[IsN64]>;
-def : Pat<(zextloadi32_u addr:$a), (DSRL (DSLL (ULW64 addr:$a), 32), 32)>,
-      Requires<[NotN64]>;
+// extended loads
+let Predicates =3D [NotN64] in {
+  def : Pat<(i64 (extloadi1  addr:$src)), (LB64 addr:$src)>;
+  def : Pat<(i64 (extloadi8  addr:$src)), (LB64 addr:$src)>;
+  def : Pat<(i64 (extloadi16_a addr:$src)), (LH64 addr:$src)>;
+  def : Pat<(i64 (extloadi16_u addr:$src)), (ULH64 addr:$src)>;
+  def : Pat<(i64 (extloadi32_a addr:$src)), (LW64 addr:$src)>;
+  def : Pat<(i64 (extloadi32_u addr:$src)), (ULW64 addr:$src)>;
+  def : Pat<(zextloadi32_u addr:$a), (DSRL (DSLL (ULW64 addr:$a), 32), 32)=
>;
+}
+let Predicates =3D [IsN64] in {
+  def : Pat<(i64 (extloadi1  addr:$src)), (LB64_P8 addr:$src)>;
+  def : Pat<(i64 (extloadi8  addr:$src)), (LB64_P8 addr:$src)>;
+  def : Pat<(i64 (extloadi16_a addr:$src)), (LH64_P8 addr:$src)>;
+  def : Pat<(i64 (extloadi16_u addr:$src)), (ULH64_P8 addr:$src)>;
+  def : Pat<(i64 (extloadi32_a addr:$src)), (LW64_P8 addr:$src)>;
+  def : Pat<(i64 (extloadi32_u addr:$src)), (ULW64_P8 addr:$src)>;
+  def : Pat<(zextloadi32_u addr:$a), (DSRL (DSLL (ULW64_P8 addr:$a), 32), =
32)>;
+}
=20
 // hi/lo relocs
-def : Pat<(i64 (MipsLo tglobaladdr:$in)), (DADDiu ZERO_64, tglobaladdr:$in=
)>;
+def : Pat<(MipsHi tglobaladdr:$in), (LUi64 tglobaladdr:$in)>;
+def : Pat<(MipsHi tblockaddress:$in), (LUi64 tblockaddress:$in)>;
+def : Pat<(MipsHi tjumptable:$in), (LUi64 tjumptable:$in)>;
+def : Pat<(MipsHi tconstpool:$in), (LUi64 tconstpool:$in)>;
+def : Pat<(MipsHi tglobaltlsaddr:$in), (LUi64 tglobaltlsaddr:$in)>;
+
+def : Pat<(MipsLo tglobaladdr:$in), (DADDiu ZERO_64, tglobaladdr:$in)>;
+def : Pat<(MipsLo tblockaddress:$in), (DADDiu ZERO_64, tblockaddress:$in)>;
+def : Pat<(MipsLo tjumptable:$in), (DADDiu ZERO_64, tjumptable:$in)>;
+def : Pat<(MipsLo tconstpool:$in), (DADDiu ZERO_64, tconstpool:$in)>;
+def : Pat<(MipsLo tglobaltlsaddr:$in), (DADDiu ZERO_64, tglobaltlsaddr:$in=
)>;
+
+def : Pat<(add CPU64Regs:$hi, (MipsLo tglobaladdr:$lo)),
+          (DADDiu CPU64Regs:$hi, tglobaladdr:$lo)>;
+def : Pat<(add CPU64Regs:$hi, (MipsLo tblockaddress:$lo)),
+          (DADDiu CPU64Regs:$hi, tblockaddress:$lo)>;
+def : Pat<(add CPU64Regs:$hi, (MipsLo tjumptable:$lo)),
+          (DADDiu CPU64Regs:$hi, tjumptable:$lo)>;
+def : Pat<(add CPU64Regs:$hi, (MipsLo tconstpool:$lo)),
+          (DADDiu CPU64Regs:$hi, tconstpool:$lo)>;
+def : Pat<(add CPU64Regs:$hi, (MipsLo tglobaltlsaddr:$lo)),
+          (DADDiu CPU64Regs:$hi, tglobaltlsaddr:$lo)>;
+
+def : WrapperPat<tglobaladdr, DADDiu, CPU64Regs>;
+def : WrapperPat<tconstpool, DADDiu, CPU64Regs>;
+def : WrapperPat<texternalsym, DADDiu, CPU64Regs>;
+def : WrapperPat<tblockaddress, DADDiu, CPU64Regs>;
+def : WrapperPat<tjumptable, DADDiu, CPU64Regs>;
+def : WrapperPat<tglobaltlsaddr, DADDiu, CPU64Regs>;
=20
 defm : BrcondPats<CPU64Regs, BEQ64, BNE64, SLT64, SLTu64, SLTi64, SLTiu64,
                   ZERO_64>;
@@ -212,3 +253,21 @@
 defm : SetgtPats<CPU64Regs, SLT64, SLTu64>;
 defm : SetgePats<CPU64Regs, SLT64, SLTu64>;
 defm : SetgeImmPats<CPU64Regs, SLTi64, SLTiu64>;
+
+// select MipsDynAlloc
+def : Pat<(MipsDynAlloc addr:$f), (DynAlloc64 addr:$f)>, Requires<[IsN64]>;
+
+// truncate
+def : Pat<(i32 (trunc CPU64Regs:$src)),
+          (SLL (EXTRACT_SUBREG CPU64Regs:$src, sub_32), 0)>, Requires<[IsN=
64]>;
+
+// 32-to-64-bit extension
+def : Pat<(i64 (anyext CPURegs:$src)), (SLL64_32 CPURegs:$src)>;
+def : Pat<(i64 (zext CPURegs:$src)), (DSRL (DSLL64_32 CPURegs:$src), 32)>;
+def : Pat<(i64 (sext CPURegs:$src)), (SLL64_32 CPURegs:$src)>;
+
+// Sign extend in register
+def : Pat<(i64 (sext_inreg CPU64Regs:$src, i32)), (SLL64_64 CPU64Regs:$src=
)>;
+
+// bswap pattern
+def : Pat<(bswap CPU64Regs:$rt), (DSHD (DSBH CPU64Regs:$rt))>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
AsmPrinter.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsAsmPrinter.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsAsmPrinter.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsAsmPrinter.cpp - Mips LLVM assembly writer -------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer ------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -16,10 +16,12 @@
 #include "MipsAsmPrinter.h"
 #include "Mips.h"
 #include "MipsInstrInfo.h"
-#include "MipsMachineFunction.h"
-#include "MipsMCInstLower.h"
-#include "MipsMCSymbolRefExpr.h"
 #include "InstPrinter/MipsInstPrinter.h"
+#include "MCTargetDesc/MipsBaseInfo.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Analysis/DebugInfo.h"
 #include "llvm/BasicBlock.h"
 #include "llvm/Instructions.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
@@ -27,55 +29,125 @@
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
+#include "llvm/Instructions.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCSymbol.h"
+#include "llvm/Support/TargetRegistry.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/Mangler.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetLoweringObjectFile.h"
 #include "llvm/Target/TargetOptions.h"
-#include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
-#include "llvm/ADT/Twine.h"
-#include "llvm/Support/TargetRegistry.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Analysis/DebugInfo.h"
=20
 using namespace llvm;
=20
-static bool isUnalignedLoadStore(unsigned Opc) {
-  return Opc =3D=3D Mips::ULW    || Opc =3D=3D Mips::ULH    || Opc =3D=3D =
Mips::ULHu ||
-         Opc =3D=3D Mips::USW    || Opc =3D=3D Mips::USH    ||
-         Opc =3D=3D Mips::ULW_P8 || Opc =3D=3D Mips::ULH_P8 || Opc =3D=3D =
Mips::ULHu_P8 ||
-         Opc =3D=3D Mips::USW_P8 || Opc =3D=3D Mips::USH_P8;
+void MipsAsmPrinter::EmitInstrWithMacroNoAT(const MachineInstr *MI) {
+  MCInst TmpInst;
+
+  MCInstLowering.Lower(MI, TmpInst);
+  OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
+  if (MipsFI->getEmitNOAT())
+    OutStreamer.EmitRawText(StringRef("\t.set\tat"));
+  OutStreamer.EmitInstruction(TmpInst);
+  if (MipsFI->getEmitNOAT())
+    OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
+  OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
+}
+
+bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
+  MipsFI =3D MF.getInfo<MipsFunctionInfo>();
+  AsmPrinter::runOnMachineFunction(MF);
+  return true;
 }
=20
 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
-  SmallString<128> Str;
-  raw_svector_ostream OS(Str);
+  if (MI->isDebugValue()) {
+    SmallString<128> Str;
+    raw_svector_ostream OS(Str);
=20
-  if (MI->isDebugValue()) {
     PrintDebugValueComment(MI, OS);
     return;
   }
=20
-  MipsMCInstLower MCInstLowering(Mang, *MF, *this);
   unsigned Opc =3D MI->getOpcode();
   MCInst TmpInst0;
-  MCInstLowering.Lower(MI, TmpInst0);
- =20
-  // Enclose unaligned load or store with .macro & .nomacro directives.
-  if (isUnalignedLoadStore(Opc)) {
-    MCInst Directive;
-    Directive.setOpcode(Mips::MACRO);
-    OutStreamer.EmitInstruction(Directive);
-    OutStreamer.EmitInstruction(TmpInst0);
-    Directive.setOpcode(Mips::NOMACRO);
-    OutStreamer.EmitInstruction(Directive);
+  SmallVector<MCInst, 4> MCInsts;
+
+  switch (Opc) {
+  case Mips::ULW:
+  case Mips::ULH:
+  case Mips::ULHu:
+  case Mips::USW:
+  case Mips::USH:
+  case Mips::ULW_P8:
+  case Mips::ULH_P8:
+  case Mips::ULHu_P8:
+  case Mips::USW_P8:
+  case Mips::USH_P8:
+  case Mips::ULD:
+  case Mips::ULW64:
+  case Mips::ULH64:
+  case Mips::ULHu64:
+  case Mips::USD:
+  case Mips::USW64:
+  case Mips::USH64:
+  case Mips::ULD_P8:
+  case Mips::ULW64_P8:
+  case Mips::ULH64_P8:
+  case Mips::ULHu64_P8:
+  case Mips::USD_P8:
+  case Mips::USW64_P8:
+  case Mips::USH64_P8: {
+    if (OutStreamer.hasRawTextSupport()) {
+      EmitInstrWithMacroNoAT(MI);
+      return;
+    }
+
+    MCInstLowering.LowerUnalignedLoadStore(MI, MCInsts);
+    for (SmallVector<MCInst, 4>::iterator I =3D MCInsts.begin(); I
+           !=3D MCInsts.end(); ++I)
+      OutStreamer.EmitInstruction(*I);
+
     return;
   }
+  case Mips::CPRESTORE: {
+    const MachineOperand &MO =3D MI->getOperand(0);
+    assert(MO.isImm() && "CPRESTORE's operand must be an immediate.");
+    int64_t Offset =3D MO.getImm();
=20
+    if (OutStreamer.hasRawTextSupport()) {
+      if (!isInt<16>(Offset)) {
+        EmitInstrWithMacroNoAT(MI);
+        return;
+      }
+    } else {
+      MCInstLowering.LowerCPRESTORE(Offset, MCInsts);
+
+      for (SmallVector<MCInst, 4>::iterator I =3D MCInsts.begin();
+           I !=3D MCInsts.end(); ++I)
+        OutStreamer.EmitInstruction(*I);
+
+      return;
+    }
+
+    break;
+  }
+  case Mips::SETGP01: {
+    MCInstLowering.LowerSETGP01(MI, MCInsts);
+
+    for (SmallVector<MCInst, 4>::iterator I =3D MCInsts.begin();
+         I !=3D MCInsts.end(); ++I)
+      OutStreamer.EmitInstruction(*I);
+
+    return;
+  }
+  default:
+    break;
+  }
+
+  MCInstLowering.Lower(MI, TmpInst0);
   OutStreamer.EmitInstruction(TmpInst0);
 }
=20
@@ -138,7 +210,7 @@
     if (Mips::CPURegsRegisterClass->contains(Reg))
       break;
=20
-    unsigned RegNum =3D MipsRegisterInfo::getRegisterNumbering(Reg);
+    unsigned RegNum =3D getMipsRegisterNumbering(Reg);
     if (Mips::AFGR64RegisterClass->contains(Reg)) {
       FPUBitmask |=3D (3 << RegNum);
       CSFPRegsSize +=3D AFGR64RegSize;
@@ -153,7 +225,7 @@
   // Set CPU Bitmask.
   for (; i !=3D e; ++i) {
     unsigned Reg =3D CSI[i].getReg();
-    unsigned RegNum =3D MipsRegisterInfo::getRegisterNumbering(Reg);
+    unsigned RegNum =3D getMipsRegisterNumbering(Reg);
     CPUBitmask |=3D (1 << RegNum);
   }
=20
@@ -177,7 +249,7 @@
 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
   O << "0x";
   for (int i =3D 7; i >=3D 0; i--)
-    O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
+    O.write_hex((Value & (0xF << (i*4))) >> (i*4));
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -192,10 +264,11 @@
   unsigned returnReg =3D RI.getRARegister();
   unsigned stackSize =3D MF->getFrameInfo()->getStackSize();
=20
-  OutStreamer.EmitRawText("\t.frame\t$" +
-           Twine(LowercaseString(MipsInstPrinter::getRegisterName(stackReg=
))) +
+  if (OutStreamer.hasRawTextSupport())
+    OutStreamer.EmitRawText("\t.frame\t$" +
+           StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
            "," + Twine(stackSize) + ",$" +
-           Twine(LowercaseString(MipsInstPrinter::getRegisterName(returnRe=
g))));
+           StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
 }
=20
 /// Emit Set directives.
@@ -205,27 +278,49 @@
   case MipsSubtarget::N32:  return "abiN32";
   case MipsSubtarget::N64:  return "abi64";
   case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
-  default: break;
+  default: llvm_unreachable("Unknown Mips ABI");;
   }
-
-  llvm_unreachable("Unknown Mips ABI");
-  return NULL;
 }
=20
 void MipsAsmPrinter::EmitFunctionEntryLabel() {
-  OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
+  if (OutStreamer.hasRawTextSupport())
+    OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
   OutStreamer.EmitLabel(CurrentFnSym);
 }
=20
 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
 /// the first basic block in the function.
 void MipsAsmPrinter::EmitFunctionBodyStart() {
+  MCInstLowering.Initialize(Mang, &MF->getContext());
+
   emitFrameDirective();
=20
-  SmallString<128> Str;
-  raw_svector_ostream OS(Str);
-  printSavedRegsBitmask(OS);
-  OutStreamer.EmitRawText(OS.str());
+  bool EmitCPLoad =3D (MF->getTarget().getRelocationModel() =3D=3D Reloc::=
PIC_) &&
+    Subtarget->isABI_O32() && MipsFI->globalBaseRegSet() &&
+    MipsFI->globalBaseRegFixed();
+
+  if (OutStreamer.hasRawTextSupport()) {
+    SmallString<128> Str;
+    raw_svector_ostream OS(Str);
+    printSavedRegsBitmask(OS);
+    OutStreamer.EmitRawText(OS.str());
+
+    OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
+
+    // Emit .cpload directive if needed.
+    if (EmitCPLoad)
+      OutStreamer.EmitRawText(StringRef("\t.cpload\t$25"));
+
+    OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
+    if (MipsFI->getEmitNOAT())
+      OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
+  } else if (EmitCPLoad) {
+    SmallVector<MCInst, 4> MCInsts;
+    MCInstLowering.LowerCPLOAD(MCInsts);
+    for (SmallVector<MCInst, 4>::iterator I =3D MCInsts.begin();
+         I !=3D MCInsts.end(); ++I)
+      OutStreamer.EmitInstruction(*I);
+  }
 }
=20
 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
@@ -234,12 +329,16 @@
   // There are instruction for this macros, but they must
   // always be at the function end, and we can't emit and
   // break with BB logic.
-  OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
-  OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
-  OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
+  if (OutStreamer.hasRawTextSupport()) {
+    if (MipsFI->getEmitNOAT())
+      OutStreamer.EmitRawText(StringRef("\t.set\tat"));
+
+    OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
+    OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
+    OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
+  }
 }
=20
-
 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
 /// exactly one predecessor and the control transfer mechanism between
 /// the predecessor and this block is a fall-through.
@@ -262,24 +361,24 @@
   // If there isn't exactly one predecessor, it can't be a fall through.
   MachineBasicBlock::const_pred_iterator PI =3D MBB->pred_begin(), PI2 =3D=
 PI;
   ++PI2;
-=20
+
   if (PI2 !=3D MBB->pred_end())
-    return false; =20
+    return false;
=20
   // The predecessor has to be immediately before this block.
   if (!Pred->isLayoutSuccessor(MBB))
     return false;
-  =20
+
   // If the block is completely empty, then it definitely does fall throug=
h.
   if (Pred->empty())
     return true;
- =20
+
   // Otherwise, check the last instruction.
   // Check if the last terminator is an unconditional branch.
   MachineBasicBlock::const_iterator I =3D Pred->end();
-  while (I !=3D Pred->begin() && !(--I)->getDesc().isTerminator()) ;
+  while (I !=3D Pred->begin() && !(--I)->isTerminator()) ;
=20
-  return !I->getDesc().isBarrier();
+  return !I->isBarrier();
 }
=20
 // Print out an operand for an inline asm expression.
@@ -300,7 +399,7 @@
                                            raw_ostream &O) {
   if (ExtraCode && ExtraCode[0])
      return true; // Unknown modifier.
-  =20
+
   const MachineOperand &MO =3D MI->getOperand(OpNum);
   assert(MO.isReg() && "unexpected inline asm memory operand");
   O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
@@ -335,7 +434,7 @@
   switch (MO.getType()) {
     case MachineOperand::MO_Register:
       O << '$'
-        << LowercaseString(MipsInstPrinter::getRegisterName(MO.getReg()));
+        << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower(=
);
       break;
=20
     case MachineOperand::MO_Immediate:
@@ -420,18 +519,23 @@
   // FIXME: Use SwitchSection.
=20
   // Tell the assembler which ABI we are using
-  OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIStrin=
g()));
+  if (OutStreamer.hasRawTextSupport())
+    OutStreamer.EmitRawText("\t.section .mdebug." +
+                            Twine(getCurrentABIString()));
=20
   // TODO: handle O64 ABI
-  if (Subtarget->isABI_EABI()) {
-    if (Subtarget->isGP32bit())
-      OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32")=
);
-    else
-      OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64")=
);
+  if (OutStreamer.hasRawTextSupport()) {
+    if (Subtarget->isABI_EABI()) {
+      if (Subtarget->isGP32bit())
+        OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32=
"));
+      else
+        OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64=
"));
+    }
   }
=20
   // return to previous section
-  OutStreamer.EmitRawText(StringRef("\t.previous"));
+  if (OutStreamer.hasRawTextSupport())
+    OutStreamer.EmitRawText(StringRef("\t.previous"));
 }
=20
 MachineLocation
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
AsmPrinter.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsAsmPrinter.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsAsmPrinter.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsAsmPrinter.h - Mips LLVM assembly writer ---------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MipsAsmPrinter.h - Mips LLVM Assembly Printer ----------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,6 +14,8 @@
 #ifndef MIPSASMPRINTER_H
 #define MIPSASMPRINTER_H
=20
+#include "MipsMachineFunction.h"
+#include "MipsMCInstLower.h"
 #include "MipsSubtarget.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/Support/Compiler.h"
@@ -22,16 +24,22 @@
 namespace llvm {
 class MCStreamer;
 class MachineInstr;
-class raw_ostream;
 class MachineBasicBlock;
 class Module;
+class raw_ostream;
=20
 class LLVM_LIBRARY_VISIBILITY MipsAsmPrinter : public AsmPrinter {
+
+  void EmitInstrWithMacroNoAT(const MachineInstr *MI);
+
+public:
+
   const MipsSubtarget *Subtarget;
- =20
-public:
+  const MipsFunctionInfo *MipsFI;
+  MipsMCInstLower MCInstLowering;
+
   explicit MipsAsmPrinter(TargetMachine &TM,  MCStreamer &Streamer)
-    : AsmPrinter(TM, Streamer) {
+    : AsmPrinter(TM, Streamer), MCInstLowering(*this) {
     Subtarget =3D &TM.getSubtarget<MipsSubtarget>();
   }
=20
@@ -39,6 +47,8 @@
     return "Mips Assembly Printer";
   }
=20
+  virtual bool runOnMachineFunction(MachineFunction &MF);
+
   void EmitInstruction(const MachineInstr *MI);
   void printSavedRegsBitmask(raw_ostream &O);
   void printHex32(unsigned int Value, raw_ostream &O);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
CallingConv.td
--- a/head/contrib/llvm/lib/Target/Mips/MipsCallingConv.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsCallingConv.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsCallingConv.td - Calling Conventions for Mips ---*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsCallingConv.td - Calling Conventions for Mips --*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -35,12 +35,18 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 def CC_MipsN : CallingConv<[
-  // FIXME: Handle byval, complex and float double parameters.
+   // Handles byval parameters.
+  CCIfByVal<CCCustom<"CC_Mips64Byval">>,
=20
-  // Promote i8/i16/i32 arguments to i64.
-  CCIfType<[i8, i16, i32], CCPromoteToType<i64>>,
+  // Promote i8/i16 arguments to i32.
+  CCIfType<[i8, i16], CCPromoteToType<i32>>,
=20
   // Integer arguments are passed in integer registers.
+  CCIfType<[i32], CCAssignToRegWithShadow<[A0, A1, A2, A3,
+                                           T0, T1, T2, T3],
+                                          [F12, F13, F14, F15,
+                                           F16, F17, F18, F19]>>,
+
   CCIfType<[i64], CCAssignToRegWithShadow<[A0_64, A1_64, A2_64, A3_64,
                                            T0_64, T1_64, T2_64, T3_64],
                                           [D12_64, D13_64, D14_64, D15_64,
@@ -59,13 +65,30 @@
                                            T0_64, T1_64, T2_64, T3_64]>>,
=20
   // All stack parameter slots become 64-bit doublewords and are 8-byte al=
igned.
-  CCIfType<[i64, f64], CCAssignToStack<8, 8>>,
-  CCIfType<[f32], CCAssignToStack<4, 8>>
+  CCIfType<[i32, f32], CCAssignToStack<4, 8>>,
+  CCIfType<[i64, f64], CCAssignToStack<8, 8>>
+]>;
+
+// N32/64 variable arguments.
+// All arguments are passed in integer registers.
+def CC_MipsN_VarArg : CallingConv<[
+   // Handles byval parameters.
+  CCIfByVal<CCCustom<"CC_Mips64Byval">>,
+
+  // Promote i8/i16 arguments to i32.
+  CCIfType<[i8, i16], CCPromoteToType<i32>>,
+
+  CCIfType<[i32, f32], CCAssignToReg<[A0, A1, A2, A3, T0, T1, T2, T3]>>,
+
+  CCIfType<[i64, f64], CCAssignToReg<[A0_64, A1_64, A2_64, A3_64,
+                                      T0_64, T1_64, T2_64, T3_64]>>,
+
+  // All stack parameter slots become 64-bit doublewords and are 8-byte al=
igned.
+  CCIfType<[i32, f32], CCAssignToStack<4, 8>>,
+  CCIfType<[i64, f64], CCAssignToStack<8, 8>>
 ]>;
=20
 def RetCC_MipsN : CallingConv<[
-  // FIXME: Handle complex and float double return values.
-
   // i32 are returned in registers V0, V1
   CCIfType<[i32], CCAssignToReg<[V0, V1]>>,
=20
@@ -137,3 +160,20 @@
   CCIfSubtarget<"isABI_N64()", CCDelegateTo<RetCC_MipsN>>,
   CCDelegateTo<RetCC_MipsO32>
 ]>;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Callee-saved register lists.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+def CSR_SingleFloatOnly : CalleeSavedRegs<(add (sequence "F%u", 31, 20), R=
A, FP,
+                                               (sequence "S%u", 7, 0))>;
+
+def CSR_O32 : CalleeSavedRegs<(add (sequence "D%u", 15, 10), RA, FP,
+                                   (sequence "S%u", 7, 0))>;
+
+def CSR_N32 : CalleeSavedRegs<(add D31_64, D29_64, D27_64, D25_64, D24_64,
+                                   D23_64, D22_64, D21_64, RA_64, FP_64, G=
P_64,
+                                   (sequence "S%u_64", 7, 0))>;
+
+def CSR_N64 : CalleeSavedRegs<(add (sequence "D%u_64", 31, 24), RA_64, FP_=
64,
+                                   GP_64, (sequence "S%u_64", 7, 0))>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
CodeEmitter.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsCodeEmitter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsCodeEmitter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- Mips/MipsCodeEmitter.cpp - Convert Mips code to machine code=
 -----=3D=3D=3D//
+//=3D=3D=3D-- Mips/MipsCodeEmitter.cpp - Convert Mips Code to Machine Code=
 ------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,18 +18,20 @@
 #include "MipsRelocations.h"
 #include "MipsSubtarget.h"
 #include "MipsTargetMachine.h"
-#include "llvm/Constants.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/Function.h"
-#include "llvm/PassManager.h"
+#include "MCTargetDesc/MipsBaseInfo.h"
+#include "llvm/ADT/Statistic.h"
 #include "llvm/CodeGen/JITCodeEmitter.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/CodeGen/Passes.h"
-#include "llvm/ADT/Statistic.h"
+#include "llvm/Constants.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/Function.h"
+#include "llvm/PassManager.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
@@ -37,8 +39,6 @@
 #include <iomanip>
 #endif
=20
-#include "llvm/CodeGen/MachineOperand.h"
-
 using namespace llvm;
=20
 STATISTIC(NumEmitted, "Number of machine instructions emitted");
@@ -66,9 +66,9 @@
   public:
     MipsCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce) :
       MachineFunctionPass(ID), JTI(0),
-        II((const MipsInstrInfo *) tm.getInstrInfo()),
-        TD(tm.getTargetData()), TM(tm), MCE(mce), MCPEs(0), MJTEs(0),
-        IsPIC(TM.getRelocationModel() =3D=3D Reloc::PIC_) {
+      II((const MipsInstrInfo *) tm.getInstrInfo()),
+      TD(tm.getTargetData()), TM(tm), MCE(mce), MCPEs(0), MJTEs(0),
+      IsPIC(TM.getRelocationModel() =3D=3D Reloc::PIC_) {
     }
=20
     bool runOnMachineFunction(MachineFunction &MF);
@@ -80,7 +80,7 @@
     /// getBinaryCodeForInstr - This function, generated by the
     /// CodeEmitterGenerator using TableGen, produces the binary encoding =
for
     /// machine instructions.
-    unsigned getBinaryCodeForInstr(const MachineInstr &MI) const;
+    uint64_t getBinaryCodeForInstr(const MachineInstr &MI) const;
=20
     void emitInstruction(const MachineInstr &MI);
=20
@@ -91,7 +91,7 @@
     /// Routines that handle operands which add machine relocations which =
are
     /// fixed up by the relocation stage.
     void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
-                                bool MayNeedFarStub) const;
+                           bool MayNeedFarStub) const;
     void emitExternalSymbolAddress(const char *ES, unsigned Reloc) const;
     void emitConstPoolAddress(unsigned CPI, unsigned Reloc) const;
     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const;
@@ -105,9 +105,22 @@
     unsigned getRelocation(const MachineInstr &MI,
                            const MachineOperand &MO) const;
=20
+    unsigned getJumpTargetOpValue(const MachineInstr &MI, unsigned OpNo) c=
onst;
+
+    unsigned getBranchTargetOpValue(const MachineInstr &MI,
+                                    unsigned OpNo) const;
     unsigned getMemEncoding(const MachineInstr &MI, unsigned OpNo) const;
     unsigned getSizeExtEncoding(const MachineInstr &MI, unsigned OpNo) con=
st;
     unsigned getSizeInsEncoding(const MachineInstr &MI, unsigned OpNo) con=
st;
+
+    int emitULW(const MachineInstr &MI);
+    int emitUSW(const MachineInstr &MI);
+    int emitULH(const MachineInstr &MI);
+    int emitULHu(const MachineInstr &MI);
+    int emitUSH(const MachineInstr &MI);
+
+    void emitGlobalAddressUnaligned(const GlobalValue *GV, unsigned Reloc,
+                                    int Offset) const;
   };
 }
=20
@@ -132,7 +145,7 @@
     for (MachineFunction::iterator MBB =3D MF.begin(), E =3D MF.end();
         MBB !=3D E; ++MBB){
       MCE.StartMachineBasicBlock(MBB);
-      for (MachineBasicBlock::const_iterator I =3D MBB->begin(), E =3D MBB=
->end();
+      for (MachineBasicBlock::iterator I =3D MBB->begin(), E =3D MBB->end(=
);
           I !=3D E; ++I)
         emitInstruction(*I);
     }
@@ -149,30 +162,50 @@
   if (Form =3D=3D MipsII::FrmJ)
     return Mips::reloc_mips_26;
   if ((Form =3D=3D MipsII::FrmI || Form =3D=3D MipsII::FrmFI)
-       && MI.getDesc().isBranch())
-    return Mips::reloc_mips_branch;
+       && MI.isBranch())
+    return Mips::reloc_mips_pc16;
   if (Form =3D=3D MipsII::FrmI && MI.getOpcode() =3D=3D Mips::LUi)
     return Mips::reloc_mips_hi;
   return Mips::reloc_mips_lo;
 }
=20
+unsigned MipsCodeEmitter::getJumpTargetOpValue(const MachineInstr &MI,
+                                               unsigned OpNo) const {
+  MachineOperand MO =3D MI.getOperand(OpNo);
+  if (MO.isGlobal())
+    emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
+  else if (MO.isSymbol())
+    emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
+  else if (MO.isMBB())
+    emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
+  else
+    llvm_unreachable("Unexpected jump target operand kind.");
+  return 0;
+}
+
+unsigned MipsCodeEmitter::getBranchTargetOpValue(const MachineInstr &MI,
+                                                 unsigned OpNo) const {
+  MachineOperand MO =3D MI.getOperand(OpNo);
+  emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
+  return 0;
+}
+
 unsigned MipsCodeEmitter::getMemEncoding(const MachineInstr &MI,
-                                          unsigned OpNo) const {
+                                         unsigned OpNo) const {
   // Base register is encoded in bits 20-16, offset is encoded in bits 15-=
0.
   assert(MI.getOperand(OpNo).isReg());
   unsigned RegBits =3D getMachineOpValue(MI, MI.getOperand(OpNo)) << 16;
-  return
-    (getMachineOpValue(MI, MI.getOperand(OpNo+1)) & 0xFFFF) | RegBits;
+  return (getMachineOpValue(MI, MI.getOperand(OpNo+1)) & 0xFFFF) | RegBits;
 }
=20
 unsigned MipsCodeEmitter::getSizeExtEncoding(const MachineInstr &MI,
-                                          unsigned OpNo) const {
+                                             unsigned OpNo) const {
   // size is encoded as size-1.
   return getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
 }
=20
 unsigned MipsCodeEmitter::getSizeInsEncoding(const MachineInstr &MI,
-                                          unsigned OpNo) const {
+                                             unsigned OpNo) const {
   // size is encoded as pos+size-1.
   return getMachineOpValue(MI, MI.getOperand(OpNo-1)) +
          getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
@@ -181,14 +214,20 @@
 /// getMachineOpValue - Return binary encoding of operand. If the machine
 /// operand requires relocation, record the relocation and return zero.
 unsigned MipsCodeEmitter::getMachineOpValue(const MachineInstr &MI,
-                                           const MachineOperand &MO) const=
 {
+                                            const MachineOperand &MO) cons=
t {
   if (MO.isReg())
-    return MipsRegisterInfo::getRegisterNumbering(MO.getReg());
+    return getMipsRegisterNumbering(MO.getReg());
   else if (MO.isImm())
     return static_cast<unsigned>(MO.getImm());
-  else if (MO.isGlobal())
-    emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
-  else if (MO.isSymbol())
+  else if (MO.isGlobal()) {
+    if (MI.getOpcode() =3D=3D Mips::ULW || MI.getOpcode() =3D=3D Mips::USW=
 ||
+          MI.getOpcode() =3D=3D Mips::ULH || MI.getOpcode() =3D=3D Mips::U=
LHu)
+      emitGlobalAddressUnaligned(MO.getGlobal(), getRelocation(MI, MO), 4);
+    else if (MI.getOpcode() =3D=3D Mips::USH)
+      emitGlobalAddressUnaligned(MO.getGlobal(), getRelocation(MI, MO), 8);
+    else
+      emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
+  } else if (MO.isSymbol())
     emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
   else if (MO.isCPI())
     emitConstPoolAddress(MO.getIndex(), getRelocation(MI, MO));
@@ -202,9 +241,18 @@
 }
=20
 void MipsCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Re=
loc,
-                                                bool MayNeedFarStub) const=
 {
+                                        bool MayNeedFarStub) const {
   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Rel=
oc,
-                             const_cast<GlobalValue *>(GV), 0, MayNeedFarS=
tub));
+                                             const_cast<GlobalValue *>(GV)=
, 0,
+                                             MayNeedFarStub));
+}
+
+void MipsCodeEmitter::emitGlobalAddressUnaligned(const GlobalValue *GV,
+                                           unsigned Reloc, int Offset) con=
st {
+  MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Rel=
oc,
+                             const_cast<GlobalValue *>(GV), 0, false));
+  MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset() + Of=
fset,
+                      Reloc, const_cast<GlobalValue *>(GV), 0, false));
 }
=20
 void MipsCodeEmitter::
@@ -225,11 +273,108 @@
 }
=20
 void MipsCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
-                                           unsigned Reloc) const {
+                                            unsigned Reloc) const {
   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
                                              Reloc, BB));
 }
=20
+int MipsCodeEmitter::emitUSW(const MachineInstr &MI) {
+  unsigned src =3D getMachineOpValue(MI, MI.getOperand(0));
+  unsigned base =3D getMachineOpValue(MI, MI.getOperand(1));
+  unsigned offset =3D getMachineOpValue(MI, MI.getOperand(2));
+  // swr src, offset(base)
+  // swl src, offset+3(base)
+  MCE.emitWordLE(
+    (0x2e << 26) | (base << 21) | (src << 16) | (offset & 0xffff));
+  MCE.emitWordLE(
+    (0x2a << 26) | (base << 21) | (src << 16) | ((offset+3) & 0xffff));
+  return 2;
+}
+
+int MipsCodeEmitter::emitULW(const MachineInstr &MI) {
+  unsigned dst =3D getMachineOpValue(MI, MI.getOperand(0));
+  unsigned base =3D getMachineOpValue(MI, MI.getOperand(1));
+  unsigned offset =3D getMachineOpValue(MI, MI.getOperand(2));
+  unsigned at =3D 1;
+  if (dst !=3D base) {
+    // lwr dst, offset(base)
+    // lwl dst, offset+3(base)
+    MCE.emitWordLE(
+      (0x26 << 26) | (base << 21) | (dst << 16) | (offset & 0xffff));
+    MCE.emitWordLE(
+      (0x22 << 26) | (base << 21) | (dst << 16) | ((offset+3) & 0xffff));
+    return 2;
+  } else {
+    // lwr at, offset(base)
+    // lwl at, offset+3(base)
+    // addu dst, at, $zero
+    MCE.emitWordLE(
+      (0x26 << 26) | (base << 21) | (at << 16) | (offset & 0xffff));
+    MCE.emitWordLE(
+      (0x22 << 26) | (base << 21) | (at << 16) | ((offset+3) & 0xffff));
+    MCE.emitWordLE(
+      (0x0 << 26) | (at << 21) | (0x0 << 16) | (dst << 11) | (0x0 << 6) | =
0x21);
+    return 3;
+  }
+}
+
+int MipsCodeEmitter::emitUSH(const MachineInstr &MI) {
+  unsigned src =3D getMachineOpValue(MI, MI.getOperand(0));
+  unsigned base =3D getMachineOpValue(MI, MI.getOperand(1));
+  unsigned offset =3D getMachineOpValue(MI, MI.getOperand(2));
+  unsigned at =3D 1;
+  // sb src, offset(base)
+  // srl at,src,8
+  // sb at, offset+1(base)
+  MCE.emitWordLE(
+    (0x28 << 26) | (base << 21) | (src << 16) | (offset & 0xffff));
+  MCE.emitWordLE(
+    (0x0 << 26) | (0x0 << 21) | (src << 16) | (at << 11) | (0x8 << 6) | 0x=
2);
+  MCE.emitWordLE(
+    (0x28 << 26) | (base << 21) | (at << 16) | ((offset+1) & 0xffff));
+  return 3;
+}
+
+int MipsCodeEmitter::emitULH(const MachineInstr &MI) {
+  unsigned dst =3D getMachineOpValue(MI, MI.getOperand(0));
+  unsigned base =3D getMachineOpValue(MI, MI.getOperand(1));
+  unsigned offset =3D getMachineOpValue(MI, MI.getOperand(2));
+  unsigned at =3D 1;
+  // lbu at, offset(base)
+  // lb dst, offset+1(base)
+  // sll dst,dst,8
+  // or dst,dst,at
+  MCE.emitWordLE(
+    (0x24 << 26) | (base << 21) | (at << 16) | (offset & 0xffff));
+  MCE.emitWordLE(
+    (0x20 << 26) | (base << 21) | (dst << 16) | ((offset+1) & 0xffff));
+  MCE.emitWordLE(
+    (0x0 << 26) | (0x0 << 21) | (dst << 16) | (dst << 11) | (0x8 << 6) | 0=
x0);
+  MCE.emitWordLE(
+    (0x0 << 26) | (dst << 21) | (at << 16) | (dst << 11) | (0x0 << 6) | 0x=
25);
+  return 4;
+}
+
+int MipsCodeEmitter::emitULHu(const MachineInstr &MI) {
+  unsigned dst =3D getMachineOpValue(MI, MI.getOperand(0));
+  unsigned base =3D getMachineOpValue(MI, MI.getOperand(1));
+  unsigned offset =3D getMachineOpValue(MI, MI.getOperand(2));
+  unsigned at =3D 1;
+  // lbu at, offset(base)
+  // lbu dst, offset+1(base)
+  // sll dst,dst,8
+  // or dst,dst,at
+  MCE.emitWordLE(
+    (0x24 << 26) | (base << 21) | (at << 16) | (offset & 0xffff));
+  MCE.emitWordLE(
+    (0x24 << 26) | (base << 21) | (dst << 16) | ((offset+1) & 0xffff));
+  MCE.emitWordLE(
+    (0x0 << 26) | (0x0 << 21) | (dst << 16) | (dst << 11) | (0x8 << 6) | 0=
x0);
+  MCE.emitWordLE(
+    (0x0 << 26) | (dst << 21) | (at << 16) | (dst << 11) | (0x0 << 6) | 0x=
25);
+  return 4;
+}
+
 void MipsCodeEmitter::emitInstruction(const MachineInstr &MI) {
   DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI=
);
=20
@@ -239,11 +384,27 @@
   if ((MI.getDesc().TSFlags & MipsII::FormMask) =3D=3D MipsII::Pseudo)
     return;
=20
-  ++NumEmitted;  // Keep track of the # of mi's emitted
=20
   switch (MI.getOpcode()) {
+  case Mips::USW:
+    NumEmitted +=3D emitUSW(MI);
+    break;
+  case Mips::ULW:
+    NumEmitted +=3D emitULW(MI);
+    break;
+  case Mips::ULH:
+    NumEmitted +=3D emitULH(MI);
+    break;
+  case Mips::ULHu:
+    NumEmitted +=3D emitULHu(MI);
+    break;
+  case Mips::USH:
+    NumEmitted +=3D emitUSH(MI);
+    break;
+
   default:
     emitWordLE(getBinaryCodeForInstr(MI));
+    ++NumEmitted;  // Keep track of the # of mi's emitted
     break;
   }
=20
@@ -259,7 +420,7 @@
 /// createMipsJITCodeEmitterPass - Return a pass that emits the collected =
Mips
 /// code to the specified MCE object.
 FunctionPass *llvm::createMipsJITCodeEmitterPass(MipsTargetMachine &TM,
-    JITCodeEmitter &JCE) {
+                                                 JITCodeEmitter &JCE) {
   return new MipsCodeEmitter(TM, JCE);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
DelaySlotFiller.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- DelaySlotFiller.cpp - Mips delay slot filler ---------------=
------=3D=3D=3D//
+//=3D=3D=3D-- DelaySlotFiller.cpp - Mips Delay Slot Filler ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -96,7 +96,7 @@
   LastFiller =3D MBB.end();
=20
   for (MachineBasicBlock::iterator I =3D MBB.begin(); I !=3D MBB.end(); ++=
I)
-    if (I->getDesc().hasDelaySlot()) {
+    if (I->hasDelaySlot()) {
       ++FilledSlots;
       Changed =3D true;
=20
@@ -105,8 +105,7 @@
       if (EnableDelaySlotFiller && findDelayInstr(MBB, I, D)) {
         MBB.splice(llvm::next(I), &MBB, D);
         ++UsefulSlots;
-      }
-      else=20
+      } else
         BuildMI(MBB, llvm::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
=20
       // Record the filler instruction that filled the delay slot.
@@ -146,7 +145,7 @@
         || I->isInlineAsm()
         || I->isLabel()
         || FI =3D=3D LastFiller
-        || I->getDesc().isPseudo()
+        || I->isPseudo()
         //
         // Should not allow:
         // ERET, DERET or WAIT, PAUSE. Need to add these to instruction
@@ -167,23 +166,21 @@
 }
=20
 bool Filler::delayHasHazard(MachineBasicBlock::iterator candidate,
-                            bool &sawLoad,
-                            bool &sawStore,
+                            bool &sawLoad, bool &sawStore,
                             SmallSet<unsigned, 32> &RegDefs,
                             SmallSet<unsigned, 32> &RegUses) {
   if (candidate->isImplicitDef() || candidate->isKill())
     return true;
=20
-  MCInstrDesc MCID =3D candidate->getDesc();
   // Loads or stores cannot be moved past a store to the delay slot
-  // and stores cannot be moved past a load.=20
-  if (MCID.mayLoad()) {
+  // and stores cannot be moved past a load.
+  if (candidate->mayLoad()) {
     if (sawStore)
       return true;
     sawLoad =3D true;
   }
=20
-  if (MCID.mayStore()) {
+  if (candidate->mayStore()) {
     if (sawStore)
       return true;
     sawStore =3D true;
@@ -191,7 +188,7 @@
       return true;
   }
=20
-  assert((!MCID.isCall() && !MCID.isReturn()) &&
+  assert((!candidate->isCall() && !candidate->isReturn()) &&
          "Cannot put calls or returns in delay slot.");
=20
   for (unsigned i =3D 0, e =3D candidate->getNumOperands(); i!=3D e; ++i) {
@@ -221,11 +218,11 @@
                             SmallSet<unsigned, 32>& RegUses) {
   // If MI is a call or return, just examine the explicit non-variadic ope=
rands.
   MCInstrDesc MCID =3D MI->getDesc();
-  unsigned e =3D MCID.isCall() || MCID.isReturn() ? MCID.getNumOperands() :
-                                                  MI->getNumOperands();
- =20
-  // Add RA to RegDefs to prevent users of RA from going into delay slot.=20
-  if (MCID.isCall())
+  unsigned e =3D MI->isCall() || MI->isReturn() ? MCID.getNumOperands() :
+                                                MI->getNumOperands();
+
+  // Add RA to RegDefs to prevent users of RA from going into delay slot.
+  if (MI->isCall())
     RegDefs.insert(Mips::RA);
=20
   for (unsigned i =3D 0; i !=3D e; ++i) {
@@ -247,7 +244,7 @@
   if (RegSet.count(Reg))
     return true;
   // check Aliased Registers
-  for (const unsigned *Alias =3D TM.getRegisterInfo()->getAliasSet(Reg);
+  for (const uint16_t *Alias =3D TM.getRegisterInfo()->getAliasSet(Reg);
        *Alias; ++Alias)
     if (RegSet.count(*Alias))
       return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
EmitGPRestore.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsEmitGPRestore.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsEmitGPRestore.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsEmitGPRestore.cpp - Emit GP restore instruction---------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MipsEmitGPRestore.cpp - Emit GP Restore Instruction --------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -44,11 +44,14 @@
 } // end of anonymous namespace
=20
 bool Inserter::runOnMachineFunction(MachineFunction &F) {
-  if (TM.getRelocationModel() !=3D Reloc::PIC_)
+  MipsFunctionInfo *MipsFI =3D F.getInfo<MipsFunctionInfo>();
+
+  if ((TM.getRelocationModel() !=3D Reloc::PIC_) ||
+      (!MipsFI->globalBaseRegFixed()))
     return false;
=20
   bool Changed =3D false;
-  int FI =3D  F.getInfo<MipsFunctionInfo>()->getGPFI();
+  int FI =3D MipsFI->getGPFI();
=20
   for (MachineFunction::iterator MFI =3D F.begin(), MFE =3D F.end();
        MFI !=3D MFE; ++MFI) {
@@ -60,7 +63,7 @@
     if (MBB.isLandingPad()) {
       // Find EH_LABEL first.
       for (; I->getOpcode() !=3D TargetOpcode::EH_LABEL; ++I) ;
-     =20
+
       // Insert lw.
       ++I;
       DebugLoc dl =3D I !=3D MBB.end() ? I->getDebugLoc() : DebugLoc();
@@ -81,7 +84,7 @@
                                                          .addImm(0);
       Changed =3D true;
     }
-  }=20
+  }
=20
   return Changed;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
ExpandPseudo.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsExpandPseudo.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsExpandPseudo.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D--  MipsExpandPseudo.cpp - Expand pseudo instructions ---------=
-------=3D=3D=3D//
+//=3D=3D=3D--  MipsExpandPseudo.cpp - Expand Pseudo Instructions ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -64,16 +64,22 @@
     const MCInstrDesc& MCid =3D I->getDesc();
=20
     switch(MCid.getOpcode()) {
-    default:=20
+    default:
       ++I;
       continue;
+    case Mips::SETGP2:
+      // Convert "setgp2 $globalreg, $t9" to "addu $globalreg, $v0, $t9"
+      BuildMI(MBB, I, I->getDebugLoc(), TII->get(Mips::ADDu),
+              I->getOperand(0).getReg())
+        .addReg(Mips::V0).addReg(I->getOperand(1).getReg());
+      break;
     case Mips::BuildPairF64:
       ExpandBuildPairF64(MBB, I);
       break;
     case Mips::ExtractElementF64:
       ExpandExtractElementF64(MBB, I);
       break;
-    }=20
+    }
=20
     // delete original instr
     MBB.erase(I++);
@@ -84,12 +90,12 @@
 }
=20
 void MipsExpandPseudo::ExpandBuildPairF64(MachineBasicBlock& MBB,
-                                            MachineBasicBlock::iterator I)=
 { =20
+                                            MachineBasicBlock::iterator I)=
 {
   unsigned DstReg =3D I->getOperand(0).getReg();
   unsigned LoReg =3D I->getOperand(1).getReg(), HiReg =3D I->getOperand(2)=
.getReg();
   const MCInstrDesc& Mtc1Tdd =3D TII->get(Mips::MTC1);
   DebugLoc dl =3D I->getDebugLoc();
-  const unsigned* SubReg =3D
+  const uint16_t* SubReg =3D
     TM.getRegisterInfo()->getSubRegisters(DstReg);
=20
   // mtc1 Lo, $fp
@@ -105,12 +111,12 @@
   unsigned N =3D I->getOperand(2).getImm();
   const MCInstrDesc& Mfc1Tdd =3D TII->get(Mips::MFC1);
   DebugLoc dl =3D I->getDebugLoc();
-  const unsigned* SubReg =3D TM.getRegisterInfo()->getSubRegisters(SrcReg);
+  const uint16_t* SubReg =3D TM.getRegisterInfo()->getSubRegisters(SrcReg);
=20
   BuildMI(MBB, I, dl, Mfc1Tdd, DstReg).addReg(*(SubReg + N));
 }
=20
-/// createMipsMipsExpandPseudoPass - Returns a pass that expands pseudo=20
+/// createMipsMipsExpandPseudoPass - Returns a pass that expands pseudo
 /// instrs into real instrs
 FunctionPass *llvm::createMipsExpandPseudoPass(MipsTargetMachine &tm) {
   return new MipsExpandPseudo(tm);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
FrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsFrameLowering.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsFrameLowering.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D=3D=3D- MipsFrameLowering.cpp - Mips Frame Information --=
----*- C++ -*-=3D=3D=3D=3D//
+//=3D=3D=3D-- MipsFrameLowering.cpp - Mips Frame Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,8 +12,10 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "MipsFrameLowering.h"
+#include "MipsAnalyzeImmediate.h"
 #include "MipsInstrInfo.h"
 #include "MipsMachineFunction.h"
+#include "MCTargetDesc/MipsBaseInfo.h"
 #include "llvm/Function.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
@@ -84,55 +86,44 @@
 // if frame pointer elimination is disabled.
 bool MipsFrameLowering::hasFP(const MachineFunction &MF) const {
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
-  return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects()
-      || MFI->isFrameAddressTaken();
+  return MF.getTarget().Options.DisableFramePointerElim(MF) ||
+      MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken();
 }
=20
 bool MipsFrameLowering::targetHandlesStackFrameRounding() const {
   return true;
 }
=20
-static unsigned AlignOffset(unsigned Offset, unsigned Align) {
-  return (Offset + Align - 1) / Align * Align;=20
-}=20
+// Build an instruction sequence to load an immediate that is too large to=
 fit
+// in 16-bit and add the result to Reg.
+static void expandLargeImm(unsigned Reg, int64_t Imm, bool IsN64,
+                           const MipsInstrInfo &TII, MachineBasicBlock& MB=
B,
+                           MachineBasicBlock::iterator II, DebugLoc DL) {
+  unsigned LUi =3D IsN64 ? Mips::LUi64 : Mips::LUi;
+  unsigned ADDu =3D IsN64 ? Mips::DADDu : Mips::ADDu;
+  unsigned ZEROReg =3D IsN64 ? Mips::ZERO_64 : Mips::ZERO;
+  unsigned ATReg =3D IsN64 ? Mips::AT_64 : Mips::AT;
+  MipsAnalyzeImmediate AnalyzeImm;
+  const MipsAnalyzeImmediate::InstSeq &Seq =3D
+    AnalyzeImm.Analyze(Imm, IsN64 ? 64 : 32, false /* LastInstrIsADDiu */);
+  MipsAnalyzeImmediate::InstSeq::const_iterator Inst =3D Seq.begin();
=20
-// expand pair of register and immediate if the immediate doesn't fit in t=
he
-// 16-bit offset field.
-// e.g.
-//  if OrigImm =3D 0x10000, OrigReg =3D $sp:
-//    generate the following sequence of instrs:
-//      lui  $at, hi(0x10000)
-//      addu $at, $sp, $at
-//
-//    (NewReg, NewImm) =3D ($at, lo(Ox10000))
-//    return true
-static bool expandRegLargeImmPair(unsigned OrigReg, int OrigImm,
-                                  unsigned& NewReg, int& NewImm,
-                                  MachineBasicBlock& MBB,
-                                  MachineBasicBlock::iterator I) {
-  // OrigImm fits in the 16-bit field
-  if (OrigImm < 0x8000 && OrigImm >=3D -0x8000) {
-    NewReg =3D OrigReg;
-    NewImm =3D OrigImm;
-    return false;
-  }
+  // The first instruction can be a LUi, which is different from other
+  // instructions (ADDiu, ORI and SLL) in that it does not have a register
+  // operand.
+  if (Inst->Opc =3D=3D LUi)
+    BuildMI(MBB, II, DL, TII.get(LUi), ATReg)
+      .addImm(SignExtend64<16>(Inst->ImmOpnd));
+  else
+    BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ZEROReg)
+      .addImm(SignExtend64<16>(Inst->ImmOpnd));
=20
-  MachineFunction* MF =3D MBB.getParent();
-  const TargetInstrInfo *TII =3D MF->getTarget().getInstrInfo();
-  DebugLoc DL =3D I->getDebugLoc();
-  int ImmLo =3D (short)(OrigImm & 0xffff);
-  int ImmHi =3D (((unsigned)OrigImm & 0xffff0000) >> 16) +
-              ((OrigImm & 0x8000) !=3D 0);
+  // Build the remaining instructions in Seq.
+  for (++Inst; Inst !=3D Seq.end(); ++Inst)
+    BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ATReg)
+      .addImm(SignExtend64<16>(Inst->ImmOpnd));
=20
-  // FIXME: change this when mips goes MC".
-  BuildMI(MBB, I, DL, TII->get(Mips::NOAT));
-  BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::AT).addImm(ImmHi);
-  BuildMI(MBB, I, DL, TII->get(Mips::ADDu), Mips::AT).addReg(OrigReg)
-                                                     .addReg(Mips::AT);
-  NewReg =3D Mips::AT;
-  NewImm =3D ImmLo;
-
-  return true;
+  BuildMI(MBB, II, DL, TII.get(ADDu), Reg).addReg(Reg).addReg(ATReg);
 }
=20
 void MipsFrameLowering::emitPrologue(MachineFunction &MF) const {
@@ -146,29 +137,41 @@
   MachineBasicBlock::iterator MBBI =3D MBB.begin();
   DebugLoc dl =3D MBBI !=3D MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
   bool isPIC =3D (MF.getTarget().getRelocationModel() =3D=3D Reloc::PIC_);
-  unsigned NewReg =3D 0;
-  int NewImm =3D 0;
-  bool ATUsed;
+  unsigned SP =3D STI.isABI_N64() ? Mips::SP_64 : Mips::SP;
+  unsigned FP =3D STI.isABI_N64() ? Mips::FP_64 : Mips::FP;
+  unsigned ZERO =3D STI.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO;
+  unsigned ADDu =3D STI.isABI_N64() ? Mips::DADDu : Mips::ADDu;
+  unsigned ADDiu =3D STI.isABI_N64() ? Mips::DADDiu : Mips::ADDiu;
=20
   // First, compute final stack size.
   unsigned RegSize =3D STI.isGP32bit() ? 4 : 8;
   unsigned StackAlign =3D getStackAlignment();
-  unsigned LocalVarAreaOffset =3D MipsFI->needGPSaveRestore() ?=20
+  unsigned LocalVarAreaOffset =3D MipsFI->needGPSaveRestore() ?
     (MFI->getObjectOffset(MipsFI->getGPFI()) + RegSize) :
     MipsFI->getMaxCallFrameSize();
-  unsigned StackSize =3D AlignOffset(LocalVarAreaOffset, StackAlign) +
-    AlignOffset(MFI->getStackSize(), StackAlign);
+  uint64_t StackSize =3D  RoundUpToAlignment(LocalVarAreaOffset, StackAlig=
n) +
+     RoundUpToAlignment(MFI->getStackSize(), StackAlign);
=20
    // Update stack size
-  MFI->setStackSize(StackSize);=20
- =20
-  BuildMI(MBB, MBBI, dl, TII.get(Mips::NOREORDER));
+  MFI->setStackSize(StackSize);
=20
-  // TODO: check need from GP here.
-  if (isPIC && STI.isABI_O32())
-    BuildMI(MBB, MBBI, dl, TII.get(Mips::CPLOAD))
-      .addReg(RegInfo->getPICCallReg());
-  BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO));
+  // Emit instructions that set the global base register if the target ABI=
 is
+  // O32.
+  if (isPIC && MipsFI->globalBaseRegSet() && STI.isABI_O32() &&
+      !MipsFI->globalBaseRegFixed()) {
+      // See MipsInstrInfo.td for explanation.
+    MachineBasicBlock *NewEntry =3D MF.CreateMachineBasicBlock();
+    MF.insert(&MBB, NewEntry);
+    NewEntry->addSuccessor(&MBB);
+
+    // Copy live in registers.
+    for (MachineBasicBlock::livein_iterator R =3D MBB.livein_begin();
+         R !=3D MBB.livein_end(); ++R)
+      NewEntry->addLiveIn(*R);
+
+    BuildMI(*NewEntry, NewEntry->begin(), dl, TII.get(Mips:: SETGP01),
+            Mips::V0);
+  }
=20
   // No need to allocate space on the stack.
   if (StackSize =3D=3D 0 && !MFI->adjustsStack()) return;
@@ -177,15 +180,13 @@
   std::vector<MachineMove> &Moves =3D MMI.getFrameMoves();
   MachineLocation DstML, SrcML;
=20
-  // Adjust stack : addi sp, sp, (-imm)
-  ATUsed =3D expandRegLargeImmPair(Mips::SP, -StackSize, NewReg, NewImm, M=
BB,
-                                 MBBI);
-  BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
-    .addReg(NewReg).addImm(NewImm);
-
-  // FIXME: change this when mips goes MC".
-  if (ATUsed)
-    BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
+  // Adjust stack.
+  if (isInt<16>(-StackSize)) // addi sp, sp, (-stacksize)
+    BuildMI(MBB, MBBI, dl, TII.get(ADDiu), SP).addReg(SP).addImm(-StackSiz=
e);
+  else { // Expand immediate that doesn't fit in 16-bit.
+    MipsFI->setEmitNOAT();
+    expandLargeImm(SP, -StackSize, STI.isABI_N64(), TII, MBB, MBBI, dl);
+  }
=20
   // emit ".cfi_def_cfa_offset StackSize"
   MCSymbol *AdjustSPLabel =3D MMI.getContext().CreateTempSymbol();
@@ -202,13 +203,13 @@
     // register to the stack.
     for (unsigned i =3D 0; i < CSI.size(); ++i)
       ++MBBI;
-=20
+
     // Iterate over list of callee-saved registers and emit .cfi_offset
     // directives.
     MCSymbol *CSLabel =3D MMI.getContext().CreateTempSymbol();
     BuildMI(MBB, MBBI, dl,
             TII.get(TargetOpcode::PROLOG_LABEL)).addSym(CSLabel);
-=20
+
     for (std::vector<CalleeSavedInfo>::const_iterator I =3D CSI.begin(),
            E =3D CSI.end(); I !=3D E; ++I) {
       int64_t Offset =3D MFI->getObjectOffset(I->getFrameIdx());
@@ -217,7 +218,7 @@
       // If Reg is a double precision register, emit two cfa_offsets,
       // one for each of the paired single precision registers.
       if (Mips::AFGR64RegisterClass->contains(Reg)) {
-        const unsigned *SubRegs =3D RegInfo->getSubRegisters(Reg);
+        const uint16_t *SubRegs =3D RegInfo->getSubRegisters(Reg);
         MachineLocation DstML0(MachineLocation::VirtualFP, Offset);
         MachineLocation DstML1(MachineLocation::VirtualFP, Offset + 4);
         MachineLocation SrcML0(*SubRegs);
@@ -236,19 +237,18 @@
         Moves.push_back(MachineMove(CSLabel, DstML, SrcML));
       }
     }
-  }   =20
+  }
=20
   // if framepointer enabled, set it to point to the stack pointer.
   if (hasFP(MF)) {
-    // Insert instruction "move $fp, $sp" at this location.   =20
-    BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDu), Mips::FP)
-      .addReg(Mips::SP).addReg(Mips::ZERO);
+    // Insert instruction "move $fp, $sp" at this location.
+    BuildMI(MBB, MBBI, dl, TII.get(ADDu), FP).addReg(SP).addReg(ZERO);
=20
-    // emit ".cfi_def_cfa_register $fp"=20
+    // emit ".cfi_def_cfa_register $fp"
     MCSymbol *SetFPLabel =3D MMI.getContext().CreateTempSymbol();
     BuildMI(MBB, MBBI, dl,
             TII.get(TargetOpcode::PROLOG_LABEL)).addSym(SetFPLabel);
-    DstML =3D MachineLocation(Mips::FP);
+    DstML =3D MachineLocation(FP);
     SrcML =3D MachineLocation(MachineLocation::VirtualFP);
     Moves.push_back(MachineMove(SetFPLabel, DstML, SrcML));
   }
@@ -256,12 +256,8 @@
   // Restore GP from the saved stack location
   if (MipsFI->needGPSaveRestore()) {
     unsigned Offset =3D MFI->getObjectOffset(MipsFI->getGPFI());
-    BuildMI(MBB, MBBI, dl, TII.get(Mips::CPRESTORE)).addImm(Offset);
-
-    if (Offset >=3D 0x8000) {
-      BuildMI(MBB, llvm::prior(MBBI), dl, TII.get(Mips::MACRO));
-      BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO));
-    }
+    BuildMI(MBB, MBBI, dl, TII.get(Mips::CPRESTORE)).addImm(Offset)
+      .addReg(Mips::GP);
   }
 }
=20
@@ -272,59 +268,59 @@
   const MipsInstrInfo &TII =3D
     *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo());
   DebugLoc dl =3D MBBI->getDebugLoc();
-
-  // Get the number of bytes from FrameInfo
-  unsigned StackSize =3D MFI->getStackSize();
-
-  unsigned NewReg =3D 0;
-  int NewImm =3D 0;
-  bool ATUsed =3D false;
+  unsigned SP =3D STI.isABI_N64() ? Mips::SP_64 : Mips::SP;
+  unsigned FP =3D STI.isABI_N64() ? Mips::FP_64 : Mips::FP;
+  unsigned ZERO =3D STI.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO;
+  unsigned ADDu =3D STI.isABI_N64() ? Mips::DADDu : Mips::ADDu;
+  unsigned ADDiu =3D STI.isABI_N64() ? Mips::DADDiu : Mips::ADDiu;
=20
   // if framepointer enabled, restore the stack pointer.
   if (hasFP(MF)) {
     // Find the first instruction that restores a callee-saved register.
     MachineBasicBlock::iterator I =3D MBBI;
-   =20
+
     for (unsigned i =3D 0; i < MFI->getCalleeSavedInfo().size(); ++i)
       --I;
=20
     // Insert instruction "move $sp, $fp" at this location.
-    BuildMI(MBB, I, dl, TII.get(Mips::ADDu), Mips::SP)
-      .addReg(Mips::FP).addReg(Mips::ZERO);
+    BuildMI(MBB, I, dl, TII.get(ADDu), SP).addReg(FP).addReg(ZERO);
   }
=20
-  // adjust stack  : insert addi sp, sp, (imm)
-  if (StackSize) {
-    ATUsed =3D expandRegLargeImmPair(Mips::SP, StackSize, NewReg, NewImm, =
MBB,
-                                   MBBI);
-    BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP)
-      .addReg(NewReg).addImm(NewImm);
+  // Get the number of bytes from FrameInfo
+  uint64_t StackSize =3D MFI->getStackSize();
=20
-    // FIXME: change this when mips goes MC".
-    if (ATUsed)
-      BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO));
-  }
+  if (!StackSize)
+    return;
+
+  // Adjust stack.
+  if (isInt<16>(StackSize)) // addi sp, sp, (-stacksize)
+    BuildMI(MBB, MBBI, dl, TII.get(ADDiu), SP).addReg(SP).addImm(StackSize=
);
+  else // Expand immediate that doesn't fit in 16-bit.
+    expandLargeImm(SP, StackSize, STI.isABI_N64(), TII, MBB, MBBI, dl);
 }
=20
 void MipsFrameLowering::
 processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
                                      RegScavenger *RS) const {
   MachineRegisterInfo& MRI =3D MF.getRegInfo();
+  unsigned FP =3D STI.isABI_N64() ? Mips::FP_64 : Mips::FP;
=20
   // FIXME: remove this code if register allocator can correctly mark
   //        $fp and $ra used or unused.
=20
   // Mark $fp and $ra as used or unused.
   if (hasFP(MF))
-    MRI.setPhysRegUsed(Mips::FP);
+    MRI.setPhysRegUsed(FP);
=20
-  // The register allocator might determine $ra is used after seeing=20
+  // The register allocator might determine $ra is used after seeing
   // instruction "jr $ra", but we do not want PrologEpilogInserter to inse=
rt
   // instructions to save/restore $ra unless there is a function call.
   // To correct this, $ra is explicitly marked unused if there is no
   // function call.
   if (MF.getFrameInfo()->hasCalls())
     MRI.setPhysRegUsed(Mips::RA);
-  else
+  else {
     MRI.setPhysRegUnused(Mips::RA);
+    MRI.setPhysRegUnused(Mips::RA_64);
+  }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
FrameLowering.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsFrameLowering.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsFrameLowering.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D--- MipsFrameLowering.h - Define frame lowering for Mips --*- C++ =
-*---=3D=3D=3D//
+//=3D=3D=3D-- MipsFrameLowering.h - Define frame lowering for Mips ----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
ISelDAGToDAG.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsISelDAGToDAG.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsISelDAGToDAG.cpp - A dag to dag inst selector for Mips -=
-------=3D=3D=3D//
+//=3D=3D=3D-- MipsISelDAGToDAG.cpp - A Dag to Dag Inst Selector for Mips -=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,10 +13,12 @@
=20
 #define DEBUG_TYPE "mips-isel"
 #include "Mips.h"
+#include "MipsAnalyzeImmediate.h"
 #include "MipsMachineFunction.h"
 #include "MipsRegisterInfo.h"
 #include "MipsSubtarget.h"
 #include "MipsTargetMachine.h"
+#include "MCTargetDesc/MipsBaseInfo.h"
 #include "llvm/GlobalValue.h"
 #include "llvm/Instructions.h"
 #include "llvm/Intrinsics.h"
@@ -28,6 +30,7 @@
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/SelectionDAGISel.h"
+#include "llvm/CodeGen/SelectionDAGNodes.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -63,6 +66,7 @@
     return "MIPS DAG->DAG Pattern Instruction Selection";
   }
=20
+  virtual bool runOnMachineFunction(MachineFunction &MF);
=20
 private:
   // Include the pieces autogenerated from the target description.
@@ -81,17 +85,24 @@
   }
=20
   SDNode *getGlobalBaseReg();
+
+  std::pair<SDNode*, SDNode*> SelectMULT(SDNode *N, unsigned Opc, DebugLoc=
 dl,
+                                         EVT Ty, bool HasLo, bool HasHi);
+
   SDNode *Select(SDNode *N);
=20
   // Complex Pattern.
-  bool SelectAddr(SDValue N, SDValue &Base, SDValue &Offset);
+  bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Offse=
t);
=20
-  // getI32Imm - Return a target constant with the specified
-  // value, of type i32.
-  inline SDValue getI32Imm(unsigned Imm) {
-    return CurDAG->getTargetConstant(Imm, MVT::i32);
+  // getImm - Return a target constant with the specified value.
+  inline SDValue getImm(const SDNode *Node, unsigned Imm) {
+    return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
   }
=20
+  void ProcessFunctionAfterISel(MachineFunction &MF);
+  bool ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI, const MachineInstr=
&);
+  void InitGlobalBaseReg(MachineFunction &MF);
+
   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
                                             char ConstraintCode,
                                             std::vector<SDValue> &OutOps);
@@ -99,20 +110,163 @@
=20
 }
=20
+// Insert instructions to initialize the global base register in the
+// first MBB of the function. When the ABI is O32 and the relocation model=
 is
+// PIC, the necessary instructions are emitted later to prevent optimizati=
on
+// passes from moving them.
+void MipsDAGToDAGISel::InitGlobalBaseReg(MachineFunction &MF) {
+  MipsFunctionInfo *MipsFI =3D MF.getInfo<MipsFunctionInfo>();
+
+  if (!MipsFI->globalBaseRegSet())
+    return;
+
+  MachineBasicBlock &MBB =3D MF.front();
+  MachineBasicBlock::iterator I =3D MBB.begin();
+  MachineRegisterInfo &RegInfo =3D MF.getRegInfo();
+  const TargetInstrInfo &TII =3D *MF.getTarget().getInstrInfo();
+  DebugLoc DL =3D I !=3D MBB.end() ? I->getDebugLoc() : DebugLoc();
+  unsigned V0, V1, GlobalBaseReg =3D MipsFI->getGlobalBaseReg();
+  bool FixGlobalBaseReg =3D MipsFI->globalBaseRegFixed();
+
+  if (Subtarget.isABI_O32() && FixGlobalBaseReg)
+    // $gp is the global base register.
+    V0 =3D V1 =3D GlobalBaseReg;
+  else {
+    const TargetRegisterClass *RC;
+    RC =3D Subtarget.isABI_N64() ?
+         Mips::CPU64RegsRegisterClass : Mips::CPURegsRegisterClass;
+
+    V0 =3D RegInfo.createVirtualRegister(RC);
+    V1 =3D RegInfo.createVirtualRegister(RC);
+  }
+
+  if (Subtarget.isABI_N64()) {
+    MF.getRegInfo().addLiveIn(Mips::T9_64);
+    MBB.addLiveIn(Mips::T9_64);
+
+    // lui $v0, %hi(%neg(%gp_rel(fname)))
+    // daddu $v1, $v0, $t9
+    // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
+    const GlobalValue *FName =3D MF.getFunction();
+    BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
+      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
+    BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0).addReg(Mips::=
T9_64);
+    BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
+      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
+  } else if (MF.getTarget().getRelocationModel() =3D=3D Reloc::Static) {
+    // Set global register to __gnu_local_gp.
+    //
+    // lui   $v0, %hi(__gnu_local_gp)
+    // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
+    BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
+      .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
+    BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
+      .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
+  } else {
+    MF.getRegInfo().addLiveIn(Mips::T9);
+    MBB.addLiveIn(Mips::T9);
+
+    if (Subtarget.isABI_N32()) {
+      // lui $v0, %hi(%neg(%gp_rel(fname)))
+      // addu $v1, $v0, $t9
+      // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
+      const GlobalValue *FName =3D MF.getFunction();
+      BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
+        .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
+      BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips:=
:T9);
+      BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
+        .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
+    } else if (!MipsFI->globalBaseRegFixed()) {
+      assert(Subtarget.isABI_O32());
+
+      BuildMI(MBB, I, DL, TII.get(Mips::SETGP2), GlobalBaseReg)
+        .addReg(Mips::T9);
+    }
+  }
+}
+
+bool MipsDAGToDAGISel::ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI,
+                                              const MachineInstr& MI) {
+  unsigned DstReg =3D 0, ZeroReg =3D 0;
+
+  // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
+  if ((MI.getOpcode() =3D=3D Mips::ADDiu) &&
+      (MI.getOperand(1).getReg() =3D=3D Mips::ZERO) &&
+      (MI.getOperand(2).getImm() =3D=3D 0)) {
+    DstReg =3D MI.getOperand(0).getReg();
+    ZeroReg =3D Mips::ZERO;
+  } else if ((MI.getOpcode() =3D=3D Mips::DADDiu) &&
+             (MI.getOperand(1).getReg() =3D=3D Mips::ZERO_64) &&
+             (MI.getOperand(2).getImm() =3D=3D 0)) {
+    DstReg =3D MI.getOperand(0).getReg();
+    ZeroReg =3D Mips::ZERO_64;
+  }
+
+  if (!DstReg)
+    return false;
+
+  // Replace uses with ZeroReg.
+  for (MachineRegisterInfo::use_iterator U =3D MRI->use_begin(DstReg),
+       E =3D MRI->use_end(); U !=3D E; ++U) {
+    MachineOperand &MO =3D U.getOperand();
+    MachineInstr *MI =3D MO.getParent();
+
+    // Do not replace if it is a phi's operand or is tied to def operand.
+    if (MI->isPHI() || MI->isRegTiedToDefOperand(U.getOperandNo()))
+      continue;
+
+    MO.setReg(ZeroReg);
+  }
+
+  return true;
+}
+
+void MipsDAGToDAGISel::ProcessFunctionAfterISel(MachineFunction &MF) {
+  InitGlobalBaseReg(MF);
+
+  MachineRegisterInfo *MRI =3D &MF.getRegInfo();
+
+  for (MachineFunction::iterator MFI =3D MF.begin(), MFE =3D MF.end(); MFI=
 !=3D MFE;
+       ++MFI)
+    for (MachineBasicBlock::iterator I =3D MFI->begin(); I !=3D MFI->end()=
; ++I)
+      ReplaceUsesWithZeroReg(MRI, *I);
+}
+
+bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
+  bool Ret =3D SelectionDAGISel::runOnMachineFunction(MF);
+
+  ProcessFunctionAfterISel(MF);
+
+  return Ret;
+}
=20
 /// getGlobalBaseReg - Output the instructions required to put the
 /// GOT address into a register.
 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
-  unsigned GlobalBaseReg =3D getInstrInfo()->getGlobalBaseReg(MF);
+  unsigned GlobalBaseReg =3D MF->getInfo<MipsFunctionInfo>()->getGlobalBas=
eReg();
   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
 }
=20
 /// ComplexPattern used on MipsInstrInfo
 /// Used on Mips Load/Store instructions
 bool MipsDAGToDAGISel::
-SelectAddr(SDValue Addr, SDValue &Base, SDValue &Offset) {
+SelectAddr(SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset) {
   EVT ValTy =3D Addr.getValueType();
-  unsigned GPReg =3D ValTy =3D=3D MVT::i32 ? Mips::GP : Mips::GP_64;
+
+  // If Parent is an unaligned f32 load or store, select a (base + index)
+  // floating point load/store instruction (luxc1 or suxc1).
+  const LSBaseSDNode* LS =3D 0;
+
+  if (Parent && (LS =3D dyn_cast<LSBaseSDNode>(Parent))) {
+    EVT VT =3D LS->getMemoryVT();
+
+    if (VT.getSizeInBits() / 8 > LS->getAlignment()) {
+      assert(TLI.allowsUnalignedMemoryAccesses(VT) &&
+             "Unaligned loads/stores not supported for this type.");
+      if (VT =3D=3D MVT::f32)
+        return false;
+    }
+  }
=20
   // if Address is FI, get the TargetFrameIndex.
   if (FrameIndexSDNode *FIN =3D dyn_cast<FrameIndexSDNode>(Addr)) {
@@ -122,21 +276,16 @@
   }
=20
   // on PIC code Load GA
-  if (TM.getRelocationModel() =3D=3D Reloc::PIC_) {
-    if (Addr.getOpcode() =3D=3D MipsISD::WrapperPIC) {
-      Base   =3D CurDAG->getRegister(GPReg, ValTy);
-      Offset =3D Addr.getOperand(0);
-      return true;
-    }
-  } else {
+  if (Addr.getOpcode() =3D=3D MipsISD::Wrapper) {
+    Base   =3D Addr.getOperand(0);
+    Offset =3D Addr.getOperand(1);
+    return true;
+  }
+
+  if (TM.getRelocationModel() !=3D Reloc::PIC_) {
     if ((Addr.getOpcode() =3D=3D ISD::TargetExternalSymbol ||
         Addr.getOpcode() =3D=3D ISD::TargetGlobalAddress))
       return false;
-    else if (Addr.getOpcode() =3D=3D ISD::TargetGlobalTLSAddress) {
-      Base   =3D CurDAG->getRegister(GPReg, ValTy);
-      Offset =3D Addr;
-      return true;
-    }
   }
=20
   // Addresses of the form FI+const or FI|const
@@ -166,17 +315,20 @@
     // Generate:
     //  lui $2, %hi($CPI1_0)
     //  lwc1 $f0, %lo($CPI1_0)($2)
-    if ((Addr.getOperand(0).getOpcode() =3D=3D MipsISD::Hi ||
-         Addr.getOperand(0).getOpcode() =3D=3D ISD::LOAD) &&
-        Addr.getOperand(1).getOpcode() =3D=3D MipsISD::Lo) {
+    if (Addr.getOperand(1).getOpcode() =3D=3D MipsISD::Lo) {
       SDValue LoVal =3D Addr.getOperand(1);
-      if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) ||=20
+      if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) ||
           isa<GlobalAddressSDNode>(LoVal.getOperand(0))) {
         Base =3D Addr.getOperand(0);
         Offset =3D LoVal.getOperand(0);
         return true;
       }
     }
+
+    // If an indexed floating point load/store can be emitted, return fals=
e.
+    if (LS && (LS->getMemoryVT() =3D=3D MVT::f32 || LS->getMemoryVT() =3D=
=3D MVT::f64) &&
+        Subtarget.hasMips32r2Or64())
+      return false;
   }
=20
   Base   =3D Addr;
@@ -184,6 +336,28 @@
   return true;
 }
=20
+/// Select multiply instructions.
+std::pair<SDNode*, SDNode*>
+MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty,
+                             bool HasLo, bool HasHi) {
+  SDNode *Lo =3D 0, *Hi =3D 0;
+  SDNode *Mul =3D CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand=
(0),
+                                       N->getOperand(1));
+  SDValue InFlag =3D SDValue(Mul, 0);
+
+  if (HasLo) {
+    Lo =3D CurDAG->getMachineNode(Ty =3D=3D MVT::i32 ? Mips::MFLO : Mips::=
MFLO64, dl,
+                                Ty, MVT::Glue, InFlag);
+    InFlag =3D SDValue(Lo, 1);
+  }
+  if (HasHi)
+    Hi =3D CurDAG->getMachineNode(Ty =3D=3D MVT::i32 ? Mips::MFHI : Mips::=
MFHI64, dl,
+                                Ty, InFlag);
+
+  return std::make_pair(Lo, Hi);
+}
+
+
 /// Select instructions not customized! Used for
 /// expanded, promoted and normal instructions
 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
@@ -203,123 +377,167 @@
   // Instruction Selection not handled by the auto-generated
   // tablegen selection should be handled here.
   ///
+  EVT NodeTy =3D Node->getValueType(0);
+  unsigned MultOpc;
+
   switch(Opcode) {
-    default: break;
+  default: break;
=20
-    case ISD::SUBE:
-    case ISD::ADDE: {
-      SDValue InFlag =3D Node->getOperand(2), CmpLHS;
-      unsigned Opc =3D InFlag.getOpcode(); (void)Opc;
-      assert(((Opc =3D=3D ISD::ADDC || Opc =3D=3D ISD::ADDE) ||
-              (Opc =3D=3D ISD::SUBC || Opc =3D=3D ISD::SUBE)) &&
-             "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
+  case ISD::SUBE:
+  case ISD::ADDE: {
+    SDValue InFlag =3D Node->getOperand(2), CmpLHS;
+    unsigned Opc =3D InFlag.getOpcode(); (void)Opc;
+    assert(((Opc =3D=3D ISD::ADDC || Opc =3D=3D ISD::ADDE) ||
+            (Opc =3D=3D ISD::SUBC || Opc =3D=3D ISD::SUBE)) &&
+           "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
=20
-      unsigned MOp;
-      if (Opcode =3D=3D ISD::ADDE) {
-        CmpLHS =3D InFlag.getValue(0);
-        MOp =3D Mips::ADDu;
-      } else {
-        CmpLHS =3D InFlag.getOperand(0);
-        MOp =3D Mips::SUBu;
+    unsigned MOp;
+    if (Opcode =3D=3D ISD::ADDE) {
+      CmpLHS =3D InFlag.getValue(0);
+      MOp =3D Mips::ADDu;
+    } else {
+      CmpLHS =3D InFlag.getOperand(0);
+      MOp =3D Mips::SUBu;
+    }
+
+    SDValue Ops[] =3D { CmpLHS, InFlag.getOperand(1) };
+
+    SDValue LHS =3D Node->getOperand(0);
+    SDValue RHS =3D Node->getOperand(1);
+
+    EVT VT =3D LHS.getValueType();
+    SDNode *Carry =3D CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
+    SDNode *AddCarry =3D CurDAG->getMachineNode(Mips::ADDu, dl, VT,
+                                              SDValue(Carry,0), RHS);
+
+    return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
+                                LHS, SDValue(AddCarry,0));
+  }
+
+  /// Mul with two results
+  case ISD::SMUL_LOHI:
+  case ISD::UMUL_LOHI: {
+    if (NodeTy =3D=3D MVT::i32)
+      MultOpc =3D (Opcode =3D=3D ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT=
);
+    else
+      MultOpc =3D (Opcode =3D=3D ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMU=
LT);
+
+    std::pair<SDNode*, SDNode*> LoHi =3D SelectMULT(Node, MultOpc, dl, Nod=
eTy,
+                                                  true, true);
+
+    if (!SDValue(Node, 0).use_empty())
+      ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
+
+    if (!SDValue(Node, 1).use_empty())
+      ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
+
+    return NULL;
+  }
+
+  /// Special Muls
+  case ISD::MUL: {
+    // Mips32 has a 32-bit three operand mul instruction.
+    if (Subtarget.hasMips32() && NodeTy =3D=3D MVT::i32)
+      break;
+    return SelectMULT(Node, NodeTy =3D=3D MVT::i32 ? Mips::MULT : Mips::DM=
ULT,
+                      dl, NodeTy, true, false).first;
+  }
+  case ISD::MULHS:
+  case ISD::MULHU: {
+    if (NodeTy =3D=3D MVT::i32)
+      MultOpc =3D (Opcode =3D=3D ISD::MULHU ? Mips::MULTu : Mips::MULT);
+    else
+      MultOpc =3D (Opcode =3D=3D ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
+
+    return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
+  }
+
+  // Get target GOT address.
+  case ISD::GLOBAL_OFFSET_TABLE:
+    return getGlobalBaseReg();
+
+  case ISD::ConstantFP: {
+    ConstantFPSDNode *CN =3D dyn_cast<ConstantFPSDNode>(Node);
+    if (Node->getValueType(0) =3D=3D MVT::f64 && CN->isExactlyValue(+0.0))=
 {
+      if (Subtarget.hasMips64()) {
+        SDValue Zero =3D CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
+                                              Mips::ZERO_64, MVT::i64);
+        return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
       }
=20
-      SDValue Ops[] =3D { CmpLHS, InFlag.getOperand(1) };
+      SDValue Zero =3D CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
+                                            Mips::ZERO, MVT::i32);
+      return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
+                                    Zero);
+    }
+    break;
+  }
=20
-      SDValue LHS =3D Node->getOperand(0);
-      SDValue RHS =3D Node->getOperand(1);
+  case ISD::Constant: {
+    const ConstantSDNode *CN =3D dyn_cast<ConstantSDNode>(Node);
+    unsigned Size =3D CN->getValueSizeInBits(0);
=20
-      EVT VT =3D LHS.getValueType();
-      SDNode *Carry =3D CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
-      SDNode *AddCarry =3D CurDAG->getMachineNode(Mips::ADDu, dl, VT,
-                                                SDValue(Carry,0), RHS);
+    if (Size =3D=3D 32)
+      break;
=20
-      return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
-                                  LHS, SDValue(AddCarry,0));
+    MipsAnalyzeImmediate AnalyzeImm;
+    int64_t Imm =3D CN->getSExtValue();
+
+    const MipsAnalyzeImmediate::InstSeq &Seq =3D
+      AnalyzeImm.Analyze(Imm, Size, false);
+
+    MipsAnalyzeImmediate::InstSeq::const_iterator Inst =3D Seq.begin();
+    DebugLoc DL =3D CN->getDebugLoc();
+    SDNode *RegOpnd;
+    SDValue ImmOpnd =3D CurDAG->getTargetConstant(SignExtend64<16>(Inst->I=
mmOpnd),
+                                                MVT::i64);
+
+    // The first instruction can be a LUi which is different from other
+    // instructions (ADDiu, ORI and SLL) in that it does not have a regist=
er
+    // operand.
+    if (Inst->Opc =3D=3D Mips::LUi64)
+      RegOpnd =3D CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
+    else
+      RegOpnd =3D
+        CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
+                               CurDAG->getRegister(Mips::ZERO_64, MVT::i64=
),
+                               ImmOpnd);
+
+    // The remaining instructions in the sequence are handled here.
+    for (++Inst; Inst !=3D Seq.end(); ++Inst) {
+      ImmOpnd =3D CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd=
),
+                                          MVT::i64);
+      RegOpnd =3D CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
+                                       SDValue(RegOpnd, 0), ImmOpnd);
     }
=20
-    /// Mul with two results
-    case ISD::SMUL_LOHI:
-    case ISD::UMUL_LOHI: {
-      assert(Node->getValueType(0) !=3D MVT::i64 &&
-             "64-bit multiplication with two results not handled.");
-      SDValue Op1 =3D Node->getOperand(0);
-      SDValue Op2 =3D Node->getOperand(1);
+    return RegOpnd;
+  }
=20
-      unsigned Op;
-      Op =3D (Opcode =3D=3D ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
+  case MipsISD::ThreadPointer: {
+    EVT PtrVT =3D TLI.getPointerTy();
+    unsigned RdhwrOpc, SrcReg, DestReg;
=20
-      SDNode *Mul =3D CurDAG->getMachineNode(Op, dl, MVT::Glue, Op1, Op2);
-
-      SDValue InFlag =3D SDValue(Mul, 0);
-      SDNode *Lo =3D CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32,
-                                          MVT::Glue, InFlag);
-      InFlag =3D SDValue(Lo,1);
-      SDNode *Hi =3D CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFl=
ag);
-
-      if (!SDValue(Node, 0).use_empty())
-        ReplaceUses(SDValue(Node, 0), SDValue(Lo,0));
-
-      if (!SDValue(Node, 1).use_empty())
-        ReplaceUses(SDValue(Node, 1), SDValue(Hi,0));
-
-      return NULL;
+    if (PtrVT =3D=3D MVT::i32) {
+      RdhwrOpc =3D Mips::RDHWR;
+      SrcReg =3D Mips::HWR29;
+      DestReg =3D Mips::V1;
+    } else {
+      RdhwrOpc =3D Mips::RDHWR64;
+      SrcReg =3D Mips::HWR29_64;
+      DestReg =3D Mips::V1_64;
     }
=20
-    /// Special Muls
-    case ISD::MUL:
-      // Mips32 has a 32-bit three operand mul instruction.
-      if (Subtarget.hasMips32() && Node->getValueType(0) =3D=3D MVT::i32)
-        break;
-    case ISD::MULHS:
-    case ISD::MULHU: {
-      assert((Opcode =3D=3D ISD::MUL || Node->getValueType(0) !=3D MVT::i6=
4) &&
-             "64-bit MULH* not handled.");
-      EVT Ty =3D Node->getValueType(0);
-      SDValue MulOp1 =3D Node->getOperand(0);
-      SDValue MulOp2 =3D Node->getOperand(1);
-
-      unsigned MulOp  =3D (Opcode =3D=3D ISD::MULHU ?
-                         Mips::MULTu :
-                         (Ty =3D=3D MVT::i32 ? Mips::MULT : Mips::DMULT));
-      SDNode *MulNode =3D CurDAG->getMachineNode(MulOp, dl,
-                                               MVT::Glue, MulOp1, MulOp2);
-
-      SDValue InFlag =3D SDValue(MulNode, 0);
-
-      if (Opcode =3D=3D ISD::MUL) {
-        unsigned Opc =3D (Ty =3D=3D MVT::i32 ? Mips::MFLO : Mips::MFLO64);
-        return CurDAG->getMachineNode(Opc, dl, Ty, InFlag);
-      }
-      else
-        return CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
-    }
-
-    // Get target GOT address.
-    case ISD::GLOBAL_OFFSET_TABLE:
-      return getGlobalBaseReg();
-
-    case ISD::ConstantFP: {
-      ConstantFPSDNode *CN =3D dyn_cast<ConstantFPSDNode>(Node);
-      if (Node->getValueType(0) =3D=3D MVT::f64 && CN->isExactlyValue(+0.0=
)) {
-        SDValue Zero =3D CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
-                                        Mips::ZERO, MVT::i32);
-        return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Ze=
ro,
-                                      Zero);
-      }
-      break;
-    }
-
-    case MipsISD::ThreadPointer: {
-      unsigned SrcReg =3D Mips::HWR29;
-      unsigned DestReg =3D Mips::V1;
-      SDNode *Rdhwr =3D CurDAG->getMachineNode(Mips::RDHWR, Node->getDebug=
Loc(),
-          Node->getValueType(0), CurDAG->getRegister(SrcReg, MVT::i32));
-      SDValue Chain =3D CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, D=
estReg,
-          SDValue(Rdhwr, 0));
-      SDValue ResNode =3D CurDAG->getCopyFromReg(Chain, dl, DestReg, MVT::=
i32);
-      ReplaceUses(SDValue(Node, 0), ResNode);
-      return ResNode.getNode();
-    }
+    SDNode *Rdhwr =3D
+      CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
+                             Node->getValueType(0),
+                             CurDAG->getRegister(SrcReg, PtrVT));
+    SDValue Chain =3D CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, Des=
tReg,
+                                         SDValue(Rdhwr, 0));
+    SDValue ResNode =3D CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
+    ReplaceUses(SDValue(Node, 0), ResNode);
+    return ResNode.getNode();
+  }
   }
=20
   // Select the default instruction
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
ISelLowering.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -18,12 +18,13 @@
 #include "MipsTargetMachine.h"
 #include "MipsTargetObjectFile.h"
 #include "MipsSubtarget.h"
+#include "InstPrinter/MipsInstPrinter.h"
+#include "MCTargetDesc/MipsBaseInfo.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
 #include "llvm/GlobalVariable.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/CallingConv.h"
-#include "InstPrinter/MipsInstPrinter.h"
 #include "llvm/CodeGen/CallingConvLower.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
@@ -35,27 +36,29 @@
 #include "llvm/Support/ErrorHandling.h"
 using namespace llvm;
=20
-// If I is a shifted mask, set the size (Size) and the first bit of the=20
+// If I is a shifted mask, set the size (Size) and the first bit of the
 // mask (Pos), and return true.
-// For example, if I is 0x003ff800, (Pos, Size) =3D (11, 11). =20
+// For example, if I is 0x003ff800, (Pos, Size) =3D (11, 11).
 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
-  if (!isUInt<32>(I) || !isShiftedMask_32(I))
+  if (!isShiftedMask_64(I))
      return false;
=20
-  Size =3D CountPopulation_32(I);
-  Pos =3D CountTrailingZeros_32(I);
+  Size =3D CountPopulation_64(I);
+  Pos =3D CountTrailingZeros_64(I);
   return true;
 }
=20
+static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
+  MipsFunctionInfo *FI =3D DAG.getMachineFunction().getInfo<MipsFunctionIn=
fo>();
+  return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
+}
+
 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
   switch (Opcode) {
   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
   case MipsISD::Hi:                return "MipsISD::Hi";
   case MipsISD::Lo:                return "MipsISD::Lo";
   case MipsISD::GPRel:             return "MipsISD::GPRel";
-  case MipsISD::TlsGd:             return "MipsISD::TlsGd";
-  case MipsISD::TprelHi:           return "MipsISD::TprelHi";
-  case MipsISD::TprelLo:           return "MipsISD::TprelLo";
   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
   case MipsISD::Ret:               return "MipsISD::Ret";
   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
@@ -71,7 +74,7 @@
   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
-  case MipsISD::WrapperPIC:        return "MipsISD::WrapperPIC";
+  case MipsISD::Wrapper:           return "MipsISD::Wrapper";
   case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
   case MipsISD::Sync:              return "MipsISD::Sync";
   case MipsISD::Ext:               return "MipsISD::Ext";
@@ -84,7 +87,8 @@
 MipsTargetLowering(MipsTargetMachine &TM)
   : TargetLowering(TM, new MipsTargetObjectFile()),
     Subtarget(&TM.getSubtarget<MipsSubtarget>()),
-    HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()) {
+    HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
+    IsO32(Subtarget->isABI_O32()) {
=20
   // Mips does not have i1 type, so use i32 for
   // setcc operations results (slt, sgt, ...).
@@ -93,17 +97,20 @@
=20
   // Set up the register classes
   addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
-  addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
=20
   if (HasMips64)
     addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
=20
-  // When dealing with single precision only, use libcalls
-  if (!Subtarget->isSingleFloat()) {
-    if (HasMips64)
-      addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
-    else
-      addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
+  if (!TM.Options.UseSoftFloat) {
+    addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
+
+    // When dealing with single precision only, use libcalls
+    if (!Subtarget->isSingleFloat()) {
+      if (HasMips64)
+        addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
+      else
+        addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
+    }
   }
=20
   // Load extented operations for i1 types must be promoted
@@ -123,7 +130,6 @@
=20
   // Mips Custom Operations
   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
-  setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
@@ -131,9 +137,30 @@
   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
+  setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
+  setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Custom);
   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
+  setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
+  setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
+  setOperationAction(ISD::MEMBARRIER,         MVT::Other, Custom);
+  setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
+
+  if (!TM.Options.NoNaNsFPMath) {
+    setOperationAction(ISD::FABS,             MVT::f32,   Custom);
+    setOperationAction(ISD::FABS,             MVT::f64,   Custom);
+  }
+
+  if (HasMips64) {
+    setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
+    setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
+    setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
+    setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
+    setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
+    setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
+    setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,   Custom);
+  }
=20
   setOperationAction(ISD::SDIV, MVT::i32, Expand);
   setOperationAction(ISD::SREM, MVT::i32, Expand);
@@ -149,10 +176,18 @@
   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
+  setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
+  setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
+  setOperationAction(ISD::CTPOP,             MVT::i64,   Expand);
   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
+  setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
=20
@@ -165,8 +200,6 @@
   setOperationAction(ISD::SHL_PARTS,         MVT::i32,   Expand);
   setOperationAction(ISD::SRA_PARTS,         MVT::i32,   Expand);
   setOperationAction(ISD::SRL_PARTS,         MVT::i32,   Expand);
-  setOperationAction(ISD::FCOPYSIGN,         MVT::f32,   Custom);
-  setOperationAction(ISD::FCOPYSIGN,         MVT::f64,   Custom);
   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
@@ -180,9 +213,18 @@
   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
+  setOperationAction(ISD::FREM,              MVT::f32,   Expand);
+  setOperationAction(ISD::FREM,              MVT::f64,   Expand);
+
+  if (!TM.Options.NoNaNsFPMath) {
+    setOperationAction(ISD::FNEG,             MVT::f32,   Expand);
+    setOperationAction(ISD::FNEG,             MVT::f64,   Expand);
+  }
=20
   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
+  setOperationAction(ISD::EXCEPTIONADDR,     MVT::i64, Expand);
   setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
+  setOperationAction(ISD::EHSELECTION,       MVT::i64, Expand);
=20
   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
@@ -192,11 +234,10 @@
   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
=20
-  setOperationAction(ISD::MEMBARRIER,        MVT::Other, Custom);
-  setOperationAction(ISD::ATOMIC_FENCE,      MVT::Other, Custom); =20
-
-  setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand); =20
-  setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand); =20
+  setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);
+  setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);
+  setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);
+  setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);
=20
   setInsertFencesForAtomic(true);
=20
@@ -208,32 +249,46 @@
     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
   }
=20
-  if (!Subtarget->hasBitCount())
+  if (!Subtarget->hasBitCount()) {
     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
-
-  if (!Subtarget->hasSwap())
+    setOperationAction(ISD::CTLZ, MVT::i64, Expand);
+  }
+
+  if (!Subtarget->hasSwap()) {
     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
+    setOperationAction(ISD::BSWAP, MVT::i64, Expand);
+  }
=20
   setTargetDAGCombine(ISD::ADDE);
   setTargetDAGCombine(ISD::SUBE);
   setTargetDAGCombine(ISD::SDIVREM);
   setTargetDAGCombine(ISD::UDIVREM);
-  setTargetDAGCombine(ISD::SETCC);
+  setTargetDAGCombine(ISD::SELECT);
   setTargetDAGCombine(ISD::AND);
   setTargetDAGCombine(ISD::OR);
=20
-  setMinFunctionAlignment(2);
-
-  setStackPointerRegisterToSaveRestore(Mips::SP);
+  setMinFunctionAlignment(HasMips64 ? 3 : 2);
+
+  setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
   computeRegisterProperties();
=20
-  setExceptionPointerRegister(Mips::A0);
-  setExceptionSelectorRegister(Mips::A1);
+  setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
+  setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
 }
=20
 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
   MVT::SimpleValueType SVT =3D VT.getSimpleVT().SimpleTy;
-  return SVT =3D=3D MVT::i64 || SVT =3D=3D MVT::i32 || SVT =3D=3D MVT::i16=
;=20
+
+  switch (SVT) {
+  case MVT::i64:
+  case MVT::i32:
+  case MVT::i16:
+    return true;
+  case MVT::f32:
+    return Subtarget->hasMips32r2Or64();
+  default:
+    return false;
+  }
 }
=20
 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
@@ -290,8 +345,7 @@
   // create MipsMAdd(u) node
   MultOpc =3D MultOpc =3D=3D ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MA=
dd;
=20
-  SDValue MAdd =3D CurDAG->getNode(MultOpc, dl,
-                                 MVT::Glue,
+  SDValue MAdd =3D CurDAG->getNode(MultOpc, dl, MVT::Glue,
                                  MultNode->getOperand(0),// Factor 0
                                  MultNode->getOperand(1),// Factor 1
                                  ADDCNode->getOperand(1),// Lo0
@@ -364,8 +418,7 @@
   // create MipsSub(u) node
   MultOpc =3D MultOpc =3D=3D ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MS=
ub;
=20
-  SDValue MSub =3D CurDAG->getNode(MultOpc, dl,
-                                 MVT::Glue,
+  SDValue MSub =3D CurDAG->getNode(MultOpc, dl, MVT::Glue,
                                  MultNode->getOperand(0),// Factor 0
                                  MultNode->getOperand(1),// Factor 1
                                  SUBCNode->getOperand(0),// Lo0
@@ -394,7 +447,8 @@
   if (DCI.isBeforeLegalize())
     return SDValue();
=20
-  if (Subtarget->hasMips32() && SelectMadd(N, &DAG))
+  if (Subtarget->hasMips32() && N->getValueType(0) =3D=3D MVT::i32 &&
+      SelectMadd(N, &DAG))
     return SDValue(N, 0);
=20
   return SDValue();
@@ -406,7 +460,8 @@
   if (DCI.isBeforeLegalize())
     return SDValue();
=20
-  if (Subtarget->hasMips32() && SelectMsub(N, &DAG))
+  if (Subtarget->hasMips32() && N->getValueType(0) =3D=3D MVT::i32 &&
+      SelectMsub(N, &DAG))
     return SDValue(N, 0);
=20
   return SDValue();
@@ -419,8 +474,8 @@
     return SDValue();
=20
   EVT Ty =3D N->getValueType(0);
-  unsigned LO =3D (Ty =3D=3D MVT::i32) ? Mips::LO : Mips::LO64;=20
-  unsigned HI =3D (Ty =3D=3D MVT::i32) ? Mips::HI : Mips::HI64;=20
+  unsigned LO =3D (Ty =3D=3D MVT::i32) ? Mips::LO : Mips::LO64;
+  unsigned HI =3D (Ty =3D=3D MVT::i32) ? Mips::HI : Mips::HI64;
   unsigned opc =3D N->getOpcode() =3D=3D ISD::SDIVREM ? MipsISD::DivRem :
                                                   MipsISD::DivRemU;
   DebugLoc dl =3D N->getDebugLoc();
@@ -481,11 +536,10 @@
   if (CC >=3D Mips::FCOND_F && CC <=3D Mips::FCOND_NGT)
     return false;
=20
-  if (CC >=3D Mips::FCOND_T && CC <=3D Mips::FCOND_GT)
-    return true;
-
-  assert(false && "Illegal Condition Code");
-  return false;
+  assert((CC >=3D Mips::FCOND_T && CC <=3D Mips::FCOND_GT) &&
+         "Illegal Condition Code");
+
+  return true;
 }
=20
 // Creates and returns an FPCmp node from a setcc node.
@@ -522,21 +576,37 @@
                      True.getValueType(), True, False, Cond);
 }
=20
-static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
-                                   TargetLowering::DAGCombinerInfo &DCI,
-                                   const MipsSubtarget* Subtarget) {
+static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG& DAG,
+                                    TargetLowering::DAGCombinerInfo &DCI,
+                                    const MipsSubtarget* Subtarget) {
   if (DCI.isBeforeLegalizeOps())
     return SDValue();
=20
-  SDValue Cond =3D CreateFPCmp(DAG, SDValue(N, 0));
-
-  if (Cond.getOpcode() !=3D MipsISD::FPCmp)
+  SDValue SetCC =3D N->getOperand(0);
+
+  if ((SetCC.getOpcode() !=3D ISD::SETCC) ||
+      !SetCC.getOperand(0).getValueType().isInteger())
     return SDValue();
=20
-  SDValue True  =3D DAG.getConstant(1, MVT::i32);
-  SDValue False =3D DAG.getConstant(0, MVT::i32);
-
-  return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
+  SDValue False =3D N->getOperand(2);
+  EVT FalseTy =3D False.getValueType();
+
+  if (!FalseTy.isInteger())
+    return SDValue();
+
+  ConstantSDNode *CN =3D dyn_cast<ConstantSDNode>(False);
+
+  if (!CN || CN->getZExtValue())
+    return SDValue();
+
+  const DebugLoc DL =3D N->getDebugLoc();
+  ISD::CondCode CC =3D cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
+  SDValue True =3D N->getOperand(1);
+ =20
+  SetCC =3D DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
+                       SetCC.getOperand(1), ISD::getSetCCInverse(CC, true)=
);
+ =20
+  return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
 }
=20
 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
@@ -549,20 +619,20 @@
     return SDValue();
=20
   SDValue ShiftRight =3D N->getOperand(0), Mask =3D N->getOperand(1);
- =20
+  unsigned ShiftRightOpc =3D ShiftRight.getOpcode();
+
   // Op's first operand must be a shift right.
-  if (ShiftRight.getOpcode() !=3D ISD::SRA && ShiftRight.getOpcode() !=3D =
ISD::SRL)
+  if (ShiftRightOpc !=3D ISD::SRA && ShiftRightOpc !=3D ISD::SRL)
     return SDValue();
=20
   // The second operand of the shift must be an immediate.
-  uint64_t Pos;
   ConstantSDNode *CN;
   if (!(CN =3D dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
     return SDValue();
- =20
-  Pos =3D CN->getZExtValue();
-
+
+  uint64_t Pos =3D CN->getZExtValue();
   uint64_t SMPos, SMSize;
+
   // Op's second operand must be a shifted mask.
   if (!(CN =3D dyn_cast<ConstantSDNode>(Mask)) ||
       !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
@@ -570,21 +640,21 @@
=20
   // Return if the shifted mask does not start at bit 0 or the sum of its =
size
   // and Pos exceeds the word's size.
-  if (SMPos !=3D 0 || Pos + SMSize > 32)
+  EVT ValTy =3D N->getValueType(0);
+  if (SMPos !=3D 0 || Pos + SMSize > ValTy.getSizeInBits())
     return SDValue();
=20
-  return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
-                     ShiftRight.getOperand(0),
-                     DAG.getConstant(Pos, MVT::i32),
+  return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
+                     ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i=
32),
                      DAG.getConstant(SMSize, MVT::i32));
 }
- =20
+
 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
                                 TargetLowering::DAGCombinerInfo &DCI,
                                 const MipsSubtarget* Subtarget) {
   // Pattern match INS.
   //  $dst =3D or (and $src1 , mask0), (and (shl $src, pos), mask1),
-  //  where mask1 =3D (2**size - 1) << pos, mask0 =3D ~mask1=20
+  //  where mask1 =3D (2**size - 1) << pos, mask0 =3D ~mask1
   //  =3D> ins $dst, $src, size, pos, $src1
   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
     return SDValue();
@@ -604,7 +674,7 @@
   // See if Op's second operand matches (and (shl $src, pos), mask1).
   if (And1.getOpcode() !=3D ISD::AND)
     return SDValue();
- =20
+
   if (!(CN =3D dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
       !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
     return SDValue();
@@ -623,17 +693,16 @@
   unsigned Shamt =3D CN->getZExtValue();
=20
   // Return if the shift amount and the first bit position of mask are not=
 the
-  // same. =20
-  if (Shamt !=3D SMPos0)
+  // same.
+  EVT ValTy =3D N->getValueType(0);
+  if ((Shamt !=3D SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
     return SDValue();
- =20
-  return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
-                     Shl.getOperand(0),
+
+  return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand=
(0),
                      DAG.getConstant(SMPos0, MVT::i32),
-                     DAG.getConstant(SMSize0, MVT::i32),
-                     And0.getOperand(0)); =20
+                     DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0=
));
 }
- =20
+
 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo =
&DCI)
   const {
   SelectionDAG &DAG =3D DCI.DAG;
@@ -648,8 +717,8 @@
   case ISD::SDIVREM:
   case ISD::UDIVREM:
     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
-  case ISD::SETCC:
-    return PerformSETCCCombine(N, DAG, DCI, Subtarget);
+  case ISD::SELECT:
+    return PerformSELECTCombine(N, DAG, DCI, Subtarget); =20
   case ISD::AND:
     return PerformANDCombine(N, DAG, DCI, Subtarget);
   case ISD::OR:
@@ -672,8 +741,10 @@
     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
     case ISD::SELECT:             return LowerSELECT(Op, DAG);
+    case ISD::SETCC:              return LowerSETCC(Op, DAG);
     case ISD::VASTART:            return LowerVASTART(Op, DAG);
     case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
+    case ISD::FABS:               return LowerFABS(Op, DAG);
     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
     case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
@@ -689,7 +760,7 @@
 // MachineFunction as a live in value.  It also creates a corresponding
 // virtual register for it.
 static unsigned
-AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
+AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *R=
C)
 {
   assert(RC->contains(PReg) && "Not the correct regclass!");
   unsigned VReg =3D MF.getRegInfo().createVirtualRegister(RC);
@@ -702,12 +773,13 @@
   if (CC >=3D Mips::FCOND_F && CC <=3D Mips::FCOND_NGT)
     return Mips::BRANCH_T;
=20
-  if (CC >=3D Mips::FCOND_T && CC <=3D Mips::FCOND_GT)
-    return Mips::BRANCH_F;
-
-  return Mips::BRANCH_INVALID;
+  assert((CC >=3D Mips::FCOND_T && CC <=3D Mips::FCOND_GT) &&
+         "Invalid CondCode.");
+
+  return Mips::BRANCH_F;
 }
=20
+/*
 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBloc=
k *BB,
                                         DebugLoc dl,
                                         const MipsSubtarget* Subtarget,
@@ -783,89 +855,115 @@
   MI->eraseFromParent();   // The pseudo instruction is gone now.
   return BB;
 }
-
+*/
 MachineBasicBlock *
 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
                                                 MachineBasicBlock *BB) con=
st {
-  const TargetInstrInfo *TII =3D getTargetMachine().getInstrInfo();
-  DebugLoc dl =3D MI->getDebugLoc();
-
   switch (MI->getOpcode()) {
-  default:
-    assert(false && "Unexpected instr type to insert");
-    return NULL;
-  case Mips::MOVT:
-  case Mips::MOVT_S:
-  case Mips::MOVT_D:
-    return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1F);
-  case Mips::MOVF:
-  case Mips::MOVF_S:
-  case Mips::MOVF_D:
-    return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1T);
-  case Mips::MOVZ_I:
-  case Mips::MOVZ_S:
-  case Mips::MOVZ_D:
-    return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BNE);
-  case Mips::MOVN_I:
-  case Mips::MOVN_S:
-  case Mips::MOVN_D:
-    return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BEQ);
-
+  default: llvm_unreachable("Unexpected instr type to insert");
   case Mips::ATOMIC_LOAD_ADD_I8:
+  case Mips::ATOMIC_LOAD_ADD_I8_P8:
     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
   case Mips::ATOMIC_LOAD_ADD_I16:
+  case Mips::ATOMIC_LOAD_ADD_I16_P8:
     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
   case Mips::ATOMIC_LOAD_ADD_I32:
+  case Mips::ATOMIC_LOAD_ADD_I32_P8:
     return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
+  case Mips::ATOMIC_LOAD_ADD_I64:
+  case Mips::ATOMIC_LOAD_ADD_I64_P8:
+    return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
=20
   case Mips::ATOMIC_LOAD_AND_I8:
+  case Mips::ATOMIC_LOAD_AND_I8_P8:
     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
   case Mips::ATOMIC_LOAD_AND_I16:
+  case Mips::ATOMIC_LOAD_AND_I16_P8:
     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
   case Mips::ATOMIC_LOAD_AND_I32:
+  case Mips::ATOMIC_LOAD_AND_I32_P8:
     return EmitAtomicBinary(MI, BB, 4, Mips::AND);
+  case Mips::ATOMIC_LOAD_AND_I64:
+  case Mips::ATOMIC_LOAD_AND_I64_P8:
+    return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
=20
   case Mips::ATOMIC_LOAD_OR_I8:
+  case Mips::ATOMIC_LOAD_OR_I8_P8:
     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
   case Mips::ATOMIC_LOAD_OR_I16:
+  case Mips::ATOMIC_LOAD_OR_I16_P8:
     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
   case Mips::ATOMIC_LOAD_OR_I32:
+  case Mips::ATOMIC_LOAD_OR_I32_P8:
     return EmitAtomicBinary(MI, BB, 4, Mips::OR);
+  case Mips::ATOMIC_LOAD_OR_I64:
+  case Mips::ATOMIC_LOAD_OR_I64_P8:
+    return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
=20
   case Mips::ATOMIC_LOAD_XOR_I8:
+  case Mips::ATOMIC_LOAD_XOR_I8_P8:
     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
   case Mips::ATOMIC_LOAD_XOR_I16:
+  case Mips::ATOMIC_LOAD_XOR_I16_P8:
     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
   case Mips::ATOMIC_LOAD_XOR_I32:
+  case Mips::ATOMIC_LOAD_XOR_I32_P8:
     return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
+  case Mips::ATOMIC_LOAD_XOR_I64:
+  case Mips::ATOMIC_LOAD_XOR_I64_P8:
+    return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
=20
   case Mips::ATOMIC_LOAD_NAND_I8:
+  case Mips::ATOMIC_LOAD_NAND_I8_P8:
     return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
   case Mips::ATOMIC_LOAD_NAND_I16:
+  case Mips::ATOMIC_LOAD_NAND_I16_P8:
     return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
   case Mips::ATOMIC_LOAD_NAND_I32:
+  case Mips::ATOMIC_LOAD_NAND_I32_P8:
     return EmitAtomicBinary(MI, BB, 4, 0, true);
+  case Mips::ATOMIC_LOAD_NAND_I64:
+  case Mips::ATOMIC_LOAD_NAND_I64_P8:
+    return EmitAtomicBinary(MI, BB, 8, 0, true);
=20
   case Mips::ATOMIC_LOAD_SUB_I8:
+  case Mips::ATOMIC_LOAD_SUB_I8_P8:
     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
   case Mips::ATOMIC_LOAD_SUB_I16:
+  case Mips::ATOMIC_LOAD_SUB_I16_P8:
     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
   case Mips::ATOMIC_LOAD_SUB_I32:
+  case Mips::ATOMIC_LOAD_SUB_I32_P8:
     return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
+  case Mips::ATOMIC_LOAD_SUB_I64:
+  case Mips::ATOMIC_LOAD_SUB_I64_P8:
+    return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
=20
   case Mips::ATOMIC_SWAP_I8:
+  case Mips::ATOMIC_SWAP_I8_P8:
     return EmitAtomicBinaryPartword(MI, BB, 1, 0);
   case Mips::ATOMIC_SWAP_I16:
+  case Mips::ATOMIC_SWAP_I16_P8:
     return EmitAtomicBinaryPartword(MI, BB, 2, 0);
   case Mips::ATOMIC_SWAP_I32:
+  case Mips::ATOMIC_SWAP_I32_P8:
     return EmitAtomicBinary(MI, BB, 4, 0);
+  case Mips::ATOMIC_SWAP_I64:
+  case Mips::ATOMIC_SWAP_I64_P8:
+    return EmitAtomicBinary(MI, BB, 8, 0);
=20
   case Mips::ATOMIC_CMP_SWAP_I8:
+  case Mips::ATOMIC_CMP_SWAP_I8_P8:
     return EmitAtomicCmpSwapPartword(MI, BB, 1);
   case Mips::ATOMIC_CMP_SWAP_I16:
+  case Mips::ATOMIC_CMP_SWAP_I16_P8:
     return EmitAtomicCmpSwapPartword(MI, BB, 2);
   case Mips::ATOMIC_CMP_SWAP_I32:
+  case Mips::ATOMIC_CMP_SWAP_I32_P8:
     return EmitAtomicCmpSwap(MI, BB, 4);
+  case Mips::ATOMIC_CMP_SWAP_I64:
+  case Mips::ATOMIC_CMP_SWAP_I64_P8:
+    return EmitAtomicCmpSwap(MI, BB, 8);
   }
 }
=20
@@ -875,13 +973,31 @@
 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *=
BB,
                                      unsigned Size, unsigned BinOpcode,
                                      bool Nand) const {
-  assert(Size =3D=3D 4 && "Unsupported size for EmitAtomicBinary.");
+  assert((Size =3D=3D 4 || Size =3D=3D 8) && "Unsupported size for EmitAto=
micBinary.");
=20
   MachineFunction *MF =3D BB->getParent();
   MachineRegisterInfo &RegInfo =3D MF->getRegInfo();
-  const TargetRegisterClass *RC =3D getRegClassFor(MVT::i32);
+  const TargetRegisterClass *RC =3D getRegClassFor(MVT::getIntegerVT(Size =
* 8));
   const TargetInstrInfo *TII =3D getTargetMachine().getInstrInfo();
   DebugLoc dl =3D MI->getDebugLoc();
+  unsigned LL, SC, AND, NOR, ZERO, BEQ;
+
+  if (Size =3D=3D 4) {
+    LL =3D IsN64 ? Mips::LL_P8 : Mips::LL;
+    SC =3D IsN64 ? Mips::SC_P8 : Mips::SC;
+    AND =3D Mips::AND;
+    NOR =3D Mips::NOR;
+    ZERO =3D Mips::ZERO;
+    BEQ =3D Mips::BEQ;
+  }
+  else {
+    LL =3D IsN64 ? Mips::LLD_P8 : Mips::LLD;
+    SC =3D IsN64 ? Mips::SCD_P8 : Mips::SCD;
+    AND =3D Mips::AND64;
+    NOR =3D Mips::NOR64;
+    ZERO =3D Mips::ZERO_64;
+    BEQ =3D Mips::BEQ64;
+  }
=20
   unsigned OldVal =3D MI->getOperand(0).getReg();
   unsigned Ptr =3D MI->getOperand(1).getReg();
@@ -919,23 +1035,20 @@
   //    sc success, storeval, 0(ptr)
   //    beq success, $0, loopMBB
   BB =3D loopMBB;
-  BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(Ptr).addImm(0);
+  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
   if (Nand) {
     //  and andres, oldval, incr
     //  nor storeval, $0, andres
-    BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Inc=
r);
-    BuildMI(BB, dl, TII->get(Mips::NOR), StoreVal)
-      .addReg(Mips::ZERO).addReg(AndRes);
+    BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
+    BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
   } else if (BinOpcode) {
     //  <binop> storeval, oldval, incr
     BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(I=
ncr);
   } else {
     StoreVal =3D Incr;
   }
-  BuildMI(BB, dl, TII->get(Mips::SC), Success)
-    .addReg(StoreVal).addReg(Ptr).addImm(0);
-  BuildMI(BB, dl, TII->get(Mips::BEQ))
-    .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
+  BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addI=
mm(0);
+  BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopM=
BB);
=20
   MI->eraseFromParent();   // The instruction is gone now.
=20
@@ -955,6 +1068,8 @@
   const TargetRegisterClass *RC =3D getRegClassFor(MVT::i32);
   const TargetInstrInfo *TII =3D getTargetMachine().getInstrInfo();
   DebugLoc dl =3D MI->getDebugLoc();
+  unsigned LL =3D IsN64 ? Mips::LL_P8 : Mips::LL;
+  unsigned SC =3D IsN64 ? Mips::SC_P8 : Mips::SC;
=20
   unsigned Dest =3D MI->getOperand(0).getReg();
   unsigned Ptr =3D MI->getOperand(1).getReg();
@@ -992,8 +1107,7 @@
=20
   // Transfer the remainder of BB and its successor edges to exitMBB.
   exitMBB->splice(exitMBB->begin(), BB,
-                  llvm::next(MachineBasicBlock::iterator(MI)),
-                  BB->end());
+                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
=20
   BB->addSuccessor(loopMBB);
@@ -1025,7 +1139,6 @@
   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Ma=
sk);
   BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Inc=
r);
=20
-
   // atomic.load.binop
   // loopMBB:
   //   ll      oldval,0(alignedaddr)
@@ -1046,7 +1159,7 @@
   //   beq     success,$0,loopMBB
=20
   BB =3D loopMBB;
-  BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0=
);
+  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
   if (Nand) {
     //  and andres, oldval, incr2
     //  nor binopres, $0, andres
@@ -1064,12 +1177,12 @@
     //  and newval, incr2, mask
     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask=
);
   }
-   =20
+
   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
     .addReg(OldVal).addReg(Mask2);
   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
     .addReg(MaskedOldVal0).addReg(NewVal);
-  BuildMI(BB, dl, TII->get(Mips::SC), Success)
+  BuildMI(BB, dl, TII->get(SC), Success)
     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
   BuildMI(BB, dl, TII->get(Mips::BEQ))
     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
@@ -1100,13 +1213,29 @@
 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
                                       MachineBasicBlock *BB,
                                       unsigned Size) const {
-  assert(Size =3D=3D 4 && "Unsupported size for EmitAtomicCmpSwap.");
+  assert((Size =3D=3D 4 || Size =3D=3D 8) && "Unsupported size for EmitAto=
micCmpSwap.");
=20
   MachineFunction *MF =3D BB->getParent();
   MachineRegisterInfo &RegInfo =3D MF->getRegInfo();
-  const TargetRegisterClass *RC =3D getRegClassFor(MVT::i32);
+  const TargetRegisterClass *RC =3D getRegClassFor(MVT::getIntegerVT(Size =
* 8));
   const TargetInstrInfo *TII =3D getTargetMachine().getInstrInfo();
   DebugLoc dl =3D MI->getDebugLoc();
+  unsigned LL, SC, ZERO, BNE, BEQ;
+
+  if (Size =3D=3D 4) {
+    LL =3D IsN64 ? Mips::LL_P8 : Mips::LL;
+    SC =3D IsN64 ? Mips::SC_P8 : Mips::SC;
+    ZERO =3D Mips::ZERO;
+    BNE =3D Mips::BNE;
+    BEQ =3D Mips::BEQ;
+  }
+  else {
+    LL =3D IsN64 ? Mips::LLD_P8 : Mips::LLD;
+    SC =3D IsN64 ? Mips::SCD_P8 : Mips::SCD;
+    ZERO =3D Mips::ZERO_64;
+    BNE =3D Mips::BNE64;
+    BEQ =3D Mips::BEQ64;
+  }
=20
   unsigned Dest    =3D MI->getOperand(0).getReg();
   unsigned Ptr     =3D MI->getOperand(1).getReg();
@@ -1128,8 +1257,7 @@
=20
   // Transfer the remainder of BB and its successor edges to exitMBB.
   exitMBB->splice(exitMBB->begin(), BB,
-                  llvm::next(MachineBasicBlock::iterator(MI)),
-                  BB->end());
+                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
=20
   //  thisMBB:
@@ -1145,18 +1273,18 @@
   //   ll dest, 0(ptr)
   //   bne dest, oldval, exitMBB
   BB =3D loop1MBB;
-  BuildMI(BB, dl, TII->get(Mips::LL), Dest).addReg(Ptr).addImm(0);
-  BuildMI(BB, dl, TII->get(Mips::BNE))
+  BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
+  BuildMI(BB, dl, TII->get(BNE))
     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
=20
   // loop2MBB:
   //   sc success, newval, 0(ptr)
   //   beq success, $0, loop1MBB
   BB =3D loop2MBB;
-  BuildMI(BB, dl, TII->get(Mips::SC), Success)
+  BuildMI(BB, dl, TII->get(SC), Success)
     .addReg(NewVal).addReg(Ptr).addImm(0);
-  BuildMI(BB, dl, TII->get(Mips::BEQ))
-    .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
+  BuildMI(BB, dl, TII->get(BEQ))
+    .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
=20
   MI->eraseFromParent();   // The instruction is gone now.
=20
@@ -1175,6 +1303,8 @@
   const TargetRegisterClass *RC =3D getRegClassFor(MVT::i32);
   const TargetInstrInfo *TII =3D getTargetMachine().getInstrInfo();
   DebugLoc dl =3D MI->getDebugLoc();
+  unsigned LL =3D IsN64 ? Mips::LL_P8 : Mips::LL;
+  unsigned SC =3D IsN64 ? Mips::SC_P8 : Mips::SC;
=20
   unsigned Dest    =3D MI->getOperand(0).getReg();
   unsigned Ptr     =3D MI->getOperand(1).getReg();
@@ -1215,8 +1345,7 @@
=20
   // Transfer the remainder of BB and its successor edges to exitMBB.
   exitMBB->splice(exitMBB->begin(), BB,
-                  llvm::next(MachineBasicBlock::iterator(MI)),
-                  BB->end());
+                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
=20
   BB->addSuccessor(loop1MBB);
@@ -1265,7 +1394,7 @@
   //    and     maskedoldval0,oldval,mask
   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
   BB =3D loop1MBB;
-  BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0=
);
+  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
     .addReg(OldVal).addReg(Mask);
   BuildMI(BB, dl, TII->get(Mips::BNE))
@@ -1281,7 +1410,7 @@
     .addReg(OldVal).addReg(Mask2);
   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
-  BuildMI(BB, dl, TII->get(Mips::SC), Success)
+  BuildMI(BB, dl, TII->get(SC), Success)
       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
   BuildMI(BB, dl, TII->get(Mips::BEQ))
       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
@@ -1313,6 +1442,7 @@
 {
   MachineFunction &MF =3D DAG.getMachineFunction();
   MipsFunctionInfo *MipsFI =3D MF.getInfo<MipsFunctionInfo>();
+  unsigned SP =3D IsN64 ? Mips::SP_64 : Mips::SP;
=20
   assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=3D
          cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() =
&&
@@ -1324,20 +1454,19 @@
   DebugLoc dl =3D Op.getDebugLoc();
=20
   // Get a reference from Mips stack pointer
-  SDValue StackPointer =3D DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i3=
2);
+  SDValue StackPointer =3D DAG.getCopyFromReg(Chain, dl, SP, getPointerTy(=
));
=20
   // Subtract the dynamic size from the actual stack size to
   // obtain the new stack size.
-  SDValue Sub =3D DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
+  SDValue Sub =3D DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, =
Size);
=20
   // The Sub result contains the new stack start address, so it
   // must be placed in the stack pointer register.
-  Chain =3D DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
-                           SDValue());
+  Chain =3D DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValu=
e());
=20
   // This node always has two return values: a new stack pointer
   // value and a chain
-  SDVTList VTLs =3D DAG.getVTList(MVT::i32, MVT::Other);
+  SDVTList VTLs =3D DAG.getVTList(getPointerTy(), MVT::Other);
   SDValue Ptr =3D DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy(=
));
   SDValue Ops[] =3D { Chain, Ptr, Chain.getValue(1) };
=20
@@ -1381,11 +1510,23 @@
                       Op.getDebugLoc());
 }
=20
+SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) cons=
t {
+  SDValue Cond =3D CreateFPCmp(DAG, Op);
+
+  assert(Cond.getOpcode() =3D=3D MipsISD::FPCmp &&
+         "Floating point operand expected.");
+
+  SDValue True  =3D DAG.getConstant(1, MVT::i32);
+  SDValue False =3D DAG.getConstant(0, MVT::i32);
+
+  return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
+}
+
 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
                                                SelectionDAG &DAG) const {
   // FIXME there isn't actually debug info here
   DebugLoc dl =3D Op.getDebugLoc();
-  const GlobalValue *GV =3D cast<GlobalAddressSDNode>(Op)->getGlobal(); =09
+  const GlobalValue *GV =3D cast<GlobalAddressSDNode>(Op)->getGlobal();
=20
   if (getTargetMachine().getRelocationModel() !=3D Reloc::PIC_ && !IsN64) {
     SDVTList VTs =3D DAG.getVTList(MVT::i32);
@@ -1413,21 +1554,20 @@
   EVT ValTy =3D Op.getValueType();
   bool HasGotOfst =3D (GV->hasInternalLinkage() ||
                      (GV->hasLocalLinkage() && !isa<Function>(GV)));
-  unsigned GotFlag =3D IsN64 ?
+  unsigned GotFlag =3D HasMips64 ?
                      (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DI=
SP) :
-                     MipsII::MO_GOT;
+                     (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
   SDValue GA =3D DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
-  GA =3D DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
-  SDValue ResNode =3D DAG.getLoad(ValTy, dl,
-                                DAG.getEntryNode(), GA, MachinePointerInfo=
(),
-                                false, false, 0);
+  GA =3D DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy)=
, GA);
+  SDValue ResNode =3D DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
+                                MachinePointerInfo(), false, false, false,=
 0);
   // On functions and global targets not internal linked only
   // a load from got/GP is necessary for PIC to work.
   if (!HasGotOfst)
     return ResNode;
   SDValue GALo =3D DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
-                                            IsN64 ? MipsII::MO_GOT_OFST :
-                                                    MipsII::MO_ABS_LO);
+                                            HasMips64 ? MipsII::MO_GOT_OFS=
T :
+                                                        MipsII::MO_ABS_LO);
   SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
   return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
 }
@@ -1438,35 +1578,34 @@
   // FIXME there isn't actually debug info here
   DebugLoc dl =3D Op.getDebugLoc();
=20
-  if (getTargetMachine().getRelocationModel() !=3D Reloc::PIC_) {
+  if (getTargetMachine().getRelocationModel() !=3D Reloc::PIC_ && !IsN64) {
     // %hi/%lo relocation
-    SDValue BAHi =3D DAG.getBlockAddress(BA, MVT::i32, true,
-                                       MipsII::MO_ABS_HI);
-    SDValue BALo =3D DAG.getBlockAddress(BA, MVT::i32, true,
-                                       MipsII::MO_ABS_LO);
+    SDValue BAHi =3D DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_AB=
S_HI);
+    SDValue BALo =3D DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_AB=
S_LO);
     SDValue Hi =3D DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
     SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
     return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
   }
=20
-  SDValue BAGOTOffset =3D DAG.getBlockAddress(BA, MVT::i32, true,
-                                            MipsII::MO_GOT);
-  BAGOTOffset =3D DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffs=
et);
-  SDValue BALOOffset =3D DAG.getBlockAddress(BA, MVT::i32, true,
-                                           MipsII::MO_ABS_LO);
-  SDValue Load =3D DAG.getLoad(MVT::i32, dl,
-                             DAG.getEntryNode(), BAGOTOffset,
-                             MachinePointerInfo(), false, false, 0);
-  SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
-  return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
+  EVT ValTy =3D Op.getValueType();
+  unsigned GOTFlag =3D HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
+  unsigned OFSTFlag =3D HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_L=
O;
+  SDValue BAGOTOffset =3D DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
+  BAGOTOffset =3D DAG.getNode(MipsISD::Wrapper, dl, ValTy,
+                            GetGlobalReg(DAG, ValTy), BAGOTOffset);
+  SDValue BALOOffset =3D DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
+  SDValue Load =3D DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
+                             MachinePointerInfo(), false, false, false, 0);
+  SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
+  return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
 }
=20
 SDValue MipsTargetLowering::
 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
 {
-  // If the relocation model is PIC, use the General Dynamic TLS Model,
-  // otherwise use the Initial Exec or Local Exec TLS Model.
-  // TODO: implement Local Dynamic TLS model
+  // If the relocation model is PIC, use the General Dynamic TLS Model or
+  // Local Dynamic TLS model, otherwise use the Initial Exec or
+  // Local Exec TLS Model.
=20
   GlobalAddressSDNode *GA =3D cast<GlobalAddressSDNode>(Op);
   DebugLoc dl =3D GA->getDebugLoc();
@@ -1475,45 +1614,63 @@
=20
   if (getTargetMachine().getRelocationModel() =3D=3D Reloc::PIC_) {
     // General Dynamic TLS Model
-    SDValue TGA =3D DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
-                                             0, MipsII::MO_TLSGD);
-    SDValue Tlsgd =3D DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
-    SDValue GP =3D DAG.getRegister(Mips::GP, MVT::i32);
-    SDValue Argument =3D DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
+    bool LocalDynamic =3D GV->hasInternalLinkage();
+    unsigned Flag =3D LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
+    SDValue TGA =3D DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
+    SDValue Argument =3D DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
+                                   GetGlobalReg(DAG, PtrVT), TGA);
+    unsigned PtrSize =3D PtrVT.getSizeInBits();
+    IntegerType *PtrTy =3D Type::getIntNTy(*DAG.getContext(), PtrSize);
+
+    SDValue TlsGetAddr =3D DAG.getExternalSymbol("__tls_get_addr", PtrVT);
=20
     ArgListTy Args;
     ArgListEntry Entry;
     Entry.Node =3D Argument;
-    Entry.Ty =3D (Type *) Type::getInt32Ty(*DAG.getContext());
+    Entry.Ty =3D PtrTy;
     Args.push_back(Entry);
+
     std::pair<SDValue, SDValue> CallResult =3D
-        LowerCallTo(DAG.getEntryNode(),
-                    (Type *) Type::getInt32Ty(*DAG.getContext()),
-                    false, false, false, false, 0, CallingConv::C, false, =
true,
-                    DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, =
DAG,
-                    dl);
-
-    return CallResult.first;
+      LowerCallTo(DAG.getEntryNode(), PtrTy,
+                  false, false, false, false, 0, CallingConv::C,
+                  /*isTailCall=3D*/false, /*doesNotRet=3D*/false,
+                  /*isReturnValueUsed=3D*/true,
+                  TlsGetAddr, Args, DAG, dl);
+
+    SDValue Ret =3D CallResult.first;
+
+    if (!LocalDynamic)
+      return Ret;
+
+    SDValue TGAHi =3D DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
+                                               MipsII::MO_DTPREL_HI);
+    SDValue Hi =3D DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
+    SDValue TGALo =3D DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
+                                               MipsII::MO_DTPREL_LO);
+    SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
+    SDValue Add =3D DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
+    return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
   }
=20
   SDValue Offset;
   if (GV->isDeclaration()) {
     // Initial Exec TLS Model
-    SDValue TGA =3D DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
+    SDValue TGA =3D DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
                                              MipsII::MO_GOTTPREL);
-    Offset =3D DAG.getLoad(MVT::i32, dl,
+    TGA =3D DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, Ptr=
VT),
+                      TGA);
+    Offset =3D DAG.getLoad(PtrVT, dl,
                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
-                         false, false, 0);
+                         false, false, false, 0);
   } else {
     // Local Exec TLS Model
-    SDVTList VTs =3D DAG.getVTList(MVT::i32);
-    SDValue TGAHi =3D DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
+    SDValue TGAHi =3D DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
                                                MipsII::MO_TPREL_HI);
-    SDValue TGALo =3D DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
+    SDValue TGALo =3D DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
                                                MipsII::MO_TPREL_LO);
-    SDValue Hi =3D DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
-    SDValue Lo =3D DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
-    Offset =3D DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
+    SDValue Hi =3D DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
+    SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
+    Offset =3D DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
   }
=20
   SDValue ThreadPointer =3D DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
@@ -1523,34 +1680,30 @@
 SDValue MipsTargetLowering::
 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
 {
-  SDValue ResNode;
-  SDValue HiPart;
+  SDValue HiPart, JTI, JTILo;
   // FIXME there isn't actually debug info here
   DebugLoc dl =3D Op.getDebugLoc();
   bool IsPIC =3D getTargetMachine().getRelocationModel() =3D=3D Reloc::PIC=
_;
-  unsigned char OpFlag =3D IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
-
   EVT PtrVT =3D Op.getValueType();
-  JumpTableSDNode *JT  =3D cast<JumpTableSDNode>(Op);
-
-  SDValue JTI =3D DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
-
-  if (!IsPIC) {
-    SDValue Ops[] =3D { JTI };
-    HiPart =3D DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, =
1);
+  JumpTableSDNode *JT =3D cast<JumpTableSDNode>(Op);
+
+  if (!IsPIC && !IsN64) {
+    JTI =3D DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_H=
I);
+    HiPart =3D DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
+    JTILo =3D DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS=
_LO);
   } else {// Emit Load from Global Pointer
-    JTI =3D DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
-    HiPart =3D DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
-                         MachinePointerInfo(),
-                         false, false, 0);
+    unsigned GOTFlag =3D HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
+    unsigned OfstFlag =3D HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS=
_LO;
+    JTI =3D DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
+    JTI =3D DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, Ptr=
VT),
+                      JTI);
+    HiPart =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
+                         MachinePointerInfo(), false, false, false, 0);
+    JTILo =3D DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
   }
=20
-  SDValue JTILo =3D DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
-                                         MipsII::MO_ABS_LO);
-  SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
-  ResNode =3D DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
-
-  return ResNode;
+  SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
+  return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
 }
=20
 SDValue MipsTargetLowering::
@@ -1572,7 +1725,7 @@
   //  SDValue GOT =3D DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
   //  ResNode =3D DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
=20
-  if (getTargetMachine().getRelocationModel() !=3D Reloc::PIC_) {
+  if (getTargetMachine().getRelocationModel() !=3D Reloc::PIC_ && !IsN64) {
     SDValue CPHi =3D DAG.getTargetConstantPool(C, MVT::i32, N->getAlignmen=
t(),
                                              N->getOffset(), MipsII::MO_AB=
S_HI);
     SDValue CPLo =3D DAG.getTargetConstantPool(C, MVT::i32, N->getAlignmen=
t(),
@@ -1581,16 +1734,19 @@
     SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
     ResNode =3D DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
   } else {
-    SDValue CP =3D DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(=
),
-                                           N->getOffset(), MipsII::MO_GOT);
-    CP =3D DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
-    SDValue Load =3D DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
-                               CP, MachinePointerInfo::getConstantPool(),
+    EVT ValTy =3D Op.getValueType();
+    unsigned GOTFlag =3D HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
+    unsigned OFSTFlag =3D HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS=
_LO;
+    SDValue CP =3D DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
+                                           N->getOffset(), GOTFlag);
+    CP =3D DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValT=
y), CP);
+    SDValue Load =3D DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
+                               MachinePointerInfo::getConstantPool(), fals=
e,
                                false, false, 0);
-    SDValue CPLo =3D DAG.getTargetConstantPool(C, MVT::i32, N->getAlignmen=
t(),
-                                             N->getOffset(), MipsII::MO_AB=
S_LO);
-    SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
-    ResNode =3D DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
+    SDValue CPLo =3D DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
+                                             N->getOffset(), OFSTFlag);
+    SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
+    ResNode =3D DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
   }
=20
   return ResNode;
@@ -1608,62 +1764,165 @@
   // memory location argument.
   const Value *SV =3D cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
-                      MachinePointerInfo(SV),
-                      false, false, 0);
+                      MachinePointerInfo(SV), false, false, 0);
 }
=20
-static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
-  // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
-  DebugLoc dl =3D Op.getDebugLoc();
-  SDValue Op0 =3D DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0)=
);
-  SDValue Op1 =3D DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1)=
);
-  SDValue And0 =3D DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
-                             DAG.getConstant(0x7fffffff, MVT::i32));
-  SDValue And1 =3D DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
-                             DAG.getConstant(0x80000000, MVT::i32));
-  SDValue Result =3D DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
-  return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
+static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2)=
 {
+  EVT TyX =3D Op.getOperand(0).getValueType();
+  EVT TyY =3D Op.getOperand(1).getValueType();
+  SDValue Const1 =3D DAG.getConstant(1, MVT::i32);
+  SDValue Const31 =3D DAG.getConstant(31, MVT::i32);
+  DebugLoc DL =3D Op.getDebugLoc();
+  SDValue Res;
+
+  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitca=
st it
+  // to i32.
+  SDValue X =3D (TyX =3D=3D MVT::f32) ?
+    DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
+    DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
+                Const1);
+  SDValue Y =3D (TyY =3D=3D MVT::f32) ?
+    DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
+    DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
+                Const1);
+
+  if (HasR2) {
+    // ext  E, Y, 31, 1  ; extract bit31 of Y
+    // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
+    SDValue E =3D DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Cons=
t1);
+    Res =3D DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
+  } else {
+    // sll SllX, X, 1
+    // srl SrlX, SllX, 1
+    // srl SrlY, Y, 31
+    // sll SllY, SrlX, 31
+    // or  Or, SrlX, SllY
+    SDValue SllX =3D DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
+    SDValue SrlX =3D DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
+    SDValue SrlY =3D DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
+    SDValue SllY =3D DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
+    Res =3D DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
+  }
+
+  if (TyX =3D=3D MVT::f32)
+    return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), =
Res);
+
+  SDValue LowX =3D DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
+                             Op.getOperand(0), DAG.getConstant(0, MVT::i32=
));
+  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
 }
=20
-static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLitt=
le) {
-  // FIXME:
-  //  Use ext/ins instructions if target architecture is Mips32r2.
-  //  Eliminate redundant mfc1 and mtc1 instructions.
-  unsigned LoIdx =3D 0, HiIdx =3D 1;
-
-  if (!isLittle)
-    std::swap(LoIdx, HiIdx);
-
-  DebugLoc dl =3D Op.getDebugLoc();
-  SDValue Word0 =3D DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
-                              Op.getOperand(0),
-                              DAG.getConstant(LoIdx, MVT::i32));
-  SDValue Hi0 =3D DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
-                            Op.getOperand(0), DAG.getConstant(HiIdx, MVT::=
i32));
-  SDValue Hi1 =3D DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
-                            Op.getOperand(1), DAG.getConstant(HiIdx, MVT::=
i32));
-  SDValue And0 =3D DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
-                             DAG.getConstant(0x7fffffff, MVT::i32));
-  SDValue And1 =3D DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
-                             DAG.getConstant(0x80000000, MVT::i32));
-  SDValue Word1 =3D DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
-
-  if (!isLittle)
-    std::swap(Word0, Word1);
-
-  return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
+static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2)=
 {
+  unsigned WidthX =3D Op.getOperand(0).getValueSizeInBits();
+  unsigned WidthY =3D Op.getOperand(1).getValueSizeInBits();
+  EVT TyX =3D MVT::getIntegerVT(WidthX), TyY =3D MVT::getIntegerVT(WidthY);
+  SDValue Const1 =3D DAG.getConstant(1, MVT::i32);
+  DebugLoc DL =3D Op.getDebugLoc();
+
+  // Bitcast to integer nodes.
+  SDValue X =3D DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
+  SDValue Y =3D DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
+
+  if (HasR2) {
+    // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
+    // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-=
1 of X
+    SDValue E =3D DAG.getNode(MipsISD::Ext, DL, TyY, Y,
+                            DAG.getConstant(WidthY - 1, MVT::i32), Const1);
+
+    if (WidthX > WidthY)
+      E =3D DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
+    else if (WidthY > WidthX)
+      E =3D DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
+
+    SDValue I =3D DAG.getNode(MipsISD::Ins, DL, TyX, E,
+                            DAG.getConstant(WidthX - 1, MVT::i32), Const1,=
 X);
+    return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), =
I);
+  }
+
+  // (d)sll SllX, X, 1
+  // (d)srl SrlX, SllX, 1
+  // (d)srl SrlY, Y, width(Y)-1
+  // (d)sll SllY, SrlX, width(Y)-1
+  // or     Or, SrlX, SllY
+  SDValue SllX =3D DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
+  SDValue SrlX =3D DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
+  SDValue SrlY =3D DAG.getNode(ISD::SRL, DL, TyY, Y,
+                             DAG.getConstant(WidthY - 1, MVT::i32));
+
+  if (WidthX > WidthY)
+    SrlY =3D DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
+  else if (WidthY > WidthX)
+    SrlY =3D DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
+
+  SDValue SllY =3D DAG.getNode(ISD::SHL, DL, TyX, SrlY,
+                             DAG.getConstant(WidthX - 1, MVT::i32));
+  SDValue Or =3D DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
+  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or=
);
 }
=20
-SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
-  const {
-  EVT Ty =3D Op.getValueType();
-
-  assert(Ty =3D=3D MVT::f32 || Ty =3D=3D MVT::f64);
-
-  if (Ty =3D=3D MVT::f32)
-    return LowerFCOPYSIGN32(Op, DAG);
-  else
-    return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
+SDValue
+MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
+  if (Subtarget->hasMips64())
+    return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
+
+  return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
+}
+
+static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
+  SDValue Res, Const1 =3D DAG.getConstant(1, MVT::i32);
+  DebugLoc DL =3D Op.getDebugLoc();
+
+  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitca=
st it
+  // to i32.
+  SDValue X =3D (Op.getValueType() =3D=3D MVT::f32) ?
+    DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
+    DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
+                Const1);
+
+  // Clear MSB.
+  if (HasR2)
+    Res =3D DAG.getNode(MipsISD::Ins, DL, MVT::i32,
+                      DAG.getRegister(Mips::ZERO, MVT::i32),
+                      DAG.getConstant(31, MVT::i32), Const1, X);
+  else {
+    SDValue SllX =3D DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
+    Res =3D DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
+  }
+
+  if (Op.getValueType() =3D=3D MVT::f32)
+    return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
+
+  SDValue LowX =3D DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
+                             Op.getOperand(0), DAG.getConstant(0, MVT::i32=
));
+  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
+}
+
+static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
+  SDValue Res, Const1 =3D DAG.getConstant(1, MVT::i32);
+  DebugLoc DL =3D Op.getDebugLoc();
+
+  // Bitcast to integer node.
+  SDValue X =3D DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
+
+  // Clear MSB.
+  if (HasR2)
+    Res =3D DAG.getNode(MipsISD::Ins, DL, MVT::i64,
+                      DAG.getRegister(Mips::ZERO_64, MVT::i64),
+                      DAG.getConstant(63, MVT::i32), Const1, X);
+  else {
+    SDValue SllX =3D DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
+    Res =3D DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
+  }
+
+  return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
+}
+
+SDValue
+MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
+  if (Subtarget->hasMips64() && (Op.getValueType() =3D=3D MVT::f64))
+    return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
+
+  return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
 }
=20
 SDValue MipsTargetLowering::
@@ -1676,13 +1935,14 @@
   MFI->setFrameAddressIsTaken(true);
   EVT VT =3D Op.getValueType();
   DebugLoc dl =3D Op.getDebugLoc();
-  SDValue FrameAddr =3D DAG.getCopyFromReg(DAG.getEntryNode(), dl, Mips::F=
P, VT);
+  SDValue FrameAddr =3D DAG.getCopyFromReg(DAG.getEntryNode(), dl,
+                                         IsN64 ? Mips::FP_64 : Mips::FP, V=
T);
   return FrameAddr;
 }
=20
 // TODO: set SType according to the desired memory barrier behavior.
-SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
-                                            SelectionDAG& DAG) const {
+SDValue
+MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
   unsigned SType =3D 0;
   DebugLoc dl =3D Op.getDebugLoc();
   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
@@ -1703,8 +1963,6 @@
 //                      Calling Convention Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "MipsGenCallingConv.inc"
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // TODO: Implement a generic logic using tblgen that can support this.
 // Mips O32 ABI rules:
@@ -1726,13 +1984,13 @@
=20
   static const unsigned IntRegsSize=3D4, FloatRegsSize=3D2;
=20
-  static const unsigned IntRegs[] =3D {
+  static const uint16_t IntRegs[] =3D {
       Mips::A0, Mips::A1, Mips::A2, Mips::A3
   };
-  static const unsigned F32Regs[] =3D {
+  static const uint16_t F32Regs[] =3D {
       Mips::F12, Mips::F14
   };
-  static const unsigned F64Regs[] =3D {
+  static const uint16_t F64Regs[] =3D {
       Mips::D6, Mips::D7
   };
=20
@@ -1811,13 +2069,77 @@
   return false; // CC must always match
 }
=20
+static const uint16_t Mips64IntRegs[8] =3D
+  {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
+   Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
+static const uint16_t Mips64DPRegs[8] =3D
+  {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
+   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
+
+static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
+                           CCValAssign::LocInfo LocInfo,
+                           ISD::ArgFlagsTy ArgFlags, CCState &State) {
+  unsigned Align =3D std::max(ArgFlags.getByValAlign(), (unsigned)8);
+  unsigned Size  =3D (ArgFlags.getByValSize() + 7) / 8 * 8;
+  unsigned FirstIdx =3D State.getFirstUnallocated(Mips64IntRegs, 8);
+
+  assert(Align <=3D 16 && "Cannot handle alignments larger than 16.");
+
+  // If byval is 16-byte aligned, the first arg register must be even.
+  if ((Align =3D=3D 16) && (FirstIdx % 2)) {
+    State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
+    ++FirstIdx;
+  }
+
+  // Mark the registers allocated.
+  for (unsigned I =3D FirstIdx; Size && (I < 8); Size -=3D 8, ++I)
+    State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
+
+  // Allocate space on caller's stack.
+  unsigned Offset =3D State.AllocateStack(Size, Align);
+
+  if (FirstIdx < 8)
+    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
+                                     LocVT, LocInfo));
+  else
+    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo)=
);
+
+  return true;
+}
+
+#include "MipsGenCallingConv.inc"
+
+static void
+AnalyzeMips64CallOperands(CCState &CCInfo,
+                          const SmallVectorImpl<ISD::OutputArg> &Outs) {
+  unsigned NumOps =3D Outs.size();
+  for (unsigned i =3D 0; i !=3D NumOps; ++i) {
+    MVT ArgVT =3D Outs[i].VT;
+    ISD::ArgFlagsTy ArgFlags =3D Outs[i].Flags;
+    bool R;
+
+    if (Outs[i].IsFixed)
+      R =3D CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
+    else
+      R =3D CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, =
CCInfo);
+
+    if (R) {
+#ifndef NDEBUG
+      dbgs() << "Call operand #" << i << " has unhandled type "
+             << EVT(ArgVT).getEVTString();
+#endif
+      llvm_unreachable(0);
+    }
+  }
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                  Call Calling Convention Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 static const unsigned O32IntRegsSize =3D 4;
=20
-static const unsigned O32IntRegs[] =3D {
+static const uint16_t O32IntRegs[] =3D {
   Mips::A0, Mips::A1, Mips::A2, Mips::A3
 };
=20
@@ -1848,9 +2170,8 @@
     SDValue LoadPtr =3D DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
                                   DAG.getConstant(Offset, MVT::i32));
     SDValue LoadVal =3D DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
-                                  MachinePointerInfo(),
-                                  false, false, std::min(ByValAlign,
-                                                         (unsigned )4));
+                                  MachinePointerInfo(), false, false, fals=
e,
+                                  std::min(ByValAlign, (unsigned )4));
     MemOpChains.push_back(LoadVal.getValue(1));
     unsigned DstReg =3D O32IntRegs[LocMemOffset / 4];
     RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
@@ -1886,7 +2207,7 @@
     // Read second subword if necessary.
     if (RemainingSize !=3D 0)  {
       assert(RemainingSize =3D=3D 1 && "There must be one byte remaining."=
);
-      LoadPtr =3D DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,=20
+      LoadPtr =3D DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
                             DAG.getConstant(Offset, MVT::i32));
       unsigned Alignment =3D std::min(ByValAlign, (unsigned )2);
       SDValue Subword =3D DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chai=
n,
@@ -1919,13 +2240,101 @@
                              MachinePointerInfo(0), MachinePointerInfo(0));
 }
=20
+// Copy Mips64 byVal arg to registers and stack.
+void static
+PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
+               SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
+               SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
+               MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
+               const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
+               EVT PtrTy, bool isLittle) {
+  unsigned ByValSize =3D Flags.getByValSize();
+  unsigned Alignment =3D std::min(Flags.getByValAlign(), (unsigned)8);
+  bool IsRegLoc =3D VA.isRegLoc();
+  unsigned Offset =3D 0; // Offset in # of bytes from the beginning of str=
uct.
+  unsigned LocMemOffset =3D 0;
+  unsigned MemCpySize =3D ByValSize;
+
+  if (!IsRegLoc)
+    LocMemOffset =3D VA.getLocMemOffset();
+  else {
+    const uint16_t *Reg =3D std::find(Mips64IntRegs, Mips64IntRegs + 8,
+                                    VA.getLocReg());
+    const uint16_t *RegEnd =3D Mips64IntRegs + 8;
+
+    // Copy double words to registers.
+    for (; (Reg !=3D RegEnd) && (ByValSize >=3D Offset + 8); ++Reg, Offset=
 +=3D 8) {
+      SDValue LoadPtr =3D DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
+                                    DAG.getConstant(Offset, PtrTy));
+      SDValue LoadVal =3D DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
+                                    MachinePointerInfo(), false, false, fa=
lse,
+                                    Alignment);
+      MemOpChains.push_back(LoadVal.getValue(1));
+      RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
+    }
+
+    // Return if the struct has been fully copied.
+    if (!(MemCpySize =3D ByValSize - Offset))
+      return;
+
+    // If there is an argument register available, copy the remainder of t=
he
+    // byval argument with sub-doubleword loads and shifts.
+    if (Reg !=3D RegEnd) {
+      assert((ByValSize < Offset + 8) &&
+             "Size of the remainder should be smaller than 8-byte.");
+      SDValue Val;
+      for (unsigned LoadSize =3D 4; Offset < ByValSize; LoadSize /=3D 2) {
+        unsigned RemSize =3D ByValSize - Offset;
+
+        if (RemSize < LoadSize)
+          continue;
+
+        SDValue LoadPtr =3D DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
+                                      DAG.getConstant(Offset, PtrTy));
+        SDValue LoadVal =3D
+          DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
+                         MachinePointerInfo(), MVT::getIntegerVT(LoadSize =
* 8),
+                         false, false, Alignment);
+        MemOpChains.push_back(LoadVal.getValue(1));
+
+        // Offset in number of bits from double word boundary.
+        unsigned OffsetDW =3D (Offset % 8) * 8;
+        unsigned Shamt =3D isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize=
 * 8);
+        SDValue Shift =3D DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
+                                    DAG.getConstant(Shamt, MVT::i32));
+
+        Val =3D Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Sh=
ift) :
+                              Shift;
+        Offset +=3D LoadSize;
+        Alignment =3D std::min(Alignment, LoadSize);
+      }
+
+      RegsToPass.push_back(std::make_pair(*Reg, Val));
+      return;
+    }
+  }
+
+  assert(MemCpySize && "MemCpySize must not be zero.");
+
+  // Create a fixed object on stack at offset LocMemOffset and copy
+  // remainder of byval arg to it with memcpy.
+  SDValue Src =3D DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
+                            DAG.getConstant(Offset, PtrTy));
+  LastFI =3D MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
+  SDValue Dst =3D DAG.getFrameIndex(LastFI, PtrTy);
+  ByValChain =3D DAG.getMemcpy(ByValChain, dl, Dst, Src,
+                             DAG.getConstant(MemCpySize, PtrTy), Alignment,
+                             /*isVolatile=3D*/false, /*AlwaysInline=3D*/fa=
lse,
+                             MachinePointerInfo(0), MachinePointerInfo(0));
+}
+
 /// LowerCall - functions arguments are copied from virtual regs to
 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitt=
ed.
 /// TODO: isTailCall.
 SDValue
 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
                               CallingConv::ID CallConv, bool isVarArg,
-                              bool &isTailCall,
+                              bool doesNotRet, bool &isTailCall,
                               const SmallVectorImpl<ISD::OutputArg> &Outs,
                               const SmallVectorImpl<SDValue> &OutVals,
                               const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -1943,10 +2352,12 @@
   // Analyze operands of the call, assigning locations to each operand.
   SmallVector<CCValAssign, 16> ArgLocs;
   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
-		 getTargetMachine(), ArgLocs, *DAG.getContext());
-
-  if (Subtarget->isABI_O32())
+                 getTargetMachine(), ArgLocs, *DAG.getContext());
+
+  if (IsO32)
     CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
+  else if (HasMips64)
+    AnalyzeMips64CallOperands(CCInfo, Outs);
   else
     CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
=20
@@ -1963,7 +2374,7 @@
=20
   // If this is the first call, create a stack frame object that points to
   // a location to which .cprestore saves $gp.
-  if (IsPIC && !MipsFI->getGPFI())
+  if (IsO32 && IsPIC && MipsFI->globalBaseRegFixed() && !MipsFI->getGPFI())
     MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
=20
   // Get the frame index of the stack frame object that points to the loca=
tion
@@ -1973,7 +2384,7 @@
   // Update size of the maximum argument space.
   // For O32, a minimum of four words (16 bytes) of argument space is
   // allocated.
-  if (Subtarget->isABI_O32())
+  if (IsO32)
     NextStackOffset =3D std::max(NextStackOffset, (unsigned)16);
=20
   unsigned MaxCallFrameSize =3D MipsFI->getMaxCallFrameSize();
@@ -1988,7 +2399,7 @@
     NextStackOffset =3D (NextStackOffset + StackAlignment - 1) /
                       StackAlignment * StackAlignment;
=20
-    if (IsPIC)
+    if (MipsFI->needGPSaveRestore())
       MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
=20
     MFI->setObjectOffset(DynAllocFI, NextStackOffset);
@@ -2004,22 +2415,40 @@
   for (unsigned i =3D 0, e =3D ArgLocs.size(); i !=3D e; ++i) {
     SDValue Arg =3D OutVals[i];
     CCValAssign &VA =3D ArgLocs[i];
+    MVT ValVT =3D VA.getValVT(), LocVT =3D VA.getLocVT();
+    ISD::ArgFlagsTy Flags =3D Outs[i].Flags;
+
+    // ByVal Arg.
+    if (Flags.isByVal()) {
+      assert(Flags.getByValSize() &&
+             "ByVal args of size 0 should have been ignored by front-end."=
);
+      if (IsO32)
+        WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, Last=
FI,
+                      MFI, DAG, Arg, VA, Flags, getPointerTy(),
+                      Subtarget->isLittle());
+      else
+        PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, Las=
tFI,
+                       MFI, DAG, Arg, VA, Flags, getPointerTy(),
+                       Subtarget->isLittle());
+      continue;
+    }
=20
     // Promote the value if needed.
     switch (VA.getLocInfo()) {
     default: llvm_unreachable("Unknown loc info!");
     case CCValAssign::Full:
-      if (Subtarget->isABI_O32() && VA.isRegLoc()) {
-        if (VA.getValVT() =3D=3D MVT::f32 && VA.getLocVT() =3D=3D MVT::i32)
-          Arg =3D DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
-        if (VA.getValVT() =3D=3D MVT::f64 && VA.getLocVT() =3D=3D MVT::i32=
) {
+      if (VA.isRegLoc()) {
+        if ((ValVT =3D=3D MVT::f32 && LocVT =3D=3D MVT::i32) ||
+            (ValVT =3D=3D MVT::f64 && LocVT =3D=3D MVT::i64))
+          Arg =3D DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
+        else if (ValVT =3D=3D MVT::f64 && LocVT =3D=3D MVT::i32) {
           SDValue Lo =3D DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::=
i32,
                                    Arg, DAG.getConstant(0, MVT::i32));
           SDValue Hi =3D DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::=
i32,
                                    Arg, DAG.getConstant(1, MVT::i32));
           if (!Subtarget->isLittle())
             std::swap(Lo, Hi);
-          unsigned LocRegLo =3D VA.getLocReg();=20
+          unsigned LocRegLo =3D VA.getLocReg();
           unsigned LocRegHigh =3D getNextIntArgReg(LocRegLo);
           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
@@ -2028,13 +2457,13 @@
       }
       break;
     case CCValAssign::SExt:
-      Arg =3D DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
+      Arg =3D DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
       break;
     case CCValAssign::ZExt:
-      Arg =3D DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
+      Arg =3D DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
       break;
     case CCValAssign::AExt:
-      Arg =3D DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
+      Arg =3D DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
       break;
     }
=20
@@ -2048,28 +2477,15 @@
     // Register can't get to this point...
     assert(VA.isMemLoc());
=20
-    // ByVal Arg.
-    ISD::ArgFlagsTy Flags =3D Outs[i].Flags;
-    if (Flags.isByVal()) {
-      assert(Subtarget->isABI_O32() &&
-             "No support for ByVal args by ABIs other than O32 yet.");
-      assert(Flags.getByValSize() &&
-             "ByVal args of size 0 should have been ignored by front-end."=
);
-      WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI=
, MFI,
-                    DAG, Arg, VA, Flags, getPointerTy(), Subtarget->isLitt=
le());
-      continue;
-    }
-
     // Create the frame index object for this incoming parameter
-    LastFI =3D MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
+    LastFI =3D MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
                                     VA.getLocMemOffset(), true);
     SDValue PtrOff =3D DAG.getFrameIndex(LastFI, getPointerTy());
=20
     // emit ISD::STORE whichs stores the
     // parameter value to a stack Location
     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
-                                       MachinePointerInfo(),
-                                       false, false, 0));
+                                       MachinePointerInfo(), false, false,=
 0));
   }
=20
   // Extend range of indices of frame objects for outgoing arguments that =
were
@@ -2093,52 +2509,68 @@
   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, e=
very
   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymb=
ol
   // node so that legalize doesn't hack it.
-  unsigned char OpFlag =3D IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLA=
G;
-  bool LoadSymAddr =3D false;
+  unsigned char OpFlag;
+  bool IsPICCall =3D (IsN64 || IsPIC); // true if calls are translated to =
jalr $25
+  bool GlobalOrExternal =3D false;
   SDValue CalleeLo;
=20
   if (GlobalAddressSDNode *G =3D dyn_cast<GlobalAddressSDNode>(Callee)) {
-    if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
-      Callee =3D DAG.getTargetGlobalAddress(G->getGlobal(), dl,
-                                          getPointerTy(), 0,MipsII:: MO_GO=
T);
+    if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
+      OpFlag =3D IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
+      unsigned char LoFlag =3D IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_=
OFST;
+      Callee =3D DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointer=
Ty(), 0,
+                                          OpFlag);
       CalleeLo =3D DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPoint=
erTy(),
-                                            0, MipsII::MO_ABS_LO);
+                                            0, LoFlag);
     } else {
+      OpFlag =3D IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
       Callee =3D DAG.getTargetGlobalAddress(G->getGlobal(), dl,
                                           getPointerTy(), 0, OpFlag);
     }
=20
-    LoadSymAddr =3D true;
+    GlobalOrExternal =3D true;
   }
   else if (ExternalSymbolSDNode *S =3D dyn_cast<ExternalSymbolSDNode>(Call=
ee)) {
-    Callee =3D DAG.getTargetExternalSymbol(S->getSymbol(),
-                                getPointerTy(), OpFlag);
-    LoadSymAddr =3D true;
+    if (IsN64 || (!IsO32 && IsPIC))
+      OpFlag =3D MipsII::MO_GOT_DISP;
+    else if (!IsPIC) // !N64 && static
+      OpFlag =3D MipsII::MO_NO_FLAG;
+    else // O32 & PIC
+      OpFlag =3D MipsII::MO_GOT_CALL;
+    Callee =3D DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
+                                         OpFlag);
+    GlobalOrExternal =3D true;
   }
=20
   SDValue InFlag;
=20
   // Create nodes that load address of callee and copy it to T9
-  if (IsPIC) {
-    if (LoadSymAddr) {
+  if (IsPICCall) {
+    if (GlobalOrExternal) {
       // Load callee address
-      Callee =3D DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, Callee);
-      SDValue LoadValue =3D DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), =
Callee,
-                                      MachinePointerInfo::getGOT(),
-                                      false, false, 0);
+      Callee =3D DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
+                           GetGlobalReg(DAG, getPointerTy()), Callee);
+      SDValue LoadValue =3D DAG.getLoad(getPointerTy(), dl, DAG.getEntryNo=
de(),
+                                      Callee, MachinePointerInfo::getGOT(),
+                                      false, false, false, 0);
=20
       // Use GOT+LO if callee has internal linkage.
       if (CalleeLo.getNode()) {
-        SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
-        Callee =3D DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
+        SDValue Lo =3D DAG.getNode(MipsISD::Lo, dl, getPointerTy(), Callee=
Lo);
+        Callee =3D DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo=
);
       } else
         Callee =3D LoadValue;
     }
-
+  }
+
+  // T9 should contain the address of the callee function if
+  // -reloction-model=3Dpic or it is an indirect call.
+  if (IsPICCall || !GlobalOrExternal) {
     // copy to T9
-    Chain =3D DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
+    unsigned T9Reg =3D IsN64 ? Mips::T9_64 : Mips::T9;
+    Chain =3D DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
     InFlag =3D Chain.getValue(1);
-    Callee =3D DAG.getRegister(Mips::T9, MVT::i32);
+    Callee =3D DAG.getRegister(T9Reg, getPointerTy());
   }
=20
   // Build a sequence of copy-to-reg nodes chained together with token
@@ -2166,6 +2598,12 @@
     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
                                   RegsToPass[i].second.getValueType()));
=20
+  // Add a register mask operand representing the call-preserved registers.
+  const TargetRegisterInfo *TRI =3D getTargetMachine().getRegisterInfo();
+  const uint32_t *Mask =3D TRI->getCallPreservedMask(CallConv);
+  assert(Mask && "Missing call preserved mask for calling convention");
+  Ops.push_back(DAG.getRegisterMask(Mask));
+
   if (InFlag.getNode())
     Ops.push_back(InFlag);
=20
@@ -2216,7 +2654,8 @@
 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
                          std::vector<SDValue>& OutChains,
                          SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
-                         const CCValAssign &VA, const ISD::ArgFlagsTy& Fla=
gs) {
+                         const CCValAssign &VA, const ISD::ArgFlagsTy& Fla=
gs,
+                         const Argument *FuncArg) {
   unsigned LocMem =3D VA.getLocMemOffset();
   unsigned FirstWord =3D LocMem / 4;
=20
@@ -2231,20 +2670,58 @@
     SDValue StorePtr =3D DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
                                    DAG.getConstant(i * 4, MVT::i32));
     SDValue Store =3D DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i3=
2),
-                                 StorePtr, MachinePointerInfo(), false,
-                                 false, 0);
+                                 StorePtr, MachinePointerInfo(FuncArg, i *=
 4),
+                                 false, false, 0);
     OutChains.push_back(Store);
   }
 }
=20
+// Create frame object on stack and copy registers used for byval passing =
to it.
+static unsigned
+CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
+                    std::vector<SDValue>& OutChains, SelectionDAG &DAG,
+                    const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
+                    MachineFrameInfo *MFI, bool IsRegLoc,
+                    SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *Mi=
psFI,
+                    EVT PtrTy, const Argument *FuncArg) {
+  const uint16_t *Reg =3D Mips64IntRegs + 8;
+  int FOOffset; // Frame object offset from virtual frame pointer.
+
+  if (IsRegLoc) {
+    Reg =3D std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
+    FOOffset =3D (Reg - Mips64IntRegs) * 8 - 8 * 8;
+  }
+  else
+    FOOffset =3D VA.getLocMemOffset();
+
+  // Create frame object.
+  unsigned NumRegs =3D (Flags.getByValSize() + 7) / 8;
+  unsigned LastFI =3D MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
+  SDValue FIN =3D DAG.getFrameIndex(LastFI, PtrTy);
+  InVals.push_back(FIN);
+
+  // Copy arg registers.
+  for (unsigned I =3D 0; (Reg !=3D Mips64IntRegs + 8) && (I < NumRegs);
+       ++Reg, ++I) {
+    unsigned VReg =3D AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
+    SDValue StorePtr =3D DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
+                                   DAG.getConstant(I * 8, PtrTy));
+    SDValue Store =3D DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i=
64),
+                                 StorePtr, MachinePointerInfo(FuncArg, I *=
 8),
+                                 false, false, 0);
+    OutChains.push_back(Store);
+  }
+
+  return LastFI;
+}
+
 /// LowerFormalArguments - transform physical registers into virtual regis=
ters
 /// and generate load operations for arguments places on the stack.
 SDValue
 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
                                          CallingConv::ID CallConv,
                                          bool isVarArg,
-                                         const SmallVectorImpl<ISD::InputA=
rg>
-                                         &Ins,
+                                      const SmallVectorImpl<ISD::InputArg>=
 &Ins,
                                          DebugLoc dl, SelectionDAG &DAG,
                                          SmallVectorImpl<SDValue> &InVals)
                                           const {
@@ -2260,23 +2737,46 @@
   // Assign locations to all of the incoming arguments.
   SmallVector<CCValAssign, 16> ArgLocs;
   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
-		 getTargetMachine(), ArgLocs, *DAG.getContext());
-
-  if (Subtarget->isABI_O32())
+                 getTargetMachine(), ArgLocs, *DAG.getContext());
+
+  if (IsO32)
     CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
   else
     CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
=20
+  Function::const_arg_iterator FuncArg =3D
+    DAG.getMachineFunction().getFunction()->arg_begin();
   int LastFI =3D 0;// MipsFI->LastInArgFI is 0 at the entry of this functi=
on.
=20
-  for (unsigned i =3D 0, e =3D ArgLocs.size(); i !=3D e; ++i) {
+  for (unsigned i =3D 0, e =3D ArgLocs.size(); i !=3D e; ++i, ++FuncArg) {
     CCValAssign &VA =3D ArgLocs[i];
+    EVT ValVT =3D VA.getValVT();
+    ISD::ArgFlagsTy Flags =3D Ins[i].Flags;
+    bool IsRegLoc =3D VA.isRegLoc();
+
+    if (Flags.isByVal()) {
+      assert(Flags.getByValSize() &&
+             "ByVal args of size 0 should have been ignored by front-end."=
);
+      if (IsO32) {
+        unsigned NumWords =3D (Flags.getByValSize() + 3) / 4;
+        LastFI =3D MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset=
(),
+                                        true);
+        SDValue FIN =3D DAG.getFrameIndex(LastFI, getPointerTy());
+        InVals.push_back(FIN);
+        ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Fla=
gs,
+                     &*FuncArg);
+      } else // N32/64
+        LastFI =3D CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, =
Flags,
+                                     MFI, IsRegLoc, InVals, MipsFI,
+                                     getPointerTy(), &*FuncArg);
+      continue;
+    }
=20
     // Arguments stored on registers
-    if (VA.isRegLoc()) {
+    if (IsRegLoc) {
       EVT RegVT =3D VA.getLocVT();
       unsigned ArgReg =3D VA.getLocReg();
-      TargetRegisterClass *RC =3D 0;
+      const TargetRegisterClass *RC;
=20
       if (RegVT =3D=3D MVT::i32)
         RC =3D Mips::CPURegsRegisterClass;
@@ -2305,23 +2805,22 @@
           Opcode =3D ISD::AssertZext;
         if (Opcode)
           ArgValue =3D DAG.getNode(Opcode, dl, RegVT, ArgValue,
-                                 DAG.getValueType(VA.getValVT()));
-        ArgValue =3D DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValu=
e);
+                                 DAG.getValueType(ValVT));
+        ArgValue =3D DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
       }
=20
-      // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
-      if (Subtarget->isABI_O32()) {
-        if (RegVT =3D=3D MVT::i32 && VA.getValVT() =3D=3D MVT::f32)
-          ArgValue =3D DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
-        if (RegVT =3D=3D MVT::i32 && VA.getValVT() =3D=3D MVT::f64) {
-          unsigned Reg2 =3D AddLiveIn(DAG.getMachineFunction(),
-                                    getNextIntArgReg(ArgReg), RC);
-          SDValue ArgValue2 =3D DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
-          if (!Subtarget->isLittle())
-            std::swap(ArgValue, ArgValue2);
-          ArgValue =3D DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
-                                 ArgValue, ArgValue2);
-        }
+      // Handle floating point arguments passed in integer registers.
+      if ((RegVT =3D=3D MVT::i32 && ValVT =3D=3D MVT::f32) ||
+          (RegVT =3D=3D MVT::i64 && ValVT =3D=3D MVT::f64))
+        ArgValue =3D DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
+      else if (IsO32 && RegVT =3D=3D MVT::i32 && ValVT =3D=3D MVT::f64) {
+        unsigned Reg2 =3D AddLiveIn(DAG.getMachineFunction(),
+                                  getNextIntArgReg(ArgReg), RC);
+        SDValue ArgValue2 =3D DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
+        if (!Subtarget->isLittle())
+          std::swap(ArgValue, ArgValue2);
+        ArgValue =3D DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
+                               ArgValue, ArgValue2);
       }
=20
       InVals.push_back(ArgValue);
@@ -2330,32 +2829,15 @@
       // sanity check
       assert(VA.isMemLoc());
=20
-      ISD::ArgFlagsTy Flags =3D Ins[i].Flags;
-
-      if (Flags.isByVal()) {
-        assert(Subtarget->isABI_O32() &&
-               "No support for ByVal args by ABIs other than O32 yet.");
-        assert(Flags.getByValSize() &&
-               "ByVal args of size 0 should have been ignored by front-end=
.");
-        unsigned NumWords =3D (Flags.getByValSize() + 3) / 4;
-        LastFI =3D MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset=
(),
-                                        true);
-        SDValue FIN =3D DAG.getFrameIndex(LastFI, getPointerTy());
-        InVals.push_back(FIN);
-        ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Fla=
gs);
-
-        continue;
-      }
-
       // The stack pointer offset is relative to the caller stack frame.
-      LastFI =3D MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
+      LastFI =3D MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
                                       VA.getLocMemOffset(), true);
=20
       // Create load nodes to retrieve arguments from the stack
       SDValue FIN =3D DAG.getFrameIndex(LastFI, getPointerTy());
-      InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
+      InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
                                    MachinePointerInfo::getFixedStack(LastF=
I),
-                                   false, false, 0));
+                                   false, false, false, 0));
     }
   }
=20
@@ -2372,28 +2854,43 @@
     Chain =3D DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
   }
=20
-  if (isVarArg && Subtarget->isABI_O32()) {
+  if (isVarArg) {
+    unsigned NumOfRegs =3D IsO32 ? 4 : 8;
+    const uint16_t *ArgRegs =3D IsO32 ? O32IntRegs : Mips64IntRegs;
+    unsigned Idx =3D CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
+    int FirstRegSlotOffset =3D IsO32 ? 0 : -64 ; // offset of $a0's slot.
+    const TargetRegisterClass *RC
+      =3D IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClas=
s;
+    unsigned RegSize =3D RC->getSize();
+    int RegSlotOffset =3D FirstRegSlotOffset + Idx * RegSize;
+
+    // Offset of the first variable argument from stack pointer.
+    int FirstVaArgOffset;
+
+    if (IsO32 || (Idx =3D=3D NumOfRegs)) {
+      FirstVaArgOffset =3D
+        (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
+    } else
+      FirstVaArgOffset =3D RegSlotOffset;
+
     // Record the frame index of the first variable argument
     // which is a value necessary to VASTART.
-    unsigned NextStackOffset =3D CCInfo.getNextStackOffset();
-    assert(NextStackOffset % 4 =3D=3D 0 &&
-           "NextStackOffset must be aligned to 4-byte boundaries.");
-    LastFI =3D MFI->CreateFixedObject(4, NextStackOffset, true);
+    LastFI =3D MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
     MipsFI->setVarArgsFrameIndex(LastFI);
=20
-    // If NextStackOffset is smaller than o32's 16-byte reserved argument =
area,
-    // copy the integer registers that have not been used for argument pas=
sing
-    // to the caller's stack frame.
-    for (; NextStackOffset < 16; NextStackOffset +=3D 4) {
-      TargetRegisterClass *RC =3D Mips::CPURegsRegisterClass;
-      unsigned Idx =3D NextStackOffset / 4;
-      unsigned Reg =3D AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx]=
, RC);
-      SDValue ArgValue =3D DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
-      LastFI =3D MFI->CreateFixedObject(4, NextStackOffset, true);
+    // Copy the integer registers that have not been used for argument pas=
sing
+    // to the argument register save area. For O32, the save area is alloc=
ated
+    // in the caller's stack frame, while for N32/64, it is allocated in t=
he
+    // callee's stack frame.
+    for (int StackOffset =3D RegSlotOffset;
+         Idx < NumOfRegs; ++Idx, StackOffset +=3D RegSize) {
+      unsigned Reg =3D AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], R=
C);
+      SDValue ArgValue =3D DAG.getCopyFromReg(Chain, dl, Reg,
+                                            MVT::getIntegerVT(RegSize * 8)=
);
+      LastFI =3D MFI->CreateFixedObject(RegSize, StackOffset, true);
       SDValue PtrOff =3D DAG.getFrameIndex(LastFI, getPointerTy());
       OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
-                                       MachinePointerInfo(),
-                                       false, false, 0));
+                                       MachinePointerInfo(), false, false,=
 0));
     }
   }
=20
@@ -2447,8 +2944,7 @@
     CCValAssign &VA =3D RVLocs[i];
     assert(VA.isRegLoc() && "Can only return in registers!");
=20
-    Chain =3D DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
-                             OutVals[i], Flag);
+    Chain =3D DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag=
);
=20
     // guarantee that all emitted copies are
     // stuck together, avoiding something bad
@@ -2505,7 +3001,6 @@
       case 'y':
       case 'f':
         return C_RegisterClass;
-        break;
     }
   }
   return TargetLowering::getConstraintType(Constraint);
@@ -2553,14 +3048,19 @@
     case 'd': // Address register. Same as 'r' unless generating MIPS16 co=
de.
     case 'y': // Same as 'r'. Exists for compatibility.
     case 'r':
-      return std::make_pair(0U, Mips::CPURegsRegisterClass);
+      if (VT =3D=3D MVT::i32)
+        return std::make_pair(0U, Mips::CPURegsRegisterClass);
+      assert(VT =3D=3D MVT::i64 && "Unexpected type.");
+      return std::make_pair(0U, Mips::CPU64RegsRegisterClass);
     case 'f':
       if (VT =3D=3D MVT::f32)
         return std::make_pair(0U, Mips::FGR32RegisterClass);
-      if (VT =3D=3D MVT::f64)
-        if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
+      if ((VT =3D=3D MVT::f64) && (!Subtarget->isSingleFloat())) {
+        if (Subtarget->isFP64bit())
+          return std::make_pair(0U, Mips::FGR64RegisterClass);
+        else
           return std::make_pair(0U, Mips::AFGR64RegisterClass);
-      break;
+      }
     }
   }
   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
@@ -2579,3 +3079,10 @@
     return false;
   return Imm.isZero();
 }
+
+unsigned MipsTargetLowering::getJumpTableEncoding() const {
+  if (IsN64)
+    return MachineJumpTableInfo::EK_GPRel64BlockAddress;
+
+  return TargetLowering::getJumpTableEncoding();
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
ISelLowering.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsISelLowering.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsISelLowering.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,10 +15,10 @@
 #ifndef MipsISELLOWERING_H
 #define MipsISELLOWERING_H
=20
+#include "Mips.h"
+#include "MipsSubtarget.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/Target/TargetLowering.h"
-#include "Mips.h"
-#include "MipsSubtarget.h"
=20
 namespace llvm {
   namespace MipsISD {
@@ -40,13 +40,6 @@
       // Handle gp_rel (small data/bss sections) relocation.
       GPRel,
=20
-      // General Dynamic TLS
-      TlsGd,
-
-      // Local Exec TLS
-      TprelHi,
-      TprelLo,
-
       // Thread Pointer
       ThreadPointer,
=20
@@ -79,7 +72,7 @@
       BuildPairF64,
       ExtractElementF64,
=20
-      WrapperPIC,
+      Wrapper,
=20
       DynAlloc,
=20
@@ -98,6 +91,8 @@
   public:
     explicit MipsTargetLowering(MipsTargetMachine &TM);
=20
+    virtual MVT getShiftAmountTy(EVT LHSTy) const { return MVT::i32; }
+
     virtual bool allowsUnalignedMemoryAccesses (EVT VT) const;
=20
     /// LowerOperation - Provide custom lowering hooks for some operations.
@@ -114,8 +109,8 @@
   private:
     // Subtarget Info
     const MipsSubtarget *Subtarget;
-   =20
-    bool HasMips64, IsN64;
+
+    bool HasMips64, IsN64, IsO32;
=20
     // Lower Operand helpers
     SDValue LowerCallResult(SDValue Chain, SDValue InFlag,
@@ -133,8 +128,10 @@
     SDValue LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerJumpTable(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerSELECT(SDValue Op, SelectionDAG &DAG) const;
+    SDValue LowerSETCC(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const;
+    SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const;
     SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG& DAG) const;
@@ -149,7 +146,7 @@
     virtual SDValue
       LowerCall(SDValue Chain, SDValue Callee,
                 CallingConv::ID CallConv, bool isVarArg,
-                bool &isTailCall,
+                bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -186,6 +183,8 @@
     /// materialize the FP immediate as a load from a constant pool.
     virtual bool isFPImmLegal(const APFloat &Imm, EVT VT) const;
=20
+    virtual unsigned getJumpTableEncoding() const;
+
     MachineBasicBlock *EmitAtomicBinary(MachineInstr *MI, MachineBasicBloc=
k *BB,
                     unsigned Size, unsigned BinOpcode, bool Nand =3D false=
) const;
     MachineBasicBlock *EmitAtomicBinaryPartword(MachineInstr *MI,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
InstrFPU.td
--- a/head/contrib/llvm/lib/Target/Mips/MipsInstrFPU.td	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsInstrFPU.td	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsInstrFPU.td - Mips FPU Instruction Information --*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsInstrFPU.td - Mips FPU Instruction Information -*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -59,6 +59,15 @@
 def IsSingleFloat    : Predicate<"Subtarget.isSingleFloat()">;
 def IsNotSingleFloat : Predicate<"!Subtarget.isSingleFloat()">;
=20
+// FP immediate patterns.
+def fpimm0 : PatLeaf<(fpimm), [{
+  return N->isExactlyValue(+0.0);
+}]>;
+
+def fpimm0neg : PatLeaf<(fpimm), [{
+  return N->isExactlyValue(-0.0);
+}]>;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Instruction Class Templates
 //
@@ -74,19 +83,35 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 // FP load.
-class FPLoad<bits<6> op, string opstr, PatFrag FOp, RegisterClass RC,
-             Operand MemOpnd>:
+class FPLoad<bits<6> op, string opstr, RegisterClass RC, Operand MemOpnd>:
   FMem<op, (outs RC:$ft), (ins MemOpnd:$addr),
-      !strconcat(opstr, "\t$ft, $addr"), [(set RC:$ft, (FOp addr:$addr))],
+      !strconcat(opstr, "\t$ft, $addr"), [(set RC:$ft, (load_a addr:$addr)=
)],
       IILoad>;
=20
 // FP store.
-class FPStore<bits<6> op, string opstr, PatFrag FOp, RegisterClass RC,
-              Operand MemOpnd>:
+class FPStore<bits<6> op, string opstr, RegisterClass RC, Operand MemOpnd>:
   FMem<op, (outs), (ins RC:$ft, MemOpnd:$addr),
-      !strconcat(opstr, "\t$ft, $addr"), [(store RC:$ft, addr:$addr)],
+      !strconcat(opstr, "\t$ft, $addr"), [(store_a RC:$ft, addr:$addr)],
       IIStore>;
=20
+// FP indexed load.
+class FPIdxLoad<bits<6> funct, string opstr, RegisterClass DRC,
+                RegisterClass PRC, PatFrag FOp>:
+  FFMemIdx<funct, (outs DRC:$fd), (ins PRC:$base, PRC:$index),
+           !strconcat(opstr, "\t$fd, $index($base)"),
+           [(set DRC:$fd, (FOp (add PRC:$base, PRC:$index)))]> {
+  let fs =3D 0;
+}
+
+// FP indexed store.
+class FPIdxStore<bits<6> funct, string opstr, RegisterClass DRC,
+                 RegisterClass PRC, PatFrag FOp>:
+  FFMemIdx<funct, (outs), (ins DRC:$fs, PRC:$base, PRC:$index),
+           !strconcat(opstr, "\t$fs, $index($base)"),
+           [(FOp DRC:$fs, (add PRC:$base, PRC:$index))]> {
+  let fd =3D 0;
+}
+
 // Instructions that convert an FP value to 32-bit fixed point.
 multiclass FFR1_W_M<bits<6> funct, string opstr> {
   def _S   : FFR1<funct, 16, opstr, "w.s", FGR32, FGR32>;
@@ -122,6 +147,19 @@
   }
 }
=20
+// FP madd/msub/nmadd/nmsub instruction classes.
+class FMADDSUB<bits<3> funct, bits<3> fmt, string opstr, string fmtstr,
+               SDNode OpNode, RegisterClass RC> :
+  FFMADDSUB<funct, fmt, (outs RC:$fd), (ins RC:$fr, RC:$fs, RC:$ft),
+            !strconcat(opstr, ".", fmtstr, "\t$fd, $fr, $fs, $ft"),
+            [(set RC:$fd, (OpNode (fmul RC:$fs, RC:$ft), RC:$fr))]>;
+
+class FNMADDSUB<bits<3> funct, bits<3> fmt, string opstr, string fmtstr,
+                SDNode OpNode, RegisterClass RC> :
+  FFMADDSUB<funct, fmt, (outs RC:$fd), (ins RC:$fr, RC:$fs, RC:$ft),
+            !strconcat(opstr, ".", fmtstr, "\t$fd, $fr, $fs, $ft"),
+            [(set RC:$fd, (fsub fpimm0, (OpNode (fmul RC:$fs, RC:$ft), RC:=
$fr)))]>;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Floating Point Instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -152,8 +190,10 @@
  def CVT_D64_L : FFR1<0x21, 21, "cvt", "d.l", FGR64, FGR64>;
 }
=20
-defm FABS    : FFR1P_M<0x5, "abs",  fabs>;
-defm FNEG    : FFR1P_M<0x7, "neg",  fneg>;
+let Predicates =3D [NoNaNsFPMath] in {
+  defm FABS    : FFR1P_M<0x5, "abs",  fabs>;
+  defm FNEG    : FFR1P_M<0x7, "neg",  fneg>;
+}
 defm FSQRT   : FFR1P_M<0x4, "sqrt", fsqrt>;
=20
 // The odd-numbered registers are only referenced when doing loads,
@@ -183,6 +223,14 @@
                   "mtc1\t$rt, $fs",
                   [(set FGR32:$fs, (bitconvert CPURegs:$rt))]>;
=20
+def DMFC1 : FFRGPR<0x01, (outs CPU64Regs:$rt), (ins FGR64:$fs),
+                  "dmfc1\t$rt, $fs",
+                  [(set CPU64Regs:$rt, (bitconvert FGR64:$fs))]>;
+
+def DMTC1 : FFRGPR<0x05, (outs FGR64:$fs), (ins CPU64Regs:$rt),
+                  "dmtc1\t$rt, $fs",
+                  [(set FGR64:$fs, (bitconvert CPU64Regs:$rt))]>;
+
 def FMOV_S   : FFR1<0x6, 16, "mov", "s", FGR32, FGR32>;
 def FMOV_D32 : FFR1<0x6, 17, "mov", "d", AFGR64, AFGR64>,
                Requires<[NotFP64bit]>;
@@ -191,23 +239,53 @@
=20
 /// Floating Point Memory Instructions
 let Predicates =3D [IsN64] in {
-  def LWC1_P8   : FPLoad<0x31, "lwc1", load, FGR32, mem64>;
-  def SWC1_P8   : FPStore<0x39, "swc1", store, FGR32, mem64>;
-  def LDC164_P8 : FPLoad<0x35, "ldc1", load, FGR64, mem64>;
-  def SDC164_P8 : FPStore<0x3d, "sdc1", store, FGR64, mem64>;
+  def LWC1_P8   : FPLoad<0x31, "lwc1", FGR32, mem64>;
+  def SWC1_P8   : FPStore<0x39, "swc1", FGR32, mem64>;
+  def LDC164_P8 : FPLoad<0x35, "ldc1", FGR64, mem64>;
+  def SDC164_P8 : FPStore<0x3d, "sdc1", FGR64, mem64>;
 }
=20
 let Predicates =3D [NotN64] in {
-  def LWC1   : FPLoad<0x31, "lwc1", load, FGR32, mem>;
-  def SWC1   : FPStore<0x39, "swc1", store, FGR32, mem>;
-  let Predicates =3D [HasMips64] in {
-    def LDC164 : FPLoad<0x35, "ldc1", load, FGR64, mem>;
-    def SDC164 : FPStore<0x3d, "sdc1", store, FGR64, mem>;
-  }
-  let Predicates =3D [NotMips64] in {
-    def LDC1   : FPLoad<0x35, "ldc1", load, AFGR64, mem>;
-    def SDC1   : FPStore<0x3d, "sdc1", store, AFGR64, mem>;
-  }
+  def LWC1   : FPLoad<0x31, "lwc1", FGR32, mem>;
+  def SWC1   : FPStore<0x39, "swc1", FGR32, mem>;
+}
+
+let Predicates =3D [NotN64, HasMips64] in {
+  def LDC164 : FPLoad<0x35, "ldc1", FGR64, mem>;
+  def SDC164 : FPStore<0x3d, "sdc1", FGR64, mem>;
+}
+
+let Predicates =3D [NotN64, NotMips64] in {
+  def LDC1   : FPLoad<0x35, "ldc1", AFGR64, mem>;
+  def SDC1   : FPStore<0x3d, "sdc1", AFGR64, mem>;
+}
+
+// Indexed loads and stores.
+let Predicates =3D [HasMips32r2Or64] in {
+  def LWXC1 : FPIdxLoad<0x0, "lwxc1", FGR32, CPURegs, load_a>;
+  def LUXC1 : FPIdxLoad<0x5, "luxc1", FGR32, CPURegs, load_u>;
+  def SWXC1 : FPIdxStore<0x8, "swxc1", FGR32, CPURegs, store_a>;
+  def SUXC1 : FPIdxStore<0xd, "suxc1", FGR32, CPURegs, store_u>;
+}
+
+let Predicates =3D [HasMips32r2, NotMips64] in {
+  def LDXC1 : FPIdxLoad<0x1, "ldxc1", AFGR64, CPURegs, load_a>;
+  def SDXC1 : FPIdxStore<0x9, "sdxc1", AFGR64, CPURegs, store_a>;
+}
+
+let Predicates =3D [HasMips64, NotN64] in {
+  def LDXC164 : FPIdxLoad<0x1, "ldxc1", FGR64, CPURegs, load_a>;
+  def SDXC164 : FPIdxStore<0x9, "sdxc1", FGR64, CPURegs, store_a>;
+}
+
+// n64
+let Predicates =3D [IsN64] in {
+  def LWXC1_P8   : FPIdxLoad<0x0, "lwxc1", FGR32, CPU64Regs, load_a>;
+  def LUXC1_P8   : FPIdxLoad<0x5, "luxc1", FGR32, CPU64Regs, load_u>;
+  def LDXC164_P8 : FPIdxLoad<0x1, "ldxc1", FGR64, CPU64Regs, load_a>;
+  def SWXC1_P8   : FPIdxStore<0x8, "swxc1", FGR32, CPU64Regs, store_a>;
+  def SUXC1_P8   : FPIdxStore<0xd, "suxc1", FGR32, CPU64Regs, store_u>;
+  def SDXC164_P8 : FPIdxStore<0x9, "sdxc1", FGR64, CPU64Regs, store_a>;
 }
=20
 /// Floating-point Aritmetic
@@ -216,6 +294,36 @@
 defm FMUL : FFR2P_M<0x02, "mul", fmul, 1>;
 defm FSUB : FFR2P_M<0x01, "sub", fsub>;
=20
+let Predicates =3D [HasMips32r2] in {
+  def MADD_S : FMADDSUB<0x4, 0, "madd", "s", fadd, FGR32>;
+  def MSUB_S : FMADDSUB<0x5, 0, "msub", "s", fsub, FGR32>;
+}
+
+let Predicates =3D [HasMips32r2, NoNaNsFPMath] in {
+  def NMADD_S : FNMADDSUB<0x6, 0, "nmadd", "s", fadd, FGR32>;
+  def NMSUB_S : FNMADDSUB<0x7, 0, "nmsub", "s", fsub, FGR32>;
+}
+
+let Predicates =3D [HasMips32r2, NotFP64bit] in {
+  def MADD_D32 : FMADDSUB<0x4, 1, "madd", "d", fadd, AFGR64>;
+  def MSUB_D32 : FMADDSUB<0x5, 1, "msub", "d", fsub, AFGR64>;
+}
+
+let Predicates =3D [HasMips32r2, NotFP64bit, NoNaNsFPMath] in {
+  def NMADD_D32 : FNMADDSUB<0x6, 1, "nmadd", "d", fadd, AFGR64>;
+  def NMSUB_D32 : FNMADDSUB<0x7, 1, "nmsub", "d", fsub, AFGR64>;
+}
+
+let Predicates =3D [HasMips32r2, IsFP64bit] in {
+  def MADD_D64 : FMADDSUB<0x4, 1, "madd", "d", fadd, FGR64>;
+  def MSUB_D64 : FMADDSUB<0x5, 1, "msub", "d", fsub, FGR64>;
+}
+
+let Predicates =3D [HasMips32r2, IsFP64bit, NoNaNsFPMath] in {
+  def NMADD_D64 : FNMADDSUB<0x6, 1, "nmadd", "d", fadd, FGR64>;
+  def NMSUB_D64 : FNMADDSUB<0x7, 1, "nmsub", "d", fsub, FGR64>;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Floating Point Branch Codes
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -259,71 +367,16 @@
 def MIPS_FCOND_LE   : PatLeaf<(i32 14)>;
 def MIPS_FCOND_NGT  : PatLeaf<(i32 15)>;
=20
+class FCMP<bits<5> fmt, RegisterClass RC, string typestr> :
+  FCC<fmt, (outs), (ins RC:$fs, RC:$ft, condcode:$cc),
+      !strconcat("c.$cc.", typestr, "\t$fs, $ft"),
+      [(MipsFPCmp RC:$fs, RC:$ft, imm:$cc)]>;
+
 /// Floating Point Compare
 let Defs=3D[FCR31] in {
-  def FCMP_S32 : FCC<0x10, (outs), (ins FGR32:$fs, FGR32:$ft, condcode:$cc=
),
-                     "c.$cc.s\t$fs, $ft",
-                     [(MipsFPCmp FGR32:$fs, FGR32:$ft, imm:$cc)]>;
-
-  def FCMP_D32 : FCC<0x11, (outs), (ins AFGR64:$fs, AFGR64:$ft, condcode:$=
cc),
-                     "c.$cc.d\t$fs, $ft",
-                     [(MipsFPCmp AFGR64:$fs, AFGR64:$ft, imm:$cc)]>,
-                     Requires<[NotFP64bit]>;
-}
-
-
-// Conditional moves:
-// These instructions are expanded in
-// MipsISelLowering::EmitInstrWithCustomInserter if target does not have
-// conditional move instructions.
-// flag:int, data:float
-let usesCustomInserter =3D 1, Constraints =3D "$F =3D $dst" in
-class CondMovIntFP<RegisterClass RC, bits<5> fmt, bits<6> func,
-                   string instr_asm> :
-  FFR<0x11, func, fmt, (outs RC:$dst), (ins RC:$T, CPURegs:$cond, RC:$F),
-      !strconcat(instr_asm, "\t$dst, $T, $cond"), []>;
-
-def MOVZ_S : CondMovIntFP<FGR32, 16, 18, "movz.s">;
-def MOVN_S : CondMovIntFP<FGR32, 16, 19, "movn.s">;
-
-let Predicates =3D [NotFP64bit] in {
-  def MOVZ_D : CondMovIntFP<AFGR64, 17, 18, "movz.d">;
-  def MOVN_D : CondMovIntFP<AFGR64, 17, 19, "movn.d">;
-}
-
-defm : MovzPats<FGR32, MOVZ_S>;
-defm : MovnPats<FGR32, MOVN_S>;
-
-let Predicates =3D [NotFP64bit] in {
-  defm : MovzPats<AFGR64, MOVZ_D>;
-  defm : MovnPats<AFGR64, MOVN_D>;
-}
-
-let cc =3D 0, usesCustomInserter =3D 1, Uses =3D [FCR31],
-    Constraints =3D "$F =3D $dst" in {
-// flag:float, data:int
-class CondMovFPInt<SDNode cmov, bits<1> tf, string instr_asm> :
-  FCMOV<tf, (outs CPURegs:$dst), (ins CPURegs:$T, CPURegs:$F),
-        !strconcat(instr_asm, "\t$dst, $T, $$fcc0"),
-        [(set CPURegs:$dst, (cmov CPURegs:$T, CPURegs:$F))]>;
-
-// flag:float, data:float
-let cc =3D 0 in
-class CondMovFPFP<RegisterClass RC, SDNode cmov, bits<5> fmt, bits<1> tf,
-                  string instr_asm> :
-  FFCMOV<fmt, tf, (outs RC:$dst), (ins RC:$T, RC:$F),
-         !strconcat(instr_asm, "\t$dst, $T, $$fcc0"),
-         [(set RC:$dst, (cmov RC:$T, RC:$F))]>;
-}
-
-def MOVT : CondMovFPInt<MipsCMovFP_T, 1, "movt">;
-def MOVF : CondMovFPInt<MipsCMovFP_F, 0, "movf">;
-def MOVT_S : CondMovFPFP<FGR32, MipsCMovFP_T, 16, 1, "movt.s">;
-def MOVF_S : CondMovFPFP<FGR32, MipsCMovFP_F, 16, 0, "movf.s">;
-
-let Predicates =3D [NotFP64bit] in {
-  def MOVT_D : CondMovFPFP<AFGR64, MipsCMovFP_T, 17, 1, "movt.d">;
-  def MOVF_D : CondMovFPFP<AFGR64, MipsCMovFP_F, 17, 0, "movf.d">;
+  def FCMP_S32 : FCMP<0x10, FGR32, "s">;
+  def FCMP_D32 : FCMP<0x11, AFGR64, "d">, Requires<[NotFP64bit]>;
+  def FCMP_D64 : FCMP<0x11, FGR64, "d">, Requires<[IsFP64bit]>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -352,25 +405,46 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Floating Point Patterns
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-def fpimm0 : PatLeaf<(fpimm), [{
-  return N->isExactlyValue(+0.0);
-}]>;
-
-def fpimm0neg : PatLeaf<(fpimm), [{
-  return N->isExactlyValue(-0.0);
-}]>;
-
 def : Pat<(f32 fpimm0), (MTC1 ZERO)>;
 def : Pat<(f32 fpimm0neg), (FNEG_S (MTC1 ZERO))>;
=20
 def : Pat<(f32 (sint_to_fp CPURegs:$src)), (CVT_S_W (MTC1 CPURegs:$src))>;
-def : Pat<(f64 (sint_to_fp CPURegs:$src)), (CVT_D32_W (MTC1 CPURegs:$src))=
>;
-
 def : Pat<(i32 (fp_to_sint FGR32:$src)), (MFC1 (TRUNC_W_S FGR32:$src))>;
-def : Pat<(i32 (fp_to_sint AFGR64:$src)), (MFC1 (TRUNC_W_D32 AFGR64:$src))=
>;
=20
 let Predicates =3D [NotFP64bit] in {
+  def : Pat<(f64 (sint_to_fp CPURegs:$src)), (CVT_D32_W (MTC1 CPURegs:$src=
))>;
+  def : Pat<(i32 (fp_to_sint AFGR64:$src)), (MFC1 (TRUNC_W_D32 AFGR64:$src=
))>;
   def : Pat<(f32 (fround AFGR64:$src)), (CVT_S_D32 AFGR64:$src)>;
   def : Pat<(f64 (fextend FGR32:$src)), (CVT_D32_S FGR32:$src)>;
 }
=20
+let Predicates =3D [IsFP64bit] in {
+  def : Pat<(f64 fpimm0), (DMTC1 ZERO_64)>;
+  def : Pat<(f64 fpimm0neg), (FNEG_D64 (DMTC1 ZERO_64))>;
+
+  def : Pat<(f64 (sint_to_fp CPURegs:$src)), (CVT_D64_W (MTC1 CPURegs:$src=
))>;
+  def : Pat<(f32 (sint_to_fp CPU64Regs:$src)),
+            (CVT_S_L (DMTC1 CPU64Regs:$src))>;
+  def : Pat<(f64 (sint_to_fp CPU64Regs:$src)),
+            (CVT_D64_L (DMTC1 CPU64Regs:$src))>;
+
+  def : Pat<(i32 (fp_to_sint FGR64:$src)), (MFC1 (TRUNC_W_D64 FGR64:$src))=
>;
+  def : Pat<(i64 (fp_to_sint FGR32:$src)), (DMFC1 (TRUNC_L_S FGR32:$src))>;
+  def : Pat<(i64 (fp_to_sint FGR64:$src)), (DMFC1 (TRUNC_L_D64 FGR64:$src)=
)>;
+
+  def : Pat<(f32 (fround FGR64:$src)), (CVT_S_D64 FGR64:$src)>;
+  def : Pat<(f64 (fextend FGR32:$src)), (CVT_D64_S FGR32:$src)>;
+}
+
+// Patterns for unaligned floating point loads and stores.
+let Predicates =3D [HasMips32r2Or64, NotN64] in {
+  def : Pat<(f32 (load_u CPURegs:$addr)), (LUXC1 CPURegs:$addr, ZERO)>;=20
+  def : Pat<(store_u FGR32:$src, CPURegs:$addr),
+            (SUXC1 FGR32:$src, CPURegs:$addr, ZERO)>;
+}
+
+let Predicates =3D [IsN64] in {
+  def : Pat<(f32 (load_u CPU64Regs:$addr)), (LUXC1_P8 CPU64Regs:$addr, ZER=
O_64)>;=20
+  def : Pat<(store_u FGR32:$src, CPU64Regs:$addr),
+            (SUXC1_P8 FGR32:$src, CPU64Regs:$addr, ZERO_64)>;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
InstrFormats.td
--- a/head/contrib/llvm/lib/Target/Mips/MipsInstrFormats.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsInstrFormats.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsInstrFormats.td - Mips Instruction Formats ------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsInstrFormats.td - Mips Instruction Formats -----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -115,7 +115,7 @@
   let Inst{15-0}  =3D imm16;
 }
=20
-class CBranchBase<bits<6> op, dag outs, dag ins, string asmstr,
+class BranchBase<bits<6> op, dag outs, dag ins, string asmstr,
                   list<dag> pattern, InstrItinClass itin>:
   MipsInst<outs, ins, asmstr, pattern, itin, FrmI>
 {
@@ -290,3 +290,40 @@
   FFR<0x11, funct, fmt, (outs RC:$fd), (ins RC:$fs, RC:$ft),
       !strconcat(opstr, ".", fmtstr, "\t$fd, $fs, $ft"),
       [(set RC:$fd, (OpNode RC:$fs, RC:$ft))]>;
+
+// Floating point madd/msub/nmadd/nmsub.
+class FFMADDSUB<bits<3> funct, bits<3> fmt, dag outs, dag ins, string asms=
tr,
+                list<dag> pattern>
+  : MipsInst<outs, ins, asmstr, pattern, NoItinerary, FrmOther> {
+  bits<5> fd;
+  bits<5> fr;
+  bits<5> fs;
+  bits<5> ft;
+
+  let Opcode =3D 0x13;
+  let Inst{25-21} =3D fr;
+  let Inst{20-16} =3D ft;
+  let Inst{15-11} =3D fs;
+  let Inst{10-6} =3D fd;
+  let Inst{5-3} =3D funct;
+  let Inst{2-0} =3D fmt;
+}
+
+// FP indexed load/store instructions.
+class FFMemIdx<bits<6> funct, dag outs, dag ins, string asmstr,
+               list<dag> pattern> :
+  MipsInst<outs, ins, asmstr, pattern, NoItinerary, FrmOther>
+{
+  bits<5>  base;
+  bits<5>  index;
+  bits<5>  fs;
+  bits<5>  fd;
+
+  let Opcode =3D 0x13;
+
+  let Inst{25-21} =3D base;
+  let Inst{20-16} =3D index;
+  let Inst{15-11} =3D fs;
+  let Inst{10-6} =3D fd;
+  let Inst{5-0} =3D funct;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
InstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsInstrInfo.cpp - Mips Instruction Information ---------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsInstrInfo.cpp - Mips Instruction Information -----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -29,10 +29,10 @@
 MipsInstrInfo::MipsInstrInfo(MipsTargetMachine &tm)
   : MipsGenInstrInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),
     TM(tm), IsN64(TM.getSubtarget<MipsSubtarget>().isABI_N64()),
-    RI(*TM.getSubtargetImpl(), *this) {}
+    RI(*TM.getSubtargetImpl(), *this),
+    UncondBrOpc(TM.getRelocationModel() =3D=3D Reloc::PIC_ ? Mips::B : Mip=
s::J) {}
=20
-
-const MipsRegisterInfo &MipsInstrInfo::getRegisterInfo() const {=20
+const MipsRegisterInfo &MipsInstrInfo::getRegisterInfo() const {
   return RI;
 }
=20
@@ -131,6 +131,8 @@
     Opc =3D Mips::FMOV_S;
   else if (Mips::AFGR64RegClass.contains(DestReg, SrcReg))
     Opc =3D Mips::FMOV_D32;
+  else if (Mips::FGR64RegClass.contains(DestReg, SrcReg))
+    Opc =3D Mips::FMOV_D64;
   else if (Mips::CCRRegClass.contains(DestReg, SrcReg))
     Opc =3D Mips::MOVCCRToCCR;
   else if (Mips::CPU64RegsRegClass.contains(DestReg)) { // Copy to CPU64 R=
eg.
@@ -140,18 +142,22 @@
       Opc =3D Mips::MFHI64, SrcReg =3D 0;
     else if (SrcReg =3D=3D Mips::LO64)
       Opc =3D Mips::MFLO64, SrcReg =3D 0;
+    else if (Mips::FGR64RegClass.contains(SrcReg))
+      Opc =3D Mips::DMFC1;
   }
   else if (Mips::CPU64RegsRegClass.contains(SrcReg)) { // Copy from CPU64 =
Reg.
     if (DestReg =3D=3D Mips::HI64)
       Opc =3D Mips::MTHI64, DestReg =3D 0;
     else if (DestReg =3D=3D Mips::LO64)
       Opc =3D Mips::MTLO64, DestReg =3D 0;
+    else if (Mips::FGR64RegClass.contains(DestReg))
+      Opc =3D Mips::DMTC1;
   }
=20
   assert(Opc && "Cannot copy registers");
=20
   MachineInstrBuilder MIB =3D BuildMI(MBB, I, DL, get(Opc));
- =20
+
   if (DestReg)
     MIB.addReg(DestReg, RegState::Define);
=20
@@ -162,6 +168,16 @@
     MIB.addReg(SrcReg, getKillRegState(KillSrc));
 }
=20
+static MachineMemOperand* GetMemOperand(MachineBasicBlock &MBB, int FI,
+                                        unsigned Flag) {
+  MachineFunction &MF =3D *MBB.getParent();
+  MachineFrameInfo &MFI =3D *MF.getFrameInfo();
+  unsigned Align =3D MFI.getObjectAlignment(FI);
+
+  return MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI), Fl=
ag,
+                                 MFI.getObjectSize(FI), Align);
+}
+
 void MipsInstrInfo::
 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
                     unsigned SrcReg, bool isKill, int FI,
@@ -169,6 +185,8 @@
                     const TargetRegisterInfo *TRI) const {
   DebugLoc DL;
   if (I !=3D MBB.end()) DL =3D I->getDebugLoc();
+  MachineMemOperand *MMO =3D GetMemOperand(MBB, FI, MachineMemOperand::MOS=
tore);
+
   unsigned Opc =3D 0;
=20
   if (RC =3D=3D Mips::CPURegsRegisterClass)
@@ -184,7 +202,7 @@
=20
   assert(Opc && "Register class not handled!");
   BuildMI(MBB, I, DL, get(Opc)).addReg(SrcReg, getKillRegState(isKill))
-    .addFrameIndex(FI).addImm(0);
+    .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
 }
=20
 void MipsInstrInfo::
@@ -195,6 +213,7 @@
 {
   DebugLoc DL;
   if (I !=3D MBB.end()) DL =3D I->getDebugLoc();
+  MachineMemOperand *MMO =3D GetMemOperand(MBB, FI, MachineMemOperand::MOL=
oad);
   unsigned Opc =3D 0;
=20
   if (RC =3D=3D Mips::CPURegsRegisterClass)
@@ -209,7 +228,8 @@
     Opc =3D IsN64 ? Mips::LDC164_P8 : Mips::LDC164;
=20
   assert(Opc && "Register class not handled!");
-  BuildMI(MBB, I, DL, get(Opc), DestReg).addFrameIndex(FI).addImm(0);
+  BuildMI(MBB, I, DL, get(Opc), DestReg).addFrameIndex(FI).addImm(0)
+    .addMemOperand(MMO);
 }
=20
 MachineInstr*
@@ -230,7 +250,8 @@
           Opc =3D=3D Mips::BGEZ   || Opc =3D=3D Mips::BLTZ   || Opc =3D=3D=
 Mips::BLEZ   ||
           Opc =3D=3D Mips::BEQ64  || Opc =3D=3D Mips::BNE64  || Opc =3D=3D=
 Mips::BGTZ64 ||
           Opc =3D=3D Mips::BGEZ64 || Opc =3D=3D Mips::BLTZ64 || Opc =3D=3D=
 Mips::BLEZ64 ||
-          Opc =3D=3D Mips::BC1T   || Opc =3D=3D Mips::BC1F   || Opc =3D=3D=
 Mips::J) ?
+          Opc =3D=3D Mips::BC1T   || Opc =3D=3D Mips::BC1F   || Opc =3D=3D=
 Mips::B      ||
+          Opc =3D=3D Mips::J) ?
          Opc : 0;
 }
=20
@@ -239,21 +260,21 @@
 unsigned Mips::GetOppositeBranchOpc(unsigned Opc)
 {
   switch (Opc) {
-  default: llvm_unreachable("Illegal opcode!");
-  case Mips::BEQ    : return Mips::BNE;
-  case Mips::BNE    : return Mips::BEQ;
-  case Mips::BGTZ   : return Mips::BLEZ;
-  case Mips::BGEZ   : return Mips::BLTZ;
-  case Mips::BLTZ   : return Mips::BGEZ;
-  case Mips::BLEZ   : return Mips::BGTZ;
-  case Mips::BEQ64  : return Mips::BNE64;
-  case Mips::BNE64  : return Mips::BEQ64;
-  case Mips::BGTZ64 : return Mips::BLEZ64;
-  case Mips::BGEZ64 : return Mips::BLTZ64;
-  case Mips::BLTZ64 : return Mips::BGEZ64;
-  case Mips::BLEZ64 : return Mips::BGTZ64;
-  case Mips::BC1T   : return Mips::BC1F;
-  case Mips::BC1F   : return Mips::BC1T;
+  default:           llvm_unreachable("Illegal opcode!");
+  case Mips::BEQ:    return Mips::BNE;
+  case Mips::BNE:    return Mips::BEQ;
+  case Mips::BGTZ:   return Mips::BLEZ;
+  case Mips::BGEZ:   return Mips::BLTZ;
+  case Mips::BLTZ:   return Mips::BGEZ;
+  case Mips::BLEZ:   return Mips::BGTZ;
+  case Mips::BEQ64:  return Mips::BNE64;
+  case Mips::BNE64:  return Mips::BEQ64;
+  case Mips::BGTZ64: return Mips::BLEZ64;
+  case Mips::BGEZ64: return Mips::BLTZ64;
+  case Mips::BLTZ64: return Mips::BGEZ64;
+  case Mips::BLEZ64: return Mips::BGTZ64;
+  case Mips::BC1T:   return Mips::BC1F;
+  case Mips::BC1F:   return Mips::BC1T;
   }
 }
=20
@@ -262,7 +283,7 @@
                           SmallVectorImpl<MachineOperand>& Cond) {
   assert(GetAnalyzableBrOpc(Opc) && "Not an analyzable branch");
   int NumOp =3D Inst->getNumExplicitOperands();
- =20
+
   // for both int and fp branches, the last explicit operand is the
   // MBB.
   BB =3D Inst->getOperand(NumOp-1).getMBB();
@@ -314,7 +335,7 @@
   // If there is only one terminator instruction, process it.
   if (!SecondLastOpc) {
     // Unconditional branch
-    if (LastOpc =3D=3D Mips::J) {
+    if (LastOpc =3D=3D UncondBrOpc) {
       TBB =3D LastInst->getOperand(0).getMBB();
       return false;
     }
@@ -331,7 +352,7 @@
=20
   // If second to last instruction is an unconditional branch,
   // analyze it and remove the last instruction.
-  if (SecondLastOpc =3D=3D Mips::J) {
+  if (SecondLastOpc =3D=3D UncondBrOpc) {
     // Return if the last instruction cannot be removed.
     if (!AllowModify)
       return true;
@@ -343,15 +364,15 @@
=20
   // Conditional branch followed by an unconditional branch.
   // The last one must be unconditional.
-  if (LastOpc !=3D Mips::J)
+  if (LastOpc !=3D UncondBrOpc)
     return true;
=20
   AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);
   FBB =3D LastInst->getOperand(0).getMBB();
=20
   return false;
-}=20
- =20
+}
+
 void MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB,
                                 MachineBasicBlock *TBB, DebugLoc DL,
                                 const SmallVectorImpl<MachineOperand>& Con=
d)
@@ -385,14 +406,14 @@
   // Two-way Conditional branch.
   if (FBB) {
     BuildCondBr(MBB, TBB, DL, Cond);
-    BuildMI(&MBB, DL, get(Mips::J)).addMBB(FBB);
+    BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(FBB);
     return 2;
   }
=20
   // One way branch.
   // Unconditional branch.
   if (Cond.empty())
-    BuildMI(&MBB, DL, get(Mips::J)).addMBB(TBB);
+    BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(TBB);
   else // Conditional branch.
     BuildCondBr(MBB, TBB, DL, Cond);
   return 1;
@@ -433,27 +454,3 @@
   return false;
 }
=20
-/// getGlobalBaseReg - Return a virtual register initialized with the
-/// the global base register value. Output instructions required to
-/// initialize the register in the function entry block, if necessary.
-///
-unsigned MipsInstrInfo::getGlobalBaseReg(MachineFunction *MF) const {
-  MipsFunctionInfo *MipsFI =3D MF->getInfo<MipsFunctionInfo>();
-  unsigned GlobalBaseReg =3D MipsFI->getGlobalBaseReg();
-  if (GlobalBaseReg !=3D 0)
-    return GlobalBaseReg;
-
-  // Insert the set of GlobalBaseReg into the first MBB of the function
-  MachineBasicBlock &FirstMBB =3D MF->front();
-  MachineBasicBlock::iterator MBBI =3D FirstMBB.begin();
-  MachineRegisterInfo &RegInfo =3D MF->getRegInfo();
-  const TargetInstrInfo *TII =3D MF->getTarget().getInstrInfo();
-
-  GlobalBaseReg =3D RegInfo.createVirtualRegister(Mips::CPURegsRegisterCla=
ss);
-  BuildMI(FirstMBB, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY),
-          GlobalBaseReg).addReg(Mips::GP);
-  RegInfo.addLiveIn(Mips::GP);
-
-  MipsFI->setGlobalBaseReg(GlobalBaseReg);
-  return GlobalBaseReg;
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
InstrInfo.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsInstrInfo.h - Mips Instruction Information -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsInstrInfo.h - Mips Instruction Information ----------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,9 +15,9 @@
 #define MIPSINSTRUCTIONINFO_H
=20
 #include "Mips.h"
+#include "MipsRegisterInfo.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "MipsRegisterInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "MipsGenInstrInfo.inc"
@@ -30,90 +30,11 @@
   unsigned GetOppositeBranchOpc(unsigned Opc);
 }
=20
-/// MipsII - This namespace holds all of the target specific flags that
-/// instruction info tracks.
-///
-namespace MipsII {
-  /// Target Operand Flag enum.
-  enum TOF {
-    //=3D=3D=3D-----------------------------------------------------------=
-------=3D=3D=3D//
-    // Mips Specific MachineOperand flags.
-
-    MO_NO_FLAG,
-
-    /// MO_GOT - Represents the offset into the global offset table at whi=
ch
-    /// the address the relocation entry symbol resides during execution.
-    MO_GOT,
-
-    /// MO_GOT_CALL - Represents the offset into the global offset table at
-    /// which the address of a call site relocation entry symbol resides
-    /// during execution. This is different from the above since this flag
-    /// can only be present in call instructions.
-    MO_GOT_CALL,
-
-    /// MO_GPREL - Represents the offset from the current gp value to be u=
sed
-    /// for the relocatable object file being produced.
-    MO_GPREL,
-
-    /// MO_ABS_HI/LO - Represents the hi or low part of an absolute symbol
-    /// address.
-    MO_ABS_HI,
-    MO_ABS_LO,
-
-    /// MO_TLSGD - Represents the offset into the global offset table at w=
hich
-    // the module ID and TSL block offset reside during execution (General
-    // Dynamic TLS).
-    MO_TLSGD,
-
-    /// MO_GOTTPREL - Represents the offset from the thread pointer (Initi=
al
-    // Exec TLS).
-    MO_GOTTPREL,
-
-    /// MO_TPREL_HI/LO - Represents the hi and low part of the offset from
-    // the thread pointer (Local Exec TLS).
-    MO_TPREL_HI,
-    MO_TPREL_LO,
-
-    // N32/64 Flags.
-    MO_GPOFF_HI,
-    MO_GPOFF_LO,
-    MO_GOT_DISP,
-    MO_GOT_PAGE,
-    MO_GOT_OFST
-  };
-
-  enum {
-    //=3D=3D=3D-----------------------------------------------------------=
-------=3D=3D=3D//
-    // Instruction encodings.  These are the standard/most common forms for
-    // Mips instructions.
-    //
-
-    // Pseudo - This represents an instruction that is a pseudo instruction
-    // or one that has not been implemented yet.  It is illegal to code ge=
nerate
-    // it, but tolerated for intermediate implementation stages.
-    Pseudo   =3D 0,
-
-    /// FrmR - This form is for instructions of the format R.
-    FrmR  =3D 1,
-    /// FrmI - This form is for instructions of the format I.
-    FrmI  =3D 2,
-    /// FrmJ - This form is for instructions of the format J.
-    FrmJ  =3D 3,
-    /// FrmFR - This form is for instructions of the format FR.
-    FrmFR =3D 4,
-    /// FrmFI - This form is for instructions of the format FI.
-    FrmFI =3D 5,
-    /// FrmOther - This form is for instructions that have no specific for=
mat.
-    FrmOther =3D 6,
-
-    FormMask =3D 15
-  };
-}
-
 class MipsInstrInfo : public MipsGenInstrInfo {
   MipsTargetMachine &TM;
   bool IsN64;
   const MipsRegisterInfo RI;
+  unsigned UncondBrOpc;
 public:
   explicit MipsInstrInfo(MipsTargetMachine &TM);
=20
@@ -182,12 +103,6 @@
   /// Insert nop instruction when hazard condition is found
   virtual void insertNoop(MachineBasicBlock &MBB,
                           MachineBasicBlock::iterator MI) const;
-
-  /// getGlobalBaseReg - Return a virtual register initialized with the
-  /// the global base register value. Output instructions required to
-  /// initialize the register in the function entry block, if necessary.
-  ///
-  unsigned getGlobalBaseReg(MachineFunction *MF) const;
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
InstrInfo.td
--- a/head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.td	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsInstrInfo.td	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -39,8 +39,8 @@
=20
 def SDT_MipsThreadPointer : SDTypeProfile<1, 0, [SDTCisPtrTy<0>]>;
=20
-def SDT_MipsDynAlloc    : SDTypeProfile<1, 1, [SDTCisVT<0, i32>,
-                                               SDTCisVT<1, iPTR>]>;
+def SDT_MipsDynAlloc    : SDTypeProfile<1, 1, [SDTCisVT<0, iPTR>,
+                                               SDTCisSameAs<0, 1>]>;
 def SDT_Sync             : SDTypeProfile<0, 1, [SDTCisVT<0, i32>]>;
=20
 def SDT_Ext : SDTypeProfile<1, 3, [SDTCisInt<0>, SDTCisSameAs<0, 1>,
@@ -103,11 +103,11 @@
 // target constant nodes that would otherwise remain unchanged with ADDiu
 // nodes. Without these wrapper node patterns, the following conditional m=
ove
 // instrucion is emitted when function cmov2 in test/CodeGen/Mips/cmov.ll =
is
-// compiled:=20
+// compiled:
 //  movn  %got(d)($gp), %got(c)($gp), $4
 // This instruction is illegal since movn can take only register operands.
=20
-def MipsWrapperPIC    : SDNode<"MipsISD::WrapperPIC",  SDTIntUnaryOp>;
+def MipsWrapper    : SDNode<"MipsISD::Wrapper", SDTIntBinOp>;
=20
 // Pointer to dynamically allocated stack area.
 def MipsDynAlloc  : SDNode<"MipsISD::DynAlloc", SDT_MipsDynAlloc,
@@ -128,18 +128,31 @@
 def HasMips32    : Predicate<"Subtarget.hasMips32()">;
 def HasMips32r2  : Predicate<"Subtarget.hasMips32r2()">;
 def HasMips64    : Predicate<"Subtarget.hasMips64()">;
+def HasMips32r2Or64 : Predicate<"Subtarget.hasMips32r2Or64()">;
 def NotMips64    : Predicate<"!Subtarget.hasMips64()">;
 def HasMips64r2  : Predicate<"Subtarget.hasMips64r2()">;
 def IsN64       : Predicate<"Subtarget.isABI_N64()">;
 def NotN64      : Predicate<"!Subtarget.isABI_N64()">;
+def RelocStatic : Predicate<"TM.getRelocationModel() =3D=3D Reloc::Static"=
>;
+def RelocPIC    : Predicate<"TM.getRelocationModel() =3D=3D Reloc::PIC_">;
+def NoNaNsFPMath : Predicate<"TM.Options.NoNaNsFPMath">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Mips Operand, Complex Patterns and Transformations Definitions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 // Instruction operand types
-def brtarget    : Operand<OtherVT>;
-def calltarget  : Operand<i32>;
+def jmptarget   : Operand<OtherVT> {
+  let EncoderMethod =3D "getJumpTargetOpValue";
+}
+def brtarget    : Operand<OtherVT> {
+  let EncoderMethod =3D "getBranchTargetOpValue";
+  let OperandType =3D "OPERAND_PCREL";
+}
+def calltarget  : Operand<iPTR> {
+  let EncoderMethod =3D "getJumpTargetOpValue";
+}
+def calltarget64: Operand<i64>;
 def simm16      : Operand<i32>;
 def simm16_64   : Operand<i64>;
 def shamt       : Operand<i32>;
@@ -167,6 +180,12 @@
   let EncoderMethod =3D "getMemEncoding";
 }
=20
+def mem_ea_64 : Operand<i64> {
+  let PrintMethod =3D "printMemOperandEA";
+  let MIOperandInfo =3D (ops CPU64Regs, simm16_64);
+  let EncoderMethod =3D "getMemEncoding";
+}
+
 // size operand of ext instruction
 def size_ext : Operand<i32> {
   let EncoderMethod =3D "getSizeExtEncoding";
@@ -179,12 +198,12 @@
=20
 // Transformation Function - get the lower 16 bits.
 def LO16 : SDNodeXForm<imm, [{
-  return getI32Imm((unsigned)N->getZExtValue() & 0xFFFF);
+  return getImm(N, N->getZExtValue() & 0xFFFF);
 }]>;
=20
 // Transformation Function - get the higher 16 bits.
 def HI16 : SDNodeXForm<imm, [{
-  return getI32Imm((unsigned)N->getZExtValue() >> 16);
+  return getImm(N, (N->getZExtValue() >> 16) & 0xFFFF);
 }]>;
=20
 // Node immediate fits as 16-bit sign extended on target immediate.
@@ -202,36 +221,42 @@
     return (uint64_t)N->getZExtValue() =3D=3D (unsigned short)N->getZExtVa=
lue();
 }], LO16>;
=20
+// Immediate can be loaded with LUi (32-bit int with lower 16-bit cleared).
+def immLow16Zero : PatLeaf<(imm), [{
+  int64_t Val =3D N->getSExtValue();
+  return isInt<32>(Val) && !(Val & 0xffff);
+}]>;
+
 // shamt field must fit in 5 bits.
-def immZExt5 : PatLeaf<(imm), [{
-  return N->getZExtValue() =3D=3D ((N->getZExtValue()) & 0x1f) ;
-}]>;
+def immZExt5 : ImmLeaf<i32, [{return Imm =3D=3D (Imm & 0x1f);}]>;
=20
 // Mips Address Mode! SDNode frameindex could possibily be a match
 // since load and store instructions from stack used it.
-def addr : ComplexPattern<iPTR, 2, "SelectAddr", [frameindex], []>;
+def addr : ComplexPattern<iPTR, 2, "SelectAddr", [frameindex], [SDNPWantPa=
rent]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Pattern fragment for load/store
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-class UnalignedLoad<PatFrag Node> : PatFrag<(ops node:$ptr), (Node node:$p=
tr), [{
+class UnalignedLoad<PatFrag Node> :
+  PatFrag<(ops node:$ptr), (Node node:$ptr), [{
   LoadSDNode *LD =3D cast<LoadSDNode>(N);
   return LD->getMemoryVT().getSizeInBits()/8 > LD->getAlignment();
 }]>;
=20
-class AlignedLoad<PatFrag Node> : PatFrag<(ops node:$ptr), (Node node:$ptr=
), [{
+class AlignedLoad<PatFrag Node> :
+  PatFrag<(ops node:$ptr), (Node node:$ptr), [{
   LoadSDNode *LD =3D cast<LoadSDNode>(N);
   return LD->getMemoryVT().getSizeInBits()/8 <=3D LD->getAlignment();
 }]>;
=20
-class UnalignedStore<PatFrag Node> : PatFrag<(ops node:$val, node:$ptr),
-                                             (Node node:$val, node:$ptr), =
[{
+class UnalignedStore<PatFrag Node> :
+  PatFrag<(ops node:$val, node:$ptr), (Node node:$val, node:$ptr), [{
   StoreSDNode *SD =3D cast<StoreSDNode>(N);
   return SD->getMemoryVT().getSizeInBits()/8 > SD->getAlignment();
 }]>;
=20
-class AlignedStore<PatFrag Node> : PatFrag<(ops node:$val, node:$ptr),
-                                           (Node node:$val, node:$ptr), [{
+class AlignedStore<PatFrag Node> :
+  PatFrag<(ops node:$val, node:$ptr), (Node node:$val, node:$ptr), [{
   StoreSDNode *SD =3D cast<StoreSDNode>(N);
   return SD->getMemoryVT().getSizeInBits()/8 <=3D SD->getAlignment();
 }]>;
@@ -313,27 +338,34 @@
 }
=20
 // Shifts
-class LogicR_shift_rotate_imm<bits<6> func, bits<5> _rs, string instr_asm,
-                              SDNode OpNode>:
-  FR<0x00, func, (outs CPURegs:$rd), (ins CPURegs:$rt, shamt:$shamt),
+class shift_rotate_imm<bits<6> func, bits<5> isRotate, string instr_asm,
+                       SDNode OpNode, PatFrag PF, Operand ImmOpnd,
+                       RegisterClass RC>:
+  FR<0x00, func, (outs RC:$rd), (ins RC:$rt, ImmOpnd:$shamt),
      !strconcat(instr_asm, "\t$rd, $rt, $shamt"),
-     [(set CPURegs:$rd, (OpNode CPURegs:$rt, (i32 immZExt5:$shamt)))], IIA=
lu> {
-  let rs =3D _rs;
+     [(set RC:$rd, (OpNode RC:$rt, PF:$shamt))], IIAlu> {
+  let rs =3D isRotate;
 }
=20
-class LogicR_shift_rotate_reg<bits<6> func, bits<5> isRotate, string instr=
_asm,
-                              SDNode OpNode>:
-  FR<0x00, func, (outs CPURegs:$rd), (ins CPURegs:$rs, CPURegs:$rt),
+// 32-bit shift instructions.
+class shift_rotate_imm32<bits<6> func, bits<5> isRotate, string instr_asm,
+                         SDNode OpNode>:
+  shift_rotate_imm<func, isRotate, instr_asm, OpNode, immZExt5, shamt, CPU=
Regs>;
+
+class shift_rotate_reg<bits<6> func, bits<5> isRotate, string instr_asm,
+                       SDNode OpNode, RegisterClass RC>:
+  FR<0x00, func, (outs RC:$rd), (ins CPURegs:$rs, RC:$rt),
      !strconcat(instr_asm, "\t$rd, $rt, $rs"),
-     [(set CPURegs:$rd, (OpNode CPURegs:$rt, CPURegs:$rs))], IIAlu> {
+     [(set RC:$rd, (OpNode RC:$rt, CPURegs:$rs))], IIAlu> {
   let shamt =3D isRotate;
 }
=20
 // Load Upper Imediate
-class LoadUpper<bits<6> op, string instr_asm>:
-  FI<op, (outs CPURegs:$rt), (ins uimm16:$imm16),
+class LoadUpper<bits<6> op, string instr_asm, RegisterClass RC, Operand Im=
m>:
+  FI<op, (outs RC:$rt), (ins Imm:$imm16),
      !strconcat(instr_asm, "\t$rt, $imm16"), [], IIAlu> {
   let rs =3D 0;
+  let neverHasSideEffects =3D 1;
 }
=20
 class FMem<bits<6> op, dag outs, dag ins, string asmstr, list<dag> pattern,
@@ -361,6 +393,14 @@
   let isPseudo =3D Pseudo;
 }
=20
+// Unaligned Memory Load/Store
+let canFoldAsLoad =3D 1 in
+class LoadUnAlign<bits<6> op, RegisterClass RC, Operand MemOpnd>:
+  FMem<op, (outs RC:$rt), (ins MemOpnd:$addr), "", [], IILoad> {}
+
+class StoreUnAlign<bits<6> op, RegisterClass RC, Operand MemOpnd>:
+  FMem<op, (outs), (ins RC:$rt, MemOpnd:$addr), "", [], IIStore> {}
+
 // 32-bit load.
 multiclass LoadM32<bits<6> op, string instr_asm, PatFrag OpNode,
                    bit Pseudo =3D 0> {
@@ -368,7 +408,7 @@
                Requires<[NotN64]>;
   def _P8    : LoadM<op, instr_asm, OpNode, CPURegs, mem64, Pseudo>,
                Requires<[IsN64]>;
-}=20
+}
=20
 // 64-bit load.
 multiclass LoadM64<bits<6> op, string instr_asm, PatFrag OpNode,
@@ -377,8 +417,15 @@
                Requires<[NotN64]>;
   def _P8    : LoadM<op, instr_asm, OpNode, CPU64Regs, mem64, Pseudo>,
                Requires<[IsN64]>;
-}=20
+}
=20
+// 32-bit load.
+multiclass LoadUnAlign32<bits<6> op> {
+  def #NAME# : LoadUnAlign<op, CPURegs, mem>,
+               Requires<[NotN64]>;
+  def _P8    : LoadUnAlign<op, CPURegs, mem64>,
+               Requires<[IsN64]>;
+}
 // 32-bit store.
 multiclass StoreM32<bits<6> op, string instr_asm, PatFrag OpNode,
                     bit Pseudo =3D 0> {
@@ -397,11 +444,19 @@
                Requires<[IsN64]>;
 }
=20
+// 32-bit store.
+multiclass StoreUnAlign32<bits<6> op> {
+  def #NAME# : StoreUnAlign<op, CPURegs, mem>,
+               Requires<[NotN64]>;
+  def _P8    : StoreUnAlign<op, CPURegs, mem64>,
+               Requires<[IsN64]>;
+}
+
 // Conditional Branch
 class CBranch<bits<6> op, string instr_asm, PatFrag cond_op, RegisterClass=
 RC>:
-  CBranchBase<op, (outs), (ins RC:$rs, RC:$rt, brtarget:$imm16),
-              !strconcat(instr_asm, "\t$rs, $rt, $imm16"),
-              [(brcond (i32 (cond_op RC:$rs, RC:$rt)), bb:$imm16)], IIBran=
ch> {
+  BranchBase<op, (outs), (ins RC:$rs, RC:$rt, brtarget:$imm16),
+             !strconcat(instr_asm, "\t$rs, $rt, $imm16"),
+             [(brcond (i32 (cond_op RC:$rs, RC:$rt)), bb:$imm16)], IIBranc=
h> {
   let isBranch =3D 1;
   let isTerminator =3D 1;
   let hasDelaySlot =3D 1;
@@ -409,9 +464,9 @@
=20
 class CBranchZero<bits<6> op, bits<5> _rt, string instr_asm, PatFrag cond_=
op,
                   RegisterClass RC>:
-  CBranchBase<op, (outs), (ins RC:$rs, brtarget:$imm16),
-              !strconcat(instr_asm, "\t$rs, $imm16"),
-              [(brcond (i32 (cond_op RC:$rs, 0)), bb:$imm16)], IIBranch> {
+  BranchBase<op, (outs), (ins RC:$rs, brtarget:$imm16),
+             !strconcat(instr_asm, "\t$rs, $imm16"),
+             [(brcond (i32 (cond_op RC:$rs, 0)), bb:$imm16)], IIBranch> {
   let rt =3D _rt;
   let isBranch =3D 1;
   let isTerminator =3D 1;
@@ -435,146 +490,228 @@
      [(set CPURegs:$rt, (cond_op RC:$rs, imm_type:$imm16))],
      IIAlu>;
=20
+// Jump
+class JumpFJ<bits<6> op, string instr_asm>:
+  FJ<op, (outs), (ins jmptarget:$target),
+     !strconcat(instr_asm, "\t$target"), [(br bb:$target)], IIBranch> {
+  let isBranch=3D1;
+  let isTerminator=3D1;
+  let isBarrier=3D1;
+  let hasDelaySlot =3D 1;
+  let Predicates =3D [RelocStatic];
+}
+
 // Unconditional branch
-let isBranch=3D1, isTerminator=3D1, isBarrier=3D1, hasDelaySlot =3D 1 in
-class JumpFJ<bits<6> op, string instr_asm>:
-  FJ<op, (outs), (ins brtarget:$target),
-     !strconcat(instr_asm, "\t$target"), [(br bb:$target)], IIBranch>;
+class UncondBranch<bits<6> op, string instr_asm>:
+  BranchBase<op, (outs), (ins brtarget:$imm16),
+             !strconcat(instr_asm, "\t$imm16"), [(br bb:$imm16)], IIBranch=
> {
+  let rs =3D 0;
+  let rt =3D 0;
+  let isBranch =3D 1;
+  let isTerminator =3D 1;
+  let isBarrier =3D 1;
+  let hasDelaySlot =3D 1;
+  let Predicates =3D [RelocPIC];
+}
=20
-let isBranch=3D1, isTerminator=3D1, isBarrier=3D1, rd=3D0, hasDelaySlot =
=3D 1 in
-class JumpFR<bits<6> op, bits<6> func, string instr_asm>:
-  FR<op, func, (outs), (ins CPURegs:$rs),
-     !strconcat(instr_asm, "\t$rs"), [(brind CPURegs:$rs)], IIBranch> {
+let isBranch=3D1, isTerminator=3D1, isBarrier=3D1, rd=3D0, hasDelaySlot =
=3D 1,
+    isIndirectBranch =3D 1 in
+class JumpFR<bits<6> op, bits<6> func, string instr_asm, RegisterClass RC>:
+  FR<op, func, (outs), (ins RC:$rs),
+     !strconcat(instr_asm, "\t$rs"), [(brind RC:$rs)], IIBranch> {
   let rt =3D 0;
   let rd =3D 0;
   let shamt =3D 0;
 }
=20
 // Jump and Link (Call)
-let isCall=3D1, hasDelaySlot=3D1,
-  // All calls clobber the non-callee saved registers...
-  Defs =3D [AT, V0, V1, A0, A1, A2, A3, T0, T1, T2, T3, T4, T5, T6, T7, T8=
, T9,
-          K0, K1, D0, D1, D2, D3, D4, D5, D6, D7, D8, D9], Uses =3D [GP] i=
n {
+let isCall=3D1, hasDelaySlot=3D1 in {
   class JumpLink<bits<6> op, string instr_asm>:
     FJ<op, (outs), (ins calltarget:$target, variable_ops),
        !strconcat(instr_asm, "\t$target"), [(MipsJmpLink imm:$target)],
        IIBranch>;
=20
-  class JumpLinkReg<bits<6> op, bits<6> func, string instr_asm>:
-    FR<op, func, (outs), (ins CPURegs:$rs, variable_ops),
-       !strconcat(instr_asm, "\t$rs"), [(MipsJmpLink CPURegs:$rs)], IIBran=
ch> {
+  class JumpLinkReg<bits<6> op, bits<6> func, string instr_asm,
+                    RegisterClass RC>:
+    FR<op, func, (outs), (ins RC:$rs, variable_ops),
+       !strconcat(instr_asm, "\t$rs"), [(MipsJmpLink RC:$rs)], IIBranch> {
     let rt =3D 0;
     let rd =3D 31;
     let shamt =3D 0;
   }
=20
-  class BranchLink<string instr_asm>:
-    FI<0x1, (outs), (ins CPURegs:$rs, brtarget:$imm16, variable_ops),
-       !strconcat(instr_asm, "\t$rs, $imm16"), [], IIBranch>;
+  class BranchLink<string instr_asm, bits<5> _rt, RegisterClass RC>:
+    FI<0x1, (outs), (ins RC:$rs, brtarget:$imm16, variable_ops),
+       !strconcat(instr_asm, "\t$rs, $imm16"), [], IIBranch> {
+    let rt =3D _rt;
+  }
 }
=20
 // Mul, Div
-class Mul<bits<6> func, string instr_asm, InstrItinClass itin>:
-  FR<0x00, func, (outs), (ins CPURegs:$rs, CPURegs:$rt),
+class Mult<bits<6> func, string instr_asm, InstrItinClass itin,
+           RegisterClass RC, list<Register> DefRegs>:
+  FR<0x00, func, (outs), (ins RC:$rs, RC:$rt),
      !strconcat(instr_asm, "\t$rs, $rt"), [], itin> {
   let rd =3D 0;
   let shamt =3D 0;
   let isCommutable =3D 1;
-  let Defs =3D [HI, LO];
+  let Defs =3D DefRegs;
+  let neverHasSideEffects =3D 1;
 }
=20
-class Div<SDNode op, bits<6> func, string instr_asm, InstrItinClass itin>:
-          FR<0x00, func, (outs), (ins CPURegs:$rs, CPURegs:$rt),
-          !strconcat(instr_asm, "\t$$zero, $rs, $rt"),
-          [(op CPURegs:$rs, CPURegs:$rt)], itin> {
+class Mult32<bits<6> func, string instr_asm, InstrItinClass itin>:
+  Mult<func, instr_asm, itin, CPURegs, [HI, LO]>;
+
+class Div<SDNode op, bits<6> func, string instr_asm, InstrItinClass itin,
+          RegisterClass RC, list<Register> DefRegs>:
+  FR<0x00, func, (outs), (ins RC:$rs, RC:$rt),
+     !strconcat(instr_asm, "\t$$zero, $rs, $rt"),
+     [(op RC:$rs, RC:$rt)], itin> {
   let rd =3D 0;
   let shamt =3D 0;
-  let Defs =3D [HI, LO];
+  let Defs =3D DefRegs;
 }
=20
+class Div32<SDNode op, bits<6> func, string instr_asm, InstrItinClass itin=
>:
+  Div<op, func, instr_asm, itin, CPURegs, [HI, LO]>;
+
 // Move from Hi/Lo
-class MoveFromLOHI<bits<6> func, string instr_asm>:
-  FR<0x00, func, (outs CPURegs:$rd), (ins),
+class MoveFromLOHI<bits<6> func, string instr_asm, RegisterClass RC,
+                   list<Register> UseRegs>:
+  FR<0x00, func, (outs RC:$rd), (ins),
      !strconcat(instr_asm, "\t$rd"), [], IIHiLo> {
   let rs =3D 0;
   let rt =3D 0;
   let shamt =3D 0;
+  let Uses =3D UseRegs;
+  let neverHasSideEffects =3D 1;
 }
=20
-class MoveToLOHI<bits<6> func, string instr_asm>:
-  FR<0x00, func, (outs), (ins CPURegs:$rs),
+class MoveToLOHI<bits<6> func, string instr_asm, RegisterClass RC,
+                 list<Register> DefRegs>:
+  FR<0x00, func, (outs), (ins RC:$rs),
      !strconcat(instr_asm, "\t$rs"), [], IIHiLo> {
   let rt =3D 0;
   let rd =3D 0;
   let shamt =3D 0;
+  let Defs =3D DefRegs;
+  let neverHasSideEffects =3D 1;
 }
=20
-class EffectiveAddress<string instr_asm> :
-  FMem<0x09, (outs CPURegs:$rt), (ins mem_ea:$addr),
-     instr_asm, [(set CPURegs:$rt, addr:$addr)], IIAlu>;
+class EffectiveAddress<string instr_asm, RegisterClass RC, Operand Mem> :
+  FMem<0x09, (outs RC:$rt), (ins Mem:$addr),
+     instr_asm, [(set RC:$rt, addr:$addr)], IIAlu>;
=20
 // Count Leading Ones/Zeros in Word
-class CountLeading<bits<6> func, string instr_asm, list<dag> pattern>:
-  FR<0x1c, func, (outs CPURegs:$rd), (ins CPURegs:$rs),
-     !strconcat(instr_asm, "\t$rd, $rs"), pattern, IIAlu>,
+class CountLeading0<bits<6> func, string instr_asm, RegisterClass RC>:
+  FR<0x1c, func, (outs RC:$rd), (ins RC:$rs),
+     !strconcat(instr_asm, "\t$rd, $rs"),
+     [(set RC:$rd, (ctlz RC:$rs))], IIAlu>,
+     Requires<[HasBitCount]> {
+  let shamt =3D 0;
+  let rt =3D rd;
+}
+
+class CountLeading1<bits<6> func, string instr_asm, RegisterClass RC>:
+  FR<0x1c, func, (outs RC:$rd), (ins RC:$rs),
+     !strconcat(instr_asm, "\t$rd, $rs"),
+     [(set RC:$rd, (ctlz (not RC:$rs)))], IIAlu>,
      Requires<[HasBitCount]> {
   let shamt =3D 0;
   let rt =3D rd;
 }
=20
 // Sign Extend in Register.
-class SignExtInReg<bits<5> sa, string instr_asm, ValueType vt>:
-  FR<0x1f, 0x20, (outs CPURegs:$rd), (ins CPURegs:$rt),
+class SignExtInReg<bits<5> sa, string instr_asm, ValueType vt,
+                   RegisterClass RC>:
+  FR<0x1f, 0x20, (outs RC:$rd), (ins RC:$rt),
      !strconcat(instr_asm, "\t$rd, $rt"),
-     [(set CPURegs:$rd, (sext_inreg CPURegs:$rt, vt))], NoItinerary> {
+     [(set RC:$rd, (sext_inreg RC:$rt, vt))], NoItinerary> {
   let rs =3D 0;
   let shamt =3D sa;
   let Predicates =3D [HasSEInReg];
 }
=20
-// Byte Swap
-class ByteSwap<bits<6> func, bits<5> sa, string instr_asm>:
-  FR<0x1f, func, (outs CPURegs:$rd), (ins CPURegs:$rt),
-     !strconcat(instr_asm, "\t$rd, $rt"),
-     [(set CPURegs:$rd, (bswap CPURegs:$rt))], NoItinerary> {
+// Subword Swap
+class SubwordSwap<bits<6> func, bits<5> sa, string instr_asm, RegisterClas=
s RC>:
+  FR<0x1f, func, (outs RC:$rd), (ins RC:$rt),
+     !strconcat(instr_asm, "\t$rd, $rt"), [], NoItinerary> {
   let rs =3D 0;
   let shamt =3D sa;
   let Predicates =3D [HasSwap];
+  let neverHasSideEffects =3D 1;
 }
=20
 // Read Hardware
-class ReadHardware: FR<0x1f, 0x3b, (outs CPURegs:$rt), (ins HWRegs:$rd),
-    "rdhwr\t$rt, $rd", [], IIAlu> {
+class ReadHardware<RegisterClass CPURegClass, RegisterClass HWRegClass>
+  : FR<0x1f, 0x3b, (outs CPURegClass:$rt), (ins HWRegClass:$rd),
+       "rdhwr\t$rt, $rd", [], IIAlu> {
   let rs =3D 0;
   let shamt =3D 0;
 }
=20
 // Ext and Ins
-class ExtIns<bits<6> _funct, string instr_asm, dag outs, dag ins,
-             list<dag> pattern, InstrItinClass itin>:
-  FR<0x1f, _funct, outs, ins, !strconcat(instr_asm, " $rt, $rs, $pos, $sz"=
),
-     pattern, itin>, Requires<[HasMips32r2]> {
+class ExtBase<bits<6> _funct, string instr_asm, RegisterClass RC>:
+  FR<0x1f, _funct, (outs RC:$rt), (ins RC:$rs, uimm16:$pos, size_ext:$sz),
+     !strconcat(instr_asm, " $rt, $rs, $pos, $sz"),
+     [(set RC:$rt, (MipsExt RC:$rs, imm:$pos, imm:$sz))], NoItinerary> {
   bits<5> pos;
   bits<5> sz;
   let rd =3D sz;
   let shamt =3D pos;
+  let Predicates =3D [HasMips32r2];
+}
+
+class InsBase<bits<6> _funct, string instr_asm, RegisterClass RC>:
+  FR<0x1f, _funct, (outs RC:$rt),
+     (ins RC:$rs, uimm16:$pos, size_ins:$sz, RC:$src),
+     !strconcat(instr_asm, " $rt, $rs, $pos, $sz"),
+     [(set RC:$rt, (MipsIns RC:$rs, imm:$pos, imm:$sz, RC:$src))],
+     NoItinerary> {
+  bits<5> pos;
+  bits<5> sz;
+  let rd =3D sz;
+  let shamt =3D pos;
+  let Predicates =3D [HasMips32r2];
+  let Constraints =3D "$src =3D $rt";
 }
=20
 // Atomic instructions with 2 source operands (ATOMIC_SWAP & ATOMIC_LOAD_*=
).
-class Atomic2Ops<PatFrag Op, string Opstr> :
-  MipsPseudo<(outs CPURegs:$dst), (ins CPURegs:$ptr, CPURegs:$incr),
+class Atomic2Ops<PatFrag Op, string Opstr, RegisterClass DRC,
+                 RegisterClass PRC> :
+  MipsPseudo<(outs DRC:$dst), (ins PRC:$ptr, DRC:$incr),
              !strconcat("atomic_", Opstr, "\t$dst, $ptr, $incr"),
-             [(set CPURegs:$dst,
-              (Op CPURegs:$ptr, CPURegs:$incr))]>;
+             [(set DRC:$dst, (Op PRC:$ptr, DRC:$incr))]>;
+
+multiclass Atomic2Ops32<PatFrag Op, string Opstr> {
+  def #NAME# : Atomic2Ops<Op, Opstr, CPURegs, CPURegs>, Requires<[NotN64]>;
+  def _P8    : Atomic2Ops<Op, Opstr, CPURegs, CPU64Regs>, Requires<[IsN64]=
>;
+}
=20
 // Atomic Compare & Swap.
-class AtomicCmpSwap<PatFrag Op, string Width> :
-  MipsPseudo<(outs CPURegs:$dst),=20
-             (ins CPURegs:$ptr, CPURegs:$cmp, CPURegs:$swap),
-             !strconcat("atomic_cmp_swap_", Width,=20
-                        "\t$dst, $ptr, $cmp, $swap"),
-             [(set CPURegs:$dst,
-              (Op CPURegs:$ptr, CPURegs:$cmp, CPURegs:$swap))]>;
+class AtomicCmpSwap<PatFrag Op, string Width, RegisterClass DRC,
+                    RegisterClass PRC> :
+  MipsPseudo<(outs DRC:$dst), (ins PRC:$ptr, DRC:$cmp, DRC:$swap),
+             !strconcat("atomic_cmp_swap_", Width, "\t$dst, $ptr, $cmp, $s=
wap"),
+             [(set DRC:$dst, (Op PRC:$ptr, DRC:$cmp, DRC:$swap))]>;
+
+multiclass AtomicCmpSwap32<PatFrag Op, string Width>  {
+  def #NAME# : AtomicCmpSwap<Op, Width, CPURegs, CPURegs>, Requires<[NotN6=
4]>;
+  def _P8    : AtomicCmpSwap<Op, Width, CPURegs, CPU64Regs>, Requires<[IsN=
64]>;
+}
+
+class LLBase<bits<6> Opc, string opstring, RegisterClass RC, Operand Mem> :
+  FMem<Opc, (outs RC:$rt), (ins Mem:$addr),
+       !strconcat(opstring, "\t$rt, $addr"), [], IILoad> {
+  let mayLoad =3D 1;
+}
+
+class SCBase<bits<6> Opc, string opstring, RegisterClass RC, Operand Mem> :
+  FMem<Opc, (outs RC:$dst), (ins RC:$rt, Mem:$addr),
+       !strconcat(opstring, "\t$rt, $addr"), [], IIStore> {
+  let mayStore =3D 1;
+  let Constraints =3D "$rt =3D $dst";
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Pseudo instructions
@@ -590,52 +727,64 @@
                                   [(callseq_end timm:$amt1, timm:$amt2)]>;
 }
=20
-// Some assembly macros need to avoid pseudoinstructions and assembler
-// automatic reodering, we should reorder ourselves.
-def MACRO     : MipsPseudo<(outs), (ins), ".set\tmacro",     []>;
-def REORDER   : MipsPseudo<(outs), (ins), ".set\treorder",   []>;
-def NOMACRO   : MipsPseudo<(outs), (ins), ".set\tnomacro",   []>;
-def NOREORDER : MipsPseudo<(outs), (ins), ".set\tnoreorder", []>;
-
-// These macros are inserted to prevent GAS from complaining
-// when using the AT register.
-def NOAT      : MipsPseudo<(outs), (ins), ".set\tnoat", []>;
-def ATMACRO   : MipsPseudo<(outs), (ins), ".set\tat", []>;
-
 // When handling PIC code the assembler needs .cpload and .cprestore
 // directives. If the real instructions corresponding these directives
 // are used, we have the same behavior, but get also a bunch of warnings
 // from the assembler.
-def CPLOAD : MipsPseudo<(outs), (ins CPURegs:$picreg), ".cpload\t$picreg",=
 []>;
-def CPRESTORE : MipsPseudo<(outs), (ins i32imm:$loc), ".cprestore\t$loc", =
[]>;
+let neverHasSideEffects =3D 1 in
+def CPRESTORE : MipsPseudo<(outs), (ins i32imm:$loc, CPURegs:$gp),
+                           ".cprestore\t$loc", []>;
+
+// For O32 ABI & PIC & non-fixed global base register, the following instr=
uction
+// seqeunce is emitted to set the global base register:
+//
+//  0. lui   $2, %hi(_gp_disp)
+//  1. addiu $2, $2, %lo(_gp_disp)
+//  2. addu  $globalbasereg, $2, $t9
+//
+// SETGP01 is emitted during Prologue/Epilogue insertion and then converte=
d to
+// instructions 0 and 1 in the sequence above during MC lowering.
+// SETGP2 is emitted just before register allocation and converted to
+// instruction 2 just prior to post-RA scheduling.
+//
+// These pseudo instructions are needed to ensure no instructions are inse=
rted
+// before or between instructions 0 and 1, which is a limitation imposed by
+// GNU linker.
+
+let isTerminator =3D 1, isBarrier =3D 1 in
+def SETGP01 : MipsPseudo<(outs CPURegs:$dst), (ins), "", []>;
+
+let neverHasSideEffects =3D 1 in
+def SETGP2 : MipsPseudo<(outs CPURegs:$globalreg), (ins CPURegs:$picreg), =
"",
+                        []>;
=20
 let usesCustomInserter =3D 1 in {
-  def ATOMIC_LOAD_ADD_I8   : Atomic2Ops<atomic_load_add_8, "load_add_8">;
-  def ATOMIC_LOAD_ADD_I16  : Atomic2Ops<atomic_load_add_16, "load_add_16">;
-  def ATOMIC_LOAD_ADD_I32  : Atomic2Ops<atomic_load_add_32, "load_add_32">;
-  def ATOMIC_LOAD_SUB_I8   : Atomic2Ops<atomic_load_sub_8, "load_sub_8">;
-  def ATOMIC_LOAD_SUB_I16  : Atomic2Ops<atomic_load_sub_16, "load_sub_16">;
-  def ATOMIC_LOAD_SUB_I32  : Atomic2Ops<atomic_load_sub_32, "load_sub_32">;
-  def ATOMIC_LOAD_AND_I8   : Atomic2Ops<atomic_load_and_8, "load_and_8">;
-  def ATOMIC_LOAD_AND_I16  : Atomic2Ops<atomic_load_and_16, "load_and_16">;
-  def ATOMIC_LOAD_AND_I32  : Atomic2Ops<atomic_load_and_32, "load_and_32">;
-  def ATOMIC_LOAD_OR_I8    : Atomic2Ops<atomic_load_or_8, "load_or_8">;
-  def ATOMIC_LOAD_OR_I16   : Atomic2Ops<atomic_load_or_16, "load_or_16">;
-  def ATOMIC_LOAD_OR_I32   : Atomic2Ops<atomic_load_or_32, "load_or_32">;
-  def ATOMIC_LOAD_XOR_I8   : Atomic2Ops<atomic_load_xor_8, "load_xor_8">;
-  def ATOMIC_LOAD_XOR_I16  : Atomic2Ops<atomic_load_xor_16, "load_xor_16">;
-  def ATOMIC_LOAD_XOR_I32  : Atomic2Ops<atomic_load_xor_32, "load_xor_32">;
-  def ATOMIC_LOAD_NAND_I8  : Atomic2Ops<atomic_load_nand_8, "load_nand_8">;
-  def ATOMIC_LOAD_NAND_I16 : Atomic2Ops<atomic_load_nand_16, "load_nand_16=
">;
-  def ATOMIC_LOAD_NAND_I32 : Atomic2Ops<atomic_load_nand_32, "load_nand_32=
">;
+  defm ATOMIC_LOAD_ADD_I8   : Atomic2Ops32<atomic_load_add_8, "load_add_8"=
>;
+  defm ATOMIC_LOAD_ADD_I16  : Atomic2Ops32<atomic_load_add_16, "load_add_1=
6">;
+  defm ATOMIC_LOAD_ADD_I32  : Atomic2Ops32<atomic_load_add_32, "load_add_3=
2">;
+  defm ATOMIC_LOAD_SUB_I8   : Atomic2Ops32<atomic_load_sub_8, "load_sub_8"=
>;
+  defm ATOMIC_LOAD_SUB_I16  : Atomic2Ops32<atomic_load_sub_16, "load_sub_1=
6">;
+  defm ATOMIC_LOAD_SUB_I32  : Atomic2Ops32<atomic_load_sub_32, "load_sub_3=
2">;
+  defm ATOMIC_LOAD_AND_I8   : Atomic2Ops32<atomic_load_and_8, "load_and_8"=
>;
+  defm ATOMIC_LOAD_AND_I16  : Atomic2Ops32<atomic_load_and_16, "load_and_1=
6">;
+  defm ATOMIC_LOAD_AND_I32  : Atomic2Ops32<atomic_load_and_32, "load_and_3=
2">;
+  defm ATOMIC_LOAD_OR_I8    : Atomic2Ops32<atomic_load_or_8, "load_or_8">;
+  defm ATOMIC_LOAD_OR_I16   : Atomic2Ops32<atomic_load_or_16, "load_or_16"=
>;
+  defm ATOMIC_LOAD_OR_I32   : Atomic2Ops32<atomic_load_or_32, "load_or_32"=
>;
+  defm ATOMIC_LOAD_XOR_I8   : Atomic2Ops32<atomic_load_xor_8, "load_xor_8"=
>;
+  defm ATOMIC_LOAD_XOR_I16  : Atomic2Ops32<atomic_load_xor_16, "load_xor_1=
6">;
+  defm ATOMIC_LOAD_XOR_I32  : Atomic2Ops32<atomic_load_xor_32, "load_xor_3=
2">;
+  defm ATOMIC_LOAD_NAND_I8  : Atomic2Ops32<atomic_load_nand_8, "load_nand_=
8">;
+  defm ATOMIC_LOAD_NAND_I16 : Atomic2Ops32<atomic_load_nand_16, "load_nand=
_16">;
+  defm ATOMIC_LOAD_NAND_I32 : Atomic2Ops32<atomic_load_nand_32, "load_nand=
_32">;
=20
-  def ATOMIC_SWAP_I8       : Atomic2Ops<atomic_swap_8, "swap_8">;
-  def ATOMIC_SWAP_I16      : Atomic2Ops<atomic_swap_16, "swap_16">;
-  def ATOMIC_SWAP_I32      : Atomic2Ops<atomic_swap_32, "swap_32">;
+  defm ATOMIC_SWAP_I8       : Atomic2Ops32<atomic_swap_8, "swap_8">;
+  defm ATOMIC_SWAP_I16      : Atomic2Ops32<atomic_swap_16, "swap_16">;
+  defm ATOMIC_SWAP_I32      : Atomic2Ops32<atomic_swap_32, "swap_32">;
=20
-  def ATOMIC_CMP_SWAP_I8   : AtomicCmpSwap<atomic_cmp_swap_8, "8">;
-  def ATOMIC_CMP_SWAP_I16  : AtomicCmpSwap<atomic_cmp_swap_16, "16">;
-  def ATOMIC_CMP_SWAP_I32  : AtomicCmpSwap<atomic_cmp_swap_32, "32">;
+  defm ATOMIC_CMP_SWAP_I8   : AtomicCmpSwap32<atomic_cmp_swap_8, "8">;
+  defm ATOMIC_CMP_SWAP_I16  : AtomicCmpSwap32<atomic_cmp_swap_16, "16">;
+  defm ATOMIC_CMP_SWAP_I32  : AtomicCmpSwap32<atomic_cmp_swap_32, "32">;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -654,7 +803,7 @@
 def ANDi    : ArithLogicI<0x0c, "andi", and, uimm16, immZExt16, CPURegs>;
 def ORi     : ArithLogicI<0x0d, "ori", or, uimm16, immZExt16, CPURegs>;
 def XORi    : ArithLogicI<0x0e, "xori", xor, uimm16, immZExt16, CPURegs>;
-def LUi     : LoadUpper<0x0f, "lui">;
+def LUi     : LoadUpper<0x0f, "lui", CPURegs, uimm16>;
=20
 /// Arithmetic Instructions (3-Operand, R-Type)
 def ADDu    : ArithLogicR<0x00, 0x21, "addu", add, IIAlu, CPURegs, 1>;
@@ -669,17 +818,17 @@
 def NOR     : LogicNOR<0x00, 0x27, "nor", CPURegs>;
=20
 /// Shift Instructions
-def SLL     : LogicR_shift_rotate_imm<0x00, 0x00, "sll", shl>;
-def SRL     : LogicR_shift_rotate_imm<0x02, 0x00, "srl", srl>;
-def SRA     : LogicR_shift_rotate_imm<0x03, 0x00, "sra", sra>;
-def SLLV    : LogicR_shift_rotate_reg<0x04, 0x00, "sllv", shl>;
-def SRLV    : LogicR_shift_rotate_reg<0x06, 0x00, "srlv", srl>;
-def SRAV    : LogicR_shift_rotate_reg<0x07, 0x00, "srav", sra>;
+def SLL     : shift_rotate_imm32<0x00, 0x00, "sll", shl>;
+def SRL     : shift_rotate_imm32<0x02, 0x00, "srl", srl>;
+def SRA     : shift_rotate_imm32<0x03, 0x00, "sra", sra>;
+def SLLV    : shift_rotate_reg<0x04, 0x00, "sllv", shl, CPURegs>;
+def SRLV    : shift_rotate_reg<0x06, 0x00, "srlv", srl, CPURegs>;
+def SRAV    : shift_rotate_reg<0x07, 0x00, "srav", sra, CPURegs>;
=20
 // Rotate Instructions
 let Predicates =3D [HasMips32r2] in {
-    def ROTR    : LogicR_shift_rotate_imm<0x02, 0x01, "rotr", rotr>;
-    def ROTRV   : LogicR_shift_rotate_reg<0x06, 0x01, "rotrv", rotr>;
+    def ROTR    : shift_rotate_imm32<0x02, 0x01, "rotr", rotr>;
+    def ROTRV   : shift_rotate_reg<0x06, 0x01, "rotrv", rotr, CPURegs>;
 }
=20
 /// Load and Store Instructions
@@ -700,6 +849,12 @@
 defm USH     : StoreM32<0x29, "ush", truncstorei16_u, 1>;
 defm USW     : StoreM32<0x2b, "usw", store_u, 1>;
=20
+/// Primitives for unaligned
+defm LWL     : LoadUnAlign32<0x22>;
+defm LWR     : LoadUnAlign32<0x26>;
+defm SWL     : StoreUnAlign32<0x2A>;
+defm SWR     : StoreUnAlign32<0x2E>;
+
 let hasSideEffects =3D 1 in
 def SYNC : MipsInst<(outs), (ins i32imm:$stype), "sync $stype",
                     [(MipsSync imm:$stype)], NoItinerary, FrmOther>
@@ -712,19 +867,15 @@
 }
=20
 /// Load-linked, Store-conditional
-let mayLoad =3D 1 in
-  def LL    : FMem<0x30, (outs CPURegs:$rt), (ins mem:$addr),
-              "ll\t$rt, $addr", [], IILoad>;
-let mayStore =3D 1, Constraints =3D "$rt =3D $dst" in
-  def SC    : FMem<0x38, (outs CPURegs:$dst), (ins CPURegs:$rt, mem:$addr),
-              "sc\t$rt, $addr", [], IIStore>;
+def LL    : LLBase<0x30, "ll", CPURegs, mem>, Requires<[NotN64]>;
+def LL_P8 : LLBase<0x30, "ll", CPURegs, mem64>, Requires<[IsN64]>;
+def SC    : SCBase<0x38, "sc", CPURegs, mem>, Requires<[NotN64]>;
+def SC_P8 : SCBase<0x38, "sc", CPURegs, mem64>, Requires<[IsN64]>;
=20
 /// Jump and Branch Instructions
 def J       : JumpFJ<0x02, "j">;
-let isIndirectBranch =3D 1 in
-  def JR      : JumpFR<0x00, 0x08, "jr">;
-def JAL     : JumpLink<0x03, "jal">;
-def JALR    : JumpLinkReg<0x00, 0x09, "jalr">;
+def JR      : JumpFR<0x00, 0x08, "jr", CPURegs>;
+def B       : UncondBranch<0x04, "b">;
 def BEQ     : CBranch<0x04, "beq", seteq, CPURegs>;
 def BNE     : CBranch<0x05, "bne", setne, CPURegs>;
 def BGEZ    : CBranchZero<0x01, 1, "bgez", setge, CPURegs>;
@@ -732,10 +883,10 @@
 def BLEZ    : CBranchZero<0x06, 0, "blez", setle, CPURegs>;
 def BLTZ    : CBranchZero<0x01, 0, "bltz", setlt, CPURegs>;
=20
-let rt=3D0x11 in
-  def BGEZAL  : BranchLink<"bgezal">;
-let rt=3D0x10 in
-  def BLTZAL  : BranchLink<"bltzal">;
+def JAL  : JumpLink<0x03, "jal">;
+def JALR : JumpLinkReg<0x00, 0x09, "jalr", CPURegs>;
+def BGEZAL  : BranchLink<"bgezal", 0x11, CPURegs>;
+def BLTZAL  : BranchLink<"bltzal", 0x10, CPURegs>;
=20
 let isReturn=3D1, isTerminator=3D1, hasDelaySlot=3D1,
     isBarrier=3D1, hasCtrlDep=3D1, rd=3D0, rt=3D0, shamt=3D0 in
@@ -743,50 +894,26 @@
                 "jr\t$target", [(MipsRet CPURegs:$target)], IIBranch>;
=20
 /// Multiply and Divide Instructions.
-def MULT    : Mul<0x18, "mult", IIImul>;
-def MULTu   : Mul<0x19, "multu", IIImul>;
-def SDIV    : Div<MipsDivRem, 0x1a, "div", IIIdiv>;
-def UDIV    : Div<MipsDivRemU, 0x1b, "divu", IIIdiv>;
+def MULT    : Mult32<0x18, "mult", IIImul>;
+def MULTu   : Mult32<0x19, "multu", IIImul>;
+def SDIV    : Div32<MipsDivRem, 0x1a, "div", IIIdiv>;
+def UDIV    : Div32<MipsDivRemU, 0x1b, "divu", IIIdiv>;
=20
-let Defs =3D [HI] in
-  def MTHI  : MoveToLOHI<0x11, "mthi">;
-let Defs =3D [LO] in
-  def MTLO  : MoveToLOHI<0x13, "mtlo">;
-
-let Uses =3D [HI] in
-  def MFHI  : MoveFromLOHI<0x10, "mfhi">;
-let Uses =3D [LO] in
-  def MFLO  : MoveFromLOHI<0x12, "mflo">;
+def MTHI : MoveToLOHI<0x11, "mthi", CPURegs, [HI]>;
+def MTLO : MoveToLOHI<0x13, "mtlo", CPURegs, [LO]>;
+def MFHI : MoveFromLOHI<0x10, "mfhi", CPURegs, [HI]>;
+def MFLO : MoveFromLOHI<0x12, "mflo", CPURegs, [LO]>;
=20
 /// Sign Ext In Register Instructions.
-def SEB : SignExtInReg<0x10, "seb", i8>;
-def SEH : SignExtInReg<0x18, "seh", i16>;
+def SEB : SignExtInReg<0x10, "seb", i8, CPURegs>;
+def SEH : SignExtInReg<0x18, "seh", i16, CPURegs>;
=20
 /// Count Leading
-def CLZ : CountLeading<0x20, "clz",
-                       [(set CPURegs:$rd, (ctlz CPURegs:$rs))]>;
-def CLO : CountLeading<0x21, "clo",
-                       [(set CPURegs:$rd, (ctlz (not CPURegs:$rs)))]>;
+def CLZ : CountLeading0<0x20, "clz", CPURegs>;
+def CLO : CountLeading1<0x21, "clo", CPURegs>;
=20
-/// Byte Swap
-def WSBW : ByteSwap<0x20, 0x2, "wsbw">;
-
-// Conditional moves:
-// These instructions are expanded in
-// MipsISelLowering::EmitInstrWithCustomInserter if target does not have
-// conditional move instructions.
-// flag:int, data:int
-class CondMovIntInt<bits<6> funct, string instr_asm> :
-  FR<0, funct, (outs CPURegs:$rd),
-     (ins CPURegs:$rs, CPURegs:$rt, CPURegs:$F),
-     !strconcat(instr_asm, "\t$rd, $rs, $rt"), [], NoItinerary> {
-  let shamt =3D 0;
-  let usesCustomInserter =3D 1;
-  let Constraints =3D "$F =3D $rd";
-}
-
-def MOVZ_I : CondMovIntInt<0x0a, "movz">;
-def MOVN_I : CondMovIntInt<0x0b, "movn">;
+/// Word Swap Bytes Within Halfwords
+def WSBH : SubwordSwap<0x20, 0x2, "wsbh", CPURegs>;
=20
 /// No operation
 let addr=3D0 in
@@ -796,13 +923,13 @@
 // instructions. The same not happens for stack address copies, so an
 // add op with mem ComplexPattern is used and the stack address copy
 // can be matched. It's similar to Sparc LEA_ADDRi
-def LEA_ADDiu : EffectiveAddress<"addiu\t$rt, $addr">;
+def LEA_ADDiu : EffectiveAddress<"addiu\t$rt, $addr", CPURegs, mem_ea>;
=20
 // DynAlloc node points to dynamically allocated stack space.
 // $sp is added to the list of implicitly used registers to prevent dead c=
ode
 // elimination from removing instructions that modify $sp.
 let Uses =3D [SP] in
-def DynAlloc : EffectiveAddress<"addiu\t$rt, $addr">;
+def DynAlloc : EffectiveAddress<"addiu\t$rt, $addr", CPURegs, mem_ea>;
=20
 // MADD*/MSUB*
 def MADD  : MArithR<0, "madd", MipsMAdd, 1>;
@@ -815,21 +942,10 @@
 def MUL   : ArithLogicR<0x1c, 0x02, "mul", mul, IIImul, CPURegs, 1>,
             Requires<[HasMips32]>;
=20
-def RDHWR : ReadHardware;
+def RDHWR : ReadHardware<CPURegs, HWRegs>;
=20
-def EXT : ExtIns<0, "ext", (outs CPURegs:$rt),
-                 (ins CPURegs:$rs, uimm16:$pos, size_ext:$sz),
-                 [(set CPURegs:$rt,
-                   (MipsExt CPURegs:$rs, immZExt5:$pos, immZExt5:$sz))],
-                 NoItinerary>;
-
-let Constraints =3D "$src =3D $rt" in
-def INS : ExtIns<4, "ins", (outs CPURegs:$rt),
-                 (ins CPURegs:$rs, uimm16:$pos, size_ins:$sz, CPURegs:$src=
),
-                 [(set CPURegs:$rt,
-                   (MipsIns CPURegs:$rs, immZExt5:$pos, immZExt5:$sz,
-                    CPURegs:$src))],
-                 NoItinerary>;
+def EXT : ExtBase<0, "ext", CPURegs>;
+def INS : InsBase<4, "ins", CPURegs>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Arbitrary patterns that map to one or more instructions
@@ -840,6 +956,8 @@
           (ADDiu ZERO, imm:$in)>;
 def : Pat<(i32 immZExt16:$in),
           (ORi ZERO, imm:$in)>;
+def : Pat<(i32 immLow16Zero:$in),
+          (LUi (HI16 imm:$in))>;
=20
 // Arbitrary immediates
 def : Pat<(i32 imm:$imm),
@@ -864,22 +982,26 @@
 // hi/lo relocs
 def : Pat<(MipsHi tglobaladdr:$in), (LUi tglobaladdr:$in)>;
 def : Pat<(MipsHi tblockaddress:$in), (LUi tblockaddress:$in)>;
+def : Pat<(MipsHi tjumptable:$in), (LUi tjumptable:$in)>;
+def : Pat<(MipsHi tconstpool:$in), (LUi tconstpool:$in)>;
+def : Pat<(MipsHi tglobaltlsaddr:$in), (LUi tglobaltlsaddr:$in)>;
+
 def : Pat<(MipsLo tglobaladdr:$in), (ADDiu ZERO, tglobaladdr:$in)>;
 def : Pat<(MipsLo tblockaddress:$in), (ADDiu ZERO, tblockaddress:$in)>;
+def : Pat<(MipsLo tjumptable:$in), (ADDiu ZERO, tjumptable:$in)>;
+def : Pat<(MipsLo tconstpool:$in), (ADDiu ZERO, tconstpool:$in)>;
+def : Pat<(MipsLo tglobaltlsaddr:$in), (ADDiu ZERO, tglobaltlsaddr:$in)>;
+
 def : Pat<(add CPURegs:$hi, (MipsLo tglobaladdr:$lo)),
           (ADDiu CPURegs:$hi, tglobaladdr:$lo)>;
 def : Pat<(add CPURegs:$hi, (MipsLo tblockaddress:$lo)),
           (ADDiu CPURegs:$hi, tblockaddress:$lo)>;
-
-def : Pat<(MipsHi tjumptable:$in), (LUi tjumptable:$in)>;
-def : Pat<(MipsLo tjumptable:$in), (ADDiu ZERO, tjumptable:$in)>;
 def : Pat<(add CPURegs:$hi, (MipsLo tjumptable:$lo)),
           (ADDiu CPURegs:$hi, tjumptable:$lo)>;
-
-def : Pat<(MipsHi tconstpool:$in), (LUi tconstpool:$in)>;
-def : Pat<(MipsLo tconstpool:$in), (ADDiu ZERO, tconstpool:$in)>;
 def : Pat<(add CPURegs:$hi, (MipsLo tconstpool:$lo)),
           (ADDiu CPURegs:$hi, tconstpool:$lo)>;
+def : Pat<(add CPURegs:$hi, (MipsLo tglobaltlsaddr:$lo)),
+          (ADDiu CPURegs:$hi, tglobaltlsaddr:$lo)>;
=20
 // gp_rel relocs
 def : Pat<(add CPURegs:$gp, (MipsGPRel tglobaladdr:$in)),
@@ -887,39 +1009,45 @@
 def : Pat<(add CPURegs:$gp, (MipsGPRel tconstpool:$in)),
           (ADDiu CPURegs:$gp, tconstpool:$in)>;
=20
-// tlsgd
-def : Pat<(add CPURegs:$gp, (MipsTlsGd tglobaltlsaddr:$in)),
-          (ADDiu CPURegs:$gp, tglobaltlsaddr:$in)>;
+// wrapper_pic
+class WrapperPat<SDNode node, Instruction ADDiuOp, RegisterClass RC>:
+      Pat<(MipsWrapper RC:$gp, node:$in),
+          (ADDiuOp RC:$gp, node:$in)>;
=20
-// tprel hi/lo
-def : Pat<(MipsTprelHi tglobaltlsaddr:$in), (LUi tglobaltlsaddr:$in)>;
-def : Pat<(MipsTprelLo tglobaltlsaddr:$in), (ADDiu ZERO, tglobaltlsaddr:$i=
n)>;
-def : Pat<(add CPURegs:$hi, (MipsTprelLo tglobaltlsaddr:$lo)),
-          (ADDiu CPURegs:$hi, tglobaltlsaddr:$lo)>;
-
-// wrapper_pic
-class WrapperPICPat<SDNode node>:
-      Pat<(MipsWrapperPIC node:$in),
-          (ADDiu GP, node:$in)>;
-
-def : WrapperPICPat<tglobaladdr>;
-def : WrapperPICPat<tconstpool>;
-def : WrapperPICPat<texternalsym>;
-def : WrapperPICPat<tblockaddress>;
-def : WrapperPICPat<tjumptable>;
+def : WrapperPat<tglobaladdr, ADDiu, CPURegs>;
+def : WrapperPat<tconstpool, ADDiu, CPURegs>;
+def : WrapperPat<texternalsym, ADDiu, CPURegs>;
+def : WrapperPat<tblockaddress, ADDiu, CPURegs>;
+def : WrapperPat<tjumptable, ADDiu, CPURegs>;
+def : WrapperPat<tglobaltlsaddr, ADDiu, CPURegs>;
=20
 // Mips does not have "not", so we expand our way
 def : Pat<(not CPURegs:$in),
           (NOR CPURegs:$in, ZERO)>;
=20
-// extended load and stores
-def : Pat<(extloadi1  addr:$src), (LBu addr:$src)>;
-def : Pat<(extloadi8  addr:$src), (LBu addr:$src)>;
-def : Pat<(extloadi16_a addr:$src), (LHu addr:$src)>;
-def : Pat<(extloadi16_u addr:$src), (ULHu addr:$src)>;
+// extended loads
+let Predicates =3D [NotN64] in {
+  def : Pat<(i32 (extloadi1  addr:$src)), (LBu addr:$src)>;
+  def : Pat<(i32 (extloadi8  addr:$src)), (LBu addr:$src)>;
+  def : Pat<(i32 (extloadi16_a addr:$src)), (LHu addr:$src)>;
+  def : Pat<(i32 (extloadi16_u addr:$src)), (ULHu addr:$src)>;
+}
+let Predicates =3D [IsN64] in {
+  def : Pat<(i32 (extloadi1  addr:$src)), (LBu_P8 addr:$src)>;
+  def : Pat<(i32 (extloadi8  addr:$src)), (LBu_P8 addr:$src)>;
+  def : Pat<(i32 (extloadi16_a addr:$src)), (LHu_P8 addr:$src)>;
+  def : Pat<(i32 (extloadi16_u addr:$src)), (ULHu_P8 addr:$src)>;
+}
=20
 // peepholes
-def : Pat<(store (i32 0), addr:$dst), (SW ZERO, addr:$dst)>;
+let Predicates =3D [NotN64] in {
+  def : Pat<(store_a (i32 0), addr:$dst), (SW ZERO, addr:$dst)>;
+  def : Pat<(store_u (i32 0), addr:$dst), (USW ZERO, addr:$dst)>;
+}
+let Predicates =3D [IsN64] in {
+  def : Pat<(store_a (i32 0), addr:$dst), (SW_P8 ZERO, addr:$dst)>;
+  def : Pat<(store_u (i32 0), addr:$dst), (USW_P8 ZERO, addr:$dst)>;
+}
=20
 // brcond patterns
 multiclass BrcondPats<RegisterClass RC, Instruction BEQOp, Instruction BNE=
Op,
@@ -950,38 +1078,6 @@
=20
 defm : BrcondPats<CPURegs, BEQ, BNE, SLT, SLTu, SLTi, SLTiu, ZERO>;
=20
-// select patterns
-multiclass MovzPats<RegisterClass RC, Instruction MOVZInst> {
-  def : Pat<(select (i32 (setge CPURegs:$lhs, CPURegs:$rhs)), RC:$T, RC:$F=
),
-            (MOVZInst RC:$T, (SLT CPURegs:$lhs, CPURegs:$rhs), RC:$F)>;
-  def : Pat<(select (i32 (setuge CPURegs:$lhs, CPURegs:$rhs)), RC:$T, RC:$=
F),
-            (MOVZInst RC:$T, (SLTu CPURegs:$lhs, CPURegs:$rhs), RC:$F)>;
-  def : Pat<(select (i32 (setge CPURegs:$lhs, immSExt16:$rhs)), RC:$T, RC:=
$F),
-            (MOVZInst RC:$T, (SLTi CPURegs:$lhs, immSExt16:$rhs), RC:$F)>;
-  def : Pat<(select (i32 (setuge CPURegs:$lh, immSExt16:$rh)), RC:$T, RC:$=
F),
-            (MOVZInst RC:$T, (SLTiu CPURegs:$lh, immSExt16:$rh), RC:$F)>;
-  def : Pat<(select (i32 (setle CPURegs:$lhs, CPURegs:$rhs)), RC:$T, RC:$F=
),
-            (MOVZInst RC:$T, (SLT CPURegs:$rhs, CPURegs:$lhs), RC:$F)>;
-  def : Pat<(select (i32 (setule CPURegs:$lhs, CPURegs:$rhs)), RC:$T, RC:$=
F),
-            (MOVZInst RC:$T, (SLTu CPURegs:$rhs, CPURegs:$lhs), RC:$F)>;
-  def : Pat<(select (i32 (seteq CPURegs:$lhs, CPURegs:$rhs)), RC:$T, RC:$F=
),
-            (MOVZInst RC:$T, (XOR CPURegs:$lhs, CPURegs:$rhs), RC:$F)>;
-  def : Pat<(select (i32 (seteq CPURegs:$lhs, 0)), RC:$T, RC:$F),
-            (MOVZInst RC:$T, CPURegs:$lhs, RC:$F)>;
-}
-
-multiclass MovnPats<RegisterClass RC, Instruction MOVNInst> {
-  def : Pat<(select (i32 (setne CPURegs:$lhs, CPURegs:$rhs)), RC:$T, RC:$F=
),
-            (MOVNInst RC:$T, (XOR CPURegs:$lhs, CPURegs:$rhs), RC:$F)>;
-  def : Pat<(select CPURegs:$cond, RC:$T, RC:$F),
-            (MOVNInst RC:$T, CPURegs:$cond, RC:$F)>;
-  def : Pat<(select (i32 (setne CPURegs:$lhs, 0)), RC:$T, RC:$F),
-            (MOVNInst RC:$T, CPURegs:$lhs, RC:$F)>;
-}
-
-defm : MovzPats<CPURegs, MOVZ_I>;
-defm : MovnPats<CPURegs, MOVN_I>;
-
 // setcc patterns
 multiclass SeteqPats<RegisterClass RC, Instruction SLTiuOp, Instruction XO=
ROp,
                      Instruction SLTuOp, Register ZEROReg> {
@@ -1029,10 +1125,14 @@
 // select MipsDynAlloc
 def : Pat<(MipsDynAlloc addr:$f), (DynAlloc addr:$f)>;
=20
+// bswap pattern
+def : Pat<(bswap CPURegs:$rt), (ROTR (WSBH CPURegs:$rt), 16)>;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Floating Point Support
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 include "MipsInstrFPU.td"
 include "Mips64InstrInfo.td"
+include "MipsCondMov.td"
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
JITInfo.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsJITInfo.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsJITInfo.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsJITInfo.cpp - Implement the JIT interfaces for the Mips t=
arget -=3D=3D=3D//
+//=3D=3D=3D-- MipsJITInfo.cpp - Implement the Mips JIT Interface ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -200,7 +200,7 @@
     intptr_t ResultPtr =3D (intptr_t) MR->getResultPointer();
=20
     switch ((Mips::RelocationType) MR->getRelocationType()) {
-    case Mips::reloc_mips_branch:
+    case Mips::reloc_mips_pc16:
       ResultPtr =3D (((ResultPtr - (intptr_t) RelocPos) - 4) >> 2) & 0xfff=
f;
       *((unsigned*) RelocPos) |=3D (unsigned) ResultPtr;
       break;
@@ -218,13 +218,16 @@
       *((unsigned*) RelocPos) |=3D (unsigned) ResultPtr;
       break;
=20
-    case Mips::reloc_mips_lo:
-      ResultPtr =3D ResultPtr & 0xffff;
+    case Mips::reloc_mips_lo: {
+      // Addend is needed for unaligned load/store instructions, where off=
set
+      // for the second load/store in the expanded instruction sequence mu=
st
+      // be modified by +1 or +3. Otherwise, Addend is 0.
+      int Addend =3D *((unsigned*) RelocPos) & 0xffff;
+      ResultPtr =3D (ResultPtr + Addend) & 0xffff;
+      *((unsigned*) RelocPos) &=3D 0xffff0000;
       *((unsigned*) RelocPos) |=3D (unsigned) ResultPtr;
       break;
-
-    default:
-      llvm_unreachable("ERROR: Unknown Mips relocation.");
+    }
     }
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
JITInfo.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsJITInfo.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsJITInfo.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsJITInfo.h - Mips implementation of the JIT interface -*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D- MipsJITInfo.h - Mips Implementation of the JIT Interface -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -19,8 +19,6 @@
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
 #include "llvm/Target/TargetJITInfo.h"
-#include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/SmallVector.h"
=20
 namespace llvm {
 class MipsTargetMachine;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
MCInstLower.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsMCInstLower.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsMCInstLower.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,99 +15,179 @@
 #include "MipsMCInstLower.h"
 #include "MipsAsmPrinter.h"
 #include "MipsInstrInfo.h"
-#include "MipsMCSymbolRefExpr.h"
+#include "MCTargetDesc/MipsBaseInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstr.h"
 #include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/MC/MCContext.h"
+#include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/Target/Mangler.h"
+
 using namespace llvm;
=20
-MipsMCInstLower::MipsMCInstLower(Mangler *mang, const MachineFunction &mf,
-                                 MipsAsmPrinter &asmprinter)
-  : Ctx(mf.getContext()), Mang(mang), AsmPrinter(asmprinter) {}
+MipsMCInstLower::MipsMCInstLower(MipsAsmPrinter &asmprinter)
+  : AsmPrinter(asmprinter) {}
+
+void MipsMCInstLower::Initialize(Mangler *M, MCContext* C) {
+  Mang =3D M;
+  Ctx =3D C;
+}
=20
 MCOperand MipsMCInstLower::LowerSymbolOperand(const MachineOperand &MO,
                                               MachineOperandType MOTy,
                                               unsigned Offset) const {
-  MipsMCSymbolRefExpr::VariantKind Kind;
+  MCSymbolRefExpr::VariantKind Kind;
   const MCSymbol *Symbol;
=20
   switch(MO.getTargetFlags()) {
-  default:                  assert(0 && "Invalid target flag!");
-  case MipsII::MO_NO_FLAG:  Kind =3D MipsMCSymbolRefExpr::VK_Mips_None; br=
eak;
-  case MipsII::MO_GPREL:    Kind =3D MipsMCSymbolRefExpr::VK_Mips_GPREL; b=
reak;
-  case MipsII::MO_GOT_CALL: Kind =3D MipsMCSymbolRefExpr::VK_Mips_GOT_CALL=
; break;
-  case MipsII::MO_GOT:      Kind =3D MipsMCSymbolRefExpr::VK_Mips_GOT; bre=
ak;
-  case MipsII::MO_ABS_HI:   Kind =3D MipsMCSymbolRefExpr::VK_Mips_ABS_HI; =
break;
-  case MipsII::MO_ABS_LO:   Kind =3D MipsMCSymbolRefExpr::VK_Mips_ABS_LO; =
break;
-  case MipsII::MO_TLSGD:    Kind =3D MipsMCSymbolRefExpr::VK_Mips_TLSGD; b=
reak;
-  case MipsII::MO_GOTTPREL: Kind =3D MipsMCSymbolRefExpr::VK_Mips_GOTTPREL=
; break;
-  case MipsII::MO_TPREL_HI: Kind =3D MipsMCSymbolRefExpr::VK_Mips_TPREL_HI=
; break;
-  case MipsII::MO_TPREL_LO: Kind =3D MipsMCSymbolRefExpr::VK_Mips_TPREL_LO=
; break;
-  case MipsII::MO_GPOFF_HI: Kind =3D MipsMCSymbolRefExpr::VK_Mips_GPOFF_HI=
; break;
-  case MipsII::MO_GPOFF_LO: Kind =3D MipsMCSymbolRefExpr::VK_Mips_GPOFF_LO=
; break;
-  case MipsII::MO_GOT_DISP: Kind =3D MipsMCSymbolRefExpr::VK_Mips_GOT_DISP=
; break;
-  case MipsII::MO_GOT_PAGE: Kind =3D MipsMCSymbolRefExpr::VK_Mips_GOT_PAGE=
; break;
-  case MipsII::MO_GOT_OFST: Kind =3D MipsMCSymbolRefExpr::VK_Mips_GOT_OFST=
; break;
+  default:                   llvm_unreachable("Invalid target flag!");
+  case MipsII::MO_NO_FLAG:   Kind =3D MCSymbolRefExpr::VK_None; break;
+  case MipsII::MO_GPREL:     Kind =3D MCSymbolRefExpr::VK_Mips_GPREL; brea=
k;
+  case MipsII::MO_GOT_CALL:  Kind =3D MCSymbolRefExpr::VK_Mips_GOT_CALL; b=
reak;
+  case MipsII::MO_GOT16:     Kind =3D MCSymbolRefExpr::VK_Mips_GOT16; brea=
k;
+  case MipsII::MO_GOT:       Kind =3D MCSymbolRefExpr::VK_Mips_GOT; break;
+  case MipsII::MO_ABS_HI:    Kind =3D MCSymbolRefExpr::VK_Mips_ABS_HI; bre=
ak;
+  case MipsII::MO_ABS_LO:    Kind =3D MCSymbolRefExpr::VK_Mips_ABS_LO; bre=
ak;
+  case MipsII::MO_TLSGD:     Kind =3D MCSymbolRefExpr::VK_Mips_TLSGD; brea=
k;
+  case MipsII::MO_TLSLDM:    Kind =3D MCSymbolRefExpr::VK_Mips_TLSLDM; bre=
ak;
+  case MipsII::MO_DTPREL_HI: Kind =3D MCSymbolRefExpr::VK_Mips_DTPREL_HI; =
break;
+  case MipsII::MO_DTPREL_LO: Kind =3D MCSymbolRefExpr::VK_Mips_DTPREL_LO; =
break;
+  case MipsII::MO_GOTTPREL:  Kind =3D MCSymbolRefExpr::VK_Mips_GOTTPREL; b=
reak;
+  case MipsII::MO_TPREL_HI:  Kind =3D MCSymbolRefExpr::VK_Mips_TPREL_HI; b=
reak;
+  case MipsII::MO_TPREL_LO:  Kind =3D MCSymbolRefExpr::VK_Mips_TPREL_LO; b=
reak;
+  case MipsII::MO_GPOFF_HI:  Kind =3D MCSymbolRefExpr::VK_Mips_GPOFF_HI; b=
reak;
+  case MipsII::MO_GPOFF_LO:  Kind =3D MCSymbolRefExpr::VK_Mips_GPOFF_LO; b=
reak;
+  case MipsII::MO_GOT_DISP:  Kind =3D MCSymbolRefExpr::VK_Mips_GOT_DISP; b=
reak;
+  case MipsII::MO_GOT_PAGE:  Kind =3D MCSymbolRefExpr::VK_Mips_GOT_PAGE; b=
reak;
+  case MipsII::MO_GOT_OFST:  Kind =3D MCSymbolRefExpr::VK_Mips_GOT_OFST; b=
reak;
   }
=20
   switch (MOTy) {
-    case MachineOperand::MO_MachineBasicBlock:
-      Symbol =3D MO.getMBB()->getSymbol();
-      break;
+  case MachineOperand::MO_MachineBasicBlock:
+    Symbol =3D MO.getMBB()->getSymbol();
+    break;
=20
-    case MachineOperand::MO_GlobalAddress:
-      Symbol =3D Mang->getSymbol(MO.getGlobal());
-      break;
+  case MachineOperand::MO_GlobalAddress:
+    Symbol =3D Mang->getSymbol(MO.getGlobal());
+    break;
=20
-    case MachineOperand::MO_BlockAddress:
-      Symbol =3D AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress());
-      break;
+  case MachineOperand::MO_BlockAddress:
+    Symbol =3D AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress());
+    break;
=20
-    case MachineOperand::MO_ExternalSymbol:
-      Symbol =3D AsmPrinter.GetExternalSymbolSymbol(MO.getSymbolName());
-      break;
+  case MachineOperand::MO_ExternalSymbol:
+    Symbol =3D AsmPrinter.GetExternalSymbolSymbol(MO.getSymbolName());
+    break;
=20
-    case MachineOperand::MO_JumpTableIndex:
-      Symbol =3D AsmPrinter.GetJTISymbol(MO.getIndex());
-      break;
+  case MachineOperand::MO_JumpTableIndex:
+    Symbol =3D AsmPrinter.GetJTISymbol(MO.getIndex());
+    break;
=20
-    case MachineOperand::MO_ConstantPoolIndex:
-      Symbol =3D AsmPrinter.GetCPISymbol(MO.getIndex());
-      if (MO.getOffset())
-        Offset +=3D MO.getOffset(); =20
-      break;
+  case MachineOperand::MO_ConstantPoolIndex:
+    Symbol =3D AsmPrinter.GetCPISymbol(MO.getIndex());
+    if (MO.getOffset())
+      Offset +=3D MO.getOffset();
+    break;
=20
-    default:
-      llvm_unreachable("<unknown operand type>");
+  default:
+    llvm_unreachable("<unknown operand type>");
   }
- =20
-  return MCOperand::CreateExpr(MipsMCSymbolRefExpr::Create(Kind, Symbol, O=
ffset,
-                                                           Ctx));
+
+  const MCSymbolRefExpr *MCSym =3D MCSymbolRefExpr::Create(Symbol, Kind, *=
Ctx);
+
+  if (!Offset)
+    return MCOperand::CreateExpr(MCSym);
+
+  // Assume offset is never negative.
+  assert(Offset > 0);
+
+  const MCConstantExpr *OffsetExpr =3D  MCConstantExpr::Create(Offset, *Ct=
x);
+  const MCBinaryExpr *AddExpr =3D MCBinaryExpr::CreateAdd(MCSym, OffsetExp=
r, *Ctx);
+  return MCOperand::CreateExpr(AddExpr);
 }
=20
-MCOperand MipsMCInstLower::LowerOperand(const MachineOperand& MO) const {
+static void CreateMCInst(MCInst& Inst, unsigned Opc, const MCOperand& Opnd=
0,
+                         const MCOperand& Opnd1,
+                         const MCOperand& Opnd2 =3D MCOperand()) {
+  Inst.setOpcode(Opc);
+  Inst.addOperand(Opnd0);
+  Inst.addOperand(Opnd1);
+  if (Opnd2.isValid())
+    Inst.addOperand(Opnd2);
+}
+
+// Lower ".cpload $reg" to
+//  "lui   $gp, %hi(_gp_disp)"
+//  "addiu $gp, $gp, %lo(_gp_disp)"
+//  "addu  $gp, $gp, $t9"
+void MipsMCInstLower::LowerCPLOAD(SmallVector<MCInst, 4>& MCInsts) {
+  MCOperand GPReg =3D MCOperand::CreateReg(Mips::GP);
+  MCOperand T9Reg =3D MCOperand::CreateReg(Mips::T9);
+  StringRef SymName("_gp_disp");
+  const MCSymbol *Sym =3D Ctx->GetOrCreateSymbol(SymName);
+  const MCSymbolRefExpr *MCSym;
+
+  MCSym =3D MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_Mips_ABS_HI, =
*Ctx);
+  MCOperand SymHi =3D MCOperand::CreateExpr(MCSym);
+  MCSym =3D MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_Mips_ABS_LO, =
*Ctx);
+  MCOperand SymLo =3D MCOperand::CreateExpr(MCSym);
+
+  MCInsts.resize(3);
+
+  CreateMCInst(MCInsts[0], Mips::LUi, GPReg, SymHi);
+  CreateMCInst(MCInsts[1], Mips::ADDiu, GPReg, GPReg, SymLo);
+  CreateMCInst(MCInsts[2], Mips::ADDu, GPReg, GPReg, T9Reg);
+}
+
+// Lower ".cprestore offset" to "sw $gp, offset($sp)".
+void MipsMCInstLower::LowerCPRESTORE(int64_t Offset,
+                                     SmallVector<MCInst, 4>& MCInsts) {
+  assert(isInt<32>(Offset) && (Offset >=3D 0) &&
+         "Imm operand of .cprestore must be a non-negative 32-bit value.");
+
+  MCOperand SPReg =3D MCOperand::CreateReg(Mips::SP), BaseReg =3D SPReg;
+  MCOperand GPReg =3D MCOperand::CreateReg(Mips::GP);
+
+  if (!isInt<16>(Offset)) {
+    unsigned Hi =3D ((Offset + 0x8000) >> 16) & 0xffff;
+    Offset &=3D 0xffff;
+    MCOperand ATReg =3D MCOperand::CreateReg(Mips::AT);
+    BaseReg =3D ATReg;
+
+    // lui   at,hi
+    // addu  at,at,sp
+    MCInsts.resize(2);
+    CreateMCInst(MCInsts[0], Mips::LUi, ATReg, MCOperand::CreateImm(Hi));
+    CreateMCInst(MCInsts[1], Mips::ADDu, ATReg, ATReg, SPReg);
+  }
+
+  MCInst Sw;
+  CreateMCInst(Sw, Mips::SW, GPReg, BaseReg, MCOperand::CreateImm(Offset));
+  MCInsts.push_back(Sw);
+}
+
+MCOperand MipsMCInstLower::LowerOperand(const MachineOperand& MO,
+                                        unsigned offset) const {
   MachineOperandType MOTy =3D MO.getType();
- =20
+
   switch (MOTy) {
-  default:
-    assert(0 && "unknown operand type");
-    break;
+  default: llvm_unreachable("unknown operand type");
   case MachineOperand::MO_Register:
     // Ignore all implicit register operands.
     if (MO.isImplicit()) break;
     return MCOperand::CreateReg(MO.getReg());
   case MachineOperand::MO_Immediate:
-    return MCOperand::CreateImm(MO.getImm());
+    return MCOperand::CreateImm(MO.getImm() + offset);
   case MachineOperand::MO_MachineBasicBlock:
   case MachineOperand::MO_GlobalAddress:
   case MachineOperand::MO_ExternalSymbol:
   case MachineOperand::MO_JumpTableIndex:
   case MachineOperand::MO_ConstantPoolIndex:
   case MachineOperand::MO_BlockAddress:
-    return LowerSymbolOperand(MO, MOTy, 0);
+    return LowerSymbolOperand(MO, MOTy, offset);
+  case MachineOperand::MO_RegisterMask:
+    break;
  }
=20
   return MCOperand();
@@ -115,7 +195,7 @@
=20
 void MipsMCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
   OutMI.setOpcode(MI->getOpcode());
- =20
+
   for (unsigned i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
     const MachineOperand &MO =3D MI->getOperand(i);
     MCOperand MCOp =3D LowerOperand(MO);
@@ -124,3 +204,140 @@
       OutMI.addOperand(MCOp);
   }
 }
+
+void MipsMCInstLower::LowerUnalignedLoadStore(const MachineInstr *MI,
+                                              SmallVector<MCInst,
+                                              4>& MCInsts) {
+  unsigned Opc =3D MI->getOpcode();
+  MCInst Instr1, Instr2, Instr3, Move;
+
+  bool TwoInstructions =3D false;
+
+  assert(MI->getNumOperands() =3D=3D 3);
+  assert(MI->getOperand(0).isReg());
+  assert(MI->getOperand(1).isReg());
+
+  MCOperand Target =3D LowerOperand(MI->getOperand(0));
+  MCOperand Base =3D LowerOperand(MI->getOperand(1));
+  MCOperand ATReg =3D MCOperand::CreateReg(Mips::AT);
+  MCOperand ZeroReg =3D MCOperand::CreateReg(Mips::ZERO);
+
+  MachineOperand UnLoweredName =3D MI->getOperand(2);
+  MCOperand Name =3D LowerOperand(UnLoweredName);
+
+  Move.setOpcode(Mips::ADDu);
+  Move.addOperand(Target);
+  Move.addOperand(ATReg);
+  Move.addOperand(ZeroReg);
+
+  switch (Opc) {
+  case Mips::ULW: {
+    // FIXME: only works for little endian right now
+    MCOperand AdjName =3D LowerOperand(UnLoweredName, 3);
+    if (Base.getReg() =3D=3D (Target.getReg())) {
+      Instr1.setOpcode(Mips::LWL);
+      Instr1.addOperand(ATReg);
+      Instr1.addOperand(Base);
+      Instr1.addOperand(AdjName);
+      Instr2.setOpcode(Mips::LWR);
+      Instr2.addOperand(ATReg);
+      Instr2.addOperand(Base);
+      Instr2.addOperand(Name);
+      Instr3 =3D Move;
+    } else {
+      TwoInstructions =3D true;
+      Instr1.setOpcode(Mips::LWL);
+      Instr1.addOperand(Target);
+      Instr1.addOperand(Base);
+      Instr1.addOperand(AdjName);
+      Instr2.setOpcode(Mips::LWR);
+      Instr2.addOperand(Target);
+      Instr2.addOperand(Base);
+      Instr2.addOperand(Name);
+    }
+    break;
+  }
+  case Mips::ULHu: {
+    // FIXME: only works for little endian right now
+    MCOperand AdjName =3D LowerOperand(UnLoweredName, 1);
+    Instr1.setOpcode(Mips::LBu);
+    Instr1.addOperand(ATReg);
+    Instr1.addOperand(Base);
+    Instr1.addOperand(AdjName);
+    Instr2.setOpcode(Mips::LBu);
+    Instr2.addOperand(Target);
+    Instr2.addOperand(Base);
+    Instr2.addOperand(Name);
+    Instr3.setOpcode(Mips::INS);
+    Instr3.addOperand(Target);
+    Instr3.addOperand(ATReg);
+    Instr3.addOperand(MCOperand::CreateImm(0x8));
+    Instr3.addOperand(MCOperand::CreateImm(0x18));
+    break;
+  }
+
+  case Mips::USW: {
+    // FIXME: only works for little endian right now
+    assert (Base.getReg() !=3D Target.getReg());
+    TwoInstructions =3D true;
+    MCOperand AdjName =3D LowerOperand(UnLoweredName, 3);
+    Instr1.setOpcode(Mips::SWL);
+    Instr1.addOperand(Target);
+    Instr1.addOperand(Base);
+    Instr1.addOperand(AdjName);
+    Instr2.setOpcode(Mips::SWR);
+    Instr2.addOperand(Target);
+    Instr2.addOperand(Base);
+    Instr2.addOperand(Name);
+    break;
+  }
+  case Mips::USH: {
+    MCOperand AdjName =3D LowerOperand(UnLoweredName, 1);
+    Instr1.setOpcode(Mips::SB);
+    Instr1.addOperand(Target);
+    Instr1.addOperand(Base);
+    Instr1.addOperand(Name);
+    Instr2.setOpcode(Mips::SRL);
+    Instr2.addOperand(ATReg);
+    Instr2.addOperand(Target);
+    Instr2.addOperand(MCOperand::CreateImm(8));
+    Instr3.setOpcode(Mips::SB);
+    Instr3.addOperand(ATReg);
+    Instr3.addOperand(Base);
+    Instr3.addOperand(AdjName);
+    break;
+  }
+  default:
+    // FIXME: need to add others
+    llvm_unreachable("unaligned instruction not processed");
+  }
+
+  MCInsts.push_back(Instr1);
+  MCInsts.push_back(Instr2);
+  if (!TwoInstructions) MCInsts.push_back(Instr3);
+}
+
+// Convert
+//  "setgp01 $reg"
+// to
+//  "lui   $reg, %hi(_gp_disp)"
+//  "addiu $reg, $reg, %lo(_gp_disp)"
+void MipsMCInstLower::LowerSETGP01(const MachineInstr *MI,
+                                   SmallVector<MCInst, 4>& MCInsts) {
+  const MachineOperand &MO =3D MI->getOperand(0);
+  assert(MO.isReg());
+  MCOperand RegOpnd =3D MCOperand::CreateReg(MO.getReg());
+  StringRef SymName("_gp_disp");
+  const MCSymbol *Sym =3D Ctx->GetOrCreateSymbol(SymName);
+  const MCSymbolRefExpr *MCSym;
+
+  MCSym =3D MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_Mips_ABS_HI, =
*Ctx);
+  MCOperand SymHi =3D MCOperand::CreateExpr(MCSym);
+  MCSym =3D MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_Mips_ABS_LO, =
*Ctx);
+  MCOperand SymLo =3D MCOperand::CreateExpr(MCSym);
+
+  MCInsts.resize(2);
+
+  CreateMCInst(MCInsts[0], Mips::LUi, RegOpnd, SymHi);
+  CreateMCInst(MCInsts[1], Mips::ADDiu, RegOpnd, RegOpnd, SymLo);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
MCInstLower.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsMCInstLower.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsMCInstLower.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsMCInstLower.h - Lower MachineInstr to MCInst -----------=
--------=3D=3D//
+//=3D=3D=3D-- MipsMCInstLower.h - Lower MachineInstr to MCInst -------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -9,35 +9,39 @@
=20
 #ifndef MIPSMCINSTLOWER_H
 #define MIPSMCINSTLOWER_H
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/CodeGen/MachineOperand.h"
 #include "llvm/Support/Compiler.h"
=20
 namespace llvm {
-  class MCAsmInfo;
   class MCContext;
   class MCInst;
   class MCOperand;
-  class MCSymbol;
   class MachineInstr;
   class MachineFunction;
   class Mangler;
   class MipsAsmPrinter;
- =20
+
 /// MipsMCInstLower - This class is used to lower an MachineInstr into an
 //                    MCInst.
 class LLVM_LIBRARY_VISIBILITY MipsMCInstLower {
   typedef MachineOperand::MachineOperandType MachineOperandType;
-  MCContext &Ctx;
+  MCContext *Ctx;
   Mangler *Mang;
   MipsAsmPrinter &AsmPrinter;
 public:
-  MipsMCInstLower(Mangler *mang, const MachineFunction &MF,
-                  MipsAsmPrinter &asmprinter); =20
+  MipsMCInstLower(MipsAsmPrinter &asmprinter);
+  void Initialize(Mangler *mang, MCContext* C);
   void Lower(const MachineInstr *MI, MCInst &OutMI) const;
+  void LowerCPLOAD(SmallVector<MCInst, 4>& MCInsts);
+  void LowerCPRESTORE(int64_t Offset, SmallVector<MCInst, 4>& MCInsts);
+  void LowerUnalignedLoadStore(const MachineInstr *MI,
+                               SmallVector<MCInst, 4>& MCInsts);
+  void LowerSETGP01(const MachineInstr *MI, SmallVector<MCInst, 4>& MCInst=
s);
 private:
   MCOperand LowerSymbolOperand(const MachineOperand &MO,
                                MachineOperandType MOTy, unsigned Offset) c=
onst;
-  MCOperand LowerOperand(const MachineOperand& MO) const;
+  MCOperand LowerOperand(const MachineOperand& MO, unsigned offset =3D 0) =
const;
 };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
MachineFunction.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsMachineFunction.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsMachineFunction.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -14,19 +14,17 @@
 #ifndef MIPS_MACHINE_FUNCTION_INFO_H
 #define MIPS_MACHINE_FUNCTION_INFO_H
=20
-#include <utility>
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/VectorExtras.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
+#include <utility>
=20
 namespace llvm {
=20
 /// MipsFunctionInfo - This class is derived from MachineFunction private
 /// Mips target-specific information for each MachineFunction.
 class MipsFunctionInfo : public MachineFunctionInfo {
+  virtual void anchor();
=20
-private:
   MachineFunction& MF;
   /// SRetReturnReg - Some subtargets require that sret lowering includes
   /// returning the value of the returned struct in a register. This field
@@ -45,18 +43,20 @@
   // InArgFIRange: Range of indices of all frame objects created during ca=
ll to
   //               LowerFormalArguments.
   // OutArgFIRange: Range of indices of all frame objects created during c=
all to
-  //                LowerCall except for the frame object for restoring $g=
p.=20
+  //                LowerCall except for the frame object for restoring $g=
p.
   std::pair<int, int> InArgFIRange, OutArgFIRange;
-  int GPFI; // Index of the frame object for restoring $gp=20
-  mutable int DynAllocFI; // Frame index of dynamically allocated stack ar=
ea.  =20
+  int GPFI; // Index of the frame object for restoring $gp
+  mutable int DynAllocFI; // Frame index of dynamically allocated stack ar=
ea.
   unsigned MaxCallFrameSize;
=20
+  bool EmitNOAT;
+
 public:
   MipsFunctionInfo(MachineFunction& MF)
   : MF(MF), SRetReturnReg(0), GlobalBaseReg(0),
     VarArgsFrameIndex(0), InArgFIRange(std::make_pair(-1, 0)),
     OutArgFIRange(std::make_pair(-1, 0)), GPFI(0), DynAllocFI(0),
-    MaxCallFrameSize(0)
+    MaxCallFrameSize(0), EmitNOAT(false)
   {}
=20
   bool isInArgFI(int FI) const {
@@ -64,7 +64,7 @@
   }
   void setLastInArgFI(int FI) { InArgFIRange.second =3D FI; }
=20
-  bool isOutArgFI(int FI) const {=20
+  bool isOutArgFI(int FI) const {
     return FI <=3D OutArgFIRange.first && FI >=3D OutArgFIRange.second;
   }
   void extendOutArgFIRange(int FirstFI, int LastFI) {
@@ -92,14 +92,18 @@
   unsigned getSRetReturnReg() const { return SRetReturnReg; }
   void setSRetReturnReg(unsigned Reg) { SRetReturnReg =3D Reg; }
=20
-  unsigned getGlobalBaseReg() const { return GlobalBaseReg; }
-  void setGlobalBaseReg(unsigned Reg) { GlobalBaseReg =3D Reg; }
+  bool globalBaseRegFixed() const;
+  bool globalBaseRegSet() const;
+  unsigned getGlobalBaseReg();
=20
   int getVarArgsFrameIndex() const { return VarArgsFrameIndex; }
   void setVarArgsFrameIndex(int Index) { VarArgsFrameIndex =3D Index; }
=20
   unsigned getMaxCallFrameSize() const { return MaxCallFrameSize; }
   void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize =3D S; }
+
+  bool getEmitNOAT() const { return EmitNOAT; }
+  void setEmitNOAT() { EmitNOAT =3D true; }
 };
=20
 } // end of namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
RegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsRegisterInfo.cpp - MIPS Register Information -=3D=3D ----=
-*- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsRegisterInfo.cpp - MIPS Register Information -=3D=3D ---=
-----------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,9 +13,10 @@
=20
 #define DEBUG_TYPE "mips-reg-info"
=20
+#include "MipsRegisterInfo.h"
 #include "Mips.h"
+#include "MipsAnalyzeImmediate.h"
 #include "MipsSubtarget.h"
-#include "MipsRegisterInfo.h"
 #include "MipsMachineFunction.h"
 #include "llvm/Constants.h"
 #include "llvm/Type.h"
@@ -45,97 +46,6 @@
                                    const TargetInstrInfo &tii)
   : MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}
=20
-/// getRegisterNumbering - Given the enum value for some register, e.g.
-/// Mips::RA, return the number that it corresponds to (e.g. 31).
-unsigned MipsRegisterInfo::
-getRegisterNumbering(unsigned RegEnum)
-{
-  switch (RegEnum) {
-  case Mips::ZERO: case Mips::ZERO_64: case Mips::F0: case Mips::D0_64:
-  case Mips::D0:
-    return 0;
-  case Mips::AT: case Mips::AT_64: case Mips::F1: case Mips::D1_64:
-    return 1;
-  case Mips::V0: case Mips::V0_64: case Mips::F2: case Mips::D2_64:
-  case Mips::D1:
-    return 2;
-  case Mips::V1: case Mips::V1_64: case Mips::F3: case Mips::D3_64:
-    return 3;
-  case Mips::A0: case Mips::A0_64: case Mips::F4: case Mips::D4_64:
-  case Mips::D2:
-    return 4;
-  case Mips::A1: case Mips::A1_64: case Mips::F5: case Mips::D5_64:
-    return 5;
-  case Mips::A2: case Mips::A2_64: case Mips::F6: case Mips::D6_64:
-  case Mips::D3:
-    return 6;
-  case Mips::A3: case Mips::A3_64: case Mips::F7: case Mips::D7_64:
-    return 7;
-  case Mips::T0: case Mips::T0_64: case Mips::F8: case Mips::D8_64:
-  case Mips::D4:
-    return 8;
-  case Mips::T1: case Mips::T1_64: case Mips::F9: case Mips::D9_64:
-    return 9;
-  case Mips::T2: case Mips::T2_64: case Mips::F10: case Mips::D10_64:
-  case Mips::D5:
-    return 10;
-  case Mips::T3: case Mips::T3_64: case Mips::F11: case Mips::D11_64:
-    return 11;
-  case Mips::T4: case Mips::T4_64: case Mips::F12: case Mips::D12_64:
-  case Mips::D6:
-    return 12;
-  case Mips::T5: case Mips::T5_64: case Mips::F13: case Mips::D13_64:
-    return 13;
-  case Mips::T6: case Mips::T6_64: case Mips::F14: case Mips::D14_64:
-  case Mips::D7:
-    return 14;
-  case Mips::T7: case Mips::T7_64: case Mips::F15: case Mips::D15_64:
-    return 15;
-  case Mips::S0: case Mips::S0_64: case Mips::F16: case Mips::D16_64:
-  case Mips::D8:
-    return 16;
-  case Mips::S1: case Mips::S1_64: case Mips::F17: case Mips::D17_64:
-    return 17;
-  case Mips::S2: case Mips::S2_64: case Mips::F18: case Mips::D18_64:
-  case Mips::D9:
-    return 18;
-  case Mips::S3: case Mips::S3_64: case Mips::F19: case Mips::D19_64:
-    return 19;
-  case Mips::S4: case Mips::S4_64: case Mips::F20: case Mips::D20_64:
-  case Mips::D10:
-    return 20;
-  case Mips::S5: case Mips::S5_64: case Mips::F21: case Mips::D21_64:
-    return 21;
-  case Mips::S6: case Mips::S6_64: case Mips::F22: case Mips::D22_64:
-  case Mips::D11:
-    return 22;
-  case Mips::S7: case Mips::S7_64: case Mips::F23: case Mips::D23_64:
-    return 23;
-  case Mips::T8: case Mips::T8_64: case Mips::F24: case Mips::D24_64:
-  case Mips::D12:
-    return 24;
-  case Mips::T9: case Mips::T9_64: case Mips::F25: case Mips::D25_64:
-    return 25;
-  case Mips::K0: case Mips::K0_64: case Mips::F26: case Mips::D26_64:
-  case Mips::D13:
-    return 26;
-  case Mips::K1: case Mips::K1_64: case Mips::F27: case Mips::D27_64:
-    return 27;
-  case Mips::GP: case Mips::GP_64: case Mips::F28: case Mips::D28_64:
-  case Mips::D14:
-    return 28;
-  case Mips::SP: case Mips::SP_64: case Mips::F29: case Mips::D29_64:
-    return 29;
-  case Mips::FP: case Mips::FP_64: case Mips::F30: case Mips::D30_64:
-  case Mips::D15:=20
-    return 30;
-  case Mips::RA: case Mips::RA_64: case Mips::F31: case Mips::D31_64:
-    return 31;
-  default: llvm_unreachable("Unknown register number!");
-  }
-  return 0; // Not reached
-}
-
 unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -143,71 +53,55 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 /// Mips Callee Saved Registers
-const unsigned* MipsRegisterInfo::
+const uint16_t* MipsRegisterInfo::
 getCalleeSavedRegs(const MachineFunction *MF) const
 {
-  // Mips callee-save register range is $16-$23, $f20-$f30
-  static const unsigned SingleFloatOnlyCalleeSavedRegs[] =3D {
-    Mips::F31, Mips::F30, Mips::F29, Mips::F28, Mips::F27, Mips::F26,
-    Mips::F25, Mips::F24, Mips::F23, Mips::F22, Mips::F21, Mips::F20,
-    Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
-    Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
-  };
+  if (Subtarget.isSingleFloat())
+    return CSR_SingleFloatOnly_SaveList;
+  else if (!Subtarget.hasMips64())
+    return CSR_O32_SaveList;
+  else if (Subtarget.isABI_N32())
+    return CSR_N32_SaveList;
=20
-  static const unsigned Mips32CalleeSavedRegs[] =3D {
-    Mips::D15, Mips::D14, Mips::D13, Mips::D12, Mips::D11, Mips::D10,
-    Mips::RA, Mips::FP, Mips::S7, Mips::S6, Mips::S5, Mips::S4,
-    Mips::S3, Mips::S2, Mips::S1, Mips::S0, 0
-  };
+  assert(Subtarget.isABI_N64());
+  return CSR_N64_SaveList; =20
+}
=20
-  static const unsigned N32CalleeSavedRegs[] =3D {
-    Mips::D31_64, Mips::D29_64, Mips::D27_64, Mips::D25_64, Mips::D23_64,
-    Mips::D21_64,
-    Mips::RA_64, Mips::FP_64, Mips::GP_64, Mips::S7_64, Mips::S6_64,
-    Mips::S5_64, Mips::S4_64, Mips::S3_64, Mips::S2_64, Mips::S1_64,
-    Mips::S0_64, 0
-  };
+const uint32_t*
+MipsRegisterInfo::getCallPreservedMask(CallingConv::ID) const
+{ =20
+  if (Subtarget.isSingleFloat())
+    return CSR_SingleFloatOnly_RegMask;
+  else if (!Subtarget.hasMips64())
+    return CSR_O32_RegMask;
+  else if (Subtarget.isABI_N32())
+    return CSR_N32_RegMask;
=20
-  static const unsigned N64CalleeSavedRegs[] =3D {
-    Mips::D31_64, Mips::D30_64, Mips::D29_64, Mips::D28_64, Mips::D27_64,
-    Mips::D26_64, Mips::D25_64, Mips::D24_64,
-    Mips::RA_64, Mips::FP_64, Mips::GP_64, Mips::S7_64, Mips::S6_64,
-    Mips::S5_64, Mips::S4_64, Mips::S3_64, Mips::S2_64, Mips::S1_64,
-    Mips::S0_64, 0
-  };
-
-  if (Subtarget.isSingleFloat())
-    return SingleFloatOnlyCalleeSavedRegs;
-  else if (!Subtarget.hasMips64())
-    return Mips32CalleeSavedRegs;
-  else if (Subtarget.isABI_N32())
-    return N32CalleeSavedRegs;
- =20
   assert(Subtarget.isABI_N64());
-  return N64CalleeSavedRegs; =20
+  return CSR_N64_RegMask; =20
 }
=20
 BitVector MipsRegisterInfo::
 getReservedRegs(const MachineFunction &MF) const {
-  static const unsigned ReservedCPURegs[] =3D {
-    Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,=20
-    Mips::GP, Mips::SP, Mips::FP, Mips::RA, 0
+  static const uint16_t ReservedCPURegs[] =3D {
+    Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,
+    Mips::SP, Mips::FP, Mips::RA
   };
=20
-  static const unsigned ReservedCPU64Regs[] =3D {
-    Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,=20
-    Mips::GP_64, Mips::SP_64, Mips::FP_64, Mips::RA_64, 0
+  static const uint16_t ReservedCPU64Regs[] =3D {
+    Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,
+    Mips::SP_64, Mips::FP_64, Mips::RA_64
   };
=20
   BitVector Reserved(getNumRegs());
   typedef TargetRegisterClass::iterator RegIter;
=20
-  for (const unsigned *Reg =3D ReservedCPURegs; *Reg; ++Reg)
-    Reserved.set(*Reg);
+  for (unsigned I =3D 0; I < array_lengthof(ReservedCPURegs); ++I)
+    Reserved.set(ReservedCPURegs[I]);
=20
   if (Subtarget.hasMips64()) {
-    for (const unsigned *Reg =3D ReservedCPU64Regs; *Reg; ++Reg)
-      Reserved.set(*Reg);
+    for (unsigned I =3D 0; I < array_lengthof(ReservedCPU64Regs); ++I)
+      Reserved.set(ReservedCPU64Regs[I]);
=20
     // Reserve all registers in AFGR64.
     for (RegIter Reg =3D Mips::AFGR64RegisterClass->begin();
@@ -224,10 +118,25 @@
          Reg !=3D Mips::FGR64RegisterClass->end(); ++Reg)
       Reserved.set(*Reg);
   }
- =20
+
+  // If GP is dedicated as a global base register, reserve it.
+  if (MF.getInfo<MipsFunctionInfo>()->globalBaseRegFixed()) {
+    Reserved.set(Mips::GP);
+    Reserved.set(Mips::GP_64);
+  }
+
+  // Reserve hardware registers.
+  Reserved.set(Mips::HWR29);
+  Reserved.set(Mips::HWR29_64);
+
   return Reserved;
 }
=20
+bool
+MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) co=
nst {
+  return true;
+}
+
 // This function eliminate ADJCALLSTACKDOWN,
 // ADJCALLSTACKUP pseudo instructions
 void MipsRegisterInfo::
@@ -259,8 +168,8 @@
         errs() << "<--------->\n" << MI);
=20
   int FrameIndex =3D MI.getOperand(i).getIndex();
-  int stackSize  =3D MF.getFrameInfo()->getStackSize();
-  int spOffset   =3D MF.getFrameInfo()->getObjectOffset(FrameIndex);
+  uint64_t stackSize =3D MF.getFrameInfo()->getStackSize();
+  int64_t spOffset =3D MF.getFrameInfo()->getObjectOffset(FrameIndex);
=20
   DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
                << "spOffset   : " << spOffset << "\n"
@@ -279,52 +188,71 @@
   //  1. Outgoing arguments.
   //  2. Pointer to dynamically allocated stack space.
   //  3. Locations for callee-saved registers.
-  // Everything else is referenced relative to whatever register=20
+  // Everything else is referenced relative to whatever register
   // getFrameRegister() returns.
   unsigned FrameReg;
=20
   if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
       (FrameIndex >=3D MinCSFI && FrameIndex <=3D MaxCSFI))
-    FrameReg =3D Mips::SP;
+    FrameReg =3D Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP;
   else
-    FrameReg =3D getFrameRegister(MF);=20
- =20
+    FrameReg =3D getFrameRegister(MF);
+
   // Calculate final offset.
   // - There is no need to change the offset if the frame object is one of=
 the
   //   following: an outgoing argument, pointer to a dynamically allocated
   //   stack space or a $gp restore location,
   // - If the frame object is any of the following, its offset must be adj=
usted
   //   by adding the size of the stack:
-  //   incoming argument, callee-saved register location or local variable=
. =20
-  int Offset;
+  //   incoming argument, callee-saved register location or local variable.
+  int64_t Offset;
=20
   if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
       MipsFI->isDynAllocFI(FrameIndex))
     Offset =3D spOffset;
   else
-    Offset =3D spOffset + stackSize;
+    Offset =3D spOffset + (int64_t)stackSize;
=20
   Offset    +=3D MI.getOperand(i+1).getImm();
=20
   DEBUG(errs() << "Offset     : " << Offset << "\n" << "<--------->\n");
=20
   // If MI is not a debug value, make sure Offset fits in the 16-bit immed=
iate
-  // field.=20
-  if (!MI.isDebugValue() && (Offset >=3D 0x8000 || Offset < -0x8000)) {
+  // field.
+  if (!MI.isDebugValue() && !isInt<16>(Offset)) {
     MachineBasicBlock &MBB =3D *MI.getParent();
     DebugLoc DL =3D II->getDebugLoc();
-    int ImmHi =3D (((unsigned)Offset & 0xffff0000) >> 16) +
-                ((Offset & 0x8000) !=3D 0);
+    MipsAnalyzeImmediate AnalyzeImm;
+    unsigned Size =3D Subtarget.isABI_N64() ? 64 : 32;
+    unsigned LUi =3D Subtarget.isABI_N64() ? Mips::LUi64 : Mips::LUi;
+    unsigned ADDu =3D Subtarget.isABI_N64() ? Mips::DADDu : Mips::ADDu;
+    unsigned ZEROReg =3D Subtarget.isABI_N64() ? Mips::ZERO_64 : Mips::ZER=
O;
+    unsigned ATReg =3D Subtarget.isABI_N64() ? Mips::AT_64 : Mips::AT;
+    const MipsAnalyzeImmediate::InstSeq &Seq =3D
+      AnalyzeImm.Analyze(Offset, Size, true /* LastInstrIsADDiu */);
+    MipsAnalyzeImmediate::InstSeq::const_iterator Inst =3D Seq.begin();
=20
-    // FIXME: change this when mips goes MC".
-    BuildMI(MBB, II, DL, TII.get(Mips::NOAT));
-    BuildMI(MBB, II, DL, TII.get(Mips::LUi), Mips::AT).addImm(ImmHi);
-    BuildMI(MBB, II, DL, TII.get(Mips::ADDu), Mips::AT).addReg(FrameReg)
-                                                       .addReg(Mips::AT);
-    FrameReg =3D Mips::AT;
-    Offset =3D (short)(Offset & 0xffff);
+    MipsFI->setEmitNOAT();
=20
-    BuildMI(MBB, ++II, MI.getDebugLoc(), TII.get(Mips::ATMACRO));
+    // The first instruction can be a LUi, which is different from other
+    // instructions (ADDiu, ORI and SLL) in that it does not have a regist=
er
+    // operand.
+    if (Inst->Opc =3D=3D LUi)
+      BuildMI(MBB, II, DL, TII.get(LUi), ATReg)
+        .addImm(SignExtend64<16>(Inst->ImmOpnd));
+    else
+      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ZEROReg)
+        .addImm(SignExtend64<16>(Inst->ImmOpnd));
+
+    // Build the remaining instructions in Seq except for the last one.
+    for (++Inst; Inst !=3D Seq.end() - 1; ++Inst)
+      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ATReg)
+        .addImm(SignExtend64<16>(Inst->ImmOpnd));
+
+    BuildMI(MBB, II, DL, TII.get(ADDu), ATReg).addReg(FrameReg).addReg(ATR=
eg);
+
+    FrameReg =3D ATReg;
+    Offset =3D SignExtend64<16>(Inst->ImmOpnd);
   }
=20
   MI.getOperand(i).ChangeToRegister(FrameReg, false);
@@ -334,18 +262,18 @@
 unsigned MipsRegisterInfo::
 getFrameRegister(const MachineFunction &MF) const {
   const TargetFrameLowering *TFI =3D MF.getTarget().getFrameLowering();
+  bool IsN64 =3D Subtarget.isABI_N64();
=20
-  return TFI->hasFP(MF) ? Mips::FP : Mips::SP;
+  return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
+                          (IsN64 ? Mips::SP_64 : Mips::SP);
 }
=20
 unsigned MipsRegisterInfo::
 getEHExceptionRegister() const {
   llvm_unreachable("What is the exception register");
-  return 0;
 }
=20
 unsigned MipsRegisterInfo::
 getEHHandlerRegister() const {
   llvm_unreachable("What is the exception handler register");
-  return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
RegisterInfo.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsRegisterInfo.h - Mips Register Information Impl ------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsRegisterInfo.h - Mips Register Information Impl -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -42,10 +42,13 @@
   void adjustMipsStackFrame(MachineFunction &MF) const;
=20
   /// Code Generation virtual methods...
-  const unsigned *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
+  const uint32_t *getCallPreservedMask(CallingConv::ID) const;
=20
   BitVector getReservedRegs(const MachineFunction &MF) const;
=20
+  virtual bool requiresRegisterScavenging(const MachineFunction &MF) const;
+
   void eliminateCallFramePseudoInstr(MachineFunction &MF,
                                      MachineBasicBlock &MBB,
                                      MachineBasicBlock::iterator I) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
RegisterInfo.td
--- a/head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsRegisterInfo.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsRegisterInfo.td - Mips Register defs ------------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsRegisterInfo.td - Mips Register defs -----------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -50,6 +50,7 @@
   : MipsRegWithSubRegs<n, subregs> {
   let Num =3D num;
   let SubRegIndices =3D [sub_fpeven, sub_fpodd];
+  let CoveredBySubRegs =3D 1;
 }
=20
 class AFPR64<bits<5> num, string n, list<Register> subregs>
@@ -68,8 +69,6 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 let Namespace =3D "Mips" in {
-  // FIXME: Fix DwarfRegNum.
-
   // General Purpose Registers
   def ZERO : MipsGPRReg< 0, "ZERO">, DwarfRegNum<[0]>;
   def AT   : MipsGPRReg< 1, "AT">,   DwarfRegNum<[1]>;
@@ -105,38 +104,38 @@
   def RA   : MipsGPRReg< 31, "RA">,  DwarfRegNum<[31]>;
=20
   // General Purpose 64-bit Registers
-  def ZERO_64 : Mips64GPRReg< 0, "ZERO", [ZERO]>;
-  def AT_64   : Mips64GPRReg< 1, "AT",   [AT]>;
-  def V0_64   : Mips64GPRReg< 2, "2",    [V0]>;
-  def V1_64   : Mips64GPRReg< 3, "3",    [V1]>;
-  def A0_64   : Mips64GPRReg< 4, "4",    [A0]>;
-  def A1_64   : Mips64GPRReg< 5, "5",    [A1]>;
-  def A2_64   : Mips64GPRReg< 6, "6",    [A2]>;
-  def A3_64   : Mips64GPRReg< 7, "7",    [A3]>;
-  def T0_64   : Mips64GPRReg< 8, "8",    [T0]>;
-  def T1_64   : Mips64GPRReg< 9, "9",    [T1]>;
-  def T2_64   : Mips64GPRReg< 10, "10",  [T2]>;  =20
-  def T3_64   : Mips64GPRReg< 11, "11",  [T3]>;  =20
-  def T4_64   : Mips64GPRReg< 12, "12",  [T4]>;  =20
-  def T5_64   : Mips64GPRReg< 13, "13",  [T5]>;  =20
-  def T6_64   : Mips64GPRReg< 14, "14",  [T6]>;  =20
-  def T7_64   : Mips64GPRReg< 15, "15",  [T7]>;  =20
-  def S0_64   : Mips64GPRReg< 16, "16",  [S0]>;  =20
-  def S1_64   : Mips64GPRReg< 17, "17",  [S1]>;  =20
-  def S2_64   : Mips64GPRReg< 18, "18",  [S2]>;  =20
-  def S3_64   : Mips64GPRReg< 19, "19",  [S3]>;  =20
-  def S4_64   : Mips64GPRReg< 20, "20",  [S4]>;  =20
-  def S5_64   : Mips64GPRReg< 21, "21",  [S5]>;  =20
-  def S6_64   : Mips64GPRReg< 22, "22",  [S6]>;  =20
-  def S7_64   : Mips64GPRReg< 23, "23",  [S7]>;
-  def T8_64   : Mips64GPRReg< 24, "24",  [T8]>;
-  def T9_64   : Mips64GPRReg< 25, "25",  [T9]>;
-  def K0_64   : Mips64GPRReg< 26, "26",  [K0]>;
-  def K1_64   : Mips64GPRReg< 27, "27",  [K1]>;
-  def GP_64   : Mips64GPRReg< 28, "GP",  [GP]>;
-  def SP_64   : Mips64GPRReg< 29, "SP",  [SP]>;
-  def FP_64   : Mips64GPRReg< 30, "FP",  [FP]>;
-  def RA_64   : Mips64GPRReg< 31, "RA",  [RA]>;
+  def ZERO_64 : Mips64GPRReg< 0, "ZERO", [ZERO]>, DwarfRegNum<[0]>;
+  def AT_64   : Mips64GPRReg< 1, "AT",   [AT]>, DwarfRegNum<[1]>;
+  def V0_64   : Mips64GPRReg< 2, "2",    [V0]>, DwarfRegNum<[2]>;
+  def V1_64   : Mips64GPRReg< 3, "3",    [V1]>, DwarfRegNum<[3]>;
+  def A0_64   : Mips64GPRReg< 4, "4",    [A0]>, DwarfRegNum<[4]>;
+  def A1_64   : Mips64GPRReg< 5, "5",    [A1]>, DwarfRegNum<[5]>;
+  def A2_64   : Mips64GPRReg< 6, "6",    [A2]>, DwarfRegNum<[6]>;
+  def A3_64   : Mips64GPRReg< 7, "7",    [A3]>, DwarfRegNum<[7]>;
+  def T0_64   : Mips64GPRReg< 8, "8",    [T0]>, DwarfRegNum<[8]>;
+  def T1_64   : Mips64GPRReg< 9, "9",    [T1]>, DwarfRegNum<[9]>;
+  def T2_64   : Mips64GPRReg< 10, "10",  [T2]>, DwarfRegNum<[10]>;
+  def T3_64   : Mips64GPRReg< 11, "11",  [T3]>, DwarfRegNum<[11]>;
+  def T4_64   : Mips64GPRReg< 12, "12",  [T4]>, DwarfRegNum<[12]>;
+  def T5_64   : Mips64GPRReg< 13, "13",  [T5]>, DwarfRegNum<[13]>;
+  def T6_64   : Mips64GPRReg< 14, "14",  [T6]>, DwarfRegNum<[14]>;
+  def T7_64   : Mips64GPRReg< 15, "15",  [T7]>, DwarfRegNum<[15]>;
+  def S0_64   : Mips64GPRReg< 16, "16",  [S0]>, DwarfRegNum<[16]>;
+  def S1_64   : Mips64GPRReg< 17, "17",  [S1]>, DwarfRegNum<[17]>;
+  def S2_64   : Mips64GPRReg< 18, "18",  [S2]>, DwarfRegNum<[18]>;
+  def S3_64   : Mips64GPRReg< 19, "19",  [S3]>, DwarfRegNum<[19]>;
+  def S4_64   : Mips64GPRReg< 20, "20",  [S4]>, DwarfRegNum<[20]>;
+  def S5_64   : Mips64GPRReg< 21, "21",  [S5]>, DwarfRegNum<[21]>;
+  def S6_64   : Mips64GPRReg< 22, "22",  [S6]>, DwarfRegNum<[22]>;
+  def S7_64   : Mips64GPRReg< 23, "23",  [S7]>, DwarfRegNum<[23]>;
+  def T8_64   : Mips64GPRReg< 24, "24",  [T8]>, DwarfRegNum<[24]>;
+  def T9_64   : Mips64GPRReg< 25, "25",  [T9]>, DwarfRegNum<[25]>;
+  def K0_64   : Mips64GPRReg< 26, "26",  [K0]>, DwarfRegNum<[26]>;
+  def K1_64   : Mips64GPRReg< 27, "27",  [K1]>, DwarfRegNum<[27]>;
+  def GP_64   : Mips64GPRReg< 28, "GP",  [GP]>, DwarfRegNum<[28]>;
+  def SP_64   : Mips64GPRReg< 29, "SP",  [SP]>, DwarfRegNum<[29]>;
+  def FP_64   : Mips64GPRReg< 30, "FP",  [FP]>, DwarfRegNum<[30]>;
+  def RA_64   : Mips64GPRReg< 31, "RA",  [RA]>, DwarfRegNum<[31]>;
=20
   /// Mips Single point precision FPU Registers
   def F0  : FPR< 0,  "F0">, DwarfRegNum<[32]>;
@@ -192,38 +191,38 @@
   def D15 : AFPR<30, "F30", [F30, F31]>;
=20
   /// Mips Double point precision FPU Registers in MFP64 mode.
-  def D0_64  : AFPR64<0, "F0", [F0]>;
-  def D1_64  : AFPR64<1, "F1", [F1]>;
-  def D2_64  : AFPR64<2, "F2", [F2]>;
-  def D3_64  : AFPR64<3, "F3", [F3]>;
-  def D4_64  : AFPR64<4, "F4", [F4]>;
-  def D5_64  : AFPR64<5, "F5", [F5]>;
-  def D6_64  : AFPR64<6, "F6", [F6]>;
-  def D7_64  : AFPR64<7, "F7", [F7]>;
-  def D8_64  : AFPR64<8, "F8", [F8]>;
-  def D9_64  : AFPR64<9, "F9", [F9]>;
-  def D10_64  : AFPR64<10, "F10", [F10]>;
-  def D11_64  : AFPR64<11, "F11", [F11]>;
-  def D12_64  : AFPR64<12, "F12", [F12]>;
-  def D13_64  : AFPR64<13, "F13", [F13]>;
-  def D14_64  : AFPR64<14, "F14", [F14]>;
-  def D15_64  : AFPR64<15, "F15", [F15]>;
-  def D16_64  : AFPR64<16, "F16", [F16]>;
-  def D17_64  : AFPR64<17, "F17", [F17]>;
-  def D18_64  : AFPR64<18, "F18", [F18]>;
-  def D19_64  : AFPR64<19, "F19", [F19]>;
-  def D20_64  : AFPR64<20, "F20", [F20]>;
-  def D21_64  : AFPR64<21, "F21", [F21]>;
-  def D22_64  : AFPR64<22, "F22", [F22]>;
-  def D23_64  : AFPR64<23, "F23", [F23]>;
-  def D24_64  : AFPR64<24, "F24", [F24]>;
-  def D25_64  : AFPR64<25, "F25", [F25]>;
-  def D26_64  : AFPR64<26, "F26", [F26]>;
-  def D27_64  : AFPR64<27, "F27", [F27]>;
-  def D28_64  : AFPR64<28, "F28", [F28]>;
-  def D29_64  : AFPR64<29, "F29", [F29]>;
-  def D30_64  : AFPR64<30, "F30", [F30]>;
-  def D31_64  : AFPR64<31, "F31", [F31]>;
+  def D0_64  : AFPR64<0, "F0", [F0]>, DwarfRegNum<[32]>;
+  def D1_64  : AFPR64<1, "F1", [F1]>, DwarfRegNum<[33]>;
+  def D2_64  : AFPR64<2, "F2", [F2]>, DwarfRegNum<[34]>;
+  def D3_64  : AFPR64<3, "F3", [F3]>, DwarfRegNum<[35]>;
+  def D4_64  : AFPR64<4, "F4", [F4]>, DwarfRegNum<[36]>;
+  def D5_64  : AFPR64<5, "F5", [F5]>, DwarfRegNum<[37]>;
+  def D6_64  : AFPR64<6, "F6", [F6]>, DwarfRegNum<[38]>;
+  def D7_64  : AFPR64<7, "F7", [F7]>, DwarfRegNum<[39]>;
+  def D8_64  : AFPR64<8, "F8", [F8]>, DwarfRegNum<[40]>;
+  def D9_64  : AFPR64<9, "F9", [F9]>, DwarfRegNum<[41]>;
+  def D10_64  : AFPR64<10, "F10", [F10]>, DwarfRegNum<[42]>;
+  def D11_64  : AFPR64<11, "F11", [F11]>, DwarfRegNum<[43]>;
+  def D12_64  : AFPR64<12, "F12", [F12]>, DwarfRegNum<[44]>;
+  def D13_64  : AFPR64<13, "F13", [F13]>, DwarfRegNum<[45]>;
+  def D14_64  : AFPR64<14, "F14", [F14]>, DwarfRegNum<[46]>;
+  def D15_64  : AFPR64<15, "F15", [F15]>, DwarfRegNum<[47]>;
+  def D16_64  : AFPR64<16, "F16", [F16]>, DwarfRegNum<[48]>;
+  def D17_64  : AFPR64<17, "F17", [F17]>, DwarfRegNum<[49]>;
+  def D18_64  : AFPR64<18, "F18", [F18]>, DwarfRegNum<[50]>;
+  def D19_64  : AFPR64<19, "F19", [F19]>, DwarfRegNum<[51]>;
+  def D20_64  : AFPR64<20, "F20", [F20]>, DwarfRegNum<[52]>;
+  def D21_64  : AFPR64<21, "F21", [F21]>, DwarfRegNum<[53]>;
+  def D22_64  : AFPR64<22, "F22", [F22]>, DwarfRegNum<[54]>;
+  def D23_64  : AFPR64<23, "F23", [F23]>, DwarfRegNum<[55]>;
+  def D24_64  : AFPR64<24, "F24", [F24]>, DwarfRegNum<[56]>;
+  def D25_64  : AFPR64<25, "F25", [F25]>, DwarfRegNum<[57]>;
+  def D26_64  : AFPR64<26, "F26", [F26]>, DwarfRegNum<[58]>;
+  def D27_64  : AFPR64<27, "F27", [F27]>, DwarfRegNum<[59]>;
+  def D28_64  : AFPR64<28, "F28", [F28]>, DwarfRegNum<[60]>;
+  def D29_64  : AFPR64<29, "F29", [F29]>, DwarfRegNum<[61]>;
+  def D30_64  : AFPR64<30, "F30", [F30]>, DwarfRegNum<[62]>;
+  def D31_64  : AFPR64<31, "F31", [F31]>, DwarfRegNum<[63]>;
=20
   // Hi/Lo registers
   def HI  : Register<"hi">, DwarfRegNum<[64]>;
@@ -239,6 +238,7 @@
=20
   // Hardware register $29
   def HWR29 : Register<"29">;
+  def HWR29_64 : Register<"29">;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -301,3 +301,5 @@
=20
 // Hardware registers
 def HWRegs : RegisterClass<"Mips", [i32], 32, (add HWR29)>;
+def HWRegs64 : RegisterClass<"Mips", [i64], 32, (add HWR29_64)>;
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
Relocations.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsRelocations.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsRelocations.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,16 +1,16 @@
-//=3D=3D=3D- MipsRelocations.h - Mips Code Relocations ---------------*- C=
++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsRelocations.h - Mips Code Relocations ---------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
 //
-//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file defines the Mips target-specific relocation types
 // (for relocation-model=3Dstatic).
 //
-//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #ifndef MIPSRELOCATIONS_H_
 #define MIPSRELOCATIONS_H_
@@ -20,10 +20,10 @@
 namespace llvm {
   namespace Mips{
     enum RelocationType {
-      // reloc_mips_branch - pc relative relocation for branches. The lowe=
r 18
+      // reloc_mips_pc16 - pc relative relocation for branches. The lower =
18
       // bits of the difference between the branch target and the branch
       // instruction, shifted right by 2.
-      reloc_mips_branch =3D 1,
+      reloc_mips_pc16 =3D 1,
=20
       // reloc_mips_hi - upper 16 bits of the address (modified by +1 if t=
he
       // lower 16 bits of the address is negative).
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
Schedule.td
--- a/head/contrib/llvm/lib/Target/Mips/MipsSchedule.td	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsSchedule.td	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsSchedule.td - Mips Scheduling Definitions -------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsSchedule.td - Mips Scheduling Definitions ------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
Subtarget.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsSubtarget.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsSubtarget.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- MipsSubtarget.cpp - Mips Subtarget Information -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsSubtarget.cpp - Mips Subtarget Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,6 +13,7 @@
=20
 #include "MipsSubtarget.h"
 #include "Mips.h"
+#include "MipsRegisterInfo.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 #define GET_SUBTARGETINFO_TARGET_DESC
@@ -21,17 +22,19 @@
=20
 using namespace llvm;
=20
+void MipsSubtarget::anchor() { }
+
 MipsSubtarget::MipsSubtarget(const std::string &TT, const std::string &CPU,
                              const std::string &FS, bool little) :
   MipsGenSubtargetInfo(TT, CPU, FS),
-  MipsArchVersion(Mips32), MipsABI(UnknownABI), IsLittle(little),=20
+  MipsArchVersion(Mips32), MipsABI(UnknownABI), IsLittle(little),
   IsSingleFloat(false), IsFP64bit(false), IsGP64bit(false), HasVFPU(false),
   IsLinux(true), HasSEInReg(false), HasCondMov(false), HasMulDivAdd(false),
   HasMinMax(false), HasSwap(false), HasBitCount(false)
 {
   std::string CPUName =3D CPU;
   if (CPUName.empty())
-    CPUName =3D "mips32r1";
+    CPUName =3D "mips32";
=20
   // Parse features string.
   ParseSubtargetFeatures(CPUName, FS);
@@ -41,7 +44,7 @@
=20
   // Set MipsABI if it hasn't been set yet.
   if (MipsABI =3D=3D UnknownABI)
-    MipsABI =3D hasMips64() ? N64 : O32;=20
+    MipsABI =3D hasMips64() ? N64 : O32;
=20
   // Check if Architecture and ABI are compatible.
   assert(((!hasMips64() && (isABI_O32() || isABI_EABI())) ||
@@ -52,3 +55,14 @@
   if (TT.find("linux") =3D=3D std::string::npos)
     IsLinux =3D false;
 }
+
+bool
+MipsSubtarget::enablePostRAScheduler(CodeGenOpt::Level OptLevel,
+                                    TargetSubtargetInfo::AntiDepBreakMode&=
 Mode,
+                                     RegClassVector& CriticalPathRCs) cons=
t {
+  Mode =3D TargetSubtargetInfo::ANTIDEP_CRITICAL;
+  CriticalPathRCs.clear();
+  CriticalPathRCs.push_back(hasMips64() ?
+                            &Mips::CPU64RegsRegClass : &Mips::CPURegsRegCl=
ass);
+  return OptLevel >=3D CodeGenOpt::Aggressive;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
Subtarget.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsSubtarget.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsSubtarget.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- MipsSubtarget.h - Define Subtarget for the Mips -----*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- MipsSubtarget.h - Define Subtarget for the Mips ---------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -25,6 +25,7 @@
 class StringRef;
=20
 class MipsSubtarget : public MipsGenSubtargetInfo {
+  virtual void anchor();
=20
 public:
   // NOTE: O64 will not be supported.
@@ -88,6 +89,9 @@
   InstrItineraryData InstrItins;
=20
 public:
+  virtual bool enablePostRAScheduler(CodeGenOpt::Level OptLevel,
+                                     AntiDepBreakMode& Mode,
+                                     RegClassVector& CriticalPathRCs) cons=
t;
=20
   /// Only O32 and EABI supported right now.
   bool isABI_EABI() const { return MipsABI =3D=3D EABI; }
@@ -111,6 +115,8 @@
   bool hasMips64() const { return MipsArchVersion >=3D Mips64; }
   bool hasMips64r2() const { return MipsArchVersion =3D=3D Mips64r2; }
=20
+  bool hasMips32r2Or64() const { return hasMips32r2() || hasMips64(); }
+
   bool isLittle() const { return IsLittle; }
   bool isFP64bit() const { return IsFP64bit; }
   bool isGP64bit() const { return IsGP64bit; }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
TargetMachine.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsTargetMachine.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsTargetMachine.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -11,9 +11,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "MipsTargetMachine.h"
 #include "Mips.h"
-#include "MipsTargetMachine.h"
 #include "llvm/PassManager.h"
+#include "llvm/CodeGen/Passes.h"
 #include "llvm/Support/TargetRegistry.h"
 using namespace llvm;
=20
@@ -34,86 +35,119 @@
 // Using CodeModel::Large enables different CALL behavior.
 MipsTargetMachine::
 MipsTargetMachine(const Target &T, StringRef TT,
-                  StringRef CPU, StringRef FS,
+                  StringRef CPU, StringRef FS, const TargetOptions &Option=
s,
                   Reloc::Model RM, CodeModel::Model CM,
-                  bool isLittle):
-  LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
-  Subtarget(TT, CPU, FS, isLittle),
-  DataLayout(isLittle ?
-             (Subtarget.isABI_N64() ?
-              "e-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-n32" :
-              "e-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32") :
-             (Subtarget.isABI_N64() ?
-              "E-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-n32" :
-              "E-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32")),
-  InstrInfo(*this),
-  FrameLowering(Subtarget),
-  TLInfo(*this), TSInfo(*this), JITInfo() {
+                  CodeGenOpt::Level OL,
+                  bool isLittle)
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
+    Subtarget(TT, CPU, FS, isLittle),
+    DataLayout(isLittle ?
+               (Subtarget.isABI_N64() ?
+                "e-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-n32=
" :
+                "e-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32") :
+               (Subtarget.isABI_N64() ?
+                "E-p:64:64:64-i8:8:32-i16:16:32-i64:64:64-f128:128:128-n32=
" :
+                "E-p:32:32:32-i8:8:32-i16:16:32-i64:64:64-n32")),
+    InstrInfo(*this),
+    FrameLowering(Subtarget),
+    TLInfo(*this), TSInfo(*this), JITInfo() {
 }
=20
+void MipsebTargetMachine::anchor() { }
+
 MipsebTargetMachine::
 MipsebTargetMachine(const Target &T, StringRef TT,
-                    StringRef CPU, StringRef FS,
-                    Reloc::Model RM, CodeModel::Model CM) :
-  MipsTargetMachine(T, TT, CPU, FS, RM, CM, false) {}
+                    StringRef CPU, StringRef FS, const TargetOptions &Opti=
ons,
+                    Reloc::Model RM, CodeModel::Model CM,
+                    CodeGenOpt::Level OL)
+  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
+
+void MipselTargetMachine::anchor() { }
=20
 MipselTargetMachine::
 MipselTargetMachine(const Target &T, StringRef TT,
-                    StringRef CPU, StringRef FS,
-                    Reloc::Model RM, CodeModel::Model CM) :
-  MipsTargetMachine(T, TT, CPU, FS, RM, CM, true) {}
+                    StringRef CPU, StringRef FS, const TargetOptions &Opti=
ons,
+                    Reloc::Model RM, CodeModel::Model CM,
+                    CodeGenOpt::Level OL)
+  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
+
+void Mips64ebTargetMachine::anchor() { }
=20
 Mips64ebTargetMachine::
 Mips64ebTargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
-                      Reloc::Model RM, CodeModel::Model CM) :
-  MipsTargetMachine(T, TT, CPU, FS, RM, CM, false) {}
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
+                      Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL)
+  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
+
+void Mips64elTargetMachine::anchor() { }
=20
 Mips64elTargetMachine::
 Mips64elTargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
-                      Reloc::Model RM, CodeModel::Model CM) :
-  MipsTargetMachine(T, TT, CPU, FS, RM, CM, true) {}
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
+                      Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL)
+  : MipsTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
+
+namespace {
+/// Mips Code Generator Pass Configuration Options.
+class MipsPassConfig : public TargetPassConfig {
+public:
+  MipsPassConfig(MipsTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  MipsTargetMachine &getMipsTargetMachine() const {
+    return getTM<MipsTargetMachine>();
+  }
+
+  const MipsSubtarget &getMipsSubtarget() const {
+    return *getMipsTargetMachine().getSubtargetImpl();
+  }
+
+  virtual bool addInstSelector();
+  virtual bool addPreRegAlloc();
+  virtual bool addPreSched2();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *MipsTargetMachine::createPassConfig(PassManagerBase &PM)=
 {
+  return new MipsPassConfig(this, PM);
+}
=20
 // Install an instruction selector pass using
 // the ISelDag to gen Mips code.
-bool MipsTargetMachine::
-addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptLevel)
+bool MipsPassConfig::addInstSelector()
 {
-  PM.add(createMipsISelDag(*this));
+  PM.add(createMipsISelDag(getMipsTargetMachine()));
   return false;
 }
=20
 // Implemented by targets that want to run passes immediately before
 // machine code is emitted. return true if -print-machineinstrs should
 // print out the code after the passes.
-bool MipsTargetMachine::
-addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLevel)
+bool MipsPassConfig::addPreEmitPass()
 {
-  PM.add(createMipsDelaySlotFillerPass(*this));
+  PM.add(createMipsDelaySlotFillerPass(getMipsTargetMachine()));
   return true;
 }
=20
-bool MipsTargetMachine::
-addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) {
+bool MipsPassConfig::addPreRegAlloc() {
   // Do not restore $gp if target is Mips64.
   // In N32/64, $gp is a callee-saved register.
-  if (!Subtarget.hasMips64())
-    PM.add(createMipsEmitGPRestorePass(*this));
+  if (!getMipsSubtarget().hasMips64())
+    PM.add(createMipsEmitGPRestorePass(getMipsTargetMachine()));
   return true;
 }
=20
-bool MipsTargetMachine::
-addPostRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLevel) {
-  PM.add(createMipsExpandPseudoPass(*this));
+bool MipsPassConfig::addPreSched2() {
+  PM.add(createMipsExpandPseudoPass(getMipsTargetMachine()));
   return true;
 }
=20
 bool MipsTargetMachine::addCodeEmitter(PassManagerBase &PM,
-                                          CodeGenOpt::Level OptLevel,
-                                          JITCodeEmitter &JCE) {
+                                       JITCodeEmitter &JCE) {
   // Machine code emitter pass for Mips.
   PM.add(createMipsJITCodeEmitterPass(*this, JCE));
   return false;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
TargetMachine.h
--- a/head/contrib/llvm/lib/Target/Mips/MipsTargetMachine.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsTargetMachine.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsTargetMachine.h - Define TargetMachine for Mips -00--*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- MipsTargetMachine.h - Define TargetMachine for Mips -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,15 +14,15 @@
 #ifndef MIPSTARGETMACHINE_H
 #define MIPSTARGETMACHINE_H
=20
-#include "MipsSubtarget.h"
+#include "MipsFrameLowering.h"
 #include "MipsInstrInfo.h"
 #include "MipsISelLowering.h"
-#include "MipsFrameLowering.h"
+#include "MipsJITInfo.h"
 #include "MipsSelectionDAGInfo.h"
+#include "MipsSubtarget.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetFrameLowering.h"
-#include "MipsJITInfo.h"
=20
 namespace llvm {
   class formatted_raw_ostream;
@@ -38,8 +38,9 @@
=20
   public:
     MipsTargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
                       Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL,
                       bool isLittle);
=20
     virtual const MipsInstrInfo   *getInstrInfo()     const
@@ -67,15 +68,8 @@
     }
=20
     // Pass Pipeline Configuration
-    virtual bool addInstSelector(PassManagerBase &PM,
-                                 CodeGenOpt::Level OptLevel);
-    virtual bool addPreEmitPass(PassManagerBase &PM,
-                                CodeGenOpt::Level OptLevel);
-    virtual bool addPreRegAlloc(PassManagerBase &PM,
-                                CodeGenOpt::Level OptLevel);
-    virtual bool addPostRegAlloc(PassManagerBase &, CodeGenOpt::Level);
+    virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
     virtual bool addCodeEmitter(PassManagerBase &PM,
-				 CodeGenOpt::Level OptLevel,
 				 JITCodeEmitter &JCE);
=20
   };
@@ -83,37 +77,47 @@
 /// MipsebTargetMachine - Mips32 big endian target machine.
 ///
 class MipsebTargetMachine : public MipsTargetMachine {
+  virtual void anchor();
 public:
   MipsebTargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
-                      Reloc::Model RM, CodeModel::Model CM);
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
+                      Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL);
 };
=20
 /// MipselTargetMachine - Mips32 little endian target machine.
 ///
 class MipselTargetMachine : public MipsTargetMachine {
+  virtual void anchor();
 public:
   MipselTargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
-                      Reloc::Model RM, CodeModel::Model CM);
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
+                      Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL);
 };
=20
 /// Mips64ebTargetMachine - Mips64 big endian target machine.
 ///
 class Mips64ebTargetMachine : public MipsTargetMachine {
+  virtual void anchor();
 public:
   Mips64ebTargetMachine(const Target &T, StringRef TT,
                         StringRef CPU, StringRef FS,
-                        Reloc::Model RM, CodeModel::Model CM);
+                        const TargetOptions &Options,
+                        Reloc::Model RM, CodeModel::Model CM,
+                        CodeGenOpt::Level OL);
 };
=20
 /// Mips64elTargetMachine - Mips64 little endian target machine.
 ///
 class Mips64elTargetMachine : public MipsTargetMachine {
+  virtual void anchor();
 public:
   Mips64elTargetMachine(const Target &T, StringRef TT,
                         StringRef CPU, StringRef FS,
-                        Reloc::Model RM, CodeModel::Model CM);
+                        const TargetOptions &Options,
+                        Reloc::Model RM, CodeModel::Model CM,
+                        CodeGenOpt::Level OL);
 };
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Mips/Mips=
TargetObjectFile.cpp
--- a/head/contrib/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Mips/MipsTargetObjectFile.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- MipsTargetObjectFile.cpp - Mips object files ---------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- MipsTargetObjectFile.cpp - Mips Object Files ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/InstP=
rinter/PTXInstPrinter.cpp
--- a/head/contrib/llvm/lib/Target/PTX/InstPrinter/PTXInstPrinter.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/InstPrinter/PTXInstPrinter.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -18,27 +18,69 @@
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCSymbol.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
=20
-#define GET_INSTRUCTION_NAME
 #include "PTXGenAsmWriter.inc"
=20
 PTXInstPrinter::PTXInstPrinter(const MCAsmInfo &MAI,
+                               const MCInstrInfo &MII,
+                               const MCRegisterInfo &MRI,
                                const MCSubtargetInfo &STI) :
-  MCInstPrinter(MAI) {
+  MCInstPrinter(MAI, MII, MRI) {
   // Initialize the set of available features.
   setAvailableFeatures(STI.getFeatureBits());
 }
=20
-StringRef PTXInstPrinter::getOpcodeName(unsigned Opcode) const {
-  return getInstructionName(Opcode);
-}
+void PTXInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
+  // Decode the register number into type and offset
+  unsigned RegSpace  =3D RegNo & 0x7;
+  unsigned RegType   =3D (RegNo >> 3) & 0x7;
+  unsigned RegOffset =3D RegNo >> 6;
=20
-void PTXInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
-  OS << getRegisterName(RegNo);
+  // Print the register
+  OS << "%";
+
+  switch (RegSpace) {
+  default:
+    llvm_unreachable("Unknown register space!");
+  case PTXRegisterSpace::Reg:
+    switch (RegType) {
+    default:
+      llvm_unreachable("Unknown register type!");
+    case PTXRegisterType::Pred:
+      OS << "p";
+      break;
+    case PTXRegisterType::B16:
+      OS << "rh";
+      break;
+    case PTXRegisterType::B32:
+      OS << "r";
+      break;
+    case PTXRegisterType::B64:
+      OS << "rd";
+      break;
+    case PTXRegisterType::F32:
+      OS << "f";
+      break;
+    case PTXRegisterType::F64:
+      OS << "fd";
+      break;
+    }
+    break;
+  case PTXRegisterSpace::Return:
+    OS << "ret";
+    break;
+  case PTXRegisterSpace::Argument:
+    OS << "arg";
+    break;
+  }
+
+  OS << RegOffset;
 }
=20
 void PTXInstPrinter::printInst(const MCInst *MI, raw_ostream &O,
@@ -96,9 +138,23 @@
     O << "), ";
   }
=20
-  O << *(MI->getOperand(Index++).getExpr()) << ", (";
+  const MCExpr* Expr =3D MI->getOperand(Index++).getExpr();
+  unsigned NumArgs =3D MI->getOperand(Index++).getImm();
+ =20
+  // if the function call is to printf or puts, change to vprintf
+  if (const MCSymbolRefExpr *SymRefExpr =3D dyn_cast<MCSymbolRefExpr>(Expr=
)) {
+    const MCSymbol &Sym =3D SymRefExpr->getSymbol();
+    if (Sym.getName() =3D=3D "printf" || Sym.getName() =3D=3D "puts") {
+      O << "vprintf";
+    } else {
+      O << Sym.getName();
+    }
+  } else {
+    O << *Expr;
+  }
+ =20
+  O << ", (";
=20
-  unsigned NumArgs =3D MI->getOperand(Index++).getImm();
   if (NumArgs > 0) {
     printOperand(MI, Index++, O);
     for (unsigned i =3D 1; i < NumArgs; ++i) {
@@ -125,6 +181,8 @@
     } else {
       O << "0000000000000000";
     }
+  } else if (Op.isReg()) {
+    printRegName(O, Op.getReg());
   } else {
     assert(Op.isExpr() && "unknown operand kind in printOperand");
     const MCExpr *Expr =3D Op.getExpr();
@@ -156,7 +214,6 @@
     llvm_unreachable("Unknown rounding mode!");
   case PTXRoundingMode::RndDefault:
     llvm_unreachable("FP rounding-mode pass did not handle instruction!");
-    break;
   case PTXRoundingMode::RndNone:
     // Do not print anything.
     break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/InstP=
rinter/PTXInstPrinter.h
--- a/head/contrib/llvm/lib/Target/PTX/InstPrinter/PTXInstPrinter.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/InstPrinter/PTXInstPrinter.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PTXInstPrinter.h - Convert PTX MCInst to assembly syntax ---=
-------=3D=3D=3D//
+//=3D=3D=3D- PTXInstPrinter.h - Convert PTX MCInst to assembly syntax -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,14 +23,12 @@
=20
 class PTXInstPrinter : public MCInstPrinter {
 public:
-  PTXInstPrinter(const MCAsmInfo &MAI, const MCSubtargetInfo &STI);
+  PTXInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                 const MCRegisterInfo &MRI, const MCSubtargetInfo &STI);
=20
   virtual void printInst(const MCInst *MI, raw_ostream &O, StringRef Annot=
);
-  virtual StringRef getOpcodeName(unsigned Opcode) const;
   virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
=20
-  static const char *getInstructionName(unsigned Opcode);
-
   // Autogenerated by tblgen.
   void printInstruction(const MCInst *MI, raw_ostream &O);
   static const char *getRegisterName(unsigned RegNo);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/MCTar=
getDesc/PTXBaseInfo.h
--- a/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXBaseInfo.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXBaseInfo.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -18,6 +18,8 @@
 #define PTXBASEINFO_H
=20
 #include "PTXMCTargetDesc.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/raw_ostream.h"
=20
 namespace llvm {
   namespace PTXStateSpace {
@@ -57,6 +59,75 @@
       RndPosInfInt        =3D 10  // .rpi
     };
   } // namespace PTXII
+
+  namespace PTXRegisterType {
+    // Register type encoded in MCOperands
+    enum {
+      Pred  =3D 0,
+      B16,
+      B32,
+      B64,
+      F32,
+      F64
+    };
+  } // namespace PTXRegisterType
+
+  namespace PTXRegisterSpace {
+    // Register space encoded in MCOperands
+    enum {
+      Reg =3D 0,
+      Local,
+      Param,
+      Argument,
+      Return
+    };
+  }
+
+  inline static void decodeRegisterName(raw_ostream &OS,
+                                        unsigned EncodedReg) {
+    OS << "%";
+
+    unsigned RegSpace  =3D EncodedReg & 0x7;
+    unsigned RegType   =3D (EncodedReg >> 3) & 0x7;
+    unsigned RegOffset =3D EncodedReg >> 6;
+
+    switch (RegSpace) {
+    default:
+      llvm_unreachable("Unknown register space!");
+    case PTXRegisterSpace::Reg:
+      switch (RegType) {
+      default:
+        llvm_unreachable("Unknown register type!");
+      case PTXRegisterType::Pred:
+        OS << "p";
+        break;
+      case PTXRegisterType::B16:
+        OS << "rh";
+        break;
+      case PTXRegisterType::B32:
+        OS << "r";
+        break;
+      case PTXRegisterType::B64:
+        OS << "rd";
+        break;
+      case PTXRegisterType::F32:
+        OS << "f";
+        break;
+      case PTXRegisterType::F64:
+        OS << "fd";
+        break;
+      }
+      break;
+    case PTXRegisterSpace::Return:
+      OS << "ret";
+      break;
+    case PTXRegisterSpace::Argument:
+      OS << "arg";
+      break;
+    }
+
+    OS << RegOffset;
+  }
 } // namespace llvm
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/MCTar=
getDesc/PTXMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCAsmInfo.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCAsmInfo.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -16,6 +16,8 @@
=20
 using namespace llvm;
=20
+void PTXMCAsmInfo::anchor() { }
+
 PTXMCAsmInfo::PTXMCAsmInfo(const Target &T, const StringRef &TT) {
   Triple TheTriple(TT);
   if (TheTriple.getArch() =3D=3D Triple::ptx64)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/MCTar=
getDesc/PTXMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCAsmInfo.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCAsmInfo.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- PTXMCAsmInfo.h - PTX asm properties -----------------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- PTXMCAsmInfo.h - PTX asm properties --------------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -20,7 +20,9 @@
   class Target;
   class StringRef;
=20
-  struct PTXMCAsmInfo : public MCAsmInfo {
+  class PTXMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit PTXMCAsmInfo(const Target &T, const StringRef &TT);
   };
 } // namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/MCTar=
getDesc/PTXMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCTargetDesc.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCTargetDesc.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PTXMCTargetDesc.cpp - PTX Target Descriptions -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PTXMCTargetDesc.cpp - PTX Target Descriptions --------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -52,18 +52,21 @@
 }
=20
 static MCCodeGenInfo *createPTXMCCodeGenInfo(StringRef TT, Reloc::Model RM,
-                                             CodeModel::Model CM) {
+                                             CodeModel::Model CM,
+                                             CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
 static MCInstPrinter *createPTXMCInstPrinter(const Target &T,
                                              unsigned SyntaxVariant,
                                              const MCAsmInfo &MAI,
+                                             const MCInstrInfo &MII,
+                                             const MCRegisterInfo &MRI,
                                              const MCSubtargetInfo &STI) {
   assert(SyntaxVariant =3D=3D 0 && "We only have one syntax variant");
-  return new PTXInstPrinter(MAI, STI);
+  return new PTXInstPrinter(MAI, MII, MRI, STI);
 }
=20
 extern "C" void LLVMInitializePTXTargetMC() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/MCTar=
getDesc/PTXMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCTargetDesc.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/MCTargetDesc/PTXMCTargetDesc.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -15,9 +15,7 @@
 #define PTXMCTARGETDESC_H
=20
 namespace llvm {
-class MCSubtargetInfo;
 class Target;
-class StringRef;
=20
 extern Target ThePTX32Target;
 extern Target ThePTX64Target;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTX.h
--- a/head/contrib/llvm/lib/Target/PTX/PTX.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTX.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,3 @@
-//=3D=3D=3D-- PTX.h - Top-level interface for PTX representation ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTX.td
--- a/head/contrib/llvm/lib/Target/PTX/PTX.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTX.td	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTX.td - Describe the PTX Target Machine ---------------*- tb=
lgen -*-=3D=3D//
+//=3D=3D=3D-- PTX.td - Describe the PTX Target Machine -----------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXAs=
mPrinter.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXAsmPrinter.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXAsmPrinter.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,8 +14,8 @@
=20
 #define DEBUG_TYPE "ptx-asm-printer"
=20
+#include "PTXAsmPrinter.h"
 #include "PTX.h"
-#include "PTXAsmPrinter.h"
 #include "PTXMachineFunctionInfo.h"
 #include "PTXParamManager.h"
 #include "PTXRegisterInfo.h"
@@ -25,7 +25,6 @@
 #include "llvm/Function.h"
 #include "llvm/Module.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/CodeGen/AsmPrinter.h"
@@ -52,23 +51,23 @@
 static const char PARAM_PREFIX[] =3D "__param_";
 static const char RETURN_PREFIX[] =3D "__ret_";
=20
-static const char *getRegisterTypeName(unsigned RegNo,
-                                       const MachineRegisterInfo& MRI) {
-  const TargetRegisterClass *TRC =3D MRI.getRegClass(RegNo);
-
-#define TEST_REGCLS(cls, clsstr) \
-  if (PTX::cls ## RegisterClass =3D=3D TRC) return # clsstr;
-
-  TEST_REGCLS(RegPred, pred);
-  TEST_REGCLS(RegI16, b16);
-  TEST_REGCLS(RegI32, b32);
-  TEST_REGCLS(RegI64, b64);
-  TEST_REGCLS(RegF32, b32);
-  TEST_REGCLS(RegF64, b64);
-#undef TEST_REGCLS
-
-  llvm_unreachable("Not in any register class!");
-  return NULL;
+static const char *getRegisterTypeName(unsigned RegType) {
+  switch (RegType) {
+  default:
+    llvm_unreachable("Unknown register type");
+  case PTXRegisterType::Pred:
+    return ".pred";
+  case PTXRegisterType::B16:
+    return ".b16";
+  case PTXRegisterType::B32:
+    return ".b32";
+  case PTXRegisterType::B64:
+    return ".b64";
+  case PTXRegisterType::F32:
+    return ".f32";
+  case PTXRegisterType::F64:
+    return ".f64";
+  }
 }
=20
 static const char *getStateSpaceName(unsigned addressSpace) {
@@ -80,7 +79,6 @@
   case PTXStateSpace::Parameter: return "param";
   case PTXStateSpace::Shared:    return "shared";
   }
-  return NULL;
 }
=20
 static const char *getTypeName(Type* type) {
@@ -139,15 +137,15 @@
   const PTXSubtarget& ST =3D TM.getSubtarget<PTXSubtarget>();
=20
   // Emit the PTX .version and .target attributes
-  OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString()));
-  OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() +
+  OutStreamer.EmitRawText(Twine("\t.version ") + ST.getPTXVersionString());
+  OutStreamer.EmitRawText(Twine("\t.target ") + ST.getTargetString() +
                                 (ST.supportsDouble() ? ""
-                                                     : ", map_f64_to_f32")=
));
+                                                     : ", map_f64_to_f32")=
);
   // .address_size directive is optional, but it must immediately follow
   // the .target directive if present within a module
   if (ST.supportsPTX23()) {
-    std::string addrSize =3D ST.is64Bit() ? "64" : "32";
-    OutStreamer.EmitRawText(Twine("\t.address_size " + addrSize));
+    const char *addrSize =3D ST.is64Bit() ? "64" : "32";
+    OutStreamer.EmitRawText(Twine("\t.address_size ") + addrSize);
   }
=20
   OutStreamer.AddBlankLine();
@@ -166,6 +164,11 @@
=20
   OutStreamer.AddBlankLine();
=20
+  // declare external functions
+  for (Module::const_iterator i =3D M.begin(), e =3D M.end();
+       i !=3D e; ++i)
+    EmitFunctionDeclaration(i);
+ =20
   // declare global variables
   for (Module::const_global_iterator i =3D M.global_begin(), e =3D M.globa=
l_end();
        i !=3D e; ++i)
@@ -179,68 +182,47 @@
   const PTXParamManager &PM =3D MFI->getParamManager();
=20
   // Print register definitions
-  std::string regDefs;
+  SmallString<128> regDefs;
+  raw_svector_ostream os(regDefs);
   unsigned numRegs;
=20
   // pred
-  numRegs =3D MFI->getNumRegistersForClass(PTX::RegPredRegisterClass);
-  if(numRegs > 0) {
-    regDefs +=3D "\t.reg .pred %p<";
-    regDefs +=3D utostr(numRegs);
-    regDefs +=3D ">;\n";
-  }
+  numRegs =3D MFI->countRegisters(PTXRegisterType::Pred, PTXRegisterSpace:=
:Reg);
+  if(numRegs > 0)
+    os << "\t.reg .pred %p<" << numRegs << ">;\n";
=20
   // i16
-  numRegs =3D MFI->getNumRegistersForClass(PTX::RegI16RegisterClass);
-  if(numRegs > 0) {
-    regDefs +=3D "\t.reg .b16 %rh<";
-    regDefs +=3D utostr(numRegs);
-    regDefs +=3D ">;\n";
-  }
+  numRegs =3D MFI->countRegisters(PTXRegisterType::B16, PTXRegisterSpace::=
Reg);
+  if(numRegs > 0)
+    os << "\t.reg .b16 %rh<" << numRegs << ">;\n";
=20
   // i32
-  numRegs =3D MFI->getNumRegistersForClass(PTX::RegI32RegisterClass);
-  if(numRegs > 0) {
-    regDefs +=3D "\t.reg .b32 %r<";
-    regDefs +=3D utostr(numRegs);
-    regDefs +=3D ">;\n";
-  }
+  numRegs =3D MFI->countRegisters(PTXRegisterType::B32, PTXRegisterSpace::=
Reg);
+  if(numRegs > 0)
+    os << "\t.reg .b32 %r<" << numRegs << ">;\n";
=20
   // i64
-  numRegs =3D MFI->getNumRegistersForClass(PTX::RegI64RegisterClass);
-  if(numRegs > 0) {
-    regDefs +=3D "\t.reg .b64 %rd<";
-    regDefs +=3D utostr(numRegs);
-    regDefs +=3D ">;\n";
-  }
+  numRegs =3D MFI->countRegisters(PTXRegisterType::B64, PTXRegisterSpace::=
Reg);
+  if(numRegs > 0)
+    os << "\t.reg .b64 %rd<" << numRegs << ">;\n";
=20
   // f32
-  numRegs =3D MFI->getNumRegistersForClass(PTX::RegF32RegisterClass);
-  if(numRegs > 0) {
-    regDefs +=3D "\t.reg .f32 %f<";
-    regDefs +=3D utostr(numRegs);
-    regDefs +=3D ">;\n";
-  }
+  numRegs =3D MFI->countRegisters(PTXRegisterType::F32, PTXRegisterSpace::=
Reg);
+  if(numRegs > 0)
+    os << "\t.reg .f32 %f<" << numRegs << ">;\n";
=20
   // f64
-  numRegs =3D MFI->getNumRegistersForClass(PTX::RegF64RegisterClass);
-  if(numRegs > 0) {
-    regDefs +=3D "\t.reg .f64 %fd<";
-    regDefs +=3D utostr(numRegs);
-    regDefs +=3D ">;\n";
-  }
+  numRegs =3D MFI->countRegisters(PTXRegisterType::F64, PTXRegisterSpace::=
Reg);
+  if(numRegs > 0)
+    os << "\t.reg .f64 %fd<" << numRegs << ">;\n";
=20
   // Local params
   for (PTXParamManager::param_iterator i =3D PM.local_begin(), e =3D PM.lo=
cal_end();
-       i !=3D e; ++i) {
-    regDefs +=3D "\t.param .b";
-    regDefs +=3D utostr(PM.getParamSize(*i));
-    regDefs +=3D " ";
-    regDefs +=3D PM.getParamName(*i);
-    regDefs +=3D ";\n";
-  }
+       i !=3D e; ++i)
+    os << "\t.param .b" << PM.getParamSize(*i) << ' ' << PM.getParamName(*=
i)
+       << ";\n";
=20
-  OutStreamer.EmitRawText(Twine(regDefs));
+  OutStreamer.EmitRawText(os.str());
=20
=20
   const MachineFrameInfo* FrameInfo =3D MF->getFrameInfo();
@@ -249,16 +231,13 @@
   for (unsigned i =3D 0, e =3D FrameInfo->getNumObjects(); i !=3D e; ++i) {
     DEBUG(dbgs() << "Size of object: " << FrameInfo->getObjectSize(i) << "=
\n");
     if (FrameInfo->getObjectSize(i) > 0) {
-      std::string def =3D "\t.local .align ";
-      def +=3D utostr(FrameInfo->getObjectAlignment(i));
-      def +=3D " .b8";
-      def +=3D " __local";
-      def +=3D utostr(i);
-      def +=3D "[";
-      def +=3D utostr(FrameInfo->getObjectSize(i)); // Convert to bits
-      def +=3D "]";
-      def +=3D ";";
-      OutStreamer.EmitRawText(Twine(def));
+      OutStreamer.EmitRawText("\t.local .align " +
+                              Twine(FrameInfo->getObjectAlignment(i)) +
+                              " .b8 __local" +
+                              Twine(i) +
+                              "[" +
+                              Twine(FrameInfo->getObjectSize(i)) +
+                              "];");
     }
   }
=20
@@ -295,36 +274,27 @@
=20
   assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
=20
-  std::string decl;
+  SmallString<128> decl;
+  raw_svector_ostream os(decl);
=20
   // check if it is defined in some other translation unit
   if (gv->isDeclaration())
-    decl +=3D ".extern ";
+    os << ".extern ";
=20
   // state space: e.g., .global
-  decl +=3D ".";
-  decl +=3D getStateSpaceName(gv->getType()->getAddressSpace());
-  decl +=3D " ";
+  os << '.' << getStateSpaceName(gv->getType()->getAddressSpace()) << ' ';
=20
   // alignment (optional)
   unsigned alignment =3D gv->getAlignment();
-  if (alignment !=3D 0) {
-    decl +=3D ".align ";
-    decl +=3D utostr(gv->getAlignment());
-    decl +=3D " ";
-  }
+  if (alignment !=3D 0)
+    os << ".align " << gv->getAlignment() << ' ';
=20
=20
   if (PointerType::classof(gv->getType())) {
     PointerType* pointerTy =3D dyn_cast<PointerType>(gv->getType());
     Type* elementTy =3D pointerTy->getElementType();
=20
-    decl +=3D ".b8 ";
-    decl +=3D gvsym->getName();
-    decl +=3D "[";
-
-    if (elementTy->isArrayTy())
-    {
+    if (elementTy->isArrayTy()) {
       assert(elementTy->isArrayTy() && "Only pointers to arrays are suppor=
ted");
=20
       ArrayType* arrayTy =3D dyn_cast<ArrayType>(elementTy);
@@ -333,7 +303,6 @@
       unsigned numElements =3D arrayTy->getNumElements();
=20
       while (elementTy->isArrayTy()) {
-
         arrayTy =3D dyn_cast<ArrayType>(elementTy);
         elementTy =3D arrayTy->getElementType();
=20
@@ -342,110 +311,91 @@
=20
       // FIXME: isPrimitiveType() =3D=3D false for i16?
       assert(elementTy->isSingleValueType() &&
-              "Non-primitive types are not handled");
+             "Non-primitive types are not handled");
=20
-      // Compute the size of the array, in bytes.
-      uint64_t arraySize =3D (elementTy->getPrimitiveSizeInBits() >> 3)
-                        * numElements;
+      // Find the size of the element in bits
+      unsigned elementSize =3D elementTy->getPrimitiveSizeInBits();
=20
-      decl +=3D utostr(arraySize);
+      os << ".b" << elementSize << ' ' << gvsym->getName()
+         << '[' << numElements << ']';
+    } else {
+      os << ".b8" << gvsym->getName() << "[]";
     }
=20
-    decl +=3D "]";
+    // handle string constants (assume ConstantArray means string)
+    if (gv->hasInitializer()) {
+      const Constant *C =3D gv->getInitializer();
+      if (const ConstantArray *CA =3D dyn_cast<ConstantArray>(C)) {
+        os << " =3D {";
=20
-    // handle string constants (assume ConstantArray means string)
+        for (unsigned i =3D 0, e =3D C->getNumOperands(); i !=3D e; ++i) {
+          if (i > 0)
+            os << ',';
=20
-    if (gv->hasInitializer())
-    {
-      const Constant *C =3D gv->getInitializer();
-      if (const ConstantArray *CA =3D dyn_cast<ConstantArray>(C))
-      {
-        decl +=3D " =3D {";
-
-        for (unsigned i =3D 0, e =3D C->getNumOperands(); i !=3D e; ++i)
-        {
-          if (i > 0)   decl +=3D ",";
-
-          decl +=3D "0x" +
-                utohexstr(cast<ConstantInt>(CA->getOperand(i))->getZExtVal=
ue());
+          os << "0x";
+          os.write_hex(cast<ConstantInt>(CA->getOperand(i))->getZExtValue(=
));
         }
=20
-        decl +=3D "}";
+        os << '}';
       }
     }
-  }
-  else {
+  } else {
     // Note: this is currently the fall-through case and most likely gener=
ates
     //       incorrect code.
-    decl +=3D getTypeName(gv->getType());
-    decl +=3D " ";
+    os << getTypeName(gv->getType()) << ' ' << gvsym->getName();
=20
-    decl +=3D gvsym->getName();
-
-    if (ArrayType::classof(gv->getType()) ||
-        PointerType::classof(gv->getType()))
-      decl +=3D "[]";
+    if (isa<ArrayType>(gv->getType()) || isa<PointerType>(gv->getType()))
+      os << "[]";
   }
=20
-  decl +=3D ";";
+  os << ';';
=20
-  OutStreamer.EmitRawText(Twine(decl));
-
+  OutStreamer.EmitRawText(os.str());
   OutStreamer.AddBlankLine();
 }
=20
 void PTXAsmPrinter::EmitFunctionEntryLabel() {
   // The function label could have already been emitted if two symbols end=
 up
   // conflicting due to asm renaming.  Detect this and emit an error.
-  if (!CurrentFnSym->isUndefined()) {
+  if (!CurrentFnSym->isUndefined())
     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
                        "' label emitted multiple times to assembly file");
-    return;
-  }
=20
   const PTXMachineFunctionInfo *MFI =3D MF->getInfo<PTXMachineFunctionInfo=
>();
   const PTXParamManager &PM =3D MFI->getParamManager();
   const bool isKernel =3D MFI->isKernel();
   const PTXSubtarget& ST =3D TM.getSubtarget<PTXSubtarget>();
-  const MachineRegisterInfo& MRI =3D MF->getRegInfo();
=20
-  std::string decl =3D isKernel ? ".entry" : ".func";
+  SmallString<128> decl;
+  raw_svector_ostream os(decl);
+  os << (isKernel ? ".entry" : ".func");
=20
   if (!isKernel) {
-    decl +=3D " (";
+    os << " (";
     if (ST.useParamSpaceForDeviceArgs()) {
       for (PTXParamManager::param_iterator i =3D PM.ret_begin(), e =3D PM.=
ret_end(),
            b =3D i; i !=3D e; ++i) {
-        if (i !=3D b) {
-          decl +=3D ", ";
-        }
+        if (i !=3D b)
+          os << ", ";
=20
-        decl +=3D ".param .b";
-        decl +=3D utostr(PM.getParamSize(*i));
-        decl +=3D " ";
-        decl +=3D PM.getParamName(*i);
+        os << ".param .b" << PM.getParamSize(*i) << ' ' << PM.getParamName=
(*i);
       }
     } else {
       for (PTXMachineFunctionInfo::reg_iterator
            i =3D MFI->retreg_begin(), e =3D MFI->retreg_end(), b =3D i;
            i !=3D e; ++i) {
-        if (i !=3D b) {
-          decl +=3D ", ";
-        }
-        decl +=3D ".reg .";
-        decl +=3D getRegisterTypeName(*i, MRI);
-        decl +=3D " ";
-        decl +=3D MFI->getRegisterName(*i);
+        if (i !=3D b)
+          os << ", ";
+
+        os << ".reg " << getRegisterTypeName(MFI->getRegisterType(*i)) << =
' '
+           << MFI->getRegisterName(*i);
       }
     }
-    decl +=3D ")";
+    os << ')';
   }
=20
   // Print function name
-  decl +=3D " ";
-  decl +=3D CurrentFnSym->getName().str();
-
-  decl +=3D " (";
+  os << ' ' << CurrentFnSym->getName() << " (";
=20
   const Function *F =3D MF->getFunction();
=20
@@ -453,63 +403,80 @@
   if (isKernel || ST.useParamSpaceForDeviceArgs()) {
     /*for (PTXParamManager::param_iterator i =3D PM.arg_begin(), e =3D PM.=
arg_end(),
          b =3D i; i !=3D e; ++i) {
-      if (i !=3D b) {
-        decl +=3D ", ";
-      }
+      if (i !=3D b)
+        os << ", ";
=20
-      decl +=3D ".param .b";
-      decl +=3D utostr(PM.getParamSize(*i));
-      decl +=3D " ";
-      decl +=3D PM.getParamName(*i);
+      os << ".param .b" << PM.getParamSize(*i) << ' ' << PM.getParamName(*=
i);
     }*/
     int Counter =3D 1;
     for (Function::const_arg_iterator i =3D F->arg_begin(), e =3D F->arg_e=
nd(),
          b =3D i; i !=3D e; ++i) {
       if (i !=3D b)
-        decl +=3D ", ";
+        os << ", ";
       const Type *ArgType =3D (*i).getType();
-      decl +=3D ".param .b";
+      os << ".param .b";
       if (ArgType->isPointerTy()) {
         if (ST.is64Bit())
-          decl +=3D "64";
+          os << "64";
         else
-          decl +=3D "32";
+          os << "32";
       } else {
-        decl +=3D utostr(ArgType->getPrimitiveSizeInBits());
+        os << ArgType->getPrimitiveSizeInBits();
       }
       if (ArgType->isPointerTy() && ST.emitPtrAttribute()) {
         const PointerType *PtrType =3D dyn_cast<const PointerType>(ArgType=
);
-        decl +=3D " .ptr";
+        os << " .ptr";
         switch (PtrType->getAddressSpace()) {
         default:
           llvm_unreachable("Unknown address space in argument");
         case PTXStateSpace::Global:
-          decl +=3D " .global";
+          os << " .global";
           break;
         case PTXStateSpace::Shared:
-          decl +=3D " .shared";
+          os << " .shared";
           break;
         }
       }
-      decl +=3D " __param_";
-      decl +=3D utostr(Counter++);
+      os << " __param_" << Counter++;
     }
   } else {
     for (PTXMachineFunctionInfo::reg_iterator
          i =3D MFI->argreg_begin(), e =3D MFI->argreg_end(), b =3D i;
          i !=3D e; ++i) {
-      if (i !=3D b) {
-        decl +=3D ", ";
-      }
+      if (i !=3D b)
+        os << ", ";
=20
-      decl +=3D ".reg .";
-      decl +=3D getRegisterTypeName(*i, MRI);
-      decl +=3D " ";
-      decl +=3D MFI->getRegisterName(*i);
+      os << ".reg " << getRegisterTypeName(MFI->getRegisterType(*i)) << ' '
+         << MFI->getRegisterName(*i);
     }
   }
-  decl +=3D ")";
+  os << ')';
=20
+  OutStreamer.EmitRawText(os.str());
+}
+
+void PTXAsmPrinter::EmitFunctionDeclaration(const Function* func)
+{
+  const PTXSubtarget& ST =3D TM.getSubtarget<PTXSubtarget>();
+=09
+  std::string decl =3D "";
+
+  // hard-coded emission of extern vprintf function=20
+ =20
+  if (func->getName() =3D=3D "printf" || func->getName() =3D=3D "puts") {	=09
+    decl +=3D ".extern .func (.param .b32 __param_1) vprintf (.param .b";
+    if (ST.is64Bit())=09
+      decl +=3D "64";
+    else			=09
+      decl +=3D "32";
+    decl +=3D " __param_2, .param .b";
+    if (ST.is64Bit())=09
+      decl +=3D "64";
+    else			=09
+      decl +=3D "32";
+    decl +=3D " __param_3)\n";
+  }
+ =20
   OutStreamer.EmitRawText(Twine(decl));
 }
=20
@@ -535,7 +502,7 @@
   Entry.setValue(SrcId);
=20
   // Print out a .file directive to specify files for .loc directives.
-  OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
+  OutStreamer.EmitDwarfFileDirective(SrcId, "", Entry.getKey());
=20
   return SrcId;
 }
@@ -550,20 +517,18 @@
 MCOperand PTXAsmPrinter::lowerOperand(const MachineOperand &MO) {
   MCOperand MCOp;
   const PTXMachineFunctionInfo *MFI =3D MF->getInfo<PTXMachineFunctionInfo=
>();
-  const MCExpr *Expr;
-  const char *RegSymbolName;
+  unsigned EncodedReg;
   switch (MO.getType()) {
   default:
     llvm_unreachable("Unknown operand type");
   case MachineOperand::MO_Register:
-    // We create register operands as symbols, since the PTXInstPrinter cl=
ass
-    // has no way to map virtual registers back to a name without some ugly
-    // hacks.
-    // FIXME: Figure out a better way to handle virtual register naming.
-    RegSymbolName =3D MFI->getRegisterName(MO.getReg());
-    Expr =3D MCSymbolRefExpr::Create(RegSymbolName, MCSymbolRefExpr::VK_No=
ne,
-                                   OutContext);
-    MCOp =3D MCOperand::CreateExpr(Expr);
+    if (MO.getReg() > 0) {
+      // Encode the register
+      EncodedReg =3D MFI->getEncodedRegister(MO.getReg());
+    } else {
+      EncodedReg =3D 0;
+    }
+    MCOp =3D MCOperand::CreateReg(EncodedReg);
     break;
   case MachineOperand::MO_Immediate:
     MCOp =3D MCOperand::CreateImm(MO.getImm());
@@ -594,4 +559,3 @@
   RegisterAsmPrinter<PTXAsmPrinter> X(ThePTX32Target);
   RegisterAsmPrinter<PTXAsmPrinter> Y(ThePTX64Target);
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXAs=
mPrinter.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXAsmPrinter.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXAsmPrinter.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PTXAsmPrinter.h - Print machine code to a PTX file ---------=
-------=3D=3D=3D//
+//=3D=3D=3D-- PTXAsmPrinter.h - Print machine code to a PTX file ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -47,7 +47,7 @@
=20
 private:
   void EmitVariableDeclaration(const GlobalVariable *gv);
-  void EmitFunctionDeclaration();
+  void EmitFunctionDeclaration(const Function* func);
=20
   StringMap<unsigned> SourceIdMap;
 }; // class PTXAsmPrinter
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXFP=
RoundingModePass.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXFPRoundingModePass.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXFPRoundingModePass.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -23,9 +23,11 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
=20
+using namespace llvm;
+
 // NOTE: PTXFPRoundingModePass should be executed just before emission.
=20
-namespace llvm {
+namespace {
   /// PTXFPRoundingModePass - Pass to assign appropriate FP rounding modes=
 to
   /// all FP instructions. Essentially, this pass just looks for all FP
   /// instructions that have a rounding mode set to RndDefault, and sets an
@@ -58,7 +60,7 @@
       void initializeMap();
       void processInstruction(MachineInstr &MI);
   }; // class PTXFPRoundingModePass
-} // namespace llvm
+} // end anonymous namespace
=20
 using namespace llvm;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXFr=
ameLowering.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXFrameLowering.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXFrameLowering.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D=3D=3D- PTXFrameLowering.cpp - PTX Frame Information ----=
---*- C++ -*-=3D=3D=3D=3D=3D//
+//=3D=3D=3D-- PTXFrameLowering.cpp - PTX Frame Information ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXFr=
ameLowering.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXFrameLowering.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXFrameLowering.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D--- PTXFrameLowering.h - Define frame lowering for PTX --*- C++=
 -*----=3D=3D=3D//
+//=3D=3D=3D-- PTXFrameLowering.h - Define frame lowering for PTX -----*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIS=
elLowering.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXISelLowering.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXISelLowering.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "PTXISelLowering.h"
 #include "PTX.h"
-#include "PTXISelLowering.h"
 #include "PTXMachineFunctionInfo.h"
 #include "PTXRegisterInfo.h"
 #include "PTXSubtarget.h"
@@ -20,6 +20,7 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/CodeGen/CallingConvLower.h"
 #include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
@@ -46,6 +47,11 @@
   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this cor=
rect?
   setMinFunctionAlignment(2);
=20
+  // Let LLVM use loads/stores for all mem* operations
+  maxStoresPerMemcpy  =3D 4096;
+  maxStoresPerMemmove =3D 4096;
+  maxStoresPerMemset  =3D 4096;
+
   ////////////////////////////////////
   /////////// Expansion //////////////
   ////////////////////////////////////
@@ -91,7 +97,8 @@
=20
   // customise setcc to use bitwise logic if possible
=20
-  setOperationAction(ISD::SETCC, MVT::i1, Custom);
+  //setOperationAction(ISD::SETCC, MVT::i1, Custom);
+  setOperationAction(ISD::SETCC, MVT::i1, Legal);
=20
   // customize translation of memory addresses
=20
@@ -150,18 +157,27 @@
   SDValue Op1 =3D Op.getOperand(1);
   SDValue Op2 =3D Op.getOperand(2);
   DebugLoc dl =3D Op.getDebugLoc();
-  ISD::CondCode CC =3D cast<CondCodeSDNode>(Op.getOperand(2))->get();
+  //ISD::CondCode CC =3D cast<CondCodeSDNode>(Op.getOperand(2))->get();
=20
   // Look for X =3D=3D 0, X =3D=3D 1, X !=3D 0, or X !=3D 1
   // We can simplify these to bitwise logic
=20
-  if (Op1.getOpcode() =3D=3D ISD::Constant &&
-      (cast<ConstantSDNode>(Op1)->getZExtValue() =3D=3D 1 ||
-       cast<ConstantSDNode>(Op1)->isNullValue()) &&
-      (CC =3D=3D ISD::SETEQ || CC =3D=3D ISD::SETNE)) {
+  //if (Op1.getOpcode() =3D=3D ISD::Constant &&
+  //    (cast<ConstantSDNode>(Op1)->getZExtValue() =3D=3D 1 ||
+  //     cast<ConstantSDNode>(Op1)->isNullValue()) &&
+  //    (CC =3D=3D ISD::SETEQ || CC =3D=3D ISD::SETNE)) {
+  //
+  //  return DAG.getNode(ISD::AND, dl, MVT::i1, Op0, Op1);
+  //}
=20
-    return DAG.getNode(ISD::AND, dl, MVT::i1, Op0, Op1);
-  }
+  //ConstantSDNode* COp1 =3D cast<ConstantSDNode>(Op1);
+  //if(COp1 && COp1->getZExtValue() =3D=3D 1) {
+  //  if(CC =3D=3D ISD::SETNE) {
+  //    return DAG.getNode(PTX::XORripreds, dl, MVT::i1, Op0);
+  //  }
+  //}
+
+  llvm_unreachable("setcc was not matched by a pattern!");
=20
   return DAG.getNode(ISD::SETCC, dl, MVT::i1, Op0, Op1, Op2);
 }
@@ -205,7 +221,6 @@
   switch (CallConv) {
     default:
       llvm_unreachable("Unsupported calling convention");
-      break;
     case CallingConv::PTX_Kernel:
       MFI->setKernel(true);
       break;
@@ -235,8 +250,25 @@
   }
   else {
     for (unsigned i =3D 0, e =3D Ins.size(); i !=3D e; ++i) {
-      EVT                  RegVT =3D Ins[i].VT;
-      TargetRegisterClass* TRC   =3D getRegClassFor(RegVT);
+      EVT                        RegVT =3D Ins[i].VT;
+      const TargetRegisterClass* TRC   =3D getRegClassFor(RegVT);
+      unsigned                   RegType;
+
+      // Determine which register class we need
+      if (RegVT =3D=3D MVT::i1)
+        RegType =3D PTXRegisterType::Pred;
+      else if (RegVT =3D=3D MVT::i16)
+        RegType =3D PTXRegisterType::B16;
+      else if (RegVT =3D=3D MVT::i32)
+        RegType =3D PTXRegisterType::B32;
+      else if (RegVT =3D=3D MVT::i64)
+        RegType =3D PTXRegisterType::B64;
+      else if (RegVT =3D=3D MVT::f32)
+        RegType =3D PTXRegisterType::F32;
+      else if (RegVT =3D=3D MVT::f64)
+        RegType =3D PTXRegisterType::F64;
+      else
+        llvm_unreachable("Unknown parameter type");
=20
       // Use a unique index in the instruction to prevent instruction fold=
ing.
       // Yes, this is a hack.
@@ -247,7 +279,7 @@
=20
       InVals.push_back(ArgValue);
=20
-      MFI->addArgReg(Reg);
+      MFI->addRegister(Reg, RegType, PTXRegisterSpace::Argument);
     }
   }
=20
@@ -297,26 +329,33 @@
   } else {
     for (unsigned i =3D 0, e =3D Outs.size(); i !=3D e; ++i) {
       EVT                  RegVT =3D Outs[i].VT;
-      TargetRegisterClass* TRC =3D 0;
+      const TargetRegisterClass* TRC;
+      unsigned             RegType;
=20
       // Determine which register class we need
       if (RegVT =3D=3D MVT::i1) {
         TRC =3D PTX::RegPredRegisterClass;
+        RegType =3D PTXRegisterType::Pred;
       }
       else if (RegVT =3D=3D MVT::i16) {
         TRC =3D PTX::RegI16RegisterClass;
+        RegType =3D PTXRegisterType::B16;
       }
       else if (RegVT =3D=3D MVT::i32) {
         TRC =3D PTX::RegI32RegisterClass;
+        RegType =3D PTXRegisterType::B32;
       }
       else if (RegVT =3D=3D MVT::i64) {
         TRC =3D PTX::RegI64RegisterClass;
+        RegType =3D PTXRegisterType::B64;
       }
       else if (RegVT =3D=3D MVT::f32) {
         TRC =3D PTX::RegF32RegisterClass;
+        RegType =3D PTXRegisterType::F32;
       }
       else if (RegVT =3D=3D MVT::f64) {
         TRC =3D PTX::RegF64RegisterClass;
+        RegType =3D PTXRegisterType::F64;
       }
       else {
         llvm_unreachable("Unknown parameter type");
@@ -329,7 +368,7 @@
=20
       Chain =3D DAG.getNode(PTXISD::WRITE_PARAM, dl, MVT::Other, Copy, Out=
Reg);
=20
-      MFI->addRetReg(Reg);
+      MFI->addRegister(Reg, RegType, PTXRegisterSpace::Return);
     }
   }
=20
@@ -344,7 +383,7 @@
 SDValue
 PTXTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                              CallingConv::ID CallConv, bool isVarArg,
-                             bool &isTailCall,
+                             bool doesNotRet, bool &isTailCall,
                              const SmallVectorImpl<ISD::OutputArg> &Outs,
                              const SmallVectorImpl<SDValue> &OutVals,
                              const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -352,38 +391,99 @@
                              SmallVectorImpl<SDValue> &InVals) const {
=20
   MachineFunction& MF =3D DAG.getMachineFunction();
-  PTXMachineFunctionInfo *MFI =3D MF.getInfo<PTXMachineFunctionInfo>();
-  PTXParamManager &PM =3D MFI->getParamManager();
+  PTXMachineFunctionInfo *PTXMFI =3D MF.getInfo<PTXMachineFunctionInfo>();
+  PTXParamManager &PM =3D PTXMFI->getParamManager();
+  MachineFrameInfo *MFI =3D MF.getFrameInfo();
=20
   assert(getTargetMachine().getSubtarget<PTXSubtarget>().callsAreHandled()=
 &&
          "Calls are not handled for the target device");
=20
+  // Identify the callee function
+  const GlobalValue *GV =3D cast<GlobalAddressSDNode>(Callee)->getGlobal();
+  const Function *function =3D cast<Function>(GV);
+
+  // allow non-device calls only for printf
+  bool isPrintf =3D function->getName() =3D=3D "printf" || function->getNa=
me() =3D=3D "puts";
+
+  assert((isPrintf || function->getCallingConv() =3D=3D CallingConv::PTX_D=
evice) &&
+			 "PTX function calls must be to PTX device functions");
+
+  unsigned outSize =3D isPrintf ? 2 : Outs.size();
+
   std::vector<SDValue> Ops;
   // The layout of the ops will be [Chain, #Ins, Ins, Callee, #Outs, Outs]
-  Ops.resize(Outs.size() + Ins.size() + 4);
+  Ops.resize(outSize + Ins.size() + 4);
=20
   Ops[0] =3D Chain;
=20
   // Identify the callee function
-  const GlobalValue *GV =3D cast<GlobalAddressSDNode>(Callee)->getGlobal();
-  assert(cast<Function>(GV)->getCallingConv() =3D=3D CallingConv::PTX_Devi=
ce &&
-         "PTX function calls must be to PTX device functions");
   Callee =3D DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
   Ops[Ins.size()+2] =3D Callee;
=20
-  // Generate STORE_PARAM nodes for each function argument.  In PTX, funct=
ion
-  // arguments are explicitly stored into .param variables and passed as
-  // arguments. There is no register/stack-based calling convention in PTX.
-  Ops[Ins.size()+3] =3D DAG.getTargetConstant(OutVals.size(), MVT::i32);
-  for (unsigned i =3D 0; i !=3D OutVals.size(); ++i) {
-    unsigned Size =3D OutVals[i].getValueType().getSizeInBits();
-    unsigned Param =3D PM.addLocalParam(Size);
-    const std::string &ParamName =3D PM.getParamName(Param);
-    SDValue ParamValue =3D DAG.getTargetExternalSymbol(ParamName.c_str(),
-                                                     MVT::Other);
+  // #Outs
+  Ops[Ins.size()+3] =3D DAG.getTargetConstant(outSize, MVT::i32);
+
+  if (isPrintf) {
+    // first argument is the address of the global string variable in memo=
ry
+    unsigned Param0 =3D PM.addLocalParam(getPointerTy().getSizeInBits());
+    SDValue ParamValue0 =3D DAG.getTargetExternalSymbol(PM.getParamName(Pa=
ram0).c_str(),
+                                                      MVT::Other);
     Chain =3D DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
-                        ParamValue, OutVals[i]);
-    Ops[i+Ins.size()+4] =3D ParamValue;
+                        ParamValue0, OutVals[0]);
+    Ops[Ins.size()+4] =3D ParamValue0;
+
+    // alignment is the maximum size of all the arguments
+    unsigned alignment =3D 0;
+    for (unsigned i =3D 1; i < OutVals.size(); ++i) {
+      alignment =3D std::max(alignment,
+    		               OutVals[i].getValueType().getSizeInBits());
+    }
+
+    // size is the alignment multiplied by the number of arguments
+    unsigned size =3D alignment * (OutVals.size() - 1);
+
+    // second argument is the address of the stack object (unless no argum=
ents)
+    unsigned Param1 =3D PM.addLocalParam(getPointerTy().getSizeInBits());
+    SDValue ParamValue1 =3D DAG.getTargetExternalSymbol(PM.getParamName(Pa=
ram1).c_str(),
+                                                      MVT::Other);
+    Ops[Ins.size()+5] =3D ParamValue1;
+
+    if (size > 0)
+    {
+      // create a local stack object to store the arguments
+      unsigned StackObject =3D MFI->CreateStackObject(size / 8, alignment =
/ 8, false);
+      SDValue FrameIndex =3D DAG.getFrameIndex(StackObject, getPointerTy()=
);
+
+      // store each of the arguments to the stack in turn
+      for (unsigned int i =3D 1; i !=3D OutVals.size(); i++) {
+        SDValue FrameAddr =3D DAG.getNode(ISD::ADD, dl, getPointerTy(), Fr=
ameIndex, DAG.getTargetConstant((i - 1) * 8, getPointerTy()));
+        Chain =3D DAG.getStore(Chain, dl, OutVals[i], FrameAddr,
+                             MachinePointerInfo(),
+                             false, false, 0);
+      }
+
+      // copy the address of the local frame index to get the address in n=
on-local space
+      SDValue genericAddr =3D DAG.getNode(PTXISD::COPY_ADDRESS, dl, getPoi=
nterTy(), FrameIndex);
+
+      // store this address in the second argument
+      Chain =3D DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain, Pa=
ramValue1, genericAddr);
+    }
+  }
+  else
+  {
+	  // Generate STORE_PARAM nodes for each function argument.  In PTX, func=
tion
+	  // arguments are explicitly stored into .param variables and passed as
+	  // arguments. There is no register/stack-based calling convention in PT=
X.
+	  for (unsigned i =3D 0; i !=3D OutVals.size(); ++i) {
+		unsigned Size =3D OutVals[i].getValueType().getSizeInBits();
+		unsigned Param =3D PM.addLocalParam(Size);
+		const std::string &ParamName =3D PM.getParamName(Param);
+		SDValue ParamValue =3D DAG.getTargetExternalSymbol(ParamName.c_str(),
+														 MVT::Other);
+		Chain =3D DAG.getNode(PTXISD::STORE_PARAM, dl, MVT::Other, Chain,
+							ParamValue, OutVals[i]);
+		Ops[i+Ins.size()+4] =3D ParamValue;
+	  }
   }
=20
   std::vector<SDValue> InParams;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIS=
elLowering.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXISelLowering.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXISelLowering.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D-- PTXISelLowering.h - PTX DAG Lowering Interface ------------*- C=
++ -*-=3D=3D//
+//=3D=3D=3D-- PTXISelLowering.h - PTX DAG Lowering Interface ----------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,8 +18,6 @@
 #include "llvm/Target/TargetLowering.h"
=20
 namespace llvm {
-class PTXSubtarget;
-class PTXTargetMachine;
=20
 namespace PTXISD {
   enum NodeType {
@@ -64,9 +62,8 @@
                   SelectionDAG &DAG) const;
=20
     virtual SDValue
-      LowerCall(SDValue Chain, SDValue Callee,
-                CallingConv::ID CallConv, bool isVarArg,
-                bool &isTailCall,
+      LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
+                bool isVarArg, bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIn=
strFormats.td
--- a/head/contrib/llvm/lib/Target/PTX/PTXInstrFormats.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXInstrFormats.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXInstrFormats.td - PTX Instruction Formats ----------*- tbl=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- PTXInstrFormats.td - PTX Instruction Formats -------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIn=
strInfo.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXInstrInfo.cpp - PTX Instruction Information --------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- PTXInstrInfo.cpp - PTX Instruction Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,8 +13,8 @@
=20
 #define DEBUG_TYPE "ptx-instrinfo"
=20
+#include "PTXInstrInfo.h"
 #include "PTX.h"
-#include "PTXInstrInfo.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/SelectionDAG.h"
@@ -116,7 +116,7 @@
 }
=20
 bool PTXInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
-  return !isPredicated(MI) && get(MI->getOpcode()).isTerminator();
+  return !isPredicated(MI) && MI->isTerminator();
 }
=20
 bool PTXInstrInfo::
@@ -184,15 +184,13 @@
   if (MBB.empty())
     return true;
=20
-  MachineBasicBlock::const_iterator iter =3D MBB.end();
+  MachineBasicBlock::iterator iter =3D MBB.end();
   const MachineInstr& instLast1 =3D *--iter;
-  const MCInstrDesc &desc1 =3D instLast1.getDesc();
   // for special case that MBB has only 1 instruction
   const bool IsSizeOne =3D MBB.size() =3D=3D 1;
   // if IsSizeOne is true, *--iter and instLast2 are invalid
   // we put a dummy value in instLast2 and desc2 since they are used
   const MachineInstr& instLast2 =3D IsSizeOne ? instLast1 : *--iter;
-  const MCInstrDesc &desc2 =3D IsSizeOne ? desc1 : instLast2.getDesc();
=20
   DEBUG(dbgs() << "\n");
   DEBUG(dbgs() << "AnalyzeBranch: opcode: " << instLast1.getOpcode() << "\=
n");
@@ -207,7 +205,7 @@
   }
=20
   // this block ends with only an unconditional branch
-  if (desc1.isUnconditionalBranch() &&
+  if (instLast1.isUnconditionalBranch() &&
       // when IsSizeOne is true, it "absorbs" the evaluation of instLast2
       (IsSizeOne || !IsAnyKindOfBranch(instLast2))) {
     DEBUG(dbgs() << "AnalyzeBranch: ends with only uncond branch\n");
@@ -217,7 +215,7 @@
=20
   // this block ends with a conditional branch and
   // it falls through to a successor block
-  if (desc1.isConditionalBranch() &&
+  if (instLast1.isConditionalBranch() &&
       IsAnySuccessorAlsoLayoutSuccessor(MBB)) {
     DEBUG(dbgs() << "AnalyzeBranch: ends with cond branch and fall through=
\n");
     TBB =3D GetBranchTarget(instLast1);
@@ -233,8 +231,8 @@
=20
   // this block ends with a conditional branch
   // followed by an unconditional branch
-  if (desc2.isConditionalBranch() &&
-      desc1.isUnconditionalBranch()) {
+  if (instLast2.isConditionalBranch() &&
+      instLast1.isUnconditionalBranch()) {
     DEBUG(dbgs() << "AnalyzeBranch: ends with cond and uncond branch\n");
     TBB =3D GetBranchTarget(instLast2);
     FBB =3D GetBranchTarget(instLast1);
@@ -302,7 +300,7 @@
                                      unsigned SrcReg, bool isKill, int Fra=
meIdx,
                                        const TargetRegisterClass *RC,
                                        const TargetRegisterInfo *TRI) cons=
t {
-  assert(false && "storeRegToStackSlot should not be called for PTX");
+  llvm_unreachable("storeRegToStackSlot should not be called for PTX");
 }
=20
 void PTXInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
@@ -310,7 +308,7 @@
                                         unsigned DestReg, int FrameIdx,
                                         const TargetRegisterClass *RC,
                                         const TargetRegisterInfo *TRI) con=
st {
-  assert(false && "loadRegFromStackSlot should not be called for PTX");
+  llvm_unreachable("loadRegFromStackSlot should not be called for PTX");
 }
=20
 // static helper routines
@@ -341,8 +339,7 @@
 }
=20
 bool PTXInstrInfo::IsAnyKindOfBranch(const MachineInstr& inst) {
-  const MCInstrDesc &desc =3D inst.getDesc();
-  return desc.isTerminator() || desc.isBranch() || desc.isIndirectBranch();
+  return inst.isTerminator() || inst.isBranch() || inst.isIndirectBranch();
 }
=20
 bool PTXInstrInfo::
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIn=
strInfo.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXInstrInfo.h - PTX Instruction Information -------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PTXInstrInfo.h - PTX Instruction Information ------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIn=
strInfo.td
--- a/head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.td	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXInstrInfo.td	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXInstrInfo.td - PTX Instruction defs -----------------*- tb=
lgen-*-=3D=3D=3D//
+//=3D=3D=3D-- PTXInstrInfo.td - PTX Instruction defs --------------*- tabl=
egen-*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -680,6 +680,12 @@
   def MOVaddr64
     : InstPTX<(outs RegI64:$d), (ins i64imm:$a), "mov.u64\t$d, $a",
               [(set RegI64:$d, (PTXcopyaddress tglobaladdr:$a))]>;
+  def MOVframe32
+    : InstPTX<(outs RegI32:$d), (ins i32imm:$a), "cvta.local.u32\t$d, $a",
+              [(set RegI32:$d, (PTXcopyaddress frameindex:$a))]>;
+  def MOVframe64
+    : InstPTX<(outs RegI64:$d), (ins i64imm:$a), "cvta.local.u64\t$d, $a",
+              [(set RegI64:$d, (PTXcopyaddress frameindex:$a))]>;
 }
=20
 // PTX cvt instructions
@@ -802,6 +808,8 @@
 let isBranch =3D 1, isTerminator =3D 1 in {
   // FIXME: The pattern part is blank because I cannot (or do not yet know
   // how to) use the first operand of PredicateOperand (a RegPred register=
) here
+  // When this is revisited, make sure to also look at LowerSETCC and try =
to
+  // fold it into negated predicates, if possible.
   def BRAdp
     : InstPTX<(outs), (ins brtarget:$d), "bra\t$d",
               [/*(brcond pred:$_p, bb:$d)*/]>;
@@ -819,17 +827,17 @@
 ///=3D=3D=3D- Parameter Passing Pseudo-Instructions ----------------------=
-------=3D=3D=3D//
=20
 def READPARAMPRED : InstPTX<(outs RegPred:$a), (ins i32imm:$b),
-                            "mov.pred\t$a, %param$b", []>;
+                            "mov.pred\t$a, %arg$b", []>;
 def READPARAMI16  : InstPTX<(outs RegI16:$a), (ins i32imm:$b),
-                            "mov.b16\t$a, %param$b", []>;
+                            "mov.b16\t$a, %arg$b", []>;
 def READPARAMI32  : InstPTX<(outs RegI32:$a), (ins i32imm:$b),
-                            "mov.b32\t$a, %param$b", []>;
+                            "mov.b32\t$a, %arg$b", []>;
 def READPARAMI64  : InstPTX<(outs RegI64:$a), (ins i32imm:$b),
-                            "mov.b64\t$a, %param$b", []>;
+                            "mov.b64\t$a, %arg$b", []>;
 def READPARAMF32  : InstPTX<(outs RegF32:$a), (ins i32imm:$b),
-                            "mov.f32\t$a, %param$b", []>;
+                            "mov.f32\t$a, %arg$b", []>;
 def READPARAMF64  : InstPTX<(outs RegF64:$a), (ins i32imm:$b),
-                            "mov.f64\t$a, %param$b", []>;
+                            "mov.f64\t$a, %arg$b", []>;
=20
 def WRITEPARAMPRED : InstPTX<(outs), (ins RegPred:$a), "//w", []>;
 def WRITEPARAMI16  : InstPTX<(outs), (ins RegI16:$a), "//w", []>;
@@ -885,19 +893,26 @@
=20
 // FMUL+FADD
 def : Pat<(f32 (fadd (fmul RegF32:$a, RegF32:$b), RegF32:$c)),
-          (FMADrrr32 RndDefault, RegF32:$a, RegF32:$b, RegF32:$c)>;
+          (FMADrrr32 RndDefault, RegF32:$a, RegF32:$b, RegF32:$c)>,
+          Requires<[SupportsFMA]>;
 def : Pat<(f32 (fadd (fmul RegF32:$a, RegF32:$b), fpimm:$c)),
-          (FMADrri32 RndDefault, RegF32:$a, RegF32:$b, fpimm:$c)>;
+          (FMADrri32 RndDefault, RegF32:$a, RegF32:$b, fpimm:$c)>,
+          Requires<[SupportsFMA]>;
 def : Pat<(f32 (fadd (fmul RegF32:$a, fpimm:$b), fpimm:$c)),
-          (FMADrrr32 RndDefault, RegF32:$a, fpimm:$b, fpimm:$c)>;
+          (FMADrrr32 RndDefault, RegF32:$a, fpimm:$b, fpimm:$c)>,
+          Requires<[SupportsFMA]>;
 def : Pat<(f32 (fadd (fmul RegF32:$a, RegF32:$b), fpimm:$c)),
-          (FMADrri32 RndDefault, RegF32:$a, RegF32:$b, fpimm:$c)>;
+          (FMADrri32 RndDefault, RegF32:$a, RegF32:$b, fpimm:$c)>,
+          Requires<[SupportsFMA]>;
 def : Pat<(f64 (fadd (fmul RegF64:$a, RegF64:$b), RegF64:$c)),
-          (FMADrrr64 RndDefault, RegF64:$a, RegF64:$b, RegF64:$c)>;
+          (FMADrrr64 RndDefault, RegF64:$a, RegF64:$b, RegF64:$c)>,
+          Requires<[SupportsFMA]>;
 def : Pat<(f64 (fadd (fmul RegF64:$a, RegF64:$b), fpimm:$c)),
-          (FMADrri64 RndDefault, RegF64:$a, RegF64:$b, fpimm:$c)>;
+          (FMADrri64 RndDefault, RegF64:$a, RegF64:$b, fpimm:$c)>,
+          Requires<[SupportsFMA]>;
 def : Pat<(f64 (fadd (fmul RegF64:$a, fpimm:$b), fpimm:$c)),
-          (FMADrri64 RndDefault, RegF64:$a, fpimm:$b, fpimm:$c)>;
+          (FMADrri64 RndDefault, RegF64:$a, fpimm:$b, fpimm:$c)>,
+          Requires<[SupportsFMA]>;
=20
 // FNEG
 def : Pat<(f32 (fneg RegF32:$a)), (FNEGrr32 RndDefault, RegF32:$a)>;
@@ -1004,6 +1019,9 @@
 def : Pat<(f64 (fextend RegF32:$a)),    (CVTf64f32 RegF32:$a)>;
 def : Pat<(f64 (bitconvert RegI64:$a)), (MOVf64i64 RegI64:$a)>;
=20
+// setcc - predicate inversion for branch conditions
+def : Pat<(i1 (setcc RegPred:$a, imm:$b, SETNE)),
+          (XORripreds RegPred:$a, imm:$b)>;
=20
 ///=3D=3D=3D- Intrinsic Instructions -------------------------------------=
-------=3D=3D=3D//
 include "PTXIntrinsicInstrInfo.td"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIn=
strLoadStore.td
--- a/head/contrib/llvm/lib/Target/PTX/PTXInstrLoadStore.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXInstrLoadStore.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXInstrLoadStore.td - PTX Load/Store Instruction Defs -*- tb=
lgen-*-=3D=3D=3D//
+//=3D=3D=3D- PTXInstrLoadStore.td - PTX Load/Store Instruction Defs -*- ta=
blegen-*-=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXIn=
trinsicInstrInfo.td
--- a/head/contrib/llvm/lib/Target/PTX/PTXIntrinsicInstrInfo.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXIntrinsicInstrInfo.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXIntrinsicInstrInfo.td - Defines PTX intrinsics ---*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- PTXIntrinsicInstrInfo.td - Defines PTX intrinsics --*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXMC=
AsmStreamer.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXMCAsmStreamer.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXMCAsmStreamer.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- lib/Target/PTX/PTXMCAsmStreamer.cpp - PTX Text Assembly Outpu=
t -----=3D=3D=3D//
+//=3D=3D=3D-- PTXMCAsmStreamer.cpp - PTX Text Assembly Output ------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -22,6 +22,7 @@
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/FormattedStream.h"
+#include "llvm/Support/PathV2.h"
 #include "llvm/Support/raw_ostream.h"
=20
 using namespace llvm;
@@ -161,11 +162,12 @@
   virtual void EmitCodeAlignment(unsigned ByteAlignment,
                                  unsigned MaxBytesToEmit =3D 0);
=20
-  virtual void EmitValueToOffset(const MCExpr *Offset,
+  virtual bool EmitValueToOffset(const MCExpr *Offset,
                                  unsigned char Value =3D 0);
=20
   virtual void EmitFileDirective(StringRef Filename);
-  virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
+  virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
+                                      StringRef Filename);
=20
   virtual void EmitInstruction(const MCInst &Inst);
=20
@@ -174,7 +176,7 @@
   /// indicated by the hasRawTextSupport() predicate.
   virtual void EmitRawText(StringRef String);
=20
-  virtual void Finish();
+  virtual void FinishImpl();
=20
   /// @}
=20
@@ -476,8 +478,8 @@
 void PTXMCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
                                          unsigned MaxBytesToEmit) {}
=20
-void PTXMCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
-                                         unsigned char Value) {}
+bool PTXMCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
+                                         unsigned char Value) {return fals=
e;}
=20
=20
 void PTXMCAsmStreamer::EmitFileDirective(StringRef Filename) {
@@ -489,11 +491,20 @@
=20
 // FIXME: should we inherit from MCAsmStreamer?
 bool PTXMCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo,
-                                              StringRef Filename){
+                                              StringRef Directory,
+                                              StringRef Filename) {
+  if (!Directory.empty()) {
+    if (sys::path::is_absolute(Filename))
+      return EmitDwarfFileDirective(FileNo, "", Filename);
+    SmallString<128> FullPathName =3D Directory;
+    sys::path::append(FullPathName, Filename);
+    return EmitDwarfFileDirective(FileNo, "", FullPathName);
+  }
+
   OS << "\t.file\t" << FileNo << ' ';
   PrintQuotedString(Filename, OS);
   EmitEOL();
-  return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
+  return this->MCStreamer::EmitDwarfFileDirective(FileNo, Directory, Filen=
ame);
 }
=20
 void PTXMCAsmStreamer::AddEncodingComment(const MCInst &Inst) {}
@@ -529,12 +540,13 @@
   EmitEOL();
 }
=20
-void PTXMCAsmStreamer::Finish() {}
+void PTXMCAsmStreamer::FinishImpl() {}
=20
 namespace llvm {
   MCStreamer *createPTXAsmStreamer(MCContext &Context,
                                    formatted_raw_ostream &OS,
                                    bool isVerboseAsm, bool useLoc, bool us=
eCFI,
+                                   bool useDwarfDirectory,
                                    MCInstPrinter *IP,
                                    MCCodeEmitter *CE, MCAsmBackend *MAB,
                                    bool ShowInst) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXMF=
InfoExtract.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXMFInfoExtract.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXMFInfoExtract.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -22,9 +22,11 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
=20
+using namespace llvm;
+
 // NOTE: PTXMFInfoExtract must after register allocation!
=20
-namespace llvm {
+namespace {
   /// PTXMFInfoExtract - PTX specific code to extract of PTX machine
   /// function information for PTXAsmPrinter
   ///
@@ -42,7 +44,7 @@
         return "PTX Machine Function Info Extractor";
       }
   }; // class PTXMFInfoExtract
-} // namespace llvm
+} // end anonymous namespace
=20
 using namespace llvm;
=20
@@ -56,7 +58,22 @@
   for (unsigned i =3D 0; i < MRI.getNumVirtRegs(); ++i) {
     unsigned Reg =3D TargetRegisterInfo::index2VirtReg(i);
     const TargetRegisterClass *TRC =3D MRI.getRegClass(Reg);
-    MFI->addVirtualRegister(TRC, Reg);
+    unsigned RegType;
+    if (TRC =3D=3D PTX::RegPredRegisterClass)
+      RegType =3D PTXRegisterType::Pred;
+    else if (TRC =3D=3D PTX::RegI16RegisterClass)
+      RegType =3D PTXRegisterType::B16;
+    else if (TRC =3D=3D PTX::RegI32RegisterClass)
+      RegType =3D PTXRegisterType::B32;
+    else if (TRC =3D=3D PTX::RegI64RegisterClass)
+      RegType =3D PTXRegisterType::B64;
+    else if (TRC =3D=3D PTX::RegF32RegisterClass)
+      RegType =3D PTXRegisterType::F32;
+    else if (TRC =3D=3D PTX::RegF64RegisterClass)
+      RegType =3D PTXRegisterType::F64;
+    else
+      llvm_unreachable("Unkown register class.");
+    MFI->addRegister(Reg, RegType, PTXRegisterSpace::Reg);
   }
=20
   return false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXMa=
chineFunctionInfo.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXMachineFunctionInfo.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXMachineFunctionInfo.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXMachineFuctionInfo.h - PTX machine function info -------*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- PTXMachineFuctionInfo.h - PTX machine function info ------*-=
 C++ -*-=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -30,20 +30,27 @@
 /// contains private PTX target-specific information for each MachineFunct=
ion.
 ///
 class PTXMachineFunctionInfo : public MachineFunctionInfo {
-private:
+  virtual void anchor();
   bool IsKernel;
   DenseSet<unsigned> RegArgs;
   DenseSet<unsigned> RegRets;
=20
-  typedef std::vector<unsigned> RegisterList;
-  typedef DenseMap<const TargetRegisterClass*, RegisterList> RegisterMap;
-  typedef DenseMap<unsigned, std::string> RegisterNameMap;
   typedef DenseMap<int, std::string> FrameMap;
=20
-  RegisterMap UsedRegs;
-  RegisterNameMap RegNames;
   FrameMap FrameSymbols;
=20
+  struct RegisterInfo {
+    unsigned Reg;
+    unsigned Type;
+    unsigned Space;
+    unsigned Offset;
+    unsigned Encoded;
+  };
+
+  typedef DenseMap<unsigned, RegisterInfo> RegisterInfoMap;
+
+  RegisterInfoMap RegInfo;
+
   PTXParamManager ParamManager;
=20
 public:
@@ -51,13 +58,7 @@
=20
   PTXMachineFunctionInfo(MachineFunction &MF)
     : IsKernel(false) {
-      UsedRegs[PTX::RegPredRegisterClass] =3D RegisterList();
-      UsedRegs[PTX::RegI16RegisterClass] =3D RegisterList();
-      UsedRegs[PTX::RegI32RegisterClass] =3D RegisterList();
-      UsedRegs[PTX::RegI64RegisterClass] =3D RegisterList();
-      UsedRegs[PTX::RegF32RegisterClass] =3D RegisterList();
-      UsedRegs[PTX::RegF64RegisterClass] =3D RegisterList();
-    }
+  }
=20
   /// getParamManager - Returns the PTXParamManager instance for this func=
tion.
   PTXParamManager& getParamManager() { return ParamManager; }
@@ -78,69 +79,106 @@
   reg_iterator retreg_begin() const { return RegRets.begin(); }
   reg_iterator retreg_end()   const { return RegRets.end(); }
=20
+  /// addRegister - Adds a virtual register to the set of all used registe=
rs
+  void addRegister(unsigned Reg, unsigned RegType, unsigned RegSpace) {
+    if (!RegInfo.count(Reg)) {
+      RegisterInfo Info;
+      Info.Reg =3D Reg;
+      Info.Type =3D RegType;
+      Info.Space =3D RegSpace;
+
+      // Determine register offset
+      Info.Offset =3D 0;
+      for(RegisterInfoMap::const_iterator i =3D RegInfo.begin(),
+          e =3D RegInfo.end(); i !=3D e; ++i) {
+        const RegisterInfo& RI =3D i->second;
+        if (RI.Space =3D=3D RegSpace)
+          if (RI.Space !=3D PTXRegisterSpace::Reg || RI.Type =3D=3D Info.T=
ype)
+            Info.Offset++;
+      }
+
+      // Encode the register data into a single register number
+      Info.Encoded =3D (Info.Offset << 6) | (Info.Type << 3) | Info.Space;
+
+      RegInfo[Reg] =3D Info;
+
+      if (RegSpace =3D=3D PTXRegisterSpace::Argument)
+        RegArgs.insert(Reg);
+      else if (RegSpace =3D=3D PTXRegisterSpace::Return)
+        RegRets.insert(Reg);
+    }
+  }
+
+  /// countRegisters - Returns the number of registers of the given type a=
nd
+  /// space.
+  unsigned countRegisters(unsigned RegType, unsigned RegSpace) const {
+    unsigned Count =3D 0;
+    for(RegisterInfoMap::const_iterator i =3D RegInfo.begin(), e =3D RegIn=
fo.end();
+        i !=3D e; ++i) {
+      const RegisterInfo& RI =3D i->second;
+      if (RI.Type =3D=3D RegType && RI.Space =3D=3D RegSpace)
+        Count++;
+    }
+    return Count;
+  }
+
+  /// getEncodedRegister - Returns the encoded value of the register.
+  unsigned getEncodedRegister(unsigned Reg) const {
+    return RegInfo.lookup(Reg).Encoded;
+  }
+
   /// addRetReg - Adds a register to the set of return-value registers.
   void addRetReg(unsigned Reg) {
     if (!RegRets.count(Reg)) {
       RegRets.insert(Reg);
-      std::string name;
-      name =3D "%ret";
-      name +=3D utostr(RegRets.size() - 1);
-      RegNames[Reg] =3D name;
     }
   }
=20
   /// addArgReg - Adds a register to the set of function argument register=
s.
   void addArgReg(unsigned Reg) {
     RegArgs.insert(Reg);
-    std::string name;
-    name =3D "%param";
-    name +=3D utostr(RegArgs.size() - 1);
-    RegNames[Reg] =3D name;
-  }
-
-  /// addVirtualRegister - Adds a virtual register to the set of all used
-  /// registers in the function.
-  void addVirtualRegister(const TargetRegisterClass *TRC, unsigned Reg) {
-    std::string name;
-
-    // Do not count registers that are argument/return registers.
-    if (!RegRets.count(Reg) && !RegArgs.count(Reg)) {
-      UsedRegs[TRC].push_back(Reg);
-      if (TRC =3D=3D PTX::RegPredRegisterClass)
-        name =3D "%p";
-      else if (TRC =3D=3D PTX::RegI16RegisterClass)
-        name =3D "%rh";
-      else if (TRC =3D=3D PTX::RegI32RegisterClass)
-        name =3D "%r";
-      else if (TRC =3D=3D PTX::RegI64RegisterClass)
-        name =3D "%rd";
-      else if (TRC =3D=3D PTX::RegF32RegisterClass)
-        name =3D "%f";
-      else if (TRC =3D=3D PTX::RegF64RegisterClass)
-        name =3D "%fd";
-      else
-        llvm_unreachable("Invalid register class");
-
-      name +=3D utostr(UsedRegs[TRC].size() - 1);
-      RegNames[Reg] =3D name;
-    }
   }
=20
   /// getRegisterName - Returns the name of the specified virtual register=
. This
   /// name is used during PTX emission.
-  const char *getRegisterName(unsigned Reg) const {
-    if (RegNames.count(Reg))
-      return RegNames.find(Reg)->second.c_str();
+  std::string getRegisterName(unsigned Reg) const {
+    if (RegInfo.count(Reg)) {
+      const RegisterInfo& RI =3D RegInfo.lookup(Reg);
+      std::string Name;
+      raw_string_ostream NameStr(Name);
+      decodeRegisterName(NameStr, RI.Encoded);
+      NameStr.flush();
+      return Name;
+    }
     else if (Reg =3D=3D PTX::NoRegister)
       return "%noreg";
     else
       llvm_unreachable("Register not in register name map");
   }
=20
-  /// getNumRegistersForClass - Returns the number of virtual registers th=
at are
-  /// used for the specified register class.
-  unsigned getNumRegistersForClass(const TargetRegisterClass *TRC) const {
-    return UsedRegs.lookup(TRC).size();
+  /// getEncodedRegisterName - Returns the name of the encoded register.
+  std::string getEncodedRegisterName(unsigned EncodedReg) const {
+    std::string Name;
+    raw_string_ostream NameStr(Name);
+    decodeRegisterName(NameStr, EncodedReg);
+    NameStr.flush();
+    return Name;
+  }
+
+  /// getRegisterType - Returns the type of the specified virtual register.
+  unsigned getRegisterType(unsigned Reg) const {
+    if (RegInfo.count(Reg))
+      return RegInfo.lookup(Reg).Type;
+    else
+      llvm_unreachable("Unknown register");
+  }
+
+  /// getOffsetForRegister - Returns the offset of the virtual register
+  unsigned getOffsetForRegister(unsigned Reg) const {
+    if (RegInfo.count(Reg))
+      return RegInfo.lookup(Reg).Offset;
+    else
+      return 0;
   }
=20
   /// getFrameSymbol - Returns the symbol name for the given FrameIndex.
@@ -148,13 +186,13 @@
     if (FrameSymbols.count(FrameIndex)) {
       return FrameSymbols.lookup(FrameIndex).c_str();
     } else {
-      std::string Name =3D "__local";
-      Name +=3D utostr(FrameIndex);
+      std::string Name          =3D "__local";
+      Name                     +=3D utostr(FrameIndex);
       // The whole point of caching this name is to ensure the pointer we =
pass
       // to any getExternalSymbol() calls will remain valid for the lifeti=
me of
       // the back-end instance. This is to work around an issue in Selecti=
onDAG
       // where symbol names are expected to be life-long strings.
-      FrameSymbols[FrameIndex] =3D Name;
+      FrameSymbols[FrameIndex]  =3D Name;
       return FrameSymbols[FrameIndex].c_str();
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXPa=
ramManager.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXParamManager.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXParamManager.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXParamManager.cpp - Manager for .param variables -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PTXParamManager.cpp - Manager for .param variables ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "PTXParamManager.h"
 #include "PTX.h"
-#include "PTXParamManager.h"
 #include "llvm/ADT/StringExtras.h"
=20
 using namespace llvm;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXPa=
ramManager.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXParamManager.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXParamManager.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXParamManager.h - Manager for .param variables ----------*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- PTXParamManager.h - Manager for .param variables --------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -17,6 +17,7 @@
=20
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
+#include <string>
=20
 namespace llvm {
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXRe=
gAlloc.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXRegAlloc.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXRegAlloc.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -24,10 +24,7 @@
   class PTXRegAlloc : public MachineFunctionPass {
   public:
     static char ID;
-    PTXRegAlloc() : MachineFunctionPass(ID) {
-      initializePHIEliminationPass(*PassRegistry::getPassRegistry());
-      initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegist=
ry());
-    }
+    PTXRegAlloc() : MachineFunctionPass(ID) {}
=20
     virtual const char* getPassName() const {
       return "PTX Register Allocator";
@@ -35,8 +32,6 @@
=20
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
-      AU.addRequiredID(PHIEliminationID);
-      AU.addRequiredID(TwoAddressInstructionPassID);
       MachineFunctionPass::getAnalysisUsage(AU);
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXRe=
gisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXRegisterInfo.cpp - PTX Register Information --------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- PTXRegisterInfo.cpp - PTX Register Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "PTXRegisterInfo.h"
 #include "PTX.h"
-#include "PTXRegisterInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
@@ -31,44 +31,8 @@
   : PTXGenRegisterInfo(0), TII(tii) {
 }
=20
-void PTXRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
-                                          int SPAdj,
-                                          RegScavenger *RS) const {
-  unsigned Index;
-  MachineInstr &MI =3D *II;
-  //MachineBasicBlock &MBB =3D *MI.getParent();
-  //DebugLoc dl =3D MI.getDebugLoc();
-  //MachineRegisterInfo &MRI =3D MI.getParent()->getParent()->getRegInfo();
-
-  //unsigned Reg =3D MRI.createVirtualRegister(PTX::RegF32RegisterClass);
-
+void PTXRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator /*II=
*/,
+                                          int /*SPAdj*/,
+                                          RegScavenger * /*RS*/) const {
   llvm_unreachable("FrameIndex should have been previously eliminated!");
-
-  Index =3D 0;
-  while (!MI.getOperand(Index).isFI()) {
-    ++Index;
-    assert(Index < MI.getNumOperands() &&
-           "Instr does not have a FrameIndex operand!");
-  }
-
-  int FrameIndex =3D MI.getOperand(Index).getIndex();
-
-  DEBUG(dbgs() << "eliminateFrameIndex: " << MI);
-  DEBUG(dbgs() << "- SPAdj: " << SPAdj << "\n");
-  DEBUG(dbgs() << "- FrameIndex: " << FrameIndex << "\n");
-
-  //MachineInstr* MI2 =3D BuildMI(MBB, II, dl, TII.get(PTX::LOAD_LOCAL_F32=
))
-  //.addReg(Reg, RegState::Define).addImm(FrameIndex);
-  //if (MI2->findFirstPredOperandIdx() =3D=3D -1) {
-  //  MI2->addOperand(MachineOperand::CreateReg(PTX::NoRegister, /*IsDef=
=3D*/false));
-  //  MI2->addOperand(MachineOperand::CreateImm(PTX::PRED_NORMAL));
-  //}
-  //MI2->dump();
-
-  //MachineOperand ESOp =3D MachineOperand::CreateES("__local__");
-
-  // This frame index is post stack slot re-use assignments
-  //MI.getOperand(Index).ChangeToRegister(Reg, false);
-  MI.getOperand(Index).ChangeToImmediate(FrameIndex);
-  //MI.getOperand(Index) =3D ESOp;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXRe=
gisterInfo.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXRegisterInfo.h - PTX Register Information Impl --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PTXRegisterInfo.h - PTX Register Information Impl -------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -32,9 +32,9 @@
   PTXRegisterInfo(PTXTargetMachine &TM,
                   const TargetInstrInfo &tii);
=20
-  virtual const unsigned
+  virtual const uint16_t
     *getCalleeSavedRegs(const MachineFunction *MF =3D 0) const {
-    static const unsigned CalleeSavedRegs[] =3D { 0 };
+    static const uint16_t CalleeSavedRegs[] =3D { 0 };
     return CalleeSavedRegs; // save nothing
   }
=20
@@ -49,7 +49,6 @@
=20
   virtual unsigned getFrameRegister(const MachineFunction &MF) const {
     llvm_unreachable("PTX does not have a frame register");
-    return 0;
   }
 }; // struct PTXRegisterInfo
 } // namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXRe=
gisterInfo.td
--- a/head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXRegisterInfo.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,5 +1,4 @@
-
-//=3D=3D=3D- PTXRegisterInfo.td - PTX Register defs ----------------*- tbl=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- PTXRegisterInfo.td - PTX Register defs -------------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXSe=
lectionDAGInfo.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXSelectionDAGInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXSelectionDAGInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -70,7 +70,7 @@
                              DAG.getNode(ISD::ADD, dl, PointerType, Src,
                                          DAG.getConstant(SrcOff, PointerTy=
pe)),
                              SrcPtrInfo.getWithOffset(SrcOff), isVolatile,
-                             false, 0);
+                             false, false, 0);
       TFOps[i] =3D Loads[i].getValue(1);
       SrcOff +=3D VTSize;
     }
@@ -108,7 +108,8 @@
     Loads[i] =3D DAG.getLoad(VT, dl, Chain,
                            DAG.getNode(ISD::ADD, dl, PointerType, Src,
                                        DAG.getConstant(SrcOff, PointerType=
)),
-                           SrcPtrInfo.getWithOffset(SrcOff), false, false,=
 0);
+                           SrcPtrInfo.getWithOffset(SrcOff), false, false,
+                           false, 0);
     TFOps[i] =3D Loads[i].getValue(1);
     ++i;
     SrcOff +=3D VTSize;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXSu=
btarget.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXSubtarget.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXSubtarget.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PTXSubtarget.cpp - PTX Subtarget Information ---------------*=
- C++ -*-=3D//
+//=3D=3D=3D-- PTXSubtarget.cpp - PTX Subtarget Information ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -22,6 +22,8 @@
=20
 using namespace llvm;
=20
+void PTXSubtarget::anchor() { }
+
 PTXSubtarget::PTXSubtarget(const std::string &TT, const std::string &CPU,
                            const std::string &FS, bool is64Bit)
   : PTXGenSubtargetInfo(TT, CPU, FS),
@@ -57,10 +59,10 @@
=20
 std::string PTXSubtarget::getPTXVersionString() const {
   switch(PTXVersion) {
-    default: llvm_unreachable("Unknown PTX version");
     case PTX_VERSION_2_0: return "2.0";
     case PTX_VERSION_2_1: return "2.1";
     case PTX_VERSION_2_2: return "2.2";
     case PTX_VERSION_2_3: return "2.3";
   }
+  llvm_unreachable("Invalid PTX version");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXSu=
btarget.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXSubtarget.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXSubtarget.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D-- PTXSubtarget.h - Define Subtarget for the PTX ---------*-=
 C++ -*--=3D=3D=3D//
+//=3D=3D=3D-- PTXSubtarget.h - Define Subtarget for the PTX -----------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,6 +23,7 @@
 class StringRef;
=20
   class PTXSubtarget : public PTXGenSubtargetInfo {
+      virtual void anchor();=20
     public:
=20
       /**
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXTa=
rgetMachine.cpp
--- a/head/contrib/llvm/lib/Target/PTX/PTXTargetMachine.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXTargetMachine.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -11,13 +11,12 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "PTXTargetMachine.h"
 #include "PTX.h"
-#include "PTXTargetMachine.h"
 #include "llvm/PassManager.h"
 #include "llvm/Analysis/Passes.h"
 #include "llvm/Analysis/Verifier.h"
 #include "llvm/Assembly/PrintModulePass.h"
-#include "llvm/ADT/OwningPtr.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
@@ -26,6 +25,7 @@
 #include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetData.h"
@@ -37,8 +37,6 @@
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetSubtargetInfo.h"
 #include "llvm/Transforms/Scalar.h"
-#include "llvm/Support/Debug.h"
-#include "llvm/Support/TargetRegistry.h"
=20
=20
 using namespace llvm;
@@ -46,7 +44,7 @@
 namespace llvm {
   MCStreamer *createPTXAsmStreamer(MCContext &Ctx, formatted_raw_ostream &=
OS,
                                    bool isVerboseAsm, bool useLoc,
-                                   bool useCFI,
+                                   bool useCFI, bool useDwarfDirectory,
                                    MCInstPrinter *InstPrint,
                                    MCCodeEmitter *CE,
                                    MCAsmBackend *MAB,
@@ -67,29 +65,16 @@
     "e-p:32:32-i64:32:32-f64:32:32-v128:32:128-v64:32:64-n32:64";
   const char* DataLayout64 =3D
     "e-p:64:64-i64:32:32-f64:32:32-v128:32:128-v64:32:64-n32:64";
-
-  // Copied from LLVMTargetMachine.cpp
-  void printNoVerify(PassManagerBase &PM, const char *Banner) {
-    if (PrintMachineCode)
-      PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
-  }
-
-  void printAndVerify(PassManagerBase &PM,
-                      const char *Banner) {
-    if (PrintMachineCode)
-      PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
-
-    //if (VerifyMachineCode)
-    //  PM.add(createMachineVerifierPass(Banner));
-  }
 }
=20
 // DataLayout and FrameLowering are filled with dummy data
 PTXTargetMachine::PTXTargetMachine(const Target &T,
                                    StringRef TT, StringRef CPU, StringRef =
FS,
+                                   const TargetOptions &Options,
                                    Reloc::Model RM, CodeModel::Model CM,
+                                   CodeGenOpt::Level OL,
                                    bool is64Bit)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     DataLayout(is64Bit ? DataLayout64 : DataLayout32),
     Subtarget(TT, CPU, FS, is64Bit),
     FrameLowering(Subtarget),
@@ -98,276 +83,83 @@
     TLInfo(*this) {
 }
=20
+void PTX32TargetMachine::anchor() { }
+
 PTX32TargetMachine::PTX32TargetMachine(const Target &T, StringRef TT,
                                        StringRef CPU, StringRef FS,
-                                       Reloc::Model RM, CodeModel::Model C=
M)
-  : PTXTargetMachine(T, TT, CPU, FS, RM, CM, false) {
+                                       const TargetOptions &Options,
+                                       Reloc::Model RM, CodeModel::Model C=
M,
+                                       CodeGenOpt::Level OL)
+  : PTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {
 }
=20
+void PTX64TargetMachine::anchor() { }
+
 PTX64TargetMachine::PTX64TargetMachine(const Target &T, StringRef TT,
                                        StringRef CPU, StringRef FS,
-                                       Reloc::Model RM, CodeModel::Model C=
M)
-  : PTXTargetMachine(T, TT, CPU, FS, RM, CM, true) {
+                                       const TargetOptions &Options,
+                                       Reloc::Model RM, CodeModel::Model C=
M,
+                                       CodeGenOpt::Level OL)
+  : PTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {
 }
=20
-bool PTXTargetMachine::addInstSelector(PassManagerBase &PM,
-                                       CodeGenOpt::Level OptLevel) {
-  PM.add(createPTXISelDag(*this, OptLevel));
+namespace llvm {
+/// PTX Code Generator Pass Configuration Options.
+class PTXPassConfig : public TargetPassConfig {
+public:
+  PTXPassConfig(PTXTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  PTXTargetMachine &getPTXTargetMachine() const {
+      return getTM<PTXTargetMachine>();
+  }
+
+  bool addInstSelector();
+  FunctionPass *createTargetRegisterAllocator(bool);
+  void addOptimizedRegAlloc(FunctionPass *RegAllocPass);
+  bool addPostRegAlloc();
+  void addMachineLateOptimization();
+  bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *PTXTargetMachine::createPassConfig(PassManagerBase &PM) {
+  PTXPassConfig *PassConfig =3D new PTXPassConfig(this, PM);
+  PassConfig->disablePass(PrologEpilogCodeInserterID);
+  return PassConfig;
+}
+
+bool PTXPassConfig::addInstSelector() {
+  PM.add(createPTXISelDag(getPTXTargetMachine(), getOptLevel()));
   return false;
 }
=20
-bool PTXTargetMachine::addPostRegAlloc(PassManagerBase &PM,
-                                       CodeGenOpt::Level OptLevel) {
+FunctionPass *PTXPassConfig::createTargetRegisterAllocator(bool /*Optimize=
d*/) {
+  return createPTXRegisterAllocator();
+}
+
+// Modify the optimized compilation path to bypass optimized register allo=
ction.
+void PTXPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
+  addFastRegAlloc(RegAllocPass);
+}
+
+bool PTXPassConfig::addPostRegAlloc() {
   // PTXMFInfoExtract must after register allocation!
-  //PM.add(createPTXMFInfoExtract(*this, OptLevel));
+  //PM.add(createPTXMFInfoExtract(getPTXTargetMachine()));
   return false;
 }
=20
-bool PTXTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
-                                           formatted_raw_ostream &Out,
-                                           CodeGenFileType FileType,
-                                           CodeGenOpt::Level OptLevel,
-                                           bool DisableVerify) {
-  // This is mostly based on LLVMTargetMachine::addPassesToEmitFile
+/// Add passes that optimize machine instructions after register allocatio=
n.
+void PTXPassConfig::addMachineLateOptimization() {
+  if (addPass(BranchFolderPassID) !=3D &NoPassID)
+    printAndVerify("After BranchFolding");
=20
-  // Add common CodeGen passes.
-  MCContext *Context =3D 0;
-  if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
-    return true;
-  assert(Context !=3D 0 && "Failed to get MCContext");
-
-  if (hasMCSaveTempLabels())
-    Context->setAllowTemporaryLabels(false);
-
-  const MCAsmInfo &MAI =3D *getMCAsmInfo();
-  const MCSubtargetInfo &STI =3D getSubtarget<MCSubtargetInfo>();
-  OwningPtr<MCStreamer> AsmStreamer;
-
-  switch (FileType) {
-  default: return true;
-  case CGFT_AssemblyFile: {
-    MCInstPrinter *InstPrinter =3D
-      getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
-
-    // Create a code emitter if asked to show the encoding.
-    MCCodeEmitter *MCE =3D 0;
-    MCAsmBackend *MAB =3D 0;
-
-    MCStreamer *S =3D getTarget().createAsmStreamer(*Context, Out,
-                                                  true, /* verbose asm */
-                                                  hasMCUseLoc(),
-                                                  hasMCUseCFI(),
-                                                  InstPrinter,
-                                                  MCE, MAB,
-                                                  false /* show MC encodin=
g */);
-    AsmStreamer.reset(S);
-    break;
-  }
-  case CGFT_ObjectFile: {
-    llvm_unreachable("Object file emission is not supported with PTX");
-  }
-  case CGFT_Null:
-    // The Null output is intended for use for performance analysis and te=
sting,
-    // not real users.
-    AsmStreamer.reset(createNullStreamer(*Context));
-    break;
-  }
-
-  // MC Logging
-  //AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
-
-  // Create the AsmPrinter, which takes ownership of AsmStreamer if succes=
sful.
-  FunctionPass *Printer =3D getTarget().createAsmPrinter(*this, *AsmStream=
er);
-  if (Printer =3D=3D 0)
-    return true;
-
-  // If successful, createAsmPrinter took ownership of AsmStreamer.
-  AsmStreamer.take();
-
-  PM.add(Printer);
-
-  PM.add(createGCInfoDeleter());
-  return false;
+  if (addPass(TailDuplicateID) !=3D &NoPassID)
+    printAndVerify("After TailDuplicate");
 }
=20
-bool PTXTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
-                                              CodeGenOpt::Level OptLevel,
-                                              bool DisableVerify,
-                                              MCContext *&OutContext) {
-  // Add standard LLVM codegen passes.
-  // This is derived from LLVMTargetMachine::addCommonCodeGenPasses, with =
some
-  // modifications for the PTX target.
-
-  // Standard LLVM-Level Passes.
-
-  // Basic AliasAnalysis support.
-  // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
-  // BasicAliasAnalysis wins if they disagree. This is intended to help
-  // support "obvious" type-punning idioms.
-  PM.add(createTypeBasedAliasAnalysisPass());
-  PM.add(createBasicAliasAnalysisPass());
-
-  // Before running any passes, run the verifier to determine if the input
-  // coming from the front-end and/or optimizer is valid.
-  if (!DisableVerify)
-    PM.add(createVerifierPass());
-
-  // Run loop strength reduction before anything else.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    PM.add(createLoopStrengthReducePass(getTargetLowering()));
-    //PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs=
()));
-  }
-
-  PM.add(createGCLoweringPass());
-
-  // Make sure that no unreachable blocks are instruction selected.
-  PM.add(createUnreachableBlockEliminationPass());
-
-  PM.add(createLowerInvokePass(getTargetLowering()));
-  // The lower invoke pass may create unreachable code. Remove it.
-  PM.add(createUnreachableBlockEliminationPass());
-
-  if (OptLevel !=3D CodeGenOpt::None)
-    PM.add(createCodeGenPreparePass(getTargetLowering()));
-
-  PM.add(createStackProtectorPass(getTargetLowering()));
-
-  addPreISel(PM, OptLevel);
-
-  //PM.add(createPrintFunctionPass("\n\n"
-  //                               "*** Final LLVM Code input to ISel ***\=
n",
-  //                               &dbgs()));
-
-  // All passes which modify the LLVM IR are now complete; run the verifier
-  // to ensure that the IR is valid.
-  if (!DisableVerify)
-    PM.add(createVerifierPass());
-
-  // Standard Lower-Level Passes.
-
-  // Install a MachineModuleInfo class, which is an immutable pass that ho=
lds
-  // all the per-module stuff we're generating, including MCContext.
-  MachineModuleInfo *MMI =3D new MachineModuleInfo(*getMCAsmInfo(),
-                                                 *getRegisterInfo(),
-                                    &getTargetLowering()->getObjFileLoweri=
ng());
-  PM.add(MMI);
-  OutContext =3D &MMI->getContext(); // Return the MCContext specifically =
by-ref.
-
-  // Set up a MachineFunction for the rest of CodeGen to work on.
-  PM.add(new MachineFunctionAnalysis(*this, OptLevel));
-
-  // Ask the target for an isel.
-  if (addInstSelector(PM, OptLevel))
-    return true;
-
-  // Print the instruction selected machine code...
-  printAndVerify(PM, "After Instruction Selection");
-
-  // Expand pseudo-instructions emitted by ISel.
-  PM.add(createExpandISelPseudosPass());
-
-  // Pre-ra tail duplication.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    PM.add(createTailDuplicatePass(true));
-    printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
-  }
-
-  // Optimize PHIs before DCE: removing dead PHI cycles may make more
-  // instructions dead.
-  if (OptLevel !=3D CodeGenOpt::None)
-    PM.add(createOptimizePHIsPass());
-
-  // If the target requests it, assign local variables to stack slots rela=
tive
-  // to one another and simplify frame index references where possible.
-  PM.add(createLocalStackSlotAllocationPass());
-
-  if (OptLevel !=3D CodeGenOpt::None) {
-    // With optimization, dead code should already be eliminated. However
-    // there is one known exception: lowered code for arguments that are o=
nly
-    // used by tail calls, where the tail calls reuse the incoming stack
-    // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
-    PM.add(createDeadMachineInstructionElimPass());
-    printAndVerify(PM, "After codegen DCE pass");
-
-    PM.add(createMachineLICMPass());
-    PM.add(createMachineCSEPass());
-    PM.add(createMachineSinkingPass());
-    printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
-
-    PM.add(createPeepholeOptimizerPass());
-    printAndVerify(PM, "After codegen peephole optimization pass");
-  }
-
-  // Run pre-ra passes.
-  if (addPreRegAlloc(PM, OptLevel))
-    printAndVerify(PM, "After PreRegAlloc passes");
-
-  // Perform register allocation.
-  PM.add(createPTXRegisterAllocator());
-  printAndVerify(PM, "After Register Allocation");
-
-  // Perform stack slot coloring and post-ra machine LICM.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    // FIXME: Re-enable coloring with register when it's capable of adding
-    // kill markers.
-    PM.add(createStackSlotColoringPass(false));
-
-    // FIXME: Post-RA LICM has asserts that fire on virtual registers.
-    // Run post-ra machine LICM to hoist reloads / remats.
-    //if (!DisablePostRAMachineLICM)
-    //  PM.add(createMachineLICMPass(false));
-
-    printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
-  }
-
-  // Run post-ra passes.
-  if (addPostRegAlloc(PM, OptLevel))
-    printAndVerify(PM, "After PostRegAlloc passes");
-
-  PM.add(createExpandPostRAPseudosPass());
-  printAndVerify(PM, "After ExpandPostRAPseudos");
-
-  // Insert prolog/epilog code.  Eliminate abstract frame index references=
...
-  PM.add(createPrologEpilogCodeInserter());
-  printAndVerify(PM, "After PrologEpilogCodeInserter");
-
-  // Run pre-sched2 passes.
-  if (addPreSched2(PM, OptLevel))
-    printAndVerify(PM, "After PreSched2 passes");
-
-  // Second pass scheduler.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    PM.add(createPostRAScheduler(OptLevel));
-    printAndVerify(PM, "After PostRAScheduler");
-  }
-
-  // Branch folding must be run after regalloc and prolog/epilog insertion.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
-    printNoVerify(PM, "After BranchFolding");
-  }
-
-  // Tail duplication.
-  if (OptLevel !=3D CodeGenOpt::None) {
-    PM.add(createTailDuplicatePass(false));
-    printNoVerify(PM, "After TailDuplicate");
-  }
-
-  PM.add(createGCMachineCodeAnalysisPass());
-
-  //if (PrintGCInfo)
-  //  PM.add(createGCInfoPrinter(dbgs()));
-
-  if (OptLevel !=3D CodeGenOpt::None) {
-    PM.add(createCodePlacementOptPass());
-    printNoVerify(PM, "After CodePlacementOpt");
-  }
-
-  if (addPreEmitPass(PM, OptLevel))
-    printNoVerify(PM, "After PreEmit passes");
-
-  PM.add(createPTXMFInfoExtract(*this, OptLevel));
-  PM.add(createPTXFPRoundingModePass(*this, OptLevel));
-
-  return false;
+bool PTXPassConfig::addPreEmitPass() {
+  PM.add(createPTXMFInfoExtract(getPTXTargetMachine(), getOptLevel()));
+  PM.add(createPTXFPRoundingModePass(getPTXTargetMachine(), getOptLevel())=
);
+  return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PTX/PTXTa=
rgetMachine.h
--- a/head/contrib/llvm/lib/Target/PTX/PTXTargetMachine.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PTX/PTXTargetMachine.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -35,8 +35,9 @@
=20
   public:
     PTXTargetMachine(const Target &T, StringRef TT,
-                     StringRef CPU, StringRef FS,
+                     StringRef CPU, StringRef FS, const TargetOptions &Opt=
ions,
                      Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL,
                      bool is64Bit);
=20
     virtual const TargetData *getTargetData() const { return &DataLayout; }
@@ -58,22 +59,9 @@
=20
     virtual const PTXSubtarget *getSubtargetImpl() const { return &Subtarg=
et; }
=20
-    virtual bool addInstSelector(PassManagerBase &PM,
-                                 CodeGenOpt::Level OptLevel);
-    virtual bool addPostRegAlloc(PassManagerBase &PM,
-                                 CodeGenOpt::Level OptLevel);
-
-    // We override this method to supply our own set of codegen passes.
-    virtual bool addPassesToEmitFile(PassManagerBase &,
-                                     formatted_raw_ostream &,
-                                     CodeGenFileType,
-                                     CodeGenOpt::Level,
-                                     bool =3D true);
-
     // Emission of machine code through JITCodeEmitter is not supported.
     virtual bool addPassesToEmitMachineCode(PassManagerBase &,
                                             JITCodeEmitter &,
-                                            CodeGenOpt::Level,
                                             bool =3D true) {
       return true;
     }
@@ -82,32 +70,33 @@
     virtual bool addPassesToEmitMC(PassManagerBase &,
                                    MCContext *&,
                                    raw_ostream &,
-                                   CodeGenOpt::Level,
                                    bool =3D true) {
       return true;
     }
=20
-  private:
-
-    bool addCommonCodeGenPasses(PassManagerBase &, CodeGenOpt::Level,
-                                bool DisableVerify, MCContext *&OutCtx);
+    // Pass Pipeline Configuration
+    virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
 }; // class PTXTargetMachine
=20
=20
 class PTX32TargetMachine : public PTXTargetMachine {
+  virtual void anchor();
 public:
=20
   PTX32TargetMachine(const Target &T, StringRef TT,
-                     StringRef CPU, StringRef FS,
-                     Reloc::Model RM, CodeModel::Model CM);
+                     StringRef CPU, StringRef FS, const TargetOptions &Opt=
ions,
+                     Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL);
 }; // class PTX32TargetMachine
=20
 class PTX64TargetMachine : public PTXTargetMachine {
+  virtual void anchor();
 public:
=20
   PTX64TargetMachine(const Target &T, StringRef TT,
-                     StringRef CPU, StringRef FS,
-                     Reloc::Model RM, CodeModel::Model CM);
+                     StringRef CPU, StringRef FS, const TargetOptions &Opt=
ions,
+                     Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL);
 }; // class PTX32TargetMachine
=20
 } // namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/I=
nstPrinter/PPCInstPrinter.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -17,16 +17,12 @@
 #include "MCTargetDesc/PPCPredicates.h"
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCInstrInfo.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
=20
-#define GET_INSTRUCTION_NAME
 #include "PPCGenAsmWriter.inc"
=20
-StringRef PPCInstPrinter::getOpcodeName(unsigned Opcode) const {
-  return getInstructionName(Opcode);
-}
-
 void PPCInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
   OS << getRegisterName(RegNo);
 }
@@ -94,7 +90,6 @@
   unsigned Code =3D MI->getOperand(OpNo).getImm();
   if (StringRef(Modifier) =3D=3D "cc") {
     switch ((PPC::Predicate)Code) {
-    default: assert(0 && "Invalid predicate");
     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
     case PPC::PRED_LT: O << "lt"; return;
     case PPC::PRED_LE: O << "le"; return;
@@ -175,7 +170,7 @@
   unsigned CCReg =3D MI->getOperand(OpNo).getReg();
   unsigned RegNo;
   switch (CCReg) {
-  default: assert(0 && "Unknown CR register");
+  default: llvm_unreachable("Unknown CR register");
   case PPC::CR0: RegNo =3D 0; break;
   case PPC::CR1: RegNo =3D 1; break;
   case PPC::CR2: RegNo =3D 2; break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/I=
nstPrinter/PPCInstPrinter.h
--- a/head/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/InstPrinter/PPCInstPrinter.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCInstPrinter.h - Convert PPC MCInst to assembly syntax ---=
-------=3D=3D=3D//
+//=3D=3D=3D- PPCInstPrinter.h - Convert PPC MCInst to assembly syntax -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -24,8 +24,9 @@
   // 0 -> AIX, 1 -> Darwin.
   unsigned SyntaxVariant;
 public:
-  PPCInstPrinter(const MCAsmInfo &MAI, unsigned syntaxVariant)
-    : MCInstPrinter(MAI), SyntaxVariant(syntaxVariant) {}
+  PPCInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                 const MCRegisterInfo &MRI, unsigned syntaxVariant)
+    : MCInstPrinter(MAI, MII, MRI), SyntaxVariant(syntaxVariant) {}
  =20
   bool isDarwinSyntax() const {
     return SyntaxVariant =3D=3D 1;
@@ -33,9 +34,6 @@
  =20
   virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
   virtual void printInst(const MCInst *MI, raw_ostream &O, StringRef Annot=
);
-  virtual StringRef getOpcodeName(unsigned Opcode) const;
- =20
-  static const char *getInstructionName(unsigned Opcode);
  =20
   // Autogenerated by tblgen.
   void printInstruction(const MCInst *MI, raw_ostream &O);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/M=
CTargetDesc/PPCAsmBackend.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCAsmBackend.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -7,10 +7,11 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "llvm/MC/MCAsmBackend.h"
 #include "MCTargetDesc/PPCMCTargetDesc.h"
 #include "MCTargetDesc/PPCFixupKinds.h"
+#include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCELFObjectWriter.h"
+#include "llvm/MC/MCFixupKindInfo.h"
 #include "llvm/MC/MCMachObjectWriter.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/MC/MCObjectWriter.h"
@@ -57,13 +58,6 @@
                         MCValue Target, uint64_t &FixedValue) {}
 };
=20
-class PPCELFObjectWriter : public MCELFObjectTargetWriter {
-public:
-  PPCELFObjectWriter(bool Is64Bit, Triple::OSType OSType, uint16_t EMachin=
e,
-                     bool HasRelocationAddend, bool isLittleEndian)
-    : MCELFObjectTargetWriter(Is64Bit, OSType, EMachine, HasRelocationAdde=
nd) {}
-};
-
 class PPCAsmBackend : public MCAsmBackend {
 const Target &TheTarget;
 public:
@@ -80,33 +74,42 @@
       { "fixup_ppc_ha16",        16,     16,   0 },
       { "fixup_ppc_lo14",        16,     14,   0 }
     };
- =20
+
     if (Kind < FirstTargetFixupKind)
       return MCAsmBackend::getFixupKindInfo(Kind);
- =20
+
     assert(unsigned(Kind - FirstTargetFixupKind) < getNumFixupKinds() &&
            "Invalid kind!");
     return Infos[Kind - FirstTargetFixupKind];
   }
- =20
-  bool MayNeedRelaxation(const MCInst &Inst) const {
+
+  bool mayNeedRelaxation(const MCInst &Inst) const {
     // FIXME.
     return false;
   }
- =20
-  void RelaxInstruction(const MCInst &Inst, MCInst &Res) const {
+
+  bool fixupNeedsRelaxation(const MCFixup &Fixup,
+                            uint64_t Value,
+                            const MCInstFragment *DF,
+                            const MCAsmLayout &Layout) const {
     // FIXME.
-    assert(0 && "RelaxInstruction() unimplemented");
+    llvm_unreachable("relaxInstruction() unimplemented");
   }
- =20
-  bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const {
+
+
+  void relaxInstruction(const MCInst &Inst, MCInst &Res) const {
+    // FIXME.
+    llvm_unreachable("relaxInstruction() unimplemented");
+  }
+
+  bool writeNopData(uint64_t Count, MCObjectWriter *OW) const {
     // FIXME: Zero fill for now. That's not right, but at least will get t=
he
     // section size right.
     for (uint64_t i =3D 0; i !=3D Count; ++i)
       OW->Write8(0);
     return true;
-  }     =20
- =20
+  }
+
   unsigned getPointerSize() const {
     StringRef Name =3D TheTarget.getName();
     if (Name =3D=3D "ppc64") return 8;
@@ -122,12 +125,12 @@
   class DarwinPPCAsmBackend : public PPCAsmBackend {
   public:
     DarwinPPCAsmBackend(const Target &T) : PPCAsmBackend(T) { }
-   =20
-    void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+
+    void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
                     uint64_t Value) const {
-      assert(0 && "UNIMP");
+      llvm_unreachable("UNIMP");
     }
-   =20
+
     MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
       bool is64 =3D getPointerSize() =3D=3D 8;
       return createMachObjectWriter(new PPCMachObjectWriter(
@@ -137,19 +140,19 @@
                                       object::mach::CSPPC_ALL),
                                     OS, /*IsLittleEndian=3D*/false);
     }
-   =20
+
     virtual bool doesSectionRequireSymbols(const MCSection &Section) const=
 {
       return false;
     }
   };
=20
   class ELFPPCAsmBackend : public PPCAsmBackend {
-    Triple::OSType OSType;
+    uint8_t OSABI;
   public:
-    ELFPPCAsmBackend(const Target &T, Triple::OSType OSType) :
-      PPCAsmBackend(T), OSType(OSType) { }
-   =20
-    void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+    ELFPPCAsmBackend(const Target &T, uint8_t OSABI) :
+      PPCAsmBackend(T), OSABI(OSABI) { }
+
+    void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
                     uint64_t Value) const {
       Value =3D adjustFixupValue(Fixup.getKind(), Value);
       if (!Value) return;           // Doesn't change encoding.
@@ -162,17 +165,12 @@
       for (unsigned i =3D 0; i !=3D 4; ++i)
         Data[Offset + i] |=3D uint8_t((Value >> ((4 - i - 1)*8)) & 0xff);
     }
-   =20
+
     MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
       bool is64 =3D getPointerSize() =3D=3D 8;
-      return createELFObjectWriter(new PPCELFObjectWriter(
-                                      /*Is64Bit=3D*/is64,
-                                      OSType,
-                                      is64 ? ELF::EM_PPC64 : ELF::EM_PPC, =
                                    =20
-                                      /*addend*/ true, /*isLittleEndian*/ =
false),
-                                   OS, /*IsLittleEndian=3D*/false);
+      return createPPCELFObjectWriter(OS, is64, OSABI);
     }
-   =20
+
     virtual bool doesSectionRequireSymbols(const MCSection &Section) const=
 {
       return false;
     }
@@ -187,5 +185,6 @@
   if (Triple(TT).isOSDarwin())
     return new DarwinPPCAsmBackend(T);
=20
-  return new ELFPPCAsmBackend(T, Triple(TT).getOS());
+  uint8_t OSABI =3D MCELFObjectTargetWriter::getOSABI(Triple(TT).getOS());
+  return new ELFPPCAsmBackend(T, OSABI);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/M=
CTargetDesc/PPCBaseInfo.h
--- a/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCBaseInfo.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCBaseInfo.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCBaseInfo.h - Top level definitions for PPC -------- --*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCBaseInfo.h - Top level definitions for PPC -----------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/M=
CTargetDesc/PPCMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCMCAsmInfo.cpp - PPC asm properties -------------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCMCAsmInfo.cpp - PPC asm properties ----------------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,6 +14,8 @@
 #include "PPCMCAsmInfo.h"
 using namespace llvm;
=20
+void PPCMCAsmInfoDarwin::anchor() { }
+
 PPCMCAsmInfoDarwin::PPCMCAsmInfoDarwin(bool is64Bit) {
   if (is64Bit)
     PointerSize =3D 8;
@@ -30,6 +32,8 @@
   SupportsDebugInformation=3D true; // Debug information.
 }
=20
+void PPCLinuxMCAsmInfo::anchor() { }
+
 PPCLinuxMCAsmInfo::PPCLinuxMCAsmInfo(bool is64Bit) {
   if (is64Bit)
     PointerSize =3D 8;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/M=
CTargetDesc/PPCMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCAsmInfo.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- PPCMCAsmInfo.h - PPC asm properties -----------------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- PPCMCAsmInfo.h - PPC asm properties --------------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,11 +18,15 @@
=20
 namespace llvm {
=20
-  struct PPCMCAsmInfoDarwin : public MCAsmInfoDarwin {
+  class PPCMCAsmInfoDarwin : public MCAsmInfoDarwin {
+    virtual void anchor();
+  public:
     explicit PPCMCAsmInfoDarwin(bool is64Bit);
   };
=20
-  struct PPCLinuxMCAsmInfo : public MCAsmInfo {
+  class PPCLinuxMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit PPCLinuxMCAsmInfo(bool is64Bit);
   };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/M=
CTargetDesc/PPCMCCodeEmitter.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cp=
p	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCCodeEmitter.cp=
p	Tue Apr 17 11:51:51 2012 +0300
@@ -57,7 +57,7 @@
  =20
   // getBinaryCodeForInstr - TableGen'erated function for getting the
   // binary encoding for an instruction.
-  unsigned getBinaryCodeForInstr(const MCInst &MI,
+  uint64_t getBinaryCodeForInstr(const MCInst &MI,
                                  SmallVectorImpl<MCFixup> &Fixups) const;
   void EncodeInstruction(const MCInst &MI, raw_ostream &OS,
                          SmallVectorImpl<MCFixup> &Fixups) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/M=
CTargetDesc/PPCMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCMCTargetDesc.cpp - PowerPC Target Descriptions -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCMCTargetDesc.cpp - PowerPC Target Descriptions ----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -20,6 +20,7 @@
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 #define GET_INSTRINFO_MC_DESC
@@ -76,7 +77,8 @@
 }
=20
 static MCCodeGenInfo *createPPCMCCodeGenInfo(StringRef TT, Reloc::Model RM,
-                                             CodeModel::Model CM) {
+                                             CodeModel::Model CM,
+                                             CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
=20
   if (RM =3D=3D Reloc::Default) {
@@ -86,7 +88,7 @@
     else
       RM =3D Reloc::Static;
   }
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
@@ -106,8 +108,10 @@
 static MCInstPrinter *createPPCMCInstPrinter(const Target &T,
                                              unsigned SyntaxVariant,
                                              const MCAsmInfo &MAI,
+                                             const MCInstrInfo &MII,
+                                             const MCRegisterInfo &MRI,
                                              const MCSubtargetInfo &STI) {
-  return new PPCInstPrinter(MAI, SyntaxVariant);
+  return new PPCInstPrinter(MAI, MII, MRI, SyntaxVariant);
 }
=20
 extern "C" void LLVMInitializePowerPCTargetMC() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/M=
CTargetDesc/PPCMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/MCTargetDesc/PPCMCTargetDesc.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -14,14 +14,18 @@
 #ifndef PPCMCTARGETDESC_H
 #define PPCMCTARGETDESC_H
=20
+#include "llvm/Support/DataTypes.h"
+
 namespace llvm {
 class MCAsmBackend;
 class MCCodeEmitter;
 class MCContext;
 class MCInstrInfo;
+class MCObjectWriter;
 class MCSubtargetInfo;
 class Target;
 class StringRef;
+class raw_ostream;
=20
 extern Target ThePPC32Target;
 extern Target ThePPC64Target;
@@ -31,7 +35,11 @@
                                       MCContext &Ctx);
=20
 MCAsmBackend *createPPCAsmBackend(const Target &T, StringRef TT);
- =20
+
+/// createPPCELFObjectWriter - Construct an PPC ELF object writer.
+MCObjectWriter *createPPCELFObjectWriter(raw_ostream &OS,
+                                         bool Is64Bit,
+                                         uint8_t OSABI);
 } // End llvm namespace
=20
 // Defines symbolic names for PowerPC registers.  This defines a mapping f=
rom
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PC.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPC.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPC.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -25,14 +25,11 @@
 namespace llvm {
   class PPCTargetMachine;
   class FunctionPass;
-  class formatted_raw_ostream;
   class JITCodeEmitter;
-  class Target;
   class MachineInstr;
   class AsmPrinter;
   class MCInst;
-  class TargetMachine;
- =20
+
   FunctionPass *createPPCBranchSelectionPass();
   FunctionPass *createPPCISelDag(PPCTargetMachine &TM);
   FunctionPass *createPPCJITCodeEmitterPass(PPCTargetMachine &TM,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PC.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPC.td	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPC.td	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPC.td - Describe the PowerPC Target Machine --------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPC.td - Describe the PowerPC Target Machine -------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This is the top level entry point for the PowerPC target.
@@ -23,6 +23,7 @@
 // CPU Directives                                                         =
    //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+def Directive440 : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_440",=
 "">;
 def Directive601 : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_601",=
 "">;
 def Directive602 : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_602",=
 "">;
 def Directive603 : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_603",=
 "">;
@@ -33,6 +34,7 @@
 def Directive970 : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_970",=
 "">;
 def Directive32  : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_32", =
"">;
 def Directive64  : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_64", =
"">;
+def DirectiveA2  : SubtargetFeature<"", "DarwinDirective", "PPC::DIR_A2", =
"">;
=20
 def Feature64Bit     : SubtargetFeature<"64bit","Has64BitSupport", "true",
                                         "Enable 64-bit instructions">;
@@ -46,6 +48,8 @@
                                         "Enable the fsqrt instruction">;
 def FeatureSTFIWX    : SubtargetFeature<"stfiwx","HasSTFIWX", "true",
                                         "Enable the stfiwx instruction">;
+def FeatureBookE     : SubtargetFeature<"booke", "IsBookE", "true",
+                                        "Enable Book E instructions">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Register File Description
@@ -60,6 +64,8 @@
 //
=20
 def : Processor<"generic", G3Itineraries, [Directive32]>;
+def : Processor<"440", PPC440Itineraries, [Directive440, FeatureBookE]>;
+def : Processor<"450", PPC440Itineraries, [Directive440, FeatureBookE]>;
 def : Processor<"601", G3Itineraries, [Directive601]>;
 def : Processor<"602", G3Itineraries, [Directive602]>;
 def : Processor<"603", G3Itineraries, [Directive603]>;
@@ -82,6 +88,10 @@
                   [Directive970, FeatureAltivec,
                    FeatureGPUL, FeatureFSqrt, FeatureSTFIWX,
                    Feature64Bit /*, Feature64BitRegs */]>;
+def : Processor<"a2",  PPCA2Itineraries, [DirectiveA2, FeatureBookE,
+                                          FeatureFSqrt, FeatureSTFIWX,
+                                          Feature64Bit
+                                      /*, Feature64BitRegs */]>;
 def : Processor<"ppc", G3Itineraries, [Directive32]>;
 def : Processor<"ppc64", G5Itineraries,
                   [Directive64, FeatureAltivec,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCAsmPrinter.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCAsmPrinter.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly=
 --------=3D//
+//=3D=3D=3D-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly=
 ------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -20,6 +20,7 @@
 #include "PPC.h"
 #include "PPCTargetMachine.h"
 #include "PPCSubtarget.h"
+#include "InstPrinter/PPCInstPrinter.h"
 #include "MCTargetDesc/PPCPredicates.h"
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/Constants.h"
@@ -39,6 +40,7 @@
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/MC/MCStreamer.h"
 #include "llvm/MC/MCSymbol.h"
+#include "llvm/MC/MCSectionELF.h"
 #include "llvm/Target/Mangler.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
@@ -49,10 +51,9 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/ELF.h"
 #include "llvm/ADT/StringExtras.h"
-#include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/SmallString.h"
-#include "InstPrinter/PPCInstPrinter.h"
 using namespace llvm;
=20
 namespace {
@@ -366,14 +367,21 @@
   }
      =20
   case PPC::MFCRpseud:
+  case PPC::MFCR8pseud:
     // Transform: %R3 =3D MFCRpseud %CR7
     // Into:      %R3 =3D MFCR      ;; cr7
     OutStreamer.AddComment(PPCInstPrinter::
                            getRegisterName(MI->getOperand(1).getReg()));
-    TmpInst.setOpcode(PPC::MFCR);
+    TmpInst.setOpcode(Subtarget.isPPC64() ? PPC::MFCR8 : PPC::MFCR);
     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
     OutStreamer.EmitInstruction(TmpInst);
     return;
+  case PPC::SYNC:
+    // In Book E sync is called msync, handle this special case here...
+    if (Subtarget.isBookE()) {
+      OutStreamer.EmitRawText(StringRef("\tmsync"));
+      return;
+    }
   }
=20
   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, Subtarget.isDarwin());
@@ -385,14 +393,26 @@
     return AsmPrinter::EmitFunctionEntryLabel();
    =20
   // Emit an official procedure descriptor.
-  // FIXME 64-bit SVR4: Use MCSection here!
-  OutStreamer.EmitRawText(StringRef("\t.section\t\".opd\",\"aw\""));
-  OutStreamer.EmitRawText(StringRef("\t.align 3"));
+  const MCSection *Current =3D OutStreamer.getCurrentSection();
+  const MCSectionELF *Section =3D OutStreamer.getContext().getELFSection("=
.opd",
+      ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
+      SectionKind::getReadOnly());
+  OutStreamer.SwitchSection(Section);
   OutStreamer.EmitLabel(CurrentFnSym);
-  OutStreamer.EmitRawText("\t.quad .L." + Twine(CurrentFnSym->getName()) +
-                          ",.TOC. at tocbase");
-  OutStreamer.EmitRawText(StringRef("\t.previous"));
-  OutStreamer.EmitRawText(".L." + Twine(CurrentFnSym->getName()) + ":");
+  OutStreamer.EmitValueToAlignment(8);
+  MCSymbol *Symbol1 =3D=20
+    OutContext.GetOrCreateSymbol(".L." + Twine(CurrentFnSym->getName()));
+  MCSymbol *Symbol2 =3D OutContext.GetOrCreateSymbol(StringRef(".TOC. at tocb=
ase"));
+  OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol1, OutContext),
+                        Subtarget.isPPC64() ? 8 : 4/*size*/, 0/*addrspace*=
/);
+  OutStreamer.EmitValue(MCSymbolRefExpr::Create(Symbol2, OutContext),
+                        Subtarget.isPPC64() ? 8 : 4/*size*/, 0/*addrspace*=
/);
+  OutStreamer.SwitchSection(Current);
+
+  MCSymbol *RealFnSym =3D OutContext.GetOrCreateSymbol(
+                          ".L." + Twine(CurrentFnSym->getName()));
+  OutStreamer.EmitLabel(RealFnSym);
+  CurrentFnSymForSize =3D RealFnSym;
 }
=20
=20
@@ -402,8 +422,10 @@
   bool isPPC64 =3D TD->getPointerSizeInBits() =3D=3D 64;
=20
   if (isPPC64 && !TOC.empty()) {
-    // FIXME 64-bit SVR4: Use MCSection here?
-    OutStreamer.EmitRawText(StringRef("\t.section\t\".toc\",\"aw\""));
+    const MCSectionELF *Section =3D OutStreamer.getContext().getELFSection=
(".toc",
+        ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC,
+        SectionKind::getReadOnly());
+    OutStreamer.SwitchSection(Section);
=20
     // FIXME: This is nondeterminstic!
     for (DenseMap<MCSymbol*, MCSymbol*>::iterator I =3D TOC.begin(),
@@ -421,12 +443,14 @@
   static const char *const CPUDirectives[] =3D {
     "",
     "ppc",
+    "ppc440",
     "ppc601",
     "ppc602",
     "ppc603",
     "ppc7400",
     "ppc750",
     "ppc970",
+    "ppcA2",
     "ppc64"
   };
=20
@@ -435,7 +459,7 @@
     Directive =3D PPC::DIR_970;
   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
     Directive =3D PPC::DIR_7400;
-  if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
+  if (Subtarget.isPPC64() && Directive < PPC::DIR_64)
     Directive =3D PPC::DIR_64;
   assert(Directive <=3D PPC::DIR_64 && "Directive out of range.");
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCBranchSelector.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCBranchSelector.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCBranchSelector.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCBranchSelector.cpp - Emit long conditional branches-----*=
- C++ -*-=3D//
+//=3D=3D=3D-- PPCBranchSelector.cpp - Emit long conditional branches -----=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCCallingConv.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCCallingConv.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCCallingConv.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,10 +1,10 @@
 //=3D=3D=3D- PPCCallingConv.td - Calling Conventions for PowerPC -*- table=
gen -*-=3D=3D=3D//
-//=20
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This describes the calling conventions for the PowerPC 32- and 64-bit
@@ -130,3 +130,34 @@
   CCCustom<"CC_PPC_SVR4_Custom_Dummy">
 ]>;
=20
+def CSR_Darwin32 : CalleeSavedRegs<(add R13, R14, R15, R16, R17, R18, R19,=
 R20,
+                                        R21, R22, R23, R24, R25, R26, R27,=
 R28,
+                                        R29, R30, R31, F14, F15, F16, F17,=
 F18,
+                                        F19, F20, F21, F22, F23, F24, F25,=
 F26,
+                                        F27, F28, F29, F30, F31, CR2, CR3,=
 CR4,
+                                        V20, V21, V22, V23, V24, V25, V26,=
 V27,
+                                        V28, V29, V30, V31)>;
+
+def CSR_SVR432   : CalleeSavedRegs<(add R14, R15, R16, R17, R18, R19, R20,=
 VRSAVE,
+                                        R21, R22, R23, R24, R25, R26, R27,=
 R28,
+                                        R29, R30, R31, F14, F15, F16, F17,=
 F18,
+                                        F19, F20, F21, F22, F23, F24, F25,=
 F26,
+                                        F27, F28, F29, F30, F31, CR2, CR3,=
 CR4,
+                                        V20, V21, V22, V23, V24, V25, V26,=
 V27,
+                                        V28, V29, V30, V31)>;
+
+def CSR_Darwin64 : CalleeSavedRegs<(add X13, X14, X15, X16, X17, X18, X19,=
 X20,
+                                        X21, X22, X23, X24, X25, X26, X27,=
 X28,
+                                        X29, X30, X31, F14, F15, F16, F17,=
 F18,
+                                        F19, F20, F21, F22, F23, F24, F25,=
 F26,
+                                        F27, F28, F29, F30, F31, CR2, CR3,=
 CR4,
+                                        V20, V21, V22, V23, V24, V25, V26,=
 V27,
+                                        V28, V29, V30, V31)>;
+
+def CSR_SVR464   : CalleeSavedRegs<(add X14, X15, X16, X17, X18, X19, X20,=
 VRSAVE,
+                                        X21, X22, X23, X24, X25, X26, X27,=
 X28,
+                                        X29, X30, X31, F14, F15, F16, F17,=
 F18,
+                                        F19, F20, F21, F22, F23, F24, F25,=
 F26,
+                                        F27, F28, F29, F30, F31, CR2, CR3,=
 CR4,
+                                        V20, V21, V22, V23, V24, V25, V26,=
 V27,
+                                        V28, V29, V30, V31)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCCodeEmitter.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCCodeEmitter.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCCodeEmitter.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCCodeEmitter.cpp - JIT Code Emitter for PowerPC32 -------*=
- C++ -*-=3D//
+//=3D=3D=3D-- PPCCodeEmitter.cpp - JIT Code Emitter for PowerPC ----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -50,7 +50,7 @@
     /// getBinaryCodeForInstr - This function, generated by the
     /// CodeEmitterGenerator using TableGen, produces the binary encoding =
for
     /// machine instructions.
-    unsigned getBinaryCodeForInstr(const MachineInstr &MI) const;
+    uint64_t getBinaryCodeForInstr(const MachineInstr &MI) const;
=20
    =20
     MachineRelocation GetRelocation(const MachineOperand &MO,
@@ -138,7 +138,8 @@
 unsigned PPCCodeEmitter::get_crbitm_encoding(const MachineInstr &MI,
                                              unsigned OpNo) const {
   const MachineOperand &MO =3D MI.getOperand(OpNo);
-  assert((MI.getOpcode() =3D=3D PPC::MTCRF || MI.getOpcode() =3D=3D PPC::M=
FOCRF) &&
+  assert((MI.getOpcode() =3D=3D PPC::MTCRF || MI.getOpcode() =3D=3D PPC::M=
TCRF8 ||
+            MI.getOpcode() =3D=3D PPC::MFOCRF) &&
          (MO.getReg() >=3D PPC::CR0 && MO.getReg() <=3D PPC::CR7));
   return 0x80 >> getPPCRegisterNumbering(MO.getReg());
 }
@@ -248,7 +249,8 @@
   if (MO.isReg()) {
     // MTCRF/MFOCRF should go through get_crbitm_encoding for the CR opera=
nd.
     // The GPR operand should come through here though.
-    assert((MI.getOpcode() !=3D PPC::MTCRF && MI.getOpcode() !=3D PPC::MFO=
CRF) ||
+    assert((MI.getOpcode() !=3D PPC::MTCRF && MI.getOpcode() !=3D PPC::MTC=
RF8 &&
+             MI.getOpcode() !=3D PPC::MFOCRF) ||
            MO.getReg() < PPC::CR0 || MO.getReg() > PPC::CR7);
     return getPPCRegisterNumbering(MO.getReg());
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCFrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCFrameLowering.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCFrameLowering.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D- PPCFrameLowering.cpp - PPC Frame Information ----------=
-*- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCFrameLowering.cpp - PPC Frame Information ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -38,7 +38,7 @@
=20
 /// VRRegNo - Map from a numbered VR register to its enum value.
 ///
-static const unsigned short VRRegNo[] =3D {
+static const uint16_t VRRegNo[] =3D {
  PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC=
::V7 ,
  PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC=
::V15,
  PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC=
::V23,
@@ -64,7 +64,7 @@
   // epilog blocks.
   for (MachineFunction::iterator I =3D MF->begin(), E =3D MF->end(); I !=
=3D E; ++I) {
     // If last instruction is a return instruction, add an epilogue
-    if (!I->empty() && I->back().getDesc().isReturn()) {
+    if (!I->empty() && I->back().isReturn()) {
       bool FoundIt =3D false;
       for (MBBI =3D I->end(); MBBI !=3D I->begin(); ) {
         --MBBI;
@@ -244,8 +244,10 @@
   if (MF.getFunction()->hasFnAttr(Attribute::Naked))
     return false;
=20
-  return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects() ||
-    (GuaranteedTailCallOpt && MF.getInfo<PPCFunctionInfo>()->hasFastCall()=
);
+  return MF.getTarget().Options.DisableFramePointerElim(MF) ||
+    MFI->hasVarSizedObjects() ||
+    (MF.getTarget().Options.GuaranteedTailCallOpt &&
+     MF.getInfo<PPCFunctionInfo>()->hasFastCall());
 }
=20
=20
@@ -365,8 +367,8 @@
         .addReg(PPC::R0, RegState::Kill)
         .addImm(NegFrameSize);
       BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX))
-        .addReg(PPC::R1)
-        .addReg(PPC::R1)
+        .addReg(PPC::R1, RegState::Kill)
+        .addReg(PPC::R1, RegState::Define)
         .addReg(PPC::R0);
     } else if (isInt<16>(NegFrameSize)) {
       BuildMI(MBB, MBBI, dl, TII.get(PPC::STWU), PPC::R1)
@@ -380,8 +382,8 @@
         .addReg(PPC::R0, RegState::Kill)
         .addImm(NegFrameSize & 0xFFFF);
       BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX))
-        .addReg(PPC::R1)
-        .addReg(PPC::R1)
+        .addReg(PPC::R1, RegState::Kill)
+        .addReg(PPC::R1, RegState::Define)
         .addReg(PPC::R0);
     }
   } else {    // PPC64.
@@ -398,8 +400,8 @@
         .addReg(PPC::X0)
         .addImm(NegFrameSize);
       BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX))
-        .addReg(PPC::X1)
-        .addReg(PPC::X1)
+        .addReg(PPC::X1, RegState::Kill)
+        .addReg(PPC::X1, RegState::Define)
         .addReg(PPC::X0);
     } else if (isInt<16>(NegFrameSize)) {
       BuildMI(MBB, MBBI, dl, TII.get(PPC::STDU), PPC::X1)
@@ -413,8 +415,8 @@
         .addReg(PPC::X0, RegState::Kill)
         .addImm(NegFrameSize & 0xFFFF);
       BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX))
-        .addReg(PPC::X1)
-        .addReg(PPC::X1)
+        .addReg(PPC::X1, RegState::Kill)
+        .addReg(PPC::X1, RegState::Define)
         .addReg(PPC::X0);
     }
   }
@@ -655,7 +657,7 @@
=20
   // Callee pop calling convention. Pop parameter/linkage area. Used for t=
ail
   // call optimization
-  if (GuaranteedTailCallOpt && RetOpcode =3D=3D PPC::BLR &&
+  if (MF.getTarget().Options.GuaranteedTailCallOpt && RetOpcode =3D=3D PPC=
::BLR &&
       MF.getFunction()->getCallingConv() =3D=3D CallingConv::Fast) {
      PPCFunctionInfo *FI =3D MF.getInfo<PPCFunctionInfo>();
      unsigned CallerAllocatedAmt =3D FI->getMinReservedArea();
@@ -758,7 +760,8 @@
=20
   // Reserve stack space to move the linkage area to in case of a tail cal=
l.
   int TCSPDelta =3D 0;
-  if (GuaranteedTailCallOpt && (TCSPDelta =3D FI->getTailCallSPDelta()) < =
0) {
+  if (MF.getTarget().Options.GuaranteedTailCallOpt &&
+      (TCSPDelta =3D FI->getTailCallSPDelta()) < 0) {
     MFI->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
   }
=20
@@ -769,7 +772,7 @@
   // FIXME: doesn't detect whether or not we need to spill vXX, which requ=
ires
   //        r0 for now.
=20
-  if (RegInfo->requiresRegisterScavenging(MF)) // FIXME (64-bit): Enable.
+  if (RegInfo->requiresRegisterScavenging(MF))
     if (needsFP(MF) || spillsCR(MF)) {
       const TargetRegisterClass *GPRC =3D &PPC::GPRCRegClass;
       const TargetRegisterClass *G8RC =3D &PPC::G8RCRegClass;
@@ -863,7 +866,8 @@
=20
   // Take into account stack space reserved for tail calls.
   int TCSPDelta =3D 0;
-  if (GuaranteedTailCallOpt && (TCSPDelta =3D PFI->getTailCallSPDelta()) <=
 0) {
+  if (MF.getTarget().Options.GuaranteedTailCallOpt &&
+      (TCSPDelta =3D PFI->getTailCallSPDelta()) < 0) {
     LowerBound =3D TCSPDelta;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCFrameLowering.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCFrameLowering.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCFrameLowering.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D-- PPCFrameLowering.h - Define frame lowering for PowerPC ----*- C=
++ -*-=3D=3D//
+//=3D=3D=3D-- PPCFrameLowering.h - Define frame lowering for PowerPC --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCHazardRecognizers.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCHazardRecognizers.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCHazardRecognizers.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -22,6 +22,30 @@
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// PowerPC Scoreboard Hazard Recognizer
+void PPCScoreboardHazardRecognizer::EmitInstruction(SUnit *SU) {
+  const MCInstrDesc *MCID =3D DAG->getInstrDesc(SU);
+  if (!MCID)
+    // This is a PPC pseudo-instruction.
+    return;
+
+  ScoreboardHazardRecognizer::EmitInstruction(SU);
+}
+
+ScheduleHazardRecognizer::HazardType
+PPCScoreboardHazardRecognizer::getHazardType(SUnit *SU, int Stalls) {
+  return ScoreboardHazardRecognizer::getHazardType(SU, Stalls);
+}
+
+void PPCScoreboardHazardRecognizer::AdvanceCycle() {
+  ScoreboardHazardRecognizer::AdvanceCycle();
+}
+
+void PPCScoreboardHazardRecognizer::Reset() {
+  ScoreboardHazardRecognizer::Reset();
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PowerPC 970 Hazard Recognizer
 //
 // This models the dispatch group formation of the PPC970 processor.  Disp=
atch
@@ -67,12 +91,6 @@
                                      bool &isFirst, bool &isSingle,
                                      bool &isCracked,
                                      bool &isLoad, bool &isStore) {
-  if ((int)Opcode >=3D 0) {
-    isFirst =3D isSingle =3D isCracked =3D isLoad =3D isStore =3D false;
-    return PPCII::PPC970_Pseudo;
-  }
-  Opcode =3D ~Opcode;
-
   const MCInstrDesc &MCID =3D TII.get(Opcode);
=20
   isLoad  =3D MCID.mayLoad();
@@ -89,29 +107,23 @@
 /// isLoadOfStoredAddress - If we have a load from the previously stored p=
ointer
 /// as indicated by StorePtr1/StorePtr2/StoreSize, return true.
 bool PPCHazardRecognizer970::
-isLoadOfStoredAddress(unsigned LoadSize, SDValue Ptr1, SDValue Ptr2) const=
 {
+isLoadOfStoredAddress(uint64_t LoadSize, int64_t LoadOffset,
+  const Value *LoadValue) const {
   for (unsigned i =3D 0, e =3D NumStores; i !=3D e; ++i) {
     // Handle exact and commuted addresses.
-    if (Ptr1 =3D=3D StorePtr1[i] && Ptr2 =3D=3D StorePtr2[i])
-      return true;
-    if (Ptr2 =3D=3D StorePtr1[i] && Ptr1 =3D=3D StorePtr2[i])
+    if (LoadValue =3D=3D StoreValue[i] && LoadOffset =3D=3D StoreOffset[i])
       return true;
=20
     // Okay, we don't have an exact match, if this is an indexed offset, s=
ee if
     // we have overlap (which happens during fp->int conversion for exampl=
e).
-    if (StorePtr2[i] =3D=3D Ptr2) {
-      if (ConstantSDNode *StoreOffset =3D dyn_cast<ConstantSDNode>(StorePt=
r1[i]))
-        if (ConstantSDNode *LoadOffset =3D dyn_cast<ConstantSDNode>(Ptr1))=
 {
-          // Okay the base pointers match, so we have [c1+r] vs [c2+r].  C=
heck
-          // to see if the load and store actually overlap.
-          int StoreOffs =3D StoreOffset->getZExtValue();
-          int LoadOffs  =3D LoadOffset->getZExtValue();
-          if (StoreOffs < LoadOffs) {
-            if (int(StoreOffs+StoreSize[i]) > LoadOffs) return true;
-          } else {
-            if (int(LoadOffs+LoadSize) > StoreOffs) return true;
-          }
-        }
+    if (StoreValue[i] =3D=3D LoadValue) {
+      // Okay the base pointers match, so we have [c1+r] vs [c2+r].  Check
+      // to see if the load and store actually overlap.
+      if (StoreOffset[i] < LoadOffset) {
+        if (int64_t(StoreOffset[i]+StoreSize[i]) > LoadOffset) return true;
+      } else {
+        if (int64_t(LoadOffset+LoadSize) > StoreOffset[i]) return true;
+      }
     }
   }
   return false;
@@ -125,13 +137,17 @@
 getHazardType(SUnit *SU, int Stalls) {
   assert(Stalls =3D=3D 0 && "PPC hazards don't support scoreboard lookahea=
d");
=20
-  const SDNode *Node =3D SU->getNode()->getGluedMachineNode();
+  MachineInstr *MI =3D SU->getInstr();
+
+  if (MI->isDebugValue())
+    return NoHazard;
+
+  unsigned Opcode =3D MI->getOpcode();
   bool isFirst, isSingle, isCracked, isLoad, isStore;
   PPCII::PPC970_Unit InstrType =3D
-    GetInstrType(Node->getOpcode(), isFirst, isSingle, isCracked,
+    GetInstrType(Opcode, isFirst, isSingle, isCracked,
                  isLoad, isStore);
   if (InstrType =3D=3D PPCII::PPC970_Pseudo) return NoHazard;
-  unsigned Opcode =3D Node->getMachineOpcode();
=20
   // We can only issue a PPC970_First/PPC970_Single instruction (such as
   // crand/mtspr/etc) if this is the first cycle of the dispatch group.
@@ -168,55 +184,10 @@
=20
   // If this is a load following a store, make sure it's not to the same or
   // overlapping address.
-  if (isLoad && NumStores) {
-    unsigned LoadSize;
-    switch (Opcode) {
-    default: llvm_unreachable("Unknown load!");
-    case PPC::LBZ:   case PPC::LBZU:
-    case PPC::LBZX:
-    case PPC::LBZ8:  case PPC::LBZU8:
-    case PPC::LBZX8:
-    case PPC::LVEBX:
-      LoadSize =3D 1;
-      break;
-    case PPC::LHA:   case PPC::LHAU:
-    case PPC::LHAX:
-    case PPC::LHZ:   case PPC::LHZU:
-    case PPC::LHZX:
-    case PPC::LVEHX:
-    case PPC::LHBRX:
-    case PPC::LHA8:   case PPC::LHAU8:
-    case PPC::LHAX8:
-    case PPC::LHZ8:   case PPC::LHZU8:
-    case PPC::LHZX8:
-      LoadSize =3D 2;
-      break;
-    case PPC::LFS:    case PPC::LFSU:
-    case PPC::LFSX:
-    case PPC::LWZ:    case PPC::LWZU:
-    case PPC::LWZX:
-    case PPC::LWA:
-    case PPC::LWAX:
-    case PPC::LVEWX:
-    case PPC::LWBRX:
-    case PPC::LWZ8:
-    case PPC::LWZX8:
-      LoadSize =3D 4;
-      break;
-    case PPC::LFD:    case PPC::LFDU:
-    case PPC::LFDX:
-    case PPC::LD:     case PPC::LDU:
-    case PPC::LDX:
-      LoadSize =3D 8;
-      break;
-    case PPC::LVX:
-    case PPC::LVXL:
-      LoadSize =3D 16;
-      break;
-    }
-
-    if (isLoadOfStoredAddress(LoadSize,
-                              Node->getOperand(0), Node->getOperand(1)))
+  if (isLoad && NumStores && !MI->memoperands_empty()) {
+    MachineMemOperand *MO =3D *MI->memoperands_begin();
+    if (isLoadOfStoredAddress(MO->getSize(),
+                              MO->getOffset(), MO->getValue()))
       return NoopHazard;
   }
=20
@@ -224,66 +195,27 @@
 }
=20
 void PPCHazardRecognizer970::EmitInstruction(SUnit *SU) {
-  const SDNode *Node =3D SU->getNode()->getGluedMachineNode();
+  MachineInstr *MI =3D SU->getInstr();
+
+  if (MI->isDebugValue())
+    return;
+
+  unsigned Opcode =3D MI->getOpcode();
   bool isFirst, isSingle, isCracked, isLoad, isStore;
   PPCII::PPC970_Unit InstrType =3D
-    GetInstrType(Node->getOpcode(), isFirst, isSingle, isCracked,
+    GetInstrType(Opcode, isFirst, isSingle, isCracked,
                  isLoad, isStore);
   if (InstrType =3D=3D PPCII::PPC970_Pseudo) return;
-  unsigned Opcode =3D Node->getMachineOpcode();
=20
   // Update structural hazard information.
   if (Opcode =3D=3D PPC::MTCTR || Opcode =3D=3D PPC::MTCTR8) HasCTRSet =3D=
 true;
=20
   // Track the address stored to.
-  if (isStore) {
-    unsigned ThisStoreSize;
-    switch (Opcode) {
-    default: llvm_unreachable("Unknown store instruction!");
-    case PPC::STB:    case PPC::STB8:
-    case PPC::STBU:   case PPC::STBU8:
-    case PPC::STBX:   case PPC::STBX8:
-    case PPC::STVEBX:
-      ThisStoreSize =3D 1;
-      break;
-    case PPC::STH:    case PPC::STH8:
-    case PPC::STHU:   case PPC::STHU8:
-    case PPC::STHX:   case PPC::STHX8:
-    case PPC::STVEHX:
-    case PPC::STHBRX:
-      ThisStoreSize =3D 2;
-      break;
-    case PPC::STFS:
-    case PPC::STFSU:
-    case PPC::STFSX:
-    case PPC::STWX:   case PPC::STWX8:
-    case PPC::STWUX:
-    case PPC::STW:    case PPC::STW8:
-    case PPC::STWU:
-    case PPC::STVEWX:
-    case PPC::STFIWX:
-    case PPC::STWBRX:
-      ThisStoreSize =3D 4;
-      break;
-    case PPC::STD_32:
-    case PPC::STDX_32:
-    case PPC::STD:
-    case PPC::STDU:
-    case PPC::STFD:
-    case PPC::STFDX:
-    case PPC::STDX:
-    case PPC::STDUX:
-      ThisStoreSize =3D 8;
-      break;
-    case PPC::STVX:
-    case PPC::STVXL:
-      ThisStoreSize =3D 16;
-      break;
-    }
-
-    StoreSize[NumStores] =3D ThisStoreSize;
-    StorePtr1[NumStores] =3D Node->getOperand(1);
-    StorePtr2[NumStores] =3D Node->getOperand(2);
+  if (isStore && NumStores < 4 && !MI->memoperands_empty()) {
+    MachineMemOperand *MO =3D *MI->memoperands_begin();
+    StoreSize[NumStores] =3D MO->getSize();
+    StoreOffset[NumStores] =3D MO->getOffset();
+    StoreValue[NumStores] =3D MO->getValue();
     ++NumStores;
   }
=20
@@ -306,3 +238,8 @@
   if (NumIssued =3D=3D 5)
     EndDispatchGroup();
 }
+
+void PPCHazardRecognizer970::Reset() {
+  EndDispatchGroup();
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCHazardRecognizers.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCHazardRecognizers.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCHazardRecognizers.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -14,12 +14,28 @@
 #ifndef PPCHAZRECS_H
 #define PPCHAZRECS_H
=20
+#include "PPCInstrInfo.h"
 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
+#include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
 #include "llvm/CodeGen/SelectionDAGNodes.h"
-#include "PPCInstrInfo.h"
=20
 namespace llvm {
=20
+/// PPCScoreboardHazardRecognizer - This class implements a scoreboard-bas=
ed
+/// hazard recognizer for generic PPC processors.
+class PPCScoreboardHazardRecognizer : public ScoreboardHazardRecognizer {
+  const ScheduleDAG *DAG;
+public:
+  PPCScoreboardHazardRecognizer(const InstrItineraryData *ItinData,
+                         const ScheduleDAG *DAG_) :
+    ScoreboardHazardRecognizer(ItinData, DAG_), DAG(DAG_) {}
+
+  virtual HazardType getHazardType(SUnit *SU, int Stalls);
+  virtual void EmitInstruction(SUnit *SU);
+  virtual void AdvanceCycle();
+  virtual void Reset();
+};
+
 /// PPCHazardRecognizer970 - This class defines a finite state automata th=
at
 /// models the dispatch logic on the PowerPC 970 (aka G5) processor.  This
 /// promotes good dispatch group formation and implements noop insertion to
@@ -42,8 +58,9 @@
   //
   // This is null if we haven't seen a store yet.  We keep track of both
   // operands of the store here, since we support [r+r] and [r+i] addressi=
ng.
-  SDValue StorePtr1[4], StorePtr2[4];
-  unsigned  StoreSize[4];
+  const Value *StoreValue[4];
+  int64_t StoreOffset[4];
+  uint64_t StoreSize[4];
   unsigned NumStores;
=20
 public:
@@ -51,6 +68,7 @@
   virtual HazardType getHazardType(SUnit *SU, int Stalls);
   virtual void EmitInstruction(SUnit *SU);
   virtual void AdvanceCycle();
+  virtual void Reset();
=20
 private:
   /// EndDispatchGroup - Called when we are finishing a new dispatch group.
@@ -63,8 +81,8 @@
                                   bool &isFirst, bool &isSingle,bool &isCr=
acked,
                                   bool &isLoad, bool &isStore);
=20
-  bool isLoadOfStoredAddress(unsigned LoadSize,
-                             SDValue Ptr1, SDValue Ptr2) const;
+  bool isLoadOfStoredAddress(uint64_t LoadSize, int64_t LoadOffset,
+                             const Value *LoadValue) const;
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCISelDAGToDAG.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -18,7 +18,6 @@
 #include "MCTargetDesc/PPCPredicates.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineFunction.h"
-#include "llvm/CodeGen/MachineFunctionAnalysis.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/SelectionDAGISel.h"
@@ -211,13 +210,13 @@
=20
   // Find all return blocks, outputting a restore in each epilog.
   for (MachineFunction::iterator BB =3D Fn.begin(), E =3D Fn.end(); BB !=
=3D E; ++BB) {
-    if (!BB->empty() && BB->back().getDesc().isReturn()) {
+    if (!BB->empty() && BB->back().isReturn()) {
       IP =3D BB->end(); --IP;
=20
       // Skip over all terminator instructions, which are part of the retu=
rn
       // sequence.
       MachineBasicBlock::iterator I2 =3D IP;
-      while (I2 !=3D BB->begin() && (--I2)->getDesc().isTerminator())
+      while (I2 !=3D BB->begin() && (--I2)->isTerminator())
         IP =3D I2;
=20
       // Emit: MTVRSAVE InVRSave
@@ -378,8 +377,8 @@
   DebugLoc dl =3D N->getDebugLoc();
=20
   APInt LKZ, LKO, RKZ, RKO;
-  CurDAG->ComputeMaskedBits(Op0, APInt::getAllOnesValue(32), LKZ, LKO);
-  CurDAG->ComputeMaskedBits(Op1, APInt::getAllOnesValue(32), RKZ, RKO);
+  CurDAG->ComputeMaskedBits(Op0, LKZ, LKO);
+  CurDAG->ComputeMaskedBits(Op1, RKZ, RKO);
=20
   unsigned TargetMask =3D LKZ.getZExtValue();
   unsigned InsertMask =3D RKZ.getZExtValue();
@@ -603,7 +602,6 @@
   case ISD::SETULT: return 0;
   case ISD::SETUGT: return 1;
   }
-  return 0;
 }
=20
 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
@@ -1067,7 +1065,7 @@
     SDValue Target =3D N->getOperand(1);
     unsigned Opc =3D Target.getValueType() =3D=3D MVT::i32 ? PPC::MTCTR : =
PPC::MTCTR8;
     unsigned Reg =3D Target.getValueType() =3D=3D MVT::i32 ? PPC::BCTR : P=
PC::BCTR8;
-    Chain =3D SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Other, Target,
+    Chain =3D SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
                                            Chain), 0);
     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCISelLowering.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -16,26 +16,24 @@
 #include "PPCPerfectShuffle.h"
 #include "PPCTargetMachine.h"
 #include "MCTargetDesc/PPCPredicates.h"
+#include "llvm/CallingConv.h"
+#include "llvm/Constants.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/Function.h"
+#include "llvm/Intrinsics.h"
 #include "llvm/ADT/STLExtras.h"
-#include "llvm/ADT/VectorExtras.h"
 #include "llvm/CodeGen/CallingConvLower.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
-#include "llvm/CallingConv.h"
-#include "llvm/Constants.h"
-#include "llvm/Function.h"
-#include "llvm/Intrinsics.h"
-#include "llvm/Support/MathExtras.h"
-#include "llvm/Target/TargetOptions.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/DerivedTypes.h"
+#include "llvm/Target/TargetOptions.h"
 using namespace llvm;
=20
 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &Loc=
VT,
@@ -104,6 +102,13 @@
   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
=20
+  // We do not currently implment this libm ops for PowerPC.
+  setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
+  setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
+  setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
+  setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
+  setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
+
   // PowerPC has no SREM/UREM instructions
   setOperationAction(ISD::SREM, MVT::i32, Expand);
   setOperationAction(ISD::UREM, MVT::i32, Expand);
@@ -147,9 +152,13 @@
   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
   setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
=20
   // PowerPC does not have ROTR
   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
@@ -217,11 +226,23 @@
   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
=20
-  // VAARG is custom lowered with the 32-bit SVR4 ABI.
-  if (TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
-      && !TM.getSubtarget<PPCSubtarget>().isPPC64()) {
-    setOperationAction(ISD::VAARG, MVT::Other, Custom);
-    setOperationAction(ISD::VAARG, MVT::i64, Custom);
+  if (TM.getSubtarget<PPCSubtarget>().isSVR4ABI()) {
+    if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
+      // VAARG always uses double-word chunks, so promote anything smaller.
+      setOperationAction(ISD::VAARG, MVT::i1, Promote);
+      AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
+      setOperationAction(ISD::VAARG, MVT::i8, Promote);
+      AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
+      setOperationAction(ISD::VAARG, MVT::i16, Promote);
+      AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
+      setOperationAction(ISD::VAARG, MVT::i32, Promote);
+      AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
+      setOperationAction(ISD::VAARG, MVT::Other, Expand);
+    } else {
+      // VAARG is custom lowered with the 32-bit SVR4 ABI.
+      setOperationAction(ISD::VAARG, MVT::Other, Custom);
+      setOperationAction(ISD::VAARG, MVT::i64, Custom);
+    }
   } else
     setOperationAction(ISD::VAARG, MVT::Other, Expand);
=20
@@ -333,7 +354,9 @@
       setOperationAction(ISD::FPOW, VT, Expand);
       setOperationAction(ISD::CTPOP, VT, Expand);
       setOperationAction(ISD::CTLZ, VT, Expand);
+      setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
       setOperationAction(ISD::CTTZ, VT, Expand);
+      setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
     }
=20
     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can ha=
ndle
@@ -366,6 +389,9 @@
     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
   }
=20
+  if (TM.getSubtarget<PPCSubtarget>().has64BitSupport())
+    setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
+
   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
=20
@@ -408,6 +434,8 @@
=20
   setInsertFencesForAtomic(true);
=20
+  setSchedulingPreference(Sched::Hybrid);
+
   computeRegisterProperties();
 }
=20
@@ -418,7 +446,16 @@
   // Darwin passes everything on 4 byte boundary.
   if (TM.getSubtarget<PPCSubtarget>().isDarwin())
     return 4;
-  // FIXME SVR4 TBD
+
+  // 16byte and wider vectors are passed on 16byte boundary.
+  if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
+    if (VTy->getBitWidth() >=3D 128)
+      return 16;
+
+  // The rest is 8 on PPC64 and 4 on PPC32 boundary.
+   if (PPCSubTarget.isPPC64())
+     return 8;
+
   return 4;
 }
=20
@@ -447,6 +484,7 @@
   case PPCISD::EXTSW_32:        return "PPCISD::EXTSW_32";
   case PPCISD::STD_32:          return "PPCISD::STD_32";
   case PPCISD::CALL_SVR4:       return "PPCISD::CALL_SVR4";
+  case PPCISD::CALL_NOP_SVR4:   return "PPCISD::CALL_NOP_SVR4";
   case PPCISD::CALL_Darwin:     return "PPCISD::CALL_Darwin";
   case PPCISD::NOP:             return "PPCISD::NOP";
   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
@@ -822,14 +860,10 @@
     APInt LHSKnownZero, LHSKnownOne;
     APInt RHSKnownZero, RHSKnownOne;
     DAG.ComputeMaskedBits(N.getOperand(0),
-                          APInt::getAllOnesValue(N.getOperand(0)
-                            .getValueSizeInBits()),
                           LHSKnownZero, LHSKnownOne);
=20
     if (LHSKnownZero.getBoolValue()) {
       DAG.ComputeMaskedBits(N.getOperand(1),
-                            APInt::getAllOnesValue(N.getOperand(1)
-                              .getValueSizeInBits()),
                             RHSKnownZero, RHSKnownOne);
       // If all of the bits are known zero on the LHS or RHS, the add won't
       // carry.
@@ -884,10 +918,7 @@
       // (for better address arithmetic) if the LHS and RHS of the OR are
       // provably disjoint.
       APInt LHSKnownZero, LHSKnownOne;
-      DAG.ComputeMaskedBits(N.getOperand(0),
-                            APInt::getAllOnesValue(N.getOperand(0)
-                                                   .getValueSizeInBits()),
-                            LHSKnownZero, LHSKnownOne);
+      DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
=20
       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) =3D=3D ~0ULL) {
         // If all of the bits are known zero on the LHS or RHS, the add wo=
n't
@@ -1000,10 +1031,7 @@
       // (for better address arithmetic) if the LHS and RHS of the OR are
       // provably disjoint.
       APInt LHSKnownZero, LHSKnownOne;
-      DAG.ComputeMaskedBits(N.getOperand(0),
-                            APInt::getAllOnesValue(N.getOperand(0)
-                                                   .getValueSizeInBits()),
-                            LHSKnownZero, LHSKnownOne);
+      DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) =3D=3D ~0ULL) {
         // If all of the bits are known zero on the LHS or RHS, the add wo=
n't
         // carry.
@@ -1223,7 +1251,7 @@
   // extra load to get the address of the global.
   if (MOHiFlag & PPCII::MO_NLP_FLAG)
     Ptr =3D DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointer=
Info(),
-                      false, false, 0);
+                      false, false, false, 0);
   return Ptr;
 }
=20
@@ -1319,11 +1347,13 @@
=20
   // areas
   SDValue OverflowArea =3D DAG.getLoad(MVT::i32, dl, InChain, OverflowArea=
Ptr,
-                                     MachinePointerInfo(), false, false, 0=
);
+                                     MachinePointerInfo(), false, false,
+                                     false, 0);
   InChain =3D OverflowArea.getValue(1);
=20
   SDValue RegSaveArea =3D DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPt=
r,
-                                    MachinePointerInfo(), false, false, 0);
+                                    MachinePointerInfo(), false, false,
+                                    false, 0);
   InChain =3D RegSaveArea.getValue(1);
=20
   // select overflow_area if index > 8
@@ -1372,7 +1402,8 @@
                               MachinePointerInfo(),
                               MVT::i32, false, false, 0);
=20
-  return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(), false,=
 false, 0);
+  return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),=20
+                     false, false, false, 0);
 }
=20
 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
@@ -1411,8 +1442,9 @@
   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
   std::pair<SDValue, SDValue> CallResult =3D
     LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
-                false, false, false, false, 0, CallingConv::C, false,
-                /*isReturnValueUsed=3D*/true,
+                false, false, false, false, 0, CallingConv::C,
+                /*isTailCall=3D*/false,
+                /*doesNotRet=3D*/false, /*isReturnValueUsed=3D*/true,
                 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
                 Args, DAG, dl);
=20
@@ -1530,7 +1562,7 @@
                                             CCValAssign::LocInfo &LocInfo,
                                             ISD::ArgFlagsTy &ArgFlags,
                                             CCState &State) {
-  static const unsigned ArgRegs[] =3D {
+  static const uint16_t ArgRegs[] =3D {
     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
   };
@@ -1557,7 +1589,7 @@
                                               CCValAssign::LocInfo &LocInf=
o,
                                               ISD::ArgFlagsTy &ArgFlags,
                                               CCState &State) {
-  static const unsigned ArgRegs[] =3D {
+  static const uint16_t ArgRegs[] =3D {
     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
     PPC::F8
   };
@@ -1581,8 +1613,8 @@
=20
 /// GetFPR - Get the set of FP registers that should be allocated for argu=
ments,
 /// on Darwin.
-static const unsigned *GetFPR() {
-  static const unsigned FPR[] =3D {
+static const uint16_t *GetFPR() {
+  static const uint16_t FPR[] =3D {
     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
   };
@@ -1663,7 +1695,8 @@
=20
   EVT PtrVT =3D DAG.getTargetLoweringInfo().getPointerTy();
   // Potential tail calls could cause overwriting of argument stack slots.
-  bool isImmutable =3D !(GuaranteedTailCallOpt && (CallConv=3D=3DCallingCo=
nv::Fast));
+  bool isImmutable =3D !(getTargetMachine().Options.GuaranteedTailCallOpt =
&&
+                       (CallConv =3D=3D CallingConv::Fast));
   unsigned PtrByteSize =3D 4;
=20
   // Assign locations to all of the incoming arguments.
@@ -1681,7 +1714,7 @@
=20
     // Arguments stored in registers.
     if (VA.isRegLoc()) {
-      TargetRegisterClass *RC;
+      const TargetRegisterClass *RC;
       EVT ValVT =3D VA.getValVT();
=20
       switch (ValVT.getSimpleVT().SimpleTy) {
@@ -1721,7 +1754,7 @@
       SDValue FIN =3D DAG.getFrameIndex(FI, PtrVT);
       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
                                    MachinePointerInfo(),
-                                   false, false, 0));
+                                   false, false, false, 0));
     }
   }
=20
@@ -1762,13 +1795,13 @@
   // If the function takes variable number of arguments, make a frame inde=
x for
   // the start of the first vararg value... for expansion of llvm.va_start.
   if (isVarArg) {
-    static const unsigned GPArgRegs[] =3D {
+    static const uint16_t GPArgRegs[] =3D {
       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
     };
     const unsigned NumGPArgRegs =3D array_lengthof(GPArgRegs);
=20
-    static const unsigned FPArgRegs[] =3D {
+    static const uint16_t FPArgRegs[] =3D {
       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
       PPC::F8
     };
@@ -1853,25 +1886,26 @@
   EVT PtrVT =3D DAG.getTargetLoweringInfo().getPointerTy();
   bool isPPC64 =3D PtrVT =3D=3D MVT::i64;
   // Potential tail calls could cause overwriting of argument stack slots.
-  bool isImmutable =3D !(GuaranteedTailCallOpt && (CallConv=3D=3DCallingCo=
nv::Fast));
+  bool isImmutable =3D !(getTargetMachine().Options.GuaranteedTailCallOpt =
&&
+                       (CallConv =3D=3D CallingConv::Fast));
   unsigned PtrByteSize =3D isPPC64 ? 8 : 4;
=20
   unsigned ArgOffset =3D PPCFrameLowering::getLinkageSize(isPPC64, true);
   // Area that is at least reserved in caller of this function.
   unsigned MinReservedArea =3D ArgOffset;
=20
-  static const unsigned GPR_32[] =3D {           // 32-bit registers.
+  static const uint16_t GPR_32[] =3D {           // 32-bit registers.
     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
   };
-  static const unsigned GPR_64[] =3D {           // 64-bit registers.
+  static const uint16_t GPR_64[] =3D {           // 64-bit registers.
     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
   };
=20
-  static const unsigned *FPR =3D GetFPR();
-
-  static const unsigned VR[] =3D {
+  static const uint16_t *FPR =3D GetFPR();
+
+  static const uint16_t VR[] =3D {
     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
   };
@@ -1882,7 +1916,7 @@
=20
   unsigned GPR_idx =3D 0, FPR_idx =3D 0, VR_idx =3D 0;
=20
-  const unsigned *GPR =3D isPPC64 ? GPR_64 : GPR_32;
+  const uint16_t *GPR =3D isPPC64 ? GPR_64 : GPR_32;
=20
   // In 32-bit non-varargs functions, the stack space for vectors is after=
 the
   // stack space for non-vectors.  We do not use this space unless we have
@@ -1896,12 +1930,11 @@
     for (unsigned ArgNo =3D 0, e =3D Ins.size(); ArgNo !=3D e;
          ++ArgNo) {
       EVT ObjectVT =3D Ins[ArgNo].VT;
-      unsigned ObjSize =3D ObjectVT.getSizeInBits()/8;
       ISD::ArgFlagsTy Flags =3D Ins[ArgNo].Flags;
=20
       if (Flags.isByVal()) {
         // ObjSize is the true size, ArgSize rounded up to multiple of reg=
s.
-        ObjSize =3D Flags.getByValSize();
+        unsigned ObjSize =3D Flags.getByValSize();
         unsigned ArgSize =3D
                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
         VecArgOffset +=3D ArgSize;
@@ -2138,7 +2171,7 @@
                                       isImmutable);
       SDValue FIN =3D DAG.getFrameIndex(FI, PtrVT);
       ArgVal =3D DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(=
),
-                           false, false, 0);
+                           false, false, false, 0);
     }
=20
     InVals.push_back(ArgVal);
@@ -2259,9 +2292,9 @@
                       PPCFrameLowering::getMinCallFrameSize(isPPC64, true)=
);
=20
   // Tail call needs the stack to be aligned.
-  if (CC=3D=3DCallingConv::Fast && GuaranteedTailCallOpt) {
-    unsigned TargetAlign =3D DAG.getMachineFunction().getTarget().getFrame=
Lowering()->
-      getStackAlignment();
+  if (CC =3D=3D CallingConv::Fast && DAG.getTarget().Options.GuaranteedTai=
lCallOpt){
+    unsigned TargetAlign =3D DAG.getMachineFunction().getTarget().
+      getFrameLowering()->getStackAlignment();
     unsigned AlignMask =3D TargetAlign-1;
     NumBytes =3D (NumBytes + AlignMask) & ~AlignMask;
   }
@@ -2295,7 +2328,7 @@
                                                      bool isVarArg,
                                       const SmallVectorImpl<ISD::InputArg>=
 &Ins,
                                                      SelectionDAG& DAG) co=
nst {
-  if (!GuaranteedTailCallOpt)
+  if (!getTargetMachine().Options.GuaranteedTailCallOpt)
     return false;
=20
   // Variable argument functions are not supported.
@@ -2443,7 +2476,7 @@
     EVT VT =3D PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
     LROpOut =3D getReturnAddrFrameIndex(DAG);
     LROpOut =3D DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
-                          false, false, 0);
+                          false, false, false, 0);
     Chain =3D SDValue(LROpOut.getNode(), 1);
=20
     // When using the 32/64-bit SVR4 ABI there is no need to load the FP s=
tack
@@ -2451,7 +2484,7 @@
     if (isDarwinABI) {
       FPOpOut =3D getFramePointerFrameIndex(DAG);
       FPOpOut =3D DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
-                            false, false, 0);
+                            false, false, false, 0);
       Chain =3D SDValue(FPOpOut.getNode(), 1);
     }
   }
@@ -2748,7 +2781,14 @@
   // the stack. Account for this here so these bytes can be pushed back on=
 in
   // PPCRegisterInfo::eliminateCallFramePseudoInstr.
   int BytesCalleePops =3D
-    (CallConv=3D=3DCallingConv::Fast && GuaranteedTailCallOpt) ? NumBytes =
: 0;
+    (CallConv =3D=3D CallingConv::Fast &&
+     getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
+
+  // Add a register mask operand representing the call-preserved registers.
+  const TargetRegisterInfo *TRI =3D getTargetMachine().getRegisterInfo();
+  const uint32_t *Mask =3D TRI->getCallPreservedMask(CallConv);
+  assert(Mask && "Missing call preserved mask for calling convention");
+  Ops.push_back(DAG.getRegisterMask(Mask));
=20
   if (InFlag.getNode())
     Ops.push_back(InFlag);
@@ -2776,9 +2816,6 @@
     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.siz=
e());
   }
=20
-  Chain =3D DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
-  InFlag =3D Chain.getValue(1);
-
   // Add a NOP immediately after the branch instruction when using the 64-=
bit
   // SVR4 ABI. At link time, if caller and callee are in a different modul=
e and
   // thus have a different TOC, the call will be replaced with a call to a=
 stub
@@ -2787,8 +2824,9 @@
   // which restores the TOC of the caller from the TOC save slot of the cu=
rrent
   // stack frame. If caller and callee belong to the same module (and have=
 the
   // same TOC), the NOP will remain unchanged.
+
+  bool needsTOCRestore =3D false;
   if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
-    SDVTList VTs =3D DAG.getVTList(MVT::Other, MVT::Glue);
     if (CallOpc =3D=3D PPCISD::BCTRL_SVR4) {
       // This is a call through a function pointer.
       // Restore the caller TOC from the save area into R2.
@@ -2799,14 +2837,22 @@
       // since r2 is a reserved register (which prevents the register allo=
cator
       // from allocating it), resulting in an additional register being
       // allocated and an unnecessary move instruction being generated.
-      Chain =3D DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
-      InFlag =3D Chain.getValue(1);
-    } else {
+      needsTOCRestore =3D true;
+    } else if (CallOpc =3D=3D PPCISD::CALL_SVR4) {
       // Otherwise insert NOP.
-      InFlag =3D DAG.getNode(PPCISD::NOP, dl, MVT::Glue, InFlag);
+      CallOpc =3D PPCISD::CALL_NOP_SVR4;
     }
   }
=20
+  Chain =3D DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
+  InFlag =3D Chain.getValue(1);
+
+  if (needsTOCRestore) {
+    SDVTList VTs =3D DAG.getVTList(MVT::Other, MVT::Glue);
+    Chain =3D DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
+    InFlag =3D Chain.getValue(1);
+  }
+
   Chain =3D DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true=
),
                              DAG.getIntPtrConstant(BytesCalleePops, true),
                              InFlag);
@@ -2820,7 +2866,7 @@
 SDValue
 PPCTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                              CallingConv::ID CallConv, bool isVarArg,
-                             bool &isTailCall,
+                             bool doesNotRet, bool &isTailCall,
                              const SmallVectorImpl<ISD::OutputArg> &Outs,
                              const SmallVectorImpl<SDValue> &OutVals,
                              const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -2864,7 +2910,8 @@
   // and restoring the callers stack pointer in this functions epilog. Thi=
s is
   // done because by tail calling the called function might overwrite the =
value
   // in this function's (MF) stack pointer stack slot 0(SP).
-  if (GuaranteedTailCallOpt && CallConv=3D=3DCallingConv::Fast)
+  if (getTargetMachine().Options.GuaranteedTailCallOpt &&
+      CallConv =3D=3D CallingConv::Fast)
     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
=20
   // Count how many bytes are to be pushed on the stack, including the lin=
kage
@@ -3071,7 +3118,8 @@
   // and restoring the callers stack pointer in this functions epilog. Thi=
s is
   // done because by tail calling the called function might overwrite the =
value
   // in this function's (MF) stack pointer stack slot 0(SP).
-  if (GuaranteedTailCallOpt && CallConv=3D=3DCallingConv::Fast)
+  if (getTargetMachine().Options.GuaranteedTailCallOpt &&
+      CallConv =3D=3D CallingConv::Fast)
     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
=20
   unsigned nAltivecParamsAtEnd =3D 0;
@@ -3120,17 +3168,17 @@
   unsigned ArgOffset =3D PPCFrameLowering::getLinkageSize(isPPC64, true);
   unsigned GPR_idx =3D 0, FPR_idx =3D 0, VR_idx =3D 0;
=20
-  static const unsigned GPR_32[] =3D {           // 32-bit registers.
+  static const uint16_t GPR_32[] =3D {           // 32-bit registers.
     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
   };
-  static const unsigned GPR_64[] =3D {           // 64-bit registers.
+  static const uint16_t GPR_64[] =3D {           // 64-bit registers.
     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
   };
-  static const unsigned *FPR =3D GetFPR();
-
-  static const unsigned VR[] =3D {
+  static const uint16_t *FPR =3D GetFPR();
+
+  static const uint16_t VR[] =3D {
     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
   };
@@ -3138,7 +3186,7 @@
   const unsigned NumFPRs =3D 13;
   const unsigned NumVRs  =3D array_lengthof(VR);
=20
-  const unsigned *GPR =3D isPPC64 ? GPR_64 : GPR_32;
+  const uint16_t *GPR =3D isPPC64 ? GPR_64 : GPR_32;
=20
   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
@@ -3212,7 +3260,7 @@
         if (GPR_idx !=3D NumGPRs) {
           SDValue Load =3D DAG.getLoad(PtrVT, dl, Chain, AddArg,
                                      MachinePointerInfo(),
-                                     false, false, 0);
+                                     false, false, false, 0);
           MemOpChains.push_back(Load.getValue(1));
           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
           ArgOffset +=3D PtrByteSize;
@@ -3250,7 +3298,8 @@
           // Float varargs are always shadowed in available integer regist=
ers
           if (GPR_idx !=3D NumGPRs) {
             SDValue Load =3D DAG.getLoad(PtrVT, dl, Store, PtrOff,
-                                       MachinePointerInfo(), false, false,=
 0);
+                                       MachinePointerInfo(), false, false,
+                                       false, 0);
             MemOpChains.push_back(Load.getValue(1));
             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
           }
@@ -3259,7 +3308,7 @@
             PtrOff =3D DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
             SDValue Load =3D DAG.getLoad(PtrVT, dl, Store, PtrOff,
                                        MachinePointerInfo(),
-                                       false, false, 0);
+                                       false, false, false, 0);
             MemOpChains.push_back(Load.getValue(1));
             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
           }
@@ -3308,7 +3357,7 @@
         if (VR_idx !=3D NumVRs) {
           SDValue Load =3D DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
                                      MachinePointerInfo(),
-                                     false, false, 0);
+                                     false, false, false, 0);
           MemOpChains.push_back(Load.getValue(1));
           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
         }
@@ -3319,7 +3368,7 @@
           SDValue Ix =3D DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
                                   DAG.getConstant(i, PtrVT));
           SDValue Load =3D DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointe=
rInfo(),
-                                     false, false, 0);
+                                     false, false, false, 0);
           MemOpChains.push_back(Load.getValue(1));
           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
         }
@@ -3483,7 +3532,7 @@
   // Load the old link SP.
   SDValue LoadLinkSP =3D DAG.getLoad(PtrVT, dl, Chain, StackPtr,
                                    MachinePointerInfo(),
-                                   false, false, 0);
+                                   false, false, false, 0);
=20
   // Restore the stack pointer.
   Chain =3D DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
@@ -3674,7 +3723,7 @@
     FIPtr =3D DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
                         DAG.getConstant(4, FIPtr.getValueType()));
   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerIn=
fo(),
-                     false, false, 0);
+                     false, false, false, 0);
 }
=20
 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
@@ -3718,7 +3767,7 @@
                             Ops, 4, MVT::i64, MMO);
   // Load the value as a double.
   SDValue Ld =3D DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo=
(),
-                           false, false, 0);
+                           false, false, false, 0);
=20
   // FCFID it and return it.
   SDValue FP =3D DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
@@ -3770,7 +3819,7 @@
   SDValue Four =3D DAG.getConstant(4, PtrVT);
   SDValue Addr =3D DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
   SDValue CWD =3D DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInf=
o(),
-                            false, false, 0);
+                            false, false, false, 0);
=20
   // Transform as necessary
   SDValue CWD1 =3D
@@ -4236,8 +4285,7 @@
=20
   // Check to see if this is a shuffle of 4-byte values.  If so, we can us=
e our
   // perfect shuffle table to emit an optimal matching sequence.
-  SmallVector<int, 16> PermMask;
-  SVOp->getMask(PermMask);
+  ArrayRef<int> PermMask =3D SVOp->getMask();
=20
   unsigned PFIndexes[4];
   bool isFourElementShuffle =3D true;
@@ -4441,7 +4489,7 @@
                                false, false, 0);
   // Load it out.
   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInf=
o(),
-                     false, false, 0);
+                     false, false, false, 0);
 }
=20
 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
@@ -4549,7 +4597,6 @@
   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
   }
-  return SDValue();
 }
=20
 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
@@ -4559,8 +4606,7 @@
   DebugLoc dl =3D N->getDebugLoc();
   switch (N->getOpcode()) {
   default:
-    assert(false && "Do not know how to custom type legalize this operatio=
n!");
-    return;
+    llvm_unreachable("Do not know how to custom type legalize this operati=
on!");
   case ISD::VAARG: {
     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
         || TM.getSubtarget<PPCSubtarget>().isPPC64())
@@ -5461,12 +5507,11 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
-                                                       const APInt &Mask,
                                                        APInt &KnownZero,
                                                        APInt &KnownOne,
                                                        const SelectionDAG =
&DAG,
                                                        unsigned Depth) con=
st {
-  KnownZero =3D KnownOne =3D APInt(Mask.getBitWidth(), 0);
+  KnownZero =3D KnownOne =3D APInt(KnownZero.getBitWidth(), 0);
   switch (Op.getOpcode()) {
   default: break;
   case PPCISD::LBRX: {
@@ -5700,7 +5745,7 @@
   return (V > -(1 << 16) && V < (1 << 16)-1);
 }
=20
-bool PPCTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) con=
st {
+bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
   return false;
 }
=20
@@ -5729,13 +5774,13 @@
     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
                                    FrameAddr, Offset),
-                       MachinePointerInfo(), false, false, 0);
+                       MachinePointerInfo(), false, false, false, 0);
   }
=20
   // Just load the return address off the stack.
   SDValue RetAddrFI =3D getReturnAddrFrameIndex(DAG);
   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
-                     RetAddrFI, MachinePointerInfo(), false, false, 0);
+                     RetAddrFI, MachinePointerInfo(), false, false, false,=
 0);
 }
=20
 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
@@ -5749,7 +5794,8 @@
   MachineFunction &MF =3D DAG.getMachineFunction();
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
   MFI->setFrameAddressIsTaken(true);
-  bool is31 =3D (DisableFramePointerElim(MF) || MFI->hasVarSizedObjects())=
 &&
+  bool is31 =3D (getTargetMachine().Options.DisableFramePointerElim(MF) ||
+               MFI->hasVarSizedObjects()) &&
                   MFI->getStackSize() &&
                   !MF.getFunction()->hasFnAttr(Attribute::Naked);
   unsigned FrameReg =3D isPPC64 ? (is31 ? PPC::X31 : PPC::X1) :
@@ -5758,7 +5804,8 @@
                                          PtrVT);
   while (Depth--)
     FrameAddr =3D DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
-                            FrameAddr, MachinePointerInfo(), false, false,=
 0);
+                            FrameAddr, MachinePointerInfo(), false, false,
+                            false, 0);
   return FrameAddr;
 }
=20
@@ -5774,7 +5821,7 @@
 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
 /// means there isn't a need to check it against alignment requirement,
 /// probably because the source does not need to be loaded. If
-/// 'NonScalarIntSafe' is true, that means it's safe to return a
+/// 'IsZeroVal' is true, that means it's safe to return a
 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
 /// constant so it does not need to be loaded.
@@ -5782,7 +5829,7 @@
 /// target-independent logic.
 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
                                            unsigned DstAlign, unsigned Src=
Align,
-                                           bool NonScalarIntSafe,
+                                           bool IsZeroVal,
                                            bool MemcpyStrSrc,
                                            MachineFunction &MF) const {
   if (this->PPCSubTarget.isPPC64()) {
@@ -5791,3 +5838,12 @@
     return MVT::i32;
   }
 }
+
+Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) co=
nst {
+  unsigned Directive =3D PPCSubTarget.getDarwinDirective();
+  if (Directive =3D=3D PPC::DIR_440 || Directive =3D=3D PPC::DIR_A2)
+    return Sched::ILP;
+
+  return TargetLowering::getSchedulingPreference(N);
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCISelLowering.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCISelLowering.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,10 +15,10 @@
 #ifndef LLVM_TARGET_POWERPC_PPC32ISELLOWERING_H
 #define LLVM_TARGET_POWERPC_PPC32ISELLOWERING_H
=20
+#include "PPC.h"
+#include "PPCSubtarget.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/CodeGen/SelectionDAG.h"
-#include "PPC.h"
-#include "PPCSubtarget.h"
=20
 namespace llvm {
   namespace PPCISD {
@@ -95,7 +95,9 @@
       EXTSW_32,
=20
       /// CALL - A direct function call.
-      CALL_Darwin, CALL_SVR4,
+      /// CALL_NOP_SVR4 is a call with the special  NOP which follows 64-b=
it
+      /// SVR4 calls.
+      CALL_Darwin, CALL_SVR4, CALL_NOP_SVR4,
=20
       /// NOP - Special NOP which follows 64-bit SVR4 calls.
       NOP,
@@ -279,6 +281,7 @@
     bool SelectAddressRegImmShift(SDValue N, SDValue &Disp, SDValue &Base,
                                   SelectionDAG &DAG) const;
=20
+    Sched::Preference getSchedulingPreference(SDNode *N) const;
=20
     /// LowerOperation - Provide custom lowering hooks for some operations.
     ///
@@ -293,7 +296,6 @@
     virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) con=
st;
=20
     virtual void computeMaskedBitsForTargetNode(const SDValue Op,
-                                                const APInt &Mask,
                                                 APInt &KnownZero,
                                                 APInt &KnownOne,
                                                 const SelectionDAG &DAG,
@@ -353,7 +355,7 @@
     /// alignment can satisfy any constraint. Similarly if SrcAlign is zer=
o it
     /// means there isn't a need to check it against alignment requirement,
     /// probably because the source does not need to be loaded. If
-    /// 'NonScalarIntSafe' is true, that means it's safe to return a
+    /// 'IsZeroVal' is true, that means it's safe to return a
     /// non-scalar-integer type, e.g. empty string source, constant, or lo=
aded
     /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
     /// constant so it does not need to be loaded.
@@ -361,7 +363,7 @@
     /// target-independent logic.
     virtual EVT
     getOptimalMemOpType(uint64_t Size, unsigned DstAlign, unsigned SrcAlig=
n,
-                        bool NonScalarIntSafe, bool MemcpyStrSrc,
+                        bool IsZeroVal, bool MemcpyStrSrc,
                         MachineFunction &MF) const;
=20
   private:
@@ -437,8 +439,8 @@
                            SmallVectorImpl<SDValue> &InVals) const;
=20
     virtual SDValue
-      LowerCall(SDValue Chain, SDValue Callee,
-                CallingConv::ID CallConv, bool isVarArg, bool &isTailCall,
+      LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
+                bool isVarArg, bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -472,21 +474,21 @@
                                 SmallVectorImpl<SDValue> &InVals) const;
=20
     SDValue
-      LowerCall_Darwin(SDValue Chain, SDValue Callee,
-                       CallingConv::ID CallConv, bool isVarArg, bool isTai=
lCall,
+      LowerCall_Darwin(SDValue Chain, SDValue Callee, CallingConv::ID Call=
Conv,
+                       bool isVarArg, bool isTailCall,
                        const SmallVectorImpl<ISD::OutputArg> &Outs,
                        const SmallVectorImpl<SDValue> &OutVals,
                        const SmallVectorImpl<ISD::InputArg> &Ins,
                        DebugLoc dl, SelectionDAG &DAG,
                        SmallVectorImpl<SDValue> &InVals) const;
     SDValue
-      LowerCall_SVR4(SDValue Chain, SDValue Callee,
-                     CallingConv::ID CallConv, bool isVarArg, bool isTailC=
all,
-                     const SmallVectorImpl<ISD::OutputArg> &Outs,
-                     const SmallVectorImpl<SDValue> &OutVals,
-                     const SmallVectorImpl<ISD::InputArg> &Ins,
-                     DebugLoc dl, SelectionDAG &DAG,
-                     SmallVectorImpl<SDValue> &InVals) const;
+    LowerCall_SVR4(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
+                   bool isVarArg, bool isTailCall,
+                   const SmallVectorImpl<ISD::OutputArg> &Outs,
+                   const SmallVectorImpl<SDValue> &OutVals,
+                   const SmallVectorImpl<ISD::InputArg> &Ins,
+                   DebugLoc dl, SelectionDAG &DAG,
+                   SmallVectorImpl<SDValue> &InVals) const;
   };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCInstr64Bit.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCInstr64Bit.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCInstr64Bit.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCInstr64Bit.td - The PowerPC 64-bit Support -------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCInstr64Bit.td - The PowerPC 64-bit Support ------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the PowerPC 64-bit instructions.  These patterns ar=
e used
@@ -64,13 +64,7 @@
                     PPC970_Unit_BRU;
=20
 // Darwin ABI Calls.
-let isCall =3D 1, PPC970_Unit =3D 7,=20
-  // All calls clobber the PPC64 non-callee saved registers.
-  Defs =3D [X0,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,
-          F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,F13,
-          V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,V13,V14,V15,V16,V17,V1=
8,V19,
-          LR8,CTR8,
-          CR0,CR1,CR5,CR6,CR7,CARRY] in {
+let isCall =3D 1, PPC970_Unit =3D 7, Defs =3D [LR8] in {
   // Convenient aliases for call instructions
   let Uses =3D [RM] in {
     def BL8_Darwin  : IForm<18, 0, 1,
@@ -90,23 +84,29 @@
=20
 // ELF 64 ABI Calls =3D Darwin ABI Calls
 // Used to define BL8_ELF and BLA8_ELF
-let isCall =3D 1, PPC970_Unit =3D 7,=20
-  // All calls clobber the PPC64 non-callee saved registers.
-  Defs =3D [X0,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,
-          F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,F13,
-          V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,V13,V14,V15,V16,V17,V1=
8,V19,
-          LR8,CTR8,
-          CR0,CR1,CR5,CR6,CR7,CARRY] in {
+let isCall =3D 1, PPC970_Unit =3D 7, Defs =3D [LR8] in {
   // Convenient aliases for call instructions
   let Uses =3D [RM] in {
     def BL8_ELF  : IForm<18, 0, 1,
                          (outs), (ins calltarget:$func, variable_ops),=20
-                         "bl $func", BrB, []>;  // See Pat patterns below.=
                           =20
+                         "bl $func", BrB, []>;  // See Pat patterns below.
+
+    let isCodeGenOnly =3D 1 in
+    def BL8_NOP_ELF  : IForm_and_DForm_4_zero<18, 0, 1, 24,
+                             (outs), (ins calltarget:$func, variable_ops),=20
+                             "bl $func\n\tnop", BrB, []>;
+
     def BLA8_ELF : IForm<18, 1, 1,
                          (outs), (ins aaddr:$func, variable_ops),
                          "bla $func", BrB, [(PPCcall_SVR4 (i64 imm:$func))=
]>;
+
+    let isCodeGenOnly =3D 1 in
+    def BLA8_NOP_ELF : IForm_and_DForm_4_zero<18, 1, 1, 24,
+                             (outs), (ins aaddr:$func, variable_ops),
+                             "bla $func\n\tnop", BrB,
+                             [(PPCcall_nop_SVR4 (i64 imm:$func))]>;
   }
-  let Uses =3D [CTR8, RM] in {
+  let Uses =3D [X11, CTR8, RM] in {
     def BCTRL8_ELF : XLForm_2_ext<19, 528, 20, 0, 1,
                                (outs), (ins variable_ops),
                                "bctrl", BrB,
@@ -123,8 +123,14 @@
=20
 def : Pat<(PPCcall_SVR4 (i64 tglobaladdr:$dst)),
           (BL8_ELF tglobaladdr:$dst)>;
+def : Pat<(PPCcall_nop_SVR4 (i64 tglobaladdr:$dst)),
+          (BL8_NOP_ELF tglobaladdr:$dst)>;
+
 def : Pat<(PPCcall_SVR4 (i64 texternalsym:$dst)),
           (BL8_ELF texternalsym:$dst)>;
+def : Pat<(PPCcall_nop_SVR4 (i64 texternalsym:$dst)),
+          (BL8_NOP_ELF texternalsym:$dst)>;
+
 def : Pat<(PPCnop),
           (NOP)>;
=20
@@ -223,6 +229,18 @@
 def : Pat<(PPCtc_return CTRRC8:$dst, imm:$imm),
           (TCRETURNri8 CTRRC8:$dst, imm:$imm)>;
=20
+// 64-but CR instructions
+def MTCRF8 : XFXForm_5<31, 144, (outs crbitm:$FXM), (ins G8RC:$rS),
+                      "mtcrf $FXM, $rS", BrMCRX>,
+            PPC970_MicroCode, PPC970_Unit_CRU;
+
+def MFCR8pseud: XFXForm_3<31, 19, (outs G8RC:$rT), (ins crbitm:$FXM),
+                       "", SprMFCR>,
+            PPC970_MicroCode, PPC970_Unit_CRU;
+           =20
+def MFCR8 : XFXForm_3<31, 19, (outs G8RC:$rT), (ins),
+                     "mfcr $rT", SprMFCR>,
+                     PPC970_MicroCode, PPC970_Unit_CRU;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // 64-bit SPR manipulation instrs.
@@ -469,6 +487,12 @@
                       (outs G8RC:$rA), (ins G8RC:$rS, u6imm:$SH, u6imm:$ME=
),
                       "rldicr $rA, $rS, $SH, $ME", IntRotateD,
                       []>, isPPC64;
+
+def RLWINM8 : MForm_2<21,
+                     (outs G8RC:$rA), (ins G8RC:$rS, u5imm:$SH, u5imm:$MB,=
 u5imm:$ME),
+                     "rlwinm $rA, $rS, $SH, $MB, $ME", IntGeneral,
+                     []>;
+
 }  // End FXU Operations.
=20
=20
@@ -500,7 +524,7 @@
 let mayLoad =3D 1 in
 def LHAU8 : DForm_1a<43, (outs G8RC:$rD, ptr_rc:$ea_result), (ins symbolLo=
:$disp,
                             ptr_rc:$rA),
-                    "lhau $rD, $disp($rA)", LdStGeneral,
+                    "lhau $rD, $disp($rA)", LdStLoad,
                     []>, RegConstraint<"$rA =3D $ea_result">,
                     NoEncode<"$ea_result">;
 // NO LWAU!
@@ -510,38 +534,38 @@
 // Zero extending loads.
 let canFoldAsLoad =3D 1, PPC970_Unit =3D 2 in {
 def LBZ8 : DForm_1<34, (outs G8RC:$rD), (ins memri:$src),
-                  "lbz $rD, $src", LdStGeneral,
+                  "lbz $rD, $src", LdStLoad,
                   [(set G8RC:$rD, (zextloadi8 iaddr:$src))]>;
 def LHZ8 : DForm_1<40, (outs G8RC:$rD), (ins memri:$src),
-                  "lhz $rD, $src", LdStGeneral,
+                  "lhz $rD, $src", LdStLoad,
                   [(set G8RC:$rD, (zextloadi16 iaddr:$src))]>;
 def LWZ8 : DForm_1<32, (outs G8RC:$rD), (ins memri:$src),
-                  "lwz $rD, $src", LdStGeneral,
+                  "lwz $rD, $src", LdStLoad,
                   [(set G8RC:$rD, (zextloadi32 iaddr:$src))]>, isPPC64;
=20
 def LBZX8 : XForm_1<31,  87, (outs G8RC:$rD), (ins memrr:$src),
-                   "lbzx $rD, $src", LdStGeneral,
+                   "lbzx $rD, $src", LdStLoad,
                    [(set G8RC:$rD, (zextloadi8 xaddr:$src))]>;
 def LHZX8 : XForm_1<31, 279, (outs G8RC:$rD), (ins memrr:$src),
-                   "lhzx $rD, $src", LdStGeneral,
+                   "lhzx $rD, $src", LdStLoad,
                    [(set G8RC:$rD, (zextloadi16 xaddr:$src))]>;
 def LWZX8 : XForm_1<31,  23, (outs G8RC:$rD), (ins memrr:$src),
-                   "lwzx $rD, $src", LdStGeneral,
+                   "lwzx $rD, $src", LdStLoad,
                    [(set G8RC:$rD, (zextloadi32 xaddr:$src))]>;
                   =20
                   =20
 // Update forms.
 let mayLoad =3D 1 in {
 def LBZU8 : DForm_1<35, (outs G8RC:$rD, ptr_rc:$ea_result), (ins memri:$ad=
dr),
-                    "lbzu $rD, $addr", LdStGeneral,
+                    "lbzu $rD, $addr", LdStLoad,
                     []>, RegConstraint<"$addr.reg =3D $ea_result">,
                     NoEncode<"$ea_result">;
 def LHZU8 : DForm_1<41, (outs G8RC:$rD, ptr_rc:$ea_result), (ins memri:$ad=
dr),
-                    "lhzu $rD, $addr", LdStGeneral,
+                    "lhzu $rD, $addr", LdStLoad,
                     []>, RegConstraint<"$addr.reg =3D $ea_result">,
                     NoEncode<"$ea_result">;
 def LWZU8 : DForm_1<33, (outs G8RC:$rD, ptr_rc:$ea_result), (ins memri:$ad=
dr),
-                    "lwzu $rD, $addr", LdStGeneral,
+                    "lwzu $rD, $addr", LdStLoad,
                     []>, RegConstraint<"$addr.reg =3D $ea_result">,
                     NoEncode<"$ea_result">;
 }
@@ -557,7 +581,8 @@
                   "",
                   [(set G8RC:$rD,
                      (PPCtoc_entry tglobaladdr:$disp, G8RC:$reg))]>, isPPC=
64;
-                    =20
+
+let hasSideEffects =3D 1 in {=20
 let RST =3D 2, DS_RA =3D 0 in // FIXME: Should be a pseudo.
 def LDinto_toc: DSForm_1<58, 0, (outs), (ins G8RC:$reg),
                     "ld 2, 8($reg)", LdStLD,
@@ -567,6 +592,7 @@
 def LDtoc_restore : DSForm_1<58, 0, (outs), (ins),
                     "ld 2, 40(1)", LdStLD,
                     [(PPCtoc_restore)]>, isPPC64;
+}
 def LDX  : XForm_1<31,  21, (outs G8RC:$rD), (ins memrr:$src),
                    "ldx $rD, $src", LdStLD,
                    [(set G8RC:$rD, (load xaddr:$src))]>, isPPC64;
@@ -587,24 +613,24 @@
 let PPC970_Unit =3D 2 in {
 // Truncating stores.                      =20
 def STB8 : DForm_1<38, (outs), (ins G8RC:$rS, memri:$src),
-                   "stb $rS, $src", LdStGeneral,
+                   "stb $rS, $src", LdStStore,
                    [(truncstorei8 G8RC:$rS, iaddr:$src)]>;
 def STH8 : DForm_1<44, (outs), (ins G8RC:$rS, memri:$src),
-                   "sth $rS, $src", LdStGeneral,
+                   "sth $rS, $src", LdStStore,
                    [(truncstorei16 G8RC:$rS, iaddr:$src)]>;
 def STW8 : DForm_1<36, (outs), (ins G8RC:$rS, memri:$src),
-                   "stw $rS, $src", LdStGeneral,
+                   "stw $rS, $src", LdStStore,
                    [(truncstorei32 G8RC:$rS, iaddr:$src)]>;
 def STBX8 : XForm_8<31, 215, (outs), (ins G8RC:$rS, memrr:$dst),
-                   "stbx $rS, $dst", LdStGeneral,
+                   "stbx $rS, $dst", LdStStore,
                    [(truncstorei8 G8RC:$rS, xaddr:$dst)]>,=20
                    PPC970_DGroup_Cracked;
 def STHX8 : XForm_8<31, 407, (outs), (ins G8RC:$rS, memrr:$dst),
-                   "sthx $rS, $dst", LdStGeneral,
+                   "sthx $rS, $dst", LdStStore,
                    [(truncstorei16 G8RC:$rS, xaddr:$dst)]>,=20
                    PPC970_DGroup_Cracked;
 def STWX8 : XForm_8<31, 151, (outs), (ins G8RC:$rS, memrr:$dst),
-                   "stwx $rS, $dst", LdStGeneral,
+                   "stwx $rS, $dst", LdStStore,
                    [(truncstorei32 G8RC:$rS, xaddr:$dst)]>,
                    PPC970_DGroup_Cracked;
 // Normal 8-byte stores.
@@ -621,14 +647,14 @@
=20
 def STBU8 : DForm_1a<38, (outs ptr_rc:$ea_res), (ins G8RC:$rS,
                              symbolLo:$ptroff, ptr_rc:$ptrreg),
-                    "stbu $rS, $ptroff($ptrreg)", LdStGeneral,
+                    "stbu $rS, $ptroff($ptrreg)", LdStStore,
                     [(set ptr_rc:$ea_res,
                           (pre_truncsti8 G8RC:$rS, ptr_rc:$ptrreg,=20
                                          iaddroff:$ptroff))]>,
                     RegConstraint<"$ptrreg =3D $ea_res">, NoEncode<"$ea_re=
s">;
 def STHU8 : DForm_1a<45, (outs ptr_rc:$ea_res), (ins G8RC:$rS,
                              symbolLo:$ptroff, ptr_rc:$ptrreg),
-                    "sthu $rS, $ptroff($ptrreg)", LdStGeneral,
+                    "sthu $rS, $ptroff($ptrreg)", LdStStore,
                     [(set ptr_rc:$ea_res,
                         (pre_truncsti16 G8RC:$rS, ptr_rc:$ptrreg,=20
                                         iaddroff:$ptroff))]>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCInstrAltivec.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCInstrAltivec.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCInstrAltivec.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCInstrAltivec.td - The PowerPC Altivec Extension --*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCInstrAltivec.td - The PowerPC Altivec Extension -*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the Altivec extension to the PowerPC instruction se=
t.
@@ -188,85 +188,85 @@
=20
 def DSS      : DSS_Form<822, (outs),
                         (ins u5imm:$ZERO0, u5imm:$STRM,u5imm:$ZERO1,u5imm:=
$ZERO2),
-                        "dss $STRM", LdStGeneral /*FIXME*/, []>;
+                        "dss $STRM", LdStLoad /*FIXME*/, []>;
 def DSSALL   : DSS_Form<822, (outs),
                         (ins u5imm:$ONE, u5imm:$ZERO0,u5imm:$ZERO1,u5imm:$=
ZERO2),
-                        "dssall", LdStGeneral /*FIXME*/, []>;
+                        "dssall", LdStLoad /*FIXME*/, []>;
 def DST      : DSS_Form<342, (outs),
                         (ins u5imm:$ZERO, u5imm:$STRM, GPRC:$rA, GPRC:$rB),
-                        "dst $rA, $rB, $STRM", LdStGeneral /*FIXME*/, []>;
+                        "dst $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
 def DSTT     : DSS_Form<342, (outs),
                         (ins u5imm:$ONE, u5imm:$STRM, GPRC:$rA, GPRC:$rB),
-                        "dstt $rA, $rB, $STRM", LdStGeneral /*FIXME*/, []>;
+                        "dstt $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
 def DSTST    : DSS_Form<374, (outs),
                         (ins u5imm:$ZERO, u5imm:$STRM, GPRC:$rA, GPRC:$rB),
-                        "dstst $rA, $rB, $STRM", LdStGeneral /*FIXME*/, []=
>;
+                        "dstst $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
 def DSTSTT   : DSS_Form<374, (outs),
                         (ins u5imm:$ONE, u5imm:$STRM, GPRC:$rA, GPRC:$rB),
-                        "dststt $rA, $rB, $STRM", LdStGeneral /*FIXME*/, [=
]>;
+                        "dststt $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
=20
 def DST64    : DSS_Form<342, (outs),
                         (ins u5imm:$ZERO, u5imm:$STRM, G8RC:$rA, GPRC:$rB),
-                        "dst $rA, $rB, $STRM", LdStGeneral /*FIXME*/, []>;
+                        "dst $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
 def DSTT64   : DSS_Form<342, (outs),
                         (ins u5imm:$ONE, u5imm:$STRM, G8RC:$rA, GPRC:$rB),
-                        "dstt $rA, $rB, $STRM", LdStGeneral /*FIXME*/, []>;
+                        "dstt $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
 def DSTST64  : DSS_Form<374, (outs),
                         (ins u5imm:$ZERO, u5imm:$STRM, G8RC:$rA, GPRC:$rB),
-                        "dstst $rA, $rB, $STRM", LdStGeneral /*FIXME*/, []=
>;
+                        "dstst $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
 def DSTSTT64 : DSS_Form<374, (outs),
                         (ins u5imm:$ONE, u5imm:$STRM, G8RC:$rA, GPRC:$rB),
-                        "dststt $rA, $rB, $STRM", LdStGeneral /*FIXME*/, [=
]>;
+                        "dststt $rA, $rB, $STRM", LdStLoad /*FIXME*/, []>;
=20
 def MFVSCR : VXForm_4<1540, (outs VRRC:$vD), (ins),
-                      "mfvscr $vD", LdStGeneral,
+                      "mfvscr $vD", LdStStore,
                       [(set VRRC:$vD, (int_ppc_altivec_mfvscr))]>;=20
 def MTVSCR : VXForm_5<1604, (outs), (ins VRRC:$vB),
-                      "mtvscr $vB", LdStGeneral,
+                      "mtvscr $vB", LdStLoad,
                       [(int_ppc_altivec_mtvscr VRRC:$vB)]>;=20
=20
 let canFoldAsLoad =3D 1, PPC970_Unit =3D 2 in {  // Loads.
 def LVEBX: XForm_1<31,   7, (outs VRRC:$vD), (ins memrr:$src),
-                   "lvebx $vD, $src", LdStGeneral,
+                   "lvebx $vD, $src", LdStLoad,
                    [(set VRRC:$vD, (int_ppc_altivec_lvebx xoaddr:$src))]>;
 def LVEHX: XForm_1<31,  39, (outs VRRC:$vD), (ins memrr:$src),
-                   "lvehx $vD, $src", LdStGeneral,
+                   "lvehx $vD, $src", LdStLoad,
                    [(set VRRC:$vD, (int_ppc_altivec_lvehx xoaddr:$src))]>;
 def LVEWX: XForm_1<31,  71, (outs VRRC:$vD), (ins memrr:$src),
-                   "lvewx $vD, $src", LdStGeneral,
+                   "lvewx $vD, $src", LdStLoad,
                    [(set VRRC:$vD, (int_ppc_altivec_lvewx xoaddr:$src))]>;
 def LVX  : XForm_1<31, 103, (outs VRRC:$vD), (ins memrr:$src),
-                   "lvx $vD, $src", LdStGeneral,
+                   "lvx $vD, $src", LdStLoad,
                    [(set VRRC:$vD, (int_ppc_altivec_lvx xoaddr:$src))]>;
 def LVXL : XForm_1<31, 359, (outs VRRC:$vD), (ins memrr:$src),
-                   "lvxl $vD, $src", LdStGeneral,
+                   "lvxl $vD, $src", LdStLoad,
                    [(set VRRC:$vD, (int_ppc_altivec_lvxl xoaddr:$src))]>;
 }
=20
 def LVSL : XForm_1<31,   6, (outs VRRC:$vD), (ins memrr:$src),
-                   "lvsl $vD, $src", LdStGeneral,
+                   "lvsl $vD, $src", LdStLoad,
                    [(set VRRC:$vD, (int_ppc_altivec_lvsl xoaddr:$src))]>,
                    PPC970_Unit_LSU;
 def LVSR : XForm_1<31,  38, (outs VRRC:$vD), (ins memrr:$src),
-                   "lvsr $vD, $src", LdStGeneral,
+                   "lvsr $vD, $src", LdStLoad,
                    [(set VRRC:$vD, (int_ppc_altivec_lvsr xoaddr:$src))]>,
                    PPC970_Unit_LSU;
=20
 let PPC970_Unit =3D 2 in {   // Stores.
 def STVEBX: XForm_8<31, 135, (outs), (ins VRRC:$rS, memrr:$dst),
-                   "stvebx $rS, $dst", LdStGeneral,
+                   "stvebx $rS, $dst", LdStStore,
                    [(int_ppc_altivec_stvebx VRRC:$rS, xoaddr:$dst)]>;
 def STVEHX: XForm_8<31, 167, (outs), (ins VRRC:$rS, memrr:$dst),
-                   "stvehx $rS, $dst", LdStGeneral,
+                   "stvehx $rS, $dst", LdStStore,
                    [(int_ppc_altivec_stvehx VRRC:$rS, xoaddr:$dst)]>;
 def STVEWX: XForm_8<31, 199, (outs), (ins VRRC:$rS, memrr:$dst),
-                   "stvewx $rS, $dst", LdStGeneral,
+                   "stvewx $rS, $dst", LdStStore,
                    [(int_ppc_altivec_stvewx VRRC:$rS, xoaddr:$dst)]>;
 def STVX  : XForm_8<31, 231, (outs), (ins VRRC:$rS, memrr:$dst),
-                   "stvx $rS, $dst", LdStGeneral,
+                   "stvx $rS, $dst", LdStStore,
                    [(int_ppc_altivec_stvx VRRC:$rS, xoaddr:$dst)]>;
 def STVXL : XForm_8<31, 487, (outs), (ins VRRC:$rS, memrr:$dst),
-                   "stvxl $rS, $dst", LdStGeneral,
+                   "stvxl $rS, $dst", LdStStore,
                    [(int_ppc_altivec_stvxl VRRC:$rS, xoaddr:$dst)]>;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCInstrFormats.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCInstrFormats.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCInstrFormats.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
 //=3D=3D=3D- PowerPCInstrFormats.td - PowerPC Instruction Formats --*- tab=
legen -*-=3D//
-//=20
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -51,6 +51,36 @@
 class PPC970_Unit_VPERM    { bits<3> PPC970_Unit =3D 6;   }
 class PPC970_Unit_BRU      { bits<3> PPC970_Unit =3D 7;   }
=20
+// Two joined instructions; used to emit two adjacent instructions as one.
+// The itinerary from the first instruction is used for scheduling and
+// classification.
+class I2<bits<6> opcode1, bits<6> opcode2, dag OOL, dag IOL, string asmstr,
+         InstrItinClass itin>
+        : Instruction {
+  field bits<64> Inst;
+
+  bit PPC64 =3D 0;  // Default value, override with isPPC64
+
+  let Namespace =3D "PPC";
+  let Inst{0-5} =3D opcode1;
+  let Inst{32-37} =3D opcode2;
+  let OutOperandList =3D OOL;
+  let InOperandList =3D IOL;
+  let AsmString =3D asmstr;
+  let Itinerary =3D itin;
+
+  bits<1> PPC970_First =3D 0;
+  bits<1> PPC970_Single =3D 0;
+  bits<1> PPC970_Cracked =3D 0;
+  bits<3> PPC970_Unit =3D 0;
+
+  /// These fields correspond to the fields in PPCInstrInfo.h.  Any change=
s to
+  /// these must be reflected there!  See comments there for what these ar=
e.
+  let TSFlags{0}   =3D PPC970_First;
+  let TSFlags{1}   =3D PPC970_Single;
+  let TSFlags{2}   =3D PPC970_Cracked;
+  let TSFlags{5-3} =3D PPC970_Unit;
+}
=20
 // 1.7.1 I-Form
 class IForm<bits<6> opcode, bit aa, bit lk, dag OOL, dag IOL, string asmst=
r,
@@ -164,6 +194,35 @@
   let Addr =3D 0;
 }
=20
+class IForm_and_DForm_1<bits<6> opcode1, bit aa, bit lk, bits<6> opcode2,
+            dag OOL, dag IOL, string asmstr,
+            InstrItinClass itin, list<dag> pattern>
+         : I2<opcode1, opcode2, OOL, IOL, asmstr, itin> {
+  bits<5>  A;
+  bits<21> Addr;
+
+  let Pattern =3D pattern;
+  bits<24> LI;
+
+  let Inst{6-29}  =3D LI;
+  let Inst{30}    =3D aa;
+  let Inst{31}    =3D lk;
+
+  let Inst{38-42}  =3D A;
+  let Inst{43-47} =3D Addr{20-16}; // Base Reg
+  let Inst{48-63} =3D Addr{15-0};  // Displacement
+}
+
+// This is used to emit BL8+NOP.
+class IForm_and_DForm_4_zero<bits<6> opcode1, bit aa, bit lk, bits<6> opco=
de2,
+            dag OOL, dag IOL, string asmstr,
+            InstrItinClass itin, list<dag> pattern>
+         :  IForm_and_DForm_1<opcode1, aa, lk, opcode2,
+                              OOL, IOL, asmstr, itin, pattern> {
+  let A =3D 0;
+  let Addr =3D 0;
+}
+
 class DForm_5<bits<6> opcode, dag OOL, dag IOL, string asmstr,
               InstrItinClass itin>
   : I<opcode, OOL, IOL, asmstr, itin> {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCInstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PPCInstrInfo.cpp - PowerPC32 Instruction Information -----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCInstrInfo.cpp - PowerPC Instruction Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -34,8 +34,8 @@
 #include "PPCGenInstrInfo.inc"
=20
 namespace llvm {
-extern cl::opt<bool> EnablePPC32RS;  // FIXME (64-bit): See PPCRegisterInf=
o.cpp.
-extern cl::opt<bool> EnablePPC64RS;  // FIXME (64-bit): See PPCRegisterInf=
o.cpp.
+extern cl::opt<bool> DisablePPC32RS;
+extern cl::opt<bool> DisablePPC64RS;
 }
=20
 using namespace llvm;
@@ -49,13 +49,32 @@
 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
   const TargetMachine *TM,
   const ScheduleDAG *DAG) const {
-  // Should use subtarget info to pick the right hazard recognizer.  For
-  // now, always return a PPC970 recognizer.
-  const TargetInstrInfo *TII =3D TM->getInstrInfo();
-  assert(TII && "No InstrInfo?");
-  return new PPCHazardRecognizer970(*TII);
+  unsigned Directive =3D TM->getSubtarget<PPCSubtarget>().getDarwinDirecti=
ve();
+  if (Directive =3D=3D PPC::DIR_440 || Directive =3D=3D PPC::DIR_A2) {
+    const InstrItineraryData *II =3D TM->getInstrItineraryData();
+    return new PPCScoreboardHazardRecognizer(II, DAG);
+  }
+
+  return TargetInstrInfoImpl::CreateTargetHazardRecognizer(TM, DAG);
 }
=20
+/// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recogniz=
er
+/// to use for this target when scheduling the DAG.
+ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
+  const InstrItineraryData *II,
+  const ScheduleDAG *DAG) const {
+  unsigned Directive =3D TM.getSubtarget<PPCSubtarget>().getDarwinDirectiv=
e();
+
+  // Most subtargets use a PPC970 recognizer.
+  if (Directive !=3D PPC::DIR_440 && Directive !=3D PPC::DIR_A2) {
+    const TargetInstrInfo *TII =3D TM.getInstrInfo();
+    assert(TII && "No InstrInfo?");
+
+    return new PPCHazardRecognizer970(*TII);
+  }
+
+  return new PPCScoreboardHazardRecognizer(II, DAG);
+}
 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
                                            int &FrameIndex) const {
   switch (MI->getOpcode()) {
@@ -327,6 +346,7 @@
     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(Kill=
Src));
 }
=20
+// This function returns true if a CR spill is necessary and false otherwi=
se.
 bool
 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
                                   unsigned SrcReg, bool isKill,
@@ -358,7 +378,7 @@
                                          FrameIdx));
     } else {
       // FIXME: this spills LR immediately to memory in one step.  To do t=
his,
-      // we use R11, which we know cannot be used in the prolog/epilog.  T=
his is
+      // we use X11, which we know cannot be used in the prolog/epilog.  T=
his is
       // a hack.
       NewMIs.push_back(BuildMI(MF, DL, get(PPC::MFLR8), PPC::X11));
       NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
@@ -377,9 +397,8 @@
                                                getKillRegState(isKill)),
                                        FrameIdx));
   } else if (PPC::CRRCRegisterClass->hasSubClassEq(RC)) {
-    if ((EnablePPC32RS && !TM.getSubtargetImpl()->isPPC64()) ||
-        (EnablePPC64RS && TM.getSubtargetImpl()->isPPC64())) {
-      // FIXME (64-bit): Enable
+    if ((!DisablePPC32RS && !TM.getSubtargetImpl()->isPPC64()) ||
+        (!DisablePPC64RS && TM.getSubtargetImpl()->isPPC64())) {
       NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR=
))
                                          .addReg(SrcReg,
                                                  getKillRegState(isKill)),
@@ -392,11 +411,14 @@
       // We hack this on Darwin by reserving R2.  It's probably broken on =
Linux
       // at the moment.
=20
+      bool is64Bit =3D TM.getSubtargetImpl()->isPPC64();
       // We need to store the CR in the low 4-bits of the saved value.  Fi=
rst,
       // issue a MFCR to save all of the CRBits.
       unsigned ScratchReg =3D TM.getSubtargetImpl()->isDarwinABI() ?
-                                                           PPC::R2 : PPC::=
R0;
-      NewMIs.push_back(BuildMI(MF, DL, get(PPC::MFCRpseud), ScratchReg)
+                              (is64Bit ? PPC::X2 : PPC::R2) :
+                              (is64Bit ? PPC::X0 : PPC::R0);
+      NewMIs.push_back(BuildMI(MF, DL, get(is64Bit ? PPC::MFCR8pseud :
+                                             PPC::MFCRpseud), ScratchReg)
                                .addReg(SrcReg, getKillRegState(isKill)));
=20
       // If the saved register wasn't CR0, shift the bits left so that the=
y are
@@ -404,12 +426,14 @@
       if (SrcReg !=3D PPC::CR0) {
         unsigned ShiftBits =3D getPPCRegisterNumbering(SrcReg)*4;
         // rlwinm scratch, scratch, ShiftBits, 0, 31.
-        NewMIs.push_back(BuildMI(MF, DL, get(PPC::RLWINM), ScratchReg)
+        NewMIs.push_back(BuildMI(MF, DL, get(is64Bit ? PPC::RLWINM8 :
+                           PPC::RLWINM), ScratchReg)
                        .addReg(ScratchReg).addImm(ShiftBits)
                        .addImm(0).addImm(31));
       }
=20
-      NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
+      NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(is64Bit ?
+                                           PPC::STW8 : PPC::STW))
                                          .addReg(ScratchReg,
                                                  getKillRegState(isKill)),
                                          FrameIdx));
@@ -486,15 +510,14 @@
=20
   const MachineFrameInfo &MFI =3D *MF.getFrameInfo();
   MachineMemOperand *MMO =3D
-    MF.getMachineMemOperand(
-                MachinePointerInfo(PseudoSourceValue::getFixedStack(FrameI=
dx)),
+    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
                             MachineMemOperand::MOStore,
                             MFI.getObjectSize(FrameIdx),
                             MFI.getObjectAlignment(FrameIdx));
   NewMIs.back()->addMemOperand(MF, MMO);
 }
=20
-void
+bool
 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
                                    unsigned DestReg, int FrameIdx,
                                    const TargetRegisterClass *RC,
@@ -514,8 +537,8 @@
                                          FrameIdx));
     } else {
       NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD),
-                                                 PPC::R11), FrameIdx));
-      NewMIs.push_back(BuildMI(MF, DL, get(PPC::MTLR8)).addReg(PPC::R11));
+                                                 PPC::X11), FrameIdx));
+      NewMIs.push_back(BuildMI(MF, DL, get(PPC::MTLR8)).addReg(PPC::X11));
     }
   } else if (PPC::F8RCRegisterClass->hasSubClassEq(RC)) {
     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), Dest=
Reg),
@@ -524,28 +547,37 @@
     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), Dest=
Reg),
                                        FrameIdx));
   } else if (PPC::CRRCRegisterClass->hasSubClassEq(RC)) {
-    // FIXME: We need a scatch reg here.  The trouble with using R0 is that
-    // it's possible for the stack frame to be so big the save location is
-    // out of range of immediate offsets, necessitating another register.
-    // We hack this on Darwin by reserving R2.  It's probably broken on Li=
nux
-    // at the moment.
-    unsigned ScratchReg =3D TM.getSubtargetImpl()->isDarwinABI() ?
-                                                          PPC::R2 : PPC::R=
0;
-    NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
-                                       ScratchReg), FrameIdx));
-
-    // If the reloaded register isn't CR0, shift the bits right so that th=
ey are
-    // in the right CR's slot.
-    if (DestReg !=3D PPC::CR0) {
-      unsigned ShiftBits =3D getPPCRegisterNumbering(DestReg)*4;
-      // rlwinm r11, r11, 32-ShiftBits, 0, 31.
-      NewMIs.push_back(BuildMI(MF, DL, get(PPC::RLWINM), ScratchReg)
-                    .addReg(ScratchReg).addImm(32-ShiftBits).addImm(0)
-                    .addImm(31));
+    if ((!DisablePPC32RS && !TM.getSubtargetImpl()->isPPC64()) ||
+        (!DisablePPC64RS && TM.getSubtargetImpl()->isPPC64())) {
+      NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
+                                                 get(PPC::RESTORE_CR), Des=
tReg)
+                                         , FrameIdx));
+      return true;
+    } else {
+      // FIXME: We need a scatch reg here.  The trouble with using R0 is t=
hat
+      // it's possible for the stack frame to be so big the save location =
is
+      // out of range of immediate offsets, necessitating another register.
+      // We hack this on Darwin by reserving R2.  It's probably broken on =
Linux
+      // at the moment.
+      unsigned ScratchReg =3D TM.getSubtargetImpl()->isDarwinABI() ?
+                                                            PPC::R2 : PPC:=
:R0;
+      NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
+                                         ScratchReg), FrameIdx));
+ =20
+      // If the reloaded register isn't CR0, shift the bits right so that =
they are
+      // in the right CR's slot.
+      if (DestReg !=3D PPC::CR0) {
+        unsigned ShiftBits =3D getPPCRegisterNumbering(DestReg)*4;
+        // rlwinm r11, r11, 32-ShiftBits, 0, 31.
+        NewMIs.push_back(BuildMI(MF, DL, get(PPC::RLWINM), ScratchReg)
+                      .addReg(ScratchReg).addImm(32-ShiftBits).addImm(0)
+                      .addImm(31));
+      }
+ =20
+      NewMIs.push_back(BuildMI(MF, DL, get(TM.getSubtargetImpl()->isPPC64(=
) ?
+                         PPC::MTCRF8 : PPC::MTCRF), DestReg)
+                       .addReg(ScratchReg));
     }
-
-    NewMIs.push_back(BuildMI(MF, DL, get(PPC::MTCRF), DestReg)
-                     .addReg(ScratchReg));
   } else if (PPC::CRBITRCRegisterClass->hasSubClassEq(RC)) {
=20
     unsigned Reg =3D 0;
@@ -590,6 +622,8 @@
   } else {
     llvm_unreachable("Unknown regclass!");
   }
+
+  return false;
 }
=20
 void
@@ -602,14 +636,16 @@
   SmallVector<MachineInstr*, 4> NewMIs;
   DebugLoc DL;
   if (MI !=3D MBB.end()) DL =3D MI->getDebugLoc();
-  LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs);
+  if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs)) {
+    PPCFunctionInfo *FuncInfo =3D MF.getInfo<PPCFunctionInfo>();
+    FuncInfo->setSpillsCR();
+  }
   for (unsigned i =3D 0, e =3D NewMIs.size(); i !=3D e; ++i)
     MBB.insert(MI, NewMIs[i]);
=20
   const MachineFrameInfo &MFI =3D *MF.getFrameInfo();
   MachineMemOperand *MMO =3D
-    MF.getMachineMemOperand(
-                MachinePointerInfo(PseudoSourceValue::getFixedStack(FrameI=
dx)),
+    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
                             MachineMemOperand::MOLoad,
                             MFI.getObjectSize(FrameIdx),
                             MFI.getObjectAlignment(FrameIdx));
@@ -649,6 +685,9 @@
   case PPC::GC_LABEL:
   case PPC::DBG_VALUE:
     return 0;
+  case PPC::BL8_NOP_ELF:
+  case PPC::BLA8_NOP_ELF:
+    return 8;
   default:
     return 4; // PowerPC instructions are all 4 bytes
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCInstrInfo.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PPCInstrInfo.h - PowerPC Instruction Information ---------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCInstrInfo.h - PowerPC Instruction Information --------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,12 +11,12 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#ifndef POWERPC32_INSTRUCTIONINFO_H
-#define POWERPC32_INSTRUCTIONINFO_H
+#ifndef POWERPC_INSTRUCTIONINFO_H
+#define POWERPC_INSTRUCTIONINFO_H
=20
 #include "PPC.h"
+#include "PPCRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "PPCRegisterInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "PPCGenInstrInfo.inc"
@@ -72,7 +72,7 @@
                            unsigned SrcReg, bool isKill, int FrameIdx,
                            const TargetRegisterClass *RC,
                            SmallVectorImpl<MachineInstr*> &NewMIs) const;
-  void LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
+  bool LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
                             unsigned DestReg, int FrameIdx,
                             const TargetRegisterClass *RC,
                             SmallVectorImpl<MachineInstr*> &NewMIs) const;
@@ -88,6 +88,9 @@
   ScheduleHazardRecognizer *
   CreateTargetHazardRecognizer(const TargetMachine *TM,
                                const ScheduleDAG *DAG) const;
+  ScheduleHazardRecognizer *
+  CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
+                                     const ScheduleDAG *DAG) const;
=20
   unsigned isLoadFromStackSlot(const MachineInstr *MI,
                                int &FrameIndex) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCInstrInfo.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCInstrInfo.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCInstrInfo.td - The PowerPC Instruction Set -------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCInstrInfo.td - The PowerPC Instruction Set ------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the subset of the 32-bit PowerPC instruction set, a=
s used
@@ -116,6 +116,9 @@
 def PPCcall_SVR4  : SDNode<"PPCISD::CALL_SVR4", SDT_PPCCall,
                            [SDNPHasChain, SDNPOptInGlue, SDNPOutGlue,
                             SDNPVariadic]>;
+def PPCcall_nop_SVR4  : SDNode<"PPCISD::CALL_NOP_SVR4", SDT_PPCCall,
+                               [SDNPHasChain, SDNPOptInGlue, SDNPOutGlue,
+                                SDNPVariadic]>;
 def PPCnop : SDNode<"PPCISD::NOP", SDT_PPCnop, [SDNPInGlue, SDNPOutGlue]>;
 def PPCload   : SDNode<"PPCISD::LOAD", SDTypeProfile<1, 1, []>,
                        [SDNPHasChain, SDNPOptInGlue, SDNPOutGlue]>;
@@ -349,10 +352,10 @@
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PowerPC Instruction Predicate Definitions.
-def FPContractions : Predicate<"!NoExcessFPPrecision">;
+def FPContractions : Predicate<"!TM.Options.NoExcessFPPrecision">;
 def In32BitMode  : Predicate<"!PPCSubTarget.isPPC64()">;
 def In64BitMode  : Predicate<"PPCSubTarget.isPPC64()">;
-
+def IsBookE  : Predicate<"PPCSubTarget.isBookE()">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PowerPC Instruction Definitions.
@@ -399,7 +402,14 @@
=20
 // SPILL_CR - Indicate that we're dumping the CR register, so we'll need to
 // scavenge a register for it.
-def SPILL_CR : Pseudo<(outs), (ins GPRC:$cond, memri:$F),
+let mayStore =3D 1 in
+def SPILL_CR : Pseudo<(outs), (ins CRRC:$cond, memri:$F),
+                     "", []>;
+
+// RESTORE_CR - Indicate that we're restoring the CR register (previously
+// spilled), so we'll need to scavenge a register for it.
+let mayLoad =3D 1 in
+def RESTORE_CR : Pseudo<(outs CRRC:$cond), (ins memri:$F),
                      "", []>;
=20
 let isTerminator =3D 1, isBarrier =3D 1, PPC970_Unit =3D 7 in {
@@ -431,13 +441,7 @@
 }
=20
 // Darwin ABI Calls.
-let isCall =3D 1, PPC970_Unit =3D 7,=20
-  // All calls clobber the non-callee saved registers...
-  Defs =3D [R0,R2,R3,R4,R5,R6,R7,R8,R9,R10,R11,R12,
-          F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,F13,
-          V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,V13,V14,V15,V16,V17,V1=
8,V19,
-          LR,CTR,
-          CR0,CR1,CR5,CR6,CR7,CARRY] in {
+let isCall =3D 1, PPC970_Unit =3D 7, Defs =3D [LR] in {
   // Convenient aliases for call instructions
   let Uses =3D [RM] in {
     def BL_Darwin  : IForm<18, 0, 1,
@@ -456,13 +460,7 @@
 }
=20
 // SVR4 ABI Calls.
-let isCall =3D 1, PPC970_Unit =3D 7,=20
-  // All calls clobber the non-callee saved registers...
-  Defs =3D [R0,R3,R4,R5,R6,R7,R8,R9,R10,R11,R12,
-          F0,F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12,F13,
-          V0,V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,V13,V14,V15,V16,V17,V1=
8,V19,
-          LR,CTR,
-          CR0,CR1,CR5,CR6,CR7,CARRY] in {
+let isCall =3D 1, PPC970_Unit =3D 7, Defs =3D [LR] in {
   // Convenient aliases for call instructions
   let Uses =3D [RM] in {
     def BL_SVR4  : IForm<18, 0, 1,
@@ -547,6 +545,9 @@
                       "dcbzl $dst", LdStDCBF, [(int_ppc_dcbzl xoaddr:$dst)=
]>,
                       PPC970_DGroup_Single;
=20
+def : Pat<(prefetch xoaddr:$dst, (i32 0), imm, (i32 1)),
+          (DCBT xoaddr:$dst)>;
+
 // Atomic operations
 let usesCustomInserter =3D 1 in {
   let Defs =3D [CR0] in {
@@ -642,7 +643,7 @@
                    isDOT;
=20
 let isTerminator =3D 1, isBarrier =3D 1, hasCtrlDep =3D 1 in
-def TRAP  : XForm_24<31, 4, (outs), (ins), "trap", LdStGeneral, [(trap)]>;
+def TRAP  : XForm_24<31, 4, (outs), (ins), "trap", LdStLoad, [(trap)]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PPC32 Load Instructions.
@@ -651,17 +652,17 @@
 // Unindexed (r+i) Loads.=20
 let canFoldAsLoad =3D 1, PPC970_Unit =3D 2 in {
 def LBZ : DForm_1<34, (outs GPRC:$rD), (ins memri:$src),
-                  "lbz $rD, $src", LdStGeneral,
+                  "lbz $rD, $src", LdStLoad,
                   [(set GPRC:$rD, (zextloadi8 iaddr:$src))]>;
 def LHA : DForm_1<42, (outs GPRC:$rD), (ins memri:$src),
                   "lha $rD, $src", LdStLHA,
                   [(set GPRC:$rD, (sextloadi16 iaddr:$src))]>,
                   PPC970_DGroup_Cracked;
 def LHZ : DForm_1<40, (outs GPRC:$rD), (ins memri:$src),
-                  "lhz $rD, $src", LdStGeneral,
+                  "lhz $rD, $src", LdStLoad,
                   [(set GPRC:$rD, (zextloadi16 iaddr:$src))]>;
 def LWZ : DForm_1<32, (outs GPRC:$rD), (ins memri:$src),
-                  "lwz $rD, $src", LdStGeneral,
+                  "lwz $rD, $src", LdStLoad,
                   [(set GPRC:$rD, (load iaddr:$src))]>;
=20
 def LFS : DForm_1<48, (outs F4RC:$rD), (ins memri:$src),
@@ -675,22 +676,22 @@
 // Unindexed (r+i) Loads with Update (preinc).
 let mayLoad =3D 1 in {
 def LBZU : DForm_1<35, (outs GPRC:$rD, ptr_rc:$ea_result), (ins memri:$add=
r),
-                   "lbzu $rD, $addr", LdStGeneral,
+                   "lbzu $rD, $addr", LdStLoad,
                    []>, RegConstraint<"$addr.reg =3D $ea_result">,
                    NoEncode<"$ea_result">;
=20
 def LHAU : DForm_1<43, (outs GPRC:$rD, ptr_rc:$ea_result), (ins memri:$add=
r),
-                   "lhau $rD, $addr", LdStGeneral,
+                   "lhau $rD, $addr", LdStLoad,
                    []>, RegConstraint<"$addr.reg =3D $ea_result">,
                    NoEncode<"$ea_result">;
=20
 def LHZU : DForm_1<41, (outs GPRC:$rD, ptr_rc:$ea_result), (ins memri:$add=
r),
-                   "lhzu $rD, $addr", LdStGeneral,
+                   "lhzu $rD, $addr", LdStLoad,
                    []>, RegConstraint<"$addr.reg =3D $ea_result">,
                    NoEncode<"$ea_result">;
=20
 def LWZU : DForm_1<33, (outs GPRC:$rD, ptr_rc:$ea_result), (ins memri:$add=
r),
-                   "lwzu $rD, $addr", LdStGeneral,
+                   "lwzu $rD, $addr", LdStLoad,
                    []>, RegConstraint<"$addr.reg =3D $ea_result">,
                    NoEncode<"$ea_result">;
=20
@@ -710,25 +711,25 @@
 //
 let canFoldAsLoad =3D 1, PPC970_Unit =3D 2 in {
 def LBZX : XForm_1<31,  87, (outs GPRC:$rD), (ins memrr:$src),
-                   "lbzx $rD, $src", LdStGeneral,
+                   "lbzx $rD, $src", LdStLoad,
                    [(set GPRC:$rD, (zextloadi8 xaddr:$src))]>;
 def LHAX : XForm_1<31, 343, (outs GPRC:$rD), (ins memrr:$src),
                    "lhax $rD, $src", LdStLHA,
                    [(set GPRC:$rD, (sextloadi16 xaddr:$src))]>,
                    PPC970_DGroup_Cracked;
 def LHZX : XForm_1<31, 279, (outs GPRC:$rD), (ins memrr:$src),
-                   "lhzx $rD, $src", LdStGeneral,
+                   "lhzx $rD, $src", LdStLoad,
                    [(set GPRC:$rD, (zextloadi16 xaddr:$src))]>;
 def LWZX : XForm_1<31,  23, (outs GPRC:$rD), (ins memrr:$src),
-                   "lwzx $rD, $src", LdStGeneral,
+                   "lwzx $rD, $src", LdStLoad,
                    [(set GPRC:$rD, (load xaddr:$src))]>;
                   =20
                   =20
 def LHBRX : XForm_1<31, 790, (outs GPRC:$rD), (ins memrr:$src),
-                   "lhbrx $rD, $src", LdStGeneral,
+                   "lhbrx $rD, $src", LdStLoad,
                    [(set GPRC:$rD, (PPClbrx xoaddr:$src, i16))]>;
 def LWBRX : XForm_1<31,  534, (outs GPRC:$rD), (ins memrr:$src),
-                   "lwbrx $rD, $src", LdStGeneral,
+                   "lwbrx $rD, $src", LdStLoad,
                    [(set GPRC:$rD, (PPClbrx xoaddr:$src, i32))]>;
=20
 def LFSX   : XForm_25<31, 535, (outs F4RC:$frD), (ins memrr:$src),
@@ -746,13 +747,13 @@
 // Unindexed (r+i) Stores.
 let PPC970_Unit =3D 2 in {
 def STB  : DForm_1<38, (outs), (ins GPRC:$rS, memri:$src),
-                   "stb $rS, $src", LdStGeneral,
+                   "stb $rS, $src", LdStStore,
                    [(truncstorei8 GPRC:$rS, iaddr:$src)]>;
 def STH  : DForm_1<44, (outs), (ins GPRC:$rS, memri:$src),
-                   "sth $rS, $src", LdStGeneral,
+                   "sth $rS, $src", LdStStore,
                    [(truncstorei16 GPRC:$rS, iaddr:$src)]>;
 def STW  : DForm_1<36, (outs), (ins GPRC:$rS, memri:$src),
-                   "stw $rS, $src", LdStGeneral,
+                   "stw $rS, $src", LdStStore,
                    [(store GPRC:$rS, iaddr:$src)]>;
 def STFS : DForm_1<52, (outs), (ins F4RC:$rS, memri:$dst),
                    "stfs $rS, $dst", LdStUX,
@@ -766,33 +767,33 @@
 let PPC970_Unit =3D 2 in {
 def STBU  : DForm_1a<39, (outs ptr_rc:$ea_res), (ins GPRC:$rS,
                              symbolLo:$ptroff, ptr_rc:$ptrreg),
-                    "stbu $rS, $ptroff($ptrreg)", LdStGeneral,
+                    "stbu $rS, $ptroff($ptrreg)", LdStStore,
                     [(set ptr_rc:$ea_res,
                           (pre_truncsti8 GPRC:$rS, ptr_rc:$ptrreg,=20
                                          iaddroff:$ptroff))]>,
                     RegConstraint<"$ptrreg =3D $ea_res">, NoEncode<"$ea_re=
s">;
 def STHU  : DForm_1a<45, (outs ptr_rc:$ea_res), (ins GPRC:$rS,
                              symbolLo:$ptroff, ptr_rc:$ptrreg),
-                    "sthu $rS, $ptroff($ptrreg)", LdStGeneral,
+                    "sthu $rS, $ptroff($ptrreg)", LdStStore,
                     [(set ptr_rc:$ea_res,
                         (pre_truncsti16 GPRC:$rS, ptr_rc:$ptrreg,=20
                                         iaddroff:$ptroff))]>,
                     RegConstraint<"$ptrreg =3D $ea_res">, NoEncode<"$ea_re=
s">;
 def STWU  : DForm_1a<37, (outs ptr_rc:$ea_res), (ins GPRC:$rS,
                              symbolLo:$ptroff, ptr_rc:$ptrreg),
-                    "stwu $rS, $ptroff($ptrreg)", LdStGeneral,
+                    "stwu $rS, $ptroff($ptrreg)", LdStStore,
                     [(set ptr_rc:$ea_res, (pre_store GPRC:$rS, ptr_rc:$ptr=
reg,=20
                                                      iaddroff:$ptroff))]>,
                     RegConstraint<"$ptrreg =3D $ea_res">, NoEncode<"$ea_re=
s">;
 def STFSU : DForm_1a<37, (outs ptr_rc:$ea_res), (ins F4RC:$rS,
                              symbolLo:$ptroff, ptr_rc:$ptrreg),
-                    "stfsu $rS, $ptroff($ptrreg)", LdStGeneral,
+                    "stfsu $rS, $ptroff($ptrreg)", LdStStore,
                     [(set ptr_rc:$ea_res, (pre_store F4RC:$rS,  ptr_rc:$pt=
rreg,=20
                                           iaddroff:$ptroff))]>,
                     RegConstraint<"$ptrreg =3D $ea_res">, NoEncode<"$ea_re=
s">;
 def STFDU : DForm_1a<37, (outs ptr_rc:$ea_res), (ins F8RC:$rS,
                              symbolLo:$ptroff, ptr_rc:$ptrreg),
-                    "stfdu $rS, $ptroff($ptrreg)", LdStGeneral,
+                    "stfdu $rS, $ptroff($ptrreg)", LdStStore,
                     [(set ptr_rc:$ea_res, (pre_store F8RC:$rS, ptr_rc:$ptr=
reg,=20
                                           iaddroff:$ptroff))]>,
                     RegConstraint<"$ptrreg =3D $ea_res">, NoEncode<"$ea_re=
s">;
@@ -803,29 +804,29 @@
 //
 let PPC970_Unit =3D 2 in {
 def STBX  : XForm_8<31, 215, (outs), (ins GPRC:$rS, memrr:$dst),
-                   "stbx $rS, $dst", LdStGeneral,
+                   "stbx $rS, $dst", LdStStore,
                    [(truncstorei8 GPRC:$rS, xaddr:$dst)]>,=20
                    PPC970_DGroup_Cracked;
 def STHX  : XForm_8<31, 407, (outs), (ins GPRC:$rS, memrr:$dst),
-                   "sthx $rS, $dst", LdStGeneral,
+                   "sthx $rS, $dst", LdStStore,
                    [(truncstorei16 GPRC:$rS, xaddr:$dst)]>,=20
                    PPC970_DGroup_Cracked;
 def STWX  : XForm_8<31, 151, (outs), (ins GPRC:$rS, memrr:$dst),
-                   "stwx $rS, $dst", LdStGeneral,
+                   "stwx $rS, $dst", LdStStore,
                    [(store GPRC:$rS, xaddr:$dst)]>,
                    PPC970_DGroup_Cracked;
                   =20
 let mayStore =3D 1 in {
 def STWUX : XForm_8<31, 183, (outs), (ins GPRC:$rS, GPRC:$rA, GPRC:$rB),
-                   "stwux $rS, $rA, $rB", LdStGeneral,
+                   "stwux $rS, $rA, $rB", LdStStore,
                    []>;
 }
 def STHBRX: XForm_8<31, 918, (outs), (ins GPRC:$rS, memrr:$dst),
-                   "sthbrx $rS, $dst", LdStGeneral,
+                   "sthbrx $rS, $dst", LdStStore,
                    [(PPCstbrx GPRC:$rS, xoaddr:$dst, i16)]>,=20
                    PPC970_DGroup_Cracked;
 def STWBRX: XForm_8<31, 662, (outs), (ins GPRC:$rS, memrr:$dst),
-                   "stwbrx $rS, $dst", LdStGeneral,
+                   "stwbrx $rS, $dst", LdStStore,
                    [(PPCstbrx GPRC:$rS, xoaddr:$dst, i32)]>,
                    PPC970_DGroup_Cracked;
=20
@@ -1091,7 +1092,7 @@
                              "mfspr $rT, 256", IntGeneral>,
                PPC970_DGroup_First, PPC970_Unit_FXU;
=20
-def MTCRF : XFXForm_5<31, 144, (outs), (ins crbitm:$FXM, GPRC:$rS),
+def MTCRF : XFXForm_5<31, 144, (outs crbitm:$FXM), (ins GPRC:$rS),
                       "mtcrf $FXM, $rS", BrMCRX>,
             PPC970_MicroCode, PPC970_Unit_CRU;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCJITInfo.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCJITInfo.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCJITInfo.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -291,9 +291,10 @@
 }
 #endif
=20
-extern "C" void *PPCCompilationCallbackC(unsigned *StubCallAddrPlus4,
-                                         unsigned *OrigCallAddrPlus4,
-                                         bool is64Bit) {
+extern "C" {
+static void* LLVM_ATTRIBUTE_USED PPCCompilationCallbackC(unsigned *StubCal=
lAddrPlus4,
+                                                         unsigned *OrigCal=
lAddrPlus4,
+                                                         bool is64Bit) {
   // Adjust the pointer to the address of the call instruction in the stub
   // emitted by emitFunctionStub, rather than the instruction after it.
   unsigned *StubCallAddr =3D StubCallAddrPlus4 - 1;
@@ -337,6 +338,7 @@
   // stack after we restore all regs.
   return Target;
 }
+}
=20
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCJITInfo.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCJITInfo.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCJITInfo.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PPCJITInfo.h - PowerPC impl. of the JIT interface --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCJITInfo.h - PowerPC impl. of the JIT interface -------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCMCInstLower.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCMCInstLower.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCMCInstLower.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -140,7 +140,7 @@
     switch (MO.getType()) {
     default:
       MI->dump();
-      assert(0 && "unknown operand type");
+      llvm_unreachable("unknown operand type");
     case MachineOperand::MO_Register:
       assert(!MO.getSubReg() && "Subregs should be eliminated!");
       MCOp =3D MCOperand::CreateReg(MO.getReg());
@@ -166,6 +166,8 @@
       MCOp =3D GetSymbolRef(MO,AP.GetBlockAddressSymbol(MO.getBlockAddress=
()),AP,
                           isDarwin);
       break;
+    case MachineOperand::MO_RegisterMask:
+      continue;
     }
    =20
     OutMI.addOperand(MCOp);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCMachineFunctionInfo.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCMachineFunctionInfo.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCMachineFunctionInfo.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -21,7 +21,8 @@
 /// PPCFunctionInfo - This class is derived from MachineFunction private
 /// PowerPC target-specific information for each MachineFunction.
 class PPCFunctionInfo : public MachineFunctionInfo {
-private:
+  virtual void anchor();
+
   /// FramePointerSaveIndex - Frame index of where the old frame pointer is
   /// stored.  Also used as an anchor for instructions that need to be alt=
ered
   /// when using frame pointers (dyna_add, dyna_sub.)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCPerfectShuffle.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCPerfectShuffle.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCPerfectShuffle.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCPerfectShuffle.h - Altivec Perfect Shuffle Table --------=
-------=3D=3D=3D//
+//=3D=3D=3D-- PPCPerfectShuffle.h - Altivec Perfect Shuffle Table -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCRegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PPCRegisterInfo.cpp - PowerPC Register Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCRegisterInfo.cpp - PowerPC Register Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,10 +13,10 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "reginfo"
+#include "PPCRegisterInfo.h"
 #include "PPC.h"
 #include "PPCInstrBuilder.h"
 #include "PPCMachineFunctionInfo.h"
-#include "PPCRegisterInfo.h"
 #include "PPCFrameLowering.h"
 #include "PPCSubtarget.h"
 #include "llvm/CallingConv.h"
@@ -46,15 +46,14 @@
 #define GET_REGINFO_TARGET_DESC
 #include "PPCGenRegisterInfo.inc"
=20
-// FIXME (64-bit): Eventually enable by default.
 namespace llvm {
-cl::opt<bool> EnablePPC32RS("enable-ppc32-regscavenger",
+cl::opt<bool> DisablePPC32RS("disable-ppc32-regscavenger",
                                    cl::init(false),
-                                   cl::desc("Enable PPC32 register scaveng=
er"),
+                                   cl::desc("Disable PPC32 register scaven=
ger"),
                                    cl::Hidden);
-cl::opt<bool> EnablePPC64RS("enable-ppc64-regscavenger",
+cl::opt<bool> DisablePPC64RS("disable-ppc64-regscavenger",
                                    cl::init(false),
-                                   cl::desc("Enable PPC64 register scaveng=
er"),
+                                   cl::desc("Disable PPC64 register scaven=
ger"),
                                    cl::Hidden);
 }
=20
@@ -63,8 +62,8 @@
 // FIXME (64-bit): Should be inlined.
 bool
 PPCRegisterInfo::requiresRegisterScavenging(const MachineFunction &) const=
 {
-  return ((EnablePPC32RS && !Subtarget.isPPC64()) ||
-          (EnablePPC64RS && Subtarget.isPPC64()));
+  return ((!DisablePPC32RS && !Subtarget.isPPC64()) ||
+          (!DisablePPC64RS && Subtarget.isPPC64()));
 }
=20
 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
@@ -99,122 +98,22 @@
   return &PPC::GPRCRegClass;
 }
=20
+const uint16_t*
+PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
+  if (Subtarget.isDarwinABI())
+    return Subtarget.isPPC64() ? CSR_Darwin64_SaveList :
+                                 CSR_Darwin32_SaveList;
+
+  return Subtarget.isPPC64() ? CSR_SVR464_SaveList : CSR_SVR432_SaveList;
+}
+
 const unsigned*
-PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
-  // 32-bit Darwin calling convention.=20
-  static const unsigned Darwin32_CalleeSavedRegs[] =3D {
-              PPC::R13, PPC::R14, PPC::R15,
-    PPC::R16, PPC::R17, PPC::R18, PPC::R19,
-    PPC::R20, PPC::R21, PPC::R22, PPC::R23,
-    PPC::R24, PPC::R25, PPC::R26, PPC::R27,
-    PPC::R28, PPC::R29, PPC::R30, PPC::R31,
+PPCRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
+  if (Subtarget.isDarwinABI())
+    return Subtarget.isPPC64() ? CSR_Darwin64_RegMask :
+                                 CSR_Darwin32_RegMask;
=20
-    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
-    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
-    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
-    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
-    PPC::F30, PPC::F31,
-   =20
-    PPC::CR2, PPC::CR3, PPC::CR4,
-    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
-    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
-    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
-   =20
-    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
-    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
-    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
-   =20
-    PPC::LR,  0
-  };
-
-  // 32-bit SVR4 calling convention.
-  static const unsigned SVR4_CalleeSavedRegs[] =3D {
-                        PPC::R14, PPC::R15,
-    PPC::R16, PPC::R17, PPC::R18, PPC::R19,
-    PPC::R20, PPC::R21, PPC::R22, PPC::R23,
-    PPC::R24, PPC::R25, PPC::R26, PPC::R27,
-    PPC::R28, PPC::R29, PPC::R30, PPC::R31,
-
-    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
-    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
-    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
-    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
-    PPC::F30, PPC::F31,
-   =20
-    PPC::CR2, PPC::CR3, PPC::CR4,
-   =20
-    PPC::VRSAVE,
-   =20
-    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
-    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
-    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
-   =20
-    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
-    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
-    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
-   =20
-    0
-  };
-  // 64-bit Darwin calling convention.=20
-  static const unsigned Darwin64_CalleeSavedRegs[] =3D {
-    PPC::X14, PPC::X15,
-    PPC::X16, PPC::X17, PPC::X18, PPC::X19,
-    PPC::X20, PPC::X21, PPC::X22, PPC::X23,
-    PPC::X24, PPC::X25, PPC::X26, PPC::X27,
-    PPC::X28, PPC::X29, PPC::X30, PPC::X31,
-   =20
-    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
-    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
-    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
-    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
-    PPC::F30, PPC::F31,
-   =20
-    PPC::CR2, PPC::CR3, PPC::CR4,
-    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
-    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
-    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
-   =20
-    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
-    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
-    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
-   =20
-    PPC::LR8,  0
-  };
-
-  // 64-bit SVR4 calling convention.
-  static const unsigned SVR4_64_CalleeSavedRegs[] =3D {
-    PPC::X14, PPC::X15,
-    PPC::X16, PPC::X17, PPC::X18, PPC::X19,
-    PPC::X20, PPC::X21, PPC::X22, PPC::X23,
-    PPC::X24, PPC::X25, PPC::X26, PPC::X27,
-    PPC::X28, PPC::X29, PPC::X30, PPC::X31,
-
-    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
-    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
-    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
-    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
-    PPC::F30, PPC::F31,
-
-    PPC::CR2, PPC::CR3, PPC::CR4,
-
-    PPC::VRSAVE,
-
-    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
-    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
-    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
-
-    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
-    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
-    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
-
-    0
-  };
- =20
-  if (Subtarget.isDarwinABI())
-    return Subtarget.isPPC64() ? Darwin64_CalleeSavedRegs :
-                                 Darwin32_CalleeSavedRegs;
-
-  return Subtarget.isPPC64() ? SVR4_64_CalleeSavedRegs : SVR4_CalleeSavedR=
egs;
+  return Subtarget.isPPC64() ? CSR_SVR464_RegMask : CSR_SVR432_RegMask;
 }
=20
 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) cons=
t {
@@ -247,9 +146,6 @@
     Reserved.set(PPC::R13);
     Reserved.set(PPC::R31);
=20
-    if (!requiresRegisterScavenging(MF))
-      Reserved.set(PPC::R0);    // FIXME (64-bit): Remove
-
     Reserved.set(PPC::X0);
     Reserved.set(PPC::X1);
     Reserved.set(PPC::X13);
@@ -259,7 +155,7 @@
     if (Subtarget.isSVR4ABI()) {
       Reserved.set(PPC::X2);
     }
-    // Reserve R2 on Darwin to hack around the problem of save/restore of =
CR
+    // Reserve X2 on Darwin to hack around the problem of save/restore of =
CR
     // when the stack frame is too big to address directly; we need two re=
gs.
     // This is a hack.
     if (Subtarget.isDarwinABI()) {
@@ -273,6 +169,29 @@
   return Reserved;
 }
=20
+unsigned
+PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
+                                         MachineFunction &MF) const {
+  const TargetFrameLowering *TFI =3D MF.getTarget().getFrameLowering();
+  const unsigned DefaultSafety =3D 1;
+
+  switch (RC->getID()) {
+  default:
+    return 0;
+  case PPC::G8RCRegClassID:
+  case PPC::GPRCRegClassID: {
+    unsigned FP =3D TFI->hasFP(MF) ? 1 : 0;
+    return 32 - FP - DefaultSafety;
+  }
+  case PPC::F8RCRegClassID:
+  case PPC::F4RCRegClassID:
+  case PPC::VRRCRegClassID:
+    return 32 - DefaultSafety;
+  case PPC::CRRCRegClassID:
+    return 8 - DefaultSafety;
+  }
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Stack Frame Processing methods
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -280,7 +199,8 @@
 void PPCRegisterInfo::
 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
                               MachineBasicBlock::iterator I) const {
-  if (GuaranteedTailCallOpt && I->getOpcode() =3D=3D PPC::ADJCALLSTACKUP) {
+  if (MF.getTarget().Options.GuaranteedTailCallOpt &&
+      I->getOpcode() =3D=3D PPC::ADJCALLSTACKUP) {
     // Add (actually subtract) back the amount the callee popped on return.
     if (int CalleeAmt =3D  I->getOperand(1).getImm()) {
       bool is64Bit =3D Subtarget.isPPC64();
@@ -295,8 +215,9 @@
       DebugLoc dl =3D MI->getDebugLoc();
=20
       if (isInt<16>(CalleeAmt)) {
-        BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg).addReg(StackReg).
-          addImm(CalleeAmt);
+        BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
+          .addReg(StackReg, RegState::Kill)
+          .addImm(CalleeAmt);
       } else {
         MachineBasicBlock::iterator MBBI =3D I;
         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
@@ -304,9 +225,8 @@
         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
           .addReg(TmpReg, RegState::Kill)
           .addImm(CalleeAmt & 0xFFFF);
-        BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
-          .addReg(StackReg)
-          .addReg(StackReg)
+        BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
+          .addReg(StackReg, RegState::Kill)
           .addReg(TmpReg);
       }
     }
@@ -403,12 +323,12 @@
     if (requiresRegisterScavenging(MF)) // FIXME (64-bit): Use "true" part.
       BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
         .addReg(Reg, RegState::Kill)
-        .addReg(PPC::X1)
+        .addReg(PPC::X1, RegState::Define)
         .addReg(MI.getOperand(1).getReg());
     else
       BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
         .addReg(PPC::X0, RegState::Kill)
-        .addReg(PPC::X1)
+        .addReg(PPC::X1, RegState::Define)
         .addReg(MI.getOperand(1).getReg());
=20
     if (!MI.getOperand(1).isKill())
@@ -424,7 +344,7 @@
   } else {
     BuildMI(MBB, II, dl, TII.get(PPC::STWUX))
       .addReg(Reg, RegState::Kill)
-      .addReg(PPC::R1)
+      .addReg(PPC::R1, RegState::Define)
       .addReg(MI.getOperand(1).getReg());
=20
     if (!MI.getOperand(1).isKill())
@@ -455,28 +375,32 @@
                                       unsigned FrameIndex, int SPAdj,
                                       RegScavenger *RS) const {
   // Get the instruction.
-  MachineInstr &MI =3D *II;       // ; SPILL_CR <SrcReg>, <offset>, <FI>
+  MachineInstr &MI =3D *II;       // ; SPILL_CR <SrcReg>, <offset>
   // Get the instruction's basic block.
   MachineBasicBlock &MBB =3D *MI.getParent();
   DebugLoc dl =3D MI.getDebugLoc();
=20
-  const TargetRegisterClass *G8RC =3D &PPC::G8RCRegClass;
-  const TargetRegisterClass *GPRC =3D &PPC::GPRCRegClass;
-  const TargetRegisterClass *RC =3D Subtarget.isPPC64() ? G8RC : GPRC;
-  unsigned Reg =3D findScratchRegister(II, RS, RC, SPAdj);
+  // FIXME: Once LLVM supports creating virtual registers here, or the reg=
ister
+  // scavenger can return multiple registers, stop using reserved registers
+  // here.
+  (void) SPAdj;
+  (void) RS;
+
+  bool LP64 =3D Subtarget.isPPC64();
+  unsigned Reg =3D Subtarget.isDarwinABI() ?  (LP64 ? PPC::X2 : PPC::R2) :
+                                            (LP64 ? PPC::X0 : PPC::R0);
   unsigned SrcReg =3D MI.getOperand(0).getReg();
-  bool LP64 =3D Subtarget.isPPC64();
=20
   // We need to store the CR in the low 4-bits of the saved value. First, =
issue
   // an MFCRpsued to save all of the CRBits and, if needed, kill the SrcRe=
g.
-  BuildMI(MBB, II, dl, TII.get(PPC::MFCRpseud), Reg)
+  BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFCR8pseud : PPC::MFCRpseud), R=
eg)
           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
    =20
   // If the saved register wasn't CR0, shift the bits left so that they ar=
e in
   // CR0's slot.
   if (SrcReg !=3D PPC::CR0)
     // rlwinm rA, rA, ShiftBits, 0, 31.
-    BuildMI(MBB, II, dl, TII.get(PPC::RLWINM), Reg)
+    BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
       .addReg(Reg, RegState::Kill)
       .addImm(getPPCRegisterNumbering(SrcReg) * 4)
       .addImm(0)
@@ -490,6 +414,48 @@
   MBB.erase(II);
 }
=20
+void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
+                                      unsigned FrameIndex, int SPAdj,
+                                      RegScavenger *RS) const {
+  // Get the instruction.
+  MachineInstr &MI =3D *II;       // ; <DestReg> =3D RESTORE_CR <offset>
+  // Get the instruction's basic block.
+  MachineBasicBlock &MBB =3D *MI.getParent();
+  DebugLoc dl =3D MI.getDebugLoc();
+
+  // FIXME: Once LLVM supports creating virtual registers here, or the reg=
ister
+  // scavenger can return multiple registers, stop using reserved registers
+  // here.
+  (void) SPAdj;
+  (void) RS;
+
+  bool LP64 =3D Subtarget.isPPC64();
+  unsigned Reg =3D Subtarget.isDarwinABI() ?  (LP64 ? PPC::X2 : PPC::R2) :
+                                            (LP64 ? PPC::X0 : PPC::R0);
+  unsigned DestReg =3D MI.getOperand(0).getReg();
+  assert(MI.definesRegister(DestReg) &&
+    "RESTORE_CR does not define its destination");
+
+  addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::L=
WZ),
+                              Reg), FrameIndex);
+
+  // If the reloaded register isn't CR0, shift the bits right so that they=
 are
+  // in the right CR's slot.
+  if (DestReg !=3D PPC::CR0) {
+    unsigned ShiftBits =3D getPPCRegisterNumbering(DestReg)*4;
+    // rlwinm r11, r11, 32-ShiftBits, 0, 31.
+    BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
+             .addReg(Reg).addImm(32-ShiftBits).addImm(0)
+             .addImm(31);
+  }
+
+  BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTCRF8 : PPC::MTCRF), DestReg)
+             .addReg(Reg);
+
+  // Discard the pseudo instruction.
+  MBB.erase(II);
+}
+
 void
 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
                                      int SPAdj, RegScavenger *RS) const {
@@ -535,16 +501,23 @@
     return;
   }
=20
-  // Special case for pseudo-op SPILL_CR.
-  if (requiresRegisterScavenging(MF)) // FIXME (64-bit): Enable by default.
+  // Special case for pseudo-ops SPILL_CR and RESTORE_CR.
+  if (requiresRegisterScavenging(MF)) {
     if (OpC =3D=3D PPC::SPILL_CR) {
       lowerCRSpilling(II, FrameIndex, SPAdj, RS);
       return;
+    } else if (OpC =3D=3D PPC::RESTORE_CR) {
+      lowerCRRestore(II, FrameIndex, SPAdj, RS);
+      return;
     }
+  }
=20
   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP=
).
+
+  bool is64Bit =3D Subtarget.isPPC64();
   MI.getOperand(FIOperandNo).ChangeToRegister(TFI->hasFP(MF) ?
-                                              PPC::R31 : PPC::R1,
+                                              (is64Bit ? PPC::X31 : PPC::R=
31) :
+                                                (is64Bit ? PPC::X1 : PPC::=
R1),
                                               false);
=20
   // Figure out if the offset in the instruction is shifted right two bits=
. This
@@ -581,7 +554,8 @@
   // clear can be encoded.  This is extremely uncommon, because normally y=
ou
   // only "std" to a stack slot that is at least 4-byte aligned, but it can
   // happen in invalid code.
-  if (isInt<16>(Offset) && (!isIXAddr || (Offset & 3) =3D=3D 0)) {
+  if (OpC =3D=3D PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
+      (isInt<16>(Offset) && (!isIXAddr || (Offset & 3) =3D=3D 0))) {
     if (isIXAddr)
       Offset >>=3D 2;    // The actual encoded value has the low two bits =
zero.
     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
@@ -590,19 +564,19 @@
=20
   // The offset doesn't fit into a single register, scavenge one to build =
the
   // offset in.
-  // FIXME: figure out what SPAdj is doing here.
=20
-  // FIXME (64-bit): Use "findScratchRegister".
   unsigned SReg;
-  if (requiresRegisterScavenging(MF))
-    SReg =3D findScratchRegister(II, RS, &PPC::GPRCRegClass, SPAdj);
-  else
-    SReg =3D PPC::R0;
+  if (requiresRegisterScavenging(MF)) {
+    const TargetRegisterClass *G8RC =3D &PPC::G8RCRegClass;
+    const TargetRegisterClass *GPRC =3D &PPC::GPRCRegClass;
+    SReg =3D findScratchRegister(II, RS, is64Bit ? G8RC : GPRC, SPAdj);
+  } else
+    SReg =3D is64Bit ? PPC::X0 : PPC::R0;
=20
   // Insert a set of rA with the full offset value before the ld, st, or a=
dd
-  BuildMI(MBB, II, dl, TII.get(PPC::LIS), SReg)
+  BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SReg)
     .addImm(Offset >> 16);
-  BuildMI(MBB, II, dl, TII.get(PPC::ORI), SReg)
+  BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
     .addReg(SReg, RegState::Kill)
     .addImm(Offset);
=20
@@ -624,7 +598,7 @@
=20
   unsigned StackReg =3D MI.getOperand(FIOperandNo).getReg();
   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
-  MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false);
+  MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true=
);
 }
=20
 unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) cons=
t {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCRegisterInfo.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PPCRegisterInfo.h - PowerPC Register Information Impl -----*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- PPCRegisterInfo.h - PowerPC Register Information Impl ---*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -37,8 +37,12 @@
   /// This is used for addressing modes.
   virtual const TargetRegisterClass *getPointerRegClass(unsigned Kind=3D0)=
 const; =20
=20
+  unsigned getRegPressureLimit(const TargetRegisterClass *RC,
+                               MachineFunction &MF) const;
+
   /// Code Generation virtual methods...
-  const unsigned *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
+  const unsigned *getCallPreservedMask(CallingConv::ID CC) const;
=20
   BitVector getReservedRegs(const MachineFunction &MF) const;
=20
@@ -54,6 +58,8 @@
                          int SPAdj, RegScavenger *RS) const;
   void lowerCRSpilling(MachineBasicBlock::iterator II, unsigned FrameIndex,
                        int SPAdj, RegScavenger *RS) const;
+  void lowerCRRestore(MachineBasicBlock::iterator II, unsigned FrameIndex,
+                       int SPAdj, RegScavenger *RS) const;
   void eliminateFrameIndex(MachineBasicBlock::iterator II,
                            int SPAdj, RegScavenger *RS =3D NULL) const;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCRegisterInfo.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCRegisterInfo.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCRegisterInfo.td - The PowerPC Register File ------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCRegisterInfo.td - The PowerPC Register File -----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCRelocations.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCRelocations.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCRelocations.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PPCRelocations.h - PPC32 Code Relocations ----------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- PPCRelocations.h - PPC Code Relocations -----------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#ifndef PPC32RELOCATIONS_H
-#define PPC32RELOCATIONS_H
+#ifndef PPCRELOCATIONS_H
+#define PPCRELOCATIONS_H
=20
 #include "llvm/CodeGen/MachineRelocation.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCSchedule.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCSchedule.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCSchedule.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCSchedule.td - PowerPC Scheduling Definitions -----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCSchedule.td - PowerPC Scheduling Definitions ----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -50,7 +50,8 @@
 def LdStDCBA     : InstrItinClass;
 def LdStDCBF     : InstrItinClass;
 def LdStDCBI     : InstrItinClass;
-def LdStGeneral  : InstrItinClass;
+def LdStLoad     : InstrItinClass;
+def LdStStore    : InstrItinClass;
 def LdStDSS      : InstrItinClass;
 def LdStICBI     : InstrItinClass;
 def LdStUX       : InstrItinClass;
@@ -103,9 +104,11 @@
 // Processor instruction itineraries.
=20
 include "PPCScheduleG3.td"
+include "PPCSchedule440.td"
 include "PPCScheduleG4.td"
 include "PPCScheduleG4Plus.td"
 include "PPCScheduleG5.td"
+include "PPCScheduleA2.td"
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Instruction to itinerary class map - When add new opcodes to the suppor=
ted
@@ -149,8 +152,8 @@
 //    dcbf       LdStDCBF
 //    dcbi       LdStDCBI
 //    dcbst      LdStDCBF
-//    dcbt       LdStGeneral
-//    dcbtst     LdStGeneral
+//    dcbt       LdStLoad
+//    dcbtst     LdStLoad
 //    dcbz       LdStDCBF
 //    divd       IntDivD
 //    divdu      IntDivD
@@ -159,9 +162,9 @@
 //    dss        LdStDSS
 //    dst        LdStDSS
 //    dstst      LdStDSS
-//    eciwx      LdStGeneral
-//    ecowx      LdStGeneral
-//    eieio      LdStGeneral
+//    eciwx      LdStLoad
+//    ecowx      LdStLoad
+//    eieio      LdStLoad
 //    eqv        IntGeneral
 //    extsb      IntGeneral
 //    extsh      IntGeneral
@@ -201,10 +204,10 @@
 //    fsubs      FPGeneral
 //    icbi       LdStICBI
 //    isync      SprISYNC
-//    lbz        LdStGeneral
-//    lbzu       LdStGeneral
+//    lbz        LdStLoad
+//    lbzu       LdStLoad
 //    lbzux      LdStUX
-//    lbzx       LdStGeneral
+//    lbzx       LdStLoad
 //    ld         LdStLD
 //    ldarx      LdStLDARX
 //    ldu        LdStLD
@@ -222,11 +225,11 @@
 //    lhau       LdStLHA
 //    lhaux      LdStLHA
 //    lhax       LdStLHA
-//    lhbrx      LdStGeneral
-//    lhz        LdStGeneral
-//    lhzu       LdStGeneral
+//    lhbrx      LdStLoad
+//    lhz        LdStLoad
+//    lhzu       LdStLoad
 //    lhzux      LdStUX
-//    lhzx       LdStGeneral
+//    lhzx       LdStLoad
 //    lmw        LdStLMW
 //    lswi       LdStLMW
 //    lswx       LdStLMW
@@ -241,11 +244,11 @@
 //    lwarx      LdStLWARX
 //    lwaux      LdStLHA
 //    lwax       LdStLHA
-//    lwbrx      LdStGeneral
-//    lwz        LdStGeneral
-//    lwzu       LdStGeneral
+//    lwbrx      LdStLoad
+//    lwz        LdStLoad
+//    lwzu       LdStLoad
 //    lwzux      LdStUX
-//    lwzx       LdStGeneral
+//    lwzx       LdStLoad
 //    mcrf       BrMCR
 //    mcrfs      FPGeneral
 //    mcrxr      BrMCRX
@@ -306,10 +309,10 @@
 //    srawi      IntShift
 //    srd        IntRotateD
 //    srw        IntGeneral
-//    stb        LdStGeneral
-//    stbu       LdStGeneral
-//    stbux      LdStGeneral
-//    stbx       LdStGeneral
+//    stb        LdStStore
+//    stbu       LdStStore
+//    stbux      LdStStore
+//    stbx       LdStStore
 //    std        LdStSTD
 //    stdcx.     LdStSTDCX
 //    stdu       LdStSTD
@@ -324,11 +327,11 @@
 //    stfsu      LdStUX
 //    stfsux     LdStUX
 //    stfsx      LdStUX
-//    sth        LdStGeneral
-//    sthbrx     LdStGeneral
-//    sthu       LdStGeneral
-//    sthux      LdStGeneral
-//    sthx       LdStGeneral
+//    sth        LdStStore
+//    sthbrx     LdStStore
+//    sthu       LdStStore
+//    sthux      LdStStore
+//    sthx       LdStStore
 //    stmw       LdStLMW
 //    stswi      LdStLMW
 //    stswx      LdStLMW
@@ -337,12 +340,12 @@
 //    stvewx     LdStSTVEBX
 //    stvx       LdStSTVEBX
 //    stvxl      LdStSTVEBX
-//    stw        LdStGeneral
-//    stwbrx     LdStGeneral
+//    stw        LdStStore
+//    stwbrx     LdStStore
 //    stwcx.     LdStSTWCX
-//    stwu       LdStGeneral
-//    stwux      LdStGeneral
-//    stwx       LdStGeneral
+//    stwu       LdStStore
+//    stwux      LdStStore
+//    stwx       LdStStore
 //    subf       IntGeneral
 //    subfc      IntGeneral
 //    subfe      IntGeneral
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCScheduleG3.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG3.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG3.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCScheduleG3.td - PPC G3 Scheduling Definitions ----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCScheduleG3.td - PPC G3 Scheduling Definitions ---*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file defines the itinerary class data for the G3 (750) processor.
@@ -32,7 +32,8 @@
   InstrItinData<LdStDCBA    , [InstrStage<2, [SLU]>]>,
   InstrItinData<LdStDCBF    , [InstrStage<3, [SLU]>]>,
   InstrItinData<LdStDCBI    , [InstrStage<3, [SLU]>]>,
-  InstrItinData<LdStGeneral , [InstrStage<2, [SLU]>]>,
+  InstrItinData<LdStLoad    , [InstrStage<2, [SLU]>]>,
+  InstrItinData<LdStStore   , [InstrStage<2, [SLU]>]>,
   InstrItinData<LdStICBI    , [InstrStage<3, [SLU]>]>,
   InstrItinData<LdStUX      , [InstrStage<2, [SLU]>]>,
   InstrItinData<LdStLFD     , [InstrStage<2, [SLU]>]>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCScheduleG4.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG4.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG4.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCScheduleG4.td - PPC G4 Scheduling Definitions ----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCScheduleG4.td - PPC G4 Scheduling Definitions ---*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file defines the itinerary class data for the G4 (7400) processor.
@@ -31,7 +31,8 @@
   InstrItinData<BrMCRX      , [InstrStage<1, [SRU]>]>,
   InstrItinData<LdStDCBF    , [InstrStage<2, [SLU]>]>,
   InstrItinData<LdStDCBI    , [InstrStage<2, [SLU]>]>,
-  InstrItinData<LdStGeneral , [InstrStage<2, [SLU]>]>,
+  InstrItinData<LdStLoad    , [InstrStage<2, [SLU]>]>,
+  InstrItinData<LdStStore   , [InstrStage<2, [SLU]>]>,
   InstrItinData<LdStDSS     , [InstrStage<2, [SLU]>]>,
   InstrItinData<LdStICBI    , [InstrStage<2, [SLU]>]>,
   InstrItinData<LdStUX      , [InstrStage<2, [SLU]>]>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCScheduleG4Plus.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG4Plus.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG4Plus.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCScheduleG4Plus.td - PPC G4+ Scheduling Defs. -----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCScheduleG4Plus.td - PPC G4+ Scheduling Defs. ----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file defines the itinerary class data for the G4+ (7450) processor.
@@ -34,7 +34,8 @@
   InstrItinData<BrMCRX      , [InstrStage<2, [IU2]>]>,
   InstrItinData<LdStDCBF    , [InstrStage<3, [SLU]>]>,
   InstrItinData<LdStDCBI    , [InstrStage<3, [SLU]>]>,
-  InstrItinData<LdStGeneral , [InstrStage<3, [SLU]>]>,
+  InstrItinData<LdStLoad    , [InstrStage<3, [SLU]>]>,
+  InstrItinData<LdStStore   , [InstrStage<3, [SLU]>]>,
   InstrItinData<LdStDSS     , [InstrStage<3, [SLU]>]>,
   InstrItinData<LdStICBI    , [InstrStage<3, [IU2]>]>,
   InstrItinData<LdStUX      , [InstrStage<3, [SLU]>]>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCScheduleG5.td
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG5.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCScheduleG5.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- PPCScheduleG5.td - PPC G5 Scheduling Definitions ----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- PPCScheduleG5.td - PPC G5 Scheduling Definitions ---*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file defines the itinerary class data for the G5 (970) processor.
@@ -35,7 +35,8 @@
   InstrItinData<BrMCR       , [InstrStage<2, [BPU]>]>,
   InstrItinData<BrMCRX      , [InstrStage<3, [BPU]>]>,
   InstrItinData<LdStDCBF    , [InstrStage<3, [SLU]>]>,
-  InstrItinData<LdStGeneral , [InstrStage<3, [SLU]>]>,
+  InstrItinData<LdStLoad    , [InstrStage<3, [SLU]>]>,
+  InstrItinData<LdStStore   , [InstrStage<3, [SLU]>]>,
   InstrItinData<LdStDSS     , [InstrStage<10, [SLU]>]>,
   InstrItinData<LdStICBI    , [InstrStage<40, [SLU]>]>,
   InstrItinData<LdStUX      , [InstrStage<4, [SLU]>]>,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCSubtarget.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCSubtarget.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCSubtarget.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- PowerPCSubtarget.cpp - PPC Subtarget Information ------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- PowerPCSubtarget.cpp - PPC Subtarget Information -----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,6 +12,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "PPCSubtarget.h"
+#include "PPCRegisterInfo.h"
 #include "PPC.h"
 #include "llvm/GlobalValue.h"
 #include "llvm/Target/TargetMachine.h"
@@ -74,6 +75,7 @@
   , HasAltivec(false)
   , HasFSQRT(false)
   , HasSTFIWX(false)
+  , IsBookE(false)
   , HasLazyResolverStubs(false)
   , IsJITCodeModel(false)
   , TargetTriple(TT) {
@@ -139,3 +141,23 @@
   return GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() ||
          GV->hasCommonLinkage() || isDecl;
 }
+
+bool PPCSubtarget::enablePostRAScheduler(
+           CodeGenOpt::Level OptLevel,
+           TargetSubtargetInfo::AntiDepBreakMode& Mode,
+           RegClassVector& CriticalPathRCs) const {
+  if (DarwinDirective =3D=3D PPC::DIR_440 || DarwinDirective =3D=3D PPC::D=
IR_A2)
+    Mode =3D TargetSubtargetInfo::ANTIDEP_ALL;
+  else
+    Mode =3D TargetSubtargetInfo::ANTIDEP_CRITICAL;
+
+  CriticalPathRCs.clear();
+
+  if (isPPC64())
+    CriticalPathRCs.push_back(&PPC::G8RCRegClass);
+  else
+    CriticalPathRCs.push_back(&PPC::GPRCRegClass);
+
+  return OptLevel >=3D CodeGenOpt::Default;
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCSubtarget.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCSubtarget.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCSubtarget.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- PPCSubtarget.h - Define Subtarget for the PPC -------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- PPCSubtarget.h - Define Subtarget for the PPC ----------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -33,12 +33,14 @@
   enum {
     DIR_NONE,
     DIR_32,
+    DIR_440,=20
     DIR_601,=20
     DIR_602,=20
     DIR_603,=20
     DIR_7400,
     DIR_750,=20
     DIR_970,=20
+    DIR_A2,
     DIR_64 =20
   };
 }
@@ -66,6 +68,7 @@
   bool HasAltivec;
   bool HasFSQRT;
   bool HasSTFIWX;
+  bool IsBookE;
   bool HasLazyResolverStubs;
   bool IsJITCodeModel;
  =20
@@ -136,15 +139,22 @@
   bool hasSTFIWX() const { return HasSTFIWX; }
   bool hasAltivec() const { return HasAltivec; }
   bool isGigaProcessor() const { return IsGigaProcessor; }
+  bool isBookE() const { return IsBookE; }
=20
   const Triple &getTargetTriple() const { return TargetTriple; }
=20
   /// isDarwin - True if this is any darwin platform.
   bool isDarwin() const { return TargetTriple.isMacOSX(); }
+  /// isBGP - True if this is a BG/P platform.
+  bool isBGP() const { return TargetTriple.getVendor() =3D=3D Triple::BGP;=
 }
=20
   bool isDarwinABI() const { return isDarwin(); }
   bool isSVR4ABI() const { return !isDarwin(); }
=20
+  /// enablePostRAScheduler - True at 'More' optimization.
+  bool enablePostRAScheduler(CodeGenOpt::Level OptLevel,
+                             TargetSubtargetInfo::AntiDepBreakMode& Mode,
+                             RegClassVector& CriticalPathRCs) const;
 };
 } // End llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCTargetMachine.cpp
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCTargetMachine.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -11,10 +11,11 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "PPCTargetMachine.h"
 #include "PPC.h"
-#include "PPCTargetMachine.h"
 #include "llvm/PassManager.h"
 #include "llvm/MC/MCStreamer.h"
+#include "llvm/CodeGen/Passes.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Support/FormattedStream.h"
 #include "llvm/Support/TargetRegistry.h"
@@ -22,37 +23,46 @@
=20
 extern "C" void LLVMInitializePowerPCTarget() {
   // Register the targets
-  RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target); =20
+  RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
   RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
 }
=20
 PPCTargetMachine::PPCTargetMachine(const Target &T, StringRef TT,
                                    StringRef CPU, StringRef FS,
+                                   const TargetOptions &Options,
                                    Reloc::Model RM, CodeModel::Model CM,
+                                   CodeGenOpt::Level OL,
                                    bool is64Bit)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     Subtarget(TT, CPU, FS, is64Bit),
     DataLayout(Subtarget.getTargetDataString()), InstrInfo(*this),
     FrameLowering(Subtarget), JITInfo(*this, is64Bit),
     TLInfo(*this), TSInfo(*this),
     InstrItins(Subtarget.getInstrItineraryData()) {
+
+  // The binutils for the BG/P are too old for CFI.
+  if (Subtarget.isBGP())
+    setMCUseCFI(false);
 }
=20
-/// Override this for PowerPC.  Tail merging happily breaks up instruction=
 issue
-/// groups, which typically degrades performance.
-bool PPCTargetMachine::getEnableTailMergeDefault() const { return false; }
+void PPC32TargetMachine::anchor() { }
=20
-PPC32TargetMachine::PPC32TargetMachine(const Target &T, StringRef TT,=20
+PPC32TargetMachine::PPC32TargetMachine(const Target &T, StringRef TT,
                                        StringRef CPU, StringRef FS,
-                                       Reloc::Model RM, CodeModel::Model C=
M)=20
-  : PPCTargetMachine(T, TT, CPU, FS, RM, CM, false) {
+                                       const TargetOptions &Options,
+                                       Reloc::Model RM, CodeModel::Model C=
M,
+                                       CodeGenOpt::Level OL)
+  : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {
 }
=20
+void PPC64TargetMachine::anchor() { }
=20
-PPC64TargetMachine::PPC64TargetMachine(const Target &T, StringRef TT,=20
+PPC64TargetMachine::PPC64TargetMachine(const Target &T, StringRef TT,
                                        StringRef CPU,  StringRef FS,
-                                       Reloc::Model RM, CodeModel::Model C=
M)
-  : PPCTargetMachine(T, TT, CPU, FS, RM, CM, true) {
+                                       const TargetOptions &Options,
+                                       Reloc::Model RM, CodeModel::Model C=
M,
+                                       CodeGenOpt::Level OL)
+  : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {
 }
=20
=20
@@ -60,33 +70,56 @@
 // Pass Pipeline Configuration
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-bool PPCTargetMachine::addInstSelector(PassManagerBase &PM,
-                                       CodeGenOpt::Level OptLevel) {
+namespace {
+/// PPC Code Generator Pass Configuration Options.
+class PPCPassConfig : public TargetPassConfig {
+public:
+  PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  PPCTargetMachine &getPPCTargetMachine() const {
+    return getTM<PPCTargetMachine>();
+  }
+
+  virtual bool addInstSelector();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
+  TargetPassConfig *PassConfig =3D new PPCPassConfig(this, PM);
+
+  // Override this for PowerPC.  Tail merging happily breaks up instructio=
n issue
+  // groups, which typically degrades performance.
+  PassConfig->setEnableTailMerge(false);
+
+  return PassConfig;
+}
+
+bool PPCPassConfig::addInstSelector() {
   // Install an instruction selector.
-  PM.add(createPPCISelDag(*this));
+  PM.add(createPPCISelDag(getPPCTargetMachine()));
   return false;
 }
=20
-bool PPCTargetMachine::addPreEmitPass(PassManagerBase &PM,
-                                      CodeGenOpt::Level OptLevel) {
+bool PPCPassConfig::addPreEmitPass() {
   // Must run branch selection immediately preceding the asm printer.
   PM.add(createPPCBranchSelectionPass());
   return false;
 }
=20
 bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM,
-                                      CodeGenOpt::Level OptLevel,
                                       JITCodeEmitter &JCE) {
   // FIXME: This should be moved to TargetJITInfo!!
   if (Subtarget.isPPC64())
     // Temporary workaround for the inability of PPC64 JIT to handle jump
     // tables.
-    DisableJumpTables =3D true;     =20
- =20
+    Options.DisableJumpTables =3D true;
+
   // Inform the subtarget that we are in JIT mode.  FIXME: does this break=
 macho
   // writing?
   Subtarget.SetJITMode();
- =20
+
   // Machine code emitter pass for PowerPC.
   PM.add(createPPCJITCodeEmitterPass(*this, JCE));
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/PowerPC/P=
PCTargetMachine.h
--- a/head/contrib/llvm/lib/Target/PowerPC/PPCTargetMachine.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/PowerPC/PPCTargetMachine.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- PPCTargetMachine.h - Define TargetMachine for PowerPC -----*=
- C++ -*-=3D//
+//=3D=3D=3D-- PPCTargetMachine.h - Define TargetMachine for PowerPC ---*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -24,8 +24,6 @@
 #include "llvm/Target/TargetData.h"
=20
 namespace llvm {
-class PassManager;
-class GlobalValue;
=20
 /// PPCTargetMachine - Common code between 32-bit and 64-bit PowerPC targe=
ts.
 ///
@@ -41,15 +39,16 @@
=20
 public:
   PPCTargetMachine(const Target &T, StringRef TT,
-                   StringRef CPU, StringRef FS,
-                   Reloc::Model RM, CodeModel::Model CM, bool is64Bit);
+                   StringRef CPU, StringRef FS, const TargetOptions &Optio=
ns,
+                   Reloc::Model RM, CodeModel::Model CM,
+                   CodeGenOpt::Level OL, bool is64Bit);
=20
   virtual const PPCInstrInfo      *getInstrInfo() const { return &InstrInf=
o; }
   virtual const PPCFrameLowering  *getFrameLowering() const {
     return &FrameLowering;
   }
   virtual       PPCJITInfo        *getJITInfo()         { return &JITInfo;=
 }
-  virtual const PPCTargetLowering *getTargetLowering() const {=20
+  virtual const PPCTargetLowering *getTargetLowering() const {
    return &TLInfo;
   }
   virtual const PPCSelectionDAGInfo* getSelectionDAGInfo() const {
@@ -58,37 +57,39 @@
   virtual const PPCRegisterInfo   *getRegisterInfo() const {
     return &InstrInfo.getRegisterInfo();
   }
- =20
+
   virtual const TargetData    *getTargetData() const    { return &DataLayo=
ut; }
   virtual const PPCSubtarget  *getSubtargetImpl() const { return &Subtarge=
t; }
-  virtual const InstrItineraryData *getInstrItineraryData() const { =20
+  virtual const InstrItineraryData *getInstrItineraryData() const {
     return &InstrItins;
   }
=20
   // Pass Pipeline Configuration
-  virtual bool addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptL=
evel);
-  virtual bool addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel);
-  virtual bool addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel,
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
+  virtual bool addCodeEmitter(PassManagerBase &PM,
                               JITCodeEmitter &JCE);
-  virtual bool getEnableTailMergeDefault() const;
 };
=20
 /// PPC32TargetMachine - PowerPC 32-bit target machine.
 ///
 class PPC32TargetMachine : public PPCTargetMachine {
+  virtual void anchor();
 public:
   PPC32TargetMachine(const Target &T, StringRef TT,
-                     StringRef CPU, StringRef FS,
-                     Reloc::Model RM, CodeModel::Model CM);
+                     StringRef CPU, StringRef FS, const TargetOptions &Opt=
ions,
+                     Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL);
 };
=20
 /// PPC64TargetMachine - PowerPC 64-bit target machine.
 ///
 class PPC64TargetMachine : public PPCTargetMachine {
+  virtual void anchor();
 public:
   PPC64TargetMachine(const Target &T, StringRef TT,
-                     StringRef CPU, StringRef FS,
-                     Reloc::Model RM, CodeModel::Model CM);
+                     StringRef CPU, StringRef FS, const TargetOptions &Opt=
ions,
+                     Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL);
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Del=
aySlotFiller.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/DelaySlotFiller.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/DelaySlotFiller.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -100,7 +100,7 @@
   bool Changed =3D false;
=20
   for (MachineBasicBlock::iterator I =3D MBB.begin(); I !=3D MBB.end(); ++=
I)
-    if (I->getDesc().hasDelaySlot()) {
+    if (I->hasDelaySlot()) {
       MachineBasicBlock::iterator D =3D MBB.end();
       MachineBasicBlock::iterator J =3D I;
=20
@@ -149,7 +149,7 @@
   }
=20
   //Call's delay filler can def some of call's uses.
-  if (slot->getDesc().isCall())
+  if (slot->isCall())
     insertCallUses(slot, RegUses);
   else
     insertDefsUses(slot, RegDefs, RegUses);
@@ -170,7 +170,7 @@
     if (I->hasUnmodeledSideEffects()
         || I->isInlineAsm()
         || I->isLabel()
-        || I->getDesc().hasDelaySlot()
+        || I->hasDelaySlot()
         || isDelayFiller(MBB, I))
       break;
=20
@@ -194,13 +194,13 @@
   if (candidate->isImplicitDef() || candidate->isKill())
     return true;
=20
-  if (candidate->getDesc().mayLoad()) {
+  if (candidate->mayLoad()) {
     sawLoad =3D true;
     if (sawStore)
       return true;
   }
=20
-  if (candidate->getDesc().mayStore()) {
+  if (candidate->mayStore()) {
     if (sawStore)
       return true;
     sawStore =3D true;
@@ -282,7 +282,7 @@
   if (RegSet.count(Reg))
     return true;
   // check Aliased Registers
-  for (const unsigned *Alias =3D TM.getRegisterInfo()->getAliasSet(Reg);
+  for (const uint16_t *Alias =3D TM.getRegisterInfo()->getAliasSet(Reg);
        *Alias; ++ Alias)
     if (RegSet.count(*Alias))
       return true;
@@ -298,13 +298,13 @@
     return false;
   if (candidate->getOpcode() =3D=3D SP::UNIMP)
     return true;
-  const MCInstrDesc &prevdesc =3D (--candidate)->getDesc();
-  return prevdesc.hasDelaySlot();
+  --candidate;
+  return candidate->hasDelaySlot();
 }
=20
 bool Filler::needsUnimp(MachineBasicBlock::iterator I, unsigned &StructSiz=
e)
 {
-  if (!I->getDesc().isCall())
+  if (!I->isCall())
     return false;
=20
   unsigned structSizeOpNum =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/FPM=
over.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/FPMover.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/FPMover.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -59,19 +59,19 @@
 /// registers that correspond to it.
 static void getDoubleRegPair(unsigned DoubleReg, unsigned &EvenReg,
                              unsigned &OddReg) {
-  static const unsigned EvenHalvesOfPairs[] =3D {
+  static const uint16_t EvenHalvesOfPairs[] =3D {
     SP::F0, SP::F2, SP::F4, SP::F6, SP::F8, SP::F10, SP::F12, SP::F14,
     SP::F16, SP::F18, SP::F20, SP::F22, SP::F24, SP::F26, SP::F28, SP::F30
   };
-  static const unsigned OddHalvesOfPairs[] =3D {
+  static const uint16_t OddHalvesOfPairs[] =3D {
     SP::F1, SP::F3, SP::F5, SP::F7, SP::F9, SP::F11, SP::F13, SP::F15,
     SP::F17, SP::F19, SP::F21, SP::F23, SP::F25, SP::F27, SP::F29, SP::F31
   };
-  static const unsigned DoubleRegsInOrder[] =3D {
+  static const uint16_t DoubleRegsInOrder[] =3D {
     SP::D0, SP::D1, SP::D2, SP::D3, SP::D4, SP::D5, SP::D6, SP::D7, SP::D8,
     SP::D9, SP::D10, SP::D11, SP::D12, SP::D13, SP::D14, SP::D15
   };
-  for (unsigned i =3D 0; i < sizeof(DoubleRegsInOrder)/sizeof(unsigned); +=
+i)
+  for (unsigned i =3D 0; i < array_lengthof(DoubleRegsInOrder); ++i)
     if (DoubleRegsInOrder[i] =3D=3D DoubleReg) {
       EvenReg =3D EvenHalvesOfPairs[i];
       OddReg =3D OddHalvesOfPairs[i];
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/MCT=
argetDesc/SparcMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -16,6 +16,8 @@
=20
 using namespace llvm;
=20
+void SparcELFMCAsmInfo::anchor() { }
+
 SparcELFMCAsmInfo::SparcELFMCAsmInfo(const Target &T, StringRef TT) {
   IsLittleEndian =3D false;
   Triple TheTriple(TT);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/MCT=
argetDesc/SparcMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCAsmInfo.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- SparcMCAsmInfo.h - Sparc asm properties -------------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- SparcMCAsmInfo.h - Sparc asm properties ----------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,13 +14,15 @@
 #ifndef SPARCTARGETASMINFO_H
 #define SPARCTARGETASMINFO_H
=20
-#include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MCAsmInfo.h"
=20
 namespace llvm {
+  class StringRef;
   class Target;
=20
-  struct SparcELFMCAsmInfo : public MCAsmInfo {
+  class SparcELFMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit SparcELFMCAsmInfo(const Target &T, StringRef TT);
   };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/MCT=
argetDesc/SparcMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- SparcMCTargetDesc.cpp - Sparc Target Descriptions --------*-=
 C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- SparcMCTargetDesc.cpp - Sparc Target Descriptions ----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -17,6 +17,7 @@
 #include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 #define GET_INSTRINFO_MC_DESC
@@ -50,9 +51,10 @@
 }
=20
 static MCCodeGenInfo *createSparcMCCodeGenInfo(StringRef TT, Reloc::Model =
RM,
-                                               CodeModel::Model CM) {
+                                               CodeModel::Model CM,
+                                               CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/MCT=
argetDesc/SparcMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/MCTargetDesc/SparcMCTargetDesc.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,7 @@
 #define SPARCMCTARGETDESC_H
=20
 namespace llvm {
-class MCSubtargetInfo;
 class Target;
-class StringRef;
=20
 extern Target TheSparcTarget;
 extern Target TheSparcV9Target;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rc.h
--- a/head/contrib/llvm/lib/Target/Sparc/Sparc.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/Target/Sparc/Sparc.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -18,7 +18,6 @@
 #include "MCTargetDesc/SparcMCTargetDesc.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Target/TargetMachine.h"
-#include <cassert>
=20
 namespace llvm {
   class FunctionPass;
@@ -74,7 +73,6 @@
  =20
   inline static const char *SPARCCondCodeToString(SPCC::CondCodes CC) {
     switch (CC) {
-    default: llvm_unreachable("Unknown condition code");
     case SPCC::ICC_NE:  return "ne";
     case SPCC::ICC_E:   return "e";
     case SPCC::ICC_G:   return "g";
@@ -103,7 +101,8 @@
     case SPCC::FCC_LE:  return "le";
     case SPCC::FCC_ULE: return "ule";
     case SPCC::FCC_O:   return "o";
-    }      =20
+    }
+    llvm_unreachable("Invalid cond code");
   }
 }  // end namespace llvm
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rc.td
--- a/head/contrib/llvm/lib/Target/Sparc/Sparc.td	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Target/Sparc/Sparc.td	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- Sparc.td - Describe the Sparc Target Machine --------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- Sparc.td - Describe the Sparc Target Machine -------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcAsmPrinter.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcAsmPrinter.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcAsmPrinter.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -23,7 +23,6 @@
 #include "llvm/MC/MCSymbol.h"
 #include "llvm/Target/Mangler.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
@@ -63,6 +62,8 @@
    =20
     virtual bool isBlockOnlyReachableByFallthrough(const MachineBasicBlock=
 *MBB)
                        const;
+
+    virtual MachineLocation getDebugValueLocation(const MachineInstr *MI) =
const;
   };
 } // end of anonymous namespace
=20
@@ -82,7 +83,7 @@
   }
   switch (MO.getType()) {
   case MachineOperand::MO_Register:
-    O << "%" << LowercaseString(getRegisterName(MO.getReg()));
+    O << "%" << StringRef(getRegisterName(MO.getReg())).lower();
     break;
=20
   case MachineOperand::MO_Immediate:
@@ -141,13 +142,13 @@
   std::string operand =3D "";
   const MachineOperand &MO =3D MI->getOperand(opNum);
   switch (MO.getType()) {
-  default: assert(0 && "Operand is not a register ");
+  default: llvm_unreachable("Operand is not a register");
   case MachineOperand::MO_Register:
     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
            "Operand is not a physical register ");
     assert(MO.getReg() !=3D SP::O7 &&=20
            "%o7 is assigned as destination for getpcx!");
-    operand =3D "%" + LowercaseString(getRegisterName(MO.getReg()));
+    operand =3D "%" + StringRef(getRegisterName(MO.getReg())).lower();
     break;
   }
=20
@@ -237,12 +238,19 @@
  =20
   // Check if the last terminator is an unconditional branch.
   MachineBasicBlock::const_iterator I =3D Pred->end();
-  while (I !=3D Pred->begin() && !(--I)->getDesc().isTerminator())
+  while (I !=3D Pred->begin() && !(--I)->isTerminator())
     ; // Noop
-  return I =3D=3D Pred->end() || !I->getDesc().isBarrier();
+  return I =3D=3D Pred->end() || !I->isBarrier();
 }
=20
-
+MachineLocation SparcAsmPrinter::
+getDebugValueLocation(const MachineInstr *MI) const {
+  assert(MI->getNumOperands() =3D=3D 4 && "Invalid number of operands!");
+  assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
+         "Unexpected MachineOperand types");
+  return MachineLocation(MI->getOperand(0).getReg(),
+                         MI->getOperand(1).getImm());
+}
=20
 // Force static initialization.
 extern "C" void LLVMInitializeSparcAsmPrinter() {=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcCallingConv.td
--- a/head/contrib/llvm/lib/Target/Sparc/SparcCallingConv.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcCallingConv.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- SparcCallingConv.td - Calling Conventions Sparc -----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SparcCallingConv.td - Calling Conventions Sparc ----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This describes the calling conventions for the Sparc architectures.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcFrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcFrameLowering.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcFrameLowering.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D- SparcFrameLowering.cpp - Sparc Frame Information -------*-=
 C++ -*-=3D=3D=3D=3D//
+//=3D=3D=3D-- SparcFrameLowering.cpp - Sparc Frame Information -----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcFrameLowering.h
--- a/head/contrib/llvm/lib/Target/Sparc/SparcFrameLowering.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcFrameLowering.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SparcFrameLowering.h - Define frame lowering for Sparc --*- C=
++ -*--=3D=3D=3D//
+//=3D=3D=3D-- SparcFrameLowering.h - Define frame lowering for Sparc --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcISelDAGToDAG.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcISelDAGToDAG.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -176,7 +176,6 @@
                                          MulLHS, MulRHS);
     // The high part is in the Y register.
     return CurDAG->SelectNodeTo(N, SP::RDY, MVT::i32, SDValue(Mul, 1));
-    return NULL;
   }
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcISelLowering.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -25,7 +25,6 @@
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
-#include "llvm/ADT/VectorExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 using namespace llvm;
=20
@@ -51,7 +50,7 @@
                                 MVT &LocVT, CCValAssign::LocInfo &LocInfo,
                                 ISD::ArgFlagsTy &ArgFlags, CCState &State)
 {
-  static const unsigned RegList[] =3D {
+  static const uint16_t RegList[] =3D {
     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
   };
   //Try to get first reg
@@ -175,7 +174,7 @@
       SDValue FIPtr =3D DAG.getFrameIndex(FrameIdx, MVT::i32);
       SDValue Arg =3D DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
                                 MachinePointerInfo(),
-                                false, false, 0);
+                                false, false, false, 0);
       InVals.push_back(Arg);
       continue;
     }
@@ -197,7 +196,7 @@
           SDValue FIPtr =3D DAG.getFrameIndex(FrameIdx, MVT::i32);
           LoVal =3D DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
                               MachinePointerInfo(),
-                              false, false, 0);
+                              false, false, false, 0);
         } else {
           unsigned loReg =3D MF.addLiveIn(NextVA.getLocReg(),
                                         &SP::IntRegsRegClass);
@@ -237,7 +236,7 @@
         SDValue FIPtr =3D DAG.getFrameIndex(FI, getPointerTy());
         SDValue Load =3D DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
                                    MachinePointerInfo(),
-                                   false,false, 0);
+                                   false,false, false, 0);
         InVals.push_back(Load);
         continue;
       }
@@ -248,7 +247,7 @@
       SDValue FIPtr =3D DAG.getFrameIndex(FI, getPointerTy());
       SDValue HiVal =3D DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
                                   MachinePointerInfo(),
-                                  false, false, 0);
+                                  false, false, false, 0);
       int FI2 =3D MF.getFrameInfo()->CreateFixedObject(4,
                                                      Offset+4,
                                                      true);
@@ -256,7 +255,7 @@
=20
       SDValue LoVal =3D DAG.getLoad(MVT::i32, dl, Chain, FIPtr2,
                                   MachinePointerInfo(),
-                                  false, false, 0);
+                                  false, false, false, 0);
=20
       SDValue WholeValue =3D
         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
@@ -273,7 +272,7 @@
     if (VA.getValVT() =3D=3D MVT::i32 || VA.getValVT() =3D=3D MVT::f32) {
       Load =3D DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
                          MachinePointerInfo(),
-                         false, false, 0);
+                         false, false, false, 0);
     } else {
       ISD::LoadExtType LoadOp =3D ISD::SEXTLOAD;
       // Sparc is big endian, so add an offset based on the ObjectVT.
@@ -302,11 +301,11 @@
=20
   // Store remaining ArgRegs to the stack if this is a varargs function.
   if (isVarArg) {
-    static const unsigned ArgRegs[] =3D {
+    static const uint16_t ArgRegs[] =3D {
       SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
     };
     unsigned NumAllocated =3D CCInfo.getFirstUnallocated(ArgRegs, 6);
-    const unsigned *CurArgReg =3D ArgRegs+NumAllocated, *ArgRegEnd =3D Arg=
Regs+6;
+    const uint16_t *CurArgReg =3D ArgRegs+NumAllocated, *ArgRegEnd =3D Arg=
Regs+6;
     unsigned ArgOffset =3D CCInfo.getNextStackOffset();
     if (NumAllocated =3D=3D 6)
       ArgOffset +=3D StackOffset;
@@ -348,7 +347,7 @@
 SDValue
 SparcTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                                CallingConv::ID CallConv, bool isVarArg,
-                               bool &isTailCall,
+                               bool doesNotRet, bool &isTailCall,
                                const SmallVectorImpl<ISD::OutputArg> &Outs,
                                const SmallVectorImpl<SDValue> &OutVals,
                                const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -467,13 +466,13 @@
                                    false, false, 0);
       // Sparc is big-endian, so the high part comes first.
       SDValue Hi =3D DAG.getLoad(MVT::i32, dl, Store, StackPtr,
-                               MachinePointerInfo(), false, false, 0);
+                               MachinePointerInfo(), false, false, false, =
0);
       // Increment the pointer to the other half.
       StackPtr =3D DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), Stac=
kPtr,
                              DAG.getIntPtrConstant(4));
       // Load the low part.
       SDValue Lo =3D DAG.getLoad(MVT::i32, dl, Store, StackPtr,
-                               MachinePointerInfo(), false, false, 0);
+                               MachinePointerInfo(), false, false, false, =
0);
=20
       if (VA.isRegLoc()) {
         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
@@ -763,7 +762,9 @@
   setOperationAction(ISD::FMA  , MVT::f32, Expand);
   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
   setOperationAction(ISD::ROTL , MVT::i32, Expand);
   setOperationAction(ISD::ROTR , MVT::i32, Expand);
   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
@@ -831,22 +832,19 @@
 /// be zero. Op is expected to be a target specific node. Used by DAG
 /// combiner.
 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
-                                                         const APInt &Mask,
                                                          APInt &KnownZero,
                                                          APInt &KnownOne,
                                                          const SelectionDA=
G &DAG,
                                                          unsigned Depth) c=
onst {
   APInt KnownZero2, KnownOne2;
-  KnownZero =3D KnownOne =3D APInt(Mask.getBitWidth(), 0);   // Don't know=
 anything.
+  KnownZero =3D KnownOne =3D APInt(KnownZero.getBitWidth(), 0);
=20
   switch (Op.getOpcode()) {
   default: break;
   case SPISD::SELECT_ICC:
   case SPISD::SELECT_FCC:
-    DAG.ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne,
-                          Depth+1);
-    DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2,
-                          Depth+1);
+    DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
+    DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1=
);
     assert((KnownZero & KnownOne) =3D=3D 0 && "Bits known to be one AND ze=
ro?");
     assert((KnownZero2 & KnownOne2) =3D=3D 0 && "Bits known to be one AND =
zero?");
=20
@@ -897,7 +895,7 @@
   SDValue AbsAddr =3D DAG.getNode(ISD::ADD, dl, MVT::i32,
                                 GlobalBase, RelAddr);
   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
-                     AbsAddr, MachinePointerInfo(), false, false, 0);
+                     AbsAddr, MachinePointerInfo(), false, false, false, 0=
);
 }
=20
 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
@@ -918,7 +916,7 @@
   SDValue AbsAddr =3D DAG.getNode(ISD::ADD, dl, MVT::i32,
                                 GlobalBase, RelAddr);
   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
-                     AbsAddr, MachinePointerInfo(), false, false, 0);
+                     AbsAddr, MachinePointerInfo(), false, false, false, 0=
);
 }
=20
 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
@@ -1026,7 +1024,7 @@
   const Value *SV =3D cast<SrcValueSDNode>(Node->getOperand(2))->getValue(=
);
   DebugLoc dl =3D Node->getDebugLoc();
   SDValue VAList =3D DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
-                               MachinePointerInfo(SV), false, false, 0);
+                               MachinePointerInfo(SV), false, false, false=
, 0);
   // Increment the pointer, VAList, to the next vaarg
   SDValue NextPtr =3D DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
                                   DAG.getConstant(VT.getSizeInBits()/8,
@@ -1038,11 +1036,11 @@
   // f64 load.
   if (VT !=3D MVT::f64)
     return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
-                       false, false, 0);
+                       false, false, false, 0);
=20
   // Otherwise, load it as i64, then do a bitconvert.
   SDValue V =3D DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerI=
nfo(),
-                          false, false, 0);
+                          false, false, false, 0);
=20
   // Bit-Convert the value to f64.
   SDValue Ops[2] =3D {
@@ -1103,7 +1101,7 @@
       FrameAddr =3D DAG.getLoad(MVT::i32, dl,
                               Chain,
                               Ptr,
-                              MachinePointerInfo(), false, false, 0);
+                              MachinePointerInfo(), false, false, false, 0=
);
     }
   }
   return FrameAddr;
@@ -1135,7 +1133,7 @@
       RetAddr =3D DAG.getLoad(MVT::i32, dl,
                             Chain,
                             Ptr,
-                            MachinePointerInfo(), false, false, 0);
+                            MachinePointerInfo(), false, false, false, 0);
     }
   }
   return RetAddr;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcISelLowering.h
--- a/head/contrib/llvm/lib/Target/Sparc/SparcISelLowering.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcISelLowering.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,8 +15,8 @@
 #ifndef SPARC_ISELLOWERING_H
 #define SPARC_ISELLOWERING_H
=20
+#include "Sparc.h"
 #include "llvm/Target/TargetLowering.h"
-#include "Sparc.h"
=20
 namespace llvm {
   namespace SPISD {
@@ -50,7 +50,6 @@
     /// in Mask are known to be either zero or one and return them in the
     /// KnownZero/KnownOne bitsets.
     virtual void computeMaskedBitsForTargetNode(const SDValue Op,
-                                                const APInt &Mask,
                                                 APInt &KnownZero,
                                                 APInt &KnownOne,
                                                 const SelectionDAG &DAG,
@@ -77,9 +76,8 @@
                            SmallVectorImpl<SDValue> &InVals) const;
=20
     virtual SDValue
-      LowerCall(SDValue Chain, SDValue Callee,
-                CallingConv::ID CallConv, bool isVarArg,
-                bool &isTailCall,
+      LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
+                bool isVarArg, bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcInstrFormats.td
--- a/head/contrib/llvm/lib/Target/Sparc/SparcInstrFormats.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcInstrFormats.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- SparcInstrFormats.td - Sparc Instruction Formats ----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SparcInstrFormats.td - Sparc Instruction Formats ---*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 class InstSP<dag outs, dag ins, string asmstr, list<dag> pattern> : Instru=
ction {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcInstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SparcInstrInfo.cpp - Sparc Instruction Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- SparcInstrInfo.cpp - Sparc Instruction Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -79,7 +79,6 @@
 static SPCC::CondCodes GetOppositeBranchCondition(SPCC::CondCodes CC)
 {
   switch(CC) {
-  default: llvm_unreachable("Unknown condition code");
   case SPCC::ICC_NE:   return SPCC::ICC_E;
   case SPCC::ICC_E:    return SPCC::ICC_NE;
   case SPCC::ICC_G:    return SPCC::ICC_LE;
@@ -110,6 +109,18 @@
   case SPCC::FCC_NE:   return SPCC::FCC_E;
   case SPCC::FCC_E:    return SPCC::FCC_NE;
   }
+  llvm_unreachable("Invalid cond code");
+}
+
+MachineInstr *
+SparcInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
+                                         int FrameIx,
+                                         uint64_t Offset,
+                                         const MDNode *MDPtr,
+                                         DebugLoc dl) const {
+  MachineInstrBuilder MIB =3D BuildMI(MF, dl, get(SP::DBG_VALUE))
+    .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
+  return &*MIB;
 }
=20
=20
@@ -133,7 +144,7 @@
       break;
=20
     //Terminator is not a branch
-    if (!I->getDesc().isBranch())
+    if (!I->isBranch())
       return true;
=20
     //Handle Unconditional branches
@@ -195,7 +206,7 @@
           .addMBB(UnCondBrIter->getOperand(0).getMBB()).addImm(BranchCode);
         BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(SP::BA))
           .addMBB(TargetBB);
-        MBB.addSuccessor(TargetBB);
+
         OldInst->eraseFromParent();
         UnCondBrIter->eraseFromParent();
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcInstrInfo.h
--- a/head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SparcInstrInfo.h - Sparc Instruction Information ---------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- SparcInstrInfo.h - Sparc Instruction Information --------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,8 +14,8 @@
 #ifndef SPARCINSTRUCTIONINFO_H
 #define SPARCINSTRUCTIONINFO_H
=20
+#include "SparcRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "SparcRegisterInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "SparcGenInstrInfo.inc"
@@ -62,6 +62,13 @@
   virtual unsigned isStoreToStackSlot(const MachineInstr *MI,
                                       int &FrameIndex) const;
=20
+  /// emitFrameIndexDebugValue - Emit a target-dependent form of
+  /// DBG_VALUE encoding the address of a frame index.
+  virtual MachineInstr *emitFrameIndexDebugValue(MachineFunction &MF,
+                                                 int FrameIx,
+                                                 uint64_t Offset,
+                                                 const MDNode *MDPtr,
+                                                 DebugLoc dl) const;
=20
   virtual bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&T=
BB,
                              MachineBasicBlock *&FBB,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcInstrInfo.td
--- a/head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcInstrInfo.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- SparcInstrInfo.td - Target Description for Sparc Target -----=
-------=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SparcInstrInfo.td - Target Description for Sparc Target ----=
-------=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the Sparc instructions in TableGen format.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcMachineFunctionInfo.h
--- a/head/contrib/llvm/lib/Target/Sparc/SparcMachineFunctionInfo.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcMachineFunctionInfo.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 namespace llvm {
=20
   class SparcMachineFunctionInfo : public MachineFunctionInfo {
+    virtual void anchor();
   private:
     unsigned GlobalBaseReg;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcRegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SparcRegisterInfo.cpp - SPARC Register Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- SparcRegisterInfo.cpp - SPARC Register Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,15 +11,15 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "SparcRegisterInfo.h"
 #include "Sparc.h"
-#include "SparcRegisterInfo.h"
 #include "SparcSubtarget.h"
+#include "llvm/Type.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "llvm/Type.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/STLExtras.h"
=20
@@ -33,9 +33,9 @@
   : SparcGenRegisterInfo(SP::I7), Subtarget(st), TII(tii) {
 }
=20
-const unsigned* SparcRegisterInfo::getCalleeSavedRegs(const MachineFunctio=
n *MF)
+const uint16_t* SparcRegisterInfo::getCalleeSavedRegs(const MachineFunctio=
n *MF)
                                                                          c=
onst {
-  static const unsigned CalleeSavedRegs[] =3D { 0 };
+  static const uint16_t CalleeSavedRegs[] =3D { 0 };
   return CalleeSavedRegs;
 }
=20
@@ -118,10 +118,8 @@
=20
 unsigned SparcRegisterInfo::getEHExceptionRegister() const {
   llvm_unreachable("What is the exception register");
-  return 0;
 }
=20
 unsigned SparcRegisterInfo::getEHHandlerRegister() const {
   llvm_unreachable("What is the exception handler register");
-  return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcRegisterInfo.h
--- a/head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SparcRegisterInfo.h - Sparc Register Information Impl ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- SparcRegisterInfo.h - Sparc Register Information Impl ---*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -32,7 +32,7 @@
   SparcRegisterInfo(SparcSubtarget &st, const TargetInstrInfo &tii);
=20
   /// Code Generation virtual methods...
-  const unsigned *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
=20
   BitVector getReservedRegs(const MachineFunction &MF) const;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcRegisterInfo.td
--- a/head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcRegisterInfo.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- SparcRegisterInfo.td - Sparc Register defs ----------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- SparcRegisterInfo.td - Sparc Register defs ---------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -39,6 +39,7 @@
   let Num =3D num;
   let SubRegs =3D subregs;
   let SubRegIndices =3D [sub_even, sub_odd];
+  let CoveredBySubRegs =3D 1;
 }
=20
 // Control Registers
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcSubtarget.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcSubtarget.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcSubtarget.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- SparcSubtarget.cpp - SPARC Subtarget Information ------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- SparcSubtarget.cpp - SPARC Subtarget Information -----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -21,6 +21,8 @@
=20
 using namespace llvm;
=20
+void SparcSubtarget::anchor() { }
+
 SparcSubtarget::SparcSubtarget(const std::string &TT, const std::string &C=
PU,
                                const std::string &FS,  bool is64Bit) :
   SparcGenSubtargetInfo(TT, CPU, FS),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcSubtarget.h
--- a/head/contrib/llvm/lib/Target/Sparc/SparcSubtarget.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcSubtarget.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- SparcSubtarget.h - Define Subtarget for the SPARC ----=
*- C++ -*-=3D=3D=3D=3D//
+//=3D=3D=3D-- SparcSubtarget.h - Define Subtarget for the SPARC -------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -24,6 +24,7 @@
 class StringRef;
=20
 class SparcSubtarget : public SparcGenSubtargetInfo {
+  virtual void anchor();
   bool IsV9;
   bool V8DeprecatedInsts;
   bool IsVIS;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcTargetMachine.cpp
--- a/head/contrib/llvm/lib/Target/Sparc/SparcTargetMachine.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcTargetMachine.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -10,9 +10,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "SparcTargetMachine.h"
 #include "Sparc.h"
-#include "SparcTargetMachine.h"
 #include "llvm/PassManager.h"
+#include "llvm/CodeGen/Passes.h"
 #include "llvm/Support/TargetRegistry.h"
 using namespace llvm;
=20
@@ -24,43 +25,73 @@
=20
 /// SparcTargetMachine ctor - Create an ILP32 architecture model
 ///
-SparcTargetMachine::SparcTargetMachine(const Target &T, StringRef TT,=20
+SparcTargetMachine::SparcTargetMachine(const Target &T, StringRef TT,
                                        StringRef CPU, StringRef FS,
+                                       const TargetOptions &Options,
                                        Reloc::Model RM, CodeModel::Model C=
M,
+                                       CodeGenOpt::Level OL,
                                        bool is64bit)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     Subtarget(TT, CPU, FS, is64bit),
     DataLayout(Subtarget.getDataLayout()),
     TLInfo(*this), TSInfo(*this), InstrInfo(Subtarget),
     FrameLowering(Subtarget) {
 }
=20
-bool SparcTargetMachine::addInstSelector(PassManagerBase &PM,
-                                         CodeGenOpt::Level OptLevel) {
-  PM.add(createSparcISelDag(*this));
+namespace {
+/// Sparc Code Generator Pass Configuration Options.
+class SparcPassConfig : public TargetPassConfig {
+public:
+  SparcPassConfig(SparcTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  SparcTargetMachine &getSparcTargetMachine() const {
+    return getTM<SparcTargetMachine>();
+  }
+
+  virtual bool addInstSelector();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *SparcTargetMachine::createPassConfig(PassManagerBase &PM=
) {
+  return new SparcPassConfig(this, PM);
+}
+
+bool SparcPassConfig::addInstSelector() {
+  PM.add(createSparcISelDag(getSparcTargetMachine()));
   return false;
 }
=20
 /// addPreEmitPass - This pass may be implemented by targets that want to =
run
 /// passes immediately before machine code is emitted.  This should return
 /// true if -print-machineinstrs should print out the code after the passe=
s.
-bool SparcTargetMachine::addPreEmitPass(PassManagerBase &PM,
-                                        CodeGenOpt::Level OptLevel){
-  PM.add(createSparcFPMoverPass(*this));
-  PM.add(createSparcDelaySlotFillerPass(*this));
+bool SparcPassConfig::addPreEmitPass(){
+  PM.add(createSparcFPMoverPass(getSparcTargetMachine()));
+  PM.add(createSparcDelaySlotFillerPass(getSparcTargetMachine()));
   return true;
 }
=20
+void SparcV8TargetMachine::anchor() { }
+
 SparcV8TargetMachine::SparcV8TargetMachine(const Target &T,
                                            StringRef TT, StringRef CPU,
-                                           StringRef FS, Reloc::Model RM,
-                                           CodeModel::Model CM)
-  : SparcTargetMachine(T, TT, CPU, FS, RM, CM, false) {
+                                           StringRef FS,
+                                           const TargetOptions &Options,
+                                           Reloc::Model RM,
+                                           CodeModel::Model CM,
+                                           CodeGenOpt::Level OL)
+  : SparcTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {
 }
=20
-SparcV9TargetMachine::SparcV9TargetMachine(const Target &T,=20
+void SparcV9TargetMachine::anchor() { }
+
+SparcV9TargetMachine::SparcV9TargetMachine(const Target &T,
                                            StringRef TT,  StringRef CPU,
-                                           StringRef FS, Reloc::Model RM,
-                                           CodeModel::Model CM)
-  : SparcTargetMachine(T, TT, CPU, FS, RM, CM, true) {
+                                           StringRef FS,
+                                           const TargetOptions &Options,
+                                           Reloc::Model RM,
+                                           CodeModel::Model CM,
+                                           CodeGenOpt::Level OL)
+  : SparcTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/Sparc/Spa=
rcTargetMachine.h
--- a/head/contrib/llvm/lib/Target/Sparc/SparcTargetMachine.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/Sparc/SparcTargetMachine.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -34,8 +34,9 @@
   SparcFrameLowering FrameLowering;
 public:
   SparcTargetMachine(const Target &T, StringRef TT,
-                     StringRef CPU, StringRef FS,
-                     Reloc::Model RM, CodeModel::Model CM, bool is64bit);
+                     StringRef CPU, StringRef FS, const TargetOptions &Opt=
ions,
+                     Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL, bool is64bit);
=20
   virtual const SparcInstrInfo *getInstrInfo() const { return &InstrInfo; }
   virtual const TargetFrameLowering  *getFrameLowering() const {
@@ -54,26 +55,31 @@
   virtual const TargetData       *getTargetData() const { return &DataLayo=
ut; }
=20
   // Pass Pipeline Configuration
-  virtual bool addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptL=
evel);
-  virtual bool addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel);
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
 };
=20
 /// SparcV8TargetMachine - Sparc 32-bit target machine
 ///
 class SparcV8TargetMachine : public SparcTargetMachine {
+  virtual void anchor();
 public:
   SparcV8TargetMachine(const Target &T, StringRef TT,
                        StringRef CPU, StringRef FS,
-                       Reloc::Model RM, CodeModel::Model CM);
+                       const TargetOptions &Options,
+                       Reloc::Model RM, CodeModel::Model CM,
+                       CodeGenOpt::Level OL);
 };
=20
 /// SparcV9TargetMachine - Sparc 64-bit target machine
 ///
 class SparcV9TargetMachine : public SparcTargetMachine {
+  virtual void anchor();
 public:
   SparcV9TargetMachine(const Target &T, StringRef TT,
                        StringRef CPU, StringRef FS,
-                       Reloc::Model RM, CodeModel::Model CM);
+                       const TargetOptions &Options,
+                       Reloc::Model RM, CodeModel::Model CM,
+                       CodeGenOpt::Level OL);
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/TargetDat=
a.cpp
--- a/head/contrib/llvm/lib/Target/TargetData.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Target/TargetData.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -125,15 +125,15 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 /// getInt - Get an integer ignoring errors.
-static unsigned getInt(StringRef R) {
-  unsigned Result =3D 0;
+static int getInt(StringRef R) {
+  int Result =3D 0;
   R.getAsInteger(10, Result);
   return Result;
 }
=20
-void TargetData::init(StringRef Desc) {
+void TargetData::init() {
   initializeTargetDataPass(*PassRegistry::getPassRegistry());
- =20
+
   LayoutMap =3D 0;
   LittleEndian =3D false;
   PointerMemSize =3D 8;
@@ -147,11 +147,19 @@
   setAlignment(INTEGER_ALIGN,   2,  2, 16);  // i16
   setAlignment(INTEGER_ALIGN,   4,  4, 32);  // i32
   setAlignment(INTEGER_ALIGN,   4,  8, 64);  // i64
+  setAlignment(FLOAT_ALIGN,     2,  2, 16);  // half
   setAlignment(FLOAT_ALIGN,     4,  4, 32);  // float
   setAlignment(FLOAT_ALIGN,     8,  8, 64);  // double
+  setAlignment(FLOAT_ALIGN,    16, 16, 128); // ppcf128, quad, ...
   setAlignment(VECTOR_ALIGN,    8,  8, 64);  // v2i32, v1i64, ...
   setAlignment(VECTOR_ALIGN,   16, 16, 128); // v16i8, v8i16, v4i32, ...
   setAlignment(AGGREGATE_ALIGN, 0,  8,  0);  // struct
+}
+
+std::string TargetData::parseSpecifier(StringRef Desc, TargetData *td) {
+
+  if (td)
+    td->init();
=20
   while (!Desc.empty()) {
     std::pair<StringRef, StringRef> Split =3D Desc.split('-');
@@ -169,28 +177,54 @@
=20
     switch (Specifier[0]) {
     case 'E':
-      LittleEndian =3D false;
+      if (td)
+        td->LittleEndian =3D false;
       break;
     case 'e':
-      LittleEndian =3D true;
+      if (td)
+        td->LittleEndian =3D true;
       break;
-    case 'p':
+    case 'p': {
+      // Pointer size.
       Split =3D Token.split(':');
-      PointerMemSize =3D getInt(Split.first) / 8;
+      int PointerMemSizeBits =3D getInt(Split.first);
+      if (PointerMemSizeBits < 0 || PointerMemSizeBits % 8 !=3D 0)
+        return "invalid pointer size, must be a positive 8-bit multiple";
+      if (td)
+        td->PointerMemSize =3D PointerMemSizeBits / 8;
+
+      // Pointer ABI alignment.
       Split =3D Split.second.split(':');
-      PointerABIAlign =3D getInt(Split.first) / 8;
+      int PointerABIAlignBits =3D getInt(Split.first);
+      if (PointerABIAlignBits < 0 || PointerABIAlignBits % 8 !=3D 0) {
+        return "invalid pointer ABI alignment, "
+               "must be a positive 8-bit multiple";
+      }
+      if (td)
+        td->PointerABIAlign =3D PointerABIAlignBits / 8;
+
+      // Pointer preferred alignment.
       Split =3D Split.second.split(':');
-      PointerPrefAlign =3D getInt(Split.first) / 8;
-      if (PointerPrefAlign =3D=3D 0)
-        PointerPrefAlign =3D PointerABIAlign;
+      int PointerPrefAlignBits =3D getInt(Split.first);
+      if (PointerPrefAlignBits < 0 || PointerPrefAlignBits % 8 !=3D 0) {
+        return "invalid pointer preferred alignment, "
+               "must be a positive 8-bit multiple";
+      }
+      if (td) {
+        td->PointerPrefAlign =3D PointerPrefAlignBits / 8;
+        if (td->PointerPrefAlign =3D=3D 0)
+          td->PointerPrefAlign =3D td->PointerABIAlign;
+      }
       break;
+    }
     case 'i':
     case 'v':
     case 'f':
     case 'a':
     case 's': {
       AlignTypeEnum AlignType;
-      switch (Specifier[0]) {
+      char field =3D Specifier[0];
+      switch (field) {
       default:
       case 'i': AlignType =3D INTEGER_ALIGN; break;
       case 'v': AlignType =3D VECTOR_ALIGN; break;
@@ -198,37 +232,66 @@
       case 'a': AlignType =3D AGGREGATE_ALIGN; break;
       case 's': AlignType =3D STACK_ALIGN; break;
       }
-      unsigned Size =3D getInt(Specifier.substr(1));
+      int Size =3D getInt(Specifier.substr(1));
+      if (Size < 0) {
+        return std::string("invalid ") + field + "-size field, "
+               "must be positive";
+      }
+
       Split =3D Token.split(':');
-      unsigned ABIAlign =3D getInt(Split.first) / 8;
+      int ABIAlignBits =3D getInt(Split.first);
+      if (ABIAlignBits < 0 || ABIAlignBits % 8 !=3D 0) {
+        return std::string("invalid ") + field +"-abi-alignment field, "
+               "must be a positive 8-bit multiple";
+      }
+      unsigned ABIAlign =3D ABIAlignBits / 8;
=20
       Split =3D Split.second.split(':');
-      unsigned PrefAlign =3D getInt(Split.first) / 8;
+
+      int PrefAlignBits =3D getInt(Split.first);
+      if (PrefAlignBits < 0 || PrefAlignBits % 8 !=3D 0) {
+        return std::string("invalid ") + field +"-preferred-alignment fiel=
d, "
+               "must be a positive 8-bit multiple";
+      }
+      unsigned PrefAlign =3D PrefAlignBits / 8;
       if (PrefAlign =3D=3D 0)
         PrefAlign =3D ABIAlign;
-      setAlignment(AlignType, ABIAlign, PrefAlign, Size);
+     =20
+      if (td)
+        td->setAlignment(AlignType, ABIAlign, PrefAlign, Size);
       break;
     }
     case 'n':  // Native integer types.
       Specifier =3D Specifier.substr(1);
       do {
-        if (unsigned Width =3D getInt(Specifier))
-          LegalIntWidths.push_back(Width);
+        int Width =3D getInt(Specifier);
+        if (Width <=3D 0) {
+          return std::string("invalid native integer size \'") + Specifier=
.str() +
+                 "\', must be a positive integer.";
+        }
+        if (td && Width !=3D 0)
+          td->LegalIntWidths.push_back(Width);
         Split =3D Token.split(':');
         Specifier =3D Split.first;
         Token =3D Split.second;
       } while (!Specifier.empty() || !Token.empty());
       break;
-    case 'S': // Stack natural alignment.
-      StackNaturalAlign =3D getInt(Specifier.substr(1));
-      StackNaturalAlign /=3D 8;
-      // FIXME: Should we really be truncating these alingments and
-      // sizes silently?
+    case 'S': { // Stack natural alignment.
+      int StackNaturalAlignBits =3D getInt(Specifier.substr(1));
+      if (StackNaturalAlignBits < 0 || StackNaturalAlignBits % 8 !=3D 0) {
+        return "invalid natural stack alignment (S-field), "
+               "must be a positive 8-bit multiple";
+      }
+      if (td)
+        td->StackNaturalAlign =3D StackNaturalAlignBits / 8;
       break;
+    }
     default:
       break;
     }
   }
+
+  return "";
 }
=20
 /// Default ctor.
@@ -242,7 +305,9 @@
=20
 TargetData::TargetData(const Module *M)
   : ImmutablePass(ID) {
-  init(M->getDataLayout());
+  std::string errMsg =3D parseSpecifier(M->getDataLayout(), this);
+  assert(errMsg =3D=3D "" && "Module M has malformed target data layout st=
ring.");
+  (void)errMsg;
 }
=20
 void
@@ -308,7 +373,7 @@
       // If the alignment is not a power of 2, round up to the next power =
of 2.
       // This happens for non-power-of-2 length vectors.
       if (Align & (Align-1))
-        Align =3D llvm::NextPowerOf2(Align);
+        Align =3D NextPowerOf2(Align);
       return Align;
     }
   }
@@ -414,6 +479,8 @@
     return cast<IntegerType>(Ty)->getBitWidth();
   case Type::VoidTyID:
     return 8;
+  case Type::HalfTyID:
+    return 16;
   case Type::FloatTyID:
     return 32;
   case Type::DoubleTyID:
@@ -430,9 +497,7 @@
     return cast<VectorType>(Ty)->getBitWidth();
   default:
     llvm_unreachable("TargetData::getTypeSizeInBits(): Unsupported type");
-    break;
   }
-  return 0;
 }
=20
 /*!
@@ -471,6 +536,7 @@
   case Type::VoidTyID:
     AlignType =3D INTEGER_ALIGN;
     break;
+  case Type::HalfTyID:
   case Type::FloatTyID:
   case Type::DoubleTyID:
   // PPC_FP128TyID and FP128TyID have different data contents, but the
@@ -486,7 +552,6 @@
     break;
   default:
     llvm_unreachable("Bad type for getAlignment!!!");
-    break;
   }
=20
   return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/TargetIns=
trInfo.cpp
--- a/head/contrib/llvm/lib/Target/TargetInstrInfo.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/TargetInstrInfo.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -13,7 +13,6 @@
=20
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetRegisterInfo.h"
-#include "llvm/CodeGen/SelectionDAGNodes.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCInstrItineraries.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -73,23 +72,6 @@
   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
 }
=20
-int
-TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
-                                   SDNode *DefNode, unsigned DefIdx,
-                                   SDNode *UseNode, unsigned UseIdx) const=
 {
-  if (!ItinData || ItinData->isEmpty())
-    return -1;
-
-  if (!DefNode->isMachineOpcode())
-    return -1;
-
-  unsigned DefClass =3D get(DefNode->getMachineOpcode()).getSchedClass();
-  if (!UseNode->isMachineOpcode())
-    return ItinData->getOperandCycle(DefClass, DefIdx);
-  unsigned UseClass =3D get(UseNode->getMachineOpcode()).getSchedClass();
-  return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
-}
-
 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
                                      const MachineInstr *MI,
                                      unsigned *PredCost) const {
@@ -99,17 +81,6 @@
   return ItinData->getStageLatency(MI->getDesc().getSchedClass());
 }
=20
-int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
-                                     SDNode *N) const {
-  if (!ItinData || ItinData->isEmpty())
-    return 1;
-
-  if (!N->isMachineOpcode())
-    return 1;
-
-  return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClas=
s());
-}
-
 bool TargetInstrInfo::hasLowDefLatency(const InstrItineraryData *ItinData,
                                        const MachineInstr *DefMI,
                                        unsigned DefIdx) const {
@@ -129,19 +100,6 @@
 }
=20
=20
-bool TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) con=
st {
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.isTerminator()) return false;
-
-  // Conditional branch is a special case.
-  if (MCID.isBranch() && !MCID.isBarrier())
-    return true;
-  if (!MCID.isPredicable())
-    return true;
-  return !isPredicated(MI);
-}
-
-
 /// Measure the specified inline asm to determine an approximation of its
 /// length.
 /// Comments (which run till the next SeparatorString or newline) do not
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/TargetLib=
raryInfo.cpp
--- a/head/contrib/llvm/lib/Target/TargetLibraryInfo.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/TargetLibraryInfo.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -20,6 +20,106 @@
                 "Target Library Information", false, true)
 char TargetLibraryInfo::ID =3D 0;
=20
+void TargetLibraryInfo::anchor() { }
+
+const char* TargetLibraryInfo::StandardNames[LibFunc::NumLibFuncs] =3D
+  {
+    "acos",
+    "acosl",
+    "acosf",
+    "asin",
+    "asinl",
+    "asinf",
+    "atan",
+    "atanl",
+    "atanf",
+    "atan2",
+    "atan2l",
+    "atan2f",
+    "ceil",
+    "ceill",
+    "ceilf",
+    "copysign",
+    "copysignf",
+    "copysignl",
+    "cos",
+    "cosl",
+    "cosf",
+    "cosh",
+    "coshl",
+    "coshf",
+    "exp",
+    "expl",
+    "expf",
+    "exp2",
+    "exp2l",
+    "exp2f",
+    "expm1",
+    "expm1l",
+    "expl1f",
+    "fabs",
+    "fabsl",
+    "fabsf",
+    "floor",
+    "floorl",
+    "floorf",
+    "fiprintf",
+    "fmod",
+    "fmodl",
+    "fmodf",
+    "fputs",
+    "fwrite",
+    "iprintf",
+    "log",
+    "logl",
+    "logf",
+    "log2",
+    "log2l",
+    "log2f",
+    "log10",
+    "log10l",
+    "log10f",
+    "log1p",
+    "log1pl",
+    "log1pf",
+    "memcpy",
+    "memmove",
+    "memset",
+    "memset_pattern16",
+    "nearbyint",
+    "nearbyintf",
+    "nearbyintl",
+    "pow",
+    "powf",
+    "powl",
+    "rint",
+    "rintf",
+    "rintl",
+    "sin",
+    "sinl",
+    "sinf",
+    "sinh",
+    "sinhl",
+    "sinhf",
+    "siprintf",
+    "sqrt",
+    "sqrtl",
+    "sqrtf",
+    "tan",
+    "tanl",
+    "tanf",
+    "tanh",
+    "tanhl",
+    "tanhf",
+    "trunc",
+    "truncf",
+    "truncl",
+    "__cxa_atexit",
+    "__cxa_guard_abort",
+    "__cxa_guard_acquire",
+    "__cxa_guard_release"
+  };
+
 /// initialize - Initialize the set of available library functions based o=
n the
 /// specified target triple.  This should be carefully written so that a m=
issing
 /// target triple gets a sane set of defaults.
@@ -38,6 +138,17 @@
     TLI.setUnavailable(LibFunc::memset_pattern16);
   }
=20
+  if (T.isMacOSX() && T.getArch() =3D=3D Triple::x86 &&
+      !T.isMacOSXVersionLT(10, 7)) {
+    // x86-32 OSX has a scheme where fwrite and fputs (and some other func=
tions
+    // we don't care about) have two versions; on recent OSX, the one we w=
ant
+    // has a $UNIX2003 suffix. The two implementations are identical except
+    // for the return value in some edge cases.  However, we don't want to
+    // generate code that depends on the old symbols.
+    TLI.setAvailableWithName(LibFunc::fwrite, "fwrite$UNIX2003");
+    TLI.setAvailableWithName(LibFunc::fputs, "fputs$UNIX2003");
+  }
+
   // iprintf and friends are only available on XCore and TCE.
   if (T.getArch() !=3D Triple::xcore && T.getArch() !=3D Triple::tce) {
     TLI.setUnavailable(LibFunc::iprintf);
@@ -64,6 +175,7 @@
 TargetLibraryInfo::TargetLibraryInfo(const TargetLibraryInfo &TLI)
   : ImmutablePass(ID) {
   memcpy(AvailableArray, TLI.AvailableArray, sizeof(AvailableArray));
+  CustomNames =3D TLI.CustomNames;
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/TargetLow=
eringObjectFile.cpp
--- a/head/contrib/llvm/lib/Target/TargetLoweringObjectFile.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/TargetLoweringObjectFile.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -28,7 +28,6 @@
 #include "llvm/Support/Dwarf.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/SmallString.h"
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -48,7 +47,7 @@
 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
 }
=20
-static bool isSuitableForBSS(const GlobalVariable *GV) {
+static bool isSuitableForBSS(const GlobalVariable *GV, bool NoZerosInBSS) {
   const Constant *C =3D GV->getInitializer();
=20
   // Must have zero initializer.
@@ -73,31 +72,27 @@
=20
 /// IsNullTerminatedString - Return true if the specified constant (which =
is
 /// known to have a type that is an array of 1/2/4 byte elements) ends wit=
h a
-/// nul value and contains no other nuls in it.
+/// nul value and contains no other nuls in it.  Note that this is more ge=
neral
+/// than ConstantDataSequential::isString because we allow 2 & 4 byte stri=
ngs.
 static bool IsNullTerminatedString(const Constant *C) {
-  ArrayType *ATy =3D cast<ArrayType>(C->getType());
-
-  // First check: is we have constant array of i8 terminated with zero
-  if (const ConstantArray *CVA =3D dyn_cast<ConstantArray>(C)) {
-    if (ATy->getNumElements() =3D=3D 0) return false;
-
-    ConstantInt *Null =3D
-      dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
-    if (Null =3D=3D 0 || !Null->isZero())
+  // First check: is we have constant array terminated with zero
+  if (const ConstantDataSequential *CDS =3D dyn_cast<ConstantDataSequentia=
l>(C)) {
+    unsigned NumElts =3D CDS->getNumElements();
+    assert(NumElts !=3D 0 && "Can't have an empty CDS");
+   =20
+    if (CDS->getElementAsInteger(NumElts-1) !=3D 0)
       return false; // Not null terminated.
-
+   =20
     // Verify that the null doesn't occur anywhere else in the string.
-    for (unsigned i =3D 0, e =3D ATy->getNumElements()-1; i !=3D e; ++i)
-      // Reject constantexpr elements etc.
-      if (!isa<ConstantInt>(CVA->getOperand(i)) ||
-          CVA->getOperand(i) =3D=3D Null)
+    for (unsigned i =3D 0; i !=3D NumElts-1; ++i)
+      if (CDS->getElementAsInteger(i) =3D=3D 0)
         return false;
     return true;
   }
=20
   // Another possibility: [1 x i8] zeroinitializer
   if (isa<ConstantAggregateZero>(C))
-    return ATy->getNumElements() =3D=3D 1;
+    return cast<ArrayType>(C->getType())->getNumElements() =3D=3D 1;
=20
   return false;
 }
@@ -133,7 +128,7 @@
=20
   // Handle thread-local data first.
   if (GVar->isThreadLocal()) {
-    if (isSuitableForBSS(GVar))
+    if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS))
       return SectionKind::getThreadBSS();
     return SectionKind::getThreadData();
   }
@@ -143,7 +138,7 @@
     return SectionKind::getCommon();
=20
   // Variable can be easily put to BSS section.
-  if (isSuitableForBSS(GVar)) {
+  if (isSuitableForBSS(GVar, TM.Options.NoZerosInBSS)) {
     if (GVar->hasLocalLinkage())
       return SectionKind::getBSSLocal();
     else if (GVar->hasExternalLinkage())
@@ -160,7 +155,6 @@
     // relocation, then we may have to drop this into a wriable data secti=
on
     // even though it is marked const.
     switch (C->getRelocationInfo()) {
-    default: assert(0 && "unknown relocation info kind");
     case Constant::NoRelocation:
       // If the global is required to have a unique address, it can't be p=
ut
       // into a mergable section: just drop it into the general read-only
@@ -234,7 +228,6 @@
     return SectionKind::getDataNoRel();
=20
   switch (C->getRelocationInfo()) {
-  default: assert(0 && "unknown relocation info kind");
   case Constant::NoRelocation:
     return SectionKind::getDataNoRel();
   case Constant::LocalRelocation:
@@ -242,6 +235,7 @@
   case Constant::GlobalRelocations:
     return SectionKind::getDataRel();
   }
+  llvm_unreachable("Invalid relocation");
 }
=20
 /// SectionForGlobal - This method computes the appropriate section to emit
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/TargetMac=
hine.cpp
--- a/head/contrib/llvm/lib/Target/TargetMachine.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/Target/TargetMachine.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -11,11 +11,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "llvm/CodeGen/MachineFunction.h"
-#include "llvm/CodeGen/MachineFrameInfo.h"
+#include "llvm/GlobalValue.h"
 #include "llvm/MC/MCAsmInfo.h"
+#include "llvm/MC/MCCodeGenInfo.h"
 #include "llvm/Target/TargetMachine.h"
-#include "llvm/Target/TargetOptions.h"
 #include "llvm/Support/CommandLine.h"
 using namespace llvm;
=20
@@ -24,153 +23,10 @@
 //
=20
 namespace llvm {
-  bool LessPreciseFPMADOption;
-  bool PrintMachineCode;
-  bool NoFramePointerElim;
-  bool NoFramePointerElimNonLeaf;
-  bool NoExcessFPPrecision;
-  bool UnsafeFPMath;
-  bool NoInfsFPMath;
-  bool NoNaNsFPMath;
-  bool HonorSignDependentRoundingFPMathOption;
-  bool UseSoftFloat;
-  FloatABI::ABIType FloatABIType;
-  bool NoImplicitFloat;
-  bool NoZerosInBSS;
-  bool JITExceptionHandling;
-  bool JITEmitDebugInfo;
-  bool JITEmitDebugInfoToDisk;
-  bool GuaranteedTailCallOpt;
-  unsigned StackAlignmentOverride;
-  bool RealignStack;
-  bool DisableJumpTables;
-  bool StrongPHIElim;
   bool HasDivModLibcall;
   bool AsmVerbosityDefault(false);
-  bool EnableSegmentedStacks;
 }
=20
-static cl::opt<bool, true>
-PrintCode("print-machineinstrs",
-  cl::desc("Print generated machine code"),
-  cl::location(PrintMachineCode), cl::init(false));
-static cl::opt<bool, true>
-DisableFPElim("disable-fp-elim",
-  cl::desc("Disable frame pointer elimination optimization"),
-  cl::location(NoFramePointerElim),
-  cl::init(false));
-static cl::opt<bool, true>
-DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
-  cl::desc("Disable frame pointer elimination optimization for non-leaf fu=
ncs"),
-  cl::location(NoFramePointerElimNonLeaf),
-  cl::init(false));
-static cl::opt<bool, true>
-DisableExcessPrecision("disable-excess-fp-precision",
-  cl::desc("Disable optimizations that may increase FP precision"),
-  cl::location(NoExcessFPPrecision),
-  cl::init(false));
-static cl::opt<bool, true>
-EnableFPMAD("enable-fp-mad",
-  cl::desc("Enable less precise MAD instructions to be generated"),
-  cl::location(LessPreciseFPMADOption),
-  cl::init(false));
-static cl::opt<bool, true>
-EnableUnsafeFPMath("enable-unsafe-fp-math",
-  cl::desc("Enable optimizations that may decrease FP precision"),
-  cl::location(UnsafeFPMath),
-  cl::init(false));
-static cl::opt<bool, true>
-EnableNoInfsFPMath("enable-no-infs-fp-math",
-  cl::desc("Enable FP math optimizations that assume no +-Infs"),
-  cl::location(NoInfsFPMath),
-  cl::init(false));
-static cl::opt<bool, true>
-EnableNoNaNsFPMath("enable-no-nans-fp-math",
-  cl::desc("Enable FP math optimizations that assume no NaNs"),
-  cl::location(NoNaNsFPMath),
-  cl::init(false));
-static cl::opt<bool, true>
-EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-=
math",
-  cl::Hidden,
-  cl::desc("Force codegen to assume rounding mode can change dynamically"),
-  cl::location(HonorSignDependentRoundingFPMathOption),
-  cl::init(false));
-static cl::opt<bool, true>
-GenerateSoftFloatCalls("soft-float",
-  cl::desc("Generate software floating point library calls"),
-  cl::location(UseSoftFloat),
-  cl::init(false));
-static cl::opt<llvm::FloatABI::ABIType, true>
-FloatABIForCalls("float-abi",
-  cl::desc("Choose float ABI type"),
-  cl::location(FloatABIType),
-  cl::init(FloatABI::Default),
-  cl::values(
-    clEnumValN(FloatABI::Default, "default",
-               "Target default float ABI type"),
-    clEnumValN(FloatABI::Soft, "soft",
-               "Soft float ABI (implied by -soft-float)"),
-    clEnumValN(FloatABI::Hard, "hard",
-               "Hard float ABI (uses FP registers)"),
-    clEnumValEnd));
-static cl::opt<bool, true>
-DontPlaceZerosInBSS("nozero-initialized-in-bss",
-  cl::desc("Don't place zero-initialized symbols into bss section"),
-  cl::location(NoZerosInBSS),
-  cl::init(false));
-static cl::opt<bool, true>
-EnableJITExceptionHandling("jit-enable-eh",
-  cl::desc("Emit exception handling information"),
-  cl::location(JITExceptionHandling),
-  cl::init(false));
-// In debug builds, make this default to true.
-#ifdef NDEBUG
-#define EMIT_DEBUG false
-#else
-#define EMIT_DEBUG true
-#endif
-static cl::opt<bool, true>
-EmitJitDebugInfo("jit-emit-debug",
-  cl::desc("Emit debug information to debugger"),
-  cl::location(JITEmitDebugInfo),
-  cl::init(EMIT_DEBUG));
-#undef EMIT_DEBUG
-static cl::opt<bool, true>
-EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
-  cl::Hidden,
-  cl::desc("Emit debug info objfiles to disk"),
-  cl::location(JITEmitDebugInfoToDisk),
-  cl::init(false));
-
-static cl::opt<bool, true>
-EnableGuaranteedTailCallOpt("tailcallopt",
-  cl::desc("Turn fastcc calls into tail calls by (potentially) changing AB=
I."),
-  cl::location(GuaranteedTailCallOpt),
-  cl::init(false));
-static cl::opt<unsigned, true>
-OverrideStackAlignment("stack-alignment",
-  cl::desc("Override default stack alignment"),
-  cl::location(StackAlignmentOverride),
-  cl::init(0));
-static cl::opt<bool, true>
-EnableRealignStack("realign-stack",
-  cl::desc("Realign stack if needed"),
-  cl::location(RealignStack),
-  cl::init(true));
-static cl::opt<bool, true>
-DisableSwitchTables(cl::Hidden, "disable-jump-tables",=20
-  cl::desc("Do not generate jump tables."),
-  cl::location(DisableJumpTables),
-  cl::init(false));
-static cl::opt<bool, true>
-EnableStrongPHIElim(cl::Hidden, "strong-phi-elim",
-  cl::desc("Use strong PHI elimination."),
-  cl::location(StrongPHIElim),
-  cl::init(false));
-static cl::opt<std::string>
-TrapFuncName("trap-func", cl::Hidden,
-  cl::desc("Emit a call to trap function rather than a trap instruction"),
-  cl::init(""));
 static cl::opt<bool>
 DataSections("fdata-sections",
   cl::desc("Emit data into separate sections"),
@@ -179,29 +35,23 @@
 FunctionSections("ffunction-sections",
   cl::desc("Emit functions into separate sections"),
   cl::init(false));
-static cl::opt<bool, true>
-SegmentedStacks("segmented-stacks",
-  cl::desc("Use segmented stacks if possible."),
-  cl::location(EnableSegmentedStacks),
-  cl::init(false));
-                        =20
+
 //------------------------------------------------------------------------=
---
 // TargetMachine Class
 //
=20
 TargetMachine::TargetMachine(const Target &T,
-                             StringRef TT, StringRef CPU, StringRef FS)
+                             StringRef TT, StringRef CPU, StringRef FS,
+                             const TargetOptions &Options)
   : TheTarget(T), TargetTriple(TT), TargetCPU(CPU), TargetFS(FS),
     CodeGenInfo(0), AsmInfo(0),
     MCRelaxAll(false),
     MCNoExecStack(false),
     MCSaveTempLabels(false),
     MCUseLoc(true),
-    MCUseCFI(true) {
-  // Typically it will be subtargets that will adjust FloatABIType from De=
fault
-  // to Soft or Hard.
-  if (UseSoftFloat)
-    FloatABIType =3D FloatABI::Soft;
+    MCUseCFI(true),
+    MCUseDwarfDirectory(false),
+    Options(Options) {
 }
=20
 TargetMachine::~TargetMachine() {
@@ -225,6 +75,35 @@
   return CodeGenInfo->getCodeModel();
 }
=20
+TLSModel::Model TargetMachine::getTLSModel(const GlobalValue *GV) const {
+  bool isLocal =3D GV->hasLocalLinkage();
+  bool isDeclaration =3D GV->isDeclaration();
+  // FIXME: what should we do for protected and internal visibility?
+  // For variables, is internal different from hidden?
+  bool isHidden =3D GV->hasHiddenVisibility();
+
+  if (getRelocationModel() =3D=3D Reloc::PIC_ &&
+      !Options.PositionIndependentExecutable) {
+    if (isLocal || isHidden)
+      return TLSModel::LocalDynamic;
+    else
+      return TLSModel::GeneralDynamic;
+  } else {
+    if (!isDeclaration || isHidden)
+      return TLSModel::LocalExec;
+    else
+      return TLSModel::InitialExec;
+  }
+}
+
+/// getOptLevel - Returns the optimization level: None, Less,
+/// Default, or Aggressive.
+CodeGenOpt::Level TargetMachine::getOptLevel() const {
+  if (!CodeGenInfo)
+    return CodeGenOpt::Default;
+  return CodeGenInfo->getOptLevel();
+}
+
 bool TargetMachine::getAsmVerbosityDefault() {
   return AsmVerbosityDefault;
 }
@@ -249,36 +128,3 @@
   DataSections =3D V;
 }
=20
-namespace llvm {
-  /// DisableFramePointerElim - This returns true if frame pointer elimina=
tion
-  /// optimization should be disabled for the given machine function.
-  bool DisableFramePointerElim(const MachineFunction &MF) {
-    // Check to see if we should eliminate non-leaf frame pointers and then
-    // check to see if we should eliminate all frame pointers.
-    if (NoFramePointerElimNonLeaf && !NoFramePointerElim) {
-      const MachineFrameInfo *MFI =3D MF.getFrameInfo();
-      return MFI->hasCalls();
-    }
-
-    return NoFramePointerElim;
-  }
-
-  /// LessPreciseFPMAD - This flag return true when -enable-fp-mad option
-  /// is specified on the command line.  When this flag is off(default), t=
he
-  /// code generator is not allowed to generate mad (multiply add) if the
-  /// result is "less precise" than doing those operations individually.
-  bool LessPreciseFPMAD() { return UnsafeFPMath || LessPreciseFPMADOption;=
 }
-
-  /// HonorSignDependentRoundingFPMath - Return true if the codegen must a=
ssume
-  /// that the rounding mode of the FPU can change from its default.
-  bool HonorSignDependentRoundingFPMath() {
-    return !UnsafeFPMath && HonorSignDependentRoundingFPMathOption;
-  }
-
-  /// getTrapFunctionName - If this returns a non-empty string, this means=
 isel
-  /// should lower Intrinsic::trap to a call to the specified function name
-  /// instead of an ISD::TRAP node.
-  StringRef getTrapFunctionName() {
-    return TrapFuncName;
-  }
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/TargetReg=
isterInfo.cpp
--- a/head/contrib/llvm/lib/Target/TargetRegisterInfo.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/TargetRegisterInfo.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -13,8 +13,6 @@
=20
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetRegisterInfo.h"
-#include "llvm/CodeGen/MachineFunction.h"
-#include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/Support/raw_ostream.h"
=20
@@ -73,7 +71,7 @@
 /// registers for the specific register class.
 static void getAllocatableSetForRC(const MachineFunction &MF,
                                    const TargetRegisterClass *RC, BitVecto=
r &R){
-  ArrayRef<unsigned> Order =3D RC->getRawAllocationOrder(MF);
+  ArrayRef<uint16_t> Order =3D RC->getRawAllocationOrder(MF);
   for (unsigned i =3D 0; i !=3D Order.size(); ++i)
     R.set(Order[i]);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/AsmPa=
rser/X86AsmLexer.cpp
--- a/head/contrib/llvm/lib/Target/X86/AsmParser/X86AsmLexer.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/AsmParser/X86AsmLexer.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -14,7 +14,6 @@
 #include "llvm/MC/MCTargetAsmLexer.h"
 #include "llvm/Support/TargetRegistry.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
=20
 using namespace llvm;
=20
@@ -144,11 +143,7 @@
     SetError(Lexer->getErrLoc(), Lexer->getErr());
     return lexedToken;
   case AsmToken::Identifier: {
-    std::string upperCase =3D lexedToken.getString().str();
-    std::string lowerCase =3D LowercaseString(upperCase);
-    StringRef lowerRef(lowerCase);
-   =20
-    unsigned regID =3D MatchRegisterName(lowerRef);
+    unsigned regID =3D MatchRegisterName(lexedToken.getString().lower());
    =20
     if (regID)
       return AsmToken(AsmToken::Register,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/AsmPa=
rser/X86AsmParser.cpp
--- a/head/contrib/llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/AsmParser/X86AsmParser.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -17,10 +17,8 @@
 #include "llvm/MC/MCParser/MCAsmLexer.h"
 #include "llvm/MC/MCParser/MCAsmParser.h"
 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
-#include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/SourceMgr.h"
@@ -32,33 +30,47 @@
 namespace {
 struct X86Operand;
=20
-class X86ATTAsmParser : public MCTargetAsmParser {
+class X86AsmParser : public MCTargetAsmParser {
   MCSubtargetInfo &STI;
   MCAsmParser &Parser;
-
 private:
   MCAsmParser &getParser() const { return Parser; }
=20
   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
=20
-  bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
+  bool Error(SMLoc L, const Twine &Msg,
+             ArrayRef<SMRange> Ranges =3D ArrayRef<SMRange>()) {
+    return Parser.Error(L, Msg, Ranges);
+  }
+
+  X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
+    Error(Loc, Msg);
+    return 0;
+  }
=20
   X86Operand *ParseOperand();
+  X86Operand *ParseATTOperand();
+  X86Operand *ParseIntelOperand();
+  X86Operand *ParseIntelMemOperand();
+  X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
   X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
=20
   bool ParseDirectiveWord(unsigned Size, SMLoc L);
   bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
=20
+  bool processInstruction(MCInst &Inst,
+                          const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
+
   bool MatchAndEmitInstruction(SMLoc IDLoc,
                                SmallVectorImpl<MCParsedAsmOperand*> &Opera=
nds,
                                MCStreamer &Out);
=20
   /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
-  /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
+  /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
   bool isSrcOp(X86Operand &Op);
=20
-  /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
-  /// or %es:(%edi) in 32bit mode.
+  /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
+  /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
   bool isDstOp(X86Operand &Op);
=20
   bool is64BitMode() const {
@@ -79,7 +91,7 @@
   /// }
=20
 public:
-  X86ATTAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
+  X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
     : MCTargetAsmParser(), STI(sti), Parser(parser) {
=20
     // Initialize the set of available features.
@@ -91,6 +103,10 @@
                                 SmallVectorImpl<MCParsedAsmOperand*> &Oper=
ands);
=20
   virtual bool ParseDirective(AsmToken DirectiveID);
+
+  bool isParsingIntelSyntax() {
+    return getParser().getAssemblerDialect();
+  }
 };
 } // end anonymous namespace
=20
@@ -101,6 +117,31 @@
=20
 /// }
=20
+static  bool isImmSExti16i8Value(uint64_t Value) {
+  return ((                                  Value <=3D 0x000000000000007F=
ULL)||
+          (0x000000000000FF80ULL <=3D Value && Value <=3D 0x000000000000FF=
FFULL)||
+          (0xFFFFFFFFFFFFFF80ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFFFF=
FFULL));
+}
+
+static bool isImmSExti32i8Value(uint64_t Value) {
+  return ((                                  Value <=3D 0x000000000000007F=
ULL)||
+          (0x00000000FFFFFF80ULL <=3D Value && Value <=3D 0x00000000FFFFFF=
FFULL)||
+          (0xFFFFFFFFFFFFFF80ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFFFF=
FFULL));
+}
+
+static bool isImmZExtu32u8Value(uint64_t Value) {
+    return (Value <=3D 0x00000000000000FFULL);
+}
+
+static bool isImmSExti64i8Value(uint64_t Value) {
+  return ((                                  Value <=3D 0x000000000000007F=
ULL)||
+	  (0xFFFFFFFFFFFFFF80ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFFFFFFULL));
+}
+
+static bool isImmSExti64i32Value(uint64_t Value) {
+  return ((                                  Value <=3D 0x000000007FFFFFFF=
ULL)||
+	  (0xFFFFFFFF80000000ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFFFFFFULL));
+}
 namespace {
=20
 /// X86Operand - Instances of this class represent a parsed X86 machine
@@ -135,6 +176,7 @@
       unsigned BaseReg;
       unsigned IndexReg;
       unsigned Scale;
+      unsigned Size;
     } Mem;
   };
=20
@@ -145,6 +187,8 @@
   SMLoc getStartLoc() const { return StartLoc; }
   /// getEndLoc - Get the location of the last token of this operand.
   SMLoc getEndLoc() const { return EndLoc; }
+ =20
+  SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
=20
   virtual void print(raw_ostream &OS) const {}
=20
@@ -205,10 +249,7 @@
=20
     // Otherwise, check the value is in a range that makes sense for this
     // extension.
-    uint64_t Value =3D CE->getValue();
-    return ((                                  Value <=3D 0x00000000000000=
7FULL)||
-            (0x000000000000FF80ULL <=3D Value && Value <=3D 0x000000000000=
FFFFULL)||
-            (0xFFFFFFFFFFFFFF80ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFF=
FFFFULL));
+    return isImmSExti16i8Value(CE->getValue());
   }
   bool isImmSExti32i8() const {
     if (!isImm())
@@ -222,10 +263,7 @@
=20
     // Otherwise, check the value is in a range that makes sense for this
     // extension.
-    uint64_t Value =3D CE->getValue();
-    return ((                                  Value <=3D 0x00000000000000=
7FULL)||
-            (0x00000000FFFFFF80ULL <=3D Value && Value <=3D 0x00000000FFFF=
FFFFULL)||
-            (0xFFFFFFFFFFFFFF80ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFF=
FFFFULL));
+    return isImmSExti32i8Value(CE->getValue());
   }
   bool isImmZExtu32u8() const {
     if (!isImm())
@@ -239,8 +277,7 @@
=20
     // Otherwise, check the value is in a range that makes sense for this
     // extension.
-    uint64_t Value =3D CE->getValue();
-    return (Value <=3D 0x00000000000000FFULL);
+    return isImmZExtu32u8Value(CE->getValue());
   }
   bool isImmSExti64i8() const {
     if (!isImm())
@@ -254,9 +291,7 @@
=20
     // Otherwise, check the value is in a range that makes sense for this
     // extension.
-    uint64_t Value =3D CE->getValue();
-    return ((                                  Value <=3D 0x00000000000000=
7FULL)||
-            (0xFFFFFFFFFFFFFF80ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFF=
FFFFULL));
+    return isImmSExti64i8Value(CE->getValue());
   }
   bool isImmSExti64i32() const {
     if (!isImm())
@@ -270,12 +305,31 @@
=20
     // Otherwise, check the value is in a range that makes sense for this
     // extension.
-    uint64_t Value =3D CE->getValue();
-    return ((                                  Value <=3D 0x000000007FFFFF=
FFULL)||
-            (0xFFFFFFFF80000000ULL <=3D Value && Value <=3D 0xFFFFFFFFFFFF=
FFFFULL));
+    return isImmSExti64i32Value(CE->getValue());
   }
=20
   bool isMem() const { return Kind =3D=3D Memory; }
+  bool isMem8() const {=20
+    return Kind =3D=3D Memory && (!Mem.Size || Mem.Size =3D=3D 8);
+  }
+  bool isMem16() const {=20
+    return Kind =3D=3D Memory && (!Mem.Size || Mem.Size =3D=3D 16);
+  }
+  bool isMem32() const {=20
+    return Kind =3D=3D Memory && (!Mem.Size || Mem.Size =3D=3D 32);
+  }
+  bool isMem64() const {=20
+    return Kind =3D=3D Memory && (!Mem.Size || Mem.Size =3D=3D 64);
+  }
+  bool isMem80() const {=20
+    return Kind =3D=3D Memory && (!Mem.Size || Mem.Size =3D=3D 80);
+  }
+  bool isMem128() const {=20
+    return Kind =3D=3D Memory && (!Mem.Size || Mem.Size =3D=3D 128);
+  }
+  bool isMem256() const {=20
+    return Kind =3D=3D Memory && (!Mem.Size || Mem.Size =3D=3D 256);
+  }
=20
   bool isAbsMem() const {
     return Kind =3D=3D Memory && !getMemSegReg() && !getMemBaseReg() &&
@@ -302,6 +356,28 @@
     addExpr(Inst, getImm());
   }
=20
+  void addMem8Operands(MCInst &Inst, unsigned N) const {=20
+    addMemOperands(Inst, N);=20
+  }
+  void addMem16Operands(MCInst &Inst, unsigned N) const {=20
+    addMemOperands(Inst, N);=20
+  }
+  void addMem32Operands(MCInst &Inst, unsigned N) const {=20
+    addMemOperands(Inst, N);=20
+  }
+  void addMem64Operands(MCInst &Inst, unsigned N) const {=20
+    addMemOperands(Inst, N);=20
+  }
+  void addMem80Operands(MCInst &Inst, unsigned N) const {=20
+    addMemOperands(Inst, N);=20
+  }
+  void addMem128Operands(MCInst &Inst, unsigned N) const {=20
+    addMemOperands(Inst, N);=20
+  }
+  void addMem256Operands(MCInst &Inst, unsigned N) const {=20
+    addMemOperands(Inst, N);=20
+  }
+
   void addMemOperands(MCInst &Inst, unsigned N) const {
     assert((N =3D=3D 5) && "Invalid number of operands!");
     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
@@ -313,11 +389,16 @@
=20
   void addAbsMemOperands(MCInst &Inst, unsigned N) const {
     assert((N =3D=3D 1) && "Invalid number of operands!");
-    Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
+    // Add as immediates when possible.
+    if (const MCConstantExpr *CE =3D dyn_cast<MCConstantExpr>(getMemDisp()=
))
+      Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
+    else
+      Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
   }
=20
   static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
-    X86Operand *Res =3D new X86Operand(Token, Loc, Loc);
+    SMLoc EndLoc =3D SMLoc::getFromPointer(Loc.getPointer() + Str.size() -=
 1);
+    X86Operand *Res =3D new X86Operand(Token, Loc, EndLoc);
     Res->Tok.Data =3D Str.data();
     Res->Tok.Length =3D Str.size();
     return Res;
@@ -337,20 +418,22 @@
=20
   /// Create an absolute memory operand.
   static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
-                               SMLoc EndLoc) {
+                               SMLoc EndLoc, unsigned Size =3D 0) {
     X86Operand *Res =3D new X86Operand(Memory, StartLoc, EndLoc);
     Res->Mem.SegReg   =3D 0;
     Res->Mem.Disp     =3D Disp;
     Res->Mem.BaseReg  =3D 0;
     Res->Mem.IndexReg =3D 0;
     Res->Mem.Scale    =3D 1;
+    Res->Mem.Size     =3D Size;
     return Res;
   }
=20
   /// Create a generalized memory operand.
   static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
                                unsigned BaseReg, unsigned IndexReg,
-                               unsigned Scale, SMLoc StartLoc, SMLoc EndLo=
c) {
+                               unsigned Scale, SMLoc StartLoc, SMLoc EndLo=
c,
+                               unsigned Size =3D 0) {
     // We should never just have a displacement, that should be parsed as =
an
     // absolute memory operand.
     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
@@ -364,13 +447,14 @@
     Res->Mem.BaseReg  =3D BaseReg;
     Res->Mem.IndexReg =3D IndexReg;
     Res->Mem.Scale    =3D Scale;
+    Res->Mem.Size     =3D Size;
     return Res;
   }
 };
=20
 } // end anonymous namespace.
=20
-bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
+bool X86AsmParser::isSrcOp(X86Operand &Op) {
   unsigned basereg =3D is64BitMode() ? X86::RSI : X86::ESI;
=20
   return (Op.isMem() &&
@@ -380,32 +464,38 @@
     Op.Mem.BaseReg =3D=3D basereg && Op.Mem.IndexReg =3D=3D 0);
 }
=20
-bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
+bool X86AsmParser::isDstOp(X86Operand &Op) {
   unsigned basereg =3D is64BitMode() ? X86::RDI : X86::EDI;
=20
-  return Op.isMem() && Op.Mem.SegReg =3D=3D X86::ES &&
+  return Op.isMem() &&=20
+    (Op.Mem.SegReg =3D=3D 0 || Op.Mem.SegReg =3D=3D X86::ES) &&
     isa<MCConstantExpr>(Op.Mem.Disp) &&
     cast<MCConstantExpr>(Op.Mem.Disp)->getValue() =3D=3D 0 &&
     Op.Mem.BaseReg =3D=3D basereg && Op.Mem.IndexReg =3D=3D 0;
 }
=20
-bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
-                                    SMLoc &StartLoc, SMLoc &EndLoc) {
+bool X86AsmParser::ParseRegister(unsigned &RegNo,
+                                 SMLoc &StartLoc, SMLoc &EndLoc) {
   RegNo =3D 0;
-  const AsmToken &TokPercent =3D Parser.getTok();
-  assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
-  StartLoc =3D TokPercent.getLoc();
-  Parser.Lex(); // Eat percent token.
+  if (!isParsingIntelSyntax()) {
+    const AsmToken &TokPercent =3D Parser.getTok();
+    assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
+    StartLoc =3D TokPercent.getLoc();
+    Parser.Lex(); // Eat percent token.
+  }
=20
   const AsmToken &Tok =3D Parser.getTok();
-  if (Tok.isNot(AsmToken::Identifier))
-    return Error(Tok.getLoc(), "invalid register name");
+  if (Tok.isNot(AsmToken::Identifier)) {
+    if (isParsingIntelSyntax()) return true;
+    return Error(StartLoc, "invalid register name",
+                 SMRange(StartLoc, Tok.getEndLoc()));
+  }
=20
   RegNo =3D MatchRegisterName(Tok.getString());
=20
   // If the match failed, try the register name as lowercase.
   if (RegNo =3D=3D 0)
-    RegNo =3D MatchRegisterName(LowercaseString(Tok.getString()));
+    RegNo =3D MatchRegisterName(Tok.getString().lower());
=20
   if (!is64BitMode()) {
     // FIXME: This should be done using Requires<In32BitMode> and
@@ -417,8 +507,9 @@
         X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
         X86II::isX86_64NonExtLowByteReg(RegNo) ||
         X86II::isX86_64ExtendedReg(RegNo))
-      return Error(Tok.getLoc(), "register %"
-                   + Tok.getString() + " is only available in 64-bit mode"=
);
+      return Error(StartLoc, "register %"
+                   + Tok.getString() + " is only available in 64-bit mode",
+                   SMRange(StartLoc, Tok.getEndLoc()));
   }
=20
   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
@@ -478,15 +569,182 @@
     }
   }
=20
-  if (RegNo =3D=3D 0)
-    return Error(Tok.getLoc(), "invalid register name");
+  if (RegNo =3D=3D 0) {
+    if (isParsingIntelSyntax()) return true;
+    return Error(StartLoc, "invalid register name",
+                 SMRange(StartLoc, Tok.getEndLoc()));
+  }
=20
-  EndLoc =3D Tok.getLoc();
+  EndLoc =3D Tok.getEndLoc();
   Parser.Lex(); // Eat identifier token.
   return false;
 }
=20
-X86Operand *X86ATTAsmParser::ParseOperand() {
+X86Operand *X86AsmParser::ParseOperand() {
+  if (isParsingIntelSyntax())
+    return ParseIntelOperand();
+  return ParseATTOperand();
+}
+
+/// getIntelMemOperandSize - Return intel memory operand size.
+static unsigned getIntelMemOperandSize(StringRef OpStr) {
+  unsigned Size =3D 0;
+  if (OpStr =3D=3D "BYTE") Size =3D 8;
+  if (OpStr =3D=3D "WORD") Size =3D 16;
+  if (OpStr =3D=3D "DWORD") Size =3D 32;
+  if (OpStr =3D=3D "QWORD") Size =3D 64;
+  if (OpStr =3D=3D "XWORD") Size =3D 80;
+  if (OpStr =3D=3D "XMMWORD") Size =3D 128;
+  if (OpStr =3D=3D "YMMWORD") Size =3D 256;
+  return Size;
+}
+
+X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
+                                                   unsigned Size) {
+  unsigned BaseReg =3D 0, IndexReg =3D 0, Scale =3D 1;
+  SMLoc Start =3D Parser.getTok().getLoc(), End;
+
+  const MCExpr *Disp =3D MCConstantExpr::Create(0, getParser().getContext(=
));
+  // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
+
+  // Eat '['
+  if (getLexer().isNot(AsmToken::LBrac))
+    return ErrorOperand(Start, "Expected '[' token!");
+  Parser.Lex();
+ =20
+  if (getLexer().is(AsmToken::Identifier)) {
+    // Parse BaseReg
+    if (ParseRegister(BaseReg, Start, End)) {
+      // Handle '[' 'symbol' ']'
+      if (getParser().ParseExpression(Disp, End)) return 0;
+      if (getLexer().isNot(AsmToken::RBrac))
+        return ErrorOperand(Start, "Expected ']' token!");
+      Parser.Lex();
+      return X86Operand::CreateMem(Disp, Start, End, Size);
+    }
+  } else if (getLexer().is(AsmToken::Integer)) {
+      int64_t Val =3D Parser.getTok().getIntVal();
+      Parser.Lex();
+      SMLoc Loc =3D Parser.getTok().getLoc();
+      if (getLexer().is(AsmToken::RBrac)) {
+        // Handle '[' number ']'
+        Parser.Lex();
+        const MCExpr *Disp =3D MCConstantExpr::Create(Val, getContext());
+        if (SegReg)
+          return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
+                                       Start, End, Size);
+        return X86Operand::CreateMem(Disp, Start, End, Size);
+      } else if (getLexer().is(AsmToken::Star)) {
+        // Handle '[' Scale*IndexReg ']'
+        Parser.Lex();
+        SMLoc IdxRegLoc =3D Parser.getTok().getLoc();
+	if (ParseRegister(IndexReg, IdxRegLoc, End))
+	  return ErrorOperand(IdxRegLoc, "Expected register");
+        Scale =3D Val;
+      } else
+        return ErrorOperand(Loc, "Unepxeted token");
+  }
+
+  if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
+    bool isPlus =3D getLexer().is(AsmToken::Plus);
+    Parser.Lex();
+    SMLoc PlusLoc =3D Parser.getTok().getLoc();
+    if (getLexer().is(AsmToken::Integer)) {
+      int64_t Val =3D Parser.getTok().getIntVal();
+      Parser.Lex();
+      if (getLexer().is(AsmToken::Star)) {
+        Parser.Lex();
+        SMLoc IdxRegLoc =3D Parser.getTok().getLoc();
+	if (ParseRegister(IndexReg, IdxRegLoc, End))
+	  return ErrorOperand(IdxRegLoc, "Expected register");
+        Scale =3D Val;
+      } else if (getLexer().is(AsmToken::RBrac)) {
+        const MCExpr *ValExpr =3D MCConstantExpr::Create(Val, getContext()=
);
+        Disp =3D isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getConte=
xt());
+      } else
+        return ErrorOperand(PlusLoc, "unexpected token after +");
+    } else if (getLexer().is(AsmToken::Identifier)) {
+      // This could be an index register or a displacement expression.
+      End =3D Parser.getTok().getLoc();
+      if (!IndexReg)
+        ParseRegister(IndexReg, Start, End);
+      else if (getParser().ParseExpression(Disp, End)) return 0;       =20
+    }
+  }
+
+  if (getLexer().isNot(AsmToken::RBrac))
+    if (getParser().ParseExpression(Disp, End)) return 0;
+
+  End =3D Parser.getTok().getLoc();
+  if (getLexer().isNot(AsmToken::RBrac))
+    return ErrorOperand(End, "expected ']' token!");
+  Parser.Lex();
+  End =3D Parser.getTok().getLoc();
+
+  // handle [-42]
+  if (!BaseReg && !IndexReg)
+    return X86Operand::CreateMem(Disp, Start, End, Size);
+
+  return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
+                               Start, End, Size);
+}
+
+/// ParseIntelMemOperand - Parse intel style memory operand.
+X86Operand *X86AsmParser::ParseIntelMemOperand() {
+  const AsmToken &Tok =3D Parser.getTok();
+  SMLoc Start =3D Parser.getTok().getLoc(), End;
+  unsigned SegReg =3D 0;
+
+  unsigned Size =3D getIntelMemOperandSize(Tok.getString());
+  if (Size) {
+    Parser.Lex();
+    assert (Tok.getString() =3D=3D "PTR" && "Unexpected token!");
+    Parser.Lex();
+  }
+
+  if (getLexer().is(AsmToken::LBrac))
+    return ParseIntelBracExpression(SegReg, Size);
+
+  if (!ParseRegister(SegReg, Start, End)) {
+    // Handel SegReg : [ ... ]
+    if (getLexer().isNot(AsmToken::Colon))
+      return ErrorOperand(Start, "Expected ':' token!");
+    Parser.Lex(); // Eat :
+    if (getLexer().isNot(AsmToken::LBrac))
+      return ErrorOperand(Start, "Expected '[' token!");
+    return ParseIntelBracExpression(SegReg, Size);
+  }
+
+  const MCExpr *Disp =3D MCConstantExpr::Create(0, getParser().getContext(=
));
+  if (getParser().ParseExpression(Disp, End)) return 0;
+  return X86Operand::CreateMem(Disp, Start, End, Size);
+}
+
+X86Operand *X86AsmParser::ParseIntelOperand() {
+  SMLoc Start =3D Parser.getTok().getLoc(), End;
+
+  // immediate.
+  if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
+      getLexer().is(AsmToken::Minus)) {
+    const MCExpr *Val;
+    if (!getParser().ParseExpression(Val, End)) {
+      End =3D Parser.getTok().getLoc();
+      return X86Operand::CreateImm(Val, Start, End);
+    }
+  }
+
+  // register
+  unsigned RegNo =3D 0;
+  if (!ParseRegister(RegNo, Start, End)) {
+    End =3D Parser.getTok().getLoc();
+    return X86Operand::CreateReg(RegNo, Start, End);
+  }
+
+  // mem operand
+  return ParseIntelMemOperand();
+}
+
+X86Operand *X86AsmParser::ParseATTOperand() {
   switch (getLexer().getKind()) {
   default:
     // Parse a memory operand with no segment register.
@@ -497,7 +755,8 @@
     SMLoc Start, End;
     if (ParseRegister(RegNo, Start, End)) return 0;
     if (RegNo =3D=3D X86::EIZ || RegNo =3D=3D X86::RIZ) {
-      Error(Start, "%eiz and %riz can only be used as index registers");
+      Error(Start, "%eiz and %riz can only be used as index registers",
+            SMRange(Start, End));
       return 0;
     }
=20
@@ -524,7 +783,7 @@
=20
 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' =
prefix
 /// has already been parsed if present.
-X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemSta=
rt) {
+X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart)=
 {
=20
   // We have to disambiguate a parenthesized expression "(4+5)" from the s=
tart
   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)"=
.  The
@@ -579,18 +838,21 @@
   // If we reached here, then we just ate the ( of the memory operand.  Pr=
ocess
   // the rest of the memory operand.
   unsigned BaseReg =3D 0, IndexReg =3D 0, Scale =3D 1;
+  SMLoc IndexLoc;
=20
   if (getLexer().is(AsmToken::Percent)) {
-    SMLoc L;
-    if (ParseRegister(BaseReg, L, L)) return 0;
+    SMLoc StartLoc, EndLoc;
+    if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
     if (BaseReg =3D=3D X86::EIZ || BaseReg =3D=3D X86::RIZ) {
-      Error(L, "eiz and riz can only be used as index registers");
+      Error(StartLoc, "eiz and riz can only be used as index registers",
+            SMRange(StartLoc, EndLoc));
       return 0;
     }
   }
=20
   if (getLexer().is(AsmToken::Comma)) {
     Parser.Lex(); // Eat the comma.
+    IndexLoc =3D Parser.getTok().getLoc();
=20
     // Following the comma we should have either an index register, or a s=
cale
     // value. We don't support the later form, but we want to parse it
@@ -616,8 +878,10 @@
           SMLoc Loc =3D Parser.getTok().getLoc();
=20
           int64_t ScaleVal;
-          if (getParser().ParseAbsoluteExpression(ScaleVal))
+          if (getParser().ParseAbsoluteExpression(ScaleVal)){
+            Error(Loc, "expected scale expression");
             return 0;
+	  }
=20
           // Validate the scale amount.
           if (ScaleVal !=3D 1 && ScaleVal !=3D 2 && ScaleVal !=3D 4 && Sca=
leVal !=3D 8){
@@ -650,11 +914,28 @@
   SMLoc MemEnd =3D Parser.getTok().getLoc();
   Parser.Lex(); // Eat the ')'.
=20
+  // If we have both a base register and an index register make sure they =
are
+  // both 64-bit or 32-bit registers.
+  if (BaseReg !=3D 0 && IndexReg !=3D 0) {
+    if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
+        !X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg) &&
+        IndexReg !=3D X86::RIZ) {
+      Error(IndexLoc, "index register is 32-bit, but base register is 64-b=
it");
+      return 0;
+    }
+    if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
+        !X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) &&
+        IndexReg !=3D X86::EIZ){
+      Error(IndexLoc, "index register is 64-bit, but base register is 32-b=
it");
+      return 0;
+    }
+  }
+
   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
                                MemStart, MemEnd);
 }
=20
-bool X86ATTAsmParser::
+bool X86AsmParser::
 ParseInstruction(StringRef Name, SMLoc NameLoc,
                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
   StringRef PatchedName =3D Name;
@@ -669,20 +950,21 @@
   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
-    bool IsVCMP =3D PatchedName.startswith("vcmp");
+    bool IsVCMP =3D PatchedName[0] =3D=3D 'v';
     unsigned SSECCIdx =3D IsVCMP ? 4 : 3;
     unsigned SSEComparisonCode =3D StringSwitch<unsigned>(
       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
-      .Case("eq",          0)
-      .Case("lt",          1)
-      .Case("le",          2)
-      .Case("unord",       3)
-      .Case("neq",         4)
-      .Case("nlt",         5)
-      .Case("nle",         6)
-      .Case("ord",         7)
-      .Case("eq_uq",       8)
-      .Case("nge",         9)
+      .Case("eq",       0x00)
+      .Case("lt",       0x01)
+      .Case("le",       0x02)
+      .Case("unord",    0x03)
+      .Case("neq",      0x04)
+      .Case("nlt",      0x05)
+      .Case("nle",      0x06)
+      .Case("ord",      0x07)
+      /* AVX only from here */
+      .Case("eq_uq",    0x08)
+      .Case("nge",      0x09)
       .Case("ngt",      0x0A)
       .Case("false",    0x0B)
       .Case("neq_oq",   0x0C)
@@ -706,7 +988,7 @@
       .Case("gt_oq",    0x1E)
       .Case("true_us",  0x1F)
       .Default(~0U);
-    if (SSEComparisonCode !=3D ~0U) {
+    if (SSEComparisonCode !=3D ~0U && (IsVCMP || SSEComparisonCode < 8)) {
       ExtraImmOp =3D MCConstantExpr::Create(SSEComparisonCode,
                                           getParser().getContext());
       if (PatchedName.endswith("ss")) {
@@ -724,10 +1006,9 @@
=20
   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
=20
-  if (ExtraImmOp)
+  if (ExtraImmOp && !isParsingIntelSyntax())
     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc)=
);
=20
-
   // Determine whether this is an instruction prefix.
   bool isPrefix =3D
     Name =3D=3D "lock" || Name =3D=3D "rep" ||
@@ -781,6 +1062,9 @@
   else if (isPrefix && getLexer().is(AsmToken::Slash))
     Parser.Lex(); // Consume the prefix separator Slash
=20
+  if (ExtraImmOp && isParsingIntelSyntax())
+    Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc)=
);
+
   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
   // documented form in various unofficial manuals, so a lot of code uses =
it.
@@ -916,11 +1200,21 @@
        Name.startswith("rcl") || Name.startswith("rcr") ||
        Name.startswith("rol") || Name.startswith("ror")) &&
       Operands.size() =3D=3D 3) {
-    X86Operand *Op1 =3D static_cast<X86Operand*>(Operands[1]);
-    if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
-        cast<MCConstantExpr>(Op1->getImm())->getValue() =3D=3D 1) {
-      delete Operands[1];
-      Operands.erase(Operands.begin() + 1);
+    if (isParsingIntelSyntax()) {
+      // Intel syntax
+      X86Operand *Op1 =3D static_cast<X86Operand*>(Operands[2]);
+      if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
+	  cast<MCConstantExpr>(Op1->getImm())->getValue() =3D=3D 1) {
+	delete Operands[2];
+	Operands.pop_back();
+      }
+    } else {
+      X86Operand *Op1 =3D static_cast<X86Operand*>(Operands[1]);
+      if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
+	  cast<MCConstantExpr>(Op1->getImm())->getValue() =3D=3D 1) {
+	delete Operands[1];
+	Operands.erase(Operands.begin() + 1);
+      }
     }
   }
  =20
@@ -939,7 +1233,246 @@
   return false;
 }
=20
-bool X86ATTAsmParser::
+bool X86AsmParser::
+processInstruction(MCInst &Inst,
+                   const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
+  switch (Inst.getOpcode()) {
+  default: return false;
+  case X86::AND16i16: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::AND16ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::AND32i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::AND32ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::AND64i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::AND64ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::XOR16i16: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::XOR16ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::XOR32i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::XOR32ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::XOR64i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::XOR64ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::OR16i16: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::OR16ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::OR32i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::OR32ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::OR64i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::OR64ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::CMP16i16: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::CMP16ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::CMP32i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::CMP32ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::CMP64i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::CMP64ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::ADD16i16: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::ADD16ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::ADD32i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::ADD32ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::ADD64i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::ADD64ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::SUB16i16: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::SUB16ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::SUB32i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::SUB32ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  case X86::SUB64i32: {
+    if (!Inst.getOperand(0).isImm() ||
+        !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
+      return false;
+
+    MCInst TmpInst;
+    TmpInst.setOpcode(X86::SUB64ri8);
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
+    TmpInst.addOperand(Inst.getOperand(0));
+    Inst =3D TmpInst;
+    return true;
+  }
+  }
+}
+
+bool X86AsmParser::
 MatchAndEmitInstruction(SMLoc IDLoc,
                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
                         MCStreamer &Out) {
@@ -957,6 +1490,7 @@
       Op->getToken() =3D=3D "fstenv" || Op->getToken() =3D=3D "fclex") {
     MCInst Inst;
     Inst.setOpcode(X86::WAIT);
+    Inst.setLoc(IDLoc);
     Out.EmitInstruction(Inst);
=20
     const char *Repl =3D
@@ -980,9 +1514,17 @@
   MCInst Inst;
=20
   // First, try a direct match.
-  switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
+  switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
+                               isParsingIntelSyntax())) {
   default: break;
   case Match_Success:
+    // Some instructions need post-processing to, for example, tweak which
+    // encoding is selected. Loop on it while changes happen so the
+    // individual transformations can chain off each other.=20
+    while (processInstruction(Inst, Operands))
+      ;
+
+    Inst.setLoc(IDLoc);
     Out.EmitInstruction(Inst);
     return false;
   case Match_MissingFeature:
@@ -1040,6 +1582,7 @@
     (Match1 =3D=3D Match_Success) + (Match2 =3D=3D Match_Success) +
     (Match3 =3D=3D Match_Success) + (Match4 =3D=3D Match_Success);
   if (NumSuccessfulMatches =3D=3D 1) {
+    Inst.setLoc(IDLoc);
     Out.EmitInstruction(Inst);
     return false;
   }
@@ -1078,21 +1621,24 @@
   if ((Match1 =3D=3D Match_MnemonicFail) && (Match2 =3D=3D Match_MnemonicF=
ail) &&
       (Match3 =3D=3D Match_MnemonicFail) && (Match4 =3D=3D Match_MnemonicF=
ail)) {
     if (!WasOriginallyInvalidOperand) {
-      Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
-      return true;
+      return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
+                   Op->getLocRange());
     }
=20
     // Recover location info for the operand if we know which was the prob=
lem.
-    SMLoc ErrorLoc =3D IDLoc;
     if (OrigErrorInfo !=3D ~0U) {
       if (OrigErrorInfo >=3D Operands.size())
         return Error(IDLoc, "too few operands for instruction");
=20
-      ErrorLoc =3D ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
-      if (ErrorLoc =3D=3D SMLoc()) ErrorLoc =3D IDLoc;
+      X86Operand *Operand =3D (X86Operand*)Operands[OrigErrorInfo];
+      if (Operand->getStartLoc().isValid()) {
+        SMRange OperandRange =3D Operand->getLocRange();
+        return Error(Operand->getStartLoc(), "invalid operand for instruct=
ion",
+                     OperandRange);
+      }
     }
=20
-    return Error(ErrorLoc, "invalid operand for instruction");
+    return Error(IDLoc, "invalid operand for instruction");
   }
=20
   // If one instruction matched with a missing feature, report this as a
@@ -1112,24 +1658,34 @@
   }
=20
   // If all of these were an outright failure, report it in a useless way.
-  // FIXME: We should give nicer diagnostics about the exact failure.
   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix"=
);
   return true;
 }
=20
=20
-bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
+bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
   StringRef IDVal =3D DirectiveID.getIdentifier();
   if (IDVal =3D=3D ".word")
     return ParseDirectiveWord(2, DirectiveID.getLoc());
   else if (IDVal.startswith(".code"))
     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
+  else if (IDVal.startswith(".intel_syntax")) {
+    getParser().setAssemblerDialect(1);
+    if (getLexer().isNot(AsmToken::EndOfStatement)) {
+      if(Parser.getTok().getString() =3D=3D "noprefix") {
+	// FIXME : Handle noprefix
+	Parser.Lex();
+      } else
+	return true;
+    }
+    return false;
+  }
   return true;
 }
=20
 /// ParseDirectiveWord
 ///  ::=3D .word [ expression (, expression)* ]
-bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
+bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
   if (getLexer().isNot(AsmToken::EndOfStatement)) {
     for (;;) {
       const MCExpr *Value;
@@ -1154,7 +1710,7 @@
=20
 /// ParseDirectiveCode
 ///  ::=3D .code32 | .code64
-bool X86ATTAsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
+bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
   if (IDVal =3D=3D ".code32") {
     Parser.Lex();
     if (is64BitMode()) {
@@ -1179,8 +1735,8 @@
=20
 // Force static initialization.
 extern "C" void LLVMInitializeX86AsmParser() {
-  RegisterMCAsmParser<X86ATTAsmParser> X(TheX86_32Target);
-  RegisterMCAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
+  RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
+  RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
   LLVMInitializeX86AsmLexer();
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/Disas=
sembler/X86Disassembler.cpp
--- a/head/contrib/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86Disassembler.cpp - Disassembler for x86 and x86_64 ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86Disassembler.cpp - Disassembler for x86 and x86_64 ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -18,9 +18,11 @@
 #include "X86DisassemblerDecoder.h"
=20
 #include "llvm/MC/EDInstInfo.h"
-#include "llvm/MC/MCDisassembler.h"
+#include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCDisassembler.h"
 #include "llvm/MC/MCInst.h"
+#include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MemoryObject.h"
@@ -42,6 +44,11 @@
   dbgs() << file << ":" << line << ": " << s;
 }
=20
+const char *x86DisassemblerGetInstrName(unsigned Opcode, void *mii) {
+  const MCInstrInfo *MII =3D static_cast<const MCInstrInfo *>(mii);
+  return MII->getName(Opcode);
+}
+
 #define debug(s) DEBUG(x86DisassemblerDebug(__FILE__, __LINE__, s));
=20
 namespace llvm { =20
@@ -65,17 +72,19 @@
 }
=20
 static bool translateInstruction(MCInst &target,
-                                InternalInstruction &source);
+                                InternalInstruction &source,
+                                const MCDisassembler *Dis);
=20
-X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,=
 DisassemblerMode mode) :
-    MCDisassembler(STI),
-    fMode(mode) {
+X86GenericDisassembler::X86GenericDisassembler(const MCSubtargetInfo &STI,
+                                               DisassemblerMode mode,
+                                               const MCInstrInfo *MII)
+  : MCDisassembler(STI), MII(MII), fMode(mode) {}
+
+X86GenericDisassembler::~X86GenericDisassembler() {
+  delete MII;
 }
=20
-X86GenericDisassembler::~X86GenericDisassembler() {
-}
-
-EDInstInfo *X86GenericDisassembler::getEDInfo() const {
+const EDInstInfo *X86GenericDisassembler::getEDInfo() const {
   return instInfoX86;
 }
=20
@@ -116,6 +125,8 @@
                                        uint64_t address,
                                        raw_ostream &vStream,
                                        raw_ostream &cStream) const {
+  CommentStream =3D &cStream;
+
   InternalInstruction internalInstr;
=20
   dlog_t loggerFn =3D logger;
@@ -127,6 +138,7 @@
                               (void*)&region,
                               loggerFn,
                               (void*)&vStream,
+                              (void*)MII,
                               address,
                               fMode);
=20
@@ -136,7 +148,8 @@
   }
   else {
     size =3D internalInstr.length;
-    return (!translateInstruction(instr, internalInstr)) ? Success : Fail;
+    return (!translateInstruction(instr, internalInstr, this)) ?
+            Success : Fail;
   }
 }
=20
@@ -161,6 +174,140 @@
   mcInst.addOperand(MCOperand::CreateReg(llvmRegnum));
 }
=20
+/// tryAddingSymbolicOperand - trys to add a symbolic operand in place of =
the
+/// immediate Value in the MCInst.=20
+///
+/// @param Value      - The immediate Value, has had any PC adjustment mad=
e by
+///                     the caller.
+/// @param isBranch   - If the instruction is a branch instruction
+/// @param Address    - The starting address of the instruction
+/// @param Offset     - The byte offset to this immediate in the instructi=
on
+/// @param Width      - The byte width of this immediate in the instruction
+///
+/// If the getOpInfo() function was set when setupForSymbolicDisassembly()=
 was
+/// called then that function is called to get any symbolic information fo=
r the
+/// immediate in the instruction using the Address, Offset and Width.  If =
that
+/// returns non-zero then the symbolic information it returns is used to c=
reate=20
+/// an MCExpr and that is added as an operand to the MCInst.  If getOpInfo=
()
+/// returns zero and isBranch is true then a symbol look up for immediate =
Value
+/// is done and if a symbol is found an MCExpr is created with that, else
+/// an MCExpr with the immediate Value is created.  This function returns =
true
+/// if it adds an operand to the MCInst and false otherwise.
+static bool tryAddingSymbolicOperand(int64_t Value, bool isBranch,
+                                     uint64_t Address, uint64_t Offset,
+                                     uint64_t Width, MCInst &MI,=20
+                                     const MCDisassembler *Dis) { =20
+  LLVMOpInfoCallback getOpInfo =3D Dis->getLLVMOpInfoCallback();
+  struct LLVMOpInfo1 SymbolicOp;
+  memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
+  SymbolicOp.Value =3D Value;
+  void *DisInfo =3D Dis->getDisInfoBlock();
+
+  if (!getOpInfo ||
+      !getOpInfo(DisInfo, Address, Offset, Width, 1, &SymbolicOp)) {
+    // Clear SymbolicOp.Value from above and also all other fields.
+    memset(&SymbolicOp, '\0', sizeof(struct LLVMOpInfo1));
+    LLVMSymbolLookupCallback SymbolLookUp =3D Dis->getLLVMSymbolLookupCall=
back();
+    if (!SymbolLookUp)
+      return false;
+    uint64_t ReferenceType;
+    if (isBranch)
+       ReferenceType =3D LLVMDisassembler_ReferenceType_In_Branch;
+    else
+       ReferenceType =3D LLVMDisassembler_ReferenceType_InOut_None;
+    const char *ReferenceName;
+    const char *Name =3D SymbolLookUp(DisInfo, Value, &ReferenceType, Addr=
ess,
+                                    &ReferenceName);
+    if (Name) {
+      SymbolicOp.AddSymbol.Name =3D Name;
+      SymbolicOp.AddSymbol.Present =3D true;
+    }
+    // For branches always create an MCExpr so it gets printed as hex addr=
ess.
+    else if (isBranch) {
+      SymbolicOp.Value =3D Value;
+    }
+    if(ReferenceType =3D=3D LLVMDisassembler_ReferenceType_Out_SymbolStub)
+      (*Dis->CommentStream) << "symbol stub for: " << ReferenceName;
+    if (!Name && !isBranch)
+      return false;
+  }
+
+  MCContext *Ctx =3D Dis->getMCContext();
+  const MCExpr *Add =3D NULL;
+  if (SymbolicOp.AddSymbol.Present) {
+    if (SymbolicOp.AddSymbol.Name) {
+      StringRef Name(SymbolicOp.AddSymbol.Name);
+      MCSymbol *Sym =3D Ctx->GetOrCreateSymbol(Name);
+      Add =3D MCSymbolRefExpr::Create(Sym, *Ctx);
+    } else {
+      Add =3D MCConstantExpr::Create((int)SymbolicOp.AddSymbol.Value, *Ctx=
);
+    }
+  }
+
+  const MCExpr *Sub =3D NULL;
+  if (SymbolicOp.SubtractSymbol.Present) {
+      if (SymbolicOp.SubtractSymbol.Name) {
+      StringRef Name(SymbolicOp.SubtractSymbol.Name);
+      MCSymbol *Sym =3D Ctx->GetOrCreateSymbol(Name);
+      Sub =3D MCSymbolRefExpr::Create(Sym, *Ctx);
+    } else {
+      Sub =3D MCConstantExpr::Create((int)SymbolicOp.SubtractSymbol.Value,=
 *Ctx);
+    }
+  }
+
+  const MCExpr *Off =3D NULL;
+  if (SymbolicOp.Value !=3D 0)
+    Off =3D MCConstantExpr::Create(SymbolicOp.Value, *Ctx);
+
+  const MCExpr *Expr;
+  if (Sub) {
+    const MCExpr *LHS;
+    if (Add)
+      LHS =3D MCBinaryExpr::CreateSub(Add, Sub, *Ctx);
+    else
+      LHS =3D MCUnaryExpr::CreateMinus(Sub, *Ctx);
+    if (Off !=3D 0)
+      Expr =3D MCBinaryExpr::CreateAdd(LHS, Off, *Ctx);
+    else
+      Expr =3D LHS;
+  } else if (Add) {
+    if (Off !=3D 0)
+      Expr =3D MCBinaryExpr::CreateAdd(Add, Off, *Ctx);
+    else
+      Expr =3D Add;
+  } else {
+    if (Off !=3D 0)
+      Expr =3D Off;
+    else
+      Expr =3D MCConstantExpr::Create(0, *Ctx);
+  }
+
+  MI.addOperand(MCOperand::CreateExpr(Expr));
+
+  return true;
+}
+
+/// tryAddingPcLoadReferenceComment - trys to add a comment as to what is =
being
+/// referenced by a load instruction with the base register that is the ri=
p.
+/// These can often be addresses in a literal pool.  The Address of the
+/// instruction and its immediate Value are used to determine the address
+/// being referenced in the literal pool entry.  The SymbolLookUp call bac=
k will
+/// return a pointer to a literal 'C' string if the referenced address is =
an=20
+/// address into a section with 'C' string literals.
+static void tryAddingPcLoadReferenceComment(uint64_t Address, uint64_t Val=
ue,
+                                            const void *Decoder) {
+  const MCDisassembler *Dis =3D static_cast<const MCDisassembler*>(Decoder=
);
+  LLVMSymbolLookupCallback SymbolLookUp =3D Dis->getLLVMSymbolLookupCallba=
ck();
+  if (SymbolLookUp) {
+    void *DisInfo =3D Dis->getDisInfoBlock();
+    uint64_t ReferenceType =3D LLVMDisassembler_ReferenceType_In_PCrel_Loa=
d;
+    const char *ReferenceName;
+    (void)SymbolLookUp(DisInfo, Value, &ReferenceType, Address, &Reference=
Name);
+    if(ReferenceType =3D=3D LLVMDisassembler_ReferenceType_Out_LitPool_Cst=
rAddr)
+      (*Dis->CommentStream) << "literal pool for: " << ReferenceName;
+  }
+}
+
 /// translateImmediate  - Appends an immediate operand to an MCInst.
 ///
 /// @param mcInst       - The MCInst to append to.
@@ -169,10 +316,11 @@
 /// @param insn         - The internal instruction.
 static void translateImmediate(MCInst &mcInst, uint64_t immediate,
                                const OperandSpecifier &operand,
-                               InternalInstruction &insn) {
+                               InternalInstruction &insn,
+                               const MCDisassembler *Dis) { =20
   // Sign-extend the immediate if necessary.
=20
-  OperandType type =3D operand.type;
+  OperandType type =3D (OperandType)operand.type;
=20
   if (type =3D=3D TYPE_RELv) {
     switch (insn.displacementSize) {
@@ -225,6 +373,8 @@
     }
   }
=20
+  bool isBranch =3D false;
+  uint64_t pcrel =3D 0;
   switch (type) {
   case TYPE_XMM128:
     mcInst.addOperand(MCOperand::CreateReg(X86::XMM0 + (immediate >> 4)));
@@ -232,8 +382,11 @@
   case TYPE_XMM256:
     mcInst.addOperand(MCOperand::CreateReg(X86::YMM0 + (immediate >> 4)));
     return;
+  case TYPE_REL8:
+    isBranch =3D true;
+    pcrel =3D insn.startLocation + insn.immediateOffset + insn.immediateSi=
ze;
+    // fall through to sign extend the immediate if needed.
   case TYPE_MOFFS8:
-  case TYPE_REL8:
     if(immediate & 0x80)
       immediate |=3D ~(0xffull);
     break;
@@ -241,9 +394,12 @@
     if(immediate & 0x8000)
       immediate |=3D ~(0xffffull);
     break;
-  case TYPE_MOFFS32:
   case TYPE_REL32:
   case TYPE_REL64:
+    isBranch =3D true;
+    pcrel =3D insn.startLocation + insn.immediateOffset + insn.immediateSi=
ze;
+    // fall through to sign extend the immediate if needed.
+  case TYPE_MOFFS32:
     if(immediate & 0x80000000)
       immediate |=3D ~(0xffffffffull);
     break;
@@ -253,7 +409,10 @@
     break;
   }
    =20
-  mcInst.addOperand(MCOperand::CreateImm(immediate));
+  if(!tryAddingSymbolicOperand(immediate + pcrel, isBranch, insn.startLoca=
tion,
+                               insn.immediateOffset, insn.immediateSize,
+                               mcInst, Dis))
+    mcInst.addOperand(MCOperand::CreateImm(immediate));
 }
=20
 /// translateRMRegister - Translates a register stored in the R/M field of=
 the
@@ -300,7 +459,8 @@
 /// @param insn         - The instruction to extract Mod, R/M, and SIB fie=
lds
 ///                       from.
 /// @return             - 0 on success; nonzero otherwise
-static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn) {
+static bool translateRMMemory(MCInst &mcInst, InternalInstruction &insn,
+                              const MCDisassembler *Dis) { =20
   // Addresses in an MCInst are represented as five operands:
   //   1. basereg       (register)  The R/M base, or (if there is a SIB) t=
he=20
   //                                SIB base
@@ -318,6 +478,7 @@
   MCOperand indexReg;
   MCOperand displacement;
   MCOperand segmentReg;
+  uint64_t pcrel =3D 0;
  =20
   if (insn.eaBase =3D=3D EA_BASE_sib || insn.eaBase =3D=3D EA_BASE_sib64) {
     if (insn.sibBase !=3D SIB_BASE_NONE) {
@@ -359,8 +520,14 @@
         debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base");
         return true;
       }
-      if (insn.mode =3D=3D MODE_64BIT)
+      if (insn.mode =3D=3D MODE_64BIT){
+        pcrel =3D insn.startLocation +
+                insn.displacementOffset + insn.displacementSize;
+        tryAddingPcLoadReferenceComment(insn.startLocation +
+                                        insn.displacementOffset,
+                                        insn.displacement + pcrel, Dis);
         baseReg =3D MCOperand::CreateReg(X86::RIP); // Section 2.2.1.6
+      }
       else
         baseReg =3D MCOperand::CreateReg(0);
      =20
@@ -426,7 +593,10 @@
   mcInst.addOperand(baseReg);
   mcInst.addOperand(scaleAmount);
   mcInst.addOperand(indexReg);
-  mcInst.addOperand(displacement);
+  if(!tryAddingSymbolicOperand(insn.displacement + pcrel, false,
+                               insn.startLocation, insn.displacementOffset,
+                               insn.displacementSize, mcInst, Dis))
+    mcInst.addOperand(displacement);
   mcInst.addOperand(segmentReg);
   return false;
 }
@@ -440,7 +610,7 @@
 ///                       from.
 /// @return             - 0 on success; nonzero otherwise
 static bool translateRM(MCInst &mcInst, const OperandSpecifier &operand,
-                        InternalInstruction &insn) {
+                        InternalInstruction &insn, const MCDisassembler *D=
is) { =20
   switch (operand.type) {
   default:
     debug("Unexpected type for a R/M operand");
@@ -480,7 +650,7 @@
   case TYPE_M1632:
   case TYPE_M1664:
   case TYPE_LEA:
-    return translateRMMemory(mcInst, insn);
+    return translateRMMemory(mcInst, insn, Dis);
   }
 }
  =20
@@ -510,7 +680,8 @@
 /// @param insn         - The internal instruction.
 /// @return             - false on success; true otherwise.
 static bool translateOperand(MCInst &mcInst, const OperandSpecifier &opera=
nd,
-                             InternalInstruction &insn) {
+                             InternalInstruction &insn,
+                             const MCDisassembler *Dis) { =20
   switch (operand.encoding) {
   default:
     debug("Unhandled operand encoding during translation");
@@ -519,7 +690,7 @@
     translateRegister(mcInst, insn.reg);
     return false;
   case ENCODING_RM:
-    return translateRM(mcInst, operand, insn);
+    return translateRM(mcInst, operand, insn, Dis);
   case ENCODING_CB:
   case ENCODING_CW:
   case ENCODING_CD:
@@ -537,7 +708,8 @@
     translateImmediate(mcInst,
                        insn.immediates[insn.numImmediatesTranslated++],
                        operand,
-                       insn);
+                       insn,
+                       Dis);
     return false;
   case ENCODING_RB:
   case ENCODING_RW:
@@ -556,7 +728,7 @@
   case ENCODING_DUP:
     return translateOperand(mcInst,
                             insn.spec->operands[operand.type - TYPE_DUP0],
-                            insn);
+                            insn, Dis);
   }
 }
  =20
@@ -567,7 +739,8 @@
 /// @param insn         - The internal instruction.
 /// @return             - false on success; true otherwise.
 static bool translateInstruction(MCInst &mcInst,
-                                InternalInstruction &insn) { =20
+                                InternalInstruction &insn,
+                                const MCDisassembler *Dis) { =20
   if (!insn.spec) {
     debug("Instruction has no specification");
     return true;
@@ -581,7 +754,7 @@
  =20
   for (index =3D 0; index < X86_MAX_OPERANDS; ++index) {
     if (insn.spec->operands[index].encoding !=3D ENCODING_NONE) {
-      if (translateOperand(mcInst, insn.spec->operands[index], insn)) {
+      if (translateOperand(mcInst, insn.spec->operands[index], insn, Dis))=
 {
         return true;
       }
     }
@@ -590,12 +763,16 @@
   return false;
 }
=20
-static MCDisassembler *createX86_32Disassembler(const Target &T, const MCS=
ubtargetInfo &STI) {
-  return new X86Disassembler::X86_32Disassembler(STI);
+static MCDisassembler *createX86_32Disassembler(const Target &T,
+                                                const MCSubtargetInfo &STI=
) {
+  return new X86Disassembler::X86GenericDisassembler(STI, MODE_32BIT,
+                                                     T.createMCInstrInfo()=
);
 }
=20
-static MCDisassembler *createX86_64Disassembler(const Target &T, const MCS=
ubtargetInfo &STI) {
-  return new X86Disassembler::X86_64Disassembler(STI);
+static MCDisassembler *createX86_64Disassembler(const Target &T,
+                                                const MCSubtargetInfo &STI=
) {
+  return new X86Disassembler::X86GenericDisassembler(STI, MODE_64BIT,
+                                                     T.createMCInstrInfo()=
);
 }
=20
 extern "C" void LLVMInitializeX86Disassembler() {=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/Disas=
sembler/X86Disassembler.h
--- a/head/contrib/llvm/lib/Target/X86/Disassembler/X86Disassembler.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/Disassembler/X86Disassembler.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86Disassembler.h - Disassembler for x86 and x86_64 ------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86Disassembler.h - Disassembler for x86 and x86_64 -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -78,7 +78,7 @@
   const char*             name;
=20
 #define INSTRUCTION_IDS               \
-  const InstrUID *instructionIDs;
+  unsigned instructionIDs;
=20
 #include "X86DisassemblerDecoderCommon.h"
=20
@@ -87,11 +87,10 @@
=20
 #include "llvm/MC/MCDisassembler.h"
=20
-struct InternalInstruction;
-
 namespace llvm {
  =20
 class MCInst;
+class MCInstrInfo;
 class MCSubtargetInfo;
 class MemoryObject;
 class raw_ostream;
@@ -104,13 +103,16 @@
 ///   All each platform class should have to do is subclass the constructo=
r, and
 ///   provide a different disassemblerMode value.
 class X86GenericDisassembler : public MCDisassembler {
-protected:
+  const MCInstrInfo *MII;
+public:
   /// Constructor     - Initializes the disassembler.
   ///
   /// @param mode     - The X86 architecture mode to decode for.
-  X86GenericDisassembler(const MCSubtargetInfo &STI, DisassemblerMode mode=
);
+  X86GenericDisassembler(const MCSubtargetInfo &STI, DisassemblerMode mode,
+                         const MCInstrInfo *MII);
+private:
+  ~X86GenericDisassembler();
 public:
-  ~X86GenericDisassembler();
=20
   /// getInstruction - See MCDisassembler.
   DecodeStatus getInstruction(MCInst &instr,
@@ -121,37 +123,13 @@
                               raw_ostream &cStream) const;
=20
   /// getEDInfo - See MCDisassembler.
-  EDInstInfo *getEDInfo() const;
+  const EDInstInfo *getEDInfo() const;
 private:
   DisassemblerMode              fMode;
 };
=20
-/// X86_16Disassembler - 16-bit X86 disassembler.
-class X86_16Disassembler : public X86GenericDisassembler {
-public:
-  X86_16Disassembler(const MCSubtargetInfo &STI) :
-    X86GenericDisassembler(STI, MODE_16BIT) {
-  }
-}; =20
+} // namespace X86Disassembler
=20
-/// X86_16Disassembler - 32-bit X86 disassembler.
-class X86_32Disassembler : public X86GenericDisassembler {
-public:
-  X86_32Disassembler(const MCSubtargetInfo &STI) :
-    X86GenericDisassembler(STI, MODE_32BIT) {
-  }
-};
+} // namespace llvm
=20
-/// X86_16Disassembler - 64-bit X86 disassembler.
-class X86_64Disassembler : public X86GenericDisassembler {
-public:
-  X86_64Disassembler(const MCSubtargetInfo &STI) :
-    X86GenericDisassembler(STI, MODE_64BIT) {
-  }
-};
-
-} // namespace X86Disassembler
- =20
-} // namespace llvm
- =20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/Disas=
sembler/X86DisassemblerDecoder.c
--- a/head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.=
c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.=
c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/*=3D=3D=3D- X86DisassemblerDecoder.c - Disassembler decoder -------------=
*- C -*-=3D=3D*
+/*=3D=3D=3D-- X86DisassemblerDecoder.c - Disassembler decoder ------------=
*- C -*-=3D=3D=3D*
  *
  *                     The LLVM Compiler Infrastructure
  *
@@ -82,11 +82,9 @@
     decision =3D &THREEBYTEA7_SYM;
     break;
   }
- =20
+
   return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
     modrm_type !=3D MODRM_ONEENTRY;
- =20
-  return 0;
 }
=20
 /*
@@ -103,12 +101,9 @@
                        InstructionContext insnContext,
                        uint8_t opcode,
                        uint8_t modRM) {
-  const struct ModRMDecision* dec;
+  const struct ModRMDecision* dec =3D 0;
  =20
   switch (type) {
-  default:
-    debug("Unknown opcode type");
-    return 0;
   case ONEBYTE:
     dec =3D &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcod=
e];
     break;
@@ -134,14 +129,17 @@
     debug("Corrupt table!  Unknown modrm_type");
     return 0;
   case MODRM_ONEENTRY:
-    return dec->instructionIDs[0];
+    return modRMTable[dec->instructionIDs];
   case MODRM_SPLITRM:
     if (modFromModRM(modRM) =3D=3D 0x3)
-      return dec->instructionIDs[1];
-    else
-      return dec->instructionIDs[0];
+      return modRMTable[dec->instructionIDs+1];
+    return modRMTable[dec->instructionIDs];
+  case MODRM_SPLITREG:
+    if (modFromModRM(modRM) =3D=3D 0x3)
+      return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
+    return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
   case MODRM_FULL:
-    return dec->instructionIDs[modRM];
+    return modRMTable[dec->instructionIDs+modRM];
   }
 }
=20
@@ -314,6 +312,15 @@
    =20
     if (consumeByte(insn, &byte))
       return -1;
+
+    /*
+     * If the first byte is a LOCK prefix break and let it be disassembled
+     * as a lock "instruction", by creating an <MCInst #xxxx LOCK_PREFIX>.
+     * FIXME there is currently no way to get the disassembler to print the
+     * lock prefix if it is not the first byte.
+     */
+    if (insn->readerCursor - 1 =3D=3D insn->startLocation && byte =3D=3D 0=
xf0)
+      break;
    =20
     switch (byte) {
     case 0xf0:  /* LOCK */
@@ -712,7 +719,7 @@
  * @return      - 0 if the ModR/M could be read when needed or was not nee=
ded;
  *                nonzero otherwise.
  */
-static int getID(struct InternalInstruction* insn) { =20
+static int getID(struct InternalInstruction* insn, void *miiArg) {
   uint8_t attrMask;
   uint16_t instructionID;
  =20
@@ -765,6 +772,8 @@
   else {
     if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
       attrMask |=3D ATTR_OPSIZE;
+    else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
+      attrMask |=3D ATTR_ADSIZE;
     else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
       attrMask |=3D ATTR_XS;
     else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
@@ -773,17 +782,20 @@
=20
   if (insn->rexPrefix & 0x08)
     attrMask |=3D ATTR_REXW;
- =20
+
   if (getIDWithAttrMask(&instructionID, insn, attrMask))
     return -1;
- =20
+
   /* The following clauses compensate for limitations of the tables. */
- =20
-  if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW)) {
+
+  if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW) &&
+      !(attrMask & ATTR_OPSIZE)) {
     /*
      * Some VEX instructions ignore the L-bit, but use the W-bit. Normally=
 L-bit
      * has precedence since there are no L-bit with W-bit entries in the t=
ables.
      * So if the L-bit isn't significant we should use the W-bit instead.
+     * We only need to do this if the instruction doesn't specify OpSize s=
ince
+     * there is a VEX_L_W_OPSIZE table.
      */
=20
     const struct InstructionSpecifier *spec;
@@ -823,7 +835,7 @@
    =20
     const struct InstructionSpecifier *spec;
     uint16_t instructionIDWithOpsize;
-    const struct InstructionSpecifier *specWithOpsize;
+    const char *specName, *specWithOpSizeName;
    =20
     spec =3D specifierForUID(instructionID);
    =20
@@ -840,11 +852,13 @@
       return 0;
     }
    =20
-    specWithOpsize =3D specifierForUID(instructionIDWithOpsize);
-   =20
-    if (is16BitEquvalent(spec->name, specWithOpsize->name)) {
+    specName =3D x86DisassemblerGetInstrName(instructionID, miiArg);
+    specWithOpSizeName =3D
+      x86DisassemblerGetInstrName(instructionIDWithOpsize, miiArg);
+
+    if (is16BitEquvalent(specName, specWithOpSizeName)) {
       insn->instructionID =3D instructionIDWithOpsize;
-      insn->spec =3D specWithOpsize;
+      insn->spec =3D specifierForUID(instructionIDWithOpsize);
     } else {
       insn->instructionID =3D instructionID;
       insn->spec =3D spec;
@@ -1011,6 +1025,7 @@
     return 0;
  =20
   insn->consumedDisplacement =3D TRUE;
+  insn->displacementOffset =3D insn->readerCursor - insn->startLocation;
  =20
   switch (insn->eaDisplacement) {
   case EA_DISP_NONE:
@@ -1407,6 +1422,7 @@
     size =3D insn->immediateSize;
   else
     insn->immediateSize =3D size;
+  insn->immediateOffset =3D insn->readerCursor - insn->startLocation;
  =20
   switch (size) {
   case 1:
@@ -1469,6 +1485,7 @@
 static int readOperands(struct InternalInstruction* insn) {
   int index;
   int hasVVVV, needVVVV;
+  int sawRegImm =3D 0;
  =20
   dbgprintf(insn, "readOperands()");
=20
@@ -1497,11 +1514,25 @@
       dbgprintf(insn, "We currently don't hande code-offset encodings");
       return -1;
     case ENCODING_IB:
+      if (sawRegImm) {
+        /* Saw a register immediate so don't read again and instead split =
the
+           previous immediate.  FIXME: This is a hack. */
+        insn->immediates[insn->numImmediatesConsumed] =3D
+          insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
+        ++insn->numImmediatesConsumed;
+        break;
+      }
       if (readImmediate(insn, 1))
         return -1;
       if (insn->spec->operands[index].type =3D=3D TYPE_IMM3 &&
           insn->immediates[insn->numImmediatesConsumed - 1] > 7)
         return -1;
+      if (insn->spec->operands[index].type =3D=3D TYPE_IMM5 &&
+          insn->immediates[insn->numImmediatesConsumed - 1] > 31)
+        return -1;
+      if (insn->spec->operands[index].type =3D=3D TYPE_XMM128 ||
+          insn->spec->operands[index].type =3D=3D TYPE_XMM256)
+        sawRegImm =3D 1;
       break;
     case ENCODING_IW:
       if (readImmediate(insn, 2))
@@ -1593,6 +1624,7 @@
                       void* readerArg,
                       dlog_t logger,
                       void* loggerArg,
+                      void* miiArg,
                       uint64_t startLoc,
                       DisassemblerMode mode) {
   memset(insn, 0, sizeof(struct InternalInstruction));
@@ -1608,7 +1640,7 @@
  =20
   if (readPrefixes(insn)       ||
       readOpcode(insn)         ||
-      getID(insn)              ||
+      getID(insn, miiArg)      ||
       insn->instructionID =3D=3D 0 ||
       readOperands(insn))
     return -1;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/Disas=
sembler/X86DisassemblerDecoder.h
--- a/head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.=
h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoder.=
h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/*=3D=3D=3D- X86DisassemblerDecoderInternal.h - Disassembler decoder -----=
*- C -*-=3D=3D*
+/*=3D=3D=3D-- X86DisassemblerDecoderInternal.h - Disassembler decoder ---*=
- C -*-=3D=3D=3D*
  *
  *                     The LLVM Compiler Infrastructure
  *
@@ -20,11 +20,10 @@
 extern "C" {
 #endif
  =20
-#define INSTRUCTION_SPECIFIER_FIELDS  \
-  const char*             name;
+#define INSTRUCTION_SPECIFIER_FIELDS
=20
 #define INSTRUCTION_IDS     \
-  const InstrUID *instructionIDs;
+  unsigned instructionIDs;
=20
 #include "X86DisassemblerDecoderCommon.h"
  =20
@@ -460,6 +459,11 @@
   uint8_t addressSize;
   uint8_t displacementSize;
   uint8_t immediateSize;
+
+  /* Offsets from the start of the instruction to the pieces of data, whic=
h is
+     needed to find relocation entries for adding symbolic operands */
+  uint8_t displacementOffset;
+  uint8_t immediateOffset;
  =20
   /* opcode state */
  =20
@@ -554,6 +558,7 @@
                       void* readerArg,
                       dlog_t logger,
                       void* loggerArg,
+                      void* miiArg,
                       uint64_t startLoc,
                       DisassemblerMode mode);
=20
@@ -568,6 +573,8 @@
                           unsigned line,
                           const char *s);
=20
+const char *x86DisassemblerGetInstrName(unsigned Opcode, void *mii);
+
 #ifdef __cplusplus=20
 }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/Disas=
sembler/X86DisassemblerDecoderCommon.h
--- a/head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoderC=
ommon.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/Disassembler/X86DisassemblerDecoderC=
ommon.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/*=3D=3D=3D- X86DisassemblerDecoderCommon.h - Disassembler decoder -------=
*- C -*-=3D=3D*
+/*=3D=3D=3D-- X86DisassemblerDecoderCommon.h - Disassembler decoder -----*=
- C -*-=3D=3D=3D*
  *
  *                     The LLVM Compiler Infrastructure
  *
@@ -54,8 +54,9 @@
   ENUM_ENTRY(ATTR_XD,     0x04) \
   ENUM_ENTRY(ATTR_REXW,   0x08) \
   ENUM_ENTRY(ATTR_OPSIZE, 0x10) \
-  ENUM_ENTRY(ATTR_VEX,    0x20) \
-  ENUM_ENTRY(ATTR_VEXL,   0x40)
+  ENUM_ENTRY(ATTR_ADSIZE, 0x20) \
+  ENUM_ENTRY(ATTR_VEX,    0x40) \
+  ENUM_ENTRY(ATTR_VEXL,   0x80)
=20
 #define ENUM_ENTRY(n, v) n =3D v,
 enum attributeBits {
@@ -77,6 +78,8 @@
                                         "64-bit mode but no more")        =
     \
   ENUM_ENTRY(IC_OPSIZE,             3,  "requires an OPSIZE prefix, so "  =
     \
                                         "operands change width")          =
     \
+  ENUM_ENTRY(IC_ADSIZE,             3,  "requires an ADSIZE prefix, so "  =
     \
+                                        "operands change width")          =
     \
   ENUM_ENTRY(IC_XD,                 2,  "may say something about the opcod=
e "  \
                                         "but not the operands")           =
     \
   ENUM_ENTRY(IC_XS,                 2,  "may say something about the opcod=
e "  \
@@ -88,6 +91,7 @@
   ENUM_ENTRY(IC_64BIT_REXW,         4,  "requires a REX.W prefix, so opera=
nds "\
                                         "change width; overrides IC_OPSIZE=
")   \
   ENUM_ENTRY(IC_64BIT_OPSIZE,       3,  "Just as meaningful as IC_OPSIZE")=
     \
+  ENUM_ENTRY(IC_64BIT_ADSIZE,       3,  "Just as meaningful as IC_ADSIZE")=
     \
   ENUM_ENTRY(IC_64BIT_XD,           5,  "XD instructions are SSE; REX.W is=
 "   \
                                         "secondary")                      =
     \
   ENUM_ENTRY(IC_64BIT_XS,           5,  "Just as meaningful as IC_64BIT_XD=
")   \
@@ -111,7 +115,8 @@
   ENUM_ENTRY(IC_VEX_L,              3,  "requires VEX and the L prefix")  =
     \
   ENUM_ENTRY(IC_VEX_L_XS,           4,  "requires VEX and the L and XS pre=
fix")\
   ENUM_ENTRY(IC_VEX_L_XD,           4,  "requires VEX and the L and XD pre=
fix")\
-  ENUM_ENTRY(IC_VEX_L_OPSIZE,       4,  "requires VEX, L, and OpSize")
+  ENUM_ENTRY(IC_VEX_L_OPSIZE,       4,  "requires VEX, L, and OpSize")    =
     \
+  ENUM_ENTRY(IC_VEX_L_W_OPSIZE,     5,  "requires VEX, L, W and OpSize")
=20
=20
 #define ENUM_ENTRY(n, r, d) n,   =20
@@ -155,6 +160,8 @@
  * MODRM_SPLITRM  - If the ModR/M byte is between 0x00 and 0xbf, the opcode
  *                  corresponds to one instruction; otherwise, it correspo=
nds to
  *                  a different instruction.
+ * MODRM_SPLITREG - ModR/M byte divided by 8 is used to select instruction=
. This
+                    corresponds to instructions that use reg field as opco=
de
  * MODRM_FULL     - Potentially, each value of the ModR/M byte could corre=
spond
  *                  to a different instruction.
  */
@@ -162,6 +169,7 @@
 #define MODRMTYPES            \
   ENUM_ENTRY(MODRM_ONEENTRY)  \
   ENUM_ENTRY(MODRM_SPLITRM)   \
+  ENUM_ENTRY(MODRM_SPLITREG)  \
   ENUM_ENTRY(MODRM_FULL)
=20
 #define ENUM_ENTRY(n) n,   =20
@@ -265,6 +273,7 @@
   ENUM_ENTRY(TYPE_IMM32,      "4-byte")                                   =
     \
   ENUM_ENTRY(TYPE_IMM64,      "8-byte")                                   =
     \
   ENUM_ENTRY(TYPE_IMM3,       "1-byte immediate operand between 0 and 7") =
     \
+  ENUM_ENTRY(TYPE_IMM5,       "1-byte immediate operand between 0 and 31")=
     \
   ENUM_ENTRY(TYPE_RM8,        "1-byte register or memory operand")        =
     \
   ENUM_ENTRY(TYPE_RM16,       "2-byte")                                   =
     \
   ENUM_ENTRY(TYPE_RM32,       "4-byte")                                   =
     \
@@ -335,8 +344,8 @@
  *   operand.
  */
 struct OperandSpecifier {
-  OperandEncoding  encoding;
-  OperandType      type;
+  uint8_t encoding;
+  uint8_t type;
 };
=20
 /*
@@ -363,7 +372,7 @@
  * its operands.
  */
 struct InstructionSpecifier {
-  ModifierType modifierType;
+  uint8_t modifierType;
   uint8_t modifierBase;
   struct OperandSpecifier operands[X86_MAX_OPERANDS];
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/InstP=
rinter/X86ATTInstPrinter.cpp
--- a/head/contrib/llvm/lib/Target/X86/InstPrinter/X86ATTInstPrinter.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/InstPrinter/X86ATTInstPrinter.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,8 @@
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/FormattedStream.h"
@@ -26,14 +28,9 @@
 using namespace llvm;
=20
 // Include the auto-generated portion of the assembly writer.
-#define GET_INSTRUCTION_NAME
 #define PRINT_ALIAS_INSTR
 #include "X86GenAsmWriter.inc"
=20
-X86ATTInstPrinter::X86ATTInstPrinter(const MCAsmInfo &MAI)
-  : MCInstPrinter(MAI) {
-}
-
 void X86ATTInstPrinter::printRegName(raw_ostream &OS,
                                      unsigned RegNo) const {
   OS << '%' << getRegisterName(RegNo);
@@ -45,29 +42,50 @@
   if (!printAliasInstr(MI, OS))
     printInstruction(MI, OS);
  =20
+  // Next always print the annotation.
+  printAnnotation(OS, Annot);
+
   // If verbose assembly is enabled, we can print some informative comment=
s.
-  if (CommentStream) {
-    printAnnotation(OS, Annot);
+  if (CommentStream)
     EmitAnyX86InstComments(MI, *CommentStream, getRegisterName);
-  }
-}
-
-StringRef X86ATTInstPrinter::getOpcodeName(unsigned Opcode) const {
-  return getInstructionName(Opcode);
 }
=20
 void X86ATTInstPrinter::printSSECC(const MCInst *MI, unsigned Op,
                                    raw_ostream &O) {
   switch (MI->getOperand(Op).getImm()) {
-  default: assert(0 && "Invalid ssecc argument!");
-  case 0: O << "eq"; break;
-  case 1: O << "lt"; break;
-  case 2: O << "le"; break;
-  case 3: O << "unord"; break;
-  case 4: O << "neq"; break;
-  case 5: O << "nlt"; break;
-  case 6: O << "nle"; break;
-  case 7: O << "ord"; break;
+  default: llvm_unreachable("Invalid ssecc argument!");
+  case    0: O << "eq"; break;
+  case    1: O << "lt"; break;
+  case    2: O << "le"; break;
+  case    3: O << "unord"; break;
+  case    4: O << "neq"; break;
+  case    5: O << "nlt"; break;
+  case    6: O << "nle"; break;
+  case    7: O << "ord"; break;
+  case    8: O << "eq_uq"; break;
+  case    9: O << "nge"; break;
+  case  0xa: O << "ngt"; break;
+  case  0xb: O << "false"; break;
+  case  0xc: O << "neq_oq"; break;
+  case  0xd: O << "ge"; break;
+  case  0xe: O << "gt"; break;
+  case  0xf: O << "true"; break;
+  case 0x10: O << "eq_os"; break;
+  case 0x11: O << "lt_oq"; break;
+  case 0x12: O << "le_oq"; break;
+  case 0x13: O << "unord_s"; break;
+  case 0x14: O << "neq_us"; break;
+  case 0x15: O << "nlt_uq"; break;
+  case 0x16: O << "nle_uq"; break;
+  case 0x17: O << "ord_s"; break;
+  case 0x18: O << "eq_us"; break;
+  case 0x19: O << "nge_uq"; break;
+  case 0x1a: O << "ngt_uq"; break;
+  case 0x1b: O << "false_os"; break;
+  case 0x1c: O << "neq_os"; break;
+  case 0x1d: O << "ge_oq"; break;
+  case 0x1e: O << "gt_oq"; break;
+  case 0x1f: O << "true_us"; break;
   }
 }
=20
@@ -79,11 +97,21 @@
                                         raw_ostream &O) {
   const MCOperand &Op =3D MI->getOperand(OpNo);
   if (Op.isImm())
-    // Print this as a signed 32-bit value.
-    O << (int)Op.getImm();
+    O << Op.getImm();
   else {
     assert(Op.isExpr() && "unknown pcrel immediate operand");
-    O << *Op.getExpr();
+    // If a symbolic branch target was added as a constant expression then=
 print
+    // that address in hex.
+    const MCConstantExpr *BranchTarget =3D dyn_cast<MCConstantExpr>(Op.get=
Expr());
+    int64_t Address;
+    if (BranchTarget && BranchTarget->EvaluateAsAbsolute(Address)) {
+      O << "0x";
+      O.write_hex(Address);
+    }
+    else {
+      // Otherwise, just print the expression.
+      O << *Op.getExpr();
+    }
   }
 }
=20
@@ -97,7 +125,7 @@
     O << '$' << (int64_t)Op.getImm();
    =20
     if (CommentStream && (Op.getImm() > 255 || Op.getImm() < -256))
-      *CommentStream << format("imm =3D 0x%llX\n", (long long)Op.getImm());
+      *CommentStream << format("imm =3D 0x%" PRIX64 "\n", (uint64_t)Op.get=
Imm());
    =20
   } else {
     assert(Op.isExpr() && "unknown operand kind in printOperand");
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/InstP=
rinter/X86ATTInstPrinter.h
--- a/head/contrib/llvm/lib/Target/X86/InstPrinter/X86ATTInstPrinter.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/InstPrinter/X86ATTInstPrinter.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86ATTInstPrinter.h - Convert X86 MCInst to assembly syntax =
-------=3D=3D=3D//
+//=3D=3D- X86ATTInstPrinter.h - Convert X86 MCInst to assembly syntax -*- =
C++ -*-=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -22,11 +22,12 @@
  =20
 class X86ATTInstPrinter : public MCInstPrinter {
 public:
-  X86ATTInstPrinter(const MCAsmInfo &MAI);
- =20
+  X86ATTInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                    const MCRegisterInfo &MRI)
+    : MCInstPrinter(MAI, MII, MRI) {}
+
   virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
   virtual void printInst(const MCInst *MI, raw_ostream &OS, StringRef Anno=
t);
-  virtual StringRef getOpcodeName(unsigned Opcode) const;
=20
   // Autogenerated by tblgen, returns true if we successfully printed an
   // alias.
@@ -35,7 +36,6 @@
   // Autogenerated by tblgen.
   void printInstruction(const MCInst *MI, raw_ostream &OS);
   static const char *getRegisterName(unsigned RegNo);
-  static const char *getInstructionName(unsigned Opcode);
=20
   void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &OS);
   void printMemReference(const MCInst *MI, unsigned Op, raw_ostream &OS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/InstP=
rinter/X86InstComments.cpp
--- a/head/contrib/llvm/lib/Target/X86/InstPrinter/X86InstComments.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/InstPrinter/X86InstComments.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -29,11 +29,17 @@
 void llvm::EmitAnyX86InstComments(const MCInst *MI, raw_ostream &OS,
                                   const char *(*getRegName)(unsigned)) {
   // If this is a shuffle operation, the switch should fill in this state.
-  SmallVector<unsigned, 8> ShuffleMask;
+  SmallVector<int, 8> ShuffleMask;
   const char *DestName =3D 0, *Src1Name =3D 0, *Src2Name =3D 0;
=20
   switch (MI->getOpcode()) {
   case X86::INSERTPSrr:
+    Src1Name =3D getRegName(MI->getOperand(0).getReg());
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    DecodeINSERTPSMask(MI->getOperand(3).getImm(), ShuffleMask);
+    break;
+  case X86::VINSERTPSrr:
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     DecodeINSERTPSMask(MI->getOperand(3).getImm(), ShuffleMask);
@@ -44,34 +50,61 @@
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     DecodeMOVLHPSMask(2, ShuffleMask);
     break;
+  case X86::VMOVLHPSrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeMOVLHPSMask(2, ShuffleMask);
+    break;
=20
   case X86::MOVHLPSrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     DecodeMOVHLPSMask(2, ShuffleMask);
     break;
+  case X86::VMOVHLPSrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeMOVHLPSMask(2, ShuffleMask);
+    break;
=20
   case X86::PSHUFDri:
+  case X86::VPSHUFDri:
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
     // FALL THROUGH.
   case X86::PSHUFDmi:
+  case X86::VPSHUFDmi:
     DestName =3D getRegName(MI->getOperand(0).getReg());
-    DecodePSHUFMask(4, MI->getOperand(MI->getNumOperands()-1).getImm(),
+    DecodePSHUFMask(MVT::v4i32, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                     ShuffleMask);
+    break;
+  case X86::VPSHUFDYri:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    // FALL THROUGH.
+  case X86::VPSHUFDYmi:
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodePSHUFMask(MVT::v8i32, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
                     ShuffleMask);
     break;
=20
+
   case X86::PSHUFHWri:
+  case X86::VPSHUFHWri:
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
     // FALL THROUGH.
   case X86::PSHUFHWmi:
+  case X86::VPSHUFHWmi:
     DestName =3D getRegName(MI->getOperand(0).getReg());
     DecodePSHUFHWMask(MI->getOperand(MI->getNumOperands()-1).getImm(),
                       ShuffleMask);
     break;
   case X86::PSHUFLWri:
+  case X86::VPSHUFLWri:
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
     // FALL THROUGH.
   case X86::PSHUFLWmi:
+  case X86::VPSHUFLWmi:
     DestName =3D getRegName(MI->getOperand(0).getReg());
     DecodePSHUFLWMask(MI->getOperand(MI->getNumOperands()-1).getImm(),
                       ShuffleMask);
@@ -82,28 +115,92 @@
     // FALL THROUGH.
   case X86::PUNPCKHBWrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKHMask(16, ShuffleMask);
+    DecodeUNPCKHMask(MVT::v16i8, ShuffleMask);
+    break;
+  case X86::VPUNPCKHBWrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHBWrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v16i8, ShuffleMask);
+    break;
+  case X86::VPUNPCKHBWYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHBWYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v32i8, ShuffleMask);
     break;
   case X86::PUNPCKHWDrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::PUNPCKHWDrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKHMask(8, ShuffleMask);
+    DecodeUNPCKHMask(MVT::v8i16, ShuffleMask);
+    break;
+  case X86::VPUNPCKHWDrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHWDrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v8i16, ShuffleMask);
+    break;
+  case X86::VPUNPCKHWDYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHWDYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v16i16, ShuffleMask);
     break;
   case X86::PUNPCKHDQrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::PUNPCKHDQrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKHMask(4, ShuffleMask);
+    DecodeUNPCKHMask(MVT::v4i32, ShuffleMask);
+    break;
+  case X86::VPUNPCKHDQrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHDQrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v4i32, ShuffleMask);
+    break;
+  case X86::VPUNPCKHDQYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHDQYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v8i32, ShuffleMask);
     break;
   case X86::PUNPCKHQDQrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::PUNPCKHQDQrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKHMask(2, ShuffleMask);
+    DecodeUNPCKHMask(MVT::v2i64, ShuffleMask);
+    break;
+  case X86::VPUNPCKHQDQrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHQDQrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v2i64, ShuffleMask);
+    break;
+  case X86::VPUNPCKHQDQYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKHQDQYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKHMask(MVT::v4i64, ShuffleMask);
     break;
=20
   case X86::PUNPCKLBWrr:
@@ -111,126 +208,284 @@
     // FALL THROUGH.
   case X86::PUNPCKLBWrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKLBWMask(16, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v16i8, ShuffleMask);
+    break;
+  case X86::VPUNPCKLBWrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLBWrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v16i8, ShuffleMask);
+    break;
+  case X86::VPUNPCKLBWYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLBWYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v32i8, ShuffleMask);
     break;
   case X86::PUNPCKLWDrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::PUNPCKLWDrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKLWDMask(8, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v8i16, ShuffleMask);
+    break;
+  case X86::VPUNPCKLWDrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLWDrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v8i16, ShuffleMask);
+    break;
+  case X86::VPUNPCKLWDYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLWDYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v16i16, ShuffleMask);
     break;
   case X86::PUNPCKLDQrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::PUNPCKLDQrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKLDQMask(4, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v4i32, ShuffleMask);
+    break;
+  case X86::VPUNPCKLDQrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLDQrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v4i32, ShuffleMask);
+    break;
+  case X86::VPUNPCKLDQYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLDQYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v8i32, ShuffleMask);
     break;
   case X86::PUNPCKLQDQrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::PUNPCKLQDQrm:
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
-    DecodePUNPCKLQDQMask(2, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v2i64, ShuffleMask);
+    break;
+  case X86::VPUNPCKLQDQrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLQDQrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v2i64, ShuffleMask);
+    break;
+  case X86::VPUNPCKLQDQYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPUNPCKLQDQYrm:
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    DecodeUNPCKLMask(MVT::v4i64, ShuffleMask);
     break;
=20
   case X86::SHUFPDrri:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::SHUFPDrmi:
-    DecodeSHUFPSMask(2, MI->getOperand(3).getImm(), ShuffleMask);
+    DecodeSHUFPMask(MVT::v2f64, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     break;
+  case X86::VSHUFPDrri:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VSHUFPDrmi:
+    DecodeSHUFPMask(MVT::v2f64, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
+  case X86::VSHUFPDYrri:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VSHUFPDYrmi:
+    DecodeSHUFPMask(MVT::v4f64, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
=20
   case X86::SHUFPSrri:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::SHUFPSrmi:
-    DecodeSHUFPSMask(4, MI->getOperand(3).getImm(), ShuffleMask);
+    DecodeSHUFPMask(MVT::v4f32, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     break;
+  case X86::VSHUFPSrri:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VSHUFPSrmi:
+    DecodeSHUFPMask(MVT::v4f32, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
+  case X86::VSHUFPSYrri:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VSHUFPSYrmi:
+    DecodeSHUFPMask(MVT::v8f32, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
=20
   case X86::UNPCKLPDrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::UNPCKLPDrm:
-    DecodeUNPCKLPDMask(2, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v2f64, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VUNPCKLPDrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::VUNPCKLPDrm:
-    DecodeUNPCKLPDMask(2, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v2f64, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VUNPCKLPDYrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::VUNPCKLPDYrm:
-    DecodeUNPCKLPDMask(4, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v4f64, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::UNPCKLPSrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::UNPCKLPSrm:
-    DecodeUNPCKLPSMask(4, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v4f32, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VUNPCKLPSrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::VUNPCKLPSrm:
-    DecodeUNPCKLPSMask(4, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v4f32, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VUNPCKLPSYrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::VUNPCKLPSYrm:
-    DecodeUNPCKLPSMask(8, ShuffleMask);
+    DecodeUNPCKLMask(MVT::v8f32, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::UNPCKHPDrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::UNPCKHPDrm:
-    DecodeUNPCKHPMask(2, ShuffleMask);
+    DecodeUNPCKHMask(MVT::v2f64, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     break;
+  case X86::VUNPCKHPDrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VUNPCKHPDrm:
+    DecodeUNPCKHMask(MVT::v2f64, ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
+  case X86::VUNPCKHPDYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VUNPCKHPDYrm:
+    DecodeUNPCKHMask(MVT::v4f64, ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
   case X86::UNPCKHPSrr:
     Src2Name =3D getRegName(MI->getOperand(2).getReg());
     // FALL THROUGH.
   case X86::UNPCKHPSrm:
-    DecodeUNPCKHPMask(4, ShuffleMask);
+    DecodeUNPCKHMask(MVT::v4f32, ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(0).getReg());
     break;
+  case X86::VUNPCKHPSrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VUNPCKHPSrm:
+    DecodeUNPCKHMask(MVT::v4f32, ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
+  case X86::VUNPCKHPSYrr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VUNPCKHPSYrm:
+    DecodeUNPCKHMask(MVT::v8f32, ShuffleMask);
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
+    break;
   case X86::VPERMILPSri:
-    DecodeVPERMILPSMask(4, MI->getOperand(2).getImm(),
-                        ShuffleMask);
-    Src1Name =3D getRegName(MI->getOperand(0).getReg());
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    // FALL THROUGH.
+  case X86::VPERMILPSmi:
+    DecodePSHUFMask(MVT::v4f32, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VPERMILPSYri:
-    DecodeVPERMILPSMask(8, MI->getOperand(2).getImm(),
-                        ShuffleMask);
-    Src1Name =3D getRegName(MI->getOperand(0).getReg());
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    // FALL THROUGH.
+  case X86::VPERMILPSYmi:
+    DecodePSHUFMask(MVT::v8f32, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VPERMILPDri:
-    DecodeVPERMILPDMask(2, MI->getOperand(2).getImm(),
-                        ShuffleMask);
-    Src1Name =3D getRegName(MI->getOperand(0).getReg());
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    // FALL THROUGH.
+  case X86::VPERMILPDmi:
+    DecodePSHUFMask(MVT::v2f64, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                    ShuffleMask);
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VPERMILPDYri:
-    DecodeVPERMILPDMask(4, MI->getOperand(2).getImm(),
-                        ShuffleMask);
-    Src1Name =3D getRegName(MI->getOperand(0).getReg());
+    Src1Name =3D getRegName(MI->getOperand(1).getReg());
+    // FALL THROUGH.
+  case X86::VPERMILPDYmi:
+    DecodePSHUFMask(MVT::v4f64, MI->getOperand(MI->getNumOperands()-1).get=
Imm(),
+                       ShuffleMask);
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   case X86::VPERM2F128rr:
-    DecodeVPERM2F128Mask(MI->getOperand(3).getImm(), ShuffleMask);
+  case X86::VPERM2I128rr:
+    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    // FALL THROUGH.
+  case X86::VPERM2F128rm:
+  case X86::VPERM2I128rm:
+    // For instruction comments purpose, assume the 256-bit vector is v4i6=
4.
+    DecodeVPERM2X128Mask(MVT::v4i64,
+                         MI->getOperand(MI->getNumOperands()-1).getImm(),
+                         ShuffleMask);
     Src1Name =3D getRegName(MI->getOperand(1).getReg());
-    Src2Name =3D getRegName(MI->getOperand(2).getReg());
+    DestName =3D getRegName(MI->getOperand(0).getReg());
     break;
   }
=20
@@ -245,7 +500,7 @@
     if (Src1Name =3D=3D Src2Name) {
       for (unsigned i =3D 0, e =3D ShuffleMask.size(); i !=3D e; ++i) {
         if ((int)ShuffleMask[i] >=3D 0 && // Not sentinel.
-            ShuffleMask[i] >=3D e)        // From second mask.
+            ShuffleMask[i] >=3D (int)e)        // From second mask.
           ShuffleMask[i] -=3D e;
       }
     }
@@ -263,13 +518,13 @@
=20
       // Otherwise, it must come from src1 or src2.  Print the span of ele=
ments
       // that comes from this src.
-      bool isSrc1 =3D ShuffleMask[i] < ShuffleMask.size();
+      bool isSrc1 =3D ShuffleMask[i] < (int)ShuffleMask.size();
       const char *SrcName =3D isSrc1 ? Src1Name : Src2Name;
       OS << (SrcName ? SrcName : "mem") << '[';
       bool IsFirst =3D true;
       while (i !=3D e &&
              (int)ShuffleMask[i] >=3D 0 &&
-             (ShuffleMask[i] < ShuffleMask.size()) =3D=3D isSrc1) {
+             (ShuffleMask[i] < (int)ShuffleMask.size()) =3D=3D isSrc1) {
         if (!IsFirst)
           OS << ',';
         else
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/InstP=
rinter/X86InstComments.h
--- a/head/contrib/llvm/lib/Target/X86/InstPrinter/X86InstComments.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/InstPrinter/X86InstComments.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86InstComments.h - Generate verbose-asm comments for instrs=
 ------=3D=3D=3D//
+//=3D- X86InstComments.h - Generate verbose-asm comments for instrs -*- C+=
+ -*-=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/InstP=
rinter/X86IntelInstPrinter.cpp
--- a/head/contrib/llvm/lib/Target/X86/InstPrinter/X86IntelInstPrinter.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/InstPrinter/X86IntelInstPrinter.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -17,15 +17,13 @@
 #include "X86InstComments.h"
 #include "MCTargetDesc/X86MCTargetDesc.h"
 #include "llvm/MC/MCInst.h"
-#include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCExpr.h"
+#include "llvm/MC/MCInstrInfo.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FormattedStream.h"
 #include <cctype>
 using namespace llvm;
=20
-// Include the auto-generated portion of the assembly writer.
-#define GET_INSTRUCTION_NAME
 #include "X86GenAsmWriter1.inc"
=20
 void X86IntelInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) co=
nst {
@@ -35,29 +33,52 @@
 void X86IntelInstPrinter::printInst(const MCInst *MI, raw_ostream &OS,
                                     StringRef Annot) {
   printInstruction(MI, OS);
- =20
+
+  // Next always print the annotation.
+  printAnnotation(OS, Annot);
+
   // If verbose assembly is enabled, we can print some informative comment=
s.
-  if (CommentStream) {
-    printAnnotation(OS, Annot);
+  if (CommentStream)
     EmitAnyX86InstComments(MI, *CommentStream, getRegisterName);
-  }
-}
-StringRef X86IntelInstPrinter::getOpcodeName(unsigned Opcode) const {
-  return getInstructionName(Opcode);
 }
=20
 void X86IntelInstPrinter::printSSECC(const MCInst *MI, unsigned Op,
                                      raw_ostream &O) {
   switch (MI->getOperand(Op).getImm()) {
-  default: assert(0 && "Invalid ssecc argument!");
-  case 0: O << "eq"; break;
-  case 1: O << "lt"; break;
-  case 2: O << "le"; break;
-  case 3: O << "unord"; break;
-  case 4: O << "neq"; break;
-  case 5: O << "nlt"; break;
-  case 6: O << "nle"; break;
-  case 7: O << "ord"; break;
+  default: llvm_unreachable("Invalid ssecc argument!");
+  case    0: O << "eq"; break;
+  case    1: O << "lt"; break;
+  case    2: O << "le"; break;
+  case    3: O << "unord"; break;
+  case    4: O << "neq"; break;
+  case    5: O << "nlt"; break;
+  case    6: O << "nle"; break;
+  case    7: O << "ord"; break;
+  case    8: O << "eq_uq"; break;
+  case    9: O << "nge"; break;
+  case  0xa: O << "ngt"; break;
+  case  0xb: O << "false"; break;
+  case  0xc: O << "neq_oq"; break;
+  case  0xd: O << "ge"; break;
+  case  0xe: O << "gt"; break;
+  case  0xf: O << "true"; break;
+  case 0x10: O << "eq_os"; break;
+  case 0x11: O << "lt_oq"; break;
+  case 0x12: O << "le_oq"; break;
+  case 0x13: O << "unord_s"; break;
+  case 0x14: O << "neq_us"; break;
+  case 0x15: O << "nlt_uq"; break;
+  case 0x16: O << "nle_uq"; break;
+  case 0x17: O << "ord_s"; break;
+  case 0x18: O << "eq_us"; break;
+  case 0x19: O << "nge_uq"; break;
+  case 0x1a: O << "ngt_uq"; break;
+  case 0x1b: O << "false_os"; break;
+  case 0x1c: O << "neq_os"; break;
+  case 0x1d: O << "ge_oq"; break;
+  case 0x1e: O << "gt_oq"; break;
+  case 0x1f: O << "true_us"; break;
+
   }
 }
=20
@@ -70,7 +91,18 @@
     O << Op.getImm();
   else {
     assert(Op.isExpr() && "unknown pcrel immediate operand");
-    O << *Op.getExpr();
+    // If a symbolic branch target was added as a constant expression then=
 print
+    // that address in hex.
+    const MCConstantExpr *BranchTarget =3D dyn_cast<MCConstantExpr>(Op.get=
Expr());
+    int64_t Address;
+    if (BranchTarget && BranchTarget->EvaluateAsAbsolute(Address)) {
+      O << "0x";
+      O.write_hex(Address);
+    }
+    else {
+      // Otherwise, just print the expression.
+      O << *Op.getExpr();
+    }
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/InstP=
rinter/X86IntelInstPrinter.h
--- a/head/contrib/llvm/lib/Target/X86/InstPrinter/X86IntelInstPrinter.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/InstPrinter/X86IntelInstPrinter.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86IntelInstPrinter.h - Convert X86 MCInst to assembly synta=
x -----=3D=3D=3D//
+//=3D X86IntelInstPrinter.h - Convert X86 MCInst to assembly syntax -*- C+=
+ -*-=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,17 +23,16 @@
  =20
 class X86IntelInstPrinter : public MCInstPrinter {
 public:
-  X86IntelInstPrinter(const MCAsmInfo &MAI)
-    : MCInstPrinter(MAI) {}
+  X86IntelInstPrinter(const MCAsmInfo &MAI, const MCInstrInfo &MII,
+                      const MCRegisterInfo &MRI)
+    : MCInstPrinter(MAI, MII, MRI) {}
=20
   virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
   virtual void printInst(const MCInst *MI, raw_ostream &OS, StringRef Anno=
t);
-  virtual StringRef getOpcodeName(unsigned Opcode) const;
  =20
   // Autogenerated by tblgen.
   void printInstruction(const MCInst *MI, raw_ostream &O);
   static const char *getRegisterName(unsigned RegNo);
-  static const char *getInstructionName(unsigned Opcode);
=20
   void printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O);
   void printMemReference(const MCInst *MI, unsigned Op, raw_ostream &O);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86AsmBackend.cpp
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86AsmBackend.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -7,10 +7,9 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "llvm/MC/MCAsmBackend.h"
 #include "MCTargetDesc/X86BaseInfo.h"
 #include "MCTargetDesc/X86FixupKinds.h"
-#include "llvm/ADT/Twine.h"
+#include "llvm/MC/MCAsmBackend.h"
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCELFObjectWriter.h"
 #include "llvm/MC/MCExpr.h"
@@ -37,18 +36,22 @@
=20
 static unsigned getFixupKindLog2Size(unsigned Kind) {
   switch (Kind) {
-  default: assert(0 && "invalid fixup kind!");
+  default: llvm_unreachable("invalid fixup kind!");
   case FK_PCRel_1:
+  case FK_SecRel_1:
   case FK_Data_1: return 0;
   case FK_PCRel_2:
+  case FK_SecRel_2:
   case FK_Data_2: return 1;
   case FK_PCRel_4:
   case X86::reloc_riprel_4byte:
   case X86::reloc_riprel_4byte_movq_load:
   case X86::reloc_signed_4byte:
   case X86::reloc_global_offset_table:
+  case FK_SecRel_4:
   case FK_Data_4: return 2;
   case FK_PCRel_8:
+  case FK_SecRel_8:
   case FK_Data_8: return 3;
   }
 }
@@ -57,9 +60,9 @@
=20
 class X86ELFObjectWriter : public MCELFObjectTargetWriter {
 public:
-  X86ELFObjectWriter(bool is64Bit, Triple::OSType OSType, uint16_t EMachin=
e,
-                     bool HasRelocationAddend)
-    : MCELFObjectTargetWriter(is64Bit, OSType, EMachine, HasRelocationAdde=
nd) {}
+  X86ELFObjectWriter(bool is64Bit, uint8_t OSABI, uint16_t EMachine,
+                     bool HasRelocationAddend, bool foobar)
+    : MCELFObjectTargetWriter(is64Bit, OSABI, EMachine, HasRelocationAdden=
d) {}
 };
=20
 class X86AsmBackend : public MCAsmBackend {
@@ -87,7 +90,7 @@
     return Infos[Kind - FirstTargetFixupKind];
   }
=20
-  void ApplyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
+  void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
                   uint64_t Value) const {
     unsigned Size =3D 1 << getFixupKindLog2Size(Fixup.getKind());
=20
@@ -105,11 +108,16 @@
       Data[Fixup.getOffset() + i] =3D uint8_t(Value >> (i * 8));
   }
=20
-  bool MayNeedRelaxation(const MCInst &Inst) const;
+  bool mayNeedRelaxation(const MCInst &Inst) const;
=20
-  void RelaxInstruction(const MCInst &Inst, MCInst &Res) const;
+  bool fixupNeedsRelaxation(const MCFixup &Fixup,
+                            uint64_t Value,
+                            const MCInstFragment *DF,
+                            const MCAsmLayout &Layout) const;
=20
-  bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const;
+  void relaxInstruction(const MCInst &Inst, MCInst &Res) const;
+
+  bool writeNopData(uint64_t Count, MCObjectWriter *OW) const;
 };
 } // end anonymous namespace
=20
@@ -214,7 +222,7 @@
   return getRelaxedOpcodeBranch(Op);
 }
=20
-bool X86AsmBackend::MayNeedRelaxation(const MCInst &Inst) const {
+bool X86AsmBackend::mayNeedRelaxation(const MCInst &Inst) const {
   // Branches can always be relaxed.
   if (getRelaxedOpcodeBranch(Inst.getOpcode()) !=3D Inst.getOpcode())
     return true;
@@ -244,9 +252,17 @@
   return hasExp && !hasRIP;
 }
=20
+bool X86AsmBackend::fixupNeedsRelaxation(const MCFixup &Fixup,
+                                         uint64_t Value,
+                                         const MCInstFragment *DF,
+                                         const MCAsmLayout &Layout) const {
+  // Relax if the value is too big for a (signed) i8.
+  return int64_t(Value) !=3D int64_t(int8_t(Value));
+}
+
 // FIXME: Can tblgen help at all here to verify there aren't other instruc=
tions
 // we can relax?
-void X86AsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) cons=
t {
+void X86AsmBackend::relaxInstruction(const MCInst &Inst, MCInst &Res) cons=
t {
   // The only relaxations X86 does is from a 1byte pcrel to a 4byte pcrel.
   unsigned RelaxedOp =3D getRelaxedOpcode(Inst.getOpcode());
=20
@@ -262,10 +278,10 @@
   Res.setOpcode(RelaxedOp);
 }
=20
-/// WriteNopData - Write optimal nops to the output file for the \arg Count
+/// writeNopData - Write optimal nops to the output file for the \arg Count
 /// bytes.  This returns the number of bytes written.  It may return 0 if
 /// the \arg Count is more than the maximum optimal nops.
-bool X86AsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const=
 {
+bool X86AsmBackend::writeNopData(uint64_t Count, MCObjectWriter *OW) const=
 {
   static const uint8_t Nops[10][10] =3D {
     // nop
     {0x90},
@@ -310,9 +326,9 @@
 namespace {
 class ELFX86AsmBackend : public X86AsmBackend {
 public:
-  Triple::OSType OSType;
-  ELFX86AsmBackend(const Target &T, Triple::OSType _OSType)
-    : X86AsmBackend(T), OSType(_OSType) {
+  uint8_t OSABI;
+  ELFX86AsmBackend(const Target &T, uint8_t _OSABI)
+    : X86AsmBackend(T), OSABI(_OSABI) {
     HasReliableSymbolDifference =3D true;
   }
=20
@@ -324,31 +340,21 @@
=20
 class ELFX86_32AsmBackend : public ELFX86AsmBackend {
 public:
-  ELFX86_32AsmBackend(const Target &T, Triple::OSType OSType)
-    : ELFX86AsmBackend(T, OSType) {}
+  ELFX86_32AsmBackend(const Target &T, uint8_t OSABI)
+    : ELFX86AsmBackend(T, OSABI) {}
=20
   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
-    return createELFObjectWriter(createELFObjectTargetWriter(),
-                                 OS, /*IsLittleEndian*/ true);
-  }
-
-  MCELFObjectTargetWriter *createELFObjectTargetWriter() const {
-    return new X86ELFObjectWriter(false, OSType, ELF::EM_386, false);
+    return createX86ELFObjectWriter(OS, /*Is64Bit*/ false, OSABI);
   }
 };
=20
 class ELFX86_64AsmBackend : public ELFX86AsmBackend {
 public:
-  ELFX86_64AsmBackend(const Target &T, Triple::OSType OSType)
-    : ELFX86AsmBackend(T, OSType) {}
+  ELFX86_64AsmBackend(const Target &T, uint8_t OSABI)
+    : ELFX86AsmBackend(T, OSABI) {}
=20
   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
-    return createELFObjectWriter(createELFObjectTargetWriter(),
-                                 OS, /*IsLittleEndian*/ true);
-  }
-
-  MCELFObjectTargetWriter *createELFObjectTargetWriter() const {
-    return new X86ELFObjectWriter(true, OSType, ELF::EM_X86_64, true);
+    return createX86ELFObjectWriter(OS, /*Is64Bit*/ true, OSABI);
   }
 };
=20
@@ -362,7 +368,7 @@
   }
=20
   MCObjectWriter *createObjectWriter(raw_ostream &OS) const {
-    return createWinCOFFObjectWriter(OS, Is64Bit);
+    return createX86WinCOFFObjectWriter(OS, Is64Bit);
   }
 };
=20
@@ -442,7 +448,8 @@
   if (TheTriple.isOSWindows())
     return new WindowsX86AsmBackend(T, false);
=20
-  return new ELFX86_32AsmBackend(T, TheTriple.getOS());
+  uint8_t OSABI =3D MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
+  return new ELFX86_32AsmBackend(T, OSABI);
 }
=20
 MCAsmBackend *llvm::createX86_64AsmBackend(const Target &T, StringRef TT) {
@@ -454,5 +461,6 @@
   if (TheTriple.isOSWindows())
     return new WindowsX86AsmBackend(T, true);
=20
-  return new ELFX86_64AsmBackend(T, TheTriple.getOS());
+  uint8_t OSABI =3D MCELFObjectTargetWriter::getOSABI(TheTriple.getOS());
+  return new ELFX86_64AsmBackend(T, OSABI);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86BaseInfo.h
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -19,7 +19,7 @@
=20
 #include "X86MCTargetDesc.h"
 #include "llvm/Support/DataTypes.h"
-#include <cassert>
+#include "llvm/Support/ErrorHandling.h"
=20
 namespace llvm {
=20
@@ -164,7 +164,13 @@
     /// is some TLS offset from the picbase.
     ///
     /// This is the 32-bit TLS offset for Darwin TLS in PIC mode.
-    MO_TLVP_PIC_BASE
+    MO_TLVP_PIC_BASE,
+
+    /// MO_SECREL - On a symbol operand this indicates that the immediate =
is
+    /// the offset from beginning of section.
+    ///
+    /// This is the TLS offset for the COFF/Windows TLS mechanism.
+    MO_SECREL
   };
=20
   enum {
@@ -223,19 +229,13 @@
     // destinations are the same register.
     MRMInitReg =3D 32,
=20
-    //// MRM_C1 - A mod/rm byte of exactly 0xC1.
-    MRM_C1 =3D 33,
-    MRM_C2 =3D 34,
-    MRM_C3 =3D 35,
-    MRM_C4 =3D 36,
-    MRM_C8 =3D 37,
-    MRM_C9 =3D 38,
-    MRM_E8 =3D 39,
-    MRM_F0 =3D 40,
-    MRM_F8 =3D 41,
-    MRM_F9 =3D 42,
-    MRM_D0 =3D 45,
-    MRM_D1 =3D 46,
+    //// MRM_XX - A mod/rm byte of exactly 0xXX.
+    MRM_C1 =3D 33, MRM_C2 =3D 34, MRM_C3 =3D 35, MRM_C4 =3D 36,
+    MRM_C8 =3D 37, MRM_C9 =3D 38, MRM_E8 =3D 39, MRM_F0 =3D 40,
+    MRM_F8 =3D 41, MRM_F9 =3D 42, MRM_D0 =3D 45, MRM_D1 =3D 46,
+    MRM_D4 =3D 47, MRM_D8 =3D 48, MRM_D9 =3D 49, MRM_DA =3D 50,
+    MRM_DB =3D 51, MRM_DC =3D 52, MRM_DD =3D 53, MRM_DE =3D 54,
+    MRM_DF =3D 55,
=20
     /// RawFrmImm8 - This is used for the ENTER instruction, which has two
     /// immediates, the first of which is a 16-bit immediate (specified by
@@ -295,8 +295,20 @@
     T8 =3D 13 << Op0Shift,  TA =3D 14 << Op0Shift,
     A6 =3D 15 << Op0Shift,  A7 =3D 16 << Op0Shift,
=20
-    // TF - Prefix before and after 0x0F
-    TF =3D 17 << Op0Shift,
+    // T8XD - Prefix before and after 0x0F. Combination of T8 and XD.
+    T8XD =3D 17 << Op0Shift,
+
+    // T8XS - Prefix before and after 0x0F. Combination of T8 and XS.
+    T8XS =3D 18 << Op0Shift,
+
+    // TAXD - Prefix before and after 0x0F. Combination of TA and XD.
+    TAXD =3D 19 << Op0Shift,
+
+    // XOP8 - Prefix to include use of imm byte.
+    XOP8 =3D 20 << Op0Shift,
+
+    // XOP9 - Prefix to exclude use of imm byte.
+    XOP9 =3D 21 << Op0Shift,
=20
     //=3D=3D=3D-----------------------------------------------------------=
-------=3D=3D=3D//
     // REX_W - REX prefixes are instruction prefixes used in 64-bit mode.
@@ -387,20 +399,24 @@
     /// and the additional register is encoded in VEX_VVVV prefix.
     VEX_4V      =3D 1U << 2,
=20
+    /// VEX_4VOp3 - Similar to VEX_4V, but used on instructions that encode
+    /// operand 3 with VEX.vvvv.
+    VEX_4VOp3   =3D 1U << 3,
+
     /// VEX_I8IMM - Specifies that the last register used in a AVX instruc=
tion,
     /// must be encoded in the i8 immediate field. This usually happens in
     /// instructions with 4 operands.
-    VEX_I8IMM   =3D 1U << 3,
+    VEX_I8IMM   =3D 1U << 4,
=20
     /// VEX_L - Stands for a bit in the VEX opcode prefix meaning the curr=
ent
     /// instruction uses 256-bit wide registers. This is usually auto dete=
cted
     /// if a VR256 register is used, but some AVX instructions also have t=
his
     /// field marked when using a f256 memory references.
-    VEX_L       =3D 1U << 4,
+    VEX_L       =3D 1U << 5,
=20
     // VEX_LIG - Specifies that this instruction ignores the L-bit in the =
VEX
     // prefix. Usually used for scalar instructions. Needed by disassemble=
r.
-    VEX_LIG     =3D 1U << 5,
+    VEX_LIG     =3D 1U << 6,
=20
     /// Has3DNow0F0FOpcode - This flag indicates that the instruction uses=
 the
     /// wacky 0x0F 0x0F prefix for 3DNow! instructions.  The manual docume=
nts
@@ -408,7 +424,15 @@
     /// storing a classifier in the imm8 field.  To simplify our implement=
ation,
     /// we handle this by storeing the classifier in the opcode field and =
using
     /// this flag to indicate that the encoder should do the wacky 3DNow! =
thing.
-    Has3DNow0F0FOpcode =3D 1U << 6
+    Has3DNow0F0FOpcode =3D 1U << 7,
+
+    /// MemOp4 - Used to indicate swapping of operand 3 and 4 to be encode=
d in
+    /// ModRM or I8IMM. This is used for FMA4 and XOP instructions.
+    MemOp4 =3D 1U << 8,
+
+    /// XOP - Opcode prefix used by XOP instructions.
+    XOP =3D 1U << 9
+
   };
=20
   // getBaseOpcodeFor - This function returns the "base" X86 opcode for the
@@ -426,7 +450,7 @@
   /// of the specified instruction.
   static inline unsigned getSizeOfImm(uint64_t TSFlags) {
     switch (TSFlags & X86II::ImmMask) {
-    default: assert(0 && "Unknown immediate size");
+    default: llvm_unreachable("Unknown immediate size");
     case X86II::Imm8:
     case X86II::Imm8PCRel:  return 1;
     case X86II::Imm16:
@@ -441,7 +465,7 @@
   /// TSFlags indicates that it is pc relative.
   static inline unsigned isImmPCRel(uint64_t TSFlags) {
     switch (TSFlags & X86II::ImmMask) {
-    default: assert(0 && "Unknown immediate size");
+    default: llvm_unreachable("Unknown immediate size");
     case X86II::Imm8PCRel:
     case X86II::Imm16PCRel:
     case X86II::Imm32PCRel:
@@ -462,10 +486,10 @@
   /// is duplicated in the MCInst (e.g. "EAX =3D addl EAX, [mem]") it is o=
nly
   /// counted as one operand.
   ///
-  static inline int getMemoryOperandNo(uint64_t TSFlags) {
+  static inline int getMemoryOperandNo(uint64_t TSFlags, unsigned Opcode) {
     switch (TSFlags & X86II::FormMask) {
-    case X86II::MRMInitReg:  assert(0 && "FIXME: Remove this form");
-    default: assert(0 && "Unknown FormMask value in getMemoryOperandNo!");
+    case X86II::MRMInitReg:  llvm_unreachable("FIXME: Remove this form");
+    default: llvm_unreachable("Unknown FormMask value in getMemoryOperandN=
o!");
     case X86II::Pseudo:
     case X86II::RawFrm:
     case X86II::AddRegFrm:
@@ -478,9 +502,12 @@
       return 0;
     case X86II::MRMSrcMem: {
       bool HasVEX_4V =3D (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
+      bool HasMemOp4 =3D (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
       unsigned FirstMemOp =3D 1;
       if (HasVEX_4V)
         ++FirstMemOp;// Skip the register source (which is encoded in VEX_=
VVVV).
+      if (HasMemOp4)
+        ++FirstMemOp;// Skip the register source (which is encoded in I8IM=
M).
=20
       // FIXME: Maybe lea should have its own form?  This is a horrible ha=
ck.
       //if (Opcode =3D=3D X86::LEA64r || Opcode =3D=3D X86::LEA64_32r ||
@@ -495,20 +522,24 @@
     case X86II::MRM0m: case X86II::MRM1m:
     case X86II::MRM2m: case X86II::MRM3m:
     case X86II::MRM4m: case X86II::MRM5m:
-    case X86II::MRM6m: case X86II::MRM7m:
-      return 0;
-    case X86II::MRM_C1:
-    case X86II::MRM_C2:
-    case X86II::MRM_C3:
-    case X86II::MRM_C4:
-    case X86II::MRM_C8:
-    case X86II::MRM_C9:
-    case X86II::MRM_E8:
-    case X86II::MRM_F0:
-    case X86II::MRM_F8:
-    case X86II::MRM_F9:
-    case X86II::MRM_D0:
-    case X86II::MRM_D1:
+    case X86II::MRM6m: case X86II::MRM7m: {
+      bool HasVEX_4V =3D (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
+      unsigned FirstMemOp =3D 0;
+      if (HasVEX_4V)
+        ++FirstMemOp;// Skip the register dest (which is encoded in VEX_VV=
VV).
+      return FirstMemOp;
+    }
+    case X86II::MRM_C1: case X86II::MRM_C2:
+    case X86II::MRM_C3: case X86II::MRM_C4:
+    case X86II::MRM_C8: case X86II::MRM_C9:
+    case X86II::MRM_E8: case X86II::MRM_F0:
+    case X86II::MRM_F8: case X86II::MRM_F9:
+    case X86II::MRM_D0: case X86II::MRM_D1:
+    case X86II::MRM_D4: case X86II::MRM_D8:
+    case X86II::MRM_D9: case X86II::MRM_DA:
+    case X86II::MRM_DB: case X86II::MRM_DC:
+    case X86II::MRM_DD: case X86II::MRM_DE:
+    case X86II::MRM_DF:
       return -1;
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86FixupKinds.h
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86FixupKinds.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86FixupKinds.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86/X86FixupKinds.h - X86 Specific Fixup Entries --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86FixupKinds.h - X86 Specific Fixup Entries ------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86MCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -48,6 +48,8 @@
   "{cc}", "cc",
   0,0};
=20
+void X86MCAsmInfoDarwin::anchor() { }
+
 X86MCAsmInfoDarwin::X86MCAsmInfoDarwin(const Triple &T) {
   bool is64Bit =3D T.getArch() =3D=3D Triple::x86_64;
   if (is64Bit)
@@ -80,6 +82,8 @@
   : X86MCAsmInfoDarwin(Triple) {
 }
=20
+void X86ELFMCAsmInfo::anchor() { }
+
 X86ELFMCAsmInfo::X86ELFMCAsmInfo(const Triple &T) {
   if (T.getArch() =3D=3D Triple::x86_64)
     PointerSize =3D 8;
@@ -125,7 +129,9 @@
                            0, SectionKind::getMetadata());
 }
=20
-X86MCAsmInfoCOFF::X86MCAsmInfoCOFF(const Triple &Triple) {
+void X86MCAsmInfoMicrosoft::anchor() { }
+
+X86MCAsmInfoMicrosoft::X86MCAsmInfoMicrosoft(const Triple &Triple) {
   if (Triple.getArch() =3D=3D Triple::x86_64) {
     GlobalPrefix =3D "";
     PrivateGlobalPrefix =3D ".L";
@@ -136,3 +142,20 @@
=20
   TextAlignFillValue =3D 0x90;
 }
+
+void X86MCAsmInfoGNUCOFF::anchor() { }
+
+X86MCAsmInfoGNUCOFF::X86MCAsmInfoGNUCOFF(const Triple &Triple) {
+  if (Triple.getArch() =3D=3D Triple::x86_64) {
+    GlobalPrefix =3D "";
+    PrivateGlobalPrefix =3D ".L";
+  }
+
+  AsmTransCBE =3D x86_asm_table;
+  AssemblerDialect =3D AsmWriterFlavor;
+
+  TextAlignFillValue =3D 0x90;
+
+  // Exceptions handling
+  ExceptionsType =3D ExceptionHandling::DwarfCFI;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86MCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCAsmInfo.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- X86MCAsmInfo.h - X86 asm properties -----------------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- X86MCAsmInfo.h - X86 asm properties --------------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -21,7 +21,9 @@
 namespace llvm {
   class Triple;
=20
-  struct X86MCAsmInfoDarwin : public MCAsmInfoDarwin {
+  class X86MCAsmInfoDarwin : public MCAsmInfoDarwin {
+    virtual void anchor();
+  public:
     explicit X86MCAsmInfoDarwin(const Triple &Triple);
   };
=20
@@ -33,13 +35,23 @@
                                 MCStreamer &Streamer) const;
   };
=20
-  struct X86ELFMCAsmInfo : public MCAsmInfo {
+  class X86ELFMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
+  public:
     explicit X86ELFMCAsmInfo(const Triple &Triple);
     virtual const MCSection *getNonexecutableStackSection(MCContext &Ctx) =
const;
   };
=20
-  struct X86MCAsmInfoCOFF : public MCAsmInfoCOFF {
-    explicit X86MCAsmInfoCOFF(const Triple &Triple);
+  class X86MCAsmInfoMicrosoft : public MCAsmInfoMicrosoft {
+    virtual void anchor();
+  public:
+    explicit X86MCAsmInfoMicrosoft(const Triple &Triple);
+  };
+
+  class X86MCAsmInfoGNUCOFF : public MCAsmInfoGNUCOFF {
+    virtual void anchor();
+  public:
+    explicit X86MCAsmInfoGNUCOFF(const Triple &Triple);
   };
 } // namespace llvm
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86MCCodeEmitter.cpp
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCCodeEmitter.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86/X86MCCodeEmitter.cpp - Convert X86 code to machine code =
-------=3D=3D=3D//
+//=3D=3D=3D-- X86MCCodeEmitter.cpp - Convert X86 code to machine code ----=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -46,6 +46,11 @@
     return (STI.getFeatureBits() & X86::Mode64Bit) !=3D 0;
   }
=20
+  bool is32BitMode() const {
+    // FIXME: Can tablegen auto-generate this?
+    return (STI.getFeatureBits() & X86::Mode64Bit) =3D=3D 0;
+  }
+
   static unsigned GetX86RegNum(const MCOperand &MO) {
     return X86_MC::getX86RegNum(MO.getReg());
   }
@@ -63,9 +68,8 @@
                                               unsigned OpNum) {
     unsigned SrcReg =3D MI.getOperand(OpNum).getReg();
     unsigned SrcRegNum =3D GetX86RegNum(MI.getOperand(OpNum));
-    if ((SrcReg >=3D X86::XMM8 && SrcReg <=3D X86::XMM15) ||
-        (SrcReg >=3D X86::YMM8 && SrcReg <=3D X86::YMM15))
-      SrcRegNum +=3D 8;
+    if (X86II::isX86_64ExtendedReg(SrcReg))
+      SrcRegNum |=3D 8;
=20
     // The registers represented through VEX_VVVV should
     // be encoded in 1's complement form.
@@ -86,7 +90,7 @@
     }
   }
=20
-  void EmitImmediate(const MCOperand &Disp,
+  void EmitImmediate(const MCOperand &Disp, SMLoc Loc,
                      unsigned ImmSize, MCFixupKind FixupKind,
                      unsigned &CurByte, raw_ostream &OS,
                      SmallVectorImpl<MCFixup> &Fixups,
@@ -155,9 +159,8 @@
   return MCFixup::getKindForSize(Size, isPCRel);
 }
=20
-/// Is32BitMemOperand - Return true if the specified instruction with a me=
mory
-/// operand should emit the 0x67 prefix byte in 64-bit mode due to a 32-bit
-/// memory operand.  Op specifies the operand # of the memoperand.
+/// Is32BitMemOperand - Return true if the specified instruction has
+/// a 32-bit memory operand. Op specifies the operand # of the memoperand.
 static bool Is32BitMemOperand(const MCInst &MI, unsigned Op) {
   const MCOperand &BaseReg  =3D MI.getOperand(Op+X86::AddrBaseReg);
   const MCOperand &IndexReg =3D MI.getOperand(Op+X86::AddrIndexReg);
@@ -170,28 +173,71 @@
   return false;
 }
=20
-/// StartsWithGlobalOffsetTable - Return true for the simple cases where t=
his
-/// expression starts with _GLOBAL_OFFSET_TABLE_. This is a needed to supp=
ort
-/// PIC on ELF i386 as that symbol is magic. We check only simple case that
+/// Is64BitMemOperand - Return true if the specified instruction has
+/// a 64-bit memory operand. Op specifies the operand # of the memoperand.
+#ifndef NDEBUG
+static bool Is64BitMemOperand(const MCInst &MI, unsigned Op) {
+  const MCOperand &BaseReg  =3D MI.getOperand(Op+X86::AddrBaseReg);
+  const MCOperand &IndexReg =3D MI.getOperand(Op+X86::AddrIndexReg);
+
+  if ((BaseReg.getReg() !=3D 0 &&
+       X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg()=
)) ||
+      (IndexReg.getReg() !=3D 0 &&
+       X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg(=
))))
+    return true;
+  return false;
+}
+#endif
+
+/// Is16BitMemOperand - Return true if the specified instruction has
+/// a 16-bit memory operand. Op specifies the operand # of the memoperand.
+static bool Is16BitMemOperand(const MCInst &MI, unsigned Op) {
+  const MCOperand &BaseReg  =3D MI.getOperand(Op+X86::AddrBaseReg);
+  const MCOperand &IndexReg =3D MI.getOperand(Op+X86::AddrIndexReg);
+
+  if ((BaseReg.getReg() !=3D 0 &&
+       X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg.getReg()=
)) ||
+      (IndexReg.getReg() !=3D 0 &&
+       X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg.getReg(=
))))
+    return true;
+  return false;
+}
+
+/// StartsWithGlobalOffsetTable - Check if this expression starts with
+///  _GLOBAL_OFFSET_TABLE_ and if it is of the form
+///  _GLOBAL_OFFSET_TABLE_-symbol. This is needed to support PIC on ELF
+/// i386 as _GLOBAL_OFFSET_TABLE_ is magical. We check only simple case th=
at
 /// are know to be used: _GLOBAL_OFFSET_TABLE_ by itself or at the start
 /// of a binary expression.
-static bool StartsWithGlobalOffsetTable(const MCExpr *Expr) {
+enum GlobalOffsetTableExprKind {
+  GOT_None,
+  GOT_Normal,
+  GOT_SymDiff
+};
+static GlobalOffsetTableExprKind
+StartsWithGlobalOffsetTable(const MCExpr *Expr) {
+  const MCExpr *RHS =3D 0;
   if (Expr->getKind() =3D=3D MCExpr::Binary) {
     const MCBinaryExpr *BE =3D static_cast<const MCBinaryExpr *>(Expr);
     Expr =3D BE->getLHS();
+    RHS =3D BE->getRHS();
   }
=20
   if (Expr->getKind() !=3D MCExpr::SymbolRef)
-    return false;
+    return GOT_None;
=20
   const MCSymbolRefExpr *Ref =3D static_cast<const MCSymbolRefExpr*>(Expr);
   const MCSymbol &S =3D Ref->getSymbol();
-  return S.getName() =3D=3D "_GLOBAL_OFFSET_TABLE_";
+  if (S.getName() !=3D "_GLOBAL_OFFSET_TABLE_")
+    return GOT_None;
+  if (RHS && RHS->getKind() =3D=3D MCExpr::SymbolRef)
+    return GOT_SymDiff;
+  return GOT_Normal;
 }
=20
 void X86MCCodeEmitter::
-EmitImmediate(const MCOperand &DispOp, unsigned Size, MCFixupKind FixupKin=
d,
-              unsigned &CurByte, raw_ostream &OS,
+EmitImmediate(const MCOperand &DispOp, SMLoc Loc, unsigned Size,
+              MCFixupKind FixupKind, unsigned &CurByte, raw_ostream &OS,
               SmallVectorImpl<MCFixup> &Fixups, int ImmOffset) const {
   const MCExpr *Expr =3D NULL;
   if (DispOp.isImm()) {
@@ -210,12 +256,21 @@
=20
   // If we have an immoffset, add it to the expression.
   if ((FixupKind =3D=3D FK_Data_4 ||
-       FixupKind =3D=3D MCFixupKind(X86::reloc_signed_4byte)) &&
-      StartsWithGlobalOffsetTable(Expr)) {
-    assert(ImmOffset =3D=3D 0);
+       FixupKind =3D=3D FK_Data_8 ||
+       FixupKind =3D=3D MCFixupKind(X86::reloc_signed_4byte))) {
+    GlobalOffsetTableExprKind Kind =3D StartsWithGlobalOffsetTable(Expr);
+    if (Kind !=3D GOT_None) {
+      assert(ImmOffset =3D=3D 0);
=20
-    FixupKind =3D MCFixupKind(X86::reloc_global_offset_table);
-    ImmOffset =3D CurByte;
+      FixupKind =3D MCFixupKind(X86::reloc_global_offset_table);
+      if (Kind =3D=3D GOT_Normal)
+        ImmOffset =3D CurByte;
+    } else if (Expr->getKind() =3D=3D MCExpr::SymbolRef) {
+      const MCSymbolRefExpr *Ref =3D static_cast<const MCSymbolRefExpr*>(E=
xpr);
+      if (Ref->getKind() =3D=3D MCSymbolRefExpr::VK_SECREL) {
+        FixupKind =3D MCFixupKind(FK_SecRel_4);
+      }
+    }
   }
=20
   // If the fixup is pc-relative, we need to bias the value to be relative=
 to
@@ -234,7 +289,7 @@
                                    Ctx);
=20
   // Emit a symbolic constant as a fixup and 4 zeros.
-  Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind));
+  Fixups.push_back(MCFixup::Create(CurByte, Expr, FixupKind, Loc));
   EmitConstant(0, Size, CurByte, OS);
 }
=20
@@ -270,7 +325,7 @@
     // expression to emit.
     int ImmSize =3D X86II::hasImm(TSFlags) ? X86II::getSizeOfImm(TSFlags) =
: 0;
=20
-    EmitImmediate(Disp, 4, MCFixupKind(FixupKind),
+    EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(FixupKind),
                   CurByte, OS, Fixups, -ImmSize);
     return;
   }
@@ -294,7 +349,7 @@
=20
     if (BaseReg =3D=3D 0) {          // [disp32]     in X86-32 mode
       EmitByte(ModRMByte(0, RegOpcodeField, 5), CurByte, OS);
-      EmitImmediate(Disp, 4, FK_Data_4, CurByte, OS, Fixups);
+      EmitImmediate(Disp, MI.getLoc(), 4, FK_Data_4, CurByte, OS, Fixups);
       return;
     }
=20
@@ -310,13 +365,13 @@
     // Otherwise, if the displacement fits in a byte, encode as [REG+disp8=
].
     if (Disp.isImm() && isDisp8(Disp.getImm())) {
       EmitByte(ModRMByte(1, RegOpcodeField, BaseRegNo), CurByte, OS);
-      EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
+      EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups);
       return;
     }
=20
     // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
     EmitByte(ModRMByte(2, RegOpcodeField, BaseRegNo), CurByte, OS);
-    EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, =
OS,
+    EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byt=
e), CurByte, OS,
                   Fixups);
     return;
   }
@@ -375,10 +430,10 @@
=20
   // Do we need to output a displacement?
   if (ForceDisp8)
-    EmitImmediate(Disp, 1, FK_Data_1, CurByte, OS, Fixups);
+    EmitImmediate(Disp, MI.getLoc(), 1, FK_Data_1, CurByte, OS, Fixups);
   else if (ForceDisp32 || Disp.getImm() !=3D 0)
-    EmitImmediate(Disp, 4, MCFixupKind(X86::reloc_signed_4byte), CurByte, =
OS,
-                  Fixups);
+    EmitImmediate(Disp, MI.getLoc(), 4, MCFixupKind(X86::reloc_signed_4byt=
e),
+                  CurByte, OS, Fixups);
 }
=20
 /// EmitVEXOpcodePrefix - AVX instructions are encoded using a opcode pref=
ix
@@ -387,9 +442,8 @@
                                            int MemOperand, const MCInst &M=
I,
                                            const MCInstrDesc &Desc,
                                            raw_ostream &OS) const {
-  bool HasVEX_4V =3D false;
-  if ((TSFlags >> X86II::VEXShift) & X86II::VEX_4V)
-    HasVEX_4V =3D true;
+  bool HasVEX_4V =3D (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
+  bool HasVEX_4VOp3 =3D (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
=20
   // VEX_R: opcode externsion equivalent to REX.R in
   // 1's complement (inverted) form
@@ -417,6 +471,9 @@
   // opcode extension, or ignored, depending on the opcode byte)
   unsigned char VEX_W =3D 0;
=20
+  // XOP: Use XOP prefix byte 0x8f instead of VEX.
+  unsigned char XOP =3D 0;
+
   // VEX_5M (VEX m-mmmmm field):
   //
   //  0b00000: Reserved for future use
@@ -424,7 +481,8 @@
   //  0b00010: implied 0F 38 leading opcode bytes
   //  0b00011: implied 0F 3A leading opcode bytes
   //  0b00100-0b11111: Reserved for future use
-  //
+  //  0b01000: XOP map select - 08h instructions with imm byte
+  //  0b10001: XOP map select - 09h instructions with no imm byte
   unsigned char VEX_5M =3D 0x1;
=20
   // VEX_4V (VEX vvvv field): a register specifier
@@ -455,27 +513,44 @@
   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
     VEX_W =3D 1;
=20
+  if ((TSFlags >> X86II::VEXShift) & X86II::XOP)
+    XOP =3D 1;
+
   if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
     VEX_L =3D 1;
=20
   switch (TSFlags & X86II::Op0Mask) {
-  default: assert(0 && "Invalid prefix!");
+  default: llvm_unreachable("Invalid prefix!");
   case X86II::T8:  // 0F 38
     VEX_5M =3D 0x2;
     break;
   case X86II::TA:  // 0F 3A
     VEX_5M =3D 0x3;
     break;
-  case X86II::TF:  // F2 0F 38
+  case X86II::T8XS: // F3 0F 38
+    VEX_PP =3D 0x2;
+    VEX_5M =3D 0x2;
+    break;
+  case X86II::T8XD: // F2 0F 38
     VEX_PP =3D 0x3;
     VEX_5M =3D 0x2;
     break;
+  case X86II::TAXD: // F2 0F 3A
+    VEX_PP =3D 0x3;
+    VEX_5M =3D 0x3;
+    break;
   case X86II::XS:  // F3 0F
     VEX_PP =3D 0x2;
     break;
   case X86II::XD:  // F2 0F
     VEX_PP =3D 0x3;
     break;
+  case X86II::XOP8:
+    VEX_5M =3D 0x8;
+    break;
+  case X86II::XOP9:
+    VEX_5M =3D 0x9;
+    break;
   case X86II::A6:  // Bypass: Not used by VEX
   case X86II::A7:  // Bypass: Not used by VEX
   case X86II::TB:  // Bypass: Not used by VEX
@@ -483,6 +558,7 @@
     break;  // No prefix!
   }
=20
+
   // Set the vector length to 256-bit if YMM0-YMM15 is used
   for (unsigned i =3D 0; i !=3D MI.getNumOperands(); ++i) {
     if (!MI.getOperand(i).isReg())
@@ -495,7 +571,7 @@
   // Classify VEX_B, VEX_4V, VEX_R, VEX_X
   unsigned CurOp =3D 0;
   switch (TSFlags & X86II::FormMask) {
-  case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
+  case X86II::MRMInitReg: llvm_unreachable("FIXME: Remove this!");
   case X86II::MRMDestMem: {
     // MRMDestMem instructions forms:
     //  MemAddr, src1(ModR/M)
@@ -516,41 +592,50 @@
       VEX_R =3D 0x0;
     break;
   }
-  case X86II::MRMSrcMem: {
+  case X86II::MRMSrcMem:
     // MRMSrcMem instructions forms:
     //  src1(ModR/M), MemAddr
     //  src1(ModR/M), src2(VEX_4V), MemAddr
     //  src1(ModR/M), MemAddr, imm8
     //  src1(ModR/M), MemAddr, src2(VEX_I8IMM)
     //
+    //  FMA4:
+    //  dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
+    //  dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
     if (X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
       VEX_R =3D 0x0;
=20
-    unsigned MemAddrOffset =3D 1;
-    if (HasVEX_4V) {
+    if (HasVEX_4V)
       VEX_4V =3D getVEXRegisterEncoding(MI, 1);
-      MemAddrOffset++;
-    }
=20
     if (X86II::isX86_64ExtendedReg(
-               MI.getOperand(MemAddrOffset+X86::AddrBaseReg).getReg()))
+               MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
       VEX_B =3D 0x0;
     if (X86II::isX86_64ExtendedReg(
-               MI.getOperand(MemAddrOffset+X86::AddrIndexReg).getReg()))
+               MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
+      VEX_X =3D 0x0;
+
+    if (HasVEX_4VOp3)
+      VEX_4V =3D getVEXRegisterEncoding(MI, X86::AddrNumOperands+1);
+    break;
+  case X86II::MRM0m: case X86II::MRM1m:
+  case X86II::MRM2m: case X86II::MRM3m:
+  case X86II::MRM4m: case X86II::MRM5m:
+  case X86II::MRM6m: case X86II::MRM7m: {
+    // MRM[0-9]m instructions forms:
+    //  MemAddr
+    //  src1(VEX_4V), MemAddr
+    if (HasVEX_4V)
+      VEX_4V =3D getVEXRegisterEncoding(MI, 0);
+
+    if (X86II::isX86_64ExtendedReg(
+               MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
+      VEX_B =3D 0x0;
+    if (X86II::isX86_64ExtendedReg(
+               MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
       VEX_X =3D 0x0;
     break;
   }
-  case X86II::MRM0m: case X86II::MRM1m:
-  case X86II::MRM2m: case X86II::MRM3m:
-  case X86II::MRM4m: case X86II::MRM5m:
-  case X86II::MRM6m: case X86II::MRM7m:
-    // MRM[0-9]m instructions forms:
-    //  MemAddr
-    if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrBaseReg).getReg(=
)))
-      VEX_B =3D 0x0;
-    if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrIndexReg).getReg=
()))
-      VEX_X =3D 0x0;
-    break;
   case X86II::MRMSrcReg:
     // MRMSrcReg instructions forms:
     //  dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
@@ -565,6 +650,9 @@
       VEX_4V =3D getVEXRegisterEncoding(MI, CurOp++);
     if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
       VEX_B =3D 0x0;
+    CurOp++;
+    if (HasVEX_4VOp3)
+      VEX_4V =3D getVEXRegisterEncoding(MI, CurOp);
     break;
   case X86II::MRMDestReg:
     // MRMDestReg instructions forms:
@@ -605,14 +693,14 @@
   //
   unsigned char LastByte =3D VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
=20
-  if (VEX_B && VEX_X && !VEX_W && (VEX_5M =3D=3D 1)) { // 2 byte VEX prefix
+  if (VEX_B && VEX_X && !VEX_W && !XOP && (VEX_5M =3D=3D 1)) { // 2 byte V=
EX prefix
     EmitByte(0xC5, CurByte, OS);
     EmitByte(LastByte | (VEX_R << 7), CurByte, OS);
     return;
   }
=20
   // 3 byte VEX prefix
-  EmitByte(0xC4, CurByte, OS);
+  EmitByte(XOP ? 0x8F : 0xC4, CurByte, OS);
   EmitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M, CurByte, OS);
   EmitByte(LastByte | (VEX_W << 7), CurByte, OS);
 }
@@ -647,7 +735,7 @@
   }
=20
   switch (TSFlags & X86II::FormMask) {
-  case X86II::MRMInitReg: assert(0 && "FIXME: Remove this!");
+  case X86II::MRMInitReg: llvm_unreachable("FIXME: Remove this!");
   case X86II::MRMSrcReg:
     if (MI.getOperand(0).isReg() &&
         X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
@@ -717,12 +805,12 @@
                                         const MCInst &MI,
                                         raw_ostream &OS) const {
   switch (TSFlags & X86II::SegOvrMask) {
-  default: assert(0 && "Invalid segment!");
+  default: llvm_unreachable("Invalid segment!");
   case 0:
     // No segment override, check for explicit one on memory operand.
     if (MemOperand !=3D -1) {   // If the instruction has a memory operand.
       switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
-      default: assert(0 && "Unknown segment register!");
+      default: llvm_unreachable("Unknown segment register!");
       case 0: break;
       case X86::CS: EmitByte(0x2E, CurByte, OS); break;
       case X86::SS: EmitByte(0x36, CurByte, OS); break;
@@ -763,8 +851,22 @@
     EmitByte(0xF3, CurByte, OS);
=20
   // Emit the address size opcode prefix as needed.
-  if ((TSFlags & X86II::AdSize) ||
-      (MemOperand !=3D -1 && is64BitMode() && Is32BitMemOperand(MI, MemOpe=
rand)))
+  bool need_address_override;
+  if (TSFlags & X86II::AdSize) {
+    need_address_override =3D true;
+  } else if (MemOperand =3D=3D -1) {
+    need_address_override =3D false;
+  } else if (is64BitMode()) {
+    assert(!Is16BitMemOperand(MI, MemOperand));
+    need_address_override =3D Is32BitMemOperand(MI, MemOperand);
+  } else if (is32BitMode()) {
+    assert(!Is64BitMemOperand(MI, MemOperand));
+    need_address_override =3D Is16BitMemOperand(MI, MemOperand);
+  } else {
+    need_address_override =3D false;
+  }
+
+  if (need_address_override)
     EmitByte(0x67, CurByte, OS);
=20
   // Emit the operand size opcode prefix as needed.
@@ -773,7 +875,7 @@
=20
   bool Need0FPrefix =3D false;
   switch (TSFlags & X86II::Op0Mask) {
-  default: assert(0 && "Invalid prefix!");
+  default: llvm_unreachable("Invalid prefix!");
   case 0: break;  // No prefix!
   case X86II::REP: break; // already handled.
   case X86II::TB:  // Two-byte opcode prefix
@@ -783,7 +885,15 @@
   case X86II::A7:  // 0F A7
     Need0FPrefix =3D true;
     break;
-  case X86II::TF: // F2 0F 38
+  case X86II::T8XS: // F3 0F 38
+    EmitByte(0xF3, CurByte, OS);
+    Need0FPrefix =3D true;
+    break;
+  case X86II::T8XD: // F2 0F 38
+    EmitByte(0xF2, CurByte, OS);
+    Need0FPrefix =3D true;
+    break;
+  case X86II::TAXD: // F2 0F 3A
     EmitByte(0xF2, CurByte, OS);
     Need0FPrefix =3D true;
     break;
@@ -818,10 +928,12 @@
=20
   // FIXME: Pull this up into previous switch if REX can be moved earlier.
   switch (TSFlags & X86II::Op0Mask) {
-  case X86II::TF:    // F2 0F 38
+  case X86II::T8XS:  // F3 0F 38
+  case X86II::T8XD:  // F2 0F 38
   case X86II::T8:    // 0F 38
     EmitByte(0x38, CurByte, OS);
     break;
+  case X86II::TAXD:  // F2 0F 3A
   case X86II::TA:    // 0F 3A
     EmitByte(0x3A, CurByte, OS);
     break;
@@ -859,18 +971,16 @@
   unsigned CurByte =3D 0;
=20
   // Is this instruction encoded using the AVX VEX prefix?
-  bool HasVEXPrefix =3D false;
+  bool HasVEXPrefix =3D (TSFlags >> X86II::VEXShift) & X86II::VEX;
=20
   // It uses the VEX.VVVV field?
-  bool HasVEX_4V =3D false;
-
-  if ((TSFlags >> X86II::VEXShift) & X86II::VEX)
-    HasVEXPrefix =3D true;
-  if ((TSFlags >> X86II::VEXShift) & X86II::VEX_4V)
-    HasVEX_4V =3D true;
+  bool HasVEX_4V =3D (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
+  bool HasVEX_4VOp3 =3D (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
+  bool HasMemOp4 =3D (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
+  const unsigned MemOp4_I8IMMOperand =3D 2;
=20
   // Determine where the memory operand starts, if present.
-  int MemoryOperand =3D X86II::getMemoryOperandNo(TSFlags);
+  int MemoryOperand =3D X86II::getMemoryOperandNo(TSFlags, Opcode);
   if (MemoryOperand !=3D -1) MemoryOperand +=3D CurOp;
=20
   if (!HasVEXPrefix)
@@ -886,27 +996,29 @@
   unsigned SrcRegNum =3D 0;
   switch (TSFlags & X86II::FormMask) {
   case X86II::MRMInitReg:
-    assert(0 && "FIXME: Remove this form when the JIT moves to MCCodeEmitt=
er!");
+    llvm_unreachable("FIXME: Remove this form when the JIT moves to MCCode=
Emitter!");
   default: errs() << "FORM: " << (TSFlags & X86II::FormMask) << "\n";
-    assert(0 && "Unknown FormMask value in X86MCCodeEmitter!");
+    llvm_unreachable("Unknown FormMask value in X86MCCodeEmitter!");
   case X86II::Pseudo:
-    assert(0 && "Pseudo instruction shouldn't be emitted");
+    llvm_unreachable("Pseudo instruction shouldn't be emitted");
   case X86II::RawFrm:
     EmitByte(BaseOpcode, CurByte, OS);
     break;
   case X86II::RawFrmImm8:
     EmitByte(BaseOpcode, CurByte, OS);
-    EmitImmediate(MI.getOperand(CurOp++),
+    EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
                   CurByte, OS, Fixups);
-    EmitImmediate(MI.getOperand(CurOp++), 1, FK_Data_1, CurByte, OS, Fixup=
s);
+    EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 1, FK_Data_1, CurBy=
te,
+                  OS, Fixups);
     break;
   case X86II::RawFrmImm16:
     EmitByte(BaseOpcode, CurByte, OS);
-    EmitImmediate(MI.getOperand(CurOp++),
+    EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
                   X86II::getSizeOfImm(TSFlags), getImmFixupKind(TSFlags),
                   CurByte, OS, Fixups);
-    EmitImmediate(MI.getOperand(CurOp++), 2, FK_Data_2, CurByte, OS, Fixup=
s);
+    EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(), 2, FK_Data_2, CurBy=
te,
+                  OS, Fixups);
     break;
=20
   case X86II::AddRegFrm:
@@ -940,9 +1052,16 @@
     if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
       SrcRegNum++;
=20
+    if(HasMemOp4) // Skip 2nd src (which is encoded in I8IMM)
+      SrcRegNum++;
+
     EmitRegModRMByte(MI.getOperand(SrcRegNum),
                      GetX86RegNum(MI.getOperand(CurOp)), CurByte, OS);
-    CurOp =3D SrcRegNum + 1;
+
+    // 2 operands skipped with HasMemOp4, comensate accordingly
+    CurOp =3D HasMemOp4 ? SrcRegNum : SrcRegNum + 1;
+    if (HasVEX_4VOp3)
+      ++CurOp;
     break;
=20
   case X86II::MRMSrcMem: {
@@ -952,12 +1071,16 @@
       ++AddrOperands;
       ++FirstMemOp;  // Skip the register source (which is encoded in VEX_=
VVVV).
     }
+    if(HasMemOp4) // Skip second register source (encoded in I8IMM)
+      ++FirstMemOp;
=20
     EmitByte(BaseOpcode, CurByte, OS);
=20
     EmitMemModRMByte(MI, FirstMemOp, GetX86RegNum(MI.getOperand(CurOp)),
                      TSFlags, CurByte, OS, Fixups);
     CurOp +=3D AddrOperands + 1;
+    if (HasVEX_4VOp3)
+      ++CurOp;
     break;
   }
=20
@@ -976,58 +1099,52 @@
   case X86II::MRM2m: case X86II::MRM3m:
   case X86II::MRM4m: case X86II::MRM5m:
   case X86II::MRM6m: case X86II::MRM7m:
+    if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
+      CurOp++;
     EmitByte(BaseOpcode, CurByte, OS);
     EmitMemModRMByte(MI, CurOp, (TSFlags & X86II::FormMask)-X86II::MRM0m,
                      TSFlags, CurByte, OS, Fixups);
     CurOp +=3D X86::AddrNumOperands;
     break;
-  case X86II::MRM_C1:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xC1, CurByte, OS);
-    break;
-  case X86II::MRM_C2:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xC2, CurByte, OS);
-    break;
-  case X86II::MRM_C3:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xC3, CurByte, OS);
-    break;
-  case X86II::MRM_C4:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xC4, CurByte, OS);
-    break;
-  case X86II::MRM_C8:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xC8, CurByte, OS);
-    break;
-  case X86II::MRM_C9:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xC9, CurByte, OS);
-    break;
-  case X86II::MRM_E8:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xE8, CurByte, OS);
-    break;
-  case X86II::MRM_F0:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xF0, CurByte, OS);
-    break;
-  case X86II::MRM_F8:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xF8, CurByte, OS);
-    break;
+  case X86II::MRM_C1: case X86II::MRM_C2:
+  case X86II::MRM_C3: case X86II::MRM_C4:
+  case X86II::MRM_C8: case X86II::MRM_C9:
+  case X86II::MRM_D0: case X86II::MRM_D1:
+  case X86II::MRM_D4: case X86II::MRM_D8:
+  case X86II::MRM_D9: case X86II::MRM_DA:
+  case X86II::MRM_DB: case X86II::MRM_DC:
+  case X86II::MRM_DD: case X86II::MRM_DE:
+  case X86II::MRM_DF: case X86II::MRM_E8:
+  case X86II::MRM_F0: case X86II::MRM_F8:
   case X86II::MRM_F9:
     EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xF9, CurByte, OS);
-    break;
-  case X86II::MRM_D0:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xD0, CurByte, OS);
-    break;
-  case X86II::MRM_D1:
-    EmitByte(BaseOpcode, CurByte, OS);
-    EmitByte(0xD1, CurByte, OS);
+
+    unsigned char MRM;
+    switch (TSFlags & X86II::FormMask) {
+    default: llvm_unreachable("Invalid Form");
+    case X86II::MRM_C1: MRM =3D 0xC1; break;
+    case X86II::MRM_C2: MRM =3D 0xC2; break;
+    case X86II::MRM_C3: MRM =3D 0xC3; break;
+    case X86II::MRM_C4: MRM =3D 0xC4; break;
+    case X86II::MRM_C8: MRM =3D 0xC8; break;
+    case X86II::MRM_C9: MRM =3D 0xC9; break;
+    case X86II::MRM_D0: MRM =3D 0xD0; break;
+    case X86II::MRM_D1: MRM =3D 0xD1; break;
+    case X86II::MRM_D4: MRM =3D 0xD4; break;
+    case X86II::MRM_D8: MRM =3D 0xD8; break;
+    case X86II::MRM_D9: MRM =3D 0xD9; break;
+    case X86II::MRM_DA: MRM =3D 0xDA; break;
+    case X86II::MRM_DB: MRM =3D 0xDB; break;
+    case X86II::MRM_DC: MRM =3D 0xDC; break;
+    case X86II::MRM_DD: MRM =3D 0xDD; break;
+    case X86II::MRM_DE: MRM =3D 0xDE; break;
+    case X86II::MRM_DF: MRM =3D 0xDF; break;
+    case X86II::MRM_E8: MRM =3D 0xE8; break;
+    case X86II::MRM_F0: MRM =3D 0xF0; break;
+    case X86II::MRM_F8: MRM =3D 0xF8; break;
+    case X86II::MRM_F9: MRM =3D 0xF9; break;
+    }
+    EmitByte(MRM, CurByte, OS);
     break;
   }
=20
@@ -1035,14 +1152,26 @@
   // according to the right size for the instruction.
   if (CurOp !=3D NumOps) {
     // The last source register of a 4 operand instruction in AVX is encod=
ed
-    // in bits[7:4] of a immediate byte, and bits[3:0] are ignored.
+    // in bits[7:4] of a immediate byte.
     if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM) {
-      const MCOperand &MO =3D MI.getOperand(CurOp++);
+      const MCOperand &MO =3D MI.getOperand(HasMemOp4 ? MemOp4_I8IMMOperand
+                                                   : CurOp);
+      CurOp++;
       bool IsExtReg =3D X86II::isX86_64ExtendedReg(MO.getReg());
       unsigned RegNum =3D (IsExtReg ? (1 << 7) : 0);
       RegNum |=3D GetX86RegNum(MO) << 4;
-      EmitImmediate(MCOperand::CreateImm(RegNum), 1, FK_Data_1, CurByte, O=
S,
-                    Fixups);
+      // If there is an additional 5th operand it must be an immediate, wh=
ich
+      // is encoded in bits[3:0]
+      if(CurOp !=3D NumOps) {
+        const MCOperand &MIMM =3D MI.getOperand(CurOp++);
+        if(MIMM.isImm()) {
+          unsigned Val =3D MIMM.getImm();
+          assert(Val < 16 && "Immediate operand value out of range");
+          RegNum |=3D Val;
+        }
+      }
+      EmitImmediate(MCOperand::CreateImm(RegNum), MI.getLoc(), 1, FK_Data_=
1,
+                    CurByte, OS, Fixups);
     } else {
       unsigned FixupKind;
       // FIXME: Is there a better way to know that we need a signed reloca=
tion?
@@ -1053,7 +1182,7 @@
         FixupKind =3D X86::reloc_signed_4byte;
       else
         FixupKind =3D getImmFixupKind(TSFlags);
-      EmitImmediate(MI.getOperand(CurOp++),
+      EmitImmediate(MI.getOperand(CurOp++), MI.getLoc(),
                     X86II::getSizeOfImm(TSFlags), MCFixupKind(FixupKind),
                     CurByte, OS, Fixups);
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86MCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86MCTargetDesc.cpp - X86 Target Descriptions -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86MCTargetDesc.cpp - X86 Target Descriptions --------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -24,6 +24,7 @@
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/Host.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 #define GET_REGINFO_MC_DESC
@@ -35,6 +36,10 @@
 #define GET_SUBTARGETINFO_MC_DESC
 #include "X86GenSubtargetInfo.inc"
=20
+#if _MSC_VER
+#include <intrin.h>
+#endif
+
 using namespace llvm;
=20
=20
@@ -45,10 +50,6 @@
     FS =3D "+64bit-mode";
   else
     FS =3D "-64bit-mode";
-  if (TheTriple.getOS() =3D=3D Triple::NativeClient)
-    FS +=3D ",+nacl-mode";
-  else
-    FS +=3D ",-nacl-mode";
   return FS;
 }
=20
@@ -76,6 +77,8 @@
     *rECX =3D registers[2];
     *rEDX =3D registers[3];
     return false;
+  #else
+    return true;
   #endif
 #elif defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M=
_IX86)
   #if defined(__GNUC__)
@@ -102,9 +105,81 @@
       mov   dword ptr [esi],edx
     }
     return false;
+  #else
+    return true;
   #endif
+#else
+  return true;
 #endif
+}
+
+/// GetCpuIDAndInfoEx - Execute the specified cpuid with subleaf and retur=
n the
+/// 4 values in the specified arguments.  If we can't run cpuid on the hos=
t,
+/// return true.
+bool X86_MC::GetCpuIDAndInfoEx(unsigned value, unsigned subleaf, unsigned =
*rEAX,
+                               unsigned *rEBX, unsigned *rECX, unsigned *r=
EDX) {
+#if defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
+  #if defined(__GNUC__)
+    // gcc desn't know cpuid would clobber ebx/rbx. Preseve it manually.
+    asm ("movq\t%%rbx, %%rsi\n\t"
+         "cpuid\n\t"
+         "xchgq\t%%rbx, %%rsi\n\t"
+         : "=3Da" (*rEAX),
+           "=3DS" (*rEBX),
+           "=3Dc" (*rECX),
+           "=3Dd" (*rEDX)
+         :  "a" (value),
+            "c" (subleaf));
+    return false;
+  #elif defined(_MSC_VER)
+    // __cpuidex was added in MSVC++ 9.0 SP1
+    #if (_MSC_VER > 1500) || (_MSC_VER =3D=3D 1500 && _MSC_FULL_VER >=3D 1=
50030729)
+      int registers[4];
+      __cpuidex(registers, value, subleaf);
+      *rEAX =3D registers[0];
+      *rEBX =3D registers[1];
+      *rECX =3D registers[2];
+      *rEDX =3D registers[3];
+      return false;
+    #else
+      return true;
+    #endif
+  #else
+    return true;
+  #endif
+#elif defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M=
_IX86)
+  #if defined(__GNUC__)
+    asm ("movl\t%%ebx, %%esi\n\t"
+         "cpuid\n\t"
+         "xchgl\t%%ebx, %%esi\n\t"
+         : "=3Da" (*rEAX),
+           "=3DS" (*rEBX),
+           "=3Dc" (*rECX),
+           "=3Dd" (*rEDX)
+         :  "a" (value),
+            "c" (subleaf));
+    return false;
+  #elif defined(_MSC_VER)
+    __asm {
+      mov   eax,value
+      mov   ecx,subleaf
+      cpuid
+      mov   esi,rEAX
+      mov   dword ptr [esi],eax
+      mov   esi,rEBX
+      mov   dword ptr [esi],ebx
+      mov   esi,rECX
+      mov   dword ptr [esi],ecx
+      mov   esi,rEDX
+      mov   dword ptr [esi],edx
+    }
+    return false;
+  #else
+    return true;
+  #endif
+#else
   return true;
+#endif
 }
=20
 void X86_MC::DetectFamilyModel(unsigned EAX, unsigned &Family,
@@ -261,7 +336,8 @@
=20
   std::string CPUName =3D CPU;
   if (CPUName.empty()) {
-#if defined (__x86_64__) || defined(__i386__)
+#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_I=
X86)\
+    || defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
     CPUName =3D sys::getHostCPUName();
 #else
     CPUName =3D "generic";
@@ -303,8 +379,10 @@
       MAI =3D new X86_64MCAsmInfoDarwin(TheTriple);
     else
       MAI =3D new X86MCAsmInfoDarwin(TheTriple);
-  } else if (TheTriple.isOSWindows()) {
-    MAI =3D new X86MCAsmInfoCOFF(TheTriple);
+  } else if (TheTriple.getOS() =3D=3D Triple::Win32) {
+    MAI =3D new X86MCAsmInfoMicrosoft(TheTriple);
+  } else if (TheTriple.getOS() =3D=3D Triple::MinGW32 || TheTriple.getOS()=
 =3D=3D Triple::Cygwin) {
+    MAI =3D new X86MCAsmInfoGNUCOFF(TheTriple);
   } else {
     MAI =3D new X86ELFMCAsmInfo(TheTriple);
   }
@@ -327,7 +405,8 @@
 }
=20
 static MCCodeGenInfo *createX86MCCodeGenInfo(StringRef TT, Reloc::Model RM,
-                                             CodeModel::Model CM) {
+                                             CodeModel::Model CM,
+                                             CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
=20
   Triple T(TT);
@@ -371,7 +450,7 @@
     // 64-bit JIT places everything in the same buffer except external fun=
cs.
     CM =3D is64Bit ? CodeModel::Large : CodeModel::Small;
=20
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
@@ -395,11 +474,13 @@
 static MCInstPrinter *createX86MCInstPrinter(const Target &T,
                                              unsigned SyntaxVariant,
                                              const MCAsmInfo &MAI,
+                                             const MCInstrInfo &MII,
+                                             const MCRegisterInfo &MRI,
                                              const MCSubtargetInfo &STI) {
   if (SyntaxVariant =3D=3D 0)
-    return new X86ATTInstPrinter(MAI);
+    return new X86ATTInstPrinter(MAI, MII, MRI);
   if (SyntaxVariant =3D=3D 1)
-    return new X86IntelInstPrinter(MAI);
+    return new X86IntelInstPrinter(MAI, MII, MRI);
   return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/MCTar=
getDesc/X86MCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -54,6 +54,11 @@
   /// the specified arguments.  If we can't run cpuid on the host, return =
true.
   bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX,
                        unsigned *rEBX, unsigned *rECX, unsigned *rEDX);
+  /// GetCpuIDAndInfoEx - Execute the specified cpuid with subleaf and ret=
urn
+  /// the 4 values in the specified arguments.  If we can't run cpuid on t=
he
+  /// host, return true.
+  bool GetCpuIDAndInfoEx(unsigned value, unsigned subleaf, unsigned *rEAX,
+                       unsigned *rEBX, unsigned *rECX, unsigned *rEDX);
=20
   void DetectFamilyModel(unsigned EAX, unsigned &Family, unsigned &Model);
=20
@@ -83,6 +88,12 @@
                                           uint32_t CPUType,
                                           uint32_t CPUSubtype);
=20
+/// createX86ELFObjectWriter - Construct an X86 ELF object writer.
+MCObjectWriter *createX86ELFObjectWriter(raw_ostream &OS,
+                                         bool Is64Bit,
+                                         uint8_t OSABI);
+/// createX86WinCOFFObjectWriter - Construct an X86 Win COFF object writer.
+MCObjectWriter *createX86WinCOFFObjectWriter(raw_ostream &OS, bool Is64Bit=
);
 } // End llvm namespace
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/Utils=
/X86ShuffleDecode.cpp
--- a/head/contrib/llvm/lib/Target/X86/Utils/X86ShuffleDecode.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/Utils/X86ShuffleDecode.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -20,7 +20,7 @@
=20
 namespace llvm {
=20
-void DecodeINSERTPSMask(unsigned Imm, SmallVectorImpl<unsigned> &ShuffleMa=
sk) {
+void DecodeINSERTPSMask(unsigned Imm, SmallVectorImpl<int> &ShuffleMask) {
   // Defaults the copying the dest value.
   ShuffleMask.push_back(0);
   ShuffleMask.push_back(1);
@@ -44,8 +44,7 @@
 }
=20
 // <3,1> or <6,7,2,3>
-void DecodeMOVHLPSMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
+void DecodeMOVHLPSMask(unsigned NElts, SmallVectorImpl<int> &ShuffleMask) {
   for (unsigned i =3D NElts/2; i !=3D NElts; ++i)
     ShuffleMask.push_back(NElts+i);
=20
@@ -54,8 +53,7 @@
 }
=20
 // <0,2> or <0,1,4,5>
-void DecodeMOVLHPSMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
+void DecodeMOVLHPSMask(unsigned NElts, SmallVectorImpl<int> &ShuffleMask) {
   for (unsigned i =3D 0; i !=3D NElts/2; ++i)
     ShuffleMask.push_back(i);
=20
@@ -63,16 +61,26 @@
     ShuffleMask.push_back(NElts+i);
 }
=20
-void DecodePSHUFMask(unsigned NElts, unsigned Imm,
-                     SmallVectorImpl<unsigned> &ShuffleMask) {
-  for (unsigned i =3D 0; i !=3D NElts; ++i) {
-    ShuffleMask.push_back(Imm % NElts);
-    Imm /=3D NElts;
+/// DecodePSHUFMask - This decodes the shuffle masks for pshufd, and vperm=
ilp*.
+/// VT indicates the type of the vector allowing it to handle different
+/// datatypes and vector widths.
+void DecodePSHUFMask(EVT VT, unsigned Imm, SmallVectorImpl<int> &ShuffleMa=
sk) {
+  unsigned NumElts =3D VT.getVectorNumElements();
+
+  unsigned NumLanes =3D VT.getSizeInBits() / 128;
+  unsigned NumLaneElts =3D NumElts / NumLanes;
+
+  int NewImm =3D Imm;
+  for (unsigned l =3D 0; l !=3D NumElts; l +=3D NumLaneElts) {
+    for (unsigned i =3D 0; i !=3D NumLaneElts; ++i) {
+      ShuffleMask.push_back(NewImm % NumLaneElts + l);
+      NewImm /=3D NumLaneElts;
+    }
+    if (NumLaneElts =3D=3D 4) NewImm =3D Imm; // reload imm
   }
 }
=20
-void DecodePSHUFHWMask(unsigned Imm,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
+void DecodePSHUFHWMask(unsigned Imm, SmallVectorImpl<int> &ShuffleMask) {
   ShuffleMask.push_back(0);
   ShuffleMask.push_back(1);
   ShuffleMask.push_back(2);
@@ -83,8 +91,7 @@
   }
 }
=20
-void DecodePSHUFLWMask(unsigned Imm,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
+void DecodePSHUFLWMask(unsigned Imm, SmallVectorImpl<int> &ShuffleMask) {
   for (unsigned i =3D 0; i !=3D 4; ++i) {
     ShuffleMask.push_back((Imm & 3));
     Imm >>=3D 2;
@@ -95,76 +102,35 @@
   ShuffleMask.push_back(7);
 }
=20
-void DecodePUNPCKLBWMask(unsigned NElts,
-                         SmallVectorImpl<unsigned> &ShuffleMask) {
-  DecodeUNPCKLPMask(MVT::getVectorVT(MVT::i8, NElts), ShuffleMask);
-}
+/// DecodeSHUFPMask - This decodes the shuffle masks for shufp*. VT indica=
tes
+/// the type of the vector allowing it to handle different datatypes and v=
ector
+/// widths.
+void DecodeSHUFPMask(EVT VT, unsigned Imm, SmallVectorImpl<int> &ShuffleMa=
sk) {
+  unsigned NumElts =3D VT.getVectorNumElements();
=20
-void DecodePUNPCKLWDMask(unsigned NElts,
-                         SmallVectorImpl<unsigned> &ShuffleMask) {
-  DecodeUNPCKLPMask(MVT::getVectorVT(MVT::i16, NElts), ShuffleMask);
-}
+  unsigned NumLanes =3D VT.getSizeInBits() / 128;
+  unsigned NumLaneElts =3D NumElts / NumLanes;
=20
-void DecodePUNPCKLDQMask(unsigned NElts,
-                         SmallVectorImpl<unsigned> &ShuffleMask) {
-  DecodeUNPCKLPMask(MVT::getVectorVT(MVT::i32, NElts), ShuffleMask);
-}
-
-void DecodePUNPCKLQDQMask(unsigned NElts,
-                          SmallVectorImpl<unsigned> &ShuffleMask) {
-  DecodeUNPCKLPMask(MVT::getVectorVT(MVT::i64, NElts), ShuffleMask);
-}
-
-void DecodePUNPCKLMask(EVT VT,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
-  DecodeUNPCKLPMask(VT, ShuffleMask);
-}
-
-void DecodePUNPCKHMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
-  for (unsigned i =3D 0; i !=3D NElts/2; ++i) {
-    ShuffleMask.push_back(i+NElts/2);
-    ShuffleMask.push_back(i+NElts+NElts/2);
+  int NewImm =3D Imm;
+  for (unsigned l =3D 0; l !=3D NumElts; l +=3D NumLaneElts) {
+    // Part that reads from dest.
+    for (unsigned i =3D 0; i !=3D NumLaneElts/2; ++i) {
+      ShuffleMask.push_back(NewImm % NumLaneElts + l);
+      NewImm /=3D NumLaneElts;
+    }
+    // Part that reads from src.
+    for (unsigned i =3D 0; i !=3D NumLaneElts/2; ++i) {
+      ShuffleMask.push_back(NewImm % NumLaneElts + NumElts + l);
+      NewImm /=3D NumLaneElts;
+    }
+    if (NumLaneElts =3D=3D 4) NewImm =3D Imm; // reload imm
   }
 }
=20
-void DecodeSHUFPSMask(unsigned NElts, unsigned Imm,
-                      SmallVectorImpl<unsigned> &ShuffleMask) {
-  // Part that reads from dest.
-  for (unsigned i =3D 0; i !=3D NElts/2; ++i) {
-    ShuffleMask.push_back(Imm % NElts);
-    Imm /=3D NElts;
-  }
-  // Part that reads from src.
-  for (unsigned i =3D 0; i !=3D NElts/2; ++i) {
-    ShuffleMask.push_back(Imm % NElts + NElts);
-    Imm /=3D NElts;
-  }
-}
-
-void DecodeUNPCKHPMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
-  for (unsigned i =3D 0; i !=3D NElts/2; ++i) {
-    ShuffleMask.push_back(i+NElts/2);        // Reads from dest
-    ShuffleMask.push_back(i+NElts+NElts/2);  // Reads from src
-  }
-}
-
-void DecodeUNPCKLPSMask(unsigned NElts,
-                        SmallVectorImpl<unsigned> &ShuffleMask) {
-  DecodeUNPCKLPMask(MVT::getVectorVT(MVT::i32, NElts), ShuffleMask);
-}
-
-void DecodeUNPCKLPDMask(unsigned NElts,
-                        SmallVectorImpl<unsigned> &ShuffleMask) {
-  DecodeUNPCKLPMask(MVT::getVectorVT(MVT::i64, NElts), ShuffleMask);
-}
-
-/// DecodeUNPCKLPMask - This decodes the shuffle masks for unpcklps/unpckl=
pd
-/// etc.  VT indicates the type of the vector allowing it to handle differ=
ent
-/// datatypes and vector widths.
-void DecodeUNPCKLPMask(EVT VT,
-                       SmallVectorImpl<unsigned> &ShuffleMask) {
+/// DecodeUNPCKHMask - This decodes the shuffle masks for unpckhps/unpckhpd
+/// and punpckh*. VT indicates the type of the vector allowing it to handle
+/// different datatypes and vector widths.
+void DecodeUNPCKHMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
   unsigned NumElts =3D VT.getVectorNumElements();
=20
   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
@@ -173,55 +139,36 @@
   if (NumLanes =3D=3D 0 ) NumLanes =3D 1;  // Handle MMX
   unsigned NumLaneElts =3D NumElts / NumLanes;
=20
-  unsigned Start =3D 0;
-  unsigned End =3D NumLaneElts / 2;
-  for (unsigned s =3D 0; s < NumLanes; ++s) {
-    for (unsigned i =3D Start; i !=3D End; ++i) {
-      ShuffleMask.push_back(i);                 // Reads from dest/src1
-      ShuffleMask.push_back(i+NumLaneElts);  // Reads from src/src2
-    }
-    // Process the next 128 bits.
-    Start +=3D NumLaneElts;
-    End +=3D NumLaneElts;
-  }
-}
-
-// DecodeVPERMILPSMask - Decodes VPERMILPS permutes for any 128-bit 32-bit
-// elements. For 256-bit vectors, it's considered as two 128 lanes, the
-// referenced elements can't cross lanes and the mask of the first lane mu=
st
-// be the same of the second.
-void DecodeVPERMILPSMask(unsigned NumElts, unsigned Imm,
-                         SmallVectorImpl<unsigned> &ShuffleMask) {
-  unsigned NumLanes =3D (NumElts*32)/128;
-  unsigned LaneSize =3D NumElts/NumLanes;
-
-  for (unsigned l =3D 0; l !=3D NumLanes; ++l) {
-    for (unsigned i =3D 0; i !=3D LaneSize; ++i) {
-      unsigned Idx =3D (Imm >> (i*2)) & 0x3 ;
-      ShuffleMask.push_back(Idx+(l*LaneSize));
+  for (unsigned l =3D 0; l !=3D NumElts; l +=3D NumLaneElts) {
+    for (unsigned i =3D l + NumLaneElts/2, e =3D l + NumLaneElts; i !=3D e=
; ++i) {
+      ShuffleMask.push_back(i);          // Reads from dest/src1
+      ShuffleMask.push_back(i+NumElts);  // Reads from src/src2
     }
   }
 }
=20
-// DecodeVPERMILPDMask - Decodes VPERMILPD permutes for any 128-bit 64-bit
-// elements. For 256-bit vectors, it's considered as two 128 lanes, the
-// referenced elements can't cross lanes but the mask of the first lane can
-// be the different of the second (not like VPERMILPS).
-void DecodeVPERMILPDMask(unsigned NumElts, unsigned Imm,
-                         SmallVectorImpl<unsigned> &ShuffleMask) {
-  unsigned NumLanes =3D (NumElts*64)/128;
-  unsigned LaneSize =3D NumElts/NumLanes;
+/// DecodeUNPCKLMask - This decodes the shuffle masks for unpcklps/unpcklpd
+/// and punpckl*. VT indicates the type of the vector allowing it to handle
+/// different datatypes and vector widths.
+void DecodeUNPCKLMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
+  unsigned NumElts =3D VT.getVectorNumElements();
=20
-  for (unsigned l =3D 0; l < NumLanes; ++l) {
-    for (unsigned i =3D l*LaneSize; i < LaneSize*(l+1); ++i) {
-      unsigned Idx =3D (Imm >> i) & 0x1;
-      ShuffleMask.push_back(Idx+(l*LaneSize));
+  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
+  // independently on 128-bit lanes.
+  unsigned NumLanes =3D VT.getSizeInBits() / 128;
+  if (NumLanes =3D=3D 0 ) NumLanes =3D 1;  // Handle MMX
+  unsigned NumLaneElts =3D NumElts / NumLanes;
+
+  for (unsigned l =3D 0; l !=3D NumElts; l +=3D NumLaneElts) {
+    for (unsigned i =3D l, e =3D l + NumLaneElts/2; i !=3D e; ++i) {
+      ShuffleMask.push_back(i);          // Reads from dest/src1
+      ShuffleMask.push_back(i+NumElts);  // Reads from src/src2
     }
   }
 }
=20
-void DecodeVPERM2F128Mask(EVT VT, unsigned Imm,
-                          SmallVectorImpl<unsigned> &ShuffleMask) {
+void DecodeVPERM2X128Mask(EVT VT, unsigned Imm,
+                          SmallVectorImpl<int> &ShuffleMask) {
   unsigned HalfSize =3D VT.getVectorNumElements()/2;
   unsigned FstHalfBegin =3D (Imm & 0x3) * HalfSize;
   unsigned SndHalfBegin =3D ((Imm >> 4) & 0x3) * HalfSize;
@@ -232,12 +179,4 @@
     ShuffleMask.push_back(i);
 }
=20
-void DecodeVPERM2F128Mask(unsigned Imm,
-                          SmallVectorImpl<unsigned> &ShuffleMask) {
-  // VPERM2F128 is used by any 256-bit EVT, but X86InstComments only
-  // has information about the instruction and not the types. So for
-  // instruction comments purpose, assume the 256-bit vector is v4i64.
-  return DecodeVPERM2F128Mask(MVT::v4i64, Imm, ShuffleMask);
-}
-
 } // llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/Utils=
/X86ShuffleDecode.h
--- a/head/contrib/llvm/lib/Target/X86/Utils/X86ShuffleDecode.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/Utils/X86ShuffleDecode.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -24,83 +24,41 @@
=20
 namespace llvm {
 enum {
-  SM_SentinelZero =3D ~0U
+  SM_SentinelZero =3D -1
 };
=20
-void DecodeINSERTPSMask(unsigned Imm, SmallVectorImpl<unsigned> &ShuffleMa=
sk);
+void DecodeINSERTPSMask(unsigned Imm, SmallVectorImpl<int> &ShuffleMask);
=20
 // <3,1> or <6,7,2,3>
-void DecodeMOVHLPSMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
+void DecodeMOVHLPSMask(unsigned NElts, SmallVectorImpl<int> &ShuffleMask);
=20
 // <0,2> or <0,1,4,5>
-void DecodeMOVLHPSMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
+void DecodeMOVLHPSMask(unsigned NElts, SmallVectorImpl<int> &ShuffleMask);
=20
-void DecodePSHUFMask(unsigned NElts, unsigned Imm,
-                     SmallVectorImpl<unsigned> &ShuffleMask);
+void DecodePSHUFMask(EVT VT, unsigned Imm, SmallVectorImpl<int> &ShuffleMa=
sk);
=20
-void DecodePSHUFHWMask(unsigned Imm,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
+void DecodePSHUFHWMask(unsigned Imm, SmallVectorImpl<int> &ShuffleMask);
=20
-void DecodePSHUFLWMask(unsigned Imm,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
+void DecodePSHUFLWMask(unsigned Imm, SmallVectorImpl<int> &ShuffleMask);
=20
-void DecodePUNPCKLBWMask(unsigned NElts,
-                         SmallVectorImpl<unsigned> &ShuffleMask);
+/// DecodeSHUFPMask - This decodes the shuffle masks for shufp*. VT indica=
tes
+/// the type of the vector allowing it to handle different datatypes and v=
ector
+/// widths.
+void DecodeSHUFPMask(EVT VT, unsigned Imm, SmallVectorImpl<int> &ShuffleMa=
sk);
=20
-void DecodePUNPCKLWDMask(unsigned NElts,
-                         SmallVectorImpl<unsigned> &ShuffleMask);
+/// DecodeUNPCKHMask - This decodes the shuffle masks for unpckhps/unpckhpd
+/// and punpckh*. VT indicates the type of the vector allowing it to handle
+/// different datatypes and vector widths.
+void DecodeUNPCKHMask(EVT VT, SmallVectorImpl<int> &ShuffleMask);
=20
-void DecodePUNPCKLDQMask(unsigned NElts,
-                         SmallVectorImpl<unsigned> &ShuffleMask);
+/// DecodeUNPCKLMask - This decodes the shuffle masks for unpcklps/unpcklpd
+/// and punpckl*. VT indicates the type of the vector allowing it to handle
+/// different datatypes and vector widths.
+void DecodeUNPCKLMask(EVT VT, SmallVectorImpl<int> &ShuffleMask);
=20
-void DecodePUNPCKLQDQMask(unsigned NElts,
-                          SmallVectorImpl<unsigned> &ShuffleMask);
=20
-void DecodePUNPCKLMask(EVT VT,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
-
-void DecodePUNPCKHMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
-
-void DecodeSHUFPSMask(unsigned NElts, unsigned Imm,
-                      SmallVectorImpl<unsigned> &ShuffleMask);
-
-void DecodeUNPCKHPMask(unsigned NElts,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
-
-void DecodeUNPCKLPSMask(unsigned NElts,
-                        SmallVectorImpl<unsigned> &ShuffleMask);
-
-void DecodeUNPCKLPDMask(unsigned NElts,
-                        SmallVectorImpl<unsigned> &ShuffleMask);
-
-/// DecodeUNPCKLPMask - This decodes the shuffle masks for unpcklps/unpckl=
pd
-/// etc.  VT indicates the type of the vector allowing it to handle differ=
ent
-/// datatypes and vector widths.
-void DecodeUNPCKLPMask(EVT VT,
-                       SmallVectorImpl<unsigned> &ShuffleMask);
-
-
-// DecodeVPERMILPSMask - Decodes VPERMILPS permutes for any 128-bit 32-bit
-// elements. For 256-bit vectors, it's considered as two 128 lanes, the
-// referenced elements can't cross lanes and the mask of the first lane mu=
st
-// be the same of the second.
-void DecodeVPERMILPSMask(unsigned NElts, unsigned Imm,
-                        SmallVectorImpl<unsigned> &ShuffleMask);
-
-// DecodeVPERMILPDMask - Decodes VPERMILPD permutes for any 128-bit 64-bit
-// elements. For 256-bit vectors, it's considered as two 128 lanes, the
-// referenced elements can't cross lanes but the mask of the first lane can
-// be the different of the second (not like VPERMILPS).
-void DecodeVPERMILPDMask(unsigned NElts, unsigned Imm,
-                        SmallVectorImpl<unsigned> &ShuffleMask);
-
-void DecodeVPERM2F128Mask(unsigned Imm,
-                          SmallVectorImpl<unsigned> &ShuffleMask);
-void DecodeVPERM2F128Mask(EVT VT, unsigned Imm,
-                          SmallVectorImpl<unsigned> &ShuffleMask);
+void DecodeVPERM2X128Mask(EVT VT, unsigned Imm,
+                          SmallVectorImpl<int> &ShuffleMask);
=20
 } // llvm namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86.h
--- a/head/contrib/llvm/lib/Target/X86/X86.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,8 +24,6 @@
=20
 class FunctionPass;
 class JITCodeEmitter;
-class MachineCodeEmitter;
-class Target;
 class X86TargetMachine;
=20
 /// createX86ISelDag - This pass converts a legalized DAG into a=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86.td
--- a/head/contrib/llvm/lib/Target/X86/X86.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86.td	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86.td - Target definition file for the Intel X86 ---*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- X86.td - Target definition file for the Intel X86 --*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -23,9 +23,6 @@
 def Mode64Bit : SubtargetFeature<"64bit-mode", "In64BitMode", "true",
                                   "64-bit mode (x86_64)">;
=20
-def ModeNaCl  : SubtargetFeature<"nacl-mode", "InNaClMode", "true",
-                                 "Native Client mode">;
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // X86 Subtarget features.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -58,7 +55,7 @@
                                       [FeatureSSSE3]>;
 def FeatureSSE42   : SubtargetFeature<"sse42", "X86SSELevel", "SSE42",
                                       "Enable SSE 4.2 instructions",
-                                      [FeatureSSE41, FeaturePOPCNT]>;
+                                      [FeatureSSE41]>;
 def Feature3DNow   : SubtargetFeature<"3dnow", "X863DNowLevel", "ThreeDNow=
",
                                       "Enable 3DNow! instructions",
                                       [FeatureMMX]>;
@@ -81,16 +78,24 @@
                                         "Fast unaligned memory access">;
 def FeatureSSE4A   : SubtargetFeature<"sse4a", "HasSSE4A", "true",
                                       "Support SSE 4a instructions",
-                                      [FeaturePOPCNT]>;
+                                      [FeatureSSE3]>;
=20
-def FeatureAVX     : SubtargetFeature<"avx", "HasAVX", "true",
-                                      "Enable AVX instructions">;
+def FeatureAVX     : SubtargetFeature<"avx", "X86SSELevel", "AVX",
+                                      "Enable AVX instructions",
+                                      [FeatureSSE42]>;
+def FeatureAVX2    : SubtargetFeature<"avx2", "X86SSELevel", "AVX2",
+                                      "Enable AVX2 instructions",
+                                      [FeatureAVX]>;
 def FeatureCLMUL   : SubtargetFeature<"clmul", "HasCLMUL", "true",
                                "Enable carry-less multiplication instructi=
ons">;
 def FeatureFMA3    : SubtargetFeature<"fma3", "HasFMA3", "true",
-                                     "Enable three-operand fused multiple-=
add">;
+                                      "Enable three-operand fused multiple=
-add",
+                                      [FeatureAVX]>;
 def FeatureFMA4    : SubtargetFeature<"fma4", "HasFMA4", "true",
-                                      "Enable four-operand fused multiple-=
add">;
+                                      "Enable four-operand fused multiple-=
add",
+                                      [FeatureAVX]>;
+def FeatureXOP     : SubtargetFeature<"xop", "HasXOP", "true",
+                                      "Enable XOP instructions">;
 def FeatureVectorUAMem : SubtargetFeature<"vector-unaligned-mem",
                                           "HasVectorUAMem", "true",
                  "Allow unaligned memory operands on vector/SIMD instructi=
ons">;
@@ -102,17 +107,31 @@
                                       "Support RDRAND instruction">;
 def FeatureF16C    : SubtargetFeature<"f16c", "HasF16C", "true",
                        "Support 16-bit floating point conversion instructi=
ons">;
+def FeatureFSGSBase : SubtargetFeature<"fsgsbase", "HasFSGSBase", "true",
+                                       "Support FS/GS Base instructions">;
 def FeatureLZCNT   : SubtargetFeature<"lzcnt", "HasLZCNT", "true",
                                       "Support LZCNT instruction">;
 def FeatureBMI     : SubtargetFeature<"bmi", "HasBMI", "true",
                                       "Support BMI instructions">;
+def FeatureBMI2    : SubtargetFeature<"bmi2", "HasBMI2", "true",
+                                      "Support BMI2 instructions">;
+def FeatureLeaForSP : SubtargetFeature<"lea-sp", "UseLeaForSP", "true",
+                                     "Use LEA for adjusting the stack poin=
ter">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // X86 processors supported.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+include "X86Schedule.td"
+
+def ProcIntelAtom : SubtargetFeature<"atom", "X86ProcFamily", "IntelAtom",
+                    "Intel Atom processors">;
+
 class Proc<string Name, list<SubtargetFeature> Features>
- : Processor<Name, NoItineraries, Features>;
+ : Processor<Name, GenericItineraries, Features>;
+
+class AtomProc<string Name, list<SubtargetFeature> Features>
+ : Processor<Name, AtomItineraries, Features>;
=20
 def : Proc<"generic",         []>;
 def : Proc<"i386",            []>;
@@ -137,34 +156,38 @@
                                FeatureSlowBTMem]>;
 def : Proc<"penryn",          [FeatureSSE41, FeatureCMPXCHG16B,
                                FeatureSlowBTMem]>;
-def : Proc<"atom",            [FeatureSSE3, FeatureCMPXCHG16B, FeatureMOVB=
E,
-                               FeatureSlowBTMem]>;
+def : AtomProc<"atom",        [ProcIntelAtom, FeatureSSE3, FeatureCMPXCHG1=
6B,
+                               FeatureMOVBE, FeatureSlowBTMem, FeatureLeaF=
orSP]>;
 // "Arrandale" along with corei3 and corei5
 def : Proc<"corei7",          [FeatureSSE42, FeatureCMPXCHG16B,
-                               FeatureSlowBTMem, FeatureFastUAMem, Feature=
AES]>;
+                               FeatureSlowBTMem, FeatureFastUAMem,
+                               FeaturePOPCNT, FeatureAES]>;
 def : Proc<"nehalem",         [FeatureSSE42,  FeatureCMPXCHG16B,
-                               FeatureSlowBTMem, FeatureFastUAMem]>;
+                               FeatureSlowBTMem, FeatureFastUAMem,
+                               FeaturePOPCNT]>;
 // Westmere is a similar machine to nehalem with some additional features.
 // Westmere is the corei3/i5/i7 path from nehalem to sandybridge
 def : Proc<"westmere",        [FeatureSSE42, FeatureCMPXCHG16B,
-                               FeatureSlowBTMem, FeatureFastUAMem, Feature=
AES,
-                               FeatureCLMUL]>;
+                               FeatureSlowBTMem, FeatureFastUAMem,
+                               FeaturePOPCNT, FeatureAES, FeatureCLMUL]>;
 // Sandy Bridge
 // SSE is not listed here since llvm treats AVX as a reimplementation of S=
SE,
 // rather than a superset.
 // FIXME: Disabling AVX for now since it's not ready.
-def : Proc<"corei7-avx",      [FeatureSSE42, FeatureCMPXCHG16B,
+def : Proc<"corei7-avx",      [FeatureSSE42, FeatureCMPXCHG16B, FeaturePOP=
CNT,
                                FeatureAES, FeatureCLMUL]>;
 // Ivy Bridge
-def : Proc<"core-avx-i",      [FeatureSSE42, FeatureCMPXCHG16B,
+def : Proc<"core-avx-i",      [FeatureSSE42, FeatureCMPXCHG16B, FeaturePOP=
CNT,
                                FeatureAES, FeatureCLMUL,
-                               FeatureRDRAND, FeatureF16C]>;
+                               FeatureRDRAND, FeatureF16C, FeatureFSGSBase=
]>;
=20
 // Haswell
-def : Proc<"core-avx2",       [FeatureSSE42, FeatureCMPXCHG16B, FeatureAES,
-                               FeatureCLMUL, FeatureRDRAND, FeatureF16C,
-                               FeatureFMA3, FeatureMOVBE, FeatureLZCNT,
-                               FeatureBMI]>;
+// FIXME: Disabling AVX/AVX2/FMA3 for now since it's not ready.
+def : Proc<"core-avx2",       [FeatureSSE42, FeatureCMPXCHG16B, FeaturePOP=
CNT,
+                               FeatureAES, FeatureCLMUL, FeatureRDRAND,
+                               FeatureF16C, FeatureFSGSBase,
+                               FeatureMOVBE, FeatureLZCNT, FeatureBMI,
+                               FeatureBMI2]>;
=20
 def : Proc<"k6",              [FeatureMMX]>;
 def : Proc<"k6-2",            [Feature3DNow]>;
@@ -189,15 +212,21 @@
 def : Proc<"athlon64-sse3",   [FeatureSSE3,   Feature3DNowA, FeatureCMPXCH=
G16B,
                                FeatureSlowBTMem]>;
 def : Proc<"amdfam10",        [FeatureSSE3,   FeatureSSE4A,
-                               Feature3DNowA, FeatureCMPXCHG16B,
-                               FeatureSlowBTMem]>;
-def : Proc<"barcelona",       [FeatureSSE3,   FeatureSSE4A,
-                               Feature3DNowA, FeatureCMPXCHG16B,
-                               FeatureSlowBTMem]>;
-def : Proc<"istanbul",        [Feature3DNowA, FeatureCMPXCHG16B,
-                               FeatureSSE4A, Feature3DNowA]>;
-def : Proc<"shanghai",        [Feature3DNowA, FeatureCMPXCHG16B, FeatureSS=
E4A,
-                               Feature3DNowA]>;
+                               Feature3DNowA, FeatureCMPXCHG16B, FeatureLZ=
CNT,
+                               FeaturePOPCNT, FeatureSlowBTMem]>;
+// Bobcat
+def : Proc<"btver1",          [FeatureSSSE3, FeatureSSE4A, FeatureCMPXCHG1=
6B,
+                               FeatureLZCNT, FeaturePOPCNT]>;
+// FIXME: Disabling AVX/FMA4 for now since it's not ready.
+// Bulldozer
+def : Proc<"bdver1",          [FeatureSSE42, FeatureSSE4A, FeatureCMPXCHG1=
6B,
+                               FeatureAES, FeatureCLMUL,
+                               FeatureXOP, FeatureLZCNT, FeaturePOPCNT]>;
+// Enhanced Bulldozer
+def : Proc<"bdver2",          [FeatureSSE42, FeatureSSE4A, FeatureCMPXCHG1=
6B,
+                               FeatureAES, FeatureCLMUL,
+                               FeatureXOP, FeatureF16C, FeatureLZCNT,
+                               FeaturePOPCNT, FeatureBMI]>;
=20
 def : Proc<"winchip-c6",      [FeatureMMX]>;
 def : Proc<"winchip2",        [Feature3DNow]>;
@@ -229,9 +258,11 @@
 // Assembly Parser
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-// Currently the X86 assembly parser only supports ATT syntax.
 def ATTAsmParser : AsmParser {
-  string AsmParserClassName =3D "ATTAsmParser";
+  string AsmParserClassName =3D "AsmParser";
+}
+
+def ATTAsmParserVariant : AsmParserVariant {
   int Variant =3D 0;
=20
   // Discard comments in assembly strings.
@@ -241,6 +272,16 @@
   string RegisterPrefix =3D "%";
 }
=20
+def IntelAsmParserVariant : AsmParserVariant {
+  int Variant =3D 1;
+
+  // Discard comments in assembly strings.
+  string CommentDelimiter =3D ";";
+
+  // Recognize hard coded registers.
+  string RegisterPrefix =3D "";
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Assembly Printers
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -261,8 +302,7 @@
 def X86 : Target {
   // Information about the instructions...
   let InstructionSet =3D X86InstrInfo;
-
   let AssemblyParsers =3D [ATTAsmParser];
-
+  let AssemblyParserVariants =3D [ATTAsmParserVariant, IntelAsmParserVaria=
nt];
   let AssemblyWriters =3D [ATTAsmWriter, IntelAsmWriter];
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86As=
mPrinter.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86AsmPrinter.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86AsmPrinter.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -13,13 +13,12 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "X86AsmPrinter.h"
-#include "InstPrinter/X86ATTInstPrinter.h"
-#include "InstPrinter/X86IntelInstPrinter.h"
 #include "X86MCInstLower.h"
 #include "X86.h"
 #include "X86COFFMachineModuleInfo.h"
 #include "X86MachineFunctionInfo.h"
 #include "X86TargetMachine.h"
+#include "InstPrinter/X86ATTInstPrinter.h"
 #include "llvm/CallingConv.h"
 #include "llvm/DerivedTypes.h"
 #include "llvm/Module.h"
@@ -199,6 +198,7 @@
   case X86II::MO_TLVP_PIC_BASE:
     O << "@TLVP" << '-' << *MF->getPICBaseSymbol();
     break;
+  case X86II::MO_SECREL:      O << "@SECREL";      break;
   }
 }
=20
@@ -264,16 +264,40 @@
 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op,
                                raw_ostream &O) {
   unsigned char value =3D MI->getOperand(Op).getImm();
-  assert(value <=3D 7 && "Invalid ssecc argument!");
   switch (value) {
-  case 0: O << "eq"; break;
-  case 1: O << "lt"; break;
-  case 2: O << "le"; break;
-  case 3: O << "unord"; break;
-  case 4: O << "neq"; break;
-  case 5: O << "nlt"; break;
-  case 6: O << "nle"; break;
-  case 7: O << "ord"; break;
+  default: llvm_unreachable("Invalid ssecc argument!");
+  case    0: O << "eq"; break;
+  case    1: O << "lt"; break;
+  case    2: O << "le"; break;
+  case    3: O << "unord"; break;
+  case    4: O << "neq"; break;
+  case    5: O << "nlt"; break;
+  case    6: O << "nle"; break;
+  case    7: O << "ord"; break;
+  case    8: O << "eq_uq"; break;
+  case    9: O << "nge"; break;
+  case  0xa: O << "ngt"; break;
+  case  0xb: O << "false"; break;
+  case  0xc: O << "neq_oq"; break;
+  case  0xd: O << "ge"; break;
+  case  0xe: O << "gt"; break;
+  case  0xf: O << "true"; break;
+  case 0x10: O << "eq_os"; break;
+  case 0x11: O << "lt_oq"; break;
+  case 0x12: O << "le_oq"; break;
+  case 0x13: O << "unord_s"; break;
+  case 0x14: O << "neq_us"; break;
+  case 0x15: O << "nlt_uq"; break;
+  case 0x16: O << "nle_uq"; break;
+  case 0x17: O << "ord_s"; break;
+  case 0x18: O << "eq_us"; break;
+  case 0x19: O << "nge_uq"; break;
+  case 0x1a: O << "ngt_uq"; break;
+  case 0x1b: O << "false_os"; break;
+  case 0x1c: O << "neq_os"; break;
+  case 0x1d: O << "ge_oq"; break;
+  case 0x1e: O << "gt_oq"; break;
+  case 0x1f: O << "true_us"; break;
   }
 }
=20
@@ -575,7 +599,7 @@
   }
=20
   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing() &&
-      MMI->callsExternalVAFunctionWithFloatingPointArguments()) {
+      MMI->usesVAFloatArgument()) {
     StringRef SymbolName =3D Subtarget->is64Bit() ? "_fltused" : "__fltuse=
d";
     MCSymbol *S =3D MMI->getContext().GetOrCreateSymbol(SymbolName);
     OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86As=
mPrinter.h
--- a/head/contrib/llvm/lib/Target/X86/X86AsmPrinter.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86AsmPrinter.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -17,7 +17,6 @@
 #include "X86.h"
 #include "X86MachineFunctionInfo.h"
 #include "X86TargetMachine.h"
-#include "llvm/ADT/StringSet.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/ValueTypes.h"
@@ -25,11 +24,7 @@
=20
 namespace llvm {
=20
-class MachineJumpTableInfo;
-class MCContext;
-class MCInst;
 class MCStreamer;
-class MCSymbol;
=20
 class LLVM_LIBRARY_VISIBILITY X86AsmPrinter : public AsmPrinter {
   const X86Subtarget *Subtarget;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86CO=
FFMachineModuleInfo.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86COFFMachineModuleInfo.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86COFFMachineModuleInfo.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- llvm/CodeGen/X86COFFMachineModuleInfo.cpp ------------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- X86COFFMachineModuleInfo.cpp - X86 COFF MMI Impl -----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86CO=
FFMachineModuleInfo.h
--- a/head/contrib/llvm/lib/Target/X86/X86COFFMachineModuleInfo.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86COFFMachineModuleInfo.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- llvm/CodeGen/X86COFFMachineModuleInfo.h -----------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86COFFMachineModuleInfo.h - X86 COFF MMI Impl ----------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,9 +14,9 @@
 #ifndef X86COFF_MACHINEMODULEINFO_H
 #define X86COFF_MACHINEMODULEINFO_H
=20
+#include "X86MachineFunctionInfo.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/ADT/DenseSet.h"
-#include "X86MachineFunctionInfo.h"
=20
 namespace llvm {
   class X86MachineFunctionInfo;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Ca=
llingConv.td
--- a/head/contrib/llvm/lib/Target/X86/X86CallingConv.td	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86CallingConv.td	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86CallingConv.td - Calling Conventions X86 32/64 ---*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86CallingConv.td - Calling Conventions X86 32/64 --*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This describes the calling conventions for the X86-32 and X86-64
@@ -61,7 +61,7 @@
   // weirdly; this is really the sse-regparm calling convention) in which
   // case they use XMM0, otherwise it is the same as the common X86 calling
   // conv.
-  CCIfInReg<CCIfSubtarget<"hasXMMInt()",
+  CCIfInReg<CCIfSubtarget<"hasSSE2()",
     CCIfType<[f32, f64], CCAssignToReg<[XMM0,XMM1,XMM2]>>>>,
   CCIfType<[f32,f64], CCAssignToReg<[ST0, ST1]>>,
   CCDelegateTo<RetCC_X86Common>
@@ -73,8 +73,8 @@
   // SSE2.
   // This can happen when a float, 2 x float, or 3 x float vector is split=
 by
   // target lowering, and is returned in 1-3 sse regs.
-  CCIfType<[f32], CCIfSubtarget<"hasXMMInt()", CCAssignToReg<[XMM0,XMM1,XM=
M2]>>>,
-  CCIfType<[f64], CCIfSubtarget<"hasXMMInt()", CCAssignToReg<[XMM0,XMM1,XM=
M2]>>>,
+  CCIfType<[f32], CCIfSubtarget<"hasSSE2()", CCAssignToReg<[XMM0,XMM1,XMM2=
]>>>,
+  CCIfType<[f64], CCIfSubtarget<"hasSSE2()", CCAssignToReg<[XMM0,XMM1,XMM2=
]>>>,
=20
   // For integers, ECX can be used as an extra return register
   CCIfType<[i8],  CCAssignToReg<[AL, DL, CL]>>,
@@ -150,18 +150,23 @@
   // The first 8 MMX vector arguments are passed in XMM registers on Darwi=
n.
   CCIfType<[x86mmx],
             CCIfSubtarget<"isTargetDarwin()",
-            CCIfSubtarget<"hasXMMInt()",
+            CCIfSubtarget<"hasSSE2()",
             CCPromoteToType<v2i64>>>>,
=20
   // The first 8 FP/Vector arguments are passed in XMM registers.
   CCIfType<[f32, f64, v16i8, v8i16, v4i32, v2i64, v4f32, v2f64],
-            CCIfSubtarget<"hasXMM()",
+            CCIfSubtarget<"hasSSE1()",
             CCAssignToReg<[XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7]=
>>>,
=20
-  // The first 8 256-bit vector arguments are passed in YMM registers.
-  CCIfType<[v32i8, v16i16, v8i32, v4i64, v8f32, v4f64],
-            CCIfSubtarget<"hasAVX()",
-            CCAssignToReg<[YMM0, YMM1, YMM2, YMM3, YMM4, YMM5, YMM6, YMM7]=
>>>,
+  // The first 8 256-bit vector arguments are passed in YMM registers, unl=
ess
+  // this is a vararg function.
+  // FIXME: This isn't precisely correct; the x86-64 ABI document says that
+  // fixed arguments to vararg functions are supposed to be passed in
+  // registers.  Actually modeling that would be a lot of work, though.
+  CCIfNotVarArg<CCIfType<[v32i8, v16i16, v8i32, v4i64, v8f32, v4f64],
+                          CCIfSubtarget<"hasAVX()",
+                          CCAssignToReg<[YMM0, YMM1, YMM2, YMM3,
+                                         YMM4, YMM5, YMM6, YMM7]>>>>,
=20
   // Integer/FP values get stored in stack slots that are 8 bytes in size =
and
   // 8-byte aligned if there are no more registers to hold them.
@@ -193,6 +198,10 @@
   // 128 bit vectors are passed by pointer
   CCIfType<[v16i8, v8i16, v4i32, v2i64, v4f32, v2f64], CCPassIndirect<i64>=
>,
=20
+
+  // 256 bit vectors are passed by pointer
+  CCIfType<[v32i8, v16i16, v8i32, v4i64, v8f32, v4f64], CCPassIndirect<i64=
>>,
+
   // The first 4 MMX vector arguments are passed in GPRs.
   CCIfType<[x86mmx], CCBitConvertToType<i64>>,
=20
@@ -233,7 +242,7 @@
=20
   // Pass in STG registers: F1, F2, F3, F4, D1, D2
   CCIfType<[f32, f64, v16i8, v8i16, v4i32, v2i64, v4f32, v2f64],
-            CCIfSubtarget<"hasXMM()",
+            CCIfSubtarget<"hasSSE1()",
             CCAssignToReg<[XMM1, XMM2, XMM3, XMM4, XMM5, XMM6]>>>
 ]>;
=20
@@ -251,7 +260,7 @@
   // The first 3 float or double arguments, if marked 'inreg' and if the c=
all
   // is not a vararg call and if SSE2 is available, are passed in SSE regi=
sters.
   CCIfNotVarArg<CCIfInReg<CCIfType<[f32,f64],
-                CCIfSubtarget<"hasXMMInt()",
+                CCIfSubtarget<"hasSSE2()",
                 CCAssignToReg<[XMM0,XMM1,XMM2]>>>>>,
=20
   // The first 3 __m64 vector arguments are passed in mmx registers if the
@@ -322,8 +331,8 @@
   // Promote i8/i16 arguments to i32.
   CCIfType<[i8, i16], CCPromoteToType<i32>>,
=20
-  // The 'nest' parameter, if any, is passed in EAX.
-  CCIfNest<CCAssignToReg<[EAX]>>,
+  // Pass sret arguments indirectly through EAX
+  CCIfSRet<CCAssignToReg<[EAX]>>,
=20
   // The first integer argument is passed in ECX
   CCIfType<[i32], CCAssignToReg<[ECX]>>,
@@ -350,7 +359,7 @@
   // The first 3 float or double arguments, if the call is not a vararg
   // call and if SSE2 is available, are passed in SSE registers.
   CCIfNotVarArg<CCIfType<[f32,f64],
-                CCIfSubtarget<"hasXMMInt()",
+                CCIfSubtarget<"hasSSE2()",
                 CCAssignToReg<[XMM0,XMM1,XMM2]>>>>,
=20
   // Doubles get 8-byte slots that are 8-byte aligned.
@@ -399,3 +408,18 @@
   CCIfSubtarget<"is64Bit()", CCDelegateTo<CC_X86_64>>,
   CCDelegateTo<CC_X86_32>
 ]>;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Callee-saved Registers.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+def CSR_Ghc : CalleeSavedRegs<(add)>;
+
+def CSR_32 : CalleeSavedRegs<(add ESI, EDI, EBX, EBP)>;
+def CSR_64 : CalleeSavedRegs<(add RBX, R12, R13, R14, R15, RBP)>;
+
+def CSR_32EHRet : CalleeSavedRegs<(add EAX, EDX, CSR_32)>;
+def CSR_64EHRet : CalleeSavedRegs<(add RAX, RDX, CSR_64)>;
+
+def CSR_Win64 : CalleeSavedRegs<(add RBX, RBP, RDI, RSI, R12, R13, R14, R1=
5,
+                                     (sequence "XMM%u", 6, 15))>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Co=
deEmitter.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86CodeEmitter.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86CodeEmitter.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86/X86CodeEmitter.cpp - Convert X86 code to machine code --=
-------=3D=3D=3D//
+//=3D=3D=3D-- X86CodeEmitter.cpp - Convert X86 code to machine code ------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -664,15 +664,14 @@
   case X86II::A7:  // 0F A7
     Need0FPrefix =3D true;
     break;
-  case X86II::TF: // F2 0F 38
-    MCE.emitByte(0xF2);
-    Need0FPrefix =3D true;
-    break;
   case X86II::REP: break; // already handled.
+  case X86II::T8XS: // F3 0F 38
   case X86II::XS:   // F3 0F
     MCE.emitByte(0xF3);
     Need0FPrefix =3D true;
     break;
+  case X86II::T8XD: // F2 0F 38
+  case X86II::TAXD: // F2 0F 3A
   case X86II::XD:   // F2 0F
     MCE.emitByte(0xF2);
     Need0FPrefix =3D true;
@@ -698,10 +697,12 @@
     MCE.emitByte(0x0F);
=20
   switch (Desc->TSFlags & X86II::Op0Mask) {
-  case X86II::TF:    // F2 0F 38
+  case X86II::T8XD:  // F2 0F 38
+  case X86II::T8XS:  // F3 0F 38
   case X86II::T8:    // 0F 38
     MCE.emitByte(0x38);
     break;
+  case X86II::TAXD:  // F2 0F 38
   case X86II::TA:    // 0F 3A
     MCE.emitByte(0x3A);
     break;
@@ -805,8 +806,7 @@
     }
    =20
     assert(MO.isImm() && "Unknown RawFrm operand!");
-    if (Opcode =3D=3D X86::CALLpcrel32 || Opcode =3D=3D X86::CALL64pcrel32=
 ||
-        Opcode =3D=3D X86::WINCALL64pcrel32) {
+    if (Opcode =3D=3D X86::CALLpcrel32 || Opcode =3D=3D X86::CALL64pcrel32=
) {
       // Fix up immediate operand for pc relative calls.
       intptr_t Imm =3D (intptr_t)MO.getImm();
       Imm =3D Imm - MCE.getCurrentPCValue() - 4;
@@ -1003,7 +1003,7 @@
     break;
   }
=20
-  if (!Desc->isVariadic() && CurOp !=3D NumOps) {
+  if (!MI.isVariadic() && CurOp !=3D NumOps) {
 #ifndef NDEBUG
     dbgs() << "Cannot encode all operands of: " << MI << "\n";
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86EL=
FWriterInfo.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86ELFWriterInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86ELFWriterInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -60,7 +60,6 @@
       llvm_unreachable("unknown x86 machine relocation type");
     }
   }
-  return 0;
 }
=20
 long int X86ELFWriterInfo::getDefaultAddendForRelTy(unsigned RelTy,
@@ -83,7 +82,6 @@
       llvm_unreachable("unknown x86 relocation type");
     }
   }
-  return 0;
 }
=20
 unsigned X86ELFWriterInfo::getRelocationTySize(unsigned RelTy) const {
@@ -107,7 +105,6 @@
       llvm_unreachable("unknown x86 relocation type");
     }
   }
-  return 0;
 }
=20
 bool X86ELFWriterInfo::isPCRelativeRel(unsigned RelTy) const {
@@ -132,7 +129,6 @@
       llvm_unreachable("unknown x86 relocation type");
     }
   }
-  return 0;
 }
=20
 unsigned X86ELFWriterInfo::getAbsoluteLabelMachineRelTy() const {
@@ -146,8 +142,6 @@
=20
   if (RelTy =3D=3D ELF::R_X86_64_PC32 || RelTy =3D=3D ELF::R_386_PC32)
     return SymOffset - (RelOffset + 4);
-  else
-    assert(0 && "computeRelocation unknown for this relocation type");
=20
-  return 0;
+  llvm_unreachable("computeRelocation unknown for this relocation type");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Fa=
stISel.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86FastISel.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86FastISel.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -60,8 +60,8 @@
   explicit X86FastISel(FunctionLoweringInfo &funcInfo) : FastISel(funcInfo=
) {
     Subtarget =3D &TM.getSubtarget<X86Subtarget>();
     StackPtr =3D Subtarget->is64Bit() ? X86::RSP : X86::ESP;
-    X86ScalarSSEf64 =3D Subtarget->hasSSE2() || Subtarget->hasAVX();
-    X86ScalarSSEf32 =3D Subtarget->hasSSE1() || Subtarget->hasAVX();
+    X86ScalarSSEf64 =3D Subtarget->hasSSE2();
+    X86ScalarSSEf32 =3D Subtarget->hasSSE1();
   }
=20
   virtual bool TargetSelectInstruction(const Instruction *I);
@@ -258,6 +258,18 @@
     Opc =3D X86ScalarSSEf64 ?
           (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_F=
p64m;
     break;
+  case MVT::v4f32:
+    Opc =3D X86::MOVAPSmr;
+    break;
+  case MVT::v2f64:
+    Opc =3D X86::MOVAPDmr;
+    break;
+  case MVT::v4i32:
+  case MVT::v2i64:
+  case MVT::v8i16:
+  case MVT::v16i8:
+    Opc =3D X86::MOVDQAmr;
+    break;
   }
=20
   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
@@ -671,7 +683,14 @@
 /// X86SelectStore - Select and emit code to implement store instructions.
 bool X86FastISel::X86SelectStore(const Instruction *I) {
   // Atomic stores need special handling.
-  if (cast<StoreInst>(I)->isAtomic())
+  const StoreInst *S =3D cast<StoreInst>(I);
+
+  if (S->isAtomic())
+    return false;
+
+  unsigned SABIAlignment =3D
+    TD.getABITypeAlignment(S->getValueOperand()->getType());
+  if (S->getAlignment() !=3D 0 && S->getAlignment() < SABIAlignment)
     return false;
=20
   MVT VT;
@@ -709,7 +728,7 @@
=20
   // fastcc with -tailcallopt is intended to provide a guaranteed
   // tail call optimization. Fastisel doesn't know how to do that.
-  if (CC =3D=3D CallingConv::Fast && GuaranteedTailCallOpt)
+  if (CC =3D=3D CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
     return false;
=20
   // Let SDISel handle vararg functions.
@@ -818,8 +837,8 @@
=20
 static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
   bool HasAVX =3D Subtarget->hasAVX();
-  bool X86ScalarSSEf32 =3D HasAVX || Subtarget->hasSSE1();
-  bool X86ScalarSSEf64 =3D HasAVX || Subtarget->hasSSE2();
+  bool X86ScalarSSEf32 =3D Subtarget->hasSSE1();
+  bool X86ScalarSSEf64 =3D Subtarget->hasSSE2();
=20
   switch (VT.getSimpleVT().SimpleTy) {
   default:       return 0;
@@ -1510,7 +1529,7 @@
=20
   // fastcc with -tailcallopt is intended to provide a guaranteed
   // tail call optimization. Fastisel doesn't know how to do that.
-  if (CC =3D=3D CallingConv::Fast && GuaranteedTailCallOpt)
+  if (CC =3D=3D CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
     return false;
=20
   PointerType *PT =3D cast<PointerType>(CS.getCalledValue()->getType());
@@ -1524,7 +1543,7 @@
=20
   // Fast-isel doesn't know about callee-pop yet.
   if (X86::isCalleePop(CC, Subtarget->is64Bit(), isVarArg,
-                       GuaranteedTailCallOpt))
+                       TM.Options.GuaranteedTailCallOpt))
     return false;
=20
   // Check whether the function can return without sret-demotion.
@@ -1557,10 +1576,11 @@
   SmallVector<unsigned, 8> Args;
   SmallVector<MVT, 8> ArgVTs;
   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
-  Args.reserve(CS.arg_size());
-  ArgVals.reserve(CS.arg_size());
-  ArgVTs.reserve(CS.arg_size());
-  ArgFlags.reserve(CS.arg_size());
+  unsigned arg_size =3D CS.arg_size();
+  Args.reserve(arg_size);
+  ArgVals.reserve(arg_size);
+  ArgVTs.reserve(arg_size);
+  ArgFlags.reserve(arg_size);
   for (ImmutableCallSite::arg_iterator i =3D CS.arg_begin(), e =3D CS.arg_=
end();
        i !=3D e; ++i) {
     // If we're lowering a mem intrinsic instead of a regular call, skip t=
he
@@ -1740,9 +1760,11 @@
         // If this is a really simple value, emit this with the Value* ver=
sion
         // of X86FastEmitStore.  If it isn't simple, we don't want to do t=
his,
         // as it can cause us to reevaluate the argument.
-        X86FastEmitStore(ArgVT, ArgVal, AM);
+        if (!X86FastEmitStore(ArgVT, ArgVal, AM))
+          return false;
       } else {
-        X86FastEmitStore(ArgVT, Arg, AM);
+        if (!X86FastEmitStore(ArgVT, Arg, AM))
+          return false;
       }
     }
   }
@@ -1757,7 +1779,7 @@
=20
   if (Subtarget->is64Bit() && isVarArg && !Subtarget->isTargetWin64()) {
     // Count the number of XMM registers allocated.
-    static const unsigned XMMArgRegs[] =3D {
+    static const uint16_t XMMArgRegs[] =3D {
       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
     };
@@ -1771,9 +1793,7 @@
   if (CalleeOp) {
     // Register-indirect call.
     unsigned CallOpc;
-    if (Subtarget->isTargetWin64())
-      CallOpc =3D X86::WINCALL64r;
-    else if (Subtarget->is64Bit())
+    if (Subtarget->is64Bit())
       CallOpc =3D X86::CALL64r;
     else
       CallOpc =3D X86::CALL32r;
@@ -1784,9 +1804,7 @@
     // Direct call.
     assert(GV && "Not a direct call");
     unsigned CallOpc;
-    if (Subtarget->isTargetWin64())
-      CallOpc =3D X86::WINCALL64pcrel32;
-    else if (Subtarget->is64Bit())
+    if (Subtarget->is64Bit())
       CallOpc =3D X86::CALL64pcrel32;
     else
       CallOpc =3D X86::CALLpcrel32;
@@ -1831,10 +1849,15 @@
   for (unsigned i =3D 0, e =3D RegArgs.size(); i !=3D e; ++i)
     MIB.addReg(RegArgs[i]);
=20
+  // Add a register mask with the call-preserved registers.
+  // Proper defs for return values will be added by setPhysRegsDeadExcept(=
).
+  MIB.addRegMask(TRI.getCallPreservedMask(CS.getCallingConv()));
+
   // Issue CALLSEQ_END
   unsigned AdjStackUp =3D TII.getCallFrameDestroyOpcode();
   unsigned NumBytesCallee =3D 0;
-  if (!Subtarget->is64Bit() && CS.paramHasAttr(1, Attribute::StructRet))
+  if (!Subtarget->is64Bit() && !Subtarget->isTargetWindows() &&
+      CS.paramHasAttr(1, Attribute::StructRet))
     NumBytesCallee =3D 4;
   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
     .addImm(NumBytes).addImm(NumBytesCallee);
@@ -2081,7 +2104,7 @@
   if (!X86SelectAddress(C, AM))
     return 0;
   unsigned Opc =3D Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
-  TargetRegisterClass* RC =3D TLI.getRegClassFor(TLI.getPointerTy());
+  const TargetRegisterClass* RC =3D TLI.getRegClassFor(TLI.getPointerTy());
   unsigned ResultReg =3D createResultReg(RC);
   addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
                          TII.get(Opc), ResultReg), AM);
@@ -2100,7 +2123,7 @@
     default: return false;
     case MVT::f32:
       if (X86ScalarSSEf32) {
-        Opc =3D Subtarget->hasAVX() ? X86::VFsFLD0SS : X86::FsFLD0SS;
+        Opc =3D X86::FsFLD0SS;
         RC  =3D X86::FR32RegisterClass;
       } else {
         Opc =3D X86::LD_Fp032;
@@ -2109,7 +2132,7 @@
       break;
     case MVT::f64:
       if (X86ScalarSSEf64) {
-        Opc =3D Subtarget->hasAVX() ? X86::VFsFLD0SD : X86::FsFLD0SD;
+        Opc =3D X86::FsFLD0SD;
         RC  =3D X86::FR64RegisterClass;
       } else {
         Opc =3D X86::LD_Fp064;
@@ -2156,7 +2179,7 @@
=20
=20
 namespace llvm {
-  llvm::FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
+  FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo) {
     return new X86FastISel(funcInfo);
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Fl=
oatingPoint.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86FloatingPoint.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86FloatingPoint.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -26,8 +26,8 @@
 #define DEBUG_TYPE "x86-codegen"
 #include "X86.h"
 #include "X86InstrInfo.h"
+#include "llvm/InlineAsm.h"
 #include "llvm/ADT/DepthFirstIterator.h"
-#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
@@ -37,7 +37,6 @@
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/Passes.h"
-#include "llvm/InlineAsm.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
@@ -219,7 +218,7 @@
     /// getSTReg - Return the X86::ST(i) register which contains the speci=
fied
     /// FP<RegNo> register.
     unsigned getSTReg(unsigned RegNo) const {
-      return StackTop - 1 - getSlot(RegNo) + llvm::X86::ST0;
+      return StackTop - 1 - getSlot(RegNo) + X86::ST0;
     }
=20
     // pushReg - Push the specified FP<n> register onto the stack.
@@ -570,8 +569,8 @@
=20
 namespace {
   struct TableEntry {
-    unsigned from;
-    unsigned to;
+    uint16_t from;
+    uint16_t to;
     bool operator<(const TableEntry &TE) const { return from < TE.from; }
     friend bool operator<(const TableEntry &TE, unsigned V) {
       return TE.from < V;
@@ -1644,6 +1643,30 @@
     return;
   }
=20
+  case X86::WIN_FTOL_32:
+  case X86::WIN_FTOL_64: {
+    // Push the operand into ST0.
+    MachineOperand &Op =3D MI->getOperand(0);
+    assert(Op.isUse() && Op.isReg() &&
+      Op.getReg() >=3D X86::FP0 && Op.getReg() <=3D X86::FP6);
+    unsigned FPReg =3D getFPReg(Op);
+    if (Op.isKill())
+      moveToTop(FPReg, I);
+    else
+      duplicateToTop(FPReg, FPReg, I);
+
+    // Emit the call. This will pop the operand.
+    BuildMI(*MBB, I, MI->getDebugLoc(), TII->get(X86::CALLpcrel32))
+      .addExternalSymbol("_ftol2")
+      .addReg(X86::ST0, RegState::ImplicitKill)
+      .addReg(X86::EAX, RegState::Define | RegState::Implicit)
+      .addReg(X86::EDX, RegState::Define | RegState::Implicit)
+      .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
+    --StackTop;
+
+    break;
+  }
+
   case X86::RET:
   case X86::RETI:
     // If RET has an FP register use operand, pass the first one in ST(0) =
and
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Fr=
ameLowering.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86FrameLowering.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86FrameLowering.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D=3D=3D- X86FrameLowering.cpp - X86 Frame Information ----=
----*- C++ -*-=3D=3D=3D=3D//
+//=3D=3D=3D-- X86FrameLowering.cpp - X86 Frame Information ---------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -47,7 +47,7 @@
   const MachineModuleInfo &MMI =3D MF.getMMI();
   const TargetRegisterInfo *RI =3D TM.getRegisterInfo();
=20
-  return (DisableFramePointerElim(MF) ||
+  return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
           RI->needsStackRealignment(MF) ||
           MFI->hasVarSizedObjects() ||
           MFI->isFrameAddressTaken() ||
@@ -79,6 +79,10 @@
   }
 }
=20
+static unsigned getLEArOpcode(unsigned is64Bit) {
+  return is64Bit ? X86::LEA64r : X86::LEA32r;
+}
+
 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
 /// when it reaches the "return" instruction. We can then pop a stack obje=
ct
 /// to this register without worry about clobbering it.
@@ -91,11 +95,11 @@
   if (!F || MF->getMMI().callsEHReturn())
     return 0;
=20
-  static const unsigned CallerSavedRegs32Bit[] =3D {
+  static const uint16_t CallerSavedRegs32Bit[] =3D {
     X86::EAX, X86::EDX, X86::ECX, 0
   };
=20
-  static const unsigned CallerSavedRegs64Bit[] =3D {
+  static const uint16_t CallerSavedRegs64Bit[] =3D {
     X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
     X86::R8,  X86::R9,  X86::R10, X86::R11, 0
   };
@@ -113,7 +117,7 @@
   case X86::TCRETURNmi64:
   case X86::EH_RETURN:
   case X86::EH_RETURN64: {
-    SmallSet<unsigned, 8> Uses;
+    SmallSet<uint16_t, 8> Uses;
     for (unsigned i =3D 0, e =3D MBBI->getNumOperands(); i !=3D e; ++i) {
       MachineOperand &MO =3D MBBI->getOperand(i);
       if (!MO.isReg() || MO.isDef())
@@ -121,11 +125,11 @@
       unsigned Reg =3D MO.getReg();
       if (!Reg)
         continue;
-      for (const unsigned *AsI =3D TRI.getOverlaps(Reg); *AsI; ++AsI)
+      for (const uint16_t *AsI =3D TRI.getOverlaps(Reg); *AsI; ++AsI)
         Uses.insert(*AsI);
     }
=20
-    const unsigned *CS =3D Is64Bit ? CallerSavedRegs64Bit : CallerSavedReg=
s32Bit;
+    const uint16_t *CS =3D Is64Bit ? CallerSavedRegs64Bit : CallerSavedReg=
s32Bit;
     for (; *CS; ++CS)
       if (!Uses.count(*CS))
         return *CS;
@@ -141,13 +145,18 @@
 static
 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBB=
I,
                   unsigned StackPtr, int64_t NumBytes,
-                  bool Is64Bit, const TargetInstrInfo &TII,
-                  const TargetRegisterInfo &TRI) {
+                  bool Is64Bit, bool UseLEA,
+                  const TargetInstrInfo &TII, const TargetRegisterInfo &TR=
I) {
   bool isSub =3D NumBytes < 0;
   uint64_t Offset =3D isSub ? -NumBytes : NumBytes;
-  unsigned Opc =3D isSub ?
-    getSUBriOpcode(Is64Bit, Offset) :
-    getADDriOpcode(Is64Bit, Offset);
+  unsigned Opc;
+  if (UseLEA)
+    Opc =3D getLEArOpcode(Is64Bit);
+  else
+    Opc =3D isSub
+      ? getSUBriOpcode(Is64Bit, Offset)
+      : getADDriOpcode(Is64Bit, Offset);
+
   uint64_t Chunk =3D (1LL << 31) - 1;
   DebugLoc DL =3D MBB.findDebugLoc(MBBI);
=20
@@ -171,13 +180,21 @@
       }
     }
=20
-    MachineInstr *MI =3D
-      BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
-      .addReg(StackPtr)
-      .addImm(ThisVal);
+    MachineInstr *MI =3D NULL;
+
+    if (UseLEA) {
+      MI =3D  addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
+                          StackPtr, false, isSub ? -ThisVal : ThisVal);
+    } else {
+      MI =3D BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
+            .addReg(StackPtr)
+            .addImm(ThisVal);
+      MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
+    }
+
     if (isSub)
       MI->setFlag(MachineInstr::FrameSetup);
-    MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
+
     Offset -=3D ThisVal;
   }
 }
@@ -191,7 +208,8 @@
   MachineBasicBlock::iterator PI =3D prior(MBBI);
   unsigned Opc =3D PI->getOpcode();
   if ((Opc =3D=3D X86::ADD64ri32 || Opc =3D=3D X86::ADD64ri8 ||
-       Opc =3D=3D X86::ADD32ri || Opc =3D=3D X86::ADD32ri8) &&
+       Opc =3D=3D X86::ADD32ri || Opc =3D=3D X86::ADD32ri8 ||
+       Opc =3D=3D X86::LEA32r || Opc =3D=3D X86::LEA64_32r) &&
       PI->getOperand(0).getReg() =3D=3D StackPtr) {
     if (NumBytes)
       *NumBytes +=3D PI->getOperand(2).getImm();
@@ -210,7 +228,7 @@
 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
                         MachineBasicBlock::iterator &MBBI,
                         unsigned StackPtr, uint64_t *NumBytes =3D NULL) {
-  // FIXME: THIS ISN'T RUN!!!
+  // FIXME:  THIS ISN'T RUN!!!
   return;
=20
   if (MBBI =3D=3D MBB.end()) return;
@@ -237,8 +255,8 @@
 }
=20
 /// mergeSPUpdates - Checks the instruction before/after the passed
-/// instruction. If it is an ADD/SUB instruction it is deleted argument an=
d the
-/// stack adjustment is returned as a positive value for ADD and a negativ=
e for
+/// instruction. If it is an ADD/SUB/LEA instruction it is deleted argumen=
t and the
+/// stack adjustment is returned as a positive value for ADD/LEA and a neg=
ative for
 /// SUB.
 static int mergeSPUpdates(MachineBasicBlock &MBB,
                            MachineBasicBlock::iterator &MBBI,
@@ -254,7 +272,8 @@
   int Offset =3D 0;
=20
   if ((Opc =3D=3D X86::ADD64ri32 || Opc =3D=3D X86::ADD64ri8 ||
-       Opc =3D=3D X86::ADD32ri || Opc =3D=3D X86::ADD32ri8) &&
+       Opc =3D=3D X86::ADD32ri || Opc =3D=3D X86::ADD32ri8 ||
+       Opc =3D=3D X86::LEA32r || Opc =3D=3D X86::LEA64_32r) &&
       PI->getOperand(0).getReg() =3D=3D StackPtr){
     Offset +=3D PI->getOperand(2).getImm();
     MBB.erase(PI);
@@ -351,20 +370,22 @@
 /// register. The number corresponds to the enum lists in
 /// compact_unwind_encoding.h.
 static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
-  int Idx =3D 1;
-  for (; *CURegs; ++CURegs, ++Idx)
+  for (int Idx =3D 1; *CURegs; ++CURegs, ++Idx)
     if (*CURegs =3D=3D Reg)
       return Idx;
=20
   return -1;
 }
=20
+// Number of registers that can be saved in a compact unwind encoding.
+#define CU_NUM_SAVED_REGS 6
+
 /// encodeCompactUnwindRegistersWithoutFrame - Create the permutation enco=
ding
 /// used with frameless stacks. It is passed the number of registers to be=
 saved
 /// and an array of the registers saved.
-static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedReg=
s[6],
-                                                         unsigned RegCount,
-                                                         bool Is64Bit) {
+static uint32_t
+encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[CU_NUM_SAVED_R=
EGS],
+                                         unsigned RegCount, bool Is64Bit) {
   // The saved registers are numbered from 1 to 6. In order to encode the =
order
   // in which they were saved, we re-number them according to their place =
in the
   // register order. The re-numbering is relative to the last re-numbered
@@ -385,14 +406,21 @@
   };
   const unsigned *CURegs =3D (Is64Bit ? CU64BitRegs : CU32BitRegs);
=20
-  uint32_t RenumRegs[6];
-  for (unsigned i =3D 6 - RegCount; i < 6; ++i) {
+  for (unsigned i =3D 0; i !=3D CU_NUM_SAVED_REGS; ++i) {
     int CUReg =3D getCompactUnwindRegNum(CURegs, SavedRegs[i]);
     if (CUReg =3D=3D -1) return ~0U;
     SavedRegs[i] =3D CUReg;
+  }
=20
+  // Reverse the list.
+  std::swap(SavedRegs[0], SavedRegs[5]);
+  std::swap(SavedRegs[1], SavedRegs[4]);
+  std::swap(SavedRegs[2], SavedRegs[3]);
+
+  uint32_t RenumRegs[CU_NUM_SAVED_REGS];
+  for (unsigned i =3D CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS;=
 ++i) {
     unsigned Countless =3D 0;
-    for (unsigned j =3D 6 - RegCount; j < i; ++j)
+    for (unsigned j =3D CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
       if (SavedRegs[j] < SavedRegs[i])
         ++Countless;
=20
@@ -435,8 +463,9 @@
=20
 /// encodeCompactUnwindRegistersWithFrame - Return the registers encoded f=
or a
 /// compact encoding with a frame pointer.
-static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6=
],
-                                                      bool Is64Bit) {
+static uint32_t
+encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[CU_NUM_SAVED_REGS=
],
+                                      bool Is64Bit) {
   static const unsigned CU32BitRegs[] =3D {
     X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
   };
@@ -446,18 +475,21 @@
   const unsigned *CURegs =3D (Is64Bit ? CU64BitRegs : CU32BitRegs);
=20
   // Encode the registers in the order they were saved, 3-bits per registe=
r. The
-  // registers are numbered from 1 to 6.
+  // registers are numbered from 1 to CU_NUM_SAVED_REGS.
   uint32_t RegEnc =3D 0;
-  for (int I =3D 5; I >=3D 0; --I) {
+  for (int I =3D CU_NUM_SAVED_REGS - 1, Idx =3D 0; I !=3D -1; --I) {
     unsigned Reg =3D SavedRegs[I];
-    if (Reg =3D=3D 0) break;
+    if (Reg =3D=3D 0) continue;
+
     int CURegNum =3D getCompactUnwindRegNum(CURegs, Reg);
-    if (CURegNum =3D=3D -1)
-      return ~0U;
-    RegEnc |=3D (CURegNum & 0x7) << (5 - I);
+    if (CURegNum =3D=3D -1) return ~0U;
+
+    // Encode the 3-bit register number in order, skipping over 3-bits for=
 each
+    // register.
+    RegEnc |=3D (CURegNum & 0x7) << (Idx++ * 3);
   }
=20
-  assert((RegEnc & 0x7FFF) =3D=3D RegEnc && "Invalid compact register enco=
ding!");
+  assert((RegEnc & 0x3FFFF) =3D=3D RegEnc && "Invalid compact register enc=
oding!");
   return RegEnc;
 }
=20
@@ -466,14 +498,11 @@
   unsigned FramePtr =3D RegInfo->getFrameRegister(MF);
   unsigned StackPtr =3D RegInfo->getStackRegister();
=20
-  X86MachineFunctionInfo *X86FI =3D MF.getInfo<X86MachineFunctionInfo>();
-  int TailCallReturnAddrDelta =3D X86FI->getTCReturnAddrDelta();
-
   bool Is64Bit =3D STI.is64Bit();
   bool HasFP =3D hasFP(MF);
=20
-  unsigned SavedRegs[6] =3D { 0, 0, 0, 0, 0, 0 };
-  int SavedRegIdx =3D 6;
+  unsigned SavedRegs[CU_NUM_SAVED_REGS] =3D { 0, 0, 0, 0, 0, 0 };
+  unsigned SavedRegIdx =3D 0;
=20
   unsigned OffsetSize =3D (Is64Bit ? 8 : 4);
=20
@@ -481,14 +510,13 @@
   unsigned PushInstrSize =3D 1;
   unsigned MoveInstr =3D (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
   unsigned MoveInstrSize =3D (Is64Bit ? 3 : 2);
-  unsigned SubtractInstr =3D getSUBriOpcode(Is64Bit, -TailCallReturnAddrDe=
lta);
   unsigned SubtractInstrIdx =3D (Is64Bit ? 3 : 2);
=20
   unsigned StackDivide =3D (Is64Bit ? 8 : 4);
=20
   unsigned InstrOffset =3D 0;
-  unsigned CFAOffset =3D 0;
   unsigned StackAdjust =3D 0;
+  unsigned StackSize =3D 0;
=20
   MachineBasicBlock &MBB =3D MF.front(); // Prologue is in entry BB.
   bool ExpectEnd =3D false;
@@ -504,10 +532,10 @@
=20
     if (Opc =3D=3D PushInstr) {
       // If there are too many saved registers, we cannot use compact enco=
ding.
-      if (--SavedRegIdx < 0) return 0;
+      if (SavedRegIdx >=3D CU_NUM_SAVED_REGS) return 0;
=20
-      SavedRegs[SavedRegIdx] =3D MI.getOperand(0).getReg();
-      CFAOffset +=3D OffsetSize;
+      SavedRegs[SavedRegIdx++] =3D MI.getOperand(0).getReg();
+      StackAdjust +=3D OffsetSize;
       InstrOffset +=3D PushInstrSize;
     } else if (Opc =3D=3D MoveInstr) {
       unsigned SrcReg =3D MI.getOperand(1).getReg();
@@ -516,12 +544,14 @@
       if (DstReg !=3D FramePtr || SrcReg !=3D StackPtr)
         return 0;
=20
-      CFAOffset =3D 0;
+      StackAdjust =3D 0;
       memset(SavedRegs, 0, sizeof(SavedRegs));
+      SavedRegIdx =3D 0;
       InstrOffset +=3D MoveInstrSize;
-    } else if (Opc =3D=3D SubtractInstr) {
-      if (StackAdjust)
-        // We all ready have a stack pointer adjustment.
+    } else if (Opc =3D=3D X86::SUB64ri32 || Opc =3D=3D X86::SUB64ri8 ||
+               Opc =3D=3D X86::SUB32ri || Opc =3D=3D X86::SUB32ri8) {
+      if (StackSize)
+        // We already have a stack size.
         return 0;
=20
       if (!MI.getOperand(0).isReg() ||
@@ -532,7 +562,7 @@
         //   %RSP<def> =3D SUB64ri8 %RSP, 48
         return 0;
=20
-      StackAdjust =3D MI.getOperand(2).getImm() / StackDivide;
+      StackSize =3D MI.getOperand(2).getImm() / StackDivide;
       SubtractInstrIdx +=3D InstrOffset;
       ExpectEnd =3D true;
     }
@@ -540,28 +570,30 @@
=20
   // Encode that we are using EBP/RBP as the frame pointer.
   uint32_t CompactUnwindEncoding =3D 0;
-  CFAOffset /=3D StackDivide;
+  StackAdjust /=3D StackDivide;
   if (HasFP) {
-    if ((CFAOffset & 0xFF) !=3D CFAOffset)
+    if ((StackAdjust & 0xFF) !=3D StackAdjust)
       // Offset was too big for compact encoding.
       return 0;
=20
     // Get the encoding of the saved registers when we have a frame pointe=
r.
     uint32_t RegEnc =3D encodeCompactUnwindRegistersWithFrame(SavedRegs, I=
s64Bit);
-    if (RegEnc =3D=3D ~0U)
-      return 0;
+    if (RegEnc =3D=3D ~0U) return 0;
=20
     CompactUnwindEncoding |=3D 0x01000000;
-    CompactUnwindEncoding |=3D (CFAOffset & 0xFF) << 16;
+    CompactUnwindEncoding |=3D (StackAdjust & 0xFF) << 16;
     CompactUnwindEncoding |=3D RegEnc & 0x7FFF;
   } else {
-    unsigned FullOffset =3D CFAOffset + StackAdjust;
-    if ((FullOffset & 0xFF) =3D=3D FullOffset) {
-      // Frameless stack.
+    ++StackAdjust;
+    uint32_t TotalStackSize =3D StackAdjust + StackSize;
+    if ((TotalStackSize & 0xFF) =3D=3D TotalStackSize) {
+      // Frameless stack with a small stack size.
       CompactUnwindEncoding |=3D 0x02000000;
-      CompactUnwindEncoding |=3D (FullOffset & 0xFF) << 16;
+
+      // Encode the stack size.
+      CompactUnwindEncoding |=3D (TotalStackSize & 0xFF) << 16;
     } else {
-      if ((CFAOffset & 0x7) !=3D CFAOffset)
+      if ((StackAdjust & 0x7) !=3D StackAdjust)
         // The extra stack adjustments are too big for us to handle.
         return 0;
=20
@@ -572,16 +604,21 @@
       // instruction.
       CompactUnwindEncoding |=3D (SubtractInstrIdx & 0xFF) << 16;
=20
-      // Encode any extra stack stack changes (done via push instructions).
-      CompactUnwindEncoding |=3D (CFAOffset & 0x7) << 13;
+      // Encode any extra stack stack adjustments (done via push instructi=
ons).
+      CompactUnwindEncoding |=3D (StackAdjust & 0x7) << 13;
     }
=20
+    // Encode the number of registers saved.
+    CompactUnwindEncoding |=3D (SavedRegIdx & 0x7) << 10;
+
     // Get the encoding of the saved registers when we don't have a frame
     // pointer.
-    uint32_t RegEnc =3D encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
-                                                               6 - SavedRe=
gIdx,
-                                                               Is64Bit);
+    uint32_t RegEnc =3D
+      encodeCompactUnwindRegistersWithoutFrame(SavedRegs, SavedRegIdx,
+                                               Is64Bit);
     if (RegEnc =3D=3D ~0U) return 0;
+
+    // Encode the register encoding.
     CompactUnwindEncoding |=3D RegEnc & 0x3FF;
   }
=20
@@ -608,6 +645,7 @@
   bool HasFP =3D hasFP(MF);
   bool Is64Bit =3D STI.is64Bit();
   bool IsWin64 =3D STI.isTargetWin64();
+  bool UseLEA =3D STI.useLeaForSP();
   unsigned StackAlign =3D getStackAlignment();
   unsigned SlotSize =3D RegInfo->getSlotSize();
   unsigned FramePtr =3D RegInfo->getFrameRegister(MF);
@@ -637,10 +675,10 @@
   // stack pointer (we fit in the Red Zone).
   if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
       !RegInfo->needsStackRealignment(MF) &&
-      !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
-      !MFI->adjustsStack() &&                      // No calls.
-      !IsWin64 &&                                  // Win64 has no Red Zone
-      !EnableSegmentedStacks) {                    // Regular stack
+      !MFI->hasVarSizedObjects() &&                     // No dynamic allo=
ca.
+      !MFI->adjustsStack() &&                           // No calls.
+      !IsWin64 &&                                       // Win64 has no Re=
d Zone
+      !MF.getTarget().Options.EnableSegmentedStacks) {  // Regular stack
     uint64_t MinSize =3D X86FI->getCalleeSavedFrameSize();
     if (HasFP) MinSize +=3D SlotSize;
     StackSize =3D std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
@@ -861,7 +899,7 @@
     // FIXME: %rax preserves the offset and should be available.
     if (isSPUpdateNeeded)
       emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
-                   TII, *RegInfo);
+                   UseLEA, TII, *RegInfo);
=20
     if (isEAXAlive) {
         // Restore EAX
@@ -873,7 +911,7 @@
     }
   } else if (NumBytes)
     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
-                 TII, *RegInfo);
+                 UseLEA, TII, *RegInfo);
=20
   if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
     // Mark end of stack pointer adjustment.
@@ -917,6 +955,7 @@
   unsigned RetOpcode =3D MBBI->getOpcode();
   DebugLoc DL =3D MBBI->getDebugLoc();
   bool Is64Bit =3D STI.is64Bit();
+  bool UseLEA =3D STI.useLeaForSP();
   unsigned StackAlign =3D getStackAlignment();
   unsigned SlotSize =3D RegInfo->getSlotSize();
   unsigned FramePtr =3D RegInfo->getFrameRegister(MF);
@@ -977,7 +1016,7 @@
     unsigned Opc =3D PI->getOpcode();
=20
     if (Opc !=3D X86::POP32r && Opc !=3D X86::POP64r && Opc !=3D X86::DBG_=
VALUE &&
-        !PI->getDesc().isTerminator())
+        !PI->isTerminator())
       break;
=20
     --MBBI;
@@ -997,7 +1036,8 @@
     // We cannot use LEA here, because stack pointer was realigned. We nee=
d to
     // deallocate local frame back.
     if (CSSize) {
-      emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
+      emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, UseLEA, TII,
+                   *RegInfo);
       MBBI =3D prior(LastCSPop);
     }
=20
@@ -1018,7 +1058,7 @@
     }
   } else if (NumBytes) {
     // Adjust stack pointer back: ESP +=3D numbytes.
-    emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
+    emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, UseLEA, TII, *Reg=
Info);
   }
=20
   // We're returning from function via eh_return.
@@ -1053,7 +1093,7 @@
     if (Offset) {
       // Check for possible merge with preceding ADD instruction.
       Offset +=3D mergeSPUpdates(MBB, MBBI, StackPtr, true);
-      emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
+      emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, UseLEA, TII, *Reg=
Info);
     }
=20
     // Jump to label or value in register.
@@ -1097,7 +1137,7 @@
=20
     // Check for possible merge with preceding ADD instruction.
     delta +=3D mergeSPUpdates(MBB, MBBI, StackPtr, true);
-    emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
+    emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, UseLEA, TII, *RegInf=
o);
   }
 }
=20
@@ -1280,31 +1320,35 @@
   return false;
 }
=20
+
+/// GetScratchRegister - Get a register for performing work in the segment=
ed
+/// stack prologue. Depending on platform and the properties of the functi=
on
+/// either one or two registers will be needed. Set primary to true for
+/// the first register, false for the second.
 static unsigned
-GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
-  if (Is64Bit) {
-    return X86::R11;
-  } else {
-    CallingConv::ID CallingConvention =3D MF.getFunction()->getCallingConv=
();
-    bool IsNested =3D HasNestArgument(&MF);
+GetScratchRegister(bool Is64Bit, const MachineFunction &MF, bool Primary) {
+  if (Is64Bit)
+    return Primary ? X86::R11 : X86::R12;
=20
-    if (CallingConvention =3D=3D CallingConv::X86_FastCall) {
-      if (IsNested) {
-        report_fatal_error("Segmented stacks does not support fastcall wit=
h "
-                           "nested function.");
-        return -1;
-      } else {
-        return X86::EAX;
-      }
-    } else {
-      if (IsNested)
-        return X86::EDX;
-      else
-        return X86::ECX;
-    }
+  CallingConv::ID CallingConvention =3D MF.getFunction()->getCallingConv();
+  bool IsNested =3D HasNestArgument(&MF);
+
+  if (CallingConvention =3D=3D CallingConv::X86_FastCall ||
+      CallingConvention =3D=3D CallingConv::Fast) {
+    if (IsNested)
+      report_fatal_error("Segmented stacks does not support fastcall with "
+                         "nested function.");
+    return Primary ? X86::EAX : X86::ECX;
   }
+  if (IsNested)
+    return Primary ? X86::EDX : X86::EAX;
+  return Primary ? X86::ECX : X86::EAX;
 }
=20
+// The stack limit in the TCB is set to this many bytes above the actual s=
tack
+// limit.
+static const uint64_t kSplitStackAvailable =3D 256;
+
 void
 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
   MachineBasicBlock &prologueMBB =3D MF.front();
@@ -1316,14 +1360,15 @@
   DebugLoc DL;
   const X86Subtarget *ST =3D &MF.getTarget().getSubtarget<X86Subtarget>();
=20
-  unsigned ScratchReg =3D GetScratchRegister(Is64Bit, MF);
+  unsigned ScratchReg =3D GetScratchRegister(Is64Bit, MF, true);
   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
          "Scratch register is live-in");
=20
   if (MF.getFunction()->isVarArg())
     report_fatal_error("Segmented stacks do not support vararg functions."=
);
-  if (!ST->isTargetLinux())
-    report_fatal_error("Segmented stacks supported only on linux.");
+  if (!ST->isTargetLinux() && !ST->isTargetDarwin() &&
+      !ST->isTargetWin32() && !ST->isTargetFreeBSD())
+    report_fatal_error("Segmented stacks not supported on this platform.");
=20
   MachineBasicBlock *allocMBB =3D MF.CreateMachineBasicBlock();
   MachineBasicBlock *checkMBB =3D MF.CreateMachineBasicBlock();
@@ -1336,26 +1381,16 @@
=20
   // The MOV R10, RAX needs to be in a different block, since the RET we e=
mit in
   // allocMBB needs to be last (terminating) instruction.
-  MachineBasicBlock *restoreR10MBB =3D NULL;
-  if (IsNested)
-    restoreR10MBB =3D MF.CreateMachineBasicBlock();
=20
   for (MachineBasicBlock::livein_iterator i =3D prologueMBB.livein_begin(),
          e =3D prologueMBB.livein_end(); i !=3D e; i++) {
     allocMBB->addLiveIn(*i);
     checkMBB->addLiveIn(*i);
-
-    if (IsNested)
-      restoreR10MBB->addLiveIn(*i);
-  }
-
-  if (IsNested) {
-    allocMBB->addLiveIn(X86::R10);
-    restoreR10MBB->addLiveIn(X86::RAX);
   }
=20
   if (IsNested)
-    MF.push_front(restoreR10MBB);
+    allocMBB->addLiveIn(X86::R10);
+
   MF.push_front(allocMBB);
   MF.push_front(checkMBB);
=20
@@ -1364,28 +1399,99 @@
   // prologue.
   StackSize =3D MFI->getStackSize();
=20
+  // When the frame size is less than 256 we just compare the stack
+  // boundary directly to the value of the stack pointer, per gcc.
+  bool CompareStackPointer =3D StackSize < kSplitStackAvailable;
+
   // Read the limit off the current stacklet off the stack_guard location.
   if (Is64Bit) {
-    TlsReg =3D X86::FS;
-    TlsOffset =3D 0x70;
+    if (ST->isTargetLinux()) {
+      TlsReg =3D X86::FS;
+      TlsOffset =3D 0x70;
+    } else if (ST->isTargetDarwin()) {
+      TlsReg =3D X86::GS;
+      TlsOffset =3D 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot =
90.
+    } else if (ST->isTargetFreeBSD()) {
+      TlsReg =3D X86::FS;
+      TlsOffset =3D 0x18;
+    } else {
+      report_fatal_error("Segmented stacks not supported on this platform.=
");
+    }
=20
-    BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RS=
P)
-      .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
+    if (CompareStackPointer)
+      ScratchReg =3D X86::RSP;
+    else
+      BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::=
RSP)
+        .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
+
     BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
-      .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
+      .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
   } else {
-    TlsReg =3D X86::GS;
-    TlsOffset =3D 0x30;
+    if (ST->isTargetLinux()) {
+      TlsReg =3D X86::GS;
+      TlsOffset =3D 0x30;
+    } else if (ST->isTargetDarwin()) {
+      TlsReg =3D X86::GS;
+      TlsOffset =3D 0x48 + 90*4;
+    } else if (ST->isTargetWin32()) {
+      TlsReg =3D X86::FS;
+      TlsOffset =3D 0x14; // pvArbitrary, reserved for application use
+    } else if (ST->isTargetFreeBSD()) {
+      report_fatal_error("Segmented stacks not supported on FreeBSD i386."=
);
+    } else {
+      report_fatal_error("Segmented stacks not supported on this platform.=
");
+    }
=20
-    BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ES=
P)
-      .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
-    BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
-      .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
+    if (CompareStackPointer)
+      ScratchReg =3D X86::ESP;
+    else
+      BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::=
ESP)
+        .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
+
+    if (ST->isTargetLinux() || ST->isTargetWin32()) {
+      BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
+        .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
+    } else if (ST->isTargetDarwin()) {
+
+      // TlsOffset doesn't fit into a mod r/m byte so we need an extra reg=
ister
+      unsigned ScratchReg2;
+      bool SaveScratch2;
+      if (CompareStackPointer) {
+        // The primary scratch register is available for holding the TLS o=
ffset
+        ScratchReg2 =3D GetScratchRegister(Is64Bit, MF, true);
+        SaveScratch2 =3D false;
+      } else {
+        // Need to use a second register to hold the TLS offset
+        ScratchReg2 =3D GetScratchRegister(Is64Bit, MF, false);
+
+        // Unfortunately, with fastcc the second scratch register may hold=
 an arg
+        SaveScratch2 =3D MF.getRegInfo().isLiveIn(ScratchReg2);
+      }
+
+      // If Scratch2 is live-in then it needs to be saved
+      assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
+             "Scratch register is live-in and not saved");
+
+      if (SaveScratch2)
+        BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
+          .addReg(ScratchReg2, RegState::Kill);
+
+      BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
+        .addImm(TlsOffset);
+      BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
+        .addReg(ScratchReg)
+        .addReg(ScratchReg2).addImm(1).addReg(0)
+        .addImm(0)
+        .addReg(TlsReg);
+
+      if (SaveScratch2)
+        BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
+    }
   }
=20
   // This jump is taken if SP >=3D (Stacklet Limit + Stack Space required).
   // It jumps to normal execution of the function body.
-  BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
+  BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
=20
   // On 32 bit we first push the arguments size and then the frame size. O=
n 64
   // bit, we pass the stack frame size in r10 and the argument size in r11.
@@ -1403,9 +1509,6 @@
     MF.getRegInfo().setPhysRegUsed(X86::R10);
     MF.getRegInfo().setPhysRegUsed(X86::R11);
   } else {
-    // Since we'll call __morestack, stack alignment needs to be preserved.
-    BuildMI(allocMBB, DL, TII.get(X86::SUB32ri), X86::ESP).addReg(X86::ESP)
-      .addImm(8);
     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
       .addImm(X86FI->getArgumentStackSize());
     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
@@ -1420,23 +1523,12 @@
     BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
       .addExternalSymbol("__morestack");
=20
-  // __morestack only seems to remove 8 bytes off the stack. Add back the
-  // additional 8 bytes we added before pushing the arguments.
-  if (!Is64Bit)
-    BuildMI(allocMBB, DL, TII.get(X86::ADD32ri), X86::ESP).addReg(X86::ESP)
-      .addImm(8);
-  BuildMI(allocMBB, DL, TII.get(X86::RET));
+  if (IsNested)
+    BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
+  else
+    BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
=20
-  if (IsNested)
-    BuildMI(restoreR10MBB, DL, TII.get(X86::MOV64rr), X86::R10)
-      .addReg(X86::RAX);
-
-  if (IsNested) {
-    allocMBB->addSuccessor(restoreR10MBB);
-    restoreR10MBB->addSuccessor(&prologueMBB);
-  } else {
-    allocMBB->addSuccessor(&prologueMBB);
-  }
+  allocMBB->addSuccessor(&prologueMBB);
=20
   checkMBB->addSuccessor(allocMBB);
   checkMBB->addSuccessor(&prologueMBB);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Fr=
ameLowering.h
--- a/head/contrib/llvm/lib/Target/X86/X86FrameLowering.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86FrameLowering.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D-- X86TargetFrameLowering.h - Define frame lowering for X86 ---*- C++=
 -*-=3D=3D=3D//
+//=3D=3D=3D-- X86TargetFrameLowering.h - Define frame lowering for X86 -*-=
 C++ -*-=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86IS=
elDAGToDAG.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86ISelDAGToDAG.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -21,7 +21,6 @@
 #include "X86TargetMachine.h"
 #include "llvm/Instructions.h"
 #include "llvm/Intrinsics.h"
-#include "llvm/Support/CFG.h"
 #include "llvm/Type.h"
 #include "llvm/CodeGen/FunctionLoweringInfo.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
@@ -32,11 +31,11 @@
 #include "llvm/CodeGen/SelectionDAGISel.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
+#include "llvm/Support/CFG.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/Statistic.h"
 using namespace llvm;
=20
@@ -540,7 +539,7 @@
   const TargetInstrInfo *TII =3D TM.getInstrInfo();
   if (Subtarget->isTargetCygMing()) {
     unsigned CallOp =3D
-      Subtarget->is64Bit() ? X86::WINCALL64pcrel32 : X86::CALLpcrel32;
+      Subtarget->is64Bit() ? X86::CALL64pcrel32 : X86::CALLpcrel32;
     BuildMI(BB, DebugLoc(),
             TII->get(CallOp)).addExternalSymbol("__main");
   }
@@ -621,14 +620,14 @@
=20
   // Handle X86-64 rip-relative addresses.  We check this before checking =
direct
   // folding because RIP is preferable to non-RIP accesses.
-  if (Subtarget->is64Bit() &&
+  if (Subtarget->is64Bit() && N.getOpcode() =3D=3D X86ISD::WrapperRIP &&
       // Under X86-64 non-small code model, GV (and friends) are 64-bits, =
so
       // they cannot be folded into immediate fields.
       // FIXME: This can be improved for kernel and other models?
-      (M =3D=3D CodeModel::Small || M =3D=3D CodeModel::Kernel) &&
-      // Base and index reg must be 0 in order to use %rip as base and low=
ering
-      // must allow RIP.
-      !AM.hasBaseOrIndexReg() && N.getOpcode() =3D=3D X86ISD::WrapperRIP) {
+      (M =3D=3D CodeModel::Small || M =3D=3D CodeModel::Kernel)) {
+    // Base and index reg must be 0 in order to use %rip as base.
+    if (AM.hasBaseOrIndexReg())
+      return true;
     if (GlobalAddressSDNode *G =3D dyn_cast<GlobalAddressSDNode>(N0)) {
       X86ISelAddressMode Backup =3D AM;
       AM.GV =3D G->getGlobal();
@@ -663,11 +662,12 @@
   }
=20
   // Handle the case when globals fit in our immediate field: This is true=
 for
-  // X86-32 always and X86-64 when in -static -mcmodel=3Dsmall mode.  In 6=
4-bit
-  // mode, this results in a non-RIP-relative computation.
+  // X86-32 always and X86-64 when in -mcmodel=3Dsmall mode.  In 64-bit
+  // mode, this only applies to a non-RIP-relative computation.
   if (!Subtarget->is64Bit() ||
-      ((M =3D=3D CodeModel::Small || M =3D=3D CodeModel::Kernel) &&
-       TM.getRelocationModel() =3D=3D Reloc::Static)) {
+      M =3D=3D CodeModel::Small || M =3D=3D CodeModel::Kernel) {
+    assert(N.getOpcode() !=3D X86ISD::WrapperRIP &&
+           "RIP-relative addressing already handled");
     if (GlobalAddressSDNode *G =3D dyn_cast<GlobalAddressSDNode>(N0)) {
       AM.GV =3D G->getGlobal();
       AM.Disp +=3D G->getOffset();
@@ -725,6 +725,213 @@
   return false;
 }
=20
+// Insert a node into the DAG at least before the Pos node's position. This
+// will reposition the node as needed, and will assign it a node ID that i=
s <=3D
+// the Pos node's ID. Note that this does *not* preserve the uniqueness of=
 node
+// IDs! The selection DAG must no longer depend on their uniqueness when t=
his
+// is used.
+static void InsertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
+  if (N.getNode()->getNodeId() =3D=3D -1 ||
+      N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
+    DAG.RepositionNode(Pos.getNode(), N.getNode());
+    N.getNode()->setNodeId(Pos.getNode()->getNodeId());
+  }
+}
+
+// Transform "(X >> (8-C1)) & C2" to "(X >> 8) & 0xff)" if safe. This
+// allows us to convert the shift and and into an h-register extract and
+// a scaled index. Returns false if the simplification is performed.
+static bool FoldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
+                                      uint64_t Mask,
+                                      SDValue Shift, SDValue X,
+                                      X86ISelAddressMode &AM) {
+  if (Shift.getOpcode() !=3D ISD::SRL ||
+      !isa<ConstantSDNode>(Shift.getOperand(1)) ||
+      !Shift.hasOneUse())
+    return true;
+
+  int ScaleLog =3D 8 - Shift.getConstantOperandVal(1);
+  if (ScaleLog <=3D 0 || ScaleLog >=3D 4 ||
+      Mask !=3D (0xffu << ScaleLog))
+    return true;
+
+  EVT VT =3D N.getValueType();
+  DebugLoc DL =3D N.getDebugLoc();
+  SDValue Eight =3D DAG.getConstant(8, MVT::i8);
+  SDValue NewMask =3D DAG.getConstant(0xff, VT);
+  SDValue Srl =3D DAG.getNode(ISD::SRL, DL, VT, X, Eight);
+  SDValue And =3D DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
+  SDValue ShlCount =3D DAG.getConstant(ScaleLog, MVT::i8);
+  SDValue Shl =3D DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
+
+  // Insert the new nodes into the topological ordering. We must do this in
+  // a valid topological ordering as nothing is going to go back and re-so=
rt
+  // these nodes. We continually insert before 'N' in sequence as this is
+  // essentially a pre-flattened and pre-sorted sequence of nodes. There i=
s no
+  // hierarchy left to express.
+  InsertDAGNode(DAG, N, Eight);
+  InsertDAGNode(DAG, N, Srl);
+  InsertDAGNode(DAG, N, NewMask);
+  InsertDAGNode(DAG, N, And);
+  InsertDAGNode(DAG, N, ShlCount);
+  InsertDAGNode(DAG, N, Shl);
+  DAG.ReplaceAllUsesWith(N, Shl);
+  AM.IndexReg =3D And;
+  AM.Scale =3D (1 << ScaleLog);
+  return false;
+}
+
+// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if th=
is
+// allows us to fold the shift into this addressing mode. Returns false if=
 the
+// transform succeeded.
+static bool FoldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
+                                        uint64_t Mask,
+                                        SDValue Shift, SDValue X,
+                                        X86ISelAddressMode &AM) {
+  if (Shift.getOpcode() !=3D ISD::SHL ||
+      !isa<ConstantSDNode>(Shift.getOperand(1)))
+    return true;
+
+  // Not likely to be profitable if either the AND or SHIFT node has more
+  // than one use (unless all uses are for address computation). Besides,
+  // isel mechanism requires their node ids to be reused.
+  if (!N.hasOneUse() || !Shift.hasOneUse())
+    return true;
+
+  // Verify that the shift amount is something we can fold.
+  unsigned ShiftAmt =3D Shift.getConstantOperandVal(1);
+  if (ShiftAmt !=3D 1 && ShiftAmt !=3D 2 && ShiftAmt !=3D 3)
+    return true;
+
+  EVT VT =3D N.getValueType();
+  DebugLoc DL =3D N.getDebugLoc();
+  SDValue NewMask =3D DAG.getConstant(Mask >> ShiftAmt, VT);
+  SDValue NewAnd =3D DAG.getNode(ISD::AND, DL, VT, X, NewMask);
+  SDValue NewShift =3D DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOper=
and(1));
+
+  // Insert the new nodes into the topological ordering. We must do this in
+  // a valid topological ordering as nothing is going to go back and re-so=
rt
+  // these nodes. We continually insert before 'N' in sequence as this is
+  // essentially a pre-flattened and pre-sorted sequence of nodes. There i=
s no
+  // hierarchy left to express.
+  InsertDAGNode(DAG, N, NewMask);
+  InsertDAGNode(DAG, N, NewAnd);
+  InsertDAGNode(DAG, N, NewShift);
+  DAG.ReplaceAllUsesWith(N, NewShift);
+
+  AM.Scale =3D 1 << ShiftAmt;
+  AM.IndexReg =3D NewAnd;
+  return false;
+}
+
+// Implement some heroics to detect shifts of masked values where the mask=
 can
+// be replaced by extending the shift and undoing that in the addressing m=
ode
+// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (a=
nd
+// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be don=
e in
+// the addressing mode. This results in code such as:
+//
+//   int f(short *y, int *lookup_table) {
+//     ...
+//     return *y + lookup_table[*y >> 11];
+//   }
+//
+// Turning into:
+//   movzwl (%rdi), %eax
+//   movl %eax, %ecx
+//   shrl $11, %ecx
+//   addl (%rsi,%rcx,4), %eax
+//
+// Instead of:
+//   movzwl (%rdi), %eax
+//   movl %eax, %ecx
+//   shrl $9, %ecx
+//   andl $124, %rcx
+//   addl (%rsi,%rcx), %eax
+//
+// Note that this function assumes the mask is provided as a mask *after* =
the
+// value is shifted. The input chain may or may not match that, but comput=
ing
+// such a mask is trivial.
+static bool FoldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
+                                    uint64_t Mask,
+                                    SDValue Shift, SDValue X,
+                                    X86ISelAddressMode &AM) {
+  if (Shift.getOpcode() !=3D ISD::SRL || !Shift.hasOneUse() ||
+      !isa<ConstantSDNode>(Shift.getOperand(1)))
+    return true;
+
+  unsigned ShiftAmt =3D Shift.getConstantOperandVal(1);
+  unsigned MaskLZ =3D CountLeadingZeros_64(Mask);
+  unsigned MaskTZ =3D CountTrailingZeros_64(Mask);
+
+  // The amount of shift we're trying to fit into the addressing mode is t=
aken
+  // from the trailing zeros of the mask.
+  unsigned AMShiftAmt =3D MaskTZ;
+
+  // There is nothing we can do here unless the mask is removing some bits.
+  // Also, the addressing mode can only represent shifts of 1, 2, or 3 bit=
s.
+  if (AMShiftAmt <=3D 0 || AMShiftAmt > 3) return true;
+
+  // We also need to ensure that mask is a continuous run of bits.
+  if (CountTrailingOnes_64(Mask >> MaskTZ) + MaskTZ + MaskLZ !=3D 64) retu=
rn true;
+
+  // Scale the leading zero count down based on the actual size of the val=
ue.
+  // Also scale it down based on the size of the shift.
+  MaskLZ -=3D (64 - X.getValueSizeInBits()) + ShiftAmt;
+
+  // The final check is to ensure that any masked out high bits of X are
+  // already known to be zero. Otherwise, the mask has a semantic impact
+  // other than masking out a couple of low bits. Unfortunately, because of
+  // the mask, zero extensions will be removed from operands in some cases.
+  // This code works extra hard to look through extensions because we can
+  // replace them with zero extensions cheaply if necessary.
+  bool ReplacingAnyExtend =3D false;
+  if (X.getOpcode() =3D=3D ISD::ANY_EXTEND) {
+    unsigned ExtendBits =3D
+      X.getValueSizeInBits() - X.getOperand(0).getValueSizeInBits();
+    // Assume that we'll replace the any-extend with a zero-extend, and
+    // narrow the search to the extended value.
+    X =3D X.getOperand(0);
+    MaskLZ =3D ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
+    ReplacingAnyExtend =3D true;
+  }
+  APInt MaskedHighBits =3D APInt::getHighBitsSet(X.getValueSizeInBits(),
+                                               MaskLZ);
+  APInt KnownZero, KnownOne;
+  DAG.ComputeMaskedBits(X, KnownZero, KnownOne);
+  if (MaskedHighBits !=3D KnownZero) return true;
+
+  // We've identified a pattern that can be transformed into a single shift
+  // and an addressing mode. Make it so.
+  EVT VT =3D N.getValueType();
+  if (ReplacingAnyExtend) {
+    assert(X.getValueType() !=3D VT);
+    // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
+    SDValue NewX =3D DAG.getNode(ISD::ZERO_EXTEND, X.getDebugLoc(), VT, X);
+    InsertDAGNode(DAG, N, NewX);
+    X =3D NewX;
+  }
+  DebugLoc DL =3D N.getDebugLoc();
+  SDValue NewSRLAmt =3D DAG.getConstant(ShiftAmt + AMShiftAmt, MVT::i8);
+  SDValue NewSRL =3D DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
+  SDValue NewSHLAmt =3D DAG.getConstant(AMShiftAmt, MVT::i8);
+  SDValue NewSHL =3D DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
+
+  // Insert the new nodes into the topological ordering. We must do this in
+  // a valid topological ordering as nothing is going to go back and re-so=
rt
+  // these nodes. We continually insert before 'N' in sequence as this is
+  // essentially a pre-flattened and pre-sorted sequence of nodes. There i=
s no
+  // hierarchy left to express.
+  InsertDAGNode(DAG, N, NewSRLAmt);
+  InsertDAGNode(DAG, N, NewSRL);
+  InsertDAGNode(DAG, N, NewSHLAmt);
+  InsertDAGNode(DAG, N, NewSHL);
+  DAG.ReplaceAllUsesWith(N, NewSHL);
+
+  AM.Scale =3D 1 << AMShiftAmt;
+  AM.IndexReg =3D NewSRL;
+  return false;
+}
+
 bool X86DAGToDAGISel::MatchAddressRecursively(SDValue N, X86ISelAddressMod=
e &AM,
                                               unsigned Depth) {
   DebugLoc dl =3D N.getDebugLoc();
@@ -814,6 +1021,33 @@
     break;
     }
=20
+  case ISD::SRL: {
+    // Scale must not be used already.
+    if (AM.IndexReg.getNode() !=3D 0 || AM.Scale !=3D 1) break;
+
+    SDValue And =3D N.getOperand(0);
+    if (And.getOpcode() !=3D ISD::AND) break;
+    SDValue X =3D And.getOperand(0);
+
+    // We only handle up to 64-bit values here as those are what matter for
+    // addressing mode optimizations.
+    if (X.getValueSizeInBits() > 64) break;
+
+    // The mask used for the transform is expected to be post-shift, but we
+    // found the shift first so just apply the shift to the mask before pa=
ssing
+    // it down.
+    if (!isa<ConstantSDNode>(N.getOperand(1)) ||
+        !isa<ConstantSDNode>(And.getOperand(1)))
+      break;
+    uint64_t Mask =3D And.getConstantOperandVal(1) >> N.getConstantOperand=
Val(1);
+
+    // Try to fold the mask and shift into the scale, and return false if =
we
+    // succeed.
+    if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
+      return false;
+    break;
+  }
+
   case ISD::SMUL_LOHI:
   case ISD::UMUL_LOHI:
     // A mul_lohi where we need the low part can be folded as a plain mult=
iply.
@@ -917,16 +1151,8 @@
     AM.Scale =3D 1;
=20
     // Insert the new nodes into the topological ordering.
-    if (Zero.getNode()->getNodeId() =3D=3D -1 ||
-        Zero.getNode()->getNodeId() > N.getNode()->getNodeId()) {
-      CurDAG->RepositionNode(N.getNode(), Zero.getNode());
-      Zero.getNode()->setNodeId(N.getNode()->getNodeId());
-    }
-    if (Neg.getNode()->getNodeId() =3D=3D -1 ||
-        Neg.getNode()->getNodeId() > N.getNode()->getNodeId()) {
-      CurDAG->RepositionNode(N.getNode(), Neg.getNode());
-      Neg.getNode()->setNodeId(N.getNode()->getNodeId());
-    }
+    InsertDAGNode(*CurDAG, N, Zero);
+    InsertDAGNode(*CurDAG, N, Neg);
     return false;
   }
=20
@@ -981,121 +1207,34 @@
     // Perform some heroic transforms on an and of a constant-count shift
     // with a constant to enable use of the scaled offset field.
=20
-    SDValue Shift =3D N.getOperand(0);
-    if (Shift.getNumOperands() !=3D 2) break;
-
     // Scale must not be used already.
     if (AM.IndexReg.getNode() !=3D 0 || AM.Scale !=3D 1) break;
=20
+    SDValue Shift =3D N.getOperand(0);
+    if (Shift.getOpcode() !=3D ISD::SRL && Shift.getOpcode() !=3D ISD::SHL=
) break;
     SDValue X =3D Shift.getOperand(0);
-    ConstantSDNode *C2 =3D dyn_cast<ConstantSDNode>(N.getOperand(1));
-    ConstantSDNode *C1 =3D dyn_cast<ConstantSDNode>(Shift.getOperand(1));
-    if (!C1 || !C2) break;
=20
-    // Handle "(X >> (8-C1)) & C2" as "(X >> 8) & 0xff)" if safe. This
-    // allows us to convert the shift and and into an h-register extract a=
nd
-    // a scaled index.
-    if (Shift.getOpcode() =3D=3D ISD::SRL && Shift.hasOneUse()) {
-      unsigned ScaleLog =3D 8 - C1->getZExtValue();
-      if (ScaleLog > 0 && ScaleLog < 4 &&
-          C2->getZExtValue() =3D=3D (UINT64_C(0xff) << ScaleLog)) {
-        SDValue Eight =3D CurDAG->getConstant(8, MVT::i8);
-        SDValue Mask =3D CurDAG->getConstant(0xff, N.getValueType());
-        SDValue Srl =3D CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
-                                      X, Eight);
-        SDValue And =3D CurDAG->getNode(ISD::AND, dl, N.getValueType(),
-                                      Srl, Mask);
-        SDValue ShlCount =3D CurDAG->getConstant(ScaleLog, MVT::i8);
-        SDValue Shl =3D CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
-                                      And, ShlCount);
+    // We only handle up to 64-bit values here as those are what matter for
+    // addressing mode optimizations.
+    if (X.getValueSizeInBits() > 64) break;
=20
-        // Insert the new nodes into the topological ordering.
-        if (Eight.getNode()->getNodeId() =3D=3D -1 ||
-            Eight.getNode()->getNodeId() > X.getNode()->getNodeId()) {
-          CurDAG->RepositionNode(X.getNode(), Eight.getNode());
-          Eight.getNode()->setNodeId(X.getNode()->getNodeId());
-        }
-        if (Mask.getNode()->getNodeId() =3D=3D -1 ||
-            Mask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
-          CurDAG->RepositionNode(X.getNode(), Mask.getNode());
-          Mask.getNode()->setNodeId(X.getNode()->getNodeId());
-        }
-        if (Srl.getNode()->getNodeId() =3D=3D -1 ||
-            Srl.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
-          CurDAG->RepositionNode(Shift.getNode(), Srl.getNode());
-          Srl.getNode()->setNodeId(Shift.getNode()->getNodeId());
-        }
-        if (And.getNode()->getNodeId() =3D=3D -1 ||
-            And.getNode()->getNodeId() > N.getNode()->getNodeId()) {
-          CurDAG->RepositionNode(N.getNode(), And.getNode());
-          And.getNode()->setNodeId(N.getNode()->getNodeId());
-        }
-        if (ShlCount.getNode()->getNodeId() =3D=3D -1 ||
-            ShlCount.getNode()->getNodeId() > X.getNode()->getNodeId()) {
-          CurDAG->RepositionNode(X.getNode(), ShlCount.getNode());
-          ShlCount.getNode()->setNodeId(N.getNode()->getNodeId());
-        }
-        if (Shl.getNode()->getNodeId() =3D=3D -1 ||
-            Shl.getNode()->getNodeId() > N.getNode()->getNodeId()) {
-          CurDAG->RepositionNode(N.getNode(), Shl.getNode());
-          Shl.getNode()->setNodeId(N.getNode()->getNodeId());
-        }
-        CurDAG->ReplaceAllUsesWith(N, Shl);
-        AM.IndexReg =3D And;
-        AM.Scale =3D (1 << ScaleLog);
-        return false;
-      }
-    }
+    if (!isa<ConstantSDNode>(N.getOperand(1)))
+      break;
+    uint64_t Mask =3D N.getConstantOperandVal(1);
=20
-    // Handle "(X << C1) & C2" as "(X & (C2>>C1)) << C1" if safe and if th=
is
-    // allows us to fold the shift into this addressing mode.
-    if (Shift.getOpcode() !=3D ISD::SHL) break;
+    // Try to fold the mask and shift into an extract and scale.
+    if (!FoldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
+      return false;
=20
-    // Not likely to be profitable if either the AND or SHIFT node has more
-    // than one use (unless all uses are for address computation). Besides,
-    // isel mechanism requires their node ids to be reused.
-    if (!N.hasOneUse() || !Shift.hasOneUse())
-      break;
-   =20
-    // Verify that the shift amount is something we can fold.
-    unsigned ShiftCst =3D C1->getZExtValue();
-    if (ShiftCst !=3D 1 && ShiftCst !=3D 2 && ShiftCst !=3D 3)
-      break;
-   =20
-    // Get the new AND mask, this folds to a constant.
-    SDValue NewANDMask =3D CurDAG->getNode(ISD::SRL, dl, N.getValueType(),
-                                         SDValue(C2, 0), SDValue(C1, 0));
-    SDValue NewAND =3D CurDAG->getNode(ISD::AND, dl, N.getValueType(), X,=20
-                                     NewANDMask);
-    SDValue NewSHIFT =3D CurDAG->getNode(ISD::SHL, dl, N.getValueType(),
-                                       NewAND, SDValue(C1, 0));
+    // Try to fold the mask and shift directly into the scale.
+    if (!FoldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
+      return false;
=20
-    // Insert the new nodes into the topological ordering.
-    if (C1->getNodeId() > X.getNode()->getNodeId()) {
-      CurDAG->RepositionNode(X.getNode(), C1);
-      C1->setNodeId(X.getNode()->getNodeId());
-    }
-    if (NewANDMask.getNode()->getNodeId() =3D=3D -1 ||
-        NewANDMask.getNode()->getNodeId() > X.getNode()->getNodeId()) {
-      CurDAG->RepositionNode(X.getNode(), NewANDMask.getNode());
-      NewANDMask.getNode()->setNodeId(X.getNode()->getNodeId());
-    }
-    if (NewAND.getNode()->getNodeId() =3D=3D -1 ||
-        NewAND.getNode()->getNodeId() > Shift.getNode()->getNodeId()) {
-      CurDAG->RepositionNode(Shift.getNode(), NewAND.getNode());
-      NewAND.getNode()->setNodeId(Shift.getNode()->getNodeId());
-    }
-    if (NewSHIFT.getNode()->getNodeId() =3D=3D -1 ||
-        NewSHIFT.getNode()->getNodeId() > N.getNode()->getNodeId()) {
-      CurDAG->RepositionNode(N.getNode(), NewSHIFT.getNode());
-      NewSHIFT.getNode()->setNodeId(N.getNode()->getNodeId());
-    }
-
-    CurDAG->ReplaceAllUsesWith(N, NewSHIFT);
-   =20
-    AM.Scale =3D 1 << ShiftCst;
-    AM.IndexReg =3D NewAND;
-    return false;
+    // Try to swap the mask and shift to place shifts which can be done as
+    // a scale on the outside of the mask.
+    if (!FoldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
+      return false;
+    break;
   }
   }
=20
@@ -1515,7 +1654,7 @@
   AtomicSzEnd
 };
=20
-static const unsigned int AtomicOpcTbl[AtomicOpcEnd][AtomicSzEnd] =3D {
+static const uint16_t AtomicOpcTbl[AtomicOpcEnd][AtomicSzEnd] =3D {
   {
     X86::LOCK_OR8mi,
     X86::LOCK_OR8mr,
@@ -1709,6 +1848,96 @@
   return true;
 }
=20
+/// isLoadIncOrDecStore - Check whether or not the chain ending in StoreNo=
de
+/// is suitable for doing the {load; increment or decrement; store} to mod=
ify
+/// transformation.
+static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,=20
+                                SDValue StoredVal, SelectionDAG *CurDAG,
+                                LoadSDNode* &LoadNode, SDValue &InputChain=
) {
+
+  // is the value stored the result of a DEC or INC?
+  if (!(Opc =3D=3D X86ISD::DEC || Opc =3D=3D X86ISD::INC)) return false;
+
+  // is the stored value result 0 of the load?
+  if (StoredVal.getResNo() !=3D 0) return false;
+
+  // are there other uses of the loaded value than the inc or dec?
+  if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
+
+  // is the store non-extending and non-indexed?
+  if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
+    return false;
+
+  SDValue Load =3D StoredVal->getOperand(0);
+  // Is the stored value a non-extending and non-indexed load?
+  if (!ISD::isNormalLoad(Load.getNode())) return false;
+
+  // Return LoadNode by reference.
+  LoadNode =3D cast<LoadSDNode>(Load);
+  // is the size of the value one that we can handle? (i.e. 64, 32, 16, or=
 8)
+  EVT LdVT =3D LoadNode->getMemoryVT();   =20
+  if (LdVT !=3D MVT::i64 && LdVT !=3D MVT::i32 && LdVT !=3D MVT::i16 &&=20
+      LdVT !=3D MVT::i8)
+    return false;
+
+  // Is store the only read of the loaded value?
+  if (!Load.hasOneUse())
+    return false;
+ =20
+  // Is the address of the store the same as the load?
+  if (LoadNode->getBasePtr() !=3D StoreNode->getBasePtr() ||
+      LoadNode->getOffset() !=3D StoreNode->getOffset())
+    return false;
+
+  // Check if the chain is produced by the load or is a TokenFactor with
+  // the load output chain as an operand. Return InputChain by reference.
+  SDValue Chain =3D StoreNode->getChain();
+
+  bool ChainCheck =3D false;
+  if (Chain =3D=3D Load.getValue(1)) {
+    ChainCheck =3D true;
+    InputChain =3D LoadNode->getChain();
+  } else if (Chain.getOpcode() =3D=3D ISD::TokenFactor) {
+    SmallVector<SDValue, 4> ChainOps;
+    for (unsigned i =3D 0, e =3D Chain.getNumOperands(); i !=3D e; ++i) {
+      SDValue Op =3D Chain.getOperand(i);
+      if (Op =3D=3D Load.getValue(1)) {
+        ChainCheck =3D true;
+        continue;
+      }
+      ChainOps.push_back(Op);
+    }
+
+    if (ChainCheck)
+      // Make a new TokenFactor with all the other input chains except
+      // for the load.
+      InputChain =3D CurDAG->getNode(ISD::TokenFactor, Chain.getDebugLoc(),
+                                   MVT::Other, &ChainOps[0], ChainOps.size=
());
+  }
+  if (!ChainCheck)
+    return false;
+
+  return true;
+}
+
+/// getFusedLdStOpcode - Get the appropriate X86 opcode for an in memory
+/// increment or decrement. Opc should be X86ISD::DEC or X86ISD::INC.
+static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
+  if (Opc =3D=3D X86ISD::DEC) {
+    if (LdVT =3D=3D MVT::i64) return X86::DEC64m;
+    if (LdVT =3D=3D MVT::i32) return X86::DEC32m;
+    if (LdVT =3D=3D MVT::i16) return X86::DEC16m;
+    if (LdVT =3D=3D MVT::i8)  return X86::DEC8m;
+  } else {
+    assert(Opc =3D=3D X86ISD::INC && "unrecognized opcode");
+    if (LdVT =3D=3D MVT::i64) return X86::INC64m;
+    if (LdVT =3D=3D MVT::i32) return X86::INC32m;
+    if (LdVT =3D=3D MVT::i16) return X86::INC16m;
+    if (LdVT =3D=3D MVT::i8)  return X86::INC8m;
+  }
+  llvm_unreachable("unrecognized size for LdVT");
+}
+
 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
   EVT NVT =3D Node->getValueType(0);
   unsigned Opc, MOpc;
@@ -1829,7 +2058,6 @@
     SDNode *New =3D CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),=
NewCst);
     return CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
                                 getI8Imm(ShlVal));
-    break;
   }
   case X86ISD::UMUL: {
     SDValue N0 =3D Node->getOperand(0);
@@ -2114,7 +2342,9 @@
         HasNoSignedComparisonUses(Node))
       // Look past the truncate if CMP is the only use of it.
       N0 =3D N0.getOperand(0);
-    if (N0.getNode()->getOpcode() =3D=3D ISD::AND && N0.getNode()->hasOneU=
se() &&
+    if ((N0.getNode()->getOpcode() =3D=3D ISD::AND ||
+         (N0.getResNo() =3D=3D 0 && N0.getNode()->getOpcode() =3D=3D X86IS=
D::AND)) &&
+        N0.getNode()->hasOneUse() &&
         N0.getValueType() !=3D MVT::i8 &&
         X86::isZeroNode(N1)) {
       ConstantSDNode *C =3D dyn_cast<ConstantSDNode>(N0.getNode()->getOper=
and(1));
@@ -2129,7 +2359,7 @@
=20
         // On x86-32, only the ABCD registers have 8-bit subregisters.
         if (!Subtarget->is64Bit()) {
-          TargetRegisterClass *TRC =3D 0;
+          const TargetRegisterClass *TRC;
           switch (N0.getValueType().getSimpleVT().SimpleTy) {
           case MVT::i32: TRC =3D &X86::GR32_ABCDRegClass; break;
           case MVT::i16: TRC =3D &X86::GR16_ABCDRegClass; break;
@@ -2158,7 +2388,7 @@
         SDValue Reg =3D N0.getNode()->getOperand(0);
=20
         // Put the value in an ABCD register.
-        TargetRegisterClass *TRC =3D 0;
+        const TargetRegisterClass *TRC;
         switch (N0.getValueType().getSimpleVT().SimpleTy) {
         case MVT::i64: TRC =3D &X86::GR64_ABCDRegClass; break;
         case MVT::i32: TRC =3D &X86::GR32_ABCDRegClass; break;
@@ -2214,6 +2444,56 @@
     }
     break;
   }
+  case ISD::STORE: {
+    // Change a chain of {load; incr or dec; store} of the same value into
+    // a simple increment or decrement through memory of that value, if the
+    // uses of the modified value and its address are suitable.
+    // The DEC64m tablegen pattern is currently not able to match the case=
 where
+    // the EFLAGS on the original DEC are used. (This also applies to=20
+    // {INC,DEC}X{64,32,16,8}.)
+    // We'll need to improve tablegen to allow flags to be transferred fro=
m a
+    // node in the pattern to the result node.  probably with a new keyword
+    // for example, we have this
+    // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$d=
st",
+    //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
+    //   (implicit EFLAGS)]>;
+    // but maybe need something like this
+    // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$d=
st",
+    //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
+    //   (transferrable EFLAGS)]>;
+
+    StoreSDNode *StoreNode =3D cast<StoreSDNode>(Node);
+    SDValue StoredVal =3D StoreNode->getOperand(1);
+    unsigned Opc =3D StoredVal->getOpcode();
+
+    LoadSDNode *LoadNode =3D 0;
+    SDValue InputChain;
+    if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
+                             LoadNode, InputChain))
+      break;
+
+    SDValue Base, Scale, Index, Disp, Segment;
+    if (!SelectAddr(LoadNode, LoadNode->getBasePtr(),
+                    Base, Scale, Index, Disp, Segment))
+      break;
+
+    MachineSDNode::mmo_iterator MemOp =3D MF->allocateMemRefsArray(2);
+    MemOp[0] =3D StoreNode->getMemOperand();
+    MemOp[1] =3D LoadNode->getMemOperand();
+    const SDValue Ops[] =3D { Base, Scale, Index, Disp, Segment, InputChai=
n };
+    EVT LdVT =3D LoadNode->getMemoryVT();   =20
+    unsigned newOpc =3D getFusedLdStOpcode(LdVT, Opc);
+    MachineSDNode *Result =3D CurDAG->getMachineNode(newOpc,
+                                                   Node->getDebugLoc(),
+                                                   MVT::i32, MVT::Other, O=
ps,
+                                                   array_lengthof(Ops));
+    Result->setMemRefs(MemOp, MemOp + 2);
+
+    ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
+    ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
+
+    return Result;
+  }
   }
=20
   SDNode *ResNode =3D SelectCode(Node);
@@ -2254,6 +2534,6 @@
 /// X86-specific DAG, ready for instruction scheduling.
 ///
 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
-                                     llvm::CodeGenOpt::Level OptLevel) {
+                                     CodeGenOpt::Level OptLevel) {
   return new X86DAGToDAGISel(TM, OptLevel);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86IS=
elLowering.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86ISelLowering.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86ISelLowering.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -13,9 +13,9 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #define DEBUG_TYPE "x86-isel"
+#include "X86ISelLowering.h"
 #include "X86.h"
 #include "X86InstrBuilder.h"
-#include "X86ISelLowering.h"
 #include "X86TargetMachine.h"
 #include "X86TargetObjectFile.h"
 #include "Utils/X86ShuffleDecode.h"
@@ -35,25 +35,21 @@
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCSymbol.h"
-#include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/StringExtras.h"
-#include "llvm/ADT/VectorExtras.h"
+#include "llvm/ADT/VariadicFunction.h"
 #include "llvm/Support/CallSite.h"
 #include "llvm/Support/Debug.h"
-#include "llvm/Support/Dwarf.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
-#include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetOptions.h"
+#include <bitset>
 using namespace llvm;
-using namespace dwarf;
=20
 STATISTIC(NumTailCalls, "Number of tail calls");
=20
@@ -61,17 +57,6 @@
 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
                        SDValue V2);
=20
-static SDValue Insert128BitVector(SDValue Result,
-                                  SDValue Vec,
-                                  SDValue Idx,
-                                  SelectionDAG &DAG,
-                                  DebugLoc dl);
-
-static SDValue Extract128BitVector(SDValue Vec,
-                                   SDValue Idx,
-                                   SelectionDAG &DAG,
-                                   DebugLoc dl);
-
 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
 /// simple subregister reference.  Idx is an index in the 128 bits we
@@ -169,8 +154,8 @@
 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
   : TargetLowering(TM, createTLOF(TM)) {
   Subtarget =3D &TM.getSubtarget<X86Subtarget>();
-  X86ScalarSSEf64 =3D Subtarget->hasXMMInt();
-  X86ScalarSSEf32 =3D Subtarget->hasXMM();
+  X86ScalarSSEf64 =3D Subtarget->hasSSE2();
+  X86ScalarSSEf32 =3D Subtarget->hasSSE1();
   X86StackPtr =3D Subtarget->is64Bit() ? X86::RSP : X86::ESP;
=20
   RegInfo =3D TM.getRegisterInfo();
@@ -186,8 +171,11 @@
=20
   // For 64-bit since we have so many registers use the ILP scheduler, for
   // 32-bit code use the register pressure specific scheduling.
+  // For 32 bit Atom, use Hybrid (register pressure + latency) scheduling.
   if (Subtarget->is64Bit())
     setSchedulingPreference(Sched::ILP);
+  else if (Subtarget->isAtom())=20
+    setSchedulingPreference(Sched::Hybrid);
   else
     setSchedulingPreference(Sched::RegPressure);
   setStackPointerRegisterToSaveRestore(X86StackPtr);
@@ -199,15 +187,18 @@
     setLibcallName(RTLIB::SREM_I64, "_allrem");
     setLibcallName(RTLIB::UREM_I64, "_aullrem");
     setLibcallName(RTLIB::MUL_I64, "_allmul");
-    setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
-    setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
-    setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
-    setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
+
+    // The _ftol2 runtime function has an unusual calling conv, which
+    // is modeled by a special pseudo-instruction.
+    setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
+    setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
+    setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
+    setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
   }
=20
   if (Subtarget->isTargetDarwin()) {
@@ -256,8 +247,8 @@
=20
   if (Subtarget->is64Bit()) {
     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
-    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
-  } else if (!UseSoftFloat) {
+    setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
+  } else if (!TM.Options.UseSoftFloat) {
     // We have an algorithm for SSE2->double, and we turn this into a
     // 64-bit FILD followed by conditional FADD for other targets.
     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
@@ -271,7 +262,7 @@
   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
=20
-  if (!UseSoftFloat) {
+  if (!TM.Options.UseSoftFloat) {
     // SSE has no i16 to fp conversion, only i32
     if (X86ScalarSSEf32) {
       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
@@ -314,7 +305,7 @@
   if (Subtarget->is64Bit()) {
     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
-  } else if (!UseSoftFloat) {
+  } else if (!TM.Options.UseSoftFloat) {
     // Since AVX is a superset of SSE3, only check for SSE here.
     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
       // Expand FP_TO_UINT into a select.
@@ -327,6 +318,12 @@
       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
   }
=20
+  if (isTargetFTOL()) {
+    // Use the _ftol2 runtime function, which has a pseudo-instruction
+    // to handle its weird calling convention.
+    setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
+  }
+
   // TODO: when we have SSE, these could be more efficient, by using movd/=
movq.
   if (!X86ScalarSSEf64) {
     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
@@ -379,10 +376,18 @@
   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
=20
+  // Promote the i8 variants and force them on up to i32 which has a short=
er
+  // encoding.
+  setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
+  AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
+  AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
   if (Subtarget->hasBMI()) {
-    setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
+    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
+    setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
+    if (Subtarget->is64Bit())
+      setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
   } else {
-    setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
     if (Subtarget->is64Bit())
@@ -390,13 +395,27 @@
   }
=20
   if (Subtarget->hasLZCNT()) {
+    // When promoting the i8 variants, force them to i32 for a shorter
+    // encoding.
     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
+    AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
+    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
+    AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
+    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
+    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
+    if (Subtarget->is64Bit())
+      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
   } else {
     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
-    if (Subtarget->is64Bit())
+    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
+    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
+    setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
+    if (Subtarget->is64Bit()) {
       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
+      setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
+    }
   }
=20
   if (Subtarget->hasPOPCNT()) {
@@ -459,7 +478,7 @@
     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
   }
=20
-  if (Subtarget->hasXMM())
+  if (Subtarget->hasSSE1())
     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
=20
   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
@@ -538,14 +557,14 @@
   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
                        MVT::i64 : MVT::i32, Custom);
-  else if (EnableSegmentedStacks)
+  else if (TM.Options.EnableSegmentedStacks)
     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
                        MVT::i64 : MVT::i32, Custom);
   else
     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
                        MVT::i64 : MVT::i32, Expand);
=20
-  if (!UseSoftFloat && X86ScalarSSEf64) {
+  if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
     // f32 and f64 use SSE.
     // Set up the FP register classes.
     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
@@ -577,7 +596,7 @@
     // cases we handle.
     addLegalFPImmediate(APFloat(+0.0)); // xorpd
     addLegalFPImmediate(APFloat(+0.0f)); // xorps
-  } else if (!UseSoftFloat && X86ScalarSSEf32) {
+  } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
     // Use SSE for f32, x87 for f64.
     // Set up the FP register classes.
     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
@@ -606,11 +625,11 @@
     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
=20
-    if (!UnsafeFPMath) {
+    if (!TM.Options.UnsafeFPMath) {
       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
     }
-  } else if (!UseSoftFloat) {
+  } else if (!TM.Options.UseSoftFloat) {
     // f32 and f64 in x87.
     // Set up the FP register classes.
     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
@@ -621,7 +640,7 @@
     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
=20
-    if (!UnsafeFPMath) {
+    if (!TM.Options.UnsafeFPMath) {
       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
     }
@@ -640,7 +659,7 @@
   setOperationAction(ISD::FMA, MVT::f32, Expand);
=20
   // Long double always uses X87.
-  if (!UseSoftFloat) {
+  if (!TM.Options.UseSoftFloat) {
     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
@@ -659,11 +678,16 @@
       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
     }
=20
-    if (!UnsafeFPMath) {
+    if (!TM.Options.UnsafeFPMath) {
       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
     }
=20
+    setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
+    setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
+    setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
+    setOperationAction(ISD::FRINT,  MVT::f80, Expand);
+    setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
     setOperationAction(ISD::FMA, MVT::f80, Expand);
   }
=20
@@ -715,7 +739,9 @@
     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
+    setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Exp=
and);
     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
+    setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Exp=
and);
     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
@@ -749,7 +775,7 @@
=20
   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
   // with -msoft-float, disable use of MMX as well.
-  if (!UseSoftFloat && Subtarget->hasMMX()) {
+  if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
     // No operations on x86mmx supported, everything uses intrinsics.
   }
@@ -786,7 +812,7 @@
   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
=20
-  if (!UseSoftFloat && Subtarget->hasXMM()) {
+  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
=20
     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
@@ -803,7 +829,7 @@
     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
   }
=20
-  if (!UseSoftFloat && Subtarget->hasXMMInt()) {
+  if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
=20
     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
@@ -909,7 +935,7 @@
     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
   }
=20
-  if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
+  if (Subtarget->hasSSE41()) {
     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
@@ -924,10 +950,6 @@
     // FIXME: Do we need to handle scalar-to-vector here?
     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
=20
-    // Can turn SHL into an integer multiply.
-    setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
-    setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
-
     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
@@ -948,30 +970,47 @@
     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
=20
+    // FIXME: these should be Legal but thats only for the case where
+    // the index is constant.  For now custom expand to deal with that.
     if (Subtarget->is64Bit()) {
-      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
-      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
-    }
-  }
-
-  if (Subtarget->hasXMMInt()) {
-    setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
-    setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
+      setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
+      setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
+    }
+  }
+
+  if (Subtarget->hasSSE2()) {
+    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
-    setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
-
-    setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
-    setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
+
     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
-
-    setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
+    setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
+
     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
-  }
-
-  if (Subtarget->hasSSE42() || Subtarget->hasAVX())
+    setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
+
+    if (Subtarget->hasAVX2()) {
+      setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
+      setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
+
+      setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
+      setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
+
+      setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
+    } else {
+      setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
+      setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
+
+      setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
+      setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
+
+      setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
+    }
+  }
+
+  if (Subtarget->hasSSE42())
     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
=20
-  if (!UseSoftFloat && Subtarget->hasAVX()) {
+  if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
@@ -1008,18 +1047,14 @@
     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
=20
-    setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
-    setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
=20
-    setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
-    setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
=20
-    setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
+    setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
=20
     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
@@ -1030,25 +1065,60 @@
     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
=20
-    setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
-    setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
-    setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
-    setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
-
-    setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
-    setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
-    setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
-    setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
-
-    setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
-    setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
-    setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
-    setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
-
-    setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
-    setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
-    setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
-    // Don't lower v32i8 because there is no 128-bit byte mul
+    setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
+    setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
+    setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
+    setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
+
+    if (Subtarget->hasAVX2()) {
+      setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
+      setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
+      setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
+      setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
+
+      setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
+      setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
+      setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
+      setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
+
+      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
+      setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
+      setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
+      // Don't lower v32i8 because there is no 128-bit byte mul
+
+      setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
+
+      setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
+      setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
+
+      setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
+      setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
+
+      setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
+    } else {
+      setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
+      setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
+      setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
+      setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
+
+      setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
+      setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
+      setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
+      setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
+
+      setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
+      setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
+      setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
+      // Don't lower v32i8 because there is no 128-bit byte mul
+
+      setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
+      setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
+
+      setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
+      setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
+
+      setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
+    }
=20
     // Custom lower several nodes for 256-bit types.
     for (unsigned i =3D (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
@@ -1099,7 +1169,8 @@
   // of this type with custom code.
   for (unsigned VT =3D (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
          VT !=3D (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
-    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, C=
ustom);
+    setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
+                       Custom);
   }
=20
   // We want to custom lower some of our intrinsics.
@@ -1137,7 +1208,6 @@
   // We have target-specific dag combine patterns for the following nodes:
   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
-  setTargetDAGCombine(ISD::BUILD_VECTOR);
   setTargetDAGCombine(ISD::VSELECT);
   setTargetDAGCombine(ISD::SELECT);
   setTargetDAGCombine(ISD::SHL);
@@ -1152,9 +1222,13 @@
   setTargetDAGCombine(ISD::LOAD);
   setTargetDAGCombine(ISD::STORE);
   setTargetDAGCombine(ISD::ZERO_EXTEND);
+  setTargetDAGCombine(ISD::SIGN_EXTEND);
+  setTargetDAGCombine(ISD::TRUNCATE);
   setTargetDAGCombine(ISD::SINT_TO_FP);
   if (Subtarget->is64Bit())
     setTargetDAGCombine(ISD::MUL);
+  if (Subtarget->hasBMI())
+    setTargetDAGCombine(ISD::XOR);
=20
   computeRegisterProperties();
=20
@@ -1166,10 +1240,10 @@
   maxStoresPerMemcpyOptSize =3D Subtarget->isTargetDarwin() ? 8 : 4;
   maxStoresPerMemmove =3D 8; // For @llvm.memmove -> sequence of stores
   maxStoresPerMemmoveOptSize =3D Subtarget->isTargetDarwin() ? 8 : 4;
-  setPrefLoopAlignment(16);
+  setPrefLoopAlignment(4); // 2^4 bytes.
   benefitFromCodePlacementOpt =3D true;
=20
-  setPrefFunctionAlignment(4);
+  setPrefFunctionAlignment(4); // 2^4 bytes.
 }
=20
=20
@@ -1219,7 +1293,7 @@
   }
=20
   unsigned Align =3D 4;
-  if (Subtarget->hasXMM())
+  if (Subtarget->hasSSE1())
     getMaxByValAlign(Ty, Align);
   return Align;
 }
@@ -1230,7 +1304,7 @@
 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
 /// means there isn't a need to check it against alignment requirement,
 /// probably because the source does not need to be loaded. If
-/// 'NonScalarIntSafe' is true, that means it's safe to return a
+/// 'IsZeroVal' is true, that means it's safe to return a
 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
 /// constant so it does not need to be loaded.
@@ -1239,31 +1313,34 @@
 EVT
 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
                                        unsigned DstAlign, unsigned SrcAlig=
n,
-                                       bool NonScalarIntSafe,
+                                       bool IsZeroVal,
                                        bool MemcpyStrSrc,
                                        MachineFunction &MF) const {
   // FIXME: This turns off use of xmm stores for memset/memcpy on targets =
like
   // linux.  This is because the stack realignment code can't handle certa=
in
   // cases like PR2962.  This should be removed when PR2962 is fixed.
   const Function *F =3D MF.getFunction();
-  if (NonScalarIntSafe &&
+  if (IsZeroVal &&
       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
     if (Size >=3D 16 &&
         (Subtarget->isUnalignedMemAccessFast() ||
          ((DstAlign =3D=3D 0 || DstAlign >=3D 16) &&
           (SrcAlign =3D=3D 0 || SrcAlign >=3D 16))) &&
         Subtarget->getStackAlignment() >=3D 16) {
-      if (Subtarget->hasAVX() &&
-          Subtarget->getStackAlignment() >=3D 32)
-        return MVT::v8f32;
-      if (Subtarget->hasXMMInt())
+      if (Subtarget->getStackAlignment() >=3D 32) {
+        if (Subtarget->hasAVX2())
+          return MVT::v8i32;
+        if (Subtarget->hasAVX())
+          return MVT::v8f32;
+      }
+      if (Subtarget->hasSSE2())
         return MVT::v4i32;
-      if (Subtarget->hasXMM())
+      if (Subtarget->hasSSE1())
         return MVT::v4f32;
     } else if (!MemcpyStrSrc && Size >=3D 8 &&
                !Subtarget->is64Bit() &&
                Subtarget->getStackAlignment() >=3D 8 &&
-               Subtarget->hasXMMInt()) {
+               Subtarget->hasSSE2()) {
       // Do not use f64 to lower memcpy if source is string constant. It's
       // better to use i32 to avoid the loads.
       return MVT::f64;
@@ -1428,14 +1505,14 @@
     // or SSE or MMX vectors.
     if ((ValVT =3D=3D MVT::f32 || ValVT =3D=3D MVT::f64 ||
          VA.getLocReg() =3D=3D X86::XMM0 || VA.getLocReg() =3D=3D X86::XMM=
1) &&
-          (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
+          (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
       report_fatal_error("SSE register return with SSE disabled");
     }
     // Likewise we can't return F64 values with SSE1 only.  gcc does so, b=
ut
     // llvm-gcc has never done it right and no one has noticed, so this
     // should be OK for now.
     if (ValVT =3D=3D MVT::f64 &&
-        (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
+        (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
       report_fatal_error("SSE2 register return with SSE2 disabled");
=20
     // Returns in ST0/ST1 are handled specially: these are pushed as opera=
nds to
@@ -1461,7 +1538,7 @@
                                   ValToCopy);
           // If we don't have SSE2 available, convert to v4f32 so the gene=
rated
           // register is legal.
-          if (!Subtarget->hasXMMInt())
+          if (!Subtarget->hasSSE2())
             ValToCopy =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCo=
py);
         }
       }
@@ -1501,15 +1578,21 @@
                      MVT::Other, &RetOps[0], RetOps.size());
 }
=20
-bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
+bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) cons=
t {
   if (N->getNumValues() !=3D 1)
     return false;
   if (!N->hasNUsesOfValue(1, 0))
     return false;
=20
+  SDValue TCChain =3D Chain;
   SDNode *Copy =3D *N->use_begin();
-  if (Copy->getOpcode() !=3D ISD::CopyToReg &&
-      Copy->getOpcode() !=3D ISD::FP_EXTEND)
+  if (Copy->getOpcode() =3D=3D ISD::CopyToReg) {
+    // If the copy has a glue operand, we conservatively assume it isn't s=
afe to
+    // perform a tail call.
+    if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() =3D=3D M=
VT::Glue)
+      return false;
+    TCChain =3D Copy->getOperand(0);
+  } else if (Copy->getOpcode() !=3D ISD::FP_EXTEND)
     return false;
=20
   bool HasRet =3D false;
@@ -1520,7 +1603,11 @@
     HasRet =3D true;
   }
=20
-  return HasRet;
+  if (!HasRet)
+    return false;
+
+  Chain =3D TCChain;
+  return true;
 }
=20
 EVT
@@ -1561,7 +1648,7 @@
=20
     // If this is x86-64, and we disabled SSE, we can't return FP values
     if ((CopyVT =3D=3D MVT::f32 || CopyVT =3D=3D MVT::f64) &&
-        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
+        ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
       report_fatal_error("SSE register return with SSE disabled");
     }
=20
@@ -1651,7 +1738,7 @@
 }
=20
 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
-  if (!CI->isTailCall())
+  if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
     return false;
=20
   CallSite CS(CI);
@@ -1664,7 +1751,8 @@
=20
 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
 /// a tailcall target by changing its ABI.
-static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
+static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
+                                   bool GuaranteedTailCallOpt) {
   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
 }
=20
@@ -1678,7 +1766,8 @@
                                     unsigned i) const {
   // Create the nodes corresponding to a load from this parameter slot.
   ISD::ArgFlagsTy Flags =3D Ins[i].Flags;
-  bool AlwaysUseMutable =3D FuncIsMadeTailCallSafe(CallConv);
+  bool AlwaysUseMutable =3D FuncIsMadeTailCallSafe(CallConv,
+                              getTargetMachine().Options.GuaranteedTailCal=
lOpt);
   bool isImmutable =3D !AlwaysUseMutable && !Flags.isByVal();
   EVT ValVT;
=20
@@ -1704,7 +1793,7 @@
     SDValue FIN =3D DAG.getFrameIndex(FI, getPointerTy());
     return DAG.getLoad(ValVT, dl, Chain, FIN,
                        MachinePointerInfo::getFixedStack(FI),
-                       false, false, 0);
+                       false, false, false, 0);
   }
 }
=20
@@ -1728,6 +1817,7 @@
=20
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
   bool Is64Bit =3D Subtarget->is64Bit();
+  bool IsWindows =3D Subtarget->isTargetWindows();
   bool IsWin64 =3D Subtarget->isTargetWin64();
=20
   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
@@ -1758,7 +1848,7 @@
=20
     if (VA.isRegLoc()) {
       EVT RegVT =3D VA.getLocVT();
-      TargetRegisterClass *RC =3D NULL;
+      const TargetRegisterClass *RC;
       if (RegVT =3D=3D MVT::i32)
         RC =3D X86::GR32RegisterClass;
       else if (Is64Bit && RegVT =3D=3D MVT::i64)
@@ -1807,7 +1897,7 @@
     // If value is passed via pointer - do a load.
     if (VA.getLocInfo() =3D=3D CCValAssign::Indirect)
       ArgValue =3D DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
-                             MachinePointerInfo(), false, false, 0);
+                             MachinePointerInfo(), false, false, false, 0);
=20
     InVals.push_back(ArgValue);
   }
@@ -1828,7 +1918,8 @@
=20
   unsigned StackSize =3D CCInfo.getNextStackOffset();
   // Align stack specially for tail calls.
-  if (FuncIsMadeTailCallSafe(CallConv))
+  if (FuncIsMadeTailCallSafe(CallConv,
+                             MF.getTarget().Options.GuaranteedTailCallOpt))
     StackSize =3D GetAlignedArgumentStackSize(StackSize, DAG);
=20
   // If the function takes variable number of arguments, make a frame inde=
x for
@@ -1842,17 +1933,17 @@
       unsigned TotalNumIntRegs =3D 0, TotalNumXMMRegs =3D 0;
=20
       // FIXME: We should really autogenerate these arrays
-      static const unsigned GPR64ArgRegsWin64[] =3D {
+      static const uint16_t GPR64ArgRegsWin64[] =3D {
         X86::RCX, X86::RDX, X86::R8,  X86::R9
       };
-      static const unsigned GPR64ArgRegs64Bit[] =3D {
+      static const uint16_t GPR64ArgRegs64Bit[] =3D {
         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
       };
-      static const unsigned XMMArgRegs64Bit[] =3D {
+      static const uint16_t XMMArgRegs64Bit[] =3D {
         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
       };
-      const unsigned *GPR64ArgRegs;
+      const uint16_t *GPR64ArgRegs;
       unsigned NumXMMRegs =3D 0;
=20
       if (IsWin64) {
@@ -1865,17 +1956,20 @@
         TotalNumIntRegs =3D 6; TotalNumXMMRegs =3D 8;
         GPR64ArgRegs =3D GPR64ArgRegs64Bit;
=20
-        NumXMMRegs =3D CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNu=
mXMMRegs);
+        NumXMMRegs =3D CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
+                                                TotalNumXMMRegs);
       }
       unsigned NumIntRegs =3D CCInfo.getFirstUnallocated(GPR64ArgRegs,
                                                        TotalNumIntRegs);
=20
       bool NoImplicitFloatOps =3D Fn->hasFnAttr(Attribute::NoImplicitFloat=
);
-      assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
+      assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
              "SSE register cannot be used when SSE is disabled!");
-      assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
+      assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
+               NoImplicitFloatOps) &&
              "SSE register cannot be used when SSE is disabled!");
-      if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
+      if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
+          !Subtarget->hasSSE1())
         // Kernel mode asks for SSE to be disabled, so don't push them
         // on the stack.
         TotalNumXMMRegs =3D 0;
@@ -1892,8 +1986,8 @@
           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
       } else {
         // For X86-64, if there are vararg parameters that are passed via
-        // registers, then we must store them to their spots on the stack =
so they
-        // may be loaded by deferencing the result of va_next.
+        // registers, then we must store them to their spots on the stack =
so
+        // they may be loaded by deferencing the result of va_next.
         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16=
);
         FuncInfo->setRegSaveFrameIndex(
@@ -1953,12 +2047,14 @@
   }
=20
   // Some CCs need callee pop.
-  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)=
) {
+  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
+                       MF.getTarget().Options.GuaranteedTailCallOpt)) {
     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
   } else {
     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
     // If this is an sret function, the return should pop the hidden point=
er.
-    if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn=
(Ins))
+    if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
+        ArgsAreStructReturn(Ins))
       FuncInfo->setBytesToPopOnReturn(4);
   }
=20
@@ -2006,7 +2102,7 @@
=20
   // Load the "old" Return address.
   OutRetAddr =3D DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo=
(),
-                           false, false, 0);
+                           false, false, false, 0);
   return SDValue(OutRetAddr.getNode(), 1);
 }
=20
@@ -2033,7 +2129,7 @@
 SDValue
 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                              CallingConv::ID CallConv, bool isVarArg,
-                             bool &isTailCall,
+                             bool doesNotRet, bool &isTailCall,
                              const SmallVectorImpl<ISD::OutputArg> &Outs,
                              const SmallVectorImpl<SDValue> &OutVals,
                              const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -2042,9 +2138,13 @@
   MachineFunction &MF =3D DAG.getMachineFunction();
   bool Is64Bit        =3D Subtarget->is64Bit();
   bool IsWin64        =3D Subtarget->isTargetWin64();
+  bool IsWindows      =3D Subtarget->isTargetWindows();
   bool IsStructRet    =3D CallIsStructReturn(Outs);
   bool IsSibcall      =3D false;
=20
+  if (MF.getTarget().Options.DisableTailCalls)
+    isTailCall =3D false;
+
   if (isTailCall) {
     // Check if it's really possible to do a tail call.
     isTailCall =3D IsEligibleForTailCallOptimization(Callee, CallConv,
@@ -2053,7 +2153,7 @@
=20
     // Sibcalls are automatically detected tailcalls which do not require
     // ABI changes.
-    if (!GuaranteedTailCallOpt && isTailCall)
+    if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
       IsSibcall =3D true;
=20
     if (isTailCall)
@@ -2081,7 +2181,8 @@
     // This is a sibcall. The memory operands are available in caller's
     // own caller's stack.
     NumBytes =3D 0;
-  else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
+  else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
+           IsTailCallConvention(CallConv))
     NumBytes =3D GetAlignedArgumentStackSize(NumBytes, DAG);
=20
   int FPDiff =3D 0;
@@ -2231,12 +2332,12 @@
     // registers used and is in the range 0 - 8 inclusive.
=20
     // Count the number of XMM registers allocated.
-    static const unsigned XMMArgRegs[] =3D {
+    static const uint16_t XMMArgRegs[] =3D {
       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
     };
     unsigned NumXMMRegs =3D CCInfo.getFirstUnallocated(XMMArgRegs, 8);
-    assert((Subtarget->hasXMM() || !NumXMMRegs)
+    assert((Subtarget->hasSSE1() || !NumXMMRegs)
            && "SSE registers cannot be used when SSE is disabled");
=20
     Chain =3D DAG.getCopyToReg(Chain, dl, X86::AL,
@@ -2260,7 +2361,7 @@
     int FI =3D 0;
     // Do not flag preceding copytoreg stuff together with the following s=
tuff.
     InFlag =3D SDValue();
-    if (GuaranteedTailCallOpt) {
+    if (getTargetMachine().Options.GuaranteedTailCallOpt) {
       for (unsigned i =3D 0, e =3D ArgLocs.size(); i !=3D e; ++i) {
         CCValAssign &VA =3D ArgLocs[i];
         if (VA.isRegLoc())
@@ -2368,7 +2469,7 @@
       if (ExtraLoad)
         Callee =3D DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Cal=
lee,
                              MachinePointerInfo::getGOT(),
-                             false, false, 0);
+                             false, false, false, 0);
     }
   } else if (ExternalSymbolSDNode *S =3D dyn_cast<ExternalSymbolSDNode>(Ca=
llee)) {
     unsigned char OpFlags =3D 0;
@@ -2421,6 +2522,12 @@
   if (Is64Bit && isVarArg && !IsWin64)
     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
=20
+  // Add a register mask operand representing the call-preserved registers.
+  const TargetRegisterInfo *TRI =3D getTargetMachine().getRegisterInfo();
+  const uint32_t *Mask =3D TRI->getCallPreservedMask(CallConv);
+  assert(Mask && "Missing call preserved mask for calling convention");
+  Ops.push_back(DAG.getRegisterMask(Mask));
+
   if (InFlag.getNode())
     Ops.push_back(InFlag);
=20
@@ -2440,12 +2547,15 @@
=20
   // Create the CALLSEQ_END node.
   unsigned NumBytesForCalleeToPush;
-  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
+  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
+                       getTargetMachine().Options.GuaranteedTailCallOpt))
     NumBytesForCalleeToPush =3D NumBytes;    // Callee pops everything
-  else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
+  else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
+           IsStructRet)
     // If this is a call to a struct-return function, the callee
     // pops the hidden struct pointer, so we have to push it back.
     // This is common for Darwin/X86, Linux & Mingw32 targets.
+    // For MSVC Win32 targets, the caller pops the hidden struct pointer.
     NumBytesForCalleeToPush =3D 4;
   else
     NumBytesForCalleeToPush =3D 0;  // Callee pops nothing.
@@ -2598,7 +2708,7 @@
   CallingConv::ID CallerCC =3D CallerF->getCallingConv();
   bool CCMatch =3D CallerCC =3D=3D CalleeCC;
=20
-  if (GuaranteedTailCallOpt) {
+  if (getTargetMachine().Options.GuaranteedTailCallOpt) {
     if (IsTailCallConvention(CalleeCC) && CCMatch)
       return true;
     return false;
@@ -2641,9 +2751,9 @@
         return false;
   }
=20
-  // If the call result is in ST0 / ST1, it needs to be popped off the x87=
 stack.
-  // Therefore if it's not used by the call it is not safe to optimize thi=
s into
-  // a sibcall.
+  // If the call result is in ST0 / ST1, it needs to be popped off the x87
+  // stack.  Therefore, if it's not used by the call it is not safe to opt=
imize
+  // this into a sibcall.
   bool Unused =3D false;
   for (unsigned i =3D 0, e =3D Ins.size(); i !=3D e; ++i) {
     if (!Ins[i].Used) {
@@ -2785,9 +2895,8 @@
   case X86ISD::PSHUFD:
   case X86ISD::PSHUFHW:
   case X86ISD::PSHUFLW:
-  case X86ISD::SHUFPD:
+  case X86ISD::SHUFP:
   case X86ISD::PALIGN:
-  case X86ISD::SHUFPS:
   case X86ISD::MOVLHPS:
   case X86ISD::MOVLHPD:
   case X86ISD::MOVHLPS:
@@ -2798,34 +2907,16 @@
   case X86ISD::MOVDDUP:
   case X86ISD::MOVSS:
   case X86ISD::MOVSD:
-  case X86ISD::UNPCKLPS:
-  case X86ISD::UNPCKLPD:
-  case X86ISD::VUNPCKLPSY:
-  case X86ISD::VUNPCKLPDY:
-  case X86ISD::PUNPCKLWD:
-  case X86ISD::PUNPCKLBW:
-  case X86ISD::PUNPCKLDQ:
-  case X86ISD::PUNPCKLQDQ:
-  case X86ISD::UNPCKHPS:
-  case X86ISD::UNPCKHPD:
-  case X86ISD::VUNPCKHPSY:
-  case X86ISD::VUNPCKHPDY:
-  case X86ISD::PUNPCKHWD:
-  case X86ISD::PUNPCKHBW:
-  case X86ISD::PUNPCKHDQ:
-  case X86ISD::PUNPCKHQDQ:
-  case X86ISD::VPERMILPS:
-  case X86ISD::VPERMILPSY:
-  case X86ISD::VPERMILPD:
-  case X86ISD::VPERMILPDY:
-  case X86ISD::VPERM2F128:
+  case X86ISD::UNPCKL:
+  case X86ISD::UNPCKH:
+  case X86ISD::VPERMILP:
+  case X86ISD::VPERM2X128:
     return true;
   }
-  return false;
 }
=20
 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
-                                               SDValue V1, SelectionDAG &D=
AG) {
+                                    SDValue V1, SelectionDAG &DAG) {
   switch(Opc) {
   default: llvm_unreachable("Unknown x86 shuffle node");
   case X86ISD::MOVSHDUP:
@@ -2833,39 +2924,32 @@
   case X86ISD::MOVDDUP:
     return DAG.getNode(Opc, dl, VT, V1);
   }
-
-  return SDValue();
 }
=20
 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
-                          SDValue V1, unsigned TargetMask, SelectionDAG &D=
AG) {
+                                    SDValue V1, unsigned TargetMask,
+                                    SelectionDAG &DAG) {
   switch(Opc) {
   default: llvm_unreachable("Unknown x86 shuffle node");
   case X86ISD::PSHUFD:
   case X86ISD::PSHUFHW:
   case X86ISD::PSHUFLW:
-  case X86ISD::VPERMILPS:
-  case X86ISD::VPERMILPSY:
-  case X86ISD::VPERMILPD:
-  case X86ISD::VPERMILPDY:
+  case X86ISD::VPERMILP:
     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i=
8));
   }
-
-  return SDValue();
 }
=20
 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
-               SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &=
DAG) {
+                                    SDValue V1, SDValue V2, unsigned Targe=
tMask,
+                                    SelectionDAG &DAG) {
   switch(Opc) {
   default: llvm_unreachable("Unknown x86 shuffle node");
   case X86ISD::PALIGN:
-  case X86ISD::SHUFPD:
-  case X86ISD::SHUFPS:
-  case X86ISD::VPERM2F128:
+  case X86ISD::SHUFP:
+  case X86ISD::VPERM2X128:
     return DAG.getNode(Opc, dl, VT, V1, V2,
                        DAG.getConstant(TargetMask, MVT::i8));
   }
-  return SDValue();
 }
=20
 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
@@ -2879,25 +2963,10 @@
   case X86ISD::MOVLPD:
   case X86ISD::MOVSS:
   case X86ISD::MOVSD:
-  case X86ISD::UNPCKLPS:
-  case X86ISD::UNPCKLPD:
-  case X86ISD::VUNPCKLPSY:
-  case X86ISD::VUNPCKLPDY:
-  case X86ISD::PUNPCKLWD:
-  case X86ISD::PUNPCKLBW:
-  case X86ISD::PUNPCKLDQ:
-  case X86ISD::PUNPCKLQDQ:
-  case X86ISD::UNPCKHPS:
-  case X86ISD::UNPCKHPD:
-  case X86ISD::VUNPCKHPSY:
-  case X86ISD::VUNPCKHPDY:
-  case X86ISD::PUNPCKHWD:
-  case X86ISD::PUNPCKHBW:
-  case X86ISD::PUNPCKHDQ:
-  case X86ISD::PUNPCKHQDQ:
+  case X86ISD::UNPCKL:
+  case X86ISD::UNPCKH:
     return DAG.getNode(Opc, dl, VT, V1, V2);
   }
-  return SDValue();
 }
=20
 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) c=
onst {
@@ -3092,17 +3161,6 @@
   return (Val < 0) || (Val >=3D Low && Val < Hi);
 }
=20
-/// isUndefOrInRange - Return true if every element in Mask, begining
-/// from position Pos and ending in Pos+Size, falls within the specified
-/// range (L, L+Pos]. or is undef.
-static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
-                             int Pos, int Size, int Low, int Hi) {
-  for (int i =3D Pos, e =3D Pos+Size; i !=3D e; ++i)
-    if (!isUndefOrInRange(Mask[i], Low, Hi))
-      return false;
-  return true;
-}
-
 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
 /// specified value.
 static bool isUndefOrEqual(int Val, int CmpVal) {
@@ -3114,7 +3172,7 @@
 /// isSequentialOrUndefInRange - Return true if every element in Mask, beg=
ining
 /// from position Pos and ending in Pos+Size, falls within the specified
 /// sequential range (L, L+Pos]. or is undef.
-static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
+static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
                                        int Pos, int Size, int Low) {
   for (int i =3D Pos, e =3D Pos+Size; i !=3D e; ++i, ++Low)
     if (!isUndefOrEqual(Mask[i], Low))
@@ -3125,7 +3183,7 @@
 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements=
 that
 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't refere=
nce
 /// the second operand.
-static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
+static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
   if (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v4i32 )
     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
   if (VT =3D=3D MVT::v2f64 || VT =3D=3D MVT::v2i64)
@@ -3133,108 +3191,144 @@
   return false;
 }
=20
-bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isPSHUFDMask(M, N->getValueType(0));
-}
-
 /// isPSHUFHWMask - Return true if the node specifies a shuffle of element=
s that
 /// is suitable for input to PSHUFHW.
-static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
+static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT) {
   if (VT !=3D MVT::v8i16)
     return false;
=20
   // Lower quadword copied in order or undef.
-  for (int i =3D 0; i !=3D 4; ++i)
-    if (Mask[i] >=3D 0 && Mask[i] !=3D i)
-      return false;
+  if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
+    return false;
=20
   // Upper quadword shuffled.
-  for (int i =3D 4; i !=3D 8; ++i)
+  for (unsigned i =3D 4; i !=3D 8; ++i)
     if (Mask[i] >=3D 0 && (Mask[i] < 4 || Mask[i] > 7))
       return false;
=20
   return true;
 }
=20
-bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isPSHUFHWMask(M, N->getValueType(0));
-}
-
 /// isPSHUFLWMask - Return true if the node specifies a shuffle of element=
s that
 /// is suitable for input to PSHUFLW.
-static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
+static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT) {
   if (VT !=3D MVT::v8i16)
     return false;
=20
   // Upper quadword copied in order.
-  for (int i =3D 4; i !=3D 8; ++i)
-    if (Mask[i] >=3D 0 && Mask[i] !=3D i)
-      return false;
+  if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
+    return false;
=20
   // Lower quadword shuffled.
-  for (int i =3D 0; i !=3D 4; ++i)
+  for (unsigned i =3D 0; i !=3D 4; ++i)
     if (Mask[i] >=3D 4)
       return false;
=20
   return true;
 }
=20
-bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isPSHUFLWMask(M, N->getValueType(0));
-}
-
 /// isPALIGNRMask - Return true if the node specifies a shuffle of element=
s that
 /// is suitable for input to PALIGNR.
-static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
-                          bool hasSSSE3OrAVX) {
-  int i, e =3D VT.getVectorNumElements();
-  if (VT.getSizeInBits() !=3D 128 && VT.getSizeInBits() !=3D 64)
-    return false;
-
-  // Do not handle v2i64 / v2f64 shuffles with palignr.
-  if (e < 4 || !hasSSSE3OrAVX)
-    return false;
-
-  for (i =3D 0; i !=3D e; ++i)
-    if (Mask[i] >=3D 0)
-      break;
-
-  // All undef, not a palignr.
-  if (i =3D=3D e)
-    return false;
-
-  // Make sure we're shifting in the right direction.
-  if (Mask[i] <=3D i)
-    return false;
-
-  int s =3D Mask[i] - i;
-
-  // Check the rest of the elements to see if they are consecutive.
-  for (++i; i !=3D e; ++i) {
-    int m =3D Mask[i];
-    if (m >=3D 0 && m !=3D s+i)
+static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
+                          const X86Subtarget *Subtarget) {
+  if ((VT.getSizeInBits() =3D=3D 128 && !Subtarget->hasSSSE3()) ||
+      (VT.getSizeInBits() =3D=3D 256 && !Subtarget->hasAVX2()))
+    return false;
+
+  unsigned NumElts =3D VT.getVectorNumElements();
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned NumLaneElts =3D NumElts/NumLanes;
+
+  // Do not handle 64-bit element shuffles with palignr.
+  if (NumLaneElts =3D=3D 2)
+    return false;
+
+  for (unsigned l =3D 0; l !=3D NumElts; l+=3DNumLaneElts) {
+    unsigned i;
+    for (i =3D 0; i !=3D NumLaneElts; ++i) {
+      if (Mask[i+l] >=3D 0)
+        break;
+    }
+
+    // Lane is all undef, go to next lane
+    if (i =3D=3D NumLaneElts)
+      continue;
+
+    int Start =3D Mask[i+l];
+
+    // Make sure its in this lane in one of the sources
+    if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
+        !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
       return false;
-  }
+
+    // If not lane 0, then we must match lane 0
+    if (l !=3D 0 && Mask[i] >=3D 0 && !isUndefOrEqual(Start, Mask[i]+l))
+      return false;
+
+    // Correct second source to be contiguous with first source
+    if (Start >=3D (int)NumElts)
+      Start -=3D NumElts - NumLaneElts;
+
+    // Make sure we're shifting in the right direction.
+    if (Start <=3D (int)(i+l))
+      return false;
+
+    Start -=3D i;
+
+    // Check the rest of the elements to see if they are consecutive.
+    for (++i; i !=3D NumLaneElts; ++i) {
+      int Idx =3D Mask[i+l];
+
+      // Make sure its in this lane
+      if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
+          !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
+        return false;
+
+      // If not lane 0, then we must match lane 0
+      if (l !=3D 0 && Mask[i] >=3D 0 && !isUndefOrEqual(Idx, Mask[i]+l))
+        return false;
+
+      if (Idx >=3D (int)NumElts)
+        Idx -=3D NumElts - NumLaneElts;
+
+      if (!isUndefOrEqual(Idx, Start+i))
+        return false;
+
+    }
+  }
+
   return true;
 }
=20
-/// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
-/// specifies a shuffle of elements that is suitable for input to 256-bit
-/// VSHUFPSY.
-static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
-                          const X86Subtarget *Subtarget) {
-  int NumElems =3D VT.getVectorNumElements();
-
-  if (!Subtarget->hasAVX() || VT.getSizeInBits() !=3D 256)
-    return false;
-
-  if (NumElems !=3D 8)
+/// CommuteVectorShuffleMask - Change values in a shuffle permute mask ass=
uming
+/// the two vector operands have swapped position.
+static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
+                                     unsigned NumElems) {
+  for (unsigned i =3D 0; i !=3D NumElems; ++i) {
+    int idx =3D Mask[i];
+    if (idx < 0)
+      continue;
+    else if (idx < (int)NumElems)
+      Mask[i] =3D idx + NumElems;
+    else
+      Mask[i] =3D idx - NumElems;
+  }
+}
+
+/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
+/// specifies a shuffle of elements that is suitable for input to 128/256-=
bit
+/// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to =
be
+/// reverse of what x86 shuffles want.
+static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
+                        bool Commuted =3D false) {
+  if (!HasAVX && VT.getSizeInBits() =3D=3D 256)
+    return false;
+
+  unsigned NumElems =3D VT.getVectorNumElements();
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned NumLaneElems =3D NumElems/NumLanes;
+
+  if (NumLaneElems !=3D 2 && NumLaneElems !=3D 4)
     return false;
=20
   // VSHUFPSY divides the resulting vector into 4 chunks.
@@ -3247,188 +3341,38 @@
   //  DST  =3D>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
   //
-  int QuarterSize =3D NumElems/4;
-  int HalfSize =3D QuarterSize*2;
-  for (int i =3D 0; i < QuarterSize; ++i)
-    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
-      return false;
-  for (int i =3D QuarterSize; i < QuarterSize*2; ++i)
-    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
-      return false;
-
-  // The mask of the second half must be the same as the first but with
-  // the appropriate offsets. This works in the same way as VPERMILPS
-  // works with masks.
-  for (int i =3D QuarterSize*2; i < QuarterSize*3; ++i) {
-    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
-      return false;
-    int FstHalfIdx =3D i-HalfSize;
-    if (Mask[FstHalfIdx] < 0)
-      continue;
-    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
-      return false;
-  }
-  for (int i =3D QuarterSize*3; i < NumElems; ++i) {
-    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
-      return false;
-    int FstHalfIdx =3D i-HalfSize;
-    if (Mask[FstHalfIdx] < 0)
-      continue;
-    if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
-      return false;
-
-  }
-
-  return true;
-}
-
-/// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuf=
fle
-/// the specified VECTOR_MASK mask with VSHUFPSY instruction.
-static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
-  EVT VT =3D SVOp->getValueType(0);
-  int NumElems =3D VT.getVectorNumElements();
-
-  assert(NumElems =3D=3D 8 && VT.getSizeInBits() =3D=3D 256 &&
-         "Only supports v8i32 and v8f32 types");
-
-  int HalfSize =3D NumElems/2;
-  unsigned Mask =3D 0;
-  for (int i =3D 0; i !=3D NumElems ; ++i) {
-    if (SVOp->getMaskElt(i) < 0)
-      continue;
-    // The mask of the first half must be equal to the second one.
-    unsigned Shamt =3D (i%HalfSize)*2;
-    unsigned Elt =3D SVOp->getMaskElt(i) % HalfSize;
-    Mask |=3D Elt << Shamt;
-  }
-
-  return Mask;
-}
-
-/// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
-/// specifies a shuffle of elements that is suitable for input to 256-bit
-/// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
-/// version and the mask of the second half isn't binded with the first
-/// one.
-static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
-                           const X86Subtarget *Subtarget) {
-  int NumElems =3D VT.getVectorNumElements();
-
-  if (!Subtarget->hasAVX() || VT.getSizeInBits() !=3D 256)
-    return false;
-
-  if (NumElems !=3D 4)
-    return false;
-
-  // VSHUFPSY divides the resulting vector into 4 chunks.
+  // VSHUFPDY divides the resulting vector into 4 chunks.
   // The sources are also splitted into 4 chunks, and each destination
   // chunk must come from a different source chunk.
   //
   //  SRC1 =3D>      X3       X2       X1       X0
   //  SRC2 =3D>      Y3       Y2       Y1       Y0
   //
-  //  DST  =3D>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
+  //  DST  =3D>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
   //
-  int QuarterSize =3D NumElems/4;
-  int HalfSize =3D QuarterSize*2;
-  for (int i =3D 0; i < QuarterSize; ++i)
-    if (!isUndefOrInRange(Mask[i], 0, HalfSize))
-      return false;
-  for (int i =3D QuarterSize; i < QuarterSize*2; ++i)
-    if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
-      return false;
-  for (int i =3D QuarterSize*2; i < QuarterSize*3; ++i)
-    if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
-      return false;
-  for (int i =3D QuarterSize*3; i < NumElems; ++i)
-    if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
-      return false;
+  unsigned HalfLaneElems =3D NumLaneElems/2;
+  for (unsigned l =3D 0; l !=3D NumElems; l +=3D NumLaneElems) {
+    for (unsigned i =3D 0; i !=3D NumLaneElems; ++i) {
+      int Idx =3D Mask[i+l];
+      unsigned RngStart =3D l + ((Commuted =3D=3D (i<HalfLaneElems)) ? Num=
Elems : 0);
+      if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
+        return false;
+      // For VSHUFPSY, the mask of the second half must be the same as the
+      // first but with the appropriate offsets. This works in the same wa=
y as
+      // VPERMILPS works with masks.
+      if (NumElems !=3D 8 || l =3D=3D 0 || Mask[i] < 0)
+        continue;
+      if (!isUndefOrEqual(Idx, Mask[i]+l))
+        return false;
+    }
+  }
=20
   return true;
 }
=20
-/// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuf=
fle
-/// the specified VECTOR_MASK mask with VSHUFPDY instruction.
-static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
-  EVT VT =3D SVOp->getValueType(0);
-  int NumElems =3D VT.getVectorNumElements();
-
-  assert(NumElems =3D=3D 4 && VT.getSizeInBits() =3D=3D 256 &&
-         "Only supports v4i64 and v4f64 types");
-
-  int HalfSize =3D NumElems/2;
-  unsigned Mask =3D 0;
-  for (int i =3D 0; i !=3D NumElems ; ++i) {
-    if (SVOp->getMaskElt(i) < 0)
-      continue;
-    int Elt =3D SVOp->getMaskElt(i) % HalfSize;
-    Mask |=3D Elt << i;
-  }
-
-  return Mask;
-}
-
-/// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
-/// specifies a shuffle of elements that is suitable for input to 128-bit
-/// SHUFPS and SHUFPD.
-static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
-  int NumElems =3D VT.getVectorNumElements();
-
-  if (VT.getSizeInBits() !=3D 128)
-    return false;
-
-  if (NumElems !=3D 2 && NumElems !=3D 4)
-    return false;
-
-  int Half =3D NumElems / 2;
-  for (int i =3D 0; i < Half; ++i)
-    if (!isUndefOrInRange(Mask[i], 0, NumElems))
-      return false;
-  for (int i =3D Half; i < NumElems; ++i)
-    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
-      return false;
-
-  return true;
-}
-
-bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isSHUFPMask(M, N->getValueType(0));
-}
-
-/// isCommutedSHUFP - Returns true if the shuffle mask is exactly
-/// the reverse of what x86 shuffles want. x86 shuffles requires the lower
-/// half elements to come from vector 1 (which would equal the dest.) and
-/// the upper half to come from vector 2.
-static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
-  int NumElems =3D VT.getVectorNumElements();
-
-  if (NumElems !=3D 2 && NumElems !=3D 4)
-    return false;
-
-  int Half =3D NumElems / 2;
-  for (int i =3D 0; i < Half; ++i)
-    if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
-      return false;
-  for (int i =3D Half; i < NumElems; ++i)
-    if (!isUndefOrInRange(Mask[i], 0, NumElems))
-      return false;
-  return true;
-}
-
-static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return isCommutedSHUFPMask(M, N->getValueType(0));
-}
-
 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
-bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
-  EVT VT =3D N->getValueType(0);
+static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
   unsigned NumElems =3D VT.getVectorNumElements();
=20
   if (VT.getSizeInBits() !=3D 128)
@@ -3438,17 +3382,16 @@
     return false;
=20
   // Expect bit0 =3D=3D 6, bit1 =3D=3D 7, bit2 =3D=3D 2, bit3 =3D=3D 3
-  return isUndefOrEqual(N->getMaskElt(0), 6) &&
-         isUndefOrEqual(N->getMaskElt(1), 7) &&
-         isUndefOrEqual(N->getMaskElt(2), 2) &&
-         isUndefOrEqual(N->getMaskElt(3), 3);
+  return isUndefOrEqual(Mask[0], 6) &&
+         isUndefOrEqual(Mask[1], 7) &&
+         isUndefOrEqual(Mask[2], 2) &&
+         isUndefOrEqual(Mask[3], 3);
 }
=20
 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical f=
orm
 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
 /// <2, 3, 2, 3>
-bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
-  EVT VT =3D N->getValueType(0);
+static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
   unsigned NumElems =3D VT.getVectorNumElements();
=20
   if (VT.getSizeInBits() !=3D 128)
@@ -3457,26 +3400,29 @@
   if (NumElems !=3D 4)
     return false;
=20
-  return isUndefOrEqual(N->getMaskElt(0), 2) &&
-         isUndefOrEqual(N->getMaskElt(1), 3) &&
-         isUndefOrEqual(N->getMaskElt(2), 2) &&
-         isUndefOrEqual(N->getMaskElt(3), 3);
+  return isUndefOrEqual(Mask[0], 2) &&
+         isUndefOrEqual(Mask[1], 3) &&
+         isUndefOrEqual(Mask[2], 2) &&
+         isUndefOrEqual(Mask[3], 3);
 }
=20
 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|=
D}.
-bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
-  unsigned NumElems =3D N->getValueType(0).getVectorNumElements();
+static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
+  if (VT.getSizeInBits() !=3D 128)
+    return false;
+
+  unsigned NumElems =3D VT.getVectorNumElements();
=20
   if (NumElems !=3D 2 && NumElems !=3D 4)
     return false;
=20
-  for (unsigned i =3D 0; i < NumElems/2; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
+  for (unsigned i =3D 0; i !=3D NumElems/2; ++i)
+    if (!isUndefOrEqual(Mask[i], i + NumElems))
       return false;
=20
-  for (unsigned i =3D NumElems/2; i < NumElems; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(i), i))
+  for (unsigned i =3D NumElems/2; i !=3D NumElems; ++i)
+    if (!isUndefOrEqual(Mask[i], i))
       return false;
=20
   return true;
@@ -3484,19 +3430,19 @@
=20
 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
-bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
-  unsigned NumElems =3D N->getValueType(0).getVectorNumElements();
+static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
+  unsigned NumElems =3D VT.getVectorNumElements();
=20
   if ((NumElems !=3D 2 && NumElems !=3D 4)
-      || N->getValueType(0).getSizeInBits() > 128)
-    return false;
-
-  for (unsigned i =3D 0; i < NumElems/2; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(i), i))
+      || VT.getSizeInBits() > 128)
+    return false;
+
+  for (unsigned i =3D 0; i !=3D NumElems/2; ++i)
+    if (!isUndefOrEqual(Mask[i], i))
       return false;
=20
-  for (unsigned i =3D 0; i < NumElems/2; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
+  for (unsigned i =3D 0; i !=3D NumElems/2; ++i)
+    if (!isUndefOrEqual(Mask[i + NumElems/2], i + NumElems))
       return false;
=20
   return true;
@@ -3504,14 +3450,15 @@
=20
 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
-static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
-                         bool V2IsSplat =3D false) {
-  int NumElts =3D VT.getVectorNumElements();
+static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
+                         bool HasAVX2, bool V2IsSplat =3D false) {
+  unsigned NumElts =3D VT.getVectorNumElements();
=20
   assert((VT.is128BitVector() || VT.is256BitVector()) &&
          "Unsupported vector type for unpckh");
=20
-  if (VT.getSizeInBits() =3D=3D 256 && NumElts !=3D 4 && NumElts !=3D 8)
+  if (VT.getSizeInBits() =3D=3D 256 && NumElts !=3D 4 && NumElts !=3D 8 &&
+      (!HasAVX2 || (NumElts !=3D 16 && NumElts !=3D 32)))
     return false;
=20
   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
@@ -3519,11 +3466,9 @@
   unsigned NumLanes =3D VT.getSizeInBits()/128;
   unsigned NumLaneElts =3D NumElts/NumLanes;
=20
-  unsigned Start =3D 0;
-  unsigned End =3D NumLaneElts;
-  for (unsigned s =3D 0; s < NumLanes; ++s) {
-    for (unsigned i =3D Start, j =3D s * NumLaneElts;
-         i !=3D End;
+  for (unsigned l =3D 0; l !=3D NumLanes; ++l) {
+    for (unsigned i =3D l*NumLaneElts, j =3D l*NumLaneElts;
+         i !=3D (l+1)*NumLaneElts;
          i +=3D 2, ++j) {
       int BitI  =3D Mask[i];
       int BitI1 =3D Mask[i+1];
@@ -3537,30 +3482,22 @@
           return false;
       }
     }
-    // Process the next 128 bits.
-    Start +=3D NumLaneElts;
-    End +=3D NumLaneElts;
   }
=20
   return true;
 }
=20
-bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
-}
-
 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
-static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
-                         bool V2IsSplat =3D false) {
-  int NumElts =3D VT.getVectorNumElements();
+static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
+                         bool HasAVX2, bool V2IsSplat =3D false) {
+  unsigned NumElts =3D VT.getVectorNumElements();
=20
   assert((VT.is128BitVector() || VT.is256BitVector()) &&
          "Unsupported vector type for unpckh");
=20
-  if (VT.getSizeInBits() =3D=3D 256 && NumElts !=3D 4 && NumElts !=3D 8)
+  if (VT.getSizeInBits() =3D=3D 256 && NumElts !=3D 4 && NumElts !=3D 8 &&
+      (!HasAVX2 || (NumElts !=3D 16 && NumElts !=3D 32)))
     return false;
=20
   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
@@ -3568,11 +3505,9 @@
   unsigned NumLanes =3D VT.getSizeInBits()/128;
   unsigned NumLaneElts =3D NumElts/NumLanes;
=20
-  unsigned Start =3D 0;
-  unsigned End =3D NumLaneElts;
   for (unsigned l =3D 0; l !=3D NumLanes; ++l) {
-    for (unsigned i =3D Start, j =3D (l*NumLaneElts)+NumLaneElts/2;
-                             i !=3D End; i +=3D 2, ++j) {
+    for (unsigned i =3D l*NumLaneElts, j =3D (l*NumLaneElts)+NumLaneElts/2;
+         i !=3D (l+1)*NumLaneElts; i +=3D 2, ++j) {
       int BitI  =3D Mask[i];
       int BitI1 =3D Mask[i+1];
       if (!isUndefOrEqual(BitI, j))
@@ -3585,42 +3520,39 @@
           return false;
       }
     }
-    // Process the next 128 bits.
-    Start +=3D NumLaneElts;
-    End +=3D NumLaneElts;
   }
   return true;
 }
=20
-bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
-}
-
 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
 /// <0, 0, 1, 1>
-static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT=
) {
-  int NumElems =3D VT.getVectorNumElements();
-  if (NumElems !=3D 2 && NumElems !=3D 4 && NumElems !=3D 8 && NumElems !=
=3D 16)
+static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
+                                  bool HasAVX2) {
+  unsigned NumElts =3D VT.getVectorNumElements();
+
+  assert((VT.is128BitVector() || VT.is256BitVector()) &&
+         "Unsupported vector type for unpckh");
+
+  if (VT.getSizeInBits() =3D=3D 256 && NumElts !=3D 4 && NumElts !=3D 8 &&
+      (!HasAVX2 || (NumElts !=3D 16 && NumElts !=3D 32)))
     return false;
=20
   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pat=
tern
   // FIXME: Need a better way to get rid of this, there's no latency diffe=
rence
   // between UNPCKLPD and MOVDDUP, the later should always be checked firs=
t and
   // the former later. We should also remove the "_undef" special mask.
-  if (NumElems =3D=3D 4 && VT.getSizeInBits() =3D=3D 256)
+  if (NumElts =3D=3D 4 && VT.getSizeInBits() =3D=3D 256)
     return false;
=20
   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
   // independently on 128-bit lanes.
-  unsigned NumLanes =3D VT.getSizeInBits() / 128;
-  unsigned NumLaneElts =3D NumElems / NumLanes;
-
-  for (unsigned s =3D 0; s < NumLanes; ++s) {
-    for (unsigned i =3D s * NumLaneElts, j =3D s * NumLaneElts;
-         i !=3D NumLaneElts * (s + 1);
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned NumLaneElts =3D NumElts/NumLanes;
+
+  for (unsigned l =3D 0; l !=3D NumLanes; ++l) {
+    for (unsigned i =3D l*NumLaneElts, j =3D l*NumLaneElts;
+         i !=3D (l+1)*NumLaneElts;
          i +=3D 2, ++j) {
       int BitI  =3D Mask[i];
       int BitI1 =3D Mask[i+1];
@@ -3635,81 +3567,77 @@
   return true;
 }
=20
-bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
-}
-
 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
 /// <2, 2, 3, 3>
-static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT=
) {
-  int NumElems =3D VT.getVectorNumElements();
-  if (NumElems !=3D 2 && NumElems !=3D 4 && NumElems !=3D 8 && NumElems !=
=3D 16)
-    return false;
-
-  for (int i =3D 0, j =3D NumElems / 2; i !=3D NumElems; i +=3D 2, ++j) {
-    int BitI  =3D Mask[i];
-    int BitI1 =3D Mask[i+1];
-    if (!isUndefOrEqual(BitI, j))
-      return false;
-    if (!isUndefOrEqual(BitI1, j))
-      return false;
+static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2=
) {
+  unsigned NumElts =3D VT.getVectorNumElements();
+
+  assert((VT.is128BitVector() || VT.is256BitVector()) &&
+         "Unsupported vector type for unpckh");
+
+  if (VT.getSizeInBits() =3D=3D 256 && NumElts !=3D 4 && NumElts !=3D 8 &&
+      (!HasAVX2 || (NumElts !=3D 16 && NumElts !=3D 32)))
+    return false;
+
+  // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
+  // independently on 128-bit lanes.
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned NumLaneElts =3D NumElts/NumLanes;
+
+  for (unsigned l =3D 0; l !=3D NumLanes; ++l) {
+    for (unsigned i =3D l*NumLaneElts, j =3D (l*NumLaneElts)+NumLaneElts/2;
+         i !=3D (l+1)*NumLaneElts; i +=3D 2, ++j) {
+      int BitI  =3D Mask[i];
+      int BitI1 =3D Mask[i+1];
+      if (!isUndefOrEqual(BitI, j))
+        return false;
+      if (!isUndefOrEqual(BitI1, j))
+        return false;
+    }
   }
   return true;
 }
=20
-bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
-}
-
 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to MOVSS,
 /// MOVSD, and MOVD, i.e. setting the lowest element.
-static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
+static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
   if (VT.getVectorElementType().getSizeInBits() < 32)
     return false;
-
-  int NumElts =3D VT.getVectorNumElements();
+  if (VT.getSizeInBits() =3D=3D 256)
+    return false;
+
+  unsigned NumElts =3D VT.getVectorNumElements();
=20
   if (!isUndefOrEqual(Mask[0], NumElts))
     return false;
=20
-  for (int i =3D 1; i < NumElts; ++i)
+  for (unsigned i =3D 1; i !=3D NumElts; ++i)
     if (!isUndefOrEqual(Mask[i], i))
       return false;
=20
   return true;
 }
=20
-bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return ::isMOVLMask(M, N->getValueType(0));
-}
-
-/// isVPERM2F128Mask - Match 256-bit shuffles where the elements are consi=
dered
+/// isVPERM2X128Mask - Match 256-bit shuffles where the elements are consi=
dered
 /// as permutations between 128-bit chunks or halves. As an example: this
 /// shuffle bellow:
 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
 /// The first half comes from the second half of V1 and the second half fr=
om the
 /// the second half of V2.
-static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
-                             const X86Subtarget *Subtarget) {
-  if (!Subtarget->hasAVX() || VT.getSizeInBits() !=3D 256)
+static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
+  if (!HasAVX || VT.getSizeInBits() !=3D 256)
     return false;
=20
   // The shuffle result is divided into half A and half B. In total the two
   // sources have 4 halves, namely: C, D, E, F. The final values of A and
   // B must come from C, D, E or F.
-  int HalfSize =3D VT.getVectorNumElements()/2;
+  unsigned HalfSize =3D VT.getVectorNumElements()/2;
   bool MatchA =3D false, MatchB =3D false;
=20
   // Check if A comes from one of C, D, E, F.
-  for (int Half =3D 0; Half < 4; ++Half) {
+  for (unsigned Half =3D 0; Half !=3D 4; ++Half) {
     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
       MatchA =3D true;
       break;
@@ -3717,7 +3645,7 @@
   }
=20
   // Check if B comes from one of C, D, E, F.
-  for (int Half =3D 0; Half < 4; ++Half) {
+  for (unsigned Half =3D 0; Half !=3D 4; ++Half) {
     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize=
)) {
       MatchB =3D true;
       break;
@@ -3727,22 +3655,21 @@
   return MatchA && MatchB;
 }
=20
-/// getShuffleVPERM2F128Immediate - Return the appropriate immediate to sh=
uffle
-/// the specified VECTOR_MASK mask with VPERM2F128 instructions.
-static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
+/// getShuffleVPERM2X128Immediate - Return the appropriate immediate to sh=
uffle
+/// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
+static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
   EVT VT =3D SVOp->getValueType(0);
=20
-  int HalfSize =3D VT.getVectorNumElements()/2;
-
-  int FstHalf =3D 0, SndHalf =3D 0;
-  for (int i =3D 0; i < HalfSize; ++i) {
+  unsigned HalfSize =3D VT.getVectorNumElements()/2;
+
+  unsigned FstHalf =3D 0, SndHalf =3D 0;
+  for (unsigned i =3D 0; i < HalfSize; ++i) {
     if (SVOp->getMaskElt(i) > 0) {
       FstHalf =3D SVOp->getMaskElt(i)/HalfSize;
       break;
     }
   }
-  for (int i =3D HalfSize; i < HalfSize*2; ++i) {
+  for (unsigned i =3D HalfSize; i < HalfSize*2; ++i) {
     if (SVOp->getMaskElt(i) > 0) {
       SndHalf =3D SVOp->getMaskElt(i)/HalfSize;
       break;
@@ -3752,141 +3679,56 @@
   return (FstHalf | (SndHalf << 4));
 }
=20
-/// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
+/// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to VPERMILP=
D*.
 /// Note that VPERMIL mask matching is different depending whether theunde=
rlying
 /// type is 32 or 64. In the VPERMILPS the high half of the mask should po=
int
 /// to the same elements of the low, but to the higher half of the source.
 /// In VPERMILPD the two lanes could be shuffled independently of each oth=
er
-/// with the same restriction that lanes can't be crossed.
-static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
-                            const X86Subtarget *Subtarget) {
-  int NumElts =3D VT.getVectorNumElements();
-  int NumLanes =3D VT.getSizeInBits()/128;
-
-  if (!Subtarget->hasAVX())
-    return false;
-
-  // Only match 256-bit with 64-bit types
-  if (VT.getSizeInBits() !=3D 256 || NumElts !=3D 4)
-    return false;
-
-  // The mask on the high lane is independent of the low. Both can match
-  // any element in inside its own lane, but can't cross.
-  int LaneSize =3D NumElts/NumLanes;
-  for (int l =3D 0; l < NumLanes; ++l)
-    for (int i =3D l*LaneSize; i < LaneSize*(l+1); ++i) {
-      int LaneStart =3D l*LaneSize;
-      if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
+/// with the same restriction that lanes can't be crossed. Also handles PS=
HUFDY.
+static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
+  if (!HasAVX)
+    return false;
+
+  unsigned NumElts =3D VT.getVectorNumElements();
+  // Only match 256-bit with 32/64-bit types
+  if (VT.getSizeInBits() !=3D 256 || (NumElts !=3D 4 && NumElts !=3D 8))
+    return false;
+
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned LaneSize =3D NumElts/NumLanes;
+  for (unsigned l =3D 0; l !=3D NumElts; l +=3D LaneSize) {
+    for (unsigned i =3D 0; i !=3D LaneSize; ++i) {
+      if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
         return false;
-    }
+      if (NumElts !=3D 8 || l =3D=3D 0)
+        continue;
+      // VPERMILPS handling
+      if (Mask[i] < 0)
+        continue;
+      if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
+        return false;
+    }
+  }
=20
   return true;
 }
=20
-/// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
-/// specifies a shuffle of elements that is suitable for input to VPERMILP=
S*.
-/// Note that VPERMIL mask matching is different depending whether theunde=
rlying
-/// type is 32 or 64. In the VPERMILPS the high half of the mask should po=
int
-/// to the same elements of the low, but to the higher half of the source.
-/// In VPERMILPD the two lanes could be shuffled independently of each oth=
er
-/// with the same restriction that lanes can't be crossed.
-static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
-                            const X86Subtarget *Subtarget) {
-  unsigned NumElts =3D VT.getVectorNumElements();
-  unsigned NumLanes =3D VT.getSizeInBits()/128;
-
-  if (!Subtarget->hasAVX())
-    return false;
-
-  // Only match 256-bit with 32-bit types
-  if (VT.getSizeInBits() !=3D 256 || NumElts !=3D 8)
-    return false;
-
-  // The mask on the high lane should be the same as the low. Actually,
-  // they can differ if any of the corresponding index in a lane is undef
-  // and the other stays in range.
-  int LaneSize =3D NumElts/NumLanes;
-  for (int i =3D 0; i < LaneSize; ++i) {
-    int HighElt =3D i+LaneSize;
-    bool HighValid =3D isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
-    bool LowValid =3D isUndefOrInRange(Mask[i], 0, LaneSize);
-
-    if (!HighValid || !LowValid)
-      return false;
-    if (Mask[i] < 0 || Mask[HighElt] < 0)
-      continue;
-    if (Mask[HighElt]-Mask[i] !=3D LaneSize)
-      return false;
-  }
-
-  return true;
-}
-
-/// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shu=
ffle
-/// the specified VECTOR_MASK mask with VPERMILPS* instructions.
-static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
-  EVT VT =3D SVOp->getValueType(0);
-
-  int NumElts =3D VT.getVectorNumElements();
-  int NumLanes =3D VT.getSizeInBits()/128;
-  int LaneSize =3D NumElts/NumLanes;
-
-  // Although the mask is equal for both lanes do it twice to get the cases
-  // where a mask will match because the same mask element is undef on the
-  // first half but valid on the second. This would get pathological cases
-  // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
-  unsigned Mask =3D 0;
-  for (int l =3D 0; l < NumLanes; ++l) {
-    for (int i =3D 0; i < LaneSize; ++i) {
-      int MaskElt =3D SVOp->getMaskElt(i+(l*LaneSize));
-      if (MaskElt < 0)
-        continue;
-      if (MaskElt >=3D LaneSize)
-        MaskElt -=3D LaneSize;
-      Mask |=3D MaskElt << (i*2);
-    }
-  }
-
-  return Mask;
-}
-
-/// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shu=
ffle
-/// the specified VECTOR_MASK mask with VPERMILPD* instructions.
-static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
-  EVT VT =3D SVOp->getValueType(0);
-
-  int NumElts =3D VT.getVectorNumElements();
-  int NumLanes =3D VT.getSizeInBits()/128;
-
-  unsigned Mask =3D 0;
-  int LaneSize =3D NumElts/NumLanes;
-  for (int l =3D 0; l < NumLanes; ++l)
-    for (int i =3D l*LaneSize; i < LaneSize*(l+1); ++i) {
-      int MaskElt =3D SVOp->getMaskElt(i);
-      if (MaskElt < 0)
-        continue;
-      Mask |=3D (MaskElt-l*LaneSize) << i;
-    }
-
-  return Mask;
-}
-
-/// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
+/// isCommutedMOVLMask - Returns true if the shuffle mask is except the re=
verse
 /// of what x86 movss want. X86 movs requires the lowest  element to be lo=
west
 /// element of vector 2 and the other elements to come from vector 1 in or=
der.
-static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
+static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
                                bool V2IsSplat =3D false, bool V2IsUndef =
=3D false) {
-  int NumOps =3D VT.getVectorNumElements();
+  unsigned NumOps =3D VT.getVectorNumElements();
+  if (VT.getSizeInBits() =3D=3D 256)
+    return false;
   if (NumOps !=3D 2 && NumOps !=3D 4 && NumOps !=3D 8 && NumOps !=3D 16)
     return false;
=20
   if (!isUndefOrEqual(Mask[0], 0))
     return false;
=20
-  for (int i =3D 1; i < NumOps; ++i)
+  for (unsigned i =3D 1; i !=3D NumOps; ++i)
     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
@@ -3895,26 +3737,14 @@
   return true;
 }
=20
-static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat =3D fals=
e,
-                           bool V2IsUndef =3D false) {
-  SmallVector<int, 8> M;
-  N->getMask(M);
-  return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
-}
-
 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
-bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
-                         const X86Subtarget *Subtarget) {
-  if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
-    return false;
-
-  // The second vector must be undef
-  if (N->getOperand(1).getOpcode() !=3D ISD::UNDEF)
-    return false;
-
-  EVT VT =3D N->getValueType(0);
+static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
+                           const X86Subtarget *Subtarget) {
+  if (!Subtarget->hasSSE3())
+    return false;
+
   unsigned NumElems =3D VT.getVectorNumElements();
=20
   if ((VT.getSizeInBits() =3D=3D 128 && NumElems !=3D 4) ||
@@ -3922,9 +3752,9 @@
     return false;
=20
   // "i+1" is the value the indexed mask element must have
-  for (unsigned i =3D 0; i < NumElems; i +=3D 2)
-    if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
-        !isUndefOrEqual(N->getMaskElt(i+1), i+1))
+  for (unsigned i =3D 0; i !=3D NumElems; i +=3D 2)
+    if (!isUndefOrEqual(Mask[i], i+1) ||
+        !isUndefOrEqual(Mask[i+1], i+1))
       return false;
=20
   return true;
@@ -3933,16 +3763,11 @@
 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
-bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
-                         const X86Subtarget *Subtarget) {
-  if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
-    return false;
-
-  // The second vector must be undef
-  if (N->getOperand(1).getOpcode() !=3D ISD::UNDEF)
-    return false;
-
-  EVT VT =3D N->getValueType(0);
+static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
+                           const X86Subtarget *Subtarget) {
+  if (!Subtarget->hasSSE3())
+    return false;
+
   unsigned NumElems =3D VT.getVectorNumElements();
=20
   if ((VT.getSizeInBits() =3D=3D 128 && NumElems !=3D 4) ||
@@ -3950,9 +3775,9 @@
     return false;
=20
   // "i" is the value the indexed mask element must have
-  for (unsigned i =3D 0; i < NumElems; i +=3D 2)
-    if (!isUndefOrEqual(N->getMaskElt(i), i) ||
-        !isUndefOrEqual(N->getMaskElt(i+1), i))
+  for (unsigned i =3D 0; i !=3D NumElems; i +=3D 2)
+    if (!isUndefOrEqual(Mask[i], i) ||
+        !isUndefOrEqual(Mask[i+1], i))
       return false;
=20
   return true;
@@ -3961,21 +3786,17 @@
 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to 256-bit
 /// version of MOVDDUP.
-static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
-                           const X86Subtarget *Subtarget) {
-  EVT VT =3D N->getValueType(0);
-  int NumElts =3D VT.getVectorNumElements();
-  bool V2IsUndef =3D N->getOperand(1).getOpcode() =3D=3D ISD::UNDEF;
-
-  if (!Subtarget->hasAVX() || VT.getSizeInBits() !=3D 256 ||
-      !V2IsUndef || NumElts !=3D 4)
-    return false;
-
-  for (int i =3D 0; i !=3D NumElts/2; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(i), 0))
+static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
+  unsigned NumElts =3D VT.getVectorNumElements();
+
+  if (!HasAVX || VT.getSizeInBits() !=3D 256 || NumElts !=3D 4)
+    return false;
+
+  for (unsigned i =3D 0; i !=3D NumElts/2; ++i)
+    if (!isUndefOrEqual(Mask[i], 0))
       return false;
-  for (int i =3D NumElts/2; i !=3D NumElts; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
+  for (unsigned i =3D NumElts/2; i !=3D NumElts; ++i)
+    if (!isUndefOrEqual(Mask[i], NumElts/2))
       return false;
   return true;
 }
@@ -3983,18 +3804,16 @@
 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
 /// specifies a shuffle of elements that is suitable for input to 128-bit
 /// version of MOVDDUP.
-bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
-  EVT VT =3D N->getValueType(0);
-
+static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
   if (VT.getSizeInBits() !=3D 128)
     return false;
=20
-  int e =3D VT.getVectorNumElements() / 2;
-  for (int i =3D 0; i < e; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(i), i))
+  unsigned e =3D VT.getVectorNumElements() / 2;
+  for (unsigned i =3D 0; i !=3D e; ++i)
+    if (!isUndefOrEqual(Mask[i], i))
       return false;
-  for (int i =3D 0; i < e; ++i)
-    if (!isUndefOrEqual(N->getMaskElt(e+i), i))
+  for (unsigned i =3D 0; i !=3D e; ++i)
+    if (!isUndefOrEqual(Mask[e+i], i))
       return false;
   return true;
 }
@@ -4039,31 +3858,43 @@
=20
 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
-unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
-  int NumOperands =3D SVOp->getValueType(0).getVectorNumElements();
-
-  unsigned Shift =3D (NumOperands =3D=3D 4) ? 2 : 1;
+/// Handles 128-bit and 256-bit.
+static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
+  EVT VT =3D N->getValueType(0);
+
+  assert((VT.is128BitVector() || VT.is256BitVector()) &&
+         "Unsupported vector type for PSHUF/SHUFP");
+
+  // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to ope=
rate
+  // independently on 128-bit lanes.
+  unsigned NumElts =3D VT.getVectorNumElements();
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned NumLaneElts =3D NumElts/NumLanes;
+
+  assert((NumLaneElts =3D=3D 2 || NumLaneElts =3D=3D 4) &&
+         "Only supports 2 or 4 elements per lane");
+
+  unsigned Shift =3D (NumLaneElts =3D=3D 4) ? 1 : 0;
   unsigned Mask =3D 0;
-  for (int i =3D 0; i < NumOperands; ++i) {
-    int Val =3D SVOp->getMaskElt(NumOperands-i-1);
-    if (Val < 0) Val =3D 0;
-    if (Val >=3D NumOperands) Val -=3D NumOperands;
-    Mask |=3D Val;
-    if (i !=3D NumOperands - 1)
-      Mask <<=3D Shift;
-  }
+  for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+    int Elt =3D N->getMaskElt(i);
+    if (Elt < 0) continue;
+    Elt %=3D NumLaneElts;
+    unsigned ShAmt =3D i << Shift;
+    if (ShAmt >=3D 8) ShAmt -=3D 8;
+    Mask |=3D Elt << ShAmt;
+  }
+
   return Mask;
 }
=20
 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuff=
le
 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
-unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
+static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
   unsigned Mask =3D 0;
   // 8 nodes, but we only care about the last 4.
   for (unsigned i =3D 7; i >=3D 4; --i) {
-    int Val =3D SVOp->getMaskElt(i);
+    int Val =3D N->getMaskElt(i);
     if (Val >=3D 0)
       Mask |=3D (Val - 4);
     if (i !=3D 4)
@@ -4074,12 +3905,11 @@
=20
 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuff=
le
 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
-unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
+static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
   unsigned Mask =3D 0;
   // 8 nodes, but we only care about the first 4.
   for (int i =3D 3; i >=3D 0; --i) {
-    int Val =3D SVOp->getMaskElt(i);
+    int Val =3D N->getMaskElt(i);
     if (Val >=3D 0)
       Mask |=3D Val;
     if (i !=3D 0)
@@ -4090,18 +3920,24 @@
=20
 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuff=
le
 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
-unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
-  EVT VVT =3D N->getValueType(0);
-  unsigned EltSize =3D VVT.getVectorElementType().getSizeInBits() >> 3;
+static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
+  EVT VT =3D SVOp->getValueType(0);
+  unsigned EltSize =3D VT.getVectorElementType().getSizeInBits() >> 3;
+
+  unsigned NumElts =3D VT.getVectorNumElements();
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned NumLaneElts =3D NumElts/NumLanes;
+
   int Val =3D 0;
-
-  unsigned i, e;
-  for (i =3D 0, e =3D VVT.getVectorNumElements(); i !=3D e; ++i) {
+  unsigned i;
+  for (i =3D 0; i !=3D NumElts; ++i) {
     Val =3D SVOp->getMaskElt(i);
     if (Val >=3D 0)
       break;
   }
+  if (Val >=3D (int)NumElts)
+    Val -=3D NumElts - NumLaneElts;
+
   assert(Val - i > 0 && "PALIGNR imm should be positive");
   return (Val - i) * EltSize;
 }
@@ -4170,36 +4006,20 @@
                               SVOp->getOperand(0), &MaskVec[0]);
 }
=20
-/// CommuteVectorShuffleMask - Change values in a shuffle permute mask ass=
uming
-/// the two vector operands have swapped position.
-static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
-  unsigned NumElems =3D VT.getVectorNumElements();
-  for (unsigned i =3D 0; i !=3D NumElems; ++i) {
-    int idx =3D Mask[i];
-    if (idx < 0)
-      continue;
-    else if (idx < (int)NumElems)
-      Mask[i] =3D idx + NumElems;
-    else
-      Mask[i] =3D idx - NumElems;
-  }
-}
-
 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
 /// match movhlps. The lower half elements should come from upper half of
 /// V1 (and in order), and the upper half elements should come from the up=
per
 /// half of V2 (and in order).
-static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
-  EVT VT =3D Op->getValueType(0);
+static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
   if (VT.getSizeInBits() !=3D 128)
     return false;
   if (VT.getVectorNumElements() !=3D 4)
     return false;
   for (unsigned i =3D 0, e =3D 2; i !=3D e; ++i)
-    if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
+    if (!isUndefOrEqual(Mask[i], i+2))
       return false;
   for (unsigned i =3D 2; i !=3D 4; ++i)
-    if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
+    if (!isUndefOrEqual(Mask[i], i+4))
       return false;
   return true;
 }
@@ -4218,14 +4038,36 @@
   return true;
 }
=20
+// Test whether the given value is a vector value which will be legalized
+// into a load.
+static bool WillBeConstantPoolLoad(SDNode *N) {
+  if (N->getOpcode() !=3D ISD::BUILD_VECTOR)
+    return false;
+
+  // Check for any non-constant elements.
+  for (unsigned i =3D 0, e =3D N->getNumOperands(); i !=3D e; ++i)
+    switch (N->getOperand(i).getNode()->getOpcode()) {
+    case ISD::UNDEF:
+    case ISD::ConstantFP:
+    case ISD::Constant:
+      break;
+    default:
+      return false;
+    }
+
+  // Vectors of all-zeros and all-ones are materialized with special
+  // instructions rather than being loaded.
+  return !ISD::isBuildVectorAllZeros(N) &&
+         !ISD::isBuildVectorAllOnes(N);
+}
+
 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transforme=
d to
 /// match movlp{s|d}. The lower half elements should come from lower half =
of
 /// V1 (and in order), and the upper half elements should come from the up=
per
 /// half of V2 (and in order). And since V1 will become the source of the
 /// MOVLP, it must be either a vector load or a scalar load to vector.
 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
-                               ShuffleVectorSDNode *Op) {
-  EVT VT =3D Op->getValueType(0);
+                               ArrayRef<int> Mask, EVT VT) {
   if (VT.getSizeInBits() !=3D 128)
     return false;
=20
@@ -4233,7 +4075,7 @@
     return false;
   // Is V2 is a vector load, don't do this transformation. We will try to =
use
   // load folding shufps op.
-  if (ISD::isNON_EXTLoad(V2))
+  if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
     return false;
=20
   unsigned NumElems =3D VT.getVectorNumElements();
@@ -4241,10 +4083,10 @@
   if (NumElems !=3D 2 && NumElems !=3D 4)
     return false;
   for (unsigned i =3D 0, e =3D NumElems/2; i !=3D e; ++i)
-    if (!isUndefOrEqual(Op->getMaskElt(i), i))
+    if (!isUndefOrEqual(Mask[i], i))
       return false;
   for (unsigned i =3D NumElems/2; i !=3D NumElems; ++i)
-    if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
+    if (!isUndefOrEqual(Mask[i], i+NumElems))
       return false;
   return true;
 }
@@ -4292,15 +4134,15 @@
=20
 /// getZeroVector - Returns a vector of specified type with all zero eleme=
nts.
 ///
-static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
-                             DebugLoc dl) {
+static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
+                             SelectionDAG &DAG, DebugLoc dl) {
   assert(VT.isVector() && "Expected a vector type");
=20
   // Always build SSE zero vectors as <4 x i32> bitcasted
   // to their dest type. This ensures they get CSE'd.
   SDValue Vec;
   if (VT.getSizeInBits() =3D=3D 128) {  // SSE
-    if (HasXMMInt) {  // SSE2
+    if (Subtarget->hasSSE2()) {  // SSE2
       SDValue Cst =3D DAG.getTargetConstant(0, MVT::i32);
       Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst=
, Cst);
     } else { // SSE1
@@ -4308,34 +4150,46 @@
       Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst=
, Cst);
     }
   } else if (VT.getSizeInBits() =3D=3D 256) { // AVX
-    // 256-bit logic and arithmetic instructions in AVX are
-    // all floating-point, no support for integer ops. Default
-    // to emitting fp zeroed vectors then.
-    SDValue Cst =3D DAG.getTargetConstantFP(+0.0, MVT::f32);
-    SDValue Ops[] =3D { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
-    Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
+    if (Subtarget->hasAVX2()) { // AVX2
+      SDValue Cst =3D DAG.getTargetConstant(0, MVT::i32);
+      SDValue Ops[] =3D { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
+      Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
+    } else {
+      // 256-bit logic and arithmetic instructions in AVX are all
+      // floating-point, no support for integer ops. Emit fp zeroed vector=
s.
+      SDValue Cst =3D DAG.getTargetConstantFP(+0.0, MVT::f32);
+      SDValue Ops[] =3D { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
+      Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
+    }
   }
   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
 }
=20
 /// getOnesVector - Returns a vector of specified type with all bits set.
-/// Always build ones vectors as <4 x i32>. For 256-bit types, use two
-/// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
-/// original type, ensuring they get CSE'd.
-static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
+/// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types=
 with
+/// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriatel=
y.
+/// Then bitcast to their original type, ensuring they get CSE'd.
+static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
+                             DebugLoc dl) {
   assert(VT.isVector() && "Expected a vector type");
   assert((VT.is128BitVector() || VT.is256BitVector())
          && "Expected a 128-bit or 256-bit vector type");
=20
   SDValue Cst =3D DAG.getTargetConstant(~0U, MVT::i32);
-  SDValue Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
-                            Cst, Cst, Cst, Cst);
-
-  if (VT.is256BitVector()) {
-    SDValue InsV =3D Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v=
8i32),
-                              Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
-    Vec =3D Insert128BitVector(InsV, Vec,
-                  DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
+  SDValue Vec;
+  if (VT.getSizeInBits() =3D=3D 256) {
+    if (HasAVX2) { // AVX2
+      SDValue Ops[] =3D { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
+      Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
+    } else { // AVX
+      Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst=
, Cst);
+      SDValue InsV =3D Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT:=
:v8i32),
+                                Vec, DAG.getConstant(0, MVT::i32), DAG, dl=
);
+      Vec =3D Insert128BitVector(InsV, Vec,
+                    DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl=
);
+    }
+  } else {
+    Vec =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, =
Cst);
   }
=20
   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
@@ -4343,24 +4197,12 @@
=20
 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elem=
ents
 /// that point to V2 points to its first element.
-static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG)=
 {
-  EVT VT =3D SVOp->getValueType(0);
-  unsigned NumElems =3D VT.getVectorNumElements();
-
-  bool Changed =3D false;
-  SmallVector<int, 8> MaskVec;
-  SVOp->getMask(MaskVec);
-
+static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
   for (unsigned i =3D 0; i !=3D NumElems; ++i) {
-    if (MaskVec[i] > (int)NumElems) {
-      MaskVec[i] =3D NumElems;
-      Changed =3D true;
-    }
-  }
-  if (Changed)
-    return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(=
0),
-                                SVOp->getOperand(1), &MaskVec[0]);
-  return SDValue(SVOp, 0);
+    if (Mask[i] > (int)NumElems) {
+      Mask[i] =3D NumElems;
+    }
+  }
 }
=20
 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
@@ -4464,7 +4306,7 @@
   // Extract the 128-bit part containing the splat element and update
   // the splat element index when it refers to the higher register.
   if (Size =3D=3D 256) {
-    unsigned Idx =3D (EltNo > NumElems/2) ? NumElems/2 : 0;
+    unsigned Idx =3D (EltNo >=3D NumElems/2) ? NumElems/2 : 0;
     V1 =3D Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl=
);
     if (Idx > 0)
       EltNo -=3D NumElems/2;
@@ -4496,11 +4338,12 @@
 /// element of V2 is swizzled into the zero/undef vector, landing at eleme=
nt
 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=3D0) or  0,1,2,4 =
(idx=3D3).
 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
-                                           bool isZero, bool HasXMMInt,
+                                           bool IsZero,
+                                           const X86Subtarget *Subtarget,
                                            SelectionDAG &DAG) {
   EVT VT =3D V2.getValueType();
-  SDValue V1 =3D isZero
-    ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(V=
T);
+  SDValue V1 =3D IsZero
+    ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(V=
T);
   unsigned NumElems =3D VT.getVectorNumElements();
   SmallVector<int, 16> MaskVec;
   for (unsigned i =3D 0; i !=3D NumElems; ++i)
@@ -4509,9 +4352,81 @@
   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
 }
=20
+/// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
+/// target specific opcode. Returns true if the Mask could be calculated.
+/// Sets IsUnary to true if only uses one source.
+static bool getTargetShuffleMask(SDNode *N, EVT VT,
+                                 SmallVectorImpl<int> &Mask, bool &IsUnary=
) {
+  unsigned NumElems =3D VT.getVectorNumElements();
+  SDValue ImmN;
+
+  IsUnary =3D false;
+  switch(N->getOpcode()) {
+  case X86ISD::SHUFP:
+    ImmN =3D N->getOperand(N->getNumOperands()-1);
+    DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
+    break;
+  case X86ISD::UNPCKH:
+    DecodeUNPCKHMask(VT, Mask);
+    break;
+  case X86ISD::UNPCKL:
+    DecodeUNPCKLMask(VT, Mask);
+    break;
+  case X86ISD::MOVHLPS:
+    DecodeMOVHLPSMask(NumElems, Mask);
+    break;
+  case X86ISD::MOVLHPS:
+    DecodeMOVLHPSMask(NumElems, Mask);
+    break;
+  case X86ISD::PSHUFD:
+  case X86ISD::VPERMILP:
+    ImmN =3D N->getOperand(N->getNumOperands()-1);
+    DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
+    IsUnary =3D true;
+    break;
+  case X86ISD::PSHUFHW:
+    ImmN =3D N->getOperand(N->getNumOperands()-1);
+    DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
+    IsUnary =3D true;
+    break;
+  case X86ISD::PSHUFLW:
+    ImmN =3D N->getOperand(N->getNumOperands()-1);
+    DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
+    IsUnary =3D true;
+    break;
+  case X86ISD::MOVSS:
+  case X86ISD::MOVSD: {
+    // The index 0 always comes from the first element of the second sourc=
e,
+    // this is why MOVSS and MOVSD are used in the first place. The other
+    // elements come from the other positions of the first source vector
+    Mask.push_back(NumElems);
+    for (unsigned i =3D 1; i !=3D NumElems; ++i) {
+      Mask.push_back(i);
+    }
+    break;
+  }
+  case X86ISD::VPERM2X128:
+    ImmN =3D N->getOperand(N->getNumOperands()-1);
+    DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), M=
ask);
+    break;
+  case X86ISD::MOVDDUP:
+  case X86ISD::MOVLHPD:
+  case X86ISD::MOVLPD:
+  case X86ISD::MOVLPS:
+  case X86ISD::MOVSHDUP:
+  case X86ISD::MOVSLDUP:
+  case X86ISD::PALIGN:
+    // Not yet implemented
+    return false;
+  default: llvm_unreachable("unknown target shuffle node");
+  }
+
+  return true;
+}
+
 /// getShuffleScalarElt - Returns the scalar element that will make up the=
 ith
 /// element of the result of the vector shuffle.
-static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
+static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG=
 &DAG,
                                    unsigned Depth) {
   if (Depth =3D=3D 6)
     return SDValue();  // Limit search depth.
@@ -4522,129 +4437,34 @@
=20
   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
   if (const ShuffleVectorSDNode *SV =3D dyn_cast<ShuffleVectorSDNode>(N)) {
-    Index =3D SV->getMaskElt(Index);
-
-    if (Index < 0)
+    int Elt =3D SV->getMaskElt(Index);
+
+    if (Elt < 0)
       return DAG.getUNDEF(VT.getVectorElementType());
=20
-    int NumElems =3D VT.getVectorNumElements();
-    SDValue NewV =3D (Index < NumElems) ? SV->getOperand(0) : SV->getOpera=
nd(1);
-    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Dept=
h+1);
+    unsigned NumElems =3D VT.getVectorNumElements();
+    SDValue NewV =3D (Elt < (int)NumElems) ? SV->getOperand(0)
+                                         : SV->getOperand(1);
+    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+=
1);
   }
=20
   // Recurse into target specific vector shuffles to find scalars.
   if (isTargetShuffle(Opcode)) {
-    int NumElems =3D VT.getVectorNumElements();
-    SmallVector<unsigned, 16> ShuffleMask;
+    unsigned NumElems =3D VT.getVectorNumElements();
+    SmallVector<int, 16> ShuffleMask;
     SDValue ImmN;
-
-    switch(Opcode) {
-    case X86ISD::SHUFPS:
-    case X86ISD::SHUFPD:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodeSHUFPSMask(NumElems,
-                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                       ShuffleMask);
-      break;
-    case X86ISD::PUNPCKHBW:
-    case X86ISD::PUNPCKHWD:
-    case X86ISD::PUNPCKHDQ:
-    case X86ISD::PUNPCKHQDQ:
-      DecodePUNPCKHMask(NumElems, ShuffleMask);
-      break;
-    case X86ISD::UNPCKHPS:
-    case X86ISD::UNPCKHPD:
-    case X86ISD::VUNPCKHPSY:
-    case X86ISD::VUNPCKHPDY:
-      DecodeUNPCKHPMask(NumElems, ShuffleMask);
-      break;
-    case X86ISD::PUNPCKLBW:
-    case X86ISD::PUNPCKLWD:
-    case X86ISD::PUNPCKLDQ:
-    case X86ISD::PUNPCKLQDQ:
-      DecodePUNPCKLMask(VT, ShuffleMask);
-      break;
-    case X86ISD::UNPCKLPS:
-    case X86ISD::UNPCKLPD:
-    case X86ISD::VUNPCKLPSY:
-    case X86ISD::VUNPCKLPDY:
-      DecodeUNPCKLPMask(VT, ShuffleMask);
-      break;
-    case X86ISD::MOVHLPS:
-      DecodeMOVHLPSMask(NumElems, ShuffleMask);
-      break;
-    case X86ISD::MOVLHPS:
-      DecodeMOVLHPSMask(NumElems, ShuffleMask);
-      break;
-    case X86ISD::PSHUFD:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodePSHUFMask(NumElems,
-                      cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                      ShuffleMask);
-      break;
-    case X86ISD::PSHUFHW:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                        ShuffleMask);
-      break;
-    case X86ISD::PSHUFLW:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                        ShuffleMask);
-      break;
-    case X86ISD::MOVSS:
-    case X86ISD::MOVSD: {
-      // The index 0 always comes from the first element of the second sou=
rce,
-      // this is why MOVSS and MOVSD are used in the first place. The other
-      // elements come from the other positions of the first source vector.
-      unsigned OpNum =3D (Index =3D=3D 0) ? 1 : 0;
-      return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
-                                 Depth+1);
-    }
-    case X86ISD::VPERMILPS:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                        ShuffleMask);
-      break;
-    case X86ISD::VPERMILPSY:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                        ShuffleMask);
-      break;
-    case X86ISD::VPERMILPD:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                        ShuffleMask);
-      break;
-    case X86ISD::VPERMILPDY:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                        ShuffleMask);
-      break;
-    case X86ISD::VPERM2F128:
-      ImmN =3D N->getOperand(N->getNumOperands()-1);
-      DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
-                           ShuffleMask);
-      break;
-    case X86ISD::MOVDDUP:
-    case X86ISD::MOVLHPD:
-    case X86ISD::MOVLPD:
-    case X86ISD::MOVLPS:
-    case X86ISD::MOVSHDUP:
-    case X86ISD::MOVSLDUP:
-    case X86ISD::PALIGN:
-      return SDValue(); // Not yet implemented.
-    default:
-      assert(0 && "unknown target shuffle node");
+    bool IsUnary;
+
+    if (!getTargetShuffleMask(N, VT, ShuffleMask, IsUnary))
       return SDValue();
-    }
-
-    Index =3D ShuffleMask[Index];
-    if (Index < 0)
+
+    int Elt =3D ShuffleMask[Index];
+    if (Elt < 0)
       return DAG.getUNDEF(VT.getVectorElementType());
=20
-    SDValue NewV =3D (Index < NumElems) ? N->getOperand(0) : N->getOperand=
(1);
-    return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
+    SDValue NewV =3D (Elt < (int)NumElems) ? N->getOperand(0)
+                                           : N->getOperand(1);
+    return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
                                Depth+1);
   }
=20
@@ -4660,7 +4480,7 @@
=20
   if (V.getOpcode() =3D=3D ISD::SCALAR_TO_VECTOR)
     return (Index =3D=3D 0) ? V.getOperand(0)
-                          : DAG.getUNDEF(VT.getVectorElementType());
+                        : DAG.getUNDEF(VT.getVectorElementType());
=20
   if (V.getOpcode() =3D=3D ISD::BUILD_VECTOR)
     return V.getOperand(Index);
@@ -4672,38 +4492,37 @@
 /// shuffle operation which come from a consecutively from a zero. The
 /// search can start in two different directions, from left or right.
 static
-unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
+unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumE=
lems,
                                   bool ZerosFromLeft, SelectionDAG &DAG) {
-  int i =3D 0;
-
-  while (i < NumElems) {
+  unsigned i;
+  for (i =3D 0; i !=3D NumElems; ++i) {
     unsigned Index =3D ZerosFromLeft ? i : NumElems-i-1;
-    SDValue Elt =3D getShuffleScalarElt(N, Index, DAG, 0);
+    SDValue Elt =3D getShuffleScalarElt(SVOp, Index, DAG, 0);
     if (!(Elt.getNode() &&
          (Elt.getOpcode() =3D=3D ISD::UNDEF || X86::isZeroNode(Elt))))
       break;
-    ++i;
   }
=20
   return i;
 }
=20
-/// isShuffleMaskConsecutive - Check if the shuffle mask indicies from Mas=
kI to
-/// MaskE correspond consecutively to elements from one of the vector oper=
ands,
+/// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, =
MaskE)
+/// correspond consecutively to elements from one of the vector operands,
 /// starting from its index OpIdx. Also tell OpNum which source vector ope=
rand.
 static
-bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int Ma=
skE,
-                              int OpIdx, int NumElems, unsigned &OpNum) {
+bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
+                              unsigned MaskI, unsigned MaskE, unsigned OpI=
dx,
+                              unsigned NumElems, unsigned &OpNum) {
   bool SeenV1 =3D false;
   bool SeenV2 =3D false;
=20
-  for (int i =3D MaskI; i <=3D MaskE; ++i, ++OpIdx) {
+  for (unsigned i =3D MaskI; i !=3D MaskE; ++i, ++OpIdx) {
     int Idx =3D SVOp->getMaskElt(i);
     // Ignore undef indicies
     if (Idx < 0)
       continue;
=20
-    if (Idx < NumElems)
+    if (Idx < (int)NumElems)
       SeenV1 =3D true;
     else
       SeenV2 =3D true;
@@ -4738,7 +4557,7 @@
   //
   if (!isShuffleMaskConsecutive(SVOp,
             0,                   // Mask Start Index
-            NumElems-NumZeros-1, // Mask End Index
+            NumElems-NumZeros,   // Mask End Index(exclusive)
             NumZeros,            // Where to start looking in the src vect=
or
             NumElems,            // Number of elements in vector
             OpSrc))              // Which source operand ?
@@ -4771,7 +4590,7 @@
   //
   if (!isShuffleMaskConsecutive(SVOp,
             NumZeros,     // Mask Start Index
-            NumElems-1,   // Mask End Index
+            NumElems,     // Mask End Index(exclusive)
             0,            // Where to start looking in the src vector
             NumElems,     // Number of elements in vector
             OpSrc))       // Which source operand ?
@@ -4804,6 +4623,7 @@
 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
                                        unsigned NumNonZero, unsigned NumZe=
ro,
                                        SelectionDAG &DAG,
+                                       const X86Subtarget* Subtarget,
                                        const TargetLowering &TLI) {
   if (NumNonZero > 8)
     return SDValue();
@@ -4815,7 +4635,7 @@
     bool ThisIsNonZero =3D (NonZeros & (1 << i)) !=3D 0;
     if (ThisIsNonZero && First) {
       if (NumZero)
-        V =3D getZeroVector(MVT::v8i16, true, DAG, dl);
+        V =3D getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
       else
         V =3D DAG.getUNDEF(MVT::v8i16);
       First =3D false;
@@ -4851,6 +4671,7 @@
 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
                                      unsigned NumNonZero, unsigned NumZero,
                                      SelectionDAG &DAG,
+                                     const X86Subtarget* Subtarget,
                                      const TargetLowering &TLI) {
   if (NumNonZero > 4)
     return SDValue();
@@ -4863,7 +4684,7 @@
     if (isNonZero) {
       if (First) {
         if (NumZero)
-          V =3D getZeroVector(MVT::v8i16, true, DAG, dl);
+          V =3D getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
         else
           V =3D DAG.getUNDEF(MVT::v8i16);
         First =3D false;
@@ -4884,7 +4705,7 @@
                          const TargetLowering &TLI, DebugLoc dl) {
   assert(VT.getSizeInBits() =3D=3D 128 && "Unknown type for VShift");
   EVT ShVT =3D MVT::v2i64;
-  unsigned Opc =3D isLeft ? X86ISD::VSHL : X86ISD::VSRL;
+  unsigned Opc =3D isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
   SrcOp =3D DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
   return DAG.getNode(ISD::BITCAST, dl, VT,
                      DAG.getNode(Opc, dl, ShVT, SrcOp,
@@ -4952,21 +4773,16 @@
     int EltNo =3D (Offset - StartOffset) >> 2;
     int NumElems =3D VT.getVectorNumElements();
=20
-    EVT CanonVT =3D VT.getSizeInBits() =3D=3D 128 ? MVT::v4i32 : MVT::v8i3=
2;
     EVT NVT =3D EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
     SDValue V1 =3D DAG.getLoad(NVT, dl, Chain, Ptr,
                              LD->getPointerInfo().getWithOffset(StartOffse=
t),
-                             false, false, 0);
-
-    // Canonicalize it to a v4i32 or v8i32 shuffle.
+                             false, false, false, 0);
+
     SmallVector<int, 8> Mask;
     for (int i =3D 0; i < NumElems; ++i)
       Mask.push_back(EltNo);
=20
-    V1 =3D DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
-    return DAG.getNode(ISD::BITCAST, dl, NVT,
-                       DAG.getVectorShuffle(CanonVT, dl, V1,
-                                            DAG.getUNDEF(CanonVT),&Mask[0]=
));
+    return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
   }
=20
   return SDValue();
@@ -5021,11 +4837,12 @@
     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >=3D 16)
       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
                          LDBase->getPointerInfo(),
-                         LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
+                         LDBase->isVolatile(), LDBase->isNonTemporal(),
+                         LDBase->isInvariant(), 0);
     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
                        LDBase->getPointerInfo(),
                        LDBase->isVolatile(), LDBase->isNonTemporal(),
-                       LDBase->getAlignment());
+                       LDBase->isInvariant(), LDBase->getAlignment());
   } else if (NumElems =3D=3D 4 && LastLoadedElt =3D=3D 1 &&
              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
     SDVTList Tys =3D DAG.getVTList(MVT::v2i64, MVT::Other);
@@ -5041,6 +4858,137 @@
   return SDValue();
 }
=20
+/// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
+/// to generate a splat value for the following cases:
+/// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
+/// 2. A splat shuffle which uses a scalar_to_vector node which comes from
+/// a scalar load, or a constant.
+/// The VBROADCAST node is returned when a pattern is found,
+/// or SDValue() otherwise.
+SDValue
+X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) co=
nst {
+  if (!Subtarget->hasAVX())
+    return SDValue();
+
+  EVT VT =3D Op.getValueType();
+  DebugLoc dl =3D Op.getDebugLoc();
+
+  SDValue Ld;
+  bool ConstSplatVal;
+
+  switch (Op.getOpcode()) {
+    default:
+      // Unknown pattern found.
+      return SDValue();
+
+    case ISD::BUILD_VECTOR: {
+      // The BUILD_VECTOR node must be a splat.
+      if (!isSplatVector(Op.getNode()))
+        return SDValue();
+
+      Ld =3D Op.getOperand(0);
+      ConstSplatVal =3D (Ld.getOpcode() =3D=3D ISD::Constant ||
+                     Ld.getOpcode() =3D=3D ISD::ConstantFP);
+
+      // The suspected load node has several users. Make sure that all
+      // of its users are from the BUILD_VECTOR node.
+      // Constants may have multiple users.
+      if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements()=
, 0))
+        return SDValue();
+      break;
+    }
+
+    case ISD::VECTOR_SHUFFLE: {
+      ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(Op);
+
+      // Shuffles must have a splat mask where the first element is
+      // broadcasted.
+      if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) !=3D 0)
+        return SDValue();
+
+      SDValue Sc =3D Op.getOperand(0);
+      if (Sc.getOpcode() !=3D ISD::SCALAR_TO_VECTOR)
+        return SDValue();
+
+      Ld =3D Sc.getOperand(0);
+      ConstSplatVal =3D (Ld.getOpcode() =3D=3D ISD::Constant ||
+                       Ld.getOpcode() =3D=3D ISD::ConstantFP);
+
+      // The scalar_to_vector node and the suspected
+      // load node must have exactly one user.
+      // Constants may have multiple users.
+      if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
+        return SDValue();
+      break;
+    }
+  }
+
+  bool Is256 =3D VT.getSizeInBits() =3D=3D 256;
+  bool Is128 =3D VT.getSizeInBits() =3D=3D 128;
+
+  // Handle the broadcasting a single constant scalar from the constant po=
ol
+  // into a vector. On Sandybridge it is still better to load a constant v=
ector
+  // from the constant pool and not to broadcast it from a scalar.
+  if (ConstSplatVal && Subtarget->hasAVX2()) {
+    EVT CVT =3D Ld.getValueType();
+    assert(!CVT.isVector() && "Must not broadcast a vector type");
+    unsigned ScalarSize =3D CVT.getSizeInBits();
+
+    if ((Is256 && (ScalarSize =3D=3D 32 || ScalarSize =3D=3D 64)) ||
+        (Is128 && (ScalarSize =3D=3D 32))) {
+
+      const Constant *C =3D 0;
+      if (ConstantSDNode *CI =3D dyn_cast<ConstantSDNode>(Ld))
+        C =3D CI->getConstantIntValue();
+      else if (ConstantFPSDNode *CF =3D dyn_cast<ConstantFPSDNode>(Ld))
+        C =3D CF->getConstantFPValue();
+
+      assert(C && "Invalid constant type");
+
+      SDValue CP =3D DAG.getConstantPool(C, getPointerTy());
+      unsigned Alignment =3D cast<ConstantPoolSDNode>(CP)->getAlignment();
+      Ld =3D DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
+                         MachinePointerInfo::getConstantPool(),
+                         false, false, false, Alignment);
+
+      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
+    }
+  }
+
+  // The scalar source must be a normal load.
+  if (!ISD::isNormalLoad(Ld.getNode()))
+    return SDValue();
+
+  // Reject loads that have uses of the chain result
+  if (Ld->hasAnyUseOfValue(1))
+    return SDValue();
+
+  unsigned ScalarSize =3D Ld.getValueType().getSizeInBits();
+
+  // VBroadcast to YMM
+  if (Is256 && (ScalarSize =3D=3D 32 || ScalarSize =3D=3D 64))
+    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
+
+  // VBroadcast to XMM
+  if (Is128 && (ScalarSize =3D=3D 32))
+    return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
+
+  // The integer check is needed for the 64-bit into 128-bit so it doesn't=
 match
+  // double since there is vbroadcastsd xmm
+  if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
+    // VBroadcast to YMM
+    if (Is256 && (ScalarSize =3D=3D 8 || ScalarSize =3D=3D 16))
+      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
+
+    // VBroadcast to XMM
+    if (Is128 && (ScalarSize =3D=3D  8 || ScalarSize =3D=3D 16 || ScalarSi=
ze =3D=3D 64))
+      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
+  }
+
+  // Unsupported broadcast.
+  return SDValue();
+}
+
 SDValue
 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
   DebugLoc dl =3D Op.getDebugLoc();
@@ -5053,21 +5001,25 @@
   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CS=
E'd
     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
-    if (Op.getValueType() =3D=3D MVT::v4i32 ||
-        Op.getValueType() =3D=3D MVT::v8i32)
+    if (VT =3D=3D MVT::v4i32 || VT =3D=3D MVT::v8i32)
       return Op;
=20
-    return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, d=
l);
+    return getZeroVector(VT, Subtarget, DAG, dl);
   }
=20
   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
-  // vectors or broken into v4i32 operations on 256-bit vectors.
+  // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can =
use
+  // vpcmpeqd on 256-bit vectors.
   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
-    if (Op.getValueType() =3D=3D MVT::v4i32)
+    if (VT =3D=3D MVT::v4i32 || (VT =3D=3D MVT::v8i32 && Subtarget->hasAVX=
2()))
       return Op;
=20
-    return getOnesVector(Op.getValueType(), DAG, dl);
-  }
+    return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
+  }
+
+  SDValue Broadcast =3D LowerVectorBroadcast(Op, DAG);
+  if (Broadcast.getNode())
+    return Broadcast;
=20
   unsigned EVTBits =3D ExtVT.getSizeInBits();
=20
@@ -5118,8 +5070,7 @@
         // convert it to a vector with movd (S2V+shuffle to zero extend).
         Item =3D DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
         Item =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
-        Item =3D getShuffleVectorZeroOrUndef(Item, 0, true,
-                                           Subtarget->hasXMMInt(), DAG);
+        Item =3D getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG=
);
=20
         // Now we have our 32-bit value zero extended in the low element of
         // a vector.  If Idx !=3D 0, swizzle it into place.
@@ -5132,7 +5083,7 @@
                                       DAG.getUNDEF(Item.getValueType()),
                                       &Mask[0]);
         }
-        return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
+        return DAG.getNode(ISD::BITCAST, dl, VT, Item);
       }
     }
=20
@@ -5141,21 +5092,33 @@
     // the rest of the elements.  This will be matched as movd/movq/movss/=
movsd
     // depending on what the source datatype is.
     if (Idx =3D=3D 0) {
-      if (NumZero =3D=3D 0) {
+      if (NumZero =3D=3D 0)
         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
-      } else if (ExtVT =3D=3D MVT::i32 || ExtVT =3D=3D MVT::f32 || ExtVT =
=3D=3D MVT::f64 ||
+
+      if (ExtVT =3D=3D MVT::i32 || ExtVT =3D=3D MVT::f32 || ExtVT =3D=3D M=
VT::f64 ||
           (ExtVT =3D=3D MVT::i64 && Subtarget->is64Bit())) {
+        if (VT.getSizeInBits() =3D=3D 256) {
+          SDValue ZeroVec =3D getZeroVector(VT, Subtarget, DAG, dl);
+          return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
+                             Item, DAG.getIntPtrConstant(0));
+        }
+        assert(VT.getSizeInBits() =3D=3D 128 && "Expected an SSE value typ=
e!");
         Item =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vect=
or.
-        return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMM=
Int(),
-                                           DAG);
-      } else if (ExtVT =3D=3D MVT::i16 || ExtVT =3D=3D MVT::i8) {
+        return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
+      }
+
+      if (ExtVT =3D=3D MVT::i16 || ExtVT =3D=3D MVT::i8) {
         Item =3D DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
-        assert(VT.getSizeInBits() =3D=3D 128 && "Expected an SSE value typ=
e!");
-        EVT MiddleVT =3D MVT::v4i32;
-        Item =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
-        Item =3D getShuffleVectorZeroOrUndef(Item, 0, true,
-                                           Subtarget->hasXMMInt(), DAG);
+        Item =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
+        if (VT.getSizeInBits() =3D=3D 256) {
+          SDValue ZeroVec =3D getZeroVector(MVT::v8i32, Subtarget, DAG, dl=
);
+          Item =3D Insert128BitVector(ZeroVec, Item, DAG.getConstant(0, MV=
T::i32),
+                                    DAG, dl);
+        } else {
+          assert(VT.getSizeInBits() =3D=3D 128 && "Expected an SSE value t=
ype!");
+          Item =3D getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, D=
AG);
+        }
         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
       }
     }
@@ -5183,8 +5146,7 @@
       Item =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
=20
       // Turn it into a shuffle of zero and zero-extended scalar to vector.
-      Item =3D getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
-                                         Subtarget->hasXMMInt(), DAG);
+      Item =3D getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget=
, DAG);
       SmallVector<int, 8> MaskVec;
       for (unsigned i =3D 0; i < NumElems; i++)
         MaskVec.push_back(i =3D=3D Idx ? 0 : 1);
@@ -5214,9 +5176,9 @@
=20
   // For AVX-length vectors, build the individual 128-bit pieces and use
   // shuffles to put them in place.
-  if (VT.getSizeInBits() =3D=3D 256 && !ISD::isBuildVectorAllZeros(Op.getN=
ode())) {
+  if (VT.getSizeInBits() =3D=3D 256) {
     SmallVector<SDValue, 32> V;
-    for (unsigned i =3D 0; i < NumElems; ++i)
+    for (unsigned i =3D 0; i !=3D NumElems; ++i)
       V.push_back(Op.getOperand(i));
=20
     EVT HVT =3D EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
@@ -5240,8 +5202,7 @@
       unsigned Idx =3D CountTrailingZeros_32(NonZeros);
       SDValue V2 =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
                                  Op.getOperand(Idx));
-      return getShuffleVectorZeroOrUndef(V2, Idx, true,
-                                         Subtarget->hasXMMInt(), DAG);
+      return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
     }
     return SDValue();
   }
@@ -5249,24 +5210,23 @@
   // If element VT is < 32 bits, convert it to inserts into a zero vector.
   if (EVTBits =3D=3D 8 && NumElems =3D=3D 16) {
     SDValue V =3D LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, D=
AG,
-                                        *this);
+                                        Subtarget, *this);
     if (V.getNode()) return V;
   }
=20
   if (EVTBits =3D=3D 16 && NumElems =3D=3D 8) {
     SDValue V =3D LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, D=
AG,
-                                      *this);
+                                      Subtarget, *this);
     if (V.getNode()) return V;
   }
=20
   // If element VT is =3D=3D 32 bits, turn it into a number of shuffles.
-  SmallVector<SDValue, 8> V;
-  V.resize(NumElems);
+  SmallVector<SDValue, 8> V(NumElems);
   if (NumElems =3D=3D 4 && NumZero > 0) {
     for (unsigned i =3D 0; i < 4; ++i) {
       bool isZero =3D !(NonZeros & (1 << i));
       if (isZero)
-        V[i] =3D getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
+        V[i] =3D getZeroVector(VT, Subtarget, DAG, dl);
       else
         V[i] =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(=
i));
     }
@@ -5289,13 +5249,14 @@
       }
     }
=20
-    SmallVector<int, 8> MaskVec;
-    bool Reverse =3D (NonZeros & 0x3) =3D=3D 2;
-    for (unsigned i =3D 0; i < 2; ++i)
-      MaskVec.push_back(Reverse ? 1-i : i);
-    Reverse =3D ((NonZeros & (0x3 << 2)) >> 2) =3D=3D 2;
-    for (unsigned i =3D 0; i < 2; ++i)
-      MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
+    bool Reverse1 =3D (NonZeros & 0x3) =3D=3D 2;
+    bool Reverse2 =3D ((NonZeros & (0x3 << 2)) >> 2) =3D=3D 2;
+    int MaskVec[] =3D {
+      Reverse1 ? 1 : 0,
+      Reverse1 ? 0 : 1,
+      static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
+      static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
+    };
     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
   }
=20
@@ -5310,7 +5271,7 @@
       return LD;
=20
     // For SSE 4.1, use insertps to put the high elements into the low ele=
ment.
-    if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
+    if (getSubtarget()->hasSSE41()) {
       SDValue Result;
       if (Op.getOperand(0).getOpcode() !=3D ISD::UNDEF)
         Result =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperan=
d(0));
@@ -5422,6 +5383,85 @@
   return LowerAVXCONCAT_VECTORS(Op, DAG);
 }
=20
+// Try to lower a shuffle node into a simple blend instruction.
+static SDValue LowerVECTOR_SHUFFLEtoBlend(SDValue Op,
+                                          const X86Subtarget *Subtarget,
+                                          SelectionDAG &DAG) {
+  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(Op);
+  SDValue V1 =3D SVOp->getOperand(0);
+  SDValue V2 =3D SVOp->getOperand(1);
+  DebugLoc dl =3D SVOp->getDebugLoc();
+  EVT VT =3D Op.getValueType();
+  EVT InVT =3D V1.getValueType();
+  int MaskSize =3D VT.getVectorNumElements();
+  int InSize =3D InVT.getVectorNumElements();
+
+  if (!Subtarget->hasSSE41())
+    return SDValue();
+
+  if (MaskSize !=3D InSize)
+    return SDValue();
+
+  int ISDNo =3D 0;
+  MVT OpTy;
+
+  switch (VT.getSimpleVT().SimpleTy) {
+  default: return SDValue();
+  case MVT::v8i16:
+           ISDNo =3D X86ISD::BLENDPW;
+           OpTy =3D MVT::v8i16;
+           break;
+  case MVT::v4i32:
+  case MVT::v4f32:
+           ISDNo =3D X86ISD::BLENDPS;
+           OpTy =3D MVT::v4f32;
+           break;
+  case MVT::v2i64:
+  case MVT::v2f64:
+           ISDNo =3D X86ISD::BLENDPD;
+           OpTy =3D MVT::v2f64;
+           break;
+  case MVT::v8i32:
+  case MVT::v8f32:
+           if (!Subtarget->hasAVX())
+             return SDValue();
+           ISDNo =3D X86ISD::BLENDPS;
+           OpTy =3D MVT::v8f32;
+           break;
+  case MVT::v4i64:
+  case MVT::v4f64:
+           if (!Subtarget->hasAVX())
+             return SDValue();
+           ISDNo =3D X86ISD::BLENDPD;
+           OpTy =3D MVT::v4f64;
+           break;
+  case MVT::v16i16:
+           if (!Subtarget->hasAVX2())
+             return SDValue();
+           ISDNo =3D X86ISD::BLENDPW;
+           OpTy =3D MVT::v16i16;
+           break;
+  }
+  assert(ISDNo && "Invalid Op Number");
+
+  unsigned MaskVals =3D 0;
+
+  for (int i =3D 0; i < MaskSize; ++i) {
+    int EltIdx =3D SVOp->getMaskElt(i);
+    if (EltIdx =3D=3D i || EltIdx =3D=3D -1)
+      MaskVals |=3D (1<<i);
+    else if (EltIdx =3D=3D (i + MaskSize))
+      continue; // Bit is set to zero;
+    else return SDValue();
+  }
+
+  V1 =3D DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
+  V2 =3D DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
+  SDValue Ret =3D  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
+                             DAG.getConstant(MaskVals, MVT::i32));
+  return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
+}
+
 // v8i16 shuffles - Prefer shuffles in the following order:
 // 1. [all]   pshuflw, pshufhw, optional move
 // 2. [ssse3] 1 x pshufb
@@ -5439,11 +5479,11 @@
   // Determine if more than 1 of the words in each of the low and high qua=
dwords
   // of the result come from the same quadword of one of the two inputs.  =
Undef
   // mask values count as coming from any quadword, for better codegen.
-  SmallVector<unsigned, 4> LoQuad(4);
-  SmallVector<unsigned, 4> HiQuad(4);
-  BitVector InputQuads(4);
+  unsigned LoQuad[] =3D { 0, 0, 0, 0 };
+  unsigned HiQuad[] =3D { 0, 0, 0, 0 };
+  std::bitset<4> InputQuads;
   for (unsigned i =3D 0; i < 8; ++i) {
-    SmallVectorImpl<unsigned> &Quad =3D i < 4 ? LoQuad : HiQuad;
+    unsigned *Quad =3D i < 4 ? LoQuad : HiQuad;
     int EltIdx =3D SVOp->getMaskElt(i);
     MaskVals.push_back(EltIdx);
     if (EltIdx < 0) {
@@ -5481,10 +5521,10 @@
   // quads, disable the next transformation since it does not help SSSE3.
   bool V1Used =3D InputQuads[0] || InputQuads[1];
   bool V2Used =3D InputQuads[2] || InputQuads[3];
-  if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
+  if (Subtarget->hasSSSE3()) {
     if (InputQuads.count() =3D=3D 2 && V1Used && V2Used) {
-      BestLoQuad =3D InputQuads.find_first();
-      BestHiQuad =3D InputQuads.find_next(BestLoQuad);
+      BestLoQuad =3D InputQuads[0] ? 0 : 1;
+      BestHiQuad =3D InputQuads[2] ? 2 : 3;
     }
     if (InputQuads.count() > 2) {
       BestLoQuad =3D -1;
@@ -5497,9 +5537,10 @@
   // words from all 4 input quadwords.
   SDValue NewV;
   if (BestLoQuad >=3D 0 || BestHiQuad >=3D 0) {
-    SmallVector<int, 8> MaskV;
-    MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
-    MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
+    int MaskV[] =3D {
+      BestLoQuad < 0 ? 0 : BestLoQuad,
+      BestHiQuad < 0 ? 1 : BestHiQuad
+    };
     NewV =3D DAG.getVectorShuffle(MVT::v2i64, dl,
                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]=
);
@@ -5544,8 +5585,9 @@
       unsigned TargetMask =3D 0;
       NewV =3D DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
-      TargetMask =3D pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNod=
e()):
-                             X86::getShufflePSHUFLWImmediate(NewV.getNode(=
));
+      ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(NewV.getNode=
());
+      TargetMask =3D pshufhw ? getShufflePSHUFHWImmediate(SVOp):
+                             getShufflePSHUFLWImmediate(SVOp);
       V1 =3D NewV.getOperand(0);
       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG=
);
     }
@@ -5554,7 +5596,7 @@
   // If we have SSSE3, and all words of the result are from 1 input vector,
   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
   // is present, fall back to case 4.
-  if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
+  if (Subtarget->hasSSSE3()) {
     SmallVector<SDValue,16> pshufbMask;
=20
     // If we have elements from both input vectors, set the high bit of the
@@ -5602,61 +5644,51 @@
=20
   // If BestLoQuad >=3D 0, generate a pshuflw to put the low elements in o=
rder,
   // and update MaskVals with new element order.
-  BitVector InOrder(8);
+  std::bitset<8> InOrder;
   if (BestLoQuad >=3D 0) {
-    SmallVector<int, 8> MaskV;
+    int MaskV[] =3D { -1, -1, -1, -1, 4, 5, 6, 7 };
     for (int i =3D 0; i !=3D 4; ++i) {
       int idx =3D MaskVals[i];
       if (idx < 0) {
-        MaskV.push_back(-1);
         InOrder.set(i);
       } else if ((idx / 4) =3D=3D BestLoQuad) {
-        MaskV.push_back(idx & 3);
+        MaskV[i] =3D idx & 3;
         InOrder.set(i);
-      } else {
-        MaskV.push_back(-1);
-      }
-    }
-    for (unsigned i =3D 4; i !=3D 8; ++i)
-      MaskV.push_back(i);
+      }
+    }
     NewV =3D DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::=
v8i16),
                                 &MaskV[0]);
=20
-    if (NewV.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE &&
-        (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
+    if (NewV.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3=
()) {
+      ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(NewV.getNode=
());
       NewV =3D getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
-                               NewV.getOperand(0),
-                               X86::getShufflePSHUFLWImmediate(NewV.getNod=
e()),
-                               DAG);
+                                  NewV.getOperand(0),
+                                  getShufflePSHUFLWImmediate(SVOp), DAG);
+    }
   }
=20
   // If BestHi >=3D 0, generate a pshufhw to put the high elements in orde=
r,
   // and update MaskVals with the new element order.
   if (BestHiQuad >=3D 0) {
-    SmallVector<int, 8> MaskV;
-    for (unsigned i =3D 0; i !=3D 4; ++i)
-      MaskV.push_back(i);
+    int MaskV[] =3D { 0, 1, 2, 3, -1, -1, -1, -1 };
     for (unsigned i =3D 4; i !=3D 8; ++i) {
       int idx =3D MaskVals[i];
       if (idx < 0) {
-        MaskV.push_back(-1);
         InOrder.set(i);
       } else if ((idx / 4) =3D=3D BestHiQuad) {
-        MaskV.push_back((idx & 3) + 4);
+        MaskV[i] =3D (idx & 3) + 4;
         InOrder.set(i);
-      } else {
-        MaskV.push_back(-1);
       }
     }
     NewV =3D DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::=
v8i16),
                                 &MaskV[0]);
=20
-    if (NewV.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE &&
-        (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
+    if (NewV.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3=
()) {
+      ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(NewV.getNode=
());
       NewV =3D getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
-                              NewV.getOperand(0),
-                              X86::getShufflePSHUFHWImmediate(NewV.getNode=
()),
-                              DAG);
+                                  NewV.getOperand(0),
+                                  getShufflePSHUFHWImmediate(SVOp), DAG);
+    }
   }
=20
   // In case BestHi & BestLo were both -1, which means each quadword has a=
 word
@@ -5698,8 +5730,7 @@
   SDValue V1 =3D SVOp->getOperand(0);
   SDValue V2 =3D SVOp->getOperand(1);
   DebugLoc dl =3D SVOp->getDebugLoc();
-  SmallVector<int, 16> MaskVals;
-  SVOp->getMask(MaskVals);
+  ArrayRef<int> MaskVals =3D SVOp->getMask();
=20
   // If we have SSSE3, case 1 is generated when all result bytes come from
   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
@@ -5718,7 +5749,7 @@
   }
=20
   // If SSSE3, use 1 pshufb instruction per vector with elements in the re=
sult.
-  if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
+  if (TLI.getSubtarget()->hasSSSE3()) {
     SmallVector<SDValue,16> pshufbMask;
=20
     // If all result elements are from one input vector, then only transla=
te
@@ -5849,7 +5880,7 @@
   unsigned NewWidth =3D (NumElems =3D=3D 4) ? 2 : 4;
   EVT NewVT;
   switch (VT.getSimpleVT().SimpleTy) {
-  default: assert(false && "Unexpected!");
+  default: llvm_unreachable("Unexpected!");
   case MVT::v4f32: NewVT =3D MVT::v2f64; break;
   case MVT::v4i32: NewVT =3D MVT::v2i64; break;
   case MVT::v8i16: NewVT =3D MVT::v4i32; break;
@@ -5915,96 +5946,89 @@
                                              OpVT, SrcOp)));
 }
=20
-/// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vec=
tor
-/// shuffle node referes to only one lane in the sources.
-static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp)=
 {
-  EVT VT =3D SVOp->getValueType(0);
-  int NumElems =3D VT.getVectorNumElements();
-  int HalfSize =3D NumElems/2;
-  SmallVector<int, 16> M;
-  SVOp->getMask(M);
-  bool MatchA =3D false, MatchB =3D false;
-
-  for (int l =3D 0; l < NumElems*2; l +=3D HalfSize) {
-    if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
-      MatchA =3D true;
-      break;
-    }
-  }
-
-  for (int l =3D 0; l < NumElems*2; l +=3D HalfSize) {
-    if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
-      MatchB =3D true;
-      break;
-    }
-  }
-
-  return MatchA && MatchB;
-}
-
 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
 /// which could not be matched by any known target speficic shuffle
 static SDValue
 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
-  if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
-    // If each half of a vector shuffle node referes to only one lane in t=
he
-    // source vectors, extract each used 128-bit lane and shuffle them usi=
ng
-    // 128-bit shuffles. Then, concatenate the results. Otherwise leave
-    // the work to the legalizer.
-    DebugLoc dl =3D SVOp->getDebugLoc();
-    EVT VT =3D SVOp->getValueType(0);
-    int NumElems =3D VT.getVectorNumElements();
-    int HalfSize =3D NumElems/2;
-
-    // Extract the reference for each half
-    int FstVecExtractIdx =3D 0, SndVecExtractIdx =3D 0;
-    int FstVecOpNum =3D 0, SndVecOpNum =3D 0;
-    for (int i =3D 0; i < HalfSize; ++i) {
-      int Elt =3D SVOp->getMaskElt(i);
-      if (SVOp->getMaskElt(i) < 0)
+  EVT VT =3D SVOp->getValueType(0);
+
+  unsigned NumElems =3D VT.getVectorNumElements();
+  unsigned NumLaneElems =3D NumElems / 2;
+
+  DebugLoc dl =3D SVOp->getDebugLoc();
+  MVT EltVT =3D VT.getVectorElementType().getSimpleVT();
+  EVT NVT =3D MVT::getVectorVT(EltVT, NumLaneElems);
+  SDValue Shufs[2];
+
+  SmallVector<int, 16> Mask;
+  for (unsigned l =3D 0; l < 2; ++l) {
+    // Build a shuffle mask for the output, discovering on the fly which
+    // input vectors to use as shuffle operands (recorded in InputUsed).
+    // If building a suitable shuffle vector proves too hard, then bail
+    // out with useBuildVector set.
+    int InputUsed[2] =3D { -1, -1 }; // Not yet discovered.
+    unsigned LaneStart =3D l * NumLaneElems;
+    for (unsigned i =3D 0; i !=3D NumLaneElems; ++i) {
+      // The mask element.  This indexes into the input.
+      int Idx =3D SVOp->getMaskElt(i+LaneStart);
+      if (Idx < 0) {
+        // the mask element does not index into any input vector.
+        Mask.push_back(-1);
         continue;
-      FstVecOpNum =3D Elt/NumElems;
-      FstVecExtractIdx =3D Elt % NumElems < HalfSize ? 0 : HalfSize;
-      break;
-    }
-    for (int i =3D HalfSize; i < NumElems; ++i) {
-      int Elt =3D SVOp->getMaskElt(i);
-      if (SVOp->getMaskElt(i) < 0)
-        continue;
-      SndVecOpNum =3D Elt/NumElems;
-      SndVecExtractIdx =3D Elt % NumElems < HalfSize ? 0 : HalfSize;
-      break;
-    }
-
-    // Extract the subvectors
-    SDValue V1 =3D Extract128BitVector(SVOp->getOperand(FstVecOpNum),
-                      DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl=
);
-    SDValue V2 =3D Extract128BitVector(SVOp->getOperand(SndVecOpNum),
-                      DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl=
);
-
-    // Generate 128-bit shuffles
-    SmallVector<int, 16> MaskV1, MaskV2;
-    for (int i =3D 0; i < HalfSize; ++i) {
-      int Elt =3D SVOp->getMaskElt(i);
-      MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
-    }
-    for (int i =3D HalfSize; i < NumElems; ++i) {
-      int Elt =3D SVOp->getMaskElt(i);
-      MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
-    }
-
-    EVT NVT =3D V1.getValueType();
-    V1 =3D DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]=
);
-    V2 =3D DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]=
);
-
-    // Concatenate the result back
-    SDValue V =3D Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
-                                   DAG.getConstant(0, MVT::i32), DAG, dl);
-    return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
-                              DAG, dl);
-  }
-
-  return SDValue();
+      }
+
+      // The input vector this mask element indexes into.
+      int Input =3D Idx / NumLaneElems;
+
+      // Turn the index into an offset from the start of the input vector.
+      Idx -=3D Input * NumLaneElems;
+
+      // Find or create a shuffle vector operand to hold this input.
+      unsigned OpNo;
+      for (OpNo =3D 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
+        if (InputUsed[OpNo] =3D=3D Input)
+          // This input vector is already an operand.
+          break;
+        if (InputUsed[OpNo] < 0) {
+          // Create a new operand for this input vector.
+          InputUsed[OpNo] =3D Input;
+          break;
+        }
+      }
+
+      if (OpNo >=3D array_lengthof(InputUsed)) {
+        // More than two input vectors used! Give up.
+        return SDValue();
+      }
+
+      // Add the mask index for the new shuffle vector.
+      Mask.push_back(Idx + OpNo * NumLaneElems);
+    }
+
+    if (InputUsed[0] < 0) {
+      // No input vectors were used! The result is undefined.
+      Shufs[l] =3D DAG.getUNDEF(NVT);
+    } else {
+      SDValue Op0 =3D Extract128BitVector(SVOp->getOperand(InputUsed[0] / =
2),
+                   DAG.getConstant((InputUsed[0] % 2) * NumLaneElems, MVT:=
:i32),
+                                   DAG, dl);
+      // If only one input was used, use an undefined vector for the other.
+      SDValue Op1 =3D (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
+        Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
+                   DAG.getConstant((InputUsed[1] % 2) * NumLaneElems, MVT:=
:i32),
+                                   DAG, dl);
+      // At least one input vector was used. Create a new shuffle vector.
+      Shufs[l] =3D DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
+    }
+
+    Mask.clear();
+  }
+
+  // Concatenate the result back
+  SDValue V =3D Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Shufs[=
0],
+                                 DAG.getConstant(0, MVT::i32), DAG, dl);
+  return Insert128BitVector(V, Shufs[1],DAG.getConstant(NumLaneElems, MVT:=
:i32),
+                            DAG, dl);
 }
=20
 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
@@ -6018,11 +6042,9 @@
=20
   assert(VT.getSizeInBits() =3D=3D 128 && "Unsupported vector size");
=20
-  SmallVector<std::pair<int, int>, 8> Locs;
-  Locs.resize(4);
-  SmallVector<int, 8> Mask1(4U, -1);
-  SmallVector<int, 8> PermMask;
-  SVOp->getMask(PermMask);
+  std::pair<int, int> Locs[4];
+  int Mask1[] =3D { -1, -1, -1, -1 };
+  SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().en=
d());
=20
   unsigned NumHi =3D 0;
   unsigned NumLo =3D 0;
@@ -6052,17 +6074,14 @@
     // vector operands, put the elements into the right order.
     V1 =3D DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
=20
-    SmallVector<int, 8> Mask2(4U, -1);
-
-    for (unsigned i =3D 0; i !=3D 4; ++i) {
-      if (Locs[i].first =3D=3D -1)
-        continue;
-      else {
+    int Mask2[] =3D { -1, -1, -1, -1 };
+
+    for (unsigned i =3D 0; i !=3D 4; ++i)
+      if (Locs[i].first !=3D -1) {
         unsigned Idx =3D (i < 2) ? 0 : 4;
         Idx +=3D Locs[i].first * 2 + Locs[i].second;
         Mask2[i] =3D Idx;
       }
-    }
=20
     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
   } else if (NumLo =3D=3D 3 || NumHi =3D=3D 3) {
@@ -6075,7 +6094,7 @@
     // from X.
     if (NumHi =3D=3D 3) {
       // Normalize it so the 3 elements come from V1.
-      CommuteVectorShuffleMask(PermMask, VT);
+      CommuteVectorShuffleMask(PermMask, 4);
       std::swap(V1, V2);
     }
=20
@@ -6115,18 +6134,16 @@
   }
=20
   // Break it into (shuffle shuffle_hi, shuffle_lo).
-  Locs.clear();
-  Locs.resize(4);
-  SmallVector<int,8> LoMask(4U, -1);
-  SmallVector<int,8> HiMask(4U, -1);
-
-  SmallVector<int,8> *MaskPtr =3D &LoMask;
+  int LoMask[] =3D { -1, -1, -1, -1 };
+  int HiMask[] =3D { -1, -1, -1, -1 };
+
+  int *MaskPtr =3D LoMask;
   unsigned MaskIdx =3D 0;
   unsigned LoIdx =3D 0;
   unsigned HiIdx =3D 2;
   for (unsigned i =3D 0; i !=3D 4; ++i) {
     if (i =3D=3D 2) {
-      MaskPtr =3D &HiMask;
+      MaskPtr =3D HiMask;
       MaskIdx =3D 1;
       LoIdx =3D 0;
       HiIdx =3D 2;
@@ -6136,26 +6153,21 @@
       Locs[i] =3D std::make_pair(-1, -1);
     } else if (Idx < 4) {
       Locs[i] =3D std::make_pair(MaskIdx, LoIdx);
-      (*MaskPtr)[LoIdx] =3D Idx;
+      MaskPtr[LoIdx] =3D Idx;
       LoIdx++;
     } else {
       Locs[i] =3D std::make_pair(MaskIdx, HiIdx);
-      (*MaskPtr)[HiIdx] =3D Idx;
+      MaskPtr[HiIdx] =3D Idx;
       HiIdx++;
     }
   }
=20
   SDValue LoShuffle =3D DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
   SDValue HiShuffle =3D DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
-  SmallVector<int, 8> MaskOps;
-  for (unsigned i =3D 0; i !=3D 4; ++i) {
-    if (Locs[i].first =3D=3D -1) {
-      MaskOps.push_back(-1);
-    } else {
-      unsigned Idx =3D Locs[i].first * 4 + Locs[i].second;
-      MaskOps.push_back(Idx);
-    }
-  }
+  int MaskOps[] =3D { -1, -1, -1, -1 };
+  for (unsigned i =3D 0; i !=3D 4; ++i)
+    if (Locs[i].first !=3D -1)
+      MaskOps[i] =3D Locs[i].first * 4 + Locs[i].second;
   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
 }
=20
@@ -6164,6 +6176,10 @@
     V =3D V.getOperand(0);
   if (V.hasOneUse() && V.getOpcode() =3D=3D ISD::SCALAR_TO_VECTOR)
     V =3D V.getOperand(0);
+  if (V.hasOneUse() && V.getOpcode() =3D=3D ISD::BUILD_VECTOR &&
+      V.getNumOperands() =3D=3D 2 && V.getOperand(1).getOpcode() =3D=3D IS=
D::UNDEF)
+    // BUILD_VECTOR (load), undef
+    V =3D V.getOperand(0);
   if (MayFoldLoad(V))
     return true;
   return false;
@@ -6186,82 +6202,6 @@
   return false;
 }
=20
-/// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
-/// a vector extract, and if both can be later optimized into a single loa=
d.
-/// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
-/// here because otherwise a target specific shuffle node is going to be
-/// emitted for this shuffle, and the optimization not done.
-/// FIXME: This is probably not the best approach, but fix the problem
-/// until the right path is decided.
-static
-bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
-                                         const TargetLowering &TLI) {
-  EVT VT =3D V.getValueType();
-  ShuffleVectorSDNode *SVOp =3D dyn_cast<ShuffleVectorSDNode>(V);
-
-  // Be sure that the vector shuffle is present in a pattern like this:
-  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $a=
ddr)
-  if (!V.hasOneUse())
-    return false;
-
-  SDNode *N =3D *V.getNode()->use_begin();
-  if (N->getOpcode() !=3D ISD::EXTRACT_VECTOR_ELT)
-    return false;
-
-  SDValue EltNo =3D N->getOperand(1);
-  if (!isa<ConstantSDNode>(EltNo))
-    return false;
-
-  // If the bit convert changed the number of elements, it is unsafe
-  // to examine the mask.
-  bool HasShuffleIntoBitcast =3D false;
-  if (V.getOpcode() =3D=3D ISD::BITCAST) {
-    EVT SrcVT =3D V.getOperand(0).getValueType();
-    if (SrcVT.getVectorNumElements() !=3D VT.getVectorNumElements())
-      return false;
-    V =3D V.getOperand(0);
-    HasShuffleIntoBitcast =3D true;
-  }
-
-  // Select the input vector, guarding against out of range extract vector.
-  unsigned NumElems =3D VT.getVectorNumElements();
-  unsigned Elt =3D cast<ConstantSDNode>(EltNo)->getZExtValue();
-  int Idx =3D (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
-  V =3D (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
-
-  // Skip one more bit_convert if necessary
-  if (V.getOpcode() =3D=3D ISD::BITCAST)
-    V =3D V.getOperand(0);
-
-  if (ISD::isNormalLoad(V.getNode())) {
-    // Is the original load suitable?
-    LoadSDNode *LN0 =3D cast<LoadSDNode>(V);
-
-    // FIXME: avoid the multi-use bug that is preventing lots of
-    // of foldings to be detected, this is still wrong of course, but
-    // give the temporary desired behavior, and if it happens that
-    // the load has real more uses, during isel it will not fold, and
-    // will generate poor code.
-    if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
-      return false;
-
-    if (!HasShuffleIntoBitcast)
-      return true;
-
-    // If there's a bitcast before the shuffle, check if the load type and
-    // alignment is valid.
-    unsigned Align =3D LN0->getAlignment();
-    unsigned NewAlign =3D
-      TLI.getTargetData()->getABITypeAlignment(
-                                    VT.getTypeForEVT(*DAG.getContext()));
-
-    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
-      return false;
-  }
-
-  return true;
-}
-
 static
 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DA=
G) {
   EVT VT =3D Op.getValueType();
@@ -6275,14 +6215,14 @@
=20
 static
 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
-                        bool HasXMMInt) {
+                        bool HasSSE2) {
   SDValue V1 =3D Op.getOperand(0);
   SDValue V2 =3D Op.getOperand(1);
   EVT VT =3D Op.getValueType();
=20
   assert(VT !=3D MVT::v2i64 && "unsupported shuffle type");
=20
-  if (HasXMMInt && VT =3D=3D MVT::v2f64)
+  if (HasSSE2 && VT =3D=3D MVT::v2f64)
     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
=20
   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
@@ -6308,24 +6248,8 @@
   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
 }
=20
-static inline unsigned getSHUFPOpcode(EVT VT) {
-  switch(VT.getSimpleVT().SimpleTy) {
-  case MVT::v8i32: // Use fp unit for int unpack.
-  case MVT::v8f32:
-  case MVT::v4i32: // Use fp unit for int unpack.
-  case MVT::v4f32: return X86ISD::SHUFPS;
-  case MVT::v4i64: // Use fp unit for int unpack.
-  case MVT::v4f64:
-  case MVT::v2i64: // Use fp unit for int unpack.
-  case MVT::v2f64: return X86ISD::SHUFPD;
-  default:
-    llvm_unreachable("Unknown type for shufp*");
-  }
-  return 0;
-}
-
 static
-SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMM=
Int) {
+SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE=
2) {
   SDValue V1 =3D Op.getOperand(0);
   SDValue V2 =3D Op.getOperand(1);
   EVT VT =3D Op.getValueType();
@@ -6346,32 +6270,30 @@
   //    turns into:
   //  (MOVLPSmr addr:$src1, VR128:$src2)
   // So, recognize this potential and also use MOVLPS or MOVLPD
-  if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
+  else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
     CanFoldLoad =3D true;
=20
-  // Both of them can't be memory operations though.
-  if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
-    CanFoldLoad =3D false;
-
+  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(Op);
   if (CanFoldLoad) {
-    if (HasXMMInt && NumElems =3D=3D 2)
+    if (HasSSE2 && NumElems =3D=3D 2)
       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
=20
     if (NumElems =3D=3D 4)
-      return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
-  }
-
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(Op);
+      // If we don't care about the second element, procede to use movss.
+      if (SVOp->getMaskElt(1) !=3D -1)
+        return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
+  }
+
   // movl and movlp will both match v2i64, but v2i64 is never matched by
   // movl earlier because we make it strict to avoid messing with the movl=
p load
   // folding logic (see the code above getMOVLP call). Match it here then,
   // this is horrible, but will stay like this until we move all shuffle
   // matching to x86 specific nodes. Note that for the 1st condition all
   // types are matched with movsd.
-  if (HasXMMInt) {
+  if (HasSSE2) {
     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
     // as to remove this logic from here, as much as possible
-    if (NumElems =3D=3D 2 || !X86::isMOVLMask(SVOp))
+    if (NumElems =3D=3D 2 || !isMOVLMask(SVOp->getMask(), VT))
       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
   }
@@ -6379,112 +6301,12 @@
   assert(VT !=3D MVT::v4i32 && "unsupported shuffle type");
=20
   // Invert the operand order and use SHUFPS to match it.
-  return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
-                              X86::getShuffleSHUFImmediate(SVOp), DAG);
-}
-
-static inline unsigned getUNPCKLOpcode(EVT VT) {
-  switch(VT.getSimpleVT().SimpleTy) {
-  case MVT::v4i32: return X86ISD::PUNPCKLDQ;
-  case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
-  case MVT::v4f32: return X86ISD::UNPCKLPS;
-  case MVT::v2f64: return X86ISD::UNPCKLPD;
-  case MVT::v8i32: // Use fp unit for int unpack.
-  case MVT::v8f32: return X86ISD::VUNPCKLPSY;
-  case MVT::v4i64: // Use fp unit for int unpack.
-  case MVT::v4f64: return X86ISD::VUNPCKLPDY;
-  case MVT::v16i8: return X86ISD::PUNPCKLBW;
-  case MVT::v8i16: return X86ISD::PUNPCKLWD;
-  default:
-    llvm_unreachable("Unknown type for unpckl");
-  }
-  return 0;
-}
-
-static inline unsigned getUNPCKHOpcode(EVT VT) {
-  switch(VT.getSimpleVT().SimpleTy) {
-  case MVT::v4i32: return X86ISD::PUNPCKHDQ;
-  case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
-  case MVT::v4f32: return X86ISD::UNPCKHPS;
-  case MVT::v2f64: return X86ISD::UNPCKHPD;
-  case MVT::v8i32: // Use fp unit for int unpack.
-  case MVT::v8f32: return X86ISD::VUNPCKHPSY;
-  case MVT::v4i64: // Use fp unit for int unpack.
-  case MVT::v4f64: return X86ISD::VUNPCKHPDY;
-  case MVT::v16i8: return X86ISD::PUNPCKHBW;
-  case MVT::v8i16: return X86ISD::PUNPCKHWD;
-  default:
-    llvm_unreachable("Unknown type for unpckh");
-  }
-  return 0;
-}
-
-static inline unsigned getVPERMILOpcode(EVT VT) {
-  switch(VT.getSimpleVT().SimpleTy) {
-  case MVT::v4i32:
-  case MVT::v4f32: return X86ISD::VPERMILPS;
-  case MVT::v2i64:
-  case MVT::v2f64: return X86ISD::VPERMILPD;
-  case MVT::v8i32:
-  case MVT::v8f32: return X86ISD::VPERMILPSY;
-  case MVT::v4i64:
-  case MVT::v4f64: return X86ISD::VPERMILPDY;
-  default:
-    llvm_unreachable("Unknown type for vpermil");
-  }
-  return 0;
-}
-
-/// isVectorBroadcast - Check if the node chain is suitable to be xformed =
to
-/// a vbroadcast node. The nodes are suitable whenever we can fold a load =
coming
-/// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
-static bool isVectorBroadcast(SDValue &Op) {
-  EVT VT =3D Op.getValueType();
-  bool Is256 =3D VT.getSizeInBits() =3D=3D 256;
-
-  assert((VT.getSizeInBits() =3D=3D 128 || Is256) &&
-         "Unsupported type for vbroadcast node");
-
-  SDValue V =3D Op;
-  if (V.hasOneUse() && V.getOpcode() =3D=3D ISD::BITCAST)
-    V =3D V.getOperand(0);
-
-  if (Is256 && !(V.hasOneUse() &&
-                 V.getOpcode() =3D=3D ISD::INSERT_SUBVECTOR &&
-                 V.getOperand(0).getOpcode() =3D=3D ISD::UNDEF))
-    return false;
-
-  if (Is256)
-    V =3D V.getOperand(1);
-
-  if (!V.hasOneUse())
-    return false;
-
-  // Check the source scalar_to_vector type. 256-bit broadcasts are
-  // supported for 32/64-bit sizes, while 128-bit ones are only supported
-  // for 32-bit scalars.
-  if (V.getOpcode() !=3D ISD::SCALAR_TO_VECTOR)
-    return false;
-
-  unsigned ScalarSize =3D V.getOperand(0).getValueType().getSizeInBits();
-  if (ScalarSize !=3D 32 && ScalarSize !=3D 64)
-    return false;
-  if (!Is256 && ScalarSize =3D=3D 64)
-    return false;
-
-  V =3D V.getOperand(0);
-  if (!MayFoldLoad(V))
-    return false;
-
-  // Return the load node
-  Op =3D V;
-  return true;
-}
-
-static
-SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
-                               const TargetLowering &TLI,
-                               const X86Subtarget *Subtarget) {
+  return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
+                              getShuffleSHUFImmediate(SVOp), DAG);
+}
+
+SDValue
+X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) c=
onst {
   ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(Op);
   EVT VT =3D Op.getValueType();
   DebugLoc dl =3D Op.getDebugLoc();
@@ -6492,22 +6314,17 @@
   SDValue V2 =3D Op.getOperand(1);
=20
   if (isZeroShuffle(SVOp))
-    return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
+    return getZeroVector(VT, Subtarget, DAG, dl);
=20
   // Handle splat operations
   if (SVOp->isSplat()) {
     unsigned NumElem =3D VT.getVectorNumElements();
     int Size =3D VT.getSizeInBits();
-    // Special case, this is the only place now where it's allowed to retu=
rn
-    // a vector_shuffle operation without using a target specific node, be=
cause
-    // *hopefully* it will be optimized away by the dag combiner. FIXME: s=
hould
-    // this be moved to DAGCombine instead?
-    if (NumElem <=3D 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI=
))
-      return Op;
=20
     // Use vbroadcast whenever the splat comes from a foldable load
-    if (Subtarget->hasAVX() && isVectorBroadcast(V1))
-      return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
+    SDValue Broadcast =3D LowerVectorBroadcast(Op, DAG);
+    if (Broadcast.getNode())
+      return Broadcast;
=20
     // Handle splats by matching through known shuffle masks
     if ((Size =3D=3D 128 && NumElem <=3D 4) ||
@@ -6525,21 +6342,26 @@
     if (NewOp.getNode())
       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
   } else if ((VT =3D=3D MVT::v4i32 ||
-             (VT =3D=3D MVT::v4f32 && Subtarget->hasXMMInt()))) {
+             (VT =3D=3D MVT::v4f32 && Subtarget->hasSSE2()))) {
     // FIXME: Figure out a cleaner way to do this.
     // Try to make use of movq to zero out the top part.
     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
       SDValue NewOp =3D RewriteAsNarrowerShuffle(SVOp, DAG, dl);
       if (NewOp.getNode()) {
-        if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
-          return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0=
),
+        EVT NewVT =3D NewOp.getValueType();
+        if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
+                               NewVT, true, false))
+          return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
                               DAG, Subtarget, dl);
       }
     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
       SDValue NewOp =3D RewriteAsNarrowerShuffle(SVOp, DAG, dl);
-      if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(New=
Op)))
-        return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
-                            DAG, Subtarget, dl);
+      if (NewOp.getNode()) {
+        EVT NewVT =3D NewOp.getValueType();
+        if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
+          return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
+                              DAG, Subtarget, dl);
+      }
     }
   }
   return SDValue();
@@ -6553,18 +6375,22 @@
   EVT VT =3D Op.getValueType();
   DebugLoc dl =3D Op.getDebugLoc();
   unsigned NumElems =3D VT.getVectorNumElements();
-  bool isMMX =3D VT.getSizeInBits() =3D=3D 64;
   bool V1IsUndef =3D V1.getOpcode() =3D=3D ISD::UNDEF;
   bool V2IsUndef =3D V2.getOpcode() =3D=3D ISD::UNDEF;
   bool V1IsSplat =3D false;
   bool V2IsSplat =3D false;
-  bool HasXMMInt =3D Subtarget->hasXMMInt();
+  bool HasSSE2 =3D Subtarget->hasSSE2();
+  bool HasAVX    =3D Subtarget->hasAVX();
+  bool HasAVX2   =3D Subtarget->hasAVX2();
   MachineFunction &MF =3D DAG.getMachineFunction();
   bool OptForSize =3D MF.getFunction()->hasFnAttr(Attribute::OptimizeForSi=
ze);
=20
-  // Shuffle operations on MMX not supported.
-  if (isMMX)
-    return Op;
+  assert(VT.getSizeInBits() !=3D 64 && "Can't lower MMX shuffles");
+
+  if (V1IsUndef && V2IsUndef)
+    return DAG.getUNDEF(VT);
+
+  assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
=20
   // Vector shuffle lowering takes 3 steps:
   //
@@ -6576,50 +6402,54 @@
   //    so the shuffle can be broken into other shuffles and the legalizer=
 can
   //    try the lowering again.
   //
-  // The general ideia is that no vector_shuffle operation should be left =
to
+  // The general idea is that no vector_shuffle operation should be left to
   // be matched during isel, all of them must be converted to a target spe=
cific
   // node here.
=20
   // Normalize the input vectors. Here splats, zeroed vectors, profitable
   // narrowing and commutation of operands should be handled. The actual c=
ode
   // doesn't include all of those, work in progress...
-  SDValue NewOp =3D NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
+  SDValue NewOp =3D NormalizeVectorShuffle(Op, DAG);
   if (NewOp.getNode())
     return NewOp;
=20
+  SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
+
   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
   // unpckh_undef). Only use pshufd if speed is more important than size.
-  if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
-    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
-  if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
-    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
-
-  if (X86::isMOVDDUPMask(SVOp) &&
-      (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
+  if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
+    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
+  if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
+    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
+
+  if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
     return getMOVDDup(Op, dl, V1, DAG);
=20
-  if (X86::isMOVHLPS_v_undef_Mask(SVOp))
+  if (isMOVHLPS_v_undef_Mask(M, VT))
     return getMOVHighToLow(Op, dl, DAG);
=20
   // Use to match splats
-  if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
+  if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
       (VT =3D=3D MVT::v2f64 || VT =3D=3D MVT::v2i64))
-    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
-
-  if (X86::isPSHUFDMask(SVOp)) {
+    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
+
+  if (isPSHUFDMask(M, VT)) {
     // The actual implementation will match the mask in the if above and t=
hen
     // during isel it can match several different instructions, not only p=
shufd
     // as its name says, sad but true, emulate the behavior for now...
-    if (X86::isMOVDDUPMask(SVOp) && ((VT =3D=3D MVT::v4f32 || VT =3D=3D MV=
T::v2i64)))
-        return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
-
-    unsigned TargetMask =3D X86::getShuffleSHUFImmediate(SVOp);
-
-    if (HasXMMInt && (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v4i32))
+    if (isMOVDDUPMask(M, VT) && ((VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v=
2i64)))
+      return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
+
+    unsigned TargetMask =3D getShuffleSHUFImmediate(SVOp);
+
+    if (HasAVX && (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v2f64))
+      return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask=
, DAG);
+
+    if (HasSSE2 && (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v4i32))
       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, =
DAG);
=20
-    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
+    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
                                 TargetMask, DAG);
   }
=20
@@ -6627,8 +6457,7 @@
   bool isLeft =3D false;
   unsigned ShAmt =3D 0;
   SDValue ShVal;
-  bool isShift =3D getSubtarget()->hasXMMInt() &&
-                 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
+  bool isShift =3D HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAm=
t);
   if (isShift && ShVal.hasOneUse()) {
     // If the shifted value has multiple uses, it may be cheaper to use
     // v_set0 + movlhps or movhlps, etc.
@@ -6637,13 +6466,11 @@
     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
   }
=20
-  if (X86::isMOVLMask(SVOp)) {
-    if (V1IsUndef)
-      return V2;
+  if (isMOVLMask(M, VT)) {
     if (ISD::isBuildVectorAllZeros(V1.getNode()))
       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
-    if (!X86::isMOVLPMask(SVOp)) {
-      if (HasXMMInt && (VT =3D=3D MVT::v2i64 || VT =3D=3D MVT::v2f64))
+    if (!isMOVLPMask(M, VT)) {
+      if (HasSSE2 && (VT =3D=3D MVT::v2i64 || VT =3D=3D MVT::v2f64))
         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
=20
       if (VT =3D=3D MVT::v4i32 || VT =3D=3D MVT::v4f32)
@@ -6652,27 +6479,27 @@
   }
=20
   // FIXME: fold these into legal mask.
-  if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
-    return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
-
-  if (X86::isMOVHLPSMask(SVOp))
+  if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
+    return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
+
+  if (isMOVHLPSMask(M, VT))
     return getMOVHighToLow(Op, dl, DAG);
=20
-  if (X86::isMOVSHDUPMask(SVOp, Subtarget))
+  if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
=20
-  if (X86::isMOVSLDUPMask(SVOp, Subtarget))
+  if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
=20
-  if (X86::isMOVLPMask(SVOp))
-    return getMOVLP(Op, dl, DAG, HasXMMInt);
-
-  if (ShouldXformToMOVHLPS(SVOp) ||
-      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
+  if (isMOVLPMask(M, VT))
+    return getMOVLP(Op, dl, DAG, HasSSE2);
+
+  if (ShouldXformToMOVHLPS(M, VT) ||
+      ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
     return CommuteVectorShuffle(SVOp, DAG);
=20
   if (isShift) {
-    // No better options. Use a vshl / vsrl.
+    // No better options. Use a vshldq / vsrldq.
     EVT EltVT =3D VT.getVectorElementType();
     ShAmt *=3D EltVT.getSizeInBits();
     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
@@ -6685,17 +6512,14 @@
   V2IsSplat =3D isSplatVector(V2.getNode());
=20
   // Canonicalize the splat or undef, if present, to be on the RHS.
-  if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
-    Op =3D CommuteVectorShuffle(SVOp, DAG);
-    SVOp =3D cast<ShuffleVectorSDNode>(Op);
-    V1 =3D SVOp->getOperand(0);
-    V2 =3D SVOp->getOperand(1);
+  if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
+    CommuteVectorShuffleMask(M, NumElems);
+    std::swap(V1, V2);
     std::swap(V1IsSplat, V2IsSplat);
-    std::swap(V1IsUndef, V2IsUndef);
     Commuted =3D true;
   }
=20
-  if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
+  if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
     // Shuffling low element of v1 into undef, just return v1.
     if (V2IsUndef)
       return V1;
@@ -6705,81 +6529,77 @@
     return getMOVL(DAG, dl, VT, V2, V1);
   }
=20
-  if (X86::isUNPCKLMask(SVOp))
-    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
-
-  if (X86::isUNPCKHMask(SVOp))
-    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
+  if (isUNPCKLMask(M, VT, HasAVX2))
+    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
+
+  if (isUNPCKHMask(M, VT, HasAVX2))
+    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
=20
   if (V2IsSplat) {
     // Normalize mask so all entries that point to V2 points to its first
     // element then try to match unpck{h|l} again. If match, return a
-    // new vector_shuffle with the corrected mask.
-    SDValue NewMask =3D NormalizeMask(SVOp, DAG);
-    ShuffleVectorSDNode *NSVOp =3D cast<ShuffleVectorSDNode>(NewMask);
-    if (NSVOp !=3D SVOp) {
-      if (X86::isUNPCKLMask(NSVOp, true)) {
-        return NewMask;
-      } else if (X86::isUNPCKHMask(NSVOp, true)) {
-        return NewMask;
-      }
+    // new vector_shuffle with the corrected mask.p
+    SmallVector<int, 8> NewMask(M.begin(), M.end());
+    NormalizeMask(NewMask, NumElems);
+    if (isUNPCKLMask(NewMask, VT, HasAVX2, true)) {
+      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
+    } else if (isUNPCKHMask(NewMask, VT, HasAVX2, true)) {
+      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
     }
   }
=20
   if (Commuted) {
     // Commute is back and try unpck* again.
     // FIXME: this seems wrong.
-    SDValue NewOp =3D CommuteVectorShuffle(SVOp, DAG);
-    ShuffleVectorSDNode *NewSVOp =3D cast<ShuffleVectorSDNode>(NewOp);
-
-    if (X86::isUNPCKLMask(NewSVOp))
-      return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG=
);
-
-    if (X86::isUNPCKHMask(NewSVOp))
-      return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG=
);
+    CommuteVectorShuffleMask(M, NumElems);
+    std::swap(V1, V2);
+    std::swap(V1IsSplat, V2IsSplat);
+    Commuted =3D false;
+
+    if (isUNPCKLMask(M, VT, HasAVX2))
+      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
+
+    if (isUNPCKHMask(M, VT, HasAVX2))
+      return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
   }
=20
   // Normalize the node to match x86 shuffle ops if needed
-  if (V2.getOpcode() !=3D ISD::UNDEF && isCommutedSHUFP(SVOp))
+  if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
     return CommuteVectorShuffle(SVOp, DAG);
=20
   // The checks below are all present in isShuffleMaskLegal, but they are
   // inlined here right now to enable us to directly emit target specific
   // nodes, and remove one by one until they don't return Op anymore.
-  SmallVector<int, 16> M;
-  SVOp->getMask(M);
-
-  if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
+
+  if (isPALIGNRMask(M, VT, Subtarget))
     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
-                                X86::getShufflePALIGNRImmediate(SVOp),
+                                getShufflePALIGNRImmediate(SVOp),
                                 DAG);
=20
   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
       SVOp->getSplatIndex() =3D=3D 0 && V2IsUndef) {
-    if (VT =3D=3D MVT::v2f64)
-      return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
-    if (VT =3D=3D MVT::v2i64)
-      return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
+    if (VT =3D=3D MVT::v2f64 || VT =3D=3D MVT::v2i64)
+      return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
   }
=20
   if (isPSHUFHWMask(M, VT))
     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
-                                X86::getShufflePSHUFHWImmediate(SVOp),
+                                getShufflePSHUFHWImmediate(SVOp),
                                 DAG);
=20
   if (isPSHUFLWMask(M, VT))
     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
-                                X86::getShufflePSHUFLWImmediate(SVOp),
+                                getShufflePSHUFLWImmediate(SVOp),
                                 DAG);
=20
-  if (isSHUFPMask(M, VT))
-    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
-                                X86::getShuffleSHUFImmediate(SVOp), DAG);
-
-  if (X86::isUNPCKL_v_undef_Mask(SVOp))
-    return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
-  if (X86::isUNPCKH_v_undef_Mask(SVOp))
-    return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
+  if (isSHUFPMask(M, VT, HasAVX))
+    return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
+                                getShuffleSHUFImmediate(SVOp), DAG);
+
+  if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
+    return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
+  if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
+    return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Generate target specific nodes for 128 or 256-bit shuffles only
@@ -6787,33 +6607,26 @@
   //
=20
   // Handle VMOVDDUPY permutations
-  if (isMOVDDUPYMask(SVOp, Subtarget))
+  if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
=20
-  // Handle VPERMILPS* permutations
-  if (isVPERMILPSMask(M, VT, Subtarget))
-    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
-                                getShuffleVPERMILPSImmediate(SVOp), DAG);
-
-  // Handle VPERMILPD* permutations
-  if (isVPERMILPDMask(M, VT, Subtarget))
-    return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
-                                getShuffleVPERMILPDImmediate(SVOp), DAG);
-
-  // Handle VPERM2F128 permutations
-  if (isVPERM2F128Mask(M, VT, Subtarget))
-    return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
-                                getShuffleVPERM2F128Immediate(SVOp), DAG);
-
-  // Handle VSHUFPSY permutations
-  if (isVSHUFPSYMask(M, VT, Subtarget))
-    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
-                                getShuffleVSHUFPSYImmediate(SVOp), DAG);
-
-  // Handle VSHUFPDY permutations
-  if (isVSHUFPDYMask(M, VT, Subtarget))
-    return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
-                                getShuffleVSHUFPDYImmediate(SVOp), DAG);
+  // Handle VPERMILPS/D* permutations
+  if (isVPERMILPMask(M, VT, HasAVX)) {
+    if (HasAVX2 && VT =3D=3D MVT::v8i32)
+      return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
+                                  getShuffleSHUFImmediate(SVOp), DAG);
+    return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
+                                getShuffleSHUFImmediate(SVOp), DAG);
+  }
+
+  // Handle VPERM2F128/VPERM2I128 permutations
+  if (isVPERM2X128Mask(M, VT, HasAVX))
+    return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
+                                V2, getShuffleVPERM2X128Immediate(SVOp), D=
AG);
+
+  SDValue BlendOp =3D LowerVECTOR_SHUFFLEtoBlend(Op, Subtarget, DAG);
+  if (BlendOp.getNode())
+    return BlendOp;
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Since no target specific shuffle was selected for this generic one,
@@ -6896,8 +6709,8 @@
                                               Op.getOperand(0)),
                                               Op.getOperand(1));
     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
-  } else if (VT =3D=3D MVT::i32) {
-    // ExtractPS works with constant index.
+  } else if (VT =3D=3D MVT::i32 || VT =3D=3D MVT::i64) {
+    // ExtractPS/pextrq works with constant index.
     if (isa<ConstantSDNode>(Op.getOperand(1)))
       return Op;
   }
@@ -6933,7 +6746,7 @@
=20
   assert(Vec.getValueSizeInBits() <=3D 128 && "Unexpected vector length");
=20
-  if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
+  if (Subtarget->hasSSE41()) {
     SDValue Res =3D LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
     if (Res.getNode())
       return Res;
@@ -7036,7 +6849,8 @@
     // Create this as a scalar to vector..
     N1 =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
-  } else if (EltVT =3D=3D MVT::i32 && isa<ConstantSDNode>(N2)) {
+  } else if ((EltVT =3D=3D MVT::i32 || EltVT =3D=3D MVT::i64) &&=20
+             isa<ConstantSDNode>(N2)) {
     // PINSR* works with constant index.
     return Op;
   }
@@ -7074,7 +6888,7 @@
     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
   }
=20
-  if (Subtarget->hasSSE41() || Subtarget->hasAVX())
+  if (Subtarget->hasSSE41())
     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
=20
   if (EltVT =3D=3D MVT::i8)
@@ -7276,7 +7090,7 @@
   // load.
   if (isGlobalStubReference(OpFlag))
     Result =3D DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
-                         MachinePointerInfo::getGOT(), false, false, 0);
+                         MachinePointerInfo::getGOT(), false, false, false=
, 0);
=20
   return Result;
 }
@@ -7344,7 +7158,7 @@
   // load.
   if (isGlobalStubReference(OpFlags))
     Result =3D DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
-                         MachinePointerInfo::getGOT(), false, false, 0);
+                         MachinePointerInfo::getGOT(), false, false, false=
, 0);
=20
   // If there was a non-zero offset that we didn't fold, create an explicit
   // addition for it.
@@ -7423,7 +7237,8 @@
=20
   SDValue ThreadPointer =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
                                       DAG.getIntPtrConstant(0),
-                                      MachinePointerInfo(Ptr), false, fals=
e, 0);
+                                      MachinePointerInfo(Ptr),
+                                      false, false, false, 0);
=20
   unsigned char OperandFlags =3D 0;
   // Most TLS accesses are not RIP relative, even on x86-64.  One exceptio=
n is
@@ -7449,7 +7264,7 @@
=20
   if (model =3D=3D TLSModel::InitialExec)
     Offset =3D DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
-                         MachinePointerInfo::getGOT(), false, false, 0);
+                         MachinePointerInfo::getGOT(), false, false, false=
, 0);
=20
   // The address of the thread local variable is the add of the thread
   // pointer with the offset of the variable.
@@ -7471,8 +7286,7 @@
     if (const GlobalAlias *GA =3D dyn_cast<GlobalAlias>(GV))
       GV =3D GA->resolveAliasedGlobal(false);
=20
-    TLSModel::Model model
-      =3D getTLSModel(GV, getTargetMachine().getRelocationModel());
+    TLSModel::Model model =3D getTargetMachine().getTLSModel(GV);
=20
     switch (model) {
       case TLSModel::GeneralDynamic:
@@ -7529,19 +7343,77 @@
     unsigned Reg =3D Subtarget->is64Bit() ? X86::RAX : X86::EAX;
     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
                               Chain.getValue(1));
-  }
-
-  assert(false &&
-         "TLS not implemented for this target.");
-
-  llvm_unreachable("Unreachable");
-  return SDValue();
-}
-
-
-/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 va=
lues and
-/// take a 2 x i32 value to shift plus a shift amount.
-SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) =
const {
+  } else if (Subtarget->isTargetWindows()) {
+    // Just use the implicit TLS architecture
+    // Need to generate someting similar to:
+    //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStora=
ge
+    //                                  ; from TEB
+    //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
+    //   mov     rcx, qword [rdx+rcx*8]
+    //   mov     eax, .tls$:tlsvar
+    //   [rax+rcx] contains the address
+    // Windows 64bit: gs:0x58
+    // Windows 32bit: fs:__tls_array
+
+    // If GV is an alias then use the aliasee for determining
+    // thread-localness.
+    if (const GlobalAlias *GA =3D dyn_cast<GlobalAlias>(GV))
+      GV =3D GA->resolveAliasedGlobal(false);
+    DebugLoc dl =3D GA->getDebugLoc();
+    SDValue Chain =3D DAG.getEntryNode();
+
+    // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
+    // %gs:0x58 (64-bit).
+    Value *Ptr =3D Constant::getNullValue(Subtarget->is64Bit()
+                                        ? Type::getInt8PtrTy(*DAG.getConte=
xt(),
+                                                             256)
+                                        : Type::getInt32PtrTy(*DAG.getCont=
ext(),
+                                                              257));
+
+    SDValue ThreadPointer =3D DAG.getLoad(getPointerTy(), dl, Chain,
+                                        Subtarget->is64Bit()
+                                        ? DAG.getIntPtrConstant(0x58)
+                                        : DAG.getExternalSymbol("_tls_arra=
y",
+                                                                getPointer=
Ty()),
+                                        MachinePointerInfo(Ptr),
+                                        false, false, false, 0);
+
+    // Load the _tls_index variable
+    SDValue IDX =3D DAG.getExternalSymbol("_tls_index", getPointerTy());
+    if (Subtarget->is64Bit())
+      IDX =3D DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
+                           IDX, MachinePointerInfo(), MVT::i32,
+                           false, false, 0);
+    else
+      IDX =3D DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerIn=
fo(),
+                        false, false, false, 0);
+
+    SDValue Scale =3D DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
+		                            getPointerTy());
+    IDX =3D DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
+
+    SDValue res =3D DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointe=
r, IDX);
+    res =3D DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo=
(),
+                      false, false, false, 0);
+
+    // Get the offset of start of .tls section
+    SDValue TGA =3D DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
+                                             GA->getValueType(0),
+                                             GA->getOffset(), X86II::MO_SE=
CREL);
+    SDValue Offset =3D DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TG=
A);
+
+    // The address of the thread local variable is the add of the thread
+    // pointer with the offset of the variable.
+    return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
+  }
+
+  llvm_unreachable("TLS not implemented for this target.");
+}
+
+
+/// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 va=
lues
+/// and take a 2 x i32 value to shift plus a shift amount.
+SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) =
const{
   assert(Op.getNumOperands() =3D=3D 3 && "Not a double-shift!");
   EVT VT =3D Op.getValueType();
   unsigned VTBits =3D VT.getSizeInBits();
@@ -7673,7 +7545,7 @@
                                     Op.getValueType(), MMO);
     Result =3D DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
                          MachinePointerInfo::getFixedStack(SSFI),
-                         false, false, 0);
+                         false, false, false, 0);
   }
=20
   return Result;
@@ -7682,85 +7554,65 @@
 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
                                                SelectionDAG &DAG) const {
-  // This algorithm is not obvious. Here it is in C code, more or less:
+  // This algorithm is not obvious. Here it is what we're trying to output:
   /*
-    double uint64_to_double( uint32_t hi, uint32_t lo ) {
-      static const __m128i exp =3D { 0x4330000045300000ULL, 0 };
-      static const __m128d bias =3D { 0x1.0p84, 0x1.0p52 };
-
-      // Copy ints to xmm registers.
-      __m128i xh =3D _mm_cvtsi32_si128( hi );
-      __m128i xl =3D _mm_cvtsi32_si128( lo );
-
-      // Combine into low half of a single xmm register.
-      __m128i x =3D _mm_unpacklo_epi32( xh, xl );
-      __m128d d;
-      double sd;
-
-      // Merge in appropriate exponents to give the integer bits the right
-      // magnitude.
-      x =3D _mm_unpacklo_epi32( x, exp );
-
-      // Subtract away the biases to deal with the IEEE-754 double precisi=
on
-      // implicit 1.
-      d =3D _mm_sub_pd( (__m128d) x, bias );
-
-      // All conversions up to here are exact. The correctly rounded resul=
t is
-      // calculated using the current rounding mode using the following
-      // horizontal add.
-      d =3D _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
-      _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM=
, this
-                                // store doesn't really need to be here (e=
xcept
-                                // maybe to zero the other double)
-      return sd;
-    }
+     movq       %rax,  %xmm0
+     punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U=
, 0U }
+     subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0=
p32 }
+     #ifdef __SSE3__
+       haddpd   %xmm0, %xmm0         =20
+     #else
+       pshufd   $0x4e, %xmm0, %xmm1=20
+       addpd    %xmm1, %xmm0
+     #endif
   */
=20
   DebugLoc dl =3D Op.getDebugLoc();
   LLVMContext *Context =3D DAG.getContext();
=20
   // Build some magic constants.
-  std::vector<Constant*> CV0;
-  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
-  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
-  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
-  CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
-  Constant *C0 =3D ConstantVector::get(CV0);
+  const uint32_t CV0[] =3D { 0x43300000, 0x45300000, 0, 0 };
+  Constant *C0 =3D ConstantDataVector::get(*Context, CV0);
   SDValue CPIdx0 =3D DAG.getConstantPool(C0, getPointerTy(), 16);
=20
-  std::vector<Constant*> CV1;
+  SmallVector<Constant*,2> CV1;
   CV1.push_back(
-    ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
+        ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL)=
)));
   CV1.push_back(
-    ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
+        ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL)=
)));
   Constant *C1 =3D ConstantVector::get(CV1);
   SDValue CPIdx1 =3D DAG.getConstantPool(C1, getPointerTy(), 16);
=20
-  SDValue XR1 =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
-                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
-                                        Op.getOperand(0),
-                                        DAG.getIntPtrConstant(1)));
-  SDValue XR2 =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
-                            DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
-                                        Op.getOperand(0),
-                                        DAG.getIntPtrConstant(0)));
-  SDValue Unpck1 =3D getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
+  // Load the 64-bit value into an XMM register.
+  SDValue XR1 =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
+                            Op.getOperand(0));
   SDValue CLod0 =3D DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
                               MachinePointerInfo::getConstantPool(),
-                              false, false, 16);
-  SDValue Unpck2 =3D getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
-  SDValue XR2F =3D DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
+                              false, false, false, 16);
+  SDValue Unpck1 =3D getUnpackl(DAG, dl, MVT::v4i32,
+                              DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR=
1),
+                              CLod0);
+
   SDValue CLod1 =3D DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
                               MachinePointerInfo::getConstantPool(),
-                              false, false, 16);
+                              false, false, false, 16);
+  SDValue XR2F =3D DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
   SDValue Sub =3D DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
-
-  // Add the halves; easiest way is to swap them into another reg first.
-  int ShufMask[2] =3D { 1, -1 };
-  SDValue Shuf =3D DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
-                                      DAG.getUNDEF(MVT::v2f64), ShufMask);
-  SDValue Add =3D DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
-  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
+  SDValue Result;
+
+  if (Subtarget->hasSSE3()) {
+    // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd=
'.
+    Result =3D DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
+  } else {
+    SDValue S2F =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
+    SDValue Shuffle =3D getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i3=
2,
+                                           S2F, 0x4E, DAG);
+    Result =3D DAG.getNode(ISD::FADD, dl, MVT::v2f64,
+                         DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle=
),
+                         Sub);
+  }
+
+  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
                      DAG.getIntPtrConstant(0));
 }
=20
@@ -7777,8 +7629,7 @@
                              Op.getOperand(0));
=20
   // Zero out the upper parts of the register.
-  Load =3D getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt=
(),
-                                     DAG);
+  Load =3D getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
=20
   Load =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
@@ -7830,6 +7681,9 @@
     return LowerUINT_TO_FP_i64(Op, DAG);
   else if (SrcVT =3D=3D MVT::i32 && X86ScalarSSEf64)
     return LowerUINT_TO_FP_i32(Op, DAG);
+  else if (Subtarget->is64Bit() &&
+           SrcVT =3D=3D MVT::i64 && DstVT =3D=3D MVT::f32)
+    return SDValue();
=20
   // Make a 64-bit buffer, and use it to build an FILD.
   SDValue StackSlot =3D DAG.CreateStackTemporary(MVT::i64);
@@ -7849,7 +7703,7 @@
=20
   assert(SrcVT =3D=3D MVT::i64 && "Unexpected type in UINT_TO_FP");
   SDValue Store =3D DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
-                                StackSlot, MachinePointerInfo(),
+                               StackSlot, MachinePointerInfo(),
                                false, false, 0);
   // For i64 source, we need to add the appropriate power of 2 if the input
   // was negative.  This is the same as the optimization in
@@ -7897,19 +7751,19 @@
 }
=20
 std::pair<SDValue,SDValue> X86TargetLowering::
-FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
+FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsRepla=
ce) const {
   DebugLoc DL =3D Op.getDebugLoc();
=20
   EVT DstTy =3D Op.getValueType();
=20
-  if (!IsSigned) {
+  if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
     assert(DstTy =3D=3D MVT::i32 && "Unexpected FP_TO_UINT");
     DstTy =3D MVT::i64;
   }
=20
   assert(DstTy.getSimpleVT() <=3D MVT::i64 &&
          DstTy.getSimpleVT() >=3D MVT::i16 &&
-         "Unknown FP_TO_SINT to lower!");
+         "Unknown FP_TO_INT to lower!");
=20
   // These are really Legal.
   if (DstTy =3D=3D MVT::i32 &&
@@ -7920,26 +7774,29 @@
       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
     return std::make_pair(SDValue(), SDValue());
=20
-  // We lower FP->sint64 into FISTP64, followed by a load, all to a tempor=
ary
-  // stack slot.
+  // We lower FP->int64 either into FISTP64 followed by a load from a temp=
orary
+  // stack slot, or into the FTOL runtime function.
   MachineFunction &MF =3D DAG.getMachineFunction();
   unsigned MemSize =3D DstTy.getSizeInBits()/8;
   int SSFI =3D MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, fals=
e);
   SDValue StackSlot =3D DAG.getFrameIndex(SSFI, getPointerTy());
=20
-
-
   unsigned Opc;
-  switch (DstTy.getSimpleVT().SimpleTy) {
-  default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
-  case MVT::i16: Opc =3D X86ISD::FP_TO_INT16_IN_MEM; break;
-  case MVT::i32: Opc =3D X86ISD::FP_TO_INT32_IN_MEM; break;
-  case MVT::i64: Opc =3D X86ISD::FP_TO_INT64_IN_MEM; break;
-  }
+  if (!IsSigned && isIntegerTypeFTOL(DstTy))
+    Opc =3D X86ISD::WIN_FTOL;
+  else
+    switch (DstTy.getSimpleVT().SimpleTy) {
+    default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
+    case MVT::i16: Opc =3D X86ISD::FP_TO_INT16_IN_MEM; break;
+    case MVT::i32: Opc =3D X86ISD::FP_TO_INT32_IN_MEM; break;
+    case MVT::i64: Opc =3D X86ISD::FP_TO_INT64_IN_MEM; break;
+    }
=20
   SDValue Chain =3D DAG.getEntryNode();
   SDValue Value =3D Op.getOperand(0);
   EVT TheVT =3D Op.getOperand(0).getValueType();
+  // FIXME This causes a redundant load/store if the SSE-class value is al=
ready
+  // in memory, such as if it is on the callstack.
   if (isScalarFPTypeInSSEReg(TheVT)) {
     assert(DstTy =3D=3D MVT::i64 && "Invalid FP_TO_SINT to lower!");
     Chain =3D DAG.getStore(Chain, DL, Value, StackSlot,
@@ -7964,12 +7821,26 @@
     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
                             MachineMemOperand::MOStore, MemSize, MemSize);
=20
-  // Build the FP_TO_INT*_IN_MEM
-  SDValue Ops[] =3D { Chain, Value, StackSlot };
-  SDValue FIST =3D DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Oth=
er),
-                                         Ops, 3, DstTy, MMO);
-
-  return std::make_pair(FIST, StackSlot);
+  if (Opc !=3D X86ISD::WIN_FTOL) {
+    // Build the FP_TO_INT*_IN_MEM
+    SDValue Ops[] =3D { Chain, Value, StackSlot };
+    SDValue FIST =3D DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::O=
ther),
+                                           Ops, 3, DstTy, MMO);
+    return std::make_pair(FIST, StackSlot);
+  } else {
+    SDValue ftol =3D DAG.getNode(X86ISD::WIN_FTOL, DL,
+      DAG.getVTList(MVT::Other, MVT::Glue),
+      Chain, Value);
+    SDValue eax =3D DAG.getCopyFromReg(ftol, DL, X86::EAX,
+      MVT::i32, ftol.getValue(1));
+    SDValue edx =3D DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
+      MVT::i32, eax.getValue(2));
+    SDValue Ops[] =3D { eax, edx };
+    SDValue pair =3D IsReplace
+      ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
+      : DAG.getMergeValues(Ops, 2, DL);
+    return std::make_pair(pair, SDValue());
+  }
 }
=20
 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
@@ -7977,25 +7848,37 @@
   if (Op.getValueType().isVector())
     return SDValue();
=20
-  std::pair<SDValue,SDValue> Vals =3D FP_TO_INTHelper(Op, DAG, true);
+  std::pair<SDValue,SDValue> Vals =3D FP_TO_INTHelper(Op, DAG,
+    /*IsSigned=3D*/ true, /*IsReplace=3D*/ false);
   SDValue FIST =3D Vals.first, StackSlot =3D Vals.second;
   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
   if (FIST.getNode() =3D=3D 0) return Op;
=20
-  // Load the result.
-  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
-                     FIST, StackSlot, MachinePointerInfo(), false, false, =
0);
+  if (StackSlot.getNode())
+    // Load the result.
+    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
+                       FIST, StackSlot, MachinePointerInfo(),
+                       false, false, false, 0);
+  else
+    // The node is the result.
+    return FIST;
 }
=20
 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
                                            SelectionDAG &DAG) const {
-  std::pair<SDValue,SDValue> Vals =3D FP_TO_INTHelper(Op, DAG, false);
+  std::pair<SDValue,SDValue> Vals =3D FP_TO_INTHelper(Op, DAG,
+    /*IsSigned=3D*/ false, /*IsReplace=3D*/ false);
   SDValue FIST =3D Vals.first, StackSlot =3D Vals.second;
   assert(FIST.getNode() && "Unexpected failure");
=20
-  // Load the result.
-  return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
-                     FIST, StackSlot, MachinePointerInfo(), false, false, =
0);
+  if (StackSlot.getNode())
+    // Load the result.
+    return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
+                       FIST, StackSlot, MachinePointerInfo(),
+                       false, false, false, 0);
+  else
+    // The node is the result.
+    return FIST;
 }
=20
 SDValue X86TargetLowering::LowerFABS(SDValue Op,
@@ -8006,23 +7889,18 @@
   EVT EltVT =3D VT;
   if (VT.isVector())
     EltVT =3D VT.getVectorElementType();
-  std::vector<Constant*> CV;
+  Constant *C;
   if (EltVT =3D=3D MVT::f64) {
-    Constant *C =3D ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << =
63))));
-    CV.push_back(C);
-    CV.push_back(C);
+    C =3D ConstantVector::getSplat(2,=20
+                ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))=
)));
   } else {
-    Constant *C =3D ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31=
))));
-    CV.push_back(C);
-    CV.push_back(C);
-    CV.push_back(C);
-    CV.push_back(C);
-  }
-  Constant *C =3D ConstantVector::get(CV);
+    C =3D ConstantVector::getSplat(4,
+               ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
+  }
   SDValue CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
   SDValue Mask =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
                              MachinePointerInfo::getConstantPool(),
-                             false, false, 16);
+                             false, false, false, 16);
   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
 }
=20
@@ -8031,31 +7909,28 @@
   DebugLoc dl =3D Op.getDebugLoc();
   EVT VT =3D Op.getValueType();
   EVT EltVT =3D VT;
-  if (VT.isVector())
+  unsigned NumElts =3D VT =3D=3D MVT::f64 ? 2 : 4;
+  if (VT.isVector()) {
     EltVT =3D VT.getVectorElementType();
-  std::vector<Constant*> CV;
-  if (EltVT =3D=3D MVT::f64) {
-    Constant *C =3D ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63=
)));
-    CV.push_back(C);
-    CV.push_back(C);
-  } else {
-    Constant *C =3D ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))=
);
-    CV.push_back(C);
-    CV.push_back(C);
-    CV.push_back(C);
-    CV.push_back(C);
-  }
-  Constant *C =3D ConstantVector::get(CV);
+    NumElts =3D VT.getVectorNumElements();
+  }
+  Constant *C;
+  if (EltVT =3D=3D MVT::f64)
+    C =3D ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
+  else
+    C =3D ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
+  C =3D ConstantVector::getSplat(NumElts, C);
   SDValue CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
   SDValue Mask =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
                              MachinePointerInfo::getConstantPool(),
-                             false, false, 16);
+                             false, false, false, 16);
   if (VT.isVector()) {
+    MVT XORVT =3D VT.getSizeInBits() =3D=3D 128 ? MVT::v2i64 : MVT::v4i64;
     return DAG.getNode(ISD::BITCAST, dl, VT,
-                       DAG.getNode(ISD::XOR, dl, MVT::v2i64,
-                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
+                       DAG.getNode(ISD::XOR, dl, XORVT,
+                    DAG.getNode(ISD::BITCAST, dl, XORVT,
                                 Op.getOperand(0)),
-                    DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
+                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
   } else {
     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
   }
@@ -8084,7 +7959,7 @@
   // type, and that won't be f80 since that is not custom lowered.
=20
   // First get the sign bit of second operand.
-  std::vector<Constant*> CV;
+  SmallVector<Constant*,4> CV;
   if (SrcVT =3D=3D MVT::f64) {
     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)))=
);
     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
@@ -8098,7 +7973,7 @@
   SDValue CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
   SDValue Mask1 =3D DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
                               MachinePointerInfo::getConstantPool(),
-                              false, false, 16);
+                              false, false, false, 16);
   SDValue SignBit =3D DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
=20
   // Shift sign bit right or left if the two operands have different types.
@@ -8127,7 +8002,7 @@
   CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
   SDValue Mask2 =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
                               MachinePointerInfo::getConstantPool(),
-                              false, false, 16);
+                              false, false, false, 16);
   SDValue Val =3D DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
=20
   // Or the value with the sign bit.
@@ -8191,8 +8066,10 @@
     // climbing the DAG back to the root, and it doesn't seem to be worth =
the
     // effort.
     for (SDNode::use_iterator UI =3D Op.getNode()->use_begin(),
-           UE =3D Op.getNode()->use_end(); UI !=3D UE; ++UI)
-      if (UI->getOpcode() !=3D ISD::CopyToReg && UI->getOpcode() !=3D ISD:=
:SETCC)
+         UE =3D Op.getNode()->use_end(); UI !=3D UE; ++UI)
+      if (UI->getOpcode() !=3D ISD::CopyToReg &&
+          UI->getOpcode() !=3D ISD::SETCC &&
+          UI->getOpcode() !=3D ISD::STORE)
         goto default_case;
=20
     if (ConstantSDNode *C =3D
@@ -8325,8 +8202,8 @@
         unsigned BitWidth =3D Op0.getValueSizeInBits();
         unsigned AndBitWidth =3D And.getValueSizeInBits();
         if (BitWidth > AndBitWidth) {
-          APInt Mask =3D APInt::getAllOnesValue(BitWidth), Zeros, Ones;
-          DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
+          APInt Zeros, Ones;
+          DAG.ComputeMaskedBits(Op0, Zeros, Ones);
           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
             return SDValue();
         }
@@ -8335,11 +8212,19 @@
       }
   } else if (Op1.getOpcode() =3D=3D ISD::Constant) {
     ConstantSDNode *AndRHS =3D cast<ConstantSDNode>(Op1);
+    uint64_t AndRHSVal =3D AndRHS->getZExtValue();
     SDValue AndLHS =3D Op0;
-    if (AndRHS->getZExtValue() =3D=3D 1 && AndLHS.getOpcode() =3D=3D ISD::=
SRL) {
+
+    if (AndRHSVal =3D=3D 1 && AndLHS.getOpcode() =3D=3D ISD::SRL) {
       LHS =3D AndLHS.getOperand(0);
       RHS =3D AndLHS.getOperand(1);
     }
+
+    // Use BT if the immediate can't be encoded in a TEST instruction.
+    if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
+      LHS =3D AndLHS;
+      RHS =3D DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
+    }
   }
=20
   if (LHS.getNode()) {
@@ -8466,9 +8351,8 @@
   if (isFP) {
     unsigned SSECC =3D 8;
     EVT EltVT =3D Op0.getValueType().getVectorElementType();
-    assert(EltVT =3D=3D MVT::f32 || EltVT =3D=3D MVT::f64);
-
-    unsigned Opc =3D EltVT =3D=3D MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
+    assert(EltVT =3D=3D MVT::f32 || EltVT =3D=3D MVT::f64); (void)EltVT;
+
     bool Swap =3D false;
=20
     // SSE Condition code mapping:
@@ -8508,61 +8392,57 @@
     if (SSECC =3D=3D 8) {
       if (SetCCOpcode =3D=3D ISD::SETUEQ) {
         SDValue UNORD, EQ;
-        UNORD =3D DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MV=
T::i8));
-        EQ =3D DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::=
i8));
+        UNORD =3D DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
+                            DAG.getConstant(3, MVT::i8));
+        EQ =3D DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
+                         DAG.getConstant(0, MVT::i8));
         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
-      }
-      else if (SetCCOpcode =3D=3D ISD::SETONE) {
+      } else if (SetCCOpcode =3D=3D ISD::SETONE) {
         SDValue ORD, NEQ;
-        ORD =3D DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT:=
:i8));
-        NEQ =3D DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT:=
:i8));
+        ORD =3D DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
+                          DAG.getConstant(7, MVT::i8));
+        NEQ =3D DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
+                          DAG.getConstant(4, MVT::i8));
         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
       }
       llvm_unreachable("Illegal FP comparison");
     }
     // Handle all other FP comparisons here.
-    return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::=
i8));
+    return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
+                       DAG.getConstant(SSECC, MVT::i8));
   }
=20
   // Break 256-bit integer vector compare into smaller ones.
-  if (!isFP && VT.getSizeInBits() =3D=3D 256)
+  if (VT.getSizeInBits() =3D=3D 256 && !Subtarget->hasAVX2())
     return Lower256IntVSETCC(Op, DAG);
=20
   // We are handling one of the integer comparisons here.  Since SSE only =
has
   // GT and EQ comparisons for integer, swapping operands and multiple
   // operations may be required for some comparisons.
-  unsigned Opc =3D 0, EQOpc =3D 0, GTOpc =3D 0;
+  unsigned Opc =3D 0;
   bool Swap =3D false, Invert =3D false, FlipSigns =3D false;
=20
-  switch (VT.getSimpleVT().SimpleTy) {
-  default: break;
-  case MVT::v16i8: EQOpc =3D X86ISD::PCMPEQB; GTOpc =3D X86ISD::PCMPGTB; b=
reak;
-  case MVT::v8i16: EQOpc =3D X86ISD::PCMPEQW; GTOpc =3D X86ISD::PCMPGTW; b=
reak;
-  case MVT::v4i32: EQOpc =3D X86ISD::PCMPEQD; GTOpc =3D X86ISD::PCMPGTD; b=
reak;
-  case MVT::v2i64: EQOpc =3D X86ISD::PCMPEQQ; GTOpc =3D X86ISD::PCMPGTQ; b=
reak;
-  }
-
   switch (SetCCOpcode) {
   default: break;
   case ISD::SETNE:  Invert =3D true;
-  case ISD::SETEQ:  Opc =3D EQOpc; break;
+  case ISD::SETEQ:  Opc =3D X86ISD::PCMPEQ; break;
   case ISD::SETLT:  Swap =3D true;
-  case ISD::SETGT:  Opc =3D GTOpc; break;
+  case ISD::SETGT:  Opc =3D X86ISD::PCMPGT; break;
   case ISD::SETGE:  Swap =3D true;
-  case ISD::SETLE:  Opc =3D GTOpc; Invert =3D true; break;
+  case ISD::SETLE:  Opc =3D X86ISD::PCMPGT; Invert =3D true; break;
   case ISD::SETULT: Swap =3D true;
-  case ISD::SETUGT: Opc =3D GTOpc; FlipSigns =3D true; break;
+  case ISD::SETUGT: Opc =3D X86ISD::PCMPGT; FlipSigns =3D true; break;
   case ISD::SETUGE: Swap =3D true;
-  case ISD::SETULE: Opc =3D GTOpc; FlipSigns =3D true; Invert =3D true; br=
eak;
+  case ISD::SETULE: Opc =3D X86ISD::PCMPGT; FlipSigns =3D true; Invert =3D=
 true; break;
   }
   if (Swap)
     std::swap(Op0, Op1);
=20
   // Check that the operation in question is available (most are plain SSE=
2,
   // but PCMPGTQ and PCMPEQQ have different requirements).
-  if (Opc =3D=3D X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->=
hasAVX())
+  if (Opc =3D=3D X86ISD::PCMPGT && VT =3D=3D MVT::v2i64 && !Subtarget->has=
SSE42())
     return SDValue();
-  if (Opc =3D=3D X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->=
hasAVX())
+  if (Opc =3D=3D X86ISD::PCMPEQ && VT =3D=3D MVT::v2i64 && !Subtarget->has=
SSE41())
     return SDValue();
=20
   // Since SSE has no unsigned integer comparisons, we need to flip  the s=
ign
@@ -8679,8 +8559,9 @@
=20
   // If condition flag is set by a X86ISD::CMP, then use it as the conditi=
on
   // setting operand in place of the X86ISD::SETCC.
-  if (Cond.getOpcode() =3D=3D X86ISD::SETCC ||
-      Cond.getOpcode() =3D=3D X86ISD::SETCC_CARRY) {
+  unsigned CondOpcode =3D Cond.getOpcode();
+  if (CondOpcode =3D=3D X86ISD::SETCC ||
+      CondOpcode =3D=3D X86ISD::SETCC_CARRY) {
     CC =3D Cond.getOperand(0);
=20
     SDValue Cmp =3D Cond.getOperand(1);
@@ -8697,6 +8578,39 @@
       Cond =3D Cmp;
       addTest =3D false;
     }
+  } else if (CondOpcode =3D=3D ISD::USUBO || CondOpcode =3D=3D ISD::SSUBO =
||
+             CondOpcode =3D=3D ISD::UADDO || CondOpcode =3D=3D ISD::SADDO =
||
+             ((CondOpcode =3D=3D ISD::UMULO || CondOpcode =3D=3D ISD::SMUL=
O) &&
+              Cond.getOperand(0).getValueType() !=3D MVT::i8)) {
+    SDValue LHS =3D Cond.getOperand(0);
+    SDValue RHS =3D Cond.getOperand(1);
+    unsigned X86Opcode;
+    unsigned X86Cond;
+    SDVTList VTs;
+    switch (CondOpcode) {
+    case ISD::UADDO: X86Opcode =3D X86ISD::ADD; X86Cond =3D X86::COND_B; b=
reak;
+    case ISD::SADDO: X86Opcode =3D X86ISD::ADD; X86Cond =3D X86::COND_O; b=
reak;
+    case ISD::USUBO: X86Opcode =3D X86ISD::SUB; X86Cond =3D X86::COND_B; b=
reak;
+    case ISD::SSUBO: X86Opcode =3D X86ISD::SUB; X86Cond =3D X86::COND_O; b=
reak;
+    case ISD::UMULO: X86Opcode =3D X86ISD::UMUL; X86Cond =3D X86::COND_O; =
break;
+    case ISD::SMULO: X86Opcode =3D X86ISD::SMUL; X86Cond =3D X86::COND_O; =
break;
+    default: llvm_unreachable("unexpected overflowing operator");
+    }
+    if (CondOpcode =3D=3D ISD::UMULO)
+      VTs =3D DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
+                          MVT::i32);
+    else
+      VTs =3D DAG.getVTList(LHS.getValueType(), MVT::i32);
+
+    SDValue X86Op =3D DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
+
+    if (CondOpcode =3D=3D ISD::UMULO)
+      Cond =3D X86Op.getValue(2);
+    else
+      Cond =3D X86Op.getValue(1);
+
+    CC =3D DAG.getConstant(X86Cond, MVT::i8);
+    addTest =3D false;
   }
=20
   if (addTest) {
@@ -8778,11 +8692,27 @@
   SDValue Dest  =3D Op.getOperand(2);
   DebugLoc dl =3D Op.getDebugLoc();
   SDValue CC;
+  bool Inverted =3D false;
=20
   if (Cond.getOpcode() =3D=3D ISD::SETCC) {
-    SDValue NewCond =3D LowerSETCC(Cond, DAG);
-    if (NewCond.getNode())
-      Cond =3D NewCond;
+    // Check for setcc([su]{add,sub,mul}o =3D=3D 0).
+    if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() =3D=3D ISD::SETEQ =
&&
+        isa<ConstantSDNode>(Cond.getOperand(1)) &&
+        cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
+        Cond.getOperand(0).getResNo() =3D=3D 1 &&
+        (Cond.getOperand(0).getOpcode() =3D=3D ISD::SADDO ||
+         Cond.getOperand(0).getOpcode() =3D=3D ISD::UADDO ||
+         Cond.getOperand(0).getOpcode() =3D=3D ISD::SSUBO ||
+         Cond.getOperand(0).getOpcode() =3D=3D ISD::USUBO ||
+         Cond.getOperand(0).getOpcode() =3D=3D ISD::SMULO ||
+         Cond.getOperand(0).getOpcode() =3D=3D ISD::UMULO)) {
+      Inverted =3D true;
+      Cond =3D Cond.getOperand(0);
+    } else {
+      SDValue NewCond =3D LowerSETCC(Cond, DAG);
+      if (NewCond.getNode())
+        Cond =3D NewCond;
+    }
   }
 #if 0
   // FIXME: LowerXALUO doesn't handle these!!
@@ -8803,8 +8733,9 @@
=20
   // If condition flag is set by a X86ISD::CMP, then use it as the conditi=
on
   // setting operand in place of the X86ISD::SETCC.
-  if (Cond.getOpcode() =3D=3D X86ISD::SETCC ||
-      Cond.getOpcode() =3D=3D X86ISD::SETCC_CARRY) {
+  unsigned CondOpcode =3D Cond.getOpcode();
+  if (CondOpcode =3D=3D X86ISD::SETCC ||
+      CondOpcode =3D=3D X86ISD::SETCC_CARRY) {
     CC =3D Cond.getOperand(0);
=20
     SDValue Cmp =3D Cond.getOperand(1);
@@ -8825,6 +8756,43 @@
         break;
       }
     }
+  }
+  CondOpcode =3D Cond.getOpcode();
+  if (CondOpcode =3D=3D ISD::UADDO || CondOpcode =3D=3D ISD::SADDO ||
+      CondOpcode =3D=3D ISD::USUBO || CondOpcode =3D=3D ISD::SSUBO ||
+      ((CondOpcode =3D=3D ISD::UMULO || CondOpcode =3D=3D ISD::SMULO) &&
+       Cond.getOperand(0).getValueType() !=3D MVT::i8)) {
+    SDValue LHS =3D Cond.getOperand(0);
+    SDValue RHS =3D Cond.getOperand(1);
+    unsigned X86Opcode;
+    unsigned X86Cond;
+    SDVTList VTs;
+    switch (CondOpcode) {
+    case ISD::UADDO: X86Opcode =3D X86ISD::ADD; X86Cond =3D X86::COND_B; b=
reak;
+    case ISD::SADDO: X86Opcode =3D X86ISD::ADD; X86Cond =3D X86::COND_O; b=
reak;
+    case ISD::USUBO: X86Opcode =3D X86ISD::SUB; X86Cond =3D X86::COND_B; b=
reak;
+    case ISD::SSUBO: X86Opcode =3D X86ISD::SUB; X86Cond =3D X86::COND_O; b=
reak;
+    case ISD::UMULO: X86Opcode =3D X86ISD::UMUL; X86Cond =3D X86::COND_O; =
break;
+    case ISD::SMULO: X86Opcode =3D X86ISD::SMUL; X86Cond =3D X86::COND_O; =
break;
+    default: llvm_unreachable("unexpected overflowing operator");
+    }
+    if (Inverted)
+      X86Cond =3D X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
+    if (CondOpcode =3D=3D ISD::UMULO)
+      VTs =3D DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
+                          MVT::i32);
+    else
+      VTs =3D DAG.getVTList(LHS.getValueType(), MVT::i32);
+
+    SDValue X86Op =3D DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
+
+    if (CondOpcode =3D=3D ISD::UMULO)
+      Cond =3D X86Op.getValue(2);
+    else
+      Cond =3D X86Op.getValue(1);
+
+    CC =3D DAG.getConstant(X86Cond, MVT::i8);
+    addTest =3D false;
   } else {
     unsigned CondOpc;
     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
@@ -8888,6 +8856,66 @@
       CC =3D DAG.getConstant(CCode, MVT::i8);
       Cond =3D Cond.getOperand(0).getOperand(1);
       addTest =3D false;
+    } else if (Cond.getOpcode() =3D=3D ISD::SETCC &&
+               cast<CondCodeSDNode>(Cond.getOperand(2))->get() =3D=3D ISD:=
:SETOEQ) {
+      // For FCMP_OEQ, we can emit
+      // two branches instead of an explicit AND instruction with a
+      // separate test. However, we only do this if this block doesn't
+      // have a fall-through edge, because this requires an explicit
+      // jmp when the condition is false.
+      if (Op.getNode()->hasOneUse()) {
+        SDNode *User =3D *Op.getNode()->use_begin();
+        // Look for an unconditional branch following this conditional bra=
nch.
+        // We need this because we need to reverse the successors in order
+        // to implement FCMP_OEQ.
+        if (User->getOpcode() =3D=3D ISD::BR) {
+          SDValue FalseBB =3D User->getOperand(1);
+          SDNode *NewBR =3D
+            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
+          assert(NewBR =3D=3D User);
+          (void)NewBR;
+          Dest =3D FalseBB;
+
+          SDValue Cmp =3D DAG.getNode(X86ISD::CMP, dl, MVT::i32,
+                                    Cond.getOperand(0), Cond.getOperand(1)=
);
+          CC =3D DAG.getConstant(X86::COND_NE, MVT::i8);
+          Chain =3D DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
+                              Chain, Dest, CC, Cmp);
+          CC =3D DAG.getConstant(X86::COND_P, MVT::i8);
+          Cond =3D Cmp;
+          addTest =3D false;
+        }
+      }
+    } else if (Cond.getOpcode() =3D=3D ISD::SETCC &&
+               cast<CondCodeSDNode>(Cond.getOperand(2))->get() =3D=3D ISD:=
:SETUNE) {
+      // For FCMP_UNE, we can emit
+      // two branches instead of an explicit AND instruction with a
+      // separate test. However, we only do this if this block doesn't
+      // have a fall-through edge, because this requires an explicit
+      // jmp when the condition is false.
+      if (Op.getNode()->hasOneUse()) {
+        SDNode *User =3D *Op.getNode()->use_begin();
+        // Look for an unconditional branch following this conditional bra=
nch.
+        // We need this because we need to reverse the successors in order
+        // to implement FCMP_UNE.
+        if (User->getOpcode() =3D=3D ISD::BR) {
+          SDValue FalseBB =3D User->getOperand(1);
+          SDNode *NewBR =3D
+            DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
+          assert(NewBR =3D=3D User);
+          (void)NewBR;
+
+          SDValue Cmp =3D DAG.getNode(X86ISD::CMP, dl, MVT::i32,
+                                    Cond.getOperand(0), Cond.getOperand(1)=
);
+          CC =3D DAG.getConstant(X86::COND_NE, MVT::i8);
+          Chain =3D DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
+                              Chain, Dest, CC, Cmp);
+          CC =3D DAG.getConstant(X86::COND_NP, MVT::i8);
+          Cond =3D Cmp;
+          addTest =3D false;
+          Dest =3D FalseBB;
+        }
+      }
     }
   }
=20
@@ -8926,7 +8954,7 @@
 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
                                            SelectionDAG &DAG) const {
   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
-          EnableSegmentedStacks) &&
+          getTargetMachine().Options.EnableSegmentedStacks) &&
          "This should be used only on Windows targets or when segmented st=
acks "
          "are being used");
   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
@@ -8940,7 +8968,7 @@
   bool Is64Bit =3D Subtarget->is64Bit();
   EVT SPTy =3D Is64Bit ? MVT::i64 : MVT::i32;
=20
-  if (EnableSegmentedStacks) {
+  if (getTargetMachine().Options.EnableSegmentedStacks) {
     MachineFunction &MF =3D DAG.getMachineFunction();
     MachineRegisterInfo &MRI =3D MF.getRegInfo();
=20
@@ -9076,10 +9104,10 @@
=20
   if (ArgMode =3D=3D 2) {
     // Sanity Check: Make sure using fp_offset makes sense.
-    assert(!UseSoftFloat &&
+    assert(!getTargetMachine().Options.UseSoftFloat &&
            !(DAG.getMachineFunction()
                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
-           Subtarget->hasXMM());
+           Subtarget->hasSSE1());
   }
=20
   // Insert VAARG_64 node into the DAG
@@ -9106,7 +9134,7 @@
                      Chain,
                      VAARG,
                      MachinePointerInfo(),
-                     false, false, 0);
+                     false, false, false, 0);
 }
=20
 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) cons=
t {
@@ -9125,6 +9153,43 @@
                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV=
));
 }
=20
+// getTargetVShiftNOde - Handle vector element shifts where the shift amou=
nt
+// may or may not be a constant. Takes immediate version of shift as input.
+static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
+                                   SDValue SrcOp, SDValue ShAmt,
+                                   SelectionDAG &DAG) {
+  assert(ShAmt.getValueType() =3D=3D MVT::i32 && "ShAmt is not i32");
+
+  if (isa<ConstantSDNode>(ShAmt)) {
+    switch (Opc) {
+      default: llvm_unreachable("Unknown target vector shift node");
+      case X86ISD::VSHLI:
+      case X86ISD::VSRLI:
+      case X86ISD::VSRAI:
+        return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
+    }
+  }
+
+  // Change opcode to non-immediate version
+  switch (Opc) {
+    default: llvm_unreachable("Unknown target vector shift node");
+    case X86ISD::VSHLI: Opc =3D X86ISD::VSHL; break;
+    case X86ISD::VSRLI: Opc =3D X86ISD::VSRL; break;
+    case X86ISD::VSRAI: Opc =3D X86ISD::VSRA; break;
+  }
+
+  // Need to build a vector containing shift amount
+  // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill wi=
th 0
+  SDValue ShOps[4];
+  ShOps[0] =3D ShAmt;
+  ShOps[1] =3D DAG.getConstant(0, MVT::i32);
+  ShOps[2] =3D DAG.getUNDEF(MVT::i32);
+  ShOps[3] =3D DAG.getUNDEF(MVT::i32);
+  ShAmt =3D DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
+  ShAmt =3D DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
+  return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
+}
+
 SDValue
 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) =
const {
   DebugLoc dl =3D Op.getDebugLoc();
@@ -9159,7 +9224,7 @@
     unsigned Opc =3D 0;
     ISD::CondCode CC =3D ISD::SETCC_INVALID;
     switch (IntNo) {
-    default: break;
+    default: llvm_unreachable("Impossible intrinsic");  // Can't reach her=
e.
     case Intrinsic::x86_sse_comieq_ss:
     case Intrinsic::x86_sse2_comieq_sd:
       Opc =3D X86ISD::COMI;
@@ -9231,7 +9296,201 @@
                                 DAG.getConstant(X86CC, MVT::i8), Cond);
     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
   }
+  // XOP comparison intrinsics
+  case Intrinsic::x86_xop_vpcomltb:
+  case Intrinsic::x86_xop_vpcomltw:
+  case Intrinsic::x86_xop_vpcomltd:
+  case Intrinsic::x86_xop_vpcomltq:
+  case Intrinsic::x86_xop_vpcomltub:
+  case Intrinsic::x86_xop_vpcomltuw:
+  case Intrinsic::x86_xop_vpcomltud:
+  case Intrinsic::x86_xop_vpcomltuq:
+  case Intrinsic::x86_xop_vpcomleb:
+  case Intrinsic::x86_xop_vpcomlew:
+  case Intrinsic::x86_xop_vpcomled:
+  case Intrinsic::x86_xop_vpcomleq:
+  case Intrinsic::x86_xop_vpcomleub:
+  case Intrinsic::x86_xop_vpcomleuw:
+  case Intrinsic::x86_xop_vpcomleud:
+  case Intrinsic::x86_xop_vpcomleuq:
+  case Intrinsic::x86_xop_vpcomgtb:
+  case Intrinsic::x86_xop_vpcomgtw:
+  case Intrinsic::x86_xop_vpcomgtd:
+  case Intrinsic::x86_xop_vpcomgtq:
+  case Intrinsic::x86_xop_vpcomgtub:
+  case Intrinsic::x86_xop_vpcomgtuw:
+  case Intrinsic::x86_xop_vpcomgtud:
+  case Intrinsic::x86_xop_vpcomgtuq:
+  case Intrinsic::x86_xop_vpcomgeb:
+  case Intrinsic::x86_xop_vpcomgew:
+  case Intrinsic::x86_xop_vpcomged:
+  case Intrinsic::x86_xop_vpcomgeq:
+  case Intrinsic::x86_xop_vpcomgeub:
+  case Intrinsic::x86_xop_vpcomgeuw:
+  case Intrinsic::x86_xop_vpcomgeud:
+  case Intrinsic::x86_xop_vpcomgeuq:
+  case Intrinsic::x86_xop_vpcomeqb:
+  case Intrinsic::x86_xop_vpcomeqw:
+  case Intrinsic::x86_xop_vpcomeqd:
+  case Intrinsic::x86_xop_vpcomeqq:
+  case Intrinsic::x86_xop_vpcomequb:
+  case Intrinsic::x86_xop_vpcomequw:
+  case Intrinsic::x86_xop_vpcomequd:
+  case Intrinsic::x86_xop_vpcomequq:
+  case Intrinsic::x86_xop_vpcomneb:
+  case Intrinsic::x86_xop_vpcomnew:
+  case Intrinsic::x86_xop_vpcomned:
+  case Intrinsic::x86_xop_vpcomneq:
+  case Intrinsic::x86_xop_vpcomneub:
+  case Intrinsic::x86_xop_vpcomneuw:
+  case Intrinsic::x86_xop_vpcomneud:
+  case Intrinsic::x86_xop_vpcomneuq:
+  case Intrinsic::x86_xop_vpcomfalseb:
+  case Intrinsic::x86_xop_vpcomfalsew:
+  case Intrinsic::x86_xop_vpcomfalsed:
+  case Intrinsic::x86_xop_vpcomfalseq:
+  case Intrinsic::x86_xop_vpcomfalseub:
+  case Intrinsic::x86_xop_vpcomfalseuw:
+  case Intrinsic::x86_xop_vpcomfalseud:
+  case Intrinsic::x86_xop_vpcomfalseuq:
+  case Intrinsic::x86_xop_vpcomtrueb:
+  case Intrinsic::x86_xop_vpcomtruew:
+  case Intrinsic::x86_xop_vpcomtrued:
+  case Intrinsic::x86_xop_vpcomtrueq:
+  case Intrinsic::x86_xop_vpcomtrueub:
+  case Intrinsic::x86_xop_vpcomtrueuw:
+  case Intrinsic::x86_xop_vpcomtrueud:
+  case Intrinsic::x86_xop_vpcomtrueuq: {
+    unsigned CC =3D 0;
+    unsigned Opc =3D 0;
+
+    switch (IntNo) {
+    default: llvm_unreachable("Impossible intrinsic");  // Can't reach her=
e.
+    case Intrinsic::x86_xop_vpcomltb:
+    case Intrinsic::x86_xop_vpcomltw:
+    case Intrinsic::x86_xop_vpcomltd:
+    case Intrinsic::x86_xop_vpcomltq:
+      CC =3D 0;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomltub:
+    case Intrinsic::x86_xop_vpcomltuw:
+    case Intrinsic::x86_xop_vpcomltud:
+    case Intrinsic::x86_xop_vpcomltuq:
+      CC =3D 0;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    case Intrinsic::x86_xop_vpcomleb:
+    case Intrinsic::x86_xop_vpcomlew:
+    case Intrinsic::x86_xop_vpcomled:
+    case Intrinsic::x86_xop_vpcomleq:
+      CC =3D 1;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomleub:
+    case Intrinsic::x86_xop_vpcomleuw:
+    case Intrinsic::x86_xop_vpcomleud:
+    case Intrinsic::x86_xop_vpcomleuq:
+      CC =3D 1;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    case Intrinsic::x86_xop_vpcomgtb:
+    case Intrinsic::x86_xop_vpcomgtw:
+    case Intrinsic::x86_xop_vpcomgtd:
+    case Intrinsic::x86_xop_vpcomgtq:
+      CC =3D 2;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomgtub:
+    case Intrinsic::x86_xop_vpcomgtuw:
+    case Intrinsic::x86_xop_vpcomgtud:
+    case Intrinsic::x86_xop_vpcomgtuq:
+      CC =3D 2;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    case Intrinsic::x86_xop_vpcomgeb:
+    case Intrinsic::x86_xop_vpcomgew:
+    case Intrinsic::x86_xop_vpcomged:
+    case Intrinsic::x86_xop_vpcomgeq:
+      CC =3D 3;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomgeub:
+    case Intrinsic::x86_xop_vpcomgeuw:
+    case Intrinsic::x86_xop_vpcomgeud:
+    case Intrinsic::x86_xop_vpcomgeuq:
+      CC =3D 3;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    case Intrinsic::x86_xop_vpcomeqb:
+    case Intrinsic::x86_xop_vpcomeqw:
+    case Intrinsic::x86_xop_vpcomeqd:
+    case Intrinsic::x86_xop_vpcomeqq:
+      CC =3D 4;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomequb:
+    case Intrinsic::x86_xop_vpcomequw:
+    case Intrinsic::x86_xop_vpcomequd:
+    case Intrinsic::x86_xop_vpcomequq:
+      CC =3D 4;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    case Intrinsic::x86_xop_vpcomneb:
+    case Intrinsic::x86_xop_vpcomnew:
+    case Intrinsic::x86_xop_vpcomned:
+    case Intrinsic::x86_xop_vpcomneq:
+      CC =3D 5;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomneub:
+    case Intrinsic::x86_xop_vpcomneuw:
+    case Intrinsic::x86_xop_vpcomneud:
+    case Intrinsic::x86_xop_vpcomneuq:
+      CC =3D 5;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    case Intrinsic::x86_xop_vpcomfalseb:
+    case Intrinsic::x86_xop_vpcomfalsew:
+    case Intrinsic::x86_xop_vpcomfalsed:
+    case Intrinsic::x86_xop_vpcomfalseq:
+      CC =3D 6;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomfalseub:
+    case Intrinsic::x86_xop_vpcomfalseuw:
+    case Intrinsic::x86_xop_vpcomfalseud:
+    case Intrinsic::x86_xop_vpcomfalseuq:
+      CC =3D 6;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    case Intrinsic::x86_xop_vpcomtrueb:
+    case Intrinsic::x86_xop_vpcomtruew:
+    case Intrinsic::x86_xop_vpcomtrued:
+    case Intrinsic::x86_xop_vpcomtrueq:
+      CC =3D 7;
+      Opc =3D X86ISD::VPCOM;
+      break;
+    case Intrinsic::x86_xop_vpcomtrueub:
+    case Intrinsic::x86_xop_vpcomtrueuw:
+    case Intrinsic::x86_xop_vpcomtrueud:
+    case Intrinsic::x86_xop_vpcomtrueuq:
+      CC =3D 7;
+      Opc =3D X86ISD::VPCOMU;
+      break;
+    }
+
+    SDValue LHS =3D Op.getOperand(1);
+    SDValue RHS =3D Op.getOperand(2);
+    return DAG.getNode(Opc, dl, Op.getValueType(), LHS, RHS,
+                       DAG.getConstant(CC, MVT::i8));
+  }
+
   // Arithmetic intrinsics.
+  case Intrinsic::x86_sse2_pmulu_dq:
+  case Intrinsic::x86_avx2_pmulu_dq:
+    return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
   case Intrinsic::x86_sse3_hadd_ps:
   case Intrinsic::x86_sse3_hadd_pd:
   case Intrinsic::x86_avx_hadd_ps_256:
@@ -9244,6 +9503,62 @@
   case Intrinsic::x86_avx_hsub_pd_256:
     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
                        Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_ssse3_phadd_w_128:
+  case Intrinsic::x86_ssse3_phadd_d_128:
+  case Intrinsic::x86_avx2_phadd_w:
+  case Intrinsic::x86_avx2_phadd_d:
+    return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_ssse3_phsub_w_128:
+  case Intrinsic::x86_ssse3_phsub_d_128:
+  case Intrinsic::x86_avx2_phsub_w:
+  case Intrinsic::x86_avx2_phsub_d:
+    return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_avx2_psllv_d:
+  case Intrinsic::x86_avx2_psllv_q:
+  case Intrinsic::x86_avx2_psllv_d_256:
+  case Intrinsic::x86_avx2_psllv_q_256:
+    return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
+                      Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_avx2_psrlv_d:
+  case Intrinsic::x86_avx2_psrlv_q:
+  case Intrinsic::x86_avx2_psrlv_d_256:
+  case Intrinsic::x86_avx2_psrlv_q_256:
+    return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
+                      Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_avx2_psrav_d:
+  case Intrinsic::x86_avx2_psrav_d_256:
+    return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
+                      Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_ssse3_pshuf_b_128:
+  case Intrinsic::x86_avx2_pshuf_b:
+    return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_ssse3_psign_b_128:
+  case Intrinsic::x86_ssse3_psign_w_128:
+  case Intrinsic::x86_ssse3_psign_d_128:
+  case Intrinsic::x86_avx2_psign_b:
+  case Intrinsic::x86_avx2_psign_w:
+  case Intrinsic::x86_avx2_psign_d:
+    return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_sse41_insertps:
+    return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3=
));
+  case Intrinsic::x86_avx_vperm2f128_ps_256:
+  case Intrinsic::x86_avx_vperm2f128_pd_256:
+  case Intrinsic::x86_avx_vperm2f128_si_256:
+  case Intrinsic::x86_avx2_vperm2i128:
+    return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2), Op.getOperand(3=
));
+  case Intrinsic::x86_avx_vpermil_ps:
+  case Intrinsic::x86_avx_vpermil_pd:
+  case Intrinsic::x86_avx_vpermil_ps_256:
+  case Intrinsic::x86_avx_vpermil_pd_256:
+    return DAG.getNode(X86ISD::VPERMILP, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
+
   // ptest and testp intrinsics. The intrinsic these come from are designe=
d to
   // return an integer value, not just an instruction so lower it to the p=
test
   // or testp pattern and a setcc for the result.
@@ -9310,16 +9625,53 @@
     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
   }
=20
-  // Fix vector shift instructions where the last operand is a non-immedia=
te
-  // i32 value.
+  // SSE/AVX shift intrinsics
+  case Intrinsic::x86_sse2_psll_w:
+  case Intrinsic::x86_sse2_psll_d:
+  case Intrinsic::x86_sse2_psll_q:
+  case Intrinsic::x86_avx2_psll_w:
+  case Intrinsic::x86_avx2_psll_d:
+  case Intrinsic::x86_avx2_psll_q:
+    return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_sse2_psrl_w:
+  case Intrinsic::x86_sse2_psrl_d:
+  case Intrinsic::x86_sse2_psrl_q:
+  case Intrinsic::x86_avx2_psrl_w:
+  case Intrinsic::x86_avx2_psrl_d:
+  case Intrinsic::x86_avx2_psrl_q:
+    return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
+  case Intrinsic::x86_sse2_psra_w:
+  case Intrinsic::x86_sse2_psra_d:
+  case Intrinsic::x86_avx2_psra_w:
+  case Intrinsic::x86_avx2_psra_d:
+    return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
+                       Op.getOperand(1), Op.getOperand(2));
   case Intrinsic::x86_sse2_pslli_w:
   case Intrinsic::x86_sse2_pslli_d:
   case Intrinsic::x86_sse2_pslli_q:
+  case Intrinsic::x86_avx2_pslli_w:
+  case Intrinsic::x86_avx2_pslli_d:
+  case Intrinsic::x86_avx2_pslli_q:
+    return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
+                               Op.getOperand(1), Op.getOperand(2), DAG);
   case Intrinsic::x86_sse2_psrli_w:
   case Intrinsic::x86_sse2_psrli_d:
   case Intrinsic::x86_sse2_psrli_q:
+  case Intrinsic::x86_avx2_psrli_w:
+  case Intrinsic::x86_avx2_psrli_d:
+  case Intrinsic::x86_avx2_psrli_q:
+    return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
+                               Op.getOperand(1), Op.getOperand(2), DAG);
   case Intrinsic::x86_sse2_psrai_w:
   case Intrinsic::x86_sse2_psrai_d:
+  case Intrinsic::x86_avx2_psrai_w:
+  case Intrinsic::x86_avx2_psrai_d:
+    return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
+                               Op.getOperand(1), Op.getOperand(2), DAG);
+  // Fix vector shift instructions where the last operand is a non-immedia=
te
+  // i32 value.
   case Intrinsic::x86_mmx_pslli_w:
   case Intrinsic::x86_mmx_pslli_d:
   case Intrinsic::x86_mmx_pslli_q:
@@ -9333,79 +9685,40 @@
       return SDValue();
=20
     unsigned NewIntNo =3D 0;
-    EVT ShAmtVT =3D MVT::v4i32;
     switch (IntNo) {
-    case Intrinsic::x86_sse2_pslli_w:
-      NewIntNo =3D Intrinsic::x86_sse2_psll_w;
-      break;
-    case Intrinsic::x86_sse2_pslli_d:
-      NewIntNo =3D Intrinsic::x86_sse2_psll_d;
-      break;
-    case Intrinsic::x86_sse2_pslli_q:
-      NewIntNo =3D Intrinsic::x86_sse2_psll_q;
-      break;
-    case Intrinsic::x86_sse2_psrli_w:
-      NewIntNo =3D Intrinsic::x86_sse2_psrl_w;
-      break;
-    case Intrinsic::x86_sse2_psrli_d:
-      NewIntNo =3D Intrinsic::x86_sse2_psrl_d;
-      break;
-    case Intrinsic::x86_sse2_psrli_q:
-      NewIntNo =3D Intrinsic::x86_sse2_psrl_q;
-      break;
-    case Intrinsic::x86_sse2_psrai_w:
-      NewIntNo =3D Intrinsic::x86_sse2_psra_w;
-      break;
-    case Intrinsic::x86_sse2_psrai_d:
-      NewIntNo =3D Intrinsic::x86_sse2_psra_d;
-      break;
-    default: {
-      ShAmtVT =3D MVT::v2i32;
-      switch (IntNo) {
-      case Intrinsic::x86_mmx_pslli_w:
-        NewIntNo =3D Intrinsic::x86_mmx_psll_w;
-        break;
-      case Intrinsic::x86_mmx_pslli_d:
-        NewIntNo =3D Intrinsic::x86_mmx_psll_d;
-        break;
-      case Intrinsic::x86_mmx_pslli_q:
-        NewIntNo =3D Intrinsic::x86_mmx_psll_q;
-        break;
-      case Intrinsic::x86_mmx_psrli_w:
-        NewIntNo =3D Intrinsic::x86_mmx_psrl_w;
-        break;
-      case Intrinsic::x86_mmx_psrli_d:
-        NewIntNo =3D Intrinsic::x86_mmx_psrl_d;
-        break;
-      case Intrinsic::x86_mmx_psrli_q:
-        NewIntNo =3D Intrinsic::x86_mmx_psrl_q;
-        break;
-      case Intrinsic::x86_mmx_psrai_w:
-        NewIntNo =3D Intrinsic::x86_mmx_psra_w;
-        break;
-      case Intrinsic::x86_mmx_psrai_d:
-        NewIntNo =3D Intrinsic::x86_mmx_psra_d;
-        break;
-      default: llvm_unreachable("Impossible intrinsic");  // Can't reach h=
ere.
-      }
-      break;
-    }
+    case Intrinsic::x86_mmx_pslli_w:
+      NewIntNo =3D Intrinsic::x86_mmx_psll_w;
+      break;
+    case Intrinsic::x86_mmx_pslli_d:
+      NewIntNo =3D Intrinsic::x86_mmx_psll_d;
+      break;
+    case Intrinsic::x86_mmx_pslli_q:
+      NewIntNo =3D Intrinsic::x86_mmx_psll_q;
+      break;
+    case Intrinsic::x86_mmx_psrli_w:
+      NewIntNo =3D Intrinsic::x86_mmx_psrl_w;
+      break;
+    case Intrinsic::x86_mmx_psrli_d:
+      NewIntNo =3D Intrinsic::x86_mmx_psrl_d;
+      break;
+    case Intrinsic::x86_mmx_psrli_q:
+      NewIntNo =3D Intrinsic::x86_mmx_psrl_q;
+      break;
+    case Intrinsic::x86_mmx_psrai_w:
+      NewIntNo =3D Intrinsic::x86_mmx_psra_w;
+      break;
+    case Intrinsic::x86_mmx_psrai_d:
+      NewIntNo =3D Intrinsic::x86_mmx_psra_d;
+      break;
+    default: llvm_unreachable("Impossible intrinsic");  // Can't reach her=
e.
     }
=20
     // The vector shift intrinsics with scalars uses 32b shift amounts but
     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
     // to be zero.
-    SDValue ShOps[4];
-    ShOps[0] =3D ShAmt;
-    ShOps[1] =3D DAG.getConstant(0, MVT::i32);
-    if (ShAmtVT =3D=3D MVT::v4i32) {
-      ShOps[2] =3D DAG.getUNDEF(MVT::i32);
-      ShOps[3] =3D DAG.getUNDEF(MVT::i32);
-      ShAmt =3D  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
-    } else {
-      ShAmt =3D  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
+    ShAmt =3D  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
+                         DAG.getConstant(0, MVT::i32));
 // FIXME this must be lowered to get rid of the invalid type.
-    }
=20
     EVT VT =3D Op.getValueType();
     ShAmt =3D DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
@@ -9432,13 +9745,13 @@
     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
                                    FrameAddr, Offset),
-                       MachinePointerInfo(), false, false, 0);
+                       MachinePointerInfo(), false, false, false, 0);
   }
=20
   // Just load the return address.
   SDValue RetAddrFI =3D getReturnAddressFrameIndex(DAG);
   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
-                     RetAddrFI, MachinePointerInfo(), false, false, 0);
+                     RetAddrFI, MachinePointerInfo(), false, false, false,=
 0);
 }
=20
 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) c=
onst {
@@ -9453,7 +9766,7 @@
   while (Depth--)
     FrameAddr =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
                             MachinePointerInfo(),
-                            false, false, 0);
+                            false, false, false, 0);
   return FrameAddr;
 }
=20
@@ -9685,7 +9998,7 @@
=20
   // Load FP Control Word from stack slot
   SDValue CWD =3D DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
-                            MachinePointerInfo(), false, false, 0);
+                            MachinePointerInfo(), false, false, false, 0);
=20
   // Transform as necessary
   SDValue CWD1 =3D
@@ -9745,7 +10058,8 @@
   return Op;
 }
=20
-SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
+SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
+                                                SelectionDAG &DAG) const {
   EVT VT =3D Op.getValueType();
   EVT OpVT =3D VT;
   unsigned NumBits =3D VT.getSizeInBits();
@@ -9753,26 +10067,41 @@
=20
   Op =3D Op.getOperand(0);
   if (VT =3D=3D MVT::i8) {
+    // Zero extend to i32 since there is not an i8 bsr.
     OpVT =3D MVT::i32;
     Op =3D DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
   }
=20
+  // Issue a bsr (scan bits in reverse).
+  SDVTList VTs =3D DAG.getVTList(OpVT, MVT::i32);
+  Op =3D DAG.getNode(X86ISD::BSR, dl, VTs, Op);
+
+  // And xor with NumBits-1.
+  Op =3D DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, Op=
VT));
+
+  if (VT =3D=3D MVT::i8)
+    Op =3D DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
+  return Op;
+}
+
+SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
+  EVT VT =3D Op.getValueType();
+  unsigned NumBits =3D VT.getSizeInBits();
+  DebugLoc dl =3D Op.getDebugLoc();
+  Op =3D Op.getOperand(0);
+
   // Issue a bsf (scan bits forward) which also sets EFLAGS.
-  SDVTList VTs =3D DAG.getVTList(OpVT, MVT::i32);
+  SDVTList VTs =3D DAG.getVTList(VT, MVT::i32);
   Op =3D DAG.getNode(X86ISD::BSF, dl, VTs, Op);
=20
   // If src is zero (i.e. bsf sets ZF), returns NumBits.
   SDValue Ops[] =3D {
     Op,
-    DAG.getConstant(NumBits, OpVT),
+    DAG.getConstant(NumBits, VT),
     DAG.getConstant(X86::COND_E, MVT::i8),
     Op.getValue(1)
   };
-  Op =3D DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
-
-  if (VT =3D=3D MVT::i8)
-    Op =3D DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
-  return Op;
+  return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
 }
=20
 // Lower256IntArith - Break a 256-bit integer operation into two new 128-b=
it
@@ -9824,49 +10153,49 @@
   EVT VT =3D Op.getValueType();
=20
   // Decompose 256-bit ops into smaller 128-bit ops.
-  if (VT.getSizeInBits() =3D=3D 256)
+  if (VT.getSizeInBits() =3D=3D 256 && !Subtarget->hasAVX2())
     return Lower256IntArith(Op, DAG);
=20
-  assert(VT =3D=3D MVT::v2i64 && "Only know how to lower V2I64 multiply");
+  assert((VT =3D=3D MVT::v2i64 || VT =3D=3D MVT::v4i64) &&
+         "Only know how to lower V2I64/V4I64 multiply");
+
   DebugLoc dl =3D Op.getDebugLoc();
=20
-  //  ulong2 Ahi =3D __builtin_ia32_psrlqi128( a, 32);
-  //  ulong2 Bhi =3D __builtin_ia32_psrlqi128( b, 32);
-  //  ulong2 AloBlo =3D __builtin_ia32_pmuludq128( a, b );
-  //  ulong2 AloBhi =3D __builtin_ia32_pmuludq128( a, Bhi );
-  //  ulong2 AhiBlo =3D __builtin_ia32_pmuludq128( Ahi, b );
+  //  Ahi =3D psrlqi(a, 32);
+  //  Bhi =3D psrlqi(b, 32);
   //
-  //  AloBhi =3D __builtin_ia32_psllqi128( AloBhi, 32 );
-  //  AhiBlo =3D __builtin_ia32_psllqi128( AhiBlo, 32 );
+  //  AloBlo =3D pmuludq(a, b);
+  //  AloBhi =3D pmuludq(a, Bhi);
+  //  AhiBlo =3D pmuludq(Ahi, b);
+
+  //  AloBhi =3D psllqi(AloBhi, 32);
+  //  AhiBlo =3D psllqi(AhiBlo, 32);
   //  return AloBlo + AloBhi + AhiBlo;
=20
   SDValue A =3D Op.getOperand(0);
   SDValue B =3D Op.getOperand(1);
=20
-  SDValue Ahi =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i=
32),
-                       A, DAG.getConstant(32, MVT::i32));
-  SDValue Bhi =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i=
32),
-                       B, DAG.getConstant(32, MVT::i32));
-  SDValue AloBlo =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::=
i32),
-                       A, B);
-  SDValue AloBhi =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::=
i32),
-                       A, Bhi);
-  SDValue AhiBlo =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::=
i32),
-                       Ahi, B);
-  AloBhi =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i=
32),
-                       AloBhi, DAG.getConstant(32, MVT::i32));
-  AhiBlo =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i=
32),
-                       AhiBlo, DAG.getConstant(32, MVT::i32));
+  SDValue ShAmt =3D DAG.getConstant(32, MVT::i32);
+
+  SDValue Ahi =3D DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
+  SDValue Bhi =3D DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
+
+  // Bit cast to 32-bit vectors for MULUDQ
+  EVT MulVT =3D (VT =3D=3D MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
+  A =3D DAG.getNode(ISD::BITCAST, dl, MulVT, A);
+  B =3D DAG.getNode(ISD::BITCAST, dl, MulVT, B);
+  Ahi =3D DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
+  Bhi =3D DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
+
+  SDValue AloBlo =3D DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
+  SDValue AloBhi =3D DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
+  SDValue AhiBlo =3D DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
+
+  AloBhi =3D DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
+  AhiBlo =3D DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
+
   SDValue Res =3D DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
-  Res =3D DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
-  return Res;
+  return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
 }
=20
 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const=
 {
@@ -9877,12 +10206,183 @@
   SDValue Amt =3D Op.getOperand(1);
   LLVMContext *Context =3D DAG.getContext();
=20
-  if (!Subtarget->hasXMMInt())
+  if (!Subtarget->hasSSE2())
     return SDValue();
=20
+  // Optimize shl/srl/sra with constant shift amount.
+  if (isSplatVector(Amt.getNode())) {
+    SDValue SclrAmt =3D Amt->getOperand(0);
+    if (ConstantSDNode *C =3D dyn_cast<ConstantSDNode>(SclrAmt)) {
+      uint64_t ShiftAmt =3D C->getZExtValue();
+
+      if (VT =3D=3D MVT::v2i64 || VT =3D=3D MVT::v4i32 || VT =3D=3D MVT::v=
8i16 ||
+          (Subtarget->hasAVX2() &&
+           (VT =3D=3D MVT::v4i64 || VT =3D=3D MVT::v8i32 || VT =3D=3D MVT:=
:v16i16))) {
+        if (Op.getOpcode() =3D=3D ISD::SHL)
+          return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
+                             DAG.getConstant(ShiftAmt, MVT::i32));
+        if (Op.getOpcode() =3D=3D ISD::SRL)
+          return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
+                             DAG.getConstant(ShiftAmt, MVT::i32));
+        if (Op.getOpcode() =3D=3D ISD::SRA && VT !=3D MVT::v2i64 && VT !=
=3D MVT::v4i64)
+          return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
+                             DAG.getConstant(ShiftAmt, MVT::i32));
+      }
+
+      if (VT =3D=3D MVT::v16i8) {
+        if (Op.getOpcode() =3D=3D ISD::SHL) {
+          // Make a large shift.
+          SDValue SHL =3D DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
+                                    DAG.getConstant(ShiftAmt, MVT::i32));
+          SHL =3D DAG.getNode(ISD::BITCAST, dl, VT, SHL);
+          // Zero out the rightmost bits.
+          SmallVector<SDValue, 16> V(16,
+                                     DAG.getConstant(uint8_t(-1U << ShiftA=
mt),
+                                                     MVT::i8));
+          return DAG.getNode(ISD::AND, dl, VT, SHL,
+                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0],=
 16));
+        }
+        if (Op.getOpcode() =3D=3D ISD::SRL) {
+          // Make a large shift.
+          SDValue SRL =3D DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
+                                    DAG.getConstant(ShiftAmt, MVT::i32));
+          SRL =3D DAG.getNode(ISD::BITCAST, dl, VT, SRL);
+          // Zero out the leftmost bits.
+          SmallVector<SDValue, 16> V(16,
+                                     DAG.getConstant(uint8_t(-1U) >> Shift=
Amt,
+                                                     MVT::i8));
+          return DAG.getNode(ISD::AND, dl, VT, SRL,
+                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0],=
 16));
+        }
+        if (Op.getOpcode() =3D=3D ISD::SRA) {
+          if (ShiftAmt =3D=3D 7) {
+            // R s>> 7  =3D=3D=3D  R s< 0
+            SDValue Zeros =3D getZeroVector(VT, Subtarget, DAG, dl);
+            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
+          }
+
+          // R s>> a =3D=3D=3D ((R u>> a) ^ m) - m
+          SDValue Res =3D DAG.getNode(ISD::SRL, dl, VT, R, Amt);
+          SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
+                                                         MVT::i8));
+          SDValue Mask =3D DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 1=
6);
+          Res =3D DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
+          Res =3D DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
+          return Res;
+        }
+      }
+
+      if (Subtarget->hasAVX2() && VT =3D=3D MVT::v32i8) {
+        if (Op.getOpcode() =3D=3D ISD::SHL) {
+          // Make a large shift.
+          SDValue SHL =3D DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
+                                    DAG.getConstant(ShiftAmt, MVT::i32));
+          SHL =3D DAG.getNode(ISD::BITCAST, dl, VT, SHL);
+          // Zero out the rightmost bits.
+          SmallVector<SDValue, 32> V(32,
+                                     DAG.getConstant(uint8_t(-1U << ShiftA=
mt),
+                                                     MVT::i8));
+          return DAG.getNode(ISD::AND, dl, VT, SHL,
+                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0],=
 32));
+        }
+        if (Op.getOpcode() =3D=3D ISD::SRL) {
+          // Make a large shift.
+          SDValue SRL =3D DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
+                                    DAG.getConstant(ShiftAmt, MVT::i32));
+          SRL =3D DAG.getNode(ISD::BITCAST, dl, VT, SRL);
+          // Zero out the leftmost bits.
+          SmallVector<SDValue, 32> V(32,
+                                     DAG.getConstant(uint8_t(-1U) >> Shift=
Amt,
+                                                     MVT::i8));
+          return DAG.getNode(ISD::AND, dl, VT, SRL,
+                             DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0],=
 32));
+        }
+        if (Op.getOpcode() =3D=3D ISD::SRA) {
+          if (ShiftAmt =3D=3D 7) {
+            // R s>> 7  =3D=3D=3D  R s< 0
+            SDValue Zeros =3D getZeroVector(VT, Subtarget, DAG, dl);
+            return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
+          }
+
+          // R s>> a =3D=3D=3D ((R u>> a) ^ m) - m
+          SDValue Res =3D DAG.getNode(ISD::SRL, dl, VT, R, Amt);
+          SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
+                                                         MVT::i8));
+          SDValue Mask =3D DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 3=
2);
+          Res =3D DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
+          Res =3D DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
+          return Res;
+        }
+      }
+    }
+  }
+
+  // Lower SHL with variable shift amount.
+  if (VT =3D=3D MVT::v4i32 && Op->getOpcode() =3D=3D ISD::SHL) {
+    Op =3D DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
+                     DAG.getConstant(23, MVT::i32));
+
+    const uint32_t CV[] =3D { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f8=
00000U};
+    Constant *C =3D ConstantDataVector::get(*Context, CV);
+    SDValue CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
+    SDValue Addend =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
+                                 MachinePointerInfo::getConstantPool(),
+                                 false, false, false, 16);
+
+    Op =3D DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
+    Op =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
+    Op =3D DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
+    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
+  }
+  if (VT =3D=3D MVT::v16i8 && Op->getOpcode() =3D=3D ISD::SHL) {
+    assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
+
+    // a =3D a << 5;
+    Op =3D DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
+                     DAG.getConstant(5, MVT::i32));
+    Op =3D DAG.getNode(ISD::BITCAST, dl, VT, Op);
+
+    // Turn 'a' into a mask suitable for VSELECT
+    SDValue VSelM =3D DAG.getConstant(0x80, VT);
+    SDValue OpVSel =3D DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
+    OpVSel =3D DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
+
+    SDValue CM1 =3D DAG.getConstant(0x0f, VT);
+    SDValue CM2 =3D DAG.getConstant(0x3f, VT);
+
+    // r =3D VSELECT(r, psllw(r & (char16)15, 4), a);
+    SDValue M =3D DAG.getNode(ISD::AND, dl, VT, R, CM1);
+    M =3D getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
+                            DAG.getConstant(4, MVT::i32), DAG);
+    M =3D DAG.getNode(ISD::BITCAST, dl, VT, M);
+    R =3D DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
+
+    // a +=3D a
+    Op =3D DAG.getNode(ISD::ADD, dl, VT, Op, Op);
+    OpVSel =3D DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
+    OpVSel =3D DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
+
+    // r =3D VSELECT(r, psllw(r & (char16)63, 2), a);
+    M =3D DAG.getNode(ISD::AND, dl, VT, R, CM2);
+    M =3D getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
+                            DAG.getConstant(2, MVT::i32), DAG);
+    M =3D DAG.getNode(ISD::BITCAST, dl, VT, M);
+    R =3D DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
+
+    // a +=3D a
+    Op =3D DAG.getNode(ISD::ADD, dl, VT, Op, Op);
+    OpVSel =3D DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
+    OpVSel =3D DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
+
+    // return VSELECT(r, r+r, a);
+    R =3D DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
+                    DAG.getNode(ISD::ADD, dl, VT, R, R), R);
+    return R;
+  }
+
   // Decompose 256-bit shifts into smaller 128-bit shifts.
   if (VT.getSizeInBits() =3D=3D 256) {
-    int NumElems =3D VT.getVectorNumElements();
+    unsigned NumElems =3D VT.getVectorNumElements();
     MVT EltVT =3D VT.getVectorElementType().getSimpleVT();
     EVT NewVT =3D MVT::getVectorVT(EltVT, NumElems/2);
=20
@@ -9897,9 +10397,9 @@
       // Constant shift amount
       SmallVector<SDValue, 4> Amt1Csts;
       SmallVector<SDValue, 4> Amt2Csts;
-      for (int i =3D 0; i < NumElems/2; ++i)
+      for (unsigned i =3D 0; i !=3D NumElems/2; ++i)
         Amt1Csts.push_back(Amt->getOperand(i));
-      for (int i =3D NumElems/2; i < NumElems; ++i)
+      for (unsigned i =3D NumElems/2; i !=3D NumElems; ++i)
         Amt2Csts.push_back(Amt->getOperand(i));
=20
       Amt1 =3D DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
@@ -9921,120 +10421,6 @@
     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
   }
=20
-  // Optimize shl/srl/sra with constant shift amount.
-  if (isSplatVector(Amt.getNode())) {
-    SDValue SclrAmt =3D Amt->getOperand(0);
-    if (ConstantSDNode *C =3D dyn_cast<ConstantSDNode>(SclrAmt)) {
-      uint64_t ShiftAmt =3D C->getZExtValue();
-
-      if (VT =3D=3D MVT::v2i64 && Op.getOpcode() =3D=3D ISD::SHL)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-
-      if (VT =3D=3D MVT::v4i32 && Op.getOpcode() =3D=3D ISD::SHL)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-
-      if (VT =3D=3D MVT::v8i16 && Op.getOpcode() =3D=3D ISD::SHL)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-
-      if (VT =3D=3D MVT::v2i64 && Op.getOpcode() =3D=3D ISD::SRL)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-
-      if (VT =3D=3D MVT::v4i32 && Op.getOpcode() =3D=3D ISD::SRL)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-
-      if (VT =3D=3D MVT::v8i16 && Op.getOpcode() =3D=3D ISD::SRL)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-
-      if (VT =3D=3D MVT::v4i32 && Op.getOpcode() =3D=3D ISD::SRA)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-
-      if (VT =3D=3D MVT::v8i16 && Op.getOpcode() =3D=3D ISD::SRA)
-       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32=
),
-                     R, DAG.getConstant(ShiftAmt, MVT::i32));
-    }
-  }
-
-  // Lower SHL with variable shift amount.
-  if (VT =3D=3D MVT::v4i32 && Op->getOpcode() =3D=3D ISD::SHL) {
-    Op =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32=
),
-                     Op.getOperand(1), DAG.getConstant(23, MVT::i32));
-
-    ConstantInt *CI =3D ConstantInt::get(*Context, APInt(32, 0x3f800000U));
-
-    std::vector<Constant*> CV(4, CI);
-    Constant *C =3D ConstantVector::get(CV);
-    SDValue CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
-    SDValue Addend =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
-                                 MachinePointerInfo::getConstantPool(),
-                                 false, false, 16);
-
-    Op =3D DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
-    Op =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
-    Op =3D DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
-    return DAG.getNode(ISD::MUL, dl, VT, Op, R);
-  }
-  if (VT =3D=3D MVT::v16i8 && Op->getOpcode() =3D=3D ISD::SHL) {
-    // a =3D a << 5;
-    Op =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32=
),
-                     Op.getOperand(1), DAG.getConstant(5, MVT::i32));
-
-    ConstantInt *CM1 =3D ConstantInt::get(*Context, APInt(8, 15));
-    ConstantInt *CM2 =3D ConstantInt::get(*Context, APInt(8, 63));
-
-    std::vector<Constant*> CVM1(16, CM1);
-    std::vector<Constant*> CVM2(16, CM2);
-    Constant *C =3D ConstantVector::get(CVM1);
-    SDValue CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
-    SDValue M =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
-                            MachinePointerInfo::getConstantPool(),
-                            false, false, 16);
-
-    // r =3D pblendv(r, psllw(r & (char16)15, 4), a);
-    M =3D DAG.getNode(ISD::AND, dl, VT, R, M);
-    M =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32)=
, M,
-                    DAG.getConstant(4, MVT::i32));
-    R =3D DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
-    // a +=3D a
-    Op =3D DAG.getNode(ISD::ADD, dl, VT, Op, Op);
-
-    C =3D ConstantVector::get(CVM2);
-    CPIdx =3D DAG.getConstantPool(C, getPointerTy(), 16);
-    M =3D DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
-                    MachinePointerInfo::getConstantPool(),
-                    false, false, 16);
-
-    // r =3D pblendv(r, psllw(r & (char16)63, 2), a);
-    M =3D DAG.getNode(ISD::AND, dl, VT, R, M);
-    M =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                    DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32)=
, M,
-                    DAG.getConstant(2, MVT::i32));
-    R =3D DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
-    // a +=3D a
-    Op =3D DAG.getNode(ISD::ADD, dl, VT, Op, Op);
-
-    // return pblendv(r, r+r, a);
-    R =3D DAG.getNode(ISD::VSELECT, dl, VT, Op,
-                    R, DAG.getNode(ISD::ADD, dl, VT, R, R));
-    return R;
-  }
   return SDValue();
 }
=20
@@ -10113,46 +10499,58 @@
   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
 }
=20
-SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG=
 &DAG) const{
+SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
+                                                  SelectionDAG &DAG) const=
 {
   DebugLoc dl =3D Op.getDebugLoc();
-  SDNode* Node =3D Op.getNode();
-  EVT ExtraVT =3D cast<VTSDNode>(Node->getOperand(1))->getVT();
-  EVT VT =3D Node->getValueType(0);
-  if (Subtarget->hasXMMInt() && VT.isVector()) {
-    unsigned BitsDiff =3D VT.getScalarType().getSizeInBits() -
-                        ExtraVT.getScalarType().getSizeInBits();
-    SDValue ShAmt =3D DAG.getConstant(BitsDiff, MVT::i32);
-
-    unsigned SHLIntrinsicsID =3D 0;
-    unsigned SRAIntrinsicsID =3D 0;
-    switch (VT.getSimpleVT().SimpleTy) {
-      default:
+  EVT ExtraVT =3D cast<VTSDNode>(Op.getOperand(1))->getVT();
+  EVT VT =3D Op.getValueType();
+
+  if (!Subtarget->hasSSE2() || !VT.isVector())
+    return SDValue();
+
+  unsigned BitsDiff =3D VT.getScalarType().getSizeInBits() -
+                      ExtraVT.getScalarType().getSizeInBits();
+  SDValue ShAmt =3D DAG.getConstant(BitsDiff, MVT::i32);
+
+  switch (VT.getSimpleVT().SimpleTy) {
+    default: return SDValue();
+    case MVT::v8i32:
+    case MVT::v16i16:
+      if (!Subtarget->hasAVX())
         return SDValue();
-      case MVT::v4i32: {
-        SHLIntrinsicsID =3D Intrinsic::x86_sse2_pslli_d;
-        SRAIntrinsicsID =3D Intrinsic::x86_sse2_psrai_d;
-        break;
-      }
-      case MVT::v8i16: {
-        SHLIntrinsicsID =3D Intrinsic::x86_sse2_pslli_w;
-        SRAIntrinsicsID =3D Intrinsic::x86_sse2_psrai_w;
-        break;
-      }
-    }
-
-    SDValue Tmp1 =3D DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                         DAG.getConstant(SHLIntrinsicsID, MVT::i32),
-                         Node->getOperand(0), ShAmt);
-
-    // In case of 1 bit sext, no need to shr
-    if (ExtraVT.getScalarType().getSizeInBits() =3D=3D 1) return Tmp1;
-
-    return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
-                       DAG.getConstant(SRAIntrinsicsID, MVT::i32),
-                       Tmp1, ShAmt);
-  }
-
-  return SDValue();
+      if (!Subtarget->hasAVX2()) {
+        // needs to be split
+        int NumElems =3D VT.getVectorNumElements();
+        SDValue Idx0 =3D DAG.getConstant(0, MVT::i32);
+        SDValue Idx1 =3D DAG.getConstant(NumElems/2, MVT::i32);
+
+        // Extract the LHS vectors
+        SDValue LHS =3D Op.getOperand(0);
+        SDValue LHS1 =3D Extract128BitVector(LHS, Idx0, DAG, dl);
+        SDValue LHS2 =3D Extract128BitVector(LHS, Idx1, DAG, dl);
+
+        MVT EltVT =3D VT.getVectorElementType().getSimpleVT();
+        EVT NewVT =3D MVT::getVectorVT(EltVT, NumElems/2);
+
+        EVT ExtraEltVT =3D ExtraVT.getVectorElementType();
+        int ExtraNumElems =3D ExtraVT.getVectorNumElements();
+        ExtraVT =3D EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
+                                   ExtraNumElems/2);
+        SDValue Extra =3D DAG.getValueType(ExtraVT);
+
+        LHS1 =3D DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
+        LHS2 =3D DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
+
+        return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
+      }
+      // fall through
+    case MVT::v4i32:
+    case MVT::v8i16: {
+      SDValue Tmp1 =3D getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
+                                         Op.getOperand(0), ShAmt, DAG);
+      return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
+    }
+  }
 }
=20
=20
@@ -10161,7 +10559,7 @@
=20
   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
   // There isn't any reason to disable it if the target processor supports=
 it.
-  if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
+  if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
     SDValue Chain =3D Op.getOperand(0);
     SDValue Zero =3D DAG.getConstant(0, MVT::i32);
     SDValue Ops[] =3D {
@@ -10215,7 +10613,7 @@
     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
     // no-sse2). There isn't any reason to disable it if the target proces=
sor
     // supports it.
-    if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
+    if (Subtarget->hasSSE2() || Subtarget->is64Bit())
       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
=20
     SDValue Chain =3D Op.getOperand(0);
@@ -10246,8 +10644,7 @@
   unsigned Reg =3D 0;
   unsigned size =3D 0;
   switch(T.getSimpleVT().SimpleTy) {
-  default:
-    assert(false && "Invalid value type!");
+  default: llvm_unreachable("Invalid value type!");
   case MVT::i8:  Reg =3D X86::AL;  size =3D 1; break;
   case MVT::i16: Reg =3D X86::AX;  size =3D 2; break;
   case MVT::i32: Reg =3D X86::EAX; size =3D 4; break;
@@ -10295,7 +10692,7 @@
                                             SelectionDAG &DAG) const {
   EVT SrcVT =3D Op.getOperand(0).getValueType();
   EVT DstVT =3D Op.getValueType();
-  assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
+  assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
          Subtarget->hasMMX() && "Unexpected custom BITCAST");
   assert((DstVT =3D=3D MVT::i64 ||
           (DstVT.isVector() && DstVT.getSizeInBits()=3D=3D64)) &&
@@ -10365,7 +10762,7 @@
   unsigned Opc;
   bool ExtraOp =3D false;
   switch (Op.getOpcode()) {
-  default: assert(0 && "Invalid code");
+  default: llvm_unreachable("Invalid code");
   case ISD::ADDC: Opc =3D X86ISD::ADD; break;
   case ISD::ADDE: Opc =3D X86ISD::ADC; ExtraOp =3D true; break;
   case ISD::SUBC: Opc =3D X86ISD::SUB; break;
@@ -10432,6 +10829,7 @@
   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
+  case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
   case ISD::MUL:                return LowerMUL(Op, DAG);
   case ISD::SRA:
@@ -10506,8 +10904,7 @@
   DebugLoc dl =3D N->getDebugLoc();
   switch (N->getOpcode()) {
   default:
-    assert(false && "Do not know how to custom type legalize this operatio=
n!");
-    return;
+    llvm_unreachable("Do not know how to custom type legalize this operati=
on!");
   case ISD::SIGN_EXTEND_INREG:
   case ISD::ADDC:
   case ISD::ADDE:
@@ -10515,15 +10912,25 @@
   case ISD::SUBE:
     // We don't want to expand or promote these.
     return;
-  case ISD::FP_TO_SINT: {
+  case ISD::FP_TO_SINT:
+  case ISD::FP_TO_UINT: {
+    bool IsSigned =3D N->getOpcode() =3D=3D ISD::FP_TO_SINT;
+
+    if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
+      return;
+
     std::pair<SDValue,SDValue> Vals =3D
-        FP_TO_INTHelper(SDValue(N, 0), DAG, true);
+        FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=3D*/ tru=
e);
     SDValue FIST =3D Vals.first, StackSlot =3D Vals.second;
     if (FIST.getNode() !=3D 0) {
       EVT VT =3D N->getValueType(0);
       // Return a load from the stack slot.
-      Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
-                                    MachinePointerInfo(), false, false, 0)=
);
+      if (StackSlot.getNode() !=3D 0)
+        Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
+                                      MachinePointerInfo(),
+                                      false, false, false, 0));
+      else
+        Results.push_back(FIST);
     }
     return;
   }
@@ -10657,15 +11064,19 @@
   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
-  case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
-  case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
-  case X86ISD::PSIGND:             return "X86ISD::PSIGND";
+  case X86ISD::PSIGN:              return "X86ISD::PSIGN";
+  case X86ISD::BLENDV:             return "X86ISD::BLENDV";
+  case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
+  case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
+  case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
+  case X86ISD::HADD:               return "X86ISD::HADD";
+  case X86ISD::HSUB:               return "X86ISD::HSUB";
+  case X86ISD::FHADD:              return "X86ISD::FHADD";
+  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
   case X86ISD::FMAX:               return "X86ISD::FMAX";
   case X86ISD::FMIN:               return "X86ISD::FMIN";
   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
   case X86ISD::FRCP:               return "X86ISD::FRCP";
-  case X86ISD::FHADD:              return "X86ISD::FHADD";
-  case X86ISD::FHSUB:              return "X86ISD::FHSUB";
   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
@@ -10681,18 +11092,17 @@
   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
+  case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
+  case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
   case X86ISD::VSHL:               return "X86ISD::VSHL";
   case X86ISD::VSRL:               return "X86ISD::VSRL";
-  case X86ISD::CMPPD:              return "X86ISD::CMPPD";
-  case X86ISD::CMPPS:              return "X86ISD::CMPPS";
-  case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
-  case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
-  case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
-  case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
-  case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
-  case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
-  case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
-  case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
+  case X86ISD::VSRA:               return "X86ISD::VSRA";
+  case X86ISD::VSHLI:              return "X86ISD::VSHLI";
+  case X86ISD::VSRLI:              return "X86ISD::VSRLI";
+  case X86ISD::VSRAI:              return "X86ISD::VSRAI";
+  case X86ISD::CMPP:               return "X86ISD::CMPP";
+  case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
+  case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
   case X86ISD::ADD:                return "X86ISD::ADD";
   case X86ISD::SUB:                return "X86ISD::SUB";
   case X86ISD::ADC:                return "X86ISD::ADC";
@@ -10705,54 +11115,39 @@
   case X86ISD::XOR:                return "X86ISD::XOR";
   case X86ISD::AND:                return "X86ISD::AND";
   case X86ISD::ANDN:               return "X86ISD::ANDN";
+  case X86ISD::BLSI:               return "X86ISD::BLSI";
+  case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
+  case X86ISD::BLSR:               return "X86ISD::BLSR";
   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
   case X86ISD::PTEST:              return "X86ISD::PTEST";
   case X86ISD::TESTP:              return "X86ISD::TESTP";
   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
-  case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
-  case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
-  case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
-  case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
+  case X86ISD::SHUFP:              return "X86ISD::SHUFP";
   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
-  case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
-  case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
-  case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
-  case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
-  case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
-  case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
-  case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
-  case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
-  case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
-  case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
-  case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
-  case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
-  case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
-  case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
-  case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
-  case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
+  case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
+  case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
-  case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
-  case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
-  case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
-  case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
-  case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
+  case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
+  case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
+  case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REG=
S";
   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
+  case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
   }
 }
=20
@@ -10855,21 +11250,21 @@
                                       EVT VT) const {
   // Very little shuffling can be done for 64-bit vectors right now.
   if (VT.getSizeInBits() =3D=3D 64)
-    return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX=
());
+    return false;
=20
   // FIXME: pshufb, blends, shifts.
   return (VT.getVectorNumElements() =3D=3D 2 ||
           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
           isMOVLMask(M, VT) ||
-          isSHUFPMask(M, VT) ||
+          isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
           isPSHUFDMask(M, VT) ||
           isPSHUFHWMask(M, VT) ||
           isPSHUFLWMask(M, VT) ||
-          isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX(=
)) ||
-          isUNPCKLMask(M, VT) ||
-          isUNPCKHMask(M, VT) ||
-          isUNPCKL_v_undef_Mask(M, VT) ||
-          isUNPCKH_v_undef_Mask(M, VT));
+          isPALIGNRMask(M, VT, Subtarget) ||
+          isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
+          isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
+          isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
+          isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
 }
=20
 bool
@@ -10882,8 +11277,8 @@
   if (NumElts =3D=3D 4 && VT.getSizeInBits() =3D=3D 128) {
     return (isMOVLMask(Mask, VT)  ||
             isCommutedMOVLMask(Mask, VT, true) ||
-            isSHUFPMask(Mask, VT) ||
-            isCommutedSHUFPMask(Mask, VT));
+            isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
+            isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true=
));
   }
   return false;
 }
@@ -10902,7 +11297,7 @@
                                                        unsigned CXchgOpc,
                                                        unsigned notOpc,
                                                        unsigned EAXreg,
-                                                       TargetRegisterClass=
 *RC,
+                                                 const TargetRegisterClass=
 *RC,
                                                        bool invSrc) const {
   // For the atomic bitwise operator, we generate
   //   thisMBB:
@@ -11274,7 +11669,7 @@
 MachineBasicBlock *
 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
                             unsigned numArgs, bool memArg) const {
-  assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
+  assert(Subtarget->hasSSE42() &&
          "Target must have SSE4.2 or AVX features enabled");
=20
   DebugLoc dl =3D MI->getDebugLoc();
@@ -11679,6 +12074,42 @@
   return EndMBB;
 }
=20
+// The EFLAGS operand of SelectItr might be missing a kill marker
+// because there were multiple uses of EFLAGS, and ISel didn't know
+// which to mark. Figure out whether SelectItr should have had a
+// kill marker, and set it if it should. Returns the correct kill
+// marker value.
+static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
+                                     MachineBasicBlock* BB,
+                                     const TargetRegisterInfo* TRI) {
+  // Scan forward through BB for a use/def of EFLAGS.
+  MachineBasicBlock::iterator miI(llvm::next(SelectItr));
+  for (MachineBasicBlock::iterator miE =3D BB->end(); miI !=3D miE; ++miI)=
 {
+    const MachineInstr& mi =3D *miI;
+    if (mi.readsRegister(X86::EFLAGS))
+      return false;
+    if (mi.definesRegister(X86::EFLAGS))
+      break; // Should have kill-flag - update below.
+  }
+
+  // If we hit the end of the block, check whether EFLAGS is live into a
+  // successor.
+  if (miI =3D=3D BB->end()) {
+    for (MachineBasicBlock::succ_iterator sItr =3D BB->succ_begin(),
+                                          sEnd =3D BB->succ_end();
+         sItr !=3D sEnd; ++sItr) {
+      MachineBasicBlock* succ =3D *sItr;
+      if (succ->isLiveIn(X86::EFLAGS))
+        return false;
+    }
+  }
+
+  // We found a def, or hit the end of the basic block and EFLAGS wasn't l=
ive
+  // out. SelectMI should have a kill flag on EFLAGS.
+  SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
+  return true;
+}
+
 MachineBasicBlock *
 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
                                      MachineBasicBlock *BB) const {
@@ -11708,7 +12139,9 @@
=20
   // If the EFLAGS register isn't dead in the terminator, then claim that =
it's
   // live into the sink and copy blocks.
-  if (!MI->killsRegister(X86::EFLAGS)) {
+  const TargetRegisterInfo* TRI =3D getTargetMachine().getRegisterInfo();
+  if (!MI->killsRegister(X86::EFLAGS) &&
+      !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
     copy0MBB->addLiveIn(X86::EFLAGS);
     sinkMBB->addLiveIn(X86::EFLAGS);
   }
@@ -11753,7 +12186,7 @@
   MachineFunction *MF =3D BB->getParent();
   const BasicBlock *LLVM_BB =3D BB->getBasicBlock();
=20
-  assert(EnableSegmentedStacks);
+  assert(getTargetMachine().Options.EnableSegmentedStacks);
=20
   unsigned TlsReg =3D Is64Bit ? X86::FS : X86::GS;
   unsigned TlsOffset =3D Is64Bit ? 0x70 : 0x30;
@@ -11785,6 +12218,7 @@
   unsigned mallocPtrVReg =3D MRI.createVirtualRegister(AddrRegClass),
     bumpSPPtrVReg =3D MRI.createVirtualRegister(AddrRegClass),
     tmpSPVReg =3D MRI.createVirtualRegister(AddrRegClass),
+    SPLimitVReg =3D MRI.createVirtualRegister(AddrRegClass),
     sizeVReg =3D MI->getOperand(1).getReg(),
     physSPReg =3D Is64Bit ? X86::RSP : X86::ESP;
=20
@@ -11802,33 +12236,39 @@
   // Add code to the main basic block to check if the stack limit has been=
 hit,
   // and if so, jump to mallocMBB otherwise to bumpMBB.
   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPRe=
g);
-  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
+  BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVR=
eg)
     .addReg(tmpSPVReg).addReg(sizeVReg);
   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
-    .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
-    .addReg(tmpSPVReg);
+    .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
+    .addReg(SPLimitVReg);
   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
=20
   // bumpMBB simply decreases the stack pointer, since we know the current
   // stacklet has enough space.
   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
-    .addReg(tmpSPVReg);
+    .addReg(SPLimitVReg);
   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
-    .addReg(tmpSPVReg);
+    .addReg(SPLimitVReg);
   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
=20
   // Calls into a routine in libgcc to allocate more space from the heap.
+  const uint32_t *RegMask =3D
+    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv=
::C);
   if (Is64Bit) {
     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
       .addReg(sizeVReg);
     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
-    .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI=
);
+      .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::R=
DI)
+      .addRegMask(RegMask)
+      .addReg(X86::RAX, RegState::ImplicitDefine);
   } else {
     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physS=
PReg)
       .addImm(12);
     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
-      .addExternalSymbol("__morestack_allocate_stack_space");
+      .addExternalSymbol("__morestack_allocate_stack_space")
+      .addRegMask(RegMask)
+      .addReg(X86::EAX, RegState::ImplicitDefine);
   }
=20
   if (!Is64Bit)
@@ -11926,6 +12366,11 @@
   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
   assert(MI->getOperand(3).isGlobal() && "This should be a global");
=20
+  // Get a register mask for the lowered call.
+  // FIXME: The 32-bit calls have non-standard calling conventions. Use a
+  // proper register mask.
+  const uint32_t *RegMask =3D
+    getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv=
::C);
   if (Subtarget->is64Bit()) {
     MachineInstrBuilder MIB =3D BuildMI(*BB, MI, DL,
                                       TII->get(X86::MOV64rm), X86::RDI)
@@ -11936,6 +12381,7 @@
     .addReg(0);
     MIB =3D BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
     addDirectMem(MIB, X86::RDI);
+    MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
   } else if (getTargetMachine().getRelocationModel() !=3D Reloc::PIC_) {
     MachineInstrBuilder MIB =3D BuildMI(*BB, MI, DL,
                                       TII->get(X86::MOV32rm), X86::EAX)
@@ -11946,6 +12392,7 @@
     .addReg(0);
     MIB =3D BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
     addDirectMem(MIB, X86::EAX);
+    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
   } else {
     MachineInstrBuilder MIB =3D BuildMI(*BB, MI, DL,
                                       TII->get(X86::MOV32rm), X86::EAX)
@@ -11956,6 +12403,7 @@
     .addReg(0);
     MIB =3D BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
     addDirectMem(MIB, X86::EAX);
+    MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
   }
=20
   MI->eraseFromParent(); // The pseudo instruction is gone now.
@@ -11966,30 +12414,14 @@
 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
                                                MachineBasicBlock *BB) cons=
t {
   switch (MI->getOpcode()) {
-  default: assert(0 && "Unexpected instr type to insert");
+  default: llvm_unreachable("Unexpected instr type to insert");
   case X86::TAILJMPd64:
   case X86::TAILJMPr64:
   case X86::TAILJMPm64:
-    assert(0 && "TAILJMP64 would not be touched here.");
+    llvm_unreachable("TAILJMP64 would not be touched here.");
   case X86::TCRETURNdi64:
   case X86::TCRETURNri64:
   case X86::TCRETURNmi64:
-    // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
-    // On AMD64, additional defs should be added before register allocatio=
n.
-    if (!Subtarget->isTargetWin64()) {
-      MI->addRegisterDefined(X86::RSI);
-      MI->addRegisterDefined(X86::RDI);
-      MI->addRegisterDefined(X86::XMM6);
-      MI->addRegisterDefined(X86::XMM7);
-      MI->addRegisterDefined(X86::XMM8);
-      MI->addRegisterDefined(X86::XMM9);
-      MI->addRegisterDefined(X86::XMM10);
-      MI->addRegisterDefined(X86::XMM11);
-      MI->addRegisterDefined(X86::XMM12);
-      MI->addRegisterDefined(X86::XMM13);
-      MI->addRegisterDefined(X86::XMM14);
-      MI->addRegisterDefined(X86::XMM15);
-    }
     return BB;
   case X86::WIN_ALLOCA:
     return EmitLoweredWinAlloca(MI, BB);
@@ -12294,11 +12726,11 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
-                                                       const APInt &Mask,
                                                        APInt &KnownZero,
                                                        APInt &KnownOne,
                                                        const SelectionDAG =
&DAG,
                                                        unsigned Depth) con=
st {
+  unsigned BitWidth =3D KnownZero.getBitWidth();
   unsigned Opc =3D Op.getOpcode();
   assert((Opc >=3D ISD::BUILTIN_OP_END ||
           Opc =3D=3D ISD::INTRINSIC_WO_CHAIN ||
@@ -12307,7 +12739,7 @@
          "Should use MaskedValueIsZero if you don't know whether Op"
          " is a target node!");
=20
-  KnownZero =3D KnownOne =3D APInt(Mask.getBitWidth(), 0);   // Don't know=
 anything.
+  KnownZero =3D KnownOne =3D APInt(BitWidth, 0);   // Don't know anything.
   switch (Opc) {
   default: break;
   case X86ISD::ADD:
@@ -12326,8 +12758,7 @@
       break;
     // Fallthrough
   case X86ISD::SETCC:
-    KnownZero |=3D APInt::getHighBitsSet(Mask.getBitWidth(),
-                                       Mask.getBitWidth() - 1);
+    KnownZero |=3D APInt::getHighBitsSet(BitWidth, BitWidth - 1);
     break;
   case ISD::INTRINSIC_WO_CHAIN: {
     unsigned IntId =3D cast<ConstantSDNode>(Op.getOperand(0))->getZExtValu=
e();
@@ -12339,18 +12770,20 @@
     case Intrinsic::x86_sse2_movmsk_pd:
     case Intrinsic::x86_avx_movmsk_pd_256:
     case Intrinsic::x86_mmx_pmovmskb:
-    case Intrinsic::x86_sse2_pmovmskb_128: {
+    case Intrinsic::x86_sse2_pmovmskb_128:
+    case Intrinsic::x86_avx2_pmovmskb: {
       // High bits of movmskp{s|d}, pmovmskb are known zero.
       switch (IntId) {
+        default: llvm_unreachable("Impossible intrinsic");  // Can't reach=
 here.
         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits =3D 4; break;
         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits =3D 8; break;
         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits =3D 2; break;
         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits =3D 4; break;
         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits =3D 8; break;
         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits =3D 16; break;
-      }
-      KnownZero =3D APInt::getHighBitsSet(Mask.getBitWidth(),
-                                        Mask.getBitWidth() - NumLoBits);
+        case Intrinsic::x86_avx2_pmovmskb:      NumLoBits =3D 32; break;
+      }
+      KnownZero =3D APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
       break;
     }
     }
@@ -12418,7 +12851,8 @@
=20
 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vecto=
rs.
 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
-                                        TargetLowering::DAGCombinerInfo &D=
CI) {
+                                        TargetLowering::DAGCombinerInfo &D=
CI,
+                                        const X86Subtarget* Subtarget) {
   DebugLoc dl =3D N->getDebugLoc();
   ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
   SDValue V1 =3D SVOp->getOperand(0);
@@ -12454,9 +12888,23 @@
           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
         return SDValue();
=20
+    // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
+    if (LoadSDNode *Ld =3D dyn_cast<LoadSDNode>(V1.getOperand(0))) {
+      SDVTList Tys =3D DAG.getVTList(MVT::v4i64, MVT::Other);
+      SDValue Ops[] =3D { Ld->getChain(), Ld->getBasePtr() };
+      SDValue ResNode =3D
+        DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
+                                Ld->getMemoryVT(),
+                                Ld->getPointerInfo(),
+                                Ld->getAlignment(),
+                                false/*isVolatile*/, true/*ReadMem*/,
+                                false/*WriteMem*/);
+      return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
+    }=20
+
     // Emit a zeroed vector and insert the desired subvector on its
     // first half.
-    SDValue Zeros =3D getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
+    SDValue Zeros =3D getZeroVector(VT, Subtarget, DAG, dl);
     SDValue InsV =3D Insert128BitVector(Zeros, V1.getOperand(0),
                          DAG.getConstant(0, MVT::i32), DAG, dl);
     return DCI.CombineTo(N, InsV);
@@ -12501,7 +12949,7 @@
   // Combine 256-bit vector shuffles. This is only profitable when in AVX =
mode
   if (Subtarget->hasAVX() && VT.getSizeInBits() =3D=3D 256 &&
       N->getOpcode() =3D=3D ISD::VECTOR_SHUFFLE)
-    return PerformShuffleCombine256(N, DAG, DCI);
+    return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
=20
   // Only handle 128 wide vector from here on.
   if (VT.getSizeInBits() !=3D 128)
@@ -12517,11 +12965,185 @@
   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
 }
=20
+
+/// PerformTruncateCombine - Converts truncate operation to
+/// a sequence of vector shuffle operations.
+/// It is possible when we truncate 256-bit vector to 128-bit vector
+
+SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG =
&DAG,=20
+                                                  DAGCombinerInfo &DCI) co=
nst {
+  if (!DCI.isBeforeLegalizeOps())
+    return SDValue();
+
+  if (!Subtarget->hasAVX()) return SDValue();
+
+  EVT VT =3D N->getValueType(0);
+  SDValue Op =3D N->getOperand(0);
+  EVT OpVT =3D Op.getValueType();
+  DebugLoc dl =3D N->getDebugLoc();
+
+  if ((VT =3D=3D MVT::v4i32) && (OpVT =3D=3D MVT::v4i64)) {
+
+    SDValue OpLo =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, O=
p,
+                          DAG.getIntPtrConstant(0));
+
+    SDValue OpHi =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, O=
p,
+                          DAG.getIntPtrConstant(2));
+
+    OpLo =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
+    OpHi =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
+
+    // PSHUFD
+    int ShufMask1[] =3D {0, 2, 0, 0};
+
+    OpLo =3D DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT),
+                                ShufMask1);
+    OpHi =3D DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT),
+                                ShufMask1);
+
+    // MOVLHPS
+    int ShufMask2[] =3D {0, 1, 4, 5};
+
+    return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
+  }
+  if ((VT =3D=3D MVT::v8i16) && (OpVT =3D=3D MVT::v8i32)) {
+
+    SDValue OpLo =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, O=
p,
+                          DAG.getIntPtrConstant(0));
+
+    SDValue OpHi =3D DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, O=
p,
+                          DAG.getIntPtrConstant(4));
+
+    OpLo =3D DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
+    OpHi =3D DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
+
+    // PSHUFB
+    int ShufMask1[] =3D {0,  1,  4,  5,  8,  9, 12, 13,=20
+                      -1, -1, -1, -1, -1, -1, -1, -1};
+
+    OpLo =3D DAG.getVectorShuffle(MVT::v16i8, dl, OpLo,
+                                DAG.getUNDEF(MVT::v16i8),
+                                ShufMask1);
+    OpHi =3D DAG.getVectorShuffle(MVT::v16i8, dl, OpHi,
+                                DAG.getUNDEF(MVT::v16i8),
+                                ShufMask1);
+
+    OpLo =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
+    OpHi =3D DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
+
+    // MOVLHPS
+    int ShufMask2[] =3D {0, 1, 4, 5};
+
+    SDValue res =3D DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufM=
ask2);
+    return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
+  }
+
+  return SDValue();
+}
+
+/// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a ta=
rget
+/// specific shuffle of a load can be folded into a single element load.
+/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
+/// shuffles have been customed lowered so we need to handle those here.
+static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &D=
AG,
+                                         TargetLowering::DAGCombinerInfo &=
DCI) {
+  if (DCI.isBeforeLegalizeOps())
+    return SDValue();
+
+  SDValue InVec =3D N->getOperand(0);
+  SDValue EltNo =3D N->getOperand(1);
+
+  if (!isa<ConstantSDNode>(EltNo))
+    return SDValue();
+
+  EVT VT =3D InVec.getValueType();
+
+  bool HasShuffleIntoBitcast =3D false;
+  if (InVec.getOpcode() =3D=3D ISD::BITCAST) {
+    // Don't duplicate a load with other uses.
+    if (!InVec.hasOneUse())
+      return SDValue();
+    EVT BCVT =3D InVec.getOperand(0).getValueType();
+    if (BCVT.getVectorNumElements() !=3D VT.getVectorNumElements())
+      return SDValue();
+    InVec =3D InVec.getOperand(0);
+    HasShuffleIntoBitcast =3D true;
+  }
+
+  if (!isTargetShuffle(InVec.getOpcode()))
+    return SDValue();
+
+  // Don't duplicate a load with other uses.
+  if (!InVec.hasOneUse())
+    return SDValue();
+
+  SmallVector<int, 16> ShuffleMask;
+  bool UnaryShuffle;
+  if (!getTargetShuffleMask(InVec.getNode(), VT, ShuffleMask, UnaryShuffle=
))
+    return SDValue();
+
+  // Select the input vector, guarding against out of range extract vector.
+  unsigned NumElems =3D VT.getVectorNumElements();
+  int Elt =3D cast<ConstantSDNode>(EltNo)->getZExtValue();
+  int Idx =3D (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
+  SDValue LdNode =3D (Idx < (int)NumElems) ? InVec.getOperand(0)
+                                         : InVec.getOperand(1);
+
+  // If inputs to shuffle are the same for both ops, then allow 2 uses
+  unsigned AllowedUses =3D InVec.getOperand(0) =3D=3D InVec.getOperand(1) =
? 2 : 1;
+
+  if (LdNode.getOpcode() =3D=3D ISD::BITCAST) {
+    // Don't duplicate a load with other uses.
+    if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
+      return SDValue();
+
+    AllowedUses =3D 1; // only allow 1 load use if we have a bitcast
+    LdNode =3D LdNode.getOperand(0);
+  }
+
+  if (!ISD::isNormalLoad(LdNode.getNode()))
+    return SDValue();
+
+  LoadSDNode *LN0 =3D cast<LoadSDNode>(LdNode);
+
+  if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
+    return SDValue();
+
+  if (HasShuffleIntoBitcast) {
+    // If there's a bitcast before the shuffle, check if the load type and
+    // alignment is valid.
+    unsigned Align =3D LN0->getAlignment();
+    const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
+    unsigned NewAlign =3D TLI.getTargetData()->
+      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
+
+    if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
+      return SDValue();
+  }
+
+  // All checks match so transform back to vector_shuffle so that DAG comb=
iner
+  // can finish the job
+  DebugLoc dl =3D N->getDebugLoc();
+
+  // Create shuffle node taking into account the case that its a unary shu=
ffle
+  SDValue Shuffle =3D (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand=
(1);
+  Shuffle =3D DAG.getVectorShuffle(InVec.getValueType(), dl,
+                                 InVec.getOperand(0), Shuffle,
+                                 &ShuffleMask[0]);
+  Shuffle =3D DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
+  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuf=
fle,
+                     EltNo);
+}
+
 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
 /// generation and convert it from being a bunch of shuffles and extracts
 /// to a simple store and scalar loads to extract the elements.
 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &D=
AG,
-                                                const TargetLowering &TLI)=
 {
+                                         TargetLowering::DAGCombinerInfo &=
DCI) {
+  SDValue NewOp =3D XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
+  if (NewOp.getNode())
+    return NewOp;
+
   SDValue InputVector =3D N->getOperand(0);
=20
   // Only operate on vectors of 4 elements, where the alternative shuffling
@@ -12582,6 +13204,7 @@
     unsigned EltSize =3D
         InputVector.getValueType().getVectorElementType().getSizeInBits()/=
8;
     uint64_t Offset =3D EltSize * cast<ConstantSDNode>(Idx)->getZExtValue(=
);
+    const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
     SDValue OffsetVal =3D DAG.getConstant(Offset, TLI.getPointerTy());
=20
     SDValue ScalarAddr =3D DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
@@ -12590,7 +13213,7 @@
     // Load the scalar.
     SDValue LoadScalar =3D DAG.getLoad(Extract->getValueType(0), dl, Ch,
                                      ScalarAddr, MachinePointerInfo(),
-                                     false, false, 0);
+                                     false, false, false, 0);
=20
     // Replace the exact with the load.
     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
@@ -12603,7 +13226,10 @@
 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and V=
SELECT
 /// nodes.
 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
+                                    TargetLowering::DAGCombinerInfo &DCI,
                                     const X86Subtarget *Subtarget) {
+
+
   DebugLoc DL =3D N->getDebugLoc();
   SDValue Cond =3D N->getOperand(0);
   // Get the LHS/RHS of the select.
@@ -12617,7 +13243,7 @@
   // ignored in unsafe-math mode).
   if (Cond.getOpcode() =3D=3D ISD::SETCC && VT.isFloatingPoint() &&
       VT !=3D MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
-      (Subtarget->hasXMMInt() ||
+      (Subtarget->hasSSE2() ||
        (Subtarget->hasSSE1() && VT.getScalarType() =3D=3D MVT::f32))) {
     ISD::CondCode CC =3D cast<CondCodeSDNode>(Cond.getOperand(2))->get();
=20
@@ -12632,7 +13258,7 @@
         // the operands would cause it to handle comparisons between posit=
ive
         // and negative zero incorrectly.
         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
-          if (!UnsafeFPMath &&
+          if (!DAG.getTarget().Options.UnsafeFPMath &&
               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
             break;
           std::swap(LHS, RHS);
@@ -12642,7 +13268,7 @@
       case ISD::SETOLE:
         // Converting this to a min would handle comparisons between posit=
ive
         // and negative zero incorrectly.
-        if (!UnsafeFPMath &&
+        if (!DAG.getTarget().Options.UnsafeFPMath &&
             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
           break;
         Opcode =3D X86ISD::FMIN;
@@ -12660,7 +13286,7 @@
       case ISD::SETOGE:
         // Converting this to a max would handle comparisons between posit=
ive
         // and negative zero incorrectly.
-        if (!UnsafeFPMath &&
+        if (!DAG.getTarget().Options.UnsafeFPMath &&
             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
           break;
         Opcode =3D X86ISD::FMAX;
@@ -12670,7 +13296,7 @@
         // the operands would cause it to handle comparisons between posit=
ive
         // and negative zero incorrectly.
         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
-          if (!UnsafeFPMath &&
+          if (!DAG.getTarget().Options.UnsafeFPMath &&
               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
             break;
           std::swap(LHS, RHS);
@@ -12696,7 +13322,7 @@
         // Converting this to a min would handle comparisons between posit=
ive
         // and negative zero incorrectly, and swapping the operands would
         // cause it to handle NaNs incorrectly.
-        if (!UnsafeFPMath &&
+        if (!DAG.getTarget().Options.UnsafeFPMath &&
             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
             break;
@@ -12706,7 +13332,7 @@
         break;
       case ISD::SETUGT:
         // Converting this to a min would handle NaNs incorrectly.
-        if (!UnsafeFPMath &&
+        if (!DAG.getTarget().Options.UnsafeFPMath &&
             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
           break;
         Opcode =3D X86ISD::FMIN;
@@ -12731,7 +13357,7 @@
         // Converting this to a max would handle comparisons between posit=
ive
         // and negative zero incorrectly, and swapping the operands would
         // cause it to handle NaNs incorrectly.
-        if (!UnsafeFPMath &&
+        if (!DAG.getTarget().Options.UnsafeFPMath &&
             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
             break;
@@ -12848,6 +13474,57 @@
       }
   }
=20
+  // Canonicalize max and min:
+  // (x > y) ? x : y -> (x >=3D y) ? x : y
+  // (x < y) ? x : y -> (x <=3D y) ? x : y
+  // This allows use of COND_S / COND_NS (see TranslateX86CC) which elimin=
ates
+  // the need for an extra compare
+  // against zero. e.g.
+  // (x - y) > 0 : (x - y) ? 0 -> (x - y) >=3D 0 : (x - y) ? 0
+  // subl   %esi, %edi
+  // testl  %edi, %edi
+  // movl   $0, %eax
+  // cmovgl %edi, %eax
+  // =3D>
+  // xorl   %eax, %eax
+  // subl   %esi, $edi
+  // cmovsl %eax, %edi
+  if (N->getOpcode() =3D=3D ISD::SELECT && Cond.getOpcode() =3D=3D ISD::SE=
TCC &&
+      DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
+      DAG.isEqualTo(RHS, Cond.getOperand(1))) {
+    ISD::CondCode CC =3D cast<CondCodeSDNode>(Cond.getOperand(2))->get();
+    switch (CC) {
+    default: break;
+    case ISD::SETLT:
+    case ISD::SETGT: {
+      ISD::CondCode NewCC =3D (CC =3D=3D ISD::SETLT) ? ISD::SETLE : ISD::S=
ETGE;
+      Cond =3D DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
+                          Cond.getOperand(0), Cond.getOperand(1), NewCC);
+      return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
+    }
+    }
+  }
+
+  // If we know that this node is legal then we know that it is going to be
+  // matched by one of the SSE/AVX BLEND instructions. These instructions =
only
+  // depend on the highest bit in each word. Try to use SimplifyDemandedBi=
ts
+  // to simplify previous instructions.
+  const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
+  if (N->getOpcode() =3D=3D ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
+      !DCI.isBeforeLegalize() &&
+      TLI.isOperationLegal(ISD::VSELECT, VT)) {
+    unsigned BitWidth =3D Cond.getValueType().getScalarType().getSizeInBit=
s();
+    assert(BitWidth >=3D 8 && BitWidth <=3D 64 && "Invalid mask size");
+    APInt DemandedMask =3D APInt::getHighBitsSet(BitWidth, 1);
+
+    APInt KnownZero, KnownOne;
+    TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
+                                          DCI.isBeforeLegalizeOps());
+    if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
+        TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, =
TLO))
+      DCI.CommitTargetLoweringOpt(TLO);
+  }
+
   return SDValue();
 }
=20
@@ -13042,7 +13719,8 @@
=20
   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
   // since the result of setcc_c is all zero's or all ones.
-  if (N1C && N0.getOpcode() =3D=3D ISD::AND &&
+  if (VT.isInteger() && !VT.isVector() &&
+      N1C && N0.getOpcode() =3D=3D ISD::AND &&
       N0.getOperand(1).getOpcode() =3D=3D ISD::Constant) {
     SDValue N00 =3D N0.getOperand(0);
     if (N00.getOpcode() =3D=3D X86ISD::SETCC_CARRY ||
@@ -13058,26 +13736,46 @@
     }
   }
=20
+
+  // Hardware support for vector shifts is sparse which makes us scalarize=
 the
+  // vector operations in many cases. Also, on sandybridge ADD is faster t=
han
+  // shl.
+  // (shl V, 1) -> add V,V
+  if (isSplatVector(N1.getNode())) {
+    assert(N0.getValueType().isVector() && "Invalid vector shift type");
+    ConstantSDNode *N1C =3D dyn_cast<ConstantSDNode>(N1->getOperand(0));
+    // We shift all of the values by one. In many cases we do not have
+    // hardware support for this operation. This is better expressed as an=
 ADD
+    // of two values.
+    if (N1C && (1 =3D=3D N1C->getZExtValue())) {
+      return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
+    }
+  }
+
   return SDValue();
 }
=20
 /// PerformShiftCombine - Transforms vector shift nodes to use vector shif=
ts
 ///                       when possible.
 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
+                                   TargetLowering::DAGCombinerInfo &DCI,
                                    const X86Subtarget *Subtarget) {
   EVT VT =3D N->getValueType(0);
-  if (!VT.isVector() && VT.isInteger() &&
-      N->getOpcode() =3D=3D ISD::SHL)
-    return PerformSHLCombine(N, DAG);
+  if (N->getOpcode() =3D=3D ISD::SHL) {
+    SDValue V =3D PerformSHLCombine(N, DAG);
+    if (V.getNode()) return V;
+  }
=20
   // On X86 with SSE2 support, we can transform this to a vector shift if
   // all elements are shifted by the same amount.  We can't do this in leg=
alize
   // because the a constant vector is typically transformed to a constant =
pool
   // so we have no knowledge of the shift amount.
-  if (!Subtarget->hasXMMInt())
+  if (!Subtarget->hasSSE2())
     return SDValue();
=20
-  if (VT !=3D MVT::v2i64 && VT !=3D MVT::v4i32 && VT !=3D MVT::v8i16)
+  if (VT !=3D MVT::v2i64 && VT !=3D MVT::v4i32 && VT !=3D MVT::v8i16 &&
+      (!Subtarget->hasAVX2() ||
+       (VT !=3D MVT::v4i64 && VT !=3D MVT::v8i32 && VT !=3D MVT::v16i16)))
     return SDValue();
=20
   SDValue ShAmtOp =3D N->getOperand(1);
@@ -13093,6 +13791,11 @@
       BaseShAmt =3D Arg;
       break;
     }
+    // Handle the case where the build_vector is all undef
+    // FIXME: Should DAG allow this?
+    if (i =3D=3D NumElts)
+      return SDValue();
+
     for (; i !=3D NumElts; ++i) {
       SDValue Arg =3D ShAmtOp.getOperand(i);
       if (Arg.getOpcode() =3D=3D ISD::UNDEF) continue;
@@ -13119,9 +13822,16 @@
            BaseShAmt =3D InVec.getOperand(1);
        }
     }
-    if (BaseShAmt.getNode() =3D=3D 0)
+    if (BaseShAmt.getNode() =3D=3D 0) {
+      // Don't create instructions with illegal types after legalize
+      // types has run.
+      if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
+          !DCI.isBeforeLegalize())
+        return SDValue();
+
       BaseShAmt =3D DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtO=
p,
                               DAG.getIntPtrConstant(0));
+    }
   } else
     return SDValue();
=20
@@ -13136,47 +13846,38 @@
   switch (N->getOpcode()) {
   default:
     llvm_unreachable("Unknown shift opcode!");
-    break;
   case ISD::SHL:
-    if (VT =3D=3D MVT::v2i64)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    if (VT =3D=3D MVT::v4i32)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    if (VT =3D=3D MVT::v8i16)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    break;
+    switch (VT.getSimpleVT().SimpleTy) {
+    default: return SDValue();
+    case MVT::v2i64:
+    case MVT::v4i32:
+    case MVT::v8i16:
+    case MVT::v4i64:
+    case MVT::v8i32:
+    case MVT::v16i16:
+      return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, =
DAG);
+    }
   case ISD::SRA:
-    if (VT =3D=3D MVT::v4i32)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    if (VT =3D=3D MVT::v8i16)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    break;
+    switch (VT.getSimpleVT().SimpleTy) {
+    default: return SDValue();
+    case MVT::v4i32:
+    case MVT::v8i16:
+    case MVT::v8i32:
+    case MVT::v16i16:
+      return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, =
DAG);
+    }
   case ISD::SRL:
-    if (VT =3D=3D MVT::v2i64)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    if (VT =3D=3D MVT::v4i32)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    if (VT =3D=3D  MVT::v8i16)
-      return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
-                         DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT:=
:i32),
-                         ValOp, BaseShAmt);
-    break;
-  }
-  return SDValue();
+    switch (VT.getSimpleVT().SimpleTy) {
+    default: return SDValue();
+    case MVT::v2i64:
+    case MVT::v4i32:
+    case MVT::v8i16:
+    case MVT::v4i64:
+    case MVT::v8i32:
+    case MVT::v16i16:
+      return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, =
DAG);
+    }
+  }
 }
=20
=20
@@ -13190,7 +13891,7 @@
=20
   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
   // we're requiring SSE2 for both.
-  if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
+  if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
     SDValue N0 =3D N->getOperand(0);
     SDValue N1 =3D N->getOperand(1);
     SDValue CMP0 =3D N0->getOperand(1);
@@ -13300,7 +14001,9 @@
=20
   EVT VT =3D N->getValueType(0);
=20
-  // Create ANDN instructions
+  // Create ANDN, BLSI, and BLSR instructions
+  // BLSI is X & (-X)
+  // BLSR is X & (X-1)
   if (Subtarget->hasBMI() && (VT =3D=3D MVT::i32 || VT =3D=3D MVT::i64)) {
     SDValue N0 =3D N->getOperand(0);
     SDValue N1 =3D N->getOperand(1);
@@ -13313,6 +14016,26 @@
     if (N1.getOpcode() =3D=3D ISD::XOR && isAllOnes(N1.getOperand(1)))
       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
=20
+    // Check LHS for neg
+    if (N0.getOpcode() =3D=3D ISD::SUB && N0.getOperand(1) =3D=3D N1 &&
+        isZero(N0.getOperand(0)))
+      return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
+
+    // Check RHS for neg
+    if (N1.getOpcode() =3D=3D ISD::SUB && N1.getOperand(1) =3D=3D N0 &&
+        isZero(N1.getOperand(0)))
+      return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
+
+    // Check LHS for X-1
+    if (N0.getOpcode() =3D=3D ISD::ADD && N0.getOperand(0) =3D=3D N1 &&
+        isAllOnes(N0.getOperand(1)))
+      return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
+
+    // Check RHS for X-1
+    if (N1.getOpcode() =3D=3D ISD::ADD && N1.getOperand(0) =3D=3D N0 &&
+        isAllOnes(N1.getOperand(1)))
+      return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
+
     return SDValue();
   }
=20
@@ -13353,97 +14076,86 @@
     return R;
=20
   EVT VT =3D N->getValueType(0);
-  if (VT !=3D MVT::i16 && VT !=3D MVT::i32 && VT !=3D MVT::i64 && VT !=3D =
MVT::v2i64)
-    return SDValue();
=20
   SDValue N0 =3D N->getOperand(0);
   SDValue N1 =3D N->getOperand(1);
=20
   // look for psign/blend
-  if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
-    if (VT =3D=3D MVT::v2i64) {
-      // Canonicalize pandn to RHS
-      if (N0.getOpcode() =3D=3D X86ISD::ANDNP)
-        std::swap(N0, N1);
-      // or (and (m, x), (pandn m, y))
-      if (N0.getOpcode() =3D=3D ISD::AND && N1.getOpcode() =3D=3D X86ISD::=
ANDNP) {
-        SDValue Mask =3D N1.getOperand(0);
-        SDValue X    =3D N1.getOperand(1);
-        SDValue Y;
-        if (N0.getOperand(0) =3D=3D Mask)
-          Y =3D N0.getOperand(1);
-        if (N0.getOperand(1) =3D=3D Mask)
-          Y =3D N0.getOperand(0);
-
-        // Check to see if the mask appeared in both the AND and ANDNP and
-        if (!Y.getNode())
-          return SDValue();
-
-        // Validate that X, Y, and Mask are BIT_CONVERTS, and see through =
them.
-        if (Mask.getOpcode() !=3D ISD::BITCAST ||
-            X.getOpcode() !=3D ISD::BITCAST ||
-            Y.getOpcode() !=3D ISD::BITCAST)
-          return SDValue();
-
-        // Look through mask bitcast.
+  if (VT =3D=3D MVT::v2i64 || VT =3D=3D MVT::v4i64) {
+    if (!Subtarget->hasSSSE3() ||
+        (VT =3D=3D MVT::v4i64 && !Subtarget->hasAVX2()))
+      return SDValue();
+
+    // Canonicalize pandn to RHS
+    if (N0.getOpcode() =3D=3D X86ISD::ANDNP)
+      std::swap(N0, N1);
+    // or (and (m, y), (pandn m, x))
+    if (N0.getOpcode() =3D=3D ISD::AND && N1.getOpcode() =3D=3D X86ISD::AN=
DNP) {
+      SDValue Mask =3D N1.getOperand(0);
+      SDValue X    =3D N1.getOperand(1);
+      SDValue Y;
+      if (N0.getOperand(0) =3D=3D Mask)
+        Y =3D N0.getOperand(1);
+      if (N0.getOperand(1) =3D=3D Mask)
+        Y =3D N0.getOperand(0);
+
+      // Check to see if the mask appeared in both the AND and ANDNP and
+      if (!Y.getNode())
+        return SDValue();
+
+      // Validate that X, Y, and Mask are BIT_CONVERTS, and see through th=
em.
+      // Look through mask bitcast.
+      if (Mask.getOpcode() =3D=3D ISD::BITCAST)
         Mask =3D Mask.getOperand(0);
-        EVT MaskVT =3D Mask.getValueType();
-
-        // Validate that the Mask operand is a vector sra node.  The sra n=
ode
-        // will be an intrinsic.
-        if (Mask.getOpcode() !=3D ISD::INTRINSIC_WO_CHAIN)
-          return SDValue();
-
-        // FIXME: what to do for bytes, since there is a psignb/pblendvb, =
but
-        // there is no psrai.b
-        switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
-        case Intrinsic::x86_sse2_psrai_w:
-        case Intrinsic::x86_sse2_psrai_d:
-          break;
-        default: return SDValue();
-        }
-
-        // Check that the SRA is all signbits.
-        SDValue SraC =3D Mask.getOperand(2);
-        unsigned SraAmt  =3D cast<ConstantSDNode>(SraC)->getZExtValue();
-        unsigned EltBits =3D MaskVT.getVectorElementType().getSizeInBits();
-        if ((SraAmt + 1) !=3D EltBits)
-          return SDValue();
-
-        DebugLoc DL =3D N->getDebugLoc();
-
-        // Now we know we at least have a plendvb with the mask val.  See =
if
-        // we can form a psignb/w/d.
-        // psign =3D x.type =3D=3D y.type =3D=3D mask.type && y =3D sub(0,=
 x);
+      if (X.getOpcode() =3D=3D ISD::BITCAST)
         X =3D X.getOperand(0);
+      if (Y.getOpcode() =3D=3D ISD::BITCAST)
         Y =3D Y.getOperand(0);
-        if (Y.getOpcode() =3D=3D ISD::SUB && Y.getOperand(1) =3D=3D X &&
-            ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
-            X.getValueType() =3D=3D MaskVT && X.getValueType() =3D=3D Y.ge=
tValueType()){
-          unsigned Opc =3D 0;
-          switch (EltBits) {
-          case 8: Opc =3D X86ISD::PSIGNB; break;
-          case 16: Opc =3D X86ISD::PSIGNW; break;
-          case 32: Opc =3D X86ISD::PSIGND; break;
-          default: break;
-          }
-          if (Opc) {
-            SDValue Sign =3D DAG.getNode(Opc, DL, MaskVT, X, Mask.getOpera=
nd(1));
-            return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
-          }
-        }
-        // PBLENDVB only available on SSE 4.1
-        if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
-          return SDValue();
-
-        X =3D DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
-        Y =3D DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
-        Mask =3D DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
-        Mask =3D DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
-        return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
-      }
-    }
-  }
+
+      EVT MaskVT =3D Mask.getValueType();
+
+      // Validate that the Mask operand is a vector sra node.
+      // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
+      // there is no psrai.b
+      if (Mask.getOpcode() !=3D X86ISD::VSRAI)
+        return SDValue();
+
+      // Check that the SRA is all signbits.
+      SDValue SraC =3D Mask.getOperand(1);
+      unsigned SraAmt  =3D cast<ConstantSDNode>(SraC)->getZExtValue();
+      unsigned EltBits =3D MaskVT.getVectorElementType().getSizeInBits();
+      if ((SraAmt + 1) !=3D EltBits)
+        return SDValue();
+
+      DebugLoc DL =3D N->getDebugLoc();
+
+      // Now we know we at least have a plendvb with the mask val.  See if
+      // we can form a psignb/w/d.
+      // psign =3D x.type =3D=3D y.type =3D=3D mask.type && y =3D sub(0, x=
);
+      if (Y.getOpcode() =3D=3D ISD::SUB && Y.getOperand(1) =3D=3D X &&
+          ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
+          X.getValueType() =3D=3D MaskVT && Y.getValueType() =3D=3D MaskVT=
) {
+        assert((EltBits =3D=3D 8 || EltBits =3D=3D 16 || EltBits =3D=3D 32=
) &&
+               "Unsupported VT for PSIGN");
+        Mask =3D DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand=
(0));
+        return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
+      }
+      // PBLENDVB only available on SSE 4.1
+      if (!Subtarget->hasSSE41())
+        return SDValue();
+
+      EVT BlendVT =3D (VT =3D=3D MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
+
+      X =3D DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
+      Y =3D DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
+      Mask =3D DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
+      Mask =3D DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
+      return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
+    }
+  }
+
+  if (VT !=3D MVT::i16 && VT !=3D MVT::i32 && VT !=3D MVT::i64)
+    return SDValue();
=20
   // fold (or (x << c) | (y >> (64 - c))) =3D=3D> (shld64 x, y, c)
   if (N0.getOpcode() =3D=3D ISD::SRL && N1.getOpcode() =3D=3D ISD::SHL)
@@ -13500,6 +14212,36 @@
   return SDValue();
 }
=20
+// PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
+static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
+                                 TargetLowering::DAGCombinerInfo &DCI,
+                                 const X86Subtarget *Subtarget) {
+  if (DCI.isBeforeLegalizeOps())
+    return SDValue();
+
+  EVT VT =3D N->getValueType(0);
+
+  if (VT !=3D MVT::i32 && VT !=3D MVT::i64)
+    return SDValue();
+
+  assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions=
");
+
+  // Create BLSMSK instructions by finding X ^ (X-1)
+  SDValue N0 =3D N->getOperand(0);
+  SDValue N1 =3D N->getOperand(1);
+  DebugLoc DL =3D N->getDebugLoc();
+
+  if (N0.getOpcode() =3D=3D ISD::ADD && N0.getOperand(0) =3D=3D N1 &&
+      isAllOnes(N0.getOperand(1)))
+    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
+
+  if (N1.getOpcode() =3D=3D ISD::ADD && N1.getOperand(0) =3D=3D N0 &&
+      isAllOnes(N1.getOperand(1)))
+    return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
+
+  return SDValue();
+}
+
 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
                                    const X86Subtarget *Subtarget) {
@@ -13515,7 +14257,8 @@
   // shuffle. We need SSE4 for the shuffles.
   // TODO: It is possible to support ZExt by zeroing the undef values
   // during the shuffle phase or after the shuffle.
-  if (RegVT.isVector() && Ext =3D=3D ISD::EXTLOAD && Subtarget->hasSSE41()=
) {
+  if (RegVT.isVector() && RegVT.isInteger() &&
+      Ext =3D=3D ISD::EXTLOAD && Subtarget->hasSSE41()) {
     assert(MemVT !=3D RegVT && "Cannot extend to the same type");
     assert(MemVT.isVector() && "Must load a vector from memory");
=20
@@ -13553,7 +14296,8 @@
     SDValue ScalarLoad =3D DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
                                   Ld->getBasePtr(),
                                   Ld->getPointerInfo(), Ld->isVolatile(),
-                                  Ld->isNonTemporal(), Ld->getAlignment());
+                                  Ld->isNonTemporal(), Ld->isInvariant(),
+                                  Ld->getAlignment());
=20
     // Insert the word loaded into a vector.
     SDValue ScalarInVector =3D DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
@@ -13561,7 +14305,8 @@
=20
     // Bitcast the loaded value to a vector of the original element type, =
in
     // the size of the target vector type.
-    SDValue SlicedVec =3D DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarI=
nVector);
+    SDValue SlicedVec =3D DAG.getNode(ISD::BITCAST, dl, WideVecVT,
+                                    ScalarInVector);
     unsigned SizeRatio =3D RegSz/MemSz;
=20
     // Redistribute the loaded elements into the different locations.
@@ -13593,7 +14338,7 @@
   SDValue StoredVal =3D St->getOperand(1);
   const TargetLowering &TLI =3D DAG.getTargetLoweringInfo();
=20
-  // If we are saving a concatination of two XMM registers, perform two st=
ores.
+  // If we are saving a concatenation of two XMM registers, perform two st=
ores.
   // This is better in Sandy Bridge cause one 256-bit mem op is done via t=
wo
   // 128-bit ones. If in the future the cost becomes only one memory acces=
s the
   // first version would be better.
@@ -13703,8 +14448,8 @@
=20
   const Function *F =3D DAG.getMachineFunction().getFunction();
   bool NoImplicitFloatOps =3D F->hasFnAttr(Attribute::NoImplicitFloat);
-  bool F64IsLegal =3D !UseSoftFloat && !NoImplicitFloatOps
-                     && Subtarget->hasXMMInt();
+  bool F64IsLegal =3D !DAG.getTarget().Options.UseSoftFloat && !NoImplicit=
FloatOps
+                     && Subtarget->hasSSE2();
   if ((VT.isVector() ||
        (VT =3D=3D MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
       isa<LoadSDNode>(St->getValue()) &&
@@ -13722,7 +14467,7 @@
       Ld =3D cast<LoadSDNode>(St->getChain());
     else if (St->getValue().hasOneUse() &&
              ChainVal->getOpcode() =3D=3D ISD::TokenFactor) {
-      for (unsigned i=3D0, e =3D ChainVal->getNumOperands(); i !=3D e; ++i=
) {
+      for (unsigned i =3D 0, e =3D ChainVal->getNumOperands(); i !=3D e; +=
+i) {
         if (ChainVal->getOperand(i).getNode() =3D=3D LdVal) {
           TokenFactorIndex =3D i;
           Ld =3D cast<LoadSDNode>(St->getValue());
@@ -13749,7 +14494,8 @@
       EVT LdVT =3D Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
       SDValue NewLd =3D DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBas=
ePtr(),
                                   Ld->getPointerInfo(), Ld->isVolatile(),
-                                  Ld->isNonTemporal(), Ld->getAlignment());
+                                  Ld->isNonTemporal(), Ld->isInvariant(),
+                                  Ld->getAlignment());
       SDValue NewChain =3D NewLd.getValue(1);
       if (TokenFactorIndex !=3D -1) {
         Ops.push_back(NewChain);
@@ -13770,10 +14516,11 @@
     SDValue LoLd =3D DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
                                Ld->getPointerInfo(),
                                Ld->isVolatile(), Ld->isNonTemporal(),
-                               Ld->getAlignment());
+                               Ld->isInvariant(), Ld->getAlignment());
     SDValue HiLd =3D DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
                                Ld->getPointerInfo().getWithOffset(4),
                                Ld->isVolatile(), Ld->isNonTemporal(),
+                               Ld->isInvariant(),
                                MinAlign(Ld->getAlignment(), 4));
=20
     SDValue NewChain =3D LoLd.getValue(1);
@@ -13817,7 +14564,7 @@
 /// set to A, RHS to B, and the routine returns 'true'.
 /// Note that the binary operation should have the property that if one of=
 the
 /// operands is UNDEF then the result is UNDEF.
-static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutati=
ve) {
+static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutati=
ve) {
   // Look for the following pattern: if
   //   A =3D < float a0, float a1, float a2, float a3 >
   //   B =3D < float b0, float b1, float b2, float b3 >
@@ -13833,7 +14580,18 @@
     return false;
=20
   EVT VT =3D LHS.getValueType();
-  unsigned N =3D VT.getVectorNumElements();
+
+  assert((VT.is128BitVector() || VT.is256BitVector()) &&
+         "Unsupported vector type for horizontal add/sub");
+
+  // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub=
 to
+  // operate independently on 128-bit lanes.
+  unsigned NumElts =3D VT.getVectorNumElements();
+  unsigned NumLanes =3D VT.getSizeInBits()/128;
+  unsigned NumLaneElts =3D NumElts / NumLanes;
+  assert((NumLaneElts % 2 =3D=3D 0) &&
+         "Vector type should have an even number of elements in each lane"=
);
+  unsigned HalfLaneElts =3D NumLaneElts/2;
=20
   // View LHS in the form
   //   LHS =3D VECTOR_SHUFFLE A, B, LMask
@@ -13842,34 +14600,36 @@
   // NOTE: in what follows a default initialized SDValue represents an UND=
EF of
   // type VT.
   SDValue A, B;
-  SmallVector<int, 8> LMask(N);
+  SmallVector<int, 16> LMask(NumElts);
   if (LHS.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE) {
     if (LHS.getOperand(0).getOpcode() !=3D ISD::UNDEF)
       A =3D LHS.getOperand(0);
     if (LHS.getOperand(1).getOpcode() !=3D ISD::UNDEF)
       B =3D LHS.getOperand(1);
-    cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
+    ArrayRef<int> Mask =3D cast<ShuffleVectorSDNode>(LHS.getNode())->getMa=
sk();
+    std::copy(Mask.begin(), Mask.end(), LMask.begin());
   } else {
     if (LHS.getOpcode() !=3D ISD::UNDEF)
       A =3D LHS;
-    for (unsigned i =3D 0; i !=3D N; ++i)
+    for (unsigned i =3D 0; i !=3D NumElts; ++i)
       LMask[i] =3D i;
   }
=20
   // Likewise, view RHS in the form
   //   RHS =3D VECTOR_SHUFFLE C, D, RMask
   SDValue C, D;
-  SmallVector<int, 8> RMask(N);
+  SmallVector<int, 16> RMask(NumElts);
   if (RHS.getOpcode() =3D=3D ISD::VECTOR_SHUFFLE) {
     if (RHS.getOperand(0).getOpcode() !=3D ISD::UNDEF)
       C =3D RHS.getOperand(0);
     if (RHS.getOperand(1).getOpcode() !=3D ISD::UNDEF)
       D =3D RHS.getOperand(1);
-    cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
+    ArrayRef<int> Mask =3D cast<ShuffleVectorSDNode>(RHS.getNode())->getMa=
sk();
+    std::copy(Mask.begin(), Mask.end(), RMask.begin());
   } else {
     if (RHS.getOpcode() !=3D ISD::UNDEF)
       C =3D RHS;
-    for (unsigned i =3D 0; i !=3D N; ++i)
+    for (unsigned i =3D 0; i !=3D NumElts; ++i)
       RMask[i] =3D i;
   }
=20
@@ -13884,30 +14644,28 @@
   // If A and B occur in reverse order in RHS, then "swap" them (which mea=
ns
   // rewriting the mask).
   if (A !=3D C)
-    for (unsigned i =3D 0; i !=3D N; ++i) {
-      unsigned Idx =3D RMask[i];
-      if (Idx < N)
-        RMask[i] +=3D N;
-      else if (Idx < 2*N)
-        RMask[i] -=3D N;
-    }
+    CommuteVectorShuffleMask(RMask, NumElts);
=20
   // At this point LHS and RHS are equivalent to
   //   LHS =3D VECTOR_SHUFFLE A, B, LMask
   //   RHS =3D VECTOR_SHUFFLE A, B, RMask
   // Check that the masks correspond to performing a horizontal operation.
-  for (unsigned i =3D 0; i !=3D N; ++i) {
-    unsigned LIdx =3D LMask[i], RIdx =3D RMask[i];
+  for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+    int LIdx =3D LMask[i], RIdx =3D RMask[i];
=20
     // Ignore any UNDEF components.
-    if (LIdx >=3D 2*N || RIdx >=3D 2*N || (!A.getNode() && (LIdx < N || RI=
dx < N))
-        || (!B.getNode() && (LIdx >=3D N || RIdx >=3D N)))
+    if (LIdx < 0 || RIdx < 0 ||
+        (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
+        (!B.getNode() && (LIdx >=3D (int)NumElts || RIdx >=3D (int)NumElts=
)))
       continue;
=20
     // Check that successive elements are being operated on.  If not, this=
 is
     // not a horizontal operation.
-    if (!(LIdx =3D=3D 2*i && RIdx =3D=3D 2*i + 1) &&
-        !(isCommutative && LIdx =3D=3D 2*i + 1 && RIdx =3D=3D 2*i))
+    unsigned Src =3D (i/HalfLaneElts) % 2; // each lane is split between s=
rcs
+    unsigned LaneStart =3D (i/NumLaneElts) * NumLaneElts;
+    int Index =3D 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
+    if (!(LIdx =3D=3D Index && RIdx =3D=3D Index + 1) &&
+        !(IsCommutative && LIdx =3D=3D Index + 1 && RIdx =3D=3D Index))
       return false;
   }
=20
@@ -13924,8 +14682,8 @@
   SDValue RHS =3D N->getOperand(1);
=20
   // Try to synthesize horizontal adds from adds of shuffles.
-  if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
-      (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v2f64) &&
+  if (((Subtarget->hasSSE3() && (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v2=
f64)) ||
+       (Subtarget->hasAVX() && (VT =3D=3D MVT::v8f32 || VT =3D=3D MVT::v4f=
64))) &&
       isHorizontalBinOp(LHS, RHS, true))
     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
   return SDValue();
@@ -13939,8 +14697,8 @@
   SDValue RHS =3D N->getOperand(1);
=20
   // Try to synthesize horizontal subs from subs of shuffles.
-  if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
-      (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v2f64) &&
+  if (((Subtarget->hasSSE3() && (VT =3D=3D MVT::v4f32 || VT =3D=3D MVT::v2=
f64)) ||
+       (Subtarget->hasAVX() && (VT =3D=3D MVT::v8f32 || VT =3D=3D MVT::v4f=
64))) &&
       isHorizontalBinOp(LHS, RHS, false))
     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
   return SDValue();
@@ -14006,7 +14764,58 @@
   return SDValue();
 }
=20
-static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
+static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
+                                  TargetLowering::DAGCombinerInfo &DCI,
+                                  const X86Subtarget *Subtarget) {
+  if (!DCI.isBeforeLegalizeOps())
+    return SDValue();
+
+  if (!Subtarget->hasAVX())=20
+    return SDValue();
+
+  // Optimize vectors in AVX mode
+  // Sign extend  v8i16 to v8i32 and
+  //              v4i32 to v4i64
+  //
+  // Divide input vector into two parts
+  // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
+  // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
+  // concat the vectors to original VT
+
+  EVT VT =3D N->getValueType(0);
+  SDValue Op =3D N->getOperand(0);
+  EVT OpVT =3D Op.getValueType();
+  DebugLoc dl =3D N->getDebugLoc();
+
+  if ((VT =3D=3D MVT::v4i64 && OpVT =3D=3D MVT::v4i32) ||
+      (VT =3D=3D MVT::v8i32 && OpVT =3D=3D MVT::v8i16)) {
+
+    unsigned NumElems =3D OpVT.getVectorNumElements();
+    SmallVector<int,8> ShufMask1(NumElems, -1);
+    for (unsigned i =3D 0; i < NumElems/2; i++) ShufMask1[i] =3D i;
+
+    SDValue OpLo =3D DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
+                                        ShufMask1.data());
+
+    SmallVector<int,8> ShufMask2(NumElems, -1);
+    for (unsigned i =3D 0; i < NumElems/2; i++) ShufMask2[i] =3D i + NumEl=
ems/2;
+
+    SDValue OpHi =3D DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
+                                        ShufMask2.data());
+
+    EVT HalfVT =3D EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),=20
+                                  VT.getVectorNumElements()/2);
+
+    OpLo =3D DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);=20
+    OpHi =3D DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
+
+    return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
+  }
+  return SDValue();
+}
+
+static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
+                                  const X86Subtarget *Subtarget) {
   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
   //           (and (i32 x86isd::setcc_carry), 1)
   // This eliminates the zext. This transformation is necessary because
@@ -14014,6 +14823,8 @@
   DebugLoc dl =3D N->getDebugLoc();
   SDValue N0 =3D N->getOperand(0);
   EVT VT =3D N->getValueType(0);
+  EVT OpVT =3D N0.getValueType();
+
   if (N0.getOpcode() =3D=3D ISD::AND &&
       N0.hasOneUse() &&
       N0.getOperand(0).hasOneUse()) {
@@ -14028,6 +14839,37 @@
                                    N00.getOperand(0), N00.getOperand(1)),
                        DAG.getConstant(1, VT));
   }
+  // Optimize vectors in AVX mode:
+  //
+  //   v8i16 -> v8i32
+  //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
+  //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
+  //   Concat upper and lower parts.
+  //
+  //   v4i32 -> v4i64
+  //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
+  //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
+  //   Concat upper and lower parts.
+  //
+  if (Subtarget->hasAVX()) {
+
+    if (((VT =3D=3D MVT::v8i32) && (OpVT =3D=3D MVT::v8i16))  ||
+      ((VT =3D=3D MVT::v4i64) && (OpVT =3D=3D MVT::v4i32)))  {
+
+      SDValue ZeroVec =3D getZeroVector(OpVT, Subtarget, DAG, dl);
+      SDValue OpLo =3D getTargetShuffleNode(X86ISD::UNPCKL, dl, OpVT, N0, =
ZeroVec, DAG);
+      SDValue OpHi =3D getTargetShuffleNode(X86ISD::UNPCKH, dl, OpVT, N0, =
ZeroVec, DAG);
+
+      EVT HVT =3D EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementT=
ype(),=20
+        VT.getVectorNumElements()/2);
+
+      OpLo =3D DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
+      OpHi =3D DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
+
+      return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
+    }
+  }
+
=20
   return SDValue();
 }
@@ -14136,7 +14978,24 @@
                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
 }
=20
-static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
+/// PerformADDCombine - Do target-specific dag combines on integer adds.
+static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
+                                 const X86Subtarget *Subtarget) {
+  EVT VT =3D N->getValueType(0);
+  SDValue Op0 =3D N->getOperand(0);
+  SDValue Op1 =3D N->getOperand(1);
+
+  // Try to synthesize horizontal adds from adds of shuffles.
+  if (((Subtarget->hasSSSE3() && (VT =3D=3D MVT::v8i16 || VT =3D=3D MVT::v=
4i32)) ||
+       (Subtarget->hasAVX2() && (VT =3D=3D MVT::v16i16 || VT =3D=3D MVT::v=
8i32))) &&
+      isHorizontalBinOp(Op0, Op1, true))
+    return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
+
+  return OptimizeConditionalInDecrement(N, DAG);
+}
+
+static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
+                                 const X86Subtarget *Subtarget) {
   SDValue Op0 =3D N->getOperand(0);
   SDValue Op1 =3D N->getOperand(1);
=20
@@ -14158,6 +15017,13 @@
     }
   }
=20
+  // Try to synthesize horizontal adds from adds of shuffles.
+  EVT VT =3D N->getValueType(0);
+  if (((Subtarget->hasSSSE3() && (VT =3D=3D MVT::v8i16 || VT =3D=3D MVT::v=
4i32)) ||
+       (Subtarget->hasAVX2() && (VT =3D=3D MVT::v16i16 || VT =3D=3D MVT::v=
8i32))) &&
+      isHorizontalBinOp(Op0, Op1, true))
+    return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
+
   return OptimizeConditionalInDecrement(N, DAG);
 }
=20
@@ -14167,19 +15033,20 @@
   switch (N->getOpcode()) {
   default: break;
   case ISD::EXTRACT_VECTOR_ELT:
-    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
+    return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
   case ISD::VSELECT:
-  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
+  case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subta=
rget);
   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
-  case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
-  case ISD::SUB:            return PerformSubCombine(N, DAG);
+  case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
+  case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
   case ISD::SHL:
   case ISD::SRA:
-  case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
+  case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtar=
get);
   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarge=
t);
   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget=
);
+  case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarge=
t);
   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
@@ -14190,27 +15057,14 @@
   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
-  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
+  case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, Subtarget);
+  case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarg=
et);
+  case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
-  case X86ISD::SHUFPS:      // Handle all target specific shuffles
-  case X86ISD::SHUFPD:
+  case X86ISD::SHUFP:       // Handle all target specific shuffles
   case X86ISD::PALIGN:
-  case X86ISD::PUNPCKHBW:
-  case X86ISD::PUNPCKHWD:
-  case X86ISD::PUNPCKHDQ:
-  case X86ISD::PUNPCKHQDQ:
-  case X86ISD::UNPCKHPS:
-  case X86ISD::UNPCKHPD:
-  case X86ISD::VUNPCKHPSY:
-  case X86ISD::VUNPCKHPDY:
-  case X86ISD::PUNPCKLBW:
-  case X86ISD::PUNPCKLWD:
-  case X86ISD::PUNPCKLDQ:
-  case X86ISD::PUNPCKLQDQ:
-  case X86ISD::UNPCKLPS:
-  case X86ISD::UNPCKLPD:
-  case X86ISD::VUNPCKLPSY:
-  case X86ISD::VUNPCKLPDY:
+  case X86ISD::UNPCKH:
+  case X86ISD::UNPCKL:
   case X86ISD::MOVHLPS:
   case X86ISD::MOVLHPS:
   case X86ISD::PSHUFD:
@@ -14218,11 +15072,8 @@
   case X86ISD::PSHUFLW:
   case X86ISD::MOVSS:
   case X86ISD::MOVSD:
-  case X86ISD::VPERMILPS:
-  case X86ISD::VPERMILPSY:
-  case X86ISD::VPERMILPD:
-  case X86ISD::VPERMILPDY:
-  case X86ISD::VPERM2F128:
+  case X86ISD::VPERMILP:
+  case X86ISD::VPERM2X128:
   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subta=
rget);
   }
=20
@@ -14330,11 +15181,38 @@
 //                           X86 Inline Assembly Support
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+namespace {
+  // Helper to match a string separated by whitespace.
+  bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
+    s =3D s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
+
+    for (unsigned i =3D 0, e =3D args.size(); i !=3D e; ++i) {
+      StringRef piece(*args[i]);
+      if (!s.startswith(piece)) // Check if the piece matches.
+        return false;
+
+      s =3D s.substr(piece.size());
+      StringRef::size_type pos =3D s.find_first_not_of(" \t");
+      if (pos =3D=3D 0) // We matched a prefix.
+        return false;
+
+      s =3D s.substr(pos);
+    }
+
+    return s.empty();
+  }
+  const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchA=
sm=3D{};
+}
+
 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
   InlineAsm *IA =3D cast<InlineAsm>(CI->getCalledValue());
=20
   std::string AsmStr =3D IA->getAsmString();
=20
+  IntegerType *Ty =3D dyn_cast<IntegerType>(CI->getType());
+  if (!Ty || Ty->getBitWidth() % 16 !=3D 0)
+    return false;
+
   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "=
foo a"
   SmallVector<StringRef, 4> AsmPieces;
   SplitString(AsmStr, AsmPieces, ";\n");
@@ -14342,35 +15220,27 @@
   switch (AsmPieces.size()) {
   default: return false;
   case 1:
-    AsmStr =3D AsmPieces[0];
-    AsmPieces.clear();
-    SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
-
     // FIXME: this should verify that we are targeting a 486 or better.  I=
f not,
-    // we will turn this bswap into something that will be lowered to logi=
cal ops
-    // instead of emitting the bswap asm.  For now, we don't support 486 o=
r lower
-    // so don't worry about this.
+    // we will turn this bswap into something that will be lowered to logi=
cal
+    // ops instead of emitting the bswap asm.  For now, we don't support 4=
86 or
+    // lower so don't worry about this.
     // bswap $0
-    if (AsmPieces.size() =3D=3D 2 &&
-        (AsmPieces[0] =3D=3D "bswap" ||
-         AsmPieces[0] =3D=3D "bswapq" ||
-         AsmPieces[0] =3D=3D "bswapl") &&
-        (AsmPieces[1] =3D=3D "$0" ||
-         AsmPieces[1] =3D=3D "${0:q}")) {
+    if (matchAsm(AsmPieces[0], "bswap", "$0") ||
+        matchAsm(AsmPieces[0], "bswapl", "$0") ||
+        matchAsm(AsmPieces[0], "bswapq", "$0") ||
+        matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
+        matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
+        matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
       // No need to check constraints, nothing other than the equivalent of
       // "=3Dr,0" would be valid here.
-      IntegerType *Ty =3D dyn_cast<IntegerType>(CI->getType());
-      if (!Ty || Ty->getBitWidth() % 16 !=3D 0)
-        return false;
       return IntrinsicLowering::LowerToByteSwap(CI);
     }
+
     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
     if (CI->getType()->isIntegerTy(16) &&
-        AsmPieces.size() =3D=3D 3 &&
-        (AsmPieces[0] =3D=3D "rorw" || AsmPieces[0] =3D=3D "rolw") &&
-        AsmPieces[1] =3D=3D "$$8," &&
-        AsmPieces[2] =3D=3D "${0:w}" &&
-        IA->getConstraintString().compare(0, 5, "=3Dr,0,") =3D=3D 0) {
+        IA->getConstraintString().compare(0, 5, "=3Dr,0,") =3D=3D 0 &&
+        (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
+         matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
       AsmPieces.clear();
       const std::string &ConstraintsStr =3D IA->getConstraintString();
       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
@@ -14379,46 +15249,26 @@
           AsmPieces[0] =3D=3D "~{cc}" &&
           AsmPieces[1] =3D=3D "~{dirflag}" &&
           AsmPieces[2] =3D=3D "~{flags}" &&
-          AsmPieces[3] =3D=3D "~{fpsr}") {
-        IntegerType *Ty =3D dyn_cast<IntegerType>(CI->getType());
-        if (!Ty || Ty->getBitWidth() % 16 !=3D 0)
-          return false;
-        return IntrinsicLowering::LowerToByteSwap(CI);
-      }
+          AsmPieces[3] =3D=3D "~{fpsr}")
+      return IntrinsicLowering::LowerToByteSwap(CI);
     }
     break;
   case 3:
     if (CI->getType()->isIntegerTy(32) &&
-        IA->getConstraintString().compare(0, 5, "=3Dr,0,") =3D=3D 0) {
-      SmallVector<StringRef, 4> Words;
-      SplitString(AsmPieces[0], Words, " \t,");
-      if (Words.size() =3D=3D 3 && Words[0] =3D=3D "rorw" && Words[1] =3D=
=3D "$$8" &&
-          Words[2] =3D=3D "${0:w}") {
-        Words.clear();
-        SplitString(AsmPieces[1], Words, " \t,");
-        if (Words.size() =3D=3D 3 && Words[0] =3D=3D "rorl" && Words[1] =
=3D=3D "$$16" &&
-            Words[2] =3D=3D "$0") {
-          Words.clear();
-          SplitString(AsmPieces[2], Words, " \t,");
-          if (Words.size() =3D=3D 3 && Words[0] =3D=3D "rorw" && Words[1] =
=3D=3D "$$8" &&
-              Words[2] =3D=3D "${0:w}") {
-            AsmPieces.clear();
-            const std::string &ConstraintsStr =3D IA->getConstraintString(=
);
-            SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",=
");
-            std::sort(AsmPieces.begin(), AsmPieces.end());
-            if (AsmPieces.size() =3D=3D 4 &&
-                AsmPieces[0] =3D=3D "~{cc}" &&
-                AsmPieces[1] =3D=3D "~{dirflag}" &&
-                AsmPieces[2] =3D=3D "~{flags}" &&
-                AsmPieces[3] =3D=3D "~{fpsr}") {
-              IntegerType *Ty =3D dyn_cast<IntegerType>(CI->getType());
-              if (!Ty || Ty->getBitWidth() % 16 !=3D 0)
-                return false;
-              return IntrinsicLowering::LowerToByteSwap(CI);
-            }
-          }
-        }
-      }
+        IA->getConstraintString().compare(0, 5, "=3Dr,0,") =3D=3D 0 &&
+        matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
+        matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
+        matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
+      AsmPieces.clear();
+      const std::string &ConstraintsStr =3D IA->getConstraintString();
+      SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
+      std::sort(AsmPieces.begin(), AsmPieces.end());
+      if (AsmPieces.size() =3D=3D 4 &&
+          AsmPieces[0] =3D=3D "~{cc}" &&
+          AsmPieces[1] =3D=3D "~{dirflag}" &&
+          AsmPieces[2] =3D=3D "~{flags}" &&
+          AsmPieces[3] =3D=3D "~{fpsr}")
+        return IntrinsicLowering::LowerToByteSwap(CI);
     }
=20
     if (CI->getType()->isIntegerTy(64)) {
@@ -14427,23 +15277,10 @@
           Constraints[0].Codes.size() =3D=3D 1 && Constraints[0].Codes[0] =
=3D=3D "A" &&
           Constraints[1].Codes.size() =3D=3D 1 && Constraints[1].Codes[0] =
=3D=3D "0") {
         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
-        SmallVector<StringRef, 4> Words;
-        SplitString(AsmPieces[0], Words, " \t");
-        if (Words.size() =3D=3D 2 && Words[0] =3D=3D "bswap" && Words[1] =
=3D=3D "%eax") {
-          Words.clear();
-          SplitString(AsmPieces[1], Words, " \t");
-          if (Words.size() =3D=3D 2 && Words[0] =3D=3D "bswap" && Words[1]=
 =3D=3D "%edx") {
-            Words.clear();
-            SplitString(AsmPieces[2], Words, " \t,");
-            if (Words.size() =3D=3D 3 && Words[0] =3D=3D "xchgl" && Words[=
1] =3D=3D "%eax" &&
-                Words[2] =3D=3D "%edx") {
-              IntegerType *Ty =3D dyn_cast<IntegerType>(CI->getType());
-              if (!Ty || Ty->getBitWidth() % 16 !=3D 0)
-                return false;
-              return IntrinsicLowering::LowerToByteSwap(CI);
-            }
-          }
-        }
+        if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
+            matchAsm(AsmPieces[1], "bswap", "%edx") &&
+            matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
+          return IntrinsicLowering::LowerToByteSwap(CI);
       }
     }
     break;
@@ -14538,7 +15375,8 @@
       break;
   case 'x':
   case 'Y':
-    if ((type->getPrimitiveSizeInBits() =3D=3D 128) && Subtarget->hasXMM())
+    if (((type->getPrimitiveSizeInBits() =3D=3D 128) && Subtarget->hasSSE1=
()) ||
+        ((type->getPrimitiveSizeInBits() =3D=3D 256) && Subtarget->hasAVX(=
)))
       weight =3D CW_Register;
     break;
   case 'I':
@@ -14608,9 +15446,9 @@
   // FP X constraints get lowered to SSE1/2 registers if available, otherw=
ise
   // 'f' like normal targets.
   if (ConstraintVT.isFloatingPoint()) {
-    if (Subtarget->hasXMMInt())
+    if (Subtarget->hasSSE2())
       return "Y";
-    if (Subtarget->hasXMM())
+    if (Subtarget->hasSSE1())
       return "x";
   }
=20
@@ -14816,10 +15654,10 @@
       if (!Subtarget->hasMMX()) break;
       return std::make_pair(0U, X86::VR64RegisterClass);
     case 'Y':   // SSE_REGS if SSE2 allowed
-      if (!Subtarget->hasXMMInt()) break;
+      if (!Subtarget->hasSSE2()) break;
       // FALL THROUGH.
-    case 'x':   // SSE_REGS if SSE1 allowed
-      if (!Subtarget->hasXMM()) break;
+    case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
+      if (!Subtarget->hasSSE1()) break;
=20
       switch (VT.getSimpleVT().SimpleTy) {
       default: break;
@@ -14838,6 +15676,15 @@
       case MVT::v4f32:
       case MVT::v2f64:
         return std::make_pair(0U, X86::VR128RegisterClass);
+      // AVX types.
+      case MVT::v32i8:
+      case MVT::v16i16:
+      case MVT::v8i32:
+      case MVT::v4i64:
+      case MVT::v8f32:
+      case MVT::v4f64:
+        return std::make_pair(0U, X86::VR256RegisterClass);
+       =20
       }
       break;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86IS=
elLowering.h
--- a/head/contrib/llvm/lib/Target/X86/X86ISelLowering.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86ISelLowering.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -172,12 +172,23 @@
       /// ANDNP - Bitwise Logical AND NOT of Packed FP values.
       ANDNP,
=20
-      /// PSIGNB/W/D - Copy integer sign.
-      PSIGNB, PSIGNW, PSIGND,
+      /// PSIGN - Copy integer sign.
+      PSIGN,
=20
-      /// BLEND family of opcodes
+      /// BLENDV - Blend where the selector is an XMM.
       BLENDV,
=20
+      /// BLENDxx - Blend where the selector is an immediate.
+      BLENDPW,
+      BLENDPS,
+      BLENDPD,
+
+      /// HADD - Integer horizontal add.
+      HADD,
+
+      /// HSUB - Integer horizontal sub.
+      HSUB,
+
       /// FHADD - Floating point horizontal add.
       FHADD,
=20
@@ -213,16 +224,26 @@
       // VZEXT_MOVL - Vector move low and zero extend.
       VZEXT_MOVL,
=20
-      // VSHL, VSRL - Vector logical left / right shift.
-      VSHL, VSRL,
+      // VSEXT_MOVL - Vector move low and sign extend.
+      VSEXT_MOVL,
=20
-      // CMPPD, CMPPS - Vector double/float comparison.
-      // CMPPD, CMPPS - Vector double/float comparison.
-      CMPPD, CMPPS,
+      // VSHL, VSRL - 128-bit vector logical left / right shift
+      VSHLDQ, VSRLDQ,
+
+      // VSHL, VSRL, VSRA - Vector shift elements
+      VSHL, VSRL, VSRA,
+
+      // VSHLI, VSRLI, VSRAI - Vector shift elements by immediate
+      VSHLI, VSRLI, VSRAI,
+
+      // CMPP - Vector packed double/float comparison.
+      CMPP,
=20
       // PCMP* - Vector integer comparisons.
-      PCMPEQB, PCMPEQW, PCMPEQD, PCMPEQQ,
-      PCMPGTB, PCMPGTW, PCMPGTD, PCMPGTQ,
+      PCMPEQ, PCMPGT,
+
+      // VPCOM, VPCOMU - XOP Vector integer comparisons.
+      VPCOM, VPCOMU,
=20
       // ADD, SUB, SMUL, etc. - Arithmetic operations with FLAGS results.
       ADD, SUB, ADC, SBB, SMUL,
@@ -230,6 +251,10 @@
=20
       ANDN, // ANDN - Bitwise AND NOT with FLAGS results.
=20
+      BLSI,   // BLSI - Extract lowest set isolated bit
+      BLSMSK, // BLSMSK - Get mask up to lowest set bit
+      BLSR,   // BLSR - Reset lowest set bit
+
       UMUL, // LOW, HI, FLAGS =3D umul LHS, RHS
=20
       // MUL_IMM - X86 specific multiply by immediate.
@@ -246,46 +271,26 @@
       PSHUFD,
       PSHUFHW,
       PSHUFLW,
-      PSHUFHW_LD,
-      PSHUFLW_LD,
-      SHUFPD,
-      SHUFPS,
+      SHUFP,
       MOVDDUP,
       MOVSHDUP,
       MOVSLDUP,
-      MOVSHDUP_LD,
-      MOVSLDUP_LD,
       MOVLHPS,
       MOVLHPD,
       MOVHLPS,
-      MOVHLPD,
       MOVLPS,
       MOVLPD,
       MOVSD,
       MOVSS,
-      UNPCKLPS,
-      UNPCKLPD,
-      VUNPCKLPSY,
-      VUNPCKLPDY,
-      UNPCKHPS,
-      UNPCKHPD,
-      VUNPCKHPSY,
-      VUNPCKHPDY,
-      PUNPCKLBW,
-      PUNPCKLWD,
-      PUNPCKLDQ,
-      PUNPCKLQDQ,
-      PUNPCKHBW,
-      PUNPCKHWD,
-      PUNPCKHDQ,
-      PUNPCKHQDQ,
-      VPERMILPS,
-      VPERMILPSY,
-      VPERMILPD,
-      VPERMILPDY,
-      VPERM2F128,
+      UNPCKL,
+      UNPCKH,
+      VPERMILP,
+      VPERM2X128,
       VBROADCAST,
=20
+      // PMULUDQ - Vector multiply packed unsigned doubleword integers
+      PMULUDQ,
+
       // VASTART_SAVE_XMM_REGS - Save xmm argument registers to the stack,
       // according to %al. An operator is needed so that this can be expan=
ded
       // with control flow.
@@ -299,6 +304,9 @@
       // falls back to heap allocation if not.
       SEG_ALLOCA,
=20
+      // WIN_FTOL - Windows's _ftol2 runtime routine to do fptoui.
+      WIN_FTOL,
+
       // Memory barrier
       MEMBARRIER,
       MFENCE,
@@ -368,75 +376,6 @@
=20
   /// Define some predicates that are used for node matching.
   namespace X86 {
-    /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to PSHU=
FD.
-    bool isPSHUFDMask(ShuffleVectorSDNode *N);
-
-    /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to PSHU=
FD.
-    bool isPSHUFHWMask(ShuffleVectorSDNode *N);
-
-    /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to PSHU=
FD.
-    bool isPSHUFLWMask(ShuffleVectorSDNode *N);
-
-    /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to SHUF=
P*.
-    bool isSHUFPMask(ShuffleVectorSDNode *N);
-
-    /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to MOVH=
LPS.
-    bool isMOVHLPSMask(ShuffleVectorSDNode *N);
-
-    /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonic=
al form
-    /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
-    /// <2, 3, 2, 3>
-    bool isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N);
-
-    /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for MOVLP{S|D}.
-    bool isMOVLPMask(ShuffleVectorSDNode *N);
-
-    /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for MOVHP{S|D}.
-    /// as well as MOVLHPS.
-    bool isMOVLHPSMask(ShuffleVectorSDNode *N);
-
-    /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to UNPC=
KL.
-    bool isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat =3D false);
-
-    /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to UNPC=
KH.
-    bool isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat =3D false);
-
-    /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical=
 form
-    /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
-    /// <0, 0, 1, 1>
-    bool isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N);
-
-    /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical=
 form
-    /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
-    /// <2, 2, 3, 3>
-    bool isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N);
-
-    /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to MOVS=
S,
-    /// MOVSD, and MOVD, i.e. setting the lowest element.
-    bool isMOVLMask(ShuffleVectorSDNode *N);
-
-    /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE opera=
nd
-    /// specifies a shuffle of elements that is suitable for input to MOVS=
HDUP.
-    bool isMOVSHDUPMask(ShuffleVectorSDNode *N, const X86Subtarget *Subtar=
get);
-
-    /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE opera=
nd
-    /// specifies a shuffle of elements that is suitable for input to MOVS=
LDUP.
-    bool isMOVSLDUPMask(ShuffleVectorSDNode *N, const X86Subtarget *Subtar=
get);
-
-    /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
-    /// specifies a shuffle of elements that is suitable for input to MOVD=
DUP.
-    bool isMOVDDUPMask(ShuffleVectorSDNode *N);
-
     /// isVEXTRACTF128Index - Return true if the specified
     /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
     /// suitable for input to VEXTRACTF128.
@@ -447,23 +386,6 @@
     /// suitable for input to VINSERTF128.
     bool isVINSERTF128Index(SDNode *N);
=20
-    /// getShuffleSHUFImmediate - Return the appropriate immediate to shuf=
fle
-    /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SH=
UFP*
-    /// instructions.
-    unsigned getShuffleSHUFImmediate(SDNode *N);
-
-    /// getShufflePSHUFHWImmediate - Return the appropriate immediate to s=
huffle
-    /// the specified VECTOR_SHUFFLE mask with PSHUFHW instruction.
-    unsigned getShufflePSHUFHWImmediate(SDNode *N);
-
-    /// getShufflePSHUFLWImmediate - Return the appropriate immediate to s=
huffle
-    /// the specified VECTOR_SHUFFLE mask with PSHUFLW instruction.
-    unsigned getShufflePSHUFLWImmediate(SDNode *N);
-
-    /// getShufflePALIGNRImmediate - Return the appropriate immediate to s=
huffle
-    /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
-    unsigned getShufflePALIGNRImmediate(SDNode *N);
-
     /// getExtractVEXTRACTF128Immediate - Return the appropriate
     /// immediate to extract the specified EXTRACT_SUBVECTOR index
     /// with VEXTRACTF128 instructions.
@@ -529,7 +451,7 @@
     /// alignment can satisfy any constraint. Similarly if SrcAlign is zer=
o it
     /// means there isn't a need to check it against alignment requirement,
     /// probably because the source does not need to be loaded. If
-    /// 'NonScalarIntSafe' is true, that means it's safe to return a
+    /// 'IsZeroVal' is true, that means it's safe to return a
     /// non-scalar-integer type, e.g. empty string source, constant, or lo=
aded
     /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
     /// constant so it does not need to be loaded.
@@ -537,7 +459,7 @@
     /// target-independent logic.
     virtual EVT
     getOptimalMemOpType(uint64_t Size, unsigned DstAlign, unsigned SrcAlig=
n,
-                        bool NonScalarIntSafe, bool MemcpyStrSrc,
+                        bool IsZeroVal, bool MemcpyStrSrc,
                         MachineFunction &MF) const;
=20
     /// allowsUnalignedMemoryAccesses - Returns true if the target allows
@@ -587,7 +509,6 @@
     /// in Mask are known to be either zero or one and return them in the
     /// KnownZero/KnownOne bitsets.
     virtual void computeMaskedBitsForTargetNode(const SDValue Op,
-                                                const APInt &Mask,
                                                 APInt &KnownZero,
                                                 APInt &KnownOne,
                                                 const SelectionDAG &DAG,
@@ -697,6 +618,18 @@
       (VT =3D=3D MVT::f32 && X86ScalarSSEf32);   // f32 is when SSE1
     }
=20
+    /// isTargetFTOL - Return true if the target uses the MSVC _ftol2 rout=
ine
+    /// for fptoui.
+    bool isTargetFTOL() const {
+      return Subtarget->isTargetWindows() && !Subtarget->is64Bit();
+    }
+
+    /// isIntegerTypeFTOL - Return true if the MSVC _ftol2 routine should =
be
+    /// used for fptoui to the given type.
+    bool isIntegerTypeFTOL(EVT VT) const {
+      return isTargetFTOL() && VT =3D=3D MVT::i64;
+    }
+
     /// createFastISel - This method returns a target specific FastISel ob=
ject,
     /// or null if the target does not support "fast" ISel.
     virtual FastISel *createFastISel(FunctionLoweringInfo &funcInfo) const;
@@ -779,7 +712,8 @@
                                          SelectionDAG &DAG) const;
=20
     std::pair<SDValue,SDValue> FP_TO_INTHelper(SDValue Op, SelectionDAG &D=
AG,
-                                               bool isSigned) const;
+                                               bool isSigned,
+                                               bool isReplace) const;
=20
     SDValue LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
                                    SelectionDAG &DAG) const;
@@ -833,6 +767,7 @@
     SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) const;
+    SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerADD(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) const;
@@ -846,9 +781,12 @@
     SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const;
     SDValue LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const;
+    SDValue PerformTruncateCombine(SDNode* N, SelectionDAG &DAG, DAGCombin=
erInfo &DCI) const;
=20
     // Utility functions to help LowerVECTOR_SHUFFLE
     SDValue LowerVECTOR_SHUFFLEv8i16(SDValue Op, SelectionDAG &DAG) const;
+    SDValue LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const;
+    SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const;
=20
     virtual SDValue
       LowerFormalArguments(SDValue Chain,
@@ -857,8 +795,8 @@
                            DebugLoc dl, SelectionDAG &DAG,
                            SmallVectorImpl<SDValue> &InVals) const;
     virtual SDValue
-      LowerCall(SDValue Chain, SDValue Callee,
-                CallingConv::ID CallConv, bool isVarArg, bool &isTailCall,
+      LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
+                bool isVarArg, bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -872,7 +810,7 @@
                   const SmallVectorImpl<SDValue> &OutVals,
                   DebugLoc dl, SelectionDAG &DAG) const;
=20
-    virtual bool isUsedByReturnOnly(SDNode *N) const;
+    virtual bool isUsedByReturnOnly(SDNode *N, SDValue &Chain) const;
=20
     virtual bool mayBeEmittedAsTailCall(CallInst *CI) const;
=20
@@ -916,7 +854,7 @@
                                                     unsigned cxchgOpc,
                                                     unsigned notOpc,
                                                     unsigned EAXreg,
-                                                    TargetRegisterClass *R=
C,
+                                              const TargetRegisterClass *R=
C,
                                                     bool invSrc =3D false)=
 const;
=20
     MachineBasicBlock *EmitAtomicBit6432WithCustomInserter(
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
str3DNow.td
--- a/head/contrib/llvm/lib/Target/X86/X86Instr3DNow.td	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86Instr3DNow.td	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D- X86Instr3DNow.td - The 3DNow! Instruction Set ------*- tab=
legen -*-=3D=3D=3D//
+//=3D=3D=3D-- X86Instr3DNow.td - The 3DNow! Instruction Set ------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strArithmetic.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrArithmetic.td	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrArithmetic.td	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86InstrArithmetic.td - Integer Arithmetic Instrs ---*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86InstrArithmetic.td - Integer Arithmetic Instrs --*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the integer arithmetic instructions in the X86
@@ -18,22 +18,24 @@
 let neverHasSideEffects =3D 1 in
 def LEA16r   : I<0x8D, MRMSrcMem,
                  (outs GR16:$dst), (ins i32mem:$src),
-                 "lea{w}\t{$src|$dst}, {$dst|$src}", []>, OpSize;
+                 "lea{w}\t{$src|$dst}, {$dst|$src}", [], IIC_LEA_16>, OpSi=
ze;
 let isReMaterializable =3D 1 in
 def LEA32r   : I<0x8D, MRMSrcMem,
                  (outs GR32:$dst), (ins i32mem:$src),
                  "lea{l}\t{$src|$dst}, {$dst|$src}",
-                 [(set GR32:$dst, lea32addr:$src)]>, Requires<[In32BitMode=
]>;
+                 [(set GR32:$dst, lea32addr:$src)], IIC_LEA>,
+                 Requires<[In32BitMode]>;
=20
 def LEA64_32r : I<0x8D, MRMSrcMem,
                   (outs GR32:$dst), (ins lea64_32mem:$src),
                   "lea{l}\t{$src|$dst}, {$dst|$src}",
-                  [(set GR32:$dst, lea32addr:$src)]>, Requires<[In64BitMod=
e]>;
+                  [(set GR32:$dst, lea32addr:$src)], IIC_LEA>,
+                  Requires<[In64BitMode]>;
=20
 let isReMaterializable =3D 1 in
 def LEA64r   : RI<0x8D, MRMSrcMem, (outs GR64:$dst), (ins i64mem:$src),
                   "lea{q}\t{$src|$dst}, {$dst|$src}",
-                  [(set GR64:$dst, lea64addr:$src)]>;
+                  [(set GR64:$dst, lea64addr:$src)], IIC_LEA>;
=20
=20
=20
@@ -51,21 +53,23 @@
                // This probably ought to be moved to a def : Pat<> if the
                // syntax can be accepted.
                [(set AL, (mul AL, GR8:$src)),
-                (implicit EFLAGS)]>;     // AL,AH =3D AL*GR8
+                (implicit EFLAGS)], IIC_MUL8>;     // AL,AH =3D AL*GR8
=20
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX], neverHasSideEffects =3D 1 in
 def MUL16r : I<0xF7, MRM4r, (outs),  (ins GR16:$src),
                "mul{w}\t$src",=20
-               []>, OpSize;    // AX,DX =3D AX*GR16
+               [], IIC_MUL16_REG>, OpSize;    // AX,DX =3D AX*GR16
=20
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX], neverHasSideEffects =3D 1 in
 def MUL32r : I<0xF7, MRM4r, (outs),  (ins GR32:$src),
                "mul{l}\t$src",   // EAX,EDX =3D EAX*GR32
-               [/*(set EAX, EDX, EFLAGS, (X86umul_flag EAX, GR32:$src))*/]=
>;
+               [/*(set EAX, EDX, EFLAGS, (X86umul_flag EAX, GR32:$src))*/],
+               IIC_MUL32_REG>;
 let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX], neverHasSideEffects =3D 1 in
 def MUL64r : RI<0xF7, MRM4r, (outs), (ins GR64:$src),
                 "mul{q}\t$src",          // RAX,RDX =3D RAX*GR64
-                [/*(set RAX, RDX, EFLAGS, (X86umul_flag RAX, GR64:$src))*/=
]>;
+                [/*(set RAX, RDX, EFLAGS, (X86umul_flag RAX, GR64:$src))*/=
],
+                IIC_MUL64>;
=20
 let Defs =3D [AL,EFLAGS,AX], Uses =3D [AL] in
 def MUL8m  : I<0xF6, MRM4m, (outs), (ins i8mem :$src),
@@ -74,50 +78,51 @@
                // This probably ought to be moved to a def : Pat<> if the
                // syntax can be accepted.
                [(set AL, (mul AL, (loadi8 addr:$src))),
-                (implicit EFLAGS)]>;   // AL,AH =3D AL*[mem8]
+                (implicit EFLAGS)], IIC_MUL8>;   // AL,AH =3D AL*[mem8]
=20
 let mayLoad =3D 1, neverHasSideEffects =3D 1 in {
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX] in
 def MUL16m : I<0xF7, MRM4m, (outs), (ins i16mem:$src),
                "mul{w}\t$src",
-               []>, OpSize; // AX,DX =3D AX*[mem16]
+               [], IIC_MUL16_MEM>, OpSize; // AX,DX =3D AX*[mem16]
=20
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX] in
 def MUL32m : I<0xF7, MRM4m, (outs), (ins i32mem:$src),
               "mul{l}\t$src",
-              []>;          // EAX,EDX =3D EAX*[mem32]
-let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX], neverHasSideEffects =3D 1 in
+              [], IIC_MUL32_MEM>;          // EAX,EDX =3D EAX*[mem32]
+let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX] in
 def MUL64m : RI<0xF7, MRM4m, (outs), (ins i64mem:$src),
-                "mul{q}\t$src", []>;         // RAX,RDX =3D RAX*[mem64]
+                "mul{q}\t$src", [], IIC_MUL64>;   // RAX,RDX =3D RAX*[mem6=
4]
 }
=20
 let neverHasSideEffects =3D 1 in {
 let Defs =3D [AL,EFLAGS,AX], Uses =3D [AL] in
-def IMUL8r  : I<0xF6, MRM5r, (outs),  (ins GR8:$src), "imul{b}\t$src", []>;
-              // AL,AH =3D AL*GR8
+def IMUL8r  : I<0xF6, MRM5r, (outs),  (ins GR8:$src), "imul{b}\t$src", [],
+              IIC_IMUL8>; // AL,AH =3D AL*GR8
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX] in
-def IMUL16r : I<0xF7, MRM5r, (outs),  (ins GR16:$src), "imul{w}\t$src", []=
>,
-              OpSize;    // AX,DX =3D AX*GR16
+def IMUL16r : I<0xF7, MRM5r, (outs),  (ins GR16:$src), "imul{w}\t$src", [],
+              IIC_IMUL16_RR>, OpSize;    // AX,DX =3D AX*GR16
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX] in
-def IMUL32r : I<0xF7, MRM5r, (outs),  (ins GR32:$src), "imul{l}\t$src", []=
>;
-              // EAX,EDX =3D EAX*GR32
-let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX], neverHasSideEffects =3D 1 in
-def IMUL64r : RI<0xF7, MRM5r, (outs), (ins GR64:$src), "imul{q}\t$src", []=
>;
-              // RAX,RDX =3D RAX*GR64
+def IMUL32r : I<0xF7, MRM5r, (outs),  (ins GR32:$src), "imul{l}\t$src", [],
+              IIC_IMUL32_RR>; // EAX,EDX =3D EAX*GR32
+let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX] in
+def IMUL64r : RI<0xF7, MRM5r, (outs), (ins GR64:$src), "imul{q}\t$src", [],
+              IIC_IMUL64_RR>; // RAX,RDX =3D RAX*GR64
=20
 let mayLoad =3D 1 in {
 let Defs =3D [AL,EFLAGS,AX], Uses =3D [AL] in
 def IMUL8m  : I<0xF6, MRM5m, (outs), (ins i8mem :$src),
-                "imul{b}\t$src", []>;    // AL,AH =3D AL*[mem8]
+                "imul{b}\t$src", [], IIC_IMUL8>;    // AL,AH =3D AL*[mem8]
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX] in
 def IMUL16m : I<0xF7, MRM5m, (outs), (ins i16mem:$src),
-                "imul{w}\t$src", []>, OpSize; // AX,DX =3D AX*[mem16]
+                "imul{w}\t$src", [], IIC_IMUL16_MEM>, OpSize;
+                // AX,DX =3D AX*[mem16]
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX] in
 def IMUL32m : I<0xF7, MRM5m, (outs), (ins i32mem:$src),
-                "imul{l}\t$src", []>;  // EAX,EDX =3D EAX*[mem32]
-let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX], neverHasSideEffects =3D 1 in
+                "imul{l}\t$src", [], IIC_IMUL32_MEM>;  // EAX,EDX =3D EAX*=
[mem32]
+let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX] in
 def IMUL64m : RI<0xF7, MRM5m, (outs), (ins i64mem:$src),
-                 "imul{q}\t$src", []>;         // RAX,RDX =3D RAX*[mem64]
+                 "imul{q}\t$src", [], IIC_IMUL64>;  // RAX,RDX =3D RAX*[me=
m64]
 }
 } // neverHasSideEffects
=20
@@ -130,16 +135,19 @@
 def IMUL16rr : I<0xAF, MRMSrcReg, (outs GR16:$dst), (ins GR16:$src1,GR16:$=
src2),
                  "imul{w}\t{$src2, $dst|$dst, $src2}",
                  [(set GR16:$dst, EFLAGS,
-                       (X86smul_flag GR16:$src1, GR16:$src2))]>, TB, OpSiz=
e;
+                       (X86smul_flag GR16:$src1, GR16:$src2))], IIC_IMUL16=
_RR>,
+                       TB, OpSize;
 def IMUL32rr : I<0xAF, MRMSrcReg, (outs GR32:$dst), (ins GR32:$src1,GR32:$=
src2),
                  "imul{l}\t{$src2, $dst|$dst, $src2}",
                  [(set GR32:$dst, EFLAGS,
-                       (X86smul_flag GR32:$src1, GR32:$src2))]>, TB;
+                       (X86smul_flag GR32:$src1, GR32:$src2))], IIC_IMUL32=
_RR>,
+                 TB;
 def IMUL64rr : RI<0xAF, MRMSrcReg, (outs GR64:$dst),
                                    (ins GR64:$src1, GR64:$src2),
                   "imul{q}\t{$src2, $dst|$dst, $src2}",
                   [(set GR64:$dst, EFLAGS,
-                        (X86smul_flag GR64:$src1, GR64:$src2))]>, TB;
+                        (X86smul_flag GR64:$src1, GR64:$src2))], IIC_IMUL6=
4_RR>,
+                 TB;
 }
=20
 // Register-Memory Signed Integer Multiply
@@ -147,18 +155,23 @@
                                   (ins GR16:$src1, i16mem:$src2),
                  "imul{w}\t{$src2, $dst|$dst, $src2}",
                  [(set GR16:$dst, EFLAGS,
-                       (X86smul_flag GR16:$src1, (load addr:$src2)))]>,
+                       (X86smul_flag GR16:$src1, (load addr:$src2)))],
+                       IIC_IMUL16_RM>,
                TB, OpSize;
 def IMUL32rm : I<0xAF, MRMSrcMem, (outs GR32:$dst),=20
                  (ins GR32:$src1, i32mem:$src2),
                  "imul{l}\t{$src2, $dst|$dst, $src2}",
                  [(set GR32:$dst, EFLAGS,
-                       (X86smul_flag GR32:$src1, (load addr:$src2)))]>, TB;
+                       (X86smul_flag GR32:$src1, (load addr:$src2)))],
+                       IIC_IMUL32_RM>,
+               TB;
 def IMUL64rm : RI<0xAF, MRMSrcMem, (outs GR64:$dst),
                                    (ins GR64:$src1, i64mem:$src2),
                   "imul{q}\t{$src2, $dst|$dst, $src2}",
                   [(set GR64:$dst, EFLAGS,
-                        (X86smul_flag GR64:$src1, (load addr:$src2)))]>, T=
B;
+                        (X86smul_flag GR64:$src1, (load addr:$src2)))],
+                        IIC_IMUL64_RM>,
+               TB;
 } // Constraints =3D "$src1 =3D $dst"
=20
 } // Defs =3D [EFLAGS]
@@ -170,33 +183,39 @@
                       (outs GR16:$dst), (ins GR16:$src1, i16imm:$src2),
                       "imul{w}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set GR16:$dst, EFLAGS,=20
-                            (X86smul_flag GR16:$src1, imm:$src2))]>, OpSiz=
e;
+                            (X86smul_flag GR16:$src1, imm:$src2))],=20
+                            IIC_IMUL16_RRI>, OpSize;
 def IMUL16rri8 : Ii8<0x6B, MRMSrcReg,                       // GR16 =3D GR=
16*I8
                      (outs GR16:$dst), (ins GR16:$src1, i16i8imm:$src2),
                      "imul{w}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                      [(set GR16:$dst, EFLAGS,
-                           (X86smul_flag GR16:$src1, i16immSExt8:$src2))]>,
+                           (X86smul_flag GR16:$src1, i16immSExt8:$src2))],
+                           IIC_IMUL16_RRI>,
                  OpSize;
 def IMUL32rri  : Ii32<0x69, MRMSrcReg,                      // GR32 =3D GR=
32*I32
                       (outs GR32:$dst), (ins GR32:$src1, i32imm:$src2),
                       "imul{l}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set GR32:$dst, EFLAGS,
-                            (X86smul_flag GR32:$src1, imm:$src2))]>;
+                            (X86smul_flag GR32:$src1, imm:$src2))],
+                            IIC_IMUL32_RRI>;
 def IMUL32rri8 : Ii8<0x6B, MRMSrcReg,                       // GR32 =3D GR=
32*I8
                      (outs GR32:$dst), (ins GR32:$src1, i32i8imm:$src2),
                      "imul{l}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                      [(set GR32:$dst, EFLAGS,
-                           (X86smul_flag GR32:$src1, i32immSExt8:$src2))]>;
+                           (X86smul_flag GR32:$src1, i32immSExt8:$src2))],
+                           IIC_IMUL32_RRI>;
 def IMUL64rri32 : RIi32<0x69, MRMSrcReg,                    // GR64 =3D GR=
64*I32
                         (outs GR64:$dst), (ins GR64:$src1, i64i32imm:$src2=
),
                         "imul{q}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                        [(set GR64:$dst, EFLAGS,
-                             (X86smul_flag GR64:$src1, i64immSExt32:$src2)=
)]>;
+                             (X86smul_flag GR64:$src1, i64immSExt32:$src2)=
)],
+                             IIC_IMUL64_RRI>;
 def IMUL64rri8 : RIi8<0x6B, MRMSrcReg,                      // GR64 =3D GR=
64*I8
                       (outs GR64:$dst), (ins GR64:$src1, i64i8imm:$src2),
                       "imul{q}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set GR64:$dst, EFLAGS,
-                            (X86smul_flag GR64:$src1, i64immSExt8:$src2))]=
>;
+                            (X86smul_flag GR64:$src1, i64immSExt8:$src2))],
+                            IIC_IMUL64_RRI>;
=20
=20
 // Memory-Integer Signed Integer Multiply
@@ -204,37 +223,43 @@
                       (outs GR16:$dst), (ins i16mem:$src1, i16imm:$src2),
                       "imul{w}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set GR16:$dst, EFLAGS,
-                            (X86smul_flag (load addr:$src1), imm:$src2))]>,
+                            (X86smul_flag (load addr:$src1), imm:$src2))],
+                            IIC_IMUL16_RMI>,
                  OpSize;
 def IMUL16rmi8 : Ii8<0x6B, MRMSrcMem,                       // GR16 =3D [m=
em16]*I8
                      (outs GR16:$dst), (ins i16mem:$src1, i16i8imm :$src2),
                      "imul{w}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                      [(set GR16:$dst, EFLAGS,
                            (X86smul_flag (load addr:$src1),
-                                         i16immSExt8:$src2))]>, OpSize;
+                                         i16immSExt8:$src2))], IIC_IMUL16_=
RMI>,
+                                         OpSize;
 def IMUL32rmi  : Ii32<0x69, MRMSrcMem,                     // GR32 =3D [me=
m32]*I32
                       (outs GR32:$dst), (ins i32mem:$src1, i32imm:$src2),
                       "imul{l}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set GR32:$dst, EFLAGS,
-                            (X86smul_flag (load addr:$src1), imm:$src2))]>;
+                            (X86smul_flag (load addr:$src1), imm:$src2))],
+                            IIC_IMUL32_RMI>;
 def IMUL32rmi8 : Ii8<0x6B, MRMSrcMem,                       // GR32 =3D [m=
em32]*I8
                      (outs GR32:$dst), (ins i32mem:$src1, i32i8imm: $src2),
                      "imul{l}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                      [(set GR32:$dst, EFLAGS,
                            (X86smul_flag (load addr:$src1),
-                                         i32immSExt8:$src2))]>;
+                                         i32immSExt8:$src2))],
+                                         IIC_IMUL32_RMI>;
 def IMUL64rmi32 : RIi32<0x69, MRMSrcMem,                   // GR64 =3D [me=
m64]*I32
                         (outs GR64:$dst), (ins i64mem:$src1, i64i32imm:$sr=
c2),
                         "imul{q}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                         [(set GR64:$dst, EFLAGS,
                               (X86smul_flag (load addr:$src1),
-                                            i64immSExt32:$src2))]>;
+                                            i64immSExt32:$src2))],
+                                            IIC_IMUL64_RMI>;
 def IMUL64rmi8 : RIi8<0x6B, MRMSrcMem,                      // GR64 =3D [m=
em64]*I8
                       (outs GR64:$dst), (ins i64mem:$src1, i64i8imm: $src2=
),
                       "imul{q}\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set GR64:$dst, EFLAGS,
                             (X86smul_flag (load addr:$src1),
-                                          i64immSExt8:$src2))]>;
+                                          i64immSExt8:$src2))],
+                                          IIC_IMUL64_RMI>;
 } // Defs =3D [EFLAGS]
=20
=20
@@ -243,62 +268,62 @@
 // unsigned division/remainder
 let Defs =3D [AL,EFLAGS,AX], Uses =3D [AX] in
 def DIV8r  : I<0xF6, MRM6r, (outs),  (ins GR8:$src),    // AX/r8 =3D AL,AH
-               "div{b}\t$src", []>;
+               "div{b}\t$src", [], IIC_DIV8_REG>;
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX,DX] in
 def DIV16r : I<0xF7, MRM6r, (outs),  (ins GR16:$src),   // DX:AX/r16 =3D A=
X,DX
-               "div{w}\t$src", []>, OpSize;
+               "div{w}\t$src", [], IIC_DIV16>, OpSize;
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX,EDX] in
 def DIV32r : I<0xF7, MRM6r, (outs),  (ins GR32:$src),   // EDX:EAX/r32 =3D=
 EAX,EDX
-               "div{l}\t$src", []>;
+               "div{l}\t$src", [], IIC_DIV32>;
 // RDX:RAX/r64 =3D RAX,RDX
 let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX,RDX] in
 def DIV64r : RI<0xF7, MRM6r, (outs), (ins GR64:$src),
-                "div{q}\t$src", []>;
+                "div{q}\t$src", [], IIC_DIV64>;
=20
 let mayLoad =3D 1 in {
 let Defs =3D [AL,EFLAGS,AX], Uses =3D [AX] in
 def DIV8m  : I<0xF6, MRM6m, (outs), (ins i8mem:$src),   // AX/[mem8] =3D A=
L,AH
-               "div{b}\t$src", []>;
+               "div{b}\t$src", [], IIC_DIV8_MEM>;
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX,DX] in
 def DIV16m : I<0xF7, MRM6m, (outs), (ins i16mem:$src),  // DX:AX/[mem16] =
=3D AX,DX
-               "div{w}\t$src", []>, OpSize;
+               "div{w}\t$src", [], IIC_DIV16>, OpSize;
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX,EDX] in    // EDX:EAX/[mem32]=
 =3D EAX,EDX
 def DIV32m : I<0xF7, MRM6m, (outs), (ins i32mem:$src),
-               "div{l}\t$src", []>;
+               "div{l}\t$src", [], IIC_DIV32>;
 // RDX:RAX/[mem64] =3D RAX,RDX
 let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX,RDX] in
 def DIV64m : RI<0xF7, MRM6m, (outs), (ins i64mem:$src),
-                "div{q}\t$src", []>;
+                "div{q}\t$src", [], IIC_DIV64>;
 }
=20
 // Signed division/remainder.
 let Defs =3D [AL,EFLAGS,AX], Uses =3D [AX] in
 def IDIV8r : I<0xF6, MRM7r, (outs),  (ins GR8:$src),    // AX/r8 =3D AL,AH
-               "idiv{b}\t$src", []>;
+               "idiv{b}\t$src", [], IIC_IDIV8>;
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX,DX] in
 def IDIV16r: I<0xF7, MRM7r, (outs),  (ins GR16:$src),   // DX:AX/r16 =3D A=
X,DX
-               "idiv{w}\t$src", []>, OpSize;
+               "idiv{w}\t$src", [], IIC_IDIV16>, OpSize;
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX,EDX] in
 def IDIV32r: I<0xF7, MRM7r, (outs),  (ins GR32:$src),   // EDX:EAX/r32 =3D=
 EAX,EDX
-               "idiv{l}\t$src", []>;
+               "idiv{l}\t$src", [], IIC_IDIV32>;
 // RDX:RAX/r64 =3D RAX,RDX
 let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX,RDX] in
 def IDIV64r: RI<0xF7, MRM7r, (outs), (ins GR64:$src),
-                "idiv{q}\t$src", []>;
-              =20
-let mayLoad =3D 1, mayLoad =3D 1 in {
+                "idiv{q}\t$src", [], IIC_IDIV64>;
+
+let mayLoad =3D 1 in {
 let Defs =3D [AL,EFLAGS,AX], Uses =3D [AX] in
 def IDIV8m : I<0xF6, MRM7m, (outs), (ins i8mem:$src),   // AX/[mem8] =3D A=
L,AH
-               "idiv{b}\t$src", []>;
+               "idiv{b}\t$src", [], IIC_IDIV8>;
 let Defs =3D [AX,DX,EFLAGS], Uses =3D [AX,DX] in
 def IDIV16m: I<0xF7, MRM7m, (outs), (ins i16mem:$src),  // DX:AX/[mem16] =
=3D AX,DX
-               "idiv{w}\t$src", []>, OpSize;
+               "idiv{w}\t$src", [], IIC_IDIV16>, OpSize;
 let Defs =3D [EAX,EDX,EFLAGS], Uses =3D [EAX,EDX] in    // EDX:EAX/[mem32]=
 =3D EAX,EDX
 def IDIV32m: I<0xF7, MRM7m, (outs), (ins i32mem:$src),=20
-               "idiv{l}\t$src", []>;
+               "idiv{l}\t$src", [], IIC_IDIV32>;
 let Defs =3D [RAX,RDX,EFLAGS], Uses =3D [RAX,RDX] in // RDX:RAX/[mem64] =
=3D RAX,RDX
 def IDIV64m: RI<0xF7, MRM7m, (outs), (ins i64mem:$src),
-                "idiv{q}\t$src", []>;
+                "idiv{q}\t$src", [], IIC_IDIV64>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -312,35 +337,35 @@
 def NEG8r  : I<0xF6, MRM3r, (outs GR8 :$dst), (ins GR8 :$src1),
                "neg{b}\t$dst",
                [(set GR8:$dst, (ineg GR8:$src1)),
-                (implicit EFLAGS)]>;
+                (implicit EFLAGS)], IIC_UNARY_REG>;
 def NEG16r : I<0xF7, MRM3r, (outs GR16:$dst), (ins GR16:$src1),
                "neg{w}\t$dst",
                [(set GR16:$dst, (ineg GR16:$src1)),
-                (implicit EFLAGS)]>, OpSize;
+                (implicit EFLAGS)], IIC_UNARY_REG>, OpSize;
 def NEG32r : I<0xF7, MRM3r, (outs GR32:$dst), (ins GR32:$src1),
                "neg{l}\t$dst",
                [(set GR32:$dst, (ineg GR32:$src1)),
-                (implicit EFLAGS)]>;
+                (implicit EFLAGS)], IIC_UNARY_REG>;
 def NEG64r : RI<0xF7, MRM3r, (outs GR64:$dst), (ins GR64:$src1), "neg{q}\t=
$dst",
                 [(set GR64:$dst, (ineg GR64:$src1)),
-                 (implicit EFLAGS)]>;
+                 (implicit EFLAGS)], IIC_UNARY_REG>;
 } // Constraints =3D "$src1 =3D $dst"
=20
 def NEG8m  : I<0xF6, MRM3m, (outs), (ins i8mem :$dst),
                "neg{b}\t$dst",
                [(store (ineg (loadi8 addr:$dst)), addr:$dst),
-                (implicit EFLAGS)]>;
+                (implicit EFLAGS)], IIC_UNARY_MEM>;
 def NEG16m : I<0xF7, MRM3m, (outs), (ins i16mem:$dst),
                "neg{w}\t$dst",
                [(store (ineg (loadi16 addr:$dst)), addr:$dst),
-                (implicit EFLAGS)]>, OpSize;
+                (implicit EFLAGS)], IIC_UNARY_MEM>, OpSize;
 def NEG32m : I<0xF7, MRM3m, (outs), (ins i32mem:$dst),
                "neg{l}\t$dst",
                [(store (ineg (loadi32 addr:$dst)), addr:$dst),
-                (implicit EFLAGS)]>;
+                (implicit EFLAGS)], IIC_UNARY_MEM>;
 def NEG64m : RI<0xF7, MRM3m, (outs), (ins i64mem:$dst), "neg{q}\t$dst",
                 [(store (ineg (loadi64 addr:$dst)), addr:$dst),
-                 (implicit EFLAGS)]>;
+                 (implicit EFLAGS)], IIC_UNARY_MEM>;
 } // Defs =3D [EFLAGS]
=20
=20
@@ -351,29 +376,30 @@
 let AddedComplexity =3D 15 in {
 def NOT8r  : I<0xF6, MRM2r, (outs GR8 :$dst), (ins GR8 :$src1),
                "not{b}\t$dst",
-               [(set GR8:$dst, (not GR8:$src1))]>;
+               [(set GR8:$dst, (not GR8:$src1))], IIC_UNARY_REG>;
 def NOT16r : I<0xF7, MRM2r, (outs GR16:$dst), (ins GR16:$src1),
                "not{w}\t$dst",
-               [(set GR16:$dst, (not GR16:$src1))]>, OpSize;
+               [(set GR16:$dst, (not GR16:$src1))], IIC_UNARY_REG>, OpSize;
 def NOT32r : I<0xF7, MRM2r, (outs GR32:$dst), (ins GR32:$src1),
                "not{l}\t$dst",
-               [(set GR32:$dst, (not GR32:$src1))]>;
+               [(set GR32:$dst, (not GR32:$src1))], IIC_UNARY_REG>;
 def NOT64r : RI<0xF7, MRM2r, (outs GR64:$dst), (ins GR64:$src1), "not{q}\t=
$dst",
-                [(set GR64:$dst, (not GR64:$src1))]>;
+                [(set GR64:$dst, (not GR64:$src1))], IIC_UNARY_REG>;
 }
 } // Constraints =3D "$src1 =3D $dst"
=20
 def NOT8m  : I<0xF6, MRM2m, (outs), (ins i8mem :$dst),
                "not{b}\t$dst",
-               [(store (not (loadi8 addr:$dst)), addr:$dst)]>;
+               [(store (not (loadi8 addr:$dst)), addr:$dst)], IIC_UNARY_ME=
M>;
 def NOT16m : I<0xF7, MRM2m, (outs), (ins i16mem:$dst),
                "not{w}\t$dst",
-               [(store (not (loadi16 addr:$dst)), addr:$dst)]>, OpSize;
+               [(store (not (loadi16 addr:$dst)), addr:$dst)], IIC_UNARY_M=
EM>,
+               OpSize;
 def NOT32m : I<0xF7, MRM2m, (outs), (ins i32mem:$dst),
                "not{l}\t$dst",
-               [(store (not (loadi32 addr:$dst)), addr:$dst)]>;
+               [(store (not (loadi32 addr:$dst)), addr:$dst)], IIC_UNARY_M=
EM>;
 def NOT64m : RI<0xF7, MRM2m, (outs), (ins i64mem:$dst), "not{q}\t$dst",
-                [(store (not (loadi64 addr:$dst)), addr:$dst)]>;
+                [(store (not (loadi64 addr:$dst)), addr:$dst)], IIC_UNARY_=
MEM>;
 } // CodeSize
=20
 // TODO: inc/dec is slow for P4, but fast for Pentium-M.
@@ -382,19 +408,22 @@
 let CodeSize =3D 2 in
 def INC8r  : I<0xFE, MRM0r, (outs GR8 :$dst), (ins GR8 :$src1),
                "inc{b}\t$dst",
-               [(set GR8:$dst, EFLAGS, (X86inc_flag GR8:$src1))]>;
+               [(set GR8:$dst, EFLAGS, (X86inc_flag GR8:$src1))],
+               IIC_UNARY_REG>;
=20
 let isConvertibleToThreeAddress =3D 1, CodeSize =3D 1 in {  // Can xform i=
nto LEA.
 def INC16r : I<0x40, AddRegFrm, (outs GR16:$dst), (ins GR16:$src1),=20
                "inc{w}\t$dst",
-               [(set GR16:$dst, EFLAGS, (X86inc_flag GR16:$src1))]>,
+               [(set GR16:$dst, EFLAGS, (X86inc_flag GR16:$src1))], IIC_UN=
ARY_REG>,
              OpSize, Requires<[In32BitMode]>;
 def INC32r : I<0x40, AddRegFrm, (outs GR32:$dst), (ins GR32:$src1),=20
                "inc{l}\t$dst",
-               [(set GR32:$dst, EFLAGS, (X86inc_flag GR32:$src1))]>,
+               [(set GR32:$dst, EFLAGS, (X86inc_flag GR32:$src1))],
+               IIC_UNARY_REG>,
              Requires<[In32BitMode]>;
 def INC64r : RI<0xFF, MRM0r, (outs GR64:$dst), (ins GR64:$src1), "inc{q}\t=
$dst",
-                [(set GR64:$dst, EFLAGS, (X86inc_flag GR64:$src1))]>;
+                [(set GR64:$dst, EFLAGS, (X86inc_flag GR64:$src1))],
+                IIC_UNARY_REG>;
 } // isConvertibleToThreeAddress =3D 1, CodeSize =3D 1
=20
=20
@@ -403,19 +432,23 @@
 // Can transform into LEA.
 def INC64_16r : I<0xFF, MRM0r, (outs GR16:$dst), (ins GR16:$src1),=20
                   "inc{w}\t$dst",
-                  [(set GR16:$dst, EFLAGS, (X86inc_flag GR16:$src1))]>,
+                  [(set GR16:$dst, EFLAGS, (X86inc_flag GR16:$src1))],
+                  IIC_UNARY_REG>,
                 OpSize, Requires<[In64BitMode]>;
 def INC64_32r : I<0xFF, MRM0r, (outs GR32:$dst), (ins GR32:$src1),=20
                   "inc{l}\t$dst",
-                  [(set GR32:$dst, EFLAGS, (X86inc_flag GR32:$src1))]>,
+                  [(set GR32:$dst, EFLAGS, (X86inc_flag GR32:$src1))],
+                  IIC_UNARY_REG>,
                 Requires<[In64BitMode]>;
 def DEC64_16r : I<0xFF, MRM1r, (outs GR16:$dst), (ins GR16:$src1),=20
                   "dec{w}\t$dst",
-                  [(set GR16:$dst, EFLAGS, (X86dec_flag GR16:$src1))]>,
+                  [(set GR16:$dst, EFLAGS, (X86dec_flag GR16:$src1))],
+                  IIC_UNARY_REG>,
                 OpSize, Requires<[In64BitMode]>;
 def DEC64_32r : I<0xFF, MRM1r, (outs GR32:$dst), (ins GR32:$src1),=20
                   "dec{l}\t$dst",
-                  [(set GR32:$dst, EFLAGS, (X86dec_flag GR32:$src1))]>,
+                  [(set GR32:$dst, EFLAGS, (X86dec_flag GR32:$src1))],
+                  IIC_UNARY_REG>,
                 Requires<[In64BitMode]>;
 } // isConvertibleToThreeAddress =3D 1, CodeSize =3D 2
=20
@@ -424,37 +457,37 @@
 let CodeSize =3D 2 in {
   def INC8m  : I<0xFE, MRM0m, (outs), (ins i8mem :$dst), "inc{b}\t$dst",
                [(store (add (loadi8 addr:$dst), 1), addr:$dst),
-                (implicit EFLAGS)]>;
+                (implicit EFLAGS)], IIC_UNARY_MEM>;
   def INC16m : I<0xFF, MRM0m, (outs), (ins i16mem:$dst), "inc{w}\t$dst",
                [(store (add (loadi16 addr:$dst), 1), addr:$dst),
-                (implicit EFLAGS)]>,
+                (implicit EFLAGS)], IIC_UNARY_MEM>,
                OpSize, Requires<[In32BitMode]>;
   def INC32m : I<0xFF, MRM0m, (outs), (ins i32mem:$dst), "inc{l}\t$dst",
                [(store (add (loadi32 addr:$dst), 1), addr:$dst),
-                (implicit EFLAGS)]>,
+                (implicit EFLAGS)], IIC_UNARY_MEM>,
                Requires<[In32BitMode]>;
   def INC64m : RI<0xFF, MRM0m, (outs), (ins i64mem:$dst), "inc{q}\t$dst",
                   [(store (add (loadi64 addr:$dst), 1), addr:$dst),
-                   (implicit EFLAGS)]>;
+                   (implicit EFLAGS)], IIC_UNARY_MEM>;
                   =20
 // These are duplicates of their 32-bit counterparts. Only needed so X86 k=
nows
 // how to unfold them.
 // FIXME: What is this for??
 def INC64_16m : I<0xFF, MRM0m, (outs), (ins i16mem:$dst), "inc{w}\t$dst",
                   [(store (add (loadi16 addr:$dst), 1), addr:$dst),
-                    (implicit EFLAGS)]>,
+                    (implicit EFLAGS)], IIC_UNARY_MEM>,
                 OpSize, Requires<[In64BitMode]>;
 def INC64_32m : I<0xFF, MRM0m, (outs), (ins i32mem:$dst), "inc{l}\t$dst",
                   [(store (add (loadi32 addr:$dst), 1), addr:$dst),
-                    (implicit EFLAGS)]>,
+                    (implicit EFLAGS)], IIC_UNARY_MEM>,
                 Requires<[In64BitMode]>;
 def DEC64_16m : I<0xFF, MRM1m, (outs), (ins i16mem:$dst), "dec{w}\t$dst",
                   [(store (add (loadi16 addr:$dst), -1), addr:$dst),
-                    (implicit EFLAGS)]>,
+                    (implicit EFLAGS)], IIC_UNARY_MEM>,
                 OpSize, Requires<[In64BitMode]>;
 def DEC64_32m : I<0xFF, MRM1m, (outs), (ins i32mem:$dst), "dec{l}\t$dst",
                   [(store (add (loadi32 addr:$dst), -1), addr:$dst),
-                    (implicit EFLAGS)]>,
+                    (implicit EFLAGS)], IIC_UNARY_MEM>,
                 Requires<[In64BitMode]>;
 } // CodeSize =3D 2
=20
@@ -462,18 +495,22 @@
 let CodeSize =3D 2 in
 def DEC8r  : I<0xFE, MRM1r, (outs GR8 :$dst), (ins GR8 :$src1),
                "dec{b}\t$dst",
-               [(set GR8:$dst, EFLAGS, (X86dec_flag GR8:$src1))]>;
+               [(set GR8:$dst, EFLAGS, (X86dec_flag GR8:$src1))],
+               IIC_UNARY_REG>;
 let isConvertibleToThreeAddress =3D 1, CodeSize =3D 1 in {   // Can xform =
into LEA.
 def DEC16r : I<0x48, AddRegFrm, (outs GR16:$dst), (ins GR16:$src1),=20
                "dec{w}\t$dst",
-               [(set GR16:$dst, EFLAGS, (X86dec_flag GR16:$src1))]>,
+               [(set GR16:$dst, EFLAGS, (X86dec_flag GR16:$src1))],
+               IIC_UNARY_REG>,
              OpSize, Requires<[In32BitMode]>;
 def DEC32r : I<0x48, AddRegFrm, (outs GR32:$dst), (ins GR32:$src1),=20
                "dec{l}\t$dst",
-               [(set GR32:$dst, EFLAGS, (X86dec_flag GR32:$src1))]>,
+               [(set GR32:$dst, EFLAGS, (X86dec_flag GR32:$src1))],
+               IIC_UNARY_REG>,
              Requires<[In32BitMode]>;
 def DEC64r : RI<0xFF, MRM1r, (outs GR64:$dst), (ins GR64:$src1), "dec{q}\t=
$dst",
-                [(set GR64:$dst, EFLAGS, (X86dec_flag GR64:$src1))]>;
+                [(set GR64:$dst, EFLAGS, (X86dec_flag GR64:$src1))],
+                IIC_UNARY_REG>;
 } // CodeSize =3D 2
 } // Constraints =3D "$src1 =3D $dst"
=20
@@ -481,18 +518,18 @@
 let CodeSize =3D 2 in {
   def DEC8m  : I<0xFE, MRM1m, (outs), (ins i8mem :$dst), "dec{b}\t$dst",
                [(store (add (loadi8 addr:$dst), -1), addr:$dst),
-                (implicit EFLAGS)]>;
+                (implicit EFLAGS)], IIC_UNARY_MEM>;
   def DEC16m : I<0xFF, MRM1m, (outs), (ins i16mem:$dst), "dec{w}\t$dst",
                [(store (add (loadi16 addr:$dst), -1), addr:$dst),
-                (implicit EFLAGS)]>,
+                (implicit EFLAGS)], IIC_UNARY_MEM>,
                OpSize, Requires<[In32BitMode]>;
   def DEC32m : I<0xFF, MRM1m, (outs), (ins i32mem:$dst), "dec{l}\t$dst",
                [(store (add (loadi32 addr:$dst), -1), addr:$dst),
-                (implicit EFLAGS)]>,
+                (implicit EFLAGS)], IIC_UNARY_MEM>,
                Requires<[In32BitMode]>;
   def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
                   [(store (add (loadi64 addr:$dst), -1), addr:$dst),
-                   (implicit EFLAGS)]>;
+                   (implicit EFLAGS)], IIC_UNARY_MEM>;
 } // CodeSize =3D 2
 } // Defs =3D [EFLAGS]
=20
@@ -588,11 +625,13 @@
 /// 4. Infers whether the low bit of the opcode should be 0 (for i8 operat=
ions)
 ///    or 1 (for i16,i32,i64 operations).
 class ITy<bits<8> opcode, Format f, X86TypeInfo typeinfo, dag outs, dag in=
s,=20
-          string mnemonic, string args, list<dag> pattern>
+          string mnemonic, string args, list<dag> pattern,
+          InstrItinClass itin =3D IIC_BIN_NONMEM>
   : I<{opcode{7}, opcode{6}, opcode{5}, opcode{4},
        opcode{3}, opcode{2}, opcode{1}, typeinfo.HasOddOpcode },
       f, outs, ins,=20
-      !strconcat(mnemonic, "{", typeinfo.InstrSuffix, "}\t", args), patter=
n> {
+      !strconcat(mnemonic, "{", typeinfo.InstrSuffix, "}\t", args), patter=
n,
+      itin> {
=20
   // Infer instruction prefixes from type info.
   let hasOpSizePrefix =3D typeinfo.HasOpSizePrefix;
@@ -601,10 +640,11 @@
=20
 // BinOpRR - Instructions like "add reg, reg, reg".
 class BinOpRR<bits<8> opcode, string mnemonic, X86TypeInfo typeinfo,
-              dag outlist, list<dag> pattern, Format f =3D MRMDestReg>
+              dag outlist, list<dag> pattern, InstrItinClass itin,
+              Format f =3D MRMDestReg>
   : ITy<opcode, f, typeinfo, outlist,
         (ins typeinfo.RegClass:$src1, typeinfo.RegClass:$src2),
-        mnemonic, "{$src2, $src1|$src1, $src2}", pattern>;
+        mnemonic, "{$src2, $src1|$src1, $src2}", pattern, itin>;
=20
 // BinOpRR_R - Instructions like "add reg, reg, reg", where the pattern has
 // just a regclass (no eflags) as a result.
@@ -612,7 +652,8 @@
                 SDNode opnode>
   : BinOpRR<opcode, mnemonic, typeinfo, (outs typeinfo.RegClass:$dst),
             [(set typeinfo.RegClass:$dst,
-                  (opnode typeinfo.RegClass:$src1, typeinfo.RegClass:$src2=
))]>;
+                  (opnode typeinfo.RegClass:$src1, typeinfo.RegClass:$src2=
))],
+                  IIC_BIN_NONMEM>;
=20
 // BinOpRR_F - Instructions like "cmp reg, Reg", where the pattern has
 // just a EFLAGS as a result.
@@ -621,7 +662,7 @@
   : BinOpRR<opcode, mnemonic, typeinfo, (outs),
             [(set EFLAGS,
                   (opnode typeinfo.RegClass:$src1, typeinfo.RegClass:$src2=
))],
-            f>;
+            IIC_BIN_NONMEM, f>;
=20
 // BinOpRR_RF - Instructions like "add reg, reg, reg", where the pattern h=
as
 // both a regclass and EFLAGS as a result.
@@ -629,7 +670,8 @@
                  SDNode opnode>
   : BinOpRR<opcode, mnemonic, typeinfo, (outs typeinfo.RegClass:$dst),
             [(set typeinfo.RegClass:$dst, EFLAGS,
-                  (opnode typeinfo.RegClass:$src1, typeinfo.RegClass:$src2=
))]>;
+                  (opnode typeinfo.RegClass:$src1, typeinfo.RegClass:$src2=
))],
+                  IIC_BIN_NONMEM>;
=20
 // BinOpRR_RFF - Instructions like "adc reg, reg, reg", where the pattern =
has
 // both a regclass and EFLAGS as a result, and has EFLAGS as input.
@@ -638,14 +680,14 @@
   : BinOpRR<opcode, mnemonic, typeinfo, (outs typeinfo.RegClass:$dst),
             [(set typeinfo.RegClass:$dst, EFLAGS,
                   (opnode typeinfo.RegClass:$src1, typeinfo.RegClass:$src2,
-                          EFLAGS))]>;
+                          EFLAGS))], IIC_BIN_NONMEM>;
=20
 // BinOpRR_Rev - Instructions like "add reg, reg, reg" (reversed encoding).
 class BinOpRR_Rev<bits<8> opcode, string mnemonic, X86TypeInfo typeinfo>
   : ITy<opcode, MRMSrcReg, typeinfo,
         (outs typeinfo.RegClass:$dst),
         (ins typeinfo.RegClass:$src1, typeinfo.RegClass:$src2),
-        mnemonic, "{$src2, $dst|$dst, $src2}", []> {
+        mnemonic, "{$src2, $dst|$dst, $src2}", [], IIC_BIN_NONMEM> {
   // The disassembler should know about this, but not the asmparser.
   let isCodeGenOnly =3D 1;
 }
@@ -654,7 +696,7 @@
 class BinOpRR_F_Rev<bits<8> opcode, string mnemonic, X86TypeInfo typeinfo>
   : ITy<opcode, MRMSrcReg, typeinfo, (outs),
         (ins typeinfo.RegClass:$src1, typeinfo.RegClass:$src2),
-        mnemonic, "{$src2, $src1|$src1, $src2}", []> {
+        mnemonic, "{$src2, $src1|$src1, $src2}", [], IIC_BIN_NONMEM> {
   // The disassembler should know about this, but not the asmparser.
   let isCodeGenOnly =3D 1;
 }
@@ -664,7 +706,7 @@
               dag outlist, list<dag> pattern>
   : ITy<opcode, MRMSrcMem, typeinfo, outlist,
         (ins typeinfo.RegClass:$src1, typeinfo.MemOperand:$src2),
-        mnemonic, "{$src2, $src1|$src1, $src2}", pattern>;
+        mnemonic, "{$src2, $src1|$src1, $src2}", pattern, IIC_BIN_NONMEM>;
=20
 // BinOpRM_R - Instructions like "add reg, reg, [mem]".
 class BinOpRM_R<bits<8> opcode, string mnemonic, X86TypeInfo typeinfo,
@@ -700,7 +742,7 @@
               Format f, dag outlist, list<dag> pattern>
   : ITy<opcode, f, typeinfo, outlist,
         (ins typeinfo.RegClass:$src1, typeinfo.ImmOperand:$src2),
-        mnemonic, "{$src2, $src1|$src1, $src2}", pattern> {
+        mnemonic, "{$src2, $src1|$src1, $src2}", pattern, IIC_BIN_NONMEM> {
   let ImmT =3D typeinfo.ImmEncoding;
 }
=20
@@ -724,7 +766,6 @@
   : BinOpRI<opcode, mnemonic, typeinfo, f, (outs typeinfo.RegClass:$dst),
             [(set typeinfo.RegClass:$dst, EFLAGS,=20
                 (opnode typeinfo.RegClass:$src1, typeinfo.ImmOperator:$src=
2))]>;
-
 // BinOpRI_RFF - Instructions like "adc reg, reg, imm".
 class BinOpRI_RFF<bits<8> opcode, string mnemonic, X86TypeInfo typeinfo,
                  SDNode opnode, Format f>
@@ -738,7 +779,7 @@
                Format f, dag outlist, list<dag> pattern>
   : ITy<opcode, f, typeinfo, outlist,
         (ins typeinfo.RegClass:$src1, typeinfo.Imm8Operand:$src2),
-        mnemonic, "{$src2, $src1|$src1, $src2}", pattern> {
+        mnemonic, "{$src2, $src1|$src1, $src2}", pattern, IIC_BIN_NONMEM> {
   let ImmT =3D Imm8; // Always 8-bit immediate.
 }
=20
@@ -776,7 +817,7 @@
               list<dag> pattern>
   : ITy<opcode, MRMDestMem, typeinfo,
         (outs), (ins typeinfo.MemOperand:$dst, typeinfo.RegClass:$src),
-        mnemonic, "{$src, $dst|$dst, $src}", pattern>;
+        mnemonic, "{$src, $dst|$dst, $src}", pattern, IIC_BIN_MEM>;
=20
 // BinOpMR_RMW - Instructions like "add [mem], reg".
 class BinOpMR_RMW<bits<8> opcode, string mnemonic, X86TypeInfo typeinfo,
@@ -804,7 +845,7 @@
               Format f, list<dag> pattern, bits<8> opcode =3D 0x80>
   : ITy<opcode, f, typeinfo,
         (outs), (ins typeinfo.MemOperand:$dst, typeinfo.ImmOperand:$src),
-        mnemonic, "{$src, $dst|$dst, $src}", pattern> {
+        mnemonic, "{$src, $dst|$dst, $src}", pattern, IIC_BIN_MEM> {
   let ImmT =3D typeinfo.ImmEncoding;
 }
=20
@@ -815,7 +856,6 @@
             [(store (opnode (typeinfo.VT (load addr:$dst)),
                             typeinfo.ImmOperator:$src), addr:$dst),
              (implicit EFLAGS)]>;
-
 // BinOpMI_RMW_FF - Instructions like "adc [mem], imm".
 class BinOpMI_RMW_FF<string mnemonic, X86TypeInfo typeinfo,
                   SDNode opnode, Format f>
@@ -837,7 +877,7 @@
                Format f, list<dag> pattern>
   : ITy<0x82, f, typeinfo,
         (outs), (ins typeinfo.MemOperand:$dst, typeinfo.Imm8Operand:$src),
-        mnemonic, "{$src, $dst|$dst, $src}", pattern> {
+        mnemonic, "{$src, $dst|$dst, $src}", pattern, IIC_BIN_MEM> {
   let ImmT =3D Imm8; // Always 8-bit immediate.
 }
=20
@@ -1150,7 +1190,7 @@
   // register class is constrained to GR8_NOREX.
   let isPseudo =3D 1 in
   def TEST8ri_NOREX : I<0, Pseudo, (outs), (ins GR8_NOREX:$src, i8imm:$mas=
k),
-                        "", []>;
+                        "", [], IIC_BIN_NONMEM>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1160,14 +1200,39 @@
                     PatFrag ld_frag> {
   def rr : I<0xF2, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
             !strconcat(mnemonic, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}"),
-            [(set RC:$dst, EFLAGS, (X86andn_flag RC:$src1, RC:$src2))]>;
+            [(set RC:$dst, EFLAGS, (X86andn_flag RC:$src1, RC:$src2))],
+            IIC_BIN_NONMEM>;
   def rm : I<0xF2, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, x86memop:$src=
2),
             !strconcat(mnemonic, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}"),
             [(set RC:$dst, EFLAGS,
-             (X86andn_flag RC:$src1, (ld_frag addr:$src2)))]>;
+             (X86andn_flag RC:$src1, (ld_frag addr:$src2)))], IIC_BIN_MEM>;
 }
=20
 let Predicates =3D [HasBMI], Defs =3D [EFLAGS] in {
   defm ANDN32 : bmi_andn<"andn{l}", GR32, i32mem, loadi32>, T8, VEX_4V;
   defm ANDN64 : bmi_andn<"andn{q}", GR64, i64mem, loadi64>, T8, VEX_4V, VE=
X_W;
 }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// MULX Instruction
+//
+multiclass bmi_mulx<string mnemonic, RegisterClass RC, X86MemOperand x86me=
mop> {
+let neverHasSideEffects =3D 1 in {
+  let isCommutable =3D 1 in
+  def rr : I<0xF6, MRMSrcReg, (outs RC:$dst1, RC:$dst2), (ins RC:$src),
+             !strconcat(mnemonic, "\t{$src, $dst2, $dst1|$dst1, $dst2, $sr=
c}"),
+             [], IIC_MUL8>, T8XD, VEX_4V;
+
+  let mayLoad =3D 1 in
+  def rm : I<0xF6, MRMSrcMem, (outs RC:$dst1, RC:$dst2), (ins x86memop:$sr=
c),
+             !strconcat(mnemonic, "\t{$src, $dst2, $dst1|$dst1, $dst2, $sr=
c}"),
+             [], IIC_MUL8>, T8XD, VEX_4V;
+}
+}
+
+let Predicates =3D [HasBMI2] in {
+  let Uses =3D [EDX] in
+    defm MULX32 : bmi_mulx<"mulx{l}", GR32, i32mem>;
+  let Uses =3D [RDX] in
+    defm MULX64 : bmi_mulx<"mulx{q}", GR64, i64mem>, VEX_W;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strBuilder.h
--- a/head/contrib/llvm/lib/Target/X86/X86InstrBuilder.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrBuilder.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -27,7 +27,6 @@
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineMemOperand.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
=20
 namespace llvm {
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strCMovSetCC.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrCMovSetCC.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrCMovSetCC.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86InstrCMovSetCC.td - Conditional Move and SetCC ---*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86InstrCMovSetCC.td - Conditional Move and SetCC --*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the X86 conditional move and set on condition
@@ -21,17 +21,20 @@
       : I<opc, MRMSrcReg, (outs GR16:$dst), (ins GR16:$src1, GR16:$src2),
           !strconcat(Mnemonic, "{w}\t{$src2, $dst|$dst, $src2}"),
           [(set GR16:$dst,
-                (X86cmov GR16:$src1, GR16:$src2, CondNode, EFLAGS))]>,TB,O=
pSize;
+                (X86cmov GR16:$src1, GR16:$src2, CondNode, EFLAGS))],
+                IIC_CMOV16_RR>,TB,OpSize;
     def #NAME#32rr
       : I<opc, MRMSrcReg, (outs GR32:$dst), (ins GR32:$src1, GR32:$src2),
           !strconcat(Mnemonic, "{l}\t{$src2, $dst|$dst, $src2}"),
           [(set GR32:$dst,
-                (X86cmov GR32:$src1, GR32:$src2, CondNode, EFLAGS))]>, TB;
+                (X86cmov GR32:$src1, GR32:$src2, CondNode, EFLAGS))],
+                IIC_CMOV32_RR>, TB;
     def #NAME#64rr
       :RI<opc, MRMSrcReg, (outs GR64:$dst), (ins GR64:$src1, GR64:$src2),
           !strconcat(Mnemonic, "{q}\t{$src2, $dst|$dst, $src2}"),
           [(set GR64:$dst,
-                (X86cmov GR64:$src1, GR64:$src2, CondNode, EFLAGS))]>, TB;
+                (X86cmov GR64:$src1, GR64:$src2, CondNode, EFLAGS))],
+                IIC_CMOV32_RR>, TB;
   }
=20
   let Uses =3D [EFLAGS], Predicates =3D [HasCMov], Constraints =3D "$src1 =
=3D $dst" in {
@@ -39,17 +42,18 @@
       : I<opc, MRMSrcMem, (outs GR16:$dst), (ins GR16:$src1, i16mem:$src2),
           !strconcat(Mnemonic, "{w}\t{$src2, $dst|$dst, $src2}"),
           [(set GR16:$dst, (X86cmov GR16:$src1, (loadi16 addr:$src2),
-                                    CondNode, EFLAGS))]>, TB, OpSize;
+                                    CondNode, EFLAGS))], IIC_CMOV16_RM>,
+                                    TB, OpSize;
     def #NAME#32rm
       : I<opc, MRMSrcMem, (outs GR32:$dst), (ins GR32:$src1, i32mem:$src2),
           !strconcat(Mnemonic, "{l}\t{$src2, $dst|$dst, $src2}"),
           [(set GR32:$dst, (X86cmov GR32:$src1, (loadi32 addr:$src2),
-                                    CondNode, EFLAGS))]>, TB;
+                                    CondNode, EFLAGS))], IIC_CMOV32_RM>, T=
B;
     def #NAME#64rm
       :RI<opc, MRMSrcMem, (outs GR64:$dst), (ins GR64:$src1, i64mem:$src2),
           !strconcat(Mnemonic, "{q}\t{$src2, $dst|$dst, $src2}"),
           [(set GR64:$dst, (X86cmov GR64:$src1, (loadi64 addr:$src2),
-                                    CondNode, EFLAGS))]>, TB;
+                                    CondNode, EFLAGS))], IIC_CMOV32_RM>, T=
B;
   } // Uses =3D [EFLAGS], Predicates =3D [HasCMov], Constraints =3D "$src1=
 =3D $dst"
 } // end multiclass
=20
@@ -78,10 +82,12 @@
   let Uses =3D [EFLAGS] in {
     def r    : I<opc, MRM0r,  (outs GR8:$dst), (ins),
                      !strconcat(Mnemonic, "\t$dst"),
-                     [(set GR8:$dst, (X86setcc OpNode, EFLAGS))]>, TB;
+                     [(set GR8:$dst, (X86setcc OpNode, EFLAGS))],
+                     IIC_SET_R>, TB;
     def m    : I<opc, MRM0m,  (outs), (ins i8mem:$dst),
                      !strconcat(Mnemonic, "\t$dst"),
-                     [(store (X86setcc OpNode, EFLAGS), addr:$dst)]>, TB;
+                     [(store (X86setcc OpNode, EFLAGS), addr:$dst)],
+                     IIC_SET_M>, TB;
   } // Uses =3D [EFLAGS]
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strCompiler.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrCompiler.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrCompiler.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -112,23 +112,39 @@
 // allocated by bumping the stack pointer. Otherwise memory is allocated f=
rom=20
 // the heap.
=20
-let Defs =3D [EAX, ESP, EFLAGS], Uses =3D [ESP, EAX] in
+let Defs =3D [EAX, ESP, EFLAGS], Uses =3D [ESP] in
 def SEG_ALLOCA_32 : I<0, Pseudo, (outs GR32:$dst), (ins GR32:$size),
                       "# variable sized alloca for segmented stacks",
                       [(set GR32:$dst,
                          (X86SegAlloca GR32:$size))]>,
                     Requires<[In32BitMode]>;
=20
-let Defs =3D [RAX, RSP, EFLAGS], Uses =3D [RSP, RAX] in
+let Defs =3D [RAX, RSP, EFLAGS], Uses =3D [RSP] in
 def SEG_ALLOCA_64 : I<0, Pseudo, (outs GR64:$dst), (ins GR64:$size),
                       "# variable sized alloca for segmented stacks",
                       [(set GR64:$dst,
                          (X86SegAlloca GR64:$size))]>,
                     Requires<[In64BitMode]>;
-
 }
=20
+// The MSVC runtime contains an _ftol2 routine for converting floating-poi=
nt
+// to integer values. It has a strange calling convention: the input is
+// popped from the x87 stack, and the return value is given in EDX:EAX. No
+// other registers (aside from flags) are touched.
+// Microsoft toolchains do not support 80-bit precision, so a WIN_FTOL_80
+// variant is unnecessary.
=20
+let Defs =3D [EAX, EDX, EFLAGS], FPForm =3D SpecialFP in {
+  def WIN_FTOL_32 : I<0, Pseudo, (outs), (ins RFP32:$src),
+                      "# win32 fptoui",
+                      [(X86WinFTOL RFP32:$src)]>,
+                    Requires<[In32BitMode]>;
+
+  def WIN_FTOL_64 : I<0, Pseudo, (outs), (ins RFP64:$src),
+                      "# win32 fptoui",
+                      [(X86WinFTOL RFP64:$src)]>,
+                    Requires<[In32BitMode]>;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // EH Pseudo Instructions
@@ -137,7 +153,7 @@
     hasCtrlDep =3D 1, isCodeGenOnly =3D 1 in {
 def EH_RETURN   : I<0xC3, RawFrm, (outs), (ins GR32:$addr),
                     "ret\t#eh_return, addr: $addr",
-                    [(X86ehret GR32:$addr)]>;
+                    [(X86ehret GR32:$addr)], IIC_RET>;
=20
 }
=20
@@ -145,11 +161,29 @@
     hasCtrlDep =3D 1, isCodeGenOnly =3D 1 in {
 def EH_RETURN64   : I<0xC3, RawFrm, (outs), (ins GR64:$addr),
                      "ret\t#eh_return, addr: $addr",
-                     [(X86ehret GR64:$addr)]>;
+                     [(X86ehret GR64:$addr)], IIC_RET>;
=20
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Pseudo instructions used by segmented stacks.
+//
+
+// This is lowered into a RET instruction by MCInstLower.  We need
+// this so that we don't have to have a MachineBasicBlock which ends
+// with a RET and also has successors.
+let isPseudo =3D 1 in {
+def MORESTACK_RET: I<0, Pseudo, (outs), (ins),
+                          "", []>;
+
+// This instruction is lowered to a RET followed by a MOV.  The two
+// instructions are not generated on a higher level since then the
+// verifier sees a MachineBasicBlock ending with a non-terminator.
+def MORESTACK_RET_RESTORE_R10 : I<0, Pseudo, (outs), (ins),
+                                  "", []>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Alias Instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -159,7 +193,7 @@
 let Defs =3D [EFLAGS], isReMaterializable =3D 1, isAsCheapAsAMove =3D 1,
     isCodeGenOnly =3D 1 in {
 def MOV8r0   : I<0x30, MRMInitReg, (outs GR8 :$dst), (ins), "",
-                 [(set GR8:$dst, 0)]>;
+                 [(set GR8:$dst, 0)], IIC_ALU_NONMEM>;
=20
 // We want to rewrite MOV16r0 in terms of MOV32r0, because it's a smaller
 // encoding and avoids a partial-register update sometimes, but doing so
@@ -168,11 +202,11 @@
 // to an MCInst.
 def MOV16r0   : I<0x31, MRMInitReg, (outs GR16:$dst), (ins),
                  "",
-                 [(set GR16:$dst, 0)]>, OpSize;
+                 [(set GR16:$dst, 0)], IIC_ALU_NONMEM>, OpSize;
=20
 // FIXME: Set encoding to pseudo.
 def MOV32r0  : I<0x31, MRMInitReg, (outs GR32:$dst), (ins), "",
-                 [(set GR32:$dst, 0)]>;
+                 [(set GR32:$dst, 0)], IIC_ALU_NONMEM>;
 }
=20
 // We want to rewrite MOV64r0 in terms of MOV32r0, because it's sometimes a
@@ -184,7 +218,7 @@
 let Defs =3D [EFLAGS], isCodeGenOnly=3D1,
     AddedComplexity =3D 1, isReMaterializable =3D 1, isAsCheapAsAMove =3D =
1 in
 def MOV64r0   : I<0x31, MRMInitReg, (outs GR64:$dst), (ins), "",
-                 [(set GR64:$dst, 0)]>;
+                 [(set GR64:$dst, 0)], IIC_ALU_NONMEM>;
=20
 // Materialize i64 constant where top 32-bits are zero. This could theoret=
ically
 // use MOV32ri with a SUBREG_TO_REG to represent the zero-extension, howev=
er
@@ -192,7 +226,8 @@
 let AddedComplexity =3D 1, isReMaterializable =3D 1, isAsCheapAsAMove =3D =
1,
     isCodeGenOnly =3D 1 in
 def MOV64ri64i32 : Ii32<0xB8, AddRegFrm, (outs GR64:$dst), (ins i64i32imm:=
$src),
-                        "", [(set GR64:$dst, i64immZExt32:$src)]>;
+                        "", [(set GR64:$dst, i64immZExt32:$src)],
+                        IIC_ALU_NONMEM>;
=20
 // Use sbb to materialize carry bit.
 let Uses =3D [EFLAGS], Defs =3D [EFLAGS], isCodeGenOnly =3D 1 in {
@@ -202,14 +237,18 @@
 // FIXME: Change these to have encoding Pseudo when X86MCCodeEmitter repla=
ces
 // X86CodeEmitter.
 def SETB_C8r : I<0x18, MRMInitReg, (outs GR8:$dst), (ins), "",
-                 [(set GR8:$dst, (X86setcc_c X86_COND_B, EFLAGS))]>;
+                 [(set GR8:$dst, (X86setcc_c X86_COND_B, EFLAGS))],
+                 IIC_ALU_NONMEM>;
 def SETB_C16r : I<0x19, MRMInitReg, (outs GR16:$dst), (ins), "",
-                 [(set GR16:$dst, (X86setcc_c X86_COND_B, EFLAGS))]>,
+                 [(set GR16:$dst, (X86setcc_c X86_COND_B, EFLAGS))],
+                 IIC_ALU_NONMEM>,
                 OpSize;
 def SETB_C32r : I<0x19, MRMInitReg, (outs GR32:$dst), (ins), "",
-                 [(set GR32:$dst, (X86setcc_c X86_COND_B, EFLAGS))]>;
+                 [(set GR32:$dst, (X86setcc_c X86_COND_B, EFLAGS))],
+                 IIC_ALU_NONMEM>;
 def SETB_C64r : RI<0x19, MRMInitReg, (outs GR64:$dst), (ins), "",
-                 [(set GR64:$dst, (X86setcc_c X86_COND_B, EFLAGS))]>;
+                 [(set GR64:$dst, (X86setcc_c X86_COND_B, EFLAGS))],
+                 IIC_ALU_NONMEM>;
 } // isCodeGenOnly
=20
=20
@@ -262,34 +301,67 @@
 // String Pseudo Instructions
 //
 let Defs =3D [ECX,EDI,ESI], Uses =3D [ECX,EDI,ESI], isCodeGenOnly =3D 1 in=
 {
-def REP_MOVSB : I<0xA4, RawFrm, (outs), (ins), "{rep;movsb|rep movsb}",
-                  [(X86rep_movs i8)]>, REP;
-def REP_MOVSW : I<0xA5, RawFrm, (outs), (ins), "{rep;movsw|rep movsw}",
-                  [(X86rep_movs i16)]>, REP, OpSize;
-def REP_MOVSD : I<0xA5, RawFrm, (outs), (ins), "{rep;movsl|rep movsd}",
-                  [(X86rep_movs i32)]>, REP;
+def REP_MOVSB_32 : I<0xA4, RawFrm, (outs), (ins), "{rep;movsb|rep movsb}",
+                    [(X86rep_movs i8)], IIC_REP_MOVS>, REP,
+                   Requires<[In32BitMode]>;
+def REP_MOVSW_32 : I<0xA5, RawFrm, (outs), (ins), "{rep;movsw|rep movsw}",
+                    [(X86rep_movs i16)], IIC_REP_MOVS>, REP, OpSize,
+                   Requires<[In32BitMode]>;
+def REP_MOVSD_32 : I<0xA5, RawFrm, (outs), (ins), "{rep;movsl|rep movsd}",
+                    [(X86rep_movs i32)], IIC_REP_MOVS>, REP,
+                   Requires<[In32BitMode]>;
 }
=20
-let Defs =3D [RCX,RDI,RSI], Uses =3D [RCX,RDI,RSI], isCodeGenOnly =3D 1 in
-def REP_MOVSQ : RI<0xA5, RawFrm, (outs), (ins), "{rep;movsq|rep movsq}",
-                   [(X86rep_movs i64)]>, REP;
-
+let Defs =3D [RCX,RDI,RSI], Uses =3D [RCX,RDI,RSI], isCodeGenOnly =3D 1 in=
 {
+def REP_MOVSB_64 : I<0xA4, RawFrm, (outs), (ins), "{rep;movsb|rep movsb}",
+                    [(X86rep_movs i8)], IIC_REP_MOVS>, REP,
+                   Requires<[In64BitMode]>;
+def REP_MOVSW_64 : I<0xA5, RawFrm, (outs), (ins), "{rep;movsw|rep movsw}",
+                    [(X86rep_movs i16)], IIC_REP_MOVS>, REP, OpSize,
+                   Requires<[In64BitMode]>;
+def REP_MOVSD_64 : I<0xA5, RawFrm, (outs), (ins), "{rep;movsl|rep movsd}",
+                    [(X86rep_movs i32)], IIC_REP_MOVS>, REP,
+                   Requires<[In64BitMode]>;
+def REP_MOVSQ_64 : RI<0xA5, RawFrm, (outs), (ins), "{rep;movsq|rep movsq}",
+                    [(X86rep_movs i64)], IIC_REP_MOVS>, REP,
+                   Requires<[In64BitMode]>;
+}
=20
 // FIXME: Should use "(X86rep_stos AL)" as the pattern.
-let Defs =3D [ECX,EDI], Uses =3D [AL,ECX,EDI], isCodeGenOnly =3D 1 in
-def REP_STOSB : I<0xAA, RawFrm, (outs), (ins), "{rep;stosb|rep stosb}",
-                  [(X86rep_stos i8)]>, REP;
-let Defs =3D [ECX,EDI], Uses =3D [AX,ECX,EDI], isCodeGenOnly =3D 1 in
-def REP_STOSW : I<0xAB, RawFrm, (outs), (ins), "{rep;stosw|rep stosw}",
-                  [(X86rep_stos i16)]>, REP, OpSize;
-let Defs =3D [ECX,EDI], Uses =3D [EAX,ECX,EDI], isCodeGenOnly =3D 1 in
-def REP_STOSD : I<0xAB, RawFrm, (outs), (ins), "{rep;stosl|rep stosd}",
-                  [(X86rep_stos i32)]>, REP;
+let Defs =3D [ECX,EDI], isCodeGenOnly =3D 1 in {
+  let Uses =3D [AL,ECX,EDI] in
+  def REP_STOSB_32 : I<0xAA, RawFrm, (outs), (ins), "{rep;stosb|rep stosb}=
",
+                      [(X86rep_stos i8)], IIC_REP_STOS>, REP,
+                     Requires<[In32BitMode]>;
+  let Uses =3D [AX,ECX,EDI] in
+  def REP_STOSW_32 : I<0xAB, RawFrm, (outs), (ins), "{rep;stosw|rep stosw}=
",
+                      [(X86rep_stos i16)], IIC_REP_STOS>, REP, OpSize,
+                     Requires<[In32BitMode]>;
+  let Uses =3D [EAX,ECX,EDI] in
+  def REP_STOSD_32 : I<0xAB, RawFrm, (outs), (ins), "{rep;stosl|rep stosd}=
",
+                      [(X86rep_stos i32)], IIC_REP_STOS>, REP,
+                     Requires<[In32BitMode]>;
+}
=20
-let Defs =3D [RCX,RDI], Uses =3D [RAX,RCX,RDI], isCodeGenOnly =3D 1 in
-def REP_STOSQ : RI<0xAB, RawFrm, (outs), (ins), "{rep;stosq|rep stosq}",
-                   [(X86rep_stos i64)]>, REP;
-
+let Defs =3D [RCX,RDI], isCodeGenOnly =3D 1 in {
+  let Uses =3D [AL,RCX,RDI] in
+  def REP_STOSB_64 : I<0xAA, RawFrm, (outs), (ins), "{rep;stosb|rep stosb}=
",
+                      [(X86rep_stos i8)], IIC_REP_STOS>, REP,
+                     Requires<[In64BitMode]>;
+  let Uses =3D [AX,RCX,RDI] in
+  def REP_STOSW_64 : I<0xAB, RawFrm, (outs), (ins), "{rep;stosw|rep stosw}=
",
+                      [(X86rep_stos i16)], IIC_REP_STOS>, REP, OpSize,
+                     Requires<[In64BitMode]>;
+  let Uses =3D [RAX,RCX,RDI] in
+  def REP_STOSD_64 : I<0xAB, RawFrm, (outs), (ins), "{rep;stosl|rep stosd}=
",
+                      [(X86rep_stos i32)], IIC_REP_STOS>, REP,
+                     Requires<[In64BitMode]>;
+=20
+  let Uses =3D [RAX,RCX,RDI] in
+  def REP_STOSQ_64 : RI<0xAB, RawFrm, (outs), (ins), "{rep;stosq|rep stosq=
}",
+                      [(X86rep_stos i64)], IIC_REP_STOS>, REP,
+                     Requires<[In64BitMode]>;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Thread Local Storage Instructions
@@ -537,22 +609,13 @@
 def OR32mrLocked  : I<0x09, MRMDestMem, (outs), (ins i32mem:$dst, GR32:$ze=
ro),
                       "lock\n\t"
                       "or{l}\t{$zero, $dst|$dst, $zero}",
-                      []>, Requires<[In32BitMode]>, LOCK;
+                      [], IIC_ALU_MEM>, Requires<[In32BitMode]>, LOCK;
=20
 let hasSideEffects =3D 1 in
 def Int_MemBarrier : I<0, Pseudo, (outs), (ins),
                      "#MEMBARRIER",
                      [(X86MemBarrier)]>;
=20
-// TODO: Get this to fold the constant into the instruction.
-let hasSideEffects =3D 1, Defs =3D [ESP], isCodeGenOnly =3D 1 in
-def Int_MemBarrierNoSSE64  : RI<0x09, MRM1r, (outs), (ins GR64:$zero),
-                           "lock\n\t"
-                           "or{q}\t{$zero, (%rsp)|(%rsp), $zero}",
-                           [(X86MemBarrierNoSSE GR64:$zero)]>,
-                           Requires<[In64BitMode]>, LOCK;
-
-
 // RegOpc corresponds to the mr version of the instruction
 // ImmOpc corresponds to the mi version of the instruction
 // ImmOpc8 corresponds to the mi8 version of the instruction
@@ -566,72 +629,72 @@
                    MRMDestMem, (outs), (ins i8mem:$dst, GR8:$src2),
                    !strconcat("lock\n\t", mnemonic, "{b}\t",
                               "{$src2, $dst|$dst, $src2}"),
-                   []>, LOCK;
+                   [], IIC_ALU_NONMEM>, LOCK;
 def #NAME#16mr : I<{RegOpc{7}, RegOpc{6}, RegOpc{5}, RegOpc{4},
                     RegOpc{3}, RegOpc{2}, RegOpc{1}, 1 },
                     MRMDestMem, (outs), (ins i16mem:$dst, GR16:$src2),
                     !strconcat("lock\n\t", mnemonic, "{w}\t",
                                "{$src2, $dst|$dst, $src2}"),
-                    []>, OpSize, LOCK;
+                    [], IIC_ALU_NONMEM>, OpSize, LOCK;
 def #NAME#32mr : I<{RegOpc{7}, RegOpc{6}, RegOpc{5}, RegOpc{4},
                     RegOpc{3}, RegOpc{2}, RegOpc{1}, 1 },
                     MRMDestMem, (outs), (ins i32mem:$dst, GR32:$src2),
                     !strconcat("lock\n\t", mnemonic, "{l}\t",
                                "{$src2, $dst|$dst, $src2}"),
-                    []>, LOCK;
+                    [], IIC_ALU_NONMEM>, LOCK;
 def #NAME#64mr : RI<{RegOpc{7}, RegOpc{6}, RegOpc{5}, RegOpc{4},
                      RegOpc{3}, RegOpc{2}, RegOpc{1}, 1 },
                      MRMDestMem, (outs), (ins i64mem:$dst, GR64:$src2),
                      !strconcat("lock\n\t", mnemonic, "{q}\t",
                                 "{$src2, $dst|$dst, $src2}"),
-                     []>, LOCK;
+                     [], IIC_ALU_NONMEM>, LOCK;
=20
 def #NAME#8mi : Ii8<{ImmOpc{7}, ImmOpc{6}, ImmOpc{5}, ImmOpc{4},
                      ImmOpc{3}, ImmOpc{2}, ImmOpc{1}, 0 },
                      ImmMod, (outs), (ins i8mem :$dst, i8imm :$src2),
                      !strconcat("lock\n\t", mnemonic, "{b}\t",
                                 "{$src2, $dst|$dst, $src2}"),
-                     []>, LOCK;
+                     [], IIC_ALU_MEM>, LOCK;
=20
 def #NAME#16mi : Ii16<{ImmOpc{7}, ImmOpc{6}, ImmOpc{5}, ImmOpc{4},
                        ImmOpc{3}, ImmOpc{2}, ImmOpc{1}, 1 },
                        ImmMod, (outs), (ins i16mem :$dst, i16imm :$src2),
                        !strconcat("lock\n\t", mnemonic, "{w}\t",
                                   "{$src2, $dst|$dst, $src2}"),
-                       []>, LOCK;
+                       [], IIC_ALU_MEM>, LOCK;
=20
 def #NAME#32mi : Ii32<{ImmOpc{7}, ImmOpc{6}, ImmOpc{5}, ImmOpc{4},
                        ImmOpc{3}, ImmOpc{2}, ImmOpc{1}, 1 },
                        ImmMod, (outs), (ins i32mem :$dst, i32imm :$src2),
                        !strconcat("lock\n\t", mnemonic, "{l}\t",
                                   "{$src2, $dst|$dst, $src2}"),
-                       []>, LOCK;
+                       [], IIC_ALU_MEM>, LOCK;
=20
 def #NAME#64mi32 : RIi32<{ImmOpc{7}, ImmOpc{6}, ImmOpc{5}, ImmOpc{4},
                           ImmOpc{3}, ImmOpc{2}, ImmOpc{1}, 1 },
                           ImmMod, (outs), (ins i64mem :$dst, i64i32imm :$s=
rc2),
                           !strconcat("lock\n\t", mnemonic, "{q}\t",
                                      "{$src2, $dst|$dst, $src2}"),
-                          []>, LOCK;
+                          [], IIC_ALU_MEM>, LOCK;
=20
 def #NAME#16mi8 : Ii8<{ImmOpc8{7}, ImmOpc8{6}, ImmOpc8{5}, ImmOpc8{4},
                        ImmOpc8{3}, ImmOpc8{2}, ImmOpc8{1}, 1 },
                        ImmMod, (outs), (ins i16mem :$dst, i16i8imm :$src2),
                        !strconcat("lock\n\t", mnemonic, "{w}\t",
                                   "{$src2, $dst|$dst, $src2}"),
-                       []>, LOCK;
+                       [], IIC_ALU_MEM>, LOCK;
 def #NAME#32mi8 : Ii8<{ImmOpc8{7}, ImmOpc8{6}, ImmOpc8{5}, ImmOpc8{4},
                        ImmOpc8{3}, ImmOpc8{2}, ImmOpc8{1}, 1 },
                        ImmMod, (outs), (ins i32mem :$dst, i32i8imm :$src2),
                        !strconcat("lock\n\t", mnemonic, "{l}\t",
                                   "{$src2, $dst|$dst, $src2}"),
-                       []>, LOCK;
+                       [], IIC_ALU_MEM>, LOCK;
 def #NAME#64mi8 : RIi8<{ImmOpc8{7}, ImmOpc8{6}, ImmOpc8{5}, ImmOpc8{4},
                         ImmOpc8{3}, ImmOpc8{2}, ImmOpc8{1}, 1 },
                         ImmMod, (outs), (ins i64mem :$dst, i64i8imm :$src2=
),
                         !strconcat("lock\n\t", mnemonic, "{q}\t",
                                    "{$src2, $dst|$dst, $src2}"),
-                        []>, LOCK;
+                        [], IIC_ALU_MEM>, LOCK;
=20
 }
=20
@@ -648,29 +711,29 @@
=20
 def LOCK_INC8m  : I<0xFE, MRM0m, (outs), (ins i8mem :$dst),
                     "lock\n\t"
-                    "inc{b}\t$dst", []>, LOCK;
+                    "inc{b}\t$dst", [], IIC_UNARY_MEM>, LOCK;
 def LOCK_INC16m : I<0xFF, MRM0m, (outs), (ins i16mem:$dst),
                     "lock\n\t"
-                    "inc{w}\t$dst", []>, OpSize, LOCK;
+                    "inc{w}\t$dst", [], IIC_UNARY_MEM>, OpSize, LOCK;
 def LOCK_INC32m : I<0xFF, MRM0m, (outs), (ins i32mem:$dst),
                     "lock\n\t"
-                    "inc{l}\t$dst", []>, LOCK;
+                    "inc{l}\t$dst", [], IIC_UNARY_MEM>, LOCK;
 def LOCK_INC64m : RI<0xFF, MRM0m, (outs), (ins i64mem:$dst),
                      "lock\n\t"
-                     "inc{q}\t$dst", []>, LOCK;
+                     "inc{q}\t$dst", [], IIC_UNARY_MEM>, LOCK;
=20
 def LOCK_DEC8m  : I<0xFE, MRM1m, (outs), (ins i8mem :$dst),
                     "lock\n\t"
-                    "dec{b}\t$dst", []>, LOCK;
+                    "dec{b}\t$dst", [], IIC_UNARY_MEM>, LOCK;
 def LOCK_DEC16m : I<0xFF, MRM1m, (outs), (ins i16mem:$dst),
                     "lock\n\t"
-                    "dec{w}\t$dst", []>, OpSize, LOCK;
+                    "dec{w}\t$dst", [], IIC_UNARY_MEM>, OpSize, LOCK;
 def LOCK_DEC32m : I<0xFF, MRM1m, (outs), (ins i32mem:$dst),
                     "lock\n\t"
-                    "dec{l}\t$dst", []>, LOCK;
+                    "dec{l}\t$dst", [], IIC_UNARY_MEM>, LOCK;
 def LOCK_DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst),
                       "lock\n\t"
-                      "dec{q}\t$dst", []>, LOCK;
+                      "dec{q}\t$dst", [], IIC_UNARY_MEM>, LOCK;
 }
=20
 // Atomic compare and swap.
@@ -679,42 +742,42 @@
 def LCMPXCHG8B : I<0xC7, MRM1m, (outs), (ins i64mem:$ptr),
                "lock\n\t"
                "cmpxchg8b\t$ptr",
-               [(X86cas8 addr:$ptr)]>, TB, LOCK;
+               [(X86cas8 addr:$ptr)], IIC_CMPX_LOCK_8B>, TB, LOCK;
=20
 let Defs =3D [RAX, RDX, EFLAGS], Uses =3D [RAX, RBX, RCX, RDX],
     isCodeGenOnly =3D 1 in
 def LCMPXCHG16B : RI<0xC7, MRM1m, (outs), (ins i128mem:$ptr),
                     "lock\n\t"
                     "cmpxchg16b\t$ptr",
-                    [(X86cas16 addr:$ptr)]>, TB, LOCK,
+                    [(X86cas16 addr:$ptr)], IIC_CMPX_LOCK_16B>, TB, LOCK,
                     Requires<[HasCmpxchg16b]>;
=20
 let Defs =3D [AL, EFLAGS], Uses =3D [AL], isCodeGenOnly =3D 1 in {
 def LCMPXCHG8 : I<0xB0, MRMDestMem, (outs), (ins i8mem:$ptr, GR8:$swap),
                "lock\n\t"
                "cmpxchg{b}\t{$swap, $ptr|$ptr, $swap}",
-               [(X86cas addr:$ptr, GR8:$swap, 1)]>, TB, LOCK;
+               [(X86cas addr:$ptr, GR8:$swap, 1)], IIC_CMPX_LOCK_8>, TB, L=
OCK;
 }
=20
 let Defs =3D [AX, EFLAGS], Uses =3D [AX], isCodeGenOnly =3D 1 in {
 def LCMPXCHG16 : I<0xB1, MRMDestMem, (outs), (ins i16mem:$ptr, GR16:$swap),
                "lock\n\t"
                "cmpxchg{w}\t{$swap, $ptr|$ptr, $swap}",
-               [(X86cas addr:$ptr, GR16:$swap, 2)]>, TB, OpSize, LOCK;
+               [(X86cas addr:$ptr, GR16:$swap, 2)], IIC_CMPX_LOCK>, TB, Op=
Size, LOCK;
 }
=20
 let Defs =3D [EAX, EFLAGS], Uses =3D [EAX], isCodeGenOnly =3D 1 in {
 def LCMPXCHG32 : I<0xB1, MRMDestMem, (outs), (ins i32mem:$ptr, GR32:$swap),
                "lock\n\t"
                "cmpxchg{l}\t{$swap, $ptr|$ptr, $swap}",
-               [(X86cas addr:$ptr, GR32:$swap, 4)]>, TB, LOCK;
+               [(X86cas addr:$ptr, GR32:$swap, 4)], IIC_CMPX_LOCK>, TB, LO=
CK;
 }
=20
 let Defs =3D [RAX, EFLAGS], Uses =3D [RAX], isCodeGenOnly =3D 1 in {
 def LCMPXCHG64 : RI<0xB1, MRMDestMem, (outs), (ins i64mem:$ptr, GR64:$swap=
),
                "lock\n\t"
                "cmpxchg{q}\t{$swap, $ptr|$ptr, $swap}",
-               [(X86cas addr:$ptr, GR64:$swap, 8)]>, TB, LOCK;
+               [(X86cas addr:$ptr, GR64:$swap, 8)], IIC_CMPX_LOCK>, TB, LO=
CK;
 }
=20
 // Atomic exchange and add
@@ -722,22 +785,26 @@
 def LXADD8  : I<0xC0, MRMSrcMem, (outs GR8:$dst), (ins GR8:$val, i8mem:$pt=
r),
                "lock\n\t"
                "xadd{b}\t{$val, $ptr|$ptr, $val}",
-               [(set GR8:$dst, (atomic_load_add_8 addr:$ptr, GR8:$val))]>,
+               [(set GR8:$dst, (atomic_load_add_8 addr:$ptr, GR8:$val))],
+                IIC_XADD_LOCK_MEM8>,
                 TB, LOCK;
 def LXADD16 : I<0xC1, MRMSrcMem, (outs GR16:$dst), (ins GR16:$val, i16mem:=
$ptr),
                "lock\n\t"
                "xadd{w}\t{$val, $ptr|$ptr, $val}",
-               [(set GR16:$dst, (atomic_load_add_16 addr:$ptr, GR16:$val))=
]>,
+               [(set GR16:$dst, (atomic_load_add_16 addr:$ptr, GR16:$val))=
],
+                IIC_XADD_LOCK_MEM>,
                 TB, OpSize, LOCK;
 def LXADD32 : I<0xC1, MRMSrcMem, (outs GR32:$dst), (ins GR32:$val, i32mem:=
$ptr),
                "lock\n\t"
                "xadd{l}\t{$val, $ptr|$ptr, $val}",
-               [(set GR32:$dst, (atomic_load_add_32 addr:$ptr, GR32:$val))=
]>,
+               [(set GR32:$dst, (atomic_load_add_32 addr:$ptr, GR32:$val))=
],
+                IIC_XADD_LOCK_MEM>,
                 TB, LOCK;
 def LXADD64 : RI<0xC1, MRMSrcMem, (outs GR64:$dst), (ins GR64:$val,i64mem:=
$ptr),
                "lock\n\t"
                "xadd{q}\t{$val, $ptr|$ptr, $val}",
-               [(set GR64:$dst, (atomic_load_add_64 addr:$ptr, GR64:$val))=
]>,
+               [(set GR64:$dst, (atomic_load_add_64 addr:$ptr, GR64:$val))=
],
+                IIC_XADD_LOCK_MEM>,
                 TB, LOCK;
 }
=20
@@ -936,14 +1003,9 @@
 // Direct PC relative function call for small code model. 32-bit displacem=
ent
 // sign extended to 64-bit.
 def : Pat<(X86call (i64 tglobaladdr:$dst)),
-          (CALL64pcrel32 tglobaladdr:$dst)>, Requires<[NotWin64]>;
+          (CALL64pcrel32 tglobaladdr:$dst)>;
 def : Pat<(X86call (i64 texternalsym:$dst)),
-          (CALL64pcrel32 texternalsym:$dst)>, Requires<[NotWin64]>;
-
-def : Pat<(X86call (i64 tglobaladdr:$dst)),
-          (WINCALL64pcrel32 tglobaladdr:$dst)>, Requires<[IsWin64]>;
-def : Pat<(X86call (i64 texternalsym:$dst)),
-          (WINCALL64pcrel32 texternalsym:$dst)>, Requires<[IsWin64]>;
+          (CALL64pcrel32 texternalsym:$dst)>;
=20
 // tailcall stuff
 def : Pat<(X86tcret GR32_TC:$dst, imm:$off),
@@ -1105,12 +1167,10 @@
   if (ConstantSDNode *CN =3D dyn_cast<ConstantSDNode>(N->getOperand(1)))
     return CurDAG->MaskedValueIsZero(N->getOperand(0), CN->getAPIntValue()=
);
=20
-  unsigned BitWidth =3D N->getValueType(0).getScalarType().getSizeInBits();
-  APInt Mask =3D APInt::getAllOnesValue(BitWidth);
   APInt KnownZero0, KnownOne0;
-  CurDAG->ComputeMaskedBits(N->getOperand(0), Mask, KnownZero0, KnownOne0,=
 0);
+  CurDAG->ComputeMaskedBits(N->getOperand(0), KnownZero0, KnownOne0, 0);
   APInt KnownZero1, KnownOne1;
-  CurDAG->ComputeMaskedBits(N->getOperand(1), Mask, KnownZero1, KnownOne1,=
 0);
+  CurDAG->ComputeMaskedBits(N->getOperand(1), KnownZero1, KnownOne1, 0);
   return (~KnownZero0 & ~KnownZero1) =3D=3D 0;
 }]>;
=20
@@ -1440,58 +1500,62 @@
 def : Pat<(shl GR32:$src1, (i8 1)), (ADD32rr GR32:$src1, GR32:$src1)>;
 def : Pat<(shl GR64:$src1, (i8 1)), (ADD64rr GR64:$src1, GR64:$src1)>;
=20
+// Helper imms that check if a mask doesn't change significant shift bits.
+def immShift32 : ImmLeaf<i8, [{ return CountTrailingOnes_32(Imm) >=3D 5; }=
]>;
+def immShift64 : ImmLeaf<i8, [{ return CountTrailingOnes_32(Imm) >=3D 6; }=
]>;
+
 // (shl x (and y, 31)) =3D=3D> (shl x, y)
-def : Pat<(shl GR8:$src1, (and CL, 31)),
+def : Pat<(shl GR8:$src1, (and CL, immShift32)),
           (SHL8rCL GR8:$src1)>;
-def : Pat<(shl GR16:$src1, (and CL, 31)),
+def : Pat<(shl GR16:$src1, (and CL, immShift32)),
           (SHL16rCL GR16:$src1)>;
-def : Pat<(shl GR32:$src1, (and CL, 31)),
+def : Pat<(shl GR32:$src1, (and CL, immShift32)),
           (SHL32rCL GR32:$src1)>;
-def : Pat<(store (shl (loadi8 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (shl (loadi8 addr:$dst), (and CL, immShift32)), addr:$dst=
),
           (SHL8mCL addr:$dst)>;
-def : Pat<(store (shl (loadi16 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (shl (loadi16 addr:$dst), (and CL, immShift32)), addr:$ds=
t),
           (SHL16mCL addr:$dst)>;
-def : Pat<(store (shl (loadi32 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (shl (loadi32 addr:$dst), (and CL, immShift32)), addr:$ds=
t),
           (SHL32mCL addr:$dst)>;
=20
-def : Pat<(srl GR8:$src1, (and CL, 31)),
+def : Pat<(srl GR8:$src1, (and CL, immShift32)),
           (SHR8rCL GR8:$src1)>;
-def : Pat<(srl GR16:$src1, (and CL, 31)),
+def : Pat<(srl GR16:$src1, (and CL, immShift32)),
           (SHR16rCL GR16:$src1)>;
-def : Pat<(srl GR32:$src1, (and CL, 31)),
+def : Pat<(srl GR32:$src1, (and CL, immShift32)),
           (SHR32rCL GR32:$src1)>;
-def : Pat<(store (srl (loadi8 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (srl (loadi8 addr:$dst), (and CL, immShift32)), addr:$dst=
),
           (SHR8mCL addr:$dst)>;
-def : Pat<(store (srl (loadi16 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (srl (loadi16 addr:$dst), (and CL, immShift32)), addr:$ds=
t),
           (SHR16mCL addr:$dst)>;
-def : Pat<(store (srl (loadi32 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (srl (loadi32 addr:$dst), (and CL, immShift32)), addr:$ds=
t),
           (SHR32mCL addr:$dst)>;
=20
-def : Pat<(sra GR8:$src1, (and CL, 31)),
+def : Pat<(sra GR8:$src1, (and CL, immShift32)),
           (SAR8rCL GR8:$src1)>;
-def : Pat<(sra GR16:$src1, (and CL, 31)),
+def : Pat<(sra GR16:$src1, (and CL, immShift32)),
           (SAR16rCL GR16:$src1)>;
-def : Pat<(sra GR32:$src1, (and CL, 31)),
+def : Pat<(sra GR32:$src1, (and CL, immShift32)),
           (SAR32rCL GR32:$src1)>;
-def : Pat<(store (sra (loadi8 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (sra (loadi8 addr:$dst), (and CL, immShift32)), addr:$dst=
),
           (SAR8mCL addr:$dst)>;
-def : Pat<(store (sra (loadi16 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (sra (loadi16 addr:$dst), (and CL, immShift32)), addr:$ds=
t),
           (SAR16mCL addr:$dst)>;
-def : Pat<(store (sra (loadi32 addr:$dst), (and CL, 31)), addr:$dst),
+def : Pat<(store (sra (loadi32 addr:$dst), (and CL, immShift32)), addr:$ds=
t),
           (SAR32mCL addr:$dst)>;
=20
 // (shl x (and y, 63)) =3D=3D> (shl x, y)
-def : Pat<(shl GR64:$src1, (and CL, 63)),
+def : Pat<(shl GR64:$src1, (and CL, immShift64)),
           (SHL64rCL GR64:$src1)>;
 def : Pat<(store (shl (loadi64 addr:$dst), (and CL, 63)), addr:$dst),
           (SHL64mCL addr:$dst)>;
=20
-def : Pat<(srl GR64:$src1, (and CL, 63)),
+def : Pat<(srl GR64:$src1, (and CL, immShift64)),
           (SHR64rCL GR64:$src1)>;
 def : Pat<(store (srl (loadi64 addr:$dst), (and CL, 63)), addr:$dst),
           (SHR64mCL addr:$dst)>;
=20
-def : Pat<(sra GR64:$src1, (and CL, 63)),
+def : Pat<(sra GR64:$src1, (and CL, immShift64)),
           (SAR64rCL GR64:$src1)>;
 def : Pat<(store (sra (loadi64 addr:$dst), (and CL, 63)), addr:$dst),
           (SAR64mCL addr:$dst)>;
@@ -1735,3 +1799,11 @@
           (AND64ri8 GR64:$src1, i64immSExt8:$src2)>;
 def : Pat<(and GR64:$src1, i64immSExt32:$src2),
           (AND64ri32 GR64:$src1, i64immSExt32:$src2)>;
+
+// Bit scan instruction patterns to match explicit zero-undef behavior.
+def : Pat<(cttz_zero_undef GR16:$src), (BSF16rr GR16:$src)>;
+def : Pat<(cttz_zero_undef GR32:$src), (BSF32rr GR32:$src)>;
+def : Pat<(cttz_zero_undef GR64:$src), (BSF64rr GR64:$src)>;
+def : Pat<(cttz_zero_undef (loadi16 addr:$src)), (BSF16rm addr:$src)>;
+def : Pat<(cttz_zero_undef (loadi32 addr:$src)), (BSF32rm addr:$src)>;
+def : Pat<(cttz_zero_undef (loadi64 addr:$src)), (BSF64rm addr:$src)>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strControl.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrControl.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrControl.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86InstrControl.td - Control Flow Instructions ------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- X86InstrControl.td - Control Flow Instructions -----*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -20,39 +20,47 @@
     hasCtrlDep =3D 1, FPForm =3D SpecialFP in {
   def RET    : I   <0xC3, RawFrm, (outs), (ins variable_ops),
                     "ret",
-                    [(X86retflag 0)]>;
+                    [(X86retflag 0)], IIC_RET>;
+  def RETW   : I   <0xC3, RawFrm, (outs), (ins variable_ops),
+                    "ret{w}",
+                    [], IIC_RET>, OpSize;
   def RETI   : Ii16<0xC2, RawFrm, (outs), (ins i16imm:$amt, variable_ops),
                     "ret\t$amt",
-                    [(X86retflag timm:$amt)]>;
+                    [(X86retflag timm:$amt)], IIC_RET_IMM>;
   def RETIW  : Ii16<0xC2, RawFrm, (outs), (ins i16imm:$amt, variable_ops),
-                    "retw\t$amt",
-                    []>, OpSize;
+                    "ret{w}\t$amt",
+                    [], IIC_RET_IMM>, OpSize;
   def LRETL  : I   <0xCB, RawFrm, (outs), (ins),
-                    "lretl", []>;
+                    "{l}ret{l|f}", [], IIC_RET>;
+  def LRETW  : I   <0xCB, RawFrm, (outs), (ins),
+                    "{l}ret{w|f}", [], IIC_RET>, OpSize;
   def LRETQ  : RI  <0xCB, RawFrm, (outs), (ins),
-                    "lretq", []>;
+                    "{l}ret{q|f}", [], IIC_RET>;
   def LRETI  : Ii16<0xCA, RawFrm, (outs), (ins i16imm:$amt),
-                    "lret\t$amt", []>;
+                    "{l}ret{l|f}\t$amt", [], IIC_RET>;
   def LRETIW : Ii16<0xCA, RawFrm, (outs), (ins i16imm:$amt),
-                    "lretw\t$amt", []>, OpSize;
+                    "{l}ret{w|f}\t$amt", [], IIC_RET>, OpSize;
 }
=20
 // Unconditional branches.
 let isBarrier =3D 1, isBranch =3D 1, isTerminator =3D 1 in {
   def JMP_4 : Ii32PCRel<0xE9, RawFrm, (outs), (ins brtarget:$dst),
-                        "jmp\t$dst", [(br bb:$dst)]>;
+                        "jmp\t$dst", [(br bb:$dst)], IIC_JMP_REL>;
   def JMP_1 : Ii8PCRel<0xEB, RawFrm, (outs), (ins brtarget8:$dst),
-                       "jmp\t$dst", []>;
+                       "jmp\t$dst", [], IIC_JMP_REL>;
+  // FIXME : Intel syntax for JMP64pcrel32 such that it is not ambiguious
+  // with JMP_1.
   def JMP64pcrel32 : I<0xE9, RawFrm, (outs), (ins brtarget:$dst),
-                       "jmp{q}\t$dst", []>;
+                       "jmpq\t$dst", [], IIC_JMP_REL>;
 }
=20
 // Conditional Branches.
 let isBranch =3D 1, isTerminator =3D 1, Uses =3D [EFLAGS] in {
   multiclass ICBr<bits<8> opc1, bits<8> opc4, string asm, PatFrag Cond> {
-    def _1 : Ii8PCRel <opc1, RawFrm, (outs), (ins brtarget8:$dst), asm, []=
>;
+    def _1 : Ii8PCRel <opc1, RawFrm, (outs), (ins brtarget8:$dst), asm, [],
+                       IIC_Jcc>;
     def _4 : Ii32PCRel<opc4, RawFrm, (outs), (ins brtarget:$dst), asm,
-                       [(X86brcond bb:$dst, Cond, EFLAGS)]>, TB;
+                       [(X86brcond bb:$dst, Cond, EFLAGS)], IIC_Jcc>, TB;
   }
 }
=20
@@ -74,61 +82,61 @@
 defm JG  : ICBr<0x7F, 0x8F, "jg\t$dst" , X86_COND_G>;
=20
 // jcx/jecx/jrcx instructions.
-let isAsmParserOnly =3D 1, isBranch =3D 1, isTerminator =3D 1 in {
+let isBranch =3D 1, isTerminator =3D 1 in {
   // These are the 32-bit versions of this instruction for the asmparser. =
 In
   // 32-bit mode, the address size prefix is jcxz and the unprefixed versi=
on is
   // jecxz.
   let Uses =3D [CX] in
     def JCXZ : Ii8PCRel<0xE3, RawFrm, (outs), (ins brtarget8:$dst),
-                        "jcxz\t$dst", []>, AdSize, Requires<[In32BitMode]>;
+                        "jcxz\t$dst", [], IIC_JCXZ>, AdSize, Requires<[In3=
2BitMode]>;
   let Uses =3D [ECX] in
     def JECXZ_32 : Ii8PCRel<0xE3, RawFrm, (outs), (ins brtarget8:$dst),
-                           "jecxz\t$dst", []>, Requires<[In32BitMode]>;
+                           "jecxz\t$dst", [], IIC_JCXZ>, Requires<[In32Bit=
Mode]>;
=20
   // J*CXZ instruction: 64-bit versions of this instruction for the asmpar=
ser.
   // In 64-bit mode, the address size prefix is jecxz and the unprefixed v=
ersion
   // is jrcxz.
   let Uses =3D [ECX] in
     def JECXZ_64 : Ii8PCRel<0xE3, RawFrm, (outs), (ins brtarget8:$dst),
-                            "jecxz\t$dst", []>, AdSize, Requires<[In64BitM=
ode]>;
+                            "jecxz\t$dst", [], IIC_JCXZ>, AdSize, Requires=
<[In64BitMode]>;
   let Uses =3D [RCX] in
     def JRCXZ : Ii8PCRel<0xE3, RawFrm, (outs), (ins brtarget8:$dst),
-                           "jrcxz\t$dst", []>, Requires<[In64BitMode]>;
+                           "jrcxz\t$dst", [], IIC_JCXZ>, Requires<[In64Bit=
Mode]>;
 }
=20
 // Indirect branches
 let isBranch =3D 1, isTerminator =3D 1, isBarrier =3D 1, isIndirectBranch =
=3D 1 in {
   def JMP32r     : I<0xFF, MRM4r, (outs), (ins GR32:$dst), "jmp{l}\t{*}$ds=
t",
-                     [(brind GR32:$dst)]>, Requires<[In32BitMode]>;
+                     [(brind GR32:$dst)], IIC_JMP_REG>, Requires<[In32BitM=
ode]>;
   def JMP32m     : I<0xFF, MRM4m, (outs), (ins i32mem:$dst), "jmp{l}\t{*}$=
dst",
-                     [(brind (loadi32 addr:$dst))]>, Requires<[In32BitMode=
]>;
+                     [(brind (loadi32 addr:$dst))], IIC_JMP_MEM>, Requires=
<[In32BitMode]>;
=20
   def JMP64r     : I<0xFF, MRM4r, (outs), (ins GR64:$dst), "jmp{q}\t{*}$ds=
t",
-                     [(brind GR64:$dst)]>, Requires<[In64BitMode]>;
+                     [(brind GR64:$dst)], IIC_JMP_REG>, Requires<[In64BitM=
ode]>;
   def JMP64m     : I<0xFF, MRM4m, (outs), (ins i64mem:$dst), "jmp{q}\t{*}$=
dst",
-                     [(brind (loadi64 addr:$dst))]>, Requires<[In64BitMode=
]>;
+                     [(brind (loadi64 addr:$dst))], IIC_JMP_MEM>, Requires=
<[In64BitMode]>;
=20
   def FARJMP16i  : Iseg16<0xEA, RawFrmImm16, (outs),
                           (ins i16imm:$off, i16imm:$seg),
-                          "ljmp{w}\t{$seg, $off|$off, $seg}", []>, OpSize;
+                          "ljmp{w}\t{$seg, $off|$off, $seg}", [], IIC_JMP_=
FAR_PTR>, OpSize;
   def FARJMP32i  : Iseg32<0xEA, RawFrmImm16, (outs),
                           (ins i32imm:$off, i16imm:$seg),
-                          "ljmp{l}\t{$seg, $off|$off, $seg}", []>;
+                          "ljmp{l}\t{$seg, $off|$off, $seg}", [], IIC_JMP_=
FAR_PTR>;
   def FARJMP64   : RI<0xFF, MRM5m, (outs), (ins opaque80mem:$dst),
-                      "ljmp{q}\t{*}$dst", []>;
+                      "ljmp{q}\t{*}$dst", [], IIC_JMP_FAR_MEM>;
=20
   def FARJMP16m  : I<0xFF, MRM5m, (outs), (ins opaque32mem:$dst),
-                     "ljmp{w}\t{*}$dst", []>, OpSize;
+                     "ljmp{w}\t{*}$dst", [], IIC_JMP_FAR_MEM>, OpSize;
   def FARJMP32m  : I<0xFF, MRM5m, (outs), (ins opaque48mem:$dst),
-                     "ljmp{l}\t{*}$dst", []>;
+                     "ljmp{l}\t{*}$dst", [], IIC_JMP_FAR_MEM>;
 }
=20
=20
 // Loop instructions
=20
-def LOOP   : Ii8PCRel<0xE2, RawFrm, (outs), (ins brtarget8:$dst), "loop\t$=
dst", []>;
-def LOOPE  : Ii8PCRel<0xE1, RawFrm, (outs), (ins brtarget8:$dst), "loope\t=
$dst", []>;
-def LOOPNE : Ii8PCRel<0xE0, RawFrm, (outs), (ins brtarget8:$dst), "loopne\=
t$dst", []>;
+def LOOP   : Ii8PCRel<0xE2, RawFrm, (outs), (ins brtarget8:$dst), "loop\t$=
dst", [], IIC_LOOP>;
+def LOOPE  : Ii8PCRel<0xE1, RawFrm, (outs), (ins brtarget8:$dst), "loope\t=
$dst", [], IIC_LOOPE>;
+def LOOPNE : Ii8PCRel<0xE0, RawFrm, (outs), (ins brtarget8:$dst), "loopne\=
t$dst", [], IIC_LOOPNE>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Call Instructions...
@@ -138,32 +146,30 @@
   // a use to prevent stack-pointer assignments that appear immediately
   // before calls from potentially appearing dead. Uses for argument
   // registers are added manually.
-  let Defs =3D [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0,
-              MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
-              XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7,
-              XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15, EFLAGS=
],
-      Uses =3D [ESP] in {
+  let Uses =3D [ESP] in {
     def CALLpcrel32 : Ii32PCRel<0xE8, RawFrm,
                            (outs), (ins i32imm_pcrel:$dst,variable_ops),
-                           "call{l}\t$dst", []>, Requires<[In32BitMode]>;
+                           "call{l}\t$dst", [], IIC_CALL_RI>, Requires<[In=
32BitMode]>;
     def CALL32r     : I<0xFF, MRM2r, (outs), (ins GR32:$dst, variable_ops),
-                        "call{l}\t{*}$dst", [(X86call GR32:$dst)]>,
+                        "call{l}\t{*}$dst", [(X86call GR32:$dst)], IIC_CAL=
L_RI>,
                          Requires<[In32BitMode]>;
     def CALL32m     : I<0xFF, MRM2m, (outs), (ins i32mem:$dst, variable_op=
s),
-                        "call{l}\t{*}$dst", [(X86call (loadi32 addr:$dst))=
]>,
+                        "call{l}\t{*}$dst", [(X86call (loadi32 addr:$dst))=
], IIC_CALL_MEM>,
                         Requires<[In32BitMode]>;
=20
     def FARCALL16i  : Iseg16<0x9A, RawFrmImm16, (outs),
                              (ins i16imm:$off, i16imm:$seg),
-                             "lcall{w}\t{$seg, $off|$off, $seg}", []>, OpS=
ize;
+                             "lcall{w}\t{$seg, $off|$off, $seg}", [],
+                             IIC_CALL_FAR_PTR>, OpSize;
     def FARCALL32i  : Iseg32<0x9A, RawFrmImm16, (outs),
                              (ins i32imm:$off, i16imm:$seg),
-                             "lcall{l}\t{$seg, $off|$off, $seg}", []>;
+                             "lcall{l}\t{$seg, $off|$off, $seg}", [],
+                             IIC_CALL_FAR_PTR>;
=20
     def FARCALL16m  : I<0xFF, MRM3m, (outs), (ins opaque32mem:$dst),
-                        "lcall{w}\t{*}$dst", []>, OpSize;
+                        "lcall{w}\t{*}$dst", [], IIC_CALL_FAR_MEM>, OpSize;
     def FARCALL32m  : I<0xFF, MRM3m, (outs), (ins opaque48mem:$dst),
-                        "lcall{l}\t{*}$dst", []>;
+                        "lcall{l}\t{*}$dst", [], IIC_CALL_FAR_MEM>;
=20
     // callw for 16 bit code for the assembler.
     let isAsmParserOnly =3D 1 in
@@ -177,11 +183,7 @@
=20
 let isCall =3D 1, isTerminator =3D 1, isReturn =3D 1, isBarrier =3D 1,
     isCodeGenOnly =3D 1 in
-  let Defs =3D [EAX, ECX, EDX, FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0,
-              MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
-              XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7,
-              XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15, EFLAGS=
],
-      Uses =3D [ESP] in {
+  let Uses =3D [ESP] in {
   def TCRETURNdi : PseudoI<(outs),
                      (ins i32imm_pcrel:$dst, i32imm:$offset, variable_ops)=
, []>;
   def TCRETURNri : PseudoI<(outs),
@@ -194,74 +196,43 @@
   // mcinst.
   def TAILJMPd : Ii32PCRel<0xE9, RawFrm, (outs),
                            (ins i32imm_pcrel:$dst, variable_ops),
-                 "jmp\t$dst  # TAILCALL",
-                 []>;
+                           "jmp\t$dst  # TAILCALL",
+                           [], IIC_JMP_REL>;
   def TAILJMPr : I<0xFF, MRM4r, (outs), (ins GR32_TC:$dst, variable_ops),
-                   "", []>;  // FIXME: Remove encoding when JIT is dead.
+                   "", [], IIC_JMP_REG>;  // FIXME: Remove encoding when J=
IT is dead.
   let mayLoad =3D 1 in
   def TAILJMPm : I<0xFF, MRM4m, (outs), (ins i32mem_TC:$dst, variable_ops),
-                   "jmp{l}\t{*}$dst  # TAILCALL", []>;
+                   "jmp{l}\t{*}$dst  # TAILCALL", [], IIC_JMP_MEM>;
 }
=20
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  Call Instructions...
 //
-let isCall =3D 1 in
-  // All calls clobber the non-callee saved registers. RSP is marked as
-  // a use to prevent stack-pointer assignments that appear immediately
-  // before calls from potentially appearing dead. Uses for argument
-  // registers are added manually.
-  let Defs =3D [RAX, RCX, RDX, RSI, RDI, R8, R9, R10, R11,
-              FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0, ST1,
-              MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
-              XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7,
-              XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15, EFLAGS=
],
-      Uses =3D [RSP] in {
=20
-    // NOTE: this pattern doesn't match "X86call imm", because we do not k=
now
-    // that the offset between an arbitrary immediate and the call will fi=
t in
-    // the 32-bit pcrel field that we have.
-    def CALL64pcrel32 : Ii32PCRel<0xE8, RawFrm,
-                          (outs), (ins i64i32imm_pcrel:$dst, variable_ops),
-                          "call{q}\t$dst", []>,
-                        Requires<[In64BitMode, NotWin64]>;
-    def CALL64r       : I<0xFF, MRM2r, (outs), (ins GR64:$dst, variable_op=
s),
-                          "call{q}\t{*}$dst", [(X86call GR64:$dst)]>,
-                        Requires<[In64BitMode, NotWin64]>;
-    def CALL64m       : I<0xFF, MRM2m, (outs), (ins i64mem:$dst, variable_=
ops),
-                          "call{q}\t{*}$dst", [(X86call (loadi64 addr:$dst=
))]>,
-                        Requires<[In64BitMode, NotWin64]>;
+// RSP is marked as a use to prevent stack-pointer assignments that appear
+// immediately before calls from potentially appearing dead. Uses for argu=
ment
+// registers are added manually.
+let isCall =3D 1, Uses =3D [RSP] in {
+  // NOTE: this pattern doesn't match "X86call imm", because we do not know
+  // that the offset between an arbitrary immediate and the call will fit =
in
+  // the 32-bit pcrel field that we have.
+  def CALL64pcrel32 : Ii32PCRel<0xE8, RawFrm,
+                        (outs), (ins i64i32imm_pcrel:$dst, variable_ops),
+                        "call{q}\t$dst", [], IIC_CALL_RI>,
+                      Requires<[In64BitMode]>;
+  def CALL64r       : I<0xFF, MRM2r, (outs), (ins GR64:$dst, variable_ops),
+                        "call{q}\t{*}$dst", [(X86call GR64:$dst)],
+                        IIC_CALL_RI>,
+                      Requires<[In64BitMode]>;
+  def CALL64m       : I<0xFF, MRM2m, (outs), (ins i64mem:$dst, variable_op=
s),
+                        "call{q}\t{*}$dst", [(X86call (loadi64 addr:$dst))=
],
+                        IIC_CALL_MEM>,
+                      Requires<[In64BitMode]>;
=20
-    def FARCALL64   : RI<0xFF, MRM3m, (outs), (ins opaque80mem:$dst),
-                         "lcall{q}\t{*}$dst", []>;
-  }
-
-  // FIXME: We need to teach codegen about single list of call-clobbered
-  // registers.
-let isCall =3D 1, isCodeGenOnly =3D 1 in
-  // All calls clobber the non-callee saved registers. RSP is marked as
-  // a use to prevent stack-pointer assignments that appear immediately
-  // before calls from potentially appearing dead. Uses for argument
-  // registers are added manually.
-  let Defs =3D [RAX, RCX, RDX, R8, R9, R10, R11,
-              FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0, ST1,
-              MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
-              XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, EFLAGS],
-      Uses =3D [RSP] in {
-    def WINCALL64pcrel32 : Ii32PCRel<0xE8, RawFrm,
-                             (outs), (ins i64i32imm_pcrel:$dst, variable_o=
ps),
-                             "call{q}\t$dst", []>,
-                           Requires<[IsWin64]>;
-    def WINCALL64r       : I<0xFF, MRM2r, (outs), (ins GR64:$dst, variable=
_ops),
-                             "call{q}\t{*}$dst",
-                             [(X86call GR64:$dst)]>, Requires<[IsWin64]>;
-    def WINCALL64m       : I<0xFF, MRM2m, (outs),
-                              (ins i64mem:$dst,variable_ops),
-                             "call{q}\t{*}$dst",
-                             [(X86call (loadi64 addr:$dst))]>,
-                           Requires<[IsWin64]>;
-  }
+  def FARCALL64   : RI<0xFF, MRM3m, (outs), (ins opaque80mem:$dst),
+                       "lcall{q}\t{*}$dst", [], IIC_CALL_FAR_MEM>;
+}
=20
 let isCall =3D 1, isCodeGenOnly =3D 1 in
   // __chkstk(MSVC):     clobber R10, R11 and EFLAGS.
@@ -270,18 +241,13 @@
       Uses =3D [RSP] in {
     def W64ALLOCA : Ii32PCRel<0xE8, RawFrm,
                       (outs), (ins i64i32imm_pcrel:$dst, variable_ops),
-                      "call{q}\t$dst", []>,
+                      "call{q}\t$dst", [], IIC_CALL_RI>,
                     Requires<[IsWin64]>;
   }
=20
 let isCall =3D 1, isTerminator =3D 1, isReturn =3D 1, isBarrier =3D 1,
     isCodeGenOnly =3D 1 in
-  // AMD64 cc clobbers RSI, RDI, XMM6-XMM15.
-  let Defs =3D [RAX, RCX, RDX, R8, R9, R10, R11,
-              FP0, FP1, FP2, FP3, FP4, FP5, FP6, ST0, ST1,
-              MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7,
-              XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, EFLAGS],
-      Uses =3D [RSP],
+  let Uses =3D [RSP],
       usesCustomInserter =3D 1 in {
   def TCRETURNdi64 : PseudoI<(outs),
                       (ins i64i32imm_pcrel:$dst, i32imm:$offset, variable_=
ops),
@@ -294,11 +260,11 @@
=20
   def TAILJMPd64 : Ii32PCRel<0xE9, RawFrm, (outs),
                                       (ins i64i32imm_pcrel:$dst, variable_=
ops),
-                   "jmp\t$dst  # TAILCALL", []>;
+                   "jmp\t$dst  # TAILCALL", [], IIC_JMP_REL>;
   def TAILJMPr64 : I<0xFF, MRM4r, (outs), (ins ptr_rc_tailcall:$dst, varia=
ble_ops),
-                     "jmp{q}\t{*}$dst  # TAILCALL", []>;
+                     "jmp{q}\t{*}$dst  # TAILCALL", [], IIC_JMP_MEM>;
=20
   let mayLoad =3D 1 in
   def TAILJMPm64 : I<0xFF, MRM4m, (outs), (ins i64mem_TC:$dst, variable_op=
s),
-                     "jmp{q}\t{*}$dst  # TAILCALL", []>;
+                     "jmp{q}\t{*}$dst  # TAILCALL", [], IIC_JMP_MEM>;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strExtension.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrExtension.td	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrExtension.td	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86InstrExtension.td - Sign and Zero Extensions -----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86InstrExtension.td - Sign and Zero Extensions ----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the sign and zero extension operations.
@@ -37,40 +37,47 @@
 }
=20
=20
+
 // Sign/Zero extenders
 def MOVSX16rr8 : I<0xBE, MRMSrcReg, (outs GR16:$dst), (ins GR8:$src),
-                   "movs{bw|x}\t{$src, $dst|$dst, $src}", []>, TB, OpSize;
+                   "movs{bw|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVSX_R1=
6_R8>,
+                   TB, OpSize;
 def MOVSX16rm8 : I<0xBE, MRMSrcMem, (outs GR16:$dst), (ins i8mem:$src),
-                   "movs{bw|x}\t{$src, $dst|$dst, $src}", []>, TB, OpSize;
+                   "movs{bw|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVSX_R1=
6_M8>,
+                   TB, OpSize;
 def MOVSX32rr8 : I<0xBE, MRMSrcReg, (outs GR32:$dst), (ins GR8:$src),
                    "movs{bl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (sext GR8:$src))]>, TB;
+                   [(set GR32:$dst, (sext GR8:$src))], IIC_MOVSX>, TB;
 def MOVSX32rm8 : I<0xBE, MRMSrcMem, (outs GR32:$dst), (ins i8mem :$src),
                    "movs{bl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (sextloadi32i8 addr:$src))]>, TB;
+                   [(set GR32:$dst, (sextloadi32i8 addr:$src))], IIC_MOVSX=
>, TB;
 def MOVSX32rr16: I<0xBF, MRMSrcReg, (outs GR32:$dst), (ins GR16:$src),
                    "movs{wl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (sext GR16:$src))]>, TB;
+                   [(set GR32:$dst, (sext GR16:$src))], IIC_MOVSX>, TB;
 def MOVSX32rm16: I<0xBF, MRMSrcMem, (outs GR32:$dst), (ins i16mem:$src),
                    "movs{wl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (sextloadi32i16 addr:$src))]>, TB;
+                   [(set GR32:$dst, (sextloadi32i16 addr:$src))], IIC_MOVS=
X>,
+                   TB;
=20
 def MOVZX16rr8 : I<0xB6, MRMSrcReg, (outs GR16:$dst), (ins GR8:$src),
-                   "movz{bw|x}\t{$src, $dst|$dst, $src}", []>, TB, OpSize;
+                   "movz{bw|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVZX_R1=
6_R8>,
+                   TB, OpSize;
 def MOVZX16rm8 : I<0xB6, MRMSrcMem, (outs GR16:$dst), (ins i8mem:$src),
-                   "movz{bw|x}\t{$src, $dst|$dst, $src}", []>, TB, OpSize;
+                   "movz{bw|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVZX_R1=
6_M8>,
+                   TB, OpSize;
 def MOVZX32rr8 : I<0xB6, MRMSrcReg, (outs GR32:$dst), (ins GR8 :$src),
                    "movz{bl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (zext GR8:$src))]>, TB;
+                   [(set GR32:$dst, (zext GR8:$src))], IIC_MOVZX>, TB;
 def MOVZX32rm8 : I<0xB6, MRMSrcMem, (outs GR32:$dst), (ins i8mem :$src),
                    "movz{bl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (zextloadi32i8 addr:$src))]>, TB;
+                   [(set GR32:$dst, (zextloadi32i8 addr:$src))], IIC_MOVZX=
>, TB;
 def MOVZX32rr16: I<0xB7, MRMSrcReg, (outs GR32:$dst), (ins GR16:$src),
                    "movz{wl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (zext GR16:$src))]>, TB;
+                   [(set GR32:$dst, (zext GR16:$src))], IIC_MOVZX>, TB;
 def MOVZX32rm16: I<0xB7, MRMSrcMem, (outs GR32:$dst), (ins i16mem:$src),
                    "movz{wl|x}\t{$src, $dst|$dst, $src}",
-                   [(set GR32:$dst, (zextloadi32i16 addr:$src))]>, TB;
+                   [(set GR32:$dst, (zextloadi32i16 addr:$src))], IIC_MOVZ=
X>,
+                   TB;
=20
 // These are the same as the regular MOVZX32rr8 and MOVZX32rm8
 // except that they use GR32_NOREX for the output operand register class
@@ -78,12 +85,12 @@
 def MOVZX32_NOREXrr8 : I<0xB6, MRMSrcReg,
                          (outs GR32_NOREX:$dst), (ins GR8_NOREX:$src),
                          "movz{bl|x}\t{$src, $dst|$dst, $src}",
-                         []>, TB;
+                         [], IIC_MOVZX>, TB;
 let mayLoad =3D 1 in
 def MOVZX32_NOREXrm8 : I<0xB6, MRMSrcMem,
                          (outs GR32_NOREX:$dst), (ins i8mem_NOREX:$src),
                          "movz{bl|x}\t{$src, $dst|$dst, $src}",
-                         []>, TB;
+                         [], IIC_MOVZX>, TB;
=20
 // MOVSX64rr8 always has a REX prefix and it has an 8-bit register
 // operand, which makes it a rare instruction with an 8-bit register
@@ -91,32 +98,38 @@
 // were generalized, this would require a special register class.
 def MOVSX64rr8 : RI<0xBE, MRMSrcReg, (outs GR64:$dst), (ins GR8 :$src),
                     "movs{bq|x}\t{$src, $dst|$dst, $src}",
-                    [(set GR64:$dst, (sext GR8:$src))]>, TB;
+                    [(set GR64:$dst, (sext GR8:$src))], IIC_MOVSX>, TB;
 def MOVSX64rm8 : RI<0xBE, MRMSrcMem, (outs GR64:$dst), (ins i8mem :$src),
                     "movs{bq|x}\t{$src, $dst|$dst, $src}",
-                    [(set GR64:$dst, (sextloadi64i8 addr:$src))]>, TB;
+                    [(set GR64:$dst, (sextloadi64i8 addr:$src))], IIC_MOVS=
X>,
+                    TB;
 def MOVSX64rr16: RI<0xBF, MRMSrcReg, (outs GR64:$dst), (ins GR16:$src),
                     "movs{wq|x}\t{$src, $dst|$dst, $src}",
-                    [(set GR64:$dst, (sext GR16:$src))]>, TB;
+                    [(set GR64:$dst, (sext GR16:$src))], IIC_MOVSX>, TB;
 def MOVSX64rm16: RI<0xBF, MRMSrcMem, (outs GR64:$dst), (ins i16mem:$src),
                     "movs{wq|x}\t{$src, $dst|$dst, $src}",
-                    [(set GR64:$dst, (sextloadi64i16 addr:$src))]>, TB;
+                    [(set GR64:$dst, (sextloadi64i16 addr:$src))], IIC_MOV=
SX>,
+                    TB;
 def MOVSX64rr32: RI<0x63, MRMSrcReg, (outs GR64:$dst), (ins GR32:$src),
                     "movs{lq|xd}\t{$src, $dst|$dst, $src}",
-                    [(set GR64:$dst, (sext GR32:$src))]>;
+                    [(set GR64:$dst, (sext GR32:$src))], IIC_MOVSX>;
 def MOVSX64rm32: RI<0x63, MRMSrcMem, (outs GR64:$dst), (ins i32mem:$src),
                     "movs{lq|xd}\t{$src, $dst|$dst, $src}",
-                    [(set GR64:$dst, (sextloadi64i32 addr:$src))]>;
+                    [(set GR64:$dst, (sextloadi64i32 addr:$src))], IIC_MOV=
SX>;
=20
 // movzbq and movzwq encodings for the disassembler
 def MOVZX64rr8_Q : RI<0xB6, MRMSrcReg, (outs GR64:$dst), (ins GR8:$src),
-                       "movz{bq|x}\t{$src, $dst|$dst, $src}", []>, TB;
+                       "movz{bq|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVZ=
X>,
+                       TB;
 def MOVZX64rm8_Q : RI<0xB6, MRMSrcMem, (outs GR64:$dst), (ins i8mem:$src),
-                       "movz{bq|x}\t{$src, $dst|$dst, $src}", []>, TB;
+                       "movz{bq|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVZ=
X>,
+                       TB;
 def MOVZX64rr16_Q : RI<0xB7, MRMSrcReg, (outs GR64:$dst), (ins GR16:$src),
-                       "movz{wq|x}\t{$src, $dst|$dst, $src}", []>, TB;
+                       "movz{wq|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVZ=
X>,
+                       TB;
 def MOVZX64rm16_Q : RI<0xB7, MRMSrcMem, (outs GR64:$dst), (ins i16mem:$src=
),
-                       "movz{wq|x}\t{$src, $dst|$dst, $src}", []>, TB;
+                       "movz{wq|x}\t{$src, $dst|$dst, $src}", [], IIC_MOVZ=
X>,
+                       TB;
=20
 // FIXME: These should be Pat patterns.
 let isCodeGenOnly =3D 1 in {
@@ -124,15 +137,17 @@
 // Use movzbl instead of movzbq when the destination is a register; it's
 // equivalent due to implicit zero-extending, and it has a smaller encodin=
g.
 def MOVZX64rr8 : I<0xB6, MRMSrcReg, (outs GR64:$dst), (ins GR8 :$src),
-                   "", [(set GR64:$dst, (zext GR8:$src))]>, TB;
+                   "", [(set GR64:$dst, (zext GR8:$src))], IIC_MOVZX>, TB;
 def MOVZX64rm8 : I<0xB6, MRMSrcMem, (outs GR64:$dst), (ins i8mem :$src),
-                   "", [(set GR64:$dst, (zextloadi64i8 addr:$src))]>, TB;
+                   "", [(set GR64:$dst, (zextloadi64i8 addr:$src))], IIC_M=
OVZX>,
+                   TB;
 // Use movzwl instead of movzwq when the destination is a register; it's
 // equivalent due to implicit zero-extending, and it has a smaller encodin=
g.
 def MOVZX64rr16: I<0xB7, MRMSrcReg, (outs GR64:$dst), (ins GR16:$src),
-                   "", [(set GR64:$dst, (zext GR16:$src))]>, TB;
+                   "", [(set GR64:$dst, (zext GR16:$src))], IIC_MOVZX>, TB;
 def MOVZX64rm16: I<0xB7, MRMSrcMem, (outs GR64:$dst), (ins i16mem:$src),
-                   "", [(set GR64:$dst, (zextloadi64i16 addr:$src))]>, TB;
+                   "", [(set GR64:$dst, (zextloadi64i16 addr:$src))],
+                   IIC_MOVZX>, TB;
=20
 // There's no movzlq instruction, but movl can be used for this purpose, u=
sing
 // implicit zero-extension. The preferred way to do 32-bit-to-64-bit zero
@@ -142,10 +157,9 @@
 // necessarily all zero. In such cases, we fall back to these explicit zext
 // instructions.
 def MOVZX64rr32 : I<0x89, MRMDestReg, (outs GR64:$dst), (ins GR32:$src),
-                    "", [(set GR64:$dst, (zext GR32:$src))]>;
+                    "", [(set GR64:$dst, (zext GR32:$src))], IIC_MOVZX>;
 def MOVZX64rm32 : I<0x8B, MRMSrcMem, (outs GR64:$dst), (ins i32mem:$src),
-                    "", [(set GR64:$dst, (zextloadi64i32 addr:$src))]>;
-
-
+                    "", [(set GR64:$dst, (zextloadi64i32 addr:$src))],
+                    IIC_MOVZX>;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strFMA.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrFMA.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrFMA.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D- X86InstrFMA.td - Describe the X86 Instruction Set --*- tab=
legen -*-=3D=3D=3D//
+//=3D=3D=3D-- X86InstrFMA.td - FMA Instruction Set ---------------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,7 +15,7 @@
 // FMA3 - Intel 3 operand Fused Multiply-Add instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-multiclass fma_rm<bits<8> opc, string OpcodeStr> {
+multiclass fma3p_rm<bits<8> opc, string OpcodeStr> {
   def r : FMA3<opc, MRMSrcReg, (outs VR128:$dst),
            (ins VR128:$src1, VR128:$src2),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}"),
@@ -34,27 +34,187 @@
            []>;
 }
=20
-multiclass fma_forms<bits<8> opc132, bits<8> opc213, bits<8> opc231,
-                     string OpcodeStr, string PackTy> {
-  defm r132 : fma_rm<opc132, !strconcat(OpcodeStr, !strconcat("132", PackT=
y))>;
-  defm r213 : fma_rm<opc213, !strconcat(OpcodeStr, !strconcat("213", PackT=
y))>;
-  defm r231 : fma_rm<opc231, !strconcat(OpcodeStr, !strconcat("231", PackT=
y))>;
+multiclass fma3p_forms<bits<8> opc132, bits<8> opc213, bits<8> opc231,
+                       string OpcodeStr, string PackTy> {
+  defm r132 : fma3p_rm<opc132, !strconcat(OpcodeStr, !strconcat("132", Pac=
kTy))>;
+  defm r213 : fma3p_rm<opc213, !strconcat(OpcodeStr, !strconcat("213", Pac=
kTy))>;
+  defm r231 : fma3p_rm<opc231, !strconcat(OpcodeStr, !strconcat("231", Pac=
kTy))>;
 }
=20
-let isAsmParserOnly =3D 1 in {
-  // Fused Multiply-Add
-  defm VFMADDPS    : fma_forms<0x98, 0xA8, 0xB8, "vfmadd", "ps">;
-  defm VFMADDPD    : fma_forms<0x98, 0xA8, 0xB8, "vfmadd", "pd">, VEX_W;
-  defm VFMADDSUBPS : fma_forms<0x96, 0xA6, 0xB6, "vfmaddsub", "ps">;
-  defm VFMADDSUBPD : fma_forms<0x96, 0xA6, 0xB6, "vfmaddsub", "pd">, VEX_W;
-  defm VFMSUBADDPS : fma_forms<0x97, 0xA7, 0xB7, "vfmsubadd", "ps">;
-  defm VFMSUBADDPD : fma_forms<0x97, 0xA7, 0xB7, "vfmsubadd", "pd">, VEX_W;
-  defm VFMSUBPS    : fma_forms<0x9A, 0xAA, 0xBA, "vfmsub", "ps">;
-  defm VFMSUBPD    : fma_forms<0x9A, 0xAA, 0xBA, "vfmsub", "pd">, VEX_W;
+// Fused Multiply-Add
+let ExeDomain =3D SSEPackedSingle in {
+  defm VFMADDPS    : fma3p_forms<0x98, 0xA8, 0xB8, "vfmadd", "ps">;
+  defm VFMSUBPS    : fma3p_forms<0x9A, 0xAA, 0xBA, "vfmsub", "ps">;
+  defm VFMADDSUBPS : fma3p_forms<0x96, 0xA6, 0xB6, "vfmaddsub", "ps">;
+  defm VFMSUBADDPS : fma3p_forms<0x97, 0xA7, 0xB7, "vfmsubadd", "ps">;
+}
=20
-  // Fused Negative Multiply-Add
-  defm VFNMADDPS : fma_forms<0x9C, 0xAC, 0xBC, "vfnmadd", "ps">;
-  defm VFNMADDPD : fma_forms<0x9C, 0xAC, 0xBC, "vfnmadd", "pd">, VEX_W;
-  defm VFNMSUBPS : fma_forms<0x9E, 0xAE, 0xBE, "vfnmsub", "ps">;
-  defm VFNMSUBPD : fma_forms<0x9E, 0xAE, 0xBE, "vfnmsub", "pd">, VEX_W;
+let ExeDomain =3D SSEPackedDouble in {
+  defm VFMADDPD    : fma3p_forms<0x98, 0xA8, 0xB8, "vfmadd", "pd">, VEX_W;
+  defm VFMSUBPD    : fma3p_forms<0x9A, 0xAA, 0xBA, "vfmsub", "pd">, VEX_W;
+  defm VFMADDSUBPD : fma3p_forms<0x96, 0xA6, 0xB6, "vfmaddsub", "pd">, VEX=
_W;
+  defm VFMSUBADDPD : fma3p_forms<0x97, 0xA7, 0xB7, "vfmsubadd", "pd">, VEX=
_W;
 }
+
+// Fused Negative Multiply-Add
+let ExeDomain =3D SSEPackedSingle in {
+  defm VFNMADDPS : fma3p_forms<0x9C, 0xAC, 0xBC, "vfnmadd", "ps">;
+  defm VFNMSUBPS : fma3p_forms<0x9E, 0xAE, 0xBE, "vfnmsub", "ps">;
+}
+let ExeDomain =3D SSEPackedDouble in {
+  defm VFNMADDPD : fma3p_forms<0x9C, 0xAC, 0xBC, "vfnmadd", "pd">, VEX_W;
+  defm VFNMSUBPD : fma3p_forms<0x9E, 0xAE, 0xBE, "vfnmsub", "pd">, VEX_W;
+}
+
+multiclass fma3s_rm<bits<8> opc, string OpcodeStr, X86MemOperand x86memop>=
 {
+  def r : FMA3<opc, MRMSrcReg, (outs VR128:$dst),
+           (ins VR128:$src1, VR128:$src2),
+           !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}"),
+           []>;
+  def m : FMA3<opc, MRMSrcMem, (outs VR128:$dst),
+           (ins VR128:$src1, x86memop:$src2),
+           !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}"),
+           []>;
+}
+
+multiclass fma3s_forms<bits<8> opc132, bits<8> opc213, bits<8> opc231,
+                       string OpcodeStr> {
+  defm SSr132 : fma3s_rm<opc132, !strconcat(OpcodeStr, "132ss"), f32mem>;
+  defm SSr213 : fma3s_rm<opc213, !strconcat(OpcodeStr, "213ss"), f32mem>;
+  defm SSr231 : fma3s_rm<opc231, !strconcat(OpcodeStr, "231ss"), f32mem>;
+  defm SDr132 : fma3s_rm<opc132, !strconcat(OpcodeStr, "132sd"), f64mem>, =
VEX_W;
+  defm SDr213 : fma3s_rm<opc213, !strconcat(OpcodeStr, "213sd"), f64mem>, =
VEX_W;
+  defm SDr231 : fma3s_rm<opc231, !strconcat(OpcodeStr, "231sd"), f64mem>, =
VEX_W;
+}
+
+defm VFMADD : fma3s_forms<0x99, 0xA9, 0xB9, "vfmadd">, VEX_LIG;
+defm VFMSUB : fma3s_forms<0x9B, 0xAB, 0xBB, "vfmsub">, VEX_LIG;
+
+defm VFNMADD : fma3s_forms<0x9D, 0xAD, 0xBD, "vfnmadd">, VEX_LIG;
+defm VFNMSUB : fma3s_forms<0x9F, 0xAF, 0xBF, "vfnmsub">, VEX_LIG;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// FMA4 - AMD 4 operand Fused Multiply-Add instructions
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+
+multiclass fma4s<bits<8> opc, string OpcodeStr, Operand memop,
+                 ComplexPattern mem_cpat, Intrinsic Int> {
+  def rr : FMA4<opc, MRMSrcReg, (outs VR128:$dst),
+           (ins VR128:$src1, VR128:$src2, VR128:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR128:$dst,
+             (Int VR128:$src1, VR128:$src2, VR128:$src3))]>, VEX_W, MemOp4;
+  def rm : FMA4<opc, MRMSrcMem, (outs VR128:$dst),
+           (ins VR128:$src1, VR128:$src2, memop:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR128:$dst,
+             (Int VR128:$src1, VR128:$src2, mem_cpat:$src3))]>, VEX_W, Mem=
Op4;
+  def mr : FMA4<opc, MRMSrcMem, (outs VR128:$dst),
+           (ins VR128:$src1, memop:$src2, VR128:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR128:$dst,
+             (Int VR128:$src1, mem_cpat:$src2, VR128:$src3))]>;
+// For disassembler
+let isCodeGenOnly =3D 1 in
+  def rr_REV : FMA4<opc, MRMSrcReg, (outs VR128:$dst),
+               (ins VR128:$src1, VR128:$src2, VR128:$src3),
+               !strconcat(OpcodeStr,
+               "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),=
 []>;
+}
+
+multiclass fma4p<bits<8> opc, string OpcodeStr,
+                 Intrinsic Int128, Intrinsic Int256,
+                 PatFrag ld_frag128, PatFrag ld_frag256> {
+  def rr : FMA4<opc, MRMSrcReg, (outs VR128:$dst),
+           (ins VR128:$src1, VR128:$src2, VR128:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR128:$dst,
+             (Int128 VR128:$src1, VR128:$src2, VR128:$src3))]>, VEX_W, Mem=
Op4;
+  def rm : FMA4<opc, MRMSrcMem, (outs VR128:$dst),
+           (ins VR128:$src1, VR128:$src2, f128mem:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR128:$dst, (Int128 VR128:$src1, VR128:$src2,
+                              (ld_frag128 addr:$src3)))]>, VEX_W, MemOp4;
+  def mr : FMA4<opc, MRMSrcMem, (outs VR128:$dst),
+           (ins VR128:$src1, f128mem:$src2, VR128:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR128:$dst,
+             (Int128 VR128:$src1, (ld_frag128 addr:$src2), VR128:$src3))]>;
+  def rrY : FMA4<opc, MRMSrcReg, (outs VR256:$dst),
+           (ins VR256:$src1, VR256:$src2, VR256:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR256:$dst,
+             (Int256 VR256:$src1, VR256:$src2, VR256:$src3))]>, VEX_W, Mem=
Op4;
+  def rmY : FMA4<opc, MRMSrcMem, (outs VR256:$dst),
+           (ins VR256:$src1, VR256:$src2, f256mem:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR256:$dst, (Int256 VR256:$src1, VR256:$src2,
+                              (ld_frag256 addr:$src3)))]>, VEX_W, MemOp4;
+  def mrY : FMA4<opc, MRMSrcMem, (outs VR256:$dst),
+           (ins VR256:$src1, f256mem:$src2, VR256:$src3),
+           !strconcat(OpcodeStr,
+           "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+           [(set VR256:$dst,
+             (Int256 VR256:$src1, (ld_frag256 addr:$src2), VR256:$src3))]>;
+// For disassembler
+let isCodeGenOnly =3D 1 in {
+  def rr_REV : FMA4<opc, MRMSrcReg, (outs VR128:$dst),
+               (ins VR128:$src1, VR128:$src2, VR128:$src3),
+               !strconcat(OpcodeStr,
+               "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),=
 []>;
+  def rrY_REV : FMA4<opc, MRMSrcReg, (outs VR256:$dst),
+                (ins VR256:$src1, VR256:$src2, VR256:$src3),
+                !strconcat(OpcodeStr,
+                "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}")=
, []>;
+} // isCodeGenOnly =3D 1
+}
+
+defm VFMADDSS4    : fma4s<0x6A, "vfmaddss", ssmem, sse_load_f32,
+                          int_x86_fma4_vfmadd_ss>;
+defm VFMADDSD4    : fma4s<0x6B, "vfmaddsd", sdmem, sse_load_f64,
+                          int_x86_fma4_vfmadd_sd>;
+defm VFMADDPS4    : fma4p<0x68, "vfmaddps", int_x86_fma4_vfmadd_ps,
+                          int_x86_fma4_vfmadd_ps_256, memopv4f32, memopv8f=
32>;
+defm VFMADDPD4    : fma4p<0x69, "vfmaddpd", int_x86_fma4_vfmadd_pd,
+                          int_x86_fma4_vfmadd_pd_256, memopv2f64, memopv4f=
64>;
+defm VFMSUBSS4    : fma4s<0x6E, "vfmsubss", ssmem, sse_load_f32,
+                          int_x86_fma4_vfmsub_ss>;
+defm VFMSUBSD4    : fma4s<0x6F, "vfmsubsd", sdmem, sse_load_f64,
+                          int_x86_fma4_vfmsub_sd>;
+defm VFMSUBPS4    : fma4p<0x6C, "vfmsubps", int_x86_fma4_vfmsub_ps,
+                          int_x86_fma4_vfmsub_ps_256, memopv4f32, memopv8f=
32>;
+defm VFMSUBPD4    : fma4p<0x6D, "vfmsubpd", int_x86_fma4_vfmsub_pd,
+                          int_x86_fma4_vfmsub_pd_256, memopv2f64, memopv4f=
64>;
+defm VFNMADDSS4   : fma4s<0x7A, "vfnmaddss", ssmem, sse_load_f32,
+                          int_x86_fma4_vfnmadd_ss>;
+defm VFNMADDSD4   : fma4s<0x7B, "vfnmaddsd", sdmem, sse_load_f64,
+                          int_x86_fma4_vfnmadd_sd>;
+defm VFNMADDPS4   : fma4p<0x78, "vfnmaddps", int_x86_fma4_vfnmadd_ps,
+                          int_x86_fma4_vfnmadd_ps_256, memopv4f32, memopv8=
f32>;
+defm VFNMADDPD4   : fma4p<0x79, "vfnmaddpd", int_x86_fma4_vfnmadd_pd,
+                          int_x86_fma4_vfnmadd_pd_256, memopv2f64, memopv4=
f64>;
+defm VFNMSUBSS4   : fma4s<0x7E, "vfnmsubss", ssmem, sse_load_f32,
+                          int_x86_fma4_vfnmsub_ss>;
+defm VFNMSUBSD4   : fma4s<0x7F, "vfnmsubsd", sdmem, sse_load_f64,
+                          int_x86_fma4_vfnmsub_sd>;
+defm VFNMSUBPS4   : fma4p<0x7C, "vfnmsubps", int_x86_fma4_vfnmsub_ps,
+                          int_x86_fma4_vfnmsub_ps_256, memopv4f32, memopv8=
f32>;
+defm VFNMSUBPD4   : fma4p<0x7D, "vfnmsubpd", int_x86_fma4_vfnmsub_pd,
+                          int_x86_fma4_vfnmsub_pd_256, memopv2f64, memopv4=
f64>;
+defm VFMADDSUBPS4 : fma4p<0x5C, "vfmaddsubps", int_x86_fma4_vfmaddsub_ps,
+                         int_x86_fma4_vfmaddsub_ps_256, memopv4f32, memopv=
8f32>;
+defm VFMADDSUBPD4 : fma4p<0x5D, "vfmaddsubpd", int_x86_fma4_vfmaddsub_pd,
+                         int_x86_fma4_vfmaddsub_pd_256, memopv2f64, memopv=
4f64>;
+defm VFMSUBADDPS4 : fma4p<0x5E, "vfmsubaddps", int_x86_fma4_vfmsubadd_ps,
+                         int_x86_fma4_vfmsubadd_ps_256, memopv4f32, memopv=
8f32>;
+defm VFMSUBADDPD4 : fma4p<0x5F, "vfmsubaddpd", int_x86_fma4_vfmsubadd_pd,
+                         int_x86_fma4_vfmsubadd_pd_256, memopv2f64, memopv=
4f64>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strFPStack.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrFPStack.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrFPStack.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D- X86InstrFPStack.td - Describe the X86 Instruction Set --*- table=
gen -*-=3D//
-//=20
+//=3D=3D=3D- X86InstrFPStack.td - FPU Instruction Set ------------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the X86 x87 FPU instruction set, defining the
@@ -225,22 +225,22 @@
 // of some of the 'reverse' forms of the fsub and fdiv instructions.  As s=
uch,
 // we have to put some 'r's in and take them out of weird places.
 def ADD_FST0r   : FPST0rInst <0xC0, "fadd\t$op">;
-def ADD_FrST0   : FPrST0Inst <0xC0, "fadd\t{%st(0), $op|$op, %ST(0)}">;
+def ADD_FrST0   : FPrST0Inst <0xC0, "fadd\t{%st(0), $op|$op, ST(0)}">;
 def ADD_FPrST0  : FPrST0PInst<0xC0, "faddp\t$op">;
 def SUBR_FST0r  : FPST0rInst <0xE8, "fsubr\t$op">;
-def SUB_FrST0   : FPrST0Inst <0xE8, "fsub{r}\t{%st(0), $op|$op, %ST(0)}">;
+def SUB_FrST0   : FPrST0Inst <0xE8, "fsub{r}\t{%st(0), $op|$op, ST(0)}">;
 def SUB_FPrST0  : FPrST0PInst<0xE8, "fsub{r}p\t$op">;
 def SUB_FST0r   : FPST0rInst <0xE0, "fsub\t$op">;
-def SUBR_FrST0  : FPrST0Inst <0xE0, "fsub{|r}\t{%st(0), $op|$op, %ST(0)}">;
+def SUBR_FrST0  : FPrST0Inst <0xE0, "fsub{|r}\t{%st(0), $op|$op, ST(0)}">;
 def SUBR_FPrST0 : FPrST0PInst<0xE0, "fsub{|r}p\t$op">;
 def MUL_FST0r   : FPST0rInst <0xC8, "fmul\t$op">;
-def MUL_FrST0   : FPrST0Inst <0xC8, "fmul\t{%st(0), $op|$op, %ST(0)}">;
+def MUL_FrST0   : FPrST0Inst <0xC8, "fmul\t{%st(0), $op|$op, ST(0)}">;
 def MUL_FPrST0  : FPrST0PInst<0xC8, "fmulp\t$op">;
 def DIVR_FST0r  : FPST0rInst <0xF8, "fdivr\t$op">;
-def DIV_FrST0   : FPrST0Inst <0xF8, "fdiv{r}\t{%st(0), $op|$op, %ST(0)}">;
+def DIV_FrST0   : FPrST0Inst <0xF8, "fdiv{r}\t{%st(0), $op|$op, ST(0)}">;
 def DIV_FPrST0  : FPrST0PInst<0xF8, "fdiv{r}p\t$op">;
 def DIV_FST0r   : FPST0rInst <0xF0, "fdiv\t$op">;
-def DIVR_FrST0  : FPrST0Inst <0xF0, "fdiv{|r}\t{%st(0), $op|$op, %ST(0)}">;
+def DIVR_FrST0  : FPrST0Inst <0xF0, "fdiv{|r}\t{%st(0), $op|$op, ST(0)}">;
 def DIVR_FPrST0 : FPrST0PInst<0xF0, "fdiv{|r}p\t$op">;
=20
 def COM_FST0r   : FPST0rInst <0xD0, "fcom\t$op">;
@@ -330,21 +330,21 @@
 let Predicates =3D [HasCMov] in {
 // These are not factored because there's no clean way to pass DA/DB.
 def CMOVB_F  : FPI<0xC0, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmovb\t{$op, %st(0)|%ST(0), $op}">, DA;
+                  "fcmovb\t{$op, %st(0)|ST(0), $op}">, DA;
 def CMOVBE_F : FPI<0xD0, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmovbe\t{$op, %st(0)|%ST(0), $op}">, DA;
+                  "fcmovbe\t{$op, %st(0)|ST(0), $op}">, DA;
 def CMOVE_F  : FPI<0xC8, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmove\t{$op, %st(0)|%ST(0), $op}">, DA;
+                  "fcmove\t{$op, %st(0)|ST(0), $op}">, DA;
 def CMOVP_F  : FPI<0xD8, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmovu\t {$op, %st(0)|%ST(0), $op}">, DA;
+                  "fcmovu\t {$op, %st(0)|ST(0), $op}">, DA;
 def CMOVNB_F : FPI<0xC0, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmovnb\t{$op, %st(0)|%ST(0), $op}">, DB;
+                  "fcmovnb\t{$op, %st(0)|ST(0), $op}">, DB;
 def CMOVNBE_F: FPI<0xD0, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmovnbe\t{$op, %st(0)|%ST(0), $op}">, DB;
+                  "fcmovnbe\t{$op, %st(0)|ST(0), $op}">, DB;
 def CMOVNE_F : FPI<0xC8, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmovne\t{$op, %st(0)|%ST(0), $op}">, DB;
+                  "fcmovne\t{$op, %st(0)|ST(0), $op}">, DB;
 def CMOVNP_F : FPI<0xD8, AddRegFrm, (outs RST:$op), (ins),
-                  "fcmovnu\t{$op, %st(0)|%ST(0), $op}">, DB;
+                  "fcmovnu\t{$op, %st(0)|ST(0), $op}">, DB;
 } // Predicates =3D [HasCMov]
=20
 // Floating point loads & stores.
@@ -437,33 +437,26 @@
 }
=20
 // FISTTP requires SSE3 even though it's a FPStack op.
+let Predicates =3D [HasSSE3] in {
 def ISTT_Fp16m32 : FpI_<(outs), (ins i16mem:$op, RFP32:$src), OneArgFP,
-                    [(X86fp_to_i16mem RFP32:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i16mem RFP32:$src, addr:$op)]>;
 def ISTT_Fp32m32 : FpI_<(outs), (ins i32mem:$op, RFP32:$src), OneArgFP,
-                    [(X86fp_to_i32mem RFP32:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i32mem RFP32:$src, addr:$op)]>;
 def ISTT_Fp64m32 : FpI_<(outs), (ins i64mem:$op, RFP32:$src), OneArgFP,
-                    [(X86fp_to_i64mem RFP32:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i64mem RFP32:$src, addr:$op)]>;
 def ISTT_Fp16m64 : FpI_<(outs), (ins i16mem:$op, RFP64:$src), OneArgFP,
-                    [(X86fp_to_i16mem RFP64:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i16mem RFP64:$src, addr:$op)]>;
 def ISTT_Fp32m64 : FpI_<(outs), (ins i32mem:$op, RFP64:$src), OneArgFP,
-                    [(X86fp_to_i32mem RFP64:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i32mem RFP64:$src, addr:$op)]>;
 def ISTT_Fp64m64 : FpI_<(outs), (ins i64mem:$op, RFP64:$src), OneArgFP,
-                    [(X86fp_to_i64mem RFP64:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i64mem RFP64:$src, addr:$op)]>;
 def ISTT_Fp16m80 : FpI_<(outs), (ins i16mem:$op, RFP80:$src), OneArgFP,
-                    [(X86fp_to_i16mem RFP80:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i16mem RFP80:$src, addr:$op)]>;
 def ISTT_Fp32m80 : FpI_<(outs), (ins i32mem:$op, RFP80:$src), OneArgFP,
-                    [(X86fp_to_i32mem RFP80:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i32mem RFP80:$src, addr:$op)]>;
 def ISTT_Fp64m80 : FpI_<(outs), (ins i64mem:$op, RFP80:$src), OneArgFP,
-                    [(X86fp_to_i64mem RFP80:$src, addr:$op)]>,
-                    Requires<[HasSSE3]>;
+                    [(X86fp_to_i64mem RFP80:$src, addr:$op)]>;
+} // Predicates =3D [HasSSE3]
=20
 let mayStore =3D 1 in {
 def ISTT_FP16m : FPI<0xDF, MRM1m, (outs), (ins i16mem:$dst), "fisttp{s}\t$=
dst">;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strFormats.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrFormats.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrFormats.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86InstrFormats.td - X86 Instruction Formats --------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86InstrFormats.td - X86 Instruction Formats -------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -43,6 +43,15 @@
 def RawFrmImm16 : Format<44>;
 def MRM_D0 : Format<45>;
 def MRM_D1 : Format<46>;
+def MRM_D4 : Format<47>;
+def MRM_D8 : Format<48>;
+def MRM_D9 : Format<49>;
+def MRM_DA : Format<50>;
+def MRM_DB : Format<51>;
+def MRM_DC : Format<52>;
+def MRM_DD : Format<53>;
+def MRM_DE : Format<54>;
+def MRM_DF : Format<55>;
=20
 // ImmType - This specifies the immediate type used by an instruction. Thi=
s is
 // part of the ad-hoc solution used to emit machine instruction encodings =
by our
@@ -107,17 +116,25 @@
 class TA     { bits<5> Prefix =3D 14; }
 class A6     { bits<5> Prefix =3D 15; }
 class A7     { bits<5> Prefix =3D 16; }
-class TF     { bits<5> Prefix =3D 17; }
+class T8XD   { bits<5> Prefix =3D 17; }
+class T8XS   { bits<5> Prefix =3D 18; }
+class TAXD   { bits<5> Prefix =3D 19; }
+class XOP8   { bits<5> Prefix =3D 20; }
+class XOP9   { bits<5> Prefix =3D 21; }
 class VEX    { bit hasVEXPrefix =3D 1; }
 class VEX_W  { bit hasVEX_WPrefix =3D 1; }
 class VEX_4V : VEX { bit hasVEX_4VPrefix =3D 1; }
+class VEX_4VOp3 : VEX { bit hasVEX_4VOp3Prefix =3D 1; }
 class VEX_I8IMM { bit hasVEX_i8ImmReg =3D 1; }
 class VEX_L  { bit hasVEX_L =3D 1; }
 class VEX_LIG { bit ignoresVEX_L =3D 1; }
 class Has3DNow0F0FOpcode  { bit has3DNow0F0FOpcode =3D 1; }
-
+class MemOp4 { bit hasMemOp4Prefix =3D 1; }
+class XOP { bit hasXOP_Prefix =3D 1; }
 class X86Inst<bits<8> opcod, Format f, ImmType i, dag outs, dag ins,
-              string AsmStr, Domain d =3D GenericDomain>
+              string AsmStr,
+              InstrItinClass itin,
+              Domain d =3D GenericDomain>
   : Instruction {
   let Namespace =3D "X86";
=20
@@ -133,6 +150,8 @@
   // If this is a pseudo instruction, mark it isCodeGenOnly.
   let isCodeGenOnly =3D !eq(!cast<string>(f), "Pseudo");
=20
+  let Itinerary =3D itin;
+
   //
   // Attributes specific to X86 instructions...
   //
@@ -148,11 +167,15 @@
   bit hasVEXPrefix =3D 0;     // Does this inst require a VEX prefix?
   bit hasVEX_WPrefix =3D 0;   // Does this inst set the VEX_W field?
   bit hasVEX_4VPrefix =3D 0;  // Does this inst require the VEX.VVVV field?
+  bit hasVEX_4VOp3Prefix =3D 0;  // Does this inst require the VEX.VVVV fi=
eld to
+                               // encode the third operand?
   bit hasVEX_i8ImmReg =3D 0;  // Does this inst require the last source re=
gister
                             // to be encoded in a immediate field?
   bit hasVEX_L =3D 0;         // Does this inst use large (256-bit) regist=
ers?
   bit ignoresVEX_L =3D 0;     // Does this instruction ignore the L-bit
   bit has3DNow0F0FOpcode =3D0;// Wacky 3dNow! encoding?
+  bit hasMemOp4Prefix =3D 0;  // Same bit as VEX_W, but used for swapping =
operands
+  bit hasXOP_Prefix =3D 0;    // Does this inst require an XOP prefix?
=20
   // TSFlags layout should be kept in sync with X86InstrInfo.h.
   let TSFlags{5-0}   =3D FormBits;
@@ -169,58 +192,63 @@
   let TSFlags{33}    =3D hasVEXPrefix;
   let TSFlags{34}    =3D hasVEX_WPrefix;
   let TSFlags{35}    =3D hasVEX_4VPrefix;
-  let TSFlags{36}    =3D hasVEX_i8ImmReg;
-  let TSFlags{37}    =3D hasVEX_L;
-  let TSFlags{38}    =3D ignoresVEX_L;
-  let TSFlags{39}    =3D has3DNow0F0FOpcode;
+  let TSFlags{36}    =3D hasVEX_4VOp3Prefix;
+  let TSFlags{37}    =3D hasVEX_i8ImmReg;
+  let TSFlags{38}    =3D hasVEX_L;
+  let TSFlags{39}    =3D ignoresVEX_L;
+  let TSFlags{40}    =3D has3DNow0F0FOpcode;
+  let TSFlags{41}    =3D hasMemOp4Prefix;
+  let TSFlags{42}    =3D hasXOP_Prefix;
 }
=20
 class PseudoI<dag oops, dag iops, list<dag> pattern>
-  : X86Inst<0, Pseudo, NoImm, oops, iops, ""> {
+  : X86Inst<0, Pseudo, NoImm, oops, iops, "", NoItinerary> {
   let Pattern =3D pattern;
 }
=20
 class I<bits<8> o, Format f, dag outs, dag ins, string asm,
-        list<dag> pattern, Domain d =3D GenericDomain>
-  : X86Inst<o, f, NoImm, outs, ins, asm, d> {
+        list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT,
+        Domain d =3D GenericDomain>
+  : X86Inst<o, f, NoImm, outs, ins, asm, itin, d> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
 class Ii8 <bits<8> o, Format f, dag outs, dag ins, string asm,=20
-           list<dag> pattern, Domain d =3D GenericDomain>
-  : X86Inst<o, f, Imm8, outs, ins, asm, d> {
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT,
+           Domain d =3D GenericDomain>
+  : X86Inst<o, f, Imm8, outs, ins, asm, itin, d> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
 class Ii8PCRel<bits<8> o, Format f, dag outs, dag ins, string asm,=20
-               list<dag> pattern>
-  : X86Inst<o, f, Imm8PCRel, outs, ins, asm> {
+               list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+  : X86Inst<o, f, Imm8PCRel, outs, ins, asm, itin> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
 class Ii16<bits<8> o, Format f, dag outs, dag ins, string asm,=20
-           list<dag> pattern>
-  : X86Inst<o, f, Imm16, outs, ins, asm> {
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+  : X86Inst<o, f, Imm16, outs, ins, asm, itin> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
 class Ii32<bits<8> o, Format f, dag outs, dag ins, string asm,=20
-           list<dag> pattern>
-  : X86Inst<o, f, Imm32, outs, ins, asm> {
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+  : X86Inst<o, f, Imm32, outs, ins, asm, itin> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
=20
 class Ii16PCRel<bits<8> o, Format f, dag outs, dag ins, string asm,=20
-           list<dag> pattern>
-  : X86Inst<o, f, Imm16PCRel, outs, ins, asm> {
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+           : X86Inst<o, f, Imm16PCRel, outs, ins, asm, itin> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
=20
 class Ii32PCRel<bits<8> o, Format f, dag outs, dag ins, string asm,=20
-           list<dag> pattern>
-  : X86Inst<o, f, Imm32PCRel, outs, ins, asm> {
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+  : X86Inst<o, f, Imm32PCRel, outs, ins, asm, itin> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
@@ -231,8 +259,9 @@
   : I<o, F, outs, ins, asm, []> {}
=20
 // FpI_ - Floating Point Pseudo Instruction template. Not Predicated.
-class FpI_<dag outs, dag ins, FPFormat fp, list<dag> pattern>
-  : X86Inst<0, Pseudo, NoImm, outs, ins, ""> {
+class FpI_<dag outs, dag ins, FPFormat fp, list<dag> pattern,
+           InstrItinClass itin =3D IIC_DEFAULT>
+  : X86Inst<0, Pseudo, NoImm, outs, ins, "", itin> {
   let FPForm =3D fp;
   let Pattern =3D pattern;
 }
@@ -244,20 +273,23 @@
 //   Iseg32 - 16-bit segment selector, 32-bit offset
=20
 class Iseg16 <bits<8> o, Format f, dag outs, dag ins, string asm,=20
-              list<dag> pattern> : X86Inst<o, f, Imm16, outs, ins, asm> {
+              list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : X86Inst<o, f, Imm16, outs, ins, asm, itin> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
=20
 class Iseg32 <bits<8> o, Format f, dag outs, dag ins, string asm,=20
-              list<dag> pattern> : X86Inst<o, f, Imm32, outs, ins, asm> {
+              list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : X86Inst<o, f, Imm32, outs, ins, asm, itin> {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
=20
 // SI - SSE 1 & 2 scalar instructions
-class SI<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pat=
tern>
-      : I<o, F, outs, ins, asm, pattern> {
+class SI<bits<8> o, Format F, dag outs, dag ins, string asm,
+         list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin> {
   let Predicates =3D !if(hasVEXPrefix /* VEX */, [HasAVX],
             !if(!eq(Prefix, 12 /* XS */), [HasSSE1], [HasSSE2]));
=20
@@ -267,8 +299,8 @@
=20
 // SIi8 - SSE 1 & 2 scalar instructions
 class SIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern> {
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin> {
   let Predicates =3D !if(hasVEXPrefix /* VEX */, [HasAVX],
             !if(!eq(Prefix, 12 /* XS */), [HasSSE1], [HasSSE2]));
=20
@@ -278,8 +310,8 @@
=20
 // PI - SSE 1 & 2 packed instructions
 class PI<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pat=
tern,
-         Domain d>
-      : I<o, F, outs, ins, asm, pattern, d> {
+         InstrItinClass itin, Domain d>
+      : I<o, F, outs, ins, asm, pattern, itin, d> {
   let Predicates =3D !if(hasVEXPrefix /* VEX */, [HasAVX],
         !if(hasOpSizePrefix /* OpSize */, [HasSSE2], [HasSSE1]));
=20
@@ -289,8 +321,8 @@
=20
 // PIi8 - SSE 1 & 2 packed instructions with immediate
 class PIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern, Domain d>
-      : Ii8<o, F, outs, ins, asm, pattern, d> {
+           list<dag> pattern, InstrItinClass itin, Domain d>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, d> {
   let Predicates =3D !if(hasVEX_4VPrefix /* VEX */, [HasAVX],
         !if(hasOpSizePrefix /* OpSize */, [HasSSE2], [HasSSE1]));
=20
@@ -306,25 +338,27 @@
 //   VSSI  - SSE1 instructions with XS prefix in AVX form.
 //   VPSI  - SSE1 instructions with TB prefix in AVX form.
=20
-class SSI<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pa=
ttern>
-      : I<o, F, outs, ins, asm, pattern>, XS, Requires<[HasSSE1]>;
+class SSI<bits<8> o, Format F, dag outs, dag ins, string asm,
+          list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, XS, Requires<[HasSSE1]>;
 class SSIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern>, XS, Requires<[HasSSE1]>;
-class PSI<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pa=
ttern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedSingle>, TB,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin>, XS, Requires<[HasSSE1]>;
+class PSI<bits<8> o, Format F, dag outs, dag ins, string asm,
+          list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedSingle>, TB,
         Requires<[HasSSE1]>;
 class PSIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedSingle>, TB,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedSingle>, TB,
         Requires<[HasSSE1]>;
 class VSSI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : I<o, F, outs, ins, !strconcat("v", asm), pattern>, XS,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, !strconcat("v", asm), pattern, itin>, XS,
         Requires<[HasAVX]>;
 class VPSI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : I<o, F, outs, ins, !strconcat("v", asm), pattern, SSEPackedSingle>=
, TB,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, !strconcat("v", asm), pattern, itin, SSEPackedS=
ingle>, TB,
         Requires<[HasAVX]>;
=20
 // SSE2 Instruction Templates:
@@ -337,28 +371,30 @@
 //   VSDI   - SSE2 instructions with XD prefix in AVX form.
 //   VPDI   - SSE2 instructions with TB and OpSize prefixes in AVX form.
=20
-class SDI<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pa=
ttern>
-      : I<o, F, outs, ins, asm, pattern>, XD, Requires<[HasSSE2]>;
+class SDI<bits<8> o, Format F, dag outs, dag ins, string asm,
+          list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, XD, Requires<[HasSSE2]>;
 class SDIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern>, XD, Requires<[HasSSE2]>;
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin>, XD, Requires<[HasSSE2]>;
 class SSDIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
              list<dag> pattern>
       : Ii8<o, F, outs, ins, asm, pattern>, XS, Requires<[HasSSE2]>;
-class PDI<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pa=
ttern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedDouble>, TB, OpSize,
+class PDI<bits<8> o, Format F, dag outs, dag ins, string asm,
+          list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedDouble>, TB, OpSiz=
e,
         Requires<[HasSSE2]>;
 class PDIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedDouble>, TB, OpSize,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedDouble>, TB, OpS=
ize,
         Requires<[HasSSE2]>;
 class VSDI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : I<o, F, outs, ins, !strconcat("v", asm), pattern>, XD,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, !strconcat("v", asm), pattern, itin>, XD,
         Requires<[HasAVX]>;
 class VPDI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : I<o, F, outs, ins, !strconcat("v", asm), pattern, SSEPackedDouble>=
, TB,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, !strconcat("v", asm), pattern, itin, SSEPackedD=
ouble>, TB,
         OpSize, Requires<[HasAVX]>;
=20
 // SSE3 Instruction Templates:
@@ -368,15 +404,16 @@
 //   S3DI  - SSE3 instructions with XD prefix.
=20
 class S3SI<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-           list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedSingle>, XS,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedSingle>, XS,
         Requires<[HasSSE3]>;
 class S3DI<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-           list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedDouble>, XD,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedDouble>, XD,
         Requires<[HasSSE3]>;
-class S3I<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pa=
ttern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedDouble>, TB, OpSize,
+class S3I<bits<8> o, Format F, dag outs, dag ins, string asm,
+          list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedDouble>, TB, OpSiz=
e,
         Requires<[HasSSE3]>;
=20
=20
@@ -386,16 +423,16 @@
 //   SS3AI - SSSE3 instructions with TA prefix.
 //
 // Note: SSSE3 instructions have 64-bit and 128-bit versions. The 64-bit v=
ersion
-// uses the MMX registers. We put those instructions here because they bet=
ter
-// fit into the SSSE3 instruction category rather than the MMX category.
+// uses the MMX registers. The 64-bit versions are grouped with the MMX
+// classes. They need to be enabled even if AVX is enabled.
=20
 class SS38I<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, T8,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, T8,
         Requires<[HasSSSE3]>;
 class SS3AI<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, TA,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
         Requires<[HasSSSE3]>;
=20
 // SSE4.1 Instruction Templates:
@@ -404,31 +441,31 @@
 //   SS41AIi8 - SSE 4.1 instructions with TA prefix and ImmT =3D=3D Imm8.
 //
 class SS48I<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedInt>, T8,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, T8,
         Requires<[HasSSE41]>;
 class SS4AIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, TA,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
         Requires<[HasSSE41]>;
=20
 // SSE4.2 Instruction Templates:
 //=20
 //   SS428I - SSE 4.2 instructions with T8 prefix.
 class SS428I<bits<8> o, Format F, dag outs, dag ins, string asm,
-             list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedInt>, T8,
+             list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, T8,
         Requires<[HasSSE42]>;
=20
-//   SS42FI - SSE 4.2 instructions with TF prefix.
+//   SS42FI - SSE 4.2 instructions with T8XD prefix.
 class SS42FI<bits<8> o, Format F, dag outs, dag ins, string asm,
-              list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern>, TF, Requires<[HasSSE42]>;
-     =20
+             list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, T8XD, Requires<[HasSSE42]>;
+
 //   SS42AI =3D SSE 4.2 instructions with TA prefix
 class SS42AI<bits<8> o, Format F, dag outs, dag ins, string asm,
-             list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, TA,
+             list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
         Requires<[HasSSE42]>;
=20
 // AVX Instruction Templates:
@@ -437,76 +474,115 @@
 //   AVX8I - AVX instructions with T8 and OpSize prefix.
 //   AVXAIi8 - AVX instructions with TA, OpSize prefix and ImmT =3D Imm8.
 class AVX8I<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedInt>, T8, OpSize,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, T8, OpSize,
         Requires<[HasAVX]>;
 class AVXAIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-              list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, TA, OpSize,
+              list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA, OpSize,
         Requires<[HasAVX]>;
=20
+// AVX2 Instruction Templates:
+//   Instructions introduced in AVX2 (no SSE equivalent forms)
+//
+//   AVX28I - AVX2 instructions with T8 and OpSize prefix.
+//   AVX2AIi8 - AVX2 instructions with TA, OpSize prefix and ImmT =3D Imm8.
+class AVX28I<bits<8> o, Format F, dag outs, dag ins, string asm,
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, T8, OpSize,
+        Requires<[HasAVX2]>;
+class AVX2AIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
+              list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA, OpSize,
+        Requires<[HasAVX2]>;
+
 // AES Instruction Templates:
 //
 // AES8I
 // These use the same encoding as the SSE4.2 T8 and TA encodings.
 class AES8I<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag>pattern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedInt>, T8,
-        Requires<[HasAES]>;
+            list<dag>pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, T8,
+        Requires<[HasSSE2, HasAES]>;
=20
 class AESAI<bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, TA,
-        Requires<[HasAES]>;
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
+        Requires<[HasSSE2, HasAES]>;
=20
 // CLMUL Instruction Templates
 class CLMULIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-               list<dag>pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, TA,
-        OpSize, Requires<[HasCLMUL]>;
+               list<dag>pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
+        OpSize, Requires<[HasSSE2, HasCLMUL]>;
=20
 class AVXCLMULIi8<bits<8> o, Format F, dag outs, dag ins, string asm,
-                  list<dag>pattern>
-      : Ii8<o, F, outs, ins, asm, pattern, SSEPackedInt>, TA,
+                  list<dag>pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
         OpSize, VEX_4V, Requires<[HasAVX, HasCLMUL]>;
=20
 // FMA3 Instruction Templates
 class FMA3<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag>pattern>
-      : I<o, F, outs, ins, asm, pattern, SSEPackedInt>, T8,
+           list<dag>pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, T8,
         OpSize, VEX_4V, Requires<[HasFMA3]>;
=20
+// FMA4 Instruction Templates
+class FMA4<bits<8> o, Format F, dag outs, dag ins, string asm,
+           list<dag>pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
+        OpSize, VEX_4V, VEX_I8IMM, Requires<[HasFMA4]>;
+
+// XOP 2, 3 and 4 Operand Instruction Template
+class IXOP<bits<8> o, Format F, dag outs, dag ins, string asm,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin, SSEPackedDouble>,
+         XOP, XOP9, Requires<[HasXOP]>;
+
+// XOP 2, 3 and 4 Operand Instruction Templates with imm byte
+class IXOPi8<bits<8> o, Format F, dag outs, dag ins, string asm,
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedDouble>,
+         XOP, XOP8, Requires<[HasXOP]>;
+
+//  XOP 5 operand instruction (VEX encoding!)
+class IXOP5<bits<8> o, Format F, dag outs, dag ins, string asm,
+           list<dag>pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin, SSEPackedInt>, TA,
+        OpSize, VEX_4V, VEX_I8IMM, Requires<[HasXOP]>;
+
 // X86-64 Instruction templates...
 //
=20
-class RI<bits<8> o, Format F, dag outs, dag ins, string asm, list<dag> pat=
tern>
-      : I<o, F, outs, ins, asm, pattern>, REX_W;
+class RI<bits<8> o, Format F, dag outs, dag ins, string asm,
+         list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, REX_W;
 class RIi8 <bits<8> o, Format F, dag outs, dag ins, string asm,
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern>, REX_W;
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin>, REX_W;
 class RIi32 <bits<8> o, Format F, dag outs, dag ins, string asm,
-             list<dag> pattern>
-      : Ii32<o, F, outs, ins, asm, pattern>, REX_W;
+             list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii32<o, F, outs, ins, asm, pattern, itin>, REX_W;
=20
 class RIi64<bits<8> o, Format f, dag outs, dag ins, string asm,
-            list<dag> pattern>
-  : X86Inst<o, f, Imm64, outs, ins, asm>, REX_W {
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+  : X86Inst<o, f, Imm64, outs, ins, asm, itin>, REX_W {
   let Pattern =3D pattern;
   let CodeSize =3D 3;
 }
=20
 class RSSI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : SSI<o, F, outs, ins, asm, pattern>, REX_W;
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : SSI<o, F, outs, ins, asm, pattern, itin>, REX_W;
 class RSDI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : SDI<o, F, outs, ins, asm, pattern>, REX_W;
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : SDI<o, F, outs, ins, asm, pattern, itin>, REX_W;
 class RPDI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : PDI<o, F, outs, ins, asm, pattern>, REX_W;
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : PDI<o, F, outs, ins, asm, pattern, itin>, REX_W;
 class VRPDI<bits<8> o, Format F, dag outs, dag ins, string asm,
-           list<dag> pattern>
-      : VPDI<o, F, outs, ins, asm, pattern>, VEX_W;
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : VPDI<o, F, outs, ins, asm, pattern, itin>, VEX_W;
=20
 // MMX Instruction templates
 //
@@ -519,23 +595,23 @@
 // MMXID  - MMX instructions with XD prefix.
 // MMXIS  - MMX instructions with XS prefix.
 class MMXI<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-           list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern>, TB, Requires<[HasMMX]>;
+           list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, TB, Requires<[HasMMX]>;
 class MMXI64<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-             list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern>, TB, Requires<[HasMMX,In64BitMode=
]>;
+             list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, TB, Requires<[HasMMX,In64B=
itMode]>;
 class MMXRI<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-            list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern>, TB, REX_W, Requires<[HasMMX]>;
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, TB, REX_W, Requires<[HasMM=
X]>;
 class MMX2I<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-            list<dag> pattern>
-      : I<o, F, outs, ins, asm, pattern>, TB, OpSize, Requires<[HasMMX]>;
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : I<o, F, outs, ins, asm, pattern, itin>, TB, OpSize, Requires<[HasM=
MX]>;
 class MMXIi8<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-             list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern>, TB, Requires<[HasMMX]>;
+             list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin>, TB, Requires<[HasMMX]>;
 class MMXID<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern>, XD, Requires<[HasMMX]>;
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin>, XD, Requires<[HasMMX]>;
 class MMXIS<bits<8> o, Format F, dag outs, dag ins, string asm,=20
-            list<dag> pattern>
-      : Ii8<o, F, outs, ins, asm, pattern>, XS, Requires<[HasMMX]>;
+            list<dag> pattern, InstrItinClass itin =3D IIC_DEFAULT>
+      : Ii8<o, F, outs, ins, asm, pattern, itin>, XS, Requires<[HasMMX]>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strFragmentsSIMD.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrFragmentsSIMD.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrFragmentsSIMD.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D=3D=3D=3D- X86InstrFragmentsSIMD.td - x86 ISA -------------*- t=
ablegen -*-=3D=3D=3D=3D=3D//
+//=3D=3D=3D-- X86InstrFragmentsSIMD.td - x86 SIMD ISA ------------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file provides pattern fragments useful for SIMD instructions.
@@ -41,24 +41,20 @@
 def X86fgetsign: SDNode<"X86ISD::FGETSIGNx86",SDTFPToIntOp>;
 def X86fhadd   : SDNode<"X86ISD::FHADD",     SDTFPBinOp>;
 def X86fhsub   : SDNode<"X86ISD::FHSUB",     SDTFPBinOp>;
+def X86hadd    : SDNode<"X86ISD::HADD",      SDTIntBinOp>;
+def X86hsub    : SDNode<"X86ISD::HSUB",      SDTIntBinOp>;
 def X86comi    : SDNode<"X86ISD::COMI",      SDTX86CmpTest>;
 def X86ucomi   : SDNode<"X86ISD::UCOMI",     SDTX86CmpTest>;
 def X86cmpss   : SDNode<"X86ISD::FSETCCss",    SDTX86Cmpss>;
 def X86cmpsd   : SDNode<"X86ISD::FSETCCsd",    SDTX86Cmpsd>;
 def X86pshufb  : SDNode<"X86ISD::PSHUFB",
-                 SDTypeProfile<1, 2, [SDTCisVT<0, v16i8>, SDTCisSameAs<0,1=
>,
+                 SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisSameAs<0,1>,
                                       SDTCisSameAs<0,2>]>>;
 def X86andnp   : SDNode<"X86ISD::ANDNP",
                  SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisSameAs<0,1>,
                                       SDTCisSameAs<0,2>]>>;
-def X86psignb  : SDNode<"X86ISD::PSIGNB",
-                 SDTypeProfile<1, 2, [SDTCisVT<0, v16i8>, SDTCisSameAs<0,1=
>,
-                                      SDTCisSameAs<0,2>]>>;
-def X86psignw  : SDNode<"X86ISD::PSIGNW",
-                 SDTypeProfile<1, 2, [SDTCisVT<0, v8i16>, SDTCisSameAs<0,1=
>,
-                                      SDTCisSameAs<0,2>]>>;
-def X86psignd  : SDNode<"X86ISD::PSIGND",
-                 SDTypeProfile<1, 2, [SDTCisVT<0, v4i32>, SDTCisSameAs<0,1=
>,
+def X86psign   : SDNode<"X86ISD::PSIGN",
+                 SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisSameAs<0,1>,
                                       SDTCisSameAs<0,2>]>>;
 def X86pextrb  : SDNode<"X86ISD::PEXTRB",
                  SDTypeProfile<1, 2, [SDTCisVT<0, i32>, SDTCisPtrTy<2>]>>;
@@ -75,20 +71,30 @@
                                       SDTCisVT<2, v4f32>, SDTCisPtrTy<3>]>=
>;
 def X86vzmovl  : SDNode<"X86ISD::VZEXT_MOVL",
                  SDTypeProfile<1, 1, [SDTCisSameAs<0,1>]>>;
+def X86vsmovl  : SDNode<"X86ISD::VSEXT_MOVL",
+                 SDTypeProfile<1, 1, [SDTCisVec<0>, SDTCisInt<1>, SDTCisIn=
t<0>]>>;
+                =20
 def X86vzload  : SDNode<"X86ISD::VZEXT_LOAD", SDTLoad,
                         [SDNPHasChain, SDNPMayLoad, SDNPMemOperand]>;
-def X86vshl    : SDNode<"X86ISD::VSHL",      SDTIntShiftOp>;
-def X86vshr    : SDNode<"X86ISD::VSRL",      SDTIntShiftOp>;
-def X86cmpps   : SDNode<"X86ISD::CMPPS",     SDTX86VFCMP>;
-def X86cmppd   : SDNode<"X86ISD::CMPPD",     SDTX86VFCMP>;
-def X86pcmpeqb : SDNode<"X86ISD::PCMPEQB", SDTIntBinOp, [SDNPCommutative]>;
-def X86pcmpeqw : SDNode<"X86ISD::PCMPEQW", SDTIntBinOp, [SDNPCommutative]>;
-def X86pcmpeqd : SDNode<"X86ISD::PCMPEQD", SDTIntBinOp, [SDNPCommutative]>;
-def X86pcmpeqq : SDNode<"X86ISD::PCMPEQQ", SDTIntBinOp, [SDNPCommutative]>;
-def X86pcmpgtb : SDNode<"X86ISD::PCMPGTB", SDTIntBinOp>;
-def X86pcmpgtw : SDNode<"X86ISD::PCMPGTW", SDTIntBinOp>;
-def X86pcmpgtd : SDNode<"X86ISD::PCMPGTD", SDTIntBinOp>;
-def X86pcmpgtq : SDNode<"X86ISD::PCMPGTQ", SDTIntBinOp>;
+def X86vshldq  : SDNode<"X86ISD::VSHLDQ",    SDTIntShiftOp>;
+def X86vshrdq  : SDNode<"X86ISD::VSRLDQ",    SDTIntShiftOp>;
+def X86cmpp    : SDNode<"X86ISD::CMPP",      SDTX86VFCMP>;
+def X86pcmpeq  : SDNode<"X86ISD::PCMPEQ", SDTIntBinOp, [SDNPCommutative]>;
+def X86pcmpgt  : SDNode<"X86ISD::PCMPGT", SDTIntBinOp>;
+
+def X86vshl    : SDNode<"X86ISD::VSHL",
+                        SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisSameAs<0,=
1>,
+                                      SDTCisVec<2>]>>;
+def X86vsrl    : SDNode<"X86ISD::VSRL",
+                        SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisSameAs<0,=
1>,
+                                      SDTCisVec<2>]>>;
+def X86vsra    : SDNode<"X86ISD::VSRA",
+                        SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisSameAs<0,=
1>,
+                                      SDTCisVec<2>]>>;
+
+def X86vshli   : SDNode<"X86ISD::VSHLI", SDTIntShiftOp>;
+def X86vsrli   : SDNode<"X86ISD::VSRLI", SDTIntShiftOp>;
+def X86vsrai   : SDNode<"X86ISD::VSRAI", SDTIntShiftOp>;
=20
 def SDTX86CmpPTest : SDTypeProfile<1, 2, [SDTCisVT<0, i32>,
                                           SDTCisVec<1>,
@@ -96,6 +102,17 @@
 def X86ptest   : SDNode<"X86ISD::PTEST", SDTX86CmpPTest>;
 def X86testp   : SDNode<"X86ISD::TESTP", SDTX86CmpPTest>;
=20
+def X86vpcom   : SDNode<"X86ISD::VPCOM",
+                        SDTypeProfile<1, 3, [SDTCisVec<0>, SDTCisSameAs<0,=
1>,
+                                      SDTCisSameAs<0,2>, SDTCisVT<3, i8>]>=
>;
+def X86vpcomu  : SDNode<"X86ISD::VPCOMU",
+                        SDTypeProfile<1, 3, [SDTCisVec<0>, SDTCisSameAs<0,=
1>,
+                                      SDTCisSameAs<0,2>, SDTCisVT<3, i8>]>=
>;
+
+def X86pmuludq : SDNode<"X86ISD::PMULUDQ",
+                        SDTypeProfile<1, 2, [SDTCisVec<0>, SDTCisVec<1>,
+                                      SDTCisSameAs<1,2>]>>;
+
 // Specific shuffle nodes - At some point ISD::VECTOR_SHUFFLE will always =
get
 // translated into one of the target nodes below during lowering.
 // Note: this is a work in progress...
@@ -109,6 +126,8 @@
                                  SDTCisSameAs<0,2>, SDTCisInt<3>]>;
=20
 def SDTVBroadcast : SDTypeProfile<1, 1, [SDTCisVec<0>]>;
+def SDTBlend : SDTypeProfile<1, 3, [SDTCisVec<0>, SDTCisSameAs<0,1>,
+SDTCisSameAs<1,2>, SDTCisVT<3, i32>]>;
=20
 def X86PAlign : SDNode<"X86ISD::PALIGN", SDTShuff3OpI>;
=20
@@ -116,8 +135,7 @@
 def X86PShufhw : SDNode<"X86ISD::PSHUFHW", SDTShuff2OpI>;
 def X86PShuflw : SDNode<"X86ISD::PSHUFLW", SDTShuff2OpI>;
=20
-def X86Shufpd : SDNode<"X86ISD::SHUFPD", SDTShuff3OpI>;
-def X86Shufps : SDNode<"X86ISD::SHUFPS", SDTShuff3OpI>;
+def X86Shufp : SDNode<"X86ISD::SHUFP", SDTShuff3OpI>;
=20
 def X86Movddup  : SDNode<"X86ISD::MOVDDUP", SDTShuff1Op>;
 def X86Movshdup : SDNode<"X86ISD::MOVSHDUP", SDTShuff1Op>;
@@ -129,40 +147,23 @@
 def X86Movlhps : SDNode<"X86ISD::MOVLHPS", SDTShuff2Op>;
 def X86Movlhpd : SDNode<"X86ISD::MOVLHPD", SDTShuff2Op>;
 def X86Movhlps : SDNode<"X86ISD::MOVHLPS", SDTShuff2Op>;
-def X86Movhlpd : SDNode<"X86ISD::MOVHLPD", SDTShuff2Op>;
=20
 def X86Movlps : SDNode<"X86ISD::MOVLPS", SDTShuff2Op>;
 def X86Movlpd : SDNode<"X86ISD::MOVLPD", SDTShuff2Op>;
=20
-def X86Unpcklps  : SDNode<"X86ISD::UNPCKLPS", SDTShuff2Op>;
-def X86Unpcklpd  : SDNode<"X86ISD::UNPCKLPD", SDTShuff2Op>;
-def X86Unpcklpsy : SDNode<"X86ISD::VUNPCKLPSY", SDTShuff2Op>;
-def X86Unpcklpdy : SDNode<"X86ISD::VUNPCKLPDY", SDTShuff2Op>;
+def X86Unpckl : SDNode<"X86ISD::UNPCKL", SDTShuff2Op>;
+def X86Unpckh : SDNode<"X86ISD::UNPCKH", SDTShuff2Op>;
=20
-def X86Unpckhps  : SDNode<"X86ISD::UNPCKHPS", SDTShuff2Op>;
-def X86Unpckhpd  : SDNode<"X86ISD::UNPCKHPD", SDTShuff2Op>;
-def X86Unpckhpsy : SDNode<"X86ISD::VUNPCKHPSY", SDTShuff2Op>;
-def X86Unpckhpdy : SDNode<"X86ISD::VUNPCKHPDY", SDTShuff2Op>;
+def X86VPermilp  : SDNode<"X86ISD::VPERMILP", SDTShuff2OpI>;
=20
-def X86Punpcklbw  : SDNode<"X86ISD::PUNPCKLBW", SDTShuff2Op>;
-def X86Punpcklwd  : SDNode<"X86ISD::PUNPCKLWD", SDTShuff2Op>;
-def X86Punpckldq  : SDNode<"X86ISD::PUNPCKLDQ", SDTShuff2Op>;
-def X86Punpcklqdq : SDNode<"X86ISD::PUNPCKLQDQ", SDTShuff2Op>;
-
-def X86Punpckhbw  : SDNode<"X86ISD::PUNPCKHBW", SDTShuff2Op>;
-def X86Punpckhwd  : SDNode<"X86ISD::PUNPCKHWD", SDTShuff2Op>;
-def X86Punpckhdq  : SDNode<"X86ISD::PUNPCKHDQ", SDTShuff2Op>;
-def X86Punpckhqdq : SDNode<"X86ISD::PUNPCKHQDQ", SDTShuff2Op>;
-
-def X86VPermilps  : SDNode<"X86ISD::VPERMILPS", SDTShuff2OpI>;
-def X86VPermilpsy : SDNode<"X86ISD::VPERMILPSY", SDTShuff2OpI>;
-def X86VPermilpd  : SDNode<"X86ISD::VPERMILPD", SDTShuff2OpI>;
-def X86VPermilpdy : SDNode<"X86ISD::VPERMILPDY", SDTShuff2OpI>;
-
-def X86VPerm2f128 : SDNode<"X86ISD::VPERM2F128", SDTShuff3OpI>;
+def X86VPerm2x128 : SDNode<"X86ISD::VPERM2X128", SDTShuff3OpI>;
=20
 def X86VBroadcast : SDNode<"X86ISD::VBROADCAST", SDTVBroadcast>;
=20
+def X86Blendpw : SDNode<"X86ISD::BLENDPW", SDTBlend>;
+def X86Blendps : SDNode<"X86ISD::BLENDPS", SDTBlend>;
+def X86Blendpd : SDNode<"X86ISD::BLENDPD", SDTBlend>;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE Complex Patterns
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -195,15 +196,15 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 // 128-bit load pattern fragments
+// NOTE: all 128-bit integer vector loads are promoted to v2i64
 def loadv4f32    : PatFrag<(ops node:$ptr), (v4f32 (load node:$ptr))>;
 def loadv2f64    : PatFrag<(ops node:$ptr), (v2f64 (load node:$ptr))>;
-def loadv4i32    : PatFrag<(ops node:$ptr), (v4i32 (load node:$ptr))>;
 def loadv2i64    : PatFrag<(ops node:$ptr), (v2i64 (load node:$ptr))>;
=20
 // 256-bit load pattern fragments
+// NOTE: all 256-bit integer vector loads are promoted to v4i64
 def loadv8f32    : PatFrag<(ops node:$ptr), (v8f32 (load node:$ptr))>;
 def loadv4f64    : PatFrag<(ops node:$ptr), (v4f64 (load node:$ptr))>;
-def loadv8i32    : PatFrag<(ops node:$ptr), (v8i32 (load node:$ptr))>;
 def loadv4i64    : PatFrag<(ops node:$ptr), (v4i64 (load node:$ptr))>;
=20
 // Like 'store', but always requires 128-bit vector alignment.
@@ -223,6 +224,11 @@
   return cast<LoadSDNode>(N)->getAlignment() >=3D 16;
 }]>;
=20
+// Like 'X86vzload', but always requires 128-bit vector alignment.
+def alignedX86vzload : PatFrag<(ops node:$ptr), (X86vzload node:$ptr), [{
+  return cast<MemSDNode>(N)->getAlignment() >=3D 16;
+}]>;
+
 // Like 'load', but always requires 256-bit vector alignment.
 def alignedload256 : PatFrag<(ops node:$ptr), (load node:$ptr), [{
   return cast<LoadSDNode>(N)->getAlignment() >=3D 32;
@@ -234,22 +240,20 @@
                                (f64 (alignedload node:$ptr))>;
=20
 // 128-bit aligned load pattern fragments
+// NOTE: all 128-bit integer vector loads are promoted to v2i64
 def alignedloadv4f32 : PatFrag<(ops node:$ptr),
                                (v4f32 (alignedload node:$ptr))>;
 def alignedloadv2f64 : PatFrag<(ops node:$ptr),
                                (v2f64 (alignedload node:$ptr))>;
-def alignedloadv4i32 : PatFrag<(ops node:$ptr),
-                               (v4i32 (alignedload node:$ptr))>;
 def alignedloadv2i64 : PatFrag<(ops node:$ptr),
                                (v2i64 (alignedload node:$ptr))>;
=20
 // 256-bit aligned load pattern fragments
+// NOTE: all 256-bit integer vector loads are promoted to v4i64
 def alignedloadv8f32 : PatFrag<(ops node:$ptr),
                                (v8f32 (alignedload256 node:$ptr))>;
 def alignedloadv4f64 : PatFrag<(ops node:$ptr),
                                (v4f64 (alignedload256 node:$ptr))>;
-def alignedloadv8i32 : PatFrag<(ops node:$ptr),
-                               (v8i32 (alignedload256 node:$ptr))>;
 def alignedloadv4i64 : PatFrag<(ops node:$ptr),
                                (v4i64 (alignedload256 node:$ptr))>;
=20
@@ -268,19 +272,16 @@
 def memopfsf64 : PatFrag<(ops node:$ptr), (f64   (memop node:$ptr))>;
=20
 // 128-bit memop pattern fragments
+// NOTE: all 128-bit integer vector loads are promoted to v2i64
 def memopv4f32 : PatFrag<(ops node:$ptr), (v4f32 (memop node:$ptr))>;
 def memopv2f64 : PatFrag<(ops node:$ptr), (v2f64 (memop node:$ptr))>;
-def memopv4i32 : PatFrag<(ops node:$ptr), (v4i32 (memop node:$ptr))>;
 def memopv2i64 : PatFrag<(ops node:$ptr), (v2i64 (memop node:$ptr))>;
-def memopv8i16 : PatFrag<(ops node:$ptr), (v8i16 (memop node:$ptr))>;
-def memopv16i8 : PatFrag<(ops node:$ptr), (v16i8 (memop node:$ptr))>;
=20
 // 256-bit memop pattern fragments
-def memopv32i8 : PatFrag<(ops node:$ptr), (v32i8 (memop node:$ptr))>;
+// NOTE: all 256-bit integer vector loads are promoted to v4i64
 def memopv8f32 : PatFrag<(ops node:$ptr), (v8f32 (memop node:$ptr))>;
 def memopv4f64 : PatFrag<(ops node:$ptr), (v4f64 (memop node:$ptr))>;
 def memopv4i64 : PatFrag<(ops node:$ptr), (v4i64 (memop node:$ptr))>;
-def memopv8i32 : PatFrag<(ops node:$ptr), (v8i32 (memop node:$ptr))>;
=20
 // SSSE3 uses MMX registers for some instructions. They aren't aligned on a
 // 16-byte boundary.
@@ -326,6 +327,8 @@
 def bc_v2i64 : PatFrag<(ops node:$in), (v2i64 (bitconvert node:$in))>;
=20
 // 256-bit bitconvert pattern fragments
+def bc_v32i8 : PatFrag<(ops node:$in), (v32i8 (bitconvert node:$in))>;
+def bc_v16i16 : PatFrag<(ops node:$in), (v16i16 (bitconvert node:$in))>;
 def bc_v8i32 : PatFrag<(ops node:$in), (v8i32 (bitconvert node:$in))>;
 def bc_v4i64 : PatFrag<(ops node:$in), (v4i64 (bitconvert node:$in))>;
=20
@@ -350,30 +353,6 @@
   return getI32Imm(N->getZExtValue() >> 3);
 }]>;
=20
-// SHUFFLE_get_shuf_imm xform function: convert vector_shuffle mask to PSH=
UF*,
-// SHUFP* etc. imm.
-def SHUFFLE_get_shuf_imm : SDNodeXForm<vector_shuffle, [{
-  return getI8Imm(X86::getShuffleSHUFImmediate(N));
-}]>;
-
-// SHUFFLE_get_pshufhw_imm xform function: convert vector_shuffle mask to
-// PSHUFHW imm.
-def SHUFFLE_get_pshufhw_imm : SDNodeXForm<vector_shuffle, [{
-  return getI8Imm(X86::getShufflePSHUFHWImmediate(N));
-}]>;
-
-// SHUFFLE_get_pshuflw_imm xform function: convert vector_shuffle mask to
-// PSHUFLW imm.
-def SHUFFLE_get_pshuflw_imm : SDNodeXForm<vector_shuffle, [{
-  return getI8Imm(X86::getShufflePSHUFLWImmediate(N));
-}]>;
-
-// SHUFFLE_get_palign_imm xform function: convert vector_shuffle mask to
-// a PALIGNR imm.
-def SHUFFLE_get_palign_imm : SDNodeXForm<vector_shuffle, [{
-  return getI8Imm(X86::getShufflePALIGNRImmediate(N));
-}]>;
-
 // EXTRACT_get_vextractf128_imm xform function: convert extract_subvector =
index
 // to VEXTRACTF128 imm.
 def EXTRACT_get_vextractf128_imm : SDNodeXForm<extract_subvector, [{
@@ -386,72 +365,6 @@
   return getI8Imm(X86::getInsertVINSERTF128Immediate(N));
 }]>;
=20
-def splat_lo : PatFrag<(ops node:$lhs, node:$rhs),
-                       (vector_shuffle node:$lhs, node:$rhs), [{
-  ShuffleVectorSDNode *SVOp =3D cast<ShuffleVectorSDNode>(N);
-  return SVOp->isSplat() && SVOp->getSplatIndex() =3D=3D 0;
-}]>;
-
-def movddup : PatFrag<(ops node:$lhs, node:$rhs),
-                      (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isMOVDDUPMask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def movhlps : PatFrag<(ops node:$lhs, node:$rhs),
-                      (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isMOVHLPSMask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def movhlps_undef : PatFrag<(ops node:$lhs, node:$rhs),
-                            (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isMOVHLPS_v_undef_Mask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def movlhps : PatFrag<(ops node:$lhs, node:$rhs),
-                      (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isMOVLHPSMask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def movlp : PatFrag<(ops node:$lhs, node:$rhs),
-                    (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isMOVLPMask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def movl : PatFrag<(ops node:$lhs, node:$rhs),
-                   (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isMOVLMask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def unpckl : PatFrag<(ops node:$lhs, node:$rhs),
-                     (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isUNPCKLMask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def unpckh : PatFrag<(ops node:$lhs, node:$rhs),
-                     (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isUNPCKHMask(cast<ShuffleVectorSDNode>(N));
-}]>;
-
-def pshufd : PatFrag<(ops node:$lhs, node:$rhs),
-                     (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isPSHUFDMask(cast<ShuffleVectorSDNode>(N));
-}], SHUFFLE_get_shuf_imm>;
-
-def shufp : PatFrag<(ops node:$lhs, node:$rhs),
-                    (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isSHUFPMask(cast<ShuffleVectorSDNode>(N));
-}], SHUFFLE_get_shuf_imm>;
-
-def pshufhw : PatFrag<(ops node:$lhs, node:$rhs),
-                      (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isPSHUFHWMask(cast<ShuffleVectorSDNode>(N));
-}], SHUFFLE_get_pshufhw_imm>;
-
-def pshuflw : PatFrag<(ops node:$lhs, node:$rhs),
-                      (vector_shuffle node:$lhs, node:$rhs), [{
-  return X86::isPSHUFLWMask(cast<ShuffleVectorSDNode>(N));
-}], SHUFFLE_get_pshuflw_imm>;
-
 def vextractf128_extract : PatFrag<(ops node:$bigvec, node:$index),
                                    (extract_subvector node:$bigvec,
                                                       node:$index), [{
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strInfo.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86InstrInfo.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrInfo.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86InstrInfo.cpp - X86 Instruction Information -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86InstrInfo.cpp - X86 Instruction Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -25,14 +25,13 @@
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/LiveVariables.h"
-#include "llvm/CodeGen/PseudoSourceValue.h"
+#include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetOptions.h"
-#include "llvm/MC/MCAsmInfo.h"
 #include <limits>
=20
 #define GET_INSTRINFO_CTOR
@@ -83,6 +82,12 @@
   TB_FOLDED_STORE =3D 1 << 19
 };
=20
+struct X86OpTblEntry {
+  uint16_t RegOp;
+  uint16_t MemOp;
+  uint32_t Flags;
+};
+
 X86InstrInfo::X86InstrInfo(X86TargetMachine &tm)
   : X86GenInstrInfo((tm.getSubtarget<X86Subtarget>().is64Bit()
                      ? X86::ADJCALLSTACKDOWN64
@@ -92,7 +97,7 @@
                      : X86::ADJCALLSTACKUP32)),
     TM(tm), RI(tm, *this) {
=20
-  static const unsigned OpTbl2Addr[][3] =3D {
+  static const X86OpTblEntry OpTbl2Addr[] =3D {
     { X86::ADC32ri,     X86::ADC32mi,    0 },
     { X86::ADC32ri8,    X86::ADC32mi8,   0 },
     { X86::ADC32rr,     X86::ADC32mr,    0 },
@@ -260,22 +265,21 @@
   };
=20
   for (unsigned i =3D 0, e =3D array_lengthof(OpTbl2Addr); i !=3D e; ++i) {
-    unsigned RegOp =3D OpTbl2Addr[i][0];
-    unsigned MemOp =3D OpTbl2Addr[i][1];
-    unsigned Flags =3D OpTbl2Addr[i][2];
+    unsigned RegOp =3D OpTbl2Addr[i].RegOp;
+    unsigned MemOp =3D OpTbl2Addr[i].MemOp;
+    unsigned Flags =3D OpTbl2Addr[i].Flags;
     AddTableEntry(RegOp2MemOpTable2Addr, MemOp2RegOpTable,
                   RegOp, MemOp,
                   // Index 0, folded load and store, no alignment requirem=
ent.
                   Flags | TB_INDEX_0 | TB_FOLDED_LOAD | TB_FOLDED_STORE);
   }
=20
-  static const unsigned OpTbl0[][3] =3D {
+  static const X86OpTblEntry OpTbl0[] =3D {
     { X86::BT16ri8,     X86::BT16mi8,       TB_FOLDED_LOAD },
     { X86::BT32ri8,     X86::BT32mi8,       TB_FOLDED_LOAD },
     { X86::BT64ri8,     X86::BT64mi8,       TB_FOLDED_LOAD },
     { X86::CALL32r,     X86::CALL32m,       TB_FOLDED_LOAD },
     { X86::CALL64r,     X86::CALL64m,       TB_FOLDED_LOAD },
-    { X86::WINCALL64r,  X86::WINCALL64m,    TB_FOLDED_LOAD },
     { X86::CMP16ri,     X86::CMP16mi,       TB_FOLDED_LOAD },
     { X86::CMP16ri8,    X86::CMP16mi8,      TB_FOLDED_LOAD },
     { X86::CMP16rr,     X86::CMP16mr,       TB_FOLDED_LOAD },
@@ -352,6 +356,7 @@
     { X86::VEXTRACTPSrr,X86::VEXTRACTPSmr,  TB_FOLDED_STORE | TB_ALIGN_16 =
},
     { X86::FsVMOVAPDrr, X86::VMOVSDmr,      TB_FOLDED_STORE | TB_NO_REVERS=
E },
     { X86::FsVMOVAPSrr, X86::VMOVSSmr,      TB_FOLDED_STORE | TB_NO_REVERS=
E },
+    { X86::VEXTRACTF128rr, X86::VEXTRACTF128mr, TB_FOLDED_STORE | TB_ALIGN=
_16 },
     { X86::VMOVAPDrr,   X86::VMOVAPDmr,     TB_FOLDED_STORE | TB_ALIGN_16 =
},
     { X86::VMOVAPSrr,   X86::VMOVAPSmr,     TB_FOLDED_STORE | TB_ALIGN_16 =
},
     { X86::VMOVDQArr,   X86::VMOVDQAmr,     TB_FOLDED_STORE | TB_ALIGN_16 =
},
@@ -362,6 +367,7 @@
     { X86::VMOVUPDrr,   X86::VMOVUPDmr,     TB_FOLDED_STORE },
     { X86::VMOVUPSrr,   X86::VMOVUPSmr,     TB_FOLDED_STORE },
     // AVX 256-bit foldable instructions
+    { X86::VEXTRACTI128rr, X86::VEXTRACTI128mr, TB_FOLDED_STORE | TB_ALIGN=
_16 },
     { X86::VMOVAPDYrr,  X86::VMOVAPDYmr,    TB_FOLDED_STORE | TB_ALIGN_32 =
},
     { X86::VMOVAPSYrr,  X86::VMOVAPSYmr,    TB_FOLDED_STORE | TB_ALIGN_32 =
},
     { X86::VMOVDQAYrr,  X86::VMOVDQAYmr,    TB_FOLDED_STORE | TB_ALIGN_32 =
},
@@ -370,14 +376,14 @@
   };
=20
   for (unsigned i =3D 0, e =3D array_lengthof(OpTbl0); i !=3D e; ++i) {
-    unsigned RegOp      =3D OpTbl0[i][0];
-    unsigned MemOp      =3D OpTbl0[i][1];
-    unsigned Flags      =3D OpTbl0[i][2];
+    unsigned RegOp      =3D OpTbl0[i].RegOp;
+    unsigned MemOp      =3D OpTbl0[i].MemOp;
+    unsigned Flags      =3D OpTbl0[i].Flags;
     AddTableEntry(RegOp2MemOpTable0, MemOp2RegOpTable,
                   RegOp, MemOp, TB_INDEX_0 | Flags);
   }
=20
-  static const unsigned OpTbl1[][3] =3D {
+  static const X86OpTblEntry OpTbl1[] =3D {
     { X86::CMP16rr,         X86::CMP16rm,             0 },
     { X86::CMP32rr,         X86::CMP32rm,             0 },
     { X86::CMP64rr,         X86::CMP64rm,             0 },
@@ -456,6 +462,9 @@
     { X86::MOVZX64rr16,     X86::MOVZX64rm16,         0 },
     { X86::MOVZX64rr32,     X86::MOVZX64rm32,         0 },
     { X86::MOVZX64rr8,      X86::MOVZX64rm8,          0 },
+    { X86::PABSBrr128,      X86::PABSBrm128,          TB_ALIGN_16 },
+    { X86::PABSDrr128,      X86::PABSDrm128,          TB_ALIGN_16 },
+    { X86::PABSWrr128,      X86::PABSWrm128,          TB_ALIGN_16 },
     { X86::PSHUFDri,        X86::PSHUFDmi,            TB_ALIGN_16 },
     { X86::PSHUFHWri,       X86::PSHUFHWmi,           TB_ALIGN_16 },
     { X86::PSHUFLWri,       X86::PSHUFLWmi,           TB_ALIGN_16 },
@@ -508,6 +517,11 @@
     { X86::VMOVZDI2PDIrr,   X86::VMOVZDI2PDIrm,       0 },
     { X86::VMOVZQI2PQIrr,   X86::VMOVZQI2PQIrm,       0 },
     { X86::VMOVZPQILo2PQIrr,X86::VMOVZPQILo2PQIrm,    TB_ALIGN_16 },
+    { X86::VPABSBrr128,     X86::VPABSBrm128,         TB_ALIGN_16 },
+    { X86::VPABSDrr128,     X86::VPABSDrm128,         TB_ALIGN_16 },
+    { X86::VPABSWrr128,     X86::VPABSWrm128,         TB_ALIGN_16 },
+    { X86::VPERMILPDri,     X86::VPERMILPDmi,         TB_ALIGN_16 },
+    { X86::VPERMILPSri,     X86::VPERMILPSmi,         TB_ALIGN_16 },
     { X86::VPSHUFDri,       X86::VPSHUFDmi,           TB_ALIGN_16 },
     { X86::VPSHUFHWri,      X86::VPSHUFHWmi,          TB_ALIGN_16 },
     { X86::VPSHUFLWri,      X86::VPSHUFLWmi,          TB_ALIGN_16 },
@@ -524,22 +538,39 @@
     // AVX 256-bit foldable instructions
     { X86::VMOVAPDYrr,      X86::VMOVAPDYrm,          TB_ALIGN_32 },
     { X86::VMOVAPSYrr,      X86::VMOVAPSYrm,          TB_ALIGN_32 },
-    { X86::VMOVDQAYrr,      X86::VMOVDQAYrm,          TB_ALIGN_16 },
+    { X86::VMOVDQAYrr,      X86::VMOVDQAYrm,          TB_ALIGN_32 },
     { X86::VMOVUPDYrr,      X86::VMOVUPDYrm,          0 },
-    { X86::VMOVUPSYrr,      X86::VMOVUPSYrm,          0 }
+    { X86::VMOVUPSYrr,      X86::VMOVUPSYrm,          0 },
+    { X86::VPERMILPDYri,    X86::VPERMILPDYmi,        TB_ALIGN_32 },
+    { X86::VPERMILPSYri,    X86::VPERMILPSYmi,        TB_ALIGN_32 },
+    // AVX2 foldable instructions
+    { X86::VPABSBrr256,     X86::VPABSBrm256,         TB_ALIGN_32 },
+    { X86::VPABSDrr256,     X86::VPABSDrm256,         TB_ALIGN_32 },
+    { X86::VPABSWrr256,     X86::VPABSWrm256,         TB_ALIGN_32 },
+    { X86::VPSHUFDYri,      X86::VPSHUFDYmi,          TB_ALIGN_32 },
+    { X86::VPSHUFHWYri,     X86::VPSHUFHWYmi,         TB_ALIGN_32 },
+    { X86::VPSHUFLWYri,     X86::VPSHUFLWYmi,         TB_ALIGN_32 },
+    { X86::VRCPPSYr,        X86::VRCPPSYm,            TB_ALIGN_32 },
+    { X86::VRCPPSYr_Int,    X86::VRCPPSYm_Int,        TB_ALIGN_32 },
+    { X86::VRSQRTPSYr,      X86::VRSQRTPSYm,          TB_ALIGN_32 },
+    { X86::VRSQRTPSYr_Int,  X86::VRSQRTPSYm_Int,      TB_ALIGN_32 },
+    { X86::VSQRTPDYr,       X86::VSQRTPDYm,           TB_ALIGN_32 },
+    { X86::VSQRTPDYr_Int,   X86::VSQRTPDYm_Int,       TB_ALIGN_32 },
+    { X86::VSQRTPSYr,       X86::VSQRTPSYm,           TB_ALIGN_32 },
+    { X86::VSQRTPSYr_Int,   X86::VSQRTPSYm_Int,       TB_ALIGN_32 },
   };
=20
   for (unsigned i =3D 0, e =3D array_lengthof(OpTbl1); i !=3D e; ++i) {
-    unsigned RegOp =3D OpTbl1[i][0];
-    unsigned MemOp =3D OpTbl1[i][1];
-    unsigned Flags =3D OpTbl1[i][2];
+    unsigned RegOp =3D OpTbl1[i].RegOp;
+    unsigned MemOp =3D OpTbl1[i].MemOp;
+    unsigned Flags =3D OpTbl1[i].Flags;
     AddTableEntry(RegOp2MemOpTable1, MemOp2RegOpTable,
                   RegOp, MemOp,
                   // Index 1, folded load
                   Flags | TB_INDEX_1 | TB_FOLDED_LOAD);
   }
=20
-  static const unsigned OpTbl2[][3] =3D {
+  static const X86OpTblEntry OpTbl2[] =3D {
     { X86::ADC32rr,         X86::ADC32rm,       0 },
     { X86::ADC64rr,         X86::ADC64rm,       0 },
     { X86::ADD16rr,         X86::ADD16rm,       0 },
@@ -563,6 +594,10 @@
     { X86::ANDNPSrr,        X86::ANDNPSrm,      TB_ALIGN_16 },
     { X86::ANDPDrr,         X86::ANDPDrm,       TB_ALIGN_16 },
     { X86::ANDPSrr,         X86::ANDPSrm,       TB_ALIGN_16 },
+    { X86::BLENDPDrri,      X86::BLENDPDrmi,    TB_ALIGN_16 },
+    { X86::BLENDPSrri,      X86::BLENDPSrmi,    TB_ALIGN_16 },
+    { X86::BLENDVPDrr0,     X86::BLENDVPDrm0,   TB_ALIGN_16 },
+    { X86::BLENDVPSrr0,     X86::BLENDVPSrm0,   TB_ALIGN_16 },
     { X86::CMOVA16rr,       X86::CMOVA16rm,     0 },
     { X86::CMOVA32rr,       X86::CMOVA32rm,     0 },
     { X86::CMOVA64rr,       X86::CMOVA64rm,     0 },
@@ -652,6 +687,7 @@
     { X86::MINSDrr_Int,     X86::MINSDrm_Int,   0 },
     { X86::MINSSrr,         X86::MINSSrm,       0 },
     { X86::MINSSrr_Int,     X86::MINSSrm_Int,   0 },
+    { X86::MPSADBWrri,      X86::MPSADBWrmi,    TB_ALIGN_16 },
     { X86::MULPDrr,         X86::MULPDrm,       TB_ALIGN_16 },
     { X86::MULPSrr,         X86::MULPSrm,       TB_ALIGN_16 },
     { X86::MULSDrr,         X86::MULSDrm,       0 },
@@ -664,30 +700,45 @@
     { X86::ORPSrr,          X86::ORPSrm,        TB_ALIGN_16 },
     { X86::PACKSSDWrr,      X86::PACKSSDWrm,    TB_ALIGN_16 },
     { X86::PACKSSWBrr,      X86::PACKSSWBrm,    TB_ALIGN_16 },
+    { X86::PACKUSDWrr,      X86::PACKUSDWrm,    TB_ALIGN_16 },
     { X86::PACKUSWBrr,      X86::PACKUSWBrm,    TB_ALIGN_16 },
     { X86::PADDBrr,         X86::PADDBrm,       TB_ALIGN_16 },
     { X86::PADDDrr,         X86::PADDDrm,       TB_ALIGN_16 },
     { X86::PADDQrr,         X86::PADDQrm,       TB_ALIGN_16 },
     { X86::PADDSBrr,        X86::PADDSBrm,      TB_ALIGN_16 },
     { X86::PADDSWrr,        X86::PADDSWrm,      TB_ALIGN_16 },
+    { X86::PADDUSBrr,       X86::PADDUSBrm,     TB_ALIGN_16 },
+    { X86::PADDUSWrr,       X86::PADDUSWrm,     TB_ALIGN_16 },
     { X86::PADDWrr,         X86::PADDWrm,       TB_ALIGN_16 },
+    { X86::PALIGNR128rr,    X86::PALIGNR128rm,  TB_ALIGN_16 },
     { X86::PANDNrr,         X86::PANDNrm,       TB_ALIGN_16 },
     { X86::PANDrr,          X86::PANDrm,        TB_ALIGN_16 },
     { X86::PAVGBrr,         X86::PAVGBrm,       TB_ALIGN_16 },
     { X86::PAVGWrr,         X86::PAVGWrm,       TB_ALIGN_16 },
+    { X86::PBLENDWrri,      X86::PBLENDWrmi,    TB_ALIGN_16 },
     { X86::PCMPEQBrr,       X86::PCMPEQBrm,     TB_ALIGN_16 },
     { X86::PCMPEQDrr,       X86::PCMPEQDrm,     TB_ALIGN_16 },
+    { X86::PCMPEQQrr,       X86::PCMPEQQrm,     TB_ALIGN_16 },
     { X86::PCMPEQWrr,       X86::PCMPEQWrm,     TB_ALIGN_16 },
     { X86::PCMPGTBrr,       X86::PCMPGTBrm,     TB_ALIGN_16 },
     { X86::PCMPGTDrr,       X86::PCMPGTDrm,     TB_ALIGN_16 },
+    { X86::PCMPGTQrr,       X86::PCMPGTQrm,     TB_ALIGN_16 },
     { X86::PCMPGTWrr,       X86::PCMPGTWrm,     TB_ALIGN_16 },
+    { X86::PHADDDrr,        X86::PHADDDrm,      TB_ALIGN_16 },
+    { X86::PHADDWrr,        X86::PHADDWrm,      TB_ALIGN_16 },
+    { X86::PHADDSWrr128,    X86::PHADDSWrm128,  TB_ALIGN_16 },
+    { X86::PHSUBDrr,        X86::PHSUBDrm,      TB_ALIGN_16 },
+    { X86::PHSUBSWrr128,    X86::PHSUBSWrm128,  TB_ALIGN_16 },
+    { X86::PHSUBWrr,        X86::PHSUBWrm,      TB_ALIGN_16 },
     { X86::PINSRWrri,       X86::PINSRWrmi,     TB_ALIGN_16 },
+    { X86::PMADDUBSWrr128,  X86::PMADDUBSWrm128, TB_ALIGN_16 },
     { X86::PMADDWDrr,       X86::PMADDWDrm,     TB_ALIGN_16 },
     { X86::PMAXSWrr,        X86::PMAXSWrm,      TB_ALIGN_16 },
     { X86::PMAXUBrr,        X86::PMAXUBrm,      TB_ALIGN_16 },
     { X86::PMINSWrr,        X86::PMINSWrm,      TB_ALIGN_16 },
     { X86::PMINUBrr,        X86::PMINUBrm,      TB_ALIGN_16 },
     { X86::PMULDQrr,        X86::PMULDQrm,      TB_ALIGN_16 },
+    { X86::PMULHRSWrr128,   X86::PMULHRSWrm128, TB_ALIGN_16 },
     { X86::PMULHUWrr,       X86::PMULHUWrm,     TB_ALIGN_16 },
     { X86::PMULHWrr,        X86::PMULHWrm,      TB_ALIGN_16 },
     { X86::PMULLDrr,        X86::PMULLDrm,      TB_ALIGN_16 },
@@ -695,6 +746,10 @@
     { X86::PMULUDQrr,       X86::PMULUDQrm,     TB_ALIGN_16 },
     { X86::PORrr,           X86::PORrm,         TB_ALIGN_16 },
     { X86::PSADBWrr,        X86::PSADBWrm,      TB_ALIGN_16 },
+    { X86::PSHUFBrr,        X86::PSHUFBrm,      TB_ALIGN_16 },
+    { X86::PSIGNBrr,        X86::PSIGNBrm,      TB_ALIGN_16 },
+    { X86::PSIGNWrr,        X86::PSIGNWrm,      TB_ALIGN_16 },
+    { X86::PSIGNDrr,        X86::PSIGNDrm,      TB_ALIGN_16 },
     { X86::PSLLDrr,         X86::PSLLDrm,       TB_ALIGN_16 },
     { X86::PSLLQrr,         X86::PSLLQrm,       TB_ALIGN_16 },
     { X86::PSLLWrr,         X86::PSLLWrm,       TB_ALIGN_16 },
@@ -778,6 +833,10 @@
     { X86::VANDNPSrr,         X86::VANDNPSrm,          TB_ALIGN_16 },
     { X86::VANDPDrr,          X86::VANDPDrm,           TB_ALIGN_16 },
     { X86::VANDPSrr,          X86::VANDPSrm,           TB_ALIGN_16 },
+    { X86::VBLENDPDrri,       X86::VBLENDPDrmi,        TB_ALIGN_16 },
+    { X86::VBLENDPSrri,       X86::VBLENDPSrmi,        TB_ALIGN_16 },
+    { X86::VBLENDVPDrr,       X86::VBLENDVPDrm,        TB_ALIGN_16 },
+    { X86::VBLENDVPSrr,       X86::VBLENDVPSrm,        TB_ALIGN_16 },
     { X86::VCMPPDrri,         X86::VCMPPDrmi,          TB_ALIGN_16 },
     { X86::VCMPPSrri,         X86::VCMPPSrmi,          TB_ALIGN_16 },
     { X86::VCMPSDrr,          X86::VCMPSDrm,           0 },
@@ -816,6 +875,7 @@
     { X86::VMINSDrr_Int,      X86::VMINSDrm_Int,       0 },
     { X86::VMINSSrr,          X86::VMINSSrm,           0 },
     { X86::VMINSSrr_Int,      X86::VMINSSrm_Int,       0 },
+    { X86::VMPSADBWrri,       X86::VMPSADBWrmi,        TB_ALIGN_16 },
     { X86::VMULPDrr,          X86::VMULPDrm,           TB_ALIGN_16 },
     { X86::VMULPSrr,          X86::VMULPSrm,           TB_ALIGN_16 },
     { X86::VMULSDrr,          X86::VMULSDrm,           0 },
@@ -824,28 +884,47 @@
     { X86::VORPSrr,           X86::VORPSrm,            TB_ALIGN_16 },
     { X86::VPACKSSDWrr,       X86::VPACKSSDWrm,        TB_ALIGN_16 },
     { X86::VPACKSSWBrr,       X86::VPACKSSWBrm,        TB_ALIGN_16 },
+    { X86::VPACKUSDWrr,       X86::VPACKUSDWrm,        TB_ALIGN_16 },
     { X86::VPACKUSWBrr,       X86::VPACKUSWBrm,        TB_ALIGN_16 },
     { X86::VPADDBrr,          X86::VPADDBrm,           TB_ALIGN_16 },
     { X86::VPADDDrr,          X86::VPADDDrm,           TB_ALIGN_16 },
     { X86::VPADDQrr,          X86::VPADDQrm,           TB_ALIGN_16 },
     { X86::VPADDSBrr,         X86::VPADDSBrm,          TB_ALIGN_16 },
     { X86::VPADDSWrr,         X86::VPADDSWrm,          TB_ALIGN_16 },
+    { X86::VPADDUSBrr,        X86::VPADDUSBrm,         TB_ALIGN_16 },
+    { X86::VPADDUSWrr,        X86::VPADDUSWrm,         TB_ALIGN_16 },
     { X86::VPADDWrr,          X86::VPADDWrm,           TB_ALIGN_16 },
+    { X86::VPALIGNR128rr,     X86::VPALIGNR128rm,      TB_ALIGN_16 },
     { X86::VPANDNrr,          X86::VPANDNrm,           TB_ALIGN_16 },
     { X86::VPANDrr,           X86::VPANDrm,            TB_ALIGN_16 },
+    { X86::VPAVGBrr,          X86::VPAVGBrm,           TB_ALIGN_16 },
+    { X86::VPAVGWrr,          X86::VPAVGWrm,           TB_ALIGN_16 },
+    { X86::VPBLENDWrri,       X86::VPBLENDWrmi,        TB_ALIGN_16 },
     { X86::VPCMPEQBrr,        X86::VPCMPEQBrm,         TB_ALIGN_16 },
     { X86::VPCMPEQDrr,        X86::VPCMPEQDrm,         TB_ALIGN_16 },
+    { X86::VPCMPEQQrr,        X86::VPCMPEQQrm,         TB_ALIGN_16 },
     { X86::VPCMPEQWrr,        X86::VPCMPEQWrm,         TB_ALIGN_16 },
     { X86::VPCMPGTBrr,        X86::VPCMPGTBrm,         TB_ALIGN_16 },
     { X86::VPCMPGTDrr,        X86::VPCMPGTDrm,         TB_ALIGN_16 },
+    { X86::VPCMPGTQrr,        X86::VPCMPGTQrm,         TB_ALIGN_16 },
     { X86::VPCMPGTWrr,        X86::VPCMPGTWrm,         TB_ALIGN_16 },
+    { X86::VPHADDDrr,         X86::VPHADDDrm,          TB_ALIGN_16 },
+    { X86::VPHADDSWrr128,     X86::VPHADDSWrm128,      TB_ALIGN_16 },
+    { X86::VPHADDWrr,         X86::VPHADDWrm,          TB_ALIGN_16 },
+    { X86::VPHSUBDrr,         X86::VPHSUBDrm,          TB_ALIGN_16 },
+    { X86::VPHSUBSWrr128,     X86::VPHSUBSWrm128,      TB_ALIGN_16 },
+    { X86::VPHSUBWrr,         X86::VPHSUBWrm,          TB_ALIGN_16 },
+    { X86::VPERMILPDrr,       X86::VPERMILPDrm,        TB_ALIGN_16 },
+    { X86::VPERMILPSrr,       X86::VPERMILPSrm,        TB_ALIGN_16 },
     { X86::VPINSRWrri,        X86::VPINSRWrmi,         TB_ALIGN_16 },
+    { X86::VPMADDUBSWrr128,   X86::VPMADDUBSWrm128,    TB_ALIGN_16 },
     { X86::VPMADDWDrr,        X86::VPMADDWDrm,         TB_ALIGN_16 },
     { X86::VPMAXSWrr,         X86::VPMAXSWrm,          TB_ALIGN_16 },
     { X86::VPMAXUBrr,         X86::VPMAXUBrm,          TB_ALIGN_16 },
     { X86::VPMINSWrr,         X86::VPMINSWrm,          TB_ALIGN_16 },
     { X86::VPMINUBrr,         X86::VPMINUBrm,          TB_ALIGN_16 },
     { X86::VPMULDQrr,         X86::VPMULDQrm,          TB_ALIGN_16 },
+    { X86::VPMULHRSWrr128,    X86::VPMULHRSWrm128,     TB_ALIGN_16 },
     { X86::VPMULHUWrr,        X86::VPMULHUWrm,         TB_ALIGN_16 },
     { X86::VPMULHWrr,         X86::VPMULHWrm,          TB_ALIGN_16 },
     { X86::VPMULLDrr,         X86::VPMULLDrm,          TB_ALIGN_16 },
@@ -853,6 +932,10 @@
     { X86::VPMULUDQrr,        X86::VPMULUDQrm,         TB_ALIGN_16 },
     { X86::VPORrr,            X86::VPORrm,             TB_ALIGN_16 },
     { X86::VPSADBWrr,         X86::VPSADBWrm,          TB_ALIGN_16 },
+    { X86::VPSHUFBrr,         X86::VPSHUFBrm,          TB_ALIGN_16 },
+    { X86::VPSIGNBrr,         X86::VPSIGNBrm,          TB_ALIGN_16 },
+    { X86::VPSIGNWrr,         X86::VPSIGNWrm,          TB_ALIGN_16 },
+    { X86::VPSIGNDrr,         X86::VPSIGNDrm,          TB_ALIGN_16 },
     { X86::VPSLLDrr,          X86::VPSLLDrm,           TB_ALIGN_16 },
     { X86::VPSLLQrr,          X86::VPSLLQrm,           TB_ALIGN_16 },
     { X86::VPSLLWrr,          X86::VPSLLWrm,           TB_ALIGN_16 },
@@ -886,14 +969,154 @@
     { X86::VUNPCKLPDrr,       X86::VUNPCKLPDrm,        TB_ALIGN_16 },
     { X86::VUNPCKLPSrr,       X86::VUNPCKLPSrm,        TB_ALIGN_16 },
     { X86::VXORPDrr,          X86::VXORPDrm,           TB_ALIGN_16 },
-    { X86::VXORPSrr,          X86::VXORPSrm,           TB_ALIGN_16 }
+    { X86::VXORPSrr,          X86::VXORPSrm,           TB_ALIGN_16 },
+    // AVX 256-bit foldable instructions
+    { X86::VADDPDYrr,         X86::VADDPDYrm,          TB_ALIGN_32 },
+    { X86::VADDPSYrr,         X86::VADDPSYrm,          TB_ALIGN_32 },
+    { X86::VADDSUBPDYrr,      X86::VADDSUBPDYrm,       TB_ALIGN_32 },
+    { X86::VADDSUBPSYrr,      X86::VADDSUBPSYrm,       TB_ALIGN_32 },
+    { X86::VANDNPDYrr,        X86::VANDNPDYrm,         TB_ALIGN_32 },
+    { X86::VANDNPSYrr,        X86::VANDNPSYrm,         TB_ALIGN_32 },
+    { X86::VANDPDYrr,         X86::VANDPDYrm,          TB_ALIGN_32 },
+    { X86::VANDPSYrr,         X86::VANDPSYrm,          TB_ALIGN_32 },
+    { X86::VBLENDPDYrri,      X86::VBLENDPDYrmi,       TB_ALIGN_32 },
+    { X86::VBLENDPSYrri,      X86::VBLENDPSYrmi,       TB_ALIGN_32 },
+    { X86::VBLENDVPDYrr,      X86::VBLENDVPDYrm,       TB_ALIGN_32 },
+    { X86::VBLENDVPSYrr,      X86::VBLENDVPSYrm,       TB_ALIGN_32 },
+    { X86::VCMPPDYrri,        X86::VCMPPDYrmi,         TB_ALIGN_32 },
+    { X86::VCMPPSYrri,        X86::VCMPPSYrmi,         TB_ALIGN_32 },
+    { X86::VDIVPDYrr,         X86::VDIVPDYrm,          TB_ALIGN_32 },
+    { X86::VDIVPSYrr,         X86::VDIVPSYrm,          TB_ALIGN_32 },
+    { X86::VHADDPDYrr,        X86::VHADDPDYrm,         TB_ALIGN_32 },
+    { X86::VHADDPSYrr,        X86::VHADDPSYrm,         TB_ALIGN_32 },
+    { X86::VHSUBPDYrr,        X86::VHSUBPDYrm,         TB_ALIGN_32 },
+    { X86::VHSUBPSYrr,        X86::VHSUBPSYrm,         TB_ALIGN_32 },
+    { X86::VINSERTF128rr,     X86::VINSERTF128rm,      TB_ALIGN_32 },
+    { X86::VMAXPDYrr,         X86::VMAXPDYrm,          TB_ALIGN_32 },
+    { X86::VMAXPDYrr_Int,     X86::VMAXPDYrm_Int,      TB_ALIGN_32 },
+    { X86::VMAXPSYrr,         X86::VMAXPSYrm,          TB_ALIGN_32 },
+    { X86::VMAXPSYrr_Int,     X86::VMAXPSYrm_Int,      TB_ALIGN_32 },
+    { X86::VMINPDYrr,         X86::VMINPDYrm,          TB_ALIGN_32 },
+    { X86::VMINPDYrr_Int,     X86::VMINPDYrm_Int,      TB_ALIGN_32 },
+    { X86::VMINPSYrr,         X86::VMINPSYrm,          TB_ALIGN_32 },
+    { X86::VMINPSYrr_Int,     X86::VMINPSYrm_Int,      TB_ALIGN_32 },
+    { X86::VMULPDYrr,         X86::VMULPDYrm,          TB_ALIGN_32 },
+    { X86::VMULPSYrr,         X86::VMULPSYrm,          TB_ALIGN_32 },
+    { X86::VORPDYrr,          X86::VORPDYrm,           TB_ALIGN_32 },
+    { X86::VORPSYrr,          X86::VORPSYrm,           TB_ALIGN_32 },
+    { X86::VPERM2F128rr,      X86::VPERM2F128rm,       TB_ALIGN_32 },
+    { X86::VPERMILPDYrr,      X86::VPERMILPDYrm,       TB_ALIGN_32 },
+    { X86::VPERMILPSYrr,      X86::VPERMILPSYrm,       TB_ALIGN_32 },
+    { X86::VSHUFPDYrri,       X86::VSHUFPDYrmi,        TB_ALIGN_32 },
+    { X86::VSHUFPSYrri,       X86::VSHUFPSYrmi,        TB_ALIGN_32 },
+    { X86::VSUBPDYrr,         X86::VSUBPDYrm,          TB_ALIGN_32 },
+    { X86::VSUBPSYrr,         X86::VSUBPSYrm,          TB_ALIGN_32 },
+    { X86::VUNPCKHPDYrr,      X86::VUNPCKHPDYrm,       TB_ALIGN_32 },
+    { X86::VUNPCKHPSYrr,      X86::VUNPCKHPSYrm,       TB_ALIGN_32 },
+    { X86::VUNPCKLPDYrr,      X86::VUNPCKLPDYrm,       TB_ALIGN_32 },
+    { X86::VUNPCKLPSYrr,      X86::VUNPCKLPSYrm,       TB_ALIGN_32 },
+    { X86::VXORPDYrr,         X86::VXORPDYrm,          TB_ALIGN_32 },
+    { X86::VXORPSYrr,         X86::VXORPSYrm,          TB_ALIGN_32 },
+    // AVX2 foldable instructions
+    { X86::VINSERTI128rr,     X86::VINSERTI128rm,      TB_ALIGN_16 },
+    { X86::VPACKSSDWYrr,      X86::VPACKSSDWYrm,       TB_ALIGN_32 },
+    { X86::VPACKSSWBYrr,      X86::VPACKSSWBYrm,       TB_ALIGN_32 },
+    { X86::VPACKUSDWYrr,      X86::VPACKUSDWYrm,       TB_ALIGN_32 },
+    { X86::VPACKUSWBYrr,      X86::VPACKUSWBYrm,       TB_ALIGN_32 },
+    { X86::VPADDBYrr,         X86::VPADDBYrm,          TB_ALIGN_32 },
+    { X86::VPADDDYrr,         X86::VPADDDYrm,          TB_ALIGN_32 },
+    { X86::VPADDQYrr,         X86::VPADDQYrm,          TB_ALIGN_32 },
+    { X86::VPADDSBYrr,        X86::VPADDSBYrm,         TB_ALIGN_32 },
+    { X86::VPADDSWYrr,        X86::VPADDSWYrm,         TB_ALIGN_32 },
+    { X86::VPADDUSBYrr,       X86::VPADDUSBYrm,        TB_ALIGN_32 },
+    { X86::VPADDUSWYrr,       X86::VPADDUSWYrm,        TB_ALIGN_32 },
+    { X86::VPADDWYrr,         X86::VPADDWYrm,          TB_ALIGN_32 },
+    { X86::VPALIGNR256rr,     X86::VPALIGNR256rm,      TB_ALIGN_32 },
+    { X86::VPANDNYrr,         X86::VPANDNYrm,          TB_ALIGN_32 },
+    { X86::VPANDYrr,          X86::VPANDYrm,           TB_ALIGN_32 },
+    { X86::VPAVGBYrr,         X86::VPAVGBYrm,          TB_ALIGN_32 },
+    { X86::VPAVGWYrr,         X86::VPAVGWYrm,          TB_ALIGN_32 },
+    { X86::VPBLENDDrri,       X86::VPBLENDDrmi,        TB_ALIGN_32 },
+    { X86::VPBLENDDYrri,      X86::VPBLENDDYrmi,       TB_ALIGN_32 },
+    { X86::VPBLENDWYrri,      X86::VPBLENDWYrmi,       TB_ALIGN_32 },
+    { X86::VPCMPEQBYrr,       X86::VPCMPEQBYrm,        TB_ALIGN_32 },
+    { X86::VPCMPEQDYrr,       X86::VPCMPEQDYrm,        TB_ALIGN_32 },
+    { X86::VPCMPEQQYrr,       X86::VPCMPEQQYrm,        TB_ALIGN_32 },
+    { X86::VPCMPEQWYrr,       X86::VPCMPEQWYrm,        TB_ALIGN_32 },
+    { X86::VPCMPGTBYrr,       X86::VPCMPGTBYrm,        TB_ALIGN_32 },
+    { X86::VPCMPGTDYrr,       X86::VPCMPGTDYrm,        TB_ALIGN_32 },
+    { X86::VPCMPGTQYrr,       X86::VPCMPGTQYrm,        TB_ALIGN_32 },
+    { X86::VPCMPGTWYrr,       X86::VPCMPGTWYrm,        TB_ALIGN_32 },
+    { X86::VPERM2I128rr,      X86::VPERM2I128rm,       TB_ALIGN_32 },
+    { X86::VPERMDYrr,         X86::VPERMDYrm,          TB_ALIGN_32 },
+    { X86::VPERMPDYrr,        X86::VPERMPDYrm,         TB_ALIGN_32 },
+    { X86::VPERMPSYrr,        X86::VPERMPSYrm,         TB_ALIGN_32 },
+    { X86::VPERMQYrr,         X86::VPERMQYrm,          TB_ALIGN_32 },
+    { X86::VPHADDDYrr,        X86::VPHADDDYrm,         TB_ALIGN_32 },
+    { X86::VPHADDSWrr256,     X86::VPHADDSWrm256,      TB_ALIGN_32 },
+    { X86::VPHADDWYrr,        X86::VPHADDWYrm,         TB_ALIGN_32 },
+    { X86::VPHSUBDYrr,        X86::VPHSUBDYrm,         TB_ALIGN_32 },
+    { X86::VPHSUBSWrr256,     X86::VPHSUBSWrm256,      TB_ALIGN_32 },
+    { X86::VPHSUBWYrr,        X86::VPHSUBWYrm,         TB_ALIGN_32 },
+    { X86::VPMADDUBSWrr256,   X86::VPMADDUBSWrm256,    TB_ALIGN_32 },
+    { X86::VPMADDWDYrr,       X86::VPMADDWDYrm,        TB_ALIGN_32 },
+    { X86::VPMAXSWYrr,        X86::VPMAXSWYrm,         TB_ALIGN_32 },
+    { X86::VPMAXUBYrr,        X86::VPMAXUBYrm,         TB_ALIGN_32 },
+    { X86::VPMINSWYrr,        X86::VPMINSWYrm,         TB_ALIGN_32 },
+    { X86::VPMINUBYrr,        X86::VPMINUBYrm,         TB_ALIGN_32 },
+    { X86::VMPSADBWYrri,      X86::VMPSADBWYrmi,       TB_ALIGN_32 },
+    { X86::VPMULDQYrr,        X86::VPMULDQYrm,         TB_ALIGN_32 },
+    { X86::VPMULHRSWrr256,    X86::VPMULHRSWrm256,     TB_ALIGN_32 },
+    { X86::VPMULHUWYrr,       X86::VPMULHUWYrm,        TB_ALIGN_32 },
+    { X86::VPMULHWYrr,        X86::VPMULHWYrm,         TB_ALIGN_32 },
+    { X86::VPMULLDYrr,        X86::VPMULLDYrm,         TB_ALIGN_32 },
+    { X86::VPMULLWYrr,        X86::VPMULLWYrm,         TB_ALIGN_32 },
+    { X86::VPMULUDQYrr,       X86::VPMULUDQYrm,        TB_ALIGN_32 },
+    { X86::VPORYrr,           X86::VPORYrm,            TB_ALIGN_32 },
+    { X86::VPSADBWYrr,        X86::VPSADBWYrm,         TB_ALIGN_32 },
+    { X86::VPSHUFBYrr,        X86::VPSHUFBYrm,         TB_ALIGN_32 },
+    { X86::VPSIGNBYrr,        X86::VPSIGNBYrm,         TB_ALIGN_32 },
+    { X86::VPSIGNWYrr,        X86::VPSIGNWYrm,         TB_ALIGN_32 },
+    { X86::VPSIGNDYrr,        X86::VPSIGNDYrm,         TB_ALIGN_32 },
+    { X86::VPSLLDYrr,         X86::VPSLLDYrm,          TB_ALIGN_16 },
+    { X86::VPSLLQYrr,         X86::VPSLLQYrm,          TB_ALIGN_16 },
+    { X86::VPSLLWYrr,         X86::VPSLLWYrm,          TB_ALIGN_16 },
+    { X86::VPSLLVDrr,         X86::VPSLLVDrm,          TB_ALIGN_16 },
+    { X86::VPSLLVDYrr,        X86::VPSLLVDYrm,         TB_ALIGN_32 },
+    { X86::VPSLLVQrr,         X86::VPSLLVQrm,          TB_ALIGN_16 },
+    { X86::VPSLLVQYrr,        X86::VPSLLVQYrm,         TB_ALIGN_32 },
+    { X86::VPSRADYrr,         X86::VPSRADYrm,          TB_ALIGN_16 },
+    { X86::VPSRAWYrr,         X86::VPSRAWYrm,          TB_ALIGN_16 },
+    { X86::VPSRAVDrr,         X86::VPSRAVDrm,          TB_ALIGN_16 },
+    { X86::VPSRAVDYrr,        X86::VPSRAVDYrm,         TB_ALIGN_32 },
+    { X86::VPSRLDYrr,         X86::VPSRLDYrm,          TB_ALIGN_16 },
+    { X86::VPSRLQYrr,         X86::VPSRLQYrm,          TB_ALIGN_16 },
+    { X86::VPSRLWYrr,         X86::VPSRLWYrm,          TB_ALIGN_16 },
+    { X86::VPSRLVDrr,         X86::VPSRLVDrm,          TB_ALIGN_16 },
+    { X86::VPSRLVDYrr,        X86::VPSRLVDYrm,         TB_ALIGN_32 },
+    { X86::VPSRLVQrr,         X86::VPSRLVQrm,          TB_ALIGN_16 },
+    { X86::VPSRLVQYrr,        X86::VPSRLVQYrm,         TB_ALIGN_32 },
+    { X86::VPSUBBYrr,         X86::VPSUBBYrm,          TB_ALIGN_32 },
+    { X86::VPSUBDYrr,         X86::VPSUBDYrm,          TB_ALIGN_32 },
+    { X86::VPSUBSBYrr,        X86::VPSUBSBYrm,         TB_ALIGN_32 },
+    { X86::VPSUBSWYrr,        X86::VPSUBSWYrm,         TB_ALIGN_32 },
+    { X86::VPSUBWYrr,         X86::VPSUBWYrm,          TB_ALIGN_32 },
+    { X86::VPUNPCKHBWYrr,     X86::VPUNPCKHBWYrm,      TB_ALIGN_32 },
+    { X86::VPUNPCKHDQYrr,     X86::VPUNPCKHDQYrm,      TB_ALIGN_32 },
+    { X86::VPUNPCKHQDQYrr,    X86::VPUNPCKHQDQYrm,     TB_ALIGN_16 },
+    { X86::VPUNPCKHWDYrr,     X86::VPUNPCKHWDYrm,      TB_ALIGN_32 },
+    { X86::VPUNPCKLBWYrr,     X86::VPUNPCKLBWYrm,      TB_ALIGN_32 },
+    { X86::VPUNPCKLDQYrr,     X86::VPUNPCKLDQYrm,      TB_ALIGN_32 },
+    { X86::VPUNPCKLQDQYrr,    X86::VPUNPCKLQDQYrm,     TB_ALIGN_32 },
+    { X86::VPUNPCKLWDYrr,     X86::VPUNPCKLWDYrm,      TB_ALIGN_32 },
+    { X86::VPXORYrr,          X86::VPXORYrm,           TB_ALIGN_32 },
     // FIXME: add AVX 256-bit foldable instructions
   };
=20
   for (unsigned i =3D 0, e =3D array_lengthof(OpTbl2); i !=3D e; ++i) {
-    unsigned RegOp =3D OpTbl2[i][0];
-    unsigned MemOp =3D OpTbl2[i][1];
-    unsigned Flags =3D OpTbl2[i][2];
+    unsigned RegOp =3D OpTbl2[i].RegOp;
+    unsigned MemOp =3D OpTbl2[i].MemOp;
+    unsigned Flags =3D OpTbl2[i].Flags;
     AddTableEntry(RegOp2MemOpTable2, MemOp2RegOpTable,
                   RegOp, MemOp,
                   // Index 2, folded load
@@ -946,7 +1169,6 @@
     switch (MI.getOpcode()) {
     default:
       llvm_unreachable(0);
-      break;
     case X86::MOVSX16rr8:
     case X86::MOVZX16rr8:
     case X86::MOVSX32rr8:
@@ -989,7 +1211,8 @@
=20
 static bool isFrameLoadOpcode(int Opcode) {
   switch (Opcode) {
-  default: break;
+  default:
+    return false;
   case X86::MOV8rm:
   case X86::MOV16rm:
   case X86::MOV32rm:
@@ -1011,9 +1234,7 @@
   case X86::MMX_MOVD64rm:
   case X86::MMX_MOVQ64rm:
     return true;
-    break;
   }
-  return false;
 }
=20
 static bool isFrameStoreOpcode(int Opcode) {
@@ -1203,6 +1424,8 @@
     bool SeenDef =3D false;
     for (unsigned j =3D 0, e =3D Iter->getNumOperands(); j !=3D e; ++j) {
       MachineOperand &MO =3D Iter->getOperand(j);
+      if (MO.isRegMask() && MO.clobbersPhysReg(X86::EFLAGS))
+        SeenDef =3D true;
       if (!MO.isReg())
         continue;
       if (MO.getReg() =3D=3D X86::EFLAGS) {
@@ -1247,6 +1470,10 @@
     bool SawKill =3D false;
     for (unsigned j =3D 0, e =3D Iter->getNumOperands(); j !=3D e; ++j) {
       MachineOperand &MO =3D Iter->getOperand(j);
+      // A register mask may clobber EFLAGS, but we should still look for a
+      // live EFLAGS def.
+      if (MO.isRegMask() && MO.clobbersPhysReg(X86::EFLAGS))
+        SawKill =3D true;
       if (MO.isReg() && MO.getReg() =3D=3D X86::EFLAGS) {
         if (MO.isDef()) return MO.isDead();
         if (MO.isKill()) SawKill =3D true;
@@ -1357,7 +1584,6 @@
   switch (MIOpc) {
   default:
     llvm_unreachable(0);
-    break;
   case X86::SHL16ri: {
     unsigned ShAmt =3D MI->getOperand(2).getImm();
     MIB.addReg(0).addImm(1 << ShAmt)
@@ -1392,9 +1618,9 @@
       leaInReg2 =3D RegInfo.createVirtualRegister(&X86::GR32_NOSPRegClass);
       // Build and insert into an implicit UNDEF value. This is OK because
       // well be shifting and then extracting the lower 16-bits.
-      BuildMI(*MFI, MIB, MI->getDebugLoc(), get(X86::IMPLICIT_DEF), leaInR=
eg2);
+      BuildMI(*MFI, &*MIB, MI->getDebugLoc(), get(X86::IMPLICIT_DEF),leaIn=
Reg2);
       InsMI2 =3D
-        BuildMI(*MFI, MIB, MI->getDebugLoc(), get(TargetOpcode::COPY))
+        BuildMI(*MFI, &*MIB, MI->getDebugLoc(), get(TargetOpcode::COPY))
         .addReg(leaInReg2, RegState::Define, X86::sub_16bit)
         .addReg(Src2, getKillRegState(isKill2));
       addRegReg(MIB, leaInReg, true, leaInReg2, true);
@@ -1469,6 +1695,24 @@
       .addReg(B, getKillRegState(isKill)).addImm(M);
     break;
   }
+  case X86::SHUFPDrri: {
+    assert(MI->getNumOperands() =3D=3D 4 && "Unknown shufpd instruction!");
+    if (!TM.getSubtarget<X86Subtarget>().hasSSE2()) return 0;
+
+    unsigned B =3D MI->getOperand(1).getReg();
+    unsigned C =3D MI->getOperand(2).getReg();
+    if (B !=3D C) return 0;
+    unsigned A =3D MI->getOperand(0).getReg();
+    unsigned M =3D MI->getOperand(3).getImm();
+
+    // Convert to PSHUFD mask.
+    M =3D ((M & 1) << 1) | ((M & 1) << 3) | ((M & 2) << 4) | ((M & 2) << 6=
)| 0x44;
+
+    NewMI =3D BuildMI(MF, MI->getDebugLoc(), get(X86::PSHUFDri))
+      .addReg(A, RegState::Define | getDeadRegState(isDead))
+      .addReg(B, getKillRegState(isKill)).addImm(M);
+    break;
+  }
   case X86::SHL64ri: {
     assert(MI->getNumOperands() >=3D 3 && "Unknown shift instruction!");
     // NOTE: LEA doesn't produce flags like shift does, but LLVM never uses
@@ -1597,7 +1841,7 @@
     case X86::ADD32rr_DB: {
       assert(MI->getNumOperands() >=3D 3 && "Unknown add instruction!");
       unsigned Opc;
-      TargetRegisterClass *RC;
+      const TargetRegisterClass *RC;
       if (MIOpc =3D=3D X86::ADD64rr || MIOpc =3D=3D X86::ADD64rr_DB) {
         Opc =3D X86::LEA64r;
         RC =3D X86::GR64_NOSPRegisterClass;
@@ -1904,13 +2148,12 @@
 }
=20
 bool X86InstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
-  const MCInstrDesc &MCID =3D MI->getDesc();
-  if (!MCID.isTerminator()) return false;
+  if (!MI->isTerminator()) return false;
=20
   // Conditional branch is a special case.
-  if (MCID.isBranch() && !MCID.isBarrier())
+  if (MI->isBranch() && !MI->isBarrier())
     return true;
-  if (!MCID.isPredicable())
+  if (!MI->isPredicable())
     return true;
   return !isPredicated(MI);
 }
@@ -1936,7 +2179,7 @@
=20
     // A terminator that isn't a branch can't easily be handled by this
     // analysis.
-    if (!I->getDesc().isBranch())
+    if (!I->isBranch())
       return true;
=20
     // Handle unconditional branches.
@@ -2420,7 +2663,9 @@
   bool HasAVX =3D TM.getSubtarget<X86Subtarget>().hasAVX();
   switch (MI->getOpcode()) {
   case X86::V_SET0:
-    return Expand2AddrUndef(MI, get(HasAVX ? X86::VPXORrr : X86::PXORrr));
+  case X86::FsFLD0SS:
+  case X86::FsFLD0SD:
+    return Expand2AddrUndef(MI, get(HasAVX ? X86::VXORPSrr : X86::XORPSrr)=
);
   case X86::TEST8ri_NOREX:
     MI->setDesc(get(X86::TEST8ri));
     return true;
@@ -2624,6 +2869,10 @@
 ///
 static bool hasPartialRegUpdate(unsigned Opcode) {
   switch (Opcode) {
+  case X86::CVTSI2SSrr:
+  case X86::CVTSI2SS64rr:
+  case X86::CVTSI2SDrr:
+  case X86::CVTSI2SD64rr:
   case X86::CVTSD2SSrr:
   case X86::Int_CVTSD2SSrr:
   case X86::CVTSS2SDrr:
@@ -2631,7 +2880,9 @@
   case X86::RCPSSr:
   case X86::RCPSSr_Int:
   case X86::ROUNDSDr:
+  case X86::ROUNDSDr_Int:
   case X86::ROUNDSSr:
+  case X86::ROUNDSSr_Int:
   case X86::RSQRTSSr:
   case X86::RSQRTSSr_Int:
   case X86::SQRTSSr:
@@ -2643,7 +2894,9 @@
   case X86::Int_VCVTSS2SDrr:
   case X86::VRCPSSr:
   case X86::VROUNDSDr:
+  case X86::VROUNDSDr_Int:
   case X86::VROUNDSSr:
+  case X86::VROUNDSSr_Int:
   case X86::VRSQRTSSr:
   case X86::VSQRTSSr:
     return true;
@@ -2652,6 +2905,54 @@
   return false;
 }
=20
+/// getPartialRegUpdateClearance - Inform the ExeDepsFix pass how many idle
+/// instructions we would like before a partial register update.
+unsigned X86InstrInfo::
+getPartialRegUpdateClearance(const MachineInstr *MI, unsigned OpNum,
+                             const TargetRegisterInfo *TRI) const {
+  if (OpNum !=3D 0 || !hasPartialRegUpdate(MI->getOpcode()))
+    return 0;
+
+  // If MI is marked as reading Reg, the partial register update is wanted.
+  const MachineOperand &MO =3D MI->getOperand(0);
+  unsigned Reg =3D MO.getReg();
+  if (TargetRegisterInfo::isVirtualRegister(Reg)) {
+    if (MO.readsReg() || MI->readsVirtualRegister(Reg))
+      return 0;
+  } else {
+    if (MI->readsRegister(Reg, TRI))
+      return 0;
+  }
+
+  // If any of the preceding 16 instructions are reading Reg, insert a
+  // dependency breaking instruction.  The magic number is based on a few
+  // Nehalem experiments.
+  return 16;
+}
+
+void X86InstrInfo::
+breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned OpNum,
+                          const TargetRegisterInfo *TRI) const {
+  unsigned Reg =3D MI->getOperand(OpNum).getReg();
+  if (X86::VR128RegClass.contains(Reg)) {
+    // These instructions are all floating point domain, so xorps is the b=
est
+    // choice.
+    bool HasAVX =3D TM.getSubtarget<X86Subtarget>().hasAVX();
+    unsigned Opc =3D HasAVX ? X86::VXORPSrr : X86::XORPSrr;
+    BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(Opc), Reg)
+      .addReg(Reg, RegState::Undef).addReg(Reg, RegState::Undef);
+  } else if (X86::VR256RegClass.contains(Reg)) {
+    // Use vxorps to clear the full ymm register.
+    // It wants to read and write the xmm sub-register.
+    unsigned XReg =3D TRI->getSubReg(Reg, X86::sub_xmm);
+    BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(X86::VXORPSrr), X=
Reg)
+      .addReg(XReg, RegState::Undef).addReg(XReg, RegState::Undef)
+      .addReg(Reg, RegState::ImplicitDefine);
+  } else
+    return;
+  MI->addRegisterKilled(Reg, TRI, true);
+}
+
 MachineInstr* X86InstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
                                                   MachineInstr *MI,
                                            const SmallVectorImpl<unsigned>=
 &Ops,
@@ -2714,6 +3015,8 @@
     switch (LoadMI->getOpcode()) {
     case X86::AVX_SET0PSY:
     case X86::AVX_SET0PDY:
+    case X86::AVX2_SETALLONES:
+    case X86::AVX2_SET0:
       Alignment =3D 32;
       break;
     case X86::V_SET0:
@@ -2722,11 +3025,9 @@
       Alignment =3D 16;
       break;
     case X86::FsFLD0SD:
-    case X86::VFsFLD0SD:
       Alignment =3D 8;
       break;
     case X86::FsFLD0SS:
-    case X86::VFsFLD0SS:
       Alignment =3D 4;
       break;
     default:
@@ -2759,10 +3060,10 @@
   case X86::AVX_SET0PSY:
   case X86::AVX_SET0PDY:
   case X86::AVX_SETALLONES:
+  case X86::AVX2_SETALLONES:
+  case X86::AVX2_SET0:
   case X86::FsFLD0SD:
-  case X86::FsFLD0SS:
-  case X86::VFsFLD0SD:
-  case X86::VFsFLD0SS: {
+  case X86::FsFLD0SS: {
     // Folding a V_SET0 or V_SETALLONES as a load, to ease register pressu=
re.
     // Create a constant-pool entry and operands to load from it.
=20
@@ -2788,16 +3089,19 @@
     MachineConstantPool &MCP =3D *MF.getConstantPool();
     Type *Ty;
     unsigned Opc =3D LoadMI->getOpcode();
-    if (Opc =3D=3D X86::FsFLD0SS || Opc =3D=3D X86::VFsFLD0SS)
+    if (Opc =3D=3D X86::FsFLD0SS)
       Ty =3D Type::getFloatTy(MF.getFunction()->getContext());
-    else if (Opc =3D=3D X86::FsFLD0SD || Opc =3D=3D X86::VFsFLD0SD)
+    else if (Opc =3D=3D X86::FsFLD0SD)
       Ty =3D Type::getDoubleTy(MF.getFunction()->getContext());
     else if (Opc =3D=3D X86::AVX_SET0PSY || Opc =3D=3D X86::AVX_SET0PDY)
       Ty =3D VectorType::get(Type::getFloatTy(MF.getFunction()->getContext=
()), 8);
+    else if (Opc =3D=3D X86::AVX2_SETALLONES || Opc =3D=3D X86::AVX2_SET0)
+      Ty =3D VectorType::get(Type::getInt32Ty(MF.getFunction()->getContext=
()), 8);
     else
       Ty =3D VectorType::get(Type::getInt32Ty(MF.getFunction()->getContext=
()), 4);
=20
-    bool IsAllOnes =3D (Opc =3D=3D X86::V_SETALLONES || Opc =3D=3D X86::AV=
X_SETALLONES);
+    bool IsAllOnes =3D (Opc =3D=3D X86::V_SETALLONES || Opc =3D=3D X86::AV=
X_SETALLONES ||
+                      Opc =3D=3D X86::AVX2_SETALLONES);
     const Constant *C =3D IsAllOnes ? Constant::getAllOnesValue(Ty) :
                                     Constant::getNullValue(Ty);
     unsigned CPI =3D MCP.getConstantPoolIndex(C, Alignment);
@@ -3329,7 +3633,7 @@
 // These are the replaceable SSE instructions. Some of these have Int vari=
ants
 // that we don't include here. We don't want to replace instructions selec=
ted
 // by intrinsics.
-static const unsigned ReplaceableInstrs[][3] =3D {
+static const uint16_t ReplaceableInstrs[][3] =3D {
   //PackedSingle     PackedDouble    PackedInt
   { X86::MOVAPSmr,   X86::MOVAPDmr,  X86::MOVDQAmr  },
   { X86::MOVAPSrm,   X86::MOVAPDrm,  X86::MOVDQArm  },
@@ -3366,31 +3670,66 @@
   { X86::VMOVAPSYrr,   X86::VMOVAPDYrr,   X86::VMOVDQAYrr  },
   { X86::VMOVUPSYmr,   X86::VMOVUPDYmr,   X86::VMOVDQUYmr  },
   { X86::VMOVUPSYrm,   X86::VMOVUPDYrm,   X86::VMOVDQUYrm  },
-  { X86::VMOVNTPSYmr,  X86::VMOVNTPDYmr,  X86::VMOVNTDQYmr },
+  { X86::VMOVNTPSYmr,  X86::VMOVNTPDYmr,  X86::VMOVNTDQYmr }
+};
+
+static const uint16_t ReplaceableInstrsAVX2[][3] =3D {
+  //PackedSingle       PackedDouble       PackedInt
+  { X86::VANDNPSYrm,   X86::VANDNPDYrm,   X86::VPANDNYrm   },
+  { X86::VANDNPSYrr,   X86::VANDNPDYrr,   X86::VPANDNYrr   },
+  { X86::VANDPSYrm,    X86::VANDPDYrm,    X86::VPANDYrm    },
+  { X86::VANDPSYrr,    X86::VANDPDYrr,    X86::VPANDYrr    },
+  { X86::VORPSYrm,     X86::VORPDYrm,     X86::VPORYrm     },
+  { X86::VORPSYrr,     X86::VORPDYrr,     X86::VPORYrr     },
+  { X86::VXORPSYrm,    X86::VXORPDYrm,    X86::VPXORYrm    },
+  { X86::VXORPSYrr,    X86::VXORPDYrr,    X86::VPXORYrr    },
+  { X86::VEXTRACTF128mr, X86::VEXTRACTF128mr, X86::VEXTRACTI128mr },
+  { X86::VEXTRACTF128rr, X86::VEXTRACTF128rr, X86::VEXTRACTI128rr },
+  { X86::VINSERTF128rm,  X86::VINSERTF128rm,  X86::VINSERTI128rm },
+  { X86::VINSERTF128rr,  X86::VINSERTF128rr,  X86::VINSERTI128rr },
+  { X86::VPERM2F128rm,   X86::VPERM2F128rm,   X86::VPERM2I128rm },
+  { X86::VPERM2F128rr,   X86::VPERM2F128rr,   X86::VPERM2I128rr }
 };
=20
 // FIXME: Some shuffle and unpack instructions have equivalents in differe=
nt
 // domains, but they require a bit more work than just switching opcodes.
=20
-static const unsigned *lookup(unsigned opcode, unsigned domain) {
+static const uint16_t *lookup(unsigned opcode, unsigned domain) {
   for (unsigned i =3D 0, e =3D array_lengthof(ReplaceableInstrs); i !=3D e=
; ++i)
     if (ReplaceableInstrs[i][domain-1] =3D=3D opcode)
       return ReplaceableInstrs[i];
   return 0;
 }
=20
+static const uint16_t *lookupAVX2(unsigned opcode, unsigned domain) {
+  for (unsigned i =3D 0, e =3D array_lengthof(ReplaceableInstrsAVX2); i !=
=3D e; ++i)
+    if (ReplaceableInstrsAVX2[i][domain-1] =3D=3D opcode)
+      return ReplaceableInstrsAVX2[i];
+  return 0;
+}
+
 std::pair<uint16_t, uint16_t>
 X86InstrInfo::getExecutionDomain(const MachineInstr *MI) const {
   uint16_t domain =3D (MI->getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
-  return std::make_pair(domain,
-                        domain && lookup(MI->getOpcode(), domain) ? 0xe : =
0);
+  bool hasAVX2 =3D TM.getSubtarget<X86Subtarget>().hasAVX2();
+  uint16_t validDomains =3D 0;
+  if (domain && lookup(MI->getOpcode(), domain))
+    validDomains =3D 0xe;
+  else if (domain && lookupAVX2(MI->getOpcode(), domain))
+    validDomains =3D hasAVX2 ? 0xe : 0x6;
+  return std::make_pair(domain, validDomains);
 }
=20
 void X86InstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) c=
onst {
   assert(Domain>0 && Domain<4 && "Invalid execution domain");
   uint16_t dom =3D (MI->getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
   assert(dom && "Not an SSE instruction");
-  const unsigned *table =3D lookup(MI->getOpcode(), dom);
+  const uint16_t *table =3D lookup(MI->getOpcode(), dom);
+  if (!table) { // try the other table
+    assert((TM.getSubtarget<X86Subtarget>().hasAVX2() || Domain < 3) &&
+           "256-bit vector operations only available in AVX2");
+    table =3D lookupAVX2(MI->getOpcode(), dom);
+  }
   assert(table && "Cannot change domain");
   MI->setDesc(get(table[Domain-1]));
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strInfo.h
--- a/head/contrib/llvm/lib/Target/X86/X86InstrInfo.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrInfo.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86InstrInfo.h - X86 Instruction Information ------------*- C=
++ -*- =3D=3D=3D//
+//=3D=3D=3D-- X86InstrInfo.h - X86 Instruction Information ------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,10 +14,10 @@
 #ifndef X86INSTRUCTIONINFO_H
 #define X86INSTRUCTIONINFO_H
=20
-#include "llvm/Target/TargetInstrInfo.h"
 #include "X86.h"
 #include "X86RegisterInfo.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/Target/TargetInstrInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "X86GenInstrInfo.inc"
@@ -345,6 +345,11 @@
=20
   void setExecutionDomain(MachineInstr *MI, unsigned Domain) const;
=20
+  unsigned getPartialRegUpdateClearance(const MachineInstr *MI, unsigned O=
pNum,
+                                        const TargetRegisterInfo *TRI) con=
st;
+  void breakPartialRegDependency(MachineBasicBlock::iterator MI, unsigned =
OpNum,
+                                 const TargetRegisterInfo *TRI) const;
+
   MachineInstr* foldMemoryOperandImpl(MachineFunction &MF,
                                       MachineInstr* MI,
                                       unsigned OpNum,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strInfo.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrInfo.td	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrInfo.td	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86InstrInfo.td - Main X86 Instruction Definition ---*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- X86InstrInfo.td - Main X86 Instruction Definition --*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -99,17 +99,16 @@
=20
 def SDT_X86SEG_ALLOCA : SDTypeProfile<1, 1, [SDTCisVT<0, iPTR>, SDTCisVT<1=
, iPTR>]>;
=20
+def SDT_X86WIN_FTOL : SDTypeProfile<0, 1, [SDTCisFP<0>]>;
+
 def SDT_X86EHRET : SDTypeProfile<0, 1, [SDTCisInt<0>]>;
=20
 def SDT_X86TCRET : SDTypeProfile<0, 2, [SDTCisPtrTy<0>, SDTCisVT<1, i32>]>;
=20
 def SDT_X86MEMBARRIER : SDTypeProfile<0, 0, []>;
-def SDT_X86MEMBARRIERNoSSE : SDTypeProfile<0, 1, [SDTCisInt<0>]>;
=20
 def X86MemBarrier : SDNode<"X86ISD::MEMBARRIER", SDT_X86MEMBARRIER,
                             [SDNPHasChain]>;
-def X86MemBarrierNoSSE : SDNode<"X86ISD::MEMBARRIER", SDT_X86MEMBARRIERNoS=
SE,
-                                [SDNPHasChain]>;
 def X86MFence : SDNode<"X86ISD::MFENCE", SDT_X86MEMBARRIER,
                         [SDNPHasChain]>;
 def X86SFence : SDNode<"X86ISD::SFENCE", SDT_X86MEMBARRIER,
@@ -226,6 +225,10 @@
                           [SDNPCommutative]>;
 def X86andn_flag : SDNode<"X86ISD::ANDN", SDTBinaryArithWithFlags>;
=20
+def X86blsi_flag : SDNode<"X86ISD::BLSI",  SDTUnaryArithWithFlags>;
+def X86blsmsk_flag : SDNode<"X86ISD::BLSMSK",  SDTUnaryArithWithFlags>;
+def X86blsr_flag : SDNode<"X86ISD::BLSR",  SDTUnaryArithWithFlags>;
+
 def X86mul_imm : SDNode<"X86ISD::MUL_IMM", SDTIntBinOp>;
=20
 def X86WinAlloca : SDNode<"X86ISD::WIN_ALLOCA", SDTX86Void,
@@ -237,6 +240,9 @@
 def X86TLSCall : SDNode<"X86ISD::TLSCALL", SDT_X86TLSCALL,
                         [SDNPHasChain, SDNPOptInGlue, SDNPOutGlue]>;
=20
+def X86WinFTOL : SDNode<"X86ISD::WIN_FTOL", SDT_X86WIN_FTOL,
+                        [SDNPHasChain, SDNPOutGlue]>;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // X86 Operand Definitions.
 //
@@ -247,10 +253,31 @@
=20
 // *mem - Operand definitions for the funky X86 addressing mode operands.
 //
-def X86MemAsmOperand : AsmOperandClass {
-  let Name =3D "Mem";
-  let SuperClasses =3D [];
+def X86MemAsmOperand : AsmOperandClass {=20
+ let Name =3D "Mem"; let PredicateMethod =3D "isMem";=20
 }
+def X86Mem8AsmOperand : AsmOperandClass {=20
+  let Name =3D "Mem8"; let PredicateMethod =3D "isMem8";
+}
+def X86Mem16AsmOperand : AsmOperandClass {=20
+  let Name =3D "Mem16"; let PredicateMethod =3D "isMem16";
+}
+def X86Mem32AsmOperand : AsmOperandClass {=20
+  let Name =3D "Mem32"; let PredicateMethod =3D "isMem32";
+}
+def X86Mem64AsmOperand : AsmOperandClass {=20
+  let Name =3D "Mem64"; let PredicateMethod =3D "isMem64";
+}
+def X86Mem80AsmOperand : AsmOperandClass {=20
+  let Name =3D "Mem80"; let PredicateMethod =3D "isMem80";
+}
+def X86Mem128AsmOperand : AsmOperandClass {=20
+  let Name =3D "Mem128"; let PredicateMethod =3D "isMem128";
+}
+def X86Mem256AsmOperand : AsmOperandClass {=20
+  let Name =3D "Mem256"; let PredicateMethod =3D "isMem256";
+}
+
 def X86AbsMemAsmOperand : AsmOperandClass {
   let Name =3D "AbsMem";
   let SuperClasses =3D [X86MemAsmOperand];
@@ -267,17 +294,28 @@
 def opaque80mem : X86MemOperand<"printopaquemem">;
 def opaque512mem : X86MemOperand<"printopaquemem">;
=20
-def i8mem   : X86MemOperand<"printi8mem">;
-def i16mem  : X86MemOperand<"printi16mem">;
-def i32mem  : X86MemOperand<"printi32mem">;
-def i64mem  : X86MemOperand<"printi64mem">;
-def i128mem : X86MemOperand<"printi128mem">;
-def i256mem : X86MemOperand<"printi256mem">;
-def f32mem  : X86MemOperand<"printf32mem">;
-def f64mem  : X86MemOperand<"printf64mem">;
-def f80mem  : X86MemOperand<"printf80mem">;
-def f128mem : X86MemOperand<"printf128mem">;
-def f256mem : X86MemOperand<"printf256mem">;
+def i8mem   : X86MemOperand<"printi8mem"> {=20
+  let ParserMatchClass =3D X86Mem8AsmOperand; }
+def i16mem  : X86MemOperand<"printi16mem"> {=20
+  let ParserMatchClass =3D X86Mem16AsmOperand; }
+def i32mem  : X86MemOperand<"printi32mem"> {=20
+  let ParserMatchClass =3D X86Mem32AsmOperand; }
+def i64mem  : X86MemOperand<"printi64mem"> {=20
+  let ParserMatchClass =3D X86Mem64AsmOperand; }
+def i128mem : X86MemOperand<"printi128mem"> {=20
+  let ParserMatchClass =3D X86Mem128AsmOperand; }
+def i256mem : X86MemOperand<"printi256mem"> {=20
+  let ParserMatchClass =3D X86Mem256AsmOperand; }
+def f32mem  : X86MemOperand<"printf32mem"> {=20
+  let ParserMatchClass =3D X86Mem32AsmOperand; }
+def f64mem  : X86MemOperand<"printf64mem"> {=20
+  let ParserMatchClass =3D X86Mem64AsmOperand; }
+def f80mem  : X86MemOperand<"printf80mem"> {=20
+  let ParserMatchClass =3D X86Mem80AsmOperand; }
+def f128mem : X86MemOperand<"printf128mem"> {=20
+  let ParserMatchClass =3D X86Mem128AsmOperand; }
+def f256mem : X86MemOperand<"printf256mem">{=20
+  let ParserMatchClass =3D X86Mem256AsmOperand; }
 }
=20
 // A version of i8mem for use on x86-64 that uses GR64_NOREX instead of
@@ -285,7 +323,7 @@
 def i8mem_NOREX : Operand<i64> {
   let PrintMethod =3D "printi8mem";
   let MIOperandInfo =3D (ops GR64_NOREX, i8imm, GR64_NOREX_NOSP, i32imm, i=
8imm);
-  let ParserMatchClass =3D X86MemAsmOperand;
+  let ParserMatchClass =3D X86Mem8AsmOperand;
   let OperandType =3D "OPERAND_MEMORY";
 }
=20
@@ -299,7 +337,7 @@
 def i32mem_TC : Operand<i32> {
   let PrintMethod =3D "printi32mem";
   let MIOperandInfo =3D (ops GR32_TC, i8imm, GR32_TC, i32imm, i8imm);
-  let ParserMatchClass =3D X86MemAsmOperand;
+  let ParserMatchClass =3D X86Mem32AsmOperand;
   let OperandType =3D "OPERAND_MEMORY";
 }
=20
@@ -310,7 +348,7 @@
   let PrintMethod =3D "printi64mem";
   let MIOperandInfo =3D (ops ptr_rc_tailcall, i8imm,
                        ptr_rc_tailcall, i32imm, i8imm);
-  let ParserMatchClass =3D X86MemAsmOperand;
+  let ParserMatchClass =3D X86Mem64AsmOperand;
   let OperandType =3D "OPERAND_MEMORY";
 }
=20
@@ -336,6 +374,11 @@
   let OperandType =3D "OPERAND_IMMEDIATE";
 }
=20
+def AVXCC : Operand<i8> {
+  let PrintMethod =3D "printSSECC";
+  let OperandType =3D "OPERAND_IMMEDIATE";
+}
+
 class ImmSExtAsmOperandClass : AsmOperandClass {
   let SuperClasses =3D [ImmAsmOperand];
   let RenderMethod =3D "addImmOperands";
@@ -466,37 +509,32 @@
 def HasSSE41     : Predicate<"Subtarget->hasSSE41()">;
 def HasSSE42     : Predicate<"Subtarget->hasSSE42()">;
 def HasSSE4A     : Predicate<"Subtarget->hasSSE4A()">;
-
 def HasAVX       : Predicate<"Subtarget->hasAVX()">;
-def HasXMMInt    : Predicate<"Subtarget->hasXMMInt()">;
+def HasAVX2      : Predicate<"Subtarget->hasAVX2()">;
=20
 def HasPOPCNT    : Predicate<"Subtarget->hasPOPCNT()">;
 def HasAES       : Predicate<"Subtarget->hasAES()">;
 def HasCLMUL     : Predicate<"Subtarget->hasCLMUL()">;
 def HasFMA3      : Predicate<"Subtarget->hasFMA3()">;
 def HasFMA4      : Predicate<"Subtarget->hasFMA4()">;
+def HasXOP       : Predicate<"Subtarget->hasXOP()">;
 def HasMOVBE     : Predicate<"Subtarget->hasMOVBE()">;
 def HasRDRAND    : Predicate<"Subtarget->hasRDRAND()">;
 def HasF16C      : Predicate<"Subtarget->hasF16C()">;
+def HasFSGSBase  : Predicate<"Subtarget->hasFSGSBase()">;
 def HasLZCNT     : Predicate<"Subtarget->hasLZCNT()">;
 def HasBMI       : Predicate<"Subtarget->hasBMI()">;
-def FPStackf32   : Predicate<"!Subtarget->hasXMM()">;
-def FPStackf64   : Predicate<"!Subtarget->hasXMMInt()">;
+def HasBMI2      : Predicate<"Subtarget->hasBMI2()">;
+def FPStackf32   : Predicate<"!Subtarget->hasSSE1()">;
+def FPStackf64   : Predicate<"!Subtarget->hasSSE2()">;
 def HasCmpxchg16b: Predicate<"Subtarget->hasCmpxchg16b()">;
 def In32BitMode  : Predicate<"!Subtarget->is64Bit()">,
                              AssemblerPredicate<"!Mode64Bit">;
 def In64BitMode  : Predicate<"Subtarget->is64Bit()">,
                              AssemblerPredicate<"Mode64Bit">;
 def IsWin64      : Predicate<"Subtarget->isTargetWin64()">;
-def NotWin64     : Predicate<"!Subtarget->isTargetWin64()">;
-def IsNaCl       : Predicate<"Subtarget->isTargetNaCl()">,
-                             AssemblerPredicate<"ModeNaCl">;
-def IsNaCl32     : Predicate<"Subtarget->isTargetNaCl32()">,
-                             AssemblerPredicate<"ModeNaCl,!Mode64Bit">;
-def IsNaCl64     : Predicate<"Subtarget->isTargetNaCl64()">,
-                             AssemblerPredicate<"ModeNaCl,Mode64Bit">;
-def NotNaCl      : Predicate<"!Subtarget->isTargetNaCl()">,
-                             AssemblerPredicate<"!ModeNaCl">;
+def IsNaCl       : Predicate<"Subtarget->isTargetNaCl()">;
+def NotNaCl      : Predicate<"!Subtarget->isTargetNaCl()">;
 def SmallCode    : Predicate<"TM.getCodeModel() =3D=3D CodeModel::Small">;
 def KernelCode   : Predicate<"TM.getCodeModel() =3D=3D CodeModel::Kernel">;
 def FarData      : Predicate<"TM.getCodeModel() !=3D CodeModel::Small &&"
@@ -1375,7 +1413,7 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// TZCNT Instruction
+// BMI Instructions
 //
 let Predicates =3D [HasBMI], Defs =3D [EFLAGS] in {
   def TZCNT16rr : I<0xBC, MRMSrcReg, (outs GR16:$dst), (ins GR16:$src),
@@ -1405,6 +1443,83 @@
                       (implicit EFLAGS)]>, XS;
 }
=20
+multiclass bmi_bls<string mnemonic, Format RegMRM, Format MemMRM,
+                  RegisterClass RC, X86MemOperand x86memop, SDNode OpNode,
+                  PatFrag ld_frag> {
+  def rr : I<0xF3, RegMRM, (outs RC:$dst), (ins RC:$src),
+             !strconcat(mnemonic, "\t{$src, $dst|$dst, $src}"),
+             [(set RC:$dst, EFLAGS, (OpNode RC:$src))]>, T8, VEX_4V;
+  def rm : I<0xF3, MemMRM, (outs RC:$dst), (ins x86memop:$src),
+             !strconcat(mnemonic, "\t{$src, $dst|$dst, $src}"),
+             [(set RC:$dst, EFLAGS, (OpNode (ld_frag addr:$src)))]>,
+             T8, VEX_4V;
+}
+
+let Predicates =3D [HasBMI], Defs =3D [EFLAGS] in {
+  defm BLSR32 : bmi_bls<"blsr{l}", MRM1r, MRM1m, GR32, i32mem,
+                        X86blsr_flag, loadi32>;
+  defm BLSR64 : bmi_bls<"blsr{q}", MRM1r, MRM1m, GR64, i64mem,
+                        X86blsr_flag, loadi64>, VEX_W;
+  defm BLSMSK32 : bmi_bls<"blsmsk{l}", MRM2r, MRM2m, GR32, i32mem,
+                          X86blsmsk_flag, loadi32>;
+  defm BLSMSK64 : bmi_bls<"blsmsk{q}", MRM2r, MRM2m, GR64, i64mem,
+                          X86blsmsk_flag, loadi64>, VEX_W;
+  defm BLSI32 : bmi_bls<"blsi{l}", MRM3r, MRM3m, GR32, i32mem,
+                        X86blsi_flag, loadi32>;
+  defm BLSI64 : bmi_bls<"blsi{q}", MRM3r, MRM3m, GR64, i64mem,
+                        X86blsi_flag, loadi64>, VEX_W;
+}
+
+multiclass bmi_bextr_bzhi<bits<8> opc, string mnemonic, RegisterClass RC,
+                          X86MemOperand x86memop, Intrinsic Int,
+                          PatFrag ld_frag> {
+  def rr : I<opc, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
+             !strconcat(mnemonic, "\t{$src2, $src1, $dst|$dst, $src1, $src=
2}"),
+             [(set RC:$dst, (Int RC:$src1, RC:$src2)), (implicit EFLAGS)]>,
+             T8, VEX_4VOp3;
+  def rm : I<opc, MRMSrcMem, (outs RC:$dst), (ins x86memop:$src1, RC:$src2=
),
+             !strconcat(mnemonic, "\t{$src2, $src1, $dst|$dst, $src1, $src=
2}"),
+             [(set RC:$dst, (Int (ld_frag addr:$src1), RC:$src2)),
+              (implicit EFLAGS)]>, T8, VEX_4VOp3;
+}
+
+let Predicates =3D [HasBMI], Defs =3D [EFLAGS] in {
+  defm BEXTR32 : bmi_bextr_bzhi<0xF7, "bextr{l}", GR32, i32mem,
+                                int_x86_bmi_bextr_32, loadi32>;
+  defm BEXTR64 : bmi_bextr_bzhi<0xF7, "bextr{q}", GR64, i64mem,
+                                int_x86_bmi_bextr_64, loadi64>, VEX_W;
+}
+
+let Predicates =3D [HasBMI2], Defs =3D [EFLAGS] in {
+  defm BZHI32 : bmi_bextr_bzhi<0xF5, "bzhi{l}", GR32, i32mem,
+                               int_x86_bmi_bzhi_32, loadi32>;
+  defm BZHI64 : bmi_bextr_bzhi<0xF5, "bzhi{q}", GR64, i64mem,
+                               int_x86_bmi_bzhi_64, loadi64>, VEX_W;
+}
+
+multiclass bmi_pdep_pext<string mnemonic, RegisterClass RC,
+                         X86MemOperand x86memop, Intrinsic Int,
+                         PatFrag ld_frag> {
+  def rr : I<0xF5, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
+             !strconcat(mnemonic, "\t{$src2, $src1, $dst|$dst, $src1, $src=
2}"),
+             [(set RC:$dst, (Int RC:$src1, RC:$src2))]>,
+             VEX_4V;
+  def rm : I<0xF5, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, x86memop:$src=
2),
+             !strconcat(mnemonic, "\t{$src2, $src1, $dst|$dst, $src1, $src=
2}"),
+             [(set RC:$dst, (Int RC:$src1, (ld_frag addr:$src2)))]>, VEX_4=
V;
+}
+
+let Predicates =3D [HasBMI2] in {
+  defm PDEP32 : bmi_pdep_pext<"pdep{l}", GR32, i32mem,
+                               int_x86_bmi_pdep_32, loadi32>, T8XD;
+  defm PDEP64 : bmi_pdep_pext<"pdep{q}", GR64, i64mem,
+                               int_x86_bmi_pdep_64, loadi64>, T8XD, VEX_W;
+  defm PEXT32 : bmi_pdep_pext<"pext{l}", GR32, i32mem,
+                               int_x86_bmi_pext_32, loadi32>, T8XS;
+  defm PEXT64 : bmi_pdep_pext<"pext{q}", GR64, i64mem,
+                               int_x86_bmi_pext_64, loadi64>, T8XS, VEX_W;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Subsystems.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1424,12 +1539,16 @@
 // FMA - Fused Multiply-Add support (requires FMA)
 include "X86InstrFMA.td"
=20
+// XOP
+include "X86InstrXOP.td"
+
 // SSE, MMX and 3DNow! vector support.
 include "X86InstrSSE.td"
 include "X86InstrMMX.td"
 include "X86Instr3DNow.td"
=20
 include "X86InstrVMX.td"
+include "X86InstrSVM.td"
=20
 // System instructions.
 include "X86InstrSystem.td"
@@ -1445,10 +1564,11 @@
 def : MnemonicAlias<"call", "callq">, Requires<[In64BitMode]>;
=20
 def : MnemonicAlias<"cbw",  "cbtw">;
+def : MnemonicAlias<"cwde", "cwtl">;
 def : MnemonicAlias<"cwd",  "cwtd">;
 def : MnemonicAlias<"cdq", "cltd">;
-def : MnemonicAlias<"cwde", "cwtl">;
 def : MnemonicAlias<"cdqe", "cltq">;
+def : MnemonicAlias<"cqo", "cqto">;
=20
 // lret maps to lretl, it is not ambiguous with lretq.
 def : MnemonicAlias<"lret", "lretl">;
@@ -1497,6 +1617,7 @@
 // System instruction aliases.
 def : MnemonicAlias<"iret", "iretl">;
 def : MnemonicAlias<"sysret", "sysretl">;
+def : MnemonicAlias<"sysexit", "sysexitl">;
=20
 def : MnemonicAlias<"lgdtl", "lgdt">, Requires<[In32BitMode]>;
 def : MnemonicAlias<"lgdtq", "lgdt">, Requires<[In64BitMode]>;
@@ -1516,6 +1637,8 @@
 def : MnemonicAlias<"fcmovae",  "fcmovnb">;
 def : MnemonicAlias<"fcomip",   "fcompi">;
 def : MnemonicAlias<"fildq",    "fildll">;
+def : MnemonicAlias<"fistpq",   "fistpll">;
+def : MnemonicAlias<"fisttpq",  "fisttpll">;
 def : MnemonicAlias<"fldcww",   "fldcw">;
 def : MnemonicAlias<"fnstcww", "fnstcw">;
 def : MnemonicAlias<"fnstsww", "fnstsw">;
@@ -1737,20 +1860,20 @@
 // errors, since its encoding is the most compact.
 def : InstAlias<"sldt $mem", (SLDT16m i16mem:$mem)>;
=20
-// shld/shrd op,op -> shld op, op, 1
-def : InstAlias<"shldw $r1, $r2", (SHLD16rri8 GR16:$r1, GR16:$r2, 1)>;
-def : InstAlias<"shldl $r1, $r2", (SHLD32rri8 GR32:$r1, GR32:$r2, 1)>;
-def : InstAlias<"shldq $r1, $r2", (SHLD64rri8 GR64:$r1, GR64:$r2, 1)>;
-def : InstAlias<"shrdw $r1, $r2", (SHRD16rri8 GR16:$r1, GR16:$r2, 1)>;
-def : InstAlias<"shrdl $r1, $r2", (SHRD32rri8 GR32:$r1, GR32:$r2, 1)>;
-def : InstAlias<"shrdq $r1, $r2", (SHRD64rri8 GR64:$r1, GR64:$r2, 1)>;
+// shld/shrd op,op -> shld op, op, CL
+def : InstAlias<"shldw $r2, $r1", (SHLD16rrCL GR16:$r1, GR16:$r2)>;
+def : InstAlias<"shldl $r2, $r1", (SHLD32rrCL GR32:$r1, GR32:$r2)>;
+def : InstAlias<"shldq $r2, $r1", (SHLD64rrCL GR64:$r1, GR64:$r2)>;
+def : InstAlias<"shrdw $r2, $r1", (SHRD16rrCL GR16:$r1, GR16:$r2)>;
+def : InstAlias<"shrdl $r2, $r1", (SHRD32rrCL GR32:$r1, GR32:$r2)>;
+def : InstAlias<"shrdq $r2, $r1", (SHRD64rrCL GR64:$r1, GR64:$r2)>;
=20
-def : InstAlias<"shldw $mem, $reg", (SHLD16mri8 i16mem:$mem, GR16:$reg, 1)=
>;
-def : InstAlias<"shldl $mem, $reg", (SHLD32mri8 i32mem:$mem, GR32:$reg, 1)=
>;
-def : InstAlias<"shldq $mem, $reg", (SHLD64mri8 i64mem:$mem, GR64:$reg, 1)=
>;
-def : InstAlias<"shrdw $mem, $reg", (SHRD16mri8 i16mem:$mem, GR16:$reg, 1)=
>;
-def : InstAlias<"shrdl $mem, $reg", (SHRD32mri8 i32mem:$mem, GR32:$reg, 1)=
>;
-def : InstAlias<"shrdq $mem, $reg", (SHRD64mri8 i64mem:$mem, GR64:$reg, 1)=
>;
+def : InstAlias<"shldw $reg, $mem", (SHLD16mrCL i16mem:$mem, GR16:$reg)>;
+def : InstAlias<"shldl $reg, $mem", (SHLD32mrCL i32mem:$mem, GR32:$reg)>;
+def : InstAlias<"shldq $reg, $mem", (SHLD64mrCL i64mem:$mem, GR64:$reg)>;
+def : InstAlias<"shrdw $reg, $mem", (SHRD16mrCL i16mem:$mem, GR16:$reg)>;
+def : InstAlias<"shrdl $reg, $mem", (SHRD32mrCL i32mem:$mem, GR32:$reg)>;
+def : InstAlias<"shrdq $reg, $mem", (SHRD64mrCL i64mem:$mem, GR64:$reg)>;
=20
 /*  FIXME: This is disabled because the asm matcher is currently incapable=
 of
  *  matching a fixed immediate like $1.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strMMX.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrMMX.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrMMX.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D- X86InstrMMX.td - Describe the MMX Instruction Set --*- tab=
legen -*-=3D=3D=3D//
+//=3D=3D=3D-- X86InstrMMX.td - Describe the MMX Instruction Set --*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -105,19 +105,23 @@
                          Intrinsic Int, X86MemOperand x86memop, PatFrag ld=
_frag,
                          string asm, Domain d> {
   def irr : PI<opc, MRMSrcReg, (outs DstRC:$dst), (ins SrcRC:$src), asm,
-                        [(set DstRC:$dst, (Int SrcRC:$src))], d>;
+                        [(set DstRC:$dst, (Int SrcRC:$src))],=20
+                        IIC_DEFAULT, d>;
   def irm : PI<opc, MRMSrcMem, (outs DstRC:$dst), (ins x86memop:$src), asm,
-                        [(set DstRC:$dst, (Int (ld_frag addr:$src)))], d>;
+                        [(set DstRC:$dst, (Int (ld_frag addr:$src)))],=20
+                        IIC_DEFAULT, d>;
 }
=20
 multiclass sse12_cvt_pint_3addr<bits<8> opc, RegisterClass SrcRC,
                     RegisterClass DstRC, Intrinsic Int, X86MemOperand x86m=
emop,
                     PatFrag ld_frag, string asm, Domain d> {
   def irr : PI<opc, MRMSrcReg, (outs DstRC:$dst),(ins DstRC:$src1, SrcRC:$=
src2),
-              asm, [(set DstRC:$dst, (Int DstRC:$src1, SrcRC:$src2))], d>;
+              asm, [(set DstRC:$dst, (Int DstRC:$src1, SrcRC:$src2))],=20
+              IIC_DEFAULT, d>;
   def irm : PI<opc, MRMSrcMem, (outs DstRC:$dst),
                    (ins DstRC:$src1, x86memop:$src2), asm,
-              [(set DstRC:$dst, (Int DstRC:$src1, (ld_frag addr:$src2)))],=
 d>;
+              [(set DstRC:$dst, (Int DstRC:$src1, (ld_frag addr:$src2)))],=20
+              IIC_DEFAULT, d>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -175,25 +179,25 @@
                         "movq\t{$src, $dst|$dst, $src}",
                         [(store (x86mmx VR64:$src), addr:$dst)]>;
=20
-def MMX_MOVDQ2Qrr : SDIi8<0xD6, MRMSrcReg, (outs VR64:$dst), (ins VR128:$s=
rc),
-                          "movdq2q\t{$src, $dst|$dst, $src}",
+def MMX_MOVDQ2Qrr : SDIi8<0xD6, MRMSrcReg, (outs VR64:$dst),
+                          (ins VR128:$src), "movdq2q\t{$src, $dst|$dst, $s=
rc}",
                           [(set VR64:$dst,
                             (x86mmx (bitconvert
                             (i64 (vector_extract (v2i64 VR128:$src),
                                   (iPTR 0))))))]>;
=20
-def MMX_MOVQ2DQrr : SSDIi8<0xD6, MRMSrcReg, (outs VR128:$dst), (ins VR64:$=
src),
-                           "movq2dq\t{$src, $dst|$dst, $src}",
+def MMX_MOVQ2DQrr : SSDIi8<0xD6, MRMSrcReg, (outs VR128:$dst),
+                            (ins VR64:$src), "movq2dq\t{$src, $dst|$dst, $=
src}",
           [(set VR128:$dst,
             (v2i64 (scalar_to_vector
                               (i64 (bitconvert (x86mmx VR64:$src))))))]>;
=20
 let neverHasSideEffects =3D 1 in
-def MMX_MOVQ2FR64rr: SSDIi8<0xD6, MRMSrcReg, (outs FR64:$dst), (ins VR64:$=
src),
-                           "movq2dq\t{$src, $dst|$dst, $src}", []>;
+def MMX_MOVQ2FR64rr: SSDIi8<0xD6, MRMSrcReg, (outs FR64:$dst),
+                       (ins VR64:$src), "movq2dq\t{$src, $dst|$dst, $src}"=
, []>;
=20
-def MMX_MOVFR642Qrr: SDIi8<0xD6, MRMSrcReg, (outs VR64:$dst), (ins FR64:$s=
rc),
-                           "movdq2q\t{$src, $dst|$dst, $src}", []>;
+def MMX_MOVFR642Qrr: SDIi8<0xD6, MRMSrcReg, (outs VR64:$dst),
+                       (ins FR64:$src), "movdq2q\t{$src, $dst|$dst, $src}"=
, []>;
=20
 def MMX_MOVNTQmr  : MMXI<0xE7, MRMDestMem, (outs), (ins i64mem:$dst, VR64:=
$src),
                          "movntq\t{$src, $dst|$dst, $src}",
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strSSE.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrSSE.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrSSE.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D- X86InstrSSE.td - Describe the X86 Instruction Set --*- tab=
legen -*-=3D=3D=3D//
+//=3D=3D=3D-- X86InstrSSE.td - SSE Instruction Set ---------------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,6 +13,126 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+class OpndItins<InstrItinClass arg_rr, InstrItinClass arg_rm> {
+  InstrItinClass rr =3D arg_rr;
+  InstrItinClass rm =3D arg_rm;
+}
+
+class SizeItins<OpndItins arg_s, OpndItins arg_d> {
+  OpndItins s =3D arg_s;
+  OpndItins d =3D arg_d;
+}
+
+
+class ShiftOpndItins<InstrItinClass arg_rr, InstrItinClass arg_rm,
+  InstrItinClass arg_ri> {
+  InstrItinClass rr =3D arg_rr;
+  InstrItinClass rm =3D arg_rm;
+  InstrItinClass ri =3D arg_ri;
+}
+
+
+// scalar
+def SSE_ALU_F32S : OpndItins<
+  IIC_SSE_ALU_F32S_RR, IIC_SSE_ALU_F32S_RM
+>;
+
+def SSE_ALU_F64S : OpndItins<
+  IIC_SSE_ALU_F64S_RR, IIC_SSE_ALU_F64S_RM
+>;
+
+def SSE_ALU_ITINS_S : SizeItins<
+  SSE_ALU_F32S, SSE_ALU_F64S
+>;
+
+def SSE_MUL_F32S : OpndItins<
+  IIC_SSE_MUL_F32S_RR, IIC_SSE_MUL_F64S_RM
+>;
+
+def SSE_MUL_F64S : OpndItins<
+  IIC_SSE_MUL_F64S_RR, IIC_SSE_MUL_F64S_RM
+>;
+
+def SSE_MUL_ITINS_S : SizeItins<
+  SSE_MUL_F32S, SSE_MUL_F64S
+>;
+
+def SSE_DIV_F32S : OpndItins<
+  IIC_SSE_DIV_F32S_RR, IIC_SSE_DIV_F64S_RM
+>;
+
+def SSE_DIV_F64S : OpndItins<
+  IIC_SSE_DIV_F64S_RR, IIC_SSE_DIV_F64S_RM
+>;
+
+def SSE_DIV_ITINS_S : SizeItins<
+  SSE_DIV_F32S, SSE_DIV_F64S
+>;
+
+// parallel
+def SSE_ALU_F32P : OpndItins<
+  IIC_SSE_ALU_F32P_RR, IIC_SSE_ALU_F32P_RM
+>;
+
+def SSE_ALU_F64P : OpndItins<
+  IIC_SSE_ALU_F64P_RR, IIC_SSE_ALU_F64P_RM
+>;
+
+def SSE_ALU_ITINS_P : SizeItins<
+  SSE_ALU_F32P, SSE_ALU_F64P
+>;
+
+def SSE_MUL_F32P : OpndItins<
+  IIC_SSE_MUL_F32P_RR, IIC_SSE_MUL_F64P_RM
+>;
+
+def SSE_MUL_F64P : OpndItins<
+  IIC_SSE_MUL_F64P_RR, IIC_SSE_MUL_F64P_RM
+>;
+
+def SSE_MUL_ITINS_P : SizeItins<
+  SSE_MUL_F32P, SSE_MUL_F64P
+>;
+
+def SSE_DIV_F32P : OpndItins<
+  IIC_SSE_DIV_F32P_RR, IIC_SSE_DIV_F64P_RM
+>;
+
+def SSE_DIV_F64P : OpndItins<
+  IIC_SSE_DIV_F64P_RR, IIC_SSE_DIV_F64P_RM
+>;
+
+def SSE_DIV_ITINS_P : SizeItins<
+  SSE_DIV_F32P, SSE_DIV_F64P
+>;
+
+def SSE_BIT_ITINS_P : OpndItins<
+  IIC_SSE_BIT_P_RR, IIC_SSE_BIT_P_RM
+>;
+
+def SSE_INTALU_ITINS_P : OpndItins<
+  IIC_SSE_INTALU_P_RR, IIC_SSE_INTALU_P_RM
+>;
+
+def SSE_INTALUQ_ITINS_P : OpndItins<
+  IIC_SSE_INTALUQ_P_RR, IIC_SSE_INTALUQ_P_RM
+>;
+
+def SSE_INTMUL_ITINS_P : OpndItins<
+  IIC_SSE_INTMUL_P_RR, IIC_SSE_INTMUL_P_RM
+>;
+
+def SSE_INTSHIFT_ITINS_P : ShiftOpndItins<
+  IIC_SSE_INTSH_P_RR, IIC_SSE_INTSH_P_RM, IIC_SSE_INTSH_P_RI
+>;
+
+def SSE_MOVA_ITINS : OpndItins<
+  IIC_SSE_MOVA_P_RR, IIC_SSE_MOVA_P_RM
+>;
+
+def SSE_MOVU_ITINS : OpndItins<
+  IIC_SSE_MOVU_P_RR, IIC_SSE_MOVU_P_RM
+>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE 1 & 2 Instructions Classes
@@ -21,25 +141,27 @@
 /// sse12_fp_scalar - SSE 1 & 2 scalar instructions class
 multiclass sse12_fp_scalar<bits<8> opc, string OpcodeStr, SDNode OpNode,
                            RegisterClass RC, X86MemOperand x86memop,
+                           OpndItins itins,
                            bit Is2Addr =3D 1> {
   let isCommutable =3D 1 in {
     def rr : SI<opc, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set RC:$dst, (OpNode RC:$src1, RC:$src2))]>;
+       [(set RC:$dst, (OpNode RC:$src1, RC:$src2))], itins.rr>;
   }
   def rm : SI<opc, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, x86memop:$src=
2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set RC:$dst, (OpNode RC:$src1, (load addr:$src2)))]>;
+       [(set RC:$dst, (OpNode RC:$src1, (load addr:$src2)))], itins.rm>;
 }
=20
 /// sse12_fp_scalar_int - SSE 1 & 2 scalar instructions intrinsics class
 multiclass sse12_fp_scalar_int<bits<8> opc, string OpcodeStr, RegisterClas=
s RC,
                              string asm, string SSEVer, string FPSizeStr,
                              Operand memopr, ComplexPattern mem_cpat,
+                             OpndItins itins,
                              bit Is2Addr =3D 1> {
   def rr_Int : SI<opc, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
@@ -47,72 +169,74 @@
            !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}")),
        [(set RC:$dst, (!cast<Intrinsic>(
                  !strconcat("int_x86_sse", SSEVer, "_", OpcodeStr, FPSizeS=
tr))
-             RC:$src1, RC:$src2))]>;
+             RC:$src1, RC:$src2))], itins.rr>;
   def rm_Int : SI<opc, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, memopr:$s=
rc2),
        !if(Is2Addr,
            !strconcat(asm, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}")),
        [(set RC:$dst, (!cast<Intrinsic>(!strconcat("int_x86_sse",
                                           SSEVer, "_", OpcodeStr, FPSizeSt=
r))
-             RC:$src1, mem_cpat:$src2))]>;
+             RC:$src1, mem_cpat:$src2))], itins.rm>;
 }
=20
 /// sse12_fp_packed - SSE 1 & 2 packed instructions class
 multiclass sse12_fp_packed<bits<8> opc, string OpcodeStr, SDNode OpNode,
                            RegisterClass RC, ValueType vt,
                            X86MemOperand x86memop, PatFrag mem_frag,
-                           Domain d, bit Is2Addr =3D 1> {
+                           Domain d, OpndItins itins, bit Is2Addr =3D 1> {
   let isCommutable =3D 1 in
     def rr : PI<opc, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set RC:$dst, (vt (OpNode RC:$src1, RC:$src2)))], d>;
+       [(set RC:$dst, (vt (OpNode RC:$src1, RC:$src2)))], itins.rr, d>;
   let mayLoad =3D 1 in
     def rm : PI<opc, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, x86memop:$s=
rc2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set RC:$dst, (OpNode RC:$src1, (mem_frag addr:$src2)))], d>;
+       [(set RC:$dst, (OpNode RC:$src1, (mem_frag addr:$src2)))],
+          itins.rm, d>;
 }
=20
 /// sse12_fp_packed_logical_rm - SSE 1 & 2 packed instructions class
 multiclass sse12_fp_packed_logical_rm<bits<8> opc, RegisterClass RC, Domai=
n d,
                                       string OpcodeStr, X86MemOperand x86m=
emop,
                                       list<dag> pat_rr, list<dag> pat_rm,
-                                      bit Is2Addr =3D 1> {
-  let isCommutable =3D 1 in
+                                      bit Is2Addr =3D 1,
+                                      bit rr_hasSideEffects =3D 0> {
+  let isCommutable =3D 1, neverHasSideEffects =3D rr_hasSideEffects in
     def rr : PI<opc, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       pat_rr, d>;
+       pat_rr, IIC_DEFAULT, d>;
   def rm : PI<opc, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, x86memop:$src=
2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       pat_rm, d>;
+       pat_rm, IIC_DEFAULT, d>;
 }
=20
 /// sse12_fp_packed_int - SSE 1 & 2 packed instructions intrinsics class
 multiclass sse12_fp_packed_int<bits<8> opc, string OpcodeStr, RegisterClas=
s RC,
                            string asm, string SSEVer, string FPSizeStr,
                            X86MemOperand x86memop, PatFrag mem_frag,
-                           Domain d, bit Is2Addr =3D 1> {
+                           Domain d, OpndItins itins, bit Is2Addr =3D 1> {
   def rr_Int : PI<opc, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(asm, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}")),
            [(set RC:$dst, (!cast<Intrinsic>(
                      !strconcat("int_x86_", SSEVer, "_", OpcodeStr, FPSize=
Str))
-                 RC:$src1, RC:$src2))], d>;
+                 RC:$src1, RC:$src2))], IIC_DEFAULT, d>;
   def rm_Int : PI<opc, MRMSrcMem, (outs RC:$dst), (ins RC:$src1,x86memop:$=
src2),
        !if(Is2Addr,
            !strconcat(asm, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}")),
        [(set RC:$dst, (!cast<Intrinsic>(
                      !strconcat("int_x86_", SSEVer, "_", OpcodeStr, FPSize=
Str))
-             RC:$src1, (mem_frag addr:$src2)))], d>;
+             RC:$src1, (mem_frag addr:$src2)))], IIC_DEFAULT, d>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -170,7 +294,7 @@
=20
 // Bitcasts between 128-bit vector types. Return the original type since
 // no instruction is needed for the conversion
-let Predicates =3D [HasXMMInt] in {
+let Predicates =3D [HasSSE2] in {
   def : Pat<(v2i64 (bitconvert (v4i32 VR128:$src))), (v2i64 VR128:$src)>;
   def : Pat<(v2i64 (bitconvert (v8i16 VR128:$src))), (v2i64 VR128:$src)>;
   def : Pat<(v2i64 (bitconvert (v16i8 VR128:$src))), (v2i64 VR128:$src)>;
@@ -239,21 +363,13 @@
 }
=20
 // Alias instructions that map fld0 to pxor for sse.
-// FIXME: Set encoding to pseudo!
-let isReMaterializable =3D 1, isAsCheapAsAMove =3D 1, isCodeGenOnly =3D 1,
-    canFoldAsLoad =3D 1 in {
-  def FsFLD0SS : I<0xEF, MRMInitReg, (outs FR32:$dst), (ins), "",
-                   [(set FR32:$dst, fp32imm0)]>,
-                   Requires<[HasSSE1]>, TB, OpSize;
-  def FsFLD0SD : I<0xEF, MRMInitReg, (outs FR64:$dst), (ins), "",
-                   [(set FR64:$dst, fpimm0)]>,
-                 Requires<[HasSSE2]>, TB, OpSize;
-  def VFsFLD0SS : I<0xEF, MRMInitReg, (outs FR32:$dst), (ins), "",
-                    [(set FR32:$dst, fp32imm0)]>,
-                    Requires<[HasAVX]>, TB, OpSize, VEX_4V;
-  def VFsFLD0SD : I<0xEF, MRMInitReg, (outs FR64:$dst), (ins), "",
-                    [(set FR64:$dst, fpimm0)]>,
-                    Requires<[HasAVX]>, TB, OpSize, VEX_4V;
+// This is expanded by ExpandPostRAPseudos.
+let isReMaterializable =3D 1, isAsCheapAsAMove =3D 1, canFoldAsLoad =3D 1,
+    isPseudo =3D 1 in {
+  def FsFLD0SS : I<0, Pseudo, (outs FR32:$dst), (ins), "",
+                   [(set FR32:$dst, fp32imm0)]>, Requires<[HasSSE1]>;
+  def FsFLD0SD : I<0, Pseudo, (outs FR64:$dst), (ins), "",
+                   [(set FR64:$dst, fpimm0)]>, Requires<[HasSSE2]>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -286,16 +402,35 @@
 // JIT implementatioan, it does not expand the instructions below like
 // X86MCInstLower does.
 let isReMaterializable =3D 1, isAsCheapAsAMove =3D 1, canFoldAsLoad =3D 1,
-    isCodeGenOnly =3D 1, Predicates =3D [HasAVX] in {
+    isCodeGenOnly =3D 1 in {
+let Predicates =3D [HasAVX] in {
 def AVX_SET0PSY : PSI<0x57, MRMInitReg, (outs VR256:$dst), (ins), "",
                    [(set VR256:$dst, (v8f32 immAllZerosV))]>, VEX_4V;
 def AVX_SET0PDY : PDI<0x57, MRMInitReg, (outs VR256:$dst), (ins), "",
                    [(set VR256:$dst, (v4f64 immAllZerosV))]>, VEX_4V;
 }
-
+let Predicates =3D [HasAVX2], neverHasSideEffects =3D 1 in
+def AVX2_SET0   : PDI<0xef, MRMInitReg, (outs VR256:$dst), (ins), "",
+                   []>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2], AddedComplexity =3D 5 in {
+  def : Pat<(v4i64 immAllZerosV), (AVX2_SET0)>;
+  def : Pat<(v8i32 immAllZerosV), (AVX2_SET0)>;
+  def : Pat<(v16i16 immAllZerosV), (AVX2_SET0)>;
+  def : Pat<(v32i8 immAllZerosV), (AVX2_SET0)>;
+}
=20
 // AVX has no support for 256-bit integer instructions, but since the 128-=
bit
 // VPXOR instruction writes zero to its upper part, it's safe build zeros.
+def : Pat<(v32i8 immAllZerosV), (SUBREG_TO_REG (i8 0), (V_SET0), sub_xmm)>;
+def : Pat<(bc_v32i8 (v8f32 immAllZerosV)),
+          (SUBREG_TO_REG (i8 0), (V_SET0), sub_xmm)>;
+
+def : Pat<(v16i16 immAllZerosV), (SUBREG_TO_REG (i16 0), (V_SET0), sub_xmm=
)>;
+def : Pat<(bc_v16i16 (v8f32 immAllZerosV)),
+          (SUBREG_TO_REG (i16 0), (V_SET0), sub_xmm)>;
+
 def : Pat<(v8i32 immAllZerosV), (SUBREG_TO_REG (i32 0), (V_SET0), sub_xmm)=
>;
 def : Pat<(bc_v8i32 (v8f32 immAllZerosV)),
           (SUBREG_TO_REG (i32 0), (V_SET0), sub_xmm)>;
@@ -310,13 +445,16 @@
 // JIT implementation, it does not expand the instructions below like
 // X86MCInstLower does.
 let isReMaterializable =3D 1, isAsCheapAsAMove =3D 1, canFoldAsLoad =3D 1,
-    isCodeGenOnly =3D 1, ExeDomain =3D SSEPackedInt in
+    isCodeGenOnly =3D 1, ExeDomain =3D SSEPackedInt in {
+  let Predicates =3D [HasAVX] in
+  def AVX_SETALLONES : PDI<0x76, MRMInitReg, (outs VR128:$dst), (ins), "",
+                         [(set VR128:$dst, (v4i32 immAllOnesV))]>, VEX_4V;
   def V_SETALLONES : PDI<0x76, MRMInitReg, (outs VR128:$dst), (ins), "",
                          [(set VR128:$dst, (v4i32 immAllOnesV))]>;
-let isReMaterializable =3D 1, isAsCheapAsAMove =3D 1, canFoldAsLoad =3D 1,
-    isCodeGenOnly =3D 1, ExeDomain =3D SSEPackedInt, Predicates =3D [HasAV=
X] in
-  def AVX_SETALLONES : PDI<0x76, MRMInitReg, (outs VR128:$dst), (ins), "",
-                         [(set VR128:$dst, (v4i32 immAllOnesV))]>, VEX_4V;
+  let Predicates =3D [HasAVX2] in
+  def AVX2_SETALLONES : PDI<0x76, MRMInitReg, (outs VR256:$dst), (ins), "",
+                          [(set VR256:$dst, (v8i32 immAllOnesV))]>, VEX_4V;
+}
=20
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -329,22 +467,25 @@
 // in terms of a copy, and just mentioned, we don't use movss/movsd for co=
pies.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-class sse12_move_rr<RegisterClass RC, ValueType vt, string asm> :
+class sse12_move_rr<RegisterClass RC, SDNode OpNode, ValueType vt, string =
asm> :
       SI<0x10, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src1, RC:$src2), =
asm,
-      [(set (vt VR128:$dst), (movl VR128:$src1, (scalar_to_vector RC:$src2=
)))]>;
+      [(set VR128:$dst, (vt (OpNode VR128:$src1,
+                             (scalar_to_vector RC:$src2))))],
+      IIC_SSE_MOV_S_RR>;
=20
 // Loading from memory automatically zeroing upper bits.
 class sse12_move_rm<RegisterClass RC, X86MemOperand x86memop,
                     PatFrag mem_pat, string OpcodeStr> :
       SI<0x10, MRMSrcMem, (outs RC:$dst), (ins x86memop:$src),
          !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
-                        [(set RC:$dst, (mem_pat addr:$src))]>;
+                        [(set RC:$dst, (mem_pat addr:$src))],
+                        IIC_SSE_MOV_S_RM>;
=20
 // AVX
-def VMOVSSrr : sse12_move_rr<FR32, v4f32,
+def VMOVSSrr : sse12_move_rr<FR32, X86Movss, v4f32,
                 "movss\t{$src2, $src1, $dst|$dst, $src1, $src2}">, XS, VEX=
_4V,
                 VEX_LIG;
-def VMOVSDrr : sse12_move_rr<FR64, v2f64,
+def VMOVSDrr : sse12_move_rr<FR64, X86Movsd, v2f64,
                 "movsd\t{$src2, $src1, $dst|$dst, $src1, $src2}">, XD, VEX=
_4V,
                 VEX_LIG;
=20
@@ -352,11 +493,13 @@
 let isCodeGenOnly =3D 1 in {
   def VMOVSSrr_REV : SI<0x11, MRMDestReg, (outs VR128:$dst),
                         (ins VR128:$src1, FR32:$src2),
-                        "movss\t{$src2, $src1, $dst|$dst, $src1, $src2}", =
[]>,
+                        "movss\t{$src2, $src1, $dst|$dst, $src1, $src2}", =
[],
+                        IIC_SSE_MOV_S_RR>,
                         XS, VEX_4V, VEX_LIG;
   def VMOVSDrr_REV : SI<0x11, MRMDestReg, (outs VR128:$dst),
                         (ins VR128:$src1, FR64:$src2),
-                        "movsd\t{$src2, $src1, $dst|$dst, $src1, $src2}", =
[]>,
+                        "movsd\t{$src2, $src1, $dst|$dst, $src1, $src2}", =
[],
+                        IIC_SSE_MOV_S_RR>,
                         XD, VEX_4V, VEX_LIG;
 }
=20
@@ -370,26 +513,30 @@
=20
 def VMOVSSmr : SI<0x11, MRMDestMem, (outs), (ins f32mem:$dst, FR32:$src),
                   "movss\t{$src, $dst|$dst, $src}",
-                  [(store FR32:$src, addr:$dst)]>, XS, VEX, VEX_LIG;
+                  [(store FR32:$src, addr:$dst)], IIC_SSE_MOV_S_MR>,
+                  XS, VEX, VEX_LIG;
 def VMOVSDmr : SI<0x11, MRMDestMem, (outs), (ins f64mem:$dst, FR64:$src),
                   "movsd\t{$src, $dst|$dst, $src}",
-                  [(store FR64:$src, addr:$dst)]>, XD, VEX, VEX_LIG;
+                  [(store FR64:$src, addr:$dst)], IIC_SSE_MOV_S_MR>,
+                  XD, VEX, VEX_LIG;
=20
 // SSE1 & 2
 let Constraints =3D "$src1 =3D $dst" in {
-  def MOVSSrr : sse12_move_rr<FR32, v4f32,
+  def MOVSSrr : sse12_move_rr<FR32, X86Movss, v4f32,
                           "movss\t{$src2, $dst|$dst, $src2}">, XS;
-  def MOVSDrr : sse12_move_rr<FR64, v2f64,
+  def MOVSDrr : sse12_move_rr<FR64, X86Movsd, v2f64,
                           "movsd\t{$src2, $dst|$dst, $src2}">, XD;
=20
   // For the disassembler
   let isCodeGenOnly =3D 1 in {
     def MOVSSrr_REV : SI<0x11, MRMDestReg, (outs VR128:$dst),
                          (ins VR128:$src1, FR32:$src2),
-                         "movss\t{$src2, $dst|$dst, $src2}", []>, XS;
+                         "movss\t{$src2, $dst|$dst, $src2}", [],
+                         IIC_SSE_MOV_S_RR>, XS;
     def MOVSDrr_REV : SI<0x11, MRMDestReg, (outs VR128:$dst),
                          (ins VR128:$src1, FR64:$src2),
-                         "movsd\t{$src2, $dst|$dst, $src2}", []>, XD;
+                         "movsd\t{$src2, $dst|$dst, $src2}", [],
+                         IIC_SSE_MOV_S_RR>, XD;
   }
 }
=20
@@ -402,153 +549,14 @@
=20
 def MOVSSmr : SSI<0x11, MRMDestMem, (outs), (ins f32mem:$dst, FR32:$src),
                   "movss\t{$src, $dst|$dst, $src}",
-                  [(store FR32:$src, addr:$dst)]>;
+                  [(store FR32:$src, addr:$dst)], IIC_SSE_MOV_S_MR>;
 def MOVSDmr : SDI<0x11, MRMDestMem, (outs), (ins f64mem:$dst, FR64:$src),
                   "movsd\t{$src, $dst|$dst, $src}",
-                  [(store FR64:$src, addr:$dst)]>;
+                  [(store FR64:$src, addr:$dst)], IIC_SSE_MOV_S_MR>;
=20
 // Patterns
-let Predicates =3D [HasSSE1] in {
-  let AddedComplexity =3D 15 in {
-  // Extract the low 32-bit value from one vector and insert it into anoth=
er.
-  def : Pat<(v4f32 (movl VR128:$src1, VR128:$src2)),
-            (MOVSSrr (v4f32 VR128:$src1),
-                     (EXTRACT_SUBREG (v4f32 VR128:$src2), sub_ss))>;
-  def : Pat<(v4i32 (movl VR128:$src1, VR128:$src2)),
-            (MOVSSrr (v4i32 VR128:$src1),
-                     (EXTRACT_SUBREG (v4i32 VR128:$src2), sub_ss))>;
-
-  // Move scalar to XMM zero-extended, zeroing a VR128 then do a
-  // MOVSS to the lower bits.
-  def : Pat<(v4f32 (X86vzmovl (v4f32 (scalar_to_vector FR32:$src)))),
-            (MOVSSrr (v4f32 (V_SET0)), FR32:$src)>;
-  def : Pat<(v4f32 (X86vzmovl (v4f32 VR128:$src))),
-            (MOVSSrr (v4f32 (V_SET0)),
-                     (f32 (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss)))>;
-  def : Pat<(v4i32 (X86vzmovl (v4i32 VR128:$src))),
-            (MOVSSrr (v4i32 (V_SET0)),
-                     (EXTRACT_SUBREG (v4i32 VR128:$src), sub_ss))>;
-  }
-
-  let AddedComplexity =3D 20 in {
-  // MOVSSrm zeros the high parts of the register; represent this
-  // with SUBREG_TO_REG.
-  def : Pat<(v4f32 (X86vzmovl (v4f32 (scalar_to_vector (loadf32 addr:$src)=
)))),
-            (SUBREG_TO_REG (i32 0), (MOVSSrm addr:$src), sub_ss)>;
-  def : Pat<(v4f32 (scalar_to_vector (loadf32 addr:$src))),
-            (SUBREG_TO_REG (i32 0), (MOVSSrm addr:$src), sub_ss)>;
-  def : Pat<(v4f32 (X86vzmovl (loadv4f32 addr:$src))),
-            (SUBREG_TO_REG (i32 0), (MOVSSrm addr:$src), sub_ss)>;
-  }
-
-  // Extract and store.
-  def : Pat<(store (f32 (vector_extract (v4f32 VR128:$src), (iPTR 0))),
-                   addr:$dst),
-            (MOVSSmr addr:$dst,
-                     (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss))>;
-
-  // Shuffle with MOVSS
-  def : Pat<(v4f32 (X86Movss VR128:$src1, (scalar_to_vector FR32:$src2))),
-            (MOVSSrr VR128:$src1, FR32:$src2)>;
-  def : Pat<(v4i32 (X86Movss VR128:$src1, VR128:$src2)),
-            (MOVSSrr (v4i32 VR128:$src1),
-                     (EXTRACT_SUBREG (v4i32 VR128:$src2), sub_ss))>;
-  def : Pat<(v4f32 (X86Movss VR128:$src1, VR128:$src2)),
-            (MOVSSrr (v4f32 VR128:$src1),
-                     (EXTRACT_SUBREG (v4f32 VR128:$src2), sub_ss))>;
-}
-
-let Predicates =3D [HasSSE2] in {
-  let AddedComplexity =3D 15 in {
-  // Extract the low 64-bit value from one vector and insert it into anoth=
er.
-  def : Pat<(v2f64 (movl VR128:$src1, VR128:$src2)),
-            (MOVSDrr (v2f64 VR128:$src1),
-                     (EXTRACT_SUBREG (v2f64 VR128:$src2), sub_sd))>;
-  def : Pat<(v2i64 (movl VR128:$src1, VR128:$src2)),
-            (MOVSDrr (v2i64 VR128:$src1),
-                     (EXTRACT_SUBREG (v2i64 VR128:$src2), sub_sd))>;
-
-  // vector_shuffle v1, v2 <4, 5, 2, 3> using movsd
-  def : Pat<(v4f32 (movlp VR128:$src1, VR128:$src2)),
-            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG VR128:$src2, sub_sd))>;
-  def : Pat<(v4i32 (movlp VR128:$src1, VR128:$src2)),
-            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG VR128:$src2, sub_sd))>;
-
-  // Move scalar to XMM zero-extended, zeroing a VR128 then do a
-  // MOVSD to the lower bits.
-  def : Pat<(v2f64 (X86vzmovl (v2f64 (scalar_to_vector FR64:$src)))),
-            (MOVSDrr (v2f64 (V_SET0)), FR64:$src)>;
-  }
-
-  let AddedComplexity =3D 20 in {
-  // MOVSDrm zeros the high parts of the register; represent this
-  // with SUBREG_TO_REG.
-  def : Pat<(v2f64 (X86vzmovl (v2f64 (scalar_to_vector (loadf64 addr:$src)=
)))),
-            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
-  def : Pat<(v2f64 (scalar_to_vector (loadf64 addr:$src))),
-            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
-  def : Pat<(v2f64 (X86vzmovl (loadv2f64 addr:$src))),
-            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
-  def : Pat<(v2f64 (X86vzmovl (bc_v2f64 (loadv4f32 addr:$src)))),
-            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
-  def : Pat<(v2f64 (X86vzload addr:$src)),
-            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
-  }
-
-  // Extract and store.
-  def : Pat<(store (f64 (vector_extract (v2f64 VR128:$src), (iPTR 0))),
-                   addr:$dst),
-            (MOVSDmr addr:$dst,
-                     (EXTRACT_SUBREG (v2f64 VR128:$src), sub_sd))>;
-
-  // Shuffle with MOVSD
-  def : Pat<(v2f64 (X86Movsd VR128:$src1, (scalar_to_vector FR64:$src2))),
-            (MOVSDrr VR128:$src1, FR64:$src2)>;
-  def : Pat<(v2i64 (X86Movsd VR128:$src1, VR128:$src2)),
-            (MOVSDrr (v2i64 VR128:$src1),
-                     (EXTRACT_SUBREG (v2i64 VR128:$src2), sub_sd))>;
-  def : Pat<(v2f64 (X86Movsd VR128:$src1, VR128:$src2)),
-            (MOVSDrr (v2f64 VR128:$src1),
-                     (EXTRACT_SUBREG (v2f64 VR128:$src2), sub_sd))>;
-  def : Pat<(v4f32 (X86Movsd VR128:$src1, VR128:$src2)),
-            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4f32 VR128:$src2),sub_=
sd))>;
-  def : Pat<(v4i32 (X86Movsd VR128:$src1, VR128:$src2)),
-            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4i32 VR128:$src2),sub_=
sd))>;
-
-  // FIXME: Instead of a X86Movlps there should be a X86Movsd here, the pr=
oblem
-  // is during lowering, where it's not possible to recognize the fold cau=
se
-  // it has two uses through a bitcast. One use disappears at isel time an=
d the
-  // fold opportunity reappears.
-  def : Pat<(v4f32 (X86Movlps VR128:$src1, VR128:$src2)),
-            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4f32 VR128:$src2),sub_=
sd))>;
-  def : Pat<(v4i32 (X86Movlps VR128:$src1, VR128:$src2)),
-            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4i32 VR128:$src2),sub_=
sd))>;
-}
-
 let Predicates =3D [HasAVX] in {
   let AddedComplexity =3D 15 in {
-  // Extract the low 32-bit value from one vector and insert it into anoth=
er.
-  def : Pat<(v4f32 (movl VR128:$src1, VR128:$src2)),
-            (VMOVSSrr (v4f32 VR128:$src1),
-                      (EXTRACT_SUBREG (v4f32 VR128:$src2), sub_ss))>;
-  def : Pat<(v4i32 (movl VR128:$src1, VR128:$src2)),
-            (VMOVSSrr (v4i32 VR128:$src1),
-                      (EXTRACT_SUBREG (v4i32 VR128:$src2), sub_ss))>;
-
-  // Extract the low 64-bit value from one vector and insert it into anoth=
er.
-  def : Pat<(v2f64 (movl VR128:$src1, VR128:$src2)),
-            (VMOVSDrr (v2f64 VR128:$src1),
-                      (EXTRACT_SUBREG (v2f64 VR128:$src2), sub_sd))>;
-  def : Pat<(v2i64 (movl VR128:$src1, VR128:$src2)),
-            (VMOVSDrr (v2i64 VR128:$src1),
-                      (EXTRACT_SUBREG (v2i64 VR128:$src2), sub_sd))>;
-
-  // vector_shuffle v1, v2 <4, 5, 2, 3> using movsd
-  def : Pat<(v4f32 (movlp VR128:$src1, VR128:$src2)),
-            (VMOVSDrr VR128:$src1, (EXTRACT_SUBREG VR128:$src2, sub_sd))>;
-  def : Pat<(v4i32 (movlp VR128:$src1, VR128:$src2)),
-            (VMOVSDrr VR128:$src1, (EXTRACT_SUBREG VR128:$src2, sub_sd))>;
-
   // Move scalar to XMM zero-extended, zeroing a VR128 then do a
   // MOVS{S,D} to the lower bits.
   def : Pat<(v4f32 (X86vzmovl (v4f32 (scalar_to_vector FR32:$src)))),
@@ -561,6 +569,16 @@
                       (EXTRACT_SUBREG (v4i32 VR128:$src), sub_ss))>;
   def : Pat<(v2f64 (X86vzmovl (v2f64 (scalar_to_vector FR64:$src)))),
             (VMOVSDrr (v2f64 (V_SET0)), FR64:$src)>;
+
+  // Move low f32 and clear high bits.
+  def : Pat<(v8f32 (X86vzmovl (v8f32 VR256:$src))),
+            (SUBREG_TO_REG (i32 0),
+              (VMOVSSrr (v4f32 (V_SET0)),
+                        (EXTRACT_SUBREG (v8f32 VR256:$src), sub_ss)), sub_=
xmm)>;
+  def : Pat<(v8i32 (X86vzmovl (v8i32 VR256:$src))),
+            (SUBREG_TO_REG (i32 0),
+              (VMOVSSrr (v4i32 (V_SET0)),
+                        (EXTRACT_SUBREG (v8i32 VR256:$src), sub_ss)), sub_=
xmm)>;
   }
=20
   let AddedComplexity =3D 20 in {
@@ -588,6 +606,9 @@
=20
   // Represent the same patterns above but in the form they appear for
   // 256-bit types
+  def : Pat<(v8i32 (X86vzmovl (insert_subvector undef,
+                   (v4i32 (scalar_to_vector (loadi32 addr:$src))), (i32 0)=
))),
+            (SUBREG_TO_REG (i32 0), (VMOVSSrm addr:$src), sub_ss)>;
   def : Pat<(v8f32 (X86vzmovl (insert_subvector undef,
                    (v4f32 (scalar_to_vector (loadf32 addr:$src))), (i32 0)=
))),
             (SUBREG_TO_REG (i32 0), (VMOVSSrm addr:$src), sub_ss)>;
@@ -605,6 +626,20 @@
             (SUBREG_TO_REG (i64 0),
                            (v2f64 (VMOVSDrr (v2f64 (V_SET0)), FR64:$src)),
                            sub_xmm)>;
+  def : Pat<(v4i64 (X86vzmovl (insert_subvector undef,
+                   (v2i64 (scalar_to_vector (loadi64 addr:$src))), (i32 0)=
))),
+            (SUBREG_TO_REG (i64 0), (VMOVSDrm addr:$src), sub_sd)>;
+
+  // Move low f64 and clear high bits.
+  def : Pat<(v4f64 (X86vzmovl (v4f64 VR256:$src))),
+            (SUBREG_TO_REG (i32 0),
+              (VMOVSDrr (v2f64 (V_SET0)),
+                        (EXTRACT_SUBREG (v4f64 VR256:$src), sub_sd)), sub_=
xmm)>;
+
+  def : Pat<(v4i64 (X86vzmovl (v4i64 VR256:$src))),
+            (SUBREG_TO_REG (i32 0),
+              (VMOVSDrr (v2i64 (V_SET0)),
+                        (EXTRACT_SUBREG (v4i64 VR256:$src), sub_sd)), sub_=
xmm)>;
=20
   // Extract and store.
   def : Pat<(store (f32 (vector_extract (v4f32 VR128:$src), (iPTR 0))),
@@ -617,8 +652,6 @@
                      (EXTRACT_SUBREG (v2f64 VR128:$src), sub_sd))>;
=20
   // Shuffle with VMOVSS
-  def : Pat<(v4f32 (X86Movss VR128:$src1, (scalar_to_vector FR32:$src2))),
-            (VMOVSSrr VR128:$src1, FR32:$src2)>;
   def : Pat<(v4i32 (X86Movss VR128:$src1, VR128:$src2)),
             (VMOVSSrr (v4i32 VR128:$src1),
                       (EXTRACT_SUBREG (v4i32 VR128:$src2), sub_ss))>;
@@ -626,9 +659,17 @@
             (VMOVSSrr (v4f32 VR128:$src1),
                       (EXTRACT_SUBREG (v4f32 VR128:$src2), sub_ss))>;
=20
+  // 256-bit variants
+  def : Pat<(v8i32 (X86Movss VR256:$src1, VR256:$src2)),
+            (SUBREG_TO_REG (i32 0),
+                (VMOVSSrr (EXTRACT_SUBREG (v8i32 VR256:$src1), sub_ss),
+                          (EXTRACT_SUBREG (v8i32 VR256:$src2), sub_ss)), s=
ub_xmm)>;
+  def : Pat<(v8f32 (X86Movss VR256:$src1, VR256:$src2)),
+            (SUBREG_TO_REG (i32 0),
+                (VMOVSSrr (EXTRACT_SUBREG (v8f32 VR256:$src1), sub_ss),
+                          (EXTRACT_SUBREG (v8f32 VR256:$src2), sub_ss)), s=
ub_xmm)>;
+
   // Shuffle with VMOVSD
-  def : Pat<(v2f64 (X86Movsd VR128:$src1, (scalar_to_vector FR64:$src2))),
-            (VMOVSDrr VR128:$src1, FR64:$src2)>;
   def : Pat<(v2i64 (X86Movsd VR128:$src1, VR128:$src2)),
             (VMOVSDrr (v2i64 VR128:$src1),
                      (EXTRACT_SUBREG (v2i64 VR128:$src2), sub_sd))>;
@@ -642,10 +683,27 @@
             (VMOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4i32 VR128:$src2),
                                                    sub_sd))>;
=20
+  // 256-bit variants
+  def : Pat<(v4i64 (X86Movsd VR256:$src1, VR256:$src2)),
+            (SUBREG_TO_REG (i32 0),
+                (VMOVSDrr (EXTRACT_SUBREG (v4i64 VR256:$src1), sub_sd),
+                          (EXTRACT_SUBREG (v4i64 VR256:$src2), sub_sd)), s=
ub_xmm)>;
+  def : Pat<(v4f64 (X86Movsd VR256:$src1, VR256:$src2)),
+            (SUBREG_TO_REG (i32 0),
+                (VMOVSDrr (EXTRACT_SUBREG (v4f64 VR256:$src1), sub_sd),
+                          (EXTRACT_SUBREG (v4f64 VR256:$src2), sub_sd)), s=
ub_xmm)>;
+
+
   // FIXME: Instead of a X86Movlps there should be a X86Movsd here, the pr=
oblem
   // is during lowering, where it's not possible to recognize the fold cau=
se
   // it has two uses through a bitcast. One use disappears at isel time an=
d the
   // fold opportunity reappears.
+  def : Pat<(v2f64 (X86Movlpd VR128:$src1, VR128:$src2)),
+            (VMOVSDrr VR128:$src1, (EXTRACT_SUBREG (v2f64 VR128:$src2),
+                                                   sub_sd))>;
+  def : Pat<(v2i64 (X86Movlpd VR128:$src1, VR128:$src2)),
+            (VMOVSDrr VR128:$src1, (EXTRACT_SUBREG (v2i64 VR128:$src2),
+                                                   sub_sd))>;
   def : Pat<(v4f32 (X86Movlps VR128:$src1, VR128:$src2)),
             (VMOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4f32 VR128:$src2),
                                                    sub_sd))>;
@@ -654,6 +712,101 @@
                                                    sub_sd))>;
 }
=20
+let Predicates =3D [HasSSE1] in {
+  let AddedComplexity =3D 15 in {
+  // Move scalar to XMM zero-extended, zeroing a VR128 then do a
+  // MOVSS to the lower bits.
+  def : Pat<(v4f32 (X86vzmovl (v4f32 (scalar_to_vector FR32:$src)))),
+            (MOVSSrr (v4f32 (V_SET0)), FR32:$src)>;
+  def : Pat<(v4f32 (X86vzmovl (v4f32 VR128:$src))),
+            (MOVSSrr (v4f32 (V_SET0)),
+                     (f32 (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss)))>;
+  def : Pat<(v4i32 (X86vzmovl (v4i32 VR128:$src))),
+            (MOVSSrr (v4i32 (V_SET0)),
+                     (EXTRACT_SUBREG (v4i32 VR128:$src), sub_ss))>;
+  }
+
+  let AddedComplexity =3D 20 in {
+  // MOVSSrm zeros the high parts of the register; represent this
+  // with SUBREG_TO_REG.
+  def : Pat<(v4f32 (X86vzmovl (v4f32 (scalar_to_vector (loadf32 addr:$src)=
)))),
+            (SUBREG_TO_REG (i32 0), (MOVSSrm addr:$src), sub_ss)>;
+  def : Pat<(v4f32 (scalar_to_vector (loadf32 addr:$src))),
+            (SUBREG_TO_REG (i32 0), (MOVSSrm addr:$src), sub_ss)>;
+  def : Pat<(v4f32 (X86vzmovl (loadv4f32 addr:$src))),
+            (SUBREG_TO_REG (i32 0), (MOVSSrm addr:$src), sub_ss)>;
+  }
+
+  // Extract and store.
+  def : Pat<(store (f32 (vector_extract (v4f32 VR128:$src), (iPTR 0))),
+                   addr:$dst),
+            (MOVSSmr addr:$dst,
+                     (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss))>;
+
+  // Shuffle with MOVSS
+  def : Pat<(v4i32 (X86Movss VR128:$src1, VR128:$src2)),
+            (MOVSSrr (v4i32 VR128:$src1),
+                     (EXTRACT_SUBREG (v4i32 VR128:$src2), sub_ss))>;
+  def : Pat<(v4f32 (X86Movss VR128:$src1, VR128:$src2)),
+            (MOVSSrr (v4f32 VR128:$src1),
+                     (EXTRACT_SUBREG (v4f32 VR128:$src2), sub_ss))>;
+}
+
+let Predicates =3D [HasSSE2] in {
+  let AddedComplexity =3D 15 in {
+  // Move scalar to XMM zero-extended, zeroing a VR128 then do a
+  // MOVSD to the lower bits.
+  def : Pat<(v2f64 (X86vzmovl (v2f64 (scalar_to_vector FR64:$src)))),
+            (MOVSDrr (v2f64 (V_SET0)), FR64:$src)>;
+  }
+
+  let AddedComplexity =3D 20 in {
+  // MOVSDrm zeros the high parts of the register; represent this
+  // with SUBREG_TO_REG.
+  def : Pat<(v2f64 (X86vzmovl (v2f64 (scalar_to_vector (loadf64 addr:$src)=
)))),
+            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
+  def : Pat<(v2f64 (scalar_to_vector (loadf64 addr:$src))),
+            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
+  def : Pat<(v2f64 (X86vzmovl (loadv2f64 addr:$src))),
+            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
+  def : Pat<(v2f64 (X86vzmovl (bc_v2f64 (loadv4f32 addr:$src)))),
+            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
+  def : Pat<(v2f64 (X86vzload addr:$src)),
+            (SUBREG_TO_REG (i64 0), (MOVSDrm addr:$src), sub_sd)>;
+  }
+
+  // Extract and store.
+  def : Pat<(store (f64 (vector_extract (v2f64 VR128:$src), (iPTR 0))),
+                   addr:$dst),
+            (MOVSDmr addr:$dst,
+                     (EXTRACT_SUBREG (v2f64 VR128:$src), sub_sd))>;
+
+  // Shuffle with MOVSD
+  def : Pat<(v2i64 (X86Movsd VR128:$src1, VR128:$src2)),
+            (MOVSDrr (v2i64 VR128:$src1),
+                     (EXTRACT_SUBREG (v2i64 VR128:$src2), sub_sd))>;
+  def : Pat<(v2f64 (X86Movsd VR128:$src1, VR128:$src2)),
+            (MOVSDrr (v2f64 VR128:$src1),
+                     (EXTRACT_SUBREG (v2f64 VR128:$src2), sub_sd))>;
+  def : Pat<(v4f32 (X86Movsd VR128:$src1, VR128:$src2)),
+            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4f32 VR128:$src2),sub_=
sd))>;
+  def : Pat<(v4i32 (X86Movsd VR128:$src1, VR128:$src2)),
+            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4i32 VR128:$src2),sub_=
sd))>;
+
+  // FIXME: Instead of a X86Movlps there should be a X86Movsd here, the pr=
oblem
+  // is during lowering, where it's not possible to recognize the fold cau=
se
+  // it has two uses through a bitcast. One use disappears at isel time an=
d the
+  // fold opportunity reappears.
+  def : Pat<(v2f64 (X86Movlpd VR128:$src1, VR128:$src2)),
+            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v2f64 VR128:$src2),sub_=
sd))>;
+  def : Pat<(v2i64 (X86Movlpd VR128:$src1, VR128:$src2)),
+            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v2i64 VR128:$src2),sub_=
sd))>;
+  def : Pat<(v4f32 (X86Movlps VR128:$src1, VR128:$src2)),
+            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4f32 VR128:$src2),sub_=
sd))>;
+  def : Pat<(v4i32 (X86Movlps VR128:$src1, VR128:$src2)),
+            (MOVSDrr VR128:$src1, (EXTRACT_SUBREG (v4i32 VR128:$src2),sub_=
sd))>;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE 1 & 2 - Move Aligned/Unaligned FP Instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -661,126 +814,176 @@
 multiclass sse12_mov_packed<bits<8> opc, RegisterClass RC,
                             X86MemOperand x86memop, PatFrag ld_frag,
                             string asm, Domain d,
+                            OpndItins itins,
                             bit IsReMaterializable =3D 1> {
 let neverHasSideEffects =3D 1 in
   def rr : PI<opc, MRMSrcReg, (outs RC:$dst), (ins RC:$src),
-              !strconcat(asm, "\t{$src, $dst|$dst, $src}"), [], d>;
+              !strconcat(asm, "\t{$src, $dst|$dst, $src}"), [], itins.rr, =
d>;
 let canFoldAsLoad =3D 1, isReMaterializable =3D IsReMaterializable in
   def rm : PI<opc, MRMSrcMem, (outs RC:$dst), (ins x86memop:$src),
               !strconcat(asm, "\t{$src, $dst|$dst, $src}"),
-                   [(set RC:$dst, (ld_frag addr:$src))], d>;
+                   [(set RC:$dst, (ld_frag addr:$src))], itins.rm, d>;
 }
=20
 defm VMOVAPS : sse12_mov_packed<0x28, VR128, f128mem, alignedloadv4f32,
-                              "movaps", SSEPackedSingle>, TB, VEX;
+                              "movaps", SSEPackedSingle, SSE_MOVA_ITINS>,
+                              TB, VEX;
 defm VMOVAPD : sse12_mov_packed<0x28, VR128, f128mem, alignedloadv2f64,
-                              "movapd", SSEPackedDouble>, TB, OpSize, VEX;
+                              "movapd", SSEPackedDouble, SSE_MOVA_ITINS>,
+                              TB, OpSize, VEX;
 defm VMOVUPS : sse12_mov_packed<0x10, VR128, f128mem, loadv4f32,
-                              "movups", SSEPackedSingle>, TB, VEX;
+                              "movups", SSEPackedSingle, SSE_MOVU_ITINS>,
+                              TB, VEX;
 defm VMOVUPD : sse12_mov_packed<0x10, VR128, f128mem, loadv2f64,
-                              "movupd", SSEPackedDouble, 0>, TB, OpSize, V=
EX;
+                              "movupd", SSEPackedDouble, SSE_MOVU_ITINS, 0=
>,
+                              TB, OpSize, VEX;
=20
 defm VMOVAPSY : sse12_mov_packed<0x28, VR256, f256mem, alignedloadv8f32,
-                              "movaps", SSEPackedSingle>, TB, VEX;
+                              "movaps", SSEPackedSingle, SSE_MOVA_ITINS>,
+                              TB, VEX;
 defm VMOVAPDY : sse12_mov_packed<0x28, VR256, f256mem, alignedloadv4f64,
-                              "movapd", SSEPackedDouble>, TB, OpSize, VEX;
+                              "movapd", SSEPackedDouble, SSE_MOVA_ITINS>,
+                              TB, OpSize, VEX;
 defm VMOVUPSY : sse12_mov_packed<0x10, VR256, f256mem, loadv8f32,
-                              "movups", SSEPackedSingle>, TB, VEX;
+                              "movups", SSEPackedSingle, SSE_MOVU_ITINS>,
+                              TB, VEX;
 defm VMOVUPDY : sse12_mov_packed<0x10, VR256, f256mem, loadv4f64,
-                              "movupd", SSEPackedDouble, 0>, TB, OpSize, V=
EX;
+                              "movupd", SSEPackedDouble, SSE_MOVU_ITINS, 0=
>,
+                              TB, OpSize, VEX;
 defm MOVAPS : sse12_mov_packed<0x28, VR128, f128mem, alignedloadv4f32,
-                              "movaps", SSEPackedSingle>, TB;
+                              "movaps", SSEPackedSingle, SSE_MOVA_ITINS>,
+                              TB;
 defm MOVAPD : sse12_mov_packed<0x28, VR128, f128mem, alignedloadv2f64,
-                              "movapd", SSEPackedDouble>, TB, OpSize;
+                              "movapd", SSEPackedDouble, SSE_MOVA_ITINS>,
+                              TB, OpSize;
 defm MOVUPS : sse12_mov_packed<0x10, VR128, f128mem, loadv4f32,
-                              "movups", SSEPackedSingle>, TB;
+                              "movups", SSEPackedSingle, SSE_MOVU_ITINS>,
+                              TB;
 defm MOVUPD : sse12_mov_packed<0x10, VR128, f128mem, loadv2f64,
-                              "movupd", SSEPackedDouble, 0>, TB, OpSize;
+                              "movupd", SSEPackedDouble, SSE_MOVU_ITINS, 0=
>,
+                              TB, OpSize;
=20
 def VMOVAPSmr : VPSI<0x29, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$s=
rc),
                    "movaps\t{$src, $dst|$dst, $src}",
-                   [(alignedstore (v4f32 VR128:$src), addr:$dst)]>, VEX;
+                   [(alignedstore (v4f32 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVA_P_MR>, VEX;
 def VMOVAPDmr : VPDI<0x29, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$s=
rc),
                    "movapd\t{$src, $dst|$dst, $src}",
-                   [(alignedstore (v2f64 VR128:$src), addr:$dst)]>, VEX;
+                   [(alignedstore (v2f64 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVA_P_MR>, VEX;
 def VMOVUPSmr : VPSI<0x11, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$s=
rc),
                    "movups\t{$src, $dst|$dst, $src}",
-                   [(store (v4f32 VR128:$src), addr:$dst)]>, VEX;
+                   [(store (v4f32 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVU_P_MR>, VEX;
 def VMOVUPDmr : VPDI<0x11, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$s=
rc),
                    "movupd\t{$src, $dst|$dst, $src}",
-                   [(store (v2f64 VR128:$src), addr:$dst)]>, VEX;
+                   [(store (v2f64 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVU_P_MR>, VEX;
 def VMOVAPSYmr : VPSI<0x29, MRMDestMem, (outs), (ins f256mem:$dst, VR256:$=
src),
                    "movaps\t{$src, $dst|$dst, $src}",
-                   [(alignedstore256 (v8f32 VR256:$src), addr:$dst)]>, VEX;
+                   [(alignedstore256 (v8f32 VR256:$src), addr:$dst)],
+                   IIC_SSE_MOVA_P_MR>, VEX;
 def VMOVAPDYmr : VPDI<0x29, MRMDestMem, (outs), (ins f256mem:$dst, VR256:$=
src),
                    "movapd\t{$src, $dst|$dst, $src}",
-                   [(alignedstore256 (v4f64 VR256:$src), addr:$dst)]>, VEX;
+                   [(alignedstore256 (v4f64 VR256:$src), addr:$dst)],
+                   IIC_SSE_MOVA_P_MR>, VEX;
 def VMOVUPSYmr : VPSI<0x11, MRMDestMem, (outs), (ins f256mem:$dst, VR256:$=
src),
                    "movups\t{$src, $dst|$dst, $src}",
-                   [(store (v8f32 VR256:$src), addr:$dst)]>, VEX;
+                   [(store (v8f32 VR256:$src), addr:$dst)],
+                   IIC_SSE_MOVU_P_MR>, VEX;
 def VMOVUPDYmr : VPDI<0x11, MRMDestMem, (outs), (ins f256mem:$dst, VR256:$=
src),
                    "movupd\t{$src, $dst|$dst, $src}",
-                   [(store (v4f64 VR256:$src), addr:$dst)]>, VEX;
+                   [(store (v4f64 VR256:$src), addr:$dst)],
+                   IIC_SSE_MOVU_P_MR>, VEX;
=20
 // For disassembler
 let isCodeGenOnly =3D 1 in {
   def VMOVAPSrr_REV : VPSI<0x29, MRMDestReg, (outs VR128:$dst),
                           (ins VR128:$src),
-                          "movaps\t{$src, $dst|$dst, $src}", []>, VEX;
+                          "movaps\t{$src, $dst|$dst, $src}", [],
+                          IIC_SSE_MOVA_P_RR>, VEX;
   def VMOVAPDrr_REV : VPDI<0x29, MRMDestReg, (outs VR128:$dst),
                            (ins VR128:$src),
-                           "movapd\t{$src, $dst|$dst, $src}", []>, VEX;
+                           "movapd\t{$src, $dst|$dst, $src}", [],
+                           IIC_SSE_MOVA_P_RR>, VEX;
   def VMOVUPSrr_REV : VPSI<0x11, MRMDestReg, (outs VR128:$dst),
                            (ins VR128:$src),
-                           "movups\t{$src, $dst|$dst, $src}", []>, VEX;
+                           "movups\t{$src, $dst|$dst, $src}", [],
+                           IIC_SSE_MOVU_P_RR>, VEX;
   def VMOVUPDrr_REV : VPDI<0x11, MRMDestReg, (outs VR128:$dst),
                            (ins VR128:$src),
-                           "movupd\t{$src, $dst|$dst, $src}", []>, VEX;
+                           "movupd\t{$src, $dst|$dst, $src}", [],
+                           IIC_SSE_MOVU_P_RR>, VEX;
   def VMOVAPSYrr_REV : VPSI<0x29, MRMDestReg, (outs VR256:$dst),
                             (ins VR256:$src),
-                            "movaps\t{$src, $dst|$dst, $src}", []>, VEX;
+                            "movaps\t{$src, $dst|$dst, $src}", [],
+                            IIC_SSE_MOVA_P_RR>, VEX;
   def VMOVAPDYrr_REV : VPDI<0x29, MRMDestReg, (outs VR256:$dst),
                             (ins VR256:$src),
-                            "movapd\t{$src, $dst|$dst, $src}", []>, VEX;
+                            "movapd\t{$src, $dst|$dst, $src}", [],
+                            IIC_SSE_MOVA_P_RR>, VEX;
   def VMOVUPSYrr_REV : VPSI<0x11, MRMDestReg, (outs VR256:$dst),
                             (ins VR256:$src),
-                            "movups\t{$src, $dst|$dst, $src}", []>, VEX;
+                            "movups\t{$src, $dst|$dst, $src}", [],
+                            IIC_SSE_MOVU_P_RR>, VEX;
   def VMOVUPDYrr_REV : VPDI<0x11, MRMDestReg, (outs VR256:$dst),
                             (ins VR256:$src),
-                            "movupd\t{$src, $dst|$dst, $src}", []>, VEX;
-}
-
-def : Pat<(int_x86_avx_loadu_ps_256 addr:$src), (VMOVUPSYrm addr:$src)>;
+                            "movupd\t{$src, $dst|$dst, $src}", [],
+                            IIC_SSE_MOVU_P_RR>, VEX;
+}
+
+let Predicates =3D [HasAVX] in {
+def : Pat<(v8i32 (X86vzmovl
+                        (insert_subvector undef, (v4i32 VR128:$src), (i32 =
0)))),
+          (SUBREG_TO_REG (i32 0), (VMOVAPSrr VR128:$src), sub_xmm)>;
+def : Pat<(v4i64 (X86vzmovl
+                        (insert_subvector undef, (v2i64 VR128:$src), (i32 =
0)))),
+          (SUBREG_TO_REG (i32 0), (VMOVAPSrr VR128:$src), sub_xmm)>;
+def : Pat<(v8f32 (X86vzmovl
+                        (insert_subvector undef, (v4f32 VR128:$src), (i32 =
0)))),
+          (SUBREG_TO_REG (i32 0), (VMOVAPSrr VR128:$src), sub_xmm)>;
+def : Pat<(v4f64 (X86vzmovl
+                        (insert_subvector undef, (v2f64 VR128:$src), (i32 =
0)))),
+          (SUBREG_TO_REG (i32 0), (VMOVAPSrr VR128:$src), sub_xmm)>;
+}
+
+
 def : Pat<(int_x86_avx_storeu_ps_256 addr:$dst, VR256:$src),
           (VMOVUPSYmr addr:$dst, VR256:$src)>;
-
-def : Pat<(int_x86_avx_loadu_pd_256 addr:$src), (VMOVUPDYrm addr:$src)>;
 def : Pat<(int_x86_avx_storeu_pd_256 addr:$dst, VR256:$src),
           (VMOVUPDYmr addr:$dst, VR256:$src)>;
=20
 def MOVAPSmr : PSI<0x29, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$src=
),
                    "movaps\t{$src, $dst|$dst, $src}",
-                   [(alignedstore (v4f32 VR128:$src), addr:$dst)]>;
+                   [(alignedstore (v4f32 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVA_P_MR>;
 def MOVAPDmr : PDI<0x29, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$src=
),
                    "movapd\t{$src, $dst|$dst, $src}",
-                   [(alignedstore (v2f64 VR128:$src), addr:$dst)]>;
+                   [(alignedstore (v2f64 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVA_P_MR>;
 def MOVUPSmr : PSI<0x11, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$src=
),
                    "movups\t{$src, $dst|$dst, $src}",
-                   [(store (v4f32 VR128:$src), addr:$dst)]>;
+                   [(store (v4f32 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVU_P_MR>;
 def MOVUPDmr : PDI<0x11, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$src=
),
                    "movupd\t{$src, $dst|$dst, $src}",
-                   [(store (v2f64 VR128:$src), addr:$dst)]>;
+                   [(store (v2f64 VR128:$src), addr:$dst)],
+                   IIC_SSE_MOVU_P_MR>;
=20
 // For disassembler
 let isCodeGenOnly =3D 1 in {
   def MOVAPSrr_REV : PSI<0x29, MRMDestReg, (outs VR128:$dst), (ins VR128:$=
src),
-                         "movaps\t{$src, $dst|$dst, $src}", []>;
+                         "movaps\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_MOVA_P_RR>;
   def MOVAPDrr_REV : PDI<0x29, MRMDestReg, (outs VR128:$dst), (ins VR128:$=
src),
-                         "movapd\t{$src, $dst|$dst, $src}", []>;
+                         "movapd\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_MOVA_P_RR>;
   def MOVUPSrr_REV : PSI<0x11, MRMDestReg, (outs VR128:$dst), (ins VR128:$=
src),
-                         "movups\t{$src, $dst|$dst, $src}", []>;
+                         "movups\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_MOVU_P_RR>;
   def MOVUPDrr_REV : PDI<0x11, MRMDestReg, (outs VR128:$dst), (ins VR128:$=
src),
-                         "movupd\t{$src, $dst|$dst, $src}", []>;
+                         "movupd\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_MOVU_P_RR>;
 }
=20
 let Predicates =3D [HasAVX] in {
@@ -797,44 +1000,9 @@
   def : Pat<(int_x86_sse2_storeu_pd addr:$dst, VR128:$src),
             (MOVUPDmr addr:$dst, VR128:$src)>;
=20
-// Use movaps / movups for SSE integer load / store (one byte shorter).
-// The instructions selected below are then converted to MOVDQA/MOVDQU
-// during the SSE domain pass.
-let Predicates =3D [HasSSE1] in {
-  def : Pat<(alignedloadv4i32 addr:$src),
-            (MOVAPSrm addr:$src)>;
-  def : Pat<(loadv4i32 addr:$src),
-            (MOVUPSrm addr:$src)>;
-  def : Pat<(alignedloadv2i64 addr:$src),
-            (MOVAPSrm addr:$src)>;
-  def : Pat<(loadv2i64 addr:$src),
-            (MOVUPSrm addr:$src)>;
-
-  def : Pat<(alignedstore (v2i64 VR128:$src), addr:$dst),
-            (MOVAPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(alignedstore (v4i32 VR128:$src), addr:$dst),
-            (MOVAPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(alignedstore (v8i16 VR128:$src), addr:$dst),
-            (MOVAPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(alignedstore (v16i8 VR128:$src), addr:$dst),
-            (MOVAPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(store (v2i64 VR128:$src), addr:$dst),
-            (MOVUPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(store (v4i32 VR128:$src), addr:$dst),
-            (MOVUPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(store (v8i16 VR128:$src), addr:$dst),
-            (MOVUPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(store (v16i8 VR128:$src), addr:$dst),
-            (MOVUPSmr addr:$dst, VR128:$src)>;
-}
-
 // Use vmovaps/vmovups for AVX integer load/store.
 let Predicates =3D [HasAVX] in {
   // 128-bit load/store
-  def : Pat<(alignedloadv4i32 addr:$src),
-            (VMOVAPSrm addr:$src)>;
-  def : Pat<(loadv4i32 addr:$src),
-            (VMOVUPSrm addr:$src)>;
   def : Pat<(alignedloadv2i64 addr:$src),
             (VMOVAPSrm addr:$src)>;
   def : Pat<(loadv2i64 addr:$src),
@@ -862,10 +1030,6 @@
             (VMOVAPSYrm addr:$src)>;
   def : Pat<(loadv4i64 addr:$src),
             (VMOVUPSYrm addr:$src)>;
-  def : Pat<(alignedloadv8i32 addr:$src),
-            (VMOVAPSYrm addr:$src)>;
-  def : Pat<(loadv8i32 addr:$src),
-            (VMOVUPSYrm addr:$src)>;
   def : Pat<(alignedstore256 (v4i64 VR256:$src), addr:$dst),
             (VMOVAPSYmr addr:$dst, VR256:$src)>;
   def : Pat<(alignedstore256 (v8i32 VR256:$src), addr:$dst),
@@ -884,36 +1048,71 @@
             (VMOVUPSYmr addr:$dst, VR256:$src)>;
 }
=20
+// Use movaps / movups for SSE integer load / store (one byte shorter).
+// The instructions selected below are then converted to MOVDQA/MOVDQU
+// during the SSE domain pass.
+let Predicates =3D [HasSSE1] in {
+  def : Pat<(alignedloadv2i64 addr:$src),
+            (MOVAPSrm addr:$src)>;
+  def : Pat<(loadv2i64 addr:$src),
+            (MOVUPSrm addr:$src)>;
+
+  def : Pat<(alignedstore (v2i64 VR128:$src), addr:$dst),
+            (MOVAPSmr addr:$dst, VR128:$src)>;
+  def : Pat<(alignedstore (v4i32 VR128:$src), addr:$dst),
+            (MOVAPSmr addr:$dst, VR128:$src)>;
+  def : Pat<(alignedstore (v8i16 VR128:$src), addr:$dst),
+            (MOVAPSmr addr:$dst, VR128:$src)>;
+  def : Pat<(alignedstore (v16i8 VR128:$src), addr:$dst),
+            (MOVAPSmr addr:$dst, VR128:$src)>;
+  def : Pat<(store (v2i64 VR128:$src), addr:$dst),
+            (MOVUPSmr addr:$dst, VR128:$src)>;
+  def : Pat<(store (v4i32 VR128:$src), addr:$dst),
+            (MOVUPSmr addr:$dst, VR128:$src)>;
+  def : Pat<(store (v8i16 VR128:$src), addr:$dst),
+            (MOVUPSmr addr:$dst, VR128:$src)>;
+  def : Pat<(store (v16i8 VR128:$src), addr:$dst),
+            (MOVUPSmr addr:$dst, VR128:$src)>;
+}
+
 // Alias instruction to do FR32 or FR64 reg-to-reg copy using movaps. Upper
 // bits are disregarded. FIXME: Set encoding to pseudo!
 let neverHasSideEffects =3D 1 in {
+def FsVMOVAPSrr : VPSI<0x28, MRMSrcReg, (outs FR32:$dst), (ins FR32:$src),
+                       "movaps\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_MOVA_P_RR>, VEX;
+def FsVMOVAPDrr : VPDI<0x28, MRMSrcReg, (outs FR64:$dst), (ins FR64:$src),
+                       "movapd\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_MOVA_P_RR>, VEX;
 def FsMOVAPSrr : PSI<0x28, MRMSrcReg, (outs FR32:$dst), (ins FR32:$src),
-                     "movaps\t{$src, $dst|$dst, $src}", []>;
+                     "movaps\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_MOVA_P_RR>;
 def FsMOVAPDrr : PDI<0x28, MRMSrcReg, (outs FR64:$dst), (ins FR64:$src),
-                     "movapd\t{$src, $dst|$dst, $src}", []>;
-def FsVMOVAPSrr : VPSI<0x28, MRMSrcReg, (outs FR32:$dst), (ins FR32:$src),
-                       "movaps\t{$src, $dst|$dst, $src}", []>, VEX;
-def FsVMOVAPDrr : VPDI<0x28, MRMSrcReg, (outs FR64:$dst), (ins FR64:$src),
-                       "movapd\t{$src, $dst|$dst, $src}", []>, VEX;
+                     "movapd\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_MOVA_P_RR>;
 }
=20
 // Alias instruction to load FR32 or FR64 from f128mem using movaps. Upper
 // bits are disregarded. FIXME: Set encoding to pseudo!
 let canFoldAsLoad =3D 1, isReMaterializable =3D 1 in {
-def FsMOVAPSrm : PSI<0x28, MRMSrcMem, (outs FR32:$dst), (ins f128mem:$src),
-                     "movaps\t{$src, $dst|$dst, $src}",
-                     [(set FR32:$dst, (alignedloadfsf32 addr:$src))]>;
-def FsMOVAPDrm : PDI<0x28, MRMSrcMem, (outs FR64:$dst), (ins f128mem:$src),
-                     "movapd\t{$src, $dst|$dst, $src}",
-                     [(set FR64:$dst, (alignedloadfsf64 addr:$src))]>;
 let isCodeGenOnly =3D 1 in {
   def FsVMOVAPSrm : VPSI<0x28, MRMSrcMem, (outs FR32:$dst), (ins f128mem:$=
src),
                          "movaps\t{$src, $dst|$dst, $src}",
-                         [(set FR32:$dst, (alignedloadfsf32 addr:$src))]>,=
 VEX;
+                         [(set FR32:$dst, (alignedloadfsf32 addr:$src))],
+                         IIC_SSE_MOVA_P_RM>, VEX;
   def FsVMOVAPDrm : VPDI<0x28, MRMSrcMem, (outs FR64:$dst), (ins f128mem:$=
src),
                          "movapd\t{$src, $dst|$dst, $src}",
-                         [(set FR64:$dst, (alignedloadfsf64 addr:$src))]>,=
 VEX;
-}
+                         [(set FR64:$dst, (alignedloadfsf64 addr:$src))],
+                         IIC_SSE_MOVA_P_RM>, VEX;
+}
+def FsMOVAPSrm : PSI<0x28, MRMSrcMem, (outs FR32:$dst), (ins f128mem:$src),
+                     "movaps\t{$src, $dst|$dst, $src}",
+                     [(set FR32:$dst, (alignedloadfsf32 addr:$src))],
+                     IIC_SSE_MOVA_P_RM>;
+def FsMOVAPDrm : PDI<0x28, MRMSrcMem, (outs FR64:$dst), (ins f128mem:$src),
+                     "movapd\t{$src, $dst|$dst, $src}",
+                     [(set FR64:$dst, (alignedloadfsf64 addr:$src))],
+                     IIC_SSE_MOVA_P_RM>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -921,94 +1120,68 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 multiclass sse12_mov_hilo_packed<bits<8>opc, RegisterClass RC,
-                                 PatFrag mov_frag, string base_opc,
-                                 string asm_opr> {
+                                 SDNode psnode, SDNode pdnode, string base=
_opc,
+                                 string asm_opr, InstrItinClass itin> {
   def PSrm : PI<opc, MRMSrcMem,
          (outs VR128:$dst), (ins VR128:$src1, f64mem:$src2),
          !strconcat(base_opc, "s", asm_opr),
      [(set RC:$dst,
-       (mov_frag RC:$src1,
+       (psnode RC:$src1,
               (bc_v4f32 (v2f64 (scalar_to_vector (loadf64 addr:$src2))))))=
],
-              SSEPackedSingle>, TB;
+              itin, SSEPackedSingle>, TB;
=20
   def PDrm : PI<opc, MRMSrcMem,
          (outs RC:$dst), (ins RC:$src1, f64mem:$src2),
          !strconcat(base_opc, "d", asm_opr),
-     [(set RC:$dst, (v2f64 (mov_frag RC:$src1,
+     [(set RC:$dst, (v2f64 (pdnode RC:$src1,
                               (scalar_to_vector (loadf64 addr:$src2)))))],
-              SSEPackedDouble>, TB, OpSize;
+              itin, SSEPackedDouble>, TB, OpSize;
 }
=20
 let AddedComplexity =3D 20 in {
-  defm VMOVL : sse12_mov_hilo_packed<0x12, VR128, movlp, "movlp",
-                     "\t{$src2, $src1, $dst|$dst, $src1, $src2}">, VEX_4V;
+  defm VMOVL : sse12_mov_hilo_packed<0x12, VR128, X86Movlps, X86Movlpd, "m=
ovlp",
+                     "\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     IIC_SSE_MOV_LH>, VEX_4V;
 }
 let Constraints =3D "$src1 =3D $dst", AddedComplexity =3D 20 in {
-  defm MOVL : sse12_mov_hilo_packed<0x12, VR128, movlp, "movlp",
-                                   "\t{$src2, $dst|$dst, $src2}">;
+  defm MOVL : sse12_mov_hilo_packed<0x12, VR128, X86Movlps, X86Movlpd, "mo=
vlp",
+                                   "\t{$src2, $dst|$dst, $src2}",
+                                   IIC_SSE_MOV_LH>;
 }
=20
 def VMOVLPSmr : VPSI<0x13, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$sr=
c),
                    "movlps\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract (bc_v2f64 (v4f32 VR128:$sr=
c)),
-                                 (iPTR 0))), addr:$dst)]>, VEX;
+                                 (iPTR 0))), addr:$dst)],
+                                 IIC_SSE_MOV_LH>, VEX;
 def VMOVLPDmr : VPDI<0x13, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$sr=
c),
                    "movlpd\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract (v2f64 VR128:$src),
-                                 (iPTR 0))), addr:$dst)]>, VEX;
+                                 (iPTR 0))), addr:$dst)],
+                                 IIC_SSE_MOV_LH>, VEX;
 def MOVLPSmr : PSI<0x13, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$src),
                    "movlps\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract (bc_v2f64 (v4f32 VR128:$sr=
c)),
-                                 (iPTR 0))), addr:$dst)]>;
+                                 (iPTR 0))), addr:$dst)],
+                                 IIC_SSE_MOV_LH>;
 def MOVLPDmr : PDI<0x13, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$src),
                    "movlpd\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract (v2f64 VR128:$src),
-                                 (iPTR 0))), addr:$dst)]>;
+                                 (iPTR 0))), addr:$dst)],
+                                 IIC_SSE_MOV_LH>;
=20
 let Predicates =3D [HasAVX] in {
-  let AddedComplexity =3D 20 in {
-    // vector_shuffle v1, (load v2) <4, 5, 2, 3> using MOVLPS
-    def : Pat<(v4f32 (movlp VR128:$src1, (load addr:$src2))),
-              (VMOVLPSrm VR128:$src1, addr:$src2)>;
-    def : Pat<(v4i32 (movlp VR128:$src1, (load addr:$src2))),
-              (VMOVLPSrm VR128:$src1, addr:$src2)>;
-    // vector_shuffle v1, (load v2) <2, 1> using MOVLPS
-    def : Pat<(v2f64 (movlp VR128:$src1, (load addr:$src2))),
-              (VMOVLPDrm VR128:$src1, addr:$src2)>;
-    def : Pat<(v2i64 (movlp VR128:$src1, (load addr:$src2))),
-              (VMOVLPDrm VR128:$src1, addr:$src2)>;
-  }
-
-  // (store (vector_shuffle (load addr), v2, <4, 5, 2, 3>), addr) using MO=
VLPS
-  def : Pat<(store (v4f32 (movlp (load addr:$src1), VR128:$src2)), addr:$s=
rc1),
-            (VMOVLPSmr addr:$src1, VR128:$src2)>;
-  def : Pat<(store (v4i32 (movlp (bc_v4i32 (loadv2i64 addr:$src1)),
-                                 VR128:$src2)), addr:$src1),
-            (VMOVLPSmr addr:$src1, VR128:$src2)>;
-
-  // (store (vector_shuffle (load addr), v2, <2, 1>), addr) using MOVLPS
-  def : Pat<(store (v2f64 (movlp (load addr:$src1), VR128:$src2)), addr:$s=
rc1),
-            (VMOVLPDmr addr:$src1, VR128:$src2)>;
-  def : Pat<(store (v2i64 (movlp (load addr:$src1), VR128:$src2)), addr:$s=
rc1),
-            (VMOVLPDmr addr:$src1, VR128:$src2)>;
-
   // Shuffle with VMOVLPS
   def : Pat<(v4f32 (X86Movlps VR128:$src1, (load addr:$src2))),
             (VMOVLPSrm VR128:$src1, addr:$src2)>;
   def : Pat<(v4i32 (X86Movlps VR128:$src1, (load addr:$src2))),
             (VMOVLPSrm VR128:$src1, addr:$src2)>;
-  def : Pat<(X86Movlps VR128:$src1,
-                      (bc_v4f32 (v2f64 (scalar_to_vector (loadf64 addr:$sr=
c2))))),
-            (VMOVLPSrm VR128:$src1, addr:$src2)>;
=20
   // Shuffle with VMOVLPD
   def : Pat<(v2f64 (X86Movlpd VR128:$src1, (load addr:$src2))),
             (VMOVLPDrm VR128:$src1, addr:$src2)>;
   def : Pat<(v2i64 (X86Movlpd VR128:$src1, (load addr:$src2))),
             (VMOVLPDrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2f64 (X86Movlpd VR128:$src1,
-                              (scalar_to_vector (loadf64 addr:$src2)))),
-            (VMOVLPDrm VR128:$src1, addr:$src2)>;
=20
   // Store patterns
   def : Pat<(store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)),
@@ -1026,19 +1199,9 @@
 }
=20
 let Predicates =3D [HasSSE1] in {
-  let AddedComplexity =3D 20 in {
-    // vector_shuffle v1, (load v2) <4, 5, 2, 3> using MOVLPS
-    def : Pat<(v4f32 (movlp VR128:$src1, (load addr:$src2))),
-              (MOVLPSrm VR128:$src1, addr:$src2)>;
-    def : Pat<(v4i32 (movlp VR128:$src1, (load addr:$src2))),
-              (MOVLPSrm VR128:$src1, addr:$src2)>;
-  }
-
   // (store (vector_shuffle (load addr), v2, <4, 5, 2, 3>), addr) using MO=
VLPS
-  def : Pat<(store (v4f32 (movlp (load addr:$src1), VR128:$src2)), addr:$s=
rc1),
-            (MOVLPSmr addr:$src1, VR128:$src2)>;
-  def : Pat<(store (v4i32 (movlp (bc_v4i32 (loadv2i64 addr:$src1)),
-                                 VR128:$src2)), addr:$src1),
+  def : Pat<(store (i64 (vector_extract (bc_v2i64 (v4f32 VR128:$src2)),
+                                 (iPTR 0))), addr:$src1),
             (MOVLPSmr addr:$src1, VR128:$src2)>;
=20
   // Shuffle with MOVLPS
@@ -1047,7 +1210,7 @@
   def : Pat<(v4i32 (X86Movlps VR128:$src1, (load addr:$src2))),
             (MOVLPSrm VR128:$src1, addr:$src2)>;
   def : Pat<(X86Movlps VR128:$src1,
-                      (bc_v4f32 (v2f64 (scalar_to_vector (loadf64 addr:$sr=
c2))))),
+                      (bc_v4f32 (v2i64 (scalar_to_vector (loadi64 addr:$sr=
c2))))),
             (MOVLPSrm VR128:$src1, addr:$src2)>;
=20
   // Store patterns
@@ -1061,28 +1224,11 @@
 }
=20
 let Predicates =3D [HasSSE2] in {
-  let AddedComplexity =3D 20 in {
-    // vector_shuffle v1, (load v2) <2, 1> using MOVLPS
-    def : Pat<(v2f64 (movlp VR128:$src1, (load addr:$src2))),
-              (MOVLPDrm VR128:$src1, addr:$src2)>;
-    def : Pat<(v2i64 (movlp VR128:$src1, (load addr:$src2))),
-              (MOVLPDrm VR128:$src1, addr:$src2)>;
-  }
-
-  // (store (vector_shuffle (load addr), v2, <2, 1>), addr) using MOVLPS
-  def : Pat<(store (v2f64 (movlp (load addr:$src1), VR128:$src2)), addr:$s=
rc1),
-            (MOVLPDmr addr:$src1, VR128:$src2)>;
-  def : Pat<(store (v2i64 (movlp (load addr:$src1), VR128:$src2)), addr:$s=
rc1),
-            (MOVLPDmr addr:$src1, VR128:$src2)>;
-
   // Shuffle with MOVLPD
   def : Pat<(v2f64 (X86Movlpd VR128:$src1, (load addr:$src2))),
             (MOVLPDrm VR128:$src1, addr:$src2)>;
   def : Pat<(v2i64 (X86Movlpd VR128:$src1, (load addr:$src2))),
             (MOVLPDrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2f64 (X86Movlpd VR128:$src1,
-                              (scalar_to_vector (loadf64 addr:$src2)))),
-            (MOVLPDrm VR128:$src1, addr:$src2)>;
=20
   // Store patterns
   def : Pat<(store (v2f64 (X86Movlpd (load addr:$src1), VR128:$src2)),
@@ -1098,12 +1244,14 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 let AddedComplexity =3D 20 in {
-  defm VMOVH : sse12_mov_hilo_packed<0x16, VR128, movlhps, "movhp",
-                     "\t{$src2, $src1, $dst|$dst, $src1, $src2}">, VEX_4V;
+  defm VMOVH : sse12_mov_hilo_packed<0x16, VR128, X86Movlhps, X86Movlhpd, =
"movhp",
+                     "\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     IIC_SSE_MOV_LH>, VEX_4V;
 }
 let Constraints =3D "$src1 =3D $dst", AddedComplexity =3D 20 in {
-  defm MOVH : sse12_mov_hilo_packed<0x16, VR128, movlhps, "movhp",
-                                   "\t{$src2, $dst|$dst, $src2}">;
+  defm MOVH : sse12_mov_hilo_packed<0x16, VR128, X86Movlhps, X86Movlhpd, "=
movhp",
+                                   "\t{$src2, $dst|$dst, $src2}",
+                                   IIC_SSE_MOV_LH>;
 }
=20
 // v2f64 extract element 1 is always custom lowered to unpack high to low
@@ -1111,94 +1259,62 @@
 def VMOVHPSmr : VPSI<0x17, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$sr=
c),
                    "movhps\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract
-                                 (unpckh (bc_v2f64 (v4f32 VR128:$src)),
-                                         (undef)), (iPTR 0))), addr:$dst)]=
>,
-                   VEX;
+                                 (X86Unpckh (bc_v2f64 (v4f32 VR128:$src)),
+                                            (bc_v2f64 (v4f32 VR128:$src))),
+                                 (iPTR 0))), addr:$dst)], IIC_SSE_MOV_LH>,=
 VEX;
 def VMOVHPDmr : VPDI<0x17, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$sr=
c),
                    "movhpd\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract
-                                 (v2f64 (unpckh VR128:$src, (undef))),
-                                 (iPTR 0))), addr:$dst)]>,
-                   VEX;
+                                 (v2f64 (X86Unpckh VR128:$src, VR128:$src)=
),
+                                 (iPTR 0))), addr:$dst)], IIC_SSE_MOV_LH>,=
 VEX;
 def MOVHPSmr : PSI<0x17, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$src),
                    "movhps\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract
-                                 (unpckh (bc_v2f64 (v4f32 VR128:$src)),
-                                         (undef)), (iPTR 0))), addr:$dst)]=
>;
+                                 (X86Unpckh (bc_v2f64 (v4f32 VR128:$src)),
+                                            (bc_v2f64 (v4f32 VR128:$src))),
+                                 (iPTR 0))), addr:$dst)], IIC_SSE_MOV_LH>;
 def MOVHPDmr : PDI<0x17, MRMDestMem, (outs), (ins f64mem:$dst, VR128:$src),
                    "movhpd\t{$src, $dst|$dst, $src}",
                    [(store (f64 (vector_extract
-                                 (v2f64 (unpckh VR128:$src, (undef))),
-                                 (iPTR 0))), addr:$dst)]>;
+                                 (v2f64 (X86Unpckh VR128:$src, VR128:$src)=
),
+                                 (iPTR 0))), addr:$dst)], IIC_SSE_MOV_LH>;
=20
 let Predicates =3D [HasAVX] in {
   // VMOVHPS patterns
-  def : Pat<(movlhps VR128:$src1, (bc_v4i32 (v2i64 (X86vzload addr:$src2))=
)),
-            (VMOVHPSrm (v4i32 VR128:$src1), addr:$src2)>;
   def : Pat<(X86Movlhps VR128:$src1,
-                 (bc_v4f32 (v2f64 (scalar_to_vector (loadf64 addr:$src2)))=
)),
+                 (bc_v4f32 (v2i64 (scalar_to_vector (loadi64 addr:$src2)))=
)),
             (VMOVHPSrm VR128:$src1, addr:$src2)>;
   def : Pat<(X86Movlhps VR128:$src1,
                  (bc_v4i32 (v2i64 (X86vzload addr:$src2)))),
             (VMOVHPSrm VR128:$src1, addr:$src2)>;
=20
-  // FIXME: Instead of X86Unpcklpd, there should be a X86Movlhpd here, the=
 problem
-  // is during lowering, where it's not possible to recognize the load fol=
d cause
-  // it has two uses through a bitcast. One use disappears at isel time an=
d the
-  // fold opportunity reappears.
-  def : Pat<(v2f64 (X86Unpcklpd VR128:$src1,
+  // FIXME: Instead of X86Unpckl, there should be a X86Movlhpd here, the p=
roblem
+  // is during lowering, where it's not possible to recognize the load fol=
d=20
+  // cause it has two uses through a bitcast. One use disappears at isel t=
ime
+  // and the fold opportunity reappears.
+  def : Pat<(v2f64 (X86Unpckl VR128:$src1,
                       (scalar_to_vector (loadf64 addr:$src2)))),
             (VMOVHPDrm VR128:$src1, addr:$src2)>;
-
-  // FIXME: This should be matched by a X86Movhpd instead. Same as above
-  def : Pat<(v2f64 (X86Movlhpd VR128:$src1,
-                      (scalar_to_vector (loadf64 addr:$src2)))),
-            (VMOVHPDrm VR128:$src1, addr:$src2)>;
-
-  // Store patterns
-  def : Pat<(store (f64 (vector_extract
-            (v2f64 (X86Unpckhps VR128:$src, (undef))), (iPTR 0))), addr:$d=
st),
-            (VMOVHPSmr addr:$dst, VR128:$src)>;
-  def : Pat<(store (f64 (vector_extract
-            (v2f64 (X86Unpckhpd VR128:$src, (undef))), (iPTR 0))), addr:$d=
st),
-            (VMOVHPDmr addr:$dst, VR128:$src)>;
 }
=20
 let Predicates =3D [HasSSE1] in {
   // MOVHPS patterns
-  def : Pat<(movlhps VR128:$src1, (bc_v4i32 (v2i64 (X86vzload addr:$src2))=
)),
-            (MOVHPSrm (v4i32 VR128:$src1), addr:$src2)>;
   def : Pat<(X86Movlhps VR128:$src1,
-                 (bc_v4f32 (v2f64 (scalar_to_vector (loadf64 addr:$src2)))=
)),
+                 (bc_v4f32 (v2i64 (scalar_to_vector (loadi64 addr:$src2)))=
)),
             (MOVHPSrm VR128:$src1, addr:$src2)>;
   def : Pat<(X86Movlhps VR128:$src1,
                  (bc_v4f32 (v2i64 (X86vzload addr:$src2)))),
             (MOVHPSrm VR128:$src1, addr:$src2)>;
-
-  // Store patterns
-  def : Pat<(store (f64 (vector_extract
-            (v2f64 (X86Unpckhps VR128:$src, (undef))), (iPTR 0))), addr:$d=
st),
-            (MOVHPSmr addr:$dst, VR128:$src)>;
 }
=20
 let Predicates =3D [HasSSE2] in {
-  // FIXME: Instead of X86Unpcklpd, there should be a X86Movlhpd here, the=
 problem
-  // is during lowering, where it's not possible to recognize the load fol=
d cause
-  // it has two uses through a bitcast. One use disappears at isel time an=
d the
-  // fold opportunity reappears.
-  def : Pat<(v2f64 (X86Unpcklpd VR128:$src1,
+  // FIXME: Instead of X86Unpckl, there should be a X86Movlhpd here, the p=
roblem
+  // is during lowering, where it's not possible to recognize the load fol=
d=20
+  // cause it has two uses through a bitcast. One use disappears at isel t=
ime
+  // and the fold opportunity reappears.
+  def : Pat<(v2f64 (X86Unpckl VR128:$src1,
                       (scalar_to_vector (loadf64 addr:$src2)))),
             (MOVHPDrm VR128:$src1, addr:$src2)>;
-
-  // FIXME: This should be matched by a X86Movhpd instead. Same as above
-  def : Pat<(v2f64 (X86Movlhpd VR128:$src1,
-                      (scalar_to_vector (loadf64 addr:$src2)))),
-            (MOVHPDrm VR128:$src1, addr:$src2)>;
-
-  // Store patterns
-  def : Pat<(store (f64 (vector_extract
-            (v2f64 (X86Unpckhpd VR128:$src, (undef))), (iPTR 0))),addr:$ds=
t),
-            (MOVHPDmr addr:$dst, VR128:$src)>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1210,13 +1326,15 @@
                                        (ins VR128:$src1, VR128:$src2),
                       "movlhps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set VR128:$dst,
-                        (v4f32 (movlhps VR128:$src1, VR128:$src2)))]>,
+                        (v4f32 (X86Movlhps VR128:$src1, VR128:$src2)))],
+                        IIC_SSE_MOV_LH>,
                       VEX_4V;
   def VMOVHLPSrr : VPSI<0x12, MRMSrcReg, (outs VR128:$dst),
                                        (ins VR128:$src1, VR128:$src2),
                       "movhlps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                       [(set VR128:$dst,
-                        (v4f32 (movhlps VR128:$src1, VR128:$src2)))]>,
+                        (v4f32 (X86Movhlps VR128:$src1, VR128:$src2)))],
+                        IIC_SSE_MOV_LH>,
                       VEX_4V;
 }
 let Constraints =3D "$src1 =3D $dst", AddedComplexity =3D 20 in {
@@ -1224,86 +1342,36 @@
                                        (ins VR128:$src1, VR128:$src2),
                       "movlhps\t{$src2, $dst|$dst, $src2}",
                       [(set VR128:$dst,
-                        (v4f32 (movlhps VR128:$src1, VR128:$src2)))]>;
+                        (v4f32 (X86Movlhps VR128:$src1, VR128:$src2)))],
+                        IIC_SSE_MOV_LH>;
   def MOVHLPSrr : PSI<0x12, MRMSrcReg, (outs VR128:$dst),
                                        (ins VR128:$src1, VR128:$src2),
                       "movhlps\t{$src2, $dst|$dst, $src2}",
                       [(set VR128:$dst,
-                        (v4f32 (movhlps VR128:$src1, VR128:$src2)))]>;
+                        (v4f32 (X86Movhlps VR128:$src1, VR128:$src2)))],
+                        IIC_SSE_MOV_LH>;
 }
=20
 let Predicates =3D [HasAVX] in {
   // MOVLHPS patterns
-  let AddedComplexity =3D 20 in {
-    def : Pat<(v4f32 (movddup VR128:$src, (undef))),
-              (VMOVLHPSrr (v4f32 VR128:$src), (v4f32 VR128:$src))>;
-    def : Pat<(v2i64 (movddup VR128:$src, (undef))),
-              (VMOVLHPSrr (v2i64 VR128:$src), (v2i64 VR128:$src))>;
-
-    // vector_shuffle v1, v2 <0, 1, 4, 5> using MOVLHPS
-    def : Pat<(v4i32 (movlhps VR128:$src1, VR128:$src2)),
-              (VMOVLHPSrr VR128:$src1, VR128:$src2)>;
-  }
-  def : Pat<(v4f32 (X86Movlhps VR128:$src1, VR128:$src2)),
-            (VMOVLHPSrr VR128:$src1, VR128:$src2)>;
   def : Pat<(v4i32 (X86Movlhps VR128:$src1, VR128:$src2)),
             (VMOVLHPSrr VR128:$src1, VR128:$src2)>;
   def : Pat<(v2i64 (X86Movlhps VR128:$src1, VR128:$src2)),
             (VMOVLHPSrr (v2i64 VR128:$src1), VR128:$src2)>;
=20
   // MOVHLPS patterns
-  let AddedComplexity =3D 20 in {
-    // vector_shuffle v1, v2 <6, 7, 2, 3> using MOVHLPS
-    def : Pat<(v4i32 (movhlps VR128:$src1, VR128:$src2)),
-              (VMOVHLPSrr VR128:$src1, VR128:$src2)>;
-
-    // vector_shuffle v1, undef <2, ?, ?, ?> using MOVHLPS
-    def : Pat<(v4f32 (movhlps_undef VR128:$src1, (undef))),
-              (VMOVHLPSrr VR128:$src1, VR128:$src1)>;
-    def : Pat<(v4i32 (movhlps_undef VR128:$src1, (undef))),
-              (VMOVHLPSrr VR128:$src1, VR128:$src1)>;
-  }
-
-  def : Pat<(v4f32 (X86Movhlps VR128:$src1, VR128:$src2)),
-            (VMOVHLPSrr VR128:$src1, VR128:$src2)>;
   def : Pat<(v4i32 (X86Movhlps VR128:$src1, VR128:$src2)),
             (VMOVHLPSrr VR128:$src1, VR128:$src2)>;
 }
=20
 let Predicates =3D [HasSSE1] in {
   // MOVLHPS patterns
-  let AddedComplexity =3D 20 in {
-    def : Pat<(v4f32 (movddup VR128:$src, (undef))),
-              (MOVLHPSrr (v4f32 VR128:$src), (v4f32 VR128:$src))>;
-    def : Pat<(v2i64 (movddup VR128:$src, (undef))),
-              (MOVLHPSrr (v2i64 VR128:$src), (v2i64 VR128:$src))>;
-
-    // vector_shuffle v1, v2 <0, 1, 4, 5> using MOVLHPS
-    def : Pat<(v4i32 (movlhps VR128:$src1, VR128:$src2)),
-              (MOVLHPSrr VR128:$src1, VR128:$src2)>;
-  }
-  def : Pat<(v4f32 (X86Movlhps VR128:$src1, VR128:$src2)),
-            (MOVLHPSrr VR128:$src1, VR128:$src2)>;
   def : Pat<(v4i32 (X86Movlhps VR128:$src1, VR128:$src2)),
             (MOVLHPSrr VR128:$src1, VR128:$src2)>;
   def : Pat<(v2i64 (X86Movlhps VR128:$src1, VR128:$src2)),
             (MOVLHPSrr (v2i64 VR128:$src1), VR128:$src2)>;
=20
   // MOVHLPS patterns
-  let AddedComplexity =3D 20 in {
-    // vector_shuffle v1, v2 <6, 7, 2, 3> using MOVHLPS
-    def : Pat<(v4i32 (movhlps VR128:$src1, VR128:$src2)),
-              (MOVHLPSrr VR128:$src1, VR128:$src2)>;
-
-    // vector_shuffle v1, undef <2, ?, ?, ?> using MOVHLPS
-    def : Pat<(v4f32 (movhlps_undef VR128:$src1, (undef))),
-              (MOVHLPSrr VR128:$src1, VR128:$src1)>;
-    def : Pat<(v4i32 (movhlps_undef VR128:$src1, (undef))),
-              (MOVHLPSrr VR128:$src1, VR128:$src1)>;
-  }
-
-  def : Pat<(v4f32 (X86Movhlps VR128:$src1, VR128:$src2)),
-            (MOVHLPSrr VR128:$src1, VR128:$src2)>;
   def : Pat<(v4i32 (X86Movhlps VR128:$src1, VR128:$src2)),
             (MOVHLPSrr VR128:$src1, VR128:$src2)>;
 }
@@ -1312,70 +1380,97 @@
 // SSE 1 & 2 - Conversion Instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+def SSE_CVT_PD : OpndItins<
+  IIC_SSE_CVT_PD_RR, IIC_SSE_CVT_PD_RM
+>;
+
+def SSE_CVT_PS : OpndItins<
+  IIC_SSE_CVT_PS_RR, IIC_SSE_CVT_PS_RM
+>;
+
+def SSE_CVT_Scalar : OpndItins<
+  IIC_SSE_CVT_Scalar_RR, IIC_SSE_CVT_Scalar_RM
+>;
+
+def SSE_CVT_SS2SI_32 : OpndItins<
+  IIC_SSE_CVT_SS2SI32_RR, IIC_SSE_CVT_SS2SI32_RM
+>;
+
+def SSE_CVT_SS2SI_64 : OpndItins<
+  IIC_SSE_CVT_SS2SI64_RR, IIC_SSE_CVT_SS2SI64_RM
+>;
+
+def SSE_CVT_SD2SI : OpndItins<
+  IIC_SSE_CVT_SD2SI_RR, IIC_SSE_CVT_SD2SI_RM
+>;
+
 multiclass sse12_cvt_s<bits<8> opc, RegisterClass SrcRC, RegisterClass Dst=
RC,
                      SDNode OpNode, X86MemOperand x86memop, PatFrag ld_fra=
g,
-                     string asm> {
+                     string asm, OpndItins itins> {
   def rr : SI<opc, MRMSrcReg, (outs DstRC:$dst), (ins SrcRC:$src), asm,
-                        [(set DstRC:$dst, (OpNode SrcRC:$src))]>;
+                        [(set DstRC:$dst, (OpNode SrcRC:$src))],
+                        itins.rr>;
   def rm : SI<opc, MRMSrcMem, (outs DstRC:$dst), (ins x86memop:$src), asm,
-                        [(set DstRC:$dst, (OpNode (ld_frag addr:$src)))]>;
-}
-
-multiclass sse12_cvt_s_np<bits<8> opc, RegisterClass SrcRC, RegisterClass =
DstRC,
-                          X86MemOperand x86memop, string asm> {
-  def rr : SI<opc, MRMSrcReg, (outs DstRC:$dst), (ins SrcRC:$src), asm, []=
>;
-  let mayLoad =3D 1 in
-  def rm : SI<opc, MRMSrcMem, (outs DstRC:$dst), (ins x86memop:$src), asm,=
 []>;
+                        [(set DstRC:$dst, (OpNode (ld_frag addr:$src)))],
+                        itins.rm>;
 }
=20
 multiclass sse12_cvt_p<bits<8> opc, RegisterClass SrcRC, RegisterClass Dst=
RC,
                          SDNode OpNode, X86MemOperand x86memop, PatFrag ld=
_frag,
-                         string asm, Domain d> {
+                         string asm, Domain d, OpndItins itins> {
   def rr : PI<opc, MRMSrcReg, (outs DstRC:$dst), (ins SrcRC:$src), asm,
-                        [(set DstRC:$dst, (OpNode SrcRC:$src))], d>;
+                        [(set DstRC:$dst, (OpNode SrcRC:$src))],
+                        itins.rr, d>;
   def rm : PI<opc, MRMSrcMem, (outs DstRC:$dst), (ins x86memop:$src), asm,
-                        [(set DstRC:$dst, (OpNode (ld_frag addr:$src)))], =
d>;
+                        [(set DstRC:$dst, (OpNode (ld_frag addr:$src)))],
+                        itins.rm, d>;
 }
=20
 multiclass sse12_vcvt_avx<bits<8> opc, RegisterClass SrcRC, RegisterClass =
DstRC,
                           X86MemOperand x86memop, string asm> {
+let neverHasSideEffects =3D 1 in {
   def rr : SI<opc, MRMSrcReg, (outs DstRC:$dst), (ins DstRC:$src1, SrcRC:$=
src),
               !strconcat(asm,"\t{$src, $src1, $dst|$dst, $src1, $src}"), [=
]>;
   let mayLoad =3D 1 in
   def rm : SI<opc, MRMSrcMem, (outs DstRC:$dst),
               (ins DstRC:$src1, x86memop:$src),
               !strconcat(asm,"\t{$src, $src1, $dst|$dst, $src1, $src}"), [=
]>;
+} // neverHasSideEffects =3D 1
 }
=20
 defm VCVTTSS2SI   : sse12_cvt_s<0x2C, FR32, GR32, fp_to_sint, f32mem, load=
f32,
-                                "cvttss2si\t{$src, $dst|$dst, $src}">, XS,=
 VEX,
-                                VEX_LIG;
+                                "cvttss2si\t{$src, $dst|$dst, $src}",
+                                SSE_CVT_SS2SI_32>,
+                                XS, VEX, VEX_LIG;
 defm VCVTTSS2SI64 : sse12_cvt_s<0x2C, FR32, GR64, fp_to_sint, f32mem, load=
f32,
-                                "cvttss2si\t{$src, $dst|$dst, $src}">, XS,=
 VEX,
-                                VEX_W, VEX_LIG;
+                                "cvttss2si\t{$src, $dst|$dst, $src}",
+                                SSE_CVT_SS2SI_64>,
+                                XS, VEX, VEX_W, VEX_LIG;
 defm VCVTTSD2SI   : sse12_cvt_s<0x2C, FR64, GR32, fp_to_sint, f64mem, load=
f64,
-                                "cvttsd2si\t{$src, $dst|$dst, $src}">, XD,=
 VEX,
-                                VEX_LIG;
+                                "cvttsd2si\t{$src, $dst|$dst, $src}",
+                                SSE_CVT_SD2SI>,
+                                XD, VEX, VEX_LIG;
 defm VCVTTSD2SI64 : sse12_cvt_s<0x2C, FR64, GR64, fp_to_sint, f64mem, load=
f64,
-                                "cvttsd2si\t{$src, $dst|$dst, $src}">, XD,
-                                VEX, VEX_W, VEX_LIG;
+                                "cvttsd2si\t{$src, $dst|$dst, $src}",
+                                SSE_CVT_SD2SI>,
+                                XD, VEX, VEX_W, VEX_LIG;
=20
 // The assembler can recognize rr 64-bit instructions by seeing a rxx
 // register, but the same isn't true when only using memory operands,
 // provide other assembly "l" and "q" forms to address this explicitly
 // where appropriate to do so.
-defm VCVTSI2SS   : sse12_vcvt_avx<0x2A, GR32, FR32, i32mem, "cvtsi2ss">, X=
S,
-                                  VEX_4V, VEX_LIG;
-defm VCVTSI2SS64 : sse12_vcvt_avx<0x2A, GR64, FR32, i64mem, "cvtsi2ss{q}">=
, XS,
-                                  VEX_4V, VEX_W, VEX_LIG;
-defm VCVTSI2SD   : sse12_vcvt_avx<0x2A, GR32, FR64, i32mem, "cvtsi2sd">, X=
D,
-                                  VEX_4V, VEX_LIG;
-defm VCVTSI2SDL  : sse12_vcvt_avx<0x2A, GR32, FR64, i32mem, "cvtsi2sd{l}">=
, XD,
-                                  VEX_4V, VEX_LIG;
-defm VCVTSI2SD64 : sse12_vcvt_avx<0x2A, GR64, FR64, i64mem, "cvtsi2sd{q}">=
, XD,
-                                  VEX_4V, VEX_W, VEX_LIG;
-
-let Predicates =3D [HasAVX] in {
+defm VCVTSI2SS   : sse12_vcvt_avx<0x2A, GR32, FR32, i32mem, "cvtsi2ss">,
+                                  XS, VEX_4V, VEX_LIG;
+defm VCVTSI2SS64 : sse12_vcvt_avx<0x2A, GR64, FR32, i64mem, "cvtsi2ss{q}">,
+                                  XS, VEX_4V, VEX_W, VEX_LIG;
+defm VCVTSI2SD   : sse12_vcvt_avx<0x2A, GR32, FR64, i32mem, "cvtsi2sd">,
+                                  XD, VEX_4V, VEX_LIG;
+defm VCVTSI2SDL  : sse12_vcvt_avx<0x2A, GR32, FR64, i32mem, "cvtsi2sd{l}">,
+                                  XD, VEX_4V, VEX_LIG;
+defm VCVTSI2SD64 : sse12_vcvt_avx<0x2A, GR64, FR64, i64mem, "cvtsi2sd{q}">,
+                                  XD, VEX_4V, VEX_W, VEX_LIG;
+
+let Predicates =3D [HasAVX], AddedComplexity =3D 1 in {
   def : Pat<(f32 (sint_to_fp (loadi32 addr:$src))),
             (VCVTSI2SSrm (f32 (IMPLICIT_DEF)), addr:$src)>;
   def : Pat<(f32 (sint_to_fp (loadi64 addr:$src))),
@@ -1396,147 +1491,174 @@
 }
=20
 defm CVTTSS2SI : sse12_cvt_s<0x2C, FR32, GR32, fp_to_sint, f32mem, loadf32,
-                      "cvttss2si\t{$src, $dst|$dst, $src}">, XS;
+                      "cvttss2si\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_SS2SI_32>, XS;
 defm CVTTSS2SI64 : sse12_cvt_s<0x2C, FR32, GR64, fp_to_sint, f32mem, loadf=
32,
-                      "cvttss2si{q}\t{$src, $dst|$dst, $src}">, XS, REX_W;
+                      "cvttss2si{q}\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_SS2SI_64>, XS, REX_W;
 defm CVTTSD2SI : sse12_cvt_s<0x2C, FR64, GR32, fp_to_sint, f64mem, loadf64,
-                      "cvttsd2si\t{$src, $dst|$dst, $src}">, XD;
+                      "cvttsd2si\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_SD2SI>, XD;
 defm CVTTSD2SI64 : sse12_cvt_s<0x2C, FR64, GR64, fp_to_sint, f64mem, loadf=
64,
-                      "cvttsd2si{q}\t{$src, $dst|$dst, $src}">, XD, REX_W;
+                      "cvttsd2si{q}\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_SD2SI>, XD, REX_W;
 defm CVTSI2SS  : sse12_cvt_s<0x2A, GR32, FR32, sint_to_fp, i32mem, loadi32,
-                      "cvtsi2ss\t{$src, $dst|$dst, $src}">, XS;
+                      "cvtsi2ss\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_Scalar>, XS;
 defm CVTSI2SS64 : sse12_cvt_s<0x2A, GR64, FR32, sint_to_fp, i64mem, loadi6=
4,
-                      "cvtsi2ss{q}\t{$src, $dst|$dst, $src}">, XS, REX_W;
+                      "cvtsi2ss{q}\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_Scalar>, XS, REX_W;
 defm CVTSI2SD  : sse12_cvt_s<0x2A, GR32, FR64, sint_to_fp, i32mem, loadi32,
-                      "cvtsi2sd\t{$src, $dst|$dst, $src}">, XD;
+                      "cvtsi2sd\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_Scalar>, XD;
 defm CVTSI2SD64 : sse12_cvt_s<0x2A, GR64, FR64, sint_to_fp, i64mem, loadi6=
4,
-                      "cvtsi2sd{q}\t{$src, $dst|$dst, $src}">, XD, REX_W;
+                      "cvtsi2sd{q}\t{$src, $dst|$dst, $src}",
+                      SSE_CVT_Scalar>, XD, REX_W;
=20
 // Conversion Instructions Intrinsics - Match intrinsics which expect MM
 // and/or XMM operand(s).
=20
 multiclass sse12_cvt_sint<bits<8> opc, RegisterClass SrcRC, RegisterClass =
DstRC,
                          Intrinsic Int, X86MemOperand x86memop, PatFrag ld=
_frag,
-                         string asm> {
+                         string asm, OpndItins itins> {
   def rr : SI<opc, MRMSrcReg, (outs DstRC:$dst), (ins SrcRC:$src),
               !strconcat(asm, "\t{$src, $dst|$dst, $src}"),
-              [(set DstRC:$dst, (Int SrcRC:$src))]>;
+              [(set DstRC:$dst, (Int SrcRC:$src))], itins.rr>;
   def rm : SI<opc, MRMSrcMem, (outs DstRC:$dst), (ins x86memop:$src),
               !strconcat(asm, "\t{$src, $dst|$dst, $src}"),
-              [(set DstRC:$dst, (Int (ld_frag addr:$src)))]>;
+              [(set DstRC:$dst, (Int (ld_frag addr:$src)))], itins.rm>;
 }
=20
 multiclass sse12_cvt_sint_3addr<bits<8> opc, RegisterClass SrcRC,
                     RegisterClass DstRC, Intrinsic Int, X86MemOperand x86m=
emop,
-                    PatFrag ld_frag, string asm, bit Is2Addr =3D 1> {
+                    PatFrag ld_frag, string asm, OpndItins itins,
+                    bit Is2Addr =3D 1> {
   def rr : SI<opc, MRMSrcReg, (outs DstRC:$dst), (ins DstRC:$src1, SrcRC:$=
src2),
               !if(Is2Addr,
                   !strconcat(asm, "\t{$src2, $dst|$dst, $src2}"),
                   !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src=
2}")),
-              [(set DstRC:$dst, (Int DstRC:$src1, SrcRC:$src2))]>;
+              [(set DstRC:$dst, (Int DstRC:$src1, SrcRC:$src2))],
+              itins.rr>;
   def rm : SI<opc, MRMSrcMem, (outs DstRC:$dst),
               (ins DstRC:$src1, x86memop:$src2),
               !if(Is2Addr,
                   !strconcat(asm, "\t{$src2, $dst|$dst, $src2}"),
                   !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src=
2}")),
-              [(set DstRC:$dst, (Int DstRC:$src1, (ld_frag addr:$src2)))]>;
-}
-
-defm Int_VCVTSD2SI : sse12_cvt_sint<0x2D, VR128, GR32, int_x86_sse2_cvtsd2=
si,
-                      f128mem, load, "cvtsd2si">, XD, VEX;
-defm Int_VCVTSD2SI64 : sse12_cvt_sint<0x2D, VR128, GR64,
-                      int_x86_sse2_cvtsd2si64, f128mem, load, "cvtsd2si">,
-                      XD, VEX, VEX_W;
-
-// FIXME: The asm matcher has a hack to ignore instructions with _Int and =
Int_
-// Get rid of this hack or rename the intrinsics, there are several
-// intructions that only match with the intrinsic form, why create duplica=
tes
-// to let them be recognized by the assembler?
-defm VCVTSD2SI     : sse12_cvt_s_np<0x2D, FR64, GR32, f64mem,
-                      "cvtsd2si\t{$src, $dst|$dst, $src}">, XD, VEX, VEX_L=
IG;
-defm VCVTSD2SI64   : sse12_cvt_s_np<0x2D, FR64, GR64, f64mem,
-                      "cvtsd2si\t{$src, $dst|$dst, $src}">, XD, VEX, VEX_W,
-                      VEX_LIG;
+              [(set DstRC:$dst, (Int DstRC:$src1, (ld_frag addr:$src2)))],
+              itins.rm>;
+}
+
+defm VCVTSD2SI : sse12_cvt_sint<0x2D, VR128, GR32, int_x86_sse2_cvtsd2si,
+                  f128mem, load, "cvtsd2si", SSE_CVT_SD2SI>, XD, VEX, VEX_=
LIG;
+defm VCVTSD2SI64 : sse12_cvt_sint<0x2D, VR128, GR64,
+                  int_x86_sse2_cvtsd2si64, f128mem, load, "cvtsd2si",
+                  SSE_CVT_SD2SI>, XD, VEX, VEX_W, VEX_LIG;
=20
 defm CVTSD2SI : sse12_cvt_sint<0x2D, VR128, GR32, int_x86_sse2_cvtsd2si,
-                f128mem, load, "cvtsd2si{l}">, XD;
+                f128mem, load, "cvtsd2si{l}", SSE_CVT_SD2SI>, XD;
 defm CVTSD2SI64 : sse12_cvt_sint<0x2D, VR128, GR64, int_x86_sse2_cvtsd2si6=
4,
-                  f128mem, load, "cvtsd2si{q}">, XD, REX_W;
+                  f128mem, load, "cvtsd2si{q}", SSE_CVT_SD2SI>, XD, REX_W;
=20
=20
 defm Int_VCVTSI2SS : sse12_cvt_sint_3addr<0x2A, GR32, VR128,
-          int_x86_sse_cvtsi2ss, i32mem, loadi32, "cvtsi2ss", 0>, XS, VEX_4=
V;
+          int_x86_sse_cvtsi2ss, i32mem, loadi32, "cvtsi2ss",
+          SSE_CVT_Scalar, 0>, XS, VEX_4V;
 defm Int_VCVTSI2SS64 : sse12_cvt_sint_3addr<0x2A, GR64, VR128,
-          int_x86_sse_cvtsi642ss, i64mem, loadi64, "cvtsi2ss", 0>, XS, VEX=
_4V,
+          int_x86_sse_cvtsi642ss, i64mem, loadi64, "cvtsi2ss",
+          SSE_CVT_Scalar, 0>, XS, VEX_4V,
           VEX_W;
 defm Int_VCVTSI2SD : sse12_cvt_sint_3addr<0x2A, GR32, VR128,
-          int_x86_sse2_cvtsi2sd, i32mem, loadi32, "cvtsi2sd", 0>, XD, VEX_=
4V;
+          int_x86_sse2_cvtsi2sd, i32mem, loadi32, "cvtsi2sd",
+          SSE_CVT_Scalar, 0>, XD, VEX_4V;
 defm Int_VCVTSI2SD64 : sse12_cvt_sint_3addr<0x2A, GR64, VR128,
-          int_x86_sse2_cvtsi642sd, i64mem, loadi64, "cvtsi2sd", 0>, XD,
+          int_x86_sse2_cvtsi642sd, i64mem, loadi64, "cvtsi2sd",
+          SSE_CVT_Scalar, 0>, XD,
           VEX_4V, VEX_W;
=20
 let Constraints =3D "$src1 =3D $dst" in {
   defm Int_CVTSI2SS : sse12_cvt_sint_3addr<0x2A, GR32, VR128,
                         int_x86_sse_cvtsi2ss, i32mem, loadi32,
-                        "cvtsi2ss">, XS;
+                        "cvtsi2ss", SSE_CVT_Scalar>, XS;
   defm Int_CVTSI2SS64 : sse12_cvt_sint_3addr<0x2A, GR64, VR128,
                         int_x86_sse_cvtsi642ss, i64mem, loadi64,
-                        "cvtsi2ss{q}">, XS, REX_W;
+                        "cvtsi2ss{q}", SSE_CVT_Scalar>, XS, REX_W;
   defm Int_CVTSI2SD : sse12_cvt_sint_3addr<0x2A, GR32, VR128,
                         int_x86_sse2_cvtsi2sd, i32mem, loadi32,
-                        "cvtsi2sd">, XD;
+                        "cvtsi2sd", SSE_CVT_Scalar>, XD;
   defm Int_CVTSI2SD64 : sse12_cvt_sint_3addr<0x2A, GR64, VR128,
                         int_x86_sse2_cvtsi642sd, i64mem, loadi64,
-                        "cvtsi2sd">, XD, REX_W;
+                        "cvtsi2sd", SSE_CVT_Scalar>, XD, REX_W;
 }
=20
 /// SSE 1 Only
=20
 // Aliases for intrinsics
 defm Int_VCVTTSS2SI : sse12_cvt_sint<0x2C, VR128, GR32, int_x86_sse_cvttss=
2si,
-                                    f32mem, load, "cvttss2si">, XS, VEX;
+                                    f32mem, load, "cvttss2si",
+                                    SSE_CVT_SS2SI_32>, XS, VEX;
 defm Int_VCVTTSS2SI64 : sse12_cvt_sint<0x2C, VR128, GR64,
                                     int_x86_sse_cvttss2si64, f32mem, load,
-                                    "cvttss2si">, XS, VEX, VEX_W;
+                                    "cvttss2si", SSE_CVT_SS2SI_64>,
+                                    XS, VEX, VEX_W;
 defm Int_VCVTTSD2SI : sse12_cvt_sint<0x2C, VR128, GR32, int_x86_sse2_cvtts=
d2si,
-                                    f128mem, load, "cvttsd2si">, XD, VEX;
+                                    f128mem, load, "cvttsd2si", SSE_CVT_SD=
2SI>,
+                                    XD, VEX;
 defm Int_VCVTTSD2SI64 : sse12_cvt_sint<0x2C, VR128, GR64,
                                     int_x86_sse2_cvttsd2si64, f128mem, loa=
d,
-                                    "cvttsd2si">, XD, VEX, VEX_W;
+                                    "cvttsd2si", SSE_CVT_SD2SI>,
+                                    XD, VEX, VEX_W;
 defm Int_CVTTSS2SI : sse12_cvt_sint<0x2C, VR128, GR32, int_x86_sse_cvttss2=
si,
-                                    f32mem, load, "cvttss2si">, XS;
+                                    f32mem, load, "cvttss2si",
+                                    SSE_CVT_SS2SI_32>, XS;
 defm Int_CVTTSS2SI64 : sse12_cvt_sint<0x2C, VR128, GR64,
                                     int_x86_sse_cvttss2si64, f32mem, load,
-                                    "cvttss2si{q}">, XS, REX_W;
+                                    "cvttss2si{q}", SSE_CVT_SS2SI_64>,
+                                    XS, REX_W;
 defm Int_CVTTSD2SI : sse12_cvt_sint<0x2C, VR128, GR32, int_x86_sse2_cvttsd=
2si,
-                                    f128mem, load, "cvttsd2si">, XD;
+                                    f128mem, load, "cvttsd2si", SSE_CVT_SD=
2SI>,
+                                    XD;
 defm Int_CVTTSD2SI64 : sse12_cvt_sint<0x2C, VR128, GR64,
                                     int_x86_sse2_cvttsd2si64, f128mem, loa=
d,
-                                    "cvttsd2si{q}">, XD, REX_W;
+                                    "cvttsd2si{q}", SSE_CVT_SD2SI>,
+                                    XD, REX_W;
=20
 let Pattern =3D []<dag> in {
 defm VCVTSS2SI   : sse12_cvt_s<0x2D, FR32, GR32, undef, f32mem, load,
-                               "cvtss2si{l}\t{$src, $dst|$dst, $src}">, XS,
-                               VEX, VEX_LIG;
+                               "cvtss2si{l}\t{$src, $dst|$dst, $src}",
+                               SSE_CVT_SS2SI_32>, XS, VEX, VEX_LIG;
 defm VCVTSS2SI64 : sse12_cvt_s<0x2D, FR32, GR64, undef, f32mem, load,
-                               "cvtss2si\t{$src, $dst|$dst, $src}">, XS, V=
EX,
-                               VEX_W, VEX_LIG;
+                               "cvtss2si\t{$src, $dst|$dst, $src}",
+                               SSE_CVT_SS2SI_64>, XS, VEX, VEX_W, VEX_LIG;
 defm VCVTDQ2PS   : sse12_cvt_p<0x5B, VR128, VR128, undef, i128mem, load,
                                "cvtdq2ps\t{$src, $dst|$dst, $src}",
-                               SSEPackedSingle>, TB, VEX;
+                               SSEPackedSingle, SSE_CVT_PS>, TB, VEX;
 defm VCVTDQ2PSY  : sse12_cvt_p<0x5B, VR256, VR256, undef, i256mem, load,
                                "cvtdq2ps\t{$src, $dst|$dst, $src}",
-                               SSEPackedSingle>, TB, VEX;
+                               SSEPackedSingle, SSE_CVT_PS>, TB, VEX;
 }
=20
 let Pattern =3D []<dag> in {
 defm CVTSS2SI : sse12_cvt_s<0x2D, FR32, GR32, undef, f32mem, load /*dummy*=
/,
-                          "cvtss2si{l}\t{$src, $dst|$dst, $src}">, XS;
+                          "cvtss2si{l}\t{$src, $dst|$dst, $src}",
+                          SSE_CVT_SS2SI_32>, XS;
 defm CVTSS2SI64 : sse12_cvt_s<0x2D, FR32, GR64, undef, f32mem, load /*dumm=
y*/,
-                          "cvtss2si{q}\t{$src, $dst|$dst, $src}">, XS, REX=
_W;
+                          "cvtss2si{q}\t{$src, $dst|$dst, $src}",
+                          SSE_CVT_SS2SI_64>, XS, REX_W;
 defm CVTDQ2PS : sse12_cvt_p<0x5B, VR128, VR128, undef, i128mem, load /*dum=
my*/,
                             "cvtdq2ps\t{$src, $dst|$dst, $src}",
-                            SSEPackedSingle>, TB; /* PD SSE3 form is avaia=
ble */
+                            SSEPackedSingle, SSE_CVT_PS>,
+                            TB; /* PD SSE3 form is avaiable */
+}
+
+let Predicates =3D [HasAVX] in {
+  def : Pat<(int_x86_sse_cvtss2si VR128:$src),
+            (VCVTSS2SIrr (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss))>;
+  def : Pat<(int_x86_sse_cvtss2si (load addr:$src)),
+            (VCVTSS2SIrm addr:$src)>;
+  def : Pat<(int_x86_sse_cvtss2si64 VR128:$src),
+            (VCVTSS2SI64rr (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss))>;
+  def : Pat<(int_x86_sse_cvtss2si64 (load addr:$src)),
+            (VCVTSS2SI64rm addr:$src)>;
 }
=20
 let Predicates =3D [HasSSE1] in {
@@ -1550,59 +1672,56 @@
             (CVTSS2SI64rm addr:$src)>;
 }
=20
-let Predicates =3D [HasAVX] in {
-  def : Pat<(int_x86_sse_cvtss2si VR128:$src),
-            (VCVTSS2SIrr (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss))>;
-  def : Pat<(int_x86_sse_cvtss2si (load addr:$src)),
-            (VCVTSS2SIrm addr:$src)>;
-  def : Pat<(int_x86_sse_cvtss2si64 VR128:$src),
-            (VCVTSS2SI64rr (EXTRACT_SUBREG (v4f32 VR128:$src), sub_ss))>;
-  def : Pat<(int_x86_sse_cvtss2si64 (load addr:$src)),
-            (VCVTSS2SI64rm addr:$src)>;
-}
-
 /// SSE 2 Only
=20
 // Convert scalar double to scalar single
 def VCVTSD2SSrr  : VSDI<0x5A, MRMSrcReg, (outs FR32:$dst),
                        (ins FR64:$src1, FR64:$src2),
-                      "cvtsd2ss\t{$src2, $src1, $dst|$dst, $src1, $src2}",=
 []>,
-                      VEX_4V, VEX_LIG;
+                      "cvtsd2ss\t{$src2, $src1, $dst|$dst, $src1, $src2}",=
 [],
+                      IIC_SSE_CVT_Scalar_RR>, VEX_4V, VEX_LIG;
 let mayLoad =3D 1 in
 def VCVTSD2SSrm  : I<0x5A, MRMSrcMem, (outs FR32:$dst),
                        (ins FR64:$src1, f64mem:$src2),
                       "vcvtsd2ss\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-                      []>, XD, Requires<[HasAVX, OptForSize]>, VEX_4V, VEX=
_LIG;
+                      [], IIC_SSE_CVT_Scalar_RM>,
+                      XD, Requires<[HasAVX, OptForSize]>, VEX_4V, VEX_LIG;
=20
 def : Pat<(f32 (fround FR64:$src)), (VCVTSD2SSrr FR64:$src, FR64:$src)>,
           Requires<[HasAVX]>;
=20
 def CVTSD2SSrr  : SDI<0x5A, MRMSrcReg, (outs FR32:$dst), (ins FR64:$src),
                       "cvtsd2ss\t{$src, $dst|$dst, $src}",
-                      [(set FR32:$dst, (fround FR64:$src))]>;
+                      [(set FR32:$dst, (fround FR64:$src))],
+                      IIC_SSE_CVT_Scalar_RR>;
 def CVTSD2SSrm  : I<0x5A, MRMSrcMem, (outs FR32:$dst), (ins f64mem:$src),
                       "cvtsd2ss\t{$src, $dst|$dst, $src}",
-                      [(set FR32:$dst, (fround (loadf64 addr:$src)))]>, XD,
+                      [(set FR32:$dst, (fround (loadf64 addr:$src)))],
+                      IIC_SSE_CVT_Scalar_RM>,
+                      XD,
                   Requires<[HasSSE2, OptForSize]>;
=20
 defm Int_VCVTSD2SS: sse12_cvt_sint_3addr<0x5A, VR128, VR128,
-                      int_x86_sse2_cvtsd2ss, f64mem, load, "cvtsd2ss", 0>,
+                      int_x86_sse2_cvtsd2ss, f64mem, load, "cvtsd2ss",
+                      SSE_CVT_Scalar, 0>,
                       XS, VEX_4V;
 let Constraints =3D "$src1 =3D $dst" in
 defm Int_CVTSD2SS: sse12_cvt_sint_3addr<0x5A, VR128, VR128,
-                      int_x86_sse2_cvtsd2ss, f64mem, load, "cvtsd2ss">, XS;
+                      int_x86_sse2_cvtsd2ss, f64mem, load, "cvtsd2ss",
+                      SSE_CVT_Scalar>, XS;
=20
 // Convert scalar single to scalar double
 // SSE2 instructions with XS prefix
 def VCVTSS2SDrr : I<0x5A, MRMSrcReg, (outs FR64:$dst),
                     (ins FR32:$src1, FR32:$src2),
                     "vcvtss2sd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-                    []>, XS, Requires<[HasAVX]>, VEX_4V, VEX_LIG;
+                    [], IIC_SSE_CVT_Scalar_RR>,
+                    XS, Requires<[HasAVX]>, VEX_4V, VEX_LIG;
 let mayLoad =3D 1 in
 def VCVTSS2SDrm : I<0x5A, MRMSrcMem, (outs FR64:$dst),
                     (ins FR32:$src1, f32mem:$src2),
                     "vcvtss2sd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-                    []>, XS, VEX_4V, VEX_LIG, Requires<[HasAVX, OptForSize=
]>;
+                    [], IIC_SSE_CVT_Scalar_RM>,
+                    XS, VEX_4V, VEX_LIG, Requires<[HasAVX, OptForSize]>;
=20
 let Predicates =3D [HasAVX] in {
   def : Pat<(f64 (fextend FR32:$src)),
@@ -1619,11 +1738,13 @@
=20
 def CVTSS2SDrr : I<0x5A, MRMSrcReg, (outs FR64:$dst), (ins FR32:$src),
                    "cvtss2sd\t{$src, $dst|$dst, $src}",
-                   [(set FR64:$dst, (fextend FR32:$src))]>, XS,
+                   [(set FR64:$dst, (fextend FR32:$src))],
+                   IIC_SSE_CVT_Scalar_RR>, XS,
                  Requires<[HasSSE2]>;
 def CVTSS2SDrm : I<0x5A, MRMSrcMem, (outs FR64:$dst), (ins f32mem:$src),
                    "cvtss2sd\t{$src, $dst|$dst, $src}",
-                   [(set FR64:$dst, (extloadf32 addr:$src))]>, XS,
+                   [(set FR64:$dst, (extloadf32 addr:$src))],
+                   IIC_SSE_CVT_Scalar_RM>, XS,
                  Requires<[HasSSE2, OptForSize]>;
=20
 // extload f32 -> f64.  This matches load+fextend because we have a hack in
@@ -1640,26 +1761,30 @@
                       (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
                     "vcvtss2sd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                     [(set VR128:$dst, (int_x86_sse2_cvtss2sd VR128:$src1,
-                                       VR128:$src2))]>, XS, VEX_4V,
+                                       VR128:$src2))],
+                                       IIC_SSE_CVT_Scalar_RR>, XS, VEX_4V,
                     Requires<[HasAVX]>;
 def Int_VCVTSS2SDrm: I<0x5A, MRMSrcMem,
                       (outs VR128:$dst), (ins VR128:$src1, f32mem:$src2),
                     "vcvtss2sd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                     [(set VR128:$dst, (int_x86_sse2_cvtss2sd VR128:$src1,
-                                       (load addr:$src2)))]>, XS, VEX_4V,
+                                       (load addr:$src2)))],
+                                       IIC_SSE_CVT_Scalar_RM>, XS, VEX_4V,
                     Requires<[HasAVX]>;
 let Constraints =3D "$src1 =3D $dst" in { // SSE2 instructions with XS pre=
fix
 def Int_CVTSS2SDrr: I<0x5A, MRMSrcReg,
                       (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
                     "cvtss2sd\t{$src2, $dst|$dst, $src2}",
                     [(set VR128:$dst, (int_x86_sse2_cvtss2sd VR128:$src1,
-                                       VR128:$src2))]>, XS,
+                                       VR128:$src2))],
+                                       IIC_SSE_CVT_Scalar_RR>, XS,
                     Requires<[HasSSE2]>;
 def Int_CVTSS2SDrm: I<0x5A, MRMSrcMem,
                       (outs VR128:$dst), (ins VR128:$src1, f32mem:$src2),
                     "cvtss2sd\t{$src2, $dst|$dst, $src2}",
                     [(set VR128:$dst, (int_x86_sse2_cvtss2sd VR128:$src1,
-                                       (load addr:$src2)))]>, XS,
+                                       (load addr:$src2)))],
+                                       IIC_SSE_CVT_Scalar_RM>, XS,
                     Requires<[HasSSE2]>;
 }
=20
@@ -1667,216 +1792,275 @@
 // SSE2 instructions without OpSize prefix
 def Int_VCVTDQ2PSrr : I<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
                        "vcvtdq2ps\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtdq2ps VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtdq2ps VR128:$src=
))],
+                       IIC_SSE_CVT_PS_RR>,
                      TB, VEX, Requires<[HasAVX]>;
 def Int_VCVTDQ2PSrm : I<0x5B, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$=
src),
                       "vcvtdq2ps\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst, (int_x86_sse2_cvtdq2ps
-                                        (bitconvert (memopv2i64 addr:$src)=
)))]>,
+                                        (bitconvert (memopv2i64 addr:$src)=
)))],
+                                        IIC_SSE_CVT_PS_RM>,
                      TB, VEX, Requires<[HasAVX]>;
 def Int_CVTDQ2PSrr : I<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
                        "cvtdq2ps\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtdq2ps VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtdq2ps VR128:$src=
))],
+                       IIC_SSE_CVT_PS_RR>,
                      TB, Requires<[HasSSE2]>;
 def Int_CVTDQ2PSrm : I<0x5B, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$s=
rc),
                       "cvtdq2ps\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst, (int_x86_sse2_cvtdq2ps
-                                        (bitconvert (memopv2i64 addr:$src)=
)))]>,
+                                        (bitconvert (memopv2i64 addr:$src)=
)))],
+                                        IIC_SSE_CVT_PS_RM>,
                      TB, Requires<[HasSSE2]>;
=20
 // FIXME: why the non-intrinsic version is described as SSE3?
 // SSE2 instructions with XS prefix
 def Int_VCVTDQ2PDrr : I<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
                        "vcvtdq2pd\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtdq2pd VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtdq2pd VR128:$src=
))],
+                       IIC_SSE_CVT_PD_RR>,
                      XS, VEX, Requires<[HasAVX]>;
 def Int_VCVTDQ2PDrm : I<0xE6, MRMSrcMem, (outs VR128:$dst), (ins i64mem:$s=
rc),
                        "vcvtdq2pd\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (int_x86_sse2_cvtdq2pd
-                                        (bitconvert (memopv2i64 addr:$src)=
)))]>,
+                                        (bitconvert (memopv2i64 addr:$src)=
)))],
+                                        IIC_SSE_CVT_PD_RM>,
                      XS, VEX, Requires<[HasAVX]>;
 def Int_CVTDQ2PDrr : I<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
                        "cvtdq2pd\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtdq2pd VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtdq2pd VR128:$src=
))],
+                       IIC_SSE_CVT_PD_RR>,
                      XS, Requires<[HasSSE2]>;
 def Int_CVTDQ2PDrm : I<0xE6, MRMSrcMem, (outs VR128:$dst), (ins i64mem:$sr=
c),
                      "cvtdq2pd\t{$src, $dst|$dst, $src}",
                      [(set VR128:$dst, (int_x86_sse2_cvtdq2pd
-                                        (bitconvert (memopv2i64 addr:$src)=
)))]>,
+                                        (bitconvert (memopv2i64 addr:$src)=
)))],
+                                        IIC_SSE_CVT_PD_RM>,
                      XS, Requires<[HasSSE2]>;
=20
=20
 // Convert packed single/double fp to doubleword
 def VCVTPS2DQrr : VPDI<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
-                       "cvtps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
+                       "cvtps2dq\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PS_RR>, VEX;
 def VCVTPS2DQrm : VPDI<0x5B, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$s=
rc),
-                       "cvtps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
+                       "cvtps2dq\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PS_RM>, VEX;
 def VCVTPS2DQYrr : VPDI<0x5B, MRMSrcReg, (outs VR256:$dst), (ins VR256:$sr=
c),
-                        "cvtps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "cvtps2dq\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_CVT_PS_RR>, VEX;
 def VCVTPS2DQYrm : VPDI<0x5B, MRMSrcMem, (outs VR256:$dst), (ins f256mem:$=
src),
-                        "cvtps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "cvtps2dq\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_CVT_PS_RM>, VEX;
 def CVTPS2DQrr : PDI<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                     "cvtps2dq\t{$src, $dst|$dst, $src}", []>;
+                     "cvtps2dq\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PS_RR>;
 def CVTPS2DQrm : PDI<0x5B, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$src=
),
-                     "cvtps2dq\t{$src, $dst|$dst, $src}", []>;
+                     "cvtps2dq\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PS_RM>;
=20
 def Int_VCVTPS2DQrr : VPDI<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:=
$src),
                         "cvtps2dq\t{$src, $dst|$dst, $src}",
-                        [(set VR128:$dst, (int_x86_sse2_cvtps2dq VR128:$sr=
c))]>,
+                        [(set VR128:$dst, (int_x86_sse2_cvtps2dq VR128:$sr=
c))],
+                        IIC_SSE_CVT_PS_RR>,
                         VEX;
 def Int_VCVTPS2DQrm : VPDI<0x5B, MRMSrcMem, (outs VR128:$dst),
                          (ins f128mem:$src),
                          "cvtps2dq\t{$src, $dst|$dst, $src}",
                          [(set VR128:$dst, (int_x86_sse2_cvtps2dq
-                                            (memop addr:$src)))]>, VEX;
+                                            (memop addr:$src)))],
+                                            IIC_SSE_CVT_PS_RM>, VEX;
 def Int_CVTPS2DQrr : PDI<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$s=
rc),
                         "cvtps2dq\t{$src, $dst|$dst, $src}",
-                        [(set VR128:$dst, (int_x86_sse2_cvtps2dq VR128:$sr=
c))]>;
+                        [(set VR128:$dst, (int_x86_sse2_cvtps2dq VR128:$sr=
c))],
+                        IIC_SSE_CVT_PS_RR>;
 def Int_CVTPS2DQrm : PDI<0x5B, MRMSrcMem, (outs VR128:$dst), (ins f128mem:=
$src),
                          "cvtps2dq\t{$src, $dst|$dst, $src}",
                          [(set VR128:$dst, (int_x86_sse2_cvtps2dq
-                                            (memop addr:$src)))]>;
+                                            (memop addr:$src)))],
+                                            IIC_SSE_CVT_PS_RM>;
=20
 // SSE2 packed instructions with XD prefix
 def Int_VCVTPD2DQrr : I<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
                        "vcvtpd2dq\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtpd2dq VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtpd2dq VR128:$src=
))],
+                       IIC_SSE_CVT_PD_RR>,
                      XD, VEX, Requires<[HasAVX]>;
 def Int_VCVTPD2DQrm : I<0xE6, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$=
src),
                        "vcvtpd2dq\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (int_x86_sse2_cvtpd2dq
-                                          (memop addr:$src)))]>,
+                                          (memop addr:$src)))],
+                                          IIC_SSE_CVT_PD_RM>,
                      XD, VEX, Requires<[HasAVX]>;
 def Int_CVTPD2DQrr : I<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
                        "cvtpd2dq\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtpd2dq VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtpd2dq VR128:$src=
))],
+                       IIC_SSE_CVT_PD_RR>,
                      XD, Requires<[HasSSE2]>;
 def Int_CVTPD2DQrm : I<0xE6, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$s=
rc),
                        "cvtpd2dq\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (int_x86_sse2_cvtpd2dq
-                                          (memop addr:$src)))]>,
+                                          (memop addr:$src)))],
+                                          IIC_SSE_CVT_PD_RM>,
                      XD, Requires<[HasSSE2]>;
=20
=20
 // Convert with truncation packed single/double fp to doubleword
 // SSE2 packed instructions with XS prefix
 def VCVTTPS2DQrr : VSSI<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
-                      "cvttps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
-let mayLoad =3D 1 in
+                        "cvttps2dq\t{$src, $dst|$dst, $src}",
+                        [(set VR128:$dst,
+                          (int_x86_sse2_cvttps2dq VR128:$src))],
+                          IIC_SSE_CVT_PS_RR>, VEX;
 def VCVTTPS2DQrm : VSSI<0x5B, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$=
src),
-                      "cvttps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "cvttps2dq\t{$src, $dst|$dst, $src}",
+                        [(set VR128:$dst, (int_x86_sse2_cvttps2dq
+                                           (memop addr:$src)))],
+                                           IIC_SSE_CVT_PS_RM>, VEX;
 def VCVTTPS2DQYrr : VSSI<0x5B, MRMSrcReg, (outs VR256:$dst), (ins VR256:$s=
rc),
-                      "cvttps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
-let mayLoad =3D 1 in
+                         "cvttps2dq\t{$src, $dst|$dst, $src}",
+                         [(set VR256:$dst,
+                           (int_x86_avx_cvtt_ps2dq_256 VR256:$src))],
+                           IIC_SSE_CVT_PS_RR>, VEX;
 def VCVTTPS2DQYrm : VSSI<0x5B, MRMSrcMem, (outs VR256:$dst), (ins f256mem:=
$src),
-                      "cvttps2dq\t{$src, $dst|$dst, $src}", []>, VEX;
+                         "cvttps2dq\t{$src, $dst|$dst, $src}",
+                         [(set VR256:$dst, (int_x86_avx_cvtt_ps2dq_256
+                                            (memopv8f32 addr:$src)))],
+                                            IIC_SSE_CVT_PS_RM>, VEX;
+
 def CVTTPS2DQrr : SSI<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                       "cvttps2dq\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst,
-                            (int_x86_sse2_cvttps2dq VR128:$src))]>;
+                            (int_x86_sse2_cvttps2dq VR128:$src))],
+                            IIC_SSE_CVT_PS_RR>;
 def CVTTPS2DQrm : SSI<0x5B, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$sr=
c),
                       "cvttps2dq\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst,
-                            (int_x86_sse2_cvttps2dq (memop addr:$src)))]>;
-
-def Int_VCVTTPS2DQrr : I<0x5B, MRMSrcReg, (outs VR128:$dst), (ins VR128:$s=
rc),
-                        "vcvttps2dq\t{$src, $dst|$dst, $src}",
-                        [(set VR128:$dst,
-                              (int_x86_sse2_cvttps2dq VR128:$src))]>,
-                      XS, VEX, Requires<[HasAVX]>;
-def Int_VCVTTPS2DQrm : I<0x5B, MRMSrcMem, (outs VR128:$dst), (ins f128mem:=
$src),
-                        "vcvttps2dq\t{$src, $dst|$dst, $src}",
-                        [(set VR128:$dst, (int_x86_sse2_cvttps2dq
-                                           (memop addr:$src)))]>,
-                      XS, VEX, Requires<[HasAVX]>;
+                            (int_x86_sse2_cvttps2dq (memop addr:$src)))],
+                            IIC_SSE_CVT_PS_RM>;
+
+let Predicates =3D [HasAVX] in {
+  def : Pat<(v4f32 (sint_to_fp (v4i32 VR128:$src))),
+            (Int_VCVTDQ2PSrr VR128:$src)>;
+  def : Pat<(v4f32 (sint_to_fp (bc_v4i32 (memopv2i64 addr:$src)))),
+            (Int_VCVTDQ2PSrm addr:$src)>;
+
+  def : Pat<(v4i32 (fp_to_sint (v4f32 VR128:$src))),
+            (VCVTTPS2DQrr VR128:$src)>;
+  def : Pat<(v4i32 (fp_to_sint (memopv4f32 addr:$src))),
+            (VCVTTPS2DQrm addr:$src)>;
+
+  def : Pat<(v8f32 (sint_to_fp (v8i32 VR256:$src))),
+            (VCVTDQ2PSYrr VR256:$src)>;
+  def : Pat<(v8f32 (sint_to_fp (bc_v8i32 (memopv4i64 addr:$src)))),
+            (VCVTDQ2PSYrm addr:$src)>;
+
+  def : Pat<(v8i32 (fp_to_sint (v8f32 VR256:$src))),
+            (VCVTTPS2DQYrr VR256:$src)>;
+  def : Pat<(v8i32 (fp_to_sint (memopv8f32 addr:$src))),
+            (VCVTTPS2DQYrm addr:$src)>;
+}
=20
 let Predicates =3D [HasSSE2] in {
   def : Pat<(v4f32 (sint_to_fp (v4i32 VR128:$src))),
             (Int_CVTDQ2PSrr VR128:$src)>;
+  def : Pat<(v4f32 (sint_to_fp (bc_v4i32 (memopv2i64 addr:$src)))),
+            (Int_CVTDQ2PSrm addr:$src)>;
+
   def : Pat<(v4i32 (fp_to_sint (v4f32 VR128:$src))),
             (CVTTPS2DQrr VR128:$src)>;
-}
-
-let Predicates =3D [HasAVX] in {
-  def : Pat<(v4f32 (sint_to_fp (v4i32 VR128:$src))),
-            (Int_VCVTDQ2PSrr VR128:$src)>;
-  def : Pat<(v4i32 (fp_to_sint (v4f32 VR128:$src))),
-            (VCVTTPS2DQrr VR128:$src)>;
-  def : Pat<(v8f32 (sint_to_fp (v8i32 VR256:$src))),
-            (VCVTDQ2PSYrr VR256:$src)>;
-  def : Pat<(v8i32 (fp_to_sint (v8f32 VR256:$src))),
-            (VCVTTPS2DQYrr VR256:$src)>;
+  def : Pat<(v4i32 (fp_to_sint (memopv4f32 addr:$src))),
+            (CVTTPS2DQrm addr:$src)>;
 }
=20
 def VCVTTPD2DQrr : VPDI<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
                         "cvttpd2dq\t{$src, $dst|$dst, $src}",
                         [(set VR128:$dst,
-                              (int_x86_sse2_cvttpd2dq VR128:$src))]>, VEX;
+                              (int_x86_sse2_cvttpd2dq VR128:$src))],
+                              IIC_SSE_CVT_PD_RR>, VEX;
 let isCodeGenOnly =3D 1 in
 def VCVTTPD2DQrm : VPDI<0xE6, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$=
src),
                         "cvttpd2dq\t{$src, $dst|$dst, $src}",
                         [(set VR128:$dst, (int_x86_sse2_cvttpd2dq
-                                               (memop addr:$src)))]>, VEX;
+                                               (memop addr:$src)))],
+                                               IIC_SSE_CVT_PD_RM>, VEX;
 def CVTTPD2DQrr : PDI<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                       "cvttpd2dq\t{$src, $dst|$dst, $src}",
-                      [(set VR128:$dst, (int_x86_sse2_cvttpd2dq VR128:$src=
))]>;
+                      [(set VR128:$dst, (int_x86_sse2_cvttpd2dq VR128:$src=
))],
+                      IIC_SSE_CVT_PD_RR>;
 def CVTTPD2DQrm : PDI<0xE6, MRMSrcMem, (outs VR128:$dst),(ins f128mem:$src=
),
                       "cvttpd2dq\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst, (int_x86_sse2_cvttpd2dq
-                                        (memop addr:$src)))]>;
+                                        (memop addr:$src)))],
+                                        IIC_SSE_CVT_PD_RM>;
=20
 // The assembler can recognize rr 256-bit instructions by seeing a ymm
 // register, but the same isn't true when using memory operands instead.
 // Provide other assembly rr and rm forms to address this explicitly.
 def VCVTTPD2DQXrYr : VPDI<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR256:$=
src),
-                          "cvttpd2dq\t{$src, $dst|$dst, $src}", []>, VEX;
+                          "cvttpd2dq\t{$src, $dst|$dst, $src}", [],
+                          IIC_SSE_CVT_PD_RR>, VEX;
=20
 // XMM only
 def VCVTTPD2DQXrr : VPDI<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$s=
rc),
-                         "cvttpd2dqx\t{$src, $dst|$dst, $src}", []>, VEX;
+                         "cvttpd2dqx\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_CVT_PD_RR>, VEX;
 def VCVTTPD2DQXrm : VPDI<0xE6, MRMSrcMem, (outs VR128:$dst), (ins f128mem:=
$src),
-                         "cvttpd2dqx\t{$src, $dst|$dst, $src}", []>, VEX;
+                         "cvttpd2dqx\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_CVT_PD_RM>, VEX;
=20
 // YMM only
 def VCVTTPD2DQYrr : VPDI<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR256:$s=
rc),
-                         "cvttpd2dqy\t{$src, $dst|$dst, $src}", []>, VEX;
+                         "cvttpd2dqy\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_CVT_PD_RR>, VEX;
 def VCVTTPD2DQYrm : VPDI<0xE6, MRMSrcMem, (outs VR128:$dst), (ins f256mem:=
$src),
-                         "cvttpd2dqy\t{$src, $dst|$dst, $src}", []>, VEX, =
VEX_L;
+                         "cvttpd2dqy\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_CVT_PD_RM>, VEX, VEX_L;
=20
 // Convert packed single to packed double
 let Predicates =3D [HasAVX] in {
                   // SSE2 instructions without OpSize prefix
 def VCVTPS2PDrr : I<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                     "vcvtps2pd\t{$src, $dst|$dst, $src}", []>, TB, VEX;
+                     "vcvtps2pd\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PD_RR>, TB, VEX;
 def VCVTPS2PDrm : I<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f64mem:$src),
-                     "vcvtps2pd\t{$src, $dst|$dst, $src}", []>, TB, VEX;
+                     "vcvtps2pd\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PD_RM>, TB, VEX;
 def VCVTPS2PDYrr : I<0x5A, MRMSrcReg, (outs VR256:$dst), (ins VR128:$src),
-                     "vcvtps2pd\t{$src, $dst|$dst, $src}", []>, TB, VEX;
+                     "vcvtps2pd\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PD_RR>, TB, VEX;
 def VCVTPS2PDYrm : I<0x5A, MRMSrcMem, (outs VR256:$dst), (ins f128mem:$src=
),
-                     "vcvtps2pd\t{$src, $dst|$dst, $src}", []>, TB, VEX;
+                     "vcvtps2pd\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PD_RM>, TB, VEX;
 }
 def CVTPS2PDrr : I<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                       "cvtps2pd\t{$src, $dst|$dst, $src}", []>, TB;
+                       "cvtps2pd\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PD_RR>, TB;
 def CVTPS2PDrm : I<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f64mem:$src),
-                       "cvtps2pd\t{$src, $dst|$dst, $src}", []>, TB;
+                       "cvtps2pd\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PD_RM>, TB;
=20
 def Int_VCVTPS2PDrr : I<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
                        "vcvtps2pd\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtps2pd VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtps2pd VR128:$src=
))],
+                       IIC_SSE_CVT_PD_RR>,
                      TB, VEX, Requires<[HasAVX]>;
 def Int_VCVTPS2PDrm : I<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f64mem:$s=
rc),
                        "vcvtps2pd\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (int_x86_sse2_cvtps2pd
-                                          (load addr:$src)))]>,
+                                          (load addr:$src)))],
+                                          IIC_SSE_CVT_PD_RM>,
                      TB, VEX, Requires<[HasAVX]>;
 def Int_CVTPS2PDrr : I<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
                        "cvtps2pd\t{$src, $dst|$dst, $src}",
-                       [(set VR128:$dst, (int_x86_sse2_cvtps2pd VR128:$src=
))]>,
+                       [(set VR128:$dst, (int_x86_sse2_cvtps2pd VR128:$src=
))],
+                       IIC_SSE_CVT_PD_RR>,
                      TB, Requires<[HasSSE2]>;
 def Int_CVTPS2PDrm : I<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f64mem:$sr=
c),
                        "cvtps2pd\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (int_x86_sse2_cvtps2pd
-                                          (load addr:$src)))]>,
+                                          (load addr:$src)))],
+                                          IIC_SSE_CVT_PD_RM>,
                      TB, Requires<[HasSSE2]>;
=20
 // Convert packed double to packed single
@@ -1884,49 +2068,61 @@
 // register, but the same isn't true when using memory operands instead.
 // Provide other assembly rr and rm forms to address this explicitly.
 def VCVTPD2PSrr : VPDI<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
-                       "cvtpd2ps\t{$src, $dst|$dst, $src}", []>, VEX;
+                       "cvtpd2ps\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PD_RR>, VEX;
 def VCVTPD2PSXrYr : VPDI<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR256:$s=
rc),
-                         "cvtpd2ps\t{$src, $dst|$dst, $src}", []>, VEX;
+                         "cvtpd2ps\t{$src, $dst|$dst, $src}", [],
+                         IIC_SSE_CVT_PD_RR>, VEX;
=20
 // XMM only
 def VCVTPD2PSXrr : VPDI<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
-                        "cvtpd2psx\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "cvtpd2psx\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_CVT_PD_RR>, VEX;
 def VCVTPD2PSXrm : VPDI<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$=
src),
-                        "cvtpd2psx\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "cvtpd2psx\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_CVT_PD_RM>, VEX;
=20
 // YMM only
 def VCVTPD2PSYrr : VPDI<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR256:$sr=
c),
-                        "cvtpd2psy\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "cvtpd2psy\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_CVT_PD_RR>, VEX;
 def VCVTPD2PSYrm : VPDI<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f256mem:$=
src),
-                        "cvtpd2psy\t{$src, $dst|$dst, $src}", []>, VEX, VE=
X_L;
+                        "cvtpd2psy\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_CVT_PD_RM>, VEX, VEX_L;
 def CVTPD2PSrr : PDI<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                     "cvtpd2ps\t{$src, $dst|$dst, $src}", []>;
+                     "cvtpd2ps\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PD_RR>;
 def CVTPD2PSrm : PDI<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$src=
),
-                     "cvtpd2ps\t{$src, $dst|$dst, $src}", []>;
+                     "cvtpd2ps\t{$src, $dst|$dst, $src}", [],
+                     IIC_SSE_CVT_PD_RM>;
=20
=20
 def Int_VCVTPD2PSrr : VPDI<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:=
$src),
                          "cvtpd2ps\t{$src, $dst|$dst, $src}",
-                        [(set VR128:$dst, (int_x86_sse2_cvtpd2ps VR128:$sr=
c))]>;
+                        [(set VR128:$dst, (int_x86_sse2_cvtpd2ps VR128:$sr=
c))],
+                        IIC_SSE_CVT_PD_RR>;
 def Int_VCVTPD2PSrm : VPDI<0x5A, MRMSrcMem, (outs VR128:$dst),
                          (ins f128mem:$src),
                          "cvtpd2ps\t{$src, $dst|$dst, $src}",
                          [(set VR128:$dst, (int_x86_sse2_cvtpd2ps
-                                            (memop addr:$src)))]>;
+                                            (memop addr:$src)))],
+                                            IIC_SSE_CVT_PD_RM>;
 def Int_CVTPD2PSrr : PDI<0x5A, MRMSrcReg, (outs VR128:$dst), (ins VR128:$s=
rc),
                          "cvtpd2ps\t{$src, $dst|$dst, $src}",
-                        [(set VR128:$dst, (int_x86_sse2_cvtpd2ps VR128:$sr=
c))]>;
+                        [(set VR128:$dst, (int_x86_sse2_cvtpd2ps VR128:$sr=
c))],
+                        IIC_SSE_CVT_PD_RR>;
 def Int_CVTPD2PSrm : PDI<0x5A, MRMSrcMem, (outs VR128:$dst), (ins f128mem:=
$src),
                          "cvtpd2ps\t{$src, $dst|$dst, $src}",
                          [(set VR128:$dst, (int_x86_sse2_cvtpd2ps
-                                            (memop addr:$src)))]>;
+                                            (memop addr:$src)))],
+                                            IIC_SSE_CVT_PD_RM>;
=20
 // AVX 256-bit register conversion intrinsics
 // FIXME: Migrate SSE conversion intrinsics matching to use patterns as be=
low
 // whenever possible to avoid declaring two versions of each one.
 def : Pat<(int_x86_avx_cvtdq2_ps_256 VR256:$src),
           (VCVTDQ2PSYrr VR256:$src)>;
-def : Pat<(int_x86_avx_cvtdq2_ps_256 (memopv8i32 addr:$src)),
+def : Pat<(int_x86_avx_cvtdq2_ps_256 (bitconvert (memopv4i64 addr:$src))),
           (VCVTDQ2PSYrm addr:$src)>;
=20
 def : Pat<(int_x86_avx_cvt_pd2_ps_256 VR256:$src),
@@ -1949,11 +2145,6 @@
 def : Pat<(int_x86_avx_cvtt_pd2dq_256 (memopv4f64 addr:$src)),
           (VCVTTPD2DQYrm addr:$src)>;
=20
-def : Pat<(int_x86_avx_cvtt_ps2dq_256 VR256:$src),
-          (VCVTTPS2DQYrr VR256:$src)>;
-def : Pat<(int_x86_avx_cvtt_ps2dq_256 (memopv8f32 addr:$src)),
-          (VCVTTPS2DQYrm addr:$src)>;
-
 // Match fround and fextend for 128/256-bit conversions
 def : Pat<(v4f32 (fround (v4f64 VR256:$src))),
           (VCVTPD2PSYrr VR256:$src)>;
@@ -1971,70 +2162,85 @@
=20
 // sse12_cmp_scalar - sse 1 & 2 compare scalar instructions
 multiclass sse12_cmp_scalar<RegisterClass RC, X86MemOperand x86memop,
-                            SDNode OpNode, ValueType VT, PatFrag ld_frag,
-                            string asm, string asm_alt> {
+                            Operand CC, SDNode OpNode, ValueType VT,=20
+                            PatFrag ld_frag, string asm, string asm_alt,
+                            OpndItins itins> {
   def rr : SIi8<0xC2, MRMSrcReg,
-                (outs RC:$dst), (ins RC:$src1, RC:$src2, SSECC:$cc), asm,
-                [(set RC:$dst, (OpNode (VT RC:$src1), RC:$src2, imm:$cc))]=
>;
+                (outs RC:$dst), (ins RC:$src1, RC:$src2, CC:$cc), asm,
+                [(set RC:$dst, (OpNode (VT RC:$src1), RC:$src2, imm:$cc))],
+                itins.rr>;
   def rm : SIi8<0xC2, MRMSrcMem,
-                (outs RC:$dst), (ins RC:$src1, x86memop:$src2, SSECC:$cc),=
 asm,
+                (outs RC:$dst), (ins RC:$src1, x86memop:$src2, CC:$cc), as=
m,
                 [(set RC:$dst, (OpNode (VT RC:$src1),
-                                         (ld_frag addr:$src2), imm:$cc))]>;
+                                         (ld_frag addr:$src2), imm:$cc))],
+                                         itins.rm>;
=20
   // Accept explicit immediate argument form instead of comparison code.
   let neverHasSideEffects =3D 1 in {
     def rr_alt : SIi8<0xC2, MRMSrcReg, (outs RC:$dst),
-                      (ins RC:$src1, RC:$src2, i8imm:$cc), asm_alt, []>;
+                      (ins RC:$src1, RC:$src2, i8imm:$cc), asm_alt, [],
+                      IIC_SSE_ALU_F32S_RR>;
     let mayLoad =3D 1 in
     def rm_alt : SIi8<0xC2, MRMSrcMem, (outs RC:$dst),
-                      (ins RC:$src1, x86memop:$src2, i8imm:$cc), asm_alt, =
[]>;
+                      (ins RC:$src1, x86memop:$src2, i8imm:$cc), asm_alt, =
[],
+                      IIC_SSE_ALU_F32S_RM>;
   }
 }
=20
-defm VCMPSS : sse12_cmp_scalar<FR32, f32mem, X86cmpss, f32, loadf32,
+defm VCMPSS : sse12_cmp_scalar<FR32, f32mem, AVXCC, X86cmpss, f32, loadf32,
                  "cmp${cc}ss\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-                 "cmpss\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}=
">,
+                 "cmpss\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}=
",
+                 SSE_ALU_F32S>,
                  XS, VEX_4V, VEX_LIG;
-defm VCMPSD : sse12_cmp_scalar<FR64, f64mem, X86cmpsd, f64, loadf64,
+defm VCMPSD : sse12_cmp_scalar<FR64, f64mem, AVXCC, X86cmpsd, f64, loadf64,
                  "cmp${cc}sd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-                 "cmpsd\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}=
">,
+                 "cmpsd\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}=
",
+                 SSE_ALU_F32S>, // same latency as 32 bit compare
                  XD, VEX_4V, VEX_LIG;
=20
 let Constraints =3D "$src1 =3D $dst" in {
-  defm CMPSS : sse12_cmp_scalar<FR32, f32mem, X86cmpss, f32, loadf32,
+  defm CMPSS : sse12_cmp_scalar<FR32, f32mem, SSECC, X86cmpss, f32, loadf3=
2,
                   "cmp${cc}ss\t{$src2, $dst|$dst, $src2}",
-                  "cmpss\t{$cc, $src2, $dst|$dst, $src2, $cc}">,
+                  "cmpss\t{$cc, $src2, $dst|$dst, $src2, $cc}", SSE_ALU_F3=
2S>,
                   XS;
-  defm CMPSD : sse12_cmp_scalar<FR64, f64mem, X86cmpsd, f64, loadf64,
+  defm CMPSD : sse12_cmp_scalar<FR64, f64mem, SSECC, X86cmpsd, f64, loadf6=
4,
                   "cmp${cc}sd\t{$src2, $dst|$dst, $src2}",
-                  "cmpsd\t{$cc, $src2, $dst|$dst, $src2, $cc}">,
+                  "cmpsd\t{$cc, $src2, $dst|$dst, $src2, $cc}",
+                  SSE_ALU_F32S>, // same latency as 32 bit compare
                   XD;
 }
=20
-multiclass sse12_cmp_scalar_int<RegisterClass RC, X86MemOperand x86memop,
-                         Intrinsic Int, string asm> {
+multiclass sse12_cmp_scalar_int<X86MemOperand x86memop, Operand CC,
+                         Intrinsic Int, string asm, OpndItins itins> {
   def rr : SIi8<0xC2, MRMSrcReg, (outs VR128:$dst),
-                      (ins VR128:$src1, VR128:$src, SSECC:$cc), asm,
+                      (ins VR128:$src1, VR128:$src, CC:$cc), asm,
                         [(set VR128:$dst, (Int VR128:$src1,
-                                               VR128:$src, imm:$cc))]>;
+                                               VR128:$src, imm:$cc))],
+                                               itins.rr>;
   def rm : SIi8<0xC2, MRMSrcMem, (outs VR128:$dst),
-                      (ins VR128:$src1, f32mem:$src, SSECC:$cc), asm,
+                      (ins VR128:$src1, x86memop:$src, CC:$cc), asm,
                         [(set VR128:$dst, (Int VR128:$src1,
-                                               (load addr:$src), imm:$cc))=
]>;
+                                               (load addr:$src), imm:$cc))=
],
+                                               itins.rm>;
 }
=20
 // Aliases to match intrinsics which expect XMM operand(s).
-defm Int_VCMPSS  : sse12_cmp_scalar_int<VR128, f32mem, int_x86_sse_cmp_ss,
-                     "cmp${cc}ss\t{$src, $src1, $dst|$dst, $src1, $src}">,
+defm Int_VCMPSS  : sse12_cmp_scalar_int<f32mem, AVXCC, int_x86_sse_cmp_ss,
+                     "cmp${cc}ss\t{$src, $src1, $dst|$dst, $src1, $src}",
+                     SSE_ALU_F32S>,
                      XS, VEX_4V;
-defm Int_VCMPSD  : sse12_cmp_scalar_int<VR128, f64mem, int_x86_sse2_cmp_sd,
-                     "cmp${cc}sd\t{$src, $src1, $dst|$dst, $src1, $src}">,
+defm Int_VCMPSD  : sse12_cmp_scalar_int<f64mem, AVXCC, int_x86_sse2_cmp_sd,
+                     "cmp${cc}sd\t{$src, $src1, $dst|$dst, $src1, $src}",
+                     SSE_ALU_F32S>, // same latency as f32
                      XD, VEX_4V;
 let Constraints =3D "$src1 =3D $dst" in {
-  defm Int_CMPSS  : sse12_cmp_scalar_int<VR128, f32mem, int_x86_sse_cmp_ss,
-                       "cmp${cc}ss\t{$src, $dst|$dst, $src}">, XS;
-  defm Int_CMPSD  : sse12_cmp_scalar_int<VR128, f64mem, int_x86_sse2_cmp_s=
d,
-                       "cmp${cc}sd\t{$src, $dst|$dst, $src}">, XD;
+  defm Int_CMPSS  : sse12_cmp_scalar_int<f32mem, SSECC, int_x86_sse_cmp_ss,
+                       "cmp${cc}ss\t{$src, $dst|$dst, $src}",
+                       SSE_ALU_F32S>, XS;
+  defm Int_CMPSD  : sse12_cmp_scalar_int<f64mem, SSECC, int_x86_sse2_cmp_s=
d,
+                       "cmp${cc}sd\t{$src, $dst|$dst, $src}",
+                       SSE_ALU_F32S>, // same latency as f32
+                       XD;
 }
=20
=20
@@ -2044,11 +2250,13 @@
                             PatFrag ld_frag, string OpcodeStr, Domain d> {
   def rr: PI<opc, MRMSrcReg, (outs), (ins RC:$src1, RC:$src2),
                      !strconcat(OpcodeStr, "\t{$src2, $src1|$src1, $src2}"=
),
-                     [(set EFLAGS, (OpNode (vt RC:$src1), RC:$src2))], d>;
+                     [(set EFLAGS, (OpNode (vt RC:$src1), RC:$src2))],
+                     IIC_SSE_COMIS_RR, d>;
   def rm: PI<opc, MRMSrcMem, (outs), (ins RC:$src1, x86memop:$src2),
                      !strconcat(OpcodeStr, "\t{$src2, $src1|$src1, $src2}"=
),
                      [(set EFLAGS, (OpNode (vt RC:$src1),
-                                           (ld_frag addr:$src2)))], d>;
+                                           (ld_frag addr:$src2)))],
+                                           IIC_SSE_COMIS_RM, d>;
 }
=20
 let Defs =3D [EFLAGS] in {
@@ -2098,89 +2306,91 @@
                                   "comisd", SSEPackedDouble>, TB, OpSize;
 } // Defs =3D [EFLAGS]
=20
-// sse12_cmp_packed - sse 1 & 2 compared packed instructions
+// sse12_cmp_packed - sse 1 & 2 compare packed instructions
 multiclass sse12_cmp_packed<RegisterClass RC, X86MemOperand x86memop,
-                            Intrinsic Int, string asm, string asm_alt,
-                            Domain d> {
-  let isAsmParserOnly =3D 1 in {
-    def rri : PIi8<0xC2, MRMSrcReg,
-               (outs RC:$dst), (ins RC:$src1, RC:$src2, SSECC:$cc), asm,
-               [(set RC:$dst, (Int RC:$src1, RC:$src2, imm:$cc))], d>;
-    def rmi : PIi8<0xC2, MRMSrcMem,
-               (outs RC:$dst), (ins RC:$src1, f128mem:$src2, SSECC:$cc), a=
sm,
-               [(set RC:$dst, (Int RC:$src1, (memop addr:$src2), imm:$cc))=
], d>;
+                            Operand CC, Intrinsic Int, string asm,=20
+                            string asm_alt, Domain d> {
+  def rri : PIi8<0xC2, MRMSrcReg,
+             (outs RC:$dst), (ins RC:$src1, RC:$src2, CC:$cc), asm,
+             [(set RC:$dst, (Int RC:$src1, RC:$src2, imm:$cc))],
+             IIC_SSE_CMPP_RR, d>;
+  def rmi : PIi8<0xC2, MRMSrcMem,
+             (outs RC:$dst), (ins RC:$src1, x86memop:$src2, CC:$cc), asm,
+             [(set RC:$dst, (Int RC:$src1, (memop addr:$src2), imm:$cc))],
+             IIC_SSE_CMPP_RM, d>;
+
+  // Accept explicit immediate argument form instead of comparison code.
+  let neverHasSideEffects =3D 1 in {
+    def rri_alt : PIi8<0xC2, MRMSrcReg,
+               (outs RC:$dst), (ins RC:$src1, RC:$src2, i8imm:$cc),
+               asm_alt, [], IIC_SSE_CMPP_RR, d>;
+    def rmi_alt : PIi8<0xC2, MRMSrcMem,
+               (outs RC:$dst), (ins RC:$src1, x86memop:$src2, i8imm:$cc),
+               asm_alt, [], IIC_SSE_CMPP_RM, d>;
   }
-
-  // Accept explicit immediate argument form instead of comparison code.
-  def rri_alt : PIi8<0xC2, MRMSrcReg,
-             (outs RC:$dst), (ins RC:$src1, RC:$src2, i8imm:$cc),
-             asm_alt, [], d>;
-  def rmi_alt : PIi8<0xC2, MRMSrcMem,
-             (outs RC:$dst), (ins RC:$src1, f128mem:$src2, i8imm:$cc),
-             asm_alt, [], d>;
-}
-
-defm VCMPPS : sse12_cmp_packed<VR128, f128mem, int_x86_sse_cmp_ps,
+}
+
+defm VCMPPS : sse12_cmp_packed<VR128, f128mem, AVXCC, int_x86_sse_cmp_ps,
                "cmp${cc}ps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                "cmpps\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}",
                SSEPackedSingle>, TB, VEX_4V;
-defm VCMPPD : sse12_cmp_packed<VR128, f128mem, int_x86_sse2_cmp_pd,
+defm VCMPPD : sse12_cmp_packed<VR128, f128mem, AVXCC, int_x86_sse2_cmp_pd,
                "cmp${cc}pd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                "cmppd\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}",
                SSEPackedDouble>, TB, OpSize, VEX_4V;
-defm VCMPPSY : sse12_cmp_packed<VR256, f256mem, int_x86_avx_cmp_ps_256,
+defm VCMPPSY : sse12_cmp_packed<VR256, f256mem, AVXCC, int_x86_avx_cmp_ps_=
256,
                "cmp${cc}ps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                "cmpps\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}",
                SSEPackedSingle>, TB, VEX_4V;
-defm VCMPPDY : sse12_cmp_packed<VR256, f256mem, int_x86_avx_cmp_pd_256,
+defm VCMPPDY : sse12_cmp_packed<VR256, f256mem, AVXCC, int_x86_avx_cmp_pd_=
256,
                "cmp${cc}pd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                "cmppd\t{$cc, $src2, $src1, $dst|$dst, $src1, $src2, $cc}",
                SSEPackedDouble>, TB, OpSize, VEX_4V;
 let Constraints =3D "$src1 =3D $dst" in {
-  defm CMPPS : sse12_cmp_packed<VR128, f128mem, int_x86_sse_cmp_ps,
+  defm CMPPS : sse12_cmp_packed<VR128, f128mem, SSECC, int_x86_sse_cmp_ps,
                  "cmp${cc}ps\t{$src2, $dst|$dst, $src2}",
                  "cmpps\t{$cc, $src2, $dst|$dst, $src2, $cc}",
                  SSEPackedSingle>, TB;
-  defm CMPPD : sse12_cmp_packed<VR128, f128mem, int_x86_sse2_cmp_pd,
+  defm CMPPD : sse12_cmp_packed<VR128, f128mem, SSECC, int_x86_sse2_cmp_pd,
                  "cmp${cc}pd\t{$src2, $dst|$dst, $src2}",
                  "cmppd\t{$cc, $src2, $dst|$dst, $src2, $cc}",
                  SSEPackedDouble>, TB, OpSize;
 }
=20
+let Predicates =3D [HasAVX] in {
+def : Pat<(v4i32 (X86cmpp (v4f32 VR128:$src1), VR128:$src2, imm:$cc)),
+          (VCMPPSrri (v4f32 VR128:$src1), (v4f32 VR128:$src2), imm:$cc)>;
+def : Pat<(v4i32 (X86cmpp (v4f32 VR128:$src1), (memop addr:$src2), imm:$cc=
)),
+          (VCMPPSrmi (v4f32 VR128:$src1), addr:$src2, imm:$cc)>;
+def : Pat<(v2i64 (X86cmpp (v2f64 VR128:$src1), VR128:$src2, imm:$cc)),
+          (VCMPPDrri VR128:$src1, VR128:$src2, imm:$cc)>;
+def : Pat<(v2i64 (X86cmpp (v2f64 VR128:$src1), (memop addr:$src2), imm:$cc=
)),
+          (VCMPPDrmi VR128:$src1, addr:$src2, imm:$cc)>;
+
+def : Pat<(v8i32 (X86cmpp (v8f32 VR256:$src1), VR256:$src2, imm:$cc)),
+          (VCMPPSYrri (v8f32 VR256:$src1), (v8f32 VR256:$src2), imm:$cc)>;
+def : Pat<(v8i32 (X86cmpp (v8f32 VR256:$src1), (memop addr:$src2), imm:$cc=
)),
+          (VCMPPSYrmi (v8f32 VR256:$src1), addr:$src2, imm:$cc)>;
+def : Pat<(v4i64 (X86cmpp (v4f64 VR256:$src1), VR256:$src2, imm:$cc)),
+          (VCMPPDYrri VR256:$src1, VR256:$src2, imm:$cc)>;
+def : Pat<(v4i64 (X86cmpp (v4f64 VR256:$src1), (memop addr:$src2), imm:$cc=
)),
+          (VCMPPDYrmi VR256:$src1, addr:$src2, imm:$cc)>;
+}
+
 let Predicates =3D [HasSSE1] in {
-def : Pat<(v4i32 (X86cmpps (v4f32 VR128:$src1), VR128:$src2, imm:$cc)),
+def : Pat<(v4i32 (X86cmpp (v4f32 VR128:$src1), VR128:$src2, imm:$cc)),
           (CMPPSrri (v4f32 VR128:$src1), (v4f32 VR128:$src2), imm:$cc)>;
-def : Pat<(v4i32 (X86cmpps (v4f32 VR128:$src1), (memop addr:$src2), imm:$c=
c)),
+def : Pat<(v4i32 (X86cmpp (v4f32 VR128:$src1), (memop addr:$src2), imm:$cc=
)),
           (CMPPSrmi (v4f32 VR128:$src1), addr:$src2, imm:$cc)>;
 }
=20
 let Predicates =3D [HasSSE2] in {
-def : Pat<(v2i64 (X86cmppd (v2f64 VR128:$src1), VR128:$src2, imm:$cc)),
+def : Pat<(v2i64 (X86cmpp (v2f64 VR128:$src1), VR128:$src2, imm:$cc)),
           (CMPPDrri VR128:$src1, VR128:$src2, imm:$cc)>;
-def : Pat<(v2i64 (X86cmppd (v2f64 VR128:$src1), (memop addr:$src2), imm:$c=
c)),
+def : Pat<(v2i64 (X86cmpp (v2f64 VR128:$src1), (memop addr:$src2), imm:$cc=
)),
           (CMPPDrmi VR128:$src1, addr:$src2, imm:$cc)>;
 }
=20
-let Predicates =3D [HasAVX] in {
-def : Pat<(v4i32 (X86cmpps (v4f32 VR128:$src1), VR128:$src2, imm:$cc)),
-          (VCMPPSrri (v4f32 VR128:$src1), (v4f32 VR128:$src2), imm:$cc)>;
-def : Pat<(v4i32 (X86cmpps (v4f32 VR128:$src1), (memop addr:$src2), imm:$c=
c)),
-          (VCMPPSrmi (v4f32 VR128:$src1), addr:$src2, imm:$cc)>;
-def : Pat<(v2i64 (X86cmppd (v2f64 VR128:$src1), VR128:$src2, imm:$cc)),
-          (VCMPPDrri VR128:$src1, VR128:$src2, imm:$cc)>;
-def : Pat<(v2i64 (X86cmppd (v2f64 VR128:$src1), (memop addr:$src2), imm:$c=
c)),
-          (VCMPPDrmi VR128:$src1, addr:$src2, imm:$cc)>;
-
-def : Pat<(v8i32 (X86cmpps (v8f32 VR256:$src1), VR256:$src2, imm:$cc)),
-          (VCMPPSYrri (v8f32 VR256:$src1), (v8f32 VR256:$src2), imm:$cc)>;
-def : Pat<(v8i32 (X86cmpps (v8f32 VR256:$src1), (memop addr:$src2), imm:$c=
c)),
-          (VCMPPSYrmi (v8f32 VR256:$src1), addr:$src2, imm:$cc)>;
-def : Pat<(v4i64 (X86cmppd (v4f64 VR256:$src1), VR256:$src2, imm:$cc)),
-          (VCMPPDYrri VR256:$src1, VR256:$src2, imm:$cc)>;
-def : Pat<(v4i64 (X86cmppd (v4f64 VR256:$src1), (memop addr:$src2), imm:$c=
c)),
-          (VCMPPDYrmi VR256:$src1, addr:$src2, imm:$cc)>;
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE 1 & 2 - Shuffle Instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2190,14 +2400,14 @@
                          ValueType vt, string asm, PatFrag mem_frag,
                          Domain d, bit IsConvertibleToThreeAddress =3D 0> {
   def rmi : PIi8<0xC6, MRMSrcMem, (outs RC:$dst),
-                   (ins RC:$src1, f128mem:$src2, i8imm:$src3), asm,
-                   [(set RC:$dst, (vt (shufp:$src3
-                            RC:$src1, (mem_frag addr:$src2))))], d>;
+                   (ins RC:$src1, x86memop:$src2, i8imm:$src3), asm,
+                   [(set RC:$dst, (vt (X86Shufp RC:$src1, (mem_frag addr:$=
src2),
+                                       (i8 imm:$src3))))], IIC_SSE_SHUFP, =
d>;
   let isConvertibleToThreeAddress =3D IsConvertibleToThreeAddress in
     def rri : PIi8<0xC6, MRMSrcReg, (outs RC:$dst),
                    (ins RC:$src1, RC:$src2, i8imm:$src3), asm,
-                   [(set RC:$dst,
-                            (vt (shufp:$src3 RC:$src1, RC:$src2)))], d>;
+                   [(set RC:$dst, (vt (X86Shufp RC:$src1, RC:$src2,
+                                       (i8 imm:$src3))))], IIC_SSE_SHUFP, =
d>;
 }
=20
 defm VSHUFPS  : sse12_shuffle<VR128, f128mem, v4f32,
@@ -2220,133 +2430,52 @@
                     TB;
   defm SHUFPD : sse12_shuffle<VR128, f128mem, v2f64,
                     "shufpd\t{$src3, $src2, $dst|$dst, $src2, $src3}",
-                    memopv2f64, SSEPackedDouble>, TB, OpSize;
+                    memopv2f64, SSEPackedDouble, 1 /* cvt to pshufd */>,
+                    TB, OpSize;
+}
+
+let Predicates =3D [HasAVX] in {
+  def : Pat<(v4i32 (X86Shufp VR128:$src1,
+                       (bc_v4i32 (memopv2i64 addr:$src2)), (i8 imm:$imm))),
+            (VSHUFPSrmi VR128:$src1, addr:$src2, imm:$imm)>;
+  def : Pat<(v4i32 (X86Shufp VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+            (VSHUFPSrri VR128:$src1, VR128:$src2, imm:$imm)>;
+
+  def : Pat<(v2i64 (X86Shufp VR128:$src1,
+                       (memopv2i64 addr:$src2), (i8 imm:$imm))),
+            (VSHUFPDrmi VR128:$src1, addr:$src2, imm:$imm)>;
+  def : Pat<(v2i64 (X86Shufp VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+            (VSHUFPDrri VR128:$src1, VR128:$src2, imm:$imm)>;
+
+  // 256-bit patterns
+  def : Pat<(v8i32 (X86Shufp VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+            (VSHUFPSYrri VR256:$src1, VR256:$src2, imm:$imm)>;
+  def : Pat<(v8i32 (X86Shufp VR256:$src1,
+                      (bc_v8i32 (memopv4i64 addr:$src2)), (i8 imm:$imm))),
+            (VSHUFPSYrmi VR256:$src1, addr:$src2, imm:$imm)>;
+
+  def : Pat<(v4i64 (X86Shufp VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+            (VSHUFPDYrri VR256:$src1, VR256:$src2, imm:$imm)>;
+  def : Pat<(v4i64 (X86Shufp VR256:$src1,
+                              (memopv4i64 addr:$src2), (i8 imm:$imm))),
+            (VSHUFPDYrmi VR256:$src1, addr:$src2, imm:$imm)>;
 }
=20
 let Predicates =3D [HasSSE1] in {
-  def : Pat<(v4f32 (X86Shufps VR128:$src1,
-                       (memopv4f32 addr:$src2), (i8 imm:$imm))),
-            (SHUFPSrmi VR128:$src1, addr:$src2, imm:$imm)>;
-  def : Pat<(v4f32 (X86Shufps VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-            (SHUFPSrri VR128:$src1, VR128:$src2, imm:$imm)>;
-  def : Pat<(v4i32 (X86Shufps VR128:$src1,
+  def : Pat<(v4i32 (X86Shufp VR128:$src1,
                        (bc_v4i32 (memopv2i64 addr:$src2)), (i8 imm:$imm))),
             (SHUFPSrmi VR128:$src1, addr:$src2, imm:$imm)>;
-  def : Pat<(v4i32 (X86Shufps VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+  def : Pat<(v4i32 (X86Shufp VR128:$src1, VR128:$src2, (i8 imm:$imm))),
             (SHUFPSrri VR128:$src1, VR128:$src2, imm:$imm)>;
-  // vector_shuffle v1, v2 <4, 5, 2, 3> using SHUFPSrri (we prefer movsd, =
but
-  // fall back to this for SSE1)
-  def : Pat<(v4f32 (movlp:$src3 VR128:$src1, (v4f32 VR128:$src2))),
-            (SHUFPSrri VR128:$src2, VR128:$src1,
-                       (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  // Special unary SHUFPSrri case.
-  def : Pat<(v4f32 (pshufd:$src3 VR128:$src1, (undef))),
-            (SHUFPSrri VR128:$src1, VR128:$src1,
-                       (SHUFFLE_get_shuf_imm VR128:$src3))>;
 }
=20
 let Predicates =3D [HasSSE2] in {
-  // Special binary v4i32 shuffle cases with SHUFPS.
-  def : Pat<(v4i32 (shufp:$src3 VR128:$src1, (v4i32 VR128:$src2))),
-            (SHUFPSrri VR128:$src1, VR128:$src2,
-                       (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  def : Pat<(v4i32 (shufp:$src3 VR128:$src1,
-                                (bc_v4i32 (memopv2i64 addr:$src2)))),
-            (SHUFPSrmi VR128:$src1, addr:$src2,
-                      (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  // Special unary SHUFPDrri cases.
-  def : Pat<(v2i64 (pshufd:$src3 VR128:$src1, (undef))),
-            (SHUFPDrri VR128:$src1, VR128:$src1,
-                       (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  def : Pat<(v2f64 (pshufd:$src3 VR128:$src1, (undef))),
-            (SHUFPDrri VR128:$src1, VR128:$src1,
-                       (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  // Special binary v2i64 shuffle cases using SHUFPDrri.
-  def : Pat<(v2i64 (shufp:$src3 VR128:$src1, VR128:$src2)),
-            (SHUFPDrri VR128:$src1, VR128:$src2,
-                       (SHUFFLE_get_shuf_imm VR128:$src3))>;
   // Generic SHUFPD patterns
-  def : Pat<(v2f64 (X86Shufps VR128:$src1,
-                       (memopv2f64 addr:$src2), (i8 imm:$imm))),
+  def : Pat<(v2i64 (X86Shufp VR128:$src1,
+                       (memopv2i64 addr:$src2), (i8 imm:$imm))),
             (SHUFPDrmi VR128:$src1, addr:$src2, imm:$imm)>;
-  def : Pat<(v2i64 (X86Shufpd VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+  def : Pat<(v2i64 (X86Shufp VR128:$src1, VR128:$src2, (i8 imm:$imm))),
             (SHUFPDrri VR128:$src1, VR128:$src2, imm:$imm)>;
-  def : Pat<(v2f64 (X86Shufpd VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-            (SHUFPDrri VR128:$src1, VR128:$src2, imm:$imm)>;
-}
-
-let Predicates =3D [HasAVX] in {
-  def : Pat<(v4f32 (X86Shufps VR128:$src1,
-                       (memopv4f32 addr:$src2), (i8 imm:$imm))),
-            (VSHUFPSrmi VR128:$src1, addr:$src2, imm:$imm)>;
-  def : Pat<(v4f32 (X86Shufps VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-            (VSHUFPSrri VR128:$src1, VR128:$src2, imm:$imm)>;
-  def : Pat<(v4i32 (X86Shufps VR128:$src1,
-                       (bc_v4i32 (memopv2i64 addr:$src2)), (i8 imm:$imm))),
-            (VSHUFPSrmi VR128:$src1, addr:$src2, imm:$imm)>;
-  def : Pat<(v4i32 (X86Shufps VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-            (VSHUFPSrri VR128:$src1, VR128:$src2, imm:$imm)>;
-  // vector_shuffle v1, v2 <4, 5, 2, 3> using SHUFPSrri (we prefer movsd, =
but
-  // fall back to this for SSE1)
-  def : Pat<(v4f32 (movlp:$src3 VR128:$src1, (v4f32 VR128:$src2))),
-            (VSHUFPSrri VR128:$src2, VR128:$src1,
-                        (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  // Special unary SHUFPSrri case.
-  def : Pat<(v4f32 (pshufd:$src3 VR128:$src1, (undef))),
-            (VSHUFPSrri VR128:$src1, VR128:$src1,
-                        (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  // Special binary v4i32 shuffle cases with SHUFPS.
-  def : Pat<(v4i32 (shufp:$src3 VR128:$src1, (v4i32 VR128:$src2))),
-            (VSHUFPSrri VR128:$src1, VR128:$src2,
-                        (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  def : Pat<(v4i32 (shufp:$src3 VR128:$src1,
-                                (bc_v4i32 (memopv2i64 addr:$src2)))),
-            (VSHUFPSrmi VR128:$src1, addr:$src2,
-                        (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  // Special unary SHUFPDrri cases.
-  def : Pat<(v2i64 (pshufd:$src3 VR128:$src1, (undef))),
-            (VSHUFPDrri VR128:$src1, VR128:$src1,
-                        (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  def : Pat<(v2f64 (pshufd:$src3 VR128:$src1, (undef))),
-            (VSHUFPDrri VR128:$src1, VR128:$src1,
-                        (SHUFFLE_get_shuf_imm VR128:$src3))>;
-  // Special binary v2i64 shuffle cases using SHUFPDrri.
-  def : Pat<(v2i64 (shufp:$src3 VR128:$src1, VR128:$src2)),
-            (VSHUFPDrri VR128:$src1, VR128:$src2,
-                        (SHUFFLE_get_shuf_imm VR128:$src3))>;
-
-  def : Pat<(v2f64 (X86Shufps VR128:$src1,
-                       (memopv2f64 addr:$src2), (i8 imm:$imm))),
-            (VSHUFPDrmi VR128:$src1, addr:$src2, imm:$imm)>;
-  def : Pat<(v2i64 (X86Shufpd VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-            (VSHUFPDrri VR128:$src1, VR128:$src2, imm:$imm)>;
-  def : Pat<(v2f64 (X86Shufpd VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-            (VSHUFPDrri VR128:$src1, VR128:$src2, imm:$imm)>;
-
-  // 256-bit patterns
-  def : Pat<(v8i32 (X86Shufps VR256:$src1, VR256:$src2, (i8 imm:$imm))),
-            (VSHUFPSYrri VR256:$src1, VR256:$src2, imm:$imm)>;
-  def : Pat<(v8i32 (X86Shufps VR256:$src1,
-                      (bc_v8i32 (memopv4i64 addr:$src2)), (i8 imm:$imm))),
-            (VSHUFPSYrmi VR256:$src1, addr:$src2, imm:$imm)>;
-
-  def : Pat<(v8f32 (X86Shufps VR256:$src1, VR256:$src2, (i8 imm:$imm))),
-            (VSHUFPSYrri VR256:$src1, VR256:$src2, imm:$imm)>;
-  def : Pat<(v8f32 (X86Shufps VR256:$src1,
-                              (memopv8f32 addr:$src2), (i8 imm:$imm))),
-            (VSHUFPSYrmi VR256:$src1, addr:$src2, imm:$imm)>;
-
-  def : Pat<(v4i64 (X86Shufpd VR256:$src1, VR256:$src2, (i8 imm:$imm))),
-            (VSHUFPDYrri VR256:$src1, VR256:$src2, imm:$imm)>;
-  def : Pat<(v4i64 (X86Shufpd VR256:$src1,
-                              (memopv4i64 addr:$src2), (i8 imm:$imm))),
-            (VSHUFPDYrmi VR256:$src1, addr:$src2, imm:$imm)>;
-
-  def : Pat<(v4f64 (X86Shufpd VR256:$src1, VR256:$src2, (i8 imm:$imm))),
-            (VSHUFPDYrri VR256:$src1, VR256:$src2, imm:$imm)>;
-  def : Pat<(v4f64 (X86Shufpd VR256:$src1,
-                              (memopv4f64 addr:$src2), (i8 imm:$imm))),
-            (VSHUFPDYrmi VR256:$src1, addr:$src2, imm:$imm)>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2354,159 +2483,80 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 /// sse12_unpack_interleave - sse 1 & 2 unpack and interleave
-multiclass sse12_unpack_interleave<bits<8> opc, PatFrag OpNode, ValueType =
vt,
+multiclass sse12_unpack_interleave<bits<8> opc, SDNode OpNode, ValueType v=
t,
                                    PatFrag mem_frag, RegisterClass RC,
                                    X86MemOperand x86memop, string asm,
                                    Domain d> {
     def rr : PI<opc, MRMSrcReg,
                 (outs RC:$dst), (ins RC:$src1, RC:$src2),
                 asm, [(set RC:$dst,
-                           (vt (OpNode RC:$src1, RC:$src2)))], d>;
+                           (vt (OpNode RC:$src1, RC:$src2)))],
+                           IIC_SSE_UNPCK, d>;
     def rm : PI<opc, MRMSrcMem,
                 (outs RC:$dst), (ins RC:$src1, x86memop:$src2),
                 asm, [(set RC:$dst,
                            (vt (OpNode RC:$src1,
-                                       (mem_frag addr:$src2))))], d>;
-}
-
-let AddedComplexity =3D 10 in {
-  defm VUNPCKHPS: sse12_unpack_interleave<0x15, unpckh, v4f32, memopv4f32,
-        VR128, f128mem, "unpckhps\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedSingle>, TB, VEX_4V;
-  defm VUNPCKHPD: sse12_unpack_interleave<0x15, unpckh, v2f64, memopv2f64,
-        VR128, f128mem, "unpckhpd\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedDouble>, TB, OpSize, VEX_4V;
-  defm VUNPCKLPS: sse12_unpack_interleave<0x14, unpckl, v4f32, memopv4f32,
-        VR128, f128mem, "unpcklps\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedSingle>, TB, VEX_4V;
-  defm VUNPCKLPD: sse12_unpack_interleave<0x14, unpckl, v2f64, memopv2f64,
-        VR128, f128mem, "unpcklpd\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedDouble>, TB, OpSize, VEX_4V;
-
-  defm VUNPCKHPSY: sse12_unpack_interleave<0x15, unpckh, v8f32, memopv8f32,
-        VR256, f256mem, "unpckhps\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedSingle>, TB, VEX_4V;
-  defm VUNPCKHPDY: sse12_unpack_interleave<0x15, unpckh, v4f64, memopv4f64,
-        VR256, f256mem, "unpckhpd\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedDouble>, TB, OpSize, VEX_4V;
-  defm VUNPCKLPSY: sse12_unpack_interleave<0x14, unpckl, v8f32, memopv8f32,
-        VR256, f256mem, "unpcklps\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedSingle>, TB, VEX_4V;
-  defm VUNPCKLPDY: sse12_unpack_interleave<0x14, unpckl, v4f64, memopv4f64,
-        VR256, f256mem, "unpcklpd\t{$src2, $src1, $dst|$dst, $src1, $src2}=
",
-                       SSEPackedDouble>, TB, OpSize, VEX_4V;
-
-  let Constraints =3D "$src1 =3D $dst" in {
-    defm UNPCKHPS: sse12_unpack_interleave<0x15, unpckh, v4f32, memopv4f32,
-          VR128, f128mem, "unpckhps\t{$src2, $dst|$dst, $src2}",
-                         SSEPackedSingle>, TB;
-    defm UNPCKHPD: sse12_unpack_interleave<0x15, unpckh, v2f64, memopv2f64,
-          VR128, f128mem, "unpckhpd\t{$src2, $dst|$dst, $src2}",
-                         SSEPackedDouble>, TB, OpSize;
-    defm UNPCKLPS: sse12_unpack_interleave<0x14, unpckl, v4f32, memopv4f32,
-          VR128, f128mem, "unpcklps\t{$src2, $dst|$dst, $src2}",
-                         SSEPackedSingle>, TB;
-    defm UNPCKLPD: sse12_unpack_interleave<0x14, unpckl, v2f64, memopv2f64,
-          VR128, f128mem, "unpcklpd\t{$src2, $dst|$dst, $src2}",
-                         SSEPackedDouble>, TB, OpSize;
-  } // Constraints =3D "$src1 =3D $dst"
-} // AddedComplexity
-
-let Predicates =3D [HasSSE1] in {
-  def : Pat<(v4f32 (X86Unpcklps VR128:$src1, (memopv4f32 addr:$src2))),
-            (UNPCKLPSrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4f32 (X86Unpcklps VR128:$src1, VR128:$src2)),
-            (UNPCKLPSrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v4f32 (X86Unpckhps VR128:$src1, (memopv4f32 addr:$src2))),
-            (UNPCKHPSrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4f32 (X86Unpckhps VR128:$src1, VR128:$src2)),
-            (UNPCKHPSrr VR128:$src1, VR128:$src2)>;
+                                       (mem_frag addr:$src2))))],
+                                       IIC_SSE_UNPCK, d>;
+}
+
+defm VUNPCKHPS: sse12_unpack_interleave<0x15, X86Unpckh, v4f32, memopv4f32,
+      VR128, f128mem, "unpckhps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedSingle>, TB, VEX_4V;
+defm VUNPCKHPD: sse12_unpack_interleave<0x15, X86Unpckh, v2f64, memopv2f64,
+      VR128, f128mem, "unpckhpd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedDouble>, TB, OpSize, VEX_4V;
+defm VUNPCKLPS: sse12_unpack_interleave<0x14, X86Unpckl, v4f32, memopv4f32,
+      VR128, f128mem, "unpcklps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedSingle>, TB, VEX_4V;
+defm VUNPCKLPD: sse12_unpack_interleave<0x14, X86Unpckl, v2f64, memopv2f64,
+      VR128, f128mem, "unpcklpd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedDouble>, TB, OpSize, VEX_4V;
+
+defm VUNPCKHPSY: sse12_unpack_interleave<0x15, X86Unpckh, v8f32, memopv8f3=
2,
+      VR256, f256mem, "unpckhps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedSingle>, TB, VEX_4V;
+defm VUNPCKHPDY: sse12_unpack_interleave<0x15, X86Unpckh, v4f64, memopv4f6=
4,
+      VR256, f256mem, "unpckhpd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedDouble>, TB, OpSize, VEX_4V;
+defm VUNPCKLPSY: sse12_unpack_interleave<0x14, X86Unpckl, v8f32, memopv8f3=
2,
+      VR256, f256mem, "unpcklps\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedSingle>, TB, VEX_4V;
+defm VUNPCKLPDY: sse12_unpack_interleave<0x14, X86Unpckl, v4f64, memopv4f6=
4,
+      VR256, f256mem, "unpcklpd\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                     SSEPackedDouble>, TB, OpSize, VEX_4V;
+
+let Constraints =3D "$src1 =3D $dst" in {
+  defm UNPCKHPS: sse12_unpack_interleave<0x15, X86Unpckh, v4f32, memopv4f3=
2,
+        VR128, f128mem, "unpckhps\t{$src2, $dst|$dst, $src2}",
+                       SSEPackedSingle>, TB;
+  defm UNPCKHPD: sse12_unpack_interleave<0x15, X86Unpckh, v2f64, memopv2f6=
4,
+        VR128, f128mem, "unpckhpd\t{$src2, $dst|$dst, $src2}",
+                       SSEPackedDouble>, TB, OpSize;
+  defm UNPCKLPS: sse12_unpack_interleave<0x14, X86Unpckl, v4f32, memopv4f3=
2,
+        VR128, f128mem, "unpcklps\t{$src2, $dst|$dst, $src2}",
+                       SSEPackedSingle>, TB;
+  defm UNPCKLPD: sse12_unpack_interleave<0x14, X86Unpckl, v2f64, memopv2f6=
4,
+        VR128, f128mem, "unpcklpd\t{$src2, $dst|$dst, $src2}",
+                       SSEPackedDouble>, TB, OpSize;
+} // Constraints =3D "$src1 =3D $dst"
+
+let Predicates =3D [HasAVX], AddedComplexity =3D 1 in {
+  // FIXME: Instead of X86Movddup, there should be a X86Unpckl here, the
+  // problem is during lowering, where it's not possible to recognize the =
load
+  // fold cause it has two uses through a bitcast. One use disappears at i=
sel
+  // time and the fold opportunity reappears.
+  def : Pat<(v2f64 (X86Movddup VR128:$src)),
+            (VUNPCKLPDrr VR128:$src, VR128:$src)>;
 }
=20
 let Predicates =3D [HasSSE2] in {
-  def : Pat<(v2f64 (X86Unpcklpd VR128:$src1, (memopv2f64 addr:$src2))),
-            (UNPCKLPDrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2f64 (X86Unpcklpd VR128:$src1, VR128:$src2)),
-            (UNPCKLPDrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2f64 (X86Unpckhpd VR128:$src1, (memopv2f64 addr:$src2))),
-            (UNPCKHPDrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2f64 (X86Unpckhpd VR128:$src1, VR128:$src2)),
-            (UNPCKHPDrr VR128:$src1, VR128:$src2)>;
-
-  // FIXME: Instead of X86Movddup, there should be a X86Unpcklpd here, the
+  // FIXME: Instead of X86Movddup, there should be a X86Unpckl here, the
   // problem is during lowering, where it's not possible to recognize the =
load
   // fold cause it has two uses through a bitcast. One use disappears at i=
sel
   // time and the fold opportunity reappears.
   def : Pat<(v2f64 (X86Movddup VR128:$src)),
             (UNPCKLPDrr VR128:$src, VR128:$src)>;
-
-  let AddedComplexity =3D 10 in
-  def : Pat<(splat_lo (v2f64 VR128:$src), (undef)),
-            (UNPCKLPDrr VR128:$src, VR128:$src)>;
-}
-
-let Predicates =3D [HasAVX] in {
-  def : Pat<(v4f32 (X86Unpcklps VR128:$src1, (memopv4f32 addr:$src2))),
-            (VUNPCKLPSrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4f32 (X86Unpcklps VR128:$src1, VR128:$src2)),
-            (VUNPCKLPSrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v4f32 (X86Unpckhps VR128:$src1, (memopv4f32 addr:$src2))),
-            (VUNPCKHPSrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4f32 (X86Unpckhps VR128:$src1, VR128:$src2)),
-            (VUNPCKHPSrr VR128:$src1, VR128:$src2)>;
-
-  def : Pat<(v8f32 (X86Unpcklpsy VR256:$src1, (memopv8f32 addr:$src2))),
-            (VUNPCKLPSYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v8f32 (X86Unpcklpsy VR256:$src1, VR256:$src2)),
-            (VUNPCKLPSYrr VR256:$src1, VR256:$src2)>;
-  def : Pat<(v8i32 (X86Unpcklpsy VR256:$src1, VR256:$src2)),
-            (VUNPCKLPSYrr VR256:$src1, VR256:$src2)>;
-  def : Pat<(v8i32 (X86Unpcklpsy VR256:$src1, (memopv8i32 addr:$src2))),
-            (VUNPCKLPSYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v8f32 (X86Unpckhpsy VR256:$src1, (memopv8f32 addr:$src2))),
-            (VUNPCKHPSYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v8f32 (X86Unpckhpsy VR256:$src1, VR256:$src2)),
-            (VUNPCKHPSYrr VR256:$src1, VR256:$src2)>;
-  def : Pat<(v8i32 (X86Unpckhpsy VR256:$src1, (memopv8i32 addr:$src2))),
-            (VUNPCKHPSYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v8i32 (X86Unpckhpsy VR256:$src1, VR256:$src2)),
-            (VUNPCKHPSYrr VR256:$src1, VR256:$src2)>;
-
-  def : Pat<(v2f64 (X86Unpcklpd VR128:$src1, (memopv2f64 addr:$src2))),
-            (VUNPCKLPDrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2f64 (X86Unpcklpd VR128:$src1, VR128:$src2)),
-            (VUNPCKLPDrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2f64 (X86Unpckhpd VR128:$src1, (memopv2f64 addr:$src2))),
-            (VUNPCKHPDrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2f64 (X86Unpckhpd VR128:$src1, VR128:$src2)),
-            (VUNPCKHPDrr VR128:$src1, VR128:$src2)>;
-
-  def : Pat<(v4f64 (X86Unpcklpdy VR256:$src1, (memopv4f64 addr:$src2))),
-            (VUNPCKLPDYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v4f64 (X86Unpcklpdy VR256:$src1, VR256:$src2)),
-            (VUNPCKLPDYrr VR256:$src1, VR256:$src2)>;
-  def : Pat<(v4i64 (X86Unpcklpdy VR256:$src1, (memopv4i64 addr:$src2))),
-            (VUNPCKLPDYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v4i64 (X86Unpcklpdy VR256:$src1, VR256:$src2)),
-            (VUNPCKLPDYrr VR256:$src1, VR256:$src2)>;
-  def : Pat<(v4f64 (X86Unpckhpdy VR256:$src1, (memopv4f64 addr:$src2))),
-            (VUNPCKHPDYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v4f64 (X86Unpckhpdy VR256:$src1, VR256:$src2)),
-            (VUNPCKHPDYrr VR256:$src1, VR256:$src2)>;
-  def : Pat<(v4i64 (X86Unpckhpdy VR256:$src1, (memopv4i64 addr:$src2))),
-            (VUNPCKHPDYrm VR256:$src1, addr:$src2)>;
-  def : Pat<(v4i64 (X86Unpckhpdy VR256:$src1, VR256:$src2)),
-            (VUNPCKHPDYrr VR256:$src1, VR256:$src2)>;
-
-  // FIXME: Instead of X86Movddup, there should be a X86Unpcklpd here, the
-  // problem is during lowering, where it's not possible to recognize the =
load
-  // fold cause it has two uses through a bitcast. One use disappears at i=
sel
-  // time and the fold opportunity reappears.
-  def : Pat<(v2f64 (X86Movddup VR128:$src)),
-            (VUNPCKLPDrr VR128:$src, VR128:$src)>;
-  let AddedComplexity =3D 10 in
-  def : Pat<(splat_lo (v2f64 VR128:$src), (undef)),
-            (VUNPCKLPDrr VR128:$src, VR128:$src)>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2518,9 +2568,52 @@
                                 Domain d> {
   def rr32 : PI<0x50, MRMSrcReg, (outs GR32:$dst), (ins RC:$src),
                 !strconcat(asm, "\t{$src, $dst|$dst, $src}"),
-                     [(set GR32:$dst, (Int RC:$src))], d>;
+                     [(set GR32:$dst, (Int RC:$src))], IIC_SSE_MOVMSK, d>;
   def rr64 : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins RC:$src),
-                !strconcat(asm, "\t{$src, $dst|$dst, $src}"), [], d>, REX_=
W;
+                !strconcat(asm, "\t{$src, $dst|$dst, $src}"), [],
+                IIC_SSE_MOVMSK, d>, REX_W;
+}
+
+let Predicates =3D [HasAVX] in {
+  defm VMOVMSKPS : sse12_extr_sign_mask<VR128, int_x86_sse_movmsk_ps,
+                                        "movmskps", SSEPackedSingle>, TB, =
VEX;
+  defm VMOVMSKPD : sse12_extr_sign_mask<VR128, int_x86_sse2_movmsk_pd,
+                                        "movmskpd", SSEPackedDouble>, TB,
+                                        OpSize, VEX;
+  defm VMOVMSKPSY : sse12_extr_sign_mask<VR256, int_x86_avx_movmsk_ps_256,
+                                        "movmskps", SSEPackedSingle>, TB, =
VEX;
+  defm VMOVMSKPDY : sse12_extr_sign_mask<VR256, int_x86_avx_movmsk_pd_256,
+                                        "movmskpd", SSEPackedDouble>, TB,
+                                        OpSize, VEX;
+
+  def : Pat<(i32 (X86fgetsign FR32:$src)),
+            (VMOVMSKPSrr32 (INSERT_SUBREG (v4f32 (IMPLICIT_DEF)), FR32:$sr=
c,
+                                          sub_ss))>;
+  def : Pat<(i64 (X86fgetsign FR32:$src)),
+            (VMOVMSKPSrr64 (INSERT_SUBREG (v4f32 (IMPLICIT_DEF)), FR32:$sr=
c,
+                                          sub_ss))>;
+  def : Pat<(i32 (X86fgetsign FR64:$src)),
+            (VMOVMSKPDrr32 (INSERT_SUBREG (v2f64 (IMPLICIT_DEF)), FR64:$sr=
c,
+                                          sub_sd))>;
+  def : Pat<(i64 (X86fgetsign FR64:$src)),
+            (VMOVMSKPDrr64 (INSERT_SUBREG (v2f64 (IMPLICIT_DEF)), FR64:$sr=
c,
+                                          sub_sd))>;
+
+  // Assembler Only
+  def VMOVMSKPSr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR128:$sr=
c),
+             "movmskps\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVMSK,
+             SSEPackedSingle>, TB, VEX;
+  def VMOVMSKPDr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR128:$sr=
c),
+             "movmskpd\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVMSK,
+             SSEPackedDouble>, TB,
+             OpSize, VEX;
+  def VMOVMSKPSYr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR256:$s=
rc),
+             "movmskps\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVMSK,
+             SSEPackedSingle>, TB, VEX;
+  def VMOVMSKPDYr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR256:$s=
rc),
+             "movmskpd\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVMSK,
+             SSEPackedDouble>, TB,
+             OpSize, VEX;
 }
=20
 defm MOVMSKPS : sse12_extr_sign_mask<VR128, int_x86_sse_movmsk_ps, "movmsk=
ps",
@@ -2541,42 +2634,70 @@
           (MOVMSKPDrr64 (INSERT_SUBREG (v2f64 (IMPLICIT_DEF)), FR64:$src,
                                        sub_sd))>, Requires<[HasSSE2]>;
=20
+//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+// SSE2 - Packed Integer Logical Instructions
+//=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
+
+let ExeDomain =3D SSEPackedInt in { // SSE integer instructions
+
+/// PDI_binop_rm - Simple SSE2 binary operator.
+multiclass PDI_binop_rm<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                        ValueType OpVT, RegisterClass RC, PatFrag memop_fr=
ag,
+                        X86MemOperand x86memop,
+                        OpndItins itins,
+                        bit IsCommutable =3D 0,
+                        bit Is2Addr =3D 1> {
+  let isCommutable =3D IsCommutable in
+  def rr : PDI<opc, MRMSrcReg, (outs RC:$dst),
+       (ins RC:$src1, RC:$src2),
+       !if(Is2Addr,
+           !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
+           !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
+       [(set RC:$dst, (OpVT (OpNode RC:$src1, RC:$src2)))], itins.rr>;
+  def rm : PDI<opc, MRMSrcMem, (outs RC:$dst),
+       (ins RC:$src1, x86memop:$src2),
+       !if(Is2Addr,
+           !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
+           !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
+       [(set RC:$dst, (OpVT (OpNode RC:$src1,
+                                     (bitconvert (memop_frag addr:$src2)))=
))],
+                                     itins.rm>;
+}
+} // ExeDomain =3D SSEPackedInt
+
+// These are ordered here for pattern ordering requirements with the fp ve=
rsions
+
 let Predicates =3D [HasAVX] in {
-  defm VMOVMSKPS : sse12_extr_sign_mask<VR128, int_x86_sse_movmsk_ps,
-                                        "movmskps", SSEPackedSingle>, TB, =
VEX;
-  defm VMOVMSKPD : sse12_extr_sign_mask<VR128, int_x86_sse2_movmsk_pd,
-                                        "movmskpd", SSEPackedDouble>, TB,
-                                        OpSize, VEX;
-  defm VMOVMSKPSY : sse12_extr_sign_mask<VR256, int_x86_avx_movmsk_ps_256,
-                                        "movmskps", SSEPackedSingle>, TB, =
VEX;
-  defm VMOVMSKPDY : sse12_extr_sign_mask<VR256, int_x86_avx_movmsk_pd_256,
-                                        "movmskpd", SSEPackedDouble>, TB,
-                                        OpSize, VEX;
-
-  def : Pat<(i32 (X86fgetsign FR32:$src)),
-            (VMOVMSKPSrr32 (INSERT_SUBREG (v4f32 (IMPLICIT_DEF)), FR32:$sr=
c,
-                                          sub_ss))>;
-  def : Pat<(i64 (X86fgetsign FR32:$src)),
-            (VMOVMSKPSrr64 (INSERT_SUBREG (v4f32 (IMPLICIT_DEF)), FR32:$sr=
c,
-                                          sub_ss))>;
-  def : Pat<(i32 (X86fgetsign FR64:$src)),
-            (VMOVMSKPDrr32 (INSERT_SUBREG (v2f64 (IMPLICIT_DEF)), FR64:$sr=
c,
-                                          sub_sd))>;
-  def : Pat<(i64 (X86fgetsign FR64:$src)),
-            (VMOVMSKPDrr64 (INSERT_SUBREG (v2f64 (IMPLICIT_DEF)), FR64:$sr=
c,
-                                          sub_sd))>;
-
-  // Assembler Only
-  def VMOVMSKPSr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR128:$sr=
c),
-             "movmskps\t{$src, $dst|$dst, $src}", [], SSEPackedSingle>, TB=
, VEX;
-  def VMOVMSKPDr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR128:$sr=
c),
-             "movmskpd\t{$src, $dst|$dst, $src}", [], SSEPackedDouble>, TB,
-             OpSize, VEX;
-  def VMOVMSKPSYr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR256:$s=
rc),
-             "movmskps\t{$src, $dst|$dst, $src}", [], SSEPackedSingle>, TB=
, VEX;
-  def VMOVMSKPDYr64r : PI<0x50, MRMSrcReg, (outs GR64:$dst), (ins VR256:$s=
rc),
-             "movmskpd\t{$src, $dst|$dst, $src}", [], SSEPackedDouble>, TB,
-             OpSize, VEX;
+defm VPAND : PDI_binop_rm<0xDB, "vpand", and, v2i64, VR128, memopv2i64,
+                          i128mem, SSE_BIT_ITINS_P, 1, 0>, VEX_4V;
+defm VPOR  : PDI_binop_rm<0xEB, "vpor" , or, v2i64, VR128, memopv2i64,
+                          i128mem, SSE_BIT_ITINS_P, 1, 0>, VEX_4V;
+defm VPXOR : PDI_binop_rm<0xEF, "vpxor", xor, v2i64, VR128, memopv2i64,
+                          i128mem, SSE_BIT_ITINS_P, 1, 0>, VEX_4V;
+defm VPANDN : PDI_binop_rm<0xDF, "vpandn", X86andnp, v2i64, VR128, memopv2=
i64,
+                          i128mem, SSE_BIT_ITINS_P, 0, 0>, VEX_4V;
+}
+
+let Constraints =3D "$src1 =3D $dst" in {
+defm PAND : PDI_binop_rm<0xDB, "pand", and, v2i64, VR128, memopv2i64,
+                         i128mem, SSE_BIT_ITINS_P, 1>;
+defm POR  : PDI_binop_rm<0xEB, "por" , or, v2i64, VR128, memopv2i64,
+                         i128mem, SSE_BIT_ITINS_P, 1>;
+defm PXOR : PDI_binop_rm<0xEF, "pxor", xor, v2i64, VR128, memopv2i64,
+                         i128mem, SSE_BIT_ITINS_P, 1>;
+defm PANDN : PDI_binop_rm<0xDF, "pandn", X86andnp, v2i64, VR128, memopv2i6=
4,
+                          i128mem, SSE_BIT_ITINS_P, 0>;
+} // Constraints =3D "$src1 =3D $dst"
+
+let Predicates =3D [HasAVX2] in {
+defm VPANDY : PDI_binop_rm<0xDB, "vpand", and, v4i64, VR256, memopv4i64,
+                           i256mem, SSE_BIT_ITINS_P, 1, 0>, VEX_4V;
+defm VPORY  : PDI_binop_rm<0xEB, "vpor", or, v4i64, VR256, memopv4i64,
+                           i256mem, SSE_BIT_ITINS_P, 1, 0>, VEX_4V;
+defm VPXORY : PDI_binop_rm<0xEF, "vpxor", xor, v4i64, VR256, memopv4i64,
+                           i256mem, SSE_BIT_ITINS_P, 1, 0>, VEX_4V;
+defm VPANDNY : PDI_binop_rm<0xDF, "vpandn", X86andnp, v4i64, VR256, memopv=
4i64,
+                            i256mem, SSE_BIT_ITINS_P, 0, 0>, VEX_4V;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2586,31 +2707,39 @@
 /// sse12_fp_alias_pack_logical - SSE 1 & 2 aliased packed FP logical ops
 ///
 multiclass sse12_fp_alias_pack_logical<bits<8> opc, string OpcodeStr,
-                                       SDNode OpNode> {
+                                       SDNode OpNode, OpndItins itins> {
   defm V#NAME#PS : sse12_fp_packed<opc, !strconcat(OpcodeStr, "ps"), OpNod=
e,
-              FR32, f32, f128mem, memopfsf32, SSEPackedSingle, 0>, TB, VEX=
_4V;
+              FR32, f32, f128mem, memopfsf32, SSEPackedSingle, itins, 0>,
+              TB, VEX_4V;
=20
   defm V#NAME#PD : sse12_fp_packed<opc, !strconcat(OpcodeStr, "pd"), OpNod=
e,
-        FR64, f64, f128mem, memopfsf64, SSEPackedDouble, 0>, TB, OpSize, V=
EX_4V;
+        FR64, f64, f128mem, memopfsf64, SSEPackedDouble, itins, 0>,
+        TB, OpSize, VEX_4V;
=20
   let Constraints =3D "$src1 =3D $dst" in {
     defm PS : sse12_fp_packed<opc, !strconcat(OpcodeStr, "ps"), OpNode, FR=
32,
-                f32, f128mem, memopfsf32, SSEPackedSingle>, TB;
+                f32, f128mem, memopfsf32, SSEPackedSingle, itins>,
+                TB;
=20
     defm PD : sse12_fp_packed<opc, !strconcat(OpcodeStr, "pd"), OpNode, FR=
64,
-                f64, f128mem, memopfsf64, SSEPackedDouble>, TB, OpSize;
+                f64, f128mem, memopfsf64, SSEPackedDouble, itins>,
+                TB, OpSize;
   }
 }
=20
 // Alias bitwise logical operations using SSE logical ops on packed FP val=
ues.
 let mayLoad =3D 0 in {
-  defm FsAND  : sse12_fp_alias_pack_logical<0x54, "and", X86fand>;
-  defm FsOR   : sse12_fp_alias_pack_logical<0x56, "or", X86for>;
-  defm FsXOR  : sse12_fp_alias_pack_logical<0x57, "xor", X86fxor>;
+  defm FsAND  : sse12_fp_alias_pack_logical<0x54, "and", X86fand,
+                SSE_BIT_ITINS_P>;
+  defm FsOR   : sse12_fp_alias_pack_logical<0x56, "or", X86for,
+                SSE_BIT_ITINS_P>;
+  defm FsXOR  : sse12_fp_alias_pack_logical<0x57, "xor", X86fxor,
+                SSE_BIT_ITINS_P>;
 }
=20
 let neverHasSideEffects =3D 1, Pattern =3D []<dag>, isCommutable =3D 0 in
-  defm FsANDN : sse12_fp_alias_pack_logical<0x55, "andn", undef>;
+  defm FsANDN : sse12_fp_alias_pack_logical<0x55, "andn", undef,
+                SSE_BIT_ITINS_P>;
=20
 /// sse12_fp_packed_logical - SSE 1 & 2 packed FP logical ops
 ///
@@ -2623,7 +2752,7 @@
   defm V#NAME#PS : sse12_fp_packed_logical_rm<opc, VR128, SSEPackedSingle,
        !strconcat(OpcodeStr, "ps"), f128mem, [],
        [(set VR128:$dst, (OpNode (bc_v2i64 (v4f32 VR128:$src1)),
-                                 (memopv2i64 addr:$src2)))], 0>, TB, VEX_4=
V;
+                                 (memopv2i64 addr:$src2)))], 0, 1>, TB, VE=
X_4V;
=20
   defm V#NAME#PD : sse12_fp_packed_logical_rm<opc, VR128, SSEPackedDouble,
        !strconcat(OpcodeStr, "pd"), f128mem,
@@ -2697,118 +2826,145 @@
 /// FIXME: once all 256-bit intrinsics are matched, cleanup and refactor t=
hose
 /// classes below
 multiclass basic_sse12_fp_binop_s<bits<8> opc, string OpcodeStr, SDNode Op=
Node,
+                                  SizeItins itins,
                                   bit Is2Addr =3D 1> {
   defm SS : sse12_fp_scalar<opc, !strconcat(OpcodeStr, "ss"),
-                            OpNode, FR32, f32mem, Is2Addr>, XS;
+                            OpNode, FR32, f32mem,
+                            itins.s, Is2Addr>, XS;
   defm SD : sse12_fp_scalar<opc, !strconcat(OpcodeStr, "sd"),
-                            OpNode, FR64, f64mem, Is2Addr>, XD;
+                            OpNode, FR64, f64mem,
+                            itins.d, Is2Addr>, XD;
 }
=20
 multiclass basic_sse12_fp_binop_p<bits<8> opc, string OpcodeStr, SDNode Op=
Node,
+                                   SizeItins itins,
                                    bit Is2Addr =3D 1> {
   let mayLoad =3D 0 in {
   defm PS : sse12_fp_packed<opc, !strconcat(OpcodeStr, "ps"), OpNode, VR12=
8,
-              v4f32, f128mem, memopv4f32, SSEPackedSingle, Is2Addr>, TB;
+              v4f32, f128mem, memopv4f32, SSEPackedSingle, itins.s, Is2Add=
r>,
+              TB;
   defm PD : sse12_fp_packed<opc, !strconcat(OpcodeStr, "pd"), OpNode, VR12=
8,
-              v2f64, f128mem, memopv2f64, SSEPackedDouble, Is2Addr>, TB, O=
pSize;
+              v2f64, f128mem, memopv2f64, SSEPackedDouble, itins.d, Is2Add=
r>,
+              TB, OpSize;
   }
 }
=20
 multiclass basic_sse12_fp_binop_p_y<bits<8> opc, string OpcodeStr,
-                                    SDNode OpNode> {
+                                    SDNode OpNode,
+                                    SizeItins itins> {
   let mayLoad =3D 0 in {
     defm PSY : sse12_fp_packed<opc, !strconcat(OpcodeStr, "ps"), OpNode, V=
R256,
-                v8f32, f256mem, memopv8f32, SSEPackedSingle, 0>, TB;
+                v8f32, f256mem, memopv8f32, SSEPackedSingle, itins.s, 0>,
+                TB;
     defm PDY : sse12_fp_packed<opc, !strconcat(OpcodeStr, "pd"), OpNode, V=
R256,
-                v4f64, f256mem, memopv4f64, SSEPackedDouble, 0>, TB, OpSiz=
e;
+                v4f64, f256mem, memopv4f64, SSEPackedDouble, itins.d, 0>,
+                TB, OpSize;
   }
 }
=20
 multiclass basic_sse12_fp_binop_s_int<bits<8> opc, string OpcodeStr,
+                                      SizeItins itins,
                                       bit Is2Addr =3D 1> {
   defm SS : sse12_fp_scalar_int<opc, OpcodeStr, VR128,
-     !strconcat(OpcodeStr, "ss"), "", "_ss", ssmem, sse_load_f32, Is2Addr>=
, XS;
+     !strconcat(OpcodeStr, "ss"), "", "_ss", ssmem, sse_load_f32,
+     itins.s, Is2Addr>, XS;
   defm SD : sse12_fp_scalar_int<opc, OpcodeStr, VR128,
-     !strconcat(OpcodeStr, "sd"), "2", "_sd", sdmem, sse_load_f64, Is2Addr=
>, XD;
+     !strconcat(OpcodeStr, "sd"), "2", "_sd", sdmem, sse_load_f64,
+     itins.d, Is2Addr>, XD;
 }
=20
 multiclass basic_sse12_fp_binop_p_int<bits<8> opc, string OpcodeStr,
+                                      SizeItins itins,
                                       bit Is2Addr =3D 1> {
   defm PS : sse12_fp_packed_int<opc, OpcodeStr, VR128,
      !strconcat(OpcodeStr, "ps"), "sse", "_ps", f128mem, memopv4f32,
-                                              SSEPackedSingle, Is2Addr>, T=
B;
+                              SSEPackedSingle, itins.s, Is2Addr>,
+                              TB;
=20
   defm PD : sse12_fp_packed_int<opc, OpcodeStr, VR128,
      !strconcat(OpcodeStr, "pd"), "sse2", "_pd", f128mem, memopv2f64,
-                                      SSEPackedDouble, Is2Addr>, TB, OpSiz=
e;
-}
-
-multiclass basic_sse12_fp_binop_p_y_int<bits<8> opc, string OpcodeStr> {
+                              SSEPackedDouble, itins.d, Is2Addr>,
+                              TB, OpSize;
+}
+
+multiclass basic_sse12_fp_binop_p_y_int<bits<8> opc, string OpcodeStr,
+                                        SizeItins itins> {
   defm PSY : sse12_fp_packed_int<opc, OpcodeStr, VR256,
      !strconcat(OpcodeStr, "ps"), "avx", "_ps_256", f256mem, memopv8f32,
-      SSEPackedSingle, 0>, TB;
+      SSEPackedSingle, itins.s, 0>, TB;
=20
   defm PDY : sse12_fp_packed_int<opc, OpcodeStr, VR256,
      !strconcat(OpcodeStr, "pd"), "avx", "_pd_256", f256mem, memopv4f64,
-      SSEPackedDouble, 0>, TB, OpSize;
+      SSEPackedDouble, itins.d, 0>, TB, OpSize;
 }
=20
 // Binary Arithmetic instructions
-defm VADD : basic_sse12_fp_binop_s<0x58, "add", fadd, 0>,
-            basic_sse12_fp_binop_s_int<0x58, "add", 0>, VEX_4V, VEX_LIG;
-defm VADD : basic_sse12_fp_binop_p<0x58, "add", fadd, 0>,
-            basic_sse12_fp_binop_p_y<0x58, "add", fadd>, VEX_4V;
-defm VMUL : basic_sse12_fp_binop_s<0x59, "mul", fmul, 0>,
-            basic_sse12_fp_binop_s_int<0x59, "mul", 0>, VEX_4V, VEX_LIG;
-defm VMUL : basic_sse12_fp_binop_p<0x59, "mul", fmul, 0>,
-            basic_sse12_fp_binop_p_y<0x59, "mul", fmul>, VEX_4V;
+defm VADD : basic_sse12_fp_binop_s<0x58, "add", fadd, SSE_ALU_ITINS_S, 0>,
+            basic_sse12_fp_binop_s_int<0x58, "add", SSE_ALU_ITINS_S, 0>,
+              VEX_4V, VEX_LIG;
+defm VADD : basic_sse12_fp_binop_p<0x58, "add", fadd, SSE_ALU_ITINS_P, 0>,
+            basic_sse12_fp_binop_p_y<0x58, "add", fadd, SSE_ALU_ITINS_P>,
+              VEX_4V;
+defm VMUL : basic_sse12_fp_binop_s<0x59, "mul", fmul, SSE_MUL_ITINS_S, 0>,
+            basic_sse12_fp_binop_s_int<0x59, "mul", SSE_MUL_ITINS_S, 0>,
+              VEX_4V, VEX_LIG;
+defm VMUL : basic_sse12_fp_binop_p<0x59, "mul", fmul, SSE_MUL_ITINS_P, 0>,
+            basic_sse12_fp_binop_p_y<0x59, "mul", fmul, SSE_MUL_ITINS_P>,
+              VEX_4V;
=20
 let isCommutable =3D 0 in {
-  defm VSUB : basic_sse12_fp_binop_s<0x5C, "sub", fsub, 0>,
-              basic_sse12_fp_binop_s_int<0x5C, "sub", 0>, VEX_4V, VEX_LIG;
-  defm VSUB : basic_sse12_fp_binop_p<0x5C, "sub", fsub, 0>,
-              basic_sse12_fp_binop_p_y<0x5C, "sub", fsub>, VEX_4V;
-  defm VDIV : basic_sse12_fp_binop_s<0x5E, "div", fdiv, 0>,
-              basic_sse12_fp_binop_s_int<0x5E, "div", 0>, VEX_4V, VEX_LIG;
-  defm VDIV : basic_sse12_fp_binop_p<0x5E, "div", fdiv, 0>,
-              basic_sse12_fp_binop_p_y<0x5E, "div", fdiv>, VEX_4V;
-  defm VMAX : basic_sse12_fp_binop_s<0x5F, "max", X86fmax, 0>,
-              basic_sse12_fp_binop_s_int<0x5F, "max", 0>, VEX_4V, VEX_LIG;
-  defm VMAX : basic_sse12_fp_binop_p<0x5F, "max", X86fmax, 0>,
-              basic_sse12_fp_binop_p_int<0x5F, "max", 0>,
-              basic_sse12_fp_binop_p_y<0x5F, "max", X86fmax>,
-              basic_sse12_fp_binop_p_y_int<0x5F, "max">, VEX_4V;
-  defm VMIN : basic_sse12_fp_binop_s<0x5D, "min", X86fmin, 0>,
-              basic_sse12_fp_binop_s_int<0x5D, "min", 0>, VEX_4V, VEX_LIG;
-  defm VMIN : basic_sse12_fp_binop_p<0x5D, "min", X86fmin, 0>,
-              basic_sse12_fp_binop_p_int<0x5D, "min", 0>,
-              basic_sse12_fp_binop_p_y_int<0x5D, "min">,
-              basic_sse12_fp_binop_p_y<0x5D, "min", X86fmin>, VEX_4V;
+  defm VSUB : basic_sse12_fp_binop_s<0x5C, "sub", fsub, SSE_ALU_ITINS_S, 0=
>,
+              basic_sse12_fp_binop_s_int<0x5C, "sub", SSE_ALU_ITINS_S, 0>,
+                VEX_4V, VEX_LIG;
+  defm VSUB : basic_sse12_fp_binop_p<0x5C, "sub", fsub, SSE_ALU_ITINS_P, 0=
>,
+              basic_sse12_fp_binop_p_y<0x5C, "sub", fsub, SSE_ALU_ITINS_P>=
, VEX_4V;
+  defm VDIV : basic_sse12_fp_binop_s<0x5E, "div", fdiv, SSE_DIV_ITINS_S, 0=
>,
+              basic_sse12_fp_binop_s_int<0x5E, "div", SSE_DIV_ITINS_S, 0>,
+                VEX_4V, VEX_LIG;
+  defm VDIV : basic_sse12_fp_binop_p<0x5E, "div", fdiv, SSE_ALU_ITINS_P, 0=
>,
+              basic_sse12_fp_binop_p_y<0x5E, "div", fdiv, SSE_DIV_ITINS_P>,
+                VEX_4V;
+  defm VMAX : basic_sse12_fp_binop_s<0x5F, "max", X86fmax, SSE_ALU_ITINS_S=
, 0>,
+              basic_sse12_fp_binop_s_int<0x5F, "max", SSE_ALU_ITINS_S, 0>,
+                VEX_4V, VEX_LIG;
+  defm VMAX : basic_sse12_fp_binop_p<0x5F, "max", X86fmax, SSE_ALU_ITINS_P=
, 0>,
+              basic_sse12_fp_binop_p_int<0x5F, "max", SSE_ALU_ITINS_P, 0>,
+              basic_sse12_fp_binop_p_y<0x5F, "max", X86fmax, SSE_ALU_ITINS=
_P>,
+              basic_sse12_fp_binop_p_y_int<0x5F, "max", SSE_ALU_ITINS_P>,
+                VEX_4V;
+  defm VMIN : basic_sse12_fp_binop_s<0x5D, "min", X86fmin, SSE_ALU_ITINS_S=
, 0>,
+              basic_sse12_fp_binop_s_int<0x5D, "min", SSE_ALU_ITINS_S, 0>,
+                VEX_4V, VEX_LIG;
+  defm VMIN : basic_sse12_fp_binop_p<0x5D, "min", X86fmin, SSE_ALU_ITINS_P=
, 0>,
+              basic_sse12_fp_binop_p_int<0x5D, "min", SSE_ALU_ITINS_P, 0>,
+              basic_sse12_fp_binop_p_y_int<0x5D, "min", SSE_ALU_ITINS_P>,
+              basic_sse12_fp_binop_p_y<0x5D, "min", X86fmin, SSE_ALU_ITINS=
_P>,
+                VEX_4V;
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
-  defm ADD : basic_sse12_fp_binop_s<0x58, "add", fadd>,
-             basic_sse12_fp_binop_p<0x58, "add", fadd>,
-             basic_sse12_fp_binop_s_int<0x58, "add">;
-  defm MUL : basic_sse12_fp_binop_s<0x59, "mul", fmul>,
-             basic_sse12_fp_binop_p<0x59, "mul", fmul>,
-             basic_sse12_fp_binop_s_int<0x59, "mul">;
+  defm ADD : basic_sse12_fp_binop_s<0x58, "add", fadd, SSE_ALU_ITINS_S>,
+             basic_sse12_fp_binop_p<0x58, "add", fadd, SSE_ALU_ITINS_P>,
+             basic_sse12_fp_binop_s_int<0x58, "add", SSE_ALU_ITINS_S>;
+  defm MUL : basic_sse12_fp_binop_s<0x59, "mul", fmul, SSE_MUL_ITINS_S>,
+             basic_sse12_fp_binop_p<0x59, "mul", fmul, SSE_MUL_ITINS_P>,
+             basic_sse12_fp_binop_s_int<0x59, "mul", SSE_MUL_ITINS_S>;
=20
   let isCommutable =3D 0 in {
-    defm SUB : basic_sse12_fp_binop_s<0x5C, "sub", fsub>,
-               basic_sse12_fp_binop_p<0x5C, "sub", fsub>,
-               basic_sse12_fp_binop_s_int<0x5C, "sub">;
-    defm DIV : basic_sse12_fp_binop_s<0x5E, "div", fdiv>,
-               basic_sse12_fp_binop_p<0x5E, "div", fdiv>,
-               basic_sse12_fp_binop_s_int<0x5E, "div">;
-    defm MAX : basic_sse12_fp_binop_s<0x5F, "max", X86fmax>,
-               basic_sse12_fp_binop_p<0x5F, "max", X86fmax>,
-               basic_sse12_fp_binop_s_int<0x5F, "max">,
-               basic_sse12_fp_binop_p_int<0x5F, "max">;
-    defm MIN : basic_sse12_fp_binop_s<0x5D, "min", X86fmin>,
-               basic_sse12_fp_binop_p<0x5D, "min", X86fmin>,
-               basic_sse12_fp_binop_s_int<0x5D, "min">,
-               basic_sse12_fp_binop_p_int<0x5D, "min">;
+    defm SUB : basic_sse12_fp_binop_s<0x5C, "sub", fsub, SSE_ALU_ITINS_S>,
+               basic_sse12_fp_binop_p<0x5C, "sub", fsub, SSE_ALU_ITINS_P>,
+               basic_sse12_fp_binop_s_int<0x5C, "sub", SSE_ALU_ITINS_S>;
+    defm DIV : basic_sse12_fp_binop_s<0x5E, "div", fdiv, SSE_DIV_ITINS_S>,
+               basic_sse12_fp_binop_p<0x5E, "div", fdiv, SSE_DIV_ITINS_P>,
+               basic_sse12_fp_binop_s_int<0x5E, "div", SSE_DIV_ITINS_S>;
+    defm MAX : basic_sse12_fp_binop_s<0x5F, "max", X86fmax, SSE_ALU_ITINS_=
S>,
+               basic_sse12_fp_binop_p<0x5F, "max", X86fmax, SSE_ALU_ITINS_=
P>,
+               basic_sse12_fp_binop_s_int<0x5F, "max", SSE_ALU_ITINS_S>,
+               basic_sse12_fp_binop_p_int<0x5F, "max", SSE_ALU_ITINS_P>;
+    defm MIN : basic_sse12_fp_binop_s<0x5D, "min", X86fmin, SSE_ALU_ITINS_=
S>,
+               basic_sse12_fp_binop_p<0x5D, "min", X86fmin, SSE_ALU_ITINS_=
P>,
+               basic_sse12_fp_binop_s_int<0x5D, "min", SSE_ALU_ITINS_S>,
+               basic_sse12_fp_binop_p_int<0x5D, "min", SSE_ALU_ITINS_P>;
   }
 }
=20
@@ -2820,9 +2976,25 @@
 ///
 /// And, we have a special variant form for a full-vector intrinsic form.
=20
+def SSE_SQRTP : OpndItins<
+  IIC_SSE_SQRTP_RR, IIC_SSE_SQRTP_RM
+>;
+
+def SSE_SQRTS : OpndItins<
+  IIC_SSE_SQRTS_RR, IIC_SSE_SQRTS_RM
+>;
+
+def SSE_RCPP : OpndItins<
+  IIC_SSE_RCPP_RR, IIC_SSE_RCPP_RM
+>;
+
+def SSE_RCPS : OpndItins<
+  IIC_SSE_RCPS_RR, IIC_SSE_RCPS_RM
+>;
+
 /// sse1_fp_unop_s - SSE1 unops in scalar form.
 multiclass sse1_fp_unop_s<bits<8> opc, string OpcodeStr,
-                          SDNode OpNode, Intrinsic F32Int> {
+                          SDNode OpNode, Intrinsic F32Int, OpndItins itins=
> {
   def SSr : SSI<opc, MRMSrcReg, (outs FR32:$dst), (ins FR32:$src),
                 !strconcat(OpcodeStr, "ss\t{$src, $dst|$dst, $src}"),
                 [(set FR32:$dst, (OpNode FR32:$src))]>;
@@ -2832,14 +3004,14 @@
   // partial register update condition.
   def SSm : I<opc, MRMSrcMem, (outs FR32:$dst), (ins f32mem:$src),
                 !strconcat(OpcodeStr, "ss\t{$src, $dst|$dst, $src}"),
-                [(set FR32:$dst, (OpNode (load addr:$src)))]>, XS,
+                [(set FR32:$dst, (OpNode (load addr:$src)))], itins.rm>, X=
S,
             Requires<[HasSSE1, OptForSize]>;
   def SSr_Int : SSI<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                     !strconcat(OpcodeStr, "ss\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (F32Int VR128:$src))]>;
+                    [(set VR128:$dst, (F32Int VR128:$src))], itins.rr>;
   def SSm_Int : SSI<opc, MRMSrcMem, (outs VR128:$dst), (ins ssmem:$src),
                     !strconcat(OpcodeStr, "ss\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (F32Int sse_load_f32:$src))]>;
+                    [(set VR128:$dst, (F32Int sse_load_f32:$src))], itins.=
rm>;
 }
=20
 /// sse1_fp_unop_s_avx - AVX SSE1 unops in scalar form.
@@ -2852,80 +3024,91 @@
                 !strconcat(OpcodeStr,
                            "ss\t{$src2, $src1, $dst|$dst, $src1, $src2}"),=
 []>;
   def SSm_Int : SSI<opc, MRMSrcMem, (outs VR128:$dst),
-                (ins ssmem:$src1, VR128:$src2),
+                (ins VR128:$src1, ssmem:$src2),
                 !strconcat(OpcodeStr,
                            "ss\t{$src2, $src1, $dst|$dst, $src1, $src2}"),=
 []>;
 }
=20
 /// sse1_fp_unop_p - SSE1 unops in packed form.
-multiclass sse1_fp_unop_p<bits<8> opc, string OpcodeStr, SDNode OpNode> {
+multiclass sse1_fp_unop_p<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                          OpndItins itins> {
   def PSr : PSI<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
               !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-              [(set VR128:$dst, (v4f32 (OpNode VR128:$src)))]>;
+              [(set VR128:$dst, (v4f32 (OpNode VR128:$src)))], itins.rr>;
   def PSm : PSI<opc, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$src),
                 !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-                [(set VR128:$dst, (OpNode (memopv4f32 addr:$src)))]>;
+                [(set VR128:$dst, (OpNode (memopv4f32 addr:$src)))], itins=
.rm>;
 }
=20
 /// sse1_fp_unop_p_y - AVX 256-bit SSE1 unops in packed form.
-multiclass sse1_fp_unop_p_y<bits<8> opc, string OpcodeStr, SDNode OpNode> {
+multiclass sse1_fp_unop_p_y<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                            OpndItins itins> {
   def PSYr : PSI<opc, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
               !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-              [(set VR256:$dst, (v8f32 (OpNode VR256:$src)))]>;
+              [(set VR256:$dst, (v8f32 (OpNode VR256:$src)))],
+              itins.rr>;
   def PSYm : PSI<opc, MRMSrcMem, (outs VR256:$dst), (ins f256mem:$src),
                 !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-                [(set VR256:$dst, (OpNode (memopv8f32 addr:$src)))]>;
+                [(set VR256:$dst, (OpNode (memopv8f32 addr:$src)))],
+                itins.rm>;
 }
=20
 /// sse1_fp_unop_p_int - SSE1 intrinsics unops in packed forms.
 multiclass sse1_fp_unop_p_int<bits<8> opc, string OpcodeStr,
-                              Intrinsic V4F32Int> {
+                              Intrinsic V4F32Int, OpndItins itins> {
   def PSr_Int : PSI<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                     !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (V4F32Int VR128:$src))]>;
+                    [(set VR128:$dst, (V4F32Int VR128:$src))],
+                    itins.rr>;
   def PSm_Int : PSI<opc, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$src),
                     !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (V4F32Int (memopv4f32 addr:$src)))]>;
+                    [(set VR128:$dst, (V4F32Int (memopv4f32 addr:$src)))],
+                    itins.rm>;
 }
=20
 /// sse1_fp_unop_p_y_int - AVX 256-bit intrinsics unops in packed forms.
 multiclass sse1_fp_unop_p_y_int<bits<8> opc, string OpcodeStr,
-                                Intrinsic V4F32Int> {
+                                Intrinsic V4F32Int, OpndItins itins> {
   def PSYr_Int : PSI<opc, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
                     !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-                    [(set VR256:$dst, (V4F32Int VR256:$src))]>;
+                    [(set VR256:$dst, (V4F32Int VR256:$src))],
+                    itins.rr>;
   def PSYm_Int : PSI<opc, MRMSrcMem, (outs VR256:$dst), (ins f256mem:$src),
                     !strconcat(OpcodeStr, "ps\t{$src, $dst|$dst, $src}"),
-                    [(set VR256:$dst, (V4F32Int (memopv8f32 addr:$src)))]>;
+                    [(set VR256:$dst, (V4F32Int (memopv8f32 addr:$src)))],
+                    itins.rm>;
 }
=20
 /// sse2_fp_unop_s - SSE2 unops in scalar form.
 multiclass sse2_fp_unop_s<bits<8> opc, string OpcodeStr,
-                          SDNode OpNode, Intrinsic F64Int> {
+                          SDNode OpNode, Intrinsic F64Int, OpndItins itins=
> {
   def SDr : SDI<opc, MRMSrcReg, (outs FR64:$dst), (ins FR64:$src),
                 !strconcat(OpcodeStr, "sd\t{$src, $dst|$dst, $src}"),
-                [(set FR64:$dst, (OpNode FR64:$src))]>;
+                [(set FR64:$dst, (OpNode FR64:$src))], itins.rr>;
   // See the comments in sse1_fp_unop_s for why this is OptForSize.
   def SDm : I<opc, MRMSrcMem, (outs FR64:$dst), (ins f64mem:$src),
                 !strconcat(OpcodeStr, "sd\t{$src, $dst|$dst, $src}"),
-                [(set FR64:$dst, (OpNode (load addr:$src)))]>, XD,
+                [(set FR64:$dst, (OpNode (load addr:$src)))], itins.rm>, X=
D,
             Requires<[HasSSE2, OptForSize]>;
   def SDr_Int : SDI<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                     !strconcat(OpcodeStr, "sd\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (F64Int VR128:$src))]>;
+                    [(set VR128:$dst, (F64Int VR128:$src))], itins.rr>;
   def SDm_Int : SDI<opc, MRMSrcMem, (outs VR128:$dst), (ins sdmem:$src),
                     !strconcat(OpcodeStr, "sd\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (F64Int sse_load_f64:$src))]>;
+                    [(set VR128:$dst, (F64Int sse_load_f64:$src))], itins.=
rm>;
 }
=20
 /// sse2_fp_unop_s_avx - AVX SSE2 unops in scalar form.
 multiclass sse2_fp_unop_s_avx<bits<8> opc, string OpcodeStr> {
+  let neverHasSideEffects =3D 1 in {
   def SDr : SDI<opc, MRMSrcReg, (outs FR64:$dst), (ins FR64:$src1, FR64:$s=
rc2),
                !strconcat(OpcodeStr,
                           "sd\t{$src2, $src1, $dst|$dst, $src1, $src2}"), =
[]>;
+  let mayLoad =3D 1 in
   def SDm : SDI<opc, MRMSrcMem, (outs FR64:$dst), (ins FR64:$src1,f64mem:$=
src2),
                !strconcat(OpcodeStr,
                           "sd\t{$src2, $src1, $dst|$dst, $src1, $src2}"), =
[]>;
+  }
   def SDm_Int : SDI<opc, MRMSrcMem, (outs VR128:$dst),
                (ins VR128:$src1, sdmem:$src2),
                !strconcat(OpcodeStr,
@@ -2934,45 +3117,52 @@
=20
 /// sse2_fp_unop_p - SSE2 unops in vector forms.
 multiclass sse2_fp_unop_p<bits<8> opc, string OpcodeStr,
-                          SDNode OpNode> {
+                          SDNode OpNode, OpndItins itins> {
   def PDr : PDI<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
               !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-              [(set VR128:$dst, (v2f64 (OpNode VR128:$src)))]>;
+              [(set VR128:$dst, (v2f64 (OpNode VR128:$src)))], itins.rr>;
   def PDm : PDI<opc, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$src),
                 !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-                [(set VR128:$dst, (OpNode (memopv2f64 addr:$src)))]>;
+                [(set VR128:$dst, (OpNode (memopv2f64 addr:$src)))], itins=
.rm>;
 }
=20
 /// sse2_fp_unop_p_y - AVX SSE2 256-bit unops in vector forms.
-multiclass sse2_fp_unop_p_y<bits<8> opc, string OpcodeStr, SDNode OpNode> {
+multiclass sse2_fp_unop_p_y<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                          OpndItins itins> {
   def PDYr : PDI<opc, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
               !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-              [(set VR256:$dst, (v4f64 (OpNode VR256:$src)))]>;
+              [(set VR256:$dst, (v4f64 (OpNode VR256:$src)))],
+              itins.rr>;
   def PDYm : PDI<opc, MRMSrcMem, (outs VR256:$dst), (ins f256mem:$src),
                 !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-                [(set VR256:$dst, (OpNode (memopv4f64 addr:$src)))]>;
+                [(set VR256:$dst, (OpNode (memopv4f64 addr:$src)))],
+                itins.rm>;
 }
=20
 /// sse2_fp_unop_p_int - SSE2 intrinsic unops in vector forms.
 multiclass sse2_fp_unop_p_int<bits<8> opc, string OpcodeStr,
-                              Intrinsic V2F64Int> {
+                              Intrinsic V2F64Int, OpndItins itins> {
   def PDr_Int : PDI<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                     !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (V2F64Int VR128:$src))]>;
+                    [(set VR128:$dst, (V2F64Int VR128:$src))],
+                    itins.rr>;
   def PDm_Int : PDI<opc, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$src),
                     !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (V2F64Int (memopv2f64 addr:$src)))]>;
+                    [(set VR128:$dst, (V2F64Int (memopv2f64 addr:$src)))],
+                    itins.rm>;
 }
=20
 /// sse2_fp_unop_p_y_int - AVX 256-bit intrinsic unops in vector forms.
 multiclass sse2_fp_unop_p_y_int<bits<8> opc, string OpcodeStr,
-                                Intrinsic V2F64Int> {
+                                Intrinsic V2F64Int, OpndItins itins> {
   def PDYr_Int : PDI<opc, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
                     !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-                    [(set VR256:$dst, (V2F64Int VR256:$src))]>;
+                    [(set VR256:$dst, (V2F64Int VR256:$src))],
+                    itins.rr>;
   def PDYm_Int : PDI<opc, MRMSrcMem, (outs VR256:$dst), (ins f256mem:$src),
                     !strconcat(OpcodeStr, "pd\t{$src, $dst|$dst, $src}"),
-                    [(set VR256:$dst, (V2F64Int (memopv4f64 addr:$src)))]>;
+                    [(set VR256:$dst, (V2F64Int (memopv4f64 addr:$src)))],
+                    itins.rm>;
 }
=20
 let Predicates =3D [HasAVX] in {
@@ -2980,31 +3170,40 @@
   defm VSQRT  : sse1_fp_unop_s_avx<0x51, "vsqrt">,
                 sse2_fp_unop_s_avx<0x51, "vsqrt">, VEX_4V, VEX_LIG;
=20
-  defm VSQRT  : sse1_fp_unop_p<0x51, "vsqrt", fsqrt>,
-                sse2_fp_unop_p<0x51, "vsqrt", fsqrt>,
-                sse1_fp_unop_p_y<0x51, "vsqrt", fsqrt>,
-                sse2_fp_unop_p_y<0x51, "vsqrt", fsqrt>,
-                sse1_fp_unop_p_int<0x51, "vsqrt", int_x86_sse_sqrt_ps>,
-                sse2_fp_unop_p_int<0x51, "vsqrt", int_x86_sse2_sqrt_pd>,
-                sse1_fp_unop_p_y_int<0x51, "vsqrt", int_x86_avx_sqrt_ps_25=
6>,
-                sse2_fp_unop_p_y_int<0x51, "vsqrt", int_x86_avx_sqrt_pd_25=
6>,
+  defm VSQRT  : sse1_fp_unop_p<0x51, "vsqrt", fsqrt, SSE_SQRTP>,
+                sse2_fp_unop_p<0x51, "vsqrt", fsqrt, SSE_SQRTP>,
+                sse1_fp_unop_p_y<0x51, "vsqrt", fsqrt, SSE_SQRTP>,
+                sse2_fp_unop_p_y<0x51, "vsqrt", fsqrt, SSE_SQRTP>,
+                sse1_fp_unop_p_int<0x51, "vsqrt", int_x86_sse_sqrt_ps,
+                                   SSE_SQRTP>,
+                sse2_fp_unop_p_int<0x51, "vsqrt", int_x86_sse2_sqrt_pd,
+                                    SSE_SQRTP>,
+                sse1_fp_unop_p_y_int<0x51, "vsqrt", int_x86_avx_sqrt_ps_25=
6,
+                                    SSE_SQRTP>,
+                sse2_fp_unop_p_y_int<0x51, "vsqrt", int_x86_avx_sqrt_pd_25=
6,
+                                    SSE_SQRTP>,
                 VEX;
=20
   // Reciprocal approximations. Note that these typically require refineme=
nt
   // in order to obtain suitable precision.
   defm VRSQRT : sse1_fp_unop_s_avx<0x52, "vrsqrt">, VEX_4V, VEX_LIG;
-  defm VRSQRT : sse1_fp_unop_p<0x52, "vrsqrt", X86frsqrt>,
-                sse1_fp_unop_p_y<0x52, "vrsqrt", X86frsqrt>,
-                sse1_fp_unop_p_y_int<0x52, "vrsqrt", int_x86_avx_rsqrt_ps_=
256>,
-                sse1_fp_unop_p_int<0x52, "vrsqrt", int_x86_sse_rsqrt_ps>, =
VEX;
+  defm VRSQRT : sse1_fp_unop_p<0x52, "vrsqrt", X86frsqrt, SSE_SQRTP>,
+                sse1_fp_unop_p_y<0x52, "vrsqrt", X86frsqrt, SSE_SQRTP>,
+                sse1_fp_unop_p_y_int<0x52, "vrsqrt", int_x86_avx_rsqrt_ps_=
256,
+                                    SSE_SQRTP>,
+                sse1_fp_unop_p_int<0x52, "vrsqrt", int_x86_sse_rsqrt_ps,
+                                    SSE_SQRTP>, VEX;
=20
   defm VRCP   : sse1_fp_unop_s_avx<0x53, "vrcp">, VEX_4V, VEX_LIG;
-  defm VRCP   : sse1_fp_unop_p<0x53, "vrcp", X86frcp>,
-                sse1_fp_unop_p_y<0x53, "vrcp", X86frcp>,
-                sse1_fp_unop_p_y_int<0x53, "vrcp", int_x86_avx_rcp_ps_256>,
-                sse1_fp_unop_p_int<0x53, "vrcp", int_x86_sse_rcp_ps>, VEX;
-}
-
+  defm VRCP   : sse1_fp_unop_p<0x53, "vrcp", X86frcp, SSE_RCPP>,
+                sse1_fp_unop_p_y<0x53, "vrcp", X86frcp, SSE_RCPP>,
+                sse1_fp_unop_p_y_int<0x53, "vrcp", int_x86_avx_rcp_ps_256,
+                                    SSE_RCPP>,
+                sse1_fp_unop_p_int<0x53, "vrcp", int_x86_sse_rcp_ps,
+                                    SSE_RCPP>, VEX;
+}
+
+let AddedComplexity =3D 1 in {
 def : Pat<(f32 (fsqrt FR32:$src)),
           (VSQRTSSr (f32 (IMPLICIT_DEF)), FR32:$src)>, Requires<[HasAVX]>;
 def : Pat<(f32 (fsqrt (load addr:$src))),
@@ -3027,8 +3226,9 @@
 def : Pat<(f32 (X86frcp (load addr:$src))),
           (VRCPSSm (f32 (IMPLICIT_DEF)), addr:$src)>,
           Requires<[HasAVX, OptForSize]>;
-
-let Predicates =3D [HasAVX] in {
+}
+
+let Predicates =3D [HasAVX], AddedComplexity =3D 1 in {
   def : Pat<(int_x86_sse_sqrt_ss VR128:$src),
             (INSERT_SUBREG (v4f32 (IMPLICIT_DEF)),
                 (VSQRTSSr (f32 (IMPLICIT_DEF)),
@@ -3063,21 +3263,26 @@
 }
=20
 // Square root.
-defm SQRT  : sse1_fp_unop_s<0x51, "sqrt",  fsqrt, int_x86_sse_sqrt_ss>,
-             sse1_fp_unop_p<0x51, "sqrt",  fsqrt>,
-             sse1_fp_unop_p_int<0x51, "sqrt",  int_x86_sse_sqrt_ps>,
-             sse2_fp_unop_s<0x51, "sqrt",  fsqrt, int_x86_sse2_sqrt_sd>,
-             sse2_fp_unop_p<0x51, "sqrt",  fsqrt>,
-             sse2_fp_unop_p_int<0x51, "sqrt", int_x86_sse2_sqrt_pd>;
+defm SQRT  : sse1_fp_unop_s<0x51, "sqrt",  fsqrt, int_x86_sse_sqrt_ss,
+                            SSE_SQRTS>,
+             sse1_fp_unop_p<0x51, "sqrt",  fsqrt, SSE_SQRTS>,
+             sse1_fp_unop_p_int<0x51, "sqrt",  int_x86_sse_sqrt_ps, SSE_SQ=
RTS>,
+             sse2_fp_unop_s<0x51, "sqrt",  fsqrt, int_x86_sse2_sqrt_sd,
+                            SSE_SQRTS>,
+             sse2_fp_unop_p<0x51, "sqrt",  fsqrt, SSE_SQRTS>,
+             sse2_fp_unop_p_int<0x51, "sqrt", int_x86_sse2_sqrt_pd, SSE_SQ=
RTS>;
=20
 // Reciprocal approximations. Note that these typically require refinement
 // in order to obtain suitable precision.
-defm RSQRT : sse1_fp_unop_s<0x52, "rsqrt", X86frsqrt, int_x86_sse_rsqrt_ss=
>,
-             sse1_fp_unop_p<0x52, "rsqrt", X86frsqrt>,
-             sse1_fp_unop_p_int<0x52, "rsqrt", int_x86_sse_rsqrt_ps>;
-defm RCP   : sse1_fp_unop_s<0x53, "rcp", X86frcp, int_x86_sse_rcp_ss>,
-             sse1_fp_unop_p<0x53, "rcp", X86frcp>,
-             sse1_fp_unop_p_int<0x53, "rcp", int_x86_sse_rcp_ps>;
+defm RSQRT : sse1_fp_unop_s<0x52, "rsqrt", X86frsqrt, int_x86_sse_rsqrt_ss,
+                            SSE_SQRTS>,
+             sse1_fp_unop_p<0x52, "rsqrt", X86frsqrt, SSE_SQRTS>,
+             sse1_fp_unop_p_int<0x52, "rsqrt", int_x86_sse_rsqrt_ps,
+                            SSE_SQRTS>;
+defm RCP   : sse1_fp_unop_s<0x53, "rcp", X86frcp, int_x86_sse_rcp_ss,
+                            SSE_RCPS>,
+             sse1_fp_unop_p<0x53, "rcp", X86frcp, SSE_RCPS>,
+             sse1_fp_unop_p_int<0x53, "rcp", int_x86_sse_rcp_ps, SSE_RCPS>;
=20
 // There is no f64 version of the reciprocal approximation instructions.
=20
@@ -3090,24 +3295,22 @@
                        (ins f128mem:$dst, VR128:$src),
                        "movntps\t{$src, $dst|$dst, $src}",
                        [(alignednontemporalstore (v4f32 VR128:$src),
-                                                 addr:$dst)]>, VEX;
+                                                 addr:$dst)],
+                                                 IIC_SSE_MOVNT>, VEX;
   def VMOVNTPDmr : VPDI<0x2B, MRMDestMem, (outs),
                        (ins f128mem:$dst, VR128:$src),
                        "movntpd\t{$src, $dst|$dst, $src}",
                        [(alignednontemporalstore (v2f64 VR128:$src),
-                                                 addr:$dst)]>, VEX;
-  def VMOVNTDQ_64mr : VPDI<0xE7, MRMDestMem, (outs),
-                        (ins f128mem:$dst, VR128:$src),
-                        "movntdq\t{$src, $dst|$dst, $src}",
-                        [(alignednontemporalstore (v2f64 VR128:$src),
-                                                  addr:$dst)]>, VEX;
+                                                 addr:$dst)],
+                                                 IIC_SSE_MOVNT>, VEX;
=20
   let ExeDomain =3D SSEPackedInt in
   def VMOVNTDQmr    : VPDI<0xE7, MRMDestMem, (outs),
                            (ins f128mem:$dst, VR128:$src),
                            "movntdq\t{$src, $dst|$dst, $src}",
-                           [(alignednontemporalstore (v4f32 VR128:$src),
-                                                     addr:$dst)]>, VEX;
+                           [(alignednontemporalstore (v2i64 VR128:$src),
+                                                     addr:$dst)],
+                                                     IIC_SSE_MOVNT>, VEX;
=20
   def : Pat<(alignednontemporalstore (v2i64 VR128:$src), addr:$dst),
             (VMOVNTDQmr addr:$dst, VR128:$src)>, Requires<[HasAVX]>;
@@ -3116,23 +3319,21 @@
                        (ins f256mem:$dst, VR256:$src),
                        "movntps\t{$src, $dst|$dst, $src}",
                        [(alignednontemporalstore (v8f32 VR256:$src),
-                                                 addr:$dst)]>, VEX;
+                                                 addr:$dst)],
+                                                 IIC_SSE_MOVNT>, VEX;
   def VMOVNTPDYmr : VPDI<0x2B, MRMDestMem, (outs),
                        (ins f256mem:$dst, VR256:$src),
                        "movntpd\t{$src, $dst|$dst, $src}",
                        [(alignednontemporalstore (v4f64 VR256:$src),
-                                                 addr:$dst)]>, VEX;
-  def VMOVNTDQY_64mr : VPDI<0xE7, MRMDestMem, (outs),
-                        (ins f256mem:$dst, VR256:$src),
-                        "movntdq\t{$src, $dst|$dst, $src}",
-                        [(alignednontemporalstore (v4f64 VR256:$src),
-                                                  addr:$dst)]>, VEX;
+                                                 addr:$dst)],
+                                                 IIC_SSE_MOVNT>, VEX;
   let ExeDomain =3D SSEPackedInt in
   def VMOVNTDQYmr : VPDI<0xE7, MRMDestMem, (outs),
                       (ins f256mem:$dst, VR256:$src),
                       "movntdq\t{$src, $dst|$dst, $src}",
-                      [(alignednontemporalstore (v8f32 VR256:$src),
-                                                addr:$dst)]>, VEX;
+                      [(alignednontemporalstore (v4i64 VR256:$src),
+                                                addr:$dst)],
+                                                IIC_SSE_MOVNT>, VEX;
 }
=20
 def : Pat<(int_x86_avx_movnt_dq_256 addr:$dst, VR256:$src),
@@ -3145,19 +3346,18 @@
 let AddedComplexity =3D 400 in { // Prefer non-temporal versions
 def MOVNTPSmr : PSI<0x2B, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$sr=
c),
                     "movntps\t{$src, $dst|$dst, $src}",
-                    [(alignednontemporalstore (v4f32 VR128:$src), addr:$ds=
t)]>;
+                    [(alignednontemporalstore (v4f32 VR128:$src), addr:$ds=
t)],
+                    IIC_SSE_MOVNT>;
 def MOVNTPDmr : PDI<0x2B, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$sr=
c),
                     "movntpd\t{$src, $dst|$dst, $src}",
-                    [(alignednontemporalstore(v2f64 VR128:$src), addr:$dst=
)]>;
-
-def MOVNTDQ_64mr : PDI<0xE7, MRMDestMem, (outs), (ins f128mem:$dst, VR128:=
$src),
-                    "movntdq\t{$src, $dst|$dst, $src}",
-                    [(alignednontemporalstore (v2f64 VR128:$src), addr:$ds=
t)]>;
+                    [(alignednontemporalstore(v2f64 VR128:$src), addr:$dst=
)],
+                    IIC_SSE_MOVNT>;
=20
 let ExeDomain =3D SSEPackedInt in
 def MOVNTDQmr : PDI<0xE7, MRMDestMem, (outs), (ins f128mem:$dst, VR128:$sr=
c),
                     "movntdq\t{$src, $dst|$dst, $src}",
-                    [(alignednontemporalstore (v4f32 VR128:$src), addr:$ds=
t)]>;
+                    [(alignednontemporalstore (v2i64 VR128:$src), addr:$ds=
t)],
+                    IIC_SSE_MOVNT>;
=20
 def : Pat<(alignednontemporalstore (v2i64 VR128:$src), addr:$dst),
           (MOVNTDQmr addr:$dst, VR128:$src)>, Requires<[HasSSE2]>;
@@ -3165,11 +3365,13 @@
 // There is no AVX form for instructions below this point
 def MOVNTImr : I<0xC3, MRMDestMem, (outs), (ins i32mem:$dst, GR32:$src),
                  "movnti{l}\t{$src, $dst|$dst, $src}",
-                 [(nontemporalstore (i32 GR32:$src), addr:$dst)]>,
+                 [(nontemporalstore (i32 GR32:$src), addr:$dst)],
+                 IIC_SSE_MOVNT>,
                TB, Requires<[HasSSE2]>;
 def MOVNTI_64mr : RI<0xC3, MRMDestMem, (outs), (ins i64mem:$dst, GR64:$src=
),
                      "movnti{q}\t{$src, $dst|$dst, $src}",
-                     [(nontemporalstore (i64 GR64:$src), addr:$dst)]>,
+                     [(nontemporalstore (i64 GR64:$src), addr:$dst)],
+                     IIC_SSE_MOVNT>,
                   TB, Requires<[HasSSE2]>;
 }
=20
@@ -3178,31 +3380,40 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 // Prefetch intrinsic.
-def PREFETCHT0   : PSI<0x18, MRM1m, (outs), (ins i8mem:$src),
-    "prefetcht0\t$src", [(prefetch addr:$src, imm, (i32 3), (i32 1))]>;
-def PREFETCHT1   : PSI<0x18, MRM2m, (outs), (ins i8mem:$src),
-    "prefetcht1\t$src", [(prefetch addr:$src, imm, (i32 2), (i32 1))]>;
-def PREFETCHT2   : PSI<0x18, MRM3m, (outs), (ins i8mem:$src),
-    "prefetcht2\t$src", [(prefetch addr:$src, imm, (i32 1), (i32 1))]>;
-def PREFETCHNTA  : PSI<0x18, MRM0m, (outs), (ins i8mem:$src),
-    "prefetchnta\t$src", [(prefetch addr:$src, imm, (i32 0), (i32 1))]>;
+let Predicates =3D [HasSSE1] in {
+def PREFETCHT0   : I<0x18, MRM1m, (outs), (ins i8mem:$src),
+    "prefetcht0\t$src", [(prefetch addr:$src, imm, (i32 3), (i32 1))],
+    IIC_SSE_PREFETCH>, TB;
+def PREFETCHT1   : I<0x18, MRM2m, (outs), (ins i8mem:$src),
+    "prefetcht1\t$src", [(prefetch addr:$src, imm, (i32 2), (i32 1))],
+    IIC_SSE_PREFETCH>, TB;
+def PREFETCHT2   : I<0x18, MRM3m, (outs), (ins i8mem:$src),
+    "prefetcht2\t$src", [(prefetch addr:$src, imm, (i32 1), (i32 1))],
+    IIC_SSE_PREFETCH>, TB;
+def PREFETCHNTA  : I<0x18, MRM0m, (outs), (ins i8mem:$src),
+    "prefetchnta\t$src", [(prefetch addr:$src, imm, (i32 0), (i32 1))],
+    IIC_SSE_PREFETCH>, TB;
+}
=20
 // Flush cache
 def CLFLUSH : I<0xAE, MRM7m, (outs), (ins i8mem:$src),
-               "clflush\t$src", [(int_x86_sse2_clflush addr:$src)]>,
-              TB, Requires<[HasSSE2]>;
+               "clflush\t$src", [(int_x86_sse2_clflush addr:$src)],
+               IIC_SSE_PREFETCH>, TB, Requires<[HasSSE2]>;
=20
 // Pause. This "instruction" is encoded as "rep; nop", so even though it
 // was introduced with SSE2, it's backward compatible.
-def PAUSE : I<0x90, RawFrm, (outs), (ins), "pause", []>, REP;
+def PAUSE : I<0x90, RawFrm, (outs), (ins), "pause", [], IIC_SSE_PAUSE>, RE=
P;
=20
 // Load, store, and memory fence
 def SFENCE : I<0xAE, MRM_F8, (outs), (ins),
-               "sfence", [(int_x86_sse_sfence)]>, TB, Requires<[HasSSE1]>;
+               "sfence", [(int_x86_sse_sfence)], IIC_SSE_SFENCE>,
+               TB, Requires<[HasSSE1]>;
 def LFENCE : I<0xAE, MRM_E8, (outs), (ins),
-               "lfence", [(int_x86_sse2_lfence)]>, TB, Requires<[HasSSE2]>;
+               "lfence", [(int_x86_sse2_lfence)], IIC_SSE_LFENCE>,
+               TB, Requires<[HasSSE2]>;
 def MFENCE : I<0xAE, MRM_F0, (outs), (ins),
-               "mfence", [(int_x86_sse2_mfence)]>, TB, Requires<[HasSSE2]>;
+               "mfence", [(int_x86_sse2_mfence)], IIC_SSE_MFENCE>,
+               TB, Requires<[HasSSE2]>;
=20
 def : Pat<(X86SFence), (SFENCE)>;
 def : Pat<(X86LFence), (LFENCE)>;
@@ -3213,14 +3424,18 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 def VLDMXCSR : VPSI<0xAE, MRM2m, (outs), (ins i32mem:$src),
-                  "ldmxcsr\t$src", [(int_x86_sse_ldmxcsr addr:$src)]>, VEX;
+                  "ldmxcsr\t$src", [(int_x86_sse_ldmxcsr addr:$src)],
+                  IIC_SSE_LDMXCSR>, VEX;
 def VSTMXCSR : VPSI<0xAE, MRM3m, (outs), (ins i32mem:$dst),
-                  "stmxcsr\t$dst", [(int_x86_sse_stmxcsr addr:$dst)]>, VEX;
+                  "stmxcsr\t$dst", [(int_x86_sse_stmxcsr addr:$dst)],
+                  IIC_SSE_STMXCSR>, VEX;
=20
 def LDMXCSR : PSI<0xAE, MRM2m, (outs), (ins i32mem:$src),
-                  "ldmxcsr\t$src", [(int_x86_sse_ldmxcsr addr:$src)]>;
+                  "ldmxcsr\t$src", [(int_x86_sse_ldmxcsr addr:$src)],
+                  IIC_SSE_LDMXCSR>;
 def STMXCSR : PSI<0xAE, MRM3m, (outs), (ins i32mem:$dst),
-                  "stmxcsr\t$dst", [(int_x86_sse_stmxcsr addr:$dst)]>;
+                  "stmxcsr\t$dst", [(int_x86_sse_stmxcsr addr:$dst)],
+                  IIC_SSE_STMXCSR>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSE2 - Move Aligned/Unaligned Packed Integer Instructions
@@ -3230,108 +3445,134 @@
=20
 let neverHasSideEffects =3D 1 in {
 def VMOVDQArr  : VPDI<0x6F, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                    "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                    "movdqa\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVA_P_=
RR>,
+                    VEX;
 def VMOVDQAYrr : VPDI<0x6F, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
-                    "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                    "movdqa\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVA_P_=
RR>,
+                    VEX;
 }
 def VMOVDQUrr  : VSSI<0x6F, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                    "movdqu\t{$src, $dst|$dst, $src}", []>, VEX;
+                    "movdqu\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVU_P_=
RR>,
+                    VEX;
 def VMOVDQUYrr : VSSI<0x6F, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
-                    "movdqu\t{$src, $dst|$dst, $src}", []>, VEX;
+                    "movdqu\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVU_P_=
RR>,
+                    VEX;
=20
 // For Disassembler
 let isCodeGenOnly =3D 1 in {
 def VMOVDQArr_REV  : VPDI<0x7F, MRMDestReg, (outs VR128:$dst), (ins VR128:=
$src),
-                        "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "movdqa\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_MOVA_P_RR>,
+                        VEX;
 def VMOVDQAYrr_REV : VPDI<0x7F, MRMDestReg, (outs VR256:$dst), (ins VR256:=
$src),
-                        "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "movdqa\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_MOVA_P_RR>,
+                        VEX;
 def VMOVDQUrr_REV  : VSSI<0x7F, MRMDestReg, (outs VR128:$dst), (ins VR128:=
$src),
-                        "movdqu\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "movdqu\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_MOVU_P_RR>,
+                        VEX;
 def VMOVDQUYrr_REV : VSSI<0x7F, MRMDestReg, (outs VR256:$dst), (ins VR256:=
$src),
-                        "movdqu\t{$src, $dst|$dst, $src}", []>, VEX;
+                        "movdqu\t{$src, $dst|$dst, $src}", [],
+                        IIC_SSE_MOVU_P_RR>,
+                        VEX;
 }
=20
 let canFoldAsLoad =3D 1, mayLoad =3D 1 in {
 def VMOVDQArm  : VPDI<0x6F, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$sr=
c),
-                   "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                   "movdqa\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVA_P_R=
M>,
+                   VEX;
 def VMOVDQAYrm : VPDI<0x6F, MRMSrcMem, (outs VR256:$dst), (ins i256mem:$sr=
c),
-                   "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                   "movdqa\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVA_P_R=
M>,
+                   VEX;
 let Predicates =3D [HasAVX] in {
   def VMOVDQUrm  : I<0x6F, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$src=
),
-                    "vmovdqu\t{$src, $dst|$dst, $src}",[]>, XS, VEX;
+                    "vmovdqu\t{$src, $dst|$dst, $src}",[], IIC_SSE_MOVU_P_=
RM>,
+                    XS, VEX;
   def VMOVDQUYrm : I<0x6F, MRMSrcMem, (outs VR256:$dst), (ins i256mem:$src=
),
-                    "vmovdqu\t{$src, $dst|$dst, $src}",[]>, XS, VEX;
+                    "vmovdqu\t{$src, $dst|$dst, $src}",[], IIC_SSE_MOVU_P_=
RM>,
+                    XS, VEX;
 }
 }
=20
 let mayStore =3D 1 in {
 def VMOVDQAmr  : VPDI<0x7F, MRMDestMem, (outs),
                      (ins i128mem:$dst, VR128:$src),
-                     "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                     "movdqa\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVA_P=
_MR>,
+                     VEX;
 def VMOVDQAYmr : VPDI<0x7F, MRMDestMem, (outs),
                      (ins i256mem:$dst, VR256:$src),
-                     "movdqa\t{$src, $dst|$dst, $src}", []>, VEX;
+                     "movdqa\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVA_P=
_MR>,
+                     VEX;
 let Predicates =3D [HasAVX] in {
 def VMOVDQUmr  : I<0x7F, MRMDestMem, (outs), (ins i128mem:$dst, VR128:$src=
),
-                  "vmovdqu\t{$src, $dst|$dst, $src}",[]>, XS, VEX;
+                  "vmovdqu\t{$src, $dst|$dst, $src}",[], IIC_SSE_MOVU_P_MR=
>,
+                  XS, VEX;
 def VMOVDQUYmr : I<0x7F, MRMDestMem, (outs), (ins i256mem:$dst, VR256:$src=
),
-                  "vmovdqu\t{$src, $dst|$dst, $src}",[]>, XS, VEX;
+                  "vmovdqu\t{$src, $dst|$dst, $src}",[], IIC_SSE_MOVU_P_MR=
>,
+                  XS, VEX;
 }
 }
=20
 let neverHasSideEffects =3D 1 in
 def MOVDQArr : PDI<0x6F, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                   "movdqa\t{$src, $dst|$dst, $src}", []>;
+                   "movdqa\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVA_P_R=
R>;
=20
 def MOVDQUrr :   I<0x6F, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                    "movdqu\t{$src, $dst|$dst, $src}",
-                   []>, XS, Requires<[HasSSE2]>;
+                   [], IIC_SSE_MOVU_P_RR>, XS, Requires<[HasSSE2]>;
=20
 // For Disassembler
 let isCodeGenOnly =3D 1 in {
 def MOVDQArr_REV : PDI<0x7F, MRMDestReg, (outs VR128:$dst), (ins VR128:$sr=
c),
-                       "movdqa\t{$src, $dst|$dst, $src}", []>;
+                       "movdqa\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_MOVA_P_RR>;
=20
 def MOVDQUrr_REV :   I<0x7F, MRMDestReg, (outs VR128:$dst), (ins VR128:$sr=
c),
                        "movdqu\t{$src, $dst|$dst, $src}",
-                       []>, XS, Requires<[HasSSE2]>;
+                       [], IIC_SSE_MOVU_P_RR>, XS, Requires<[HasSSE2]>;
 }
=20
 let canFoldAsLoad =3D 1, mayLoad =3D 1 in {
 def MOVDQArm : PDI<0x6F, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$src),
                    "movdqa\t{$src, $dst|$dst, $src}",
-                   [/*(set VR128:$dst, (alignedloadv2i64 addr:$src))*/]>;
+                   [/*(set VR128:$dst, (alignedloadv2i64 addr:$src))*/],
+                   IIC_SSE_MOVA_P_RM>;
 def MOVDQUrm :   I<0x6F, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$src),
                    "movdqu\t{$src, $dst|$dst, $src}",
-                   [/*(set VR128:$dst, (loadv2i64 addr:$src))*/]>,
+                   [/*(set VR128:$dst, (loadv2i64 addr:$src))*/],
+                   IIC_SSE_MOVU_P_RM>,
                  XS, Requires<[HasSSE2]>;
 }
=20
 let mayStore =3D 1 in {
 def MOVDQAmr : PDI<0x7F, MRMDestMem, (outs), (ins i128mem:$dst, VR128:$src=
),
                    "movdqa\t{$src, $dst|$dst, $src}",
-                   [/*(alignedstore (v2i64 VR128:$src), addr:$dst)*/]>;
+                   [/*(alignedstore (v2i64 VR128:$src), addr:$dst)*/],
+                   IIC_SSE_MOVA_P_MR>;
 def MOVDQUmr :   I<0x7F, MRMDestMem, (outs), (ins i128mem:$dst, VR128:$src=
),
                    "movdqu\t{$src, $dst|$dst, $src}",
-                   [/*(store (v2i64 VR128:$src), addr:$dst)*/]>,
+                   [/*(store (v2i64 VR128:$src), addr:$dst)*/],
+                   IIC_SSE_MOVU_P_MR>,
                  XS, Requires<[HasSSE2]>;
 }
=20
 // Intrinsic forms of MOVDQU load and store
 def VMOVDQUmr_Int : I<0x7F, MRMDestMem, (outs), (ins i128mem:$dst, VR128:$=
src),
                        "vmovdqu\t{$src, $dst|$dst, $src}",
-                       [(int_x86_sse2_storeu_dq addr:$dst, VR128:$src)]>,
+                       [(int_x86_sse2_storeu_dq addr:$dst, VR128:$src)],
+                       IIC_SSE_MOVU_P_MR>,
                      XS, VEX, Requires<[HasAVX]>;
=20
 def MOVDQUmr_Int :   I<0x7F, MRMDestMem, (outs), (ins i128mem:$dst, VR128:=
$src),
                        "movdqu\t{$src, $dst|$dst, $src}",
-                       [(int_x86_sse2_storeu_dq addr:$dst, VR128:$src)]>,
+                       [(int_x86_sse2_storeu_dq addr:$dst, VR128:$src)],
+                       IIC_SSE_MOVU_P_MR>,
                      XS, Requires<[HasSSE2]>;
=20
 } // ExeDomain =3D SSEPackedInt
=20
 let Predicates =3D [HasAVX] in {
-  def : Pat<(int_x86_avx_loadu_dq_256 addr:$src), (VMOVDQUYrm addr:$src)>;
   def : Pat<(int_x86_avx_storeu_dq_256 addr:$dst, VR256:$src),
             (VMOVDQUYmr addr:$dst, VR256:$src)>;
 }
@@ -3340,178 +3581,326 @@
 // SSE2 - Packed Integer Arithmetic Instructions
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
+def SSE_PMADD : OpndItins<
+  IIC_SSE_PMADD, IIC_SSE_PMADD
+>;
+
 let ExeDomain =3D SSEPackedInt in { // SSE integer instructions
=20
 multiclass PDI_binop_rm_int<bits<8> opc, string OpcodeStr, Intrinsic IntId,
-                            bit IsCommutable =3D 0, bit Is2Addr =3D 1> {
+                            RegisterClass RC, PatFrag memop_frag,
+                            X86MemOperand x86memop,
+                            OpndItins itins,
+                            bit IsCommutable =3D 0,
+                            bit Is2Addr =3D 1> {
   let isCommutable =3D IsCommutable in
-  def rr : PDI<opc, MRMSrcReg, (outs VR128:$dst),
-       (ins VR128:$src1, VR128:$src2),
+  def rr : PDI<opc, MRMSrcReg, (outs RC:$dst),
+       (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (IntId VR128:$src1, VR128:$src2))]>;
-  def rm : PDI<opc, MRMSrcMem, (outs VR128:$dst),
-       (ins VR128:$src1, i128mem:$src2),
+       [(set RC:$dst, (IntId RC:$src1, RC:$src2))], itins.rr>;
+  def rm : PDI<opc, MRMSrcMem, (outs RC:$dst),
+       (ins RC:$src1, x86memop:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (IntId VR128:$src1,
-                                (bitconvert (memopv2i64 addr:$src2))))]>;
-}
-
-multiclass PDI_binop_rmi_int<bits<8> opc, bits<8> opc2, Format ImmForm,
-                             string OpcodeStr, Intrinsic IntId,
-                             Intrinsic IntId2, bit Is2Addr =3D 1> {
-  def rr : PDI<opc, MRMSrcReg, (outs VR128:$dst),
-       (ins VR128:$src1, VR128:$src2),
+       [(set RC:$dst, (IntId RC:$src1, (bitconvert (memop_frag addr:$src2)=
)))],
+       itins.rm>;
+}
+
+multiclass PDI_binop_rmi<bits<8> opc, bits<8> opc2, Format ImmForm,
+                         string OpcodeStr, SDNode OpNode,
+                         SDNode OpNode2, RegisterClass RC,
+                         ValueType DstVT, ValueType SrcVT, PatFrag bc_frag,
+                         ShiftOpndItins itins,
+                         bit Is2Addr =3D 1> {
+  // src2 is always 128-bit
+  def rr : PDI<opc, MRMSrcReg, (outs RC:$dst),
+       (ins RC:$src1, VR128:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (IntId VR128:$src1, VR128:$src2))]>;
-  def rm : PDI<opc, MRMSrcMem, (outs VR128:$dst),
-       (ins VR128:$src1, i128mem:$src2),
+       [(set RC:$dst, (DstVT (OpNode RC:$src1, (SrcVT VR128:$src2))))],
+        itins.rr>;
+  def rm : PDI<opc, MRMSrcMem, (outs RC:$dst),
+       (ins RC:$src1, i128mem:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (IntId VR128:$src1,
-                                      (bitconvert (memopv2i64 addr:$src2))=
))]>;
-  def ri : PDIi8<opc2, ImmForm, (outs VR128:$dst),
-       (ins VR128:$src1, i32i8imm:$src2),
+       [(set RC:$dst, (DstVT (OpNode RC:$src1,
+                       (bc_frag (memopv2i64 addr:$src2)))))], itins.rm>;
+  def ri : PDIi8<opc2, ImmForm, (outs RC:$dst),
+       (ins RC:$src1, i32i8imm:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (IntId2 VR128:$src1, (i32 imm:$src2)))]>;
-}
-
-/// PDI_binop_rm - Simple SSE2 binary operator.
-multiclass PDI_binop_rm<bits<8> opc, string OpcodeStr, SDNode OpNode,
-                        ValueType OpVT, bit IsCommutable =3D 0, bit Is2Add=
r =3D 1> {
+       [(set RC:$dst, (DstVT (OpNode2 RC:$src1, (i32 imm:$src2))))], itins=
.ri>;
+}
+
+/// PDI_binop_rm - Simple SSE2 binary operator with different src and dst =
types
+multiclass PDI_binop_rm2<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                         ValueType DstVT, ValueType SrcVT, RegisterClass R=
C,
+                         PatFrag memop_frag, X86MemOperand x86memop,
+                         OpndItins itins,
+                         bit IsCommutable =3D 0, bit Is2Addr =3D 1> {
   let isCommutable =3D IsCommutable in
-  def rr : PDI<opc, MRMSrcReg, (outs VR128:$dst),
-       (ins VR128:$src1, VR128:$src2),
+  def rr : PDI<opc, MRMSrcReg, (outs RC:$dst),
+       (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (OpVT (OpNode VR128:$src1, VR128:$src2)))]>;
-  def rm : PDI<opc, MRMSrcMem, (outs VR128:$dst),
-       (ins VR128:$src1, i128mem:$src2),
+       [(set RC:$dst, (DstVT (OpNode (SrcVT RC:$src1), RC:$src2)))]>;
+  def rm : PDI<opc, MRMSrcMem, (outs RC:$dst),
+       (ins RC:$src1, x86memop:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (OpVT (OpNode VR128:$src1,
-                                     (bitconvert (memopv2i64 addr:$src2)))=
))]>;
-}
-
-/// PDI_binop_rm_v2i64 - Simple SSE2 binary operator whose type is v2i64.
-///
-/// FIXME: we could eliminate this and use PDI_binop_rm instead if tblgen =
knew
-/// to collapse (bitconvert VT to VT) into its operand.
-///
-multiclass PDI_binop_rm_v2i64<bits<8> opc, string OpcodeStr, SDNode OpNode,
-                              bit IsCommutable =3D 0, bit Is2Addr =3D 1> {
-  let isCommutable =3D IsCommutable in
-  def rr : PDI<opc, MRMSrcReg, (outs VR128:$dst),
-       (ins VR128:$src1, VR128:$src2),
-       !if(Is2Addr,
-           !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
-           !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (v2i64 (OpNode VR128:$src1, VR128:$src2)))]>;
-  def rm : PDI<opc, MRMSrcMem, (outs VR128:$dst),
-       (ins VR128:$src1, i128mem:$src2),
-       !if(Is2Addr,
-           !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
-           !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (OpNode VR128:$src1, (memopv2i64 addr:$src2)))]>;
-}
-
+       [(set RC:$dst, (DstVT (OpNode (SrcVT RC:$src1),
+                                     (bitconvert (memop_frag addr:$src2)))=
))]>;
+}
 } // ExeDomain =3D SSEPackedInt
=20
 // 128-bit Integer Arithmetic
=20
 let Predicates =3D [HasAVX] in {
-defm VPADDB  : PDI_binop_rm<0xFC, "vpaddb", add, v16i8, 1, 0 /*3addr*/>, V=
EX_4V;
-defm VPADDW  : PDI_binop_rm<0xFD, "vpaddw", add, v8i16, 1, 0>, VEX_4V;
-defm VPADDD  : PDI_binop_rm<0xFE, "vpaddd", add, v4i32, 1, 0>, VEX_4V;
-defm VPADDQ  : PDI_binop_rm_v2i64<0xD4, "vpaddq", add, 1, 0>, VEX_4V;
-defm VPMULLW : PDI_binop_rm<0xD5, "vpmullw", mul, v8i16, 1, 0>, VEX_4V;
-defm VPSUBB : PDI_binop_rm<0xF8, "vpsubb", sub, v16i8, 0, 0>, VEX_4V;
-defm VPSUBW : PDI_binop_rm<0xF9, "vpsubw", sub, v8i16, 0, 0>, VEX_4V;
-defm VPSUBD : PDI_binop_rm<0xFA, "vpsubd", sub, v4i32, 0, 0>, VEX_4V;
-defm VPSUBQ : PDI_binop_rm_v2i64<0xFB, "vpsubq", sub, 0, 0>, VEX_4V;
+defm VPADDB  : PDI_binop_rm<0xFC, "vpaddb", add, v16i8, VR128, memopv2i64,
+                            i128mem, SSE_INTALU_ITINS_P, 1, 0 /*3addr*/>,
+                            VEX_4V;
+defm VPADDW  : PDI_binop_rm<0xFD, "vpaddw", add, v8i16, VR128, memopv2i64,
+                            i128mem, SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDD  : PDI_binop_rm<0xFE, "vpaddd", add, v4i32, VR128, memopv2i64,
+                            i128mem, SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDQ  : PDI_binop_rm<0xD4, "vpaddq", add, v2i64, VR128, memopv2i64,
+                            i128mem, SSE_INTALUQ_ITINS_P, 1, 0>, VEX_4V;
+defm VPMULLW : PDI_binop_rm<0xD5, "vpmullw", mul, v8i16, VR128, memopv2i64,
+                            i128mem, SSE_INTMUL_ITINS_P, 1, 0>, VEX_4V;
+defm VPSUBB : PDI_binop_rm<0xF8, "vpsubb", sub, v16i8, VR128, memopv2i64,
+                            i128mem, SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBW : PDI_binop_rm<0xF9, "vpsubw", sub, v8i16, VR128, memopv2i64,
+                            i128mem, SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBD : PDI_binop_rm<0xFA, "vpsubd", sub, v4i32, VR128, memopv2i64,
+                            i128mem, SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBQ : PDI_binop_rm<0xFB, "vpsubq", sub, v2i64, VR128, memopv2i64,
+                            i128mem, SSE_INTALUQ_ITINS_P, 0, 0>, VEX_4V;
+defm VPMULUDQ : PDI_binop_rm2<0xF4, "vpmuludq", X86pmuludq, v2i64, v4i32, =
VR128,
+                              memopv2i64, i128mem, SSE_INTMUL_ITINS_P, 1, =
0>,
+                              VEX_4V;
=20
 // Intrinsic forms
-defm VPSUBSB  : PDI_binop_rm_int<0xE8, "vpsubsb" , int_x86_sse2_psubs_b, 0=
, 0>,
-                                 VEX_4V;
-defm VPSUBSW  : PDI_binop_rm_int<0xE9, "vpsubsw" , int_x86_sse2_psubs_w, 0=
, 0>,
-                                 VEX_4V;
-defm VPSUBUSB : PDI_binop_rm_int<0xD8, "vpsubusb", int_x86_sse2_psubus_b, =
0, 0>,
-                                 VEX_4V;
-defm VPSUBUSW : PDI_binop_rm_int<0xD9, "vpsubusw", int_x86_sse2_psubus_w, =
0, 0>,
-                                 VEX_4V;
-defm VPADDSB  : PDI_binop_rm_int<0xEC, "vpaddsb" , int_x86_sse2_padds_b, 1=
, 0>,
-                                 VEX_4V;
-defm VPADDSW  : PDI_binop_rm_int<0xED, "vpaddsw" , int_x86_sse2_padds_w, 1=
, 0>,
-                                 VEX_4V;
-defm VPADDUSB : PDI_binop_rm_int<0xDC, "vpaddusb", int_x86_sse2_paddus_b, =
1, 0>,
-                                 VEX_4V;
-defm VPADDUSW : PDI_binop_rm_int<0xDD, "vpaddusw", int_x86_sse2_paddus_w, =
1, 0>,
-                                 VEX_4V;
-defm VPMULHUW : PDI_binop_rm_int<0xE4, "vpmulhuw", int_x86_sse2_pmulhu_w, =
1, 0>,
-                                 VEX_4V;
-defm VPMULHW  : PDI_binop_rm_int<0xE5, "vpmulhw" , int_x86_sse2_pmulh_w, 1=
, 0>,
-                                 VEX_4V;
-defm VPMULUDQ : PDI_binop_rm_int<0xF4, "vpmuludq", int_x86_sse2_pmulu_dq, =
1, 0>,
-                                 VEX_4V;
-defm VPMADDWD : PDI_binop_rm_int<0xF5, "vpmaddwd", int_x86_sse2_pmadd_wd, =
1, 0>,
-                                 VEX_4V;
-defm VPAVGB   : PDI_binop_rm_int<0xE0, "vpavgb", int_x86_sse2_pavg_b, 1, 0=
>,
-                                 VEX_4V;
-defm VPAVGW   : PDI_binop_rm_int<0xE3, "vpavgw", int_x86_sse2_pavg_w, 1, 0=
>,
-                                 VEX_4V;
-defm VPMINUB  : PDI_binop_rm_int<0xDA, "vpminub", int_x86_sse2_pminu_b, 1,=
 0>,
-                                 VEX_4V;
-defm VPMINSW  : PDI_binop_rm_int<0xEA, "vpminsw", int_x86_sse2_pmins_w, 1,=
 0>,
-                                 VEX_4V;
-defm VPMAXUB  : PDI_binop_rm_int<0xDE, "vpmaxub", int_x86_sse2_pmaxu_b, 1,=
 0>,
-                                 VEX_4V;
-defm VPMAXSW  : PDI_binop_rm_int<0xEE, "vpmaxsw", int_x86_sse2_pmaxs_w, 1,=
 0>,
-                                 VEX_4V;
-defm VPSADBW  : PDI_binop_rm_int<0xF6, "vpsadbw", int_x86_sse2_psad_bw, 1,=
 0>,
-                                 VEX_4V;
+defm VPSUBSB  : PDI_binop_rm_int<0xE8, "vpsubsb" , int_x86_sse2_psubs_b,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBSW  : PDI_binop_rm_int<0xE9, "vpsubsw" , int_x86_sse2_psubs_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBUSB : PDI_binop_rm_int<0xD8, "vpsubusb", int_x86_sse2_psubus_b,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBUSW : PDI_binop_rm_int<0xD9, "vpsubusw", int_x86_sse2_psubus_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPADDSB  : PDI_binop_rm_int<0xEC, "vpaddsb" , int_x86_sse2_padds_b,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDSW  : PDI_binop_rm_int<0xED, "vpaddsw" , int_x86_sse2_padds_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDUSB : PDI_binop_rm_int<0xDC, "vpaddusb", int_x86_sse2_paddus_b,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDUSW : PDI_binop_rm_int<0xDD, "vpaddusw", int_x86_sse2_paddus_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMULHUW : PDI_binop_rm_int<0xE4, "vpmulhuw", int_x86_sse2_pmulhu_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTMUL_ITINS_P, 1, 0>, VEX_4V;
+defm VPMULHW  : PDI_binop_rm_int<0xE5, "vpmulhw" , int_x86_sse2_pmulh_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTMUL_ITINS_P, 1, 0>, VEX_4V;
+defm VPMADDWD : PDI_binop_rm_int<0xF5, "vpmaddwd", int_x86_sse2_pmadd_wd,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_PMADD, 1, 0>, VEX_4V;
+defm VPAVGB   : PDI_binop_rm_int<0xE0, "vpavgb", int_x86_sse2_pavg_b,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPAVGW   : PDI_binop_rm_int<0xE3, "vpavgw", int_x86_sse2_pavg_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMINUB  : PDI_binop_rm_int<0xDA, "vpminub", int_x86_sse2_pminu_b,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMINSW  : PDI_binop_rm_int<0xEA, "vpminsw", int_x86_sse2_pmins_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMAXUB  : PDI_binop_rm_int<0xDE, "vpmaxub", int_x86_sse2_pmaxu_b,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMAXSW  : PDI_binop_rm_int<0xEE, "vpmaxsw", int_x86_sse2_pmaxs_w,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPSADBW  : PDI_binop_rm_int<0xF6, "vpsadbw", int_x86_sse2_psad_bw,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2] in {
+defm VPADDBY  : PDI_binop_rm<0xFC, "vpaddb", add, v32i8, VR256, memopv4i64,
+                             i256mem, SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDWY  : PDI_binop_rm<0xFD, "vpaddw", add, v16i16, VR256, memopv4i6=
4,
+                             i256mem, SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDDY  : PDI_binop_rm<0xFE, "vpaddd", add, v8i32, VR256, memopv4i64,
+                             i256mem, SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDQY  : PDI_binop_rm<0xD4, "vpaddq", add, v4i64, VR256, memopv4i64,
+                             i256mem, SSE_INTALUQ_ITINS_P, 1, 0>, VEX_4V;
+defm VPMULLWY : PDI_binop_rm<0xD5, "vpmullw", mul, v16i16, VR256, memopv4i=
64,
+                             i256mem, SSE_INTMUL_ITINS_P, 1, 0>, VEX_4V;
+defm VPSUBBY  : PDI_binop_rm<0xF8, "vpsubb", sub, v32i8, VR256, memopv4i64,
+                             i256mem, SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBWY  : PDI_binop_rm<0xF9, "vpsubw", sub, v16i16,VR256, memopv4i64,
+                             i256mem, SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBDY  : PDI_binop_rm<0xFA, "vpsubd", sub, v8i32, VR256, memopv4i64,
+                             i256mem, SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBQY  : PDI_binop_rm<0xFB, "vpsubq", sub, v4i64, VR256, memopv4i64,
+                             i256mem, SSE_INTALUQ_ITINS_P, 0, 0>, VEX_4V;
+defm VPMULUDQY : PDI_binop_rm2<0xF4, "vpmuludq", X86pmuludq, v4i64, v8i32,
+                               VR256, memopv4i64, i256mem,
+                               SSE_INTMUL_ITINS_P, 1, 0>, VEX_4V;
+
+// Intrinsic forms
+defm VPSUBSBY  : PDI_binop_rm_int<0xE8, "vpsubsb" , int_x86_avx2_psubs_b,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBSWY  : PDI_binop_rm_int<0xE9, "vpsubsw" , int_x86_avx2_psubs_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBUSBY : PDI_binop_rm_int<0xD8, "vpsubusb", int_x86_avx2_psubus_b,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPSUBUSWY : PDI_binop_rm_int<0xD9, "vpsubusw", int_x86_avx2_psubus_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPADDSBY  : PDI_binop_rm_int<0xEC, "vpaddsb" , int_x86_avx2_padds_b,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDSWY  : PDI_binop_rm_int<0xED, "vpaddsw" , int_x86_avx2_padds_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDUSBY : PDI_binop_rm_int<0xDC, "vpaddusb", int_x86_avx2_paddus_b,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPADDUSWY : PDI_binop_rm_int<0xDD, "vpaddusw", int_x86_avx2_paddus_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMULHUWY : PDI_binop_rm_int<0xE4, "vpmulhuw", int_x86_avx2_pmulhu_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTMUL_ITINS_P, 1, 0>, VEX_4V;
+defm VPMULHWY  : PDI_binop_rm_int<0xE5, "vpmulhw" , int_x86_avx2_pmulh_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTMUL_ITINS_P, 1, 0>, VEX_4V;
+defm VPMADDWDY : PDI_binop_rm_int<0xF5, "vpmaddwd", int_x86_avx2_pmadd_wd,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_PMADD, 1, 0>, VEX_4V;
+defm VPAVGBY   : PDI_binop_rm_int<0xE0, "vpavgb", int_x86_avx2_pavg_b,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPAVGWY   : PDI_binop_rm_int<0xE3, "vpavgw", int_x86_avx2_pavg_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMINUBY  : PDI_binop_rm_int<0xDA, "vpminub", int_x86_avx2_pminu_b,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMINSWY  : PDI_binop_rm_int<0xEA, "vpminsw", int_x86_avx2_pmins_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMAXUBY  : PDI_binop_rm_int<0xDE, "vpmaxub", int_x86_avx2_pmaxu_b,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPMAXSWY  : PDI_binop_rm_int<0xEE, "vpmaxsw", int_x86_avx2_pmaxs_w,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+defm VPSADBWY  : PDI_binop_rm_int<0xF6, "vpsadbw", int_x86_avx2_psad_bw,
+                                  VR256, memopv4i64, i256mem,
+                                  SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
-defm PADDB  : PDI_binop_rm<0xFC, "paddb", add, v16i8, 1>;
-defm PADDW  : PDI_binop_rm<0xFD, "paddw", add, v8i16, 1>;
-defm PADDD  : PDI_binop_rm<0xFE, "paddd", add, v4i32, 1>;
-defm PADDQ  : PDI_binop_rm_v2i64<0xD4, "paddq", add, 1>;
-defm PMULLW : PDI_binop_rm<0xD5, "pmullw", mul, v8i16, 1>;
-defm PSUBB : PDI_binop_rm<0xF8, "psubb", sub, v16i8>;
-defm PSUBW : PDI_binop_rm<0xF9, "psubw", sub, v8i16>;
-defm PSUBD : PDI_binop_rm<0xFA, "psubd", sub, v4i32>;
-defm PSUBQ : PDI_binop_rm_v2i64<0xFB, "psubq", sub>;
+defm PADDB  : PDI_binop_rm<0xFC, "paddb", add, v16i8, VR128, memopv2i64,
+                           i128mem, SSE_INTALU_ITINS_P, 1>;
+defm PADDW  : PDI_binop_rm<0xFD, "paddw", add, v8i16, VR128, memopv2i64,
+                           i128mem, SSE_INTALU_ITINS_P, 1>;
+defm PADDD  : PDI_binop_rm<0xFE, "paddd", add, v4i32, VR128, memopv2i64,
+                           i128mem, SSE_INTALU_ITINS_P, 1>;
+defm PADDQ  : PDI_binop_rm<0xD4, "paddq", add, v2i64, VR128, memopv2i64,
+                           i128mem, SSE_INTALUQ_ITINS_P, 1>;
+defm PMULLW : PDI_binop_rm<0xD5, "pmullw", mul, v8i16, VR128, memopv2i64,
+                           i128mem, SSE_INTMUL_ITINS_P, 1>;
+defm PSUBB : PDI_binop_rm<0xF8, "psubb", sub, v16i8, VR128, memopv2i64,
+                          i128mem, SSE_INTALU_ITINS_P>;
+defm PSUBW : PDI_binop_rm<0xF9, "psubw", sub, v8i16, VR128, memopv2i64,
+                          i128mem, SSE_INTALU_ITINS_P>;
+defm PSUBD : PDI_binop_rm<0xFA, "psubd", sub, v4i32, VR128, memopv2i64,
+                          i128mem, SSE_INTALU_ITINS_P>;
+defm PSUBQ : PDI_binop_rm<0xFB, "psubq", sub, v2i64, VR128, memopv2i64,
+                          i128mem, SSE_INTALUQ_ITINS_P>;
+defm PMULUDQ : PDI_binop_rm2<0xF4, "pmuludq", X86pmuludq, v2i64, v4i32, VR=
128,
+                             memopv2i64, i128mem, SSE_INTMUL_ITINS_P, 1>;
=20
 // Intrinsic forms
-defm PSUBSB  : PDI_binop_rm_int<0xE8, "psubsb" , int_x86_sse2_psubs_b>;
-defm PSUBSW  : PDI_binop_rm_int<0xE9, "psubsw" , int_x86_sse2_psubs_w>;
-defm PSUBUSB : PDI_binop_rm_int<0xD8, "psubusb", int_x86_sse2_psubus_b>;
-defm PSUBUSW : PDI_binop_rm_int<0xD9, "psubusw", int_x86_sse2_psubus_w>;
-defm PADDSB  : PDI_binop_rm_int<0xEC, "paddsb" , int_x86_sse2_padds_b, 1>;
-defm PADDSW  : PDI_binop_rm_int<0xED, "paddsw" , int_x86_sse2_padds_w, 1>;
-defm PADDUSB : PDI_binop_rm_int<0xDC, "paddusb", int_x86_sse2_paddus_b, 1>;
-defm PADDUSW : PDI_binop_rm_int<0xDD, "paddusw", int_x86_sse2_paddus_w, 1>;
-defm PMULHUW : PDI_binop_rm_int<0xE4, "pmulhuw", int_x86_sse2_pmulhu_w, 1>;
-defm PMULHW  : PDI_binop_rm_int<0xE5, "pmulhw" , int_x86_sse2_pmulh_w, 1>;
-defm PMULUDQ : PDI_binop_rm_int<0xF4, "pmuludq", int_x86_sse2_pmulu_dq, 1>;
-defm PMADDWD : PDI_binop_rm_int<0xF5, "pmaddwd", int_x86_sse2_pmadd_wd, 1>;
-defm PAVGB   : PDI_binop_rm_int<0xE0, "pavgb", int_x86_sse2_pavg_b, 1>;
-defm PAVGW   : PDI_binop_rm_int<0xE3, "pavgw", int_x86_sse2_pavg_w, 1>;
-defm PMINUB  : PDI_binop_rm_int<0xDA, "pminub", int_x86_sse2_pminu_b, 1>;
-defm PMINSW  : PDI_binop_rm_int<0xEA, "pminsw", int_x86_sse2_pmins_w, 1>;
-defm PMAXUB  : PDI_binop_rm_int<0xDE, "pmaxub", int_x86_sse2_pmaxu_b, 1>;
-defm PMAXSW  : PDI_binop_rm_int<0xEE, "pmaxsw", int_x86_sse2_pmaxs_w, 1>;
-defm PSADBW  : PDI_binop_rm_int<0xF6, "psadbw", int_x86_sse2_psad_bw, 1>;
+defm PSUBSB  : PDI_binop_rm_int<0xE8, "psubsb" , int_x86_sse2_psubs_b,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P>;
+defm PSUBSW  : PDI_binop_rm_int<0xE9, "psubsw" , int_x86_sse2_psubs_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P>;
+defm PSUBUSB : PDI_binop_rm_int<0xD8, "psubusb", int_x86_sse2_psubus_b,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P>;
+defm PSUBUSW : PDI_binop_rm_int<0xD9, "psubusw", int_x86_sse2_psubus_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P>;
+defm PADDSB  : PDI_binop_rm_int<0xEC, "paddsb" , int_x86_sse2_padds_b,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PADDSW  : PDI_binop_rm_int<0xED, "paddsw" , int_x86_sse2_padds_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PADDUSB : PDI_binop_rm_int<0xDC, "paddusb", int_x86_sse2_paddus_b,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PADDUSW : PDI_binop_rm_int<0xDD, "paddusw", int_x86_sse2_paddus_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PMULHUW : PDI_binop_rm_int<0xE4, "pmulhuw", int_x86_sse2_pmulhu_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTMUL_ITINS_P, 1>;
+defm PMULHW  : PDI_binop_rm_int<0xE5, "pmulhw" , int_x86_sse2_pmulh_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTMUL_ITINS_P, 1>;
+defm PMADDWD : PDI_binop_rm_int<0xF5, "pmaddwd", int_x86_sse2_pmadd_wd,
+                                VR128, memopv2i64, i128mem,
+                                SSE_PMADD, 1>;
+defm PAVGB   : PDI_binop_rm_int<0xE0, "pavgb", int_x86_sse2_pavg_b,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PAVGW   : PDI_binop_rm_int<0xE3, "pavgw", int_x86_sse2_pavg_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PMINUB  : PDI_binop_rm_int<0xDA, "pminub", int_x86_sse2_pminu_b,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PMINSW  : PDI_binop_rm_int<0xEA, "pminsw", int_x86_sse2_pmins_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PMAXUB  : PDI_binop_rm_int<0xDE, "pmaxub", int_x86_sse2_pmaxu_b,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PMAXSW  : PDI_binop_rm_int<0xEE, "pmaxsw", int_x86_sse2_pmaxs_w,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
+defm PSADBW  : PDI_binop_rm_int<0xF6, "psadbw", int_x86_sse2_psad_bw,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1>;
=20
 } // Constraints =3D "$src1 =3D $dst"
=20
@@ -3520,145 +3909,176 @@
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 let Predicates =3D [HasAVX] in {
-defm VPSLLW : PDI_binop_rmi_int<0xF1, 0x71, MRM6r, "vpsllw",
-                                int_x86_sse2_psll_w, int_x86_sse2_pslli_w,=
 0>,
-                                VEX_4V;
-defm VPSLLD : PDI_binop_rmi_int<0xF2, 0x72, MRM6r, "vpslld",
-                                int_x86_sse2_psll_d, int_x86_sse2_pslli_d,=
 0>,
-                                VEX_4V;
-defm VPSLLQ : PDI_binop_rmi_int<0xF3, 0x73, MRM6r, "vpsllq",
-                                int_x86_sse2_psll_q, int_x86_sse2_pslli_q,=
 0>,
-                                VEX_4V;
-
-defm VPSRLW : PDI_binop_rmi_int<0xD1, 0x71, MRM2r, "vpsrlw",
-                                int_x86_sse2_psrl_w, int_x86_sse2_psrli_w,=
 0>,
-                                VEX_4V;
-defm VPSRLD : PDI_binop_rmi_int<0xD2, 0x72, MRM2r, "vpsrld",
-                                int_x86_sse2_psrl_d, int_x86_sse2_psrli_d,=
 0>,
-                                VEX_4V;
-defm VPSRLQ : PDI_binop_rmi_int<0xD3, 0x73, MRM2r, "vpsrlq",
-                                int_x86_sse2_psrl_q, int_x86_sse2_psrli_q,=
 0>,
-                                VEX_4V;
-
-defm VPSRAW : PDI_binop_rmi_int<0xE1, 0x71, MRM4r, "vpsraw",
-                                int_x86_sse2_psra_w, int_x86_sse2_psrai_w,=
 0>,
-                                VEX_4V;
-defm VPSRAD : PDI_binop_rmi_int<0xE2, 0x72, MRM4r, "vpsrad",
-                                int_x86_sse2_psra_d, int_x86_sse2_psrai_d,=
 0>,
-                                VEX_4V;
-
-defm VPAND : PDI_binop_rm_v2i64<0xDB, "vpand", and, 1, 0>, VEX_4V;
-defm VPOR  : PDI_binop_rm_v2i64<0xEB, "vpor" , or, 1, 0>, VEX_4V;
-defm VPXOR : PDI_binop_rm_v2i64<0xEF, "vpxor", xor, 1, 0>, VEX_4V;
+defm VPSLLW : PDI_binop_rmi<0xF1, 0x71, MRM6r, "vpsllw", X86vshl, X86vshli,
+                            VR128, v8i16, v8i16, bc_v8i16,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSLLD : PDI_binop_rmi<0xF2, 0x72, MRM6r, "vpslld", X86vshl, X86vshli,
+                            VR128, v4i32, v4i32, bc_v4i32,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSLLQ : PDI_binop_rmi<0xF3, 0x73, MRM6r, "vpsllq", X86vshl, X86vshli,
+                            VR128, v2i64, v2i64, bc_v2i64,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+
+defm VPSRLW : PDI_binop_rmi<0xD1, 0x71, MRM2r, "vpsrlw", X86vsrl, X86vsrli,
+                            VR128, v8i16, v8i16, bc_v8i16,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSRLD : PDI_binop_rmi<0xD2, 0x72, MRM2r, "vpsrld", X86vsrl, X86vsrli,
+                            VR128, v4i32, v4i32, bc_v4i32,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSRLQ : PDI_binop_rmi<0xD3, 0x73, MRM2r, "vpsrlq", X86vsrl, X86vsrli,
+                            VR128, v2i64, v2i64, bc_v2i64,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+
+defm VPSRAW : PDI_binop_rmi<0xE1, 0x71, MRM4r, "vpsraw", X86vsra, X86vsrai,
+                            VR128, v8i16, v8i16, bc_v8i16,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSRAD : PDI_binop_rmi<0xE2, 0x72, MRM4r, "vpsrad", X86vsra, X86vsrai,
+                            VR128, v4i32, v4i32, bc_v4i32,
+                            SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
=20
 let ExeDomain =3D SSEPackedInt in {
-  let neverHasSideEffects =3D 1 in {
-    // 128-bit logical shifts.
-    def VPSLLDQri : PDIi8<0x73, MRM7r,
-                      (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$src2),
-                      "vpslldq\t{$src2, $src1, $dst|$dst, $src1, $src2}", =
[]>,
-                      VEX_4V;
-    def VPSRLDQri : PDIi8<0x73, MRM3r,
-                      (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$src2),
-                      "vpsrldq\t{$src2, $src1, $dst|$dst, $src1, $src2}", =
[]>,
-                      VEX_4V;
-    // PSRADQri doesn't exist in SSE[1-3].
-  }
-  def VPANDNrr : PDI<0xDF, MRMSrcReg,
-                    (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
-                    "vpandn\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+  // 128-bit logical shifts.
+  def VPSLLDQri : PDIi8<0x73, MRM7r,
+                    (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$src2),
+                    "vpslldq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                     [(set VR128:$dst,
-                          (v2i64 (X86andnp VR128:$src1, VR128:$src2)))]>,V=
EX_4V;
-
-  def VPANDNrm : PDI<0xDF, MRMSrcMem,
-                    (outs VR128:$dst), (ins VR128:$src1, i128mem:$src2),
-                    "vpandn\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-                    [(set VR128:$dst, (X86andnp VR128:$src1,
-                                            (memopv2i64 addr:$src2)))]>, V=
EX_4V;
-}
-}
+                      (int_x86_sse2_psll_dq_bs VR128:$src1, imm:$src2))]>,
+                    VEX_4V;
+  def VPSRLDQri : PDIi8<0x73, MRM3r,
+                    (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$src2),
+                    "vpsrldq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                    [(set VR128:$dst,
+                      (int_x86_sse2_psrl_dq_bs VR128:$src1, imm:$src2))]>,
+                    VEX_4V;
+  // PSRADQri doesn't exist in SSE[1-3].
+}
+} // Predicates =3D [HasAVX]
+
+let Predicates =3D [HasAVX2] in {
+defm VPSLLWY : PDI_binop_rmi<0xF1, 0x71, MRM6r, "vpsllw", X86vshl, X86vshl=
i,
+                             VR256, v16i16, v8i16, bc_v8i16,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSLLDY : PDI_binop_rmi<0xF2, 0x72, MRM6r, "vpslld", X86vshl, X86vshl=
i,
+                             VR256, v8i32, v4i32, bc_v4i32,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSLLQY : PDI_binop_rmi<0xF3, 0x73, MRM6r, "vpsllq", X86vshl, X86vshl=
i,
+                             VR256, v4i64, v2i64, bc_v2i64,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+
+defm VPSRLWY : PDI_binop_rmi<0xD1, 0x71, MRM2r, "vpsrlw", X86vsrl, X86vsrl=
i,
+                             VR256, v16i16, v8i16, bc_v8i16,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSRLDY : PDI_binop_rmi<0xD2, 0x72, MRM2r, "vpsrld", X86vsrl, X86vsrl=
i,
+                             VR256, v8i32, v4i32, bc_v4i32,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSRLQY : PDI_binop_rmi<0xD3, 0x73, MRM2r, "vpsrlq", X86vsrl, X86vsrl=
i,
+                             VR256, v4i64, v2i64, bc_v2i64,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+
+defm VPSRAWY : PDI_binop_rmi<0xE1, 0x71, MRM4r, "vpsraw", X86vsra, X86vsra=
i,
+                             VR256, v16i16, v8i16, bc_v8i16,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+defm VPSRADY : PDI_binop_rmi<0xE2, 0x72, MRM4r, "vpsrad", X86vsra, X86vsra=
i,
+                             VR256, v8i32, v4i32, bc_v4i32,
+                             SSE_INTSHIFT_ITINS_P, 0>, VEX_4V;
+
+let ExeDomain =3D SSEPackedInt in {
+  // 256-bit logical shifts.
+  def VPSLLDQYri : PDIi8<0x73, MRM7r,
+                    (outs VR256:$dst), (ins VR256:$src1, i32i8imm:$src2),
+                    "vpslldq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                    [(set VR256:$dst,
+                      (int_x86_avx2_psll_dq_bs VR256:$src1, imm:$src2))]>,
+                    VEX_4V;
+  def VPSRLDQYri : PDIi8<0x73, MRM3r,
+                    (outs VR256:$dst), (ins VR256:$src1, i32i8imm:$src2),
+                    "vpsrldq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                    [(set VR256:$dst,
+                      (int_x86_avx2_psrl_dq_bs VR256:$src1, imm:$src2))]>,
+                    VEX_4V;
+  // PSRADQYri doesn't exist in SSE[1-3].
+}
+} // Predicates =3D [HasAVX2]
=20
 let Constraints =3D "$src1 =3D $dst" in {
-defm PSLLW : PDI_binop_rmi_int<0xF1, 0x71, MRM6r, "psllw",
-                               int_x86_sse2_psll_w, int_x86_sse2_pslli_w>;
-defm PSLLD : PDI_binop_rmi_int<0xF2, 0x72, MRM6r, "pslld",
-                               int_x86_sse2_psll_d, int_x86_sse2_pslli_d>;
-defm PSLLQ : PDI_binop_rmi_int<0xF3, 0x73, MRM6r, "psllq",
-                               int_x86_sse2_psll_q, int_x86_sse2_pslli_q>;
-
-defm PSRLW : PDI_binop_rmi_int<0xD1, 0x71, MRM2r, "psrlw",
-                               int_x86_sse2_psrl_w, int_x86_sse2_psrli_w>;
-defm PSRLD : PDI_binop_rmi_int<0xD2, 0x72, MRM2r, "psrld",
-                               int_x86_sse2_psrl_d, int_x86_sse2_psrli_d>;
-defm PSRLQ : PDI_binop_rmi_int<0xD3, 0x73, MRM2r, "psrlq",
-                               int_x86_sse2_psrl_q, int_x86_sse2_psrli_q>;
-
-defm PSRAW : PDI_binop_rmi_int<0xE1, 0x71, MRM4r, "psraw",
-                               int_x86_sse2_psra_w, int_x86_sse2_psrai_w>;
-defm PSRAD : PDI_binop_rmi_int<0xE2, 0x72, MRM4r, "psrad",
-                               int_x86_sse2_psra_d, int_x86_sse2_psrai_d>;
-
-defm PAND : PDI_binop_rm_v2i64<0xDB, "pand", and, 1>;
-defm POR  : PDI_binop_rm_v2i64<0xEB, "por" , or, 1>;
-defm PXOR : PDI_binop_rm_v2i64<0xEF, "pxor", xor, 1>;
+defm PSLLW : PDI_binop_rmi<0xF1, 0x71, MRM6r, "psllw", X86vshl, X86vshli,
+                           VR128, v8i16, v8i16, bc_v8i16,
+                           SSE_INTSHIFT_ITINS_P>;
+defm PSLLD : PDI_binop_rmi<0xF2, 0x72, MRM6r, "pslld", X86vshl, X86vshli,
+                           VR128, v4i32, v4i32, bc_v4i32,
+                           SSE_INTSHIFT_ITINS_P>;
+defm PSLLQ : PDI_binop_rmi<0xF3, 0x73, MRM6r, "psllq", X86vshl, X86vshli,
+                           VR128, v2i64, v2i64, bc_v2i64,
+                           SSE_INTSHIFT_ITINS_P>;
+
+defm PSRLW : PDI_binop_rmi<0xD1, 0x71, MRM2r, "psrlw", X86vsrl, X86vsrli,
+                           VR128, v8i16, v8i16, bc_v8i16,
+                           SSE_INTSHIFT_ITINS_P>;
+defm PSRLD : PDI_binop_rmi<0xD2, 0x72, MRM2r, "psrld", X86vsrl, X86vsrli,
+                           VR128, v4i32, v4i32, bc_v4i32,
+                           SSE_INTSHIFT_ITINS_P>;
+defm PSRLQ : PDI_binop_rmi<0xD3, 0x73, MRM2r, "psrlq", X86vsrl, X86vsrli,
+                           VR128, v2i64, v2i64, bc_v2i64,
+                           SSE_INTSHIFT_ITINS_P>;
+
+defm PSRAW : PDI_binop_rmi<0xE1, 0x71, MRM4r, "psraw", X86vsra, X86vsrai,
+                           VR128, v8i16, v8i16, bc_v8i16,
+                           SSE_INTSHIFT_ITINS_P>;
+defm PSRAD : PDI_binop_rmi<0xE2, 0x72, MRM4r, "psrad", X86vsra, X86vsrai,
+                           VR128, v4i32, v4i32, bc_v4i32,
+                           SSE_INTSHIFT_ITINS_P>;
=20
 let ExeDomain =3D SSEPackedInt in {
-  let neverHasSideEffects =3D 1 in {
-    // 128-bit logical shifts.
-    def PSLLDQri : PDIi8<0x73, MRM7r,
-                         (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$sr=
c2),
-                         "pslldq\t{$src2, $dst|$dst, $src2}", []>;
-    def PSRLDQri : PDIi8<0x73, MRM3r,
-                         (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$sr=
c2),
-                         "psrldq\t{$src2, $dst|$dst, $src2}", []>;
-    // PSRADQri doesn't exist in SSE[1-3].
-  }
-  def PANDNrr : PDI<0xDF, MRMSrcReg,
-                    (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
-                    "pandn\t{$src2, $dst|$dst, $src2}", []>;
-
-  def PANDNrm : PDI<0xDF, MRMSrcMem,
-                    (outs VR128:$dst), (ins VR128:$src1, i128mem:$src2),
-                    "pandn\t{$src2, $dst|$dst, $src2}", []>;
+  // 128-bit logical shifts.
+  def PSLLDQri : PDIi8<0x73, MRM7r,
+                       (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$src2=
),
+                       "pslldq\t{$src2, $dst|$dst, $src2}",
+                       [(set VR128:$dst,
+                         (int_x86_sse2_psll_dq_bs VR128:$src1, imm:$src2))=
]>;
+  def PSRLDQri : PDIi8<0x73, MRM3r,
+                       (outs VR128:$dst), (ins VR128:$src1, i32i8imm:$src2=
),
+                       "psrldq\t{$src2, $dst|$dst, $src2}",
+                       [(set VR128:$dst,
+                         (int_x86_sse2_psrl_dq_bs VR128:$src1, imm:$src2))=
]>;
+  // PSRADQri doesn't exist in SSE[1-3].
 }
 } // Constraints =3D "$src1 =3D $dst"
=20
 let Predicates =3D [HasAVX] in {
   def : Pat<(int_x86_sse2_psll_dq VR128:$src1, imm:$src2),
-            (v2i64 (VPSLLDQri VR128:$src1, (BYTE_imm imm:$src2)))>;
+            (VPSLLDQri VR128:$src1, (BYTE_imm imm:$src2))>;
   def : Pat<(int_x86_sse2_psrl_dq VR128:$src1, imm:$src2),
-            (v2i64 (VPSRLDQri VR128:$src1, (BYTE_imm imm:$src2)))>;
-  def : Pat<(int_x86_sse2_psll_dq_bs VR128:$src1, imm:$src2),
-            (v2i64 (VPSLLDQri VR128:$src1, imm:$src2))>;
-  def : Pat<(int_x86_sse2_psrl_dq_bs VR128:$src1, imm:$src2),
-            (v2i64 (VPSRLDQri VR128:$src1, imm:$src2))>;
+            (VPSRLDQri VR128:$src1, (BYTE_imm imm:$src2))>;
   def : Pat<(v2f64 (X86fsrl VR128:$src1, i32immSExt8:$src2)),
-            (v2f64 (VPSRLDQri VR128:$src1, (BYTE_imm imm:$src2)))>;
+            (VPSRLDQri VR128:$src1, (BYTE_imm imm:$src2))>;
=20
   // Shift up / down and insert zero's.
-  def : Pat<(v2i64 (X86vshl  VR128:$src, (i8 imm:$amt))),
-            (v2i64 (VPSLLDQri VR128:$src, (BYTE_imm imm:$amt)))>;
-  def : Pat<(v2i64 (X86vshr  VR128:$src, (i8 imm:$amt))),
-            (v2i64 (VPSRLDQri VR128:$src, (BYTE_imm imm:$amt)))>;
+  def : Pat<(v2i64 (X86vshldq VR128:$src, (i8 imm:$amt))),
+            (VPSLLDQri VR128:$src, (BYTE_imm imm:$amt))>;
+  def : Pat<(v2i64 (X86vshrdq VR128:$src, (i8 imm:$amt))),
+            (VPSRLDQri VR128:$src, (BYTE_imm imm:$amt))>;
+}
+
+let Predicates =3D [HasAVX2] in {
+  def : Pat<(int_x86_avx2_psll_dq VR256:$src1, imm:$src2),
+            (VPSLLDQYri VR256:$src1, (BYTE_imm imm:$src2))>;
+  def : Pat<(int_x86_avx2_psrl_dq VR256:$src1, imm:$src2),
+            (VPSRLDQYri VR256:$src1, (BYTE_imm imm:$src2))>;
 }
=20
 let Predicates =3D [HasSSE2] in {
   def : Pat<(int_x86_sse2_psll_dq VR128:$src1, imm:$src2),
-            (v2i64 (PSLLDQri VR128:$src1, (BYTE_imm imm:$src2)))>;
+            (PSLLDQri VR128:$src1, (BYTE_imm imm:$src2))>;
   def : Pat<(int_x86_sse2_psrl_dq VR128:$src1, imm:$src2),
-            (v2i64 (PSRLDQri VR128:$src1, (BYTE_imm imm:$src2)))>;
-  def : Pat<(int_x86_sse2_psll_dq_bs VR128:$src1, imm:$src2),
-            (v2i64 (PSLLDQri VR128:$src1, imm:$src2))>;
-  def : Pat<(int_x86_sse2_psrl_dq_bs VR128:$src1, imm:$src2),
-            (v2i64 (PSRLDQri VR128:$src1, imm:$src2))>;
+            (PSRLDQri VR128:$src1, (BYTE_imm imm:$src2))>;
   def : Pat<(v2f64 (X86fsrl VR128:$src1, i32immSExt8:$src2)),
-            (v2f64 (PSRLDQri VR128:$src1, (BYTE_imm imm:$src2)))>;
+            (PSRLDQri VR128:$src1, (BYTE_imm imm:$src2))>;
=20
   // Shift up / down and insert zero's.
-  def : Pat<(v2i64 (X86vshl  VR128:$src, (i8 imm:$amt))),
-            (v2i64 (PSLLDQri VR128:$src, (BYTE_imm imm:$amt)))>;
-  def : Pat<(v2i64 (X86vshr  VR128:$src, (i8 imm:$amt))),
-            (v2i64 (PSRLDQri VR128:$src, (BYTE_imm imm:$amt)))>;
+  def : Pat<(v2i64 (X86vshldq VR128:$src, (i8 imm:$amt))),
+            (PSLLDQri VR128:$src, (BYTE_imm imm:$amt))>;
+  def : Pat<(v2i64 (X86vshrdq VR128:$src, (i8 imm:$amt))),
+            (PSRLDQri VR128:$src, (BYTE_imm imm:$amt))>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -3666,100 +4086,106 @@
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 let Predicates =3D [HasAVX] in {
-  defm VPCMPEQB  : PDI_binop_rm_int<0x74, "vpcmpeqb", int_x86_sse2_pcmpeq_=
b, 1,
-                                    0>, VEX_4V;
-  defm VPCMPEQW  : PDI_binop_rm_int<0x75, "vpcmpeqw", int_x86_sse2_pcmpeq_=
w, 1,
-                                    0>, VEX_4V;
-  defm VPCMPEQD  : PDI_binop_rm_int<0x76, "vpcmpeqd", int_x86_sse2_pcmpeq_=
d, 1,
-                                    0>, VEX_4V;
-  defm VPCMPGTB  : PDI_binop_rm_int<0x64, "vpcmpgtb", int_x86_sse2_pcmpgt_=
b, 0,
-                                    0>, VEX_4V;
-  defm VPCMPGTW  : PDI_binop_rm_int<0x65, "vpcmpgtw", int_x86_sse2_pcmpgt_=
w, 0,
-                                    0>, VEX_4V;
-  defm VPCMPGTD  : PDI_binop_rm_int<0x66, "vpcmpgtd", int_x86_sse2_pcmpgt_=
d, 0,
-                                    0>, VEX_4V;
-
-  def : Pat<(v16i8 (X86pcmpeqb VR128:$src1, VR128:$src2)),
-            (VPCMPEQBrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v16i8 (X86pcmpeqb VR128:$src1, (memop addr:$src2))),
-            (VPCMPEQBrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v8i16 (X86pcmpeqw VR128:$src1, VR128:$src2)),
-            (VPCMPEQWrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v8i16 (X86pcmpeqw VR128:$src1, (memop addr:$src2))),
-            (VPCMPEQWrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4i32 (X86pcmpeqd VR128:$src1, VR128:$src2)),
-            (VPCMPEQDrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v4i32 (X86pcmpeqd VR128:$src1, (memop addr:$src2))),
-            (VPCMPEQDrm VR128:$src1, addr:$src2)>;
-
-  def : Pat<(v16i8 (X86pcmpgtb VR128:$src1, VR128:$src2)),
-            (VPCMPGTBrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v16i8 (X86pcmpgtb VR128:$src1, (memop addr:$src2))),
-            (VPCMPGTBrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v8i16 (X86pcmpgtw VR128:$src1, VR128:$src2)),
-            (VPCMPGTWrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v8i16 (X86pcmpgtw VR128:$src1, (memop addr:$src2))),
-            (VPCMPGTWrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4i32 (X86pcmpgtd VR128:$src1, VR128:$src2)),
-            (VPCMPGTDrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v4i32 (X86pcmpgtd VR128:$src1, (memop addr:$src2))),
-            (VPCMPGTDrm VR128:$src1, addr:$src2)>;
+  defm VPCMPEQB  : PDI_binop_rm<0x74, "vpcmpeqb", X86pcmpeq, v16i8,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+  defm VPCMPEQW  : PDI_binop_rm<0x75, "vpcmpeqw", X86pcmpeq, v8i16,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+  defm VPCMPEQD  : PDI_binop_rm<0x76, "vpcmpeqd", X86pcmpeq, v4i32,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+  defm VPCMPGTB  : PDI_binop_rm<0x64, "vpcmpgtb", X86pcmpgt, v16i8,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+  defm VPCMPGTW  : PDI_binop_rm<0x65, "vpcmpgtw", X86pcmpgt, v8i16,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+  defm VPCMPGTD  : PDI_binop_rm<0x66, "vpcmpgtd", X86pcmpgt, v4i32,
+                                VR128, memopv2i64, i128mem,
+                                SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2] in {
+  defm VPCMPEQBY : PDI_binop_rm<0x74, "vpcmpeqb", X86pcmpeq, v32i8,
+                                VR256, memopv4i64, i256mem,
+                                SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+  defm VPCMPEQWY : PDI_binop_rm<0x75, "vpcmpeqw", X86pcmpeq, v16i16,
+                                VR256, memopv4i64, i256mem,
+                                SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+  defm VPCMPEQDY : PDI_binop_rm<0x76, "vpcmpeqd", X86pcmpeq, v8i32,
+                                VR256, memopv4i64, i256mem,
+                                SSE_INTALU_ITINS_P, 1, 0>, VEX_4V;
+  defm VPCMPGTBY : PDI_binop_rm<0x64, "vpcmpgtb", X86pcmpgt, v32i8,
+                                VR256, memopv4i64, i256mem,
+                                SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+  defm VPCMPGTWY : PDI_binop_rm<0x65, "vpcmpgtw", X86pcmpgt, v16i16,
+                                VR256, memopv4i64, i256mem,
+                                SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+  defm VPCMPGTDY : PDI_binop_rm<0x66, "vpcmpgtd", X86pcmpgt, v8i32,
+                                VR256, memopv4i64, i256mem,
+                                SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
-  defm PCMPEQB  : PDI_binop_rm_int<0x74, "pcmpeqb", int_x86_sse2_pcmpeq_b,=
 1>;
-  defm PCMPEQW  : PDI_binop_rm_int<0x75, "pcmpeqw", int_x86_sse2_pcmpeq_w,=
 1>;
-  defm PCMPEQD  : PDI_binop_rm_int<0x76, "pcmpeqd", int_x86_sse2_pcmpeq_d,=
 1>;
-  defm PCMPGTB  : PDI_binop_rm_int<0x64, "pcmpgtb", int_x86_sse2_pcmpgt_b>;
-  defm PCMPGTW  : PDI_binop_rm_int<0x65, "pcmpgtw", int_x86_sse2_pcmpgt_w>;
-  defm PCMPGTD  : PDI_binop_rm_int<0x66, "pcmpgtd", int_x86_sse2_pcmpgt_d>;
+  defm PCMPEQB  : PDI_binop_rm<0x74, "pcmpeqb", X86pcmpeq, v16i8,
+                               VR128, memopv2i64, i128mem,
+                               SSE_INTALU_ITINS_P, 1>;
+  defm PCMPEQW  : PDI_binop_rm<0x75, "pcmpeqw", X86pcmpeq, v8i16,
+                               VR128, memopv2i64, i128mem,
+                               SSE_INTALU_ITINS_P, 1>;
+  defm PCMPEQD  : PDI_binop_rm<0x76, "pcmpeqd", X86pcmpeq, v4i32,
+                               VR128, memopv2i64, i128mem,
+                               SSE_INTALU_ITINS_P, 1>;
+  defm PCMPGTB  : PDI_binop_rm<0x64, "pcmpgtb", X86pcmpgt, v16i8,
+                               VR128, memopv2i64, i128mem,
+                               SSE_INTALU_ITINS_P>;
+  defm PCMPGTW  : PDI_binop_rm<0x65, "pcmpgtw", X86pcmpgt, v8i16,
+                               VR128, memopv2i64, i128mem,
+                               SSE_INTALU_ITINS_P>;
+  defm PCMPGTD  : PDI_binop_rm<0x66, "pcmpgtd", X86pcmpgt, v4i32,
+                               VR128, memopv2i64, i128mem,
+                               SSE_INTALU_ITINS_P>;
 } // Constraints =3D "$src1 =3D $dst"
=20
-let Predicates =3D [HasSSE2] in {
-  def : Pat<(v16i8 (X86pcmpeqb VR128:$src1, VR128:$src2)),
-            (PCMPEQBrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v16i8 (X86pcmpeqb VR128:$src1, (memop addr:$src2))),
-            (PCMPEQBrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v8i16 (X86pcmpeqw VR128:$src1, VR128:$src2)),
-            (PCMPEQWrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v8i16 (X86pcmpeqw VR128:$src1, (memop addr:$src2))),
-            (PCMPEQWrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4i32 (X86pcmpeqd VR128:$src1, VR128:$src2)),
-            (PCMPEQDrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v4i32 (X86pcmpeqd VR128:$src1, (memop addr:$src2))),
-            (PCMPEQDrm VR128:$src1, addr:$src2)>;
-
-  def : Pat<(v16i8 (X86pcmpgtb VR128:$src1, VR128:$src2)),
-            (PCMPGTBrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v16i8 (X86pcmpgtb VR128:$src1, (memop addr:$src2))),
-            (PCMPGTBrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v8i16 (X86pcmpgtw VR128:$src1, VR128:$src2)),
-            (PCMPGTWrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v8i16 (X86pcmpgtw VR128:$src1, (memop addr:$src2))),
-            (PCMPGTWrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v4i32 (X86pcmpgtd VR128:$src1, VR128:$src2)),
-            (PCMPGTDrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v4i32 (X86pcmpgtd VR128:$src1, (memop addr:$src2))),
-            (PCMPGTDrm VR128:$src1, addr:$src2)>;
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSE2 - Packed Integer Pack Instructions
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 let Predicates =3D [HasAVX] in {
 defm VPACKSSWB : PDI_binop_rm_int<0x63, "vpacksswb", int_x86_sse2_packsswb=
_128,
-                                  0, 0>, VEX_4V;
+                                  VR128, memopv2i64, i128mem,
+                                  SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
 defm VPACKSSDW : PDI_binop_rm_int<0x6B, "vpackssdw", int_x86_sse2_packssdw=
_128,
-                                  0, 0>, VEX_4V;
+                                  VR128, memopv2i64, i128mem,
+                                  SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
 defm VPACKUSWB : PDI_binop_rm_int<0x67, "vpackuswb", int_x86_sse2_packuswb=
_128,
-                                  0, 0>, VEX_4V;
+                                  VR128, memopv2i64, i128mem,
+                                  SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2] in {
+defm VPACKSSWBY : PDI_binop_rm_int<0x63, "vpacksswb", int_x86_avx2_packssw=
b,
+                                   VR256, memopv4i64, i256mem,
+                                   SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPACKSSDWY : PDI_binop_rm_int<0x6B, "vpackssdw", int_x86_avx2_packssd=
w,
+                                   VR256, memopv4i64, i256mem,
+                                   SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
+defm VPACKUSWBY : PDI_binop_rm_int<0x67, "vpackuswb", int_x86_avx2_packusw=
b,
+                                   VR256, memopv4i64, i256mem,
+                                   SSE_INTALU_ITINS_P, 0, 0>, VEX_4V;
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
-defm PACKSSWB : PDI_binop_rm_int<0x63, "packsswb", int_x86_sse2_packsswb_1=
28>;
-defm PACKSSDW : PDI_binop_rm_int<0x6B, "packssdw", int_x86_sse2_packssdw_1=
28>;
-defm PACKUSWB : PDI_binop_rm_int<0x67, "packuswb", int_x86_sse2_packuswb_1=
28>;
+defm PACKSSWB : PDI_binop_rm_int<0x63, "packsswb", int_x86_sse2_packsswb_1=
28,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P>;
+defm PACKSSDW : PDI_binop_rm_int<0x6B, "packssdw", int_x86_sse2_packssdw_1=
28,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P>;
+defm PACKUSWB : PDI_binop_rm_int<0x67, "packuswb", int_x86_sse2_packuswb_1=
28,
+                                 VR128, memopv2i64, i128mem,
+                                 SSE_INTALU_ITINS_P>;
 } // Constraints =3D "$src1 =3D $dst"
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -3767,103 +4193,75 @@
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 let ExeDomain =3D SSEPackedInt in {
-multiclass sse2_pshuffle<string OpcodeStr, ValueType vt, PatFrag pshuf_fra=
g,
-                         PatFrag bc_frag> {
+multiclass sse2_pshuffle<string OpcodeStr, ValueType vt, SDNode OpNode> {
 def ri : Ii8<0x70, MRMSrcReg,
-              (outs VR128:$dst), (ins VR128:$src1, i8imm:$src2),
+             (outs VR128:$dst), (ins VR128:$src1, i8imm:$src2),
+             !strconcat(OpcodeStr,
+                        "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+              [(set VR128:$dst, (vt (OpNode VR128:$src1, (i8 imm:$src2))))=
],
+              IIC_SSE_PSHUF>;
+def mi : Ii8<0x70, MRMSrcMem,
+             (outs VR128:$dst), (ins i128mem:$src1, i8imm:$src2),
+             !strconcat(OpcodeStr,
+                        "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+              [(set VR128:$dst,
+                (vt (OpNode (bitconvert (memopv2i64 addr:$src1)),
+                             (i8 imm:$src2))))],
+                             IIC_SSE_PSHUF>;
+}
+
+multiclass sse2_pshuffle_y<string OpcodeStr, ValueType vt, SDNode OpNode> {
+def Yri : Ii8<0x70, MRMSrcReg,
+              (outs VR256:$dst), (ins VR256:$src1, i8imm:$src2),
               !strconcat(OpcodeStr,
                          "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
-              [(set VR128:$dst, (vt (pshuf_frag:$src2 VR128:$src1,
-                                                      (undef))))]>;
-def mi : Ii8<0x70, MRMSrcMem,
-              (outs VR128:$dst), (ins i128mem:$src1, i8imm:$src2),
+              [(set VR256:$dst, (vt (OpNode VR256:$src1, (i8 imm:$src2))))=
]>;
+def Ymi : Ii8<0x70, MRMSrcMem,
+              (outs VR256:$dst), (ins i256mem:$src1, i8imm:$src2),
               !strconcat(OpcodeStr,
                          "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
-              [(set VR128:$dst, (vt (pshuf_frag:$src2
-                                      (bc_frag (memopv2i64 addr:$src1)),
-                                      (undef))))]>;
+              [(set VR256:$dst,
+                (vt (OpNode (bitconvert (memopv4i64 addr:$src1)),
+                             (i8 imm:$src2))))]>;
 }
 } // ExeDomain =3D SSEPackedInt
=20
 let Predicates =3D [HasAVX] in {
-  let AddedComplexity =3D 5 in
-  defm VPSHUFD : sse2_pshuffle<"vpshufd", v4i32, pshufd, bc_v4i32>, TB, Op=
Size,
-                               VEX;
-
-  // SSE2 with ImmT =3D=3D Imm8 and XS prefix.
-  defm VPSHUFHW : sse2_pshuffle<"vpshufhw", v8i16, pshufhw, bc_v8i16>, XS,
-                               VEX;
-
-  // SSE2 with ImmT =3D=3D Imm8 and XD prefix.
-  defm VPSHUFLW : sse2_pshuffle<"vpshuflw", v8i16, pshuflw, bc_v8i16>, XD,
-                               VEX;
-
-  let AddedComplexity =3D 5 in
-  def : Pat<(v4f32 (pshufd:$src2 VR128:$src1, (undef))),
-            (VPSHUFDri VR128:$src1, (SHUFFLE_get_shuf_imm VR128:$src2))>;
-  // Unary v4f32 shuffle with VPSHUF* in order to fold a load.
-  def : Pat<(pshufd:$src2 (bc_v4i32 (memopv4f32 addr:$src1)), (undef)),
-            (VPSHUFDmi addr:$src1, (SHUFFLE_get_shuf_imm VR128:$src2))>;
-
-  def : Pat<(v4i32 (X86PShufd (bc_v4i32 (memopv2i64 addr:$src1)),
-                                   (i8 imm:$imm))),
-            (VPSHUFDmi addr:$src1, imm:$imm)>;
-  def : Pat<(v4i32 (X86PShufd (bc_v4i32 (memopv4f32 addr:$src1)),
-                                   (i8 imm:$imm))),
-            (VPSHUFDmi addr:$src1, imm:$imm)>;
-  def : Pat<(v4f32 (X86PShufd VR128:$src1, (i8 imm:$imm))),
-            (VPSHUFDri VR128:$src1, imm:$imm)>;
-  def : Pat<(v4i32 (X86PShufd VR128:$src1, (i8 imm:$imm))),
-            (VPSHUFDri VR128:$src1, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShufhw VR128:$src, (i8 imm:$imm))),
-            (VPSHUFHWri VR128:$src, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShufhw (bc_v8i16 (memopv2i64 addr:$src)),
-                               (i8 imm:$imm))),
-            (VPSHUFHWmi addr:$src, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShuflw VR128:$src, (i8 imm:$imm))),
-            (VPSHUFLWri VR128:$src, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShuflw (bc_v8i16 (memopv2i64 addr:$src)),
-                               (i8 imm:$imm))),
-            (VPSHUFLWmi addr:$src, imm:$imm)>;
+ let AddedComplexity =3D 5 in
+  defm VPSHUFD : sse2_pshuffle<"vpshufd", v4i32, X86PShufd>, TB, OpSize, V=
EX;
+
+ // SSE2 with ImmT =3D=3D Imm8 and XS prefix.
+  defm VPSHUFHW : sse2_pshuffle<"vpshufhw", v8i16, X86PShufhw>, XS, VEX;
+
+ // SSE2 with ImmT =3D=3D Imm8 and XD prefix.
+  defm VPSHUFLW : sse2_pshuffle<"vpshuflw", v8i16, X86PShuflw>, XD, VEX;
+
+ def : Pat<(v4f32 (X86PShufd (memopv4f32 addr:$src1), (i8 imm:$imm))),
+           (VPSHUFDmi addr:$src1, imm:$imm)>;
+ def : Pat<(v4f32 (X86PShufd VR128:$src1, (i8 imm:$imm))),
+           (VPSHUFDri VR128:$src1, imm:$imm)>;
+}
+
+let Predicates =3D [HasAVX2] in {
+  defm VPSHUFD : sse2_pshuffle_y<"vpshufd", v8i32, X86PShufd>, TB, OpSize,=
 VEX;
+  defm VPSHUFHW : sse2_pshuffle_y<"vpshufhw", v16i16, X86PShufhw>, XS, VEX;
+  defm VPSHUFLW : sse2_pshuffle_y<"vpshuflw", v16i16, X86PShuflw>, XD, VEX;
 }
=20
 let Predicates =3D [HasSSE2] in {
-  let AddedComplexity =3D 5 in
-  defm PSHUFD : sse2_pshuffle<"pshufd", v4i32, pshufd, bc_v4i32>, TB, OpSi=
ze;
-
-  // SSE2 with ImmT =3D=3D Imm8 and XS prefix.
-  defm PSHUFHW : sse2_pshuffle<"pshufhw", v8i16, pshufhw, bc_v8i16>, XS;
-
-  // SSE2 with ImmT =3D=3D Imm8 and XD prefix.
-  defm PSHUFLW : sse2_pshuffle<"pshuflw", v8i16, pshuflw, bc_v8i16>, XD;
-
-  let AddedComplexity =3D 5 in
-  def : Pat<(v4f32 (pshufd:$src2 VR128:$src1, (undef))),
-            (PSHUFDri VR128:$src1, (SHUFFLE_get_shuf_imm VR128:$src2))>;
-  // Unary v4f32 shuffle with PSHUF* in order to fold a load.
-  def : Pat<(pshufd:$src2 (bc_v4i32 (memopv4f32 addr:$src1)), (undef)),
-            (PSHUFDmi addr:$src1, (SHUFFLE_get_shuf_imm VR128:$src2))>;
-
-  def : Pat<(v4i32 (X86PShufd (bc_v4i32 (memopv2i64 addr:$src1)),
-                                   (i8 imm:$imm))),
-            (PSHUFDmi addr:$src1, imm:$imm)>;
-  def : Pat<(v4i32 (X86PShufd (bc_v4i32 (memopv4f32 addr:$src1)),
-                                   (i8 imm:$imm))),
-            (PSHUFDmi addr:$src1, imm:$imm)>;
-  def : Pat<(v4f32 (X86PShufd VR128:$src1, (i8 imm:$imm))),
-            (PSHUFDri VR128:$src1, imm:$imm)>;
-  def : Pat<(v4i32 (X86PShufd VR128:$src1, (i8 imm:$imm))),
-            (PSHUFDri VR128:$src1, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShufhw VR128:$src, (i8 imm:$imm))),
-            (PSHUFHWri VR128:$src, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShufhw (bc_v8i16 (memopv2i64 addr:$src)),
-                               (i8 imm:$imm))),
-            (PSHUFHWmi addr:$src, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShuflw VR128:$src, (i8 imm:$imm))),
-            (PSHUFLWri VR128:$src, imm:$imm)>;
-  def : Pat<(v8i16 (X86PShuflw (bc_v8i16 (memopv2i64 addr:$src)),
-                               (i8 imm:$imm))),
-            (PSHUFLWmi addr:$src, imm:$imm)>;
+ let AddedComplexity =3D 5 in
+  defm PSHUFD : sse2_pshuffle<"pshufd", v4i32, X86PShufd>, TB, OpSize;
+
+ // SSE2 with ImmT =3D=3D Imm8 and XS prefix.
+  defm PSHUFHW : sse2_pshuffle<"pshufhw", v8i16, X86PShufhw>, XS;
+
+ // SSE2 with ImmT =3D=3D Imm8 and XD prefix.
+  defm PSHUFLW : sse2_pshuffle<"pshuflw", v8i16, X86PShuflw>, XD;
+
+ def : Pat<(v4f32 (X86PShufd (memopv4f32 addr:$src1), (i8 imm:$imm))),
+           (PSHUFDmi addr:$src1, imm:$imm)>;
+ def : Pat<(v4f32 (X86PShufd VR128:$src1, (i8 imm:$imm))),
+           (PSHUFDri VR128:$src1, imm:$imm)>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -3878,7 +4276,8 @@
       !if(Is2Addr,
           !strconcat(OpcodeStr,"\t{$src2, $dst|$dst, $src2}"),
           !strconcat(OpcodeStr,"\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
-      [(set VR128:$dst, (vt (OpNode VR128:$src1, VR128:$src2)))]>;
+      [(set VR128:$dst, (vt (OpNode VR128:$src1, VR128:$src2)))],
+      IIC_SSE_UNPCK>;
   def rm : PDI<opc, MRMSrcMem,
       (outs VR128:$dst), (ins VR128:$src1, i128mem:$src2),
       !if(Is2Addr,
@@ -3886,96 +4285,104 @@
           !strconcat(OpcodeStr,"\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
       [(set VR128:$dst, (OpNode VR128:$src1,
                                   (bc_frag (memopv2i64
-                                               addr:$src2))))]>;
+                                               addr:$src2))))],
+                                               IIC_SSE_UNPCK>;
+}
+
+multiclass sse2_unpack_y<bits<8> opc, string OpcodeStr, ValueType vt,
+                         SDNode OpNode, PatFrag bc_frag> {
+  def Yrr : PDI<opc, MRMSrcReg,
+      (outs VR256:$dst), (ins VR256:$src1, VR256:$src2),
+      !strconcat(OpcodeStr,"\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+      [(set VR256:$dst, (vt (OpNode VR256:$src1, VR256:$src2)))]>;
+  def Yrm : PDI<opc, MRMSrcMem,
+      (outs VR256:$dst), (ins VR256:$src1, i256mem:$src2),
+      !strconcat(OpcodeStr,"\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+      [(set VR256:$dst, (OpNode VR256:$src1,
+                                  (bc_frag (memopv4i64 addr:$src2))))]>;
 }
=20
 let Predicates =3D [HasAVX] in {
-  defm VPUNPCKLBW  : sse2_unpack<0x60, "vpunpcklbw", v16i8, X86Punpcklbw,
+  defm VPUNPCKLBW  : sse2_unpack<0x60, "vpunpcklbw", v16i8, X86Unpckl,
                                  bc_v16i8, 0>, VEX_4V;
-  defm VPUNPCKLWD  : sse2_unpack<0x61, "vpunpcklwd", v8i16, X86Punpcklwd,
+  defm VPUNPCKLWD  : sse2_unpack<0x61, "vpunpcklwd", v8i16, X86Unpckl,
                                  bc_v8i16, 0>, VEX_4V;
-  defm VPUNPCKLDQ  : sse2_unpack<0x62, "vpunpckldq", v4i32, X86Punpckldq,
+  defm VPUNPCKLDQ  : sse2_unpack<0x62, "vpunpckldq", v4i32, X86Unpckl,
                                  bc_v4i32, 0>, VEX_4V;
-
-  /// FIXME: we could eliminate this and use sse2_unpack instead if tblgen
-  /// knew to collapse (bitconvert VT to VT) into its operand.
-  def VPUNPCKLQDQrr : PDI<0x6C, MRMSrcReg,
-            (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
-            "vpunpcklqdq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-            [(set VR128:$dst, (v2i64 (X86Punpcklqdq VR128:$src1,
-                                                    VR128:$src2)))]>, VEX_=
4V;
-  def VPUNPCKLQDQrm : PDI<0x6C, MRMSrcMem,
-            (outs VR128:$dst), (ins VR128:$src1, i128mem:$src2),
-            "vpunpcklqdq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-            [(set VR128:$dst, (v2i64 (X86Punpcklqdq VR128:$src1,
-                                        (memopv2i64 addr:$src2))))]>, VEX_=
4V;
-
-  defm VPUNPCKHBW  : sse2_unpack<0x68, "vpunpckhbw", v16i8, X86Punpckhbw,
+  defm VPUNPCKLQDQ : sse2_unpack<0x6C, "vpunpcklqdq", v2i64, X86Unpckl,
+                                 bc_v2i64, 0>, VEX_4V;
+
+  defm VPUNPCKHBW  : sse2_unpack<0x68, "vpunpckhbw", v16i8, X86Unpckh,
                                  bc_v16i8, 0>, VEX_4V;
-  defm VPUNPCKHWD  : sse2_unpack<0x69, "vpunpckhwd", v8i16, X86Punpckhwd,
+  defm VPUNPCKHWD  : sse2_unpack<0x69, "vpunpckhwd", v8i16, X86Unpckh,
                                  bc_v8i16, 0>, VEX_4V;
-  defm VPUNPCKHDQ  : sse2_unpack<0x6A, "vpunpckhdq", v4i32, X86Punpckhdq,
+  defm VPUNPCKHDQ  : sse2_unpack<0x6A, "vpunpckhdq", v4i32, X86Unpckh,
                                  bc_v4i32, 0>, VEX_4V;
-
-  /// FIXME: we could eliminate this and use sse2_unpack instead if tblgen
-  /// knew to collapse (bitconvert VT to VT) into its operand.
-  def VPUNPCKHQDQrr : PDI<0x6D, MRMSrcReg,
-             (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
-             "vpunpckhqdq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-             [(set VR128:$dst, (v2i64 (X86Punpckhqdq VR128:$src1,
-                                                     VR128:$src2)))]>, VEX=
_4V;
-  def VPUNPCKHQDQrm : PDI<0x6D, MRMSrcMem,
-             (outs VR128:$dst), (ins VR128:$src1, i128mem:$src2),
-             "vpunpckhqdq\t{$src2, $src1, $dst|$dst, $src1, $src2}",
-             [(set VR128:$dst, (v2i64 (X86Punpckhqdq VR128:$src1,
-                                        (memopv2i64 addr:$src2))))]>, VEX_=
4V;
+  defm VPUNPCKHQDQ : sse2_unpack<0x6D, "vpunpckhqdq", v2i64, X86Unpckh,
+                                 bc_v2i64, 0>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2] in {
+  defm VPUNPCKLBW  : sse2_unpack_y<0x60, "vpunpcklbw", v32i8, X86Unpckl,
+                                   bc_v32i8>, VEX_4V;
+  defm VPUNPCKLWD  : sse2_unpack_y<0x61, "vpunpcklwd", v16i16, X86Unpckl,
+                                   bc_v16i16>, VEX_4V;
+  defm VPUNPCKLDQ  : sse2_unpack_y<0x62, "vpunpckldq", v8i32, X86Unpckl,
+                                   bc_v8i32>, VEX_4V;
+  defm VPUNPCKLQDQ : sse2_unpack_y<0x6C, "vpunpcklqdq", v4i64, X86Unpckl,
+                                   bc_v4i64>, VEX_4V;
+
+  defm VPUNPCKHBW  : sse2_unpack_y<0x68, "vpunpckhbw", v32i8, X86Unpckh,
+                                   bc_v32i8>, VEX_4V;
+  defm VPUNPCKHWD  : sse2_unpack_y<0x69, "vpunpckhwd", v16i16, X86Unpckh,
+                                   bc_v16i16>, VEX_4V;
+  defm VPUNPCKHDQ  : sse2_unpack_y<0x6A, "vpunpckhdq", v8i32, X86Unpckh,
+                                   bc_v8i32>, VEX_4V;
+  defm VPUNPCKHQDQ : sse2_unpack_y<0x6D, "vpunpckhqdq", v4i64, X86Unpckh,
+                                   bc_v4i64>, VEX_4V;
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
-  defm PUNPCKLBW  : sse2_unpack<0x60, "punpcklbw", v16i8, X86Punpcklbw, bc=
_v16i8>;
-  defm PUNPCKLWD  : sse2_unpack<0x61, "punpcklwd", v8i16, X86Punpcklwd, bc=
_v8i16>;
-  defm PUNPCKLDQ  : sse2_unpack<0x62, "punpckldq", v4i32, X86Punpckldq, bc=
_v4i32>;
-
-  /// FIXME: we could eliminate this and use sse2_unpack instead if tblgen
-  /// knew to collapse (bitconvert VT to VT) into its operand.
-  def PUNPCKLQDQrr : PDI<0x6C, MRMSrcReg,
-                         (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
-                         "punpcklqdq\t{$src2, $dst|$dst, $src2}",
-                        [(set VR128:$dst,
-                          (v2i64 (X86Punpcklqdq VR128:$src1, VR128:$src2))=
)]>;
-  def PUNPCKLQDQrm : PDI<0x6C, MRMSrcMem,
-                         (outs VR128:$dst), (ins VR128:$src1, i128mem:$src=
2),
-                         "punpcklqdq\t{$src2, $dst|$dst, $src2}",
-                        [(set VR128:$dst,
-                          (v2i64 (X86Punpcklqdq VR128:$src1,
-                                         (memopv2i64 addr:$src2))))]>;
-
-  defm PUNPCKHBW  : sse2_unpack<0x68, "punpckhbw", v16i8, X86Punpckhbw, bc=
_v16i8>;
-  defm PUNPCKHWD  : sse2_unpack<0x69, "punpckhwd", v8i16, X86Punpckhwd, bc=
_v8i16>;
-  defm PUNPCKHDQ  : sse2_unpack<0x6A, "punpckhdq", v4i32, X86Punpckhdq, bc=
_v4i32>;
-
-  /// FIXME: we could eliminate this and use sse2_unpack instead if tblgen
-  /// knew to collapse (bitconvert VT to VT) into its operand.
-  def PUNPCKHQDQrr : PDI<0x6D, MRMSrcReg,
-                         (outs VR128:$dst), (ins VR128:$src1, VR128:$src2),
-                         "punpckhqdq\t{$src2, $dst|$dst, $src2}",
-                        [(set VR128:$dst,
-                          (v2i64 (X86Punpckhqdq VR128:$src1, VR128:$src2))=
)]>;
-  def PUNPCKHQDQrm : PDI<0x6D, MRMSrcMem,
-                        (outs VR128:$dst), (ins VR128:$src1, i128mem:$src2=
),
-                        "punpckhqdq\t{$src2, $dst|$dst, $src2}",
-                        [(set VR128:$dst,
-                          (v2i64 (X86Punpckhqdq VR128:$src1,
-                                         (memopv2i64 addr:$src2))))]>;
+  defm PUNPCKLBW  : sse2_unpack<0x60, "punpcklbw", v16i8, X86Unpckl,
+                                bc_v16i8>;
+  defm PUNPCKLWD  : sse2_unpack<0x61, "punpcklwd", v8i16, X86Unpckl,
+                                bc_v8i16>;
+  defm PUNPCKLDQ  : sse2_unpack<0x62, "punpckldq", v4i32, X86Unpckl,
+                                bc_v4i32>;
+  defm PUNPCKLQDQ : sse2_unpack<0x6C, "punpcklqdq", v2i64, X86Unpckl,
+                                bc_v2i64>;
+
+  defm PUNPCKHBW  : sse2_unpack<0x68, "punpckhbw", v16i8, X86Unpckh,
+                                bc_v16i8>;
+  defm PUNPCKHWD  : sse2_unpack<0x69, "punpckhwd", v8i16, X86Unpckh,
+                                bc_v8i16>;
+  defm PUNPCKHDQ  : sse2_unpack<0x6A, "punpckhdq", v4i32, X86Unpckh,
+                                bc_v4i32>;
+  defm PUNPCKHQDQ : sse2_unpack<0x6D, "punpckhqdq", v2i64, X86Unpckh,
+                                bc_v2i64>;
 }
 } // ExeDomain =3D SSEPackedInt
=20
-// Splat v2f64 / v2i64
-let AddedComplexity =3D 10 in {
-  def : Pat<(splat_lo (v2i64 VR128:$src), (undef)),
-            (PUNPCKLQDQrr VR128:$src, VR128:$src)>, Requires<[HasSSE2]>;
-  def : Pat<(splat_lo (v2i64 VR128:$src), (undef)),
-            (VPUNPCKLQDQrr VR128:$src, VR128:$src)>, Requires<[HasAVX]>;
+// Patterns for using AVX1 instructions with integer vectors
+// Here to give AVX2 priority
+let Predicates =3D [HasAVX] in {
+  def : Pat<(v8i32 (X86Unpckl VR256:$src1, (bc_v8i32 (memopv4i64 addr:$src=
2)))),
+            (VUNPCKLPSYrm VR256:$src1, addr:$src2)>;
+  def : Pat<(v8i32 (X86Unpckl VR256:$src1, VR256:$src2)),
+            (VUNPCKLPSYrr VR256:$src1, VR256:$src2)>;
+  def : Pat<(v8i32 (X86Unpckh VR256:$src1, (bc_v8i32 (memopv4i64 addr:$src=
2)))),
+            (VUNPCKHPSYrm VR256:$src1, addr:$src2)>;
+  def : Pat<(v8i32 (X86Unpckh VR256:$src1, VR256:$src2)),
+            (VUNPCKHPSYrr VR256:$src1, VR256:$src2)>;
+
+  def : Pat<(v4i64 (X86Unpckl VR256:$src1, (memopv4i64 addr:$src2))),
+            (VUNPCKLPDYrm VR256:$src1, addr:$src2)>;
+  def : Pat<(v4i64 (X86Unpckl VR256:$src1, VR256:$src2)),
+            (VUNPCKLPDYrr VR256:$src1, VR256:$src2)>;
+  def : Pat<(v4i64 (X86Unpckh VR256:$src1, (memopv4i64 addr:$src2))),
+            (VUNPCKHPDYrm VR256:$src1, addr:$src2)>;
+  def : Pat<(v4i64 (X86Unpckh VR256:$src1, VR256:$src2)),
+            (VUNPCKHPDYrr VR256:$src1, VR256:$src2)>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -3991,7 +4398,7 @@
            "pinsrw\t{$src3, $src2, $dst|$dst, $src2, $src3}",
            "vpinsrw\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
"),
        [(set VR128:$dst,
-         (X86pinsrw VR128:$src1, GR32:$src2, imm:$src3))]>;
+         (X86pinsrw VR128:$src1, GR32:$src2, imm:$src3))], IIC_SSE_PINSRW>;
   def rmi : Ii8<0xC4, MRMSrcMem,
                        (outs VR128:$dst), (ins VR128:$src1,
                         i16mem:$src2, i32i8imm:$src3),
@@ -4000,7 +4407,7 @@
            "vpinsrw\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
"),
        [(set VR128:$dst,
          (X86pinsrw VR128:$src1, (extloadi16 addr:$src2),
-                    imm:$src3))]>;
+                    imm:$src3))], IIC_SSE_PINSRW>;
 }
=20
 // Extract
@@ -4014,7 +4421,7 @@
                     (outs GR32:$dst), (ins VR128:$src1, i32i8imm:$src2),
                     "pextrw\t{$src2, $src1, $dst|$dst, $src1, $src2}",
                     [(set GR32:$dst, (X86pextrw (v8i16 VR128:$src1),
-                                                imm:$src2))]>;
+                                                imm:$src2))], IIC_SSE_PEXT=
RW>;
=20
 // Insert
 let Predicates =3D [HasAVX] in {
@@ -4038,12 +4445,23 @@
=20
 def VPMOVMSKBrr  : VPDI<0xD7, MRMSrcReg, (outs GR32:$dst), (ins VR128:$src=
),
            "pmovmskb\t{$src, $dst|$dst, $src}",
-           [(set GR32:$dst, (int_x86_sse2_pmovmskb_128 VR128:$src))]>, VEX;
+           [(set GR32:$dst, (int_x86_sse2_pmovmskb_128 VR128:$src))],
+           IIC_SSE_MOVMSK>, VEX;
 def VPMOVMSKBr64r : VPDI<0xD7, MRMSrcReg, (outs GR64:$dst), (ins VR128:$sr=
c),
+           "pmovmskb\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVMSK>, VEX;
+
+let Predicates =3D [HasAVX2] in {
+def VPMOVMSKBYrr  : VPDI<0xD7, MRMSrcReg, (outs GR32:$dst), (ins VR256:$sr=
c),
+           "pmovmskb\t{$src, $dst|$dst, $src}",
+           [(set GR32:$dst, (int_x86_avx2_pmovmskb VR256:$src))]>, VEX;
+def VPMOVMSKBYr64r : VPDI<0xD7, MRMSrcReg, (outs GR64:$dst), (ins VR256:$s=
rc),
            "pmovmskb\t{$src, $dst|$dst, $src}", []>, VEX;
+}
+
 def PMOVMSKBrr : PDI<0xD7, MRMSrcReg, (outs GR32:$dst), (ins VR128:$src),
            "pmovmskb\t{$src, $dst|$dst, $src}",
-           [(set GR32:$dst, (int_x86_sse2_pmovmskb_128 VR128:$src))]>;
+           [(set GR32:$dst, (int_x86_sse2_pmovmskb_128 VR128:$src))],
+           IIC_SSE_MOVMSK>;
=20
 } // ExeDomain =3D SSEPackedInt
=20
@@ -4057,21 +4475,25 @@
 def VMASKMOVDQU : VPDI<0xF7, MRMSrcReg, (outs),
            (ins VR128:$src, VR128:$mask),
            "maskmovdqu\t{$mask, $src|$src, $mask}",
-           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, EDI)]>, VEX;
+           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, EDI)],
+           IIC_SSE_MASKMOV>, VEX;
 let Uses =3D [RDI] in
 def VMASKMOVDQU64 : VPDI<0xF7, MRMSrcReg, (outs),
            (ins VR128:$src, VR128:$mask),
            "maskmovdqu\t{$mask, $src|$src, $mask}",
-           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, RDI)]>, VEX;
+           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, RDI)],
+           IIC_SSE_MASKMOV>, VEX;
=20
 let Uses =3D [EDI] in
 def MASKMOVDQU : PDI<0xF7, MRMSrcReg, (outs), (ins VR128:$src, VR128:$mask=
),
            "maskmovdqu\t{$mask, $src|$src, $mask}",
-           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, EDI)]>;
+           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, EDI)],
+           IIC_SSE_MASKMOV>;
 let Uses =3D [RDI] in
 def MASKMOVDQU64 : PDI<0xF7, MRMSrcReg, (outs), (ins VR128:$src, VR128:$ma=
sk),
            "maskmovdqu\t{$mask, $src|$src, $mask}",
-           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, RDI)]>;
+           [(int_x86_sse2_maskmov_dqu VR128:$src, VR128:$mask, RDI)],
+           IIC_SSE_MASKMOV>;
=20
 } // ExeDomain =3D SSEPackedInt
=20
@@ -4085,54 +4507,65 @@
 def VMOVDI2PDIrr : VPDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR32:$src=
),
                       "movd\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst,
-                        (v4i32 (scalar_to_vector GR32:$src)))]>, VEX;
+                        (v4i32 (scalar_to_vector GR32:$src)))], IIC_SSE_MO=
VDQ>,
+                        VEX;
 def VMOVDI2PDIrm : VPDI<0x6E, MRMSrcMem, (outs VR128:$dst), (ins i32mem:$s=
rc),
                       "movd\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst,
-                        (v4i32 (scalar_to_vector (loadi32 addr:$src))))]>,
+                        (v4i32 (scalar_to_vector (loadi32 addr:$src))))],
+                        IIC_SSE_MOVDQ>,
                       VEX;
 def VMOV64toPQIrr : VRPDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR64:$s=
rc),
                         "mov{d|q}\t{$src, $dst|$dst, $src}",
                         [(set VR128:$dst,
-                          (v2i64 (scalar_to_vector GR64:$src)))]>, VEX;
+                          (v2i64 (scalar_to_vector GR64:$src)))],
+                          IIC_SSE_MOVDQ>, VEX;
 def VMOV64toSDrr : VRPDI<0x6E, MRMSrcReg, (outs FR64:$dst), (ins GR64:$src=
),
                        "mov{d|q}\t{$src, $dst|$dst, $src}",
-                       [(set FR64:$dst, (bitconvert GR64:$src))]>, VEX;
+                       [(set FR64:$dst, (bitconvert GR64:$src))],
+                       IIC_SSE_MOVDQ>, VEX;
=20
 def MOVDI2PDIrr : PDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR32:$src),
                       "movd\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst,
-                        (v4i32 (scalar_to_vector GR32:$src)))]>;
+                        (v4i32 (scalar_to_vector GR32:$src)))], IIC_SSE_MO=
VDQ>;
 def MOVDI2PDIrm : PDI<0x6E, MRMSrcMem, (outs VR128:$dst), (ins i32mem:$src=
),
                       "movd\t{$src, $dst|$dst, $src}",
                       [(set VR128:$dst,
-                        (v4i32 (scalar_to_vector (loadi32 addr:$src))))]>;
+                        (v4i32 (scalar_to_vector (loadi32 addr:$src))))],
+                        IIC_SSE_MOVDQ>;
 def MOV64toPQIrr : RPDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR64:$src=
),
                         "mov{d|q}\t{$src, $dst|$dst, $src}",
                         [(set VR128:$dst,
-                          (v2i64 (scalar_to_vector GR64:$src)))]>;
+                          (v2i64 (scalar_to_vector GR64:$src)))],
+                          IIC_SSE_MOVDQ>;
 def MOV64toSDrr : RPDI<0x6E, MRMSrcReg, (outs FR64:$dst), (ins GR64:$src),
                        "mov{d|q}\t{$src, $dst|$dst, $src}",
-                       [(set FR64:$dst, (bitconvert GR64:$src))]>;
+                       [(set FR64:$dst, (bitconvert GR64:$src))],
+                       IIC_SSE_MOVDQ>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Move Int Doubleword to Single Scalar
 //
 def VMOVDI2SSrr  : VPDI<0x6E, MRMSrcReg, (outs FR32:$dst), (ins GR32:$src),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(set FR32:$dst, (bitconvert GR32:$src))]>, VEX;
+                      [(set FR32:$dst, (bitconvert GR32:$src))],
+                      IIC_SSE_MOVDQ>, VEX;
=20
 def VMOVDI2SSrm  : VPDI<0x6E, MRMSrcMem, (outs FR32:$dst), (ins i32mem:$sr=
c),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(set FR32:$dst, (bitconvert (loadi32 addr:$src)))]>,
+                      [(set FR32:$dst, (bitconvert (loadi32 addr:$src)))],
+                      IIC_SSE_MOVDQ>,
                       VEX;
 def MOVDI2SSrr  : PDI<0x6E, MRMSrcReg, (outs FR32:$dst), (ins GR32:$src),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(set FR32:$dst, (bitconvert GR32:$src))]>;
+                      [(set FR32:$dst, (bitconvert GR32:$src))],
+                      IIC_SSE_MOVDQ>;
=20
 def MOVDI2SSrm  : PDI<0x6E, MRMSrcMem, (outs FR32:$dst), (ins i32mem:$src),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(set FR32:$dst, (bitconvert (loadi32 addr:$src)))]>;
+                      [(set FR32:$dst, (bitconvert (loadi32 addr:$src)))],
+                      IIC_SSE_MOVDQ>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Move Packed Doubleword Int to Packed Double Int
@@ -4140,20 +4573,22 @@
 def VMOVPDI2DIrr  : VPDI<0x7E, MRMDestReg, (outs GR32:$dst), (ins VR128:$s=
rc),
                        "movd\t{$src, $dst|$dst, $src}",
                        [(set GR32:$dst, (vector_extract (v4i32 VR128:$src),
-                                        (iPTR 0)))]>, VEX;
+                                        (iPTR 0)))], IIC_SSE_MOVD_ToGP>, V=
EX;
 def VMOVPDI2DImr  : VPDI<0x7E, MRMDestMem, (outs),
                        (ins i32mem:$dst, VR128:$src),
                        "movd\t{$src, $dst|$dst, $src}",
                        [(store (i32 (vector_extract (v4i32 VR128:$src),
-                                     (iPTR 0))), addr:$dst)]>, VEX;
+                                     (iPTR 0))), addr:$dst)], IIC_SSE_MOVD=
Q>,
+                                     VEX;
 def MOVPDI2DIrr  : PDI<0x7E, MRMDestReg, (outs GR32:$dst), (ins VR128:$src=
),
                        "movd\t{$src, $dst|$dst, $src}",
                        [(set GR32:$dst, (vector_extract (v4i32 VR128:$src),
-                                        (iPTR 0)))]>;
+                                        (iPTR 0)))], IIC_SSE_MOVD_ToGP>;
 def MOVPDI2DImr  : PDI<0x7E, MRMDestMem, (outs), (ins i32mem:$dst, VR128:$=
src),
                        "movd\t{$src, $dst|$dst, $src}",
                        [(store (i32 (vector_extract (v4i32 VR128:$src),
-                                     (iPTR 0))), addr:$dst)]>;
+                                     (iPTR 0))), addr:$dst)],
+                                     IIC_SSE_MOVDQ>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Move Packed Doubleword Int first element to Doubleword Int
@@ -4161,13 +4596,15 @@
 def VMOVPQIto64rr : I<0x7E, MRMDestReg, (outs GR64:$dst), (ins VR128:$src),
                           "mov{d|q}\t{$src, $dst|$dst, $src}",
                           [(set GR64:$dst, (vector_extract (v2i64 VR128:$s=
rc),
-                                                           (iPTR 0)))]>,
+                                                           (iPTR 0)))],
+                                                           IIC_SSE_MOVD_To=
GP>,
                       TB, OpSize, VEX, VEX_W, Requires<[HasAVX, In64BitMod=
e]>;
=20
 def MOVPQIto64rr : RPDI<0x7E, MRMDestReg, (outs GR64:$dst), (ins VR128:$sr=
c),
                         "mov{d|q}\t{$src, $dst|$dst, $src}",
                         [(set GR64:$dst, (vector_extract (v2i64 VR128:$src=
),
-                                                         (iPTR 0)))]>;
+                                                         (iPTR 0)))],
+                                                         IIC_SSE_MOVD_ToGP=
>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Bitcast FR64 <-> GR64
@@ -4179,36 +4616,45 @@
                         VEX;
 def VMOVSDto64rr : VRPDI<0x7E, MRMDestReg, (outs GR64:$dst), (ins FR64:$sr=
c),
                          "mov{d|q}\t{$src, $dst|$dst, $src}",
-                         [(set GR64:$dst, (bitconvert FR64:$src))]>;
+                         [(set GR64:$dst, (bitconvert FR64:$src))],
+                         IIC_SSE_MOVDQ>, VEX;
 def VMOVSDto64mr : VRPDI<0x7E, MRMDestMem, (outs), (ins i64mem:$dst, FR64:=
$src),
                          "movq\t{$src, $dst|$dst, $src}",
-                         [(store (i64 (bitconvert FR64:$src)), addr:$dst)]=
>;
+                         [(store (i64 (bitconvert FR64:$src)), addr:$dst)],
+                         IIC_SSE_MOVDQ>, VEX;
=20
 def MOV64toSDrm : S3SI<0x7E, MRMSrcMem, (outs FR64:$dst), (ins i64mem:$src=
),
                        "movq\t{$src, $dst|$dst, $src}",
-                       [(set FR64:$dst, (bitconvert (loadi64 addr:$src)))]=
>;
+                       [(set FR64:$dst, (bitconvert (loadi64 addr:$src)))],
+                       IIC_SSE_MOVDQ>;
 def MOVSDto64rr : RPDI<0x7E, MRMDestReg, (outs GR64:$dst), (ins FR64:$src),
                        "mov{d|q}\t{$src, $dst|$dst, $src}",
-                       [(set GR64:$dst, (bitconvert FR64:$src))]>;
+                       [(set GR64:$dst, (bitconvert FR64:$src))],
+                       IIC_SSE_MOVD_ToGP>;
 def MOVSDto64mr : RPDI<0x7E, MRMDestMem, (outs), (ins i64mem:$dst, FR64:$s=
rc),
                        "movq\t{$src, $dst|$dst, $src}",
-                       [(store (i64 (bitconvert FR64:$src)), addr:$dst)]>;
+                       [(store (i64 (bitconvert FR64:$src)), addr:$dst)],
+                       IIC_SSE_MOVDQ>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Move Scalar Single to Double Int
 //
 def VMOVSS2DIrr  : VPDI<0x7E, MRMDestReg, (outs GR32:$dst), (ins FR32:$src=
),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(set GR32:$dst, (bitconvert FR32:$src))]>, VEX;
+                      [(set GR32:$dst, (bitconvert FR32:$src))],
+                      IIC_SSE_MOVD_ToGP>, VEX;
 def VMOVSS2DImr  : VPDI<0x7E, MRMDestMem, (outs), (ins i32mem:$dst, FR32:$=
src),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(store (i32 (bitconvert FR32:$src)), addr:$dst)]>, =
VEX;
+                      [(store (i32 (bitconvert FR32:$src)), addr:$dst)],
+                      IIC_SSE_MOVDQ>, VEX;
 def MOVSS2DIrr  : PDI<0x7E, MRMDestReg, (outs GR32:$dst), (ins FR32:$src),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(set GR32:$dst, (bitconvert FR32:$src))]>;
+                      [(set GR32:$dst, (bitconvert FR32:$src))],
+                      IIC_SSE_MOVD_ToGP>;
 def MOVSS2DImr  : PDI<0x7E, MRMDestMem, (outs), (ins i32mem:$dst, FR32:$sr=
c),
                       "movd\t{$src, $dst|$dst, $src}",
-                      [(store (i32 (bitconvert FR32:$src)), addr:$dst)]>;
+                      [(store (i32 (bitconvert FR32:$src)), addr:$dst)],
+                      IIC_SSE_MOVDQ>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Patterns and instructions to describe movd/movq to XMM register zero-ex=
tends
@@ -4217,23 +4663,26 @@
 def VMOVZDI2PDIrr : VPDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR32:$sr=
c),
                        "movd\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (v4i32 (X86vzmovl
-                                      (v4i32 (scalar_to_vector GR32:$src))=
)))]>,
-                                      VEX;
+                                      (v4i32 (scalar_to_vector GR32:$src))=
)))],
+                                      IIC_SSE_MOVDQ>, VEX;
 def VMOVZQI2PQIrr : VPDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR64:$sr=
c),
                        "mov{d|q}\t{$src, $dst|$dst, $src}", // X86-64 only
                        [(set VR128:$dst, (v2i64 (X86vzmovl
-                                      (v2i64 (scalar_to_vector GR64:$src))=
)))]>,
+                                      (v2i64 (scalar_to_vector GR64:$src))=
)))],
+                                      IIC_SSE_MOVDQ>,
                                       VEX, VEX_W;
 }
 let AddedComplexity =3D 15 in {
 def MOVZDI2PDIrr : PDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR32:$src),
                        "movd\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (v4i32 (X86vzmovl
-                                      (v4i32 (scalar_to_vector GR32:$src))=
)))]>;
+                                      (v4i32 (scalar_to_vector GR32:$src))=
)))],
+                                      IIC_SSE_MOVDQ>;
 def MOVZQI2PQIrr : RPDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR64:$src=
),
                        "mov{d|q}\t{$src, $dst|$dst, $src}", // X86-64 only
                        [(set VR128:$dst, (v2i64 (X86vzmovl
-                                      (v2i64 (scalar_to_vector GR64:$src))=
)))]>;
+                                      (v2i64 (scalar_to_vector GR64:$src))=
)))],
+                                      IIC_SSE_MOVDQ>;
 }
=20
 let AddedComplexity =3D 20 in {
@@ -4241,29 +4690,19 @@
                        "movd\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst,
                          (v4i32 (X86vzmovl (v4i32 (scalar_to_vector
-                                                   (loadi32 addr:$src)))))=
)]>,
-                                                   VEX;
+                                                   (loadi32 addr:$src)))))=
)],
+                                                   IIC_SSE_MOVDQ>, VEX;
 def MOVZDI2PDIrm : PDI<0x6E, MRMSrcMem, (outs VR128:$dst), (ins i32mem:$sr=
c),
                        "movd\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst,
                          (v4i32 (X86vzmovl (v4i32 (scalar_to_vector
-                                                   (loadi32 addr:$src)))))=
)]>;
-}
-
-let Predicates =3D [HasSSE2], AddedComplexity =3D 20 in {
-  def : Pat<(v4i32 (X86vzmovl (loadv4i32 addr:$src))),
-            (MOVZDI2PDIrm addr:$src)>;
-  def : Pat<(v4i32 (X86vzmovl (bc_v4i32 (loadv4f32 addr:$src)))),
-            (MOVZDI2PDIrm addr:$src)>;
-  def : Pat<(v4i32 (X86vzmovl (bc_v4i32 (loadv2i64 addr:$src)))),
-            (MOVZDI2PDIrm addr:$src)>;
+                                                   (loadi32 addr:$src)))))=
)],
+                                                   IIC_SSE_MOVDQ>;
 }
=20
 let Predicates =3D [HasAVX] in {
   // AVX 128-bit movd/movq instruction write zeros in the high 128-bit par=
t.
   let AddedComplexity =3D 20 in {
-    def : Pat<(v4i32 (X86vzmovl (loadv4i32 addr:$src))),
-              (VMOVZDI2PDIrm addr:$src)>;
     def : Pat<(v4i32 (X86vzmovl (bc_v4i32 (loadv4f32 addr:$src)))),
               (VMOVZDI2PDIrm addr:$src)>;
     def : Pat<(v4i32 (X86vzmovl (bc_v4i32 (loadv2i64 addr:$src)))),
@@ -4278,6 +4717,13 @@
             (SUBREG_TO_REG (i64 0), (VMOVZQI2PQIrr GR64:$src), sub_xmm)>;
 }
=20
+let Predicates =3D [HasSSE2], AddedComplexity =3D 20 in {
+  def : Pat<(v4i32 (X86vzmovl (bc_v4i32 (loadv4f32 addr:$src)))),
+            (MOVZDI2PDIrm addr:$src)>;
+  def : Pat<(v4i32 (X86vzmovl (bc_v4i32 (loadv2i64 addr:$src)))),
+            (MOVZDI2PDIrm addr:$src)>;
+}
+
 // These are the correct encodings of the instructions so that we know how=
 to
 // read correct assembly, even though we continue to emit the wrong ones f=
or
 // compatibility with Darwin's buggy assembler.
@@ -4309,7 +4755,8 @@
 def MOVQI2PQIrm : I<0x7E, MRMSrcMem, (outs VR128:$dst), (ins i64mem:$src),
                     "movq\t{$src, $dst|$dst, $src}",
                     [(set VR128:$dst,
-                      (v2i64 (scalar_to_vector (loadi64 addr:$src))))]>, X=
S,
+                      (v2i64 (scalar_to_vector (loadi64 addr:$src))))],
+                      IIC_SSE_MOVDQ>, XS,
                     Requires<[HasSSE2]>; // SSE2 instruction with XS Prefix
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -4318,11 +4765,13 @@
 def VMOVPQI2QImr : VPDI<0xD6, MRMDestMem, (outs), (ins i64mem:$dst, VR128:=
$src),
                       "movq\t{$src, $dst|$dst, $src}",
                       [(store (i64 (vector_extract (v2i64 VR128:$src),
-                                    (iPTR 0))), addr:$dst)]>, VEX;
+                                    (iPTR 0))), addr:$dst)],
+                                    IIC_SSE_MOVDQ>, VEX;
 def MOVPQI2QImr : PDI<0xD6, MRMDestMem, (outs), (ins i64mem:$dst, VR128:$s=
rc),
                       "movq\t{$src, $dst|$dst, $src}",
                       [(store (i64 (vector_extract (v2i64 VR128:$src),
-                                    (iPTR 0))), addr:$dst)]>;
+                                    (iPTR 0))), addr:$dst)],
+                                    IIC_SSE_MOVDQ>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Store / copy lower 64-bits of a XMM register.
@@ -4332,14 +4781,16 @@
                      [(int_x86_sse2_storel_dq addr:$dst, VR128:$src)]>, VE=
X;
 def MOVLQ128mr : PDI<0xD6, MRMDestMem, (outs), (ins i64mem:$dst, VR128:$sr=
c),
                      "movq\t{$src, $dst|$dst, $src}",
-                     [(int_x86_sse2_storel_dq addr:$dst, VR128:$src)]>;
+                     [(int_x86_sse2_storel_dq addr:$dst, VR128:$src)],
+                     IIC_SSE_MOVDQ>;
=20
 let AddedComplexity =3D 20 in
 def VMOVZQI2PQIrm : I<0x7E, MRMSrcMem, (outs VR128:$dst), (ins i64mem:$src=
),
                      "vmovq\t{$src, $dst|$dst, $src}",
                      [(set VR128:$dst,
                        (v2i64 (X86vzmovl (v2i64 (scalar_to_vector
-                                                 (loadi64 addr:$src))))))]=
>,
+                                                 (loadi64 addr:$src))))))],
+                                                 IIC_SSE_MOVDQ>,
                      XS, VEX, Requires<[HasAVX]>;
=20
 let AddedComplexity =3D 20 in
@@ -4347,17 +4798,10 @@
                      "movq\t{$src, $dst|$dst, $src}",
                      [(set VR128:$dst,
                        (v2i64 (X86vzmovl (v2i64 (scalar_to_vector
-                                                 (loadi64 addr:$src))))))]=
>,
+                                                 (loadi64 addr:$src))))))],
+                                                 IIC_SSE_MOVDQ>,
                      XS, Requires<[HasSSE2]>;
=20
-let Predicates =3D [HasSSE2], AddedComplexity =3D 20 in {
-  def : Pat<(v2i64 (X86vzmovl (loadv2i64 addr:$src))),
-            (MOVZQI2PQIrm addr:$src)>;
-  def : Pat<(v2i64 (X86vzmovl (bc_v2i64 (loadv4f32 addr:$src)))),
-            (MOVZQI2PQIrm addr:$src)>;
-  def : Pat<(v2i64 (X86vzload addr:$src)), (MOVZQI2PQIrm addr:$src)>;
-}
-
 let Predicates =3D [HasAVX], AddedComplexity =3D 20 in {
   def : Pat<(v2i64 (X86vzmovl (loadv2i64 addr:$src))),
             (VMOVZQI2PQIrm addr:$src)>;
@@ -4367,6 +4811,21 @@
             (VMOVZQI2PQIrm addr:$src)>;
 }
=20
+let Predicates =3D [HasSSE2], AddedComplexity =3D 20 in {
+  def : Pat<(v2i64 (X86vzmovl (loadv2i64 addr:$src))),
+            (MOVZQI2PQIrm addr:$src)>;
+  def : Pat<(v2i64 (X86vzmovl (bc_v2i64 (loadv4f32 addr:$src)))),
+            (MOVZQI2PQIrm addr:$src)>;
+  def : Pat<(v2i64 (X86vzload addr:$src)), (MOVZQI2PQIrm addr:$src)>;
+}
+
+let Predicates =3D [HasAVX] in {
+def : Pat<(v4i64 (alignedX86vzload addr:$src)),
+          (SUBREG_TO_REG (i32 0), (VMOVAPSrm addr:$src), sub_xmm)>;
+def : Pat<(v4i64 (X86vzload addr:$src)),
+          (SUBREG_TO_REG (i32 0), (VMOVUPSrm addr:$src), sub_xmm)>;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // Moving from XMM to XMM and clear upper 64 bits. Note, there is a bug in
 // IA32 document. movq xmm1, xmm2 does clear the high bits.
@@ -4374,51 +4833,58 @@
 let AddedComplexity =3D 15 in
 def VMOVZPQILo2PQIrr : I<0x7E, MRMSrcReg, (outs VR128:$dst), (ins VR128:$s=
rc),
                         "vmovq\t{$src, $dst|$dst, $src}",
-                    [(set VR128:$dst, (v2i64 (X86vzmovl (v2i64 VR128:$src)=
)))]>,
+                    [(set VR128:$dst, (v2i64 (X86vzmovl (v2i64 VR128:$src)=
)))],
+                    IIC_SSE_MOVQ_RR>,
                       XS, VEX, Requires<[HasAVX]>;
 let AddedComplexity =3D 15 in
 def MOVZPQILo2PQIrr : I<0x7E, MRMSrcReg, (outs VR128:$dst), (ins VR128:$sr=
c),
                         "movq\t{$src, $dst|$dst, $src}",
-                    [(set VR128:$dst, (v2i64 (X86vzmovl (v2i64 VR128:$src)=
)))]>,
+                    [(set VR128:$dst, (v2i64 (X86vzmovl (v2i64 VR128:$src)=
)))],
+                    IIC_SSE_MOVQ_RR>,
                       XS, Requires<[HasSSE2]>;
=20
 let AddedComplexity =3D 20 in
 def VMOVZPQILo2PQIrm : I<0x7E, MRMSrcMem, (outs VR128:$dst), (ins i128mem:=
$src),
                         "vmovq\t{$src, $dst|$dst, $src}",
                     [(set VR128:$dst, (v2i64 (X86vzmovl
-                                             (loadv2i64 addr:$src))))]>,
+                                             (loadv2i64 addr:$src))))],
+                                             IIC_SSE_MOVDQ>,
                       XS, VEX, Requires<[HasAVX]>;
 let AddedComplexity =3D 20 in {
 def MOVZPQILo2PQIrm : I<0x7E, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$=
src),
                         "movq\t{$src, $dst|$dst, $src}",
                     [(set VR128:$dst, (v2i64 (X86vzmovl
-                                             (loadv2i64 addr:$src))))]>,
+                                             (loadv2i64 addr:$src))))],
+                                             IIC_SSE_MOVDQ>,
                       XS, Requires<[HasSSE2]>;
 }
=20
 let AddedComplexity =3D 20 in {
+  let Predicates =3D [HasAVX] in {
+    def : Pat<(v2i64 (X86vzmovl (loadv2i64 addr:$src))),
+              (VMOVZPQILo2PQIrm addr:$src)>;
+    def : Pat<(v2f64 (X86vzmovl (v2f64 VR128:$src))),
+              (VMOVZPQILo2PQIrr VR128:$src)>;
+  }
   let Predicates =3D [HasSSE2] in {
-    def : Pat<(v2i64 (X86vzmovl (bc_v2i64 (loadv4i32 addr:$src)))),
+    def : Pat<(v2i64 (X86vzmovl (loadv2i64 addr:$src))),
               (MOVZPQILo2PQIrm addr:$src)>;
     def : Pat<(v2f64 (X86vzmovl (v2f64 VR128:$src))),
               (MOVZPQILo2PQIrr VR128:$src)>;
   }
-  let Predicates =3D [HasAVX] in {
-    def : Pat<(v2i64 (X86vzmovl (bc_v2i64 (loadv4i32 addr:$src)))),
-              (VMOVZPQILo2PQIrm addr:$src)>;
-    def : Pat<(v2f64 (X86vzmovl (v2f64 VR128:$src))),
-              (VMOVZPQILo2PQIrr VR128:$src)>;
-  }
 }
=20
 // Instructions to match in the assembler
 def VMOVQs64rr : VPDI<0x6E, MRMSrcReg, (outs VR128:$dst), (ins GR64:$src),
-                      "movq\t{$src, $dst|$dst, $src}", []>, VEX, VEX_W;
+                      "movq\t{$src, $dst|$dst, $src}", [],
+                      IIC_SSE_MOVDQ>, VEX, VEX_W;
 def VMOVQd64rr : VPDI<0x7E, MRMDestReg, (outs GR64:$dst), (ins VR128:$src),
-                      "movq\t{$src, $dst|$dst, $src}", []>, VEX, VEX_W;
+                      "movq\t{$src, $dst|$dst, $src}", [],
+                      IIC_SSE_MOVDQ>, VEX, VEX_W;
 // Recognize "movd" with GR64 destination, but encode as a "movq"
 def VMOVQd64rr_alt : VPDI<0x7E, MRMDestReg, (outs GR64:$dst), (ins VR128:$=
src),
-                          "movd\t{$src, $dst|$dst, $src}", []>, VEX, VEX_W;
+                          "movd\t{$src, $dst|$dst, $src}", [],
+                          IIC_SSE_MOVDQ>, VEX, VEX_W;
=20
 // Instructions for the disassembler
 // xr =3D XMM register
@@ -4428,7 +4894,7 @@
 def VMOVQxrxr: I<0x7E, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                  "vmovq\t{$src, $dst|$dst, $src}", []>, VEX, XS;
 def MOVQxrxr : I<0x7E, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                 "movq\t{$src, $dst|$dst, $src}", []>, XS;
+                 "movq\t{$src, $dst|$dst, $src}", [], IIC_SSE_MOVQ_RR>, XS;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSE3 - Conversion Instructions
@@ -4458,14 +4924,16 @@
 }
=20
 def CVTPD2DQrm  : S3DI<0xE6, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$s=
rc),
-                       "cvtpd2dq\t{$src, $dst|$dst, $src}", []>;
+                       "cvtpd2dq\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PD_RM>;
 def CVTPD2DQrr  : S3DI<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
-                       "cvtpd2dq\t{$src, $dst|$dst, $src}", []>;
+                       "cvtpd2dq\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PD_RR>;
=20
 def : Pat<(v4i32 (fp_to_sint (v4f64 VR256:$src))),
-          (VCVTPD2DQYrr VR256:$src)>;
+          (VCVTTPD2DQYrr VR256:$src)>;
 def : Pat<(v4i32 (fp_to_sint (memopv4f64 addr:$src))),
-          (VCVTPD2DQYrm addr:$src)>;
+          (VCVTTPD2DQYrm addr:$src)>;
=20
 // Convert Packed DW Integers to Packed Double FP
 let Predicates =3D [HasAVX] in {
@@ -4480,14 +4948,16 @@
 }
=20
 def CVTDQ2PDrm  : S3SI<0xE6, MRMSrcMem, (outs VR128:$dst), (ins f128mem:$s=
rc),
-                       "cvtdq2pd\t{$src, $dst|$dst, $src}", []>;
+                       "cvtdq2pd\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PD_RR>;
 def CVTDQ2PDrr  : S3SI<0xE6, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src=
),
-                       "cvtdq2pd\t{$src, $dst|$dst, $src}", []>;
+                       "cvtdq2pd\t{$src, $dst|$dst, $src}", [],
+                       IIC_SSE_CVT_PD_RM>;
=20
 // AVX 256-bit register conversion intrinsics
 def : Pat<(int_x86_avx_cvtdq2_pd_256 VR128:$src),
            (VCVTDQ2PDYrr VR128:$src)>;
-def : Pat<(int_x86_avx_cvtdq2_pd_256 (memopv4i32 addr:$src)),
+def : Pat<(int_x86_avx_cvtdq2_pd_256 (bitconvert (memopv2i64 addr:$src))),
            (VCVTDQ2PDYrm addr:$src)>;
=20
 def : Pat<(int_x86_avx_cvt_pd2dq_256 VR256:$src),
@@ -4497,7 +4967,7 @@
=20
 def : Pat<(v4f64 (sint_to_fp (v4i32 VR128:$src))),
           (VCVTDQ2PDYrr VR128:$src)>;
-def : Pat<(v4f64 (sint_to_fp (memopv4i32 addr:$src))),
+def : Pat<(v4f64 (sint_to_fp (bc_v4i32 (memopv2i64 addr:$src)))),
           (VCVTDQ2PDYrm addr:$src)>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -4508,10 +4978,12 @@
                               X86MemOperand x86memop> {
 def rr : S3SI<op, MRMSrcReg, (outs RC:$dst), (ins RC:$src),
                     !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
-                      [(set RC:$dst, (vt (OpNode RC:$src)))]>;
+                      [(set RC:$dst, (vt (OpNode RC:$src)))],
+                      IIC_SSE_MOV_LH>;
 def rm : S3SI<op, MRMSrcMem, (outs RC:$dst), (ins x86memop:$src),
                     !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
-                      [(set RC:$dst, (OpNode (mem_frag addr:$src)))]>;
+                      [(set RC:$dst, (OpNode (mem_frag addr:$src)))],
+                      IIC_SSE_MOV_LH>;
 }
=20
 let Predicates =3D [HasAVX] in {
@@ -4529,17 +5001,6 @@
 defm MOVSLDUP : sse3_replicate_sfp<0x12, X86Movsldup, "movsldup", v4f32, V=
R128,
                                    memopv4f32, f128mem>;
=20
-let Predicates =3D [HasSSE3] in {
-  def : Pat<(v4i32 (X86Movshdup VR128:$src)),
-            (MOVSHDUPrr VR128:$src)>;
-  def : Pat<(v4i32 (X86Movshdup (bc_v4i32 (memopv2i64 addr:$src)))),
-            (MOVSHDUPrm addr:$src)>;
-  def : Pat<(v4i32 (X86Movsldup VR128:$src)),
-            (MOVSLDUPrr VR128:$src)>;
-  def : Pat<(v4i32 (X86Movsldup (bc_v4i32 (memopv2i64 addr:$src)))),
-            (MOVSLDUPrm addr:$src)>;
-}
-
 let Predicates =3D [HasAVX] in {
   def : Pat<(v4i32 (X86Movshdup VR128:$src)),
             (VMOVSHDUPrr VR128:$src)>;
@@ -4559,101 +5020,87 @@
             (VMOVSLDUPYrm addr:$src)>;
 }
=20
+let Predicates =3D [HasSSE3] in {
+  def : Pat<(v4i32 (X86Movshdup VR128:$src)),
+            (MOVSHDUPrr VR128:$src)>;
+  def : Pat<(v4i32 (X86Movshdup (bc_v4i32 (memopv2i64 addr:$src)))),
+            (MOVSHDUPrm addr:$src)>;
+  def : Pat<(v4i32 (X86Movsldup VR128:$src)),
+            (MOVSLDUPrr VR128:$src)>;
+  def : Pat<(v4i32 (X86Movsldup (bc_v4i32 (memopv2i64 addr:$src)))),
+            (MOVSLDUPrm addr:$src)>;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSE3 - Replicate Double FP - MOVDDUP
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 multiclass sse3_replicate_dfp<string OpcodeStr> {
+let neverHasSideEffects =3D 1 in
 def rr  : S3DI<0x12, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                     !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst,(v2f64 (movddup VR128:$src, (undef)))=
)]>;
+                    [], IIC_SSE_MOV_LH>;
 def rm  : S3DI<0x12, MRMSrcMem, (outs VR128:$dst), (ins f64mem:$src),
                     !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
                     [(set VR128:$dst,
-                      (v2f64 (movddup (scalar_to_vector (loadf64 addr:$src=
)),
-                                      (undef))))]>;
+                      (v2f64 (X86Movddup
+                              (scalar_to_vector (loadf64 addr:$src)))))],
+                              IIC_SSE_MOV_LH>;
 }
=20
 // FIXME: Merge with above classe when there're patterns for the ymm versi=
on
 multiclass sse3_replicate_dfp_y<string OpcodeStr> {
+def rr  : S3DI<0x12, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
+                    !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                    [(set VR256:$dst, (v4f64 (X86Movddup VR256:$src)))]>;
+def rm  : S3DI<0x12, MRMSrcMem, (outs VR256:$dst), (ins f256mem:$src),
+                    !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                    [(set VR256:$dst,
+                      (v4f64 (X86Movddup
+                              (scalar_to_vector (loadf64 addr:$src)))))]>;
+}
+
 let Predicates =3D [HasAVX] in {
-  def rr  : S3DI<0x12, MRMSrcReg, (outs VR256:$dst), (ins VR256:$src),
-                      !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
-                      []>;
-  def rm  : S3DI<0x12, MRMSrcMem, (outs VR256:$dst), (ins f256mem:$src),
-                      !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
-                      []>;
-  }
+  defm VMOVDDUP  : sse3_replicate_dfp<"vmovddup">, VEX;
+  defm VMOVDDUPY : sse3_replicate_dfp_y<"vmovddup">, VEX;
 }
=20
 defm MOVDDUP : sse3_replicate_dfp<"movddup">;
-defm VMOVDDUP  : sse3_replicate_dfp<"vmovddup">, VEX;
-defm VMOVDDUPY : sse3_replicate_dfp_y<"vmovddup">, VEX;
+
+let Predicates =3D [HasAVX] in {
+  def : Pat<(X86Movddup (memopv2f64 addr:$src)),
+            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
+  def : Pat<(X86Movddup (bc_v2f64 (memopv4f32 addr:$src))),
+            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
+  def : Pat<(X86Movddup (bc_v2f64 (memopv2i64 addr:$src))),
+            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
+  def : Pat<(X86Movddup (bc_v2f64
+                             (v2i64 (scalar_to_vector (loadi64 addr:$src))=
))),
+            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
+
+  // 256-bit version
+  def : Pat<(X86Movddup (memopv4f64 addr:$src)),
+            (VMOVDDUPYrm addr:$src)>;
+  def : Pat<(X86Movddup (memopv4i64 addr:$src)),
+            (VMOVDDUPYrm addr:$src)>;
+  def : Pat<(X86Movddup (v4i64 (scalar_to_vector (loadi64 addr:$src)))),
+            (VMOVDDUPYrm addr:$src)>;
+  def : Pat<(X86Movddup (v4i64 VR256:$src)),
+            (VMOVDDUPYrr VR256:$src)>;
+}
=20
 let Predicates =3D [HasSSE3] in {
-  def : Pat<(movddup (bc_v2f64 (v2i64 (scalar_to_vector (loadi64 addr:$src=
)))),
-                   (undef)),
-            (MOVDDUPrm addr:$src)>;
-  let AddedComplexity =3D 5 in {
-  def : Pat<(movddup (memopv2f64 addr:$src), (undef)), (MOVDDUPrm addr:$sr=
c)>;
-  def : Pat<(movddup (bc_v4f32 (memopv2f64 addr:$src)), (undef)),
-            (MOVDDUPrm addr:$src)>;
-  def : Pat<(movddup (memopv2i64 addr:$src), (undef)), (MOVDDUPrm addr:$sr=
c)>;
-  def : Pat<(movddup (bc_v4i32 (memopv2i64 addr:$src)), (undef)),
-            (MOVDDUPrm addr:$src)>;
-  }
   def : Pat<(X86Movddup (memopv2f64 addr:$src)),
             (MOVDDUPrm addr:$src)>;
   def : Pat<(X86Movddup (bc_v2f64 (memopv4f32 addr:$src))),
             (MOVDDUPrm addr:$src)>;
   def : Pat<(X86Movddup (bc_v2f64 (memopv2i64 addr:$src))),
             (MOVDDUPrm addr:$src)>;
-  def : Pat<(X86Movddup (v2f64 (scalar_to_vector (loadf64 addr:$src)))),
-            (MOVDDUPrm addr:$src)>;
   def : Pat<(X86Movddup (bc_v2f64
                              (v2i64 (scalar_to_vector (loadi64 addr:$src))=
))),
             (MOVDDUPrm addr:$src)>;
 }
=20
-let Predicates =3D [HasAVX] in {
-  def : Pat<(movddup (bc_v2f64 (v2i64 (scalar_to_vector (loadi64 addr:$src=
)))),
-                   (undef)),
-            (VMOVDDUPrm addr:$src)>;
-  let AddedComplexity =3D 5 in {
-  def : Pat<(movddup (memopv2f64 addr:$src), (undef)), (VMOVDDUPrm addr:$s=
rc)>;
-  def : Pat<(movddup (bc_v4f32 (memopv2f64 addr:$src)), (undef)),
-            (VMOVDDUPrm addr:$src)>;
-  def : Pat<(movddup (memopv2i64 addr:$src), (undef)), (VMOVDDUPrm addr:$s=
rc)>;
-  def : Pat<(movddup (bc_v4i32 (memopv2i64 addr:$src)), (undef)),
-            (VMOVDDUPrm addr:$src)>;
-  }
-  def : Pat<(X86Movddup (memopv2f64 addr:$src)),
-            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
-  def : Pat<(X86Movddup (bc_v2f64 (memopv4f32 addr:$src))),
-            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
-  def : Pat<(X86Movddup (bc_v2f64 (memopv2i64 addr:$src))),
-            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
-  def : Pat<(X86Movddup (v2f64 (scalar_to_vector (loadf64 addr:$src)))),
-            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
-  def : Pat<(X86Movddup (bc_v2f64
-                             (v2i64 (scalar_to_vector (loadi64 addr:$src))=
))),
-            (VMOVDDUPrm addr:$src)>, Requires<[HasAVX]>;
-
-  // 256-bit version
-  def : Pat<(X86Movddup (memopv4f64 addr:$src)),
-            (VMOVDDUPYrm addr:$src)>;
-  def : Pat<(X86Movddup (memopv4i64 addr:$src)),
-            (VMOVDDUPYrm addr:$src)>;
-  def : Pat<(X86Movddup (v4f64 (scalar_to_vector (loadf64 addr:$src)))),
-            (VMOVDDUPYrm addr:$src)>;
-  def : Pat<(X86Movddup (v4i64 (scalar_to_vector (loadi64 addr:$src)))),
-            (VMOVDDUPYrm addr:$src)>;
-  def : Pat<(X86Movddup (v4f64 VR256:$src)),
-            (VMOVDDUPYrr VR256:$src)>;
-  def : Pat<(X86Movddup (v4i64 VR256:$src)),
-            (VMOVDDUPYrr VR256:$src)>;
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSE3 - Move Unaligned Integer
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -4668,45 +5115,51 @@
 }
 def LDDQUrm : S3DI<0xF0, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$src),
                    "lddqu\t{$src, $dst|$dst, $src}",
-                   [(set VR128:$dst, (int_x86_sse3_ldu_dq addr:$src))]>;
+                   [(set VR128:$dst, (int_x86_sse3_ldu_dq addr:$src))],
+                   IIC_SSE_LDDQU>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSE3 - Arithmetic
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 multiclass sse3_addsub<Intrinsic Int, string OpcodeStr, RegisterClass RC,
-                       X86MemOperand x86memop, bit Is2Addr =3D 1> {
+                       X86MemOperand x86memop, OpndItins itins,
+                       bit Is2Addr =3D 1> {
   def rr : I<0xD0, MRMSrcReg,
        (outs RC:$dst), (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set RC:$dst, (Int RC:$src1, RC:$src2))]>;
+       [(set RC:$dst, (Int RC:$src1, RC:$src2))], itins.rr>;
   def rm : I<0xD0, MRMSrcMem,
        (outs RC:$dst), (ins RC:$src1, x86memop:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set RC:$dst, (Int RC:$src1, (memop addr:$src2)))]>;
-}
-
-let Predicates =3D [HasAVX],
-  ExeDomain =3D SSEPackedDouble in {
-  defm VADDSUBPS : sse3_addsub<int_x86_sse3_addsub_ps, "vaddsubps", VR128,
-                               f128mem, 0>, TB, XD, VEX_4V;
-  defm VADDSUBPD : sse3_addsub<int_x86_sse3_addsub_pd, "vaddsubpd", VR128,
-                               f128mem, 0>, TB, OpSize, VEX_4V;
-  defm VADDSUBPSY : sse3_addsub<int_x86_avx_addsub_ps_256, "vaddsubps", VR=
256,
-                               f256mem, 0>, TB, XD, VEX_4V;
-  defm VADDSUBPDY : sse3_addsub<int_x86_avx_addsub_pd_256, "vaddsubpd", VR=
256,
-                               f256mem, 0>, TB, OpSize, VEX_4V;
-}
-let Constraints =3D "$src1 =3D $dst", Predicates =3D [HasSSE3],
-    ExeDomain =3D SSEPackedDouble in {
+       [(set RC:$dst, (Int RC:$src1, (memop addr:$src2)))], itins.rr>;
+}
+
+let Predicates =3D [HasAVX] in {
+  let ExeDomain =3D SSEPackedSingle in {
+    defm VADDSUBPS : sse3_addsub<int_x86_sse3_addsub_ps, "vaddsubps", VR12=
8,
+                                 f128mem, SSE_ALU_F32P, 0>, TB, XD, VEX_4V;
+    defm VADDSUBPSY : sse3_addsub<int_x86_avx_addsub_ps_256, "vaddsubps", =
VR256,
+                                 f256mem, SSE_ALU_F32P, 0>, TB, XD, VEX_4V;
+  }
+  let ExeDomain =3D SSEPackedDouble in {
+    defm VADDSUBPD : sse3_addsub<int_x86_sse3_addsub_pd, "vaddsubpd", VR12=
8,
+                                 f128mem, SSE_ALU_F64P, 0>, TB, OpSize, VE=
X_4V;
+    defm VADDSUBPDY : sse3_addsub<int_x86_avx_addsub_pd_256, "vaddsubpd", =
VR256,
+                                 f256mem, SSE_ALU_F64P, 0>, TB, OpSize, VE=
X_4V;
+  }
+}
+let Constraints =3D "$src1 =3D $dst", Predicates =3D [HasSSE3] in {
+  let ExeDomain =3D SSEPackedSingle in
   defm ADDSUBPS : sse3_addsub<int_x86_sse3_addsub_ps, "addsubps", VR128,
-                              f128mem>, TB, XD;
+                              f128mem, SSE_ALU_F32P>, TB, XD;
+  let ExeDomain =3D SSEPackedDouble in
   defm ADDSUBPD : sse3_addsub<int_x86_sse3_addsub_pd, "addsubpd", VR128,
-                              f128mem>, TB, OpSize;
+                              f128mem, SSE_ALU_F64P>, TB, OpSize;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -4720,13 +5173,14 @@
        !if(Is2Addr,
          !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
          !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
-      [(set RC:$dst, (vt (OpNode RC:$src1, RC:$src2)))]>;
+      [(set RC:$dst, (vt (OpNode RC:$src1, RC:$src2)))], IIC_SSE_HADDSUB_R=
R>;
=20
   def rm : S3DI<o, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, x86memop:$src=
2),
        !if(Is2Addr,
          !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
          !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
-      [(set RC:$dst, (vt (OpNode RC:$src1, (memop addr:$src2))))]>;
+      [(set RC:$dst, (vt (OpNode RC:$src1, (memop addr:$src2))))],
+        IIC_SSE_HADDSUB_RM>;
 }
 multiclass S3_Int<bits<8> o, string OpcodeStr, ValueType vt, RegisterClass=
 RC,
                   X86MemOperand x86memop, SDNode OpNode, bit Is2Addr =3D 1=
> {
@@ -4734,39 +5188,48 @@
        !if(Is2Addr,
          !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
          !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
-      [(set RC:$dst, (vt (OpNode RC:$src1, RC:$src2)))]>;
+      [(set RC:$dst, (vt (OpNode RC:$src1, RC:$src2)))], IIC_SSE_HADDSUB_R=
R>;
=20
   def rm : S3I<o, MRMSrcMem, (outs RC:$dst), (ins RC:$src1, x86memop:$src2=
),
        !if(Is2Addr,
          !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
          !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
-      [(set RC:$dst, (vt (OpNode RC:$src1, (memop addr:$src2))))]>;
+      [(set RC:$dst, (vt (OpNode RC:$src1, (memop addr:$src2))))],
+        IIC_SSE_HADDSUB_RM>;
 }
=20
 let Predicates =3D [HasAVX] in {
-  defm VHADDPS  : S3D_Int<0x7C, "vhaddps", v4f32, VR128, f128mem,
-                          X86fhadd, 0>, VEX_4V;
-  defm VHADDPD  : S3_Int <0x7C, "vhaddpd", v2f64, VR128, f128mem,
-                          X86fhadd, 0>, VEX_4V;
-  defm VHSUBPS  : S3D_Int<0x7D, "vhsubps", v4f32, VR128, f128mem,
-                          X86fhsub, 0>, VEX_4V;
-  defm VHSUBPD  : S3_Int <0x7D, "vhsubpd", v2f64, VR128, f128mem,
-                          X86fhsub, 0>, VEX_4V;
-  defm VHADDPSY : S3D_Int<0x7C, "vhaddps", v8f32, VR256, f256mem,
-                          X86fhadd, 0>, VEX_4V;
-  defm VHADDPDY : S3_Int <0x7C, "vhaddpd", v4f64, VR256, f256mem,
-                          X86fhadd, 0>, VEX_4V;
-  defm VHSUBPSY : S3D_Int<0x7D, "vhsubps", v8f32, VR256, f256mem,
-                          X86fhsub, 0>, VEX_4V;
-  defm VHSUBPDY : S3_Int <0x7D, "vhsubpd", v4f64, VR256, f256mem,
-                          X86fhsub, 0>, VEX_4V;
+  let ExeDomain =3D SSEPackedSingle in {
+    defm VHADDPS  : S3D_Int<0x7C, "vhaddps", v4f32, VR128, f128mem,
+                            X86fhadd, 0>, VEX_4V;
+    defm VHSUBPS  : S3D_Int<0x7D, "vhsubps", v4f32, VR128, f128mem,
+                            X86fhsub, 0>, VEX_4V;
+    defm VHADDPSY : S3D_Int<0x7C, "vhaddps", v8f32, VR256, f256mem,
+                            X86fhadd, 0>, VEX_4V;
+    defm VHSUBPSY : S3D_Int<0x7D, "vhsubps", v8f32, VR256, f256mem,
+                            X86fhsub, 0>, VEX_4V;
+  }
+  let ExeDomain =3D SSEPackedDouble in {
+    defm VHADDPD  : S3_Int <0x7C, "vhaddpd", v2f64, VR128, f128mem,
+                            X86fhadd, 0>, VEX_4V;
+    defm VHSUBPD  : S3_Int <0x7D, "vhsubpd", v2f64, VR128, f128mem,
+                            X86fhsub, 0>, VEX_4V;
+    defm VHADDPDY : S3_Int <0x7C, "vhaddpd", v4f64, VR256, f256mem,
+                            X86fhadd, 0>, VEX_4V;
+    defm VHSUBPDY : S3_Int <0x7D, "vhsubpd", v4f64, VR256, f256mem,
+                            X86fhsub, 0>, VEX_4V;
+  }
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
-  defm HADDPS : S3D_Int<0x7C, "haddps", v4f32, VR128, f128mem, X86fhadd>;
-  defm HADDPD : S3_Int<0x7C, "haddpd", v2f64, VR128, f128mem, X86fhadd>;
-  defm HSUBPS : S3D_Int<0x7D, "hsubps", v4f32, VR128, f128mem, X86fhsub>;
-  defm HSUBPD : S3_Int<0x7D, "hsubpd", v2f64, VR128, f128mem, X86fhsub>;
+  let ExeDomain =3D SSEPackedSingle in {
+    defm HADDPS : S3D_Int<0x7C, "haddps", v4f32, VR128, f128mem, X86fhadd>;
+    defm HSUBPS : S3D_Int<0x7D, "hsubps", v4f32, VR128, f128mem, X86fhsub>;
+  }
+  let ExeDomain =3D SSEPackedDouble in {
+    defm HADDPD : S3_Int<0x7C, "haddpd", v2f64, VR128, f128mem, X86fhadd>;
+    defm HSUBPD : S3_Int<0x7D, "hsubpd", v2f64, VR128, f128mem, X86fhsub>;
+  }
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -4776,11 +5239,11 @@
=20
 /// SS3I_unop_rm_int - Simple SSSE3 unary op whose type can be v*{i8,i16,i=
32}.
 multiclass SS3I_unop_rm_int<bits<8> opc, string OpcodeStr,
-                            PatFrag mem_frag128, Intrinsic IntId128> {
+                            Intrinsic IntId128> {
   def rr128 : SS38I<opc, MRMSrcReg, (outs VR128:$dst),
                     (ins VR128:$src),
                     !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
-                    [(set VR128:$dst, (IntId128 VR128:$src))]>,
+                    [(set VR128:$dst, (IntId128 VR128:$src))], IIC_SSE_PAB=
S_RR>,
                     OpSize;
=20
   def rm128 : SS38I<opc, MRMSrcMem, (outs VR128:$dst),
@@ -4788,32 +5251,101 @@
                     !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
                     [(set VR128:$dst,
                       (IntId128
-                       (bitconvert (mem_frag128 addr:$src))))]>, OpSize;
+                       (bitconvert (memopv2i64 addr:$src))))], IIC_SSE_PAB=
S_RM>,
+                    OpSize;
+}
+
+/// SS3I_unop_rm_int_y - Simple SSSE3 unary op whose type can be v*{i8,i16=
,i32}.
+multiclass SS3I_unop_rm_int_y<bits<8> opc, string OpcodeStr,
+                              Intrinsic IntId256> {
+  def rr256 : SS38I<opc, MRMSrcReg, (outs VR256:$dst),
+                    (ins VR256:$src),
+                    !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                    [(set VR256:$dst, (IntId256 VR256:$src))]>,
+                    OpSize;
+
+  def rm256 : SS38I<opc, MRMSrcMem, (outs VR256:$dst),
+                    (ins i256mem:$src),
+                    !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                    [(set VR256:$dst,
+                      (IntId256
+                       (bitconvert (memopv4i64 addr:$src))))]>, OpSize;
 }
=20
 let Predicates =3D [HasAVX] in {
-  defm VPABSB  : SS3I_unop_rm_int<0x1C, "vpabsb", memopv16i8,
+  defm VPABSB  : SS3I_unop_rm_int<0x1C, "vpabsb",
                                   int_x86_ssse3_pabs_b_128>, VEX;
-  defm VPABSW  : SS3I_unop_rm_int<0x1D, "vpabsw", memopv8i16,
+  defm VPABSW  : SS3I_unop_rm_int<0x1D, "vpabsw",
                                   int_x86_ssse3_pabs_w_128>, VEX;
-  defm VPABSD  : SS3I_unop_rm_int<0x1E, "vpabsd", memopv4i32,
+  defm VPABSD  : SS3I_unop_rm_int<0x1E, "vpabsd",
                                   int_x86_ssse3_pabs_d_128>, VEX;
 }
=20
-defm PABSB : SS3I_unop_rm_int<0x1C, "pabsb", memopv16i8,
+let Predicates =3D [HasAVX2] in {
+  defm VPABSB  : SS3I_unop_rm_int_y<0x1C, "vpabsb",
+                                    int_x86_avx2_pabs_b>, VEX;
+  defm VPABSW  : SS3I_unop_rm_int_y<0x1D, "vpabsw",
+                                    int_x86_avx2_pabs_w>, VEX;
+  defm VPABSD  : SS3I_unop_rm_int_y<0x1E, "vpabsd",
+                                    int_x86_avx2_pabs_d>, VEX;
+}
+
+defm PABSB : SS3I_unop_rm_int<0x1C, "pabsb",
                               int_x86_ssse3_pabs_b_128>;
-defm PABSW : SS3I_unop_rm_int<0x1D, "pabsw", memopv8i16,
+defm PABSW : SS3I_unop_rm_int<0x1D, "pabsw",
                               int_x86_ssse3_pabs_w_128>;
-defm PABSD : SS3I_unop_rm_int<0x1E, "pabsd", memopv4i32,
+defm PABSD : SS3I_unop_rm_int<0x1E, "pabsd",
                               int_x86_ssse3_pabs_d_128>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSSE3 - Packed Binary Operator Instructions
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
+def SSE_PHADDSUBD : OpndItins<
+  IIC_SSE_PHADDSUBD_RR, IIC_SSE_PHADDSUBD_RM
+>;
+def SSE_PHADDSUBSW : OpndItins<
+  IIC_SSE_PHADDSUBSW_RR, IIC_SSE_PHADDSUBSW_RM
+>;
+def SSE_PHADDSUBW : OpndItins<
+  IIC_SSE_PHADDSUBW_RR, IIC_SSE_PHADDSUBW_RM
+>;
+def SSE_PSHUFB : OpndItins<
+  IIC_SSE_PSHUFB_RR, IIC_SSE_PSHUFB_RM
+>;
+def SSE_PSIGN : OpndItins<
+  IIC_SSE_PSIGN_RR, IIC_SSE_PSIGN_RM
+>;
+def SSE_PMULHRSW : OpndItins<
+  IIC_SSE_PMULHRSW, IIC_SSE_PMULHRSW
+>;
+
+/// SS3I_binop_rm - Simple SSSE3 bin op
+multiclass SS3I_binop_rm<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                         ValueType OpVT, RegisterClass RC, PatFrag memop_f=
rag,
+                         X86MemOperand x86memop, OpndItins itins,
+                         bit Is2Addr =3D 1> {
+  let isCommutable =3D 1 in
+  def rr : SS38I<opc, MRMSrcReg, (outs RC:$dst),
+       (ins RC:$src1, RC:$src2),
+       !if(Is2Addr,
+         !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
+         !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
+       [(set RC:$dst, (OpVT (OpNode RC:$src1, RC:$src2)))], itins.rr>,
+       OpSize;
+  def rm : SS38I<opc, MRMSrcMem, (outs RC:$dst),
+       (ins RC:$src1, x86memop:$src2),
+       !if(Is2Addr,
+         !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
+         !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
+       [(set RC:$dst,
+         (OpVT (OpNode RC:$src1,
+          (bitconvert (memop_frag addr:$src2)))))], itins.rm>, OpSize;
+}
+
 /// SS3I_binop_rm_int - Simple SSSE3 bin op whose type can be v*{i8,i16,i3=
2}.
 multiclass SS3I_binop_rm_int<bits<8> opc, string OpcodeStr,
-                             PatFrag mem_frag128, Intrinsic IntId128,
+                             Intrinsic IntId128, OpndItins itins,
                              bit Is2Addr =3D 1> {
   let isCommutable =3D 1 in
   def rr128 : SS38I<opc, MRMSrcReg, (outs VR128:$dst),
@@ -4830,94 +5362,134 @@
          !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
)),
        [(set VR128:$dst,
          (IntId128 VR128:$src1,
-          (bitconvert (memopv16i8 addr:$src2))))]>, OpSize;
+          (bitconvert (memopv2i64 addr:$src2))))]>, OpSize;
+}
+
+multiclass SS3I_binop_rm_int_y<bits<8> opc, string OpcodeStr,
+                               Intrinsic IntId256> {
+  let isCommutable =3D 1 in
+  def rr256 : SS38I<opc, MRMSrcReg, (outs VR256:$dst),
+       (ins VR256:$src1, VR256:$src2),
+       !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+       [(set VR256:$dst, (IntId256 VR256:$src1, VR256:$src2))]>,
+       OpSize;
+  def rm256 : SS38I<opc, MRMSrcMem, (outs VR256:$dst),
+       (ins VR256:$src1, i256mem:$src2),
+       !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+       [(set VR256:$dst,
+         (IntId256 VR256:$src1,
+          (bitconvert (memopv4i64 addr:$src2))))]>, OpSize;
 }
=20
 let ImmT =3D NoImm, Predicates =3D [HasAVX] in {
 let isCommutable =3D 0 in {
-  defm VPHADDW    : SS3I_binop_rm_int<0x01, "vphaddw", memopv8i16,
-                                      int_x86_ssse3_phadd_w_128, 0>, VEX_4=
V;
-  defm VPHADDD    : SS3I_binop_rm_int<0x02, "vphaddd", memopv4i32,
-                                      int_x86_ssse3_phadd_d_128, 0>, VEX_4=
V;
-  defm VPHADDSW   : SS3I_binop_rm_int<0x03, "vphaddsw", memopv8i16,
-                                      int_x86_ssse3_phadd_sw_128, 0>, VEX_=
4V;
-  defm VPHSUBW    : SS3I_binop_rm_int<0x05, "vphsubw", memopv8i16,
-                                      int_x86_ssse3_phsub_w_128, 0>, VEX_4=
V;
-  defm VPHSUBD    : SS3I_binop_rm_int<0x06, "vphsubd", memopv4i32,
-                                      int_x86_ssse3_phsub_d_128, 0>, VEX_4=
V;
-  defm VPHSUBSW   : SS3I_binop_rm_int<0x07, "vphsubsw", memopv8i16,
-                                      int_x86_ssse3_phsub_sw_128, 0>, VEX_=
4V;
-  defm VPMADDUBSW : SS3I_binop_rm_int<0x04, "vpmaddubsw", memopv16i8,
-                                      int_x86_ssse3_pmadd_ub_sw_128, 0>, V=
EX_4V;
-  defm VPSHUFB    : SS3I_binop_rm_int<0x00, "vpshufb", memopv16i8,
-                                      int_x86_ssse3_pshuf_b_128, 0>, VEX_4=
V;
-  defm VPSIGNB    : SS3I_binop_rm_int<0x08, "vpsignb", memopv16i8,
-                                      int_x86_ssse3_psign_b_128, 0>, VEX_4=
V;
-  defm VPSIGNW    : SS3I_binop_rm_int<0x09, "vpsignw", memopv8i16,
-                                      int_x86_ssse3_psign_w_128, 0>, VEX_4=
V;
-  defm VPSIGND    : SS3I_binop_rm_int<0x0A, "vpsignd", memopv4i32,
-                                      int_x86_ssse3_psign_d_128, 0>, VEX_4=
V;
-}
-defm VPMULHRSW    : SS3I_binop_rm_int<0x0B, "vpmulhrsw", memopv8i16,
-                                      int_x86_ssse3_pmul_hr_sw_128, 0>, VE=
X_4V;
+  defm VPHADDW    : SS3I_binop_rm<0x01, "vphaddw", X86hadd, v8i16, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPHADDD    : SS3I_binop_rm<0x02, "vphaddd", X86hadd, v4i32, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PHADDSUBD, 0>, VEX_4V;
+  defm VPHSUBW    : SS3I_binop_rm<0x05, "vphsubw", X86hsub, v8i16, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPHSUBD    : SS3I_binop_rm<0x06, "vphsubd", X86hsub, v4i32, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PHADDSUBD, 0>, VEX_4V;
+  defm VPSIGNB    : SS3I_binop_rm<0x08, "vpsignb", X86psign, v16i8, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PSIGN, 0>, VEX_4V;
+  defm VPSIGNW    : SS3I_binop_rm<0x09, "vpsignw", X86psign, v8i16, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PSIGN, 0>, VEX_4V;
+  defm VPSIGND    : SS3I_binop_rm<0x0A, "vpsignd", X86psign, v4i32, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PSIGN, 0>, VEX_4V;
+  defm VPSHUFB    : SS3I_binop_rm<0x00, "vpshufb", X86pshufb, v16i8, VR128,
+                                  memopv2i64, i128mem,
+                                  SSE_PSHUFB, 0>, VEX_4V;
+  defm VPHADDSW   : SS3I_binop_rm_int<0x03, "vphaddsw",
+                                      int_x86_ssse3_phadd_sw_128,
+                                      SSE_PHADDSUBSW, 0>, VEX_4V;
+  defm VPHSUBSW   : SS3I_binop_rm_int<0x07, "vphsubsw",
+                                      int_x86_ssse3_phsub_sw_128,
+                                      SSE_PHADDSUBSW, 0>, VEX_4V;
+  defm VPMADDUBSW : SS3I_binop_rm_int<0x04, "vpmaddubsw",
+                                      int_x86_ssse3_pmadd_ub_sw_128,
+                                      SSE_PMADD, 0>, VEX_4V;
+}
+defm VPMULHRSW    : SS3I_binop_rm_int<0x0B, "vpmulhrsw",
+                                      int_x86_ssse3_pmul_hr_sw_128,
+                                      SSE_PMULHRSW, 0>, VEX_4V;
+}
+
+let ImmT =3D NoImm, Predicates =3D [HasAVX2] in {
+let isCommutable =3D 0 in {
+  defm VPHADDWY   : SS3I_binop_rm<0x01, "vphaddw", X86hadd, v16i16, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPHADDDY   : SS3I_binop_rm<0x02, "vphaddd", X86hadd, v8i32, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPHSUBWY   : SS3I_binop_rm<0x05, "vphsubw", X86hsub, v16i16, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPHSUBDY   : SS3I_binop_rm<0x06, "vphsubd", X86hsub, v8i32, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPSIGNBY   : SS3I_binop_rm<0x08, "vpsignb", X86psign, v32i8, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPSIGNWY   : SS3I_binop_rm<0x09, "vpsignw", X86psign, v16i16, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPSIGNDY   : SS3I_binop_rm<0x0A, "vpsignd", X86psign, v8i32, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPSHUFBY   : SS3I_binop_rm<0x00, "vpshufb", X86pshufb, v32i8, VR256,
+                                  memopv4i64, i256mem,
+                                  SSE_PHADDSUBW, 0>, VEX_4V;
+  defm VPHADDSW   : SS3I_binop_rm_int_y<0x03, "vphaddsw",
+                                        int_x86_avx2_phadd_sw>, VEX_4V;
+  defm VPHSUBSW   : SS3I_binop_rm_int_y<0x07, "vphsubsw",
+                                        int_x86_avx2_phsub_sw>, VEX_4V;
+  defm VPMADDUBSW : SS3I_binop_rm_int_y<0x04, "vpmaddubsw",
+                                        int_x86_avx2_pmadd_ub_sw>, VEX_4V;
+}
+defm VPMULHRSW    : SS3I_binop_rm_int_y<0x0B, "vpmulhrsw",
+                                        int_x86_avx2_pmul_hr_sw>, VEX_4V;
 }
=20
 // None of these have i8 immediate fields.
 let ImmT =3D NoImm, Constraints =3D "$src1 =3D $dst" in {
 let isCommutable =3D 0 in {
-  defm PHADDW    : SS3I_binop_rm_int<0x01, "phaddw", memopv8i16,
-                                     int_x86_ssse3_phadd_w_128>;
-  defm PHADDD    : SS3I_binop_rm_int<0x02, "phaddd", memopv4i32,
-                                     int_x86_ssse3_phadd_d_128>;
-  defm PHADDSW   : SS3I_binop_rm_int<0x03, "phaddsw", memopv8i16,
-                                     int_x86_ssse3_phadd_sw_128>;
-  defm PHSUBW    : SS3I_binop_rm_int<0x05, "phsubw", memopv8i16,
-                                     int_x86_ssse3_phsub_w_128>;
-  defm PHSUBD    : SS3I_binop_rm_int<0x06, "phsubd", memopv4i32,
-                                     int_x86_ssse3_phsub_d_128>;
-  defm PHSUBSW   : SS3I_binop_rm_int<0x07, "phsubsw", memopv8i16,
-                                     int_x86_ssse3_phsub_sw_128>;
-  defm PMADDUBSW : SS3I_binop_rm_int<0x04, "pmaddubsw", memopv16i8,
-                                     int_x86_ssse3_pmadd_ub_sw_128>;
-  defm PSHUFB    : SS3I_binop_rm_int<0x00, "pshufb", memopv16i8,
-                                     int_x86_ssse3_pshuf_b_128>;
-  defm PSIGNB    : SS3I_binop_rm_int<0x08, "psignb", memopv16i8,
-                                     int_x86_ssse3_psign_b_128>;
-  defm PSIGNW    : SS3I_binop_rm_int<0x09, "psignw", memopv8i16,
-                                     int_x86_ssse3_psign_w_128>;
-  defm PSIGND    : SS3I_binop_rm_int<0x0A, "psignd", memopv4i32,
-                                       int_x86_ssse3_psign_d_128>;
-}
-defm PMULHRSW    : SS3I_binop_rm_int<0x0B, "pmulhrsw", memopv8i16,
-                                     int_x86_ssse3_pmul_hr_sw_128>;
-}
-
-let Predicates =3D [HasSSSE3] in {
-  def : Pat<(X86pshufb VR128:$src, VR128:$mask),
-            (PSHUFBrr128 VR128:$src, VR128:$mask)>;
-  def : Pat<(X86pshufb VR128:$src, (bc_v16i8 (memopv2i64 addr:$mask))),
-            (PSHUFBrm128 VR128:$src, addr:$mask)>;
-
-  def : Pat<(X86psignb VR128:$src1, VR128:$src2),
-            (PSIGNBrr128 VR128:$src1, VR128:$src2)>;
-  def : Pat<(X86psignw VR128:$src1, VR128:$src2),
-            (PSIGNWrr128 VR128:$src1, VR128:$src2)>;
-  def : Pat<(X86psignd VR128:$src1, VR128:$src2),
-            (PSIGNDrr128 VR128:$src1, VR128:$src2)>;
-}
-
-let Predicates =3D [HasAVX] in {
-  def : Pat<(X86pshufb VR128:$src, VR128:$mask),
-            (VPSHUFBrr128 VR128:$src, VR128:$mask)>;
-  def : Pat<(X86pshufb VR128:$src, (bc_v16i8 (memopv2i64 addr:$mask))),
-            (VPSHUFBrm128 VR128:$src, addr:$mask)>;
-
-  def : Pat<(X86psignb VR128:$src1, VR128:$src2),
-            (VPSIGNBrr128 VR128:$src1, VR128:$src2)>;
-  def : Pat<(X86psignw VR128:$src1, VR128:$src2),
-            (VPSIGNWrr128 VR128:$src1, VR128:$src2)>;
-  def : Pat<(X86psignd VR128:$src1, VR128:$src2),
-            (VPSIGNDrr128 VR128:$src1, VR128:$src2)>;
+  defm PHADDW    : SS3I_binop_rm<0x01, "phaddw", X86hadd, v8i16, VR128,
+                                 memopv2i64, i128mem, SSE_PHADDSUBW>;
+  defm PHADDD    : SS3I_binop_rm<0x02, "phaddd", X86hadd, v4i32, VR128,
+                                 memopv2i64, i128mem, SSE_PHADDSUBD>;
+  defm PHSUBW    : SS3I_binop_rm<0x05, "phsubw", X86hsub, v8i16, VR128,
+                                 memopv2i64, i128mem, SSE_PHADDSUBW>;
+  defm PHSUBD    : SS3I_binop_rm<0x06, "phsubd", X86hsub, v4i32, VR128,
+                                 memopv2i64, i128mem, SSE_PHADDSUBD>;
+  defm PSIGNB    : SS3I_binop_rm<0x08, "psignb", X86psign, v16i8, VR128,
+                                 memopv2i64, i128mem, SSE_PSIGN>;
+  defm PSIGNW    : SS3I_binop_rm<0x09, "psignw", X86psign, v8i16, VR128,
+                                 memopv2i64, i128mem, SSE_PSIGN>;
+  defm PSIGND    : SS3I_binop_rm<0x0A, "psignd", X86psign, v4i32, VR128,
+                                 memopv2i64, i128mem, SSE_PSIGN>;
+  defm PSHUFB    : SS3I_binop_rm<0x00, "pshufb", X86pshufb, v16i8, VR128,
+                                 memopv2i64, i128mem, SSE_PSHUFB>;
+  defm PHADDSW   : SS3I_binop_rm_int<0x03, "phaddsw",
+                                     int_x86_ssse3_phadd_sw_128,
+                                     SSE_PHADDSUBSW>;
+  defm PHSUBSW   : SS3I_binop_rm_int<0x07, "phsubsw",
+                                     int_x86_ssse3_phsub_sw_128,
+                                     SSE_PHADDSUBSW>;
+  defm PMADDUBSW : SS3I_binop_rm_int<0x04, "pmaddubsw",
+                                     int_x86_ssse3_pmadd_ub_sw_128, SSE_PM=
ADD>;
+}
+defm PMULHRSW    : SS3I_binop_rm_int<0x0B, "pmulhrsw",
+                                     int_x86_ssse3_pmul_hr_sw_128,
+                                     SSE_PMULHRSW>;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
@@ -4925,27 +5497,70 @@
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 multiclass ssse3_palign<string asm, bit Is2Addr =3D 1> {
+  let neverHasSideEffects =3D 1 in {
   def R128rr : SS3AI<0x0F, MRMSrcReg, (outs VR128:$dst),
       (ins VR128:$src1, VR128:$src2, i8imm:$src3),
       !if(Is2Addr,
         !strconcat(asm, "\t{$src3, $src2, $dst|$dst, $src2, $src3}"),
         !strconcat(asm,
                   "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
")),
-      []>, OpSize;
+      [], IIC_SSE_PALIGNR>, OpSize;
+  let mayLoad =3D 1 in
   def R128rm : SS3AI<0x0F, MRMSrcMem, (outs VR128:$dst),
       (ins VR128:$src1, i128mem:$src2, i8imm:$src3),
       !if(Is2Addr,
         !strconcat(asm, "\t{$src3, $src2, $dst|$dst, $src2, $src3}"),
         !strconcat(asm,
                   "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
")),
+      [], IIC_SSE_PALIGNR>, OpSize;
+  }
+}
+
+multiclass ssse3_palign_y<string asm, bit Is2Addr =3D 1> {
+  let neverHasSideEffects =3D 1 in {
+  def R256rr : SS3AI<0x0F, MRMSrcReg, (outs VR256:$dst),
+      (ins VR256:$src1, VR256:$src2, i8imm:$src3),
+      !strconcat(asm,
+                 "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"=
),
       []>, OpSize;
+  let mayLoad =3D 1 in
+  def R256rm : SS3AI<0x0F, MRMSrcMem, (outs VR256:$dst),
+      (ins VR256:$src1, i256mem:$src2, i8imm:$src3),
+      !strconcat(asm,
+                 "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"=
),
+      []>, OpSize;
+  }
 }
=20
 let Predicates =3D [HasAVX] in
   defm VPALIGN : ssse3_palign<"vpalignr", 0>, VEX_4V;
+let Predicates =3D [HasAVX2] in
+  defm VPALIGN : ssse3_palign_y<"vpalignr", 0>, VEX_4V;
 let Constraints =3D "$src1 =3D $dst", Predicates =3D [HasSSSE3] in
   defm PALIGN : ssse3_palign<"palignr">;
=20
+let Predicates =3D [HasAVX2] in {
+def : Pat<(v8i32 (X86PAlign VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          (VPALIGNR256rr VR256:$src2, VR256:$src1, imm:$imm)>;
+def : Pat<(v8f32 (X86PAlign VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          (VPALIGNR256rr VR256:$src2, VR256:$src1, imm:$imm)>;
+def : Pat<(v16i16 (X86PAlign VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          (VPALIGNR256rr VR256:$src2, VR256:$src1, imm:$imm)>;
+def : Pat<(v32i8 (X86PAlign VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          (VPALIGNR256rr VR256:$src2, VR256:$src1, imm:$imm)>;
+}
+
+let Predicates =3D [HasAVX] in {
+def : Pat<(v4i32 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
+def : Pat<(v4f32 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
+def : Pat<(v8i16 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
+def : Pat<(v16i8 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
+          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
+}
+
 let Predicates =3D [HasSSSE3] in {
 def : Pat<(v4i32 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
           (PALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
@@ -4957,34 +5572,25 @@
           (PALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
 }
=20
-let Predicates =3D [HasAVX] in {
-def : Pat<(v4i32 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
-def : Pat<(v4f32 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
-def : Pat<(v8i16 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
-def : Pat<(v16i8 (X86PAlign VR128:$src1, VR128:$src2, (i8 imm:$imm))),
-          (VPALIGNR128rr VR128:$src2, VR128:$src1, imm:$imm)>;
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // SSSE3 - Thread synchronization
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
=20
 let usesCustomInserter =3D 1 in {
 def MONITOR : PseudoI<(outs), (ins i32mem:$src1, GR32:$src2, GR32:$src3),
-                [(int_x86_sse3_monitor addr:$src1, GR32:$src2, GR32:$src3)=
]>;
+                [(int_x86_sse3_monitor addr:$src1, GR32:$src2, GR32:$src3)=
]>,
+                Requires<[HasSSE3]>;
 def MWAIT : PseudoI<(outs), (ins GR32:$src1, GR32:$src2),
-                [(int_x86_sse3_mwait GR32:$src1, GR32:$src2)]>;
+                [(int_x86_sse3_mwait GR32:$src1, GR32:$src2)]>,
+                Requires<[HasSSE3]>;
 }
=20
 let Uses =3D [EAX, ECX, EDX] in
-def MONITORrrr : I<0x01, MRM_C8, (outs), (ins), "monitor", []>, TB,
-                 Requires<[HasSSE3]>;
+def MONITORrrr : I<0x01, MRM_C8, (outs), (ins), "monitor", [], IIC_SSE_MON=
ITOR>,
+                 TB, Requires<[HasSSE3]>;
 let Uses =3D [ECX, EAX] in
-def MWAITrr   : I<0x01, MRM_C9, (outs), (ins), "mwait", []>, TB,
-                Requires<[HasSSE3]>;
+def MWAITrr   : I<0x01, MRM_C9, (outs), (ins), "mwait", [], IIC_SSE_MWAIT>,
+                TB, Requires<[HasSSE3]>;
=20
 def : InstAlias<"mwait %eax, %ecx", (MWAITrr)>, Requires<[In32BitMode]>;
 def : InstAlias<"mwait %rax, %rcx", (MWAITrr)>, Requires<[In64BitMode]>;
@@ -5010,6 +5616,17 @@
        OpSize;
 }
=20
+multiclass SS41I_binop_rm_int16_y<bits<8> opc, string OpcodeStr,
+                                 Intrinsic IntId> {
+  def Yrr : SS48I<opc, MRMSrcReg, (outs VR256:$dst), (ins VR128:$src),
+                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                  [(set VR256:$dst, (IntId VR128:$src))]>, OpSize;
+
+  def Yrm : SS48I<opc, MRMSrcMem, (outs VR256:$dst), (ins i128mem:$src),
+                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                  [(set VR256:$dst, (IntId (load addr:$src)))]>, OpSize;
+}
+
 let Predicates =3D [HasAVX] in {
 defm VPMOVSXBW : SS41I_binop_rm_int8<0x20, "vpmovsxbw", int_x86_sse41_pmov=
sxbw>,
                                      VEX;
@@ -5025,6 +5642,21 @@
                                      VEX;
 }
=20
+let Predicates =3D [HasAVX2] in {
+defm VPMOVSXBW : SS41I_binop_rm_int16_y<0x20, "vpmovsxbw",
+                                        int_x86_avx2_pmovsxbw>, VEX;
+defm VPMOVSXWD : SS41I_binop_rm_int16_y<0x23, "vpmovsxwd",
+                                        int_x86_avx2_pmovsxwd>, VEX;
+defm VPMOVSXDQ : SS41I_binop_rm_int16_y<0x25, "vpmovsxdq",
+                                        int_x86_avx2_pmovsxdq>, VEX;
+defm VPMOVZXBW : SS41I_binop_rm_int16_y<0x30, "vpmovzxbw",
+                                        int_x86_avx2_pmovzxbw>, VEX;
+defm VPMOVZXWD : SS41I_binop_rm_int16_y<0x33, "vpmovzxwd",
+                                        int_x86_avx2_pmovzxwd>, VEX;
+defm VPMOVZXDQ : SS41I_binop_rm_int16_y<0x35, "vpmovzxdq",
+                                        int_x86_avx2_pmovzxdq>, VEX;
+}
+
 defm PMOVSXBW   : SS41I_binop_rm_int8<0x20, "pmovsxbw", int_x86_sse41_pmov=
sxbw>;
 defm PMOVSXWD   : SS41I_binop_rm_int8<0x23, "pmovsxwd", int_x86_sse41_pmov=
sxwd>;
 defm PMOVSXDQ   : SS41I_binop_rm_int8<0x25, "pmovsxdq", int_x86_sse41_pmov=
sxdq>;
@@ -5032,6 +5664,39 @@
 defm PMOVZXWD   : SS41I_binop_rm_int8<0x33, "pmovzxwd", int_x86_sse41_pmov=
zxwd>;
 defm PMOVZXDQ   : SS41I_binop_rm_int8<0x35, "pmovzxdq", int_x86_sse41_pmov=
zxdq>;
=20
+let Predicates =3D [HasAVX] in {
+  // Common patterns involving scalar load.
+  def : Pat<(int_x86_sse41_pmovsxbw (vzmovl_v2i64 addr:$src)),
+            (VPMOVSXBWrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovsxbw (vzload_v2i64 addr:$src)),
+            (VPMOVSXBWrm addr:$src)>;
+
+  def : Pat<(int_x86_sse41_pmovsxwd (vzmovl_v2i64 addr:$src)),
+            (VPMOVSXWDrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovsxwd (vzload_v2i64 addr:$src)),
+            (VPMOVSXWDrm addr:$src)>;
+
+  def : Pat<(int_x86_sse41_pmovsxdq (vzmovl_v2i64 addr:$src)),
+            (VPMOVSXDQrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovsxdq (vzload_v2i64 addr:$src)),
+            (VPMOVSXDQrm addr:$src)>;
+
+  def : Pat<(int_x86_sse41_pmovzxbw (vzmovl_v2i64 addr:$src)),
+            (VPMOVZXBWrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovzxbw (vzload_v2i64 addr:$src)),
+            (VPMOVZXBWrm addr:$src)>;
+
+  def : Pat<(int_x86_sse41_pmovzxwd (vzmovl_v2i64 addr:$src)),
+            (VPMOVZXWDrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovzxwd (vzload_v2i64 addr:$src)),
+            (VPMOVZXWDrm addr:$src)>;
+
+  def : Pat<(int_x86_sse41_pmovzxdq (vzmovl_v2i64 addr:$src)),
+            (VPMOVZXDQrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovzxdq (vzload_v2i64 addr:$src)),
+            (VPMOVZXDQrm addr:$src)>;
+}
+
 let Predicates =3D [HasSSE41] in {
   // Common patterns involving scalar load.
   def : Pat<(int_x86_sse41_pmovsxbw (vzmovl_v2i64 addr:$src)),
@@ -5066,36 +5731,13 @@
 }
=20
 let Predicates =3D [HasAVX] in {
-  // Common patterns involving scalar load.
-  def : Pat<(int_x86_sse41_pmovsxbw (vzmovl_v2i64 addr:$src)),
-            (VPMOVSXBWrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovsxbw (vzload_v2i64 addr:$src)),
-            (VPMOVSXBWrm addr:$src)>;
-
-  def : Pat<(int_x86_sse41_pmovsxwd (vzmovl_v2i64 addr:$src)),
-            (VPMOVSXWDrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovsxwd (vzload_v2i64 addr:$src)),
-            (VPMOVSXWDrm addr:$src)>;
-
-  def : Pat<(int_x86_sse41_pmovsxdq (vzmovl_v2i64 addr:$src)),
-            (VPMOVSXDQrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovsxdq (vzload_v2i64 addr:$src)),
-            (VPMOVSXDQrm addr:$src)>;
-
-  def : Pat<(int_x86_sse41_pmovzxbw (vzmovl_v2i64 addr:$src)),
-            (VPMOVZXBWrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovzxbw (vzload_v2i64 addr:$src)),
-            (VPMOVZXBWrm addr:$src)>;
-
-  def : Pat<(int_x86_sse41_pmovzxwd (vzmovl_v2i64 addr:$src)),
-            (VPMOVZXWDrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovzxwd (vzload_v2i64 addr:$src)),
-            (VPMOVZXWDrm addr:$src)>;
-
-  def : Pat<(int_x86_sse41_pmovzxdq (vzmovl_v2i64 addr:$src)),
-            (VPMOVZXDQrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovzxdq (vzload_v2i64 addr:$src)),
-            (VPMOVZXDQrm addr:$src)>;
+def : Pat<(v2i64 (X86vsmovl (v4i32 VR128:$src))), (VPMOVSXDQrr VR128:$src)=
>;
+def : Pat<(v4i32 (X86vsmovl (v8i16 VR128:$src))), (VPMOVSXWDrr VR128:$src)=
>;
+}
+
+let Predicates =3D [HasSSE41] in {
+def : Pat<(v2i64 (X86vsmovl (v4i32 VR128:$src))), (PMOVSXDQrr VR128:$src)>;
+def : Pat<(v4i32 (X86vsmovl (v8i16 VR128:$src))), (PMOVSXWDrr VR128:$src)>;
 }
=20
=20
@@ -5111,6 +5753,19 @@
           OpSize;
 }
=20
+multiclass SS41I_binop_rm_int8_y<bits<8> opc, string OpcodeStr,
+                                 Intrinsic IntId> {
+  def Yrr : SS48I<opc, MRMSrcReg, (outs VR256:$dst), (ins VR128:$src),
+                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                  [(set VR256:$dst, (IntId VR128:$src))]>, OpSize;
+
+  def Yrm : SS48I<opc, MRMSrcMem, (outs VR256:$dst), (ins i32mem:$src),
+                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+       [(set VR256:$dst,
+         (IntId (bitconvert (v2i64 (scalar_to_vector (loadi64 addr:$src)))=
)))]>,
+          OpSize;
+}
+
 let Predicates =3D [HasAVX] in {
 defm VPMOVSXBD : SS41I_binop_rm_int4<0x21, "vpmovsxbd", int_x86_sse41_pmov=
sxbd>,
                                      VEX;
@@ -5122,11 +5777,35 @@
                                      VEX;
 }
=20
+let Predicates =3D [HasAVX2] in {
+defm VPMOVSXBD : SS41I_binop_rm_int8_y<0x21, "vpmovsxbd",
+                                       int_x86_avx2_pmovsxbd>, VEX;
+defm VPMOVSXWQ : SS41I_binop_rm_int8_y<0x24, "vpmovsxwq",
+                                       int_x86_avx2_pmovsxwq>, VEX;
+defm VPMOVZXBD : SS41I_binop_rm_int8_y<0x31, "vpmovzxbd",
+                                       int_x86_avx2_pmovzxbd>, VEX;
+defm VPMOVZXWQ : SS41I_binop_rm_int8_y<0x34, "vpmovzxwq",
+                                       int_x86_avx2_pmovzxwq>, VEX;
+}
+
 defm PMOVSXBD   : SS41I_binop_rm_int4<0x21, "pmovsxbd", int_x86_sse41_pmov=
sxbd>;
 defm PMOVSXWQ   : SS41I_binop_rm_int4<0x24, "pmovsxwq", int_x86_sse41_pmov=
sxwq>;
 defm PMOVZXBD   : SS41I_binop_rm_int4<0x31, "pmovzxbd", int_x86_sse41_pmov=
zxbd>;
 defm PMOVZXWQ   : SS41I_binop_rm_int4<0x34, "pmovzxwq", int_x86_sse41_pmov=
zxwq>;
=20
+let Predicates =3D [HasAVX] in {
+  // Common patterns involving scalar load
+  def : Pat<(int_x86_sse41_pmovsxbd (vzmovl_v4i32 addr:$src)),
+            (VPMOVSXBDrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovsxwq (vzmovl_v4i32 addr:$src)),
+            (VPMOVSXWQrm addr:$src)>;
+
+  def : Pat<(int_x86_sse41_pmovzxbd (vzmovl_v4i32 addr:$src)),
+            (VPMOVZXBDrm addr:$src)>;
+  def : Pat<(int_x86_sse41_pmovzxwq (vzmovl_v4i32 addr:$src)),
+            (VPMOVZXWQrm addr:$src)>;
+}
+
 let Predicates =3D [HasSSE41] in {
   // Common patterns involving scalar load
   def : Pat<(int_x86_sse41_pmovsxbd (vzmovl_v4i32 addr:$src)),
@@ -5140,19 +5819,6 @@
             (PMOVZXWQrm addr:$src)>;
 }
=20
-let Predicates =3D [HasAVX] in {
-  // Common patterns involving scalar load
-  def : Pat<(int_x86_sse41_pmovsxbd (vzmovl_v4i32 addr:$src)),
-            (VPMOVSXBDrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovsxwq (vzmovl_v4i32 addr:$src)),
-            (VPMOVSXWQrm addr:$src)>;
-
-  def : Pat<(int_x86_sse41_pmovzxbd (vzmovl_v4i32 addr:$src)),
-            (VPMOVZXBDrm addr:$src)>;
-  def : Pat<(int_x86_sse41_pmovzxwq (vzmovl_v4i32 addr:$src)),
-            (VPMOVZXWQrm addr:$src)>;
-}
-
 multiclass SS41I_binop_rm_int2<bits<8> opc, string OpcodeStr, Intrinsic In=
tId> {
   def rr : SS48I<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
@@ -5166,15 +5832,48 @@
                  OpSize;
 }
=20
+multiclass SS41I_binop_rm_int4_y<bits<8> opc, string OpcodeStr,
+                                 Intrinsic IntId> {
+  def Yrr : SS48I<opc, MRMSrcReg, (outs VR256:$dst), (ins VR128:$src),
+                 !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                 [(set VR256:$dst, (IntId VR128:$src))]>, OpSize;
+
+  // Expecting a i16 load any extended to i32 value.
+  def Yrm : SS48I<opc, MRMSrcMem, (outs VR256:$dst), (ins i16mem:$src),
+                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                  [(set VR256:$dst, (IntId (bitconvert
+                      (v4i32 (scalar_to_vector (loadi32 addr:$src))))))]>,
+                  OpSize;
+}
+
 let Predicates =3D [HasAVX] in {
 defm VPMOVSXBQ : SS41I_binop_rm_int2<0x22, "vpmovsxbq", int_x86_sse41_pmov=
sxbq>,
                                      VEX;
 defm VPMOVZXBQ : SS41I_binop_rm_int2<0x32, "vpmovzxbq", int_x86_sse41_pmov=
zxbq>,
                                      VEX;
 }
+let Predicates =3D [HasAVX2] in {
+defm VPMOVSXBQ : SS41I_binop_rm_int4_y<0x22, "vpmovsxbq",
+                                       int_x86_avx2_pmovsxbq>, VEX;
+defm VPMOVZXBQ : SS41I_binop_rm_int4_y<0x32, "vpmovzxbq",
+                                       int_x86_avx2_pmovzxbq>, VEX;
+}
 defm PMOVSXBQ   : SS41I_binop_rm_int2<0x22, "pmovsxbq", int_x86_sse41_pmov=
sxbq>;
 defm PMOVZXBQ   : SS41I_binop_rm_int2<0x32, "pmovzxbq", int_x86_sse41_pmov=
zxbq>;
=20
+let Predicates =3D [HasAVX] in {
+  // Common patterns involving scalar load
+  def : Pat<(int_x86_sse41_pmovsxbq
+              (bitconvert (v4i32 (X86vzmovl
+                            (v4i32 (scalar_to_vector (loadi32 addr:$src)))=
)))),
+            (VPMOVSXBQrm addr:$src)>;
+
+  def : Pat<(int_x86_sse41_pmovzxbq
+              (bitconvert (v4i32 (X86vzmovl
+                            (v4i32 (scalar_to_vector (loadi32 addr:$src)))=
)))),
+            (VPMOVZXBQrm addr:$src)>;
+}
+
 let Predicates =3D [HasSSE41] in {
   // Common patterns involving scalar load
   def : Pat<(int_x86_sse41_pmovsxbq
@@ -5188,19 +5887,6 @@
             (PMOVZXBQrm addr:$src)>;
 }
=20
-let Predicates =3D [HasAVX] in {
-  // Common patterns involving scalar load
-  def : Pat<(int_x86_sse41_pmovsxbq
-              (bitconvert (v4i32 (X86vzmovl
-                            (v4i32 (scalar_to_vector (loadi32 addr:$src)))=
)))),
-            (VPMOVSXBQrm addr:$src)>;
-
-  def : Pat<(int_x86_sse41_pmovzxbq
-              (bitconvert (v4i32 (X86vzmovl
-                            (v4i32 (scalar_to_vector (loadi32 addr:$src)))=
)))),
-            (VPMOVZXBQrm addr:$src)>;
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE4.1 - Extract Instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -5213,6 +5899,7 @@
                   "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
                  [(set GR32:$dst, (X86pextrb (v16i8 VR128:$src1), imm:$src=
2))]>,
                  OpSize;
+  let neverHasSideEffects =3D 1, mayStore =3D 1 in
   def mr : SS4AIi8<opc, MRMDestMem, (outs),
                  (ins i8mem:$dst, VR128:$src1, i32i8imm:$src2),
                  !strconcat(OpcodeStr,
@@ -5235,6 +5922,7 @@
=20
 /// SS41I_extract16 - SSE 4.1 extract 16 bits to memory destination
 multiclass SS41I_extract16<bits<8> opc, string OpcodeStr> {
+  let neverHasSideEffects =3D 1, mayStore =3D 1 in
   def mr : SS4AIi8<opc, MRMDestMem, (outs),
                  (ins i16mem:$dst, VR128:$src1, i32i8imm:$src2),
                  !strconcat(OpcodeStr,
@@ -5311,26 +5999,28 @@
                           addr:$dst)]>, OpSize;
 }
=20
-let Predicates =3D [HasAVX] in {
-  defm VEXTRACTPS : SS41I_extractf32<0x17, "vextractps">, VEX;
-  def VEXTRACTPSrr64 : SS4AIi8<0x17, MRMDestReg, (outs GR64:$dst),
-                  (ins VR128:$src1, i32i8imm:$src2),
-                  "vextractps \t{$src2, $src1, $dst|$dst, $src1, $src2}",
-                  []>, OpSize, VEX;
-}
-defm EXTRACTPS   : SS41I_extractf32<0x17, "extractps">;
+let ExeDomain =3D SSEPackedSingle in {
+  let Predicates =3D [HasAVX] in {
+    defm VEXTRACTPS : SS41I_extractf32<0x17, "vextractps">, VEX;
+    def VEXTRACTPSrr64 : SS4AIi8<0x17, MRMDestReg, (outs GR64:$dst),
+                    (ins VR128:$src1, i32i8imm:$src2),
+                    "vextractps \t{$src2, $src1, $dst|$dst, $src1, $src2}",
+                    []>, OpSize, VEX;
+  }
+  defm EXTRACTPS   : SS41I_extractf32<0x17, "extractps">;
+}
=20
 // Also match an EXTRACTPS store when the store is done as f32 instead of =
i32.
 def : Pat<(store (f32 (bitconvert (extractelt (bc_v4i32 (v4f32 VR128:$src1=
)),
                                               imm:$src2))),
                  addr:$dst),
+          (VEXTRACTPSmr addr:$dst, VR128:$src1, imm:$src2)>,
+          Requires<[HasAVX]>;
+def : Pat<(store (f32 (bitconvert (extractelt (bc_v4i32 (v4f32 VR128:$src1=
)),
+                                              imm:$src2))),
+                 addr:$dst),
           (EXTRACTPSmr addr:$dst, VR128:$src1, imm:$src2)>,
           Requires<[HasSSE41]>;
-def : Pat<(store (f32 (bitconvert (extractelt (bc_v4i32 (v4f32 VR128:$src1=
)),
-                                              imm:$src2))),
-                 addr:$dst),
-          (VEXTRACTPSmr addr:$dst, VR128:$src1, imm:$src2)>,
-          Requires<[HasAVX]>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE4.1 - Insert Instructions
@@ -5439,17 +6129,12 @@
                     imm:$src3))]>, OpSize;
 }
=20
-let Constraints =3D "$src1 =3D $dst" in
-  defm INSERTPS : SS41I_insertf32<0x21, "insertps">;
-let Predicates =3D [HasAVX] in
-  defm VINSERTPS : SS41I_insertf32<0x21, "vinsertps", 0>, VEX_4V;
-
-def : Pat<(int_x86_sse41_insertps VR128:$src1, VR128:$src2, imm:$src3),
-          (VINSERTPSrr VR128:$src1, VR128:$src2, imm:$src3)>,
-          Requires<[HasAVX]>;
-def : Pat<(int_x86_sse41_insertps VR128:$src1, VR128:$src2, imm:$src3),
-          (INSERTPSrr VR128:$src1, VR128:$src2, imm:$src3)>,
-          Requires<[HasSSE41]>;
+let ExeDomain =3D SSEPackedSingle in {
+  let Predicates =3D [HasAVX] in
+    defm VINSERTPS : SS41I_insertf32<0x21, "vinsertps", 0>, VEX_4V;
+  let Constraints =3D "$src1 =3D $dst" in
+    defm INSERTPS : SS41I_insertf32<0x21, "insertps">;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE4.1 - Round Instructions
@@ -5459,6 +6144,7 @@
                             X86MemOperand x86memop, RegisterClass RC,
                             PatFrag mem_frag32, PatFrag mem_frag64,
                             Intrinsic V4F32Int, Intrinsic V2F64Int> {
+let ExeDomain =3D SSEPackedSingle in {
   // Intrinsic operation, reg.
   // Vector intrinsic operation, reg
   def PSr : SS4AIi8<opcps, MRMSrcReg,
@@ -5469,15 +6155,16 @@
                     OpSize;
=20
   // Vector intrinsic operation, mem
-  def PSm : Ii8<opcps, MRMSrcMem,
+  def PSm : SS4AIi8<opcps, MRMSrcMem,
                     (outs RC:$dst), (ins x86memop:$src1, i32i8imm:$src2),
                     !strconcat(OpcodeStr,
                     "ps\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
                     [(set RC:$dst,
                           (V4F32Int (mem_frag32 addr:$src1),imm:$src2))]>,
-                    TA, OpSize,
-                Requires<[HasSSE41]>;
-
+                    OpSize;
+} // ExeDomain =3D SSEPackedSingle
+
+let ExeDomain =3D SSEPackedDouble in {
   // Vector intrinsic operation, reg
   def PDr : SS4AIi8<opcpd, MRMSrcReg,
                     (outs RC:$dst), (ins RC:$src1, i32i8imm:$src2),
@@ -5494,46 +6181,26 @@
                     [(set RC:$dst,
                           (V2F64Int (mem_frag64 addr:$src1),imm:$src2))]>,
                     OpSize;
-}
-
-multiclass sse41_fp_unop_rm_avx_p<bits<8> opcps, bits<8> opcpd,
-                   RegisterClass RC, X86MemOperand x86memop, string Opcode=
Str> {
-  // Intrinsic operation, reg.
-  // Vector intrinsic operation, reg
-  def PSr_AVX : SS4AIi8<opcps, MRMSrcReg,
-                    (outs RC:$dst), (ins RC:$src1, i32i8imm:$src2),
-                    !strconcat(OpcodeStr,
-                    "ps\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
-                    []>, OpSize;
-
-  // Vector intrinsic operation, mem
-  def PSm_AVX : Ii8<opcps, MRMSrcMem,
-                    (outs RC:$dst), (ins x86memop:$src1, i32i8imm:$src2),
-                    !strconcat(OpcodeStr,
-                    "ps\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
-                    []>, TA, OpSize, Requires<[HasSSE41]>;
-
-  // Vector intrinsic operation, reg
-  def PDr_AVX : SS4AIi8<opcpd, MRMSrcReg,
-                    (outs RC:$dst), (ins RC:$src1, i32i8imm:$src2),
-                    !strconcat(OpcodeStr,
-                    "pd\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
-                    []>, OpSize;
-
-  // Vector intrinsic operation, mem
-  def PDm_AVX : SS4AIi8<opcpd, MRMSrcMem,
-                    (outs RC:$dst), (ins x86memop:$src1, i32i8imm:$src2),
-                    !strconcat(OpcodeStr,
-                    "pd\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
-                    []>, OpSize;
+} // ExeDomain =3D SSEPackedDouble
 }
=20
 multiclass sse41_fp_binop_rm<bits<8> opcss, bits<8> opcsd,
                             string OpcodeStr,
                             Intrinsic F32Int,
                             Intrinsic F64Int, bit Is2Addr =3D 1> {
+let ExeDomain =3D GenericDomain in {
+  // Operation, reg.
+  def SSr : SS4AIi8<opcss, MRMSrcReg,
+      (outs FR32:$dst), (ins FR32:$src1, FR32:$src2, i32i8imm:$src3),
+      !if(Is2Addr,
+          !strconcat(OpcodeStr,
+              "ss\t{$src3, $src2, $dst|$dst, $src2, $src3}"),
+          !strconcat(OpcodeStr,
+              "ss\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}")=
),
+      []>, OpSize;
+
   // Intrinsic operation, reg.
-  def SSr : SS4AIi8<opcss, MRMSrcReg,
+  def SSr_Int : SS4AIi8<opcss, MRMSrcReg,
         (outs VR128:$dst), (ins VR128:$src1, VR128:$src2, i32i8imm:$src3),
         !if(Is2Addr,
             !strconcat(OpcodeStr,
@@ -5555,8 +6222,18 @@
              (F32Int VR128:$src1, sse_load_f32:$src2, imm:$src3))]>,
         OpSize;
=20
+  // Operation, reg.
+  def SDr : SS4AIi8<opcsd, MRMSrcReg,
+        (outs FR64:$dst), (ins FR64:$src1, FR64:$src2, i32i8imm:$src3),
+        !if(Is2Addr,
+            !strconcat(OpcodeStr,
+                "sd\t{$src3, $src2, $dst|$dst, $src2, $src3}"),
+            !strconcat(OpcodeStr,
+                "sd\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
")),
+        []>, OpSize;
+
   // Intrinsic operation, reg.
-  def SDr : SS4AIi8<opcsd, MRMSrcReg,
+  def SDr_Int : SS4AIi8<opcsd, MRMSrcReg,
         (outs VR128:$dst), (ins VR128:$src1, VR128:$src2, i32i8imm:$src3),
         !if(Is2Addr,
             !strconcat(OpcodeStr,
@@ -5577,37 +6254,7 @@
         [(set VR128:$dst,
               (F64Int VR128:$src1, sse_load_f64:$src2, imm:$src3))]>,
         OpSize;
-}
-
-multiclass sse41_fp_binop_rm_avx_s<bits<8> opcss, bits<8> opcsd,
-                                   string OpcodeStr> {
-  // Intrinsic operation, reg.
-  def SSr_AVX : SS4AIi8<opcss, MRMSrcReg,
-        (outs VR128:$dst), (ins VR128:$src1, VR128:$src2, i32i8imm:$src3),
-        !strconcat(OpcodeStr,
-                "ss\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
"),
-        []>, OpSize;
-
-  // Intrinsic operation, mem.
-  def SSm_AVX : SS4AIi8<opcss, MRMSrcMem,
-        (outs VR128:$dst), (ins VR128:$src1, ssmem:$src2, i32i8imm:$src3),
-        !strconcat(OpcodeStr,
-                "ss\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
"),
-        []>, OpSize;
-
-  // Intrinsic operation, reg.
-  def SDr_AVX : SS4AIi8<opcsd, MRMSrcReg,
-        (outs VR128:$dst), (ins VR128:$src1, VR128:$src2, i32i8imm:$src3),
-            !strconcat(OpcodeStr,
-                "sd\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
"),
-        []>, OpSize;
-
-  // Intrinsic operation, mem.
-  def SDm_AVX : SS4AIi8<opcsd, MRMSrcMem,
-        (outs VR128:$dst), (ins VR128:$src1, sdmem:$src2, i32i8imm:$src3),
-            !strconcat(OpcodeStr,
-                "sd\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}=
"),
-        []>, OpSize;
+} // ExeDomain =3D GenericDomain
 }
=20
 // FP round - roundss, roundps, roundsd, roundpd
@@ -5625,12 +6272,26 @@
                                   int_x86_sse41_round_ss,
                                   int_x86_sse41_round_sd, 0>, VEX_4V, VEX_=
LIG;
=20
-  // Instructions for the assembler
-  defm VROUND  : sse41_fp_unop_rm_avx_p<0x08, 0x09, VR128, f128mem, "vroun=
d">,
-                                        VEX;
-  defm VROUNDY : sse41_fp_unop_rm_avx_p<0x08, 0x09, VR256, f256mem, "vroun=
d">,
-                                        VEX;
-  defm VROUND  : sse41_fp_binop_rm_avx_s<0x0A, 0x0B, "vround">, VEX_4V, VE=
X_LIG;
+  def : Pat<(ffloor FR32:$src),
+            (VROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x1))>;
+  def : Pat<(f64 (ffloor FR64:$src)),
+            (VROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x1))>;
+  def : Pat<(f32 (fnearbyint FR32:$src)),
+            (VROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0xC))>;
+  def : Pat<(f64 (fnearbyint FR64:$src)),
+            (VROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0xC))>;
+  def : Pat<(f32 (fceil FR32:$src)),
+            (VROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x2))>;
+  def : Pat<(f64 (fceil FR64:$src)),
+            (VROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x2))>;
+  def : Pat<(f32 (frint FR32:$src)),
+            (VROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x4))>;
+  def : Pat<(f64 (frint FR64:$src)),
+            (VROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x4))>;
+  def : Pat<(f32 (ftrunc FR32:$src)),
+            (VROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x3))>;
+  def : Pat<(f64 (ftrunc FR64:$src)),
+            (VROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x3))>;
 }
=20
 defm ROUND  : sse41_fp_unop_rm<0x08, 0x09, "round", f128mem, VR128,
@@ -5640,6 +6301,27 @@
 defm ROUND  : sse41_fp_binop_rm<0x0A, 0x0B, "round",
                                int_x86_sse41_round_ss, int_x86_sse41_round=
_sd>;
=20
+def : Pat<(ffloor FR32:$src),
+          (ROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x1))>;
+def : Pat<(f64 (ffloor FR64:$src)),
+          (ROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x1))>;
+def : Pat<(f32 (fnearbyint FR32:$src)),
+          (ROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0xC))>;
+def : Pat<(f64 (fnearbyint FR64:$src)),
+          (ROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0xC))>;
+def : Pat<(f32 (fceil FR32:$src)),
+          (ROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x2))>;
+def : Pat<(f64 (fceil FR64:$src)),
+          (ROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x2))>;
+def : Pat<(f32 (frint FR32:$src)),
+          (ROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x4))>;
+def : Pat<(f64 (frint FR64:$src)),
+          (ROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x4))>;
+def : Pat<(f32 (ftrunc FR32:$src)),
+          (ROUNDSSr (f32 (IMPLICIT_DEF)), FR32:$src, (i32 0x3))>;
+def : Pat<(f64 (ftrunc FR64:$src)),
+          (ROUNDSDr (f64 (IMPLICIT_DEF)), FR64:$src, (i32 0x3))>;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE4.1 - Packed Bit Test
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -5649,11 +6331,11 @@
 let Defs =3D [EFLAGS], Predicates =3D [HasAVX] in {
 def VPTESTrr  : SS48I<0x17, MRMSrcReg, (outs), (ins VR128:$src1, VR128:$sr=
c2),
                 "vptest\t{$src2, $src1|$src1, $src2}",
-                [(set EFLAGS, (X86ptest VR128:$src1, (v4f32 VR128:$src2)))=
]>,
+                [(set EFLAGS, (X86ptest VR128:$src1, (v2i64 VR128:$src2)))=
]>,
                 OpSize, VEX;
 def VPTESTrm  : SS48I<0x17, MRMSrcMem, (outs), (ins VR128:$src1, f128mem:$=
src2),
                 "vptest\t{$src2, $src1|$src1, $src2}",
-                [(set EFLAGS,(X86ptest VR128:$src1, (memopv4f32 addr:$src2=
)))]>,
+                [(set EFLAGS,(X86ptest VR128:$src1, (memopv2i64 addr:$src2=
)))]>,
                 OpSize, VEX;
=20
 def VPTESTYrr : SS48I<0x17, MRMSrcReg, (outs), (ins VR256:$src1, VR256:$sr=
c2),
@@ -5668,12 +6350,12 @@
=20
 let Defs =3D [EFLAGS] in {
 def PTESTrr : SS48I<0x17, MRMSrcReg, (outs), (ins VR128:$src1, VR128:$src2=
),
-              "ptest \t{$src2, $src1|$src1, $src2}",
-              [(set EFLAGS, (X86ptest VR128:$src1, (v4f32 VR128:$src2)))]>,
+              "ptest\t{$src2, $src1|$src1, $src2}",
+              [(set EFLAGS, (X86ptest VR128:$src1, (v2i64 VR128:$src2)))]>,
               OpSize;
 def PTESTrm : SS48I<0x17, MRMSrcMem, (outs), (ins VR128:$src1, f128mem:$sr=
c2),
-              "ptest \t{$src2, $src1|$src1, $src2}",
-              [(set EFLAGS, (X86ptest VR128:$src1, (memopv4f32 addr:$src2)=
))]>,
+              "ptest\t{$src2, $src1|$src1, $src2}",
+              [(set EFLAGS, (X86ptest VR128:$src1, (memopv2i64 addr:$src2)=
))]>,
               OpSize;
 }
=20
@@ -5690,11 +6372,15 @@
 }
=20
 let Defs =3D [EFLAGS], Predicates =3D [HasAVX] in {
+let ExeDomain =3D SSEPackedSingle in {
 defm VTESTPS  : avx_bittest<0x0E, "vtestps", VR128, f128mem, memopv4f32, v=
4f32>;
 defm VTESTPSY : avx_bittest<0x0E, "vtestps", VR256, f256mem, memopv8f32, v=
8f32>;
+}
+let ExeDomain =3D SSEPackedDouble in {
 defm VTESTPD  : avx_bittest<0x0F, "vtestpd", VR128, f128mem, memopv2f64, v=
2f64>;
 defm VTESTPDY : avx_bittest<0x0F, "vtestpd", VR256, f256mem, memopv4f64, v=
4f64>;
 }
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE4.1 - Misc Instructions
@@ -5743,7 +6429,7 @@
                      !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
                      [(set VR128:$dst,
                        (IntId128
-                       (bitconvert (memopv8i16 addr:$src))))]>, OpSize;
+                        (bitconvert (memopv2i64 addr:$src))))]>, OpSize;
 }
=20
 let Predicates =3D [HasAVX] in
@@ -5769,15 +6455,29 @@
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
        [(set VR128:$dst,
          (IntId128 VR128:$src1,
-          (bitconvert (memopv16i8 addr:$src2))))]>, OpSize;
+          (bitconvert (memopv2i64 addr:$src2))))]>, OpSize;
+}
+
+/// SS41I_binop_rm_int - Simple SSE 4.1 binary operator
+multiclass SS41I_binop_rm_int_y<bits<8> opc, string OpcodeStr,
+                                Intrinsic IntId256> {
+  let isCommutable =3D 1 in
+  def Yrr : SS48I<opc, MRMSrcReg, (outs VR256:$dst),
+       (ins VR256:$src1, VR256:$src2),
+       !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+       [(set VR256:$dst, (IntId256 VR256:$src1, VR256:$src2))]>, OpSize;
+  def Yrm : SS48I<opc, MRMSrcMem, (outs VR256:$dst),
+       (ins VR256:$src1, i256mem:$src2),
+       !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+       [(set VR256:$dst,
+         (IntId256 VR256:$src1,
+          (bitconvert (memopv4i64 addr:$src2))))]>, OpSize;
 }
=20
 let Predicates =3D [HasAVX] in {
   let isCommutable =3D 0 in
   defm VPACKUSDW : SS41I_binop_rm_int<0x2B, "vpackusdw", int_x86_sse41_pac=
kusdw,
                                                          0>, VEX_4V;
-  defm VPCMPEQQ  : SS41I_binop_rm_int<0x29, "vpcmpeqq",  int_x86_sse41_pcm=
peqq,
-                                                         0>, VEX_4V;
   defm VPMINSB   : SS41I_binop_rm_int<0x38, "vpminsb",   int_x86_sse41_pmi=
nsb,
                                                          0>, VEX_4V;
   defm VPMINSD   : SS41I_binop_rm_int<0x39, "vpminsd",   int_x86_sse41_pmi=
nsd,
@@ -5796,17 +6496,35 @@
                                                          0>, VEX_4V;
   defm VPMULDQ   : SS41I_binop_rm_int<0x28, "vpmuldq",   int_x86_sse41_pmu=
ldq,
                                                          0>, VEX_4V;
-
-  def : Pat<(v2i64 (X86pcmpeqq VR128:$src1, VR128:$src2)),
-            (VPCMPEQQrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (X86pcmpeqq VR128:$src1, (memop addr:$src2))),
-            (VPCMPEQQrm VR128:$src1, addr:$src2)>;
+}
+
+let Predicates =3D [HasAVX2] in {
+  let isCommutable =3D 0 in
+  defm VPACKUSDW : SS41I_binop_rm_int_y<0x2B, "vpackusdw",
+                                        int_x86_avx2_packusdw>, VEX_4V;
+  defm VPMINSB   : SS41I_binop_rm_int_y<0x38, "vpminsb",
+                                        int_x86_avx2_pmins_b>, VEX_4V;
+  defm VPMINSD   : SS41I_binop_rm_int_y<0x39, "vpminsd",
+                                        int_x86_avx2_pmins_d>, VEX_4V;
+  defm VPMINUD   : SS41I_binop_rm_int_y<0x3B, "vpminud",
+                                        int_x86_avx2_pminu_d>, VEX_4V;
+  defm VPMINUW   : SS41I_binop_rm_int_y<0x3A, "vpminuw",
+                                        int_x86_avx2_pminu_w>, VEX_4V;
+  defm VPMAXSB   : SS41I_binop_rm_int_y<0x3C, "vpmaxsb",
+                                        int_x86_avx2_pmaxs_b>, VEX_4V;
+  defm VPMAXSD   : SS41I_binop_rm_int_y<0x3D, "vpmaxsd",
+                                        int_x86_avx2_pmaxs_d>, VEX_4V;
+  defm VPMAXUD   : SS41I_binop_rm_int_y<0x3F, "vpmaxud",
+                                        int_x86_avx2_pmaxu_d>, VEX_4V;
+  defm VPMAXUW   : SS41I_binop_rm_int_y<0x3E, "vpmaxuw",
+                                        int_x86_avx2_pmaxu_w>, VEX_4V;
+  defm VPMULDQ   : SS41I_binop_rm_int_y<0x28, "vpmuldq",
+                                        int_x86_avx2_pmul_dq>, VEX_4V;
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
   let isCommutable =3D 0 in
   defm PACKUSDW : SS41I_binop_rm_int<0x2B, "packusdw", int_x86_sse41_packu=
sdw>;
-  defm PCMPEQQ  : SS41I_binop_rm_int<0x29, "pcmpeqq",  int_x86_sse41_pcmpe=
qq>;
   defm PMINSB   : SS41I_binop_rm_int<0x38, "pminsb",   int_x86_sse41_pmins=
b>;
   defm PMINSD   : SS41I_binop_rm_int<0x39, "pminsd",   int_x86_sse41_pmins=
d>;
   defm PMINUD   : SS41I_binop_rm_int<0x3B, "pminud",   int_x86_sse41_pminu=
d>;
@@ -5818,36 +6536,46 @@
   defm PMULDQ   : SS41I_binop_rm_int<0x28, "pmuldq",   int_x86_sse41_pmuld=
q>;
 }
=20
-def : Pat<(v2i64 (X86pcmpeqq VR128:$src1, VR128:$src2)),
-          (PCMPEQQrr VR128:$src1, VR128:$src2)>;
-def : Pat<(v2i64 (X86pcmpeqq VR128:$src1, (memop addr:$src2))),
-          (PCMPEQQrm VR128:$src1, addr:$src2)>;
-
 /// SS48I_binop_rm - Simple SSE41 binary operator.
 multiclass SS48I_binop_rm<bits<8> opc, string OpcodeStr, SDNode OpNode,
-                        ValueType OpVT, bit Is2Addr =3D 1> {
+                          ValueType OpVT, RegisterClass RC, PatFrag memop_=
frag,
+                          X86MemOperand x86memop, bit Is2Addr =3D 1> {
   let isCommutable =3D 1 in
-  def rr : SS48I<opc, MRMSrcReg, (outs VR128:$dst),
-       (ins VR128:$src1, VR128:$src2),
+  def rr : SS48I<opc, MRMSrcReg, (outs RC:$dst),
+       (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (OpVT (OpNode VR128:$src1, VR128:$src2)))]>,
-       OpSize;
-  def rm : SS48I<opc, MRMSrcMem, (outs VR128:$dst),
-       (ins VR128:$src1, i128mem:$src2),
+       [(set RC:$dst, (OpVT (OpNode RC:$src1, RC:$src2)))]>, OpSize;
+  def rm : SS48I<opc, MRMSrcMem, (outs RC:$dst),
+       (ins RC:$src1, x86memop:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (OpNode VR128:$src1,
-                                  (bc_v4i32 (memopv2i64 addr:$src2))))]>,
-       OpSize;
-}
-
-let Predicates =3D [HasAVX] in
-  defm VPMULLD : SS48I_binop_rm<0x40, "vpmulld", mul, v4i32, 0>, VEX_4V;
-let Constraints =3D "$src1 =3D $dst" in
-  defm PMULLD : SS48I_binop_rm<0x40, "pmulld", mul, v4i32>;
+       [(set RC:$dst,
+         (OpVT (OpNode RC:$src1,
+          (bitconvert (memop_frag addr:$src2)))))]>, OpSize;
+}
+
+let Predicates =3D [HasAVX] in {
+  defm VPMULLD  : SS48I_binop_rm<0x40, "vpmulld", mul, v4i32, VR128,
+                                memopv2i64, i128mem, 0>, VEX_4V;
+  defm VPCMPEQQ : SS48I_binop_rm<0x29, "vpcmpeqq", X86pcmpeq, v2i64, VR128,
+                                 memopv2i64, i128mem, 0>, VEX_4V;
+}
+let Predicates =3D [HasAVX2] in {
+  defm VPMULLDY  : SS48I_binop_rm<0x40, "vpmulld", mul, v8i32, VR256,
+                                  memopv4i64, i256mem, 0>, VEX_4V;
+  defm VPCMPEQQY : SS48I_binop_rm<0x29, "vpcmpeqq", X86pcmpeq, v4i64, VR25=
6,
+                                  memopv4i64, i256mem, 0>, VEX_4V;
+}
+
+let Constraints =3D "$src1 =3D $dst" in {
+  defm PMULLD  : SS48I_binop_rm<0x40, "pmulld", mul, v4i32, VR128,
+                                memopv2i64, i128mem>;
+  defm PCMPEQQ : SS48I_binop_rm<0x29, "pcmpeqq", X86pcmpeq, v2i64, VR128,
+                                memopv2i64, i128mem>;
+}
=20
 /// SS41I_binop_rmi_int - SSE 4.1 binary operator with 8-bit immediate
 multiclass SS41I_binop_rmi_int<bits<8> opc, string OpcodeStr,
@@ -5878,77 +6606,106 @@
=20
 let Predicates =3D [HasAVX] in {
   let isCommutable =3D 0 in {
-  defm VBLENDPS : SS41I_binop_rmi_int<0x0C, "vblendps", int_x86_sse41_blen=
dps,
-                                      VR128, memopv16i8, i128mem, 0>, VEX_=
4V;
-  defm VBLENDPD : SS41I_binop_rmi_int<0x0D, "vblendpd", int_x86_sse41_blen=
dpd,
-                                      VR128, memopv16i8, i128mem, 0>, VEX_=
4V;
-  defm VBLENDPSY : SS41I_binop_rmi_int<0x0C, "vblendps",
-            int_x86_avx_blend_ps_256, VR256, memopv32i8, i256mem, 0>, VEX_=
4V;
-  defm VBLENDPDY : SS41I_binop_rmi_int<0x0D, "vblendpd",
-            int_x86_avx_blend_pd_256, VR256, memopv32i8, i256mem, 0>, VEX_=
4V;
+    let ExeDomain =3D SSEPackedSingle in {
+    defm VBLENDPS : SS41I_binop_rmi_int<0x0C, "vblendps", int_x86_sse41_bl=
endps,
+                                        VR128, memopv4f32, i128mem, 0>, VE=
X_4V;
+    defm VBLENDPSY : SS41I_binop_rmi_int<0x0C, "vblendps",
+              int_x86_avx_blend_ps_256, VR256, memopv8f32, i256mem, 0>, VE=
X_4V;
+    }
+    let ExeDomain =3D SSEPackedDouble in {
+    defm VBLENDPD : SS41I_binop_rmi_int<0x0D, "vblendpd", int_x86_sse41_bl=
endpd,
+                                        VR128, memopv2f64, i128mem, 0>, VE=
X_4V;
+    defm VBLENDPDY : SS41I_binop_rmi_int<0x0D, "vblendpd",
+              int_x86_avx_blend_pd_256, VR256, memopv4f64, i256mem, 0>, VE=
X_4V;
+    }
   defm VPBLENDW : SS41I_binop_rmi_int<0x0E, "vpblendw", int_x86_sse41_pble=
ndw,
-                                      VR128, memopv16i8, i128mem, 0>, VEX_=
4V;
+                                      VR128, memopv2i64, i128mem, 0>, VEX_=
4V;
   defm VMPSADBW : SS41I_binop_rmi_int<0x42, "vmpsadbw", int_x86_sse41_mpsa=
dbw,
-                                      VR128, memopv16i8, i128mem, 0>, VEX_=
4V;
+                                      VR128, memopv2i64, i128mem, 0>, VEX_=
4V;
   }
+  let ExeDomain =3D SSEPackedSingle in
   defm VDPPS : SS41I_binop_rmi_int<0x40, "vdpps", int_x86_sse41_dpps,
-                                   VR128, memopv16i8, i128mem, 0>, VEX_4V;
+                                   VR128, memopv4f32, i128mem, 0>, VEX_4V;
+  let ExeDomain =3D SSEPackedDouble in
   defm VDPPD : SS41I_binop_rmi_int<0x41, "vdppd", int_x86_sse41_dppd,
-                                   VR128, memopv16i8, i128mem, 0>, VEX_4V;
+                                   VR128, memopv2f64, i128mem, 0>, VEX_4V;
+  let ExeDomain =3D SSEPackedSingle in
   defm VDPPSY : SS41I_binop_rmi_int<0x40, "vdpps", int_x86_avx_dp_ps_256,
-                                   VR256, memopv32i8, i256mem, 0>, VEX_4V;
+                                   VR256, memopv8f32, i256mem, 0>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2] in {
+  let isCommutable =3D 0 in {
+  defm VPBLENDWY : SS41I_binop_rmi_int<0x0E, "vpblendw", int_x86_avx2_pble=
ndw,
+                                       VR256, memopv4i64, i256mem, 0>, VEX=
_4V;
+  defm VMPSADBWY : SS41I_binop_rmi_int<0x42, "vmpsadbw", int_x86_avx2_mpsa=
dbw,
+                                       VR256, memopv4i64, i256mem, 0>, VEX=
_4V;
+  }
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
   let isCommutable =3D 0 in {
+  let ExeDomain =3D SSEPackedSingle in
   defm BLENDPS : SS41I_binop_rmi_int<0x0C, "blendps", int_x86_sse41_blendp=
s,
-                                     VR128, memopv16i8, i128mem>;
+                                     VR128, memopv4f32, i128mem>;
+  let ExeDomain =3D SSEPackedDouble in
   defm BLENDPD : SS41I_binop_rmi_int<0x0D, "blendpd", int_x86_sse41_blendp=
d,
-                                     VR128, memopv16i8, i128mem>;
+                                     VR128, memopv2f64, i128mem>;
   defm PBLENDW : SS41I_binop_rmi_int<0x0E, "pblendw", int_x86_sse41_pblend=
w,
-                                     VR128, memopv16i8, i128mem>;
+                                     VR128, memopv2i64, i128mem>;
   defm MPSADBW : SS41I_binop_rmi_int<0x42, "mpsadbw", int_x86_sse41_mpsadb=
w,
-                                     VR128, memopv16i8, i128mem>;
+                                     VR128, memopv2i64, i128mem>;
   }
+  let ExeDomain =3D SSEPackedSingle in
   defm DPPS : SS41I_binop_rmi_int<0x40, "dpps", int_x86_sse41_dpps,
-                                  VR128, memopv16i8, i128mem>;
+                                  VR128, memopv4f32, i128mem>;
+  let ExeDomain =3D SSEPackedDouble in
   defm DPPD : SS41I_binop_rmi_int<0x41, "dppd", int_x86_sse41_dppd,
-                                  VR128, memopv16i8, i128mem>;
+                                  VR128, memopv2f64, i128mem>;
 }
=20
 /// SS41I_quaternary_int_avx - AVX SSE 4.1 with 4 operators
-let Predicates =3D [HasAVX] in {
 multiclass SS41I_quaternary_int_avx<bits<8> opc, string OpcodeStr,
                                     RegisterClass RC, X86MemOperand x86mem=
op,
                                     PatFrag mem_frag, Intrinsic IntId> {
-  def rr : I<opc, MRMSrcReg, (outs RC:$dst),
+  def rr : Ii8<opc, MRMSrcReg, (outs RC:$dst),
                   (ins RC:$src1, RC:$src2, RC:$src3),
                   !strconcat(OpcodeStr,
                     "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src=
3}"),
                   [(set RC:$dst, (IntId RC:$src1, RC:$src2, RC:$src3))],
-                  SSEPackedInt>, OpSize, TA, VEX_4V, VEX_I8IMM;
-
-  def rm : I<opc, MRMSrcMem, (outs RC:$dst),
+                  IIC_DEFAULT, SSEPackedInt>, OpSize, TA, VEX_4V, VEX_I8IM=
M;
+
+  def rm : Ii8<opc, MRMSrcMem, (outs RC:$dst),
                   (ins RC:$src1, x86memop:$src2, RC:$src3),
                   !strconcat(OpcodeStr,
                     "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src=
3}"),
                   [(set RC:$dst,
                         (IntId RC:$src1, (bitconvert (mem_frag addr:$src2)=
),
                                RC:$src3))],
-                  SSEPackedInt>, OpSize, TA, VEX_4V, VEX_I8IMM;
-}
-}
-
+                  IIC_DEFAULT, SSEPackedInt>, OpSize, TA, VEX_4V, VEX_I8IM=
M;
+}
+
+let Predicates =3D [HasAVX] in {
+let ExeDomain =3D SSEPackedDouble in {
 defm VBLENDVPD  : SS41I_quaternary_int_avx<0x4B, "vblendvpd", VR128, i128m=
em,
-                                           memopv16i8, int_x86_sse41_blend=
vpd>;
+                                           memopv2f64, int_x86_sse41_blend=
vpd>;
+defm VBLENDVPDY : SS41I_quaternary_int_avx<0x4B, "vblendvpd", VR256, i256m=
em,
+                                         memopv4f64, int_x86_avx_blendv_pd=
_256>;
+} // ExeDomain =3D SSEPackedDouble
+let ExeDomain =3D SSEPackedSingle in {
 defm VBLENDVPS  : SS41I_quaternary_int_avx<0x4A, "vblendvps", VR128, i128m=
em,
-                                           memopv16i8, int_x86_sse41_blend=
vps>;
+                                           memopv4f32, int_x86_sse41_blend=
vps>;
+defm VBLENDVPSY : SS41I_quaternary_int_avx<0x4A, "vblendvps", VR256, i256m=
em,
+                                         memopv8f32, int_x86_avx_blendv_ps=
_256>;
+} // ExeDomain =3D SSEPackedSingle
 defm VPBLENDVB  : SS41I_quaternary_int_avx<0x4C, "vpblendvb", VR128, i128m=
em,
-                                           memopv16i8, int_x86_sse41_pblen=
dvb>;
-defm VBLENDVPDY : SS41I_quaternary_int_avx<0x4B, "vblendvpd", VR256, i256m=
em,
-                                         memopv32i8, int_x86_avx_blendv_pd=
_256>;
-defm VBLENDVPSY : SS41I_quaternary_int_avx<0x4A, "vblendvps", VR256, i256m=
em,
-                                         memopv32i8, int_x86_avx_blendv_ps=
_256>;
+                                           memopv2i64, int_x86_sse41_pblen=
dvb>;
+}
+
+let Predicates =3D [HasAVX2] in {
+defm VPBLENDVBY : SS41I_quaternary_int_avx<0x4C, "vpblendvb", VR256, i256m=
em,
+                                           memopv4i64, int_x86_avx2_pblend=
vb>;
+}
=20
 let Predicates =3D [HasAVX] in {
   def : Pat<(v16i8 (vselect (v16i8 VR128:$mask), (v16i8 VR128:$src1),
@@ -5978,11 +6735,28 @@
   def : Pat<(v4f64 (vselect (v4i64 VR256:$mask), (v4f64 VR256:$src1),
                             (v4f64 VR256:$src2))),
             (VBLENDVPDYrr VR256:$src2, VR256:$src1, VR256:$mask)>;
+
+  def : Pat<(v8f32 (X86Blendps (v8f32 VR256:$src1), (v8f32 VR256:$src2),
+                               (imm:$mask))),
+            (VBLENDPSYrri VR256:$src2, VR256:$src1, imm:$mask)>;
+  def : Pat<(v4f64 (X86Blendpd (v4f64 VR256:$src1), (v4f64 VR256:$src2),
+                               (imm:$mask))),
+            (VBLENDPDYrri VR256:$src2, VR256:$src1, imm:$mask)>;
+}
+
+let Predicates =3D [HasAVX2] in {
+  def : Pat<(v32i8 (vselect (v32i8 VR256:$mask), (v32i8 VR256:$src1),
+                            (v32i8 VR256:$src2))),
+            (VPBLENDVBYrr VR256:$src2, VR256:$src1, VR256:$mask)>;
+  def : Pat<(v16i16 (X86Blendpw (v16i16 VR256:$src1), (v16i16 VR256:$src2),
+                               (imm:$mask))),
+            (VPBLENDWYrri VR256:$src2, VR256:$src1, imm:$mask)>;
 }
=20
 /// SS41I_ternary_int - SSE 4.1 ternary operator
 let Uses =3D [XMM0], Constraints =3D "$src1 =3D $dst" in {
-  multiclass SS41I_ternary_int<bits<8> opc, string OpcodeStr, Intrinsic In=
tId> {
+  multiclass SS41I_ternary_int<bits<8> opc, string OpcodeStr, PatFrag mem_=
frag,
+                               Intrinsic IntId> {
     def rr0 : SS48I<opc, MRMSrcReg, (outs VR128:$dst),
                     (ins VR128:$src1, VR128:$src2),
                     !strconcat(OpcodeStr,
@@ -5996,13 +6770,18 @@
                      "\t{$src2, $dst|$dst, $src2}"),
                     [(set VR128:$dst,
                       (IntId VR128:$src1,
-                       (bitconvert (memopv16i8 addr:$src2)), XMM0))]>, OpS=
ize;
+                       (bitconvert (mem_frag addr:$src2)), XMM0))]>, OpSiz=
e;
   }
 }
=20
-defm BLENDVPD : SS41I_ternary_int<0x15, "blendvpd", int_x86_sse41_blendvpd=
>;
-defm BLENDVPS : SS41I_ternary_int<0x14, "blendvps", int_x86_sse41_blendvps=
>;
-defm PBLENDVB : SS41I_ternary_int<0x10, "pblendvb", int_x86_sse41_pblendvb=
>;
+let ExeDomain =3D SSEPackedDouble in
+defm BLENDVPD : SS41I_ternary_int<0x15, "blendvpd", memopv2f64,
+                                  int_x86_sse41_blendvpd>;
+let ExeDomain =3D SSEPackedSingle in
+defm BLENDVPS : SS41I_ternary_int<0x14, "blendvps", memopv4f32,
+                                  int_x86_sse41_blendvps>;
+defm PBLENDVB : SS41I_ternary_int<0x10, "pblendvb", memopv2i64,
+                                  int_x86_sse41_pblendvb>;
=20
 let Predicates =3D [HasSSE41] in {
   def : Pat<(v16i8 (vselect (v16i8 XMM0), (v16i8 VR128:$src1),
@@ -6020,6 +6799,17 @@
   def : Pat<(v2f64 (vselect (v2i64 XMM0), (v2f64 VR128:$src1),
                             (v2f64 VR128:$src2))),
             (BLENDVPDrr0 VR128:$src2, VR128:$src1)>;
+
+  def : Pat<(v8i16 (X86Blendpw (v8i16 VR128:$src1), (v8i16 VR128:$src2),
+                               (imm:$mask))),
+            (VPBLENDWrri VR128:$src2, VR128:$src1, imm:$mask)>;
+  def : Pat<(v4f32 (X86Blendps (v4f32 VR128:$src1), (v4f32 VR128:$src2),
+                               (imm:$mask))),
+            (VBLENDPSrri VR128:$src2, VR128:$src1, imm:$mask)>;
+  def : Pat<(v2f64 (X86Blendpd (v2f64 VR128:$src1), (v2f64 VR128:$src2),
+                               (imm:$mask))),
+            (VBLENDPDrri VR128:$src2, VR128:$src1, imm:$mask)>;
+
 }
=20
 let Predicates =3D [HasAVX] in
@@ -6027,6 +6817,11 @@
                        "vmovntdqa\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (int_x86_sse41_movntdqa addr:$src=
))]>,
                        OpSize, VEX;
+let Predicates =3D [HasAVX2] in
+def VMOVNTDQAYrm : SS48I<0x2A, MRMSrcMem, (outs VR256:$dst), (ins i256mem:=
$src),
+                         "vmovntdqa\t{$src, $dst|$dst, $src}",
+                         [(set VR256:$dst, (int_x86_avx2_movntdqa addr:$sr=
c))]>,
+                         OpSize, VEX;
 def MOVNTDQArm : SS48I<0x2A, MRMSrcMem, (outs VR128:$dst), (ins i128mem:$s=
rc),
                        "movntdqa\t{$src, $dst|$dst, $src}",
                        [(set VR128:$dst, (int_x86_sse41_movntdqa addr:$src=
))]>,
@@ -6036,43 +6831,37 @@
 // SSE4.2 - Compare Instructions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-/// SS42I_binop_rm_int - Simple SSE 4.2 binary operator
-multiclass SS42I_binop_rm_int<bits<8> opc, string OpcodeStr,
-                              Intrinsic IntId128, bit Is2Addr =3D 1> {
-  def rr : SS428I<opc, MRMSrcReg, (outs VR128:$dst),
-       (ins VR128:$src1, VR128:$src2),
+/// SS42I_binop_rm - Simple SSE 4.2 binary operator
+multiclass SS42I_binop_rm<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                          ValueType OpVT, RegisterClass RC, PatFrag memop_=
frag,
+                          X86MemOperand x86memop, bit Is2Addr =3D 1> {
+  def rr : SS428I<opc, MRMSrcReg, (outs RC:$dst),
+       (ins RC:$src1, RC:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst, (IntId128 VR128:$src1, VR128:$src2))]>,
+       [(set RC:$dst, (OpVT (OpNode RC:$src1, RC:$src2)))]>,
        OpSize;
-  def rm : SS428I<opc, MRMSrcMem, (outs VR128:$dst),
-       (ins VR128:$src1, i128mem:$src2),
+  def rm : SS428I<opc, MRMSrcMem, (outs RC:$dst),
+       (ins RC:$src1, x86memop:$src2),
        !if(Is2Addr,
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
-       [(set VR128:$dst,
-         (IntId128 VR128:$src1,
-          (bitconvert (memopv16i8 addr:$src2))))]>, OpSize;
-}
-
-let Predicates =3D [HasAVX] in {
-  defm VPCMPGTQ : SS42I_binop_rm_int<0x37, "vpcmpgtq", int_x86_sse42_pcmpg=
tq,
-                                     0>, VEX_4V;
-
-  def : Pat<(v2i64 (X86pcmpgtq VR128:$src1, VR128:$src2)),
-            (VPCMPGTQrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (X86pcmpgtq VR128:$src1, (memop addr:$src2))),
-            (VPCMPGTQrm VR128:$src1, addr:$src2)>;
-}
+       [(set RC:$dst,
+         (OpVT (OpNode RC:$src1, (memop_frag addr:$src2))))]>, OpSize;
+}
+
+let Predicates =3D [HasAVX] in
+  defm VPCMPGTQ : SS42I_binop_rm<0x37, "vpcmpgtq", X86pcmpgt, v2i64, VR128,
+                                 memopv2i64, i128mem, 0>, VEX_4V;
+
+let Predicates =3D [HasAVX2] in
+  defm VPCMPGTQY : SS42I_binop_rm<0x37, "vpcmpgtq", X86pcmpgt, v4i64, VR25=
6,
+                                  memopv4i64, i256mem, 0>, VEX_4V;
=20
 let Constraints =3D "$src1 =3D $dst" in
-  defm PCMPGTQ : SS42I_binop_rm_int<0x37, "pcmpgtq", int_x86_sse42_pcmpgtq=
>;
-
-def : Pat<(v2i64 (X86pcmpgtq VR128:$src1, VR128:$src2)),
-          (PCMPGTQrr VR128:$src1, VR128:$src2)>;
-def : Pat<(v2i64 (X86pcmpgtq VR128:$src1, (memop addr:$src2))),
-          (PCMPGTQrm VR128:$src1, addr:$src2)>;
+  defm PCMPGTQ : SS42I_binop_rm<0x37, "pcmpgtq", X86pcmpgt, v2i64, VR128,
+                                memopv2i64, i128mem>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // SSE4.2 - String/text Processing Instructions
@@ -6091,23 +6880,26 @@
 }
=20
 let Defs =3D [EFLAGS], usesCustomInserter =3D 1 in {
+  let AddedComplexity =3D 1 in
+    defm VPCMPISTRM128 : pseudo_pcmpistrm<"#VPCMPISTRM128">, Requires<[Has=
AVX]>;
   defm PCMPISTRM128 : pseudo_pcmpistrm<"#PCMPISTRM128">, Requires<[HasSSE4=
2]>;
-  defm VPCMPISTRM128 : pseudo_pcmpistrm<"#VPCMPISTRM128">, Requires<[HasAV=
X]>;
-}
-
-let Defs =3D [XMM0, EFLAGS], Predicates =3D [HasAVX] in {
+}
+
+let Defs =3D [XMM0, EFLAGS], neverHasSideEffects =3D 1, Predicates =3D [Ha=
sAVX] in {
   def VPCMPISTRM128rr : SS42AI<0x62, MRMSrcReg, (outs),
       (ins VR128:$src1, VR128:$src2, i8imm:$src3),
       "vpcmpistrm\t{$src3, $src2, $src1|$src1, $src2, $src3}", []>, OpSize=
, VEX;
+  let mayLoad =3D 1 in
   def VPCMPISTRM128rm : SS42AI<0x62, MRMSrcMem, (outs),
       (ins VR128:$src1, i128mem:$src2, i8imm:$src3),
       "vpcmpistrm\t{$src3, $src2, $src1|$src1, $src2, $src3}", []>, OpSize=
, VEX;
 }
=20
-let Defs =3D [XMM0, EFLAGS] in {
+let Defs =3D [XMM0, EFLAGS], neverHasSideEffects =3D 1 in {
   def PCMPISTRM128rr : SS42AI<0x62, MRMSrcReg, (outs),
       (ins VR128:$src1, VR128:$src2, i8imm:$src3),
       "pcmpistrm\t{$src3, $src2, $src1|$src1, $src2, $src3}", []>, OpSize;
+  let mayLoad =3D 1 in
   def PCMPISTRM128rm : SS42AI<0x62, MRMSrcMem, (outs),
       (ins VR128:$src1, i128mem:$src2, i8imm:$src3),
       "pcmpistrm\t{$src3, $src2, $src1|$src1, $src2, $src3}", []>, OpSize;
@@ -6126,24 +6918,27 @@
 }
=20
 let Defs =3D [EFLAGS], Uses =3D [EAX, EDX], usesCustomInserter =3D 1 in {
+  let AddedComplexity =3D 1 in
+    defm VPCMPESTRM128 : pseudo_pcmpestrm<"#VPCMPESTRM128">, Requires<[Has=
AVX]>;
   defm PCMPESTRM128 : pseudo_pcmpestrm<"#PCMPESTRM128">, Requires<[HasSSE4=
2]>;
-  defm VPCMPESTRM128 : pseudo_pcmpestrm<"#VPCMPESTRM128">, Requires<[HasAV=
X]>;
 }
=20
 let Predicates =3D [HasAVX],
-    Defs =3D [XMM0, EFLAGS], Uses =3D [EAX, EDX] in {
+    Defs =3D [XMM0, EFLAGS], Uses =3D [EAX, EDX], neverHasSideEffects =3D =
1 in {
   def VPCMPESTRM128rr : SS42AI<0x60, MRMSrcReg, (outs),
       (ins VR128:$src1, VR128:$src3, i8imm:$src5),
       "vpcmpestrm\t{$src5, $src3, $src1|$src1, $src3, $src5}", []>, OpSize=
, VEX;
+  let mayLoad =3D 1 in
   def VPCMPESTRM128rm : SS42AI<0x60, MRMSrcMem, (outs),
       (ins VR128:$src1, i128mem:$src3, i8imm:$src5),
       "vpcmpestrm\t{$src5, $src3, $src1|$src1, $src3, $src5}", []>, OpSize=
, VEX;
 }
=20
-let Defs =3D [XMM0, EFLAGS], Uses =3D [EAX, EDX] in {
+let Defs =3D [XMM0, EFLAGS], Uses =3D [EAX, EDX], neverHasSideEffects =3D =
1 in {
   def PCMPESTRM128rr : SS42AI<0x60, MRMSrcReg, (outs),
       (ins VR128:$src1, VR128:$src3, i8imm:$src5),
       "pcmpestrm\t{$src5, $src3, $src1|$src1, $src3, $src5}", []>, OpSize;
+  let mayLoad =3D 1 in
   def PCMPESTRM128rm : SS42AI<0x60, MRMSrcMem, (outs),
       (ins VR128:$src1, i128mem:$src3, i8imm:$src5),
       "pcmpestrm\t{$src5, $src3, $src1|$src1, $src3, $src5}", []>, OpSize;
@@ -6318,8 +7113,7 @@
            !strconcat(OpcodeStr, "\t{$src2, $dst|$dst, $src2}"),
            !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $src2=
}")),
        [(set VR128:$dst,
-         (IntId128 VR128:$src1,
-          (bitconvert (memopv16i8 addr:$src2))))]>, OpSize;
+         (IntId128 VR128:$src1, (memopv2i64 addr:$src2)))]>, OpSize;
 }
=20
 // Perform One Round of an AES Encryption/Decryption Flow
@@ -6345,44 +7139,6 @@
                          int_x86_aesni_aesdeclast>;
 }
=20
-let Predicates =3D [HasAES] in {
-  def : Pat<(v2i64 (int_x86_aesni_aesenc VR128:$src1, VR128:$src2)),
-            (AESENCrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesenc VR128:$src1, (memop addr:$src2))),
-            (AESENCrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesenclast VR128:$src1, VR128:$src2)),
-            (AESENCLASTrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesenclast VR128:$src1, (memop addr:$src=
2))),
-            (AESENCLASTrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdec VR128:$src1, VR128:$src2)),
-            (AESDECrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdec VR128:$src1, (memop addr:$src2))),
-            (AESDECrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdeclast VR128:$src1, VR128:$src2)),
-            (AESDECLASTrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdeclast VR128:$src1, (memop addr:$src=
2))),
-            (AESDECLASTrm VR128:$src1, addr:$src2)>;
-}
-
-let Predicates =3D [HasAVX, HasAES], AddedComplexity =3D 20 in {
-  def : Pat<(v2i64 (int_x86_aesni_aesenc VR128:$src1, VR128:$src2)),
-            (VAESENCrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesenc VR128:$src1, (memop addr:$src2))),
-            (VAESENCrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesenclast VR128:$src1, VR128:$src2)),
-            (VAESENCLASTrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesenclast VR128:$src1, (memop addr:$src=
2))),
-            (VAESENCLASTrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdec VR128:$src1, VR128:$src2)),
-            (VAESDECrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdec VR128:$src1, (memop addr:$src2))),
-            (VAESDECrm VR128:$src1, addr:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdeclast VR128:$src1, VR128:$src2)),
-            (VAESDECLASTrr VR128:$src1, VR128:$src2)>;
-  def : Pat<(v2i64 (int_x86_aesni_aesdeclast VR128:$src1, (memop addr:$src=
2))),
-            (VAESDECLASTrm VR128:$src1, addr:$src2)>;
-}
-
 // Perform the AES InvMixColumn Transformation
 let Predicates =3D [HasAVX, HasAES] in {
   def VAESIMCrr : AES8I<0xDB, MRMSrcReg, (outs VR128:$dst),
@@ -6394,8 +7150,7 @@
   def VAESIMCrm : AES8I<0xDB, MRMSrcMem, (outs VR128:$dst),
       (ins i128mem:$src1),
       "vaesimc\t{$src1, $dst|$dst, $src1}",
-      [(set VR128:$dst,
-        (int_x86_aesni_aesimc (bitconvert (memopv2i64 addr:$src1))))]>,
+      [(set VR128:$dst, (int_x86_aesni_aesimc (memopv2i64 addr:$src1)))]>,
       OpSize, VEX;
 }
 def AESIMCrr : AES8I<0xDB, MRMSrcReg, (outs VR128:$dst),
@@ -6407,8 +7162,7 @@
 def AESIMCrm : AES8I<0xDB, MRMSrcMem, (outs VR128:$dst),
   (ins i128mem:$src1),
   "aesimc\t{$src1, $dst|$dst, $src1}",
-  [(set VR128:$dst,
-    (int_x86_aesni_aesimc (bitconvert (memopv2i64 addr:$src1))))]>,
+  [(set VR128:$dst, (int_x86_aesni_aesimc (memopv2i64 addr:$src1)))]>,
   OpSize;
=20
 // AES Round Key Generation Assist
@@ -6423,8 +7177,7 @@
       (ins i128mem:$src1, i8imm:$src2),
       "vaeskeygenassist\t{$src2, $src1, $dst|$dst, $src1, $src2}",
       [(set VR128:$dst,
-        (int_x86_aesni_aeskeygenassist (bitconvert (memopv2i64 addr:$src1)=
),
-                                        imm:$src2))]>,
+        (int_x86_aesni_aeskeygenassist (memopv2i64 addr:$src1), imm:$src2)=
)]>,
       OpSize, VEX;
 }
 def AESKEYGENASSIST128rr : AESAI<0xDF, MRMSrcReg, (outs VR128:$dst),
@@ -6437,8 +7190,7 @@
   (ins i128mem:$src1, i8imm:$src2),
   "aeskeygenassist\t{$src2, $src1, $dst|$dst, $src1, $src2}",
   [(set VR128:$dst,
-    (int_x86_aesni_aeskeygenassist (bitconvert (memopv2i64 addr:$src1)),
-                                    imm:$src2))]>,
+    (int_x86_aesni_aeskeygenassist (memopv2i64 addr:$src1), imm:$src2))]>,
   OpSize;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -6446,28 +7198,32 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 // Carry-less Multiplication instructions
+let neverHasSideEffects =3D 1 in {
+// AVX carry-less Multiplication instructions
+def VPCLMULQDQrr : AVXCLMULIi8<0x44, MRMSrcReg, (outs VR128:$dst),
+           (ins VR128:$src1, VR128:$src2, i8imm:$src3),
+           "vpclmulqdq\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
+           []>;
+
+let mayLoad =3D 1 in
+def VPCLMULQDQrm : AVXCLMULIi8<0x44, MRMSrcMem, (outs VR128:$dst),
+           (ins VR128:$src1, i128mem:$src2, i8imm:$src3),
+           "vpclmulqdq\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
+           []>;
+
 let Constraints =3D "$src1 =3D $dst" in {
 def PCLMULQDQrr : CLMULIi8<0x44, MRMSrcReg, (outs VR128:$dst),
            (ins VR128:$src1, VR128:$src2, i8imm:$src3),
            "pclmulqdq\t{$src3, $src2, $dst|$dst, $src2, $src3}",
            []>;
=20
+let mayLoad =3D 1 in
 def PCLMULQDQrm : CLMULIi8<0x44, MRMSrcMem, (outs VR128:$dst),
            (ins VR128:$src1, i128mem:$src2, i8imm:$src3),
            "pclmulqdq\t{$src3, $src2, $dst|$dst, $src2, $src3}",
            []>;
-}
-
-// AVX carry-less Multiplication instructions
-def VPCLMULQDQrr : AVXCLMULIi8<0x44, MRMSrcReg, (outs VR128:$dst),
-           (ins VR128:$src1, VR128:$src2, i8imm:$src3),
-           "vpclmulqdq\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
-           []>;
-
-def VPCLMULQDQrm : AVXCLMULIi8<0x44, MRMSrcMem, (outs VR128:$dst),
-           (ins VR128:$src1, i128mem:$src2, i8imm:$src3),
-           "vpclmulqdq\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
-           []>;
+} // Constraints =3D "$src1 =3D $dst"
+} // neverHasSideEffects =3D 1
=20
=20
 multiclass pclmul_alias<string asm, int immop> {
@@ -6506,51 +7262,60 @@
         !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
         [(set RC:$dst, (Int addr:$src))]>, VEX;
=20
-def VBROADCASTSS   : avx_broadcast<0x18, "vbroadcastss", VR128, f32mem,
-                                   int_x86_avx_vbroadcastss>;
-def VBROADCASTSSY  : avx_broadcast<0x18, "vbroadcastss", VR256, f32mem,
-                                   int_x86_avx_vbroadcastss_256>;
-def VBROADCASTSD   : avx_broadcast<0x19, "vbroadcastsd", VR256, f64mem,
-                                   int_x86_avx_vbroadcast_sd_256>;
+// AVX2 adds register forms
+class avx2_broadcast_reg<bits<8> opc, string OpcodeStr, RegisterClass RC,
+                         Intrinsic Int> :
+  AVX28I<opc, MRMSrcReg, (outs RC:$dst), (ins VR128:$src),
+         !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+         [(set RC:$dst, (Int VR128:$src))]>, VEX;
+
+let ExeDomain =3D SSEPackedSingle in {
+  def VBROADCASTSSrm  : avx_broadcast<0x18, "vbroadcastss", VR128, f32mem,
+                                      int_x86_avx_vbroadcast_ss>;
+  def VBROADCASTSSYrm : avx_broadcast<0x18, "vbroadcastss", VR256, f32mem,
+                                      int_x86_avx_vbroadcast_ss_256>;
+}
+let ExeDomain =3D SSEPackedDouble in
+def VBROADCASTSDrm  : avx_broadcast<0x19, "vbroadcastsd", VR256, f64mem,
+                                    int_x86_avx_vbroadcast_sd_256>;
 def VBROADCASTF128 : avx_broadcast<0x1A, "vbroadcastf128", VR256, f128mem,
                                    int_x86_avx_vbroadcastf128_pd_256>;
=20
+let ExeDomain =3D SSEPackedSingle in {
+  def VBROADCASTSSrr  : avx2_broadcast_reg<0x18, "vbroadcastss", VR128,
+                                           int_x86_avx2_vbroadcast_ss_ps>;
+  def VBROADCASTSSYrr : avx2_broadcast_reg<0x18, "vbroadcastss", VR256,
+                                           int_x86_avx2_vbroadcast_ss_ps_2=
56>;
+}
+let ExeDomain =3D SSEPackedDouble in
+def VBROADCASTSDrr  : avx2_broadcast_reg<0x19, "vbroadcastsd", VR256,
+                                         int_x86_avx2_vbroadcast_sd_pd_256=
>;
+
+let Predicates =3D [HasAVX2] in
+def VBROADCASTI128 : avx_broadcast<0x5A, "vbroadcasti128", VR256, i128mem,
+                                   int_x86_avx2_vbroadcasti128>;
+
+let Predicates =3D [HasAVX] in
 def : Pat<(int_x86_avx_vbroadcastf128_ps_256 addr:$src),
           (VBROADCASTF128 addr:$src)>;
=20
-def : Pat<(v8i32 (X86VBroadcast (loadi32 addr:$src))),
-          (VBROADCASTSSY addr:$src)>;
-def : Pat<(v4i64 (X86VBroadcast (loadi64 addr:$src))),
-          (VBROADCASTSD addr:$src)>;
-def : Pat<(v8f32 (X86VBroadcast (loadf32 addr:$src))),
-          (VBROADCASTSSY addr:$src)>;
-def : Pat<(v4f64 (X86VBroadcast (loadf64 addr:$src))),
-          (VBROADCASTSD addr:$src)>;
-
-def : Pat<(v4f32 (X86VBroadcast (loadf32 addr:$src))),
-          (VBROADCASTSS addr:$src)>;
-def : Pat<(v4i32 (X86VBroadcast (loadi32 addr:$src))),
-          (VBROADCASTSS addr:$src)>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // VINSERTF128 - Insert packed floating-point values
 //
+let neverHasSideEffects =3D 1, ExeDomain =3D SSEPackedSingle in {
 def VINSERTF128rr : AVXAIi8<0x18, MRMSrcReg, (outs VR256:$dst),
           (ins VR256:$src1, VR128:$src2, i8imm:$src3),
           "vinsertf128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
           []>, VEX_4V;
+let mayLoad =3D 1 in
 def VINSERTF128rm : AVXAIi8<0x18, MRMSrcMem, (outs VR256:$dst),
           (ins VR256:$src1, f128mem:$src2, i8imm:$src3),
           "vinsertf128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
           []>, VEX_4V;
-
-def : Pat<(int_x86_avx_vinsertf128_pd_256 VR256:$src1, VR128:$src2, imm:$s=
rc3),
-          (VINSERTF128rr VR256:$src1, VR128:$src2, imm:$src3)>;
-def : Pat<(int_x86_avx_vinsertf128_ps_256 VR256:$src1, VR128:$src2, imm:$s=
rc3),
-          (VINSERTF128rr VR256:$src1, VR128:$src2, imm:$src3)>;
-def : Pat<(int_x86_avx_vinsertf128_si_256 VR256:$src1, VR128:$src2, imm:$s=
rc3),
-          (VINSERTF128rr VR256:$src1, VR128:$src2, imm:$src3)>;
-
+}
+
+let Predicates =3D [HasAVX] in {
 def : Pat<(vinsertf128_insert:$ins (v8f32 VR256:$src1), (v4f32 VR128:$src2=
),
                                    (i32 imm)),
           (VINSERTF128rr VR256:$src1, VR128:$src2,
@@ -6559,11 +7324,11 @@
                                    (i32 imm)),
           (VINSERTF128rr VR256:$src1, VR128:$src2,
                          (INSERT_get_vinsertf128_imm VR256:$ins))>;
-def : Pat<(vinsertf128_insert:$ins (v8i32 VR256:$src1), (v4i32 VR128:$src2=
),
+def : Pat<(vinsertf128_insert:$ins (v4i64 VR256:$src1), (v2i64 VR128:$src2=
),
                                    (i32 imm)),
           (VINSERTF128rr VR256:$src1, VR128:$src2,
                          (INSERT_get_vinsertf128_imm VR256:$ins))>;
-def : Pat<(vinsertf128_insert:$ins (v4i64 VR256:$src1), (v2i64 VR128:$src2=
),
+def : Pat<(vinsertf128_insert:$ins (v8i32 VR256:$src1), (v4i32 VR128:$src2=
),
                                    (i32 imm)),
           (VINSERTF128rr VR256:$src1, VR128:$src2,
                          (INSERT_get_vinsertf128_imm VR256:$ins))>;
@@ -6576,18 +7341,54 @@
           (VINSERTF128rr VR256:$src1, VR128:$src2,
                          (INSERT_get_vinsertf128_imm VR256:$ins))>;
=20
+def : Pat<(vinsertf128_insert:$ins (v8f32 VR256:$src1), (loadv4f32 addr:$s=
rc2),
+                                   (i32 imm)),
+          (VINSERTF128rm VR256:$src1, addr:$src2,
+                         (INSERT_get_vinsertf128_imm VR256:$ins))>;
+def : Pat<(vinsertf128_insert:$ins (v4f64 VR256:$src1), (loadv2f64 addr:$s=
rc2),
+                                   (i32 imm)),
+          (VINSERTF128rm VR256:$src1, addr:$src2,
+                         (INSERT_get_vinsertf128_imm VR256:$ins))>;
+def : Pat<(vinsertf128_insert:$ins (v4i64 VR256:$src1), (loadv2i64 addr:$s=
rc2),
+                                   (i32 imm)),
+          (VINSERTF128rm VR256:$src1, addr:$src2,
+                         (INSERT_get_vinsertf128_imm VR256:$ins))>;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // VEXTRACTF128 - Extract packed floating-point values
 //
+let neverHasSideEffects =3D 1, ExeDomain =3D SSEPackedSingle in {
 def VEXTRACTF128rr : AVXAIi8<0x19, MRMDestReg, (outs VR128:$dst),
           (ins VR256:$src1, i8imm:$src2),
           "vextractf128\t{$src2, $src1, $dst|$dst, $src1, $src2}",
           []>, VEX;
+let mayStore =3D 1 in
 def VEXTRACTF128mr : AVXAIi8<0x19, MRMDestMem, (outs),
           (ins f128mem:$dst, VR256:$src1, i8imm:$src2),
           "vextractf128\t{$src2, $src1, $dst|$dst, $src1, $src2}",
           []>, VEX;
-
+}
+
+// Extract and store.
+let Predicates =3D [HasAVX] in {
+  def : Pat<(alignedstore (int_x86_avx_vextractf128_ps_256 VR256:$src1, im=
m:$src2), addr:$dst),
+          (VEXTRACTF128mr addr:$dst, VR256:$src1, imm:$src2)>;
+  def : Pat<(alignedstore (int_x86_avx_vextractf128_pd_256 VR256:$src1, im=
m:$src2), addr:$dst),
+          (VEXTRACTF128mr addr:$dst, VR256:$src1, imm:$src2)>;
+  def : Pat<(alignedstore (int_x86_avx_vextractf128_si_256 VR256:$src1, im=
m:$src2), addr:$dst),
+          (VEXTRACTF128mr addr:$dst, VR256:$src1, imm:$src2)>;
+
+  def : Pat<(int_x86_sse_storeu_ps addr:$dst, (int_x86_avx_vextractf128_ps=
_256 VR256:$src1, imm:$src2)),
+          (VEXTRACTF128mr addr:$dst, VR256:$src1, imm:$src2)>;
+  def : Pat<(int_x86_sse2_storeu_pd addr:$dst, (int_x86_avx_vextractf128_p=
d_256 VR256:$src1, imm:$src2)),
+          (VEXTRACTF128mr addr:$dst, VR256:$src1, imm:$src2)>;
+  def : Pat<(int_x86_sse2_storeu_dq addr:$dst, (bc_v16i8 (int_x86_avx_vext=
ractf128_si_256 VR256:$src1, imm:$src2))),
+          (VEXTRACTF128mr addr:$dst, VR256:$src1, imm:$src2)>;
+}
+
+// AVX1 patterns
+let Predicates =3D [HasAVX] in {
 def : Pat<(int_x86_avx_vextractf128_pd_256 VR256:$src1, imm:$src2),
           (VEXTRACTF128rr VR256:$src1, imm:$src2)>;
 def : Pat<(int_x86_avx_vextractf128_ps_256 VR256:$src1, imm:$src2),
@@ -6604,14 +7405,14 @@
                     (v4f64 VR256:$src1),
                     (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
 def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
+          (v2i64 (VEXTRACTF128rr
+                    (v4i64 VR256:$src1),
+                    (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
+def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
           (v4i32 (VEXTRACTF128rr
                     (v8i32 VR256:$src1),
                     (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
 def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
-          (v2i64 (VEXTRACTF128rr
-                    (v4i64 VR256:$src1),
-                    (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
-def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
           (v8i16 (VEXTRACTF128rr
                     (v16i16 VR256:$src1),
                     (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
@@ -6619,14 +7420,14 @@
           (v16i8 (VEXTRACTF128rr
                     (v32i8 VR256:$src1),
                     (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // VMASKMOV - Conditional SIMD Packed Loads and Stores
 //
 multiclass avx_movmask_rm<bits<8> opc_rm, bits<8> opc_mr, string OpcodeStr,
                           Intrinsic IntLd, Intrinsic IntLd256,
-                          Intrinsic IntSt, Intrinsic IntSt256,
-                          PatFrag pf128, PatFrag pf256> {
+                          Intrinsic IntSt, Intrinsic IntSt256> {
   def rm  : AVX8I<opc_rm, MRMSrcMem, (outs VR128:$dst),
              (ins VR128:$src1, f128mem:$src2),
              !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
@@ -6647,26 +7448,26 @@
              [(IntSt256 addr:$dst, VR256:$src1, VR256:$src2)]>, VEX_4V;
 }
=20
+let ExeDomain =3D SSEPackedSingle in
 defm VMASKMOVPS : avx_movmask_rm<0x2C, 0x2E, "vmaskmovps",
                                  int_x86_avx_maskload_ps,
                                  int_x86_avx_maskload_ps_256,
                                  int_x86_avx_maskstore_ps,
-                                 int_x86_avx_maskstore_ps_256,
-                                 memopv4f32, memopv8f32>;
+                                 int_x86_avx_maskstore_ps_256>;
+let ExeDomain =3D SSEPackedDouble in
 defm VMASKMOVPD : avx_movmask_rm<0x2D, 0x2F, "vmaskmovpd",
                                  int_x86_avx_maskload_pd,
                                  int_x86_avx_maskload_pd_256,
                                  int_x86_avx_maskstore_pd,
-                                 int_x86_avx_maskstore_pd_256,
-                                 memopv2f64, memopv4f64>;
+                                 int_x86_avx_maskstore_pd_256>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // VPERMIL - Permute Single and Double Floating-Point Values
 //
 multiclass avx_permil<bits<8> opc_rm, bits<8> opc_rmi, string OpcodeStr,
                       RegisterClass RC, X86MemOperand x86memop_f,
-                      X86MemOperand x86memop_i, PatFrag f_frag, PatFrag i_=
frag,
-                      Intrinsic IntVar, Intrinsic IntImm> {
+                      X86MemOperand x86memop_i, PatFrag i_frag,
+                      Intrinsic IntVar, ValueType vt> {
   def rr  : AVX8I<opc_rm, MRMSrcReg, (outs RC:$dst),
              (ins RC:$src1, RC:$src2),
              !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
@@ -6674,85 +7475,97 @@
   def rm  : AVX8I<opc_rm, MRMSrcMem, (outs RC:$dst),
              (ins RC:$src1, x86memop_i:$src2),
              !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
-             [(set RC:$dst, (IntVar RC:$src1, (i_frag addr:$src2)))]>, VEX=
_4V;
+             [(set RC:$dst, (IntVar RC:$src1,
+                             (bitconvert (i_frag addr:$src2))))]>, VEX_4V;
=20
   def ri  : AVXAIi8<opc_rmi, MRMSrcReg, (outs RC:$dst),
              (ins RC:$src1, i8imm:$src2),
              !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
-             [(set RC:$dst, (IntImm RC:$src1, imm:$src2))]>, VEX;
+             [(set RC:$dst, (vt (X86VPermilp RC:$src1, (i8 imm:$src2))))]>=
, VEX;
   def mi  : AVXAIi8<opc_rmi, MRMSrcMem, (outs RC:$dst),
              (ins x86memop_f:$src1, i8imm:$src2),
              !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
-             [(set RC:$dst, (IntImm (f_frag addr:$src1), imm:$src2))]>, VE=
X;
-}
-
-defm VPERMILPS  : avx_permil<0x0C, 0x04, "vpermilps", VR128, f128mem, i128=
mem,
-                             memopv4f32, memopv4i32,
-                             int_x86_avx_vpermilvar_ps,
-                             int_x86_avx_vpermil_ps>;
-defm VPERMILPSY : avx_permil<0x0C, 0x04, "vpermilps", VR256, f256mem, i256=
mem,
-                             memopv8f32, memopv8i32,
-                             int_x86_avx_vpermilvar_ps_256,
-                             int_x86_avx_vpermil_ps_256>;
-defm VPERMILPD  : avx_permil<0x0D, 0x05, "vpermilpd", VR128, f128mem, i128=
mem,
-                             memopv2f64, memopv2i64,
-                             int_x86_avx_vpermilvar_pd,
-                             int_x86_avx_vpermil_pd>;
-defm VPERMILPDY : avx_permil<0x0D, 0x05, "vpermilpd", VR256, f256mem, i256=
mem,
-                             memopv4f64, memopv4i64,
-                             int_x86_avx_vpermilvar_pd_256,
-                             int_x86_avx_vpermil_pd_256>;
-
-def : Pat<(v8f32 (X86VPermilpsy VR256:$src1, (i8 imm:$imm))),
+             [(set RC:$dst,
+               (vt (X86VPermilp (memop addr:$src1), (i8 imm:$src2))))]>, V=
EX;
+}
+
+let ExeDomain =3D SSEPackedSingle in {
+  defm VPERMILPS  : avx_permil<0x0C, 0x04, "vpermilps", VR128, f128mem, i1=
28mem,
+                               memopv2i64, int_x86_avx_vpermilvar_ps, v4f3=
2>;
+  defm VPERMILPSY : avx_permil<0x0C, 0x04, "vpermilps", VR256, f256mem, i2=
56mem,
+                              memopv4i64, int_x86_avx_vpermilvar_ps_256, v=
8f32>;
+}
+let ExeDomain =3D SSEPackedDouble in {
+  defm VPERMILPD  : avx_permil<0x0D, 0x05, "vpermilpd", VR128, f128mem, i1=
28mem,
+                               memopv2i64, int_x86_avx_vpermilvar_pd, v2f6=
4>;
+  defm VPERMILPDY : avx_permil<0x0D, 0x05, "vpermilpd", VR256, f256mem, i2=
56mem,
+                              memopv4i64, int_x86_avx_vpermilvar_pd_256, v=
4f64>;
+}
+
+let Predicates =3D [HasAVX] in {
+def : Pat<(v8i32 (X86VPermilp VR256:$src1, (i8 imm:$imm))),
           (VPERMILPSYri VR256:$src1, imm:$imm)>;
-def : Pat<(v4f64 (X86VPermilpdy VR256:$src1, (i8 imm:$imm))),
+def : Pat<(v4i64 (X86VPermilp VR256:$src1, (i8 imm:$imm))),
           (VPERMILPDYri VR256:$src1, imm:$imm)>;
-def : Pat<(v8i32 (X86VPermilpsy VR256:$src1, (i8 imm:$imm))),
-          (VPERMILPSYri VR256:$src1, imm:$imm)>;
-def : Pat<(v4i64 (X86VPermilpdy VR256:$src1, (i8 imm:$imm))),
-          (VPERMILPDYri VR256:$src1, imm:$imm)>;
+def : Pat<(v8i32 (X86VPermilp (bc_v8i32 (memopv4i64 addr:$src1)),
+                               (i8 imm:$imm))),
+          (VPERMILPSYmi addr:$src1, imm:$imm)>;
+def : Pat<(v4i64 (X86VPermilp (memopv4i64 addr:$src1), (i8 imm:$imm))),
+          (VPERMILPDYmi addr:$src1, imm:$imm)>;
+
+def : Pat<(v2i64 (X86VPermilp VR128:$src1, (i8 imm:$imm))),
+          (VPERMILPDri VR128:$src1, imm:$imm)>;
+def : Pat<(v2i64 (X86VPermilp (memopv2i64 addr:$src1), (i8 imm:$imm))),
+          (VPERMILPDmi addr:$src1, imm:$imm)>;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // VPERM2F128 - Permute Floating-Point Values in 128-bit chunks
 //
+let ExeDomain =3D SSEPackedSingle in {
 def VPERM2F128rr : AVXAIi8<0x06, MRMSrcReg, (outs VR256:$dst),
           (ins VR256:$src1, VR256:$src2, i8imm:$src3),
           "vperm2f128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src=
3}",
-          []>, VEX_4V;
+          [(set VR256:$dst, (v8f32 (X86VPerm2x128 VR256:$src1, VR256:$src2,
+                              (i8 imm:$src3))))]>, VEX_4V;
 def VPERM2F128rm : AVXAIi8<0x06, MRMSrcMem, (outs VR256:$dst),
           (ins VR256:$src1, f256mem:$src2, i8imm:$src3),
           "vperm2f128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src=
3}",
-          []>, VEX_4V;
-
-def : Pat<(int_x86_avx_vperm2f128_ps_256 VR256:$src1, VR256:$src2, imm:$sr=
c3),
-          (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$src3)>;
-def : Pat<(int_x86_avx_vperm2f128_pd_256 VR256:$src1, VR256:$src2, imm:$sr=
c3),
-          (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$src3)>;
-def : Pat<(int_x86_avx_vperm2f128_si_256 VR256:$src1, VR256:$src2, imm:$sr=
c3),
-          (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$src3)>;
-
-def : Pat<(int_x86_avx_vperm2f128_ps_256
-                  VR256:$src1, (memopv8f32 addr:$src2), imm:$src3),
-          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$src3)>;
-def : Pat<(int_x86_avx_vperm2f128_pd_256
-                  VR256:$src1, (memopv4f64 addr:$src2), imm:$src3),
-          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$src3)>;
-def : Pat<(int_x86_avx_vperm2f128_si_256
-                  VR256:$src1, (memopv8i32 addr:$src2), imm:$src3),
-          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$src3)>;
-
-def : Pat<(v8f32 (X86VPerm2f128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          [(set VR256:$dst, (X86VPerm2x128 VR256:$src1, (memopv8f32 addr:$=
src2),
+                             (i8 imm:$src3)))]>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX] in {
+def : Pat<(v8i32 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
           (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$imm)>;
-def : Pat<(v8i32 (X86VPerm2f128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+def : Pat<(v4i64 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
           (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$imm)>;
-def : Pat<(v4i64 (X86VPerm2f128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+def : Pat<(v4f64 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
           (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$imm)>;
-def : Pat<(v4f64 (X86VPerm2f128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+def : Pat<(v32i8 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
           (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$imm)>;
-def : Pat<(v32i8 (X86VPerm2f128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+def : Pat<(v16i16 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
           (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$imm)>;
-def : Pat<(v16i16 (X86VPerm2f128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
-          (VPERM2F128rr VR256:$src1, VR256:$src2, imm:$imm)>;
+
+def : Pat<(v8f32 (X86VPerm2x128 VR256:$src1,
+                  (memopv8f32 addr:$src2), (i8 imm:$imm))),
+          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$imm)>;
+def : Pat<(v8i32 (X86VPerm2x128 VR256:$src1,
+                  (bc_v8i32 (memopv4i64 addr:$src2)), (i8 imm:$imm))),
+          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$imm)>;
+def : Pat<(v4i64 (X86VPerm2x128 VR256:$src1,
+                  (memopv4i64 addr:$src2), (i8 imm:$imm))),
+          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$imm)>;
+def : Pat<(v4f64 (X86VPerm2x128 VR256:$src1,
+                  (memopv4f64 addr:$src2), (i8 imm:$imm))),
+          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$imm)>;
+def : Pat<(v32i8 (X86VPerm2x128 VR256:$src1,
+                  (bc_v32i8 (memopv4i64 addr:$src2)), (i8 imm:$imm))),
+          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$imm)>;
+def : Pat<(v16i16 (X86VPerm2x128 VR256:$src1,
+                  (bc_v16i16 (memopv4i64 addr:$src2)), (i8 imm:$imm))),
+          (VPERM2F128rm VR256:$src1, addr:$src2, imm:$imm)>;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // VZERO - Zero YMM registers
@@ -6770,30 +7583,362 @@
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Half precision conversion instructions
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+multiclass f16c_ph2ps<RegisterClass RC, X86MemOperand x86memop, Intrinsic =
Int> {
+let Predicates =3D [HasAVX, HasF16C] in {
+  def rr : I<0x13, MRMSrcReg, (outs RC:$dst), (ins VR128:$src),
+             "vcvtph2ps\t{$src, $dst|$dst, $src}",
+             [(set RC:$dst, (Int VR128:$src))]>,
+             T8, OpSize, VEX;
+  let neverHasSideEffects =3D 1, mayLoad =3D 1 in
+  def rm : I<0x13, MRMSrcMem, (outs RC:$dst), (ins x86memop:$src),
+             "vcvtph2ps\t{$src, $dst|$dst, $src}", []>, T8, OpSize, VEX;
+}
+}
+
+multiclass f16c_ps2ph<RegisterClass RC, X86MemOperand x86memop, Intrinsic =
Int> {
+let Predicates =3D [HasAVX, HasF16C] in {
+  def rr : Ii8<0x1D, MRMDestReg, (outs VR128:$dst),
+               (ins RC:$src1, i32i8imm:$src2),
+               "vcvtps2ph\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+               [(set VR128:$dst, (Int RC:$src1, imm:$src2))]>,
+               TA, OpSize, VEX;
+  let neverHasSideEffects =3D 1, mayLoad =3D 1 in
+  def mr : Ii8<0x1D, MRMDestMem, (outs x86memop:$dst),
+               (ins RC:$src1, i32i8imm:$src2),
+               "vcvtps2ph\t{$src2, $src1, $dst|$dst, $src1, $src2}", []>,
+               TA, OpSize, VEX;
+}
+}
+
+defm VCVTPH2PS  : f16c_ph2ps<VR128, f64mem, int_x86_vcvtph2ps_128>;
+defm VCVTPH2PSY : f16c_ph2ps<VR256, f128mem, int_x86_vcvtph2ps_256>;
+defm VCVTPS2PH  : f16c_ps2ph<VR128, f64mem, int_x86_vcvtps2ph_128>;
+defm VCVTPS2PHY : f16c_ps2ph<VR256, f128mem, int_x86_vcvtps2ph_256>;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// AVX2 Instructions
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+/// AVX2_binop_rmi_int - AVX2 binary operator with 8-bit immediate
+multiclass AVX2_binop_rmi_int<bits<8> opc, string OpcodeStr,
+                 Intrinsic IntId, RegisterClass RC, PatFrag memop_frag,
+                 X86MemOperand x86memop> {
+  let isCommutable =3D 1 in
+  def rri : AVX2AIi8<opc, MRMSrcReg, (outs RC:$dst),
+        (ins RC:$src1, RC:$src2, u32u8imm:$src3),
+        !strconcat(OpcodeStr,
+            "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+        [(set RC:$dst, (IntId RC:$src1, RC:$src2, imm:$src3))]>,
+        VEX_4V;
+  def rmi : AVX2AIi8<opc, MRMSrcMem, (outs RC:$dst),
+        (ins RC:$src1, x86memop:$src2, u32u8imm:$src3),
+        !strconcat(OpcodeStr,
+            "\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src3}"),
+        [(set RC:$dst,
+          (IntId RC:$src1,
+           (bitconvert (memop_frag addr:$src2)), imm:$src3))]>,
+        VEX_4V;
+}
+
+let isCommutable =3D 0 in {
+defm VPBLENDD : AVX2_binop_rmi_int<0x02, "vpblendd", int_x86_avx2_pblendd_=
128,
+                                   VR128, memopv2i64, i128mem>;
+defm VPBLENDDY : AVX2_binop_rmi_int<0x02, "vpblendd", int_x86_avx2_pblendd=
_256,
+                                    VR256, memopv4i64, i256mem>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// VPBROADCAST - Load from memory and broadcast to all elements of the
+//               destination operand
 //
-let Predicates =3D [HasAVX, HasF16C] in {
-  def VCVTPH2PSrm : I<0x13, MRMSrcMem, (outs VR128:$dst), (ins f64mem:$src=
),
-                     "vcvtph2ps\t{$src, $dst|$dst, $src}", []>, T8, OpSize=
, VEX;
-  def VCVTPH2PSrr : I<0x13, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
-                     "vcvtph2ps\t{$src, $dst|$dst, $src}", []>, T8, OpSize=
, VEX;
-  def VCVTPH2PSYrm : I<0x13, MRMSrcMem, (outs VR256:$dst), (ins f128mem:$s=
rc),
-                     "vcvtph2ps\t{$src, $dst|$dst, $src}", []>, T8, OpSize=
, VEX;
-  def VCVTPH2PSYrr : I<0x13, MRMSrcReg, (outs VR256:$dst), (ins VR128:$src=
),
-                     "vcvtph2ps\t{$src, $dst|$dst, $src}", []>, T8, OpSize=
, VEX;
-  def VCVTPS2PHmr : Ii8<0x1D, MRMDestMem, (outs f64mem:$dst),
-                      (ins VR128:$src1, i32i8imm:$src2),
-                      "vcvtps2ph\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
, []>,
-                      TA, OpSize, VEX;
-  def VCVTPS2PHrr : Ii8<0x1D, MRMDestReg, (outs VR128:$dst),
-                      (ins VR128:$src1, i32i8imm:$src2),
-                      "vcvtps2ph\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
, []>,
-                      TA, OpSize, VEX;
-  def VCVTPS2PHYmr : Ii8<0x1D, MRMDestMem, (outs f128mem:$dst),
-                      (ins VR256:$src1, i32i8imm:$src2),
-                      "vcvtps2ph\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
, []>,
-                      TA, OpSize, VEX;
-  def VCVTPS2PHYrr : Ii8<0x1D, MRMDestReg, (outs VR128:$dst),
-                      (ins VR256:$src1, i32i8imm:$src2),
-                      "vcvtps2ph\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
, []>,
-                      TA, OpSize, VEX;
-}
+multiclass avx2_broadcast<bits<8> opc, string OpcodeStr,
+                          X86MemOperand x86memop, PatFrag ld_frag,
+                          Intrinsic Int128, Intrinsic Int256> {
+  def rr : AVX28I<opc, MRMSrcReg, (outs VR128:$dst), (ins VR128:$src),
+                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                  [(set VR128:$dst, (Int128 VR128:$src))]>, VEX;
+  def rm : AVX28I<opc, MRMSrcMem, (outs VR128:$dst), (ins x86memop:$src),
+                  !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                  [(set VR128:$dst,
+                    (Int128 (scalar_to_vector (ld_frag addr:$src))))]>, VE=
X;
+  def Yrr : AVX28I<opc, MRMSrcReg, (outs VR256:$dst), (ins VR128:$src),
+                   !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                   [(set VR256:$dst, (Int256 VR128:$src))]>, VEX;
+  def Yrm : AVX28I<opc, MRMSrcMem, (outs VR256:$dst), (ins x86memop:$src),
+                   !strconcat(OpcodeStr, "\t{$src, $dst|$dst, $src}"),
+                   [(set VR256:$dst,
+                    (Int256 (scalar_to_vector (ld_frag addr:$src))))]>, VE=
X;
+}
+
+defm VPBROADCASTB  : avx2_broadcast<0x78, "vpbroadcastb", i8mem, loadi8,
+                                    int_x86_avx2_pbroadcastb_128,
+                                    int_x86_avx2_pbroadcastb_256>;
+defm VPBROADCASTW  : avx2_broadcast<0x79, "vpbroadcastw", i16mem, loadi16,
+                                    int_x86_avx2_pbroadcastw_128,
+                                    int_x86_avx2_pbroadcastw_256>;
+defm VPBROADCASTD  : avx2_broadcast<0x58, "vpbroadcastd", i32mem, loadi32,
+                                    int_x86_avx2_pbroadcastd_128,
+                                    int_x86_avx2_pbroadcastd_256>;
+defm VPBROADCASTQ  : avx2_broadcast<0x59, "vpbroadcastq", i64mem, loadi64,
+                                    int_x86_avx2_pbroadcastq_128,
+                                    int_x86_avx2_pbroadcastq_256>;
+
+let Predicates =3D [HasAVX2] in {
+  def : Pat<(v16i8 (X86VBroadcast (loadi8 addr:$src))),
+          (VPBROADCASTBrm addr:$src)>;
+  def : Pat<(v32i8 (X86VBroadcast (loadi8 addr:$src))),
+          (VPBROADCASTBYrm addr:$src)>;
+  def : Pat<(v8i16 (X86VBroadcast (loadi16 addr:$src))),
+          (VPBROADCASTWrm addr:$src)>;
+  def : Pat<(v16i16 (X86VBroadcast (loadi16 addr:$src))),
+          (VPBROADCASTWYrm addr:$src)>;
+  def : Pat<(v4i32 (X86VBroadcast (loadi32 addr:$src))),
+          (VPBROADCASTDrm addr:$src)>;
+  def : Pat<(v8i32 (X86VBroadcast (loadi32 addr:$src))),
+          (VPBROADCASTDYrm addr:$src)>;
+  def : Pat<(v2i64 (X86VBroadcast (loadi64 addr:$src))),
+          (VPBROADCASTQrm addr:$src)>;
+  def : Pat<(v4i64 (X86VBroadcast (loadi64 addr:$src))),
+          (VPBROADCASTQYrm addr:$src)>;
+}
+
+// AVX1 broadcast patterns
+let Predicates =3D [HasAVX] in {
+def : Pat<(v8i32 (X86VBroadcast (loadi32 addr:$src))),
+          (VBROADCASTSSYrm addr:$src)>;
+def : Pat<(v4i64 (X86VBroadcast (loadi64 addr:$src))),
+          (VBROADCASTSDrm addr:$src)>;
+def : Pat<(v8f32 (X86VBroadcast (loadf32 addr:$src))),
+          (VBROADCASTSSYrm addr:$src)>;
+def : Pat<(v4f64 (X86VBroadcast (loadf64 addr:$src))),
+          (VBROADCASTSDrm addr:$src)>;
+
+def : Pat<(v4f32 (X86VBroadcast (loadf32 addr:$src))),
+          (VBROADCASTSSrm addr:$src)>;
+def : Pat<(v4i32 (X86VBroadcast (loadi32 addr:$src))),
+          (VBROADCASTSSrm addr:$src)>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// VPERM - Permute instructions
+//
+
+multiclass avx2_perm<bits<8> opc, string OpcodeStr, PatFrag mem_frag,
+                     Intrinsic Int> {
+  def Yrr : AVX28I<opc, MRMSrcReg, (outs VR256:$dst),
+                   (ins VR256:$src1, VR256:$src2),
+                   !strconcat(OpcodeStr,
+                       "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+                   [(set VR256:$dst, (Int VR256:$src1, VR256:$src2))]>, VE=
X_4V;
+  def Yrm : AVX28I<opc, MRMSrcMem, (outs VR256:$dst),
+                   (ins VR256:$src1, i256mem:$src2),
+                   !strconcat(OpcodeStr,
+                       "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+                   [(set VR256:$dst, (Int VR256:$src1,
+                                      (bitconvert (mem_frag addr:$src2))))=
]>,
+                   VEX_4V;
+}
+
+defm VPERMD : avx2_perm<0x36, "vpermd", memopv4i64, int_x86_avx2_permd>;
+let ExeDomain =3D SSEPackedSingle in
+defm VPERMPS : avx2_perm<0x16, "vpermps", memopv8f32, int_x86_avx2_permps>;
+
+multiclass avx2_perm_imm<bits<8> opc, string OpcodeStr, PatFrag mem_frag,
+                         Intrinsic Int> {
+  def Yrr : AVX2AIi8<opc, MRMSrcReg, (outs VR256:$dst),
+                     (ins VR256:$src1, i8imm:$src2),
+                     !strconcat(OpcodeStr,
+                         "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+                     [(set VR256:$dst, (Int VR256:$src1, imm:$src2))]>, VE=
X;
+  def Yrm : AVX2AIi8<opc, MRMSrcMem, (outs VR256:$dst),
+                     (ins i256mem:$src1, i8imm:$src2),
+                     !strconcat(OpcodeStr,
+                         "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),
+                     [(set VR256:$dst, (Int (mem_frag addr:$src1), imm:$sr=
c2))]>,
+                     VEX;
+}
+
+defm VPERMQ : avx2_perm_imm<0x00, "vpermq", memopv4i64, int_x86_avx2_permq=
>,
+                            VEX_W;
+let ExeDomain =3D SSEPackedDouble in
+defm VPERMPD : avx2_perm_imm<0x01, "vpermpd", memopv4f64, int_x86_avx2_per=
mpd>,
+                             VEX_W;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// VPERM2I128 - Permute Floating-Point Values in 128-bit chunks
+//
+let AddedComplexity =3D 1 in {
+def VPERM2I128rr : AVX2AIi8<0x46, MRMSrcReg, (outs VR256:$dst),
+          (ins VR256:$src1, VR256:$src2, i8imm:$src3),
+          "vperm2i128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src=
3}",
+          [(set VR256:$dst, (v4i64 (X86VPerm2x128 VR256:$src1, VR256:$src2,
+                            (i8 imm:$src3))))]>, VEX_4V;
+def VPERM2I128rm : AVX2AIi8<0x46, MRMSrcMem, (outs VR256:$dst),
+          (ins VR256:$src1, f256mem:$src2, i8imm:$src3),
+          "vperm2i128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $src=
3}",
+          [(set VR256:$dst, (X86VPerm2x128 VR256:$src1, (memopv4i64 addr:$=
src2),
+                             (i8 imm:$src3)))]>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2], AddedComplexity =3D 1 in {
+def : Pat<(v8i32 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          (VPERM2I128rr VR256:$src1, VR256:$src2, imm:$imm)>;
+def : Pat<(v32i8 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          (VPERM2I128rr VR256:$src1, VR256:$src2, imm:$imm)>;
+def : Pat<(v16i16 (X86VPerm2x128 VR256:$src1, VR256:$src2, (i8 imm:$imm))),
+          (VPERM2I128rr VR256:$src1, VR256:$src2, imm:$imm)>;
+
+def : Pat<(v32i8 (X86VPerm2x128 VR256:$src1, (bc_v32i8 (memopv4i64 addr:$s=
rc2)),
+                  (i8 imm:$imm))),
+          (VPERM2I128rm VR256:$src1, addr:$src2, imm:$imm)>;
+def : Pat<(v16i16 (X86VPerm2x128 VR256:$src1,
+                   (bc_v16i16 (memopv4i64 addr:$src2)), (i8 imm:$imm))),
+          (VPERM2I128rm VR256:$src1, addr:$src2, imm:$imm)>;
+def : Pat<(v8i32 (X86VPerm2x128 VR256:$src1, (bc_v8i32 (memopv4i64 addr:$s=
rc2)),
+                  (i8 imm:$imm))),
+          (VPERM2I128rm VR256:$src1, addr:$src2, imm:$imm)>;
+}
+
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// VINSERTI128 - Insert packed integer values
+//
+let neverHasSideEffects =3D 1 in {
+def VINSERTI128rr : AVX2AIi8<0x38, MRMSrcReg, (outs VR256:$dst),
+          (ins VR256:$src1, VR128:$src2, i8imm:$src3),
+          "vinserti128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
+          []>,
+          VEX_4V;
+def VINSERTI128rm : AVX2AIi8<0x38, MRMSrcMem, (outs VR256:$dst),
+          (ins VR256:$src1, i128mem:$src2, i8imm:$src3),
+          "vinserti128\t{$src3, $src2, $src1, $dst|$dst, $src1, $src2, $sr=
c3}",
+          []>, VEX_4V;
+}
+
+let Predicates =3D [HasAVX2], AddedComplexity =3D 1 in {
+def : Pat<(vinsertf128_insert:$ins (v4i64 VR256:$src1), (v2i64 VR128:$src2=
),
+                                   (i32 imm)),
+          (VINSERTI128rr VR256:$src1, VR128:$src2,
+                         (INSERT_get_vinsertf128_imm VR256:$ins))>;
+def : Pat<(vinsertf128_insert:$ins (v8i32 VR256:$src1), (v4i32 VR128:$src2=
),
+                                   (i32 imm)),
+          (VINSERTI128rr VR256:$src1, VR128:$src2,
+                         (INSERT_get_vinsertf128_imm VR256:$ins))>;
+def : Pat<(vinsertf128_insert:$ins (v32i8 VR256:$src1), (v16i8 VR128:$src2=
),
+                                   (i32 imm)),
+          (VINSERTI128rr VR256:$src1, VR128:$src2,
+                         (INSERT_get_vinsertf128_imm VR256:$ins))>;
+def : Pat<(vinsertf128_insert:$ins (v16i16 VR256:$src1), (v8i16 VR128:$src=
2),
+                                   (i32 imm)),
+          (VINSERTI128rr VR256:$src1, VR128:$src2,
+                         (INSERT_get_vinsertf128_imm VR256:$ins))>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// VEXTRACTI128 - Extract packed integer values
+//
+def VEXTRACTI128rr : AVX2AIi8<0x39, MRMDestReg, (outs VR128:$dst),
+          (ins VR256:$src1, i8imm:$src2),
+          "vextracti128\t{$src2, $src1, $dst|$dst, $src1, $src2}",
+          [(set VR128:$dst,
+            (int_x86_avx2_vextracti128 VR256:$src1, imm:$src2))]>,
+          VEX;
+let neverHasSideEffects =3D 1, mayStore =3D 1 in
+def VEXTRACTI128mr : AVX2AIi8<0x39, MRMDestMem, (outs),
+          (ins i128mem:$dst, VR256:$src1, i8imm:$src2),
+          "vextracti128\t{$src2, $src1, $dst|$dst, $src1, $src2}", []>, VE=
X;
+
+let Predicates =3D [HasAVX2], AddedComplexity =3D 1 in {
+def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
+          (v2i64 (VEXTRACTI128rr
+                    (v4i64 VR256:$src1),
+                    (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
+def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
+          (v4i32 (VEXTRACTI128rr
+                    (v8i32 VR256:$src1),
+                    (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
+def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
+          (v8i16 (VEXTRACTI128rr
+                    (v16i16 VR256:$src1),
+                    (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
+def : Pat<(vextractf128_extract:$ext VR256:$src1, (i32 imm)),
+          (v16i8 (VEXTRACTI128rr
+                    (v32i8 VR256:$src1),
+                    (EXTRACT_get_vextractf128_imm VR128:$ext)))>;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// VPMASKMOV - Conditional SIMD Integer Packed Loads and Stores
+//
+multiclass avx2_pmovmask<string OpcodeStr,
+                         Intrinsic IntLd128, Intrinsic IntLd256,
+                         Intrinsic IntSt128, Intrinsic IntSt256> {
+  def rm  : AVX28I<0x8c, MRMSrcMem, (outs VR128:$dst),
+             (ins VR128:$src1, i128mem:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(set VR128:$dst, (IntLd128 addr:$src2, VR128:$src1))]>, VEX_=
4V;
+  def Yrm : AVX28I<0x8c, MRMSrcMem, (outs VR256:$dst),
+             (ins VR256:$src1, i256mem:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(set VR256:$dst, (IntLd256 addr:$src2, VR256:$src1))]>, VEX_=
4V;
+  def mr  : AVX28I<0x8e, MRMDestMem, (outs),
+             (ins i128mem:$dst, VR128:$src1, VR128:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(IntSt128 addr:$dst, VR128:$src1, VR128:$src2)]>, VEX_4V;
+  def Ymr : AVX28I<0x8e, MRMDestMem, (outs),
+             (ins i256mem:$dst, VR256:$src1, VR256:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(IntSt256 addr:$dst, VR256:$src1, VR256:$src2)]>, VEX_4V;
+}
+
+defm VPMASKMOVD : avx2_pmovmask<"vpmaskmovd",
+                                int_x86_avx2_maskload_d,
+                                int_x86_avx2_maskload_d_256,
+                                int_x86_avx2_maskstore_d,
+                                int_x86_avx2_maskstore_d_256>;
+defm VPMASKMOVQ : avx2_pmovmask<"vpmaskmovq",
+                                int_x86_avx2_maskload_q,
+                                int_x86_avx2_maskload_q_256,
+                                int_x86_avx2_maskstore_q,
+                                int_x86_avx2_maskstore_q_256>, VEX_W;
+
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Variable Bit Shifts
+//
+multiclass avx2_var_shift<bits<8> opc, string OpcodeStr, SDNode OpNode,
+                          ValueType vt128, ValueType vt256> {
+  def rr  : AVX28I<opc, MRMSrcReg, (outs VR128:$dst),
+             (ins VR128:$src1, VR128:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(set VR128:$dst,
+               (vt128 (OpNode VR128:$src1, (vt128 VR128:$src2))))]>,
+             VEX_4V;
+  def rm  : AVX28I<opc, MRMSrcMem, (outs VR128:$dst),
+             (ins VR128:$src1, i128mem:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(set VR128:$dst,
+               (vt128 (OpNode VR128:$src1,
+                       (vt128 (bitconvert (memopv2i64 addr:$src2))))))]>,
+             VEX_4V;
+  def Yrr : AVX28I<opc, MRMSrcReg, (outs VR256:$dst),
+             (ins VR256:$src1, VR256:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(set VR256:$dst,
+               (vt256 (OpNode VR256:$src1, (vt256 VR256:$src2))))]>,
+             VEX_4V;
+  def Yrm : AVX28I<opc, MRMSrcMem, (outs VR256:$dst),
+             (ins VR256:$src1, i256mem:$src2),
+             !strconcat(OpcodeStr, "\t{$src2, $src1, $dst|$dst, $src1, $sr=
c2}"),
+             [(set VR256:$dst,
+               (vt256 (OpNode VR256:$src1,
+                       (vt256 (bitconvert (memopv4i64 addr:$src2))))))]>,
+             VEX_4V;
+}
+
+defm VPSLLVD : avx2_var_shift<0x47, "vpsllvd", shl, v4i32, v8i32>;
+defm VPSLLVQ : avx2_var_shift<0x47, "vpsllvq", shl, v2i64, v4i64>, VEX_W;
+defm VPSRLVD : avx2_var_shift<0x45, "vpsrlvd", srl, v4i32, v8i32>;
+defm VPSRLVQ : avx2_var_shift<0x45, "vpsrlvq", srl, v2i64, v4i64>, VEX_W;
+defm VPSRAVD : avx2_var_shift<0x46, "vpsravd", sra, v4i32, v8i32>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strShiftRotate.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrShiftRotate.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrShiftRotate.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86InstrShiftRotate.td - Shift and Rotate Instrs ----*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86InstrShiftRotate.td - Shift and Rotate Instrs ---*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the shift and rotate instructions.
@@ -19,44 +19,46 @@
 let Uses =3D [CL] in {
 def SHL8rCL  : I<0xD2, MRM4r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "shl{b}\t{%cl, $dst|$dst, CL}",
-                 [(set GR8:$dst, (shl GR8:$src1, CL))]>;
+                 [(set GR8:$dst, (shl GR8:$src1, CL))], IIC_SR>;
 def SHL16rCL : I<0xD3, MRM4r, (outs GR16:$dst), (ins GR16:$src1),
                  "shl{w}\t{%cl, $dst|$dst, CL}",
-                 [(set GR16:$dst, (shl GR16:$src1, CL))]>, OpSize;
+                 [(set GR16:$dst, (shl GR16:$src1, CL))], IIC_SR>, OpSize;
 def SHL32rCL : I<0xD3, MRM4r, (outs GR32:$dst), (ins GR32:$src1),
                  "shl{l}\t{%cl, $dst|$dst, CL}",
-                 [(set GR32:$dst, (shl GR32:$src1, CL))]>;
+                 [(set GR32:$dst, (shl GR32:$src1, CL))], IIC_SR>;
 def SHL64rCL : RI<0xD3, MRM4r, (outs GR64:$dst), (ins GR64:$src1),
-                  "shl{q}\t{%cl, $dst|$dst, %CL}",
-                  [(set GR64:$dst, (shl GR64:$src1, CL))]>;
+                  "shl{q}\t{%cl, $dst|$dst, CL}",
+                  [(set GR64:$dst, (shl GR64:$src1, CL))], IIC_SR>;
 } // Uses =3D [CL]
=20
 def SHL8ri   : Ii8<0xC0, MRM4r, (outs GR8 :$dst), (ins GR8 :$src1, i8imm:$=
src2),
                    "shl{b}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR8:$dst, (shl GR8:$src1, (i8 imm:$src2)))]>;
+                   [(set GR8:$dst, (shl GR8:$src1, (i8 imm:$src2)))], IIC_=
SR>;
                   =20
 let isConvertibleToThreeAddress =3D 1 in {   // Can transform into LEA.
 def SHL16ri  : Ii8<0xC1, MRM4r, (outs GR16:$dst), (ins GR16:$src1, i8imm:$=
src2),
                    "shl{w}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR16:$dst, (shl GR16:$src1, (i8 imm:$src2)))]>, O=
pSize;
+                   [(set GR16:$dst, (shl GR16:$src1, (i8 imm:$src2)))], II=
C_SR>,
+                   OpSize;
 def SHL32ri  : Ii8<0xC1, MRM4r, (outs GR32:$dst), (ins GR32:$src1, i8imm:$=
src2),
                    "shl{l}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR32:$dst, (shl GR32:$src1, (i8 imm:$src2)))]>;
+                   [(set GR32:$dst, (shl GR32:$src1, (i8 imm:$src2)))], II=
C_SR>;
 def SHL64ri  : RIi8<0xC1, MRM4r, (outs GR64:$dst),=20
                     (ins GR64:$src1, i8imm:$src2),
                     "shl{q}\t{$src2, $dst|$dst, $src2}",
-                    [(set GR64:$dst, (shl GR64:$src1, (i8 imm:$src2)))]>;
+                    [(set GR64:$dst, (shl GR64:$src1, (i8 imm:$src2)))],
+                    IIC_SR>;
=20
 // NOTE: We don't include patterns for shifts of a register by one, because
 // 'add reg,reg' is cheaper (and we have a Pat pattern for shift-by-one).
 def SHL8r1   : I<0xD0, MRM4r, (outs GR8:$dst), (ins GR8:$src1),
-                 "shl{b}\t$dst", []>;
+                 "shl{b}\t$dst", [], IIC_SR>;
 def SHL16r1  : I<0xD1, MRM4r, (outs GR16:$dst), (ins GR16:$src1),
-                 "shl{w}\t$dst", []>, OpSize;
+                 "shl{w}\t$dst", [], IIC_SR>, OpSize;
 def SHL32r1  : I<0xD1, MRM4r, (outs GR32:$dst), (ins GR32:$src1),
-                 "shl{l}\t$dst", []>;
+                 "shl{l}\t$dst", [], IIC_SR>;
 def SHL64r1  : RI<0xD1, MRM4r, (outs GR64:$dst), (ins GR64:$src1),
-                 "shl{q}\t$dst", []>;
+                 "shl{q}\t$dst", [], IIC_SR>;
 } // isConvertibleToThreeAddress =3D 1
 } // Constraints =3D "$src =3D $dst"=20
=20
@@ -66,223 +68,266 @@
 let Uses =3D [CL] in {
 def SHL8mCL  : I<0xD2, MRM4m, (outs), (ins i8mem :$dst),
                  "shl{b}\t{%cl, $dst|$dst, CL}",
-                 [(store (shl (loadi8 addr:$dst), CL), addr:$dst)]>;
+                 [(store (shl (loadi8 addr:$dst), CL), addr:$dst)], IIC_SR=
>;
 def SHL16mCL : I<0xD3, MRM4m, (outs), (ins i16mem:$dst),
                  "shl{w}\t{%cl, $dst|$dst, CL}",
-                 [(store (shl (loadi16 addr:$dst), CL), addr:$dst)]>, OpSi=
ze;
+                 [(store (shl (loadi16 addr:$dst), CL), addr:$dst)], IIC_S=
R>,
+                 OpSize;
 def SHL32mCL : I<0xD3, MRM4m, (outs), (ins i32mem:$dst),
                  "shl{l}\t{%cl, $dst|$dst, CL}",
-                 [(store (shl (loadi32 addr:$dst), CL), addr:$dst)]>;
+                 [(store (shl (loadi32 addr:$dst), CL), addr:$dst)], IIC_S=
R>;
 def SHL64mCL : RI<0xD3, MRM4m, (outs), (ins i64mem:$dst),
-                  "shl{q}\t{%cl, $dst|$dst, %CL}",
-                  [(store (shl (loadi64 addr:$dst), CL), addr:$dst)]>;
+                  "shl{q}\t{%cl, $dst|$dst, CL}",
+                  [(store (shl (loadi64 addr:$dst), CL), addr:$dst)], IIC_=
SR>;
 }
 def SHL8mi   : Ii8<0xC0, MRM4m, (outs), (ins i8mem :$dst, i8imm:$src),
                    "shl{b}\t{$src, $dst|$dst, $src}",
-                [(store (shl (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+                [(store (shl (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+                IIC_SR>;
 def SHL16mi  : Ii8<0xC1, MRM4m, (outs), (ins i16mem:$dst, i8imm:$src),
                    "shl{w}\t{$src, $dst|$dst, $src}",
-               [(store (shl (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>,
+               [(store (shl (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+               IIC_SR>,
                    OpSize;
 def SHL32mi  : Ii8<0xC1, MRM4m, (outs), (ins i32mem:$dst, i8imm:$src),
                    "shl{l}\t{$src, $dst|$dst, $src}",
-               [(store (shl (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+               [(store (shl (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+               IIC_SR>;
 def SHL64mi : RIi8<0xC1, MRM4m, (outs), (ins i64mem:$dst, i8imm:$src),
                   "shl{q}\t{$src, $dst|$dst, $src}",
-                 [(store (shl (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)]>;
+                 [(store (shl (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)],
+                 IIC_SR>;
=20
 // Shift by 1
 def SHL8m1   : I<0xD0, MRM4m, (outs), (ins i8mem :$dst),
                  "shl{b}\t$dst",
-                [(store (shl (loadi8 addr:$dst), (i8 1)), addr:$dst)]>;
+                [(store (shl (loadi8 addr:$dst), (i8 1)), addr:$dst)],
+                IIC_SR>;
 def SHL16m1  : I<0xD1, MRM4m, (outs), (ins i16mem:$dst),
                  "shl{w}\t$dst",
-               [(store (shl (loadi16 addr:$dst), (i8 1)), addr:$dst)]>,
+               [(store (shl (loadi16 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>,
                    OpSize;
 def SHL32m1  : I<0xD1, MRM4m, (outs), (ins i32mem:$dst),
                  "shl{l}\t$dst",
-               [(store (shl (loadi32 addr:$dst), (i8 1)), addr:$dst)]>;
+               [(store (shl (loadi32 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>;
 def SHL64m1 : RI<0xD1, MRM4m, (outs), (ins i64mem:$dst),
                   "shl{q}\t$dst",
-                 [(store (shl (loadi64 addr:$dst), (i8 1)), addr:$dst)]>;
+                 [(store (shl (loadi64 addr:$dst), (i8 1)), addr:$dst)],
+                 IIC_SR>;
=20
 let Constraints =3D "$src1 =3D $dst" in {
 let Uses =3D [CL] in {
 def SHR8rCL  : I<0xD2, MRM5r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "shr{b}\t{%cl, $dst|$dst, CL}",
-                 [(set GR8:$dst, (srl GR8:$src1, CL))]>;
+                 [(set GR8:$dst, (srl GR8:$src1, CL))], IIC_SR>;
 def SHR16rCL : I<0xD3, MRM5r, (outs GR16:$dst), (ins GR16:$src1),
                  "shr{w}\t{%cl, $dst|$dst, CL}",
-                 [(set GR16:$dst, (srl GR16:$src1, CL))]>, OpSize;
+                 [(set GR16:$dst, (srl GR16:$src1, CL))], IIC_SR>, OpSize;
 def SHR32rCL : I<0xD3, MRM5r, (outs GR32:$dst), (ins GR32:$src1),
                  "shr{l}\t{%cl, $dst|$dst, CL}",
-                 [(set GR32:$dst, (srl GR32:$src1, CL))]>;
+                 [(set GR32:$dst, (srl GR32:$src1, CL))], IIC_SR>;
 def SHR64rCL : RI<0xD3, MRM5r, (outs GR64:$dst), (ins GR64:$src1),
-                  "shr{q}\t{%cl, $dst|$dst, %CL}",
-                  [(set GR64:$dst, (srl GR64:$src1, CL))]>;
+                  "shr{q}\t{%cl, $dst|$dst, CL}",
+                  [(set GR64:$dst, (srl GR64:$src1, CL))], IIC_SR>;
 }
=20
 def SHR8ri   : Ii8<0xC0, MRM5r, (outs GR8:$dst), (ins GR8:$src1, i8imm:$sr=
c2),
                    "shr{b}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR8:$dst, (srl GR8:$src1, (i8 imm:$src2)))]>;
+                   [(set GR8:$dst, (srl GR8:$src1, (i8 imm:$src2)))], IIC_=
SR>;
 def SHR16ri  : Ii8<0xC1, MRM5r, (outs GR16:$dst), (ins GR16:$src1, i8imm:$=
src2),
                    "shr{w}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR16:$dst, (srl GR16:$src1, (i8 imm:$src2)))]>, O=
pSize;
+                   [(set GR16:$dst, (srl GR16:$src1, (i8 imm:$src2)))],
+                   IIC_SR>, OpSize;
 def SHR32ri  : Ii8<0xC1, MRM5r, (outs GR32:$dst), (ins GR32:$src1, i8imm:$=
src2),
                    "shr{l}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR32:$dst, (srl GR32:$src1, (i8 imm:$src2)))]>;
+                   [(set GR32:$dst, (srl GR32:$src1, (i8 imm:$src2)))],
+                   IIC_SR>;
 def SHR64ri : RIi8<0xC1, MRM5r, (outs GR64:$dst), (ins GR64:$src1, i8imm:$=
src2),
                   "shr{q}\t{$src2, $dst|$dst, $src2}",
-                  [(set GR64:$dst, (srl GR64:$src1, (i8 imm:$src2)))]>;
+                  [(set GR64:$dst, (srl GR64:$src1, (i8 imm:$src2)))], IIC=
_SR>;
=20
 // Shift right by 1
 def SHR8r1   : I<0xD0, MRM5r, (outs GR8:$dst), (ins GR8:$src1),
                  "shr{b}\t$dst",
-                 [(set GR8:$dst, (srl GR8:$src1, (i8 1)))]>;
+                 [(set GR8:$dst, (srl GR8:$src1, (i8 1)))], IIC_SR>;
 def SHR16r1  : I<0xD1, MRM5r, (outs GR16:$dst), (ins GR16:$src1),
                  "shr{w}\t$dst",
-                 [(set GR16:$dst, (srl GR16:$src1, (i8 1)))]>, OpSize;
+                 [(set GR16:$dst, (srl GR16:$src1, (i8 1)))], IIC_SR>, OpS=
ize;
 def SHR32r1  : I<0xD1, MRM5r, (outs GR32:$dst), (ins GR32:$src1),
                  "shr{l}\t$dst",
-                 [(set GR32:$dst, (srl GR32:$src1, (i8 1)))]>;
+                 [(set GR32:$dst, (srl GR32:$src1, (i8 1)))], IIC_SR>;
 def SHR64r1  : RI<0xD1, MRM5r, (outs GR64:$dst), (ins GR64:$src1),
                  "shr{q}\t$dst",
-                 [(set GR64:$dst, (srl GR64:$src1, (i8 1)))]>;
+                 [(set GR64:$dst, (srl GR64:$src1, (i8 1)))], IIC_SR>;
 } // Constraints =3D "$src =3D $dst"
=20
=20
 let Uses =3D [CL] in {
 def SHR8mCL  : I<0xD2, MRM5m, (outs), (ins i8mem :$dst),
                  "shr{b}\t{%cl, $dst|$dst, CL}",
-                 [(store (srl (loadi8 addr:$dst), CL), addr:$dst)]>;
+                 [(store (srl (loadi8 addr:$dst), CL), addr:$dst)], IIC_SR=
>;
 def SHR16mCL : I<0xD3, MRM5m, (outs), (ins i16mem:$dst),
                  "shr{w}\t{%cl, $dst|$dst, CL}",
-                 [(store (srl (loadi16 addr:$dst), CL), addr:$dst)]>,
+                 [(store (srl (loadi16 addr:$dst), CL), addr:$dst)], IIC_S=
R>,
                  OpSize;
 def SHR32mCL : I<0xD3, MRM5m, (outs), (ins i32mem:$dst),
                  "shr{l}\t{%cl, $dst|$dst, CL}",
-                 [(store (srl (loadi32 addr:$dst), CL), addr:$dst)]>;
+                 [(store (srl (loadi32 addr:$dst), CL), addr:$dst)], IIC_S=
R>;
 def SHR64mCL : RI<0xD3, MRM5m, (outs), (ins i64mem:$dst),
-                  "shr{q}\t{%cl, $dst|$dst, %CL}",
-                  [(store (srl (loadi64 addr:$dst), CL), addr:$dst)]>;
+                  "shr{q}\t{%cl, $dst|$dst, CL}",
+                  [(store (srl (loadi64 addr:$dst), CL), addr:$dst)], IIC_=
SR>;
 }
 def SHR8mi   : Ii8<0xC0, MRM5m, (outs), (ins i8mem :$dst, i8imm:$src),
                    "shr{b}\t{$src, $dst|$dst, $src}",
-                [(store (srl (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+                [(store (srl (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+                IIC_SR>;
 def SHR16mi  : Ii8<0xC1, MRM5m, (outs), (ins i16mem:$dst, i8imm:$src),
                    "shr{w}\t{$src, $dst|$dst, $src}",
-               [(store (srl (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>,
+               [(store (srl (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+               IIC_SR>,
                    OpSize;
 def SHR32mi  : Ii8<0xC1, MRM5m, (outs), (ins i32mem:$dst, i8imm:$src),
                    "shr{l}\t{$src, $dst|$dst, $src}",
-               [(store (srl (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+               [(store (srl (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+               IIC_SR>;
 def SHR64mi : RIi8<0xC1, MRM5m, (outs), (ins i64mem:$dst, i8imm:$src),
                   "shr{q}\t{$src, $dst|$dst, $src}",
-                 [(store (srl (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)]>;
+                 [(store (srl (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)],
+                 IIC_SR>;
=20
 // Shift by 1
 def SHR8m1   : I<0xD0, MRM5m, (outs), (ins i8mem :$dst),
                  "shr{b}\t$dst",
-                [(store (srl (loadi8 addr:$dst), (i8 1)), addr:$dst)]>;
+                [(store (srl (loadi8 addr:$dst), (i8 1)), addr:$dst)],
+                IIC_SR>;
 def SHR16m1  : I<0xD1, MRM5m, (outs), (ins i16mem:$dst),
                  "shr{w}\t$dst",
-               [(store (srl (loadi16 addr:$dst), (i8 1)), addr:$dst)]>,OpS=
ize;
+               [(store (srl (loadi16 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>,OpSize;
 def SHR32m1  : I<0xD1, MRM5m, (outs), (ins i32mem:$dst),
                  "shr{l}\t$dst",
-               [(store (srl (loadi32 addr:$dst), (i8 1)), addr:$dst)]>;
+               [(store (srl (loadi32 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>;
 def SHR64m1 : RI<0xD1, MRM5m, (outs), (ins i64mem:$dst),
                   "shr{q}\t$dst",
-                 [(store (srl (loadi64 addr:$dst), (i8 1)), addr:$dst)]>;
+                 [(store (srl (loadi64 addr:$dst), (i8 1)), addr:$dst)],
+                 IIC_SR>;
=20
 let Constraints =3D "$src1 =3D $dst" in {
 let Uses =3D [CL] in {
 def SAR8rCL  : I<0xD2, MRM7r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "sar{b}\t{%cl, $dst|$dst, CL}",
-                 [(set GR8:$dst, (sra GR8:$src1, CL))]>;
+                 [(set GR8:$dst, (sra GR8:$src1, CL))],
+                 IIC_SR>;
 def SAR16rCL : I<0xD3, MRM7r, (outs GR16:$dst), (ins GR16:$src1),
                  "sar{w}\t{%cl, $dst|$dst, CL}",
-                 [(set GR16:$dst, (sra GR16:$src1, CL))]>, OpSize;
+                 [(set GR16:$dst, (sra GR16:$src1, CL))],
+                 IIC_SR>, OpSize;
 def SAR32rCL : I<0xD3, MRM7r, (outs GR32:$dst), (ins GR32:$src1),
                  "sar{l}\t{%cl, $dst|$dst, CL}",
-                 [(set GR32:$dst, (sra GR32:$src1, CL))]>;
+                 [(set GR32:$dst, (sra GR32:$src1, CL))],
+                 IIC_SR>;
 def SAR64rCL : RI<0xD3, MRM7r, (outs GR64:$dst), (ins GR64:$src1),
-                 "sar{q}\t{%cl, $dst|$dst, %CL}",
-                 [(set GR64:$dst, (sra GR64:$src1, CL))]>;
+                 "sar{q}\t{%cl, $dst|$dst, CL}",
+                 [(set GR64:$dst, (sra GR64:$src1, CL))],
+                 IIC_SR>;
 }
=20
 def SAR8ri   : Ii8<0xC0, MRM7r, (outs GR8 :$dst), (ins GR8 :$src1, i8imm:$=
src2),
                    "sar{b}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR8:$dst, (sra GR8:$src1, (i8 imm:$src2)))]>;
+                   [(set GR8:$dst, (sra GR8:$src1, (i8 imm:$src2)))],
+                   IIC_SR>;
 def SAR16ri  : Ii8<0xC1, MRM7r, (outs GR16:$dst), (ins GR16:$src1, i8imm:$=
src2),
                    "sar{w}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR16:$dst, (sra GR16:$src1, (i8 imm:$src2)))]>,
+                   [(set GR16:$dst, (sra GR16:$src1, (i8 imm:$src2)))],
+                   IIC_SR>,
                    OpSize;
 def SAR32ri  : Ii8<0xC1, MRM7r, (outs GR32:$dst), (ins GR32:$src1, i8imm:$=
src2),
                    "sar{l}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR32:$dst, (sra GR32:$src1, (i8 imm:$src2)))]>;
+                   [(set GR32:$dst, (sra GR32:$src1, (i8 imm:$src2)))],
+                   IIC_SR>;
 def SAR64ri  : RIi8<0xC1, MRM7r, (outs GR64:$dst),
                     (ins GR64:$src1, i8imm:$src2),
                     "sar{q}\t{$src2, $dst|$dst, $src2}",
-                    [(set GR64:$dst, (sra GR64:$src1, (i8 imm:$src2)))]>;
+                    [(set GR64:$dst, (sra GR64:$src1, (i8 imm:$src2)))],
+                    IIC_SR>;
=20
 // Shift by 1
 def SAR8r1   : I<0xD0, MRM7r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "sar{b}\t$dst",
-                 [(set GR8:$dst, (sra GR8:$src1, (i8 1)))]>;
+                 [(set GR8:$dst, (sra GR8:$src1, (i8 1)))],
+                 IIC_SR>;
 def SAR16r1  : I<0xD1, MRM7r, (outs GR16:$dst), (ins GR16:$src1),
                  "sar{w}\t$dst",
-                 [(set GR16:$dst, (sra GR16:$src1, (i8 1)))]>, OpSize;
+                 [(set GR16:$dst, (sra GR16:$src1, (i8 1)))],
+                 IIC_SR>, OpSize;
 def SAR32r1  : I<0xD1, MRM7r, (outs GR32:$dst), (ins GR32:$src1),
                  "sar{l}\t$dst",
-                 [(set GR32:$dst, (sra GR32:$src1, (i8 1)))]>;
+                 [(set GR32:$dst, (sra GR32:$src1, (i8 1)))],
+                 IIC_SR>;
 def SAR64r1  : RI<0xD1, MRM7r, (outs GR64:$dst), (ins GR64:$src1),
                  "sar{q}\t$dst",
-                 [(set GR64:$dst, (sra GR64:$src1, (i8 1)))]>;
+                 [(set GR64:$dst, (sra GR64:$src1, (i8 1)))],
+                 IIC_SR>;
 } // Constraints =3D "$src =3D $dst"
=20
=20
 let Uses =3D [CL] in {
 def SAR8mCL  : I<0xD2, MRM7m, (outs), (ins i8mem :$dst),
                  "sar{b}\t{%cl, $dst|$dst, CL}",
-                 [(store (sra (loadi8 addr:$dst), CL), addr:$dst)]>;
+                 [(store (sra (loadi8 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>;
 def SAR16mCL : I<0xD3, MRM7m, (outs), (ins i16mem:$dst),
                  "sar{w}\t{%cl, $dst|$dst, CL}",
-                 [(store (sra (loadi16 addr:$dst), CL), addr:$dst)]>, OpSi=
ze;
+                 [(store (sra (loadi16 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>, OpSize;
 def SAR32mCL : I<0xD3, MRM7m, (outs), (ins i32mem:$dst),=20
                  "sar{l}\t{%cl, $dst|$dst, CL}",
-                 [(store (sra (loadi32 addr:$dst), CL), addr:$dst)]>;
+                 [(store (sra (loadi32 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>;
 def SAR64mCL : RI<0xD3, MRM7m, (outs), (ins i64mem:$dst),=20
-                 "sar{q}\t{%cl, $dst|$dst, %CL}",
-                 [(store (sra (loadi64 addr:$dst), CL), addr:$dst)]>;
+                 "sar{q}\t{%cl, $dst|$dst, CL}",
+                 [(store (sra (loadi64 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>;
 }
 def SAR8mi   : Ii8<0xC0, MRM7m, (outs), (ins i8mem :$dst, i8imm:$src),
                    "sar{b}\t{$src, $dst|$dst, $src}",
-                [(store (sra (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+                [(store (sra (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+                IIC_SR>;
 def SAR16mi  : Ii8<0xC1, MRM7m, (outs), (ins i16mem:$dst, i8imm:$src),
                    "sar{w}\t{$src, $dst|$dst, $src}",
-               [(store (sra (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>,
+               [(store (sra (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+               IIC_SR>,
                    OpSize;
 def SAR32mi  : Ii8<0xC1, MRM7m, (outs), (ins i32mem:$dst, i8imm:$src),
                    "sar{l}\t{$src, $dst|$dst, $src}",
-               [(store (sra (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+               [(store (sra (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+               IIC_SR>;
 def SAR64mi  : RIi8<0xC1, MRM7m, (outs), (ins i64mem:$dst, i8imm:$src),
                     "sar{q}\t{$src, $dst|$dst, $src}",
-                 [(store (sra (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)]>;
+                 [(store (sra (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)],
+                 IIC_SR>;
=20
 // Shift by 1
 def SAR8m1   : I<0xD0, MRM7m, (outs), (ins i8mem :$dst),
                  "sar{b}\t$dst",
-                [(store (sra (loadi8 addr:$dst), (i8 1)), addr:$dst)]>;
+                [(store (sra (loadi8 addr:$dst), (i8 1)), addr:$dst)],
+                IIC_SR>;
 def SAR16m1  : I<0xD1, MRM7m, (outs), (ins i16mem:$dst),
                  "sar{w}\t$dst",
-               [(store (sra (loadi16 addr:$dst), (i8 1)), addr:$dst)]>,
+               [(store (sra (loadi16 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>,
                    OpSize;
 def SAR32m1  : I<0xD1, MRM7m, (outs), (ins i32mem:$dst),
                  "sar{l}\t$dst",
-               [(store (sra (loadi32 addr:$dst), (i8 1)), addr:$dst)]>;
+               [(store (sra (loadi32 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>;
 def SAR64m1 : RI<0xD1, MRM7m, (outs), (ins i64mem:$dst),
                   "sar{q}\t$dst",
-                 [(store (sra (loadi64 addr:$dst), (i8 1)), addr:$dst)]>;
+                 [(store (sra (loadi64 addr:$dst), (i8 1)), addr:$dst)],
+                 IIC_SR>;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Rotate instructions
@@ -290,125 +335,125 @@
=20
 let Constraints =3D "$src1 =3D $dst" in {
 def RCL8r1 : I<0xD0, MRM2r, (outs GR8:$dst), (ins GR8:$src1),
-               "rcl{b}\t$dst", []>;
+               "rcl{b}\t$dst", [], IIC_SR>;
 def RCL8ri : Ii8<0xC0, MRM2r, (outs GR8:$dst), (ins GR8:$src1, i8imm:$cnt),
-                 "rcl{b}\t{$cnt, $dst|$dst, $cnt}", []>;
+                 "rcl{b}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 let Uses =3D [CL] in
 def RCL8rCL : I<0xD2, MRM2r, (outs GR8:$dst), (ins GR8:$src1),
-                "rcl{b}\t{%cl, $dst|$dst, CL}", []>;
+                "rcl{b}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
  =20
 def RCL16r1 : I<0xD1, MRM2r, (outs GR16:$dst), (ins GR16:$src1),
-                "rcl{w}\t$dst", []>, OpSize;
+                "rcl{w}\t$dst", [], IIC_SR>, OpSize;
 def RCL16ri : Ii8<0xC1, MRM2r, (outs GR16:$dst), (ins GR16:$src1, i8imm:$c=
nt),
-                  "rcl{w}\t{$cnt, $dst|$dst, $cnt}", []>, OpSize;
+                  "rcl{w}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>, OpSize;
 let Uses =3D [CL] in
 def RCL16rCL : I<0xD3, MRM2r, (outs GR16:$dst), (ins GR16:$src1),
-                 "rcl{w}\t{%cl, $dst|$dst, CL}", []>, OpSize;
+                 "rcl{w}\t{%cl, $dst|$dst, CL}", [], IIC_SR>, OpSize;
=20
 def RCL32r1 : I<0xD1, MRM2r, (outs GR32:$dst), (ins GR32:$src1),
-                "rcl{l}\t$dst", []>;
+                "rcl{l}\t$dst", [], IIC_SR>;
 def RCL32ri : Ii8<0xC1, MRM2r, (outs GR32:$dst), (ins GR32:$src1, i8imm:$c=
nt),
-                  "rcl{l}\t{$cnt, $dst|$dst, $cnt}", []>;
+                  "rcl{l}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 let Uses =3D [CL] in
 def RCL32rCL : I<0xD3, MRM2r, (outs GR32:$dst), (ins GR32:$src1),
-                 "rcl{l}\t{%cl, $dst|$dst, CL}", []>;
+                 "rcl{l}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
=20
=20
 def RCL64r1 : RI<0xD1, MRM2r, (outs GR64:$dst), (ins GR64:$src1),
-                 "rcl{q}\t$dst", []>;
+                 "rcl{q}\t$dst", [], IIC_SR>;
 def RCL64ri : RIi8<0xC1, MRM2r, (outs GR64:$dst), (ins GR64:$src1, i8imm:$=
cnt),
-                   "rcl{q}\t{$cnt, $dst|$dst, $cnt}", []>;
+                   "rcl{q}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 let Uses =3D [CL] in
 def RCL64rCL : RI<0xD3, MRM2r, (outs GR64:$dst), (ins GR64:$src1),
-                  "rcl{q}\t{%cl, $dst|$dst, CL}", []>;
+                  "rcl{q}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
=20
=20
 def RCR8r1 : I<0xD0, MRM3r, (outs GR8:$dst), (ins GR8:$src1),
-               "rcr{b}\t$dst", []>;
+               "rcr{b}\t$dst", [], IIC_SR>;
 def RCR8ri : Ii8<0xC0, MRM3r, (outs GR8:$dst), (ins GR8:$src1, i8imm:$cnt),
-                 "rcr{b}\t{$cnt, $dst|$dst, $cnt}", []>;
+                 "rcr{b}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 let Uses =3D [CL] in
 def RCR8rCL : I<0xD2, MRM3r, (outs GR8:$dst), (ins GR8:$src1),
-                "rcr{b}\t{%cl, $dst|$dst, CL}", []>;
+                "rcr{b}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
  =20
 def RCR16r1 : I<0xD1, MRM3r, (outs GR16:$dst), (ins GR16:$src1),
-                "rcr{w}\t$dst", []>, OpSize;
+                "rcr{w}\t$dst", [], IIC_SR>, OpSize;
 def RCR16ri : Ii8<0xC1, MRM3r, (outs GR16:$dst), (ins GR16:$src1, i8imm:$c=
nt),
-                  "rcr{w}\t{$cnt, $dst|$dst, $cnt}", []>, OpSize;
+                  "rcr{w}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>, OpSize;
 let Uses =3D [CL] in
 def RCR16rCL : I<0xD3, MRM3r, (outs GR16:$dst), (ins GR16:$src1),
-                 "rcr{w}\t{%cl, $dst|$dst, CL}", []>, OpSize;
+                 "rcr{w}\t{%cl, $dst|$dst, CL}", [], IIC_SR>, OpSize;
=20
 def RCR32r1 : I<0xD1, MRM3r, (outs GR32:$dst), (ins GR32:$src1),
-                "rcr{l}\t$dst", []>;
+                "rcr{l}\t$dst", [], IIC_SR>;
 def RCR32ri : Ii8<0xC1, MRM3r, (outs GR32:$dst), (ins GR32:$src1, i8imm:$c=
nt),
-                  "rcr{l}\t{$cnt, $dst|$dst, $cnt}", []>;
+                  "rcr{l}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 let Uses =3D [CL] in
 def RCR32rCL : I<0xD3, MRM3r, (outs GR32:$dst), (ins GR32:$src1),
-                 "rcr{l}\t{%cl, $dst|$dst, CL}", []>;
+                 "rcr{l}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
                 =20
 def RCR64r1 : RI<0xD1, MRM3r, (outs GR64:$dst), (ins GR64:$src1),
-                 "rcr{q}\t$dst", []>;
+                 "rcr{q}\t$dst", [], IIC_SR>;
 def RCR64ri : RIi8<0xC1, MRM3r, (outs GR64:$dst), (ins GR64:$src1, i8imm:$=
cnt),
-                   "rcr{q}\t{$cnt, $dst|$dst, $cnt}", []>;
+                   "rcr{q}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 let Uses =3D [CL] in
 def RCR64rCL : RI<0xD3, MRM3r, (outs GR64:$dst), (ins GR64:$src1),
-                  "rcr{q}\t{%cl, $dst|$dst, CL}", []>;
+                  "rcr{q}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
=20
 } // Constraints =3D "$src =3D $dst"
=20
 def RCL8m1 : I<0xD0, MRM2m, (outs), (ins i8mem:$dst),
-               "rcl{b}\t$dst", []>;
+               "rcl{b}\t$dst", [], IIC_SR>;
 def RCL8mi : Ii8<0xC0, MRM2m, (outs), (ins i8mem:$dst, i8imm:$cnt),
-                 "rcl{b}\t{$cnt, $dst|$dst, $cnt}", []>;
+                 "rcl{b}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 def RCL16m1 : I<0xD1, MRM2m, (outs), (ins i16mem:$dst),
-                "rcl{w}\t$dst", []>, OpSize;
+                "rcl{w}\t$dst", [], IIC_SR>, OpSize;
 def RCL16mi : Ii8<0xC1, MRM2m, (outs), (ins i16mem:$dst, i8imm:$cnt),
-                  "rcl{w}\t{$cnt, $dst|$dst, $cnt}", []>, OpSize;
+                  "rcl{w}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>, OpSize;
 def RCL32m1 : I<0xD1, MRM2m, (outs), (ins i32mem:$dst),
-                "rcl{l}\t$dst", []>;
+                "rcl{l}\t$dst", [], IIC_SR>;
 def RCL32mi : Ii8<0xC1, MRM2m, (outs), (ins i32mem:$dst, i8imm:$cnt),
-                  "rcl{l}\t{$cnt, $dst|$dst, $cnt}", []>;
+                  "rcl{l}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 def RCL64m1 : RI<0xD1, MRM2m, (outs), (ins i64mem:$dst),
-                 "rcl{q}\t$dst", []>;
+                 "rcl{q}\t$dst", [], IIC_SR>;
 def RCL64mi : RIi8<0xC1, MRM2m, (outs), (ins i64mem:$dst, i8imm:$cnt),
-                   "rcl{q}\t{$cnt, $dst|$dst, $cnt}", []>;
+                   "rcl{q}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
=20
 def RCR8m1 : I<0xD0, MRM3m, (outs), (ins i8mem:$dst),
-               "rcr{b}\t$dst", []>;
+               "rcr{b}\t$dst", [], IIC_SR>;
 def RCR8mi : Ii8<0xC0, MRM3m, (outs), (ins i8mem:$dst, i8imm:$cnt),
-                 "rcr{b}\t{$cnt, $dst|$dst, $cnt}", []>;
+                 "rcr{b}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 def RCR16m1 : I<0xD1, MRM3m, (outs), (ins i16mem:$dst),
-                "rcr{w}\t$dst", []>, OpSize;
+                "rcr{w}\t$dst", [], IIC_SR>, OpSize;
 def RCR16mi : Ii8<0xC1, MRM3m, (outs), (ins i16mem:$dst, i8imm:$cnt),
-                  "rcr{w}\t{$cnt, $dst|$dst, $cnt}", []>, OpSize;
+                  "rcr{w}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>, OpSize;
 def RCR32m1 : I<0xD1, MRM3m, (outs), (ins i32mem:$dst),
-                "rcr{l}\t$dst", []>;
+                "rcr{l}\t$dst", [], IIC_SR>;
 def RCR32mi : Ii8<0xC1, MRM3m, (outs), (ins i32mem:$dst, i8imm:$cnt),
-                  "rcr{l}\t{$cnt, $dst|$dst, $cnt}", []>;
+                  "rcr{l}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
 def RCR64m1 : RI<0xD1, MRM3m, (outs), (ins i64mem:$dst),
-                 "rcr{q}\t$dst", []>;
+                 "rcr{q}\t$dst", [], IIC_SR>;
 def RCR64mi : RIi8<0xC1, MRM3m, (outs), (ins i64mem:$dst, i8imm:$cnt),
-                   "rcr{q}\t{$cnt, $dst|$dst, $cnt}", []>;
+                   "rcr{q}\t{$cnt, $dst|$dst, $cnt}", [], IIC_SR>;
=20
 let Uses =3D [CL] in {
 def RCL8mCL : I<0xD2, MRM2m, (outs), (ins i8mem:$dst),
-                "rcl{b}\t{%cl, $dst|$dst, CL}", []>;
+                "rcl{b}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
 def RCL16mCL : I<0xD3, MRM2m, (outs), (ins i16mem:$dst),
-                 "rcl{w}\t{%cl, $dst|$dst, CL}", []>, OpSize;
+                 "rcl{w}\t{%cl, $dst|$dst, CL}", [], IIC_SR>, OpSize;
 def RCL32mCL : I<0xD3, MRM2m, (outs), (ins i32mem:$dst),
-                 "rcl{l}\t{%cl, $dst|$dst, CL}", []>;
+                 "rcl{l}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
 def RCL64mCL : RI<0xD3, MRM2m, (outs), (ins i64mem:$dst),
-                  "rcl{q}\t{%cl, $dst|$dst, CL}", []>;
+                  "rcl{q}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
=20
 def RCR8mCL : I<0xD2, MRM3m, (outs), (ins i8mem:$dst),
-                "rcr{b}\t{%cl, $dst|$dst, CL}", []>;
+                "rcr{b}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
 def RCR16mCL : I<0xD3, MRM3m, (outs), (ins i16mem:$dst),
-                 "rcr{w}\t{%cl, $dst|$dst, CL}", []>, OpSize;
+                 "rcr{w}\t{%cl, $dst|$dst, CL}", [], IIC_SR>, OpSize;
 def RCR32mCL : I<0xD3, MRM3m, (outs), (ins i32mem:$dst),
-                 "rcr{l}\t{%cl, $dst|$dst, CL}", []>;
+                 "rcr{l}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
 def RCR64mCL : RI<0xD3, MRM3m, (outs), (ins i64mem:$dst),
-                  "rcr{q}\t{%cl, $dst|$dst, CL}", []>;
+                  "rcr{q}\t{%cl, $dst|$dst, CL}", [], IIC_SR>;
 }
=20
 let Constraints =3D "$src1 =3D $dst" in {
@@ -416,179 +461,217 @@
 let Uses =3D [CL] in {
 def ROL8rCL  : I<0xD2, MRM0r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "rol{b}\t{%cl, $dst|$dst, CL}",
-                 [(set GR8:$dst, (rotl GR8:$src1, CL))]>;
+                 [(set GR8:$dst, (rotl GR8:$src1, CL))], IIC_SR>;
 def ROL16rCL : I<0xD3, MRM0r, (outs GR16:$dst), (ins GR16:$src1),
                  "rol{w}\t{%cl, $dst|$dst, CL}",
-                 [(set GR16:$dst, (rotl GR16:$src1, CL))]>, OpSize;
+                 [(set GR16:$dst, (rotl GR16:$src1, CL))], IIC_SR>, OpSize;
 def ROL32rCL : I<0xD3, MRM0r, (outs GR32:$dst), (ins GR32:$src1),
                  "rol{l}\t{%cl, $dst|$dst, CL}",
-                 [(set GR32:$dst, (rotl GR32:$src1, CL))]>;
+                 [(set GR32:$dst, (rotl GR32:$src1, CL))], IIC_SR>;
 def ROL64rCL : RI<0xD3, MRM0r, (outs GR64:$dst), (ins GR64:$src1),
-                  "rol{q}\t{%cl, $dst|$dst, %CL}",
-                  [(set GR64:$dst, (rotl GR64:$src1, CL))]>;
+                  "rol{q}\t{%cl, $dst|$dst, CL}",
+                  [(set GR64:$dst, (rotl GR64:$src1, CL))], IIC_SR>;
 }
=20
 def ROL8ri   : Ii8<0xC0, MRM0r, (outs GR8 :$dst), (ins GR8 :$src1, i8imm:$=
src2),
                    "rol{b}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR8:$dst, (rotl GR8:$src1, (i8 imm:$src2)))]>;
+                   [(set GR8:$dst, (rotl GR8:$src1, (i8 imm:$src2)))], IIC=
_SR>;
 def ROL16ri  : Ii8<0xC1, MRM0r, (outs GR16:$dst), (ins GR16:$src1, i8imm:$=
src2),
                    "rol{w}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR16:$dst, (rotl GR16:$src1, (i8 imm:$src2)))]>,=20
+                   [(set GR16:$dst, (rotl GR16:$src1, (i8 imm:$src2)))],
+                   IIC_SR>,=20
                    OpSize;
 def ROL32ri  : Ii8<0xC1, MRM0r, (outs GR32:$dst), (ins GR32:$src1, i8imm:$=
src2),
                    "rol{l}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR32:$dst, (rotl GR32:$src1, (i8 imm:$src2)))]>;
+                   [(set GR32:$dst, (rotl GR32:$src1, (i8 imm:$src2)))],
+                   IIC_SR>;
 def ROL64ri  : RIi8<0xC1, MRM0r, (outs GR64:$dst),=20
                     (ins GR64:$src1, i8imm:$src2),
                     "rol{q}\t{$src2, $dst|$dst, $src2}",
-                    [(set GR64:$dst, (rotl GR64:$src1, (i8 imm:$src2)))]>;
+                    [(set GR64:$dst, (rotl GR64:$src1, (i8 imm:$src2)))],
+                    IIC_SR>;
=20
 // Rotate by 1
 def ROL8r1   : I<0xD0, MRM0r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "rol{b}\t$dst",
-                 [(set GR8:$dst, (rotl GR8:$src1, (i8 1)))]>;
+                 [(set GR8:$dst, (rotl GR8:$src1, (i8 1)))],
+                 IIC_SR>;
 def ROL16r1  : I<0xD1, MRM0r, (outs GR16:$dst), (ins GR16:$src1),
                  "rol{w}\t$dst",
-                 [(set GR16:$dst, (rotl GR16:$src1, (i8 1)))]>, OpSize;
+                 [(set GR16:$dst, (rotl GR16:$src1, (i8 1)))],
+                 IIC_SR>, OpSize;
 def ROL32r1  : I<0xD1, MRM0r, (outs GR32:$dst), (ins GR32:$src1),
                  "rol{l}\t$dst",
-                 [(set GR32:$dst, (rotl GR32:$src1, (i8 1)))]>;
+                 [(set GR32:$dst, (rotl GR32:$src1, (i8 1)))],
+                 IIC_SR>;
 def ROL64r1  : RI<0xD1, MRM0r, (outs GR64:$dst), (ins GR64:$src1),
                   "rol{q}\t$dst",
-                  [(set GR64:$dst, (rotl GR64:$src1, (i8 1)))]>;
+                  [(set GR64:$dst, (rotl GR64:$src1, (i8 1)))],
+                  IIC_SR>;
 } // Constraints =3D "$src =3D $dst"
=20
 let Uses =3D [CL] in {
 def ROL8mCL  : I<0xD2, MRM0m, (outs), (ins i8mem :$dst),
                  "rol{b}\t{%cl, $dst|$dst, CL}",
-                 [(store (rotl (loadi8 addr:$dst), CL), addr:$dst)]>;
+                 [(store (rotl (loadi8 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>;
 def ROL16mCL : I<0xD3, MRM0m, (outs), (ins i16mem:$dst),
                  "rol{w}\t{%cl, $dst|$dst, CL}",
-                 [(store (rotl (loadi16 addr:$dst), CL), addr:$dst)]>, OpS=
ize;
+                 [(store (rotl (loadi16 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>, OpSize;
 def ROL32mCL : I<0xD3, MRM0m, (outs), (ins i32mem:$dst),
                  "rol{l}\t{%cl, $dst|$dst, CL}",
-                 [(store (rotl (loadi32 addr:$dst), CL), addr:$dst)]>;
+                 [(store (rotl (loadi32 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>;
 def ROL64mCL :  RI<0xD3, MRM0m, (outs), (ins i64mem:$dst),
-                   "rol{q}\t{%cl, $dst|$dst, %CL}",
-                   [(store (rotl (loadi64 addr:$dst), CL), addr:$dst)]>;
+                   "rol{q}\t{%cl, $dst|$dst, %cl}",
+                   [(store (rotl (loadi64 addr:$dst), CL), addr:$dst)],
+                   IIC_SR>;
 }
 def ROL8mi   : Ii8<0xC0, MRM0m, (outs), (ins i8mem :$dst, i8imm:$src1),
                    "rol{b}\t{$src1, $dst|$dst, $src1}",
-               [(store (rotl (loadi8 addr:$dst), (i8 imm:$src1)), addr:$ds=
t)]>;
+               [(store (rotl (loadi8 addr:$dst), (i8 imm:$src1)), addr:$ds=
t)],
+               IIC_SR>;
 def ROL16mi  : Ii8<0xC1, MRM0m, (outs), (ins i16mem:$dst, i8imm:$src1),
                    "rol{w}\t{$src1, $dst|$dst, $src1}",
-              [(store (rotl (loadi16 addr:$dst), (i8 imm:$src1)), addr:$ds=
t)]>,
+              [(store (rotl (loadi16 addr:$dst), (i8 imm:$src1)), addr:$ds=
t)],
+              IIC_SR>,
                    OpSize;
 def ROL32mi  : Ii8<0xC1, MRM0m, (outs), (ins i32mem:$dst, i8imm:$src1),
                    "rol{l}\t{$src1, $dst|$dst, $src1}",
-              [(store (rotl (loadi32 addr:$dst), (i8 imm:$src1)), addr:$ds=
t)]>;
+              [(store (rotl (loadi32 addr:$dst), (i8 imm:$src1)), addr:$ds=
t)],
+              IIC_SR>;
 def ROL64mi  : RIi8<0xC1, MRM0m, (outs), (ins i64mem:$dst, i8imm:$src1),
                     "rol{q}\t{$src1, $dst|$dst, $src1}",
-                [(store (rotl (loadi64 addr:$dst), (i8 imm:$src1)), addr:$=
dst)]>;
+                [(store (rotl (loadi64 addr:$dst), (i8 imm:$src1)), addr:$=
dst)],
+                IIC_SR>;
=20
 // Rotate by 1
 def ROL8m1   : I<0xD0, MRM0m, (outs), (ins i8mem :$dst),
                  "rol{b}\t$dst",
-               [(store (rotl (loadi8 addr:$dst), (i8 1)), addr:$dst)]>;
+               [(store (rotl (loadi8 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>;
 def ROL16m1  : I<0xD1, MRM0m, (outs), (ins i16mem:$dst),
                  "rol{w}\t$dst",
-              [(store (rotl (loadi16 addr:$dst), (i8 1)), addr:$dst)]>,
+              [(store (rotl (loadi16 addr:$dst), (i8 1)), addr:$dst)],
+              IIC_SR>,
                    OpSize;
 def ROL32m1  : I<0xD1, MRM0m, (outs), (ins i32mem:$dst),
                  "rol{l}\t$dst",
-              [(store (rotl (loadi32 addr:$dst), (i8 1)), addr:$dst)]>;
+              [(store (rotl (loadi32 addr:$dst), (i8 1)), addr:$dst)],
+              IIC_SR>;
 def ROL64m1  : RI<0xD1, MRM0m, (outs), (ins i64mem:$dst),
                  "rol{q}\t$dst",
-               [(store (rotl (loadi64 addr:$dst), (i8 1)), addr:$dst)]>;
+               [(store (rotl (loadi64 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>;
=20
 let Constraints =3D "$src1 =3D $dst" in {
 let Uses =3D [CL] in {
 def ROR8rCL  : I<0xD2, MRM1r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "ror{b}\t{%cl, $dst|$dst, CL}",
-                 [(set GR8:$dst, (rotr GR8:$src1, CL))]>;
+                 [(set GR8:$dst, (rotr GR8:$src1, CL))], IIC_SR>;
 def ROR16rCL : I<0xD3, MRM1r, (outs GR16:$dst), (ins GR16:$src1),
                  "ror{w}\t{%cl, $dst|$dst, CL}",
-                 [(set GR16:$dst, (rotr GR16:$src1, CL))]>, OpSize;
+                 [(set GR16:$dst, (rotr GR16:$src1, CL))], IIC_SR>, OpSize;
 def ROR32rCL : I<0xD3, MRM1r, (outs GR32:$dst), (ins GR32:$src1),
                  "ror{l}\t{%cl, $dst|$dst, CL}",
-                 [(set GR32:$dst, (rotr GR32:$src1, CL))]>;
+                 [(set GR32:$dst, (rotr GR32:$src1, CL))], IIC_SR>;
 def ROR64rCL : RI<0xD3, MRM1r, (outs GR64:$dst), (ins GR64:$src1),
-                  "ror{q}\t{%cl, $dst|$dst, %CL}",
-                  [(set GR64:$dst, (rotr GR64:$src1, CL))]>;
+                  "ror{q}\t{%cl, $dst|$dst, CL}",
+                  [(set GR64:$dst, (rotr GR64:$src1, CL))], IIC_SR>;
 }
=20
 def ROR8ri   : Ii8<0xC0, MRM1r, (outs GR8 :$dst), (ins GR8 :$src1, i8imm:$=
src2),
                    "ror{b}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR8:$dst, (rotr GR8:$src1, (i8 imm:$src2)))]>;
+                   [(set GR8:$dst, (rotr GR8:$src1, (i8 imm:$src2)))], IIC=
_SR>;
 def ROR16ri  : Ii8<0xC1, MRM1r, (outs GR16:$dst), (ins GR16:$src1, i8imm:$=
src2),
                    "ror{w}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR16:$dst, (rotr GR16:$src1, (i8 imm:$src2)))]>,=20
+                   [(set GR16:$dst, (rotr GR16:$src1, (i8 imm:$src2)))],
+                   IIC_SR>,=20
                    OpSize;
 def ROR32ri  : Ii8<0xC1, MRM1r, (outs GR32:$dst), (ins GR32:$src1, i8imm:$=
src2),
                    "ror{l}\t{$src2, $dst|$dst, $src2}",
-                   [(set GR32:$dst, (rotr GR32:$src1, (i8 imm:$src2)))]>;
+                   [(set GR32:$dst, (rotr GR32:$src1, (i8 imm:$src2)))],
+                   IIC_SR>;
 def ROR64ri  : RIi8<0xC1, MRM1r, (outs GR64:$dst),=20
                     (ins GR64:$src1, i8imm:$src2),
                     "ror{q}\t{$src2, $dst|$dst, $src2}",
-                    [(set GR64:$dst, (rotr GR64:$src1, (i8 imm:$src2)))]>;
+                    [(set GR64:$dst, (rotr GR64:$src1, (i8 imm:$src2)))],
+                    IIC_SR>;
=20
 // Rotate by 1
 def ROR8r1   : I<0xD0, MRM1r, (outs GR8 :$dst), (ins GR8 :$src1),
                  "ror{b}\t$dst",
-                 [(set GR8:$dst, (rotr GR8:$src1, (i8 1)))]>;
+                 [(set GR8:$dst, (rotr GR8:$src1, (i8 1)))],
+                 IIC_SR>;
 def ROR16r1  : I<0xD1, MRM1r, (outs GR16:$dst), (ins GR16:$src1),
                  "ror{w}\t$dst",
-                 [(set GR16:$dst, (rotr GR16:$src1, (i8 1)))]>, OpSize;
+                 [(set GR16:$dst, (rotr GR16:$src1, (i8 1)))],
+                 IIC_SR>, OpSize;
 def ROR32r1  : I<0xD1, MRM1r, (outs GR32:$dst), (ins GR32:$src1),
                  "ror{l}\t$dst",
-                 [(set GR32:$dst, (rotr GR32:$src1, (i8 1)))]>;
+                 [(set GR32:$dst, (rotr GR32:$src1, (i8 1)))],
+                 IIC_SR>;
 def ROR64r1  : RI<0xD1, MRM1r, (outs GR64:$dst), (ins GR64:$src1),
                   "ror{q}\t$dst",
-                  [(set GR64:$dst, (rotr GR64:$src1, (i8 1)))]>;
+                  [(set GR64:$dst, (rotr GR64:$src1, (i8 1)))],
+                  IIC_SR>;
 } // Constraints =3D "$src =3D $dst"
=20
 let Uses =3D [CL] in {
 def ROR8mCL  : I<0xD2, MRM1m, (outs), (ins i8mem :$dst),
                  "ror{b}\t{%cl, $dst|$dst, CL}",
-                 [(store (rotr (loadi8 addr:$dst), CL), addr:$dst)]>;
+                 [(store (rotr (loadi8 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>;
 def ROR16mCL : I<0xD3, MRM1m, (outs), (ins i16mem:$dst),
                  "ror{w}\t{%cl, $dst|$dst, CL}",
-                 [(store (rotr (loadi16 addr:$dst), CL), addr:$dst)]>, OpS=
ize;
+                 [(store (rotr (loadi16 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>, OpSize;
 def ROR32mCL : I<0xD3, MRM1m, (outs), (ins i32mem:$dst),=20
                  "ror{l}\t{%cl, $dst|$dst, CL}",
-                 [(store (rotr (loadi32 addr:$dst), CL), addr:$dst)]>;
+                 [(store (rotr (loadi32 addr:$dst), CL), addr:$dst)],
+                 IIC_SR>;
 def ROR64mCL : RI<0xD3, MRM1m, (outs), (ins i64mem:$dst),=20
-                  "ror{q}\t{%cl, $dst|$dst, %CL}",
-                  [(store (rotr (loadi64 addr:$dst), CL), addr:$dst)]>;
+                  "ror{q}\t{%cl, $dst|$dst, CL}",
+                  [(store (rotr (loadi64 addr:$dst), CL), addr:$dst)],
+                  IIC_SR>;
 }
 def ROR8mi   : Ii8<0xC0, MRM1m, (outs), (ins i8mem :$dst, i8imm:$src),
                    "ror{b}\t{$src, $dst|$dst, $src}",
-               [(store (rotr (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+               [(store (rotr (loadi8 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+               IIC_SR>;
 def ROR16mi  : Ii8<0xC1, MRM1m, (outs), (ins i16mem:$dst, i8imm:$src),
                    "ror{w}\t{$src, $dst|$dst, $src}",
-              [(store (rotr (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>,
+              [(store (rotr (loadi16 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+              IIC_SR>,
                    OpSize;
 def ROR32mi  : Ii8<0xC1, MRM1m, (outs), (ins i32mem:$dst, i8imm:$src),
                    "ror{l}\t{$src, $dst|$dst, $src}",
-              [(store (rotr (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)]>;
+              [(store (rotr (loadi32 addr:$dst), (i8 imm:$src)), addr:$dst=
)],
+              IIC_SR>;
 def ROR64mi  : RIi8<0xC1, MRM1m, (outs), (ins i64mem:$dst, i8imm:$src),
                     "ror{q}\t{$src, $dst|$dst, $src}",
-                [(store (rotr (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)]>;
+                [(store (rotr (loadi64 addr:$dst), (i8 imm:$src)), addr:$d=
st)],
+                IIC_SR>;
=20
 // Rotate by 1
 def ROR8m1   : I<0xD0, MRM1m, (outs), (ins i8mem :$dst),
                  "ror{b}\t$dst",
-               [(store (rotr (loadi8 addr:$dst), (i8 1)), addr:$dst)]>;
+               [(store (rotr (loadi8 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>;
 def ROR16m1  : I<0xD1, MRM1m, (outs), (ins i16mem:$dst),
                  "ror{w}\t$dst",
-              [(store (rotr (loadi16 addr:$dst), (i8 1)), addr:$dst)]>,
+              [(store (rotr (loadi16 addr:$dst), (i8 1)), addr:$dst)],
+              IIC_SR>,
                    OpSize;
 def ROR32m1  : I<0xD1, MRM1m, (outs), (ins i32mem:$dst),
                  "ror{l}\t$dst",
-              [(store (rotr (loadi32 addr:$dst), (i8 1)), addr:$dst)]>;
+              [(store (rotr (loadi32 addr:$dst), (i8 1)), addr:$dst)],
+              IIC_SR>;
 def ROR64m1  : RI<0xD1, MRM1m, (outs), (ins i64mem:$dst),
                  "ror{q}\t$dst",
-               [(store (rotr (loadi64 addr:$dst), (i8 1)), addr:$dst)]>;
+               [(store (rotr (loadi64 addr:$dst), (i8 1)), addr:$dst)],
+               IIC_SR>;
=20
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -601,30 +684,36 @@
 def SHLD16rrCL : I<0xA5, MRMDestReg, (outs GR16:$dst),=20
                    (ins GR16:$src1, GR16:$src2),
                    "shld{w}\t{%cl, $src2, $dst|$dst, $src2, CL}",
-                   [(set GR16:$dst, (X86shld GR16:$src1, GR16:$src2, CL))]=
>,
+                   [(set GR16:$dst, (X86shld GR16:$src1, GR16:$src2, CL))],
+                    IIC_SHD16_REG_CL>,
                    TB, OpSize;
 def SHRD16rrCL : I<0xAD, MRMDestReg, (outs GR16:$dst),=20
                    (ins GR16:$src1, GR16:$src2),
                    "shrd{w}\t{%cl, $src2, $dst|$dst, $src2, CL}",
-                   [(set GR16:$dst, (X86shrd GR16:$src1, GR16:$src2, CL))]=
>,
+                   [(set GR16:$dst, (X86shrd GR16:$src1, GR16:$src2, CL))],
+                    IIC_SHD16_REG_CL>,
                    TB, OpSize;
 def SHLD32rrCL : I<0xA5, MRMDestReg, (outs GR32:$dst),=20
                    (ins GR32:$src1, GR32:$src2),
                    "shld{l}\t{%cl, $src2, $dst|$dst, $src2, CL}",
-                   [(set GR32:$dst, (X86shld GR32:$src1, GR32:$src2, CL))]=
>, TB;
+                   [(set GR32:$dst, (X86shld GR32:$src1, GR32:$src2, CL))],
+                    IIC_SHD32_REG_CL>, TB;
 def SHRD32rrCL : I<0xAD, MRMDestReg, (outs GR32:$dst),
                    (ins GR32:$src1, GR32:$src2),
                    "shrd{l}\t{%cl, $src2, $dst|$dst, $src2, CL}",
-                   [(set GR32:$dst, (X86shrd GR32:$src1, GR32:$src2, CL))]=
>, TB;
+                   [(set GR32:$dst, (X86shrd GR32:$src1, GR32:$src2, CL))],
+                   IIC_SHD32_REG_CL>, TB;
 def SHLD64rrCL : RI<0xA5, MRMDestReg, (outs GR64:$dst),=20
                     (ins GR64:$src1, GR64:$src2),
-                    "shld{q}\t{%cl, $src2, $dst|$dst, $src2, %CL}",
-                    [(set GR64:$dst, (X86shld GR64:$src1, GR64:$src2, CL))=
]>,=20
+                    "shld{q}\t{%cl, $src2, $dst|$dst, $src2, CL}",
+                    [(set GR64:$dst, (X86shld GR64:$src1, GR64:$src2, CL))=
],
+                    IIC_SHD64_REG_CL>,=20
                     TB;
 def SHRD64rrCL : RI<0xAD, MRMDestReg, (outs GR64:$dst),=20
                     (ins GR64:$src1, GR64:$src2),
-                    "shrd{q}\t{%cl, $src2, $dst|$dst, $src2, %CL}",
-                    [(set GR64:$dst, (X86shrd GR64:$src1, GR64:$src2, CL))=
]>,=20
+                    "shrd{q}\t{%cl, $src2, $dst|$dst, $src2, CL}",
+                    [(set GR64:$dst, (X86shrd GR64:$src1, GR64:$src2, CL))=
],
+                    IIC_SHD64_REG_CL>,=20
                     TB;
 }
=20
@@ -634,42 +723,42 @@
                      (ins GR16:$src1, GR16:$src2, i8imm:$src3),
                      "shld{w}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                      [(set GR16:$dst, (X86shld GR16:$src1, GR16:$src2,
-                                      (i8 imm:$src3)))]>,
+                                      (i8 imm:$src3)))], IIC_SHD16_REG_IM>,
                      TB, OpSize;
 def SHRD16rri8 : Ii8<0xAC, MRMDestReg,
                      (outs GR16:$dst),=20
                      (ins GR16:$src1, GR16:$src2, i8imm:$src3),
                      "shrd{w}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                      [(set GR16:$dst, (X86shrd GR16:$src1, GR16:$src2,
-                                      (i8 imm:$src3)))]>,
+                                      (i8 imm:$src3)))], IIC_SHD16_REG_IM>,
                      TB, OpSize;
 def SHLD32rri8 : Ii8<0xA4, MRMDestReg,
                      (outs GR32:$dst),=20
                      (ins GR32:$src1, GR32:$src2, i8imm:$src3),
                      "shld{l}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                      [(set GR32:$dst, (X86shld GR32:$src1, GR32:$src2,
-                                      (i8 imm:$src3)))]>,
+                                      (i8 imm:$src3)))], IIC_SHD32_REG_IM>,
                  TB;
 def SHRD32rri8 : Ii8<0xAC, MRMDestReg,
                      (outs GR32:$dst),=20
                      (ins GR32:$src1, GR32:$src2, i8imm:$src3),
                      "shrd{l}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                      [(set GR32:$dst, (X86shrd GR32:$src1, GR32:$src2,
-                                      (i8 imm:$src3)))]>,
+                                      (i8 imm:$src3)))], IIC_SHD32_REG_IM>,
                  TB;
 def SHLD64rri8 : RIi8<0xA4, MRMDestReg,
                       (outs GR64:$dst),=20
                       (ins GR64:$src1, GR64:$src2, i8imm:$src3),
                       "shld{q}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                       [(set GR64:$dst, (X86shld GR64:$src1, GR64:$src2,
-                                       (i8 imm:$src3)))]>,
+                                       (i8 imm:$src3)))], IIC_SHD64_REG_IM=
>,
                  TB;
 def SHRD64rri8 : RIi8<0xAC, MRMDestReg,
                       (outs GR64:$dst),=20
                       (ins GR64:$src1, GR64:$src2, i8imm:$src3),
                       "shrd{q}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                       [(set GR64:$dst, (X86shrd GR64:$src1, GR64:$src2,
-                                       (i8 imm:$src3)))]>,
+                                       (i8 imm:$src3)))], IIC_SHD64_REG_IM=
>,
                  TB;
 }
 } // Constraints =3D "$src =3D $dst"
@@ -678,69 +767,110 @@
 def SHLD16mrCL : I<0xA5, MRMDestMem, (outs), (ins i16mem:$dst, GR16:$src2),
                    "shld{w}\t{%cl, $src2, $dst|$dst, $src2, CL}",
                    [(store (X86shld (loadi16 addr:$dst), GR16:$src2, CL),
-                     addr:$dst)]>, TB, OpSize;
+                     addr:$dst)], IIC_SHD16_MEM_CL>, TB, OpSize;
 def SHRD16mrCL : I<0xAD, MRMDestMem, (outs), (ins i16mem:$dst, GR16:$src2),
                   "shrd{w}\t{%cl, $src2, $dst|$dst, $src2, CL}",
                   [(store (X86shrd (loadi16 addr:$dst), GR16:$src2, CL),
-                    addr:$dst)]>, TB, OpSize;
+                    addr:$dst)], IIC_SHD16_MEM_CL>, TB, OpSize;
=20
 def SHLD32mrCL : I<0xA5, MRMDestMem, (outs), (ins i32mem:$dst, GR32:$src2),
                    "shld{l}\t{%cl, $src2, $dst|$dst, $src2, CL}",
                    [(store (X86shld (loadi32 addr:$dst), GR32:$src2, CL),
-                     addr:$dst)]>, TB;
+                     addr:$dst)], IIC_SHD32_MEM_CL>, TB;
 def SHRD32mrCL : I<0xAD, MRMDestMem, (outs), (ins i32mem:$dst, GR32:$src2),
                   "shrd{l}\t{%cl, $src2, $dst|$dst, $src2, CL}",
                   [(store (X86shrd (loadi32 addr:$dst), GR32:$src2, CL),
-                    addr:$dst)]>, TB;
+                    addr:$dst)], IIC_SHD32_MEM_CL>, TB;
                    =20
 def SHLD64mrCL : RI<0xA5, MRMDestMem, (outs), (ins i64mem:$dst, GR64:$src2=
),
-                    "shld{q}\t{%cl, $src2, $dst|$dst, $src2, %CL}",
+                    "shld{q}\t{%cl, $src2, $dst|$dst, $src2, CL}",
                     [(store (X86shld (loadi64 addr:$dst), GR64:$src2, CL),
-                      addr:$dst)]>, TB;
+                      addr:$dst)], IIC_SHD64_MEM_CL>, TB;
 def SHRD64mrCL : RI<0xAD, MRMDestMem, (outs), (ins i64mem:$dst, GR64:$src2=
),
-                    "shrd{q}\t{%cl, $src2, $dst|$dst, $src2, %CL}",
+                    "shrd{q}\t{%cl, $src2, $dst|$dst, $src2, CL}",
                     [(store (X86shrd (loadi64 addr:$dst), GR64:$src2, CL),
-                      addr:$dst)]>, TB;
+                      addr:$dst)], IIC_SHD64_MEM_CL>, TB;
 }
=20
 def SHLD16mri8 : Ii8<0xA4, MRMDestMem,
                     (outs), (ins i16mem:$dst, GR16:$src2, i8imm:$src3),
                     "shld{w}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                     [(store (X86shld (loadi16 addr:$dst), GR16:$src2,
-                                      (i8 imm:$src3)), addr:$dst)]>,
+                                      (i8 imm:$src3)), addr:$dst)],
+                                      IIC_SHD16_MEM_IM>,
                     TB, OpSize;
 def SHRD16mri8 : Ii8<0xAC, MRMDestMem,=20
                      (outs), (ins i16mem:$dst, GR16:$src2, i8imm:$src3),
                      "shrd{w}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                     [(store (X86shrd (loadi16 addr:$dst), GR16:$src2,
-                                      (i8 imm:$src3)), addr:$dst)]>,
+                                      (i8 imm:$src3)), addr:$dst)],
+                                      IIC_SHD16_MEM_IM>,
                      TB, OpSize;
=20
 def SHLD32mri8 : Ii8<0xA4, MRMDestMem,
                     (outs), (ins i32mem:$dst, GR32:$src2, i8imm:$src3),
                     "shld{l}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                     [(store (X86shld (loadi32 addr:$dst), GR32:$src2,
-                                      (i8 imm:$src3)), addr:$dst)]>,
+                                      (i8 imm:$src3)), addr:$dst)],
+                                      IIC_SHD32_MEM_IM>,
                     TB;
 def SHRD32mri8 : Ii8<0xAC, MRMDestMem,=20
                      (outs), (ins i32mem:$dst, GR32:$src2, i8imm:$src3),
                      "shrd{l}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                      [(store (X86shrd (loadi32 addr:$dst), GR32:$src2,
-                                       (i8 imm:$src3)), addr:$dst)]>,
+                                       (i8 imm:$src3)), addr:$dst)],
+                                       IIC_SHD32_MEM_IM>,
                      TB;
=20
 def SHLD64mri8 : RIi8<0xA4, MRMDestMem,
                       (outs), (ins i64mem:$dst, GR64:$src2, i8imm:$src3),
                       "shld{q}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                       [(store (X86shld (loadi64 addr:$dst), GR64:$src2,
-                                       (i8 imm:$src3)), addr:$dst)]>,
+                                       (i8 imm:$src3)), addr:$dst)],
+                                       IIC_SHD64_MEM_IM>,
                  TB;
 def SHRD64mri8 : RIi8<0xAC, MRMDestMem,=20
                       (outs), (ins i64mem:$dst, GR64:$src2, i8imm:$src3),
                       "shrd{q}\t{$src3, $src2, $dst|$dst, $src2, $src3}",
                       [(store (X86shrd (loadi64 addr:$dst), GR64:$src2,
-                                       (i8 imm:$src3)), addr:$dst)]>,
+                                       (i8 imm:$src3)), addr:$dst)],
+                                       IIC_SHD64_MEM_IM>,
                  TB;
=20
 } // Defs =3D [EFLAGS]
=20
+multiclass bmi_rotate<string asm, RegisterClass RC, X86MemOperand x86memop=
> {
+let neverHasSideEffects =3D 1 in {
+  def ri : Ii8<0xF0, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, i8imm:$src2=
),
+               !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
),
+               []>, TAXD, VEX;
+  let mayLoad =3D 1 in
+  def mi : Ii8<0xF0, MRMSrcMem, (outs RC:$dst),
+               (ins x86memop:$src1, i8imm:$src2),
+               !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"=
),
+               []>, TAXD, VEX;
+}
+}
+
+multiclass bmi_shift<string asm, RegisterClass RC, X86MemOperand x86memop>=
 {
+let neverHasSideEffects =3D 1 in {
+  def rr : I<0xF7, MRMSrcReg, (outs RC:$dst), (ins RC:$src1, RC:$src2),
+             !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),=
 []>,
+             VEX_4VOp3;
+  let mayLoad =3D 1 in
+  def rm : I<0xF7, MRMSrcMem, (outs RC:$dst), (ins x86memop:$src1, RC:$src=
2),
+             !strconcat(asm, "\t{$src2, $src1, $dst|$dst, $src1, $src2}"),=
 []>,
+             VEX_4VOp3;
+}
+}
+
+let Predicates =3D [HasBMI2] in {
+  defm RORX32 : bmi_rotate<"rorx{l}", GR32, i32mem>;
+  defm RORX64 : bmi_rotate<"rorx{q}", GR64, i64mem>, VEX_W;
+  defm SARX32 : bmi_shift<"sarx{l}", GR32, i32mem>, T8XS;
+  defm SARX64 : bmi_shift<"sarx{q}", GR64, i64mem>, T8XS, VEX_W;
+  defm SHRX32 : bmi_shift<"shrx{l}", GR32, i32mem>, T8XD;
+  defm SHRX64 : bmi_shift<"shrx{q}", GR64, i64mem>, T8XD, VEX_W;
+  defm SHLX32 : bmi_shift<"shlx{l}", GR32, i32mem>, T8, OpSize;
+  defm SHLX64 : bmi_shift<"shlx{q}", GR64, i64mem>, T8, OpSize, VEX_W;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strSystem.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrSystem.td	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrSystem.td	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86InstrSystem.td - System Instructions -------------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86InstrSystem.td - System Instructions ------------*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the X86 instructions that are generally used in
@@ -45,18 +45,17 @@
=20
=20
 def SYSCALL  : I<0x05, RawFrm, (outs), (ins), "syscall", []>, TB;
-def SYSRETL  : I<0x07, RawFrm, (outs), (ins), "sysretl", []>, TB;
-def SYSRETQ  :RI<0x07, RawFrm, (outs), (ins), "sysretq", []>, TB,
+def SYSRET   : I<0x07, RawFrm, (outs), (ins), "sysret{l}", []>, TB;
+def SYSRET64 :RI<0x07, RawFrm, (outs), (ins), "sysret{q}", []>, TB,
                Requires<[In64BitMode]>;
=20
 def SYSENTER : I<0x34, RawFrm, (outs), (ins), "sysenter", []>, TB;
                 =20
-def SYSEXIT   : I<0x35, RawFrm, (outs), (ins), "sysexit", []>, TB,
-                Requires<[In32BitMode]>;
-def SYSEXIT64 :RI<0x35, RawFrm, (outs), (ins), "sysexit", []>, TB,
+def SYSEXIT   : I<0x35, RawFrm, (outs), (ins), "sysexit{l}", []>, TB;
+def SYSEXIT64 :RI<0x35, RawFrm, (outs), (ins), "sysexit{q}", []>, TB,
                 Requires<[In64BitMode]>;
=20
-def IRET16 : I<0xcf, RawFrm, (outs), (ins), "iretw", []>, OpSize;
+def IRET16 : I<0xcf, RawFrm, (outs), (ins), "iret{w}", []>, OpSize;
 def IRET32 : I<0xcf, RawFrm, (outs), (ins), "iret{l|d}", []>;
 def IRET64 : RI<0xcf, RawFrm, (outs), (ins), "iretq", []>,
              Requires<[In64BitMode]>;
@@ -215,18 +214,18 @@
 def INVLPG : I<0x01, MRM7m, (outs), (ins i8mem:$addr), "invlpg\t$addr", []=
>, TB;
=20
 def STR16r : I<0x00, MRM1r, (outs GR16:$dst), (ins),
-               "str{w}\t{$dst}", []>, TB, OpSize;
+               "str{w}\t$dst", []>, TB, OpSize;
 def STR32r : I<0x00, MRM1r, (outs GR32:$dst), (ins),
-               "str{l}\t{$dst}", []>, TB;
+               "str{l}\t$dst", []>, TB;
 def STR64r : RI<0x00, MRM1r, (outs GR64:$dst), (ins),
-                "str{q}\t{$dst}", []>, TB;
+                "str{q}\t$dst", []>, TB;
 def STRm   : I<0x00, MRM1m, (outs i16mem:$dst), (ins),
-               "str{w}\t{$dst}", []>, TB;
+               "str{w}\t$dst", []>, TB;
=20
 def LTRr : I<0x00, MRM3r, (outs), (ins GR16:$src),
-             "ltr{w}\t{$src}", []>, TB;
+             "ltr{w}\t$src", []>, TB;
 def LTRm : I<0x00, MRM3m, (outs), (ins i16mem:$src),
-             "ltr{w}\t{$src}", []>, TB;
+             "ltr{w}\t$src", []>, TB;
             =20
 def PUSHCS16 : I<0x0E, RawFrm, (outs), (ins),
                  "push{w}\t{%cs|CS}", []>, Requires<[In32BitMode]>, OpSize;
@@ -447,21 +446,38 @@
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // FS/GS Base Instructions
-let Predicates =3D [In64BitMode] in {
+let Predicates =3D [HasFSGSBase, In64BitMode] in {
   def RDFSBASE : I<0xAE, MRM0r, (outs GR32:$dst), (ins),
-                   "rdfsbase{l}\t$dst", []>, TB, XS;
+                   "rdfsbase{l}\t$dst",
+                   [(set GR32:$dst, (int_x86_rdfsbase_32))]>, TB, XS;
   def RDFSBASE64 : RI<0xAE, MRM0r, (outs GR64:$dst), (ins),
-                     "rdfsbase{q}\t$dst", []>, TB, XS;
+                     "rdfsbase{q}\t$dst",
+                     [(set GR64:$dst, (int_x86_rdfsbase_64))]>, TB, XS;
   def RDGSBASE : I<0xAE, MRM1r, (outs GR32:$dst), (ins),
-                   "rdgsbase{l}\t$dst", []>, TB, XS;
+                   "rdgsbase{l}\t$dst",
+                   [(set GR32:$dst, (int_x86_rdgsbase_32))]>, TB, XS;
   def RDGSBASE64 : RI<0xAE, MRM1r, (outs GR64:$dst), (ins),
-                     "rdgsbase{q}\t$dst", []>, TB, XS;
-  def WRFSBASE : I<0xAE, MRM2r, (outs), (ins GR32:$dst),
-                   "wrfsbase{l}\t$dst", []>, TB, XS;
-  def WRFSBASE64 : RI<0xAE, MRM2r, (outs), (ins GR64:$dst),
-                   "wrfsbase{q}\t$dst", []>, TB, XS;
-  def WRGSBASE : I<0xAE, MRM3r, (outs), (ins GR32:$dst),
-                   "wrgsbase{l}\t$dst", []>, TB, XS;
-  def WRGSBASE64 : RI<0xAE, MRM3r, (outs), (ins GR64:$dst),
-                    "wrgsbase{q}\t$dst", []>, TB, XS;
+                     "rdgsbase{q}\t$dst",
+                     [(set GR64:$dst, (int_x86_rdgsbase_64))]>, TB, XS;
+  def WRFSBASE : I<0xAE, MRM2r, (outs), (ins GR32:$src),
+                   "wrfsbase{l}\t$src",
+                   [(int_x86_wrfsbase_32 GR32:$src)]>, TB, XS;
+  def WRFSBASE64 : RI<0xAE, MRM2r, (outs), (ins GR64:$src),
+                      "wrfsbase{q}\t$src",
+                      [(int_x86_wrfsbase_64 GR64:$src)]>, TB, XS;
+  def WRGSBASE : I<0xAE, MRM3r, (outs), (ins GR32:$src),
+                   "wrgsbase{l}\t$src",
+                   [(int_x86_wrgsbase_32 GR32:$src)]>, TB, XS;
+  def WRGSBASE64 : RI<0xAE, MRM3r, (outs), (ins GR64:$src),
+                      "wrgsbase{q}\t$src",
+                      [(int_x86_wrgsbase_64 GR64:$src)]>, TB, XS;
 }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// INVPCID Instruction
+def INVPCID32 : I<0x82, MRMSrcMem, (outs), (ins GR32:$src1, i128mem:$src2),
+                "invpcid {$src2, $src1|$src1, $src2}", []>, OpSize, T8,
+                Requires<[In32BitMode]>;
+def INVPCID64 : I<0x82, MRMSrcMem, (outs), (ins GR64:$src1, i128mem:$src2),
+                "invpcid {$src2, $src1|$src1, $src2}", []>, OpSize, T8,
+                Requires<[In64BitMode]>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86In=
strVMX.td
--- a/head/contrib/llvm/lib/Target/X86/X86InstrVMX.td	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86InstrVMX.td	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D- X86InstrVMX.td - VMX Instruction Set Extension ------*- table=
gen -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86InstrVMX.td - VMX Instruction Set Extension -----*- table=
gen -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file describes the instructions that make up the Intel VMX instruc=
tion
@@ -17,18 +17,24 @@
=20
 // 66 0F 38 80
 def INVEPT32 : I<0x80, MRMSrcMem, (outs), (ins GR32:$src1, i128mem:$src2),
-               "invept {$src2, $src1|$src1, $src2}", []>, OpSize, T8;
+               "invept {$src2, $src1|$src1, $src2}", []>, OpSize, T8,
+               Requires<[In32BitMode]>;
 def INVEPT64 : I<0x80, MRMSrcMem, (outs), (ins GR64:$src1, i128mem:$src2),
-               "invept {$src2, $src1|$src1, $src2}", []>, OpSize, T8;
+               "invept {$src2, $src1|$src1, $src2}", []>, OpSize, T8,
+               Requires<[In64BitMode]>;
 // 66 0F 38 81
 def INVVPID32 : I<0x81, MRMSrcMem, (outs), (ins GR32:$src1, i128mem:$src2),
-                "invvpid {$src2, $src1|$src1, $src2}", []>, OpSize, T8;
+                "invvpid {$src2, $src1|$src1, $src2}", []>, OpSize, T8,
+                Requires<[In32BitMode]>;
 def INVVPID64 : I<0x81, MRMSrcMem, (outs), (ins GR64:$src1, i128mem:$src2),
-                "invvpid {$src2, $src1|$src1, $src2}", []>, OpSize, T8;
+                "invvpid {$src2, $src1|$src1, $src2}", []>, OpSize, T8,
+                Requires<[In64BitMode]>;
 // 0F 01 C1
 def VMCALL : I<0x01, MRM_C1, (outs), (ins), "vmcall", []>, TB;
 def VMCLEARm : I<0xC7, MRM6m, (outs), (ins i64mem:$vmcs),
   "vmclear\t$vmcs", []>, OpSize, TB;
+// OF 01 D4
+def VMFUNC : I<0x01, MRM_D4, (outs), (ins), "vmfunc", []>, TB;
 // 0F 01 C2
 def VMLAUNCH : I<0x01, MRM_C2, (outs), (ins), "vmlaunch", []>, TB;
 // 0F 01 C3
@@ -38,23 +44,23 @@
 def VMPTRSTm : I<0xC7, MRM7m, (outs i64mem:$vmcs), (ins),
   "vmptrst\t$vmcs", []>, TB;
 def VMREAD64rm : I<0x78, MRMDestMem, (outs i64mem:$dst), (ins GR64:$src),
-  "vmread{q}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmread{q}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In64BitMode]>;
 def VMREAD64rr : I<0x78, MRMDestReg, (outs GR64:$dst), (ins GR64:$src),
-  "vmread{q}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmread{q}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In64BitMode]>;
 def VMREAD32rm : I<0x78, MRMDestMem, (outs i32mem:$dst), (ins GR32:$src),
-  "vmread{l}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmread{l}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In32BitMode]>;
 def VMREAD32rr : I<0x78, MRMDestReg, (outs GR32:$dst), (ins GR32:$src),
-  "vmread{l}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmread{l}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In32BitMode]>;
 def VMWRITE64rm : I<0x79, MRMSrcMem, (outs GR64:$dst), (ins i64mem:$src),
-  "vmwrite{q}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmwrite{q}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In64BitMode]>;
 def VMWRITE64rr : I<0x79, MRMSrcReg, (outs GR64:$dst), (ins GR64:$src),
-  "vmwrite{q}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmwrite{q}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In64BitMode]>;
 def VMWRITE32rm : I<0x79, MRMSrcMem, (outs GR32:$dst), (ins i32mem:$src),
-  "vmwrite{l}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmwrite{l}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In32BitMode]>;
 def VMWRITE32rr : I<0x79, MRMSrcReg, (outs GR32:$dst), (ins GR32:$src),
-  "vmwrite{l}\t{$src, $dst|$dst, $src}", []>, TB;
+  "vmwrite{l}\t{$src, $dst|$dst, $src}", []>, TB, Requires<[In32BitMode]>;
 // 0F 01 C4
 def VMXOFF : I<0x01, MRM_C4, (outs), (ins), "vmxoff", []>, TB;
 def VMXON : I<0xC7, MRM6m, (outs), (ins i64mem:$vmxon),
-  "vmxon\t{$vmxon}", []>, XS;
+  "vmxon\t$vmxon", []>, XS;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86JI=
TInfo.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86JITInfo.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86JITInfo.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -300,7 +300,10 @@
     SIZE(X86CompilationCallback_SSE)
   );
 # else
-  void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr);
+  // the following function is called only from this translation unit,
+  // unless we are under 64bit Windows with MSC, where there is
+  // no support for inline assembly
+  static void X86CompilationCallback2(intptr_t *StackPtr, intptr_t RetAddr=
);
=20
   _declspec(naked) void X86CompilationCallback(void) {
     __asm {
@@ -424,7 +427,9 @@
=20
 TargetJITInfo::LazyResolverFn
 X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
+  TsanIgnoreWritesBegin();
   JITCompilerFunction =3D F;
+  TsanIgnoreWritesEnd();
=20
 #if defined (X86_32_JIT) && !defined (_MSC_VER)
   if (Subtarget->hasSSE1())
@@ -569,6 +574,5 @@
   return TLSOffset;
 #else
   llvm_unreachable("Cannot allocate thread local storage on this arch!");
-  return 0;
 #endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86JI=
TInfo.h
--- a/head/contrib/llvm/lib/Target/X86/X86JITInfo.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86JITInfo.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86JITInfo.h - X86 implementation of the JIT interface  --*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86JITInfo.h - X86 implementation of the JIT interface --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86MC=
InstLower.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86MCInstLower.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86MCInstLower.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -12,10 +12,11 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "InstPrinter/X86ATTInstPrinter.h"
 #include "X86MCInstLower.h"
 #include "X86AsmPrinter.h"
 #include "X86COFFMachineModuleInfo.h"
+#include "InstPrinter/X86ATTInstPrinter.h"
+#include "llvm/Type.h"
 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCContext.h"
@@ -26,7 +27,6 @@
 #include "llvm/Target/Mangler.h"
 #include "llvm/Support/FormattedStream.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/Type.h"
 using namespace llvm;
=20
 X86MCInstLower::X86MCInstLower(Mangler *mang, const MachineFunction &mf,
@@ -154,6 +154,7 @@
                                                            Ctx),
                                    Ctx);
     break;
+  case X86II::MO_SECREL:    RefKind =3D MCSymbolRefExpr::VK_SECREL; break;
   case X86II::MO_TLSGD:     RefKind =3D MCSymbolRefExpr::VK_TLSGD; break;
   case X86II::MO_GOTTPOFF:  RefKind =3D MCSymbolRefExpr::VK_GOTTPOFF; brea=
k;
   case X86II::MO_INDNTPOFF: RefKind =3D MCSymbolRefExpr::VK_INDNTPOFF; bre=
ak;
@@ -230,7 +231,8 @@
 /// a short fixed-register form.
 static void SimplifyShortImmForm(MCInst &Inst, unsigned Opcode) {
   unsigned ImmOp =3D Inst.getNumOperands() - 1;
-  assert(Inst.getOperand(0).isReg() && Inst.getOperand(ImmOp).isImm() &&
+  assert(Inst.getOperand(0).isReg() &&
+         (Inst.getOperand(ImmOp).isImm() || Inst.getOperand(ImmOp).isExpr(=
)) &&
          ((Inst.getNumOperands() =3D=3D 3 && Inst.getOperand(1).isReg() &&
            Inst.getOperand(0).getReg() =3D=3D Inst.getOperand(1).getReg())=
 ||
           Inst.getNumOperands() =3D=3D 2) && "Unexpected instruction!");
@@ -335,6 +337,9 @@
       MCOp =3D LowerSymbolOperand(MO,
                      AsmPrinter.GetBlockAddressSymbol(MO.getBlockAddress()=
));
       break;
+    case MachineOperand::MO_RegisterMask:
+      // Ignore call clobbers.
+      continue;
     }
    =20
     OutMI.addOperand(MCOp);
@@ -368,14 +373,12 @@
   case X86::SETB_C64r:    LowerUnaryToTwoAddr(OutMI, X86::SBB64rr); break;
   case X86::MOV8r0:       LowerUnaryToTwoAddr(OutMI, X86::XOR8rr); break;
   case X86::MOV32r0:      LowerUnaryToTwoAddr(OutMI, X86::XOR32rr); break;
-  case X86::FsFLD0SS:      LowerUnaryToTwoAddr(OutMI, X86::PXORrr); break;
-  case X86::FsFLD0SD:      LowerUnaryToTwoAddr(OutMI, X86::PXORrr); break;
-  case X86::VFsFLD0SS:     LowerUnaryToTwoAddr(OutMI, X86::VPXORrr); break;
-  case X86::VFsFLD0SD:     LowerUnaryToTwoAddr(OutMI, X86::VPXORrr); break;
   case X86::V_SETALLONES:  LowerUnaryToTwoAddr(OutMI, X86::PCMPEQDrr); bre=
ak;
   case X86::AVX_SET0PSY:   LowerUnaryToTwoAddr(OutMI, X86::VXORPSYrr); bre=
ak;
   case X86::AVX_SET0PDY:   LowerUnaryToTwoAddr(OutMI, X86::VXORPDYrr); bre=
ak;
   case X86::AVX_SETALLONES:  LowerUnaryToTwoAddr(OutMI, X86::VPCMPEQDrr); =
break;
+  case X86::AVX2_SETALLONES: LowerUnaryToTwoAddr(OutMI, X86::VPCMPEQDYrr);=
break;
+  case X86::AVX2_SET0:     LowerUnaryToTwoAddr(OutMI, X86::VPXORYrr); brea=
k;
=20
   case X86::MOV16r0:
     LowerSubReg32_Op0(OutMI, X86::MOV32r0);   // MOV16r0 -> MOV32r0
@@ -386,14 +389,12 @@
     LowerUnaryToTwoAddr(OutMI, X86::XOR32rr); // MOV32r0 -> XOR32rr
     break;
=20
-  // TAILJMPr64, [WIN]CALL64r, [WIN]CALL64pcrel32 - These instructions have
-  // register inputs modeled as normal uses instead of implicit uses.  As =
such,
-  // truncate off all but the first operand (the callee).  FIXME: Change i=
sel.
+  // TAILJMPr64, CALL64r, CALL64pcrel32 - These instructions have register
+  // inputs modeled as normal uses instead of implicit uses.  As such, tru=
ncate
+  // off all but the first operand (the callee).  FIXME: Change isel.
   case X86::TAILJMPr64:
   case X86::CALL64r:
-  case X86::CALL64pcrel32:
-  case X86::WINCALL64r:
-  case X86::WINCALL64pcrel32: {
+  case X86::CALL64pcrel32: {
     unsigned Opcode =3D OutMI.getOpcode();
     MCOperand Saved =3D OutMI.getOperand(0);
     OutMI =3D MCInst();
@@ -415,7 +416,7 @@
   case X86::TAILJMPd64: {
     unsigned Opcode;
     switch (OutMI.getOpcode()) {
-    default: assert(0 && "Invalid opcode");
+    default: llvm_unreachable("Invalid opcode");
     case X86::TAILJMPr: Opcode =3D X86::JMP32r; break;
     case X86::TAILJMPd:
     case X86::TAILJMPd64: Opcode =3D X86::JMP_1; break;
@@ -527,6 +528,22 @@
   case X86::XOR16ri:    SimplifyShortImmForm(OutMI, X86::XOR16i16);  break;
   case X86::XOR32ri:    SimplifyShortImmForm(OutMI, X86::XOR32i32);  break;
   case X86::XOR64ri32:  SimplifyShortImmForm(OutMI, X86::XOR64i32);  break;
+
+  case X86::MORESTACK_RET:
+    OutMI.setOpcode(X86::RET);
+    break;
+
+  case X86::MORESTACK_RET_RESTORE_R10: {
+    MCInst retInst;
+
+    OutMI.setOpcode(X86::MOV64rr);
+    OutMI.addOperand(MCOperand::CreateReg(X86::R10));
+    OutMI.addOperand(MCOperand::CreateReg(X86::RAX));
+
+    retInst.setOpcode(X86::RET);
+    AsmPrinter.OutStreamer.EmitInstruction(retInst);
+    break;
+  }
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86MC=
InstLower.h
--- a/head/contrib/llvm/lib/Target/X86/X86MCInstLower.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86MCInstLower.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- X86MCInstLower.h - Lower MachineInstr to MCInst ------------=
-------=3D=3D=3D//
+//=3D=3D=3D-- X86MCInstLower.h - Lower MachineInstr to MCInst ---------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Ma=
chineFunctionInfo.h
--- a/head/contrib/llvm/lib/Target/X86/X86MachineFunctionInfo.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86MachineFunctionInfo.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-//=3D=3D=3D=3D- X86MachineFuctionInfo.h - X86 machine function info -----*=
- C++ -*-=3D=3D=3D//
-//=20
+//=3D=3D=3D-- X86MachineFuctionInfo.h - X86 machine function info -----*- =
C++ -*-=3D=3D=3D//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file is distributed under the University of Illinois Open Source
 // License. See LICENSE.TXT for details.
-//=20
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
 // This file declares X86-specific per-machine-function information.
@@ -21,6 +21,8 @@
 /// X86MachineFunctionInfo - This class is derived from MachineFunction and
 /// contains private X86 target-specific information for each MachineFunct=
ion.
 class X86MachineFunctionInfo : public MachineFunctionInfo {
+  virtual void anchor();
+
   /// ForceFramePointer - True if the function is required to use of frame
   /// pointer for reasons other than it containing dynamic allocation or=20
   /// that FP eliminatation is turned off. For example, Cygwin main functi=
on
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Re=
gisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86RegisterInfo.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86RegisterInfo.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86RegisterInfo.cpp - X86 Register Information -----------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86RegisterInfo.cpp - X86 Register Information -------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -13,8 +13,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "X86RegisterInfo.h"
 #include "X86.h"
-#include "X86RegisterInfo.h"
 #include "X86InstrBuilder.h"
 #include "X86MachineFunctionInfo.h"
 #include "X86Subtarget.h"
@@ -127,121 +127,13 @@
 X86RegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
                                           const TargetRegisterClass *B,
                                           unsigned SubIdx) const {
-  switch (SubIdx) {
-  default: return 0;
-  case X86::sub_8bit:
-    if (B =3D=3D &X86::GR8RegClass) {
-      if (A->getSize() =3D=3D 2 || A->getSize() =3D=3D 4 || A->getSize() =
=3D=3D 8)
-        return A;
-    } else if (B =3D=3D &X86::GR8_ABCD_LRegClass || B =3D=3D &X86::GR8_ABC=
D_HRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_ABCDRegClass =
||
-          A =3D=3D &X86::GR64_NOREXRegClass ||
-          A =3D=3D &X86::GR64_NOSPRegClass ||
-          A =3D=3D &X86::GR64_NOREX_NOSPRegClass)
-        return &X86::GR64_ABCDRegClass;
-      else if (A =3D=3D &X86::GR32RegClass || A =3D=3D &X86::GR32_ABCDRegC=
lass ||
-               A =3D=3D &X86::GR32_NOREXRegClass ||
-               A =3D=3D &X86::GR32_NOSPRegClass)
-        return &X86::GR32_ABCDRegClass;
-      else if (A =3D=3D &X86::GR16RegClass || A =3D=3D &X86::GR16_ABCDRegC=
lass ||
-               A =3D=3D &X86::GR16_NOREXRegClass)
-        return &X86::GR16_ABCDRegClass;
-    } else if (B =3D=3D &X86::GR8_NOREXRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_NOREXRegClass=
 ||
-          A =3D=3D &X86::GR64_NOSPRegClass || A =3D=3D &X86::GR64_NOREX_NO=
SPRegClass)
-        return &X86::GR64_NOREXRegClass;
-      else if (A =3D=3D &X86::GR64_ABCDRegClass)
-        return &X86::GR64_ABCDRegClass;
-      else if (A =3D=3D &X86::GR32RegClass || A =3D=3D &X86::GR32_NOREXReg=
Class ||
-               A =3D=3D &X86::GR32_NOSPRegClass)
-        return &X86::GR32_NOREXRegClass;
-      else if (A =3D=3D &X86::GR32_ABCDRegClass)
-        return &X86::GR32_ABCDRegClass;
-      else if (A =3D=3D &X86::GR16RegClass || A =3D=3D &X86::GR16_NOREXReg=
Class)
-        return &X86::GR16_NOREXRegClass;
-      else if (A =3D=3D &X86::GR16_ABCDRegClass)
-        return &X86::GR16_ABCDRegClass;
-    }
-    break;
-  case X86::sub_8bit_hi:
-    if (B->hasSubClassEq(&X86::GR8_ABCD_HRegClass))
-      switch (A->getSize()) {
-        case 2: return getCommonSubClass(A, &X86::GR16_ABCDRegClass);
-        case 4: return getCommonSubClass(A, &X86::GR32_ABCDRegClass);
-        case 8: return getCommonSubClass(A, &X86::GR64_ABCDRegClass);
-        default: return 0;
-      }
-    break;
-  case X86::sub_16bit:
-    if (B =3D=3D &X86::GR16RegClass) {
-      if (A->getSize() =3D=3D 4 || A->getSize() =3D=3D 8)
-        return A;
-    } else if (B =3D=3D &X86::GR16_ABCDRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_ABCDRegClass =
||
-          A =3D=3D &X86::GR64_NOREXRegClass ||
-          A =3D=3D &X86::GR64_NOSPRegClass ||
-          A =3D=3D &X86::GR64_NOREX_NOSPRegClass)
-        return &X86::GR64_ABCDRegClass;
-      else if (A =3D=3D &X86::GR32RegClass || A =3D=3D &X86::GR32_ABCDRegC=
lass ||
-               A =3D=3D &X86::GR32_NOREXRegClass || A =3D=3D &X86::GR32_NO=
SPRegClass)
-        return &X86::GR32_ABCDRegClass;
-    } else if (B =3D=3D &X86::GR16_NOREXRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_NOREXRegClass=
 ||
-          A =3D=3D &X86::GR64_NOSPRegClass || A =3D=3D &X86::GR64_NOREX_NO=
SPRegClass)
-        return &X86::GR64_NOREXRegClass;
-      else if (A =3D=3D &X86::GR64_ABCDRegClass)
-        return &X86::GR64_ABCDRegClass;
-      else if (A =3D=3D &X86::GR32RegClass || A =3D=3D &X86::GR32_NOREXReg=
Class ||
-               A =3D=3D &X86::GR32_NOSPRegClass)
-        return &X86::GR32_NOREXRegClass;
-      else if (A =3D=3D &X86::GR32_ABCDRegClass)
-        return &X86::GR64_ABCDRegClass;
-    }
-    break;
-  case X86::sub_32bit:
-    if (B =3D=3D &X86::GR32RegClass) {
-      if (A->getSize() =3D=3D 8)
-        return A;
-    } else if (B =3D=3D &X86::GR32_NOSPRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_NOSPRegClass)
-        return &X86::GR64_NOSPRegClass;
-      if (A->getSize() =3D=3D 8)
-        return getCommonSubClass(A, &X86::GR64_NOSPRegClass);
-    } else if (B =3D=3D &X86::GR32_ABCDRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_ABCDRegClass =
||
-          A =3D=3D &X86::GR64_NOREXRegClass ||
-          A =3D=3D &X86::GR64_NOSPRegClass ||
-          A =3D=3D &X86::GR64_NOREX_NOSPRegClass)
-        return &X86::GR64_ABCDRegClass;
-    } else if (B =3D=3D &X86::GR32_NOREXRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_NOREXRegClass)
-        return &X86::GR64_NOREXRegClass;
-      else if (A =3D=3D &X86::GR64_NOSPRegClass || A =3D=3D &X86::GR64_NOR=
EX_NOSPRegClass)
-        return &X86::GR64_NOREX_NOSPRegClass;
-      else if (A =3D=3D &X86::GR64_ABCDRegClass)
-        return &X86::GR64_ABCDRegClass;
-    } else if (B =3D=3D &X86::GR32_NOREX_NOSPRegClass) {
-      if (A =3D=3D &X86::GR64RegClass || A =3D=3D &X86::GR64_NOREXRegClass=
 ||
-          A =3D=3D &X86::GR64_NOSPRegClass || A =3D=3D &X86::GR64_NOREX_NO=
SPRegClass)
-        return &X86::GR64_NOREX_NOSPRegClass;
-      else if (A =3D=3D &X86::GR64_ABCDRegClass)
-        return &X86::GR64_ABCDRegClass;
-    }
-    break;
-  case X86::sub_ss:
-    if (B =3D=3D &X86::FR32RegClass)
-      return A;
-    break;
-  case X86::sub_sd:
-    if (B =3D=3D &X86::FR64RegClass)
-      return A;
-    break;
-  case X86::sub_xmm:
-    if (B =3D=3D &X86::VR128RegClass)
-      return A;
-    break;
+  // The sub_8bit sub-register index is more constrained in 32-bit mode.
+  if (!Is64Bit && SubIdx =3D=3D X86::sub_8bit) {
+    A =3D X86GenRegisterInfo::getSubClassWithSubReg(A, X86::sub_8bit_hi);
+    if (!A)
+      return 0;
   }
-  return 0;
+  return X86GenRegisterInfo::getMatchingSuperRegClass(A, B, SubIdx);
 }
=20
 const TargetRegisterClass*
@@ -334,7 +226,7 @@
   }
 }
=20
-const unsigned *
+const uint16_t *
 X86RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
   bool callsEHReturn =3D false;
   bool ghcCall =3D false;
@@ -345,45 +237,29 @@
     ghcCall =3D (F ? F->getCallingConv() =3D=3D CallingConv::GHC : false);
   }
=20
-  static const unsigned GhcCalleeSavedRegs[] =3D {
-    0
-  };
+  if (ghcCall)
+    return CSR_Ghc_SaveList;
+  if (Is64Bit) {
+    if (IsWin64)
+      return CSR_Win64_SaveList;
+    if (callsEHReturn)
+      return CSR_64EHRet_SaveList;
+    return CSR_64_SaveList;
+  }
+  if (callsEHReturn)
+    return CSR_32EHRet_SaveList;
+  return CSR_32_SaveList;
+}
=20
-  static const unsigned CalleeSavedRegs32Bit[] =3D {
-    X86::ESI, X86::EDI, X86::EBX, X86::EBP,  0
-  };
-
-  static const unsigned CalleeSavedRegs32EHRet[] =3D {
-    X86::EAX, X86::EDX, X86::ESI, X86::EDI, X86::EBX, X86::EBP,  0
-  };
-
-  static const unsigned CalleeSavedRegs64Bit[] =3D {
-    X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
-  };
-
-  static const unsigned CalleeSavedRegs64EHRet[] =3D {
-    X86::RAX, X86::RDX, X86::RBX, X86::R12,
-    X86::R13, X86::R14, X86::R15, X86::RBP, 0
-  };
-
-  static const unsigned CalleeSavedRegsWin64[] =3D {
-    X86::RBX,   X86::RBP,   X86::RDI,   X86::RSI,
-    X86::R12,   X86::R13,   X86::R14,   X86::R15,
-    X86::XMM6,  X86::XMM7,  X86::XMM8,  X86::XMM9,
-    X86::XMM10, X86::XMM11, X86::XMM12, X86::XMM13,
-    X86::XMM14, X86::XMM15, 0
-  };
-
-  if (ghcCall) {
-    return GhcCalleeSavedRegs;
-  } else if (Is64Bit) {
-    if (IsWin64)
-      return CalleeSavedRegsWin64;
-    else
-      return (callsEHReturn ? CalleeSavedRegs64EHRet : CalleeSavedRegs64Bi=
t);
-  } else {
-    return (callsEHReturn ? CalleeSavedRegs32EHRet : CalleeSavedRegs32Bit);
-  }
+const uint32_t*
+X86RegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
+  if (CC =3D=3D CallingConv::GHC)
+    return CSR_Ghc_RegMask;
+  if (!Is64Bit)
+    return CSR_32_RegMask;
+  if (IsWin64)
+    return CSR_Win64_RegMask;
+  return CSR_64_RegMask;
 }
=20
 BitVector X86RegisterInfo::getReservedRegs(const MachineFunction &MF) cons=
t {
@@ -428,16 +304,16 @@
=20
     for (unsigned n =3D 0; n !=3D 8; ++n) {
       // R8, R9, ...
-      const unsigned GPR64[] =3D {
+      static const uint16_t GPR64[] =3D {
         X86::R8,  X86::R9,  X86::R10, X86::R11,
         X86::R12, X86::R13, X86::R14, X86::R15
       };
-      for (const unsigned *AI =3D getOverlaps(GPR64[n]); unsigned Reg =3D =
*AI; ++AI)
+      for (const uint16_t *AI =3D getOverlaps(GPR64[n]); unsigned Reg =3D =
*AI; ++AI)
         Reserved.set(Reg);
=20
       // XMM8, XMM9, ...
       assert(X86::XMM15 =3D=3D X86::XMM8+7);
-      for (const unsigned *AI =3D getOverlaps(X86::XMM8 + n); unsigned Reg=
 =3D *AI;
+      for (const uint16_t *AI =3D getOverlaps(X86::XMM8 + n); unsigned Reg=
 =3D *AI;
            ++AI)
         Reserved.set(Reg);
     }
@@ -452,7 +328,7 @@
=20
 bool X86RegisterInfo::canRealignStack(const MachineFunction &MF) const {
   const MachineFrameInfo *MFI =3D MF.getFrameInfo();
-  return (RealignStack &&
+  return (MF.getTarget().Options.RealignStack &&
           !MFI->hasVarSizedObjects());
 }
=20
@@ -583,7 +459,7 @@
     // sure we restore the stack pointer immediately after the call, there=
 may
     // be spill code inserted between the CALL and ADJCALLSTACKUP instruct=
ions.
     MachineBasicBlock::iterator B =3D MBB.begin();
-    while (I !=3D B && !llvm::prior(I)->getDesc().isCall())
+    while (I !=3D B && !llvm::prior(I)->isCall())
       --I;
     MBB.insert(I, New);
   }
@@ -650,12 +526,10 @@
=20
 unsigned X86RegisterInfo::getEHExceptionRegister() const {
   llvm_unreachable("What is the exception register");
-  return 0;
 }
=20
 unsigned X86RegisterInfo::getEHHandlerRegister() const {
   llvm_unreachable("What is the exception handler register");
-  return 0;
 }
=20
 namespace llvm {
@@ -665,7 +539,7 @@
   case MVT::i8:
     if (High) {
       switch (Reg) {
-      default: return 0;
+      default: return getX86SubSuperRegister(Reg, MVT::i64, High);
       case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::R=
AX:
         return X86::AH;
       case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::R=
DX:
@@ -785,6 +659,22 @@
       return X86::R15D;
     }
   case MVT::i64:
+    // For 64-bit mode if we've requested a "high" register and the
+    // Q or r constraints we want one of these high registers or
+    // just the register name otherwise.
+    if (High) {
+      switch (Reg) {
+      case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
+        return X86::SI;
+      case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
+        return X86::DI;
+      case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
+        return X86::BP;
+      case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
+        return X86::SP;
+      // Fallthrough.
+      }
+    }
     switch (Reg) {
     default: return Reg;
     case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
@@ -821,8 +711,6 @@
       return X86::R15;
     }
   }
-
-  return Reg;
 }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Re=
gisterInfo.h
--- a/head/contrib/llvm/lib/Target/X86/X86RegisterInfo.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86RegisterInfo.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86RegisterInfo.h - X86 Register Information Impl --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86RegisterInfo.h - X86 Register Information Impl -------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -95,7 +95,8 @@
=20
   /// getCalleeSavedRegs - Return a null-terminated list of all of the
   /// callee-save registers on this target.
-  const unsigned *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction* MF =3D 0) cons=
t;
+  const uint32_t *getCallPreservedMask(CallingConv::ID) const;
=20
   /// getReservedRegs - Returns a bitset indexed by physical register numb=
er
   /// indicating if a register is a special register that has particular u=
ses and
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Re=
gisterInfo.td
--- a/head/contrib/llvm/lib/Target/X86/X86RegisterInfo.td	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86RegisterInfo.td	Tue Apr 17 11:51:=
51 2012 +0300
@@ -70,7 +70,7 @@
   def BH : Register<"bh">;
=20
   // 16-bit registers
-  let SubRegIndices =3D [sub_8bit, sub_8bit_hi] in {
+  let SubRegIndices =3D [sub_8bit, sub_8bit_hi], CoveredBySubRegs =3D 1 in=
 {
   def AX : RegisterWithSubRegs<"ax", [AL,AH]>;
   def DX : RegisterWithSubRegs<"dx", [DL,DH]>;
   def CX : RegisterWithSubRegs<"cx", [CL,CH]>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Re=
locations.h
--- a/head/contrib/llvm/lib/Target/X86/X86Relocations.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86Relocations.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- X86Relocations.h - X86 Code Relocations ------------------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86Relocations.h - X86 Code Relocations -----------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Se=
lectionDAGInfo.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86SelectionDAGInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86SelectionDAGInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -65,7 +65,8 @@
       std::pair<SDValue,SDValue> CallResult =3D
         TLI.LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
                         false, false, false, false,
-                        0, CallingConv::C, false, /*isReturnValueUsed=3D*/=
false,
+                        0, CallingConv::C, /*isTailCall=3D*/false,
+                        /*doesNotRet=3D*/false, /*isReturnValueUsed=3D*/fa=
lse,
                         DAG.getExternalSymbol(bzeroEntry, IntPtr), Args,
                         DAG, dl);
       return CallResult.second;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Su=
btarget.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86Subtarget.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86Subtarget.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -21,7 +21,6 @@
 #include "llvm/Support/Host.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
-#include "llvm/ADT/SmallVector.h"
=20
 #define GET_SUBTARGETINFO_TARGET_DESC
 #define GET_SUBTARGETINFO_CTOR
@@ -177,16 +176,18 @@
=20
 void X86Subtarget::AutoDetectSubtargetFeatures() {
   unsigned EAX =3D 0, EBX =3D 0, ECX =3D 0, EDX =3D 0;
+  unsigned MaxLevel;
   union {
     unsigned u[3];
     char     c[12];
   } text;
- =20
-  if (X86_MC::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1))
+
+  if (X86_MC::GetCpuIDAndInfo(0, &MaxLevel, text.u+0, text.u+2, text.u+1) =
||
+      MaxLevel < 1)
     return;
=20
   X86_MC::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
- =20
+
   if ((EDX >> 15) & 1) { HasCMov =3D true;      ToggleFeature(X86::Feature=
CMOV); }
   if ((EDX >> 23) & 1) { X86SSELevel =3D MMX;   ToggleFeature(X86::Feature=
MMX);  }
   if ((EDX >> 25) & 1) { X86SSELevel =3D SSE1;  ToggleFeature(X86::Feature=
SSE1); }
@@ -196,7 +197,7 @@
   if ((ECX >> 19) & 1) { X86SSELevel =3D SSE41; ToggleFeature(X86::Feature=
SSE41);}
   if ((ECX >> 20) & 1) { X86SSELevel =3D SSE42; ToggleFeature(X86::Feature=
SSE42);}
   // FIXME: AVX codegen support is not ready.
-  //if ((ECX >> 28) & 1) { HasAVX =3D true;  ToggleFeature(X86::FeatureAVX=
); }
+  //if ((ECX >> 28) & 1) { X86SSELevel =3D AVX;  ToggleFeature(X86::Featur=
eAVX); }
=20
   bool IsIntel =3D memcmp(text.c, "GenuineIntel", 12) =3D=3D 0;
   bool IsAMD   =3D !IsIntel && memcmp(text.c, "AuthenticAMD", 12) =3D=3D 0;
@@ -244,28 +245,69 @@
       IsBTMemSlow =3D true;
       ToggleFeature(X86::FeatureSlowBTMem);
     }
+
     // If it's Nehalem, unaligned memory access is fast.
+    // FIXME: Nehalem is family 6. Also include Westmere and later process=
ors?
     if (Family =3D=3D 15 && Model =3D=3D 26) {
       IsUAMemFast =3D true;
       ToggleFeature(X86::FeatureFastUAMem);
     }
=20
-    X86_MC::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
-    if ((EDX >> 29) & 0x1) {
-      HasX86_64 =3D true;
-      ToggleFeature(X86::Feature64Bit);
+    // Set processor type. Currently only Atom is detected.
+    if (Family =3D=3D 6 && Model =3D=3D 28) {
+      X86ProcFamily =3D IntelAtom;
+      ToggleFeature(X86::FeatureLeaForSP);
     }
-    if ((ECX >> 5) & 0x1) {
-      HasLZCNT =3D true;
-      ToggleFeature(X86::FeatureLZCNT);
+
+    unsigned MaxExtLevel;
+    X86_MC::GetCpuIDAndInfo(0x80000000, &MaxExtLevel, &EBX, &ECX, &EDX);
+
+    if (MaxExtLevel >=3D 0x80000001) {
+      X86_MC::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
+      if ((EDX >> 29) & 0x1) {
+        HasX86_64 =3D true;
+        ToggleFeature(X86::Feature64Bit);
+      }
+      if ((ECX >> 5) & 0x1) {
+        HasLZCNT =3D true;
+        ToggleFeature(X86::FeatureLZCNT);
+      }
+      if (IsAMD) {
+        if ((ECX >> 6) & 0x1) {
+          HasSSE4A =3D true;
+          ToggleFeature(X86::FeatureSSE4A);
+        }
+        if ((ECX >> 11) & 0x1) {
+          HasXOP =3D true;
+          ToggleFeature(X86::FeatureXOP);
+        }
+        if ((ECX >> 16) & 0x1) {
+          HasFMA4 =3D true;
+          ToggleFeature(X86::FeatureFMA4);
+        }
+      }
     }
-    if (IsAMD && ((ECX >> 6) & 0x1)) {
-      HasSSE4A =3D true;
-      ToggleFeature(X86::FeatureSSE4A);
-    }
-    if (IsAMD && ((ECX >> 16) & 0x1)) {
-      HasFMA4 =3D true;
-      ToggleFeature(X86::FeatureFMA4);
+  }
+
+  if (IsIntel && MaxLevel >=3D 7) {
+    if (!X86_MC::GetCpuIDAndInfoEx(0x7, 0x0, &EAX, &EBX, &ECX, &EDX)) {
+      if (EBX & 0x1) {
+        HasFSGSBase =3D true;
+        ToggleFeature(X86::FeatureFSGSBase);
+      }
+      if ((EBX >> 3) & 0x1) {
+        HasBMI =3D true;
+        ToggleFeature(X86::FeatureBMI);
+      }
+      // FIXME: AVX2 codegen support is not ready.
+      //if ((EBX >> 5) & 0x1) {
+      //  X86SSELevel =3D AVX2;
+      //  ToggleFeature(X86::FeatureAVX2);
+      //}
+      if ((EBX >> 8) & 0x1) {
+        HasBMI2 =3D true;
+        ToggleFeature(X86::FeatureBMI2);
+      }
     }
   }
 }
@@ -274,6 +316,7 @@
                            const std::string &FS,=20
                            unsigned StackAlignOverride, bool is64Bit)
   : X86GenSubtargetInfo(TT, CPU, FS)
+  , X86ProcFamily(Others)
   , PICStyle(PICStyles::None)
   , X86SSELevel(NoMMXSSE)
   , X863DNowLevel(NoThreeDNow)
@@ -281,31 +324,35 @@
   , HasX86_64(false)
   , HasPOPCNT(false)
   , HasSSE4A(false)
-  , HasAVX(false)
   , HasAES(false)
   , HasCLMUL(false)
   , HasFMA3(false)
   , HasFMA4(false)
+  , HasXOP(false)
   , HasMOVBE(false)
   , HasRDRAND(false)
   , HasF16C(false)
+  , HasFSGSBase(false)
   , HasLZCNT(false)
   , HasBMI(false)
+  , HasBMI2(false)
   , IsBTMemSlow(false)
   , IsUAMemFast(false)
   , HasVectorUAMem(false)
   , HasCmpxchg16b(false)
-  , stackAlignment(8)
+  , UseLeaForSP(false)
+  , PostRAScheduler(false)
+  , stackAlignment(4)
   // FIXME: this is a known good value for Yonah. How about others?
   , MaxInlineSizeThreshold(128)
   , TargetTriple(TT)
-  , In64BitMode(is64Bit)
-  , InNaClMode(false) {
+  , In64BitMode(is64Bit) {
   // Determine default and user specified characteristics
+  std::string CPUName =3D CPU;
   if (!FS.empty() || !CPU.empty()) {
-    std::string CPUName =3D CPU;
     if (CPUName.empty()) {
-#if defined (__x86_64__) || defined(__i386__)
+#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_I=
X86)\
+    || defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
       CPUName =3D sys::getHostCPUName();
 #else
       CPUName =3D "generic";
@@ -325,6 +372,13 @@
     // If feature string is not empty, parse features string.
     ParseSubtargetFeatures(CPUName, FullFS);
   } else {
+    if (CPUName.empty()) {
+#if defined (__x86_64__) || defined(__i386__)
+      CPUName =3D sys::getHostCPUName();
+#else
+      CPUName =3D "generic";
+#endif
+    }
     // Otherwise, use CPUID to auto-detect feature set.
     AutoDetectSubtargetFeatures();
=20
@@ -333,7 +387,7 @@
       HasX86_64 =3D true; ToggleFeature(X86::Feature64Bit);
       HasCMov =3D true;   ToggleFeature(X86::FeatureCMOV);
=20
-      if (!HasAVX && X86SSELevel < SSE2) {
+      if (X86SSELevel < SSE2) {
         X86SSELevel =3D SSE2;
         ToggleFeature(X86::FeatureSSE1);
         ToggleFeature(X86::FeatureSSE2);
@@ -341,28 +395,22 @@
     }
   }
=20
+  if (X86ProcFamily =3D=3D IntelAtom) {
+    PostRAScheduler =3D true;
+    InstrItins =3D getInstrItineraryForCPU(CPUName);
+  }
+
   // It's important to keep the MCSubtargetInfo feature bits in sync with
   // target data structure which is shared with MC code emitter, etc.
   if (In64BitMode)
     ToggleFeature(X86::Mode64Bit);
=20
-  if (isTargetNaCl()) {
-    InNaClMode =3D true;
-    ToggleFeature(X86::ModeNaCl);
-  }
-
-  if (HasAVX)
-    X86SSELevel =3D NoMMXSSE;
-   =20
   DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel
                << ", 3DNowLevel " << X863DNowLevel
                << ", 64bit " << HasX86_64 << "\n");
   assert((!In64BitMode || HasX86_64) &&
          "64-bit code requested on a subtarget that doesn't support it!");
=20
-  if(EnableSegmentedStacks && !isTargetELF())
-    report_fatal_error("Segmented stacks are only implemented on ELF.");
-
   // Stack alignment is 16 bytes on Darwin, FreeBSD, Linux and Solaris (bo=
th
   // 32 and 64 bit) and for all 64-bit targets.
   if (StackAlignOverride)
@@ -371,3 +419,12 @@
            isTargetSolaris() || In64BitMode)
     stackAlignment =3D 16;
 }
+
+bool X86Subtarget::enablePostRAScheduler(
+           CodeGenOpt::Level OptLevel,
+           TargetSubtargetInfo::AntiDepBreakMode& Mode,
+           RegClassVector& CriticalPathRCs) const {
+  Mode =3D TargetSubtargetInfo::ANTIDEP_CRITICAL;
+  CriticalPathRCs.clear();
+  return PostRAScheduler && OptLevel >=3D CodeGenOpt::Default;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Su=
btarget.h
--- a/head/contrib/llvm/lib/Target/X86/X86Subtarget.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86Subtarget.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D---- X86Subtarget.h - Define Subtarget for the X86 -----*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- X86Subtarget.h - Define Subtarget for the X86 ----------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,9 +14,9 @@
 #ifndef X86SUBTARGET_H
 #define X86SUBTARGET_H
=20
+#include "llvm/CallingConv.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Target/TargetSubtargetInfo.h"
-#include "llvm/CallingConv.h"
 #include <string>
=20
 #define GET_SUBTARGETINFO_HEADER
@@ -42,13 +42,20 @@
 class X86Subtarget : public X86GenSubtargetInfo {
 protected:
   enum X86SSEEnum {
-    NoMMXSSE, MMX, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42
+    NoMMXSSE, MMX, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42, AVX, AVX2
   };
=20
   enum X863DNowEnum {
     NoThreeDNow, ThreeDNow, ThreeDNowA
   };
=20
+  enum X86ProcFamilyEnum {
+    Others, IntelAtom
+  };
+
+  /// X86ProcFamily - X86 processor family: Intel Atom, and others
+  X86ProcFamilyEnum X86ProcFamily;
+ =20
   /// PICStyle - Which PIC style to use
   ///
   PICStyles::Style PICStyle;
@@ -75,9 +82,6 @@
   /// HasSSE4A - True if the processor supports SSE4A instructions.
   bool HasSSE4A;
=20
-  /// HasAVX - Target has AVX instructions
-  bool HasAVX;
-
   /// HasAES - Target has AES instructions
   bool HasAES;
=20
@@ -90,6 +94,9 @@
   /// HasFMA4 - Target has 4-operand fused multiply-add
   bool HasFMA4;
=20
+  /// HasXOP - Target has XOP instructions
+  bool HasXOP;
+
   /// HasMOVBE - True if the processor has the MOVBE instruction.
   bool HasMOVBE;
=20
@@ -99,12 +106,18 @@
   /// HasF16C - Processor has 16-bit floating point conversion instruction=
s.
   bool HasF16C;
=20
+  /// HasFSGSBase - Processor has FS/GS base insturctions.
+  bool HasFSGSBase;
+
   /// HasLZCNT - Processor has LZCNT instruction.
   bool HasLZCNT;
=20
   /// HasBMI - Processor has BMI1 instructions.
   bool HasBMI;
=20
+  /// HasBMI2 - Processor has BMI2 instructions.
+  bool HasBMI2;
+
   /// IsBTMemSlow - True if BT (bit test) of memory instructions are slow.
   bool IsBTMemSlow;
=20
@@ -119,6 +132,13 @@
   /// this is true for most x86-64 chips, but not the first AMD chips.
   bool HasCmpxchg16b;
=20
+  /// UseLeaForSP - True if the LEA instruction should be used for adjusti=
ng
+  /// the stack pointer. This is an optimization for Intel Atom processors.
+  bool UseLeaForSP;
+
+  /// PostRAScheduler - True if using post-register-allocation scheduler.
+  bool PostRAScheduler;
+
   /// stackAlignment - The minimum alignment known to hold of the stack fr=
ame on
   /// entry to the function and which must be maintained by every function.
   unsigned stackAlignment;
@@ -129,14 +149,14 @@
=20
   /// TargetTriple - What processor and OS we're targeting.
   Triple TargetTriple;
+ =20
+  /// Instruction itineraries for scheduling
+  InstrItineraryData InstrItins;
=20
 private:
   /// In64BitMode - True if compiling for 64-bit, false for 32-bit.
   bool In64BitMode;
=20
-  /// InNaClMode - True if compiling for Native Client target.
-  bool InNaClMode;
-
 public:
=20
   /// This constructor initializes the data members to match that
@@ -176,26 +196,31 @@
   bool hasSSSE3() const { return X86SSELevel >=3D SSSE3; }
   bool hasSSE41() const { return X86SSELevel >=3D SSE41; }
   bool hasSSE42() const { return X86SSELevel >=3D SSE42; }
+  bool hasAVX() const { return X86SSELevel >=3D AVX; }
+  bool hasAVX2() const { return X86SSELevel >=3D AVX2; }
   bool hasSSE4A() const { return HasSSE4A; }
   bool has3DNow() const { return X863DNowLevel >=3D ThreeDNow; }
   bool has3DNowA() const { return X863DNowLevel >=3D ThreeDNowA; }
   bool hasPOPCNT() const { return HasPOPCNT; }
-  bool hasAVX() const { return HasAVX; }
-  bool hasXMM() const { return hasSSE1() || hasAVX(); }
-  bool hasXMMInt() const { return hasSSE2() || hasAVX(); }
   bool hasAES() const { return HasAES; }
   bool hasCLMUL() const { return HasCLMUL; }
   bool hasFMA3() const { return HasFMA3; }
   bool hasFMA4() const { return HasFMA4; }
+  bool hasXOP() const { return HasXOP; }
   bool hasMOVBE() const { return HasMOVBE; }
   bool hasRDRAND() const { return HasRDRAND; }
   bool hasF16C() const { return HasF16C; }
+  bool hasFSGSBase() const { return HasFSGSBase; }
   bool hasLZCNT() const { return HasLZCNT; }
   bool hasBMI() const { return HasBMI; }
+  bool hasBMI2() const { return HasBMI2; }
   bool isBTMemSlow() const { return IsBTMemSlow; }
   bool isUnalignedMemAccessFast() const { return IsUAMemFast; }
   bool hasVectorUAMem() const { return HasVectorUAMem; }
   bool hasCmpxchg16b() const { return HasCmpxchg16b; }
+  bool useLeaForSP() const { return UseLeaForSP; }
+
+  bool isAtom() const { return X86ProcFamily =3D=3D IntelAtom; }
=20
   const Triple &getTargetTriple() const { return TargetTriple; }
=20
@@ -209,38 +234,28 @@
=20
   // ELF is a reasonably sane default and the only other X86 targets we
   // support are Darwin and Windows. Just use "not those".
-  bool isTargetELF() const {
-    return !isTargetDarwin() && !isTargetWindows() && !isTargetCygMing();
-  }
+  bool isTargetELF() const { return TargetTriple.isOSBinFormatELF(); }
   bool isTargetLinux() const { return TargetTriple.getOS() =3D=3D Triple::=
Linux; }
   bool isTargetNaCl() const {
     return TargetTriple.getOS() =3D=3D Triple::NativeClient;
   }
   bool isTargetNaCl32() const { return isTargetNaCl() && !is64Bit(); }
   bool isTargetNaCl64() const { return isTargetNaCl() && is64Bit(); }
-
   bool isTargetWindows() const { return TargetTriple.getOS() =3D=3D Triple=
::Win32; }
   bool isTargetMingw() const { return TargetTriple.getOS() =3D=3D Triple::=
MinGW32; }
   bool isTargetCygwin() const { return TargetTriple.getOS() =3D=3D Triple:=
:Cygwin; }
-  bool isTargetCygMing() const {
-    return isTargetMingw() || isTargetCygwin();
-  }
-
-  /// isTargetCOFF - Return true if this is any COFF/Windows target varian=
t.
-  bool isTargetCOFF() const {
-    return isTargetMingw() || isTargetCygwin() || isTargetWindows();
-  }
+  bool isTargetCygMing() const { return TargetTriple.isOSCygMing(); }
+  bool isTargetCOFF() const { return TargetTriple.isOSBinFormatCOFF(); }
+  bool isTargetEnvMacho() const { return TargetTriple.isEnvironmentMachO()=
; }
=20
   bool isTargetWin64() const {
     // FIXME: x86_64-cygwin has not been released yet.
-    return In64BitMode && (isTargetCygMing() || isTargetWindows());
-  }
-
-  bool isTargetEnvMacho() const {
-    return isTargetDarwin() || (TargetTriple.getEnvironment() =3D=3D Tripl=
e::MachO);
+    return In64BitMode && TargetTriple.isOSWindows();
   }
=20
   bool isTargetWin32() const {
+    // FIXME: Cygwin is included for isTargetWin64 -- should it be included
+    // here too?
     return !In64BitMode && (isTargetMingw() || isTargetWindows());
   }
=20
@@ -286,6 +301,15 @@
   /// indicating the number of scheduling cycles of backscheduling that
   /// should be attempted.
   unsigned getSpecialAddressLatency() const;
+
+  /// enablePostRAScheduler - run for Atom optimization.
+  bool enablePostRAScheduler(CodeGenOpt::Level OptLevel,
+                             TargetSubtargetInfo::AntiDepBreakMode& Mode,
+                             RegClassVector& CriticalPathRCs) const;
+
+  /// getInstrItins =3D Return the instruction itineraries based on the
+  /// subtarget selection.
+  const InstrItineraryData &getInstrItineraryData() const { return InstrIt=
ins; }
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Ta=
rgetMachine.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86TargetMachine.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86TargetMachine.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -28,11 +28,14 @@
   RegisterTargetMachine<X86_64TargetMachine> Y(TheX86_64Target);
 }
=20
+void X86_32TargetMachine::anchor() { }
=20
 X86_32TargetMachine::X86_32TargetMachine(const Target &T, StringRef TT,
                                          StringRef CPU, StringRef FS,
-                                         Reloc::Model RM, CodeModel::Model=
 CM)
-  : X86TargetMachine(T, TT, CPU, FS, RM, CM, false),
+                                         const TargetOptions &Options,
+                                         Reloc::Model RM, CodeModel::Model=
 CM,
+                                         CodeGenOpt::Level OL)
+  : X86TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false),
     DataLayout(getSubtargetImpl()->isTargetDarwin() ?
                "e-p:32:32-f64:32:64-i64:32:64-f80:128:128-f128:128:128-"
                "n8:16:32-S128" :
@@ -48,11 +51,14 @@
     JITInfo(*this) {
 }
=20
+void X86_64TargetMachine::anchor() { }
=20
 X86_64TargetMachine::X86_64TargetMachine(const Target &T, StringRef TT,
                                          StringRef CPU, StringRef FS,
-                                         Reloc::Model RM, CodeModel::Model=
 CM)
-  : X86TargetMachine(T, TT, CPU, FS, RM, CM, true),
+                                         const TargetOptions &Options,
+                                         Reloc::Model RM, CodeModel::Model=
 CM,
+                                         CodeGenOpt::Level OL)
+  : X86TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true),
     DataLayout("e-p:64:64-s:64-f64:64:64-i64:64:64-f80:128:128-f128:128:12=
8-"
                "n8:16:32:64-S128"),
     InstrInfo(*this),
@@ -65,12 +71,15 @@
 ///
 X86TargetMachine::X86TargetMachine(const Target &T, StringRef TT,
                                    StringRef CPU, StringRef FS,
+                                   const TargetOptions &Options,
                                    Reloc::Model RM, CodeModel::Model CM,
+                                   CodeGenOpt::Level OL,
                                    bool is64Bit)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
-    Subtarget(TT, CPU, FS, StackAlignmentOverride, is64Bit),
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
+    Subtarget(TT, CPU, FS, Options.StackAlignmentOverride, is64Bit),
     FrameLowering(*this, Subtarget),
-    ELFWriterInfo(is64Bit, true) {
+    ELFWriterInfo(is64Bit, true),
+    InstrItins(Subtarget.getInstrItineraryData()){
   // Determine the PICStyle based on the target selected.
   if (getRelocationModel() =3D=3D Reloc::Static) {
     // Unless we're in PIC or DynamicNoPIC mode, set the PIC style to None.
@@ -92,8 +101,8 @@
   }
=20
   // default to hard float ABI
-  if (FloatABIType =3D=3D FloatABI::Default)
-    FloatABIType =3D FloatABI::Hard;   =20
+  if (Options.FloatABIType =3D=3D FloatABI::Default)
+    this->Options.FloatABIType =3D FloatABI::Hard;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -102,46 +111,67 @@
 static cl::opt<bool>
 UseVZeroUpper("x86-use-vzeroupper",
   cl::desc("Minimize AVX to SSE transition penalty"),
-  cl::init(false));
+  cl::init(true));
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Pass Pipeline Configuration
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-bool X86TargetMachine::addInstSelector(PassManagerBase &PM,
-                                       CodeGenOpt::Level OptLevel) {
+namespace {
+/// X86 Code Generator Pass Configuration Options.
+class X86PassConfig : public TargetPassConfig {
+public:
+  X86PassConfig(X86TargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  X86TargetMachine &getX86TargetMachine() const {
+    return getTM<X86TargetMachine>();
+  }
+
+  const X86Subtarget &getX86Subtarget() const {
+    return *getX86TargetMachine().getSubtargetImpl();
+  }
+
+  virtual bool addInstSelector();
+  virtual bool addPreRegAlloc();
+  virtual bool addPostRegAlloc();
+  virtual bool addPreEmitPass();
+};
+} // namespace
+
+TargetPassConfig *X86TargetMachine::createPassConfig(PassManagerBase &PM) {
+  return new X86PassConfig(this, PM);
+}
+
+bool X86PassConfig::addInstSelector() {
   // Install an instruction selector.
-  PM.add(createX86ISelDag(*this, OptLevel));
+  PM.add(createX86ISelDag(getX86TargetMachine(), getOptLevel()));
=20
   // For 32-bit, prepend instructions to set the "global base reg" for PIC.
-  if (!Subtarget.is64Bit())
+  if (!getX86Subtarget().is64Bit())
     PM.add(createGlobalBaseRegPass());
=20
   return false;
 }
=20
-bool X86TargetMachine::addPreRegAlloc(PassManagerBase &PM,
-                                      CodeGenOpt::Level OptLevel) {
+bool X86PassConfig::addPreRegAlloc() {
   PM.add(createX86MaxStackAlignmentHeuristicPass());
   return false;  // -print-machineinstr shouldn't print after this.
 }
=20
-bool X86TargetMachine::addPostRegAlloc(PassManagerBase &PM,
-                                       CodeGenOpt::Level OptLevel) {
+bool X86PassConfig::addPostRegAlloc() {
   PM.add(createX86FloatingPointStackifierPass());
   return true;  // -print-machineinstr should print after this.
 }
=20
-bool X86TargetMachine::addPreEmitPass(PassManagerBase &PM,
-                                      CodeGenOpt::Level OptLevel) {
+bool X86PassConfig::addPreEmitPass() {
   bool ShouldPrint =3D false;
-  if (OptLevel !=3D CodeGenOpt::None &&
-      (Subtarget.hasSSE2() || Subtarget.hasAVX())) {
+  if (getOptLevel() !=3D CodeGenOpt::None && getX86Subtarget().hasSSE2()) {
     PM.add(createExecutionDependencyFixPass(&X86::VR128RegClass));
     ShouldPrint =3D true;
   }
=20
-  if (Subtarget.hasAVX() && UseVZeroUpper) {
+  if (getX86Subtarget().hasAVX() && UseVZeroUpper) {
     PM.add(createX86IssueVZeroUpperPass());
     ShouldPrint =3D true;
   }
@@ -150,7 +180,6 @@
 }
=20
 bool X86TargetMachine::addCodeEmitter(PassManagerBase &PM,
-                                      CodeGenOpt::Level OptLevel,
                                       JITCodeEmitter &JCE) {
   PM.add(createX86JITCodeEmitterPass(*this, JCE));
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Ta=
rgetMachine.h
--- a/head/contrib/llvm/lib/Target/X86/X86TargetMachine.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86TargetMachine.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -27,19 +27,20 @@
 #include "llvm/Target/TargetFrameLowering.h"
=20
 namespace llvm {
- =20
-class formatted_raw_ostream;
+
 class StringRef;
=20
 class X86TargetMachine : public LLVMTargetMachine {
-  X86Subtarget      Subtarget;
-  X86FrameLowering  FrameLowering;
-  X86ELFWriterInfo  ELFWriterInfo;
+  X86Subtarget       Subtarget;
+  X86FrameLowering   FrameLowering;
+  X86ELFWriterInfo   ELFWriterInfo;
+  InstrItineraryData InstrItins;
=20
 public:
-  X86TargetMachine(const Target &T, StringRef TT,=20
-                   StringRef CPU, StringRef FS,
+  X86TargetMachine(const Target &T, StringRef TT,
+                   StringRef CPU, StringRef FS, const TargetOptions &Optio=
ns,
                    Reloc::Model RM, CodeModel::Model CM,
+                   CodeGenOpt::Level OL,
                    bool is64Bit);
=20
   virtual const X86InstrInfo     *getInstrInfo() const {
@@ -55,7 +56,7 @@
   virtual const X86TargetLowering *getTargetLowering() const {
     llvm_unreachable("getTargetLowering not implemented");
   }
-  virtual const X86SelectionDAGInfo *getSelectionDAGInfo() const {=20
+  virtual const X86SelectionDAGInfo *getSelectionDAGInfo() const {
     llvm_unreachable("getSelectionDAGInfo not implemented");
   }
   virtual const X86RegisterInfo  *getRegisterInfo() const {
@@ -64,19 +65,21 @@
   virtual const X86ELFWriterInfo *getELFWriterInfo() const {
     return Subtarget.isTargetELF() ? &ELFWriterInfo : 0;
   }
+  virtual const InstrItineraryData *getInstrItineraryData() const {
+    return &InstrItins;
+  }
=20
   // Set up the pass pipeline.
-  virtual bool addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptL=
evel);
-  virtual bool addPreRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel);
-  virtual bool addPostRegAlloc(PassManagerBase &PM, CodeGenOpt::Level OptL=
evel);
-  virtual bool addPreEmitPass(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel);
-  virtual bool addCodeEmitter(PassManagerBase &PM, CodeGenOpt::Level OptLe=
vel,
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
+
+  virtual bool addCodeEmitter(PassManagerBase &PM,
                               JITCodeEmitter &JCE);
 };
=20
 /// X86_32TargetMachine - X86 32-bit target machine.
 ///
 class X86_32TargetMachine : public X86TargetMachine {
+  virtual void anchor();
   const TargetData  DataLayout; // Calculates type size & alignment
   X86InstrInfo      InstrInfo;
   X86SelectionDAGInfo TSInfo;
@@ -84,13 +87,14 @@
   X86JITInfo        JITInfo;
 public:
   X86_32TargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
-                      Reloc::Model RM, CodeModel::Model CM);
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
+                      Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL);
   virtual const TargetData *getTargetData() const { return &DataLayout; }
   virtual const X86TargetLowering *getTargetLowering() const {
     return &TLInfo;
   }
-  virtual const X86SelectionDAGInfo *getSelectionDAGInfo() const {=20
+  virtual const X86SelectionDAGInfo *getSelectionDAGInfo() const {
     return &TSInfo;
   }
   virtual const X86InstrInfo     *getInstrInfo() const {
@@ -104,6 +108,7 @@
 /// X86_64TargetMachine - X86 64-bit target machine.
 ///
 class X86_64TargetMachine : public X86TargetMachine {
+  virtual void anchor();
   const TargetData  DataLayout; // Calculates type size & alignment
   X86InstrInfo      InstrInfo;
   X86SelectionDAGInfo TSInfo;
@@ -111,13 +116,14 @@
   X86JITInfo        JITInfo;
 public:
   X86_64TargetMachine(const Target &T, StringRef TT,
-                      StringRef CPU, StringRef FS,
-                      Reloc::Model RM, CodeModel::Model CM);
+                      StringRef CPU, StringRef FS, const TargetOptions &Op=
tions,
+                      Reloc::Model RM, CodeModel::Model CM,
+                      CodeGenOpt::Level OL);
   virtual const TargetData *getTargetData() const { return &DataLayout; }
   virtual const X86TargetLowering *getTargetLowering() const {
     return &TLInfo;
   }
-  virtual const X86SelectionDAGInfo *getSelectionDAGInfo() const {=20
+  virtual const X86SelectionDAGInfo *getSelectionDAGInfo() const {
     return &TSInfo;
   }
   virtual const X86InstrInfo     *getInstrInfo() const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Ta=
rgetObjectFile.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86TargetObjectFile.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86TargetObjectFile.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- llvm/Target/X86/X86TargetObjectFile.cpp - X86 Object Info --=
-------=3D=3D=3D//
+//=3D=3D=3D-- X86TargetObjectFile.cpp - X86 Object Info ------------------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,7 +14,6 @@
 #include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/Target/Mangler.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/Dwarf.h"
 using namespace llvm;
 using namespace dwarf;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86Ta=
rgetObjectFile.h
--- a/head/contrib/llvm/lib/Target/X86/X86TargetObjectFile.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86TargetObjectFile.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- llvm/Target/X86/X86TargetObjectFile.h - X86 Object Info -*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- X86TargetObjectFile.h - X86 Object Info -----------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -15,7 +15,6 @@
 #include "llvm/Target/TargetLoweringObjectFile.h"
=20
 namespace llvm {
-  class X86TargetMachine;
=20
   /// X8664_MachoTargetObjectFile - This TLOF implementation is used for D=
arwin
   /// x86-64.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/X86/X86VZ=
eroUpper.cpp
--- a/head/contrib/llvm/lib/Target/X86/X86VZeroUpper.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Target/X86/X86VZeroUpper.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,14 +14,16 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#define DEBUG_TYPE "x86-codegen"
+#define DEBUG_TYPE "x86-vzeroupper"
 #include "X86.h"
 #include "X86InstrInfo.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
+#include "llvm/CodeGen/MachineRegisterInfo.h"
 #include "llvm/CodeGen/Passes.h"
-#include "llvm/GlobalValue.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetInstrInfo.h"
 using namespace llvm;
=20
@@ -41,6 +43,60 @@
   private:
     const TargetInstrInfo *TII; // Machine instruction info.
     MachineBasicBlock *MBB;     // Current basic block
+
+    // Any YMM register live-in to this function?
+    bool FnHasLiveInYmm;
+
+    // BBState - Contains the state of each MBB: unknown, clean, dirty
+    SmallVector<uint8_t, 8> BBState;
+
+    // BBSolved - Keep track of all MBB which had been already analyzed
+    // and there is no further processing required.
+    BitVector BBSolved;
+
+    // Machine Basic Blocks are classified according this pass:
+    //
+    //  ST_UNKNOWN - The MBB state is unknown, meaning from the entry state
+    //    until the MBB exit there isn't a instruction using YMM to change
+    //    the state to dirty, or one of the incoming predecessors is unkno=
wn
+    //    and there's not a dirty predecessor between them.
+    //
+    //  ST_CLEAN - No YMM usage in the end of the MBB. A MBB could have
+    //    instructions using YMM and be marked ST_CLEAN, as long as the st=
ate
+    //    is cleaned by a vzeroupper before any call.
+    //
+    //  ST_DIRTY - Any MBB ending with a YMM usage not cleaned up by a
+    //    vzeroupper instruction.
+    //
+    //  ST_INIT - Placeholder for an empty state set
+    //
+    enum {
+      ST_UNKNOWN =3D 0,
+      ST_CLEAN   =3D 1,
+      ST_DIRTY   =3D 2,
+      ST_INIT    =3D 3
+    };
+
+    // computeState - Given two states, compute the resulting state, in
+    // the following way
+    //
+    //  1) One dirty state yields another dirty state
+    //  2) All states must be clean for the result to be clean
+    //  3) If none above and one unknown, the result state is also unknown
+    //
+    unsigned computeState(unsigned PrevState, unsigned CurState) {
+      if (PrevState =3D=3D ST_INIT)
+        return CurState;
+
+      if (PrevState =3D=3D ST_DIRTY || CurState =3D=3D ST_DIRTY)
+        return ST_DIRTY;
+
+      if (PrevState =3D=3D ST_CLEAN && CurState =3D=3D ST_CLEAN)
+        return ST_CLEAN;
+
+      return ST_UNKNOWN;
+    }
+
   };
   char VZeroUpperInserter::ID =3D 0;
 }
@@ -49,37 +105,82 @@
   return new VZeroUpperInserter();
 }
=20
+static bool isYmmReg(unsigned Reg) {
+  if (Reg >=3D X86::YMM0 && Reg <=3D X86::YMM15)
+    return true;
+
+  return false;
+}
+
+static bool checkFnHasLiveInYmm(MachineRegisterInfo &MRI) {
+  for (MachineRegisterInfo::livein_iterator I =3D MRI.livein_begin(),
+       E =3D MRI.livein_end(); I !=3D E; ++I)
+    if (isYmmReg(I->first))
+      return true;
+
+  return false;
+}
+
+static bool hasYmmReg(MachineInstr *MI) {
+  for (int i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
+    const MachineOperand &MO =3D MI->getOperand(i);
+    if (!MO.isReg())
+      continue;
+    if (MO.isDebug())
+      continue;
+    if (isYmmReg(MO.getReg()))
+      return true;
+  }
+  return false;
+}
+
 /// runOnMachineFunction - Loop over all of the basic blocks, inserting
 /// vzero upper instructions before function calls.
 bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
   TII =3D MF.getTarget().getInstrInfo();
-  bool Changed =3D false;
+  MachineRegisterInfo &MRI =3D MF.getRegInfo();
+  bool EverMadeChange =3D false;
=20
-  // Process any unreachable blocks in arbitrary order now.
-  for (MachineFunction::iterator BB =3D MF.begin(), E =3D MF.end(); BB !=
=3D E; ++BB)
-    Changed |=3D processBasicBlock(MF, *BB);
+  // Fast check: if the function doesn't use any ymm registers, we don't n=
eed
+  // to insert any VZEROUPPER instructions.  This is constant-time, so it =
is
+  // cheap in the common case of no ymm use.
+  bool YMMUsed =3D false;
+  const TargetRegisterClass *RC =3D X86::VR256RegisterClass;
+  for (TargetRegisterClass::iterator i =3D RC->begin(), e =3D RC->end();
+       i !=3D e; i++) {
+    if (MRI.isPhysRegUsed(*i)) {
+      YMMUsed =3D true;
+      break;
+    }
+  }
+  if (!YMMUsed)
+    return EverMadeChange;
=20
-  return Changed;
-}
+  // Pre-compute the existence of any live-in YMM registers to this functi=
on
+  FnHasLiveInYmm =3D checkFnHasLiveInYmm(MRI);
=20
-static bool isCallToModuleFn(const MachineInstr *MI) {
-  assert(MI->getDesc().isCall() && "Isn't a call instruction");
+  assert(BBState.empty());
+  BBState.resize(MF.getNumBlockIDs(), 0);
+  BBSolved.resize(MF.getNumBlockIDs(), 0);
=20
-  for (int i =3D 0, e =3D MI->getNumOperands(); i !=3D e; ++i) {
-    const MachineOperand &MO =3D MI->getOperand(i);
+  // Each BB state depends on all predecessors, loop over until everything
+  // converges.  (Once we converge, we can implicitly mark everything that=
 is
+  // still ST_UNKNOWN as ST_CLEAN.)
+  while (1) {
+    bool MadeChange =3D false;
=20
-    if (!MO.isGlobal())
-      continue;
+    // Process all basic blocks.
+    for (MachineFunction::iterator I =3D MF.begin(), E =3D MF.end(); I !=
=3D E; ++I)
+      MadeChange |=3D processBasicBlock(MF, *I);
=20
-    const GlobalValue *GV =3D MO.getGlobal();
-    GlobalValue::LinkageTypes LT =3D GV->getLinkage();
-    if (GV->isInternalLinkage(LT) || GV->isPrivateLinkage(LT) ||
-        (GV->isExternalLinkage(LT) && !GV->isDeclaration()))
-      return true;
+    // If this iteration over the code changed anything, keep iterating.
+    if (!MadeChange) break;
+    EverMadeChange =3D true;
+  }
=20
-    return false;
-  }
-  return false;
+  BBState.clear();
+  BBSolved.clear();
+  return EverMadeChange;
 }
=20
 /// processBasicBlock - Loop over all of the instructions in the basic blo=
ck,
@@ -87,19 +188,98 @@
 bool VZeroUpperInserter::processBasicBlock(MachineFunction &MF,
                                            MachineBasicBlock &BB) {
   bool Changed =3D false;
+  unsigned BBNum =3D BB.getNumber();
   MBB =3D &BB;
=20
+  // Don't process already solved BBs
+  if (BBSolved[BBNum])
+    return false; // No changes
+
+  // Check the state of all predecessors
+  unsigned EntryState =3D ST_INIT;
+  for (MachineBasicBlock::const_pred_iterator PI =3D BB.pred_begin(),
+       PE =3D BB.pred_end(); PI !=3D PE; ++PI) {
+    EntryState =3D computeState(EntryState, BBState[(*PI)->getNumber()]);
+    if (EntryState =3D=3D ST_DIRTY)
+      break;
+  }
+
+
+  // The entry MBB for the function may set the inital state to dirty if
+  // the function receives any YMM incoming arguments
+  if (MBB =3D=3D MF.begin()) {
+    EntryState =3D ST_CLEAN;
+    if (FnHasLiveInYmm)
+      EntryState =3D ST_DIRTY;
+  }
+
+  // The current state is initialized according to the predecessors
+  unsigned CurState =3D EntryState;
+  bool BBHasCall =3D false;
+
   for (MachineBasicBlock::iterator I =3D BB.begin(); I !=3D BB.end(); ++I)=
 {
     MachineInstr *MI =3D I;
     DebugLoc dl =3D I->getDebugLoc();
+    bool isControlFlow =3D MI->isCall() || MI->isReturn();
=20
-    // Insert a vzeroupper instruction before each control transfer
-    // to functions outside this module
-    if (MI->getDesc().isCall() && !isCallToModuleFn(MI)) {
-      BuildMI(*MBB, I, dl, TII->get(X86::VZEROUPPER));
-      ++NumVZU;
+    // Shortcut: don't need to check regular instructions in dirty state.=20
+    if (!isControlFlow && CurState =3D=3D ST_DIRTY)
+      continue;
+
+    if (hasYmmReg(MI)) {
+      // We found a ymm-using instruction; this could be an AVX instructio=
n,
+      // or it could be control flow.
+      CurState =3D ST_DIRTY;
+      continue;
+    }
+
+    // Check for control-flow out of the current function (which might
+    // indirectly execute SSE instructions).
+    if (!isControlFlow)
+      continue;
+
+    BBHasCall =3D true;
+
+    // The VZEROUPPER instruction resets the upper 128 bits of all Intel A=
VX
+    // registers. This instruction has zero latency. In addition, the proc=
essor
+    // changes back to Clean state, after which execution of Intel SSE
+    // instructions or Intel AVX instructions has no transition penalty. A=
dd
+    // the VZEROUPPER instruction before any function call/return that mig=
ht
+    // execute SSE code.
+    // FIXME: In some cases, we may want to move the VZEROUPPER into a
+    // predecessor block.
+    if (CurState =3D=3D ST_DIRTY) {
+      // Only insert the VZEROUPPER in case the entry state isn't unknown.
+      // When unknown, only compute the information within the block to ha=
ve
+      // it available in the exit if possible, but don't change the block.
+      if (EntryState !=3D ST_UNKNOWN) {
+        BuildMI(*MBB, I, dl, TII->get(X86::VZEROUPPER));
+        ++NumVZU;
+      }
+
+      // After the inserted VZEROUPPER the state becomes clean again, but
+      // other YMM may appear before other subsequent calls or even before
+      // the end of the BB.
+      CurState =3D ST_CLEAN;
     }
   }
=20
+  DEBUG(dbgs() << "MBB #" << BBNum
+               << ", current state: " << CurState << '\n');
+
+  // A BB can only be considered solved when we both have done all the
+  // necessary transformations, and have computed the exit state.  This ha=
ppens
+  // in two cases:
+  //  1) We know the entry state: this immediately implies the exit state =
and
+  //     all the necessary transformations.
+  //  2) There are no calls, and and a non-call instruction marks this blo=
ck:
+  //     no transformations are necessary, and we know the exit state.
+  if (EntryState !=3D ST_UNKNOWN || (!BBHasCall && CurState !=3D ST_UNKNOW=
N))
+    BBSolved[BBNum] =3D true;
+
+  if (CurState !=3D BBState[BBNum])
+    Changed =3D true;
+
+  BBState[BBNum] =3D CurState;
   return Changed;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/MCT=
argetDesc/XCoreMCAsmInfo.cpp
--- a/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -8,8 +8,11 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "XCoreMCAsmInfo.h"
+#include "llvm/ADT/StringRef.h"
 using namespace llvm;
=20
+void XCoreMCAsmInfo::anchor() { }
+
 XCoreMCAsmInfo::XCoreMCAsmInfo(const Target &T, StringRef TT) {
   SupportsDebugInformation =3D true;
   Data16bitsDirective =3D "\t.short\t";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/MCT=
argetDesc/XCoreMCAsmInfo.h
--- a/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCAsmInfo.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- XCoreMCAsmInfo.h - XCore asm properties -------------*=
- C++ -*--=3D=3D=3D=3D//
+//=3D=3D=3D-- XCoreMCAsmInfo.h - XCore asm properties ----------------*- C=
++ -*--=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,13 +14,14 @@
 #ifndef XCORETARGETASMINFO_H
 #define XCORETARGETASMINFO_H
=20
-#include "llvm/ADT/StringRef.h"
 #include "llvm/MC/MCAsmInfo.h"
=20
 namespace llvm {
+  class StringRef;
   class Target;
=20
   class XCoreMCAsmInfo : public MCAsmInfo {
+    virtual void anchor();
   public:
     explicit XCoreMCAsmInfo(const Target &T, StringRef TT);
   };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/MCT=
argetDesc/XCoreMCTargetDesc.cpp
--- a/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- XCoreMCTargetDesc.cpp - XCore Target Descriptions -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreMCTargetDesc.cpp - XCore Target Descriptions ----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -17,6 +17,7 @@
 #include "llvm/MC/MCInstrInfo.h"
 #include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/TargetRegistry.h"
=20
 #define GET_INSTRINFO_MC_DESC
@@ -61,9 +62,10 @@
 }
=20
 static MCCodeGenInfo *createXCoreMCCodeGenInfo(StringRef TT, Reloc::Model =
RM,
-                                               CodeModel::Model CM) {
+                                               CodeModel::Model CM,
+                                               CodeGenOpt::Level OL) {
   MCCodeGenInfo *X =3D new MCCodeGenInfo();
-  X->InitMCCodeGenInfo(RM, CM);
+  X->InitMCCodeGenInfo(RM, CM, OL);
   return X;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/MCT=
argetDesc/XCoreMCTargetDesc.h
--- a/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/MCTargetDesc/XCoreMCTargetDesc.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,7 @@
 #define XCOREMCTARGETDESC_H
=20
 namespace llvm {
-class MCSubtargetInfo;
 class Target;
-class StringRef;
=20
 extern Target TheXCoreTarget;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
re.h
--- a/head/contrib/llvm/lib/Target/XCore/XCore.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCore.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -24,7 +24,8 @@
   class XCoreTargetMachine;
   class formatted_raw_ostream;
=20
-  FunctionPass *createXCoreISelDag(XCoreTargetMachine &TM);
+  FunctionPass *createXCoreISelDag(XCoreTargetMachine &TM,
+                                   CodeGenOpt::Level OptLevel);
=20
 } // end namespace llvm;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
re.td
--- a/head/contrib/llvm/lib/Target/XCore/XCore.td	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCore.td	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCore.td - Describe the XCore Target Machine --------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- XCore.td - Describe the XCore Target Machine -------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -7,6 +7,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
+// This is the top level entry point for the XCore target.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reFrameLowering.cpp
--- a/head/contrib/llvm/lib/Target/XCore/XCoreFrameLowering.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreFrameLowering.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- XCoreFrameLowering.cpp - Frame info for XCore Target -----*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- XCoreFrameLowering.cpp - Frame info for XCore Target -------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -12,8 +12,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "XCoreFrameLowering.h"
 #include "XCore.h"
-#include "XCoreFrameLowering.h"
 #include "XCoreInstrInfo.h"
 #include "XCoreMachineFunctionInfo.h"
 #include "llvm/Function.h"
@@ -84,7 +84,8 @@
 }
=20
 bool XCoreFrameLowering::hasFP(const MachineFunction &MF) const {
-  return DisableFramePointerElim(MF) || MF.getFrameInfo()->hasVarSizedObje=
cts();
+  return MF.getTarget().Options.DisableFramePointerElim(MF) ||
+    MF.getFrameInfo()->hasVarSizedObjects();
 }
=20
 void XCoreFrameLowering::emitPrologue(MachineFunction &MF) const {
@@ -92,8 +93,6 @@
   MachineBasicBlock::iterator MBBI =3D MBB.begin();
   MachineFrameInfo *MFI =3D MF.getFrameInfo();
   MachineModuleInfo *MMI =3D &MF.getMMI();
-  const XCoreRegisterInfo *RegInfo =3D
-    static_cast<const XCoreRegisterInfo*>(MF.getTarget().getRegisterInfo()=
);
   const XCoreInstrInfo &TII =3D
     *static_cast<const XCoreInstrInfo*>(MF.getTarget().getInstrInfo());
   XCoreFunctionInfo *XFI =3D MF.getInfo<XCoreFunctionInfo>();
@@ -118,7 +117,7 @@
     // FIXME could emit multiple instructions.
     report_fatal_error("emitPrologue Frame size too big: " + Twine(FrameSi=
ze));
   }
-  bool emitFrameMoves =3D RegInfo->needsFrameMoves(MF);
+  bool emitFrameMoves =3D XCoreRegisterInfo::needsFrameMoves(MF);
=20
   // Do we need to allocate space on the stack?
   if (FrameSize) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reFrameLowering.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreFrameLowering.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreFrameLowering.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- XCoreFrameLowering.h - Frame info for XCore Target -------*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- XCoreFrameLowering.h - Frame info for XCore Target ------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reISelDAGToDAG.cpp
--- a/head/contrib/llvm/lib/Target/XCore/XCoreISelDAGToDAG.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreISelDAGToDAG.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -41,8 +41,8 @@
     const XCoreSubtarget &Subtarget;
=20
   public:
-    XCoreDAGToDAGISel(XCoreTargetMachine &TM)
-      : SelectionDAGISel(TM),
+    XCoreDAGToDAGISel(XCoreTargetMachine &TM, CodeGenOpt::Level OptLevel)
+      : SelectionDAGISel(TM, OptLevel),
         Lowering(*TM.getTargetLowering()),=20
         Subtarget(*TM.getSubtargetImpl()) { }
=20
@@ -83,8 +83,9 @@
 /// createXCoreISelDag - This pass converts a legalized DAG into a=20
 /// XCore-specific DAG, ready for instruction scheduling.
 ///
-FunctionPass *llvm::createXCoreISelDag(XCoreTargetMachine &TM) {
-  return new XCoreDAGToDAGISel(TM);
+FunctionPass *llvm::createXCoreISelDag(XCoreTargetMachine &TM,
+                                       CodeGenOpt::Level OptLevel) {
+  return new XCoreDAGToDAGISel(TM, OptLevel);
 }
=20
 bool XCoreDAGToDAGISel::SelectADDRspii(SDValue Addr, SDValue &Base,
@@ -120,7 +121,7 @@
     ConstantSDNode *CN =3D 0;
     if ((Addr.getOperand(0).getOpcode() =3D=3D XCoreISD::DPRelativeWrapper)
       && (CN =3D dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
-      && (CN->getSExtValue() % 4 =3D=3D 0)) {
+      && (CN->getSExtValue() % 4 =3D=3D 0 && CN->getSExtValue() >=3D 0)) {
       // Constant word offset from a object in the data region
       Base =3D Addr.getOperand(0).getOperand(0);
       Offset =3D CurDAG->getTargetConstant(CN->getSExtValue(), MVT::i32);
@@ -141,7 +142,7 @@
     ConstantSDNode *CN =3D 0;
     if ((Addr.getOperand(0).getOpcode() =3D=3D XCoreISD::CPRelativeWrapper)
       && (CN =3D dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
-      && (CN->getSExtValue() % 4 =3D=3D 0)) {
+      && (CN->getSExtValue() % 4 =3D=3D 0 && CN->getSExtValue() >=3D 0)) {
       // Constant word offset from a object in the data region
       Base =3D Addr.getOperand(0).getOperand(0);
       Offset =3D CurDAG->getTargetConstant(CN->getSExtValue(), MVT::i32);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reISelLowering.cpp
--- a/head/contrib/llvm/lib/Target/XCore/XCoreISelLowering.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreISelLowering.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation   =
------=3D=3D=3D//
+//=3D=3D=3D-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation --=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -36,7 +36,6 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/VectorExtras.h"
 using namespace llvm;
=20
 const char *XCoreTargetLowering::
@@ -109,6 +108,8 @@
   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
   setOperationAction(ISD::ROTL , MVT::i32, Expand);
   setOperationAction(ISD::ROTR , MVT::i32, Expand);
+  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
+  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
=20
   setOperationAction(ISD::TRAP, MVT::Other, Legal);
=20
@@ -186,7 +187,6 @@
   case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
   default:
     llvm_unreachable("unimplemented operand");
-    return SDValue();
   }
 }
=20
@@ -198,7 +198,6 @@
   switch (N->getOpcode()) {
   default:
     llvm_unreachable("Don't know how to custom expand this!");
-    return;
   case ISD::ADD:
   case ISD::SUB:
     Results.push_back(ExpandADDSUB(N, DAG));
@@ -274,9 +273,8 @@
     if (const GlobalAlias *GA =3D dyn_cast<GlobalAlias>(GV))
       GVar =3D dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal()=
);
   }
-  if (! GVar) {
+  if (!GVar) {
     llvm_unreachable("Thread local object not a GlobalVariable?");
-    return SDValue();
   }
   Type *Ty =3D cast<PointerType>(GV->getType())->getElementType();
   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
@@ -386,6 +384,15 @@
     Offset =3D off;
     return true;
   }
+  // Check for an aligned global variable.
+  if (GlobalAddressSDNode *GA =3D dyn_cast<GlobalAddressSDNode>(*Root)) {
+    const GlobalValue *GV =3D GA->getGlobal();
+    if (GA->getOffset() =3D=3D 0 && GV->getAlignment() >=3D 4) {
+      AlignedBase =3D Base;
+      Offset =3D off;
+      return true;
+    }
+  }
   return false;
 }
=20
@@ -418,7 +425,7 @@
       //
       return DAG.getLoad(getPointerTy(), DL, Chain, BasePtr,
                          MachinePointerInfo(),
-                         false, false, 0);
+                         false, false, false, 0);
     }
     // Lower to
     // ldw low, base[offset >> 2]
@@ -435,9 +442,11 @@
     SDValue HighAddr =3D DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOff=
set);
=20
     SDValue Low =3D DAG.getLoad(getPointerTy(), DL, Chain,
-                              LowAddr, MachinePointerInfo(), false, false,=
 0);
+                              LowAddr, MachinePointerInfo(),
+                              false, false, false, 0);
     SDValue High =3D DAG.getLoad(getPointerTy(), DL, Chain,
-                               HighAddr, MachinePointerInfo(), false, fals=
e, 0);
+                               HighAddr, MachinePointerInfo(),
+                               false, false, false, 0);
     SDValue LowShifted =3D DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShi=
ft);
     SDValue HighShifted =3D DAG.getNode(ISD::SHL, DL, MVT::i32, High, High=
Shift);
     SDValue Result =3D DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, High=
Shifted);
@@ -478,8 +487,8 @@
=20
   std::pair<SDValue, SDValue> CallResult =3D
         LowerCallTo(Chain, IntPtrTy, false, false,
-                    false, false, 0, CallingConv::C, false,
-                    /*isReturnValueUsed=3D*/true,
+                    false, false, 0, CallingConv::C, /*isTailCall=3D*/fals=
e,
+                    /*doesNotRet=3D*/false, /*isReturnValueUsed=3D*/true,
                     DAG.getExternalSymbol("__misaligned_load", getPointerT=
y()),
                     Args, DAG, DL);
=20
@@ -540,8 +549,8 @@
=20
   std::pair<SDValue, SDValue> CallResult =3D
         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, fals=
e,
-                    false, false, 0, CallingConv::C, false,
-                    /*isReturnValueUsed=3D*/true,
+                    false, false, 0, CallingConv::C, /*isTailCall=3D*/fals=
e,
+                    /*doesNotRet=3D*/false, /*isReturnValueUsed=3D*/true,
                     DAG.getExternalSymbol("__misaligned_store", getPointer=
Ty()),
                     Args, DAG, dl);
=20
@@ -745,14 +754,14 @@
 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
 {
   llvm_unreachable("unimplemented");
-  // FIX Arguments passed by reference need a extra dereference.
+  // FIXME Arguments passed by reference need a extra dereference.
   SDNode *Node =3D Op.getNode();
   DebugLoc dl =3D Node->getDebugLoc();
   const Value *V =3D cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
   EVT VT =3D Node->getValueType(0);
   SDValue VAList =3D DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
                                Node->getOperand(1), MachinePointerInfo(V),
-                               false, false, 0);
+                               false, false, false, 0);
   // Increment the pointer, VAList, to the next vararg
   SDValue Tmp3 =3D DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
                      DAG.getConstant(VT.getSizeInBits(),
@@ -762,7 +771,7 @@
                       MachinePointerInfo(V), false, false, 0);
   // Load the actual argument out of the pointer VAList
   return DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
-                     false, false, 0);
+                     false, false, false, 0);
 }
=20
 SDValue XCoreTargetLowering::
@@ -866,7 +875,7 @@
 SDValue
 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
                                CallingConv::ID CallConv, bool isVarArg,
-                               bool &isTailCall,
+                               bool doesNotRet, bool &isTailCall,
                                const SmallVectorImpl<ISD::OutputArg> &Outs,
                                const SmallVectorImpl<SDValue> &OutVals,
                                const SmallVectorImpl<ISD::InputArg> &Ins,
@@ -1137,13 +1146,13 @@
       SDValue FIN =3D DAG.getFrameIndex(FI, MVT::i32);
       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
                                    MachinePointerInfo::getFixedStack(FI),
-                                   false, false, 0));
+                                   false, false, false, 0));
     }
   }
=20
   if (isVarArg) {
     /* Argument registers */
-    static const unsigned ArgRegs[] =3D {
+    static const uint16_t ArgRegs[] =3D {
       XCore::R0, XCore::R1, XCore::R2, XCore::R3
     };
     XCoreFunctionInfo *XFI =3D MF.getInfo<XCoreFunctionInfo>();
@@ -1354,8 +1363,8 @@
       APInt KnownZero, KnownOne;
       APInt Mask =3D APInt::getHighBitsSet(VT.getSizeInBits(),
                                          VT.getSizeInBits() - 1);
-      DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
-      if (KnownZero =3D=3D Mask) {
+      DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
+      if ((KnownZero & Mask) =3D=3D Mask) {
         SDValue Carry =3D DAG.getConstant(0, VT);
         SDValue Result =3D DAG.getNode(ISD::ADD, dl, VT, N0, N2);
         SDValue Ops [] =3D { Carry, Result };
@@ -1377,8 +1386,8 @@
       APInt KnownZero, KnownOne;
       APInt Mask =3D APInt::getHighBitsSet(VT.getSizeInBits(),
                                          VT.getSizeInBits() - 1);
-      DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
-      if (KnownZero =3D=3D Mask) {
+      DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
+      if ((KnownZero & Mask) =3D=3D Mask) {
         SDValue Borrow =3D N2;
         SDValue Result =3D DAG.getNode(ISD::SUB, dl, VT,
                                      DAG.getConstant(0, VT), N2);
@@ -1393,8 +1402,8 @@
       APInt KnownZero, KnownOne;
       APInt Mask =3D APInt::getHighBitsSet(VT.getSizeInBits(),
                                          VT.getSizeInBits() - 1);
-      DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
-      if (KnownZero =3D=3D Mask) {
+      DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
+      if ((KnownZero & Mask) =3D=3D Mask) {
         SDValue Borrow =3D DAG.getConstant(0, VT);
         SDValue Result =3D DAG.getNode(ISD::SUB, dl, VT, N0, N2);
         SDValue Ops [] =3D { Borrow, Result };
@@ -1512,21 +1521,19 @@
 }
=20
 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
-                                                         const APInt &Mask,
                                                          APInt &KnownZero,
                                                          APInt &KnownOne,
                                                          const SelectionDA=
G &DAG,
                                                          unsigned Depth) c=
onst {
-  KnownZero =3D KnownOne =3D APInt(Mask.getBitWidth(), 0);
+  KnownZero =3D KnownOne =3D APInt(KnownZero.getBitWidth(), 0);
   switch (Op.getOpcode()) {
   default: break;
   case XCoreISD::LADD:
   case XCoreISD::LSUB:
     if (Op.getResNo() =3D=3D 0) {
       // Top bits of carry / borrow are clear.
-      KnownZero =3D APInt::getHighBitsSet(Mask.getBitWidth(),
-                                        Mask.getBitWidth() - 1);
-      KnownZero &=3D Mask;
+      KnownZero =3D APInt::getHighBitsSet(KnownZero.getBitWidth(),
+                                        KnownZero.getBitWidth() - 1);
     }
     break;
   }
@@ -1590,8 +1597,6 @@
     // reg + reg<<2
     return AM.Scale =3D=3D 4 && AM.BaseOffs =3D=3D 0;
   }
-
-  return false;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reISelLowering.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreISelLowering.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreISelLowering.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -15,9 +15,9 @@
 #ifndef XCOREISELLOWERING_H
 #define XCOREISELLOWERING_H
=20
+#include "XCore.h"
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/Target/TargetLowering.h"
-#include "XCore.h"
=20
 namespace llvm {
=20
@@ -160,7 +160,6 @@
     virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) con=
st;
=20
     virtual void computeMaskedBitsForTargetNode(const SDValue Op,
-                                                const APInt &Mask,
                                                 APInt &KnownZero,
                                                 APInt &KnownOne,
                                                 const SelectionDAG &DAG,
@@ -175,9 +174,8 @@
                            SmallVectorImpl<SDValue> &InVals) const;
=20
     virtual SDValue
-      LowerCall(SDValue Chain, SDValue Callee,
-                CallingConv::ID CallConv, bool isVarArg,
-                bool &isTailCall,
+      LowerCall(SDValue Chain, SDValue Callee, CallingConv::ID CallConv,
+                bool isVarArg, bool doesNotRet, bool &isTailCall,
                 const SmallVectorImpl<ISD::OutputArg> &Outs,
                 const SmallVectorImpl<SDValue> &OutVals,
                 const SmallVectorImpl<ISD::InputArg> &Ins,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reInstrFormats.td
--- a/head/contrib/llvm/lib/Target/XCore/XCoreInstrFormats.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreInstrFormats.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreInstrFormats.td - XCore Instruction Formats ----*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreInstrFormats.td - XCore Instruction Formats ---*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reInstrInfo.cpp
--- a/head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreInstrInfo.cpp - XCore Instruction Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreInstrInfo.cpp - XCore Instruction Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -11,8 +11,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "XCoreInstrInfo.h"
 #include "XCoreMachineFunctionInfo.h"
-#include "XCoreInstrInfo.h"
 #include "XCore.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reInstrInfo.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreInstrInfo.h - XCore Instruction Information ---------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreInstrInfo.h - XCore Instruction Information --------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,8 +14,8 @@
 #ifndef XCOREINSTRUCTIONINFO_H
 #define XCOREINSTRUCTIONINFO_H
=20
+#include "XCoreRegisterInfo.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "XCoreRegisterInfo.h"
=20
 #define GET_INSTRINFO_HEADER
 #include "XCoreGenInstrInfo.inc"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reInstrInfo.td
--- a/head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.td	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreInstrInfo.td	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreInstrInfo.td - Target Description for XCore ----*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreInstrInfo.td - Target Description for XCore ---*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reMachineFunctionInfo.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreMachineFunctionInfo.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreMachineFunctionInfo.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D- XCoreMachineFuctionInfo.h - XCore machine function info -*=
- C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreMachineFuctionInfo.h - XCore machine function info -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -26,7 +26,7 @@
 /// XCoreFunctionInfo - This class is derived from MachineFunction private
 /// XCore target-specific information for each MachineFunction.
 class XCoreFunctionInfo : public MachineFunctionInfo {
-private:
+  virtual void anchor();
   bool UsesLR;
   int LRSpillSlot;
   int FPSpillSlot;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reRegisterInfo.cpp
--- a/head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreRegisterInfo.cpp - XCore Register Information -------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreRegisterInfo.cpp - XCore Register Information ---------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -14,6 +14,8 @@
 #include "XCoreRegisterInfo.h"
 #include "XCoreMachineFunctionInfo.h"
 #include "XCore.h"
+#include "llvm/Type.h"
+#include "llvm/Function.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
@@ -24,8 +26,6 @@
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/Target/TargetInstrInfo.h"
-#include "llvm/Type.h"
-#include "llvm/Function.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Debug.h"
@@ -54,28 +54,14 @@
   return val < (1 << 16);
 }
=20
-static const unsigned XCore_ArgRegs[] =3D {
-  XCore::R0, XCore::R1, XCore::R2, XCore::R3
-};
-
-const unsigned * XCoreRegisterInfo::getArgRegs(const MachineFunction *MF)
-{
-  return XCore_ArgRegs;
-}
-
-unsigned XCoreRegisterInfo::getNumArgRegs(const MachineFunction *MF)
-{
-  return array_lengthof(XCore_ArgRegs);
-}
-
 bool XCoreRegisterInfo::needsFrameMoves(const MachineFunction &MF) {
   return MF.getMMI().hasDebugInfo() ||
     MF.getFunction()->needsUnwindTableEntry();
 }
=20
-const unsigned* XCoreRegisterInfo::getCalleeSavedRegs(const MachineFunctio=
n *MF)
+const uint16_t* XCoreRegisterInfo::getCalleeSavedRegs(const MachineFunctio=
n *MF)
                                                                          c=
onst {
-  static const unsigned CalleeSavedRegs[] =3D {
+  static const uint16_t CalleeSavedRegs[] =3D {
     XCore::R4, XCore::R5, XCore::R6, XCore::R7,
     XCore::R8, XCore::R9, XCore::R10, XCore::LR,
     0
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reRegisterInfo.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreRegisterInfo.h - XCore Register Information Impl ----*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreRegisterInfo.h - XCore Register Information Impl ---*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -44,7 +44,7 @@
=20
   /// Code Generation virtual methods...
=20
-  const unsigned *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
+  const uint16_t *getCalleeSavedRegs(const MachineFunction *MF =3D 0) cons=
t;
=20
   BitVector getReservedRegs(const MachineFunction &MF) const;
  =20
@@ -62,15 +62,6 @@
   // Debug information queries.
   unsigned getFrameRegister(const MachineFunction &MF) const;
=20
-  //! Return the array of argument passing registers
-  /*!
-    \note The size of this array is returned by getArgRegsSize().
-    */
-  static const unsigned *getArgRegs(const MachineFunction *MF =3D 0);
-
-  //! Return the size of the argument passing register array
-  static unsigned getNumArgRegs(const MachineFunction *MF =3D 0);
- =20
   //! Return whether to emit frame moves
   static bool needsFrameMoves(const MachineFunction &MF);
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reRegisterInfo.td
--- a/head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.td	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreRegisterInfo.td	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreRegisterInfo.td - XCore Register defs ----------*- table=
gen -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreRegisterInfo.td - XCore Register defs ---------*- table=
gen -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reSubtarget.cpp
--- a/head/contrib/llvm/lib/Target/XCore/XCoreSubtarget.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreSubtarget.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D- XCoreSubtarget.cpp - XCore Subtarget Information -----------*=
- C++ -*-=3D//
+//=3D=3D=3D-- XCoreSubtarget.cpp - XCore Subtarget Information -----------=
-------=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -21,6 +21,8 @@
=20
 using namespace llvm;
=20
+void XCoreSubtarget::anchor() { }
+
 XCoreSubtarget::XCoreSubtarget(const std::string &TT,
                                const std::string &CPU, const std::string &=
FS)
   : XCoreGenSubtargetInfo(TT, CPU, FS)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reSubtarget.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreSubtarget.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreSubtarget.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D=3D=3D-- XCoreSubtarget.h - Define Subtarget for the XCore ----=
-*- C++ -*--=3D=3D//
+//=3D=3D=3D-- XCoreSubtarget.h - Define Subtarget for the XCore -------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -25,6 +25,7 @@
 class StringRef;
=20
 class XCoreSubtarget : public XCoreGenSubtargetInfo {
+  virtual void anchor();
=20
 public:
   /// This constructor initializes the data members to match that
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reTargetMachine.cpp
--- a/head/contrib/llvm/lib/Target/XCore/XCoreTargetMachine.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreTargetMachine.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #include "XCore.h"
 #include "llvm/Module.h"
 #include "llvm/PassManager.h"
+#include "llvm/CodeGen/Passes.h"
 #include "llvm/Support/TargetRegistry.h"
 using namespace llvm;
=20
@@ -21,8 +22,10 @@
 ///
 XCoreTargetMachine::XCoreTargetMachine(const Target &T, StringRef TT,
                                        StringRef CPU, StringRef FS,
-                                       Reloc::Model RM, CodeModel::Model C=
M)
-  : LLVMTargetMachine(T, TT, CPU, FS, RM, CM),
+                                       const TargetOptions &Options,
+                                       Reloc::Model RM, CodeModel::Model C=
M,
+                                       CodeGenOpt::Level OL)
+  : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
     Subtarget(TT, CPU, FS),
     DataLayout("e-p:32:32:32-a0:0:32-f32:32:32-f64:32:32-i1:8:32-i8:8:32-"
                "i16:16:32-i32:32:32-i64:32:32-n32"),
@@ -32,9 +35,27 @@
     TSInfo(*this) {
 }
=20
-bool XCoreTargetMachine::addInstSelector(PassManagerBase &PM,
-                                         CodeGenOpt::Level OptLevel) {
-  PM.add(createXCoreISelDag(*this));
+namespace {
+/// XCore Code Generator Pass Configuration Options.
+class XCorePassConfig : public TargetPassConfig {
+public:
+  XCorePassConfig(XCoreTargetMachine *TM, PassManagerBase &PM)
+    : TargetPassConfig(TM, PM) {}
+
+  XCoreTargetMachine &getXCoreTargetMachine() const {
+    return getTM<XCoreTargetMachine>();
+  }
+
+  virtual bool addInstSelector();
+};
+} // namespace
+
+TargetPassConfig *XCoreTargetMachine::createPassConfig(PassManagerBase &PM=
) {
+  return new XCorePassConfig(this, PM);
+}
+
+bool XCorePassConfig::addInstSelector() {
+  PM.add(createXCoreISelDag(getXCoreTargetMachine(), getOptLevel()));
   return false;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reTargetMachine.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreTargetMachine.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreTargetMachine.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -14,13 +14,13 @@
 #ifndef XCORETARGETMACHINE_H
 #define XCORETARGETMACHINE_H
=20
-#include "llvm/Target/TargetMachine.h"
-#include "llvm/Target/TargetData.h"
 #include "XCoreFrameLowering.h"
 #include "XCoreSubtarget.h"
 #include "XCoreInstrInfo.h"
 #include "XCoreISelLowering.h"
 #include "XCoreSelectionDAGInfo.h"
+#include "llvm/Target/TargetMachine.h"
+#include "llvm/Target/TargetData.h"
=20
 namespace llvm {
=20
@@ -33,8 +33,9 @@
   XCoreSelectionDAGInfo TSInfo;
 public:
   XCoreTargetMachine(const Target &T, StringRef TT,
-                     StringRef CPU, StringRef FS,
-                     Reloc::Model RM, CodeModel::Model CM);
+                     StringRef CPU, StringRef FS, const TargetOptions &Opt=
ions,
+                     Reloc::Model RM, CodeModel::Model CM,
+                     CodeGenOpt::Level OL);
=20
   virtual const XCoreInstrInfo *getInstrInfo() const { return &InstrInfo; }
   virtual const XCoreFrameLowering *getFrameLowering() const {
@@ -55,7 +56,7 @@
   virtual const TargetData       *getTargetData() const { return &DataLayo=
ut; }
=20
   // Pass Pipeline Configuration
-  virtual bool addInstSelector(PassManagerBase &PM, CodeGenOpt::Level OptL=
evel);
+  virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
 };
=20
 } // end namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Target/XCore/XCo=
reTargetObjectFile.h
--- a/head/contrib/llvm/lib/Target/XCore/XCoreTargetObjectFile.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Target/XCore/XCoreTargetObjectFile.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- llvm/Target/XCoreTargetObjectFile.h - XCore Object Info -*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D-- XCoreTargetObjectFile.h - XCore Object Info -------------*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/C=
onstantMerge.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/ConstantMerge.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/ConstantMerge.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -140,18 +140,24 @@
           UsedGlobals.count(GV))
         continue;
=20
+      // This transformation is legal for weak ODR globals in the sense it
+      // doesn't change semantics, but we really don't want to perform it
+      // anyway; it's likely to pessimize code generation, and some tools
+      // (like the Darwin linker in cases involving CFString) don't expect=
 it.
+      if (GV->isWeakForLinker())
+        continue;
+
       Constant *Init =3D GV->getInitializer();
=20
       // Check to see if the initializer is already known.
       PointerIntPair<Constant*, 1, bool> Pair(Init, hasKnownAlignment(GV));
       GlobalVariable *&Slot =3D CMap[Pair];
=20
-      // If this is the first constant we find or if the old on is local,
-      // replace with the current one. It the current is externally visible
+      // If this is the first constant we find or if the old one is local,
+      // replace with the current one. If the current is externally visible
       // it cannot be replace, but can be the canonical constant we merge =
with.
-      if (Slot =3D=3D 0 || IsBetterCannonical(*GV, *Slot)) {
+      if (Slot =3D=3D 0 || IsBetterCannonical(*GV, *Slot))
         Slot =3D GV;
-      }
     }
=20
     // Second: identify all globals that can be merged together, filling in
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/D=
eadArgumentElimination.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -74,7 +74,7 @@
=20
       std::string getDescription() const {
         return std::string((IsArg ? "Argument #" : "Return value #"))
-               + utostr(Idx) + " of function " + F->getNameStr();
+               + utostr(Idx) + " of function " + F->getName().str();
       }
     };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/F=
unctionAttrs.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/FunctionAttrs.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/FunctionAttrs.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -27,6 +27,7 @@
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Analysis/CallGraph.h"
 #include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/ADT/SCCIterator.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/ADT/UniqueVector.h"
@@ -225,31 +226,247 @@
   return MadeChange;
 }
=20
+namespace {
+  // For a given pointer Argument, this retains a list of Arguments of fun=
ctions
+  // in the same SCC that the pointer data flows into. We use this to buil=
d an
+  // SCC of the arguments.
+  struct ArgumentGraphNode {
+    Argument *Definition;
+    SmallVector<ArgumentGraphNode*, 4> Uses;
+  };
+
+  class ArgumentGraph {
+    // We store pointers to ArgumentGraphNode objects, so it's important t=
hat
+    // that they not move around upon insert.
+    typedef std::map<Argument*, ArgumentGraphNode> ArgumentMapTy;
+
+    ArgumentMapTy ArgumentMap;
+
+    // There is no root node for the argument graph, in fact:
+    //   void f(int *x, int *y) { if (...) f(x, y); }
+    // is an example where the graph is disconnected. The SCCIterator requ=
ires a
+    // single entry point, so we maintain a fake ("synthetic") root node t=
hat
+    // uses every node. Because the graph is directed and nothing points i=
nto
+    // the root, it will not participate in any SCCs (except for its own).
+    ArgumentGraphNode SyntheticRoot;
+
+  public:
+    ArgumentGraph() { SyntheticRoot.Definition =3D 0; }
+
+    typedef SmallVectorImpl<ArgumentGraphNode*>::iterator iterator;
+
+    iterator begin() { return SyntheticRoot.Uses.begin(); }
+    iterator end() { return SyntheticRoot.Uses.end(); }
+    ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
+
+    ArgumentGraphNode *operator[](Argument *A) {
+      ArgumentGraphNode &Node =3D ArgumentMap[A];
+      Node.Definition =3D A;
+      SyntheticRoot.Uses.push_back(&Node);
+      return &Node;
+    }
+  };
+
+  // This tracker checks whether callees are in the SCC, and if so it does=
 not
+  // consider that a capture, instead adding it to the "Uses" list and
+  // continuing with the analysis.
+  struct ArgumentUsesTracker : public CaptureTracker {
+    ArgumentUsesTracker(const SmallPtrSet<Function*, 8> &SCCNodes)
+      : Captured(false), SCCNodes(SCCNodes) {}
+
+    void tooManyUses() { Captured =3D true; }
+
+    bool shouldExplore(Use *U) { return true; }
+
+    bool captured(Use *U) {
+      CallSite CS(U->getUser());
+      if (!CS.getInstruction()) { Captured =3D true; return true; }
+
+      Function *F =3D CS.getCalledFunction();
+      if (!F || !SCCNodes.count(F)) { Captured =3D true; return true; }
+
+      Function::arg_iterator AI =3D F->arg_begin(), AE =3D F->arg_end();
+      for (CallSite::arg_iterator PI =3D CS.arg_begin(), PE =3D CS.arg_end=
();
+           PI !=3D PE; ++PI, ++AI) {
+        if (AI =3D=3D AE) {
+          assert(F->isVarArg() && "More params than args in non-varargs ca=
ll");
+          Captured =3D true;
+          return true;
+        }
+        if (PI =3D=3D U) {
+          Uses.push_back(AI);
+          break;
+        }
+      }
+      assert(!Uses.empty() && "Capturing call-site captured nothing?");
+      return false;
+    }
+
+    bool Captured;  // True only if certainly captured (used outside our S=
CC).
+    SmallVector<Argument*, 4> Uses;  // Uses within our SCC.
+
+    const SmallPtrSet<Function*, 8> &SCCNodes;
+  };
+}
+
+namespace llvm {
+  template<> struct GraphTraits<ArgumentGraphNode*> {
+    typedef ArgumentGraphNode NodeType;
+    typedef SmallVectorImpl<ArgumentGraphNode*>::iterator ChildIteratorTyp=
e;
+
+    static inline NodeType *getEntryNode(NodeType *A) { return A; }
+    static inline ChildIteratorType child_begin(NodeType *N) {
+      return N->Uses.begin();
+    }
+    static inline ChildIteratorType child_end(NodeType *N) {
+      return N->Uses.end();
+    }
+  };
+  template<> struct GraphTraits<ArgumentGraph*>
+    : public GraphTraits<ArgumentGraphNode*> {
+    static NodeType *getEntryNode(ArgumentGraph *AG) {
+      return AG->getEntryNode();
+    }
+    static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
+      return AG->begin();
+    }
+    static ChildIteratorType nodes_end(ArgumentGraph *AG) {
+      return AG->end();
+    }
+  };
+}
+
 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
   bool Changed =3D false;
=20
+  SmallPtrSet<Function*, 8> SCCNodes;
+
+  // Fill SCCNodes with the elements of the SCC.  Used for quickly
+  // looking up whether a given CallGraphNode is in this SCC.
+  for (CallGraphSCC::iterator I =3D SCC.begin(), E =3D SCC.end(); I !=3D E=
; ++I) {
+    Function *F =3D (*I)->getFunction();
+    if (F && !F->isDeclaration() && !F->mayBeOverridden())
+      SCCNodes.insert(F);
+  }
+
+  ArgumentGraph AG;
+
   // Check each function in turn, determining which pointer arguments are =
not
   // captured.
   for (CallGraphSCC::iterator I =3D SCC.begin(), E =3D SCC.end(); I !=3D E=
; ++I) {
     Function *F =3D (*I)->getFunction();
=20
     if (F =3D=3D 0)
-      // External node - skip it;
+      // External node - only a problem for arguments that we pass to it.
       continue;
=20
     // Definitions with weak linkage may be overridden at linktime with
-    // something that writes memory, so treat them like declarations.
+    // something that captures pointers, so treat them like declarations.
     if (F->isDeclaration() || F->mayBeOverridden())
       continue;
=20
+    // Functions that are readonly (or readnone) and nounwind and don't re=
turn
+    // a value can't capture arguments. Don't analyze them.
+    if (F->onlyReadsMemory() && F->doesNotThrow() &&
+        F->getReturnType()->isVoidTy()) {
+      for (Function::arg_iterator A =3D F->arg_begin(), E =3D F->arg_end();
+           A !=3D E; ++A) {
+        if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
+          A->addAttr(Attribute::NoCapture);
+          ++NumNoCapture;
+          Changed =3D true;
+        }
+      }
+      continue;
+    }
+
     for (Function::arg_iterator A =3D F->arg_begin(), E =3D F->arg_end(); =
A!=3DE; ++A)
-      if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
-          !PointerMayBeCaptured(A, true, /*StoreCaptures=3D*/false)) {
-        A->addAttr(Attribute::NoCapture);
+      if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
+        ArgumentUsesTracker Tracker(SCCNodes);
+        PointerMayBeCaptured(A, &Tracker);
+        if (!Tracker.Captured) {
+          if (Tracker.Uses.empty()) {
+            // If it's trivially not captured, mark it nocapture now.
+            A->addAttr(Attribute::NoCapture);
+            ++NumNoCapture;
+            Changed =3D true;
+          } else {
+            // If it's not trivially captured and not trivially not captur=
ed,
+            // then it must be calling into another function in our SCC. S=
ave
+            // its particulars for Argument-SCC analysis later.
+            ArgumentGraphNode *Node =3D AG[A];
+            for (SmallVectorImpl<Argument*>::iterator UI =3D Tracker.Uses.=
begin(),
+                   UE =3D Tracker.Uses.end(); UI !=3D UE; ++UI)
+              Node->Uses.push_back(AG[*UI]);
+          }
+        }
+        // Otherwise, it's captured. Don't bother doing SCC analysis on it.
+      }
+  }
+
+  // The graph we've collected is partial because we stopped scanning for
+  // argument uses once we solved the argument trivially. These partial no=
des
+  // show up as ArgumentGraphNode objects with an empty Uses list, and for
+  // these nodes the final decision about whether they capture has already=
 been
+  // made.  If the definition doesn't have a 'nocapture' attribute by now,=
 it
+  // captures.
+
+  for (scc_iterator<ArgumentGraph*> I =3D scc_begin(&AG), E =3D scc_end(&A=
G);
+       I !=3D E; ++I) {
+    std::vector<ArgumentGraphNode*> &ArgumentSCC =3D *I;
+    if (ArgumentSCC.size() =3D=3D 1) {
+      if (!ArgumentSCC[0]->Definition) continue;  // synthetic root node
+
+      // eg. "void f(int* x) { if (...) f(x); }"
+      if (ArgumentSCC[0]->Uses.size() =3D=3D 1 &&
+          ArgumentSCC[0]->Uses[0] =3D=3D ArgumentSCC[0]) {
+        ArgumentSCC[0]->Definition->addAttr(Attribute::NoCapture);
         ++NumNoCapture;
         Changed =3D true;
       }
+      continue;
+    }
+
+    bool SCCCaptured =3D false;
+    for (std::vector<ArgumentGraphNode*>::iterator I =3D ArgumentSCC.begin=
(),
+           E =3D ArgumentSCC.end(); I !=3D E && !SCCCaptured; ++I) {
+      ArgumentGraphNode *Node =3D *I;
+      if (Node->Uses.empty()) {
+        if (!Node->Definition->hasNoCaptureAttr())
+          SCCCaptured =3D true;
+      }
+    }
+    if (SCCCaptured) continue;
+
+    SmallPtrSet<Argument*, 8> ArgumentSCCNodes;
+    // Fill ArgumentSCCNodes with the elements of the ArgumentSCC.  Used f=
or
+    // quickly looking up whether a given Argument is in this ArgumentSCC.
+    for (std::vector<ArgumentGraphNode*>::iterator I =3D ArgumentSCC.begin=
(),
+           E =3D ArgumentSCC.end(); I !=3D E; ++I) {
+      ArgumentSCCNodes.insert((*I)->Definition);
+    }
+
+    for (std::vector<ArgumentGraphNode*>::iterator I =3D ArgumentSCC.begin=
(),
+           E =3D ArgumentSCC.end(); I !=3D E && !SCCCaptured; ++I) {
+      ArgumentGraphNode *N =3D *I;
+      for (SmallVectorImpl<ArgumentGraphNode*>::iterator UI =3D N->Uses.be=
gin(),
+             UE =3D N->Uses.end(); UI !=3D UE; ++UI) {
+        Argument *A =3D (*UI)->Definition;
+        if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
+          continue;
+        SCCCaptured =3D true;
+        break;
+      }
+    }
+    if (SCCCaptured) continue;
+
+    for (unsigned i =3D 0, e =3D ArgumentSCC.size(); i !=3D e; ++i) {
+      Argument *A =3D ArgumentSCC[i]->Definition;
+      A->addAttr(Attribute::NoCapture);
+      ++NumNoCapture;
+      Changed =3D true;
+    }
   }
=20
   return Changed;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/G=
lobalOpt.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/GlobalOpt.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/GlobalOpt.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -26,6 +26,7 @@
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Support/CallSite.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -61,6 +62,7 @@
   struct GlobalStatus;
   struct GlobalOpt : public ModulePass {
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+      AU.addRequired<TargetLibraryInfo>();
     }
     static char ID; // Pass identification, replacement for typeid
     GlobalOpt() : ModulePass(ID) {
@@ -80,11 +82,17 @@
                                const SmallPtrSet<const PHINode*, 16> &PHIU=
sers,
                                const GlobalStatus &GS);
     bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
+
+    TargetData *TD;
+    TargetLibraryInfo *TLI;
   };
 }
=20
 char GlobalOpt::ID =3D 0;
-INITIALIZE_PASS(GlobalOpt, "globalopt",
+INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
+                "Global Variable Optimizer", false, false)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
+INITIALIZE_PASS_END(GlobalOpt, "globalopt",
                 "Global Variable Optimizer", false, false)
=20
 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
@@ -143,18 +151,31 @@
   /// HasPHIUser - Set to true if this global has a user that is a PHI nod=
e.
   bool HasPHIUser;
=20
+  /// AtomicOrdering - Set to the strongest atomic ordering requirement.
+  AtomicOrdering Ordering;
+
   GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStore=
d),
                    StoredOnceValue(0), AccessingFunction(0),
-                   HasMultipleAccessingFunctions(false), HasNonInstruction=
User(false),
-                   HasPHIUser(false) {}
+                   HasMultipleAccessingFunctions(false),
+                   HasNonInstructionUser(false), HasPHIUser(false),
+                   Ordering(NotAtomic) {}
 };
=20
 }
=20
-// SafeToDestroyConstant - It is safe to destroy a constant iff it is only=
 used
-// by constants itself.  Note that constants cannot be cyclic, so this tes=
t is
-// pretty easy to implement recursively.
-//
+/// StrongerOrdering - Return the stronger of the two ordering. If the two
+/// orderings are acquire and release, then return AcquireRelease.
+///
+static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y)=
 {
+  if (X =3D=3D Acquire && Y =3D=3D Release) return AcquireRelease;
+  if (Y =3D=3D Acquire && X =3D=3D Release) return AcquireRelease;
+  return (AtomicOrdering)std::max(X, Y);
+}
+
+/// SafeToDestroyConstant - It is safe to destroy a constant iff it is onl=
y used
+/// by constants itself.  Note that constants cannot be cyclic, so this te=
st is
+/// pretty easy to implement recursively.
+///
 static bool SafeToDestroyConstant(const Constant *C) {
   if (isa<GlobalValue>(C)) return false;
=20
@@ -195,14 +216,16 @@
       }
       if (const LoadInst *LI =3D dyn_cast<LoadInst>(I)) {
         GS.isLoaded =3D true;
-        // Don't hack on volatile/atomic loads.
-        if (!LI->isSimple()) return true;
+        // Don't hack on volatile loads.
+        if (LI->isVolatile()) return true;
+        GS.Ordering =3D StrongerOrdering(GS.Ordering, LI->getOrdering());
       } else if (const StoreInst *SI =3D dyn_cast<StoreInst>(I)) {
         // Don't allow a store OF the address, only stores TO the address.
         if (SI->getOperand(0) =3D=3D V) return true;
=20
-        // Don't hack on volatile/atomic stores.
-        if (!SI->isSimple()) return true;
+        // Don't hack on volatile stores.
+        if (SI->isVolatile()) return true;
+        GS.Ordering =3D StrongerOrdering(GS.Ordering, SI->getOrdering());
=20
         // If this is a direct store to the global (i.e., the global is a =
scalar
         // value, not an aggregate), keep more specific information about
@@ -271,43 +294,12 @@
   return false;
 }
=20
-static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx)=
 {
-  ConstantInt *CI =3D dyn_cast<ConstantInt>(Idx);
-  if (!CI) return 0;
-  unsigned IdxV =3D CI->getZExtValue();
-
-  if (ConstantStruct *CS =3D dyn_cast<ConstantStruct>(Agg)) {
-    if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
-  } else if (ConstantArray *CA =3D dyn_cast<ConstantArray>(Agg)) {
-    if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
-  } else if (ConstantVector *CP =3D dyn_cast<ConstantVector>(Agg)) {
-    if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
-  } else if (isa<ConstantAggregateZero>(Agg)) {
-    if (StructType *STy =3D dyn_cast<StructType>(Agg->getType())) {
-      if (IdxV < STy->getNumElements())
-        return Constant::getNullValue(STy->getElementType(IdxV));
-    } else if (SequentialType *STy =3D
-               dyn_cast<SequentialType>(Agg->getType())) {
-      return Constant::getNullValue(STy->getElementType());
-    }
-  } else if (isa<UndefValue>(Agg)) {
-    if (StructType *STy =3D dyn_cast<StructType>(Agg->getType())) {
-      if (IdxV < STy->getNumElements())
-        return UndefValue::get(STy->getElementType(IdxV));
-    } else if (SequentialType *STy =3D
-               dyn_cast<SequentialType>(Agg->getType())) {
-      return UndefValue::get(STy->getElementType());
-    }
-  }
-  return 0;
-}
-
-
 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
 /// users of the global, cleaning up the obvious ones.  This is largely ju=
st a
 /// quick scan over the use list to clean up the easy and obvious cruft.  =
This
 /// returns true if it made a change.
-static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
+static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
+                                       TargetData *TD, TargetLibraryInfo *=
TLI) {
   bool Changed =3D false;
   for (Value::use_iterator UI =3D V->use_begin(), E =3D V->use_end(); UI !=
=3D E;) {
     User *U =3D *UI++;
@@ -328,11 +320,11 @@
         Constant *SubInit =3D 0;
         if (Init)
           SubInit =3D ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
-        Changed |=3D CleanupConstantGlobalUsers(CE, SubInit);
+        Changed |=3D CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
       } else if (CE->getOpcode() =3D=3D Instruction::BitCast &&
                  CE->getType()->isPointerTy()) {
         // Pointer cast, delete any stores and memsets to the global.
-        Changed |=3D CleanupConstantGlobalUsers(CE, 0);
+        Changed |=3D CleanupConstantGlobalUsers(CE, 0, TD, TLI);
       }
=20
       if (CE->use_empty()) {
@@ -346,11 +338,17 @@
       Constant *SubInit =3D 0;
       if (!isa<ConstantExpr>(GEP->getOperand(0))) {
         ConstantExpr *CE =3D
-          dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
+          dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, =
TLI));
         if (Init && CE && CE->getOpcode() =3D=3D Instruction::GetElementPt=
r)
           SubInit =3D ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
+
+        // If the initializer is an all-null value and we have an inbounds=
 GEP,
+        // we already know what the result of any load from that GEP is.
+        // TODO: Handle splats.
+        if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
+          SubInit =3D Constant::getNullValue(GEP->getType()->getElementTyp=
e());
       }
-      Changed |=3D CleanupConstantGlobalUsers(GEP, SubInit);
+      Changed |=3D CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
=20
       if (GEP->use_empty()) {
         GEP->eraseFromParent();
@@ -368,7 +366,7 @@
       if (SafeToDestroyConstant(C)) {
         C->destroyConstant();
         // This could have invalidated UI, start over from scratch.
-        CleanupConstantGlobalUsers(V, Init);
+        CleanupConstantGlobalUsers(V, Init, TD, TLI);
         return true;
       }
     }
@@ -514,8 +512,7 @@
     NewGlobals.reserve(STy->getNumElements());
     const StructLayout &Layout =3D *TD.getStructLayout(STy);
     for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i) {
-      Constant *In =3D getAggregateConstantElement(Init,
-                    ConstantInt::get(Type::getInt32Ty(STy->getContext()), =
i));
+      Constant *In =3D Init->getAggregateElement(i);
       assert(In && "Couldn't get element of initializer?");
       GlobalVariable *NGV =3D new GlobalVariable(STy->getElementType(i), f=
alse,
                                                GlobalVariable::InternalLin=
kage,
@@ -547,8 +544,7 @@
     uint64_t EltSize =3D TD.getTypeAllocSize(STy->getElementType());
     unsigned EltAlign =3D TD.getABITypeAlignment(STy->getElementType());
     for (unsigned i =3D 0, e =3D NumElements; i !=3D e; ++i) {
-      Constant *In =3D getAggregateConstantElement(Init,
-                    ConstantInt::get(Type::getInt32Ty(Init->getContext()),=
 i));
+      Constant *In =3D Init->getAggregateElement(i);
       assert(In && "Couldn't get element of initializer?");
=20
       GlobalVariable *NGV =3D new GlobalVariable(STy->getElementType(), fa=
lse,
@@ -770,7 +766,9 @@
 /// value stored into it.  If there are uses of the loaded value that woul=
d trap
 /// if the loaded value is dynamically null, then we know that they cannot=
 be
 /// reachable with a null optimize away the load.
-static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *=
LV) {
+static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *=
LV,
+                                            TargetData *TD,
+                                            TargetLibraryInfo *TLI) {
   bool Changed =3D false;
=20
   // Keep track of whether we are able to remove all the uses of the global
@@ -813,7 +811,7 @@
   // nor is the global.
   if (AllNonStoreUsesGone) {
     DEBUG(dbgs() << "  *** GLOBAL NOW DEAD!\n");
-    CleanupConstantGlobalUsers(GV, 0);
+    CleanupConstantGlobalUsers(GV, 0, TD, TLI);
     if (GV->use_empty()) {
       GV->eraseFromParent();
       ++NumDeleted;
@@ -825,10 +823,11 @@
=20
 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of =
the
 /// instructions that are foldable.
-static void ConstantPropUsersOf(Value *V) {
+static void ConstantPropUsersOf(Value *V,
+                                TargetData *TD, TargetLibraryInfo *TLI) {
   for (Value::use_iterator UI =3D V->use_begin(), E =3D V->use_end(); UI !=
=3D E; )
     if (Instruction *I =3D dyn_cast<Instruction>(*UI++))
-      if (Constant *NewC =3D ConstantFoldInstruction(I)) {
+      if (Constant *NewC =3D ConstantFoldInstruction(I, TD, TLI)) {
         I->replaceAllUsesWith(NewC);
=20
         // Advance UI to the next non-I use to avoid invalidating it!
@@ -848,7 +847,8 @@
                                                      CallInst *CI,
                                                      Type *AllocTy,
                                                      ConstantInt *NElement=
s,
-                                                     TargetData* TD) {
+                                                     TargetData *TD,
+                                                     TargetLibraryInfo *TL=
I) {
   DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << "  CALL =3D " << *CI << '=
\n');
=20
   Type *GlobalType;
@@ -906,7 +906,8 @@
   while (!GV->use_empty()) {
     if (StoreInst *SI =3D dyn_cast<StoreInst>(GV->use_back())) {
       // The global is initialized when the store to it occurs.
-      new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
+      new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, fals=
e, 0,
+                    SI->getOrdering(), SI->getSynchScope(), SI);
       SI->eraseFromParent();
       continue;
     }
@@ -921,7 +922,10 @@
=20
       ICmpInst *ICI =3D cast<ICmpInst>(LoadUse.getUser());
       // Replace the cmp X, 0 with a use of the bool value.
-      Value *LV =3D new LoadInst(InitBool, InitBool->getName()+".val", ICI=
);
+      // Sink the load to where the compare was, if atomic rules allow us =
to.
+      Value *LV =3D new LoadInst(InitBool, InitBool->getName()+".val", fal=
se, 0,
+                               LI->getOrdering(), LI->getSynchScope(),
+                               LI->isUnordered() ? (Instruction*)ICI : LI);
       InitBoolUsed =3D true;
       switch (ICI->getPredicate()) {
       default: llvm_unreachable("Unknown ICmp Predicate!");
@@ -962,9 +966,9 @@
   // To further other optimizations, loop over all users of NewGV and try =
to
   // constant prop them.  This will promote GEP instructions with constant
   // indices into GEP constant-exprs, which will allow global-opt to hack =
on it.
-  ConstantPropUsersOf(NewGV);
+  ConstantPropUsersOf(NewGV, TD, TLI);
   if (RepValue !=3D NewGV)
-    ConstantPropUsersOf(RepValue);
+    ConstantPropUsersOf(RepValue, TD, TLI);
=20
   return NewGV;
 }
@@ -1203,7 +1207,6 @@
     PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
   } else {
     llvm_unreachable("Unknown usable value");
-    Result =3D 0;
   }
=20
   return FieldVals[FieldNo] =3D Result;
@@ -1293,9 +1296,9 @@
 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. =
 Break
 /// it up into multiple allocations of arrays of the fields.
 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *=
CI,
-                                            Value* NElems, TargetData *TD)=
 {
+                                            Value *NElems, TargetData *TD)=
 {
   DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << "  MALLOC =3D " << *CI << =
'\n');
-  Type* MAT =3D getMallocAllocatedType(CI);
+  Type *MAT =3D getMallocAllocatedType(CI);
   StructType *STy =3D cast<StructType>(MAT);
=20
   // There is guaranteed to be at least one use of the malloc (storing
@@ -1482,8 +1485,10 @@
 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
                                                CallInst *CI,
                                                Type *AllocTy,
+                                               AtomicOrdering Ordering,
                                                Module::global_iterator &GV=
I,
-                                               TargetData *TD) {
+                                               TargetData *TD,
+                                               TargetLibraryInfo *TLI) {
   if (!TD)
     return false;
=20
@@ -1502,7 +1507,7 @@
=20
   // We can't optimize this if the malloc itself is used in a complex way,
   // for example, being stored into multiple globals.  This allows the
-  // malloc to be stored into the specified global, loaded setcc'd, and
+  // malloc to be stored into the specified global, loaded icmp'd, and
   // GEP'd.  These are all things we could transform to using the global
   // for.
   SmallPtrSet<const PHINode*, 8> PHIs;
@@ -1523,7 +1528,7 @@
     // (2048 bytes currently), as we don't want to introduce a 16M global =
or
     // something.
     if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
-      GVI =3D OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD=
);
+      GVI =3D OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD=
, TLI);
       return true;
     }
=20
@@ -1531,6 +1536,9 @@
   // into multiple malloc'd arrays, one for each field.  This is basically
   // SRoA for malloc'd memory.
=20
+  if (Ordering !=3D NotAtomic)
+    return false;
+
   // If this is an allocation of a fixed size array of structs, analyze as=
 a
   // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
   if (NElems =3D=3D ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
@@ -1563,7 +1571,7 @@
         extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
     }
=20
-    GVI =3D PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),=
TD);
+    GVI =3D PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),=
 TD);
     return true;
   }
=20
@@ -1573,8 +1581,9 @@
 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowled=
ge
 // that only one value (besides its initializer) is ever stored to the glo=
bal.
 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnce=
Val,
+                                     AtomicOrdering Ordering,
                                      Module::global_iterator &GVI,
-                                     TargetData *TD) {
+                                     TargetData *TD, TargetLibraryInfo *TL=
I) {
   // Ignore no-op GEPs and bitcasts.
   StoredOnceVal =3D StoredOnceVal->stripPointerCasts();
=20
@@ -1589,12 +1598,13 @@
         SOVC =3D ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getT=
ype());
=20
       // Optimize away any trapping uses of the loaded value.
-      if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
+      if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
         return true;
     } else if (CallInst *CI =3D extractMallocCall(StoredOnceVal)) {
-      Type* MallocType =3D getMallocAllocatedType(CI);
-      if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocT=
ype,
-                                                           GVI, TD))
+      Type *MallocType =3D getMallocAllocatedType(CI);
+      if (MallocType &&
+          TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering,=
 GVI,
+                                             TD, TLI))
         return true;
     }
   }
@@ -1670,7 +1680,8 @@
         if (LoadInst *LI =3D dyn_cast<LoadInst>(StoredVal)) {
           assert(LI->getOperand(0) =3D=3D GV && "Not a copy!");
           // Insert a new load, to preserve the saved value.
-          StoreVal =3D new LoadInst(NewGV, LI->getName()+".b", LI);
+          StoreVal =3D new LoadInst(NewGV, LI->getName()+".b", false, 0,
+                                  LI->getOrdering(), LI->getSynchScope(), =
LI);
         } else {
           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) =
&&
                  "This is not a form that we understand!");
@@ -1678,11 +1689,13 @@
           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
         }
       }
-      new StoreInst(StoreVal, NewGV, SI);
+      new StoreInst(StoreVal, NewGV, false, 0,
+                    SI->getOrdering(), SI->getSynchScope(), SI);
     } else {
       // Change the load into a load of bool then a select.
       LoadInst *LI =3D cast<LoadInst>(UI);
-      LoadInst *NLI =3D new LoadInst(NewGV, LI->getName()+".b", LI);
+      LoadInst *NLI =3D new LoadInst(NewGV, LI->getName()+".b", false, 0,
+                                   LI->getOrdering(), LI->getSynchScope(),=
 LI);
       Value *NSI;
       if (IsOneZero)
         NSI =3D new ZExtInst(NLI, LI->getType(), "", LI);
@@ -1699,8 +1712,8 @@
 }
=20
=20
-/// ProcessInternalGlobal - Analyze the specified global variable and opti=
mize
-/// it if possible.  If we make a change, return true.
+/// ProcessGlobal - Analyze the specified global variable and optimize it =
if
+/// possible.  If we make a change, return true.
 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
                               Module::global_iterator &GVI) {
   if (!GV->hasLocalLinkage())
@@ -1737,7 +1750,7 @@
 /// it if possible.  If we make a change, return true.
 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
                                       Module::global_iterator &GVI,
-                                      const SmallPtrSet<const PHINode*, 16=
> &PHIUsers,
+                                const SmallPtrSet<const PHINode*, 16> &PHI=
Users,
                                       const GlobalStatus &GS) {
   // If this is a first class global and has only one accessing function
   // and this function is main (which we know is not recursive we can make
@@ -1755,11 +1768,11 @@
       GS.AccessingFunction->hasExternalLinkage() &&
       GV->getType()->getAddressSpace() =3D=3D 0) {
     DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
-    Instruction& FirstI =3D const_cast<Instruction&>(*GS.AccessingFunction
+    Instruction &FirstI =3D const_cast<Instruction&>(*GS.AccessingFunction
                                                    ->getEntryBlock().begin=
());
-    Type* ElemTy =3D GV->getType()->getElementType();
+    Type *ElemTy =3D GV->getType()->getElementType();
     // FIXME: Pass Global's alignment when globals have alignment
-    AllocaInst* Alloca =3D new AllocaInst(ElemTy, NULL, GV->getName(), &Fi=
rstI);
+    AllocaInst *Alloca =3D new AllocaInst(ElemTy, NULL, GV->getName(), &Fi=
rstI);
     if (!isa<UndefValue>(GV->getInitializer()))
       new StoreInst(GV->getInitializer(), Alloca, &FirstI);
=20
@@ -1776,7 +1789,8 @@
=20
     // Delete any stores we can find to the global.  We may not be able to
     // make it completely dead though.
-    bool Changed =3D CleanupConstantGlobalUsers(GV, GV->getInitializer());
+    bool Changed =3D CleanupConstantGlobalUsers(GV, GV->getInitializer(),
+                                              TD, TLI);
=20
     // If the global is dead now, delete it.
     if (GV->use_empty()) {
@@ -1791,7 +1805,7 @@
     GV->setConstant(true);
=20
     // Clean up any obviously simplifiable users now.
-    CleanupConstantGlobalUsers(GV, GV->getInitializer());
+    CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
=20
     // If the global is dead now, just nuke it.
     if (GV->use_empty()) {
@@ -1820,7 +1834,7 @@
         GV->setInitializer(SOVConstant);
=20
         // Clean up any obviously simplifiable users now.
-        CleanupConstantGlobalUsers(GV, GV->getInitializer());
+        CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
=20
         if (GV->use_empty()) {
           DEBUG(dbgs() << "   *** Substituting initializer allowed us to "
@@ -1836,8 +1850,8 @@
=20
     // Try to optimize globals based on the knowledge that only one value
     // (besides its initializer) is ever stored to the global.
-    if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
-                                 getAnalysisIfAvailable<TargetData>()))
+    if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
+                                 TD, TLI))
       return true;
=20
     // Otherwise, if the global was not a boolean, we can shrink it to be a
@@ -1890,7 +1904,7 @@
     if (!F->hasName() && !F->isDeclaration())
       F->setLinkage(GlobalValue::InternalLinkage);
     F->removeDeadConstantUsers();
-    if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage()=
)) {
+    if (F->isDefTriviallyDead()) {
       F->eraseFromParent();
       Changed =3D true;
       ++NumFnDeleted;
@@ -1930,8 +1944,7 @@
     // Simplify the initializer.
     if (GV->hasInitializer())
       if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(GV->getInitializer()=
)) {
-        TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
-        Constant *New =3D ConstantFoldConstantExpression(CE, TD);
+        Constant *New =3D ConstantFoldConstantExpression(CE, TD, TLI);
         if (New && New !=3D CE)
           GV->setInitializer(New);
       }
@@ -2052,16 +2065,10 @@
 }
=20
=20
-static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value=
 *V) {
-  if (Constant *CV =3D dyn_cast<Constant>(V)) return CV;
-  Constant *R =3D ComputedValues[V];
-  assert(R && "Reference to an uncomputed value!");
-  return R;
-}
-
 static inline bool=20
 isSimpleEnoughValueToCommit(Constant *C,
-                            SmallPtrSet<Constant*, 8> &SimpleConstants);
+                            SmallPtrSet<Constant*, 8> &SimpleConstants,
+                            const TargetData *TD);
=20
=20
 /// isSimpleEnoughValueToCommit - Return true if the specified constant ca=
n be
@@ -2073,7 +2080,8 @@
 /// in SimpleConstants to avoid having to rescan the same constants all the
 /// time.
 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
-                                   SmallPtrSet<Constant*, 8> &SimpleConsta=
nts) {
+                                   SmallPtrSet<Constant*, 8> &SimpleConsta=
nts,
+                                   const TargetData *TD) {
   // Simple integer, undef, constant aggregate zero, global addresses, etc=
 are
   // all supported.
   if (C->getNumOperands() =3D=3D 0 || isa<BlockAddress>(C) ||
@@ -2085,7 +2093,7 @@
       isa<ConstantVector>(C)) {
     for (unsigned i =3D 0, e =3D C->getNumOperands(); i !=3D e; ++i) {
       Constant *Op =3D cast<Constant>(C->getOperand(i));
-      if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
+      if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
         return false;
     }
     return true;
@@ -2097,34 +2105,42 @@
   ConstantExpr *CE =3D cast<ConstantExpr>(C);
   switch (CE->getOpcode()) {
   case Instruction::BitCast:
+    // Bitcast is fine if the casted value is fine.
+    return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants,=
 TD);
+
   case Instruction::IntToPtr:
   case Instruction::PtrToInt:
-    // These casts are always fine if the casted value is.
-    return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
+    // int <=3D> ptr is fine if the int type is the same size as the
+    // pointer type.
+    if (!TD || TD->getTypeSizeInBits(CE->getType()) !=3D
+               TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
+      return false;
+    return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants,=
 TD);
      =20
   // GEP is fine if it is simple + constant offset.
   case Instruction::GetElementPtr:
     for (unsigned i =3D 1, e =3D CE->getNumOperands(); i !=3D e; ++i)
       if (!isa<ConstantInt>(CE->getOperand(i)))
         return false;
-    return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
+    return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants,=
 TD);
      =20
   case Instruction::Add:
     // We allow simple+cst.
     if (!isa<ConstantInt>(CE->getOperand(1)))
       return false;
-    return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
+    return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants,=
 TD);
   }
   return false;
 }
=20
 static inline bool=20
 isSimpleEnoughValueToCommit(Constant *C,
-                            SmallPtrSet<Constant*, 8> &SimpleConstants) {
+                            SmallPtrSet<Constant*, 8> &SimpleConstants,
+                            const TargetData *TD) {
   // If we already checked this constant, we win.
   if (!SimpleConstants.insert(C)) return true;
   // Check the constant.
-  return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
+  return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
 }
=20
=20
@@ -2191,23 +2207,11 @@
     return Val;
   }
=20
-  std::vector<Constant*> Elts;
+  SmallVector<Constant*, 32> Elts;
   if (StructType *STy =3D dyn_cast<StructType>(Init->getType())) {
-
     // Break up the constant into its elements.
-    if (ConstantStruct *CS =3D dyn_cast<ConstantStruct>(Init)) {
-      for (User::op_iterator i =3D CS->op_begin(), e =3D CS->op_end(); i !=
=3D e; ++i)
-        Elts.push_back(cast<Constant>(*i));
-    } else if (isa<ConstantAggregateZero>(Init)) {
-      for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i)
-        Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
-    } else if (isa<UndefValue>(Init)) {
-      for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i)
-        Elts.push_back(UndefValue::get(STy->getElementType(i)));
-    } else {
-      llvm_unreachable("This code is out of sync with "
-             " ConstantFoldLoadThroughGEPConstantExpr");
-    }
+    for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i)
+      Elts.push_back(Init->getAggregateElement(i));
=20
     // Replace the element that we are supposed to.
     ConstantInt *CU =3D cast<ConstantInt>(Addr->getOperand(OpNo));
@@ -2226,22 +2230,11 @@
   if (ArrayType *ATy =3D dyn_cast<ArrayType>(InitTy))
     NumElts =3D ATy->getNumElements();
   else
-    NumElts =3D cast<VectorType>(InitTy)->getNumElements();
+    NumElts =3D InitTy->getVectorNumElements();
=20
   // Break up the array into elements.
-  if (ConstantArray *CA =3D dyn_cast<ConstantArray>(Init)) {
-    for (User::op_iterator i =3D CA->op_begin(), e =3D CA->op_end(); i !=
=3D e; ++i)
-      Elts.push_back(cast<Constant>(*i));
-  } else if (ConstantVector *CV =3D dyn_cast<ConstantVector>(Init)) {
-    for (User::op_iterator i =3D CV->op_begin(), e =3D CV->op_end(); i !=
=3D e; ++i)
-      Elts.push_back(cast<Constant>(*i));
-  } else if (isa<ConstantAggregateZero>(Init)) {
-    Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
-  } else {
-    assert(isa<UndefValue>(Init) && "This code is out of sync with "
-           " ConstantFoldLoadThroughGEPConstantExpr");
-    Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
-  }
+  for (uint64_t i =3D 0, e =3D NumElts; i !=3D e; ++i)
+    Elts.push_back(Init->getAggregateElement(i));
=20
   assert(CI->getZExtValue() < NumElts);
   Elts[CI->getZExtValue()] =3D
@@ -2266,15 +2259,109 @@
   GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
 }
=20
+namespace {
+
+/// Evaluator - This class evaluates LLVM IR, producing the Constant
+/// representing each SSA instruction.  Changes to global variables are st=
ored
+/// in a mapping that can be iterated over after the evaluation is complet=
e.
+/// Once an evaluation call fails, the evaluation object should not be reu=
sed.
+class Evaluator {
+public:
+  Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
+    : TD(TD), TLI(TLI) {
+    ValueStack.push_back(new DenseMap<Value*, Constant*>);
+  }
+
+  ~Evaluator() {
+    DeleteContainerPointers(ValueStack);
+    while (!AllocaTmps.empty()) {
+      GlobalVariable *Tmp =3D AllocaTmps.back();
+      AllocaTmps.pop_back();
+
+      // If there are still users of the alloca, the program is doing some=
thing
+      // silly, e.g. storing the address of the alloca somewhere and using=
 it
+      // later.  Since this is undefined, we'll just make it be null.
+      if (!Tmp->use_empty())
+        Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
+      delete Tmp;
+    }
+  }
+
+  /// EvaluateFunction - Evaluate a call to function F, returning true if
+  /// successful, false if we can't evaluate it.  ActualArgs contains the =
formal
+  /// arguments for the function.
+  bool EvaluateFunction(Function *F, Constant *&RetVal,
+                        const SmallVectorImpl<Constant*> &ActualArgs);
+
+  /// EvaluateBlock - Evaluate all instructions in block BB, returning tru=
e if
+  /// successful, false if we can't evaluate it.  NewBB returns the next B=
B that
+  /// control flows into, or null upon return.
+  bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
+
+  Constant *getVal(Value *V) {
+    if (Constant *CV =3D dyn_cast<Constant>(V)) return CV;
+    Constant *R =3D ValueStack.back()->lookup(V);
+    assert(R && "Reference to an uncomputed value!");
+    return R;
+  }
+
+  void setVal(Value *V, Constant *C) {
+    ValueStack.back()->operator[](V) =3D C;
+  }
+
+  const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
+    return MutatedMemory;
+  }
+
+  const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
+    return Invariants;
+  }
+
+private:
+  Constant *ComputeLoadResult(Constant *P);
+
+  /// ValueStack - As we compute SSA register values, we store their conte=
nts
+  /// here. The back of the vector contains the current function and the s=
tack
+  /// contains the values in the calling frames.
+  SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
+
+  /// CallStack - This is used to detect recursion.  In pathological situa=
tions
+  /// we could hit exponential behavior, but at least there is nothing
+  /// unbounded.
+  SmallVector<Function*, 4> CallStack;
+
+  /// MutatedMemory - For each store we execute, we update this map.  Loads
+  /// check this to get the most up-to-date value.  If evaluation is succe=
ssful,
+  /// this state is committed to the process.
+  DenseMap<Constant*, Constant*> MutatedMemory;
+
+  /// AllocaTmps - To 'execute' an alloca, we create a temporary global va=
riable
+  /// to represent its body.  This vector is needed so we can delete the
+  /// temporary globals when we are done.
+  SmallVector<GlobalVariable*, 32> AllocaTmps;
+
+  /// Invariants - These global variables have been marked invariant by the
+  /// static constructor.
+  SmallPtrSet<GlobalVariable*, 8> Invariants;
+
+  /// SimpleConstants - These are constants we have checked and know to be
+  /// simple enough to live in a static initializer of a global.
+  SmallPtrSet<Constant*, 8> SimpleConstants;
+
+  const TargetData *TD;
+  const TargetLibraryInfo *TLI;
+};
+
+}  // anonymous namespace
+
 /// ComputeLoadResult - Return the value that would be computed by a load =
from
 /// P after the stores reflected by 'memory' have been performed.  If we c=
an't
 /// decide, return null.
-static Constant *ComputeLoadResult(Constant *P,
-                                const DenseMap<Constant*, Constant*> &Memo=
ry) {
+Constant *Evaluator::ComputeLoadResult(Constant *P) {
   // If this memory location has been recently stored, use the stored valu=
e: it
   // is the most up-to-date.
-  DenseMap<Constant*, Constant*>::const_iterator I =3D Memory.find(P);
-  if (I !=3D Memory.end()) return I->second;
+  DenseMap<Constant*, Constant*>::const_iterator I =3D MutatedMemory.find(=
P);
+  if (I !=3D MutatedMemory.end()) return I->second;
=20
   // Access it.
   if (GlobalVariable *GV =3D dyn_cast<GlobalVariable>(P)) {
@@ -2295,56 +2382,29 @@
   return 0;  // don't know how to evaluate.
 }
=20
-/// EvaluateFunction - Evaluate a call to function F, returning true if
-/// successful, false if we can't evaluate it.  ActualArgs contains the fo=
rmal
-/// arguments for the function.
-static bool EvaluateFunction(Function *F, Constant *&RetVal,
-                             const SmallVectorImpl<Constant*> &ActualArgs,
-                             std::vector<Function*> &CallStack,
-                             DenseMap<Constant*, Constant*> &MutatedMemory,
-                             std::vector<GlobalVariable*> &AllocaTmps,
-                             SmallPtrSet<Constant*, 8> &SimpleConstants,
-                             const TargetData *TD) {
-  // Check to see if this function is already executing (recursion).  If s=
o,
-  // bail out.  TODO: we might want to accept limited recursion.
-  if (std::find(CallStack.begin(), CallStack.end(), F) !=3D CallStack.end(=
))
-    return false;
-
-  CallStack.push_back(F);
-
-  /// Values - As we compute SSA register values, we store their contents =
here.
-  DenseMap<Value*, Constant*> Values;
-
-  // Initialize arguments to the incoming values specified.
-  unsigned ArgNo =3D 0;
-  for (Function::arg_iterator AI =3D F->arg_begin(), E =3D F->arg_end(); A=
I !=3D E;
-       ++AI, ++ArgNo)
-    Values[AI] =3D ActualArgs[ArgNo];
-
-  /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As=
 such,
-  /// we can only evaluate any one basic block at most once.  This set kee=
ps
-  /// track of what we have executed so we can detect recursive cases etc.
-  SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
-
-  // CurInst - The current instruction we're evaluating.
-  BasicBlock::iterator CurInst =3D F->begin()->begin();
-
+/// EvaluateBlock - Evaluate all instructions in block BB, returning true =
if
+/// successful, false if we can't evaluate it.  NewBB returns the next BB =
that
+/// control flows into, or null upon return.
+bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
+                              BasicBlock *&NextBB) {
   // This is the main evaluation loop.
   while (1) {
     Constant *InstResult =3D 0;
=20
     if (StoreInst *SI =3D dyn_cast<StoreInst>(CurInst)) {
       if (!SI->isSimple()) return false;  // no volatile/atomic accesses.
-      Constant *Ptr =3D getVal(Values, SI->getOperand(1));
+      Constant *Ptr =3D getVal(SI->getOperand(1));
+      if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(Ptr))
+        Ptr =3D ConstantFoldConstantExpression(CE, TD, TLI);
       if (!isSimpleEnoughPointerToCommit(Ptr))
         // If this is too complex for us to commit, reject it.
         return false;
      =20
-      Constant *Val =3D getVal(Values, SI->getOperand(0));
+      Constant *Val =3D getVal(SI->getOperand(0));
=20
       // If this might be too difficult for the backend to handle (e.g. th=
e addr
       // of one global variable divided by another) then we can't commit i=
t.
-      if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
+      if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
         return false;
        =20
       if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(Ptr))
@@ -2354,7 +2414,7 @@
           // stored value.
           Ptr =3D CE->getOperand(0);
          =20
-          Type *NewTy=3Dcast<PointerType>(Ptr->getType())->getElementType(=
);
+          Type *NewTy =3D cast<PointerType>(Ptr->getType())->getElementTyp=
e();
          =20
           // In order to push the bitcast onto the stored value, a bitcast
           // from NewTy to Val's type must be legal.  If it's not, we can =
try
@@ -2366,16 +2426,18 @@
             if (StructType *STy =3D dyn_cast<StructType>(NewTy)) {
               NewTy =3D STy->getTypeAtIndex(0U);
=20
-              IntegerType *IdxTy =3DIntegerType::get(NewTy->getContext(), =
32);
+              IntegerType *IdxTy =3D IntegerType::get(NewTy->getContext(),=
 32);
               Constant *IdxZero =3D ConstantInt::get(IdxTy, 0, false);
               Constant * const IdxList[] =3D {IdxZero, IdxZero};
=20
               Ptr =3D ConstantExpr::getGetElementPtr(Ptr, IdxList);
-           =20
+              if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(Ptr))
+                Ptr =3D ConstantFoldConstantExpression(CE, TD, TLI);
+
             // If we can't improve the situation by introspecting NewTy,
             // we have to give up.
             } else {
-              return 0;
+              return false;
             }
           }
          =20
@@ -2387,33 +2449,35 @@
       MutatedMemory[Ptr] =3D Val;
     } else if (BinaryOperator *BO =3D dyn_cast<BinaryOperator>(CurInst)) {
       InstResult =3D ConstantExpr::get(BO->getOpcode(),
-                                     getVal(Values, BO->getOperand(0)),
-                                     getVal(Values, BO->getOperand(1)));
+                                     getVal(BO->getOperand(0)),
+                                     getVal(BO->getOperand(1)));
     } else if (CmpInst *CI =3D dyn_cast<CmpInst>(CurInst)) {
       InstResult =3D ConstantExpr::getCompare(CI->getPredicate(),
-                                            getVal(Values, CI->getOperand(=
0)),
-                                            getVal(Values, CI->getOperand(=
1)));
+                                            getVal(CI->getOperand(0)),
+                                            getVal(CI->getOperand(1)));
     } else if (CastInst *CI =3D dyn_cast<CastInst>(CurInst)) {
       InstResult =3D ConstantExpr::getCast(CI->getOpcode(),
-                                         getVal(Values, CI->getOperand(0)),
+                                         getVal(CI->getOperand(0)),
                                          CI->getType());
     } else if (SelectInst *SI =3D dyn_cast<SelectInst>(CurInst)) {
-      InstResult =3D ConstantExpr::getSelect(getVal(Values, SI->getOperand=
(0)),
-                                           getVal(Values, SI->getOperand(1=
)),
-                                           getVal(Values, SI->getOperand(2=
)));
+      InstResult =3D ConstantExpr::getSelect(getVal(SI->getOperand(0)),
+                                           getVal(SI->getOperand(1)),
+                                           getVal(SI->getOperand(2)));
     } else if (GetElementPtrInst *GEP =3D dyn_cast<GetElementPtrInst>(CurI=
nst)) {
-      Constant *P =3D getVal(Values, GEP->getOperand(0));
+      Constant *P =3D getVal(GEP->getOperand(0));
       SmallVector<Constant*, 8> GEPOps;
       for (User::op_iterator i =3D GEP->op_begin() + 1, e =3D GEP->op_end(=
);
            i !=3D e; ++i)
-        GEPOps.push_back(getVal(Values, *i));
+        GEPOps.push_back(getVal(*i));
       InstResult =3D
         ConstantExpr::getGetElementPtr(P, GEPOps,
                                        cast<GEPOperator>(GEP)->isInBounds(=
));
     } else if (LoadInst *LI =3D dyn_cast<LoadInst>(CurInst)) {
       if (!LI->isSimple()) return false;  // no volatile/atomic accesses.
-      InstResult =3D ComputeLoadResult(getVal(Values, LI->getOperand(0)),
-                                     MutatedMemory);
+      Constant *Ptr =3D getVal(LI->getOperand(0));
+      if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(Ptr))
+        Ptr =3D ConstantFoldConstantExpression(CE, TD, TLI);
+      InstResult =3D ComputeLoadResult(Ptr);
       if (InstResult =3D=3D 0) return false; // Could not evaluate load.
     } else if (AllocaInst *AI =3D dyn_cast<AllocaInst>(CurInst)) {
       if (AI->isArrayAllocation()) return false;  // Cannot handle array a=
llocs.
@@ -2423,25 +2487,53 @@
                                               UndefValue::get(Ty),
                                               AI->getName()));
       InstResult =3D AllocaTmps.back();
-    } else if (CallInst *CI =3D dyn_cast<CallInst>(CurInst)) {
+    } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
+      CallSite CS(CurInst);
=20
       // Debug info can safely be ignored here.
-      if (isa<DbgInfoIntrinsic>(CI)) {
+      if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
         ++CurInst;
         continue;
       }
=20
       // Cannot handle inline asm.
-      if (isa<InlineAsm>(CI->getCalledValue())) return false;
-
-      if (MemSetInst *MSI =3D dyn_cast<MemSetInst>(CI)) {
-        if (MSI->isVolatile()) return false;
-        Constant *Ptr =3D getVal(Values, MSI->getDest());
-        Constant *Val =3D getVal(Values, MSI->getValue());
-        Constant *DestVal =3D ComputeLoadResult(getVal(Values, Ptr),
-                                              MutatedMemory);
-        if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
-          // This memset is a no-op.
+      if (isa<InlineAsm>(CS.getCalledValue())) return false;
+
+      if (IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(CS.getInstruction(=
))) {
+        if (MemSetInst *MSI =3D dyn_cast<MemSetInst>(II)) {
+          if (MSI->isVolatile()) return false;
+          Constant *Ptr =3D getVal(MSI->getDest());
+          Constant *Val =3D getVal(MSI->getValue());
+          Constant *DestVal =3D ComputeLoadResult(getVal(Ptr));
+          if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
+            // This memset is a no-op.
+            ++CurInst;
+            continue;
+          }
+        }
+
+        if (II->getIntrinsicID() =3D=3D Intrinsic::lifetime_start ||
+            II->getIntrinsicID() =3D=3D Intrinsic::lifetime_end) {
+          ++CurInst;
+          continue;
+        }
+
+        if (II->getIntrinsicID() =3D=3D Intrinsic::invariant_start) {
+          // We don't insert an entry into Values, as it doesn't have a
+          // meaningful return value.
+          if (!II->use_empty())
+            return false;
+          ConstantInt *Size =3D cast<ConstantInt>(II->getArgOperand(0));
+          Value *PtrArg =3D getVal(II->getArgOperand(1));
+          Value *Ptr =3D PtrArg->stripPointerCasts();
+          if (GlobalVariable *GV =3D dyn_cast<GlobalVariable>(Ptr)) {
+            Type *ElemTy =3D cast<PointerType>(GV->getType())->getElementT=
ype();
+            if (!Size->isAllOnesValue() &&
+                Size->getValue().getLimitedValue() >=3D
+                TD->getTypeStoreSize(ElemTy))
+              Invariants.insert(GV);
+          }
+          // Continue even if we do nothing.
           ++CurInst;
           continue;
         }
@@ -2449,19 +2541,17 @@
       }
=20
       // Resolve function pointers.
-      Function *Callee =3D dyn_cast<Function>(getVal(Values,
-                                                   CI->getCalledValue()));
-      if (!Callee) return false;  // Cannot resolve.
+      Function *Callee =3D dyn_cast<Function>(getVal(CS.getCalledValue()));
+      if (!Callee || Callee->mayBeOverridden())
+        return false;  // Cannot resolve.
=20
       SmallVector<Constant*, 8> Formals;
-      CallSite CS(CI);
-      for (User::op_iterator i =3D CS.arg_begin(), e =3D CS.arg_end();
-           i !=3D e; ++i)
-        Formals.push_back(getVal(Values, *i));
+      for (User::op_iterator i =3D CS.arg_begin(), e =3D CS.arg_end(); i !=
=3D e; ++i)
+        Formals.push_back(getVal(*i));
=20
       if (Callee->isDeclaration()) {
         // If this is a function we can constant fold, do it.
-        if (Constant *C =3D ConstantFoldCall(Callee, Formals)) {
+        if (Constant *C =3D ConstantFoldCall(Callee, Formals, TLI)) {
           InstResult =3D C;
         } else {
           return false;
@@ -2472,62 +2562,43 @@
=20
         Constant *RetVal;
         // Execute the call, if successful, use the return value.
-        if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
-                              MutatedMemory, AllocaTmps, SimpleConstants, =
TD))
+        ValueStack.push_back(new DenseMap<Value*, Constant*>);
+        if (!EvaluateFunction(Callee, RetVal, Formals))
           return false;
+        delete ValueStack.pop_back_val();
         InstResult =3D RetVal;
       }
     } else if (isa<TerminatorInst>(CurInst)) {
-      BasicBlock *NewBB =3D 0;
       if (BranchInst *BI =3D dyn_cast<BranchInst>(CurInst)) {
         if (BI->isUnconditional()) {
-          NewBB =3D BI->getSuccessor(0);
+          NextBB =3D BI->getSuccessor(0);
         } else {
           ConstantInt *Cond =3D
-            dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
+            dyn_cast<ConstantInt>(getVal(BI->getCondition()));
           if (!Cond) return false;  // Cannot determine.
=20
-          NewBB =3D BI->getSuccessor(!Cond->getZExtValue());
+          NextBB =3D BI->getSuccessor(!Cond->getZExtValue());
         }
       } else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(CurInst)) {
         ConstantInt *Val =3D
-          dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
+          dyn_cast<ConstantInt>(getVal(SI->getCondition()));
         if (!Val) return false;  // Cannot determine.
-        NewBB =3D SI->getSuccessor(SI->findCaseValue(Val));
+        NextBB =3D SI->findCaseValue(Val).getCaseSuccessor();
       } else if (IndirectBrInst *IBI =3D dyn_cast<IndirectBrInst>(CurInst)=
) {
-        Value *Val =3D getVal(Values, IBI->getAddress())->stripPointerCast=
s();
+        Value *Val =3D getVal(IBI->getAddress())->stripPointerCasts();
         if (BlockAddress *BA =3D dyn_cast<BlockAddress>(Val))
-          NewBB =3D BA->getBasicBlock();
+          NextBB =3D BA->getBasicBlock();
         else
           return false;  // Cannot determine.
-      } else if (ReturnInst *RI =3D dyn_cast<ReturnInst>(CurInst)) {
-        if (RI->getNumOperands())
-          RetVal =3D getVal(Values, RI->getOperand(0));
-
-        CallStack.pop_back();  // return from fn.
-        return true;  // We succeeded at evaluating this ctor!
+      } else if (isa<ReturnInst>(CurInst)) {
+        NextBB =3D 0;
       } else {
         // invoke, unwind, resume, unreachable.
         return false;  // Cannot handle this terminator.
       }
=20
-      // Okay, we succeeded in evaluating this control flow.  See if we ha=
ve
-      // executed the new block before.  If so, we have a looping function,
-      // which we cannot evaluate in reasonable time.
-      if (!ExecutedBlocks.insert(NewBB))
-        return false;  // looped!
-
-      // Okay, we have never been in this block before.  Check to see if t=
here
-      // are any PHI nodes.  If so, evaluate them with information about w=
here
-      // we came from.
-      BasicBlock *OldBB =3D CurInst->getParent();
-      CurInst =3D NewBB->begin();
-      PHINode *PN;
-      for (; (PN =3D dyn_cast<PHINode>(CurInst)); ++CurInst)
-        Values[PN] =3D getVal(Values, PN->getIncomingValueForBlock(OldBB));
-
-      // Do NOT increment CurInst.  We know that the terminator had no val=
ue.
-      continue;
+      // We succeeded at evaluating this block!
+      return true;
     } else {
       // Did not know how to evaluate this!
       return false;
@@ -2535,9 +2606,15 @@
=20
     if (!CurInst->use_empty()) {
       if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(InstResult))
-        InstResult =3D ConstantFoldConstantExpression(CE, TD);
+        InstResult =3D ConstantFoldConstantExpression(CE, TD, TLI);
      =20
-      Values[CurInst] =3D InstResult;
+      setVal(CurInst, InstResult);
+    }
+
+    // If we just processed an invoke, we finished evaluating the block.
+    if (InvokeInst *II =3D dyn_cast<InvokeInst>(CurInst)) {
+      NextBB =3D II->getNormalDest();
+      return true;
     }
=20
     // Advance program counter.
@@ -2545,64 +2622,96 @@
   }
 }
=20
+/// EvaluateFunction - Evaluate a call to function F, returning true if
+/// successful, false if we can't evaluate it.  ActualArgs contains the fo=
rmal
+/// arguments for the function.
+bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
+                                 const SmallVectorImpl<Constant*> &ActualA=
rgs) {
+  // Check to see if this function is already executing (recursion).  If s=
o,
+  // bail out.  TODO: we might want to accept limited recursion.
+  if (std::find(CallStack.begin(), CallStack.end(), F) !=3D CallStack.end(=
))
+    return false;
+
+  CallStack.push_back(F);
+
+  // Initialize arguments to the incoming values specified.
+  unsigned ArgNo =3D 0;
+  for (Function::arg_iterator AI =3D F->arg_begin(), E =3D F->arg_end(); A=
I !=3D E;
+       ++AI, ++ArgNo)
+    setVal(AI, ActualArgs[ArgNo]);
+
+  // ExecutedBlocks - We only handle non-looping, non-recursive code.  As =
such,
+  // we can only evaluate any one basic block at most once.  This set keeps
+  // track of what we have executed so we can detect recursive cases etc.
+  SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
+
+  // CurBB - The current basic block we're evaluating.
+  BasicBlock *CurBB =3D F->begin();
+
+  BasicBlock::iterator CurInst =3D CurBB->begin();
+
+  while (1) {
+    BasicBlock *NextBB =3D 0; // Initialized to avoid compiler warnings.
+    if (!EvaluateBlock(CurInst, NextBB))
+      return false;
+
+    if (NextBB =3D=3D 0) {
+      // Successfully running until there's no next block means that we fo=
und
+      // the return.  Fill it the return value and pop the call stack.
+      ReturnInst *RI =3D cast<ReturnInst>(CurBB->getTerminator());
+      if (RI->getNumOperands())
+        RetVal =3D getVal(RI->getOperand(0));
+      CallStack.pop_back();
+      return true;
+    }
+
+    // Okay, we succeeded in evaluating this control flow.  See if we have
+    // executed the new block before.  If so, we have a looping function,
+    // which we cannot evaluate in reasonable time.
+    if (!ExecutedBlocks.insert(NextBB))
+      return false;  // looped!
+
+    // Okay, we have never been in this block before.  Check to see if the=
re
+    // are any PHI nodes.  If so, evaluate them with information about whe=
re
+    // we came from.
+    PHINode *PN =3D 0;
+    for (CurInst =3D NextBB->begin();
+         (PN =3D dyn_cast<PHINode>(CurInst)); ++CurInst)
+      setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
+
+    // Advance to the next block.
+    CurBB =3D NextBB;
+  }
+}
+
 /// EvaluateStaticConstructor - Evaluate static constructors in the functi=
on, if
 /// we can.  Return true if we can, false otherwise.
-static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
-  /// MutatedMemory - For each store we execute, we update this map.  Loads
-  /// check this to get the most up-to-date value.  If evaluation is succe=
ssful,
-  /// this state is committed to the process.
-  DenseMap<Constant*, Constant*> MutatedMemory;
-
-  /// AllocaTmps - To 'execute' an alloca, we create a temporary global va=
riable
-  /// to represent its body.  This vector is needed so we can delete the
-  /// temporary globals when we are done.
-  std::vector<GlobalVariable*> AllocaTmps;
-
-  /// CallStack - This is used to detect recursion.  In pathological situa=
tions
-  /// we could hit exponential behavior, but at least there is nothing
-  /// unbounded.
-  std::vector<Function*> CallStack;
-
-  /// SimpleConstants - These are constants we have checked and know to be
-  /// simple enough to live in a static initializer of a global.
-  SmallPtrSet<Constant*, 8> SimpleConstants;
- =20
+static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
+                                      const TargetLibraryInfo *TLI) {
   // Call the function.
+  Evaluator Eval(TD, TLI);
   Constant *RetValDummy;
-  bool EvalSuccess =3D EvaluateFunction(F, RetValDummy,
-                                      SmallVector<Constant*, 0>(), CallSta=
ck,
-                                      MutatedMemory, AllocaTmps,
-                                      SimpleConstants, TD);
+  bool EvalSuccess =3D Eval.EvaluateFunction(F, RetValDummy,
+                                           SmallVector<Constant*, 0>());
  =20
   if (EvalSuccess) {
     // We succeeded at evaluation: commit the result.
     DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
-          << F->getName() << "' to " << MutatedMemory.size()
+          << F->getName() << "' to " << Eval.getMutatedMemory().size()
           << " stores.\n");
-    for (DenseMap<Constant*, Constant*>::iterator I =3D MutatedMemory.begi=
n(),
-         E =3D MutatedMemory.end(); I !=3D E; ++I)
+    for (DenseMap<Constant*, Constant*>::const_iterator I =3D
+           Eval.getMutatedMemory().begin(), E =3D Eval.getMutatedMemory().=
end();
+	 I !=3D E; ++I)
       CommitValueTo(I->second, I->first);
-  }
-
-  // At this point, we are done interpreting.  If we created any 'alloca'
-  // temporaries, release them now.
-  while (!AllocaTmps.empty()) {
-    GlobalVariable *Tmp =3D AllocaTmps.back();
-    AllocaTmps.pop_back();
-
-    // If there are still users of the alloca, the program is doing someth=
ing
-    // silly, e.g. storing the address of the alloca somewhere and using it
-    // later.  Since this is undefined, we'll just make it be null.
-    if (!Tmp->use_empty())
-      Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
-    delete Tmp;
+    for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =3D
+           Eval.getInvariants().begin(), E =3D Eval.getInvariants().end();
+         I !=3D E; ++I)
+      (*I)->setConstant(true);
   }
=20
   return EvalSuccess;
 }
=20
-
-
 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if poss=
ible.
 /// Return true if anything changed.
 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
@@ -2610,7 +2719,6 @@
   bool MadeChange =3D false;
   if (Ctors.empty()) return false;
=20
-  const TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
   // Loop over global ctors, optimizing them when we can.
   for (unsigned i =3D 0; i !=3D Ctors.size(); ++i) {
     Function *F =3D Ctors[i];
@@ -2628,7 +2736,7 @@
     if (F->empty()) continue;
=20
     // If we can evaluate the ctor at compile time, do.
-    if (EvaluateStaticConstructor(F, TD)) {
+    if (EvaluateStaticConstructor(F, TD, TLI)) {
       Ctors.erase(Ctors.begin()+i);
       MadeChange =3D true;
       --i;
@@ -2700,12 +2808,15 @@
   return Changed;
 }
=20
-static Function *FindCXAAtExit(Module &M) {
-  Function *Fn =3D M.getFunction("__cxa_atexit");
+static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
+  if (!TLI->has(LibFunc::cxa_atexit))
+    return 0;
+
+  Function *Fn =3D M.getFunction(TLI->getName(LibFunc::cxa_atexit));
  =20
   if (!Fn)
     return 0;
- =20
+
   FunctionType *FTy =3D Fn->getFunctionType();
  =20
   // Checking that the function has the right return type, the right numbe=
r of=20
@@ -2724,7 +2835,8 @@
 /// destructor and can therefore be eliminated.
 /// Note that we assume that other optimization passes have already simpli=
fied
 /// the code so we only look for a function with a single basic block, whe=
re
-/// the only allowed instructions are 'ret' or 'call' to empty C++ dtor.
+/// the only allowed instructions are 'ret', 'call' to an empty C++ dtor a=
nd
+/// other side-effect free instructions.
 static bool cxxDtorIsEmpty(const Function &Fn,
                            SmallPtrSet<const Function *, 8> &CalledFunctio=
ns) {
   // FIXME: We could eliminate C++ destructors if they're readonly/readnon=
e and
@@ -2757,9 +2869,9 @@
       if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
         return false;
     } else if (isa<ReturnInst>(*I))
-      return true;
-    else
-      return false;
+      return true; // We're done.
+    else if (I->mayHaveSideEffects())
+      return false; // Destructor with side effects, bail.
   }
=20
   return false;
@@ -2815,10 +2927,13 @@
 bool GlobalOpt::runOnModule(Module &M) {
   bool Changed =3D false;
=20
+  TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
+
   // Try to find the llvm.globalctors list.
   GlobalVariable *GlobalCtors =3D FindGlobalCtors(M);
=20
-  Function *CXAAtExitFn =3D FindCXAAtExit(M);
+  Function *CXAAtExitFn =3D FindCXAAtExit(M, TLI);
=20
   bool LocalChange =3D true;
   while (LocalChange) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/I=
nlineAlways.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/InlineAlways.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/InlineAlways.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -32,34 +32,21 @@
=20
   // AlwaysInliner only inlines functions that are mark as "always inline".
   class AlwaysInliner : public Inliner {
-    // Functions that are never inlined
-    SmallPtrSet<const Function*, 16> NeverInline;
-    InlineCostAnalyzer CA;
   public:
     // Use extremely low threshold.
-    AlwaysInliner() : Inliner(ID, -2000000000) {
+    AlwaysInliner() : Inliner(ID, -2000000000, /*InsertLifetime*/true) {
+      initializeAlwaysInlinerPass(*PassRegistry::getPassRegistry());
+    }
+    AlwaysInliner(bool InsertLifetime) : Inliner(ID, -2000000000,
+                                                 InsertLifetime) {
       initializeAlwaysInlinerPass(*PassRegistry::getPassRegistry());
     }
     static char ID; // Pass identification, replacement for typeid
-    InlineCost getInlineCost(CallSite CS) {
-      return CA.getInlineCost(CS, NeverInline);
-    }
-    float getInlineFudgeFactor(CallSite CS) {
-      return CA.getInlineFudgeFactor(CS);
-    }
-    void resetCachedCostInfo(Function *Caller) {
-      CA.resetCachedCostInfo(Caller);
-    }
-    void growCachedCostInfo(Function* Caller, Function* Callee) {
-      CA.growCachedCostInfo(Caller, Callee);
-    }
+    virtual InlineCost getInlineCost(CallSite CS);
     virtual bool doFinalization(CallGraph &CG) {
-      return removeDeadFunctions(CG, &NeverInline);
+      return removeDeadFunctions(CG, /*AlwaysInlineOnly=3D*/true);
     }
     virtual bool doInitialization(CallGraph &CG);
-    void releaseMemory() {
-      CA.clear();
-    }
   };
 }
=20
@@ -72,17 +59,74 @@
=20
 Pass *llvm::createAlwaysInlinerPass() { return new AlwaysInliner(); }
=20
+Pass *llvm::createAlwaysInlinerPass(bool InsertLifetime) {
+  return new AlwaysInliner(InsertLifetime);
+}
+
+/// \brief Minimal filter to detect invalid constructs for inlining.
+static bool isInlineViable(Function &F) {
+  bool ReturnsTwice =3D F.hasFnAttr(Attribute::ReturnsTwice);
+  for (Function::iterator BI =3D F.begin(), BE =3D F.end(); BI !=3D BE; ++=
BI) {
+    // Disallow inlining of functions which contain an indirect branch.
+    if (isa<IndirectBrInst>(BI->getTerminator()))
+      return false;
+
+    for (BasicBlock::iterator II =3D BI->begin(), IE =3D BI->end(); II !=
=3D IE;
+         ++II) {
+      CallSite CS(II);
+      if (!CS)
+        continue;
+
+      // Disallow recursive calls.
+      if (&F =3D=3D CS.getCalledFunction())
+        return false;
+
+      // Disallow calls which expose returns-twice to a function not previ=
ously
+      // attributed as such.
+      if (!ReturnsTwice && CS.isCall() &&
+          cast<CallInst>(CS.getInstruction())->canReturnTwice())
+        return false;
+    }
+  }
+
+  return true;
+}
+
+/// \brief Get the inline cost for the always-inliner.
+///
+/// The always inliner *only* handles functions which are marked with the
+/// attribute to force inlining. As such, it is dramatically simpler and a=
voids
+/// using the powerful (but expensive) inline cost analysis. Instead it us=
es
+/// a very simple and boring direct walk of the instructions looking for
+/// impossible-to-inline constructs.
+///
+/// Note, it would be possible to go to some lengths to cache the informat=
ion
+/// computed here, but as we only expect to do this for relatively few and
+/// small functions which have the explicit attribute to force inlining, i=
t is
+/// likely not worth it in practice.
+InlineCost AlwaysInliner::getInlineCost(CallSite CS) {
+  Function *Callee =3D CS.getCalledFunction();
+  // We assume indirect calls aren't calling an always-inline function.
+  if (!Callee) return InlineCost::getNever();
+
+  // We can't inline calls to external functions.
+  // FIXME: We shouldn't even get here.
+  if (Callee->isDeclaration()) return InlineCost::getNever();
+
+  // Return never for anything not marked as always inline.
+  if (!Callee->hasFnAttr(Attribute::AlwaysInline))
+    return InlineCost::getNever();
+
+  // Do some minimal analysis to preclude non-viable functions.
+  if (!isInlineViable(*Callee))
+    return InlineCost::getNever();
+
+  // Otherwise, force inlining.
+  return InlineCost::getAlways();
+}
+
 // doInitialization - Initializes the vector of functions that have not
 // been annotated with the "always inline" attribute.
 bool AlwaysInliner::doInitialization(CallGraph &CG) {
-  CA.setTargetData(getAnalysisIfAvailable<TargetData>());
-
-  Module &M =3D CG.getModule();
-
-  for (Module::iterator I =3D M.begin(), E =3D M.end();
-       I !=3D E; ++I)
-    if (!I->isDeclaration() && !I->hasFnAttr(Attribute::AlwaysInline))
-      NeverInline.insert(I);
-
   return false;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/I=
nlineSimple.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/InlineSimple.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/InlineSimple.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -23,40 +23,26 @@
 #include "llvm/Transforms/IPO.h"
 #include "llvm/Transforms/IPO/InlinerPass.h"
 #include "llvm/Target/TargetData.h"
-#include "llvm/ADT/SmallPtrSet.h"
=20
 using namespace llvm;
=20
 namespace {
=20
   class SimpleInliner : public Inliner {
-    // Functions that are never inlined
-    SmallPtrSet<const Function*, 16> NeverInline;
     InlineCostAnalyzer CA;
   public:
     SimpleInliner() : Inliner(ID) {
       initializeSimpleInlinerPass(*PassRegistry::getPassRegistry());
     }
-    SimpleInliner(int Threshold) : Inliner(ID, Threshold) {
+    SimpleInliner(int Threshold) : Inliner(ID, Threshold,
+                                           /*InsertLifetime*/true) {
       initializeSimpleInlinerPass(*PassRegistry::getPassRegistry());
     }
     static char ID; // Pass identification, replacement for typeid
     InlineCost getInlineCost(CallSite CS) {
-      return CA.getInlineCost(CS, NeverInline);
-    }
-    float getInlineFudgeFactor(CallSite CS) {
-      return CA.getInlineFudgeFactor(CS);
-    }
-    void resetCachedCostInfo(Function *Caller) {
-      CA.resetCachedCostInfo(Caller);
-    }
-    void growCachedCostInfo(Function* Caller, Function* Callee) {
-      CA.growCachedCostInfo(Caller, Callee);
+      return CA.getInlineCost(CS, getInlineThreshold(CS));
     }
     virtual bool doInitialization(CallGraph &CG);
-    void releaseMemory() {
-      CA.clear();
-    }
   };
 }
=20
@@ -77,44 +63,6 @@
 // annotated with the noinline attribute.
 bool SimpleInliner::doInitialization(CallGraph &CG) {
   CA.setTargetData(getAnalysisIfAvailable<TargetData>());
-
-  Module &M =3D CG.getModule();
-
-  for (Module::iterator I =3D M.begin(), E =3D M.end();
-       I !=3D E; ++I)
-    if (!I->isDeclaration() && I->hasFnAttr(Attribute::NoInline))
-      NeverInline.insert(I);
-
-  // Get llvm.noinline
-  GlobalVariable *GV =3D M.getNamedGlobal("llvm.noinline");
-
-  if (GV =3D=3D 0)
-    return false;
-
-  // Don't crash on invalid code
-  if (!GV->hasDefinitiveInitializer())
-    return false;
-
-  const ConstantArray *InitList =3D dyn_cast<ConstantArray>(GV->getInitial=
izer());
-
-  if (InitList =3D=3D 0)
-    return false;
-
-  // Iterate over each element and add to the NeverInline set
-  for (unsigned i =3D 0, e =3D InitList->getNumOperands(); i !=3D e; ++i) {
-
-    // Get Source
-    const Constant *Elt =3D InitList->getOperand(i);
-
-    if (const ConstantExpr *CE =3D dyn_cast<ConstantExpr>(Elt))
-      if (CE->getOpcode() =3D=3D Instruction::BitCast)
-        Elt =3D CE->getOperand(0);
-
-    // Insert into set of functions to never inline
-    if (const Function *F =3D dyn_cast<Function>(Elt))
-      NeverInline.insert(F);
-  }
-
   return false;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/I=
nliner.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/Inliner.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/Inliner.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -36,6 +36,11 @@
 STATISTIC(NumDeleted, "Number of functions deleted because all callers fou=
nd");
 STATISTIC(NumMergedAllocas, "Number of allocas merged together");
=20
+// This weirdly named statistic tracks the number of times that, when atte=
mting
+// to inline a function A into B, we analyze the callers of B in order to =
see
+// if those would be more profitable and blocked inline steps.
+STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
+
 static cl::opt<int>
 InlineLimit("inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
         cl::desc("Control the amount of inlining to perform (default =3D 2=
25)"));
@@ -48,11 +53,12 @@
 const int OptSizeThreshold =3D 75;
=20
 Inliner::Inliner(char &ID)=20
-  : CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
+  : CallGraphSCCPass(ID), InlineThreshold(InlineLimit), InsertLifetime(tru=
e) {}
=20
-Inliner::Inliner(char &ID, int Threshold)=20
+Inliner::Inliner(char &ID, int Threshold, bool InsertLifetime)
   : CallGraphSCCPass(ID), InlineThreshold(InlineLimit.getNumOccurrences() =
> 0 ?
-                                          InlineLimit : Threshold) {}
+                                          InlineLimit : Threshold),
+    InsertLifetime(InsertLifetime) {}
=20
 /// getAnalysisUsage - For this class, we declare that we require and pres=
erve
 /// the call graph.  If the derived class implements this method, it should
@@ -75,13 +81,13 @@
 /// any new allocas to the set if not possible.
 static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
                                  InlinedArrayAllocasTy &InlinedArrayAlloca=
s,
-                                 int InlineHistory) {
+                                 int InlineHistory, bool InsertLifetime) {
   Function *Callee =3D CS.getCalledFunction();
   Function *Caller =3D CS.getCaller();
=20
   // Try to inline the function.  Get the list of static allocas that were
   // inlined.
-  if (!InlineFunction(CS, IFI))
+  if (!InlineFunction(CS, IFI, InsertLifetime))
     return false;
=20
   // If the inlined function had a higher stack protection level than the
@@ -230,29 +236,37 @@
     return false;
   }
  =20
-  int Cost =3D IC.getValue();
   Function *Caller =3D CS.getCaller();
-  int CurrentThreshold =3D getInlineThreshold(CS);
-  float FudgeFactor =3D getInlineFudgeFactor(CS);
-  int AdjThreshold =3D (int)(CurrentThreshold * FudgeFactor);
-  if (Cost >=3D AdjThreshold) {
-    DEBUG(dbgs() << "    NOT Inlining: cost=3D" << Cost
-          << ", thres=3D" << AdjThreshold
+  if (!IC) {
+    DEBUG(dbgs() << "    NOT Inlining: cost=3D" << IC.getCost()
+          << ", thres=3D" << (IC.getCostDelta() + IC.getCost())
           << ", Call: " << *CS.getInstruction() << "\n");
     return false;
   }
  =20
-  // Try to detect the case where the current inlining candidate caller
-  // (call it B) is a static function and is an inlining candidate elsewhe=
re,
-  // and the current candidate callee (call it C) is large enough that
-  // inlining it into B would make B too big to inline later.  In these
-  // circumstances it may be best not to inline C into B, but to inline B
-  // into its callers.
-  if (Caller->hasLocalLinkage()) {
+  // Try to detect the case where the current inlining candidate caller (c=
all
+  // it B) is a static or linkonce-ODR function and is an inlining candida=
te
+  // elsewhere, and the current candidate callee (call it C) is large enou=
gh
+  // that inlining it into B would make B too big to inline later. In these
+  // circumstances it may be best not to inline C into B, but to inline B =
into
+  // its callers.
+  //
+  // This only applies to static and linkonce-ODR functions because those =
are
+  // expected to be available for inlining in the translation units where =
they
+  // are used. Thus we will always have the opportunity to make local inli=
ning
+  // decisions. Importantly the linkonce-ODR linkage covers inline functio=
ns
+  // and templates in C++.
+  //
+  // FIXME: All of this logic should be sunk into getInlineCost. It relies=
 on
+  // the internal implementation of the inline cost metrics rather than
+  // treating them as truly abstract units etc.
+  if (Caller->hasLocalLinkage() ||
+      Caller->getLinkage() =3D=3D GlobalValue::LinkOnceODRLinkage) {
     int TotalSecondaryCost =3D 0;
-    bool outerCallsFound =3D false;
+    // The candidate cost to be imposed upon the current function.
+    int CandidateCost =3D IC.getCost() - (InlineConstants::CallPenalty + 1=
);
     // This bool tracks what happens if we do NOT inline C into B.
-    bool callerWillBeRemoved =3D true;
+    bool callerWillBeRemoved =3D Caller->hasLocalLinkage();
     // This bool tracks what happens if we DO inline C into B.
     bool inliningPreventsSomeOuterInline =3D false;
     for (Value::use_iterator I =3D Caller->use_begin(), E =3DCaller->use_e=
nd();=20
@@ -268,26 +282,20 @@
       }
=20
       InlineCost IC2 =3D getInlineCost(CS2);
-      if (IC2.isNever())
+      ++NumCallerCallersAnalyzed;
+      if (!IC2) {
         callerWillBeRemoved =3D false;
-      if (IC2.isAlways() || IC2.isNever())
+        continue;
+      }
+      if (IC2.isAlways())
         continue;
=20
-      outerCallsFound =3D true;
-      int Cost2 =3D IC2.getValue();
-      int CurrentThreshold2 =3D getInlineThreshold(CS2);
-      float FudgeFactor2 =3D getInlineFudgeFactor(CS2);
-
-      if (Cost2 >=3D (int)(CurrentThreshold2 * FudgeFactor2))
-        callerWillBeRemoved =3D false;
-
-      // See if we have this case.  We subtract off the penalty
-      // for the call instruction, which we would be deleting.
-      if (Cost2 < (int)(CurrentThreshold2 * FudgeFactor2) &&
-          Cost2 + Cost - (InlineConstants::CallPenalty + 1) >=3D=20
-                (int)(CurrentThreshold2 * FudgeFactor2)) {
+      // See if inlining or original callsite would erase the cost delta of
+      // this callsite. We subtract off the penalty for the call instructi=
on,
+      // which we would be deleting.
+      if (IC2.getCostDelta() <=3D CandidateCost) {
         inliningPreventsSomeOuterInline =3D true;
-        TotalSecondaryCost +=3D Cost2;
+        TotalSecondaryCost +=3D IC2.getCost();
       }
     }
     // If all outer calls to Caller would get inlined, the cost for the la=
st
@@ -297,17 +305,16 @@
     if (callerWillBeRemoved && Caller->use_begin() !=3D Caller->use_end())
       TotalSecondaryCost +=3D InlineConstants::LastCallToStaticBonus;
=20
-    if (outerCallsFound && inliningPreventsSomeOuterInline &&
-        TotalSecondaryCost < Cost) {
-      DEBUG(dbgs() << "    NOT Inlining: " << *CS.getInstruction() <<=20
-           " Cost =3D " << Cost <<=20
+    if (inliningPreventsSomeOuterInline && TotalSecondaryCost < IC.getCost=
()) {
+      DEBUG(dbgs() << "    NOT Inlining: " << *CS.getInstruction() <<
+           " Cost =3D " << IC.getCost() <<
            ", outer Cost =3D " << TotalSecondaryCost << '\n');
       return false;
     }
   }
=20
-  DEBUG(dbgs() << "    Inlining: cost=3D" << Cost
-        << ", thres=3D" << AdjThreshold
+  DEBUG(dbgs() << "    Inlining: cost=3D" << IC.getCost()
+        << ", thres=3D" << (IC.getCostDelta() + IC.getCost())
         << ", Call: " << *CS.getInstruction() << '\n');
   return true;
 }
@@ -326,7 +333,6 @@
   return false;
 }
=20
-
 bool Inliner::runOnSCC(CallGraphSCC &SCC) {
   CallGraph &CG =3D getAnalysis<CallGraph>();
   const TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
@@ -415,8 +421,6 @@
         CG[Caller]->removeCallEdgeFor(CS);
         CS.getInstruction()->eraseFromParent();
         ++NumCallsDeleted;
-        // Update the cached cost info with the missing call
-        growCachedCostInfo(Caller, NULL);
       } else {
         // We can only inline direct calls to non-declarations.
         if (Callee =3D=3D 0 || Callee->isDeclaration()) continue;
@@ -439,7 +443,7 @@
=20
         // Attempt to inline the function.
         if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
-                                  InlineHistoryID))
+                                  InlineHistoryID, InsertLifetime))
           continue;
         ++NumInlined;
        =20
@@ -457,9 +461,6 @@
             CallSites.push_back(std::make_pair(CallSite(Ptr), NewHistoryID=
));
           }
         }
-       =20
-        // Update the cached cost info with the inlined call.
-        growCachedCostInfo(Caller, Callee);
       }
      =20
       // If we inlined or deleted the last possible call site to the funct=
ion,
@@ -479,8 +480,6 @@
         // Remove any call graph edges from the callee to its callees.
         CalleeNode->removeAllCalledFunctions();
        =20
-        resetCachedCostInfo(Callee);
-       =20
         // Removing the node for callee from the call graph and delete it.
         delete CG.removeFunctionFromModule(CalleeNode);
         ++NumDeleted;
@@ -514,29 +513,28 @@
=20
 /// removeDeadFunctions - Remove dead functions that are not included in
 /// DNR (Do Not Remove) list.
-bool Inliner::removeDeadFunctions(CallGraph &CG,=20
-                                  SmallPtrSet<const Function *, 16> *DNR) {
-  SmallPtrSet<CallGraphNode*, 16> FunctionsToRemove;
+bool Inliner::removeDeadFunctions(CallGraph &CG, bool AlwaysInlineOnly) {
+  SmallVector<CallGraphNode*, 16> FunctionsToRemove;
=20
   // Scan for all of the functions, looking for ones that should now be re=
moved
   // from the program.  Insert the dead ones in the FunctionsToRemove set.
   for (CallGraph::iterator I =3D CG.begin(), E =3D CG.end(); I !=3D E; ++I=
) {
     CallGraphNode *CGN =3D I->second;
-    if (CGN->getFunction() =3D=3D 0)
+    Function *F =3D CGN->getFunction();
+    if (!F || F->isDeclaration())
       continue;
-   =20
-    Function *F =3D CGN->getFunction();
-   =20
+
+    // Handle the case when this function is called and we only want to ca=
re
+    // about always-inline functions. This is a bit of a hack to share code
+    // between here and the InlineAlways pass.
+    if (AlwaysInlineOnly && !F->hasFnAttr(Attribute::AlwaysInline))
+      continue;
+
     // If the only remaining users of the function are dead constants, rem=
ove
     // them.
     F->removeDeadConstantUsers();
=20
-    if (DNR && DNR->count(F))
-      continue;
-    if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
-        !F->hasAvailableExternallyLinkage())
-      continue;
-    if (!F->use_empty())
+    if (!F->isDefTriviallyDead())
       continue;
    =20
     // Remove any call graph edges from the function to its callees.
@@ -548,24 +546,27 @@
     CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
=20
     // Removing the node for callee from the call graph and delete it.
-    FunctionsToRemove.insert(CGN);
+    FunctionsToRemove.push_back(CGN);
   }
+  if (FunctionsToRemove.empty())
+    return false;
=20
   // Now that we know which functions to delete, do so.  We didn't want to=
 do
   // this inline, because that would invalidate our CallGraph::iterator
   // objects. :(
   //
-  // Note that it doesn't matter that we are iterating over a non-stable s=
et
+  // Note that it doesn't matter that we are iterating over a non-stable o=
rder
   // here to do this, it doesn't matter which order the functions are dele=
ted
   // in.
-  bool Changed =3D false;
-  for (SmallPtrSet<CallGraphNode*, 16>::iterator I =3D FunctionsToRemove.b=
egin(),
-       E =3D FunctionsToRemove.end(); I !=3D E; ++I) {
-    resetCachedCostInfo((*I)->getFunction());
+  array_pod_sort(FunctionsToRemove.begin(), FunctionsToRemove.end());
+  FunctionsToRemove.erase(std::unique(FunctionsToRemove.begin(),
+                                      FunctionsToRemove.end()),
+                          FunctionsToRemove.end());
+  for (SmallVectorImpl<CallGraphNode *>::iterator I =3D FunctionsToRemove.=
begin(),
+                                                  E =3D FunctionsToRemove.=
end();
+       I !=3D E; ++I) {
     delete CG.removeFunctionFromModule(*I);
     ++NumDeleted;
-    Changed =3D true;
   }
-
-  return Changed;
+  return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/I=
nternalize.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/Internalize.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/Internalize.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -122,6 +122,9 @@
=20
   bool Changed =3D false;
=20
+  // Never internalize functions which code-gen might insert.
+  ExternalNames.insert("__stack_chk_fail");
+
   // Mark all functions not in the api as internal.
   // FIXME: maybe use private linkage?
   for (Module::iterator I =3D M.begin(), E =3D M.end(); I !=3D E; ++I)
@@ -148,9 +151,11 @@
   // won't find them.  (see MachineModuleInfo.)
   ExternalNames.insert("llvm.global_ctors");
   ExternalNames.insert("llvm.global_dtors");
-  ExternalNames.insert("llvm.noinline");
   ExternalNames.insert("llvm.global.annotations");
=20
+  // Never internalize symbols code-gen inserts.
+  ExternalNames.insert("__stack_chk_guard");
+
   // Mark all global variables with initializers that are not in the api as
   // internal as well.
   // FIXME: maybe use private linkage?
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/P=
assManagerBuilder.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/PassManagerBuilder.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/PassManagerBuilder.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -22,14 +22,19 @@
 #include "llvm/PassManager.h"
 #include "llvm/Analysis/Passes.h"
 #include "llvm/Analysis/Verifier.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Transforms/Scalar.h"
+#include "llvm/Transforms/Vectorize.h"
 #include "llvm/Transforms/IPO.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/ManagedStatic.h"
=20
 using namespace llvm;
=20
+static cl::opt<bool>
+RunVectorization("vectorize", cl::desc("Run vectorization passes"));
+
 PassManagerBuilder::PassManagerBuilder() {
     OptLevel =3D 2;
     SizeLevel =3D 0;
@@ -38,6 +43,7 @@
     DisableSimplifyLibCalls =3D false;
     DisableUnitAtATime =3D false;
     DisableUnrollLoops =3D false;
+    Vectorize =3D RunVectorization;
 }
=20
 PassManagerBuilder::~PassManagerBuilder() {
@@ -101,6 +107,7 @@
       MPM.add(Inliner);
       Inliner =3D 0;
     }
+    addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
     return;
   }
=20
@@ -110,6 +117,8 @@
   addInitialAliasAnalysisPasses(MPM);
=20
   if (!DisableUnitAtATime) {
+    addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
+
     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
=20
     MPM.add(createIPSCCPPass());              // IP SCCP
@@ -170,6 +179,13 @@
=20
   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
=20
+  if (Vectorize) {
+    MPM.add(createBBVectorizePass());
+    MPM.add(createInstructionCombiningPass());
+    if (OptLevel > 1)
+      MPM.add(createGVNPass());                 // Remove redundancies
+  }
+
   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
@@ -186,11 +202,13 @@
     if (OptLevel > 1)
       MPM.add(createConstantMergePass());     // Merge dup global constants
   }
+  addExtensionsToPM(EP_OptimizerLast, MPM);
 }
=20
 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
                                                 bool Internalize,
-                                                bool RunInliner) {
+                                                bool RunInliner,
+                                                bool DisableGVNLoadPRE) {
   // Provide AliasAnalysis services for optimizations.
   addInitialAliasAnalysisPasses(PM);
=20
@@ -246,9 +264,9 @@
   PM.add(createFunctionAttrsPass()); // Add nocapture.
   PM.add(createGlobalsModRefPass()); // IP alias analysis.
=20
-  PM.add(createLICMPass());      // Hoist loop invariants.
-  PM.add(createGVNPass());       // Remove redundancies.
-  PM.add(createMemCpyOptPass()); // Remove dead memcpys.
+  PM.add(createLICMPass());                 // Hoist loop invariants.
+  PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
+  PM.add(createMemCpyOptPass());            // Remove dead memcpys.
   // Nuke dead stores.
   PM.add(createDeadStoreEliminationPass());
=20
@@ -340,4 +358,3 @@
   PassManagerBase *LPM =3D unwrap(PM);
   Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/IPO/P=
runeEH.cpp
--- a/head/contrib/llvm/lib/Transforms/IPO/PruneEH.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/IPO/PruneEH.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -101,8 +101,7 @@
       // Check to see if this function performs an unwind or calls an
       // unwinding function.
       for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D E=
; ++BB) {
-        if (CheckUnwind && (isa<UnwindInst>(BB->getTerminator()) ||
-                            isa<ResumeInst>(BB->getTerminator()))) {
+        if (CheckUnwind && isa<ResumeInst>(BB->getTerminator())) {
           // Uses unwind / resume!
           SCCMightUnwind =3D true;
         } else if (CheckReturn && isa<ReturnInst>(BB->getTerminator())) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombine.h
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombine.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombine.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -22,6 +22,7 @@
 namespace llvm {
   class CallSite;
   class TargetData;
+  class TargetLibraryInfo;
   class DbgDeclareInst;
   class MemIntrinsic;
   class MemSetInst;
@@ -71,6 +72,7 @@
                              : public FunctionPass,
                                public InstVisitor<InstCombiner, Instructio=
n*> {
   TargetData *TD;
+  TargetLibraryInfo *TLI;
   bool MadeIRChange;
 public:
   /// Worklist - All of the instructions that need to be simplified.
@@ -92,9 +94,11 @@
   bool DoOneIteration(Function &F, unsigned ItNum);
=20
   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
-                                =20
+
   TargetData *getTargetData() const { return TD; }
=20
+  TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
+
   // Visitation implementation - Implement instruction combining for diffe=
rent
   // instruction types.  The semantics are as follows:
   // Return Value:
@@ -287,9 +291,9 @@
     return 0;  // Don't do anything with FI
   }
      =20
-  void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
+  void ComputeMaskedBits(Value *V, APInt &KnownZero,
                          APInt &KnownOne, unsigned Depth =3D 0) const {
-    return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth=
);
+    return llvm::ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
   }
  =20
   bool MaskedValueIsZero(Value *V, const APInt &Mask,=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineAddSub.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -136,6 +136,18 @@
         Value *NewShl =3D Builder->CreateShl(XorLHS, ShAmt, "sext");
         return BinaryOperator::CreateAShr(NewShl, ShAmt);
       }
+
+      // If this is a xor that was canonicalized from a sub, turn it back =
into
+      // a sub and fuse this add with it.
+      if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
+        IntegerType *IT =3D cast<IntegerType>(I.getType());
+        APInt LHSKnownOne(IT->getBitWidth(), 0);
+        APInt LHSKnownZero(IT->getBitWidth(), 0);
+        ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
+        if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
+          return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI=
),
+                                           XorLHS);
+      }
     }
   }
=20
@@ -189,14 +201,13 @@
=20
   // A+B --> A|B iff A and B have no bits set in common.
   if (IntegerType *IT =3D dyn_cast<IntegerType>(I.getType())) {
-    APInt Mask =3D APInt::getAllOnesValue(IT->getBitWidth());
     APInt LHSKnownOne(IT->getBitWidth(), 0);
     APInt LHSKnownZero(IT->getBitWidth(), 0);
-    ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
+    ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
     if (LHSKnownZero !=3D 0) {
       APInt RHSKnownOne(IT->getBitWidth(), 0);
       APInt RHSKnownZero(IT->getBitWidth(), 0);
-      ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
+      ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
      =20
       // No bits in common -> bitwise or.
       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
@@ -466,57 +477,57 @@
   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can opt=
imize
   // this.
   bool Swapped =3D false;
-  GetElementPtrInst *GEP =3D 0;
-  ConstantExpr *CstGEP =3D 0;
- =20
-  // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A=
.foo".
+  GEPOperator *GEP1 =3D 0, *GEP2 =3D 0;
+
   // For now we require one side to be the base pointer "A" or a constant
-  // expression derived from it.
-  if (GetElementPtrInst *LHSGEP =3D dyn_cast<GetElementPtrInst>(LHS)) {
+  // GEP derived from it.
+  if (GEPOperator *LHSGEP =3D dyn_cast<GEPOperator>(LHS)) {
     // (gep X, ...) - X
     if (LHSGEP->getOperand(0) =3D=3D RHS) {
-      GEP =3D LHSGEP;
+      GEP1 =3D LHSGEP;
       Swapped =3D false;
-    } else if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(RHS)) {
-      // (gep X, ...) - (ce_gep X, ...)
-      if (CE->getOpcode() =3D=3D Instruction::GetElementPtr &&
-          LHSGEP->getOperand(0) =3D=3D CE->getOperand(0)) {
-        CstGEP =3D CE;
-        GEP =3D LHSGEP;
+    } else if (GEPOperator *RHSGEP =3D dyn_cast<GEPOperator>(RHS)) {
+      // (gep X, ...) - (gep X, ...)
+      if (LHSGEP->getOperand(0)->stripPointerCasts() =3D=3D
+            RHSGEP->getOperand(0)->stripPointerCasts()) {
+        GEP2 =3D RHSGEP;
+        GEP1 =3D LHSGEP;
         Swapped =3D false;
       }
     }
   }
  =20
-  if (GetElementPtrInst *RHSGEP =3D dyn_cast<GetElementPtrInst>(RHS)) {
+  if (GEPOperator *RHSGEP =3D dyn_cast<GEPOperator>(RHS)) {
     // X - (gep X, ...)
     if (RHSGEP->getOperand(0) =3D=3D LHS) {
-      GEP =3D RHSGEP;
+      GEP1 =3D RHSGEP;
       Swapped =3D true;
-    } else if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(LHS)) {
-      // (ce_gep X, ...) - (gep X, ...)
-      if (CE->getOpcode() =3D=3D Instruction::GetElementPtr &&
-          RHSGEP->getOperand(0) =3D=3D CE->getOperand(0)) {
-        CstGEP =3D CE;
-        GEP =3D RHSGEP;
+    } else if (GEPOperator *LHSGEP =3D dyn_cast<GEPOperator>(LHS)) {
+      // (gep X, ...) - (gep X, ...)
+      if (RHSGEP->getOperand(0)->stripPointerCasts() =3D=3D
+            LHSGEP->getOperand(0)->stripPointerCasts()) {
+        GEP2 =3D LHSGEP;
+        GEP1 =3D RHSGEP;
         Swapped =3D true;
       }
     }
   }
  =20
-  if (GEP =3D=3D 0)
+  // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
+  // multiple users.
+  if (GEP1 =3D=3D 0 ||
+      (GEP2 !=3D 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()=
))
     return 0;
  =20
   // Emit the offset of the GEP and an intptr_t.
-  Value *Result =3D EmitGEPOffset(GEP);
+  Value *Result =3D EmitGEPOffset(GEP1);
  =20
   // If we had a constant expression GEP on the other side offsetting the
   // pointer, subtract it from the offset we have.
-  if (CstGEP) {
-    Value *CstOffset =3D EmitGEPOffset(CstGEP);
-    Result =3D Builder->CreateSub(Result, CstOffset);
+  if (GEP2) {
+    Value *Offset =3D EmitGEPOffset(GEP2);
+    Result =3D Builder->CreateSub(Result, Offset);
   }
- =20
=20
   // If we have p - gep(p, ...)  then we have to negate the result.
   if (Swapped)
@@ -587,6 +598,9 @@
     ConstantInt *C2;
     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(C2))))
       return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
+
+    if (SimplifyDemandedInstructionBits(I))
+      return &I;
   }
=20
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineAndOrXor.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #include "InstCombine.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/Analysis/InstructionSimplify.h"
+#include "llvm/Transforms/Utils/CmpInstAnalysis.h"
 #include "llvm/Support/ConstantRange.h"
 #include "llvm/Support/PatternMatch.h"
 using namespace llvm;
@@ -62,50 +63,6 @@
   return 0;
 }
=20
-
-/// getICmpCode - Encode a icmp predicate into a three bit mask.  These bi=
ts
-/// are carefully arranged to allow folding of expressions such as:
-///
-///      (A < B) | (A > B) --> (A !=3D B)
-///
-/// Note that this is only valid if the first and second predicates have t=
he
-/// same sign. Is illegal to do: (A u< B) | (A s> B)=20
-///
-/// Three bits are used to represent the condition, as follows:
-///   0  A > B
-///   1  A =3D=3D B
-///   2  A < B
-///
-/// <=3D>  Value  Definition
-/// 000     0   Always false
-/// 001     1   A >  B
-/// 010     2   A =3D=3D B
-/// 011     3   A >=3D B
-/// 100     4   A <  B
-/// 101     5   A !=3D B
-/// 110     6   A <=3D B
-/// 111     7   Always true
-/// =20
-static unsigned getICmpCode(const ICmpInst *ICI) {
-  switch (ICI->getPredicate()) {
-    // False -> 0
-  case ICmpInst::ICMP_UGT: return 1;  // 001
-  case ICmpInst::ICMP_SGT: return 1;  // 001
-  case ICmpInst::ICMP_EQ:  return 2;  // 010
-  case ICmpInst::ICMP_UGE: return 3;  // 011
-  case ICmpInst::ICMP_SGE: return 3;  // 011
-  case ICmpInst::ICMP_ULT: return 4;  // 100
-  case ICmpInst::ICMP_SLT: return 4;  // 100
-  case ICmpInst::ICMP_NE:  return 5;  // 101
-  case ICmpInst::ICMP_ULE: return 6;  // 110
-  case ICmpInst::ICMP_SLE: return 6;  // 110
-    // True -> 7
-  default:
-    llvm_unreachable("Invalid ICmp predicate!");
-    return 0;
-  }
-}
-
 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a =
fcmp
 /// predicate into a three bit mask. It also returns whether it is an orde=
red
 /// predicate by reference.
@@ -130,31 +87,19 @@
   default:
     // Not expecting FCMP_FALSE and FCMP_TRUE;
     llvm_unreachable("Unexpected FCmp predicate!");
-    return 0;
   }
 }
=20
-/// getICmpValue - This is the complement of getICmpCode, which turns an
+/// getNewICmpValue - This is the complement of getICmpCode, which turns an
 /// opcode and two operands into either a constant true or false, or a bra=
nd=20
 /// new ICmp instruction. The sign is passed in to determine which kind
 /// of predicate to use in the new icmp instruction.
-static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RH=
S,
-                           InstCombiner::BuilderTy *Builder) {
-  CmpInst::Predicate Pred;
-  switch (Code) {
-  default: assert(0 && "Illegal ICmp code!");
-  case 0: // False.
-    return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
-  case 1: Pred =3D Sign ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
-  case 2: Pred =3D ICmpInst::ICMP_EQ; break;
-  case 3: Pred =3D Sign ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
-  case 4: Pred =3D Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
-  case 5: Pred =3D ICmpInst::ICMP_NE; break;
-  case 6: Pred =3D Sign ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
-  case 7: // True.
-    return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
-  }
-  return Builder->CreateICmp(Pred, LHS, RHS);
+static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value =
*RHS,
+                              InstCombiner::BuilderTy *Builder) {
+  ICmpInst::Predicate NewPred;
+  if (Value *NewConstant =3D getICmpValue(Sign, Code, LHS, RHS, NewPred))
+    return NewConstant;
+  return Builder->CreateICmp(NewPred, LHS, RHS);
 }
=20
 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
@@ -165,7 +110,7 @@
                            InstCombiner::BuilderTy *Builder) {
   CmpInst::Predicate Pred;
   switch (code) {
-  default: assert(0 && "Illegal FCmp code!");
+  default: llvm_unreachable("Illegal FCmp code!");
   case 0: Pred =3D isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; br=
eak;
   case 1: Pred =3D isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; br=
eak;
   case 2: Pred =3D isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; br=
eak;
@@ -180,14 +125,6 @@
   return Builder->CreateFCmp(Pred, LHS, RHS);
 }
=20
-/// PredicatesFoldable - Return true if both predicates match sign or if at
-/// least one of them is an equality comparison (which is signless).
-static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate=
 p2) {
-  return (CmpInst::isSigned(p1) =3D=3D CmpInst::isSigned(p2)) ||
-         (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
-         (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
-}
-
 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Wh=
ere
 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
 // guaranteed to be a binary operator.
@@ -558,6 +495,38 @@
   return result;
 }
=20
+/// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
+/// if possible. The returned predicate is either =3D=3D or !=3D. Returns =
false if
+/// decomposition fails.
+static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &P=
red,
+                                 Value *&X, Value *&Y, Value *&Z) {
+  // X < 0 is equivalent to (X & SignBit) !=3D 0.
+  if (I->getPredicate() =3D=3D ICmpInst::ICMP_SLT)
+    if (ConstantInt *C =3D dyn_cast<ConstantInt>(I->getOperand(1)))
+      if (C->isZero()) {
+        X =3D I->getOperand(0);
+        Y =3D ConstantInt::get(I->getContext(),
+                             APInt::getSignBit(C->getBitWidth()));
+        Pred =3D ICmpInst::ICMP_NE;
+        Z =3D C;
+        return true;
+      }
+
+  // X > -1 is equivalent to (X & SignBit) =3D=3D 0.
+  if (I->getPredicate() =3D=3D ICmpInst::ICMP_SGT)
+    if (ConstantInt *C =3D dyn_cast<ConstantInt>(I->getOperand(1)))
+      if (C->isAllOnesValue()) {
+        X =3D I->getOperand(0);
+        Y =3D ConstantInt::get(I->getContext(),
+                             APInt::getSignBit(C->getBitWidth()));
+        Pred =3D ICmpInst::ICMP_EQ;
+        Z =3D ConstantInt::getNullValue(C->getType());
+        return true;
+      }
+
+  return false;
+}
+
 /// foldLogOpOfMaskedICmpsHelper:
 /// handle (icmp(A & B) =3D=3D/!=3D C) &/| (icmp(A & D) =3D=3D/!=3D E)
 /// return the set of pattern classes (from MaskedICmpType)
@@ -565,10 +534,9 @@
 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,=20
                                              Value*& B, Value*& C,
                                              Value*& D, Value*& E,
-                                             ICmpInst *LHS, ICmpInst *RHS)=
 {
-  ICmpInst::Predicate LHSCC =3D LHS->getPredicate(), RHSCC =3D RHS->getPre=
dicate();
-  if (LHSCC !=3D ICmpInst::ICMP_EQ && LHSCC !=3D ICmpInst::ICMP_NE) return=
 0;
-  if (RHSCC !=3D ICmpInst::ICMP_EQ && RHSCC !=3D ICmpInst::ICMP_NE) return=
 0;
+                                             ICmpInst *LHS, ICmpInst *RHS,
+                                             ICmpInst::Predicate &LHSCC,
+                                             ICmpInst::Predicate &RHSCC) {
   if (LHS->getOperand(0)->getType() !=3D RHS->getOperand(0)->getType()) re=
turn 0;
   // vectors are not (yet?) supported
   if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
@@ -582,40 +550,60 @@
   Value *L1 =3D LHS->getOperand(0);
   Value *L2 =3D LHS->getOperand(1);
   Value *L11,*L12,*L21,*L22;
-  if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
-    if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
+  // Check whether the icmp can be decomposed into a bit test.
+  if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
+    L21 =3D L22 =3D L1 =3D 0;
+  } else {
+    // Look for ANDs in the LHS icmp.
+    if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
+      if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
+        L21 =3D L22 =3D 0;
+    } else {
+      if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
+        return 0;
+      std::swap(L1, L2);
       L21 =3D L22 =3D 0;
+    }
   }
-  else {
-    if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
-      return 0;
-    std::swap(L1, L2);
-    L21 =3D L22 =3D 0;
-  }
+
+  // Bail if LHS was a icmp that can't be decomposed into an equality.
+  if (!ICmpInst::isEquality(LHSCC))
+    return 0;
=20
   Value *R1 =3D RHS->getOperand(0);
   Value *R2 =3D RHS->getOperand(1);
   Value *R11,*R12;
   bool ok =3D false;
-  if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
-    if (R11 !=3D 0 && (R11 =3D=3D L11 || R11 =3D=3D L12 || R11 =3D=3D L21 =
|| R11 =3D=3D L22)) {
+  if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
+    if (R11 =3D=3D L11 || R11 =3D=3D L12 || R11 =3D=3D L21 || R11 =3D=3D L=
22) {
+      A =3D R11; D =3D R12;
+    } else if (R12 =3D=3D L11 || R12 =3D=3D L12 || R12 =3D=3D L21 || R12 =
=3D=3D L22) {
+      A =3D R12; D =3D R11;
+    } else {
+      return 0;
+    }
+    E =3D R2; R1 =3D 0; ok =3D true;
+  } else if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
+    if (R11 =3D=3D L11 || R11 =3D=3D L12 || R11 =3D=3D L21 || R11 =3D=3D L=
22) {
       A =3D R11; D =3D R12; E =3D R2; ok =3D true;
-    }
-    else=20
-    if (R12 !=3D 0 && (R12 =3D=3D L11 || R12 =3D=3D L12 || R12 =3D=3D L21 =
|| R12 =3D=3D L22)) {
+    } else if (R12 =3D=3D L11 || R12 =3D=3D L12 || R12 =3D=3D L21 || R12 =
=3D=3D L22) {
       A =3D R12; D =3D R11; E =3D R2; ok =3D true;
     }
   }
+
+  // Bail if RHS was a icmp that can't be decomposed into an equality.
+  if (!ICmpInst::isEquality(RHSCC))
+    return 0;
+
+  // Look for ANDs in on the right side of the RHS icmp.
   if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
-    if (R11 !=3D 0 && (R11 =3D=3D L11 || R11 =3D=3D L12 || R11 =3D=3D L21 =
|| R11 =3D=3D L22)) {
-       A =3D R11; D =3D R12; E =3D R1; ok =3D true;
+    if (R11 =3D=3D L11 || R11 =3D=3D L12 || R11 =3D=3D L21 || R11 =3D=3D L=
22) {
+      A =3D R11; D =3D R12; E =3D R1; ok =3D true;
+    } else if (R12 =3D=3D L11 || R12 =3D=3D L12 || R12 =3D=3D L21 || R12 =
=3D=3D L22) {
+      A =3D R12; D =3D R11; E =3D R1; ok =3D true;
+    } else {
+      return 0;
     }
-    else=20
-    if (R12 !=3D 0 && (R12 =3D=3D L11 || R12 =3D=3D L12 || R12 =3D=3D L21 =
|| R12 =3D=3D L22)) {
-      A =3D R12; D =3D R11; E =3D R1; ok =3D true;
-    }
-    else
-      return 0;
   }
   if (!ok)
     return 0;
@@ -644,8 +632,12 @@
                                      ICmpInst::Predicate NEWCC,
                                      llvm::InstCombiner::BuilderTy* Builde=
r) {
   Value *A =3D 0, *B =3D 0, *C =3D 0, *D =3D 0, *E =3D 0;
-  unsigned mask =3D foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS);
+  ICmpInst::Predicate LHSCC =3D LHS->getPredicate(), RHSCC =3D RHS->getPre=
dicate();
+  unsigned mask =3D foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
+                                               LHSCC, RHSCC);
   if (mask =3D=3D 0) return 0;
+  assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
+         "foldLogOpOfMaskedICmpsHelper must return an equality predicate."=
);
=20
   if (NEWCC =3D=3D ICmpInst::ICMP_NE)
     mask >>=3D 1; // treat "Not"-states as normal states
@@ -693,11 +685,11 @@
=20
     ConstantInt *CCst =3D dyn_cast<ConstantInt>(C);
     if (CCst =3D=3D 0) return 0;
-    if (LHS->getPredicate() !=3D NEWCC)
+    if (LHSCC !=3D NEWCC)
       CCst =3D dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
     ConstantInt *ECst =3D dyn_cast<ConstantInt>(E);
     if (ECst =3D=3D 0) return 0;
-    if (RHS->getPredicate() !=3D NEWCC)
+    if (RHSCC !=3D NEWCC)
       ECst =3D dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
     ConstantInt* MCst =3D dyn_cast<ConstantInt>(
       ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
@@ -728,7 +720,7 @@
       Value *Op0 =3D LHS->getOperand(0), *Op1 =3D LHS->getOperand(1);
       unsigned Code =3D getICmpCode(LHS) & getICmpCode(RHS);
       bool isSigned =3D LHS->isSigned() || RHS->isSigned();
-      return getICmpValue(isSigned, Code, Op0, Op1, Builder);
+      return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
     }
   }
=20
@@ -756,24 +748,12 @@
       Value *NewOr =3D Builder->CreateOr(Val, Val2);
       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
     }
-
-    // (icmp slt A, 0) & (icmp slt B, 0) --> (icmp slt (A&B), 0)
-    if (LHSCC =3D=3D ICmpInst::ICMP_SLT && LHSCst->isZero()) {
-      Value *NewAnd =3D Builder->CreateAnd(Val, Val2);
-      return Builder->CreateICmp(LHSCC, NewAnd, LHSCst);
-    }
-
-    // (icmp sgt A, -1) & (icmp sgt B, -1) --> (icmp sgt (A|B), -1)
-    if (LHSCC =3D=3D ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()) {
-      Value *NewOr =3D Builder->CreateOr(Val, Val2);
-      return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
-    }
   }
=20
   // (trunc x) =3D=3D C1 & (and x, CA) =3D=3D C2 -> (and x, CA|CMAX) =3D=
=3D C1|C2
   // where CMAX is the all ones value for the truncated type,
   // iff the lower bits of C2 and CA are zero.
-  if (LHSCC =3D=3D RHSCC && ICmpInst::isEquality(LHSCC) &&
+  if (LHSCC =3D=3D ICmpInst::ICMP_EQ && LHSCC =3D=3D RHSCC &&
       LHS->hasOneUse() && RHS->hasOneUse()) {
     Value *V;
     ConstantInt *AndCst, *SmallCst =3D 0, *BigCst =3D 0;
@@ -805,7 +785,7 @@
       }
     }
   }
- =20
+
   // From here on, we only handle:
   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
   if (Val !=3D Val2) return 0;
@@ -1382,13 +1362,8 @@
   // part of the value (e.g. byte 3) then it must be shifted right.  If fr=
om the
   // low part, it must be shifted left.
   unsigned DestByteNo =3D InputByteNo + OverallLeftShift;
-  if (InputByteNo < ByteValues.size()/2) {
-    if (ByteValues.size()-1-DestByteNo !=3D InputByteNo)
-      return true;
-  } else {
-    if (ByteValues.size()-1-DestByteNo !=3D InputByteNo)
-      return true;
-  }
+  if (ByteValues.size()-1-DestByteNo !=3D InputByteNo)
+    return true;
  =20
   // If the destination byte value is already defined, the values are or'd
   // together, which isn't a bswap (unless it's an or of the same bits).
@@ -1469,7 +1444,7 @@
       Value *Op0 =3D LHS->getOperand(0), *Op1 =3D LHS->getOperand(1);
       unsigned Code =3D getICmpCode(LHS) | getICmpCode(RHS);
       bool isSigned =3D LHS->isSigned() || RHS->isSigned();
-      return getICmpValue(isSigned, Code, Op0, Op1, Builder);
+      return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
     }
   }
=20
@@ -1490,18 +1465,6 @@
       Value *NewOr =3D Builder->CreateOr(Val, Val2);
       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
     }
-
-    // (icmp slt A, 0) | (icmp slt B, 0) --> (icmp slt (A|B), 0)
-    if (LHSCC =3D=3D ICmpInst::ICMP_SLT && LHSCst->isZero()) {
-      Value *NewOr =3D Builder->CreateOr(Val, Val2);
-      return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
-    }
-
-    // (icmp sgt A, -1) | (icmp sgt B, -1) --> (icmp sgt (A&B), -1)
-    if (LHSCC =3D=3D ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()) {
-      Value *NewAnd =3D Builder->CreateAnd(Val, Val2);
-      return Builder->CreateICmp(LHSCC, NewAnd, LHSCst);
-    }
   }
=20
   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
@@ -1586,7 +1549,6 @@
     case ICmpInst::ICMP_SLT:         // (X !=3D 13 | X s< 15) -> true
       return ConstantInt::getTrue(LHS->getContext());
     }
-    break;
   case ICmpInst::ICMP_ULT:
     switch (RHSCC) {
     default: llvm_unreachable("Unknown integer condition code!");
@@ -1962,8 +1924,11 @@
       }
=20
   // Canonicalize xor to the RHS.
-  if (match(Op0, m_Xor(m_Value(), m_Value())))
+  bool SwappedForXor =3D false;
+  if (match(Op0, m_Xor(m_Value(), m_Value()))) {
     std::swap(Op0, Op1);
+    SwappedForXor =3D true;
+  }
=20
   // A | ( A ^ B) -> A |  B
   // A | (~A ^ B) -> A | ~B
@@ -1994,6 +1959,9 @@
         return BinaryOperator::CreateOr(Not, Op0);
       }
=20
+  if (SwappedForXor)
+    std::swap(Op0, Op1);
+
   if (ICmpInst *RHS =3D dyn_cast<ICmpInst>(I.getOperand(1)))
     if (ICmpInst *LHS =3D dyn_cast<ICmpInst>(I.getOperand(0)))
       if (Value *Res =3D FoldOrOfICmps(LHS, RHS))
@@ -2281,7 +2249,8 @@
           unsigned Code =3D getICmpCode(LHS) ^ getICmpCode(RHS);
           bool isSigned =3D LHS->isSigned() || RHS->isSigned();
           return ReplaceInstUsesWith(I,=20
-                               getICmpValue(isSigned, Code, Op0, Op1, Buil=
der));
+                               getNewICmpValue(isSigned, Code, Op0, Op1,
+                                               Builder));
         }
       }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineCalls.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -37,26 +37,26 @@
   unsigned CopyAlign =3D MI->getAlignment();
=20
   if (CopyAlign < MinAlign) {
-    MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),=20
+    MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
                                              MinAlign, false));
     return MI;
   }
- =20
+
   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
   // load/store.
   ConstantInt *MemOpLength =3D dyn_cast<ConstantInt>(MI->getArgOperand(2));
   if (MemOpLength =3D=3D 0) return 0;
- =20
+
   // Source and destination pointer types are always "i8*" for intrinsic. =
 See
   // if the size is something we can handle with a single primitive load/s=
tore.
   // A single load+store correctly handles overlapping memory in the memmo=
ve
   // case.
   unsigned Size =3D MemOpLength->getZExtValue();
   if (Size =3D=3D 0) return MI;  // Delete this mem transfer.
- =20
+
   if (Size > 8 || (Size&(Size-1)))
     return 0;  // If not 1/2/4/8 bytes, exit.
- =20
+
   // Use an integer load+store unless we can find something better.
   unsigned SrcAddrSp =3D
     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
@@ -66,7 +66,7 @@
   IntegerType* IntType =3D IntegerType::get(MI->getContext(), Size<<3);
   Type *NewSrcPtrTy =3D PointerType::get(IntType, SrcAddrSp);
   Type *NewDstPtrTy =3D PointerType::get(IntType, DstAddrSp);
- =20
+
   // Memcpy forces the use of i8* for the source and destination.  That me=
ans
   // that if you're using memcpy to move one double around, you'll get a c=
ast
   // from double* to i8*.  We'd much rather use a double load+store rather=
 than
@@ -94,20 +94,20 @@
         } else
           break;
       }
-     =20
+
       if (SrcETy->isSingleValueType()) {
         NewSrcPtrTy =3D PointerType::get(SrcETy, SrcAddrSp);
         NewDstPtrTy =3D PointerType::get(SrcETy, DstAddrSp);
       }
     }
   }
- =20
- =20
+
+
   // If the memcpy/memmove provides better alignment info than we can
   // infer, use it.
   SrcAlign =3D std::max(SrcAlign, CopyAlign);
   DstAlign =3D std::max(DstAlign, CopyAlign);
- =20
+
   Value *Src =3D Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
   Value *Dest =3D Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy=
);
   LoadInst *L =3D Builder->CreateLoad(Src, MI->isVolatile());
@@ -127,7 +127,7 @@
                                              Alignment, false));
     return MI;
   }
- =20
+
   // Extract the length and alignment and fill if they are constant.
   ConstantInt *LenC =3D dyn_cast<ConstantInt>(MI->getLength());
   ConstantInt *FillC =3D dyn_cast<ConstantInt>(MI->getValue());
@@ -135,14 +135,14 @@
     return 0;
   uint64_t Len =3D LenC->getZExtValue();
   Alignment =3D MI->getAlignment();
- =20
+
   // If the length is zero, this is a no-op
   if (Len =3D=3D 0) return MI; // memset(d,c,0,a) -> noop
- =20
+
   // memset(s,c,n) -> store s, c (for n=3D1,2,4,8)
   if (Len <=3D 8 && isPowerOf2_32((uint32_t)Len)) {
     Type *ITy =3D IntegerType::get(MI->getContext(), Len*8);  // n=3D1 -> =
i8.
-   =20
+
     Value *Dest =3D MI->getDest();
     unsigned DstAddrSp =3D cast<PointerType>(Dest->getType())->getAddressS=
pace();
     Type *NewDstPtrTy =3D PointerType::get(ITy, DstAddrSp);
@@ -150,13 +150,13 @@
=20
     // Alignment 0 is identity for alignment 1 for memset, but not store.
     if (Alignment =3D=3D 0) Alignment =3D 1;
-   =20
+
     // Extract the fill value and store.
     uint64_t Fill =3D FillC->getZExtValue()*0x0101010101010101ULL;
     StoreInst *S =3D Builder->CreateStore(ConstantInt::get(ITy, Fill), Des=
t,
                                         MI->isVolatile());
     S->setAlignment(Alignment);
-   =20
+
     // Set the size of the copy to 0, it will be deleted on the next itera=
tion.
     MI->setLength(Constant::getNullValue(LenC->getType()));
     return MI;
@@ -165,7 +165,7 @@
   return 0;
 }
=20
-/// visitCallInst - CallInst simplification.  This mostly only handles fol=
ding=20
+/// visitCallInst - CallInst simplification.  This mostly only handles fol=
ding
 /// of intrinsic instructions.  For normal calls, it allows visitCallSite =
to do
 /// the heavy lifting.
 ///
@@ -182,7 +182,7 @@
     CI.setDoesNotThrow();
     return &CI;
   }
- =20
+
   IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(&CI);
   if (!II) return visitCallSite(&CI);
=20
@@ -203,7 +203,7 @@
           // alignment is sufficient.
         }
     }
-   =20
+
     // No other transformations apply to volatile transfers.
     if (MI->isVolatile())
       return 0;
@@ -242,13 +242,13 @@
=20
     if (Changed) return II;
   }
- =20
+
   switch (II->getIntrinsicID()) {
   default: break;
   case Intrinsic::objectsize: {
     // We need target data for just about everything so depend on it.
     if (!TD) break;
-   =20
+
     Type *ReturnTy =3D CI.getType();
     uint64_t DontKnow =3D II->getArgOperand(1) =3D=3D Builder->getTrue() ?=
 0 : -1ULL;
=20
@@ -265,6 +265,8 @@
       // Get the current byte offset into the thing. Use the original
       // operand in case we're looking through a bitcast.
       SmallVector<Value*, 8> Ops(GEP->idx_begin(), GEP->idx_end());
+      if (!GEP->getPointerOperandType()->isPointerTy())
+        return 0;
       Offset =3D TD->getIndexedOffset(GEP->getPointerOperandType(), Ops);
=20
       Op1 =3D GEP->getPointerOperand()->stripPointerCasts();
@@ -322,7 +324,7 @@
     if (IntrinsicInst *Operand =3D dyn_cast<IntrinsicInst>(II->getArgOpera=
nd(0)))
       if (Operand->getIntrinsicID() =3D=3D Intrinsic::bswap)
         return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
-     =20
+
     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
     if (TruncInst *TI =3D dyn_cast<TruncInst>(II->getArgOperand(0))) {
       if (IntrinsicInst *Operand =3D dyn_cast<IntrinsicInst>(TI->getOperan=
d(0)))
@@ -334,7 +336,7 @@
           return new TruncInst(V, TI->getType());
         }
     }
-     =20
+
     break;
   case Intrinsic::powi:
     if (ConstantInt *Power =3D dyn_cast<ConstantInt>(II->getArgOperand(1))=
) {
@@ -359,14 +361,13 @@
     uint32_t BitWidth =3D IT->getBitWidth();
     APInt KnownZero(BitWidth, 0);
     APInt KnownOne(BitWidth, 0);
-    ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidt=
h),
-                      KnownZero, KnownOne);
+    ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
     unsigned TrailingZeros =3D KnownOne.countTrailingZeros();
     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
     if ((Mask & KnownZero) =3D=3D Mask)
       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
                                  APInt(BitWidth, TrailingZeros)));
-   =20
+
     }
     break;
   case Intrinsic::ctlz: {
@@ -378,31 +379,29 @@
     uint32_t BitWidth =3D IT->getBitWidth();
     APInt KnownZero(BitWidth, 0);
     APInt KnownOne(BitWidth, 0);
-    ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidt=
h),
-                      KnownZero, KnownOne);
+    ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
     unsigned LeadingZeros =3D KnownOne.countLeadingZeros();
     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
     if ((Mask & KnownZero) =3D=3D Mask)
       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
                                  APInt(BitWidth, LeadingZeros)));
-   =20
+
     }
     break;
   case Intrinsic::uadd_with_overflow: {
     Value *LHS =3D II->getArgOperand(0), *RHS =3D II->getArgOperand(1);
     IntegerType *IT =3D cast<IntegerType>(II->getArgOperand(0)->getType());
     uint32_t BitWidth =3D IT->getBitWidth();
-    APInt Mask =3D APInt::getSignBit(BitWidth);
     APInt LHSKnownZero(BitWidth, 0);
     APInt LHSKnownOne(BitWidth, 0);
-    ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
+    ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
     bool LHSKnownNegative =3D LHSKnownOne[BitWidth - 1];
     bool LHSKnownPositive =3D LHSKnownZero[BitWidth - 1];
=20
     if (LHSKnownNegative || LHSKnownPositive) {
       APInt RHSKnownZero(BitWidth, 0);
       APInt RHSKnownOne(BitWidth, 0);
-      ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
+      ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
       bool RHSKnownNegative =3D RHSKnownOne[BitWidth - 1];
       bool RHSKnownPositive =3D RHSKnownZero[BitWidth - 1];
       if (LHSKnownNegative && RHSKnownNegative) {
@@ -448,7 +447,7 @@
     // X + undef -> undef
     if (isa<UndefValue>(II->getArgOperand(1)))
       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
-     =20
+
     if (ConstantInt *RHS =3D dyn_cast<ConstantInt>(II->getArgOperand(1))) {
       // X + 0 -> {X, false}
       if (RHS->isZero()) {
@@ -469,7 +468,7 @@
     if (isa<UndefValue>(II->getArgOperand(0)) ||
         isa<UndefValue>(II->getArgOperand(1)))
       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
-     =20
+
     if (ConstantInt *RHS =3D dyn_cast<ConstantInt>(II->getArgOperand(1))) {
       // X - 0 -> {X, false}
       if (RHS->isZero()) {
@@ -477,7 +476,7 @@
           UndefValue::get(II->getArgOperand(0)->getType()),
           ConstantInt::getFalse(II->getContext())
         };
-        Constant *Struct =3D=20
+        Constant *Struct =3D
           ConstantStruct::get(cast<StructType>(II->getType()), V);
         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
       }
@@ -486,14 +485,13 @@
   case Intrinsic::umul_with_overflow: {
     Value *LHS =3D II->getArgOperand(0), *RHS =3D II->getArgOperand(1);
     unsigned BitWidth =3D cast<IntegerType>(LHS->getType())->getBitWidth();
-    APInt Mask =3D APInt::getAllOnesValue(BitWidth);
=20
     APInt LHSKnownZero(BitWidth, 0);
     APInt LHSKnownOne(BitWidth, 0);
-    ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
+    ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
     APInt RHSKnownZero(BitWidth, 0);
     APInt RHSKnownOne(BitWidth, 0);
-    ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
+    ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
=20
     // Get the largest possible values for each operand.
     APInt LHSMax =3D ~LHSKnownZero;
@@ -526,19 +524,19 @@
     // X * undef -> undef
     if (isa<UndefValue>(II->getArgOperand(1)))
       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
-     =20
+
     if (ConstantInt *RHSI =3D dyn_cast<ConstantInt>(II->getArgOperand(1)))=
 {
       // X*0 -> {0, false}
       if (RHSI->isZero())
         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType(=
)));
-     =20
+
       // X * 1 -> {X, false}
       if (RHSI->equalsInt(1)) {
         Constant *V[] =3D {
           UndefValue::get(II->getArgOperand(0)->getType()),
           ConstantInt::getFalse(II->getContext())
         };
-        Constant *Struct =3D=20
+        Constant *Struct =3D
           ConstantStruct::get(cast<StructType>(II->getType()), V);
         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
       }
@@ -557,7 +555,7 @@
   case Intrinsic::ppc_altivec_stvxl:
     // Turn stvx -> store if the pointer is known aligned.
     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, TD) >=3D 16) {
-      Type *OpPtrTy =3D=20
+      Type *OpPtrTy =3D
         PointerType::getUnqual(II->getArgOperand(0)->getType());
       Value *Ptr =3D Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
       return new StoreInst(II->getArgOperand(0), Ptr);
@@ -568,7 +566,7 @@
   case Intrinsic::x86_sse2_storeu_dq:
     // Turn X86 storeu -> store if the pointer is known aligned.
     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >=3D 16) {
-      Type *OpPtrTy =3D=20
+      Type *OpPtrTy =3D
         PointerType::getUnqual(II->getArgOperand(1)->getType());
       Value *Ptr =3D Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
       return new StoreInst(II->getArgOperand(1), Ptr);
@@ -621,19 +619,21 @@
=20
   case Intrinsic::ppc_altivec_vperm:
     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
-    if (ConstantVector *Mask =3D dyn_cast<ConstantVector>(II->getArgOperan=
d(2))) {
-      assert(Mask->getNumOperands() =3D=3D 16 && "Bad type for intrinsic!"=
);
-     =20
+    if (Constant *Mask =3D dyn_cast<Constant>(II->getArgOperand(2))) {
+      assert(Mask->getType()->getVectorNumElements() =3D=3D 16 &&
+             "Bad type for intrinsic!");
+
       // Check that all of the elements are integer constants or undefs.
       bool AllEltsOk =3D true;
       for (unsigned i =3D 0; i !=3D 16; ++i) {
-        if (!isa<ConstantInt>(Mask->getOperand(i)) &&=20
-            !isa<UndefValue>(Mask->getOperand(i))) {
+        Constant *Elt =3D Mask->getAggregateElement(i);
+        if (Elt =3D=3D 0 ||
+            !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
           AllEltsOk =3D false;
           break;
         }
       }
-     =20
+
       if (AllEltsOk) {
         // Cast the input vectors to byte vectors.
         Value *Op0 =3D Builder->CreateBitCast(II->getArgOperand(0),
@@ -641,23 +641,24 @@
         Value *Op1 =3D Builder->CreateBitCast(II->getArgOperand(1),
                                             Mask->getType());
         Value *Result =3D UndefValue::get(Op0->getType());
-       =20
+
         // Only extract each element once.
         Value *ExtractedElts[32];
         memset(ExtractedElts, 0, sizeof(ExtractedElts));
-       =20
+
         for (unsigned i =3D 0; i !=3D 16; ++i) {
-          if (isa<UndefValue>(Mask->getOperand(i)))
+          if (isa<UndefValue>(Mask->getAggregateElement(i)))
             continue;
-          unsigned Idx=3Dcast<ConstantInt>(Mask->getOperand(i))->getZExtVa=
lue();
+          unsigned Idx =3D
+            cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue(=
);
           Idx &=3D 31;  // Match the hardware behavior.
-         =20
+
           if (ExtractedElts[Idx] =3D=3D 0) {
-            ExtractedElts[Idx] =3D=20
+            ExtractedElts[Idx] =3D
               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
                                             Builder->getInt32(Idx&15));
           }
-       =20
+
           // Insert this value into the result vector.
           Result =3D Builder->CreateInsertElement(Result, ExtractedElts[Id=
x],
                                                 Builder->getInt32(i));
@@ -703,7 +704,7 @@
           return EraseInstFromFunction(CI);
       }
     }
-   =20
+
     // Scan down this block to see if there is another stack restore in the
     // same block without an intervening call/alloca.
     BasicBlock::iterator BI =3D II;
@@ -728,12 +729,11 @@
         }
       }
     }
-   =20
+
     // If the stack restore is in a return, resume, or unwind block and if=
 there
     // are no allocas or calls between the restore and the return, nuke the
     // restore.
-    if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI) ||
-                          isa<UnwindInst>(TI)))
+    if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
       return EraseInstFromFunction(CI);
     break;
   }
@@ -748,7 +748,7 @@
   return visitCallSite(&II);
 }
=20
-/// isSafeToEliminateVarargsCast - If this cast does not affect the value=20
+/// isSafeToEliminateVarargsCast - If this cast does not affect the value
 /// passed through the varargs area, we can eliminate the use of the cast.
 static bool isSafeToEliminateVarargsCast(const CallSite CS,
                                          const CastInst * const CI,
@@ -760,10 +760,10 @@
   // The size of ByVal arguments is derived from the type, so we
   // can't change to a type with a different size.  If the size were
   // passed explicitly we could avoid this check.
-  if (!CS.paramHasAttr(ix, Attribute::ByVal))
+  if (!CS.isByValArgument(ix))
     return true;
=20
-  Type* SrcTy =3D=20
+  Type* SrcTy =3D
             cast<PointerType>(CI->getOperand(0)->getType())->getElementTyp=
e();
   Type* DstTy =3D cast<PointerType>(CI->getType())->getElementType();
   if (!SrcTy->isSized() || !DstTy->isSized())
@@ -807,7 +807,7 @@
 } // end anonymous namespace
=20
 // Try to fold some different type of calls here.
-// Currently we're only working with the checking functions, memcpy_chk,=20
+// Currently we're only working with the checking functions, memcpy_chk,
 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_c=
hk,
 // strcat_chk and strncat_chk.
 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData =
*TD) {
@@ -916,7 +916,7 @@
         !CalleeF->isDeclaration()) {
       Instruction *OldCall =3D CS.getInstruction();
       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
-                UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),=20
+                UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
                                   OldCall);
       // If OldCall dues not return void then replaceAllUsesWith undef.
       // This allows ValueHandlers and custom metadata to adjust itself.
@@ -924,7 +924,7 @@
         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
       if (isa<CallInst>(OldCall))
         return EraseInstFromFunction(*OldCall);
-     =20
+
       // We cannot remove an invoke, because it would change the CFG, just
       // change the callee to a null pointer.
       cast<InvokeInst>(OldCall)->setCalledFunction(
@@ -960,7 +960,7 @@
   PointerType *PTy =3D cast<PointerType>(Callee->getType());
   FunctionType *FTy =3D cast<FunctionType>(PTy->getElementType());
   if (FTy->isVarArg()) {
-    int ix =3D FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
+    int ix =3D FTy->getNumParams();
     // See if we can optimize any arguments passed through the varargs are=
a of
     // the call.
     for (CallSite::arg_iterator I =3D CS.arg_begin()+FTy->getNumParams(),
@@ -1061,17 +1061,17 @@
     if (!CastInst::isCastable(ActTy, ParamTy))
       return false;   // Cannot transform this parameter value.
=20
-    unsigned Attrs =3D CallerPAL.getParamAttributes(i + 1);
+    Attributes Attrs =3D CallerPAL.getParamAttributes(i + 1);
     if (Attrs & Attribute::typeIncompatible(ParamTy))
       return false;   // Attribute not compatible with transformed value.
-   =20
+
     // If the parameter is passed as a byval argument, then we have to hav=
e a
     // sized type and the sized type has to have the same size as the old =
type.
     if (ParamTy !=3D ActTy && (Attrs & Attribute::ByVal)) {
       PointerType *ParamPTy =3D dyn_cast<PointerType>(ParamTy);
       if (ParamPTy =3D=3D 0 || !ParamPTy->getElementType()->isSized() || T=
D =3D=3D 0)
         return false;
-     =20
+
       Type *CurElTy =3D cast<PointerType>(ActTy)->getElementType();
       if (TD->getTypeAllocSize(CurElTy) !=3D
           TD->getTypeAllocSize(ParamPTy->getElementType()))
@@ -1099,8 +1099,17 @@
     PointerType *APTy =3D cast<PointerType>(CS.getCalledValue()->getType()=
);
     if (FT->isVarArg()!=3Dcast<FunctionType>(APTy->getElementType())->isVa=
rArg())
       return false;
+
+    // If both the callee and the cast type are varargs, we still have to =
make
+    // sure the number of fixed parameters are the same or we have the same
+    // ABI issues as if we introduce a varargs call.
+    if (FT->isVarArg() &&
+        cast<FunctionType>(APTy->getElementType())->isVarArg() &&
+        FT->getNumParams() !=3D
+        cast<FunctionType>(APTy->getElementType())->getNumParams())
+      return false;
   }
-     =20
+
   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
       !CallerPAL.isEmpty())
     // In this case we have more arguments than the new function type, but=
 we
@@ -1114,7 +1123,7 @@
         return false;
     }
=20
- =20
+
   // Okay, we decided that this is a safe thing to do: go ahead and start
   // inserting cast instructions as necessary.
   std::vector<Value*> Args;
@@ -1352,11 +1361,11 @@
=20
       // Replace the trampoline call with a direct call.  Let the generic
       // code sort out any function type mismatches.
-      FunctionType *NewFTy =3D FunctionType::get(FTy->getReturnType(), New=
Types,=20
+      FunctionType *NewFTy =3D FunctionType::get(FTy->getReturnType(), New=
Types,
                                                 FTy->isVarArg());
       Constant *NewCallee =3D
         NestF->getType() =3D=3D PointerType::getUnqual(NewFTy) ?
-        NestF : ConstantExpr::getBitCast(NestF,=20
+        NestF : ConstantExpr::getBitCast(NestF,
                                          PointerType::getUnqual(NewFTy));
       const AttrListPtr &NewPAL =3D AttrListPtr::get(NewAttrs.begin(),
                                                    NewAttrs.end());
@@ -1385,9 +1394,8 @@
   // parameter, there is no need to adjust the argument list.  Let the gen=
eric
   // code sort out any function type mismatches.
   Constant *NewCallee =3D
-    NestF->getType() =3D=3D PTy ? NestF :=20
+    NestF->getType() =3D=3D PTy ? NestF :
                               ConstantExpr::getBitCast(NestF, PTy);
   CS.setCalledFunction(NewCallee);
   return CS.getInstruction();
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineCasts.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #include "InstCombine.h"
 #include "llvm/Analysis/ConstantFolding.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Support/PatternMatch.h"
 using namespace llvm;
 using namespace PatternMatch;
@@ -147,8 +148,6 @@
   return ReplaceInstUsesWith(CI, New);
 }
=20
-
-
 /// EvaluateInDifferentType - Given an expression that=20
 /// CanEvaluateTruncated or CanEvaluateSExtd returns true for, actually
 /// insert the code to evaluate the expression.
@@ -158,7 +157,7 @@
     C =3D ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
     // If we got a constantexpr back, try to simplify it with TD info.
     if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(C))
-      C =3D ConstantFoldConstantExpression(CE, TD);
+      C =3D ConstantFoldConstantExpression(CE, TD, TLI);
     return C;
   }
=20
@@ -216,7 +215,6 @@
   default:=20
     // TODO: Can handle more cases here.
     llvm_unreachable("Unreachable!");
-    break;
   }
  =20
   Res->takeName(I);
@@ -528,9 +526,7 @@
=20
       return ReplaceInstUsesWith(CI, In);
     }
-     =20
-     =20
-     =20
+
     // zext (X =3D=3D 0) to i32 --> X^1      iff X has only the low bit se=
t.
     // zext (X =3D=3D 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit se=
t.
     // zext (X =3D=3D 1) to i32 --> X        iff X has only the low bit se=
t.
@@ -545,8 +541,7 @@
       // If Op1C some other power of two, convert:
       uint32_t BitWidth =3D Op1C->getType()->getBitWidth();
       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-      APInt TypeMask(APInt::getAllOnesValue(BitWidth));
-      ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
+      ComputeMaskedBits(ICI->getOperand(0), KnownZero, KnownOne);
        =20
       APInt KnownZeroMask(~KnownZero);
       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
@@ -594,9 +589,8 @@
=20
       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
-      APInt TypeMask(APInt::getAllOnesValue(BitWidth));
-      ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
-      ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
+      ComputeMaskedBits(LHS, KnownZeroLHS, KnownOneLHS);
+      ComputeMaskedBits(RHS, KnownZeroRHS, KnownOneRHS);
=20
       if (KnownZeroLHS =3D=3D KnownZeroRHS && KnownOneLHS =3D=3D KnownOneR=
HS) {
         APInt KnownBits =3D KnownZeroLHS | KnownOneLHS;
@@ -915,8 +909,7 @@
         ICI->isEquality() && (Op1C->isZero() || Op1C->getValue().isPowerOf=
2())){
       unsigned BitWidth =3D Op1C->getType()->getBitWidth();
       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-      APInt TypeMask(APInt::getAllOnesValue(BitWidth));
-      ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
+      ComputeMaskedBits(Op0, KnownZero, KnownOne);
=20
       APInt KnownZeroMask(~KnownZero);
       if (KnownZeroMask.isPowerOf2()) {
@@ -1163,6 +1156,9 @@
   if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(V)) {
     if (CFP->getType() =3D=3D Type::getPPC_FP128Ty(V->getContext()))
       return V;  // No constant folding of this.
+    // See if the value can be truncated to half and then reextended.
+    if (Value *V =3D FitsInFPType(CFP, APFloat::IEEEhalf))
+      return V;
     // See if the value can be truncated to float and then reextended.
     if (Value *V =3D FitsInFPType(CFP, APFloat::IEEEsingle))
       return V;
@@ -1213,10 +1209,9 @@
   }
  =20
   // Fold (fptrunc (sqrt (fpext x))) -> (sqrtf x)
-  // NOTE: This should be disabled by -fno-builtin-sqrt if we ever support=
 it.
   CallInst *Call =3D dyn_cast<CallInst>(CI.getOperand(0));
-  if (Call && Call->getCalledFunction() &&
-      Call->getCalledFunction()->getName() =3D=3D "sqrt" &&
+  if (Call && Call->getCalledFunction() && TLI->has(LibFunc::sqrtf) &&
+      Call->getCalledFunction()->getName() =3D=3D TLI->getName(LibFunc::sq=
rt) &&
       Call->getNumArgOperands() =3D=3D 1 &&
       Call->hasOneUse()) {
     CastInst *Arg =3D dyn_cast<CastInst>(Call->getArgOperand(0));
@@ -1423,16 +1418,15 @@
   // Now that the element types match, get the shuffle mask and RHS of the
   // shuffle to use, which depends on whether we're increasing or decreasi=
ng the
   // size of the input.
-  SmallVector<Constant*, 16> ShuffleMask;
+  SmallVector<uint32_t, 16> ShuffleMask;
   Value *V2;
-  IntegerType *Int32Ty =3D Type::getInt32Ty(SrcTy->getContext());
  =20
   if (SrcTy->getNumElements() > DestTy->getNumElements()) {
     // If we're shrinking the number of elements, just shuffle in the low
     // elements from the input and use undef as the second shuffle input.
     V2 =3D UndefValue::get(SrcTy);
     for (unsigned i =3D 0, e =3D DestTy->getNumElements(); i !=3D e; ++i)
-      ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
+      ShuffleMask.push_back(i);
    =20
   } else {
     // If we're increasing the number of elements, shuffle in all of the
@@ -1441,14 +1435,16 @@
     V2 =3D Constant::getNullValue(SrcTy);
     unsigned SrcElts =3D SrcTy->getNumElements();
     for (unsigned i =3D 0, e =3D SrcElts; i !=3D e; ++i)
-      ShuffleMask.push_back(ConstantInt::get(Int32Ty, i));
+      ShuffleMask.push_back(i);
=20
     // The excess elements reference the first element of the zero input.
-    ShuffleMask.append(DestTy->getNumElements()-SrcElts,
-                       ConstantInt::get(Int32Ty, SrcElts));
+    for (unsigned i =3D 0, e =3D DestTy->getNumElements()-SrcElts; i !=3D =
e; ++i)
+      ShuffleMask.push_back(SrcElts);
   }
  =20
-  return new ShuffleVectorInst(InVal, V2, ConstantVector::get(ShuffleMask)=
);
+  return new ShuffleVectorInst(InVal, V2,
+                               ConstantDataVector::get(V2->getContext(),
+                                                       ShuffleMask));
 }
=20
 static bool isMultipleOfTypeSize(unsigned Value, Type *Ty) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineCompares.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -203,8 +203,12 @@
   // We need TD information to know the pointer size unless this is inboun=
ds.
   if (!GEP->isInBounds() && TD =3D=3D 0) return 0;
=20
-  ConstantArray *Init =3D dyn_cast<ConstantArray>(GV->getInitializer());
-  if (Init =3D=3D 0 || Init->getNumOperands() > 1024) return 0;
+  Constant *Init =3D GV->getInitializer();
+  if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
+    return 0;
+ =20
+  uint64_t ArrayElementCount =3D Init->getType()->getArrayNumElements();
+  if (ArrayElementCount > 1024) return 0;  // Don't blow up on huge arrays.
=20
   // There are many forms of this optimization we can handle, for now, jus=
t do
   // the simple index into a single-dimensional array.
@@ -221,7 +225,7 @@
   // structs.
   SmallVector<unsigned, 4> LaterIndices;
=20
-  Type *EltTy =3D cast<ArrayType>(Init->getType())->getElementType();
+  Type *EltTy =3D Init->getType()->getArrayElementType();
   for (unsigned i =3D 3, e =3D GEP->getNumOperands(); i !=3D e; ++i) {
     ConstantInt *Idx =3D dyn_cast<ConstantInt>(GEP->getOperand(i));
     if (Idx =3D=3D 0) return 0;  // Variable index.
@@ -272,8 +276,9 @@
=20
   // Scan the array and see if one of our patterns matches.
   Constant *CompareRHS =3D cast<Constant>(ICI.getOperand(1));
-  for (unsigned i =3D 0, e =3D Init->getNumOperands(); i !=3D e; ++i) {
-    Constant *Elt =3D Init->getOperand(i);
+  for (unsigned i =3D 0, e =3D ArrayElementCount; i !=3D e; ++i) {
+    Constant *Elt =3D Init->getAggregateElement(i);
+    if (Elt =3D=3D 0) return 0;
=20
     // If this is indexing an array of structures, get the structure eleme=
nt.
     if (!LaterIndices.empty())
@@ -284,7 +289,7 @@
=20
     // Find out if the comparison would be true or false for the i'th elem=
ent.
     Constant *C =3D ConstantFoldCompareInstOperands(ICI.getPredicate(), El=
t,
-                                                  CompareRHS, TD);
+                                                  CompareRHS, TD, TLI);
     // If the result is undef for this element, ignore it.
     if (isa<UndefValue>(C)) {
       // Extend range state machines to cover this element in case there i=
s an
@@ -440,10 +445,10 @@
   // If a 32-bit or 64-bit magic bitvector captures the entire comparison =
state
   // of this load, replace it with computation that does:
   //   ((magic_cst >> i) & 1) !=3D 0
-  if (Init->getNumOperands() <=3D 32 ||
-      (TD && Init->getNumOperands() <=3D 64 && TD->isLegalInteger(64))) {
+  if (ArrayElementCount <=3D 32 ||
+      (TD && ArrayElementCount <=3D 64 && TD->isLegalInteger(64))) {
     Type *Ty;
-    if (Init->getNumOperands() <=3D 32)
+    if (ArrayElementCount <=3D 32)
       Ty =3D Type::getInt32Ty(Init->getContext());
     else
       Ty =3D Type::getInt64Ty(Init->getContext());
@@ -566,6 +571,14 @@
 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
                                        ICmpInst::Predicate Cond,
                                        Instruction &I) {
+  // Don't transform signed compares of GEPs into index compares. Even if =
the
+  // GEP is inbounds, the final add of the base pointer can have signed ov=
erflow
+  // and would change the result of the icmp.
+  // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" cou=
ld be
+  // the maximum signed value for the pointer type.
+  if (ICmpInst::isSigned(Cond))
+    return 0;
+
   // Look through bitcasts.
   if (BitCastInst *BCI =3D dyn_cast<BitCastInst>(RHS))
     RHS =3D BCI->getOperand(0);
@@ -602,6 +615,20 @@
         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
=20
+      // If we're comparing GEPs with two base pointers that only differ i=
n type
+      // and both GEPs have only constant indices or just one use, then fo=
ld
+      // the compare with the adjusted indices.
+      if (TD && GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
+          (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
+          (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
+          PtrBase->stripPointerCasts() =3D=3D
+            GEPRHS->getOperand(0)->stripPointerCasts()) {
+        Value *Cmp =3D Builder->CreateICmp(ICmpInst::getSignedPredicate(Co=
nd),
+                                         EmitGEPOffset(GEPLHS),
+                                         EmitGEPOffset(GEPRHS));
+        return ReplaceInstUsesWith(I, Cmp);
+      }
+
       // Otherwise, the base pointers are different and the indices are
       // different, bail out.
       return 0;
@@ -1001,9 +1028,8 @@
       // of the high bits truncated out of x are known.
       unsigned DstBits =3D LHSI->getType()->getPrimitiveSizeInBits(),
              SrcBits =3D LHSI->getOperand(0)->getType()->getPrimitiveSizeI=
nBits();
-      APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
-      ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
+      ComputeMaskedBits(LHSI->getOperand(0), KnownZero, KnownOne);
=20
       // If all the high bits are known, we can do this xform.
       if ((KnownZero|KnownOne).countLeadingOnes() >=3D SrcBits-DstBits) {
@@ -1657,6 +1683,14 @@
       CI1->getValue() !=3D APInt::getLowBitsSet(CI1->getBitWidth(), NewWid=
th))
     return 0;
=20
+  // This is only really a signed overflow check if the inputs have been
+  // sign-extended; check for that condition. For example, if CI2 is 2^31 =
and
+  // the operands of the add are 64 bits wide, we need at least 33 sign bi=
ts.
+  unsigned NeededSignBits =3D CI1->getBitWidth() - NewWidth + 1;
+  if (IC.ComputeNumSignBits(A) < NeededSignBits ||
+      IC.ComputeNumSignBits(B) < NeededSignBits)
+    return 0;
+
   // In order to replace the original add with a narrower
   // llvm.sadd.with.overflow, the only uses allowed are the add-with-const=
ant
   // and truncates that discard the high bits of the add.  Verify that thi=
s is
@@ -1787,6 +1821,24 @@
   if (Value *V =3D SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
     return ReplaceInstUsesWith(I, V);
=20
+  // comparing -val or val with non-zero is the same as just comparing val
+  // ie, abs(val) !=3D 0 -> val !=3D 0
+  if (I.getPredicate() =3D=3D ICmpInst::ICMP_NE && match(Op1, m_Zero()))
+  {
+    Value *Cond, *SelectTrue, *SelectFalse;
+    if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
+                            m_Value(SelectFalse)))) {
+      if (Value *V =3D dyn_castNegVal(SelectTrue)) {
+        if (V =3D=3D SelectFalse)
+          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, O=
p1);
+      }
+      else if (Value *V =3D dyn_castNegVal(SelectFalse)) {
+        if (V =3D=3D SelectTrue)
+          return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, O=
p1);
+      }
+    }
+  }
+
   Type *Ty =3D Op0->getType();
=20
   // icmp's with boolean values can always be turned into bitwise operatio=
ns
@@ -2683,6 +2735,17 @@
         return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())=
);
       return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
     }
+  } else {
+    // See if the RHS value is < UnsignedMin.
+    APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
+    SMin.convertFromAPInt(APInt::getMinValue(IntWidth), true,
+                          APFloat::rmNearestTiesToEven);
+    if (SMin.compare(RHS) =3D=3D APFloat::cmpGreaterThan) { // umin > 1231=
2.0
+      if (Pred =3D=3D ICmpInst::ICMP_NE || Pred =3D=3D ICmpInst::ICMP_UGT =
||
+          Pred =3D=3D ICmpInst::ICMP_UGE)
+        return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext())=
);
+      return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
+    }
   }
=20
   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX]=
 or
@@ -2822,7 +2885,9 @@
=20
         const fltSemantics *Sem;
         // FIXME: This shouldn't be here.
-        if (LHSExt->getSrcTy()->isFloatTy())
+        if (LHSExt->getSrcTy()->isHalfTy())
+          Sem =3D &APFloat::IEEEhalf;
+        else if (LHSExt->getSrcTy()->isFloatTy())
           Sem =3D &APFloat::IEEEsingle;
         else if (LHSExt->getSrcTy()->isDoubleTy())
           Sem =3D &APFloat::IEEEdouble;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineLoadStoreAlloca.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAllo=
ca.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAllo=
ca.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -22,6 +22,72 @@
=20
 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
=20
+// Try to kill dead allocas by walking through its uses until we see some =
use
+// that could escape. This is a conservative analysis which tries to handle
+// GEPs, bitcasts, stores, and no-op intrinsics. These tend to be the thin=
gs
+// left after inlining and SROA finish chewing on an alloca.
+static Instruction *removeDeadAlloca(InstCombiner &IC, AllocaInst &AI) {
+  SmallVector<Instruction *, 4> Worklist, DeadStores;
+  Worklist.push_back(&AI);
+  do {
+    Instruction *PI =3D Worklist.pop_back_val();
+    for (Value::use_iterator UI =3D PI->use_begin(), UE =3D PI->use_end();
+         UI !=3D UE; ++UI) {
+      Instruction *I =3D cast<Instruction>(*UI);
+      switch (I->getOpcode()) {
+      default:
+        // Give up the moment we see something we can't handle.
+        return 0;
+
+      case Instruction::GetElementPtr:
+      case Instruction::BitCast:
+        Worklist.push_back(I);
+        continue;
+
+      case Instruction::Call:
+        // We can handle a limited subset of calls to no-op intrinsics.
+        if (IntrinsicInst *II =3D dyn_cast<IntrinsicInst>(I)) {
+          switch (II->getIntrinsicID()) {
+          case Intrinsic::dbg_declare:
+          case Intrinsic::dbg_value:
+          case Intrinsic::invariant_start:
+          case Intrinsic::invariant_end:
+          case Intrinsic::lifetime_start:
+          case Intrinsic::lifetime_end:
+            continue;
+          default:
+            return 0;
+          }
+        }
+        // Reject everything else.
+        return 0;
+
+      case Instruction::Store: {
+        // Stores into the alloca are only live if the alloca is live.
+        StoreInst *SI =3D cast<StoreInst>(I);
+        // We can eliminate atomic stores, but not volatile.
+        if (SI->isVolatile())
+          return 0;
+        // The store is only trivially safe if the poniter is the destinat=
ion
+        // as opposed to the value. We're conservative here and don't chec=
k for
+        // the case where we store the address of a dead alloca into a dead
+        // alloca.
+        if (SI->getPointerOperand() !=3D PI)
+          return 0;
+        DeadStores.push_back(I);
+        continue;
+      }
+      }
+    }
+  } while (!Worklist.empty());
+
+  // The alloca is dead. Kill off all the stores to it, and then replace it
+  // with undef.
+  while (!DeadStores.empty())
+    IC.EraseInstFromFunction(*DeadStores.pop_back_val());
+  return IC.ReplaceInstUsesWith(AI, UndefValue::get(AI.getType()));
+}
+
 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
   // Ensure that the alloca array size argument has type intptr_t, so that
   // any casting is exposed early.
@@ -81,7 +147,10 @@
       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
   }
=20
-  return 0;
+  // Try to aggressively remove allocas which are only used for GEPs, life=
time
+  // markers, and stores. This happens when SROA iteratively promotes stor=
es
+  // out of the alloca, and we need to cleanup after it.
+  return removeDeadAlloca(*this, AI);
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineMulDivRem.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -256,22 +256,18 @@
   bool Changed =3D SimplifyAssociativeOrCommutative(I);
   Value *Op0 =3D I.getOperand(0), *Op1 =3D I.getOperand(1);
=20
-  // Simplify mul instructions with a constant RHS...
+  // Simplify mul instructions with a constant RHS.
   if (Constant *Op1C =3D dyn_cast<Constant>(Op1)) {
     if (ConstantFP *Op1F =3D dyn_cast<ConstantFP>(Op1C)) {
       // "In IEEE floating point, x*1 is not equivalent to x for nans.  Ho=
wever,
       // ANSI says we can drop signals, so we can do this anyway." (from G=
CC)
       if (Op1F->isExactlyValue(1.0))
         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'fmul double %X,=
 1.0'
-    } else if (Op1C->getType()->isVectorTy()) {
-      if (ConstantVector *Op1V =3D dyn_cast<ConstantVector>(Op1C)) {
-        // As above, vector X*splat(1.0) -> X in all defined cases.
-        if (Constant *Splat =3D Op1V->getSplatValue()) {
-          if (ConstantFP *F =3D dyn_cast<ConstantFP>(Splat))
-            if (F->isExactlyValue(1.0))
-              return ReplaceInstUsesWith(I, Op0);
-        }
-      }
+    } else if (ConstantDataVector *Op1V =3D dyn_cast<ConstantDataVector>(O=
p1C)) {
+      // As above, vector X*splat(1.0) -> X in all defined cases.
+      if (ConstantFP *F =3D dyn_cast_or_null<ConstantFP>(Op1V->getSplatVal=
ue()))
+        if (F->isExactlyValue(1.0))
+          return ReplaceInstUsesWith(I, Op0);
     }
=20
     // Try to fold constant mul into select arguments.
@@ -441,19 +437,23 @@
   // Handle the integer div common cases
   if (Instruction *Common =3D commonIDivTransforms(I))
     return Common;
-
-  if (ConstantInt *C =3D dyn_cast<ConstantInt>(Op1)) {
+ =20
+  {=20
     // X udiv 2^C -> X >> C
     // Check to see if this is an unsigned division with an exact power of=
 2,
     // if so, convert to a right shift.
-    if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
+    const APInt *C;
+    if (match(Op1, m_Power2(C))) {
       BinaryOperator *LShr =3D
-        BinaryOperator::CreateLShr(Op0,=20
-            ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
+      BinaryOperator::CreateLShr(Op0,=20
+                                 ConstantInt::get(Op0->getType(),=20
+                                                  C->logBase2()));
       if (I.isExact()) LShr->setIsExact();
       return LShr;
     }
+  }
=20
+  if (ConstantInt *C =3D dyn_cast<ConstantInt>(Op1)) {
     // X udiv C, where C >=3D signbit
     if (C->getValue().isNegative()) {
       Value *IC =3D Builder->CreateICmpULT(Op0, C);
@@ -684,28 +684,36 @@
   }
=20
   // If it's a constant vector, flip any negative values positive.
-  if (ConstantVector *RHSV =3D dyn_cast<ConstantVector>(Op1)) {
-    unsigned VWidth =3D RHSV->getNumOperands();
+  if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
+    Constant *C =3D cast<Constant>(Op1);
+    unsigned VWidth =3D C->getType()->getVectorNumElements();
=20
     bool hasNegative =3D false;
-    for (unsigned i =3D 0; !hasNegative && i !=3D VWidth; ++i)
-      if (ConstantInt *RHS =3D dyn_cast<ConstantInt>(RHSV->getOperand(i)))
+    bool hasMissing =3D false;
+    for (unsigned i =3D 0; i !=3D VWidth; ++i) {
+      Constant *Elt =3D C->getAggregateElement(i);
+      if (Elt =3D=3D 0) {
+        hasMissing =3D true;
+        break;
+      }
+
+      if (ConstantInt *RHS =3D dyn_cast<ConstantInt>(Elt))
         if (RHS->isNegative())
           hasNegative =3D true;
+    }
=20
-    if (hasNegative) {
-      std::vector<Constant *> Elts(VWidth);
+    if (hasNegative && !hasMissing) {
+      SmallVector<Constant *, 16> Elts(VWidth);
       for (unsigned i =3D 0; i !=3D VWidth; ++i) {
-        if (ConstantInt *RHS =3D dyn_cast<ConstantInt>(RHSV->getOperand(i)=
)) {
+        Elts[i] =3D C->getAggregateElement(i);  // Handle undef, etc.
+        if (ConstantInt *RHS =3D dyn_cast<ConstantInt>(Elts[i])) {
           if (RHS->isNegative())
             Elts[i] =3D cast<ConstantInt>(ConstantExpr::getNeg(RHS));
-          else
-            Elts[i] =3D RHS;
         }
       }
=20
       Constant *NewRHSV =3D ConstantVector::get(Elts);
-      if (NewRHSV !=3D RHSV) {
+      if (NewRHSV !=3D C) {  // Don't loop on -MININT
         Worklist.AddValue(I.getOperand(1));
         I.setOperand(1, NewRHSV);
         return &I;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineSelect.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -184,7 +184,6 @@
       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
   }
   llvm_unreachable("Shouldn't get here");
-  return 0;
 }
=20
 static bool isSelect01(Constant *C1, Constant *C2) {
@@ -282,7 +281,8 @@
 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
 /// replaced with RepOp.
 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
-                                     const TargetData *TD) {
+                                     const TargetData *TD,
+                                     const TargetLibraryInfo *TLI) {
   // Trivial replacement.
   if (V =3D=3D Op)
     return RepOp;
@@ -294,17 +294,19 @@
   // If this is a binary operator, try to simplify it with the replaced op.
   if (BinaryOperator *B =3D dyn_cast<BinaryOperator>(I)) {
     if (B->getOperand(0) =3D=3D Op)
-      return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD);
+      return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TL=
I);
     if (B->getOperand(1) =3D=3D Op)
-      return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD);
+      return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TL=
I);
   }
=20
   // Same for CmpInsts.
   if (CmpInst *C =3D dyn_cast<CmpInst>(I)) {
     if (C->getOperand(0) =3D=3D Op)
-      return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), T=
D);
+      return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), T=
D,
+                             TLI);
     if (C->getOperand(1) =3D=3D Op)
-      return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, T=
D);
+      return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, T=
D,
+                             TLI);
   }
=20
   // TODO: We could hand off more cases to instsimplify here.
@@ -330,7 +332,7 @@
           return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
=20
       return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
-                                      ConstOps, TD);
+                                      ConstOps, TD, TLI);
     }
   }
=20
@@ -479,18 +481,18 @@
   // arms of the select. See if substituting this value into the arm and
   // simplifying the result yields the same value as the other arm.
   if (Pred =3D=3D ICmpInst::ICMP_EQ) {
-    if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD) =3D=3D TrueVa=
l ||
-        SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD) =3D=3D TrueVa=
l)
+    if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) =3D=3D T=
rueVal ||
+        SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) =3D=3D T=
rueVal)
       return ReplaceInstUsesWith(SI, FalseVal);
-    if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD) =3D=3D FalseVa=
l ||
-        SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD) =3D=3D FalseVa=
l)
+    if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) =3D=3D Fa=
lseVal ||
+        SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) =3D=3D Fa=
lseVal)
       return ReplaceInstUsesWith(SI, FalseVal);
   } else if (Pred =3D=3D ICmpInst::ICMP_NE) {
-    if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD) =3D=3D FalseVa=
l ||
-        SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD) =3D=3D FalseVa=
l)
+    if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, TD, TLI) =3D=3D Fa=
lseVal ||
+        SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, TD, TLI) =3D=3D Fa=
lseVal)
       return ReplaceInstUsesWith(SI, TrueVal);
-    if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD) =3D=3D TrueVa=
l ||
-        SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD) =3D=3D TrueVa=
l)
+    if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, TD, TLI) =3D=3D T=
rueVal ||
+        SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, TD, TLI) =3D=3D T=
rueVal)
       return ReplaceInstUsesWith(SI, TrueVal);
   }
=20
@@ -679,6 +681,13 @@
       return BinaryOperator::CreateOr(CondVal, FalseVal);
     else if (CondVal =3D=3D FalseVal)
       return BinaryOperator::CreateAnd(CondVal, TrueVal);
+
+    // select a, ~a, b -> (~a)&b
+    // select a, b, ~a -> (~a)|b
+    if (match(TrueVal, m_Not(m_Specific(CondVal))))
+      return BinaryOperator::CreateAnd(TrueVal, FalseVal);
+    else if (match(FalseVal, m_Not(m_Specific(CondVal))))
+      return BinaryOperator::CreateOr(TrueVal, FalseVal);
   }
=20
   // Selecting between two integer constants?
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineShifts.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -190,7 +190,8 @@
       V =3D IC.Builder->CreateLShr(C, NumBits);
     // If we got a constantexpr back, try to simplify it with TD info.
     if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(V))
-      V =3D ConstantFoldConstantExpression(CE, IC.getTargetData());
+      V =3D ConstantFoldConstantExpression(CE, IC.getTargetData(),
+                                         IC.getTargetLibraryInfo());
     return V;
   }
  =20
@@ -198,7 +199,7 @@
   IC.Worklist.Add(I);
=20
   switch (I->getOpcode()) {
-  default: assert(0 && "Inconsistency with CanEvaluateShifted");
+  default: llvm_unreachable("Inconsistency with CanEvaluateShifted");
   case Instruction::And:
   case Instruction::Or:
   case Instruction::Xor:
@@ -535,12 +536,11 @@
     if (ShiftAmt1 =3D=3D 0) return 0;  // Will be simplified in the future.
     Value *X =3D ShiftOp->getOperand(0);
    =20
-    uint32_t AmtSum =3D ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
-   =20
     IntegerType *Ty =3D cast<IntegerType>(I.getType());
    =20
     // Check for (X << c1) << c2  and  (X >> c1) >> c2
     if (I.getOpcode() =3D=3D ShiftOp->getOpcode()) {
+      uint32_t AmtSum =3D ShiftAmt1+ShiftAmt2;   // Fold into one big shif=
t.
       // If this is oversized composite shift, then unsigned shifts get 0,=
 ashr
       // saturates.
       if (AmtSum >=3D TypeBits) {
@@ -576,7 +576,16 @@
           ShiftOp->getOpcode() !=3D Instruction::Shl) {
         assert(ShiftOp->getOpcode() =3D=3D Instruction::LShr ||
                ShiftOp->getOpcode() =3D=3D Instruction::AShr);
-        Value *Shift =3D Builder->CreateShl(X, ConstantInt::get(Ty, ShiftD=
iff));
+        ConstantInt *ShiftDiffCst =3D ConstantInt::get(Ty, ShiftDiff);
+        if (ShiftOp->isExact()) {
+          // (X >>?,exact C1) << C2 --> X << (C2-C1)
+          BinaryOperator *NewShl =3D BinaryOperator::Create(Instruction::S=
hl,
+                                                          X, ShiftDiffCst);
+          NewShl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
+          NewShl->setHasNoSignedWrap(I.hasNoSignedWrap());
+          return NewShl;
+        }
+        Value *Shift =3D Builder->CreateShl(X, ShiftDiffCst);
        =20
         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
         return BinaryOperator::CreateAnd(Shift,
@@ -586,15 +595,34 @@
       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
       if (I.getOpcode() =3D=3D Instruction::LShr &&
           ShiftOp->getOpcode() =3D=3D Instruction::Shl) {
-        assert(ShiftOp->getOpcode() =3D=3D Instruction::Shl);
-        Value *Shift =3D Builder->CreateLShr(X, ConstantInt::get(Ty, Shift=
Diff));
+        ConstantInt *ShiftDiffCst =3D ConstantInt::get(Ty, ShiftDiff);
+        // (X <<nuw C1) >>u C2 --> X >>u (C2-C1)
+        if (ShiftOp->hasNoUnsignedWrap()) {
+          BinaryOperator *NewLShr =3D BinaryOperator::Create(Instruction::=
LShr,
+                                                           X, ShiftDiffCst=
);
+          NewLShr->setIsExact(I.isExact());
+          return NewLShr;
+        }
+        Value *Shift =3D Builder->CreateLShr(X, ShiftDiffCst);
        =20
         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
         return BinaryOperator::CreateAnd(Shift,
                                          ConstantInt::get(I.getContext(),M=
ask));
       }
-     =20
-      // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
+
+      // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. Ho=
wever,
+      // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bi=
ts.
+      if (I.getOpcode() =3D=3D Instruction::AShr &&
+          ShiftOp->getOpcode() =3D=3D Instruction::Shl) {
+        if (ShiftOp->hasNoSignedWrap()) {
+          // (X <<nsw C1) >>s C2 --> X >>s (C2-C1)
+          ConstantInt *ShiftDiffCst =3D ConstantInt::get(Ty, ShiftDiff);
+          BinaryOperator *NewAShr =3D BinaryOperator::Create(Instruction::=
AShr,
+                                                           X, ShiftDiffCst=
);
+          NewAShr->setIsExact(I.isExact());
+          return NewAShr;
+        }
+      }
     } else {
       assert(ShiftAmt2 < ShiftAmt1);
       uint32_t ShiftDiff =3D ShiftAmt1-ShiftAmt2;
@@ -602,9 +630,16 @@
       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
       if (I.getOpcode() =3D=3D Instruction::Shl &&
           ShiftOp->getOpcode() !=3D Instruction::Shl) {
-        Value *Shift =3D Builder->CreateBinOp(ShiftOp->getOpcode(), X,
-                                            ConstantInt::get(Ty, ShiftDiff=
));
-       =20
+        ConstantInt *ShiftDiffCst =3D ConstantInt::get(Ty, ShiftDiff);
+        if (ShiftOp->isExact()) {
+          // (X >>?exact C1) << C2 --> X >>?exact (C1-C2)
+          BinaryOperator *NewShr =3D BinaryOperator::Create(ShiftOp->getOp=
code(),
+                                                          X, ShiftDiffCst);
+          NewShr->setIsExact(true);
+          return NewShr;
+        }
+        Value *Shift =3D Builder->CreateBinOp(ShiftOp->getOpcode(),
+                                            X, ShiftDiffCst);
         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
         return BinaryOperator::CreateAnd(Shift,
                                          ConstantInt::get(I.getContext(),M=
ask));
@@ -613,14 +648,34 @@
       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
       if (I.getOpcode() =3D=3D Instruction::LShr &&
           ShiftOp->getOpcode() =3D=3D Instruction::Shl) {
-        Value *Shift =3D Builder->CreateShl(X, ConstantInt::get(Ty, ShiftD=
iff));
+        ConstantInt *ShiftDiffCst =3D ConstantInt::get(Ty, ShiftDiff);
+        if (ShiftOp->hasNoUnsignedWrap()) {
+          // (X <<nuw C1) >>u C2 --> X <<nuw (C1-C2)
+          BinaryOperator *NewShl =3D BinaryOperator::Create(Instruction::S=
hl,
+                                                          X, ShiftDiffCst);
+          NewShl->setHasNoUnsignedWrap(true);
+          return NewShl;
+        }
+        Value *Shift =3D Builder->CreateShl(X, ShiftDiffCst);
        =20
         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
         return BinaryOperator::CreateAnd(Shift,
                                          ConstantInt::get(I.getContext(),M=
ask));
       }
      =20
-      // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
+      // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in. Ho=
wever,
+      // we can handle (X <<nsw C1) >>s C2 since it only shifts in sign bi=
ts.
+      if (I.getOpcode() =3D=3D Instruction::AShr &&
+          ShiftOp->getOpcode() =3D=3D Instruction::Shl) {
+        if (ShiftOp->hasNoSignedWrap()) {
+          // (X <<nsw C1) >>s C2 --> X <<nsw (C1-C2)
+          ConstantInt *ShiftDiffCst =3D ConstantInt::get(Ty, ShiftDiff);
+          BinaryOperator *NewShl =3D BinaryOperator::Create(Instruction::S=
hl,
+                                                          X, ShiftDiffCst);
+          NewShl->setHasNoSignedWrap(true);
+          return NewShl;
+        }
+      }
     }
   }
   return 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineSimplifyDemanded.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDeman=
ded.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineSimplifyDeman=
ded.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -142,7 +142,7 @@
=20
   Instruction *I =3D dyn_cast<Instruction>(V);
   if (!I) {
-    ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
+    ComputeMaskedBits(V, KnownZero, KnownOne, Depth);
     return 0;        // Only analyze instructions.
   }
=20
@@ -156,10 +156,8 @@
     // this instruction has a simpler value in that context.
     if (I->getOpcode() =3D=3D Instruction::And) {
       // If either the LHS or the RHS are Zero, the result is zero.
-      ComputeMaskedBits(I->getOperand(1), DemandedMask,
-                        RHSKnownZero, RHSKnownOne, Depth+1);
-      ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
-                        LHSKnownZero, LHSKnownOne, Depth+1);
+      ComputeMaskedBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth=
+1);
+      ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth=
+1);
      =20
       // If all of the demanded bits are known 1 on one side, return the o=
ther.
       // These bits cannot contribute to the result of the 'and' in this
@@ -180,10 +178,8 @@
       // only bits from X or Y are demanded.
      =20
       // If either the LHS or the RHS are One, the result is One.
-      ComputeMaskedBits(I->getOperand(1), DemandedMask,=20
-                        RHSKnownZero, RHSKnownOne, Depth+1);
-      ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,=20
-                        LHSKnownZero, LHSKnownOne, Depth+1);
+      ComputeMaskedBits(I->getOperand(1), RHSKnownZero, RHSKnownOne, Depth=
+1);
+      ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth=
+1);
      =20
       // If all of the demanded bits are known zero on one side, return the
       // other.  These bits cannot contribute to the result of the 'or' in=
 this
@@ -206,7 +202,7 @@
     }
    =20
     // Compute the KnownZero/KnownOne bits to simplify things downstream.
-    ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
+    ComputeMaskedBits(I, KnownZero, KnownOne, Depth);
     return 0;
   }
  =20
@@ -219,7 +215,7 @@
  =20
   switch (I->getOpcode()) {
   default:
-    ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
+    ComputeMaskedBits(I, KnownZero, KnownOne, Depth);
     break;
   case Instruction::And:
     // If either the LHS or the RHS are Zero, the result is zero.
@@ -567,9 +563,20 @@
                                LHSKnownZero, LHSKnownOne, Depth+1))
         return I;
     }
+
     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
     // the known zeros and ones.
-    ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
+    ComputeMaskedBits(V, KnownZero, KnownOne, Depth);
+
+    // Turn this into a xor if LHS is 2^n-1 and the remaining bits are kno=
wn
+    // zero.
+    if (ConstantInt *C0 =3D dyn_cast<ConstantInt>(I->getOperand(0))) {
+      APInt I0 =3D C0->getValue();
+      if ((I0 + 1).isPowerOf2() && (I0 | KnownZero).isAllOnesValue()) {
+        Instruction *Xor =3D BinaryOperator::CreateXor(I->getOperand(1), C=
0);
+        return InsertNewInstWith(Xor, *I);
+      }
+    }
     break;
   case Instruction::Shl:
     if (ConstantInt *SA =3D dyn_cast<ConstantInt>(I->getOperand(1))) {
@@ -671,8 +678,9 @@
       if (BitWidth <=3D ShiftAmt || KnownZero[BitWidth-ShiftAmt-1] ||=20
           (HighBits & ~DemandedMask) =3D=3D HighBits) {
         // Perform the logical shift right.
-        Instruction *NewVal =3D BinaryOperator::CreateLShr(
-                          I->getOperand(0), SA, I->getName());
+        BinaryOperator *NewVal =3D BinaryOperator::CreateLShr(I->getOperan=
d(0),
+                                                            SA, I->getName=
());
+        NewVal->setIsExact(cast<BinaryOperator>(I)->isExact());
         return InsertNewInstWith(NewVal, *I);
       } else if ((KnownOne & SignBit) !=3D 0) { // New bits are known one.
         KnownOne |=3D HighBits;
@@ -717,10 +725,8 @@
     // The sign bit is the LHS's sign bit, except when the result of the
     // remainder is zero.
     if (DemandedMask.isNegative() && KnownZero.isNonNegative()) {
-      APInt Mask2 =3D APInt::getSignBit(BitWidth);
       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
-      ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne,
-                        Depth+1);
+      ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth=
+1);
       // If it's known zero, our sign bit is also zero.
       if (LHSKnownZero.isNegative())
         KnownZero |=3D LHSKnownZero;
@@ -783,7 +789,7 @@
         return 0;
       }
     }
-    ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
+    ComputeMaskedBits(V, KnownZero, KnownOne, Depth);
     break;
   }
  =20
@@ -822,46 +828,39 @@
   }
=20
   UndefElts =3D 0;
-  if (ConstantVector *CV =3D dyn_cast<ConstantVector>(V)) {
-    Type *EltTy =3D cast<VectorType>(V->getType())->getElementType();
-    Constant *Undef =3D UndefValue::get(EltTy);
-
-    std::vector<Constant*> Elts;
-    for (unsigned i =3D 0; i !=3D VWidth; ++i)
-      if (!DemandedElts[i]) {   // If not demanded, set to undef.
-        Elts.push_back(Undef);
-        UndefElts.setBit(i);
-      } else if (isa<UndefValue>(CV->getOperand(i))) {   // Already undef.
-        Elts.push_back(Undef);
-        UndefElts.setBit(i);
-      } else {                               // Otherwise, defined.
-        Elts.push_back(CV->getOperand(i));
-      }
-
-    // If we changed the constant, return it.
-    Constant *NewCP =3D ConstantVector::get(Elts);
-    return NewCP !=3D CV ? NewCP : 0;
-  }
  =20
-  if (isa<ConstantAggregateZero>(V)) {
-    // Simplify the CAZ to a ConstantVector where the non-demanded element=
s are
-    // set to undef.
-   =20
+  // Handle ConstantAggregateZero, ConstantVector, ConstantDataSequential.
+  if (Constant *C =3D dyn_cast<Constant>(V)) {
     // Check if this is identity. If so, return 0 since we are not simplif=
ying
     // anything.
     if (DemandedElts.isAllOnesValue())
       return 0;
+
+    Type *EltTy =3D cast<VectorType>(V->getType())->getElementType();
+    Constant *Undef =3D UndefValue::get(EltTy);
    =20
-    Type *EltTy =3D cast<VectorType>(V->getType())->getElementType();
-    Constant *Zero =3D Constant::getNullValue(EltTy);
-    Constant *Undef =3D UndefValue::get(EltTy);
-    std::vector<Constant*> Elts;
+    SmallVector<Constant*, 16> Elts;
     for (unsigned i =3D 0; i !=3D VWidth; ++i) {
-      Constant *Elt =3D DemandedElts[i] ? Zero : Undef;
-      Elts.push_back(Elt);
+      if (!DemandedElts[i]) {   // If not demanded, set to undef.
+        Elts.push_back(Undef);
+        UndefElts.setBit(i);
+        continue;
+      }
+     =20
+      Constant *Elt =3D C->getAggregateElement(i);
+      if (Elt =3D=3D 0) return 0;
+     =20
+      if (isa<UndefValue>(Elt)) {   // Already undef.
+        Elts.push_back(Undef);
+        UndefElts.setBit(i);
+      } else {                               // Otherwise, defined.
+        Elts.push_back(Elt);
+      }
     }
-    UndefElts =3D DemandedElts ^ EltMask;
-    return ConstantVector::get(Elts);
+   =20
+    // If we changed the constant, return it.
+    Constant *NewCV =3D ConstantVector::get(Elts);
+    return NewCV !=3D C ? NewCV : 0;
   }
  =20
   // Limit search depth.
@@ -977,7 +976,7 @@
=20
     if (NewUndefElts) {
       // Add additional discovered undefs.
-      std::vector<Constant*> Elts;
+      SmallVector<Constant*, 16> Elts;
       for (unsigned i =3D 0; i < VWidth; ++i) {
         if (UndefElts[i])
           Elts.push_back(UndefValue::get(Type::getInt32Ty(I->getContext())=
));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineVectorOps.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -16,16 +16,16 @@
 using namespace llvm;
=20
 /// CheapToScalarize - Return true if the value is cheaper to scalarize th=
an it
-/// is to leave as a vector operation.
+/// is to leave as a vector operation.  isConstant indicates whether we're
+/// extracting one known element.  If false we're extracting a variable in=
dex.
 static bool CheapToScalarize(Value *V, bool isConstant) {
-  if (isa<ConstantAggregateZero>(V))
-    return true;
-  if (ConstantVector *C =3D dyn_cast<ConstantVector>(V)) {
+  if (Constant *C =3D dyn_cast<Constant>(V)) {
     if (isConstant) return true;
-    // If all elts are the same, we can extract.
-    Constant *Op0 =3D C->getOperand(0);
-    for (unsigned i =3D 1; i < C->getNumOperands(); ++i)
-      if (C->getOperand(i) !=3D Op0)
+
+    // If all elts are the same, we can extract it and use any of the valu=
es.
+    Constant *Op0 =3D C->getAggregateElement(0U);
+    for (unsigned i =3D 1, e =3D V->getType()->getVectorNumElements(); i !=
=3D e; ++i)
+      if (C->getAggregateElement(i) !=3D Op0)
         return false;
     return true;
   }
@@ -53,41 +53,18 @@
   return false;
 }
=20
-/// getShuffleMask - Read and decode a shufflevector mask.
-/// Turn undef elements into negative values.
-static std::vector<int> getShuffleMask(const ShuffleVectorInst *SVI) {
-  unsigned NElts =3D SVI->getType()->getNumElements();
-  if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
-    return std::vector<int>(NElts, 0);
-  if (isa<UndefValue>(SVI->getOperand(2)))
-    return std::vector<int>(NElts, -1);
-
-  std::vector<int> Result;
-  const ConstantVector *CP =3D cast<ConstantVector>(SVI->getOperand(2));
-  for (User::const_op_iterator i =3D CP->op_begin(), e =3D CP->op_end(); i=
!=3De; ++i)
-    if (isa<UndefValue>(*i))
-      Result.push_back(-1);  // undef
-    else
-      Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
-  return Result;
-}
-
 /// FindScalarElement - Given a vector and an element number, see if the s=
calar
 /// value is already around as a register, for example if it were inserted=
 then
 /// extracted from the vector.
 static Value *FindScalarElement(Value *V, unsigned EltNo) {
   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
-  VectorType *PTy =3D cast<VectorType>(V->getType());
-  unsigned Width =3D PTy->getNumElements();
+  VectorType *VTy =3D cast<VectorType>(V->getType());
+  unsigned Width =3D VTy->getNumElements();
   if (EltNo >=3D Width)  // Out of range access.
-    return UndefValue::get(PTy->getElementType());
+    return UndefValue::get(VTy->getElementType());
=20
-  if (isa<UndefValue>(V))
-    return UndefValue::get(PTy->getElementType());
-  if (isa<ConstantAggregateZero>(V))
-    return Constant::getNullValue(PTy->getElementType());
-  if (ConstantVector *CP =3D dyn_cast<ConstantVector>(V))
-    return CP->getOperand(EltNo);
+  if (Constant *C =3D dyn_cast<Constant>(V))
+    return C->getAggregateElement(EltNo);
=20
   if (InsertElementInst *III =3D dyn_cast<InsertElementInst>(V)) {
     // If this is an insert to a variable element, we don't know what it i=
s.
@@ -106,11 +83,10 @@
   }
=20
   if (ShuffleVectorInst *SVI =3D dyn_cast<ShuffleVectorInst>(V)) {
-    unsigned LHSWidth =3D
-      cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
-    int InEl =3D getShuffleMask(SVI)[EltNo];
+    unsigned LHSWidth =3D SVI->getOperand(0)->getType()->getVectorNumEleme=
nts();
+    int InEl =3D SVI->getMaskValue(EltNo);
     if (InEl < 0)
-      return UndefValue::get(PTy->getElementType());
+      return UndefValue::get(VTy->getElementType());
     if (InEl < (int)LHSWidth)
       return FindScalarElement(SVI->getOperand(0), InEl);
     return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
@@ -121,27 +97,11 @@
 }
=20
 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI)=
 {
-  // If vector val is undef, replace extract with scalar undef.
-  if (isa<UndefValue>(EI.getOperand(0)))
-    return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
-
-  // If vector val is constant 0, replace extract with scalar 0.
-  if (isa<ConstantAggregateZero>(EI.getOperand(0)))
-    return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
-
-  if (ConstantVector *C =3D dyn_cast<ConstantVector>(EI.getOperand(0))) {
-    // If vector val is constant with all elements the same, replace EI wi=
th
-    // that element. When the elements are not identical, we cannot replac=
e yet
-    // (we do that below, but only when the index is constant).
-    Constant *op0 =3D C->getOperand(0);
-    for (unsigned i =3D 1; i !=3D C->getNumOperands(); ++i)
-      if (C->getOperand(i) !=3D op0) {
-        op0 =3D 0;
-        break;
-      }
-    if (op0)
-      return ReplaceInstUsesWith(EI, op0);
-  }
+  // If vector val is constant with all elements the same, replace EI with
+  // that element.  We handle a known element # below.
+  if (Constant *C =3D dyn_cast<Constant>(EI.getOperand(0)))
+    if (CheapToScalarize(C, false))
+      return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
=20
   // If extracting a specified index from the vector, see if we can recurs=
ively
   // find a previously computed scalar that was inserted into the vector.
@@ -175,8 +135,7 @@
     // the same number of elements, see if we can find the source element =
from
     // it.  In this case, we will end up needing to bitcast the scalars.
     if (BitCastInst *BCI =3D dyn_cast<BitCastInst>(EI.getOperand(0))) {
-      if (VectorType *VT =3D
-          dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
+      if (VectorType *VT =3D dyn_cast<VectorType>(BCI->getOperand(0)->getT=
ype()))
         if (VT->getNumElements() =3D=3D VectorWidth)
           if (Value *Elt =3D FindScalarElement(BCI->getOperand(0), IndexVa=
l))
             return new BitCastInst(Elt, EI.getType());
@@ -212,10 +171,10 @@
       // If this is extracting an element from a shufflevector, figure out=
 where
       // it came from and extract from the appropriate input element inste=
ad.
       if (ConstantInt *Elt =3D dyn_cast<ConstantInt>(EI.getOperand(1))) {
-        int SrcIdx =3D getShuffleMask(SVI)[Elt->getZExtValue()];
+        int SrcIdx =3D SVI->getMaskValue(Elt->getZExtValue());
         Value *Src;
         unsigned LHSWidth =3D
-          cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements(=
);
+          SVI->getOperand(0)->getType()->getVectorNumElements();
=20
         if (SrcIdx < 0)
           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
@@ -248,7 +207,7 @@
 /// elements from either LHS or RHS, return the shuffle mask and true.
 /// Otherwise, return false.
 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
-                                         std::vector<Constant*> &Mask) {
+                                         SmallVectorImpl<Constant*> &Mask)=
 {
   assert(V->getType() =3D=3D LHS->getType() && V->getType() =3D=3D RHS->ge=
tType() &&
          "Invalid CollectSingleShuffleElements");
   unsigned NumElts =3D cast<VectorType>(V->getType())->getNumElements();
@@ -325,7 +284,7 @@
 /// CollectShuffleElements - We are building a shuffle of V, using RHS as =
the
 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle m=
ask
 /// that computes V and the LHS value of the shuffle.
-static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mas=
k,
+static Value *CollectShuffleElements(Value *V, SmallVectorImpl<Constant*> =
&Mask,
                                      Value *&RHS) {
   assert(V->getType()->isVectorTy() &&
          (RHS =3D=3D 0 || V->getType() =3D=3D RHS->getType()) &&
@@ -335,10 +294,14 @@
   if (isa<UndefValue>(V)) {
     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())=
));
     return V;
-  } else if (isa<ConstantAggregateZero>(V)) {
+  }
+ =20
+  if (isa<ConstantAggregateZero>(V)) {
     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()=
),0));
     return V;
-  } else if (InsertElementInst *IEI =3D dyn_cast<InsertElementInst>(V)) {
+  }
+ =20
+  if (InsertElementInst *IEI =3D dyn_cast<InsertElementInst>(V)) {
     // If this is an insert of an extract from some other vector, include =
it.
     Value *VecOp    =3D IEI->getOperand(0);
     Value *ScalarOp =3D IEI->getOperand(1);
@@ -421,7 +384,7 @@
       // If this insertelement isn't used by some other insertelement, tur=
n it
       // (and any insertelements it points to), into one big shuffle.
       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
-        std::vector<Constant*> Mask;
+        SmallVector<Constant*, 16> Mask;
         Value *RHS =3D 0;
         Value *LHS =3D CollectShuffleElements(&IE, Mask, RHS);
         if (RHS =3D=3D 0) RHS =3D UndefValue::get(LHS->getType());
@@ -447,7 +410,7 @@
 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
   Value *LHS =3D SVI.getOperand(0);
   Value *RHS =3D SVI.getOperand(1);
-  std::vector<int> Mask =3D getShuffleMask(&SVI);
+  SmallVector<int, 16> Mask =3D SVI.getShuffleMask();
=20
   bool MadeChange =3D false;
=20
@@ -457,9 +420,6 @@
=20
   unsigned VWidth =3D cast<VectorType>(SVI.getType())->getNumElements();
=20
-  if (VWidth !=3D cast<VectorType>(LHS->getType())->getNumElements())
-    return 0;
-
   APInt UndefElts(VWidth, 0);
   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
   if (Value *V =3D SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefE=
lts)) {
@@ -470,29 +430,34 @@
     MadeChange =3D true;
   }
=20
+  unsigned LHSWidth =3D cast<VectorType>(LHS->getType())->getNumElements();
+
   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
   if (LHS =3D=3D RHS || isa<UndefValue>(LHS)) {
     if (isa<UndefValue>(LHS) && LHS =3D=3D RHS) {
       // shuffle(undef,undef,mask) -> undef.
-      return ReplaceInstUsesWith(SVI, LHS);
+      Value* result =3D (VWidth =3D=3D LHSWidth)
+                      ? LHS : UndefValue::get(SVI.getType());
+      return ReplaceInstUsesWith(SVI, result);
     }
=20
     // Remap any references to RHS to use LHS.
-    std::vector<Constant*> Elts;
-    for (unsigned i =3D 0, e =3D Mask.size(); i !=3D e; ++i) {
-      if (Mask[i] < 0)
+    SmallVector<Constant*, 16> Elts;
+    for (unsigned i =3D 0, e =3D LHSWidth; i !=3D VWidth; ++i) {
+      if (Mask[i] < 0) {
         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext()))=
);
-      else {
-        if ((Mask[i] >=3D (int)e && isa<UndefValue>(RHS)) ||
-            (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
-          Mask[i] =3D -1;     // Turn into undef.
-          Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext()=
)));
-        } else {
-          Mask[i] =3D Mask[i] % e;  // Force to LHS.
-          Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext(=
)),
-                                          Mask[i]));
-        }
+        continue;
+      }
+
+      if ((Mask[i] >=3D (int)e && isa<UndefValue>(RHS)) ||
+          (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
+        Mask[i] =3D -1;     // Turn into undef.
+        Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext()))=
);
+      } else {
+        Mask[i] =3D Mask[i] % e;  // Force to LHS.
+        Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
+                                        Mask[i]));
       }
     }
     SVI.setOperand(0, SVI.getOperand(1));
@@ -503,72 +468,204 @@
     MadeChange =3D true;
   }
=20
-  // Analyze the shuffle, are the LHS or RHS and identity shuffles?
-  bool isLHSID =3D true, isRHSID =3D true;
+  if (VWidth =3D=3D LHSWidth) {
+    // Analyze the shuffle, are the LHS or RHS and identity shuffles?
+    bool isLHSID =3D true, isRHSID =3D true;
=20
-  for (unsigned i =3D 0, e =3D Mask.size(); i !=3D e; ++i) {
-    if (Mask[i] < 0) continue;  // Ignore undef values.
-    // Is this an identity shuffle of the LHS value?
-    isLHSID &=3D (Mask[i] =3D=3D (int)i);
+    for (unsigned i =3D 0, e =3D Mask.size(); i !=3D e; ++i) {
+      if (Mask[i] < 0) continue;  // Ignore undef values.
+      // Is this an identity shuffle of the LHS value?
+      isLHSID &=3D (Mask[i] =3D=3D (int)i);
=20
-    // Is this an identity shuffle of the RHS value?
-    isRHSID &=3D (Mask[i]-e =3D=3D i);
+      // Is this an identity shuffle of the RHS value?
+      isRHSID &=3D (Mask[i]-e =3D=3D i);
+    }
+
+    // Eliminate identity shuffles.
+    if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
+    if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
   }
=20
-  // Eliminate identity shuffles.
-  if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
-  if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
-
   // If the LHS is a shufflevector itself, see if we can combine it with t=
his
-  // one without producing an unusual shuffle.  Here we are really conserv=
ative:
+  // one without producing an unusual shuffle.
+  // Cases that might be simplified:
+  // 1.
+  // x1=3Dshuffle(v1,v2,mask1)
+  //  x=3Dshuffle(x1,undef,mask)
+  //        =3D=3D>
+  //  x=3Dshuffle(v1,undef,newMask)
+  // newMask[i] =3D (mask[i] < x1.size()) ? mask1[mask[i]] : -1
+  // 2.
+  // x1=3Dshuffle(v1,undef,mask1)
+  //  x=3Dshuffle(x1,x2,mask)
+  // where v1.size() =3D=3D mask1.size()
+  //        =3D=3D>
+  //  x=3Dshuffle(v1,x2,newMask)
+  // newMask[i] =3D (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
+  // 3.
+  // x2=3Dshuffle(v2,undef,mask2)
+  //  x=3Dshuffle(x1,x2,mask)
+  // where v2.size() =3D=3D mask2.size()
+  //        =3D=3D>
+  //  x=3Dshuffle(x1,v2,newMask)
+  // newMask[i] =3D (mask[i] < x1.size())
+  //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
+  // 4.
+  // x1=3Dshuffle(v1,undef,mask1)
+  // x2=3Dshuffle(v2,undef,mask2)
+  //  x=3Dshuffle(x1,x2,mask)
+  // where v1.size() =3D=3D v2.size()
+  //        =3D=3D>
+  //  x=3Dshuffle(v1,v2,newMask)
+  // newMask[i] =3D (mask[i] < x1.size())
+  //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
+  //
+  // Here we are really conservative:
   // we are absolutely afraid of producing a shuffle mask not in the input
   // program, because the code gen may not be smart enough to turn a merged
   // shuffle into two specific shuffles: it may produce worse code.  As su=
ch,
   // we only merge two shuffles if the result is either a splat or one of =
the
-  // two input shuffle masks.  In this case, merging the shuffles just rem=
oves
+  // input shuffle masks.  In this case, merging the shuffles just removes
   // one instruction, which we know is safe.  This is good for things like
-  // turning: (splat(splat)) -> splat.
-  if (ShuffleVectorInst *LHSSVI =3D dyn_cast<ShuffleVectorInst>(LHS)) {
+  // turning: (splat(splat)) -> splat, or
+  // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
+  ShuffleVectorInst* LHSShuffle =3D dyn_cast<ShuffleVectorInst>(LHS);
+  ShuffleVectorInst* RHSShuffle =3D dyn_cast<ShuffleVectorInst>(RHS);
+  if (LHSShuffle)
+    if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RH=
S))
+      LHSShuffle =3D NULL;
+  if (RHSShuffle)
+    if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
+      RHSShuffle =3D NULL;
+  if (!LHSShuffle && !RHSShuffle)
+    return MadeChange ? &SVI : 0;
+
+  Value* LHSOp0 =3D NULL;
+  Value* LHSOp1 =3D NULL;
+  Value* RHSOp0 =3D NULL;
+  unsigned LHSOp0Width =3D 0;
+  unsigned RHSOp0Width =3D 0;
+  if (LHSShuffle) {
+    LHSOp0 =3D LHSShuffle->getOperand(0);
+    LHSOp1 =3D LHSShuffle->getOperand(1);
+    LHSOp0Width =3D cast<VectorType>(LHSOp0->getType())->getNumElements();
+  }
+  if (RHSShuffle) {
+    RHSOp0 =3D RHSShuffle->getOperand(0);
+    RHSOp0Width =3D cast<VectorType>(RHSOp0->getType())->getNumElements();
+  }
+  Value* newLHS =3D LHS;
+  Value* newRHS =3D RHS;
+  if (LHSShuffle) {
+    // case 1
     if (isa<UndefValue>(RHS)) {
-      std::vector<int> LHSMask =3D getShuffleMask(LHSSVI);
+      newLHS =3D LHSOp0;
+      newRHS =3D LHSOp1;
+    }
+    // case 2 or 4
+    else if (LHSOp0Width =3D=3D LHSWidth) {
+      newLHS =3D LHSOp0;
+    }
+  }
+  // case 3 or 4
+  if (RHSShuffle && RHSOp0Width =3D=3D LHSWidth) {
+    newRHS =3D RHSOp0;
+  }
+  // case 4
+  if (LHSOp0 =3D=3D RHSOp0) {
+    newLHS =3D LHSOp0;
+    newRHS =3D NULL;
+  }
=20
-      if (LHSMask.size() =3D=3D Mask.size()) {
-        std::vector<int> NewMask;
-        bool isSplat =3D true;
-        int SplatElt =3D -1; // undef
-        for (unsigned i =3D 0, e =3D Mask.size(); i !=3D e; ++i) {
-          int MaskElt;
-          if (Mask[i] < 0 || Mask[i] >=3D (int)e)
-            MaskElt =3D -1; // undef
-          else
-            MaskElt =3D LHSMask[Mask[i]];
-          // Check if this could still be a splat.
-          if (MaskElt >=3D 0) {
-            if (SplatElt >=3D0 && SplatElt !=3D MaskElt)
-              isSplat =3D false;
-            SplatElt =3D MaskElt;
-          }
-          NewMask.push_back(MaskElt);
-        }
+  if (newLHS =3D=3D LHS && newRHS =3D=3D RHS)
+    return MadeChange ? &SVI : 0;
=20
-        // If the result mask is equal to the src shuffle or this
-        // shuffle mask, do the replacement.
-        if (isSplat || NewMask =3D=3D LHSMask || NewMask =3D=3D Mask) {
-          std::vector<Constant*> Elts;
-          Type *Int32Ty =3D Type::getInt32Ty(SVI.getContext());
-          for (unsigned i =3D 0, e =3D NewMask.size(); i !=3D e; ++i) {
-            if (NewMask[i] < 0) {
-              Elts.push_back(UndefValue::get(Int32Ty));
-            } else {
-              Elts.push_back(ConstantInt::get(Int32Ty, NewMask[i]));
-            }
-          }
-          return new ShuffleVectorInst(LHSSVI->getOperand(0),
-                                       LHSSVI->getOperand(1),
-                                       ConstantVector::get(Elts));
+  SmallVector<int, 16> LHSMask;
+  SmallVector<int, 16> RHSMask;
+  if (newLHS !=3D LHS)
+    LHSMask =3D LHSShuffle->getShuffleMask();
+  if (RHSShuffle && newRHS !=3D RHS)
+    RHSMask =3D RHSShuffle->getShuffleMask();
+
+  unsigned newLHSWidth =3D (newLHS !=3D LHS) ? LHSOp0Width : LHSWidth;
+  SmallVector<int, 16> newMask;
+  bool isSplat =3D true;
+  int SplatElt =3D -1;
+  // Create a new mask for the new ShuffleVectorInst so that the new
+  // ShuffleVectorInst is equivalent to the original one.
+  for (unsigned i =3D 0; i < VWidth; ++i) {
+    int eltMask;
+    if (Mask[i] =3D=3D -1) {
+      // This element is an undef value.
+      eltMask =3D -1;
+    } else if (Mask[i] < (int)LHSWidth) {
+      // This element is from left hand side vector operand.
+      //=20
+      // If LHS is going to be replaced (case 1, 2, or 4), calculate the
+      // new mask value for the element.
+      if (newLHS !=3D LHS) {
+        eltMask =3D LHSMask[Mask[i]];
+        // If the value selected is an undef value, explicitly specify it
+        // with a -1 mask value.
+        if (eltMask >=3D (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
+          eltMask =3D -1;
+      }
+      else
+        eltMask =3D Mask[i];
+    } else {
+      // This element is from right hand side vector operand
+      //
+      // If the value selected is an undef value, explicitly specify it
+      // with a -1 mask value. (case 1)
+      if (isa<UndefValue>(RHS))
+        eltMask =3D -1;
+      // If RHS is going to be replaced (case 3 or 4), calculate the
+      // new mask value for the element.
+      else if (newRHS !=3D RHS) {
+        eltMask =3D RHSMask[Mask[i]-LHSWidth];
+        // If the value selected is an undef value, explicitly specify it
+        // with a -1 mask value.
+        if (eltMask >=3D (int)RHSOp0Width) {
+          assert(isa<UndefValue>(RHSShuffle->getOperand(1))
+                 && "should have been check above");
+          eltMask =3D -1;
         }
       }
+      else
+        eltMask =3D Mask[i]-LHSWidth;
+
+      // If LHS's width is changed, shift the mask value accordingly.
+      // If newRHS =3D=3D NULL, i.e. LHSOp0 =3D=3D RHSOp0, we want to rema=
p any
+      // references to RHSOp0 to LHSOp0, so we don't need to shift the mas=
k.
+      if (eltMask >=3D 0 && newRHS !=3D NULL)
+        eltMask +=3D newLHSWidth;
     }
+
+    // Check if this could still be a splat.
+    if (eltMask >=3D 0) {
+      if (SplatElt >=3D 0 && SplatElt !=3D eltMask)
+        isSplat =3D false;
+      SplatElt =3D eltMask;
+    }
+
+    newMask.push_back(eltMask);
+  }
+
+  // If the result mask is equal to one of the original shuffle masks,
+  // or is a splat, do the replacement.
+  if (isSplat || newMask =3D=3D LHSMask || newMask =3D=3D RHSMask || newMa=
sk =3D=3D Mask) {
+    SmallVector<Constant*, 16> Elts;
+    Type *Int32Ty =3D Type::getInt32Ty(SVI.getContext());
+    for (unsigned i =3D 0, e =3D newMask.size(); i !=3D e; ++i) {
+      if (newMask[i] < 0) {
+        Elts.push_back(UndefValue::get(Int32Ty));
+      } else {
+        Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
+      }
+    }
+    if (newRHS =3D=3D NULL)
+      newRHS =3D UndefValue::get(newLHS->getType());
+    return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)=
);
   }
=20
   return MadeChange ? &SVI : 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstCombineWorklist.h
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineWorklist.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstCombineWorklist.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -55,9 +55,9 @@
     Worklist.reserve(NumEntries+16);
     WorklistMap.resize(NumEntries);
     DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n=
");
-    for (; NumEntries; --NumEntries) {
+    for (unsigned Idx =3D 0; NumEntries; --NumEntries) {
       Instruction *I =3D List[NumEntries-1];
-      WorklistMap.insert(std::make_pair(I, Worklist.size()));
+      WorklistMap.insert(std::make_pair(I, Idx++));
       Worklist.push_back(I);
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/InstC=
ombine/InstructionCombining.cpp
--- a/head/contrib/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -41,6 +41,7 @@
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/Debug.h"
@@ -74,11 +75,15 @@
 }
=20
 char InstCombiner::ID =3D 0;
-INITIALIZE_PASS(InstCombiner, "instcombine",
+INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
+                "Combine redundant instructions", false, false)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
+INITIALIZE_PASS_END(InstCombiner, "instcombine",
                 "Combine redundant instructions", false, false)
=20
 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
   AU.setPreservesCFG();
+  AU.addRequired<TargetLibraryInfo>();
 }
=20
=20
@@ -490,7 +495,7 @@
   if (ConstantInt *C =3D dyn_cast<ConstantInt>(V))
     return ConstantExpr::getNeg(C);
=20
-  if (ConstantVector *C =3D dyn_cast<ConstantVector>(V))
+  if (ConstantDataVector *C =3D dyn_cast<ConstantDataVector>(V))
     if (C->getType()->getElementType()->isIntegerTy())
       return ConstantExpr::getNeg(C);
=20
@@ -509,7 +514,7 @@
   if (ConstantFP *C =3D dyn_cast<ConstantFP>(V))
     return ConstantExpr::getFNeg(C);
=20
-  if (ConstantVector *C =3D dyn_cast<ConstantVector>(V))
+  if (ConstantDataVector *C =3D dyn_cast<ConstantDataVector>(V))
     if (C->getType()->getElementType()->isFloatingPointTy())
       return ConstantExpr::getFNeg(C);
=20
@@ -826,7 +831,8 @@
           MadeChange =3D true;
         }
=20
-      if ((*I)->getType() !=3D IntPtrTy) {
+      Type *IndexTy =3D (*I)->getType();
+      if (IndexTy !=3D IntPtrTy && !IndexTy->isVectorTy()) {
         // If we are using a wider index than needed for this platform, sh=
rink
         // it to what we need.  If narrower, sign-extend it to what we nee=
d.
         // This explicit cast can make subsequent optimizations more obvio=
us.
@@ -909,7 +915,12 @@
=20
   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
   Value *StrippedPtr =3D PtrOp->stripPointerCasts();
-  PointerType *StrippedPtrTy =3Dcast<PointerType>(StrippedPtr->getType());
+  PointerType *StrippedPtrTy =3D dyn_cast<PointerType>(StrippedPtr->getTyp=
e());
+
+  // We do not handle pointer-vector geps here.
+  if (!StrippedPtrTy)
+    return 0;
+
   if (StrippedPtr !=3D PtrOp &&
     StrippedPtrTy->getAddressSpace() =3D=3D GEP.getPointerAddressSpace()) {
=20
@@ -1235,15 +1246,15 @@
     if (I->getOpcode() =3D=3D Instruction::Add)
       if (ConstantInt *AddRHS =3D dyn_cast<ConstantInt>(I->getOperand(1)))=
 {
         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
-        unsigned NumCases =3D SI.getNumCases();
         // Skip the first item since that's the default case.
-        for (unsigned i =3D 1; i < NumCases; ++i) {
-          ConstantInt* CaseVal =3D SI.getCaseValue(i);
+        for (SwitchInst::CaseIt i =3D SI.case_begin(), e =3D SI.case_end();
+             i !=3D e; ++i) {
+          ConstantInt* CaseVal =3D i.getCaseValue();
           Constant* NewCaseVal =3D ConstantExpr::getSub(cast<Constant>(Cas=
eVal),
                                                       AddRHS);
           assert(isa<ConstantInt>(NewCaseVal) &&
                  "Result of expression should be constant");
-          SI.setSuccessorValue(i, cast<ConstantInt>(NewCaseVal));
+          i.setValue(cast<ConstantInt>(NewCaseVal));
         }
         SI.setCondition(I->getOperand(0));
         Worklist.Add(I);
@@ -1260,24 +1271,16 @@
     return ReplaceInstUsesWith(EV, Agg);
=20
   if (Constant *C =3D dyn_cast<Constant>(Agg)) {
-    if (isa<UndefValue>(C))
-      return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
-     =20
-    if (isa<ConstantAggregateZero>(C))
-      return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
-
-    if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
-      // Extract the element indexed by the first index out of the constant
-      Value *V =3D C->getOperand(*EV.idx_begin());
-      if (EV.getNumIndices() > 1)
-        // Extract the remaining indices out of the constant indexed by the
-        // first index
-        return ExtractValueInst::Create(V, EV.getIndices().slice(1));
-      else
-        return ReplaceInstUsesWith(EV, V);
+    if (Constant *C2 =3D C->getAggregateElement(*EV.idx_begin())) {
+      if (EV.getNumIndices() =3D=3D 0)
+        return ReplaceInstUsesWith(EV, C2);
+      // Extract the remaining indices out of the constant indexed by the
+      // first index
+      return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
     }
     return 0; // Can't handle other constants
-  }=20
+  }
+ =20
   if (InsertValueInst *IV =3D dyn_cast<InsertValueInst>(Agg)) {
     // We're extracting from an insertvalue instruction, compare the indic=
es
     const unsigned *exti, *exte, *insi, *inse;
@@ -1414,7 +1417,8 @@
 enum Personality_Type {
   Unknown_Personality,
   GNU_Ada_Personality,
-  GNU_CXX_Personality
+  GNU_CXX_Personality,
+  GNU_ObjC_Personality
 };
=20
 /// RecognizePersonality - See if the given exception handling personality
@@ -1426,7 +1430,8 @@
     return Unknown_Personality;
   return StringSwitch<Personality_Type>(F->getName())
     .Case("__gnat_eh_personality", GNU_Ada_Personality)
-    .Case("__gxx_personality_v0", GNU_CXX_Personality)
+    .Case("__gxx_personality_v0",  GNU_CXX_Personality)
+    .Case("__objc_personality_v0", GNU_ObjC_Personality)
     .Default(Unknown_Personality);
 }
=20
@@ -1440,6 +1445,7 @@
     // match foreign exceptions (or didn't, before gcc-4.7).
     return false;
   case GNU_CXX_Personality:
+  case GNU_ObjC_Personality:
     return TypeInfo->isNullValue();
   }
   llvm_unreachable("Unknown personality!");
@@ -1795,7 +1801,8 @@
 static bool AddReachableCodeToWorklist(BasicBlock *BB,=20
                                        SmallPtrSet<BasicBlock*, 64> &Visit=
ed,
                                        InstCombiner &IC,
-                                       const TargetData *TD) {
+                                       const TargetData *TD,
+                                       const TargetLibraryInfo *TLI) {
   bool MadeIRChange =3D false;
   SmallVector<BasicBlock*, 256> Worklist;
   Worklist.push_back(BB);
@@ -1822,7 +1829,7 @@
      =20
       // ConstantProp instruction if trivially constant.
       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
-        if (Constant *C =3D ConstantFoldInstruction(Inst, TD)) {
+        if (Constant *C =3D ConstantFoldInstruction(Inst, TD, TLI)) {
           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
                        << *Inst << '\n');
           Inst->replaceAllUsesWith(C);
@@ -1840,7 +1847,7 @@
=20
           Constant*& FoldRes =3D FoldedConstants[CE];
           if (!FoldRes)
-            FoldRes =3D ConstantFoldConstantExpression(CE, TD);
+            FoldRes =3D ConstantFoldConstantExpression(CE, TD, TLI);
           if (!FoldRes)
             FoldRes =3D CE;
=20
@@ -1867,15 +1874,16 @@
     } else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
       if (ConstantInt *Cond =3D dyn_cast<ConstantInt>(SI->getCondition()))=
 {
         // See if this is an explicit destination.
-        for (unsigned i =3D 1, e =3D SI->getNumSuccessors(); i !=3D e; ++i)
-          if (SI->getCaseValue(i) =3D=3D Cond) {
-            BasicBlock *ReachableBB =3D SI->getSuccessor(i);
+        for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end=
();
+             i !=3D e; ++i)
+          if (i.getCaseValue() =3D=3D Cond) {
+            BasicBlock *ReachableBB =3D i.getCaseSuccessor();
             Worklist.push_back(ReachableBB);
             continue;
           }
        =20
         // Otherwise it is the default destination.
-        Worklist.push_back(SI->getSuccessor(0));
+        Worklist.push_back(SI->getDefaultDest());
         continue;
       }
     }
@@ -1899,14 +1907,15 @@
   MadeIRChange =3D false;
  =20
   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
-        << F.getNameStr() << "\n");
+               << F.getName() << "\n");
=20
   {
     // Do a depth-first traversal of the function, populate the worklist w=
ith
     // the reachable instructions.  Ignore blocks that are not reachable. =
 Keep
     // track of which blocks we visit.
     SmallPtrSet<BasicBlock*, 64> Visited;
-    MadeIRChange |=3D AddReachableCodeToWorklist(F.begin(), Visited, *this=
, TD);
+    MadeIRChange |=3D AddReachableCodeToWorklist(F.begin(), Visited, *this=
, TD,
+                                               TLI);
=20
     // Do a quick scan over the function.  If we find any blocks that are
     // unreachable, remove any instructions inside of them.  This prevents
@@ -1951,7 +1960,7 @@
=20
     // Instruction isn't dead, see if we can constant propagate it.
     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
-      if (Constant *C =3D ConstantFoldInstruction(I, TD)) {
+      if (Constant *C =3D ConstantFoldInstruction(I, TD, TLI)) {
         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '=
\n');
=20
         // Add operands to the worklist.
@@ -2059,7 +2068,7 @@
=20
 bool InstCombiner::runOnFunction(Function &F) {
   TD =3D getAnalysisIfAvailable<TargetData>();
-
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
  =20
   /// Builder - This is an IRBuilder that automatically inserts new
   /// instructions into the worklist when they are created.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Instr=
umentation/GCOVProfiling.cpp
--- a/head/contrib/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -43,12 +43,14 @@
   public:
     static char ID;
     GCOVProfiler()
-        : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(fa=
lse) {
+        : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(fa=
lse),
+          UseExtraChecksum(false) {
       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
     }
-    GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format =3D fals=
e)
+    GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format =3D fals=
e,
+                 bool useExtraChecksum =3D false)
         : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
-          Use402Format(use402Format) {
+          Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
       assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?=
");
       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
     }
@@ -94,6 +96,7 @@
     bool EmitNotes;
     bool EmitData;
     bool Use402Format;
+    bool UseExtraChecksum;
=20
     Module *M;
     LLVMContext *Ctx;
@@ -105,8 +108,9 @@
                 "Insert instrumentation for GCOV profiling", false, false)
=20
 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
-                                         bool Use402Format) {
-  return new GCOVProfiler(EmitNotes, EmitData, Use402Format);
+                                         bool Use402Format,
+                                         bool UseExtraChecksum) {
+  return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraCheck=
sum);
 }
=20
 namespace {
@@ -167,7 +171,7 @@
     }
=20
     uint32_t length() {
-      // Here 2 =3D 1 for string lenght + 1 for '0' id#.
+      // Here 2 =3D 1 for string length + 1 for '0' id#.
       return lengthOfGCOVString(Filename) + 2 + Lines.size();
     }
=20
@@ -244,10 +248,12 @@
   // object users can construct, the blocks and lines will be rooted here.
   class GCOVFunction : public GCOVRecord {
    public:
-    GCOVFunction(DISubprogram SP, raw_ostream *os, bool Use402Format) {
+    GCOVFunction(DISubprogram SP, raw_ostream *os,
+                 bool Use402Format, bool UseExtraChecksum) {
       this->os =3D os;
=20
       Function *F =3D SP.getFunction();
+      DEBUG(dbgs() << "Function: " << F->getName() << "\n");
       uint32_t i =3D 0;
       for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D E=
; ++BB) {
         Blocks[BB] =3D new GCOVBlock(i++, os);
@@ -257,14 +263,14 @@
       writeBytes(FunctionTag, 4);
       uint32_t BlockLen =3D 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
           1 + lengthOfGCOVString(SP.getFilename()) + 1;
-      if (!Use402Format)
-        ++BlockLen; // For second checksum.
+      if (UseExtraChecksum)
+        ++BlockLen;
       write(BlockLen);
       uint32_t Ident =3D reinterpret_cast<intptr_t>((MDNode*)SP);
       write(Ident);
-      write(0);  // checksum #1
-      if (!Use402Format)
-        write(0);  // checksum #2
+      write(0);  // lineno checksum
+      if (UseExtraChecksum)
+        write(0);  // cfg checksum
       writeGCOVString(SP.getName());
       writeGCOVString(SP.getFilename());
       write(SP.getLineNumber());
@@ -290,6 +296,7 @@
       for (int i =3D 0, e =3D Blocks.size() + 1; i !=3D e; ++i) {
         write(0);  // No flags on our blocks.
       }
+      DEBUG(dbgs() << Blocks.size() << " blocks.\n");
=20
       // Emit edges between blocks.
       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I =3D Blocks.begi=
n(),
@@ -301,6 +308,8 @@
         write(Block.OutEdges.size() * 2 + 1);
         write(Block.Number);
         for (int i =3D 0, e =3D Block.OutEdges.size(); i !=3D e; ++i) {
+          DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Num=
ber
+                       << "\n");
           write(Block.OutEdges[i]->Number);
           write(0);  // no flags
         }
@@ -350,68 +359,60 @@
 }
=20
 void GCOVProfiler::emitGCNO() {
-  DenseMap<const MDNode *, raw_fd_ostream *> GcnoFiles;
   NamedMDNode *CU_Nodes =3D M->getNamedMetadata("llvm.dbg.cu");
-  if (CU_Nodes) {
-    for (unsigned i =3D 0, e =3D CU_Nodes->getNumOperands(); i !=3D e; ++i=
) {
-      // Each compile unit gets its own .gcno file. This means that whethe=
r we run
-      // this pass over the original .o's as they're produced, or run it a=
fter
-      // LTO, we'll generate the same .gcno files.
-     =20
-      DICompileUnit CU(CU_Nodes->getOperand(i));
-      raw_fd_ostream *&out =3D GcnoFiles[CU];
-      std::string ErrorInfo;
-      out =3D new raw_fd_ostream(mangleName(CU, "gcno").c_str(), ErrorInfo,
-                               raw_fd_ostream::F_Binary);
-      if (!Use402Format)
-        out->write("oncg*404MVLL", 12);
-      else
-        out->write("oncg*204MVLL", 12);
- =20
-      DIArray SPs =3D CU.getSubprograms();
-      for (unsigned i =3D 0, e =3D SPs.getNumElements(); i !=3D e; ++i) {
-        DISubprogram SP(SPs.getElement(i));
-        if (!SP.Verify()) continue;
-        raw_fd_ostream *&os =3D GcnoFiles[CU];
-       =20
-        Function *F =3D SP.getFunction();
-        if (!F) continue;
-        GCOVFunction Func(SP, os, Use402Format);
-       =20
-        for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D=
 E; ++BB) {
-          GCOVBlock &Block =3D Func.getBlock(BB);
-          TerminatorInst *TI =3D BB->getTerminator();
-          if (int successors =3D TI->getNumSuccessors()) {
-            for (int i =3D 0; i !=3D successors; ++i) {
-              Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
-            }
-          } else if (isa<ReturnInst>(TI)) {
-            Block.addEdge(Func.getReturnBlock());
+  if (!CU_Nodes) return;
+
+  for (unsigned i =3D 0, e =3D CU_Nodes->getNumOperands(); i !=3D e; ++i) {
+    // Each compile unit gets its own .gcno file. This means that whether =
we run
+    // this pass over the original .o's as they're produced, or run it aft=
er
+    // LTO, we'll generate the same .gcno files.
+
+    DICompileUnit CU(CU_Nodes->getOperand(i));
+    std::string ErrorInfo;
+    raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
+                       raw_fd_ostream::F_Binary);
+    if (!Use402Format)
+      out.write("oncg*404MVLL", 12);
+    else
+      out.write("oncg*204MVLL", 12);
+
+    DIArray SPs =3D CU.getSubprograms();
+    for (unsigned i =3D 0, e =3D SPs.getNumElements(); i !=3D e; ++i) {
+      DISubprogram SP(SPs.getElement(i));
+      if (!SP.Verify()) continue;
+
+      Function *F =3D SP.getFunction();
+      if (!F) continue;
+      GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
+
+      for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D E=
; ++BB) {
+        GCOVBlock &Block =3D Func.getBlock(BB);
+        TerminatorInst *TI =3D BB->getTerminator();
+        if (int successors =3D TI->getNumSuccessors()) {
+          for (int i =3D 0; i !=3D successors; ++i) {
+            Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
           }
-         =20
-          uint32_t Line =3D 0;
-          for (BasicBlock::iterator I =3D BB->begin(), IE =3D BB->end(); I=
 !=3D IE; ++I) {
-            const DebugLoc &Loc =3D I->getDebugLoc();
-            if (Loc.isUnknown()) continue;
-            if (Line =3D=3D Loc.getLine()) continue;
-            Line =3D Loc.getLine();
-            if (SP !=3D getDISubprogram(Loc.getScope(*Ctx))) continue;
-           =20
-            GCOVLines &Lines =3D Block.getFile(SP.getFilename());
-            Lines.addLine(Loc.getLine());
-          }
+        } else if (isa<ReturnInst>(TI)) {
+          Block.addEdge(Func.getReturnBlock());
         }
-        Func.writeOut();
+
+        uint32_t Line =3D 0;
+        for (BasicBlock::iterator I =3D BB->begin(), IE =3D BB->end();
+             I !=3D IE; ++I) {
+          const DebugLoc &Loc =3D I->getDebugLoc();
+          if (Loc.isUnknown()) continue;
+          if (Line =3D=3D Loc.getLine()) continue;
+          Line =3D Loc.getLine();
+          if (SP !=3D getDISubprogram(Loc.getScope(*Ctx))) continue;
+
+          GCOVLines &Lines =3D Block.getFile(SP.getFilename());
+          Lines.addLine(Loc.getLine());
+        }
       }
+      Func.writeOut();
     }
-  }
-
-  for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
-           I =3D GcnoFiles.begin(), E =3D GcnoFiles.end(); I !=3D E; ++I) {
-    raw_fd_ostream *&out =3D I->second;
-    out->write("\0\0\0\0\0\0\0\0", 8);  // EOF
-    out->close();
-    delete out;
+    out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
+    out.close();
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Instr=
umentation/Instrumentation.cpp
--- a/head/contrib/llvm/lib/Transforms/Instrumentation/Instrumentation.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Instrumentation/Instrumentation.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -24,6 +24,8 @@
   initializeOptimalEdgeProfilerPass(Registry);
   initializePathProfilerPass(Registry);
   initializeGCOVProfilerPass(Registry);
+  initializeAddressSanitizerPass(Registry);
+  initializeThreadSanitizerPass(Registry);
 }
=20
 /// LLVMInitializeInstrumentation - C binding for
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Instr=
umentation/OptimalEdgeProfiling.cpp
--- a/head/contrib/llvm/lib/Transforms/Instrumentation/OptimalEdgeProfiling=
.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Instrumentation/OptimalEdgeProfiling=
.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -69,7 +69,7 @@
                                     BasicBlock* b,
                                     unsigned i) {
   DEBUG(dbgs() << "--Edge Counter for " << (e) << " in " \
-               << ((b)?(b)->getNameStr():"0") << " (# " << (i) << ")\n");
+               << ((b)?(b)->getName():"0") << " (# " << (i) << ")\n");
 }
=20
 bool OptimalEdgeProfiler::runOnModule(Module &M) {
@@ -127,7 +127,7 @@
   unsigned i =3D 0;
   for (Module::iterator F =3D M.begin(), E =3D M.end(); F !=3D E; ++F) {
     if (F->isDeclaration()) continue;
-    DEBUG(dbgs() << "Working on " << F->getNameStr() << "\n");
+    DEBUG(dbgs() << "Working on " << F->getName() << "\n");
=20
     // Calculate a Maximum Spanning Tree with the edge weights determined =
by
     // ProfileEstimator. ProfileEstimator also assign weights to the virtu=
al
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Instr=
umentation/PathProfiling.cpp
--- a/head/contrib/llvm/lib/Transforms/Instrumentation/PathProfiling.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Instrumentation/PathProfiling.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -665,7 +665,7 @@
 // Generate a .dot graph to represent the DAG and pathNumbers
 void BLInstrumentationDag::generateDotGraph() {
   std::string errorInfo;
-  std::string functionName =3D getFunction().getNameStr();
+  std::string functionName =3D getFunction().getName().str();
   std::string filename =3D "pathdag." + functionName + ".dot";
=20
   DEBUG (dbgs() << "Writing '" << filename << "'...\n");
@@ -750,7 +750,8 @@
 // Sets the Value of the pathNumber.  Used by the instrumentation code.
 void BLInstrumentationNode::setStartingPathNumber(Value* pathNumber) {
   DEBUG(dbgs() << "  SPN-" << getName() << " <-- " << (pathNumber ?
-                                                       pathNumber->getName=
Str() : "unused") << "\n");
+                                                       pathNumber->getName=
() :
+                                                       "unused") << "\n");
   _startingPathNumber =3D pathNumber;
 }
=20
@@ -760,7 +761,7 @@
=20
 void BLInstrumentationNode::setEndingPathNumber(Value* pathNumber) {
   DEBUG(dbgs() << "  EPN-" << getName() << " <-- "
-        << (pathNumber ? pathNumber->getNameStr() : "unused") << "\n");
+               << (pathNumber ? pathNumber->getName() : "unused") << "\n");
   _endingPathNumber =3D pathNumber;
 }
=20
@@ -1239,9 +1240,9 @@
       insertPoint++;
=20
     DEBUG(dbgs() << "\nInstrumenting method call block '"
-          << node->getBlock()->getNameStr() << "'\n");
+                 << node->getBlock()->getName() << "'\n");
     DEBUG(dbgs() << "   Path number initialized: "
-          << ((node->getStartingPathNumber()) ? "yes" : "no") << "\n");
+                 << ((node->getStartingPathNumber()) ? "yes" : "no") << "\=
n");
=20
     Value* newpn;
     if( node->getStartingPathNumber() ) {
@@ -1370,7 +1371,7 @@
     if (F->isDeclaration())
       continue;
=20
-    DEBUG(dbgs() << "Function: " << F->getNameStr() << "\n");
+    DEBUG(dbgs() << "Function: " << F->getName() << "\n");
     functionNumber++;
=20
     // set function number
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/CodeGenPrepare.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/CodeGenPrepare.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/CodeGenPrepare.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -26,6 +26,7 @@
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/ProfileInfo.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
@@ -64,11 +65,17 @@
   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
   cl::desc("Disable branch optimizations in CodeGenPrepare"));
=20
+// FIXME: Remove this abomination once all of the tests pass without it!
+static cl::opt<bool> DisableDeleteDeadBlocks(
+  "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
+  cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
+
 namespace {
   class CodeGenPrepare : public FunctionPass {
     /// TLI - Keep a pointer of a TargetLowering to consult for determining
     /// transformation profitability.
     const TargetLowering *TLI;
+    const TargetLibraryInfo *TLInfo;
     DominatorTree *DT;
     ProfileInfo *PFI;
    =20
@@ -97,6 +104,7 @@
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addPreserved<DominatorTree>();
       AU.addPreserved<ProfileInfo>();
+      AU.addRequired<TargetLibraryInfo>();
     }
=20
   private:
@@ -116,7 +124,10 @@
 }
=20
 char CodeGenPrepare::ID =3D 0;
-INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
+INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
+                "Optimize for code generation", false, false)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
+INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
                 "Optimize for code generation", false, false)
=20
 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
@@ -127,6 +138,7 @@
   bool EverMadeChange =3D false;
=20
   ModifiedDT =3D false;
+  TLInfo =3D &getAnalysis<TargetLibraryInfo>();
   DT =3D getAnalysisIfAvailable<DominatorTree>();
   PFI =3D getAnalysisIfAvailable<ProfileInfo>();
=20
@@ -153,8 +165,22 @@
=20
   if (!DisableBranchOpts) {
     MadeChange =3D false;
-    for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++=
BB)
+    SmallPtrSet<BasicBlock*, 8> WorkList;
+    for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++=
BB) {
+      SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
       MadeChange |=3D ConstantFoldTerminator(BB, true);
+      if (!MadeChange) continue;
+
+      for (SmallVectorImpl<BasicBlock*>::iterator
+             II =3D Successors.begin(), IE =3D Successors.end(); II !=3D I=
E; ++II)
+        if (pred_begin(*II) =3D=3D pred_end(*II))
+          WorkList.insert(*II);
+    }
+
+    if (!DisableDeleteDeadBlocks)
+      for (SmallPtrSet<BasicBlock*, 8>::iterator
+             I =3D WorkList.begin(), E =3D WorkList.end(); I !=3D E; ++I)
+        DeleteDeadBlock(*I);
=20
     if (MadeChange)
       ModifiedDT =3D true;
@@ -541,8 +567,8 @@
     // happens.
     WeakVH IterHandle(CurInstIterator);
    =20
-    ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0,
-                              ModifiedDT ? 0 : DT);
+    replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() :=
 0,
+                                  TLInfo, ModifiedDT ? 0 : DT);
=20
     // If the iterator instruction was recursively deleted, start over at =
the
     // start of the block.
@@ -553,6 +579,15 @@
     return true;
   }
=20
+  if (II && TLI) {
+    SmallVector<Value*, 2> PtrOps;
+    Type *AccessTy;
+    if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
+      while (!PtrOps.empty())
+        if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
+          return true;
+  }
+
   // From here on out we're working with named functions.
   if (CI->getCalledFunction() =3D=3D 0) return false;
=20
@@ -612,7 +647,7 @@
   // It's not safe to eliminate the sign / zero extension of the return va=
lue.
   // See llvm::isInTailCallPosition().
   const Function *F =3D BB->getParent();
-  unsigned CallerRetAttr =3D F->getAttributes().getRetAttributes();
+  Attributes CallerRetAttr =3D F->getAttributes().getRetAttributes();
   if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SEx=
t))
     return false;
=20
@@ -667,7 +702,7 @@
=20
     // Conservatively require the attributes of the call to match those of=
 the
     // return. Ignore noalias because it doesn't affect the call sequence.
-    unsigned CalleeRetAttr =3D CS.getAttributes().getRetAttributes();
+    Attributes CalleeRetAttr =3D CS.getAttributes().getRetAttributes();
     if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
       continue;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/ConstantProp.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/ConstantProp.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/ConstantProp.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -24,6 +24,8 @@
 #include "llvm/Constant.h"
 #include "llvm/Instruction.h"
 #include "llvm/Pass.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Support/InstIterator.h"
 #include "llvm/ADT/Statistic.h"
 #include <set>
@@ -42,19 +44,22 @@
=20
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
+      AU.addRequired<TargetLibraryInfo>();
     }
   };
 }
=20
 char ConstantPropagation::ID =3D 0;
-INITIALIZE_PASS(ConstantPropagation, "constprop",
+INITIALIZE_PASS_BEGIN(ConstantPropagation, "constprop",
+                "Simple constant propagation", false, false)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
+INITIALIZE_PASS_END(ConstantPropagation, "constprop",
                 "Simple constant propagation", false, false)
=20
 FunctionPass *llvm::createConstantPropagationPass() {
   return new ConstantPropagation();
 }
=20
-
 bool ConstantPropagation::runOnFunction(Function &F) {
   // Initialize the worklist to all of the instructions ready to process...
   std::set<Instruction*> WorkList;
@@ -62,13 +67,15 @@
       WorkList.insert(&*i);
   }
   bool Changed =3D false;
+  TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
+  TargetLibraryInfo *TLI =3D &getAnalysis<TargetLibraryInfo>();
=20
   while (!WorkList.empty()) {
     Instruction *I =3D *WorkList.begin();
     WorkList.erase(WorkList.begin());    // Get an element from the workli=
st...
=20
     if (!I->use_empty())                 // Don't muck with dead instructi=
ons...
-      if (Constant *C =3D ConstantFoldInstruction(I)) {
+      if (Constant *C =3D ConstantFoldInstruction(I, TD, TLI)) {
         // Add all of the users of this instruction to the worklist, they =
might
         // be constant propagatable now...
         for (Value::use_iterator UI =3D I->use_begin(), UE =3D I->use_end(=
);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/CorrelatedValuePropagation.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cp=
p	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cp=
p	Tue Apr 17 11:51:51 2012 +0300
@@ -28,6 +28,7 @@
 STATISTIC(NumSelects,   "Number of selects propagated");
 STATISTIC(NumMemAccess, "Number of memory access targets propagated");
 STATISTIC(NumCmps,      "Number of comparisons propagated");
+STATISTIC(NumDeadCases, "Number of switch cases removed");
=20
 namespace {
   class CorrelatedValuePropagation : public FunctionPass {
@@ -37,6 +38,7 @@
     bool processPHI(PHINode *P);
     bool processMemAccess(Instruction *I);
     bool processCmp(CmpInst *C);
+    bool processSwitch(SwitchInst *SI);
=20
   public:
     static char ID;
@@ -110,7 +112,8 @@
     Changed =3D true;
   }
=20
-  ++NumPhis;
+  if (Changed)
+    ++NumPhis;
=20
   return Changed;
 }
@@ -173,6 +176,86 @@
   return true;
 }
=20
+/// processSwitch - Simplify a switch instruction by removing cases which =
can
+/// never fire.  If the uselessness of a case could be determined locally =
then
+/// constant propagation would already have figured it out.  Instead, walk=
 the
+/// predecessors and statically evaluate cases based on information availa=
ble
+/// on that edge.  Cases that cannot fire no matter what the incoming edge=
 can
+/// safely be removed.  If a case fires on every incoming edge then the en=
tire
+/// switch can be removed and replaced with a branch to the case destinati=
on.
+bool CorrelatedValuePropagation::processSwitch(SwitchInst *SI) {
+  Value *Cond =3D SI->getCondition();
+  BasicBlock *BB =3D SI->getParent();
+
+  // If the condition was defined in same block as the switch then LazyVal=
ueInfo
+  // currently won't say anything useful about it, though in theory it cou=
ld.
+  if (isa<Instruction>(Cond) && cast<Instruction>(Cond)->getParent() =3D=
=3D BB)
+    return false;
+
+  // If the switch is unreachable then trying to improve it is a waste of =
time.
+  pred_iterator PB =3D pred_begin(BB), PE =3D pred_end(BB);
+  if (PB =3D=3D PE) return false;
+
+  // Analyse each switch case in turn.  This is done in reverse order so t=
hat
+  // removing a case doesn't cause trouble for the iteration.
+  bool Changed =3D false;
+  for (SwitchInst::CaseIt CI =3D SI->case_end(), CE =3D SI->case_begin(); =
CI-- !=3D CE;
+       ) {
+    ConstantInt *Case =3D CI.getCaseValue();
+
+    // Check to see if the switch condition is equal to/not equal to the c=
ase
+    // value on every incoming edge, equal/not equal being the same each t=
ime.
+    LazyValueInfo::Tristate State =3D LazyValueInfo::Unknown;
+    for (pred_iterator PI =3D PB; PI !=3D PE; ++PI) {
+      // Is the switch condition equal to the case value?
+      LazyValueInfo::Tristate Value =3D LVI->getPredicateOnEdge(CmpInst::I=
CMP_EQ,
+                                                              Cond, Case, =
*PI, BB);
+      // Give up on this case if nothing is known.
+      if (Value =3D=3D LazyValueInfo::Unknown) {
+        State =3D LazyValueInfo::Unknown;
+        break;
+      }
+
+      // If this was the first edge to be visited, record that all other e=
dges
+      // need to give the same result.
+      if (PI =3D=3D PB) {
+        State =3D Value;
+        continue;
+      }
+
+      // If this case is known to fire for some edges and known not to fir=
e for
+      // others then there is nothing we can do - give up.
+      if (Value !=3D State) {
+        State =3D LazyValueInfo::Unknown;
+        break;
+      }
+    }
+
+    if (State =3D=3D LazyValueInfo::False) {
+      // This case never fires - remove it.
+      CI.getCaseSuccessor()->removePredecessor(BB);
+      SI->removeCase(CI); // Does not invalidate the iterator.
+      ++NumDeadCases;
+      Changed =3D true;
+    } else if (State =3D=3D LazyValueInfo::True) {
+      // This case always fires.  Arrange for the switch to be turned into=
 an
+      // unconditional branch by replacing the switch condition with the c=
ase
+      // value.
+      SI->setCondition(Case);
+      NumDeadCases +=3D SI->getNumCases();
+      Changed =3D true;
+      break;
+    }
+  }
+
+  if (Changed)
+    // If the switch has been simplified to the point where it can be repl=
aced
+    // by a branch then do so now.
+    ConstantFoldTerminator(BB);
+
+  return Changed;
+}
+
 bool CorrelatedValuePropagation::runOnFunction(Function &F) {
   LVI =3D &getAnalysis<LazyValueInfo>();
=20
@@ -200,6 +283,13 @@
       }
     }
=20
+    Instruction *Term =3D FI->getTerminator();
+    switch (Term->getOpcode()) {
+    case Instruction::Switch:
+      BBChanged |=3D processSwitch(cast<SwitchInst>(Term));
+      break;
+    }
+
     FnChanged |=3D BBChanged;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/DeadStoreElimination.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/DeadStoreElimination.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -24,6 +24,7 @@
 #include "llvm/IntrinsicInst.h"
 #include "llvm/Pass.h"
 #include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/Analysis/CaptureTracking.h"
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
@@ -33,6 +34,7 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/STLExtras.h"
 using namespace llvm;
=20
 STATISTIC(NumFastStores, "Number of stores deleted");
@@ -42,25 +44,26 @@
   struct DSE : public FunctionPass {
     AliasAnalysis *AA;
     MemoryDependenceAnalysis *MD;
+    DominatorTree *DT;
=20
     static char ID; // Pass identification, replacement for typeid
-    DSE() : FunctionPass(ID), AA(0), MD(0) {
+    DSE() : FunctionPass(ID), AA(0), MD(0), DT(0) {
       initializeDSEPass(*PassRegistry::getPassRegistry());
     }
=20
     virtual bool runOnFunction(Function &F) {
       AA =3D &getAnalysis<AliasAnalysis>();
       MD =3D &getAnalysis<MemoryDependenceAnalysis>();
-      DominatorTree &DT =3D getAnalysis<DominatorTree>();
+      DT =3D &getAnalysis<DominatorTree>();
=20
       bool Changed =3D false;
       for (Function::iterator I =3D F.begin(), E =3D F.end(); I !=3D E; ++=
I)
         // Only check non-dead blocks.  Dead blocks may have strange point=
er
         // cycles that will confuse alias analysis.
-        if (DT.isReachableFromEntry(I))
+        if (DT->isReachableFromEntry(I))
           Changed |=3D runOnBasicBlock(*I);
=20
-      AA =3D 0; MD =3D 0;
+      AA =3D 0; MD =3D 0; DT =3D 0;
       return Changed;
     }
=20
@@ -221,7 +224,7 @@
=20
   IntrinsicInst *II =3D cast<IntrinsicInst>(I);
   switch (II->getIntrinsicID()) {
-  default: assert(0 && "doesn't pass 'hasMemoryWrite' predicate");
+  default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
   case Intrinsic::lifetime_end:
     // Never remove dead lifetime_end's, e.g. because it is followed by a
     // free.
@@ -238,6 +241,24 @@
   }
 }
=20
+
+/// isShortenable - Returns true if this instruction can be safely shorten=
ed in
+/// length.
+static bool isShortenable(Instruction *I) {
+  // Don't shorten stores for now
+  if (isa<StoreInst>(I))
+    return false;
+ =20
+  IntrinsicInst *II =3D cast<IntrinsicInst>(I);
+  switch (II->getIntrinsicID()) {
+    default: return false;
+    case Intrinsic::memset:
+    case Intrinsic::memcpy:
+      // Do shorten memory intrinsics.
+      return true;
+  }
+}
+
 /// getStoredPointerOperand - Return the pointer that is being written to.
 static Value *getStoredPointerOperand(Instruction *I) {
   if (StoreInst *SI =3D dyn_cast<StoreInst>(I))
@@ -247,46 +268,61 @@
=20
   IntrinsicInst *II =3D cast<IntrinsicInst>(I);
   switch (II->getIntrinsicID()) {
-  default: assert(false && "Unexpected intrinsic!");
+  default: llvm_unreachable("Unexpected intrinsic!");
   case Intrinsic::init_trampoline:
     return II->getArgOperand(0);
   }
 }
=20
-static uint64_t getPointerSize(Value *V, AliasAnalysis &AA) {
+static uint64_t getPointerSize(const Value *V, AliasAnalysis &AA) {
   const TargetData *TD =3D AA.getTargetData();
+
+  if (const CallInst *CI =3D extractMallocCall(V)) {
+    if (const ConstantInt *C =3D dyn_cast<ConstantInt>(CI->getArgOperand(0=
)))
+      return C->getZExtValue();
+  }
+
   if (TD =3D=3D 0)
     return AliasAnalysis::UnknownSize;
=20
-  if (AllocaInst *A =3D dyn_cast<AllocaInst>(V)) {
+  if (const AllocaInst *A =3D dyn_cast<AllocaInst>(V)) {
     // Get size information for the alloca
-    if (ConstantInt *C =3D dyn_cast<ConstantInt>(A->getArraySize()))
+    if (const ConstantInt *C =3D dyn_cast<ConstantInt>(A->getArraySize()))
       return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType(=
));
-    return AliasAnalysis::UnknownSize;
   }
=20
-  assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
-  PointerType *PT =3D cast<PointerType>(V->getType());
-  return TD->getTypeAllocSize(PT->getElementType());
+  if (const Argument *A =3D dyn_cast<Argument>(V)) {
+    if (A->hasByValAttr())
+      if (PointerType *PT =3D dyn_cast<PointerType>(A->getType()))
+        return TD->getTypeAllocSize(PT->getElementType());
+  }
+
+  if (const GlobalVariable *GV =3D dyn_cast<GlobalVariable>(V)) {
+    if (!GV->mayBeOverridden())
+      return TD->getTypeAllocSize(GV->getType()->getElementType());
+  }
+
+  return AliasAnalysis::UnknownSize;
 }
=20
-/// isObjectPointerWithTrustworthySize - Return true if the specified Valu=
e* is
-/// pointing to an object with a pointer size we can trust.
-static bool isObjectPointerWithTrustworthySize(const Value *V) {
-  if (const AllocaInst *AI =3D dyn_cast<AllocaInst>(V))
-    return !AI->isArrayAllocation();
-  if (const GlobalVariable *GV =3D dyn_cast<GlobalVariable>(V))
-    return !GV->mayBeOverridden();
-  if (const Argument *A =3D dyn_cast<Argument>(V))
-    return A->hasByValAttr();
-  return false;
+namespace {
+  enum OverwriteResult
+  {
+    OverwriteComplete,
+    OverwriteEnd,
+    OverwriteUnknown
+  };
 }
=20
-/// isCompleteOverwrite - Return true if a store to the 'Later' location
+/// isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' loc=
ation
 /// completely overwrites a store to the 'Earlier' location.
-static bool isCompleteOverwrite(const AliasAnalysis::Location &Later,
-                                const AliasAnalysis::Location &Earlier,
-                                AliasAnalysis &AA) {
+/// 'OverwriteEnd' if the end of the 'Earlier' location is completely=20
+/// overwritten by 'Later', or 'OverwriteUnknown' if nothing can be determ=
ined
+static OverwriteResult isOverwrite(const AliasAnalysis::Location &Later,
+                                   const AliasAnalysis::Location &Earlier,
+                                   AliasAnalysis &AA,
+                                   int64_t &EarlierOff,
+                                   int64_t &LaterOff) {
   const Value *P1 =3D Earlier.Ptr->stripPointerCasts();
   const Value *P2 =3D Later.Ptr->stripPointerCasts();
=20
@@ -300,23 +336,24 @@
       // If we have no TargetData information around, then the size of the=
 store
       // is inferrable from the pointee type.  If they are the same type, =
then
       // we know that the store is safe.
-      if (AA.getTargetData() =3D=3D 0)
-        return Later.Ptr->getType() =3D=3D Earlier.Ptr->getType();
-      return false;
+      if (AA.getTargetData() =3D=3D 0 &&
+          Later.Ptr->getType() =3D=3D Earlier.Ptr->getType())
+        return OverwriteComplete;
+       =20
+      return OverwriteUnknown;
     }
=20
     // Make sure that the Later size is >=3D the Earlier size.
-    if (Later.Size < Earlier.Size)
-      return false;
-    return true;
+    if (Later.Size >=3D Earlier.Size)
+      return OverwriteComplete;
   }
=20
   // Otherwise, we have to have size information, and the later store has =
to be
   // larger than the earlier one.
   if (Later.Size =3D=3D AliasAnalysis::UnknownSize ||
       Earlier.Size =3D=3D AliasAnalysis::UnknownSize ||
-      Later.Size <=3D Earlier.Size || AA.getTargetData() =3D=3D 0)
-    return false;
+      AA.getTargetData() =3D=3D 0)
+    return OverwriteUnknown;
=20
   // Check to see if the later store is to the entire object (either a glo=
bal,
   // an alloca, or a byval argument).  If so, then it clearly overwrites a=
ny
@@ -329,26 +366,25 @@
   // If we can't resolve the same pointers to the same object, then we can=
't
   // analyze them at all.
   if (UO1 !=3D UO2)
-    return false;
+    return OverwriteUnknown;
=20
   // If the "Later" store is to a recognizable object, get its size.
-  if (isObjectPointerWithTrustworthySize(UO2)) {
-    uint64_t ObjectSize =3D
-      TD.getTypeAllocSize(cast<PointerType>(UO2->getType())->getElementTyp=
e());
-    if (ObjectSize =3D=3D Later.Size)
-      return true;
-  }
+  uint64_t ObjectSize =3D getPointerSize(UO2, AA);
+  if (ObjectSize !=3D AliasAnalysis::UnknownSize)
+    if (ObjectSize =3D=3D Later.Size && ObjectSize >=3D Earlier.Size)
+      return OverwriteComplete;
=20
   // Okay, we have stores to two completely different pointers.  Try to
   // decompose the pointer into a "base + constant_offset" form.  If the b=
ase
   // pointers are equal, then we can reason about the two stores.
-  int64_t EarlierOff =3D 0, LaterOff =3D 0;
+  EarlierOff =3D 0;
+  LaterOff =3D 0;
   const Value *BP1 =3D GetPointerBaseWithConstantOffset(P1, EarlierOff, TD=
);
   const Value *BP2 =3D GetPointerBaseWithConstantOffset(P2, LaterOff, TD);
=20
   // If the base pointers still differ, we have two completely different s=
tores.
   if (BP1 !=3D BP2)
-    return false;
+    return OverwriteUnknown;
=20
   // The later store completely overlaps the earlier store if:
   //
@@ -366,11 +402,25 @@
   //
   // We have to be careful here as *Off is signed while *.Size is unsigned.
   if (EarlierOff >=3D LaterOff &&
+      Later.Size > Earlier.Size &&
       uint64_t(EarlierOff - LaterOff) + Earlier.Size <=3D Later.Size)
-    return true;
+    return OverwriteComplete;
+ =20
+  // The other interesting case is if the later store overwrites the end of
+  // the earlier store
+  //
+  //      |--earlier--|
+  //                |--   later   --|
+  //
+  // In this case we may want to trim the size of earlier to avoid generat=
ing
+  // writes to addresses which will definitely be overwritten later
+  if (LaterOff > EarlierOff &&
+      LaterOff < int64_t(EarlierOff + Earlier.Size) &&
+      int64_t(LaterOff + Later.Size) >=3D int64_t(EarlierOff + Earlier.Siz=
e))
+    return OverwriteEnd;
=20
   // Otherwise, they don't completely overlap.
-  return false;
+  return OverwriteUnknown;
 }
=20
 /// isPossibleSelfRead - If 'Inst' might be a self read (i.e. a noop copy =
of a
@@ -494,22 +544,52 @@
       // If we find a write that is a) removable (i.e., non-volatile), b) =
is
       // completely obliterated by the store to 'Loc', and c) which we kno=
w that
       // 'Inst' doesn't load from, then we can remove it.
-      if (isRemovable(DepWrite) && isCompleteOverwrite(Loc, DepLoc, *AA) &&
+      if (isRemovable(DepWrite) &&=20
           !isPossibleSelfRead(Inst, Loc, DepWrite, *AA)) {
-        DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: "
-              << *DepWrite << "\n  KILLER: " << *Inst << '\n');
+        int64_t InstWriteOffset, DepWriteOffset;=20
+        OverwriteResult OR =3D isOverwrite(Loc, DepLoc, *AA,=20
+                                         DepWriteOffset, InstWriteOffset);=20
+        if (OR =3D=3D OverwriteComplete) {
+          DEBUG(dbgs() << "DSE: Remove Dead Store:\n  DEAD: "
+                << *DepWrite << "\n  KILLER: " << *Inst << '\n');
=20
-        // Delete the store and now-dead instructions that feed it.
-        DeleteDeadInstruction(DepWrite, *MD);
-        ++NumFastStores;
-        MadeChange =3D true;
-
-        // DeleteDeadInstruction can delete the current instruction in loop
-        // cases, reset BBI.
-        BBI =3D Inst;
-        if (BBI !=3D BB.begin())
-          --BBI;
-        break;
+          // Delete the store and now-dead instructions that feed it.
+          DeleteDeadInstruction(DepWrite, *MD);
+          ++NumFastStores;
+          MadeChange =3D true;
+         =20
+          // DeleteDeadInstruction can delete the current instruction in l=
oop
+          // cases, reset BBI.
+          BBI =3D Inst;
+          if (BBI !=3D BB.begin())
+            --BBI;
+          break;
+        } else if (OR =3D=3D OverwriteEnd && isShortenable(DepWrite)) {
+          // TODO: base this on the target vector size so that if the earl=
ier
+          // store was too small to get vector writes anyway then its like=
ly
+          // a good idea to shorten it
+          // Power of 2 vector writes are probably always a bad idea to op=
timize
+          // as any store/memset/memcpy is likely using vector instruction=
s so
+          // shortening it to not vector size is likely to be slower
+          MemIntrinsic* DepIntrinsic =3D cast<MemIntrinsic>(DepWrite);
+          unsigned DepWriteAlign =3D DepIntrinsic->getAlignment();
+          if (llvm::isPowerOf2_64(InstWriteOffset) ||
+              ((DepWriteAlign !=3D 0) && InstWriteOffset % DepWriteAlign =
=3D=3D 0)) {
+           =20
+            DEBUG(dbgs() << "DSE: Remove Dead Store:\n  OW END: "
+                  << *DepWrite << "\n  KILLER (offset "=20
+                  << InstWriteOffset << ", "=20
+                  << DepLoc.Size << ")"
+                  << *Inst << '\n');
+           =20
+            Value* DepWriteLength =3D DepIntrinsic->getLength();
+            Value* TrimmedLength =3D ConstantInt::get(DepWriteLength->getT=
ype(),
+                                                    InstWriteOffset -=20
+                                                    DepWriteOffset);
+            DepIntrinsic->setLength(TrimmedLength);
+            MadeChange =3D true;
+          }
+        }
       }
=20
       // If this is a may-aliased store that is clobbering the store value=
, we
@@ -538,37 +618,67 @@
   return MadeChange;
 }
=20
+/// Find all blocks that will unconditionally lead to the block BB and app=
end
+/// them to F.
+static void FindUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
+                                   BasicBlock *BB, DominatorTree *DT) {
+  for (pred_iterator I =3D pred_begin(BB), E =3D pred_end(BB); I !=3D E; +=
+I) {
+    BasicBlock *Pred =3D *I;
+    if (Pred =3D=3D BB) continue;
+    TerminatorInst *PredTI =3D Pred->getTerminator();
+    if (PredTI->getNumSuccessors() !=3D 1)
+      continue;
+
+    if (DT->isReachableFromEntry(Pred))
+      Blocks.push_back(Pred);
+  }
+}
+
 /// HandleFree - Handle frees of entire structures whose dependency is a s=
tore
 /// to a field of that structure.
 bool DSE::HandleFree(CallInst *F) {
   bool MadeChange =3D false;
=20
-  MemDepResult Dep =3D MD->getDependency(F);
+  AliasAnalysis::Location Loc =3D AliasAnalysis::Location(F->getOperand(0)=
);
+  SmallVector<BasicBlock *, 16> Blocks;
+  Blocks.push_back(F->getParent());
=20
-  while (Dep.isDef() || Dep.isClobber()) {
-    Instruction *Dependency =3D Dep.getInst();
-    if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
-      return MadeChange;
+  while (!Blocks.empty()) {
+    BasicBlock *BB =3D Blocks.pop_back_val();
+    Instruction *InstPt =3D BB->getTerminator();
+    if (BB =3D=3D F->getParent()) InstPt =3D F;
=20
-    Value *DepPointer =3D
-      GetUnderlyingObject(getStoredPointerOperand(Dependency));
+    MemDepResult Dep =3D MD->getPointerDependencyFrom(Loc, false, InstPt, =
BB);
+    while (Dep.isDef() || Dep.isClobber()) {
+      Instruction *Dependency =3D Dep.getInst();
+      if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
+        break;
=20
-    // Check for aliasing.
-    if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
-      return MadeChange;
+      Value *DepPointer =3D
+        GetUnderlyingObject(getStoredPointerOperand(Dependency));
=20
-    // DCE instructions only used to calculate that store
-    DeleteDeadInstruction(Dependency, *MD);
-    ++NumFastStores;
-    MadeChange =3D true;
+      // Check for aliasing.
+      if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
+        break;
=20
-    // Inst's old Dependency is now deleted. Compute the next dependency,
-    // which may also be dead, as in
-    //    s[0] =3D 0;
-    //    s[1] =3D 0; // This has just been deleted.
-    //    free(s);
-    Dep =3D MD->getDependency(F);
-  };
+      Instruction *Next =3D llvm::next(BasicBlock::iterator(Dependency));
+
+      // DCE instructions only used to calculate that store
+      DeleteDeadInstruction(Dependency, *MD);
+      ++NumFastStores;
+      MadeChange =3D true;
+
+      // Inst's old Dependency is now deleted. Compute the next dependency,
+      // which may also be dead, as in
+      //    s[0] =3D 0;
+      //    s[1] =3D 0; // This has just been deleted.
+      //    free(s);
+      Dep =3D MD->getPointerDependencyFrom(Loc, false, Next, BB);
+    }
+
+    if (Dep.isNonLocal())
+      FindUnconditionalPreds(Blocks, BB, DT);
+  }
=20
   return MadeChange;
 }
@@ -588,10 +698,17 @@
=20
   // Find all of the alloca'd pointers in the entry block.
   BasicBlock *Entry =3D BB.getParent()->begin();
-  for (BasicBlock::iterator I =3D Entry->begin(), E =3D Entry->end(); I !=
=3D E; ++I)
+  for (BasicBlock::iterator I =3D Entry->begin(), E =3D Entry->end(); I !=
=3D E; ++I) {
     if (AllocaInst *AI =3D dyn_cast<AllocaInst>(I))
       DeadStackObjects.insert(AI);
=20
+    // Okay, so these are dead heap objects, but if the pointer never esca=
pes
+    // then it's leaked by this function anyways.
+    if (CallInst *CI =3D extractMallocCall(I))
+      if (!PointerMayBeCaptured(CI, true, true))
+        DeadStackObjects.insert(CI);
+  }
+
   // Treat byval arguments the same, stores to them are dead at the end of=
 the
   // function.
   for (Function::arg_iterator AI =3D BB.getParent()->arg_begin(),
@@ -637,6 +754,11 @@
       continue;
     }
=20
+    if (CallInst *CI =3D extractMallocCall(BBI)) {
+      DeadStackObjects.erase(CI);
+      continue;
+    }
+
     if (CallSite CS =3D cast<Value>(BBI)) {
       // If this call does not access memory, it can't be loading any of o=
ur
       // pointers.
@@ -732,4 +854,3 @@
        I !=3D E; ++I)
     DeadStackObjects.erase(*I);
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/EarlyCSE.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/EarlyCSE.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/EarlyCSE.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -19,11 +19,13 @@
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/RecyclingAllocator.h"
 #include "llvm/ADT/ScopedHashTable.h"
 #include "llvm/ADT/Statistic.h"
+#include <deque>
 using namespace llvm;
=20
 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
@@ -215,6 +217,7 @@
 class EarlyCSE : public FunctionPass {
 public:
   const TargetData *TD;
+  const TargetLibraryInfo *TLI;
   DominatorTree *DT;
   typedef RecyclingAllocator<BumpPtrAllocator,
                       ScopedHashTableVal<SimpleValue, Value*> > AllocatorT=
y;
@@ -257,12 +260,77 @@
   bool runOnFunction(Function &F);
=20
 private:
- =20
+
+  // NodeScope - almost a POD, but needs to call the constructors for the
+  // scoped hash tables so that a new scope gets pushed on. These are RAII=
 so
+  // that the scope gets popped when the NodeScope is destroyed.
+  class NodeScope {
+   public:
+    NodeScope(ScopedHTType *availableValues,
+              LoadHTType *availableLoads,
+              CallHTType *availableCalls) :
+        Scope(*availableValues),
+        LoadScope(*availableLoads),
+        CallScope(*availableCalls) {}
+
+   private:
+    NodeScope(const NodeScope&); // DO NOT IMPLEMENT
+
+    ScopedHTType::ScopeTy Scope;
+    LoadHTType::ScopeTy LoadScope;
+    CallHTType::ScopeTy CallScope;
+  };
+
+  // StackNode - contains all the needed information to create a stack for
+  // doing a depth first tranversal of the tree. This includes scopes for
+  // values, loads, and calls as well as the generation. There is a child
+  // iterator so that the children do not need to be store spearately.
+  class StackNode {
+   public:
+    StackNode(ScopedHTType *availableValues,
+              LoadHTType *availableLoads,
+              CallHTType *availableCalls,
+              unsigned cg, DomTreeNode *n,
+              DomTreeNode::iterator child, DomTreeNode::iterator end) :
+        CurrentGeneration(cg), ChildGeneration(cg), Node(n),
+        ChildIter(child), EndIter(end),
+        Scopes(availableValues, availableLoads, availableCalls),
+        Processed(false) {}
+
+    // Accessors.
+    unsigned currentGeneration() { return CurrentGeneration; }
+    unsigned childGeneration() { return ChildGeneration; }
+    void childGeneration(unsigned generation) { ChildGeneration =3D genera=
tion; }
+    DomTreeNode *node() { return Node; }
+    DomTreeNode::iterator childIter() { return ChildIter; }
+    DomTreeNode *nextChild() {
+      DomTreeNode *child =3D *ChildIter;
+      ++ChildIter;
+      return child;
+    }
+    DomTreeNode::iterator end() { return EndIter; }
+    bool isProcessed() { return Processed; }
+    void process() { Processed =3D true; }
+
+   private:
+    StackNode(const StackNode&); // DO NOT IMPLEMENT
+
+    // Members.
+    unsigned CurrentGeneration;
+    unsigned ChildGeneration;
+    DomTreeNode *Node;
+    DomTreeNode::iterator ChildIter;
+    DomTreeNode::iterator EndIter;
+    NodeScope Scopes;
+    bool Processed;
+  };
+
   bool processNode(DomTreeNode *Node);
  =20
   // This transformation requires dominator postdominator info
   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
     AU.addRequired<DominatorTree>();
+    AU.addRequired<TargetLibraryInfo>();
     AU.setPreservesCFG();
   }
 };
@@ -277,22 +345,10 @@
=20
 INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
 INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
=20
 bool EarlyCSE::processNode(DomTreeNode *Node) {
-  // Define a scope in the scoped hash table.  When we are done processing=
 this
-  // domtree node and recurse back up to our parent domtree node, this wil=
l pop
-  // off all the values we install.
-  ScopedHTType::ScopeTy Scope(*AvailableValues);
- =20
-  // Define a scope for the load values so that anything we add will get
-  // popped when we recurse back up to our parent domtree node.
-  LoadHTType::ScopeTy LoadScope(*AvailableLoads);
- =20
-  // Define a scope for the call values so that anything we add will get
-  // popped when we recurse back up to our parent domtree node.
-  CallHTType::ScopeTy CallScope(*AvailableCalls);
- =20
   BasicBlock *BB =3D Node->getBlock();
  =20
   // If this block has a single predecessor, then the predecessor is the p=
arent
@@ -328,7 +384,7 @@
    =20
     // If the instruction can be simplified (e.g. X+0 =3D X) then replace =
it with
     // its simpler value.
-    if (Value *V =3D SimplifyInstruction(Inst, TD, DT)) {
+    if (Value *V =3D SimplifyInstruction(Inst, TD, TLI, DT)) {
       DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << "  to: " << *V << =
'\n');
       Inst->replaceAllUsesWith(V);
       Inst->eraseFromParent();
@@ -442,19 +498,16 @@
       }
     }
   }
- =20
-  unsigned LiveOutGeneration =3D CurrentGeneration;
-  for (DomTreeNode::iterator I =3D Node->begin(), E =3D Node->end(); I !=
=3D E; ++I) {
-    Changed |=3D processNode(*I);
-    // Pop any generation changes off the stack from the recursive walk.
-    CurrentGeneration =3D LiveOutGeneration;
-  }
+
   return Changed;
 }
=20
=20
 bool EarlyCSE::runOnFunction(Function &F) {
+  std::deque<StackNode *> nodesToProcess;
+
   TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
   DT =3D &getAnalysis<DominatorTree>();
  =20
   // Tables that the pass uses when walking the domtree.
@@ -466,5 +519,52 @@
   AvailableCalls =3D &CallTable;
  =20
   CurrentGeneration =3D 0;
-  return processNode(DT->getRootNode());
+  bool Changed =3D false;
+
+  // Process the root node.
+  nodesToProcess.push_front(
+      new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
+                    CurrentGeneration, DT->getRootNode(),
+                    DT->getRootNode()->begin(),
+                    DT->getRootNode()->end()));
+
+  // Save the current generation.
+  unsigned LiveOutGeneration =3D CurrentGeneration;
+
+  // Process the stack.
+  while (!nodesToProcess.empty()) {
+    // Grab the first item off the stack. Set the current generation, remo=
ve
+    // the node from the stack, and process it.
+    StackNode *NodeToProcess =3D nodesToProcess.front();
+
+    // Initialize class members.
+    CurrentGeneration =3D NodeToProcess->currentGeneration();
+
+    // Check if the node needs to be processed.
+    if (!NodeToProcess->isProcessed()) {
+      // Process the node.
+      Changed |=3D processNode(NodeToProcess->node());
+      NodeToProcess->childGeneration(CurrentGeneration);
+      NodeToProcess->process();
+    } else if (NodeToProcess->childIter() !=3D NodeToProcess->end()) {
+      // Push the next child onto the stack.
+      DomTreeNode *child =3D NodeToProcess->nextChild();
+      nodesToProcess.push_front(
+          new StackNode(AvailableValues,
+                        AvailableLoads,
+                        AvailableCalls,
+                        NodeToProcess->childGeneration(), child,
+                        child->begin(), child->end()));
+    } else {
+      // It has been processed, and there are no more children to process,
+      // so delete it and pop it off the stack.
+      delete NodeToProcess;
+      nodesToProcess.pop_front();
+    }
+  } // while (!nodes...)
+
+  // Reset the current generation.
+  CurrentGeneration =3D LiveOutGeneration;
+
+  return Changed;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/GVN.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/GVN.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/GVN.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -31,10 +31,12 @@
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/SSAUpdater.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DepthFirstIterator.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/Allocator.h"
@@ -83,6 +85,12 @@
         return false;
       return true;
     }
+
+    friend hash_code hash_value(const Expression &Value) {
+      return hash_combine(Value.opcode, Value.type,
+                          hash_combine_range(Value.varargs.begin(),
+                                             Value.varargs.end()));
+    }
   };
=20
   class ValueTable {
@@ -95,12 +103,17 @@
     uint32_t nextValueNumber;
=20
     Expression create_expression(Instruction* I);
+    Expression create_cmp_expression(unsigned Opcode,
+                                     CmpInst::Predicate Predicate,
+                                     Value *LHS, Value *RHS);
     Expression create_extractvalue_expression(ExtractValueInst* EI);
     uint32_t lookup_or_add_call(CallInst* C);
   public:
     ValueTable() : nextValueNumber(1) { }
     uint32_t lookup_or_add(Value *V);
     uint32_t lookup(Value *V) const;
+    uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
+                               Value *LHS, Value *RHS);
     void add(Value *V, uint32_t num);
     void clear();
     void erase(Value *v);
@@ -124,16 +137,8 @@
   }
=20
   static unsigned getHashValue(const Expression e) {
-    unsigned hash =3D e.opcode;
-
-    hash =3D ((unsigned)((uintptr_t)e.type >> 4) ^
-            (unsigned)((uintptr_t)e.type >> 9));
-
-    for (SmallVector<uint32_t, 4>::const_iterator I =3D e.varargs.begin(),
-         E =3D e.varargs.end(); I !=3D E; ++I)
-      hash =3D *I + hash * 37;
-   =20
-    return hash;
+    using llvm::hash_value;
+    return static_cast<unsigned>(hash_value(e));
   }
   static bool isEqual(const Expression &LHS, const Expression &RHS) {
     return LHS =3D=3D RHS;
@@ -153,9 +158,24 @@
   for (Instruction::op_iterator OI =3D I->op_begin(), OE =3D I->op_end();
        OI !=3D OE; ++OI)
     e.varargs.push_back(lookup_or_add(*OI));
+  if (I->isCommutative()) {
+    // Ensure that commutative instructions that only differ by a permutat=
ion
+    // of their operands get the same value number by sorting the operand =
value
+    // numbers.  Since all commutative instructions have two operands it i=
s more
+    // efficient to sort by hand rather than using, say, std::sort.
+    assert(I->getNumOperands() =3D=3D 2 && "Unsupported commutative instru=
ction!");
+    if (e.varargs[0] > e.varargs[1])
+      std::swap(e.varargs[0], e.varargs[1]);
+  }
  =20
   if (CmpInst *C =3D dyn_cast<CmpInst>(I)) {
-    e.opcode =3D (C->getOpcode() << 8) | C->getPredicate();
+    // Sort the operand value numbers so x<y and y>x get the same value nu=
mber.
+    CmpInst::Predicate Predicate =3D C->getPredicate();
+    if (e.varargs[0] > e.varargs[1]) {
+      std::swap(e.varargs[0], e.varargs[1]);
+      Predicate =3D CmpInst::getSwappedPredicate(Predicate);
+    }
+    e.opcode =3D (C->getOpcode() << 8) | Predicate;
   } else if (InsertValueInst *E =3D dyn_cast<InsertValueInst>(I)) {
     for (InsertValueInst::idx_iterator II =3D E->idx_begin(), IE =3D E->id=
x_end();
          II !=3D IE; ++II)
@@ -165,6 +185,25 @@
   return e;
 }
=20
+Expression ValueTable::create_cmp_expression(unsigned Opcode,
+                                             CmpInst::Predicate Predicate,
+                                             Value *LHS, Value *RHS) {
+  assert((Opcode =3D=3D Instruction::ICmp || Opcode =3D=3D Instruction::FC=
mp) &&
+         "Not a comparison!");
+  Expression e;
+  e.type =3D CmpInst::makeCmpResultType(LHS->getType());
+  e.varargs.push_back(lookup_or_add(LHS));
+  e.varargs.push_back(lookup_or_add(RHS));
+
+  // Sort the operand value numbers so x<y and y>x get the same value numb=
er.
+  if (e.varargs[0] > e.varargs[1]) {
+    std::swap(e.varargs[0], e.varargs[1]);
+    Predicate =3D CmpInst::getSwappedPredicate(Predicate);
+  }
+  e.opcode =3D (Opcode << 8) | Predicate;
+  return e;
+}
+
 Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI=
) {
   assert(EI !=3D 0 && "Not an ExtractValueInst?");
   Expression e;
@@ -414,6 +453,19 @@
   return VI->second;
 }
=20
+/// lookup_or_add_cmp - Returns the value number of the given comparison,
+/// assigning it a new number if it did not have one before.  Useful when
+/// we deduced the result of a comparison, but don't immediately have an
+/// instruction realizing that comparison to hand.
+uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
+                                       CmpInst::Predicate Predicate,
+                                       Value *LHS, Value *RHS) {
+  Expression exp =3D create_cmp_expression(Opcode, Predicate, LHS, RHS);
+  uint32_t& e =3D expressionNumbering[exp];
+  if (!e) e =3D nextValueNumber++;
+  return e;
+}
+
 /// clear - Remove all entries from the ValueTable.
 void ValueTable::clear() {
   valueNumbering.clear();
@@ -446,7 +498,8 @@
     MemoryDependenceAnalysis *MD;
     DominatorTree *DT;
     const TargetData *TD;
-   =20
+    const TargetLibraryInfo *TLI;
+
     ValueTable VN;
    =20
     /// LeaderTable - A mapping from value numbers to lists of Value*'s th=
at
@@ -530,6 +583,7 @@
     // This transformation requires dominator postdominator info
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<DominatorTree>();
+      AU.addRequired<TargetLibraryInfo>();
       if (!NoLoads)
         AU.addRequired<MemoryDependenceAnalysis>();
       AU.addRequired<AliasAnalysis>();
@@ -568,6 +622,7 @@
 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
=20
@@ -776,7 +831,7 @@
                                           Value *WritePtr,
                                           uint64_t WriteSizeInBits,
                                           const TargetData &TD) {
-  // If the loaded or stored value is an first class array or struct, don'=
t try
+  // If the loaded or stored value is a first class array or struct, don't=
 try
   // to transform them.  We need to be able to bitcast to integer.
   if (LoadTy->isStructTy() || LoadTy->isArrayTy())
     return -1;
@@ -973,7 +1028,7 @@
   return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
 }
=20
-/// GetStoreValueForLoad - This function is called when we have a
+/// GetLoadValueForLoad - This function is called when we have a
 /// memdep query of a load that ends up being a clobbering load.  This mea=
ns
 /// that the load *may* provide bits used by the load but we can't be sure
 /// because the pointers don't mustalias.  Check this case to see if there=
 is
@@ -1274,14 +1329,14 @@
   // If we had to process more than one hundred blocks to find the
   // dependencies, this load isn't worth worrying about.  Optimizing
   // it will be too expensive.
-  if (Deps.size() > 100)
+  unsigned NumDeps =3D Deps.size();
+  if (NumDeps > 100)
     return false;
=20
   // If we had a phi translation failure, we'll have a single entry which =
is a
   // clobber in the current block.  Reject this early.
-  if (Deps.size() =3D=3D 1
-      && !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber())
-  {
+  if (NumDeps =3D=3D 1 &&
+      !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
     DEBUG(
       dbgs() << "GVN: non-local load ";
       WriteAsOperand(dbgs(), LI);
@@ -1294,10 +1349,10 @@
   // where we have a value available in repl, also keep track of whether w=
e see
   // dependencies that produce an unknown value for the load (such as a ca=
ll
   // that could potentially clobber the load).
-  SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
-  SmallVector<BasicBlock*, 16> UnavailableBlocks;
+  SmallVector<AvailableValueInBlock, 64> ValuesPerBlock;
+  SmallVector<BasicBlock*, 64> UnavailableBlocks;
=20
-  for (unsigned i =3D 0, e =3D Deps.size(); i !=3D e; ++i) {
+  for (unsigned i =3D 0, e =3D NumDeps; i !=3D e; ++i) {
     BasicBlock *DepBB =3D Deps[i].getBB();
     MemDepResult DepInfo =3D Deps[i].getResult();
=20
@@ -1896,12 +1951,19 @@
   unsigned Count =3D 0;
   for (Value::use_iterator UI =3D From->use_begin(), UE =3D From->use_end(=
);
        UI !=3D UE; ) {
-    Instruction *User =3D cast<Instruction>(*UI);
-    unsigned OpNum =3D UI.getOperandNo();
-    ++UI;
+    Use &U =3D (UI++).getUse();
=20
-    if (DT->dominates(Root, User->getParent())) {
-      User->setOperand(OpNum, To);
+    // If From occurs as a phi node operand then the use implicitly lives =
in the
+    // corresponding incoming block.  Otherwise it is the block containing=
 the
+    // user that must be dominated by Root.
+    BasicBlock *UsingBlock;
+    if (PHINode *PN =3D dyn_cast<PHINode>(U.getUser()))
+      UsingBlock =3D PN->getIncomingBlock(U);
+    else
+      UsingBlock =3D cast<Instruction>(U.getUser())->getParent();
+
+    if (DT->dominates(Root, UsingBlock)) {
+      U.set(To);
       ++Count;
     }
   }
@@ -1912,69 +1974,119 @@
 /// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
 /// 'RHS' everywhere in the scope.  Returns whether a change was made.
 bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
-  if (LHS =3D=3D RHS) return false;
-  assert(LHS->getType() =3D=3D RHS->getType() && "Equal but types differ!"=
);
+  SmallVector<std::pair<Value*, Value*>, 4> Worklist;
+  Worklist.push_back(std::make_pair(LHS, RHS));
+  bool Changed =3D false;
=20
-  // Don't try to propagate equalities between constants.
-  if (isa<Constant>(LHS) && isa<Constant>(RHS))
-    return false;
+  while (!Worklist.empty()) {
+    std::pair<Value*, Value*> Item =3D Worklist.pop_back_val();
+    LHS =3D Item.first; RHS =3D Item.second;
=20
-  // Make sure that any constants are on the right-hand side.  In general =
the
-  // best results are obtained by placing the longest lived value on the R=
HS.
-  if (isa<Constant>(LHS))
-    std::swap(LHS, RHS);
+    if (LHS =3D=3D RHS) continue;
+    assert(LHS->getType() =3D=3D RHS->getType() && "Equality but unequal t=
ypes!");
=20
-  // If neither term is constant then bail out.  This is not for correctne=
ss,
-  // it's just that the non-constant case is much less useful: it occurs j=
ust
-  // as often as the constant case but handling it hardly ever results in =
an
-  // improvement.
-  if (!isa<Constant>(RHS))
-    return false;
+    // Don't try to propagate equalities between constants.
+    if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
=20
-  // If value numbering later deduces that an instruction in the scope is =
equal
-  // to 'LHS' then ensure it will be turned into 'RHS'.
-  addToLeaderTable(VN.lookup_or_add(LHS), RHS, Root);
+    // Prefer a constant on the right-hand side, or an Argument if no cons=
tants.
+    if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
+      std::swap(LHS, RHS);
+    assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected va=
lue!");
=20
-  // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.
-  unsigned NumReplacements =3D replaceAllDominatedUsesWith(LHS, RHS, Root);
-  bool Changed =3D NumReplacements > 0;
-  NumGVNEqProp +=3D NumReplacements;
+    // If there is no obvious reason to prefer the left-hand side over the=
 right-
+    // hand side, ensure the longest lived term is on the right-hand side,=
 so the
+    // shortest lived term will be replaced by the longest lived.  This te=
nds to
+    // expose more simplifications.
+    uint32_t LVN =3D VN.lookup_or_add(LHS);
+    if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
+        (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
+      // Move the 'oldest' value to the right-hand side, using the value n=
umber as
+      // a proxy for age.
+      uint32_t RVN =3D VN.lookup_or_add(RHS);
+      if (LVN < RVN) {
+        std::swap(LHS, RHS);
+        LVN =3D RVN;
+      }
+    }
+    assert((!isa<Instruction>(RHS) ||
+            DT->properlyDominates(cast<Instruction>(RHS)->getParent(), Roo=
t)) &&
+           "Instruction doesn't dominate scope!");
=20
-  // Now try to deduce additional equalities from this one.  For example, =
if the
-  // known equality was "(A !=3D B)" =3D=3D "false" then it follows that A=
 and B are
-  // equal in the scope.  Only boolean equalities with an explicit true or=
 false
-  // RHS are currently supported.
-  if (!RHS->getType()->isIntegerTy(1))
-    // Not a boolean equality - bail out.
-    return Changed;
-  ConstantInt *CI =3D dyn_cast<ConstantInt>(RHS);
-  if (!CI)
-    // RHS neither 'true' nor 'false' - bail out.
-    return Changed;
-  // Whether RHS equals 'true'.  Otherwise it equals 'false'.
-  bool isKnownTrue =3D CI->isAllOnesValue();
-  bool isKnownFalse =3D !isKnownTrue;
+    // If value numbering later deduces that an instruction in the scope i=
s equal
+    // to 'LHS' then ensure it will be turned into 'RHS'.
+    addToLeaderTable(LVN, RHS, Root);
=20
-  // If "A && B" is known true then both A and B are known true.  If "A ||=
 B"
-  // is known false then both A and B are known false.
-  Value *A, *B;
-  if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
-      (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
-    Changed |=3D propagateEquality(A, RHS, Root);
-    Changed |=3D propagateEquality(B, RHS, Root);
-    return Changed;
-  }
+    // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope=
.  As
+    // LHS always has at least one use that is not dominated by Root, this=
 will
+    // never do anything if LHS has only one use.
+    if (!LHS->hasOneUse()) {
+      unsigned NumReplacements =3D replaceAllDominatedUsesWith(LHS, RHS, R=
oot);
+      Changed |=3D NumReplacements > 0;
+      NumGVNEqProp +=3D NumReplacements;
+    }
=20
-  // If we are propagating an equality like "(A =3D=3D B)" =3D=3D "true" t=
hen also
-  // propagate the equality A =3D=3D B.
-  if (ICmpInst *Cmp =3D dyn_cast<ICmpInst>(LHS)) {
-    // Only equality comparisons are supported.
-    if ((isKnownTrue && Cmp->getPredicate() =3D=3D CmpInst::ICMP_EQ) ||
-        (isKnownFalse && Cmp->getPredicate() =3D=3D CmpInst::ICMP_NE)) {
+    // Now try to deduce additional equalities from this one.  For example=
, if the
+    // known equality was "(A !=3D B)" =3D=3D "false" then it follows that=
 A and B are
+    // equal in the scope.  Only boolean equalities with an explicit true =
or false
+    // RHS are currently supported.
+    if (!RHS->getType()->isIntegerTy(1))
+      // Not a boolean equality - bail out.
+      continue;
+    ConstantInt *CI =3D dyn_cast<ConstantInt>(RHS);
+    if (!CI)
+      // RHS neither 'true' nor 'false' - bail out.
+      continue;
+    // Whether RHS equals 'true'.  Otherwise it equals 'false'.
+    bool isKnownTrue =3D CI->isAllOnesValue();
+    bool isKnownFalse =3D !isKnownTrue;
+
+    // If "A && B" is known true then both A and B are known true.  If "A =
|| B"
+    // is known false then both A and B are known false.
+    Value *A, *B;
+    if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
+        (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
+      Worklist.push_back(std::make_pair(A, RHS));
+      Worklist.push_back(std::make_pair(B, RHS));
+      continue;
+    }
+
+    // If we are propagating an equality like "(A =3D=3D B)" =3D=3D "true"=
 then also
+    // propagate the equality A =3D=3D B.  When propagating a comparison s=
uch as
+    // "(A >=3D B)" =3D=3D "true", replace all instances of "A < B" with "=
false".
+    if (ICmpInst *Cmp =3D dyn_cast<ICmpInst>(LHS)) {
       Value *Op0 =3D Cmp->getOperand(0), *Op1 =3D Cmp->getOperand(1);
-      Changed |=3D propagateEquality(Op0, Op1, Root);
+
+      // If "A =3D=3D B" is known true, or "A !=3D B" is known false, then=
 replace
+      // A with B everywhere in the scope.
+      if ((isKnownTrue && Cmp->getPredicate() =3D=3D CmpInst::ICMP_EQ) ||
+          (isKnownFalse && Cmp->getPredicate() =3D=3D CmpInst::ICMP_NE))
+        Worklist.push_back(std::make_pair(Op0, Op1));
+
+      // If "A >=3D B" is known true, replace "A < B" with false everywher=
e.
+      CmpInst::Predicate NotPred =3D Cmp->getInversePredicate();
+      Constant *NotVal =3D ConstantInt::get(Cmp->getType(), isKnownFalse);
+      // Since we don't have the instruction "A < B" immediately to hand, =
work out
+      // the value number that it would have and use that to find an appro=
priate
+      // instruction (if any).
+      uint32_t NextNum =3D VN.getNextUnusedValueNumber();
+      uint32_t Num =3D VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0=
, Op1);
+      // If the number we were assigned was brand new then there is no poi=
nt in
+      // looking for an instruction realizing it: there cannot be one!
+      if (Num < NextNum) {
+        Value *NotCmp =3D findLeader(Root, Num);
+        if (NotCmp && isa<Instruction>(NotCmp)) {
+          unsigned NumReplacements =3D
+            replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
+          Changed |=3D NumReplacements > 0;
+          NumGVNEqProp +=3D NumReplacements;
+        }
+      }
+      // Ensure that any instruction in scope that gets the "A < B" value =
number
+      // is replaced with false.
+      addToLeaderTable(Num, NotVal, Root);
+
+      continue;
     }
-    return Changed;
   }
=20
   return Changed;
@@ -1985,35 +2097,15 @@
 /// particular 'Dst' must not be reachable via another edge from 'Src'.
 static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
                                        DominatorTree *DT) {
-  // First off, there must not be more than one edge from Src to Dst, there
-  // should be exactly one.  So keep track of the number of times Src occu=
rs
-  // as a predecessor of Dst and fail if it's more than once.  Secondly, a=
ny
-  // other predecessors of Dst should be dominated by Dst (see logic below=
).
-  bool SawEdgeFromSrc =3D false;
-  for (pred_iterator PI =3D pred_begin(Dst), PE =3D pred_end(Dst); PI !=3D=
 PE; ++PI) {
-    BasicBlock *Pred =3D *PI;
-    if (Pred =3D=3D Src) {
-      // An edge from Src to Dst.
-      if (SawEdgeFromSrc)
-        // There are multiple edges from Src to Dst - fail.
-        return false;
-      SawEdgeFromSrc =3D true;
-      continue;
-    }
-    // If the predecessor is not dominated by Dst, then it must be possibl=
e to
-    // reach it either without passing through Src (and thus not via the e=
dge)
-    // or by passing through Src but taking a different edge out of Src.  =
Either
-    // way it is possible to reach Dst without passing via the edge, so fa=
il.
-    if (!DT->dominates(Dst, *PI))
-      return false;
-  }
-  assert(SawEdgeFromSrc && "No edge between these basic blocks!");
-
-  // Every path from the entry block to Dst must at some point pass to Dst=
 from
-  // a predecessor that is not dominated by Dst.  This predecessor can onl=
y be
-  // Src, since all others are dominated by Dst.  As there is only one edg=
e from
-  // Src to Dst, the path passes by this edge.
-  return true;
+  // While in theory it is interesting to consider the case in which Dst h=
as
+  // more than one predecessor, because Dst might be part of a loop which =
is
+  // only reachable from Src, in practice it is pointless since at the time
+  // GVN runs all such loops have preheaders, which means that Dst will ha=
ve
+  // been changed to have only one predecessor, namely Src.
+  BasicBlock *Pred =3D Dst->getSinglePredecessor();
+  assert((!Pred || Pred =3D=3D Src) && "No edge between these basic blocks=
!");
+  (void)Src;
+  return Pred !=3D 0;
 }
=20
 /// processInstruction - When calculating availability, handle an instruct=
ion
@@ -2027,7 +2119,7 @@
   // to value numbering it.  Value numbering often exposes redundancies, f=
or
   // example if it determines that %y is equal to %x then the instruction
   // "%z =3D and i32 %x, %y" becomes "%z =3D and i32 %x, %x" which we now =
simplify.
-  if (Value *V =3D SimplifyInstruction(I, TD, DT)) {
+  if (Value *V =3D SimplifyInstruction(I, TD, TLI, DT)) {
     I->replaceAllUsesWith(V);
     if (MD && V->getType()->isPointerTy())
       MD->invalidateCachedPointerInfo(V);
@@ -2076,16 +2168,17 @@
     Value *SwitchCond =3D SI->getCondition();
     BasicBlock *Parent =3D SI->getParent();
     bool Changed =3D false;
-    for (unsigned i =3D 1, e =3D SI->getNumCases(); i !=3D e; ++i) {
-      BasicBlock *Dst =3D SI->getSuccessor(i);
+    for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end();
+         i !=3D e; ++i) {
+      BasicBlock *Dst =3D i.getCaseSuccessor();
       if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
-        Changed |=3D propagateEquality(SwitchCond, SI->getCaseValue(i), Ds=
t);
+        Changed |=3D propagateEquality(SwitchCond, i.getCaseValue(), Dst);
     }
     return Changed;
   }
=20
   // Instructions with void type don't return a value, so there's
-  // no point in trying to find redudancies in them.
+  // no point in trying to find redundancies in them.
   if (I->getType()->isVoidTy()) return false;
  =20
   uint32_t NextNum =3D VN.getNextUnusedValueNumber();
@@ -2101,7 +2194,7 @@
   // If the number we were assigned was a brand new VN, then we don't
   // need to do a lookup to see if the number already exists
   // somewhere in the domtree: it can't!
-  if (Num =3D=3D NextNum) {
+  if (Num >=3D NextNum) {
     addToLeaderTable(Num, I, I->getParent());
     return false;
   }
@@ -2129,6 +2222,7 @@
     MD =3D &getAnalysis<MemoryDependenceAnalysis>();
   DT =3D &getAnalysis<DominatorTree>();
   TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
   VN.setMemDep(MD);
   VN.setDomTree(DT);
@@ -2241,7 +2335,14 @@
           CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
           isa<DbgInfoIntrinsic>(CurInst))
         continue;
-     =20
+
+      // Don't do PRE on compares. The PHI would prevent CodeGenPrepare fr=
om
+      // sinking the compare again, and it would force the code generator =
to
+      // move the i1 from processor flags or predicate registers into a ge=
neral
+      // purpose register.
+      if (isa<CmpInst>(CurInst))
+        continue;
+
       // We don't currently value number ANY inline asm calls.
       if (CallInst *CallI =3D dyn_cast<CallInst>(CurInst))
         if (CallI->isInlineAsm())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/IndVarSimplify.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -33,7 +33,6 @@
 #include "llvm/LLVMContext.h"
 #include "llvm/Type.h"
 #include "llvm/Analysis/Dominators.h"
-#include "llvm/Analysis/IVUsers.h"
 #include "llvm/Analysis/ScalarEvolutionExpander.h"
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/LoopPass.h"
@@ -50,30 +49,21 @@
 #include "llvm/ADT/Statistic.h"
 using namespace llvm;
=20
-STATISTIC(NumRemoved     , "Number of aux indvars removed");
 STATISTIC(NumWidened     , "Number of indvars widened");
-STATISTIC(NumInserted    , "Number of canonical indvars added");
 STATISTIC(NumReplaced    , "Number of exit values replaced");
 STATISTIC(NumLFTR        , "Number of loop exit tests replaced");
 STATISTIC(NumElimExt     , "Number of IV sign/zero extends eliminated");
 STATISTIC(NumElimIV      , "Number of congruent IVs eliminated");
=20
-namespace llvm {
-  cl::opt<bool> EnableIVRewrite(
-    "enable-iv-rewrite", cl::Hidden,
-    cl::desc("Enable canonical induction variable rewriting"));
-
-  // Trip count verification can be enabled by default under NDEBUG if we
-  // implement a strong expression equivalence checker in SCEV. Until then=
, we
-  // use the verify-indvars flag, which may assert in some cases.
-  cl::opt<bool> VerifyIndvars(
-    "verify-indvars", cl::Hidden,
-    cl::desc("Verify the ScalarEvolution result after running indvars"));
-}
+// Trip count verification can be enabled by default under NDEBUG if we
+// implement a strong expression equivalence checker in SCEV. Until then, =
we
+// use the verify-indvars flag, which may assert in some cases.
+static cl::opt<bool> VerifyIndvars(
+  "verify-indvars", cl::Hidden,
+  cl::desc("Verify the ScalarEvolution result after running indvars"));
=20
 namespace {
   class IndVarSimplify : public LoopPass {
-    IVUsers         *IU;
     LoopInfo        *LI;
     ScalarEvolution *SE;
     DominatorTree   *DT;
@@ -84,7 +74,7 @@
   public:
=20
     static char ID; // Pass identification, replacement for typeid
-    IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0),
+    IndVarSimplify() : LoopPass(ID), LI(0), SE(0), DT(0), TD(0),
                        Changed(false) {
       initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
     }
@@ -97,13 +87,9 @@
       AU.addRequired<ScalarEvolution>();
       AU.addRequiredID(LoopSimplifyID);
       AU.addRequiredID(LCSSAID);
-      if (EnableIVRewrite)
-        AU.addRequired<IVUsers>();
       AU.addPreserved<ScalarEvolution>();
       AU.addPreservedID(LoopSimplifyID);
       AU.addPreservedID(LCSSAID);
-      if (EnableIVRewrite)
-        AU.addPreserved<IVUsers>();
       AU.setPreservesCFG();
     }
=20
@@ -121,8 +107,6 @@
=20
     void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
=20
-    void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
-
     Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCou=
nt,
                                      PHINode *IndVar, SCEVExpander &Rewrit=
er);
=20
@@ -138,7 +122,6 @@
 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
 INITIALIZE_PASS_DEPENDENCY(LCSSA)
-INITIALIZE_PASS_DEPENDENCY(IVUsers)
 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
                 "Induction Variable Simplification", false, false)
=20
@@ -180,6 +163,11 @@
     // base of a recurrence. This handles the case in which SCEV expansion
     // converts a pointer type recurrence into a nonrecurrent pointer base
     // indexed by an integer recurrence.
+
+    // If the GEP base pointer is a vector of pointers, abort.
+    if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointer=
Ty())
+      return false;
+
     const SCEV *FromBase =3D SE->getPointerBase(SE->getSCEV(FromPtr));
     const SCEV *ToBase =3D SE->getPointerBase(SE->getSCEV(ToPtr));
     if (FromBase =3D=3D ToBase)
@@ -445,11 +433,6 @@
     PN->replaceAllUsesWith(Conv);
     RecursivelyDeleteTriviallyDeadInstructions(PN);
   }
-
-  // Add a new IVUsers entry for the newly-created integer PHI.
-  if (IU)
-    IU->AddUsersIfInteresting(NewPHI);
-
   Changed =3D true;
 }
=20
@@ -595,124 +578,6 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//  Rewrite IV users based on a canonical IV.
-//  Only for use with -enable-iv-rewrite.
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-/// FIXME: It is an extremely bad idea to indvar substitute anything more
-/// complex than affine induction variables.  Doing so will put expensive
-/// polynomial evaluations inside of the loop, and the str reduction pass
-/// currently can only reduce affine polynomials.  For now just disable
-/// indvar subst on anything more complex than an affine addrec, unless
-/// it can be expanded to a trivial value.
-static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
-  // Loop-invariant values are safe.
-  if (SE->isLoopInvariant(S, L)) return true;
-
-  // Affine addrecs are safe. Non-affine are not, because LSR doesn't know=
 how
-  // to transform them into efficient code.
-  if (const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(S))
-    return AR->isAffine();
-
-  // An add is safe it all its operands are safe.
-  if (const SCEVCommutativeExpr *Commutative
-      =3D dyn_cast<SCEVCommutativeExpr>(S)) {
-    for (SCEVCommutativeExpr::op_iterator I =3D Commutative->op_begin(),
-         E =3D Commutative->op_end(); I !=3D E; ++I)
-      if (!isSafe(*I, L, SE)) return false;
-    return true;
-  }
-
-  // A cast is safe if its operand is.
-  if (const SCEVCastExpr *C =3D dyn_cast<SCEVCastExpr>(S))
-    return isSafe(C->getOperand(), L, SE);
-
-  // A udiv is safe if its operands are.
-  if (const SCEVUDivExpr *UD =3D dyn_cast<SCEVUDivExpr>(S))
-    return isSafe(UD->getLHS(), L, SE) &&
-           isSafe(UD->getRHS(), L, SE);
-
-  // SCEVUnknown is always safe.
-  if (isa<SCEVUnknown>(S))
-    return true;
-
-  // Nothing else is safe.
-  return false;
-}
-
-void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter)=
 {
-  // Rewrite all induction variable expressions in terms of the canonical
-  // induction variable.
-  //
-  // If there were induction variables of other sizes or offsets, manually
-  // add the offsets to the primary induction variable and cast, avoiding
-  // the need for the code evaluation methods to insert induction variables
-  // of different sizes.
-  for (IVUsers::iterator UI =3D IU->begin(), E =3D IU->end(); UI !=3D E; +=
+UI) {
-    Value *Op =3D UI->getOperandValToReplace();
-    Type *UseTy =3D Op->getType();
-    Instruction *User =3D UI->getUser();
-
-    // Compute the final addrec to expand into code.
-    const SCEV *AR =3D IU->getReplacementExpr(*UI);
-
-    // Evaluate the expression out of the loop, if possible.
-    if (!L->contains(UI->getUser())) {
-      const SCEV *ExitVal =3D SE->getSCEVAtScope(AR, L->getParentLoop());
-      if (SE->isLoopInvariant(ExitVal, L))
-        AR =3D ExitVal;
-    }
-
-    // FIXME: It is an extremely bad idea to indvar substitute anything mo=
re
-    // complex than affine induction variables.  Doing so will put expensi=
ve
-    // polynomial evaluations inside of the loop, and the str reduction pa=
ss
-    // currently can only reduce affine polynomials.  For now just disable
-    // indvar subst on anything more complex than an affine addrec, unless
-    // it can be expanded to a trivial value.
-    if (!isSafe(AR, L, SE))
-      continue;
-
-    // Determine the insertion point for this user. By default, insert
-    // immediately before the user. The SCEVExpander class will automatica=
lly
-    // hoist loop invariants out of the loop. For PHI nodes, there may be
-    // multiple uses, so compute the nearest common dominator for the
-    // incoming blocks.
-    Instruction *InsertPt =3D getInsertPointForUses(User, Op, DT);
-
-    // Now expand it into actual Instructions and patch it into place.
-    Value *NewVal =3D Rewriter.expandCodeFor(AR, UseTy, InsertPt);
-
-    DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
-                 << "   into =3D " << *NewVal << "\n");
-
-    if (!isValidRewrite(Op, NewVal)) {
-      DeadInsts.push_back(NewVal);
-      continue;
-    }
-    // Inform ScalarEvolution that this value is changing. The change does=
n't
-    // affect its value, but it does potentially affect which use lists the
-    // value will be on after the replacement, which affects ScalarEvoluti=
on's
-    // ability to walk use lists and drop dangling pointers when a value is
-    // deleted.
-    SE->forgetValue(User);
-
-    // Patch the new value into place.
-    if (Op->hasName())
-      NewVal->takeName(Op);
-    if (Instruction *NewValI =3D dyn_cast<Instruction>(NewVal))
-      NewValI->setDebugLoc(User->getDebugLoc());
-    User->replaceUsesOfWith(Op, NewVal);
-    UI->setOperandValToReplace(NewVal);
-
-    ++NumRemoved;
-    Changed =3D true;
-
-    // The old value may be dead now.
-    DeadInsts.push_back(Op);
-  }
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  IV Widening - Extend the width of an IV to cover its widest uses.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -843,7 +708,7 @@
=20
   const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
=20
-  Instruction *WidenIVUse(NarrowIVDefUse DU);
+  Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
=20
   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
 };
@@ -917,7 +782,6 @@
     }
     return WideBO;
   }
-  llvm_unreachable(0);
 }
=20
 /// No-wrap operations can transfer sign extension of their result to their
@@ -946,9 +810,13 @@
   else
     return 0;
=20
+  // When creating this AddExpr, don't apply the current operations NSW or=
 NUW
+  // flags. This instruction may be guarded by control flow that the no-wr=
ap
+  // behavior depends on. Non-control-equivalent instructions can be mappe=
d to
+  // the same SCEV expression, and it would be incorrect to transfer NSW/N=
UW
+  // semantics to those operations.
   const SCEVAddRecExpr *AddRec =3D dyn_cast<SCEVAddRecExpr>(
-    SE->getAddExpr(SE->getSCEV(DU.WideDef), ExtendOperExpr,
-                   IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW));
+    SE->getAddExpr(SE->getSCEV(DU.WideDef), ExtendOperExpr));
=20
   if (!AddRec || AddRec->getLoop() !=3D L)
     return 0;
@@ -983,7 +851,7 @@
=20
 /// WidenIVUse - Determine whether an individual user of the narrow IV can=
 be
 /// widened. If so, return the wide clone of the user.
-Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU) {
+Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter=
) {
=20
   // Stop traversing the def-use chain at inner-loop phis or post-loop phi=
s.
   if (isa<PHINode>(DU.NarrowUse) &&
@@ -1051,7 +919,7 @@
   // NarrowUse.
   Instruction *WideUse =3D 0;
   if (WideAddRec =3D=3D WideIncExpr
-      && SCEVExpander::hoistStep(WideInc, DU.NarrowUse, DT))
+      && Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
     WideUse =3D WideInc;
   else {
     WideUse =3D CloneIVUser(DU);
@@ -1156,7 +1024,7 @@
=20
     // Process a def-use edge. This may replace the use, so don't hold a
     // use_iterator across it.
-    Instruction *WideUse =3D WidenIVUse(DU);
+    Instruction *WideUse =3D WidenIVUse(DU, Rewriter);
=20
     // Follow all def-use edges from the previous narrow use.
     if (WideUse)
@@ -1231,7 +1099,11 @@
 /// BackedgeTakenInfo. If these expressions have not been reduced, then
 /// expanding them may incur additional cost (albeit in the loop preheader=
).
 static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
+                                SmallPtrSet<const SCEV*, 8> &Processed,
                                 ScalarEvolution *SE) {
+  if (!Processed.insert(S))
+    return false;
+
   // If the backedge-taken count is a UDiv, it's very likely a UDiv that
   // ScalarEvolution's HowFarToZero or HowManyLessThans produced to comput=
e a
   // precise expression, rather than a UDiv from the user's code. If we ca=
n't
@@ -1250,16 +1122,13 @@
     }
   }
=20
-  if (EnableIVRewrite)
-    return false;
-
   // Recurse past add expressions, which commonly occur in the
   // BackedgeTakenCount. They may already exist in program code, and if no=
t,
   // they are not too expensive rematerialize.
   if (const SCEVAddExpr *Add =3D dyn_cast<SCEVAddExpr>(S)) {
     for (SCEVAddExpr::op_iterator I =3D Add->op_begin(), E =3D Add->op_end=
();
          I !=3D E; ++I) {
-      if (isHighCostExpansion(*I, BI, SE))
+      if (isHighCostExpansion(*I, BI, Processed, SE))
         return true;
     }
     return false;
@@ -1270,14 +1139,24 @@
   if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
     return true;
=20
-  // If we haven't recognized an expensive SCEV patter, assume its an expr=
ession
-  // produced by program code.
+  // If we haven't recognized an expensive SCEV pattern, assume it's an
+  // expression produced by program code.
   return false;
 }
=20
 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
 /// count expression can be safely and cheaply expanded into an instruction
 /// sequence that can be used by LinearFunctionTestReplace.
+///
+/// TODO: This fails for pointer-type loop counters with greater than one =
byte
+/// strides, consequently preventing LFTR from running. For the purpose of=
 LFTR
+/// we could skip this check in the case that the LFTR loop counter (chose=
n by
+/// FindLoopCounter) is also pointer type. Instead, we could directly conv=
ert
+/// the loop test to an inequality test by checking the target data's alig=
nment
+/// of element types (given that the initial pointer value originates from=
 or is
+/// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
+/// However, we don't yet have a strong motivation for converting loop tes=
ts
+/// into inequality tests.
 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
   const SCEV *BackedgeTakenCount =3D SE->getBackedgeTakenCount(L);
   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
@@ -1292,42 +1171,13 @@
   if (!BI)
     return false;
=20
-  if (isHighCostExpansion(BackedgeTakenCount, BI, SE))
+  SmallPtrSet<const SCEV*, 8> Processed;
+  if (isHighCostExpansion(BackedgeTakenCount, BI, Processed, SE))
     return false;
=20
   return true;
 }
=20
-/// getBackedgeIVType - Get the widest type used by the loop test after pe=
eking
-/// through Truncs.
-///
-/// TODO: Unnecessary when ForceLFTR is removed.
-static Type *getBackedgeIVType(Loop *L) {
-  if (!L->getExitingBlock())
-    return 0;
-
-  // Can't rewrite non-branch yet.
-  BranchInst *BI =3D dyn_cast<BranchInst>(L->getExitingBlock()->getTermina=
tor());
-  if (!BI)
-    return 0;
-
-  ICmpInst *Cond =3D dyn_cast<ICmpInst>(BI->getCondition());
-  if (!Cond)
-    return 0;
-
-  Type *Ty =3D 0;
-  for(User::op_iterator OI =3D Cond->op_begin(), OE =3D Cond->op_end();
-      OI !=3D OE; ++OI) {
-    assert((!Ty || Ty =3D=3D (*OI)->getType()) && "bad icmp operand types"=
);
-    TruncInst *Trunc =3D dyn_cast<TruncInst>(*OI);
-    if (!Trunc)
-      continue;
-
-    return Trunc->getSrcTy();
-  }
-  return Ty;
-}
-
 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
 /// invariant value to the phi.
 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *=
DT) {
@@ -1429,6 +1279,10 @@
=20
 /// FindLoopCounter - Find an affine IV in canonical form.
 ///
+/// BECount may be an i8* pointer type. The pointer difference is already
+/// valid count without scaling the address stride, so it remains a pointer
+/// expression as far as SCEV is concerned.
+///
 /// FIXME: Accept -1 stride and set IVLimit =3D IVInit - BECount
 ///
 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Str=
ide.
@@ -1437,11 +1291,6 @@
 static PHINode *
 FindLoopCounter(Loop *L, const SCEV *BECount,
                 ScalarEvolution *SE, DominatorTree *DT, const TargetData *=
TD) {
-  // I'm not sure how BECount could be a pointer type, but we definitely d=
on't
-  // want to LFTR that.
-  if (BECount->getType()->isPointerTy())
-    return 0;
-
   uint64_t BCWidth =3D SE->getTypeSizeInBits(BECount->getType());
=20
   Value *Cond =3D
@@ -1458,6 +1307,10 @@
     if (!SE->isSCEVable(Phi->getType()))
       continue;
=20
+    // Avoid comparing an integer IV against a pointer Limit.
+    if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy(=
))
+      continue;
+
     const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi)=
);
     if (!AR || AR->getLoop() !=3D L || !AR->isAffine())
       continue;
@@ -1503,6 +1356,82 @@
   return BestPhi;
 }
=20
+/// genLoopLimit - Help LinearFunctionTestReplace by generating a value th=
at
+/// holds the RHS of the new loop test.
+static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
+                           SCEVExpander &Rewriter, ScalarEvolution *SE) {
+  const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar=
));
+  assert(AR && AR->getLoop() =3D=3D L && AR->isAffine() && "bad loop count=
er");
+  const SCEV *IVInit =3D AR->getStart();
+
+  // IVInit may be a pointer while IVCount is an integer when FindLoopCoun=
ter
+  // finds a valid pointer IV. Sign extend BECount in order to materialize=
 a
+  // GEP. Avoid running SCEVExpander on a new pointer value, instead reusi=
ng
+  // the existing GEPs whenever possible.
+  if (IndVar->getType()->isPointerTy()
+      && !IVCount->getType()->isPointerTy()) {
+
+    Type *OfsTy =3D SE->getEffectiveSCEVType(IVInit->getType());
+    const SCEV *IVOffset =3D SE->getTruncateOrSignExtend(IVCount, OfsTy);
+
+    // Expand the code for the iteration count.
+    assert(SE->isLoopInvariant(IVOffset, L) &&
+           "Computed iteration count is not loop invariant!");
+    BranchInst *BI =3D cast<BranchInst>(L->getExitingBlock()->getTerminato=
r());
+    Value *GEPOffset =3D Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
+
+    Value *GEPBase =3D IndVar->getIncomingValueForBlock(L->getLoopPreheade=
r());
+    assert(AR->getStart() =3D=3D SE->getSCEV(GEPBase) && "bad loop counter=
");
+    // We could handle pointer IVs other than i8*, but we need to compensa=
te for
+    // gep index scaling. See canExpandBackedgeTakenCount comments.
+    assert(SE->getSizeOfExpr(
+             cast<PointerType>(GEPBase->getType())->getElementType())->isO=
ne()
+           && "unit stride pointer IV must be i8*");
+
+    IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
+    return Builder.CreateGEP(GEPBase, GEPOffset, "lftr.limit");
+  }
+  else {
+    // In any other case, convert both IVInit and IVCount to integers befo=
re
+    // comparing. This may result in SCEV expension of pointers, but in pr=
actice
+    // SCEV will fold the pointer arithmetic away as such:
+    // BECount =3D (IVEnd - IVInit - 1) =3D> IVLimit =3D IVInit (postinc).
+    //
+    // Valid Cases: (1) both integers is most common; (2) both may be poin=
ters
+    // for simple memset-style loops; (3) IVInit is an integer and IVCount=
 is a
+    // pointer may occur when enable-iv-rewrite generates a canonical IV o=
n top
+    // of case #2.
+
+    const SCEV *IVLimit =3D 0;
+    // For unit stride, IVCount =3D Start + BECount with 2's complement ov=
erflow.
+    // For non-zero Start, compute IVCount here.
+    if (AR->getStart()->isZero())
+      IVLimit =3D IVCount;
+    else {
+      assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit str=
ide");
+      const SCEV *IVInit =3D AR->getStart();
+
+      // For integer IVs, truncate the IV before computing IVInit + BECoun=
t.
+      if (SE->getTypeSizeInBits(IVInit->getType())
+          > SE->getTypeSizeInBits(IVCount->getType()))
+        IVInit =3D SE->getTruncateExpr(IVInit, IVCount->getType());
+
+      IVLimit =3D SE->getAddExpr(IVInit, IVCount);
+    }
+    // Expand the code for the iteration count.
+    BranchInst *BI =3D cast<BranchInst>(L->getExitingBlock()->getTerminato=
r());
+    IRBuilder<> Builder(BI);
+    assert(SE->isLoopInvariant(IVLimit, L) &&
+           "Computed iteration count is not loop invariant!");
+    // Ensure that we generate the same type as IndVar, or a smaller integ=
er
+    // type. In the presence of null pointer values, we have an integer ty=
pe
+    // SCEV expression (IVInit) for a pointer type IV value (IndVar).
+    Type *LimitTy =3D IVCount->getType()->isPointerTy() ?
+      IndVar->getType() : IVCount->getType();
+    return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
+  }
+}
+
 /// LinearFunctionTestReplace - This method rewrites the exit condition of=
 the
 /// loop to be a canonical !=3D comparison against the incremented loop in=
duction
 /// variable.  This pass is able to rewrite the exit tests of any loop whe=
re the
@@ -1514,37 +1443,35 @@
                           PHINode *IndVar,
                           SCEVExpander &Rewriter) {
   assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
-  BranchInst *BI =3D cast<BranchInst>(L->getExitingBlock()->getTerminator(=
));
=20
   // LFTR can ignore IV overflow and truncate to the width of
   // BECount. This avoids materializing the add(zext(add)) expression.
-  Type *CntTy =3D !EnableIVRewrite ?
-    BackedgeTakenCount->getType() : IndVar->getType();
+  Type *CntTy =3D BackedgeTakenCount->getType();
=20
-  const SCEV *IVLimit =3D BackedgeTakenCount;
+  const SCEV *IVCount =3D BackedgeTakenCount;
=20
-  // If the exiting block is not the same as the backedge block, we must c=
ompare
-  // against the preincremented value, otherwise we prefer to compare agai=
nst
-  // the post-incremented value.
+  // If the exiting block is the same as the backedge block, we prefer to
+  // compare against the post-incremented value, otherwise we must compare
+  // against the preincremented value.
   Value *CmpIndVar;
   if (L->getExitingBlock() =3D=3D L->getLoopLatch()) {
     // Add one to the "backedge-taken" count to get the trip count.
     // If this addition may overflow, we have to be more pessimistic and
     // cast the induction variable before doing the add.
     const SCEV *N =3D
-      SE->getAddExpr(IVLimit, SE->getConstant(IVLimit->getType(), 1));
-    if (CntTy =3D=3D IVLimit->getType())
-      IVLimit =3D N;
+      SE->getAddExpr(IVCount, SE->getConstant(IVCount->getType(), 1));
+    if (CntTy =3D=3D IVCount->getType())
+      IVCount =3D N;
     else {
-      const SCEV *Zero =3D SE->getConstant(IVLimit->getType(), 0);
+      const SCEV *Zero =3D SE->getConstant(IVCount->getType(), 0);
       if ((isa<SCEVConstant>(N) && !N->isZero()) ||
           SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
         // No overflow. Cast the sum.
-        IVLimit =3D SE->getTruncateOrZeroExtend(N, CntTy);
+        IVCount =3D SE->getTruncateOrZeroExtend(N, CntTy);
       } else {
         // Potential overflow. Cast before doing the add.
-        IVLimit =3D SE->getTruncateOrZeroExtend(IVLimit, CntTy);
-        IVLimit =3D SE->getAddExpr(IVLimit, SE->getConstant(CntTy, 1));
+        IVCount =3D SE->getTruncateOrZeroExtend(IVCount, CntTy);
+        IVCount =3D SE->getAddExpr(IVCount, SE->getConstant(CntTy, 1));
       }
     }
     // The BackedgeTaken expression contains the number of times that the
@@ -1552,62 +1479,17 @@
     // number of times the loop executes, so use the incremented indvar.
     CmpIndVar =3D IndVar->getIncomingValueForBlock(L->getExitingBlock());
   } else {
-    // We have to use the preincremented value...
-    IVLimit =3D SE->getTruncateOrZeroExtend(IVLimit, CntTy);
+    // We must use the preincremented value...
+    IVCount =3D SE->getTruncateOrZeroExtend(IVCount, CntTy);
     CmpIndVar =3D IndVar;
   }
=20
-  // For unit stride, IVLimit =3D Start + BECount with 2's complement over=
flow.
-  // So for, non-zero start compute the IVLimit here.
-  bool isPtrIV =3D false;
-  Type *CmpTy =3D CntTy;
-  const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar=
));
-  assert(AR && AR->getLoop() =3D=3D L && AR->isAffine() && "bad loop count=
er");
-  if (!AR->getStart()->isZero()) {
-    assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit strid=
e");
-    const SCEV *IVInit =3D AR->getStart();
-
-    // For pointer types, sign extend BECount in order to materialize a GE=
P.
-    // Note that for without EnableIVRewrite, we never run SCEVExpander on=
 a
-    // pointer type, because we must preserve the existing GEPs. Instead we
-    // directly generate a GEP later.
-    if (IVInit->getType()->isPointerTy()) {
-      isPtrIV =3D true;
-      CmpTy =3D SE->getEffectiveSCEVType(IVInit->getType());
-      IVLimit =3D SE->getTruncateOrSignExtend(IVLimit, CmpTy);
-    }
-    // For integer types, truncate the IV before computing IVInit + BECoun=
t.
-    else {
-      if (SE->getTypeSizeInBits(IVInit->getType())
-          > SE->getTypeSizeInBits(CmpTy))
-        IVInit =3D SE->getTruncateExpr(IVInit, CmpTy);
-
-      IVLimit =3D SE->getAddExpr(IVInit, IVLimit);
-    }
-  }
-  // Expand the code for the iteration count.
-  IRBuilder<> Builder(BI);
-
-  assert(SE->isLoopInvariant(IVLimit, L) &&
-         "Computed iteration count is not loop invariant!");
-  Value *ExitCnt =3D Rewriter.expandCodeFor(IVLimit, CmpTy, BI);
-
-  // Create a gep for IVInit + IVLimit from on an existing pointer base.
-  assert(isPtrIV =3D=3D IndVar->getType()->isPointerTy() &&
-         "IndVar type must match IVInit type");
-  if (isPtrIV) {
-      Value *IVStart =3D IndVar->getIncomingValueForBlock(L->getLoopPrehea=
der());
-      assert(AR->getStart() =3D=3D SE->getSCEV(IVStart) && "bad loop count=
er");
-      assert(SE->getSizeOfExpr(
-               cast<PointerType>(IVStart->getType())->getElementType())->i=
sOne()
-             && "unit stride pointer IV must be i8*");
-
-      Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
-      ExitCnt =3D Builder.CreateGEP(IVStart, ExitCnt, "lftr.limit");
-      Builder.SetInsertPoint(BI);
-  }
+  Value *ExitCnt =3D genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
+  assert(ExitCnt->getType()->isPointerTy() =3D=3D IndVar->getType()->isPoi=
nterTy()
+         && "genLoopLimit missed a cast");
=20
   // Insert a new icmp_ne or icmp_eq instruction before the branch.
+  BranchInst *BI =3D cast<BranchInst>(L->getExitingBlock()->getTerminator(=
));
   ICmpInst::Predicate P;
   if (L->contains(BI->getSuccessor(0)))
     P =3D ICmpInst::ICMP_NE;
@@ -1619,11 +1501,13 @@
                << "       op:\t"
                << (P =3D=3D ICmpInst::ICMP_NE ? "!=3D" : "=3D=3D") << "\n"
                << "      RHS:\t" << *ExitCnt << "\n"
-               << "     Expr:\t" << *IVLimit << "\n");
+               << "  IVCount:\t" << *IVCount << "\n");
=20
+  IRBuilder<> Builder(BI);
   if (SE->getTypeSizeInBits(CmpIndVar->getType())
-      > SE->getTypeSizeInBits(CmpTy)) {
-    CmpIndVar =3D Builder.CreateTrunc(CmpIndVar, CmpTy, "lftr.wideiv");
+      > SE->getTypeSizeInBits(ExitCnt->getType())) {
+    CmpIndVar =3D Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
+                                    "lftr.wideiv");
   }
=20
   Value *Cond =3D Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
@@ -1680,11 +1564,12 @@
     if (isa<LandingPadInst>(I))
       continue;
=20
-    // Don't sink static AllocaInsts out of the entry block, which would
-    // turn them into dynamic allocas!
-    if (AllocaInst *AI =3D dyn_cast<AllocaInst>(I))
-      if (AI->isStaticAlloca())
-        continue;
+    // Don't sink alloca: we never want to sink static alloca's out of the
+    // entry block, and correctly sinking dynamic alloca's requires
+    // checks for stacksave/stackrestore intrinsics.
+    // FIXME: Refactor this check somehow?
+    if (isa<AllocaInst>(I))
+      continue;
=20
     // Determine if there is a use in or before the loop (direct or
     // otherwise).
@@ -1746,8 +1631,6 @@
   if (!L->isLoopSimplifyForm())
     return false;
=20
-  if (EnableIVRewrite)
-    IU =3D &getAnalysis<IVUsers>();
   LI =3D &getAnalysis<LoopInfo>();
   SE =3D &getAnalysis<ScalarEvolution>();
   DT =3D &getAnalysis<DominatorTree>();
@@ -1774,10 +1657,8 @@
   // attempt to avoid evaluating SCEVs for sign/zero extend operations unt=
il
   // other expressions involving loop IVs have been evaluated. This helps =
SCEV
   // set no-wrap flags before normalizing sign/zero extension.
-  if (!EnableIVRewrite) {
-    Rewriter.disableCanonicalMode();
-    SimplifyAndExtend(L, Rewriter, LPM);
-  }
+  Rewriter.disableCanonicalMode();
+  SimplifyAndExtend(L, Rewriter, LPM);
=20
   // Check to see if this loop has a computable loop-invariant execution c=
ount.
   // If so, this means that we can compute the final value of any expressi=
ons
@@ -1788,106 +1669,28 @@
   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
     RewriteLoopExitValues(L, Rewriter);
=20
-  // Eliminate redundant IV users.
-  if (EnableIVRewrite)
-    Changed |=3D simplifyIVUsers(IU, SE, &LPM, DeadInsts);
+  // Eliminate redundant IV cycles.
+  NumElimIV +=3D Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
=20
-  // Eliminate redundant IV cycles.
-  if (!EnableIVRewrite)
-    NumElimIV +=3D Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
-
-  // Compute the type of the largest recurrence expression, and decide whe=
ther
-  // a canonical induction variable should be inserted.
-  Type *LargestType =3D 0;
-  bool NeedCannIV =3D false;
-  bool ExpandBECount =3D canExpandBackedgeTakenCount(L, SE);
-  if (EnableIVRewrite && ExpandBECount) {
-    // If we have a known trip count and a single exit block, we'll be
-    // rewriting the loop exit test condition below, which requires a
-    // canonical induction variable.
-    NeedCannIV =3D true;
-    Type *Ty =3D BackedgeTakenCount->getType();
-    if (!EnableIVRewrite) {
-      // In this mode, SimplifyIVUsers may have already widened the IV use=
d by
-      // the backedge test and inserted a Trunc on the compare's operand. =
Get
-      // the wider type to avoid creating a redundant narrow IV only used =
by the
-      // loop test.
-      LargestType =3D getBackedgeIVType(L);
-    }
-    if (!LargestType ||
-        SE->getTypeSizeInBits(Ty) >
-        SE->getTypeSizeInBits(LargestType))
-      LargestType =3D SE->getEffectiveSCEVType(Ty);
-  }
-  if (EnableIVRewrite) {
-    for (IVUsers::const_iterator I =3D IU->begin(), E =3D IU->end(); I !=
=3D E; ++I) {
-      NeedCannIV =3D true;
-      Type *Ty =3D
-        SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
-      if (!LargestType ||
-          SE->getTypeSizeInBits(Ty) >
-          SE->getTypeSizeInBits(LargestType))
-        LargestType =3D Ty;
+  // If we have a trip count expression, rewrite the loop's exit condition
+  // using it.  We can currently only handle loops with a single exit.
+  if (canExpandBackedgeTakenCount(L, SE) && needsLFTR(L, DT)) {
+    PHINode *IndVar =3D FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
+    if (IndVar) {
+      // Check preconditions for proper SCEVExpander operation. SCEV does =
not
+      // express SCEVExpander's dependencies, such as LoopSimplify. Instea=
d any
+      // pass that uses the SCEVExpander must do it. This does not work we=
ll for
+      // loop passes because SCEVExpander makes assumptions about all loop=
s, while
+      // LoopPassManager only forces the current loop to be simplified.
+      //
+      // FIXME: SCEV expansion has no way to bail out, so the caller must
+      // explicitly check any assumptions made by SCEV. Brittle.
+      const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(BackedgeTakenC=
ount);
+      if (!AR || AR->getLoop()->getLoopPreheader())
+        (void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
+                                        Rewriter);
     }
   }
-
-  // Now that we know the largest of the induction variable expressions
-  // in this loop, insert a canonical induction variable of the largest si=
ze.
-  PHINode *IndVar =3D 0;
-  if (NeedCannIV) {
-    // Check to see if the loop already has any canonical-looking induction
-    // variables. If any are present and wider than the planned canonical
-    // induction variable, temporarily remove them, so that the Rewriter
-    // doesn't attempt to reuse them.
-    SmallVector<PHINode *, 2> OldCannIVs;
-    while (PHINode *OldCannIV =3D L->getCanonicalInductionVariable()) {
-      if (SE->getTypeSizeInBits(OldCannIV->getType()) >
-          SE->getTypeSizeInBits(LargestType))
-        OldCannIV->removeFromParent();
-      else
-        break;
-      OldCannIVs.push_back(OldCannIV);
-    }
-
-    IndVar =3D Rewriter.getOrInsertCanonicalInductionVariable(L, LargestTy=
pe);
-
-    ++NumInserted;
-    Changed =3D true;
-    DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
-
-    // Now that the official induction variable is established, reinsert
-    // any old canonical-looking variables after it so that the IR remains
-    // consistent. They will be deleted as part of the dead-PHI deletion at
-    // the end of the pass.
-    while (!OldCannIVs.empty()) {
-      PHINode *OldCannIV =3D OldCannIVs.pop_back_val();
-      OldCannIV->insertBefore(L->getHeader()->getFirstInsertionPt());
-    }
-  }
-  else if (!EnableIVRewrite && ExpandBECount && needsLFTR(L, DT)) {
-    IndVar =3D FindLoopCounter(L, BackedgeTakenCount, SE, DT, TD);
-  }
-  // If we have a trip count expression, rewrite the loop's exit condition
-  // using it.  We can currently only handle loops with a single exit.
-  Value *NewICmp =3D 0;
-  if (ExpandBECount && IndVar) {
-    // Check preconditions for proper SCEVExpander operation. SCEV does not
-    // express SCEVExpander's dependencies, such as LoopSimplify. Instead =
any
-    // pass that uses the SCEVExpander must do it. This does not work well=
 for
-    // loop passes because SCEVExpander makes assumptions about all loops,=
 while
-    // LoopPassManager only forces the current loop to be simplified.
-    //
-    // FIXME: SCEV expansion has no way to bail out, so the caller must
-    // explicitly check any assumptions made by SCEV. Brittle.
-    const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(BackedgeTakenCou=
nt);
-    if (!AR || AR->getLoop()->getLoopPreheader())
-      NewICmp =3D
-        LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar, Rewriter);
-  }
-  // Rewrite IV-derived expressions.
-  if (EnableIVRewrite)
-    RewriteIVExpressions(L, Rewriter);
-
   // Clear the rewriter cache, because values that are in the rewriter's c=
ache
   // can be deleted in the loop below, causing the AssertingVH in the cach=
e to
   // trigger.
@@ -1906,13 +1709,6 @@
   // loop may be sunk below the loop to reduce register pressure.
   SinkUnusedInvariants(L);
=20
-  // For completeness, inform IVUsers of the IV use in the newly-created
-  // loop exit test instruction.
-  if (IU && NewICmp) {
-    ICmpInst *NewICmpInst =3D dyn_cast<ICmpInst>(NewICmp);
-    if (NewICmpInst)
-      IU->AddUsersIfInteresting(cast<Instruction>(NewICmpInst->getOperand(=
0)));
-  }
   // Clean up dead instructions.
   Changed |=3D DeleteDeadPHIs(L->getHeader());
   // Check a post-condition.
@@ -1922,8 +1718,7 @@
   // Verify that LFTR, and any other change have not interfered with SCEV's
   // ability to compute trip count.
 #ifndef NDEBUG
-  if (!EnableIVRewrite && VerifyIndvars &&
-      !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
+  if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
     SE->forgetLoop(L);
     const SCEV *NewBECount =3D SE->getBackedgeTakenCount(L);
     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/JumpThreading.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/JumpThreading.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/JumpThreading.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -24,6 +24,7 @@
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Transforms/Utils/SSAUpdater.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/Statistic.h"
@@ -75,6 +76,7 @@
   ///
   class JumpThreading : public FunctionPass {
     TargetData *TD;
+    TargetLibraryInfo *TLI;
     LazyValueInfo *LVI;
 #ifdef NDEBUG
     SmallPtrSet<BasicBlock*, 16> LoopHeaders;
@@ -107,6 +109,7 @@
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<LazyValueInfo>();
       AU.addPreserved<LazyValueInfo>();
+      AU.addRequired<TargetLibraryInfo>();
     }
=20
     void FindLoopHeaders(Function &F);
@@ -133,6 +136,7 @@
 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
                 "Jump Threading", false, false)
 INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
 INITIALIZE_PASS_END(JumpThreading, "jump-threading",
                 "Jump Threading", false, false)
=20
@@ -144,6 +148,7 @@
 bool JumpThreading::runOnFunction(Function &F) {
   DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
   TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
   LVI =3D &getAnalysis<LazyValueInfo>();
=20
   FindLoopHeaders(F);
@@ -674,7 +679,7 @@
   // Run constant folding to see if we can reduce the condition to a simple
   // constant.
   if (Instruction *I =3D dyn_cast<Instruction>(Condition)) {
-    Value *SimpleVal =3D ConstantFoldInstruction(I, TD);
+    Value *SimpleVal =3D ConstantFoldInstruction(I, TD, TLI);
     if (SimpleVal) {
       I->replaceAllUsesWith(SimpleVal);
       I->eraseFromParent();
@@ -852,6 +857,9 @@
   if (BBIt !=3D LoadBB->begin())
     return false;
=20
+  // If all of the loads and stores that feed the value have the same TBAA=
 tag,
+  // then we can propagate it onto any newly inserted loads.
+  MDNode *TBAATag =3D LI->getMetadata(LLVMContext::MD_tbaa);=20
=20
   SmallPtrSet<BasicBlock*, 8> PredsScanned;
   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
@@ -870,11 +878,16 @@
=20
     // Scan the predecessor to see if the value is available in the pred.
     BBIt =3D PredBB->end();
-    Value *PredAvailable =3D FindAvailableLoadedValue(LoadedPtr, PredBB, B=
BIt, 6);
+    MDNode *ThisTBAATag =3D 0;
+    Value *PredAvailable =3D FindAvailableLoadedValue(LoadedPtr, PredBB, B=
BIt, 6,
+                                                    0, &ThisTBAATag);
     if (!PredAvailable) {
       OneUnavailablePred =3D PredBB;
       continue;
     }
+   =20
+    // If tbaa tags disagree or are not present, forget about them.
+    if (TBAATag !=3D ThisTBAATag) TBAATag =3D 0;
=20
     // If so, this load is partially redundant.  Remember this info so tha=
t we
     // can create a PHI node.
@@ -921,8 +934,7 @@
=20
     // Split them out to their own block.
     UnavailablePred =3D
-      SplitBlockPredecessors(LoadBB, &PredsToSplit[0], PredsToSplit.size(),
-                             "thread-pre-split", this);
+      SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split", thi=
s);
   }
=20
   // If the value isn't available in all predecessors, then there will be
@@ -935,6 +947,9 @@
                                  LI->getAlignment(),
                                  UnavailablePred->getTerminator());
     NewVal->setDebugLoc(LI->getDebugLoc());
+    if (TBAATag)
+      NewVal->setMetadata(LLVMContext::MD_tbaa, TBAATag);
+   =20
     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
   }
=20
@@ -1082,9 +1097,9 @@
       DestBB =3D 0;
     else if (BranchInst *BI =3D dyn_cast<BranchInst>(BB->getTerminator()))
       DestBB =3D BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
-    else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(BB->getTerminator()))
-      DestBB =3D SI->getSuccessor(SI->findCaseValue(cast<ConstantInt>(Val)=
));
-    else {
+    else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(BB->getTerminator()))=
 {
+      DestBB =3D SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccesso=
r();
+    } else {
       assert(isa<IndirectBrInst>(BB->getTerminator())
               && "Unexpected terminator");
       DestBB =3D cast<BlockAddress>(Val)->getBasicBlock();
@@ -1334,8 +1349,7 @@
   else {
     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
           << " common predecessors.\n");
-    PredBB =3D SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
-                                    ".thr_comm", this);
+    PredBB =3D SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
   }
=20
   // And finally, do it!
@@ -1479,8 +1493,7 @@
   else {
     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
           << " common predecessors.\n");
-    PredBB =3D SplitBlockPredecessors(BB, &PredBBs[0], PredBBs.size(),
-                                    ".thr_comm", this);
+    PredBB =3D SplitBlockPredecessors(BB, PredBBs, ".thr_comm", this);
   }
=20
   // Okay, we decided to do this!  Clone all the instructions in BB onto t=
he end
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/LICM.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/LICM.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/LICM.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -43,8 +43,11 @@
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/LoopPass.h"
 #include "llvm/Analysis/Dominators.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Transforms/Utils/SSAUpdater.h"
+#include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/raw_ostream.h"
@@ -84,6 +87,7 @@
       AU.addPreserved<AliasAnalysis>();
       AU.addPreserved("scalar-evolution");
       AU.addPreservedID(LoopSimplifyID);
+      AU.addRequired<TargetLibraryInfo>();
     }
=20
     bool doFinalization() {
@@ -96,6 +100,9 @@
     LoopInfo      *LI;       // Current LoopInfo
     DominatorTree *DT;       // Dominator Tree for the current Loop.
=20
+    TargetData *TD;          // TargetData for constant folding.
+    TargetLibraryInfo *TLI;  // TargetLibraryInfo for constant folding.
+
     // State that is updated as we process loops.
     bool Changed;            // Set to true when we change anything.
     BasicBlock *Preheader;   // The preheader block of the current loop...
@@ -177,6 +184,7 @@
 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, fal=
se)
=20
@@ -194,6 +202,9 @@
   AA =3D &getAnalysis<AliasAnalysis>();
   DT =3D &getAnalysis<DominatorTree>();
=20
+  TD =3D getAnalysisIfAvailable<TargetData>();
+  TLI =3D &getAnalysis<TargetLibraryInfo>();
+
   CurAST =3D new AliasSetTracker(*AA);
   // Collect Alias info from subloops.
   for (Loop::iterator LoopItr =3D L->begin(), LoopItrE =3D L->end();
@@ -333,7 +344,7 @@
       // Try constant folding this instruction.  If all the operands are
       // constants, it is technically hoistable, but it would be better to=
 just
       // fold it.
-      if (Constant *C =3D ConstantFoldInstruction(&I)) {
+      if (Constant *C =3D ConstantFoldInstruction(&I, TD, TLI)) {
         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\=
n');
         CurAST->copyValue(&I, C);
         CurAST->deleteValue(&I);
@@ -369,6 +380,8 @@
     // in the same alias set as something that ends up being modified.
     if (AA->pointsToConstantMemory(LI->getOperand(0)))
       return true;
+    if (LI->getMetadata("invariant.load"))
+      return true;
=20
     // Don't hoist loads which have may-aliased stores in loop.
     uint64_t Size =3D 0;
@@ -579,7 +592,7 @@
 ///
 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
   // If it is not a trapping instruction, it is always safe to hoist.
-  if (Inst.isSafeToSpeculativelyExecute())
+  if (isSafeToSpeculativelyExecute(&Inst))
     return true;
=20
   return isGuaranteedToExecute(Inst);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/LoopInstSimplify.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/LoopInstSimplify.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "llvm/Analysis/LoopPass.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/ADT/Statistic.h"
@@ -43,6 +44,7 @@
       AU.addPreservedID(LoopSimplifyID);
       AU.addPreservedID(LCSSAID);
       AU.addPreserved("scalar-evolution");
+      AU.addRequired<TargetLibraryInfo>();
     }
   };
 }
@@ -50,6 +52,7 @@
 char LoopInstSimplify::ID =3D 0;
 INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
                 "Simplify instructions in loops", false, false)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
 INITIALIZE_PASS_DEPENDENCY(LCSSA)
@@ -64,6 +67,7 @@
   DominatorTree *DT =3D getAnalysisIfAvailable<DominatorTree>();
   LoopInfo *LI =3D &getAnalysis<LoopInfo>();
   const TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
+  const TargetLibraryInfo *TLI =3D &getAnalysis<TargetLibraryInfo>();
=20
   SmallVector<BasicBlock*, 8> ExitBlocks;
   L->getUniqueExitBlocks(ExitBlocks);
@@ -104,7 +108,7 @@
=20
         // Don't bother simplifying unused instructions.
         if (!I->use_empty()) {
-          Value *V =3D SimplifyInstruction(I, TD, DT);
+          Value *V =3D SimplifyInstruction(I, TD, TLI, DT);
           if (V && LI->replacementPreservesLCSSAForm(I, V)) {
             // Mark all uses for resimplification next time round the loop.
             for (Value::use_iterator UI =3D I->use_begin(), UE =3D I->use_=
end();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/LoopRotation.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/LoopRotation.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/LoopRotation.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "llvm/Analysis/LoopPass.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/ScalarEvolution.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/Transforms/Utils/SSAUpdater.h"
@@ -52,13 +53,14 @@
     }
=20
     bool runOnLoop(Loop *L, LPPassManager &LPM);
+    void simplifyLoopLatch(Loop *L);
     bool rotateLoop(Loop *L);
-   =20
+
   private:
     LoopInfo *LI;
   };
 }
- =20
+
 char LoopRotate::ID =3D 0;
 INITIALIZE_PASS_BEGIN(LoopRotate, "loop-rotate", "Rotate Loops", false, fa=
lse)
 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
@@ -73,6 +75,11 @@
 bool LoopRotate::runOnLoop(Loop *L, LPPassManager &LPM) {
   LI =3D &getAnalysis<LoopInfo>();
=20
+  // Simplify the loop latch before attempting to rotate the header
+  // upward. Rotation may not be needed if the loop tail can be folded int=
o the
+  // loop exit.
+  simplifyLoopLatch(L);
+
   // One loop can be rotated multiple times.
   bool MadeChange =3D false;
   while (rotateLoop(L))
@@ -92,18 +99,18 @@
   BasicBlock::iterator I, E =3D OrigHeader->end();
   for (I =3D OrigHeader->begin(); PHINode *PN =3D dyn_cast<PHINode>(I); ++=
I)
     PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
-   =20
+
   // Now fix up users of the instructions in OrigHeader, inserting PHI nod=
es
   // as necessary.
   SSAUpdater SSA;
   for (I =3D OrigHeader->begin(); I !=3D E; ++I) {
     Value *OrigHeaderVal =3D I;
-   =20
+
     // If there are no uses of the value (e.g. because it returns void), t=
here
     // is nothing to rewrite.
     if (OrigHeaderVal->use_empty())
       continue;
-   =20
+
     Value *OrigPreHeaderVal =3D ValueMap[OrigHeaderVal];
=20
     // The value now exits in two versions: the initial value in the prehe=
ader
@@ -111,27 +118,27 @@
     SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
     SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
     SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
-   =20
+
     // Visit each use of the OrigHeader instruction.
     for (Value::use_iterator UI =3D OrigHeaderVal->use_begin(),
          UE =3D OrigHeaderVal->use_end(); UI !=3D UE; ) {
       // Grab the use before incrementing the iterator.
       Use &U =3D UI.getUse();
-     =20
+
       // Increment the iterator before removing the use from the list.
       ++UI;
-     =20
+
       // SSAUpdater can't handle a non-PHI use in the same block as an
       // earlier def. We can easily handle those cases manually.
       Instruction *UserInst =3D cast<Instruction>(U.getUser());
       if (!isa<PHINode>(UserInst)) {
         BasicBlock *UserBB =3D UserInst->getParent();
-       =20
+
         // The original users in the OrigHeader are already using the
         // original definitions.
         if (UserBB =3D=3D OrigHeader)
           continue;
-       =20
+
         // Users in the OrigPreHeader need to use the value to which the
         // original definitions are mapped.
         if (UserBB =3D=3D OrigPreheader) {
@@ -139,32 +146,128 @@
           continue;
         }
       }
-     =20
+
       // Anything else can be handled by SSAUpdater.
       SSA.RewriteUse(U);
     }
   }
-} =20
+}
+
+/// Determine whether the instructions in this range my be safely and chea=
ply
+/// speculated. This is not an important enough situation to develop compl=
ex
+/// heuristics. We handle a single arithmetic instruction along with any t=
ype
+/// conversions.
+static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
+                                  BasicBlock::iterator End) {
+  bool seenIncrement =3D false;
+  for (BasicBlock::iterator I =3D Begin; I !=3D End; ++I) {
+
+    if (!isSafeToSpeculativelyExecute(I))
+      return false;
+
+    if (isa<DbgInfoIntrinsic>(I))
+      continue;
+
+    switch (I->getOpcode()) {
+    default:
+      return false;
+    case Instruction::GetElementPtr:
+      // GEPs are cheap if all indices are constant.
+      if (!cast<GEPOperator>(I)->hasAllConstantIndices())
+        return false;
+      // fall-thru to increment case
+    case Instruction::Add:
+    case Instruction::Sub:
+    case Instruction::And:
+    case Instruction::Or:
+    case Instruction::Xor:
+    case Instruction::Shl:
+    case Instruction::LShr:
+    case Instruction::AShr:
+      if (seenIncrement)
+        return false;
+      seenIncrement =3D true;
+      break;
+    case Instruction::Trunc:
+    case Instruction::ZExt:
+    case Instruction::SExt:
+      // ignore type conversions
+      break;
+    }
+  }
+  return true;
+}
+
+/// Fold the loop tail into the loop exit by speculating the loop tail
+/// instructions. Typically, this is a single post-increment. In the case =
of a
+/// simple 2-block loop, hoisting the increment can be much better than
+/// duplicating the entire loop header. In the cast of loops with early ex=
its,
+/// rotation will not work anyway, but simplifyLoopLatch will put the loop=
 in
+/// canonical form so downstream passes can handle it.
+///
+/// I don't believe this invalidates SCEV.
+void LoopRotate::simplifyLoopLatch(Loop *L) {
+  BasicBlock *Latch =3D L->getLoopLatch();
+  if (!Latch || Latch->hasAddressTaken())
+    return;
+
+  BranchInst *Jmp =3D dyn_cast<BranchInst>(Latch->getTerminator());
+  if (!Jmp || !Jmp->isUnconditional())
+    return;
+
+  BasicBlock *LastExit =3D Latch->getSinglePredecessor();
+  if (!LastExit || !L->isLoopExiting(LastExit))
+    return;
+
+  BranchInst *BI =3D dyn_cast<BranchInst>(LastExit->getTerminator());
+  if (!BI)
+    return;
+
+  if (!shouldSpeculateInstrs(Latch->begin(), Jmp))
+    return;
+
+  DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
+        << LastExit->getName() << "\n");
+
+  // Hoist the instructions from Latch into LastExit.
+  LastExit->getInstList().splice(BI, Latch->getInstList(), Latch->begin(),=
 Jmp);
+
+  unsigned FallThruPath =3D BI->getSuccessor(0) =3D=3D Latch ? 0 : 1;
+  BasicBlock *Header =3D Jmp->getSuccessor(0);
+  assert(Header =3D=3D L->getHeader() && "expected a backward branch");
+
+  // Remove Latch from the CFG so that LastExit becomes the new Latch.
+  BI->setSuccessor(FallThruPath, Header);
+  Latch->replaceSuccessorsPhiUsesWith(LastExit);
+  Jmp->eraseFromParent();
+
+  // Nuke the Latch block.
+  assert(Latch->empty() && "unable to evacuate Latch");
+  LI->removeBlock(Latch);
+  if (DominatorTree *DT =3D getAnalysisIfAvailable<DominatorTree>())
+    DT->eraseNode(Latch);
+  Latch->eraseFromParent();
+}
=20
 /// Rotate loop LP. Return true if the loop is rotated.
 bool LoopRotate::rotateLoop(Loop *L) {
   // If the loop has only one block then there is not much to rotate.
   if (L->getBlocks().size() =3D=3D 1)
     return false;
- =20
+
   BasicBlock *OrigHeader =3D L->getHeader();
- =20
+
   BranchInst *BI =3D dyn_cast<BranchInst>(OrigHeader->getTerminator());
   if (BI =3D=3D 0 || BI->isUnconditional())
     return false;
- =20
+
   // If the loop header is not one of the loop exiting blocks then
   // either this loop is already rotated or it is not
   // suitable for loop rotation transformations.
   if (!L->isLoopExiting(OrigHeader))
     return false;
=20
-  // Updating PHInodes in loops with multiple exits adds complexity.=20
+  // Updating PHInodes in loops with multiple exits adds complexity.
   // Keep it simple, and restrict loop rotation to loops with one exit onl=
y.
   // In future, lift this restriction and support for multiple exits if
   // required.
@@ -184,7 +287,7 @@
   // Now, this loop is suitable for rotation.
   BasicBlock *OrigPreheader =3D L->getLoopPreheader();
   BasicBlock *OrigLatch =3D L->getLoopLatch();
- =20
+
   // If the loop could not be converted to canonical form, it must have an
   // indirectbr in it, just give up.
   if (OrigPreheader =3D=3D 0 || OrigLatch =3D=3D 0)
@@ -203,9 +306,9 @@
   if (L->contains(Exit))
     std::swap(Exit, NewHeader);
   assert(NewHeader && "Unable to determine new loop header");
-  assert(L->contains(NewHeader) && !L->contains(Exit) &&=20
+  assert(L->contains(NewHeader) && !L->contains(Exit) &&
          "Unable to determine loop header and exit blocks");
- =20
+
   // This code assumes that the new header has exactly one predecessor.
   // Remove any single-entry PHI nodes in it.
   assert(NewHeader->getSinglePredecessor() &&
@@ -227,7 +330,7 @@
   TerminatorInst *LoopEntryBranch =3D OrigPreheader->getTerminator();
   while (I !=3D E) {
     Instruction *Inst =3D I++;
-   =20
+
     // If the instruction's operands are invariant and it doesn't read or =
write
     // memory, then it is safe to hoist.  Doing this doesn't change the or=
der of
     // execution in the preheader, but does prevent the instruction from
@@ -236,18 +339,19 @@
     // memory (without proving that the loop doesn't write).
     if (L->hasLoopInvariantOperands(Inst) &&
         !Inst->mayReadFromMemory() && !Inst->mayWriteToMemory() &&
-        !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst)) {
+        !isa<TerminatorInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst) &&
+        !isa<AllocaInst>(Inst)) {
       Inst->moveBefore(LoopEntryBranch);
       continue;
     }
-   =20
+
     // Otherwise, create a duplicate of the instruction.
     Instruction *C =3D Inst->clone();
-   =20
+
     // Eagerly remap the operands of the instruction.
     RemapInstruction(C, ValueMap,
                      RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
-   =20
+
     // With the operands remapped, see if the instruction constant folds o=
r is
     // otherwise simplifyable.  This commonly occurs because the entry fro=
m PHI
     // nodes allows icmps and other instructions to fold.
@@ -287,7 +391,7 @@
   L->moveToHeader(NewHeader);
   assert(L->getHeader() =3D=3D NewHeader && "Latch block is our new header=
");
=20
- =20
+
   // At this point, we've finished our major CFG changes.  As part of clon=
ing
   // the loop into the preheader we've simplified instructions and the
   // duplicated conditional branch may now be branching on a constant.  If=
 it is
@@ -308,16 +412,16 @@
       // the dominator of Exit.
       DT->changeImmediateDominator(Exit, OrigPreheader);
       DT->changeImmediateDominator(NewHeader, OrigPreheader);
-     =20
+
       // Update OrigHeader to be dominated by the new header block.
       DT->changeImmediateDominator(OrigHeader, OrigLatch);
     }
-   =20
+
     // Right now OrigPreHeader has two successors, NewHeader and ExitBlock=
, and
     // thus is not a preheader anymore.  Split the edge to form a real pre=
header.
     BasicBlock *NewPH =3D SplitCriticalEdge(OrigPreheader, NewHeader, this=
);
     NewPH->setName(NewHeader->getName() + ".lr.ph");
-   =20
+
     // Preserve canonical loop form, which means that 'Exit' should have o=
nly one
     // predecessor.
     BasicBlock *ExitSplit =3D SplitCriticalEdge(L->getLoopLatch(), Exit, t=
his);
@@ -329,7 +433,7 @@
     BranchInst *NewBI =3D BranchInst::Create(NewHeader, PHBI);
     NewBI->setDebugLoc(PHBI->getDebugLoc());
     PHBI->eraseFromParent();
-   =20
+
     // With our CFG finalized, update DomTree if it is available.
     if (DominatorTree *DT =3D getAnalysisIfAvailable<DominatorTree>()) {
       // Update OrigHeader to be dominated by the new header block.
@@ -337,7 +441,7 @@
       DT->changeImmediateDominator(OrigHeader, OrigLatch);
     }
   }
- =20
+
   assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotat=
ion");
   assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
=20
@@ -346,7 +450,7 @@
   // connected by an unconditional branch.  This is just a cleanup so the
   // emitted code isn't too gross in this common case.
   MergeBlockIntoPredecessor(OrigHeader, this);
- =20
+
   ++NumRotated;
   return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/LoopStrengthReduce.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -77,19 +77,22 @@
 #include <algorithm>
 using namespace llvm;
=20
-namespace llvm {
-cl::opt<bool> EnableNested(
-  "enable-lsr-nested", cl::Hidden, cl::desc("Enable LSR on nested loops"));
-
-cl::opt<bool> EnableRetry(
-    "enable-lsr-retry", cl::Hidden, cl::desc("Enable LSR retry"));
-
 // Temporary flag to cleanup congruent phis after LSR phi expansion.
 // It's currently disabled until we can determine whether it's truly usefu=
l or
 // not. The flag should be removed after the v3.0 release.
-cl::opt<bool> EnablePhiElim(
-    "enable-lsr-phielim", cl::Hidden, cl::desc("Enable LSR phi elimination=
"));
-}
+// This is now needed for ivchains.
+static cl::opt<bool> EnablePhiElim(
+  "enable-lsr-phielim", cl::Hidden, cl::init(true),
+  cl::desc("Enable LSR phi elimination"));
+
+#ifndef NDEBUG
+// Stress test IV chain generation.
+static cl::opt<bool> StressIVChain(
+  "stress-ivchain", cl::Hidden, cl::init(false),
+  cl::desc("Stress test LSR IV chains"));
+#else
+static bool StressIVChain =3D false;
+#endif
=20
 namespace {
=20
@@ -636,6 +639,91 @@
   return AccessTy;
 }
=20
+/// isExistingPhi - Return true if this AddRec is already a phi in its loo=
p.
+static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
+  for (BasicBlock::iterator I =3D AR->getLoop()->getHeader()->begin();
+       PHINode *PN =3D dyn_cast<PHINode>(I); ++I) {
+    if (SE.isSCEVable(PN->getType()) &&
+        (SE.getEffectiveSCEVType(PN->getType()) =3D=3D
+         SE.getEffectiveSCEVType(AR->getType())) &&
+        SE.getSCEV(PN) =3D=3D AR)
+      return true;
+  }
+  return false;
+}
+
+/// Check if expanding this expression is likely to incur significant cost=
. This
+/// is tricky because SCEV doesn't track which expressions are actually co=
mputed
+/// by the current IR.
+///
+/// We currently allow expansion of IV increments that involve adds,
+/// multiplication by constants, and AddRecs from existing phis.
+///
+/// TODO: Allow UDivExpr if we can find an existing IV increment that is an
+/// obvious multiple of the UDivExpr.
+static bool isHighCostExpansion(const SCEV *S,
+                                SmallPtrSet<const SCEV*, 8> &Processed,
+                                ScalarEvolution &SE) {
+  // Zero/One operand expressions
+  switch (S->getSCEVType()) {
+  case scUnknown:
+  case scConstant:
+    return false;
+  case scTruncate:
+    return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
+                               Processed, SE);
+  case scZeroExtend:
+    return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
+                               Processed, SE);
+  case scSignExtend:
+    return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
+                               Processed, SE);
+  }
+
+  if (!Processed.insert(S))
+    return false;
+
+  if (const SCEVAddExpr *Add =3D dyn_cast<SCEVAddExpr>(S)) {
+    for (SCEVAddExpr::op_iterator I =3D Add->op_begin(), E =3D Add->op_end=
();
+         I !=3D E; ++I) {
+      if (isHighCostExpansion(*I, Processed, SE))
+        return true;
+    }
+    return false;
+  }
+
+  if (const SCEVMulExpr *Mul =3D dyn_cast<SCEVMulExpr>(S)) {
+    if (Mul->getNumOperands() =3D=3D 2) {
+      // Multiplication by a constant is ok
+      if (isa<SCEVConstant>(Mul->getOperand(0)))
+        return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
+
+      // If we have the value of one operand, check if an existing
+      // multiplication already generates this expression.
+      if (const SCEVUnknown *U =3D dyn_cast<SCEVUnknown>(Mul->getOperand(1=
))) {
+        Value *UVal =3D U->getValue();
+        for (Value::use_iterator UI =3D UVal->use_begin(), UE =3D UVal->us=
e_end();
+             UI !=3D UE; ++UI) {
+          // If U is a constant, it may be used by a ConstantExpr.
+          Instruction *User =3D dyn_cast<Instruction>(*UI);
+          if (User && User->getOpcode() =3D=3D Instruction::Mul
+              && SE.isSCEVable(User->getType())) {
+            return SE.getSCEV(User) =3D=3D Mul;
+          }
+        }
+      }
+    }
+  }
+
+  if (const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(S)) {
+    if (isExistingPhi(AR, SE))
+      return false;
+  }
+
+  // Fow now, consider any other type of expression (div/mul/min/max) high=
 cost.
+  return true;
+}
+
 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
 /// specified set are trivially dead, delete them and see if this makes an=
y of
 /// their operands subsequently dead.
@@ -705,7 +793,8 @@
                    const DenseSet<const SCEV *> &VisitedRegs,
                    const Loop *L,
                    const SmallVectorImpl<int64_t> &Offsets,
-                   ScalarEvolution &SE, DominatorTree &DT);
+                   ScalarEvolution &SE, DominatorTree &DT,
+                   SmallPtrSet<const SCEV *, 16> *LoserRegs =3D 0);
=20
   void print(raw_ostream &OS) const;
   void dump() const;
@@ -718,7 +807,8 @@
   void RatePrimaryRegister(const SCEV *Reg,
                            SmallPtrSet<const SCEV *, 16> &Regs,
                            const Loop *L,
-                           ScalarEvolution &SE, DominatorTree &DT);
+                           ScalarEvolution &SE, DominatorTree &DT,
+                           SmallPtrSet<const SCEV *, 16> *LoserRegs);
 };
=20
 }
@@ -729,41 +819,20 @@
                         const Loop *L,
                         ScalarEvolution &SE, DominatorTree &DT) {
   if (const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(Reg)) {
-    if (AR->getLoop() =3D=3D L)
-      AddRecCost +=3D 1; /// TODO: This should be a function of the stride.
-
     // If this is an addrec for another loop, don't second-guess its addre=
c phi
     // nodes. LSR isn't currently smart enough to reason about more than o=
ne
-    // loop at a time. LSR has either already run on inner loops, will not=
 run
-    // on other loops, and cannot be expected to change sibling loops. If =
the
-    // AddRec exists, consider it's register free and leave it alone. Othe=
rwise,
-    // do not consider this formula at all.
-    // FIXME: why do we need to generate such fomulae?
-    else if (!EnableNested || L->contains(AR->getLoop()) ||
-             (!AR->getLoop()->contains(L) &&
-              DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
-      for (BasicBlock::iterator I =3D AR->getLoop()->getHeader()->begin();
-           PHINode *PN =3D dyn_cast<PHINode>(I); ++I) {
-        if (SE.isSCEVable(PN->getType()) &&
-            (SE.getEffectiveSCEVType(PN->getType()) =3D=3D
-             SE.getEffectiveSCEVType(AR->getType())) &&
-            SE.getSCEV(PN) =3D=3D AR)
-          return;
-      }
-      if (!EnableNested) {
-        Loose();
+    // loop at a time. LSR has already run on inner loops, will not run on=
 outer
+    // loops, and cannot be expected to change sibling loops.
+    if (AR->getLoop() !=3D L) {
+      // If the AddRec exists, consider it's register free and leave it al=
one.
+      if (isExistingPhi(AR, SE))
         return;
-      }
-      // If this isn't one of the addrecs that the loop already has, it
-      // would require a costly new phi and add. TODO: This isn't
-      // precisely modeled right now.
-      ++NumBaseAdds;
-      if (!Regs.count(AR->getStart())) {
-        RateRegister(AR->getStart(), Regs, L, SE, DT);
-        if (isLoser())
-          return;
-      }
+
+      // Otherwise, do not consider this formula at all.
+      Loose();
+      return;
     }
+    AddRecCost +=3D 1; /// TODO: This should be a function of the stride.
=20
     // Add the step value register, if it needs one.
     // TODO: The non-affine case isn't precisely modeled here.
@@ -791,13 +860,22 @@
 }
=20
 /// RatePrimaryRegister - Record this register in the set. If we haven't s=
een it
-/// before, rate it.
+/// before, rate it. Optional LoserRegs provides a way to declare any form=
ula
+/// that refers to one of those regs an instant loser.
 void Cost::RatePrimaryRegister(const SCEV *Reg,
                                SmallPtrSet<const SCEV *, 16> &Regs,
                                const Loop *L,
-                               ScalarEvolution &SE, DominatorTree &DT) {
-  if (Regs.insert(Reg))
+                               ScalarEvolution &SE, DominatorTree &DT,
+                               SmallPtrSet<const SCEV *, 16> *LoserRegs) {
+  if (LoserRegs && LoserRegs->count(Reg)) {
+    Loose();
+    return;
+  }
+  if (Regs.insert(Reg)) {
     RateRegister(Reg, Regs, L, SE, DT);
+    if (isLoser())
+      LoserRegs->insert(Reg);
+  }
 }
=20
 void Cost::RateFormula(const Formula &F,
@@ -805,14 +883,15 @@
                        const DenseSet<const SCEV *> &VisitedRegs,
                        const Loop *L,
                        const SmallVectorImpl<int64_t> &Offsets,
-                       ScalarEvolution &SE, DominatorTree &DT) {
+                       ScalarEvolution &SE, DominatorTree &DT,
+                       SmallPtrSet<const SCEV *, 16> *LoserRegs) {
   // Tally up the registers.
   if (const SCEV *ScaledReg =3D F.ScaledReg) {
     if (VisitedRegs.count(ScaledReg)) {
       Loose();
       return;
     }
-    RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
+    RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
     if (isLoser())
       return;
   }
@@ -823,7 +902,7 @@
       Loose();
       return;
     }
-    RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
+    RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
     if (isLoser())
       return;
   }
@@ -1105,7 +1184,6 @@
   Formulae.push_back(F);
=20
   // Record registers now being used by this use.
-  if (F.ScaledReg) Regs.insert(F.ScaledReg);
   Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
=20
   return true;
@@ -1116,7 +1194,6 @@
   if (&F !=3D &Formulae.back())
     std::swap(F, Formulae.back());
   Formulae.pop_back();
-  assert(!Formulae.empty() && "LSRUse has no formulae left!");
 }
=20
 /// RecomputeRegs - Recompute the Regs field, and update RegUses.
@@ -1205,10 +1282,19 @@
     // If we have low-level target information, ask the target if it can f=
old an
     // integer immediate on an icmp.
     if (AM.BaseOffs !=3D 0) {
-      if (TLI) return TLI->isLegalICmpImmediate(-(uint64_t)AM.BaseOffs);
-      return false;
+      if (!TLI)
+        return false;
+      // We have one of:
+      // ICmpZero     BaseReg + Offset =3D> ICmp BaseReg, -Offset
+      // ICmpZero -1*ScaleReg + Offset =3D> ICmp ScaleReg, Offset
+      // Offs is the ICmp immediate.
+      int64_t Offs =3D AM.BaseOffs;
+      if (AM.Scale =3D=3D 0)
+        Offs =3D -(uint64_t)Offs; // The cast does the right thing with IN=
T64_MIN.
+      return TLI->isLegalICmpImmediate(Offs);
     }
=20
+    // ICmpZero BaseReg + -1*ScaleReg =3D> ICmp BaseReg, ScaleReg
     return true;
=20
   case LSRUse::Basic:
@@ -1220,7 +1306,7 @@
     return AM.Scale =3D=3D 0 || AM.Scale =3D=3D -1;
   }
=20
-  return false;
+  llvm_unreachable("Invalid LSRUse Kind!");
 }
=20
 static bool isLegalUse(TargetLowering::AddrMode AM,
@@ -1327,6 +1413,36 @@
   }
 };
=20
+/// IVInc - An individual increment in a Chain of IV increments.
+/// Relate an IV user to an expression that computes the IV it uses from t=
he IV
+/// used by the previous link in the Chain.
+///
+/// For the head of a chain, IncExpr holds the absolute SCEV expression fo=
r the
+/// original IVOperand. The head of the chain's IVOperand is only valid du=
ring
+/// chain collection, before LSR replaces IV users. During chain generatio=
n,
+/// IncExpr can be used to find the new IVOperand that computes the same
+/// expression.
+struct IVInc {
+  Instruction *UserInst;
+  Value* IVOperand;
+  const SCEV *IncExpr;
+
+  IVInc(Instruction *U, Value *O, const SCEV *E):
+    UserInst(U), IVOperand(O), IncExpr(E) {}
+};
+
+// IVChain - The list of IV increments in program order.
+// We typically add the head of a chain without finding subsequent links.
+typedef SmallVector<IVInc,1> IVChain;
+
+/// ChainUsers - Helper for CollectChains to track multiple IV increment u=
ses.
+/// Distinguish between FarUsers that definitely cross IV increments and
+/// NearUsers that may be used between IV increments.
+struct ChainUsers {
+  SmallPtrSet<Instruction*, 4> FarUsers;
+  SmallPtrSet<Instruction*, 4> NearUsers;
+};
+
 /// LSRInstance - This class holds state for the main loop strength reduct=
ion
 /// logic.
 class LSRInstance {
@@ -1359,11 +1475,29 @@
   /// RegUses - Track which uses use which register candidates.
   RegUseTracker RegUses;
=20
+  // Limit the number of chains to avoid quadratic behavior. We don't expe=
ct to
+  // have more than a few IV increment chains in a loop. Missing a Chain f=
alls
+  // back to normal LSR behavior for those uses.
+  static const unsigned MaxChains =3D 8;
+
+  /// IVChainVec - IV users can form a chain of IV increments.
+  SmallVector<IVChain, MaxChains> IVChainVec;
+
+  /// IVIncSet - IV users that belong to profitable IVChains.
+  SmallPtrSet<Use*, MaxChains> IVIncSet;
+
   void OptimizeShadowIV();
   bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
   ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
   void OptimizeLoopTermCond();
=20
+  void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
+                        SmallVectorImpl<ChainUsers> &ChainUsersVec);
+  void FinalizeChain(IVChain &Chain);
+  void CollectChains();
+  void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
+                       SmallVectorImpl<WeakVH> &DeadInsts);
+
   void CollectInterestingTypesAndFactors();
   void CollectFixupsAndInitialFormulae();
=20
@@ -1389,7 +1523,6 @@
=20
   LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU=
);
=20
-public:
   void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
   void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
   void CountRegisters(const Formula &F, size_t LUIdx);
@@ -1428,9 +1561,11 @@
   BasicBlock::iterator
     HoistInsertPosition(BasicBlock::iterator IP,
                         const SmallVectorImpl<Instruction *> &Inputs) cons=
t;
-  BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator =
IP,
-                                                     const LSRFixup &LF,
-                                                     const LSRUse &LU) con=
st;
+  BasicBlock::iterator
+    AdjustInsertPositionForExpand(BasicBlock::iterator IP,
+                                  const LSRFixup &LF,
+                                  const LSRUse &LU,
+                                  SCEVExpander &Rewriter) const;
=20
   Value *Expand(const LSRFixup &LF,
                 const Formula &F,
@@ -1450,6 +1585,7 @@
   void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
                          Pass *P);
=20
+public:
   LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
=20
   bool getChanged() const { return Changed; }
@@ -2045,7 +2181,8 @@
     do {
       const SCEV *S =3D Worklist.pop_back_val();
       if (const SCEVAddRecExpr *AR =3D dyn_cast<SCEVAddRecExpr>(S)) {
-        Strides.insert(AR->getStepRecurrence(SE));
+        if (AR->getLoop() =3D=3D L)
+          Strides.insert(AR->getStepRecurrence(SE));
         Worklist.push_back(AR->getStart());
       } else if (const SCEVAddExpr *Add =3D dyn_cast<SCEVAddExpr>(S)) {
         Worklist.append(Add->op_begin(), Add->op_end());
@@ -2091,11 +2228,544 @@
   DEBUG(print_factors_and_types(dbgs()));
 }
=20
+/// findIVOperand - Helper for CollectChains that finds an IV operand (com=
puted
+/// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers ma=
pped
+/// Instructions to IVStrideUses, we could partially skip this.
+static User::op_iterator
+findIVOperand(User::op_iterator OI, User::op_iterator OE,
+              Loop *L, ScalarEvolution &SE) {
+  for(; OI !=3D OE; ++OI) {
+    if (Instruction *Oper =3D dyn_cast<Instruction>(*OI)) {
+      if (!SE.isSCEVable(Oper->getType()))
+        continue;
+
+      if (const SCEVAddRecExpr *AR =3D
+          dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
+        if (AR->getLoop() =3D=3D L)
+          break;
+      }
+    }
+  }
+  return OI;
+}
+
+/// getWideOperand - IVChain logic must consistenctly peek base TruncInst
+/// operands, so wrap it in a convenient helper.
+static Value *getWideOperand(Value *Oper) {
+  if (TruncInst *Trunc =3D dyn_cast<TruncInst>(Oper))
+    return Trunc->getOperand(0);
+  return Oper;
+}
+
+/// isCompatibleIVType - Return true if we allow an IV chain to include bo=
th
+/// types.
+static bool isCompatibleIVType(Value *LVal, Value *RVal) {
+  Type *LType =3D LVal->getType();
+  Type *RType =3D RVal->getType();
+  return (LType =3D=3D RType) || (LType->isPointerTy() && RType->isPointer=
Ty());
+}
+
+/// getExprBase - Return an approximation of this SCEV expression's "base"=
, or
+/// NULL for any constant. Returning the expression itself is
+/// conservative. Returning a deeper subexpression is more precise and val=
id as
+/// long as it isn't less complex than another subexpression. For expressi=
ons
+/// involving multiple unscaled values, we need to return the pointer-type
+/// SCEVUnknown. This avoids forming chains across objects, such as:
+/// PrevOper=3D=3Da[i], IVOper=3D=3Db[i], IVInc=3D=3Db-a.
+///
+/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
+/// SCEVUnknown, we simply return the rightmost SCEV operand.
+static const SCEV *getExprBase(const SCEV *S) {
+  switch (S->getSCEVType()) {
+  default: // uncluding scUnknown.
+    return S;
+  case scConstant:
+    return 0;
+  case scTruncate:
+    return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
+  case scZeroExtend:
+    return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
+  case scSignExtend:
+    return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
+  case scAddExpr: {
+    // Skip over scaled operands (scMulExpr) to follow add operands as lon=
g as
+    // there's nothing more complex.
+    // FIXME: not sure if we want to recognize negation.
+    const SCEVAddExpr *Add =3D cast<SCEVAddExpr>(S);
+    for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
+           E(Add->op_begin()); I !=3D E; ++I) {
+      const SCEV *SubExpr =3D *I;
+      if (SubExpr->getSCEVType() =3D=3D scAddExpr)
+        return getExprBase(SubExpr);
+
+      if (SubExpr->getSCEVType() !=3D scMulExpr)
+        return SubExpr;
+    }
+    return S; // all operands are scaled, be conservative.
+  }
+  case scAddRecExpr:
+    return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
+  }
+}
+
+/// Return true if the chain increment is profitable to expand into a loop
+/// invariant value, which may require its own register. A profitable chain
+/// increment will be an offset relative to the same base. We allow such o=
ffsets
+/// to potentially be used as chain increment as long as it's not obviously
+/// expensive to expand using real instructions.
+static const SCEV *
+getProfitableChainIncrement(Value *NextIV, Value *PrevIV,
+                            const IVChain &Chain, Loop *L,
+                            ScalarEvolution &SE, const TargetLowering *TLI=
) {
+  // Prune the solution space aggressively by checking that both IV operan=
ds
+  // are expressions that operate on the same unscaled SCEVUnknown. This
+  // "base" will be canceled by the subsequent getMinusSCEV call. Checking=
 first
+  // avoids creating extra SCEV expressions.
+  const SCEV *OperExpr =3D SE.getSCEV(NextIV);
+  const SCEV *PrevExpr =3D SE.getSCEV(PrevIV);
+  if (getExprBase(OperExpr) !=3D getExprBase(PrevExpr) && !StressIVChain)
+    return 0;
+
+  const SCEV *IncExpr =3D SE.getMinusSCEV(OperExpr, PrevExpr);
+  if (!SE.isLoopInvariant(IncExpr, L))
+    return 0;
+
+  // We are not able to expand an increment unless it is loop invariant,
+  // however, the following checks are purely for profitability.
+  if (StressIVChain)
+    return IncExpr;
+
+  // Do not replace a constant offset from IV head with a nonconstant IV
+  // increment.
+  if (!isa<SCEVConstant>(IncExpr)) {
+    const SCEV *HeadExpr =3D SE.getSCEV(getWideOperand(Chain[0].IVOperand)=
);
+    if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
+      return 0;
+  }
+
+  SmallPtrSet<const SCEV*, 8> Processed;
+  if (isHighCostExpansion(IncExpr, Processed, SE))
+    return 0;
+
+  return IncExpr;
+}
+
+/// Return true if the number of registers needed for the chain is estimat=
ed to
+/// be less than the number required for the individual IV users. First pr=
ohibit
+/// any IV users that keep the IV live across increments (the Users set sh=
ould
+/// be empty). Next count the number and type of increments in the chain.
+///
+/// Chaining IVs can lead to considerable code bloat if ISEL doesn't
+/// effectively use postinc addressing modes. Only consider it profitable =
it the
+/// increments can be computed in fewer registers when chained.
+///
+/// TODO: Consider IVInc free if it's already used in another chains.
+static bool
+isProfitableChain(IVChain &Chain, SmallPtrSet<Instruction*, 4> &Users,
+                  ScalarEvolution &SE, const TargetLowering *TLI) {
+  if (StressIVChain)
+    return true;
+
+  if (Chain.size() <=3D 2)
+    return false;
+
+  if (!Users.empty()) {
+    DEBUG(dbgs() << "Chain: " << *Chain[0].UserInst << " users:\n";
+          for (SmallPtrSet<Instruction*, 4>::const_iterator I =3D Users.be=
gin(),
+                 E =3D Users.end(); I !=3D E; ++I) {
+            dbgs() << "  " << **I << "\n";
+          });
+    return false;
+  }
+  assert(!Chain.empty() && "empty IV chains are not allowed");
+
+  // The chain itself may require a register, so intialize cost to 1.
+  int cost =3D 1;
+
+  // A complete chain likely eliminates the need for keeping the original =
IV in
+  // a register. LSR does not currently know how to form a complete chain =
unless
+  // the header phi already exists.
+  if (isa<PHINode>(Chain.back().UserInst)
+      && SE.getSCEV(Chain.back().UserInst) =3D=3D Chain[0].IncExpr) {
+    --cost;
+  }
+  const SCEV *LastIncExpr =3D 0;
+  unsigned NumConstIncrements =3D 0;
+  unsigned NumVarIncrements =3D 0;
+  unsigned NumReusedIncrements =3D 0;
+  for (IVChain::const_iterator I =3D llvm::next(Chain.begin()), E =3D Chai=
n.end();
+       I !=3D E; ++I) {
+
+    if (I->IncExpr->isZero())
+      continue;
+
+    // Incrementing by zero or some constant is neutral. We assume constan=
ts can
+    // be folded into an addressing mode or an add's immediate operand.
+    if (isa<SCEVConstant>(I->IncExpr)) {
+      ++NumConstIncrements;
+      continue;
+    }
+
+    if (I->IncExpr =3D=3D LastIncExpr)
+      ++NumReusedIncrements;
+    else
+      ++NumVarIncrements;
+
+    LastIncExpr =3D I->IncExpr;
+  }
+  // An IV chain with a single increment is handled by LSR's postinc
+  // uses. However, a chain with multiple increments requires keeping the =
IV's
+  // value live longer than it needs to be if chained.
+  if (NumConstIncrements > 1)
+    --cost;
+
+  // Materializing increment expressions in the preheader that didn't exis=
t in
+  // the original code may cost a register. For example, sign-extended arr=
ay
+  // indices can produce ridiculous increments like this:
+  // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
+  cost +=3D NumVarIncrements;
+
+  // Reusing variable increments likely saves a register to hold the multi=
ple of
+  // the stride.
+  cost -=3D NumReusedIncrements;
+
+  DEBUG(dbgs() << "Chain: " << *Chain[0].UserInst << " Cost: " << cost << =
"\n");
+
+  return cost < 0;
+}
+
+/// ChainInstruction - Add this IV user to an existing chain or make it th=
e head
+/// of a new chain.
+void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVO=
per,
+                                   SmallVectorImpl<ChainUsers> &ChainUsers=
Vec) {
+  // When IVs are used as types of varying widths, they are generally conv=
erted
+  // to a wider type with some uses remaining narrow under a (free) trunc.
+  Value *NextIV =3D getWideOperand(IVOper);
+
+  // Visit all existing chains. Check if its IVOper can be computed as a
+  // profitable loop invariant increment from the last link in the Chain.
+  unsigned ChainIdx =3D 0, NChains =3D IVChainVec.size();
+  const SCEV *LastIncExpr =3D 0;
+  for (; ChainIdx < NChains; ++ChainIdx) {
+    Value *PrevIV =3D getWideOperand(IVChainVec[ChainIdx].back().IVOperand=
);
+    if (!isCompatibleIVType(PrevIV, NextIV))
+      continue;
+
+    // A phi node terminates a chain.
+    if (isa<PHINode>(UserInst)
+        && isa<PHINode>(IVChainVec[ChainIdx].back().UserInst))
+      continue;
+
+    if (const SCEV *IncExpr =3D
+        getProfitableChainIncrement(NextIV, PrevIV, IVChainVec[ChainIdx],
+                                    L, SE, TLI)) {
+      LastIncExpr =3D IncExpr;
+      break;
+    }
+  }
+  // If we haven't found a chain, create a new one, unless we hit the max.=
 Don't
+  // bother for phi nodes, because they must be last in the chain.
+  if (ChainIdx =3D=3D NChains) {
+    if (isa<PHINode>(UserInst))
+      return;
+    if (NChains >=3D MaxChains && !StressIVChain) {
+      DEBUG(dbgs() << "IV Chain Limit\n");
+      return;
+    }
+    LastIncExpr =3D SE.getSCEV(NextIV);
+    // IVUsers may have skipped over sign/zero extensions. We don't curren=
tly
+    // attempt to form chains involving extensions unless they can be hois=
ted
+    // into this loop's AddRec.
+    if (!isa<SCEVAddRecExpr>(LastIncExpr))
+      return;
+    ++NChains;
+    IVChainVec.resize(NChains);
+    ChainUsersVec.resize(NChains);
+    DEBUG(dbgs() << "IV Head: (" << *UserInst << ") IV=3D" << *LastIncExpr
+          << "\n");
+  }
+  else
+    DEBUG(dbgs() << "IV  Inc: (" << *UserInst << ") IV+" << *LastIncExpr
+          << "\n");
+
+  // Add this IV user to the end of the chain.
+  IVChainVec[ChainIdx].push_back(IVInc(UserInst, IVOper, LastIncExpr));
+
+  SmallPtrSet<Instruction*,4> &NearUsers =3D ChainUsersVec[ChainIdx].NearU=
sers;
+  // This chain's NearUsers become FarUsers.
+  if (!LastIncExpr->isZero()) {
+    ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
+                                            NearUsers.end());
+    NearUsers.clear();
+  }
+
+  // All other uses of IVOperand become near uses of the chain.
+  // We currently ignore intermediate values within SCEV expressions, assu=
ming
+  // they will eventually be used be the current chain, or can be computed
+  // from one of the chain increments. To be more precise we could
+  // transitively follow its user and only add leaf IV users to the set.
+  for (Value::use_iterator UseIter =3D IVOper->use_begin(),
+         UseEnd =3D IVOper->use_end(); UseIter !=3D UseEnd; ++UseIter) {
+    Instruction *OtherUse =3D dyn_cast<Instruction>(*UseIter);
+    if (!OtherUse || OtherUse =3D=3D UserInst)
+      continue;
+    if (SE.isSCEVable(OtherUse->getType())
+        && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
+        && IU.isIVUserOrOperand(OtherUse)) {
+      continue;
+    }
+    NearUsers.insert(OtherUse);
+  }
+
+  // Since this user is part of the chain, it's no longer considered a use
+  // of the chain.
+  ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
+}
+
+/// CollectChains - Populate the vector of Chains.
+///
+/// This decreases ILP at the architecture level. Targets with ample regis=
ters,
+/// multiple memory ports, and no register renaming probably don't want
+/// this. However, such targets should probably disable LSR altogether.
+///
+/// The job of LSR is to make a reasonable choice of induction variables a=
cross
+/// the loop. Subsequent passes can easily "unchain" computation exposing =
more
+/// ILP *within the loop* if the target wants it.
+///
+/// Finding the best IV chain is potentially a scheduling problem. Since L=
SR
+/// will not reorder memory operations, it will recognize this as a chain,=
 but
+/// will generate redundant IV increments. Ideally this would be corrected=
 later
+/// by a smart scheduler:
+///        =3D A[i]
+///        =3D A[i+x]
+/// A[i]   =3D
+/// A[i+x] =3D
+///
+/// TODO: Walk the entire domtree within this loop, not just the path to t=
he
+/// loop latch. This will discover chains on side paths, but requires
+/// maintaining multiple copies of the Chains state.
+void LSRInstance::CollectChains() {
+  SmallVector<ChainUsers, 8> ChainUsersVec;
+
+  SmallVector<BasicBlock *,8> LatchPath;
+  BasicBlock *LoopHeader =3D L->getHeader();
+  for (DomTreeNode *Rung =3D DT.getNode(L->getLoopLatch());
+       Rung->getBlock() !=3D LoopHeader; Rung =3D Rung->getIDom()) {
+    LatchPath.push_back(Rung->getBlock());
+  }
+  LatchPath.push_back(LoopHeader);
+
+  // Walk the instruction stream from the loop header to the loop latch.
+  for (SmallVectorImpl<BasicBlock *>::reverse_iterator
+         BBIter =3D LatchPath.rbegin(), BBEnd =3D LatchPath.rend();
+       BBIter !=3D BBEnd; ++BBIter) {
+    for (BasicBlock::iterator I =3D (*BBIter)->begin(), E =3D (*BBIter)->e=
nd();
+         I !=3D E; ++I) {
+      // Skip instructions that weren't seen by IVUsers analysis.
+      if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
+        continue;
+
+      // Ignore users that are part of a SCEV expression. This way we only
+      // consider leaf IV Users. This effectively rediscovers a portion of
+      // IVUsers analysis but in program order this time.
+      if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
+        continue;
+
+      // Remove this instruction from any NearUsers set it may be in.
+      for (unsigned ChainIdx =3D 0, NChains =3D IVChainVec.size();
+           ChainIdx < NChains; ++ChainIdx) {
+        ChainUsersVec[ChainIdx].NearUsers.erase(I);
+      }
+      // Search for operands that can be chained.
+      SmallPtrSet<Instruction*, 4> UniqueOperands;
+      User::op_iterator IVOpEnd =3D I->op_end();
+      User::op_iterator IVOpIter =3D findIVOperand(I->op_begin(), IVOpEnd,=
 L, SE);
+      while (IVOpIter !=3D IVOpEnd) {
+        Instruction *IVOpInst =3D cast<Instruction>(*IVOpIter);
+        if (UniqueOperands.insert(IVOpInst))
+          ChainInstruction(I, IVOpInst, ChainUsersVec);
+        IVOpIter =3D findIVOperand(llvm::next(IVOpIter), IVOpEnd, L, SE);
+      }
+    } // Continue walking down the instructions.
+  } // Continue walking down the domtree.
+  // Visit phi backedges to determine if the chain can generate the IV pos=
tinc.
+  for (BasicBlock::iterator I =3D L->getHeader()->begin();
+       PHINode *PN =3D dyn_cast<PHINode>(I); ++I) {
+    if (!SE.isSCEVable(PN->getType()))
+      continue;
+
+    Instruction *IncV =3D
+      dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()=
));
+    if (IncV)
+      ChainInstruction(PN, IncV, ChainUsersVec);
+  }
+  // Remove any unprofitable chains.
+  unsigned ChainIdx =3D 0;
+  for (unsigned UsersIdx =3D 0, NChains =3D IVChainVec.size();
+       UsersIdx < NChains; ++UsersIdx) {
+    if (!isProfitableChain(IVChainVec[UsersIdx],
+                           ChainUsersVec[UsersIdx].FarUsers, SE, TLI))
+      continue;
+    // Preserve the chain at UsesIdx.
+    if (ChainIdx !=3D UsersIdx)
+      IVChainVec[ChainIdx] =3D IVChainVec[UsersIdx];
+    FinalizeChain(IVChainVec[ChainIdx]);
+    ++ChainIdx;
+  }
+  IVChainVec.resize(ChainIdx);
+}
+
+void LSRInstance::FinalizeChain(IVChain &Chain) {
+  assert(!Chain.empty() && "empty IV chains are not allowed");
+  DEBUG(dbgs() << "Final Chain: " << *Chain[0].UserInst << "\n");
+
+  for (IVChain::const_iterator I =3D llvm::next(Chain.begin()), E =3D Chai=
n.end();
+       I !=3D E; ++I) {
+    DEBUG(dbgs() << "        Inc: " << *I->UserInst << "\n");
+    User::op_iterator UseI =3D
+      std::find(I->UserInst->op_begin(), I->UserInst->op_end(), I->IVOpera=
nd);
+    assert(UseI !=3D I->UserInst->op_end() && "cannot find IV operand");
+    IVIncSet.insert(UseI);
+  }
+}
+
+/// Return true if the IVInc can be folded into an addressing mode.
+static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
+                             Value *Operand, const TargetLowering *TLI) {
+  const SCEVConstant *IncConst =3D dyn_cast<SCEVConstant>(IncExpr);
+  if (!IncConst || !isAddressUse(UserInst, Operand))
+    return false;
+
+  if (IncConst->getValue()->getValue().getMinSignedBits() > 64)
+    return false;
+
+  int64_t IncOffset =3D IncConst->getValue()->getSExtValue();
+  if (!isAlwaysFoldable(IncOffset, /*BaseGV=3D*/0, /*HaseBaseReg=3D*/false,
+                       LSRUse::Address, getAccessType(UserInst), TLI))
+    return false;
+
+  return true;
+}
+
+/// GenerateIVChains - Generate an add or subtract for each IVInc in a cha=
in to
+/// materialize the IV user's operand from the previous IV user's operand.
+void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewr=
iter,
+                                  SmallVectorImpl<WeakVH> &DeadInsts) {
+  // Find the new IVOperand for the head of the chain. It may have been re=
placed
+  // by LSR.
+  const IVInc &Head =3D Chain[0];
+  User::op_iterator IVOpEnd =3D Head.UserInst->op_end();
+  User::op_iterator IVOpIter =3D findIVOperand(Head.UserInst->op_begin(),
+                                             IVOpEnd, L, SE);
+  Value *IVSrc =3D 0;
+  while (IVOpIter !=3D IVOpEnd) {
+    IVSrc =3D getWideOperand(*IVOpIter);
+
+    // If this operand computes the expression that the chain needs, we ma=
y use
+    // it. (Check this after setting IVSrc which is used below.)
+    //
+    // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
+    // narrow for the chain, so we can no longer use it. We do allow using=
 a
+    // wider phi, assuming the LSR checked for free truncation. In that ca=
se we
+    // should already have a truncate on this operand such that
+    // getSCEV(IVSrc) =3D=3D IncExpr.
+    if (SE.getSCEV(*IVOpIter) =3D=3D Head.IncExpr
+        || SE.getSCEV(IVSrc) =3D=3D Head.IncExpr) {
+      break;
+    }
+    IVOpIter =3D findIVOperand(llvm::next(IVOpIter), IVOpEnd, L, SE);
+  }
+  if (IVOpIter =3D=3D IVOpEnd) {
+    // Gracefully give up on this chain.
+    DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
+    return;
+  }
+
+  DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
+  Type *IVTy =3D IVSrc->getType();
+  Type *IntTy =3D SE.getEffectiveSCEVType(IVTy);
+  const SCEV *LeftOverExpr =3D 0;
+  for (IVChain::const_iterator IncI =3D llvm::next(Chain.begin()),
+         IncE =3D Chain.end(); IncI !=3D IncE; ++IncI) {
+
+    Instruction *InsertPt =3D IncI->UserInst;
+    if (isa<PHINode>(InsertPt))
+      InsertPt =3D L->getLoopLatch()->getTerminator();
+
+    // IVOper will replace the current IV User's operand. IVSrc is the IV
+    // value currently held in a register.
+    Value *IVOper =3D IVSrc;
+    if (!IncI->IncExpr->isZero()) {
+      // IncExpr was the result of subtraction of two narrow values, so mu=
st
+      // be signed.
+      const SCEV *IncExpr =3D SE.getNoopOrSignExtend(IncI->IncExpr, IntTy);
+      LeftOverExpr =3D LeftOverExpr ?
+        SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
+    }
+    if (LeftOverExpr && !LeftOverExpr->isZero()) {
+      // Expand the IV increment.
+      Rewriter.clearPostInc();
+      Value *IncV =3D Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt=
);
+      const SCEV *IVOperExpr =3D SE.getAddExpr(SE.getUnknown(IVSrc),
+                                             SE.getUnknown(IncV));
+      IVOper =3D Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
+
+      // If an IV increment can't be folded, use it as the next IV value.
+      if (!canFoldIVIncExpr(LeftOverExpr, IncI->UserInst, IncI->IVOperand,
+                            TLI)) {
+        assert(IVTy =3D=3D IVOper->getType() && "inconsistent IV increment=
 type");
+        IVSrc =3D IVOper;
+        LeftOverExpr =3D 0;
+      }
+    }
+    Type *OperTy =3D IncI->IVOperand->getType();
+    if (IVTy !=3D OperTy) {
+      assert(SE.getTypeSizeInBits(IVTy) >=3D SE.getTypeSizeInBits(OperTy) =
&&
+             "cannot extend a chained IV");
+      IRBuilder<> Builder(InsertPt);
+      IVOper =3D Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
+    }
+    IncI->UserInst->replaceUsesOfWith(IncI->IVOperand, IVOper);
+    DeadInsts.push_back(IncI->IVOperand);
+  }
+  // If LSR created a new, wider phi, we may also replace its postinc. We =
only
+  // do this if we also found a wide value for the head of the chain.
+  if (isa<PHINode>(Chain.back().UserInst)) {
+    for (BasicBlock::iterator I =3D L->getHeader()->begin();
+         PHINode *Phi =3D dyn_cast<PHINode>(I); ++I) {
+      if (!isCompatibleIVType(Phi, IVSrc))
+        continue;
+      Instruction *PostIncV =3D dyn_cast<Instruction>(
+        Phi->getIncomingValueForBlock(L->getLoopLatch()));
+      if (!PostIncV || (SE.getSCEV(PostIncV) !=3D SE.getSCEV(IVSrc)))
+        continue;
+      Value *IVOper =3D IVSrc;
+      Type *PostIncTy =3D PostIncV->getType();
+      if (IVTy !=3D PostIncTy) {
+        assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
+        IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
+        Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
+        IVOper =3D Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain"=
);
+      }
+      Phi->replaceUsesOfWith(PostIncV, IVOper);
+      DeadInsts.push_back(PostIncV);
+    }
+  }
+}
+
 void LSRInstance::CollectFixupsAndInitialFormulae() {
   for (IVUsers::const_iterator UI =3D IU.begin(), E =3D IU.end(); UI !=3D =
E; ++UI) {
+    Instruction *UserInst =3D UI->getUser();
+    // Skip IV users that are part of profitable IV Chains.
+    User::op_iterator UseI =3D std::find(UserInst->op_begin(), UserInst->o=
p_end(),
+                                       UI->getOperandValToReplace());
+    assert(UseI !=3D UserInst->op_end() && "cannot find IV operand");
+    if (IVIncSet.count(UseI))
+      continue;
+
     // Record the uses.
     LSRFixup &LF =3D getNewFixup();
-    LF.UserInst =3D UI->getUser();
+    LF.UserInst =3D UserInst;
     LF.OperandValToReplace =3D UI->getOperandValToReplace();
     LF.PostIncLoops =3D UI->getPostIncLoops();
=20
@@ -2914,6 +3584,7 @@
 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
   DenseSet<const SCEV *> VisitedRegs;
   SmallPtrSet<const SCEV *, 16> Regs;
+  SmallPtrSet<const SCEV *, 16> LoserRegs;
 #ifndef NDEBUG
   bool ChangedFormulae =3D false;
 #endif
@@ -2933,46 +3604,66 @@
          FIdx !=3D NumForms; ++FIdx) {
       Formula &F =3D LU.Formulae[FIdx];
=20
-      SmallVector<const SCEV *, 2> Key;
-      for (SmallVectorImpl<const SCEV *>::const_iterator J =3D F.BaseRegs.=
begin(),
-           JE =3D F.BaseRegs.end(); J !=3D JE; ++J) {
-        const SCEV *Reg =3D *J;
-        if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
-          Key.push_back(Reg);
+      // Some formulas are instant losers. For example, they may depend on
+      // nonexistent AddRecs from other loops. These need to be filtered
+      // immediately, otherwise heuristics could choose them over others l=
eading
+      // to an unsatisfactory solution. Passing LoserRegs into RateFormula=
 here
+      // avoids the need to recompute this information across formulae usi=
ng the
+      // same bad AddRec. Passing LoserRegs is also essential unless we re=
move
+      // the corresponding bad register from the Regs set.
+      Cost CostF;
+      Regs.clear();
+      CostF.RateFormula(F, Regs, VisitedRegs, L, LU.Offsets, SE, DT,
+                        &LoserRegs);
+      if (CostF.isLoser()) {
+        // During initial formula generation, undesirable formulae are gen=
erated
+        // by uses within other loops that have some non-trivial address m=
ode or
+        // use the postinc form of the IV. LSR needs to provide these form=
ulae
+        // as the basis of rediscovering the desired formula that uses an =
AddRec
+        // corresponding to the existing phi. Once all formulae have been
+        // generated, these initial losers may be pruned.
+        DEBUG(dbgs() << "  Filtering loser "; F.print(dbgs());
+              dbgs() << "\n");
       }
-      if (F.ScaledReg &&
-          RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
-        Key.push_back(F.ScaledReg);
-      // Unstable sort by host order ok, because this is only used for
-      // uniquifying.
-      std::sort(Key.begin(), Key.end());
-
-      std::pair<BestFormulaeTy::const_iterator, bool> P =3D
-        BestFormulae.insert(std::make_pair(Key, FIdx));
-      if (!P.second) {
+      else {
+        SmallVector<const SCEV *, 2> Key;
+        for (SmallVectorImpl<const SCEV *>::const_iterator J =3D F.BaseReg=
s.begin(),
+               JE =3D F.BaseRegs.end(); J !=3D JE; ++J) {
+          const SCEV *Reg =3D *J;
+          if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
+            Key.push_back(Reg);
+        }
+        if (F.ScaledReg &&
+            RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
+          Key.push_back(F.ScaledReg);
+        // Unstable sort by host order ok, because this is only used for
+        // uniquifying.
+        std::sort(Key.begin(), Key.end());
+
+        std::pair<BestFormulaeTy::const_iterator, bool> P =3D
+          BestFormulae.insert(std::make_pair(Key, FIdx));
+        if (P.second)
+          continue;
+
         Formula &Best =3D LU.Formulae[P.first->second];
=20
-        Cost CostF;
-        CostF.RateFormula(F, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
+        Cost CostBest;
         Regs.clear();
-        Cost CostBest;
         CostBest.RateFormula(Best, Regs, VisitedRegs, L, LU.Offsets, SE, D=
T);
-        Regs.clear();
         if (CostF < CostBest)
           std::swap(F, Best);
         DEBUG(dbgs() << "  Filtering out formula "; F.print(dbgs());
               dbgs() << "\n"
                         "    in favor of formula "; Best.print(dbgs());
               dbgs() << '\n');
+      }
 #ifndef NDEBUG
-        ChangedFormulae =3D true;
+      ChangedFormulae =3D true;
 #endif
-        LU.DeleteFormula(F);
-        --FIdx;
-        --NumForms;
-        Any =3D true;
-        continue;
-      }
+      LU.DeleteFormula(F);
+      --FIdx;
+      --NumForms;
+      Any =3D true;
     }
=20
     // Now that we've filtered out some formulae, recompute the Regs set.
@@ -3284,24 +3975,29 @@
     if (LU.Regs.count(*I))
       ReqRegs.insert(*I);
=20
-  bool AnySatisfiedReqRegs =3D false;
   SmallPtrSet<const SCEV *, 16> NewRegs;
   Cost NewCost;
-retry:
   for (SmallVectorImpl<Formula>::const_iterator I =3D LU.Formulae.begin(),
        E =3D LU.Formulae.end(); I !=3D E; ++I) {
     const Formula &F =3D *I;
=20
     // Ignore formulae which do not use any of the required registers.
+    bool SatisfiedReqReg =3D true;
     for (SmallSetVector<const SCEV *, 4>::const_iterator J =3D ReqRegs.beg=
in(),
          JE =3D ReqRegs.end(); J !=3D JE; ++J) {
       const SCEV *Reg =3D *J;
       if ((!F.ScaledReg || F.ScaledReg !=3D Reg) &&
           std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) =3D=3D
-          F.BaseRegs.end())
-        goto skip;
+          F.BaseRegs.end()) {
+        SatisfiedReqReg =3D false;
+        break;
+      }
     }
-    AnySatisfiedReqRegs =3D true;
+    if (!SatisfiedReqReg) {
+      // If none of the formulae satisfied the required registers, then we=
 could
+      // clear ReqRegs and try again. Currently, we simply give up in this=
 case.
+      continue;
+    }
=20
     // Evaluate the cost of the current formula. If it's already worse than
     // the current best, prune the search at that point.
@@ -3317,7 +4013,7 @@
           VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
       } else {
         DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
-              dbgs() << ". Regs:";
+              dbgs() << ".\n Regs:";
               for (SmallPtrSet<const SCEV *, 16>::const_iterator
                    I =3D NewRegs.begin(), E =3D NewRegs.end(); I !=3D E; +=
+I)
                 dbgs() << ' ' << **I;
@@ -3328,18 +4024,6 @@
       }
       Workspace.pop_back();
     }
-  skip:;
-  }
-
-  if (!EnableRetry && !AnySatisfiedReqRegs)
-    return;
-
-  // If none of the formulae had all of the required registers, relax the
-  // constraint so that we don't exclude all formulae.
-  if (!AnySatisfiedReqRegs) {
-    assert(!ReqRegs.empty() && "Solver failed even without required regist=
ers");
-    ReqRegs.clear();
-    goto retry;
   }
 }
=20
@@ -3435,9 +4119,10 @@
 /// AdjustInsertPositionForExpand - Determine an input position which will=
 be
 /// dominated by the operands and which will dominate the result.
 BasicBlock::iterator
-LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
+LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
                                            const LSRFixup &LF,
-                                           const LSRUse &LU) const {
+                                           const LSRUse &LU,
+                                           SCEVExpander &Rewriter) const {
   // Collect some instructions which must be dominated by the
   // expanding replacement. These must be dominated by any operands that
   // will be required in the expansion.
@@ -3472,9 +4157,13 @@
     }
   }
=20
+  assert(!isa<PHINode>(LowestIP) && !isa<LandingPadInst>(LowestIP)
+         && !isa<DbgInfoIntrinsic>(LowestIP) &&
+         "Insertion point must be a normal instruction");
+
   // Then, climb up the immediate dominator tree as far as we can go while
   // still being dominated by the input positions.
-  IP =3D HoistInsertPosition(IP, Inputs);
+  BasicBlock::iterator IP =3D HoistInsertPosition(LowestIP, Inputs);
=20
   // Don't insert instructions before PHI nodes.
   while (isa<PHINode>(IP)) ++IP;
@@ -3485,6 +4174,11 @@
   // Ignore debug intrinsics.
   while (isa<DbgInfoIntrinsic>(IP)) ++IP;
=20
+  // Set IP below instructions recently inserted by SCEVExpander. This kee=
ps the
+  // IP consistent across expansions and allows the previously inserted
+  // instructions to be reused by subsequent expansion.
+  while (Rewriter.isInsertedInstruction(IP) && IP !=3D LowestIP) ++IP;
+
   return IP;
 }
=20
@@ -3499,7 +4193,7 @@
=20
   // Determine an input position which will be dominated by the operands a=
nd
   // which will dominate the result.
-  IP =3D AdjustInsertPositionForExpand(IP, LF, LU);
+  IP =3D AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
=20
   // Inform the Rewriter if we have a post-increment use, so that it can
   // perform an advantageous expansion.
@@ -3775,10 +4469,20 @@
   SmallVector<WeakVH, 16> DeadInsts;
=20
   SCEVExpander Rewriter(SE, "lsr");
+#ifndef NDEBUG
+  Rewriter.setDebugType(DEBUG_TYPE);
+#endif
   Rewriter.disableCanonicalMode();
   Rewriter.enableLSRMode();
   Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
=20
+  // Mark phi nodes that terminate chains so the expander tries to reuse t=
hem.
+  for (SmallVectorImpl<IVChain>::const_iterator ChainI =3D IVChainVec.begi=
n(),
+         ChainE =3D IVChainVec.end(); ChainI !=3D ChainE; ++ChainI) {
+    if (PHINode *PN =3D dyn_cast<PHINode>(ChainI->back().UserInst))
+      Rewriter.setChainedPhi(PN);
+  }
+
   // Expand the new value definitions and update the users.
   for (SmallVectorImpl<LSRFixup>::const_iterator I =3D Fixups.begin(),
        E =3D Fixups.end(); I !=3D E; ++I) {
@@ -3789,6 +4493,11 @@
     Changed =3D true;
   }
=20
+  for (SmallVectorImpl<IVChain>::const_iterator ChainI =3D IVChainVec.begi=
n(),
+         ChainE =3D IVChainVec.end(); ChainI !=3D ChainE; ++ChainI) {
+    GenerateIVChain(*ChainI, Rewriter, DeadInsts);
+    Changed =3D true;
+  }
   // Clean up after ourselves. This must be done before deleting any
   // instructions.
   Rewriter.clear();
@@ -3804,11 +4513,29 @@
     TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
=20
   // If LoopSimplify form is not available, stay out of trouble.
-  if (!L->isLoopSimplifyForm()) return;
+  if (!L->isLoopSimplifyForm())
+    return;
=20
   // If there's no interesting work to be done, bail early.
   if (IU.empty()) return;
=20
+#ifndef NDEBUG
+  // All dominating loops must have preheaders, or SCEVExpander may not be=
 able
+  // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
+  //
+  // IVUsers analysis should only create users that are dominated by simpl=
e loop
+  // headers. Since this loop should dominate all of its users, its user l=
ist
+  // should be empty if this loop itself is not within a simple loop nest.
+  for (DomTreeNode *Rung =3D DT.getNode(L->getLoopPreheader());
+       Rung; Rung =3D Rung->getIDom()) {
+    BasicBlock *BB =3D Rung->getBlock();
+    const Loop *DomLoop =3D LI.getLoopFor(BB);
+    if (DomLoop && DomLoop->getHeader() =3D=3D BB) {
+      assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop n=
est");
+    }
+  }
+#endif // DEBUG
+
   DEBUG(dbgs() << "\nLSR on loop ";
         WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=3D*/false);
         dbgs() << ":\n");
@@ -3821,24 +4548,18 @@
   if (IU.empty()) return;
=20
   // Skip nested loops until we can model them better with formulae.
-  if (!EnableNested && !L->empty()) {
-
-    if (EnablePhiElim) {
-      // Remove any extra phis created by processing inner loops.
-      SmallVector<WeakVH, 16> DeadInsts;
-      SCEVExpander Rewriter(SE, "lsr");
-      Changed |=3D Rewriter.replaceCongruentIVs(L, &DT, DeadInsts);
-      Changed |=3D DeleteTriviallyDeadInstructions(DeadInsts);
-    }
+  if (!L->empty()) {
     DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
     return;
   }
=20
   // Start collecting data and preparing for the solver.
+  CollectChains();
   CollectInterestingTypesAndFactors();
   CollectFixupsAndInitialFormulae();
   CollectLoopInvariantFixupsAndFormulae();
=20
+  assert(!Uses.empty() && "IVUsers reported at least one use");
   DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
         print_uses(dbgs()));
=20
@@ -3875,14 +4596,6 @@
=20
   // Now that we've decided what we want, make it so.
   ImplementSolution(Solution, P);
-
-  if (EnablePhiElim) {
-    // Remove any extra phis created by processing inner loops.
-    SmallVector<WeakVH, 16> DeadInsts;
-    SCEVExpander Rewriter(SE, "lsr");
-    Changed |=3D Rewriter.replaceCongruentIVs(L, &DT, DeadInsts);
-    Changed |=3D DeleteTriviallyDeadInstructions(DeadInsts);
-  }
 }
=20
 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
@@ -4008,9 +4721,21 @@
   // Run the main LSR transformation.
   Changed |=3D LSRInstance(TLI, L, this).getChanged();
=20
-  // At this point, it is worth checking to see if any recurrence PHIs are=
 also
-  // dead, so that we can remove them as well.
+  // Remove any extra phis created by processing inner loops.
   Changed |=3D DeleteDeadPHIs(L->getHeader());
-
+  if (EnablePhiElim) {
+    SmallVector<WeakVH, 16> DeadInsts;
+    SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), "lsr");
+#ifndef NDEBUG
+    Rewriter.setDebugType(DEBUG_TYPE);
+#endif
+    unsigned numFolded =3D Rewriter.
+      replaceCongruentIVs(L, &getAnalysis<DominatorTree>(), DeadInsts, TLI=
);
+    if (numFolded) {
+      Changed =3D true;
+      DeleteTriviallyDeadInstructions(DeadInsts);
+      DeleteDeadPHIs(L->getHeader());
+    }
+  }
   return Changed;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/LoopUnrollPass.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/LoopUnrollPass.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -40,10 +40,9 @@
   cl::desc("Allows loops to be partially unrolled until "
            "-unroll-threshold loop size is reached."));
=20
-// Temporary flag to be removed in 3.0
 static cl::opt<bool>
-NoSCEVUnroll("disable-unroll-scev", cl::init(false), cl::Hidden,
-  cl::desc("Use ScalarEvolution to analyze loop trip counts for unrolling"=
));
+UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidde=
n,
+  cl::desc("Unroll loops with run-time trip counts"));
=20
 namespace {
   class LoopUnroll : public LoopPass {
@@ -68,6 +67,10 @@
     // explicit -unroll-threshold).
     static const unsigned OptSizeUnrollThreshold =3D 50;
=20
+    // Default unroll count for loops with run-time trip count if
+    // -unroll-count is not set
+    static const unsigned UnrollRuntimeCount =3D 8;
+
     unsigned CurrentCount;
     unsigned CurrentThreshold;
     bool     CurrentAllowPartial;
@@ -101,6 +104,7 @@
 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
 INITIALIZE_PASS_DEPENDENCY(LCSSA)
+INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, fals=
e)
=20
 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartia=
l) {
@@ -147,23 +151,21 @@
   // Find trip count and trip multiple if count is not available
   unsigned TripCount =3D 0;
   unsigned TripMultiple =3D 1;
-  if (!NoSCEVUnroll) {
-    // Find "latch trip count". UnrollLoop assumes that control cannot exit
-    // via the loop latch on any iteration prior to TripCount. The loop ma=
y exit
-    // early via an earlier branch.
-    BasicBlock *LatchBlock =3D L->getLoopLatch();
-    if (LatchBlock) {
-      TripCount =3D SE->getSmallConstantTripCount(L, LatchBlock);
-      TripMultiple =3D SE->getSmallConstantTripMultiple(L, LatchBlock);
-    }
+  // Find "latch trip count". UnrollLoop assumes that control cannot exit
+  // via the loop latch on any iteration prior to TripCount. The loop may =
exit
+  // early via an earlier branch.
+  BasicBlock *LatchBlock =3D L->getLoopLatch();
+  if (LatchBlock) {
+    TripCount =3D SE->getSmallConstantTripCount(L, LatchBlock);
+    TripMultiple =3D SE->getSmallConstantTripMultiple(L, LatchBlock);
   }
-  else {
-    TripCount =3D L->getSmallConstantTripCount();
-    if (TripCount =3D=3D 0)
-      TripMultiple =3D L->getSmallConstantTripMultiple();
-  }
-  // Automatically select an unroll count.
+  // Use a default unroll-count if the user doesn't specify a value
+  // and the trip count is a run-time value.  The default is different
+  // for run-time or compile-time trip count loops.
   unsigned Count =3D CurrentCount;
+  if (UnrollRuntime && CurrentCount =3D=3D 0 && TripCount =3D=3D 0)
+    Count =3D UnrollRuntimeCount;
+
   if (Count =3D=3D 0) {
     // Conservative heuristic: if we know the trip count, see if we can
     // completely unroll (subject to the threshold, checked below); otherw=
ise
@@ -188,15 +190,23 @@
     if (TripCount !=3D 1 && Size > Threshold) {
       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
             << " because size: " << Size << ">" << Threshold << "\n");
-      if (!CurrentAllowPartial) {
+      if (!CurrentAllowPartial && !(UnrollRuntime && TripCount =3D=3D 0)) {
         DEBUG(dbgs() << "  will not try to unroll partially because "
               << "-unroll-allow-partial not given\n");
         return false;
       }
-      // Reduce unroll count to be modulo of TripCount for partial unrolli=
ng
-      Count =3D Threshold / LoopSize;
-      while (Count !=3D 0 && TripCount%Count !=3D 0) {
-        Count--;
+      if (TripCount) {
+        // Reduce unroll count to be modulo of TripCount for partial unrol=
ling
+        Count =3D Threshold / LoopSize;
+        while (Count !=3D 0 && TripCount%Count !=3D 0)
+          Count--;
+      }
+      else if (UnrollRuntime) {
+        // Reduce unroll count to be a lower power-of-two value
+        while (Count !=3D 0 && Size > Threshold) {
+          Count >>=3D 1;
+          Size =3D LoopSize*Count;
+        }
       }
       if (Count < 2) {
         DEBUG(dbgs() << "  could not unroll partially\n");
@@ -207,7 +217,7 @@
   }
=20
   // Unroll the loop.
-  if (!UnrollLoop(L, Count, TripCount, TripMultiple, LI, &LPM))
+  if (!UnrollLoop(L, Count, TripCount, UnrollRuntime, TripMultiple, LI, &L=
PM))
     return false;
=20
   return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/LoopUnswitch.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/LoopUnswitch.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/LoopUnswitch.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -32,7 +32,7 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
 #include "llvm/Instructions.h"
-#include "llvm/Analysis/InlineCost.h"
+#include "llvm/Analysis/CodeMetrics.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/LoopPass.h"
@@ -48,6 +48,7 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
 #include <algorithm>
+#include <map>
 #include <set>
 using namespace llvm;
=20
@@ -56,14 +57,70 @@
 STATISTIC(NumSelects , "Number of selects unswitched");
 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
+STATISTIC(TotalInsts,  "Total number of instructions analyzed");
=20
-// The specific value of 50 here was chosen based only on intuition and a
+// The specific value of 100 here was chosen based only on intuition and a
 // few specific examples.
 static cl::opt<unsigned>
 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
-          cl::init(50), cl::Hidden);
- =20
+          cl::init(100), cl::Hidden);
+
 namespace {
+
+  class LUAnalysisCache {
+
+    typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
+      UnswitchedValsMap;
+
+    typedef UnswitchedValsMap::iterator UnswitchedValsIt;
+
+    struct LoopProperties {
+      unsigned CanBeUnswitchedCount;
+      unsigned SizeEstimation;
+      UnswitchedValsMap UnswitchedVals;
+    };
+
+    // Here we use std::map instead of DenseMap, since we need to keep val=
id
+    // LoopProperties pointer for current loop for better performance.
+    typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
+    typedef LoopPropsMap::iterator LoopPropsMapIt;
+
+    LoopPropsMap LoopsProperties;
+    UnswitchedValsMap* CurLoopInstructions;
+    LoopProperties* CurrentLoopProperties;
+
+    // Max size of code we can produce on remained iterations.
+    unsigned MaxSize;
+
+    public:
+
+      LUAnalysisCache() :
+        CurLoopInstructions(NULL), CurrentLoopProperties(NULL),
+        MaxSize(Threshold)
+      {}
+
+      // Analyze loop. Check its size, calculate is it possible to unswitch
+      // it. Returns true if we can unswitch this loop.
+      bool countLoop(const Loop* L);
+
+      // Clean all data related to given loop.
+      void forgetLoop(const Loop* L);
+
+      // Mark case value as unswitched.
+      // Since SI instruction can be partly unswitched, in order to avoid
+      // extra unswitching in cloned loops keep track all unswitched value=
s.
+      void setUnswitched(const SwitchInst* SI, const Value* V);
+
+      // Check was this case value unswitched before or not.
+      bool isUnswitched(const SwitchInst* SI, const Value* V);
+
+      // Clone all loop-unswitch related loop properties.
+      // Redistribute unswitching quotas.
+      // Note, that new loop data is stored inside the VMap.
+      void cloneData(const Loop* NewLoop, const Loop* OldLoop,
+                     const ValueToValueMapTy& VMap);
+  };
+
   class LoopUnswitch : public LoopPass {
     LoopInfo *LI;  // Loop information
     LPPassManager *LPM;
@@ -71,8 +128,9 @@
     // LoopProcessWorklist - Used to check if second loop needs processing
     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
     std::vector<Loop*> LoopProcessWorklist;
-    SmallPtrSet<Value *,8> UnswitchedVals;
-   =20
+
+    LUAnalysisCache BranchesInfo;
+
     bool OptimizeForSize;
     bool redoLoop;
=20
@@ -80,9 +138,9 @@
     DominatorTree *DT;
     BasicBlock *loopHeader;
     BasicBlock *loopPreheader;
-   =20
+
     // LoopBlocks contains all of the basic blocks of the loop, including =
the
-    // preheader of the loop, the body of the loop, and the exit blocks of=
 the=20
+    // preheader of the loop, the body of the loop, and the exit blocks of=
 the
     // loop, in that order.
     std::vector<BasicBlock*> LoopBlocks;
     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
@@ -90,8 +148,8 @@
=20
   public:
     static char ID; // Pass ID, replacement for typeid
-    explicit LoopUnswitch(bool Os =3D false) :=20
-      LoopPass(ID), OptimizeForSize(Os), redoLoop(false),=20
+    explicit LoopUnswitch(bool Os =3D false) :
+      LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
       currentLoop(NULL), DT(NULL), loopHeader(NULL),
       loopPreheader(NULL) {
         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
@@ -117,7 +175,7 @@
   private:
=20
     virtual void releaseMemory() {
-      UnswitchedVals.clear();
+      BranchesInfo.forgetLoop(currentLoop);
     }
=20
     /// RemoveLoopFromWorklist - If the specified loop is on the loop work=
list,
@@ -147,7 +205,7 @@
                                               Constant *Val, bool isEqual);
=20
     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
-                                        BasicBlock *TrueDest,=20
+                                        BasicBlock *TrueDest,
                                         BasicBlock *FalseDest,
                                         Instruction *InsertPt);
=20
@@ -160,6 +218,112 @@
=20
   };
 }
+
+// Analyze loop. Check its size, calculate is it possible to unswitch
+// it. Returns true if we can unswitch this loop.
+bool LUAnalysisCache::countLoop(const Loop* L) {
+
+  std::pair<LoopPropsMapIt, bool> InsertRes =3D
+      LoopsProperties.insert(std::make_pair(L, LoopProperties()));
+
+  LoopProperties& Props =3D InsertRes.first->second;
+
+  if (InsertRes.second) {
+    // New loop.
+
+    // Limit the number of instructions to avoid causing significant code
+    // expansion, and the number of basic blocks, to avoid loops with
+    // large numbers of branches which cause loop unswitching to go crazy.
+    // This is a very ad-hoc heuristic.
+
+    // FIXME: This is overly conservative because it does not take into
+    // consideration code simplification opportunities and code that can
+    // be shared by the resultant unswitched loops.
+    CodeMetrics Metrics;
+    for (Loop::block_iterator I =3D L->block_begin(),
+           E =3D L->block_end();
+         I !=3D E; ++I)
+      Metrics.analyzeBasicBlock(*I);
+
+    Props.SizeEstimation =3D std::min(Metrics.NumInsts, Metrics.NumBlocks =
* 5);
+    Props.CanBeUnswitchedCount =3D MaxSize / (Props.SizeEstimation);
+    MaxSize -=3D Props.SizeEstimation * Props.CanBeUnswitchedCount;
+  }
+
+  if (!Props.CanBeUnswitchedCount) {
+    DEBUG(dbgs() << "NOT unswitching loop %"
+          << L->getHeader()->getName() << ", cost too high: "
+          << L->getBlocks().size() << "\n");
+
+    return false;
+  }
+
+  // Be careful. This links are good only before new loop addition.
+  CurrentLoopProperties =3D &Props;
+  CurLoopInstructions =3D &Props.UnswitchedVals;
+
+  return true;
+}
+
+// Clean all data related to given loop.
+void LUAnalysisCache::forgetLoop(const Loop* L) {
+
+  LoopPropsMapIt LIt =3D LoopsProperties.find(L);
+
+  if (LIt !=3D LoopsProperties.end()) {
+    LoopProperties& Props =3D LIt->second;
+    MaxSize +=3D Props.CanBeUnswitchedCount * Props.SizeEstimation;
+    LoopsProperties.erase(LIt);
+  }
+
+  CurrentLoopProperties =3D NULL;
+  CurLoopInstructions =3D NULL;
+}
+
+// Mark case value as unswitched.
+// Since SI instruction can be partly unswitched, in order to avoid
+// extra unswitching in cloned loops keep track all unswitched values.
+void LUAnalysisCache::setUnswitched(const SwitchInst* SI, const Value* V) {
+  (*CurLoopInstructions)[SI].insert(V);
+}
+
+// Check was this case value unswitched before or not.
+bool LUAnalysisCache::isUnswitched(const SwitchInst* SI, const Value* V) {
+  return (*CurLoopInstructions)[SI].count(V);
+}
+
+// Clone all loop-unswitch related loop properties.
+// Redistribute unswitching quotas.
+// Note, that new loop data is stored inside the VMap.
+void LUAnalysisCache::cloneData(const Loop* NewLoop, const Loop* OldLoop,
+                     const ValueToValueMapTy& VMap) {
+
+  LoopProperties& NewLoopProps =3D LoopsProperties[NewLoop];
+  LoopProperties& OldLoopProps =3D *CurrentLoopProperties;
+  UnswitchedValsMap& Insts =3D OldLoopProps.UnswitchedVals;
+
+  // Reallocate "can-be-unswitched quota"
+
+  --OldLoopProps.CanBeUnswitchedCount;
+  unsigned Quota =3D OldLoopProps.CanBeUnswitchedCount;
+  NewLoopProps.CanBeUnswitchedCount =3D Quota / 2;
+  OldLoopProps.CanBeUnswitchedCount =3D Quota - Quota / 2;
+
+  NewLoopProps.SizeEstimation =3D OldLoopProps.SizeEstimation;
+
+  // Clone unswitched values info:
+  // for new loop switches we clone info about values that was
+  // already unswitched and has redundant successors.
+  for (UnswitchedValsIt I =3D Insts.begin(); I !=3D Insts.end(); ++I) {
+    const SwitchInst* OldInst =3D I->first;
+    Value* NewI =3D VMap.lookup(OldInst);
+    const SwitchInst* NewInst =3D cast_or_null<SwitchInst>(NewI);
+    assert(NewInst && "All instructions that are in SrcBB must be in VMap.=
");
+
+    NewLoopProps.UnswitchedVals[NewInst] =3D OldLoopProps.UnswitchedVals[O=
ldInst];
+  }
+}
+
 char LoopUnswitch::ID =3D 0;
 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
                       false, false)
@@ -169,14 +333,18 @@
 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
                       false, false)
=20
-Pass *llvm::createLoopUnswitchPass(bool Os) {=20
-  return new LoopUnswitch(Os);=20
+Pass *llvm::createLoopUnswitchPass(bool Os) {
+  return new LoopUnswitch(Os);
 }
=20
 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
 /// invariant in the loop, or has an invariant piece, return the invariant.
 /// Otherwise, return null.
 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
+
+  // We started analyze new instruction, increment scanned instructions co=
unter.
+  ++TotalInsts;
+
   // We can never unswitch on vector conditions.
   if (Cond->getType()->isVectorTy())
     return 0;
@@ -201,7 +369,7 @@
       if (Value *RHS =3D FindLIVLoopCondition(BO->getOperand(1), L, Change=
d))
         return RHS;
     }
- =20
+
   return 0;
 }
=20
@@ -226,16 +394,36 @@
   return Changed;
 }
=20
-/// processCurrentLoop - Do actual work and unswitch loop if possible=20
+/// processCurrentLoop - Do actual work and unswitch loop if possible
 /// and profitable.
 bool LoopUnswitch::processCurrentLoop() {
   bool Changed =3D false;
-  LLVMContext &Context =3D currentLoop->getHeader()->getContext();
+
+  initLoopData();
+
+  // If LoopSimplify was unable to form a preheader, don't do any unswitch=
ing.
+  if (!loopPreheader)
+    return false;
+
+  // Loops with indirectbr cannot be cloned.
+  if (!currentLoop->isSafeToClone())
+    return false;
+
+  // Without dedicated exits, splitting the exit edge may fail.
+  if (!currentLoop->hasDedicatedExits())
+    return false;
+
+  LLVMContext &Context =3D loopHeader->getContext();
+
+  // Probably we reach the quota of branches for this loop. If so
+  // stop unswitching.
+  if (!BranchesInfo.countLoop(currentLoop))
+    return false;
=20
   // Loop over all of the basic blocks in the loop.  If we find an interior
   // block that is branching on a loop-invariant condition, we can unswitc=
h this
   // loop.
-  for (Loop::block_iterator I =3D currentLoop->block_begin(),=20
+  for (Loop::block_iterator I =3D currentLoop->block_begin(),
          E =3D currentLoop->block_end(); I !=3D E; ++I) {
     TerminatorInst *TI =3D (*I)->getTerminator();
     if (BranchInst *BI =3D dyn_cast<BranchInst>(TI)) {
@@ -244,24 +432,37 @@
       if (BI->isConditional()) {
         // See if this, or some part of it, is loop invariant.  If so, we =
can
         // unswitch on it if we desire.
-        Value *LoopCond =3D FindLIVLoopCondition(BI->getCondition(),=20
+        Value *LoopCond =3D FindLIVLoopCondition(BI->getCondition(),
                                                currentLoop, Changed);
-        if (LoopCond && UnswitchIfProfitable(LoopCond,=20
+        if (LoopCond && UnswitchIfProfitable(LoopCond,
                                              ConstantInt::getTrue(Context)=
)) {
           ++NumBranches;
           return true;
         }
-      }     =20
+      }
     } else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
-      Value *LoopCond =3D FindLIVLoopCondition(SI->getCondition(),=20
+      Value *LoopCond =3D FindLIVLoopCondition(SI->getCondition(),
                                              currentLoop, Changed);
-      if (LoopCond && SI->getNumCases() > 1) {
+      unsigned NumCases =3D SI->getNumCases();
+      if (LoopCond && NumCases) {
         // Find a value to unswitch on:
         // FIXME: this should chose the most expensive case!
         // FIXME: scan for a case with a non-critical edge?
-        Constant *UnswitchVal =3D SI->getCaseValue(1);
+        Constant *UnswitchVal =3D NULL;
+
         // Do not process same value again and again.
-        if (!UnswitchedVals.insert(UnswitchVal))
+        // At this point we have some cases already unswitched and
+        // some not yet unswitched. Let's find the first not yet unswitche=
d one.
+        for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end=
();
+             i !=3D e; ++i) {
+          Constant* UnswitchValCandidate =3D i.getCaseValue();
+          if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
+            UnswitchVal =3D UnswitchValCandidate;
+            break;
+          }
+        }
+
+        if (!UnswitchVal)
           continue;
=20
         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
@@ -270,14 +471,14 @@
         }
       }
     }
-   =20
+
     // Scan the instructions to check for unswitchable values.
-    for (BasicBlock::iterator BBI =3D (*I)->begin(), E =3D (*I)->end();=20
+    for (BasicBlock::iterator BBI =3D (*I)->begin(), E =3D (*I)->end();
          BBI !=3D E; ++BBI)
       if (SelectInst *SI =3D dyn_cast<SelectInst>(BBI)) {
-        Value *LoopCond =3D FindLIVLoopCondition(SI->getCondition(),=20
+        Value *LoopCond =3D FindLIVLoopCondition(SI->getCondition(),
                                                currentLoop, Changed);
-        if (LoopCond && UnswitchIfProfitable(LoopCond,=20
+        if (LoopCond && UnswitchIfProfitable(LoopCond,
                                              ConstantInt::getTrue(Context)=
)) {
           ++NumSelects;
           return true;
@@ -297,7 +498,8 @@
                                          BasicBlock *&ExitBB,
                                          std::set<BasicBlock*> &Visited) {
   if (!Visited.insert(BB).second) {
-    // Already visited. Without more analysis, this could indicate an infi=
nte loop.
+    // Already visited. Without more analysis, this could indicate an infi=
nite
+    // loop.
     return false;
   } else if (!L->contains(BB)) {
     // Otherwise, this is a loop exit, this is fine so long as this is the
@@ -306,7 +508,7 @@
     ExitBB =3D BB;
     return true;
   }
- =20
+
   // Otherwise, this is an unvisited intra-loop node.  Check all successor=
s.
   for (succ_iterator SI =3D succ_begin(BB), E =3D succ_end(BB); SI !=3D E;=
 ++SI) {
     // Check to see if the successor is a trivial loop exit.
@@ -319,12 +521,12 @@
   for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E; =
++I)
     if (I->mayHaveSideEffects())
       return false;
- =20
+
   return true;
 }
=20
 /// isTrivialLoopExitBlock - Return true if the specified block unconditio=
nally
-/// leads to an exit from the specified loop, and has no side-effects in t=
he=20
+/// leads to an exit from the specified loop, and has no side-effects in t=
he
 /// process.  If so, return the block that is exited to, otherwise return =
null.
 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
   std::set<BasicBlock*> Visited;
@@ -352,49 +554,61 @@
   BasicBlock *Header =3D currentLoop->getHeader();
   TerminatorInst *HeaderTerm =3D Header->getTerminator();
   LLVMContext &Context =3D Header->getContext();
- =20
+
   BasicBlock *LoopExitBB =3D 0;
   if (BranchInst *BI =3D dyn_cast<BranchInst>(HeaderTerm)) {
     // If the header block doesn't end with a conditional branch on Cond, =
we
     // can't handle it.
     if (!BI->isConditional() || BI->getCondition() !=3D Cond)
       return false;
- =20
-    // Check to see if a successor of the branch is guaranteed to=20
-    // exit through a unique exit block without having any=20
+
+    // Check to see if a successor of the branch is guaranteed to
+    // exit through a unique exit block without having any
     // side-effects.  If so, determine the value of Cond that causes it to=
 do
     // this.
-    if ((LoopExitBB =3D isTrivialLoopExitBlock(currentLoop,=20
+    if ((LoopExitBB =3D isTrivialLoopExitBlock(currentLoop,
                                              BI->getSuccessor(0)))) {
       if (Val) *Val =3D ConstantInt::getTrue(Context);
-    } else if ((LoopExitBB =3D isTrivialLoopExitBlock(currentLoop,=20
+    } else if ((LoopExitBB =3D isTrivialLoopExitBlock(currentLoop,
                                                     BI->getSuccessor(1))))=
 {
       if (Val) *Val =3D ConstantInt::getFalse(Context);
     }
   } else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(HeaderTerm)) {
     // If this isn't a switch on Cond, we can't handle it.
     if (SI->getCondition() !=3D Cond) return false;
-   =20
+
     // Check to see if a successor of the switch is guaranteed to go to the
-    // latch block or exit through a one exit block without having any=20
+    // latch block or exit through a one exit block without having any
     // side-effects.  If so, determine the value of Cond that causes it to=
 do
-    // this.  Note that we can't trivially unswitch on the default case.
-    for (unsigned i =3D 1, e =3D SI->getNumSuccessors(); i !=3D e; ++i)
-      if ((LoopExitBB =3D isTrivialLoopExitBlock(currentLoop,=20
-                                               SI->getSuccessor(i)))) {
+    // this.
+    // Note that we can't trivially unswitch on the default case or
+    // on already unswitched cases.
+    for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end();
+         i !=3D e; ++i) {
+      BasicBlock* LoopExitCandidate;
+      if ((LoopExitCandidate =3D isTrivialLoopExitBlock(currentLoop,
+                                               i.getCaseSuccessor()))) {
         // Okay, we found a trivial case, remember the value that is trivi=
al.
-        if (Val) *Val =3D SI->getCaseValue(i);
+        ConstantInt* CaseVal =3D i.getCaseValue();
+
+        // Check that it was not unswitched before, since already unswitch=
ed
+        // trivial vals are looks trivial too.
+        if (BranchesInfo.isUnswitched(SI, CaseVal))
+          continue;
+        LoopExitBB =3D LoopExitCandidate;
+        if (Val) *Val =3D CaseVal;
         break;
       }
+    }
   }
=20
   // If we didn't find a single unique LoopExit block, or if the loop exit=
 block
   // contains phi nodes, this isn't trivial.
   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
     return false;   // Can't handle this.
- =20
+
   if (LoopExit) *LoopExit =3D LoopExitBB;
- =20
+
   // We already know that nothing uses any scalar values defined inside of=
 this
   // loop.  As such, we just have to check to see if this loop will execut=
e any
   // side-effecting instructions (e.g. stores, calls, volatile loads) in t=
he
@@ -411,12 +625,6 @@
 /// unswitch the loop, reprocess the pieces, then return true.
 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
=20
-  initLoopData();
-
-  // If LoopSimplify was unable to form a preheader, don't do any unswitch=
ing.
-  if (!loopPreheader)
-    return false;
-
   Function *F =3D loopHeader->getParent();
=20
   Constant *CondVal =3D 0;
@@ -434,28 +642,6 @@
   if (OptimizeForSize || F->hasFnAttr(Attribute::OptimizeForSize))
     return false;
=20
-  // FIXME: This is overly conservative because it does not take into
-  // consideration code simplification opportunities and code that can
-  // be shared by the resultant unswitched loops.
-  CodeMetrics Metrics;
-  for (Loop::block_iterator I =3D currentLoop->block_begin(),=20
-         E =3D currentLoop->block_end();
-       I !=3D E; ++I)
-    Metrics.analyzeBasicBlock(*I);
-
-  // Limit the number of instructions to avoid causing significant code
-  // expansion, and the number of basic blocks, to avoid loops with
-  // large numbers of branches which cause loop unswitching to go crazy.
-  // This is a very ad-hoc heuristic.
-  if (Metrics.NumInsts > Threshold ||
-      Metrics.NumBlocks * 5 > Threshold ||
-      Metrics.containsIndirectBr || Metrics.isRecursive) {
-    DEBUG(dbgs() << "NOT unswitching loop %"
-          << currentLoop->getHeader()->getName() << ", cost too high: "
-          << currentLoop->getBlocks().size() << "\n");
-    return false;
-  }
-
   UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
   return true;
 }
@@ -508,17 +694,17 @@
=20
 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
 /// condition in it (a cond branch from its header block to its latch bloc=
k,
-/// where the path through the loop that doesn't execute its body has no=20
+/// where the path through the loop that doesn't execute its body has no
 /// side-effects), unswitch it.  This doesn't involve any code duplication=
, just
 /// moving the conditional branch outside of the loop and updating loop in=
fo.
-void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,=20
-                                            Constant *Val,=20
+void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
+                                            Constant *Val,
                                             BasicBlock *ExitBlock) {
   DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
         << loopHeader->getName() << " [" << L->getBlocks().size()
         << " blocks] in Function " << L->getHeader()->getParent()->getName=
()
         << " on cond: " << *Val << " =3D=3D " << *Cond << "\n");
- =20
+
   // First step, split the preheader, so that we know that there is a safe=
 place
   // to insert the conditional branch.  We will change loopPreheader to ha=
ve a
   // conditional branch on Cond.
@@ -527,24 +713,24 @@
   // Now that we have a place to insert the conditional branch, create a p=
lace
   // to branch to: this is the exit block out of the loop that we should
   // short-circuit to.
- =20
+
   // Split this block now, so that the loop maintains its exit block, and =
so
   // that the jump from the preheader can execute the contents of the exit=
 block
   // without actually branching to it (the exit block should be dominated =
by the
   // loop header, not the preheader).
   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
   BasicBlock *NewExit =3D SplitBlock(ExitBlock, ExitBlock->begin(), this);
-   =20
-  // Okay, now we have a position to branch from and a position to branch =
to,=20
+
+  // Okay, now we have a position to branch from and a position to branch =
to,
   // insert the new conditional branch.
-  EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,=20
+  EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
                                  loopPreheader->getTerminator());
   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
   loopPreheader->getTerminator()->eraseFromParent();
=20
   // We need to reprocess this loop, it could be unswitched again.
   redoLoop =3D true;
- =20
+
   // Now that we know that the loop is never entered when this condition i=
s a
   // particular value, rewrite the loop with this info.  We know that this=
 will
   // at least eliminate the old branch.
@@ -554,7 +740,7 @@
=20
 /// SplitExitEdges - Split all of the edges from inside the loop to their =
exit
 /// blocks.  Update the appropriate Phi nodes as we do so.
-void LoopUnswitch::SplitExitEdges(Loop *L,=20
+void LoopUnswitch::SplitExitEdges(Loop *L,
                                 const SmallVector<BasicBlock *, 8> &ExitBl=
ocks){
=20
   for (unsigned i =3D 0, e =3D ExitBlocks.size(); i !=3D e; ++i) {
@@ -565,8 +751,7 @@
     // Although SplitBlockPredecessors doesn't preserve loop-simplify in
     // general, if we call it on all predecessors of all exits then it doe=
s.
     if (!ExitBlock->isLandingPad()) {
-      SplitBlockPredecessors(ExitBlock, Preds.data(), Preds.size(),
-                             ".us-lcssa", this);
+      SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", this);
     } else {
       SmallVector<BasicBlock*, 2> NewBBs;
       SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcss=
a",
@@ -575,10 +760,10 @@
   }
 }
=20
-/// UnswitchNontrivialCondition - We determined that the loop is profitabl=
e=20
-/// to unswitch when LIC equal Val.  Split it into loop versions and test =
the=20
+/// UnswitchNontrivialCondition - We determined that the loop is profitable
+/// to unswitch when LIC equal Val.  Split it into loop versions and test =
the
 /// condition outside of either loop.  Return the loops created as Out1/Ou=
t2.
-void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,=20
+void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
                                                Loop *L) {
   Function *F =3D loopHeader->getParent();
   DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
@@ -621,6 +806,7 @@
   ValueToValueMapTy VMap;
   for (unsigned i =3D 0, e =3D LoopBlocks.size(); i !=3D e; ++i) {
     BasicBlock *NewBB =3D CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
+
     NewBlocks.push_back(NewBB);
     VMap[LoopBlocks[i]] =3D NewBB;  // Keep the BB mapping.
     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
@@ -633,6 +819,11 @@
=20
   // Now we create the new Loop object for the versioned loop.
   Loop *NewLoop =3D CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
+
+  // Recalculate unswitching quota, inherit simplified switches info for N=
ewBB,
+  // Probably clone more loop-unswitch related loop properties.
+  BranchesInfo.cloneData(NewLoop, L, VMap);
+
   Loop *ParentLoop =3D L->getParentLoop();
   if (ParentLoop) {
     // Make sure to add the cloned preheader and exit blocks to the parent=
 loop
@@ -645,7 +836,7 @@
     // The new exit block should be in the same loop as the old one.
     if (Loop *ExitBBLoop =3D LI->getLoopFor(ExitBlocks[i]))
       ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
-   =20
+
     assert(NewExit->getTerminator()->getNumSuccessors() =3D=3D 1 &&
            "Exit block should have been split to have one successor!");
     BasicBlock *ExitSucc =3D NewExit->getTerminator()->getSuccessor(0);
@@ -680,7 +871,7 @@
     for (BasicBlock::iterator I =3D NewBlocks[i]->begin(),
            E =3D NewBlocks[i]->end(); I !=3D E; ++I)
       RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEnt=
ries);
- =20
+
   // Rewrite the original preheader to select between versions of the loop.
   BranchInst *OldBR =3D cast<BranchInst>(loopPreheader->getTerminator());
   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) =3D=3D LoopBlo=
cks[0] &&
@@ -699,7 +890,7 @@
   // the condition that we're unswitching on), we don't rewrite the second
   // iteration.
   WeakVH LICHandle(LIC);
- =20
+
   // Now we rewrite the original code to know that the condition is true a=
nd the
   // new code to know that the condition is false.
   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
@@ -714,7 +905,7 @@
=20
 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
 /// specified.
-static void RemoveFromWorklist(Instruction *I,=20
+static void RemoveFromWorklist(Instruction *I,
                                std::vector<Instruction*> &Worklist) {
   std::vector<Instruction*>::iterator WI =3D std::find(Worklist.begin(),
                                                      Worklist.end(), I);
@@ -727,7 +918,7 @@
=20
 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from=
 the
 /// program, replacing all uses with V and update the worklist.
-static void ReplaceUsesOfWith(Instruction *I, Value *V,=20
+static void ReplaceUsesOfWith(Instruction *I, Value *V,
                               std::vector<Instruction*> &Worklist,
                               Loop *L, LPPassManager *LPM) {
   DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
@@ -760,10 +951,10 @@
     if (BasicBlock *Pred =3D BB->getSinglePredecessor()) {
       // If it has one pred, fold phi nodes in BB.
       while (isa<PHINode>(BB->begin()))
-        ReplaceUsesOfWith(BB->begin(),=20
-                          cast<PHINode>(BB->begin())->getIncomingValue(0),=20
+        ReplaceUsesOfWith(BB->begin(),
+                          cast<PHINode>(BB->begin())->getIncomingValue(0),
                           Worklist, L, LPM);
-     =20
+
       // If this is the header of a loop and the only pred is the latch, w=
e now
       // have an unreachable loop.
       if (Loop *L =3D LI->getLoopFor(BB))
@@ -774,15 +965,15 @@
           LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
           Pred->getTerminator()->eraseFromParent();
           new UnreachableInst(BB->getContext(), Pred);
-         =20
+
           // The loop is now broken, remove it from LI.
           RemoveLoopFromHierarchy(L);
-         =20
+
           // Reprocess the header, which now IS dead.
           RemoveBlockIfDead(BB, Worklist, L);
           return;
         }
-     =20
+
       // If pred ends in a uncond branch, add uncond branch to worklist so=
 that
       // the two blocks will get merged.
       if (BranchInst *BI =3D dyn_cast<BranchInst>(Pred->getTerminator()))
@@ -793,11 +984,11 @@
   }
=20
   DEBUG(dbgs() << "Nuking dead block: " << *BB);
- =20
+
   // Remove the instructions in the basic block from the worklist.
   for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E; =
++I) {
     RemoveFromWorklist(I, Worklist);
-   =20
+
     // Anything that uses the instructions in this basic block should have=
 their
     // uses replaced with undefs.
     // If I is not void type then replaceAllUsesWith undef.
@@ -805,7 +996,7 @@
     if (!I->getType()->isVoidTy())
       I->replaceAllUsesWith(UndefValue::get(I->getType()));
   }
- =20
+
   // If this is the edge to the header block for a loop, remove the loop a=
nd
   // promote all subloops.
   if (Loop *BBLoop =3D LI->getLoopFor(BB)) {
@@ -821,8 +1012,8 @@
   // Remove the block from the loop info, which removes it from any loops =
it
   // was in.
   LI->removeBlock(BB);
- =20
- =20
+
+
   // Remove phi node entries in successors for this block.
   TerminatorInst *TI =3D BB->getTerminator();
   SmallVector<BasicBlock*, 4> Succs;
@@ -830,13 +1021,13 @@
     Succs.push_back(TI->getSuccessor(i));
     TI->getSuccessor(i)->removePredecessor(BB);
   }
- =20
+
   // Unique the successors, remove anything with multiple uses.
   array_pod_sort(Succs.begin(), Succs.end());
   Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
- =20
+
   // Remove the basic block, including all of the instructions contained i=
n it.
-  LPM->deleteSimpleAnalysisValue(BB, L); =20
+  LPM->deleteSimpleAnalysisValue(BB, L);
   BB->eraseFromParent();
   // Remove successor blocks here that are not dead, so that we know we on=
ly
   // have dead blocks in this list.  Nondead blocks have a way of becoming=
 dead,
@@ -854,7 +1045,7 @@
         --i;
       }
     }
- =20
+
   for (unsigned i =3D 0, e =3D Succs.size(); i !=3D e; ++i)
     RemoveBlockIfDead(Succs[i], Worklist, L);
 }
@@ -877,14 +1068,14 @@
                                                         Constant *Val,
                                                         bool IsEqual) {
   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
- =20
+
   // FIXME: Support correlated properties, like:
   //  for (...)
   //    if (li1 < li2)
   //      ...
   //    if (li1 > li2)
   //      ...
- =20
+
   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
   // selects, switches.
   std::vector<Instruction*> Worklist;
@@ -899,21 +1090,25 @@
     if (IsEqual)
       Replacement =3D Val;
     else
-      Replacement =3D ConstantInt::get(Type::getInt1Ty(Val->getContext()),=20
+      Replacement =3D ConstantInt::get(Type::getInt1Ty(Val->getContext()),
                                      !cast<ConstantInt>(Val)->getZExtValue=
());
-   =20
+
     for (Value::use_iterator UI =3D LIC->use_begin(), E =3D LIC->use_end();
          UI !=3D E; ++UI) {
       Instruction *U =3D dyn_cast<Instruction>(*UI);
       if (!U || !L->contains(U))
         continue;
-      U->replaceUsesOfWith(LIC, Replacement);
       Worklist.push_back(U);
     }
+
+    for (std::vector<Instruction*>::iterator UI =3D Worklist.begin();
+         UI !=3D Worklist.end(); ++UI)
+      (*UI)->replaceUsesOfWith(LIC, Replacement);
+
     SimplifyCode(Worklist, L);
     return;
   }
- =20
+
   // Otherwise, we don't know the precise value of LIC, but we do know tha=
t it
   // is certainly NOT "Val".  As such, simplify any uses in the loop that =
we
   // can.  This case occurs when we unswitch switch statements.
@@ -925,23 +1120,27 @@
=20
     Worklist.push_back(U);
=20
-    // TODO: We could do other simplifications, for example, turning=20
+    // TODO: We could do other simplifications, for example, turning
     // 'icmp eq LIC, Val' -> false.
=20
     // If we know that LIC is not Val, use this info to simplify code.
     SwitchInst *SI =3D dyn_cast<SwitchInst>(U);
     if (SI =3D=3D 0 || !isa<ConstantInt>(Val)) continue;
-   =20
-    unsigned DeadCase =3D SI->findCaseValue(cast<ConstantInt>(Val));
-    if (DeadCase =3D=3D 0) continue;  // Default case is live for multiple=
 values.
-   =20
-    // Found a dead case value.  Don't remove PHI nodes in the=20
+
+    SwitchInst::CaseIt DeadCase =3D SI->findCaseValue(cast<ConstantInt>(Va=
l));
+    // Default case is live for multiple values.
+    if (DeadCase =3D=3D SI->case_default()) continue;
+
+    // Found a dead case value.  Don't remove PHI nodes in the
     // successor if they become single-entry, those PHI nodes may
     // be in the Users list.
=20
     BasicBlock *Switch =3D SI->getParent();
-    BasicBlock *SISucc =3D SI->getSuccessor(DeadCase);
+    BasicBlock *SISucc =3D DeadCase.getCaseSuccessor();
     BasicBlock *Latch =3D L->getLoopLatch();
+
+    BranchesInfo.setUnswitched(SI, Val);
+
     if (!SI->findCaseDest(SISucc)) continue;  // Edge is critical.
     // If the DeadCase successor dominates the loop latch, then the
     // transformation isn't safe since it will delete the sole predecessor=
 edge
@@ -957,7 +1156,7 @@
     // Compute the successors instead of relying on the return value
     // of SplitEdge, since it may have split the switch successor
     // after PHI nodes.
-    BasicBlock *NewSISucc =3D SI->getSuccessor(DeadCase);
+    BasicBlock *NewSISucc =3D DeadCase.getCaseSuccessor();
     BasicBlock *OldSISucc =3D *succ_begin(NewSISucc);
     // Create an "unreachable" destination.
     BasicBlock *Abort =3D BasicBlock::Create(Context, "us-unreachable",
@@ -981,7 +1180,7 @@
     if (DT)
       DT->addNewBlock(Abort, NewSISucc);
   }
- =20
+
   SimplifyCode(Worklist, L);
 }
=20
@@ -1002,7 +1201,7 @@
     // Simple DCE.
     if (isInstructionTriviallyDead(I)) {
       DEBUG(dbgs() << "Remove dead instruction '" << *I);
-     =20
+
       // Add uses to the worklist, which may be dead now.
       for (unsigned i =3D 0, e =3D I->getNumOperands(); i !=3D e; ++i)
         if (Instruction *Use =3D dyn_cast<Instruction>(I->getOperand(i)))
@@ -1017,7 +1216,7 @@
     // See if instruction simplification can hack this up.  This is common=
 for
     // things like "select false, X, Y" after unswitching made the conditi=
on be
     // 'false'.
-    if (Value *V =3D SimplifyInstruction(I, 0, DT))
+    if (Value *V =3D SimplifyInstruction(I, 0, 0, DT))
       if (LI->replacementPreservesLCSSAForm(I, V)) {
         ReplaceUsesOfWith(I, V, Worklist, L, LPM);
         continue;
@@ -1034,24 +1233,24 @@
         if (!SinglePred) continue;  // Nothing to do.
         assert(SinglePred =3D=3D Pred && "CFG broken");
=20
-        DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "=20
+        DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
               << Succ->getName() << "\n");
-       =20
+
         // Resolve any single entry PHI nodes in Succ.
         while (PHINode *PN =3D dyn_cast<PHINode>(Succ->begin()))
           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
-       =20
+
         // If Succ has any successors with PHI nodes, update them to have
         // entries coming from Pred instead of Succ.
         Succ->replaceAllUsesWith(Pred);
-       =20
+
         // Move all of the successor contents from Succ to Pred.
         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
                                    Succ->end());
         LPM->deleteSimpleAnalysisValue(BI, L);
         BI->eraseFromParent();
         RemoveFromWorklist(BI, Worklist);
-       =20
+
         // Remove Succ from the loop tree.
         LI->removeBlock(Succ);
         LPM->deleteSimpleAnalysisValue(Succ, L);
@@ -1059,7 +1258,7 @@
         ++NumSimplify;
         continue;
       }
-     =20
+
       if (ConstantInt *CB =3D dyn_cast<ConstantInt>(BI->getCondition())){
         // Conditional branch.  Turn it into an unconditional branch, then
         // remove dead blocks.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/MemCpyOptimizer.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -147,8 +147,8 @@
 } // end anon namespace
=20
 bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
-  // If we found more than 8 stores to merge or 64 bytes, use memset.
-  if (TheStores.size() >=3D 8 || End-Start >=3D 64) return true;
+  // If we found more than 4 stores to merge or 16 bytes, use memset.
+  if (TheStores.size() >=3D 4 || End-Start >=3D 16) return true;
=20
   // If there is nothing to merge, don't do anything.
   if (TheStores.size() < 2) return false;
@@ -806,21 +806,25 @@
   //   a) memcpy-memcpy xform which exposes redundance for DSE.
   //   b) call-memcpy xform for return slot optimization.
   MemDepResult DepInfo =3D MD->getDependency(M);
-  if (!DepInfo.isClobber())
-    return false;
- =20
-  if (MemCpyInst *MDep =3D dyn_cast<MemCpyInst>(DepInfo.getInst()))
-    return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue()=
);
-   =20
-  if (CallInst *C =3D dyn_cast<CallInst>(DepInfo.getInst())) {
-    if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
-                             CopySize->getZExtValue(), C)) {
-      MD->removeInstruction(M);
-      M->eraseFromParent();
-      return true;
+  if (DepInfo.isClobber()) {
+    if (CallInst *C =3D dyn_cast<CallInst>(DepInfo.getInst())) {
+      if (performCallSlotOptzn(M, M->getDest(), M->getSource(),
+                               CopySize->getZExtValue(), C)) {
+        MD->removeInstruction(M);
+        M->eraseFromParent();
+        return true;
+      }
     }
   }
- =20
+
+  AliasAnalysis::Location SrcLoc =3D AliasAnalysis::getLocationForSource(M=
);
+  MemDepResult SrcDepInfo =3D MD->getPointerDependencyFrom(SrcLoc, true,
+                                                         M, M->getParent()=
);
+  if (SrcDepInfo.isClobber()) {
+    if (MemCpyInst *MDep =3D dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
+      return processMemCpyMemCpyDependence(M, MDep, CopySize->getZExtValue=
());
+  }
+
   return false;
 }
=20
@@ -945,7 +949,7 @@
         RepeatInstruction =3D processMemMove(M);
       else if (CallSite CS =3D (Value*)I) {
         for (unsigned i =3D 0, e =3D CS.arg_size(); i !=3D e; ++i)
-          if (CS.paramHasAttr(i+1, Attribute::ByVal))
+          if (CS.isByValArgument(i))
             MadeChange |=3D processByValArgument(CS, i);
       }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/ObjCARC.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/ObjCARC.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/ObjCARC.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -88,13 +88,14 @@
     }
 #endif
=20
-    ValueT &operator[](KeyT Arg) {
+    ValueT &operator[](const KeyT &Arg) {
       std::pair<typename MapTy::iterator, bool> Pair =3D
         Map.insert(std::make_pair(Arg, size_t(0)));
       if (Pair.second) {
-        Pair.first->second =3D Vector.size();
+        size_t Num =3D Vector.size();
+        Pair.first->second =3D Num;
         Vector.push_back(std::make_pair(Arg, ValueT()));
-        return Vector.back().second;
+        return Vector[Num].second;
       }
       return Vector[Pair.first->second].second;
     }
@@ -104,14 +105,15 @@
       std::pair<typename MapTy::iterator, bool> Pair =3D
         Map.insert(std::make_pair(InsertPair.first, size_t(0)));
       if (Pair.second) {
-        Pair.first->second =3D Vector.size();
+        size_t Num =3D Vector.size();
+        Pair.first->second =3D Num;
         Vector.push_back(InsertPair);
-        return std::make_pair(llvm::prior(Vector.end()), true);
+        return std::make_pair(Vector.begin() + Num, true);
       }
       return std::make_pair(Vector.begin() + Pair.first->second, false);
     }
=20
-    const_iterator find(KeyT Key) const {
+    const_iterator find(const KeyT &Key) const {
       typename MapTy::const_iterator It =3D Map.find(Key);
       if (It =3D=3D Map.end()) return Vector.end();
       return Vector.begin() + It->second;
@@ -121,7 +123,7 @@
     /// from the vector, it just zeros out the key in the vector. This lea=
ves
     /// iterators intact, but clients must be prepared for zeroed-out keys=
 when
     /// iterating.
-    void blot(KeyT Key) {
+    void blot(const KeyT &Key) {
       typename MapTy::iterator It =3D Map.find(Key);
       if (It =3D=3D Map.end()) return;
       Vector[It->second].first =3D KeyT();
@@ -179,9 +181,13 @@
         Arg->hasNestAttr() ||
         Arg->hasStructRetAttr())
       return false;
-  // Only consider values with pointer types, and not function pointers.
+  // Only consider values with pointer types.
+  // It seemes intuitive to exclude function pointer types as well, since
+  // functions are never reference-counted, however clang occasionally
+  // bitcasts reference-counted pointers to function-pointer type
+  // temporarily.
   PointerType *Ty =3D dyn_cast<PointerType>(Op->getType());
-  if (!Ty || isa<FunctionType>(Ty->getElementType()))
+  if (!Ty)
     return false;
   // Conservatively assume anything else is a potential use.
   return true;
@@ -371,7 +377,7 @@
   }
=20
   // Otherwise, be conservative.
-  return IC_User;
+  return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
 }
=20
 /// IsRetain - Test if the the given class is objc_retain or
@@ -597,6 +603,46 @@
     M.getNamedValue("objc_unretainedPointer");
 }
=20
+/// DoesObjCBlockEscape - Test whether the given pointer, which is an
+/// Objective C block pointer, does not "escape". This differs from regular
+/// escape analysis in that a use as an argument to a call is not consider=
ed
+/// an escape.
+static bool DoesObjCBlockEscape(const Value *BlockPtr) {
+  // Walk the def-use chains.
+  SmallVector<const Value *, 4> Worklist;
+  Worklist.push_back(BlockPtr);
+  do {
+    const Value *V =3D Worklist.pop_back_val();
+    for (Value::const_use_iterator UI =3D V->use_begin(), UE =3D V->use_en=
d();
+         UI !=3D UE; ++UI) {
+      const User *UUser =3D *UI;
+      // Special - Use by a call (callee or argument) is not considered
+      // to be an escape.
+      if (isa<CallInst>(UUser) || isa<InvokeInst>(UUser))
+        continue;
+      // Use by an instruction which copies the value is an escape if the
+      // result is an escape.
+      if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
+          isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
+        Worklist.push_back(UUser);
+        continue;
+      }
+      // Use by a load is not an escape.
+      if (isa<LoadInst>(UUser))
+        continue;
+      // Use by a store is not an escape if the use is the address.
+      if (const StoreInst *SI =3D dyn_cast<StoreInst>(UUser))
+        if (V !=3D SI->getValueOperand())
+          continue;
+      // Otherwise, conservatively assume an escape.
+      return true;
+    }
+  } while (!Worklist.empty());
+
+  // No escapes found.
+  return false;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ARC AliasAnalysis.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -850,6 +896,139 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// ARC autorelease pool elimination.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+#include "llvm/Constants.h"
+
+namespace {
+  /// ObjCARCAPElim - Autorelease pool elimination.
+  class ObjCARCAPElim : public ModulePass {
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
+    virtual bool runOnModule(Module &M);
+
+    bool MayAutorelease(CallSite CS, unsigned Depth =3D 0);
+    bool OptimizeBB(BasicBlock *BB);
+
+  public:
+    static char ID;
+    ObjCARCAPElim() : ModulePass(ID) {
+      initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
+    }
+  };
+}
+
+char ObjCARCAPElim::ID =3D 0;
+INITIALIZE_PASS(ObjCARCAPElim,
+                "objc-arc-apelim",
+                "ObjC ARC autorelease pool elimination",
+                false, false)
+
+Pass *llvm::createObjCARCAPElimPass() {
+  return new ObjCARCAPElim();
+}
+
+void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
+  AU.setPreservesCFG();
+}
+
+/// MayAutorelease - Interprocedurally determine if calls made by the
+/// given call site can possibly produce autoreleases.
+bool ObjCARCAPElim::MayAutorelease(CallSite CS, unsigned Depth) {
+  if (Function *Callee =3D CS.getCalledFunction()) {
+    if (Callee->isDeclaration() || Callee->mayBeOverridden())
+      return true;
+    for (Function::iterator I =3D Callee->begin(), E =3D Callee->end();
+         I !=3D E; ++I) {
+      BasicBlock *BB =3D I;
+      for (BasicBlock::iterator J =3D BB->begin(), F =3D BB->end(); J !=3D=
 F; ++J)
+        if (CallSite JCS =3D CallSite(J))
+          // This recursion depth limit is arbitrary. It's just great
+          // enough to cover known interesting testcases.
+          if (Depth < 3 &&
+              !JCS.onlyReadsMemory() &&
+              MayAutorelease(JCS, Depth + 1))
+            return true;
+    }
+    return false;
+  }
+
+  return true;
+}
+
+bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
+  bool Changed =3D false;
+
+  Instruction *Push =3D 0;
+  for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E; =
) {
+    Instruction *Inst =3D I++;
+    switch (GetBasicInstructionClass(Inst)) {
+    case IC_AutoreleasepoolPush:
+      Push =3D Inst;
+      break;
+    case IC_AutoreleasepoolPop:
+      // If this pop matches a push and nothing in between can autorelease,
+      // zap the pair.
+      if (Push && cast<CallInst>(Inst)->getArgOperand(0) =3D=3D Push) {
+        Changed =3D true;
+        Inst->eraseFromParent();
+        Push->eraseFromParent();
+      }
+      Push =3D 0;
+      break;
+    case IC_CallOrUser:
+      if (MayAutorelease(CallSite(Inst)))
+        Push =3D 0;
+      break;
+    default:
+      break;
+    }
+  }
+
+  return Changed;
+}
+
+bool ObjCARCAPElim::runOnModule(Module &M) {
+  if (!EnableARCOpts)
+    return false;
+
+  // If nothing in the Module uses ARC, don't do anything.
+  if (!ModuleHasARC(M))
+    return false;
+
+  // Find the llvm.global_ctors variable, as the first step in
+  // identifying the global constructors.
+  GlobalVariable *GV =3D M.getGlobalVariable("llvm.global_ctors");
+  if (!GV)
+    return false;
+
+  assert(GV->hasDefinitiveInitializer() &&
+         "llvm.global_ctors is uncooperative!");
+
+  bool Changed =3D false;
+
+  // Dig the constructor functions out of GV's initializer.
+  ConstantArray *Init =3D cast<ConstantArray>(GV->getInitializer());
+  for (User::op_iterator OI =3D Init->op_begin(), OE =3D Init->op_end();
+       OI !=3D OE; ++OI) {
+    Value *Op =3D *OI;
+    // llvm.global_ctors is an array of pairs where the second members
+    // are constructor functions.
+    Function *F =3D cast<Function>(cast<ConstantStruct>(Op)->getOperand(1)=
);
+    // Only look at function definitions.
+    if (F->isDeclaration())
+      continue;
+    // Only look at functions with one basic block.
+    if (llvm::next(F->begin()) !=3D F->end())
+      continue;
+    // Ok, a single-block constructor function definition. Try to optimize=
 it.
+    Changed |=3D OptimizeBB(F->begin());
+  }
+
+  return Changed;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ARC optimization.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -896,8 +1075,9 @@
 #include "llvm/LLVMContext.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/CFG.h"
-#include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/DenseSet.h"
=20
 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminate=
d");
@@ -1158,6 +1338,12 @@
     /// with the "tail" keyword.
     bool IsTailCallRelease;
=20
+    /// Partial - True of we've seen an opportunity for partial RR elimina=
tion,
+    /// such as pushing calls into a CFG triangle or into one side of a
+    /// CFG diamond.
+    /// TODO: Consider moving this to PtrState.
+    bool Partial;
+
     /// ReleaseMetadata - If the Calls are objc_release calls and they all=
 have
     /// a clang.imprecise_release tag, this is the metadata tag.
     MDNode *ReleaseMetadata;
@@ -1171,7 +1357,8 @@
     SmallPtrSet<Instruction *, 2> ReverseInsertPts;
=20
     RRInfo() :
-      KnownSafe(false), IsRetainBlock(false), IsTailCallRelease(false),
+      KnownSafe(false), IsRetainBlock(false),
+      IsTailCallRelease(false), Partial(false),
       ReleaseMetadata(0) {}
=20
     void clear();
@@ -1182,6 +1369,7 @@
   KnownSafe =3D false;
   IsRetainBlock =3D false;
   IsTailCallRelease =3D false;
+  Partial =3D false;
   ReleaseMetadata =3D 0;
   Calls.clear();
   ReverseInsertPts.clear();
@@ -1239,16 +1427,6 @@
       Seq =3D NewSeq;
     }
=20
-    void SetSeqToRelease(MDNode *M) {
-      if (Seq =3D=3D S_None || Seq =3D=3D S_Use) {
-        Seq =3D M ? S_MovableRelease : S_Release;
-        RRI.ReleaseMetadata =3D M;
-      } else if (Seq !=3D S_MovableRelease || RRI.ReleaseMetadata !=3D M) {
-        Seq =3D S_Release;
-        RRI.ReleaseMetadata =3D 0;
-      }
-    }
-
     Sequence GetSeq() const {
       return Seq;
     }
@@ -1272,8 +1450,16 @@
   if (RRI.IsRetainBlock !=3D Other.RRI.IsRetainBlock)
     Seq =3D S_None;
=20
+  // If we're not in a sequence (anymore), drop all associated state.
   if (Seq =3D=3D S_None) {
     RRI.clear();
+  } else if (RRI.Partial || Other.RRI.Partial) {
+    // If we're doing a merge on a path that's previously seen a partial
+    // merge, conservatively drop the sequence, to avoid doing partial
+    // RR elimination. If the branch predicates for the two merge differ,
+    // mixing them is unsafe.
+    Seq =3D S_None;
+    RRI.clear();
   } else {
     // Conservatively merge the ReleaseMetadata information.
     if (RRI.ReleaseMetadata !=3D Other.RRI.ReleaseMetadata)
@@ -1282,8 +1468,15 @@
     RRI.KnownSafe =3D RRI.KnownSafe && Other.RRI.KnownSafe;
     RRI.IsTailCallRelease =3D RRI.IsTailCallRelease && Other.RRI.IsTailCal=
lRelease;
     RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
-    RRI.ReverseInsertPts.insert(Other.RRI.ReverseInsertPts.begin(),
-                                Other.RRI.ReverseInsertPts.end());
+
+    // Merge the insert point sets. If there are any differences,
+    // that makes this a partial merge.
+    RRI.Partial =3D RRI.ReverseInsertPts.size() !=3D
+                  Other.RRI.ReverseInsertPts.size();
+    for (SmallPtrSet<Instruction *, 2>::const_iterator
+         I =3D Other.RRI.ReverseInsertPts.begin(),
+         E =3D Other.RRI.ReverseInsertPts.end(); I !=3D E; ++I)
+      RRI.Partial |=3D RRI.ReverseInsertPts.insert(*I);
   }
 }
=20
@@ -1460,6 +1653,14 @@
     /// metadata.
     unsigned ImpreciseReleaseMDKind;
=20
+    /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
+    /// metadata.
+    unsigned CopyOnEscapeMDKind;
+
+    /// NoObjCARCExceptionsMDKind - The Metadata Kind for
+    /// clang.arc.no_objc_arc_exceptions metadata.
+    unsigned NoObjCARCExceptionsMDKind;
+
     Constant *getRetainRVCallee(Module *M);
     Constant *getAutoreleaseRVCallee(Module *M);
     Constant *getReleaseCallee(Module *M);
@@ -1467,6 +1668,8 @@
     Constant *getRetainBlockCallee(Module *M);
     Constant *getAutoreleaseCallee(Module *M);
=20
+    bool IsRetainBlockOptimizable(const Instruction *Inst);
+
     void OptimizeRetainCall(Function &F, Instruction *Retain);
     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV=
);
@@ -1475,9 +1678,16 @@
     void CheckForCFGHazards(const BasicBlock *BB,
                             DenseMap<const BasicBlock *, BBState> &BBState=
s,
                             BBState &MyStates) const;
+    bool VisitInstructionBottomUp(Instruction *Inst,
+                                  BasicBlock *BB,
+                                  MapVector<Value *, RRInfo> &Retains,
+                                  BBState &MyStates);
     bool VisitBottomUp(BasicBlock *BB,
                        DenseMap<const BasicBlock *, BBState> &BBStates,
                        MapVector<Value *, RRInfo> &Retains);
+    bool VisitInstructionTopDown(Instruction *Inst,
+                                 DenseMap<Value *, RRInfo> &Releases,
+                                 BBState &MyStates);
     bool VisitTopDown(BasicBlock *BB,
                       DenseMap<const BasicBlock *, BBState> &BBStates,
                       DenseMap<Value *, RRInfo> &Releases);
@@ -1534,6 +1744,22 @@
   AU.setPreservesCFG();
 }
=20
+bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
+  // Without the magic metadata tag, we have to assume this might be an
+  // objc_retainBlock call inserted to convert a block pointer to an id,
+  // in which case it really is needed.
+  if (!Inst->getMetadata(CopyOnEscapeMDKind))
+    return false;
+
+  // If the pointer "escapes" (not including being used in a call),
+  // the copy may be needed.
+  if (DoesObjCBlockEscape(Inst))
+    return false;
+
+  // Otherwise, it's not needed.
+  return true;
+}
+
 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
   if (!RetainRVCallee) {
     LLVMContext &C =3D M->getContext();
@@ -1737,6 +1963,7 @@
   /// use here.
   enum DependenceKind {
     NeedsPositiveRetainCount,
+    AutoreleasePoolBoundary,
     CanChangeRetainCount,
     RetainAutoreleaseDep,       ///< Blocks objc_retainAutorelease.
     RetainAutoreleaseRVDep,     ///< Blocks objc_retainAutoreleaseReturnVa=
lue.
@@ -1766,6 +1993,19 @@
     }
   }
=20
+  case AutoreleasePoolBoundary: {
+    InstructionClass Class =3D GetInstructionClass(Inst);
+    switch (Class) {
+    case IC_AutoreleasepoolPop:
+    case IC_AutoreleasepoolPush:
+      // These mark the end and begin of an autorelease pool scope.
+      return true;
+    default:
+      // Nothing else does this.
+      return false;
+    }
+  }
+
   case CanChangeRetainCount: {
     InstructionClass Class =3D GetInstructionClass(Inst);
     switch (Class) {
@@ -1783,6 +2023,7 @@
   case RetainAutoreleaseDep:
     switch (GetBasicInstructionClass(Inst)) {
     case IC_AutoreleasepoolPop:
+    case IC_AutoreleasepoolPush:
       // Don't merge an objc_autorelease with an objc_retain inside a diff=
erent
       // autoreleasepool scope.
       return true;
@@ -1794,7 +2035,6 @@
       // Nothing else matters for objc_retainAutorelease formation.
       return false;
     }
-    break;
=20
   case RetainAutoreleaseRVDep: {
     InstructionClass Class =3D GetBasicInstructionClass(Inst);
@@ -1808,7 +2048,6 @@
       // retainAutoreleaseReturnValue formation.
       return CanInterruptRV(Class);
     }
-    break;
   }
=20
   case RetainRVDep:
@@ -1816,7 +2055,6 @@
   }
=20
   llvm_unreachable("Invalid dependence flavor");
-  return true;
 }
=20
 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB)=
 and
@@ -1920,17 +2158,26 @@
 /// return true.
 bool
 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
-  // Check for the argument being from an immediately preceding call.
+  // Check for the argument being from an immediately preceding call or in=
voke.
   Value *Arg =3D GetObjCArg(RetainRV);
   CallSite CS(Arg);
-  if (Instruction *Call =3D CS.getInstruction())
+  if (Instruction *Call =3D CS.getInstruction()) {
     if (Call->getParent() =3D=3D RetainRV->getParent()) {
       BasicBlock::iterator I =3D Call;
       ++I;
       while (isNoopInstruction(I)) ++I;
       if (&*I =3D=3D RetainRV)
         return false;
+    } else if (InvokeInst *II =3D dyn_cast<InvokeInst>(Call)) {
+      BasicBlock *RetainRVParent =3D RetainRV->getParent();
+      if (II->getNormalDest() =3D=3D RetainRVParent) {
+        BasicBlock::iterator I =3D RetainRVParent->begin();
+        while (isNoopInstruction(I)) ++I;
+        if (&*I =3D=3D RetainRV)
+          return false;
+      }
     }
+  }
=20
   // Check for being preceded by an objc_autoreleaseReturnValue on the same
   // pointer. In this case, we can delete the pair.
@@ -2144,9 +2391,34 @@
=20
         // Check that there is nothing that cares about the reference
         // count between the call and the phi.
-        FindDependencies(NeedsPositiveRetainCount, Arg,
-                         Inst->getParent(), Inst,
-                         DependingInstructions, Visited, PA);
+        switch (Class) {
+        case IC_Retain:
+        case IC_RetainBlock:
+          // These can always be moved up.
+          break;
+        case IC_Release:
+          // These can't be moved across things that care about the retain=
 count.
+          FindDependencies(NeedsPositiveRetainCount, Arg,
+                           Inst->getParent(), Inst,
+                           DependingInstructions, Visited, PA);
+          break;
+        case IC_Autorelease:
+          // These can't be moved across autorelease pool scope boundaries.
+          FindDependencies(AutoreleasePoolBoundary, Arg,
+                           Inst->getParent(), Inst,
+                           DependingInstructions, Visited, PA);
+          break;
+        case IC_RetainRV:
+        case IC_AutoreleaseRV:
+          // Don't move these; the RV optimization depends on the autorele=
aseRV
+          // being tail called, and the retainRV being immediately after a=
 call
+          // (which might still happen if we get lucky with codegen layout=
, but
+          // it's not worth taking the chance).
+          continue;
+        default:
+          llvm_unreachable("Invalid dependence flavor");
+        }
+
         if (DependingInstructions.size() =3D=3D 1 &&
             *DependingInstructions.begin() =3D=3D PN) {
           Changed =3D true;
@@ -2186,7 +2458,7 @@
                                BBState &MyStates) const {
   // If any top-down local-use or possible-dec has a succ which is earlier=
 in
   // the sequence, forget it.
-  for (BBState::ptr_const_iterator I =3D MyStates.top_down_ptr_begin(),
+  for (BBState::ptr_iterator I =3D MyStates.top_down_ptr_begin(),
        E =3D MyStates.top_down_ptr_end(); I !=3D E; ++I)
     switch (I->second.GetSeq()) {
     default: break;
@@ -2195,14 +2467,32 @@
       const TerminatorInst *TI =3D cast<TerminatorInst>(&BB->back());
       bool SomeSuccHasSame =3D false;
       bool AllSuccsHaveSame =3D true;
-      PtrState &S =3D MyStates.getPtrTopDownState(Arg);
-      for (succ_const_iterator SI(TI), SE(TI, false); SI !=3D SE; ++SI) {
-        PtrState &SuccS =3D BBStates[*SI].getPtrBottomUpState(Arg);
-        switch (SuccS.GetSeq()) {
+      PtrState &S =3D I->second;
+      succ_const_iterator SI(TI), SE(TI, false);
+
+      // If the terminator is an invoke marked with the
+      // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
+      // ignored, for ARC purposes.
+      if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind=
))
+        --SE;
+
+      for (; SI !=3D SE; ++SI) {
+        Sequence SuccSSeq =3D S_None;
+        bool SuccSRRIKnownSafe =3D false;
+        // If VisitBottomUp has visited this successor, take what we know =
about it.
+        DenseMap<const BasicBlock *, BBState>::iterator BBI =3D BBStates.f=
ind(*SI);
+        if (BBI !=3D BBStates.end()) {
+          const PtrState &SuccS =3D BBI->second.getPtrBottomUpState(Arg);
+          SuccSSeq =3D SuccS.GetSeq();
+          SuccSRRIKnownSafe =3D SuccS.RRI.KnownSafe;
+        }
+        switch (SuccSSeq) {
         case S_None:
         case S_CanRelease: {
-          if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
+          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
             S.ClearSequenceProgress();
+            break;
+          }
           continue;
         }
         case S_Use:
@@ -2211,7 +2501,7 @@
         case S_Stop:
         case S_Release:
         case S_MovableRelease:
-          if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
+          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
             AllSuccsHaveSame =3D false;
           break;
         case S_Retain:
@@ -2223,19 +2513,38 @@
       // guards against loops in the middle of a sequence.
       if (SomeSuccHasSame && !AllSuccsHaveSame)
         S.ClearSequenceProgress();
+      break;
     }
     case S_CanRelease: {
       const Value *Arg =3D I->first;
       const TerminatorInst *TI =3D cast<TerminatorInst>(&BB->back());
       bool SomeSuccHasSame =3D false;
       bool AllSuccsHaveSame =3D true;
-      PtrState &S =3D MyStates.getPtrTopDownState(Arg);
-      for (succ_const_iterator SI(TI), SE(TI, false); SI !=3D SE; ++SI) {
-        PtrState &SuccS =3D BBStates[*SI].getPtrBottomUpState(Arg);
-        switch (SuccS.GetSeq()) {
+      PtrState &S =3D I->second;
+      succ_const_iterator SI(TI), SE(TI, false);
+
+      // If the terminator is an invoke marked with the
+      // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
+      // ignored, for ARC purposes.
+      if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind=
))
+        --SE;
+
+      for (; SI !=3D SE; ++SI) {
+        Sequence SuccSSeq =3D S_None;
+        bool SuccSRRIKnownSafe =3D false;
+        // If VisitBottomUp has visited this successor, take what we know =
about it.
+        DenseMap<const BasicBlock *, BBState>::iterator BBI =3D BBStates.f=
ind(*SI);
+        if (BBI !=3D BBStates.end()) {
+          const PtrState &SuccS =3D BBI->second.getPtrBottomUpState(Arg);
+          SuccSSeq =3D SuccS.GetSeq();
+          SuccSRRIKnownSafe =3D SuccS.RRI.KnownSafe;
+        }
+        switch (SuccSSeq) {
         case S_None: {
-          if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
+          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
             S.ClearSequenceProgress();
+            break;
+          }
           continue;
         }
         case S_CanRelease:
@@ -2245,7 +2554,7 @@
         case S_Release:
         case S_MovableRelease:
         case S_Use:
-          if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
+          if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
             AllSuccsHaveSame =3D false;
           break;
         case S_Retain:
@@ -2257,11 +2566,170 @@
       // guards against loops in the middle of a sequence.
       if (SomeSuccHasSame && !AllSuccsHaveSame)
         S.ClearSequenceProgress();
+      break;
     }
     }
 }
=20
 bool
+ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
+                                     BasicBlock *BB,
+                                     MapVector<Value *, RRInfo> &Retains,
+                                     BBState &MyStates) {
+  bool NestingDetected =3D false;
+  InstructionClass Class =3D GetInstructionClass(Inst);
+  const Value *Arg =3D 0;
+
+  switch (Class) {
+  case IC_Release: {
+    Arg =3D GetObjCArg(Inst);
+
+    PtrState &S =3D MyStates.getPtrBottomUpState(Arg);
+
+    // If we see two releases in a row on the same pointer. If so, make
+    // a note, and we'll cicle back to revisit it after we've
+    // hopefully eliminated the second release, which may allow us to
+    // eliminate the first release too.
+    // Theoretically we could implement removal of nested retain+release
+    // pairs by making PtrState hold a stack of states, but this is
+    // simple and avoids adding overhead for the non-nested case.
+    if (S.GetSeq() =3D=3D S_Release || S.GetSeq() =3D=3D S_MovableRelease)
+      NestingDetected =3D true;
+
+    S.RRI.clear();
+
+    MDNode *ReleaseMetadata =3D Inst->getMetadata(ImpreciseReleaseMDKind);
+    S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
+    S.RRI.ReleaseMetadata =3D ReleaseMetadata;
+    S.RRI.KnownSafe =3D S.IsKnownNested() || S.IsKnownIncremented();
+    S.RRI.IsTailCallRelease =3D cast<CallInst>(Inst)->isTailCall();
+    S.RRI.Calls.insert(Inst);
+
+    S.IncrementRefCount();
+    S.IncrementNestCount();
+    break;
+  }
+  case IC_RetainBlock:
+    // An objc_retainBlock call with just a use may need to be kept,
+    // because it may be copying a block from the stack to the heap.
+    if (!IsRetainBlockOptimizable(Inst))
+      break;
+    // FALLTHROUGH
+  case IC_Retain:
+  case IC_RetainRV: {
+    Arg =3D GetObjCArg(Inst);
+
+    PtrState &S =3D MyStates.getPtrBottomUpState(Arg);
+    S.DecrementRefCount();
+    S.SetAtLeastOneRefCount();
+    S.DecrementNestCount();
+
+    switch (S.GetSeq()) {
+    case S_Stop:
+    case S_Release:
+    case S_MovableRelease:
+    case S_Use:
+      S.RRI.ReverseInsertPts.clear();
+      // FALL THROUGH
+    case S_CanRelease:
+      // Don't do retain+release tracking for IC_RetainRV, because it's
+      // better to let it remain as the first instruction after a call.
+      if (Class !=3D IC_RetainRV) {
+        S.RRI.IsRetainBlock =3D Class =3D=3D IC_RetainBlock;
+        Retains[Inst] =3D S.RRI;
+      }
+      S.ClearSequenceProgress();
+      break;
+    case S_None:
+      break;
+    case S_Retain:
+      llvm_unreachable("bottom-up pointer in retain state!");
+    }
+    return NestingDetected;
+  }
+  case IC_AutoreleasepoolPop:
+    // Conservatively, clear MyStates for all known pointers.
+    MyStates.clearBottomUpPointers();
+    return NestingDetected;
+  case IC_AutoreleasepoolPush:
+  case IC_None:
+    // These are irrelevant.
+    return NestingDetected;
+  default:
+    break;
+  }
+
+  // Consider any other possible effects of this instruction on each
+  // pointer being tracked.
+  for (BBState::ptr_iterator MI =3D MyStates.bottom_up_ptr_begin(),
+       ME =3D MyStates.bottom_up_ptr_end(); MI !=3D ME; ++MI) {
+    const Value *Ptr =3D MI->first;
+    if (Ptr =3D=3D Arg)
+      continue; // Handled above.
+    PtrState &S =3D MI->second;
+    Sequence Seq =3D S.GetSeq();
+
+    // Check for possible releases.
+    if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
+      S.DecrementRefCount();
+      switch (Seq) {
+      case S_Use:
+        S.SetSeq(S_CanRelease);
+        continue;
+      case S_CanRelease:
+      case S_Release:
+      case S_MovableRelease:
+      case S_Stop:
+      case S_None:
+        break;
+      case S_Retain:
+        llvm_unreachable("bottom-up pointer in retain state!");
+      }
+    }
+
+    // Check for possible direct uses.
+    switch (Seq) {
+    case S_Release:
+    case S_MovableRelease:
+      if (CanUse(Inst, Ptr, PA, Class)) {
+        assert(S.RRI.ReverseInsertPts.empty());
+        // If this is an invoke instruction, we're scanning it as part of
+        // one of its successor blocks, since we can't insert code after it
+        // in its own block, and we don't want to split critical edges.
+        if (isa<InvokeInst>(Inst))
+          S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
+        else
+          S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(In=
st)));
+        S.SetSeq(S_Use);
+      } else if (Seq =3D=3D S_Release &&
+                 (Class =3D=3D IC_User || Class =3D=3D IC_CallOrUser)) {
+        // Non-movable releases depend on any possible objc pointer use.
+        S.SetSeq(S_Stop);
+        assert(S.RRI.ReverseInsertPts.empty());
+        // As above; handle invoke specially.
+        if (isa<InvokeInst>(Inst))
+          S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
+        else
+          S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(In=
st)));
+      }
+      break;
+    case S_Stop:
+      if (CanUse(Inst, Ptr, PA, Class))
+        S.SetSeq(S_Use);
+      break;
+    case S_CanRelease:
+    case S_Use:
+    case S_None:
+      break;
+    case S_Retain:
+      llvm_unreachable("bottom-up pointer in retain state!");
+    }
+  }
+
+  return NestingDetected;
+}
+
+bool
 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
                           DenseMap<const BasicBlock *, BBState> &BBStates,
                           MapVector<Value *, RRInfo> &Retains) {
@@ -2274,7 +2742,13 @@
   succ_const_iterator SI(TI), SE(TI, false);
   if (SI =3D=3D SE)
     MyStates.SetAsExit();
-  else
+  else {
+    // If the terminator is an invoke marked with the
+    // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
+    // ignored, for ARC purposes.
+    if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
+      --SE;
+
     do {
       const BasicBlock *Succ =3D *SI++;
       if (Succ =3D=3D BB)
@@ -2295,318 +2769,145 @@
       }
       break;
     } while (SI !=3D SE);
+  }
=20
   // Visit all the instructions, bottom-up.
   for (BasicBlock::iterator I =3D BB->end(), E =3D BB->begin(); I !=3D E; =
--I) {
     Instruction *Inst =3D llvm::prior(I);
-    InstructionClass Class =3D GetInstructionClass(Inst);
-    const Value *Arg =3D 0;
-
-    switch (Class) {
-    case IC_Release: {
-      Arg =3D GetObjCArg(Inst);
-
-      PtrState &S =3D MyStates.getPtrBottomUpState(Arg);
-
-      // If we see two releases in a row on the same pointer. If so, make
+
+    // Invoke instructions are visited as part of their successors (below).
+    if (isa<InvokeInst>(Inst))
+      continue;
+
+    NestingDetected |=3D VisitInstructionBottomUp(Inst, BB, Retains, MySta=
tes);
+  }
+
+  // If there's a predecessor with an invoke, visit the invoke as
+  // if it were part of this block, since we can't insert code after
+  // an invoke in its own block, and we don't want to split critical
+  // edges.
+  for (pred_iterator PI(BB), PE(BB, false); PI !=3D PE; ++PI) {
+    BasicBlock *Pred =3D *PI;
+    TerminatorInst *PredTI =3D cast<TerminatorInst>(&Pred->back());
+    if (isa<InvokeInst>(PredTI))
+      NestingDetected |=3D VisitInstructionBottomUp(PredTI, BB, Retains, M=
yStates);
+  }
+
+  return NestingDetected;
+}
+
+bool
+ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
+                                    DenseMap<Value *, RRInfo> &Releases,
+                                    BBState &MyStates) {
+  bool NestingDetected =3D false;
+  InstructionClass Class =3D GetInstructionClass(Inst);
+  const Value *Arg =3D 0;
+
+  switch (Class) {
+  case IC_RetainBlock:
+    // An objc_retainBlock call with just a use may need to be kept,
+    // because it may be copying a block from the stack to the heap.
+    if (!IsRetainBlockOptimizable(Inst))
+      break;
+    // FALLTHROUGH
+  case IC_Retain:
+  case IC_RetainRV: {
+    Arg =3D GetObjCArg(Inst);
+
+    PtrState &S =3D MyStates.getPtrTopDownState(Arg);
+
+    // Don't do retain+release tracking for IC_RetainRV, because it's
+    // better to let it remain as the first instruction after a call.
+    if (Class !=3D IC_RetainRV) {
+      // If we see two retains in a row on the same pointer. If so, make
       // a note, and we'll cicle back to revisit it after we've
-      // hopefully eliminated the second release, which may allow us to
-      // eliminate the first release too.
+      // hopefully eliminated the second retain, which may allow us to
+      // eliminate the first retain too.
       // Theoretically we could implement removal of nested retain+release
       // pairs by making PtrState hold a stack of states, but this is
       // simple and avoids adding overhead for the non-nested case.
-      if (S.GetSeq() =3D=3D S_Release || S.GetSeq() =3D=3D S_MovableReleas=
e)
+      if (S.GetSeq() =3D=3D S_Retain)
         NestingDetected =3D true;
=20
-      S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
+      S.SetSeq(S_Retain);
       S.RRI.clear();
-      S.RRI.KnownSafe =3D S.IsKnownNested() || S.IsKnownIncremented();
+      S.RRI.IsRetainBlock =3D Class =3D=3D IC_RetainBlock;
+      // Don't check S.IsKnownIncremented() here because it's not
+      // sufficient.
+      S.RRI.KnownSafe =3D S.IsKnownNested();
+      S.RRI.Calls.insert(Inst);
+    }
+
+    S.SetAtLeastOneRefCount();
+    S.IncrementRefCount();
+    S.IncrementNestCount();
+    return NestingDetected;
+  }
+  case IC_Release: {
+    Arg =3D GetObjCArg(Inst);
+
+    PtrState &S =3D MyStates.getPtrTopDownState(Arg);
+    S.DecrementRefCount();
+    S.DecrementNestCount();
+
+    switch (S.GetSeq()) {
+    case S_Retain:
+    case S_CanRelease:
+      S.RRI.ReverseInsertPts.clear();
+      // FALL THROUGH
+    case S_Use:
+      S.RRI.ReleaseMetadata =3D Inst->getMetadata(ImpreciseReleaseMDKind);
       S.RRI.IsTailCallRelease =3D cast<CallInst>(Inst)->isTailCall();
-      S.RRI.Calls.insert(Inst);
-
-      S.IncrementRefCount();
-      S.IncrementNestCount();
+      Releases[Inst] =3D S.RRI;
+      S.ClearSequenceProgress();
       break;
+    case S_None:
+      break;
+    case S_Stop:
+    case S_Release:
+    case S_MovableRelease:
+      llvm_unreachable("top-down pointer in release state!");
     }
-    case IC_RetainBlock:
-    case IC_Retain:
-    case IC_RetainRV: {
-      Arg =3D GetObjCArg(Inst);
-
-      PtrState &S =3D MyStates.getPtrBottomUpState(Arg);
+    break;
+  }
+  case IC_AutoreleasepoolPop:
+    // Conservatively, clear MyStates for all known pointers.
+    MyStates.clearTopDownPointers();
+    return NestingDetected;
+  case IC_AutoreleasepoolPush:
+  case IC_None:
+    // These are irrelevant.
+    return NestingDetected;
+  default:
+    break;
+  }
+
+  // Consider any other possible effects of this instruction on each
+  // pointer being tracked.
+  for (BBState::ptr_iterator MI =3D MyStates.top_down_ptr_begin(),
+       ME =3D MyStates.top_down_ptr_end(); MI !=3D ME; ++MI) {
+    const Value *Ptr =3D MI->first;
+    if (Ptr =3D=3D Arg)
+      continue; // Handled above.
+    PtrState &S =3D MI->second;
+    Sequence Seq =3D S.GetSeq();
+
+    // Check for possible releases.
+    if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
       S.DecrementRefCount();
-      S.SetAtLeastOneRefCount();
-      S.DecrementNestCount();
-
-      // An objc_retainBlock call with just a use still needs to be kept,
-      // because it may be copying a block from the stack to the heap.
-      if (Class =3D=3D IC_RetainBlock && S.GetSeq() =3D=3D S_Use)
+      switch (Seq) {
+      case S_Retain:
         S.SetSeq(S_CanRelease);
-
-      switch (S.GetSeq()) {
-      case S_Stop:
-      case S_Release:
-      case S_MovableRelease:
+        assert(S.RRI.ReverseInsertPts.empty());
+        S.RRI.ReverseInsertPts.insert(Inst);
+
+        // One call can't cause a transition from S_Retain to S_CanRelease
+        // and S_CanRelease to S_Use. If we've made the first transition,
+        // we're done.
+        continue;
       case S_Use:
-        S.RRI.ReverseInsertPts.clear();
-        // FALL THROUGH
       case S_CanRelease:
-        // Don't do retain+release tracking for IC_RetainRV, because it's
-        // better to let it remain as the first instruction after a call.
-        if (Class !=3D IC_RetainRV) {
-          S.RRI.IsRetainBlock =3D Class =3D=3D IC_RetainBlock;
-          Retains[Inst] =3D S.RRI;
-        }
-        S.ClearSequenceProgress();
-        break;
-      case S_None:
-        break;
-      case S_Retain:
-        llvm_unreachable("bottom-up pointer in retain state!");
-      }
-      continue;
-    }
-    case IC_AutoreleasepoolPop:
-      // Conservatively, clear MyStates for all known pointers.
-      MyStates.clearBottomUpPointers();
-      continue;
-    case IC_AutoreleasepoolPush:
-    case IC_None:
-      // These are irrelevant.
-      continue;
-    default:
-      break;
-    }
-
-    // Consider any other possible effects of this instruction on each
-    // pointer being tracked.
-    for (BBState::ptr_iterator MI =3D MyStates.bottom_up_ptr_begin(),
-         ME =3D MyStates.bottom_up_ptr_end(); MI !=3D ME; ++MI) {
-      const Value *Ptr =3D MI->first;
-      if (Ptr =3D=3D Arg)
-        continue; // Handled above.
-      PtrState &S =3D MI->second;
-      Sequence Seq =3D S.GetSeq();
-
-      // Check for possible releases.
-      if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
-        S.DecrementRefCount();
-        switch (Seq) {
-        case S_Use:
-          S.SetSeq(S_CanRelease);
-          continue;
-        case S_CanRelease:
-        case S_Release:
-        case S_MovableRelease:
-        case S_Stop:
-        case S_None:
-          break;
-        case S_Retain:
-          llvm_unreachable("bottom-up pointer in retain state!");
-        }
-      }
-
-      // Check for possible direct uses.
-      switch (Seq) {
-      case S_Release:
-      case S_MovableRelease:
-        if (CanUse(Inst, Ptr, PA, Class)) {
-          assert(S.RRI.ReverseInsertPts.empty());
-          S.RRI.ReverseInsertPts.insert(Inst);
-          S.SetSeq(S_Use);
-        } else if (Seq =3D=3D S_Release &&
-                   (Class =3D=3D IC_User || Class =3D=3D IC_CallOrUser)) {
-          // Non-movable releases depend on any possible objc pointer use.
-          S.SetSeq(S_Stop);
-          assert(S.RRI.ReverseInsertPts.empty());
-          S.RRI.ReverseInsertPts.insert(Inst);
-        }
-        break;
-      case S_Stop:
-        if (CanUse(Inst, Ptr, PA, Class))
-          S.SetSeq(S_Use);
-        break;
-      case S_CanRelease:
-      case S_Use:
-      case S_None:
-        break;
-      case S_Retain:
-        llvm_unreachable("bottom-up pointer in retain state!");
-      }
-    }
-  }
-
-  return NestingDetected;
-}
-
-bool
-ObjCARCOpt::VisitTopDown(BasicBlock *BB,
-                         DenseMap<const BasicBlock *, BBState> &BBStates,
-                         DenseMap<Value *, RRInfo> &Releases) {
-  bool NestingDetected =3D false;
-  BBState &MyStates =3D BBStates[BB];
-
-  // Merge the states from each predecessor to compute the initial state
-  // for the current block.
-  const_pred_iterator PI(BB), PE(BB, false);
-  if (PI =3D=3D PE)
-    MyStates.SetAsEntry();
-  else
-    do {
-      const BasicBlock *Pred =3D *PI++;
-      if (Pred =3D=3D BB)
-        continue;
-      DenseMap<const BasicBlock *, BBState>::iterator I =3D BBStates.find(=
Pred);
-      assert(I !=3D BBStates.end());
-      // If we haven't seen this node yet, then we've found a CFG cycle.
-      // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
-      if (!I->second.isVisitedTopDown())
-        continue;
-      MyStates.InitFromPred(I->second);
-      while (PI !=3D PE) {
-        Pred =3D *PI++;
-        if (Pred !=3D BB) {
-          I =3D BBStates.find(Pred);
-          assert(I !=3D BBStates.end());
-          if (I->second.isVisitedTopDown())
-            MyStates.MergePred(I->second);
-        }
-      }
-      break;
-    } while (PI !=3D PE);
-
-  // Visit all the instructions, top-down.
-  for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E; =
++I) {
-    Instruction *Inst =3D I;
-    InstructionClass Class =3D GetInstructionClass(Inst);
-    const Value *Arg =3D 0;
-
-    switch (Class) {
-    case IC_RetainBlock:
-    case IC_Retain:
-    case IC_RetainRV: {
-      Arg =3D GetObjCArg(Inst);
-
-      PtrState &S =3D MyStates.getPtrTopDownState(Arg);
-
-      // Don't do retain+release tracking for IC_RetainRV, because it's
-      // better to let it remain as the first instruction after a call.
-      if (Class !=3D IC_RetainRV) {
-        // If we see two retains in a row on the same pointer. If so, make
-        // a note, and we'll cicle back to revisit it after we've
-        // hopefully eliminated the second retain, which may allow us to
-        // eliminate the first retain too.
-        // Theoretically we could implement removal of nested retain+relea=
se
-        // pairs by making PtrState hold a stack of states, but this is
-        // simple and avoids adding overhead for the non-nested case.
-        if (S.GetSeq() =3D=3D S_Retain)
-          NestingDetected =3D true;
-
-        S.SetSeq(S_Retain);
-        S.RRI.clear();
-        S.RRI.IsRetainBlock =3D Class =3D=3D IC_RetainBlock;
-        // Don't check S.IsKnownIncremented() here because it's not
-        // sufficient.
-        S.RRI.KnownSafe =3D S.IsKnownNested();
-        S.RRI.Calls.insert(Inst);
-      }
-
-      S.SetAtLeastOneRefCount();
-      S.IncrementRefCount();
-      S.IncrementNestCount();
-      continue;
-    }
-    case IC_Release: {
-      Arg =3D GetObjCArg(Inst);
-
-      PtrState &S =3D MyStates.getPtrTopDownState(Arg);
-      S.DecrementRefCount();
-      S.DecrementNestCount();
-
-      switch (S.GetSeq()) {
-      case S_Retain:
-      case S_CanRelease:
-        S.RRI.ReverseInsertPts.clear();
-        // FALL THROUGH
-      case S_Use:
-        S.RRI.ReleaseMetadata =3D Inst->getMetadata(ImpreciseReleaseMDKind=
);
-        S.RRI.IsTailCallRelease =3D cast<CallInst>(Inst)->isTailCall();
-        Releases[Inst] =3D S.RRI;
-        S.ClearSequenceProgress();
-        break;
-      case S_None:
-        break;
-      case S_Stop:
-      case S_Release:
-      case S_MovableRelease:
-        llvm_unreachable("top-down pointer in release state!");
-      }
-      break;
-    }
-    case IC_AutoreleasepoolPop:
-      // Conservatively, clear MyStates for all known pointers.
-      MyStates.clearTopDownPointers();
-      continue;
-    case IC_AutoreleasepoolPush:
-    case IC_None:
-      // These are irrelevant.
-      continue;
-    default:
-      break;
-    }
-
-    // Consider any other possible effects of this instruction on each
-    // pointer being tracked.
-    for (BBState::ptr_iterator MI =3D MyStates.top_down_ptr_begin(),
-         ME =3D MyStates.top_down_ptr_end(); MI !=3D ME; ++MI) {
-      const Value *Ptr =3D MI->first;
-      if (Ptr =3D=3D Arg)
-        continue; // Handled above.
-      PtrState &S =3D MI->second;
-      Sequence Seq =3D S.GetSeq();
-
-      // Check for possible releases.
-      if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
-        S.DecrementRefCount();
-        switch (Seq) {
-        case S_Retain:
-          S.SetSeq(S_CanRelease);
-          assert(S.RRI.ReverseInsertPts.empty());
-          S.RRI.ReverseInsertPts.insert(Inst);
-
-          // One call can't cause a transition from S_Retain to S_CanRelea=
se
-          // and S_CanRelease to S_Use. If we've made the first transition,
-          // we're done.
-          continue;
-        case S_Use:
-        case S_CanRelease:
-        case S_None:
-          break;
-        case S_Stop:
-        case S_Release:
-        case S_MovableRelease:
-          llvm_unreachable("top-down pointer in release state!");
-        }
-      }
-
-      // Check for possible direct uses.
-      switch (Seq) {
-      case S_CanRelease:
-        if (CanUse(Inst, Ptr, PA, Class))
-          S.SetSeq(S_Use);
-        break;
-      case S_Retain:
-        // An objc_retainBlock call may be responsible for copying the blo=
ck
-        // data from the stack to the heap. Model this by moving it straig=
ht
-        // from S_Retain to S_Use.
-        if (S.RRI.IsRetainBlock &&
-            CanUse(Inst, Ptr, PA, Class)) {
-          assert(S.RRI.ReverseInsertPts.empty());
-          S.RRI.ReverseInsertPts.insert(Inst);
-          S.SetSeq(S_Use);
-        }
-        break;
-      case S_Use:
       case S_None:
         break;
       case S_Stop:
@@ -2615,55 +2916,189 @@
         llvm_unreachable("top-down pointer in release state!");
       }
     }
+
+    // Check for possible direct uses.
+    switch (Seq) {
+    case S_CanRelease:
+      if (CanUse(Inst, Ptr, PA, Class))
+        S.SetSeq(S_Use);
+      break;
+    case S_Retain:
+    case S_Use:
+    case S_None:
+      break;
+    case S_Stop:
+    case S_Release:
+    case S_MovableRelease:
+      llvm_unreachable("top-down pointer in release state!");
+    }
+  }
+
+  return NestingDetected;
+}
+
+bool
+ObjCARCOpt::VisitTopDown(BasicBlock *BB,
+                         DenseMap<const BasicBlock *, BBState> &BBStates,
+                         DenseMap<Value *, RRInfo> &Releases) {
+  bool NestingDetected =3D false;
+  BBState &MyStates =3D BBStates[BB];
+
+  // Merge the states from each predecessor to compute the initial state
+  // for the current block.
+  const_pred_iterator PI(BB), PE(BB, false);
+  if (PI =3D=3D PE)
+    MyStates.SetAsEntry();
+  else
+    do {
+      unsigned OperandNo =3D PI.getOperandNo();
+      const Use &Us =3D PI.getUse();
+      ++PI;
+
+      // Skip invoke unwind edges on invoke instructions marked with
+      // clang.arc.no_objc_arc_exceptions.
+      if (const InvokeInst *II =3D dyn_cast<InvokeInst>(Us.getUser()))
+        if (OperandNo =3D=3D II->getNumArgOperands() + 2 &&
+            II->getMetadata(NoObjCARCExceptionsMDKind))
+          continue;
+
+      const BasicBlock *Pred =3D cast<TerminatorInst>(Us.getUser())->getPa=
rent();
+      if (Pred =3D=3D BB)
+        continue;
+      DenseMap<const BasicBlock *, BBState>::iterator I =3D BBStates.find(=
Pred);
+      // If we haven't seen this node yet, then we've found a CFG cycle.
+      // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
+      if (I =3D=3D BBStates.end() || !I->second.isVisitedTopDown())
+        continue;
+      MyStates.InitFromPred(I->second);
+      while (PI !=3D PE) {
+        Pred =3D *PI++;
+        if (Pred !=3D BB) {
+          I =3D BBStates.find(Pred);
+          if (I !=3D BBStates.end() && I->second.isVisitedTopDown())
+            MyStates.MergePred(I->second);
+        }
+      }
+      break;
+    } while (PI !=3D PE);
+
+  // Visit all the instructions, top-down.
+  for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E; =
++I) {
+    Instruction *Inst =3D I;
+    NestingDetected |=3D VisitInstructionTopDown(Inst, Releases, MyStates);
   }
=20
   CheckForCFGHazards(BB, BBStates, MyStates);
   return NestingDetected;
 }
=20
+static void
+ComputePostOrders(Function &F,
+                  SmallVectorImpl<BasicBlock *> &PostOrder,
+                  SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
+  /// Backedges - Backedges detected in the DFS. These edges will be
+  /// ignored in the reverse-CFG DFS, so that loops with multiple exits wi=
ll be
+  /// traversed in the desired order.
+  DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
+
+  /// Visited - The visited set, for doing DFS walks.
+  SmallPtrSet<BasicBlock *, 16> Visited;
+
+  // Do DFS, computing the PostOrder.
+  SmallPtrSet<BasicBlock *, 16> OnStack;
+  SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
+  BasicBlock *EntryBB =3D &F.getEntryBlock();
+  SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
+  Visited.insert(EntryBB);
+  OnStack.insert(EntryBB);
+  do {
+  dfs_next_succ:
+    TerminatorInst *TI =3D cast<TerminatorInst>(&SuccStack.back().first->b=
ack());
+    succ_iterator End =3D succ_iterator(TI, true);
+    while (SuccStack.back().second !=3D End) {
+      BasicBlock *BB =3D *SuccStack.back().second++;
+      if (Visited.insert(BB)) {
+        SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
+        OnStack.insert(BB);
+        goto dfs_next_succ;
+      }
+      if (OnStack.count(BB))
+        Backedges.insert(std::make_pair(SuccStack.back().first, BB));
+    }
+    OnStack.erase(SuccStack.back().first);
+    PostOrder.push_back(SuccStack.pop_back_val().first);
+  } while (!SuccStack.empty());
+
+  Visited.clear();
+
+  // Compute the exits, which are the starting points for reverse-CFG DFS.
+  // This includes blocks where all the successors are backedges that
+  // we're skipping.
+  SmallVector<BasicBlock *, 4> Exits;
+  for (Function::iterator I =3D F.begin(), E =3D F.end(); I !=3D E; ++I) {
+    BasicBlock *BB =3D I;
+    TerminatorInst *TI =3D cast<TerminatorInst>(&BB->back());
+    for (succ_iterator SI(TI), SE(TI, true); SI !=3D SE; ++SI)
+      if (!Backedges.count(std::make_pair(BB, *SI)))
+        goto HasNonBackedgeSucc;
+    Exits.push_back(BB);
+  HasNonBackedgeSucc:;
+  }
+
+  // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
+  SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
+  for (SmallVectorImpl<BasicBlock *>::iterator I =3D Exits.begin(), E =3D =
Exits.end();
+       I !=3D E; ++I) {
+    BasicBlock *ExitBB =3D *I;
+    PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
+    Visited.insert(ExitBB);
+    while (!PredStack.empty()) {
+    reverse_dfs_next_succ:
+      pred_iterator End =3D pred_end(PredStack.back().first);
+      while (PredStack.back().second !=3D End) {
+        BasicBlock *BB =3D *PredStack.back().second++;
+        // Skip backedges detected in the forward-CFG DFS.
+        if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
+          continue;
+        if (Visited.insert(BB)) {
+          PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
+          goto reverse_dfs_next_succ;
+        }
+      }
+      ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
+    }
+  }
+}
+
 // Visit - Visit the function both top-down and bottom-up.
 bool
 ObjCARCOpt::Visit(Function &F,
                   DenseMap<const BasicBlock *, BBState> &BBStates,
                   MapVector<Value *, RRInfo> &Retains,
                   DenseMap<Value *, RRInfo> &Releases) {
-  // Use reverse-postorder on the reverse CFG for bottom-up, because we
-  // magically know that loops will be well behaved, i.e. they won't repea=
tedly
-  // call retain on a single pointer without doing a release. We can't use
-  // ReversePostOrderTraversal here because we want to walk up from each
-  // function exit point.
-  SmallPtrSet<BasicBlock *, 16> Visited;
-  SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
-  SmallVector<BasicBlock *, 16> Order;
-  for (Function::iterator I =3D F.begin(), E =3D F.end(); I !=3D E; ++I) {
-    BasicBlock *BB =3D I;
-    if (BB->getTerminator()->getNumSuccessors() =3D=3D 0)
-      Stack.push_back(std::make_pair(BB, pred_begin(BB)));
-  }
-  while (!Stack.empty()) {
-    pred_iterator End =3D pred_end(Stack.back().first);
-    while (Stack.back().second !=3D End) {
-      BasicBlock *BB =3D *Stack.back().second++;
-      if (Visited.insert(BB))
-        Stack.push_back(std::make_pair(BB, pred_begin(BB)));
-    }
-    Order.push_back(Stack.pop_back_val().first);
-  }
+
+  // Use reverse-postorder traversals, because we magically know that loops
+  // will be well behaved, i.e. they won't repeatedly call retain on a sin=
gle
+  // pointer without doing a release. We can't use the ReversePostOrderTra=
versal
+  // class here because we want the reverse-CFG postorder to consider each
+  // function exit point, and we want to ignore selected cycle edges.
+  SmallVector<BasicBlock *, 16> PostOrder;
+  SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
+  ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
+
+  // Use reverse-postorder on the reverse CFG for bottom-up.
   bool BottomUpNestingDetected =3D false;
   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =3D
-         Order.rbegin(), E =3D Order.rend(); I !=3D E; ++I) {
-    BasicBlock *BB =3D *I;
-    BottomUpNestingDetected |=3D VisitBottomUp(BB, BBStates, Retains);
-  }
-
-  // Use regular reverse-postorder for top-down.
+       ReverseCFGPostOrder.rbegin(), E =3D ReverseCFGPostOrder.rend();
+       I !=3D E; ++I)
+    BottomUpNestingDetected |=3D VisitBottomUp(*I, BBStates, Retains);
+
+  // Use reverse-postorder for top-down.
   bool TopDownNestingDetected =3D false;
-  typedef ReversePostOrderTraversal<Function *> RPOTType;
-  RPOTType RPOT(&F);
-  for (RPOTType::rpo_iterator I =3D RPOT.begin(), E =3D RPOT.end(); I !=3D=
 E; ++I) {
-    BasicBlock *BB =3D *I;
-    TopDownNestingDetected |=3D VisitTopDown(BB, BBStates, Releases);
-  }
+  for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =3D
+       PostOrder.rbegin(), E =3D PostOrder.rend();
+       I !=3D E; ++I)
+    TopDownNestingDetected |=3D VisitTopDown(*I, BBStates, Releases);
=20
   return TopDownNestingDetected && BottomUpNestingDetected;
 }
@@ -2691,40 +3126,26 @@
                          getRetainBlockCallee(M) : getRetainCallee(M),
                        MyArg, "", InsertPt);
     Call->setDoesNotThrow();
-    if (!RetainsToMove.IsRetainBlock)
+    if (RetainsToMove.IsRetainBlock)
+      Call->setMetadata(CopyOnEscapeMDKind,
+                        MDNode::get(M->getContext(), ArrayRef<Value *>()));
+    else
       Call->setTailCall();
   }
   for (SmallPtrSet<Instruction *, 2>::const_iterator
        PI =3D RetainsToMove.ReverseInsertPts.begin(),
        PE =3D RetainsToMove.ReverseInsertPts.end(); PI !=3D PE; ++PI) {
-    Instruction *LastUse =3D *PI;
-    Instruction *InsertPts[] =3D { 0, 0, 0 };
-    if (InvokeInst *II =3D dyn_cast<InvokeInst>(LastUse)) {
-      // We can't insert code immediately after an invoke instruction, so
-      // insert code at the beginning of both successor blocks instead.
-      // The invoke's return value isn't available in the unwind block,
-      // but our releases will never depend on it, because they must be
-      // paired with retains from before the invoke.
-      InsertPts[0] =3D II->getNormalDest()->getFirstInsertionPt();
-      InsertPts[1] =3D II->getUnwindDest()->getFirstInsertionPt();
-    } else {
-      // Insert code immediately after the last use.
-      InsertPts[0] =3D llvm::next(BasicBlock::iterator(LastUse));
-    }
-
-    for (Instruction **I =3D InsertPts; *I; ++I) {
-      Instruction *InsertPt =3D *I;
-      Value *MyArg =3D ArgTy =3D=3D ParamTy ? Arg :
-                     new BitCastInst(Arg, ParamTy, "", InsertPt);
-      CallInst *Call =3D CallInst::Create(getReleaseCallee(M), MyArg,
-                                        "", InsertPt);
-      // Attach a clang.imprecise_release metadata tag, if appropriate.
-      if (MDNode *M =3D ReleasesToMove.ReleaseMetadata)
-        Call->setMetadata(ImpreciseReleaseMDKind, M);
-      Call->setDoesNotThrow();
-      if (ReleasesToMove.IsTailCallRelease)
-        Call->setTailCall();
-    }
+    Instruction *InsertPt =3D *PI;
+    Value *MyArg =3D ArgTy =3D=3D ParamTy ? Arg :
+                   new BitCastInst(Arg, ParamTy, "", InsertPt);
+    CallInst *Call =3D CallInst::Create(getReleaseCallee(M), MyArg,
+                                      "", InsertPt);
+    // Attach a clang.imprecise_release metadata tag, if appropriate.
+    if (MDNode *M =3D ReleasesToMove.ReleaseMetadata)
+      Call->setMetadata(ImpreciseReleaseMDKind, M);
+    Call->setDoesNotThrow();
+    if (ReleasesToMove.IsTailCallRelease)
+      Call->setTailCall();
   }
=20
   // Delete the original retain and release calls.
@@ -2765,17 +3186,11 @@
     Instruction *Retain =3D cast<Instruction>(V);
     Value *Arg =3D GetObjCArg(Retain);
=20
-    // If the object being released is in static storage, we know it's
+    // If the object being released is in static or stack storage, we know=
 it's
     // not being managed by ObjC reference counting, so we can delete pairs
     // regardless of what possible decrements or uses lie between them.
-    bool KnownSafe =3D isa<Constant>(Arg);
+    bool KnownSafe =3D isa<Constant>(Arg) || isa<AllocaInst>(Arg);
   =20
-    // Same for stack storage, unless this is an objc_retainBlock call,
-    // which is responsible for copying the block data from the stack to
-    // the heap.
-    if (!I->second.IsRetainBlock && isa<AllocaInst>(Arg))
-      KnownSafe =3D true;
-
     // A constant pointer can't be pointing to an object on the heap. It m=
ay
     // be reference-counted, but it won't be deleted.
     if (const LoadInst *LI =3D dyn_cast<LoadInst>(Arg))
@@ -3091,7 +3506,7 @@
            UE =3D Alloca->use_end(); UI !=3D UE; ) {
         CallInst *UserInst =3D cast<CallInst>(*UI++);
         if (!UserInst->use_empty())
-          UserInst->replaceAllUsesWith(UserInst->getOperand(1));
+          UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
         UserInst->eraseFromParent();
       }
       Alloca->eraseFromParent();
@@ -3243,6 +3658,10 @@
   // Identify the imprecise release metadata kind.
   ImpreciseReleaseMDKind =3D
     M.getContext().getMDKindID("clang.imprecise_release");
+  CopyOnEscapeMDKind =3D
+    M.getContext().getMDKindID("clang.arc.copy_on_escape");
+  NoObjCARCExceptionsMDKind =3D
+    M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
=20
   // Intuitively, objc_retain and others are nocapture, however in practice
   // they are not, because they return their argument value. And objc_rele=
ase
@@ -3344,6 +3763,11 @@
     /// RetainRV calls to make the optimization work on targets which need=
 it.
     const MDString *RetainRVMarker;
=20
+    /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
+    /// at the end of walking the function we have found no alloca
+    /// instructions, these calls can be marked "tail".
+    DenseSet<CallInst *> StoreStrongCalls;
+
     Constant *getStoreStrongCallee(Module *M);
     Constant *getRetainAutoreleaseCallee(Module *M);
     Constant *getRetainAutoreleaseRVCallee(Module *M);
@@ -3547,6 +3971,11 @@
   StoreStrong->setDoesNotThrow();
   StoreStrong->setDebugLoc(Store->getDebugLoc());
=20
+  // We can't set the tail flag yet, because we haven't yet determined
+  // whether there are any escaping allocas. Remember this call, so that
+  // we can set the tail flag once we know it's safe.
+  StoreStrongCalls.insert(StoreStrong);
+
   if (&*Iter =3D=3D Store) ++Iter;
   Store->eraseFromParent();
   Release->eraseFromParent();
@@ -3593,6 +4022,13 @@
=20
   PA.setAA(&getAnalysis<AliasAnalysis>());
=20
+  // Track whether it's ok to mark objc_storeStrong calls with the "tail"
+  // keyword. Be conservative if the function has variadic arguments.
+  // It seems that functions which "return twice" are also unsafe for the
+  // "tail" argument, because they are setjmp, which could need to
+  // return to an earlier stack state.
+  bool TailOkForStoreStrongs =3D !F.isVarArg() && !F.callsFunctionThatRetu=
rnsTwice();
+
   // For ObjC library calls which return their argument, replace uses of t=
he
   // argument with uses of the call return value, if it dominates the use.=
 This
   // reduces register pressure.
@@ -3649,6 +4085,13 @@
     case IC_Release:
       ContractRelease(Inst, I);
       continue;
+    case IC_User:
+      // Be conservative if the function has any alloca instructions.
+      // Technically we only care about escaping alloca instructions,
+      // but this is sufficient to handle some interesting cases.
+      if (isa<AllocaInst>(Inst))
+        TailOkForStoreStrongs =3D false;
+      continue;
     default:
       continue;
     }
@@ -3666,36 +4109,37 @@
         Use &U =3D UI.getUse();
         unsigned OperandNo =3D UI.getOperandNo();
         ++UI; // Increment UI now, because we may unlink its element.
-        if (Instruction *UserInst =3D dyn_cast<Instruction>(U.getUser()))
-          if (Inst !=3D UserInst && DT->dominates(Inst, UserInst)) {
-            Changed =3D true;
-            Instruction *Replacement =3D Inst;
-            Type *UseTy =3D U.get()->getType();
-            if (PHINode *PHI =3D dyn_cast<PHINode>(UserInst)) {
-              // For PHI nodes, insert the bitcast in the predecessor bloc=
k.
-              unsigned ValNo =3D
-                PHINode::getIncomingValueNumForOperand(OperandNo);
-              BasicBlock *BB =3D
-                PHI->getIncomingBlock(ValNo);
-              if (Replacement->getType() !=3D UseTy)
-                Replacement =3D new BitCastInst(Replacement, UseTy, "",
-                                              &BB->back());
-              for (unsigned i =3D 0, e =3D PHI->getNumIncomingValues();
-                   i !=3D e; ++i)
-                if (PHI->getIncomingBlock(i) =3D=3D BB) {
-                  // Keep the UI iterator valid.
-                  if (&PHI->getOperandUse(
-                        PHINode::getOperandNumForIncomingValue(i)) =3D=3D
-                        &UI.getUse())
-                    ++UI;
-                  PHI->setIncomingValue(i, Replacement);
-                }
-            } else {
-              if (Replacement->getType() !=3D UseTy)
-                Replacement =3D new BitCastInst(Replacement, UseTy, "", Us=
erInst);
-              U.set(Replacement);
-            }
+        if (DT->isReachableFromEntry(U) &&
+            DT->dominates(Inst, U)) {
+          Changed =3D true;
+          Instruction *Replacement =3D Inst;
+          Type *UseTy =3D U.get()->getType();
+          if (PHINode *PHI =3D dyn_cast<PHINode>(U.getUser())) {
+            // For PHI nodes, insert the bitcast in the predecessor block.
+            unsigned ValNo =3D
+              PHINode::getIncomingValueNumForOperand(OperandNo);
+            BasicBlock *BB =3D
+              PHI->getIncomingBlock(ValNo);
+            if (Replacement->getType() !=3D UseTy)
+              Replacement =3D new BitCastInst(Replacement, UseTy, "",
+                                            &BB->back());
+            for (unsigned i =3D 0, e =3D PHI->getNumIncomingValues();
+                 i !=3D e; ++i)
+              if (PHI->getIncomingBlock(i) =3D=3D BB) {
+                // Keep the UI iterator valid.
+                if (&PHI->getOperandUse(
+                      PHINode::getOperandNumForIncomingValue(i)) =3D=3D
+                    &UI.getUse())
+                  ++UI;
+                PHI->setIncomingValue(i, Replacement);
+              }
+          } else {
+            if (Replacement->getType() !=3D UseTy)
+              Replacement =3D new BitCastInst(Replacement, UseTy, "",
+                                            cast<Instruction>(U.getUser())=
);
+            U.set(Replacement);
           }
+        }
       }
=20
       // If Arg is a no-op casted pointer, strip one level of casts and
@@ -3713,5 +4157,13 @@
     }
   }
=20
+  // If this function has no escaping allocas or suspicious vararg usage,
+  // objc_storeStrong calls can be marked with the "tail" keyword.
+  if (TailOkForStoreStrongs)
+    for (DenseSet<CallInst *>::iterator I =3D StoreStrongCalls.begin(),
+         E =3D StoreStrongCalls.end(); I !=3D E; ++I)
+      (*I)->setTailCall();
+  StoreStrongCalls.clear();
+
   return Changed;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/Reassociate.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/Reassociate.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/Reassociate.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -74,7 +74,7 @@
 namespace {
   class Reassociate : public FunctionPass {
     DenseMap<BasicBlock*, unsigned> RankMap;
-    DenseMap<AssertingVH<>, unsigned> ValueRankMap;
+    DenseMap<AssertingVH<Value>, unsigned> ValueRankMap;
     SmallVector<WeakVH, 8> RedoInsts;
     SmallVector<WeakVH, 8> DeadInsts;
     bool MadeChange;
@@ -210,7 +210,7 @@
 /// LowerNegateToMultiply - Replace 0-X with X*-1.
 ///
 static Instruction *LowerNegateToMultiply(Instruction *Neg,
-                              DenseMap<AssertingVH<>, unsigned> &ValueRank=
Map) {
+                         DenseMap<AssertingVH<Value>, unsigned> &ValueRank=
Map) {
   Constant *Cst =3D Constant::getAllOnesValue(Neg->getType());
=20
   Instruction *Res =3D BinaryOperator::CreateMul(Neg->getOperand(1), Cst, =
"",Neg);
@@ -492,7 +492,7 @@
 /// only used by an add, transform this into (X+(0-Y)) to promote better
 /// reassociation.
 static Instruction *BreakUpSubtract(Instruction *Sub,
-                              DenseMap<AssertingVH<>, unsigned> &ValueRank=
Map) {
+                         DenseMap<AssertingVH<Value>, unsigned> &ValueRank=
Map) {
   // Convert a subtract into an add and a neg instruction. This allows sub
   // instructions to be commuted with other add instructions.
   //
@@ -517,8 +517,8 @@
 /// ConvertShiftToMul - If this is a shift of a reassociable multiply or i=
s used
 /// by one, change this into a multiply by a constant to assist with furth=
er
 /// reassociation.
-static Instruction *ConvertShiftToMul(Instruction *Shl,=20
-                              DenseMap<AssertingVH<>, unsigned> &ValueRank=
Map) {
+static Instruction *ConvertShiftToMul(Instruction *Shl,
+                         DenseMap<AssertingVH<Value>, unsigned> &ValueRank=
Map) {
   // If an operand of this shift is a reassociable multiply, or if the shi=
ft
   // is used by a reassociable multiply or add, turn into a multiply.
   if (isReassociableOp(Shl->getOperand(0), Instruction::Mul) ||
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/SCCP.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/SCCP.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/SCCP.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -25,9 +25,9 @@
 #include "llvm/Instructions.h"
 #include "llvm/Pass.h"
 #include "llvm/Analysis/ConstantFolding.h"
-#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Support/CallSite.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -39,9 +39,7 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
-#include "llvm/ADT/STLExtras.h"
 #include <algorithm>
-#include <map>
 using namespace llvm;
=20
 STATISTIC(NumInstRemoved, "Number of instructions removed");
@@ -59,7 +57,7 @@
   enum LatticeValueTy {
     /// undefined - This LLVM Value has no known value yet.
     undefined,
-   =20
+
     /// constant - This LLVM Value has a specific constant value.
     constant,
=20
@@ -68,7 +66,7 @@
     /// with another (different) constant, it goes to overdefined, instead=
 of
     /// asserting.
     forcedconstant,
-   =20
+
     /// overdefined - This instruction is not known to be constant, and we=
 know
     /// it has a value.
     overdefined
@@ -77,30 +75,30 @@
   /// Val: This stores the current lattice value along with the Constant* =
for
   /// the constant if this is a 'constant' or 'forcedconstant' value.
   PointerIntPair<Constant *, 2, LatticeValueTy> Val;
- =20
+
   LatticeValueTy getLatticeValue() const {
     return Val.getInt();
   }
- =20
+
 public:
   LatticeVal() : Val(0, undefined) {}
- =20
+
   bool isUndefined() const { return getLatticeValue() =3D=3D undefined; }
   bool isConstant() const {
     return getLatticeValue() =3D=3D constant || getLatticeValue() =3D=3D f=
orcedconstant;
   }
   bool isOverdefined() const { return getLatticeValue() =3D=3D overdefined=
; }
- =20
+
   Constant *getConstant() const {
     assert(isConstant() && "Cannot get the constant of a non-constant!");
     return Val.getPointer();
   }
- =20
+
   /// markOverdefined - Return true if this is a change in status.
   bool markOverdefined() {
     if (isOverdefined())
       return false;
-   =20
+
     Val.setInt(overdefined);
     return true;
   }
@@ -111,17 +109,17 @@
       assert(getConstant() =3D=3D V && "Marking constant with different va=
lue");
       return false;
     }
-   =20
+
     if (isUndefined()) {
       Val.setInt(constant);
       assert(V && "Marking constant with NULL");
       Val.setPointer(V);
     } else {
-      assert(getLatticeValue() =3D=3D forcedconstant &&=20
+      assert(getLatticeValue() =3D=3D forcedconstant &&
              "Cannot move from overdefined to constant!");
       // Stay at forcedconstant if the constant is the same.
       if (V =3D=3D getConstant()) return false;
-     =20
+
       // Otherwise, we go to overdefined.  Assumptions made based on the
       // forced value are possibly wrong.  Assuming this is another consta=
nt
       // could expose a contradiction.
@@ -137,7 +135,7 @@
       return dyn_cast<ConstantInt>(getConstant());
     return 0;
   }
- =20
+
   void markForcedConstant(Constant *V) {
     assert(isUndefined() && "Can't force a defined value!");
     Val.setInt(forcedconstant);
@@ -156,6 +154,7 @@
 ///
 class SCCPSolver : public InstVisitor<SCCPSolver> {
   const TargetData *TD;
+  const TargetLibraryInfo *TLI;
   SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
   DenseMap<Value*, LatticeVal> ValueState;  // The state each value is in.
=20
@@ -163,7 +162,7 @@
   /// StructType, for example for formal arguments, calls, insertelement, =
etc.
   ///
   DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
- =20
+
   /// GlobalValue - If we are tracking any values for the contents of a gl=
obal
   /// variable, we keep a mapping from the constant accessor to the elemen=
t of
   /// the global, to the currently known value.  If the value becomes
@@ -178,7 +177,7 @@
   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functi=
ons
   /// that return multiple values.
   DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetV=
als;
- =20
+
   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
   /// represented here for efficient lookup.
   SmallPtrSet<Function*, 16> MRVFunctionsTracked;
@@ -187,7 +186,7 @@
   /// arguments we make optimistic assumptions about and try to prove as
   /// constants.
   SmallPtrSet<Function*, 16> TrackingIncomingArguments;
- =20
+
   /// The reason for two worklists is that overdefined is the lowest state
   /// on the lattice, and moving things to overdefined as fast as possible
   /// makes SCCP converge much faster.
@@ -201,16 +200,13 @@
=20
   SmallVector<BasicBlock*, 64>  BBWorkList;  // The BasicBlock work list
=20
-  /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that a=
re not
-  /// overdefined, despite the fact that the PHI node is overdefined.
-  std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
-
   /// KnownFeasibleEdges - Entries in this set are edges which have alread=
y had
   /// PHI nodes retriggered.
   typedef std::pair<BasicBlock*, BasicBlock*> Edge;
   DenseSet<Edge> KnownFeasibleEdges;
 public:
-  SCCPSolver(const TargetData *td) : TD(td) {}
+  SCCPSolver(const TargetData *td, const TargetLibraryInfo *tli)
+    : TD(td), TLI(tli) {}
=20
   /// MarkBlockExecutable - This method can be used by clients to mark all=
 of
   /// the blocks that are known to be intrinsically live in the processed =
unit.
@@ -253,7 +249,7 @@
   void AddArgumentTrackedFunction(Function *F) {
     TrackingIncomingArguments.insert(F);
   }
- =20
+
   /// Solve - Solve for constants and executable blocks.
   ///
   void Solve();
@@ -274,9 +270,9 @@
     assert(I !=3D ValueState.end() && "V is not in valuemap!");
     return I->second;
   }
- =20
+
   /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
-    DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
=3D=20
+    DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
=3D
       StructValueState.find(std::make_pair(V, i));
     assert(I !=3D StructValueState.end() && "V is not in valuemap!");
     return I->second;
@@ -308,7 +304,7 @@
     else
       markOverdefined(V);
   }
- =20
+
 private:
   // markConstant - Make a value be marked as "constant".  If the value
   // is not already a constant, add it to the instruction work list so that
@@ -322,7 +318,7 @@
     else
       InstWorkList.push_back(V);
   }
- =20
+
   void markConstant(Value *V, Constant *C) {
     assert(!V->getType()->isStructTy() && "Should use other method");
     markConstant(ValueState[V], V, C);
@@ -338,14 +334,14 @@
     else
       InstWorkList.push_back(V);
   }
- =20
- =20
+
+
   // markOverdefined - Make a value be marked as "overdefined". If the
   // value is not already overdefined, add it to the overdefined instructi=
on
   // work list so that the users of the instruction are updated later.
   void markOverdefined(LatticeVal &IV, Value *V) {
     if (!IV.markOverdefined()) return;
-   =20
+
     DEBUG(dbgs() << "markOverdefined: ";
           if (Function *F =3D dyn_cast<Function>(V))
             dbgs() << "Function '" << F->getName() << "'\n";
@@ -365,7 +361,7 @@
     else if (IV.getConstant() !=3D MergeWithV.getConstant())
       markOverdefined(IV, V);
   }
- =20
+
   void mergeInValue(Value *V, LatticeVal MergeWithV) {
     assert(!V->getType()->isStructTy() && "Should use other method");
     mergeInValue(ValueState[V], V, MergeWithV);
@@ -390,7 +386,7 @@
       if (!isa<UndefValue>(V))
         LV.markConstant(C);          // Constants are constant
     }
-   =20
+
     // All others are underdefined by default.
     return LV;
   }
@@ -412,21 +408,20 @@
       return LV;  // Common case, already in the map.
=20
     if (Constant *C =3D dyn_cast<Constant>(V)) {
-      if (isa<UndefValue>(C))
+      Constant *Elt =3D C->getAggregateElement(i);
+     =20
+      if (Elt =3D=3D 0)
+        LV.markOverdefined();      // Unknown sort of constant.
+      else if (isa<UndefValue>(Elt))
         ; // Undef values remain undefined.
-      else if (ConstantStruct *CS =3D dyn_cast<ConstantStruct>(C))
-        LV.markConstant(CS->getOperand(i));      // Constants are constant.
-      else if (isa<ConstantAggregateZero>(C)) {
-        Type *FieldTy =3D cast<StructType>(V->getType())->getElementType(i=
);
-        LV.markConstant(Constant::getNullValue(FieldTy));
-      } else
-        LV.markOverdefined();      // Unknown sort of constant.
+      else
+        LV.markConstant(Elt);      // Constants are constant.
     }
-   =20
+
     // All others are underdefined by default.
     return LV;
   }
- =20
+
=20
   /// markEdgeExecutable - Mark a basic block as executable, adding it to =
the BB
   /// work list if it is not already executable.
@@ -466,33 +461,6 @@
     if (BBExecutable.count(I->getParent()))   // Inst is executable?
       visit(*I);
   }
- =20
-  /// RemoveFromOverdefinedPHIs - If I has any entries in the
-  /// UsersOfOverdefinedPHIs map for PN, remove them now.
-  void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
-    if (UsersOfOverdefinedPHIs.empty()) return;
-    typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
-    std::pair<ItTy, ItTy> Range =3D UsersOfOverdefinedPHIs.equal_range(PN);
-    for (ItTy It =3D Range.first, E =3D Range.second; It !=3D E;) {
-      if (It->second =3D=3D I)
-        UsersOfOverdefinedPHIs.erase(It++);
-      else
-        ++It;
-    }
-  }
-
-  /// InsertInOverdefinedPHIs - Insert an entry in the UsersOfOverdefinedP=
HIS
-  /// map for I and PN, but if one is there already, do not create another.
-  /// (Duplicate entries do not break anything directly, but can lead to
-  /// exponential growth of the table in rare cases.)
-  void InsertInOverdefinedPHIs(Instruction *I, PHINode *PN) {
-    typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
-    std::pair<ItTy, ItTy> Range =3D UsersOfOverdefinedPHIs.equal_range(PN);
-    for (ItTy J =3D Range.first, E =3D Range.second; J !=3D E; ++J)
-      if (J->second =3D=3D I)
-        return;
-    UsersOfOverdefinedPHIs.insert(std::make_pair(PN, I));
-  }
=20
 private:
   friend class InstVisitor<SCCPSolver>;
@@ -559,7 +527,7 @@
       Succs[0] =3D true;
       return;
     }
-   =20
+
     LatticeVal BCValue =3D getValueState(BI->getCondition());
     ConstantInt *CI =3D BCValue.getConstantInt();
     if (CI =3D=3D 0) {
@@ -569,44 +537,44 @@
         Succs[0] =3D Succs[1] =3D true;
       return;
     }
-   =20
+
     // Constant condition variables mean the branch can only go a single w=
ay.
     Succs[CI->isZero()] =3D true;
     return;
   }
- =20
+
   if (isa<InvokeInst>(TI)) {
     // Invoke instructions successors are always executable.
     Succs[0] =3D Succs[1] =3D true;
     return;
   }
- =20
+
   if (SwitchInst *SI =3D dyn_cast<SwitchInst>(&TI)) {
-    if (TI.getNumSuccessors() < 2) {
+    if (!SI->getNumCases()) {
       Succs[0] =3D true;
       return;
     }
     LatticeVal SCValue =3D getValueState(SI->getCondition());
     ConstantInt *CI =3D SCValue.getConstantInt();
-   =20
+
     if (CI =3D=3D 0) {   // Overdefined or undefined condition?
       // All destinations are executable!
       if (!SCValue.isUndefined())
         Succs.assign(TI.getNumSuccessors(), true);
       return;
     }
-     =20
-    Succs[SI->findCaseValue(CI)] =3D true;
+
+    Succs[SI->findCaseValue(CI).getSuccessorIndex()] =3D true;
     return;
   }
- =20
+
   // TODO: This could be improved if the operand is a [cast of a] BlockAdd=
ress.
   if (isa<IndirectBrInst>(&TI)) {
     // Just mark all destinations executable!
     Succs.assign(TI.getNumSuccessors(), true);
     return;
   }
- =20
+
 #ifndef NDEBUG
   dbgs() << "Unknown terminator instruction: " << TI << '\n';
 #endif
@@ -628,7 +596,7 @@
   if (BranchInst *BI =3D dyn_cast<BranchInst>(TI)) {
     if (BI->isUnconditional())
       return true;
-   =20
+
     LatticeVal BCValue =3D getValueState(BI->getCondition());
=20
     // Overdefined condition variables mean the branch could go either way,
@@ -636,40 +604,33 @@
     ConstantInt *CI =3D BCValue.getConstantInt();
     if (CI =3D=3D 0)
       return !BCValue.isUndefined();
-   =20
+
     // Constant condition variables mean the branch can only go a single w=
ay.
     return BI->getSuccessor(CI->isZero()) =3D=3D To;
   }
- =20
+
   // Invoke instructions successors are always executable.
   if (isa<InvokeInst>(TI))
     return true;
- =20
+
   if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
-    if (SI->getNumSuccessors() < 2)
+    if (SI->getNumCases() < 1)
       return true;
=20
     LatticeVal SCValue =3D getValueState(SI->getCondition());
     ConstantInt *CI =3D SCValue.getConstantInt();
-   =20
+
     if (CI =3D=3D 0)
       return !SCValue.isUndefined();
=20
-    // Make sure to skip the "default value" which isn't a value
-    for (unsigned i =3D 1, E =3D SI->getNumSuccessors(); i !=3D E; ++i)
-      if (SI->getSuccessorValue(i) =3D=3D CI) // Found the taken branch.
-        return SI->getSuccessor(i) =3D=3D To;
+    return SI->findCaseValue(CI).getCaseSuccessor() =3D=3D To;
+  }
=20
-    // If the constant value is not equal to any of the branches, we must
-    // execute default branch.
-    return SI->getDefaultDest() =3D=3D To;
-  }
- =20
   // Just mark all destinations executable!
   // TODO: This could be improved if the operand is a [cast of a] BlockAdd=
ress.
   if (isa<IndirectBrInst>(TI))
     return true;
- =20
+
 #ifndef NDEBUG
   dbgs() << "Unknown terminator instruction: " << *TI << '\n';
 #endif
@@ -699,30 +660,15 @@
   // TODO: We could do a lot better than this if code actually uses this.
   if (PN.getType()->isStructTy())
     return markAnythingOverdefined(&PN);
- =20
-  if (getValueState(&PN).isOverdefined()) {
-    // There may be instructions using this PHI node that are not overdefi=
ned
-    // themselves.  If so, make sure that they know that the PHI node oper=
and
-    // changed.
-    typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
-    std::pair<ItTy, ItTy> Range =3D UsersOfOverdefinedPHIs.equal_range(&PN=
);
-   =20
-    if (Range.first =3D=3D Range.second)
-      return;
-   =20
-    SmallVector<Instruction*, 16> Users;
-    for (ItTy I =3D Range.first, E =3D Range.second; I !=3D E; ++I)
-      Users.push_back(I->second);
-    while (!Users.empty())
-      visit(Users.pop_back_val());
+
+  if (getValueState(&PN).isOverdefined())
     return;  // Quick exit
-  }
=20
   // Super-extra-high-degree PHI nodes are unlikely to ever be marked cons=
tant,
   // and slow us down a lot.  Just mark them overdefined.
   if (PN.getNumIncomingValues() > 64)
     return markOverdefined(&PN);
- =20
+
   // Look at all of the executable operands of the PHI node.  If any of th=
em
   // are overdefined, the PHI becomes overdefined as well.  If they are all
   // constant, and they agree with each other, the PHI becomes the identic=
al
@@ -736,7 +682,7 @@
=20
     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
       continue;
-   =20
+
     if (IV.isOverdefined())    // PHI node becomes overdefined!
       return markOverdefined(&PN);
=20
@@ -744,11 +690,11 @@
       OperandVal =3D IV.getConstant();
       continue;
     }
-   =20
+
     // There is already a reachable operand.  If we conflict with it,
     // then the PHI node becomes overdefined.  If we agree with it, we
     // can continue on.
-   =20
+
     // Check to see if there are two different constants merging, if so, t=
he PHI
     // node is overdefined.
     if (IV.getConstant() !=3D OperandVal)
@@ -772,7 +718,7 @@
=20
   Function *F =3D I.getParent()->getParent();
   Value *ResultOp =3D I.getOperand(0);
- =20
+
   // If we are tracking the return value of this function, merge it in.
   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
     DenseMap<Function*, LatticeVal>::iterator TFRVI =3D
@@ -782,7 +728,7 @@
       return;
     }
   }
- =20
+
   // Handle functions that return multiple values.
   if (!TrackedMultipleRetVals.empty()) {
     if (StructType *STy =3D dyn_cast<StructType>(ResultOp->getType()))
@@ -790,7 +736,7 @@
         for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i)
           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
                        getStructValueState(ResultOp, i));
-   =20
+
   }
 }
=20
@@ -811,7 +757,7 @@
   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
     markOverdefined(&I);
   else if (OpSt.isConstant())        // Propagate constant value
-    markConstant(&I, ConstantExpr::getCast(I.getOpcode(),=20
+    markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
                                            OpSt.getConstant(), I.getType()=
));
 }
=20
@@ -821,7 +767,7 @@
   // structs in structs.
   if (EVI.getType()->isStructTy())
     return markAnythingOverdefined(&EVI);
-   =20
+
   // If this is extracting from more than one level of struct, we don't kn=
ow.
   if (EVI.getNumIndices() !=3D 1)
     return markOverdefined(&EVI);
@@ -841,15 +787,15 @@
   StructType *STy =3D dyn_cast<StructType>(IVI.getType());
   if (STy =3D=3D 0)
     return markOverdefined(&IVI);
- =20
+
   // If this has more than one index, we can't handle it, drive all result=
s to
   // undef.
   if (IVI.getNumIndices() !=3D 1)
     return markAnythingOverdefined(&IVI);
- =20
+
   Value *Aggr =3D IVI.getAggregateOperand();
   unsigned Idx =3D *IVI.idx_begin();
- =20
+
   // Compute the result based on what we're inserting.
   for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i) {
     // This passes through all values that aren't the inserted element.
@@ -858,7 +804,7 @@
       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
       continue;
     }
-   =20
+
     Value *Val =3D IVI.getInsertedValueOperand();
     if (Val->getType()->isStructTy())
       // We don't track structs in structs.
@@ -875,25 +821,25 @@
   // TODO: We could do a lot better than this if code actually uses this.
   if (I.getType()->isStructTy())
     return markAnythingOverdefined(&I);
- =20
+
   LatticeVal CondValue =3D getValueState(I.getCondition());
   if (CondValue.isUndefined())
     return;
- =20
+
   if (ConstantInt *CondCB =3D CondValue.getConstantInt()) {
     Value *OpVal =3D CondCB->isZero() ? I.getFalseValue() : I.getTrueValue=
();
     mergeInValue(&I, getValueState(OpVal));
     return;
   }
- =20
+
   // Otherwise, the condition is overdefined or a constant we can't evalua=
te.
   // See if we can produce something better than overdefined based on the =
T/F
   // value.
   LatticeVal TVal =3D getValueState(I.getTrueValue());
   LatticeVal FVal =3D getValueState(I.getFalseValue());
- =20
+
   // select ?, C, C -> C.
-  if (TVal.isConstant() && FVal.isConstant() &&=20
+  if (TVal.isConstant() && FVal.isConstant() &&
       TVal.getConstant() =3D=3D FVal.getConstant())
     return markConstant(&I, FVal.getConstant());
=20
@@ -908,7 +854,7 @@
 void SCCPSolver::visitBinaryOperator(Instruction &I) {
   LatticeVal V1State =3D getValueState(I.getOperand(0));
   LatticeVal V2State =3D getValueState(I.getOperand(1));
- =20
+
   LatticeVal &IV =3D ValueState[&I];
   if (IV.isOverdefined()) return;
=20
@@ -916,14 +862,14 @@
     return markConstant(IV, &I,
                         ConstantExpr::get(I.getOpcode(), V1State.getConsta=
nt(),
                                           V2State.getConstant()));
- =20
+
   // If something is undef, wait for it to resolve.
   if (!V1State.isOverdefined() && !V2State.isOverdefined())
     return;
- =20
+
   // Otherwise, one of our operands is overdefined.  Try to produce someth=
ing
   // better than overdefined with some tricks.
- =20
+
   // If this is an AND or OR with 0 or -1, it doesn't matter that the other
   // operand is overdefined.
   if (I.getOpcode() =3D=3D Instruction::And || I.getOpcode() =3D=3D Instru=
ction::Or) {
@@ -945,7 +891,7 @@
                        Constant::getAllOnesValue(I.getType()));
         return;
       }
-     =20
+
       if (I.getOpcode() =3D=3D Instruction::And) {
         // X and 0 =3D 0
         if (NonOverdefVal->getConstant()->isNullValue())
@@ -959,64 +905,6 @@
   }
=20
=20
-  // If both operands are PHI nodes, it is possible that this instruction =
has
-  // a constant value, despite the fact that the PHI node doesn't.  Check =
for
-  // this condition now.
-  if (PHINode *PN1 =3D dyn_cast<PHINode>(I.getOperand(0)))
-    if (PHINode *PN2 =3D dyn_cast<PHINode>(I.getOperand(1)))
-      if (PN1->getParent() =3D=3D PN2->getParent()) {
-        // Since the two PHI nodes are in the same basic block, they must =
have
-        // entries for the same predecessors.  Walk the predecessor list, =
and
-        // if all of the incoming values are constants, and the result of
-        // evaluating this expression with all incoming value pairs is the
-        // same, then this expression is a constant even though the PHI no=
de
-        // is not a constant!
-        LatticeVal Result;
-        for (unsigned i =3D 0, e =3D PN1->getNumIncomingValues(); i !=3D e=
; ++i) {
-          LatticeVal In1 =3D getValueState(PN1->getIncomingValue(i));
-          BasicBlock *InBlock =3D PN1->getIncomingBlock(i);
-          LatticeVal In2 =3DgetValueState(PN2->getIncomingValueForBlock(In=
Block));
-
-          if (In1.isOverdefined() || In2.isOverdefined()) {
-            Result.markOverdefined();
-            break;  // Cannot fold this operation over the PHI nodes!
-          }
-         =20
-          if (In1.isConstant() && In2.isConstant()) {
-            Constant *V =3D ConstantExpr::get(I.getOpcode(), In1.getConsta=
nt(),
-                                            In2.getConstant());
-            if (Result.isUndefined())
-              Result.markConstant(V);
-            else if (Result.isConstant() && Result.getConstant() !=3D V) {
-              Result.markOverdefined();
-              break;
-            }
-          }
-        }
-
-        // If we found a constant value here, then we know the instruction=
 is
-        // constant despite the fact that the PHI nodes are overdefined.
-        if (Result.isConstant()) {
-          markConstant(IV, &I, Result.getConstant());
-          // Remember that this instruction is virtually using the PHI node
-          // operands.=20
-          InsertInOverdefinedPHIs(&I, PN1);
-          InsertInOverdefinedPHIs(&I, PN2);
-          return;
-        }
-       =20
-        if (Result.isUndefined())
-          return;
-
-        // Okay, this really is overdefined now.  Since we might have
-        // speculatively thought that this was not overdefined before, and
-        // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
-        // make sure to clean out any entries that we put there, for
-        // efficiency.
-        RemoveFromOverdefinedPHIs(&I, PN1);
-        RemoveFromOverdefinedPHIs(&I, PN2);
-      }
-
   markOverdefined(&I);
 }
=20
@@ -1029,75 +917,13 @@
   if (IV.isOverdefined()) return;
=20
   if (V1State.isConstant() && V2State.isConstant())
-    return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),=20
-                                                         V1State.getConsta=
nt(),=20
+    return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
+                                                         V1State.getConsta=
nt(),
                                                         V2State.getConstan=
t()));
- =20
+
   // If operands are still undefined, wait for it to resolve.
   if (!V1State.isOverdefined() && !V2State.isOverdefined())
     return;
- =20
-  // If something is overdefined, use some tricks to avoid ending up and o=
ver
-  // defined if we can.
- =20
-  // If both operands are PHI nodes, it is possible that this instruction =
has
-  // a constant value, despite the fact that the PHI node doesn't.  Check =
for
-  // this condition now.
-  if (PHINode *PN1 =3D dyn_cast<PHINode>(I.getOperand(0)))
-    if (PHINode *PN2 =3D dyn_cast<PHINode>(I.getOperand(1)))
-      if (PN1->getParent() =3D=3D PN2->getParent()) {
-        // Since the two PHI nodes are in the same basic block, they must =
have
-        // entries for the same predecessors.  Walk the predecessor list, =
and
-        // if all of the incoming values are constants, and the result of
-        // evaluating this expression with all incoming value pairs is the
-        // same, then this expression is a constant even though the PHI no=
de
-        // is not a constant!
-        LatticeVal Result;
-        for (unsigned i =3D 0, e =3D PN1->getNumIncomingValues(); i !=3D e=
; ++i) {
-          LatticeVal In1 =3D getValueState(PN1->getIncomingValue(i));
-          BasicBlock *InBlock =3D PN1->getIncomingBlock(i);
-          LatticeVal In2 =3DgetValueState(PN2->getIncomingValueForBlock(In=
Block));
-
-          if (In1.isOverdefined() || In2.isOverdefined()) {
-            Result.markOverdefined();
-            break;  // Cannot fold this operation over the PHI nodes!
-          }
-         =20
-          if (In1.isConstant() && In2.isConstant()) {
-            Constant *V =3D ConstantExpr::getCompare(I.getPredicate(),=20
-                                                   In1.getConstant(),=20
-                                                   In2.getConstant());
-            if (Result.isUndefined())
-              Result.markConstant(V);
-            else if (Result.isConstant() && Result.getConstant() !=3D V) {
-              Result.markOverdefined();
-              break;
-            }
-          }
-        }
-
-        // If we found a constant value here, then we know the instruction=
 is
-        // constant despite the fact that the PHI nodes are overdefined.
-        if (Result.isConstant()) {
-          markConstant(&I, Result.getConstant());
-          // Remember that this instruction is virtually using the PHI node
-          // operands.
-          InsertInOverdefinedPHIs(&I, PN1);
-          InsertInOverdefinedPHIs(&I, PN2);
-          return;
-        }
-       =20
-        if (Result.isUndefined())
-          return;
-
-        // Okay, this really is overdefined now.  Since we might have
-        // speculatively thought that this was not overdefined before, and
-        // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
-        // make sure to clean out any entries that we put there, for
-        // efficiency.
-        RemoveFromOverdefinedPHIs(&I, PN1);
-        RemoveFromOverdefinedPHIs(&I, PN2);
-      }
=20
   markOverdefined(&I);
 }
@@ -1135,7 +961,7 @@
                                                     EltState.getConstant(),
                                                     IdxState.getConstant()=
));
   else if (ValState.isUndefined() && EltState.isConstant() &&
-           IdxState.isConstant())=20
+           IdxState.isConstant())
     markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getTy=
pe()),
                                                    EltState.getConstant(),
                                                    IdxState.getConstant())=
);
@@ -1153,17 +979,17 @@
   if (MaskState.isUndefined() ||
       (V1State.isUndefined() && V2State.isUndefined()))
     return;  // Undefined output if mask or both inputs undefined.
- =20
+
   if (V1State.isOverdefined() || V2State.isOverdefined() ||
       MaskState.isOverdefined()) {
     markOverdefined(&I);
   } else {
     // A mix of constant/undef inputs.
-    Constant *V1 =3D V1State.isConstant() ?=20
+    Constant *V1 =3D V1State.isConstant() ?
         V1State.getConstant() : UndefValue::get(I.getType());
-    Constant *V2 =3D V2State.isConstant() ?=20
+    Constant *V2 =3D V2State.isConstant() ?
         V2State.getConstant() : UndefValue::get(I.getType());
-    Constant *Mask =3D MaskState.isConstant() ?=20
+    Constant *Mask =3D MaskState.isConstant() ?
       MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType()=
);
     markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
   }
@@ -1183,7 +1009,7 @@
     LatticeVal State =3D getValueState(I.getOperand(i));
     if (State.isUndefined())
       return;  // Operands are not resolved yet.
-   =20
+
     if (State.isOverdefined())
       return markOverdefined(&I);
=20
@@ -1200,10 +1026,10 @@
   // If this store is of a struct, ignore it.
   if (SI.getOperand(0)->getType()->isStructTy())
     return;
- =20
+
   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
     return;
- =20
+
   GlobalVariable *GV =3D cast<GlobalVariable>(SI.getOperand(1));
   DenseMap<GlobalVariable*, LatticeVal>::iterator I =3D TrackedGlobals.fin=
d(GV);
   if (I =3D=3D TrackedGlobals.end() || I->second.isOverdefined()) return;
@@ -1221,22 +1047,22 @@
   // If this load is of a struct, just mark the result overdefined.
   if (I.getType()->isStructTy())
     return markAnythingOverdefined(&I);
- =20
+
   LatticeVal PtrVal =3D getValueState(I.getOperand(0));
   if (PtrVal.isUndefined()) return;   // The pointer is not resolved yet!
- =20
+
   LatticeVal &IV =3D ValueState[&I];
   if (IV.isOverdefined()) return;
=20
   if (!PtrVal.isConstant() || I.isVolatile())
     return markOverdefined(IV, &I);
-   =20
+
   Constant *Ptr =3D PtrVal.getConstant();
=20
   // load null -> null
   if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() =3D=3D 0)
     return markConstant(IV, &I, Constant::getNullValue(I.getType()));
- =20
+
   // Transform load (constant global) into the value loaded.
   if (GlobalVariable *GV =3D dyn_cast<GlobalVariable>(Ptr)) {
     if (!TrackedGlobals.empty()) {
@@ -1262,7 +1088,7 @@
 void SCCPSolver::visitCallSite(CallSite CS) {
   Function *F =3D CS.getCalledFunction();
   Instruction *I =3D CS.getInstruction();
- =20
+
   // The common case is that we aren't tracking the callee, either because=
 we
   // are not doing interprocedural analysis or the callee is indirect, or =
is
   // external.  Handle these cases first.
@@ -1270,17 +1096,17 @@
 CallOverdefined:
     // Void return and not tracking callee, just bail.
     if (I->getType()->isVoidTy()) return;
-   =20
+
     // Otherwise, if we have a single return value case, and if the functi=
on is
     // a declaration, maybe we can constant fold it.
     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
         canConstantFoldCallTo(F)) {
-     =20
+
       SmallVector<Constant*, 8> Operands;
       for (CallSite::arg_iterator AI =3D CS.arg_begin(), E =3D CS.arg_end(=
);
            AI !=3D E; ++AI) {
         LatticeVal State =3D getValueState(*AI);
-       =20
+
         if (State.isUndefined())
           return;  // Operands are not resolved yet.
         if (State.isOverdefined())
@@ -1288,10 +1114,10 @@
         assert(State.isConstant() && "Unknown state!");
         Operands.push_back(State.getConstant());
       }
-    =20
+
       // If we can constant fold this, mark the result of the call as a
       // constant.
-      if (Constant *C =3D ConstantFoldCall(F, Operands))
+      if (Constant *C =3D ConstantFoldCall(F, Operands, TLI))
         return markConstant(I, C);
     }
=20
@@ -1304,7 +1130,7 @@
   // the formal arguments of the function.
   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.coun=
t(F)){
     MarkBlockExecutable(F->begin());
-   =20
+
     // Propagate information from this call site into the callee.
     CallSite::arg_iterator CAI =3D CS.arg_begin();
     for (Function::arg_iterator AI =3D F->arg_begin(), E =3D F->arg_end();
@@ -1315,7 +1141,7 @@
         markOverdefined(AI);
         continue;
       }
-     =20
+
       if (StructType *STy =3D dyn_cast<StructType>(AI->getType())) {
         for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i)=
 {
           LatticeVal CallArg =3D getStructValueState(*CAI, i);
@@ -1326,22 +1152,22 @@
       }
     }
   }
- =20
+
   // If this is a single/zero retval case, see if we're tracking the funct=
ion.
   if (StructType *STy =3D dyn_cast<StructType>(F->getReturnType())) {
     if (!MRVFunctionsTracked.count(F))
       goto CallOverdefined;  // Not tracking this callee.
-   =20
+
     // If we are tracking this callee, propagate the result of the function
     // into this call site.
     for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i)
-      mergeInValue(getStructValueState(I, i), I,=20
+      mergeInValue(getStructValueState(I, i), I,
                    TrackedMultipleRetVals[std::make_pair(F, i)]);
   } else {
     DenseMap<Function*, LatticeVal>::iterator TFRVI =3D TrackedRetVals.fin=
d(F);
     if (TFRVI =3D=3D TrackedRetVals.end())
       goto CallOverdefined;  // Not tracking this callee.
-     =20
+
     // If so, propagate the return value of the callee into this call resu=
lt.
     mergeInValue(I, TFRVI->second);
   }
@@ -1370,7 +1196,7 @@
         if (Instruction *I =3D dyn_cast<Instruction>(*UI))
           OperandChangedState(I);
     }
-   =20
+
     // Process the instruction work list.
     while (!InstWorkList.empty()) {
       Value *I =3D InstWorkList.pop_back_val();
@@ -1427,11 +1253,11 @@
   for (Function::iterator BB =3D F.begin(), E =3D F.end(); BB !=3D E; ++BB=
) {
     if (!BBExecutable.count(BB))
       continue;
-   =20
+
     for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E=
; ++I) {
       // Look for instructions which produce undef values.
       if (I->getType()->isVoidTy()) continue;
-     =20
+
       if (StructType *STy =3D dyn_cast<StructType>(I->getType())) {
         // Only a few things that can be structs matter for undef.
=20
@@ -1442,7 +1268,7 @@
               continue;
=20
         // extractvalue and insertvalue don't need to be marked; they are
-        // tracked as precisely as their operands.=20
+        // tracked as precisely as their operands.
         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
           continue;
=20
@@ -1549,12 +1375,12 @@
         // X / undef -> undef.  No change.
         // X % undef -> undef.  No change.
         if (Op1LV.isUndefined()) break;
-       =20
+
         // undef / X -> 0.   X could be maxint.
         // undef % X -> 0.   X could be 1.
         markForcedConstant(I, Constant::getNullValue(ITy));
         return true;
-       =20
+
       case Instruction::AShr:
         // X >>a undef -> undef.
         if (Op1LV.isUndefined()) break;
@@ -1587,7 +1413,7 @@
         } else {
           // Leave Op1LV as Operand(1)'s LatticeValue.
         }
-       =20
+
         if (Op1LV.isConstant())
           markForcedConstant(I, Op1LV.getConstant());
         else
@@ -1627,7 +1453,7 @@
         return true;
       }
     }
- =20
+
     // Check to see if we have a branch or switch on an undefined value.  =
If so
     // we force the branch to go one way or the other to make the successor
     // values live.  It doesn't really matter which way we force it.
@@ -1636,7 +1462,7 @@
       if (!BI->isConditional()) continue;
       if (!getValueState(BI->getCondition()).isUndefined())
         continue;
-   =20
+
       // If the input to SCCP is actually branch on undef, fix the undef to
       // false.
       if (isa<UndefValue>(BI->getCondition())) {
@@ -1644,7 +1470,7 @@
         markEdgeExecutable(BB, TI->getSuccessor(1));
         return true;
       }
-     =20
+
       // Otherwise, it is a branch on a symbolic value which is currently
       // considered to be undef.  Handle this by forcing the input value t=
o the
       // branch to false.
@@ -1652,22 +1478,22 @@
                          ConstantInt::getFalse(TI->getContext()));
       return true;
     }
-   =20
+
     if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
-      if (SI->getNumSuccessors() < 2)   // no cases
+      if (!SI->getNumCases())
         continue;
       if (!getValueState(SI->getCondition()).isUndefined())
         continue;
-     =20
+
       // If the input to SCCP is actually switch on undef, fix the undef to
       // the first constant.
       if (isa<UndefValue>(SI->getCondition())) {
-        SI->setCondition(SI->getCaseValue(1));
-        markEdgeExecutable(BB, TI->getSuccessor(1));
+        SI->setCondition(SI->case_begin().getCaseValue());
+        markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
         return true;
       }
-     =20
-      markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
+
+      markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue=
());
       return true;
     }
   }
@@ -1683,6 +1509,9 @@
   /// Sparse Conditional Constant Propagator.
   ///
   struct SCCP : public FunctionPass {
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+      AU.addRequired<TargetLibraryInfo>();
+    }
     static char ID; // Pass identification, replacement for typeid
     SCCP() : FunctionPass(ID) {
       initializeSCCPPass(*PassRegistry::getPassRegistry());
@@ -1735,7 +1564,9 @@
 //
 bool SCCP::runOnFunction(Function &F) {
   DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
-  SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
+  const TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
+  const TargetLibraryInfo *TLI =3D &getAnalysis<TargetLibraryInfo>();
+  SCCPSolver Solver(TD, TLI);
=20
   // Mark the first block of the function as being executable.
   Solver.MarkBlockExecutable(F.begin());
@@ -1764,7 +1595,7 @@
       MadeChanges =3D true;
       continue;
     }
- =20
+
     // Iterate over all of the instructions in a function, replacing them =
with
     // constants if we have found them to be of constant values.
     //
@@ -1772,25 +1603,25 @@
       Instruction *Inst =3D BI++;
       if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
         continue;
-     =20
+
       // TODO: Reconstruct structs from their elements.
       if (Inst->getType()->isStructTy())
         continue;
-     =20
+
       LatticeVal IV =3D Solver.getLatticeValueFor(Inst);
       if (IV.isOverdefined())
         continue;
-     =20
+
       Constant *Const =3D IV.isConstant()
         ? IV.getConstant() : UndefValue::get(Inst->getType());
       DEBUG(dbgs() << "  Constant: " << *Const << " =3D " << *Inst);
=20
       // Replaces all of the uses of a variable with uses of the constant.
       Inst->replaceAllUsesWith(Const);
-     =20
+
       // Delete the instruction.
       Inst->eraseFromParent();
-     =20
+
       // Hey, we just changed something!
       MadeChanges =3D true;
       ++NumInstRemoved;
@@ -1807,6 +1638,9 @@
   /// Constant Propagation.
   ///
   struct IPSCCP : public ModulePass {
+    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
+      AU.addRequired<TargetLibraryInfo>();
+    }
     static char ID;
     IPSCCP() : ModulePass(ID) {
       initializeIPSCCPPass(*PassRegistry::getPassRegistry());
@@ -1816,7 +1650,11 @@
 } // end anonymous namespace
=20
 char IPSCCP::ID =3D 0;
-INITIALIZE_PASS(IPSCCP, "ipsccp",
+INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
+                "Interprocedural Sparse Conditional Constant Propagation",
+                false, false)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
+INITIALIZE_PASS_END(IPSCCP, "ipsccp",
                 "Interprocedural Sparse Conditional Constant Propagation",
                 false, false)
=20
@@ -1855,7 +1693,9 @@
 }
=20
 bool IPSCCP::runOnModule(Module &M) {
-  SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
+  const TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
+  const TargetLibraryInfo *TLI =3D &getAnalysis<TargetLibraryInfo>();
+  SCCPSolver Solver(TD, TLI);
=20
   // AddressTakenFunctions - This set keeps track of the address-taken fun=
ctions
   // that are in the input.  As IPSCCP runs through and simplifies code,
@@ -1863,19 +1703,19 @@
   // address-taken-ness.  Because of this, we keep track of their addresse=
s from
   // the first pass so we can use them for the later simplification pass.
   SmallPtrSet<Function*, 32> AddressTakenFunctions;
- =20
+
   // Loop over all functions, marking arguments to those with their addres=
ses
   // taken or that are external as overdefined.
   //
   for (Module::iterator F =3D M.begin(), E =3D M.end(); F !=3D E; ++F) {
     if (F->isDeclaration())
       continue;
-   =20
+
     // If this is a strong or ODR definition of this function, then we can
     // propagate information about its result into callsites of it.
     if (!F->mayBeOverridden())
       Solver.AddTrackedFunction(F);
-   =20
+
     // If this function only has direct calls that we can see, we can trac=
k its
     // arguments and return value aggressively, and can assume it is not c=
alled
     // unless we see evidence to the contrary.
@@ -1890,7 +1730,7 @@
=20
     // Assume the function is called.
     Solver.MarkBlockExecutable(F->begin());
-   =20
+
     // Assume nothing about the incoming arguments.
     for (Function::arg_iterator AI =3D F->arg_begin(), E =3D F->arg_end();
          AI !=3D E; ++AI)
@@ -1928,17 +1768,17 @@
       for (Function::arg_iterator AI =3D F->arg_begin(), E =3D F->arg_end(=
);
            AI !=3D E; ++AI) {
         if (AI->use_empty() || AI->getType()->isStructTy()) continue;
-       =20
+
         // TODO: Could use getStructLatticeValueFor to find out if the ent=
ire
         // result is a constant and replace it entirely if so.
=20
         LatticeVal IV =3D Solver.getLatticeValueFor(AI);
         if (IV.isOverdefined()) continue;
-       =20
+
         Constant *CST =3D IV.isConstant() ?
         IV.getConstant() : UndefValue::get(AI->getType());
         DEBUG(dbgs() << "***  Arg " << *AI << " =3D " << *CST <<"\n");
-       =20
+
         // Replaces all of the uses of a variable with uses of the
         // constant.
         AI->replaceAllUsesWith(CST);
@@ -1967,19 +1807,19 @@
           new UnreachableInst(M.getContext(), BB);
         continue;
       }
-     =20
+
       for (BasicBlock::iterator BI =3D BB->begin(), E =3D BB->end(); BI !=
=3D E; ) {
         Instruction *Inst =3D BI++;
         if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
           continue;
-       =20
+
         // TODO: Could use getStructLatticeValueFor to find out if the ent=
ire
         // result is a constant and replace it entirely if so.
-       =20
+
         LatticeVal IV =3D Solver.getLatticeValueFor(Inst);
         if (IV.isOverdefined())
           continue;
-       =20
+
         Constant *Const =3D IV.isConstant()
           ? IV.getConstant() : UndefValue::get(Inst->getType());
         DEBUG(dbgs() << "  Constant: " << *Const << " =3D " << *Inst);
@@ -1987,7 +1827,7 @@
         // Replaces all of the uses of a variable with uses of the
         // constant.
         Inst->replaceAllUsesWith(Const);
-       =20
+
         // Delete the instruction.
         if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
           Inst->eraseFromParent();
@@ -2029,15 +1869,15 @@
             llvm_unreachable("Didn't fold away reference to block!");
           }
 #endif
-         =20
+
           // Make this an uncond branch to the first successor.
           TerminatorInst *TI =3D I->getParent()->getTerminator();
           BranchInst::Create(TI->getSuccessor(0), TI);
-         =20
+
           // Remove entries in successor phi nodes to remove edges.
           for (unsigned i =3D 1, e =3D TI->getNumSuccessors(); i !=3D e; +=
+i)
             TI->getSuccessor(i)->removePredecessor(TI->getParent());
-         =20
+
           // Remove the old terminator.
           TI->eraseFromParent();
         }
@@ -2060,7 +1900,7 @@
   // last use of a function, the order of processing functions would affect
   // whether other functions are optimizable.
   SmallVector<ReturnInst*, 8> ReturnsToZap;
- =20
+
   // TODO: Process multiple value ret instructions also.
   const DenseMap<Function*, LatticeVal> &RV =3D Solver.getTrackedRetVals();
   for (DenseMap<Function*, LatticeVal>::const_iterator I =3D RV.begin(),
@@ -2068,11 +1908,11 @@
     Function *F =3D I->first;
     if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
       continue;
- =20
+
     // We can only do this if we know that nothing else can call the funct=
ion.
     if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
       continue;
-   =20
+
     for (Function::iterator BB =3D F->begin(), E =3D F->end(); BB !=3D E; =
++BB)
       if (ReturnInst *RI =3D dyn_cast<ReturnInst>(BB->getTerminator()))
         if (!isa<UndefValue>(RI->getOperand(0)))
@@ -2084,9 +1924,9 @@
     Function *F =3D ReturnsToZap[i]->getParent()->getParent();
     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
   }
-   =20
-  // If we inferred constant or undef values for globals variables, we can=
 delete
-  // the global and any stores that remain to it.
+
+  // If we inferred constant or undef values for globals variables, we can
+  // delete the global and any stores that remain to it.
   const DenseMap<GlobalVariable*, LatticeVal> &TG =3D Solver.getTrackedGlo=
bals();
   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I =3D TG.begi=
n(),
          E =3D TG.end(); I !=3D E; ++I) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/Scalar.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/Scalar.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/Scalar.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -51,6 +51,7 @@
   initializeLowerExpectIntrinsicPass(Registry);
   initializeMemCpyOptPass(Registry);
   initializeObjCARCAliasAnalysisPass(Registry);
+  initializeObjCARCAPElimPass(Registry);
   initializeObjCARCExpandPass(Registry);
   initializeObjCARCContractPass(Registry);
   initializeObjCARCOptPass(Registry);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/ScalarReplAggregates.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/ScalarReplAggregates.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/ScalarReplAggregates.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 // each member (if possible).  Then, if possible, it transforms the indivi=
dual
 // alloca instructions into nice clean scalar SSA form.
 //
-// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
+// This combines a simple SRoA algorithm with the Mem2Reg algorithm becaus=
e they
 // often interact, especially for C++ programs.  As such, iterating between
 // SRoA, then Mem2Reg until we run out of things to promote works well.
 //
@@ -453,6 +453,8 @@
=20
       // Compute the offset that this GEP adds to the pointer.
       SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
+      if (!GEP->getPointerOperandType()->isPointerTy())
+        return false;
       uint64_t GEPOffset =3D TD.getIndexedOffset(GEP->getPointerOperandTyp=
e(),
                                                Indices);
       // See if all uses can be converted.
@@ -572,8 +574,9 @@
     // transform it into a store of the expanded constant value.
     if (MemSetInst *MSI =3D dyn_cast<MemSetInst>(User)) {
       assert(MSI->getRawDest() =3D=3D Ptr && "Consistency error!");
-      unsigned NumBytes =3D cast<ConstantInt>(MSI->getLength())->getZExtVa=
lue();
-      if (NumBytes !=3D 0) {
+      int64_t SNumBytes =3D cast<ConstantInt>(MSI->getLength())->getSExtVa=
lue();
+      if (SNumBytes > 0 && (SNumBytes >> 32) =3D=3D 0) {
+        unsigned NumBytes =3D static_cast<unsigned>(SNumBytes);
         unsigned Val =3D cast<ConstantInt>(MSI->getValue())->getZExtValue(=
);
=20
         // Compute the value replicated the right number of times.
@@ -806,8 +809,10 @@
         return Builder.CreateBitCast(SV, AllocaType);
=20
     // Must be an element insertion.
-    assert(SV->getType() =3D=3D VTy->getElementType());
-    uint64_t EltSize =3D TD.getTypeAllocSizeInBits(VTy->getElementType());
+    Type *EltTy =3D VTy->getElementType();
+    if (SV->getType() !=3D EltTy)
+      SV =3D Builder.CreateBitCast(SV, EltTy);
+    uint64_t EltSize =3D TD.getTypeAllocSizeInBits(EltTy);
     unsigned Elt =3D Offset/EltSize;
     return Builder.CreateInsertElement(Old, SV, Builder.getInt32(Elt));
   }
@@ -934,13 +939,14 @@
   void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
     // Remember which alloca we're promoting (for isInstInList).
     this->AI =3D AI;
-    if (MDNode *DebugNode =3D MDNode::getIfExists(AI->getContext(), AI))
+    if (MDNode *DebugNode =3D MDNode::getIfExists(AI->getContext(), AI)) {
       for (Value::use_iterator UI =3D DebugNode->use_begin(),
              E =3D DebugNode->use_end(); UI !=3D E; ++UI)
         if (DbgDeclareInst *DDI =3D dyn_cast<DbgDeclareInst>(*UI))
           DDIs.push_back(DDI);
         else if (DbgValueInst *DVI =3D dyn_cast<DbgValueInst>(*UI))
           DVIs.push_back(DVI);
+    }
=20
     LoadAndStorePromoter::run(Insts);
     AI->eraseFromParent();
@@ -975,30 +981,25 @@
     for (SmallVector<DbgValueInst *, 4>::const_iterator I =3D DVIs.begin()=
,=20
            E =3D DVIs.end(); I !=3D E; ++I) {
       DbgValueInst *DVI =3D *I;
+      Value *Arg =3D NULL;
       if (StoreInst *SI =3D dyn_cast<StoreInst>(Inst)) {
-        Instruction *DbgVal =3D NULL;
         // If an argument is zero extended then use argument directly. The=
 ZExt
         // may be zapped by an optimization pass in future.
-        Argument *ExtendedArg =3D NULL;
         if (ZExtInst *ZExt =3D dyn_cast<ZExtInst>(SI->getOperand(0)))
-          ExtendedArg =3D dyn_cast<Argument>(ZExt->getOperand(0));
+          Arg =3D dyn_cast<Argument>(ZExt->getOperand(0));
         if (SExtInst *SExt =3D dyn_cast<SExtInst>(SI->getOperand(0)))
-          ExtendedArg =3D dyn_cast<Argument>(SExt->getOperand(0));
-        if (ExtendedArg)
-          DbgVal =3D DIB->insertDbgValueIntrinsic(ExtendedArg, 0,=20
-                                                DIVariable(DVI->getVariabl=
e()),
-                                                SI);
-        else
-          DbgVal =3D DIB->insertDbgValueIntrinsic(SI->getOperand(0), 0,=20
-                                                DIVariable(DVI->getVariabl=
e()),
-                                                SI);
-        DbgVal->setDebugLoc(DVI->getDebugLoc());
+          Arg =3D dyn_cast<Argument>(SExt->getOperand(0));
+        if (!Arg)
+          Arg =3D SI->getOperand(0);
       } else if (LoadInst *LI =3D dyn_cast<LoadInst>(Inst)) {
-        Instruction *DbgVal =3D=20
-          DIB->insertDbgValueIntrinsic(LI->getOperand(0), 0,=20
-                                       DIVariable(DVI->getVariable()), LI);
-        DbgVal->setDebugLoc(DVI->getDebugLoc());
+        Arg =3D LI->getOperand(0);
+      } else {
+        continue;
       }
+      Instruction *DbgVal =3D
+        DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()=
),
+                                     Inst);
+      DbgVal->setDebugLoc(DVI->getDebugLoc());
     }
   }
 };
@@ -1517,6 +1518,9 @@
       ConstantInt *Length =3D dyn_cast<ConstantInt>(MI->getLength());
       if (Length =3D=3D 0)
         return MarkUnsafe(Info, User);
+      if (Length->isNegative())
+        return MarkUnsafe(Info, User);
+
       isSafeMemAccess(Offset, Length->getZExtValue(), 0,
                       UI.getOperandNo() =3D=3D 0, Info, MI,
                       true /*AllowWholeAccess*/);
@@ -1873,8 +1877,14 @@
     return;
=20
   // The bitcast references the original alloca.  Replace its uses with
-  // references to the first new element alloca.
-  Instruction *Val =3D NewElts[0];
+  // references to the alloca containing offset zero (which is normally at
+  // index zero, but might not be in cases involving structs with elements
+  // of size zero).
+  Type *T =3D AI->getAllocatedType();
+  uint64_t EltOffset =3D 0;
+  Type *IdxTy;
+  uint64_t Idx =3D FindElementAndOffset(T, EltOffset, IdxTy);
+  Instruction *Val =3D NewElts[Idx];
   if (Val->getType() !=3D BC->getDestTy()) {
     Val =3D new BitCastInst(Val, BC->getDestTy(), "", BC);
     Val->takeName(BC);
@@ -2146,8 +2156,7 @@
           // If the requested value was a vector constant, create it.
           if (EltTy->isVectorTy()) {
             unsigned NumElts =3D cast<VectorType>(EltTy)->getNumElements();
-            SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
-            StoreVal =3D ConstantVector::get(Elts);
+            StoreVal =3D ConstantVector::getSplat(NumElts, StoreVal);
           }
         }
         new StoreInst(StoreVal, EltPtr, MI);
@@ -2158,6 +2167,8 @@
     }
=20
     unsigned EltSize =3D TD->getTypeAllocSize(EltTy);
+    if (!EltSize)
+      continue;
=20
     IRBuilder<> Builder(MI);
=20
@@ -2524,13 +2535,12 @@
       // ignore it if we know that the value isn't captured.
       unsigned ArgNo =3D CS.getArgumentNo(UI);
       if (CS.onlyReadsMemory() &&
-          (CS.getInstruction()->use_empty() ||
-           CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
+          (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
         continue;
=20
       // If this is being passed as a byval argument, the caller is making=
 a
       // copy, so it is only a read of the alloca.
-      if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
+      if (CS.isByValArgument(ArgNo))
         continue;
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/SimplifyLibCalls.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/SimplifyLibCalls.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/SimplifyLibCalls.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -256,19 +256,18 @@
                         ConstantInt::get(TD->getIntPtrType(*Context), Len),
                         B, TD);
     }
-
+   =20
     // Otherwise, the character is a constant, see if the first argument is
     // a string literal.  If so, we can constant fold.
-    std::string Str;
-    if (!GetConstantStringInfo(SrcStr, Str))
+    StringRef Str;
+    if (!getConstantStringInfo(SrcStr, Str))
       return 0;
=20
-    // strchr can find the nul character.
-    Str +=3D '\0';
-
-    // Compute the offset.
-    size_t I =3D Str.find(CharC->getSExtValue());
-    if (I =3D=3D std::string::npos) // Didn't find the char.  strchr retur=
ns null.
+    // Compute the offset, make sure to handle the case when we're searchi=
ng for
+    // zero (a weird way to spell strlen).
+    size_t I =3D CharC->getSExtValue() =3D=3D 0 ?
+        Str.size() : Str.find(CharC->getSExtValue());
+    if (I =3D=3D StringRef::npos) // Didn't find the char.  strchr returns=
 null.
       return Constant::getNullValue(CI->getType());
=20
     // strchr(s+n,c)  -> gep(s+n+i,c)
@@ -296,20 +295,18 @@
     if (!CharC)
       return 0;
=20
-    std::string Str;
-    if (!GetConstantStringInfo(SrcStr, Str)) {
+    StringRef Str;
+    if (!getConstantStringInfo(SrcStr, Str)) {
       // strrchr(s, 0) -> strchr(s, 0)
       if (TD && CharC->isZero())
         return EmitStrChr(SrcStr, '\0', B, TD);
       return 0;
     }
=20
-    // strrchr can find the nul character.
-    Str +=3D '\0';
-
     // Compute the offset.
-    size_t I =3D Str.rfind(CharC->getSExtValue());
-    if (I =3D=3D std::string::npos) // Didn't find the char. Return null.
+    size_t I =3D CharC->getSExtValue() =3D=3D 0 ?
+        Str.size() : Str.rfind(CharC->getSExtValue());
+    if (I =3D=3D StringRef::npos) // Didn't find the char. Return null.
       return Constant::getNullValue(CI->getType());
=20
     // strrchr(s+n,c) -> gep(s+n+i,c)
@@ -334,14 +331,13 @@
     if (Str1P =3D=3D Str2P)      // strcmp(x,x)  -> 0
       return ConstantInt::get(CI->getType(), 0);
=20
-    std::string Str1, Str2;
-    bool HasStr1 =3D GetConstantStringInfo(Str1P, Str1);
-    bool HasStr2 =3D GetConstantStringInfo(Str2P, Str2);
+    StringRef Str1, Str2;
+    bool HasStr1 =3D getConstantStringInfo(Str1P, Str1);
+    bool HasStr2 =3D getConstantStringInfo(Str2P, Str2);
=20
     // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
     if (HasStr1 && HasStr2)
-      return ConstantInt::get(CI->getType(),
-                              StringRef(Str1).compare(Str2));
+      return ConstantInt::get(CI->getType(), Str1.compare(Str2));
=20
     if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
       return B.CreateNeg(B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"),
@@ -397,14 +393,14 @@
     if (TD && Length =3D=3D 1) // strncmp(x,y,1) -> memcmp(x,y,1)
       return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, TD);
=20
-    std::string Str1, Str2;
-    bool HasStr1 =3D GetConstantStringInfo(Str1P, Str1);
-    bool HasStr2 =3D GetConstantStringInfo(Str2P, Str2);
+    StringRef Str1, Str2;
+    bool HasStr1 =3D getConstantStringInfo(Str1P, Str1);
+    bool HasStr2 =3D getConstantStringInfo(Str2P, Str2);
=20
     // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
     if (HasStr1 && HasStr2) {
-      StringRef SubStr1 =3D StringRef(Str1).substr(0, Length);
-      StringRef SubStr2 =3D StringRef(Str2).substr(0, Length);
+      StringRef SubStr1 =3D Str1.substr(0, Length);
+      StringRef SubStr2 =3D Str2.substr(0, Length);
       return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
     }
=20
@@ -549,9 +545,9 @@
         FT->getReturnType() !=3D FT->getParamType(0))
       return 0;
=20
-    std::string S1, S2;
-    bool HasS1 =3D GetConstantStringInfo(CI->getArgOperand(0), S1);
-    bool HasS2 =3D GetConstantStringInfo(CI->getArgOperand(1), S2);
+    StringRef S1, S2;
+    bool HasS1 =3D getConstantStringInfo(CI->getArgOperand(0), S1);
+    bool HasS2 =3D getConstantStringInfo(CI->getArgOperand(1), S2);
=20
     // strpbrk(s, "") -> NULL
     // strpbrk("", s) -> NULL
@@ -609,9 +605,9 @@
         !FT->getReturnType()->isIntegerTy())
       return 0;
=20
-    std::string S1, S2;
-    bool HasS1 =3D GetConstantStringInfo(CI->getArgOperand(0), S1);
-    bool HasS2 =3D GetConstantStringInfo(CI->getArgOperand(1), S2);
+    StringRef S1, S2;
+    bool HasS1 =3D getConstantStringInfo(CI->getArgOperand(0), S1);
+    bool HasS2 =3D getConstantStringInfo(CI->getArgOperand(1), S2);
=20
     // strspn(s, "") -> 0
     // strspn("", s) -> 0
@@ -619,8 +615,11 @@
       return Constant::getNullValue(CI->getType());
=20
     // Constant folding.
-    if (HasS1 && HasS2)
-      return ConstantInt::get(CI->getType(), strspn(S1.c_str(), S2.c_str()=
));
+    if (HasS1 && HasS2) {
+      size_t Pos =3D S1.find_first_not_of(S2);
+      if (Pos =3D=3D StringRef::npos) Pos =3D S1.size();
+      return ConstantInt::get(CI->getType(), Pos);
+    }
=20
     return 0;
   }
@@ -638,17 +637,20 @@
         !FT->getReturnType()->isIntegerTy())
       return 0;
=20
-    std::string S1, S2;
-    bool HasS1 =3D GetConstantStringInfo(CI->getArgOperand(0), S1);
-    bool HasS2 =3D GetConstantStringInfo(CI->getArgOperand(1), S2);
+    StringRef S1, S2;
+    bool HasS1 =3D getConstantStringInfo(CI->getArgOperand(0), S1);
+    bool HasS2 =3D getConstantStringInfo(CI->getArgOperand(1), S2);
=20
     // strcspn("", s) -> 0
     if (HasS1 && S1.empty())
       return Constant::getNullValue(CI->getType());
=20
     // Constant folding.
-    if (HasS1 && HasS2)
-      return ConstantInt::get(CI->getType(), strcspn(S1.c_str(), S2.c_str(=
)));
+    if (HasS1 && HasS2) {
+      size_t Pos =3D S1.find_first_of(S2);
+      if (Pos =3D=3D StringRef::npos) Pos =3D S1.size();
+      return ConstantInt::get(CI->getType(), Pos);
+    }
=20
     // strcspn(s, "") -> strlen(s)
     if (TD && HasS2 && S2.empty())
@@ -692,9 +694,9 @@
     }
=20
     // See if either input string is a constant string.
-    std::string SearchStr, ToFindStr;
-    bool HasStr1 =3D GetConstantStringInfo(CI->getArgOperand(0), SearchStr=
);
-    bool HasStr2 =3D GetConstantStringInfo(CI->getArgOperand(1), ToFindStr=
);
+    StringRef SearchStr, ToFindStr;
+    bool HasStr1 =3D getConstantStringInfo(CI->getArgOperand(0), SearchStr=
);
+    bool HasStr2 =3D getConstantStringInfo(CI->getArgOperand(1), ToFindStr=
);
=20
     // fold strstr(x, "") -> x.
     if (HasStr2 && ToFindStr.empty())
@@ -704,7 +706,7 @@
     if (HasStr1 && HasStr2) {
       std::string::size_type Offset =3D SearchStr.find(ToFindStr);
=20
-      if (Offset =3D=3D std::string::npos) // strstr("foo", "bar") -> null
+      if (Offset =3D=3D StringRef::npos) // strstr("foo", "bar") -> null
         return Constant::getNullValue(CI->getType());
=20
       // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
@@ -756,11 +758,11 @@
     }
=20
     // Constant folding: memcmp(x, y, l) -> cnst (all arguments are consta=
nt)
-    std::string LHSStr, RHSStr;
-    if (GetConstantStringInfo(LHS, LHSStr) &&
-        GetConstantStringInfo(RHS, RHSStr)) {
+    StringRef LHSStr, RHSStr;
+    if (getConstantStringInfo(LHS, LHSStr) &&
+        getConstantStringInfo(RHS, RHSStr)) {
       // Make sure we're not reading out-of-bounds memory.
-      if (Len > LHSStr.length() || Len > RHSStr.length())
+      if (Len > LHSStr.size() || Len > RHSStr.size())
         return 0;
       uint64_t Ret =3D memcmp(LHSStr.data(), RHSStr.data(), Len);
       return ConstantInt::get(CI->getType(), Ret);
@@ -841,6 +843,28 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 //=3D=3D=3D---------------------------------------=3D=3D=3D//
+// 'cos*' Optimizations
+
+struct CosOpt : public LibCallOptimization {
+  virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<>=
 &B) {
+    FunctionType *FT =3D Callee->getFunctionType();
+    // Just make sure this has 1 argument of FP type, which matches the
+    // result type.
+    if (FT->getNumParams() !=3D 1 || FT->getReturnType() !=3D FT->getParam=
Type(0) ||
+        !FT->getParamType(0)->isFloatingPointTy())
+      return 0;
+
+    // cos(-x) -> cos(x)
+    Value *Op1 =3D CI->getArgOperand(0);
+    if (BinaryOperator::isFNeg(Op1)) {
+      BinaryOperator *BinExpr =3D cast<BinaryOperator>(Op1);
+      return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
+    }
+    return 0;
+  }
+};
+
+//=3D=3D=3D---------------------------------------=3D=3D=3D//
 // 'pow*' Optimizations
=20
 struct PowOpt : public LibCallOptimization {
@@ -870,7 +894,7 @@
     if (Op2C->isExactlyValue(0.5)) {
       // Expand pow(x, 0.5) to (x =3D=3D -infinity ? +infinity : fabs(sqrt=
(x))).
       // This is faster than calling pow, and still handles negative zero
-      // and negative infinite correctly.
+      // and negative infinity correctly.
       // TODO: In fast-math mode, this could be just sqrt(x).
       // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
       Value *Inf =3D ConstantFP::getInfinity(CI->getType());
@@ -963,8 +987,7 @@
=20
     // floor((double)floatval) -> (double)floorf(floatval)
     Value *V =3D Cast->getOperand(0);
-    V =3D EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
-                             Callee->getAttributes());
+    V =3D EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttribu=
tes());
     return B.CreateFPExt(V, B.getDoubleTy());
   }
 };
@@ -1000,7 +1023,7 @@
     Type *ArgType =3D Op->getType();
     Value *F =3D Intrinsic::getDeclaration(Callee->getParent(),
                                          Intrinsic::cttz, ArgType);
-    Value *V =3D B.CreateCall(F, Op, "cttz");
+    Value *V =3D B.CreateCall2(F, Op, B.getFalse(), "cttz");
     V =3D B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
     V =3D B.CreateIntCast(V, B.getInt32Ty(), false);
=20
@@ -1095,8 +1118,8 @@
   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
                                    IRBuilder<> &B) {
     // Check for a fixed format string.
-    std::string FormatStr;
-    if (!GetConstantStringInfo(CI->getArgOperand(0), FormatStr))
+    StringRef FormatStr;
+    if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
       return 0;
=20
     // Empty format string -> noop.
@@ -1122,11 +1145,9 @@
         FormatStr.find('%') =3D=3D std::string::npos) {  // no format char=
acters.
       // Create a string literal with no \n on it.  We expect the constant=
 merge
       // pass to be run after this pass, to merge duplicate strings.
-      FormatStr.erase(FormatStr.end()-1);
-      Constant *C =3D ConstantArray::get(*Context, FormatStr, true);
-      C =3D new GlobalVariable(*Callee->getParent(), C->getType(), true,
-                             GlobalVariable::InternalLinkage, C, "str");
-      EmitPutS(C, B, TD);
+      FormatStr =3D FormatStr.drop_back();
+      Value *GV =3D B.CreateGlobalString(FormatStr, "str");
+      EmitPutS(GV, B, TD);
       return CI->use_empty() ? (Value*)CI :
                     ConstantInt::get(CI->getType(), FormatStr.size()+1);
     }
@@ -1184,8 +1205,8 @@
   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
                                    IRBuilder<> &B) {
     // Check for a fixed format string.
-    std::string FormatStr;
-    if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
+    StringRef FormatStr;
+    if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
       return 0;
=20
     // If we just have a format string (nothing else crazy) transform it.
@@ -1296,7 +1317,8 @@
       return ConstantInt::get(CI->getType(), 0);
=20
     // If this is writing one byte, turn it into fputc.
-    if (Bytes =3D=3D 1) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
+    // This optimisation is only valid, if the return value is unused.
+    if (Bytes =3D=3D 1 && CI->use_empty()) {  // fwrite(S,1,1,F) -> fputc(=
S[0],F)
       Value *Char =3D B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "c=
har");
       EmitFPutC(Char, CI->getArgOperand(3), B, TD);
       return ConstantInt::get(CI->getType(), 1);
@@ -1326,7 +1348,7 @@
     if (!Len) return 0;
     EmitFWrite(CI->getArgOperand(0),
                ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
-               CI->getArgOperand(1), B, TD);
+               CI->getArgOperand(1), B, TD, TLI);
     return CI;  // Known to have no uses (see above).
   }
 };
@@ -1338,8 +1360,8 @@
   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
                                    IRBuilder<> &B) {
     // All the optimizations depend on the format string.
-    std::string FormatStr;
-    if (!GetConstantStringInfo(CI->getArgOperand(1), FormatStr))
+    StringRef FormatStr;
+    if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
       return 0;
=20
     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
@@ -1354,7 +1376,7 @@
       EmitFWrite(CI->getArgOperand(1),
                  ConstantInt::get(TD->getIntPtrType(*Context),
                                   FormatStr.size()),
-                 CI->getArgOperand(0), B, TD);
+                 CI->getArgOperand(0), B, TD, TLI);
       return ConstantInt::get(CI->getType(), FormatStr.size());
     }
=20
@@ -1376,7 +1398,7 @@
       // fprintf(F, "%s", str) --> fputs(str, F)
       if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empt=
y())
         return 0;
-      EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD);
+      EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
       return CI;
     }
     return 0;
@@ -1422,8 +1444,8 @@
       return 0;
=20
     // Check for a constant string.
-    std::string Str;
-    if (!GetConstantStringInfo(CI->getArgOperand(0), Str))
+    StringRef Str;
+    if (!getConstantStringInfo(CI->getArgOperand(0), Str))
       return 0;
=20
     if (Str.empty() && CI->use_empty()) {
@@ -1457,7 +1479,7 @@
     StrToOpt StrTo; StrSpnOpt StrSpn; StrCSpnOpt StrCSpn; StrStrOpt StrStr;
     MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemS=
et;
     // Math Library Optimizations
-    PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
+    CosOpt Cos; PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
     // Integer Optimizations
     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
     ToAsciiOpt ToAscii;
@@ -1472,6 +1494,7 @@
     SimplifyLibCalls() : FunctionPass(ID), StrCpy(false), StrCpyChk(true) {
       initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
     }
+    void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
     void InitOptimizations();
     bool runOnFunction(Function &F);
=20
@@ -1502,6 +1525,11 @@
   return new SimplifyLibCalls();
 }
=20
+void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
+  if (TLI->has(F))
+    Optimizations[TLI->getName(F)] =3D Opt;
+}
+
 /// Optimizations - Populate the Optimizations map with all the optimizati=
ons
 /// we know.
 void SimplifyLibCalls::InitOptimizations() {
@@ -1527,14 +1555,17 @@
   Optimizations["strcspn"] =3D &StrCSpn;
   Optimizations["strstr"] =3D &StrStr;
   Optimizations["memcmp"] =3D &MemCmp;
-  if (TLI->has(LibFunc::memcpy)) Optimizations["memcpy"] =3D &MemCpy;
+  AddOpt(LibFunc::memcpy, &MemCpy);
   Optimizations["memmove"] =3D &MemMove;
-  if (TLI->has(LibFunc::memset)) Optimizations["memset"] =3D &MemSet;
+  AddOpt(LibFunc::memset, &MemSet);
=20
   // _chk variants of String and Memory LibCall Optimizations.
   Optimizations["__strcpy_chk"] =3D &StrCpyChk;
=20
   // Math Library Optimizations
+  Optimizations["cosf"] =3D &Cos;
+  Optimizations["cos"] =3D &Cos;
+  Optimizations["cosl"] =3D &Cos;
   Optimizations["powf"] =3D &Pow;
   Optimizations["pow"] =3D &Pow;
   Optimizations["powl"] =3D &Pow;
@@ -1582,8 +1613,8 @@
   // Formatting and IO Optimizations
   Optimizations["sprintf"] =3D &SPrintF;
   Optimizations["printf"] =3D &PrintF;
-  Optimizations["fwrite"] =3D &FWrite;
-  Optimizations["fputs"] =3D &FPuts;
+  AddOpt(LibFunc::fwrite, &FWrite);
+  AddOpt(LibFunc::fputs, &FPuts);
   Optimizations["fprintf"] =3D &FPrintF;
   Optimizations["puts"] =3D &Puts;
 }
@@ -2348,9 +2379,6 @@
 //   * cbrt(sqrt(x))  -> pow(x,1/6)
 //   * cbrt(sqrt(x))  -> pow(x,1/9)
 //
-// cos, cosf, cosl:
-//   * cos(-x)  -> cos(x)
-//
 // exp, expf, expl:
 //   * exp(log(x))  -> x
 //
@@ -2387,6 +2415,8 @@
 //   * stpcpy(str, "literal") ->
 //           llvm.memcpy(str,"literal",strlen("literal")+1,1)
 //
+// strchr:
+//   * strchr(p, 0) -> strlen(p)
 // tan, tanf, tanl:
 //   * tan(atan(x)) -> x
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Scala=
r/Sink.cpp
--- a/head/contrib/llvm/lib/Transforms/Scalar/Sink.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Scalar/Sink.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -18,6 +18,7 @@
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/Analysis/AliasAnalysis.h"
+#include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/CFG.h"
@@ -240,7 +241,7 @@
   if (SuccToSinkTo->getUniquePredecessor() !=3D ParentBlock) {
     // We cannot sink a load across a critical edge - there may be stores =
in
     // other code paths.
-    if (!Inst->isSafeToSpeculativelyExecute()) {
+    if (!isSafeToSpeculativelyExecute(Inst)) {
       DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n=
");
       return false;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/AddrModeMatcher.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/AddrModeMatcher.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/AddrModeMatcher.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -473,14 +473,7 @@
   // Check to see if this value is already used in the memory instruction's
   // block.  If so, it's already live into the block at the very least, so=
 we
   // can reasonably fold it.
-  BasicBlock *MemBB =3D MemoryInst->getParent();
-  for (Value::use_iterator UI =3D Val->use_begin(), E =3D Val->use_end();
-       UI !=3D E; ++UI)
-    // We know that uses of arguments and instructions have to be instruct=
ions.
-    if (cast<Instruction>(*UI)->getParent() =3D=3D MemBB)
-      return true;
- =20
-  return false;
+  return Val->isUsedInBasicBlock(MemoryInst->getParent());
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/BasicBlockUtils.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -249,7 +249,6 @@
     if (Term->getSuccessor(i) =3D=3D Succ)
       return i;
   }
-  return 0;
 }
=20
 /// SplitEdge -  Split the edge connecting specified block. Pass P must=20
@@ -453,9 +452,8 @@
 /// of the edges being split is an exit of a loop with other exits).
 ///
 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,=20
-                                         BasicBlock *const *Preds,
-                                         unsigned NumPreds, const char *Su=
ffix,
-                                         Pass *P) {
+                                         ArrayRef<BasicBlock*> Preds,
+                                         const char *Suffix, Pass *P) {
   // Create new basic block, insert right before the original block.
   BasicBlock *NewBB =3D BasicBlock::Create(BB->getContext(), BB->getName()=
+Suffix,
                                          BB->getParent(), BB);
@@ -464,7 +462,7 @@
   BranchInst *BI =3D BranchInst::Create(BB, NewBB);
  =20
   // Move the edges from Preds to point to NewBB instead of BB.
-  for (unsigned i =3D 0; i !=3D NumPreds; ++i) {
+  for (unsigned i =3D 0, e =3D Preds.size(); i !=3D e; ++i) {
     // This is slightly more strict than necessary; the minimum requirement
     // is that there be no more than one indirectbr branching to BB. And
     // all BlockAddress uses would need to be updated.
@@ -477,7 +475,7 @@
   // node becomes an incoming value for BB's phi node.  However, if the Pr=
eds
   // list is empty, we need to insert dummy entries into the PHI nodes in =
BB to
   // account for the newly created predecessor.
-  if (NumPreds =3D=3D 0) {
+  if (Preds.size() =3D=3D 0) {
     // Insert dummy values as the incoming value.
     for (BasicBlock::iterator I =3D BB->begin(); isa<PHINode>(I); ++I)
       cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
@@ -486,12 +484,10 @@
=20
   // Update DominatorTree, LoopInfo, and LCCSA analysis information.
   bool HasLoopExit =3D false;
-  UpdateAnalysisInformation(BB, NewBB, ArrayRef<BasicBlock*>(Preds, NumPre=
ds),
-                            P, HasLoopExit);
+  UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
=20
   // Update the PHI nodes in BB with the values coming from NewBB.
-  UpdatePHINodes(BB, NewBB, ArrayRef<BasicBlock*>(Preds, NumPreds), BI,
-                 P, HasLoopExit);
+  UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
   return NewBB;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/BreakCriticalEdges.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/BreakCriticalEdges.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -372,8 +372,7 @@
           // form, which we're in the process of restoring!
           if (!Preds.empty() && HasPredOutsideOfLoop) {
             BasicBlock *NewExitBB =3D
-              SplitBlockPredecessors(Exit, Preds.data(), Preds.size(),
-                                     "split", P);
+              SplitBlockPredecessors(Exit, Preds, "split", P);
             if (P->mustPreserveAnalysisID(LCSSAID))
               CreatePHIsForSplitLoopExit(Preds, NewExitBB, Exit);
           }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/BuildLibCalls.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/BuildLibCalls.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/BuildLibCalls.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -15,11 +15,15 @@
 #include "llvm/Type.h"
 #include "llvm/Constants.h"
 #include "llvm/Function.h"
+#include "llvm/Intrinsics.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Module.h"
 #include "llvm/Support/IRBuilder.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/LLVMContext.h"
 #include "llvm/Intrinsics.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace llvm;
=20
@@ -206,19 +210,16 @@
 /// 'floor').  This function is known to take a single of type matching 'O=
p' and
 /// returns one value with the same type.  If 'Op' is a long double, 'l' is
 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
-Value *llvm::EmitUnaryFloatFnCall(Value *Op, const char *Name,
-                                  IRBuilder<> &B, const AttrListPtr &Attrs=
) {
-  char NameBuffer[20];
+Value *llvm::EmitUnaryFloatFnCall(Value *Op, StringRef Name, IRBuilder<> &=
B,
+                                  const AttrListPtr &Attrs) {
+  SmallString<20> NameBuffer;
   if (!Op->getType()->isDoubleTy()) {
     // If we need to add a suffix, copy into NameBuffer.
-    unsigned NameLen =3D strlen(Name);
-    assert(NameLen < sizeof(NameBuffer)-2);
-    memcpy(NameBuffer, Name, NameLen);
+    NameBuffer +=3D Name;
     if (Op->getType()->isFloatTy())
-      NameBuffer[NameLen] =3D 'f';  // floorf
+      NameBuffer +=3D 'f'; // floorf
     else
-      NameBuffer[NameLen] =3D 'l';  // floorl
-    NameBuffer[NameLen+1] =3D 0;
+      NameBuffer +=3D 'l'; // floorl
     Name =3D NameBuffer;
   }
=20
@@ -299,20 +300,21 @@
 /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
 /// pointer and File is a pointer to FILE.
 void llvm::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B,
-                     const TargetData *TD) {
+                     const TargetData *TD, const TargetLibraryInfo *TLI) {
   Module *M =3D B.GetInsertBlock()->getParent()->getParent();
   AttributeWithIndex AWI[3];
   AWI[0] =3D AttributeWithIndex::get(1, Attribute::NoCapture);
   AWI[1] =3D AttributeWithIndex::get(2, Attribute::NoCapture);
   AWI[2] =3D AttributeWithIndex::get(~0u, Attribute::NoUnwind);
+  StringRef FPutsName =3D TLI->getName(LibFunc::fputs);
   Constant *F;
   if (File->getType()->isPointerTy())
-    F =3D M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
+    F =3D M->getOrInsertFunction(FPutsName, AttrListPtr::get(AWI, 3),
                                B.getInt32Ty(),
                                B.getInt8PtrTy(),
                                File->getType(), NULL);
   else
-    F =3D M->getOrInsertFunction("fputs", B.getInt32Ty(),
+    F =3D M->getOrInsertFunction(FPutsName, B.getInt32Ty(),
                                B.getInt8PtrTy(),
                                File->getType(), NULL);
   CallInst *CI =3D B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
@@ -324,23 +326,25 @@
 /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Pt=
r is
 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
 void llvm::EmitFWrite(Value *Ptr, Value *Size, Value *File,
-                      IRBuilder<> &B, const TargetData *TD) {
+                      IRBuilder<> &B, const TargetData *TD,
+                      const TargetLibraryInfo *TLI) {
   Module *M =3D B.GetInsertBlock()->getParent()->getParent();
   AttributeWithIndex AWI[3];
   AWI[0] =3D AttributeWithIndex::get(1, Attribute::NoCapture);
   AWI[1] =3D AttributeWithIndex::get(4, Attribute::NoCapture);
   AWI[2] =3D AttributeWithIndex::get(~0u, Attribute::NoUnwind);
   LLVMContext &Context =3D B.GetInsertBlock()->getContext();
+  StringRef FWriteName =3D TLI->getName(LibFunc::fwrite);
   Constant *F;
   if (File->getType()->isPointerTy())
-    F =3D M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
+    F =3D M->getOrInsertFunction(FWriteName, AttrListPtr::get(AWI, 3),
                                TD->getIntPtrType(Context),
                                B.getInt8PtrTy(),
                                TD->getIntPtrType(Context),
                                TD->getIntPtrType(Context),
                                File->getType(), NULL);
   else
-    F =3D M->getOrInsertFunction("fwrite", TD->getIntPtrType(Context),
+    F =3D M->getOrInsertFunction(FWriteName, TD->getIntPtrType(Context),
                                B.getInt8PtrTy(),
                                TD->getIntPtrType(Context),
                                TD->getIntPtrType(Context),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/CloneFunction.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/CloneFunction.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/CloneFunction.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -23,8 +23,11 @@
 #include "llvm/LLVMContext.h"
 #include "llvm/Metadata.h"
 #include "llvm/Support/CFG.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Transforms/Utils/ValueMapper.h"
 #include "llvm/Analysis/ConstantFolding.h"
+#include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/ADT/SmallVector.h"
 #include <map>
@@ -60,7 +63,6 @@
  =20
   if (CodeInfo) {
     CodeInfo->ContainsCalls          |=3D hasCalls;
-    CodeInfo->ContainsUnwinds        |=3D isa<UnwindInst>(BB->getTerminato=
r());
     CodeInfo->ContainsDynamicAllocas |=3D hasDynamicAllocas;
     CodeInfo->ContainsDynamicAllocas |=3D hasStaticAllocas &&=20
                                         BB !=3D &BB->getParent()->getEntry=
Block();
@@ -75,7 +77,8 @@
                              ValueToValueMapTy &VMap,
                              bool ModuleLevelChanges,
                              SmallVectorImpl<ReturnInst*> &Returns,
-                             const char *NameSuffix, ClonedCodeInfo *CodeI=
nfo) {
+                             const char *NameSuffix, ClonedCodeInfo *CodeI=
nfo,
+                             ValueMapTypeRemapper *TypeMapper) {
   assert(NameSuffix && "NameSuffix cannot be null!");
=20
 #ifndef NDEBUG
@@ -113,8 +116,23 @@
=20
     // Create a new basic block and copy instructions into it!
     BasicBlock *CBB =3D CloneBasicBlock(&BB, VMap, NameSuffix, NewFunc, Co=
deInfo);
-    VMap[&BB] =3D CBB;                       // Add basic block mapping.
=20
+    // Add basic block mapping.
+    VMap[&BB] =3D CBB;
+
+    // It is only legal to clone a function if a block address within that
+    // function is never referenced outside of the function.  Given that, =
we
+    // want to map block addresses from the old function to block addresse=
s in
+    // the clone. (This is different from the generic ValueMapper
+    // implementation, which generates an invalid blockaddress when
+    // cloning a function.)
+    if (BB.hasAddressTaken()) {
+      Constant *OldBBAddr =3D BlockAddress::get(const_cast<Function*>(OldF=
unc),
+                                              const_cast<BasicBlock*>(&BB)=
);
+      VMap[OldBBAddr] =3D BlockAddress::get(NewFunc, CBB);                =
                        =20
+    }
+
+    // Note return instructions for the caller.
     if (ReturnInst *RI =3D dyn_cast<ReturnInst>(CBB->getTerminator()))
       Returns.push_back(RI);
   }
@@ -126,7 +144,8 @@
     // Loop over all instructions, fixing each one as we find it...
     for (BasicBlock::iterator II =3D BB->begin(); II !=3D BB->end(); ++II)
       RemapInstruction(II, VMap,
-                       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChan=
ges);
+                       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChan=
ges,
+                       TypeMapper);
 }
=20
 /// CloneFunction - Return a copy of the specified function, but without
@@ -181,7 +200,6 @@
     const Function *OldFunc;
     ValueToValueMapTy &VMap;
     bool ModuleLevelChanges;
-    SmallVectorImpl<ReturnInst*> &Returns;
     const char *NameSuffix;
     ClonedCodeInfo *CodeInfo;
     const TargetData *TD;
@@ -189,24 +207,18 @@
     PruningFunctionCloner(Function *newFunc, const Function *oldFunc,
                           ValueToValueMapTy &valueMap,
                           bool moduleLevelChanges,
-                          SmallVectorImpl<ReturnInst*> &returns,
                           const char *nameSuffix,=20
                           ClonedCodeInfo *codeInfo,
                           const TargetData *td)
     : NewFunc(newFunc), OldFunc(oldFunc),
       VMap(valueMap), ModuleLevelChanges(moduleLevelChanges),
-      Returns(returns), NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td)=
 {
+      NameSuffix(nameSuffix), CodeInfo(codeInfo), TD(td) {
     }
=20
     /// CloneBlock - The specified block is found to be reachable, clone i=
t and
     /// anything that it can reach.
     void CloneBlock(const BasicBlock *BB,
                     std::vector<const BasicBlock*> &ToClone);
-   =20
-  public:
-    /// ConstantFoldMappedInstruction - Constant fold the specified instru=
ction,
-    /// mapping its operands through VMap if they are available.
-    Constant *ConstantFoldMappedInstruction(const Instruction *I);
   };
 }
=20
@@ -214,7 +226,7 @@
 /// anything that it can reach.
 void PruningFunctionCloner::CloneBlock(const BasicBlock *BB,
                                        std::vector<const BasicBlock*> &ToC=
lone){
-  TrackingVH<Value> &BBEntry =3D VMap[BB];
+  WeakVH &BBEntry =3D VMap[BB];
=20
   // Have we already cloned this block?
   if (BBEntry) return;
@@ -224,25 +236,55 @@
   BBEntry =3D NewBB =3D BasicBlock::Create(BB->getContext());
   if (BB->hasName()) NewBB->setName(BB->getName()+NameSuffix);
=20
+  // It is only legal to clone a function if a block address within that
+  // function is never referenced outside of the function.  Given that, we
+  // want to map block addresses from the old function to block addresses =
in
+  // the clone. (This is different from the generic ValueMapper
+  // implementation, which generates an invalid blockaddress when
+  // cloning a function.)
+  //
+  // Note that we don't need to fix the mapping for unreachable blocks;
+  // the default mapping there is safe.
+  if (BB->hasAddressTaken()) {
+    Constant *OldBBAddr =3D BlockAddress::get(const_cast<Function*>(OldFun=
c),
+                                            const_cast<BasicBlock*>(BB));
+    VMap[OldBBAddr] =3D BlockAddress::get(NewFunc, NewBB);
+  }
+   =20
+
   bool hasCalls =3D false, hasDynamicAllocas =3D false, hasStaticAllocas =
=3D false;
  =20
   // Loop over all instructions, and copy them over, DCE'ing as we go.  Th=
is
   // loop doesn't include the terminator.
   for (BasicBlock::const_iterator II =3D BB->begin(), IE =3D --BB->end();
        II !=3D IE; ++II) {
-    // If this instruction constant folds, don't bother cloning the instru=
ction,
-    // instead, just add the constant to the value map.
-    if (Constant *C =3D ConstantFoldMappedInstruction(II)) {
-      VMap[II] =3D C;
-      continue;
+    Instruction *NewInst =3D II->clone();
+
+    // Eagerly remap operands to the newly cloned instruction, except for =
PHI
+    // nodes for which we defer processing until we update the CFG.
+    if (!isa<PHINode>(NewInst)) {
+      RemapInstruction(NewInst, VMap,
+                       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChan=
ges);
+
+      // If we can simplify this instruction to some other value, simply a=
dd
+      // a mapping to that value rather than inserting a new instruction i=
nto
+      // the basic block.
+      if (Value *V =3D SimplifyInstruction(NewInst, TD)) {
+        // On the off-chance that this simplifies to an instruction in the=
 old
+        // function, map it back into the new function.
+        if (Value *MappedV =3D VMap.lookup(V))
+          V =3D MappedV;
+
+        VMap[II] =3D V;
+        delete NewInst;
+        continue;
+      }
     }
=20
-    Instruction *NewInst =3D II->clone();
     if (II->hasName())
       NewInst->setName(II->getName()+NameSuffix);
+    VMap[II] =3D NewInst;                // Add instruction map to value.
     NewBB->getInstList().push_back(NewInst);
-    VMap[II] =3D NewInst;                // Add instruction map to value.
-   =20
     hasCalls |=3D (isa<CallInst>(II) && !isa<DbgInfoIntrinsic>(II));
     if (const AllocaInst *AI =3D dyn_cast<AllocaInst>(II)) {
       if (isa<ConstantInt>(AI->getArraySize()))
@@ -281,7 +323,8 @@
       Cond =3D dyn_cast_or_null<ConstantInt>(V);
     }
     if (Cond) {     // Constant fold to uncond branch!
-      BasicBlock *Dest =3D SI->getSuccessor(SI->findCaseValue(Cond));
+      SwitchInst::ConstCaseIt Case =3D SI->findCaseValue(Cond);
+      BasicBlock *Dest =3D const_cast<BasicBlock*>(Case.getCaseSuccessor()=
);
       VMap[OldTI] =3D BranchInst::Create(Dest, NewBB);
       ToClone.push_back(Dest);
       TerminatorDone =3D true;
@@ -303,38 +346,10 @@
  =20
   if (CodeInfo) {
     CodeInfo->ContainsCalls          |=3D hasCalls;
-    CodeInfo->ContainsUnwinds        |=3D isa<UnwindInst>(OldTI);
     CodeInfo->ContainsDynamicAllocas |=3D hasDynamicAllocas;
     CodeInfo->ContainsDynamicAllocas |=3D hasStaticAllocas &&=20
       BB !=3D &BB->getParent()->front();
   }
- =20
-  if (ReturnInst *RI =3D dyn_cast<ReturnInst>(NewBB->getTerminator()))
-    Returns.push_back(RI);
-}
-
-/// ConstantFoldMappedInstruction - Constant fold the specified instructio=
n,
-/// mapping its operands through VMap if they are available.
-Constant *PruningFunctionCloner::
-ConstantFoldMappedInstruction(const Instruction *I) {
-  SmallVector<Constant*, 8> Ops;
-  for (unsigned i =3D 0, e =3D I->getNumOperands(); i !=3D e; ++i)
-    if (Constant *Op =3D dyn_cast_or_null<Constant>(MapValue(I->getOperand=
(i),
-                                                           VMap,
-                  ModuleLevelChanges ? RF_None : RF_NoModuleLevelChanges)))
-      Ops.push_back(Op);
-    else
-      return 0;  // All operands not constant!
-
-  if (const CmpInst *CI =3D dyn_cast<CmpInst>(I))
-    return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops=
[1],
-                                           TD);
-
-  if (const LoadInst *LI =3D dyn_cast<LoadInst>(I))
-    if (!LI->isVolatile())
-      return ConstantFoldLoadFromConstPtr(Ops[0], TD);
-
-  return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD);
 }
=20
 /// CloneAndPruneFunctionInto - This works exactly like CloneFunctionInto,
@@ -361,7 +376,7 @@
 #endif
=20
   PruningFunctionCloner PFC(NewFunc, OldFunc, VMap, ModuleLevelChanges,
-                            Returns, NameSuffix, CodeInfo, TD);
+                            NameSuffix, CodeInfo, TD);
=20
   // Clone the entry block, and anything recursively reachable from it.
   std::vector<const BasicBlock*> CloneWorklist;
@@ -386,29 +401,19 @@
=20
     // Add the new block to the new function.
     NewFunc->getBasicBlockList().push_back(NewBB);
-   =20
-    // Loop over all of the instructions in the block, fixing up operand
-    // references as we go.  This uses VMap to do all the hard work.
-    //
-    BasicBlock::iterator I =3D NewBB->begin();
=20
-    DebugLoc TheCallDL;
-    if (TheCall)=20
-      TheCallDL =3D TheCall->getDebugLoc();
-   =20
     // Handle PHI nodes specially, as we have to remove references to dead
     // blocks.
-    if (PHINode *PN =3D dyn_cast<PHINode>(I)) {
-      // Skip over all PHI nodes, remembering them for later.
-      BasicBlock::const_iterator OldI =3D BI->begin();
-      for (; (PN =3D dyn_cast<PHINode>(I)); ++I, ++OldI)
-        PHIToResolve.push_back(cast<PHINode>(OldI));
-    }
-   =20
-    // Otherwise, remap the rest of the instructions normally.
-    for (; I !=3D NewBB->end(); ++I)
-      RemapInstruction(I, VMap,
-                       ModuleLevelChanges ? RF_None : RF_NoModuleLevelChan=
ges);
+    for (BasicBlock::const_iterator I =3D BI->begin(), E =3D BI->end(); I =
!=3D E; ++I)
+      if (const PHINode *PN =3D dyn_cast<PHINode>(I))
+        PHIToResolve.push_back(PN);
+      else
+        break;
+
+    // Finally, remap the terminator instructions, as those can't be remap=
ped
+    // until all BBs are mapped.
+    RemapInstruction(NewBB->getTerminator(), VMap,
+                     ModuleLevelChanges ? RF_None : RF_NoModuleLevelChange=
s);
   }
  =20
   // Defer PHI resolution until rest of function is resolved, PHI resoluti=
on
@@ -490,31 +495,55 @@
         ++OldI;
       }
     }
-    // NOTE: We cannot eliminate single entry phi nodes here, because of
-    // VMap.  Single entry phi nodes can have multiple VMap entries
-    // pointing at them.  Thus, deleting one would require scanning the VM=
ap
-    // to update any entries in it that would require that.  This would be
-    // really slow.
   }
- =20
+
+  // Make a second pass over the PHINodes now that all of them have been
+  // remapped into the new function, simplifying the PHINode and performin=
g any
+  // recursive simplifications exposed. This will transparently update the
+  // WeakVH in the VMap. Notably, we rely on that so that if we coalesce
+  // two PHINodes, the iteration over the old PHIs remains valid, and the
+  // mapping will just map us to the new node (which may not even be a PHI
+  // node).
+  for (unsigned Idx =3D 0, Size =3D PHIToResolve.size(); Idx !=3D Size; ++=
Idx)
+    if (PHINode *PN =3D dyn_cast<PHINode>(VMap[PHIToResolve[Idx]]))
+      recursivelySimplifyInstruction(PN, TD);
+
   // Now that the inlined function body has been fully constructed, go thr=
ough
   // and zap unconditional fall-through branches.  This happen all the tim=
e when
   // specializing code: code specialization turns conditional branches into
   // uncond branches, and this code folds them.
-  Function::iterator I =3D cast<BasicBlock>(VMap[&OldFunc->getEntryBlock()=
]);
+  Function::iterator Begin =3D cast<BasicBlock>(VMap[&OldFunc->getEntryBlo=
ck()]);
+  Function::iterator I =3D Begin;
   while (I !=3D NewFunc->end()) {
+    // Check if this block has become dead during inlining or other
+    // simplifications. Note that the first block will appear dead, as it =
has
+    // not yet been wired up properly.
+    if (I !=3D Begin && (pred_begin(I) =3D=3D pred_end(I) ||
+                       I->getSinglePredecessor() =3D=3D I)) {
+      BasicBlock *DeadBB =3D I++;
+      DeleteDeadBlock(DeadBB);
+      continue;
+    }
+
+    // We need to simplify conditional branches and switches with a consta=
nt
+    // operand. We try to prune these out when cloning, but if the
+    // simplification required looking through PHI nodes, those are only
+    // available after forming the full basic block. That may leave some h=
ere,
+    // and we still want to prune the dead code as early as possible.
+    ConstantFoldTerminator(I);
+
     BranchInst *BI =3D dyn_cast<BranchInst>(I->getTerminator());
     if (!BI || BI->isConditional()) { ++I; continue; }
    =20
-    // Note that we can't eliminate uncond branches if the destination has
-    // single-entry PHI nodes.  Eliminating the single-entry phi nodes wou=
ld
-    // require scanning the VMap to update any entries that point to the p=
hi
-    // node.
     BasicBlock *Dest =3D BI->getSuccessor(0);
-    if (!Dest->getSinglePredecessor() || isa<PHINode>(Dest->begin())) {
+    if (!Dest->getSinglePredecessor()) {
       ++I; continue;
     }
-   =20
+
+    // We shouldn't be able to get single-entry PHI nodes here, as instsim=
plify
+    // above should have zapped all of them..
+    assert(!isa<PHINode>(Dest->begin()));
+
     // We know all single-entry PHI nodes in the inlined function have been
     // removed, so we just need to splice the blocks.
     BI->eraseFromParent();
@@ -530,4 +559,13 @@
    =20
     // Do not increment I, iteratively merge all things this block branche=
s to.
   }
+
+  // Make a final pass over the basic blocks from theh old function to gat=
her
+  // any return instructions which survived folding. We have to do this he=
re
+  // because we can iteratively remove and merge returns above.
+  for (Function::iterator I =3D cast<BasicBlock>(VMap[&OldFunc->getEntryBl=
ock()]),
+                          E =3D NewFunc->end();
+       I !=3D E; ++I)
+    if (ReturnInst *RI =3D dyn_cast<ReturnInst>(I->getTerminator()))
+      Returns.push_back(RI);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/CodeExtractor.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/CodeExtractor.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/CodeExtractor.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -615,9 +615,10 @@
   default:
     // Otherwise, make the default destination of the switch instruction b=
e one
     // of the other successors.
-    TheSwitch->setOperand(0, call);
-    TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
-    TheSwitch->removeCase(NumExitBlocks);  // Remove redundant case
+    TheSwitch->setCondition(call);
+    TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks));
+    // Remove redundant case
+    TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1));
     break;
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/DemoteRegToStack.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/DemoteRegToStack.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/DemoteRegToStack.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -6,21 +6,12 @@
 // License. See LICENSE.TXT for details.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//
-// This file provide the function DemoteRegToStack().  This function takes=
 a
-// virtual register computed by an Instruction and replaces it with a slot=
 in
-// the stack frame, allocated via alloca. It returns the pointer to the
-// AllocaInst inserted.  After this function is called on an instruction, =
we are
-// guaranteed that the only user of the instruction is a store that is
-// immediately after it.
-//
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Function.h"
 #include "llvm/Instructions.h"
 #include "llvm/Type.h"
-#include <map>
+#include "llvm/ADT/DenseMap.h"
 using namespace llvm;
=20
 /// DemoteRegToStack - This function takes a virtual register computed by =
an
@@ -28,8 +19,7 @@
 /// alloca.  This allows the CFG to be changed around without fear of
 /// invalidating the SSA information for the value.  It returns the pointe=
r to
 /// the alloca inserted to create a stack slot for I.
-///
-AllocaInst* llvm::DemoteRegToStack(Instruction &I, bool VolatileLoads,
+AllocaInst *llvm::DemoteRegToStack(Instruction &I, bool VolatileLoads,
                                    Instruction *AllocaPoint) {
   if (I.use_empty()) {
     I.eraseFromParent();
@@ -47,21 +37,20 @@
                           F->getEntryBlock().begin());
   }
=20
-  // Change all of the users of the instruction to read from the stack slot
-  // instead.
+  // Change all of the users of the instruction to read from the stack slo=
t.
   while (!I.use_empty()) {
     Instruction *U =3D cast<Instruction>(I.use_back());
     if (PHINode *PN =3D dyn_cast<PHINode>(U)) {
       // If this is a PHI node, we can't insert a load of the value before=
 the
-      // use.  Instead, insert the load in the predecessor block correspon=
ding
+      // use.  Instead insert the load in the predecessor block correspond=
ing
       // to the incoming value.
       //
       // Note that if there are multiple edges from a basic block to this =
PHI
-      // node that we cannot multiple loads.  The problem is that the resu=
ltant
-      // PHI node will have multiple values (from each load) coming in fro=
m the
-      // same block, which is illegal SSA form.  For this reason, we keep =
track
-      // and reuse loads we insert.
-      std::map<BasicBlock*, Value*> Loads;
+      // node that we cannot have multiple loads. The problem is that the
+      // resulting PHI node will have multiple values (from each load) com=
ing in
+      // from the same block, which is illegal SSA form. For this reason, =
we
+      // keep track of and reuse loads we insert.
+      DenseMap<BasicBlock*, Value*> Loads;
       for (unsigned i =3D 0, e =3D PN->getNumIncomingValues(); i !=3D e; +=
+i)
         if (PN->getIncomingValue(i) =3D=3D &I) {
           Value *&V =3D Loads[PN->getIncomingBlock(i)];
@@ -81,9 +70,9 @@
   }
=20
=20
-  // Insert stores of the computed value into the stack slot.  We have to =
be
-  // careful is I is an invoke instruction though, because we can't insert=
 the
-  // store AFTER the terminator instruction.
+  // Insert stores of the computed value into the stack slot. We have to be
+  // careful if I is an invoke instruction, because we can't insert the st=
ore
+  // AFTER the terminator instruction.
   BasicBlock::iterator InsertPt;
   if (!isa<TerminatorInst>(I)) {
     InsertPt =3D &I;
@@ -97,18 +86,17 @@
     InsertPt =3D II.getNormalDest()->begin();
   }
=20
-  for (; isa<PHINode>(InsertPt); ++InsertPt)
-  /* empty */;   // Don't insert before any PHI nodes.
+  for (; isa<PHINode>(InsertPt) || isa<LandingPadInst>(InsertPt); ++Insert=
Pt)
+    /* empty */;   // Don't insert before PHI nodes or landingpad instrs.
+
   new StoreInst(&I, Slot, InsertPt);
-
   return Slot;
 }
=20
-
-/// DemotePHIToStack - This function takes a virtual register computed by =
a phi
-/// node and replaces it with a slot in the stack frame, allocated via all=
oca.
-/// The phi node is deleted and it returns the pointer to the alloca inser=
ted.
-AllocaInst* llvm::DemotePHIToStack(PHINode *P, Instruction *AllocaPoint) {
+/// DemotePHIToStack - This function takes a virtual register computed by =
a PHI
+/// node and replaces it with a slot in the stack frame allocated via allo=
ca.
+/// The PHI node is deleted. It returns the pointer to the alloca inserted.
+AllocaInst *llvm::DemotePHIToStack(PHINode *P, Instruction *AllocaPoint) {
   if (P->use_empty()) {
     P->eraseFromParent();
     return 0;
@@ -125,7 +113,7 @@
                           F->getEntryBlock().begin());
   }
=20
-  // Iterate over each operand, insert store in each predecessor.
+  // Iterate over each operand inserting a store in each predecessor.
   for (unsigned i =3D 0, e =3D P->getNumIncomingValues(); i < e; ++i) {
     if (InvokeInst *II =3D dyn_cast<InvokeInst>(P->getIncomingValue(i))) {
       assert(II->getParent() !=3D P->getIncomingBlock(i) &&
@@ -135,12 +123,11 @@
                   P->getIncomingBlock(i)->getTerminator());
   }
=20
-  // Insert load in place of the phi and replace all uses.
+  // Insert a load in place of the PHI and replace all uses.
   Value *V =3D new LoadInst(Slot, P->getName()+".reload", P);
   P->replaceAllUsesWith(V);
=20
-  // Delete phi.
+  // Delete PHI.
   P->eraseFromParent();
-
   return Slot;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/InlineFunction.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/InlineFunction.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/InlineFunction.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -10,13 +10,6 @@
 // This file implements inlining of a function into a call site, resolving
 // parameters and the return value as appropriate.
 //
-// The code in this file for handling inlines through invoke
-// instructions preserves semantics only under some assumptions about
-// the behavior of unwinders which correspond to gcc-style libUnwind
-// exception personality functions.  Eventually the IR will be
-// improved to make this unnecessary, but until then, this code is
-// marked [LIBUNWIND].
-//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Transforms/Utils/Cloning.h"
@@ -38,271 +31,52 @@
 #include "llvm/Support/IRBuilder.h"
 using namespace llvm;
=20
-bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI) {
-  return InlineFunction(CallSite(CI), IFI);
+bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI,
+                          bool InsertLifetime) {
+  return InlineFunction(CallSite(CI), IFI, InsertLifetime);
 }
-bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI) {
-  return InlineFunction(CallSite(II), IFI);
-}
-
-// FIXME: New EH - Remove the functions marked [LIBUNWIND] when new EH is
-// turned on.
-
-/// [LIBUNWIND] Look for an llvm.eh.exception call in the given block.
-static EHExceptionInst *findExceptionInBlock(BasicBlock *bb) {
-  for (BasicBlock::iterator i =3D bb->begin(), e =3D bb->end(); i !=3D e; =
i++) {
-    EHExceptionInst *exn =3D dyn_cast<EHExceptionInst>(i);
-    if (exn) return exn;
-  }
-
-  return 0;
-}
-
-/// [LIBUNWIND] Look for the 'best' llvm.eh.selector instruction for
-/// the given llvm.eh.exception call.
-static EHSelectorInst *findSelectorForException(EHExceptionInst *exn) {
-  BasicBlock *exnBlock =3D exn->getParent();
-
-  EHSelectorInst *outOfBlockSelector =3D 0;
-  for (Instruction::use_iterator
-         ui =3D exn->use_begin(), ue =3D exn->use_end(); ui !=3D ue; ++ui)=
 {
-    EHSelectorInst *sel =3D dyn_cast<EHSelectorInst>(*ui);
-    if (!sel) continue;
-
-    // Immediately accept an eh.selector in the same block as the
-    // excepton call.
-    if (sel->getParent() =3D=3D exnBlock) return sel;
-
-    // Otherwise, use the first selector we see.
-    if (!outOfBlockSelector) outOfBlockSelector =3D sel;
-  }
-
-  return outOfBlockSelector;
-}
-
-/// [LIBUNWIND] Find the (possibly absent) call to @llvm.eh.selector
-/// in the given landing pad.  In principle, llvm.eh.exception is
-/// required to be in the landing pad; in practice, SplitCriticalEdge
-/// can break that invariant, and then inlining can break it further.
-/// There's a real need for a reliable solution here, but until that
-/// happens, we have some fragile workarounds here.
-static EHSelectorInst *findSelectorForLandingPad(BasicBlock *lpad) {
-  // Look for an exception call in the actual landing pad.
-  EHExceptionInst *exn =3D findExceptionInBlock(lpad);
-  if (exn) return findSelectorForException(exn);
-
-  // Okay, if that failed, look for one in an obvious successor.  If
-  // we find one, we'll fix the IR by moving things back to the
-  // landing pad.
-
-  bool dominates =3D true; // does the lpad dominate the exn call
-  BasicBlock *nonDominated =3D 0; // if not, the first non-dominated block
-  BasicBlock *lastDominated =3D 0; // and the block which branched to it
-
-  BasicBlock *exnBlock =3D lpad;
-
-  // We need to protect against lpads that lead into infinite loops.
-  SmallPtrSet<BasicBlock*,4> visited;
-  visited.insert(exnBlock);
-
-  do {
-    // We're not going to apply this hack to anything more complicated
-    // than a series of unconditional branches, so if the block
-    // doesn't terminate in an unconditional branch, just fail.  More
-    // complicated cases can arise when, say, sinking a call into a
-    // split unwind edge and then inlining it; but that can do almost
-    // *anything* to the CFG, including leaving the selector
-    // completely unreachable.  The only way to fix that properly is
-    // to (1) prohibit transforms which move the exception or selector
-    // values away from the landing pad, e.g. by producing them with
-    // instructions that are pinned to an edge like a phi, or
-    // producing them with not-really-instructions, and (2) making
-    // transforms which split edges deal with that.
-    BranchInst *branch =3D dyn_cast<BranchInst>(&exnBlock->back());
-    if (!branch || branch->isConditional()) return 0;
-
-    BasicBlock *successor =3D branch->getSuccessor(0);
-
-    // Fail if we found an infinite loop.
-    if (!visited.insert(successor)) return 0;
-
-    // If the successor isn't dominated by exnBlock:
-    if (!successor->getSinglePredecessor()) {
-      // We don't want to have to deal with threading the exception
-      // through multiple levels of phi, so give up if we've already
-      // followed a non-dominating edge.
-      if (!dominates) return 0;
-
-      // Otherwise, remember this as a non-dominating edge.
-      dominates =3D false;
-      nonDominated =3D successor;
-      lastDominated =3D exnBlock;
-    }
-
-    exnBlock =3D successor;
-
-    // Can we stop here?
-    exn =3D findExceptionInBlock(exnBlock);
-  } while (!exn);
-
-  // Look for a selector call for the exception we found.
-  EHSelectorInst *selector =3D findSelectorForException(exn);
-  if (!selector) return 0;
-
-  // The easy case is when the landing pad still dominates the
-  // exception call, in which case we can just move both calls back to
-  // the landing pad.
-  if (dominates) {
-    selector->moveBefore(lpad->getFirstNonPHI());
-    exn->moveBefore(selector);
-    return selector;
-  }
-
-  // Otherwise, we have to split at the first non-dominating block.
-  // The CFG looks basically like this:
-  //    lpad:
-  //      phis_0
-  //      insnsAndBranches_1
-  //      br label %nonDominated
-  //    nonDominated:
-  //      phis_2
-  //      insns_3
-  //      %exn =3D call i8* @llvm.eh.exception()
-  //      insnsAndBranches_4
-  //      %selector =3D call @llvm.eh.selector(i8* %exn, ...
-  // We need to turn this into:
-  //    lpad:
-  //      phis_0
-  //      %exn0 =3D call i8* @llvm.eh.exception()
-  //      %selector0 =3D call @llvm.eh.selector(i8* %exn0, ...
-  //      insnsAndBranches_1
-  //      br label %split // from lastDominated
-  //    nonDominated:
-  //      phis_2 (without edge from lastDominated)
-  //      %exn1 =3D call i8* @llvm.eh.exception()
-  //      %selector1 =3D call i8* @llvm.eh.selector(i8* %exn1, ...
-  //      br label %split
-  //    split:
-  //      phis_2 (edge from lastDominated, edge from split)
-  //      %exn =3D phi ...
-  //      %selector =3D phi ...
-  //      insns_3
-  //      insnsAndBranches_4
-
-  assert(nonDominated);
-  assert(lastDominated);
-
-  // First, make clones of the intrinsics to go in lpad.
-  EHExceptionInst *lpadExn =3D cast<EHExceptionInst>(exn->clone());
-  EHSelectorInst *lpadSelector =3D cast<EHSelectorInst>(selector->clone());
-  lpadSelector->setArgOperand(0, lpadExn);
-  lpadSelector->insertBefore(lpad->getFirstNonPHI());
-  lpadExn->insertBefore(lpadSelector);
-
-  // Split the non-dominated block.
-  BasicBlock *split =3D
-    nonDominated->splitBasicBlock(nonDominated->getFirstNonPHI(),
-                                  nonDominated->getName() + ".lpad-fix");
-
-  // Redirect the last dominated branch there.
-  cast<BranchInst>(lastDominated->back()).setSuccessor(0, split);
-
-  // Move the existing intrinsics to the end of the old block.
-  selector->moveBefore(&nonDominated->back());
-  exn->moveBefore(selector);
-
-  Instruction *splitIP =3D &split->front();
-
-  // For all the phis in nonDominated, make a new phi in split to join
-  // that phi with the edge from lastDominated.
-  for (BasicBlock::iterator
-         i =3D nonDominated->begin(), e =3D nonDominated->end(); i !=3D e;=
 ++i) {
-    PHINode *phi =3D dyn_cast<PHINode>(i);
-    if (!phi) break;
-
-    PHINode *splitPhi =3D PHINode::Create(phi->getType(), 2, phi->getName(=
),
-                                        splitIP);
-    phi->replaceAllUsesWith(splitPhi);
-    splitPhi->addIncoming(phi, nonDominated);
-    splitPhi->addIncoming(phi->removeIncomingValue(lastDominated),
-                          lastDominated);
-  }
-
-  // Make new phis for the exception and selector.
-  PHINode *exnPhi =3D PHINode::Create(exn->getType(), 2, "", splitIP);
-  exn->replaceAllUsesWith(exnPhi);
-  selector->setArgOperand(0, exn); // except for this use
-  exnPhi->addIncoming(exn, nonDominated);
-  exnPhi->addIncoming(lpadExn, lastDominated);
-
-  PHINode *selectorPhi =3D PHINode::Create(selector->getType(), 2, "", spl=
itIP);
-  selector->replaceAllUsesWith(selectorPhi);
-  selectorPhi->addIncoming(selector, nonDominated);
-  selectorPhi->addIncoming(lpadSelector, lastDominated);
-
-  return lpadSelector;
+bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI,
+                          bool InsertLifetime) {
+  return InlineFunction(CallSite(II), IFI, InsertLifetime);
 }
=20
 namespace {
   /// A class for recording information about inlining through an invoke.
   class InvokeInliningInfo {
-    BasicBlock *OuterUnwindDest;
-    EHSelectorInst *OuterSelector;
-    BasicBlock *InnerUnwindDest;
-    PHINode *InnerExceptionPHI;
-    PHINode *InnerSelectorPHI;
-    SmallVector<Value*, 8> UnwindDestPHIValues;
-
-    // FIXME: New EH - These will replace the analogous ones above.
     BasicBlock *OuterResumeDest; //< Destination of the invoke's unwind.
     BasicBlock *InnerResumeDest; //< Destination for the callee's resume.
     LandingPadInst *CallerLPad;  //< LandingPadInst associated with the in=
voke.
     PHINode *InnerEHValuesPHI;   //< PHI for EH values from landingpad ins=
ts.
+    SmallVector<Value*, 8> UnwindDestPHIValues;
=20
   public:
     InvokeInliningInfo(InvokeInst *II)
-      : OuterUnwindDest(II->getUnwindDest()), OuterSelector(0),
-        InnerUnwindDest(0), InnerExceptionPHI(0), InnerSelectorPHI(0),
-        OuterResumeDest(II->getUnwindDest()), InnerResumeDest(0),
+      : OuterResumeDest(II->getUnwindDest()), InnerResumeDest(0),
         CallerLPad(0), InnerEHValuesPHI(0) {
       // If there are PHI nodes in the unwind destination block, we need t=
o keep
       // track of which values came into them from the invoke before remov=
ing
       // the edge from this block.
       llvm::BasicBlock *InvokeBB =3D II->getParent();
-      BasicBlock::iterator I =3D OuterUnwindDest->begin();
+      BasicBlock::iterator I =3D OuterResumeDest->begin();
       for (; isa<PHINode>(I); ++I) {
         // Save the value to use for this edge.
         PHINode *PHI =3D cast<PHINode>(I);
         UnwindDestPHIValues.push_back(PHI->getIncomingValueForBlock(Invoke=
BB));
       }
=20
-      // FIXME: With the new EH, this if/dyn_cast should be a 'cast'.
-      if (LandingPadInst *LPI =3D dyn_cast<LandingPadInst>(I)) {
-        CallerLPad =3D LPI;
-      }
+      CallerLPad =3D cast<LandingPadInst>(I);
     }
=20
-    /// The outer unwind destination is the target of unwind edges
-    /// introduced for calls within the inlined function.
-    BasicBlock *getOuterUnwindDest() const {
-      return OuterUnwindDest;
+    /// getOuterResumeDest - The outer unwind destination is the target of
+    /// unwind edges introduced for calls within the inlined function.
+    BasicBlock *getOuterResumeDest() const {
+      return OuterResumeDest;
     }
=20
-    EHSelectorInst *getOuterSelector() {
-      if (!OuterSelector)
-        OuterSelector =3D findSelectorForLandingPad(OuterUnwindDest);
-      return OuterSelector;
-    }
-
-    BasicBlock *getInnerUnwindDest();
-
-    // FIXME: New EH - Rename when new EH is turned on.
-    BasicBlock *getInnerUnwindDestNewEH();
+    BasicBlock *getInnerResumeDest();
=20
     LandingPadInst *getLandingPadInst() const { return CallerLPad; }
=20
-    bool forwardEHResume(CallInst *call, BasicBlock *src);
-
     /// forwardResume - Forward the 'resume' instruction to the caller's l=
anding
     /// pad block. When the landing pad block has only one predecessor, th=
is is
     /// a simple branch. When there is more than one predecessor, we need =
to
@@ -314,7 +88,7 @@
     /// destination block for the given basic block, using the values for =
the
     /// original invoke's source block.
     void addIncomingPHIValuesFor(BasicBlock *BB) const {
-      addIncomingPHIValuesForInto(BB, OuterUnwindDest);
+      addIncomingPHIValuesForInto(BB, OuterResumeDest);
     }
=20
     void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) co=
nst {
@@ -327,113 +101,8 @@
   };
 }
=20
-/// [LIBUNWIND] Get or create a target for the branch out of rewritten cal=
ls to
-/// llvm.eh.resume.
-BasicBlock *InvokeInliningInfo::getInnerUnwindDest() {
-  if (InnerUnwindDest) return InnerUnwindDest;
-
-  // Find and hoist the llvm.eh.exception and llvm.eh.selector calls
-  // in the outer landing pad to immediately following the phis.
-  EHSelectorInst *selector =3D getOuterSelector();
-  if (!selector) return 0;
-
-  // The call to llvm.eh.exception *must* be in the landing pad.
-  Instruction *exn =3D cast<Instruction>(selector->getArgOperand(0));
-  assert(exn->getParent() =3D=3D OuterUnwindDest);
-
-  // TODO: recognize when we've already done this, so that we don't
-  // get a linear number of these when inlining calls into lots of
-  // invokes with the same landing pad.
-
-  // Do the hoisting.
-  Instruction *splitPoint =3D exn->getParent()->getFirstNonPHI();
-  assert(splitPoint !=3D selector && "selector-on-exception dominance brok=
en!");
-  if (splitPoint =3D=3D exn) {
-    selector->removeFromParent();
-    selector->insertAfter(exn);
-    splitPoint =3D selector->getNextNode();
-  } else {
-    exn->moveBefore(splitPoint);
-    selector->moveBefore(splitPoint);
-  }
-
-  // Split the landing pad.
-  InnerUnwindDest =3D OuterUnwindDest->splitBasicBlock(splitPoint,
-                                        OuterUnwindDest->getName() + ".bod=
y");
-
-  // The number of incoming edges we expect to the inner landing pad.
-  const unsigned phiCapacity =3D 2;
-
-  // Create corresponding new phis for all the phis in the outer landing p=
ad.
-  BasicBlock::iterator insertPoint =3D InnerUnwindDest->begin();
-  BasicBlock::iterator I =3D OuterUnwindDest->begin();
-  for (unsigned i =3D 0, e =3D UnwindDestPHIValues.size(); i !=3D e; ++i, =
++I) {
-    PHINode *outerPhi =3D cast<PHINode>(I);
-    PHINode *innerPhi =3D PHINode::Create(outerPhi->getType(), phiCapacity,
-                                        outerPhi->getName() + ".lpad-body",
-                                        insertPoint);
-    outerPhi->replaceAllUsesWith(innerPhi);
-    innerPhi->addIncoming(outerPhi, OuterUnwindDest);
-  }
-
-  // Create a phi for the exception value...
-  InnerExceptionPHI =3D PHINode::Create(exn->getType(), phiCapacity,
-                                      "exn.lpad-body", insertPoint);
-  exn->replaceAllUsesWith(InnerExceptionPHI);
-  selector->setArgOperand(0, exn); // restore this use
-  InnerExceptionPHI->addIncoming(exn, OuterUnwindDest);
-
-  // ...and the selector.
-  InnerSelectorPHI =3D PHINode::Create(selector->getType(), phiCapacity,
-                                     "selector.lpad-body", insertPoint);
-  selector->replaceAllUsesWith(InnerSelectorPHI);
-  InnerSelectorPHI->addIncoming(selector, OuterUnwindDest);
-
-  // All done.
-  return InnerUnwindDest;
-}
-
-/// [LIBUNWIND] Try to forward the given call, which logically occurs
-/// at the end of the given block, as a branch to the inner unwind
-/// block.  Returns true if the call was forwarded.
-bool InvokeInliningInfo::forwardEHResume(CallInst *call, BasicBlock *src) {
-  // First, check whether this is a call to the intrinsic.
-  Function *fn =3D dyn_cast<Function>(call->getCalledValue());
-  if (!fn || fn->getName() !=3D "llvm.eh.resume")
-    return false;
- =20
-  // At this point, we need to return true on all paths, because
-  // otherwise we'll construct an invoke of the intrinsic, which is
-  // not well-formed.
-
-  // Try to find or make an inner unwind dest, which will fail if we
-  // can't find a selector call for the outer unwind dest.
-  BasicBlock *dest =3D getInnerUnwindDest();
-  bool hasSelector =3D (dest !=3D 0);
-
-  // If we failed, just use the outer unwind dest, dropping the
-  // exception and selector on the floor.
-  if (!hasSelector)
-    dest =3D OuterUnwindDest;
-
-  // Make a branch.
-  BranchInst::Create(dest, src);
-
-  // Update the phis in the destination.  They were inserted in an
-  // order which makes this work.
-  addIncomingPHIValuesForInto(src, dest);
-
-  if (hasSelector) {
-    InnerExceptionPHI->addIncoming(call->getArgOperand(0), src);
-    InnerSelectorPHI->addIncoming(call->getArgOperand(1), src);
-  }
-
-  return true;
-}
-
-/// Get or create a target for the branch from ResumeInsts.
-BasicBlock *InvokeInliningInfo::getInnerUnwindDestNewEH() {
-  // FIXME: New EH - rename this function when new EH is turned on.
+/// getInnerResumeDest - Get or create a target for the branch from Resume=
Insts.
+BasicBlock *InvokeInliningInfo::getInnerResumeDest() {
   if (InnerResumeDest) return InnerResumeDest;
=20
   // Split the landing pad.
@@ -472,7 +141,7 @@
 /// branch. When there is more than one predecessor, we need to split the
 /// landing pad block after the landingpad instruction and jump to there.
 void InvokeInliningInfo::forwardResume(ResumeInst *RI) {
-  BasicBlock *Dest =3D getInnerUnwindDestNewEH();
+  BasicBlock *Dest =3D getInnerResumeDest();
   BasicBlock *Src =3D RI->getParent();
=20
   BranchInst::Create(Dest, Src);
@@ -485,14 +154,6 @@
   RI->eraseFromParent();
 }
=20
-/// [LIBUNWIND] Check whether this selector is "only cleanups":
-///   call i32 @llvm.eh.selector(blah, blah, i32 0)
-static bool isCleanupOnlySelector(EHSelectorInst *selector) {
-  if (selector->getNumArgOperands() !=3D 3) return false;
-  ConstantInt *val =3D dyn_cast<ConstantInt>(selector->getArgOperand(2));
-  return (val && val->isZero());
-}
-
 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block =
into
 /// an invoke, we have to turn all of the calls that can throw into
 /// invokes.  This function analyze BB to see if there are any calls, and =
if so,
@@ -507,77 +168,34 @@
   for (BasicBlock::iterator BBI =3D BB->begin(), E =3D BB->end(); BBI !=3D=
 E; ) {
     Instruction *I =3D BBI++;
=20
-    if (LPI) // FIXME: New EH - This won't be NULL in the new EH.
-      if (LandingPadInst *L =3D dyn_cast<LandingPadInst>(I)) {
-        unsigned NumClauses =3D LPI->getNumClauses();
-        L->reserveClauses(NumClauses);
-        for (unsigned i =3D 0; i !=3D NumClauses; ++i)
-          L->addClause(LPI->getClause(i));
-      }
+    if (LandingPadInst *L =3D dyn_cast<LandingPadInst>(I)) {
+      unsigned NumClauses =3D LPI->getNumClauses();
+      L->reserveClauses(NumClauses);
+      for (unsigned i =3D 0; i !=3D NumClauses; ++i)
+        L->addClause(LPI->getClause(i));
+    }
=20
     // We only need to check for function calls: inlined invoke
     // instructions require no special handling.
     CallInst *CI =3D dyn_cast<CallInst>(I);
-    if (CI =3D=3D 0) continue;
=20
-    // LIBUNWIND: merge selector instructions.
-    if (EHSelectorInst *Inner =3D dyn_cast<EHSelectorInst>(CI)) {
-      EHSelectorInst *Outer =3D Invoke.getOuterSelector();
-      if (!Outer) continue;
+    // If this call cannot unwind, don't convert it to an invoke.
+    if (!CI || CI->doesNotThrow())
+      continue;
=20
-      bool innerIsOnlyCleanup =3D isCleanupOnlySelector(Inner);
-      bool outerIsOnlyCleanup =3D isCleanupOnlySelector(Outer);
-
-      // If both selectors contain only cleanups, we don't need to do
-      // anything.  TODO: this is really just a very specific instance
-      // of a much more general optimization.
-      if (innerIsOnlyCleanup && outerIsOnlyCleanup) continue;
-
-      // Otherwise, we just append the outer selector to the inner selecto=
r.
-      SmallVector<Value*, 16> NewSelector;
-      for (unsigned i =3D 0, e =3D Inner->getNumArgOperands(); i !=3D e; +=
+i)
-        NewSelector.push_back(Inner->getArgOperand(i));
-      for (unsigned i =3D 2, e =3D Outer->getNumArgOperands(); i !=3D e; +=
+i)
-        NewSelector.push_back(Outer->getArgOperand(i));
-
-      CallInst *NewInner =3D
-        IRBuilder<>(Inner).CreateCall(Inner->getCalledValue(), NewSelector=
);
-      // No need to copy attributes, calling convention, etc.
-      NewInner->takeName(Inner);
-      Inner->replaceAllUsesWith(NewInner);
-      Inner->eraseFromParent();
-      continue;
-    }
-   =20
-    // If this call cannot unwind, don't convert it to an invoke.
-    if (CI->doesNotThrow())
-      continue;
-   =20
-    // Convert this function call into an invoke instruction.
-    // First, split the basic block.
+    // Convert this function call into an invoke instruction.  First, spli=
t the
+    // basic block.
     BasicBlock *Split =3D BB->splitBasicBlock(CI, CI->getName()+".noexc");
=20
     // Delete the unconditional branch inserted by splitBasicBlock
     BB->getInstList().pop_back();
=20
-    // LIBUNWIND: If this is a call to @llvm.eh.resume, just branch
-    // directly to the new landing pad.
-    if (Invoke.forwardEHResume(CI, BB)) {
-      // TODO: 'Split' is now unreachable; clean it up.
-
-      // We want to leave the original call intact so that the call
-      // graph and other structures won't get misled.  We also have to
-      // avoid processing the next block, or we'll iterate here forever.
-      return true;
-    }
-
-    // Otherwise, create the new invoke instruction.
+    // Create the new invoke instruction.
     ImmutableCallSite CS(CI);
     SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
-    InvokeInst *II =3D
-      InvokeInst::Create(CI->getCalledValue(), Split,
-                         Invoke.getOuterUnwindDest(),
-                         InvokeArgs, CI->getName(), BB);
+    InvokeInst *II =3D InvokeInst::Create(CI->getCalledValue(), Split,
+                                        Invoke.getOuterResumeDest(),
+                                        InvokeArgs, CI->getName(), BB);
     II->setCallingConv(CI->getCallingConv());
     II->setAttributes(CI->getAttributes());
    =20
@@ -585,21 +203,20 @@
     // updates the CallGraph if present, because it uses a WeakVH.
     CI->replaceAllUsesWith(II);
=20
-    Split->getInstList().pop_front();  // Delete the original call
+    // Delete the original call
+    Split->getInstList().pop_front();
=20
-    // Update any PHI nodes in the exceptional block to indicate that
-    // there is now a new entry in them.
+    // Update any PHI nodes in the exceptional block to indicate that ther=
e is
+    // now a new entry in them.
     Invoke.addIncomingPHIValuesFor(BB);
     return false;
   }
=20
   return false;
 }
- =20
=20
 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert=
 calls
-/// in the body of the inlined function into invokes and turn unwind
-/// instructions into branches to the invoke unwind dest.
+/// in the body of the inlined function into invokes.
 ///
 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
 /// block of the inlined code (the last block is the end of the function),
@@ -614,7 +231,7 @@
   // start of the inlined code to its end, checking for stuff we need to
   // rewrite.  If the code doesn't have calls or unwinds, we know there is
   // nothing to rewrite.
-  if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
+  if (!InlinedCodeInfo.ContainsCalls) {
     // Now that everything is happy, we have one final detail.  The PHI no=
des in
     // the exception destination block still have entries due to the origi=
nal
     // invoke instruction.  Eliminate these entries (which might even dele=
te the
@@ -628,30 +245,13 @@
   for (Function::iterator BB =3D FirstNewBlock, E =3D Caller->end(); BB !=
=3D E; ++BB){
     if (InlinedCodeInfo.ContainsCalls)
       if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
-        // Honor a request to skip the next block.  We don't need to
-        // consider UnwindInsts in this case either.
+        // Honor a request to skip the next block.
         ++BB;
         continue;
       }
=20
-    if (UnwindInst *UI =3D dyn_cast<UnwindInst>(BB->getTerminator())) {
-      // An UnwindInst requires special handling when it gets inlined into=
 an
-      // invoke site.  Once this happens, we know that the unwind would ca=
use
-      // a control transfer to the invoke exception destination, so we can
-      // transform it into a direct branch to the exception destination.
-      BranchInst::Create(InvokeDest, UI);
-
-      // Delete the unwind instruction!
-      UI->eraseFromParent();
-
-      // Update any PHI nodes in the exceptional block to indicate that
-      // there is now a new entry in them.
-      Invoke.addIncomingPHIValuesFor(BB);
-    }
-
-    if (ResumeInst *RI =3D dyn_cast<ResumeInst>(BB->getTerminator())) {
+    if (ResumeInst *RI =3D dyn_cast<ResumeInst>(BB->getTerminator()))
       Invoke.forwardResume(RI);
-    }
   }
=20
   // Now that everything is happy, we have one final detail.  The PHI node=
s in
@@ -836,8 +436,8 @@
   return false;
 }
=20
-/// updateInlinedAtInfo - Helper function used by fixupLineNumbers to recu=
rsively
-/// update InlinedAtEntry of a DebugLoc.
+/// updateInlinedAtInfo - Helper function used by fixupLineNumbers to
+/// recursively update InlinedAtEntry of a DebugLoc.
 static DebugLoc updateInlinedAtInfo(const DebugLoc &DL,=20
                                     const DebugLoc &InlinedAtDL,
                                     LLVMContext &Ctx) {
@@ -847,16 +447,15 @@
     return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
                          NewInlinedAtDL.getAsMDNode(Ctx));
   }
-                                            =20
+
   return DebugLoc::get(DL.getLine(), DL.getCol(), DL.getScope(Ctx),
                        InlinedAtDL.getAsMDNode(Ctx));
 }
=20
-
 /// fixupLineNumbers - Update inlined instructions' line numbers to=20
 /// to encode location where these instructions are inlined.
 static void fixupLineNumbers(Function *Fn, Function::iterator FI,
-                              Instruction *TheCall) {
+                             Instruction *TheCall) {
   DebugLoc TheCallDL =3D TheCall->getDebugLoc();
   if (TheCallDL.isUnknown())
     return;
@@ -878,18 +477,18 @@
   }
 }
=20
-// InlineFunction - This function inlines the called function into the bas=
ic
-// block of the caller.  This returns false if it is not possible to inlin=
e this
-// call.  The program is still in a well defined state if this occurs thou=
gh.
-//
-// Note that this only does one level of inlining.  For example, if the
-// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C=
' now
-// exists in the instruction stream.  Similarly this will inline a recursi=
ve
-// function by one level.
-//
-bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
+/// InlineFunction - This function inlines the called function into the ba=
sic
+/// block of the caller.  This returns false if it is not possible to inli=
ne
+/// this call.  The program is still in a well defined state if this occurs
+/// though.
+///
+/// Note that this only does one level of inlining.  For example, if the
+/// instruction 'call B' is inlined, and 'B' calls 'C', then the call to '=
C' now
+/// exists in the instruction stream.  Similarly this will inline a recurs=
ive
+/// function by one level.
+bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
+                          bool InsertLifetime) {
   Instruction *TheCall =3D CS.getInstruction();
-  LLVMContext &Context =3D TheCall->getContext();
   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
          "Instruction not in function!");
=20
@@ -924,43 +523,40 @@
       return false;
   }
=20
+  // Get the personality function from the callee if it contains a landing=
 pad.
+  Value *CalleePersonality =3D 0;
+  for (Function::const_iterator I =3D CalledFunc->begin(), E =3D CalledFun=
c->end();
+       I !=3D E; ++I)
+    if (const InvokeInst *II =3D dyn_cast<InvokeInst>(I->getTerminator()))=
 {
+      const BasicBlock *BB =3D II->getUnwindDest();
+      const LandingPadInst *LP =3D BB->getLandingPadInst();
+      CalleePersonality =3D LP->getPersonalityFn();
+      break;
+    }
+
   // Find the personality function used by the landing pads of the caller.=
 If it
   // exists, then check to see that it matches the personality function us=
ed in
   // the callee.
-  for (Function::const_iterator
-         I =3D Caller->begin(), E =3D Caller->end(); I !=3D E; ++I)
-    if (const InvokeInst *II =3D dyn_cast<InvokeInst>(I->getTerminator()))=
 {
-      const BasicBlock *BB =3D II->getUnwindDest();
-      // FIXME: This 'isa' here should become go away once the new EH syst=
em is
-      // in place.
-      if (!isa<LandingPadInst>(BB->getFirstNonPHI()))
-        continue;
-      const LandingPadInst *LP =3D cast<LandingPadInst>(BB->getFirstNonPHI=
());
-      const Value *CallerPersFn =3D LP->getPersonalityFn();
+  if (CalleePersonality) {
+    for (Function::const_iterator I =3D Caller->begin(), E =3D Caller->end=
();
+         I !=3D E; ++I)
+      if (const InvokeInst *II =3D dyn_cast<InvokeInst>(I->getTerminator()=
)) {
+        const BasicBlock *BB =3D II->getUnwindDest();
+        const LandingPadInst *LP =3D BB->getLandingPadInst();
=20
-      // If the personality functions match, then we can perform the
-      // inlining. Otherwise, we can't inline.
-      // TODO: This isn't 100% true. Some personality functions are proper
-      //       supersets of others and can be used in place of the other.
-      for (Function::const_iterator
-             I =3D CalledFunc->begin(), E =3D CalledFunc->end(); I !=3D E;=
 ++I)
-        if (const InvokeInst *II =3D dyn_cast<InvokeInst>(I->getTerminator=
())) {
-          const BasicBlock *BB =3D II->getUnwindDest();
-          // FIXME: This 'if/dyn_cast' here should become a normal 'cast' =
once
-          // the new EH system is in place.
-          if (const LandingPadInst *LP =3D
-              dyn_cast<LandingPadInst>(BB->getFirstNonPHI()))
-            if (CallerPersFn !=3D LP->getPersonalityFn())
-              return false;
-          break;
-        }
+        // If the personality functions match, then we can perform the
+        // inlining. Otherwise, we can't inline.
+        // TODO: This isn't 100% true. Some personality functions are prop=
er
+        //       supersets of others and can be used in place of the other.
+        if (LP->getPersonalityFn() !=3D CalleePersonality)
+          return false;
=20
-      break;
-    }
+        break;
+      }
+  }
=20
   // Get an iterator to the last basic block in the function, which will h=
ave
   // the new function inlined after it.
-  //
   Function::iterator LastBlock =3D &Caller->back();
=20
   // Make sure to capture all of the return instructions from the cloned
@@ -987,7 +583,7 @@
       // by them explicit.  However, we don't do this if the callee is rea=
donly
       // or readnone, because the copy would be unneeded: the callee doesn=
't
       // modify the struct.
-      if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
+      if (CS.isByValArgument(ArgNo)) {
         ActualArg =3D HandleByValArgument(ActualArg, TheCall, CalledFunc, =
IFI,
                                         CalledFunc->getParamAlignment(ArgN=
o+1));
 =20
@@ -1023,7 +619,6 @@
   // block for the callee, move them to the entry block of the caller.  Fi=
rst
   // calculate which instruction they should be inserted before.  We inser=
t the
   // instructions at the end of the current alloca list.
-  //
   {
     BasicBlock::iterator InsertPoint =3D Caller->begin()->begin();
     for (BasicBlock::iterator I =3D FirstNewBlock->begin(),
@@ -1063,7 +658,7 @@
=20
   // Leave lifetime markers for the static alloca's, scoping them to the
   // function we just inlined.
-  if (!IFI.StaticAllocas.empty()) {
+  if (InsertLifetime && !IFI.StaticAllocas.empty()) {
     IRBuilder<> builder(FirstNewBlock->begin());
     for (unsigned ai =3D 0, ae =3D IFI.StaticAllocas.size(); ai !=3D ae; +=
+ai) {
       AllocaInst *AI =3D IFI.StaticAllocas[ai];
@@ -1098,20 +693,6 @@
     for (unsigned i =3D 0, e =3D Returns.size(); i !=3D e; ++i) {
       IRBuilder<>(Returns[i]).CreateCall(StackRestore, SavedPtr);
     }
-
-    // Count the number of StackRestore calls we insert.
-    unsigned NumStackRestores =3D Returns.size();
-
-    // If we are inlining an invoke instruction, insert restores before ea=
ch
-    // unwind.  These unwinds will be rewritten into branches later.
-    if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
-      for (Function::iterator BB =3D FirstNewBlock, E =3D Caller->end();
-           BB !=3D E; ++BB)
-        if (UnwindInst *UI =3D dyn_cast<UnwindInst>(BB->getTerminator())) {
-          IRBuilder<>(UI).CreateCall(StackRestore, SavedPtr);
-          ++NumStackRestores;
-        }
-    }
   }
=20
   // If we are inlining tail call instruction through a call site that isn=
't
@@ -1131,21 +712,8 @@
         }
   }
=20
-  // If we are inlining through a 'nounwind' call site then any inlined 'u=
nwind'
-  // instructions are unreachable.
-  if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
-    for (Function::iterator BB =3D FirstNewBlock, E =3D Caller->end();
-         BB !=3D E; ++BB) {
-      TerminatorInst *Term =3D BB->getTerminator();
-      if (isa<UnwindInst>(Term)) {
-        new UnreachableInst(Context, Term);
-        BB->getInstList().erase(Term);
-      }
-    }
-
   // If we are inlining for an invoke instruction, we must make sure to re=
write
-  // any inlined 'unwind' instructions into branches to the invoke excepti=
on
-  // destination, and call instructions into invoke instructions.
+  // any call instructions into invoke instructions.
   if (InvokeInst *II =3D dyn_cast<InvokeInst>(TheCall))
     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
=20
@@ -1308,11 +876,12 @@
   // If we inserted a phi node, check to see if it has a single value (e.g=
. all
   // the entries are the same or undef).  If so, remove the PHI so it does=
n't
   // block other optimizations.
-  if (PHI)
+  if (PHI) {
     if (Value *V =3D SimplifyInstruction(PHI, IFI.TD)) {
       PHI->replaceAllUsesWith(V);
       PHI->eraseFromParent();
     }
+  }
=20
   return true;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/Local.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/Local.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/Local.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -28,6 +28,7 @@
 #include "llvm/Analysis/DIBuilder.h"
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/InstructionSimplify.h"
+#include "llvm/Analysis/MemoryBuiltins.h"
 #include "llvm/Analysis/ProfileInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Target/TargetData.h"
@@ -105,33 +106,32 @@
     // If we are switching on a constant, we can convert the switch into a
     // single branch instruction!
     ConstantInt *CI =3D dyn_cast<ConstantInt>(SI->getCondition());
-    BasicBlock *TheOnlyDest =3D SI->getSuccessor(0);  // The default dest
+    BasicBlock *TheOnlyDest =3D SI->getDefaultDest();
     BasicBlock *DefaultDest =3D TheOnlyDest;
-    assert(TheOnlyDest =3D=3D SI->getDefaultDest() &&
-           "Default destination is not successor #0?");
=20
     // Figure out which case it goes to.
-    for (unsigned i =3D 1, e =3D SI->getNumSuccessors(); i !=3D e; ++i) {
+    for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end();
+         i !=3D e; ++i) {
       // Found case matching a constant operand?
-      if (SI->getSuccessorValue(i) =3D=3D CI) {
-        TheOnlyDest =3D SI->getSuccessor(i);
+      if (i.getCaseValue() =3D=3D CI) {
+        TheOnlyDest =3D i.getCaseSuccessor();
         break;
       }
=20
       // Check to see if this branch is going to the same place as the def=
ault
       // dest.  If so, eliminate it as an explicit compare.
-      if (SI->getSuccessor(i) =3D=3D DefaultDest) {
+      if (i.getCaseSuccessor() =3D=3D DefaultDest) {
         // Remove this entry.
         DefaultDest->removePredecessor(SI->getParent());
         SI->removeCase(i);
-        --i; --e;  // Don't skip an entry...
+        --i; --e;
         continue;
       }
=20
       // Otherwise, check to see if the switch only branches to one destin=
ation.
       // We do this by reseting "TheOnlyDest" to null when we find two non=
-equal
       // destinations.
-      if (SI->getSuccessor(i) !=3D TheOnlyDest) TheOnlyDest =3D 0;
+      if (i.getCaseSuccessor() !=3D TheOnlyDest) TheOnlyDest =3D 0;
     }
=20
     if (CI && !TheOnlyDest) {
@@ -165,14 +165,16 @@
       return true;
     }
    =20
-    if (SI->getNumSuccessors() =3D=3D 2) {
+    if (SI->getNumCases() =3D=3D 1) {
       // Otherwise, we can fold this switch into a conditional branch
       // instruction if it has only one non-default destination.
+      SwitchInst::CaseIt FirstCase =3D SI->case_begin();
       Value *Cond =3D Builder.CreateICmpEQ(SI->getCondition(),
-                                         SI->getSuccessorValue(1), "cond");
+          FirstCase.getCaseValue(), "cond");
=20
       // Insert the new branch.
-      Builder.CreateCondBr(Cond, SI->getSuccessor(1), SI->getSuccessor(0));
+      Builder.CreateCondBr(Cond, FirstCase.getCaseSuccessor(),
+                           SI->getDefaultDest());
=20
       // Delete the old switch.
       SI->eraseFromParent();
@@ -257,6 +259,13 @@
         II->getIntrinsicID() =3D=3D Intrinsic::lifetime_end)
       return isa<UndefValue>(II->getArgOperand(1));
   }
+
+  if (extractMallocCall(I)) return true;
+
+  if (CallInst *CI =3D isFreeCall(I))
+    if (Constant *C =3D dyn_cast<Constant>(CI->getArgOperand(0)))
+      return C->isNullValue() || isa<UndefValue>(C);
+
   return false;
 }
=20
@@ -346,22 +355,27 @@
 /// instructions in other blocks as well in this block.
 bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *T=
D) {
   bool MadeChange =3D false;
-  for (BasicBlock::iterator BI =3D BB->begin(), E =3D BB->end(); BI !=3D E=
; ) {
+
+#ifndef NDEBUG
+  // In debug builds, ensure that the terminator of the block is never rep=
laced
+  // or deleted by these simplifications. The idea of simplification is th=
at it
+  // cannot introduce new instructions, and there is no way to replace the
+  // terminator of a block without introducing a new instruction.
+  AssertingVH<Instruction> TerminatorVH(--BB->end());
+#endif
+
+  for (BasicBlock::iterator BI =3D BB->begin(), E =3D --BB->end(); BI !=3D=
 E; ) {
+    assert(!BI->isTerminator());
     Instruction *Inst =3D BI++;
-   =20
-    if (Value *V =3D SimplifyInstruction(Inst, TD)) {
-      WeakVH BIHandle(BI);
-      ReplaceAndSimplifyAllUses(Inst, V, TD);
+
+    WeakVH BIHandle(BI);
+    if (recursivelySimplifyInstruction(Inst, TD)) {
       MadeChange =3D true;
       if (BIHandle !=3D BI)
         BI =3D BB->begin();
       continue;
     }
=20
-    if (Inst->isTerminator())
-      break;
-
-    WeakVH BIHandle(BI);
     MadeChange |=3D RecursivelyDeleteTriviallyDeadInstructions(Inst);
     if (BIHandle !=3D BI)
       BI =3D BB->begin();
@@ -399,17 +413,11 @@
   WeakVH PhiIt =3D &BB->front();
   while (PHINode *PN =3D dyn_cast<PHINode>(PhiIt)) {
     PhiIt =3D &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
+    Value *OldPhiIt =3D PhiIt;
=20
-    Value *PNV =3D SimplifyInstruction(PN, TD);
-    if (PNV =3D=3D 0) continue;
+    if (!recursivelySimplifyInstruction(PN, TD))
+      continue;
=20
-    // If we're able to simplify the phi to a single value, substitute the=
 new
-    // value into all of its uses.
-    assert(PNV !=3D PN && "SimplifyInstruction broken!");
-   =20
-    Value *OldPhiIt =3D PhiIt;
-    ReplaceAndSimplifyAllUses(PN, PNV, TD);
-   =20
     // If recursive simplification ended up deleting the next PHI node we =
would
     // iterate to, then our iterator is invalid, restart scanning from the=
 top
     // of the block.
@@ -486,22 +494,8 @@
   if (Succ->getSinglePredecessor()) return true;
=20
   // Make a list of the predecessors of BB
-  typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
-  BlockSet BBPreds(pred_begin(BB), pred_end(BB));
+  SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
=20
-  // Use that list to make another list of common predecessors of BB and S=
ucc
-  BlockSet CommonPreds;
-  for (pred_iterator PI =3D pred_begin(Succ), PE =3D pred_end(Succ);
-       PI !=3D PE; ++PI) {
-    BasicBlock *P =3D *PI;
-    if (BBPreds.count(P))
-      CommonPreds.insert(P);
-  }
-
-  // Shortcut, if there are no common predecessors, merging is always safe
-  if (CommonPreds.empty())
-    return true;
- =20
   // Look at all the phi nodes in Succ, to see if they present a conflict =
when
   // merging these blocks
   for (BasicBlock::iterator I =3D Succ->begin(); isa<PHINode>(I); ++I) {
@@ -512,28 +506,28 @@
     // merge the phi nodes and then the blocks can still be merged
     PHINode *BBPN =3D dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
     if (BBPN && BBPN->getParent() =3D=3D BB) {
-      for (BlockSet::iterator PI =3D CommonPreds.begin(), PE =3D CommonPre=
ds.end();
-            PI !=3D PE; PI++) {
-        if (BBPN->getIncomingValueForBlock(*PI)=20
-              !=3D PN->getIncomingValueForBlock(*PI)) {
+      for (unsigned PI =3D 0, PE =3D PN->getNumIncomingValues(); PI !=3D P=
E; ++PI) {
+        BasicBlock *IBB =3D PN->getIncomingBlock(PI);
+        if (BBPreds.count(IBB) &&
+            BBPN->getIncomingValueForBlock(IBB) !=3D PN->getIncomingValue(=
PI)) {
           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in=
 "=20
                 << Succ->getName() << " is conflicting with "=20
                 << BBPN->getName() << " with regard to common predecessor "
-                << (*PI)->getName() << "\n");
+                << IBB->getName() << "\n");
           return false;
         }
       }
     } else {
       Value* Val =3D PN->getIncomingValueForBlock(BB);
-      for (BlockSet::iterator PI =3D CommonPreds.begin(), PE =3D CommonPre=
ds.end();
-            PI !=3D PE; PI++) {
+      for (unsigned PI =3D 0, PE =3D PN->getNumIncomingValues(); PI !=3D P=
E; ++PI) {
         // See if the incoming value for the common predecessor is equal t=
o the
         // one for BB, in which case this phi node will not prevent the me=
rging
         // of the block.
-        if (Val !=3D PN->getIncomingValueForBlock(*PI)) {
+        BasicBlock *IBB =3D PN->getIncomingBlock(PI);
+        if (BBPreds.count(IBB) && Val !=3D PN->getIncomingValue(PI)) {
           DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in=
 "=20
                 << Succ->getName() << " is conflicting with regard to comm=
on "
-                << "predecessor " << (*PI)->getName() << "\n");
+                << "predecessor " << IBB->getName() << "\n");
           return false;
         }
       }
@@ -740,6 +734,10 @@
     // If there is a large requested alignment and we can, bump up the ali=
gnment
     // of the global.
     if (GV->isDeclaration()) return Align;
+    // If the memory we set aside for the global may not be the memory use=
d by
+    // the final program then it is impossible for us to reliably enforce =
the
+    // preferred alignment.
+    if (GV->isWeakForLinker()) return Align;
    =20
     if (GV->getAlignment() >=3D PrefAlign)
       return GV->getAlignment();
@@ -764,9 +762,8 @@
   assert(V->getType()->isPointerTy() &&
          "getOrEnforceKnownAlignment expects a pointer!");
   unsigned BitWidth =3D TD ? TD->getPointerSizeInBits() : 64;
-  APInt Mask =3D APInt::getAllOnesValue(BitWidth);
   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
-  ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
+  ComputeMaskedBits(V, KnownZero, KnownOne, TD);
   unsigned TrailZ =3D KnownZero.countTrailingOnes();
  =20
   // Avoid trouble with rediculously large TrailZ values, such as
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/LoopSimplify.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/LoopSimplify.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/LoopSimplify.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -99,7 +99,8 @@
     bool ProcessLoop(Loop *L, LPPassManager &LPM);
     BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
     BasicBlock *InsertPreheaderForLoop(Loop *L);
-    Loop *SeparateNestedLoop(Loop *L, LPPassManager &LPM);
+    Loop *SeparateNestedLoop(Loop *L, LPPassManager &LPM,
+                             BasicBlock *Preheader);
     BasicBlock *InsertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader);
     void PlaceSplitBlockCarefully(BasicBlock *NewBB,
                                   SmallVectorImpl<BasicBlock*> &SplitPreds,
@@ -240,7 +241,7 @@
     // this for loops with a giant number of backedges, just factor them i=
nto a
     // common backedge instead.
     if (L->getNumBackEdges() < 8) {
-      if (SeparateNestedLoop(L, LPM)) {
+      if (SeparateNestedLoop(L, LPM, Preheader)) {
         ++NumNested;
         // This is a big restructuring change, reprocess the whole loop.
         Changed =3D true;
@@ -265,7 +266,7 @@
   PHINode *PN;
   for (BasicBlock::iterator I =3D L->getHeader()->begin();
        (PN =3D dyn_cast<PHINode>(I++)); )
-    if (Value *V =3D SimplifyInstruction(PN, 0, DT)) {
+    if (Value *V =3D SimplifyInstruction(PN, 0, 0, DT)) {
       if (AA) AA->deleteValue(PN);
       if (SE) SE->forgetValue(PN);
       PN->replaceAllUsesWith(V);
@@ -379,19 +380,27 @@
   }
=20
   // Split out the loop pre-header.
-  BasicBlock *NewBB =3D
-    SplitBlockPredecessors(Header, &OutsideBlocks[0], OutsideBlocks.size(),
-                           ".preheader", this);
+  BasicBlock *PreheaderBB;
+  if (!Header->isLandingPad()) {
+    PreheaderBB =3D SplitBlockPredecessors(Header, OutsideBlocks, ".prehea=
der",
+                                         this);
+  } else {
+    SmallVector<BasicBlock*, 2> NewBBs;
+    SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader",
+                                ".split-lp", this, NewBBs);
+    PreheaderBB =3D NewBBs[0];
+  }
=20
-  NewBB->getTerminator()->setDebugLoc(Header->getFirstNonPHI()->getDebugLo=
c());
-  DEBUG(dbgs() << "LoopSimplify: Creating pre-header " << NewBB->getName()
-               << "\n");
+  PreheaderBB->getTerminator()->setDebugLoc(
+                                      Header->getFirstNonPHI()->getDebugLo=
c());
+  DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
+               << PreheaderBB->getName() << "\n");
=20
   // Make sure that NewBB is put someplace intelligent, which doesn't mess=
 up
   // code layout too horribly.
-  PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
+  PlaceSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
=20
-  return NewBB;
+  return PreheaderBB;
 }
=20
 /// RewriteLoopExitBlock - Ensure that the loop preheader dominates all ex=
it
@@ -420,9 +429,7 @@
                                 this, NewBBs);
     NewExitBB =3D NewBBs[0];
   } else {
-    NewExitBB =3D SplitBlockPredecessors(Exit, &LoopBlocks[0],
-                                       LoopBlocks.size(), ".loopexit",
-                                       this);
+    NewExitBB =3D SplitBlockPredecessors(Exit, LoopBlocks, ".loopexit", th=
is);
   }
=20
   DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
@@ -456,7 +463,7 @@
   for (BasicBlock::iterator I =3D L->getHeader()->begin(); isa<PHINode>(I)=
; ) {
     PHINode *PN =3D cast<PHINode>(I);
     ++I;
-    if (Value *V =3D SimplifyInstruction(PN, 0, DT)) {
+    if (Value *V =3D SimplifyInstruction(PN, 0, 0, DT)) {
       // This is a degenerate PHI already, don't modify it!
       PN->replaceAllUsesWith(V);
       if (AA) AA->deleteValue(PN);
@@ -529,7 +536,16 @@
 /// If we are able to separate out a loop, return the new outer loop that =
was
 /// created.
 ///
-Loop *LoopSimplify::SeparateNestedLoop(Loop *L, LPPassManager &LPM) {
+Loop *LoopSimplify::SeparateNestedLoop(Loop *L, LPPassManager &LPM,
+                                       BasicBlock *Preheader) {
+  // Don't try to separate loops without a preheader.
+  if (!Preheader)
+    return 0;
+
+  // The header is not a landing pad; preheader insertion should ensure th=
is.
+  assert(!L->getHeader()->isLandingPad() &&
+         "Can't insert backedge to landing pad");
+
   PHINode *PN =3D FindPHIToPartitionLoops(L, DT, AA, LI);
   if (PN =3D=3D 0) return 0;  // No known way to partition.
=20
@@ -537,16 +553,15 @@
   // handles the case when a PHI node has multiple instances of itself as
   // arguments.
   SmallVector<BasicBlock*, 8> OuterLoopPreds;
-  for (unsigned i =3D 0, e =3D PN->getNumIncomingValues(); i !=3D e; ++i)
+  for (unsigned i =3D 0, e =3D PN->getNumIncomingValues(); i !=3D e; ++i) {
     if (PN->getIncomingValue(i) !=3D PN ||
         !L->contains(PN->getIncomingBlock(i))) {
       // We can't split indirectbr edges.
       if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
         return 0;
-
       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
     }
-
+  }
   DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
=20
   // If ScalarEvolution is around and knows anything about values in
@@ -556,9 +571,8 @@
     SE->forgetLoop(L);
=20
   BasicBlock *Header =3D L->getHeader();
-  BasicBlock *NewBB =3D SplitBlockPredecessors(Header, &OuterLoopPreds[0],
-                                             OuterLoopPreds.size(),
-                                             ".outer", this);
+  BasicBlock *NewBB =3D
+    SplitBlockPredecessors(Header, OuterLoopPreds,  ".outer", this);
=20
   // Make sure that NewBB is put someplace intelligent, which doesn't mess=
 up
   // code layout too horribly.
@@ -640,6 +654,9 @@
   if (!Preheader)
     return 0;
=20
+  // The header is not a landing pad; preheader insertion should ensure th=
is.
+  assert(!Header->isLandingPad() && "Can't insert backedge to landing pad"=
);
+
   // Figure out which basic blocks contain back-edges to the loop header.
   std::vector<BasicBlock*> BackedgeBlocks;
   for (pred_iterator I =3D pred_begin(Header), E =3D pred_end(Header); I !=
=3D E; ++I){
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/LoopUnroll.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/LoopUnroll.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/LoopUnroll.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -135,7 +135,8 @@
 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution a=
re
 /// available it must also preserve those analyses.
 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
-                      unsigned TripMultiple, LoopInfo *LI, LPPassManager *=
LPM) {
+                      bool AllowRuntime, unsigned TripMultiple,
+                      LoopInfo *LI, LPPassManager *LPM) {
   BasicBlock *Preheader =3D L->getLoopPreheader();
   if (!Preheader) {
     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
@@ -148,6 +149,12 @@
     return false;
   }
=20
+  // Loops with indirectbr cannot be cloned.
+  if (!L->isSafeToClone()) {
+    DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
+    return false;
+  }
+
   BasicBlock *Header =3D L->getHeader();
   BranchInst *BI =3D dyn_cast<BranchInst>(LatchBlock->getTerminator());
=20
@@ -165,12 +172,6 @@
     return false;
   }
=20
-  // Notify ScalarEvolution that the loop will be substantially changed,
-  // if not outright eliminated.
-  ScalarEvolution *SE =3D LPM->getAnalysisIfAvailable<ScalarEvolution>();
-  if (SE)
-    SE->forgetLoop(L);
-
   if (TripCount !=3D 0)
     DEBUG(dbgs() << "  Trip Count =3D " << TripCount << "\n");
   if (TripMultiple !=3D 1)
@@ -181,6 +182,11 @@
   if (TripCount !=3D 0 && Count > TripCount)
     Count =3D TripCount;
=20
+  // Don't enter the unroll code if there is nothing to do. This way we do=
n't
+  // need to support "partial unrolling by 1".
+  if (TripCount =3D=3D 0 && Count < 2)
+    return false;
+
   assert(Count > 0);
   assert(TripMultiple > 0);
   assert(TripCount =3D=3D 0 || TripCount % TripMultiple =3D=3D 0);
@@ -188,6 +194,20 @@
   // Are we eliminating the loop control altogether?
   bool CompletelyUnroll =3D Count =3D=3D TripCount;
=20
+  // We assume a run-time trip count if the compiler cannot
+  // figure out the loop trip count and the unroll-runtime
+  // flag is specified.
+  bool RuntimeTripCount =3D (TripCount =3D=3D 0 && Count > 0 && AllowRunti=
me);
+
+  if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
+    return false;
+
+  // Notify ScalarEvolution that the loop will be substantially changed,
+  // if not outright eliminated.
+  ScalarEvolution *SE =3D LPM->getAnalysisIfAvailable<ScalarEvolution>();
+  if (SE)
+    SE->forgetLoop(L);
+
   // If we know the trip count, we know the multiple...
   unsigned BreakoutTrip =3D 0;
   if (TripCount !=3D 0) {
@@ -209,6 +229,8 @@
       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
     } else if (TripMultiple !=3D 1) {
       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
+    } else if (RuntimeTripCount) {
+      DEBUG(dbgs() << " with run-time trip count");
     }
     DEBUG(dbgs() << "!\n");
   }
@@ -332,6 +354,10 @@
     BasicBlock *Dest =3D Headers[j];
     bool NeedConditional =3D true;
=20
+    if (RuntimeTripCount && j !=3D 0) {
+      NeedConditional =3D false;
+    }
+
     // For a complete unroll, make the last iteration end with a branch
     // to the exit block.
     if (CompletelyUnroll && j =3D=3D 0) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/LowerExpectIntrinsic.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/LowerExpectIntrinsic.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/LowerExpectIntrinsic.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -1,3 +1,16 @@
+//=3D=3D=3D- LowerExpectIntrinsic.cpp - Lower expect intrinsic -----------=
-------=3D=3D=3D//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//
+// This pass lowers the 'expect' intrinsic to LLVM metadata.
+//
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
 #define DEBUG_TYPE "lower-expect-intrinsic"
 #include "llvm/Constants.h"
 #include "llvm/Function.h"
@@ -60,14 +73,17 @@
   LLVMContext &Context =3D CI->getContext();
   Type *Int32Ty =3D Type::getInt32Ty(Context);
=20
-  unsigned caseNo =3D SI->findCaseValue(ExpectedValue);
+  SwitchInst::CaseIt Case =3D SI->findCaseValue(ExpectedValue);
   std::vector<Value *> Vec;
   unsigned n =3D SI->getNumCases();
-  Vec.resize(n + 1); // +1 for MDString
+  Vec.resize(n + 1 + 1); // +1 for MDString and +1 for default case
=20
   Vec[0] =3D MDString::get(Context, "branch_weights");
+  Vec[1] =3D ConstantInt::get(Int32Ty, Case =3D=3D SI->case_default() ?
+                            LikelyBranchWeight : UnlikelyBranchWeight);
   for (unsigned i =3D 0; i < n; ++i) {
-    Vec[i + 1] =3D ConstantInt::get(Int32Ty, i =3D=3D caseNo ? LikelyBranc=
hWeight : UnlikelyBranchWeight);
+    Vec[i + 1 + 1] =3D ConstantInt::get(Int32Ty, i =3D=3D Case.getCaseInde=
x() ?
+        LikelyBranchWeight : UnlikelyBranchWeight);
   }
=20
   MDNode *WeightsNode =3D llvm::MDNode::get(Context, Vec);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/LowerInvoke.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/LowerInvoke.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/LowerInvoke.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -54,7 +54,6 @@
 using namespace llvm;
=20
 STATISTIC(NumInvokes, "Number of invokes replaced");
-STATISTIC(NumUnwinds, "Number of unwinds replaced");
 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
=20
 static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
@@ -193,20 +192,6 @@
       BB->getInstList().erase(II);
=20
       ++NumInvokes; Changed =3D true;
-    } else if (UnwindInst *UI =3D dyn_cast<UnwindInst>(BB->getTerminator()=
)) {
-      // Insert a call to abort()
-      CallInst::Create(AbortFn, "", UI)->setTailCall();
-
-      // Insert a return instruction.  This really should be a "barrier", =
as it
-      // is unreachable.
-      ReturnInst::Create(F.getContext(),
-                         F.getReturnType()->isVoidTy() ?
-                          0 : Constant::getNullValue(F.getReturnType()), U=
I);
-
-      // Remove the unwind instruction now.
-      BB->getInstList().erase(UI);
-
-      ++NumUnwinds; Changed =3D true;
     }
   return Changed;
 }
@@ -404,7 +389,6 @@
=20
 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
   SmallVector<ReturnInst*,16> Returns;
-  SmallVector<UnwindInst*,16> Unwinds;
   SmallVector<InvokeInst*,16> Invokes;
   UnreachableInst* UnreachablePlaceholder =3D 0;
=20
@@ -415,14 +399,11 @@
       Returns.push_back(RI);
     } else if (InvokeInst *II =3D dyn_cast<InvokeInst>(BB->getTerminator()=
)) {
       Invokes.push_back(II);
-    } else if (UnwindInst *UI =3D dyn_cast<UnwindInst>(BB->getTerminator()=
)) {
-      Unwinds.push_back(UI);
     }
=20
-  if (Unwinds.empty() && Invokes.empty()) return false;
+  if (Invokes.empty()) return false;
=20
   NumInvokes +=3D Invokes.size();
-  NumUnwinds +=3D Unwinds.size();
=20
   // TODO: This is not an optimal way to do this.  In particular, this alw=
ays
   // inserts setjmp calls into the entries of functions with invoke instru=
ctions
@@ -572,13 +553,6 @@
   CallInst::Create(AbortFn, "",
                    TermBlock->getTerminator())->setTailCall();
=20
-
-  // Replace all unwinds with a branch to the unwind handler.
-  for (unsigned i =3D 0, e =3D Unwinds.size(); i !=3D e; ++i) {
-    BranchInst::Create(UnwindHandler, Unwinds[i]);
-    Unwinds[i]->eraseFromParent();
-  }
-
   // Replace the inserted unreachable with a branch to the unwind handler.
   if (UnreachablePlaceholder) {
     BranchInst::Create(UnwindHandler, UnreachablePlaceholder);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/LowerSwitch.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/LowerSwitch.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/LowerSwitch.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -237,10 +237,10 @@
   unsigned numCmps =3D 0;
=20
   // Start with "simple" cases
-  for (unsigned i =3D 1; i < SI->getNumSuccessors(); ++i)
-    Cases.push_back(CaseRange(SI->getSuccessorValue(i),
-                              SI->getSuccessorValue(i),
-                              SI->getSuccessor(i)));
+  for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end(); i =
!=3D e; ++i)
+    Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
+                              i.getCaseSuccessor()));
+ =20
   std::sort(Cases.begin(), Cases.end(), CaseCmp());
=20
   // Merge case into clusters
@@ -281,7 +281,7 @@
   BasicBlock* Default =3D SI->getDefaultDest();
=20
   // If there is only the default destination, don't bother with the code =
below.
-  if (SI->getNumCases() =3D=3D 1) {
+  if (!SI->getNumCases()) {
     BranchInst::Create(SI->getDefaultDest(), CurBlock);
     CurBlock->getInstList().erase(SI);
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/PromoteMemoryToRegister.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/PromoteMemoryToRegister.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -41,6 +41,7 @@
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
@@ -66,7 +67,8 @@
     return EltTy(reinterpret_cast<BasicBlock*>(-2), 0U);
   }
   static unsigned getHashValue(const std::pair<BasicBlock*, unsigned> &Val=
) {
-    return DenseMapInfo<void*>::getHashValue(Val.first) + Val.second*2;
+    using llvm::hash_value;
+    return static_cast<unsigned>(hash_value(Val));
   }
   static bool isEqual(const EltTy &LHS, const EltTy &RHS) {
     return LHS =3D=3D RHS;
@@ -423,7 +425,8 @@
=20
       // Finally, after the scan, check to see if the store is all that is=
 left.
       if (Info.UsingBlocks.empty()) {
-        // Record debuginfo for the store and remove the declaration's deb=
uginfo.
+        // Record debuginfo for the store and remove the declaration's=20
+        // debuginfo.
         if (DbgDeclareInst *DDI =3D Info.DbgDeclare) {
           if (!DIB)
             DIB =3D new DIBuilder(*DDI->getParent()->getParent()->getParen=
t());
@@ -590,7 +593,7 @@
       PHINode *PN =3D I->second;
=20
       // If this PHI node merges one value and/or undefs, get the value.
-      if (Value *V =3D SimplifyInstruction(PN, 0, &DT)) {
+      if (Value *V =3D SimplifyInstruction(PN, 0, 0, &DT)) {
         if (AST && PN->getType()->isPointerTy())
           AST->deleteValue(PN);
         PN->replaceAllUsesWith(V);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/SSAUpdater.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/SSAUpdater.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/SSAUpdater.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -518,3 +518,10 @@
     User->eraseFromParent();
   }
 }
+
+bool
+LoadAndStorePromoter::isInstInList(Instruction *I,
+                                   const SmallVectorImpl<Instruction*> &In=
sts)
+                                   const {
+  return std::find(Insts.begin(), Insts.end(), I) !=3D Insts.end();
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/SimplifyCFG.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/SimplifyCFG.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/SimplifyCFG.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,16 +14,20 @@
 #define DEBUG_TYPE "simplifycfg"
 #include "llvm/Transforms/Utils/Local.h"
 #include "llvm/Constants.h"
+#include "llvm/DerivedTypes.h"
+#include "llvm/GlobalVariable.h"
 #include "llvm/Instructions.h"
 #include "llvm/IntrinsicInst.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Metadata.h"
+#include "llvm/Operator.h"
 #include "llvm/Type.h"
-#include "llvm/DerivedTypes.h"
-#include "llvm/GlobalVariable.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Analysis/ValueTracking.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/Statistic.h"
@@ -63,9 +67,8 @@
   bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
                                            IRBuilder<> &Builder);
=20
+  bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
   bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
-  bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
-  bool SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder);
   bool SimplifyUnreachable(UnreachableInst *UI);
   bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
   bool SimplifyIndirectBr(IndirectBrInst *IBI);
@@ -205,6 +208,42 @@
   return BI->getCondition();
 }
=20
+/// ComputeSpeculuationCost - Compute an abstract "cost" of speculating the
+/// given instruction, which is assumed to be safe to speculate. 1 means
+/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
+static unsigned ComputeSpeculationCost(const User *I) {
+  assert(isSafeToSpeculativelyExecute(I) &&
+         "Instruction is not safe to speculatively execute!");
+  switch (Operator::getOpcode(I)) {
+  default:
+    // In doubt, be conservative.
+    return UINT_MAX;
+  case Instruction::GetElementPtr:
+    // GEPs are cheap if all indices are constant.
+    if (!cast<GEPOperator>(I)->hasAllConstantIndices())
+      return UINT_MAX;
+    return 1;
+  case Instruction::Load:
+  case Instruction::Add:
+  case Instruction::Sub:
+  case Instruction::And:
+  case Instruction::Or:
+  case Instruction::Xor:
+  case Instruction::Shl:
+  case Instruction::LShr:
+  case Instruction::AShr:
+  case Instruction::ICmp:
+  case Instruction::Trunc:
+  case Instruction::ZExt:
+  case Instruction::SExt:
+    return 1; // These are all cheap.
+
+  case Instruction::Call:
+  case Instruction::Select:
+    return 2;
+  }
+}
+
 /// DominatesMergePoint - If we have a merge point of an "if condition" as
 /// accepted above, return true if the specified value dominates the block=
.  We
 /// don't handle the true generality of domination here, just a special ca=
se
@@ -257,46 +296,10 @@
   // Okay, it looks like the instruction IS in the "condition".  Check to
   // see if it's a cheap instruction to unconditionally compute, and if it
   // only uses stuff defined outside of the condition.  If so, hoist it ou=
t.
-  if (!I->isSafeToSpeculativelyExecute())
+  if (!isSafeToSpeculativelyExecute(I))
     return false;
=20
-  unsigned Cost =3D 0;
-
-  switch (I->getOpcode()) {
-  default: return false;  // Cannot hoist this out safely.
-  case Instruction::Load:
-    // We have to check to make sure there are no instructions before the
-    // load in its basic block, as we are going to hoist the load out to i=
ts
-    // predecessor.
-    if (PBB->getFirstNonPHIOrDbg() !=3D I)
-      return false;
-    Cost =3D 1;
-    break;
-  case Instruction::GetElementPtr:
-    // GEPs are cheap if all indices are constant.
-    if (!cast<GetElementPtrInst>(I)->hasAllConstantIndices())
-      return false;
-    Cost =3D 1;
-    break;
-  case Instruction::Add:
-  case Instruction::Sub:
-  case Instruction::And:
-  case Instruction::Or:
-  case Instruction::Xor:
-  case Instruction::Shl:
-  case Instruction::LShr:
-  case Instruction::AShr:
-  case Instruction::ICmp:
-  case Instruction::Trunc:
-  case Instruction::ZExt:
-  case Instruction::SExt:
-    Cost =3D 1;
-    break;   // These are all cheap and non-trapping instructions.
-
-  case Instruction::Select:
-    Cost =3D 2;
-    break;
-  }
+  unsigned Cost =3D ComputeSpeculationCost(I);
=20
   if (Cost > CostRemaining)
     return false;
@@ -373,9 +376,7 @@
         Span =3D Span.inverse();
      =20
       // If there are a ton of values, we don't want to make a ginormous s=
witch.
-      if (Span.getSetSize().ugt(8) || Span.isEmptySet() ||
-          // We don't handle wrapped sets yet.
-          Span.isWrappedSet())
+      if (Span.getSetSize().ugt(8) || Span.isEmptySet())
         return 0;
      =20
       for (APInt Tmp =3D Span.getLower(); Tmp !=3D Span.getUpper(); ++Tmp)
@@ -430,9 +431,9 @@
  =20
   return 0;
 }
-     =20
+
 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
-  Instruction* Cond =3D 0;
+  Instruction *Cond =3D 0;
   if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
     Cond =3D dyn_cast<Instruction>(SI->getCondition());
   } else if (BranchInst *BI =3D dyn_cast<BranchInst>(TI)) {
@@ -479,8 +480,9 @@
                                                       BasicBlock*> > &Case=
s) {
   if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
     Cases.reserve(SI->getNumCases());
-    for (unsigned i =3D 1, e =3D SI->getNumCases(); i !=3D e; ++i)
-      Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor=
(i)));
+    for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end(); =
i !=3D e; ++i)
+      Cases.push_back(std::make_pair(i.getCaseValue(),
+                                     i.getCaseSuccessor()));
     return SI->getDefaultDest();
   }
=20
@@ -603,11 +605,13 @@
     DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
                  << "Through successor TI: " << *TI);
=20
-    for (unsigned i =3D SI->getNumCases()-1; i !=3D 0; --i)
-      if (DeadCases.count(SI->getCaseValue(i))) {
-        SI->getSuccessor(i)->removePredecessor(TI->getParent());
+    for (SwitchInst::CaseIt i =3D SI->case_end(), e =3D SI->case_begin(); =
i !=3D e;) {
+      --i;
+      if (DeadCases.count(i.getCaseValue())) {
+        i.getCaseSuccessor()->removePredecessor(TI->getParent());
         SI->removeCase(i);
       }
+    }
=20
     DEBUG(dbgs() << "Leaving: " << *TI << "\n");
     return true;
@@ -951,6 +955,20 @@
 /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
 /// (for now, restricted to a single instruction that's side effect free) =
from
 /// the BB1 into the branch block to speculatively execute it.
+///
+/// Turn
+/// BB:
+///     %t1 =3D icmp
+///     br i1 %t1, label %BB1, label %BB2
+/// BB1:
+///     %t3 =3D add %t2, c
+///     br label BB2
+/// BB2:
+/// =3D>
+/// BB:
+///     %t1 =3D icmp
+///     %t4 =3D add %t2, c
+///     %t3 =3D select i1 %t1, %t2, %t3
 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
   // Only speculatively execution a single instruction (not counting the
   // terminator) for now.
@@ -967,8 +985,29 @@
       return false;
     HInst =3D I;
   }
-  if (!HInst)
-    return false;
+
+  BasicBlock *BIParent =3D BI->getParent();
+
+  // Check the instruction to be hoisted, if there is one.
+  if (HInst) {
+    // Don't hoist the instruction if it's unsafe or expensive.
+    if (!isSafeToSpeculativelyExecute(HInst))
+      return false;
+    if (ComputeSpeculationCost(HInst) > PHINodeFoldingThreshold)
+      return false;
+
+    // Do not hoist the instruction if any of its operands are defined but=
 not
+    // used in this BB. The transformation will prevent the operand from
+    // being sunk into the use block.
+    for (User::op_iterator i =3D HInst->op_begin(), e =3D HInst->op_end();=20
+         i !=3D e; ++i) {
+      Instruction *OpI =3D dyn_cast<Instruction>(*i);
+      if (OpI && OpI->getParent() =3D=3D BIParent &&
+          !OpI->mayHaveSideEffects() &&
+          !OpI->isUsedInBasicBlock(BIParent))
+        return false;
+    }
+  }
=20
   // Be conservative for now. FP select instruction can often be expensive.
   Value *BrCond =3D BI->getCondition();
@@ -983,130 +1022,78 @@
     Invert =3D true;
   }
=20
-  // Turn
-  // BB:
-  //     %t1 =3D icmp
-  //     br i1 %t1, label %BB1, label %BB2
-  // BB1:
-  //     %t3 =3D add %t2, c
-  //     br label BB2
-  // BB2:
-  // =3D>
-  // BB:
-  //     %t1 =3D icmp
-  //     %t4 =3D add %t2, c
-  //     %t3 =3D select i1 %t1, %t2, %t3
-  switch (HInst->getOpcode()) {
-  default: return false;  // Not safe / profitable to hoist.
-  case Instruction::Add:
-  case Instruction::Sub:
-    // Not worth doing for vector ops.
-    if (HInst->getType()->isVectorTy())
-      return false;
-    break;
-  case Instruction::And:
-  case Instruction::Or:
-  case Instruction::Xor:
-  case Instruction::Shl:
-  case Instruction::LShr:
-  case Instruction::AShr:
-    // Don't mess with vector operations.
-    if (HInst->getType()->isVectorTy())
-      return false;
-    break;   // These are all cheap and non-trapping instructions.
-  }
- =20
-  // If the instruction is obviously dead, don't try to predicate it.
-  if (HInst->use_empty()) {
-    HInst->eraseFromParent();
-    return true;
+  // Collect interesting PHIs, and scan for hazards.
+  SmallSetVector<std::pair<Value *, Value *>, 4> PHIs;
+  BasicBlock *BB2 =3D BB1->getTerminator()->getSuccessor(0);
+  for (BasicBlock::iterator I =3D BB2->begin();
+       PHINode *PN =3D dyn_cast<PHINode>(I); ++I) {
+    Value *BB1V =3D PN->getIncomingValueForBlock(BB1);
+    Value *BIParentV =3D PN->getIncomingValueForBlock(BIParent);
+
+    // Skip PHIs which are trivial.
+    if (BB1V =3D=3D BIParentV)
+      continue;
+
+    // Check for saftey.
+    if (ConstantExpr *CE =3D dyn_cast<ConstantExpr>(BB1V)) {
+      // An unfolded ConstantExpr could end up getting expanded into
+      // Instructions. Don't speculate this and another instruction at
+      // the same time.
+      if (HInst)
+        return false;
+      if (!isSafeToSpeculativelyExecute(CE))
+        return false;
+      if (ComputeSpeculationCost(CE) > PHINodeFoldingThreshold)
+        return false;
+    }
+
+    // Ok, we may insert a select for this PHI.
+    PHIs.insert(std::make_pair(BB1V, BIParentV));
   }
=20
-  // Can we speculatively execute the instruction? And what is the value=20
-  // if the condition is false? Consider the phi uses, if the incoming val=
ue
-  // from the "if" block are all the same V, then V is the value of the
-  // select if the condition is false.
-  BasicBlock *BIParent =3D BI->getParent();
-  SmallVector<PHINode*, 4> PHIUses;
-  Value *FalseV =3D NULL;
+  // If there are no PHIs to process, bail early. This helps ensure idempo=
tence
+  // as well.
+  if (PHIs.empty())
+    return false;
  =20
-  BasicBlock *BB2 =3D BB1->getTerminator()->getSuccessor(0);
-  for (Value::use_iterator UI =3D HInst->use_begin(), E =3D HInst->use_end=
();
-       UI !=3D E; ++UI) {
-    // Ignore any user that is not a PHI node in BB2.  These can only occu=
r in
-    // unreachable blocks, because they would not be dominated by the inst=
r.
-    PHINode *PN =3D dyn_cast<PHINode>(*UI);
-    if (!PN || PN->getParent() !=3D BB2)
-      return false;
-    PHIUses.push_back(PN);
-   =20
-    Value *PHIV =3D PN->getIncomingValueForBlock(BIParent);
-    if (!FalseV)
-      FalseV =3D PHIV;
-    else if (FalseV !=3D PHIV)
-      return false;  // Inconsistent value when condition is false.
-  }
- =20
-  assert(FalseV && "Must have at least one user, and it must be a PHI");
+  // If we get here, we can hoist the instruction and if-convert.
+  DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *BB1 << "\n";);
=20
-  // Do not hoist the instruction if any of its operands are defined but n=
ot
-  // used in this BB. The transformation will prevent the operand from
-  // being sunk into the use block.
-  for (User::op_iterator i =3D HInst->op_begin(), e =3D HInst->op_end();=20
-       i !=3D e; ++i) {
-    Instruction *OpI =3D dyn_cast<Instruction>(*i);
-    if (OpI && OpI->getParent() =3D=3D BIParent &&
-        !OpI->isUsedInBasicBlock(BIParent))
-      return false;
-  }
+  // Hoist the instruction.
+  if (HInst)
+    BIParent->getInstList().splice(BI, BB1->getInstList(), HInst);
=20
-  // If we get here, we can hoist the instruction. Try to place it
-  // before the icmp instruction preceding the conditional branch.
-  BasicBlock::iterator InsertPos =3D BI;
-  if (InsertPos !=3D BIParent->begin())
-    --InsertPos;
-  // Skip debug info between condition and branch.
-  while (InsertPos !=3D BIParent->begin() && isa<DbgInfoIntrinsic>(InsertP=
os))
-    --InsertPos;
-  if (InsertPos =3D=3D BrCond && !isa<PHINode>(BrCond)) {
-    SmallPtrSet<Instruction *, 4> BB1Insns;
-    for(BasicBlock::iterator BB1I =3D BB1->begin(), BB1E =3D BB1->end();=20
-        BB1I !=3D BB1E; ++BB1I)=20
-      BB1Insns.insert(BB1I);
-    for(Value::use_iterator UI =3D BrCond->use_begin(), UE =3D BrCond->use=
_end();
-        UI !=3D UE; ++UI) {
-      Instruction *Use =3D cast<Instruction>(*UI);
-      if (!BB1Insns.count(Use)) continue;
-     =20
-      // If BrCond uses the instruction that place it just before
-      // branch instruction.
-      InsertPos =3D BI;
-      break;
+  // Insert selects and rewrite the PHI operands.
+  IRBuilder<true, NoFolder> Builder(BI);
+  for (unsigned i =3D 0, e =3D PHIs.size(); i !=3D e; ++i) {
+    Value *TrueV =3D PHIs[i].first;
+    Value *FalseV =3D PHIs[i].second;
+
+    // Create a select whose true value is the speculatively executed valu=
e and
+    // false value is the previously determined FalseV.
+    SelectInst *SI;
+    if (Invert)
+      SI =3D cast<SelectInst>
+        (Builder.CreateSelect(BrCond, FalseV, TrueV,
+                              FalseV->getName() + "." + TrueV->getName()));
+    else
+      SI =3D cast<SelectInst>
+        (Builder.CreateSelect(BrCond, TrueV, FalseV,
+                              TrueV->getName() + "." + FalseV->getName()));
+
+    // Make the PHI node use the select for all incoming values for "then"=
 and
+    // "if" blocks.
+    for (BasicBlock::iterator I =3D BB2->begin();
+         PHINode *PN =3D dyn_cast<PHINode>(I); ++I) {
+      unsigned BB1I =3D PN->getBasicBlockIndex(BB1);
+      unsigned BIParentI =3D PN->getBasicBlockIndex(BIParent);
+      Value *BB1V =3D PN->getIncomingValue(BB1I);
+      Value *BIParentV =3D PN->getIncomingValue(BIParentI);
+      if (TrueV =3D=3D BB1V && FalseV =3D=3D BIParentV) {
+        PN->setIncomingValue(BB1I, SI);
+        PN->setIncomingValue(BIParentI, SI);
+      }
     }
-  } else
-    InsertPos =3D BI;
-  BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
-
-  // Create a select whose true value is the speculatively executed value =
and
-  // false value is the previously determined FalseV.
-  IRBuilder<true, NoFolder> Builder(BI);
-  SelectInst *SI;
-  if (Invert)
-    SI =3D cast<SelectInst>
-      (Builder.CreateSelect(BrCond, FalseV, HInst,
-                            FalseV->getName() + "." + HInst->getName()));
-  else
-    SI =3D cast<SelectInst>
-      (Builder.CreateSelect(BrCond, HInst, FalseV,
-                            HInst->getName() + "." + FalseV->getName()));
-
-  // Make the PHI node use the select for all incoming values for "then" a=
nd
-  // "if" blocks.
-  for (unsigned i =3D 0, e =3D PHIUses.size(); i !=3D e; ++i) {
-    PHINode *PN =3D PHIUses[i];
-    for (unsigned j =3D 0, ee =3D PN->getNumIncomingValues(); j !=3D ee; +=
+j)
-      if (PN->getIncomingBlock(j) =3D=3D BB1 || PN->getIncomingBlock(j) =
=3D=3D BIParent)
-        PN->setIncomingValue(j, SI);
   }
=20
   ++NumSpeculations;
@@ -1461,6 +1448,49 @@
   return true;
 }
=20
+/// ExtractBranchMetadata - Given a conditional BranchInstruction, retriev=
e the
+/// probabilities of the branch taking each edge. Fills in the two APInt
+/// parameters and return true, or returns false if no or invalid metadata=
 was
+/// found.
+static bool ExtractBranchMetadata(BranchInst *BI,
+                                  APInt &ProbTrue, APInt &ProbFalse) {
+  assert(BI->isConditional() &&
+         "Looking for probabilities on unconditional branch?");
+  MDNode *ProfileData =3D BI->getMetadata(LLVMContext::MD_prof);
+  if (!ProfileData || ProfileData->getNumOperands() !=3D 3) return false;
+  ConstantInt *CITrue =3D dyn_cast<ConstantInt>(ProfileData->getOperand(1)=
);
+  ConstantInt *CIFalse =3D dyn_cast<ConstantInt>(ProfileData->getOperand(2=
));
+  if (!CITrue || !CIFalse) return false;
+  ProbTrue =3D CITrue->getValue();
+  ProbFalse =3D CIFalse->getValue();
+  assert(ProbTrue.getBitWidth() =3D=3D 32 && ProbFalse.getBitWidth() =3D=
=3D 32 &&
+         "Branch probability metadata must be 32-bit integers");
+  return true;
+}
+
+/// MultiplyAndLosePrecision - Multiplies A and B, then returns the result=
. In
+/// the event of overflow, logically-shifts all four inputs right until the
+/// multiply fits.
+static APInt MultiplyAndLosePrecision(APInt &A, APInt &B, APInt &C, APInt =
&D,
+                                      unsigned &BitsLost) {
+  BitsLost =3D 0;
+  bool Overflow =3D false;
+  APInt Result =3D A.umul_ov(B, Overflow);
+  if (Overflow) {
+    APInt MaxB =3D APInt::getMaxValue(A.getBitWidth()).udiv(A);
+    do {
+      B =3D B.lshr(1);
+      ++BitsLost;
+    } while (B.ugt(MaxB));
+    A =3D A.lshr(BitsLost);
+    C =3D C.lshr(BitsLost);
+    D =3D D.lshr(BitsLost);
+    Result =3D A * B;
+  }
+  return Result;
+}
+
+
 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
 /// predecessor branches to us and one of our successors, fold the block i=
nto
 /// the predecessor and use logical operations to pick the right destinati=
on.
@@ -1479,7 +1509,7 @@
=20
   // Ignore dbg intrinsics.
   while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
-   =20
+
   // Allow a single instruction to be hoisted in addition to the compare
   // that feeds the branch.  We later ensure that any values that _it_ uses
   // were also live in the predecessor, so that we don't unnecessarily cre=
ate
@@ -1487,7 +1517,7 @@
   Instruction *BonusInst =3D 0;
   if (&*FrontIt !=3D Cond &&
       FrontIt->hasOneUse() && *FrontIt->use_begin() =3D=3D Cond &&
-      FrontIt->isSafeToSpeculativelyExecute()) {
+      isSafeToSpeculativelyExecute(FrontIt)) {
     BonusInst =3D &*FrontIt;
     ++FrontIt;
    =20
@@ -1557,7 +1587,7 @@
       SmallPtrSet<Value*, 4> UsedValues;
       for (Instruction::op_iterator OI =3D BonusInst->op_begin(),
            OE =3D BonusInst->op_end(); OI !=3D OE; ++OI) {
-        Value* V =3D *OI;
+        Value *V =3D *OI;
         if (!isa<Constant>(V))
           UsedValues.insert(V);
       }
@@ -1602,10 +1632,7 @@
       }
      =20
       PBI->setCondition(NewCond);
-      BasicBlock *OldTrue =3D PBI->getSuccessor(0);
-      BasicBlock *OldFalse =3D PBI->getSuccessor(1);
-      PBI->setSuccessor(0, OldFalse);
-      PBI->setSuccessor(1, OldTrue);
+      PBI->swapSuccessors();
     }
    =20
     // If we have a bonus inst, clone it into the predecessor block.
@@ -1638,6 +1665,94 @@
       PBI->setSuccessor(1, FalseDest);
     }
=20
+    // TODO: If BB is reachable from all paths through PredBlock, then we
+    // could replace PBI's branch probabilities with BI's.
+
+    // Merge probability data into PredBlock's branch.
+    APInt A, B, C, D;
+    if (ExtractBranchMetadata(PBI, C, D) && ExtractBranchMetadata(BI, A, B=
)) {
+      // Given IR which does:
+      //   bbA:
+      //     br i1 %x, label %bbB, label %bbC
+      //   bbB:
+      //     br i1 %y, label %bbD, label %bbC
+      // Let's call the probability that we take the edge from %bbA to %bbB
+      // 'a', from %bbA to %bbC, 'b', from %bbB to %bbD 'c' and from %bbB =
to
+      // %bbC probability 'd'.
+      //
+      // We transform the IR into:
+      //   bbA:
+      //     br i1 %z, label %bbD, label %bbC
+      // where the probability of going to %bbD is (a*c) and going to bbC =
is
+      // (b+a*d).
+      //
+      // Probabilities aren't stored as ratios directly. Using branch weig=
hts,
+      // we get:
+      // (a*c)% =3D A*C, (b+(a*d))% =3D A*D+B*C+B*D.
+
+      // In the event of overflow, we want to drop the LSB of the input
+      // probabilities.
+      unsigned BitsLost;
+
+      // Ignore overflow result on ProbTrue.
+      APInt ProbTrue =3D MultiplyAndLosePrecision(A, C, B, D, BitsLost);
+
+      APInt Tmp1 =3D MultiplyAndLosePrecision(B, D, A, C, BitsLost);
+      if (BitsLost) {
+        ProbTrue =3D ProbTrue.lshr(BitsLost*2);
+      }
+
+      APInt Tmp2 =3D MultiplyAndLosePrecision(A, D, C, B, BitsLost);
+      if (BitsLost) {
+        ProbTrue =3D ProbTrue.lshr(BitsLost*2);
+        Tmp1 =3D Tmp1.lshr(BitsLost*2);
+      }
+
+      APInt Tmp3 =3D MultiplyAndLosePrecision(B, C, A, D, BitsLost);
+      if (BitsLost) {
+        ProbTrue =3D ProbTrue.lshr(BitsLost*2);
+        Tmp1 =3D Tmp1.lshr(BitsLost*2);
+        Tmp2 =3D Tmp2.lshr(BitsLost*2);
+      }
+
+      bool Overflow1 =3D false, Overflow2 =3D false;
+      APInt Tmp4 =3D Tmp2.uadd_ov(Tmp3, Overflow1);
+      APInt ProbFalse =3D Tmp4.uadd_ov(Tmp1, Overflow2);
+
+      if (Overflow1 || Overflow2) {
+        ProbTrue =3D ProbTrue.lshr(1);
+        Tmp1 =3D Tmp1.lshr(1);
+        Tmp2 =3D Tmp2.lshr(1);
+        Tmp3 =3D Tmp3.lshr(1);
+        Tmp4 =3D Tmp2 + Tmp3;
+        ProbFalse =3D Tmp4 + Tmp1;
+      }
+
+      // The sum of branch weights must fit in 32-bits.
+      if (ProbTrue.isNegative() && ProbFalse.isNegative()) {
+        ProbTrue =3D ProbTrue.lshr(1);
+        ProbFalse =3D ProbFalse.lshr(1);
+      }
+
+      if (ProbTrue !=3D ProbFalse) {
+        // Normalize the result.
+        APInt GCD =3D APIntOps::GreatestCommonDivisor(ProbTrue, ProbFalse);
+        ProbTrue =3D ProbTrue.udiv(GCD);
+        ProbFalse =3D ProbFalse.udiv(GCD);
+
+        LLVMContext &Context =3D BI->getContext();
+        Value *Ops[3];
+        Ops[0] =3D BI->getMetadata(LLVMContext::MD_prof)->getOperand(0);
+        Ops[1] =3D ConstantInt::get(Context, ProbTrue);
+        Ops[2] =3D ConstantInt::get(Context, ProbFalse);
+        PBI->setMetadata(LLVMContext::MD_prof, MDNode::get(Context, Ops));
+      } else {
+        PBI->setMetadata(LLVMContext::MD_prof, NULL);
+      }
+    } else {
+      PBI->setMetadata(LLVMContext::MD_prof, NULL);
+    }
+
     // Copy any debug value intrinsics into the end of PredBlock.
     for (BasicBlock::iterator I =3D BB->begin(), E =3D BB->end(); I !=3D E=
; ++I)
       if (isa<DbgInfoIntrinsic>(*I))
@@ -1894,8 +2009,8 @@
=20
   // Find the relevant condition and destinations.
   Value *Condition =3D Select->getCondition();
-  BasicBlock *TrueBB =3D SI->getSuccessor(SI->findCaseValue(TrueVal));
-  BasicBlock *FalseBB =3D SI->getSuccessor(SI->findCaseValue(FalseVal));
+  BasicBlock *TrueBB =3D SI->findCaseValue(TrueVal).getCaseSuccessor();
+  BasicBlock *FalseBB =3D SI->findCaseValue(FalseVal).getCaseSuccessor();
=20
   // Perform the actual simplification.
   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB);
@@ -1979,7 +2094,7 @@
   // Ok, the block is reachable from the default dest.  If the constant we=
're
   // comparing exists in one of the other edges, then we can constant fold=
 ICI
   // and zap it.
-  if (SI->findCaseValue(Cst) !=3D 0) {
+  if (SI->findCaseValue(Cst) !=3D SI->case_default()) {
     Value *V;
     if (ICI->getPredicate() =3D=3D ICmpInst::ICMP_EQ)
       V =3D ConstantInt::getFalse(BB->getContext());
@@ -2235,52 +2350,6 @@
   return false;
 }
=20
-bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI, IRBuilder<> &Builder) {
-  // Check to see if the first instruction in this block is just an unwind.
-  // If so, replace any invoke instructions which use this as an exception
-  // destination with call instructions.
-  BasicBlock *BB =3D UI->getParent();
-  if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
-
-  bool Changed =3D false;
-  SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
-  while (!Preds.empty()) {
-    BasicBlock *Pred =3D Preds.back();
-    InvokeInst *II =3D dyn_cast<InvokeInst>(Pred->getTerminator());
-    if (II && II->getUnwindDest() =3D=3D BB) {
-      // Insert a new branch instruction before the invoke, because this
-      // is now a fall through.
-      Builder.SetInsertPoint(II);
-      BranchInst *BI =3D Builder.CreateBr(II->getNormalDest());
-      Pred->getInstList().remove(II);   // Take out of symbol table
-     =20
-      // Insert the call now.
-      SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
-      Builder.SetInsertPoint(BI);
-      CallInst *CI =3D Builder.CreateCall(II->getCalledValue(),
-                                        Args, II->getName());
-      CI->setCallingConv(II->getCallingConv());
-      CI->setAttributes(II->getAttributes());
-      // If the invoke produced a value, the Call now does instead.
-      II->replaceAllUsesWith(CI);
-      delete II;
-      Changed =3D true;
-    }
-   =20
-    Preds.pop_back();
-  }
- =20
-  // If this block is now dead (and isn't the entry block), remove it.
-  if (pred_begin(BB) =3D=3D pred_end(BB) &&
-      BB !=3D &BB->getParent()->getEntryBlock()) {
-    // We know there are no successors, so just nuke the block.
-    BB->eraseFromParent();
-    return true;
-  }
- =20
-  return Changed; =20
-}
-
 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
   BasicBlock *BB =3D UI->getParent();
  =20
@@ -2352,8 +2421,9 @@
         }
       }
     } else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(TI)) {
-      for (unsigned i =3D 1, e =3D SI->getNumCases(); i !=3D e; ++i)
-        if (SI->getSuccessor(i) =3D=3D BB) {
+      for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end();
+           i !=3D e; ++i)
+        if (i.getCaseSuccessor() =3D=3D BB) {
           BB->removePredecessor(SI->getParent());
           SI->removeCase(i);
           --i; --e;
@@ -2361,14 +2431,15 @@
         }
       // If the default value is unreachable, figure out the most popular
       // destination and make it the default.
-      if (SI->getSuccessor(0) =3D=3D BB) {
+      if (SI->getDefaultDest() =3D=3D BB) {
         std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
-        for (unsigned i =3D 1, e =3D SI->getNumCases(); i !=3D e; ++i) {
-          std::pair<unsigned, unsigned>& entry =3D
-              Popularity[SI->getSuccessor(i)];
+        for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_end=
();
+             i !=3D e; ++i) {
+          std::pair<unsigned, unsigned> &entry =3D
+              Popularity[i.getCaseSuccessor()];
           if (entry.first =3D=3D 0) {
             entry.first =3D 1;
-            entry.second =3D i;
+            entry.second =3D i.getCaseIndex();
           } else {
             entry.first++;
           }
@@ -2390,7 +2461,7 @@
         if (MaxBlock) {
           // Make this the new default, allowing us to delete any explicit
           // edges to it.
-          SI->setSuccessor(0, MaxBlock);
+          SI->setDefaultDest(MaxBlock);
           Changed =3D true;
          =20
           // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
@@ -2399,8 +2470,9 @@
             for (unsigned i =3D 0; i !=3D MaxPop-1; ++i)
               MaxBlock->removePredecessor(SI->getParent());
          =20
-          for (unsigned i =3D 1, e =3D SI->getNumCases(); i !=3D e; ++i)
-            if (SI->getSuccessor(i) =3D=3D MaxBlock) {
+          for (SwitchInst::CaseIt i =3D SI->case_begin(), e =3D SI->case_e=
nd();
+               i !=3D e; ++i)
+            if (i.getCaseSuccessor() =3D=3D MaxBlock) {
               SI->removeCase(i);
               --i; --e;
             }
@@ -2442,17 +2514,19 @@
 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
 /// integer range comparison into a sub, an icmp and a branch.
 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
-  assert(SI->getNumCases() > 2 && "Degenerate switch?");
+  assert(SI->getNumCases() > 1 && "Degenerate switch?");
=20
   // Make sure all cases point to the same destination and gather the valu=
es.
   SmallVector<ConstantInt *, 16> Cases;
-  Cases.push_back(SI->getCaseValue(1));
-  for (unsigned I =3D 2, E =3D SI->getNumCases(); I !=3D E; ++I) {
-    if (SI->getSuccessor(I-1) !=3D SI->getSuccessor(I))
+  SwitchInst::CaseIt I =3D SI->case_begin();
+  Cases.push_back(I.getCaseValue());
+  SwitchInst::CaseIt PrevI =3D I++;
+  for (SwitchInst::CaseIt E =3D SI->case_end(); I !=3D E; PrevI =3D I++) {
+    if (PrevI.getCaseSuccessor() !=3D I.getCaseSuccessor())
       return false;
-    Cases.push_back(SI->getCaseValue(I));
+    Cases.push_back(I.getCaseValue());
   }
-  assert(Cases.size() =3D=3D SI->getNumCases()-1 && "Not all cases gathere=
d");
+  assert(Cases.size() =3D=3D SI->getNumCases() && "Not all cases gathered"=
);
=20
   // Sort the case values, then check if they form a range we can transfor=
m.
   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
@@ -2462,18 +2536,19 @@
   }
=20
   Constant *Offset =3D ConstantExpr::getNeg(Cases.back());
-  Constant *NumCases =3D ConstantInt::get(Offset->getType(), SI->getNumCas=
es()-1);
+  Constant *NumCases =3D ConstantInt::get(Offset->getType(), SI->getNumCas=
es());
=20
   Value *Sub =3D SI->getCondition();
   if (!Offset->isNullValue())
     Sub =3D Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
   Value *Cmp =3D Builder.CreateICmpULT(Sub, NumCases, "switch");
-  Builder.CreateCondBr(Cmp, SI->getSuccessor(1), SI->getDefaultDest());
+  Builder.CreateCondBr(
+      Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
=20
   // Prune obsolete incoming values off the successor's PHI nodes.
-  for (BasicBlock::iterator BBI =3D SI->getSuccessor(1)->begin();
+  for (BasicBlock::iterator BBI =3D SI->case_begin().getCaseSuccessor()->b=
egin();
        isa<PHINode>(BBI); ++BBI) {
-    for (unsigned I =3D 0, E =3D SI->getNumCases()-2; I !=3D E; ++I)
+    for (unsigned I =3D 0, E =3D SI->getNumCases()-1; I !=3D E; ++I)
       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
   }
   SI->eraseFromParent();
@@ -2487,24 +2562,26 @@
   Value *Cond =3D SI->getCondition();
   unsigned Bits =3D cast<IntegerType>(Cond->getType())->getBitWidth();
   APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
-  ComputeMaskedBits(Cond, APInt::getAllOnesValue(Bits), KnownZero, KnownOn=
e);
+  ComputeMaskedBits(Cond, KnownZero, KnownOne);
=20
   // Gather dead cases.
   SmallVector<ConstantInt*, 8> DeadCases;
-  for (unsigned I =3D 1, E =3D SI->getNumCases(); I !=3D E; ++I) {
-    if ((SI->getCaseValue(I)->getValue() & KnownZero) !=3D 0 ||
-        (SI->getCaseValue(I)->getValue() & KnownOne) !=3D KnownOne) {
-      DeadCases.push_back(SI->getCaseValue(I));
+  for (SwitchInst::CaseIt I =3D SI->case_begin(), E =3D SI->case_end(); I =
!=3D E; ++I) {
+    if ((I.getCaseValue()->getValue() & KnownZero) !=3D 0 ||
+        (I.getCaseValue()->getValue() & KnownOne) !=3D KnownOne) {
+      DeadCases.push_back(I.getCaseValue());
       DEBUG(dbgs() << "SimplifyCFG: switch case '"
-                   << SI->getCaseValue(I)->getValue() << "' is dead.\n");
+                   << I.getCaseValue() << "' is dead.\n");
     }
   }
=20
   // Remove dead cases from the switch.
   for (unsigned I =3D 0, E =3D DeadCases.size(); I !=3D E; ++I) {
-    unsigned Case =3D SI->findCaseValue(DeadCases[I]);
+    SwitchInst::CaseIt Case =3D SI->findCaseValue(DeadCases[I]);
+    assert(Case !=3D SI->case_default() &&
+           "Case was not found. Probably mistake in DeadCases forming.");
     // Prune unused values from PHI nodes.
-    SI->getSuccessor(Case)->removePredecessor(SI->getParent());
+    Case.getCaseSuccessor()->removePredecessor(SI->getParent());
     SI->removeCase(Case);
   }
=20
@@ -2553,9 +2630,9 @@
   typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
   ForwardingNodesMap ForwardingNodes;
=20
-  for (unsigned I =3D 1; I < SI->getNumCases(); ++I) { // 0 is the default=
 case.
-    ConstantInt *CaseValue =3D SI->getCaseValue(I);
-    BasicBlock *CaseDest =3D SI->getSuccessor(I);
+  for (SwitchInst::CaseIt I =3D SI->case_begin(), E =3D SI->case_end(); I =
!=3D E; ++I) {
+    ConstantInt *CaseValue =3D I.getCaseValue();
+    BasicBlock *CaseDest =3D I.getCaseSuccessor();
=20
     int PhiIndex;
     PHINode *PHI =3D FindPHIForConditionForwarding(CaseValue, CaseDest,
@@ -2676,8 +2753,8 @@
     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
         ;
-      if (I->isTerminator()=20
-          && TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
+      if (I->isTerminator() &&
+          TryToSimplifyUncondBranchWithICmpInIt(ICI, TD, Builder))
         return true;
     }
  =20
@@ -2720,6 +2797,12 @@
   if (SimplifyBranchOnICmpChain(BI, TD, Builder))
     return true;
  =20
+  // If this basic block is ONLY a compare and a branch, and if a predeces=
sor
+  // branches to us and one of our successors, fold the comparison into the
+  // predecessor and use logical operations to pick the right destination.
+  if (FoldBranchToCommonDest(BI))
+    return SimplifyCFG(BB) | true;
+ =20
   // We have a conditional branch to two blocks that are only reachable
   // from BI.  We know that the condbr dominates the two blocks, so see if
   // there is any identical code in the "then" and "else" blocks.  If so, =
we
@@ -2754,12 +2837,6 @@
       if (FoldCondBranchOnPHI(BI, TD))
         return SimplifyCFG(BB) | true;
  =20
-  // If this basic block is ONLY a setcc and a branch, and if a predecessor
-  // branches to us and one of our successors, fold the setcc into the
-  // predecessor and use logical operations to pick the right destination.
-  if (FoldBranchToCommonDest(BI))
-    return SimplifyCFG(BB) | true;
- =20
   // Scan predecessor blocks for conditional branches.
   for (pred_iterator PI =3D pred_begin(BB), E =3D pred_end(BB); PI !=3D E;=
 ++PI)
     if (BranchInst *PBI =3D dyn_cast<BranchInst>((*PI)->getTerminator()))
@@ -2809,7 +2886,7 @@
 }
=20
 /// If BB has an incoming value that will always trigger undefined behavior
-/// (eg. null pointer derefence), remove the branch leading here.
+/// (eg. null pointer dereference), remove the branch leading here.
 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
   for (BasicBlock::iterator i =3D BB->begin();
        PHINode *PHI =3D dyn_cast<PHINode>(i); ++i)
@@ -2883,17 +2960,15 @@
     } else {
       if (SimplifyCondBranch(BI, Builder)) return true;
     }
+  } else if (ReturnInst *RI =3D dyn_cast<ReturnInst>(BB->getTerminator()))=
 {
+    if (SimplifyReturn(RI, Builder)) return true;
   } else if (ResumeInst *RI =3D dyn_cast<ResumeInst>(BB->getTerminator()))=
 {
     if (SimplifyResume(RI, Builder)) return true;
-  } else if (ReturnInst *RI =3D dyn_cast<ReturnInst>(BB->getTerminator()))=
 {
-    if (SimplifyReturn(RI, Builder)) return true;
   } else if (SwitchInst *SI =3D dyn_cast<SwitchInst>(BB->getTerminator()))=
 {
     if (SimplifySwitch(SI, Builder)) return true;
   } else if (UnreachableInst *UI =3D
                dyn_cast<UnreachableInst>(BB->getTerminator())) {
     if (SimplifyUnreachable(UI)) return true;
-  } else if (UnwindInst *UI =3D dyn_cast<UnwindInst>(BB->getTerminator()))=
 {
-    if (SimplifyUnwind(UI, Builder)) return true;
   } else if (IndirectBrInst *IBI =3D
                dyn_cast<IndirectBrInst>(BB->getTerminator())) {
     if (SimplifyIndirectBr(IBI)) return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/SimplifyIndVar.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/SimplifyIndVar.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -46,7 +46,6 @@
     LoopInfo         *LI;
     DominatorTree    *DT;
     ScalarEvolution  *SE;
-    IVUsers          *IU; // NULL for DisableIVRewrite
     const TargetData *TD; // May be NULL
=20
     SmallVectorImpl<WeakVH> &DeadInsts;
@@ -59,7 +58,6 @@
       L(Loop),
       LI(LPM->getAnalysisIfAvailable<LoopInfo>()),
       SE(SE),
-      IU(IVU),
       TD(LPM->getAnalysisIfAvailable<TargetData>()),
       DeadInsts(Dead),
       Changed(false) {
@@ -107,8 +105,8 @@
=20
     // Attempt to fold a binary operator with constant operand.
     // e.g. ((I + 1) >> 2) =3D> I >> 2
-    if (IVOperand->getNumOperands() !=3D 2 ||
-        !isa<ConstantInt>(IVOperand->getOperand(1)))
+    if (!isa<BinaryOperator>(IVOperand)
+        || !isa<ConstantInt>(IVOperand->getOperand(1)))
       return 0;
=20
     IVSrc =3D IVOperand->getOperand(0);
@@ -229,11 +227,6 @@
     Rem->replaceAllUsesWith(Sel);
   }
=20
-  // Inform IVUsers about the new users.
-  if (IU) {
-    if (Instruction *I =3D dyn_cast<Instruction>(Rem->getOperand(0)))
-      IU->AddUsersIfInteresting(I);
-  }
   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
   ++NumElimRem;
   Changed =3D true;
@@ -375,6 +368,8 @@
=20
 namespace llvm {
=20
+void IVVisitor::anchor() { }
+
 /// simplifyUsersOfIV - Simplify instructions that use this induction vari=
able
 /// by using ScalarEvolution to analyze the IV's recurrence.
 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, LPPassManager=
 *LPM,
@@ -397,36 +392,4 @@
   return Changed;
 }
=20
-/// simplifyIVUsers - Perform simplification on instructions recorded by t=
he
-/// IVUsers pass.
-///
-/// This is the old approach to IV simplification to be replaced by
-/// SimplifyLoopIVs.
-bool simplifyIVUsers(IVUsers *IU, ScalarEvolution *SE, LPPassManager *LPM,
-                     SmallVectorImpl<WeakVH> &Dead) {
-  SimplifyIndvar SIV(IU->getLoop(), SE, LPM, Dead);
-
-  // Each round of simplification involves a round of eliminating operatio=
ns
-  // followed by a round of widening IVs. A single IVUsers worklist is used
-  // across all rounds. The inner loop advances the user. If widening expo=
ses
-  // more uses, then another pass through the outer loop is triggered.
-  for (IVUsers::iterator I =3D IU->begin(); I !=3D IU->end(); ++I) {
-    Instruction *UseInst =3D I->getUser();
-    Value *IVOperand =3D I->getOperandValToReplace();
-
-    if (ICmpInst *ICmp =3D dyn_cast<ICmpInst>(UseInst)) {
-      SIV.eliminateIVComparison(ICmp, IVOperand);
-      continue;
-    }
-    if (BinaryOperator *Rem =3D dyn_cast<BinaryOperator>(UseInst)) {
-      bool IsSigned =3D Rem->getOpcode() =3D=3D Instruction::SRem;
-      if (IsSigned || Rem->getOpcode() =3D=3D Instruction::URem) {
-        SIV.eliminateIVRemainder(Rem, IVOperand, IsSigned);
-        continue;
-      }
-    }
-  }
-  return SIV.hasChanged();
-}
-
 } // namespace llvm
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/SimplifyInstructions.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/SimplifyInstructions.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/SimplifyInstructions.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -24,6 +24,7 @@
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Analysis/InstructionSimplify.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetLibraryInfo.h"
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Transforms/Utils/Local.h"
 using namespace llvm;
@@ -39,12 +40,14 @@
=20
     void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesCFG();
+      AU.addRequired<TargetLibraryInfo>();
     }
=20
     /// runOnFunction - Remove instructions that simplify.
     bool runOnFunction(Function &F) {
       const DominatorTree *DT =3D getAnalysisIfAvailable<DominatorTree>();
       const TargetData *TD =3D getAnalysisIfAvailable<TargetData>();
+      const TargetLibraryInfo *TLI =3D &getAnalysis<TargetLibraryInfo>();
       SmallPtrSet<const Instruction*, 8> S1, S2, *ToSimplify =3D &S1, *Nex=
t =3D &S2;
       bool Changed =3D false;
=20
@@ -60,7 +63,7 @@
               continue;
             // Don't waste time simplifying unused instructions.
             if (!I->use_empty())
-              if (Value *V =3D SimplifyInstruction(I, TD, DT)) {
+              if (Value *V =3D SimplifyInstruction(I, TD, TLI, DT)) {
                 // Mark all uses for resimplification next time round the =
loop.
                 for (Value::use_iterator UI =3D I->use_begin(), UE =3D I->=
use_end();
                      UI !=3D UE; ++UI)
@@ -84,8 +87,11 @@
 }
=20
 char InstSimplifier::ID =3D 0;
-INITIALIZE_PASS(InstSimplifier, "instsimplify", "Remove redundant instruct=
ions",
-                false, false)
+INITIALIZE_PASS_BEGIN(InstSimplifier, "instsimplify",
+                      "Remove redundant instructions", false, false)
+INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
+INITIALIZE_PASS_END(InstSimplifier, "instsimplify",
+                    "Remove redundant instructions", false, false)
 char &llvm::InstructionSimplifierID =3D InstSimplifier::ID;
=20
 // Public interface to the simplify instructions pass.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/Transforms/Utils=
/UnifyFunctionExitNodes.cpp
--- a/head/contrib/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/Transforms/Utils/UnifyFunctionExitNodes.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -50,33 +50,13 @@
   // return.
   //
   std::vector<BasicBlock*> ReturningBlocks;
-  std::vector<BasicBlock*> UnwindingBlocks;
   std::vector<BasicBlock*> UnreachableBlocks;
   for(Function::iterator I =3D F.begin(), E =3D F.end(); I !=3D E; ++I)
     if (isa<ReturnInst>(I->getTerminator()))
       ReturningBlocks.push_back(I);
-    else if (isa<UnwindInst>(I->getTerminator()))
-      UnwindingBlocks.push_back(I);
     else if (isa<UnreachableInst>(I->getTerminator()))
       UnreachableBlocks.push_back(I);
=20
-  // Handle unwinding blocks first.
-  if (UnwindingBlocks.empty()) {
-    UnwindBlock =3D 0;
-  } else if (UnwindingBlocks.size() =3D=3D 1) {
-    UnwindBlock =3D UnwindingBlocks.front();
-  } else {
-    UnwindBlock =3D BasicBlock::Create(F.getContext(), "UnifiedUnwindBlock=
", &F);
-    new UnwindInst(F.getContext(), UnwindBlock);
-
-    for (std::vector<BasicBlock*>::iterator I =3D UnwindingBlocks.begin(),
-           E =3D UnwindingBlocks.end(); I !=3D E; ++I) {
-      BasicBlock *BB =3D *I;
-      BB->getInstList().pop_back();  // Remove the unwind insn
-      BranchInst::Create(UnwindBlock, BB);
-    }
-  }
-
   // Then unreachable blocks.
   if (UnreachableBlocks.empty()) {
     UnreachableBlock =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/AsmWriter=
.cpp
--- a/head/contrib/llvm/lib/VMCore/AsmWriter.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/VMCore/AsmWriter.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -89,7 +89,6 @@
 static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Pref=
ix) {
   assert(!Name.empty() && "Cannot get empty name!");
   switch (Prefix) {
-  default: llvm_unreachable("Bad prefix!");
   case NoPrefix: break;
   case GlobalPrefix: OS << '@'; break;
   case LabelPrefix:  break;
@@ -189,6 +188,7 @@
 void TypePrinting::print(Type *Ty, raw_ostream &OS) {
   switch (Ty->getTypeID()) {
   case Type::VoidTyID:      OS << "void"; break;
+  case Type::HalfTyID:      OS << "half"; break;
   case Type::FloatTyID:     OS << "float"; break;
   case Type::DoubleTyID:    OS << "double"; break;
   case Type::X86_FP80TyID:  OS << "x86_fp80"; break;
@@ -231,7 +231,7 @@
     if (I !=3D NumberedTypes.end())
       OS << '%' << I->second;
     else  // Not enumerated, print the hex address.
-      OS << "%\"type 0x" << STy << '\"';
+      OS << "%\"type " << STy << '\"';
     return;
   }
   case Type::PointerTyID: {
@@ -708,31 +708,37 @@
   }
=20
   if (const ConstantFP *CFP =3D dyn_cast<ConstantFP>(CV)) {
-    if (&CFP->getValueAPF().getSemantics() =3D=3D &APFloat::IEEEdouble ||
-        &CFP->getValueAPF().getSemantics() =3D=3D &APFloat::IEEEsingle) {
+    if (&CFP->getValueAPF().getSemantics() =3D=3D &APFloat::IEEEhalf ||
+        &CFP->getValueAPF().getSemantics() =3D=3D &APFloat::IEEEsingle ||
+        &CFP->getValueAPF().getSemantics() =3D=3D &APFloat::IEEEdouble) {
       // We would like to output the FP constant value in exponential nota=
tion,
       // but we cannot do this if doing so will lose precision.  Check her=
e to
       // make sure that we only output it in exponential format if we can =
parse
       // the value back and get the same value.
       //
       bool ignored;
+      bool isHalf =3D &CFP->getValueAPF().getSemantics()=3D=3D&APFloat::IE=
EEhalf;
       bool isDouble =3D &CFP->getValueAPF().getSemantics()=3D=3D&APFloat::=
IEEEdouble;
-      double Val =3D isDouble ? CFP->getValueAPF().convertToDouble() :
-                              CFP->getValueAPF().convertToFloat();
-      SmallString<128> StrVal;
-      raw_svector_ostream(StrVal) << Val;
+      bool isInf =3D CFP->getValueAPF().isInfinity();
+      bool isNaN =3D CFP->getValueAPF().isNaN();
+      if (!isHalf && !isInf && !isNaN) {
+        double Val =3D isDouble ? CFP->getValueAPF().convertToDouble() :
+                                CFP->getValueAPF().convertToFloat();
+        SmallString<128> StrVal;
+        raw_svector_ostream(StrVal) << Val;
=20
-      // Check to make sure that the stringized number is not some string =
like
-      // "Inf" or NaN, that atof will accept, but the lexer will not.  Che=
ck
-      // that the string matches the "[-+]?[0-9]" regex.
-      //
-      if ((StrVal[0] >=3D '0' && StrVal[0] <=3D '9') ||
-          ((StrVal[0] =3D=3D '-' || StrVal[0] =3D=3D '+') &&
-           (StrVal[1] >=3D '0' && StrVal[1] <=3D '9'))) {
-        // Reparse stringized version!
-        if (atof(StrVal.c_str()) =3D=3D Val) {
-          Out << StrVal.str();
-          return;
+        // Check to make sure that the stringized number is not some strin=
g like
+        // "Inf" or NaN, that atof will accept, but the lexer will not.  C=
heck
+        // that the string matches the "[-+]?[0-9]" regex.
+        //
+        if ((StrVal[0] >=3D '0' && StrVal[0] <=3D '9') ||
+            ((StrVal[0] =3D=3D '-' || StrVal[0] =3D=3D '+') &&
+             (StrVal[1] >=3D '0' && StrVal[1] <=3D '9'))) {
+          // Reparse stringized version!
+          if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() =3D=
=3D Val) {
+            Out << StrVal.str();
+            return;
+          }
         }
       }
       // Otherwise we could not reparse it to exactly the same value, so w=
e must
@@ -743,7 +749,7 @@
              "assuming that double is 64 bits!");
       char Buffer[40];
       APFloat apf =3D CFP->getValueAPF();
-      // Floats are represented in ASCII IR as double, convert.
+      // Halves and floats are represented in ASCII IR as double, convert.
       if (!isDouble)
         apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
                           &ignored);
@@ -823,35 +829,53 @@
   }
=20
   if (const ConstantArray *CA =3D dyn_cast<ConstantArray>(CV)) {
+    Type *ETy =3D CA->getType()->getElementType();
+    Out << '[';
+    TypePrinter.print(ETy, Out);
+    Out << ' ';
+    WriteAsOperandInternal(Out, CA->getOperand(0),
+                           &TypePrinter, Machine,
+                           Context);
+    for (unsigned i =3D 1, e =3D CA->getNumOperands(); i !=3D e; ++i) {
+      Out << ", ";
+      TypePrinter.print(ETy, Out);
+      Out << ' ';
+      WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
+                             Context);
+    }
+    Out << ']';
+    return;
+  }
+ =20
+  if (const ConstantDataArray *CA =3D dyn_cast<ConstantDataArray>(CV)) {
     // As a special case, print the array as a string if it is an array of
     // i8 with ConstantInt values.
-    //
-    Type *ETy =3D CA->getType()->getElementType();
     if (CA->isString()) {
       Out << "c\"";
       PrintEscapedString(CA->getAsString(), Out);
       Out << '"';
-    } else {                // Cannot output in string format...
-      Out << '[';
-      if (CA->getNumOperands()) {
-        TypePrinter.print(ETy, Out);
-        Out << ' ';
-        WriteAsOperandInternal(Out, CA->getOperand(0),
-                               &TypePrinter, Machine,
-                               Context);
-        for (unsigned i =3D 1, e =3D CA->getNumOperands(); i !=3D e; ++i) {
-          Out << ", ";
-          TypePrinter.print(ETy, Out);
-          Out << ' ';
-          WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Mac=
hine,
-                                 Context);
-        }
-      }
-      Out << ']';
+      return;
     }
+
+    Type *ETy =3D CA->getType()->getElementType();
+    Out << '[';
+    TypePrinter.print(ETy, Out);
+    Out << ' ';
+    WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
+                           &TypePrinter, Machine,
+                           Context);
+    for (unsigned i =3D 1, e =3D CA->getNumElements(); i !=3D e; ++i) {
+      Out << ", ";
+      TypePrinter.print(ETy, Out);
+      Out << ' ';
+      WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinte=
r,
+                             Machine, Context);
+    }
+    Out << ']';
     return;
   }
=20
+
   if (const ConstantStruct *CS =3D dyn_cast<ConstantStruct>(CV)) {
     if (CS->getType()->isPacked())
       Out << '<';
@@ -882,21 +906,19 @@
     return;
   }
=20
-  if (const ConstantVector *CP =3D dyn_cast<ConstantVector>(CV)) {
-    Type *ETy =3D CP->getType()->getElementType();
-    assert(CP->getNumOperands() > 0 &&
-           "Number of operands for a PackedConst must be > 0");
+  if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
+    Type *ETy =3D CV->getType()->getVectorElementType();
     Out << '<';
     TypePrinter.print(ETy, Out);
     Out << ' ';
-    WriteAsOperandInternal(Out, CP->getOperand(0), &TypePrinter, Machine,
-                           Context);
-    for (unsigned i =3D 1, e =3D CP->getNumOperands(); i !=3D e; ++i) {
+    WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
+                           Machine, Context);
+    for (unsigned i =3D 1, e =3D CV->getType()->getVectorNumElements(); i =
!=3D e;++i){
       Out << ", ";
       TypePrinter.print(ETy, Out);
       Out << ' ';
-      WriteAsOperandInternal(Out, CP->getOperand(i), &TypePrinter, Machine,
-                             Context);
+      WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
+                             Machine, Context);
     }
     Out << '>';
     return;
@@ -1162,7 +1184,6 @@
     return;
=20
   switch (SynchScope) {
-  default: Out << " <bad scope " << int(SynchScope) << ">"; break;
   case SingleThread: Out << " singlethread"; break;
   case CrossThread: break;
   }
@@ -1710,13 +1731,12 @@
     Out << ", ";
     writeOperand(SI.getDefaultDest(), true);
     Out << " [";
-    // Skip the first item since that's the default case.
-    unsigned NumCases =3D SI.getNumCases();
-    for (unsigned i =3D 1; i < NumCases; ++i) {
+    for (SwitchInst::CaseIt i =3D SI.case_begin(), e =3D SI.case_end();
+         i !=3D e; ++i) {
       Out << "\n    ";
-      writeOperand(SI.getCaseValue(i), true);
+      writeOperand(i.getCaseValue(), true);
       Out << ", ";
-      writeOperand(SI.getSuccessor(i), true);
+      writeOperand(i.getCaseSuccessor(), true);
     }
     Out << "\n  ]";
   } else if (isa<IndirectBrInst>(I)) {
@@ -1988,7 +2008,7 @@
   if (!CI) return;
   APInt Val =3D CI->getValue();
   APInt Tag =3D Val & ~APInt(Val.getBitWidth(), LLVMDebugVersionMask);
-  if (Val.ult(LLVMDebugVersion))
+  if (Val.ult(LLVMDebugVersion11))
     return;
=20
   Out.PadToColumn(50);
@@ -2110,3 +2130,6 @@
=20
 // Module::dump() - Allow printing of Modules from the debugger.
 void Module::dump() const { print(dbgs(), 0); }
+
+// NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
+void NamedMDNode::dump() const { print(dbgs(), 0); }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Attribute=
s.cpp
--- a/head/contrib/llvm/lib/VMCore/Attributes.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/VMCore/Attributes.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -76,6 +76,8 @@
     Result +=3D "naked ";
   if (Attrs & Attribute::NonLazyBind)
     Result +=3D "nonlazybind ";
+  if (Attrs & Attribute::AddressSafety)
+    Result +=3D "address_safety ";
   if (Attrs & Attribute::StackAlignment) {
     Result +=3D "alignstack(";
     Result +=3D utostr(Attribute::getStackAlignmentFromAttrs(Attrs));
@@ -152,8 +154,10 @@
   }
   static void Profile(FoldingSetNodeID &ID, const AttributeWithIndex *Attr,
                       unsigned NumAttrs) {
-    for (unsigned i =3D 0; i !=3D NumAttrs; ++i)
-      ID.AddInteger(uint64_t(Attr[i].Attrs) << 32 | unsigned(Attr[i].Index=
));
+    for (unsigned i =3D 0; i !=3D NumAttrs; ++i) {
+      ID.AddInteger(Attr[i].Attrs.Raw());
+      ID.AddInteger(Attr[i].Index);
+    }
   }
 };
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/AutoUpgra=
de.cpp
--- a/head/contrib/llvm/lib/VMCore/AutoUpgrade.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/VMCore/AutoUpgrade.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -38,105 +38,31 @@
     return false;
   Name =3D Name.substr(5); // Strip off "llvm."
=20
-  FunctionType *FTy =3D F->getFunctionType();
-  Module *M =3D F->getParent();
- =20
   switch (Name[0]) {
   default: break;
-  case 'a':
-    if (Name.startswith("atomic.cmp.swap") ||
-        Name.startswith("atomic.swap") ||
-        Name.startswith("atomic.load.add") ||
-        Name.startswith("atomic.load.sub") ||
-        Name.startswith("atomic.load.and") ||
-        Name.startswith("atomic.load.nand") ||
-        Name.startswith("atomic.load.or") ||
-        Name.startswith("atomic.load.xor") ||
-        Name.startswith("atomic.load.max") ||
-        Name.startswith("atomic.load.min") ||
-        Name.startswith("atomic.load.umax") ||
-        Name.startswith("atomic.load.umin"))
-      return true;
-  case 'i':
-    //  This upgrades the old llvm.init.trampoline to the new
-    //  llvm.init.trampoline and llvm.adjust.trampoline pair.
-    if (Name =3D=3D "init.trampoline") {
-      // The new llvm.init.trampoline returns nothing.
-      if (FTy->getReturnType()->isVoidTy())
-        break;
-
-      assert(FTy->getNumParams() =3D=3D 3 && "old init.trampoline takes 3 =
args!");
-
-      // Change the name of the old intrinsic so that we can play with its=
 type.
-      std::string NameTmp =3D F->getName();
-      F->setName("");
-      NewFn =3D cast<Function>(M->getOrInsertFunction(
-                               NameTmp,
-                               Type::getVoidTy(M->getContext()),
-                               FTy->getParamType(0), FTy->getParamType(1),
-                               FTy->getParamType(2), (Type *)0));
+  case 'c': {
+    if (Name.startswith("ctlz.") && F->arg_size() =3D=3D 1) {
+      F->setName(Name + ".old");
+      NewFn =3D Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
+                                        F->arg_begin()->getType());
       return true;
     }
-  case 'm':
-    if (Name =3D=3D "memory.barrier")
-      return true;
-  case 'p':
-    //  This upgrades the llvm.prefetch intrinsic to accept one more param=
eter,
-    //  which is a instruction / data cache identifier. The old version on=
ly
-    //  implicitly accepted the data version.
-    if (Name =3D=3D "prefetch") {
-      // Don't do anything if it has the correct number of arguments alrea=
dy
-      if (FTy->getNumParams() =3D=3D 4)
-        break;
-
-      assert(FTy->getNumParams() =3D=3D 3 && "old prefetch takes 3 args!");
-      //  We first need to change the name of the old (bad) intrinsic, bec=
ause
-      //  its type is incorrect, but we cannot overload that name. We
-      //  arbitrarily unique it here allowing us to construct a correctly =
named
-      //  and typed function below.
-      std::string NameTmp =3D F->getName();
-      F->setName("");
-      NewFn =3D cast<Function>(M->getOrInsertFunction(NameTmp,
-                                                    FTy->getReturnType(),
-                                                    FTy->getParamType(0),
-                                                    FTy->getParamType(1),
-                                                    FTy->getParamType(2),
-                                                    FTy->getParamType(2),
-                                                    (Type*)0));
+    if (Name.startswith("cttz.") && F->arg_size() =3D=3D 1) {
+      F->setName(Name + ".old");
+      NewFn =3D Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
+                                        F->arg_begin()->getType());
       return true;
     }
-
     break;
+  }
   case 'x': {
-    const char *NewFnName =3D NULL;
-    // This fixes the poorly named crc32 intrinsics.
-    if (Name =3D=3D "x86.sse42.crc32.8")
-      NewFnName =3D "llvm.x86.sse42.crc32.32.8";
-    else if (Name =3D=3D "x86.sse42.crc32.16")
-      NewFnName =3D "llvm.x86.sse42.crc32.32.16";
-    else if (Name =3D=3D "x86.sse42.crc32.32")
-      NewFnName =3D "llvm.x86.sse42.crc32.32.32";
-    else if (Name =3D=3D "x86.sse42.crc64.8")
-      NewFnName =3D "llvm.x86.sse42.crc32.64.8";
-    else if (Name =3D=3D "x86.sse42.crc64.64")
-      NewFnName =3D "llvm.x86.sse42.crc32.64.64";
-   =20
-    if (NewFnName) {
-      F->setName(NewFnName);
-      NewFn =3D F;
+    if (Name.startswith("x86.sse2.pcmpeq.") ||
+        Name.startswith("x86.sse2.pcmpgt.") ||
+        Name.startswith("x86.avx2.pcmpeq.") ||
+        Name.startswith("x86.avx2.pcmpgt.")) {
+      NewFn =3D 0;
       return true;
     }
-
-    // Calls to these instructions are transformed into unaligned loads.
-    if (Name =3D=3D "x86.sse.loadu.ps" || Name =3D=3D "x86.sse2.loadu.dq" =
||
-        Name =3D=3D "x86.sse2.loadu.pd")
-      return true;
-     =20
-    // Calls to these instructions are transformed into nontemporal stores.
-    if (Name =3D=3D "x86.sse.movnt.ps"  || Name =3D=3D "x86.sse2.movnt.dq"=
 ||
-        Name =3D=3D "x86.sse2.movnt.pd" || Name =3D=3D "x86.sse2.movnt.i")
-      return true;
-
     break;
   }
   }
@@ -171,188 +97,52 @@
 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
   Function *F =3D CI->getCalledFunction();
   LLVMContext &C =3D CI->getContext();
-  ImmutableCallSite CS(CI);
+  IRBuilder<> Builder(C);
+  Builder.SetInsertPoint(CI->getParent(), CI);
=20
-  assert(F && "CallInst has no function associated with it.");
+  assert(F && "Intrinsic call is not direct?");
=20
   if (!NewFn) {
-    if (F->getName() =3D=3D "llvm.x86.sse.loadu.ps" ||
-        F->getName() =3D=3D "llvm.x86.sse2.loadu.dq" ||
-        F->getName() =3D=3D "llvm.x86.sse2.loadu.pd") {
-      // Convert to a native, unaligned load.
-      Type *VecTy =3D CI->getType();
-      Type *IntTy =3D IntegerType::get(C, 128);
-      IRBuilder<> Builder(C);
-      Builder.SetInsertPoint(CI->getParent(), CI);
+    // Get the Function's name.
+    StringRef Name =3D F->getName();
=20
-      Value *BC =3D Builder.CreateBitCast(CI->getArgOperand(0),
-                                        PointerType::getUnqual(IntTy),
-                                        "cast");
-      LoadInst *LI =3D Builder.CreateLoad(BC, CI->getName());
-      LI->setAlignment(1);      // Unaligned load.
-      BC =3D Builder.CreateBitCast(LI, VecTy, "new.cast");
-
-      // Fix up all the uses with our new load.
-      if (!CI->use_empty())
-        CI->replaceAllUsesWith(BC);
-
-      // Remove intrinsic.
-      CI->eraseFromParent();
-    } else if (F->getName() =3D=3D "llvm.x86.sse.movnt.ps" ||
-               F->getName() =3D=3D "llvm.x86.sse2.movnt.dq" ||
-               F->getName() =3D=3D "llvm.x86.sse2.movnt.pd" ||
-               F->getName() =3D=3D "llvm.x86.sse2.movnt.i") {
-      IRBuilder<> Builder(C);
-      Builder.SetInsertPoint(CI->getParent(), CI);
-
-      Module *M =3D F->getParent();
-      SmallVector<Value *, 1> Elts;
-      Elts.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
-      MDNode *Node =3D MDNode::get(C, Elts);
-
-      Value *Arg0 =3D CI->getArgOperand(0);
-      Value *Arg1 =3D CI->getArgOperand(1);
-
-      // Convert the type of the pointer to a pointer to the stored type.
-      Value *BC =3D Builder.CreateBitCast(Arg0,
-                                        PointerType::getUnqual(Arg1->getTy=
pe()),
-                                        "cast");
-      StoreInst *SI =3D Builder.CreateStore(Arg1, BC);
-      SI->setMetadata(M->getMDKindID("nontemporal"), Node);
-      SI->setAlignment(16);
-
-      // Remove intrinsic.
-      CI->eraseFromParent();
-    } else if (F->getName().startswith("llvm.atomic.cmp.swap")) {
-      IRBuilder<> Builder(C);
-      Builder.SetInsertPoint(CI->getParent(), CI);
-      Value *Val =3D Builder.CreateAtomicCmpXchg(CI->getArgOperand(0),
-                                               CI->getArgOperand(1),
-                                               CI->getArgOperand(2),
-                                               Monotonic);
-
-      // Replace intrinsic.
-      Val->takeName(CI);
-      if (!CI->use_empty())
-        CI->replaceAllUsesWith(Val);
-      CI->eraseFromParent();
-    } else if (F->getName().startswith("llvm.atomic")) {
-      IRBuilder<> Builder(C);
-      Builder.SetInsertPoint(CI->getParent(), CI);
-
-      AtomicRMWInst::BinOp Op;
-      if (F->getName().startswith("llvm.atomic.swap"))
-        Op =3D AtomicRMWInst::Xchg;
-      else if (F->getName().startswith("llvm.atomic.load.add"))
-        Op =3D AtomicRMWInst::Add;
-      else if (F->getName().startswith("llvm.atomic.load.sub"))
-        Op =3D AtomicRMWInst::Sub;
-      else if (F->getName().startswith("llvm.atomic.load.and"))
-        Op =3D AtomicRMWInst::And;
-      else if (F->getName().startswith("llvm.atomic.load.nand"))
-        Op =3D AtomicRMWInst::Nand;
-      else if (F->getName().startswith("llvm.atomic.load.or"))
-        Op =3D AtomicRMWInst::Or;
-      else if (F->getName().startswith("llvm.atomic.load.xor"))
-        Op =3D AtomicRMWInst::Xor;
-      else if (F->getName().startswith("llvm.atomic.load.max"))
-        Op =3D AtomicRMWInst::Max;
-      else if (F->getName().startswith("llvm.atomic.load.min"))
-        Op =3D AtomicRMWInst::Min;
-      else if (F->getName().startswith("llvm.atomic.load.umax"))
-        Op =3D AtomicRMWInst::UMax;
-      else if (F->getName().startswith("llvm.atomic.load.umin"))
-        Op =3D AtomicRMWInst::UMin;
-      else
-        llvm_unreachable("Unknown atomic");
-
-      Value *Val =3D Builder.CreateAtomicRMW(Op, CI->getArgOperand(0),
-                                           CI->getArgOperand(1),
-                                           Monotonic);
-
-      // Replace intrinsic.
-      Val->takeName(CI);
-      if (!CI->use_empty())
-        CI->replaceAllUsesWith(Val);
-      CI->eraseFromParent();
-    } else if (F->getName() =3D=3D "llvm.memory.barrier") {
-      IRBuilder<> Builder(C);
-      Builder.SetInsertPoint(CI->getParent(), CI);
-
-      // Note that this conversion ignores the "device" bit; it was not re=
ally
-      // well-defined, and got abused because nobody paid enough attention=
 to
-      // get it right. In practice, this probably doesn't matter; applicat=
ion
-      // code generally doesn't need anything stronger than
-      // SequentiallyConsistent (and realistically, SequentiallyConsistent
-      // is lowered to a strong enough barrier for almost anything).
-
-      if (cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue())
-        Builder.CreateFence(SequentiallyConsistent);
-      else if (!cast<ConstantInt>(CI->getArgOperand(0))->getZExtValue())
-        Builder.CreateFence(Release);
-      else if (!cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue())
-        Builder.CreateFence(Acquire);
-      else
-        Builder.CreateFence(AcquireRelease);
-
-      // Remove intrinsic.
-      CI->eraseFromParent();
+    Value *Rep;
+    // Upgrade packed integer vector compares intrinsics to compare instru=
ctions
+    if (Name.startswith("llvm.x86.sse2.pcmpeq.") ||
+        Name.startswith("llvm.x86.avx2.pcmpeq.")) {
+      Rep =3D Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand=
(1),
+                                 "pcmpeq");
+      // need to sign extend since icmp returns vector of i1
+      Rep =3D Builder.CreateSExt(Rep, CI->getType(), "");
+    } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") ||
+               Name.startswith("llvm.x86.avx2.pcmpgt.")) {
+      Rep =3D Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperan=
d(1),
+                                  "pcmpgt");
+      // need to sign extend since icmp returns vector of i1
+      Rep =3D Builder.CreateSExt(Rep, CI->getType(), "");
     } else {
       llvm_unreachable("Unknown function for CallInst upgrade.");
     }
+
+    CI->replaceAllUsesWith(Rep);
+    CI->eraseFromParent();
     return;
   }
=20
   switch (NewFn->getIntrinsicID()) {
-  case Intrinsic::prefetch: {
-    IRBuilder<> Builder(C);
-    Builder.SetInsertPoint(CI->getParent(), CI);
-    llvm::Type *I32Ty =3D llvm::Type::getInt32Ty(CI->getContext());
+  default:
+    llvm_unreachable("Unknown function for CallInst upgrade.");
=20
-    // Add the extra "data cache" argument
-    Value *Operands[4] =3D { CI->getArgOperand(0), CI->getArgOperand(1),
-                           CI->getArgOperand(2),
-                           llvm::ConstantInt::get(I32Ty, 1) };
-    CallInst *NewCI =3D CallInst::Create(NewFn, Operands,
-                                       CI->getName(), CI);
-    NewCI->setTailCall(CI->isTailCall());
-    NewCI->setCallingConv(CI->getCallingConv());
-    //  Handle any uses of the old CallInst.
-    if (!CI->use_empty())
-      //  Replace all uses of the old call with the new cast which has the
-      //  correct type.
-      CI->replaceAllUsesWith(NewCI);
-
-    //  Clean up the old call now that it has been completely upgraded.
+  case Intrinsic::ctlz:
+  case Intrinsic::cttz:
+    assert(CI->getNumArgOperands() =3D=3D 1 &&
+           "Mismatch between function args and call args");
+    StringRef Name =3D CI->getName();
+    CI->setName(Name + ".old");
+    CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
+                                               Builder.getFalse(), Name));
     CI->eraseFromParent();
-    break;
-  }
-  case Intrinsic::init_trampoline: {
-
-    //  Transform
-    //    %tramp =3D call i8* llvm.init.trampoline (i8* x, i8* y, i8* z)
-    //  to
-    //    call void llvm.init.trampoline (i8* %x, i8* %y, i8* %z)
-    //    %tramp =3D call i8* llvm.adjust.trampoline (i8* %x)
-
-    Function *AdjustTrampolineFn =3D
-      cast<Function>(Intrinsic::getDeclaration(F->getParent(),
-                                               Intrinsic::adjust_trampolin=
e));
-
-    IRBuilder<> Builder(C);
-    Builder.SetInsertPoint(CI);
-
-    Builder.CreateCall3(NewFn, CI->getArgOperand(0), CI->getArgOperand(1),
-                        CI->getArgOperand(2));
-
-    CallInst *AdjustCall =3D Builder.CreateCall(AdjustTrampolineFn,
-                                              CI->getArgOperand(0),
-                                              CI->getName());
-    if (!CI->use_empty())
-      CI->replaceAllUsesWith(AdjustCall);
-    CI->eraseFromParent();
-    break;
-  }
+    return;
   }
 }
=20
@@ -378,291 +168,3 @@
   }
 }
=20
-/// This function strips all debug info intrinsics, except for llvm.dbg.de=
clare.
-/// If an llvm.dbg.declare intrinsic is invalid, then this function simply
-/// strips that use.
-void llvm::CheckDebugInfoIntrinsics(Module *M) {
-  if (Function *FuncStart =3D M->getFunction("llvm.dbg.func.start")) {
-    while (!FuncStart->use_empty())
-      cast<CallInst>(FuncStart->use_back())->eraseFromParent();
-    FuncStart->eraseFromParent();
-  }
- =20
-  if (Function *StopPoint =3D M->getFunction("llvm.dbg.stoppoint")) {
-    while (!StopPoint->use_empty())
-      cast<CallInst>(StopPoint->use_back())->eraseFromParent();
-    StopPoint->eraseFromParent();
-  }
-
-  if (Function *RegionStart =3D M->getFunction("llvm.dbg.region.start")) {
-    while (!RegionStart->use_empty())
-      cast<CallInst>(RegionStart->use_back())->eraseFromParent();
-    RegionStart->eraseFromParent();
-  }
-
-  if (Function *RegionEnd =3D M->getFunction("llvm.dbg.region.end")) {
-    while (!RegionEnd->use_empty())
-      cast<CallInst>(RegionEnd->use_back())->eraseFromParent();
-    RegionEnd->eraseFromParent();
-  }
- =20
-  if (Function *Declare =3D M->getFunction("llvm.dbg.declare")) {
-    if (!Declare->use_empty()) {
-      DbgDeclareInst *DDI =3D cast<DbgDeclareInst>(Declare->use_back());
-      if (!isa<MDNode>(DDI->getArgOperand(0)) ||
-          !isa<MDNode>(DDI->getArgOperand(1))) {
-        while (!Declare->use_empty()) {
-          CallInst *CI =3D cast<CallInst>(Declare->use_back());
-          CI->eraseFromParent();
-        }
-        Declare->eraseFromParent();
-      }
-    }
-  }
-}
-
-/// FindExnAndSelIntrinsics - Find the eh_exception and eh_selector intrin=
sic
-/// calls reachable from the unwind basic block.
-static void FindExnAndSelIntrinsics(BasicBlock *BB, CallInst *&Exn,
-                                    CallInst *&Sel,
-                                    SmallPtrSet<BasicBlock*, 8> &Visited) {
-  if (!Visited.insert(BB)) return;
-
-  for (BasicBlock::iterator
-         I =3D BB->begin(), E =3D BB->end(); I !=3D E; ++I) {
-    if (CallInst *CI =3D dyn_cast<CallInst>(I)) {
-      switch (CI->getCalledFunction()->getIntrinsicID()) {
-      default: break;
-      case Intrinsic::eh_exception:
-        assert(!Exn && "Found more than one eh.exception call!");
-        Exn =3D CI;
-        break;
-      case Intrinsic::eh_selector:
-        assert(!Sel && "Found more than one eh.selector call!");
-        Sel =3D CI;
-        break;
-      }
-
-      if (Exn && Sel) return;
-    }
-  }
-
-  if (Exn && Sel) return;
-
-  for (succ_iterator I =3D succ_begin(BB), E =3D succ_end(BB); I !=3D E; +=
+I) {
-    FindExnAndSelIntrinsics(*I, Exn, Sel, Visited);
-    if (Exn && Sel) return;
-  }
-}
-
-/// TransferClausesToLandingPadInst - Transfer the exception handling clau=
ses
-/// from the eh_selector call to the new landingpad instruction.
-static void TransferClausesToLandingPadInst(LandingPadInst *LPI,
-                                            CallInst *EHSel) {
-  LLVMContext &Context =3D LPI->getContext();
-  unsigned N =3D EHSel->getNumArgOperands();
-
-  for (unsigned i =3D N - 1; i > 1; --i) {
-    if (const ConstantInt *CI =3D dyn_cast<ConstantInt>(EHSel->getArgOpera=
nd(i))){
-      unsigned FilterLength =3D CI->getZExtValue();
-      unsigned FirstCatch =3D i + FilterLength + !FilterLength;
-      assert(FirstCatch <=3D N && "Invalid filter length");
-
-      if (FirstCatch < N)
-        for (unsigned j =3D FirstCatch; j < N; ++j) {
-          Value *Val =3D EHSel->getArgOperand(j);
-          if (!Val->hasName() || Val->getName() !=3D "llvm.eh.catch.all.va=
lue") {
-            LPI->addClause(EHSel->getArgOperand(j));
-          } else {
-            GlobalVariable *GV =3D cast<GlobalVariable>(Val);
-            LPI->addClause(GV->getInitializer());
-          }
-        }
-
-      if (!FilterLength) {
-        // Cleanup.
-        LPI->setCleanup(true);
-      } else {
-        // Filter.
-        SmallVector<Constant *, 4> TyInfo;
-        TyInfo.reserve(FilterLength - 1);
-        for (unsigned j =3D i + 1; j < FirstCatch; ++j)
-          TyInfo.push_back(cast<Constant>(EHSel->getArgOperand(j)));
-        ArrayType *AType =3D
-          ArrayType::get(!TyInfo.empty() ? TyInfo[0]->getType() :
-                         PointerType::getUnqual(Type::getInt8Ty(Context)),
-                         TyInfo.size());
-        LPI->addClause(ConstantArray::get(AType, TyInfo));
-      }
-
-      N =3D i;
-    }
-  }
-
-  if (N > 2)
-    for (unsigned j =3D 2; j < N; ++j) {
-      Value *Val =3D EHSel->getArgOperand(j);
-      if (!Val->hasName() || Val->getName() !=3D "llvm.eh.catch.all.value"=
) {
-        LPI->addClause(EHSel->getArgOperand(j));
-      } else {
-        GlobalVariable *GV =3D cast<GlobalVariable>(Val);
-        LPI->addClause(GV->getInitializer());
-      }
-    }
-}
-
-/// This function upgrades the old pre-3.0 exception handling system to th=
e new
-/// one. N.B. This will be removed in 3.1.
-void llvm::UpgradeExceptionHandling(Module *M) {
-  Function *EHException =3D M->getFunction("llvm.eh.exception");
-  Function *EHSelector =3D M->getFunction("llvm.eh.selector");
-  if (!EHException || !EHSelector)
-    return;
-
-  LLVMContext &Context =3D M->getContext();
-  Type *ExnTy =3D PointerType::getUnqual(Type::getInt8Ty(Context));
-  Type *SelTy =3D Type::getInt32Ty(Context);
-  Type *LPadSlotTy =3D StructType::get(ExnTy, SelTy, NULL);
-
-  // This map links the invoke instruction with the eh.exception and eh.se=
lector
-  // calls associated with it.
-  DenseMap<InvokeInst*, std::pair<Value*, Value*> > InvokeToIntrinsicsMap;
-  for (Module::iterator
-         I =3D M->begin(), E =3D M->end(); I !=3D E; ++I) {
-    Function &F =3D *I;
-
-    for (Function::iterator
-           II =3D F.begin(), IE =3D F.end(); II !=3D IE; ++II) {
-      BasicBlock *BB =3D &*II;
-      InvokeInst *Inst =3D dyn_cast<InvokeInst>(BB->getTerminator());
-      if (!Inst) continue;
-      BasicBlock *UnwindDest =3D Inst->getUnwindDest();
-      if (UnwindDest->isLandingPad()) continue; // Already converted.
-
-      SmallPtrSet<BasicBlock*, 8> Visited;
-      CallInst *Exn =3D 0;
-      CallInst *Sel =3D 0;
-      FindExnAndSelIntrinsics(UnwindDest, Exn, Sel, Visited);
-      assert(Exn && Sel && "Cannot find eh.exception and eh.selector calls=
!");
-      InvokeToIntrinsicsMap[Inst] =3D std::make_pair(Exn, Sel);
-    }
-  }
-
-  // This map stores the slots where the exception object and selector val=
ue are
-  // stored within a function.
-  DenseMap<Function*, std::pair<Value*, Value*> > FnToLPadSlotMap;
-  SmallPtrSet<Instruction*, 32> DeadInsts;
-  for (DenseMap<InvokeInst*, std::pair<Value*, Value*> >::iterator
-         I =3D InvokeToIntrinsicsMap.begin(), E =3D InvokeToIntrinsicsMap.=
end();
-       I !=3D E; ++I) {
-    InvokeInst *Invoke =3D I->first;
-    BasicBlock *UnwindDest =3D Invoke->getUnwindDest();
-    Function *F =3D UnwindDest->getParent();
-    std::pair<Value*, Value*> EHIntrinsics =3D I->second;
-    CallInst *Exn =3D cast<CallInst>(EHIntrinsics.first);
-    CallInst *Sel =3D cast<CallInst>(EHIntrinsics.second);
-
-    // Store the exception object and selector value in the entry block.
-    Value *ExnSlot =3D 0;
-    Value *SelSlot =3D 0;
-    if (!FnToLPadSlotMap[F].first) {
-      BasicBlock *Entry =3D &F->front();
-      ExnSlot =3D new AllocaInst(ExnTy, "exn", Entry->getTerminator());
-      SelSlot =3D new AllocaInst(SelTy, "sel", Entry->getTerminator());
-      FnToLPadSlotMap[F] =3D std::make_pair(ExnSlot, SelSlot);
-    } else {
-      ExnSlot =3D FnToLPadSlotMap[F].first;
-      SelSlot =3D FnToLPadSlotMap[F].second;
-    }
-
-    if (!UnwindDest->getSinglePredecessor()) {
-      // The unwind destination doesn't have a single predecessor. Create =
an
-      // unwind destination which has only one predecessor.
-      BasicBlock *NewBB =3D BasicBlock::Create(Context, "new.lpad",
-                                             UnwindDest->getParent());
-      BranchInst::Create(UnwindDest, NewBB);
-      Invoke->setUnwindDest(NewBB);
-
-      // Fix up any PHIs in the original unwind destination block.
-      for (BasicBlock::iterator
-             II =3D UnwindDest->begin(); isa<PHINode>(II); ++II) {
-        PHINode *PN =3D cast<PHINode>(II);
-        int Idx =3D PN->getBasicBlockIndex(Invoke->getParent());
-        if (Idx =3D=3D -1) continue;
-        PN->setIncomingBlock(Idx, NewBB);
-      }
-
-      UnwindDest =3D NewBB;
-    }
-
-    IRBuilder<> Builder(Context);
-    Builder.SetInsertPoint(UnwindDest, UnwindDest->getFirstInsertionPt());
-
-    Value *PersFn =3D Sel->getArgOperand(1);
-    LandingPadInst *LPI =3D Builder.CreateLandingPad(LPadSlotTy, PersFn, 0=
);
-    Value *LPExn =3D Builder.CreateExtractValue(LPI, 0);
-    Value *LPSel =3D Builder.CreateExtractValue(LPI, 1);
-    Builder.CreateStore(LPExn, ExnSlot);
-    Builder.CreateStore(LPSel, SelSlot);
-
-    TransferClausesToLandingPadInst(LPI, Sel);
-
-    DeadInsts.insert(Exn);
-    DeadInsts.insert(Sel);
-  }
-
-  // Replace the old intrinsic calls with the values from the landingpad
-  // instruction(s). These values were stored in allocas for us to use her=
e.
-  for (DenseMap<InvokeInst*, std::pair<Value*, Value*> >::iterator
-         I =3D InvokeToIntrinsicsMap.begin(), E =3D InvokeToIntrinsicsMap.=
end();
-       I !=3D E; ++I) {
-    std::pair<Value*, Value*> EHIntrinsics =3D I->second;
-    CallInst *Exn =3D cast<CallInst>(EHIntrinsics.first);
-    CallInst *Sel =3D cast<CallInst>(EHIntrinsics.second);
-    BasicBlock *Parent =3D Exn->getParent();
-
-    std::pair<Value*,Value*> ExnSelSlots =3D FnToLPadSlotMap[Parent->getPa=
rent()];
-
-    IRBuilder<> Builder(Context);
-    Builder.SetInsertPoint(Parent, Exn);
-    LoadInst *LPExn =3D Builder.CreateLoad(ExnSelSlots.first, "exn.load");
-    LoadInst *LPSel =3D Builder.CreateLoad(ExnSelSlots.second, "sel.load");
-
-    Exn->replaceAllUsesWith(LPExn);
-    Sel->replaceAllUsesWith(LPSel);
-  }
-
-  // Remove the dead instructions.
-  for (SmallPtrSet<Instruction*, 32>::iterator
-         I =3D DeadInsts.begin(), E =3D DeadInsts.end(); I !=3D E; ++I) {
-    Instruction *Inst =3D *I;
-    Inst->eraseFromParent();
-  }
-
-  // Replace calls to "llvm.eh.resume" with the 'resume' instruction. Load=
 the
-  // exception and selector values from the stored place.
-  Function *EHResume =3D M->getFunction("llvm.eh.resume");
-  if (!EHResume) return;
-
-  while (!EHResume->use_empty()) {
-    CallInst *Resume =3D cast<CallInst>(EHResume->use_back());
-    BasicBlock *BB =3D Resume->getParent();
-
-    IRBuilder<> Builder(Context);
-    Builder.SetInsertPoint(BB, Resume);
-
-    Value *LPadVal =3D
-      Builder.CreateInsertValue(UndefValue::get(LPadSlotTy),
-                                Resume->getArgOperand(0), 0, "lpad.val");
-    LPadVal =3D Builder.CreateInsertValue(LPadVal, Resume->getArgOperand(1=
),
-                                        1, "lpad.val");
-    Builder.CreateResume(LPadVal);
-
-    // Remove all instructions after the 'resume.'
-    BasicBlock::iterator I =3D Resume;
-    while (I !=3D BB->end()) {
-      Instruction *Inst =3D &*I++;
-      Inst->eraseFromParent();
-    }
-  }
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/BasicBloc=
k.cpp
--- a/head/contrib/llvm/lib/VMCore/BasicBlock.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/VMCore/BasicBlock.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -366,3 +366,6 @@
 LandingPadInst *BasicBlock::getLandingPadInst() {
   return dyn_cast<LandingPadInst>(getFirstNonPHI());
 }
+const LandingPadInst *BasicBlock::getLandingPadInst() const {
+  return dyn_cast<LandingPadInst>(getFirstNonPHI());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/ConstantF=
old.cpp
--- a/head/contrib/llvm/lib/VMCore/ConstantFold.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/VMCore/ConstantFold.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -38,11 +38,10 @@
 //                ConstantFold*Instruction Implementations
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-/// BitCastConstantVector - Convert the specified ConstantVector node to t=
he
+/// BitCastConstantVector - Convert the specified vector Constant node to =
the
 /// specified vector type.  At this point, we know that the elements of the
 /// input vector constant are all simple integer or FP values.
-static Constant *BitCastConstantVector(ConstantVector *CV,
-                                       VectorType *DstTy) {
+static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
=20
   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
@@ -51,22 +50,21 @@
   // doing so requires endianness information.  This should be handled by
   // Analysis/ConstantFolding.cpp
   unsigned NumElts =3D DstTy->getNumElements();
-  if (NumElts !=3D CV->getNumOperands())
+  if (NumElts !=3D CV->getType()->getVectorNumElements())
     return 0;
+ =20
+  Type *DstEltTy =3D DstTy->getElementType();
=20
   // Check to verify that all elements of the input are simple.
+  SmallVector<Constant*, 16> Result;
   for (unsigned i =3D 0; i !=3D NumElts; ++i) {
-    if (!isa<ConstantInt>(CV->getOperand(i)) &&
-        !isa<ConstantFP>(CV->getOperand(i)))
-      return 0;
+    Constant *C =3D CV->getAggregateElement(i);
+    if (C =3D=3D 0) return 0;
+    C =3D ConstantExpr::getBitCast(C, DstEltTy);
+    if (isa<ConstantExpr>(C)) return 0;
+    Result.push_back(C);
   }
=20
-  // Bitcast each element now.
-  std::vector<Constant*> Result;
-  Type *DstEltTy =3D DstTy->getElementType();
-  for (unsigned i =3D 0; i !=3D NumElts; ++i)
-    Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i),
-                                                    DstEltTy));
   return ConstantVector::get(Result);
 }
=20
@@ -104,7 +102,8 @@
   // the first element.  If so, return the appropriate GEP instruction.
   if (PointerType *PTy =3D dyn_cast<PointerType>(V->getType()))
     if (PointerType *DPTy =3D dyn_cast<PointerType>(DestTy))
-      if (PTy->getAddressSpace() =3D=3D DPTy->getAddressSpace()) {
+      if (PTy->getAddressSpace() =3D=3D DPTy->getAddressSpace()
+          && DPTy->getElementType()->isSized()) {
         SmallVector<Value*, 8> IdxList;
         Value *Zero =3D
           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
@@ -141,8 +140,8 @@
       if (isa<ConstantAggregateZero>(V))
         return Constant::getNullValue(DestTy);
=20
-      if (ConstantVector *CV =3D dyn_cast<ConstantVector>(V))
-        return BitCastConstantVector(CV, DestPTy);
+      // Handle ConstantVector and ConstantAggregateVector.
+      return BitCastConstantVector(V, DestPTy);
     }
=20
     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcas=
ts
@@ -548,18 +547,17 @@
   // If the cast operand is a constant vector, perform the cast by
   // operating on each element. In the cast of bitcasts, the element
   // count may be mismatched; don't attempt to handle that here.
-  if (ConstantVector *CV =3D dyn_cast<ConstantVector>(V))
-    if (DestTy->isVectorTy() &&
-        cast<VectorType>(DestTy)->getNumElements() =3D=3D
-        CV->getType()->getNumElements()) {
-      std::vector<Constant*> res;
-      VectorType *DestVecTy =3D cast<VectorType>(DestTy);
-      Type *DstEltTy =3D DestVecTy->getElementType();
-      for (unsigned i =3D 0, e =3D CV->getType()->getNumElements(); i !=3D=
 e; ++i)
-        res.push_back(ConstantExpr::getCast(opc,
-                                            CV->getOperand(i), DstEltTy));
-      return ConstantVector::get(res);
-    }
+  if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
+      DestTy->isVectorTy() &&
+      DestTy->getVectorNumElements() =3D=3D V->getType()->getVectorNumElem=
ents()) {
+    SmallVector<Constant*, 16> res;
+    VectorType *DestVecTy =3D cast<VectorType>(DestTy);
+    Type *DstEltTy =3D DestVecTy->getElementType();
+    for (unsigned i =3D 0, e =3D V->getType()->getVectorNumElements(); i !=
=3D e; ++i)
+      res.push_back(ConstantExpr::getCast(opc,
+                                          V->getAggregateElement(i), DstEl=
tTy));
+    return ConstantVector::get(res);
+  }
=20
   // We actually have to do a cast now. Perform the cast according to the
   // opcode specified.
@@ -571,7 +569,8 @@
     if (ConstantFP *FPC =3D dyn_cast<ConstantFP>(V)) {
       bool ignored;
       APFloat Val =3D FPC->getValueAPF();
-      Val.convert(DestTy->isFloatTy() ? APFloat::IEEEsingle :
+      Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
+                  DestTy->isFloatTy() ? APFloat::IEEEsingle :
                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
@@ -690,45 +689,27 @@
=20
 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
                                               Constant *V1, Constant *V2) {
-  if (ConstantInt *CB =3D dyn_cast<ConstantInt>(Cond))
-    return CB->getZExtValue() ? V1 : V2;
+  // Check for i1 and vector true/false conditions.
+  if (Cond->isNullValue()) return V2;
+  if (Cond->isAllOnesValue()) return V1;
=20
-  // Check for zero aggregate and ConstantVector of zeros
-  if (Cond->isNullValue()) return V2;
-
-  if (ConstantVector* CondV =3D dyn_cast<ConstantVector>(Cond)) {
-
-    if (CondV->isAllOnesValue()) return V1;
-
-    VectorType *VTy =3D cast<VectorType>(V1->getType());
-    ConstantVector *CP1 =3D dyn_cast<ConstantVector>(V1);
-    ConstantVector *CP2 =3D dyn_cast<ConstantVector>(V2);
-
-    if ((CP1 || isa<ConstantAggregateZero>(V1)) &&
-        (CP2 || isa<ConstantAggregateZero>(V2))) {
-
-      // Find the element type of the returned vector
-      Type *EltTy =3D VTy->getElementType();
-      unsigned NumElem =3D VTy->getNumElements();
-      std::vector<Constant*> Res(NumElem);
-
-      bool Valid =3D true;
-      for (unsigned i =3D 0; i < NumElem; ++i) {
-        ConstantInt* c =3D dyn_cast<ConstantInt>(CondV->getOperand(i));
-        if (!c) {
-          Valid =3D false;
-          break;
-        }
-        Constant *C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue=
(EltTy);
-        Constant *C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue=
(EltTy);
-        Res[i] =3D c->getZExtValue() ? C1 : C2;
-      }
-      // If we were able to build the vector, return it
-      if (Valid) return ConstantVector::get(Res);
+  // If the condition is a vector constant, fold the result elementwise.
+  if (ConstantVector *CondV =3D dyn_cast<ConstantVector>(Cond)) {
+    SmallVector<Constant*, 16> Result;
+    for (unsigned i =3D 0, e =3D V1->getType()->getVectorNumElements(); i =
!=3D e;++i){
+      ConstantInt *Cond =3D dyn_cast<ConstantInt>(CondV->getOperand(i));
+      if (Cond =3D=3D 0) break;
+     =20
+      Constant *Res =3D (Cond->getZExtValue() ? V2 : V1)->getAggregateElem=
ent(i);
+      if (Res =3D=3D 0) break;
+      Result.push_back(Res);
     }
+   =20
+    // If we were able to build the vector, return it.
+    if (Result.size() =3D=3D V1->getType()->getVectorNumElements())
+      return ConstantVector::get(Result);
   }
=20
-
   if (isa<UndefValue>(Cond)) {
     if (isa<UndefValue>(V1)) return V1;
     return V2;
@@ -754,22 +735,19 @@
 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
                                                       Constant *Idx) {
   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
-    return UndefValue::get(cast<VectorType>(Val->getType())->getElementTyp=
e());
+    return UndefValue::get(Val->getType()->getVectorElementType());
   if (Val->isNullValue())  // ee(zero, x) -> zero
-    return Constant::getNullValue(
-                          cast<VectorType>(Val->getType())->getElementType=
());
+    return Constant::getNullValue(Val->getType()->getVectorElementType());
+  // ee({w,x,y,z}, undef) -> undef
+  if (isa<UndefValue>(Idx))
+    return UndefValue::get(Val->getType()->getVectorElementType());
=20
-  if (ConstantVector *CVal =3D dyn_cast<ConstantVector>(Val)) {
-    if (ConstantInt *CIdx =3D dyn_cast<ConstantInt>(Idx)) {
-      uint64_t Index =3D CIdx->getZExtValue();
-      if (Index >=3D CVal->getNumOperands())
-        // ee({w,x,y,z}, wrong_value) -> undef
-        return UndefValue::get(cast<VectorType>(Val->getType())->getElemen=
tType());
-      return CVal->getOperand(CIdx->getZExtValue());
-    } else if (isa<UndefValue>(Idx)) {
-      // ee({w,x,y,z}, undef) -> undef
-      return UndefValue::get(cast<VectorType>(Val->getType())->getElementT=
ype());
-    }
+  if (ConstantInt *CIdx =3D dyn_cast<ConstantInt>(Idx)) {
+    uint64_t Index =3D CIdx->getZExtValue();
+    // ee({w,x,y,z}, wrong_value) -> undef
+    if (Index >=3D Val->getType()->getVectorNumElements())
+      return UndefValue::get(Val->getType()->getVectorElementType());
+    return Val->getAggregateElement(Index);
   }
   return 0;
 }
@@ -779,103 +757,55 @@
                                                      Constant *Idx) {
   ConstantInt *CIdx =3D dyn_cast<ConstantInt>(Idx);
   if (!CIdx) return 0;
-  APInt idxVal =3D CIdx->getValue();
-  if (isa<UndefValue>(Val)) {=20
-    // Insertion of scalar constant into vector undef
-    // Optimize away insertion of undef
-    if (isa<UndefValue>(Elt))
-      return Val;
-    // Otherwise break the aggregate undef into multiple undefs and do
-    // the insertion
-    unsigned numOps =3D=20
-      cast<VectorType>(Val->getType())->getNumElements();
-    std::vector<Constant*> Ops;=20
-    Ops.reserve(numOps);
-    for (unsigned i =3D 0; i < numOps; ++i) {
-      Constant *Op =3D
-        (idxVal =3D=3D i) ? Elt : UndefValue::get(Elt->getType());
-      Ops.push_back(Op);
+  const APInt &IdxVal =3D CIdx->getValue();
+ =20
+  SmallVector<Constant*, 16> Result;
+  for (unsigned i =3D 0, e =3D Val->getType()->getVectorNumElements(); i !=
=3D e; ++i){
+    if (i =3D=3D IdxVal) {
+      Result.push_back(Elt);
+      continue;
     }
-    return ConstantVector::get(Ops);
+   =20
+    if (Constant *C =3D Val->getAggregateElement(i))
+      Result.push_back(C);
+    else
+      return 0;
   }
-  if (isa<ConstantAggregateZero>(Val)) {
-    // Insertion of scalar constant into vector aggregate zero
-    // Optimize away insertion of zero
-    if (Elt->isNullValue())
-      return Val;
-    // Otherwise break the aggregate zero into multiple zeros and do
-    // the insertion
-    unsigned numOps =3D=20
-      cast<VectorType>(Val->getType())->getNumElements();
-    std::vector<Constant*> Ops;=20
-    Ops.reserve(numOps);
-    for (unsigned i =3D 0; i < numOps; ++i) {
-      Constant *Op =3D
-        (idxVal =3D=3D i) ? Elt : Constant::getNullValue(Elt->getType());
-      Ops.push_back(Op);
-    }
-    return ConstantVector::get(Ops);
-  }
-  if (ConstantVector *CVal =3D dyn_cast<ConstantVector>(Val)) {
-    // Insertion of scalar constant into vector constant
-    std::vector<Constant*> Ops;=20
-    Ops.reserve(CVal->getNumOperands());
-    for (unsigned i =3D 0; i < CVal->getNumOperands(); ++i) {
-      Constant *Op =3D
-        (idxVal =3D=3D i) ? Elt : cast<Constant>(CVal->getOperand(i));
-      Ops.push_back(Op);
-    }
-    return ConstantVector::get(Ops);
-  }
-
-  return 0;
-}
-
-/// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or =
Undef
-/// return the specified element value.  Otherwise return null.
-static Constant *GetVectorElement(Constant *C, unsigned EltNo) {
-  if (ConstantVector *CV =3D dyn_cast<ConstantVector>(C))
-    return CV->getOperand(EltNo);
-
-  Type *EltTy =3D cast<VectorType>(C->getType())->getElementType();
-  if (isa<ConstantAggregateZero>(C))
-    return Constant::getNullValue(EltTy);
-  if (isa<UndefValue>(C))
-    return UndefValue::get(EltTy);
-  return 0;
+ =20
+  return ConstantVector::get(Result);
 }
=20
 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
                                                      Constant *V2,
                                                      Constant *Mask) {
+  unsigned MaskNumElts =3D Mask->getType()->getVectorNumElements();
+  Type *EltTy =3D V1->getType()->getVectorElementType();
+
   // Undefined shuffle mask -> undefined value.
-  if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
+  if (isa<UndefValue>(Mask))
+    return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
=20
-  unsigned MaskNumElts =3D cast<VectorType>(Mask->getType())->getNumElemen=
ts();
-  unsigned SrcNumElts =3D cast<VectorType>(V1->getType())->getNumElements(=
);
-  Type *EltTy =3D cast<VectorType>(V1->getType())->getElementType();
+  // Don't break the bitcode reader hack.
+  if (isa<ConstantExpr>(Mask)) return 0;
+ =20
+  unsigned SrcNumElts =3D V1->getType()->getVectorNumElements();
=20
   // Loop over the shuffle mask, evaluating each element.
   SmallVector<Constant*, 32> Result;
   for (unsigned i =3D 0; i !=3D MaskNumElts; ++i) {
-    Constant *InElt =3D GetVectorElement(Mask, i);
+    int Elt =3D ShuffleVectorInst::getMaskValue(Mask, i);
+    if (Elt =3D=3D -1) {
+      Result.push_back(UndefValue::get(EltTy));
+      continue;
+    }
+    Constant *InElt;
+    if (unsigned(Elt) >=3D SrcNumElts*2)
+      InElt =3D UndefValue::get(EltTy);
+    else if (unsigned(Elt) >=3D SrcNumElts)
+      InElt =3D V2->getAggregateElement(Elt - SrcNumElts);
+    else
+      InElt =3D V1->getAggregateElement(Elt);
     if (InElt =3D=3D 0) return 0;
-
-    if (isa<UndefValue>(InElt))
-      InElt =3D UndefValue::get(EltTy);
-    else if (ConstantInt *CI =3D dyn_cast<ConstantInt>(InElt)) {
-      unsigned Elt =3D CI->getZExtValue();
-      if (Elt >=3D SrcNumElts*2)
-        InElt =3D UndefValue::get(EltTy);
-      else if (Elt >=3D SrcNumElts)
-        InElt =3D GetVectorElement(V2, Elt - SrcNumElts);
-      else
-        InElt =3D GetVectorElement(V1, Elt);
-      if (InElt =3D=3D 0) return 0;
-    } else {
-      // Unknown value.
-      return 0;
-    }
     Result.push_back(InElt);
   }
=20
@@ -888,26 +818,10 @@
   if (Idxs.empty())
     return Agg;
=20
-  if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
-    return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
-                                                            Idxs));
+  if (Constant *C =3D Agg->getAggregateElement(Idxs[0]))
+    return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
=20
-  if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
-    return
-      Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType=
(),
-                                                              Idxs));
-
-  // Otherwise recurse.
-  if (ConstantStruct *CS =3D dyn_cast<ConstantStruct>(Agg))
-    return ConstantFoldExtractValueInstruction(CS->getOperand(Idxs[0]),
-                                               Idxs.slice(1));
-
-  if (ConstantArray *CA =3D dyn_cast<ConstantArray>(Agg))
-    return ConstantFoldExtractValueInstruction(CA->getOperand(Idxs[0]),
-                                               Idxs.slice(1));
-  ConstantVector *CV =3D cast<ConstantVector>(Agg);
-  return ConstantFoldExtractValueInstruction(CV->getOperand(Idxs[0]),
-                                             Idxs.slice(1));
+  return 0;
 }
=20
 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
@@ -917,84 +831,30 @@
   if (Idxs.empty())
     return Val;
=20
-  if (isa<UndefValue>(Agg)) {
-    // Insertion of constant into aggregate undef
-    // Optimize away insertion of undef.
-    if (isa<UndefValue>(Val))
-      return Agg;
+  unsigned NumElts;
+  if (StructType *ST =3D dyn_cast<StructType>(Agg->getType()))
+    NumElts =3D ST->getNumElements();
+  else if (ArrayType *AT =3D dyn_cast<ArrayType>(Agg->getType()))
+    NumElts =3D AT->getNumElements();
+  else
+    NumElts =3D AT->getVectorNumElements();
+ =20
+  SmallVector<Constant*, 32> Result;
+  for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+    Constant *C =3D Agg->getAggregateElement(i);
+    if (C =3D=3D 0) return 0;
    =20
-    // Otherwise break the aggregate undef into multiple undefs and do
-    // the insertion.
-    CompositeType *AggTy =3D cast<CompositeType>(Agg->getType());
-    unsigned numOps;
-    if (ArrayType *AR =3D dyn_cast<ArrayType>(AggTy))
-      numOps =3D AR->getNumElements();
-    else
-      numOps =3D cast<StructType>(AggTy)->getNumElements();
+    if (Idxs[0] =3D=3D i)
+      C =3D ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
    =20
-    std::vector<Constant*> Ops(numOps);=20
-    for (unsigned i =3D 0; i < numOps; ++i) {
-      Type *MemberTy =3D AggTy->getTypeAtIndex(i);
-      Constant *Op =3D
-        (Idxs[0] =3D=3D i) ?
-        ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
-                                           Val, Idxs.slice(1)) :
-        UndefValue::get(MemberTy);
-      Ops[i] =3D Op;
-    }
-   =20
-    if (StructType* ST =3D dyn_cast<StructType>(AggTy))
-      return ConstantStruct::get(ST, Ops);
-    return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
+    Result.push_back(C);
   }
  =20
-  if (isa<ConstantAggregateZero>(Agg)) {
-    // Insertion of constant into aggregate zero
-    // Optimize away insertion of zero.
-    if (Val->isNullValue())
-      return Agg;
-   =20
-    // Otherwise break the aggregate zero into multiple zeros and do
-    // the insertion.
-    CompositeType *AggTy =3D cast<CompositeType>(Agg->getType());
-    unsigned numOps;
-    if (ArrayType *AR =3D dyn_cast<ArrayType>(AggTy))
-      numOps =3D AR->getNumElements();
-    else
-      numOps =3D cast<StructType>(AggTy)->getNumElements();
-   =20
-    std::vector<Constant*> Ops(numOps);
-    for (unsigned i =3D 0; i < numOps; ++i) {
-      Type *MemberTy =3D AggTy->getTypeAtIndex(i);
-      Constant *Op =3D
-        (Idxs[0] =3D=3D i) ?
-        ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy=
),
-                                           Val, Idxs.slice(1)) :
-        Constant::getNullValue(MemberTy);
-      Ops[i] =3D Op;
-    }
-   =20
-    if (StructType *ST =3D dyn_cast<StructType>(AggTy))
-      return ConstantStruct::get(ST, Ops);
-    return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
-  }
- =20
-  if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
-    // Insertion of constant into aggregate constant.
-    std::vector<Constant*> Ops(Agg->getNumOperands());
-    for (unsigned i =3D 0; i < Agg->getNumOperands(); ++i) {
-      Constant *Op =3D cast<Constant>(Agg->getOperand(i));
-      if (Idxs[0] =3D=3D i)
-        Op =3D ConstantFoldInsertValueInstruction(Op, Val, Idxs.slice(1));
-      Ops[i] =3D Op;
-    }
-   =20
-    if (StructType* ST =3D dyn_cast<StructType>(Agg->getType()))
-      return ConstantStruct::get(ST, Ops);
-    return ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
-  }
-
-  return 0;
+  if (StructType *ST =3D dyn_cast<StructType>(Agg->getType()))
+    return ConstantStruct::get(ST, Result);
+  if (ArrayType *AT =3D dyn_cast<ArrayType>(Agg->getType()))
+    return ConstantArray::get(AT, Result);
+  return ConstantVector::get(Result);
 }
=20
=20
@@ -1172,7 +1032,6 @@
   // At this point we know neither constant is an UndefValue.
   if (ConstantInt *CI1 =3D dyn_cast<ConstantInt>(C1)) {
     if (ConstantInt *CI2 =3D dyn_cast<ConstantInt>(C2)) {
-      using namespace APIntOps;
       const APInt &C1V =3D CI1->getValue();
       const APInt &C2V =3D CI2->getValue();
       switch (Opcode) {
@@ -1269,145 +1128,18 @@
       }
     }
   } else if (VectorType *VTy =3D dyn_cast<VectorType>(C1->getType())) {
-    ConstantVector *CP1 =3D dyn_cast<ConstantVector>(C1);
-    ConstantVector *CP2 =3D dyn_cast<ConstantVector>(C2);
-    if ((CP1 !=3D NULL || isa<ConstantAggregateZero>(C1)) &&
-        (CP2 !=3D NULL || isa<ConstantAggregateZero>(C2))) {
-      std::vector<Constant*> Res;
-      Type* EltTy =3D VTy->getElementType(); =20
-      Constant *C1 =3D 0;
-      Constant *C2 =3D 0;
-      switch (Opcode) {
-      default:
-        break;
-      case Instruction::Add:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getAdd(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::FAdd:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getFAdd(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::Sub:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getSub(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::FSub:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getFSub(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::Mul:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getMul(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::FMul:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getFMul(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::UDiv:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getUDiv(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::SDiv:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getSDiv(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::FDiv:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getFDiv(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::URem:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getURem(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::SRem:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getSRem(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::FRem:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getFRem(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::And:=20
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getAnd(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::Or:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getOr(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::Xor:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getXor(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::LShr:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getLShr(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::AShr:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getAShr(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      case Instruction::Shl:
-        for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i)=
 {
-          C1 =3D CP1 ? CP1->getOperand(i) : Constant::getNullValue(EltTy);
-          C2 =3D CP2 ? CP2->getOperand(i) : Constant::getNullValue(EltTy);
-          Res.push_back(ConstantExpr::getShl(C1, C2));
-        }
-        return ConstantVector::get(Res);
-      }
+    // Perform elementwise folding.
+    SmallVector<Constant*, 16> Result;
+    for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; ++i) {
+      Constant *LHS =3D C1->getAggregateElement(i);
+      Constant *RHS =3D C2->getAggregateElement(i);
+      if (LHS =3D=3D 0 || RHS =3D=3D 0) break;
+     =20
+      Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
     }
+   =20
+    if (Result.size() =3D=3D VTy->getNumElements())
+      return ConstantVector::get(Result);
   }
=20
   if (ConstantExpr *CE1 =3D dyn_cast<ConstantExpr>(C1)) {
@@ -1906,7 +1638,7 @@
     APInt V1 =3D cast<ConstantInt>(C1)->getValue();
     APInt V2 =3D cast<ConstantInt>(C2)->getValue();
     switch (pred) {
-    default: llvm_unreachable("Invalid ICmp Predicate"); return 0;
+    default: llvm_unreachable("Invalid ICmp Predicate");
     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 =3D=3D V=
2);
     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 !=3D V2);
     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
@@ -1923,7 +1655,7 @@
     APFloat C2V =3D cast<ConstantFP>(C2)->getValueAPF();
     APFloat::cmpResult R =3D C1V.compare(C2V);
     switch (pred) {
-    default: llvm_unreachable("Invalid FCmp Predicate"); return 0;
+    default: llvm_unreachable("Invalid FCmp Predicate");
     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
     case FCmpInst::FCMP_UNO:
@@ -1962,20 +1694,20 @@
                                         R=3D=3DAPFloat::cmpEqual);
     }
   } else if (C1->getType()->isVectorTy()) {
-    SmallVector<Constant*, 16> C1Elts, C2Elts;
-    C1->getVectorElements(C1Elts);
-    C2->getVectorElements(C2Elts);
-    if (C1Elts.empty() || C2Elts.empty())
-      return 0;
-
     // If we can constant fold the comparison of each element, constant fo=
ld
     // the whole vector comparison.
     SmallVector<Constant*, 4> ResElts;
     // Compare the elements, producing an i1 result or constant expr.
-    for (unsigned i =3D 0, e =3D C1Elts.size(); i !=3D e; ++i)
-      ResElts.push_back(ConstantExpr::getCompare(pred, C1Elts[i], C2Elts[i=
]));
-
-    return ConstantVector::get(ResElts);
+    for (unsigned i =3D 0, e =3D C1->getType()->getVectorNumElements(); i =
!=3D e;++i){
+      Constant *C1E =3D C1->getAggregateElement(i);
+      Constant *C2E =3D C2->getAggregateElement(i);
+      if (C1E =3D=3D 0 || C2E =3D=3D 0) break;
+     =20
+      ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
+    }
+   =20
+    if (ResElts.size() =3D=3D C1->getType()->getVectorNumElements())
+      return ConstantVector::get(ResElts);
   }
=20
   if (C1->getType()->isFloatingPointTy()) {
@@ -2209,7 +1941,7 @@
            I !=3D E; ++I)
         LastTy =3D *I;
=20
-      if ((LastTy && LastTy->isArrayTy()) || Idx0->isNullValue()) {
+      if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
         SmallVector<Value*, 16> NewIndices;
         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
         for (unsigned i =3D 1, e =3D CE->getNumOperands()-1; i !=3D e; ++i)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Constants=
.cpp
--- a/head/contrib/llvm/lib/VMCore/Constants.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/VMCore/Constants.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -40,6 +40,8 @@
 //                              Constant Class
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void Constant::anchor() { }
+
 bool Constant::isNegativeZeroValue() const {
   // Floating point values have an explicit -0.0 value.
   if (const ConstantFP *CFP =3D dyn_cast<ConstantFP>(this))
@@ -71,17 +73,27 @@
   if (const ConstantFP *CFP =3D dyn_cast<ConstantFP>(this))
     return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
=20
-  // Check for constant vectors
+  // Check for constant vectors which are splats of -1 values.
   if (const ConstantVector *CV =3D dyn_cast<ConstantVector>(this))
-    return CV->isAllOnesValue();
+    if (Constant *Splat =3D CV->getSplatValue())
+      return Splat->isAllOnesValue();
+
+  // Check for constant vectors which are splats of -1 values.
+  if (const ConstantDataVector *CV =3D dyn_cast<ConstantDataVector>(this))
+    if (Constant *Splat =3D CV->getSplatValue())
+      return Splat->isAllOnesValue();
=20
   return false;
 }
+
 // Constructor to create a '0' constant of arbitrary type...
 Constant *Constant::getNullValue(Type *Ty) {
   switch (Ty->getTypeID()) {
   case Type::IntegerTyID:
     return ConstantInt::get(Ty, 0);
+  case Type::HalfTyID:
+    return ConstantFP::get(Ty->getContext(),
+                           APFloat::getZero(APFloat::IEEEhalf));
   case Type::FloatTyID:
     return ConstantFP::get(Ty->getContext(),
                            APFloat::getZero(APFloat::IEEEsingle));
@@ -105,8 +117,7 @@
     return ConstantAggregateZero::get(Ty);
   default:
     // Function, Label, or Opaque type?
-    assert(0 && "Cannot create a null constant of that type!");
-    return 0;
+    llvm_unreachable("Cannot create a null constant of that type!");
   }
 }
=20
@@ -122,7 +133,7 @@
=20
   // Broadcast a scalar to a vector, if necessary.
   if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
-    C =3D ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(=
), C));
+    C =3D ConstantVector::getSplat(VTy->getNumElements(), C);
=20
   return C;
 }
@@ -138,13 +149,44 @@
     return ConstantFP::get(Ty->getContext(), FL);
   }
=20
-  SmallVector<Constant*, 16> Elts;
   VectorType *VTy =3D cast<VectorType>(Ty);
-  Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()=
));
-  assert(Elts[0] && "Invalid AllOnes value!");
-  return cast<ConstantVector>(ConstantVector::get(Elts));
+  return ConstantVector::getSplat(VTy->getNumElements(),
+                                  getAllOnesValue(VTy->getElementType()));
 }
=20
+/// getAggregateElement - For aggregates (struct/array/vector) return the
+/// constant that corresponds to the specified element if possible, or nul=
l if
+/// not.  This can return null if the element index is a ConstantExpr, or =
if
+/// 'this' is a constant expr.
+Constant *Constant::getAggregateElement(unsigned Elt) const {
+  if (const ConstantStruct *CS =3D dyn_cast<ConstantStruct>(this))
+    return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
+ =20
+  if (const ConstantArray *CA =3D dyn_cast<ConstantArray>(this))
+    return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
+ =20
+  if (const ConstantVector *CV =3D dyn_cast<ConstantVector>(this))
+    return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
+ =20
+  if (const ConstantAggregateZero *CAZ =3Ddyn_cast<ConstantAggregateZero>(=
this))
+    return CAZ->getElementValue(Elt);
+ =20
+  if (const UndefValue *UV =3D dyn_cast<UndefValue>(this))
+    return UV->getElementValue(Elt);
+ =20
+  if (const ConstantDataSequential *CDS =3Ddyn_cast<ConstantDataSequential=
>(this))
+    return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : =
0;
+  return 0;
+}
+
+Constant *Constant::getAggregateElement(Constant *Elt) const {
+  assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
+  if (ConstantInt *CI =3D dyn_cast<ConstantInt>(Elt))
+    return getAggregateElement(CI->getZExtValue());
+  return 0;
+}
+
+
 void Constant::destroyConstantImpl() {
   // When a Constant is destroyed, there may be lingering
   // references to the constant by other constants in the constant pool.  =
These
@@ -163,8 +205,7 @@
     }
 #endif
     assert(isa<Constant>(V) && "References remain to Constant being destro=
yed");
-    Constant *CV =3D cast<Constant>(V);
-    CV->destroyConstant();
+    cast<Constant>(V)->destroyConstant();
=20
     // The constant should remove itself from our use list...
     assert((use_empty() || use_back() !=3D V) && "Constant not removed!");
@@ -270,36 +311,6 @@
   return Result;
 }
=20
-
-/// getVectorElements - This method, which is only valid on constant of ve=
ctor
-/// type, returns the elements of the vector in the specified smallvector.
-/// This handles breaking down a vector undef into undef elements, etc.  F=
or
-/// constant exprs and other cases we can't handle, we return an empty vec=
tor.
-void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
-  assert(getType()->isVectorTy() && "Not a vector constant!");
- =20
-  if (const ConstantVector *CV =3D dyn_cast<ConstantVector>(this)) {
-    for (unsigned i =3D 0, e =3D CV->getNumOperands(); i !=3D e; ++i)
-      Elts.push_back(CV->getOperand(i));
-    return;
-  }
- =20
-  VectorType *VT =3D cast<VectorType>(getType());
-  if (isa<ConstantAggregateZero>(this)) {
-    Elts.assign(VT->getNumElements(),=20
-                Constant::getNullValue(VT->getElementType()));
-    return;
-  }
- =20
-  if (isa<UndefValue>(this)) {
-    Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()=
));
-    return;
-  }
- =20
-  // Unknown type, must be constant expr etc.
-}
-
-
 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, rem=
ove
 /// it.  This involves recursively eliminating any dead users of the
 /// constantexpr.
@@ -358,6 +369,8 @@
 //                                ConstantInt
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ConstantInt::anchor() { }
+
 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
   assert(V.getBitWidth() =3D=3D Ty->getBitWidth() && "Invalid constant for=
 type");
@@ -385,9 +398,8 @@
   }
   assert(VTy->getElementType()->isIntegerTy(1) &&
          "True must be vector of i1 or i1.");
-  SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
-                                   ConstantInt::getTrue(Ty->getContext()));
-  return ConstantVector::get(Splat);
+  return ConstantVector::getSplat(VTy->getNumElements(),
+                                  ConstantInt::getTrue(Ty->getContext()));
 }
=20
 Constant *ConstantInt::getFalse(Type *Ty) {
@@ -398,9 +410,8 @@
   }
   assert(VTy->getElementType()->isIntegerTy(1) &&
          "False must be vector of i1 or i1.");
-  SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
-                                   ConstantInt::getFalse(Ty->getContext())=
);
-  return ConstantVector::get(Splat);
+  return ConstantVector::getSplat(VTy->getNumElements(),
+                                  ConstantInt::getFalse(Ty->getContext()));
 }
=20
=20
@@ -424,18 +435,17 @@
=20
   // For vectors, broadcast the value.
   if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
-    return ConstantVector::get(SmallVector<Constant*,
-                                           16>(VTy->getNumElements(), C));
+    return ConstantVector::getSplat(VTy->getNumElements(), C);
=20
   return C;
 }
=20
-ConstantInt* ConstantInt::get(IntegerType* Ty, uint64_t V,=20
+ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,=20
                               bool isSigned) {
   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
 }
=20
-ConstantInt* ConstantInt::getSigned(IntegerType* Ty, int64_t V) {
+ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
   return get(Ty, V, true);
 }
=20
@@ -443,20 +453,19 @@
   return get(Ty, V, true);
 }
=20
-Constant *ConstantInt::get(Type* Ty, const APInt& V) {
+Constant *ConstantInt::get(Type *Ty, const APInt& V) {
   ConstantInt *C =3D get(Ty->getContext(), V);
   assert(C->getType() =3D=3D Ty->getScalarType() &&
          "ConstantInt type doesn't match the type implied by its value!");
=20
   // For vectors, broadcast the value.
   if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
-    return ConstantVector::get(
-      SmallVector<Constant *, 16>(VTy->getNumElements(), C));
+    return ConstantVector::getSplat(VTy->getNumElements(), C);
=20
   return C;
 }
=20
-ConstantInt* ConstantInt::get(IntegerType* Ty, StringRef Str,
+ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
                               uint8_t radix) {
   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
 }
@@ -466,6 +475,8 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
+  if (Ty->isHalfTy())
+    return &APFloat::IEEEhalf;
   if (Ty->isFloatTy())
     return &APFloat::IEEEsingle;
   if (Ty->isDoubleTy())
@@ -479,10 +490,12 @@
   return &APFloat::PPCDoubleDouble;
 }
=20
+void ConstantFP::anchor() { }
+
 /// get() - This returns a constant fp for the specified value in the
 /// specified type.  This should only be used for simple constant values l=
ike
 /// 2.0/1.0 etc, that are known-valid both as double and as the target for=
mat.
-Constant *ConstantFP::get(Type* Ty, double V) {
+Constant *ConstantFP::get(Type *Ty, double V) {
   LLVMContext &Context =3D Ty->getContext();
  =20
   APFloat FV(V);
@@ -493,14 +506,13 @@
=20
   // For vectors, broadcast the value.
   if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
-    return ConstantVector::get(
-      SmallVector<Constant *, 16>(VTy->getNumElements(), C));
+    return ConstantVector::getSplat(VTy->getNumElements(), C);
=20
   return C;
 }
=20
=20
-Constant *ConstantFP::get(Type* Ty, StringRef Str) {
+Constant *ConstantFP::get(Type *Ty, StringRef Str) {
   LLVMContext &Context =3D Ty->getContext();
=20
   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
@@ -508,31 +520,28 @@
=20
   // For vectors, broadcast the value.
   if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
-    return ConstantVector::get(
-      SmallVector<Constant *, 16>(VTy->getNumElements(), C));
+    return ConstantVector::getSplat(VTy->getNumElements(), C);
=20
   return C;=20
 }
=20
=20
-ConstantFP* ConstantFP::getNegativeZero(Type* Ty) {
+ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
   LLVMContext &Context =3D Ty->getContext();
-  APFloat apf =3D cast <ConstantFP>(Constant::getNullValue(Ty))->getValueA=
PF();
+  APFloat apf =3D cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAP=
F();
   apf.changeSign();
   return get(Context, apf);
 }
=20
=20
-Constant *ConstantFP::getZeroValueForNegation(Type* Ty) {
-  if (VectorType *PTy =3D dyn_cast<VectorType>(Ty))
-    if (PTy->getElementType()->isFloatingPointTy()) {
-      SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
-                           getNegativeZero(PTy->getElementType()));
-      return ConstantVector::get(zeros);
-    }
-
-  if (Ty->isFloatingPointTy())=20
-    return getNegativeZero(Ty);
+Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
+  Type *ScalarTy =3D Ty->getScalarType();
+  if (ScalarTy->isFloatingPointTy()) {
+    Constant *C =3D getNegativeZero(ScalarTy);
+    if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
+      return ConstantVector::getSplat(VTy->getNumElements(), C);
+    return C;
+  }
=20
   return Constant::getNullValue(Ty);
 }
@@ -548,7 +557,9 @@
    =20
   if (!Slot) {
     Type *Ty;
-    if (&V.getSemantics() =3D=3D &APFloat::IEEEsingle)
+    if (&V.getSemantics() =3D=3D &APFloat::IEEEhalf)
+      Ty =3D Type::getHalfTy(Context);
+    else if (&V.getSemantics() =3D=3D &APFloat::IEEEsingle)
       Ty =3D Type::getFloatTy(Context);
     else if (&V.getSemantics() =3D=3D &APFloat::IEEEdouble)
       Ty =3D Type::getDoubleTy(Context);
@@ -584,9 +595,83 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//                   ConstantAggregateZero Implementation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+/// getSequentialElement - If this CAZ has array or vector type, return a =
zero
+/// with the right element type.
+Constant *ConstantAggregateZero::getSequentialElement() const {
+  return Constant::getNullValue(getType()->getSequentialElementType());
+}
+
+/// getStructElement - If this CAZ has struct type, return a zero with the
+/// right element type for the specified element.
+Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
+  return Constant::getNullValue(getType()->getStructElementType(Elt));
+}
+
+/// getElementValue - Return a zero of the right value for the specified G=
EP
+/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
+Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
+  if (isa<SequentialType>(getType()))
+    return getSequentialElement();
+  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
+}
+
+/// getElementValue - Return a zero of the right value for the specified G=
EP
+/// index.
+Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
+  if (isa<SequentialType>(getType()))
+    return getSequentialElement();
+  return getStructElement(Idx);
+}
+
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//                         UndefValue Implementation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+/// getSequentialElement - If this undef has array or vector type, return =
an
+/// undef with the right element type.
+UndefValue *UndefValue::getSequentialElement() const {
+  return UndefValue::get(getType()->getSequentialElementType());
+}
+
+/// getStructElement - If this undef has struct type, return a zero with t=
he
+/// right element type for the specified element.
+UndefValue *UndefValue::getStructElement(unsigned Elt) const {
+  return UndefValue::get(getType()->getStructElementType(Elt));
+}
+
+/// getElementValue - Return an undef of the right value for the specified=
 GEP
+/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
+UndefValue *UndefValue::getElementValue(Constant *C) const {
+  if (isa<SequentialType>(getType()))
+    return getSequentialElement();
+  return getStructElement(cast<ConstantInt>(C)->getZExtValue());
+}
+
+/// getElementValue - Return an undef of the right value for the specified=
 GEP
+/// index.
+UndefValue *UndefValue::getElementValue(unsigned Idx) const {
+  if (isa<SequentialType>(getType()))
+    return getSequentialElement();
+  return getStructElement(Idx);
+}
+
+
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                            ConstantXXX Classes
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+template <typename ItTy, typename EltTy>
+static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
+  for (; Start !=3D End; ++Start)
+    if (*Start !=3D Elt)
+      return false;
+  return true;
+}
=20
 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
   : Constant(T, ConstantArrayVal,
@@ -601,45 +686,97 @@
 }
=20
 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
+  // Empty arrays are canonicalized to ConstantAggregateZero.
+  if (V.empty())
+    return ConstantAggregateZero::get(Ty);
+
   for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i) {
     assert(V[i]->getType() =3D=3D Ty->getElementType() &&
            "Wrong type in array element initializer");
   }
   LLVMContextImpl *pImpl =3D Ty->getContext().pImpl;
-  // If this is an all-zero array, return a ConstantAggregateZero object
-  if (!V.empty()) {
-    Constant *C =3D V[0];
-    if (!C->isNullValue())
-      return pImpl->ArrayConstants.getOrCreate(Ty, V);
+ =20
+  // If this is an all-zero array, return a ConstantAggregateZero object. =
 If
+  // all undef, return an UndefValue, if "all simple", then return a
+  // ConstantDataArray.
+  Constant *C =3D V[0];
+  if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
+    return UndefValue::get(Ty);
+
+  if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
+    return ConstantAggregateZero::get(Ty);
+
+  // Check to see if all of the elements are ConstantFP or ConstantInt and=
 if
+  // the element type is compatible with ConstantDataVector.  If so, use i=
t.
+  if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
+    // We speculatively build the elements here even if it turns out that =
there
+    // is a constantexpr or something else weird in the array, since it is=
 so
+    // uncommon for that to happen.
+    if (ConstantInt *CI =3D dyn_cast<ConstantInt>(C)) {
+      if (CI->getType()->isIntegerTy(8)) {
+        SmallVector<uint8_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataArray::get(C->getContext(), Elts);
+      } else if (CI->getType()->isIntegerTy(16)) {
+        SmallVector<uint16_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataArray::get(C->getContext(), Elts);
+      } else if (CI->getType()->isIntegerTy(32)) {
+        SmallVector<uint32_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataArray::get(C->getContext(), Elts);
+      } else if (CI->getType()->isIntegerTy(64)) {
+        SmallVector<uint64_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataArray::get(C->getContext(), Elts);
+      }
+    }
    =20
-    for (unsigned i =3D 1, e =3D V.size(); i !=3D e; ++i)
-      if (V[i] !=3D C)
-        return pImpl->ArrayConstants.getOrCreate(Ty, V);
-  }
- =20
-  return ConstantAggregateZero::get(Ty);
-}
-
-/// ConstantArray::get(const string&) - Return an array that is initialize=
d to
-/// contain the specified string.  If length is zero then a null terminato=
r is=20
-/// added to the specified string so that it may be used in a natural way.=20
-/// Otherwise, the length parameter specifies how much of the string to us=
e=20
-/// and it won't be null terminated.
-///
-Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
-                             bool AddNull) {
-  std::vector<Constant*> ElementVals;
-  ElementVals.reserve(Str.size() + size_t(AddNull));
-  for (unsigned i =3D 0; i < Str.size(); ++i)
-    ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i=
]));
-
-  // Add a null terminator to the string...
-  if (AddNull) {
-    ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
+    if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(C)) {
+      if (CFP->getType()->isFloatTy()) {
+        SmallVector<float, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(V[i]))
+            Elts.push_back(CFP->getValueAPF().convertToFloat());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataArray::get(C->getContext(), Elts);
+      } else if (CFP->getType()->isDoubleTy()) {
+        SmallVector<double, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(V[i]))
+            Elts.push_back(CFP->getValueAPF().convertToDouble());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataArray::get(C->getContext(), Elts);
+      }
+    }
   }
=20
-  ArrayType *ATy =3D ArrayType::get(Type::getInt8Ty(Context), ElementVals.=
size());
-  return get(ATy, ElementVals);
+  // Otherwise, we really do want to create a ConstantArray.
+  return pImpl->ArrayConstants.getOrCreate(Ty, V);
 }
=20
 /// getTypeForElements - Return an anonymous struct type to use for a cons=
tant
@@ -647,9 +784,10 @@
 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
                                                ArrayRef<Constant*> V,
                                                bool Packed) {
-  SmallVector<Type*, 16> EltTypes;
-  for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
-    EltTypes.push_back(V[i]->getType());
+  unsigned VecSize =3D V.size();
+  SmallVector<Type*, 16> EltTypes(VecSize);
+  for (unsigned i =3D 0; i !=3D VecSize; ++i)
+    EltTypes[i] =3D V[i]->getType();
  =20
   return StructType::get(Context, EltTypes, Packed);
 }
@@ -677,14 +815,31 @@
=20
 // ConstantStruct accessors.
 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
-  // Create a ConstantAggregateZero value if all elements are zeros.
-  for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
-    if (!V[i]->isNullValue())
-      return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
-
   assert((ST->isOpaque() || ST->getNumElements() =3D=3D V.size()) &&
          "Incorrect # elements specified to ConstantStruct::get");
-  return ConstantAggregateZero::get(ST);
+
+  // Create a ConstantAggregateZero value if all elements are zeros.
+  bool isZero =3D true;
+  bool isUndef =3D false;
+ =20
+  if (!V.empty()) {
+    isUndef =3D isa<UndefValue>(V[0]);
+    isZero =3D V[0]->isNullValue();
+    if (isUndef || isZero) {
+      for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i) {
+        if (!V[i]->isNullValue())
+          isZero =3D false;
+        if (!isa<UndefValue>(V[i]))
+          isUndef =3D false;
+      }
+    }
+  } =20
+  if (isZero)
+    return ConstantAggregateZero::get(ST);
+  if (isUndef)
+    return UndefValue::get(ST);
+   =20
+  return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
 }
=20
 Constant *ConstantStruct::get(StructType *T, ...) {
@@ -731,10 +886,93 @@
     return ConstantAggregateZero::get(T);
   if (isUndef)
     return UndefValue::get(T);
+  =20
+  // Check to see if all of the elements are ConstantFP or ConstantInt and=
 if
+  // the element type is compatible with ConstantDataVector.  If so, use i=
t.
+  if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
+    // We speculatively build the elements here even if it turns out that =
there
+    // is a constantexpr or something else weird in the array, since it is=
 so
+    // uncommon for that to happen.
+    if (ConstantInt *CI =3D dyn_cast<ConstantInt>(C)) {
+      if (CI->getType()->isIntegerTy(8)) {
+        SmallVector<uint8_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataVector::get(C->getContext(), Elts);
+      } else if (CI->getType()->isIntegerTy(16)) {
+        SmallVector<uint16_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataVector::get(C->getContext(), Elts);
+      } else if (CI->getType()->isIntegerTy(32)) {
+        SmallVector<uint32_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataVector::get(C->getContext(), Elts);
+      } else if (CI->getType()->isIntegerTy(64)) {
+        SmallVector<uint64_t, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V[i]))
+            Elts.push_back(CI->getZExtValue());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataVector::get(C->getContext(), Elts);
+      }
+    }
    =20
+    if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(C)) {
+      if (CFP->getType()->isFloatTy()) {
+        SmallVector<float, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(V[i]))
+            Elts.push_back(CFP->getValueAPF().convertToFloat());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataVector::get(C->getContext(), Elts);
+      } else if (CFP->getType()->isDoubleTy()) {
+        SmallVector<double, 16> Elts;
+        for (unsigned i =3D 0, e =3D V.size(); i !=3D e; ++i)
+          if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(V[i]))
+            Elts.push_back(CFP->getValueAPF().convertToDouble());
+          else
+            break;
+        if (Elts.size() =3D=3D V.size())
+          return ConstantDataVector::get(C->getContext(), Elts);
+      }
+    }
+  }
+ =20
+  // Otherwise, the element type isn't compatible with ConstantDataVector,=
 or
+  // the operand list constants a ConstantExpr or something else strange.
   return pImpl->VectorConstants.getOrCreate(T, V);
 }
=20
+Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
+  // If this splat is compatible with ConstantDataVector, use it instead of
+  // ConstantVector.
+  if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
+      ConstantDataSequential::isElementTypeCompatible(V->getType()))
+    return ConstantDataVector::getSplat(NumElts, V);
+ =20
+  SmallVector<Constant*, 32> Elts(NumElts, V);
+  return get(Elts);
+}
+
+
 // Utility function for determining if a ConstantExpr is a CastOp or not. =
This
 // can't be inline because we don't want to #include Instruction.h into
 // Constant.h
@@ -793,66 +1031,16 @@
 /// one, but with the specified operand set to the specified value.
 Constant *
 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
-  assert(OpNo < getNumOperands() && "Operand num is out of range!");
   assert(Op->getType() =3D=3D getOperand(OpNo)->getType() &&
          "Replacing operand with value of different type!");
   if (getOperand(OpNo) =3D=3D Op)
     return const_cast<ConstantExpr*>(this);
+
+  SmallVector<Constant*, 8> NewOps;
+  for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i)
+    NewOps.push_back(i =3D=3D OpNo ? Op : getOperand(i));
  =20
-  Constant *Op0, *Op1, *Op2;
-  switch (getOpcode()) {
-  case Instruction::Trunc:
-  case Instruction::ZExt:
-  case Instruction::SExt:
-  case Instruction::FPTrunc:
-  case Instruction::FPExt:
-  case Instruction::UIToFP:
-  case Instruction::SIToFP:
-  case Instruction::FPToUI:
-  case Instruction::FPToSI:
-  case Instruction::PtrToInt:
-  case Instruction::IntToPtr:
-  case Instruction::BitCast:
-    return ConstantExpr::getCast(getOpcode(), Op, getType());
-  case Instruction::Select:
-    Op0 =3D (OpNo =3D=3D 0) ? Op : getOperand(0);
-    Op1 =3D (OpNo =3D=3D 1) ? Op : getOperand(1);
-    Op2 =3D (OpNo =3D=3D 2) ? Op : getOperand(2);
-    return ConstantExpr::getSelect(Op0, Op1, Op2);
-  case Instruction::InsertElement:
-    Op0 =3D (OpNo =3D=3D 0) ? Op : getOperand(0);
-    Op1 =3D (OpNo =3D=3D 1) ? Op : getOperand(1);
-    Op2 =3D (OpNo =3D=3D 2) ? Op : getOperand(2);
-    return ConstantExpr::getInsertElement(Op0, Op1, Op2);
-  case Instruction::ExtractElement:
-    Op0 =3D (OpNo =3D=3D 0) ? Op : getOperand(0);
-    Op1 =3D (OpNo =3D=3D 1) ? Op : getOperand(1);
-    return ConstantExpr::getExtractElement(Op0, Op1);
-  case Instruction::ShuffleVector:
-    Op0 =3D (OpNo =3D=3D 0) ? Op : getOperand(0);
-    Op1 =3D (OpNo =3D=3D 1) ? Op : getOperand(1);
-    Op2 =3D (OpNo =3D=3D 2) ? Op : getOperand(2);
-    return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
-  case Instruction::GetElementPtr: {
-    SmallVector<Constant*, 8> Ops;
-    Ops.resize(getNumOperands()-1);
-    for (unsigned i =3D 1, e =3D getNumOperands(); i !=3D e; ++i)
-      Ops[i-1] =3D getOperand(i);
-    if (OpNo =3D=3D 0)
-      return
-        ConstantExpr::getGetElementPtr(Op, Ops,
-                                       cast<GEPOperator>(this)->isInBounds=
());
-    Ops[OpNo-1] =3D Op;
-    return
-      ConstantExpr::getGetElementPtr(getOperand(0), Ops,
-                                     cast<GEPOperator>(this)->isInBounds()=
);
-  }
-  default:
-    assert(getNumOperands() =3D=3D 2 && "Must be binary operator?");
-    Op0 =3D (OpNo =3D=3D 0) ? Op : getOperand(0);
-    Op1 =3D (OpNo =3D=3D 1) ? Op : getOperand(1);
-    return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
-  }
+  return getWithOperands(NewOps);
 }
=20
 /// getWithOperands - This returns the current constant expression with the
@@ -888,12 +1076,15 @@
     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
   case Instruction::ExtractElement:
     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
+  case Instruction::InsertValue:
+    return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
+  case Instruction::ExtractValue:
+    return ConstantExpr::getExtractValue(Ops[0], getIndices());
   case Instruction::ShuffleVector:
     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
   case Instruction::GetElementPtr:
-    return
-      ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
-                                     cast<GEPOperator>(this)->isInBounds()=
);
+    return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
+                                      cast<GEPOperator>(this)->isInBounds(=
));
   case Instruction::ICmp:
   case Instruction::FCmp:
     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
@@ -908,8 +1099,8 @@
 //                      isValueValidForType implementations
=20
 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
-  unsigned NumBits =3D cast<IntegerType>(Ty)->getBitWidth(); // assert okay
-  if (Ty =3D=3D Type::getInt1Ty(Ty->getContext()))
+  unsigned NumBits =3D Ty->getIntegerBitWidth(); // assert okay
+  if (Ty->isIntegerTy(1))
     return Val =3D=3D 0 || Val =3D=3D 1;
   if (NumBits >=3D 64)
     return true; // always true, has to fit in largest type
@@ -918,8 +1109,8 @@
 }
=20
 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
-  unsigned NumBits =3D cast<IntegerType>(Ty)->getBitWidth(); // assert okay
-  if (Ty =3D=3D Type::getInt1Ty(Ty->getContext()))
+  unsigned NumBits =3D Ty->getIntegerBitWidth();
+  if (Ty->isIntegerTy(1))
     return Val =3D=3D 0 || Val =3D=3D 1 || Val =3D=3D -1;
   if (NumBits >=3D 64)
     return true; // always true, has to fit in largest type
@@ -937,6 +1128,12 @@
     return false;         // These can't be represented as floating point!
=20
   // FIXME rounding mode needs to be more flexible
+  case Type::HalfTyID: {
+    if (&Val2.getSemantics() =3D=3D &APFloat::IEEEhalf)
+      return true;
+    Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesIn=
fo);
+    return !losesInfo;
+  }
   case Type::FloatTyID: {
     if (&Val2.getSemantics() =3D=3D &APFloat::IEEEsingle)
       return true;
@@ -944,42 +1141,50 @@
     return !losesInfo;
   }
   case Type::DoubleTyID: {
-    if (&Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||
+    if (&Val2.getSemantics() =3D=3D &APFloat::IEEEhalf ||
+        &Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||
         &Val2.getSemantics() =3D=3D &APFloat::IEEEdouble)
       return true;
     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &loses=
Info);
     return !losesInfo;
   }
   case Type::X86_FP80TyID:
-    return &Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||=20
+    return &Val2.getSemantics() =3D=3D &APFloat::IEEEhalf ||
+           &Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||=20
            &Val2.getSemantics() =3D=3D &APFloat::IEEEdouble ||
            &Val2.getSemantics() =3D=3D &APFloat::x87DoubleExtended;
   case Type::FP128TyID:
-    return &Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||=20
+    return &Val2.getSemantics() =3D=3D &APFloat::IEEEhalf ||
+           &Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||=20
            &Val2.getSemantics() =3D=3D &APFloat::IEEEdouble ||
            &Val2.getSemantics() =3D=3D &APFloat::IEEEquad;
   case Type::PPC_FP128TyID:
-    return &Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||=20
+    return &Val2.getSemantics() =3D=3D &APFloat::IEEEhalf ||
+           &Val2.getSemantics() =3D=3D &APFloat::IEEEsingle ||=20
            &Val2.getSemantics() =3D=3D &APFloat::IEEEdouble ||
            &Val2.getSemantics() =3D=3D &APFloat::PPCDoubleDouble;
   }
 }
=20
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                      Factory Function Implementation
=20
-ConstantAggregateZero* ConstantAggregateZero::get(Type* Ty) {
+ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
          "Cannot create an aggregate zero of non-aggregate type!");
  =20
-  LLVMContextImpl *pImpl =3D Ty->getContext().pImpl;
-  return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
+  ConstantAggregateZero *&Entry =3D Ty->getContext().pImpl->CAZConstants[T=
y];
+  if (Entry =3D=3D 0)
+    Entry =3D new ConstantAggregateZero(Ty);
+ =20
+  return Entry;
 }
=20
-/// destroyConstant - Remove the constant from the constant table...
+/// destroyConstant - Remove the constant from the constant table.
 ///
 void ConstantAggregateZero::destroyConstant() {
-  getType()->getContext().pImpl->AggZeroConstants.remove(this);
+  getContext().pImpl->CAZConstants.erase(getType());
   destroyConstantImpl();
 }
=20
@@ -990,69 +1195,6 @@
   destroyConstantImpl();
 }
=20
-/// isString - This method returns true if the array is an array of i8, an=
d=20
-/// if the elements of the array are all ConstantInt's.
-bool ConstantArray::isString() const {
-  // Check the element type for i8...
-  if (!getType()->getElementType()->isIntegerTy(8))
-    return false;
-  // Check the elements to make sure they are all integers, not constant
-  // expressions.
-  for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i)
-    if (!isa<ConstantInt>(getOperand(i)))
-      return false;
-  return true;
-}
-
-/// isCString - This method returns true if the array is a string (see
-/// isString) and it ends in a null byte \\0 and does not contains any oth=
er
-/// null bytes except its terminator.
-bool ConstantArray::isCString() const {
-  // Check the element type for i8...
-  if (!getType()->getElementType()->isIntegerTy(8))
-    return false;
-
-  // Last element must be a null.
-  if (!getOperand(getNumOperands()-1)->isNullValue())
-    return false;
-  // Other elements must be non-null integers.
-  for (unsigned i =3D 0, e =3D getNumOperands()-1; i !=3D e; ++i) {
-    if (!isa<ConstantInt>(getOperand(i)))
-      return false;
-    if (getOperand(i)->isNullValue())
-      return false;
-  }
-  return true;
-}
-
-
-/// convertToString - Helper function for getAsString() and getAsCString().
-static std::string convertToString(const User *U, unsigned len) {
-  std::string Result;
-  Result.reserve(len);
-  for (unsigned i =3D 0; i !=3D len; ++i)
-    Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtVal=
ue());
-  return Result;
-}
-
-/// getAsString - If this array is isString(), then this method converts t=
he
-/// array to an std::string and returns it.  Otherwise, it asserts out.
-///
-std::string ConstantArray::getAsString() const {
-  assert(isString() && "Not a string!");
-  return convertToString(this, getNumOperands());
-}
-
-
-/// getAsCString - If this array is isCString(), then this method converts=
 the
-/// array (without the trailing null byte) to an std::string and returns i=
t.
-/// Otherwise, it asserts out.
-///
-std::string ConstantArray::getAsCString() const {
-  assert(isCString() && "Not a string!");
-  return convertToString(this, getNumOperands() - 1);
-}
-
=20
 //---- ConstantStruct::get() implementation...
 //
@@ -1071,26 +1213,6 @@
   destroyConstantImpl();
 }
=20
-/// This function will return true iff every element in this vector consta=
nt
-/// is set to all ones.
-/// @returns true iff this constant's elements are all set to all ones.
-/// @brief Determine if the value is all ones.
-bool ConstantVector::isAllOnesValue() const {
-  // Check out first element.
-  const Constant *Elt =3D getOperand(0);
-  const ConstantInt *CI =3D dyn_cast<ConstantInt>(Elt);
-  const ConstantFP *CF =3D dyn_cast<ConstantFP>(Elt);
-
-  // Then make sure all remaining elements point to the same value.
-  for (unsigned I =3D 1, E =3D getNumOperands(); I < E; ++I)
-    if (getOperand(I) !=3D Elt)
-      return false;
- =20
-  // First value is all-ones.
-  return (CI && CI->isAllOnesValue()) ||=20
-         (CF && CF->isAllOnesValue());
-}
-
 /// getSplatValue - If this is a splat constant, where all of the
 /// elements have the same value, return that value. Otherwise return null.
 Constant *ConstantVector::getSplatValue() const {
@@ -1107,13 +1229,18 @@
 //
=20
 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
-  return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
+  ConstantPointerNull *&Entry =3D Ty->getContext().pImpl->CPNConstants[Ty];
+  if (Entry =3D=3D 0)
+    Entry =3D new ConstantPointerNull(Ty);
+ =20
+  return Entry;
 }
=20
 // destroyConstant - Remove the constant from the constant table...
 //
 void ConstantPointerNull::destroyConstant() {
-  getType()->getContext().pImpl->NullPtrConstants.remove(this);
+  getContext().pImpl->CPNConstants.erase(getType());
+  // Free the constant and any dangling references to it.
   destroyConstantImpl();
 }
=20
@@ -1122,13 +1249,18 @@
 //
=20
 UndefValue *UndefValue::get(Type *Ty) {
-  return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
+  UndefValue *&Entry =3D Ty->getContext().pImpl->UVConstants[Ty];
+  if (Entry =3D=3D 0)
+    Entry =3D new UndefValue(Ty);
+ =20
+  return Entry;
 }
=20
 // destroyConstant - Remove the constant from the constant table.
 //
 void UndefValue::destroyConstant() {
-  getType()->getContext().pImpl->UndefValueConstants.remove(this);
+  // Free the constant and any dangling references to it.
+  getContext().pImpl->UVConstants.erase(getType());
   destroyConstantImpl();
 }
=20
@@ -1236,7 +1368,6 @@
   switch (opc) {
   default:
     llvm_unreachable("Invalid cast opcode");
-    break;
   case Instruction::Trunc:    return getTrunc(C, Ty);
   case Instruction::ZExt:     return getZExt(C, Ty);
   case Instruction::SExt:     return getSExt(C, Ty);
@@ -1250,7 +1381,6 @@
   case Instruction::IntToPtr: return getIntToPtr(C, Ty);
   case Instruction::BitCast:  return getBitCast(C, Ty);
   }
-  return 0;
 }=20
=20
 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
@@ -1416,14 +1546,26 @@
 }
=20
 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
-  assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
-  assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
+  assert(C->getType()->getScalarType()->isPointerTy() &&
+         "PtrToInt source must be pointer or pointer vector");
+  assert(DstTy->getScalarType()->isIntegerTy() &&=20
+         "PtrToInt destination must be integer or integer vector");
+  assert(isa<VectorType>(C->getType()) =3D=3D isa<VectorType>(DstTy));
+  if (isa<VectorType>(C->getType()))
+    assert(C->getType()->getVectorNumElements()=3D=3DDstTy->getVectorNumEl=
ements()&&
+           "Invalid cast between a different number of vector elements");
   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
 }
=20
 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
-  assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral"=
);
-  assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
+  assert(C->getType()->getScalarType()->isIntegerTy() &&
+         "IntToPtr source must be integer or integer vector");
+  assert(DstTy->getScalarType()->isPointerTy() &&
+         "IntToPtr destination must be a pointer or pointer vector");
+  assert(isa<VectorType>(C->getType()) =3D=3D isa<VectorType>(DstTy));
+  if (isa<VectorType>(C->getType()))
+    assert(C->getType()->getVectorNumElements()=3D=3DDstTy->getVectorNumEl=
ements()&&
+           "Invalid cast between a different number of vector elements");
   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
 }
=20
@@ -1603,7 +1745,7 @@
   // Get the result type of the getelementptr!
   Type *Ty =3D GetElementPtrInst::getIndexedType(C->getType(), Idxs);
   assert(Ty && "GEP indices invalid!");
-  unsigned AS =3D cast<PointerType>(C->getType())->getAddressSpace();
+  unsigned AS =3D C->getType()->getPointerAddressSpace();
   Type *ReqTy =3D Ty->getPointerTo(AS);
  =20
   assert(C->getType()->isPointerTy() &&
@@ -1683,7 +1825,7 @@
   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
  =20
   LLVMContextImpl *pImpl =3D Val->getContext().pImpl;
-  Type *ReqTy =3D cast<VectorType>(Val->getType())->getElementType();
+  Type *ReqTy =3D Val->getType()->getVectorElementType();
   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
 }
=20
@@ -1691,8 +1833,8 @@
                                          Constant *Idx) {
   assert(Val->getType()->isVectorTy() &&
          "Tried to create insertelement operation on non-vector type!");
-  assert(Elt->getType() =3D=3D cast<VectorType>(Val->getType())->getElemen=
tType()
-         && "Insertelement types must match!");
+  assert(Elt->getType() =3D=3D Val->getType()->getVectorElementType() &&
+         "Insertelement types must match!");
   assert(Idx->getType()->isIntegerTy(32) &&
          "Insertelement index must be i32 type!");
=20
@@ -1716,8 +1858,8 @@
   if (Constant *FC =3D ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
     return FC;          // Fold a few common cases.
=20
-  unsigned NElts =3D cast<VectorType>(Mask->getType())->getNumElements();
-  Type *EltTy =3D cast<VectorType>(V1->getType())->getElementType();
+  unsigned NElts =3D Mask->getType()->getVectorNumElements();
+  Type *EltTy =3D V1->getType()->getVectorElementType();
   Type *ShufTy =3D VectorType::get(EltTy, NElts);
=20
   // Look up the constant in the table first to ensure uniqueness
@@ -1879,7 +2021,7 @@
=20
=20
 GetElementPtrConstantExpr::
-GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxLi=
st,
+GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
                           Type *DestTy)
   : ConstantExpr(DestTy, Instruction::GetElementPtr,
                  OperandTraits<GetElementPtrConstantExpr>::op_end(this)
@@ -1889,6 +2031,341 @@
     OperandList[i+1] =3D IdxList[i];
 }
=20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//                       ConstantData* implementations
+
+void ConstantDataArray::anchor() {}
+void ConstantDataVector::anchor() {}
+
+/// getElementType - Return the element type of the array/vector.
+Type *ConstantDataSequential::getElementType() const {
+  return getType()->getElementType();
+}
+
+StringRef ConstantDataSequential::getRawDataValues() const {
+  return StringRef(DataElements, getNumElements()*getElementByteSize());
+}
+
+/// isElementTypeCompatible - Return true if a ConstantDataSequential can =
be
+/// formed with a vector or array of the specified element type.
+/// ConstantDataArray only works with normal float and int types that are
+/// stored densely in memory, not with things like i42 or x86_f80.
+bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
+  if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
+  if (const IntegerType *IT =3D dyn_cast<IntegerType>(Ty)) {
+    switch (IT->getBitWidth()) {
+    case 8:
+    case 16:
+    case 32:
+    case 64:
+      return true;
+    default: break;
+    }
+  }
+  return false;
+}
+
+/// getNumElements - Return the number of elements in the array or vector.
+unsigned ConstantDataSequential::getNumElements() const {
+  if (ArrayType *AT =3D dyn_cast<ArrayType>(getType()))
+    return AT->getNumElements();
+  return getType()->getVectorNumElements();
+}
+
+
+/// getElementByteSize - Return the size in bytes of the elements in the d=
ata.
+uint64_t ConstantDataSequential::getElementByteSize() const {
+  return getElementType()->getPrimitiveSizeInBits()/8;
+}
+
+/// getElementPointer - Return the start of the specified element.
+const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
+  assert(Elt < getNumElements() && "Invalid Elt");
+  return DataElements+Elt*getElementByteSize();
+}
+
+
+/// isAllZeros - return true if the array is empty or all zeros.
+static bool isAllZeros(StringRef Arr) {
+  for (StringRef::iterator I =3D Arr.begin(), E =3D Arr.end(); I !=3D E; +=
+I)
+    if (*I !=3D 0)
+      return false;
+  return true;
+}
+
+/// getImpl - This is the underlying implementation of all of the
+/// ConstantDataSequential::get methods.  They all thunk down to here, pro=
viding
+/// the correct element type.  We take the bytes in as a StringRef because
+/// we *want* an underlying "char*" to avoid TBAA type punning violations.
+Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
+  assert(isElementTypeCompatible(Ty->getSequentialElementType()));
+  // If the elements are all zero or there are no elements, return a CAZ, =
which
+  // is more dense and canonical.
+  if (isAllZeros(Elements))
+    return ConstantAggregateZero::get(Ty);
+
+  // Do a lookup to see if we have already formed one of these.
+  StringMap<ConstantDataSequential*>::MapEntryTy &Slot =3D
+    Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
+ =20
+  // The bucket can point to a linked list of different CDS's that have th=
e same
+  // body but different types.  For example, 0,0,0,1 could be a 4 element =
array
+  // of i8, or a 1-element array of i32.  They'll both end up in the same
+  /// StringMap bucket, linked up by their Next pointers.  Walk the list.
+  ConstantDataSequential **Entry =3D &Slot.getValue();
+  for (ConstantDataSequential *Node =3D *Entry; Node !=3D 0;
+       Entry =3D &Node->Next, Node =3D *Entry)
+    if (Node->getType() =3D=3D Ty)
+      return Node;
+ =20
+  // Okay, we didn't get a hit.  Create a node of the right class, link it=
 in,
+  // and return it.
+  if (isa<ArrayType>(Ty))
+    return *Entry =3D new ConstantDataArray(Ty, Slot.getKeyData());
+
+  assert(isa<VectorType>(Ty));
+  return *Entry =3D new ConstantDataVector(Ty, Slot.getKeyData());
+}
+
+void ConstantDataSequential::destroyConstant() {
+  // Remove the constant from the StringMap.
+  StringMap<ConstantDataSequential*> &CDSConstants =3D=20
+    getType()->getContext().pImpl->CDSConstants;
+ =20
+  StringMap<ConstantDataSequential*>::iterator Slot =3D
+    CDSConstants.find(getRawDataValues());
+
+  assert(Slot !=3D CDSConstants.end() && "CDS not found in uniquing table"=
);
+
+  ConstantDataSequential **Entry =3D &Slot->getValue();
+
+  // Remove the entry from the hash table.
+  if ((*Entry)->Next =3D=3D 0) {
+    // If there is only one value in the bucket (common case) it must be t=
his
+    // entry, and removing the entry should remove the bucket completely.
+    assert((*Entry) =3D=3D this && "Hash mismatch in ConstantDataSequentia=
l");
+    getContext().pImpl->CDSConstants.erase(Slot);
+  } else {
+    // Otherwise, there are multiple entries linked off the bucket, unlink=
 the=20
+    // node we care about but keep the bucket around.
+    for (ConstantDataSequential *Node =3D *Entry; ;
+         Entry =3D &Node->Next, Node =3D *Entry) {
+      assert(Node && "Didn't find entry in its uniquing hash table!");
+      // If we found our entry, unlink it from the list and we're done.
+      if (Node =3D=3D this) {
+        *Entry =3D Node->Next;
+        break;
+      }
+    }
+  }
+ =20
+  // If we were part of a list, make sure that we don't delete the list th=
at is
+  // still owned by the uniquing map.
+  Next =3D 0;
+ =20
+  // Finally, actually delete it.
+  destroyConstantImpl();
+}
+
+/// get() constructors - Return a constant with array type with an element
+/// count and element type matching the ArrayRef passed in.  Note that this
+/// can return a ConstantAggregateZero object.
+Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> E=
lts) {
+  Type *Ty =3D ArrayType::get(Type::getInt8Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
+}
+Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> =
Elts){
+  Type *Ty =3D ArrayType::get(Type::getInt16Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
+}
+Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> =
Elts){
+  Type *Ty =3D ArrayType::get(Type::getInt32Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
+}
+Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> =
Elts){
+  Type *Ty =3D ArrayType::get(Type::getInt64Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
+}
+Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elt=
s) {
+  Type *Ty =3D ArrayType::get(Type::getFloatTy(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
+}
+Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> El=
ts) {
+  Type *Ty =3D ArrayType::get(Type::getDoubleTy(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
+}
+
+/// getString - This method constructs a CDS and initializes it with a text
+/// string. The default behavior (AddNull=3D=3Dtrue) causes a null termina=
tor to
+/// be placed at the end of the array (increasing the length of the string=
 by
+/// one more than the StringRef would normally indicate.  Pass AddNull=3Df=
alse
+/// to disable this behavior.
+Constant *ConstantDataArray::getString(LLVMContext &Context,
+                                       StringRef Str, bool AddNull) {
+  if (!AddNull)
+    return get(Context, ArrayRef<uint8_t>((uint8_t*)Str.data(), Str.size()=
));
+ =20
+  SmallVector<uint8_t, 64> ElementVals;
+  ElementVals.append(Str.begin(), Str.end());
+  ElementVals.push_back(0);
+  return get(Context, ElementVals);
+}
+
+/// get() constructors - Return a constant with vector type with an element
+/// count and element type matching the ArrayRef passed in.  Note that this
+/// can return a ConstantAggregateZero object.
+Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> =
Elts){
+  Type *Ty =3D VectorType::get(Type::getInt8Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*1), Ty);
+}
+Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t>=
 Elts){
+  Type *Ty =3D VectorType::get(Type::getInt16Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*2), Ty);
+}
+Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t>=
 Elts){
+  Type *Ty =3D VectorType::get(Type::getInt32Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
+}
+Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t>=
 Elts){
+  Type *Ty =3D VectorType::get(Type::getInt64Ty(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
+}
+Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> El=
ts) {
+  Type *Ty =3D VectorType::get(Type::getFloatTy(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*4), Ty);
+}
+Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> E=
lts) {
+  Type *Ty =3D VectorType::get(Type::getDoubleTy(Context), Elts.size());
+  return getImpl(StringRef((char*)Elts.data(), Elts.size()*8), Ty);
+}
+
+Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
+  assert(isElementTypeCompatible(V->getType()) &&
+         "Element type not compatible with ConstantData");
+  if (ConstantInt *CI =3D dyn_cast<ConstantInt>(V)) {
+    if (CI->getType()->isIntegerTy(8)) {
+      SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
+      return get(V->getContext(), Elts);
+    }
+    if (CI->getType()->isIntegerTy(16)) {
+      SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
+      return get(V->getContext(), Elts);
+    }
+    if (CI->getType()->isIntegerTy(32)) {
+      SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
+      return get(V->getContext(), Elts);
+    }
+    assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData typ=
e");
+    SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
+    return get(V->getContext(), Elts);
+  }
+
+  if (ConstantFP *CFP =3D dyn_cast<ConstantFP>(V)) {
+    if (CFP->getType()->isFloatTy()) {
+      SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFlo=
at());
+      return get(V->getContext(), Elts);
+    }
+    if (CFP->getType()->isDoubleTy()) {
+      SmallVector<double, 16> Elts(NumElts,
+                                   CFP->getValueAPF().convertToDouble());
+      return get(V->getContext(), Elts);
+    }
+  }
+  return ConstantVector::getSplat(NumElts, V);
+}
+
+
+/// getElementAsInteger - If this is a sequential container of integers (of
+/// any size), return the specified element in the low bits of a uint64_t.
+uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
+  assert(isa<IntegerType>(getElementType()) &&
+         "Accessor can only be used when element is an integer");
+  const char *EltPtr =3D getElementPointer(Elt);
+ =20
+  // The data is stored in host byte order, make sure to cast back to the =
right
+  // type to load with the right endianness.
+  switch (getElementType()->getIntegerBitWidth()) {
+  default: llvm_unreachable("Invalid bitwidth for CDS");
+  case 8:  return *(uint8_t*)EltPtr;
+  case 16: return *(uint16_t*)EltPtr;
+  case 32: return *(uint32_t*)EltPtr;
+  case 64: return *(uint64_t*)EltPtr;
+  }
+}
+
+/// getElementAsAPFloat - If this is a sequential container of floating po=
int
+/// type, return the specified element as an APFloat.
+APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
+  const char *EltPtr =3D getElementPointer(Elt);
+
+  switch (getElementType()->getTypeID()) {
+  default:
+    llvm_unreachable("Accessor can only be used when element is float/doub=
le!");
+  case Type::FloatTyID: return APFloat(*(float*)EltPtr);
+  case Type::DoubleTyID: return APFloat(*(double*)EltPtr);
+  }
+}
+
+/// getElementAsFloat - If this is an sequential container of floats, retu=
rn
+/// the specified element as a float.
+float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
+  assert(getElementType()->isFloatTy() &&
+         "Accessor can only be used when element is a 'float'");
+  return *(float*)getElementPointer(Elt);
+}
+
+/// getElementAsDouble - If this is an sequential container of doubles, re=
turn
+/// the specified element as a float.
+double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
+  assert(getElementType()->isDoubleTy() &&
+         "Accessor can only be used when element is a 'float'");
+  return *(double*)getElementPointer(Elt);
+}
+
+/// getElementAsConstant - Return a Constant for a specified index's eleme=
nt.
+/// Note that this has to compute a new constant to return, so it isn't as
+/// efficient as getElementAsInteger/Float/Double.
+Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const=
 {
+  if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
+    return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
+ =20
+  return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
+}
+
+/// isString - This method returns true if this is an array of i8.
+bool ConstantDataSequential::isString() const {
+  return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
+}
+
+/// isCString - This method returns true if the array "isString", ends wit=
h a
+/// nul byte, and does not contains any other nul bytes.
+bool ConstantDataSequential::isCString() const {
+  if (!isString())
+    return false;
+ =20
+  StringRef Str =3D getAsString();
+ =20
+  // The last value must be nul.
+  if (Str.back() !=3D 0) return false;
+ =20
+  // Other elements must be non-nul.
+  return Str.drop_back().find(0) =3D=3D StringRef::npos;
+}
+
+/// getSplatValue - If this is a splat constant, meaning that all of the
+/// elements have the same value, return that value. Otherwise return NULL.
+Constant *ConstantDataVector::getSplatValue() const {
+  const char *Base =3D getRawDataValues().data();
+ =20
+  // Compare elements 1+ to the 0'th element.
+  unsigned EltSize =3D getElementByteSize();
+  for (unsigned i =3D 1, e =3D getNumElements(); i !=3D e; ++i)
+    if (memcmp(Base, Base+i*EltSize, EltSize))
+      return 0;
+ =20
+  // If they're all the same, return the 0th one as a representative.
+  return getElementAsConstant(0);
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                replaceUsesOfWithOnConstant implementations
@@ -1911,56 +2388,46 @@
=20
   LLVMContextImpl *pImpl =3D getType()->getContext().pImpl;
=20
-  std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Loo=
kup;
-  Lookup.first.first =3D cast<ArrayType>(getType());
-  Lookup.second =3D this;
-
-  std::vector<Constant*> &Values =3D Lookup.first.second;
+  SmallVector<Constant*, 8> Values;
+  LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
+  Lookup.first =3D cast<ArrayType>(getType());
   Values.reserve(getNumOperands());  // Build replacement array.
=20
   // Fill values with the modified operands of the constant array.  Also,=20
   // compute whether this turns into an all-zeros array.
-  bool isAllZeros =3D false;
   unsigned NumUpdated =3D 0;
-  if (!ToC->isNullValue()) {
-    for (Use *O =3D OperandList, *E =3D OperandList+getNumOperands(); O !=
=3D E; ++O) {
-      Constant *Val =3D cast<Constant>(O->get());
-      if (Val =3D=3D From) {
-        Val =3D ToC;
-        ++NumUpdated;
-      }
-      Values.push_back(Val);
+ =20
+  // Keep track of whether all the values in the array are "ToC".
+  bool AllSame =3D true;
+  for (Use *O =3D OperandList, *E =3D OperandList+getNumOperands(); O !=3D=
 E; ++O) {
+    Constant *Val =3D cast<Constant>(O->get());
+    if (Val =3D=3D From) {
+      Val =3D ToC;
+      ++NumUpdated;
     }
-  } else {
-    isAllZeros =3D true;
-    for (Use *O =3D OperandList, *E =3D OperandList+getNumOperands();O !=
=3D E; ++O) {
-      Constant *Val =3D cast<Constant>(O->get());
-      if (Val =3D=3D From) {
-        Val =3D ToC;
-        ++NumUpdated;
-      }
-      Values.push_back(Val);
-      if (isAllZeros) isAllZeros =3D Val->isNullValue();
-    }
+    Values.push_back(Val);
+    AllSame &=3D Val =3D=3D ToC;
   }
  =20
   Constant *Replacement =3D 0;
-  if (isAllZeros) {
+  if (AllSame && ToC->isNullValue()) {
     Replacement =3D ConstantAggregateZero::get(getType());
+  } else if (AllSame && isa<UndefValue>(ToC)) {
+    Replacement =3D UndefValue::get(getType());
   } else {
     // Check to see if we have this array type already.
-    bool Exists;
+    Lookup.second =3D makeArrayRef(Values);
     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =3D
-      pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
+      pImpl->ArrayConstants.find(Lookup);
    =20
-    if (Exists) {
-      Replacement =3D I->second;
+    if (I !=3D pImpl->ArrayConstants.map_end()) {
+      Replacement =3D I->first;
     } else {
       // Okay, the new shape doesn't exist in the system yet.  Instead of
       // creating a new constant array, inserting it, replaceallusesof'ing=
 the
       // old with the new, then deleting the old... just update the curren=
t one
       // in place!
-      pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
+      pImpl->ArrayConstants.remove(this);
      =20
       // Update to the new value.  Optimize for the case when we have a si=
ngle
       // operand that we're changing, but handle bulk updates efficiently.
@@ -1974,6 +2441,7 @@
           if (getOperand(i) =3D=3D From)
             setOperand(i, ToC);
       }
+      pImpl->ArrayConstants.insert(this);
       return;
     }
   }
@@ -1996,26 +2464,32 @@
   unsigned OperandToUpdate =3D U-OperandList;
   assert(getOperand(OperandToUpdate) =3D=3D From && "ReplaceAllUsesWith br=
oken!");
=20
-  std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> L=
ookup;
-  Lookup.first.first =3D cast<StructType>(getType());
-  Lookup.second =3D this;
-  std::vector<Constant*> &Values =3D Lookup.first.second;
+  SmallVector<Constant*, 8> Values;
+  LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
+  Lookup.first =3D cast<StructType>(getType());
   Values.reserve(getNumOperands());  // Build replacement struct.
  =20
- =20
   // Fill values with the modified operands of the constant struct.  Also,=20
   // compute whether this turns into an all-zeros struct.
   bool isAllZeros =3D false;
-  if (!ToC->isNullValue()) {
-    for (Use *O =3D OperandList, *E =3D OperandList + getNumOperands(); O =
!=3D E; ++O)
-      Values.push_back(cast<Constant>(O->get()));
-  } else {
+  bool isAllUndef =3D false;
+  if (ToC->isNullValue()) {
     isAllZeros =3D true;
     for (Use *O =3D OperandList, *E =3D OperandList+getNumOperands(); O !=
=3D E; ++O) {
       Constant *Val =3D cast<Constant>(O->get());
       Values.push_back(Val);
       if (isAllZeros) isAllZeros =3D Val->isNullValue();
     }
+  } else if (isa<UndefValue>(ToC)) {
+    isAllUndef =3D true;
+    for (Use *O =3D OperandList, *E =3D OperandList+getNumOperands(); O !=
=3D E; ++O) {
+      Constant *Val =3D cast<Constant>(O->get());
+      Values.push_back(Val);
+      if (isAllUndef) isAllUndef =3D isa<UndefValue>(Val);
+    }
+  } else {
+    for (Use *O =3D OperandList, *E =3D OperandList + getNumOperands(); O =
!=3D E; ++O)
+      Values.push_back(cast<Constant>(O->get()));
   }
   Values[OperandToUpdate] =3D ToC;
  =20
@@ -2024,23 +2498,26 @@
   Constant *Replacement =3D 0;
   if (isAllZeros) {
     Replacement =3D ConstantAggregateZero::get(getType());
+  } else if (isAllUndef) {
+    Replacement =3D UndefValue::get(getType());
   } else {
     // Check to see if we have this struct type already.
-    bool Exists;
+    Lookup.second =3D makeArrayRef(Values);
     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =3D
-      pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
+      pImpl->StructConstants.find(Lookup);
    =20
-    if (Exists) {
-      Replacement =3D I->second;
+    if (I !=3D pImpl->StructConstants.map_end()) {
+      Replacement =3D I->first;
     } else {
       // Okay, the new shape doesn't exist in the system yet.  Instead of
       // creating a new constant struct, inserting it, replaceallusesof'in=
g the
       // old with the new, then deleting the old... just update the curren=
t one
       // in place!
-      pImpl->StructConstants.MoveConstantToNewSlot(this, I);
+      pImpl->StructConstants.remove(this);
      =20
       // Update to the new value.
       setOperand(OperandToUpdate, ToC);
+      pImpl->StructConstants.insert(this);
       return;
     }
   }
@@ -2058,7 +2535,7 @@
                                                  Use *U) {
   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!=
");
  =20
-  std::vector<Constant*> Values;
+  SmallVector<Constant*, 8> Values;
   Values.reserve(getNumOperands());  // Build replacement array...
   for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i) {
     Constant *Val =3D getOperand(i);
@@ -2081,89 +2558,13 @@
   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant=
!");
   Constant *To =3D cast<Constant>(ToV);
  =20
-  Constant *Replacement =3D 0;
-  if (getOpcode() =3D=3D Instruction::GetElementPtr) {
-    SmallVector<Constant*, 8> Indices;
-    Constant *Pointer =3D getOperand(0);
-    Indices.reserve(getNumOperands()-1);
-    if (Pointer =3D=3D From) Pointer =3D To;
-   =20
-    for (unsigned i =3D 1, e =3D getNumOperands(); i !=3D e; ++i) {
-      Constant *Val =3D getOperand(i);
-      if (Val =3D=3D From) Val =3D To;
-      Indices.push_back(Val);
-    }
-    Replacement =3D ConstantExpr::getGetElementPtr(Pointer, Indices,
-                                         cast<GEPOperator>(this)->isInBoun=
ds());
-  } else if (getOpcode() =3D=3D Instruction::ExtractValue) {
-    Constant *Agg =3D getOperand(0);
-    if (Agg =3D=3D From) Agg =3D To;
-   =20
-    ArrayRef<unsigned> Indices =3D getIndices();
-    Replacement =3D ConstantExpr::getExtractValue(Agg, Indices);
-  } else if (getOpcode() =3D=3D Instruction::InsertValue) {
-    Constant *Agg =3D getOperand(0);
-    Constant *Val =3D getOperand(1);
-    if (Agg =3D=3D From) Agg =3D To;
-    if (Val =3D=3D From) Val =3D To;
-   =20
-    ArrayRef<unsigned> Indices =3D getIndices();
-    Replacement =3D ConstantExpr::getInsertValue(Agg, Val, Indices);
-  } else if (isCast()) {
-    assert(getOperand(0) =3D=3D From && "Cast only has one use!");
-    Replacement =3D ConstantExpr::getCast(getOpcode(), To, getType());
-  } else if (getOpcode() =3D=3D Instruction::Select) {
-    Constant *C1 =3D getOperand(0);
-    Constant *C2 =3D getOperand(1);
-    Constant *C3 =3D getOperand(2);
-    if (C1 =3D=3D From) C1 =3D To;
-    if (C2 =3D=3D From) C2 =3D To;
-    if (C3 =3D=3D From) C3 =3D To;
-    Replacement =3D ConstantExpr::getSelect(C1, C2, C3);
-  } else if (getOpcode() =3D=3D Instruction::ExtractElement) {
-    Constant *C1 =3D getOperand(0);
-    Constant *C2 =3D getOperand(1);
-    if (C1 =3D=3D From) C1 =3D To;
-    if (C2 =3D=3D From) C2 =3D To;
-    Replacement =3D ConstantExpr::getExtractElement(C1, C2);
-  } else if (getOpcode() =3D=3D Instruction::InsertElement) {
-    Constant *C1 =3D getOperand(0);
-    Constant *C2 =3D getOperand(1);
-    Constant *C3 =3D getOperand(1);
-    if (C1 =3D=3D From) C1 =3D To;
-    if (C2 =3D=3D From) C2 =3D To;
-    if (C3 =3D=3D From) C3 =3D To;
-    Replacement =3D ConstantExpr::getInsertElement(C1, C2, C3);
-  } else if (getOpcode() =3D=3D Instruction::ShuffleVector) {
-    Constant *C1 =3D getOperand(0);
-    Constant *C2 =3D getOperand(1);
-    Constant *C3 =3D getOperand(2);
-    if (C1 =3D=3D From) C1 =3D To;
-    if (C2 =3D=3D From) C2 =3D To;
-    if (C3 =3D=3D From) C3 =3D To;
-    Replacement =3D ConstantExpr::getShuffleVector(C1, C2, C3);
-  } else if (isCompare()) {
-    Constant *C1 =3D getOperand(0);
-    Constant *C2 =3D getOperand(1);
-    if (C1 =3D=3D From) C1 =3D To;
-    if (C2 =3D=3D From) C2 =3D To;
-    if (getOpcode() =3D=3D Instruction::ICmp)
-      Replacement =3D ConstantExpr::getICmp(getPredicate(), C1, C2);
-    else {
-      assert(getOpcode() =3D=3D Instruction::FCmp);
-      Replacement =3D ConstantExpr::getFCmp(getPredicate(), C1, C2);
-    }
-  } else if (getNumOperands() =3D=3D 2) {
-    Constant *C1 =3D getOperand(0);
-    Constant *C2 =3D getOperand(1);
-    if (C1 =3D=3D From) C1 =3D To;
-    if (C2 =3D=3D From) C2 =3D To;
-    Replacement =3D ConstantExpr::get(getOpcode(), C1, C2, SubclassOptiona=
lData);
-  } else {
-    llvm_unreachable("Unknown ConstantExpr type!");
-    return;
+  SmallVector<Constant*, 8> NewOps;
+  for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i) {
+    Constant *Op =3D getOperand(i);
+    NewOps.push_back(Op =3D=3D From ? To : Op);
   }
  =20
+  Constant *Replacement =3D getWithOperands(NewOps);
   assert(Replacement !=3D this && "I didn't contain From!");
  =20
   // Everyone using this now uses the replacement.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Constants=
Context.h
--- a/head/contrib/llvm/lib/VMCore/ConstantsContext.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/lib/VMCore/ConstantsContext.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -15,6 +15,8 @@
 #ifndef LLVM_CONSTANTSCONTEXT_H
 #define LLVM_CONSTANTSCONTEXT_H
=20
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Hashing.h"
 #include "llvm/InlineAsm.h"
 #include "llvm/Instructions.h"
 #include "llvm/Operator.h"
@@ -30,6 +32,7 @@
 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
 /// behind the scenes to implement unary constant exprs.
 class UnaryConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly one operand
@@ -46,6 +49,7 @@
 /// BinaryConstantExpr - This class is private to Constants.cpp, and is us=
ed
 /// behind the scenes to implement binary constant exprs.
 class BinaryConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly two operands
@@ -66,6 +70,7 @@
 /// SelectConstantExpr - This class is private to Constants.cpp, and is us=
ed
 /// behind the scenes to implement select constant exprs.
 class SelectConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly three operands
@@ -86,6 +91,7 @@
 /// Constants.cpp, and is used behind the scenes to implement
 /// extractelement constant exprs.
 class ExtractElementConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly two operands
@@ -106,6 +112,7 @@
 /// Constants.cpp, and is used behind the scenes to implement
 /// insertelement constant exprs.
 class InsertElementConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly three operands
@@ -127,6 +134,7 @@
 /// Constants.cpp, and is used behind the scenes to implement
 /// shufflevector constant exprs.
 class ShuffleVectorConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly three operands
@@ -151,6 +159,7 @@
 /// Constants.cpp, and is used behind the scenes to implement
 /// extractvalue constant exprs.
 class ExtractValueConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly one operand
@@ -176,6 +185,7 @@
 /// Constants.cpp, and is used behind the scenes to implement
 /// insertvalue constant exprs.
 class InsertValueConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
 public:
   // allocate space for exactly one operand
@@ -202,11 +212,12 @@
 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, an=
d is
 /// used behind the scenes to implement getelementpr constant exprs.
 class GetElementPtrConstantExpr : public ConstantExpr {
-  GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &Idx=
List,
+  virtual void anchor();
+  GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
                             Type *DestTy);
 public:
   static GetElementPtrConstantExpr *Create(Constant *C,
-                                           const std::vector<Constant*>&Id=
xList,
+                                           ArrayRef<Constant*> IdxList,
                                            Type *DestTy,
                                            unsigned Flags) {
     GetElementPtrConstantExpr *Result =3D
@@ -221,8 +232,10 @@
 // CompareConstantExpr - This class is private to Constants.cpp, and is us=
ed
 // behind the scenes to implement ICmp and FCmp constant expressions. This=
 is
 // needed in order to store the predicate value for these instructions.
-struct CompareConstantExpr : public ConstantExpr {
+class CompareConstantExpr : public ConstantExpr {
+  virtual void anchor();
   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
+public:
   // allocate space for exactly two operands
   void *operator new(size_t s) {
     return User::operator new(s, 2);
@@ -397,6 +410,13 @@
   }
 };
=20
+template<class ConstantClass, class TypeClass>
+struct ConstantArrayCreator {
+  static ConstantClass *create(TypeClass *Ty, ArrayRef<Constant*> V) {
+    return new(V.size()) ConstantClass(Ty, V);
+  }
+};
+
 template<class ConstantClass>
 struct ConstantKeyData {
   typedef void ValType;
@@ -447,7 +467,6 @@
       return new CompareConstantExpr(Ty, Instruction::FCmp, V.subclassdata,
                                      V.operands[0], V.operands[1]);
     llvm_unreachable("Invalid ConstantExpr!");
-    return 0;
   }
 };
=20
@@ -467,90 +486,6 @@
   }
 };
=20
-// ConstantAggregateZero does not take extra "value" argument...
-template<class ValType>
-struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
-  static ConstantAggregateZero *create(Type *Ty, const ValType &V){
-    return new ConstantAggregateZero(Ty);
-  }
-};
-
-template<>
-struct ConstantKeyData<ConstantVector> {
-  typedef std::vector<Constant*> ValType;
-  static ValType getValType(ConstantVector *CP) {
-    std::vector<Constant*> Elements;
-    Elements.reserve(CP->getNumOperands());
-    for (unsigned i =3D 0, e =3D CP->getNumOperands(); i !=3D e; ++i)
-      Elements.push_back(CP->getOperand(i));
-    return Elements;
-  }
-};
-
-template<>
-struct ConstantKeyData<ConstantAggregateZero> {
-  typedef char ValType;
-  static ValType getValType(ConstantAggregateZero *C) {
-    return 0;
-  }
-};
-
-template<>
-struct ConstantKeyData<ConstantArray> {
-  typedef std::vector<Constant*> ValType;
-  static ValType getValType(ConstantArray *CA) {
-    std::vector<Constant*> Elements;
-    Elements.reserve(CA->getNumOperands());
-    for (unsigned i =3D 0, e =3D CA->getNumOperands(); i !=3D e; ++i)
-      Elements.push_back(cast<Constant>(CA->getOperand(i)));
-    return Elements;
-  }
-};
-
-template<>
-struct ConstantKeyData<ConstantStruct> {
-  typedef std::vector<Constant*> ValType;
-  static ValType getValType(ConstantStruct *CS) {
-    std::vector<Constant*> Elements;
-    Elements.reserve(CS->getNumOperands());
-    for (unsigned i =3D 0, e =3D CS->getNumOperands(); i !=3D e; ++i)
-      Elements.push_back(cast<Constant>(CS->getOperand(i)));
-    return Elements;
-  }
-};
-
-// ConstantPointerNull does not take extra "value" argument...
-template<class ValType>
-struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
-  static ConstantPointerNull *create(PointerType *Ty, const ValType &V){
-    return new ConstantPointerNull(Ty);
-  }
-};
-
-template<>
-struct ConstantKeyData<ConstantPointerNull> {
-  typedef char ValType;
-  static ValType getValType(ConstantPointerNull *C) {
-    return 0;
-  }
-};
-
-// UndefValue does not take extra "value" argument...
-template<class ValType>
-struct ConstantCreator<UndefValue, Type, ValType> {
-  static UndefValue *create(Type *Ty, const ValType &V) {
-    return new UndefValue(Ty);
-  }
-};
-
-template<>
-struct ConstantKeyData<UndefValue> {
-  typedef char ValType;
-  static ValType getValType(UndefValue *C) {
-    return 0;
-  }
-};
-
 template<>
 struct ConstantCreator<InlineAsm, PointerType, InlineAsmKeyType> {
   static InlineAsm *create(PointerType *Ty, const InlineAsmKeyType &Key) {
@@ -704,6 +639,129 @@
   }
 };
=20
+// Unique map for aggregate constants
+template<class TypeClass, class ConstantClass>
+class ConstantAggrUniqueMap {
+public:
+  typedef ArrayRef<Constant*> Operands;
+  typedef std::pair<TypeClass*, Operands> LookupKey;
+private:
+  struct MapInfo {
+    typedef DenseMapInfo<ConstantClass*> ConstantClassInfo;
+    typedef DenseMapInfo<Constant*> ConstantInfo;
+    typedef DenseMapInfo<TypeClass*> TypeClassInfo;
+    static inline ConstantClass* getEmptyKey() {
+      return ConstantClassInfo::getEmptyKey();
+    }
+    static inline ConstantClass* getTombstoneKey() {
+      return ConstantClassInfo::getTombstoneKey();
+    }
+    static unsigned getHashValue(const ConstantClass *CP) {
+      SmallVector<Constant*, 8> CPOperands;
+      CPOperands.reserve(CP->getNumOperands());
+      for (unsigned I =3D 0, E =3D CP->getNumOperands(); I < E; ++I)
+        CPOperands.push_back(CP->getOperand(I));
+      return getHashValue(LookupKey(CP->getType(), CPOperands));
+    }
+    static bool isEqual(const ConstantClass *LHS, const ConstantClass *RHS=
) {
+      return LHS =3D=3D RHS;
+    }
+    static unsigned getHashValue(const LookupKey &Val) {
+      return hash_combine(Val.first, hash_combine_range(Val.second.begin(),
+                                                        Val.second.end()));
+    }
+    static bool isEqual(const LookupKey &LHS, const ConstantClass *RHS) {
+      if (RHS =3D=3D getEmptyKey() || RHS =3D=3D getTombstoneKey())
+        return false;
+      if (LHS.first !=3D RHS->getType()
+          || LHS.second.size() !=3D RHS->getNumOperands())
+        return false;
+      for (unsigned I =3D 0, E =3D RHS->getNumOperands(); I < E; ++I) {
+        if (LHS.second[I] !=3D RHS->getOperand(I))
+          return false;
+      }
+      return true;
+    }
+  };
+public:
+  typedef DenseMap<ConstantClass *, char, MapInfo> MapTy;
+
+private:
+  /// Map - This is the main map from the element descriptor to the Consta=
nts.
+  /// This is the primary way we avoid creating two of the same shape
+  /// constant.
+  MapTy Map;
+
+public:
+  typename MapTy::iterator map_begin() { return Map.begin(); }
+  typename MapTy::iterator map_end() { return Map.end(); }
+
+  void freeConstants() {
+    for (typename MapTy::iterator I=3DMap.begin(), E=3DMap.end();
+         I !=3D E; ++I) {
+      // Asserts that use_empty().
+      delete I->first;
+    }
+  }
+
+private:
+  typename MapTy::iterator findExistingElement(ConstantClass *CP) {
+    return Map.find(CP);
+  }
+
+  ConstantClass *Create(TypeClass *Ty, Operands V, typename MapTy::iterato=
r I) {
+    ConstantClass* Result =3D
+      ConstantArrayCreator<ConstantClass,TypeClass>::create(Ty, V);
+
+    assert(Result->getType() =3D=3D Ty && "Type specified is not correct!"=
);
+    Map[Result] =3D '\0';
+
+    return Result;
+  }
+public:
+
+  /// getOrCreate - Return the specified constant from the map, creating i=
t if
+  /// necessary.
+  ConstantClass *getOrCreate(TypeClass *Ty, Operands V) {
+    LookupKey Lookup(Ty, V);
+    ConstantClass* Result =3D 0;
+
+    typename MapTy::iterator I =3D Map.find_as(Lookup);
+    // Is it in the map?
+    if (I !=3D Map.end())
+      Result =3D I->first;
+
+    if (!Result) {
+      // If no preexisting value, create one now...
+      Result =3D Create(Ty, V, I);
+    }
+
+    return Result;
+  }
+
+  /// Find the constant by lookup key.
+  typename MapTy::iterator find(LookupKey Lookup) {
+    return Map.find_as(Lookup);
+  }
+
+  /// Insert the constant into its proper slot.
+  void insert(ConstantClass *CP) {
+    Map[CP] =3D '\0';
+  }
+
+  /// Remove this constant from the map
+  void remove(ConstantClass *CP) {
+    typename MapTy::iterator I =3D findExistingElement(CP);
+    assert(I !=3D Map.end() && "Constant not found in constant table!");
+    assert(I->first =3D=3D CP && "Didn't find correct element?");
+    Map.erase(I);
+  }
+
+  void dump() const {
+    DEBUG(dbgs() << "Constant.cpp: ConstantUniqueMap\n");
+  }
+};
+
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Core.cpp
--- a/head/contrib/llvm/lib/VMCore/Core.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/Core.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -13,6 +13,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm-c/Core.h"
+#include "llvm/Attributes.h"
 #include "llvm/Bitcode/ReaderWriter.h"
 #include "llvm/Constants.h"
 #include "llvm/DerivedTypes.h"
@@ -132,10 +133,11 @@
=20
 LLVMTypeKind LLVMGetTypeKind(LLVMTypeRef Ty) {
   switch (unwrap(Ty)->getTypeID()) {
-  default:
-    assert(false && "Unhandled TypeID.");
+  default: llvm_unreachable("Unhandled TypeID.");
   case Type::VoidTyID:
     return LLVMVoidTypeKind;
+  case Type::HalfTyID:
+    return LLVMHalfTypeKind;
   case Type::FloatTyID:
     return LLVMFloatTypeKind;
   case Type::DoubleTyID:
@@ -222,6 +224,9 @@
=20
 /*--.. Operations on real types ..........................................=
..--*/
=20
+LLVMTypeRef LLVMHalfTypeInContext(LLVMContextRef C) {
+  return (LLVMTypeRef) Type::getHalfTy(*unwrap(C));
+}
 LLVMTypeRef LLVMFloatTypeInContext(LLVMContextRef C) {
   return (LLVMTypeRef) Type::getFloatTy(*unwrap(C));
 }
@@ -241,6 +246,9 @@
   return (LLVMTypeRef) Type::getX86_MMXTy(*unwrap(C));
 }
=20
+LLVMTypeRef LLVMHalfType(void) {
+  return LLVMHalfTypeInContext(LLVMGetGlobalContext());
+}
 LLVMTypeRef LLVMFloatType(void) {
   return LLVMFloatTypeInContext(LLVMGetGlobalContext());
 }
@@ -558,6 +566,17 @@
     Dest[i] =3D wrap(N->getOperand(i));
 }
=20
+void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char* name,
+                                 LLVMValueRef Val)
+{
+  NamedMDNode *N =3D unwrap(M)->getOrInsertNamedMetadata(name);
+  if (!N)
+    return;
+  MDNode *Op =3D Val ? unwrap<MDNode>(Val) : NULL;
+  if (Op)
+    N->addOperand(Op);
+}
+
 /*--.. Operations on scalar constants ....................................=
..--*/
=20
 LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N,
@@ -614,8 +633,8 @@
                                       LLVMBool DontNullTerminate) {
   /* Inverted the sense of AddNull because ', 0)' is a
      better mnemonic for null termination than ', 1)'. */
-  return wrap(ConstantArray::get(*unwrap(C), StringRef(Str, Length),
-                                 DontNullTerminate =3D=3D 0));
+  return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Leng=
th),
+                                           DontNullTerminate =3D=3D 0));
 }
 LLVMValueRef LLVMConstStructInContext(LLVMContextRef C,=20
                                       LLVMValueRef *ConstantVals,
@@ -660,8 +679,7 @@
 static LLVMOpcode map_to_llvmopcode(int opcode)
 {
     switch (opcode) {
-      default:
-        assert(0 && "Unhandled Opcode.");
+      default: llvm_unreachable("Unhandled Opcode.");
 #define HANDLE_INST(num, opc, clas) case num: return LLVM##opc;
 #include "llvm/Instruction.def"
 #undef HANDLE_INST
@@ -671,12 +689,11 @@
 static int map_from_llvmopcode(LLVMOpcode code)
 {
     switch (code) {
-      default:
-        assert(0 && "Unhandled Opcode.");
 #define HANDLE_INST(num, opc, clas) case LLVM##opc: return num;
 #include "llvm/Instruction.def"
 #undef HANDLE_INST
     }
+    llvm_unreachable("Unhandled Opcode.");
 }
=20
 /*--.. Constant expressions ..............................................=
..--*/
@@ -1040,8 +1057,6 @@
=20
 LLVMLinkage LLVMGetLinkage(LLVMValueRef Global) {
   switch (unwrap<GlobalValue>(Global)->getLinkage()) {
-  default:
-    assert(false && "Unhandled Linkage Type.");
   case GlobalValue::ExternalLinkage:
     return LLVMExternalLinkage;
   case GlobalValue::AvailableExternallyLinkage:
@@ -1076,16 +1091,13 @@
     return LLVMCommonLinkage;
   }
=20
-  // Should never get here.
-  return static_cast<LLVMLinkage>(0);
+  llvm_unreachable("Invalid GlobalValue linkage!");
 }
=20
 void LLVMSetLinkage(LLVMValueRef Global, LLVMLinkage Linkage) {
   GlobalValue *GV =3D unwrap<GlobalValue>(Global);
=20
   switch (Linkage) {
-  default:
-    assert(false && "Unhandled Linkage Type.");
   case LLVMExternalLinkage:
     GV->setLinkage(GlobalValue::ExternalLinkage);
     break;
@@ -1337,14 +1349,14 @@
 void LLVMAddFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA) {
   Function *Func =3D unwrap<Function>(Fn);
   const AttrListPtr PAL =3D Func->getAttributes();
-  const AttrListPtr PALnew =3D PAL.addAttr(~0U, PA);
+  const AttrListPtr PALnew =3D PAL.addAttr(~0U, Attributes(PA));
   Func->setAttributes(PALnew);
 }
=20
 void LLVMRemoveFunctionAttr(LLVMValueRef Fn, LLVMAttribute PA) {
   Function *Func =3D unwrap<Function>(Fn);
   const AttrListPtr PAL =3D Func->getAttributes();
-  const AttrListPtr PALnew =3D PAL.removeAttr(~0U, PA);
+  const AttrListPtr PALnew =3D PAL.removeAttr(~0U, Attributes(PA));
   Func->setAttributes(PALnew);
 }
=20
@@ -1352,7 +1364,7 @@
   Function *Func =3D unwrap<Function>(Fn);
   const AttrListPtr PAL =3D Func->getAttributes();
   Attributes attr =3D PAL.getFnAttributes();
-  return (LLVMAttribute)attr;
+  return (LLVMAttribute)attr.Raw();
 }
=20
 /*--.. Operations on parameters ..........................................=
..--*/
@@ -1414,18 +1426,18 @@
 }
=20
 void LLVMAddAttribute(LLVMValueRef Arg, LLVMAttribute PA) {
-  unwrap<Argument>(Arg)->addAttr(PA);
+  unwrap<Argument>(Arg)->addAttr(Attributes(PA));
 }
=20
 void LLVMRemoveAttribute(LLVMValueRef Arg, LLVMAttribute PA) {
-  unwrap<Argument>(Arg)->removeAttr(PA);
+  unwrap<Argument>(Arg)->removeAttr(Attributes(PA));
 }
=20
 LLVMAttribute LLVMGetAttribute(LLVMValueRef Arg) {
   Argument *A =3D unwrap<Argument>(Arg);
   Attributes attr =3D A->getParent()->getAttributes().getParamAttributes(
     A->getArgNo()+1);
-  return (LLVMAttribute)attr;
+  return (LLVMAttribute)attr.Raw();
 }
  =20
=20
@@ -1603,10 +1615,9 @@
   Value *V =3D unwrap(Instr);
   if (CallInst *CI =3D dyn_cast<CallInst>(V))
     return CI->getCallingConv();
-  else if (InvokeInst *II =3D dyn_cast<InvokeInst>(V))
+  if (InvokeInst *II =3D dyn_cast<InvokeInst>(V))
     return II->getCallingConv();
   llvm_unreachable("LLVMGetInstructionCallConv applies only to call and in=
voke!");
-  return 0;
 }
=20
 void LLVMSetInstructionCallConv(LLVMValueRef Instr, unsigned CC) {
@@ -1622,14 +1633,14 @@
                            LLVMAttribute PA) {
   CallSite Call =3D CallSite(unwrap<Instruction>(Instr));
   Call.setAttributes(
-    Call.getAttributes().addAttr(index, PA));
+    Call.getAttributes().addAttr(index, Attributes(PA)));
 }
=20
 void LLVMRemoveInstrAttribute(LLVMValueRef Instr, unsigned index,=20
                               LLVMAttribute PA) {
   CallSite Call =3D CallSite(unwrap<Instruction>(Instr));
   Call.setAttributes(
-    Call.getAttributes().removeAttr(index, PA));
+    Call.getAttributes().removeAttr(index, Attributes(PA)));
 }
=20
 void LLVMSetInstrParamAlignment(LLVMValueRef Instr, unsigned index,=20
@@ -2055,6 +2066,20 @@
   return wrap(unwrap(B)->CreateGlobalStringPtr(Str, Name));
 }
=20
+LLVMBool LLVMGetVolatile(LLVMValueRef MemAccessInst) {
+  Value *P =3D unwrap<Value>(MemAccessInst);
+  if (LoadInst *LI =3D dyn_cast<LoadInst>(P))
+    return LI->isVolatile();
+  return cast<StoreInst>(P)->isVolatile();
+}
+
+void LLVMSetVolatile(LLVMValueRef MemAccessInst, LLVMBool isVolatile) {
+  Value *P =3D unwrap<Value>(MemAccessInst);
+  if (LoadInst *LI =3D dyn_cast<LoadInst>(P))
+    return LI->setVolatile(isVolatile);
+  return cast<StoreInst>(P)->setVolatile(isVolatile);
+}
+
 /*--.. Casts .............................................................=
..--*/
=20
 LLVMValueRef LLVMBuildTrunc(LLVMBuilderRef B, LLVMValueRef Val,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/DebugLoc.=
cpp
--- a/head/contrib/llvm/lib/VMCore/DebugLoc.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/VMCore/DebugLoc.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -173,10 +173,7 @@
 }
=20
 unsigned DenseMapInfo<DebugLoc>::getHashValue(const DebugLoc &Key) {
-  FoldingSetNodeID ID;
-  ID.AddInteger(Key.LineCol);
-  ID.AddInteger(Key.ScopeIdx);
-  return ID.ComputeHash();
+  return static_cast<unsigned>(hash_combine(Key.LineCol, Key.ScopeIdx));
 }
=20
 bool DenseMapInfo<DebugLoc>::isEqual(const DebugLoc &LHS, const DebugLoc &=
RHS) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Dominator=
s.cpp
--- a/head/contrib/llvm/lib/VMCore/Dominators.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/VMCore/Dominators.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -80,27 +80,187 @@
   DT->print(OS);
 }
=20
-// dominates - Return true if A dominates a use in B. This performs the
-// special checks necessary if A and B are in the same basic block.
-bool DominatorTree::dominates(const Instruction *A, const Instruction *B) =
const{
-  const BasicBlock *BBA =3D A->getParent(), *BBB =3D B->getParent();
- =20
-  // If A is an invoke instruction, its value is only available in this no=
rmal
-  // successor block.
-  if (const InvokeInst *II =3D dyn_cast<InvokeInst>(A))
-    BBA =3D II->getNormalDest();
- =20
-  if (BBA !=3D BBB) return dominates(BBA, BBB);
- =20
-  // It is not possible to determine dominance between two PHI nodes=20
-  // based on their ordering.
-  if (isa<PHINode>(A) && isa<PHINode>(B))=20
+// dominates - Return true if Def dominates a use in User. This performs
+// the special checks necessary if Def and User are in the same basic bloc=
k.
+// Note that Def doesn't dominate a use in Def itself!
+bool DominatorTree::dominates(const Instruction *Def,
+                              const Instruction *User) const {
+  const BasicBlock *UseBB =3D User->getParent();
+  const BasicBlock *DefBB =3D Def->getParent();
+
+  // Any unreachable use is dominated, even if Def =3D=3D User.
+  if (!isReachableFromEntry(UseBB))
+    return true;
+
+  // Unreachable definitions don't dominate anything.
+  if (!isReachableFromEntry(DefBB))
     return false;
- =20
-  // Loop through the basic block until we find A or B.
-  BasicBlock::const_iterator I =3D BBA->begin();
-  for (; &*I !=3D A && &*I !=3D B; ++I)
+
+  // An instruction doesn't dominate a use in itself.
+  if (Def =3D=3D User)
+    return false;
+
+  // The value defined by an invoke dominates an instruction only if
+  // it dominates every instruction in UseBB.
+  // A PHI is dominated only if the instruction dominates every possible u=
se
+  // in the UseBB.
+  if (isa<InvokeInst>(Def) || isa<PHINode>(User))
+    return dominates(Def, UseBB);
+
+  if (DefBB !=3D UseBB)
+    return dominates(DefBB, UseBB);
+
+  // Loop through the basic block until we find Def or User.
+  BasicBlock::const_iterator I =3D DefBB->begin();
+  for (; &*I !=3D Def && &*I !=3D User; ++I)
     /*empty*/;
- =20
-  return &*I =3D=3D A;
+
+  return &*I =3D=3D Def;
 }
+
+// true if Def would dominate a use in any instruction in UseBB.
+// note that dominates(Def, Def->getParent()) is false.
+bool DominatorTree::dominates(const Instruction *Def,
+                              const BasicBlock *UseBB) const {
+  const BasicBlock *DefBB =3D Def->getParent();
+
+  // Any unreachable use is dominated, even if DefBB =3D=3D UseBB.
+  if (!isReachableFromEntry(UseBB))
+    return true;
+
+  // Unreachable definitions don't dominate anything.
+  if (!isReachableFromEntry(DefBB))
+    return false;
+
+  if (DefBB =3D=3D UseBB)
+    return false;
+
+  const InvokeInst *II =3D dyn_cast<InvokeInst>(Def);
+  if (!II)
+    return dominates(DefBB, UseBB);
+
+  // Invoke results are only usable in the normal destination, not in the
+  // exceptional destination.
+  BasicBlock *NormalDest =3D II->getNormalDest();
+  if (!dominates(NormalDest, UseBB))
+    return false;
+
+  // Simple case: if the normal destination has a single predecessor, the
+  // fact that it dominates the use block implies that we also do.
+  if (NormalDest->getSinglePredecessor())
+    return true;
+
+  // The normal edge from the invoke is critical. Conceptually, what we wo=
uld
+  // like to do is split it and check if the new block dominates the use.
+  // With X being the new block, the graph would look like:
+  //
+  //        DefBB
+  //          /\      .  .
+  //         /  \     .  .
+  //        /    \    .  .
+  //       /      \   |  |
+  //      A        X  B  C
+  //      |         \ | /
+  //      .          \|/
+  //      .      NormalDest
+  //      .
+  //
+  // Given the definition of dominance, NormalDest is dominated by X iff X
+  // dominates all of NormalDest's predecessors (X, B, C in the example). X
+  // trivially dominates itself, so we only have to find if it dominates t=
he
+  // other predecessors. Since the only way out of X is via NormalDest, X =
can
+  // only properly dominate a node if NormalDest dominates that node too.
+  for (pred_iterator PI =3D pred_begin(NormalDest),
+         E =3D pred_end(NormalDest); PI !=3D E; ++PI) {
+    const BasicBlock *BB =3D *PI;
+    if (BB =3D=3D DefBB)
+      continue;
+
+    if (!DT->isReachableFromEntry(BB))
+      continue;
+
+    if (!dominates(NormalDest, BB))
+      return false;
+  }
+  return true;
+}
+
+bool DominatorTree::dominates(const Instruction *Def,
+                              const Use &U) const {
+  Instruction *UserInst =3D dyn_cast<Instruction>(U.getUser());
+
+  // Instructions do not dominate non-instructions.
+  if (!UserInst)
+    return false;
+
+  const BasicBlock *DefBB =3D Def->getParent();
+
+  // Determine the block in which the use happens. PHI nodes use
+  // their operands on edges; simulate this by thinking of the use
+  // happening at the end of the predecessor block.
+  const BasicBlock *UseBB;
+  if (PHINode *PN =3D dyn_cast<PHINode>(UserInst))
+    UseBB =3D PN->getIncomingBlock(U);
+  else
+    UseBB =3D UserInst->getParent();
+
+  // Any unreachable use is dominated, even if Def =3D=3D User.
+  if (!isReachableFromEntry(UseBB))
+    return true;
+
+  // Unreachable definitions don't dominate anything.
+  if (!isReachableFromEntry(DefBB))
+    return false;
+
+  // Invoke instructions define their return values on the edges
+  // to their normal successors, so we have to handle them specially.
+  // Among other things, this means they don't dominate anything in
+  // their own block, except possibly a phi, so we don't need to
+  // walk the block in any case.
+  if (const InvokeInst *II =3D dyn_cast<InvokeInst>(Def)) {
+    // A PHI in the normal successor using the invoke's return value is
+    // dominated by the invoke's return value.
+    if (isa<PHINode>(UserInst) &&
+        UserInst->getParent() =3D=3D II->getNormalDest() &&
+        cast<PHINode>(UserInst)->getIncomingBlock(U) =3D=3D DefBB)
+      return true;
+
+    // Otherwise use the instruction-dominates-block query, which
+    // handles the crazy case of an invoke with a critical edge
+    // properly.
+    return dominates(Def, UseBB);
+  }
+
+  // If the def and use are in different blocks, do a simple CFG dominator
+  // tree query.
+  if (DefBB !=3D UseBB)
+    return dominates(DefBB, UseBB);
+
+  // Ok, def and use are in the same block. If the def is an invoke, it
+  // doesn't dominate anything in the block. If it's a PHI, it dominates
+  // everything in the block.
+  if (isa<PHINode>(UserInst))
+    return true;
+
+  // Otherwise, just loop through the basic block until we find Def or Use=
r.
+  BasicBlock::const_iterator I =3D DefBB->begin();
+  for (; &*I !=3D Def && &*I !=3D UserInst; ++I)
+    /*empty*/;
+
+  return &*I !=3D UserInst;
+}
+
+bool DominatorTree::isReachableFromEntry(const Use &U) const {
+  Instruction *I =3D dyn_cast<Instruction>(U.getUser());
+
+  // ConstantExprs aren't really reachable from the entry block, but they
+  // don't need to be treated like unreachable code either.
+  if (!I) return true;
+
+  // PHI nodes use their operands on their incoming edges.
+  if (PHINode *PN =3D dyn_cast<PHINode>(I))
+    return isReachableFromEntry(PN->getIncomingBlock(U));
+
+  // Everything else uses their operands in their own block.
+  return isReachableFromEntry(I->getParent());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Function.=
cpp
--- a/head/contrib/llvm/lib/VMCore/Function.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/VMCore/Function.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -39,6 +39,8 @@
 // Argument Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void Argument::anchor() { }
+
 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
   : Value(Ty, Value::ArgumentVal) {
   Parent =3D 0;
@@ -359,7 +361,7 @@
 FunctionType *Intrinsic::getType(LLVMContext &Context,
                                        ID id, ArrayRef<Type*> Tys) {
   Type *ResultTy =3D NULL;
-  std::vector<Type*> ArgTys;
+  SmallVector<Type*, 8> ArgTys;
   bool IsVarArg =3D false;
  =20
 #define GET_INTRINSIC_GENERATOR
@@ -370,13 +372,9 @@
 }
=20
 bool Intrinsic::isOverloaded(ID id) {
-  static const bool OTable[] =3D {
-    false,
 #define GET_INTRINSIC_OVERLOAD_TABLE
 #include "llvm/Intrinsics.gen"
 #undef GET_INTRINSIC_OVERLOAD_TABLE
-  };
-  return OTable[id];
 }
=20
 /// This defines the "Intrinsic::getAttributes(ID id)" method.
@@ -402,6 +400,7 @@
 bool Function::hasAddressTaken(const User* *PutOffender) const {
   for (Value::const_use_iterator I =3D use_begin(), E =3D use_end(); I !=
=3D E; ++I) {
     const User *U =3D *I;
+    // FIXME: Check for blockaddress, which does not take the address.
     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
       return PutOffender ? (*PutOffender =3D U, true) : true;
     ImmutableCallSite CS(cast<Instruction>(U));
@@ -411,41 +410,30 @@
   return false;
 }
=20
+bool Function::isDefTriviallyDead() const {
+  // Check the linkage
+  if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
+      !hasAvailableExternallyLinkage())
+    return false;
+
+  // Check if the function is used by anything other than a blockaddress.
+  for (Value::const_use_iterator I =3D use_begin(), E =3D use_end(); I !=
=3D E; ++I)
+    if (!isa<BlockAddress>(*I))
+      return false;
+
+  return true;
+}
+
 /// callsFunctionThatReturnsTwice - Return true if the function has a call=
 to
 /// setjmp or other function that gcc recognizes as "returning twice".
-///
-/// FIXME: Remove after <rdar://problem/8031714> is fixed.
-/// FIXME: Is the above FIXME valid?
 bool Function::callsFunctionThatReturnsTwice() const {
-  static const char *const ReturnsTwiceFns[] =3D {
-    "_setjmp",
-    "setjmp",
-    "sigsetjmp",
-    "setjmp_syscall",
-    "savectx",
-    "qsetjmp",
-    "vfork",
-    "getcontext"
-  };
-
-  for (const_inst_iterator I =3D inst_begin(this), E =3D inst_end(this); I=
 !=3D E;
-       ++I) {
+  for (const_inst_iterator
+         I =3D inst_begin(this), E =3D inst_end(this); I !=3D E; ++I) {
     const CallInst* callInst =3D dyn_cast<CallInst>(&*I);
     if (!callInst)
       continue;
     if (callInst->canReturnTwice())
       return true;
-
-    // check for known function names.
-    // FIXME: move this to clang.
-    Function *F =3D callInst->getCalledFunction();
-    if (!F)
-      continue;
-    StringRef Name =3D F->getName();
-    for (unsigned J =3D 0, e =3D array_lengthof(ReturnsTwiceFns); J !=3D e=
; ++J) {
-      if (Name =3D=3D ReturnsTwiceFns[J])
-        return true;
-    }
   }
=20
   return false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/GCOV.cpp
--- a/head/contrib/llvm/lib/VMCore/GCOV.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/GCOV.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -107,7 +107,7 @@
     for (unsigned i =3D 0, e =3D Count; i !=3D e; ++i) {
       Blocks[i]->addCount(Buff.readInt64());
     }
-    return true;;
+    return true;
   }
=20
   LineNumber =3D Buff.readInt();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/IRBuilder=
.cpp
--- a/head/contrib/llvm/lib/VMCore/IRBuilder.cpp	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/contrib/llvm/lib/VMCore/IRBuilder.cpp	Tue Apr 17 11:51:51 2012 +=
0300
@@ -24,10 +24,10 @@
 /// specified.  If Name is specified, it is the name of the global variable
 /// created.
 Value *IRBuilderBase::CreateGlobalString(StringRef Str, const Twine &Name)=
 {
-  Constant *StrConstant =3D ConstantArray::get(Context, Str, true);
+  Constant *StrConstant =3D ConstantDataArray::getString(Context, Str);
   Module &M =3D *BB->getParent()->getParent();
   GlobalVariable *GV =3D new GlobalVariable(M, StrConstant->getType(),
-                                          true, GlobalValue::InternalLinka=
ge,
+                                          true, GlobalValue::PrivateLinkag=
e,
                                           StrConstant, "", 0, false);
   GV->setName(Name);
   GV->setUnnamedAddr(true);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Instructi=
on.cpp
--- a/head/contrib/llvm/lib/VMCore/Instruction.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/VMCore/Instruction.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -102,7 +102,6 @@
   case IndirectBr: return "indirectbr";
   case Invoke: return "invoke";
   case Resume: return "resume";
-  case Unwind: return "unwind";
   case Unreachable: return "unreachable";
=20
   // Standard binary operators...
@@ -166,8 +165,6 @@
=20
   default: return "<Invalid operator> ";
   }
-
-  return 0;
 }
=20
 /// isIdenticalTo - Return true if the specified instruction is exactly
@@ -391,59 +388,6 @@
   }
 }
=20
-bool Instruction::isSafeToSpeculativelyExecute() const {
-  for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i)
-    if (Constant *C =3D dyn_cast<Constant>(getOperand(i)))
-      if (C->canTrap())
-        return false;
-
-  switch (getOpcode()) {
-  default:
-    return true;
-  case UDiv:
-  case URem: {
-    // x / y is undefined if y =3D=3D 0, but calcuations like x / 3 are sa=
fe.
-    ConstantInt *Op =3D dyn_cast<ConstantInt>(getOperand(1));
-    return Op && !Op->isNullValue();
-  }
-  case SDiv:
-  case SRem: {
-    // x / y is undefined if y =3D=3D 0, and might be undefined if y =3D=
=3D -1,
-    // but calcuations like x / 3 are safe.
-    ConstantInt *Op =3D dyn_cast<ConstantInt>(getOperand(1));
-    return Op && !Op->isNullValue() && !Op->isAllOnesValue();
-  }
-  case Load: {
-    const LoadInst *LI =3D cast<LoadInst>(this);
-    if (!LI->isUnordered())
-      return false;
-    return LI->getPointerOperand()->isDereferenceablePointer();
-  }
-  case Call:
-    return false; // The called function could have undefined behavior or
-                  // side-effects.
-                  // FIXME: We should special-case some intrinsics (bswap,
-                  // overflow-checking arithmetic, etc.)
-  case VAArg:
-  case Alloca:
-  case Invoke:
-  case PHI:
-  case Store:
-  case Ret:
-  case Br:
-  case IndirectBr:
-  case Switch:
-  case Unwind:
-  case Unreachable:
-  case Fence:
-  case LandingPad:
-  case AtomicRMW:
-  case AtomicCmpXchg:
-  case Resume:
-    return false; // Misc instructions which have effects
-  }
-}
-
 Instruction *Instruction::clone() const {
   Instruction *New =3D clone_impl();
   New->SubclassOptionalData =3D SubclassOptionalData;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Instructi=
ons.cpp
--- a/head/contrib/llvm/lib/VMCore/Instructions.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/lib/VMCore/Instructions.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -625,40 +625,12 @@
=20
 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
   llvm_unreachable("ReturnInst has no successors!");
-  return 0;
 }
=20
 ReturnInst::~ReturnInst() {
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-//                        UnwindInst Implementation
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
-  : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
-                   0, 0, InsertBefore) {
-}
-UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
-  : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
-                   0, 0, InsertAtEnd) {
-}
-
-
-unsigned UnwindInst::getNumSuccessorsV() const {
-  return getNumSuccessors();
-}
-
-void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
-  llvm_unreachable("UnwindInst has no successors!");
-}
-
-BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
-  llvm_unreachable("UnwindInst has no successors!");
-  return 0;
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                        ResumeInst Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -690,7 +662,6 @@
=20
 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
   llvm_unreachable("ResumeInst has no successors!");
-  return 0;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -712,12 +683,11 @@
 }
=20
 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
-  llvm_unreachable("UnwindInst has no successors!");
+  llvm_unreachable("UnreachableInst has no successors!");
 }
=20
 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
-  llvm_unreachable("UnwindInst has no successors!");
-  return 0;
+  llvm_unreachable("UnreachableInst has no successors!");
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1359,6 +1329,15 @@
 ///
 template <typename IndexTy>
 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
+  if (Ptr->isVectorTy()) {
+    assert(IdxList.size() =3D=3D 1 &&
+      "GEP with vector pointers must have a single index");
+    PointerType *PTy =3D dyn_cast<PointerType>(
+        cast<VectorType>(Ptr)->getElementType());
+    assert(PTy && "Gep with invalid vector pointer found");
+    return PTy->getElementType();
+  }
+
   PointerType *PTy =3D dyn_cast<PointerType>(Ptr);
   if (!PTy) return 0;   // Type isn't a pointer type!
   Type *Agg =3D PTy->getElementType();
@@ -1366,7 +1345,7 @@
   // Handle the special case of the empty set index set, which is always v=
alid.
   if (IdxList.empty())
     return Agg;
- =20
+
   // If there is at least one index, the top level type must be sized, oth=
erwise
   // it cannot be 'stepped over'.
   if (!Agg->isSized())
@@ -1396,6 +1375,18 @@
   return getIndexedTypeInternal(Ptr, IdxList);
 }
=20
+unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
+  Type *Ty =3D Ptr->getType();
+
+  if (VectorType *VTy =3D dyn_cast<VectorType>(Ty))
+    Ty =3D VTy->getElementType();
+
+  if (PointerType *PTy =3D dyn_cast<PointerType>(Ty))
+    return PTy->getAddressSpace();
+
+  llvm_unreachable("Invalid GEP pointer type");
+}
+
 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
 /// zeros.  If so, the result pointer and the first operand have the same
 /// value, just potentially different types.
@@ -1558,45 +1549,83 @@
=20
 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
                                         const Value *Mask) {
+  // V1 and V2 must be vectors of the same type.
   if (!V1->getType()->isVectorTy() || V1->getType() !=3D V2->getType())
     return false;
  =20
+  // Mask must be vector of i32.
   VectorType *MaskTy =3D dyn_cast<VectorType>(Mask->getType());
   if (MaskTy =3D=3D 0 || !MaskTy->getElementType()->isIntegerTy(32))
     return false;
=20
   // Check to see if Mask is valid.
+  if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
+    return true;
+
   if (const ConstantVector *MV =3D dyn_cast<ConstantVector>(Mask)) {
-    VectorType *VTy =3D cast<VectorType>(V1->getType());
+    unsigned V1Size =3D cast<VectorType>(V1->getType())->getNumElements();
     for (unsigned i =3D 0, e =3D MV->getNumOperands(); i !=3D e; ++i) {
-      if (ConstantInt* CI =3D dyn_cast<ConstantInt>(MV->getOperand(i))) {
-        if (CI->uge(VTy->getNumElements()*2))
+      if (ConstantInt *CI =3D dyn_cast<ConstantInt>(MV->getOperand(i))) {
+        if (CI->uge(V1Size*2))
           return false;
       } else if (!isa<UndefValue>(MV->getOperand(i))) {
         return false;
       }
     }
+    return true;
   }
-  else if (!isa<UndefValue>(Mask) && !isa<ConstantAggregateZero>(Mask))
-    return false;
  =20
-  return true;
+  if (const ConstantDataSequential *CDS =3D
+        dyn_cast<ConstantDataSequential>(Mask)) {
+    unsigned V1Size =3D cast<VectorType>(V1->getType())->getNumElements();
+    for (unsigned i =3D 0, e =3D MaskTy->getNumElements(); i !=3D e; ++i)
+      if (CDS->getElementAsInteger(i) >=3D V1Size*2)
+        return false;
+    return true;
+  }
+ =20
+  // The bitcode reader can create a place holder for a forward reference
+  // used as the shuffle mask. When this occurs, the shuffle mask will
+  // fall into this case and fail. To avoid this error, do this bit of
+  // ugliness to allow such a mask pass.
+  if (const ConstantExpr *CE =3D dyn_cast<ConstantExpr>(Mask))
+    if (CE->getOpcode() =3D=3D Instruction::UserOp1)
+      return true;
+
+  return false;
 }
=20
 /// getMaskValue - Return the index from the shuffle mask for the specified
 /// output result.  This is either -1 if the element is undef or a number =
less
 /// than 2*numelements.
-int ShuffleVectorInst::getMaskValue(unsigned i) const {
-  const Constant *Mask =3D cast<Constant>(getOperand(2));
-  if (isa<UndefValue>(Mask)) return -1;
-  if (isa<ConstantAggregateZero>(Mask)) return 0;
-  const ConstantVector *MaskCV =3D cast<ConstantVector>(Mask);
-  assert(i < MaskCV->getNumOperands() && "Index out of range");
-
-  if (isa<UndefValue>(MaskCV->getOperand(i)))
+int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
+  assert(i < Mask->getType()->getVectorNumElements() && "Index out of rang=
e");
+  if (ConstantDataSequential *CDS =3Ddyn_cast<ConstantDataSequential>(Mask=
))
+    return CDS->getElementAsInteger(i);
+  Constant *C =3D Mask->getAggregateElement(i);
+  if (isa<UndefValue>(C))
     return -1;
-  return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
-}
+  return cast<ConstantInt>(C)->getZExtValue();
+}
+
+/// getShuffleMask - Return the full mask for this instruction, where each
+/// element is the element number and undef's are returned as -1.
+void ShuffleVectorInst::getShuffleMask(Constant *Mask,
+                                       SmallVectorImpl<int> &Result) {
+  unsigned NumElts =3D Mask->getType()->getVectorNumElements();
+ =20
+  if (ConstantDataSequential *CDS=3Ddyn_cast<ConstantDataSequential>(Mask)=
) {
+    for (unsigned i =3D 0; i !=3D NumElts; ++i)
+      Result.push_back(CDS->getElementAsInteger(i));
+    return;
+  }   =20
+  for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+    Constant *C =3D Mask->getAggregateElement(i);
+    Result.push_back(isa<UndefValue>(C) ? -1 :
+                     cast<ConstantInt>(C)->getZExtValue());
+  }
+}
+
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                             InsertValueInst Class
@@ -1848,46 +1877,27 @@
 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
                                            Instruction *InsertBefore) {
   Value *zero =3D ConstantFP::getZeroValueForNegation(Op->getType());
-  return new BinaryOperator(Instruction::FSub,
-                            zero, Op,
+  return new BinaryOperator(Instruction::FSub, zero, Op,
                             Op->getType(), Name, InsertBefore);
 }
=20
 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
                                            BasicBlock *InsertAtEnd) {
   Value *zero =3D ConstantFP::getZeroValueForNegation(Op->getType());
-  return new BinaryOperator(Instruction::FSub,
-                            zero, Op,
+  return new BinaryOperator(Instruction::FSub, zero, Op,
                             Op->getType(), Name, InsertAtEnd);
 }
=20
 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
                                           Instruction *InsertBefore) {
-  Constant *C;
-  if (VectorType *PTy =3D dyn_cast<VectorType>(Op->getType())) {
-    C =3D Constant::getAllOnesValue(PTy->getElementType());
-    C =3D ConstantVector::get(
-                              std::vector<Constant*>(PTy->getNumElements()=
, C));
-  } else {
-    C =3D Constant::getAllOnesValue(Op->getType());
-  }
- =20
+  Constant *C =3D Constant::getAllOnesValue(Op->getType());
   return new BinaryOperator(Instruction::Xor, Op, C,
                             Op->getType(), Name, InsertBefore);
 }
=20
 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
                                           BasicBlock *InsertAtEnd) {
-  Constant *AllOnes;
-  if (VectorType *PTy =3D dyn_cast<VectorType>(Op->getType())) {
-    // Create a vector of all ones values.
-    Constant *Elt =3D Constant::getAllOnesValue(PTy->getElementType());
-    AllOnes =3D ConstantVector::get(
-                            std::vector<Constant*>(PTy->getNumElements(), =
Elt));
-  } else {
-    AllOnes =3D Constant::getAllOnesValue(Op->getType());
-  }
- =20
+  Constant *AllOnes =3D Constant::getAllOnesValue(Op->getType());
   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
                             Op->getType(), Name, InsertAtEnd);
 }
@@ -1895,10 +1905,8 @@
=20
 // isConstantAllOnes - Helper function for several functions below
 static inline bool isConstantAllOnes(const Value *V) {
-  if (const ConstantInt *CI =3D dyn_cast<ConstantInt>(V))
-    return CI->isAllOnesValue();
-  if (const ConstantVector *CV =3D dyn_cast<ConstantVector>(V))
-    return CV->isAllOnesValue();
+  if (const Constant *C =3D dyn_cast<Constant>(V))
+    return C->isAllOnesValue();
   return false;
 }
=20
@@ -1998,6 +2006,8 @@
 //                                CastInst Class
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void CastInst::anchor() {}
+
 // Just determine if this cast only deals with integral->integral conversi=
on.
 bool CastInst::isIntegerCast() const {
   switch (getOpcode()) {
@@ -2042,8 +2052,7 @@
                           Type *DestTy,
                           Type *IntPtrTy) {
   switch (Opcode) {
-    default:
-      assert(0 && "Invalid CastOp");
+    default: llvm_unreachable("Invalid CastOp");
     case Instruction::Trunc:
     case Instruction::ZExt:
     case Instruction::SExt:=20
@@ -2236,13 +2245,10 @@
     case 99:=20
       // cast combination can't happen (error in input). This is for all c=
ases
       // where the MidTy is not the same for the two cast instructions.
-      assert(0 && "Invalid Cast Combination");
-      return 0;
+      llvm_unreachable("Invalid Cast Combination");
     default:
-      assert(0 && "Error in CastResults table!!!");
-      return 0;
+      llvm_unreachable("Error in CastResults table!!!");
   }
-  return 0;
 }
=20
 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,=20
@@ -2262,10 +2268,8 @@
     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
-    default:
-      assert(0 && "Invalid opcode provided");
+    default: llvm_unreachable("Invalid opcode provided");
   }
-  return 0;
 }
=20
 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
@@ -2285,10 +2289,8 @@
     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
-    default:
-      assert(0 && "Invalid opcode provided");
+    default: llvm_unreachable("Invalid opcode provided");
   }
-  return 0;
 }
=20
 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,=20
@@ -2557,9 +2559,8 @@
       assert(DestBits =3D=3D SrcBits &&
              "Casting vector to floating point of different width");
       return BitCast;                             // same size, no-op cast
-    } else {
-      llvm_unreachable("Casting pointer or non-first class to float");
     }
+    llvm_unreachable("Casting pointer or non-first class to float");
   } else if (DestTy->isVectorTy()) {
     assert(DestBits =3D=3D SrcBits &&
            "Illegal cast to vector (wrong type or size)");
@@ -2569,24 +2570,16 @@
       return BitCast;                               // ptr -> ptr
     } else if (SrcTy->isIntegerTy()) {
       return IntToPtr;                              // int -> ptr
-    } else {
-      assert(0 && "Casting pointer to other than pointer or int");
     }
+    llvm_unreachable("Casting pointer to other than pointer or int");
   } else if (DestTy->isX86_MMXTy()) {
     if (SrcTy->isVectorTy()) {
       assert(DestBits =3D=3D SrcBits && "Casting vector of wrong width to =
X86_MMX");
       return BitCast;                               // 64-bit vector to MMX
-    } else {
-      assert(0 && "Illegal cast to X86_MMX");
     }
-  } else {
-    assert(0 && "Casting to type that is not first-class");
+    llvm_unreachable("Illegal cast to X86_MMX");
   }
-
-  // If we fall through to here we probably hit an assertion cast above
-  // and assertions are not turned on. Anything we return is an error, so
-  // BitCast is as good a choice as any.
-  return BitCast;
+  llvm_unreachable("Casting to type that is not first-class");
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2645,9 +2638,21 @@
     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
       SrcLength =3D=3D DstLength;
   case Instruction::PtrToInt:
-    return SrcTy->isPointerTy() && DstTy->isIntegerTy();
+    if (isa<VectorType>(SrcTy) !=3D isa<VectorType>(DstTy))
+      return false;
+    if (VectorType *VT =3D dyn_cast<VectorType>(SrcTy))
+      if (VT->getNumElements() !=3D cast<VectorType>(DstTy)->getNumElement=
s())
+        return false;
+    return SrcTy->getScalarType()->isPointerTy() &&
+           DstTy->getScalarType()->isIntegerTy();
   case Instruction::IntToPtr:
-    return SrcTy->isIntegerTy() && DstTy->isPointerTy();
+    if (isa<VectorType>(SrcTy) !=3D isa<VectorType>(DstTy))
+      return false;
+    if (VectorType *VT =3D dyn_cast<VectorType>(SrcTy))
+      if (VT->getNumElements() !=3D cast<VectorType>(DstTy)->getNumElement=
s())
+        return false;
+    return SrcTy->getScalarType()->isIntegerTy() &&
+           DstTy->getScalarType()->isPointerTy();
   case Instruction::BitCast:
     // BitCast implies a no-op cast of type only. No bits change.
     // However, you can't cast pointers to anything but pointers.
@@ -2890,7 +2895,7 @@
=20
 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
   switch (pred) {
-    default: assert(0 && "Unknown cmp predicate!");
+    default: llvm_unreachable("Unknown cmp predicate!");
     case ICMP_EQ: return ICMP_NE;
     case ICMP_NE: return ICMP_EQ;
     case ICMP_UGT: return ICMP_ULE;
@@ -2923,7 +2928,7 @@
=20
 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
   switch (pred) {
-    default: assert(0 && "Unknown icmp predicate!");
+    default: llvm_unreachable("Unknown icmp predicate!");
     case ICMP_EQ: case ICMP_NE:=20
     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:=20
        return pred;
@@ -2936,7 +2941,7 @@
=20
 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
   switch (pred) {
-    default: assert(0 && "Unknown icmp predicate!");
+    default: llvm_unreachable("Unknown icmp predicate!");
     case ICMP_EQ: case ICMP_NE:=20
     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:=20
        return pred;
@@ -3012,7 +3017,7 @@
=20
 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
   switch (pred) {
-    default: assert(0 && "Unknown cmp predicate!");
+    default: llvm_unreachable("Unknown cmp predicate!");
     case ICMP_EQ: case ICMP_NE:
       return pred;
     case ICMP_SGT: return ICMP_SLT;
@@ -3147,31 +3152,32 @@
 /// addCase - Add an entry to the switch instruction...
 ///
 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
+  unsigned NewCaseIdx =3D getNumCases();=20
   unsigned OpNo =3D NumOperands;
   if (OpNo+2 > ReservedSpace)
     growOperands();  // Get more space!
   // Initialize some new operands.
   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
   NumOperands =3D OpNo+2;
-  OperandList[OpNo] =3D OnVal;
-  OperandList[OpNo+1] =3D Dest;
-}
-
-/// removeCase - This method removes the specified successor from the swit=
ch
-/// instruction.  Note that this cannot be used to remove the default
-/// destination (successor #0).
-///
-void SwitchInst::removeCase(unsigned idx) {
-  assert(idx !=3D 0 && "Cannot remove the default case!");
-  assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
+  CaseIt Case(this, NewCaseIdx);
+  Case.setValue(OnVal);
+  Case.setSuccessor(Dest);
+}
+
+/// removeCase - This method removes the specified case and its successor
+/// from the switch instruction.
+void SwitchInst::removeCase(CaseIt i) {
+  unsigned idx =3D i.getCaseIndex();
+ =20
+  assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
=20
   unsigned NumOps =3D getNumOperands();
   Use *OL =3D OperandList;
=20
   // Overwrite this case with the end of the list.
-  if ((idx + 1) * 2 !=3D NumOps) {
-    OL[idx * 2] =3D OL[NumOps - 2];
-    OL[idx * 2 + 1] =3D OL[NumOps - 1];
+  if (2 + (idx + 1) * 2 !=3D NumOps) {
+    OL[2 + idx * 2] =3D OL[NumOps - 2];
+    OL[2 + idx * 2 + 1] =3D OL[NumOps - 1];
   }
=20
   // Nuke the last value.
@@ -3438,15 +3444,11 @@
 }
=20
 InsertElementInst *InsertElementInst::clone_impl() const {
-  return InsertElementInst::Create(getOperand(0),
-                                   getOperand(1),
-                                   getOperand(2));
+  return InsertElementInst::Create(getOperand(0), getOperand(1), getOperan=
d(2));
 }
=20
 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
-  return new ShuffleVectorInst(getOperand(0),
-                           getOperand(1),
-                           getOperand(2));
+  return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2)=
);
 }
=20
 PHINode *PHINode::clone_impl() const {
@@ -3482,11 +3484,6 @@
   return new(1) ResumeInst(*this);
 }
=20
-UnwindInst *UnwindInst::clone_impl() const {
-  LLVMContext &Context =3D getContext();
-  return new UnwindInst(Context);
-}
-
 UnreachableInst *UnreachableInst::clone_impl() const {
   LLVMContext &Context =3D getContext();
   return new UnreachableInst(Context);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/LLVMConte=
xt.cpp
--- a/head/contrib/llvm/lib/VMCore/LLVMContext.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/VMCore/LLVMContext.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -43,6 +43,16 @@
   // Create the 'prof' metadata kind.
   unsigned ProfID =3D getMDKindID("prof");
   assert(ProfID =3D=3D MD_prof && "prof kind id drifted"); (void)ProfID;
+
+  // Create the 'fpaccuracy' metadata kind.
+  unsigned FPAccuracyID =3D getMDKindID("fpaccuracy");
+  assert(FPAccuracyID =3D=3D MD_fpaccuracy && "fpaccuracy kind id drifted"=
);
+  (void)FPAccuracyID;
+
+  // Create the 'range' metadata kind.
+  unsigned RangeID =3D getMDKindID("range");
+  assert(RangeID =3D=3D MD_range && "range kind id drifted");
+  (void)RangeID;
 }
 LLVMContext::~LLVMContext() { delete pImpl; }
=20
@@ -78,11 +88,11 @@
   return pImpl->InlineAsmDiagContext;
 }
=20
-void LLVMContext::emitError(StringRef ErrorStr) {
+void LLVMContext::emitError(const Twine &ErrorStr) {
   emitError(0U, ErrorStr);
 }
=20
-void LLVMContext::emitError(const Instruction *I, StringRef ErrorStr) {
+void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
   unsigned LocCookie =3D 0;
   if (const MDNode *SrcLoc =3D I->getMetadata("srcloc")) {
     if (SrcLoc->getNumOperands() !=3D 0)
@@ -92,7 +102,7 @@
   return emitError(LocCookie, ErrorStr);
 }
=20
-void LLVMContext::emitError(unsigned LocCookie, StringRef ErrorStr) {
+void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
   // If there is no error handler installed, just print the error and exit.
   if (pImpl->InlineAsmDiagHandler =3D=3D 0) {
     errs() << "error: " << ErrorStr << "\n";
@@ -100,7 +110,7 @@
   }
=20
   // If we do have an error handler, we can report the error and keep goin=
g.
-  SMDiagnostic Diag("", "error: " + ErrorStr.str());
+  SMDiagnostic Diag("", SourceMgr::DK_Error, ErrorStr.str());
=20
   pImpl->InlineAsmDiagHandler(Diag, pImpl->InlineAsmDiagContext, LocCookie=
);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/LLVMConte=
xtImpl.cpp
--- a/head/contrib/llvm/lib/VMCore/LLVMContextImpl.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/LLVMContextImpl.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -21,6 +21,7 @@
   : TheTrueVal(0), TheFalseVal(0),
     VoidTy(C, Type::VoidTyID),
     LabelTy(C, Type::LabelTyID),
+    HalfTy(C, Type::HalfTyID),
     FloatTy(C, Type::FloatTyID),
     DoubleTy(C, Type::DoubleTyID),
     MetadataTy(C, Type::MetadataTyID),
@@ -47,6 +48,16 @@
     P.second->dropAllReferences();
   }
 };
+
+// Temporary - drops pair.first instead of second.
+struct DropFirst {
+  // Takes the value_type of a ConstantUniqueMap's internal map, whose 'se=
cond'
+  // is a Constant*.
+  template<typename PairT>
+  void operator()(const PairT &P) {
+    P.first->dropAllReferences();
+  }
+};
 }
=20
 LLVMContextImpl::~LLVMContextImpl() {
@@ -57,25 +68,32 @@
   std::vector<Module*> Modules(OwnedModules.begin(), OwnedModules.end());
   DeleteContainerPointers(Modules);
  =20
+  // Free the constants.  This is important to do here to ensure that they=
 are
+  // freed before the LeakDetector is torn down.
   std::for_each(ExprConstants.map_begin(), ExprConstants.map_end(),
                 DropReferences());
   std::for_each(ArrayConstants.map_begin(), ArrayConstants.map_end(),
-                DropReferences());
+                DropFirst());
   std::for_each(StructConstants.map_begin(), StructConstants.map_end(),
-                DropReferences());
+                DropFirst());
   std::for_each(VectorConstants.map_begin(), VectorConstants.map_end(),
-                DropReferences());
+                DropFirst());
   ExprConstants.freeConstants();
   ArrayConstants.freeConstants();
   StructConstants.freeConstants();
   VectorConstants.freeConstants();
-  AggZeroConstants.freeConstants();
-  NullPtrConstants.freeConstants();
-  UndefValueConstants.freeConstants();
+  DeleteContainerSeconds(CAZConstants);
+  DeleteContainerSeconds(CPNConstants);
+  DeleteContainerSeconds(UVConstants);
   InlineAsms.freeConstants();
   DeleteContainerSeconds(IntConstants);
   DeleteContainerSeconds(FPConstants);
  =20
+  for (StringMap<ConstantDataSequential*>::iterator I =3D CDSConstants.beg=
in(),
+       E =3D CDSConstants.end(); I !=3D E; ++I)
+    delete I->second;
+  CDSConstants.clear();
+ =20
   // Destroy MDNodes.  ~MDNode can move and remove nodes between the MDNod=
eSet
   // and the NonUniquedMDNodes sets, so copy the values out first.
   SmallVector<MDNode*, 8> MDNodes;
@@ -92,3 +110,24 @@
   // Destroy MDStrings.
   DeleteContainerSeconds(MDStringCache);
 }
+
+// ConstantsContext anchors
+void UnaryConstantExpr::anchor() { }
+
+void BinaryConstantExpr::anchor() { }
+
+void SelectConstantExpr::anchor() { }
+
+void ExtractElementConstantExpr::anchor() { }
+
+void InsertElementConstantExpr::anchor() { }
+
+void ShuffleVectorConstantExpr::anchor() { }
+
+void ExtractValueConstantExpr::anchor() { }
+
+void InsertValueConstantExpr::anchor() { }
+
+void GetElementPtrConstantExpr::anchor() { }
+
+void CompareConstantExpr::anchor() { }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/LLVMConte=
xtImpl.h
--- a/head/contrib/llvm/lib/VMCore/LLVMContextImpl.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/lib/VMCore/LLVMContextImpl.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -29,6 +29,7 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/Hashing.h"
 #include <vector>
=20
 namespace llvm {
@@ -51,12 +52,14 @@
     bool operator!=3D(const KeyTy& that) const {
       return !this->operator=3D=3D(that);
     }
+    friend hash_code hash_value(const KeyTy &Key) {
+      return hash_combine(Key.type, Key.val);
+    }
   };
   static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
   static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
   static unsigned getHashValue(const KeyTy &Key) {
-    return DenseMapInfo<void*>::getHashValue(Key.type) ^=20
-      Key.val.getHashValue();
+    return static_cast<unsigned>(hash_value(Key));
   }
   static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
     return LHS =3D=3D RHS;
@@ -74,6 +77,9 @@
     bool operator!=3D(const KeyTy& that) const {
       return !this->operator=3D=3D(that);
     }
+    friend hash_code hash_value(const KeyTy &Key) {
+      return hash_combine(Key.val);
+    }
   };
   static inline KeyTy getEmptyKey() {=20
     return KeyTy(APFloat(APFloat::Bogus,1));
@@ -82,13 +88,132 @@
     return KeyTy(APFloat(APFloat::Bogus,2));=20
   }
   static unsigned getHashValue(const KeyTy &Key) {
-    return Key.val.getHashValue();
+    return static_cast<unsigned>(hash_value(Key));
   }
   static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
     return LHS =3D=3D RHS;
   }
 };
=20
+struct AnonStructTypeKeyInfo {
+  struct KeyTy {
+    ArrayRef<Type*> ETypes;
+    bool isPacked;
+    KeyTy(const ArrayRef<Type*>& E, bool P) :
+      ETypes(E), isPacked(P) {}
+    KeyTy(const KeyTy& that) :
+      ETypes(that.ETypes), isPacked(that.isPacked) {}
+    KeyTy(const StructType* ST) :
+      ETypes(ArrayRef<Type*>(ST->element_begin(), ST->element_end())),
+      isPacked(ST->isPacked()) {}
+    bool operator=3D=3D(const KeyTy& that) const {
+      if (isPacked !=3D that.isPacked)
+        return false;
+      if (ETypes !=3D that.ETypes)
+        return false;
+      return true;
+    }
+    bool operator!=3D(const KeyTy& that) const {
+      return !this->operator=3D=3D(that);
+    }
+  };
+  static inline StructType* getEmptyKey() {
+    return DenseMapInfo<StructType*>::getEmptyKey();
+  }
+  static inline StructType* getTombstoneKey() {
+    return DenseMapInfo<StructType*>::getTombstoneKey();
+  }
+  static unsigned getHashValue(const KeyTy& Key) {
+    return hash_combine(hash_combine_range(Key.ETypes.begin(),
+                                           Key.ETypes.end()),
+                        Key.isPacked);
+  }
+  static unsigned getHashValue(const StructType *ST) {
+    return getHashValue(KeyTy(ST));
+  }
+  static bool isEqual(const KeyTy& LHS, const StructType *RHS) {
+    if (RHS =3D=3D getEmptyKey() || RHS =3D=3D getTombstoneKey())
+      return false;
+    return LHS =3D=3D KeyTy(RHS);
+  }
+  static bool isEqual(const StructType *LHS, const StructType *RHS) {
+    return LHS =3D=3D RHS;
+  }
+};
+
+struct FunctionTypeKeyInfo {
+  struct KeyTy {
+    const Type *ReturnType;
+    ArrayRef<Type*> Params;
+    bool isVarArg;
+    KeyTy(const Type* R, const ArrayRef<Type*>& P, bool V) :
+      ReturnType(R), Params(P), isVarArg(V) {}
+    KeyTy(const KeyTy& that) :
+      ReturnType(that.ReturnType),
+      Params(that.Params),
+      isVarArg(that.isVarArg) {}
+    KeyTy(const FunctionType* FT) :
+      ReturnType(FT->getReturnType()),
+      Params(ArrayRef<Type*>(FT->param_begin(), FT->param_end())),
+      isVarArg(FT->isVarArg()) {}
+    bool operator=3D=3D(const KeyTy& that) const {
+      if (ReturnType !=3D that.ReturnType)
+        return false;
+      if (isVarArg !=3D that.isVarArg)
+        return false;
+      if (Params !=3D that.Params)
+        return false;
+      return true;
+    }
+    bool operator!=3D(const KeyTy& that) const {
+      return !this->operator=3D=3D(that);
+    }
+  };
+  static inline FunctionType* getEmptyKey() {
+    return DenseMapInfo<FunctionType*>::getEmptyKey();
+  }
+  static inline FunctionType* getTombstoneKey() {
+    return DenseMapInfo<FunctionType*>::getTombstoneKey();
+  }
+  static unsigned getHashValue(const KeyTy& Key) {
+    return hash_combine(Key.ReturnType,
+                        hash_combine_range(Key.Params.begin(),
+                                           Key.Params.end()),
+                        Key.isVarArg);
+  }
+  static unsigned getHashValue(const FunctionType *FT) {
+    return getHashValue(KeyTy(FT));
+  }
+  static bool isEqual(const KeyTy& LHS, const FunctionType *RHS) {
+    if (RHS =3D=3D getEmptyKey() || RHS =3D=3D getTombstoneKey())
+      return false;
+    return LHS =3D=3D KeyTy(RHS);
+  }
+  static bool isEqual(const FunctionType *LHS, const FunctionType *RHS) {
+    return LHS =3D=3D RHS;
+  }
+};
+
+// Provide a FoldingSetTrait::Equals specialization for MDNode that can us=
e a
+// shortcut to avoid comparing all operands.
+template<> struct FoldingSetTrait<MDNode> : DefaultFoldingSetTrait<MDNode>=
 {
+  static bool Equals(const MDNode &X, const FoldingSetNodeID &ID,
+                     unsigned IDHash, FoldingSetNodeID &TempID) {
+    assert(!X.isNotUniqued() && "Non-uniqued MDNode in FoldingSet?");
+    // First, check if the cached hashes match.  If they don't we can skip=
 the
+    // expensive operand walk.
+    if (X.Hash !=3D IDHash)
+      return false;
+
+    // If they match we have to compare the operands.
+    X.Profile(TempID);
+    return TempID =3D=3D ID;
+  }
+  static unsigned ComputeHash(const MDNode &X, FoldingSetNodeID &) {
+    return X.Hash; // Return cached hash.
+  }
+};
+
 /// DebugRecVH - This is a CallbackVH used to keep the Scope -> index maps
 /// up to date as MDNodes mutate.  This class is implemented in DebugLoc.c=
pp.
 class DebugRecVH : public CallbackVH {
@@ -129,7 +254,7 @@
                          DenseMapAPFloatKeyInfo> FPMapTy;
   FPMapTy FPConstants;
  =20
-  StringMap<MDString*> MDStringCache;
+  StringMap<Value*> MDStringCache;
  =20
   FoldingSet<MDNode> MDNodeSet;
   // MDNodes may be uniqued or not uniqued.  When they're not uniqued, they
@@ -138,23 +263,23 @@
   // on Context destruction.
   SmallPtrSet<MDNode*, 1> NonUniquedMDNodes;
  =20
-  ConstantUniqueMap<char, char, Type, ConstantAggregateZero> AggZeroConsta=
nts;
+  DenseMap<Type*, ConstantAggregateZero*> CAZConstants;
=20
-  typedef ConstantUniqueMap<std::vector<Constant*>, ArrayRef<Constant*>,
-    ArrayType, ConstantArray, true /*largekey*/> ArrayConstantsTy;
+  typedef ConstantAggrUniqueMap<ArrayType, ConstantArray> ArrayConstantsTy;
   ArrayConstantsTy ArrayConstants;
  =20
-  typedef ConstantUniqueMap<std::vector<Constant*>, ArrayRef<Constant*>,
-    StructType, ConstantStruct, true /*largekey*/> StructConstantsTy;
+  typedef ConstantAggrUniqueMap<StructType, ConstantStruct> StructConstant=
sTy;
   StructConstantsTy StructConstants;
  =20
-  typedef ConstantUniqueMap<std::vector<Constant*>, ArrayRef<Constant*>,
-                            VectorType, ConstantVector> VectorConstantsTy;
+  typedef ConstantAggrUniqueMap<VectorType, ConstantVector> VectorConstant=
sTy;
   VectorConstantsTy VectorConstants;
  =20
-  ConstantUniqueMap<char, char, PointerType, ConstantPointerNull>
-    NullPtrConstants;
-  ConstantUniqueMap<char, char, Type, UndefValue> UndefValueConstants;
+  DenseMap<PointerType*, ConstantPointerNull*> CPNConstants;
+
+  DenseMap<Type*, UndefValue*> UVConstants;
+ =20
+  StringMap<ConstantDataSequential*> CDSConstants;
+
  =20
   DenseMap<std::pair<Function*, BasicBlock*> , BlockAddress*> BlockAddress=
es;
   ConstantUniqueMap<ExprMapKeyType, const ExprMapKeyType&, Type, ConstantE=
xpr>
@@ -169,7 +294,7 @@
   LeakDetectorImpl<Value> LLVMObjects;
  =20
   // Basic type instances.
-  Type VoidTy, LabelTy, FloatTy, DoubleTy, MetadataTy;
+  Type VoidTy, LabelTy, HalfTy, FloatTy, DoubleTy, MetadataTy;
   Type X86_FP80Ty, FP128Ty, PPC_FP128Ty, X86_MMXTy;
   IntegerType Int1Ty, Int8Ty, Int16Ty, Int32Ty, Int64Ty;
=20
@@ -180,9 +305,10 @@
  =20
   DenseMap<unsigned, IntegerType*> IntegerTypes;
  =20
-  // TODO: Optimize FunctionTypes/AnonStructTypes!
-  std::map<std::vector<Type*>, FunctionType*> FunctionTypes;
-  std::map<std::vector<Type*>, StructType*> AnonStructTypes;
+  typedef DenseMap<FunctionType*, bool, FunctionTypeKeyInfo> FunctionTypeM=
ap;
+  FunctionTypeMap FunctionTypes;
+  typedef DenseMap<StructType*, bool, AnonStructTypeKeyInfo> StructTypeMap;
+  StructTypeMap AnonStructTypes;
   StringMap<StructType*> NamedStructTypes;
   unsigned NamedStructTypesUniqueID;
    =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Metadata.=
cpp
--- a/head/contrib/llvm/lib/VMCore/Metadata.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/VMCore/Metadata.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -29,16 +29,19 @@
 // MDString implementation.
 //
=20
-MDString::MDString(LLVMContext &C, StringRef S)
-  : Value(Type::getMetadataTy(C), Value::MDStringVal), Str(S) {}
+void MDString::anchor() { }
+
+MDString::MDString(LLVMContext &C)
+  : Value(Type::getMetadataTy(C), Value::MDStringVal) {}
=20
 MDString *MDString::get(LLVMContext &Context, StringRef Str) {
   LLVMContextImpl *pImpl =3D Context.pImpl;
-  StringMapEntry<MDString *> &Entry =3D
+  StringMapEntry<Value*> &Entry =3D
     pImpl->MDStringCache.GetOrCreateValue(Str);
-  MDString *&S =3D Entry.getValue();
-  if (!S) S =3D new MDString(Context, Entry.getKey());
-  return S;
+  Value *&S =3D Entry.getValue();
+  if (!S) S =3D new MDString(Context);
+  S->setValueName(&Entry);
+  return cast<MDString>(S);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -48,14 +51,26 @@
 // Use CallbackVH to hold MDNode operands.
 namespace llvm {
 class MDNodeOperand : public CallbackVH {
-  MDNode *Parent;
+  MDNode *getParent() {
+    MDNodeOperand *Cur =3D this;
+
+    while (Cur->getValPtrInt() !=3D 1)
+      --Cur;
+
+    assert(Cur->getValPtrInt() =3D=3D 1 &&
+           "Couldn't find the beginning of the operand list!");
+    return reinterpret_cast<MDNode*>(Cur) - 1;
+  }
+
 public:
-  MDNodeOperand(Value *V, MDNode *P) : CallbackVH(V), Parent(P) {}
+  MDNodeOperand(Value *V) : CallbackVH(V) {}
   ~MDNodeOperand() {}
=20
-  void set(Value *V) {
-    setValPtr(V);
-  }
+  void set(Value *V) { this->setValPtr(V); }
+
+  /// setAsFirstOperand - Accessor method to mark the operand as the first=
 in
+  /// the list.
+  void setAsFirstOperand(unsigned V) { this->setValPtrInt(V); }
=20
   virtual void deleted();
   virtual void allUsesReplacedWith(Value *NV);
@@ -64,15 +79,13 @@
=20
=20
 void MDNodeOperand::deleted() {
-  Parent->replaceOperand(this, 0);
+  getParent()->replaceOperand(this, 0);
 }
=20
 void MDNodeOperand::allUsesReplacedWith(Value *NV) {
-  Parent->replaceOperand(this, NV);
+  getParent()->replaceOperand(this, NV);
 }
=20
-
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // MDNode implementation.
 //
@@ -85,6 +98,11 @@
   return reinterpret_cast<MDNodeOperand*>(N+1)+Op;
 }
=20
+void MDNode::replaceOperandWith(unsigned i, Value *Val) {
+  MDNodeOperand *Op =3D getOperandPtr(this, i);
+  replaceOperand(Op, Val);
+}
+
 MDNode::MDNode(LLVMContext &C, ArrayRef<Value*> Vals, bool isFunctionLocal)
 : Value(Type::getMetadataTy(C), Value::MDNodeVal) {
   NumOperands =3D Vals.size();
@@ -95,8 +113,13 @@
   // Initialize the operand list, which is co-allocated on the end of the =
node.
   unsigned i =3D 0;
   for (MDNodeOperand *Op =3D getOperandPtr(this, 0), *E =3D Op+NumOperands;
-       Op !=3D E; ++Op, ++i)
-    new (Op) MDNodeOperand(Vals[i], this);
+       Op !=3D E; ++Op, ++i) {
+    new (Op) MDNodeOperand(Vals[i]);
+
+    // Mark the first MDNodeOperand as being the first in the list of oper=
ands.
+    if (i =3D=3D 0)
+      Op->setAsFirstOperand(1);
+  }
 }
=20
=20
@@ -161,12 +184,13 @@
 const Function *MDNode::getFunction() const {
 #ifndef NDEBUG
   return assertLocalFunction(this);
-#endif
+#else
   if (!isFunctionLocal()) return NULL;
   for (unsigned i =3D 0, e =3D getNumOperands(); i !=3D e; ++i)
     if (const Function *F =3D getFunctionForValue(getOperand(i)))
       return F;
   return NULL;
+#endif
 }
=20
 // destroy - Delete this node.  Only when there are no uses.
@@ -197,11 +221,11 @@
     ID.AddPointer(Vals[i]);
=20
   void *InsertPoint;
-  MDNode *N =3D NULL;
- =20
-  if ((N =3D pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint)))
+  MDNode *N =3D pImpl->MDNodeSet.FindNodeOrInsertPos(ID, InsertPoint);
+
+  if (N || !Insert)
     return N;
-   =20
+
   bool isFunctionLocal =3D false;
   switch (FL) {
   case FL_Unknown:
@@ -226,6 +250,9 @@
   void *Ptr =3D malloc(sizeof(MDNode)+Vals.size()*sizeof(MDNodeOperand));
   N =3D new (Ptr) MDNode(Context, Vals, isFunctionLocal);
=20
+  // Cache the operand hash.
+  N->Hash =3D ID.ComputeHash();
+
   // InsertPoint will have been set by the FindNodeOrInsertPos call.
   pImpl->MDNodeSet.InsertNode(N, InsertPoint);
=20
@@ -349,6 +376,8 @@
     return;
   }
=20
+  // Cache the operand hash.
+  Hash =3D ID.ComputeHash();
   // InsertPoint will have been set by the FindNodeOrInsertPos call.
   pImpl->MDNodeSet.InsertNode(this, InsertPoint);
=20
@@ -425,12 +454,12 @@
 // Instruction Metadata method implementations.
 //
=20
-void Instruction::setMetadata(const char *Kind, MDNode *Node) {
+void Instruction::setMetadata(StringRef Kind, MDNode *Node) {
   if (Node =3D=3D 0 && !hasMetadata()) return;
   setMetadata(getContext().getMDKindID(Kind), Node);
 }
=20
-MDNode *Instruction::getMetadataImpl(const char *Kind) const {
+MDNode *Instruction::getMetadataImpl(StringRef Kind) const {
   return getMetadataImpl(getContext().getMDKindID(Kind));
 }
=20
@@ -468,9 +497,11 @@
   }
=20
   // Otherwise, we're removing metadata from an instruction.
-  assert(hasMetadataHashEntry() &&
-         getContext().pImpl->MetadataStore.count(this) &&
+  assert((hasMetadataHashEntry() =3D=3D
+          getContext().pImpl->MetadataStore.count(this)) &&
          "HasMetadata bit out of date!");
+  if (!hasMetadataHashEntry())
+    return;  // Nothing to remove!
   LLVMContextImpl::MDMapTy &Info =3D getContext().pImpl->MetadataStore[thi=
s];
=20
   // Common case is removing the only entry.
@@ -541,17 +572,15 @@
          getContext().pImpl->MetadataStore.count(this) &&
          "Shouldn't have called this");
   const LLVMContextImpl::MDMapTy &Info =3D
-  getContext().pImpl->MetadataStore.find(this)->second;
+    getContext().pImpl->MetadataStore.find(this)->second;
   assert(!Info.empty() && "Shouldn't have called this");
- =20
   Result.append(Info.begin(), Info.end());
- =20
+
   // Sort the resulting array so it is stable.
   if (Result.size() > 1)
     array_pod_sort(Result.begin(), Result.end());
 }
=20
-
 /// clearMetadataHashEntries - Clear all hashtable-based metadata from
 /// this instruction.
 void Instruction::clearMetadataHashEntries() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Module.cpp
--- a/head/contrib/llvm/lib/VMCore/Module.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/Module.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -321,11 +321,67 @@
   return NMD;
 }
=20
+/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
+/// delete it.
 void Module::eraseNamedMetadata(NamedMDNode *NMD) {
   static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getNa=
me());
   NamedMDList.erase(NMD);
 }
=20
+/// getModuleFlagsMetadata - Returns the module flags in the provided vect=
or.
+void Module::
+getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
+  const NamedMDNode *ModFlags =3D getModuleFlagsMetadata();
+  if (!ModFlags) return;
+
+  for (unsigned i =3D 0, e =3D ModFlags->getNumOperands(); i !=3D e; ++i) {
+    MDNode *Flag =3D ModFlags->getOperand(i);
+    ConstantInt *Behavior =3D cast<ConstantInt>(Flag->getOperand(0));
+    MDString *Key =3D cast<MDString>(Flag->getOperand(1));
+    Value *Val =3D Flag->getOperand(2);
+    Flags.push_back(ModuleFlagEntry(ModFlagBehavior(Behavior->getZExtValue=
()),
+                                    Key, Val));
+  }
+}
+
+/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
+/// represents module-level flags. This method returns null if there are no
+/// module-level flags.
+NamedMDNode *Module::getModuleFlagsMetadata() const {
+  return getNamedMetadata("llvm.module.flags");
+}
+
+/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module=
 that
+/// represents module-level flags. If module-level flags aren't found, it
+/// creates the named metadata that contains them.
+NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
+  return getOrInsertNamedMetadata("llvm.module.flags");
+}
+
+/// addModuleFlag - Add a module-level flag to the module-level flags
+/// metadata. It will create the module-level flags named metadata if it d=
oesn't
+/// already exist.
+void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
+                           Value *Val) {
+  Type *Int32Ty =3D Type::getInt32Ty(Context);
+  Value *Ops[3] =3D {
+    ConstantInt::get(Int32Ty, Behavior), MDString::get(Context, Key), Val
+  };
+  getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
+}
+void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
+                           uint32_t Val) {
+  Type *Int32Ty =3D Type::getInt32Ty(Context);
+  addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
+}
+void Module::addModuleFlag(MDNode *Node) {
+  assert(Node->getNumOperands() =3D=3D 3 &&
+         "Invalid number of operands for module flag!");
+  assert(isa<ConstantInt>(Node->getOperand(0)) &&
+         isa<MDString>(Node->getOperand(1)) &&
+         "Invalid operand types for module flag!");
+  getOrInsertModuleFlagsMetadata()->addOperand(Node);
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Methods to control the materialization of GlobalValues in the Module.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Pass.cpp
--- a/head/contrib/llvm/lib/VMCore/Pass.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/Pass.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,11 +25,9 @@
 // Pass Implementation
 //
=20
-Pass::Pass(PassKind K, char &pid) : Resolver(0), PassID(&pid), Kind(K) { }
-
 // Force out-of-line virtual method.
-Pass::~Pass() {=20
-  delete Resolver;=20
+Pass::~Pass() {
+  delete Resolver;
 }
=20
 // Force out-of-line virtual method.
@@ -48,7 +46,7 @@
   return Resolver->getAnalysisIfAvailable(&AID, true) !=3D 0;
 }
=20
-// dumpPassStructure - Implement the -debug-passes=3DStructure option
+// dumpPassStructure - Implement the -debug-pass=3DStructure option
 void Pass::dumpPassStructure(unsigned Offset) {
   dbgs().indent(Offset*2) << getPassName() << "\n";
 }
@@ -71,7 +69,7 @@
=20
 PassManagerType Pass::getPotentialPassManagerType() const {
   // Default implementation.
-  return PMT_Unknown;=20
+  return PMT_Unknown;
 }
=20
 void Pass::getAnalysisUsage(AnalysisUsage &) const {
@@ -155,9 +153,8 @@
=20
 Pass *BasicBlockPass::createPrinterPass(raw_ostream &O,
                                         const std::string &Banner) const {
- =20
+
   llvm_unreachable("BasicBlockPass printing unsupported.");
-  return 0;
 }
=20
 bool BasicBlockPass::doInitialization(Module &) {
@@ -181,7 +178,7 @@
 }
=20
 PassManagerType BasicBlockPass::getPotentialPassManagerType() const {
-  return PMT_BasicBlockPassManager;=20
+  return PMT_BasicBlockPassManager;
 }
=20
 const PassInfo *Pass::lookupPassInfo(const void *TI) {
@@ -192,6 +189,13 @@
   return PassRegistry::getPassRegistry()->getPassInfo(Arg);
 }
=20
+Pass *Pass::createPass(AnalysisID ID) {
+  const PassInfo *PI =3D PassRegistry::getPassRegistry()->getPassInfo(ID);
+  if (!PI)
+    return NULL;
+  return PI->createPass();
+}
+
 Pass *PassInfo::createPass() const {
   assert((!isAnalysisGroup() || NormalCtor) &&
          "No default implementation found for analysis group!");
@@ -246,7 +250,7 @@
     typedef AnalysisUsage::VectorType VectorType;
     VectorType &CFGOnlyList;
     GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
-   =20
+
     void passEnumerate(const PassInfo *P) {
       if (P->isCFGOnlyPass())
         CFGOnlyList.push_back(P->getTypeInfo());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/PassManag=
er.cpp
--- a/head/contrib/llvm/lib/VMCore/PassManager.cpp	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/lib/VMCore/PassManager.cpp	Tue Apr 17 11:51:51 2012=
 +0300
@@ -14,7 +14,6 @@
=20
 #include "llvm/PassManagers.h"
 #include "llvm/PassManager.h"
-#include "llvm/DebugInfoProbe.h"
 #include "llvm/Assembly/PrintModulePass.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/Support/CommandLine.h"
@@ -26,7 +25,6 @@
 #include "llvm/Support/PassNameParser.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Mutex.h"
-#include "llvm/ADT/StringMap.h"
 #include <algorithm>
 #include <map>
 using namespace llvm;
@@ -84,32 +82,28 @@
 /// This is a helper to determine whether to print IR before or
 /// after a pass.
=20
-static bool ShouldPrintBeforeOrAfterPass(const void *PassID,
+static bool ShouldPrintBeforeOrAfterPass(const PassInfo *PI,
                                          PassOptionList &PassesToPrint) {
-  if (const llvm::PassInfo *PI =3D
-      PassRegistry::getPassRegistry()->getPassInfo(PassID)) {
-    for (unsigned i =3D 0, ie =3D PassesToPrint.size(); i < ie; ++i) {
-      const llvm::PassInfo *PassInf =3D PassesToPrint[i];
-      if (PassInf)
-        if (PassInf->getPassArgument() =3D=3D PI->getPassArgument()) {
-          return true;
-        }
-    }
+  for (unsigned i =3D 0, ie =3D PassesToPrint.size(); i < ie; ++i) {
+    const llvm::PassInfo *PassInf =3D PassesToPrint[i];
+    if (PassInf)
+      if (PassInf->getPassArgument() =3D=3D PI->getPassArgument()) {
+        return true;
+      }
   }
   return false;
 }
=20
-
 /// This is a utility to check whether a pass should have IR dumped
 /// before it.
-static bool ShouldPrintBeforePass(const void *PassID) {
-  return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PassID, PrintBefor=
e);
+static bool ShouldPrintBeforePass(const PassInfo *PI) {
+  return PrintBeforeAll || ShouldPrintBeforeOrAfterPass(PI, PrintBefore);
 }
=20
 /// This is a utility to check whether a pass should have IR dumped
 /// after it.
-static bool ShouldPrintAfterPass(const void *PassID) {
-  return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PassID, PrintAfter);
+static bool ShouldPrintAfterPass(const PassInfo *PI) {
+  return PrintAfterAll || ShouldPrintBeforeOrAfterPass(PI, PrintAfter);
 }
=20
 } // End of llvm namespace
@@ -223,6 +217,7 @@
 class FunctionPassManagerImpl : public Pass,
                                 public PMDataManager,
                                 public PMTopLevelManager {
+  virtual void anchor();
 private:
   bool wasRun;
 public:
@@ -263,27 +258,15 @@
=20
   virtual PMDataManager *getAsPMDataManager() { return this; }
   virtual Pass *getAsPass() { return this; }
+  virtual PassManagerType getTopLevelPassManagerType() {
+    return PMT_FunctionPassManager;
+  }
=20
   /// Pass Manager itself does not invalidate any analysis info.
   void getAnalysisUsage(AnalysisUsage &Info) const {
     Info.setPreservesAll();
   }
=20
-  void addTopLevelPass(Pass *P) {
-    if (ImmutablePass *IP =3D P->getAsImmutablePass()) {
-      // P is a immutable pass and it will be managed by this
-      // top level manager. Set up analysis resolver to connect them.
-      AnalysisResolver *AR =3D new AnalysisResolver(*this);
-      P->setResolver(AR);
-      initializeAnalysisImpl(P);
-      addImmutablePass(IP);
-      recordAvailableAnalysis(IP);
-    } else {
-      P->assignPassManager(activeStack, PMT_FunctionPassManager);
-    }
-
-  }
-
   FPPassManager *getContainedManager(unsigned N) {
     assert(N < PassManagers.size() && "Pass number out of range!");
     FPPassManager *FP =3D static_cast<FPPassManager *>(PassManagers[N]);
@@ -291,6 +274,8 @@
   }
 };
=20
+void FunctionPassManagerImpl::anchor() {}
+
 char FunctionPassManagerImpl::ID =3D 0;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -384,6 +369,7 @@
 class PassManagerImpl : public Pass,
                         public PMDataManager,
                         public PMTopLevelManager {
+  virtual void anchor();
=20
 public:
   static char ID;
@@ -413,22 +399,11 @@
     Info.setPreservesAll();
   }
=20
-  void addTopLevelPass(Pass *P) {
-    if (ImmutablePass *IP =3D P->getAsImmutablePass()) {
-      // P is a immutable pass and it will be managed by this
-      // top level manager. Set up analysis resolver to connect them.
-      AnalysisResolver *AR =3D new AnalysisResolver(*this);
-      P->setResolver(AR);
-      initializeAnalysisImpl(P);
-      addImmutablePass(IP);
-      recordAvailableAnalysis(IP);
-    } else {
-      P->assignPassManager(activeStack, PMT_ModulePassManager);
-    }
-  }
-
   virtual PMDataManager *getAsPMDataManager() { return this; }
   virtual Pass *getAsPass() { return this; }
+  virtual PassManagerType getTopLevelPassManagerType() {
+    return PMT_ModulePassManager;
+  }
=20
   MPPassManager *getContainedManager(unsigned N) {
     assert(N < PassManagers.size() && "Pass number out of range!");
@@ -437,26 +412,14 @@
   }
 };
=20
+void PassManagerImpl::anchor() {}
+
 char PassManagerImpl::ID =3D 0;
 } // End of llvm namespace
=20
 namespace {
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// DebugInfoProbe
-
-static DebugInfoProbeInfo *TheDebugProbe;
-static void createDebugInfoProbe() {
-  if (TheDebugProbe) return;
-
-  // Constructed the first time this is called. This guarantees that the
-  // object will be constructed, if -enable-debug-info-probe is set,
-  // before static globals, thus it will be destroyed before them.
-  static ManagedStatic<DebugInfoProbeInfo> DIP;
-  TheDebugProbe =3D &*DIP;
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 /// TimingInfo Class - This class is used to calculate information about t=
he
 /// amount of time each pass takes to execute.  This only happens when
 /// -time-passes is enabled on the command line.
@@ -654,7 +617,32 @@
   }
=20
   // Now all required passes are available.
-  addTopLevelPass(P);
+  if (ImmutablePass *IP =3D P->getAsImmutablePass()) {
+    // P is a immutable pass and it will be managed by this
+    // top level manager. Set up analysis resolver to connect them.
+    PMDataManager *DM =3D getAsPMDataManager();
+    AnalysisResolver *AR =3D new AnalysisResolver(*DM);
+    P->setResolver(AR);
+    DM->initializeAnalysisImpl(P);
+    addImmutablePass(IP);
+    DM->recordAvailableAnalysis(IP);
+    return;
+  }
+
+  if (PI && !PI->isAnalysis() && ShouldPrintBeforePass(PI)) {
+    Pass *PP =3D P->createPrinterPass(
+      dbgs(), std::string("*** IR Dump Before ") + P->getPassName() + " **=
*");
+    PP->assignPassManager(activeStack, getTopLevelPassManagerType());
+  }
+
+  // Add the requested pass to the best available pass manager.
+  P->assignPassManager(activeStack, getTopLevelPassManagerType());
+
+  if (PI && !PI->isAnalysis() && ShouldPrintAfterPass(PI)) {
+    Pass *PP =3D P->createPrinterPass(
+      dbgs(), std::string("*** IR Dump After ") + P->getPassName() + " ***=
");
+    PP->assignPassManager(activeStack, getTopLevelPassManagerType());
+  }
 }
=20
 /// Find the pass that implements Analysis AID. Search immutable
@@ -1224,8 +1212,7 @@
 }
=20
 Pass *PMDataManager::getOnTheFlyPass(Pass *P, AnalysisID PI, Function &F) {
-  assert(0 && "Unable to find on the fly pass");
-  return NULL;
+  llvm_unreachable("Unable to find on the fly pass");
 }
=20
 // Destructor
@@ -1351,31 +1338,13 @@
   delete FPM;
 }
=20
-/// addImpl - Add a pass to the queue of passes to run, without
-/// checking whether to add a printer pass.
-void FunctionPassManager::addImpl(Pass *P) {
-  FPM->add(P);
-}
-
 /// add - Add a pass to the queue of passes to run.  This passes
 /// ownership of the Pass to the PassManager.  When the
 /// PassManager_X is destroyed, the pass will be destroyed as well, so
 /// there is no need to delete the pass. (TODO delete passes.)
 /// This implies that all passes MUST be allocated with 'new'.
 void FunctionPassManager::add(Pass *P) {
-  // If this is a not a function pass, don't add a printer for it.
-  const void *PassID =3D P->getPassID();
-  if (P->getPassKind() =3D=3D PT_Function)
-    if (ShouldPrintBeforePass(PassID))
-      addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before=
 ")
-                                   + P->getPassName() + " ***"));
-
-  addImpl(P);
-
-  if (P->getPassKind() =3D=3D PT_Function)
-    if (ShouldPrintAfterPass(PassID))
-      addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After =
")
-                                   + P->getPassName() + " ***"));
+  FPM->add(P);
 }
=20
 /// run - Execute all of the passes scheduled for execution.  Keep
@@ -1455,7 +1424,6 @@
 bool FunctionPassManagerImpl::run(Function &F) {
   bool Changed =3D false;
   TimingInfo::createTheTimeInfo();
-  createDebugInfoProbe();
=20
   initializeAllAnalysisInfo();
   for (unsigned Index =3D 0; Index < getNumContainedManagers(); ++Index)
@@ -1474,7 +1442,7 @@
 char FPPassManager::ID =3D 0;
 /// Print passes managed by this manager
 void FPPassManager::dumpPassStructure(unsigned Offset) {
-  llvm::dbgs() << std::string(Offset*2, ' ') << "FunctionPass Manager\n";
+  dbgs().indent(Offset*2) << "FunctionPass Manager\n";
   for (unsigned Index =3D 0; Index < getNumContainedPasses(); ++Index) {
     FunctionPass *FP =3D getContainedPass(Index);
     FP->dumpPassStructure(Offset + 1);
@@ -1503,16 +1471,13 @@
     dumpRequiredSet(FP);
=20
     initializeAnalysisImpl(FP);
-    if (TheDebugProbe)
-      TheDebugProbe->initialize(FP, F);
+
     {
       PassManagerPrettyStackEntry X(FP, F);
       TimeRegion PassTimer(getPassTimer(FP));
=20
       LocalChanged |=3D FP->runOnFunction(F);
     }
-    if (TheDebugProbe)
-      TheDebugProbe->finalize(FP, F);
=20
     Changed |=3D LocalChanged;
     if (LocalChanged)
@@ -1662,7 +1627,6 @@
 bool PassManagerImpl::run(Module &M) {
   bool Changed =3D false;
   TimingInfo::createTheTimeInfo();
-  createDebugInfoProbe();
=20
   dumpArguments();
   dumpPasses();
@@ -1687,27 +1651,12 @@
   delete PM;
 }
=20
-/// addImpl - Add a pass to the queue of passes to run, without
-/// checking whether to add a printer pass.
-void PassManager::addImpl(Pass *P) {
-  PM->add(P);
-}
-
 /// add - Add a pass to the queue of passes to run.  This passes ownership=
 of
 /// the Pass to the PassManager.  When the PassManager is destroyed, the p=
ass
 /// will be destroyed as well, so there is no need to delete the pass.  Th=
is
 /// implies that all passes MUST be allocated with 'new'.
 void PassManager::add(Pass *P) {
-  const void* PassID =3D P->getPassID();
-  if (ShouldPrintBeforePass(PassID))
-    addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump Before ")
-                                 + P->getPassName() + " ***"));
-
-  addImpl(P);
-
-  if (ShouldPrintAfterPass(PassID))
-    addImpl(P->createPrinterPass(dbgs(), std::string("*** IR Dump After ")
-                                 + P->getPassName() + " ***"));
+  PM->add(P);
 }
=20
 /// run - Execute all of the passes scheduled for execution.  Keep track of
@@ -1817,7 +1766,7 @@
 void FunctionPass::assignPassManager(PMStack &PMS,
                                      PassManagerType PreferredType) {
=20
-  // Find Module Pass Manager
+  // Find Function Pass Manager
   while (!PMS.empty()) {
     if (PMS.top()->getPassManagerType() > PMT_FunctionPassManager)
       PMS.pop();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Type.cpp
--- a/head/contrib/llvm/lib/VMCore/Type.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/Type.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,6 +25,7 @@
 Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
   switch (IDNumber) {
   case VoidTyID      : return getVoidTy(C);
+  case HalfTyID      : return getHalfTy(C);
   case FloatTyID     : return getFloatTy(C);
   case DoubleTyID    : return getDoubleTy(C);
   case X86_FP80TyID  : return getX86_FP80Ty(C);
@@ -57,7 +58,7 @@
 bool Type::isIntOrIntVectorTy() const {
   if (isIntegerTy())
     return true;
-  if (ID !=3D Type::VectorTyID) return false;
+  if (getTypeID() !=3D Type::VectorTyID) return false;
  =20
   return cast<VectorType>(this)->getElementType()->isIntegerTy();
 }
@@ -65,11 +66,12 @@
 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP =
types.
 ///
 bool Type::isFPOrFPVectorTy() const {
-  if (ID =3D=3D Type::FloatTyID || ID =3D=3D Type::DoubleTyID ||=20
-      ID =3D=3D Type::FP128TyID || ID =3D=3D Type::X86_FP80TyID ||=20
-      ID =3D=3D Type::PPC_FP128TyID)
+  if (getTypeID() =3D=3D Type::HalfTyID || getTypeID() =3D=3D Type::FloatT=
yID ||
+      getTypeID() =3D=3D Type::DoubleTyID ||
+      getTypeID() =3D=3D Type::FP128TyID || getTypeID() =3D=3D Type::X86_F=
P80TyID ||=20
+      getTypeID() =3D=3D Type::PPC_FP128TyID)
     return true;
-  if (ID !=3D Type::VectorTyID) return false;
+  if (getTypeID() !=3D Type::VectorTyID) return false;
  =20
   return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
 }
@@ -131,6 +133,7 @@
=20
 unsigned Type::getPrimitiveSizeInBits() const {
   switch (getTypeID()) {
+  case Type::HalfTyID: return 16;
   case Type::FloatTyID: return 32;
   case Type::DoubleTyID: return 64;
   case Type::X86_FP80TyID: return 80;
@@ -157,11 +160,12 @@
   if (const VectorType *VTy =3D dyn_cast<VectorType>(this))
     return VTy->getElementType()->getFPMantissaWidth();
   assert(isFloatingPointTy() && "Not a floating point type!");
-  if (ID =3D=3D FloatTyID) return 24;
-  if (ID =3D=3D DoubleTyID) return 53;
-  if (ID =3D=3D X86_FP80TyID) return 64;
-  if (ID =3D=3D FP128TyID) return 113;
-  assert(ID =3D=3D PPC_FP128TyID && "unknown fp type");
+  if (getTypeID() =3D=3D HalfTyID) return 11;
+  if (getTypeID() =3D=3D FloatTyID) return 24;
+  if (getTypeID() =3D=3D DoubleTyID) return 53;
+  if (getTypeID() =3D=3D X86_FP80TyID) return 64;
+  if (getTypeID() =3D=3D FP128TyID) return 113;
+  assert(getTypeID() =3D=3D PPC_FP128TyID && "unknown fp type");
   return -1;
 }
=20
@@ -181,24 +185,69 @@
   if (!this->isStructTy())=20
     return false;
=20
-  // Opaque structs have no size.
-  if (cast<StructType>(this)->isOpaque())
-    return false;
- =20
-  // Okay, our struct is sized if all of the elements are.
-  for (subtype_iterator I =3D subtype_begin(), E =3D subtype_end(); I !=3D=
 E; ++I)
-    if (!(*I)->isSized())=20
-      return false;
+  return cast<StructType>(this)->isSized();
+}
=20
-  return true;
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//                         Subclass Helper Methods
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+unsigned Type::getIntegerBitWidth() const {
+  return cast<IntegerType>(this)->getBitWidth();
 }
=20
+bool Type::isFunctionVarArg() const {
+  return cast<FunctionType>(this)->isVarArg();
+}
+
+Type *Type::getFunctionParamType(unsigned i) const {
+  return cast<FunctionType>(this)->getParamType(i);
+}
+
+unsigned Type::getFunctionNumParams() const {
+  return cast<FunctionType>(this)->getNumParams();
+}
+
+StringRef Type::getStructName() const {
+  return cast<StructType>(this)->getName();
+}
+
+unsigned Type::getStructNumElements() const {
+  return cast<StructType>(this)->getNumElements();
+}
+
+Type *Type::getStructElementType(unsigned N) const {
+  return cast<StructType>(this)->getElementType(N);
+}
+
+
+
+Type *Type::getSequentialElementType() const {
+  return cast<SequentialType>(this)->getElementType();
+}
+
+uint64_t Type::getArrayNumElements() const {
+  return cast<ArrayType>(this)->getNumElements();
+}
+
+unsigned Type::getVectorNumElements() const {
+  return cast<VectorType>(this)->getNumElements();
+}
+
+unsigned Type::getPointerAddressSpace() const {
+  return cast<PointerType>(this)->getAddressSpace();
+}
+
+
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                          Primitive 'Type' data
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 Type *Type::getVoidTy(LLVMContext &C) { return &C.pImpl->VoidTy; }
 Type *Type::getLabelTy(LLVMContext &C) { return &C.pImpl->LabelTy; }
+Type *Type::getHalfTy(LLVMContext &C) { return &C.pImpl->HalfTy; }
 Type *Type::getFloatTy(LLVMContext &C) { return &C.pImpl->FloatTy; }
 Type *Type::getDoubleTy(LLVMContext &C) { return &C.pImpl->DoubleTy; }
 Type *Type::getMetadataTy(LLVMContext &C) { return &C.pImpl->MetadataTy; }
@@ -217,6 +266,10 @@
   return IntegerType::get(C, N);
 }
=20
+PointerType *Type::getHalfPtrTy(LLVMContext &C, unsigned AS) {
+  return getHalfTy(C)->getPointerTo(AS);
+}
+
 PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
   return getFloatTy(C)->getPointerTo(AS);
 }
@@ -328,23 +381,20 @@
 // FunctionType::get - The factory function for the FunctionType class.
 FunctionType *FunctionType::get(Type *ReturnType,
                                 ArrayRef<Type*> Params, bool isVarArg) {
-  // TODO: This is brutally slow.
-  std::vector<Type*> Key;
-  Key.reserve(Params.size()+2);
-  Key.push_back(const_cast<Type*>(ReturnType));
-  for (unsigned i =3D 0, e =3D Params.size(); i !=3D e; ++i)
-    Key.push_back(const_cast<Type*>(Params[i]));
-  if (isVarArg)
-    Key.push_back(0);
- =20
   LLVMContextImpl *pImpl =3D ReturnType->getContext().pImpl;
-  FunctionType *&FT =3D pImpl->FunctionTypes[Key];
- =20
-  if (FT =3D=3D 0) {
+  FunctionTypeKeyInfo::KeyTy Key(ReturnType, Params, isVarArg);
+  LLVMContextImpl::FunctionTypeMap::iterator I =3D
+    pImpl->FunctionTypes.find_as(Key);
+  FunctionType *FT;
+
+  if (I =3D=3D pImpl->FunctionTypes.end()) {
     FT =3D (FunctionType*) pImpl->TypeAllocator.
-      Allocate(sizeof(FunctionType) + sizeof(Type*)*(Params.size()+1),
+      Allocate(sizeof(FunctionType) + sizeof(Type*) * (Params.size() + 1),
                AlignOf<FunctionType>::Alignment);
     new (FT) FunctionType(ReturnType, Params, isVarArg);
+    pImpl->FunctionTypes[FT] =3D true;
+  } else {
+    FT =3D I->first;
   }
=20
   return FT;
@@ -377,23 +427,22 @@
=20
 StructType *StructType::get(LLVMContext &Context, ArrayRef<Type*> ETypes,=20
                             bool isPacked) {
-  // FIXME: std::vector is horribly inefficient for this probe.
-  std::vector<Type*> Key;
-  for (unsigned i =3D 0, e =3D ETypes.size(); i !=3D e; ++i) {
-    assert(isValidElementType(ETypes[i]) &&
-           "Invalid type for structure element!");
-    Key.push_back(ETypes[i]);
+  LLVMContextImpl *pImpl =3D Context.pImpl;
+  AnonStructTypeKeyInfo::KeyTy Key(ETypes, isPacked);
+  LLVMContextImpl::StructTypeMap::iterator I =3D
+    pImpl->AnonStructTypes.find_as(Key);
+  StructType *ST;
+
+  if (I =3D=3D pImpl->AnonStructTypes.end()) {
+    // Value not found.  Create a new type!
+    ST =3D new (Context.pImpl->TypeAllocator) StructType(Context);
+    ST->setSubclassData(SCDB_IsLiteral);  // Literal struct.
+    ST->setBody(ETypes, isPacked);
+    Context.pImpl->AnonStructTypes[ST] =3D true;
+  } else {
+    ST =3D I->first;
   }
-  if (isPacked)
-    Key.push_back(0);
- =20
-  StructType *&ST =3D Context.pImpl->AnonStructTypes[Key];
-  if (ST) return ST;
- =20
-  // Value not found.  Create a new type!
-  ST =3D new (Context.pImpl->TypeAllocator) StructType(Context);
-  ST->setSubclassData(SCDB_IsLiteral);  // Literal struct.
-  ST->setBody(ETypes, isPacked);
+
   return ST;
 }
=20
@@ -403,13 +452,13 @@
   setSubclassData(getSubclassData() | SCDB_HasBody);
   if (isPacked)
     setSubclassData(getSubclassData() | SCDB_Packed);
- =20
-  Type **Elts =3D getContext().pImpl->
-    TypeAllocator.Allocate<Type*>(Elements.size());
-  memcpy(Elts, Elements.data(), sizeof(Elements[0])*Elements.size());
+
+  unsigned NumElements =3D Elements.size();
+  Type **Elts =3D getContext().pImpl->TypeAllocator.Allocate<Type*>(NumEle=
ments);
+  memcpy(Elts, Elements.data(), sizeof(Elements[0]) * NumElements);
  =20
   ContainedTys =3D Elts;
-  NumContainedTys =3D Elements.size();
+  NumContainedTys =3D NumElements;
 }
=20
 void StructType::setName(StringRef Name) {
@@ -434,9 +483,10 @@
     SmallString<64> TempStr(Name);
     TempStr.push_back('.');
     raw_svector_ostream TmpStream(TempStr);
+    unsigned NameSize =3D Name.size();
   =20
     do {
-      TempStr.resize(Name.size()+1);
+      TempStr.resize(NameSize + 1);
       TmpStream.resync();
       TmpStream << getContext().pImpl->NamedStructTypesUniqueID++;
      =20
@@ -520,6 +570,26 @@
   return llvm::StructType::create(Ctx, StructFields, Name);
 }
=20
+bool StructType::isSized() const {
+  if ((getSubclassData() & SCDB_IsSized) !=3D 0)
+    return true;
+  if (isOpaque())
+    return false;
+
+  // Okay, our struct is sized if all of the elements are, but if one of t=
he
+  // elements is opaque, the struct isn't sized *yet*, but may become size=
d in
+  // the future, so just bail out without caching.
+  for (element_iterator I =3D element_begin(), E =3D element_end(); I !=3D=
 E; ++I)
+    if (!(*I)->isSized())
+      return false;
+
+  // Here we cheat a bit and cast away const-ness. The goal is to memoize =
when
+  // we find a sized type, as types can only move from opaque to sized, no=
t the
+  // other way.
+  const_cast<StructType*>(this)->setSubclassData(
+    getSubclassData() | SCDB_IsSized);
+  return true;
+}
=20
 StringRef StructType::getName() const {
   assert(!isLiteral() && "Literal structs never have names");
@@ -664,6 +734,8 @@
 }
=20
 bool VectorType::isValidElementType(Type *ElemTy) {
+  if (PointerType *PTy =3D dyn_cast<PointerType>(ElemTy))
+    ElemTy =3D PTy->getElementType();
   return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy();
 }
=20
@@ -689,7 +761,12 @@
=20
 PointerType::PointerType(Type *E, unsigned AddrSpace)
   : SequentialType(PointerTyID, E) {
+#ifndef NDEBUG
+  const unsigned oldNCT =3D NumContainedTys;
+#endif
   setSubclassData(AddrSpace);
+  // Check for miscompile. PR11652.
+  assert(oldNCT =3D=3D NumContainedTys && "bitfield written out of bounds?=
");
 }
=20
 PointerType *Type::getPointerTo(unsigned addrs) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Use.cpp
--- a/head/contrib/llvm/lib/VMCore/Use.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/Use.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -12,6 +12,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "llvm/Value.h"
+#include <new>
=20
 namespace llvm {
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/User.cpp
--- a/head/contrib/llvm/lib/VMCore/User.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/User.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -17,6 +17,8 @@
 //                                 User Class
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void User::anchor() {}
+
 // replaceUsesOfWith - Replaces all references to the "From" definition wi=
th
 // references to the "To" definition.
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Value.cpp
--- a/head/contrib/llvm/lib/VMCore/Value.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/lib/VMCore/Value.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -66,7 +66,7 @@
   // a <badref>
   //
   if (!use_empty()) {
-    dbgs() << "While deleting: " << *VTy << " %" << getNameStr() << "\n";
+    dbgs() << "While deleting: " << *VTy << " %" << getName() << "\n";
     for (use_iterator I =3D use_begin(), E =3D use_end(); I !=3D E; ++I)
       dbgs() << "Use still stuck around after Def is destroyed:"
            << **I << "\n";
@@ -76,7 +76,7 @@
=20
   // If this value is named, destroy the name.  This should not be in a sy=
mtab
   // at this point.
-  if (Name)
+  if (Name && SubclassID !=3D MDStringVal)
     Name->Destroy();
=20
   // There should be no uses of this object anymore, remove it.
@@ -108,6 +108,19 @@
 /// isUsedInBasicBlock - Return true if this value is used in the specified
 /// basic block.
 bool Value::isUsedInBasicBlock(const BasicBlock *BB) const {
+  // Start by scanning over the instructions looking for a use before we s=
tart
+  // the expensive use iteration.
+  unsigned MaxBlockSize =3D 3;
+  for (BasicBlock::const_iterator I =3D BB->begin(), E =3D BB->end(); I !=
=3D E; ++I) {
+    if (std::find(I->op_begin(), I->op_end(), this) !=3D I->op_end())
+      return true;
+    if (MaxBlockSize-- =3D=3D 0) // If the block is larger fall back to us=
e_iterator
+      break;
+  }
+
+  if (MaxBlockSize !=3D 0) // We scanned the entire block and found no use.
+    return false;
+
   for (const_use_iterator I =3D use_begin(), E =3D use_end(); I !=3D E; ++=
I) {
     const Instruction *User =3D dyn_cast<Instruction>(*I);
     if (User && User->getParent() =3D=3D BB)
@@ -156,11 +169,10 @@
   return Name->getKey();
 }
=20
-std::string Value::getNameStr() const {
-  return getName().str();
-}
+void Value::setName(const Twine &NewName) {
+  assert(SubclassID !=3D MDStringVal &&
+         "Cannot set the name of MDString with this method!");
=20
-void Value::setName(const Twine &NewName) {
   // Fast path for common IRBuilder case of setName("") when there is no n=
ame.
   if (NewName.isTriviallyEmpty() && !hasName())
     return;
@@ -219,6 +231,8 @@
 /// takeName - transfer the name from V to this value, setting V's name to
 /// empty.  It is an error to call V->takeName(V).
 void Value::takeName(Value *V) {
+  assert(SubclassID !=3D MDStringVal && "Cannot take the name of an MDStri=
ng!");
+
   ValueSymbolTable *ST =3D 0;
   // If this value has a name, drop it.
   if (hasName()) {
@@ -308,20 +322,40 @@
     BB->replaceSuccessorsPhiUsesWith(cast<BasicBlock>(New));
 }
=20
-Value *Value::stripPointerCasts() {
-  if (!getType()->isPointerTy())
-    return this;
+namespace {
+// Various metrics for how much to strip off of pointers.
+enum PointerStripKind {
+  PSK_ZeroIndices,
+  PSK_InBoundsConstantIndices,
+  PSK_InBounds
+};
+
+template <PointerStripKind StripKind>
+static Value *stripPointerCastsAndOffsets(Value *V) {
+  if (!V->getType()->isPointerTy())
+    return V;
=20
   // Even though we don't look through PHI nodes, we could be called on an
   // instruction in an unreachable block, which may be on a cycle.
   SmallPtrSet<Value *, 4> Visited;
=20
-  Value *V =3D this;
   Visited.insert(V);
   do {
     if (GEPOperator *GEP =3D dyn_cast<GEPOperator>(V)) {
-      if (!GEP->hasAllZeroIndices())
-        return V;
+      switch (StripKind) {
+      case PSK_ZeroIndices:
+        if (!GEP->hasAllZeroIndices())
+          return V;
+        break;
+      case PSK_InBoundsConstantIndices:
+        if (!GEP->hasAllConstantIndices())
+          return V;
+        // fallthrough
+      case PSK_InBounds:
+        if (!GEP->isInBounds())
+          return V;
+        break;
+      }
       V =3D GEP->getPointerOperand();
     } else if (Operator::getOpcode(V) =3D=3D Instruction::BitCast) {
       V =3D cast<Operator>(V)->getOperand(0);
@@ -337,10 +371,24 @@
=20
   return V;
 }
+} // namespace
+
+Value *Value::stripPointerCasts() {
+  return stripPointerCastsAndOffsets<PSK_ZeroIndices>(this);
+}
+
+Value *Value::stripInBoundsConstantOffsets() {
+  return stripPointerCastsAndOffsets<PSK_InBoundsConstantIndices>(this);
+}
+
+Value *Value::stripInBoundsOffsets() {
+  return stripPointerCastsAndOffsets<PSK_InBounds>(this);
+}
=20
 /// isDereferenceablePointer - Test if this value is always a pointer to
 /// allocated and suitably aligned memory for a simple load or store.
-bool Value::isDereferenceablePointer() const {
+static bool isDereferenceablePointer(const Value *V,
+                                     SmallPtrSet<const Value *, 32> &Visit=
ed) {
   // Note that it is not safe to speculate into a malloc'd region because
   // malloc may return null.
   // It's also not always safe to follow a bitcast, for example:
@@ -349,20 +397,22 @@
   // be handled using TargetData to check sizes and alignments though.
=20
   // These are obviously ok.
-  if (isa<AllocaInst>(this)) return true;
+  if (isa<AllocaInst>(V)) return true;
=20
   // Global variables which can't collapse to null are ok.
-  if (const GlobalVariable *GV =3D dyn_cast<GlobalVariable>(this))
+  if (const GlobalVariable *GV =3D dyn_cast<GlobalVariable>(V))
     return !GV->hasExternalWeakLinkage();
=20
   // byval arguments are ok.
-  if (const Argument *A =3D dyn_cast<Argument>(this))
+  if (const Argument *A =3D dyn_cast<Argument>(V))
     return A->hasByValAttr();
- =20
+
   // For GEPs, determine if the indexing lands within the allocated object.
-  if (const GEPOperator *GEP =3D dyn_cast<GEPOperator>(this)) {
+  if (const GEPOperator *GEP =3D dyn_cast<GEPOperator>(V)) {
     // Conservatively require that the base pointer be fully dereferenceab=
le.
-    if (!GEP->getOperand(0)->isDereferenceablePointer())
+    if (!Visited.insert(GEP->getOperand(0)))
+      return false;
+    if (!isDereferenceablePointer(GEP->getOperand(0), Visited))
       return false;
     // Check the indices.
     gep_type_iterator GTI =3D gep_type_begin(GEP);
@@ -396,6 +446,13 @@
   return false;
 }
=20
+/// isDereferenceablePointer - Test if this value is always a pointer to
+/// allocated and suitably aligned memory for a simple load or store.
+bool Value::isDereferenceablePointer() const {
+  SmallPtrSet<const Value *, 32> Visited;
+  return ::isDereferenceablePointer(this, Visited);
+}
+
 /// DoPHITranslation - If this value is a PHI node with CurBB as its paren=
t,
 /// return the value in the PHI node corresponding to PredBB.  If not, ret=
urn
 /// ourself.  This is useful if you want to know the value something has i=
n a
@@ -425,7 +482,7 @@
   setPrevPtr(List);
   if (Next) {
     Next->setPrevPtr(&Next);
-    assert(VP =3D=3D Next->VP && "Added to wrong list?");
+    assert(VP.getPointer() =3D=3D Next->VP.getPointer() && "Added to wrong=
 list?");
   }
 }
=20
@@ -441,14 +498,14 @@
=20
 /// AddToUseList - Add this ValueHandle to the use list for VP.
 void ValueHandleBase::AddToUseList() {
-  assert(VP && "Null pointer doesn't have a use list!");
+  assert(VP.getPointer() && "Null pointer doesn't have a use list!");
=20
-  LLVMContextImpl *pImpl =3D VP->getContext().pImpl;
+  LLVMContextImpl *pImpl =3D VP.getPointer()->getContext().pImpl;
=20
-  if (VP->HasValueHandle) {
+  if (VP.getPointer()->HasValueHandle) {
     // If this value already has a ValueHandle, then it must be in the
     // ValueHandles map already.
-    ValueHandleBase *&Entry =3D pImpl->ValueHandles[VP];
+    ValueHandleBase *&Entry =3D pImpl->ValueHandles[VP.getPointer()];
     assert(Entry !=3D 0 && "Value doesn't have any handles?");
     AddToExistingUseList(&Entry);
     return;
@@ -462,10 +519,10 @@
   DenseMap<Value*, ValueHandleBase*> &Handles =3D pImpl->ValueHandles;
   const void *OldBucketPtr =3D Handles.getPointerIntoBucketsArray();
=20
-  ValueHandleBase *&Entry =3D Handles[VP];
+  ValueHandleBase *&Entry =3D Handles[VP.getPointer()];
   assert(Entry =3D=3D 0 && "Value really did already have handles?");
   AddToExistingUseList(&Entry);
-  VP->HasValueHandle =3D true;
+  VP.getPointer()->HasValueHandle =3D true;
=20
   // If reallocation didn't happen or if this was the first insertion, don=
't
   // walk the table.
@@ -477,14 +534,16 @@
   // Okay, reallocation did happen.  Fix the Prev Pointers.
   for (DenseMap<Value*, ValueHandleBase*>::iterator I =3D Handles.begin(),
        E =3D Handles.end(); I !=3D E; ++I) {
-    assert(I->second && I->first =3D=3D I->second->VP && "List invariant b=
roken!");
+    assert(I->second && I->first =3D=3D I->second->VP.getPointer() &&
+           "List invariant broken!");
     I->second->setPrevPtr(&I->second);
   }
 }
=20
 /// RemoveFromUseList - Remove this ValueHandle from its current use list.
 void ValueHandleBase::RemoveFromUseList() {
-  assert(VP && VP->HasValueHandle && "Pointer doesn't have a use list!");
+  assert(VP.getPointer() && VP.getPointer()->HasValueHandle &&
+         "Pointer doesn't have a use list!");
=20
   // Unlink this from its use list.
   ValueHandleBase **PrevPtr =3D getPrevPtr();
@@ -500,11 +559,11 @@
   // If the Next pointer was null, then it is possible that this was the l=
ast
   // ValueHandle watching VP.  If so, delete its entry from the ValueHandl=
es
   // map.
-  LLVMContextImpl *pImpl =3D VP->getContext().pImpl;
+  LLVMContextImpl *pImpl =3D VP.getPointer()->getContext().pImpl;
   DenseMap<Value*, ValueHandleBase*> &Handles =3D pImpl->ValueHandles;
   if (Handles.isPointerIntoBucketsArray(PrevPtr)) {
-    Handles.erase(VP);
-    VP->HasValueHandle =3D false;
+    Handles.erase(VP.getPointer());
+    VP.getPointer()->HasValueHandle =3D false;
   }
 }
=20
@@ -554,7 +613,7 @@
   // All callbacks, weak references, and assertingVHs should be dropped by=
 now.
   if (V->HasValueHandle) {
 #ifndef NDEBUG      // Only in +Asserts mode...
-    dbgs() << "While deleting: " << *V->getType() << " %" << V->getNameStr=
()
+    dbgs() << "While deleting: " << *V->getType() << " %" << V->getName()
            << "\n";
     if (pImpl->ValueHandles[V]->getKind() =3D=3D Assert)
       llvm_unreachable("An asserting value handle still pointed to this"
@@ -617,8 +676,8 @@
       case Tracking:
       case Weak:
         dbgs() << "After RAUW from " << *Old->getType() << " %"
-          << Old->getNameStr() << " to " << *New->getType() << " %"
-          << New->getNameStr() << "\n";
+               << Old->getName() << " to " << *New->getType() << " %"
+               << New->getName() << "\n";
         llvm_unreachable("A tracking or weak value handle still pointed to=
 the"
                          " old value!\n");
       default:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/ValueType=
s.cpp
--- a/head/contrib/llvm/lib/VMCore/ValueTypes.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/lib/VMCore/ValueTypes.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -87,8 +87,7 @@
     return ITy->getBitWidth();
   if (VectorType *VTy =3D dyn_cast<VectorType>(LLVMTy))
     return VTy->getBitWidth();
-  assert(false && "Unrecognized extended type!");
-  return 0; // Suppress warnings.
+  llvm_unreachable("Unrecognized extended type!");
 }
=20
 /// getEVTString - This function returns value type as a string, e.g. "i32=
".
@@ -101,13 +100,13 @@
     if (isInteger())
       return "i" + utostr(getSizeInBits());
     llvm_unreachable("Invalid EVT!");
-    return "?";
   case MVT::i1:      return "i1";
   case MVT::i8:      return "i8";
   case MVT::i16:     return "i16";
   case MVT::i32:     return "i32";
   case MVT::i64:     return "i64";
   case MVT::i128:    return "i128";
+  case MVT::f16:     return "f16";
   case MVT::f32:     return "f32";
   case MVT::f64:     return "f64";
   case MVT::f80:     return "f80";
@@ -134,12 +133,13 @@
   case MVT::v4i64:   return "v4i64";
   case MVT::v8i64:   return "v8i64";
   case MVT::v2f32:   return "v2f32";
+  case MVT::v2f16:   return "v2f16";
   case MVT::v4f32:   return "v4f32";
   case MVT::v8f32:   return "v8f32";
   case MVT::v2f64:   return "v2f64";
   case MVT::v4f64:   return "v4f64";
   case MVT::Metadata:return "Metadata";
-  case MVT::untyped: return "untyped";
+  case MVT::Untyped: return "Untyped";
   }
 }
=20
@@ -158,6 +158,7 @@
   case MVT::i32:     return Type::getInt32Ty(Context);
   case MVT::i64:     return Type::getInt64Ty(Context);
   case MVT::i128:    return IntegerType::get(Context, 128);
+  case MVT::f16:     return Type::getHalfTy(Context);
   case MVT::f32:     return Type::getFloatTy(Context);
   case MVT::f64:     return Type::getDoubleTy(Context);
   case MVT::f80:     return Type::getX86_FP80Ty(Context);
@@ -180,6 +181,7 @@
   case MVT::v2i64:   return VectorType::get(Type::getInt64Ty(Context), 2);
   case MVT::v4i64:   return VectorType::get(Type::getInt64Ty(Context), 4);
   case MVT::v8i64:   return VectorType::get(Type::getInt64Ty(Context), 8);
+  case MVT::v2f16:   return VectorType::get(Type::getHalfTy(Context), 2);
   case MVT::v2f32:   return VectorType::get(Type::getFloatTy(Context), 2);
   case MVT::v4f32:   return VectorType::get(Type::getFloatTy(Context), 4);
   case MVT::v8f32:   return VectorType::get(Type::getFloatTy(Context), 8);
@@ -197,11 +199,11 @@
   default:
     if (HandleUnknown) return MVT(MVT::Other);
     llvm_unreachable("Unknown type!");
-    return MVT::isVoid;
   case Type::VoidTyID:
     return MVT::isVoid;
   case Type::IntegerTyID:
     return getIntegerVT(Ty->getContext(), cast<IntegerType>(Ty)->getBitWid=
th());
+  case Type::HalfTyID:      return MVT(MVT::f16);
   case Type::FloatTyID:     return MVT(MVT::f32);
   case Type::DoubleTyID:    return MVT(MVT::f64);
   case Type::X86_FP80TyID:  return MVT(MVT::f80);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/lib/VMCore/Verifier.=
cpp
--- a/head/contrib/llvm/lib/VMCore/Verifier.cpp	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/lib/VMCore/Verifier.cpp	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-//=3D=3D=3D-- Verifier.cpp - Implement the Module Verifier -------------*-=
 C++ -*-=3D=3D//
+//=3D=3D=3D-- Verifier.cpp - Implement the Module Verifier ---------------=
--------=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -51,6 +51,7 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/InlineAsm.h"
 #include "llvm/IntrinsicInst.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Metadata.h"
 #include "llvm/Module.h"
 #include "llvm/Pass.h"
@@ -117,7 +118,6 @@
   struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
     static char ID; // Pass ID, replacement for typeid
     bool Broken;          // Is this module found to be broken?
-    bool RealPass;        // Are we not being run by a PassManager?
     VerifierFailureAction action;
                           // What to do if verification fails.
     Module *Mod;          // Module we are verifying right now
@@ -143,13 +143,13 @@
     const Value *PersonalityFn;
=20
     Verifier()
-      : FunctionPass(ID), Broken(false), RealPass(true),
+      : FunctionPass(ID), Broken(false),
         action(AbortProcessAction), Mod(0), Context(0), DT(0),
         MessagesStr(Messages), PersonalityFn(0) {
       initializeVerifierPass(*PassRegistry::getPassRegistry());
     }
     explicit Verifier(VerifierFailureAction ctn)
-      : FunctionPass(ID), Broken(false), RealPass(true), action(ctn), Mod(=
0),
+      : FunctionPass(ID), Broken(false), action(ctn), Mod(0),
         Context(0), DT(0), MessagesStr(Messages), PersonalityFn(0) {
       initializeVerifierPass(*PassRegistry::getPassRegistry());
     }
@@ -158,17 +158,14 @@
       Mod =3D &M;
       Context =3D &M.getContext();
=20
-      // If this is a real pass, in a pass manager, we must abort before
-      // returning back to the pass manager, or else the pass manager may =
try to
-      // run other passes on the broken module.
-      if (RealPass)
-        return abortIfBroken();
-      return false;
+      // We must abort before returning back to the pass manager, or else =
the
+      // pass manager may try to run other passes on the broken module.
+      return abortIfBroken();
     }
=20
     bool runOnFunction(Function &F) {
       // Get dominator information if we are being run by PassManager
-      if (RealPass) DT =3D &getAnalysis<DominatorTree>();
+      DT =3D &getAnalysis<DominatorTree>();
=20
       Mod =3D F.getParent();
       if (!Context) Context =3D &F.getContext();
@@ -177,13 +174,9 @@
       InstsInThisBlock.clear();
       PersonalityFn =3D 0;
=20
-      // If this is a real pass, in a pass manager, we must abort before
-      // returning back to the pass manager, or else the pass manager may =
try to
-      // run other passes on the broken module.
-      if (RealPass)
-        return abortIfBroken();
-
-      return false;
+      // We must abort before returning back to the pass manager, or else =
the
+      // pass manager may try to run other passes on the broken module.
+      return abortIfBroken();
     }
=20
     bool doFinalization(Module &M) {
@@ -214,8 +207,7 @@
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.setPreservesAll();
       AU.addRequiredID(PreVerifyID);
-      if (RealPass)
-        AU.addRequired<DominatorTree>();
+      AU.addRequired<DominatorTree>();
     }
=20
     /// abortIfBroken - If the module is broken and we are supposed to abo=
rt on
@@ -225,7 +217,6 @@
       if (!Broken) return false;
       MessagesStr << "Broken module found, ";
       switch (action) {
-      default: llvm_unreachable("Unknown action");
       case AbortProcessAction:
         MessagesStr << "compilation aborted!\n";
         dbgs() << MessagesStr.str();
@@ -239,6 +230,7 @@
         MessagesStr << "compilation terminated.\n";
         return true;
       }
+      llvm_unreachable("Invalid action");
     }
=20
=20
@@ -279,6 +271,7 @@
     void visitGetElementPtrInst(GetElementPtrInst &GEP);
     void visitLoadInst(LoadInst &LI);
     void visitStoreInst(StoreInst &SI);
+    void verifyDominatesUse(Instruction &I, unsigned i);
     void visitInstruction(Instruction &I);
     void visitTerminatorInst(TerminatorInst &I);
     void visitBranchInst(BranchInst &BI);
@@ -547,7 +540,7 @@
   for (unsigned i =3D 0;
        i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
     Attributes MutI =3D Attrs & Attribute::MutuallyIncompatible[i];
-    Assert1(!(MutI & (MutI - 1)), "Attributes " +
+    Assert1(MutI.isEmptyOrSingleton(), "Attributes " +
             Attribute::getAsString(MutI) + " are incompatible!", V);
   }
=20
@@ -607,7 +600,7 @@
   for (unsigned i =3D 0;
        i < array_lengthof(Attribute::MutuallyIncompatible); ++i) {
     Attributes MutI =3D FAttrs & Attribute::MutuallyIncompatible[i];
-    Assert1(!(MutI & (MutI - 1)), "Attributes " +
+    Assert1(MutI.isEmptyOrSingleton(), "Attributes " +
             Attribute::getAsString(MutI) + " are incompatible!", V);
   }
 }
@@ -812,11 +805,11 @@
   // have the same type as the switched-on value.
   Type *SwitchTy =3D SI.getCondition()->getType();
   SmallPtrSet<ConstantInt*, 32> Constants;
-  for (unsigned i =3D 1, e =3D SI.getNumCases(); i !=3D e; ++i) {
-    Assert1(SI.getCaseValue(i)->getType() =3D=3D SwitchTy,
+  for (SwitchInst::CaseIt i =3D SI.case_begin(), e =3D SI.case_end(); i !=
=3D e; ++i) {
+    Assert1(i.getCaseValue()->getType() =3D=3D SwitchTy,
             "Switch constants must all be same type as switch value!", &SI=
);
-    Assert2(Constants.insert(SI.getCaseValue(i)),
-            "Duplicate integer as switch case", &SI, SI.getCaseValue(i));
+    Assert2(Constants.insert(i.getCaseValue()),
+            "Duplicate integer as switch case", &SI, i.getCaseValue());
   }
=20
   visitTerminatorInst(SI);
@@ -1035,8 +1028,19 @@
   Type *SrcTy =3D I.getOperand(0)->getType();
   Type *DestTy =3D I.getType();
=20
-  Assert1(SrcTy->isPointerTy(), "PtrToInt source must be pointer", &I);
-  Assert1(DestTy->isIntegerTy(), "PtrToInt result must be integral", &I);
+  Assert1(SrcTy->getScalarType()->isPointerTy(),
+          "PtrToInt source must be pointer", &I);
+  Assert1(DestTy->getScalarType()->isIntegerTy(),
+          "PtrToInt result must be integral", &I);
+  Assert1(SrcTy->isVectorTy() =3D=3D DestTy->isVectorTy(),
+          "PtrToInt type mismatch", &I);
+
+  if (SrcTy->isVectorTy()) {
+    VectorType *VSrc =3D dyn_cast<VectorType>(SrcTy);
+    VectorType *VDest =3D dyn_cast<VectorType>(DestTy);
+    Assert1(VSrc->getNumElements() =3D=3D VDest->getNumElements(),
+          "PtrToInt Vector width mismatch", &I);
+  }
=20
   visitInstruction(I);
 }
@@ -1046,9 +1050,18 @@
   Type *SrcTy =3D I.getOperand(0)->getType();
   Type *DestTy =3D I.getType();
=20
-  Assert1(SrcTy->isIntegerTy(), "IntToPtr source must be an integral", &I);
-  Assert1(DestTy->isPointerTy(), "IntToPtr result must be a pointer",&I);
-
+  Assert1(SrcTy->getScalarType()->isIntegerTy(),
+          "IntToPtr source must be an integral", &I);
+  Assert1(DestTy->getScalarType()->isPointerTy(),
+          "IntToPtr result must be a pointer",&I);
+  Assert1(SrcTy->isVectorTy() =3D=3D DestTy->isVectorTy(),
+          "IntToPtr type mismatch", &I);
+  if (SrcTy->isVectorTy()) {
+    VectorType *VSrc =3D dyn_cast<VectorType>(SrcTy);
+    VectorType *VDest =3D dyn_cast<VectorType>(DestTy);
+    Assert1(VSrc->getNumElements() =3D=3D VDest->getNumElements(),
+          "IntToPtr Vector width mismatch", &I);
+  }
   visitInstruction(I);
 }
=20
@@ -1245,7 +1258,7 @@
   Assert1(Op0Ty =3D=3D Op1Ty,
           "Both operands to ICmp instruction are not of the same type!", &=
IC);
   // Check that the operands are the right type
-  Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->isPointerTy(),
+  Assert1(Op0Ty->isIntOrIntVectorTy() || Op0Ty->getScalarType()->isPointer=
Ty(),
           "Invalid operand types for ICmp instruction", &IC);
   // Check that the predicate is valid.
   Assert1(IC.getPredicate() >=3D CmpInst::FIRST_ICMP_PREDICATE &&
@@ -1295,17 +1308,41 @@
 }
=20
 void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) {
-  Assert1(cast<PointerType>(GEP.getOperand(0)->getType())
-            ->getElementType()->isSized(),
+  Type *TargetTy =3D GEP.getPointerOperandType()->getScalarType();
+
+  Assert1(isa<PointerType>(TargetTy),
+    "GEP base pointer is not a vector or a vector of pointers", &GEP);
+  Assert1(cast<PointerType>(TargetTy)->getElementType()->isSized(),
           "GEP into unsized type!", &GEP);
- =20
+
   SmallVector<Value*, 16> Idxs(GEP.idx_begin(), GEP.idx_end());
   Type *ElTy =3D
-    GetElementPtrInst::getIndexedType(GEP.getOperand(0)->getType(), Idxs);
+    GetElementPtrInst::getIndexedType(GEP.getPointerOperandType(), Idxs);
   Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP);
-  Assert2(GEP.getType()->isPointerTy() &&
-          cast<PointerType>(GEP.getType())->getElementType() =3D=3D ElTy,
-          "GEP is not of right type for indices!", &GEP, ElTy);
+
+  if (GEP.getPointerOperandType()->isPointerTy()) {
+    // Validate GEPs with scalar indices.
+    Assert2(GEP.getType()->isPointerTy() &&
+           cast<PointerType>(GEP.getType())->getElementType() =3D=3D ElTy,
+           "GEP is not of right type for indices!", &GEP, ElTy);
+  } else {
+    // Validate GEPs with a vector index.
+    Assert1(Idxs.size() =3D=3D 1, "Invalid number of indices!", &GEP);
+    Value *Index =3D Idxs[0];
+    Type  *IndexTy =3D Index->getType();
+    Assert1(IndexTy->isVectorTy(),
+      "Vector GEP must have vector indices!", &GEP);
+    Assert1(GEP.getType()->isVectorTy(),
+      "Vector GEP must return a vector value", &GEP);
+    Type *ElemPtr =3D cast<VectorType>(GEP.getType())->getElementType();
+    Assert1(ElemPtr->isPointerTy(),
+      "Vector GEP pointer operand is not a pointer!", &GEP);
+    unsigned IndexWidth =3D cast<VectorType>(IndexTy)->getNumElements();
+    unsigned GepWidth =3D cast<VectorType>(GEP.getType())->getNumElements(=
);
+    Assert1(IndexWidth =3D=3D GepWidth, "Invalid GEP index vector width", =
&GEP);
+    Assert1(ElTy =3D=3D cast<PointerType>(ElemPtr)->getElementType(),
+      "Vector GEP type does not match pointer type!", &GEP);
+  }
   visitInstruction(GEP);
 }
=20
@@ -1324,6 +1361,25 @@
     Assert1(LI.getSynchScope() =3D=3D CrossThread,
             "Non-atomic load cannot have SynchronizationScope specified", =
&LI);
   }
+
+  if (MDNode *Range =3D LI.getMetadata(LLVMContext::MD_range)) {
+    unsigned NumOperands =3D Range->getNumOperands();
+    Assert1(NumOperands % 2 =3D=3D 0, "Unfinished range!", Range);
+    unsigned NumRanges =3D NumOperands / 2;
+    Assert1(NumRanges >=3D 1, "It should have at least one range!", Range);
+    for (unsigned i =3D 0; i < NumRanges; ++i) {
+      ConstantInt *Low =3D dyn_cast<ConstantInt>(Range->getOperand(2*i));
+      Assert1(Low, "The lower limit must be an integer!", Low);
+      ConstantInt *High =3D dyn_cast<ConstantInt>(Range->getOperand(2*i + =
1));
+      Assert1(High, "The upper limit must be an integer!", High);
+      Assert1(High->getType() =3D=3D Low->getType() &&
+              High->getType() =3D=3D ElTy, "Range types must match load ty=
pe!",
+              &LI);
+      Assert1(High->getValue() !=3D Low->getValue(), "Range must not be em=
pty!",
+              Range);
+    }
+  }
+
   visitInstruction(LI);
 }
=20
@@ -1468,6 +1524,58 @@
   visitInstruction(LPI);
 }
=20
+void Verifier::verifyDominatesUse(Instruction &I, unsigned i) {
+  Instruction *Op =3D cast<Instruction>(I.getOperand(i));
+  BasicBlock *BB =3D I.getParent();
+  BasicBlock *OpBlock =3D Op->getParent();
+  PHINode *PN =3D dyn_cast<PHINode>(&I);
+
+  // DT can handle non phi instructions for us.
+  if (!PN) {
+    // Definition must dominate use unless use is unreachable!
+    Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(BB) ||
+            DT->dominates(Op, &I),
+            "Instruction does not dominate all uses!", Op, &I);
+    return;
+  }
+
+  // Check that a definition dominates all of its uses.
+  if (InvokeInst *II =3D dyn_cast<InvokeInst>(Op)) {
+    // Invoke results are only usable in the normal destination, not in the
+    // exceptional destination.
+    BasicBlock *NormalDest =3D II->getNormalDest();
+
+
+    // PHI nodes differ from other nodes because they actually "use" the
+    // value in the predecessor basic blocks they correspond to.
+    BasicBlock *UseBlock =3D BB;
+    unsigned j =3D PHINode::getIncomingValueNumForOperand(i);
+    UseBlock =3D PN->getIncomingBlock(j);
+    Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB",
+            Op, &I);
+
+    if (UseBlock =3D=3D OpBlock) {
+      // Special case of a phi node in the normal destination or the unwind
+      // destination.
+      Assert2(BB =3D=3D NormalDest || !DT->isReachableFromEntry(UseBlock),
+              "Invoke result not available in the unwind destination!",
+              Op, &I);
+    } else {
+      Assert2(DT->dominates(II, UseBlock) ||
+              !DT->isReachableFromEntry(UseBlock),
+              "Invoke result does not dominate all uses!", Op, &I);
+    }
+  }
+
+  // PHI nodes are more difficult than other nodes because they actually
+  // "use" the value in the predecessor basic blocks they correspond to.
+  unsigned j =3D PHINode::getIncomingValueNumForOperand(i);
+  BasicBlock *PredBB =3D PN->getIncomingBlock(j);
+  Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
+                     !DT->isReachableFromEntry(PredBB)),
+          "Instruction does not dominate all uses!", Op, &I);
+}
+
 /// verifyInstruction - Verify that an instruction is well formed.
 ///
 void Verifier::visitInstruction(Instruction &I) {
@@ -1536,84 +1644,30 @@
     } else if (GlobalValue *GV =3D dyn_cast<GlobalValue>(I.getOperand(i)))=
 {
       Assert1(GV->getParent() =3D=3D Mod, "Referencing global in another m=
odule!",
               &I);
-    } else if (Instruction *Op =3D dyn_cast<Instruction>(I.getOperand(i)))=
 {
-      BasicBlock *OpBlock =3D Op->getParent();
-
-      // Check that a definition dominates all of its uses.
-      if (InvokeInst *II =3D dyn_cast<InvokeInst>(Op)) {
-        // Invoke results are only usable in the normal destination, not i=
n the
-        // exceptional destination.
-        BasicBlock *NormalDest =3D II->getNormalDest();
-
-        Assert2(NormalDest !=3D II->getUnwindDest(),
-                "No uses of invoke possible due to dominance structure!",
-                Op, &I);
-
-        // PHI nodes differ from other nodes because they actually "use" t=
he
-        // value in the predecessor basic blocks they correspond to.
-        BasicBlock *UseBlock =3D BB;
-        if (PHINode *PN =3D dyn_cast<PHINode>(&I)) {
-          unsigned j =3D PHINode::getIncomingValueNumForOperand(i);
-          UseBlock =3D PN->getIncomingBlock(j);
-        }
-        Assert2(UseBlock, "Invoke operand is PHI node with bad incoming-BB=
",
-                Op, &I);
-
-        if (isa<PHINode>(I) && UseBlock =3D=3D OpBlock) {
-          // Special case of a phi node in the normal destination or the u=
nwind
-          // destination.
-          Assert2(BB =3D=3D NormalDest || !DT->isReachableFromEntry(UseBlo=
ck),
-                  "Invoke result not available in the unwind destination!",
-                  Op, &I);
-        } else {
-          Assert2(DT->dominates(NormalDest, UseBlock) ||
-                  !DT->isReachableFromEntry(UseBlock),
-                  "Invoke result does not dominate all uses!", Op, &I);
-
-          // If the normal successor of an invoke instruction has multiple
-          // predecessors, then the normal edge from the invoke is critica=
l,
-          // so the invoke value can only be live if the destination block
-          // dominates all of it's predecessors (other than the invoke).
-          if (!NormalDest->getSinglePredecessor() &&
-              DT->isReachableFromEntry(UseBlock))
-            // If it is used by something non-phi, then the other case is =
that
-            // 'NormalDest' dominates all of its predecessors other than t=
he
-            // invoke.  In this case, the invoke value can still be used.
-            for (pred_iterator PI =3D pred_begin(NormalDest),
-                 E =3D pred_end(NormalDest); PI !=3D E; ++PI)
-              if (*PI !=3D II->getParent() && !DT->dominates(NormalDest, *=
PI) &&
-                  DT->isReachableFromEntry(*PI)) {
-                CheckFailed("Invoke result does not dominate all uses!", O=
p,&I);
-                return;
-              }
-        }
-      } else if (PHINode *PN =3D dyn_cast<PHINode>(&I)) {
-        // PHI nodes are more difficult than other nodes because they actu=
ally
-        // "use" the value in the predecessor basic blocks they correspond=
 to.
-        unsigned j =3D PHINode::getIncomingValueNumForOperand(i);
-        BasicBlock *PredBB =3D PN->getIncomingBlock(j);
-        Assert2(PredBB && (DT->dominates(OpBlock, PredBB) ||
-                           !DT->isReachableFromEntry(PredBB)),
-                "Instruction does not dominate all uses!", Op, &I);
-      } else {
-        if (OpBlock =3D=3D BB) {
-          // If they are in the same basic block, make sure that the defin=
ition
-          // comes before the use.
-          Assert2(InstsInThisBlock.count(Op) || !DT->isReachableFromEntry(=
BB),
-                  "Instruction does not dominate all uses!", Op, &I);
-        }
-
-        // Definition must dominate use unless use is unreachable!
-        Assert2(InstsInThisBlock.count(Op) || DT->dominates(Op, &I) ||
-                !DT->isReachableFromEntry(BB),
-                "Instruction does not dominate all uses!", Op, &I);
-      }
+    } else if (isa<Instruction>(I.getOperand(i))) {
+      verifyDominatesUse(I, i);
     } else if (isa<InlineAsm>(I.getOperand(i))) {
       Assert1((i + 1 =3D=3D e && isa<CallInst>(I)) ||
               (i + 3 =3D=3D e && isa<InvokeInst>(I)),
               "Cannot take the address of an inline asm!", &I);
     }
   }
+
+  if (MDNode *MD =3D I.getMetadata(LLVMContext::MD_fpaccuracy)) {
+    Assert1(I.getType()->isFPOrFPVectorTy(),
+            "fpaccuracy requires a floating point result!", &I);
+    Assert1(MD->getNumOperands() =3D=3D 1, "fpaccuracy takes one operand!"=
, &I);
+    ConstantFP *Op =3D dyn_cast_or_null<ConstantFP>(MD->getOperand(0));
+    Assert1(Op, "fpaccuracy ULPs not a floating point number!", &I);
+    APFloat ULPs =3D Op->getValueAPF();
+    Assert1(ULPs.isNormal() || ULPs.isZero(),
+            "fpaccuracy ULPs not a normal number!", &I);
+    Assert1(!ULPs.isNegative(), "fpaccuracy ULPs is negative!", &I);
+  }
+
+  MDNode *MD =3D I.getMetadata(LLVMContext::MD_range);
+  Assert1(!MD || isa<LoadInst>(I), "Ranges are only for loads!", &I);
+
   InstsInThisBlock.insert(&I);
 }
=20
@@ -1642,6 +1696,12 @@
   switch (ID) {
   default:
     break;
+  case Intrinsic::ctlz:  // llvm.ctlz
+  case Intrinsic::cttz:  // llvm.cttz
+    Assert1(isa<ConstantInt>(CI.getArgOperand(1)),
+            "is_zero_undef argument of bit counting intrinsics must be a "
+            "constant int", &CI);
+    break;
   case Intrinsic::dbg_declare: {  // llvm.dbg.declare
     Assert1(CI.getArgOperand(0) && isa<MDNode>(CI.getArgOperand(0)),
                 "invalid llvm.dbg.declare intrinsic call 1", &CI);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/BugDr=
iver.cpp
--- a/head/contrib/llvm/tools/bugpoint/BugDriver.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/tools/bugpoint/BugDriver.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -87,7 +87,7 @@
   SMDiagnostic Err;
   Module *Result =3D ParseIRFile(Filename, Err, Ctxt);
   if (!Result)
-    Err.Print("bugpoint", errs());
+    Err.print("bugpoint", errs());
=20
   // If we don't have an override triple, use the first one to configure
   // bugpoint, or use the host triple if none provided.
@@ -96,7 +96,7 @@
       Triple TheTriple(Result->getTargetTriple());
=20
       if (TheTriple.getTriple().empty())
-        TheTriple.setTriple(sys::getHostTriple());
+        TheTriple.setTriple(sys::getDefaultTargetTriple());
=20
       TargetTriple.setTriple(TheTriple.getTriple());
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/Crash=
Debugger.cpp
--- a/head/contrib/llvm/tools/bugpoint/CrashDebugger.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/bugpoint/CrashDebugger.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -169,7 +169,7 @@
   return false;
 }
=20
-namespace llvm {
+namespace {
   /// ReduceCrashingFunctions reducer - This works by removing functions a=
nd
   /// seeing if the program still crashes. If it does, then keep the newer,
   /// smaller program.
@@ -401,7 +401,8 @@
     for (Function::iterator FI =3D MI->begin(), FE =3D MI->end(); FI !=3D =
FE; ++FI)
       for (BasicBlock::iterator I =3D FI->begin(), E =3D FI->end(); I !=3D=
 E;) {
         Instruction *Inst =3D I++;
-        if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst)) {
+        if (!Instructions.count(Inst) && !isa<TerminatorInst>(Inst) &&
+            !isa<LandingPadInst>(Inst)) {
           if (!Inst->getType()->isVoidTy())
             Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
           Inst->eraseFromParent();
@@ -568,12 +569,15 @@
         for (Function::const_iterator BI =3D FI->begin(), E =3D FI->end();=
 BI !=3D E;
              ++BI)
           for (BasicBlock::const_iterator I =3D BI->begin(), E =3D --BI->e=
nd();
-               I !=3D E; ++I, ++CurInstructionNum)
+               I !=3D E; ++I, ++CurInstructionNum) {
             if (InstructionsToSkipBeforeDeleting) {
               --InstructionsToSkipBeforeDeleting;
             } else {
               if (BugpointIsInterrupted) goto ExitLoops;
=20
+              if (isa<LandingPadInst>(I))
+                continue;
+
               outs() << "Checking instruction: " << *I;
               Module *M =3D BD.deleteInstructionFromProgram(I, Simplificat=
ion);
=20
@@ -590,6 +594,7 @@
               // one.
               delete M;
             }
+          }
=20
     if (InstructionsToSkipBeforeDeleting) {
       InstructionsToSkipBeforeDeleting =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/Execu=
tionDriver.cpp
--- a/head/contrib/llvm/tools/bugpoint/ExecutionDriver.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/bugpoint/ExecutionDriver.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -28,8 +28,7 @@
   // for miscompilation.
   //
   enum OutputType {
-    AutoPick, RunLLI, RunJIT, RunLLC, RunLLCIA, RunCBE, CBE_bug, LLC_Safe,
-    CompileCustom, Custom
+    AutoPick, RunLLI, RunJIT, RunLLC, RunLLCIA, LLC_Safe, CompileCustom, C=
ustom
   };
=20
   cl::opt<double>
@@ -48,8 +47,6 @@
                             clEnumValN(RunLLC, "run-llc", "Compile with LL=
C"),
                             clEnumValN(RunLLCIA, "run-llc-ia",
                                   "Compile with LLC with integrated assemb=
ler"),
-                            clEnumValN(RunCBE, "run-cbe", "Compile with CB=
E"),
-                            clEnumValN(CBE_bug,"cbe-bug", "Find CBE bugs"),
                             clEnumValN(LLC_Safe, "llc-safe", "Use LLC for =
all"),
                             clEnumValN(CompileCustom, "compile-custom",
                             "Use -compile-command to define a command to "
@@ -64,7 +61,6 @@
   SafeInterpreterSel(cl::desc("Specify \"safe\" i.e. known-good backend:"),
               cl::values(clEnumValN(AutoPick, "safe-auto", "Use best guess=
"),
                          clEnumValN(RunLLC, "safe-run-llc", "Compile with =
LLC"),
-                         clEnumValN(RunCBE, "safe-run-cbe", "Compile with =
CBE"),
                          clEnumValN(Custom, "safe-run-custom",
                          "Use -exec-command to define a command to execute=
 "
                          "the bitcode. Useful for cross-compilation."),
@@ -154,10 +150,6 @@
=20
   switch (InterpreterSel) {
   case AutoPick:
-    InterpreterSel =3D RunCBE;
-    Interpreter =3D
-      AbstractInterpreter::createCBE(getToolName(), Message, GCCBinary,
-                                     &ToolArgv, &GCCToolArgv);
     if (!Interpreter) {
       InterpreterSel =3D RunJIT;
       Interpreter =3D AbstractInterpreter::createJIT(getToolName(), Messag=
e,
@@ -195,12 +187,6 @@
     Interpreter =3D AbstractInterpreter::createJIT(getToolName(), Message,
                                                  &ToolArgv);
     break;
-  case RunCBE:
-  case CBE_bug:
-    Interpreter =3D AbstractInterpreter::createCBE(getToolName(), Message,
-                                                 GCCBinary, &ToolArgv,
-                                                 &GCCToolArgv);
-    break;
   case CompileCustom:
     Interpreter =3D
       AbstractInterpreter::createCustomCompiler(Message, CustomCompileComm=
and);
@@ -209,9 +195,6 @@
     Interpreter =3D
       AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand=
);
     break;
-  default:
-    Message =3D "Sorry, this back-end is not supported by bugpoint right n=
ow!\n";
-    break;
   }
   if (!Interpreter)
     errs() << Message;
@@ -224,17 +207,6 @@
   std::vector<std::string> SafeToolArgs =3D SafeToolArgv;
   switch (SafeInterpreterSel) {
   case AutoPick:
-    // In "cbe-bug" mode, default to using LLC as the "safe" backend.
-    if (!SafeInterpreter &&
-        InterpreterSel =3D=3D CBE_bug) {
-      SafeInterpreterSel =3D RunLLC;
-      SafeToolArgs.push_back("--relocation-model=3Dpic");
-      SafeInterpreter =3D AbstractInterpreter::createLLC(Path.c_str(), Mes=
sage,
-                                                       GCCBinary,
-                                                       &SafeToolArgs,
-                                                       &GCCToolArgv);
-    }
-
     // In "llc-safe" mode, default to using LLC as the "safe" backend.
     if (!SafeInterpreter &&
         InterpreterSel =3D=3D LLC_Safe) {
@@ -246,17 +218,6 @@
                                                        &GCCToolArgv);
     }
=20
-    // Pick a backend that's different from the test backend. The JIT and
-    // LLC backends share a lot of code, so prefer to use the CBE as the
-    // safe back-end when testing them.
-    if (!SafeInterpreter &&
-        InterpreterSel !=3D RunCBE) {
-      SafeInterpreterSel =3D RunCBE;
-      SafeInterpreter =3D AbstractInterpreter::createCBE(Path.c_str(), Mes=
sage,
-                                                       GCCBinary,
-                                                       &SafeToolArgs,
-                                                       &GCCToolArgv);
-    }
     if (!SafeInterpreter &&
         InterpreterSel !=3D RunLLC &&
         InterpreterSel !=3D RunJIT) {
@@ -280,11 +241,6 @@
                                                      &GCCToolArgv,
                                                 SafeInterpreterSel =3D=3D =
RunLLCIA);
     break;
-  case RunCBE:
-    SafeInterpreter =3D AbstractInterpreter::createCBE(Path.c_str(), Messa=
ge,
-                                                     GCCBinary, &SafeToolA=
rgs,
-                                                     &GCCToolArgv);
-    break;
   case Custom:
     SafeInterpreter =3D
       AbstractInterpreter::createCustomExecutor(Message, CustomExecCommand=
);
@@ -462,8 +418,8 @@
     errs() << Error;
     if (Interpreter !=3D SafeInterpreter) {
       errs() << "*** There is a bug running the \"safe\" backend.  Either"
-             << " debug it (for example with the -run-cbe bugpoint option,"
-             << " if CBE is being used as the \"safe\" backend), or fix th=
e"
+             << " debug it (for example with the -run-jit bugpoint option,"
+             << " if JIT is being used as the \"safe\" backend), or fix th=
e"
              << " error some other way.\n";
     }
     return false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/Extra=
ctFunction.cpp
--- a/head/contrib/llvm/tools/bugpoint/ExtractFunction.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/bugpoint/ExtractFunction.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -47,7 +47,39 @@
   cl::opt<bool, true>
   NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
          cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
-}
+
+  Function* globalInitUsesExternalBA(GlobalVariable* GV) {
+    if (!GV->hasInitializer())
+      return 0;
+
+    Constant *I =3D GV->getInitializer();
+
+    // walk the values used by the initializer
+    // (and recurse into things like ConstantExpr)
+    std::vector<Constant*> Todo;
+    std::set<Constant*> Done;
+    Todo.push_back(I);
+
+    while (!Todo.empty()) {
+      Constant* V =3D Todo.back();
+      Todo.pop_back();
+      Done.insert(V);
+
+      if (BlockAddress *BA =3D dyn_cast<BlockAddress>(V)) {
+        Function *F =3D BA->getFunction();
+        if (F->isDeclaration())
+          return F;
+      }
+
+      for (User::op_iterator i =3D V->op_begin(), e =3D V->op_end(); i !=
=3D e; ++i) {
+        Constant *C =3D dyn_cast<Constant>(*i);
+        if (C && !isa<GlobalValue>(C) && !Done.count(C))
+          Todo.push_back(C);
+      }
+    }
+    return 0;
+  }
+}  // end anonymous namespace
=20
 /// deleteInstructionFromProgram - This method clones the current Program =
and
 /// deletes the specified instruction from the cloned module.  It then run=
s a
@@ -272,11 +304,6 @@
   ValueToValueMapTy NewVMap;
   Module *New =3D CloneModule(M, NewVMap);
=20
-  // Make sure global initializers exist only in the safe module (CBE->.so)
-  for (Module::global_iterator I =3D New->global_begin(), E =3D New->globa=
l_end();
-       I !=3D E; ++I)
-    I->setInitializer(0);  // Delete the initializer to make it external
-
   // Remove the Test functions from the Safe module
   std::set<Function *> TestFunctions;
   for (unsigned i =3D 0, e =3D F.size(); i !=3D e; ++i) {
@@ -295,6 +322,27 @@
       DeleteFunctionBody(I);
  =20
=20
+  // Try to split the global initializers evenly
+  for (Module::global_iterator I =3D M->global_begin(), E =3D M->global_en=
d();
+       I !=3D E; ++I) {
+    GlobalVariable *GV =3D cast<GlobalVariable>(NewVMap[I]);
+    if (Function *TestFn =3D globalInitUsesExternalBA(I)) {
+      if (Function *SafeFn =3D globalInitUsesExternalBA(GV)) {
+        errs() << "*** Error: when reducing functions, encountered "
+                  "the global '";
+        WriteAsOperand(errs(), GV, false);
+        errs() << "' with an initializer that references blockaddresses "
+                  "from safe function '" << SafeFn->getName()
+               << "' and from test function '" << TestFn->getName() << "'.=
\n";
+        exit(1);
+      }
+      I->setInitializer(0);  // Delete the initializer to make it external
+    } else {
+      // If we keep it in the safe module, then delete it in the test modu=
le
+      GV->setInitializer(0);
+    }
+  }
+
   // Make sure that there is a global ctor/dtor array in both halves of the
   // module if they both have static ctor/dtor functions.
   SplitStaticCtorDtor("llvm.global_ctors", M, New, NewVMap);
@@ -340,7 +388,7 @@
     // If the BB doesn't have a name, give it one so we have something to =
key
     // off of.
     if (!BB->hasName()) BB->setName("tmpbb");
-    BlocksToNotExtractFile.os() << BB->getParent()->getNameStr() << " "
+    BlocksToNotExtractFile.os() << BB->getParent()->getName() << " "
                                 << BB->getName() << "\n";
   }
   BlocksToNotExtractFile.os().close();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/Misco=
mpilation.cpp
--- a/head/contrib/llvm/tools/bugpoint/Miscompilation.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/bugpoint/Miscompilation.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -820,7 +820,8 @@
       // Don't forward functions which are external in the test module too.
       if (TestFn && !TestFn->isDeclaration()) {
         // 1. Add a string constant with its name to the global file
-        Constant *InitArray =3D ConstantArray::get(F->getContext(), F->get=
Name());
+        Constant *InitArray =3D
+          ConstantDataArray::getString(F->getContext(), F->getName());
         GlobalVariable *funcName =3D
           new GlobalVariable(*Safe, InitArray->getType(), true /*isConstan=
t*/,
                              GlobalValue::InternalLinkage, InitArray,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/Optim=
izerDriver.cpp
--- a/head/contrib/llvm/tools/bugpoint/OptimizerDriver.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/bugpoint/OptimizerDriver.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -85,8 +85,11 @@
   if (NoFlyer || PassesToRun.empty()) return;
   outs() << "\n*** You can reproduce the problem with: ";
   if (UseValgrind) outs() << "valgrind ";
-  outs() << "opt " << Filename << " ";
-  outs() << getPassesString(PassesToRun) << "\n";
+  outs() << "opt " << Filename;
+  for (unsigned i =3D 0, e =3D PluginLoader::getNumPlugins(); i !=3D e; ++=
i) {
+    outs() << " -load " << PluginLoader::getPlugin(i);
+  }
+  outs() << " " << getPassesString(PassesToRun) << "\n";
 }
=20
 cl::opt<bool> SilencePasses("silence-passes",
@@ -145,10 +148,9 @@
     return 1;
   }
=20
-  sys::Path tool =3D PrependMainExecutablePath("opt", getToolName(),
-                                             (void*)"opt");
+  sys::Path tool =3D sys::Program::FindProgramByName("opt");
   if (tool.empty()) {
-    errs() << "Cannot find `opt' in executable directory!\n";
+    errs() << "Cannot find `opt' in PATH!\n";
     return 1;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/ToolR=
unner.cpp
--- a/head/contrib/llvm/tools/bugpoint/ToolRunner.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/tools/bugpoint/ToolRunner.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -234,6 +234,8 @@
       Timeout, MemoryLimit, Error);
 }
=20
+void AbstractInterpreter::anchor() { }
+
 // LLI create method - Try to find the LLI executable
 AbstractInterpreter *AbstractInterpreter::createLLI(const char *Argv0,
                                                     std::string &Message,
@@ -621,94 +623,6 @@
   return 0;
 }
=20
-GCC::FileType CBE::OutputCode(const std::string &Bitcode,
-                              sys::Path &OutputCFile, std::string &Error,
-                              unsigned Timeout, unsigned MemoryLimit) {
-  sys::Path uniqueFile(Bitcode+".cbe.c");
-  std::string ErrMsg;
-  if (uniqueFile.makeUnique(true, &ErrMsg)) {
-    errs() << "Error making unique filename: " << ErrMsg << "\n";
-    exit(1);
-  }
-  OutputCFile =3D uniqueFile;
-  std::vector<const char *> LLCArgs;
-  LLCArgs.push_back(LLCPath.c_str());
-
-  // Add any extra LLC args.
-  for (unsigned i =3D 0, e =3D ToolArgs.size(); i !=3D e; ++i)
-    LLCArgs.push_back(ToolArgs[i].c_str());
-
-  LLCArgs.push_back("-o");
-  LLCArgs.push_back(OutputCFile.c_str());   // Output to the C file
-  LLCArgs.push_back("-march=3Dc");            // Output C language
-  LLCArgs.push_back(Bitcode.c_str());      // This is the input bitcode
-  LLCArgs.push_back(0);
-
-  outs() << "<cbe>"; outs().flush();
-  DEBUG(errs() << "\nAbout to run:\t";
-        for (unsigned i =3D 0, e =3D LLCArgs.size()-1; i !=3D e; ++i)
-          errs() << " " << LLCArgs[i];
-        errs() << "\n";
-        );
-  if (RunProgramWithTimeout(LLCPath, &LLCArgs[0], sys::Path(), sys::Path(),
-                            sys::Path(), Timeout, MemoryLimit))
-    Error =3D ProcessFailure(LLCPath, &LLCArgs[0], Timeout, MemoryLimit);
-  return GCC::CFile;
-}
-
-void CBE::compileProgram(const std::string &Bitcode, std::string *Error,
-                         unsigned Timeout, unsigned MemoryLimit) {
-  sys::Path OutputCFile;
-  OutputCode(Bitcode, OutputCFile, *Error, Timeout, MemoryLimit);
-  OutputCFile.eraseFromDisk();
-}
-
-int CBE::ExecuteProgram(const std::string &Bitcode,
-                        const std::vector<std::string> &Args,
-                        const std::string &InputFile,
-                        const std::string &OutputFile,
-                        std::string *Error,
-                        const std::vector<std::string> &ArgsForGCC,
-                        const std::vector<std::string> &SharedLibs,
-                        unsigned Timeout,
-                        unsigned MemoryLimit) {
-  sys::Path OutputCFile;
-  OutputCode(Bitcode, OutputCFile, *Error, Timeout, MemoryLimit);
-
-  FileRemover CFileRemove(OutputCFile.str(), !SaveTemps);
-
-  std::vector<std::string> GCCArgs(ArgsForGCC);
-  GCCArgs.insert(GCCArgs.end(), SharedLibs.begin(), SharedLibs.end());
-
-  return gcc->ExecuteProgram(OutputCFile.str(), Args, GCC::CFile,
-                             InputFile, OutputFile, Error, GCCArgs,
-                             Timeout, MemoryLimit);
-}
-
-/// createCBE - Try to find the 'llc' executable
-///
-CBE *AbstractInterpreter::createCBE(const char *Argv0,
-                                    std::string &Message,
-                                    const std::string &GCCBinary,
-                                    const std::vector<std::string> *Args,
-                                    const std::vector<std::string> *GCCArg=
s) {
-  sys::Path LLCPath =3D
-    PrependMainExecutablePath("llc", Argv0, (void *)(intptr_t)&createCBE);
-  if (LLCPath.isEmpty()) {
-    Message =3D
-      "Cannot find `llc' in executable directory!\n";
-    return 0;
-  }
-
-  Message =3D "Found llc: " + LLCPath.str() + "\n";
-  GCC *gcc =3D GCC::create(Message, GCCBinary, GCCArgs);
-  if (!gcc) {
-    errs() << Message << "\n";
-    exit(1);
-  }
-  return new CBE(LLCPath, gcc, Args);
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
------=3D=3D=3D//
 // GCC abstraction
 //
@@ -920,8 +834,7 @@
   } else
     GCCArgs.push_back("-shared");  // `-shared' for Linux/X86, maybe others
=20
-  if ((TargetTriple.getArch() =3D=3D Triple::alpha) ||
-      (TargetTriple.getArch() =3D=3D Triple::x86_64))
+  if (TargetTriple.getArch() =3D=3D Triple::x86_64)
     GCCArgs.push_back("-fPIC");   // Requires shared objs to contain PIC
=20
   if (TargetTriple.getArch() =3D=3D Triple::sparc)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/ToolR=
unner.h
--- a/head/contrib/llvm/tools/bugpoint/ToolRunner.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/tools/bugpoint/ToolRunner.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -86,6 +86,7 @@
 /// complexity behind a simple interface.
 ///
 class AbstractInterpreter {
+  virtual void anchor();
 public:
   static CBE *createCBE(const char *Argv0, std::string &Message,
                         const std::string              &GCCBinary,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/bugpoint/bugpo=
int.cpp
--- a/head/contrib/llvm/tools/bugpoint/bugpoint.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/tools/bugpoint/bugpoint.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -120,6 +120,7 @@
   PassRegistry &Registry =3D *PassRegistry::getPassRegistry();
   initializeCore(Registry);
   initializeScalarOpts(Registry);
+  initializeVectorization(Registry);
   initializeIPO(Registry);
   initializeAnalysis(Registry);
   initializeIPA(Registry);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/LICENSE.=
TXT
--- a/head/contrib/llvm/tools/clang/LICENSE.TXT	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/llvm/tools/clang/LICENSE.TXT	Tue Apr 17 11:51:51 2012 +0=
300
@@ -4,7 +4,7 @@
 University of Illinois/NCSA
 Open Source License
=20
-Copyright (c) 2007-2011 University of Illinois at Urbana-Champaign.
+Copyright (c) 2007-2012 University of Illinois at Urbana-Champaign.
 All rights reserved.
=20
 Developed by:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang-c/Index.h
--- a/head/contrib/llvm/tools/clang/include/clang-c/Index.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang-c/Index.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -35,6 +35,16 @@
   #define CINDEX_LINKAGE
 #endif
=20
+#ifdef __GNUC__
+  #define CINDEX_DEPRECATED __attribute__((deprecated))
+#else
+  #ifdef _MSC_VER
+    #define CINDEX_DEPRECATED __declspec(deprecated)
+  #else
+    #define CINDEX_DEPRECATED
+  #endif
+#endif
+
 /** \defgroup CINDEX libclang: C Interface to Clang
  *
  * The C Interface to Clang provides a relatively small API that exposes
@@ -204,6 +214,61 @@
  */
 CINDEX_LINKAGE void clang_disposeIndex(CXIndex index);
=20
+typedef enum {
+  /**
+   * \brief Used to indicate that no special CXIndex options are needed.
+   */
+  CXGlobalOpt_None =3D 0x0,
+
+  /**
+   * \brief Used to indicate that threads that libclang creates for indexi=
ng
+   * purposes should use background priority.
+   * Affects \see clang_indexSourceFile, \see clang_indexTranslationUnit,
+   * \see clang_parseTranslationUnit, \see clang_saveTranslationUnit.
+   */
+  CXGlobalOpt_ThreadBackgroundPriorityForIndexing =3D 0x1,
+
+  /**
+   * \brief Used to indicate that threads that libclang creates for editing
+   * purposes should use background priority.
+   * Affects \see clang_reparseTranslationUnit, \see clang_codeCompleteAt,
+   * \see clang_annotateTokens
+   */
+  CXGlobalOpt_ThreadBackgroundPriorityForEditing =3D 0x2,
+
+  /**
+   * \brief Used to indicate that all threads that libclang creates should=
 use
+   * background priority.
+   */
+  CXGlobalOpt_ThreadBackgroundPriorityForAll =3D
+      CXGlobalOpt_ThreadBackgroundPriorityForIndexing |
+      CXGlobalOpt_ThreadBackgroundPriorityForEditing
+
+} CXGlobalOptFlags;
+
+/**
+ * \brief Sets general options associated with a CXIndex.=20
+ *
+ * For example:
+ * \code
+ * CXIndex idx =3D ...;
+ * clang_CXIndex_setGlobalOptions(idx,
+ *     clang_CXIndex_getGlobalOptions(idx) |
+ *     CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
+ * \endcode
+ *
+ * \param options A bitmask of options, a bitwise OR of CXGlobalOpt_XXX fl=
ags.
+ */
+CINDEX_LINKAGE void clang_CXIndex_setGlobalOptions(CXIndex, unsigned optio=
ns);
+
+/**
+ * \brief Gets the general options associated with a CXIndex.
+ *
+ * \returns A bitmask of options, a bitwise OR of CXGlobalOpt_XXX flags th=
at
+ * are associated with the given CXIndex object.
+ */
+CINDEX_LINKAGE unsigned clang_CXIndex_getGlobalOptions(CXIndex);
+
 /**
  * \defgroup CINDEX_FILES File manipulation routines
  *
@@ -522,6 +587,86 @@
 typedef void *CXDiagnostic;
=20
 /**
+ * \brief A group of CXDiagnostics.
+ */
+typedef void *CXDiagnosticSet;
+ =20
+/**
+ * \brief Determine the number of diagnostics in a CXDiagnosticSet.
+ */
+CINDEX_LINKAGE unsigned clang_getNumDiagnosticsInSet(CXDiagnosticSet Diags=
);
+
+/**
+ * \brief Retrieve a diagnostic associated with the given CXDiagnosticSet.
+ *
+ * \param Unit the CXDiagnosticSet to query.
+ * \param Index the zero-based diagnostic number to retrieve.
+ *
+ * \returns the requested diagnostic. This diagnostic must be freed
+ * via a call to \c clang_disposeDiagnostic().
+ */
+CINDEX_LINKAGE CXDiagnostic clang_getDiagnosticInSet(CXDiagnosticSet Diags,
+                                                     unsigned Index); =20
+
+
+/**
+ * \brief Describes the kind of error that occurred (if any) in a call to
+ * \c clang_loadDiagnostics.
+ */
+enum CXLoadDiag_Error {
+  /**
+   * \brief Indicates that no error occurred.
+   */
+  CXLoadDiag_None =3D 0,
+ =20
+  /**
+   * \brief Indicates that an unknown error occurred while attempting to
+   * deserialize diagnostics.
+   */
+  CXLoadDiag_Unknown =3D 1,
+ =20
+  /**
+   * \brief Indicates that the file containing the serialized diagnostics
+   * could not be opened.
+   */
+  CXLoadDiag_CannotLoad =3D 2,
+ =20
+  /**
+   * \brief Indicates that the serialized diagnostics file is invalid or
+   *  corrupt.
+   */
+  CXLoadDiag_InvalidFile =3D 3
+};
+ =20
+/**
+ * \brief Deserialize a set of diagnostics from a Clang diagnostics bitcode
+ *  file.
+ *
+ * \param The name of the file to deserialize.
+ * \param A pointer to a enum value recording if there was a problem
+ *        deserializing the diagnostics.
+ * \param A pointer to a CXString for recording the error string
+ *        if the file was not successfully loaded.
+ *
+ * \returns A loaded CXDiagnosticSet if successful, and NULL otherwise.  T=
hese
+ *  diagnostics should be released using clang_disposeDiagnosticSet().
+ */
+CINDEX_LINKAGE CXDiagnosticSet clang_loadDiagnostics(const char *file,
+                                                  enum CXLoadDiag_Error *e=
rror,
+                                                  CXString *errorString);
+
+/**
+ * \brief Release a CXDiagnosticSet and all of its contained diagnostics.
+ */
+CINDEX_LINKAGE void clang_disposeDiagnosticSet(CXDiagnosticSet Diags);
+
+/**
+ * \brief Retrieve the child diagnostics of a CXDiagnostic.  This
+ *  CXDiagnosticSet does not need to be released by clang_diposeDiagnostic=
Set.
+ */
+CINDEX_LINKAGE CXDiagnosticSet clang_getChildDiagnostics(CXDiagnostic D);
+
+/**
  * \brief Determine the number of diagnostics produced for the given
  * translation unit.
  */
@@ -540,6 +685,15 @@
                                                 unsigned Index);
=20
 /**
+ * \brief Retrieve the complete set of diagnostics associated with a
+ *        translation unit.
+ *
+ * \param Unit the translation unit to query.
+ */
+CINDEX_LINKAGE CXDiagnosticSet
+  clang_getDiagnosticSetFromTU(CXTranslationUnit Unit); =20
+
+/**
  * \brief Destroy a diagnostic.
  */
 CINDEX_LINKAGE void clang_disposeDiagnostic(CXDiagnostic Diagnostic);
@@ -686,14 +840,25 @@
 CINDEX_LINKAGE unsigned clang_getDiagnosticCategory(CXDiagnostic);
=20
 /**
- * \brief Retrieve the name of a particular diagnostic category.
+ * \brief Retrieve the name of a particular diagnostic category.  This
+ *  is now deprecated.  Use clang_getDiagnosticCategoryText()
+ *  instead.
  *
  * \param Category A diagnostic category number, as returned by=20
  * \c clang_getDiagnosticCategory().
  *
  * \returns The name of the given diagnostic category.
  */
-CINDEX_LINKAGE CXString clang_getDiagnosticCategoryName(unsigned Category);
+CINDEX_DEPRECATED CINDEX_LINKAGE
+CXString clang_getDiagnosticCategoryName(unsigned Category);
+
+/**
+ * \brief Retrieve the diagnostic category text for a given diagnostic.
+ *
+ *
+ * \returns The text of the given diagnostic category.
+ */
+CINDEX_LINKAGE CXString clang_getDiagnosticCategoryText(CXDiagnostic);
  =20
 /**
  * \brief Determine the number of source ranges associated with the given
@@ -905,27 +1070,15 @@
    * we are testing C++ precompiled preamble support. It is deprecated.
    */
   CXTranslationUnit_CXXChainedPCH =3D 0x20,
- =20
+
   /**
-   * \brief Used to indicate that the "detailed" preprocessing record,
-   * if requested, should also contain nested macro expansions.
+   * \brief Used to indicate that function/method bodies should be skipped=
 while
+   * parsing.
    *
-   * Nested macro expansions (i.e., macro expansions that occur
-   * inside another macro expansion) can, in some code bases, require
-   * a large amount of storage to due preprocessor metaprogramming. Moreov=
er,
-   * its fairly rare that this information is useful for libclang clients.
-   */
-  CXTranslationUnit_NestedMacroExpansions =3D 0x40,
-
-  /**
-   * \brief Legacy name to indicate that the "detailed" preprocessing reco=
rd,
-   * if requested, should contain nested macro expansions.
-   *
-   * \see CXTranslationUnit_NestedMacroExpansions for the current name for=
 this
-   * value, and its semantics. This is just an alias.
-   */
-  CXTranslationUnit_NestedMacroInstantiations =3D
-    CXTranslationUnit_NestedMacroExpansions
+   * This option can be used to search for declarations/definitions while
+   * ignoring the usages.
+   */
+  CXTranslationUnit_SkipFunctionBodies =3D 0x40
 };
=20
 /**
@@ -1411,7 +1564,13 @@
    */
   CXCursor_OverloadedDeclRef             =3D 49,
  =20
-  CXCursor_LastRef                       =3D CXCursor_OverloadedDeclRef,
+  /**
+   * \brief A reference to a variable that occurs in some non-expression=20
+   * context, e.g., a C++ lambda capture list.
+   */
+  CXCursor_VariableRef                   =3D 50,
+ =20
+  CXCursor_LastRef                       =3D CXCursor_VariableRef,
=20
   /* Error conditions */
   CXCursor_FirstInvalid                  =3D 70,
@@ -1528,7 +1687,7 @@
    */
   CXCursor_StmtExpr                      =3D 121,
=20
-  /** \brief Represents a C1X generic selection.
+  /** \brief Represents a C11 generic selection.
    */
   CXCursor_GenericSelectionExpr          =3D 122,
=20
@@ -1605,19 +1764,19 @@
    */
   CXCursor_UnaryExpr                     =3D 136,
=20
-  /** \brief ObjCStringLiteral, used for Objective-C string literals i.e. =
"foo".
+  /** \brief An Objective-C string literal i.e. @"foo".
    */
   CXCursor_ObjCStringLiteral             =3D 137,
=20
-  /** \brief ObjCEncodeExpr, used for in Objective-C.
+  /** \brief An Objective-C @encode expression.
    */
   CXCursor_ObjCEncodeExpr                =3D 138,
=20
-  /** \brief ObjCSelectorExpr used for in Objective-C.
+  /** \brief An Objective-C @selector expression.
    */
   CXCursor_ObjCSelectorExpr              =3D 139,
=20
-  /** \brief Objective-C's protocol expression.
+  /** \brief An Objective-C @protocol expression.
    */
   CXCursor_ObjCProtocolExpr              =3D 140,
=20
@@ -1657,7 +1816,25 @@
    */
   CXCursor_SizeOfPackExpr                =3D 143,
=20
-  CXCursor_LastExpr                      =3D CXCursor_SizeOfPackExpr,
+  /* \brief Represents a C++ lambda expression that produces a local funct=
ion
+   * object.
+   *
+   * \code
+   * void abssort(float *x, unsigned N) {
+   *   std::sort(x, x + N,
+   *             [](float a, float b) {
+   *               return std::abs(a) < std::abs(b);
+   *             });
+   * }
+   * \endcode
+   */
+  CXCursor_LambdaExpr                    =3D 144,
+ =20
+  /** \brief Objective-c Boolean Literal.
+   */
+  CXCursor_ObjCBoolLiteralExpr           =3D 145,
+
+  CXCursor_LastExpr                      =3D CXCursor_ObjCBoolLiteralExpr,
=20
   /* Statements */
   CXCursor_FirstStmt                     =3D 200,
@@ -1744,7 +1921,7 @@
    */
   CXCursor_AsmStmt                       =3D 215,
=20
-  /** \brief Objective-C's overall @try- at catc-@finall statement.
+  /** \brief Objective-C's overall @try- at catch-@finally statement.
    */
   CXCursor_ObjCAtTryStmt                 =3D 216,
=20
@@ -1831,7 +2008,8 @@
   CXCursor_CXXFinalAttr                  =3D 404,
   CXCursor_CXXOverrideAttr               =3D 405,
   CXCursor_AnnotateAttr                  =3D 406,
-  CXCursor_LastAttr                      =3D CXCursor_AnnotateAttr,
+  CXCursor_AsmLabelAttr                  =3D 407,
+  CXCursor_LastAttr                      =3D CXCursor_AsmLabelAttr,
     =20
   /* Preprocessing */
   CXCursor_PreprocessingDirective        =3D 500,
@@ -1894,7 +2072,7 @@
 /**
  * \brief Returns non-zero if \arg cursor is null.
  */
-int clang_Cursor_isNull(CXCursor);
+CINDEX_LINKAGE int clang_Cursor_isNull(CXCursor);
=20
 /**
  * \brief Compute a hash value for the given cursor.
@@ -2126,11 +2304,12 @@
  * In both Objective-C and C++, a method (aka virtual member function,
  * in C++) can override a virtual method in a base class. For
  * Objective-C, a method is said to override any method in the class's
- * interface (if we're coming from an implementation), its protocols,
- * or its categories, that has the same selector and is of the same
- * kind (class or instance). If no such method exists, the search
- * continues to the class's superclass, its protocols, and its
- * categories, and so on.
+ * base class, its protocols, or its categories' protocols, that has the s=
ame
+ * selector and is of the same kind (class or instance).
+ * If no such method exists, the search continues to the class's superclas=
s,
+ * its protocols, and its categories, and so on. A method from an Objectiv=
e-C
+ * implementation is considered to override the same methods as its
+ * corresponding method in the interface.
  *
  * For C++, a virtual member function overrides any virtual member
  * function with the same signature that occurs in its base
@@ -2303,10 +2482,29 @@
   CXType_ObjCObjectPointer =3D 109,
   CXType_FunctionNoProto =3D 110,
   CXType_FunctionProto =3D 111,
-  CXType_ConstantArray =3D 112
+  CXType_ConstantArray =3D 112,
+  CXType_Vector =3D 113
 };
=20
 /**
+ * \brief Describes the calling convention of a function type
+ */
+enum CXCallingConv {
+  CXCallingConv_Default =3D 0,
+  CXCallingConv_C =3D 1,
+  CXCallingConv_X86StdCall =3D 2,
+  CXCallingConv_X86FastCall =3D 3,
+  CXCallingConv_X86ThisCall =3D 4,
+  CXCallingConv_X86Pascal =3D 5,
+  CXCallingConv_AAPCS =3D 6,
+  CXCallingConv_AAPCS_VFP =3D 7,
+
+  CXCallingConv_Invalid =3D 100,
+  CXCallingConv_Unexposed =3D 200
+};
+
+
+/**
  * \brief The type of an element in the abstract syntax tree.
  *
  */
@@ -2321,6 +2519,58 @@
 CINDEX_LINKAGE CXType clang_getCursorType(CXCursor C);
=20
 /**
+ * \brief Retrieve the underlying type of a typedef declaration.
+ *
+ * If the cursor does not reference a typedef declaration, an invalid type=
 is
+ * returned.
+ */
+CINDEX_LINKAGE CXType clang_getTypedefDeclUnderlyingType(CXCursor C);
+
+/**
+ * \brief Retrieve the integer type of an enum declaration.
+ *
+ * If the cursor does not reference an enum declaration, an invalid type is
+ * returned.
+ */
+CINDEX_LINKAGE CXType clang_getEnumDeclIntegerType(CXCursor C);
+
+/**
+ * \brief Retrieve the integer value of an enum constant declaration as a =
signed
+ *  long long.
+ *
+ * If the cursor does not reference an enum constant declaration, LLONG_MI=
N is returned.
+ * Since this is also potentially a valid constant value, the kind of the =
cursor
+ * must be verified before calling this function.
+ */
+CINDEX_LINKAGE long long clang_getEnumConstantDeclValue(CXCursor C);
+
+/**
+ * \brief Retrieve the integer value of an enum constant declaration as an=
 unsigned
+ *  long long.
+ *
+ * If the cursor does not reference an enum constant declaration, ULLONG_M=
AX is returned.
+ * Since this is also potentially a valid constant value, the kind of the =
cursor
+ * must be verified before calling this function.
+ */
+CINDEX_LINKAGE unsigned long long clang_getEnumConstantDeclUnsignedValue(C=
XCursor C);
+
+/**
+ * \brief Retrieve the number of non-variadic arguments associated with a =
given
+ * cursor.
+ *
+ * If a cursor that is not a function or method is passed in, -1 is return=
ed.
+ */
+CINDEX_LINKAGE int clang_Cursor_getNumArguments(CXCursor C);
+
+/**
+ * \brief Retrieve the argument cursor of a function or method.
+ *
+ * If a cursor that is not a function or method is passed in or the index
+ * exceeds the number of arguments, an invalid cursor is returned.
+ */
+CINDEX_LINKAGE CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i);
+
+/**
  * \determine Determine whether two CXTypes represent the same type.
  *
  * \returns non-zero if the CXTypes represent the same type and=20
@@ -2378,13 +2628,44 @@
 CINDEX_LINKAGE CXString clang_getTypeKindSpelling(enum CXTypeKind K);
=20
 /**
+ * \brief Retrieve the calling convention associated with a function type.
+ *
+ * If a non-function type is passed in, CXCallingConv_Invalid is returned.
+ */
+CINDEX_LINKAGE enum CXCallingConv clang_getFunctionTypeCallingConv(CXType =
T);
+
+/**
  * \brief Retrieve the result type associated with a function type.
+ *
+ * If a non-function type is passed in, an invalid type is returned.
  */
 CINDEX_LINKAGE CXType clang_getResultType(CXType T);
=20
 /**
- * \brief Retrieve the result type associated with a given cursor.  This o=
nly
- *  returns a valid type of the cursor refers to a function or method.
+ * \brief Retrieve the number of non-variadic arguments associated with a =
function type.
+ *
+ * If a non-function type is passed in, -1 is returned.
+ */
+CINDEX_LINKAGE int clang_getNumArgTypes(CXType T);
+
+/**
+ * \brief Retrieve the type of an argument of a function type.
+ *
+ * If a non-function type is passed in or the function does not have enoug=
h parameters,
+ * an invalid type is returned.
+ */
+CINDEX_LINKAGE CXType clang_getArgType(CXType T, unsigned i);
+
+/**
+ * \brief Return 1 if the CXType is a variadic function type, and 0 otherw=
ise.
+ *
+ */
+CINDEX_LINKAGE unsigned clang_isFunctionTypeVariadic(CXType T);
+
+/**
+ * \brief Retrieve the result type associated with a given cursor.
+ *
+ * This only returns a valid type if the cursor refers to a function or me=
thod.
  */
 CINDEX_LINKAGE CXType clang_getCursorResultType(CXCursor C);
=20
@@ -2395,6 +2676,22 @@
 CINDEX_LINKAGE unsigned clang_isPODType(CXType T);
=20
 /**
+ * \brief Return the element type of an array, complex, or vector type.
+ *
+ * If a type is passed in that is not an array, complex, or vector type,
+ * an invalid type is returned.
+ */
+CINDEX_LINKAGE CXType clang_getElementType(CXType T);
+
+/**
+ * \brief Return the number of elements of an array or vector type.
+ *
+ * If a type is passed in that is not an array or vector type,
+ * -1 is returned.
+ */
+CINDEX_LINKAGE long long clang_getNumElements(CXType T);
+
+/**
  * \brief Return the element type of an array type.
  *
  * If a non-array type is passed in, an invalid type is returned.
@@ -2653,6 +2950,21 @@
 CINDEX_LINKAGE CXString clang_getCursorSpelling(CXCursor);
=20
 /**
+ * \brief Retrieve a range for a piece that forms the cursors spelling nam=
e.
+ * Most of the times there is only one range for the complete spelling but=
 for
+ * objc methods and objc message expressions, there are multiple pieces fo=
r each
+ * selector identifier.
+ *=20
+ * \param pieceIndex the index of the spelling name piece. If this is grea=
ter
+ * than the actual number of pieces, it will return a NULL (invalid) range.
+ * =20
+ * \param options Reserved.
+ */
+CINDEX_LINKAGE CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor,
+                                                          unsigned pieceIn=
dex,
+                                                          unsigned options=
);
+
+/**
  * \brief Retrieve the display name for the entity referenced by this curs=
or.
  *
  * The display name contains extra information that helps identify the cur=
sor,
@@ -2735,6 +3047,20 @@
  */
 CINDEX_LINKAGE CXCursor clang_getCanonicalCursor(CXCursor);
=20
+
+/**
+ * \brief If the cursor points to a selector identifier in a objc method or
+ * message expression, this returns the selector index.
+ *
+ * After getting a cursor with \see clang_getCursor, this can be called to
+ * determine if the location points to a selector identifier.
+ *
+ * \returns The selector index if the cursor is an objc method or message
+ * expression and the cursor is pointing to a selector identifier, or -1
+ * otherwise.
+ */
+CINDEX_LINKAGE int clang_Cursor_getObjCSelectorIndex(CXCursor);
+
 /**
  * @}
  */
@@ -3347,6 +3673,26 @@
                               unsigned annotation_number);
=20
 /**
+ * \brief Retrieve the parent context of the given completion string.
+ *
+ * The parent context of a completion string is the semantic parent of=20
+ * the declaration (if any) that the code completion represents. For examp=
le,
+ * a code completion for an Objective-C method would have the method's cla=
ss
+ * or protocol as its context.
+ *
+ * \param completion_string The code completion string whose parent is
+ * being queried.
+ *
+ * \param kind If non-NULL, will be set to the kind of the parent context,
+ * or CXCursor_NotImplemented if there is no context.
+ *
+ * \param Returns the name of the completion parent, e.g., "NSObject" if
+ * the completion string represents a method in the NSObject class.
+ */
+CINDEX_LINKAGE CXString
+clang_getCompletionParent(CXCompletionString completion_string,
+                          enum CXCursorKind *kind);
+/**
  * \brief Retrieve a completion string for an arbitrary declaration or mac=
ro
  * definition cursor.
  *
@@ -3788,6 +4134,20 @@
 CINDEX_LINKAGE CXRemapping clang_getRemappings(const char *path);
=20
 /**
+ * \brief Retrieve a remapping.
+ *
+ * \param filePaths pointer to an array of file paths containing remapping=
 info.
+ *
+ * \param numFiles number of file paths.
+ *
+ * \returns the requested remapping. This remapping must be freed
+ * via a call to \c clang_remap_dispose(). Can return NULL if an error occ=
urred.
+ */
+CINDEX_LINKAGE
+CXRemapping clang_getRemappingsFromFileList(const char **filePaths,
+                                            unsigned numFiles);
+
+/**
  * \brief Determine the number of remappings.
  */
 CINDEX_LINKAGE unsigned clang_remap_getNumFiles(CXRemapping);
@@ -3856,6 +4216,524 @@
 #endif
=20
 /**
+ * \brief The client's data object that is associated with a CXFile.
+ */
+typedef void *CXIdxClientFile;
+
+/**
+ * \brief The client's data object that is associated with a semantic enti=
ty.
+ */
+typedef void *CXIdxClientEntity;
+
+/**
+ * \brief The client's data object that is associated with a semantic cont=
ainer
+ * of entities.
+ */
+typedef void *CXIdxClientContainer;
+
+/**
+ * \brief The client's data object that is associated with an AST file (PCH
+ * or module).
+ */
+typedef void *CXIdxClientASTFile;
+
+/**
+ * \brief Source location passed to index callbacks.
+ */
+typedef struct {
+  void *ptr_data[2];
+  unsigned int_data;
+} CXIdxLoc;
+
+/**
+ * \brief Data for \see ppIncludedFile callback.
+ */
+typedef struct {
+  /**
+   * \brief Location of '#' in the #include/#import directive.
+   */
+  CXIdxLoc hashLoc;
+  /**
+   * \brief Filename as written in the #include/#import directive.
+   */
+  const char *filename;
+  /**
+   * \brief The actual file that the #include/#import directive resolved t=
o.
+   */
+  CXFile file;
+  int isImport;
+  int isAngled;
+} CXIdxIncludedFileInfo;
+
+/**
+ * \brief Data for \see importedASTFile callback.
+ */
+typedef struct {
+  CXFile file;
+  /**
+   * \brief Location where the file is imported. It is useful mostly for
+   * modules.
+   */
+  CXIdxLoc loc;
+  /**
+   * \brief Non-zero if the AST file is a module otherwise it's a PCH.
+   */
+  int isModule;
+} CXIdxImportedASTFileInfo;
+
+typedef enum {
+  CXIdxEntity_Unexposed     =3D 0,
+  CXIdxEntity_Typedef       =3D 1,
+  CXIdxEntity_Function      =3D 2,
+  CXIdxEntity_Variable      =3D 3,
+  CXIdxEntity_Field         =3D 4,
+  CXIdxEntity_EnumConstant  =3D 5,
+
+  CXIdxEntity_ObjCClass     =3D 6,
+  CXIdxEntity_ObjCProtocol  =3D 7,
+  CXIdxEntity_ObjCCategory  =3D 8,
+
+  CXIdxEntity_ObjCInstanceMethod =3D 9,
+  CXIdxEntity_ObjCClassMethod    =3D 10,
+  CXIdxEntity_ObjCProperty  =3D 11,
+  CXIdxEntity_ObjCIvar      =3D 12,
+
+  CXIdxEntity_Enum          =3D 13,
+  CXIdxEntity_Struct        =3D 14,
+  CXIdxEntity_Union         =3D 15,
+
+  CXIdxEntity_CXXClass              =3D 16,
+  CXIdxEntity_CXXNamespace          =3D 17,
+  CXIdxEntity_CXXNamespaceAlias     =3D 18,
+  CXIdxEntity_CXXStaticVariable     =3D 19,
+  CXIdxEntity_CXXStaticMethod       =3D 20,
+  CXIdxEntity_CXXInstanceMethod     =3D 21,
+  CXIdxEntity_CXXConstructor        =3D 22,
+  CXIdxEntity_CXXDestructor         =3D 23,
+  CXIdxEntity_CXXConversionFunction =3D 24,
+  CXIdxEntity_CXXTypeAlias          =3D 25
+
+} CXIdxEntityKind;
+
+typedef enum {
+  CXIdxEntityLang_None =3D 0,
+  CXIdxEntityLang_C    =3D 1,
+  CXIdxEntityLang_ObjC =3D 2,
+  CXIdxEntityLang_CXX  =3D 3
+} CXIdxEntityLanguage;
+
+/**
+ * \brief Extra C++ template information for an entity. This can apply to:
+ * CXIdxEntity_Function
+ * CXIdxEntity_CXXClass
+ * CXIdxEntity_CXXStaticMethod
+ * CXIdxEntity_CXXInstanceMethod
+ * CXIdxEntity_CXXConstructor
+ * CXIdxEntity_CXXConversionFunction
+ * CXIdxEntity_CXXTypeAlias
+ */
+typedef enum {
+  CXIdxEntity_NonTemplate   =3D 0,
+  CXIdxEntity_Template      =3D 1,
+  CXIdxEntity_TemplatePartialSpecialization =3D 2,
+  CXIdxEntity_TemplateSpecialization =3D 3
+} CXIdxEntityCXXTemplateKind;
+
+typedef enum {
+  CXIdxAttr_Unexposed     =3D 0,
+  CXIdxAttr_IBAction      =3D 1,
+  CXIdxAttr_IBOutlet      =3D 2,
+  CXIdxAttr_IBOutletCollection =3D 3
+} CXIdxAttrKind;
+
+typedef struct {
+  CXIdxAttrKind kind;
+  CXCursor cursor;
+  CXIdxLoc loc;
+} CXIdxAttrInfo;
+
+typedef struct {
+  CXIdxEntityKind kind;
+  CXIdxEntityCXXTemplateKind templateKind;
+  CXIdxEntityLanguage lang;
+  const char *name;
+  const char *USR;
+  CXCursor cursor;
+  const CXIdxAttrInfo *const *attributes;
+  unsigned numAttributes;
+} CXIdxEntityInfo;
+
+typedef struct {
+  CXCursor cursor;
+} CXIdxContainerInfo;
+
+typedef struct {
+  const CXIdxAttrInfo *attrInfo;
+  const CXIdxEntityInfo *objcClass;
+  CXCursor classCursor;
+  CXIdxLoc classLoc;
+} CXIdxIBOutletCollectionAttrInfo;
+
+typedef struct {
+  const CXIdxEntityInfo *entityInfo;
+  CXCursor cursor;
+  CXIdxLoc loc;
+  const CXIdxContainerInfo *semanticContainer;
+  /**
+   * \brief Generally same as \see semanticContainer but can be different =
in
+   * cases like out-of-line C++ member functions.
+   */
+  const CXIdxContainerInfo *lexicalContainer;
+  int isRedeclaration;
+  int isDefinition;
+  int isContainer;
+  const CXIdxContainerInfo *declAsContainer;
+  /**
+   * \brief Whether the declaration exists in code or was created implicit=
ly
+   * by the compiler, e.g. implicit objc methods for properties.
+   */
+  int isImplicit;
+  const CXIdxAttrInfo *const *attributes;
+  unsigned numAttributes;
+} CXIdxDeclInfo;
+
+typedef enum {
+  CXIdxObjCContainer_ForwardRef =3D 0,
+  CXIdxObjCContainer_Interface =3D 1,
+  CXIdxObjCContainer_Implementation =3D 2
+} CXIdxObjCContainerKind;
+
+typedef struct {
+  const CXIdxDeclInfo *declInfo;
+  CXIdxObjCContainerKind kind;
+} CXIdxObjCContainerDeclInfo;
+
+typedef struct {
+  const CXIdxEntityInfo *base;
+  CXCursor cursor;
+  CXIdxLoc loc;
+} CXIdxBaseClassInfo;
+
+typedef struct {
+  const CXIdxEntityInfo *protocol;
+  CXCursor cursor;
+  CXIdxLoc loc;
+} CXIdxObjCProtocolRefInfo;
+
+typedef struct {
+  const CXIdxObjCProtocolRefInfo *const *protocols;
+  unsigned numProtocols;
+} CXIdxObjCProtocolRefListInfo;
+
+typedef struct {
+  const CXIdxObjCContainerDeclInfo *containerInfo;
+  const CXIdxBaseClassInfo *superInfo;
+  const CXIdxObjCProtocolRefListInfo *protocols;
+} CXIdxObjCInterfaceDeclInfo;
+
+typedef struct {
+  const CXIdxObjCContainerDeclInfo *containerInfo;
+  const CXIdxEntityInfo *objcClass;
+  CXCursor classCursor;
+  CXIdxLoc classLoc;
+  const CXIdxObjCProtocolRefListInfo *protocols;
+} CXIdxObjCCategoryDeclInfo;
+
+typedef struct {
+  const CXIdxDeclInfo *declInfo;
+  const CXIdxEntityInfo *getter;
+  const CXIdxEntityInfo *setter;
+} CXIdxObjCPropertyDeclInfo;
+
+typedef struct {
+  const CXIdxDeclInfo *declInfo;
+  const CXIdxBaseClassInfo *const *bases;
+  unsigned numBases;
+} CXIdxCXXClassDeclInfo;
+
+/**
+ * \brief Data for \see indexEntityReference callback.
+ */
+typedef enum {
+  /**
+   * \brief The entity is referenced directly in user's code.
+   */
+  CXIdxEntityRef_Direct =3D 1,
+  /**
+   * \brief An implicit reference, e.g. a reference of an ObjC method via =
the
+   * dot syntax.
+   */
+  CXIdxEntityRef_Implicit =3D 2
+} CXIdxEntityRefKind;
+
+/**
+ * \brief Data for \see indexEntityReference callback.
+ */
+typedef struct {
+  CXIdxEntityRefKind kind;
+  /**
+   * \brief Reference cursor.
+   */
+  CXCursor cursor;
+  CXIdxLoc loc;
+  /**
+   * \brief The entity that gets referenced.
+   */
+  const CXIdxEntityInfo *referencedEntity;
+  /**
+   * \brief Immediate "parent" of the reference. For example:
+   *=20
+   * \code
+   * Foo *var;
+   * \endcode
+   *=20
+   * The parent of reference of type 'Foo' is the variable 'var'.
+   * For references inside statement bodies of functions/methods,
+   * the parentEntity will be the function/method.
+   */
+  const CXIdxEntityInfo *parentEntity;
+  /**
+   * \brief Lexical container context of the reference.
+   */
+  const CXIdxContainerInfo *container;
+} CXIdxEntityRefInfo;
+
+typedef struct {
+  /**
+   * \brief Called periodically to check whether indexing should be aborte=
d.
+   * Should return 0 to continue, and non-zero to abort.
+   */
+  int (*abortQuery)(CXClientData client_data, void *reserved);
+
+  /**
+   * \brief Called at the end of indexing; passes the complete diagnostic =
set.
+   */
+  void (*diagnostic)(CXClientData client_data,
+                     CXDiagnosticSet, void *reserved);
+
+  CXIdxClientFile (*enteredMainFile)(CXClientData client_data,
+                               CXFile mainFile, void *reserved);
+ =20
+  /**
+   * \brief Called when a file gets #included/#imported.
+   */
+  CXIdxClientFile (*ppIncludedFile)(CXClientData client_data,
+                                    const CXIdxIncludedFileInfo *);
+ =20
+  /**
+   * \brief Called when a AST file (PCH or module) gets imported.
+   *=20
+   * AST files will not get indexed (there will not be callbacks to index =
all
+   * the entities in an AST file). The recommended action is that, if the =
AST
+   * file is not already indexed, to block further indexing and initiate a=
 new
+   * indexing job specific to the AST file.
+   */
+  CXIdxClientASTFile (*importedASTFile)(CXClientData client_data,
+                                        const CXIdxImportedASTFileInfo *);
+
+  /**
+   * \brief Called at the beginning of indexing a translation unit.
+   */
+  CXIdxClientContainer (*startedTranslationUnit)(CXClientData client_data,
+                                                 void *reserved);
+
+  void (*indexDeclaration)(CXClientData client_data,
+                           const CXIdxDeclInfo *);
+
+  /**
+   * \brief Called to index a reference of an entity.
+   */
+  void (*indexEntityReference)(CXClientData client_data,
+                               const CXIdxEntityRefInfo *);
+
+} IndexerCallbacks;
+
+CINDEX_LINKAGE int clang_index_isEntityObjCContainerKind(CXIdxEntityKind);
+CINDEX_LINKAGE const CXIdxObjCContainerDeclInfo *
+clang_index_getObjCContainerDeclInfo(const CXIdxDeclInfo *);
+
+CINDEX_LINKAGE const CXIdxObjCInterfaceDeclInfo *
+clang_index_getObjCInterfaceDeclInfo(const CXIdxDeclInfo *);
+
+CINDEX_LINKAGE
+const CXIdxObjCCategoryDeclInfo *
+clang_index_getObjCCategoryDeclInfo(const CXIdxDeclInfo *);
+
+CINDEX_LINKAGE const CXIdxObjCProtocolRefListInfo *
+clang_index_getObjCProtocolRefListInfo(const CXIdxDeclInfo *);
+
+CINDEX_LINKAGE const CXIdxObjCPropertyDeclInfo *
+clang_index_getObjCPropertyDeclInfo(const CXIdxDeclInfo *);
+
+CINDEX_LINKAGE const CXIdxIBOutletCollectionAttrInfo *
+clang_index_getIBOutletCollectionAttrInfo(const CXIdxAttrInfo *);
+
+CINDEX_LINKAGE const CXIdxCXXClassDeclInfo *
+clang_index_getCXXClassDeclInfo(const CXIdxDeclInfo *);
+
+/**
+ * \brief For retrieving a custom CXIdxClientContainer attached to a
+ * container.
+ */
+CINDEX_LINKAGE CXIdxClientContainer
+clang_index_getClientContainer(const CXIdxContainerInfo *);
+
+/**
+ * \brief For setting a custom CXIdxClientContainer attached to a
+ * container.
+ */
+CINDEX_LINKAGE void
+clang_index_setClientContainer(const CXIdxContainerInfo *,CXIdxClientConta=
iner);
+
+/**
+ * \brief For retrieving a custom CXIdxClientEntity attached to an entity.
+ */
+CINDEX_LINKAGE CXIdxClientEntity
+clang_index_getClientEntity(const CXIdxEntityInfo *);
+
+/**
+ * \brief For setting a custom CXIdxClientEntity attached to an entity.
+ */
+CINDEX_LINKAGE void
+clang_index_setClientEntity(const CXIdxEntityInfo *, CXIdxClientEntity);
+
+/**
+ * \brief An indexing action, to be applied to one or multiple translation=
 units
+ * but not on concurrent threads. If there are threads doing indexing
+ * concurrently, they should use different CXIndexAction objects.
+ */
+typedef void *CXIndexAction;
+
+/**
+ * \brief An indexing action, to be applied to one or multiple translation=
 units
+ * but not on concurrent threads. If there are threads doing indexing
+ * concurrently, they should use different CXIndexAction objects.
+ *
+ * \param CIdx The index object with which the index action will be associ=
ated.
+ */
+CINDEX_LINKAGE CXIndexAction clang_IndexAction_create(CXIndex CIdx);
+
+/**
+ * \brief Destroy the given index action.
+ *
+ * The index action must not be destroyed until all of the translation uni=
ts
+ * created within that index action have been destroyed.
+ */
+CINDEX_LINKAGE void clang_IndexAction_dispose(CXIndexAction);
+
+typedef enum {
+  /**
+   * \brief Used to indicate that no special indexing options are needed.
+   */
+  CXIndexOpt_None =3D 0x0,
+ =20
+  /**
+   * \brief Used to indicate that \see indexEntityReference should be invo=
ked
+   * for only one reference of an entity per source file that does not also
+   * include a declaration/definition of the entity.
+   */
+  CXIndexOpt_SuppressRedundantRefs =3D 0x1,
+
+  /**
+   * \brief Function-local symbols should be indexed. If this is not set
+   * function-local symbols will be ignored.
+   */
+  CXIndexOpt_IndexFunctionLocalSymbols =3D 0x2,
+
+  /**
+   * \brief Implicit function/class template instantiations should be inde=
xed.
+   * If this is not set, implicit instantiations will be ignored.
+   */
+  CXIndexOpt_IndexImplicitTemplateInstantiations =3D 0x4,
+
+  /**
+   * \brief Suppress all compiler warnings when parsing for indexing.
+   */
+  CXIndexOpt_SuppressWarnings =3D 0x8
+} CXIndexOptFlags;
+
+/**
+ * \brief Index the given source file and the translation unit correspondi=
ng
+ * to that file via callbacks implemented through \see IndexerCallbacks.
+ *
+ * \param client_data pointer data supplied by the client, which will
+ * be passed to the invoked callbacks.
+ *
+ * \param index_callbacks Pointer to indexing callbacks that the client
+ * implements.
+ *
+ * \param index_callbacks_size Size of \see IndexerCallbacks structure tha=
t gets
+ * passed in index_callbacks.
+ *
+ * \param index_options A bitmask of options that affects how indexing is
+ * performed. This should be a bitwise OR of the CXIndexOpt_XXX flags.
+ *
+ * \param out_TU [out] pointer to store a CXTranslationUnit that can be re=
used
+ * after indexing is finished. Set to NULL if you do not require it.
+ *
+ * \returns If there is a failure from which the there is no recovery, ret=
urns
+ * non-zero, otherwise returns 0.
+ *
+ * The rest of the parameters are the same as \see clang_parseTranslationU=
nit.
+ */
+CINDEX_LINKAGE int clang_indexSourceFile(CXIndexAction,
+                                         CXClientData client_data,
+                                         IndexerCallbacks *index_callbacks,
+                                         unsigned index_callbacks_size,
+                                         unsigned index_options,
+                                         const char *source_filename,
+                                         const char * const *command_line_=
args,
+                                         int num_command_line_args,
+                                         struct CXUnsavedFile *unsaved_fil=
es,
+                                         unsigned num_unsaved_files,
+                                         CXTranslationUnit *out_TU,
+                                         unsigned TU_options);
+
+/**
+ * \brief Index the given translation unit via callbacks implemented throu=
gh
+ * \see IndexerCallbacks.
+ *=20
+ * The order of callback invocations is not guaranteed to be the same as
+ * when indexing a source file. The high level order will be:
+ *=20
+ *   -Preprocessor callbacks invocations
+ *   -Declaration/reference callbacks invocations
+ *   -Diagnostic callback invocations
+ *
+ * The parameters are the same as \see clang_indexSourceFile.
+ *=20
+ * \returns If there is a failure from which the there is no recovery, ret=
urns
+ * non-zero, otherwise returns 0.
+ */
+CINDEX_LINKAGE int clang_indexTranslationUnit(CXIndexAction,
+                                              CXClientData client_data,
+                                              IndexerCallbacks *index_call=
backs,
+                                              unsigned index_callbacks_siz=
e,
+                                              unsigned index_options,
+                                              CXTranslationUnit);
+
+/**
+ * \brief Retrieve the CXIdxFile, file, line, column, and offset represent=
ed by
+ * the given CXIdxLoc.
+ *
+ * If the location refers into a macro expansion, retrieves the
+ * location of the macro expansion and if it refers into a macro argument
+ * retrieves the location of the argument.
+ */
+CINDEX_LINKAGE void clang_indexLoc_getFileLocation(CXIdxLoc loc,
+                                                   CXIdxClientFile *indexF=
ile,
+                                                   CXFile *file,
+                                                   unsigned *line,
+                                                   unsigned *column,
+                                                   unsigned *offset);
+
+/**
+ * \brief Retrieve the CXSourceLocation represented by the given CXIdxLoc.
+ */
+CINDEX_LINKAGE
+CXSourceLocation clang_indexLoc_getCXSourceLocation(CXIdxLoc loc);
+
+/**
  * @}
  */
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/ARCMigrate/ARCMT.h
--- a/head/contrib/llvm/tools/clang/include/clang/ARCMigrate/ARCMT.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/ARCMigrate/ARCMT.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -37,7 +37,7 @@
 ///
 /// \returns false if no error is produced, true otherwise.
 bool checkForManualIssues(CompilerInvocation &CI,
-                          StringRef Filename, InputKind Kind,
+                          const FrontendInputFile &Input,
                           DiagnosticConsumer *DiagClient,
                           bool emitPremigrationARCErrors =3D false,
                           StringRef plistOut =3D StringRef());
@@ -47,7 +47,7 @@
 ///
 /// \returns false if no error is produced, true otherwise.
 bool applyTransformations(CompilerInvocation &origCI,
-                          StringRef Filename, InputKind Kind,
+                          const FrontendInputFile &Input,
                           DiagnosticConsumer *DiagClient);
=20
 /// \brief Applies automatic modifications and produces temporary files
@@ -62,7 +62,7 @@
 ///
 /// \returns false if no error is produced, true otherwise.
 bool migrateWithTemporaryFiles(CompilerInvocation &origCI,
-                               StringRef Filename, InputKind Kind,
+                               const FrontendInputFile &Input,
                                DiagnosticConsumer *DiagClient,
                                StringRef outputDir,
                                bool emitPremigrationARCErrors,
@@ -76,9 +76,19 @@
                        StringRef outputDir,
                        DiagnosticConsumer *DiagClient);
=20
+/// \brief Get the set of file remappings from a list of files with remapp=
ing
+/// info.
+///
+/// \returns false if no error is produced, true otherwise.
+bool getFileRemappingsFromFileList(
+                        std::vector<std::pair<std::string,std::string> > &=
remap,
+                        ArrayRef<StringRef> remapFiles,
+                        DiagnosticConsumer *DiagClient);
+
 typedef void (*TransformFn)(MigrationPass &pass);
=20
-std::vector<TransformFn> getAllTransformations();
+std::vector<TransformFn> getAllTransformations(LangOptions::GCMode OrigGCM=
ode,
+                                               bool NoFinalizeRemoval);
=20
 class MigrationProcess {
   CompilerInvocation OrigCI;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/ARCMigrate/ARCMTActions.h
--- a/head/contrib/llvm/tools/clang/include/clang/ARCMigrate/ARCMTActions.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/ARCMigrate/ARCMTActions.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -11,6 +11,7 @@
 #define LLVM_CLANG_ARCMIGRATE_ARCMT_ACTION_H
=20
 #include "clang/Frontend/FrontendAction.h"
+#include "clang/ARCMigrate/FileRemapper.h"
 #include "llvm/ADT/OwningPtr.h"
=20
 namespace clang {
@@ -32,6 +33,14 @@
   ModifyAction(FrontendAction *WrappedAction);
 };
=20
+class MigrateSourceAction : public ASTFrontendAction {
+  FileRemapper Remapper;
+protected:
+  virtual bool BeginInvocation(CompilerInstance &CI);
+  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
+                                         StringRef InFile);
+};
+
 class MigrateAction : public WrapperFrontendAction {
   std::string MigrateDir;
   std::string PlistOut;
@@ -45,6 +54,23 @@
                 bool emitPremigrationARCErrors);
 };
=20
+/// \brief Migrates to modern ObjC syntax.
+class ObjCMigrateAction : public WrapperFrontendAction {
+  std::string MigrateDir;
+  bool MigrateLiterals;
+  bool MigrateSubscripting;
+  FileRemapper Remapper;
+  CompilerInstance *CompInst;
+public:
+  ObjCMigrateAction(FrontendAction *WrappedAction, StringRef migrateDir,
+                    bool migrateLiterals,
+                    bool migrateSubscripting);
+
+protected:
+  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,StringRef In=
File);
+  virtual bool BeginInvocation(CompilerInstance &CI);
+};
+
 }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/ARCMigrate/FileRemapper.h
--- a/head/contrib/llvm/tools/clang/include/clang/ARCMigrate/FileRemapper.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/ARCMigrate/FileRemapper.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -24,13 +24,13 @@
   class FileManager;
   class FileEntry;
   class DiagnosticsEngine;
-  class CompilerInvocation;
+  class PreprocessorOptions;
=20
 namespace arcmt {
=20
 class FileRemapper {
   // FIXME: Reuse the same FileManager for multiple ASTContexts.
-  llvm::OwningPtr<FileManager> FileMgr;
+  OwningPtr<FileManager> FileMgr;
=20
   typedef llvm::PointerUnion<const FileEntry *, llvm::MemoryBuffer *> Targ=
et;
   typedef llvm::DenseMap<const FileEntry *, Target> MappingsTy;
@@ -44,7 +44,10 @@
  =20
   bool initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag,
                     bool ignoreIfFilesChanged);
+  bool initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
+                    bool ignoreIfFilesChanged);
   bool flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag);
+  bool flushToFile(StringRef outputPath, DiagnosticsEngine &Diag);
=20
   bool overwriteOriginal(DiagnosticsEngine &Diag,
                          StringRef outputDir =3D StringRef());
@@ -52,9 +55,9 @@
   void remap(StringRef filePath, llvm::MemoryBuffer *memBuf);
   void remap(StringRef filePath, StringRef newPath);
=20
-  void applyMappings(CompilerInvocation &CI) const;
+  void applyMappings(PreprocessorOptions &PPOpts) const;
=20
-  void transferMappingsAndClear(CompilerInvocation &CI);
+  void transferMappingsAndClear(PreprocessorOptions &PPOpts);
=20
   void clear(StringRef outputDir =3D StringRef());
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/APValue.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/APValue.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/APValue.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -17,14 +17,24 @@
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/APSInt.h"
 #include "llvm/ADT/APFloat.h"
+#include "llvm/ADT/PointerIntPair.h"
+#include "llvm/ADT/PointerUnion.h"
=20
 namespace clang {
+  class AddrLabelExpr;
+  class ASTContext;
   class CharUnits;
   class DiagnosticBuilder;
   class Expr;
+  class FieldDecl;
+  class Decl;
+  class ValueDecl;
+  class CXXRecordDecl;
+  class QualType;
=20
 /// APValue - This class implements a discriminated union of [uninitialize=
d]
-/// [APSInt] [APFloat], [Complex APSInt] [Complex APFloat], [Expr + Offset=
].
+/// [APSInt] [APFloat], [Complex APSInt] [Complex APFloat], [Expr + Offset=
],
+/// [Vector: N * APValue], [Array: N * APValue]
 class APValue {
   typedef llvm::APSInt APSInt;
   typedef llvm::APFloat APFloat;
@@ -36,8 +46,25 @@
     ComplexInt,
     ComplexFloat,
     LValue,
-    Vector
+    Vector,
+    Array,
+    Struct,
+    Union,
+    MemberPointer,
+    AddrLabelDiff
   };
+  typedef llvm::PointerUnion<const ValueDecl *, const Expr *> LValueBase;
+  typedef llvm::PointerIntPair<const Decl *, 1, bool> BaseOrMemberType;
+  union LValuePathEntry {
+    /// BaseOrMember - The FieldDecl or CXXRecordDecl indicating the next =
item
+    /// in the path. An opaque value of type BaseOrMemberType.
+    void *BaseOrMember;
+    /// ArrayIndex - The array index of the next item in the path.
+    uint64_t ArrayIndex;
+  };
+  struct NoLValuePath {};
+  struct UninitArray {};
+  struct UninitStruct {};
 private:
   ValueKind Kind;
=20
@@ -49,13 +76,37 @@
     APFloat Real, Imag;
     ComplexAPFloat() : Real(0.0), Imag(0.0) {}
   };
-
+  struct LV;
   struct Vec {
     APValue *Elts;
     unsigned NumElts;
     Vec() : Elts(0), NumElts(0) {}
     ~Vec() { delete[] Elts; }
   };
+  struct Arr {
+    APValue *Elts;
+    unsigned NumElts, ArrSize;
+    Arr(unsigned NumElts, unsigned ArrSize);
+    ~Arr();
+  };
+  struct StructData {
+    APValue *Elts;
+    unsigned NumBases;
+    unsigned NumFields;
+    StructData(unsigned NumBases, unsigned NumFields);
+    ~StructData();
+  };
+  struct UnionData {
+    const FieldDecl *Field;
+    APValue *Value;
+    UnionData();
+    ~UnionData();
+  };
+  struct AddrLabelDiffData {
+    const AddrLabelExpr* LHSExpr;
+    const AddrLabelExpr* RHSExpr;
+  };
+  struct MemberPointerData;
=20
   enum {
     MaxSize =3D (sizeof(ComplexAPSInt) > sizeof(ComplexAPFloat) ?
@@ -84,18 +135,42 @@
   APValue(const APFloat &R, const APFloat &I) : Kind(Uninitialized) {
     MakeComplexFloat(); setComplexFloat(R, I);
   }
-  APValue(const APValue &RHS) : Kind(Uninitialized) {
-    *this =3D RHS;
+  APValue(const APValue &RHS);
+  APValue(LValueBase B, const CharUnits &O, NoLValuePath N, unsigned CallI=
ndex)
+      : Kind(Uninitialized) {
+    MakeLValue(); setLValue(B, O, N, CallIndex);
   }
-  APValue(const Expr* B, const CharUnits &O) : Kind(Uninitialized) {
-    MakeLValue(); setLValue(B, O);
+  APValue(LValueBase B, const CharUnits &O, ArrayRef<LValuePathEntry> Path,
+          bool OnePastTheEnd, unsigned CallIndex)
+      : Kind(Uninitialized) {
+    MakeLValue(); setLValue(B, O, Path, OnePastTheEnd, CallIndex);
   }
-  APValue(const Expr* B);
+  APValue(UninitArray, unsigned InitElts, unsigned Size) : Kind(Uninitiali=
zed) {
+    MakeArray(InitElts, Size);
+  }
+  APValue(UninitStruct, unsigned B, unsigned M) : Kind(Uninitialized) {
+    MakeStruct(B, M);
+  }
+  explicit APValue(const FieldDecl *D, const APValue &V =3D APValue())
+      : Kind(Uninitialized) {
+    MakeUnion(); setUnion(D, V);
+  }
+  APValue(const ValueDecl *Member, bool IsDerivedMember,
+          ArrayRef<const CXXRecordDecl*> Path) : Kind(Uninitialized) {
+    MakeMemberPointer(Member, IsDerivedMember, Path);
+  }
+  APValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr)
+      : Kind(Uninitialized) {
+    MakeAddrLabelDiff(); setAddrLabelDiff(LHSExpr, RHSExpr);
+  }
=20
   ~APValue() {
     MakeUninit();
   }
=20
+  /// \brief Swaps the contents of this and the given APValue.
+  void swap(APValue &RHS);
+
   ValueKind getKind() const { return Kind; }
   bool isUninit() const { return Kind =3D=3D Uninitialized; }
   bool isInt() const { return Kind =3D=3D Int; }
@@ -104,9 +179,17 @@
   bool isComplexFloat() const { return Kind =3D=3D ComplexFloat; }
   bool isLValue() const { return Kind =3D=3D LValue; }
   bool isVector() const { return Kind =3D=3D Vector; }
+  bool isArray() const { return Kind =3D=3D Array; }
+  bool isStruct() const { return Kind =3D=3D Struct; }
+  bool isUnion() const { return Kind =3D=3D Union; }
+  bool isMemberPointer() const { return Kind =3D=3D MemberPointer; }
+  bool isAddrLabelDiff() const { return Kind =3D=3D AddrLabelDiff; }
=20
-  void print(raw_ostream &OS) const;
   void dump() const;
+  void dump(raw_ostream &OS) const;
+
+  void printPretty(raw_ostream &OS, ASTContext &Ctx, QualType Ty) const;
+  std::string getAsString(ASTContext &Ctx, QualType Ty) const;
=20
   APSInt &getInt() {
     assert(isInt() && "Invalid accessor");
@@ -124,19 +207,6 @@
     return const_cast<APValue*>(this)->getFloat();
   }
=20
-  APValue &getVectorElt(unsigned i) {
-    assert(isVector() && "Invalid accessor");
-    return ((Vec*)(char*)Data)->Elts[i];
-  }
-  const APValue &getVectorElt(unsigned i) const {
-    assert(isVector() && "Invalid accessor");
-    return ((const Vec*)(const char*)Data)->Elts[i];
-  }
-  unsigned getVectorLength() const {
-    assert(isVector() && "Invalid accessor");
-    return ((const Vec*)(const void *)Data)->NumElts;
-  }
-
   APSInt &getComplexIntReal() {
     assert(isComplexInt() && "Invalid accessor");
     return ((ComplexAPSInt*)(char*)Data)->Real;
@@ -169,8 +239,104 @@
     return const_cast<APValue*>(this)->getComplexFloatImag();
   }
=20
-  const Expr* getLValueBase() const;
-  CharUnits getLValueOffset() const;
+  const LValueBase getLValueBase() const;
+  CharUnits &getLValueOffset();
+  const CharUnits &getLValueOffset() const {
+    return const_cast<APValue*>(this)->getLValueOffset();
+  }
+  bool isLValueOnePastTheEnd() const;
+  bool hasLValuePath() const;
+  ArrayRef<LValuePathEntry> getLValuePath() const;
+  unsigned getLValueCallIndex() const;
+
+  APValue &getVectorElt(unsigned I) {
+    assert(isVector() && "Invalid accessor");
+    assert(I < getVectorLength() && "Index out of range");
+    return ((Vec*)(char*)Data)->Elts[I];
+  }
+  const APValue &getVectorElt(unsigned I) const {
+    return const_cast<APValue*>(this)->getVectorElt(I);
+  }
+  unsigned getVectorLength() const {
+    assert(isVector() && "Invalid accessor");
+    return ((const Vec*)(const void *)Data)->NumElts;
+  }
+
+  APValue &getArrayInitializedElt(unsigned I) {
+    assert(isArray() && "Invalid accessor");
+    assert(I < getArrayInitializedElts() && "Index out of range");
+    return ((Arr*)(char*)Data)->Elts[I];
+  }
+  const APValue &getArrayInitializedElt(unsigned I) const {
+    return const_cast<APValue*>(this)->getArrayInitializedElt(I);
+  }
+  bool hasArrayFiller() const {
+    return getArrayInitializedElts() !=3D getArraySize();
+  }
+  APValue &getArrayFiller() {
+    assert(isArray() && "Invalid accessor");
+    assert(hasArrayFiller() && "No array filler");
+    return ((Arr*)(char*)Data)->Elts[getArrayInitializedElts()];
+  }
+  const APValue &getArrayFiller() const {
+    return const_cast<APValue*>(this)->getArrayFiller();
+  }
+  unsigned getArrayInitializedElts() const {
+    assert(isArray() && "Invalid accessor");
+    return ((const Arr*)(const void *)Data)->NumElts;
+  }
+  unsigned getArraySize() const {
+    assert(isArray() && "Invalid accessor");
+    return ((const Arr*)(const void *)Data)->ArrSize;
+  }
+
+  unsigned getStructNumBases() const {
+    assert(isStruct() && "Invalid accessor");
+    return ((const StructData*)(const char*)Data)->NumBases;
+  }
+  unsigned getStructNumFields() const {
+    assert(isStruct() && "Invalid accessor");
+    return ((const StructData*)(const char*)Data)->NumFields;
+  }
+  APValue &getStructBase(unsigned i) {
+    assert(isStruct() && "Invalid accessor");
+    return ((StructData*)(char*)Data)->Elts[i];
+  }
+  APValue &getStructField(unsigned i) {
+    assert(isStruct() && "Invalid accessor");
+    return ((StructData*)(char*)Data)->Elts[getStructNumBases() + i];
+  }
+  const APValue &getStructBase(unsigned i) const {
+    return const_cast<APValue*>(this)->getStructBase(i);
+  }
+  const APValue &getStructField(unsigned i) const {
+    return const_cast<APValue*>(this)->getStructField(i);
+  }
+
+  const FieldDecl *getUnionField() const {
+    assert(isUnion() && "Invalid accessor");
+    return ((const UnionData*)(const char*)Data)->Field;
+  }
+  APValue &getUnionValue() {
+    assert(isUnion() && "Invalid accessor");
+    return *((UnionData*)(char*)Data)->Value;
+  }
+  const APValue &getUnionValue() const {
+    return const_cast<APValue*>(this)->getUnionValue();
+  }
+
+  const ValueDecl *getMemberPointerDecl() const;
+  bool isMemberPointerToDerivedMember() const;
+  ArrayRef<const CXXRecordDecl*> getMemberPointerPath() const;
+
+  const AddrLabelExpr* getAddrLabelDiffLHS() const {
+    assert(isAddrLabelDiff() && "Invalid accessor");
+    return ((const AddrLabelDiffData*)(const char*)Data)->LHSExpr;
+  }
+  const AddrLabelExpr* getAddrLabelDiffRHS() const {
+    assert(isAddrLabelDiff() && "Invalid accessor");
+    return ((const AddrLabelDiffData*)(const char*)Data)->RHSExpr;
+  }
=20
   void setInt(const APSInt &I) {
     assert(isInt() && "Invalid accessor");
@@ -201,12 +367,34 @@
     ((ComplexAPFloat*)(char*)Data)->Real =3D R;
     ((ComplexAPFloat*)(char*)Data)->Imag =3D I;
   }
-  void setLValue(const Expr *B, const CharUnits &O);
+  void setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
+                 unsigned CallIndex);
+  void setLValue(LValueBase B, const CharUnits &O,
+                 ArrayRef<LValuePathEntry> Path, bool OnePastTheEnd,
+                 unsigned CallIndex);
+  void setUnion(const FieldDecl *Field, const APValue &Value) {
+    assert(isUnion() && "Invalid accessor");
+    ((UnionData*)(char*)Data)->Field =3D Field;
+    *((UnionData*)(char*)Data)->Value =3D Value;
+  }
+  void setAddrLabelDiff(const AddrLabelExpr* LHSExpr,
+                        const AddrLabelExpr* RHSExpr) {
+    ((AddrLabelDiffData*)(char*)Data)->LHSExpr =3D LHSExpr;
+    ((AddrLabelDiffData*)(char*)Data)->RHSExpr =3D RHSExpr;
+  }
=20
-  const APValue &operator=3D(const APValue &RHS);
+  /// Assign by swapping from a copy of the RHS.
+  APValue &operator=3D(APValue RHS) {
+    swap(RHS);
+    return *this;
+  }
=20
 private:
-  void MakeUninit();
+  void DestroyDataAndMakeUninit();
+  void MakeUninit() {
+    if (Kind !=3D Uninitialized)
+      DestroyDataAndMakeUninit();
+  }
   void MakeInt() {
     assert(isUninit() && "Bad state change");
     new ((void*)Data) APSInt(1);
@@ -233,17 +421,26 @@
     Kind =3D ComplexFloat;
   }
   void MakeLValue();
+  void MakeArray(unsigned InitElts, unsigned Size);
+  void MakeStruct(unsigned B, unsigned M) {
+    assert(isUninit() && "Bad state change");
+    new ((void*)(char*)Data) StructData(B, M);
+    Kind =3D Struct;
+  }
+  void MakeUnion() {
+    assert(isUninit() && "Bad state change");
+    new ((void*)(char*)Data) UnionData();
+    Kind =3D Union;
+  }
+  void MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
+                         ArrayRef<const CXXRecordDecl*> Path);
+  void MakeAddrLabelDiff() {
+    assert(isUninit() && "Bad state change");
+    new ((void*)(char*)Data) AddrLabelDiffData();
+    Kind =3D AddrLabelDiff;
+  }
 };
=20
-inline raw_ostream &operator<<(raw_ostream &OS, const APValue &V) {
-  V.print(OS);
-  return OS;
-}
-
-// Writes a concise representation of V to DB, in a single << operation.
-const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
-                                    const APValue &V);
-
 } // end namespace clang.
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ASTConsumer.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ASTConsumer.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ASTConsumer.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -24,6 +24,7 @@
   class SemaConsumer; // layering violation required for safe SemaConsumer
   class TagDecl;
   class VarDecl;
+  class FunctionDecl;
=20
 /// ASTConsumer - This is an abstract interface that should be implemented=
 by
 /// clients that read ASTs.  This abstraction layer allows the client to be
@@ -48,7 +49,9 @@
   /// called by the parser to process every top-level Decl*. Note that D c=
an be
   /// the head of a chain of Decls (e.g. for `int a, b` the chain will hav=
e two
   /// elements). Use Decl::getNextDeclarator() to walk the chain.
-  virtual void HandleTopLevelDecl(DeclGroupRef D);
+  ///
+  /// \returns true to continue parsing, or false to abort parsing.
+  virtual bool HandleTopLevelDecl(DeclGroupRef D);
=20
   /// HandleInterestingDecl - Handle the specified interesting declaration=
. This
   /// is called by the AST reader when deserializing things that might int=
erest
@@ -65,6 +68,17 @@
   /// can be defined in declspecs).
   virtual void HandleTagDeclDefinition(TagDecl *D) {}
=20
+  /// \brief Invoked when a function is implicitly instantiated.
+  /// Note that at this point point it does not have a body, its body is
+  /// instantiated at the end of the translation unit and passed to
+  /// HandleTopLevelDecl.
+  virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D) {}
+
+  /// \brief Handle the specified top-level declaration that occurred insi=
de
+  /// and ObjC container.
+  /// The default implementation ignored them.
+  virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D);
+
   /// CompleteTentativeDefinition - Callback invoked at the end of a trans=
lation
   /// unit to notify the consumer that the given tentative definition shou=
ld be
   /// completed.
@@ -76,6 +90,10 @@
   /// modified by the introduction of an implicit zero initializer.
   virtual void CompleteTentativeDefinition(VarDecl *D) {}
=20
+  /// HandleCXXStaticMemberVarInstantiation - Tell the consumer that this
+  // variable has been instantiated.
+  virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D) {}
+
   /// \brief Callback involved at the end of a translation unit to
   /// notify the consumer that a vtable for the given C++ class is
   /// required.
@@ -94,7 +112,9 @@
=20
   /// \brief If the consumer is interested in entities being deserialized =
from
   /// AST files, it should return a pointer to a ASTDeserializationListene=
r here
-  virtual ASTDeserializationListener *GetASTDeserializationListener() { re=
turn 0; }
+  virtual ASTDeserializationListener *GetASTDeserializationListener() {
+    return 0;
+  }
=20
   /// PrintStats - If desired, print any statistics.
   virtual void PrintStats() {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ASTContext.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ASTContext.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ASTContext.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -21,17 +21,18 @@
 #include "clang/Basic/PartialDiagnostic.h"
 #include "clang/Basic/VersionTuple.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/LambdaMangleContext.h"
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "clang/AST/TemplateName.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/CanonicalType.h"
-#include "clang/AST/UsuallyTinyPtrVector.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/Support/Allocator.h"
 #include <vector>
=20
@@ -55,6 +56,7 @@
   class CXXABI;
   // Decls
   class DeclContext;
+  class CXXConversionDecl;
   class CXXMethodDecl;
   class CXXRecordDecl;
   class Decl;
@@ -80,7 +82,7 @@
=20
 /// ASTContext - This class holds long-lived AST nodes (such as types and
 /// decls) that can be referred to throughout the semantic analysis of a f=
ile.
-class ASTContext : public llvm::RefCountedBase<ASTContext> {
+class ASTContext : public RefCountedBase<ASTContext> {
   ASTContext &this_() { return *this; }
=20
   mutable std::vector<Type*> Types;
@@ -145,6 +147,11 @@
   mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
     ObjCLayouts;
=20
+  /// TypeInfoMap - A cache from types to size and alignment information.
+  typedef llvm::DenseMap<const Type*,
+                         std::pair<uint64_t, unsigned> > TypeInfoMap;
+  mutable TypeInfoMap MemoizedTypeInfo;
+
   /// KeyFunctions - A cache mapping from CXXRecordDecls to key functions.
   llvm::DenseMap<const CXXRecordDecl*, const CXXMethodDecl*> KeyFunctions;
  =20
@@ -202,12 +209,12 @@
   /// \brief The typedef for the predefined 'SEL' type.
   mutable TypedefDecl *ObjCSelDecl;
=20
-  QualType ObjCProtoType;
-  const RecordType *ProtoStructType;
-
   /// \brief The typedef for the predefined 'Class' type.
   mutable TypedefDecl *ObjCClassDecl;
- =20
+
+  /// \brief The typedef for the predefined 'Protocol' class in Objective-=
C.
+  mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
+
   // Typedefs which may be provided defining the structure of Objective-C
   // pseudo-builtins
   QualType ObjCIdRedefinitionType;
@@ -216,6 +223,8 @@
=20
   QualType ObjCConstantStringType;
   mutable RecordDecl *CFConstantStringTypeDecl;
+ =20
+  QualType ObjCNSStringType;
=20
   /// \brief The typedef declaration for the Objective-C "instancetype" ty=
pe.
   TypedefDecl *ObjCInstanceTypeDecl;
@@ -318,15 +327,22 @@
   /// Since most C++ member functions aren't virtual and therefore
   /// don't override anything, we store the overridden functions in
   /// this map on the side rather than within the CXXMethodDecl structure.
-  typedef UsuallyTinyPtrVector<const CXXMethodDecl> CXXMethodVector;
+  typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
=20
+  /// \brief Mapping from each declaration context to its corresponding la=
mbda=20
+  /// mangling context.
+  llvm::DenseMap<const DeclContext *, LambdaMangleContext> LambdaMangleCon=
texts;
+ =20
   /// \brief Mapping that stores parameterIndex values for ParmVarDecls
   /// when that value exceeds the bitfield size of
   /// ParmVarDeclBits.ParameterIndex.
   typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
   ParameterIndexTable ParamIndices; =20
  =20
+  ImportDecl *FirstLocalImport;
+  ImportDecl *LastLocalImport;
+ =20
   TranslationUnitDecl *TUDecl;
=20
   /// SourceMgr - The associated SourceManager object.
@@ -346,7 +362,7 @@
   PartialDiagnostic::StorageAllocator DiagAllocator;
=20
   /// \brief The current C++ ABI.
-  llvm::OwningPtr<CXXABI> ABI;
+  OwningPtr<CXXABI> ABI;
   CXXABI *createCXXABI(const TargetInfo &T);
=20
   /// \brief The logical -> physical address space map.
@@ -355,7 +371,8 @@
   friend class ASTDeclReader;
   friend class ASTReader;
   friend class ASTWriter;
- =20
+  friend class CXXRecordDecl;
+
   const TargetInfo *Target;
   clang::PrintingPolicy PrintingPolicy;
  =20
@@ -364,7 +381,7 @@
   SelectorTable &Selectors;
   Builtin::Context &BuiltinInfo;
   mutable DeclarationNameTable DeclarationNames;
-  llvm::OwningPtr<ExternalASTSource> ExternalSource;
+  OwningPtr<ExternalASTSource> ExternalSource;
   ASTMutationListener *Listener;
=20
   clang::PrintingPolicy getPrintingPolicy() const { return PrintingPolicy;=
 }
@@ -394,7 +411,7 @@
=20
   const TargetInfo &getTargetInfo() const { return *Target; }
  =20
-  const LangOptions& getLangOptions() const { return LangOpts; }
+  const LangOptions& getLangOpts() const { return LangOpts; }
=20
   DiagnosticsEngine &getDiagnostics() const;
=20
@@ -468,7 +485,7 @@
                                   const FieldDecl *LastFD) const;
=20
   // Access to the set of methods overridden by the given C++ method.
-  typedef CXXMethodVector::iterator overridden_cxx_method_iterator;
+  typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
   overridden_cxx_method_iterator
   overridden_methods_begin(const CXXMethodDecl *Method) const;
=20
@@ -482,6 +499,56 @@
   void addOverriddenMethod(const CXXMethodDecl *Method,=20
                            const CXXMethodDecl *Overridden);
  =20
+  /// \brief Notify the AST context that a new import declaration has been
+  /// parsed or implicitly created within this translation unit.
+  void addedLocalImportDecl(ImportDecl *Import);
+
+  static ImportDecl *getNextLocalImport(ImportDecl *Import) {
+    return Import->NextLocalImport;
+  }
+ =20
+  /// \brief Iterator that visits import declarations.
+  class import_iterator {
+    ImportDecl *Import;
+   =20
+  public:
+    typedef ImportDecl               *value_type;
+    typedef ImportDecl               *reference;
+    typedef ImportDecl               *pointer;
+    typedef int                       difference_type;
+    typedef std::forward_iterator_tag iterator_category;
+   =20
+    import_iterator() : Import() { }
+    explicit import_iterator(ImportDecl *Import) : Import(Import) { }
+   =20
+    reference operator*() const { return Import; }
+    pointer operator->() const { return Import; }
+   =20
+    import_iterator &operator++() {
+      Import =3D ASTContext::getNextLocalImport(Import);
+      return *this;
+    }
+
+    import_iterator operator++(int) {
+      import_iterator Other(*this);
+      ++(*this);
+      return Other;
+    }
+   =20
+    friend bool operator=3D=3D(import_iterator X, import_iterator Y) {
+      return X.Import =3D=3D Y.Import;
+    }
+
+    friend bool operator!=3D(import_iterator X, import_iterator Y) {
+      return X.Import !=3D Y.Import;
+    }
+  };
+ =20
+  import_iterator local_import_begin() const {=20
+    return import_iterator(FirstLocalImport);=20
+  }
+  import_iterator local_import_end() const { return import_iterator(); }
+ =20
   TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
=20
=20
@@ -500,7 +567,9 @@
   CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
   CanQualType VoidPtrTy, NullPtrTy;
   CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
+  CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
   CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
+  CanQualType ObjCBuiltinBoolTy;
=20
   // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on de=
mand.
   mutable QualType AutoDeductTy;     // Deduction against 'auto'.
@@ -519,7 +588,7 @@
   /// The external AST source provides the ability to load parts of
   /// the abstract syntax tree as needed from some external storage,
   /// e.g., a precompiled header.
-  void setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source);
+  void setExternalSource(OwningPtr<ExternalASTSource> &Source);
=20
   /// \brief Retrieve a pointer to the external AST source associated
   /// with this AST context, if any.
@@ -800,7 +869,8 @@
   QualType getPackExpansionType(QualType Pattern,
                                 llvm::Optional<unsigned> NumExpansions);
=20
-  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const;
+  QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
+                                ObjCInterfaceDecl *PrevDecl =3D 0) const;
=20
   QualType getObjCObjectType(QualType Base,
                              ObjCProtocolDecl * const *Protocols,
@@ -815,7 +885,7 @@
   QualType getTypeOfType(QualType t) const;
=20
   /// getDecltypeType - C++0x decltype.
-  QualType getDecltypeType(Expr *e) const;
+  QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
=20
   /// getUnaryTransformType - unary type transforms
   QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingTyp=
e,
@@ -838,6 +908,14 @@
   /// in <stddef.h>. The sizeof operator requires this (C99 6.5.3.4p4).
   CanQualType getSizeType() const;
=20
+  /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5),
+  /// defined in <stdint.h>.
+  CanQualType getIntMaxType() const;
+
+  /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.=
5),
+  /// defined in <stdint.h>.
+  CanQualType getUIntMaxType() const;
+
   /// getWCharType - In C++, this returns the unique wchar_t type.  In C99=
, this
   /// returns a type compatible with the type defined in <stddef.h> as def=
ined
   /// by the target.
@@ -851,7 +929,7 @@
   /// Used when in C++, as a GCC extension.
   QualType getUnsignedWCharType() const;
=20
-  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
+  /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.1=
7)
   /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
   QualType getPointerDiffType() const;
=20
@@ -874,6 +952,14 @@
     return ObjCConstantStringType;
   }
=20
+  QualType getObjCNSStringType() const {
+    return ObjCNSStringType;
+  }
+ =20
+  void setObjCNSStringType(QualType T) {
+    ObjCNSStringType =3D T;
+  }
+ =20
   /// \brief Retrieve the type that 'id' has been defined to, which may be
   /// different from the built-in 'id' if 'id' has been typedef'd.
   QualType getObjCIdRedefinitionType() const {
@@ -972,7 +1058,7 @@
=20
   /// \brief The result type of logical operations, '<', '>', '!=3D', etc.
   QualType getLogicalOperationType() const {
-    return getLangOptions().CPlusPlus ? BoolTy : IntTy;
+    return getLangOpts().CPlusPlus ? BoolTy : IntTy;
   }
=20
   /// getObjCEncodingForType - Emit the ObjC type encoding for the
@@ -999,7 +1085,8 @@
   ///
   /// \returns true if an error occurred (e.g., because one of the paramet=
er
   /// types is incomplete), false otherwise.
-  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::strin=
g &S)
+  bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::strin=
g &S,
+                                    bool Extended =3D false)
     const;
=20
   /// getObjCEncodingForBlock - Return the encoded type for this block
@@ -1041,9 +1128,6 @@
     return getTypeDeclType(getObjCSelDecl());
   }
=20
-  void setObjCProtoType(QualType QT);
-  QualType getObjCProtoType() const { return ObjCProtoType; }
-
   /// \brief Retrieve the typedef declaration corresponding to the predefi=
ned
   /// Objective-C 'Class' type.
   TypedefDecl *getObjCClassDecl() const;
@@ -1055,6 +1139,15 @@
     return getTypeDeclType(getObjCClassDecl());
   }
=20
+  /// \brief Retrieve the Objective-C class declaration corresponding to=20
+  /// the predefined 'Protocol' class.
+  ObjCInterfaceDecl *getObjCProtocolDecl() const;
+ =20
+  /// \brief Retrieve the type of the Objective-C "Protocol" class.
+  QualType getObjCProtoType() const {
+    return getObjCInterfaceType(getObjCProtocolDecl());
+  }
+ =20
   void setBuiltinVaListType(QualType T);
   QualType getBuiltinVaListType() const { return BuiltinVaListType; }
=20
@@ -1064,6 +1157,11 @@
     return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
   }
=20
+  /// getQualifiedType - Un-split a SplitQualType.
+  QualType getQualifiedType(SplitQualType split) const {
+    return getQualifiedType(split.Ty, split.Quals);
+  }
+
   /// getQualifiedType - Returns a type with additional qualifiers.
   QualType getQualifiedType(QualType T, Qualifiers Qs) const {
     if (!Qs.hasNonFastQualifiers())
@@ -1127,6 +1225,7 @@
=20
 private:
   CanQualType getFromTargetType(unsigned Type) const;
+  std::pair<uint64_t, unsigned> getTypeInfoImpl(const Type *T) const;
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   //                         Type Predicates.
@@ -1230,7 +1329,8 @@
   const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl=
 *D)
     const;
=20
-  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS) const;
+  void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
+                        bool Simple =3D false) const;
=20
   /// getASTObjCImplementationLayout - Get or compute information about
   /// the layout of the specified Objective-C implementation. This may
@@ -1246,6 +1346,9 @@
   /// of class definition.
   const CXXMethodDecl *getKeyFunction(const CXXRecordDecl *RD);
=20
+  /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
+  uint64_t getFieldOffset(const ValueDecl *FD) const;
+
   bool isNearlyEmpty(const CXXRecordDecl *RD) const;
=20
   MangleContext *createMangleContext();
@@ -1282,7 +1385,7 @@
   CanQualType getCanonicalParamType(QualType T) const;
=20
   /// \brief Determine whether the given types are equivalent.
-  bool hasSameType(QualType T1, QualType T2) {
+  bool hasSameType(QualType T1, QualType T2) const {
     return getCanonicalType(T1) =3D=3D getCanonicalType(T2);
   }
=20
@@ -1302,7 +1405,7 @@
=20
   /// \brief Determine whether the given types are equivalent after
   /// cvr-qualifiers have been removed.
-  bool hasSameUnqualifiedType(QualType T1, QualType T2) {
+  bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
     return getCanonicalType(T1).getTypePtr() =3D=3D
            getCanonicalType(T2).getTypePtr();
   }
@@ -1590,6 +1693,8 @@
     return Res;
   }
=20
+  bool isSentinelNullExpr(const Expr *E);
+
   /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none e=
xists.
   ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
   /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none e=
xists.
@@ -1622,6 +1727,11 @@
                                   const ObjCMethodDecl *Redecl) {
     ObjCMethodRedecls[MD] =3D Redecl;
   }
+
+  /// \brief Returns the objc interface that \arg ND belongs to if it is a
+  /// objc method/property/ivar etc. that is part of an interface,
+  /// otherwise returns null.
+  ObjCInterfaceDecl *getObjContainingInterface(NamedDecl *ND) const;
  =20
   /// \brief Set the copy inialization expression of a block var decl.
   void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
@@ -1671,6 +1781,8 @@
   /// it is not used.
   bool DeclMustBeEmitted(const Decl *D);
=20
+  /// \brief Retrieve the lambda mangling number for a lambda expression.
+  unsigned getLambdaManglingNumber(CXXMethodDecl *CallOperator);
  =20
   /// \brief Used by ParmVarDecl to store on the side the
   /// index of the parameter when it exceeds the size of the normal bitfie=
ld.
@@ -1751,13 +1863,20 @@
                                   const FieldDecl *Field,
                                   bool OutermostType =3D false,
                                   bool EncodingProperty =3D false,
-                                  bool StructField =3D false) const;
+                                  bool StructField =3D false,
+                                  bool EncodeBlockParameters =3D false,
+                                  bool EncodeClassNames =3D false) const;
=20
   // Adds the encoding of the structure's members.
   void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
                                        const FieldDecl *Field,
                                        bool includeVBases =3D true) const;
-=20
+
+  // Adds the encoding of a method parameter or return type.
+  void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
+                                         QualType T, std::string& S,
+                                         bool Extended) const;
+
   const ASTRecordLayout &
   getObjCLayout(const ObjCInterfaceDecl *D,
                 const ObjCImplementationDecl *Impl) const;
@@ -1795,13 +1914,19 @@
 }  // end namespace clang
=20
 // operator new and delete aren't allowed inside namespaces.
-// The throw specifications are mandated by the standard.
+
 /// @brief Placement new for using the ASTContext's allocator.
 ///
 /// This placement form of operator new uses the ASTContext's allocator for
-/// obtaining memory. It is a non-throwing new, which means that it returns
-/// null on error. (If that is what the allocator does. The current does, =
so if
-/// this ever changes, this operator will have to be changed, too.)
+/// obtaining memory.
+///
+/// IMPORTANT: These are also declared in clang/AST/Attr.h! Any changes he=
re
+/// need to also be made there.
+///
+/// We intentionally avoid using a nothrow specification here so that the =
calls
+/// to this operator will not perform a null check on the result -- the
+/// underlying allocator never returns null pointers.
+///
 /// Usage looks like this (assuming there's an ASTContext 'Context' in sco=
pe):
 /// @code
 /// // Default alignment (8)
@@ -1819,7 +1944,7 @@
 ///                  allocator supports it).
 /// @return The allocated memory. Could be NULL.
 inline void *operator new(size_t Bytes, const clang::ASTContext &C,
-                          size_t Alignment) throw () {
+                          size_t Alignment) {
   return C.Allocate(Bytes, Alignment);
 }
 /// @brief Placement delete companion to the new above.
@@ -1828,14 +1953,17 @@
 /// invoking it directly; see the new operator for more details. This oper=
ator
 /// is called implicitly by the compiler if a placement new expression usi=
ng
 /// the ASTContext throws in the object constructor.
-inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t)
-              throw () {
+inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t)=
 {
   C.Deallocate(Ptr);
 }
=20
 /// This placement form of operator new[] uses the ASTContext's allocator =
for
-/// obtaining memory. It is a non-throwing new[], which means that it retu=
rns
-/// null on error.
+/// obtaining memory.
+///
+/// We intentionally avoid using a nothrow specification here so that the =
calls
+/// to this operator will not perform a null check on the result -- the
+/// underlying allocator never returns null pointers.
+///
 /// Usage looks like this (assuming there's an ASTContext 'Context' in sco=
pe):
 /// @code
 /// // Default alignment (8)
@@ -1853,7 +1981,7 @@
 ///                  allocator supports it).
 /// @return The allocated memory. Could be NULL.
 inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
-                            size_t Alignment =3D 8) throw () {
+                            size_t Alignment =3D 8) {
   return C.Allocate(Bytes, Alignment);
 }
=20
@@ -1863,8 +1991,7 @@
 /// invoking it directly; see the new[] operator for more details. This op=
erator
 /// is called implicitly by the compiler if a placement new[] expression u=
sing
 /// the ASTContext throws in the object constructor.
-inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_=
t)
-              throw () {
+inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_=
t) {
   C.Deallocate(Ptr);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ASTDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ASTDiagnostic.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ASTDiagnostic.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
   namespace diag {
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
 #define ASTSTART
 #include "clang/Basic/DiagnosticASTKinds.inc"
 #undef DIAG
@@ -44,7 +44,7 @@
       unsigned NumPrevArgs,
       SmallVectorImpl<char> &Output,
       void *Cookie,
-      SmallVectorImpl<intptr_t> &QualTypeVals);
+      ArrayRef<intptr_t> QualTypeVals);
 }  // end namespace clang
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ASTImporter.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ASTImporter.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ASTImporter.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -255,6 +255,12 @@
    =20
     /// \brief Return the set of declarations that we know are not equival=
ent.
     NonEquivalentDeclSet &getNonEquivalentDecls() { return NonEquivalentDe=
cls; }
+
+    /// \brief Called for ObjCInterfaceDecl, ObjCProtocolDecl, and TagDecl.
+    /// Mark the Decl as complete, filling it in as much as possible.
+    ///
+    /// \param D A declaration in the "to" context.
+    virtual void CompleteDecl(Decl* D);
    =20
     /// \brief Note that we have imported the "from" declaration by mappin=
g it
     /// to the (potentially-newly-created) "to" declaration.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ASTMutationListener.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ASTMutationListener.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ASTMutationListener.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -24,6 +24,8 @@
   class FunctionTemplateDecl;
   class ObjCCategoryDecl;
   class ObjCInterfaceDecl;
+  class ObjCContainerDecl;
+  class ObjCPropertyDecl;
=20
 /// \brief An abstract interface that should be implemented by listeners
 /// that want to be notified when an AST entity gets modified after its
@@ -60,6 +62,21 @@
   /// \brief A new objc category class was added for an interface.
   virtual void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
                                             const ObjCInterfaceDecl *IFD) =
{}
+
+  /// \brief A objc class extension redeclared or introduced a property.
+  ///
+  /// \param Prop the property in the class extension
+  ///
+  /// \param OrigProp the property from the original interface that was de=
clared
+  /// or null if the property was introduced.
+  ///
+  /// \param ClassExt the class extension.
+  virtual void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *P=
rop,
+                                            const ObjCPropertyDecl *OrigPr=
op,
+                                            const ObjCCategoryDecl *ClassE=
xt) {}
+
+  // NOTE: If new methods are added they should also be added to
+  // MultiplexASTMutationListener.
 };
=20
 } // end namespace clang
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/Attr.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/Attr.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/Attr.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -23,6 +23,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/raw_ostream.h"
 #include <cassert>
 #include <cstring>
 #include <algorithm>
@@ -39,19 +40,17 @@
=20
 // Defined in ASTContext.h
 void *operator new(size_t Bytes, const clang::ASTContext &C,
-                   size_t Alignment =3D 16) throw ();
+                   size_t Alignment =3D 16);
 // FIXME: Being forced to not have a default argument here due to redeclar=
ation
 //        rules on default arguments sucks
 void *operator new[](size_t Bytes, const clang::ASTContext &C,
-                     size_t Alignment) throw ();
+                     size_t Alignment);
=20
 // It is good practice to pair new/delete operators.  Also, MSVC gives many
 // warnings if a matching delete overload is not declared, even though the
 // throw() spec guarantees it will not be implicitly called.
-void operator delete(void *Ptr, const clang::ASTContext &C, size_t)
-              throw ();
-void operator delete[](void *Ptr, const clang::ASTContext &C, size_t)
-              throw ();
+void operator delete(void *Ptr, const clang::ASTContext &C, size_t);
+void operator delete[](void *Ptr, const clang::ASTContext &C, size_t);
=20
 namespace clang {
=20
@@ -103,11 +102,17 @@
   // Clone this attribute.
   virtual Attr* clone(ASTContext &C) const =3D 0;
=20
+  virtual bool isLateParsed() const { return false; }
+
+  // Pretty print this attribute.
+  virtual void printPretty(llvm::raw_ostream &OS, ASTContext &C) const =3D=
 0;
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Attr *) { return true; }
 };
=20
 class InheritableAttr : public Attr {
+  virtual void anchor();
 protected:
   InheritableAttr(attr::Kind AK, SourceRange R)
     : Attr(AK, R) {}
@@ -123,6 +128,7 @@
 };
=20
 class InheritableParamAttr : public InheritableAttr {
+  virtual void anchor();
 protected:
   InheritableParamAttr(attr::Kind AK, SourceRange R)
     : InheritableAttr(AK, R) {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/CanonicalType.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/CanonicalType.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/CanonicalType.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -108,6 +108,8 @@
   /// or a derived class thereof, a NULL canonical type.
   template<typename U> CanProxy<U> getAs() const;
=20
+  template<typename U> CanProxy<U> castAs() const;
+
   /// \brief Overloaded arrow operator that produces a canonical type
   /// proxy.
   CanProxy<T> operator->() const;
@@ -753,6 +755,13 @@
 }
=20
 template<typename T>
+template<typename U>
+CanProxy<U> CanQual<T>::castAs() const {
+  assert(!Stored.isNull() && isa<U>(Stored.getTypePtr()));
+  return CanQual<U>::CreateUnsafe(Stored);
+}
+
+template<typename T>
 CanProxy<T> CanQual<T>::operator->() const {
   return CanProxy<T>(*this);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/Decl.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/Decl.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/Decl.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -22,6 +22,7 @@
 #include "clang/Basic/Linkage.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
 class CXXTemporary;
@@ -40,7 +41,8 @@
 class TypeLoc;
 class UnresolvedSetImpl;
 class LabelStmt;
-
+class Module;
+ =20
 /// \brief A container of type source information.
 ///
 /// A client can read the relevant info using TypeLoc wrappers, e.g:
@@ -66,6 +68,7 @@
=20
 /// TranslationUnitDecl - The top declaration context.
 class TranslationUnitDecl : public Decl, public DeclContext {
+  virtual void anchor();
   ASTContext &Ctx;
=20
   /// The (most recently entered) anonymous namespace for this
@@ -98,11 +101,15 @@
 /// NamedDecl - This represents a decl with a name.  Many decls have names=
 such
 /// as ObjCMethodDecl, but not @class, etc.
 class NamedDecl : public Decl {
+  virtual void anchor();
   /// Name - The name of this declaration, which is typically a normal
   /// identifier but may also be a special kind of name (C++
   /// constructor, Objective-C selector, etc.)
   DeclarationName Name;
=20
+private:
+  NamedDecl *getUnderlyingDeclImpl();
+
 protected:
   NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
     : Decl(DK, DC, L), Name(N) { }
@@ -182,15 +189,11 @@
   /// \brief Determine whether this declaration has linkage.
   bool hasLinkage() const;
=20
-  /// \brief Whether this declaration was marked as being private to the
-  /// module in which it was defined.
-  bool isModulePrivate() const { return ModulePrivate; }
+  using Decl::isModulePrivate;
+  using Decl::setModulePrivate;
  =20
-  /// \brief Specify whether this declaration was marked as being private
-  /// to the module in which it was defined.
-  void setModulePrivate(bool MP =3D true) {
-    ModulePrivate =3D MP;
-  }
+  /// \brief Determine whether this declaration is hidden from name lookup.
+  bool isHidden() const { return Hidden; }
  =20
   /// \brief Determine whether this declaration is a C++ class member.
   bool isCXXClassMember() const {
@@ -206,8 +209,8 @@
     return DC->isRecord();
   }
=20
-  /// \brief Given that this declaration is a C++ class member,
-  /// determine whether it's an instance member of its class.
+  /// \brief Determine whether the given declaration is an instance member=
 of
+  /// a C++ class.
   bool isCXXInstanceMember() const;
=20
   class LinkageInfo {
@@ -249,26 +252,52 @@
       setLinkage(minLinkage(linkage(), L));
     }
     void mergeLinkage(LinkageInfo Other) {
-      setLinkage(minLinkage(linkage(), Other.linkage()));
+      mergeLinkage(Other.linkage());
     }
=20
-    void mergeVisibility(Visibility V) {
-      setVisibility(minVisibility(visibility(), V));
+    // Merge the visibility V giving preference to explicit ones.
+    // This is used, for example, when merging the visibility of a class
+    // down to one of its members. If the member has no explicit visibilit=
y,
+    // the class visibility wins.
+    void mergeVisibility(Visibility V, bool E =3D false) {
+      // If one has explicit visibility and the other doesn't, keep the
+      // explicit one.
+      if (visibilityExplicit() && !E)
+        return;
+      if (!visibilityExplicit() && E)
+        setVisibility(V, E);
+
+      // If both are explicit or both are implicit, keep the minimum.
+      setVisibility(minVisibility(visibility(), V), visibilityExplicit() |=
| E);
     }
-    void mergeVisibility(Visibility V, bool E) {
-      setVisibility(minVisibility(visibility(), V), visibilityExplicit() |=
| E);
+    // Merge the visibility V, keeping the most restrictive one.
+    // This is used for cases like merging the visibility of a template
+    // argument to an instantiation. If we already have a hidden class,
+    // no argument should give it default visibility.
+    void mergeVisibilityWithMin(Visibility V, bool E =3D false) {
+      // Never increase the visibility
+      if (visibility() < V)
+        return;
+
+      // If this visibility is explicit, keep it.
+      if (visibilityExplicit() && !E)
+        return;
+      setVisibility(V, E);
     }
     void mergeVisibility(LinkageInfo Other) {
       mergeVisibility(Other.visibility(), Other.visibilityExplicit());
     }
+    void mergeVisibilityWithMin(LinkageInfo Other) {
+      mergeVisibilityWithMin(Other.visibility(), Other.visibilityExplicit(=
));
+    }
=20
     void merge(LinkageInfo Other) {
       mergeLinkage(Other);
       mergeVisibility(Other);
     }
-    void merge(std::pair<Linkage,Visibility> LV) {
-      mergeLinkage(LV.first);
-      mergeVisibility(LV.second);
+    void mergeWithMin(LinkageInfo Other) {
+      mergeLinkage(Other);
+      mergeVisibilityWithMin(Other);
     }
=20
     friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) {
@@ -281,7 +310,9 @@
   Linkage getLinkage() const;
=20
   /// \brief Determines the visibility of this entity.
-  Visibility getVisibility() const { return getLinkageAndVisibility().visi=
bility(); }
+  Visibility getVisibility() const {
+    return getLinkageAndVisibility().visibility();
+  }
=20
   /// \brief Determines the linkage and visibility of this entity.
   LinkageInfo getLinkageAndVisibility() const;
@@ -291,12 +322,19 @@
   llvm::Optional<Visibility> getExplicitVisibility() const;
=20
   /// \brief Clear the linkage cache in response to a change
-  /// to the declaration.=20
+  /// to the declaration.
   void ClearLinkageCache();
=20
   /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
   /// the underlying named decl.
-  NamedDecl *getUnderlyingDecl();
+  NamedDecl *getUnderlyingDecl() {
+    // Fast-path the common case.
+    if (this->getKind() !=3D UsingShadow &&
+        this->getKind() !=3D ObjCCompatibleAlias)
+      return this;
+
+    return getUnderlyingDeclImpl();
+  }
   const NamedDecl *getUnderlyingDecl() const {
     return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
   }
@@ -317,6 +355,7 @@
 /// location of the statement.  For GNU local labels (__label__), the decl
 /// location is where the __label__ is.
 class LabelDecl : public NamedDecl {
+  virtual void anchor();
   LabelStmt *TheStmt;
   /// LocStart - For normal labels, this is the same as the main declarati=
on
   /// label, i.e., the location of the identifier; for GNU local labels,
@@ -333,14 +372,15 @@
   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
                            SourceLocation IdentL, IdentifierInfo *II,
                            SourceLocation GnuLabelL);
-
+  static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   LabelStmt *getStmt() const { return TheStmt; }
   void setStmt(LabelStmt *T) { TheStmt =3D T; }
=20
   bool isGnuLocal() const { return LocStart !=3D getLocation(); }
   void setLocStart(SourceLocation L) { LocStart =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LocStart, getLocation());
   }
=20
@@ -349,10 +389,12 @@
   static bool classof(const LabelDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D Label; }
 };
- =20
+
 /// NamespaceDecl - Represent a C++ namespace.
-class NamespaceDecl : public NamedDecl, public DeclContext {
-  bool IsInline : 1;
+class NamespaceDecl : public NamedDecl, public DeclContext,=20
+                      public Redeclarable<NamespaceDecl>=20
+{
+  virtual void anchor();
=20
   /// LocStart - The starting location of the source range, pointing
   /// to either the namespace or the inline keyword.
@@ -360,41 +402,40 @@
   /// RBraceLoc - The ending location of the source range.
   SourceLocation RBraceLoc;
=20
-  // For extended namespace definitions:
-  //
-  // namespace A { int x; }
-  // namespace A { int y; }
-  //
-  // there will be one NamespaceDecl for each declaration.
-  // NextNamespace points to the next extended declaration.
-  // OrigNamespace points to the original namespace declaration.
-  // OrigNamespace of the first namespace decl points to its anonymous nam=
espace
-  LazyDeclPtr NextNamespace;
-
-  /// \brief A pointer to either the original namespace definition for
-  /// this namespace (if the boolean value is false) or the anonymous
-  /// namespace that lives just inside this namespace (if the boolean
-  /// value is true).
-  ///
-  /// We can combine these two notions because the anonymous namespace
-  /// must only be stored in one of the namespace declarations (so all
-  /// of the namespace declarations can find it). We therefore choose
-  /// the original namespace declaration, since all of the namespace
-  /// declarations have a link directly to it; the original namespace
-  /// declaration itself only needs to know that it is the original
-  /// namespace declaration (which the boolean indicates).
-  llvm::PointerIntPair<NamespaceDecl *, 1, bool> OrigOrAnonNamespace;
-
-  NamespaceDecl(DeclContext *DC, SourceLocation StartLoc,
-                SourceLocation IdLoc, IdentifierInfo *Id)
-    : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
-      IsInline(false), LocStart(StartLoc), RBraceLoc(),
-      NextNamespace(), OrigOrAnonNamespace(0, true) { }
-
+  /// \brief A pointer to either the anonymous namespace that lives just i=
nside
+  /// this namespace or to the first namespace in the chain (the latter ca=
se
+  /// only when this is not the first in the chain), along with a=20
+  /// boolean value indicating whether this is an inline namespace.
+  llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndIn=
line;
+
+  NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc,
+                SourceLocation IdLoc, IdentifierInfo *Id,
+                NamespaceDecl *PrevDecl);
+ =20
+  typedef Redeclarable<NamespaceDecl> redeclarable_base;
+  virtual NamespaceDecl *getNextRedeclaration() {
+    return RedeclLink.getNext();
+  }
+  virtual NamespaceDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
+  }
+  virtual NamespaceDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
+  }
+ =20
 public:
   static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
-                               SourceLocation StartLoc,
-                               SourceLocation IdLoc, IdentifierInfo *Id);
+                               bool Inline, SourceLocation StartLoc,
+                               SourceLocation IdLoc, IdentifierInfo *Id,
+                               NamespaceDecl *PrevDecl);
+
+  static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+
+  typedef redeclarable_base::redecl_iterator redecl_iterator;
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
=20
   /// \brief Returns true if this is an anonymous namespace declaration.
   ///
@@ -411,67 +452,60 @@
=20
   /// \brief Returns true if this is an inline namespace declaration.
   bool isInline() const {
-    return IsInline;
+    return AnonOrFirstNamespaceAndInline.getInt();
   }
=20
   /// \brief Set whether this is an inline namespace declaration.
   void setInline(bool Inline) {
-    IsInline =3D Inline;
+    AnonOrFirstNamespaceAndInline.setInt(Inline);
   }
=20
-  /// \brief Return the next extended namespace declaration or null if the=
re
-  /// is none.
-  NamespaceDecl *getNextNamespace();
-  const NamespaceDecl *getNextNamespace() const {=20
-    return const_cast<NamespaceDecl *>(this)->getNextNamespace();
+  /// \brief Get the original (first) namespace declaration.
+  NamespaceDecl *getOriginalNamespace() {
+    if (isFirstDeclaration())
+      return this;
+
+    return AnonOrFirstNamespaceAndInline.getPointer();
   }
=20
-  /// \brief Set the next extended namespace declaration.
-  void setNextNamespace(NamespaceDecl *ND) { NextNamespace =3D ND; }
-
   /// \brief Get the original (first) namespace declaration.
-  NamespaceDecl *getOriginalNamespace() const {
-    if (OrigOrAnonNamespace.getInt())
-      return const_cast<NamespaceDecl *>(this);
-
-    return OrigOrAnonNamespace.getPointer();
+  const NamespaceDecl *getOriginalNamespace() const {
+    if (isFirstDeclaration())
+      return this;
+
+    return AnonOrFirstNamespaceAndInline.getPointer();
   }
=20
   /// \brief Return true if this declaration is an original (first) declar=
ation
   /// of the namespace. This is false for non-original (subsequent) namesp=
ace
   /// declarations and anonymous namespaces.
   bool isOriginalNamespace() const {
-    return getOriginalNamespace() =3D=3D this;
+    return isFirstDeclaration();
   }
=20
-  /// \brief Set the original (first) namespace declaration.
-  void setOriginalNamespace(NamespaceDecl *ND) {=20
-    if (ND !=3D this) {
-      OrigOrAnonNamespace.setPointer(ND);
-      OrigOrAnonNamespace.setInt(false);
-    }
+  /// \brief Retrieve the anonymous namespace nested inside this namespace,
+  /// if any.
+  NamespaceDecl *getAnonymousNamespace() const {
+    return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointe=
r();
   }
=20
-  NamespaceDecl *getAnonymousNamespace() const {
-    return getOriginalNamespace()->OrigOrAnonNamespace.getPointer();
+  void setAnonymousNamespace(NamespaceDecl *D) {
+    getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
   }
=20
-  void setAnonymousNamespace(NamespaceDecl *D) {
-    assert(!D || D->isAnonymousNamespace());
-    assert(!D || D->getParent()->getRedeclContext() =3D=3D this);
-    getOriginalNamespace()->OrigOrAnonNamespace.setPointer(D);
+  /// Retrieves the canonical declaration of this namespace.
+  NamespaceDecl *getCanonicalDecl() {
+    return getOriginalNamespace();
   }
-
-  virtual NamespaceDecl *getCanonicalDecl() { return getOriginalNamespace(=
); }
-  const NamespaceDecl *getCanonicalDecl() const {=20
-    return getOriginalNamespace();=20
+  const NamespaceDecl *getCanonicalDecl() const {
+    return getOriginalNamespace();
   }
-
-  virtual SourceRange getSourceRange() const {
+ =20
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LocStart, RBraceLoc);
   }
=20
-  SourceLocation getLocStart() const { return LocStart; }
+  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
   SourceLocation getRBraceLoc() const { return RBraceLoc; }
   void setLocStart(SourceLocation L) { LocStart =3D L; }
   void setRBraceLoc(SourceLocation L) { RBraceLoc =3D L; }
@@ -486,7 +520,7 @@
   static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
     return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
   }
- =20
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
 };
@@ -495,6 +529,7 @@
 /// an lvalue) a function (in which case it is a function designator) or
 /// an enum constant.
 class ValueDecl : public NamedDecl {
+  virtual void anchor();
   QualType DeclType;
=20
 protected:
@@ -505,6 +540,12 @@
   QualType getType() const { return DeclType; }
   void setType(QualType newType) { DeclType =3D newType; }
=20
+  /// \brief Determine whether this symbol is weakly-imported,
+  ///        or declared with the weak or weak-ref attr.
+  bool isWeak() const {
+    return hasAttr<WeakAttr>() || hasAttr<WeakRefAttr>() || isWeakImported=
();
+  }
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ValueDecl *D) { return true; }
@@ -537,7 +578,7 @@
   void setTemplateParameterListsInfo(ASTContext &Context,
                                      unsigned NumTPLists,
                                      TemplateParameterList **TPLists);
- =20
+
 private:
   // Copy constructor and copy assignment are disabled.
   QualifierInfo(const QualifierInfo&);
@@ -592,7 +633,10 @@
   /// range taking into account any outer template declarations.
   SourceLocation getOuterLocStart() const;
=20
-  virtual SourceRange getSourceRange() const;
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
+  SourceLocation getLocStart() const LLVM_READONLY {
+    return getOuterLocStart();
+  }
=20
   /// \brief Retrieve the nested-name-specifier that qualifies the name of=
 this
   /// declaration, if it was present in the source.
@@ -600,15 +644,15 @@
     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifie=
r()
                         : 0;
   }
- =20
-  /// \brief Retrieve the nested-name-specifier (with source-location=20
-  /// information) that qualifies the name of this declaration, if it was=20
+
+  /// \brief Retrieve the nested-name-specifier (with source-location
+  /// information) that qualifies the name of this declaration, if it was
   /// present in the source.
   NestedNameSpecifierLoc getQualifierLoc() const {
     return hasExtInfo() ? getExtInfo()->QualifierLoc
                         : NestedNameSpecifierLoc();
   }
- =20
+
   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
=20
   unsigned getNumTemplateParameterLists() const {
@@ -655,8 +699,9 @@
   /// integral constant expression.
   bool CheckingICE : 1;
=20
-  /// \brief Whether this statement is an integral constant
-  /// expression. Only valid if CheckedICE is true.
+  /// \brief Whether this statement is an integral constant expression,
+  /// or in C++11, whether the statement is a constant expression. Only
+  /// valid if CheckedICE is true.
   bool IsICE : 1;
=20
   Stmt *Value;
@@ -675,6 +720,13 @@
   /// It is illegal to call this function with SC =3D=3D None.
   static const char *getStorageClassSpecifierString(StorageClass SC);
=20
+  /// \brief Initialization styles.
+  enum InitializationStyle {
+    CInit,    ///< C-style initialization with assignment
+    CallInit, ///< Call-style initialization (C++98)
+    ListInit  ///< Direct list-initialization (C++11)
+  };
+
 protected:
   /// \brief Placeholder type used in Init to denote an unparsed C++ defau=
lt
   /// argument.
@@ -700,14 +752,15 @@
     unsigned SClass : 3;
     unsigned SClassAsWritten : 3;
     unsigned ThreadSpecified : 1;
-    unsigned HasCXXDirectInit : 1;
+    unsigned InitStyle : 2;
=20
     /// \brief Whether this variable is the exception variable in a C++ ca=
tch
     /// or an Objective-C @catch statement.
     unsigned ExceptionVar : 1;
- =20
+
     /// \brief Whether this local variable could be allocated in the return
-    /// slot of its function, enabling the named return value optimization=
 (NRVO).
+    /// slot of its function, enabling the named return value optimization
+    /// (NRVO).
     unsigned NRVOVariable : 1;
=20
     /// \brief Whether this variable is the for-range-declaration in a C++=
0x
@@ -721,14 +774,14 @@
     /// \brief Whether this variable is (C++0x) constexpr.
     unsigned IsConstexpr : 1;
   };
-  enum { NumVarDeclBits =3D 13 };
+  enum { NumVarDeclBits =3D 14 };
=20
   friend class ASTDeclReader;
   friend class StmtIteratorBase;
- =20
+
 protected:
   enum { NumParameterIndexBits =3D 8 };
- =20
+
   class ParmVarDeclBitfields {
     friend class ParmVarDecl;
     friend class ASTDeclReader;
@@ -749,7 +802,7 @@
     /// Otherwise, the number of function parameter scopes enclosing
     /// the function parameter scope in which this parameter was
     /// declared.
-    unsigned ScopeDepthOrObjCQuals : 8;
+    unsigned ScopeDepthOrObjCQuals : 7;
=20
     /// The number of parameters preceding this parameter in the
     /// function parameter scope in which it was declared.
@@ -777,22 +830,28 @@
=20
   typedef Redeclarable<VarDecl> redeclarable_base;
   virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
+  virtual VarDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
+  }
+  virtual VarDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
+  }
=20
 public:
   typedef redeclarable_base::redecl_iterator redecl_iterator;
-  redecl_iterator redecls_begin() const {
-    return redeclarable_base::redecls_begin();
-  }
-  redecl_iterator redecls_end() const {
-    return redeclarable_base::redecls_end();
-  }
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
=20
   static VarDecl *Create(ASTContext &C, DeclContext *DC,
                          SourceLocation StartLoc, SourceLocation IdLoc,
                          IdentifierInfo *Id, QualType T, TypeSourceInfo *T=
Info,
                          StorageClass S, StorageClass SCAsWritten);
=20
-  virtual SourceRange getSourceRange() const;
+  static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
=20
   StorageClass getStorageClass() const {
     return (StorageClass) VarDeclBits.SClass;
@@ -823,12 +882,12 @@
     return getStorageClass() >=3D SC_Auto;
   }
=20
-  /// isStaticLocal - Returns true if a variable with function scope is a=20
+  /// isStaticLocal - Returns true if a variable with function scope is a
   /// static local variable.
   bool isStaticLocal() const {
     return getStorageClass() =3D=3D SC_Static && !isFileVarDecl();
   }
- =20
+
   /// hasExternStorage - Returns true if a variable has extern or
   /// __private_extern__ storage.
   bool hasExternalStorage() const {
@@ -896,11 +955,17 @@
   /// \brief Check whether this declaration is a definition. If this could=
 be
   /// a tentative definition (in C), don't check whether there's an overri=
ding
   /// definition.
-  DefinitionKind isThisDeclarationADefinition() const;
+  DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
+  DefinitionKind isThisDeclarationADefinition() const {
+    return isThisDeclarationADefinition(getASTContext());
+  }
=20
   /// \brief Check whether this variable is defined in this
   /// translation unit.
-  DefinitionKind hasDefinition() const;
+  DefinitionKind hasDefinition(ASTContext &) const;
+  DefinitionKind hasDefinition() const {
+    return hasDefinition(getASTContext());
+  }
=20
   /// \brief Get the tentative definition that acts as the real definition=
 in
   /// a TU. Returns null if there is a proper definition available.
@@ -914,26 +979,32 @@
   bool isTentativeDefinitionNow() const;
=20
   /// \brief Get the real (not just tentative) definition for this declara=
tion.
-  VarDecl *getDefinition();
+  VarDecl *getDefinition(ASTContext &);
+  const VarDecl *getDefinition(ASTContext &C) const {
+    return const_cast<VarDecl*>(this)->getDefinition(C);
+  }
+  VarDecl *getDefinition() {
+    return getDefinition(getASTContext());
+  }
   const VarDecl *getDefinition() const {
     return const_cast<VarDecl*>(this)->getDefinition();
   }
=20
-  /// \brief Determine whether this is or was instantiated from an out-of-=
line=20
+  /// \brief Determine whether this is or was instantiated from an out-of-=
line
   /// definition of a static data member.
   virtual bool isOutOfLine() const;
=20
   /// \brief If this is a static data member, find its out-of-line definit=
ion.
   VarDecl *getOutOfLineDefinition();
- =20
+
   /// isFileVarDecl - Returns true for file scoped variable declaration.
   bool isFileVarDecl() const {
     if (getKind() !=3D Decl::Var)
       return false;
-   =20
+
     if (getDeclContext()->getRedeclContext()->isFileContext())
       return true;
-   =20
+
     if (isStaticDataMember())
       return true;
=20
@@ -996,7 +1067,7 @@
   void setInit(Expr *I);
=20
   /// \brief Determine whether this variable is a reference that
-  /// extends the lifetime of its temporary initializer.=20
+  /// extends the lifetime of its temporary initializer.
   ///
   /// A reference extends the lifetime of its temporary initializer if
   /// it's initializer is an rvalue that would normally go out of scope
@@ -1009,41 +1080,21 @@
   /// \endcode
   bool extendsLifetimeOfTemporary() const;
=20
-  EvaluatedStmt *EnsureEvaluatedStmt() const {
-    EvaluatedStmt *Eval =3D Init.dyn_cast<EvaluatedStmt *>();
-    if (!Eval) {
-      Stmt *S =3D Init.get<Stmt *>();
-      Eval =3D new (getASTContext()) EvaluatedStmt;
-      Eval->Value =3D S;
-      Init =3D Eval;
-    }
-    return Eval;
-  }
-
-  /// \brief Check whether we are in the process of checking whether the
-  /// initializer can be evaluated.
-  bool isEvaluatingValue() const {
-    if (EvaluatedStmt *Eval =3D Init.dyn_cast<EvaluatedStmt *>())
-      return Eval->IsEvaluating;
-
-    return false;
-  }
-
-  /// \brief Note that we now are checking whether the initializer can be
-  /// evaluated.
-  void setEvaluatingValue() const {
-    EvaluatedStmt *Eval =3D EnsureEvaluatedStmt();
-    Eval->IsEvaluating =3D true;
-  }
-
-  /// \brief Note that constant evaluation has computed the given
-  /// value for this variable's initializer.
-  void setEvaluatedValue(const APValue &Value) const {
-    EvaluatedStmt *Eval =3D EnsureEvaluatedStmt();
-    Eval->IsEvaluating =3D false;
-    Eval->WasEvaluated =3D true;
-    Eval->Evaluated =3D Value;
-  }
+  /// \brief Determine whether this variable's value can be used in a
+  /// constant expression, according to the relevant language standard.
+  /// This only checks properties of the declaration, and does not check
+  /// whether the initializer is in fact a constant expression.
+  bool isUsableInConstantExpressions(ASTContext &C) const;
+
+  EvaluatedStmt *ensureEvaluatedStmt() const;
+
+  /// \brief Attempt to evaluate the value of the initializer attached to =
this
+  /// declaration, and produce notes explaining why it cannot be evaluated=
 or is
+  /// not a constant expression. Returns a pointer to the value if evaluat=
ion
+  /// succeeded, 0 otherwise.
+  APValue *evaluateValue() const;
+  APValue *evaluateValue(
+    llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
=20
   /// \brief Return the already-evaluated value of this variable's
   /// initializer, or NULL if the value is not yet known. Returns pointer
@@ -1065,8 +1116,9 @@
     return false;
   }
=20
-  /// \brief Determines whether the initializer is an integral
-  /// constant expression.
+  /// \brief Determines whether the initializer is an integral constant
+  /// expression, or in C++11, whether the initializer is a constant
+  /// expression.
   ///
   /// \pre isInitKnownICE()
   bool isInitICE() const {
@@ -1075,41 +1127,31 @@
     return Init.get<EvaluatedStmt *>()->IsICE;
   }
=20
-  /// \brief Check whether we are in the process of checking the initializ=
er
-  /// is an integral constant expression.
-  bool isCheckingICE() const {
-    if (EvaluatedStmt *Eval =3D Init.dyn_cast<EvaluatedStmt *>())
-      return Eval->CheckingICE;
-
-    return false;
+  /// \brief Determine whether the value of the initializer attached to th=
is
+  /// declaration is an integral constant expression.
+  bool checkInitIsICE() const;
+
+  void setInitStyle(InitializationStyle Style) {
+    VarDeclBits.InitStyle =3D Style;
   }
=20
-  /// \brief Note that we now are checking whether the initializer is an
-  /// integral constant expression.
-  void setCheckingICE() const {
-    EvaluatedStmt *Eval =3D EnsureEvaluatedStmt();
-    Eval->CheckingICE =3D true;
+  /// \brief The style of initialization for this declaration.
+  ///
+  /// C-style initialization is "int x =3D 1;". Call-style initialization =
is
+  /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression wi=
ll be
+  /// the expression inside the parens or a "ClassType(a,b,c)" class const=
ructor
+  /// expression for class types. List-style initialization is C++11 synta=
x,
+  /// e.g. "int x{1};". Clients can distinguish between different forms of
+  /// initialization by checking this value. In particular, "int x =3D {1}=
;" is
+  /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; =
the
+  /// Init expression in all three cases is an InitListExpr.
+  InitializationStyle getInitStyle() const {
+    return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
   }
=20
-  /// \brief Note that we now know whether the initializer is an
-  /// integral constant expression.
-  void setInitKnownICE(bool IsICE) const {
-    EvaluatedStmt *Eval =3D EnsureEvaluatedStmt();
-    Eval->CheckingICE =3D false;
-    Eval->CheckedICE =3D true;
-    Eval->IsICE =3D IsICE;
-  }
-
-  void setCXXDirectInitializer(bool T) { VarDeclBits.HasCXXDirectInit =3D =
T; }
-
-  /// hasCXXDirectInitializer - If true, the initializer was a direct
-  /// initializer, e.g: "int x(1);". The Init expression will be the expre=
ssion
-  /// inside the parens or a "ClassType(a,b,c)" class constructor expressi=
on for
-  /// class types. Clients can distinguish between "int x(1);" and "int x=
=3D1;"
-  /// by checking hasCXXDirectInitializer.
-  ///
-  bool hasCXXDirectInitializer() const {
-    return VarDeclBits.HasCXXDirectInit;
+  /// \brief Whether the initializer is a direct-initializer (list or call=
).
+  bool isDirectInit() const {
+    return getInitStyle() !=3D CInit;
   }
=20
   /// \brief Determine whether this variable is the exception variable in a
@@ -1118,7 +1160,7 @@
     return VarDeclBits.ExceptionVar;
   }
   void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar =3D EV; }
- =20
+
   /// \brief Determine whether this local variable can be used with the na=
med
   /// return value optimization (NRVO).
   ///
@@ -1143,7 +1185,7 @@
   /// Generally such variables are also 'const' for safety.
   bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
   void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong =3D ps; }
- =20
+
   /// Whether this variable is (C++0x) constexpr.
   bool isConstexpr() const { return VarDeclBits.IsConstexpr; }
   void setConstexpr(bool IC) { VarDeclBits.IsConstexpr =3D IC; }
@@ -1153,15 +1195,15 @@
   /// from which it was instantiated.
   VarDecl *getInstantiatedFromStaticDataMember() const;
=20
-  /// \brief If this variable is a static data member, determine what kind=
 of=20
+  /// \brief If this variable is a static data member, determine what kind=
 of
   /// template specialization or instantiation this is.
   TemplateSpecializationKind getTemplateSpecializationKind() const;
- =20
+
   /// \brief If this variable is an instantiation of a static data member =
of a
   /// class template specialization, retrieves the member specialization
   /// information.
   MemberSpecializationInfo *getMemberSpecializationInfo() const;
- =20
+
   /// \brief For a static data member that was instantiated from a static
   /// data member of a class template, set the template specialiation kind.
   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
@@ -1174,11 +1216,14 @@
 };
=20
 class ImplicitParamDecl : public VarDecl {
+  virtual void anchor();
 public:
   static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
                                    SourceLocation IdLoc, IdentifierInfo *I=
d,
                                    QualType T);
=20
+  static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc,
                     IdentifierInfo *Id, QualType Type)
     : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type,
@@ -1218,8 +1263,10 @@
                              StorageClass S, StorageClass SCAsWritten,
                              Expr *DefArg);
=20
-  virtual SourceRange getSourceRange() const;
+  static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  =20
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
+
   void setObjCMethodScopeInfo(unsigned parameterIndex) {
     ParmVarDeclBits.IsObjCMethodParam =3D true;
     setParameterIndex(parameterIndex);
@@ -1229,7 +1276,8 @@
     assert(!ParmVarDeclBits.IsObjCMethodParam);
=20
     ParmVarDeclBits.ScopeDepthOrObjCQuals =3D scopeDepth;
-    assert(ParmVarDeclBits.ScopeDepthOrObjCQuals =3D=3D scopeDepth && "tru=
ncation!");
+    assert(ParmVarDeclBits.ScopeDepthOrObjCQuals =3D=3D scopeDepth
+           && "truncation!");
=20
     setParameterIndex(parameterIndex);
   }
@@ -1276,20 +1324,14 @@
   const Expr *getDefaultArg() const {
     return const_cast<ParmVarDecl *>(this)->getDefaultArg();
   }
- =20
+
   void setDefaultArg(Expr *defarg) {
     Init =3D reinterpret_cast<Stmt *>(defarg);
   }
=20
-  unsigned getNumDefaultArgTemporaries() const;
-  CXXTemporary *getDefaultArgTemporary(unsigned i);
-  const CXXTemporary *getDefaultArgTemporary(unsigned i) const {
-    return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i);
-  }
- =20
   /// \brief Retrieve the source range that covers the entire default
   /// argument.
-  SourceRange getDefaultArgRange() const; =20
+  SourceRange getDefaultArgRange() const;
   void setUninstantiatedDefaultArg(Expr *arg) {
     Init =3D reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
   }
@@ -1351,7 +1393,7 @@
   /// \brief Determine whether this parameter is actually a function
   /// parameter pack.
   bool isParameterPack() const;
- =20
+
   /// setOwningFunction - Sets the function declaration that owns this
   /// ParmVarDecl. Since ParmVarDecls are often created before the
   /// FunctionDecls that own them, this routine is required to update
@@ -1362,7 +1404,7 @@
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ParmVarDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D ParmVar; }
- =20
+
 private:
   enum { ParameterIndexSentinel =3D (1 << NumParameterIndexBits) - 1 };
=20
@@ -1371,7 +1413,7 @@
       setParameterIndexLarge(parameterIndex);
       return;
     }
-   =20
+
     ParmVarDeclBits.ParameterIndex =3D parameterIndex;
     assert(ParmVarDeclBits.ParameterIndex =3D=3D parameterIndex && "trunca=
tion!");
   }
@@ -1379,7 +1421,7 @@
     unsigned d =3D ParmVarDeclBits.ParameterIndex;
     return d =3D=3D ParameterIndexSentinel ? getParameterIndexLarge() : d;
   }
- =20
+
   void setParameterIndexLarge(unsigned parameterIndex);
   unsigned getParameterIndexLarge() const;
 };
@@ -1394,7 +1436,7 @@
 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
 /// contains all of the information known about the function. Other,
 /// previous declarations of the function are available via the
-/// getPreviousDeclaration() chain.
+/// getPreviousDecl() chain.
 class FunctionDecl : public DeclaratorDecl, public DeclContext,
                      public Redeclarable<FunctionDecl> {
 public:
@@ -1415,6 +1457,11 @@
   /// no formals.
   ParmVarDecl **ParamInfo;
=20
+  /// DeclsInPrototypeScope - Array of pointers to NamedDecls for
+  /// decls defined in the function prototype that are not parameters. E.g.
+  /// 'enum Y' in 'void f(enum Y {AA} x) {}'.
+  llvm::ArrayRef<NamedDecl*> DeclsInPrototypeScope;
+
   LazyDeclStmtPtr Body;
=20
   // FIXME: This can be packed into the bitfields in Decl.
@@ -1456,7 +1503,7 @@
   /// FunctionTemplateSpecializationInfo, which contains information about
   /// the template being specialized and the template arguments involved in
   /// that specialization.
-  llvm::PointerUnion4<FunctionTemplateDecl *,=20
+  llvm::PointerUnion4<FunctionTemplateDecl *,
                       MemberSpecializationInfo *,
                       FunctionTemplateSpecializationInfo *,
                       DependentFunctionTemplateSpecializationInfo *>
@@ -1486,7 +1533,7 @@
   /// \param TemplateArgsAsWritten location info of template arguments.
   ///
   /// \param PointOfInstantiation point at which the function template
-  /// specialization was first instantiated.=20
+  /// specialization was first instantiated.
   void setFunctionTemplateSpecialization(ASTContext &C,
                                          FunctionTemplateDecl *Template,
                                        const TemplateArgumentList *Templat=
eArgs,
@@ -1524,15 +1571,19 @@
=20
   typedef Redeclarable<FunctionDecl> redeclarable_base;
   virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext=
(); }
+  virtual FunctionDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
+  }
+  virtual FunctionDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
+  }
=20
 public:
   typedef redeclarable_base::redecl_iterator redecl_iterator;
-  redecl_iterator redecls_begin() const {
-    return redeclarable_base::redecls_begin();
-  }
-  redecl_iterator redecls_end() const {
-    return redeclarable_base::redecls_end();
-  }
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
=20
   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
                               SourceLocation StartLoc, SourceLocation NLoc,
@@ -1560,6 +1611,8 @@
                               bool hasWrittenPrototype =3D true,
                               bool isConstexprSpecified =3D false);
=20
+  static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+                      =20
   DeclarationNameInfo getNameInfo() const {
     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
   }
@@ -1570,7 +1623,7 @@
=20
   void setRangeEnd(SourceLocation E) { EndRangeLoc =3D E; }
=20
-  virtual SourceRange getSourceRange() const;
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
=20
   /// \brief Returns true if the function has a body (definition). The
   /// function body might be in any of the (re-)declarations of this
@@ -1656,7 +1709,7 @@
   void setTrivial(bool IT) { IsTrivial =3D IT; }
=20
   /// Whether this function is defaulted per C++0x. Only valid for
-  /// special member functions.=20
+  /// special member functions.
   bool isDefaulted() const { return IsDefaulted; }
   void setDefaulted(bool D =3D true) { IsDefaulted =3D D; }
=20
@@ -1774,6 +1827,11 @@
     setParams(getASTContext(), NewParamInfo);
   }
=20
+  const llvm::ArrayRef<NamedDecl*> &getDeclsInPrototypeScope() const {
+    return DeclsInPrototypeScope;
+  }
+  void setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls);
+
   /// getMinRequiredArguments - Returns the minimum number of arguments
   /// needed to call this function. This may be fewer than the number of
   /// function parameters, if some of the parameters have default
@@ -1783,12 +1841,12 @@
   QualType getResultType() const {
     return getType()->getAs<FunctionType>()->getResultType();
   }
- =20
+
   /// \brief Determine the type of an expression that calls this function.
   QualType getCallResultType() const {
     return getType()->getAs<FunctionType>()->getCallResultType(getASTConte=
xt());
   }
-                      =20
+
   StorageClass getStorageClass() const { return StorageClass(SClass); }
   void setStorageClass(StorageClass SC);
=20
@@ -1799,10 +1857,10 @@
   /// \brief Determine whether the "inline" keyword was specified for this
   /// function.
   bool isInlineSpecified() const { return IsInlineSpecified; }
-                      =20
+
   /// Set whether the "inline" keyword was specified for this function.
-  void setInlineSpecified(bool I) {=20
-    IsInlineSpecified =3D I;=20
+  void setInlineSpecified(bool I) {
+    IsInlineSpecified =3D I;
     IsInline =3D I;
   }
=20
@@ -1819,7 +1877,7 @@
   bool isInlineDefinitionExternallyVisible() const;
=20
   bool doesDeclarationForceExternallyVisibleDefinition() const;
-                      =20
+
   /// isOverloadedOperator - Whether this function declaration
   /// represents an C++ overloaded operator, e.g., "operator+".
   bool isOverloadedOperator() const {
@@ -1852,7 +1910,7 @@
   /// X<int>::A is required, it will be instantiated from the
   /// declaration returned by getInstantiatedFromMemberFunction().
   FunctionDecl *getInstantiatedFromMemberFunction() const;
- =20
+
   /// \brief What kind of templated function this is.
   TemplatedKind getTemplatedKind() const;
=20
@@ -1860,7 +1918,7 @@
   /// class template specialization, retrieves the member specialization
   /// information.
   MemberSpecializationInfo *getMemberSpecializationInfo() const;
-                      =20
+
   /// \brief Specify that this record is an instantiation of the
   /// member function FD.
   void setInstantiationOfMemberFunction(FunctionDecl *FD,
@@ -1888,7 +1946,7 @@
     TemplateOrSpecialization =3D Template;
   }
=20
-  /// \brief Determine whether this function is a function template=20
+  /// \brief Determine whether this function is a function template
   /// specialization.
   bool isFunctionTemplateSpecialization() const {
     return getPrimaryTemplate() !=3D 0;
@@ -1899,7 +1957,7 @@
   FunctionDecl *getClassScopeSpecializationPattern() const;
=20
   /// \brief If this function is actually a function template specializati=
on,
-  /// retrieve information about this function template specialization.=20
+  /// retrieve information about this function template specialization.
   /// Otherwise, returns NULL.
   FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() cons=
t {
     return TemplateOrSpecialization.
@@ -1910,7 +1968,11 @@
   /// specialization or a member of a class template specialization that c=
an
   /// be implicitly instantiated.
   bool isImplicitlyInstantiable() const;
-             =20
+
+  /// \brief Determines if the given function was instantiated from a
+  /// function template.
+  bool isTemplateInstantiation() const;
+
   /// \brief Retrieve the function declaration from which this function co=
uld
   /// be instantiated, if it is an instantiation (rather than a non-templa=
te
   /// or a specialization, for example).
@@ -1958,7 +2020,7 @@
   /// \param TemplateArgsAsWritten location info of template arguments.
   ///
   /// \param PointOfInstantiation point at which the function template
-  /// specialization was first instantiated.=20
+  /// specialization was first instantiated.
   void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
                                       const TemplateArgumentList *Template=
Args,
                                          void *InsertPos,
@@ -1994,15 +2056,21 @@
   /// \brief Retrieve the (first) point of instantiation of a function tem=
plate
   /// specialization or a member of a class template specialization.
   ///
-  /// \returns the first point of instantiation, if this function was=20
-  /// instantiated from a template; otherwise, returns an invalid source=20
+  /// \returns the first point of instantiation, if this function was
+  /// instantiated from a template; otherwise, returns an invalid source
   /// location.
   SourceLocation getPointOfInstantiation() const;
-                      =20
-  /// \brief Determine whether this is or was instantiated from an out-of-=
line=20
+
+  /// \brief Determine whether this is or was instantiated from an out-of-=
line
   /// definition of a member function.
   virtual bool isOutOfLine() const;
-                      =20
+
+  /// \brief Identify a memory copying or setting function.
+  /// If the given function is a memory copy or setting function, returns
+  /// the corresponding Builtin ID. If the function is not a memory functi=
on,
+  /// returns 0.
+  unsigned getMemoryFunctionKind() const;
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const FunctionDecl *D) { return true; }
@@ -2056,6 +2124,8 @@
                            TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
                            bool HasInit);
=20
+  static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   /// getFieldIndex - Returns the index of this field within its record,
   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
   unsigned getFieldIndex() const;
@@ -2108,7 +2178,8 @@
   Expr *getInClassInitializer() const {
     return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : =
0;
   }
-  /// setInClassInitializer - Set the C++0x in-class initializer for this =
member.
+  /// setInClassInitializer - Set the C++0x in-class initializer for this
+  /// member.
   void setInClassInitializer(Expr *Init);
   /// removeInClassInitializer - Remove the C++0x in-class initializer fro=
m this
   /// member.
@@ -2128,7 +2199,7 @@
     return cast<RecordDecl>(getDeclContext());
   }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -2155,7 +2226,8 @@
                                   SourceLocation L, IdentifierInfo *Id,
                                   QualType T, Expr *E,
                                   const llvm::APSInt &V);
-
+  static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   const Expr *getInitExpr() const { return (const Expr*) Init; }
   Expr *getInitExpr() { return (Expr*) Init; }
   const llvm::APSInt &getInitVal() const { return Val; }
@@ -2163,8 +2235,8 @@
   void setInitExpr(Expr *E) { Init =3D (Stmt*) E; }
   void setInitVal(const llvm::APSInt &V) { Val =3D V; }
=20
-  SourceRange getSourceRange() const;
- =20
+  SourceRange getSourceRange() const LLVM_READONLY;
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const EnumConstantDecl *D) { return true; }
@@ -2177,6 +2249,7 @@
 /// field injected from an anonymous union/struct into the parent scope.
 /// IndirectFieldDecl are always implicit.
 class IndirectFieldDecl : public ValueDecl {
+  virtual void anchor();
   NamedDecl **Chaining;
   unsigned ChainingSize;
=20
@@ -2189,6 +2262,8 @@
   static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
                                    SourceLocation L, IdentifierInfo *Id,
                                    QualType T, NamedDecl **CH, unsigned CH=
S);
+
+  static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  =20
   typedef NamedDecl * const *chain_iterator;
   chain_iterator chain_begin() const { return Chaining; }
@@ -2216,6 +2291,7 @@
 /// TypeDecl - Represents a declaration of a type.
 ///
 class TypeDecl : public NamedDecl {
+  virtual void anchor();
   /// TypeForDecl - This indicates the Type object that represents
   /// this TypeDecl.  It is a cache maintained by
   /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
@@ -2228,6 +2304,7 @@
   friend class TagDecl;
   friend class TemplateTypeParmDecl;
   friend class TagType;
+  friend class ASTReader;
=20
 protected:
   TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
@@ -2239,9 +2316,9 @@
   const Type *getTypeForDecl() const { return TypeForDecl; }
   void setTypeForDecl(const Type *TD) { TypeForDecl =3D TD; }
=20
-  SourceLocation getLocStart() const { return LocStart; }
+  SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
   void setLocStart(SourceLocation L) { LocStart =3D L; }
-  virtual SourceRange getSourceRange() const {
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
     if (LocStart.isValid())
       return SourceRange(LocStart, getLocation());
     else
@@ -2257,6 +2334,7 @@
=20
 /// Base class for declarations which introduce a typedef-name.
 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDe=
cl> {
+  virtual void anchor();
   /// UnderlyingType - This is the type the typedef is set to.
   TypeSourceInfo *TInfo;
=20
@@ -2270,15 +2348,19 @@
   virtual TypedefNameDecl *getNextRedeclaration() {
     return RedeclLink.getNext();
   }
+  virtual TypedefNameDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
+  }
+  virtual TypedefNameDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
+  }
=20
 public:
   typedef redeclarable_base::redecl_iterator redecl_iterator;
-  redecl_iterator redecls_begin() const {
-    return redeclarable_base::redecls_begin();
-  }
-  redecl_iterator redecls_end() const {
-    return redeclarable_base::redecls_end();
-  }
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
=20
   TypeSourceInfo *getTypeSourceInfo() const {
     return TInfo;
@@ -2318,8 +2400,9 @@
   static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
                              SourceLocation StartLoc, SourceLocation IdLoc,
                              IdentifierInfo *Id, TypeSourceInfo *TInfo);
-
-  SourceRange getSourceRange() const;
+  static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -2338,8 +2421,9 @@
   static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
                                SourceLocation StartLoc, SourceLocation IdL=
oc,
                                IdentifierInfo *Id, TypeSourceInfo *TInfo);
-
-  SourceRange getSourceRange() const;
+  static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -2364,15 +2448,17 @@
   /// a definition until the definition has been fully processed.
   bool IsCompleteDefinition : 1;
=20
+protected:
   /// IsBeingDefined - True if this is currently being defined.
   bool IsBeingDefined : 1;
=20
+private:
   /// IsEmbeddedInDeclarator - True if this tag declaration is
   /// "embedded" (i.e., defined or declared for the very first time)
   /// in the syntax of a declarator.
   bool IsEmbeddedInDeclarator : 1;
=20
-  /// /brief True if this tag is free standing, e.g. "struct foo;".
+  /// \brief True if this tag is free standing, e.g. "struct foo;".
   bool IsFreeStanding : 1;
=20
 protected:
@@ -2381,7 +2467,7 @@
   unsigned NumNegativeBits : 8;
=20
   /// IsScoped - True if this tag declaration is a scoped enumeration. Only
-  /// possible in C++0x mode.
+  /// possible in C++11 mode.
   bool IsScoped : 1;
   /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
   /// then this is true if the scoped enum was declared using the class
@@ -2390,7 +2476,7 @@
   bool IsScopedUsingClassTag : 1;
=20
   /// IsFixed - True if this is an enumeration with fixed underlying type.=
 Only
-  /// possible in C++0x mode.
+  /// possible in C++11 or Microsoft extensions mode.
   bool IsFixed : 1;
=20
 private:
@@ -2431,20 +2517,24 @@
=20
   typedef Redeclarable<TagDecl> redeclarable_base;
   virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); }
+  virtual TagDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
+  }
+  virtual TagDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
+  }
=20
   /// @brief Completes the definition of this tag declaration.
   ///
   /// This is a helper function for derived classes.
-  void completeDefinition();   =20
-   =20
+  void completeDefinition();
+
 public:
   typedef redeclarable_base::redecl_iterator redecl_iterator;
-  redecl_iterator redecls_begin() const {
-    return redeclarable_base::redecls_begin();
-  }
-  redecl_iterator redecls_end() const {
-    return redeclarable_base::redecls_end();
-  }
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
=20
   SourceLocation getRBraceLoc() const { return RBraceLoc; }
   void setRBraceLoc(SourceLocation L) { RBraceLoc =3D L; }
@@ -2456,7 +2546,7 @@
   /// getOuterLocStart - Return SourceLocation representing start of source
   /// range taking into account any outer template declarations.
   SourceLocation getOuterLocStart() const;
-  virtual SourceRange getSourceRange() const;
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
=20
   virtual TagDecl* getCanonicalDecl();
   const TagDecl* getCanonicalDecl() const {
@@ -2532,7 +2622,8 @@
   bool isEnum()   const { return getTagKind() =3D=3D TTK_Enum; }
=20
   TypedefNameDecl *getTypedefNameForAnonDecl() const {
-    return hasExtInfo() ? 0 : TypedefNameDeclOrQualifier.get<TypedefNameDe=
cl*>();
+    return hasExtInfo() ? 0 :
+           TypedefNameDeclOrQualifier.get<TypedefNameDecl*>();
   }
=20
   void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
@@ -2543,15 +2634,15 @@
     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifie=
r()
                         : 0;
   }
- =20
-  /// \brief Retrieve the nested-name-specifier (with source-location=20
-  /// information) that qualifies the name of this declaration, if it was=20
+
+  /// \brief Retrieve the nested-name-specifier (with source-location
+  /// information) that qualifies the name of this declaration, if it was
   /// present in the source.
   NestedNameSpecifierLoc getQualifierLoc() const {
     return hasExtInfo() ? getExtInfo()->QualifierLoc
                         : NestedNameSpecifierLoc();
   }
-   =20
+
   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
=20
   unsigned getNumTemplateParameterLists() const {
@@ -2580,9 +2671,11 @@
   friend class ASTDeclWriter;
 };
=20
-/// EnumDecl - Represents an enum.  As an extension, we allow forward-decl=
ared
-/// enums.
+/// EnumDecl - Represents an enum.  In C++11, enums can be forward-declared
+/// with a fixed underlying type, and in C we allow them to be forward-dec=
lared
+/// with no underlying type as an extension.
 class EnumDecl : public TagDecl {
+  virtual void anchor();
   /// IntegerType - This represent the integer type that the enum correspo=
nds
   /// to for code generation purposes.  Note that the enumerator constants=
 may
   /// have a different type than this does.
@@ -2606,23 +2699,16 @@
   /// in C++) are of the enum type instead.
   QualType PromotionType;
=20
-  /// \brief If the enumeration was instantiated from an enumeration
-  /// within a class or function template, this pointer refers to the
-  /// enumeration declared within the template.
-  EnumDecl *InstantiatedFrom;
-
-  // The number of positive and negative bits required by the
-  // enumerators are stored in the SubclassBits field.
-  enum {
-    NumBitsWidth =3D 8,
-    NumBitsMask =3D (1 << NumBitsWidth) - 1
-  };
+  /// \brief If this enumeration is an instantiation of a member enumerati=
on
+  /// of a class template specialization, this is the member specialization
+  /// information.
+  MemberSpecializationInfo *SpecializationInfo;
=20
   EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc,
            IdentifierInfo *Id, EnumDecl *PrevDecl,
            bool Scoped, bool ScopedUsingClassTag, bool Fixed)
     : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc),
-      InstantiatedFrom(0) {
+      SpecializationInfo(0) {
     assert(Scoped || !ScopedUsingClassTag);
     IntegerType =3D (const Type*)0;
     NumNegativeBits =3D 0;
@@ -2631,6 +2717,9 @@
     IsScopedUsingClassTag =3D ScopedUsingClassTag;
     IsFixed =3D Fixed;
   }
+
+  void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
+                                    TemplateSpecializationKind TSK);
 public:
   EnumDecl *getCanonicalDecl() {
     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
@@ -2639,11 +2728,22 @@
     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
   }
=20
-  const EnumDecl *getPreviousDeclaration() const {
-    return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
+  const EnumDecl *getPreviousDecl() const {
+    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
   }
-  EnumDecl *getPreviousDeclaration() {
-    return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration());
+  EnumDecl *getPreviousDecl() {
+    return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl());
+  }
+
+  const EnumDecl *getMostRecentDecl() const {
+    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
+  }
+  EnumDecl *getMostRecentDecl() {
+    return cast<EnumDecl>(TagDecl::getMostRecentDecl());
+  }
+
+  EnumDecl *getDefinition() const {
+    return cast_or_null<EnumDecl>(TagDecl::getDefinition());
   }
=20
   static EnumDecl *Create(ASTContext &C, DeclContext *DC,
@@ -2651,7 +2751,7 @@
                           IdentifierInfo *Id, EnumDecl *PrevDecl,
                           bool IsScoped, bool IsScopedUsingClassTag,
                           bool IsFixed);
-  static EnumDecl *Create(ASTContext &C, EmptyShell Empty);
+  static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
=20
   /// completeDefinition - When created, the EnumDecl corresponds to a
   /// forward-declared enum. This method is used to mark the
@@ -2668,14 +2768,14 @@
   typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
=20
   enumerator_iterator enumerator_begin() const {
-    const EnumDecl *E =3D cast_or_null<EnumDecl>(getDefinition());
+    const EnumDecl *E =3D getDefinition();
     if (!E)
       E =3D this;
     return enumerator_iterator(E->decls_begin());
   }
=20
   enumerator_iterator enumerator_end() const {
-    const EnumDecl *E =3D cast_or_null<EnumDecl>(getDefinition());
+    const EnumDecl *E =3D getDefinition();
     if (!E)
       E =3D this;
     return enumerator_iterator(E->decls_end());
@@ -2723,7 +2823,7 @@
   /// \brief Returns the width in bits required to store all the
   /// negative enumerators of this enum.  These widths include
   /// the rightmost leading 1;  that is:
-  ///=20
+  ///
   /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
   /// ------------------------     -------     -----------------
   ///                       -1     1111111                     1
@@ -2760,11 +2860,31 @@
   /// \brief Returns the enumeration (declared within the template)
   /// from which this enumeration type was instantiated, or NULL if
   /// this enumeration was not instantiated from any template.
-  EnumDecl *getInstantiatedFromMemberEnum() const {
-    return InstantiatedFrom;
+  EnumDecl *getInstantiatedFromMemberEnum() const;
+
+  /// \brief If this enumeration is a member of a specialization of a
+  /// templated class, determine what kind of template specialization
+  /// or instantiation this is.
+  TemplateSpecializationKind getTemplateSpecializationKind() const;
+
+  /// \brief For an enumeration member that was instantiated from a member
+  /// enumeration of a templated class, set the template specialiation kin=
d.
+  void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
+                        SourceLocation PointOfInstantiation =3D SourceLoca=
tion());
+
+  /// \brief If this enumeration is an instantiation of a member enumerati=
on of
+  /// a class template specialization, retrieves the member specialization
+  /// information.
+  MemberSpecializationInfo *getMemberSpecializationInfo() const {
+    return SpecializationInfo;
   }
=20
-  void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom =3D I=
F; }
+  /// \brief Specify that this enumeration is an instantiation of the
+  /// member enumeration ED.
+  void setInstantiationOfMemberEnum(EnumDecl *ED,
+                                    TemplateSpecializationKind TSK) {
+    setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
+  }
=20
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const EnumDecl *D) { return true; }
@@ -2791,7 +2911,7 @@
   bool AnonymousStructOrUnion : 1;
=20
   /// HasObjectMember - This is true if this struct has at least one member
-  /// containing an object.
+  /// containing an Objective-C object pointer type.
   bool HasObjectMember : 1;
=20
   /// \brief Whether the field declarations of this record have been loaded
@@ -2810,13 +2930,20 @@
   static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *=
DC,
                             SourceLocation StartLoc, SourceLocation IdLoc,
                             IdentifierInfo *Id, RecordDecl* PrevDecl =3D 0=
);
-  static RecordDecl *Create(const ASTContext &C, EmptyShell Empty);
-
-  const RecordDecl *getPreviousDeclaration() const {
-    return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
+  static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
+
+  const RecordDecl *getPreviousDecl() const {
+    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
   }
-  RecordDecl *getPreviousDeclaration() {
-    return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration());
+  RecordDecl *getPreviousDecl() {
+    return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl());
+  }
+
+  const RecordDecl *getMostRecentDecl() const {
+    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
+  }
+  RecordDecl *getMostRecentDecl() {
+    return cast<RecordDecl>(TagDecl::getMostRecentDecl());
   }
=20
   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
@@ -2902,6 +3029,7 @@
 };
=20
 class FileScopeAsmDecl : public Decl {
+  virtual void anchor();
   StringLiteral *AsmString;
   SourceLocation RParenLoc;
   FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
@@ -2912,10 +3040,12 @@
                                   StringLiteral *Str, SourceLocation AsmLo=
c,
                                   SourceLocation RParenLoc);
=20
+  static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   SourceLocation getAsmLoc() const { return getLocation(); }
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getAsmLoc(), getRParenLoc());
   }
=20
@@ -2976,6 +3106,8 @@
   // FIXME: This can be packed into the bitfields in Decl.
   bool IsVariadic : 1;
   bool CapturesCXXThis : 1;
+  bool BlockMissingReturnType : 1;
+  bool IsConversionFromLambda : 1;
   /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
   /// parameters of this function.  This is null if a prototype or if ther=
e are
   /// no formals.
@@ -2992,12 +3124,14 @@
   BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
     : Decl(Block, DC, CaretLoc), DeclContext(Block),
       IsVariadic(false), CapturesCXXThis(false),
+      BlockMissingReturnType(true), IsConversionFromLambda(false),
       ParamInfo(0), NumParams(0), Body(0),
       SignatureAsWritten(0), Captures(0), NumCaptures(0) {}
=20
 public:
-  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation =
L);
-
+  static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation =
L);=20
+  static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   SourceLocation getCaretLocation() const { return getLocation(); }
=20
   bool isVariadic() const { return IsVariadic; }
@@ -3049,6 +3183,11 @@
   capture_const_iterator capture_end() const { return Captures + NumCaptur=
es; }
=20
   bool capturesCXXThis() const { return CapturesCXXThis; }
+  bool blockMissingReturnType() const { return BlockMissingReturnType; }
+  void setBlockMissingReturnType(bool val) { BlockMissingReturnType =3D va=
l; }
+
+  bool isConversionFromLambda() const { return IsConversionFromLambda; }
+  void setIsConversionFromLambda(bool val) { IsConversionFromLambda =3D va=
l; }
=20
   bool capturesVariable(const VarDecl *var) const;
=20
@@ -3057,8 +3196,8 @@
                    const Capture *end,
                    bool capturesCXXThis);
=20
-  virtual SourceRange getSourceRange() const;
- =20
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const BlockDecl *D) { return true; }
@@ -3071,6 +3210,75 @@
   }
 };
=20
+/// \brief Describes a module import declaration, which makes the contents
+/// of the named module visible in the current translation unit.
+///
+/// An import declaration imports the named module (or submodule). For exa=
mple:
+/// \code
+///   @__experimental_modules_import std.vector;
+/// \endcode
+///
+/// Import declarations can also be implicitly generated from #include/#im=
port=20
+/// directives.
+class ImportDecl : public Decl {
+  /// \brief The imported module, along with a bit that indicates whether
+  /// we have source-location information for each identifier in the module
+  /// name.=20
+  ///
+  /// When the bit is false, we only have a single source location for the
+  /// end of the import declaration.
+  llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
+ =20
+  /// \brief The next import in the list of imports local to the translati=
on
+  /// unit being parsed (not loaded from an AST file).
+  ImportDecl *NextLocalImport;
+ =20
+  friend class ASTReader;
+  friend class ASTDeclReader;
+  friend class ASTContext;
+ =20
+  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
+             ArrayRef<SourceLocation> IdentifierLocs);
+
+  ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
+             SourceLocation EndLoc);
+
+  ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
+ =20
+public:
+  /// \brief Create a new module import declaration.
+  static ImportDecl *Create(ASTContext &C, DeclContext *DC,=20
+                            SourceLocation StartLoc, Module *Imported,
+                            ArrayRef<SourceLocation> IdentifierLocs);
+ =20
+  /// \brief Create a new module import declaration for an implicitly-gene=
rated
+  /// import.
+  static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,=20
+                                    SourceLocation StartLoc, Module *Impor=
ted,=20
+                                    SourceLocation EndLoc);
+ =20
+  /// \brief Create a new, deserialized module import declaration.
+  static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,=20
+                                        unsigned NumLocations);
+ =20
+  /// \brief Retrieve the module that was imported by the import declarati=
on.
+  Module *getImportedModule() const { return ImportedAndComplete.getPointe=
r(); }
+ =20
+  /// \brief Retrieves the locations of each of the identifiers that make =
up
+  /// the complete module name in the import declaration.
+  ///
+  /// This will return an empty array if the locations of the individual
+  /// identifiers aren't available.
+  ArrayRef<SourceLocation> getIdentifierLocs() const;
+ =20
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
+ =20
+  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
+  static bool classof(const ImportDecl *D) { return true; }
+  static bool classofKind(Kind K) { return K =3D=3D Import; }
+};
+ =20
+
 /// Insertion operator for diagnostics.  This allows sending NamedDecl's
 /// into a diagnostic with <<.
 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
@@ -3079,6 +3287,12 @@
                   DiagnosticsEngine::ak_nameddecl);
   return DB;
 }
+inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
+                                           const NamedDecl* ND) {
+  PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
+                  DiagnosticsEngine::ak_nameddecl);
+  return PD;
+}
=20
 template<typename decl_type>
 void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) {
@@ -3086,26 +3300,44 @@
   // and Redeclarable to be defined.
=20
   decl_type *First;
- =20
+
   if (PrevDecl) {
     // Point to previous. Make sure that this is actually the most recent
     // redeclaration, or we can build invalid chains. If the most recent
     // redeclaration is invalid, it won't be PrevDecl, but we want it anyw=
ay.
-    RedeclLink =3D PreviousDeclLink(llvm::cast<decl_type>(
-                                                        PrevDecl->getMostR=
ecentDeclaration()));
+    RedeclLink =3D PreviousDeclLink(
+                   llvm::cast<decl_type>(PrevDecl->getMostRecentDecl()));
     First =3D PrevDecl->getFirstDeclaration();
     assert(First->RedeclLink.NextIsLatest() && "Expected first");
   } else {
     // Make this first.
     First =3D static_cast<decl_type*>(this);
   }
- =20
+
   // First one will point to this one as latest.
   First->RedeclLink =3D LatestDeclLink(static_cast<decl_type*>(this));
   if (NamedDecl *ND =3D dyn_cast<NamedDecl>(static_cast<decl_type*>(this)))
     ND->ClearLinkageCache();
 }
=20
+// Inline function definitions.
+
+/// \brief Check if the given decl is complete.
+///
+/// We use this function to break a cycle between the inline definitions in
+/// Type.h and Decl.h.
+inline bool IsEnumDeclComplete(EnumDecl *ED) {
+  return ED->isComplete();
+}
+
+/// \brief Check if the given decl is scoped.
+///
+/// We use this function to break a cycle between the inline definitions in
+/// Type.h and Decl.h.
+inline bool IsEnumDeclScoped(EnumDecl *ED) {
+  return ED->isScoped();
+}
+
 }  // end namespace clang
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DeclBase.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DeclBase.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DeclBase.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -17,8 +17,9 @@
 #include "clang/AST/Attr.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/Specifiers.h"
+#include "llvm/ADT/PointerUnion.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/PrettyStackTrace.h"
-#include "llvm/ADT/PointerUnion.h"
=20
 namespace clang {
 class DeclContext;
@@ -98,7 +99,7 @@
   /// identifiers.  C++ describes lookup completely differently:
   /// certain lookups merely "ignore" certain kinds of declarations,
   /// usually based on whether the declaration is of a type, etc.
-  ///=20
+  ///
   /// These are meant as bitmasks, so that searches in
   /// C++ can look into the "tag" namespace during ordinary lookup.
   ///
@@ -180,12 +181,28 @@
     OBJC_TQ_Oneway =3D 0x20
   };
=20
-private:
-  /// NextDeclInContext - The next declaration within the same lexical
+protected:
+  // Enumeration values used in the bits stored in NextInContextAndBits.
+  enum {
+    /// \brief Whether this declaration is a top-level declaration (functi=
on,
+    /// global variable, etc.) that is lexically inside an objc container
+    /// definition.
+    TopLevelDeclInObjCContainerFlag =3D 0x01,
+   =20
+    /// \brief Whether this declaration is private to the module in which =
it was
+    /// defined.
+    ModulePrivateFlag =3D 0x02
+  };
+ =20
+  /// \brief The next declaration within the same lexical
   /// DeclContext. These pointers form the linked list that is
   /// traversed via DeclContext's decls_begin()/decls_end().
-  Decl *NextDeclInContext;
+  ///
+  /// The extra two bits are used for the TopLevelDeclInObjCContainer and
+  /// ModulePrivate bits.
+  llvm::PointerIntPair<Decl *, 2, unsigned> NextInContextAndBits;
=20
+private:
   friend class DeclContext;
=20
   struct MultipleDC {
@@ -243,7 +260,10 @@
   /// evaluated context or not, e.g. functions used in uninstantiated temp=
lates
   /// are regarded as "referenced" but not "used".
   unsigned Referenced : 1;
- =20
+
+  /// \brief Whether statistic collection is enabled.
+  static bool StatisticsEnabled;
+
 protected:
   /// Access - Used by C++ decls for the access specifier.
   // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier en=
um
@@ -252,14 +272,12 @@
=20
   /// \brief Whether this declaration was loaded from an AST file.
   unsigned FromASTFile : 1;
+
+  /// \brief Whether this declaration is hidden from normal name lookup, e=
.g.,
+  /// because it is was loaded from an AST file is either module-private or
+  /// because its submodule has not been made visible.
+  unsigned Hidden : 1;
  =20
-  /// ChangedAfterLoad - if this declaration has changed since being loaded
-  unsigned ChangedAfterLoad : 1;
-
-  /// \brief Whether this declaration is private to the module in which it=
 was
-  /// defined.
-  unsigned ModulePrivate : 1;
-
   /// IdentifierNamespace - This specifies what IDNS_* namespace this live=
s in.
   unsigned IdentifierNamespace : 12;
=20
@@ -267,14 +285,15 @@
   ///
   /// This field is only valid for NamedDecls subclasses.
   mutable unsigned HasCachedLinkage : 1;
- =20
+
   /// \brief If \c HasCachedLinkage, the linkage of this declaration.
   ///
   /// This field is only valid for NamedDecls subclasses.
   mutable unsigned CachedLinkage : 2;
- =20
+
   friend class ASTDeclWriter;
   friend class ASTDeclReader;
+  friend class ASTReader;
=20
 private:
   void CheckAccessDeclContext() const;
@@ -282,38 +301,52 @@
 protected:
=20
   Decl(Kind DK, DeclContext *DC, SourceLocation L)
-    : NextDeclInContext(0), DeclCtx(DC),
+    : NextInContextAndBits(), DeclCtx(DC),
       Loc(L), DeclKind(DK), InvalidDecl(0),
       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
-      Access(AS_none), FromASTFile(0), ChangedAfterLoad(false),
-      ModulePrivate(0),
+      Access(AS_none), FromASTFile(0), Hidden(0),
       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
-      HasCachedLinkage(0)=20
+      HasCachedLinkage(0)
   {
-    if (Decl::CollectingStats()) add(DK);
+    if (StatisticsEnabled) add(DK);
   }
=20
   Decl(Kind DK, EmptyShell Empty)
-    : NextDeclInContext(0), DeclKind(DK), InvalidDecl(0),
+    : NextInContextAndBits(), DeclKind(DK), InvalidDecl(0),
       HasAttrs(false), Implicit(false), Used(false), Referenced(false),
-      Access(AS_none), FromASTFile(0), ChangedAfterLoad(false),
-      ModulePrivate(0),
+      Access(AS_none), FromASTFile(0), Hidden(0),
       IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
       HasCachedLinkage(0)
   {
-    if (Decl::CollectingStats()) add(DK);
+    if (StatisticsEnabled) add(DK);
   }
=20
   virtual ~Decl();
=20
+  /// \brief Allocate memory for a deserialized declaration.
+  ///
+  /// This routine must be used to allocate memory for any declaration tha=
t is
+  /// deserialized from a module file.
+  ///
+  /// \param Context The context in which we will allocate memory.
+  /// \param ID The global ID of the deserialized declaration.
+  /// \param Size The size of the allocated object.
+  static void *AllocateDeserializedDecl(const ASTContext &Context,
+                                        unsigned ID,
+                                        unsigned Size);
+ =20
 public:
=20
   /// \brief Source range that this declaration covers.
-  virtual SourceRange getSourceRange() const {
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getLocation(), getLocation());
   }
-  SourceLocation getLocStart() const { return getSourceRange().getBegin();=
 }
-  SourceLocation getLocEnd() const { return getSourceRange().getEnd(); }
+  SourceLocation getLocStart() const LLVM_READONLY {
+    return getSourceRange().getBegin();
+  }
+  SourceLocation getLocEnd() const LLVM_READONLY {
+    return getSourceRange().getEnd();
+  }
=20
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc =3D L; }
@@ -321,8 +354,8 @@
   Kind getKind() const { return static_cast<Kind>(DeclKind); }
   const char *getDeclKindName() const;
=20
-  Decl *getNextDeclInContext() { return NextDeclInContext; }
-  const Decl *getNextDeclInContext() const { return NextDeclInContext; }
+  Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer();=
 }
+  const Decl *getNextDeclInContext() const {return NextInContextAndBits.ge=
tPointer();}
=20
   DeclContext *getDeclContext() {
     if (isInSemaDC())
@@ -347,7 +380,7 @@
=20
   bool isInAnonymousNamespace() const;
=20
-  ASTContext &getASTContext() const;
+  ASTContext &getASTContext() const LLVM_READONLY;
=20
   void setAccess(AccessSpecifier AS) {
     Access =3D AS;
@@ -364,7 +397,9 @@
   }
=20
   bool hasAttrs() const { return HasAttrs; }
-  void setAttrs(const AttrVec& Attrs);
+  void setAttrs(const AttrVec& Attrs) {
+    return setAttrsImpl(Attrs, getASTContext());
+  }
   AttrVec &getAttrs() {
     return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
   }
@@ -389,11 +424,11 @@
   attr_iterator attr_end() const {
     return hasAttrs() ? getAttrs().end() : 0;
   }
- =20
+
   template <typename T>
   void dropAttr() {
     if (!HasAttrs) return;
-   =20
+
     AttrVec &Attrs =3D getAttrs();
     for (unsigned i =3D 0, e =3D Attrs.size(); i !=3D e; /* in loop */) {
       if (isa<T>(Attrs[i])) {
@@ -406,7 +441,7 @@
     if (Attrs.empty())
       HasAttrs =3D false;
   }
-   =20
+
   template <typename T>
   specific_attr_iterator<T> specific_attr_begin() const {
     return specific_attr_iterator<T>(attr_begin());
@@ -455,6 +490,48 @@
=20
   void setReferenced(bool R =3D true) { Referenced =3D R; }
=20
+  /// \brief Whether this declaration is a top-level declaration (function,
+  /// global variable, etc.) that is lexically inside an objc container
+  /// definition.
+  bool isTopLevelDeclInObjCContainer() const {
+    return NextInContextAndBits.getInt() & TopLevelDeclInObjCContainerFlag;
+  }
+
+  void setTopLevelDeclInObjCContainer(bool V =3D true) {
+    unsigned Bits =3D NextInContextAndBits.getInt();
+    if (V)
+      Bits |=3D TopLevelDeclInObjCContainerFlag;
+    else
+      Bits &=3D ~TopLevelDeclInObjCContainerFlag;
+    NextInContextAndBits.setInt(Bits);
+  }
+
+protected:
+  /// \brief Whether this declaration was marked as being private to the
+  /// module in which it was defined.
+  bool isModulePrivate() const {=20
+    return NextInContextAndBits.getInt() & ModulePrivateFlag;
+  }
+ =20
+  /// \brief Specify whether this declaration was marked as being private
+  /// to the module in which it was defined.
+  void setModulePrivate(bool MP =3D true) {
+    unsigned Bits =3D NextInContextAndBits.getInt();
+    if (MP)
+      Bits |=3D ModulePrivateFlag;
+    else
+      Bits &=3D ~ModulePrivateFlag;
+    NextInContextAndBits.setInt(Bits);
+  }
+
+  /// \brief Set the owning module ID.
+  void setOwningModuleID(unsigned ID) {
+    assert(isFromASTFile() && "Only works on a deserialized declaration");
+    *((unsigned*)this - 2) =3D ID;
+  }
+ =20
+public:
+ =20
   /// \brief Determine the availability of the given declaration.
   ///
   /// This routine will determine the most restrictive availability of
@@ -504,20 +581,24 @@
   /// \brief Determine whether this declaration came from an AST file (suc=
h as
   /// a precompiled header or module) rather than having been parsed.
   bool isFromASTFile() const { return FromASTFile; }
+
+  /// \brief Retrieve the global declaration ID associated with this=20
+  /// declaration, which specifies where in the=20
+  unsigned getGlobalID() const {=20
+    if (isFromASTFile())
+      return *((const unsigned*)this - 1);
+    return 0;
+  }
  =20
-  /// \brief Query whether this declaration was changed in a significant w=
ay
-  /// since being loaded from an AST file.
-  ///
-  /// In an epic violation of layering, what is "significant" is entirely
-  /// up to the serialization system, but implemented in AST and Sema.
-  bool isChangedSinceDeserialization() const { return ChangedAfterLoad; }
-
-  /// \brief Mark this declaration as having changed since deserialization=
, or
-  /// reset the flag.
-  void setChangedSinceDeserialization(bool Changed) {
-    ChangedAfterLoad =3D Changed;
+  /// \brief Retrieve the global ID of the module that owns this particular
+  /// declaration.
+  unsigned getOwningModuleID() const {
+    if (isFromASTFile())
+      return *((const unsigned*)this - 2);
+   =20
+    return 0;
   }
-
+ =20
   unsigned getIdentifierNamespace() const {
     return IdentifierNamespace;
   }
@@ -587,7 +668,7 @@
=20
   /// \brief Whether this particular Decl is a canonical one.
   bool isCanonicalDecl() const { return getCanonicalDecl() =3D=3D this; }
-
+ =20
 protected:
   /// \brief Returns the next redeclaration or itself if this is the only =
decl.
   ///
@@ -595,6 +676,14 @@
   /// Decl::redecl_iterator can iterate over them.
   virtual Decl *getNextRedeclaration() { return this; }
=20
+  /// \brief Implementation of getPreviousDecl(), to be overridden by any
+  /// subclass that has a redeclaration chain.
+  virtual Decl *getPreviousDeclImpl() { return 0; }
+ =20
+  /// \brief Implementation of getMostRecentDecl(), to be overridden by any
+  /// subclass that has a redeclaration chain. =20
+  virtual Decl *getMostRecentDeclImpl() { return this; }
+ =20
 public:
   /// \brief Iterates through all the redeclarations of the same decl.
   class redecl_iterator {
@@ -645,6 +734,26 @@
   }
   redecl_iterator redecls_end() const { return redecl_iterator(); }
=20
+  /// \brief Retrieve the previous declaration that declares the same enti=
ty
+  /// as this declaration, or NULL if there is no previous declaration.
+  Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
+ =20
+  /// \brief Retrieve the most recent declaration that declares the same e=
ntity
+  /// as this declaration, or NULL if there is no previous declaration.
+  const Decl *getPreviousDecl() const {=20
+    return const_cast<Decl *>(this)->getPreviousDeclImpl();
+  }
+ =20
+  /// \brief Retrieve the most recent declaration that declares the same e=
ntity
+  /// as this declaration (which may be this declaration).
+  Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
+
+  /// \brief Retrieve the most recent declaration that declares the same e=
ntity
+  /// as this declaration (which may be this declaration).
+  const Decl *getMostRecentDecl() const {=20
+    return const_cast<Decl *>(this)->getMostRecentDeclImpl();
+  }
+
   /// getBody - If this Decl represents a declaration for a body of code,
   ///  such as a function or method definition, this method returns the
   ///  top-level Stmt* of that body.  Otherwise this method returns null.
@@ -660,7 +769,7 @@
=20
   // global temp stats (until we have a per-module visitor)
   static void add(Kind k);
-  static bool CollectingStats(bool Enable =3D false);
+  static void EnableStatistics();
   static void PrintStats();
=20
   /// isTemplateParameter - Determines whether this declaration is a
@@ -673,7 +782,7 @@
=20
   /// \brief Whether this declaration is a parameter pack.
   bool isParameterPack() const;
- =20
+
   /// \brief returns true if this declaration is a template
   bool isTemplateDecl() const;
=20
@@ -722,7 +831,7 @@
     unsigned mask
       =3D (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
     if (!mask) return FOK_None;
-    return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?=20
+    return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ?
               FOK_Declared : FOK_Undeclared);
   }
=20
@@ -747,17 +856,31 @@
   static void printGroup(Decl** Begin, unsigned NumDecls,
                          raw_ostream &Out, const PrintingPolicy &Policy,
                          unsigned Indentation =3D 0);
-  void dump() const;
-  void dumpXML() const;
+  LLVM_ATTRIBUTE_USED void dump() const;
+  LLVM_ATTRIBUTE_USED void dumpXML() const;
   void dumpXML(raw_ostream &OS) const;
=20
 private:
   const Attr *getAttrsImpl() const;
+  void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
+  void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
+                           ASTContext &Ctx);
=20
 protected:
   ASTMutationListener *getASTMutationListener() const;
 };
=20
+/// \brief Determine whether two declarations declare the same entity.
+inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
+  if (!D1 || !D2)
+    return false;
+ =20
+  if (D1 =3D=3D D2)
+    return true;
+ =20
+  return D1->getCanonicalDecl() =3D=3D D2->getCanonicalDecl();
+}
+ =20
 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened wh=
en
 /// doing something to a specific decl.
 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
@@ -826,8 +949,11 @@
=20
   /// \brief Pointer to the data structure used to lookup declarations
   /// within this context (or a DependentStoredDeclsMap if this is a
-  /// dependent context).
-  mutable StoredDeclsMap *LookupPtr;
+  /// dependent context), and a bool indicating whether we have lazily
+  /// omitted any declarations from the map. We maintain the invariant
+  /// that, if the map contains an entry for a DeclarationName, then it
+  /// contains all relevant entries for that name.
+  mutable llvm::PointerIntPair<StoredDeclsMap*, 1, bool> LookupPtr;
=20
 protected:
   /// FirstDecl - The first declaration stored within this declaration
@@ -841,16 +967,17 @@
   mutable Decl *LastDecl;
=20
   friend class ExternalASTSource;
+  friend class ASTWriter;
=20
   /// \brief Build up a chain of declarations.
   ///
   /// \returns the first/last pair of declarations.
   static std::pair<Decl *, Decl *>
-  BuildDeclChain(const SmallVectorImpl<Decl*> &Decls, bool FieldsAlreadyLo=
aded);
+  BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
=20
    DeclContext(Decl::Kind K)
      : DeclKind(K), ExternalLexicalStorage(false),
-       ExternalVisibleStorage(false), LookupPtr(0), FirstDecl(0),
+       ExternalVisibleStorage(false), LookupPtr(0, false), FirstDecl(0),
        LastDecl(0) { }
=20
 public:
@@ -886,11 +1013,11 @@
   }
=20
   DeclContext *getLookupParent();
- =20
+
   const DeclContext *getLookupParent() const {
     return const_cast<DeclContext*>(this)->getLookupParent();
   }
- =20
+
   ASTContext &getParentASTContext() const {
     return cast<Decl>(this)->getASTContext();
   }
@@ -974,6 +1101,14 @@
   /// declaration context DC.
   bool Encloses(const DeclContext *DC) const;
=20
+  /// \brief Find the nearest non-closure ancestor of this context,
+  /// i.e. the innermost semantic parent of this context which is not
+  /// a closure.  A context may be its own non-closure ancestor.
+  DeclContext *getNonClosureAncestor();
+  const DeclContext *getNonClosureAncestor() const {
+    return const_cast<DeclContext*>(this)->getNonClosureAncestor();
+  }
+
   /// getPrimaryContext - There may be many different
   /// declarations of the same entity (including forward declarations
   /// of classes, multiple definitions of namespaces, etc.), each with
@@ -1007,24 +1142,30 @@
   /// inline, its enclosing namespace, recursively.
   bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
=20
-  /// getNextContext - If this is a DeclContext that may have other
-  /// DeclContexts that are semantically connected but syntactically
-  /// different, such as C++ namespaces, this routine retrieves the
-  /// next DeclContext in the link. Iteration through the chain of
-  /// DeclContexts should begin at the primary DeclContext and
-  /// continue until this function returns NULL. For example, given:
-  /// @code
+  /// \\brief Collects all of the declaration contexts that are semantical=
ly
+  /// connected to this declaration context.
+  ///
+  /// For declaration contexts that have multiple semantically connected b=
ut
+  /// syntactically distinct contexts, such as C++ namespaces, this routin=
e=20
+  /// retrieves the complete set of such declaration contexts in source or=
der.
+  /// For example, given:
+  ///
+  /// \code
   /// namespace N {
   ///   int x;
   /// }
   /// namespace N {
   ///   int y;
   /// }
-  /// @endcode
-  /// The first occurrence of namespace N will be the primary
-  /// DeclContext. Its getNextContext will return the second
-  /// occurrence of namespace N.
-  DeclContext *getNextContext();
+  /// \endcode
+  ///
+  /// The \c Contexts parameter will contain both definitions of N.
+  ///
+  /// \param Contexts Will be cleared and set to the set of declaration
+  /// contexts that are semanticaly connected to this declaration context,
+  /// in source order, including this context (which may be the only resul=
t,
+  /// for non-namespace contexts).
+  void collectAllContexts(llvm::SmallVectorImpl<DeclContext *> &Contexts);
=20
   /// decl_iterator - Iterates through the declarations stored
   /// within this context.
@@ -1133,13 +1274,13 @@
       return tmp;
     }
=20
-    friend bool
-    operator=3D=3D(const specific_decl_iterator& x, const specific_decl_it=
erator& y) {
+    friend bool operator=3D=3D(const specific_decl_iterator& x,
+                           const specific_decl_iterator& y) {
       return x.Current =3D=3D y.Current;
     }
=20
-    friend bool
-    operator!=3D(const specific_decl_iterator& x, const specific_decl_iter=
ator& y) {
+    friend bool operator!=3D(const specific_decl_iterator& x,
+                           const specific_decl_iterator& y) {
       return x.Current !=3D y.Current;
     }
   };
@@ -1207,13 +1348,13 @@
       return tmp;
     }
=20
-    friend bool
-    operator=3D=3D(const filtered_decl_iterator& x, const filtered_decl_it=
erator& y) {
+    friend bool operator=3D=3D(const filtered_decl_iterator& x,
+                           const filtered_decl_iterator& y) {
       return x.Current =3D=3D y.Current;
     }
=20
-    friend bool
-    operator!=3D(const filtered_decl_iterator& x, const filtered_decl_iter=
ator& y) {
+    friend bool operator!=3D(const filtered_decl_iterator& x,
+                           const filtered_decl_iterator& y) {
       return x.Current !=3D y.Current;
     }
   };
@@ -1232,6 +1373,16 @@
   /// semantic context via makeDeclVisibleInContext.
   void addDecl(Decl *D);
=20
+  /// @brief Add the declaration D into this context, but suppress
+  /// searches for external declarations with the same name.
+  ///
+  /// Although analogous in function to addDecl, this removes an
+  /// important check.  This is only useful if the Decl is being
+  /// added in response to an external search; in all other cases,
+  /// addDecl() is the right function to use.
+  /// See the ASTImporter for use cases.
+  void addDeclInternal(Decl *D);
+
   /// @brief Add the declaration D to this context without modifying
   /// any lookup tables.
   ///
@@ -1265,12 +1416,12 @@
   /// \brief A simplistic name lookup mechanism that performs name lookup
   /// into this declaration context without consulting the external source.
   ///
-  /// This function should almost never be used, because it subverts the=20
+  /// This function should almost never be used, because it subverts the
   /// usual relationship between a DeclContext and the external source.
   /// See the ASTImporter for the (few, but important) use cases.
-  void localUncachedLookup(DeclarationName Name,=20
+  void localUncachedLookup(DeclarationName Name,
                            llvm::SmallVectorImpl<NamedDecl *> &Results);
- =20
+
   /// @brief Makes a declaration visible within this context.
   ///
   /// This routine makes the declaration D visible to name lookup
@@ -1285,11 +1436,15 @@
   /// visible from this context, as determined by
   /// NamedDecl::declarationReplaces, the previous declaration will be
   /// replaced with D.
-  ///
-  /// @param Recoverable true if it's okay to not add this decl to
-  /// the lookup tables because it can be easily recovered by walking
-  /// the declaration chains.
-  void makeDeclVisibleInContext(NamedDecl *D, bool Recoverable =3D true);
+  void makeDeclVisibleInContext(NamedDecl *D);
+
+  /// all_lookups_iterator - An iterator that provides a view over the res=
ults
+  /// of looking up every possible name.
+  class all_lookups_iterator;
+
+  all_lookups_iterator lookups_begin() const;
+
+  all_lookups_iterator lookups_end() const;
=20
   /// udir_iterator - Iterates through the using-directives stored
   /// within this context.
@@ -1315,7 +1470,11 @@
   // Low-level accessors
=20
   /// \brief Retrieve the internal representation of the lookup structure.
-  StoredDeclsMap* getLookupPtr() const { return LookupPtr; }
+  /// This may omit some names if we are lazily building the structure.
+  StoredDeclsMap *getLookupPtr() const { return LookupPtr.getPointer(); }
+
+  /// \brief Ensure the lookup structure is fully-built and return it.
+  StoredDeclsMap *buildLookup();
=20
   /// \brief Whether this DeclContext has external storage containing
   /// additional declarations that are lexically in this context.
@@ -1340,9 +1499,10 @@
   /// \brief Determine whether the given declaration is stored in the list=
 of
   /// declarations lexically within this context.
   bool isDeclInLexicalTraversal(const Decl *D) const {
-    return D && (D->NextDeclInContext || D =3D=3D FirstDecl || D =3D=3D La=
stDecl);
+    return D && (D->NextInContextAndBits.getPointer() || D =3D=3D FirstDec=
l ||=20
+                 D =3D=3D LastDecl);
   }
- =20
+
   static bool classof(const Decl *D);
   static bool classof(const DeclContext *D) { return true; }
 #define DECL(NAME, BASE)
@@ -1350,16 +1510,26 @@
   static bool classof(const NAME##Decl *D) { return true; }
 #include "clang/AST/DeclNodes.inc"
=20
-  void dumpDeclContext() const;
+  LLVM_ATTRIBUTE_USED void dumpDeclContext() const;
=20
 private:
   void LoadLexicalDeclsFromExternalStorage() const;
=20
+  /// @brief Makes a declaration visible within this context, but
+  /// suppresses searches for external declarations with the same
+  /// name.
+  ///
+  /// Analogous to makeDeclVisibleInContext, but for the exclusive
+  /// use of addDeclInternal().
+  void makeDeclVisibleInContextInternal(NamedDecl *D);
+
   friend class DependentDiagnostic;
   StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
=20
-  void buildLookup(DeclContext *DCtx);
-  void makeDeclVisibleInContextImpl(NamedDecl *D);
+  void buildLookupImpl(DeclContext *DCtx);
+  void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
+                                         bool Rediscoverable);
+  void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
 };
=20
 inline bool Decl::isTemplateParameter() const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DeclCXX.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DeclCXX.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -16,10 +16,14 @@
 #define LLVM_CLANG_AST_DECLCXX_H
=20
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/AST/UnresolvedSet.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
=20
@@ -36,7 +40,8 @@
 class CXXFinalOverriderMap;
 class CXXIndirectPrimaryBaseSet;
 class FriendDecl;
- =20
+class LambdaExpr;
+
 /// \brief Represents any kind of function declaration, whether it is a
 /// concrete function or a function template.
 class AnyFunctionDecl {
@@ -104,6 +109,7 @@
 /// Also note that this class has nothing to do with so-called
 /// "access declarations" (C++98 11.3 [class.access.dcl]).
 class AccessSpecDecl : public Decl {
+  virtual void anchor();
   /// ColonLoc - The location of the ':'.
   SourceLocation ColonLoc;
=20
@@ -125,7 +131,7 @@
   /// setColonLoc - Sets the location of the colon.
   void setColonLoc(SourceLocation CLoc) { ColonLoc =3D CLoc; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getAccessSpecifierLoc(), getColonLoc());
   }
=20
@@ -134,9 +140,7 @@
                                 SourceLocation ColonLoc) {
     return new (C) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
   }
-  static AccessSpecDecl *Create(ASTContext &C, EmptyShell Empty) {
-    return new (C) AccessSpecDecl(Empty);
-  }
+  static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
=20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -170,7 +174,7 @@
   /// \brief The source location of the ellipsis, if this is a pack
   /// expansion.
   SourceLocation EllipsisLoc;
- =20
+
   /// Virtual - Whether this is a virtual base class or not.
   bool Virtual : 1;
=20
@@ -200,12 +204,14 @@
=20
   CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
                    TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
-    : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),=20
+    : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
       Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) { }
=20
   /// getSourceRange - Retrieves the source range that contains the
   /// entire base specifier.
-  SourceRange getSourceRange() const { return Range; }
+  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
+  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin=
(); }
+  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
=20
   /// isVirtual - Determines whether the base class is a virtual base
   /// class (or not).
@@ -214,7 +220,7 @@
   /// \brief Determine whether this base class is a base of a class declar=
ed
   /// with the 'class' keyword (vs. one declared with the 'struct' keyword=
).
   bool isBaseOfClass() const { return BaseOfClass; }
- =20
+
   /// \brief Determine whether this base specifier is a pack expansion.
   bool isPackExpansion() const { return EllipsisLoc.isValid(); }
=20
@@ -319,7 +325,8 @@
     /// * has no non-static data members of type non-standard-layout class=
 (or
     ///   array of such types) or reference,
     /// * has no virtual functions (10.3) and no virtual base classes (10.=
1),
-    /// * has the same access control (Clause 11) for all non-static data =
members
+    /// * has the same access control (Clause 11) for all non-static data
+    ///   members
     /// * has no non-standard-layout base classes,
     /// * either has no non-static data members in the most derived class =
and at
     ///   most one base class with non-static data members, or has no base
@@ -346,7 +353,10 @@
=20
     /// \brief True if this class (or any subobject) has mutable fields.
     bool HasMutableFields : 1;
-   =20
+
+    /// \brief True if there no non-field members declared by the user.
+    bool HasOnlyCMembers : 1;
+
     /// HasTrivialDefaultConstructor - True when, if this class has a defa=
ult
     /// constructor, this default constructor is trivial.
     ///
@@ -364,10 +374,34 @@
     bool HasTrivialDefaultConstructor : 1;
=20
     /// HasConstexprNonCopyMoveConstructor - True when this class has at l=
east
-    /// one constexpr constructor which is neither the copy nor move
-    /// constructor.
+    /// one user-declared constexpr constructor which is neither the copy =
nor
+    /// move constructor.
     bool HasConstexprNonCopyMoveConstructor : 1;
=20
+    /// DefaultedDefaultConstructorIsConstexpr - True if a defaulted defau=
lt
+    /// constructor for this class would be constexpr.
+    bool DefaultedDefaultConstructorIsConstexpr : 1;
+
+    /// DefaultedCopyConstructorIsConstexpr - True if a defaulted copy
+    /// constructor for this class would be constexpr.
+    bool DefaultedCopyConstructorIsConstexpr : 1;
+
+    /// DefaultedMoveConstructorIsConstexpr - True if a defaulted move
+    /// constructor for this class would be constexpr.
+    bool DefaultedMoveConstructorIsConstexpr : 1;
+
+    /// HasConstexprDefaultConstructor - True if this class has a constexpr
+    /// default constructor (either user-declared or implicitly declared).
+    bool HasConstexprDefaultConstructor : 1;
+
+    /// HasConstexprCopyConstructor - True if this class has a constexpr c=
opy
+    /// constructor (either user-declared or implicitly declared).
+    bool HasConstexprCopyConstructor : 1;
+
+    /// HasConstexprMoveConstructor - True if this class has a constexpr m=
ove
+    /// constructor (either user-declared or implicitly declared).
+    bool HasConstexprMoveConstructor : 1;
+
     /// HasTrivialCopyConstructor - True when this class has a trivial copy
     /// constructor.
     ///
@@ -438,8 +472,13 @@
     ///   type (or array thereof), each such class has a trivial destructo=
r.
     bool HasTrivialDestructor : 1;
=20
+    /// HasIrrelevantDestructor - True when this class has a destructor wi=
th no
+    /// semantic effect.
+    bool HasIrrelevantDestructor : 1;
+
     /// HasNonLiteralTypeFieldsOrBases - True when this class contains at =
least
-    /// one non-static data member or base class of non literal type.
+    /// one non-static data member or base class of non-literal or volatile
+    /// type.
     bool HasNonLiteralTypeFieldsOrBases : 1;
=20
     /// ComputedVisibleConversions - True when visible conversion function=
s are
@@ -458,13 +497,13 @@
=20
     /// \brief Whether we have already declared the move constructor.
     bool DeclaredMoveConstructor : 1;
-   =20
+
     /// \brief Whether we have already declared the copy-assignment operat=
or.
     bool DeclaredCopyAssignment : 1;
=20
     /// \brief Whether we have already declared the move-assignment operat=
or.
     bool DeclaredMoveAssignment : 1;
-   =20
+
     /// \brief Whether we have already declared a destructor within the cl=
ass.
     bool DeclaredDestructor : 1;
=20
@@ -476,9 +515,12 @@
     /// declared but would have been deleted.
     bool FailedImplicitMoveAssignment : 1;
=20
+    /// \brief Whether this class describes a C++ lambda.
+    bool IsLambda : 1;
+
     /// NumBases - The number of base class specifiers in Bases.
     unsigned NumBases;
-   =20
+
     /// NumVBases - The number of virtual base class specifiers in VBases.
     unsigned NumVBases;
=20
@@ -510,17 +552,59 @@
     /// in reverse order.
     FriendDecl *FirstFriend;
=20
-    /// \brief Retrieve the set of direct base classes.   =20
+    /// \brief Retrieve the set of direct base classes.
     CXXBaseSpecifier *getBases() const {
       return Bases.get(Definition->getASTContext().getExternalSource());
     }
=20
-    /// \brief Retrieve the set of virtual base classes.   =20
+    /// \brief Retrieve the set of virtual base classes.
     CXXBaseSpecifier *getVBases() const {
       return VBases.get(Definition->getASTContext().getExternalSource());
     }
   } *DefinitionData;
=20
+  /// \brief Describes a C++ closure type (generated by a lambda expressio=
n).
+  struct LambdaDefinitionData : public DefinitionData {
+    typedef LambdaExpr::Capture Capture;
+   =20
+    LambdaDefinitionData(CXXRecordDecl *D, bool Dependent)=20
+      : DefinitionData(D), Dependent(Dependent), NumCaptures(0),=20
+        NumExplicitCaptures(0), ManglingNumber(0), ContextDecl(0), Capture=
s(0)=20
+    {
+      IsLambda =3D true;
+    }
+
+    /// \brief Whether this lambda is known to be dependent, even if its
+    /// context isn't dependent.
+    ///=20
+    /// A lambda with a non-dependent context can be dependent if it occurs
+    /// within the default argument of a function template, because the
+    /// lambda will have been created with the enclosing context as its
+    /// declaration context, rather than function. This is an unfortunate
+    /// artifact of having to parse the default arguments before=20
+    unsigned Dependent : 1;
+   =20
+    /// \brief The number of captures in this lambda.
+    unsigned NumCaptures : 16;
+
+    /// \brief The number of explicit captures in this lambda.
+    unsigned NumExplicitCaptures : 15;
+
+    /// \brief The number used to indicate this lambda expression for name=20
+    /// mangling in the Itanium C++ ABI.
+    unsigned ManglingNumber;
+   =20
+    /// \brief The declaration that provides context for this lambda, if t=
he
+    /// actual DeclContext does not suffice. This is used for lambdas that
+    /// occur within default arguments of function parameters within the c=
lass
+    /// or within a data member initializer.
+    Decl *ContextDecl;
+   =20
+    /// \brief The list of captures, both explicit and implicit, for this=20
+    /// lambda.
+    Capture *Captures;   =20
+  };
+
   struct DefinitionData &data() {
     assert(DefinitionData && "queried property of class with no definition=
");
     return *DefinitionData;
@@ -530,6 +614,13 @@
     assert(DefinitionData && "queried property of class with no definition=
");
     return *DefinitionData;
   }
+
+  struct LambdaDefinitionData &getLambdaData() const {
+    assert(DefinitionData && "queried property of lambda with no definitio=
n");
+    assert(DefinitionData->IsLambda &&=20
+           "queried lambda property of non-lambda class");
+    return static_cast<LambdaDefinitionData &>(*DefinitionData);
+  }
  =20
   /// \brief The template or declaration that this declaration
   /// describes or was instantiated from, respectively.
@@ -538,23 +629,26 @@
   /// declarations that describe a class template, this will be a
   /// pointer to a ClassTemplateDecl. For member
   /// classes of class template specializations, this will be the
-  /// MemberSpecializationInfo referring to the member class that was=20
+  /// MemberSpecializationInfo referring to the member class that was
   /// instantiated or specialized.
   llvm::PointerUnion<ClassTemplateDecl*, MemberSpecializationInfo*>
     TemplateOrInstantiation;
=20
   friend class DeclContext;
- =20
+  friend class LambdaExpr;
+
   /// \brief Notify the class that member has been added.
   ///
-  /// This routine helps maintain information about the class based on whi=
ch=20
+  /// This routine helps maintain information about the class based on whi=
ch
   /// members have been added. It will be invoked by DeclContext::addDecl()
   /// whenever a member is added to this record.
   void addedMember(Decl *D);
=20
   void markedVirtualFunctionPure();
   friend void FunctionDecl::setPure(bool);
- =20
+
+  friend class ASTNodeImporter;
+
 protected:
   CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
                 SourceLocation StartLoc, SourceLocation IdLoc,
@@ -585,12 +679,19 @@
   virtual const CXXRecordDecl *getCanonicalDecl() const {
     return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
   }
- =20
-  const CXXRecordDecl *getPreviousDeclaration() const {
-    return cast_or_null<CXXRecordDecl>(RecordDecl::getPreviousDeclaration(=
));
+
+  const CXXRecordDecl *getPreviousDecl() const {
+    return cast_or_null<CXXRecordDecl>(RecordDecl::getPreviousDecl());
   }
-  CXXRecordDecl *getPreviousDeclaration() {
-    return cast_or_null<CXXRecordDecl>(RecordDecl::getPreviousDeclaration(=
));
+  CXXRecordDecl *getPreviousDecl() {
+    return cast_or_null<CXXRecordDecl>(RecordDecl::getPreviousDecl());
+  }
+
+  const CXXRecordDecl *getMostRecentDecl() const {
+    return cast_or_null<CXXRecordDecl>(RecordDecl::getMostRecentDecl());
+  }
+  CXXRecordDecl *getMostRecentDecl() {
+    return cast_or_null<CXXRecordDecl>(RecordDecl::getMostRecentDecl());
   }
=20
   CXXRecordDecl *getDefinition() const {
@@ -604,7 +705,9 @@
                                SourceLocation StartLoc, SourceLocation IdL=
oc,
                                IdentifierInfo *Id, CXXRecordDecl* PrevDecl=
=3D0,
                                bool DelayTypeCreation =3D false);
-  static CXXRecordDecl *Create(const ASTContext &C, EmptyShell Empty);
+  static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
+                                     SourceLocation Loc, bool DependentLam=
bda);
+  static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned I=
D);
=20
   bool isDynamicClass() const {
     return data().Polymorphic || data().NumVBases !=3D 0;
@@ -704,7 +807,7 @@
   ///
   /// This value is used for lazy creation of default constructors.
   bool needsImplicitDefaultConstructor() const {
-    return !data().UserDeclaredConstructor &&=20
+    return !data().UserDeclaredConstructor &&
            !data().DeclaredDefaultConstructor;
   }
=20
@@ -722,11 +825,11 @@
   CXXConstructorDecl *getCopyConstructor(unsigned TypeQuals) const;
=20
   /// getMoveConstructor - Returns the move constructor for this class
-  CXXConstructorDecl *getMoveConstructor() const;=20
+  CXXConstructorDecl *getMoveConstructor() const;
=20
   /// \brief Retrieve the copy-assignment operator for this class, if avai=
lable.
   ///
-  /// This routine attempts to find the copy-assignment operator for this=20
+  /// This routine attempts to find the copy-assignment operator for this
   /// class, using a simplistic form of overload resolution.
   ///
   /// \param ArgIsConst Whether the argument to the copy-assignment operat=
or
@@ -739,7 +842,7 @@
   /// getMoveAssignmentOperator - Returns the move assignment operator for=
 this
   /// class
   CXXMethodDecl *getMoveAssignmentOperator() const;
- =20
+
   /// hasUserDeclaredConstructor - Whether this class has any
   /// user-declared constructors. When true, a default constructor
   /// will not be implicitly declared.
@@ -760,7 +863,7 @@
     return data().UserDeclaredCopyConstructor;
   }
=20
-  /// \brief Determine whether this class has had its copy constructor=20
+  /// \brief Determine whether this class has had its copy constructor
   /// declared, either via the user or via an implicit declaration.
   ///
   /// This value is used for lazy creation of copy constructors.
@@ -822,7 +925,7 @@
     return data().UserDeclaredCopyAssignment;
   }
=20
-  /// \brief Determine whether this class has had its copy assignment oper=
ator=20
+  /// \brief Determine whether this class has had its copy assignment oper=
ator
   /// declared, either via the user or via an implicit declaration.
   ///
   /// This value is used for lazy creation of copy assignment operators.
@@ -882,6 +985,29 @@
   /// This value is used for lazy creation of destructors.
   bool hasDeclaredDestructor() const { return data().DeclaredDestructor; }
=20
+  /// \brief Determine whether this class describes a lambda function obje=
ct.
+  bool isLambda() const { return hasDefinition() && data().IsLambda; }
+ =20
+  /// \brief For a closure type, retrieve the mapping from captured
+  /// variables and this to the non-static data members that store the
+  /// values or references of the captures.
+  ///
+  /// \param Captures Will be populated with the mapping from captured
+  /// variables to the corresponding fields.
+  ///
+  /// \param ThisCapture Will be set to the field declaration for the
+  /// 'this' capture.
+  void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Capt=
ures,
+                        FieldDecl *&ThisCapture) const;
+
+  typedef const LambdaExpr::Capture* capture_const_iterator;
+  capture_const_iterator captures_begin() const {
+    return isLambda() ? getLambdaData().Captures : NULL;
+  }
+  capture_const_iterator captures_end() const {
+    return isLambda() ? captures_begin() + getLambdaData().NumCaptures : N=
ULL;
+  }
+
   /// getConversions - Retrieve the overload set containing all of the
   /// conversion functions in this class.
   UnresolvedSetImpl *getConversionFunctions() {
@@ -920,6 +1046,10 @@
   /// user-defined destructor.
   bool isPOD() const { return data().PlainOldData; }
=20
+  /// \brief True if this class is C-like, without C++-specific features, =
e.g.
+  /// it contains only public fields, no bases, tag kind is not 'class', e=
tc.
+  bool isCLike() const;
+
   /// isEmpty - Whether this class is empty (C++0x [meta.unary.prop]), whi=
ch
   /// means it has a virtual function, virtual base, data member (other th=
an
   /// 0-width bit-field) or inherits from a non-empty class. Does NOT incl=
ude
@@ -941,20 +1071,63 @@
   /// \brief Whether this class, or any of its class subobjects, contains a
   /// mutable field.
   bool hasMutableFields() const { return data().HasMutableFields; }
- =20
-  // hasTrivialDefaultConstructor - Whether this class has a trivial defau=
lt
-  // constructor
-  // (C++0x [class.ctor]p5)
+
+  /// hasTrivialDefaultConstructor - Whether this class has a trivial defa=
ult
+  /// constructor (C++11 [class.ctor]p5).
   bool hasTrivialDefaultConstructor() const {
     return data().HasTrivialDefaultConstructor &&
            (!data().UserDeclaredConstructor ||
              data().DeclaredDefaultConstructor);
   }
=20
-  // hasConstexprNonCopyMoveConstructor - Whether this class has at least =
one
-  // constexpr constructor other than the copy or move constructors.
+  /// hasConstexprNonCopyMoveConstructor - Whether this class has at least=
 one
+  /// constexpr constructor other than the copy or move constructors.
   bool hasConstexprNonCopyMoveConstructor() const {
-    return data().HasConstexprNonCopyMoveConstructor;
+    return data().HasConstexprNonCopyMoveConstructor ||
+           (!hasUserDeclaredConstructor() &&
+            defaultedDefaultConstructorIsConstexpr());
+  }
+
+  /// defaultedDefaultConstructorIsConstexpr - Whether a defaulted default
+  /// constructor for this class would be constexpr.
+  bool defaultedDefaultConstructorIsConstexpr() const {
+    return data().DefaultedDefaultConstructorIsConstexpr;
+  }
+
+  /// defaultedCopyConstructorIsConstexpr - Whether a defaulted copy
+  /// constructor for this class would be constexpr.
+  bool defaultedCopyConstructorIsConstexpr() const {
+    return data().DefaultedCopyConstructorIsConstexpr;
+  }
+
+  /// defaultedMoveConstructorIsConstexpr - Whether a defaulted move
+  /// constructor for this class would be constexpr.
+  bool defaultedMoveConstructorIsConstexpr() const {
+    return data().DefaultedMoveConstructorIsConstexpr;
+  }
+
+  /// hasConstexprDefaultConstructor - Whether this class has a constexpr
+  /// default constructor.
+  bool hasConstexprDefaultConstructor() const {
+    return data().HasConstexprDefaultConstructor ||
+           (!data().UserDeclaredConstructor &&
+            data().DefaultedDefaultConstructorIsConstexpr && isLiteral());
+  }
+
+  /// hasConstexprCopyConstructor - Whether this class has a constexpr copy
+  /// constructor.
+  bool hasConstexprCopyConstructor() const {
+    return data().HasConstexprCopyConstructor ||
+           (!data().DeclaredCopyConstructor &&
+            data().DefaultedCopyConstructorIsConstexpr && isLiteral());
+  }
+
+  /// hasConstexprMoveConstructor - Whether this class has a constexpr move
+  /// constructor.
+  bool hasConstexprMoveConstructor() const {
+    return data().HasConstexprMoveConstructor ||
+           (needsImplicitMoveConstructor() &&
+            data().DefaultedMoveConstructorIsConstexpr && isLiteral());
   }
=20
   // hasTrivialCopyConstructor - Whether this class has a trivial copy
@@ -985,8 +1158,15 @@
   // (C++ [class.dtor]p3)
   bool hasTrivialDestructor() const { return data().HasTrivialDestructor; }
=20
-  // hasNonLiteralTypeFieldsOrBases - Whether this class has a non-literal=
 type
-  // non-static data member or base class.
+  // hasIrrelevantDestructor - Whether this class has a destructor which h=
as no
+  // semantic effect. Any such destructor will be trivial, public, default=
ed
+  // and not deleted, and will call only irrelevant destructors.
+  bool hasIrrelevantDestructor() const {
+    return data().HasIrrelevantDestructor;
+  }
+
+  // hasNonLiteralTypeFieldsOrBases - Whether this class has a non-literal=
 or
+  // volatile type non-static data member or base class.
   bool hasNonLiteralTypeFieldsOrBases() const {
     return data().HasNonLiteralTypeFieldsOrBases;
   }
@@ -1006,20 +1186,23 @@
=20
   // isLiteral - Whether this class is a literal type.
   //
-  // C++0x [basic.types]p10
+  // C++11 [basic.types]p10
   //   A class type that has all the following properties:
-  //     -- a trivial destructor
+  //     -- it has a trivial destructor
   //     -- every constructor call and full-expression in the
   //        brace-or-equal-intializers for non-static data members (if any=
) is
   //        a constant expression.
   //     -- it is an aggregate type or has at least one constexpr construc=
tor or
   //        constructor template that is not a copy or move constructor, a=
nd
-  //     -- all non-static data members and base classes of literal types
+  //     -- all of its non-static data members and base classes are of lit=
eral
+  //        types
   //
-  // We resolve DR1361 by ignoring the second bullet.
+  // We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
+  // treating types with trivial default constructors as literal types.
   bool isLiteral() const {
     return hasTrivialDestructor() &&
-           (isAggregate() || hasConstexprNonCopyMoveConstructor()) &&
+           (isAggregate() || hasConstexprNonCopyMoveConstructor() ||
+            hasTrivialDefaultConstructor()) &&
            !hasNonLiteralTypeFieldsOrBases();
   }
=20
@@ -1043,12 +1226,12 @@
   /// X<int>::A is required, it will be instantiated from the
   /// declaration returned by getInstantiatedFromMemberClass().
   CXXRecordDecl *getInstantiatedFromMemberClass() const;
- =20
+
   /// \brief If this class is an instantiation of a member class of a
   /// class template specialization, retrieves the member specialization
   /// information.
   MemberSpecializationInfo *getMemberSpecializationInfo() const;
- =20
+
   /// \brief Specify that this record is an instantiation of the
   /// member class RD.
   void setInstantiationOfMemberClass(CXXRecordDecl *RD,
@@ -1077,7 +1260,7 @@
   /// instantiation of a class template or member class of a class templat=
e,
   /// and how it was instantiated or specialized.
   TemplateSpecializationKind getTemplateSpecializationKind() const;
- =20
+
   /// \brief Set the kind of specialization or template instantiation this=
 is.
   void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
=20
@@ -1104,7 +1287,7 @@
   ///
   /// \returns true if this class is derived from Base, false otherwise.
   bool isDerivedFrom(const CXXRecordDecl *Base) const;
- =20
+
   /// \brief Determine whether this class is derived from the type \p Base.
   ///
   /// This routine only determines whether this class is derived from \p B=
ase,
@@ -1119,8 +1302,8 @@
   ///
   /// \returns true if this class is derived from Base, false otherwise.
   ///
-  /// \todo add a separate paramaeter to configure IsDerivedFrom, rather t=
han=20
-  /// tangling input and output in \p Paths =20
+  /// \todo add a separate paramaeter to configure IsDerivedFrom, rather t=
han
+  /// tangling input and output in \p Paths
   bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
=20
   /// \brief Determine whether this class is virtually derived from
@@ -1155,20 +1338,20 @@
   ///
   /// The class itself does not count as a base class.  This routine
   /// returns false if the class has non-computable base classes.
-  ///=20
+  ///
   /// \param AllowShortCircuit if false, forces the callback to be called
   /// for every base class, even if a dependent or non-matching base was
   /// found.
   bool forallBases(ForallBasesCallback *BaseMatches, void *UserData,
                    bool AllowShortCircuit =3D true) const;
- =20
-  /// \brief Function type used by lookupInBases() to determine whether a=20
+
+  /// \brief Function type used by lookupInBases() to determine whether a
   /// specific base class subobject matches the lookup criteria.
   ///
-  /// \param Specifier the base-class specifier that describes the inherit=
ance=20
+  /// \param Specifier the base-class specifier that describes the inherit=
ance
   /// from the base class we are trying to match.
   ///
-  /// \param Path the current path, from the most-derived class down to th=
e=20
+  /// \param Path the current path, from the most-derived class down to the
   /// base named by the \p Specifier.
   ///
   /// \param UserData a single pointer to user-specified data, provided to
@@ -1178,13 +1361,13 @@
   typedef bool BaseMatchesCallback(const CXXBaseSpecifier *Specifier,
                                    CXXBasePath &Path,
                                    void *UserData);
- =20
+
   /// \brief Look for entities within the base classes of this C++ class,
   /// transitively searching all base class subobjects.
   ///
-  /// This routine uses the callback function \p BaseMatches to find base=20
+  /// This routine uses the callback function \p BaseMatches to find base
   /// classes meeting some search criteria, walking all base class subobje=
cts
-  /// and populating the given \p Paths structure with the paths through t=
he=20
+  /// and populating the given \p Paths structure with the paths through t=
he
   /// inheritance hierarchy that resulted in a match. On a successful sear=
ch,
   /// the \p Paths structure can be queried to retrieve the matching paths=
 and
   /// to determine if there were any ambiguities.
@@ -1201,7 +1384,7 @@
   /// subobject that matches the search criteria.
   bool lookupInBases(BaseMatchesCallback *BaseMatches, void *UserData,
                      CXXBasePaths &Paths) const;
- =20
+
   /// \brief Base-class lookup callback that determines whether the given
   /// base class specifier refers to a specific class declaration.
   ///
@@ -1223,7 +1406,7 @@
   /// are searching for.
   static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
                                    CXXBasePath &Path, void *BaseRecord);
- =20
+
   /// \brief Base-class lookup callback that determines whether there exis=
ts
   /// a tag with the given name.
   ///
@@ -1241,7 +1424,7 @@
   /// is an opaque \c DeclarationName pointer.
   static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
                                  CXXBasePath &Path, void *Name);
- =20
+
   /// \brief Base-class lookup callback that determines whether there exis=
ts
   /// a member with the given name that can be used in a nested-name-speci=
fier.
   ///
@@ -1277,15 +1460,15 @@
   /// \brief Indicates that the definition of this class is now complete.
   virtual void completeDefinition();
=20
-  /// \brief Indicates that the definition of this class is now complete,=20
+  /// \brief Indicates that the definition of this class is now complete,
   /// and provides a final overrider map to help determine
-  ///=20
+  ///
   /// \param FinalOverriders The final overrider map for this class, which=
 can
   /// be provided as an optimization for abstract-class checking. If NULL,
   /// final overriders will be computed if they are needed to complete the
   /// definition.
   void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
- =20
+
   /// \brief Determine whether this class may end up being abstract, even =
though
   /// it is not yet known to be abstract.
   ///
@@ -1294,6 +1477,53 @@
   /// will need to compute final overriders to determine whether the class=
 is
   /// actually abstract.
   bool mayBeAbstract() const;
+
+  /// \brief If this is the closure type of a lambda expression, retrieve =
the
+  /// number to be used for name mangling in the Itanium C++ ABI.
+  ///
+  /// Zero indicates that this closure type has internal linkage, so the=20
+  /// mangling number does not matter, while a non-zero value indicates wh=
ich
+  /// lambda expression this is in this particular context.
+  unsigned getLambdaManglingNumber() const {
+    assert(isLambda() && "Not a lambda closure type!");
+    return getLambdaData().ManglingNumber;
+  }
+ =20
+  /// \brief Retrieve the declaration that provides additional context for=
 a=20
+  /// lambda, when the normal declaration context is not specific enough.
+  ///
+  /// Certain contexts (default arguments of in-class function parameters =
and=20
+  /// the initializers of data members) have separate name mangling rules =
for
+  /// lambdas within the Itanium C++ ABI. For these cases, this routine pr=
ovides
+  /// the declaration in which the lambda occurs, e.g., the function param=
eter=20
+  /// or the non-static data member. Otherwise, it returns NULL to imply t=
hat
+  /// the declaration context suffices.
+  Decl *getLambdaContextDecl() const {
+    assert(isLambda() && "Not a lambda closure type!");
+    return getLambdaData().ContextDecl;   =20
+  }
+ =20
+  /// \brief Set the mangling number and context declaration for a lambda
+  /// class.
+  void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) {
+    getLambdaData().ManglingNumber =3D ManglingNumber;
+    getLambdaData().ContextDecl =3D ContextDecl;
+  }
+
+  /// \brief Determine whether this lambda expression was known to be depe=
ndent
+  /// at the time it was created, even if its context does not appear to be
+  /// dependent.
+  ///
+  /// This flag is a workaround for an issue with parsing, where default
+  /// arguments are parsed before their enclosing function declarations ha=
ve
+  /// been created. This means that any lambda expressions within those
+  /// default arguments will have as their DeclContext the context enclosi=
ng
+  /// the function declaration, which may be non-dependent even when the
+  /// function declaration itself is dependent. This flag indicates when we
+  /// know that the lambda is dependent despite that.
+  bool isDependentLambda() const {
+    return isLambda() && getLambdaData().Dependent;
+  }
  =20
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) {
@@ -1313,6 +1543,7 @@
 /// CXXMethodDecl - Represents a static or instance method of a
 /// struct/union/class.
 class CXXMethodDecl : public FunctionDecl {
+  virtual void anchor();
 protected:
   CXXMethodDecl(Kind DK, CXXRecordDecl *RD, SourceLocation StartLoc,
                 const DeclarationNameInfo &NameInfo,
@@ -1322,9 +1553,9 @@
     : FunctionDecl(DK, RD, StartLoc, NameInfo, T, TInfo,
                    (isStatic ? SC_Static : SC_None),
                    SCAsWritten, isInline, isConstexpr) {
-      if (EndLocation.isValid())
-        setRangeEnd(EndLocation);
-    }
+    if (EndLocation.isValid())
+      setRangeEnd(EndLocation);
+  }
=20
 public:
   static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
@@ -1337,16 +1568,18 @@
                                bool isConstexpr,
                                SourceLocation EndLocation);
=20
+  static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   bool isStatic() const { return getStorageClass() =3D=3D SC_Static; }
   bool isInstance() const { return !isStatic(); }
=20
   bool isVirtual() const {
-    CXXMethodDecl *CD =3D=20
+    CXXMethodDecl *CD =3D
       cast<CXXMethodDecl>(const_cast<CXXMethodDecl*>(this)->getCanonicalDe=
cl());
=20
     if (CD->isVirtualAsWritten())
       return true;
-   =20
+
     return (CD->begin_overridden_methods() !=3D CD->end_overridden_methods=
());
   }
=20
@@ -1354,14 +1587,14 @@
   /// (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded
   /// delete or delete[] operator with a particular signature.
   bool isUsualDeallocationFunction() const;
- =20
+
   /// \brief Determine whether this is a copy-assignment operator, regardl=
ess
   /// of whether it was declared implicitly or explicitly.
   bool isCopyAssignmentOperator() const;
=20
   /// \brief Determine whether this is a move assignment operator.
   bool isMoveAssignmentOperator() const;
- =20
+
   const CXXMethodDecl *getCanonicalDecl() const {
     return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
   }
@@ -1374,11 +1607,11 @@
   bool isUserProvided() const {
     return !(isDeleted() || getCanonicalDecl()->isDefaulted());
   }
- =20
+
   ///
   void addOverriddenMethod(const CXXMethodDecl *MD);
=20
-  typedef const CXXMethodDecl ** method_iterator;
+  typedef const CXXMethodDecl *const* method_iterator;
=20
   method_iterator begin_overridden_methods() const;
   method_iterator end_overridden_methods() const;
@@ -1419,9 +1652,18 @@
   RefQualifierKind getRefQualifier() const {
     return getType()->getAs<FunctionProtoType>()->getRefQualifier();
   }
+
+  bool hasInlineBody() const;
+
+  /// \brief Determine whether this is a lambda closure type's static memb=
er
+  /// function that is used for the result of the lambda's conversion to
+  /// function pointer (for a lambda with no captures).
+  ///
+  /// The function itself, if used, will have a placeholder body that will=
 be
+  /// supplied by IR generation to either forward to the function call ope=
rator
+  /// or clone the function call operator.
+  bool isLambdaStaticInvoker() const;
  =20
-  bool hasInlineBody() const;
-
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const CXXMethodDecl *D) { return true; }
@@ -1445,31 +1687,34 @@
 /// };
 /// @endcode
 class CXXCtorInitializer {
-  /// \brief Either the base class name (stored as a TypeSourceInfo*), an =
normal
-  /// field (FieldDecl), anonymous field (IndirectFieldDecl*), or target
-  /// constructor (CXXConstructorDecl*) being initialized.
-  llvm::PointerUnion4<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *,
-                      CXXConstructorDecl *>
+  /// \brief Either the base class name/delegating constructor type (store=
d as
+  /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous fie=
ld
+  /// (IndirectFieldDecl*) being initialized.
+  llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
     Initializee;
- =20
+
   /// \brief The source location for the field name or, for a base initial=
izer
   /// pack expansion, the location of the ellipsis. In the case of a deleg=
ating
   /// constructor, it will still include the type's source location as the
   /// Initializee points to the CXXConstructorDecl (to allow loop detectio=
n).
   SourceLocation MemberOrEllipsisLocation;
- =20
+
   /// \brief The argument used to initialize the base or member, which may
   /// end up constructing an object (when multiple arguments are involved).
-  /// If 0, this is a field initializer, and the in-class member initializ=
er=20
+  /// If 0, this is a field initializer, and the in-class member initializ=
er
   /// will be used.
   Stmt *Init;
- =20
+
   /// LParenLoc - Location of the left paren of the ctor-initializer.
   SourceLocation LParenLoc;
=20
   /// RParenLoc - Location of the right paren of the ctor-initializer.
   SourceLocation RParenLoc;
=20
+  /// \brief If the initializee is a type, whether that type makes this
+  /// a delegating initialization.
+  bool IsDelegating : 1;
+
   /// IsVirtual - If the initializer is a base initializer, this keeps tra=
ck
   /// of whether the base is virtual or not.
   bool IsVirtual : 1;
@@ -1483,12 +1728,12 @@
   /// original sources, counting from 0; otherwise, if IsWritten is false,
   /// it stores the number of array index variables stored after this
   /// object in memory.
-  unsigned SourceOrderOrNumArrayIndices : 14;
+  unsigned SourceOrderOrNumArrayIndices : 13;
=20
   CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
                      SourceLocation MemberLoc, SourceLocation L, Expr *Ini=
t,
                      SourceLocation R, VarDecl **Indices, unsigned NumIndi=
ces);
- =20
+
 public:
   /// CXXCtorInitializer - Creates a new base-class initializer.
   explicit
@@ -1510,25 +1755,27 @@
=20
   /// CXXCtorInitializer - Creates a new delegating Initializer.
   explicit
-  CXXCtorInitializer(ASTContext &Context, SourceLocation D, SourceLocation=
 L,
-                     CXXConstructorDecl *Target, Expr *Init, SourceLocatio=
n R);
-
-  /// \brief Creates a new member initializer that optionally contains=20
+  CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
+                     SourceLocation L, Expr *Init, SourceLocation R);
+
+  /// \brief Creates a new member initializer that optionally contains
   /// array indices used to describe an elementwise initialization.
   static CXXCtorInitializer *Create(ASTContext &Context, FieldDecl *Member,
                                     SourceLocation MemberLoc, SourceLocati=
on L,
                                     Expr *Init, SourceLocation R,
                                     VarDecl **Indices, unsigned NumIndices=
);
- =20
+
   /// isBaseInitializer - Returns true when this initializer is
   /// initializing a base class.
-  bool isBaseInitializer() const { return Initializee.is<TypeSourceInfo*>(=
); }
+  bool isBaseInitializer() const {
+    return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
+  }
=20
   /// isMemberInitializer - Returns true when this initializer is
   /// initializing a non-static data member.
   bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
=20
-  bool isAnyMemberInitializer() const {=20
+  bool isAnyMemberInitializer() const {
     return isMemberInitializer() || isIndirectMemberInitializer();
   }
=20
@@ -1546,21 +1793,21 @@
   /// isDelegatingInitializer - Returns true when this initializer is crea=
ting
   /// a delegating constructor.
   bool isDelegatingInitializer() const {
-    return Initializee.is<CXXConstructorDecl *>();
+    return Initializee.is<TypeSourceInfo*>() && IsDelegating;
   }
=20
   /// \brief Determine whether this initializer is a pack expansion.
-  bool isPackExpansion() const {=20
-    return isBaseInitializer() && MemberOrEllipsisLocation.isValid();=20
+  bool isPackExpansion() const {
+    return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
   }
- =20
+
   // \brief For a pack expansion, returns the location of the ellipsis.
   SourceLocation getEllipsisLoc() const {
     assert(isPackExpansion() && "Initializer is not a pack expansion");
     return MemberOrEllipsisLocation;
   }
-          =20
-  /// If this is a base class initializer, returns the type of the=20
+
+  /// If this is a base class initializer, returns the type of the
   /// base class with location information. Otherwise, returns an NULL
   /// type location.
   TypeLoc getBaseClassLoc() const;
@@ -1572,56 +1819,47 @@
   /// Returns whether the base is virtual or not.
   bool isBaseVirtual() const {
     assert(isBaseInitializer() && "Must call this on base initializer!");
-   =20
+
     return IsVirtual;
   }
=20
-  /// \brief Returns the declarator information for a base class initializ=
er.
-  TypeSourceInfo *getBaseClassInfo() const {
+  /// \brief Returns the declarator information for a base class or delega=
ting
+  /// initializer.
+  TypeSourceInfo *getTypeSourceInfo() const {
     return Initializee.dyn_cast<TypeSourceInfo *>();
   }
- =20
+
   /// getMember - If this is a member initializer, returns the
   /// declaration of the non-static data member being
   /// initialized. Otherwise, returns NULL.
   FieldDecl *getMember() const {
     if (isMemberInitializer())
       return Initializee.get<FieldDecl*>();
-    else
-      return 0;
+    return 0;
   }
   FieldDecl *getAnyMember() const {
     if (isMemberInitializer())
       return Initializee.get<FieldDecl*>();
-    else if (isIndirectMemberInitializer())
+    if (isIndirectMemberInitializer())
       return Initializee.get<IndirectFieldDecl*>()->getAnonField();
-    else
-      return 0;
+    return 0;
   }
=20
   IndirectFieldDecl *getIndirectMember() const {
     if (isIndirectMemberInitializer())
       return Initializee.get<IndirectFieldDecl*>();
-    else
-      return 0;
+    return 0;
   }
=20
-  CXXConstructorDecl *getTargetConstructor() const {
-    if (isDelegatingInitializer())
-      return Initializee.get<CXXConstructorDecl*>();
-    else
-      return 0;
-  }
-
-  SourceLocation getMemberLocation() const {=20
+  SourceLocation getMemberLocation() const {
     return MemberOrEllipsisLocation;
   }
- =20
+
   /// \brief Determine the source location of the initializer.
   SourceLocation getSourceLocation() const;
- =20
+
   /// \brief Determine the source range covering the entire initializer.
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   /// isWritten - Returns true if this initializer is explicitly written
   /// in the source code.
@@ -1656,7 +1894,7 @@
     return IsWritten ? 0 : SourceOrderOrNumArrayIndices;
   }
=20
-  /// \brief Retrieve a particular array index variable used to=20
+  /// \brief Retrieve a particular array index variable used to
   /// describe an array member initialization.
   VarDecl *getArrayIndex(unsigned I) {
     assert(I < getNumArrayIndices() && "Out of bounds member array index");
@@ -1670,7 +1908,12 @@
     assert(I < getNumArrayIndices() && "Out of bounds member array index");
     reinterpret_cast<VarDecl **>(this + 1)[I] =3D Index;
   }
- =20
+  ArrayRef<VarDecl *> getArrayIndexes() {
+    assert(getNumArrayIndices() !=3D 0 && "Getting indexes for non-array i=
nit");
+    return ArrayRef<VarDecl *>(reinterpret_cast<VarDecl **>(this + 1),
+                               getNumArrayIndices());
+  }
+
   /// \brief Get the initializer. This is 0 if this is an in-class initial=
izer
   /// for a non-static data member which has not yet been parsed.
   Expr *getInit() const {
@@ -1691,6 +1934,7 @@
 /// };
 /// @endcode
 class CXXConstructorDecl : public CXXMethodDecl {
+  virtual void anchor();
   /// IsExplicitSpecified - Whether this constructor declaration has the
   /// 'explicit' keyword specified.
   bool IsExplicitSpecified : 1;
@@ -1712,7 +1956,7 @@
   CXXConstructorDecl(CXXRecordDecl *RD, SourceLocation StartLoc,
                      const DeclarationNameInfo &NameInfo,
                      QualType T, TypeSourceInfo *TInfo,
-                     bool isExplicitSpecified, bool isInline,=20
+                     bool isExplicitSpecified, bool isInline,
                      bool isImplicitlyDeclared, bool isConstexpr)
     : CXXMethodDecl(CXXConstructor, RD, StartLoc, NameInfo, T, TInfo, fals=
e,
                     SC_None, isInline, isConstexpr, SourceLocation()),
@@ -1722,7 +1966,7 @@
   }
=20
 public:
-  static CXXConstructorDecl *Create(ASTContext &C, EmptyShell Empty);
+  static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID=
);
   static CXXConstructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
                                     SourceLocation StartLoc,
                                     const DeclarationNameInfo &NameInfo,
@@ -1734,7 +1978,7 @@
   /// isExplicitSpecified - Whether this constructor declaration has the
   /// 'explicit' keyword specified.
   bool isExplicitSpecified() const { return IsExplicitSpecified; }
- =20
+
   /// isExplicit - Whether this constructor was marked "explicit" or not.
   bool isExplicit() const {
     return cast<CXXConstructorDecl>(getFirstDeclaration())
@@ -1782,7 +2026,8 @@
   }
=20
   typedef std::reverse_iterator<init_iterator> init_reverse_iterator;
-  typedef std::reverse_iterator<init_const_iterator> init_const_reverse_it=
erator;
+  typedef std::reverse_iterator<init_const_iterator>
+          init_const_reverse_iterator;
=20
   init_reverse_iterator init_rbegin() {
     return init_reverse_iterator(init_end());
@@ -1821,11 +2066,7 @@
=20
   /// getTargetConstructor - When this constructor delegates to
   /// another, retrieve the target
-  CXXConstructorDecl *getTargetConstructor() const {
-    assert(isDelegatingConstructor() &&
-           "A non-delegating constructor has no target");
-    return CtorInitializers[0]->getTargetConstructor();
-  }
+  CXXConstructorDecl *getTargetConstructor() const;
=20
   /// isDefaultConstructor - Whether this constructor is a default
   /// constructor (C++ [class.ctor]p5), which can be used to
@@ -1902,12 +2143,12 @@
   CXXConstructorDecl *getCanonicalDecl() {
     return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
   }
- =20
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const CXXConstructorDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D CXXConstructor; }
- =20
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
 };
@@ -1922,6 +2163,7 @@
 /// };
 /// @endcode
 class CXXDestructorDecl : public CXXMethodDecl {
+  virtual void anchor();
   /// ImplicitlyDefined - Whether this destructor was implicitly
   /// defined by the compiler. When false, the destructor was defined
   /// by the user. In C++03, this flag will have the same value as
@@ -1931,7 +2173,7 @@
   bool ImplicitlyDefined : 1;
=20
   FunctionDecl *OperatorDelete;
- =20
+
   CXXDestructorDecl(CXXRecordDecl *RD, SourceLocation StartLoc,
                     const DeclarationNameInfo &NameInfo,
                     QualType T, TypeSourceInfo *TInfo,
@@ -1943,13 +2185,13 @@
   }
=20
 public:
-  static CXXDestructorDecl *Create(ASTContext& C, EmptyShell Empty);
   static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
                                    SourceLocation StartLoc,
                                    const DeclarationNameInfo &NameInfo,
                                    QualType T, TypeSourceInfo* TInfo,
                                    bool isInline,
                                    bool isImplicitlyDeclared);
+  static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID=
);
=20
   /// isImplicitlyDefined - Whether this destructor was implicitly
   /// defined. If false, then this destructor was defined by the
@@ -1957,7 +2199,8 @@
   /// already been defined.
   bool isImplicitlyDefined() const {
     assert(isThisDeclarationADefinition() &&
-           "Can only get the implicit-definition flag once the destructor =
has been defined");
+           "Can only get the implicit-definition flag once the destructor =
has "
+           "been defined");
     return ImplicitlyDefined;
   }
=20
@@ -1965,7 +2208,8 @@
   /// implicitly defined or not.
   void setImplicitlyDefined(bool ID) {
     assert(isThisDeclarationADefinition() &&
-           "Can only set the implicit-definition flag once the destructor =
has been defined");
+           "Can only set the implicit-definition flag once the destructor =
has "
+           "been defined");
     ImplicitlyDefined =3D ID;
   }
=20
@@ -1976,7 +2220,7 @@
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const CXXDestructorDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D CXXDestructor; }
- =20
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
 };
@@ -1991,7 +2235,8 @@
 /// };
 /// @endcode
 class CXXConversionDecl : public CXXMethodDecl {
-  /// IsExplicitSpecified - Whether this conversion function declaration i=
s=20
+  virtual void anchor();
+  /// IsExplicitSpecified - Whether this conversion function declaration is
   /// marked "explicit", meaning that it can only be applied when the user
   /// explicitly wrote a cast. This is a C++0x feature.
   bool IsExplicitSpecified : 1;
@@ -2006,7 +2251,6 @@
       IsExplicitSpecified(isExplicitSpecified) { }
=20
 public:
-  static CXXConversionDecl *Create(ASTContext &C, EmptyShell Empty);
   static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD,
                                    SourceLocation StartLoc,
                                    const DeclarationNameInfo &NameInfo,
@@ -2014,8 +2258,9 @@
                                    bool isInline, bool isExplicit,
                                    bool isConstexpr,
                                    SourceLocation EndLocation);
-
-  /// IsExplicitSpecified - Whether this conversion function declaration i=
s=20
+  static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+
+  /// IsExplicitSpecified - Whether this conversion function declaration is
   /// marked "explicit", meaning that it can only be applied when the user
   /// explicitly wrote a cast. This is a C++0x feature.
   bool isExplicitSpecified() const { return IsExplicitSpecified; }
@@ -2034,11 +2279,15 @@
     return getType()->getAs<FunctionType>()->getResultType();
   }
=20
+  /// \brief Determine whether this conversion function is a conversion fr=
om
+  /// a lambda closure type to a block pointer.
+  bool isLambdaToBlockPointerConversion() const;
+ =20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const CXXConversionDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D CXXConversion; }
- =20
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
 };
@@ -2047,6 +2296,7 @@
 ///   extern "C" void foo();
 ///
 class LinkageSpecDecl : public Decl, public DeclContext {
+  virtual void anchor();
 public:
   /// LanguageIDs - Used to represent the language in a linkage
   /// specification.  The values are part of the serialization abi for
@@ -2076,7 +2326,8 @@
                                  SourceLocation ExternLoc,
                                  SourceLocation LangLoc, LanguageIDs Lang,
                                  SourceLocation RBraceLoc =3D SourceLocati=
on());
-
+  static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   /// \brief Return the language specified by this linkage specification.
   LanguageIDs getLanguage() const { return Language; }
   /// \brief Set the language specified by this linkage specification.
@@ -2091,7 +2342,7 @@
   void setExternLoc(SourceLocation L) { ExternLoc =3D L; }
   void setRBraceLoc(SourceLocation L) { RBraceLoc =3D L; }
=20
-  SourceLocation getLocEnd() const {
+  SourceLocation getLocEnd() const LLVM_READONLY {
     if (hasBraces())
       return getRBraceLoc();
     // No braces: get the end location of the (only) declaration in context
@@ -2099,7 +2350,7 @@
     return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(ExternLoc, getLocEnd());
   }
=20
@@ -2119,12 +2370,13 @@
 ///    using namespace std;
 ///
 // NB: UsingDirectiveDecl should be Decl not NamedDecl, but we provide
-// artificial name, for all using-directives in order to store
+// artificial names for all using-directives in order to store
 // them in DeclContext effectively.
 class UsingDirectiveDecl : public NamedDecl {
+  virtual void anchor();
   /// \brief The location of the "using" keyword.
   SourceLocation UsingLoc;
- =20
+
   /// SourceLocation - Location of 'namespace' token.
   SourceLocation NamespaceLoc;
=20
@@ -2159,11 +2411,11 @@
   /// \brief Retrieve the nested-name-specifier that qualifies the
   /// name of the namespace, with source-location information.
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
- =20
+
   /// \brief Retrieve the nested-name-specifier that qualifies the
   /// name of the namespace.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
=20
   NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace;=
 }
@@ -2185,7 +2437,7 @@
=20
   /// \brief Return the location of the "using" keyword.
   SourceLocation getUsingLoc() const { return UsingLoc; }
- =20
+
   // FIXME: Could omit 'Key' in name.
   /// getNamespaceKeyLocation - Returns location of namespace keyword.
   SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
@@ -2200,18 +2452,19 @@
                                     SourceLocation IdentLoc,
                                     NamedDecl *Nominated,
                                     DeclContext *CommonAncestor);
-
-  SourceRange getSourceRange() const {
+  static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID=
);
+ =20
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(UsingLoc, getLocation());
   }
- =20
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const UsingDirectiveDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D UsingDirective; }
=20
   // Friend for getUsingDirectiveName.
   friend class DeclContext;
- =20
+
   friend class ASTDeclReader;
 };
=20
@@ -2221,15 +2474,17 @@
 /// namespace Foo =3D Bar;
 /// @endcode
 class NamespaceAliasDecl : public NamedDecl {
+  virtual void anchor();
+
   /// \brief The location of the "namespace" keyword.
   SourceLocation NamespaceLoc;
=20
   /// IdentLoc - Location of namespace identifier. Accessed by TargetNameL=
oc.
   SourceLocation IdentLoc;
- =20
+
   /// \brief The nested-name-specifier that precedes the namespace.
   NestedNameSpecifierLoc QualifierLoc;
- =20
+
   /// Namespace - The Decl that this alias points to. Can either be a
   /// NamespaceDecl or a NamespaceAliasDecl.
   NamedDecl *Namespace;
@@ -2238,23 +2493,23 @@
                      SourceLocation AliasLoc, IdentifierInfo *Alias,
                      NestedNameSpecifierLoc QualifierLoc,
                      SourceLocation IdentLoc, NamedDecl *Namespace)
-    : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias),=20
+    : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias),
       NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
       QualifierLoc(QualifierLoc), Namespace(Namespace) { }
=20
   friend class ASTDeclReader;
- =20
+
 public:
   /// \brief Retrieve the nested-name-specifier that qualifies the
   /// name of the namespace, with source-location information.
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
- =20
+
   /// \brief Retrieve the nested-name-specifier that qualifies the
   /// name of the namespace.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
- =20
+
   /// \brief Retrieve the namespace declaration aliased by this directive.
   NamespaceDecl *getNamespace() {
     if (NamespaceAliasDecl *AD =3D dyn_cast<NamespaceAliasDecl>(Namespace))
@@ -2282,17 +2537,19 @@
   NamedDecl *getAliasedNamespace() const { return Namespace; }
=20
   static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
-                                    SourceLocation NamespaceLoc,=20
+                                    SourceLocation NamespaceLoc,
                                     SourceLocation AliasLoc,
                                     IdentifierInfo *Alias,
                                     NestedNameSpecifierLoc QualifierLoc,
                                     SourceLocation IdentLoc,
                                     NamedDecl *Namespace);
=20
-  virtual SourceRange getSourceRange() const {
+  static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID=
);
+ =20
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(NamespaceLoc, IdentLoc);
   }
- =20
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const NamespaceAliasDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D NamespaceAlias; }
@@ -2310,6 +2567,8 @@
 /// }
 ///
 class UsingShadowDecl : public NamedDecl {
+  virtual void anchor();
+
   /// The referenced declaration.
   NamedDecl *Underlying;
=20
@@ -2337,6 +2596,8 @@
     return new (C) UsingShadowDecl(DC, Loc, Using, Target);
   }
=20
+  static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   /// \brief Gets the underlying declaration which has been brought into t=
he
   /// local scope.
   NamedDecl *getTargetDecl() const { return Underlying; }
@@ -2369,6 +2630,8 @@
 /// UsingDecl - Represents a C++ using-declaration. For example:
 ///    using someNameSpace::someIdentifier;
 class UsingDecl : public NamedDecl {
+  virtual void anchor();
+
   /// \brief The source location of the "using" location itself.
   SourceLocation UsingLocation;
=20
@@ -2380,18 +2643,16 @@
   DeclarationNameLoc DNLoc;
=20
   /// \brief The first shadow declaration of the shadow decl chain associa=
ted
-  /// with this using declaration.
-  UsingShadowDecl *FirstUsingShadow;
-
-  // \brief Has 'typename' keyword.
-  bool IsTypeName;
-
-  UsingDecl(DeclContext *DC, SourceLocation UL,=20
+  /// with this using declaration. The bool member of the pair store wheth=
er
+  /// this decl has the 'typename' keyword.
+  llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
+
+  UsingDecl(DeclContext *DC, SourceLocation UL,
             NestedNameSpecifierLoc QualifierLoc,
             const DeclarationNameInfo &NameInfo, bool IsTypeNameArg)
     : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
       UsingLocation(UL), QualifierLoc(QualifierLoc),
-      DNLoc(NameInfo.getInfo()), FirstUsingShadow(0),IsTypeName(IsTypeName=
Arg) {
+      DNLoc(NameInfo.getInfo()), FirstUsingShadow(0, IsTypeNameArg) {
   }
=20
 public:
@@ -2406,8 +2667,8 @@
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
=20
   /// \brief Retrieve the nested-name-specifier that qualifies the name.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
=20
   DeclarationNameInfo getNameInfo() const {
@@ -2415,10 +2676,10 @@
   }
=20
   /// \brief Return true if the using declaration has 'typename'.
-  bool isTypeName() const { return IsTypeName; }
+  bool isTypeName() const { return FirstUsingShadow.getInt(); }
=20
   /// \brief Sets whether the using declaration has 'typename'.
-  void setTypeName(bool TN) { IsTypeName =3D TN; }
+  void setTypeName(bool TN) { FirstUsingShadow.setInt(TN); }
=20
   /// \brief Iterates through the using shadow declarations assosiated with
   /// this using declaration.
@@ -2459,7 +2720,7 @@
   };
=20
   shadow_iterator shadow_begin() const {
-    return shadow_iterator(FirstUsingShadow);
+    return shadow_iterator(FirstUsingShadow.getPointer());
   }
   shadow_iterator shadow_end() const { return shadow_iterator(); }
=20
@@ -2478,7 +2739,9 @@
                            const DeclarationNameInfo &NameInfo,
                            bool IsTypeNameArg);
=20
-  SourceRange getSourceRange() const {
+  static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(UsingLocation, getNameInfo().getEndLoc());
   }
=20
@@ -2499,6 +2762,8 @@
 ///   using Base<T>::foo;
 /// };
 class UnresolvedUsingValueDecl : public ValueDecl {
+  virtual void anchor();
+
   /// \brief The source location of the 'using' keyword
   SourceLocation UsingLocation;
=20
@@ -2510,7 +2775,7 @@
   DeclarationNameLoc DNLoc;
=20
   UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
-                           SourceLocation UsingLoc,=20
+                           SourceLocation UsingLoc,
                            NestedNameSpecifierLoc QualifierLoc,
                            const DeclarationNameInfo &NameInfo)
     : ValueDecl(UnresolvedUsingValue, DC,
@@ -2531,20 +2796,23 @@
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
=20
   /// \brief Retrieve the nested-name-specifier that qualifies the name.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
- =20
+
   DeclarationNameInfo getNameInfo() const {
     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
   }
=20
   static UnresolvedUsingValueDecl *
     Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
-           NestedNameSpecifierLoc QualifierLoc,=20
+           NestedNameSpecifierLoc QualifierLoc,
            const DeclarationNameInfo &NameInfo);
=20
-  SourceRange getSourceRange() const {
+  static UnresolvedUsingValueDecl *
+  CreateDeserialized(ASTContext &C, unsigned ID);
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(UsingLocation, getNameInfo().getEndLoc());
   }
=20
@@ -2566,6 +2834,8 @@
 /// The type associated with a unresolved using typename decl is
 /// currently always a typename type.
 class UnresolvedUsingTypenameDecl : public TypeDecl {
+  virtual void anchor();
+
   /// \brief The source location of the 'using' keyword
   SourceLocation UsingLocation;
=20
@@ -2578,14 +2848,14 @@
   UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
                               SourceLocation TypenameLoc,
                               NestedNameSpecifierLoc QualifierLoc,
-                              SourceLocation TargetNameLoc,=20
+                              SourceLocation TargetNameLoc,
                               IdentifierInfo *TargetName)
     : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
                UsingLoc),
       TypenameLocation(TypenameLoc), QualifierLoc(QualifierLoc) { }
=20
   friend class ASTDeclReader;
- =20
+
 public:
   /// \brief Returns the source location of the 'using' keyword.
   SourceLocation getUsingLoc() const { return getLocStart(); }
@@ -2598,8 +2868,8 @@
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
=20
   /// \brief Retrieve the nested-name-specifier that qualifies the name.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
=20
   static UnresolvedUsingTypenameDecl *
@@ -2607,6 +2877,9 @@
            SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
            SourceLocation TargetNameLoc, DeclarationName TargetName);
=20
+  static UnresolvedUsingTypenameDecl *
+  CreateDeserialized(ASTContext &C, unsigned ID);
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const UnresolvedUsingTypenameDecl *D) { return true;=
 }
   static bool classofKind(Kind K) { return K =3D=3D UnresolvedUsingTypenam=
e; }
@@ -2614,6 +2887,7 @@
=20
 /// StaticAssertDecl - Represents a C++0x static_assert declaration.
 class StaticAssertDecl : public Decl {
+  virtual void anchor();
   Expr *AssertExpr;
   StringLiteral *Message;
   SourceLocation RParenLoc;
@@ -2629,7 +2903,8 @@
                                   SourceLocation StaticAssertLoc,
                                   Expr *AssertExpr, StringLiteral *Message,
                                   SourceLocation RParenLoc);
-
+  static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   Expr *getAssertExpr() { return AssertExpr; }
   const Expr *getAssertExpr() const { return AssertExpr; }
=20
@@ -2639,7 +2914,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getLocation(), getRParenLoc());
   }
=20
@@ -2655,6 +2930,9 @@
 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
                                     AccessSpecifier AS);
=20
+const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
+                                    AccessSpecifier AS);
+
 } // end namespace clang
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DeclFriend.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DeclFriend.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DeclFriend.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #define LLVM_CLANG_AST_DECLFRIEND_H
=20
 #include "clang/AST/DeclCXX.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
=20
@@ -35,6 +36,7 @@
 ///
 /// The semantic context of a friend decl is its declaring class.
 class FriendDecl : public Decl {
+  virtual void anchor();
 public:
   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
=20
@@ -77,7 +79,7 @@
   static FriendDecl *Create(ASTContext &C, DeclContext *DC,
                             SourceLocation L, FriendUnion Friend_,
                             SourceLocation FriendL);
-  static FriendDecl *Create(ASTContext &C, EmptyShell Empty);
+  static FriendDecl *CreateDeserialized(ASTContext &C, unsigned ID);
=20
   /// If this friend declaration names an (untemplated but possibly
   /// dependent) type, return the type; otherwise return null.  This
@@ -99,7 +101,7 @@
   }
=20
   /// Retrieves the source range for the friend declaration.
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     /* FIXME: consider the case of templates wrt start of range. */
     if (NamedDecl *ND =3D getFriendDecl())
       return SourceRange(getFriendLoc(), ND->getLocEnd());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DeclObjC.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DeclObjC.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DeclObjC.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/SelectorLocationsKind.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
 class Expr;
@@ -84,7 +85,7 @@
   loc_iterator loc_begin() const { return Locations; }
   loc_iterator loc_end() const { return Locations + size(); }
=20
-  void set(ObjCProtocolDecl* const* InList, unsigned Elts,=20
+  void set(ObjCProtocolDecl* const* InList, unsigned Elts,
            const SourceLocation *Locs, ASTContext &Ctx);
 };
=20
@@ -124,7 +125,7 @@
=20
   // Synthesized declaration method for a property setter/getter
   unsigned IsSynthesized : 1;
- =20
+
   // Method has a definition.
   unsigned IsDefined : 1;
=20
@@ -144,14 +145,14 @@
=20
   /// \brief Indicates whether this method has a related result type.
   unsigned RelatedResultType : 1;
- =20
+
   /// \brief Whether the locations of the selector identifiers are in a
   /// "standard" position, a enum SelectorLocationsKind.
   unsigned SelLocsKind : 2;
=20
   // Result type of this method.
   QualType MethodDeclType;
- =20
+
   // Type source information for the result type.
   TypeSourceInfo *ResultTInfo;
=20
@@ -246,7 +247,7 @@
                                 SourceLocation beginLoc,
                                 SourceLocation endLoc,
                                 Selector SelInfo,
-                                QualType T,=20
+                                QualType T,
                                 TypeSourceInfo *ResultTInfo,
                                 DeclContext *contextDecl,
                                 bool isInstance =3D true,
@@ -257,6 +258,8 @@
                                 ImplementationControl impControl =3D None,
                                 bool HasRelatedResultType =3D false);
=20
+  static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   virtual ObjCMethodDecl *getCanonicalDecl();
   const ObjCMethodDecl *getCanonicalDecl() const {
     return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
@@ -270,23 +273,27 @@
   /// \brief Determine whether this method has a result type that is relat=
ed
   /// to the message receiver's type.
   bool hasRelatedResultType() const { return RelatedResultType; }
- =20
+
   /// \brief Note whether this method has a related result type.
   void SetRelatedResultType(bool RRT =3D true) { RelatedResultType =3D RRT=
; }
=20
   /// \brief True if this is a method redeclaration in the same interface.
   bool isRedeclaration() const { return IsRedeclaration; }
   void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
- =20
+
   // Location information, modeled after the Stmt API.
-  SourceLocation getLocStart() const { return getLocation(); }
-  SourceLocation getLocEnd() const { return EndLoc; }
+  SourceLocation getLocStart() const LLVM_READONLY { return getLocation();=
 }
+  SourceLocation getLocEnd() const LLVM_READONLY { return EndLoc; }
   void setEndLoc(SourceLocation Loc) { EndLoc =3D Loc; }
-  virtual SourceRange getSourceRange() const {
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getLocation(), EndLoc);
   }
=20
-  SourceLocation getSelectorStartLoc() const { return getSelectorLoc(0); }
+  SourceLocation getSelectorStartLoc() const {
+    if (isImplicit())
+      return getLocStart();
+    return getSelectorLoc(0);
+  }
   SourceLocation getSelectorLoc(unsigned Index) const {
     assert(Index < getNumSelectorLocs() && "Index out of range!");
     if (hasStandardSelLocs())
@@ -319,12 +326,12 @@
   QualType getResultType() const { return MethodDeclType; }
   void setResultType(QualType T) { MethodDeclType =3D T; }
=20
-  /// \brief Determine the type of an expression that sends a message to t=
his=20
+  /// \brief Determine the type of an expression that sends a message to t=
his
   /// function.
   QualType getSendResultType() const {
     return getResultType().getNonLValueExprType(getASTContext());
   }
- =20
+
   TypeSourceInfo *getResultTypeSourceInfo() const { return ResultTInfo; }
   void setResultTypeSourceInfo(TypeSourceInfo *TInfo) { ResultTInfo =3D TI=
nfo; }
=20
@@ -338,8 +345,8 @@
   param_iterator param_end() { return getParams() + NumParams; }
   // This method returns and of the parameters which are part of the selec=
tor
   // name mangling requirements.
-  param_const_iterator sel_param_end() const {=20
-    return param_begin() + getSelector().getNumArgs();=20
+  param_const_iterator sel_param_end() const {
+    return param_begin() + getSelector().getNumArgs();
   }
=20
   /// \brief Sets the method's parameters and selector source locations.
@@ -385,7 +392,7 @@
=20
   bool isSynthesized() const { return IsSynthesized; }
   void setSynthesized(bool isSynth) { IsSynthesized =3D isSynth; }
- =20
+
   bool isDefined() const { return IsDefined; }
   void setDefined(bool isDefined) { IsDefined =3D isDefined; }
=20
@@ -426,6 +433,8 @@
 /// ObjCProtocolDecl, and ObjCImplDecl.
 ///
 class ObjCContainerDecl : public NamedDecl, public DeclContext {
+  virtual void anchor();
+
   SourceLocation AtStart;
=20
   // These two locations in the range mark the end of the method container.
@@ -499,7 +508,7 @@
     AtEnd =3D atEnd;
   }
=20
-  virtual SourceRange getSourceRange() const {
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtStart, getAtEndRange().getEnd());
   }
=20
@@ -540,64 +549,113 @@
 ///   Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
 ///   typically inherit from NSObject (an exception is NSProxy).
 ///
-class ObjCInterfaceDecl : public ObjCContainerDecl {
+class ObjCInterfaceDecl : public ObjCContainerDecl
+                        , public Redeclarable<ObjCInterfaceDecl> {
+  virtual void anchor();
+
   /// TypeForDecl - This indicates the Type object that represents this
   /// TypeDecl.  It is a cache maintained by ASTContext::getObjCInterfaceT=
ype
   mutable const Type *TypeForDecl;
   friend class ASTContext;
+ =20
+  struct DefinitionData {
+    /// \brief The definition of this class, for quick access from any=20
+    /// declaration.
+    ObjCInterfaceDecl *Definition;
+   =20
+    /// Class's super class.
+    ObjCInterfaceDecl *SuperClass;
=20
-  /// Class's super class.
-  ObjCInterfaceDecl *SuperClass;
+    /// Protocols referenced in the @interface  declaration
+    ObjCProtocolList ReferencedProtocols;
=20
-  /// Protocols referenced in the @interface  declaration
-  ObjCProtocolList ReferencedProtocols;
- =20
-  /// Protocols reference in both the @interface and class extensions.
-  ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
+    /// Protocols reference in both the @interface and class extensions.
+    ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
=20
-  /// \brief List of categories and class extensions defined for this clas=
s.
-  ///
-  /// Categories are stored as a linked list in the AST, since the categor=
ies
-  /// and class extensions come long after the initial interface declarati=
on,
-  /// and we avoid dynamically-resized arrays in the AST wherever possible.
-  ObjCCategoryDecl *CategoryList;
- =20
-  /// IvarList - List of all ivars defined by this class; including class
-  /// extensions and implementation. This list is built lazily.
-  ObjCIvarDecl *IvarList;
+    /// \brief List of categories and class extensions defined for this cl=
ass.
+    ///
+    /// Categories are stored as a linked list in the AST, since the categ=
ories
+    /// and class extensions come long after the initial interface declara=
tion,
+    /// and we avoid dynamically-resized arrays in the AST wherever possib=
le.
+    ObjCCategoryDecl *CategoryList;
=20
-  bool ForwardDecl:1; // declared with @class.
-  bool InternalInterface:1; // true - no @interface for @implementation
- =20
-  /// \brief Indicates that the contents of this Objective-C class will be
-  /// completed by the external AST source when required.
-  mutable bool ExternallyCompleted : 1;
- =20
-  SourceLocation SuperClassLoc; // location of the super class identifier.
-  SourceLocation EndLoc; // marks the '>', '}', or identifier.
+    /// IvarList - List of all ivars defined by this class; including class
+    /// extensions and implementation. This list is built lazily.
+    ObjCIvarDecl *IvarList;
+
+    /// \brief Indicates that the contents of this Objective-C class will =
be
+    /// completed by the external AST source when required.
+    mutable bool ExternallyCompleted : 1;
+
+    /// \brief The location of the superclass, if any.
+    SourceLocation SuperClassLoc;
+   =20
+    /// \brief The location of the last location in this declaration, befo=
re
+    /// the properties/methods. For example, this will be the '>', '}', or=20
+    /// identifier,=20
+    SourceLocation EndLoc;=20
+
+    DefinitionData() : Definition(), SuperClass(), CategoryList(), IvarLis=
t(),=20
+                       ExternallyCompleted() { }
+  };
=20
   ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo =
*Id,
-                    SourceLocation CLoc, bool FD, bool isInternal);
+                    SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
+                    bool isInternal);
=20
   void LoadExternalDefinition() const;
+
+  /// \brief Contains a pointer to the data associated with this class,
+  /// which will be NULL if this class has not yet been defined.
+  DefinitionData *Data;
+
+  DefinitionData &data() const {
+    assert(Data !=3D 0 && "Declaration has no definition!");
+    return *Data;
+  }
+
+  /// \brief Allocate the definition data for this class.
+  void allocateDefinitionData();
+ =20
+  typedef Redeclarable<ObjCInterfaceDecl> redeclarable_base;
+  virtual ObjCInterfaceDecl *getNextRedeclaration() {=20
+    return RedeclLink.getNext();=20
+  }
+  virtual ObjCInterfaceDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
+  }
+  virtual ObjCInterfaceDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
+  }
+
 public:
-  static ObjCInterfaceDecl *Create(ASTContext &C, DeclContext *DC,
+  static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
                                    SourceLocation atLoc,
                                    IdentifierInfo *Id,
+                                   ObjCInterfaceDecl *PrevDecl,
                                    SourceLocation ClassLoc =3D SourceLocat=
ion(),
-                                   bool ForwardDecl =3D false,
                                    bool isInternal =3D false);
- =20
+
+  static ObjCInterfaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
+    if (isThisDeclarationADefinition())
+      return ObjCContainerDecl::getSourceRange();
+   =20
+    return SourceRange(getAtStartLoc(), getLocation());
+  }
+
   /// \brief Indicate that this Objective-C class is complete, but that
   /// the external AST source will be responsible for filling in its conte=
nts
   /// when a complete class is required.
   void setExternallyCompleted();
- =20
+
   const ObjCProtocolList &getReferencedProtocols() const {
-    if (ExternallyCompleted)
+    assert(hasDefinition() && "Caller did not check for forward reference!=
");
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
-   =20
-    return ReferencedProtocols;
+
+    return data().ReferencedProtocols;
   }
=20
   ObjCImplementationDecl *getImplementation() const;
@@ -614,108 +672,182 @@
   }
=20
   typedef ObjCProtocolList::iterator protocol_iterator;
- =20
+
   protocol_iterator protocol_begin() const {
-    if (ExternallyCompleted)
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return protocol_iterator();
+   =20
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return ReferencedProtocols.begin();
+    return data().ReferencedProtocols.begin();
   }
   protocol_iterator protocol_end() const {
-    if (ExternallyCompleted)
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return protocol_iterator();
+
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return ReferencedProtocols.end();
+    return data().ReferencedProtocols.end();
   }
=20
   typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
=20
-  protocol_loc_iterator protocol_loc_begin() const {=20
-    if (ExternallyCompleted)
+  protocol_loc_iterator protocol_loc_begin() const {
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return protocol_loc_iterator();
+
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return ReferencedProtocols.loc_begin();=20
+    return data().ReferencedProtocols.loc_begin();
   }
=20
-  protocol_loc_iterator protocol_loc_end() const {=20
-    if (ExternallyCompleted)
+  protocol_loc_iterator protocol_loc_end() const {
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return protocol_loc_iterator();
+
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return ReferencedProtocols.loc_end();=20
+    return data().ReferencedProtocols.loc_end();
   }
- =20
+
   typedef ObjCList<ObjCProtocolDecl>::iterator all_protocol_iterator;
- =20
+
   all_protocol_iterator all_referenced_protocol_begin() const {
-    if (ExternallyCompleted)
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return all_protocol_iterator();
+
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return AllReferencedProtocols.empty() ? protocol_begin()
-      : AllReferencedProtocols.begin();
+    return data().AllReferencedProtocols.empty() =20
+             ? protocol_begin()
+             : data().AllReferencedProtocols.begin();
   }
   all_protocol_iterator all_referenced_protocol_end() const {
-    if (ExternallyCompleted)
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return all_protocol_iterator();
+   =20
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return AllReferencedProtocols.empty() ? protocol_end()=20
-      : AllReferencedProtocols.end();
+    return data().AllReferencedProtocols.empty()=20
+             ? protocol_end()
+             : data().AllReferencedProtocols.end();
   }
=20
   typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
=20
-  ivar_iterator ivar_begin() const { return ivar_iterator(decls_begin()); }
-  ivar_iterator ivar_end() const { return ivar_iterator(decls_end()); }
+  ivar_iterator ivar_begin() const {=20
+    if (const ObjCInterfaceDecl *Def =3D getDefinition())
+      return ivar_iterator(Def->decls_begin());=20
+   =20
+    // FIXME: Should make sure no callers ever do this.
+    return ivar_iterator();
+  }
+  ivar_iterator ivar_end() const {=20
+    if (const ObjCInterfaceDecl *Def =3D getDefinition())
+      return ivar_iterator(Def->decls_end());=20
+
+    // FIXME: Should make sure no callers ever do this.
+    return ivar_iterator();
+  }
=20
   unsigned ivar_size() const {
     return std::distance(ivar_begin(), ivar_end());
   }
- =20
+
   bool ivar_empty() const { return ivar_begin() =3D=3D ivar_end(); }
- =20
+
   ObjCIvarDecl *all_declared_ivar_begin();
   const ObjCIvarDecl *all_declared_ivar_begin() const {
     // Even though this modifies IvarList, it's conceptually const:
     // the ivar chain is essentially a cached property of ObjCInterfaceDec=
l.
     return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin(=
);
   }
-  void setIvarList(ObjCIvarDecl *ivar) { IvarList =3D ivar; }
- =20
+  void setIvarList(ObjCIvarDecl *ivar) { data().IvarList =3D ivar; }
+
   /// setProtocolList - Set the list of protocols that this interface
   /// implements.
   void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
                        const SourceLocation *Locs, ASTContext &C) {
-    ReferencedProtocols.set(List, Num, Locs, C);
+    data().ReferencedProtocols.set(List, Num, Locs, C);
   }
=20
   /// mergeClassExtensionProtocolList - Merge class extension's protocol l=
ist
   /// into the protocol list for this class.
-  void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,=20
+  void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
                                        unsigned Num,
                                        ASTContext &C);
=20
-  bool isForwardDecl() const { return ForwardDecl; }
-  void setForwardDecl(bool val) { ForwardDecl =3D val; }
+  /// \brief Determine whether this particular declaration of this class is
+  /// actually also a definition.
+  bool isThisDeclarationADefinition() const {=20
+    return Data && Data->Definition =3D=3D this;
+  }
+                         =20
+  /// \brief Determine whether this class has been defined.
+  bool hasDefinition() const { return Data; }
+                       =20
+  /// \brief Retrieve the definition of this class, or NULL if this class=20
+  /// has been forward-declared (with @class) but not yet defined (with=20
+  /// @interface).
+  ObjCInterfaceDecl *getDefinition() {
+    return hasDefinition()? Data->Definition : 0;
+  }
=20
-  ObjCInterfaceDecl *getSuperClass() const {=20
-    if (ExternallyCompleted)
+  /// \brief Retrieve the definition of this class, or NULL if this class=20
+  /// has been forward-declared (with @class) but not yet defined (with=20
+  /// @interface).
+  const ObjCInterfaceDecl *getDefinition() const {
+    return hasDefinition()? Data->Definition : 0;
+  }
+
+  /// \brief Starts the definition of this Objective-C class, taking it fr=
om
+  /// a forward declaration (@class) to a definition (@interface).
+  void startDefinition();
+ =20
+  ObjCInterfaceDecl *getSuperClass() const {
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return 0;
+   =20
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return SuperClass;=20
+    return data().SuperClass;
   }
- =20
-  void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass =3D superC=
ls; }
=20
-  ObjCCategoryDecl* getCategoryList() const {=20
-    if (ExternallyCompleted)
+  void setSuperClass(ObjCInterfaceDecl * superCls) {=20
+    data().SuperClass =3D=20
+      (superCls && superCls->hasDefinition()) ? superCls->getDefinition()=20
+                                              : superCls;=20
+  }
+
+  ObjCCategoryDecl* getCategoryList() const {
+    // FIXME: Should make sure no callers ever do this.
+    if (!hasDefinition())
+      return 0;
+   =20
+    if (data().ExternallyCompleted)
       LoadExternalDefinition();
=20
-    return CategoryList;=20
+    return data().CategoryList;
   }
- =20
+
   void setCategoryList(ObjCCategoryDecl *category) {
-    CategoryList =3D category;
+    data().CategoryList =3D category;
   }
- =20
+
   ObjCCategoryDecl* getFirstClassExtension() const;
=20
   ObjCPropertyDecl
@@ -726,8 +858,9 @@
   bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
     // If RHS is derived from LHS it is OK; else it is not OK.
     while (I !=3D NULL) {
-      if (this =3D=3D I)
+      if (declaresSameEntity(this, I))
         return true;
+     =20
       I =3D I->getSuperClass();
     }
     return false;
@@ -742,7 +875,20 @@
         return true;
       Class =3D Class->getSuperClass();
    }
-   return false;=20
+   return false;
+  }
+
+  /// isObjCRequiresPropertyDefs - Checks that a class or one of its super=20
+  /// classes must not be auto-synthesized. Returns class decl. if it must=
 not be;
+  /// 0, otherwise.
+  const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const {
+    const ObjCInterfaceDecl *Class =3D this;
+    while (Class) {
+      if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>())
+        return Class;
+      Class =3D Class->getSuperClass();
+   }
+   return 0;
   }
=20
   ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
@@ -754,31 +900,39 @@
=20
   // Lookup a method. First, we search locally. If a method isn't
   // found, we search referenced protocols and class categories.
-  ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
-  ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
-    return lookupMethod(Sel, true/*isInstance*/);
+  ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
+                               bool shallowCategoryLookup=3D false) const;
+  ObjCMethodDecl *lookupInstanceMethod(Selector Sel,
+                            bool shallowCategoryLookup =3D false) const {
+    return lookupMethod(Sel, true/*isInstance*/, shallowCategoryLookup);
   }
-  ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
-    return lookupMethod(Sel, false/*isInstance*/);
+  ObjCMethodDecl *lookupClassMethod(Selector Sel,
+                     bool shallowCategoryLookup =3D false) const {
+    return lookupMethod(Sel, false/*isInstance*/, shallowCategoryLookup);
   }
   ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
- =20
+
   // Lookup a method in the classes implementation hierarchy.
   ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel, bool Instance=
=3Dtrue);
=20
-  // Location information, modeled after the Stmt API.
-  SourceLocation getLocStart() const { return getAtStartLoc(); } // '@'int=
erface
-  SourceLocation getLocEnd() const { return EndLoc; }
-  void setLocEnd(SourceLocation LE) { EndLoc =3D LE; }
+  SourceLocation getEndOfDefinitionLoc() const {=20
+    if (!hasDefinition())
+      return getLocation();
+   =20
+    return data().EndLoc;=20
+  }
+                         =20
+  void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc =3D LE; }
=20
-  void setSuperClassLoc(SourceLocation Loc) { SuperClassLoc =3D Loc; }
-  SourceLocation getSuperClassLoc() const { return SuperClassLoc; }
+  void setSuperClassLoc(SourceLocation Loc) { data().SuperClassLoc =3D Loc=
; }
+  SourceLocation getSuperClassLoc() const { return data().SuperClassLoc; }
=20
   /// isImplicitInterfaceDecl - check that this is an implicitly declared
   /// ObjCInterfaceDecl node. This is for legacy objective-c @implementati=
on
   /// declaration without an @interface declaration.
-  bool isImplicitInterfaceDecl() const { return InternalInterface; }
-  void setImplicitInterfaceDecl(bool val) { InternalInterface =3D val; }
+  bool isImplicitInterfaceDecl() const {=20
+    return hasDefinition() ? Data->Definition->isImplicit() : isImplicit()=
;=20
+  }
=20
   /// ClassImplementsProtocol - Checks that 'lProto' protocol
   /// has been implemented in IDecl class, its super class or categories (=
if
@@ -787,6 +941,20 @@
                                bool lookupCategory,
                                bool RHSIsQualifiedID =3D false);
=20
+  typedef redeclarable_base::redecl_iterator redecl_iterator;
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
+
+  /// Retrieves the canonical declaration of this Objective-C class.
+  ObjCInterfaceDecl *getCanonicalDecl() {
+    return getFirstDeclaration();
+  }
+  const ObjCInterfaceDecl *getCanonicalDecl() const {
+    return getFirstDeclaration();
+  }
+
   // Low-level accessor
   const Type *getTypeForDecl() const { return TypeForDecl; }
   void setTypeForDecl(const Type *TD) const { TypeForDecl =3D TD; }
@@ -795,6 +963,7 @@
   static bool classof(const ObjCInterfaceDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D ObjCInterface; }
=20
+  friend class ASTReader;
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
 };
@@ -815,6 +984,8 @@
 ///   }
 ///
 class ObjCIvarDecl : public FieldDecl {
+  virtual void anchor();
+
 public:
   enum AccessControl {
     None, Private, Protected, Public, Package
@@ -837,12 +1008,14 @@
                               AccessControl ac, Expr *BW =3D NULL,
                               bool synthesized=3Dfalse);
=20
+  static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   /// \brief Return the class interface that this ivar is logically contai=
ned
   /// in; this is either the interface where the ivar was declared, or the
   /// interface the ivar is conceptually a part of in the case of synthesi=
zed
   /// ivars.
   const ObjCInterfaceDecl *getContainingInterface() const;
- =20
+
   ObjCIvarDecl *getNextIvar() { return NextIvar; }
   const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
   void setNextIvar(ObjCIvarDecl *ivar) { NextIvar =3D ivar; }
@@ -857,16 +1030,16 @@
=20
   void setSynthesize(bool synth) { Synthesized =3D synth; }
   bool getSynthesize() const { return Synthesized; }
- =20
+
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ObjCIvarDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D ObjCIvar; }
 private:
-  /// NextIvar - Next Ivar in the list of ivars declared in class; class's=20
+  /// NextIvar - Next Ivar in the list of ivars declared in class; class's
   /// extensions and class's implementation
   ObjCIvarDecl *NextIvar;
- =20
+
   // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
   unsigned DeclAccess : 3;
   unsigned Synthesized : 1;
@@ -876,7 +1049,7 @@
 /// ObjCAtDefsFieldDecl - Represents a field declaration created by an
 ///  @defs(...).
 class ObjCAtDefsFieldDecl : public FieldDecl {
-private:
+  virtual void anchor();
   ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
                       SourceLocation IdLoc, IdentifierInfo *Id,
                       QualType T, Expr *BW)
@@ -890,6 +1063,8 @@
                                      SourceLocation IdLoc, IdentifierInfo =
*Id,
                                      QualType T, Expr *BW);
=20
+  static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned I=
D);
+ =20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ObjCAtDefsFieldDecl *D) { return true; }
@@ -920,46 +1095,94 @@
 ///
 /// id <NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
 ///
-class ObjCProtocolDecl : public ObjCContainerDecl {
-  /// Referenced protocols
-  ObjCProtocolList ReferencedProtocols;
+class ObjCProtocolDecl : public ObjCContainerDecl,
+                         public Redeclarable<ObjCProtocolDecl> {
+  virtual void anchor();
=20
-  bool isForwardProtoDecl; // declared with @protocol.
+  struct DefinitionData {
+    // \brief The declaration that defines this protocol.
+    ObjCProtocolDecl *Definition;
=20
-  SourceLocation EndLoc; // marks the '>' or identifier.
+    /// \brief Referenced protocols
+    ObjCProtocolList ReferencedProtocols;   =20
+  };
+ =20
+  DefinitionData *Data;
=20
+  DefinitionData &data() const {
+    assert(Data && "Objective-C protocol has no definition!");
+    return *Data;
+  }
+ =20
   ObjCProtocolDecl(DeclContext *DC, IdentifierInfo *Id,
-                   SourceLocation nameLoc, SourceLocation atStartLoc)
-    : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
-      isForwardProtoDecl(true) {
+                   SourceLocation nameLoc, SourceLocation atStartLoc,
+                   ObjCProtocolDecl *PrevDecl);
+
+  void allocateDefinitionData();
+
+  typedef Redeclarable<ObjCProtocolDecl> redeclarable_base;
+  virtual ObjCProtocolDecl *getNextRedeclaration() {=20
+    return RedeclLink.getNext();=20
   }
-
+  virtual ObjCProtocolDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
+  }
+  virtual ObjCProtocolDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
+  }
+                          =20
 public:
   static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
                                   IdentifierInfo *Id,
                                   SourceLocation nameLoc,
-                                  SourceLocation atStartLoc);
+                                  SourceLocation atStartLoc,
+                                  ObjCProtocolDecl *PrevDecl);
=20
+  static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+                          =20
   const ObjCProtocolList &getReferencedProtocols() const {
-    return ReferencedProtocols;
+    assert(hasDefinition() && "No definition available!");
+    return data().ReferencedProtocols;
   }
   typedef ObjCProtocolList::iterator protocol_iterator;
-  protocol_iterator protocol_begin() const {return ReferencedProtocols.beg=
in();}
-  protocol_iterator protocol_end() const { return ReferencedProtocols.end(=
); }
+  protocol_iterator protocol_begin() const {
+    if (!hasDefinition())
+      return protocol_iterator();
+   =20
+    return data().ReferencedProtocols.begin();
+  }
+  protocol_iterator protocol_end() const {=20
+    if (!hasDefinition())
+      return protocol_iterator();
+   =20
+    return data().ReferencedProtocols.end();=20
+  }
   typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
-  protocol_loc_iterator protocol_loc_begin() const {=20
-    return ReferencedProtocols.loc_begin();=20
+  protocol_loc_iterator protocol_loc_begin() const {
+    if (!hasDefinition())
+      return protocol_loc_iterator();
+   =20
+    return data().ReferencedProtocols.loc_begin();
   }
-  protocol_loc_iterator protocol_loc_end() const {=20
-    return ReferencedProtocols.loc_end();=20
+  protocol_loc_iterator protocol_loc_end() const {
+    if (!hasDefinition())
+      return protocol_loc_iterator();
+   =20
+    return data().ReferencedProtocols.loc_end();
   }
-  unsigned protocol_size() const { return ReferencedProtocols.size(); }
+  unsigned protocol_size() const {=20
+    if (!hasDefinition())
+      return 0;
+   =20
+    return data().ReferencedProtocols.size();=20
+  }
=20
   /// setProtocolList - Set the list of protocols that this interface
   /// implements.
   void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
                        const SourceLocation *Locs, ASTContext &C) {
-    ReferencedProtocols.set(List, Num, Locs, C);
+    assert(Data && "Protocol is not defined");
+    data().ReferencedProtocols.set(List, Num, Locs, C);
   }
=20
   ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
@@ -973,102 +1196,57 @@
   ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
     return lookupMethod(Sel, false/*isInstance*/);
   }
+
+  /// \brief Determine whether this protocol has a definition.
+  bool hasDefinition() const { return Data !=3D 0; }
+
+  /// \brief Retrieve the definition of this protocol, if any.
+  ObjCProtocolDecl *getDefinition() {
+    return Data? Data->Definition : 0;
+  }
+
+  /// \brief Retrieve the definition of this protocol, if any.
+  const ObjCProtocolDecl *getDefinition() const {
+    return Data? Data->Definition : 0;
+  }
+
+  /// \brief Determine whether this particular declaration is also the=20
+  /// definition.
+  bool isThisDeclarationADefinition() const {
+    return getDefinition() =3D=3D this;
+  }
  =20
-  bool isForwardDecl() const { return isForwardProtoDecl; }
-  void setForwardDecl(bool val) { isForwardProtoDecl =3D val; }
+  /// \brief Starts the definition of this Objective-C protocol.
+  void startDefinition();
=20
-  // Location information, modeled after the Stmt API.
-  SourceLocation getLocStart() const { return getAtStartLoc(); } // '@'pro=
tocol
-  SourceLocation getLocEnd() const { return EndLoc; }
-  void setLocEnd(SourceLocation LE) { EndLoc =3D LE; }
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
+    if (isThisDeclarationADefinition())
+      return ObjCContainerDecl::getSourceRange();
+  =20
+    return SourceRange(getAtStartLoc(), getLocation());
+  }
+  =20
+  typedef redeclarable_base::redecl_iterator redecl_iterator;
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
+
+  /// Retrieves the canonical declaration of this Objective-C protocol.
+  ObjCProtocolDecl *getCanonicalDecl() {
+    return getFirstDeclaration();
+  }
+  const ObjCProtocolDecl *getCanonicalDecl() const {
+    return getFirstDeclaration();
+  }
=20
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ObjCProtocolDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D ObjCProtocol; }
-};
=20
-/// ObjCClassDecl - Specifies a list of forward class declarations. For ex=
ample:
-///
-/// @class NSCursor, NSImage, NSPasteboard, NSWindow;
-///
-class ObjCClassDecl : public Decl {
-public:
-  class ObjCClassRef {
-    ObjCInterfaceDecl *ID;
-    SourceLocation L;
-  public:
-    ObjCClassRef(ObjCInterfaceDecl *d, SourceLocation l) : ID(d), L(l) {}
-    SourceLocation getLocation() const { return L; }
-    ObjCInterfaceDecl *getInterface() const { return ID; }
-  };
-private:
-  ObjCClassRef *ForwardDecl;
-
-  ObjCClassDecl(DeclContext *DC, SourceLocation L,
-                ObjCInterfaceDecl *const Elt, const SourceLocation Loc,   =
            =20
-                ASTContext &C);
-public:
-  static ObjCClassDecl *Create(ASTContext &C, DeclContext *DC, SourceLocat=
ion L,
-                               ObjCInterfaceDecl *const Elt =3D 0,
-                               const SourceLocation Locs =3D SourceLocatio=
n());
-   =20
-  ObjCInterfaceDecl *getForwardInterfaceDecl() { return ForwardDecl->getIn=
terface(); }
-  ObjCClassRef *getForwardDecl() { return ForwardDecl; }
-  void setClass(ASTContext &C, ObjCInterfaceDecl*const Cls,
-                const SourceLocation Locs);
- =20
-  virtual SourceRange getSourceRange() const;
-
-  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
-  static bool classof(const ObjCClassDecl *D) { return true; }
-  static bool classofKind(Kind K) { return K =3D=3D ObjCClass; }
-};
-
-/// ObjCForwardProtocolDecl - Specifies a list of forward protocol declara=
tions.
-/// For example:
-///
-/// @protocol NSTextInput, NSChangeSpelling, NSDraggingInfo;
-///
-class ObjCForwardProtocolDecl : public Decl {
-  ObjCProtocolList ReferencedProtocols;
-
-  ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L,
-                          ObjCProtocolDecl *const *Elts, unsigned nElts,
-                          const SourceLocation *Locs, ASTContext &C);
-
-public:
-  static ObjCForwardProtocolDecl *Create(ASTContext &C, DeclContext *DC,
-                                         SourceLocation L,
-                                         ObjCProtocolDecl *const *Elts,
-                                         unsigned Num,
-                                         const SourceLocation *Locs);
-
-  static ObjCForwardProtocolDecl *Create(ASTContext &C, DeclContext *DC,
-                                         SourceLocation L) {
-    return Create(C, DC, L, 0, 0, 0);
-  }
-
-  typedef ObjCProtocolList::iterator protocol_iterator;
-  protocol_iterator protocol_begin() const {return ReferencedProtocols.beg=
in();}
-  protocol_iterator protocol_end() const { return ReferencedProtocols.end(=
); }
-  typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
-  protocol_loc_iterator protocol_loc_begin() const {=20
-    return ReferencedProtocols.loc_begin();=20
-  }
-  protocol_loc_iterator protocol_loc_end() const {=20
-    return ReferencedProtocols.loc_end();=20
-  }
-
-  unsigned protocol_size() const { return ReferencedProtocols.size(); }
-
-  /// setProtocolList - Set the list of forward protocols.
-  void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
-                       const SourceLocation *Locs, ASTContext &C) {
-    ReferencedProtocols.set(List, Num, Locs, C);
-  }
-  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
-  static bool classof(const ObjCForwardProtocolDecl *D) { return true; }
-  static bool classofKind(Kind K) { return K =3D=3D ObjCForwardProtocol; }
+  friend class ASTReader;
+  friend class ASTDeclReader;
+  friend class ASTDeclWriter;
 };
=20
 /// ObjCCategoryDecl - Represents a category declaration. A category allows
@@ -1089,6 +1267,8 @@
 /// don't support this level of dynamism, which is both powerful and dange=
rous.
 ///
 class ObjCCategoryDecl : public ObjCContainerDecl {
+  virtual void anchor();
+
   /// Interface belonging to this category
   ObjCInterfaceDecl *ClassInterface;
=20
@@ -1105,22 +1285,31 @@
   /// \brief The location of the category name in this declaration.
   SourceLocation CategoryNameLoc;
=20
-  ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,=20
+  /// class extension may have private ivars.
+  SourceLocation IvarLBraceLoc;
+  SourceLocation IvarRBraceLoc;
+ =20
+  ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
                    SourceLocation ClassNameLoc, SourceLocation CategoryNam=
eLoc,
-                   IdentifierInfo *Id, ObjCInterfaceDecl *IDecl)
+                   IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
+                   SourceLocation IvarLBraceLoc=3DSourceLocation(),
+                   SourceLocation IvarRBraceLoc=3DSourceLocation())
     : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
       ClassInterface(IDecl), NextClassCategory(0), HasSynthBitfield(false),
-      CategoryNameLoc(CategoryNameLoc) {
+      CategoryNameLoc(CategoryNameLoc),
+      IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
   }
 public:
=20
   static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
-                                  SourceLocation AtLoc,=20
+                                  SourceLocation AtLoc,
                                   SourceLocation ClassNameLoc,
                                   SourceLocation CategoryNameLoc,
                                   IdentifierInfo *Id,
-                                  ObjCInterfaceDecl *IDecl);
-  static ObjCCategoryDecl *Create(ASTContext &C, EmptyShell Empty);
+                                  ObjCInterfaceDecl *IDecl,
+                                  SourceLocation IvarLBraceLoc=3DSourceLoc=
ation(),
+                                  SourceLocation IvarRBraceLoc=3DSourceLoc=
ation());
+  static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
=20
   ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
   const ObjCInterfaceDecl *getClassInterface() const { return ClassInterfa=
ce; }
@@ -1144,21 +1333,21 @@
   protocol_iterator protocol_end() const { return ReferencedProtocols.end(=
); }
   unsigned protocol_size() const { return ReferencedProtocols.size(); }
   typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
-  protocol_loc_iterator protocol_loc_begin() const {=20
-    return ReferencedProtocols.loc_begin();=20
+  protocol_loc_iterator protocol_loc_begin() const {
+    return ReferencedProtocols.loc_begin();
   }
-  protocol_loc_iterator protocol_loc_end() const {=20
-    return ReferencedProtocols.loc_end();=20
+  protocol_loc_iterator protocol_loc_end() const {
+    return ReferencedProtocols.loc_end();
   }
=20
   ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategor=
y; }
=20
   bool IsClassExtension() const { return getIdentifier() =3D=3D 0; }
   const ObjCCategoryDecl *getNextClassExtension() const;
- =20
+
   bool hasSynthBitfield() const { return HasSynthBitfield; }
   void setHasSynthBitfield (bool val) { HasSynthBitfield =3D val; }
- =20
+
   typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
   ivar_iterator ivar_begin() const {
     return ivar_iterator(decls_begin());
@@ -1175,6 +1364,11 @@
=20
   SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
   void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc =3D Loc; }
+ =20
+  void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc =3D Loc; }
+  SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
+  void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc =3D Loc; }
+  SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
=20
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ObjCCategoryDecl *D) { return true; }
@@ -1185,6 +1379,8 @@
 };
=20
 class ObjCImplDecl : public ObjCContainerDecl {
+  virtual void anchor();
+
   /// Class interface for this class/category implementation
   ObjCInterfaceDecl *ClassInterface;
=20
@@ -1248,28 +1444,36 @@
 ///
 /// ObjCCategoryImplDecl
 class ObjCCategoryImplDecl : public ObjCImplDecl {
+  virtual void anchor();
+
   // Category name
   IdentifierInfo *Id;
=20
+  // Category name location
+  SourceLocation CategoryNameLoc;
+
   ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
                        ObjCInterfaceDecl *classInterface,
-                       SourceLocation nameLoc, SourceLocation atStartLoc)
+                       SourceLocation nameLoc, SourceLocation atStartLoc,
+                       SourceLocation CategoryNameLoc)
     : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, nameLoc, atStartL=
oc),
-      Id(Id) {}
+      Id(Id), CategoryNameLoc(CategoryNameLoc) {}
 public:
   static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
                                       IdentifierInfo *Id,
                                       ObjCInterfaceDecl *classInterface,
                                       SourceLocation nameLoc,
-                                      SourceLocation atStartLoc);
+                                      SourceLocation atStartLoc,
+                                      SourceLocation CategoryNameLoc);
+  static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned =
ID);
=20
   /// getIdentifier - Get the identifier that names the category
   /// interface associated with this implementation.
   /// FIXME: This is a bad API, we are overriding the NamedDecl::getIdenti=
fier()
   /// to mean something different. For example:
-  /// ((NamedDecl *)SomeCategoryImplDecl)->getIdentifier()=20
-  /// returns the class interface name, whereas=20
-  /// ((ObjCCategoryImplDecl *)SomeCategoryImplDecl)->getIdentifier()=20
+  /// ((NamedDecl *)SomeCategoryImplDecl)->getIdentifier()
+  /// returns the class interface name, whereas
+  /// ((ObjCCategoryImplDecl *)SomeCategoryImplDecl)->getIdentifier()
   /// returns the category name.
   IdentifierInfo *getIdentifier() const {
     return Id;
@@ -1278,6 +1482,8 @@
=20
   ObjCCategoryDecl *getCategoryDecl() const;
=20
+  SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
+
   /// getName - Get the name of identifier for the class interface associa=
ted
   /// with this implementation as a StringRef.
   //
@@ -1306,10 +1512,12 @@
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ObjCCategoryImplDecl *D) { return true; }
   static bool classofKind(Kind K) { return K =3D=3D ObjCCategoryImpl;}
+
+  friend class ASTDeclReader;
+  friend class ASTDeclWriter;
 };
=20
-raw_ostream &operator<<(raw_ostream &OS,
-                              const ObjCCategoryImplDecl *CID);
+raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
=20
 /// ObjCImplementationDecl - Represents a class definition - this is where
 /// method definitions are specified. For example:
@@ -1326,8 +1534,13 @@
 /// specified, they need to be *identical* to the interface.
 ///
 class ObjCImplementationDecl : public ObjCImplDecl {
+  virtual void anchor();
   /// Implementation Class's super class.
   ObjCInterfaceDecl *SuperClass;
+  /// @implementation may have private ivars.
+  SourceLocation IvarLBraceLoc;
+  SourceLocation IvarRBraceLoc;
+ =20
   /// Support for ivar initialization.
   /// IvarInitializers - The arguments used to initialize the ivars
   CXXCtorInitializer **IvarInitializers;
@@ -1335,35 +1548,43 @@
=20
   /// true if class has a .cxx_[construct,destruct] method.
   bool HasCXXStructors : 1;
- =20
+
   /// true of class extension has at least one bitfield ivar.
   bool HasSynthBitfield : 1;
- =20
+
   ObjCImplementationDecl(DeclContext *DC,
                          ObjCInterfaceDecl *classInterface,
                          ObjCInterfaceDecl *superDecl,
-                         SourceLocation nameLoc, SourceLocation atStartLoc)
+                         SourceLocation nameLoc, SourceLocation atStartLoc,
+                         SourceLocation IvarLBraceLoc=3DSourceLocation(),=20
+                         SourceLocation IvarRBraceLoc=3DSourceLocation())
     : ObjCImplDecl(ObjCImplementation, DC, classInterface, nameLoc, atStar=
tLoc),
-       SuperClass(superDecl), IvarInitializers(0), NumIvarInitializers(0),
-       HasCXXStructors(false), HasSynthBitfield(false) {}
+       SuperClass(superDecl), IvarLBraceLoc(IvarLBraceLoc),=20
+       IvarRBraceLoc(IvarRBraceLoc),
+       IvarInitializers(0), NumIvarInitializers(0),
+       HasCXXStructors(false), HasSynthBitfield(false){}
 public:
   static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
                                         ObjCInterfaceDecl *classInterface,
                                         ObjCInterfaceDecl *superDecl,
                                         SourceLocation nameLoc,
-                                        SourceLocation atStartLoc);
- =20
+                                        SourceLocation atStartLoc,
+                                        SourceLocation IvarLBraceLoc=3DSou=
rceLocation(),=20
+                                        SourceLocation IvarRBraceLoc=3DSou=
rceLocation());
+
+  static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigne=
d ID);
+
   /// init_iterator - Iterates through the ivar initializer list.
   typedef CXXCtorInitializer **init_iterator;
- =20
+
   /// init_const_iterator - Iterates through the ivar initializer list.
   typedef CXXCtorInitializer * const * init_const_iterator;
- =20
+
   /// init_begin() - Retrieve an iterator to the first initializer.
   init_iterator       init_begin()       { return IvarInitializers; }
   /// begin() - Retrieve an iterator to the first initializer.
   init_const_iterator init_begin() const { return IvarInitializers; }
- =20
+
   /// init_end() - Retrieve an iterator past the last initializer.
   init_iterator       init_end()       {
     return IvarInitializers + NumIvarInitializers;
@@ -1376,21 +1597,21 @@
   unsigned getNumIvarInitializers() const {
     return NumIvarInitializers;
   }
- =20
+
   void setNumIvarInitializers(unsigned numNumIvarInitializers) {
     NumIvarInitializers =3D numNumIvarInitializers;
   }
- =20
+
   void setIvarInitializers(ASTContext &C,
                            CXXCtorInitializer ** initializers,
                            unsigned numInitializers);
=20
   bool hasCXXStructors() const { return HasCXXStructors; }
   void setHasCXXStructors(bool val) { HasCXXStructors =3D val; }
- =20
+
   bool hasSynthBitfield() const { return HasSynthBitfield; }
   void setHasSynthBitfield (bool val) { HasSynthBitfield =3D val; }
-   =20
+
   /// getIdentifier - Get the identifier that names the class
   /// interface associated with this implementation.
   IdentifierInfo *getIdentifier() const {
@@ -1428,6 +1649,11 @@
=20
   void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass =3D superC=
ls; }
=20
+  void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc =3D Loc; }
+  SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
+  void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc =3D Loc; }
+  SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
+ =20
   typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
   ivar_iterator ivar_begin() const {
     return ivar_iterator(decls_begin());
@@ -1450,12 +1676,12 @@
   friend class ASTDeclWriter;
 };
=20
-raw_ostream &operator<<(raw_ostream &OS,
-                              const ObjCImplementationDecl *ID);
+raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
=20
 /// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
 /// declared as @compatibility_alias alias class.
 class ObjCCompatibleAliasDecl : public NamedDecl {
+  virtual void anchor();
   /// Class that this is an alias of.
   ObjCInterfaceDecl *AliasedClass;
=20
@@ -1467,6 +1693,9 @@
                                          SourceLocation L, IdentifierInfo =
*Id,
                                          ObjCInterfaceDecl* aliasedClass);
=20
+  static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,=20
+                                                     unsigned ID);
+ =20
   const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass=
; }
   ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
   void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass =3D D; }
@@ -1482,6 +1711,7 @@
 /// @property (assign, readwrite) int MyProperty;
 ///
 class ObjCPropertyDecl : public NamedDecl {
+  virtual void anchor();
 public:
   enum PropertyAttributeKind {
     OBJC_PR_noattr    =3D 0x00,
@@ -1509,6 +1739,7 @@
   enum PropertyControl { None, Required, Optional };
 private:
   SourceLocation AtLoc;   // location of @property
+  SourceLocation LParenLoc; // location of '(' starting attribute list or =
null.
   TypeSourceInfo *DeclType;
   unsigned PropertyAttributes : NumPropertyAttrsBits;
   unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
@@ -1523,9 +1754,11 @@
   ObjCIvarDecl *PropertyIvarDecl;   // Synthesize ivar for this property
=20
   ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
-                   SourceLocation AtLocation, TypeSourceInfo *T)
-    : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation), DeclType(T),
-      PropertyAttributes(OBJC_PR_noattr),=20
+                   SourceLocation AtLocation,  SourceLocation LParenLocati=
on,
+                   TypeSourceInfo *T)
+    : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),=20
+      LParenLoc(LParenLocation), DeclType(T),
+      PropertyAttributes(OBJC_PR_noattr),
       PropertyAttributesAsWritten(OBJC_PR_noattr),
       PropertyImplementation(None),
       GetterName(Selector()),
@@ -1535,11 +1768,18 @@
   static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
                                   SourceLocation L,
                                   IdentifierInfo *Id, SourceLocation AtLoc=
ation,
+                                  SourceLocation LParenLocation,
                                   TypeSourceInfo *T,
                                   PropertyControl propControl =3D None);
+ =20
+  static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
+ =20
   SourceLocation getAtLoc() const { return AtLoc; }
   void setAtLoc(SourceLocation L) { AtLoc =3D L; }
  =20
+  SourceLocation getLParenLoc() const { return LParenLoc; }
+  void setLParenLoc(SourceLocation L) { LParenLoc =3D L; }
+
   TypeSourceInfo *getTypeSourceInfo() const { return DeclType; }
   QualType getType() const { return DeclType->getType(); }
   void setType(TypeSourceInfo *T) { DeclType =3D T; }
@@ -1560,11 +1800,11 @@
         OBJC_PR_unsafe_unretained | OBJC_PR_retain | OBJC_PR_strong |
         OBJC_PR_weak);
   }
- =20
+
   void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
     PropertyAttributesAsWritten =3D PRVal;
   }
- =20
+
  void makeitReadWriteAttribute(void) {
     PropertyAttributes &=3D ~OBJC_PR_readonly;
     PropertyAttributes |=3D OBJC_PR_readwrite;
@@ -1630,7 +1870,7 @@
     return PropertyIvarDecl;
   }
=20
-  virtual SourceRange getSourceRange() const {
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtLoc, getLocation());
   }
=20
@@ -1655,7 +1895,7 @@
   };
 private:
   SourceLocation AtLoc;   // location of @synthesize or @dynamic
- =20
+
   /// \brief For @synthesize, the location of the ivar, if it was written =
in
   /// the source code.
   ///
@@ -1663,16 +1903,16 @@
   /// @synthesize int a =3D b
   /// \endcode
   SourceLocation IvarLoc;
- =20
+
   /// Property declaration being implemented
   ObjCPropertyDecl *PropertyDecl;
=20
   /// Null for @dynamic. Required for @synthesize.
   ObjCIvarDecl *PropertyIvarDecl;
- =20
+
   /// Null for @dynamic. Non-null if property must be copy-constructed in =
getter
   Expr *GetterCXXConstructor;
- =20
+
   /// Null for @dynamic. Non-null if property has assignment operator to c=
all
   /// in Setter synthesis.
   Expr *SetterCXXAssignment;
@@ -1683,7 +1923,7 @@
                        ObjCIvarDecl *ivarDecl,
                        SourceLocation ivarLoc)
     : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
-      IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl)=
,=20
+      IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl),
       GetterCXXConstructor(0), SetterCXXAssignment(0) {
     assert (PK =3D=3D Dynamic || PropertyIvarDecl);
   }
@@ -1696,9 +1936,11 @@
                                       ObjCIvarDecl *ivarDecl,
                                       SourceLocation ivarLoc);
=20
-  virtual SourceRange getSourceRange() const;
+  static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned =
ID);
  =20
-  SourceLocation getLocStart() const { return AtLoc; }
+  virtual SourceRange getSourceRange() const LLVM_READONLY;
+
+  SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; }
   void setAtLoc(SourceLocation Loc) { AtLoc =3D Loc; }
=20
   ObjCPropertyDecl *getPropertyDecl() const {
@@ -1714,13 +1956,13 @@
     return PropertyIvarDecl;
   }
   SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
- =20
+
   void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
-                           SourceLocation IvarLoc) {=20
-    PropertyIvarDecl =3D Ivar;=20
+                           SourceLocation IvarLoc) {
+    PropertyIvarDecl =3D Ivar;
     this->IvarLoc =3D IvarLoc;
   }
- =20
+
   Expr *getGetterCXXConstructor() const {
     return GetterCXXConstructor;
   }
@@ -1734,11 +1976,11 @@
   void setSetterCXXAssignment(Expr *setterCXXAssignment) {
     SetterCXXAssignment =3D setterCXXAssignment;
   }
- =20
+
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classof(const ObjCPropertyImplDecl *D) { return true; }
   static bool classofKind(Decl::Kind K) { return K =3D=3D ObjCPropertyImpl=
; }
- =20
+
   friend class ASTDeclReader;
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DeclTemplate.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DeclTemplate.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DeclTemplate.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -15,8 +15,10 @@
 #define LLVM_CLANG_AST_DECLTEMPLATE_H
=20
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/Redeclarable.h"
 #include "clang/AST/TemplateBase.h"
 #include "llvm/ADT/PointerUnion.h"
+#include "llvm/Support/Compiler.h"
 #include <limits>
=20
 namespace clang {
@@ -99,12 +101,12 @@
   /// The first template parameter list in a declaration will have depth 0,
   /// the second template parameter list will have depth 1, etc.
   unsigned getDepth() const;
- =20
+
   SourceLocation getTemplateLoc() const { return TemplateLoc; }
   SourceLocation getLAngleLoc() const { return LAngleLoc; }
   SourceLocation getRAngleLoc() const { return RAngleLoc; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(TemplateLoc, RAngleLoc);
   }
 };
@@ -116,7 +118,8 @@
   NamedDecl *Params[N];
=20
 public:
-  FixedSizeTemplateParameterList(SourceLocation TemplateLoc, SourceLocatio=
n LAngleLoc,
+  FixedSizeTemplateParameterList(SourceLocation TemplateLoc,
+                                 SourceLocation LAngleLoc,
                                  NamedDecl **Params, SourceLocation RAngle=
Loc) :
     TemplateParameterList(TemplateLoc, LAngleLoc, Params, N, RAngleLoc) {
   }
@@ -142,7 +145,7 @@
     : Arguments(Args, Owned), NumArguments(NumArgs) { }
=20
 public:
-  /// \brief Type used to indicate that the template argument list itself =
is a=20
+  /// \brief Type used to indicate that the template argument list itself =
is a
   /// stack object. It does not own its template arguments.
   enum OnStackType { OnStack };
=20
@@ -156,12 +159,12 @@
   ///
   /// The template argument list does not own the template arguments
   /// provided.
-  explicit TemplateArgumentList(OnStackType,=20
+  explicit TemplateArgumentList(OnStackType,
                                 const TemplateArgument *Args, unsigned Num=
Args)
     : Arguments(Args, false), NumArguments(NumArgs) { }
-                               =20
-  /// \brief Produces a shallow copy of the given template argument list. =20
-  ///=20
+
+  /// \brief Produces a shallow copy of the given template argument list.
+  ///
   /// This operation assumes that the input argument list outlives it.
   /// This takes the list as a pointer to avoid looking like a copy
   /// constructor, since this really really isn't safe to use that
@@ -197,6 +200,7 @@
 /// parameters and a reference to the templated scoped declaration: the
 /// underlying AST node.
 class TemplateDecl : public NamedDecl {
+  virtual void anchor();
 protected:
   // This is probably never used.
   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
@@ -236,7 +240,7 @@
     return K >=3D firstTemplate && K <=3D lastTemplate;
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(TemplateParams->getTemplateLoc(),
                        TemplatedDecl->getSourceRange().getEnd());
   }
@@ -244,7 +248,7 @@
 protected:
   NamedDecl *TemplatedDecl;
   TemplateParameterList* TemplateParams;
- =20
+
 public:
   /// \brief Initialize the underlying templated declaration and
   /// template parameters.
@@ -298,9 +302,9 @@
   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
=20
   /// \brief The point at which this function template specialization was
-  /// first instantiated.=20
+  /// first instantiated.
   SourceLocation PointOfInstantiation;
- =20
+
   /// \brief Retrieve the template from which this function was specialize=
d.
   FunctionTemplateDecl *getTemplate() const { return Template.getPointer()=
; }
=20
@@ -325,16 +329,16 @@
   ///
   /// The point of instantiation may be an invalid source location if this
   /// function has yet to be instantiated.
-  SourceLocation getPointOfInstantiation() const {=20
-    return PointOfInstantiation;=20
+  SourceLocation getPointOfInstantiation() const {
+    return PointOfInstantiation;
   }
- =20
+
   /// \brief Set the (first) point of instantiation of this function templ=
ate
   /// specialization.
   void setPointOfInstantiation(SourceLocation POI) {
     PointOfInstantiation =3D POI;
   }
- =20
+
   void Profile(llvm::FoldingSetNodeID &ID) {
     Profile(ID, TemplateArguments->data(),
             TemplateArguments->size(),
@@ -350,49 +354,49 @@
   }
 };
=20
-/// \brief Provides information a specialization of a member of a class=20
-/// template, which may be a member function, static data member, or
-/// member class.
+/// \brief Provides information a specialization of a member of a class
+/// template, which may be a member function, static data member,
+/// member class or member enumeration.
 class MemberSpecializationInfo {
   // The member declaration from which this member was instantiated, and t=
he
   // manner in which the instantiation occurred (in the lower two bits).
   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
- =20
+
   // The point at which this member was first instantiated.
   SourceLocation PointOfInstantiation;
- =20
+
 public:
-  explicit=20
+  explicit
   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
                            SourceLocation POI =3D SourceLocation())
     : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
-    assert(TSK !=3D TSK_Undeclared &&=20
+    assert(TSK !=3D TSK_Undeclared &&
            "Cannot encode undeclared template specializations for members"=
);
   }
- =20
+
   /// \brief Retrieve the member declaration from which this member was
   /// instantiated.
   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(=
); }
- =20
+
   /// \brief Determine what kind of template specialization this is.
   TemplateSpecializationKind getTemplateSpecializationKind() const {
     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
   }
- =20
+
   /// \brief Set the template specialization kind.
   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
-    assert(TSK !=3D TSK_Undeclared &&=20
+    assert(TSK !=3D TSK_Undeclared &&
            "Cannot encode undeclared template specializations for members"=
);
     MemberAndTSK.setInt(TSK - 1);
   }
- =20
-  /// \brief Retrieve the first point of instantiation of this member.=20
+
+  /// \brief Retrieve the first point of instantiation of this member.
   /// If the point of instantiation is an invalid location, then this memb=
er
   /// has not yet been instantiated.
-  SourceLocation getPointOfInstantiation() const {=20
-    return PointOfInstantiation;=20
+  SourceLocation getPointOfInstantiation() const {
+    return PointOfInstantiation;
   }
- =20
+
   /// \brief Set the first point of instantiation.
   void setPointOfInstantiation(SourceLocation POI) {
     PointOfInstantiation =3D POI;
@@ -414,14 +418,14 @@
   union {
     // Force sizeof to be a multiple of sizeof(void*) so that the
     // trailing data is aligned.
-    void *Aligner;=20
+    void *Aligner;
=20
     struct {
       /// The number of potential template candidates.
       unsigned NumTemplates;
=20
       /// The number of template arguments.
-      unsigned NumArgs;     =20
+      unsigned NumArgs;
     } d;
   };
=20
@@ -452,7 +456,7 @@
   /// \brief Returns the explicit template arguments that were given.
   const TemplateArgumentLoc *getTemplateArgs() const {
     return reinterpret_cast<const TemplateArgumentLoc*>(
-                                                        &getTemplates()[ge=
tNumTemplates()]);
+                                            &getTemplates()[getNumTemplate=
s()]);
   }
=20
   /// \brief Returns the number of explicit template arguments that were g=
iven.
@@ -474,33 +478,28 @@
     return AngleLocs.getEnd();
   }
 };
- =20
+
 /// Declaration of a redeclarable template.
-class RedeclarableTemplateDecl : public TemplateDecl {
-
-  RedeclarableTemplateDecl *getPreviousDeclarationImpl() {
-    return CommonOrPrev.dyn_cast<RedeclarableTemplateDecl*>();
+class RedeclarableTemplateDecl : public TemplateDecl,=20
+                                 public Redeclarable<RedeclarableTemplateD=
ecl>=20
+{
+  typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
+  virtual RedeclarableTemplateDecl *getNextRedeclaration() {
+    return RedeclLink.getNext();
   }
-
-  RedeclarableTemplateDecl *getCanonicalDeclImpl();
-
-  void setPreviousDeclarationImpl(RedeclarableTemplateDecl *Prev);
-
-  RedeclarableTemplateDecl *getInstantiatedFromMemberTemplateImpl() {
-    return getCommonPtr()->InstantiatedFromMember.getPointer();
+  virtual RedeclarableTemplateDecl *getPreviousDeclImpl() {
+    return getPreviousDecl();
   }
-
-  void setInstantiatedFromMemberTemplateImpl(RedeclarableTemplateDecl *TD)=
 {
-    assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
-    getCommonPtr()->InstantiatedFromMember.setPointer(TD);
+  virtual RedeclarableTemplateDecl *getMostRecentDeclImpl() {
+    return getMostRecentDecl();
   }
=20
 protected:
   template <typename EntryType> struct SpecEntryTraits {
     typedef EntryType DeclType;
=20
-    static DeclType *getMostRecentDeclaration(EntryType *D) {
-      return D->getMostRecentDeclaration();
+    static DeclType *getMostRecentDecl(EntryType *D) {
+      return D->getMostRecentDecl();
     }
   };
=20
@@ -522,7 +521,7 @@
     SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {}
=20
     DeclType *operator*() const {
-      return SETraits::getMostRecentDeclaration(&*SetIter);
+      return SETraits::getMostRecentDecl(&*SetIter);
     }
     DeclType *operator->() const { return **this; }
=20
@@ -562,15 +561,12 @@
     /// was explicitly specialized.
     llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
       InstantiatedFromMember;
-
-    /// \brief The latest declaration of this template.
-    RedeclarableTemplateDecl *Latest;
   };
=20
-  /// \brief A pointer to the previous declaration (if this is a redeclara=
tion)
-  /// or to the data that is common to all declarations of this template.
-  llvm::PointerUnion<CommonBase*, RedeclarableTemplateDecl*> CommonOrPrev;
-
+  /// \brief Pointer to the common data shared by all declarations of this
+  /// template.
+  CommonBase *Common;
+ =20
   /// \brief Retrieves the "common" pointer shared by all (re-)declaration=
s of
   /// the same template. Calling this routine may implicitly allocate memo=
ry
   /// for the common pointer.
@@ -582,56 +578,18 @@
   RedeclarableTemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
                            DeclarationName Name, TemplateParameterList *Pa=
rams,
                            NamedDecl *Decl)
-    : TemplateDecl(DK, DC, L, Name, Params, Decl),
-      CommonOrPrev((CommonBase*)0) { }
+    : TemplateDecl(DK, DC, L, Name, Params, Decl), Common() { }
=20
 public:
   template <class decl_type> friend class RedeclarableTemplate;
=20
-  RedeclarableTemplateDecl *getCanonicalDecl() {
-    return getCanonicalDeclImpl();
+  /// Retrieves the canonical declaration of this template.
+  RedeclarableTemplateDecl *getCanonicalDecl() { return getFirstDeclaratio=
n(); }
+  const RedeclarableTemplateDecl *getCanonicalDecl() const {=20
+    return getFirstDeclaration();=20
   }
=20
-  /// \brief Retrieve the previous declaration of this template, or
-  /// NULL if no such declaration exists.
-  RedeclarableTemplateDecl *getPreviousDeclaration() {
-    return getPreviousDeclarationImpl();
-  }
-
-  /// \brief Retrieve the previous declaration of this template, or
-  /// NULL if no such declaration exists.
-  const RedeclarableTemplateDecl *getPreviousDeclaration() const {
-    return
-      const_cast<RedeclarableTemplateDecl*>(this)->getPreviousDeclaration(=
);
-  }
-
-  /// \brief Retrieve the first declaration of this template, or itself
-  /// if this the first one.
-  RedeclarableTemplateDecl *getFirstDeclaration() {
-    return getCanonicalDecl();
-  }
-
-  /// \brief Retrieve the first declaration of this template, or itself
-  /// if this the first one.
-  const RedeclarableTemplateDecl *getFirstDeclaration() const {
-    return
-      const_cast<RedeclarableTemplateDecl*>(this)->getFirstDeclaration();
-  }
-
-  /// \brief Retrieve the most recent declaration of this template, or its=
elf
-  /// if this the most recent one.
-  RedeclarableTemplateDecl *getMostRecentDeclaration() {
-    return getCommonPtr()->Latest;
-  }
-
-  /// \brief Retrieve the most recent declaration of this template, or its=
elf
-  /// if this the most recent one.
-  const RedeclarableTemplateDecl *getMostRecentDeclaration() const {
-    return
-      const_cast<RedeclarableTemplateDecl*>(this)->getMostRecentDeclaratio=
n();
-  }
-
-  /// \brief Determines whether this template was a specialization of a=20
+  /// \brief Determines whether this template was a specialization of a
   /// member template.
   ///
   /// In the following example, the function template \c X<int>::f and the
@@ -652,21 +610,64 @@
   bool isMemberSpecialization() {
     return getCommonPtr()->InstantiatedFromMember.getInt();
   }
- =20
+
   /// \brief Note that this member template is a specialization.
   void setMemberSpecialization() {
     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
            "Only member templates can be member template specializations");
     getCommonPtr()->InstantiatedFromMember.setInt(true);
   }
- =20
-  /// \brief Retrieve the previous declaration of this template, or
-  /// NULL if no such declaration exists.
+
+  /// \brief Retrieve the member template from which this template was
+  /// instantiated, or NULL if this template was not instantiated from a=20
+  /// member template.
+  ///
+  /// A template is instantiated from a member template when the member=20
+  /// template itself is part of a class template (or member thereof). For
+  /// example, given
+  ///
+  /// \code
+  /// template<typename T>
+  /// struct X {
+  ///   template<typename U> void f(T, U);
+  /// };
+  ///
+  /// void test(X<int> x) {
+  ///   x.f(1, 'a');
+  /// };
+  /// \endcode
+  ///
+  /// \c X<int>::f is a FunctionTemplateDecl that describes the function
+  /// template
+  ///
+  /// \code
+  /// template<typename U> void X<int>::f(int, U);
+  /// \endcode
+  ///
+  /// which was itself created during the instantiation of \c X<int>. Call=
ing
+  /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
+  /// retrieve the FunctionTemplateDecl for the original template "f" with=
in
+  /// the class template \c X<T>, i.e.,
+  ///
+  /// \code
+  /// template<typename T>
+  /// template<typename U>
+  /// void X<T>::f(T, U);
+  /// \endcode
   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() {
-    return getInstantiatedFromMemberTemplateImpl();
+    return getCommonPtr()->InstantiatedFromMember.getPointer();
   }
=20
-  virtual RedeclarableTemplateDecl *getNextRedeclaration();
+  void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
+    assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
+    getCommonPtr()->InstantiatedFromMember.setPointer(TD);
+  }
+
+  typedef redeclarable_base::redecl_iterator redecl_iterator;
+  using redeclarable_base::redecls_begin;
+  using redeclarable_base::redecls_end;
+  using redeclarable_base::getPreviousDecl;
+  using redeclarable_base::getMostRecentDecl;
=20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -678,107 +679,35 @@
     return K >=3D firstRedeclarableTemplate && K <=3D lastRedeclarableTemp=
late;
   }
=20
+  friend class ASTReader;
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
 };
=20
-template <class decl_type>
-class RedeclarableTemplate {
-  RedeclarableTemplateDecl *thisDecl() {
-    return static_cast<decl_type*>(this);
-  }
-
-public:
-  /// \brief Retrieve the previous declaration of this function template, =
or
-  /// NULL if no such declaration exists.
-  decl_type *getPreviousDeclaration() {
-    return static_cast<decl_type*>(thisDecl()->getPreviousDeclarationImpl(=
));
-  }
-
-  /// \brief Retrieve the previous declaration of this function template, =
or
-  /// NULL if no such declaration exists.
-  const decl_type *getPreviousDeclaration() const {
-    return const_cast<RedeclarableTemplate*>(this)->getPreviousDeclaration=
();
-  }
-
-  /// \brief Set the previous declaration of this function template.
-  void setPreviousDeclaration(decl_type *Prev) {
-    thisDecl()->setPreviousDeclarationImpl(Prev);
-  }
-
-  decl_type *getCanonicalDecl() {
-    return static_cast<decl_type*>(thisDecl()->getCanonicalDeclImpl());
-  }
-
-  const decl_type *getCanonicalDecl() const {
-    return const_cast<RedeclarableTemplate*>(this)->getCanonicalDecl();
-  }
-
-  /// \brief Retrieve the member template that this template was instantia=
ted
-  /// from.
-  ///
-  /// This routine will return non-NULL for member templates of
-  /// class templates.  For example, given:
-  ///
-  /// \code
-  /// template <typename T>
-  /// struct X {
-  ///   template <typename U> void f();
-  ///   template <typename U> struct A {};
-  /// };
-  /// \endcode
-  ///
-  /// X<int>::f<float> is a CXXMethodDecl (whose parent is X<int>, a
-  /// ClassTemplateSpecializationDecl) for which getPrimaryTemplate() will
-  /// return X<int>::f, a FunctionTemplateDecl (whose parent is again
-  /// X<int>) for which getInstantiatedFromMemberTemplate() will return
-  /// X<T>::f, a FunctionTemplateDecl (whose parent is X<T>, a
-  /// ClassTemplateDecl).
-  ///
-  /// X<int>::A<float> is a ClassTemplateSpecializationDecl (whose parent
-  /// is X<int>, also a CTSD) for which getSpecializedTemplate() will
-  /// return X<int>::A<U>, a ClassTemplateDecl (whose parent is again
-  /// X<int>) for which getInstantiatedFromMemberTemplate() will return
-  /// X<T>::A<U>, a ClassTemplateDecl (whose parent is X<T>, also a CTD).
-  ///
-  /// \returns NULL if this is not an instantiation of a member template.
-  decl_type *getInstantiatedFromMemberTemplate() {
-    return static_cast<decl_type*>(
-             thisDecl()->getInstantiatedFromMemberTemplateImpl());
-  }
-
-  void setInstantiatedFromMemberTemplate(decl_type *TD) {
-    thisDecl()->setInstantiatedFromMemberTemplateImpl(TD);
-  }
-};
-
 template <> struct RedeclarableTemplateDecl::
 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
   typedef FunctionDecl DeclType;
=20
   static DeclType *
-  getMostRecentDeclaration(FunctionTemplateSpecializationInfo *I) {
-    return I->Function->getMostRecentDeclaration();
+  getMostRecentDecl(FunctionTemplateSpecializationInfo *I) {
+    return I->Function->getMostRecentDecl();
   }
 };
=20
 /// Declaration of a template function.
-class FunctionTemplateDecl : public RedeclarableTemplateDecl,
-                             public RedeclarableTemplate<FunctionTemplateD=
ecl> {
+class FunctionTemplateDecl : public RedeclarableTemplateDecl {
   static void DeallocateCommon(void *Ptr);
=20
 protected:
-  typedef RedeclarableTemplate<FunctionTemplateDecl> redeclarable_base;
-
   /// \brief Data that is common to all of the declarations of a given
   /// function template.
   struct Common : CommonBase {
     Common() : InjectedArgs(0) { }
-   =20
+
     /// \brief The function template specializations for this function
     /// template, including explicit specializations and instantiations.
     llvm::FoldingSet<FunctionTemplateSpecializationInfo> Specializations;
-   =20
+
     /// \brief The set of "injected" template arguments used within this
     /// function template.
     ///
@@ -813,7 +742,7 @@
   ///        retrieved by an earlier call to findSpecialization().
   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
                          void *InsertPos);
- =20
+
 public:
   /// Get the underlying function declaration of the template.
   FunctionDecl *getTemplatedDecl() const {
@@ -832,26 +761,31 @@
                                    unsigned NumArgs, void *&InsertPos);
=20
   FunctionTemplateDecl *getCanonicalDecl() {
-    return redeclarable_base::getCanonicalDecl();
+    return cast<FunctionTemplateDecl>(
+             RedeclarableTemplateDecl::getCanonicalDecl());
   }
   const FunctionTemplateDecl *getCanonicalDecl() const {
-    return redeclarable_base::getCanonicalDecl();
+    return cast<FunctionTemplateDecl>(
+             RedeclarableTemplateDecl::getCanonicalDecl());
   }
=20
   /// \brief Retrieve the previous declaration of this function template, =
or
   /// NULL if no such declaration exists.
-  FunctionTemplateDecl *getPreviousDeclaration() {
-    return redeclarable_base::getPreviousDeclaration();
+  FunctionTemplateDecl *getPreviousDecl() {
+    return cast_or_null<FunctionTemplateDecl>(
+             RedeclarableTemplateDecl::getPreviousDecl());
   }
=20
   /// \brief Retrieve the previous declaration of this function template, =
or
   /// NULL if no such declaration exists.
-  const FunctionTemplateDecl *getPreviousDeclaration() const {
-    return redeclarable_base::getPreviousDeclaration();
+  const FunctionTemplateDecl *getPreviousDecl() const {
+    return cast_or_null<FunctionTemplateDecl>(
+             RedeclarableTemplateDecl::getPreviousDecl());
   }
=20
   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() {
-    return redeclarable_base::getInstantiatedFromMemberTemplate();
+    return cast_or_null<FunctionTemplateDecl>(
+             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate()=
);
   }
=20
   typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
@@ -866,13 +800,13 @@
=20
   /// \brief Retrieve the "injected" template arguments that correspond to=
 the
   /// template parameters of this function template.
-  ///                              =20
+  ///
   /// Although the C++ standard has no notion of the "injected" template
   /// arguments for a function template, the notion is convenient when
   /// we need to perform substitutions inside the definition of a function
-  /// template.    =20
+  /// template.
   std::pair<const TemplateArgument *, unsigned> getInjectedTemplateArgs();
-                              =20
+
   /// \brief Create a function template node.
   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
                                       SourceLocation L,
@@ -881,7 +815,7 @@
                                       NamedDecl *Decl);
=20
   /// \brief Create an empty function template node.
-  static FunctionTemplateDecl *Create(ASTContext &C, EmptyShell);
+  static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned =
ID);
=20
   // Implement isa/cast/dyncast support
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -966,7 +900,8 @@
                                       unsigned D, unsigned P,
                                       IdentifierInfo *Id, bool Typename,
                                       bool ParameterPack);
-  static TemplateTypeParmDecl *Create(const ASTContext &C, EmptyShell Empt=
y);
+  static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,=20
+                                                  unsigned ID);
=20
   /// \brief Whether this template type parameter was declared with
   /// the 'typename' keyword. If not, it was declared with the 'class'
@@ -1003,21 +938,21 @@
     DefaultArgument =3D 0;
     InheritedDefault =3D false;
   }
- =20
+
   /// \brief Set whether this template type parameter was declared with
   /// the 'typename' or 'class' keyword.
   void setDeclaredWithTypename(bool withTypename) { Typename =3D withTypen=
ame; }
=20
   /// \brief Retrieve the depth of the template parameter.
   unsigned getDepth() const;
- =20
+
   /// \brief Retrieve the index of the template parameter.
   unsigned getIndex() const;
=20
   /// \brief Returns whether this is a parameter pack.
   bool isParameterPack() const;
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -1038,18 +973,18 @@
=20
   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/=
index
   // down here to save memory.
-   =20
+
   /// \brief Whether this non-type template parameter is a parameter pack.
   bool ParameterPack;
-   =20
-  /// \brief Whether this non-type template parameter is an "expanded"=20
+
+  /// \brief Whether this non-type template parameter is an "expanded"
   /// parameter pack, meaning that its type is a pack expansion and we
   /// already know the set of types that expansion expands to.
   bool ExpandedParameterPack;
-   =20
+
   /// \brief The number of types in an expanded parameter pack.
   unsigned NumExpandedTypes;
-   =20
+
   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
                           SourceLocation IdLoc, unsigned D, unsigned P,
                           IdentifierInfo *Id, QualType T,
@@ -1069,7 +1004,7 @@
                           TypeSourceInfo **ExpandedTInfos);
=20
   friend class ASTDeclReader;
-   =20
+
 public:
   static NonTypeTemplateParmDecl *
   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
@@ -1083,13 +1018,19 @@
          const QualType *ExpandedTypes, unsigned NumExpandedTypes,
          TypeSourceInfo **ExpandedTInfos);
=20
+  static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,=20
+                                                     unsigned ID);
+  static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,=20
+                                                     unsigned ID,
+                                                     unsigned NumExpandedT=
ypes);
+   =20
   using TemplateParmPosition::getDepth;
   using TemplateParmPosition::setDepth;
   using TemplateParmPosition::getPosition;
   using TemplateParmPosition::setPosition;
   using TemplateParmPosition::getIndex;
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   /// \brief Determine whether this template parameter has a default
   /// argument.
@@ -1135,7 +1076,7 @@
   /// template<typename T, unsigned ...Dims> struct multi_array;
   /// \endcode
   bool isParameterPack() const { return ParameterPack; }
-   =20
+
   /// \brief Whether this parameter is a non-type template parameter pack
   /// that has different types at different positions.
   ///
@@ -1150,25 +1091,26 @@
   ///   struct Y { /* ... */ };
   /// };
   /// \endcode
-  ///=20
+  ///
   /// The parameter pack \c Values has a \c PackExpansionType as its type,
   /// which expands \c Types. When \c Types is supplied with template argu=
ments
-  /// by instantiating \c X, the instantiation of \c Values becomes an=20
-  /// expanded parameter pack. For example, instantiating=20
+  /// by instantiating \c X, the instantiation of \c Values becomes an
+  /// expanded parameter pack. For example, instantiating
   /// \c X<int, unsigned int> results in \c Values being an expanded param=
eter
   /// pack with expansion types \c int and \c unsigned int.
   ///
-  /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functi=
ons=20
+  /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functi=
ons
   /// return the expansion types.
   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
-   =20
-  /// \brief Retrieves the number of expansion types in an expanded parame=
ter pack.
+
+  /// \brief Retrieves the number of expansion types in an expanded parame=
ter
+  /// pack.
   unsigned getNumExpansionTypes() const {
     assert(ExpandedParameterPack && "Not an expansion parameter pack");
     return NumExpandedTypes;
   }
=20
-  /// \brief Retrieve a particular expansion type within an expanded param=
eter=20
+  /// \brief Retrieve a particular expansion type within an expanded param=
eter
   /// pack.
   QualType getExpansionType(unsigned I) const {
     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
@@ -1176,7 +1118,7 @@
     return QualType::getFromOpaquePtr(TypesAndInfos[2*I]);
   }
=20
-  /// \brief Retrieve a particular expansion type source info within an=20
+  /// \brief Retrieve a particular expansion type source info within an
   /// expanded parameter pack.
   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
@@ -1197,8 +1139,10 @@
 /// @endcode
 /// A template template parameter is a TemplateDecl because it defines the
 /// name of a template and the template parameters allowable for substitut=
ion.
-class TemplateTemplateParmDecl
-  : public TemplateDecl, protected TemplateParmPosition {
+class TemplateTemplateParmDecl : public TemplateDecl,=20
+                                 protected TemplateParmPosition=20
+{
+  virtual void anchor();
=20
   /// DefaultArgument - The default template argument, if any.
   TemplateArgumentLoc DefaultArgument;
@@ -1207,7 +1151,7 @@
=20
   /// \brief Whether this parameter is a parameter pack.
   bool ParameterPack;
-   =20
+
   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
                            unsigned D, unsigned P, bool ParameterPack,
                            IdentifierInfo *Id, TemplateParameterList *Para=
ms)
@@ -1223,6 +1167,9 @@
                                           IdentifierInfo *Id,
                                           TemplateParameterList *Params);
=20
+  static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,=20
+                                                      unsigned ID);
+ =20
   using TemplateParmPosition::getDepth;
   using TemplateParmPosition::getPosition;
   using TemplateParmPosition::getIndex;
@@ -1269,7 +1216,7 @@
     DefaultArgumentWasInherited =3D false;
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     SourceLocation End =3D getLocation();
     if (hasDefaultArgument() && !defaultArgumentWasInherited())
       End =3D getDefaultArgument().getSourceRange().getEnd();
@@ -1365,19 +1312,19 @@
          unsigned NumArgs,
          ClassTemplateSpecializationDecl *PrevDecl);
   static ClassTemplateSpecializationDecl *
-  Create(ASTContext &Context, EmptyShell Empty);
+  CreateDeserialized(ASTContext &C, unsigned ID);
=20
   virtual void getNameForDiagnostic(std::string &S,
                                     const PrintingPolicy &Policy,
                                     bool Qualified) const;
=20
-  ClassTemplateSpecializationDecl *getMostRecentDeclaration() {
+  ClassTemplateSpecializationDecl *getMostRecentDecl() {
     CXXRecordDecl *Recent
-        =3D cast<CXXRecordDecl>(CXXRecordDecl::getMostRecentDeclaration());
+        =3D cast<CXXRecordDecl>(CXXRecordDecl::getMostRecentDecl());
     if (!isa<ClassTemplateSpecializationDecl>(Recent)) {
       // FIXME: Does injected class name need to be in the redeclarations =
chain?
-      assert(Recent->isInjectedClassName() && Recent->getPreviousDeclarati=
on());
-      Recent =3D Recent->getPreviousDeclaration();
+      assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
+      Recent =3D Recent->getPreviousDecl();
     }
     return cast<ClassTemplateSpecializationDecl>(Recent);
   }
@@ -1525,7 +1472,7 @@
     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocatio=
n();
   }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   void Profile(llvm::FoldingSetNodeID &ID) const {
     Profile(ID, TemplateArgs->data(), TemplateArgs->size(), getASTContext(=
));
@@ -1552,13 +1499,15 @@
   static bool classof(const ClassTemplatePartialSpecializationDecl *) {
     return true;
   }
- =20
+
   friend class ASTDeclReader;
   friend class ASTDeclWriter;
 };
=20
 class ClassTemplatePartialSpecializationDecl
   : public ClassTemplateSpecializationDecl {
+  virtual void anchor();
+
   /// \brief The list of template parameters
   TemplateParameterList* TemplateParams;
=20
@@ -1571,15 +1520,15 @@
   /// specialization was added to the set of partial specializations for
   /// its owning class template.
   unsigned SequenceNumber;
-   =20
-  /// \brief The class template partial specialization from which this=20
+
+  /// \brief The class template partial specialization from which this
   /// class template partial specialization was instantiated.
   ///
   /// The boolean value will be true to indicate that this class template
   /// partial specialization was specialized at this level.
   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
       InstantiatedFromMember;
-   =20
+
   ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
                                          DeclContext *DC,
                                          SourceLocation StartLoc,
@@ -1592,7 +1541,7 @@
                                          unsigned NumArgInfos,
                                ClassTemplatePartialSpecializationDecl *Pre=
vDecl,
                                          unsigned SequenceNumber);
- =20
+
   ClassTemplatePartialSpecializationDecl()
     : ClassTemplateSpecializationDecl(ClassTemplatePartialSpecialization),
       TemplateParams(0), ArgsAsWritten(0),
@@ -1601,7 +1550,7 @@
=20
 public:
   static ClassTemplatePartialSpecializationDecl *
-  Create(ASTContext &Context, TagKind TK,DeclContext *DC,
+  Create(ASTContext &Context, TagKind TK, DeclContext *DC,
          SourceLocation StartLoc, SourceLocation IdLoc,
          TemplateParameterList *Params,
          ClassTemplateDecl *SpecializedTemplate,
@@ -1613,11 +1562,11 @@
          unsigned SequenceNumber);
=20
   static ClassTemplatePartialSpecializationDecl *
-  Create(ASTContext &Context, EmptyShell Empty);
+  CreateDeserialized(ASTContext &C, unsigned ID);
=20
-  ClassTemplatePartialSpecializationDecl *getMostRecentDeclaration() {
+  ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
     return cast<ClassTemplatePartialSpecializationDecl>(
-                   ClassTemplateSpecializationDecl::getMostRecentDeclarati=
on());
+                   ClassTemplateSpecializationDecl::getMostRecentDecl());
   }
=20
   /// Get the list of template parameters
@@ -1654,9 +1603,9 @@
   /// \endcode
   ///
   /// In this example, the instantiation of \c Outer<float>::Inner<int*> w=
ill
-  /// end up instantiating the partial specialization=20
-  /// \c Outer<float>::Inner<U*>, which itself was instantiated from the c=
lass=20
-  /// template partial specialization \c Outer<T>::Inner<U*>. Given=20
+  /// end up instantiating the partial specialization
+  /// \c Outer<float>::Inner<U*>, which itself was instantiated from the c=
lass
+  /// template partial specialization \c Outer<T>::Inner<U*>. Given
   /// \c Outer<float>::Inner<U*>, this function would return
   /// \c Outer<T>::Inner<U*>.
   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() {
@@ -1664,15 +1613,15 @@
       =3D cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration=
());
     return First->InstantiatedFromMember.getPointer();
   }
- =20
+
   void setInstantiatedFromMember(
                           ClassTemplatePartialSpecializationDecl *PartialS=
pec) {
     ClassTemplatePartialSpecializationDecl *First
       =3D cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration=
());
     First->InstantiatedFromMember.setPointer(PartialSpec);
   }
-   =20
-  /// \brief Determines whether this class template partial specialization=20
+
+  /// \brief Determines whether this class template partial specialization
   /// template was a specialization of a member partial specialization.
   ///
   /// In the following example, the member template partial specialization
@@ -1693,7 +1642,7 @@
       =3D cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration=
());
     return First->InstantiatedFromMember.getInt();
   }
- =20
+
   /// \brief Note that this member template is a specialization.
   void setMemberSpecialization() {
     ClassTemplatePartialSpecializationDecl *First
@@ -1711,7 +1660,7 @@
     return cast<InjectedClassNameType>(getTypeForDecl())
              ->getInjectedSpecializationType();
   }
-   =20
+
   // FIXME: Add Profile support!
=20
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -1728,18 +1677,15 @@
 };
=20
 /// Declaration of a class template.
-class ClassTemplateDecl : public RedeclarableTemplateDecl,
-                          public RedeclarableTemplate<ClassTemplateDecl> {
+class ClassTemplateDecl : public RedeclarableTemplateDecl {
   static void DeallocateCommon(void *Ptr);
- =20
+
 protected:
-  typedef RedeclarableTemplate<ClassTemplateDecl> redeclarable_base;
-
   /// \brief Data that is common to all of the declarations of a given
   /// class template.
   struct Common : CommonBase {
     Common() : LazySpecializations() { }
-   =20
+
     /// \brief The class template specializations for this class
     /// template, including explicit specializations and instantiations.
     llvm::FoldingSet<ClassTemplateSpecializationDecl> Specializations;
@@ -1751,7 +1697,7 @@
=20
     /// \brief The injected-class-name type for this class template.
     QualType InjectedClassNameType;
-   =20
+
     /// \brief If non-null, points to an array of specializations (includi=
ng
     /// partial specializations) known ownly by their external declaration=
 IDs.
     ///
@@ -1762,7 +1708,7 @@
=20
   /// \brief Load any lazily-loaded specializations from the external sour=
ce.
   void LoadLazySpecializations();
-                           =20
+
   /// \brief Retrieve the set of specializations of this class template.
   llvm::FoldingSet<ClassTemplateSpecializationDecl> &getSpecializations();
=20
@@ -1806,7 +1752,7 @@
                                    ClassTemplateDecl *PrevDecl);
=20
   /// Create an empty class template node.
-  static ClassTemplateDecl *Create(ASTContext &C, EmptyShell);
+  static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
=20
   /// \brief Return the specialization with the provided arguments if it e=
xists,
   /// otherwise return the insertion point.
@@ -1819,26 +1765,31 @@
   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertP=
os);
=20
   ClassTemplateDecl *getCanonicalDecl() {
-    return redeclarable_base::getCanonicalDecl();
+    return cast<ClassTemplateDecl>(
+             RedeclarableTemplateDecl::getCanonicalDecl());
   }
   const ClassTemplateDecl *getCanonicalDecl() const {
-    return redeclarable_base::getCanonicalDecl();
+    return cast<ClassTemplateDecl>(
+             RedeclarableTemplateDecl::getCanonicalDecl());
   }
=20
   /// \brief Retrieve the previous declaration of this class template, or
   /// NULL if no such declaration exists.
-  ClassTemplateDecl *getPreviousDeclaration() {
-    return redeclarable_base::getPreviousDeclaration();
+  ClassTemplateDecl *getPreviousDecl() {
+    return cast_or_null<ClassTemplateDecl>(
+             RedeclarableTemplateDecl::getPreviousDecl());
   }
=20
   /// \brief Retrieve the previous declaration of this class template, or
   /// NULL if no such declaration exists.
-  const ClassTemplateDecl *getPreviousDeclaration() const {
-    return redeclarable_base::getPreviousDeclaration();
+  const ClassTemplateDecl *getPreviousDecl() const {
+    return cast_or_null<ClassTemplateDecl>(
+             RedeclarableTemplateDecl::getPreviousDecl());
   }
=20
   ClassTemplateDecl *getInstantiatedFromMemberTemplate() {
-    return redeclarable_base::getInstantiatedFromMemberTemplate();
+    return cast_or_null<ClassTemplateDecl>(
+             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate()=
);
   }
=20
   /// \brief Return the partial specialization with the provided arguments=
 if it
@@ -1860,7 +1811,7 @@
   /// \brief Retrieve the partial specializations as an ordered list.
   void getPartialSpecializations(
           SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
- =20
+
   /// \brief Find a class template partial specialization with the given
   /// type T.
   ///
@@ -1870,7 +1821,7 @@
   /// \returns the class template partial specialization that exactly matc=
hes
   /// the type \p T, or NULL if no such partial specialization exists.
   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualTy=
pe T);
- =20
+
   /// \brief Find a class template partial specialization which was instan=
tiated
   /// from the given member partial specialization.
   ///
@@ -1939,6 +1890,7 @@
 /// NOTE: This class is not currently in use.  All of the above
 /// will yield a FriendDecl, not a FriendTemplateDecl.
 class FriendTemplateDecl : public Decl {
+  virtual void anchor();
 public:
   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
=20
@@ -1957,7 +1909,7 @@
=20
=20
   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
-                     unsigned NParams,=20
+                     unsigned NParams,
                      TemplateParameterList **Params,
                      FriendUnion Friend,
                      SourceLocation FriendLoc)
@@ -1977,12 +1929,12 @@
 public:
   static FriendTemplateDecl *Create(ASTContext &Context,
                                     DeclContext *DC, SourceLocation Loc,
-                                    unsigned NParams,=20
+                                    unsigned NParams,
                                     TemplateParameterList **Params,
                                     FriendUnion Friend,
                                     SourceLocation FriendLoc);
=20
-  static FriendTemplateDecl *Create(ASTContext &Context, EmptyShell Empty);
+  static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID=
);
=20
   /// If this friend declaration names a templated type (or
   /// a dependent member type of a templated type), return that
@@ -2023,13 +1975,10 @@
 /// Declaration of an alias template.  For example:
 ///
 /// template <typename T> using V =3D std::map<T*, int, MyCompare<T>>;
-class TypeAliasTemplateDecl : public RedeclarableTemplateDecl,
-                            public RedeclarableTemplate<TypeAliasTemplateD=
ecl> {
+class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
   static void DeallocateCommon(void *Ptr);
=20
 protected:
-  typedef RedeclarableTemplate<TypeAliasTemplateDecl> redeclarable_base;
-
   typedef CommonBase Common;
=20
   TypeAliasTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName=
 Name,
@@ -2050,29 +1999,34 @@
=20
=20
   TypeAliasTemplateDecl *getCanonicalDecl() {
-    return redeclarable_base::getCanonicalDecl();
+    return cast<TypeAliasTemplateDecl>(
+             RedeclarableTemplateDecl::getCanonicalDecl());
   }
   const TypeAliasTemplateDecl *getCanonicalDecl() const {
-    return redeclarable_base::getCanonicalDecl();
+    return cast<TypeAliasTemplateDecl>(
+             RedeclarableTemplateDecl::getCanonicalDecl());
   }
=20
   /// \brief Retrieve the previous declaration of this function template, =
or
   /// NULL if no such declaration exists.
-  TypeAliasTemplateDecl *getPreviousDeclaration() {
-    return redeclarable_base::getPreviousDeclaration();
+  TypeAliasTemplateDecl *getPreviousDecl() {
+    return cast_or_null<TypeAliasTemplateDecl>(
+             RedeclarableTemplateDecl::getPreviousDecl());
   }
=20
   /// \brief Retrieve the previous declaration of this function template, =
or
   /// NULL if no such declaration exists.
-  const TypeAliasTemplateDecl *getPreviousDeclaration() const {
-    return redeclarable_base::getPreviousDeclaration();
+  const TypeAliasTemplateDecl *getPreviousDecl() const {
+    return cast_or_null<TypeAliasTemplateDecl>(
+             RedeclarableTemplateDecl::getPreviousDecl());
   }
=20
   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() {
-    return redeclarable_base::getInstantiatedFromMemberTemplate();
+    return cast_or_null<TypeAliasTemplateDecl>(
+             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate()=
);
   }
=20
-                              =20
+
   /// \brief Create a function template node.
   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
                                        SourceLocation L,
@@ -2081,7 +2035,7 @@
                                        NamedDecl *Decl);
=20
   /// \brief Create an empty alias template node.
-  static TypeAliasTemplateDecl *Create(ASTContext &C, EmptyShell);
+  static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned=
 ID);
=20
   // Implement isa/cast/dyncast support
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
@@ -2105,7 +2059,8 @@
 /// CXXMethodDecl. Then during an instantiation of class A, it will be
 /// transformed into an actual function specialization.
 class ClassScopeFunctionSpecializationDecl : public Decl {
-private:
+  virtual void anchor();
+
   ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
                                        CXXMethodDecl *FD)
     : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
@@ -2126,11 +2081,9 @@
     return new (C) ClassScopeFunctionSpecializationDecl(DC , Loc, FD);
   }
=20
-  static ClassScopeFunctionSpecializationDecl *Create(ASTContext &Context,
-                                                      EmptyShell Empty) {
-    return new (Context)ClassScopeFunctionSpecializationDecl(0,
-                                                         SourceLocation(),=
 0);
-  }
+  static ClassScopeFunctionSpecializationDecl *
+  CreateDeserialized(ASTContext &Context, unsigned ID);
+ =20
   // Implement isa/cast/dyncast/etc.
   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   static bool classofKind(Kind K) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DeclVisitor.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DeclVisitor.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DeclVisitor.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -30,12 +30,12 @@
 public:
   RetTy Visit(Decl *D) {
     switch (D->getKind()) {
-      default: llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
 #define DECL(DERIVED, BASE) \
       case Decl::DERIVED: DISPATCH(DERIVED##Decl, DERIVED##Decl);
 #define ABSTRACT_DECL(DECL)
 #include "clang/AST/DeclNodes.inc"
     }
+    llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
   }
=20
   // If the implementation chooses not to implement a certain visit
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DeclarationName.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DeclarationName.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DeclarationName.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "clang/AST/Type.h"
 #include "clang/AST/CanonicalType.h"
 #include "clang/Basic/PartialDiagnostic.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace llvm {
   template <typename T> struct DenseMapInfo;
@@ -510,8 +511,17 @@
   /// getEndLoc - Retrieve the location of the last token.
   SourceLocation getEndLoc() const;
   /// getSourceRange - The range of the declaration name.
-  SourceRange getSourceRange() const {
-    return SourceRange(getBeginLoc(), getEndLoc());
+  SourceRange getSourceRange() const LLVM_READONLY {
+    SourceLocation BeginLoc =3D getBeginLoc();
+    SourceLocation EndLoc =3D getEndLoc();
+    return SourceRange(BeginLoc, EndLoc.isValid() ? EndLoc : BeginLoc);
+  }
+  SourceLocation getLocStart() const LLVM_READONLY {
+    return getBeginLoc();
+  }
+  SourceLocation getLocEnd() const LLVM_READONLY {
+    SourceLocation EndLoc =3D getEndLoc();
+    return EndLoc.isValid() ? EndLoc : getLocStart();
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/DependentDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/DependentDiagnostic.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/DependentDiagnostic.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -177,7 +177,7 @@
   assert(isDependentContext()
          && "cannot iterate dependent diagnostics of non-dependent context=
");
   const DependentStoredDeclsMap *Map
-    =3D static_cast<DependentStoredDeclsMap*>(getPrimaryContext()->LookupP=
tr);
+    =3D static_cast<DependentStoredDeclsMap*>(getPrimaryContext()->getLook=
upPtr());
=20
   if (!Map) return ddiag_iterator();
   return ddiag_iterator(Map->FirstDiagnostic);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/Expr.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/Expr.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/Expr.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -21,12 +21,13 @@
 #include "clang/AST/OperationKinds.h"
 #include "clang/AST/ASTVector.h"
 #include "clang/AST/TemplateBase.h"
-#include "clang/AST/UsuallyTinyPtrVector.h"
+#include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/TypeTraits.h"
 #include "llvm/ADT/APSInt.h"
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Compiler.h"
 #include <cctype>
=20
 namespace clang {
@@ -56,8 +57,8 @@
=20
 protected:
   Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
-       bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)=20
-    : Stmt(SC)=20
+       bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
+    : Stmt(SC)
   {
     ExprBits.TypeDependent =3D TD;
     ExprBits.ValueDependent =3D VD;
@@ -97,8 +98,8 @@
   bool isValueDependent() const { return ExprBits.ValueDependent; }
=20
   /// \brief Set whether this expression is value-dependent or not.
-  void setValueDependent(bool VD) {=20
-    ExprBits.ValueDependent =3D VD;=20
+  void setValueDependent(bool VD) {
+    ExprBits.ValueDependent =3D VD;
     if (VD)
       ExprBits.InstantiationDependent =3D true;
   }
@@ -117,8 +118,8 @@
   bool isTypeDependent() const { return ExprBits.TypeDependent; }
=20
   /// \brief Set whether this expression is type-dependent or not.
-  void setTypeDependent(bool TD) {=20
-    ExprBits.TypeDependent =3D TD;=20
+  void setTypeDependent(bool TD) {
+    ExprBits.TypeDependent =3D TD;
     if (TD)
       ExprBits.InstantiationDependent =3D true;
   }
@@ -140,12 +141,12 @@
   /// }
   /// \endcode
   ///
-  bool isInstantiationDependent() const {=20
-    return ExprBits.InstantiationDependent;=20
-  }
- =20
+  bool isInstantiationDependent() const {
+    return ExprBits.InstantiationDependent;
+  }
+
   /// \brief Set whether this expression is instantiation-dependent or not.
-  void setInstantiationDependent(bool ID) {=20
+  void setInstantiationDependent(bool ID) {
     ExprBits.InstantiationDependent =3D ID;
   }
=20
@@ -163,8 +164,8 @@
   ///
   /// The expressions \c args and \c static_cast<Types&&>(args) both
   /// contain parameter packs.
-  bool containsUnexpandedParameterPack() const {=20
-    return ExprBits.ContainsUnexpandedParameterPack;=20
+  bool containsUnexpandedParameterPack() const {
+    return ExprBits.ContainsUnexpandedParameterPack;
   }
=20
   /// \brief Set the bit that describes whether this expression
@@ -175,7 +176,7 @@
=20
   /// getExprLoc - Return the preferred location for the arrow when diagno=
sing
   /// a problem with a generic expression.
-  SourceLocation getExprLoc() const;
+  SourceLocation getExprLoc() const LLVM_READONLY;
=20
   /// isUnusedResultAWarning - Return true if this immediate expression sh=
ould
   /// be warned about if the result is unused.  If so, fill in Loc and Ran=
ges
@@ -235,7 +236,6 @@
     MLV_IncompleteType,
     MLV_ConstQualified,
     MLV_ArrayType,
-    MLV_NotBlockQualified,
     MLV_ReadonlyProperty,
     MLV_NoSetterProperty,
     MLV_MemberFunction,
@@ -271,7 +271,6 @@
       CM_RValue, // Not modifiable because it's an rvalue
       CM_Function, // Not modifiable because it's a function; C++ only
       CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalu=
e ext
-      CM_NotBlockQualified, // Not captured in the closure
       CM_NoSetterProperty,// Implicit assignment to ObjC property without =
setter
       CM_ConstQualified,
       CM_ArrayType,
@@ -302,12 +301,12 @@
     bool isPRValue() const { return Kind >=3D CL_Function; }
     bool isRValue() const { return Kind >=3D CL_XValue; }
     bool isModifiable() const { return getModifiable() =3D=3D CM_Modifiabl=
e; }
-   =20
+
     /// \brief Create a simple, modifiably lvalue
     static Classification makeSimpleLValue() {
       return Classification(CL_LValue, CM_Modifiable);
     }
-   =20
+
   };
   /// \brief Classify - Classify this expression according to the C++0x
   ///        expression taxonomy.
@@ -390,54 +389,79 @@
=20
   /// \brief Returns whether this expression refers to a vector element.
   bool refersToVectorElement() const;
- =20
+
+  /// \brief Returns whether this expression has a placeholder type.
+  bool hasPlaceholderType() const {
+    return getType()->isPlaceholderType();
+  }
+
+  /// \brief Returns whether this expression has a specific placeholder ty=
pe.
+  bool hasPlaceholderType(BuiltinType::Kind K) const {
+    assert(BuiltinType::isPlaceholderTypeKind(K));
+    if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(getType()))
+      return BT->getKind() =3D=3D K;
+    return false;
+  }
+
   /// isKnownToHaveBooleanValue - Return true if this is an integer expres=
sion
   /// that is known to return 0 or 1.  This happens for _Bool/bool express=
ions
   /// but also int expressions which are produced by things like compariso=
ns in
   /// C.
   bool isKnownToHaveBooleanValue() const;
- =20
+
   /// isIntegerConstantExpr - Return true if this expression is a valid in=
teger
   /// constant expression, and, if so, return its value in Result.  If not=
 a
   /// valid i-c-e, return false and fill in Loc (if specified) with the lo=
cation
   /// of the invalid expression.
+  ///
+  /// Note: This does not perform the implicit conversions required by C++=
11
+  /// [expr.const]p5.
   bool isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
                              SourceLocation *Loc =3D 0,
                              bool isEvaluated =3D true) const;
-  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc =3D 0) c=
onst {
-    llvm::APSInt X;
-    return isIntegerConstantExpr(X, Ctx, Loc);
-  }
-  /// isConstantInitializer - Returns true if this expression is a constant
-  /// initializer, which can be emitted at compile-time.
+  bool isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc =3D 0) c=
onst;
+
+  /// isCXX98IntegralConstantExpr - Return true if this expression is an
+  /// integral constant expression in C++98. Can only be used in C++.
+  bool isCXX98IntegralConstantExpr(ASTContext &Ctx) const;
+
+  /// isCXX11ConstantExpr - Return true if this expression is a constant
+  /// expression in C++11. Can only be used in C++.
+  ///
+  /// Note: This does not perform the implicit conversions required by C++=
11
+  /// [expr.const]p5.
+  bool isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result =3D 0,
+                           SourceLocation *Loc =3D 0) const;
+
+  /// isPotentialConstantExpr - Return true if this function's definition
+  /// might be usable in a constant expression in C++11, if it were marked
+  /// constexpr. Return false if the function can never produce a constant
+  /// expression, along with diagnostics describing why not.
+  static bool isPotentialConstantExpr(const FunctionDecl *FD,
+                                      llvm::SmallVectorImpl<
+                                        PartialDiagnosticAt> &Diags);
+
+  /// isConstantInitializer - Returns true if this expression can be emitt=
ed to
+  /// IR as a constant, and thus can be used as a constant initializer in =
C.
   bool isConstantInitializer(ASTContext &Ctx, bool ForRef) const;
=20
-  /// EvalResult is a struct with detailed info about an evaluated express=
ion.
-  struct EvalResult {
-    /// Val - This is the value the expression can be folded to.
-    APValue Val;
-
+  /// EvalStatus is a struct with detailed info about an evaluation in pro=
gress.
+  struct EvalStatus {
     /// HasSideEffects - Whether the evaluated expression has side effects.
     /// For example, (f() && 0) can be folded, but it still has side effec=
ts.
     bool HasSideEffects;
=20
-    /// Diag - If the expression is unfoldable, then Diag contains a note
-    /// diagnostic indicating why it's not foldable. DiagLoc indicates a c=
aret
-    /// position for the error, and DiagExpr is the expression that caused
-    /// the error.
-    /// If the expression is foldable, but not an integer constant express=
ion,
-    /// Diag contains a note diagnostic that describes why it isn't an int=
eger
-    /// constant expression. If the expression *is* an integer constant
-    /// expression, then Diag will be zero.
-    unsigned Diag;
-    const Expr *DiagExpr;
-    SourceLocation DiagLoc;
-
-    EvalResult() : HasSideEffects(false), Diag(0), DiagExpr(0) {}
-
-    // isGlobalLValue - Return true if the evaluated lvalue expression
-    // is global.
-    bool isGlobalLValue() const;
+    /// Diag - If this is non-null, it will be filled in with a stack of n=
otes
+    /// indicating why evaluation failed (or why it failed to produce a co=
nstant
+    /// expression).
+    /// If the expression is unfoldable, the notes will indicate why it's =
not
+    /// foldable. If the expression is foldable, but not a constant expres=
sion,
+    /// the notes will describes why it isn't a constant expression. If the
+    /// expression *is* a constant expression, no notes will be produced.
+    llvm::SmallVectorImpl<PartialDiagnosticAt> *Diag;
+
+    EvalStatus() : HasSideEffects(false), Diag(0) {}
+
     // hasSideEffects - Return true if the evaluated expression has
     // side effects.
     bool hasSideEffects() const {
@@ -445,11 +469,23 @@
     }
   };
=20
-  /// Evaluate - Return true if this is a constant which we can fold using
-  /// any crazy technique (that has nothing to do with language standards)=
 that
-  /// we want to.  If this function returns true, it returns the folded co=
nstant
-  /// in Result.
-  bool Evaluate(EvalResult &Result, const ASTContext &Ctx) const;
+  /// EvalResult is a struct with detailed info about an evaluated express=
ion.
+  struct EvalResult : EvalStatus {
+    /// Val - This is the value the expression can be folded to.
+    APValue Val;
+
+    // isGlobalLValue - Return true if the evaluated lvalue expression
+    // is global.
+    bool isGlobalLValue() const;
+  };
+
+  /// EvaluateAsRValue - Return true if this is a constant which we can fo=
ld to
+  /// an rvalue using any crazy technique (that has nothing to do with lan=
guage
+  /// standards) that we want to, even if the expression has side-effects.=
 If
+  /// this function returns true, it returns the folded constant in Result=
. If
+  /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
+  /// applied.
+  bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
=20
   /// EvaluateAsBooleanCondition - Return true if this is a constant
   /// which we we can fold and convert to a boolean condition using
@@ -457,30 +493,43 @@
   /// side-effects.
   bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) con=
st;
=20
+  enum SideEffectsKind { SE_NoSideEffects, SE_AllowSideEffects };
+
   /// EvaluateAsInt - Return true if this is a constant which we can fold =
and
-  /// convert to an integer using any crazy technique that we want to.
-  bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx) const;
-
-  /// isEvaluatable - Call Evaluate to see if this expression can be const=
ant
-  /// folded, but discard the result.
+  /// convert to an integer, using any crazy technique that we want to.
+  bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
+                     SideEffectsKind AllowSideEffects =3D SE_NoSideEffects=
) const;
+
+  /// isEvaluatable - Call EvaluateAsRValue to see if this expression can =
be
+  /// constant folded without side-effects, but discard the result.
   bool isEvaluatable(const ASTContext &Ctx) const;
=20
   /// HasSideEffects - This routine returns true for all those expressions
-  /// which must be evaluated each time and must not be optimized away=20
+  /// which must be evaluated each time and must not be optimized away
   /// or evaluated at compile time. Example is a function call, volatile
   /// variable read.
   bool HasSideEffects(const ASTContext &Ctx) const;
+
+  /// \brief Determine whether this expression involves a call to any func=
tion
+  /// that is not trivial.
+  bool hasNonTrivialCall(ASTContext &Ctx);
  =20
-  /// EvaluateKnownConstInt - Call Evaluate and return the folded integer.=
 This
-  /// must be called on an expression that constant folds to an integer.
+  /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
+  /// integer. This must be called on an expression that constant folds to=
 an
+  /// integer.
   llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const;
=20
-  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue
-  /// with link time known address.
+  /// EvaluateAsLValue - Evaluate an expression to see if we can fold it t=
o an
+  /// lvalue with link time known address, with no side-effects.
   bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
=20
-  /// EvaluateAsLValue - Evaluate an expression to see if it's a lvalue.
-  bool EvaluateAsAnyLValue(EvalResult &Result, const ASTContext &Ctx) cons=
t;
+  /// EvaluateAsInitializer - Evaluate an expression as if it were the
+  /// initializer of the given declaration. Returns true if the initializer
+  /// can be folded to a constant, and produces any relevant notes. In C++=
11,
+  /// notes will be produced if the expression is not a constant expressio=
n.
+  bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
+                             const VarDecl *VD,
+                       llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) =
const;
=20
   /// \brief Enumeration used to describe the kind of Null pointer constant
   /// returned from \c isNullPointerConstant().
@@ -503,16 +552,16 @@
   enum NullPointerConstantValueDependence {
     /// \brief Specifies that the expression should never be value-depende=
nt.
     NPC_NeverValueDependent =3D 0,
-   =20
+
     /// \brief Specifies that a value-dependent expression of integral or
     /// dependent type should be considered a null pointer constant.
     NPC_ValueDependentIsNull,
-   =20
+
     /// \brief Specifies that a value-dependent expression should be consi=
dered
     /// to never be a null pointer constant.
     NPC_ValueDependentIsNotNull
   };
- =20
+
   /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
   /// a Null pointer constant. The return value can further distinguish the
   /// kind of NULL pointer constant that was detected.
@@ -544,60 +593,62 @@
=20
   /// IgnoreImpCasts - Skip past any implicit casts which might
   /// surround this expression.  Only skips ImplicitCastExprs.
-  Expr *IgnoreImpCasts();
+  Expr *IgnoreImpCasts() LLVM_READONLY;
=20
   /// IgnoreImplicit - Skip past any implicit AST nodes which might
   /// surround this expression.
-  Expr *IgnoreImplicit() { return cast<Expr>(Stmt::IgnoreImplicit()); }
+  Expr *IgnoreImplicit() LLVM_READONLY {
+    return cast<Expr>(Stmt::IgnoreImplicit());
+  }
=20
   /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, ret=
urn
   ///  its subexpression.  If that subexpression is also a ParenExpr,
   ///  then this method recursively returns its subexpression, and so fort=
h.
   ///  Otherwise, the method returns the current Expr.
-  Expr *IgnoreParens();
+  Expr *IgnoreParens() LLVM_READONLY;
=20
   /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any Pare=
nExpr
   /// or CastExprs, returning their operand.
-  Expr *IgnoreParenCasts();
-
-  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip =
off any
-  /// ParenExpr or ImplicitCastExprs, returning their operand.
-  Expr *IgnoreParenImpCasts();
+  Expr *IgnoreParenCasts() LLVM_READONLY;
+
+  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip =
off
+  /// any ParenExpr or ImplicitCastExprs, returning their operand.
+  Expr *IgnoreParenImpCasts() LLVM_READONLY;
=20
   /// IgnoreConversionOperator - Ignore conversion operator. If this Expr =
is a
   /// call to a conversion operator, return the argument.
-  Expr *IgnoreConversionOperator();
-
-  const Expr *IgnoreConversionOperator() const {
+  Expr *IgnoreConversionOperator() LLVM_READONLY;
+
+  const Expr *IgnoreConversionOperator() const LLVM_READONLY {
     return const_cast<Expr*>(this)->IgnoreConversionOperator();
   }
=20
-  const Expr *IgnoreParenImpCasts() const {
+  const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
     return const_cast<Expr*>(this)->IgnoreParenImpCasts();
   }
- =20
+
   /// Ignore parentheses and lvalue casts.  Strip off any ParenExpr and
   /// CastExprs that represent lvalue casts, returning their operand.
-  Expr *IgnoreParenLValueCasts();
- =20
-  const Expr *IgnoreParenLValueCasts() const {
+  Expr *IgnoreParenLValueCasts() LLVM_READONLY;
+
+  const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
     return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
   }
=20
   /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not chan=
ge the
   /// value (including ptr->int casts of the same size).  Strip off any
   /// ParenExpr or CastExprs, returning their operand.
-  Expr *IgnoreParenNoopCasts(ASTContext &Ctx);
+  Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
=20
   /// \brief Determine whether this expression is a default function argum=
ent.
   ///
   /// Default arguments are implicitly generated in the abstract syntax tr=
ee
-  /// by semantic analysis for function calls, object constructions, etc. =
in=20
+  /// by semantic analysis for function calls, object constructions, etc. =
in
   /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
   /// this routine also looks through any implicit casts to determine whet=
her
   /// the expression is a default argument.
   bool isDefaultArgument() const;
- =20
+
   /// \brief Determine whether the result of this expression is a
   /// temporary object of the given class type.
   bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) con=
st;
@@ -605,21 +656,20 @@
   /// \brief Whether this expression is an implicit reference to 'this' in=
 C++.
   bool isImplicitCXXThis() const;
=20
-  const Expr *IgnoreImpCasts() const {
+  const Expr *IgnoreImpCasts() const LLVM_READONLY {
     return const_cast<Expr*>(this)->IgnoreImpCasts();
   }
-  const Expr *IgnoreParens() const {
+  const Expr *IgnoreParens() const LLVM_READONLY {
     return const_cast<Expr*>(this)->IgnoreParens();
   }
-  const Expr *IgnoreParenCasts() const {
+  const Expr *IgnoreParenCasts() const LLVM_READONLY {
     return const_cast<Expr*>(this)->IgnoreParenCasts();
   }
-  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const {
+  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
     return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
   }
=20
-  static bool hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs=
);
-  static bool hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExpr=
s);
+  static bool hasAnyTypeDependentArguments(llvm::ArrayRef<Expr *> Exprs);
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() >=3D firstExprConstant &&
@@ -642,15 +692,18 @@
   friend class ASTStmtReader;
   Expr *SourceExpr;
   SourceLocation Loc;
- =20
+
 public:
-  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,=20
-                  ExprObjectKind OK =3D OK_Ordinary)
+  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
+                  ExprObjectKind OK =3D OK_Ordinary,
+                  Expr *SourceExpr =3D 0)
     : Expr(OpaqueValueExprClass, T, VK, OK,
-           T->isDependentType(), T->isDependentType(),=20
+           T->isDependentType(),=20
+           T->isDependentType() ||=20
+           (SourceExpr && SourceExpr->isValueDependent()),
            T->isInstantiationDependentType(),
-           false),=20
-      SourceExpr(0), Loc(Loc) {
+           false),
+      SourceExpr(SourceExpr), Loc(Loc) {
   }
=20
   /// Given an expression which invokes a copy constructor --- i.e.  a
@@ -663,12 +716,12 @@
=20
   /// \brief Retrieve the location of this expression.
   SourceLocation getLocation() const { return Loc; }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     if (SourceExpr) return SourceExpr->getSourceRange();
     return Loc;
   }
-  SourceLocation getExprLoc() const {
+  SourceLocation getExprLoc() const LLVM_READONLY {
     if (SourceExpr) return SourceExpr->getExprLoc();
     return Loc;
   }
@@ -684,7 +737,6 @@
   /// expression which binds the opaque value expression in the first
   /// place.
   Expr *getSourceExpr() const { return SourceExpr; }
-  void setSourceExpr(Expr *e) { SourceExpr =3D e; }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D OpaqueValueExprClass;
@@ -709,9 +761,12 @@
 ///       Specifies when this declaration reference expression has a recor=
d of
 ///       a NamedDecl (different from the referenced ValueDecl) which was =
found
 ///       during name lookup and/or overload resolution.
-///   DeclRefExprBits.HasExplicitTemplateArgs:
+///   DeclRefExprBits.HasTemplateKWAndArgsInfo:
 ///       Specifies when this declaration reference expression has an expl=
icit
-///       C++ template argument list.
+///       C++ template keyword and/or template argument list.
+///   DeclRefExprBits.RefersToEnclosingLocal
+///       Specifies when this declaration reference expression (validly)
+///       refers to a local variable from a different function.
 class DeclRefExpr : public Expr {
   /// \brief The declaration that we are referencing.
   ValueDecl *D;
@@ -753,8 +808,11 @@
     return const_cast<DeclRefExpr *>(this)->getInternalFoundDecl();
   }
=20
-  DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
-              ValueDecl *D, const DeclarationNameInfo &NameInfo,
+  DeclRefExpr(ASTContext &Ctx,
+              NestedNameSpecifierLoc QualifierLoc,
+              SourceLocation TemplateKWLoc,
+              ValueDecl *D, bool refersToEnclosingLocal,
+              const DeclarationNameInfo &NameInfo,
               NamedDecl *FoundD,
               const TemplateArgumentListInfo *TemplateArgs,
               QualType T, ExprValueKind VK);
@@ -765,23 +823,27 @@
=20
   /// \brief Computes the type- and value-dependence flags for this
   /// declaration reference expression.
-  void computeDependence();
+  void computeDependence(ASTContext &C);
=20
 public:
-  DeclRefExpr(ValueDecl *D, QualType T, ExprValueKind VK, SourceLocation L,
+  DeclRefExpr(ValueDecl *D, bool refersToEnclosingLocal, QualType T,
+              ExprValueKind VK, SourceLocation L,
               const DeclarationNameLoc &LocInfo =3D DeclarationNameLoc())
     : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, fals=
e),
       D(D), Loc(L), DNLoc(LocInfo) {
     DeclRefExprBits.HasQualifier =3D 0;
-    DeclRefExprBits.HasExplicitTemplateArgs =3D 0;
+    DeclRefExprBits.HasTemplateKWAndArgsInfo =3D 0;
     DeclRefExprBits.HasFoundDecl =3D 0;
     DeclRefExprBits.HadMultipleCandidates =3D 0;
-    computeDependence();
+    DeclRefExprBits.RefersToEnclosingLocal =3D refersToEnclosingLocal;
+    computeDependence(D->getASTContext());
   }
=20
   static DeclRefExpr *Create(ASTContext &Context,
                              NestedNameSpecifierLoc QualifierLoc,
+                             SourceLocation TemplateKWLoc,
                              ValueDecl *D,
+                             bool isEnclosingLocal,
                              SourceLocation NameLoc,
                              QualType T, ExprValueKind VK,
                              NamedDecl *FoundD =3D 0,
@@ -789,7 +851,9 @@
=20
   static DeclRefExpr *Create(ASTContext &Context,
                              NestedNameSpecifierLoc QualifierLoc,
+                             SourceLocation TemplateKWLoc,
                              ValueDecl *D,
+                             bool isEnclosingLocal,
                              const DeclarationNameInfo &NameInfo,
                              QualType T, ExprValueKind VK,
                              NamedDecl *FoundD =3D 0,
@@ -799,7 +863,7 @@
   static DeclRefExpr *CreateEmpty(ASTContext &Context,
                                   bool HasQualifier,
                                   bool HasFoundDecl,
-                                  bool HasExplicitTemplateArgs,
+                                  bool HasTemplateKWAndArgsInfo,
                                   unsigned NumTemplateArgs);
=20
   ValueDecl *getDecl() { return D; }
@@ -812,7 +876,9 @@
=20
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc =3D L; }
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
+  SourceLocation getLocStart() const LLVM_READONLY;
+  SourceLocation getLocEnd() const LLVM_READONLY;
=20
   /// \brief Determine whether this declaration reference was preceded by a
   /// C++ nested-name-specifier, e.g., \c N::foo.
@@ -851,25 +917,65 @@
     return hasFoundDecl() ? getInternalFoundDecl() : D;
   }
=20
+  bool hasTemplateKWAndArgsInfo() const {
+    return DeclRefExprBits.HasTemplateKWAndArgsInfo;
+  }
+
+  /// \brief Return the optional template keyword and arguments info.
+  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
+    if (!hasTemplateKWAndArgsInfo())
+      return 0;
+
+    if (hasFoundDecl())
+      return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
+        &getInternalFoundDecl() + 1);
+
+    if (hasQualifier())
+      return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
+        &getInternalQualifierLoc() + 1);
+
+    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
+  }
+
+  /// \brief Return the optional template keyword and arguments info.
+  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
+    return const_cast<DeclRefExpr*>(this)->getTemplateKWAndArgsInfo();
+  }
+
+  /// \brief Retrieve the location of the template keyword preceding
+  /// this name, if any.
+  SourceLocation getTemplateKeywordLoc() const {
+    if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
+  }
+
+  /// \brief Retrieve the location of the left angle bracket starting the
+  /// explicit template argument list following the name, if any.
+  SourceLocation getLAngleLoc() const {
+    if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->LAngleLoc;
+  }
+
+  /// \brief Retrieve the location of the right angle bracket ending the
+  /// explicit template argument list following the name, if any.
+  SourceLocation getRAngleLoc() const {
+    if (!hasTemplateKWAndArgsInfo()) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->RAngleLoc;
+  }
+
+  /// \brief Determines whether the name in this declaration reference
+  /// was preceded by the template keyword.
+  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid=
(); }
+
   /// \brief Determines whether this declaration reference was followed by=
 an
-  /// explict template argument list.
-  bool hasExplicitTemplateArgs() const {
-    return DeclRefExprBits.HasExplicitTemplateArgs;
-  }
+  /// explicit template argument list.
+  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
=20
   /// \brief Retrieve the explicit template argument list that followed the
   /// member template name.
   ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
     assert(hasExplicitTemplateArgs());
-    if (hasFoundDecl())
-      return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
-        &getInternalFoundDecl() + 1);
-
-    if (hasQualifier())
-      return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
-        &getInternalQualifierLoc() + 1);
-
-    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
+    return *getTemplateKWAndArgsInfo();
   }
=20
   /// \brief Retrieve the explicit template argument list that followed the
@@ -881,7 +987,7 @@
   /// \brief Retrieves the optional explicit template arguments.
   /// This points to the same data as getExplicitTemplateArgs(), but
   /// returns null if there are no explicit template arguments.
-  const ASTTemplateArgumentListInfo *getExplicitTemplateArgsOpt() const {
+  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() con=
st {
     if (!hasExplicitTemplateArgs()) return 0;
     return &getExplicitTemplateArgs();
   }
@@ -893,15 +999,6 @@
       getExplicitTemplateArgs().copyInto(List);
   }
=20
-  /// \brief Retrieve the location of the left angle bracket following the
-  /// member name ('<'), if any.
-  SourceLocation getLAngleLoc() const {
-    if (!hasExplicitTemplateArgs())
-      return SourceLocation();
-
-    return getExplicitTemplateArgs().LAngleLoc;
-  }
-
   /// \brief Retrieve the template arguments provided as part of this
   /// template-id.
   const TemplateArgumentLoc *getTemplateArgs() const {
@@ -920,15 +1017,6 @@
     return getExplicitTemplateArgs().NumTemplateArgs;
   }
=20
-  /// \brief Retrieve the location of the right angle bracket following the
-  /// template arguments ('>').
-  SourceLocation getRAngleLoc() const {
-    if (!hasExplicitTemplateArgs())
-      return SourceLocation();
-
-    return getExplicitTemplateArgs().RAngleLoc;
-  }
-
   /// \brief Returns true if this expression refers to a function that
   /// was resolved from an overloaded set having size greater than 1.
   bool hadMultipleCandidates() const {
@@ -941,6 +1029,12 @@
     DeclRefExprBits.HadMultipleCandidates =3D V;
   }
=20
+  /// Does this DeclRefExpr refer to a local declaration from an
+  /// enclosing function scope?
+  bool refersToEnclosingLocal() const {
+    return DeclRefExprBits.RefersToEnclosingLocal;
+  }
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D DeclRefExprClass;
   }
@@ -971,7 +1065,7 @@
 public:
   PredefinedExpr(SourceLocation l, QualType type, IdentType IT)
     : Expr(PredefinedExprClass, type, VK_LValue, OK_Ordinary,
-           type->isDependentType(), type->isDependentType(),=20
+           type->isDependentType(), type->isDependentType(),
            type->isInstantiationDependentType(),
            /*ContainsUnexpandedParameterPack=3D*/false),
       Loc(l), Type(IT) {}
@@ -988,7 +1082,7 @@
=20
   static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
=20
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D PredefinedExprClass;
@@ -1008,11 +1102,11 @@
 /// the APFloat/APInt values will never get freed. APNumericStorage uses
 /// ASTContext's allocator for memory allocation.
 class APNumericStorage {
-  unsigned BitWidth;
   union {
     uint64_t VAL;    ///< Used to store the <=3D 64 bits integer value.
     uint64_t *pVal;  ///< Used to store the >64 bits integer value.
   };
+  unsigned BitWidth;
=20
   bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) >=
 1; }
=20
@@ -1020,7 +1114,7 @@
   APNumericStorage& operator=3D(const APNumericStorage&); // do not implem=
ent
=20
 protected:
-  APNumericStorage() : BitWidth(0), VAL(0) { }
+  APNumericStorage() : VAL(0), BitWidth(0) { }
=20
   llvm::APInt getIntValue() const {
     unsigned NumWords =3D llvm::APInt::getNumWords(BitWidth);
@@ -1032,22 +1126,23 @@
   void setIntValue(ASTContext &C, const llvm::APInt &Val);
 };
=20
-class APIntStorage : public APNumericStorage {
-public: =20
-  llvm::APInt getValue() const { return getIntValue(); }=20
+class APIntStorage : private APNumericStorage {
+public:
+  llvm::APInt getValue() const { return getIntValue(); }
   void setValue(ASTContext &C, const llvm::APInt &Val) { setIntValue(C, Va=
l); }
 };
=20
-class APFloatStorage : public APNumericStorage {
-public: =20
-  llvm::APFloat getValue() const { return llvm::APFloat(getIntValue()); }=20
+class APFloatStorage : private APNumericStorage {
+public:
+  llvm::APFloat getValue(bool IsIEEE) const {
+    return llvm::APFloat(getIntValue(), IsIEEE);
+  }
   void setValue(ASTContext &C, const llvm::APFloat &Val) {
     setIntValue(C, Val.bitcastToAPInt());
   }
 };
=20
-class IntegerLiteral : public Expr {
-  APIntStorage Num;
+class IntegerLiteral : public Expr, public APIntStorage {
   SourceLocation Loc;
=20
   /// \brief Construct an empty integer literal.
@@ -1077,13 +1172,11 @@
   /// \brief Returns a new empty integer literal.
   static IntegerLiteral *Create(ASTContext &C, EmptyShell Empty);
=20
-  llvm::APInt getValue() const { return Num.getValue(); }
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
=20
   /// \brief Retrieve the location of the literal.
   SourceLocation getLocation() const { return Loc; }
=20
-  void setValue(ASTContext &C, const llvm::APInt &Val) { Num.setValue(C, V=
al); }
   void setLocation(SourceLocation Location) { Loc =3D Location; }
=20
   static bool classof(const Stmt *T) {
@@ -1107,28 +1200,30 @@
 private:
   unsigned Value;
   SourceLocation Loc;
-  unsigned Kind : 2;
 public:
   // type should be IntTy
   CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
                    SourceLocation l)
     : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, fal=
se,
            false, false),
-      Value(value), Loc(l), Kind(kind) {
+      Value(value), Loc(l) {
+    CharacterLiteralBits.Kind =3D kind;
   }
=20
   /// \brief Construct an empty character literal.
   CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) =
{ }
=20
   SourceLocation getLocation() const { return Loc; }
-  CharacterKind getKind() const { return static_cast<CharacterKind>(Kind);=
 }
-
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
+  CharacterKind getKind() const {
+    return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
+  }
+
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
=20
   unsigned getValue() const { return Value; }
=20
   void setLocation(SourceLocation Location) { Loc =3D Location; }
-  void setKind(CharacterKind kind) { Kind =3D kind; }
+  void setKind(CharacterKind kind) { CharacterLiteralBits.Kind =3D kind; }
   void setValue(unsigned Val) { Value =3D Val; }
=20
   static bool classof(const Stmt *T) {
@@ -1140,35 +1235,41 @@
   child_range children() { return child_range(); }
 };
=20
-class FloatingLiteral : public Expr {
-  APFloatStorage Num;
-  bool IsExact : 1;
+class FloatingLiteral : public Expr, private APFloatStorage {
   SourceLocation Loc;
=20
   FloatingLiteral(ASTContext &C, const llvm::APFloat &V, bool isexact,
                   QualType Type, SourceLocation L)
     : Expr(FloatingLiteralClass, Type, VK_RValue, OK_Ordinary, false, fals=
e,
-           false, false),
-      IsExact(isexact), Loc(L) {
+           false, false), Loc(L) {
+    FloatingLiteralBits.IsIEEE =3D
+      &C.getTargetInfo().getLongDoubleFormat() =3D=3D &llvm::APFloat::IEEE=
quad;
+    FloatingLiteralBits.IsExact =3D isexact;
     setValue(C, V);
   }
=20
   /// \brief Construct an empty floating-point literal.
-  explicit FloatingLiteral(EmptyShell Empty)
-    : Expr(FloatingLiteralClass, Empty), IsExact(false) { }
+  explicit FloatingLiteral(ASTContext &C, EmptyShell Empty)
+    : Expr(FloatingLiteralClass, Empty) {
+    FloatingLiteralBits.IsIEEE =3D
+      &C.getTargetInfo().getLongDoubleFormat() =3D=3D &llvm::APFloat::IEEE=
quad;
+    FloatingLiteralBits.IsExact =3D false;
+  }
=20
 public:
   static FloatingLiteral *Create(ASTContext &C, const llvm::APFloat &V,
                                  bool isexact, QualType Type, SourceLocati=
on L);
   static FloatingLiteral *Create(ASTContext &C, EmptyShell Empty);
=20
-  llvm::APFloat getValue() const { return Num.getValue(); }
+  llvm::APFloat getValue() const {
+    return APFloatStorage::getValue(FloatingLiteralBits.IsIEEE);
+  }
   void setValue(ASTContext &C, const llvm::APFloat &Val) {
-    Num.setValue(C, Val);
-  }
-
-  bool isExact() const { return IsExact; }
-  void setExact(bool E) { IsExact =3D E; }
+    APFloatStorage::setValue(C, Val);
+  }
+
+  bool isExact() const { return FloatingLiteralBits.IsExact; }
+  void setExact(bool E) { FloatingLiteralBits.IsExact =3D E; }
=20
   /// getValueAsApproximateDouble - This returns the value as an inaccurate
   /// double.  Note that this may cause loss of precision, but is useful f=
or
@@ -1178,7 +1279,7 @@
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc =3D L; }
=20
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D FloatingLiteralClass;
@@ -1210,7 +1311,7 @@
   Expr *getSubExpr() { return cast<Expr>(Val); }
   void setSubExpr(Expr *E) { Val =3D E; }
=20
-  SourceRange getSourceRange() const { return Val->getSourceRange(); }
+  SourceRange getSourceRange() const LLVM_READONLY { return Val->getSource=
Range(); }
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D ImaginaryLiteralClass;
   }
@@ -1249,17 +1350,24 @@
 private:
   friend class ASTStmtReader;
=20
-  const char *StrData;
-  unsigned ByteLength;
+  union {
+    const char *asChar;
+    const uint16_t *asUInt16;
+    const uint32_t *asUInt32;
+  } StrData;
+  unsigned Length;
+  unsigned CharByteWidth : 4;
+  unsigned Kind : 3;
+  unsigned IsPascal : 1;
   unsigned NumConcatenated;
-  unsigned Kind : 3;
-  bool IsPascal : 1;
   SourceLocation TokLocs[1];
=20
   StringLiteral(QualType Ty) :
     Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, fal=
se,
          false) {}
=20
+  static int mapCharByteWidth(TargetInfo const &target,StringKind k);
+
 public:
   /// This is the "fully general" constructor that allows representation of
   /// strings formed from multiple concatenated tokens.
@@ -1278,15 +1386,46 @@
   static StringLiteral *CreateEmpty(ASTContext &C, unsigned NumStrs);
=20
   StringRef getString() const {
-    return StringRef(StrData, ByteLength);
-  }
-
-  unsigned getByteLength() const { return ByteLength; }
+    assert(CharByteWidth=3D=3D1
+           && "This function is used in places that assume strings use cha=
r");
+    return StringRef(StrData.asChar, getByteLength());
+  }
+
+  /// Allow clients that need the byte representation, such as ASTWriterSt=
mt
+  /// ::VisitStringLiteral(), access.
+  StringRef getBytes() const {
+    // FIXME: StringRef may not be the right type to use as a result for t=
his.
+    if (CharByteWidth =3D=3D 1)
+      return StringRef(StrData.asChar, getByteLength());
+    if (CharByteWidth =3D=3D 4)
+      return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
+                       getByteLength());
+    assert(CharByteWidth =3D=3D 2 && "unsupported CharByteWidth");
+    return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
+                     getByteLength());
+  }
+
+  uint32_t getCodeUnit(size_t i) const {
+    assert(i < Length && "out of bounds access");
+    if (CharByteWidth =3D=3D 1)
+      return static_cast<unsigned char>(StrData.asChar[i]);
+    if (CharByteWidth =3D=3D 4)
+      return StrData.asUInt32[i];
+    assert(CharByteWidth =3D=3D 2 && "unsupported CharByteWidth");
+    return StrData.asUInt16[i];
+  }
+
+  unsigned getByteLength() const { return CharByteWidth*Length; }
+  unsigned getLength() const { return Length; }
+  unsigned getCharByteWidth() const { return CharByteWidth; }
=20
   /// \brief Sets the string data to the given string data.
-  void setString(ASTContext &C, StringRef Str);
+  void setString(ASTContext &C, StringRef Str,
+                 StringKind Kind, bool IsPascal);
=20
   StringKind getKind() const { return static_cast<StringKind>(Kind); }
+
+
   bool isAscii() const { return Kind =3D=3D Ascii; }
   bool isWide() const { return Kind =3D=3D Wide; }
   bool isUTF8() const { return Kind =3D=3D UTF8; }
@@ -1301,6 +1440,7 @@
         return true;
     return false;
   }
+
   /// getNumConcatenated - Get the number of string literal tokens that we=
re
   /// concatenated in translation phase #6 to form this string literal.
   unsigned getNumConcatenated() const { return NumConcatenated; }
@@ -1313,7 +1453,7 @@
     assert(TokNum < NumConcatenated && "Invalid tok number");
     TokLocs[TokNum] =3D L;
   }
- =20
+
   /// getLocationOfByte - Return a source location that points to the spec=
ified
   /// byte of this string literal.
   ///
@@ -1329,7 +1469,7 @@
   tokloc_iterator tokloc_begin() const { return TokLocs; }
   tokloc_iterator tokloc_end() const { return TokLocs+NumConcatenated; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(TokLocs[0], TokLocs[NumConcatenated-1]);
   }
   static bool classof(const Stmt *T) {
@@ -1363,7 +1503,7 @@
   Expr *getSubExpr() { return cast<Expr>(Val); }
   void setSubExpr(Expr *E) { Val =3D E; }
=20
-  SourceRange getSourceRange() const { return SourceRange(L, R); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(L,=
 R); }
=20
   /// \brief Get the location of the left parentheses '('.
   SourceLocation getLParen() const { return L; }
@@ -1408,7 +1548,7 @@
     : Expr(UnaryOperatorClass, type, VK, OK,
            input->isTypeDependent() || type->isDependentType(),
            input->isValueDependent(),
-           (input->isInstantiationDependent() ||=20
+           (input->isInstantiationDependent() ||
             type->isInstantiationDependentType()),
            input->containsUnexpandedParameterPack()),
       Opc(opc), Loc(l), Val(input) {}
@@ -1439,12 +1579,26 @@
=20
   bool isPrefix() const { return isPrefix(getOpcode()); }
   bool isPostfix() const { return isPostfix(getOpcode()); }
+
+  static bool isIncrementOp(Opcode Op) {
+    return Op =3D=3D UO_PreInc || Op =3D=3D UO_PostInc;
+  }
   bool isIncrementOp() const {
-    return Opc =3D=3D UO_PreInc || Opc =3D=3D UO_PostInc;
-  }
+    return isIncrementOp(getOpcode());
+  }
+
+  static bool isDecrementOp(Opcode Op) {
+    return Op =3D=3D UO_PreDec || Op =3D=3D UO_PostDec;
+  }
+  bool isDecrementOp() const {
+    return isDecrementOp(getOpcode());
+  }
+
+  static bool isIncrementDecrementOp(Opcode Op) { return Op <=3D UO_PreDec=
; }
   bool isIncrementDecrementOp() const {
-    return Opc <=3D UO_PreDec;
-  }
+    return isIncrementDecrementOp(getOpcode());
+  }
+
   static bool isArithmeticOp(Opcode Op) {
     return Op >=3D UO_Plus && Op <=3D UO_LNot;
   }
@@ -1462,13 +1616,13 @@
   /// the given unary opcode.
   static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     if (isPostfix())
       return SourceRange(Val->getLocStart(), Loc);
     else
       return SourceRange(Loc, Val->getLocEnd());
   }
-  SourceLocation getExprLoc() const { return Loc; }
+  SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D UnaryOperatorClass;
@@ -1484,14 +1638,14 @@
 /// @code
 /// struct S {
 ///   float f;
-///   double d;   =20
+///   double d;
 /// };
 /// struct T {
 ///   int i;
 ///   struct S s[10];
 /// };
 /// @endcode
-/// we can represent and evaluate the expression @c offsetof(struct T, s[2=
].d).=20
+/// we can represent and evaluate the expression @c offsetof(struct T, s[2=
].d).
=20
 class OffsetOfExpr : public Expr {
 public:
@@ -1513,48 +1667,48 @@
=20
   private:
     enum { MaskBits =3D 2, Mask =3D 0x03 };
-   =20
+
     /// \brief The source range that covers this part of the designator.
     SourceRange Range;
-   =20
+
     /// \brief The data describing the designator, which comes in three
     /// different forms, depending on the lower two bits.
-    ///   - An unsigned index into the array of Expr*'s stored after this =
node=20
+    ///   - An unsigned index into the array of Expr*'s stored after this =
node
     ///     in memory, for [constant-expression] designators.
     ///   - A FieldDecl*, for references to a known field.
     ///   - An IdentifierInfo*, for references to a field with a given name
     ///     when the class type is dependent.
-    ///   - A CXXBaseSpecifier*, for references that look at a field in a=20
+    ///   - A CXXBaseSpecifier*, for references that look at a field in a
     ///     base class.
     uintptr_t Data;
-   =20
+
   public:
     /// \brief Create an offsetof node that refers to an array element.
-    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,=20
+    OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
                  SourceLocation RBracketLoc)
       : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) { }
-   =20
+
     /// \brief Create an offsetof node that refers to a field.
-    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,=20
+    OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field,
                  SourceLocation NameLoc)
-      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),=20
+      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
         Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) { }
-   =20
+
     /// \brief Create an offsetof node that refers to an identifier.
     OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
                  SourceLocation NameLoc)
-      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),=20
+      : Range(DotLoc.isValid()? DotLoc : NameLoc, NameLoc),
         Data(reinterpret_cast<uintptr_t>(Name) | Identifier) { }
=20
     /// \brief Create an offsetof node that refers into a C++ base class.
     explicit OffsetOfNode(const CXXBaseSpecifier *Base)
       : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Ba=
se) {}
-   =20
+
     /// \brief Determine what kind of offsetof node this is.
-    Kind getKind() const {=20
+    Kind getKind() const {
       return static_cast<Kind>(Data & Mask);
     }
-   =20
+
     /// \brief For an array element node, returns the index into the array
     /// of expressions.
     unsigned getArrayExprIndex() const {
@@ -1567,28 +1721,28 @@
       assert(getKind() =3D=3D Field);
       return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
     }
-   =20
+
     /// \brief For a field or identifier offsetof node, returns the name of
     /// the field.
     IdentifierInfo *getFieldName() const;
-   =20
+
     /// \brief For a base class node, returns the base specifier.
     CXXBaseSpecifier *getBase() const {
       assert(getKind() =3D=3D Base);
-      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask)=
;     =20
+      return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
     }
-   =20
+
     /// \brief Retrieve the source range that covers this offsetof node.
     ///
     /// For an array element node, the source range contains the locations=
 of
     /// the square brackets. For a field or identifier node, the source ra=
nge
-    /// contains the location of the period (if there is one) and the=20
+    /// contains the location of the period (if there is one) and the
     /// identifier.
-    SourceRange getSourceRange() const { return Range; }
+    SourceRange getSourceRange() const LLVM_READONLY { return Range; }
   };
=20
 private:
- =20
+
   SourceLocation OperatorLoc, RParenLoc;
   // Base type;
   TypeSourceInfo *TSInfo;
@@ -1596,26 +1750,26 @@
   unsigned NumComps;
   // Number of sub-expressions (i.e. array subscript expressions).
   unsigned NumExprs;
- =20
-  OffsetOfExpr(ASTContext &C, QualType type,=20
+
+  OffsetOfExpr(ASTContext &C, QualType type,
                SourceLocation OperatorLoc, TypeSourceInfo *tsi,
-               OffsetOfNode* compsPtr, unsigned numComps,=20
+               OffsetOfNode* compsPtr, unsigned numComps,
                Expr** exprsPtr, unsigned numExprs,
                SourceLocation RParenLoc);
=20
   explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
     : Expr(OffsetOfExprClass, EmptyShell()),
-      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {} =20
+      TSInfo(0), NumComps(numComps), NumExprs(numExprs) {}
=20
 public:
- =20
-  static OffsetOfExpr *Create(ASTContext &C, QualType type,=20
-                              SourceLocation OperatorLoc, TypeSourceInfo *=
tsi,=20
-                              OffsetOfNode* compsPtr, unsigned numComps,=20
+
+  static OffsetOfExpr *Create(ASTContext &C, QualType type,
+                              SourceLocation OperatorLoc, TypeSourceInfo *=
tsi,
+                              OffsetOfNode* compsPtr, unsigned numComps,
                               Expr** exprsPtr, unsigned numExprs,
                               SourceLocation RParenLoc);
=20
-  static OffsetOfExpr *CreateEmpty(ASTContext &C,=20
+  static OffsetOfExpr *CreateEmpty(ASTContext &C,
                                    unsigned NumComps, unsigned NumExprs);
=20
   /// getOperatorLoc - Return the location of the operator.
@@ -1625,14 +1779,14 @@
   /// \brief Return the location of the right parentheses.
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation R) { RParenLoc =3D R; }
- =20
+
   TypeSourceInfo *getTypeSourceInfo() const {
     return TSInfo;
   }
   void setTypeSourceInfo(TypeSourceInfo *tsi) {
     TSInfo =3D tsi;
   }
- =20
+
   const OffsetOfNode &getComponent(unsigned Idx) const {
     assert(Idx < NumComps && "Subscript out of range");
     return reinterpret_cast<const OffsetOfNode *> (this + 1)[Idx];
@@ -1642,7 +1796,7 @@
     assert(Idx < NumComps && "Subscript out of range");
     reinterpret_cast<OffsetOfNode *> (this + 1)[Idx] =3D ON;
   }
- =20
+
   unsigned getNumComponents() const {
     return NumComps;
   }
@@ -1661,12 +1815,12 @@
     reinterpret_cast<Expr **>(
                 reinterpret_cast<OffsetOfNode *>(this+1) + NumComps)[Idx] =
=3D E;
   }
- =20
+
   unsigned getNumExpressions() const {
     return NumExprs;
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(OperatorLoc, RParenLoc);
   }
=20
@@ -1689,8 +1843,6 @@
 /// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
 /// vec_step (OpenCL 1.1 6.11.12).
 class UnaryExprOrTypeTraitExpr : public Expr {
-  unsigned Kind : 2;
-  bool isType : 1;    // true if operand is a type, false if an expression
   union {
     TypeSourceInfo *Ty;
     Stmt *Ex;
@@ -1707,7 +1859,9 @@
            TInfo->getType()->isDependentType(),
            TInfo->getType()->isInstantiationDependentType(),
            TInfo->getType()->containsUnexpandedParameterPack()),
-      Kind(ExprKind), isType(true), OpLoc(op), RParenLoc(rp) {
+      OpLoc(op), RParenLoc(rp) {
+    UnaryExprOrTypeTraitExprBits.Kind =3D ExprKind;
+    UnaryExprOrTypeTraitExprBits.IsType =3D true;
     Argument.Ty =3D TInfo;
   }
=20
@@ -1720,7 +1874,9 @@
            E->isTypeDependent(),
            E->isInstantiationDependent(),
            E->containsUnexpandedParameterPack()),
-      Kind(ExprKind), isType(false), OpLoc(op), RParenLoc(rp) {
+      OpLoc(op), RParenLoc(rp) {
+    UnaryExprOrTypeTraitExprBits.Kind =3D ExprKind;
+    UnaryExprOrTypeTraitExprBits.IsType =3D false;
     Argument.Ex =3D E;
   }
=20
@@ -1729,11 +1885,11 @@
     : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
=20
   UnaryExprOrTypeTrait getKind() const {
-    return static_cast<UnaryExprOrTypeTrait>(Kind);
-  }
-  void setKind(UnaryExprOrTypeTrait K) { Kind =3D K; }
-
-  bool isArgumentType() const { return isType; }
+    return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.=
Kind);
+  }
+  void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind=
 =3D K;}
+
+  bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType=
; }
   QualType getArgumentType() const {
     return getArgumentTypeInfo()->getType();
   }
@@ -1749,10 +1905,13 @@
     return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
   }
=20
-  void setArgument(Expr *E) { Argument.Ex =3D E; isType =3D false; }
+  void setArgument(Expr *E) {
+    Argument.Ex =3D E;
+    UnaryExprOrTypeTraitExprBits.IsType =3D false;
+  }
   void setArgument(TypeSourceInfo *TInfo) {
     Argument.Ty =3D TInfo;
-    isType =3D true;
+    UnaryExprOrTypeTraitExprBits.IsType =3D true;
   }
=20
   /// Gets the argument type, or the type of the argument expression, whic=
hever
@@ -1767,7 +1926,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(OpLoc, RParenLoc);
   }
=20
@@ -1842,14 +2001,14 @@
     return cast<Expr>(getRHS()->getType()->isIntegerType() ? getRHS():getL=
HS());
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getLHS()->getLocStart(), RBracketLoc);
   }
=20
   SourceLocation getRBracketLoc() const { return RBracketLoc; }
   void setRBracketLoc(SourceLocation L) { RBracketLoc =3D L; }
=20
-  SourceLocation getExprLoc() const { return getBase()->getExprLoc(); }
+  SourceLocation getExprLoc() const LLVM_READONLY { return getBase()->getE=
xprLoc(); }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D ArraySubscriptExprClass;
@@ -1927,7 +2086,10 @@
   Expr **getArgs() {
     return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_STAR=
T);
   }
- =20
+  const Expr *const *getArgs() const {
+    return const_cast<CallExpr*>(this)->getArgs();
+  }
+
   /// getArg - Return the specified argument.
   Expr *getArg(unsigned Arg) {
     assert(Arg < NumArgs && "Arg access out of range!");
@@ -1969,7 +2131,7 @@
=20
   /// isBuiltinCall - If this is a call to a builtin, return the builtin I=
D.  If
   /// not, return 0.
-  unsigned isBuiltinCall(const ASTContext &Context) const;
+  unsigned isBuiltinCall() const;
=20
   /// getCallReturnType - Get the return type of the call expr. This is not
   /// always the type of the expr itself, if the return type is a reference
@@ -1979,7 +2141,9 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
+  SourceLocation getLocStart() const LLVM_READONLY;
+  SourceLocation getLocEnd() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() >=3D firstCallExprConstant &&
@@ -2016,13 +2180,13 @@
   /// In X.F, this is the decl referenced by F.
   ValueDecl *MemberDecl;
=20
-  /// MemberLoc - This is the location of the member name.
-  SourceLocation MemberLoc;
-
   /// MemberDNLoc - Provides source/type location info for the
   /// declaration name embedded in MemberDecl.
   DeclarationNameLoc MemberDNLoc;
=20
+  /// MemberLoc - This is the location of the member name.
+  SourceLocation MemberLoc;
+
   /// IsArrow - True if this is "X->F", false if this is "X.F".
   bool IsArrow : 1;
=20
@@ -2032,12 +2196,14 @@
   /// structure is allocated immediately after the MemberExpr.
   bool HasQualifierOrFoundDecl : 1;
=20
-  /// \brief True if this member expression specified a template argument =
list
-  /// explicitly, e.g., x->f<int>. When true, an ExplicitTemplateArgumentL=
ist
-  /// structure (and its TemplateArguments) are allocated immediately after
-  /// the MemberExpr or, if the member expression also has a qualifier, af=
ter
-  /// the MemberNameQualifier structure.
-  bool HasExplicitTemplateArgumentList : 1;
+  /// \brief True if this member expression specified a template keyword
+  /// and/or a template argument list explicitly, e.g., x->f<int>,
+  /// x->template f, x->template f<int>.
+  /// When true, an ASTTemplateKWAndArgsInfo structure and its
+  /// TemplateArguments (if any) are allocated immediately after
+  /// the MemberExpr or, if the member expression also has a qualifier,
+  /// after the MemberNameQualifier structure.
+  bool HasTemplateKWAndArgsInfo : 1;
=20
   /// \brief True if this member expression refers to a method that
   /// was resolved from an overloaded set having size greater than 1.
@@ -2059,13 +2225,13 @@
              const DeclarationNameInfo &NameInfo, QualType ty,
              ExprValueKind VK, ExprObjectKind OK)
     : Expr(MemberExprClass, ty, VK, OK,
-           base->isTypeDependent(),=20
+           base->isTypeDependent(),
            base->isValueDependent(),
            base->isInstantiationDependent(),
            base->containsUnexpandedParameterPack()),
-      Base(base), MemberDecl(memberdecl), MemberLoc(NameInfo.getLoc()),
-      MemberDNLoc(NameInfo.getInfo()), IsArrow(isarrow),
-      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(fals=
e),
+      Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
+      MemberLoc(NameInfo.getLoc()), IsArrow(isarrow),
+      HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
       HadMultipleCandidates(false) {
     assert(memberdecl->getDeclName() =3D=3D NameInfo.getName());
   }
@@ -2073,7 +2239,7 @@
   // NOTE: this constructor should be used only when it is known that
   // the member name can not provide additional syntactic info
   // (i.e., source locations for C++ operator names or type source info
-  // for constructors, destructors and conversion oeprators).
+  // for constructors, destructors and conversion operators).
   MemberExpr(Expr *base, bool isarrow, ValueDecl *memberdecl,
              SourceLocation l, QualType ty,
              ExprValueKind VK, ExprObjectKind OK)
@@ -2081,13 +2247,14 @@
            base->isTypeDependent(), base->isValueDependent(),
            base->isInstantiationDependent(),
            base->containsUnexpandedParameterPack()),
-      Base(base), MemberDecl(memberdecl), MemberLoc(l), MemberDNLoc(),
+      Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
       IsArrow(isarrow),
-      HasQualifierOrFoundDecl(false), HasExplicitTemplateArgumentList(fals=
e),
+      HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
       HadMultipleCandidates(false) {}
=20
   static MemberExpr *Create(ASTContext &C, Expr *base, bool isarrow,
                             NestedNameSpecifierLoc QualifierLoc,
+                            SourceLocation TemplateKWLoc,
                             ValueDecl *memberdecl, DeclAccessPair founddec=
l,
                             DeclarationNameInfo MemberNameInfo,
                             const TemplateArgumentListInfo *targs,
@@ -2126,21 +2293,60 @@
     return getMemberQualifier()->QualifierLoc.getNestedNameSpecifier();
   }
=20
-  /// \brief If the member name was qualified, retrieves the=20
+  /// \brief If the member name was qualified, retrieves the
   /// nested-name-specifier that precedes the member name, with source-loc=
ation
   /// information.
   NestedNameSpecifierLoc getQualifierLoc() const {
     if (!hasQualifier())
       return NestedNameSpecifierLoc();
-   =20
+
     return getMemberQualifier()->QualifierLoc;
   }
=20
-  /// \brief Determines whether this member expression actually had a C++
-  /// template argument list explicitly specified, e.g., x.f<int>.
-  bool hasExplicitTemplateArgs() const {
-    return HasExplicitTemplateArgumentList;
-  }
+  /// \brief Return the optional template keyword and arguments info.
+  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
+    if (!HasTemplateKWAndArgsInfo)
+      return 0;
+
+    if (!HasQualifierOrFoundDecl)
+      return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(this + 1);
+
+    return reinterpret_cast<ASTTemplateKWAndArgsInfo *>(
+                                                      getMemberQualifier()=
 + 1);
+  }
+
+  /// \brief Return the optional template keyword and arguments info.
+  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
+    return const_cast<MemberExpr*>(this)->getTemplateKWAndArgsInfo();
+  }
+
+  /// \brief Retrieve the location of the template keyword preceding
+  /// the member name, if any.
+  SourceLocation getTemplateKeywordLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
+  }
+
+  /// \brief Retrieve the location of the left angle bracket starting the
+  /// explicit template argument list following the member name, if any.
+  SourceLocation getLAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->LAngleLoc;
+  }
+
+  /// \brief Retrieve the location of the right angle bracket ending the
+  /// explicit template argument list following the member name, if any.
+  SourceLocation getRAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->RAngleLoc;
+  }
+
+  /// Determines whether the member name was preceded by the template keyw=
ord.
+  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid=
(); }
+
+  /// \brief Determines whether the member name was followed by an
+  /// explicit template argument list.
+  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
=20
   /// \brief Copies the template arguments (if present) into the given
   /// structure.
@@ -2153,12 +2359,8 @@
   /// follow the member template name.  This must only be called on an
   /// expression with explicit template arguments.
   ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
-    assert(HasExplicitTemplateArgumentList);
-    if (!HasQualifierOrFoundDecl)
-      return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
-
-    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(
-                                                      getMemberQualifier()=
 + 1);
+    assert(hasExplicitTemplateArgs());
+    return *getTemplateKWAndArgsInfo();
   }
=20
   /// \brief Retrieve the explicit template argument list that
@@ -2175,20 +2377,11 @@
     if (!hasExplicitTemplateArgs()) return 0;
     return &getExplicitTemplateArgs();
   }
- =20
-  /// \brief Retrieve the location of the left angle bracket following the
-  /// member name ('<'), if any.
-  SourceLocation getLAngleLoc() const {
-    if (!HasExplicitTemplateArgumentList)
-      return SourceLocation();
-
-    return getExplicitTemplateArgs().LAngleLoc;
-  }
=20
   /// \brief Retrieve the template arguments provided as part of this
   /// template-id.
   const TemplateArgumentLoc *getTemplateArgs() const {
-    if (!HasExplicitTemplateArgumentList)
+    if (!hasExplicitTemplateArgs())
       return 0;
=20
     return getExplicitTemplateArgs().getTemplateArgs();
@@ -2197,21 +2390,12 @@
   /// \brief Retrieve the number of template arguments provided as part of=
 this
   /// template-id.
   unsigned getNumTemplateArgs() const {
-    if (!HasExplicitTemplateArgumentList)
+    if (!hasExplicitTemplateArgs())
       return 0;
=20
     return getExplicitTemplateArgs().NumTemplateArgs;
   }
=20
-  /// \brief Retrieve the location of the right angle bracket following the
-  /// template arguments ('>').
-  SourceLocation getRAngleLoc() const {
-    if (!HasExplicitTemplateArgumentList)
-      return SourceLocation();
-
-    return getExplicitTemplateArgs().RAngleLoc;
-  }
-
   /// \brief Retrieve the member declaration name info.
   DeclarationNameInfo getMemberNameInfo() const {
     return DeclarationNameInfo(MemberDecl->getDeclName(),
@@ -2226,9 +2410,11 @@
   SourceLocation getMemberLoc() const { return MemberLoc; }
   void setMemberLoc(SourceLocation L) { MemberLoc =3D L; }
=20
-  SourceRange getSourceRange() const;
- =20
-  SourceLocation getExprLoc() const { return MemberLoc; }
+  SourceRange getSourceRange() const LLVM_READONLY;
+  SourceLocation getLocStart() const LLVM_READONLY;
+  SourceLocation getLocEnd() const LLVM_READONLY;
+
+  SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
=20
   /// \brief Determine whether the base of this explicit is implicit.
   bool isImplicitAccess() const {
@@ -2269,19 +2455,19 @@
=20
   /// The type as written.  This can be an incomplete array type, in
   /// which case the actual expression type will be different.
-  TypeSourceInfo *TInfo;
+  /// The int part of the pair stores whether this expr is file scope.
+  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
   Stmt *Init;
-  bool FileScope;
 public:
   CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
                       QualType T, ExprValueKind VK, Expr *init, bool fileS=
cope)
     : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
-           tinfo->getType()->isDependentType(),=20
+           tinfo->getType()->isDependentType(),
            init->isValueDependent(),
            (init->isInstantiationDependent() ||
             tinfo->getType()->isInstantiationDependentType()),
            init->containsUnexpandedParameterPack()),
-      LParenLoc(lparenloc), TInfo(tinfo), Init(init), FileScope(fileScope)=
 {}
+      LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
=20
   /// \brief Construct an empty compound literal.
   explicit CompoundLiteralExpr(EmptyShell Empty)
@@ -2291,16 +2477,20 @@
   Expr *getInitializer() { return cast<Expr>(Init); }
   void setInitializer(Expr *E) { Init =3D E; }
=20
-  bool isFileScope() const { return FileScope; }
-  void setFileScope(bool FS) { FileScope =3D FS; }
+  bool isFileScope() const { return TInfoAndScope.getInt(); }
+  void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
=20
   SourceLocation getLParenLoc() const { return LParenLoc; }
   void setLParenLoc(SourceLocation L) { LParenLoc =3D L; }
=20
-  TypeSourceInfo *getTypeSourceInfo() const { return TInfo; }
-  void setTypeSourceInfo(TypeSourceInfo* tinfo) { TInfo =3D tinfo; }
-
-  SourceRange getSourceRange() const {
+  TypeSourceInfo *getTypeSourceInfo() const {
+    return TInfoAndScope.getPointer();
+  }
+  void setTypeSourceInfo(TypeSourceInfo *tinfo) {
+    TInfoAndScope.setPointer(tinfo);
+  }
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     // FIXME: Init should never be null.
     if (!Init)
       return SourceRange();
@@ -2352,7 +2542,7 @@
          // Cast expressions are value-dependent if the type is
          // dependent or if the subexpression is value-dependent.
          ty->isDependentType() || (op && op->isValueDependent()),
-         (ty->isInstantiationDependentType() ||=20
+         (ty->isInstantiationDependentType() ||
           (op && op->isInstantiationDependent())),
          (ty->containsUnexpandedParameterPack() ||
           op->containsUnexpandedParameterPack())),
@@ -2454,9 +2644,15 @@
=20
   static ImplicitCastExpr *CreateEmpty(ASTContext &Context, unsigned PathS=
ize);
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return getSubExpr()->getSourceRange();
   }
+  SourceLocation getLocStart() const LLVM_READONLY {
+    return getSubExpr()->getLocStart();
+  }
+  SourceLocation getLocEnd() const LLVM_READONLY {
+    return getSubExpr()->getLocEnd();
+  }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D ImplicitCastExprClass;
@@ -2551,7 +2747,7 @@
   SourceLocation getRParenLoc() const { return RPLoc; }
   void setRParenLoc(SourceLocation L) { RPLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LPLoc, getSubExpr()->getSourceRange().getEnd());
   }
   static bool classof(const Stmt *T) {
@@ -2611,6 +2807,7 @@
   explicit BinaryOperator(EmptyShell Empty)
     : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
=20
+  SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
   SourceLocation getOperatorLoc() const { return OpLoc; }
   void setOperatorLoc(SourceLocation L) { OpLoc =3D L; }
=20
@@ -2622,7 +2819,7 @@
   Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
   void setRHS(Expr *E) { SubExprs[RHS] =3D E; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getLHS()->getLocStart(), getRHS()->getLocEnd());
   }
=20
@@ -2674,6 +2871,13 @@
   bool isCompoundAssignmentOp() const {
     return isCompoundAssignmentOp(getOpcode());
   }
+  static Opcode getOpForCompoundAssignment(Opcode Opc) {
+    assert(isCompoundAssignmentOp(Opc));
+    if (Opc >=3D BO_AndAssign)
+      return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
+    else
+      return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
+  }
=20
   static bool isShiftAssignOp(Opcode Opc) {
     return Opc =3D=3D BO_ShlAssign || Opc =3D=3D BO_ShrAssign;
@@ -2842,11 +3046,11 @@
   //   the expression if the condition evaluates to false.  This is
   //   the same as getRHS.
   Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
- =20
+
   Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
   Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getCond()->getLocStart(), getRHS()->getLocEnd());
   }
   static bool classof(const Stmt *T) {
@@ -2895,8 +3099,7 @@
     SubExprs[COND] =3D cond;
     SubExprs[LHS] =3D lhs;
     SubExprs[RHS] =3D rhs;
-
-    OpaqueValue->setSourceExpr(common);
+    assert(OpaqueValue->getSourceExpr() =3D=3D common && "Wrong opaque val=
ue");
   }
=20
   /// \brief Build an empty conditional operator.
@@ -2928,8 +3131,8 @@
   Expr *getFalseExpr() const {
     return cast<Expr>(SubExprs[RHS]);
   }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getCommon()->getLocStart(), getFalseExpr()->getLocE=
nd());
   }
   static bool classof(const Stmt *T) {
@@ -2981,7 +3184,7 @@
   SourceLocation getLabelLoc() const { return LabelLoc; }
   void setLabelLoc(SourceLocation L) { LabelLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AmpAmpLoc, LabelLoc);
   }
=20
@@ -3023,7 +3226,7 @@
   const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubSt=
mt); }
   void setSubStmt(CompoundStmt *S) { SubStmt =3D S; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LParenLoc, RParenLoc);
   }
=20
@@ -3073,7 +3276,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(BuiltinLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -3088,7 +3291,7 @@
=20
   /// \brief Retrieve the array of expressions.
   Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
- =20
+
   /// getExpr - Return the Expr at the specified index.
   Expr *getExpr(unsigned Index) {
     assert((Index < NumExprs) && "Arg access out of range!");
@@ -3168,7 +3371,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(BuiltinLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -3205,7 +3408,7 @@
   SourceLocation getTokenLocation() const { return TokenLoc; }
   void setTokenLocation(SourceLocation L) { TokenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(TokenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -3251,7 +3454,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(BuiltinLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -3319,10 +3522,6 @@
   ///  field within the union will be initialized.
   llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
=20
-  /// Whether this initializer list originally had a GNU array-range
-  /// designator in it. This is a temporary marker used by CodeGen.
-  bool HadArrayRangeDesignator;
-
 public:
   InitListExpr(ASTContext &C, SourceLocation lbraceloc,
                Expr **initexprs, unsigned numinits,
@@ -3336,7 +3535,7 @@
=20
   /// \brief Retrieve the set of initializers.
   Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
-   =20
+
   const Expr *getInit(unsigned Init) const {
     assert(Init < getNumInits() && "Initializer access out of range!");
     return cast_or_null<Expr>(InitExprs[Init]);
@@ -3383,6 +3582,10 @@
   }
   void setArrayFiller(Expr *filler);
=20
+  /// \brief Return true if this is an array initializer and its array "fi=
ller"
+  /// has been set.
+  bool hasArrayFiller() const { return getArrayFiller(); }
+
   /// \brief If this initializes a union, specifies which field in the
   /// union to initialize.
   ///
@@ -3417,12 +3620,21 @@
   InitListExpr *getSyntacticForm() const { return SyntacticForm; }
   void setSyntacticForm(InitListExpr *Init) { SyntacticForm =3D Init; }
=20
-  bool hadArrayRangeDesignator() const { return HadArrayRangeDesignator; }
+  bool hadArrayRangeDesignator() const {
+    return InitListExprBits.HadArrayRangeDesignator !=3D 0;
+  }
   void sawArrayRangeDesignator(bool ARD =3D true) {
-    HadArrayRangeDesignator =3D ARD;
-  }
-
-  SourceRange getSourceRange() const;
+    InitListExprBits.HadArrayRangeDesignator =3D ARD;
+  }
+
+  bool initializesStdInitializerList() const {
+    return InitListExprBits.InitializesStdInitializerList !=3D 0;
+  }
+  void setInitializesStdInitializerList(bool ISIL =3D true) {
+    InitListExprBits.InitializesStdInitializerList =3D ISIL;
+  }
+
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D InitListExprClass;
@@ -3490,15 +3702,15 @@
   /// The number of designators in this initializer expression.
   unsigned NumDesignators : 15;
=20
-  /// \brief The designators in this designated initialization
-  /// expression.
-  Designator *Designators;
-
   /// The number of subexpressions of this initializer expression,
   /// which contains both the initializer and any additional
   /// expressions used by array and array-range designators.
   unsigned NumSubExprs : 16;
=20
+  /// \brief The designators in this designated initialization
+  /// expression.
+  Designator *Designators;
+
=20
   DesignatedInitExpr(ASTContext &C, QualType Ty, unsigned NumDesignators,
                      const Designator *Designators,
@@ -3508,7 +3720,7 @@
=20
   explicit DesignatedInitExpr(unsigned NumSubExprs)
     : Expr(DesignatedInitExprClass, EmptyShell()),
-      NumDesignators(0), Designators(0), NumSubExprs(NumSubExprs) { }
+      NumDesignators(0), NumSubExprs(NumSubExprs), Designators(0) { }
=20
 public:
   /// A field designator, e.g., ".x".
@@ -3658,7 +3870,7 @@
     SourceLocation getEndLocation() const {
       return Kind =3D=3D FieldDesignator ? getFieldLoc() : getRBracketLoc(=
);
     }
-    SourceRange getSourceRange() const {
+    SourceRange getSourceRange() const LLVM_READONLY {
       return SourceRange(getStartLocation(), getEndLocation());
     }
   };
@@ -3707,7 +3919,7 @@
=20
   Designator *getDesignator(unsigned Idx) { return &designators_begin()[Id=
x]; }
=20
-  void setDesignators(ASTContext &C, const Designator *Desigs,=20
+  void setDesignators(ASTContext &C, const Designator *Desigs,
                       unsigned NumDesigs);
=20
   Expr *getArrayIndex(const Designator& D);
@@ -3760,7 +3972,7 @@
=20
   SourceRange getDesignatorsSourceRange() const;
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D DesignatedInitExprClass;
@@ -3797,7 +4009,7 @@
   }
   static bool classof(const ImplicitValueInitExpr *) { return true; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange();
   }
=20
@@ -3813,7 +4025,7 @@
=20
 public:
   ParenListExpr(ASTContext& C, SourceLocation lparenloc, Expr **exprs,
-                unsigned numexprs, SourceLocation rparenloc, QualType T);
+                unsigned numexprs, SourceLocation rparenloc);
=20
   /// \brief Build an empty paren list.
   explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empt=
y) { }
@@ -3835,7 +4047,7 @@
   SourceLocation getLParenLoc() const { return LParenLoc; }
   SourceLocation getRParenLoc() const { return RParenLoc; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LParenLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -3853,9 +4065,9 @@
 };
=20
=20
-/// \brief Represents a C1X generic selection.
+/// \brief Represents a C11 generic selection.
 ///
-/// A generic selection (C1X 6.5.1.1) contains an unevaluated controlling
+/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
 /// expression, followed by one or more generic associations.  Each generic
 /// association specifies a type name and an expression, or "default" and =
an
 /// expression (in which case it is known as a default generic association=
).
@@ -3950,7 +4162,7 @@
   const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()=
); }
   Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(GenericLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -4016,7 +4228,7 @@
   /// aggregate Constant of ConstantInt(s).
   void getEncodedElementAccess(SmallVectorImpl<unsigned> &Elts) const;
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getBase()->getLocStart(), AccessorLoc);
   }
=20
@@ -4042,9 +4254,8 @@
 public:
   BlockExpr(BlockDecl *BD, QualType ty)
     : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
-           ty->isDependentType(), false,=20
-           // FIXME: Check for instantiate-dependence in the statement?
-           ty->isInstantiationDependentType(),
+           ty->isDependentType(), ty->isDependentType(),
+           ty->isInstantiationDependentType() || BD->isDependentContext(),
            false),
       TheBlock(BD) {}
=20
@@ -4060,12 +4271,12 @@
   const Stmt *getBody() const;
   Stmt *getBody();
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getCaretLocation(), getBody()->getLocEnd());
   }
=20
   /// getFunctionType - Return the underlying function type for this block.
-  const FunctionType *getFunctionType() const;
+  const FunctionProtoType *getFunctionType() const;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D BlockExprClass;
@@ -4076,46 +4287,6 @@
   child_range children() { return child_range(); }
 };
=20
-/// BlockDeclRefExpr - A reference to a local variable declared in an
-/// enclosing scope.
-class BlockDeclRefExpr : public Expr {
-  VarDecl *D;
-  SourceLocation Loc;
-  bool IsByRef : 1;
-  bool ConstQualAdded : 1;
-public:
-  BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind VK,
-                   SourceLocation l, bool ByRef, bool constAdded =3D false=
);
-
-  // \brief Build an empty reference to a declared variable in a
-  // block.
-  explicit BlockDeclRefExpr(EmptyShell Empty)
-    : Expr(BlockDeclRefExprClass, Empty) { }
-
-  VarDecl *getDecl() { return D; }
-  const VarDecl *getDecl() const { return D; }
-  void setDecl(VarDecl *VD) { D =3D VD; }
-
-  SourceLocation getLocation() const { return Loc; }
-  void setLocation(SourceLocation L) { Loc =3D L; }
-
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
-
-  bool isByRef() const { return IsByRef; }
-  void setByRef(bool BR) { IsByRef =3D BR; }
-
-  bool isConstQualAdded() const { return ConstQualAdded; }
-  void setConstQualAdded(bool C) { ConstQualAdded =3D C; }
- =20
-  static bool classof(const Stmt *T) {
-    return T->getStmtClass() =3D=3D BlockDeclRefExprClass;
-  }
-  static bool classof(const BlockDeclRefExpr *) { return true; }
-
-  // Iterators
-  child_range children() { return child_range(); }
-};
-
 /// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
 /// This AST node provides support for reinterpreting a type to another
 /// type of the same size.
@@ -4127,12 +4298,12 @@
   friend class ASTReader;
   friend class ASTStmtReader;
   explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
- =20
+
 public:
   AsTypeExpr(Expr* SrcExpr, QualType DstType,
              ExprValueKind VK, ExprObjectKind OK,
              SourceLocation BuiltinLoc, SourceLocation RParenLoc)
-    : Expr(AsTypeExprClass, DstType, VK, OK,=20
+    : Expr(AsTypeExprClass, DstType, VK, OK,
            DstType->isDependentType(),
            DstType->isDependentType() || SrcExpr->isValueDependent(),
            (DstType->isInstantiationDependentType() ||
@@ -4140,7 +4311,7 @@
            (DstType->containsUnexpandedParameterPack() ||
             SrcExpr->containsUnexpandedParameterPack())),
   SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
- =20
+
   /// getSrcExpr - Return the Expr to be converted.
   Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
=20
@@ -4149,83 +4320,218 @@
=20
   /// getRParenLoc - Return the location of final right parenthesis.
   SourceLocation getRParenLoc() const { return RParenLoc; }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(BuiltinLoc, RParenLoc);
   }
- =20
+
   static bool classof(const Stmt *T) {
-    return T->getStmtClass() =3D=3D AsTypeExprClass;=20
+    return T->getStmtClass() =3D=3D AsTypeExprClass;
   }
   static bool classof(const AsTypeExpr *) { return true; }
- =20
+
   // Iterators
   child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
 };
=20
+/// PseudoObjectExpr - An expression which accesses a pseudo-object
+/// l-value.  A pseudo-object is an abstract object, accesses to which
+/// are translated to calls.  The pseudo-object expression has a
+/// syntactic form, which shows how the expression was actually
+/// written in the source code, and a semantic form, which is a series
+/// of expressions to be executed in order which detail how the
+/// operation is actually evaluated.  Optionally, one of the semantic
+/// forms may also provide a result value for the expression.
+///
+/// If any of the semantic-form expressions is an OpaqueValueExpr,
+/// that OVE is required to have a source expression, and it is bound
+/// to the result of that source expression.  Such OVEs may appear
+/// only in subsequent semantic-form expressions and as
+/// sub-expressions of the syntactic form.
+///
+/// PseudoObjectExpr should be used only when an operation can be
+/// usefully described in terms of fairly simple rewrite rules on
+/// objects and functions that are meant to be used by end-developers.
+/// For example, under the Itanium ABI, dynamic casts are implemented
+/// as a call to a runtime function called __dynamic_cast; using this
+/// class to describe that would be inappropriate because that call is
+/// not really part of the user-visible semantics, and instead the
+/// cast is properly reflected in the AST and IR-generation has been
+/// taught to generate the call as necessary.  In contrast, an
+/// Objective-C property access is semantically defined to be
+/// equivalent to a particular message send, and this is very much
+/// part of the user model.  The name of this class encourages this
+/// modelling design.
+class PseudoObjectExpr : public Expr {
+  // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
+  // Always at least two, because the first sub-expression is the
+  // syntactic form.
+
+  // PseudoObjectExprBits.ResultIndex - The index of the
+  // sub-expression holding the result.  0 means the result is void,
+  // which is unambiguous because it's the index of the syntactic
+  // form.  Note that this is therefore 1 higher than the value passed
+  // in to Create, which is an index within the semantic forms.
+  // Note also that ASTStmtWriter assumes this encoding.
+
+  Expr **getSubExprsBuffer() { return reinterpret_cast<Expr**>(this + 1); }
+  const Expr * const *getSubExprsBuffer() const {
+    return reinterpret_cast<const Expr * const *>(this + 1);
+  }
+
+  friend class ASTStmtReader;
+
+  PseudoObjectExpr(QualType type, ExprValueKind VK,
+                   Expr *syntactic, ArrayRef<Expr*> semantic,
+                   unsigned resultIndex);
+
+  PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
+
+  unsigned getNumSubExprs() const {
+    return PseudoObjectExprBits.NumSubExprs;
+  }
+
+public:
+  /// NoResult - A value for the result index indicating that there is
+  /// no semantic result.
+  enum { NoResult =3D ~0U };
+
+  static PseudoObjectExpr *Create(ASTContext &Context, Expr *syntactic,
+                                  ArrayRef<Expr*> semantic,
+                                  unsigned resultIndex);
+
+  static PseudoObjectExpr *Create(ASTContext &Context, EmptyShell shell,
+                                  unsigned numSemanticExprs);
+
+  /// Return the syntactic form of this expression, i.e. the
+  /// expression it actually looks like.  Likely to be expressed in
+  /// terms of OpaqueValueExprs bound in the semantic form.
+  Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
+  const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
+
+  /// Return the index of the result-bearing expression into the semantics
+  /// expressions, or PseudoObjectExpr::NoResult if there is none.
+  unsigned getResultExprIndex() const {
+    if (PseudoObjectExprBits.ResultIndex =3D=3D 0) return NoResult;
+    return PseudoObjectExprBits.ResultIndex - 1;
+  }
+
+  /// Return the result-bearing expression, or null if there is none.
+  Expr *getResultExpr() {
+    if (PseudoObjectExprBits.ResultIndex =3D=3D 0)
+      return 0;
+    return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
+  }
+  const Expr *getResultExpr() const {
+    return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
+  }
+
+  unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
+
+  typedef Expr * const *semantics_iterator;
+  typedef const Expr * const *const_semantics_iterator;
+  semantics_iterator semantics_begin() {
+    return getSubExprsBuffer() + 1;
+  }
+  const_semantics_iterator semantics_begin() const {
+    return getSubExprsBuffer() + 1;
+  }
+  semantics_iterator semantics_end() {
+    return getSubExprsBuffer() + getNumSubExprs();
+  }
+  const_semantics_iterator semantics_end() const {
+    return getSubExprsBuffer() + getNumSubExprs();
+  }
+  Expr *getSemanticExpr(unsigned index) {
+    assert(index + 1 < getNumSubExprs());
+    return getSubExprsBuffer()[index + 1];
+  }
+  const Expr *getSemanticExpr(unsigned index) const {
+    return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
+  }
+
+  SourceLocation getExprLoc() const LLVM_READONLY {
+    return getSyntacticForm()->getExprLoc();
+  }
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return getSyntacticForm()->getSourceRange();
+  }
+
+  child_range children() {
+    Stmt **cs =3D reinterpret_cast<Stmt**>(getSubExprsBuffer());
+    return child_range(cs, cs + getNumSubExprs());
+  }
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() =3D=3D PseudoObjectExprClass;
+  }
+  static bool classof(const PseudoObjectExpr *) { return true; }
+};
+
 /// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fet=
ch_*,
 /// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
-/// similarly-named C++0x instructions.  All of these instructions take one
-/// primary pointer and at least one memory order.
+/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.=
h>.
+/// All of these instructions take one primary pointer and at least one me=
mory
+/// order.
 class AtomicExpr : public Expr {
 public:
-  enum AtomicOp { Load, Store, CmpXchgStrong, CmpXchgWeak, Xchg,
-                  Add, Sub, And, Or, Xor };
+  enum AtomicOp {
+#define BUILTIN(ID, TYPE, ATTRS)
+#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
+#include "clang/Basic/Builtins.def"
+    // Avoid trailing comma
+    BI_First =3D 0
+  };
+
 private:
-  enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, END_EXPR };
+  enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
   Stmt* SubExprs[END_EXPR];
   unsigned NumSubExprs;
   SourceLocation BuiltinLoc, RParenLoc;
   AtomicOp Op;
=20
+  friend class ASTStmtReader;
+
 public:
   AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr, QualType t,
              AtomicOp op, SourceLocation RP);
=20
+  /// \brief Determine the number of arguments the specified atomic builtin
+  /// should have.
+  static unsigned getNumSubExprs(AtomicOp Op);
+
   /// \brief Build an empty AtomicExpr.
   explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
=20
   Expr *getPtr() const {
     return cast<Expr>(SubExprs[PTR]);
   }
-  void setPtr(Expr *E) {
-    SubExprs[PTR] =3D E;
-  }
   Expr *getOrder() const {
     return cast<Expr>(SubExprs[ORDER]);
   }
-  void setOrder(Expr *E) {
-    SubExprs[ORDER] =3D E;
-  }
   Expr *getVal1() const {
-    assert(NumSubExprs >=3D 3);
+    if (Op =3D=3D AO__c11_atomic_init)
+      return cast<Expr>(SubExprs[ORDER]);
+    assert(NumSubExprs > VAL1);
     return cast<Expr>(SubExprs[VAL1]);
   }
-  void setVal1(Expr *E) {
-    assert(NumSubExprs >=3D 3);
-    SubExprs[VAL1] =3D E;
-  }
   Expr *getOrderFail() const {
-    assert(NumSubExprs =3D=3D 5);
+    assert(NumSubExprs > ORDER_FAIL);
     return cast<Expr>(SubExprs[ORDER_FAIL]);
   }
-  void setOrderFail(Expr *E) {
-    assert(NumSubExprs =3D=3D 5);
-    SubExprs[ORDER_FAIL] =3D E;
-  }
   Expr *getVal2() const {
-    assert(NumSubExprs =3D=3D 5);
+    if (Op =3D=3D AO__atomic_exchange)
+      return cast<Expr>(SubExprs[ORDER_FAIL]);
+    assert(NumSubExprs > VAL2);
     return cast<Expr>(SubExprs[VAL2]);
   }
-  void setVal2(Expr *E) {
-    assert(NumSubExprs =3D=3D 5);
-    SubExprs[VAL2] =3D E;
+  Expr *getWeak() const {
+    assert(NumSubExprs > WEAK);
+    return cast<Expr>(SubExprs[WEAK]);
   }
=20
   AtomicOp getOp() const { return Op; }
-  void setOp(AtomicOp op) { Op =3D op; }
   unsigned getNumSubExprs() { return NumSubExprs; }
-  void setNumSubExprs(unsigned num) { NumSubExprs =3D num; }
=20
   Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
=20
@@ -4234,17 +4540,16 @@
   }
=20
   bool isCmpXChg() const {
-    return getOp() =3D=3D AtomicExpr::CmpXchgStrong ||
-           getOp() =3D=3D AtomicExpr::CmpXchgWeak;
+    return getOp() =3D=3D AO__c11_atomic_compare_exchange_strong ||
+           getOp() =3D=3D AO__c11_atomic_compare_exchange_weak ||
+           getOp() =3D=3D AO__atomic_compare_exchange ||
+           getOp() =3D=3D AO__atomic_compare_exchange_n;
   }
=20
   SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
-  void setBuiltinLoc(SourceLocation L) { BuiltinLoc =3D L; }
-
   SourceLocation getRParenLoc() const { return RParenLoc; }
-  void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
-
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(BuiltinLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ExprCXX.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ExprCXX.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ExprCXX.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -14,11 +14,13 @@
 #ifndef LLVM_CLANG_AST_EXPRCXX_H
 #define LLVM_CLANG_AST_EXPRCXX_H
=20
-#include "clang/Basic/TypeTraits.h"
-#include "clang/Basic/ExpressionTraits.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/UnresolvedSet.h"
 #include "clang/AST/TemplateBase.h"
+#include "clang/Basic/ExpressionTraits.h"
+#include "clang/Basic/Lambda.h"
+#include "clang/Basic/TypeTraits.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
=20
@@ -72,7 +74,7 @@
   /// bracket.
   SourceLocation getOperatorLoc() const { return getRParenLoc(); }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXOperatorCallExprClass;
@@ -101,7 +103,7 @@
   /// argument for the member call. For example, in "x.f(5)", this
   /// operation would return "x".
   Expr *getImplicitObjectArgument() const;
- =20
+
   /// Retrieves the declaration of the called method.
   CXXMethodDecl *getMethodDecl() const;
=20
@@ -158,7 +160,7 @@
 private:
   SourceLocation Loc; // the location of the casting op
   SourceLocation RParenLoc; // the location of the right parenthesis
- =20
+
 protected:
   CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
                    CastKind kind, Expr *op, unsigned PathSize,
@@ -171,7 +173,7 @@
     : ExplicitCastExpr(SC, Shell, PathSize) { }
=20
   friend class ASTStmtReader;
- =20
+
 public:
   const char *getCastName() const;
=20
@@ -181,8 +183,8 @@
=20
   /// \brief Retrieve the location of the closing parenthesis.
   SourceLocation getRParenLoc() const { return RParenLoc; }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(Loc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -199,7 +201,8 @@
   static bool classof(const CXXNamedCastExpr *) { return true; }
 };
=20
-/// CXXStaticCastExpr - A C++ @c static_cast expression (C++ [expr.static.=
cast]).
+/// CXXStaticCastExpr - A C++ @c static_cast expression
+/// (C++ [expr.static.cast]).
 ///
 /// This expression node represents a C++ static cast, e.g.,
 /// @c static_cast<int>(1.0).
@@ -217,7 +220,7 @@
   static CXXStaticCastExpr *Create(ASTContext &Context, QualType T,
                                    ExprValueKind VK, CastKind K, Expr *Op,
                                    const CXXCastPath *Path,
-                                   TypeSourceInfo *Written, SourceLocation=
 L,=20
+                                   TypeSourceInfo *Written, SourceLocation=
 L,
                                    SourceLocation RParenLoc);
   static CXXStaticCastExpr *CreateEmpty(ASTContext &Context,
                                         unsigned PathSize);
@@ -248,9 +251,9 @@
   static CXXDynamicCastExpr *Create(ASTContext &Context, QualType T,
                                     ExprValueKind VK, CastKind Kind, Expr =
*Op,
                                     const CXXCastPath *Path,
-                                    TypeSourceInfo *Written, SourceLocatio=
n L,=20
+                                    TypeSourceInfo *Written, SourceLocatio=
n L,
                                     SourceLocation RParenLoc);
- =20
+
   static CXXDynamicCastExpr *CreateEmpty(ASTContext &Context,
                                          unsigned pathSize);
=20
@@ -271,7 +274,7 @@
 class CXXReinterpretCastExpr : public CXXNamedCastExpr {
   CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
                          Expr *op, unsigned pathSize,
-                         TypeSourceInfo *writtenTy, SourceLocation l,=20
+                         TypeSourceInfo *writtenTy, SourceLocation l,
                          SourceLocation RParenLoc)
     : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
                        pathSize, writtenTy, l, RParenLoc) {}
@@ -283,7 +286,7 @@
   static CXXReinterpretCastExpr *Create(ASTContext &Context, QualType T,
                                         ExprValueKind VK, CastKind Kind,
                                         Expr *Op, const CXXCastPath *Path,
-                                 TypeSourceInfo *WrittenTy, SourceLocation=
 L,=20
+                                 TypeSourceInfo *WrittenTy, SourceLocation=
 L,
                                         SourceLocation RParenLoc);
   static CXXReinterpretCastExpr *CreateEmpty(ASTContext &Context,
                                              unsigned pathSize);
@@ -301,9 +304,9 @@
 /// @c const_cast<char*>(PtrToConstChar).
 class CXXConstCastExpr : public CXXNamedCastExpr {
   CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
-                   TypeSourceInfo *writtenTy, SourceLocation l,=20
+                   TypeSourceInfo *writtenTy, SourceLocation l,
                    SourceLocation RParenLoc)
-    : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,=20
+    : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
                        0, writtenTy, l, RParenLoc) {}
=20
   explicit CXXConstCastExpr(EmptyShell Empty)
@@ -312,7 +315,7 @@
 public:
   static CXXConstCastExpr *Create(ASTContext &Context, QualType T,
                                   ExprValueKind VK, Expr *Op,
-                                  TypeSourceInfo *WrittenTy, SourceLocatio=
n L,=20
+                                  TypeSourceInfo *WrittenTy, SourceLocatio=
n L,
                                   SourceLocation RParenLoc);
   static CXXConstCastExpr *CreateEmpty(ASTContext &Context);
=20
@@ -322,6 +325,67 @@
   static bool classof(const CXXConstCastExpr *) { return true; }
 };
=20
+/// UserDefinedLiteral - A call to a literal operator (C++11 [over.literal=
])
+/// written as a user-defined literal (C++11 [lit.ext]).
+///
+/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While t=
his
+/// is semantically equivalent to a normal call, this AST node provides be=
tter
+/// information about the syntactic representation of the literal.
+///
+/// Since literal operators are never found by ADL and can only be declare=
d at
+/// namespace scope, a user-defined literal is never dependent.
+class UserDefinedLiteral : public CallExpr {
+  /// \brief The location of a ud-suffix within the literal.
+  SourceLocation UDSuffixLoc;
+
+public:
+  UserDefinedLiteral(ASTContext &C, Expr *Fn, Expr **Args, unsigned NumArg=
s,
+                     QualType T, ExprValueKind VK, SourceLocation LitEndLo=
c,
+                     SourceLocation SuffixLoc)
+    : CallExpr(C, UserDefinedLiteralClass, Fn, 0, Args, NumArgs, T, VK,
+               LitEndLoc), UDSuffixLoc(SuffixLoc) {}
+  explicit UserDefinedLiteral(ASTContext &C, EmptyShell Empty)
+    : CallExpr(C, UserDefinedLiteralClass, Empty) {}
+
+  /// The kind of literal operator which is invoked.
+  enum LiteralOperatorKind {
+    LOK_Raw,      ///< Raw form: operator "" X (const char *)
+    LOK_Template, ///< Raw form: operator "" X<cs...> ()
+    LOK_Integer,  ///< operator "" X (unsigned long long)
+    LOK_Floating, ///< operator "" X (long double)
+    LOK_String,   ///< operator "" X (const CharT *, size_t)
+    LOK_Character ///< operator "" X (CharT)
+  };
+
+  /// getLiteralOperatorKind - Returns the kind of literal operator invoca=
tion
+  /// which this expression represents.
+  LiteralOperatorKind getLiteralOperatorKind() const;
+
+  /// getCookedLiteral - If this is not a raw user-defined literal, get the
+  /// underlying cooked literal (representing the literal with the suffix
+  /// removed).
+  Expr *getCookedLiteral();
+  const Expr *getCookedLiteral() const {
+    return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
+  }
+
+  /// getUDSuffixLoc - Returns the location of a ud-suffix in the expressi=
on.
+  /// For a string literal, there may be multiple identical suffixes. This
+  /// returns the first.
+  SourceLocation getUDSuffixLoc() const { return getRParenLoc(); }
+
+  /// getUDSuffix - Returns the ud-suffix specified for this literal.
+  const IdentifierInfo *getUDSuffix() const;
+
+  static bool classof(const Stmt *S) {
+    return S->getStmtClass() =3D=3D UserDefinedLiteralClass;
+  }
+  static bool classof(const UserDefinedLiteral *) { return true; }
+
+  friend class ASTStmtReader;
+  friend class ASTStmtWriter;
+};
+
 /// CXXBoolLiteralExpr - [C++ 2.13.5] C++ Boolean Literal.
 ///
 class CXXBoolLiteralExpr : public Expr {
@@ -339,7 +403,7 @@
   bool getValue() const { return Value; }
   void setValue(bool V) { Value =3D V; }
=20
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
=20
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc =3D L; }
@@ -365,7 +429,7 @@
   explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
     : Expr(CXXNullPtrLiteralExprClass, Empty) { }
=20
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
=20
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc =3D L; }
@@ -398,7 +462,7 @@
            Operand->getType()->isInstantiationDependentType(),
            Operand->getType()->containsUnexpandedParameterPack()),
       Operand(Operand), Range(R) { }
- =20
+
   CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
     : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
         // typeid is never type-dependent (C++ [temp.dep.expr]p4)
@@ -416,9 +480,9 @@
     else
       Operand =3D (TypeSourceInfo*)0;
   }
- =20
+
   bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
- =20
+
   /// \brief Retrieves the type operand of this typeid() expression after
   /// various required adjustments (removing reference types, cv-qualifier=
s).
   QualType getTypeOperand() const;
@@ -433,20 +497,20 @@
     assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)=
");
     Operand =3D TSI;
   }
- =20
+
   Expr *getExprOperand() const {
     assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type=
)");
     return static_cast<Expr*>(Operand.get<Stmt *>());
   }
- =20
+
   void setExprOperand(Expr *E) {
     assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type=
)");
     Operand =3D E;
   }
- =20
-  SourceRange getSourceRange() const { return Range; }
+
+  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
   void setSourceRange(SourceRange R) { Range =3D R; }
- =20
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXTypeidExprClass;
   }
@@ -476,7 +540,7 @@
            Operand->getType()->isInstantiationDependentType(),
            Operand->getType()->containsUnexpandedParameterPack()),
       Operand(Operand), Range(R) { }
- =20
+
   CXXUuidofExpr(QualType Ty, Expr *Operand, SourceRange R)
     : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
            false, Operand->isTypeDependent(),
@@ -491,9 +555,9 @@
     else
       Operand =3D (TypeSourceInfo*)0;
   }
- =20
+
   bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
- =20
+
   /// \brief Retrieves the type operand of this __uuidof() expression after
   /// various required adjustments (removing reference types, cv-qualifier=
s).
   QualType getTypeOperand() const;
@@ -508,20 +572,20 @@
     assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(exp=
r)");
     Operand =3D TSI;
   }
- =20
+
   Expr *getExprOperand() const {
     assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(ty=
pe)");
     return static_cast<Expr*>(Operand.get<Stmt *>());
   }
- =20
+
   void setExprOperand(Expr *E) {
     assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(ty=
pe)");
     Operand =3D E;
   }
=20
-  SourceRange getSourceRange() const { return Range; }
+  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
   void setSourceRange(SourceRange R) { Range =3D R; }
- =20
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXUuidofExprClass;
   }
@@ -549,7 +613,7 @@
 class CXXThisExpr : public Expr {
   SourceLocation Loc;
   bool Implicit : 1;
- =20
+
 public:
   CXXThisExpr(SourceLocation L, QualType Type, bool isImplicit)
     : Expr(CXXThisExprClass, Type, VK_RValue, OK_Ordinary,
@@ -565,11 +629,11 @@
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc =3D L; }
=20
-  SourceRange getSourceRange() const { return SourceRange(Loc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
=20
   bool isImplicit() const { return Implicit; }
   void setImplicit(bool I) { Implicit =3D I; }
- =20
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXThisExprClass;
   }
@@ -588,9 +652,9 @@
   SourceLocation ThrowLoc;
   /// \brief Whether the thrown variable (if any) is in scope.
   unsigned IsThrownVariableInScope : 1;
- =20
+
   friend class ASTStmtReader;
- =20
+
 public:
   // Ty is the void type which is used as the result type of the
   // exepression.  The l is the location of the throw keyword.  expr
@@ -614,8 +678,8 @@
   /// This information is required to determine whether the NRVO can apply=
 to
   /// this variable.
   bool isThrownVariableInScope() const { return IsThrownVariableInScope; }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     if (getSubExpr() =3D=3D 0)
       return SourceRange(ThrowLoc, ThrowLoc);
     return SourceRange(ThrowLoc, getSubExpr()->getSourceRange().getEnd());
@@ -639,16 +703,16 @@
 class CXXDefaultArgExpr : public Expr {
   /// \brief The parameter whose default is being used.
   ///
-  /// When the bit is set, the subexpression is stored after the=20
+  /// When the bit is set, the subexpression is stored after the
   /// CXXDefaultArgExpr itself. When the bit is clear, the parameter's
   /// actual default expression is the subexpression.
   llvm::PointerIntPair<ParmVarDecl *, 1, bool> Param;
=20
   /// \brief The location where the default argument expression was used.
   SourceLocation Loc;
- =20
+
   CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param)
-    : Expr(SC,=20
+    : Expr(SC,
            param->hasUnparsedDefaultArg()
              ? param->getType().getNonReferenceType()
              : param->getDefaultArg()->getType(),
@@ -656,19 +720,19 @@
            param->getDefaultArg()->getObjectKind(), false, false, false, f=
alse),
       Param(param, false), Loc(Loc) { }
=20
-  CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param,=20
+  CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param,
                     Expr *SubExpr)
     : Expr(SC, SubExpr->getType(),
            SubExpr->getValueKind(), SubExpr->getObjectKind(),
-           false, false, false, false),=20
+           false, false, false, false),
       Param(param, true), Loc(Loc) {
     *reinterpret_cast<Expr **>(this + 1) =3D SubExpr;
   }
- =20
+
 public:
   CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty=
) {}
=20
- =20
+
   // Param is the parameter whose default argument is used by this
   // expression.
   static CXXDefaultArgExpr *Create(ASTContext &C, SourceLocation Loc,
@@ -678,32 +742,32 @@
=20
   // Param is the parameter whose default argument is used by this
   // expression, and SubExpr is the expression that will actually be used.
-  static CXXDefaultArgExpr *Create(ASTContext &C,=20
+  static CXXDefaultArgExpr *Create(ASTContext &C,
                                    SourceLocation Loc,
-                                   ParmVarDecl *Param,=20
+                                   ParmVarDecl *Param,
                                    Expr *SubExpr);
- =20
+
   // Retrieve the parameter that the argument was created from.
   const ParmVarDecl *getParam() const { return Param.getPointer(); }
   ParmVarDecl *getParam() { return Param.getPointer(); }
- =20
+
   // Retrieve the actual argument to the function call.
-  const Expr *getExpr() const {=20
+  const Expr *getExpr() const {
     if (Param.getInt())
       return *reinterpret_cast<Expr const * const*> (this + 1);
-    return getParam()->getDefaultArg();=20
+    return getParam()->getDefaultArg();
   }
-  Expr *getExpr() {=20
+  Expr *getExpr() {
     if (Param.getInt())
       return *reinterpret_cast<Expr **> (this + 1);
-    return getParam()->getDefaultArg();=20
+    return getParam()->getDefaultArg();
   }
=20
-  /// \brief Retrieve the location where this default argument was actuall=
y=20
+  /// \brief Retrieve the location where this default argument was actually
   /// used.
   SourceLocation getUsedLocation() const { return Loc; }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     // Default argument expressions have no representation in the
     // source, so they have an empty source range.
     return SourceRange();
@@ -734,6 +798,9 @@
                               const CXXDestructorDecl *Destructor);
=20
   const CXXDestructorDecl *getDestructor() const { return Destructor; }
+  void setDestructor(const CXXDestructorDecl *Dtor) {
+    Destructor =3D Dtor;
+  }
 };
=20
 /// \brief Represents binding an expression to a temporary.
@@ -757,7 +824,7 @@
=20
   CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
    : Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
-          VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),=20
+          VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
           SubExpr->isValueDependent(),
           SubExpr->isInstantiationDependent(),
           SubExpr->containsUnexpandedParameterPack()),
@@ -766,7 +833,7 @@
 public:
   CXXBindTemporaryExpr(EmptyShell Empty)
     : Expr(CXXBindTemporaryExprClass, Empty), Temp(0), SubExpr(0) {}
- =20
+
   static CXXBindTemporaryExpr *Create(ASTContext &C, CXXTemporary *Temp,
                                       Expr* SubExpr);
=20
@@ -778,7 +845,7 @@
   Expr *getSubExpr() { return cast<Expr>(SubExpr); }
   void setSubExpr(Expr *E) { SubExpr =3D E; }
=20
-  SourceRange getSourceRange() const {=20
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SubExpr->getSourceRange();
   }
=20
@@ -801,7 +868,7 @@
     CK_VirtualBase,
     CK_Delegating
   };
-   =20
+
 private:
   CXXConstructorDecl *Constructor;
=20
@@ -810,6 +877,7 @@
   unsigned NumArgs : 16;
   bool Elidable : 1;
   bool HadMultipleCandidates : 1;
+  bool ListInitialization : 1;
   bool ZeroInitialization : 1;
   unsigned ConstructKind : 2;
   Stmt **Args;
@@ -820,39 +888,43 @@
                    CXXConstructorDecl *d, bool elidable,
                    Expr **args, unsigned numargs,
                    bool HadMultipleCandidates,
-                   bool ZeroInitialization =3D false,
-                   ConstructionKind ConstructKind =3D CK_Complete,
-                   SourceRange ParenRange =3D SourceRange());
+                   bool ListInitialization,
+                   bool ZeroInitialization,
+                   ConstructionKind ConstructKind,
+                   SourceRange ParenRange);
=20
   /// \brief Construct an empty C++ construction expression.
   CXXConstructExpr(StmtClass SC, EmptyShell Empty)
-    : Expr(SC, Empty), Constructor(0), NumArgs(0), Elidable(0),
-      HadMultipleCandidates(false), ZeroInitialization(0),
-      ConstructKind(0), Args(0) { }
+    : Expr(SC, Empty), Constructor(0), NumArgs(0), Elidable(false),
+      HadMultipleCandidates(false), ListInitialization(false),
+      ZeroInitialization(false), ConstructKind(0), Args(0)
+  { }
=20
 public:
   /// \brief Construct an empty C++ construction expression.
   explicit CXXConstructExpr(EmptyShell Empty)
     : Expr(CXXConstructExprClass, Empty), Constructor(0),
-      NumArgs(0), Elidable(0), HadMultipleCandidates(false),
-      ZeroInitialization(0), ConstructKind(0), Args(0) { }
+      NumArgs(0), Elidable(false), HadMultipleCandidates(false),
+      ListInitialization(false), ZeroInitialization(false),
+      ConstructKind(0), Args(0)
+  { }
=20
   static CXXConstructExpr *Create(ASTContext &C, QualType T,
                                   SourceLocation Loc,
                                   CXXConstructorDecl *D, bool Elidable,
                                   Expr **Args, unsigned NumArgs,
                                   bool HadMultipleCandidates,
-                                  bool ZeroInitialization =3D false,
-                                  ConstructionKind ConstructKind =3D CK_Co=
mplete,
-                                  SourceRange ParenRange =3D SourceRange()=
);
-
+                                  bool ListInitialization,
+                                  bool ZeroInitialization,
+                                  ConstructionKind ConstructKind,
+                                  SourceRange ParenRange);
=20
   CXXConstructorDecl* getConstructor() const { return Constructor; }
   void setConstructor(CXXConstructorDecl *C) { Constructor =3D C; }
- =20
+
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation Loc) { this->Loc =3D Loc; }
- =20
+
   /// \brief Whether this construction is elidable.
   bool isElidable() const { return Elidable; }
   void setElidable(bool E) { Elidable =3D E; }
@@ -862,22 +934,26 @@
   bool hadMultipleCandidates() const { return HadMultipleCandidates; }
   void setHadMultipleCandidates(bool V) { HadMultipleCandidates =3D V; }
=20
+  /// \brief Whether this constructor call was written as list-initializat=
ion.
+  bool isListInitialization() const { return ListInitialization; }
+  void setListInitialization(bool V) { ListInitialization =3D V; }
+
   /// \brief Whether this construction first requires
   /// zero-initialization before the initializer is called.
   bool requiresZeroInitialization() const { return ZeroInitialization; }
   void setRequiresZeroInitialization(bool ZeroInit) {
     ZeroInitialization =3D ZeroInit;
   }
- =20
+
   /// \brief Determines whether this constructor is actually constructing
   /// a base class (rather than a complete object).
   ConstructionKind getConstructionKind() const {
     return (ConstructionKind)ConstructKind;
   }
-  void setConstructionKind(ConstructionKind CK) {=20
+  void setConstructionKind(ConstructionKind CK) {
     ConstructKind =3D CK;
   }
- =20
+
   typedef ExprIterator arg_iterator;
   typedef ConstExprIterator const_arg_iterator;
=20
@@ -905,7 +981,7 @@
     Args[Arg] =3D ArgExpr;
   }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
   SourceRange getParenRange() const { return ParenRange; }
=20
   static bool classof(const Stmt *T) {
@@ -933,7 +1009,7 @@
                         TypeSourceInfo *writtenTy,
                         SourceLocation tyBeginLoc, CastKind kind,
                         Expr *castExpr, unsigned pathSize,
-                        SourceLocation rParenLoc)=20
+                        SourceLocation rParenLoc)
     : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
                        castExpr, pathSize, writtenTy),
       TyBeginLoc(tyBeginLoc), RParenLoc(rParenLoc) {}
@@ -957,7 +1033,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(TyBeginLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -971,7 +1047,7 @@
 ///
 /// This expression type represents a C++ "functional" cast
 /// (C++[expr.type.conv]) with N !=3D 1 arguments that invokes a
-/// constructor to build a temporary object. With N =3D=3D 1 arguments the=20
+/// constructor to build a temporary object. With N =3D=3D 1 arguments the
 /// functional cast expression will be represented by CXXFunctionalCastExp=
r.
 /// Example:
 /// @code
@@ -996,8 +1072,8 @@
=20
   TypeSourceInfo *getTypeSourceInfo() const { return Type; }
=20
-  SourceRange getSourceRange() const;
- =20
+  SourceRange getSourceRange() const LLVM_READONLY;
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXTemporaryObjectExprClass;
   }
@@ -1006,6 +1082,303 @@
   friend class ASTStmtReader;
 };
=20
+/// \brief A C++ lambda expression, which produces a function object
+/// (of unspecified type) that can be invoked later.
+///
+/// Example:
+/// \code
+/// void low_pass_filter(std::vector<double> &values, double cutoff) {
+///   values.erase(std::remove_if(values.begin(), values.end(),
+//                                [=3D](double value) { return value > cut=
off; });
+/// }
+/// \endcode
+///
+/// Lambda expressions can capture local variables, either by copying
+/// the values of those local variables at the time the function
+/// object is constructed (not when it is called!) or by holding a
+/// reference to the local variable. These captures can occur either
+/// implicitly or can be written explicitly between the square
+/// brackets ([...]) that start the lambda expression.
+class LambdaExpr : public Expr {
+  enum {
+    /// \brief Flag used by the Capture class to indicate that the given
+    /// capture was implicit.
+    Capture_Implicit =3D 0x01,
+
+    /// \brief Flag used by the Capture class to indciate that the
+    /// given capture was by-copy.
+    Capture_ByCopy =3D 0x02
+  };
+
+  /// \brief The source range that covers the lambda introducer ([...]).
+  SourceRange IntroducerRange;
+
+  /// \brief The number of captures.
+  unsigned NumCaptures : 16;
+ =20
+  /// \brief The default capture kind, which is a value of type
+  /// LambdaCaptureDefault.
+  unsigned CaptureDefault : 2;
+
+  /// \brief Whether this lambda had an explicit parameter list vs. an
+  /// implicit (and empty) parameter list.
+  unsigned ExplicitParams : 1;
+
+  /// \brief Whether this lambda had the result type explicitly specified.
+  unsigned ExplicitResultType : 1;
+ =20
+  /// \brief Whether there are any array index variables stored at the end=
 of
+  /// this lambda expression.
+  unsigned HasArrayIndexVars : 1;
+ =20
+  /// \brief The location of the closing brace ('}') that completes
+  /// the lambda.
+  ///=20
+  /// The location of the brace is also available by looking up the
+  /// function call operator in the lambda class. However, it is
+  /// stored here to improve the performance of getSourceRange(), and
+  /// to avoid having to deserialize the function call operator from a
+  /// module file just to determine the source range.
+  SourceLocation ClosingBrace;
+
+  // Note: The capture initializers are stored directly after the lambda
+  // expression, along with the index variables used to initialize by-copy
+  // array captures.
+
+public:
+  /// \brief Describes the capture of either a variable or 'this'.
+  class Capture {
+    llvm::PointerIntPair<VarDecl *, 2> VarAndBits;
+    SourceLocation Loc;
+    SourceLocation EllipsisLoc;
+   =20
+    friend class ASTStmtReader;
+    friend class ASTStmtWriter;
+   =20
+  public:
+    /// \brief Create a new capture.
+    ///
+    /// \param Loc The source location associated with this capture.
+    ///
+    /// \param Kind The kind of capture (this, byref, bycopy).
+    ///
+    /// \param Implicit Whether the capture was implicit or explicit.
+    ///
+    /// \param Var The local variable being captured, or null if capturing=
 this.
+    ///
+    /// \param EllipsisLoc The location of the ellipsis (...) for a
+    /// capture that is a pack expansion, or an invalid source
+    /// location to indicate that this is not a pack expansion.
+    Capture(SourceLocation Loc, bool Implicit,
+            LambdaCaptureKind Kind, VarDecl *Var =3D 0,
+            SourceLocation EllipsisLoc =3D SourceLocation());
+
+    /// \brief Determine the kind of capture.
+    LambdaCaptureKind getCaptureKind() const;
+
+    /// \brief Determine whether this capture handles the C++ 'this'
+    /// pointer.
+    bool capturesThis() const { return VarAndBits.getPointer() =3D=3D 0; }
+
+    /// \brief Determine whether this capture handles a variable.
+    bool capturesVariable() const { return VarAndBits.getPointer() !=3D 0;=
 }
+
+    /// \brief Retrieve the declaration of the local variable being
+    /// captured.
+    ///
+    /// This operation is only valid if this capture does not capture
+    /// 'this'.
+    VarDecl *getCapturedVar() const {=20
+      assert(!capturesThis() && "No variable available for 'this' capture"=
);
+      return VarAndBits.getPointer();
+    }
+
+    /// \brief Determine whether this was an implicit capture (not
+    /// written between the square brackets introducing the lambda).
+    bool isImplicit() const { return VarAndBits.getInt() & Capture_Implici=
t; }
+
+    /// \brief Determine whether this was an explicit capture, written
+    /// between the square brackets introducing the lambda.
+    bool isExplicit() const { return !isImplicit(); }
+
+    /// \brief Retrieve the source location of the capture.
+    ///
+    /// For an explicit capture, this returns the location of the
+    /// explicit capture in the source. For an implicit capture, this
+    /// returns the location at which the variable or 'this' was first
+    /// used.
+    SourceLocation getLocation() const { return Loc; }
+
+    /// \brief Determine whether this capture is a pack expansion,
+    /// which captures a function parameter pack.
+    bool isPackExpansion() const { return EllipsisLoc.isValid(); }
+
+    /// \brief Retrieve the location of the ellipsis for a capture
+    /// that is a pack expansion.
+    SourceLocation getEllipsisLoc() const {
+      assert(isPackExpansion() && "No ellipsis location for a non-expansio=
n");
+      return EllipsisLoc;
+    }
+  };
+
+private:
+  /// \brief Construct a lambda expression.
+  LambdaExpr(QualType T, SourceRange IntroducerRange,
+             LambdaCaptureDefault CaptureDefault,
+             ArrayRef<Capture> Captures,
+             bool ExplicitParams,
+             bool ExplicitResultType,
+             ArrayRef<Expr *> CaptureInits,
+             ArrayRef<VarDecl *> ArrayIndexVars,
+             ArrayRef<unsigned> ArrayIndexStarts,
+             SourceLocation ClosingBrace);
+
+  /// \brief Construct an empty lambda expression.
+  LambdaExpr(EmptyShell Empty, unsigned NumCaptures, bool HasArrayIndexVar=
s)
+    : Expr(LambdaExprClass, Empty),
+      NumCaptures(NumCaptures), CaptureDefault(LCD_None), ExplicitParams(f=
alse),
+      ExplicitResultType(false), HasArrayIndexVars(true) {=20
+    getStoredStmts()[NumCaptures] =3D 0;
+  }
+ =20
+  Stmt **getStoredStmts() const {
+    return reinterpret_cast<Stmt **>(const_cast<LambdaExpr *>(this) + 1);
+  }
+ =20
+  /// \brief Retrieve the mapping from captures to the first array index
+  /// variable.
+  unsigned *getArrayIndexStarts() const {
+    return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1=
);
+  }
+ =20
+  /// \brief Retrieve the complete set of array-index variables.
+  VarDecl **getArrayIndexVars() const {
+    return reinterpret_cast<VarDecl **>(
+             getArrayIndexStarts() + NumCaptures + 1);
+  }
+
+public:
+  /// \brief Construct a new lambda expression.
+  static LambdaExpr *Create(ASTContext &C,=20
+                            CXXRecordDecl *Class,
+                            SourceRange IntroducerRange,
+                            LambdaCaptureDefault CaptureDefault,
+                            ArrayRef<Capture> Captures,
+                            bool ExplicitParams,
+                            bool ExplicitResultType,
+                            ArrayRef<Expr *> CaptureInits,
+                            ArrayRef<VarDecl *> ArrayIndexVars,
+                            ArrayRef<unsigned> ArrayIndexStarts,
+                            SourceLocation ClosingBrace);
+
+  /// \brief Construct a new lambda expression that will be deserialized f=
rom
+  /// an external source.
+  static LambdaExpr *CreateDeserialized(ASTContext &C, unsigned NumCapture=
s,
+                                        unsigned NumArrayIndexVars);
+ =20
+  /// \brief Determine the default capture kind for this lambda.
+  LambdaCaptureDefault getCaptureDefault() const {
+    return static_cast<LambdaCaptureDefault>(CaptureDefault);
+  }
+
+  /// \brief An iterator that walks over the captures of the lambda,
+  /// both implicit and explicit.
+  typedef const Capture *capture_iterator;
+
+  /// \brief Retrieve an iterator pointing to the first lambda capture.
+  capture_iterator capture_begin() const;
+
+  /// \brief Retrieve an iterator pointing past the end of the
+  /// sequence of lambda captures.
+  capture_iterator capture_end() const;
+
+  /// \brief Determine the number of captures in this lambda.
+  unsigned capture_size() const { return NumCaptures; }
+ =20
+  /// \brief Retrieve an iterator pointing to the first explicit
+  /// lambda capture.
+  capture_iterator explicit_capture_begin() const;
+
+  /// \brief Retrieve an iterator pointing past the end of the sequence of
+  /// explicit lambda captures.
+  capture_iterator explicit_capture_end() const;
+
+  /// \brief Retrieve an iterator pointing to the first implicit
+  /// lambda capture.
+  capture_iterator implicit_capture_begin() const;
+
+  /// \brief Retrieve an iterator pointing past the end of the sequence of
+  /// implicit lambda captures.
+  capture_iterator implicit_capture_end() const;
+
+  /// \brief Iterator that walks over the capture initialization
+  /// arguments.
+  typedef Expr **capture_init_iterator;
+
+  /// \brief Retrieve the first initialization argument for this
+  /// lambda expression (which initializes the first capture field).
+  capture_init_iterator capture_init_begin() const {
+    return reinterpret_cast<Expr **>(getStoredStmts());
+  }
+
+  /// \brief Retrieve the iterator pointing one past the last
+  /// initialization argument for this lambda expression.
+  capture_init_iterator capture_init_end() const {
+    return capture_init_begin() + NumCaptures;   =20
+  }
+
+  /// \brief Retrieve the set of index variables used in the capture=20
+  /// initializer of an array captured by copy.
+  ///
+  /// \param Iter The iterator that points at the capture initializer for=20
+  /// which we are extracting the corresponding index variables.
+  ArrayRef<VarDecl *> getCaptureInitIndexVars(capture_init_iterator Iter) =
const;
+ =20
+  /// \brief Retrieve the source range covering the lambda introducer,
+  /// which contains the explicit capture list surrounded by square
+  /// brackets ([...]).
+  SourceRange getIntroducerRange() const { return IntroducerRange; }
+
+  /// \brief Retrieve the class that corresponds to the lambda, which
+  /// stores the captures in its fields and provides the various
+  /// operations permitted on a lambda (copying, calling).
+  CXXRecordDecl *getLambdaClass() const;
+
+  /// \brief Retrieve the function call operator associated with this
+  /// lambda expression.=20
+  CXXMethodDecl *getCallOperator() const;
+
+  /// \brief Retrieve the body of the lambda.
+  CompoundStmt *getBody() const;
+
+  /// \brief Determine whether the lambda is mutable, meaning that any
+  /// captures values can be modified.
+  bool isMutable() const;
+
+  /// \brief Determine whether this lambda has an explicit parameter
+  /// list vs. an implicit (empty) parameter list.
+  bool hasExplicitParameters() const { return ExplicitParams; }
+
+  /// \brief Whether this lambda had its result type explicitly specified.
+  bool hasExplicitResultType() const { return ExplicitResultType; }
+   =20
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() =3D=3D LambdaExprClass;
+  }
+  static bool classof(const LambdaExpr *) { return true; }
+
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return SourceRange(IntroducerRange.getBegin(), ClosingBrace);
+  }
+
+  child_range children() {
+    return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + =
1);
+  }
+
+  friend class ASTStmtReader;
+  friend class ASTStmtWriter;
+};
+
 /// CXXScalarValueInitExpr - [C++ 5.2.3p2]
 /// Expression "T()" which creates a value-initialized rvalue of type
 /// T, which is a non-class type.
@@ -1015,9 +1388,9 @@
   TypeSourceInfo *TypeInfo;
=20
   friend class ASTStmtReader;
- =20
+
 public:
-  /// \brief Create an explicitly-written scalar-value initialization=20
+  /// \brief Create an explicitly-written scalar-value initialization
   /// expression.
   CXXScalarValueInitExpr(QualType Type,
                          TypeSourceInfo *TypeInfo,
@@ -1032,10 +1405,10 @@
   TypeSourceInfo *getTypeSourceInfo() const {
     return TypeInfo;
   }
- =20
+
   SourceLocation getRParenLoc() const { return RParenLoc; }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXScalarValueInitExprClass;
@@ -1049,68 +1422,63 @@
 /// CXXNewExpr - A new expression for memory allocation and constructor ca=
lls,
 /// e.g: "new CXXNewExpr(foo)".
 class CXXNewExpr : public Expr {
+  // Contains an optional array size expression, an optional initialization
+  // expression, and any number of optional placement arguments, in that o=
rder.
+  Stmt **SubExprs;
+  // Points to the allocation function used.
+  FunctionDecl *OperatorNew;
+  // Points to the deallocation function used in case of error. May be nul=
l.
+  FunctionDecl *OperatorDelete;
+
+  /// \brief The allocated type-source information, as written in the sour=
ce.
+  TypeSourceInfo *AllocatedTypeInfo;
+
+  /// \brief If the allocated type was expressed as a parenthesized type-i=
d,
+  /// the source range covering the parenthesized type-id.
+  SourceRange TypeIdParens;
+
+  /// \brief Location of the first token.
+  SourceLocation StartLoc;
+
+  /// \brief Source-range of a paren-delimited initializer.
+  SourceRange DirectInitRange;
+
   // Was the usage ::new, i.e. is the global new to be used?
   bool GlobalNew : 1;
-  // Is there an initializer? If not, built-ins are uninitialized, else th=
ey're
-  // value-initialized.
-  bool Initializer : 1;
   // Do we allocate an array? If so, the first SubExpr is the size express=
ion.
   bool Array : 1;
   // If this is an array allocation, does the usual deallocation
   // function for the allocated type want to know the allocated size?
   bool UsualArrayDeleteWantsSize : 1;
-  // Whether the referred constructor (if any) was resolved from an
-  // overload set having size greater than 1.
-  bool HadMultipleCandidates : 1;
   // The number of placement new arguments.
   unsigned NumPlacementArgs : 13;
-  // The number of constructor arguments. This may be 1 even for non-class
-  // types; use the pseudo copy constructor.
-  unsigned NumConstructorArgs : 14;
-  // Contains an optional array size expression, any number of optional
-  // placement arguments, and any number of optional constructor arguments,
-  // in that order.
-  Stmt **SubExprs;
-  // Points to the allocation function used.
-  FunctionDecl *OperatorNew;
-  // Points to the deallocation function used in case of error. May be nul=
l.
-  FunctionDecl *OperatorDelete;
-  // Points to the constructor used. Cannot be null if AllocType is a reco=
rd;
-  // it would still point at the default constructor (even an implicit one=
).
-  // Must be null for all other types.
-  CXXConstructorDecl *Constructor;
-
-  /// \brief The allocated type-source information, as written in the sour=
ce.
-  TypeSourceInfo *AllocatedTypeInfo;
- =20
-  /// \brief If the allocated type was expressed as a parenthesized type-i=
d,=20
-  /// the source range covering the parenthesized type-id.
-  SourceRange TypeIdParens;
- =20
-  SourceLocation StartLoc;
-  SourceLocation EndLoc;
-  SourceLocation ConstructorLParen;
-  SourceLocation ConstructorRParen;
+  // What kind of initializer do we have? Could be none, parens, or braces.
+  // In storage, we distinguish between "none, and no initializer expr", a=
nd
+  // "none, but an implicit initializer expr".
+  unsigned StoredInitializationStyle : 2;
=20
   friend class ASTStmtReader;
+  friend class ASTStmtWriter;
 public:
+  enum InitializationStyle {
+    NoInit,   ///< New-expression has no initializer as written.
+    CallInit, ///< New-expression has a C++98 paren-delimited initializer.
+    ListInit  ///< New-expression has a C++11 list-initializer.
+  };
+
   CXXNewExpr(ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
+             FunctionDecl *operatorDelete, bool usualArrayDeleteWantsSize,
              Expr **placementArgs, unsigned numPlaceArgs,
-             SourceRange TypeIdParens,
-             Expr *arraySize, CXXConstructorDecl *constructor, bool initia=
lizer,
-             Expr **constructorArgs, unsigned numConsArgs,
-             bool HadMultipleCandidates,
-             FunctionDecl *operatorDelete, bool usualArrayDeleteWantsSize,
+             SourceRange typeIdParens, Expr *arraySize,
+             InitializationStyle initializationStyle, Expr *initializer,
              QualType ty, TypeSourceInfo *AllocatedTypeInfo,
-             SourceLocation startLoc, SourceLocation endLoc,
-             SourceLocation constructorLParen,
-             SourceLocation constructorRParen);
+             SourceLocation startLoc, SourceRange directInitRange);
   explicit CXXNewExpr(EmptyShell Shell)
     : Expr(CXXNewExprClass, Shell), SubExprs(0) { }
=20
   void AllocateArgsArray(ASTContext &C, bool isArray, unsigned numPlaceArg=
s,
-                         unsigned numConsArgs);
- =20
+                         bool hasInitializer);
+
   QualType getAllocatedType() const {
     assert(getType()->isPointerType());
     return getType()->getAs<PointerType>()->getPointeeType();
@@ -1130,13 +1498,11 @@
   /// identical except that the definition of a non-throwing
   /// exception specification is just "is it throw()?".
   bool shouldNullCheckAllocation(ASTContext &Ctx) const;
- =20
+
   FunctionDecl *getOperatorNew() const { return OperatorNew; }
   void setOperatorNew(FunctionDecl *D) { OperatorNew =3D D; }
   FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
   void setOperatorDelete(FunctionDecl *D) { OperatorDelete =3D D; }
-  CXXConstructorDecl *getConstructor() const { return Constructor; }
-  void setConstructor(CXXConstructorDecl *D) { Constructor =3D D; }
=20
   bool isArray() const { return Array; }
   Expr *getArraySize() {
@@ -1147,24 +1513,46 @@
   }
=20
   unsigned getNumPlacementArgs() const { return NumPlacementArgs; }
-  Expr **getPlacementArgs() {=20
-    return reinterpret_cast<Expr **>(SubExprs + Array);=20
+  Expr **getPlacementArgs() {
+    return reinterpret_cast<Expr **>(SubExprs + Array + hasInitializer());
   }
- =20
+
   Expr *getPlacementArg(unsigned i) {
     assert(i < NumPlacementArgs && "Index out of range");
-    return cast<Expr>(SubExprs[Array + i]);
+    return getPlacementArgs()[i];
   }
   const Expr *getPlacementArg(unsigned i) const {
     assert(i < NumPlacementArgs && "Index out of range");
-    return cast<Expr>(SubExprs[Array + i]);
+    return const_cast<CXXNewExpr*>(this)->getPlacementArg(i);
   }
=20
   bool isParenTypeId() const { return TypeIdParens.isValid(); }
   SourceRange getTypeIdParens() const { return TypeIdParens; }
=20
   bool isGlobalNew() const { return GlobalNew; }
-  bool hasInitializer() const { return Initializer; }
+
+  /// \brief Whether this new-expression has any initializer at all.
+  bool hasInitializer() const { return StoredInitializationStyle > 0; }
+
+  /// \brief The kind of initializer this new-expression has.
+  InitializationStyle getInitializationStyle() const {
+    if (StoredInitializationStyle =3D=3D 0)
+      return NoInit;
+    return static_cast<InitializationStyle>(StoredInitializationStyle-1);
+  }
+
+  /// \brief The initializer of this new-expression.
+  Expr *getInitializer() {
+    return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
+  }
+  const Expr *getInitializer() const {
+    return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
+  }
+
+  /// \brief Returns the CXXConstructExpr from this new-expression, or NUL=
L.
+  const CXXConstructExpr* getConstructExpr() {
+    return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
+  }
=20
   /// Answers whether the usual array deallocation function for the
   /// allocated type expects the size of the allocation as a
@@ -1173,71 +1561,39 @@
     return UsualArrayDeleteWantsSize;
   }
=20
-  unsigned getNumConstructorArgs() const { return NumConstructorArgs; }
- =20
-  Expr **getConstructorArgs() {
-    return reinterpret_cast<Expr **>(SubExprs + Array + NumPlacementArgs);
-  }
- =20
-  Expr *getConstructorArg(unsigned i) {
-    assert(i < NumConstructorArgs && "Index out of range");
-    return cast<Expr>(SubExprs[Array + NumPlacementArgs + i]);
-  }
-  const Expr *getConstructorArg(unsigned i) const {
-    assert(i < NumConstructorArgs && "Index out of range");
-    return cast<Expr>(SubExprs[Array + NumPlacementArgs + i]);
-  }
-
-  /// \brief Whether the new expression refers a constructor that was
-  /// resolved from an overloaded set having size greater than 1.
-  bool hadMultipleCandidates() const { return HadMultipleCandidates; }
-  void setHadMultipleCandidates(bool V) { HadMultipleCandidates =3D V; }
-
   typedef ExprIterator arg_iterator;
   typedef ConstExprIterator const_arg_iterator;
=20
   arg_iterator placement_arg_begin() {
-    return SubExprs + Array;
+    return SubExprs + Array + hasInitializer();
   }
   arg_iterator placement_arg_end() {
-    return SubExprs + Array + getNumPlacementArgs();
+    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
   }
   const_arg_iterator placement_arg_begin() const {
-    return SubExprs + Array;
+    return SubExprs + Array + hasInitializer();
   }
   const_arg_iterator placement_arg_end() const {
-    return SubExprs + Array + getNumPlacementArgs();
+    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
   }
=20
-  arg_iterator constructor_arg_begin() {
-    return SubExprs + Array + getNumPlacementArgs();
-  }
-  arg_iterator constructor_arg_end() {
-    return SubExprs + Array + getNumPlacementArgs() + getNumConstructorArg=
s();
-  }
-  const_arg_iterator constructor_arg_begin() const {
-    return SubExprs + Array + getNumPlacementArgs();
-  }
-  const_arg_iterator constructor_arg_end() const {
-    return SubExprs + Array + getNumPlacementArgs() + getNumConstructorArg=
s();
-  }
- =20
   typedef Stmt **raw_arg_iterator;
   raw_arg_iterator raw_arg_begin() { return SubExprs; }
   raw_arg_iterator raw_arg_end() {
-    return SubExprs + Array + getNumPlacementArgs() + getNumConstructorArg=
s();
+    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
   }
   const_arg_iterator raw_arg_begin() const { return SubExprs; }
-  const_arg_iterator raw_arg_end() const { return constructor_arg_end(); }
+  const_arg_iterator raw_arg_end() const {
+    return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
+  }
=20
   SourceLocation getStartLoc() const { return StartLoc; }
-  SourceLocation getEndLoc() const { return EndLoc; }
-
-  SourceLocation getConstructorLParen() const { return ConstructorLParen; }
-  SourceLocation getConstructorRParen() const { return ConstructorRParen; }
-
-  SourceRange getSourceRange() const {
-    return SourceRange(StartLoc, EndLoc);
+  SourceLocation getEndLoc() const;
+
+  SourceRange getDirectInitRange() const { return DirectInitRange; }
+
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return SourceRange(getStartLoc(), getEndLoc());
   }
=20
   static bool classof(const Stmt *T) {
@@ -1247,15 +1603,19 @@
=20
   // Iterators
   child_range children() {
-    return child_range(&SubExprs[0],
-                       &SubExprs[0] + Array + getNumPlacementArgs()
-                         + getNumConstructorArgs());
+    return child_range(raw_arg_begin(), raw_arg_end());
   }
 };
=20
 /// CXXDeleteExpr - A delete expression for memory deallocation and destru=
ctor
 /// calls, e.g. "delete[] pArray".
 class CXXDeleteExpr : public Expr {
+  // Points to the operator delete overload that is used. Could be a membe=
r.
+  FunctionDecl *OperatorDelete;
+  // The pointer expression to be deleted.
+  Stmt *Argument;
+  // Location of the expression.
+  SourceLocation Loc;
   // Is this a forced global delete, i.e. "::delete"?
   bool GlobalDelete : 1;
   // Is this the array form of delete, i.e. "delete[]"?
@@ -1267,12 +1627,6 @@
   // Does the usual deallocation function for the element type require
   // a size_t argument?
   bool UsualArrayDeleteWantsSize : 1;
-  // Points to the operator delete overload that is used. Could be a membe=
r.
-  FunctionDecl *OperatorDelete;
-  // The pointer expression to be deleted.
-  Stmt *Argument;
-  // Location of the expression.
-  SourceLocation Loc;
 public:
   CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm,
                 bool arrayFormAsWritten, bool usualArrayDeleteWantsSize,
@@ -1280,10 +1634,10 @@
     : Expr(CXXDeleteExprClass, ty, VK_RValue, OK_Ordinary, false, false,
            arg->isInstantiationDependent(),
            arg->containsUnexpandedParameterPack()),
+      OperatorDelete(operatorDelete), Argument(arg), Loc(loc),
       GlobalDelete(globalDelete),
       ArrayForm(arrayForm), ArrayFormAsWritten(arrayFormAsWritten),
-      UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize),
-      OperatorDelete(operatorDelete), Argument(arg), Loc(loc) { }
+      UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) { }
   explicit CXXDeleteExpr(EmptyShell Shell)
     : Expr(CXXDeleteExprClass, Shell), OperatorDelete(0), Argument(0) { }
=20
@@ -1308,8 +1662,8 @@
   /// destroyed is a dependent type which may or may not be a pointer,
   /// return an invalid type.
   QualType getDestroyedType() const;
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(Loc, Argument->getLocEnd());
   }
=20
@@ -1324,39 +1678,39 @@
   friend class ASTStmtReader;
 };
=20
-/// \brief Structure used to store the type being destroyed by a=20
+/// \brief Structure used to store the type being destroyed by a
 /// pseudo-destructor expression.
 class PseudoDestructorTypeStorage {
-  /// \brief Either the type source information or the name of the type, i=
f=20
+  /// \brief Either the type source information or the name of the type, if
   /// it couldn't be resolved due to type-dependence.
   llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
- =20
+
   /// \brief The starting source location of the pseudo-destructor type.
   SourceLocation Location;
- =20
+
 public:
   PseudoDestructorTypeStorage() { }
- =20
+
   PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
     : Type(II), Location(Loc) { }
- =20
+
   PseudoDestructorTypeStorage(TypeSourceInfo *Info);
- =20
-  TypeSourceInfo *getTypeSourceInfo() const {=20
-    return Type.dyn_cast<TypeSourceInfo *>();=20
+
+  TypeSourceInfo *getTypeSourceInfo() const {
+    return Type.dyn_cast<TypeSourceInfo *>();
   }
- =20
+
   IdentifierInfo *getIdentifier() const {
     return Type.dyn_cast<IdentifierInfo *>();
   }
- =20
+
   SourceLocation getLocation() const { return Location; }
 };
- =20
+
 /// \brief Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
 ///
 /// A pseudo-destructor is an expression that looks like a member access t=
o a
-/// destructor of a scalar type, except that scalar types don't have=20
+/// destructor of a scalar type, except that scalar types don't have
 /// destructors. For example:
 ///
 /// \code
@@ -1367,7 +1721,7 @@
 /// \endcode
 ///
 /// Pseudo-destructors typically occur when instantiating templates such a=
s:
-///=20
+///
 /// \code
 /// template<typename T>
 /// void destroy(T* ptr) {
@@ -1387,27 +1741,27 @@
=20
   /// \brief The location of the '.' or '->' operator.
   SourceLocation OperatorLoc;
- =20
+
   /// \brief The nested-name-specifier that follows the operator, if prese=
nt.
   NestedNameSpecifierLoc QualifierLoc;
=20
   /// \brief The type that precedes the '::' in a qualified pseudo-destruc=
tor
   /// expression.
   TypeSourceInfo *ScopeType;
- =20
-  /// \brief The location of the '::' in a qualified pseudo-destructor=20
+
+  /// \brief The location of the '::' in a qualified pseudo-destructor
   /// expression.
   SourceLocation ColonColonLoc;
- =20
+
   /// \brief The location of the '~'.
   SourceLocation TildeLoc;
- =20
-  /// \brief The type being destroyed, or its name if we were unable to=20
+
+  /// \brief The type being destroyed, or its name if we were unable to
   /// resolve the name.
   PseudoDestructorTypeStorage DestroyedType;
=20
   friend class ASTStmtReader;
- =20
+
 public:
   CXXPseudoDestructorExpr(ASTContext &Context,
                           Expr *Base, bool isArrow, SourceLocation Operato=
rLoc,
@@ -1431,12 +1785,12 @@
   /// \brief Retrieves the nested-name-specifier that qualifies the type n=
ame,
   /// with source-location information.
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
- =20
+
   /// \brief If the member name was qualified, retrieves the
   /// nested-name-specifier that precedes the member name. Otherwise, retu=
rns
   /// NULL.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
=20
   /// \brief Determine whether this pseudo-destructor expression was writt=
en
@@ -1446,48 +1800,48 @@
   /// \brief Retrieve the location of the '.' or '->' operator.
   SourceLocation getOperatorLoc() const { return OperatorLoc; }
=20
-  /// \brief Retrieve the scope type in a qualified pseudo-destructor=20
+  /// \brief Retrieve the scope type in a qualified pseudo-destructor
   /// expression.
   ///
   /// Pseudo-destructor expressions can have extra qualification within th=
em
   /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
   /// Here, if the object type of the expression is (or may be) a scalar t=
ype,
-  /// \p T may also be a scalar type and, therefore, cannot be part of a=20
+  /// \p T may also be a scalar type and, therefore, cannot be part of a
   /// nested-name-specifier. It is stored as the "scope type" of the pseud=
o-
   /// destructor expression.
   TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
- =20
+
   /// \brief Retrieve the location of the '::' in a qualified pseudo-destr=
uctor
   /// expression.
   SourceLocation getColonColonLoc() const { return ColonColonLoc; }
- =20
+
   /// \brief Retrieve the location of the '~'.
   SourceLocation getTildeLoc() const { return TildeLoc; }
- =20
+
   /// \brief Retrieve the source location information for the type
   /// being destroyed.
   ///
-  /// This type-source information is available for non-dependent=20
+  /// This type-source information is available for non-dependent
   /// pseudo-destructor expressions and some dependent pseudo-destructor
   /// expressions. Returns NULL if we only have the identifier for a
   /// dependent pseudo-destructor expression.
-  TypeSourceInfo *getDestroyedTypeInfo() const {=20
-    return DestroyedType.getTypeSourceInfo();=20
+  TypeSourceInfo *getDestroyedTypeInfo() const {
+    return DestroyedType.getTypeSourceInfo();
   }
- =20
+
   /// \brief In a dependent pseudo-destructor expression for which we do n=
ot
   /// have full type information on the destroyed type, provides the name
   /// of the destroyed type.
   IdentifierInfo *getDestroyedTypeIdentifier() const {
     return DestroyedType.getIdentifier();
   }
- =20
+
   /// \brief Retrieve the type being destroyed.
   QualType getDestroyedType() const;
- =20
+
   /// \brief Retrieve the starting location of the type being destroyed.
-  SourceLocation getDestroyedTypeLoc() const {=20
-    return DestroyedType.getLocation();=20
+  SourceLocation getDestroyedTypeLoc() const {
+    return DestroyedType.getLocation();
   }
=20
   /// \brief Set the name of destroyed type for a dependent pseudo-destruc=
tor
@@ -1501,7 +1855,7 @@
     DestroyedType =3D PseudoDestructorTypeStorage(Info);
   }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXPseudoDestructorExprClass;
@@ -1533,7 +1887,7 @@
   TypeSourceInfo *QueriedType;
=20
 public:
-  UnaryTypeTraitExpr(SourceLocation loc, UnaryTypeTrait utt,=20
+  UnaryTypeTraitExpr(SourceLocation loc, UnaryTypeTrait utt,
                      TypeSourceInfo *queried, bool value,
                      SourceLocation rparen, QualType ty)
     : Expr(UnaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
@@ -1546,14 +1900,14 @@
     : Expr(UnaryTypeTraitExprClass, Empty), UTT(0), Value(false),
       QueriedType() { }
=20
-  SourceRange getSourceRange() const { return SourceRange(Loc, RParen);}
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c, RParen);}
=20
   UnaryTypeTrait getTrait() const { return static_cast<UnaryTypeTrait>(UTT=
); }
=20
   QualType getQueriedType() const { return QueriedType->getType(); }
=20
   TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
- =20
+
   bool getValue() const { return Value; }
=20
   static bool classof(const Stmt *T) {
@@ -1591,10 +1945,10 @@
   TypeSourceInfo *RhsType;
=20
 public:
-  BinaryTypeTraitExpr(SourceLocation loc, BinaryTypeTrait btt,=20
-                     TypeSourceInfo *lhsType, TypeSourceInfo *rhsType,=20
+  BinaryTypeTraitExpr(SourceLocation loc, BinaryTypeTrait btt,
+                     TypeSourceInfo *lhsType, TypeSourceInfo *rhsType,
                      bool value, SourceLocation rparen, QualType ty)
-    : Expr(BinaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary, false,=20
+    : Expr(BinaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary, false,
            lhsType->getType()->isDependentType() ||
            rhsType->getType()->isDependentType(),
            (lhsType->getType()->isInstantiationDependentType() ||
@@ -1609,7 +1963,7 @@
     : Expr(BinaryTypeTraitExprClass, Empty), BTT(0), Value(false),
       LhsType(), RhsType() { }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(Loc, RParen);
   }
=20
@@ -1622,7 +1976,7 @@
=20
   TypeSourceInfo *getLhsTypeSourceInfo() const { return LhsType; }
   TypeSourceInfo *getRhsTypeSourceInfo() const { return RhsType; }
- =20
+
   bool getValue() const { assert(!isTypeDependent()); return Value; }
=20
   static bool classof(const Stmt *T) {
@@ -1636,12 +1990,110 @@
   friend class ASTStmtReader;
 };
=20
+/// \brief A type trait used in the implementation of various C++11 and
+/// Library TR1 trait templates.
+///
+/// \code
+///   __is_trivially_constructible(vector<int>, int*, int*)
+/// \endcode
+class TypeTraitExpr : public Expr {
+  /// \brief The location of the type trait keyword.
+  SourceLocation Loc;
+ =20
+  /// \brief  The location of the closing parenthesis.
+  SourceLocation RParenLoc;
+ =20
+  // Note: The TypeSourceInfos for the arguments are allocated after the
+  // TypeTraitExpr.
+ =20
+  TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
+                ArrayRef<TypeSourceInfo *> Args,
+                SourceLocation RParenLoc,
+                bool Value);
+
+  TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) { }
+
+  /// \brief Retrieve the argument types.
+  TypeSourceInfo **getTypeSourceInfos() {
+    return reinterpret_cast<TypeSourceInfo **>(this+1);
+  }
+ =20
+  /// \brief Retrieve the argument types.
+  TypeSourceInfo * const *getTypeSourceInfos() const {
+    return reinterpret_cast<TypeSourceInfo * const*>(this+1);
+  }
+ =20
+public:
+  /// \brief Create a new type trait expression.
+  static TypeTraitExpr *Create(ASTContext &C, QualType T, SourceLocation L=
oc,=20
+                               TypeTrait Kind,
+                               ArrayRef<TypeSourceInfo *> Args,
+                               SourceLocation RParenLoc,
+                               bool Value);
+
+  static TypeTraitExpr *CreateDeserialized(ASTContext &C, unsigned NumArgs=
);
+ =20
+  /// \brief Determine which type trait this expression uses.
+  TypeTrait getTrait() const {
+    return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
+  }
+
+  bool getValue() const {=20
+    assert(!isValueDependent());=20
+    return TypeTraitExprBits.Value;=20
+  }
+ =20
+  /// \brief Determine the number of arguments to this type trait.
+  unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
+ =20
+  /// \brief Retrieve the Ith argument.
+  TypeSourceInfo *getArg(unsigned I) const {
+    assert(I < getNumArgs() && "Argument out-of-range");
+    return getArgs()[I];
+  }
+ =20
+  /// \brief Retrieve the argument types.
+  ArrayRef<TypeSourceInfo *> getArgs() const {=20
+    return ArrayRef<TypeSourceInfo *>(getTypeSourceInfos(), getNumArgs());
+  }
+ =20
+  typedef TypeSourceInfo **arg_iterator;
+  arg_iterator arg_begin() {=20
+    return getTypeSourceInfos();=20
+  }
+  arg_iterator arg_end() {=20
+    return getTypeSourceInfos() + getNumArgs();=20
+  }
+
+  typedef TypeSourceInfo const * const *arg_const_iterator;
+  arg_const_iterator arg_begin() const { return getTypeSourceInfos(); }
+  arg_const_iterator arg_end() const {=20
+    return getTypeSourceInfos() + getNumArgs();=20
+  }
+
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c, RParenLoc); }
+ =20
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() =3D=3D TypeTraitExprClass;
+  }
+  static bool classof(const TypeTraitExpr *) { return true; }
+ =20
+  // Iterators
+  child_range children() { return child_range(); }
+ =20
+  friend class ASTStmtReader;
+  friend class ASTStmtWriter;
+
+};
+ =20
 /// ArrayTypeTraitExpr - An Embarcadero array type trait, as used in the
 /// implementation of __array_rank and __array_extent.
 /// Example:
 /// __array_rank(int[10][20]) =3D=3D 2
 /// __array_extent(int, 1)    =3D=3D 20
 class ArrayTypeTraitExpr : public Expr {
+  virtual void anchor();
+
   /// ATT - The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
   unsigned ATT : 2;
=20
@@ -1679,7 +2131,9 @@
=20
   virtual ~ArrayTypeTraitExpr() { }
=20
-  virtual SourceRange getSourceRange() const { return SourceRange(Loc, RPa=
ren); }
+  virtual SourceRange getSourceRange() const LLVM_READONLY {
+    return SourceRange(Loc, RParen);
+  }
=20
   ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT=
); }
=20
@@ -1720,7 +2174,7 @@
=20
   Expr* QueriedExpression;
 public:
-  ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,=20
+  ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
                      Expr *queried, bool value,
                      SourceLocation rparen, QualType resultType)
     : Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
@@ -1729,13 +2183,14 @@
            queried->isTypeDependent(),
            queried->isInstantiationDependent(),
            queried->containsUnexpandedParameterPack()),
-      ET(et), Value(value), Loc(loc), RParen(rparen), QueriedExpression(qu=
eried) { }
+      ET(et), Value(value), Loc(loc), RParen(rparen),
+      QueriedExpression(queried) { }
=20
   explicit ExpressionTraitExpr(EmptyShell Empty)
     : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false),
       QueriedExpression() { }
=20
-  SourceRange getSourceRange() const { return SourceRange(Loc, RParen);}
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c, RParen);}
=20
   ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(E=
T); }
=20
@@ -1758,6 +2213,12 @@
 /// \brief A reference to an overloaded function set, either an
 /// \t UnresolvedLookupExpr or an \t UnresolvedMemberExpr.
 class OverloadExpr : public Expr {
+  /// The common name of these declarations.
+  DeclarationNameInfo NameInfo;
+
+  /// \brief The nested-name-specifier that qualifies the name, if any.
+  NestedNameSpecifierLoc QualifierLoc;
+
   /// The results.  These are undesugared, which is to say, they may
   /// include UsingShadowDecls.  Access is relative to the naming
   /// class.
@@ -1765,18 +2226,22 @@
   DeclAccessPair *Results;
   unsigned NumResults;
=20
-  /// The common name of these declarations.
-  DeclarationNameInfo NameInfo;
-
-  /// \brief The nested-name-specifier that qualifies the name, if any.
-  NestedNameSpecifierLoc QualifierLoc;
-
 protected:
-  /// True if the name was a template-id.
-  bool HasExplicitTemplateArgs;
+  /// \brief Whether the name includes info for explicit template
+  /// keyword and arguments.
+  bool HasTemplateKWAndArgsInfo;
+
+  /// \brief Return the optional template keyword and arguments info.
+  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo(); // defined far bel=
ow.
+
+  /// \brief Return the optional template keyword and arguments info.
+  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
+    return const_cast<OverloadExpr*>(this)->getTemplateKWAndArgsInfo();
+  }
=20
   OverloadExpr(StmtClass K, ASTContext &C,
                NestedNameSpecifierLoc QualifierLoc,
+               SourceLocation TemplateKWLoc,
                const DeclarationNameInfo &NameInfo,
                const TemplateArgumentListInfo *TemplateArgs,
                UnresolvedSetIterator Begin, UnresolvedSetIterator End,
@@ -1785,8 +2250,8 @@
                bool KnownContainsUnexpandedParameterPack);
=20
   OverloadExpr(StmtClass K, EmptyShell Empty)
-    : Expr(K, Empty), Results(0), NumResults(0),
-      QualifierLoc(), HasExplicitTemplateArgs(false) { }
+    : Expr(K, Empty), QualifierLoc(), Results(0), NumResults(0),
+      HasTemplateKWAndArgsInfo(false) { }
=20
   void initializeResults(ASTContext &C,
                          UnresolvedSetIterator Begin,
@@ -1832,10 +2297,10 @@
=20
   typedef UnresolvedSetImpl::iterator decls_iterator;
   decls_iterator decls_begin() const { return UnresolvedSetIterator(Result=
s); }
-  decls_iterator decls_end() const {=20
+  decls_iterator decls_end() const {
     return UnresolvedSetIterator(Results + NumResults);
   }
- =20
+
   /// Gets the number of declarations in the unresolved set.
   unsigned getNumDecls() const { return NumResults; }
=20
@@ -1849,24 +2314,67 @@
   SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
=20
   /// Fetches the nested-name qualifier, if one was given.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
=20
-  /// Fetches the nested-name qualifier with source-location information, =
if=20
+  /// Fetches the nested-name qualifier with source-location information, =
if
   /// one was given.
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
=20
-  /// \brief Determines whether this expression had an explicit
-  /// template argument list, e.g. f<int>.
-  bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
-
-  ASTTemplateArgumentListInfo &getExplicitTemplateArgs(); // defined far b=
elow
+  /// \brief Retrieve the location of the template keyword preceding
+  /// this name, if any.
+  SourceLocation getTemplateKeywordLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
+  }
+
+  /// \brief Retrieve the location of the left angle bracket starting the
+  /// explicit template argument list following the name, if any.
+  SourceLocation getLAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->LAngleLoc;
+  }
+
+  /// \brief Retrieve the location of the right angle bracket ending the
+  /// explicit template argument list following the name, if any.
+  SourceLocation getRAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->RAngleLoc;
+  }
+
+  /// Determines whether the name was preceded by the template keyword.
+  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid=
(); }
+
+  /// Determines whether this expression had explicit template arguments.
+  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
+
+  // Note that, inconsistently with the explicit-template-argument AST
+  // nodes, users are *forbidden* from calling these methods on objects
+  // without explicit template arguments.
+
+  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
+    assert(hasExplicitTemplateArgs());
+    return *getTemplateKWAndArgsInfo();
+  }
=20
   const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
     return const_cast<OverloadExpr*>(this)->getExplicitTemplateArgs();
   }
=20
+  TemplateArgumentLoc const *getTemplateArgs() const {
+    return getExplicitTemplateArgs().getTemplateArgs();
+  }
+
+  unsigned getNumTemplateArgs() const {
+    return getExplicitTemplateArgs().NumTemplateArgs;
+  }
+
+  /// Copies the template arguments into the given structure.
+  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
+    getExplicitTemplateArgs().copyInto(List);
+  }
+
   /// \brief Retrieves the optional explicit template arguments.
   /// This points to the same data as getExplicitTemplateArgs(), but
   /// returns null if there are no explicit template arguments.
@@ -1916,16 +2424,17 @@
   /// against the qualified-lookup bits.
   CXXRecordDecl *NamingClass;
=20
-  UnresolvedLookupExpr(ASTContext &C,=20
+  UnresolvedLookupExpr(ASTContext &C,
                        CXXRecordDecl *NamingClass,
                        NestedNameSpecifierLoc QualifierLoc,
+                       SourceLocation TemplateKWLoc,
                        const DeclarationNameInfo &NameInfo,
-                       bool RequiresADL, bool Overloaded,=20
+                       bool RequiresADL, bool Overloaded,
                        const TemplateArgumentListInfo *TemplateArgs,
                        UnresolvedSetIterator Begin, UnresolvedSetIterator =
End,
                        bool StdIsAssociatedNamespace)
-    : OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, NameInfo,=20
-                   TemplateArgs, Begin, End, false, false, false),
+    : OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, TemplateKWL=
oc,
+                   NameInfo, TemplateArgs, Begin, End, false, false, false=
),
       RequiresADL(RequiresADL),
       StdIsAssociatedNamespace(StdIsAssociatedNamespace),
       Overloaded(Overloaded), NamingClass(NamingClass)
@@ -1938,19 +2447,20 @@
   {}
=20
   friend class ASTStmtReader;
- =20
+
 public:
   static UnresolvedLookupExpr *Create(ASTContext &C,
                                       CXXRecordDecl *NamingClass,
                                       NestedNameSpecifierLoc QualifierLoc,
                                       const DeclarationNameInfo &NameInfo,
                                       bool ADL, bool Overloaded,
-                                      UnresolvedSetIterator Begin,=20
+                                      UnresolvedSetIterator Begin,
                                       UnresolvedSetIterator End,
                                       bool StdIsAssociatedNamespace =3D fa=
lse) {
     assert((ADL || !StdIsAssociatedNamespace) &&
            "std considered associated namespace when not performing ADL");
-    return new(C) UnresolvedLookupExpr(C, NamingClass, QualifierLoc, NameI=
nfo,=20
+    return new(C) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
+                                       SourceLocation(), NameInfo,
                                        ADL, Overloaded, 0, Begin, End,
                                        StdIsAssociatedNamespace);
   }
@@ -1958,14 +2468,15 @@
   static UnresolvedLookupExpr *Create(ASTContext &C,
                                       CXXRecordDecl *NamingClass,
                                       NestedNameSpecifierLoc QualifierLoc,
+                                      SourceLocation TemplateKWLoc,
                                       const DeclarationNameInfo &NameInfo,
                                       bool ADL,
-                                      const TemplateArgumentListInfo &Args,
-                                      UnresolvedSetIterator Begin,=20
+                                      const TemplateArgumentListInfo *Args,
+                                      UnresolvedSetIterator Begin,
                                       UnresolvedSetIterator End);
=20
   static UnresolvedLookupExpr *CreateEmpty(ASTContext &C,
-                                           bool HasExplicitTemplateArgs,
+                                           bool HasTemplateKWAndArgsInfo,
                                            unsigned NumTemplateArgs);
=20
   /// True if this declaration should be extended by
@@ -1984,56 +2495,11 @@
   /// that was looked in to find these results.
   CXXRecordDecl *getNamingClass() const { return NamingClass; }
=20
-  // Note that, inconsistently with the explicit-template-argument AST
-  // nodes, users are *forbidden* from calling these methods on objects
-  // without explicit template arguments.
-
-  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
-    assert(hasExplicitTemplateArgs());
-    return *reinterpret_cast<ASTTemplateArgumentListInfo*>(this + 1);
-  }
-
-  /// Gets a reference to the explicit template argument list.
-  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
-    assert(hasExplicitTemplateArgs());
-    return *reinterpret_cast<const ASTTemplateArgumentListInfo*>(this + 1);
-  }
-
-  /// \brief Retrieves the optional explicit template arguments.
-  /// This points to the same data as getExplicitTemplateArgs(), but
-  /// returns null if there are no explicit template arguments.
-  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() {
-    if (!hasExplicitTemplateArgs()) return 0;
-    return &getExplicitTemplateArgs();
-  }
-
-  /// \brief Copies the template arguments (if present) into the given
-  /// structure.
-  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
-    getExplicitTemplateArgs().copyInto(List);
-  }
- =20
-  SourceLocation getLAngleLoc() const {
-    return getExplicitTemplateArgs().LAngleLoc;
-  }
-
-  SourceLocation getRAngleLoc() const {
-    return getExplicitTemplateArgs().RAngleLoc;
-  }
-
-  TemplateArgumentLoc const *getTemplateArgs() const {
-    return getExplicitTemplateArgs().getTemplateArgs();
-  }
-
-  unsigned getNumTemplateArgs() const {
-    return getExplicitTemplateArgs().NumTemplateArgs;
-  }
-
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     SourceRange Range(getNameInfo().getSourceRange());
-    if (getQualifierLoc())=20
+    if (getQualifierLoc())
       Range.setBegin(getQualifierLoc().getBeginLoc());
-    if (hasExplicitTemplateArgs())=20
+    if (hasExplicitTemplateArgs())
       Range.setEnd(getRAngleLoc());
     return Range;
   }
@@ -2064,26 +2530,40 @@
   /// \brief The nested-name-specifier that qualifies this unresolved
   /// declaration name.
   NestedNameSpecifierLoc QualifierLoc;
- =20
+
   /// The name of the entity we will be referencing.
   DeclarationNameInfo NameInfo;
=20
-  /// \brief Whether the name includes explicit template arguments.
-  bool HasExplicitTemplateArgs;
+  /// \brief Whether the name includes info for explicit template
+  /// keyword and arguments.
+  bool HasTemplateKWAndArgsInfo;
+
+  /// \brief Return the optional template keyword and arguments info.
+  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
+    if (!HasTemplateKWAndArgsInfo) return 0;
+    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
+  }
+  /// \brief Return the optional template keyword and arguments info.
+  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
+    return const_cast<DependentScopeDeclRefExpr*>(this)
+      ->getTemplateKWAndArgsInfo();
+  }
=20
   DependentScopeDeclRefExpr(QualType T,
                             NestedNameSpecifierLoc QualifierLoc,
+                            SourceLocation TemplateKWLoc,
                             const DeclarationNameInfo &NameInfo,
                             const TemplateArgumentListInfo *Args);
=20
 public:
   static DependentScopeDeclRefExpr *Create(ASTContext &C,
                                            NestedNameSpecifierLoc Qualifie=
rLoc,
+                                           SourceLocation TemplateKWLoc,
                                            const DeclarationNameInfo &Name=
Info,
-                              const TemplateArgumentListInfo *TemplateArgs=
 =3D 0);
+                              const TemplateArgumentListInfo *TemplateArgs=
);
=20
   static DependentScopeDeclRefExpr *CreateEmpty(ASTContext &C,
-                                                bool HasExplicitTemplateAr=
gs,
+                                                bool HasTemplateKWAndArgsI=
nfo,
                                                 unsigned NumTemplateArgs);
=20
   /// \brief Retrieve the name that this expression refers to.
@@ -2098,16 +2578,40 @@
   /// \brief Retrieve the nested-name-specifier that qualifies the
   /// name, with source location information.
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
- =20
- =20
+
+
   /// \brief Retrieve the nested-name-specifier that qualifies this
   /// declaration.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
=20
+  /// \brief Retrieve the location of the template keyword preceding
+  /// this name, if any.
+  SourceLocation getTemplateKeywordLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
+  }
+
+  /// \brief Retrieve the location of the left angle bracket starting the
+  /// explicit template argument list following the name, if any.
+  SourceLocation getLAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->LAngleLoc;
+  }
+
+  /// \brief Retrieve the location of the right angle bracket ending the
+  /// explicit template argument list following the name, if any.
+  SourceLocation getRAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->RAngleLoc;
+  }
+
+  /// Determines whether the name was preceded by the template keyword.
+  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid=
(); }
+
   /// Determines whether this lookup had explicit template arguments.
-  bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
+  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
=20
   // Note that, inconsistently with the explicit-template-argument AST
   // nodes, users are *forbidden* from calling these methods on objects
@@ -2137,14 +2641,6 @@
   void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
     getExplicitTemplateArgs().copyInto(List);
   }
- =20
-  SourceLocation getLAngleLoc() const {
-    return getExplicitTemplateArgs().LAngleLoc;
-  }
-
-  SourceLocation getRAngleLoc() const {
-    return getExplicitTemplateArgs().RAngleLoc;
-  }
=20
   TemplateArgumentLoc const *getTemplateArgs() const {
     return getExplicitTemplateArgs().getTemplateArgs();
@@ -2154,7 +2650,7 @@
     return getExplicitTemplateArgs().NumTemplateArgs;
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     SourceRange Range(QualifierLoc.getBeginLoc(), getLocation());
     if (hasExplicitTemplateArgs())
       Range.setEnd(getRAngleLoc());
@@ -2175,46 +2671,61 @@
 /// Represents an expression --- generally a full-expression --- which
 /// introduces cleanups to be run at the end of the sub-expression's
 /// evaluation.  The most common source of expression-introduced
-/// cleanups is temporary objects in C++, but several other C++
-/// expressions can create cleanups.
+/// cleanups is temporary objects in C++, but several other kinds of
+/// expressions can create cleanups, including basically every
+/// call in ARC that returns an Objective-C pointer.
+///
+/// This expression also tracks whether the sub-expression contains a
+/// potentially-evaluated block literal.  The lifetime of a block
+/// literal is the extent of the enclosing scope.
 class ExprWithCleanups : public Expr {
+public:
+  /// The type of objects that are kept in the cleanup.
+  /// It's useful to remember the set of blocks;  we could also
+  /// remember the set of temporaries, but there's currently
+  /// no need.
+  typedef BlockDecl *CleanupObject;
+
+private:
   Stmt *SubExpr;
=20
-  CXXTemporary **Temps;
-  unsigned NumTemps;
-
-  ExprWithCleanups(ASTContext &C, Expr *SubExpr,
-                   CXXTemporary **Temps, unsigned NumTemps);
- =20
+  ExprWithCleanups(EmptyShell, unsigned NumObjects);
+  ExprWithCleanups(Expr *SubExpr, ArrayRef<CleanupObject> Objects);
+
+  CleanupObject *getObjectsBuffer() {
+    return reinterpret_cast<CleanupObject*>(this + 1);
+  }
+  const CleanupObject *getObjectsBuffer() const {
+    return reinterpret_cast<const CleanupObject*>(this + 1);
+  }
+  friend class ASTStmtReader;
+
 public:
-  ExprWithCleanups(EmptyShell Empty)
-    : Expr(ExprWithCleanupsClass, Empty),
-      SubExpr(0), Temps(0), NumTemps(0) {}
-                        =20
-  static ExprWithCleanups *Create(ASTContext &C, Expr *SubExpr,
-                                        CXXTemporary **Temps,=20
-                                        unsigned NumTemps);
-
-  unsigned getNumTemporaries() const { return NumTemps; }
-  void setNumTemporaries(ASTContext &C, unsigned N);
-   =20
-  CXXTemporary *getTemporary(unsigned i) {
-    assert(i < NumTemps && "Index out of range");
-    return Temps[i];
+  static ExprWithCleanups *Create(ASTContext &C, EmptyShell empty,
+                                  unsigned numObjects);
+
+  static ExprWithCleanups *Create(ASTContext &C, Expr *subexpr,
+                                  ArrayRef<CleanupObject> objects);
+
+  ArrayRef<CleanupObject> getObjects() const {
+    return ArrayRef<CleanupObject>(getObjectsBuffer(), getNumObjects());
   }
-  const CXXTemporary *getTemporary(unsigned i) const {
-    return const_cast<ExprWithCleanups*>(this)->getTemporary(i);
-  }
-  void setTemporary(unsigned i, CXXTemporary *T) {
-    assert(i < NumTemps && "Index out of range");
-    Temps[i] =3D T;
+
+  unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects;=
 }
+
+  CleanupObject getObject(unsigned i) const {
+    assert(i < getNumObjects() && "Index out of range");
+    return getObjects()[i];
   }
=20
   Expr *getSubExpr() { return cast<Expr>(SubExpr); }
   const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
+
+  /// setSubExpr - As with any mutator of the AST, be very careful
+  /// when modifying an existing AST to preserve its invariants.
   void setSubExpr(Expr *E) { SubExpr =3D E; }
=20
-  SourceRange getSourceRange() const {=20
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SubExpr->getSourceRange();
   }
=20
@@ -2252,7 +2763,7 @@
 class CXXUnresolvedConstructExpr : public Expr {
   /// \brief The type being constructed.
   TypeSourceInfo *Type;
- =20
+
   /// \brief The location of the left parentheses ('(').
   SourceLocation LParenLoc;
=20
@@ -2272,7 +2783,7 @@
     : Expr(CXXUnresolvedConstructExprClass, Empty), Type(), NumArgs(NumArg=
s) { }
=20
   friend class ASTStmtReader;
- =20
+
 public:
   static CXXUnresolvedConstructExpr *Create(ASTContext &C,
                                             TypeSourceInfo *Type,
@@ -2288,10 +2799,10 @@
   /// in the source code.
   QualType getTypeAsWritten() const { return Type->getType(); }
=20
-  /// \brief Retrieve the type source information for the type being=20
+  /// \brief Retrieve the type source information for the type being
   /// constructed.
   TypeSourceInfo *getTypeSourceInfo() const { return Type; }
- =20
+
   /// \brief Retrieve the location of the left parentheses ('(') that
   /// precedes the argument list.
   SourceLocation getLParenLoc() const { return LParenLoc; }
@@ -2332,8 +2843,8 @@
     *(arg_begin() + I) =3D E;
   }
=20
-  SourceRange getSourceRange() const;
- =20
+  SourceRange getSourceRange() const LLVM_READONLY;
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CXXUnresolvedConstructExprClass;
   }
@@ -2366,9 +2877,9 @@
   /// the '.' operator.
   bool IsArrow : 1;
=20
-  /// \brief Whether this member expression has explicitly-specified templ=
ate
-  /// arguments.
-  bool HasExplicitTemplateArgs : 1;
+  /// \brief Whether this member expression has info for explicit template
+  /// keyword and arguments.
+  bool HasTemplateKWAndArgsInfo : 1;
=20
   /// \brief The location of the '->' or '.' operator.
   SourceLocation OperatorLoc;
@@ -2390,10 +2901,22 @@
   /// FIXME: could also be a template-id
   DeclarationNameInfo MemberNameInfo;
=20
+  /// \brief Return the optional template keyword and arguments info.
+  ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
+    if (!HasTemplateKWAndArgsInfo) return 0;
+    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
+  }
+  /// \brief Return the optional template keyword and arguments info.
+  const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
+    return const_cast<CXXDependentScopeMemberExpr*>(this)
+      ->getTemplateKWAndArgsInfo();
+  }
+
   CXXDependentScopeMemberExpr(ASTContext &C,
                           Expr *Base, QualType BaseType, bool IsArrow,
                           SourceLocation OperatorLoc,
                           NestedNameSpecifierLoc QualifierLoc,
+                          SourceLocation TemplateKWLoc,
                           NamedDecl *FirstQualifierFoundInScope,
                           DeclarationNameInfo MemberNameInfo,
                           const TemplateArgumentListInfo *TemplateArgs);
@@ -2412,12 +2935,13 @@
          Expr *Base, QualType BaseType, bool IsArrow,
          SourceLocation OperatorLoc,
          NestedNameSpecifierLoc QualifierLoc,
+         SourceLocation TemplateKWLoc,
          NamedDecl *FirstQualifierFoundInScope,
          DeclarationNameInfo MemberNameInfo,
          const TemplateArgumentListInfo *TemplateArgs);
=20
   static CXXDependentScopeMemberExpr *
-  CreateEmpty(ASTContext &C, bool HasExplicitTemplateArgs,=20
+  CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
               unsigned NumTemplateArgs);
=20
   /// \brief True if this is an implicit access, i.e. one in which the
@@ -2443,15 +2967,15 @@
=20
   /// \brief Retrieve the nested-name-specifier that qualifies the member
   /// name.
-  NestedNameSpecifier *getQualifier() const {=20
-    return QualifierLoc.getNestedNameSpecifier();=20
+  NestedNameSpecifier *getQualifier() const {
+    return QualifierLoc.getNestedNameSpecifier();
   }
=20
   /// \brief Retrieve the nested-name-specifier that qualifies the member
   /// name, with source location information.
   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
- =20
- =20
+
+
   /// \brief Retrieve the first part of the nested-name-specifier that was
   /// found in the scope of the member access expression when the member a=
ccess
   /// was initially parsed.
@@ -2481,16 +3005,38 @@
   // expression refers to.
   SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
=20
+  /// \brief Retrieve the location of the template keyword preceding the
+  /// member name, if any.
+  SourceLocation getTemplateKeywordLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
+  }
+
+  /// \brief Retrieve the location of the left angle bracket starting the
+  /// explicit template argument list following the member name, if any.
+  SourceLocation getLAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->LAngleLoc;
+  }
+
+  /// \brief Retrieve the location of the right angle bracket ending the
+  /// explicit template argument list following the member name, if any.
+  SourceLocation getRAngleLoc() const {
+    if (!HasTemplateKWAndArgsInfo) return SourceLocation();
+    return getTemplateKWAndArgsInfo()->RAngleLoc;
+  }
+
+  /// Determines whether the member name was preceded by the template keyw=
ord.
+  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid=
(); }
+
   /// \brief Determines whether this member expression actually had a C++
   /// template argument list explicitly specified, e.g., x.f<int>.
-  bool hasExplicitTemplateArgs() const {
-    return HasExplicitTemplateArgs;
-  }
+  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
=20
   /// \brief Retrieve the explicit template argument list that followed the
   /// member template name, if any.
   ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
-    assert(HasExplicitTemplateArgs);
+    assert(hasExplicitTemplateArgs());
     return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
   }
=20
@@ -2520,12 +3066,6 @@
     getExplicitTemplateArgs().initializeFrom(List);
   }
=20
-  /// \brief Retrieve the location of the left angle bracket following the
-  /// member name ('<'), if any.
-  SourceLocation getLAngleLoc() const {
-    return getExplicitTemplateArgs().LAngleLoc;
-  }
-
   /// \brief Retrieve the template arguments provided as part of this
   /// template-id.
   const TemplateArgumentLoc *getTemplateArgs() const {
@@ -2538,13 +3078,7 @@
     return getExplicitTemplateArgs().NumTemplateArgs;
   }
=20
-  /// \brief Retrieve the location of the right angle bracket following the
-  /// template arguments ('>').
-  SourceLocation getRAngleLoc() const {
-    return getExplicitTemplateArgs().RAngleLoc;
-  }
-
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     SourceRange Range;
     if (!isImplicitAccess())
       Range.setBegin(Base->getSourceRange().getBegin());
@@ -2612,28 +3146,30 @@
                        Expr *Base, QualType BaseType, bool IsArrow,
                        SourceLocation OperatorLoc,
                        NestedNameSpecifierLoc QualifierLoc,
+                       SourceLocation TemplateKWLoc,
                        const DeclarationNameInfo &MemberNameInfo,
                        const TemplateArgumentListInfo *TemplateArgs,
                        UnresolvedSetIterator Begin, UnresolvedSetIterator =
End);
- =20
+
   UnresolvedMemberExpr(EmptyShell Empty)
     : OverloadExpr(UnresolvedMemberExprClass, Empty), IsArrow(false),
       HasUnresolvedUsing(false), Base(0) { }
=20
   friend class ASTStmtReader;
- =20
+
 public:
   static UnresolvedMemberExpr *
   Create(ASTContext &C, bool HasUnresolvedUsing,
          Expr *Base, QualType BaseType, bool IsArrow,
          SourceLocation OperatorLoc,
          NestedNameSpecifierLoc QualifierLoc,
+         SourceLocation TemplateKWLoc,
          const DeclarationNameInfo &MemberNameInfo,
          const TemplateArgumentListInfo *TemplateArgs,
          UnresolvedSetIterator Begin, UnresolvedSetIterator End);
=20
   static UnresolvedMemberExpr *
-  CreateEmpty(ASTContext &C, bool HasExplicitTemplateArgs,
+  CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
               unsigned NumTemplateArgs);
=20
   /// \brief True if this is an implicit access, i.e. one in which the
@@ -2680,58 +3216,7 @@
   // expression refers to.
   SourceLocation getMemberLoc() const { return getNameLoc(); }
=20
-  /// \brief Retrieve the explicit template argument list that followed the
-  /// member template name.
-  ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
-    assert(hasExplicitTemplateArgs());
-    return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
-  }
-
-  /// \brief Retrieve the explicit template argument list that followed the
-  /// member template name, if any.
-  const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
-    assert(hasExplicitTemplateArgs());
-    return *reinterpret_cast<const ASTTemplateArgumentListInfo *>(this + 1=
);
-  }
-
-  /// \brief Retrieves the optional explicit template arguments.
-  /// This points to the same data as getExplicitTemplateArgs(), but
-  /// returns null if there are no explicit template arguments.
-  const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() {
-    if (!hasExplicitTemplateArgs()) return 0;
-    return &getExplicitTemplateArgs();
-  }
-
-  /// \brief Copies the template arguments into the given structure.
-  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
-    getExplicitTemplateArgs().copyInto(List);
-  }
-
-  /// \brief Retrieve the location of the left angle bracket following
-  /// the member name ('<').
-  SourceLocation getLAngleLoc() const {
-    return getExplicitTemplateArgs().LAngleLoc;
-  }
-
-  /// \brief Retrieve the template arguments provided as part of this
-  /// template-id.
-  const TemplateArgumentLoc *getTemplateArgs() const {
-    return getExplicitTemplateArgs().getTemplateArgs();
-  }
-
-  /// \brief Retrieve the number of template arguments provided as
-  /// part of this template-id.
-  unsigned getNumTemplateArgs() const {
-    return getExplicitTemplateArgs().NumTemplateArgs;
-  }
-
-  /// \brief Retrieve the location of the right angle bracket
-  /// following the template arguments ('>').
-  SourceLocation getRAngleLoc() const {
-    return getExplicitTemplateArgs().RAngleLoc;
-  }
-
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     SourceRange Range =3D getMemberNameInfo().getSourceRange();
     if (!isImplicitAccess())
       Range.setBegin(Base->getSourceRange().getBegin());
@@ -2783,7 +3268,7 @@
=20
   Expr *getOperand() const { return static_cast<Expr*>(Operand); }
=20
-  SourceRange getSourceRange() const { return Range; }
+  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
=20
   bool getValue() const { return Value; }
=20
@@ -2796,7 +3281,7 @@
   child_range children() { return child_range(&Operand, &Operand + 1); }
 };
=20
-/// \brief Represents a C++0x pack expansion that produces a sequence of=20
+/// \brief Represents a C++0x pack expansion that produces a sequence of
 /// expressions.
 ///
 /// A pack expansion expression contains a pattern (which itself is an
@@ -2810,29 +3295,29 @@
 /// \endcode
 ///
 /// Here, the argument to the function object \c f is a pack expansion who=
se
-/// pattern is \c static_cast<Types&&>(args). When the \c forward function=20
+/// pattern is \c static_cast<Types&&>(args). When the \c forward function
 /// template is instantiated, the pack expansion will instantiate to zero =
or
 /// or more function arguments to the function object \c f.
 class PackExpansionExpr : public Expr {
   SourceLocation EllipsisLoc;
- =20
+
   /// \brief The number of expansions that will be produced by this pack
   /// expansion expression, if known.
   ///
   /// When zero, the number of expansions is not known. Otherwise, this va=
lue
   /// is the number of expansions + 1.
   unsigned NumExpansions;
- =20
+
   Stmt *Pattern;
- =20
+
   friend class ASTStmtReader;
   friend class ASTStmtWriter;
- =20
+
 public:
   PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
                     llvm::Optional<unsigned> NumExpansions)
-    : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),=20
-           Pattern->getObjectKind(), /*TypeDependent=3D*/true,=20
+    : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
+           Pattern->getObjectKind(), /*TypeDependent=3D*/true,
            /*ValueDependent=3D*/true, /*InstantiationDependent=3D*/true,
            /*ContainsUnexpandedParameterPack=3D*/false),
       EllipsisLoc(EllipsisLoc),
@@ -2840,7 +3325,7 @@
       Pattern(Pattern) { }
=20
   PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty=
) { }
- =20
+
   /// \brief Retrieve the pattern of the pack expansion.
   Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
=20
@@ -2850,17 +3335,17 @@
   /// \brief Retrieve the location of the ellipsis that describes this pack
   /// expansion.
   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
- =20
-  /// \brief Determine the number of expansions that will be produced when=20
+
+  /// \brief Determine the number of expansions that will be produced when
   /// this pack expansion is instantiated, if already known.
   llvm::Optional<unsigned> getNumExpansions() const {
     if (NumExpansions)
       return NumExpansions - 1;
-   =20
+
     return llvm::Optional<unsigned>();
   }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(Pattern->getLocStart(), EllipsisLoc);
   }
=20
@@ -2868,21 +3353,24 @@
     return T->getStmtClass() =3D=3D PackExpansionExprClass;
   }
   static bool classof(const PackExpansionExpr *) { return true; }
- =20
+
   // Iterators
   child_range children() {
     return child_range(&Pattern, &Pattern + 1);
   }
 };
- =20
-inline ASTTemplateArgumentListInfo &OverloadExpr::getExplicitTemplateArgs(=
) {
+
+inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
+  if (!HasTemplateKWAndArgsInfo) return 0;
   if (isa<UnresolvedLookupExpr>(this))
-    return cast<UnresolvedLookupExpr>(this)->getExplicitTemplateArgs();
+    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
+      (cast<UnresolvedLookupExpr>(this) + 1);
   else
-    return cast<UnresolvedMemberExpr>(this)->getExplicitTemplateArgs();
+    return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
+      (cast<UnresolvedMemberExpr>(this) + 1);
 }
=20
-/// \brief Represents an expression that computes the length of a paramete=
r=20
+/// \brief Represents an expression that computes the length of a parameter
 /// pack.
 ///
 /// \code
@@ -2894,30 +3382,30 @@
 class SizeOfPackExpr : public Expr {
   /// \brief The location of the 'sizeof' keyword.
   SourceLocation OperatorLoc;
- =20
+
   /// \brief The location of the name of the parameter pack.
   SourceLocation PackLoc;
- =20
+
   /// \brief The location of the closing parenthesis.
   SourceLocation RParenLoc;
- =20
+
   /// \brief The length of the parameter pack, if known.
   ///
   /// When this expression is value-dependent, the length of the parameter=
 pack
   /// is unknown. When this expression is not value-dependent, the length =
is
   /// known.
   unsigned Length;
- =20
+
   /// \brief The parameter pack itself.
   NamedDecl *Pack;
- =20
+
   friend class ASTStmtReader;
   friend class ASTStmtWriter;
- =20
+
 public:
   /// \brief Creates a value-dependent expression that computes the length=
 of
   /// the given parameter pack.
-  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl =
*Pack,=20
+  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl =
*Pack,
                  SourceLocation PackLoc, SourceLocation RParenLoc)
     : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
            /*TypeDependent=3D*/false, /*ValueDependent=3D*/true,
@@ -2928,7 +3416,7 @@
=20
   /// \brief Creates an expression that computes the length of
   /// the given parameter pack, which is already known.
-  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl =
*Pack,=20
+  SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl =
*Pack,
                  SourceLocation PackLoc, SourceLocation RParenLoc,
                  unsigned Length)
   : Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
@@ -2940,38 +3428,38 @@
=20
   /// \brief Create an empty expression.
   SizeOfPackExpr(EmptyShell Empty) : Expr(SizeOfPackExprClass, Empty) { }
- =20
+
   /// \brief Determine the location of the 'sizeof' keyword.
   SourceLocation getOperatorLoc() const { return OperatorLoc; }
=20
   /// \brief Determine the location of the parameter pack.
   SourceLocation getPackLoc() const { return PackLoc; }
- =20
+
   /// \brief Determine the location of the right parenthesis.
   SourceLocation getRParenLoc() const { return RParenLoc; }
- =20
+
   /// \brief Retrieve the parameter pack.
   NamedDecl *getPack() const { return Pack; }
- =20
+
   /// \brief Retrieve the length of the parameter pack.
   ///
-  /// This routine may only be invoked when the expression is not=20
+  /// This routine may only be invoked when the expression is not
   /// value-dependent.
   unsigned getPackLength() const {
-    assert(!isValueDependent() &&=20
+    assert(!isValueDependent() &&
            "Cannot get the length of a value-dependent pack size expressio=
n");
     return Length;
   }
- =20
-  SourceRange getSourceRange() const {
+
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(OperatorLoc, RParenLoc);
   }
- =20
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D SizeOfPackExprClass;
   }
   static bool classof(const SizeOfPackExpr *) { return true; }
- =20
+
   // Iterators
   child_range children() { return child_range(); }
 };
@@ -2990,11 +3478,11 @@
=20
   friend class ASTReader;
   friend class ASTStmtReader;
-  explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)=20
+  explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
     : Expr(SubstNonTypeTemplateParmExprClass, Empty) { }
=20
 public:
-  SubstNonTypeTemplateParmExpr(QualType type,=20
+  SubstNonTypeTemplateParmExpr(QualType type,
                                ExprValueKind valueKind,
                                SourceLocation loc,
                                NonTypeTemplateParmDecl *param,
@@ -3006,19 +3494,19 @@
       Param(param), Replacement(replacement), NameLoc(loc) {}
=20
   SourceLocation getNameLoc() const { return NameLoc; }
-  SourceRange getSourceRange() const { return NameLoc; }
+  SourceRange getSourceRange() const LLVM_READONLY { return NameLoc; }
=20
   Expr *getReplacement() const { return cast<Expr>(Replacement); }
-   =20
+
   NonTypeTemplateParmDecl *getParameter() const { return Param; }
=20
   static bool classof(const Stmt *s) {
     return s->getStmtClass() =3D=3D SubstNonTypeTemplateParmExprClass;
   }
-  static bool classof(const SubstNonTypeTemplateParmExpr *) {=20
-    return true;=20
+  static bool classof(const SubstNonTypeTemplateParmExpr *) {
+    return true;
   }
- =20
+
   // Iterators
   child_range children() { return child_range(&Replacement, &Replacement+1=
); }
 };
@@ -3028,7 +3516,7 @@
 ///
 /// When a pack expansion in the source code contains multiple parameter p=
acks
 /// and those parameter packs correspond to different levels of template
-/// parameter lists, this node node is used to represent a non-type templa=
te=20
+/// parameter lists, this node node is used to represent a non-type templa=
te
 /// parameter pack from an outer level, which has already had its argument=
 pack
 /// substituted but that still lives within a pack expansion that itself
 /// could not be instantiated. When actually performing a substitution into
@@ -3038,47 +3526,47 @@
 class SubstNonTypeTemplateParmPackExpr : public Expr {
   /// \brief The non-type template parameter pack itself.
   NonTypeTemplateParmDecl *Param;
- =20
+
   /// \brief A pointer to the set of template arguments that this
   /// parameter pack is instantiated with.
   const TemplateArgument *Arguments;
- =20
+
   /// \brief The number of template arguments in \c Arguments.
   unsigned NumArguments;
- =20
+
   /// \brief The location of the non-type template parameter pack referenc=
e.
   SourceLocation NameLoc;
- =20
+
   friend class ASTReader;
   friend class ASTStmtReader;
-  explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)=20
+  explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
     : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) { }
- =20
+
 public:
-  SubstNonTypeTemplateParmPackExpr(QualType T,=20
+  SubstNonTypeTemplateParmPackExpr(QualType T,
                                    NonTypeTemplateParmDecl *Param,
                                    SourceLocation NameLoc,
                                    const TemplateArgument &ArgPack);
- =20
+
   /// \brief Retrieve the non-type template parameter pack being substitut=
ed.
   NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
=20
   /// \brief Retrieve the location of the parameter pack name.
   SourceLocation getParameterPackLocation() const { return NameLoc; }
- =20
+
   /// \brief Retrieve the template argument pack containing the substituted
   /// template arguments.
   TemplateArgument getArgumentPack() const;
=20
-  SourceRange getSourceRange() const { return NameLoc; }
- =20
+  SourceRange getSourceRange() const LLVM_READONLY { return NameLoc; }
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D SubstNonTypeTemplateParmPackExprClass;
   }
-  static bool classof(const SubstNonTypeTemplateParmPackExpr *) {=20
-    return true;=20
+  static bool classof(const SubstNonTypeTemplateParmPackExpr *) {
+    return true;
   }
- =20
+
   // Iterators
   child_range children() { return child_range(); }
 };
@@ -3102,13 +3590,13 @@
 class MaterializeTemporaryExpr : public Expr {
   /// \brief The temporary-generating expression whose value will be
   /// materialized.
- Stmt *Temporary;
- =20
+  Stmt *Temporary;
+
   friend class ASTStmtReader;
   friend class ASTStmtWriter;
- =20
+
 public:
-  MaterializeTemporaryExpr(QualType T, Expr *Temporary,=20
+  MaterializeTemporaryExpr(QualType T, Expr *Temporary,
                            bool BoundToLvalueReference)
     : Expr(MaterializeTemporaryExprClass, T,
            BoundToLvalueReference? VK_LValue : VK_XValue, OK_Ordinary,
@@ -3116,33 +3604,35 @@
            Temporary->isInstantiationDependent(),
            Temporary->containsUnexpandedParameterPack()),
       Temporary(Temporary) { }
- =20
-  MaterializeTemporaryExpr(EmptyShell Empty)=20
+
+  MaterializeTemporaryExpr(EmptyShell Empty)
     : Expr(MaterializeTemporaryExprClass, Empty) { }
- =20
+
   /// \brief Retrieve the temporary-generating subexpression whose value w=
ill
   /// be materialized into a glvalue.
   Expr *GetTemporaryExpr() const { return reinterpret_cast<Expr *>(Tempora=
ry); }
- =20
+
   /// \brief Determine whether this materialized temporary is bound to an
   /// lvalue reference; otherwise, it's bound to an rvalue reference.
-  bool isBoundToLvalueReference() const {=20
+  bool isBoundToLvalueReference() const {
     return getValueKind() =3D=3D VK_LValue;
   }
- =20
-  SourceRange getSourceRange() const { return Temporary->getSourceRange();=
 }
- =20
+
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return Temporary->getSourceRange();
+  }
+
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D MaterializeTemporaryExprClass;
   }
-  static bool classof(const MaterializeTemporaryExpr *) {=20
-    return true;=20
+  static bool classof(const MaterializeTemporaryExpr *) {
+    return true;
   }
- =20
+
   // Iterators
   child_range children() { return child_range(&Temporary, &Temporary + 1);=
 }
 };
- =20
+
 }  // end namespace clang
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ExprObjC.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ExprObjC.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ExprObjC.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/SelectorLocationsKind.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
   class IdentifierInfo;
@@ -43,7 +44,7 @@
   SourceLocation getAtLoc() const { return AtLoc; }
   void setAtLoc(SourceLocation L) { AtLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtLoc, String->getLocEnd());
   }
=20
@@ -56,6 +57,281 @@
   child_range children() { return child_range(&String, &String+1); }
 };
=20
+/// ObjCBoolLiteralExpr - Objective-C Boolean Literal.
+///
+class ObjCBoolLiteralExpr : public Expr {
+  bool Value;
+  SourceLocation Loc;
+public:
+  ObjCBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) :
+  Expr(ObjCBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
+       false, false), Value(val), Loc(l) {}
+   =20
+  explicit ObjCBoolLiteralExpr(EmptyShell Empty)
+  : Expr(ObjCBoolLiteralExprClass, Empty) { }
+   =20
+  bool getValue() const { return Value; }
+  void setValue(bool V) { Value =3D V; }
+   =20
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Lo=
c); }
+   =20
+  SourceLocation getLocation() const { return Loc; }
+  void setLocation(SourceLocation L) { Loc =3D L; }
+   =20
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() =3D=3D ObjCBoolLiteralExprClass;
+  }
+  static bool classof(const ObjCBoolLiteralExpr *) { return true; }
+   =20
+  // Iterators
+  child_range children() { return child_range(); }
+};
+
+/// ObjCNumericLiteral - used for objective-c numeric literals;
+/// as in: @42 or @true (c++/objc++) or @__yes (c/objc)
+class ObjCNumericLiteral : public Expr {
+  /// Number - expression AST node for the numeric literal
+  Stmt *Number;
+  ObjCMethodDecl *ObjCNumericLiteralMethod;
+  SourceLocation AtLoc;
+public:
+  ObjCNumericLiteral(Stmt *NL, QualType T, ObjCMethodDecl *method,
+                     SourceLocation L)
+  : Expr(ObjCNumericLiteralClass, T, VK_RValue, OK_Ordinary,=20
+         false, false, false, false), Number(NL),=20
+    ObjCNumericLiteralMethod(method), AtLoc(L) {}
+  explicit ObjCNumericLiteral(EmptyShell Empty)
+  : Expr(ObjCNumericLiteralClass, Empty) {}
+ =20
+  Expr *getNumber() { return cast<Expr>(Number); }
+  const Expr *getNumber() const { return cast<Expr>(Number); }
+ =20
+  ObjCMethodDecl *getObjCNumericLiteralMethod() const {
+    return ObjCNumericLiteralMethod;=20
+  }
+   =20
+  SourceLocation getAtLoc() const { return AtLoc; }
+ =20
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return SourceRange(AtLoc, Number->getSourceRange().getEnd());
+  }
+
+  static bool classof(const Stmt *T) {
+      return T->getStmtClass() =3D=3D ObjCNumericLiteralClass;
+  }
+  static bool classof(const ObjCNumericLiteral *) { return true; }
+ =20
+  // Iterators
+  child_range children() { return child_range(&Number, &Number+1); }
+   =20
+  friend class ASTStmtReader;
+};
+
+/// ObjCArrayLiteral - used for objective-c array containers; as in:
+/// @[@"Hello", NSApp, [NSNumber numberWithInt:42]];
+class ObjCArrayLiteral : public Expr {
+  unsigned NumElements;
+  SourceRange Range;
+  ObjCMethodDecl *ArrayWithObjectsMethod;
+ =20
+  ObjCArrayLiteral(llvm::ArrayRef<Expr *> Elements,
+                   QualType T, ObjCMethodDecl * Method,
+                   SourceRange SR);
+ =20
+  explicit ObjCArrayLiteral(EmptyShell Empty, unsigned NumElements)
+    : Expr(ObjCArrayLiteralClass, Empty), NumElements(NumElements) {}
+
+public:
+  static ObjCArrayLiteral *Create(ASTContext &C,=20
+                                  llvm::ArrayRef<Expr *> Elements,
+                                  QualType T, ObjCMethodDecl * Method,
+                                  SourceRange SR);
+
+  static ObjCArrayLiteral *CreateEmpty(ASTContext &C, unsigned NumElements=
);
+
+  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
+
+  static bool classof(const Stmt *T) {
+      return T->getStmtClass() =3D=3D ObjCArrayLiteralClass;
+  }
+  static bool classof(const ObjCArrayLiteral *) { return true; }
+
+  /// \brief Retrieve elements of array of literals.
+  Expr **getElements() { return reinterpret_cast<Expr **>(this + 1); }
+
+  /// \brief Retrieve elements of array of literals.
+  const Expr * const *getElements() const {=20
+    return reinterpret_cast<const Expr * const*>(this + 1);=20
+  }
+
+  /// getNumElements - Return number of elements of objective-c array lite=
ral.
+  unsigned getNumElements() const { return NumElements; }
+   =20
+    /// getExpr - Return the Expr at the specified index.
+  Expr *getElement(unsigned Index) {
+    assert((Index < NumElements) && "Arg access out of range!");
+    return cast<Expr>(getElements()[Index]);
+  }
+  const Expr *getElement(unsigned Index) const {
+    assert((Index < NumElements) && "Arg access out of range!");
+    return cast<Expr>(getElements()[Index]);
+  }
+   =20
+  ObjCMethodDecl *getArrayWithObjectsMethod() const {
+    return ArrayWithObjectsMethod;=20
+  }
+   =20
+  // Iterators
+  child_range children() {=20
+    return child_range((Stmt **)getElements(),=20
+                       (Stmt **)getElements() + NumElements);
+  }
+   =20
+  friend class ASTStmtReader;
+};
+
+/// \brief An element in an Objective-C dictionary literal.
+///
+struct ObjCDictionaryElement {
+  /// \brief The key for the dictionary element.
+  Expr *Key;
+ =20
+  /// \brief The value of the dictionary element.
+  Expr *Value;
+ =20
+  /// \brief The location of the ellipsis, if this is a pack expansion.
+  SourceLocation EllipsisLoc;
+ =20
+  /// \brief The number of elements this pack expansion will expand to, if
+  /// this is a pack expansion and is known.
+  llvm::Optional<unsigned> NumExpansions;
+
+  /// \brief Determines whether this dictionary element is a pack expansio=
n.
+  bool isPackExpansion() const { return EllipsisLoc.isValid(); }
+};
+
+/// ObjCDictionaryLiteral - AST node to represent objective-c dictionary=20
+/// literals; as in:  @{@"name" : NSUserName(), @"date" : [NSDate date] };
+class ObjCDictionaryLiteral : public Expr {
+  /// \brief Key/value pair used to store the key and value of a given ele=
ment.
+  ///
+  /// Objects of this type are stored directly after the expression.
+  struct KeyValuePair {
+    Expr *Key;
+    Expr *Value;
+  };
+ =20
+  /// \brief Data that describes an element that is a pack expansion, used=
 if any
+  /// of the elements in the dictionary literal are pack expansions.
+  struct ExpansionData {
+    /// \brief The location of the ellipsis, if this element is a pack
+    /// expansion.
+    SourceLocation EllipsisLoc;
+
+    /// \brief If non-zero, the number of elements that this pack
+    /// expansion will expand to (+1).
+    unsigned NumExpansionsPlusOne;
+  };
+
+  /// \brief The number of elements in this dictionary literal.
+  unsigned NumElements : 31;
+ =20
+  /// \brief Determine whether this dictionary literal has any pack expans=
ions.
+  ///
+  /// If the dictionary literal has pack expansions, then there will
+  /// be an array of pack expansion data following the array of
+  /// key/value pairs, which provide the locations of the ellipses (if
+  /// any) and number of elements in the expansion (if known). If
+  /// there are no pack expansions, we optimize away this storage.
+  unsigned HasPackExpansions : 1;
+ =20
+  SourceRange Range;
+  ObjCMethodDecl *DictWithObjectsMethod;
+   =20
+  ObjCDictionaryLiteral(ArrayRef<ObjCDictionaryElement> VK,=20
+                        bool HasPackExpansions,
+                        QualType T, ObjCMethodDecl *method,
+                        SourceRange SR);
+
+  explicit ObjCDictionaryLiteral(EmptyShell Empty, unsigned NumElements,
+                                 bool HasPackExpansions)
+    : Expr(ObjCDictionaryLiteralClass, Empty), NumElements(NumElements),
+      HasPackExpansions(HasPackExpansions) {}
+
+  KeyValuePair *getKeyValues() {
+    return reinterpret_cast<KeyValuePair *>(this + 1);
+  }
+ =20
+  const KeyValuePair *getKeyValues() const {
+    return reinterpret_cast<const KeyValuePair *>(this + 1);
+  }
+
+  ExpansionData *getExpansionData() {
+    if (!HasPackExpansions)
+      return 0;
+   =20
+    return reinterpret_cast<ExpansionData *>(getKeyValues() + NumElements);
+  }
+
+  const ExpansionData *getExpansionData() const {
+    if (!HasPackExpansions)
+      return 0;
+   =20
+    return reinterpret_cast<const ExpansionData *>(getKeyValues()+NumEleme=
nts);
+  }
+
+public:
+  static ObjCDictionaryLiteral *Create(ASTContext &C,
+                                       ArrayRef<ObjCDictionaryElement> VK,=20
+                                       bool HasPackExpansions,
+                                       QualType T, ObjCMethodDecl *method,
+                                       SourceRange SR);
+ =20
+  static ObjCDictionaryLiteral *CreateEmpty(ASTContext &C,=20
+                                            unsigned NumElements,
+                                            bool HasPackExpansions);
+ =20
+  /// getNumElements - Return number of elements of objective-c dictionary=20
+  /// literal.
+  unsigned getNumElements() const { return NumElements; }
+
+  ObjCDictionaryElement getKeyValueElement(unsigned Index) const {
+    assert((Index < NumElements) && "Arg access out of range!");
+    const KeyValuePair &KV =3D getKeyValues()[Index];
+    ObjCDictionaryElement Result =3D { KV.Key, KV.Value, SourceLocation(),
+                                     llvm::Optional<unsigned>() };
+    if (HasPackExpansions) {
+      const ExpansionData &Expansion =3D getExpansionData()[Index];
+      Result.EllipsisLoc =3D Expansion.EllipsisLoc;
+      if (Expansion.NumExpansionsPlusOne > 0)
+        Result.NumExpansions =3D Expansion.NumExpansionsPlusOne - 1;
+    }
+    return Result;
+  }
+   =20
+  ObjCMethodDecl *getDictWithObjectsMethod() const
+    { return DictWithObjectsMethod; }
+
+  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
+ =20
+  static bool classof(const Stmt *T) {
+      return T->getStmtClass() =3D=3D ObjCDictionaryLiteralClass;
+  }
+  static bool classof(const ObjCDictionaryLiteral *) { return true; }
+   =20
+  // Iterators
+  child_range children() {=20
+    // Note: we're taking advantage of the layout of the KeyValuePair stru=
ct
+    // here. If that struct changes, this code will need to change as well.
+    return child_range(reinterpret_cast<Stmt **>(this + 1),
+                       reinterpret_cast<Stmt **>(this + 1) + NumElements *=
 2);
+  }
+   =20
+  friend class ASTStmtReader;
+  friend class ASTStmtWriter;
+};
+
+
 /// ObjCEncodeExpr, used for @encode in Objective-C.  @encode has the same=
 type
 /// and behavior as StringLiteral except that the string initializer is ob=
tained
 /// from ASTContext with the encoding type as an argument.
@@ -87,7 +363,7 @@
     EncodedType =3D EncType;=20
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtLoc, RParenLoc);
   }
=20
@@ -121,7 +397,7 @@
   void setAtLoc(SourceLocation L) { AtLoc =3D L; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtLoc, RParenLoc);
   }
=20
@@ -161,7 +437,7 @@
   void setAtLoc(SourceLocation L) { AtLoc =3D L; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtLoc, RParenLoc);
   }
=20
@@ -176,9 +452,9 @@
=20
 /// ObjCIvarRefExpr - A reference to an ObjC instance variable.
 class ObjCIvarRefExpr : public Expr {
-  class ObjCIvarDecl *D;
+  ObjCIvarDecl *D;
+  Stmt *Base;
   SourceLocation Loc;
-  Stmt *Base;
   bool IsArrow:1;      // True if this is "X->F", false if this is "X.F".
   bool IsFreeIvar:1;   // True if ivar reference has no base (self assumed=
).
=20
@@ -190,7 +466,7 @@
          /*TypeDependent=3D*/false, base->isValueDependent(),=20
          base->isInstantiationDependent(),
          base->containsUnexpandedParameterPack()),=20
-    D(d), Loc(l), Base(base), IsArrow(arrow), IsFreeIvar(freeIvar) {}
+    D(d), Base(base), Loc(l), IsArrow(arrow), IsFreeIvar(freeIvar) {}
=20
   explicit ObjCIvarRefExpr(EmptyShell Empty)
     : Expr(ObjCIvarRefExprClass, Empty) {}
@@ -211,7 +487,7 @@
   SourceLocation getLocation() const { return Loc; }
   void setLocation(SourceLocation L) { Loc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return isFreeIvar() ? SourceRange(Loc)
     : SourceRange(getBase()->getLocStart(), Loc);
   }
@@ -227,7 +503,6 @@
=20
 /// ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC
 /// property.
-///
 class ObjCPropertyRefExpr : public Expr {
 private:
   /// If the bool is true, this is an implicit property reference; the
@@ -235,7 +510,23 @@
   /// if the bool is false, this is an explicit property reference;
   /// the pointer is an ObjCPropertyDecl and Setter is always null.
   llvm::PointerIntPair<NamedDecl*, 1, bool> PropertyOrGetter;
-  ObjCMethodDecl *Setter;
+
+  /// \brief Indicates whether the property reference will result in a mes=
sage
+  /// to the getter, the setter, or both.
+  /// This applies to both implicit and explicit property references.
+  enum MethodRefFlags {
+    MethodRef_None =3D 0,
+    MethodRef_Getter =3D 0x1,
+    MethodRef_Setter =3D 0x2
+  };
+
+  /// \brief Contains the Setter method pointer and MethodRefFlags bit fla=
gs.
+  llvm::PointerIntPair<ObjCMethodDecl *, 2, unsigned> SetterAndMethodRefFl=
ags;
+
+  // FIXME: Maybe we should store the property identifier here,
+  // because it's not rederivable from the other data when there's an
+  // implicit property with no getter (because the 'foo' -> 'setFoo:'
+  // transformation is lossy on the first character).
=20
   SourceLocation IdLoc;
  =20
@@ -253,8 +544,9 @@
            /*TypeDependent=3D*/false, base->isValueDependent(),
            base->isInstantiationDependent(),
            base->containsUnexpandedParameterPack()),
-      PropertyOrGetter(PD, false), Setter(0),
+      PropertyOrGetter(PD, false), SetterAndMethodRefFlags(),
       IdLoc(l), ReceiverLoc(), Receiver(base) {
+    assert(t->isSpecificPlaceholderType(BuiltinType::PseudoObject));
   }
  =20
   ObjCPropertyRefExpr(ObjCPropertyDecl *PD, QualType t,
@@ -263,8 +555,9 @@
     : Expr(ObjCPropertyRefExprClass, t, VK, OK,
            /*TypeDependent=3D*/false, false, st->isInstantiationDependentT=
ype(),
            st->containsUnexpandedParameterPack()),
-      PropertyOrGetter(PD, false), Setter(0),
+      PropertyOrGetter(PD, false), SetterAndMethodRefFlags(),
       IdLoc(l), ReceiverLoc(sl), Receiver(st.getTypePtr()) {
+    assert(t->isSpecificPlaceholderType(BuiltinType::PseudoObject));
   }
=20
   ObjCPropertyRefExpr(ObjCMethodDecl *Getter, ObjCMethodDecl *Setter,
@@ -273,8 +566,9 @@
     : Expr(ObjCPropertyRefExprClass, T, VK, OK, false,
            Base->isValueDependent(), Base->isInstantiationDependent(),
            Base->containsUnexpandedParameterPack()),
-      PropertyOrGetter(Getter, true), Setter(Setter),
+      PropertyOrGetter(Getter, true), SetterAndMethodRefFlags(Setter, 0),
       IdLoc(IdLoc), ReceiverLoc(), Receiver(Base) {
+    assert(T->isSpecificPlaceholderType(BuiltinType::PseudoObject));
   }
=20
   ObjCPropertyRefExpr(ObjCMethodDecl *Getter, ObjCMethodDecl *Setter,
@@ -282,8 +576,9 @@
                       SourceLocation IdLoc,
                       SourceLocation SuperLoc, QualType SuperTy)
     : Expr(ObjCPropertyRefExprClass, T, VK, OK, false, false, false, false=
),
-      PropertyOrGetter(Getter, true), Setter(Setter),
+      PropertyOrGetter(Getter, true), SetterAndMethodRefFlags(Setter, 0),
       IdLoc(IdLoc), ReceiverLoc(SuperLoc), Receiver(SuperTy.getTypePtr()) {
+    assert(T->isSpecificPlaceholderType(BuiltinType::PseudoObject));
   }
=20
   ObjCPropertyRefExpr(ObjCMethodDecl *Getter, ObjCMethodDecl *Setter,
@@ -291,8 +586,9 @@
                       SourceLocation IdLoc,
                       SourceLocation ReceiverLoc, ObjCInterfaceDecl *Recei=
ver)
     : Expr(ObjCPropertyRefExprClass, T, VK, OK, false, false, false, false=
),
-      PropertyOrGetter(Getter, true), Setter(Setter),
+      PropertyOrGetter(Getter, true), SetterAndMethodRefFlags(Setter, 0),
       IdLoc(IdLoc), ReceiverLoc(ReceiverLoc), Receiver(Receiver) {
+    assert(T->isSpecificPlaceholderType(BuiltinType::PseudoObject));
   }
=20
   explicit ObjCPropertyRefExpr(EmptyShell Empty)
@@ -313,7 +609,7 @@
=20
   ObjCMethodDecl *getImplicitPropertySetter() const {
     assert(isImplicitProperty());
-    return Setter;
+    return SetterAndMethodRefFlags.getPointer();
   }
=20
   Selector getGetterSelector() const {
@@ -328,6 +624,28 @@
     return getExplicitProperty()->getSetterName();
   }
=20
+  /// \brief True if the property reference will result in a message to the
+  /// getter.
+  /// This applies to both implicit and explicit property references.
+  bool isMessagingGetter() const {
+    return SetterAndMethodRefFlags.getInt() & MethodRef_Getter;
+  }
+
+  /// \brief True if the property reference will result in a message to the
+  /// setter.
+  /// This applies to both implicit and explicit property references.
+  bool isMessagingSetter() const {
+    return SetterAndMethodRefFlags.getInt() & MethodRef_Setter;
+  }
+
+  void setIsMessagingGetter(bool val =3D true) {
+    setMethodRefFlag(MethodRef_Getter, val);
+  }
+
+  void setIsMessagingSetter(bool val =3D true) {
+    setMethodRefFlag(MethodRef_Setter, val);
+  }
+
   const Expr *getBase() const {=20
     return cast<Expr>(Receiver.get<Stmt*>());=20
   }
@@ -348,14 +666,15 @@
       if (const ObjCMethodDecl *Getter =3D PDecl->getGetterMethodDecl())
         ResultType =3D Getter->getResultType();
       else
-        ResultType =3D getType();
+        ResultType =3D PDecl->getType();
     } else {
       const ObjCMethodDecl *Getter =3D getImplicitPropertyGetter();
-      ResultType =3D Getter->getResultType(); // with reference!
+      if (Getter)
+        ResultType =3D Getter->getResultType(); // with reference!
     }
     return ResultType;
   }
- =20
+
   QualType getSetterArgType() const {
     QualType ArgType;
     if (isImplicitProperty()) {
@@ -381,7 +700,7 @@
   bool isSuperReceiver() const { return Receiver.is<const Type*>(); }
   bool isClassReceiver() const { return Receiver.is<ObjCInterfaceDecl*>();=
 }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange((isObjectReceiver() ? getBase()->getLocStart()
                                            : getReceiverLocation()),=20
                        IdLoc);
@@ -403,15 +722,19 @@
=20
 private:
   friend class ASTStmtReader;
-  void setExplicitProperty(ObjCPropertyDecl *D) {
+  friend class ASTStmtWriter;
+  void setExplicitProperty(ObjCPropertyDecl *D, unsigned methRefFlags) {
     PropertyOrGetter.setPointer(D);
     PropertyOrGetter.setInt(false);
-    Setter =3D 0;
+    SetterAndMethodRefFlags.setPointer(0);
+    SetterAndMethodRefFlags.setInt(methRefFlags);
   }
-  void setImplicitProperty(ObjCMethodDecl *Getter, ObjCMethodDecl *Setter)=
 {
+  void setImplicitProperty(ObjCMethodDecl *Getter, ObjCMethodDecl *Setter,
+                           unsigned methRefFlags) {
     PropertyOrGetter.setPointer(Getter);
     PropertyOrGetter.setInt(true);
-    this->Setter =3D Setter;
+    SetterAndMethodRefFlags.setPointer(Setter);
+    SetterAndMethodRefFlags.setInt(methRefFlags);
   }
   void setBase(Expr *Base) { Receiver =3D Base; }
   void setSuperReceiver(QualType T) { Receiver =3D T.getTypePtr(); }
@@ -419,7 +742,98 @@
=20
   void setLocation(SourceLocation L) { IdLoc =3D L; }
   void setReceiverLocation(SourceLocation Loc) { ReceiverLoc =3D Loc; }
+
+  void setMethodRefFlag(MethodRefFlags flag, bool val) {
+    unsigned f =3D SetterAndMethodRefFlags.getInt();
+    if (val)
+      f |=3D flag;
+    else
+      f &=3D ~flag;
+    SetterAndMethodRefFlags.setInt(f);
+  }
 };
+ =20
+/// ObjCSubscriptRefExpr - used for array and dictionary subscripting.
+/// array[4] =3D array[3]; dictionary[key] =3D dictionary[alt_key];
+///
+class ObjCSubscriptRefExpr : public Expr {
+  // Location of ']' in an indexing expression.
+  SourceLocation RBracket;
+  // array/dictionary base expression.
+  // for arrays, this is a numeric expression. For dictionaries, this is
+  // an objective-c object pointer expression.
+  enum { BASE, KEY, END_EXPR };
+  Stmt* SubExprs[END_EXPR];
+ =20
+  ObjCMethodDecl *GetAtIndexMethodDecl;
+ =20
+  // For immutable objects this is null. When ObjCSubscriptRefExpr is to r=
ead
+  // an indexed object this is null too.
+  ObjCMethodDecl *SetAtIndexMethodDecl;
+ =20
+public:
+ =20
+  ObjCSubscriptRefExpr(Expr *base, Expr *key, QualType T,
+                       ExprValueKind VK, ExprObjectKind OK,
+                       ObjCMethodDecl *getMethod,
+                       ObjCMethodDecl *setMethod, SourceLocation RB)
+    : Expr(ObjCSubscriptRefExprClass, T, VK, OK,=20
+           base->isTypeDependent() || key->isTypeDependent(),=20
+           base->isValueDependent() || key->isValueDependent(),
+           base->isInstantiationDependent() || key->isInstantiationDepende=
nt(),
+           (base->containsUnexpandedParameterPack() ||
+            key->containsUnexpandedParameterPack())),
+      RBracket(RB),=20
+  GetAtIndexMethodDecl(getMethod),=20
+  SetAtIndexMethodDecl(setMethod)=20
+    {SubExprs[BASE] =3D base; SubExprs[KEY] =3D key;}
+
+  explicit ObjCSubscriptRefExpr(EmptyShell Empty)
+    : Expr(ObjCSubscriptRefExprClass, Empty) {}
+ =20
+  static ObjCSubscriptRefExpr *Create(ASTContext &C,
+                                      Expr *base,
+                                      Expr *key, QualType T,=20
+                                      ObjCMethodDecl *getMethod,
+                                      ObjCMethodDecl *setMethod,=20
+                                      SourceLocation RB);
+ =20
+  SourceLocation getRBracket() const { return RBracket; }
+  void setRBracket(SourceLocation RB) { RBracket =3D RB; }
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return SourceRange(SubExprs[BASE]->getLocStart(), RBracket);
+  }
+ =20
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() =3D=3D ObjCSubscriptRefExprClass;
+  }
+  static bool classof(const ObjCSubscriptRefExpr *) { return true; }
+ =20
+  Expr *getBaseExpr() const { return cast<Expr>(SubExprs[BASE]); }
+  void setBaseExpr(Stmt *S) { SubExprs[BASE] =3D S; }
+ =20
+  Expr *getKeyExpr() const { return cast<Expr>(SubExprs[KEY]); }
+  void setKeyExpr(Stmt *S) { SubExprs[KEY] =3D S; }
+ =20
+  ObjCMethodDecl *getAtIndexMethodDecl() const {
+    return GetAtIndexMethodDecl;
+  }
+=20
+  ObjCMethodDecl *setAtIndexMethodDecl() const {
+    return SetAtIndexMethodDecl;
+  }
+ =20
+  bool isArraySubscriptRefExpr() const {
+    return getKeyExpr()->getType()->isIntegralOrEnumerationType();
+  }
+ =20
+  child_range children() {
+    return child_range(SubExprs, SubExprs+END_EXPR);
+  }
+private:
+  friend class ASTStmtReader;
+};
+ =20
=20
 /// \brief An expression that sends a message to the given Objective-C
 /// object or class.
@@ -477,7 +891,11 @@
   /// \brief Whether this message send is a "delegate init call",
   /// i.e. a call of an init method on self from within an init method.
   unsigned IsDelegateInitCall : 1;
- =20
+
+  /// \brief Whether this message send was implicitly generated by
+  /// the implementation rather than explicitly written by the user.
+  unsigned IsImplicit : 1;
+
   /// \brief Whether the locations of the selector identifiers are in a
   /// "standard" position, a enum SelectorLocationsKind.
   unsigned SelLocsKind : 2;
@@ -492,7 +910,7 @@
=20
   ObjCMessageExpr(EmptyShell Empty, unsigned NumArgs)
     : Expr(ObjCMessageExprClass, Empty), SelectorOrMethod(0), Kind(0),=20
-      HasMethod(0), IsDelegateInitCall(0) {
+      HasMethod(0), IsDelegateInitCall(0), IsImplicit(0), SelLocsKind(0) {
     setNumArgs(NumArgs);
   }
=20
@@ -506,7 +924,8 @@
                   SelectorLocationsKind SelLocsK,
                   ObjCMethodDecl *Method,
                   ArrayRef<Expr *> Args,
-                  SourceLocation RBracLoc);
+                  SourceLocation RBracLoc,
+                  bool isImplicit);
   ObjCMessageExpr(QualType T, ExprValueKind VK,
                   SourceLocation LBracLoc,
                   TypeSourceInfo *Receiver,
@@ -515,7 +934,8 @@
                   SelectorLocationsKind SelLocsK,
                   ObjCMethodDecl *Method,
                   ArrayRef<Expr *> Args,
-                  SourceLocation RBracLoc);
+                  SourceLocation RBracLoc,
+                  bool isImplicit);
   ObjCMessageExpr(QualType T, ExprValueKind VK,
                   SourceLocation LBracLoc,
                   Expr *Receiver,
@@ -524,7 +944,8 @@
                   SelectorLocationsKind SelLocsK,
                   ObjCMethodDecl *Method,
                   ArrayRef<Expr *> Args,
-                  SourceLocation RBracLoc);
+                  SourceLocation RBracLoc,
+                  bool isImplicit);
=20
   void initArgsAndSelLocs(ArrayRef<Expr *> Args,
                           ArrayRef<SourceLocation> SelLocs,
@@ -625,7 +1046,8 @@
                                  ArrayRef<SourceLocation> SelLocs,
                                  ObjCMethodDecl *Method,
                                  ArrayRef<Expr *> Args,
-                                 SourceLocation RBracLoc);
+                                 SourceLocation RBracLoc,
+                                 bool isImplicit);
=20
   /// \brief Create a class message send.
   ///
@@ -660,7 +1082,8 @@
                                  ArrayRef<SourceLocation> SelLocs,
                                  ObjCMethodDecl *Method,
                                  ArrayRef<Expr *> Args,
-                                 SourceLocation RBracLoc);
+                                 SourceLocation RBracLoc,
+                                 bool isImplicit);
=20
   /// \brief Create an instance message send.
   ///
@@ -695,7 +1118,8 @@
                                  ArrayRef<SourceLocation> SeLocs,
                                  ObjCMethodDecl *Method,
                                  ArrayRef<Expr *> Args,
-                                 SourceLocation RBracLoc);
+                                 SourceLocation RBracLoc,
+                                 bool isImplicit);
=20
   /// \brief Create an empty Objective-C message expression, to be
   /// filled in by subsequent calls.
@@ -708,6 +1132,11 @@
                                       unsigned NumArgs,
                                       unsigned NumStoredSelLocs);
=20
+  /// \brief Indicates whether the message send was implicitly
+  /// generated by the implementation. If false, it was written explicitly
+  /// in the source code.
+  bool isImplicit() const { return IsImplicit; }
+
   /// \brief Determine the kind of receiver that this message is being
   /// sent to.
   ReceiverKind getReceiverKind() const { return (ReceiverKind)Kind; }
@@ -877,7 +1306,11 @@
   SourceLocation getLeftLoc() const { return LBracLoc; }
   SourceLocation getRightLoc() const { return RBracLoc; }
=20
-  SourceLocation getSelectorStartLoc() const { return getSelectorLoc(0); }
+  SourceLocation getSelectorStartLoc() const {
+    if (isImplicit())
+      return getLocStart();
+    return getSelectorLoc(0);
+  }
   SourceLocation getSelectorLoc(unsigned Index) const {
     assert(Index < getNumSelectorLocs() && "Index out of range!");
     if (hasStandardSelLocs())
@@ -892,6 +1325,8 @@
   void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
=20
   unsigned getNumSelectorLocs() const {
+    if (isImplicit())
+      return 0;
     Selector Sel =3D getSelector();
     if (Sel.isUnarySelector())
       return 1;
@@ -902,7 +1337,7 @@
     LBracLoc =3D R.getBegin();
     RBracLoc =3D R.getEnd();
   }
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LBracLoc, RBracLoc);
   }
=20
@@ -965,11 +1400,11 @@
   SourceLocation getIsaMemberLoc() const { return IsaMemberLoc; }
   void setIsaMemberLoc(SourceLocation L) { IsaMemberLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getBase()->getLocStart(), IsaMemberLoc);
   }
=20
-  SourceLocation getExprLoc() const { return IsaMemberLoc; }
+  SourceLocation getExprLoc() const LLVM_READONLY { return IsaMemberLoc; }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D ObjCIsaExprClass;
@@ -1038,8 +1473,12 @@
   child_range children() { return child_range(&Operand, &Operand+1); } =20
=20
   // Source locations are determined by the subexpression.
-  SourceRange getSourceRange() const { return Operand->getSourceRange(); }
-  SourceLocation getExprLoc() const { return getSubExpr()->getExprLoc(); }
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return Operand->getSourceRange();
+  }
+  SourceLocation getExprLoc() const LLVM_READONLY {
+    return getSubExpr()->getExprLoc();
+  }
=20
   static bool classof(const Stmt *s) {
     return s->getStmtClass() =3D=3D ObjCIndirectCopyRestoreExprClass;
@@ -1086,7 +1525,7 @@
   /// \brief The location of the bridge keyword.
   SourceLocation getBridgeKeywordLoc() const { return BridgeKeywordLoc; }
  =20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LParenLoc, getSubExpr()->getLocEnd());
   }
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/ExternalASTSource.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/ExternalASTSource.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/ExternalASTSource.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -15,6 +15,8 @@
 #define LLVM_CLANG_AST_EXTERNAL_AST_SOURCE_H
=20
 #include "clang/AST/DeclBase.h"
+#include "clang/AST/CharUnits.h"
+#include "llvm/ADT/DenseMap.h"
=20
 namespace clang {
=20
@@ -153,6 +155,12 @@
     return FindExternalLexicalDecls(DC, DeclTy::classofKind, Result);
   }
=20
+  /// \brief Get the decls that are contained in a file in the Offset/Leng=
th
+  /// range. \arg Length can be 0 to indicate a point at \arg Offset inste=
ad of
+  /// a range.=20
+  virtual void FindFileRegionDecls(FileID File, unsigned Offset,unsigned L=
ength,
+                                   SmallVectorImpl<Decl *> &Decls) {}
+
   /// \brief Gives the external AST source an opportunity to complete
   /// an incomplete type.
   virtual void CompleteType(TagDecl *Tag) {}
@@ -190,6 +198,44 @@
   /// The default implementation of this method is a no-op.
   virtual void PrintStats();
  =20
+ =20
+  /// \brief Perform layout on the given record.
+  ///
+  /// This routine allows the external AST source to provide an specific=20
+  /// layout for a record, overriding the layout that would normally be
+  /// constructed. It is intended for clients who receive specific layout
+  /// details rather than source code (such as LLDB). The client is expect=
ed
+  /// to fill in the field offsets, base offsets, virtual base offsets, and
+  /// complete object size.
+  ///
+  /// \param Record The record whose layout is being requested.
+  ///
+  /// \param Size The final size of the record, in bits.
+  ///
+  /// \param Alignment The final alignment of the record, in bits.
+  ///
+  /// \param FieldOffsets The offset of each of the fields within the reco=
rd,
+  /// expressed in bits. All of the fields must be provided with offsets.
+  ///
+  /// \param BaseOffsets The offset of each of the direct, non-virtual base
+  /// classes. If any bases are not given offsets, the bases will be laid=20
+  /// out according to the ABI.
+  ///
+  /// \param VirtualBaseOffsets The offset of each of the virtual base cla=
sses
+  /// (either direct or not). If any bases are not given offsets, the base=
s will be laid=20
+  /// out according to the ABI.
+  ///=20
+  /// \returns true if the record layout was provided, false otherwise.
+  virtual bool=20
+  layoutRecordType(const RecordDecl *Record,
+                   uint64_t &Size, uint64_t &Alignment,
+                   llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffse=
ts,
+                 llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOff=
sets,
+          llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOff=
sets)
+  {=20
+    return false;
+  }
+ =20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Queries for performance analysis.
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/Mangle.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/Mangle.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/Mangle.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -58,12 +58,14 @@
=20
 private:
   StringRef String;
-  llvm::SmallString<256> Buffer;
+  SmallString<256> Buffer;
 };
=20
 /// MangleContext - Context for tracking state which persists across multi=
ple
 /// calls to the C++ name mangler.
 class MangleContext {
+  virtual void anchor();
+
   ASTContext &Context;
   DiagnosticsEngine &Diags;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/NestedNameSpecifier.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/NestedNameSpecifier.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/NestedNameSpecifier.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/PointerIntPair.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
=20
@@ -36,8 +37,9 @@
 /// namespaces. For example, "foo::" in "foo::x" is a nested name
 /// specifier. Nested name specifiers are made up of a sequence of
 /// specifiers, each of which can be a namespace, type, identifier
-/// (for dependent names), or the global specifier ('::', must be the
-/// first specifier).
+/// (for dependent names), decltype specifier, or the global specifier (':=
:').
+/// The last two specifiers can only appear at the start of a=20
+/// nested-namespace-specifier.
 class NestedNameSpecifier : public llvm::FoldingSetNode {
=20
   /// \brief Enumeration describing
@@ -95,7 +97,8 @@
       Specifier(Other.Specifier) {
   }
=20
-  NestedNameSpecifier &operator=3D(const NestedNameSpecifier &); // do not=
 implement
+  NestedNameSpecifier &operator=3D(const NestedNameSpecifier &); // do not
+                                                               // implement
=20
   /// \brief Either find or insert the given nested name specifier
   /// mockup in the given context.
@@ -221,12 +224,12 @@
 public:
   /// \brief Construct an empty nested-name-specifier.
   NestedNameSpecifierLoc() : Qualifier(0), Data(0) { }
- =20
+
   /// \brief Construct a nested-name-specifier with source location inform=
ation
-  /// from=20
+  /// from
   NestedNameSpecifierLoc(NestedNameSpecifier *Qualifier, void *Data)
     : Qualifier(Qualifier), Data(Data) { }
- =20
+
   /// \brief Evalutes true when this nested-name-specifier location is
   /// non-empty.
   operator bool() const { return Qualifier; }
@@ -239,14 +242,14 @@
=20
   /// \brief Retrieve the opaque pointer that refers to source-location da=
ta.
   void *getOpaqueData() const { return Data; }
- =20
+
   /// \brief Retrieve the source range covering the entirety of this
   /// nested-name-specifier.
   ///
   /// For example, if this instance refers to a nested-name-specifier
   /// \c ::std::vector<int>::, the returned source range would cover
   /// from the initial '::' to the last '::'.
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   /// \brief Retrieve the source range covering just the last part of
   /// this nested-name-specifier, not including the prefix.
@@ -258,25 +261,25 @@
=20
   /// \brief Retrieve the location of the beginning of this
   /// nested-name-specifier.
-  SourceLocation getBeginLoc() const {=20
+  SourceLocation getBeginLoc() const {
     return getSourceRange().getBegin();
   }
=20
   /// \brief Retrieve the location of the end of this
   /// nested-name-specifier.
-  SourceLocation getEndLoc() const {=20
+  SourceLocation getEndLoc() const {
     return getSourceRange().getEnd();
   }
=20
   /// \brief Retrieve the location of the beginning of this
   /// component of the nested-name-specifier.
-  SourceLocation getLocalBeginLoc() const {=20
+  SourceLocation getLocalBeginLoc() const {
     return getLocalSourceRange().getBegin();
   }
- =20
+
   /// \brief Retrieve the location of the end of this component of the
   /// nested-name-specifier.
-  SourceLocation getLocalEndLoc() const {=20
+  SourceLocation getLocalEndLoc() const {
     return getLocalSourceRange().getEnd();
   }
=20
@@ -300,13 +303,13 @@
   /// \brief Determines the data length for the entire
   /// nested-name-specifier.
   unsigned getDataLength() const { return getDataLength(Qualifier); }
- =20
-  friend bool operator=3D=3D(NestedNameSpecifierLoc X,=20
+
+  friend bool operator=3D=3D(NestedNameSpecifierLoc X,
                          NestedNameSpecifierLoc Y) {
     return X.Qualifier =3D=3D Y.Qualifier && X.Data =3D=3D Y.Data;
   }
=20
-  friend bool operator!=3D(NestedNameSpecifierLoc X,=20
+  friend bool operator!=3D(NestedNameSpecifierLoc X,
                          NestedNameSpecifierLoc Y) {
     return !(X =3D=3D Y);
   }
@@ -316,39 +319,43 @@
 /// with source-location information for all of the components of the
 /// nested-name-specifier.
 class NestedNameSpecifierLocBuilder {
-  /// \brief The current representation of the nested-name-specifier we're=20
+  /// \brief The current representation of the nested-name-specifier we're
   /// building.
   NestedNameSpecifier *Representation;
- =20
+
   /// \brief Buffer used to store source-location information for the
   /// nested-name-specifier.
   ///
-  /// Note that we explicitly manage the buffer (rather than using a=20
+  /// Note that we explicitly manage the buffer (rather than using a
   /// SmallVector) because \c Declarator expects it to be possible to memc=
py()
   /// a \c CXXScopeSpec, and CXXScopeSpec uses a NestedNameSpecifierLocBui=
lder.
   char *Buffer;
- =20
+
   /// \brief The size of the buffer used to store source-location informat=
ion
   /// for the nested-name-specifier.
   unsigned BufferSize;
- =20
-  /// \brief The capacity of the buffer used to store source-location=20
+
+  /// \brief The capacity of the buffer used to store source-location
   /// information for the nested-name-specifier.
   unsigned BufferCapacity;
=20
 public:
-  NestedNameSpecifierLocBuilder();
- =20
+  NestedNameSpecifierLocBuilder()
+    : Representation(0), Buffer(0), BufferSize(0), BufferCapacity(0) { }
+
   NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other=
);
- =20
+
   NestedNameSpecifierLocBuilder &
   operator=3D(const NestedNameSpecifierLocBuilder &Other);
- =20
-  ~NestedNameSpecifierLocBuilder();
- =20
+
+  ~NestedNameSpecifierLocBuilder() {
+    if (BufferCapacity)
+      free(Buffer);
+  }
+
   /// \brief Retrieve the representation of the nested-name-specifier.
   NestedNameSpecifier *getRepresentation() const { return Representation; }
- =20
+
   /// \brief Extend the current nested-name-specifier by another
   /// nested-name-specifier component of the form 'type::'.
   ///
@@ -362,8 +369,8 @@
   /// \param ColonColonLoc The location of the trailing '::'.
   void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc T=
L,
               SourceLocation ColonColonLoc);
- =20
-  /// \brief Extend the current nested-name-specifier by another=20
+
+  /// \brief Extend the current nested-name-specifier by another
   /// nested-name-specifier component of the form 'identifier::'.
   ///
   /// \param Context The AST context in which this nested-name-specifier
@@ -376,8 +383,8 @@
   /// \param ColonColonLoc The location of the trailing '::'.
   void Extend(ASTContext &Context, IdentifierInfo *Identifier,
               SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
- =20
-  /// \brief Extend the current nested-name-specifier by another=20
+
+  /// \brief Extend the current nested-name-specifier by another
   /// nested-name-specifier component of the form 'namespace::'.
   ///
   /// \param Context The AST context in which this nested-name-specifier
@@ -390,8 +397,8 @@
   /// \param ColonColonLoc The location of the trailing '::'.
   void Extend(ASTContext &Context, NamespaceDecl *Namespace,
               SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
- =20
-  /// \brief Extend the current nested-name-specifier by another=20
+
+  /// \brief Extend the current nested-name-specifier by another
   /// nested-name-specifier component of the form 'namespace-alias::'.
   ///
   /// \param Context The AST context in which this nested-name-specifier
@@ -399,35 +406,35 @@
   ///
   /// \param Alias The namespace alias.
   ///
-  /// \param AliasLoc The location of the namespace alias=20
+  /// \param AliasLoc The location of the namespace alias
   /// name.
   ///
   /// \param ColonColonLoc The location of the trailing '::'.
   void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
               SourceLocation AliasLoc, SourceLocation ColonColonLoc);
- =20
+
   /// \brief Turn this (empty) nested-name-specifier into the global
   /// nested-name-specifier '::'.
   void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
- =20
+
   /// \brief Make a new nested-name-specifier from incomplete source-locat=
ion
   /// information.
   ///
   /// This routine should be used very, very rarely, in cases where we
   /// need to synthesize a nested-name-specifier. Most code should instead=
 use
   /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
-  void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,=20
+  void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
                    SourceRange R);
- =20
-  /// \brief Adopt an existing nested-name-specifier (with source-range=20
+
+  /// \brief Adopt an existing nested-name-specifier (with source-range
   /// information).
   void Adopt(NestedNameSpecifierLoc Other);
- =20
+
   /// \brief Retrieve the source range covered by this nested-name-specifi=
er.
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return NestedNameSpecifierLoc(Representation, Buffer).getSourceRange();
   }
-   =20
+
   /// \brief Retrieve a nested-name-specifier with location information,
   /// copied into the given AST context.
   ///
@@ -449,7 +456,7 @@
     Representation =3D 0;
     BufferSize =3D 0;
   }
- =20
+
   /// \brief Retrieve the underlying buffer.
   ///
   /// \returns A pair containing a pointer to the buffer of source-location
@@ -459,9 +466,9 @@
     return std::make_pair(Buffer, BufferSize);
   }
 };
- =20
-/// Insertion operator for diagnostics.  This allows sending NestedNameSpe=
cifiers
-/// into a diagnostic with <<.
+
+/// Insertion operator for diagnostics.  This allows sending
+/// NestedNameSpecifiers into a diagnostic with <<.
 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
                                            NestedNameSpecifier *NNS) {
   DB.AddTaggedVal(reinterpret_cast<intptr_t>(NNS),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/OperationKinds.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/OperationKinds.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/OperationKinds.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -52,13 +52,6 @@
   /// conversion is always unqualified.
   CK_LValueToRValue,
=20
-  /// CK_GetObjCProperty - A conversion which calls an Objective-C
-  /// property getter.  The operand is an OK_ObjCProperty l-value; the
-  /// result will generally be an r-value, but could be an ordinary
-  /// gl-value if the property reference is to an implicit property
-  /// for a method that returns a reference type.
-  CK_GetObjCProperty,
-   =20
   /// CK_NoOp - A conversion which does not affect the type other than
   /// (possibly) adding qualifiers.
   ///   int    -> int
@@ -124,6 +117,15 @@
   /// against the null member pointer.
   CK_MemberPointerToBoolean,
=20
+  /// CK_ReinterpretMemberPointer - Reinterpret a member pointer as a
+  /// different kind of member pointer.  C++ forbids this from
+  /// crossing between function and object types, but otherwise does
+  /// not restrict it.  However, the only operation that is permitted
+  /// on a "punned" member pointer is casting it back to the original
+  /// type, which is required to be a lossless operation (although
+  /// many ABIs do not guarantee this on all possible intermediate types).
+  CK_ReinterpretMemberPointer,
+
   /// CK_UserDefinedConversion - Conversion using a user defined type
   /// conversion function.
   ///    struct A { operator int(); }; int i =3D int(A());
@@ -274,7 +276,19 @@
   /// in ARC cause blocks to be copied; this is for cases where that
   /// would not otherwise be guaranteed, such as when casting to a
   /// non-block pointer type.
-  CK_ARCExtendBlockObject
+  CK_ARCExtendBlockObject,
+
+  /// \brief Converts from _Atomic(T) to T.
+  CK_AtomicToNonAtomic,
+  /// \brief Converts from T to _Atomic(T).
+  CK_NonAtomicToAtomic,
+ =20
+  /// \brief Causes a block literal to by copied to the heap and then=20
+  /// autoreleased.
+  ///
+  /// This particular cast kind is used for the conversion from a C++11
+  /// lambda expression to a block pointer.
+  CK_CopyAndAutoreleaseBlockObject
 };
=20
 #define CK_Invalid ((CastKind) -1)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/PrettyPrinter.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/PrettyPrinter.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/PrettyPrinter.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
   PrintingPolicy(const LangOptions &LO)
     : Indentation(2), LangOpts(LO), SuppressSpecifiers(false),
       SuppressTagKeyword(false), SuppressTag(false), SuppressScope(false),
-      SuppressInitializers(false),
+      SuppressUnwrittenScope(false), SuppressInitializers(false),
       Dump(false), ConstantArraySizeAsWritten(false),
       AnonymousTagLocations(true), SuppressStrongLifetime(false),
       Bool(LO.Bool) { }
@@ -86,6 +86,10 @@
   /// \brief Suppresses printing of scope specifiers.
   bool SuppressScope : 1;
=20
+  /// \brief Suppress printing parts of scope specifiers that don't need
+  /// to be written, e.g., for inline or anonymous namespaces.
+  bool SuppressUnwrittenScope : 1;
+ =20
   /// \brief Suppress printing of variable initializers.
   ///
   /// This flag is used when printing the loop variable in a for-range
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/RecordLayout.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/RecordLayout.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/RecordLayout.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -62,8 +62,11 @@
     /// (either a base or a member). Will be zero if the class doesn't con=
tain
     /// any empty subobjects.
     CharUnits SizeOfLargestEmptySubobject;
-   =20
-    /// VBPtrOffset - Virtual base table offset.
+
+    /// VFPtrOffset - Virtual function table offset (Microsoft-only).
+    CharUnits VFPtrOffset;
+
+    /// VBPtrOffset - Virtual base table offset (Microsoft-only).
     CharUnits VBPtrOffset;
    =20
     /// PrimaryBase - The primary base info for this record.
@@ -92,7 +95,8 @@
   // Constructor for C++ records.
   typedef CXXRecordLayoutInfo::BaseOffsetsMapTy BaseOffsetsMapTy;
   ASTRecordLayout(const ASTContext &Ctx,
-                  CharUnits size, CharUnits alignment, CharUnits vbptroffs=
et,
+                  CharUnits size, CharUnits alignment,
+                  CharUnits vfptroffset, CharUnits vbptroffset,
                   CharUnits datasize,
                   const uint64_t *fieldoffsets, unsigned fieldcount,
                   CharUnits nonvirtualsize, CharUnits nonvirtualalign,
@@ -204,7 +208,17 @@
     return CXXInfo->SizeOfLargestEmptySubobject;
   }
=20
+  /// getVFPtrOffset - Get the offset for virtual function table pointer.
+  /// This is only meaningful with the Microsoft ABI.
+  CharUnits getVFPtrOffset() const {
+    assert(CXXInfo && "Record layout does not have C++ specific info!");
+    return CXXInfo->VFPtrOffset;
+  }
+
+  /// getVBPtrOffset - Get the offset for virtual base table pointer.
+  /// This is only meaningful with the Microsoft ABI.
   CharUnits getVBPtrOffset() const {
+    assert(CXXInfo && "Record layout does not have C++ specific info!");
     return CXXInfo->VBPtrOffset;
   }
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/RecursiveASTVisitor.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/RecursiveASTVisitor.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -147,7 +147,13 @@
   /// \brief Return whether this visitor should recurse into the types of
   /// TypeLocs.
   bool shouldWalkTypesOfTypeLocs() const { return true; }
- =20
+
+  /// \brief Return whether \param S should be traversed using data recurs=
ion
+  /// to avoid a stack overflow with extreme cases.
+  bool shouldUseDataRecursionFor(Stmt *S) const {
+    return isa<BinaryOperator>(S) || isa<UnaryOperator>(S) || isa<CaseStmt=
>(S);
+  }
+
   /// \brief Recursively visit a statement or expression, by
   /// dispatching to Traverse*() based on the argument's dynamic type.
   ///
@@ -181,12 +187,17 @@
   /// \returns false if the visitation was terminated early, true otherwis=
e.
   bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
=20
-  /// \brief Recursively visit a C++ nested-name-specifier with location=20
+  /// \brief Recursively visit a C++ nested-name-specifier with location
   /// information.
   ///
   /// \returns false if the visitation was terminated early, true otherwis=
e.
   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
=20
+  /// \brief Recursively visit a name with its location information.
+  ///
+  /// \returns false if the visitation was terminated early, true otherwis=
e.
+  bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo);
+
   /// \brief Recursively visit a template name and dispatch to the
   /// appropriate method.
   ///
@@ -223,6 +234,11 @@
   /// \returns false if the visitation was terminated early, true otherwis=
e.
   bool TraverseConstructorInitializer(CXXCtorInitializer *Init);
=20
+  /// \brief Recursively visit a lambda capture.
+  ///
+  /// \returns false if the visitation was terminated early, true otherwis=
e.
+  bool TraverseLambdaCapture(LambdaExpr::Capture C);
+ =20
   // ---- Methods on Stmts ----
=20
   // Declare Traverse*() for all concrete Stmt classes.
@@ -387,8 +403,102 @@
   bool TraverseDeclContextHelper(DeclContext *DC);
   bool TraverseFunctionHelper(FunctionDecl *D);
   bool TraverseVarHelper(VarDecl *D);
+
+  bool Walk(Stmt *S);
+
+  struct EnqueueJob {
+    Stmt *S;
+    Stmt::child_iterator StmtIt;
+
+    EnqueueJob(Stmt *S) : S(S), StmtIt() {
+      if (Expr *E =3D dyn_cast_or_null<Expr>(S))
+        S =3D E->IgnoreParens();
+    }
+  };
+  bool dataTraverse(Stmt *S);
 };
=20
+template<typename Derived>
+bool RecursiveASTVisitor<Derived>::dataTraverse(Stmt *S) {
+
+  SmallVector<EnqueueJob, 16> Queue;
+  Queue.push_back(S);
+
+  while (!Queue.empty()) {
+    EnqueueJob &job =3D Queue.back();
+    Stmt *CurrS =3D job.S;
+    if (!CurrS) {
+      Queue.pop_back();
+      continue;
+    }
+
+    if (getDerived().shouldUseDataRecursionFor(CurrS)) {
+      if (job.StmtIt =3D=3D Stmt::child_iterator()) {
+        if (!Walk(CurrS)) return false;
+        job.StmtIt =3D CurrS->child_begin();
+      } else {
+        ++job.StmtIt;
+      }
+
+      if (job.StmtIt !=3D CurrS->child_end())
+        Queue.push_back(*job.StmtIt);
+      else
+        Queue.pop_back();
+      continue;
+    }
+
+    Queue.pop_back();
+    TRY_TO(TraverseStmt(CurrS));
+  }
+
+  return true;
+}
+
+template<typename Derived>
+bool RecursiveASTVisitor<Derived>::Walk(Stmt *S) {
+
+#define DISPATCH_WALK(NAME, CLASS, VAR) \
+  return getDerived().WalkUpFrom##NAME(static_cast<CLASS*>(VAR));
+
+  if (BinaryOperator *BinOp =3D dyn_cast<BinaryOperator>(S)) {
+    switch (BinOp->getOpcode()) {
+#define OPERATOR(NAME) \
+    case BO_##NAME: DISPATCH_WALK(Bin##NAME, BinaryOperator, S);
+
+    BINOP_LIST()
+#undef OPERATOR
+
+#define OPERATOR(NAME)                                          \
+    case BO_##NAME##Assign:                          \
+    DISPATCH_WALK(Bin##NAME##Assign, CompoundAssignOperator, S);
+
+    CAO_LIST()
+#undef OPERATOR
+    }
+  } else if (UnaryOperator *UnOp =3D dyn_cast<UnaryOperator>(S)) {
+    switch (UnOp->getOpcode()) {
+#define OPERATOR(NAME)                                                  \
+    case UO_##NAME: DISPATCH_WALK(Unary##NAME, UnaryOperator, S);
+
+    UNARYOP_LIST()
+#undef OPERATOR
+    }
+  }
+
+  // Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStm=
t.
+  switch (S->getStmtClass()) {
+  case Stmt::NoStmtClass: break;
+#define ABSTRACT_STMT(STMT)
+#define STMT(CLASS, PARENT) \
+  case Stmt::CLASS##Class: DISPATCH_WALK(CLASS, CLASS, S);
+#include "clang/AST/StmtNodes.inc"
+  }
+
+#undef DISPATCH_WALK
+
+  return true;
+}
+
 #define DISPATCH(NAME, CLASS, VAR) \
   return getDerived().Traverse##NAME(static_cast<CLASS*>(VAR))
=20
@@ -397,6 +507,9 @@
   if (!S)
     return true;
=20
+  if (getDerived().shouldUseDataRecursionFor(S))
+    return dataTraverse(S);
+
   // If we have a binary expr, dispatch to the subcode of the binop.  A sm=
art
   // optimizer (e.g. LLVM) will fold this comparison into the switch stmt
   // below.
@@ -525,23 +638,48 @@
                                                   NestedNameSpecifierLoc N=
NS) {
   if (!NNS)
     return true;
- =20
+
    if (NestedNameSpecifierLoc Prefix =3D NNS.getPrefix())
      TRY_TO(TraverseNestedNameSpecifierLoc(Prefix));
-          =20
+
   switch (NNS.getNestedNameSpecifier()->getKind()) {
   case NestedNameSpecifier::Identifier:
   case NestedNameSpecifier::Namespace:
   case NestedNameSpecifier::NamespaceAlias:
   case NestedNameSpecifier::Global:
     return true;
-    =20
+
   case NestedNameSpecifier::TypeSpec:
   case NestedNameSpecifier::TypeSpecWithTemplate:
     TRY_TO(TraverseTypeLoc(NNS.getTypeLoc()));
     break;
   }
- =20
+
+  return true;
+}
+
+template<typename Derived>
+bool RecursiveASTVisitor<Derived>::TraverseDeclarationNameInfo(
+                                                 DeclarationNameInfo NameI=
nfo) {
+  switch (NameInfo.getName().getNameKind()) {
+  case DeclarationName::CXXConstructorName:
+  case DeclarationName::CXXDestructorName:
+  case DeclarationName::CXXConversionFunctionName:
+    if (TypeSourceInfo *TSInfo =3D NameInfo.getNamedTypeInfo())
+      TRY_TO(TraverseTypeLoc(TSInfo->getTypeLoc()));
+
+    break;
+
+  case DeclarationName::Identifier:
+  case DeclarationName::ObjCZeroArgSelector:
+  case DeclarationName::ObjCOneArgSelector:
+  case DeclarationName::ObjCMultiArgSelector:
+  case DeclarationName::CXXOperatorName:
+  case DeclarationName::CXXLiteralOperatorName:
+  case DeclarationName::CXXUsingDirective:
+    break;
+  }
+
   return true;
 }
=20
@@ -600,7 +738,7 @@
     // FIXME: how can TSI ever be NULL?
     if (TypeSourceInfo *TSI =3D ArgLoc.getTypeSourceInfo())
       return getDerived().TraverseTypeLoc(TSI->getTypeLoc());
-    else=20
+    else
       return getDerived().TraverseType(Arg.getAsType());
   }
=20
@@ -637,12 +775,18 @@
 template<typename Derived>
 bool RecursiveASTVisitor<Derived>::TraverseConstructorInitializer(
                                                      CXXCtorInitializer *I=
nit) {
-  // FIXME: recurse on TypeLoc of the base initializer if isBaseInitialize=
r()?
+  if (TypeSourceInfo *TInfo =3D Init->getTypeSourceInfo())
+    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
+
   if (Init->isWritten())
     TRY_TO(TraverseStmt(Init->getInit()));
   return true;
 }
=20
+template<typename Derived>
+bool RecursiveASTVisitor<Derived>::TraverseLambdaCapture(LambdaExpr::Captu=
re C){
+  return true;
+}
=20
 // ----------------- Type traversal -----------------
=20
@@ -822,8 +966,8 @@
 // ----------------- TypeLoc traversal -----------------
=20
 // This macro makes available a variable TL, the passed-in TypeLoc.
-// If requested, it calls WalkUpFrom* for the Type in the given TypeLoc,=20
-// in addition to WalkUpFrom* for the TypeLoc itself, such that existing=20
+// If requested, it calls WalkUpFrom* for the Type in the given TypeLoc,
+// in addition to WalkUpFrom* for the TypeLoc itself, such that existing
 // clients that override the WalkUpFrom*Type() and/or Visit*Type() methods
 // continue to work.
 #define DEF_TRAVERSE_TYPELOC(TYPE, CODE)                                \
@@ -1022,7 +1166,7 @@
     if (TL.getQualifierLoc()) {
       TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
     }
-   =20
+
     for (unsigned I =3D 0, E =3D TL.getNumArgs(); I !=3D E; ++I) {
       TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
     }
@@ -1099,6 +1243,8 @@
     TRY_TO(TraverseStmt(D->getAsmString()));
   })
=20
+DEF_TRAVERSE_DECL(ImportDecl, { })
+
 DEF_TRAVERSE_DECL(FriendDecl, {
     // Friend is either decl or a type.
     if (D->getFriendType())
@@ -1128,14 +1274,6 @@
=20
 DEF_TRAVERSE_DECL(LinkageSpecDecl, { })
=20
-DEF_TRAVERSE_DECL(ObjCClassDecl, {
-    // FIXME: implement this
-  })
-
-DEF_TRAVERSE_DECL(ObjCForwardProtocolDecl, {
-    // FIXME: implement this
-  })
-
 DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, {
     // FIXME: implement this
   })
@@ -1164,8 +1302,8 @@
 DEF_TRAVERSE_DECL(LabelDecl, {
   // There is no code in a LabelDecl.
 })
- =20
- =20
+
+
 DEF_TRAVERSE_DECL(NamespaceDecl, {
     // Code in an unnamed namespace shows up automatically in
     // decls_begin()/decls_end().  Thus we don't need to recurse on
@@ -1216,6 +1354,7 @@
=20
 DEF_TRAVERSE_DECL(UsingDecl, {
     TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
+    TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
   })
=20
 DEF_TRAVERSE_DECL(UsingDirectiveDecl, {
@@ -1312,7 +1451,8 @@
 bool RecursiveASTVisitor<Derived>::TraverseFunctionInstantiations(
   FunctionTemplateDecl* D) {
   FunctionTemplateDecl::spec_iterator end =3D D->spec_end();
-  for (FunctionTemplateDecl::spec_iterator it =3D D->spec_begin(); it !=3D=
 end; ++it) {
+  for (FunctionTemplateDecl::spec_iterator it =3D D->spec_begin(); it !=3D=
 end;
+       ++it) {
     FunctionDecl* FD =3D *it;
     switch (FD->getTemplateSpecializationKind()) {
     case TSK_ImplicitInstantiation:
@@ -1329,8 +1469,6 @@
     case TSK_Undeclared:           // Declaration of the template definiti=
on.
     case TSK_ExplicitSpecialization:
       break;
-    default:
-      llvm_unreachable("Unknown specialization kind.");
     }
   }
=20
@@ -1511,6 +1649,7 @@
     // Like UnresolvedUsingTypenameDecl, but without the 'typename':
     //    template <class T> Class A : public Base<T> { using Base<T>::foo=
; };
     TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
+    TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
   })
=20
 DEF_TRAVERSE_DECL(IndirectFieldDecl, {})
@@ -1529,6 +1668,8 @@
     TRY_TO(TraverseDeclaratorHelper(D));
     if (D->isBitField())
       TRY_TO(TraverseStmt(D->getBitWidth()));
+    else if (D->hasInClassInitializer())
+      TRY_TO(TraverseStmt(D->getInClassInitializer()));
   })
=20
 DEF_TRAVERSE_DECL(ObjCAtDefsFieldDecl, {
@@ -1548,6 +1689,7 @@
 template<typename Derived>
 bool RecursiveASTVisitor<Derived>::TraverseFunctionHelper(FunctionDecl *D)=
 {
   TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
+  TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
=20
   // If we're an explicit template specialization, iterate over the
   // template args that were explicitly specified.  If we were doing
@@ -1624,7 +1766,9 @@
 template<typename Derived>
 bool RecursiveASTVisitor<Derived>::TraverseVarHelper(VarDecl *D) {
   TRY_TO(TraverseDeclaratorHelper(D));
-  TRY_TO(TraverseStmt(D->getInit()));
+  // Default params are taken care of when we traverse the ParmVarDecl.
+  if (!isa<ParmVarDecl>(D))
+    TRY_TO(TraverseStmt(D->getInit()));
   return true;
 }
=20
@@ -1735,6 +1879,10 @@
 DEF_TRAVERSE_STMT(ObjCForCollectionStmt, { })
 DEF_TRAVERSE_STMT(ObjCAutoreleasePoolStmt, { })
 DEF_TRAVERSE_STMT(CXXForRangeStmt, { })
+DEF_TRAVERSE_STMT(MSDependentExistsStmt, {
+    TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
+    TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
+})
 DEF_TRAVERSE_STMT(ReturnStmt, { })
 DEF_TRAVERSE_STMT(SwitchStmt, { })
 DEF_TRAVERSE_STMT(WhileStmt, { })
@@ -1742,6 +1890,7 @@
=20
 DEF_TRAVERSE_STMT(CXXDependentScopeMemberExpr, {
     TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
+    TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
     if (S->hasExplicitTemplateArgs()) {
       TRY_TO(TraverseTemplateArgumentLocsHelper(
           S->getTemplateArgs(), S->getNumTemplateArgs()));
@@ -1750,12 +1899,14 @@
=20
 DEF_TRAVERSE_STMT(DeclRefExpr, {
     TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
+    TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
     TRY_TO(TraverseTemplateArgumentLocsHelper(
         S->getTemplateArgs(), S->getNumTemplateArgs()));
   })
=20
 DEF_TRAVERSE_STMT(DependentScopeDeclRefExpr, {
     TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
+    TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
     if (S->hasExplicitTemplateArgs()) {
       TRY_TO(TraverseTemplateArgumentLocsHelper(
           S->getExplicitTemplateArgs().getTemplateArgs(),
@@ -1765,6 +1916,7 @@
=20
 DEF_TRAVERSE_STMT(MemberExpr, {
     TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
+    TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
     TRY_TO(TraverseTemplateArgumentLocsHelper(
         S->getTemplateArgs(), S->getNumTemplateArgs()));
   })
@@ -1831,6 +1983,23 @@
   return true;
 }
=20
+// PseudoObjectExpr is a special case because of the wierdness with
+// syntactic expressions and opaque values.
+template<typename Derived>
+bool RecursiveASTVisitor<Derived>::
+TraversePseudoObjectExpr(PseudoObjectExpr *S) {
+  TRY_TO(WalkUpFromPseudoObjectExpr(S));
+  TRY_TO(TraverseStmt(S->getSyntacticForm()));
+  for (PseudoObjectExpr::semantics_iterator
+         i =3D S->semantics_begin(), e =3D S->semantics_end(); i !=3D e; +=
+i) {
+    Expr *sub =3D *i;
+    if (OpaqueValueExpr *OVE =3D dyn_cast<OpaqueValueExpr>(sub))
+      sub =3D OVE->getSourceExpr();
+    TRY_TO(TraverseStmt(sub));
+  }
+  return true;
+}
+
 DEF_TRAVERSE_STMT(CXXScalarValueInitExpr, {
     // This is called for code like 'return T()' where T is a built-in
     // (i.e. non-class) type.
@@ -1880,6 +2049,11 @@
     TRY_TO(TraverseTypeLoc(S->getRhsTypeSourceInfo()->getTypeLoc()));
   })
=20
+DEF_TRAVERSE_STMT(TypeTraitExpr, {
+  for (unsigned I =3D 0, N =3D S->getNumArgs(); I !=3D N; ++I)
+    TRY_TO(TraverseTypeLoc(S->getArg(I)->getTypeLoc()));
+})
+
 DEF_TRAVERSE_STMT(ArrayTypeTraitExpr, {
     TRY_TO(TraverseTypeLoc(S->getQueriedTypeSourceInfo()->getTypeLoc()));
   })
@@ -1898,6 +2072,37 @@
     TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
   })
=20
+// Walk only the visible parts of lambda expressions. =20
+template<typename Derived>
+bool RecursiveASTVisitor<Derived>::TraverseLambdaExpr(LambdaExpr *S) {
+  for (LambdaExpr::capture_iterator C =3D S->explicit_capture_begin(),
+                                 CEnd =3D S->explicit_capture_end();
+       C !=3D CEnd; ++C) {
+    TRY_TO(TraverseLambdaCapture(*C));
+  }
+
+  if (S->hasExplicitParameters() || S->hasExplicitResultType()) {
+    TypeLoc TL =3D S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
+    if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
+      // Visit the whole type.
+      TRY_TO(TraverseTypeLoc(TL));
+    } else if (isa<FunctionProtoTypeLoc>(TL)) {
+      FunctionProtoTypeLoc Proto =3D cast<FunctionProtoTypeLoc>(TL);
+      if (S->hasExplicitParameters()) {
+        // Visit parameters.
+        for (unsigned I =3D 0, N =3D Proto.getNumArgs(); I !=3D N; ++I) {
+          TRY_TO(TraverseDecl(Proto.getArg(I)));
+        }
+      } else {
+        TRY_TO(TraverseTypeLoc(Proto.getResultLoc()));
+      }       =20
+    }
+  }
+
+  TRY_TO(TraverseStmt(S->getBody()));
+  return true;
+}
+
 DEF_TRAVERSE_STMT(CXXUnresolvedConstructExpr, {
     // This is called for code like 'T()', where T is a template argument.
     TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
@@ -1913,7 +2118,6 @@
 // over the children.
 DEF_TRAVERSE_STMT(AddrLabelExpr, { })
 DEF_TRAVERSE_STMT(ArraySubscriptExpr, { })
-DEF_TRAVERSE_STMT(BlockDeclRefExpr, { })
 DEF_TRAVERSE_STMT(BlockExpr, {
   TRY_TO(TraverseDecl(S->getBlockDecl()));
   return true; // no child statements to loop through.
@@ -1926,7 +2130,7 @@
 DEF_TRAVERSE_STMT(CXXDeleteExpr, { })
 DEF_TRAVERSE_STMT(ExprWithCleanups, { })
 DEF_TRAVERSE_STMT(CXXNullPtrLiteralExpr, { })
-DEF_TRAVERSE_STMT(CXXPseudoDestructorExpr, {=20
+DEF_TRAVERSE_STMT(CXXPseudoDestructorExpr, {
   TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
   if (TypeSourceInfo *ScopeInfo =3D S->getScopeTypeInfo())
     TRY_TO(TraverseTypeLoc(ScopeInfo->getTypeLoc()));
@@ -1935,15 +2139,18 @@
 })
 DEF_TRAVERSE_STMT(CXXThisExpr, { })
 DEF_TRAVERSE_STMT(CXXThrowExpr, { })
+DEF_TRAVERSE_STMT(UserDefinedLiteral, { })
 DEF_TRAVERSE_STMT(DesignatedInitExpr, { })
 DEF_TRAVERSE_STMT(ExtVectorElementExpr, { })
 DEF_TRAVERSE_STMT(GNUNullExpr, { })
 DEF_TRAVERSE_STMT(ImplicitValueInitExpr, { })
+DEF_TRAVERSE_STMT(ObjCBoolLiteralExpr, { })
 DEF_TRAVERSE_STMT(ObjCEncodeExpr, { })
 DEF_TRAVERSE_STMT(ObjCIsaExpr, { })
 DEF_TRAVERSE_STMT(ObjCIvarRefExpr, { })
 DEF_TRAVERSE_STMT(ObjCMessageExpr, { })
 DEF_TRAVERSE_STMT(ObjCPropertyRefExpr, { })
+DEF_TRAVERSE_STMT(ObjCSubscriptRefExpr, { })
 DEF_TRAVERSE_STMT(ObjCProtocolExpr, { })
 DEF_TRAVERSE_STMT(ObjCSelectorExpr, { })
 DEF_TRAVERSE_STMT(ObjCIndirectCopyRestoreExpr, { })
@@ -1958,15 +2165,15 @@
 DEF_TRAVERSE_STMT(UnresolvedLookupExpr, {
   TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
   if (S->hasExplicitTemplateArgs()) {
-    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),=20
+    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
                                               S->getNumTemplateArgs()));
   }
 })
- =20
+
 DEF_TRAVERSE_STMT(UnresolvedMemberExpr, {
   TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
   if (S->hasExplicitTemplateArgs()) {
-    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),=20
+    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
                                               S->getNumTemplateArgs()));
   }
 })
@@ -2001,6 +2208,9 @@
 DEF_TRAVERSE_STMT(ImaginaryLiteral, { })
 DEF_TRAVERSE_STMT(StringLiteral, { })
 DEF_TRAVERSE_STMT(ObjCStringLiteral, { })
+DEF_TRAVERSE_STMT(ObjCNumericLiteral, { })
+DEF_TRAVERSE_STMT(ObjCArrayLiteral, { })
+DEF_TRAVERSE_STMT(ObjCDictionaryLiteral, { })
  =20
 // Traverse OpenCL: AsType, Convert.
 DEF_TRAVERSE_STMT(AsTypeExpr, { })
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/Redeclarable.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/Redeclarable.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/Redeclarable.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -64,22 +64,22 @@
=20
   /// \brief Return the previous declaration of this declaration or NULL i=
f this
   /// is the first declaration.
-  decl_type *getPreviousDeclaration() {
+  decl_type *getPreviousDecl() {
     if (RedeclLink.NextIsPrevious())
       return RedeclLink.getNext();
     return 0;
   }
-  const decl_type *getPreviousDeclaration() const {
+  const decl_type *getPreviousDecl() const {
     return const_cast<decl_type *>(
-                 static_cast<const decl_type*>(this))->getPreviousDeclarat=
ion();
+                 static_cast<const decl_type*>(this))->getPreviousDecl();
   }
=20
   /// \brief Return the first declaration of this declaration or itself if=
 this
   /// is the only declaration.
   decl_type *getFirstDeclaration() {
     decl_type *D =3D static_cast<decl_type*>(this);
-    while (D->getPreviousDeclaration())
-      D =3D D->getPreviousDeclaration();
+    while (D->getPreviousDecl())
+      D =3D D->getPreviousDecl();
     return D;
   }
=20
@@ -87,8 +87,8 @@
   /// is the only declaration.
   const decl_type *getFirstDeclaration() const {
     const decl_type *D =3D static_cast<const decl_type*>(this);
-    while (D->getPreviousDeclaration())
-      D =3D D->getPreviousDeclaration();
+    while (D->getPreviousDecl())
+      D =3D D->getPreviousDecl();
     return D;
   }
=20
@@ -98,12 +98,12 @@
   }
=20
   /// \brief Returns the most recent (re)declaration of this declaration.
-  decl_type *getMostRecentDeclaration() {
+  decl_type *getMostRecentDecl() {
     return getFirstDeclaration()->RedeclLink.getNext();
   }
=20
   /// \brief Returns the most recent (re)declaration of this declaration.
-  const decl_type *getMostRecentDeclaration() const {
+  const decl_type *getMostRecentDecl() const {
     return getFirstDeclaration()->RedeclLink.getNext();
   }
  =20
@@ -116,6 +116,7 @@
     /// Current - The current declaration.
     decl_type *Current;
     decl_type *Starter;
+    bool PassedFirst;
=20
   public:
     typedef decl_type*                value_type;
@@ -125,13 +126,24 @@
     typedef std::ptrdiff_t            difference_type;
=20
     redecl_iterator() : Current(0) { }
-    explicit redecl_iterator(decl_type *C) : Current(C), Starter(C) { }
+    explicit redecl_iterator(decl_type *C)
+      : Current(C), Starter(C), PassedFirst(false) { }
=20
     reference operator*() const { return Current; }
     pointer operator->() const { return Current; }
=20
     redecl_iterator& operator++() {
       assert(Current && "Advancing while iterator has reached end");
+      // Sanity check to avoid infinite loop on invalid redecl chain.
+      if (Current->isFirstDeclaration()) {
+        if (PassedFirst) {
+          assert(0 && "Passed first decl twice, invalid redecl chain!");
+          Current =3D 0;
+          return *this;
+        }
+        PassedFirst =3D true;
+      }
+
       // Get either previous decl or latest decl.
       decl_type *Next =3D Current->RedeclLink.getNext();
       Current =3D (Next !=3D Starter ? Next : 0);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/Stmt.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/Stmt.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/Stmt.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -20,8 +20,9 @@
 #include "clang/AST/StmtIterator.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/AST/ASTContext.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/raw_ostream.h"
-#include "llvm/ADT/SmallVector.h"
 #include <string>
=20
 namespace llvm {
@@ -39,11 +40,11 @@
   class StringLiteral;
   class SwitchStmt;
=20
-  //=3D=3D=3D-------------------------------------------------------------=
---------=3D=3D=3D//
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // ExprIterator - Iterators for iterating over Stmt* arrays that contain
   //  only Expr*.  This is needed because AST nodes use Stmt* arrays to st=
ore
   //  references to children (to be compatible with StmtIterator).
-  //=3D=3D=3D-------------------------------------------------------------=
---------=3D=3D=3D//
+  //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
=20
   class Stmt;
   class Expr;
@@ -141,11 +142,14 @@
     friend class CallExpr; // ctor
     friend class OffsetOfExpr; // ctor
     friend class ObjCMessageExpr; // ctor
+    friend class ObjCArrayLiteral; // ctor
+    friend class ObjCDictionaryLiteral; // ctor
     friend class ShuffleVectorExpr; // ctor
     friend class ParenListExpr; // ctor
     friend class CXXUnresolvedConstructExpr; // ctor
     friend class CXXDependentScopeMemberExpr; // ctor
     friend class OverloadExpr; // ctor
+    friend class PseudoObjectExpr; // ctor
     friend class AtomicExpr; // ctor
     unsigned : NumStmtBits;
=20
@@ -158,15 +162,39 @@
   };
   enum { NumExprBits =3D 16 };
=20
+  class CharacterLiteralBitfields {
+    friend class CharacterLiteral;
+    unsigned : NumExprBits;
+
+    unsigned Kind : 2;
+  };
+
+  class FloatingLiteralBitfields {
+    friend class FloatingLiteral;
+    unsigned : NumExprBits;
+
+    unsigned IsIEEE : 1; // Distinguishes between PPC128 and IEEE128.
+    unsigned IsExact : 1;
+  };
+
+  class UnaryExprOrTypeTraitExprBitfields {
+    friend class UnaryExprOrTypeTraitExpr;
+    unsigned : NumExprBits;
+
+    unsigned Kind : 2;
+    unsigned IsType : 1; // true if operand is a type, false if an express=
ion.
+  };
+
   class DeclRefExprBitfields {
     friend class DeclRefExpr;
     friend class ASTStmtReader; // deserialization
     unsigned : NumExprBits;
=20
     unsigned HasQualifier : 1;
-    unsigned HasExplicitTemplateArgs : 1;
+    unsigned HasTemplateKWAndArgsInfo : 1;
     unsigned HasFoundDecl : 1;
     unsigned HadMultipleCandidates : 1;
+    unsigned RefersToEnclosingLocal : 1;
   };
=20
   class CastExprBitfields {
@@ -184,6 +212,27 @@
     unsigned NumPreArgs : 1;
   };
=20
+  class ExprWithCleanupsBitfields {
+    friend class ExprWithCleanups;
+    friend class ASTStmtReader; // deserialization
+
+    unsigned : NumExprBits;
+
+    unsigned NumObjects : 32 - NumExprBits;
+  };
+
+  class PseudoObjectExprBitfields {
+    friend class PseudoObjectExpr;
+    friend class ASTStmtReader; // deserialization
+
+    unsigned : NumExprBits;
+
+    // These don't need to be particularly wide, because they're
+    // strictly limited by the forms of expressions we permit.
+    unsigned NumSubExprs : 8;
+    unsigned ResultIndex : 32 - 8 - NumExprBits;
+  };
+
   class ObjCIndirectCopyRestoreExprBitfields {
     friend class ObjCIndirectCopyRestoreExpr;
     unsigned : NumExprBits;
@@ -191,6 +240,38 @@
     unsigned ShouldCopy : 1;
   };
=20
+  class InitListExprBitfields {
+    friend class InitListExpr;
+
+    unsigned : NumExprBits;
+
+    /// Whether this initializer list originally had a GNU array-range
+    /// designator in it. This is a temporary marker used by CodeGen.
+    unsigned HadArrayRangeDesignator : 1;
+
+    /// Whether this initializer list initializes a std::initializer_list
+    /// object.
+    unsigned InitializesStdInitializerList : 1;
+  };
+
+  class TypeTraitExprBitfields {
+    friend class TypeTraitExpr;
+    friend class ASTStmtReader;
+    friend class ASTStmtWriter;
+   =20
+    unsigned : NumExprBits;
+   =20
+    /// \brief The kind of type trait, which is a value of a TypeTrait enu=
merator.
+    unsigned Kind : 8;
+   =20
+    /// \brief If this expression is not value-dependent, this indicates w=
hether
+    /// the trait evaluated true or false.
+    unsigned Value : 1;
+
+    /// \brief The number of arguments to this type trait.
+    unsigned NumArgs : 32 - 8 - 1 - NumExprBits;
+  };
+ =20
   union {
     // FIXME: this is wasteful on 64-bit platforms.
     void *Aligner;
@@ -198,13 +279,21 @@
     StmtBitfields StmtBits;
     CompoundStmtBitfields CompoundStmtBits;
     ExprBitfields ExprBits;
+    CharacterLiteralBitfields CharacterLiteralBits;
+    FloatingLiteralBitfields FloatingLiteralBits;
+    UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits;
     DeclRefExprBitfields DeclRefExprBits;
     CastExprBitfields CastExprBits;
     CallExprBitfields CallExprBits;
+    ExprWithCleanupsBitfields ExprWithCleanupsBits;
+    PseudoObjectExprBitfields PseudoObjectExprBits;
     ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
+    InitListExprBitfields InitListExprBits;
+    TypeTraitExprBitfields TypeTraitExprBits;
   };
=20
   friend class ASTStmtReader;
+  friend class ASTStmtWriter;
=20
 public:
   // Only allow allocation of Stmts using the allocator in ASTContext
@@ -234,20 +323,24 @@
   /// de-serialization).
   struct EmptyShell { };
=20
+private:
+  /// \brief Whether statistic collection is enabled.
+  static bool StatisticsEnabled;
+
 protected:
   /// \brief Construct an empty statement.
   explicit Stmt(StmtClass SC, EmptyShell) {
     StmtBits.sClass =3D SC;
-    if (Stmt::CollectingStats()) Stmt::addStmtClass(SC);
+    if (StatisticsEnabled) Stmt::addStmtClass(SC);
   }
=20
 public:
   Stmt(StmtClass SC) {
     StmtBits.sClass =3D SC;
-    if (Stmt::CollectingStats()) Stmt::addStmtClass(SC);
+    if (StatisticsEnabled) Stmt::addStmtClass(SC);
   }
=20
-  StmtClass getStmtClass() const {=20
+  StmtClass getStmtClass() const {
     return static_cast<StmtClass>(StmtBits.sClass);
   }
   const char *getStmtClassName() const;
@@ -255,21 +348,20 @@
   /// SourceLocation tokens are not useful in isolation - they are low lev=
el
   /// value objects created/interpreted by SourceManager. We assume AST
   /// clients will have a pointer to the respective SourceManager.
-  SourceRange getSourceRange() const;
-
-  SourceLocation getLocStart() const { return getSourceRange().getBegin();=
 }
-  SourceLocation getLocEnd() const { return getSourceRange().getEnd(); }
+  SourceRange getSourceRange() const LLVM_READONLY;
+  SourceLocation getLocStart() const LLVM_READONLY;
+  SourceLocation getLocEnd() const LLVM_READONLY;
=20
   // global temp stats (until we have a per-module visitor)
   static void addStmtClass(const StmtClass s);
-  static bool CollectingStats(bool Enable =3D false);
+  static void EnableStatistics();
   static void PrintStats();
=20
   /// dump - This does a local dump of the specified AST fragment.  It dum=
ps the
   /// specified node and a few nodes underneath it, but not the whole subt=
ree.
   /// This is useful in a debugger.
-  void dump() const;
-  void dump(SourceManager &SM) const;
+  LLVM_ATTRIBUTE_USED void dump() const;
+  LLVM_ATTRIBUTE_USED void dump(SourceManager &SM) const;
   void dump(raw_ostream &OS, SourceManager &SM) const;
=20
   /// dumpAll - This does a dump of the specified AST fragment and all sub=
trees.
@@ -384,7 +476,7 @@
   SourceLocation getEndLoc() const { return EndLoc; }
   void setEndLoc(SourceLocation L) { EndLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(StartLoc, EndLoc);
   }
=20
@@ -433,7 +525,7 @@
=20
   bool hasLeadingEmptyMacro() const { return HasLeadingEmptyMacro; }
=20
-  SourceRange getSourceRange() const { return SourceRange(SemiLoc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Se=
miLoc); }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D NullStmtClass;
@@ -483,7 +575,7 @@
   body_iterator body_begin() { return Body; }
   body_iterator body_end() { return Body + size(); }
   Stmt *body_back() { return !body_empty() ? Body[size()-1] : 0; }
- =20
+
   void setLastStmt(Stmt *S) {
     assert(!body_empty() && "setLastStmt");
     Body[size()-1] =3D S;
@@ -513,7 +605,7 @@
     return const_reverse_body_iterator(body_begin());
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(LBracLoc, RBracLoc);
   }
=20
@@ -531,7 +623,7 @@
   child_range children() {
     return child_range(&Body[0], &Body[0]+CompoundStmtBits.NumStmts);
   }
- =20
+
   const_child_range children() const {
     return child_range(&Body[0], &Body[0]+CompoundStmtBits.NumStmts);
   }
@@ -558,7 +650,7 @@
     return const_cast<SwitchCase*>(this)->getSubStmt();
   }
=20
-  SourceRange getSourceRange() const { return SourceRange(); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange();=
 }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D CaseStmtClass ||
@@ -613,7 +705,7 @@
   void setRHS(Expr *Val) { SubExprs[RHS] =3D reinterpret_cast<Stmt*>(Val);=
 }
=20
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     // Handle deeply nested case statements with iteration instead of recu=
rsion.
     const CaseStmt *CS =3D this;
     while (const CaseStmt *CS2 =3D dyn_cast<CaseStmt>(CS->getSubStmt()))
@@ -653,7 +745,7 @@
   SourceLocation getColonLoc() const { return ColonLoc; }
   void setColonLoc(SourceLocation L) { ColonLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(DefaultLoc, SubStmt->getLocEnd());
   }
   static bool classof(const Stmt *T) {
@@ -665,7 +757,7 @@
   child_range children() { return child_range(&SubStmt, &SubStmt+1); }
 };
=20
- =20
+
 /// LabelStmt - Represents a label, which has a substatement.  For example:
 ///    foo: return;
 ///
@@ -690,7 +782,7 @@
   void setIdentLoc(SourceLocation L) { IdentLoc =3D L; }
   void setSubStmt(Stmt *SS) { SubStmt =3D SS; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(IdentLoc, SubStmt->getLocEnd());
   }
   child_range children() { return child_range(&SubStmt, &SubStmt+1); }
@@ -710,11 +802,11 @@
=20
   SourceLocation IfLoc;
   SourceLocation ElseLoc;
- =20
+
 public:
-  IfStmt(ASTContext &C, SourceLocation IL, VarDecl *var, Expr *cond,=20
+  IfStmt(ASTContext &C, SourceLocation IL, VarDecl *var, Expr *cond,
          Stmt *then, SourceLocation EL =3D SourceLocation(), Stmt *elsev =
=3D 0);
- =20
+
   /// \brief Build an empty if/then/else statement
   explicit IfStmt(EmptyShell Empty) : Stmt(IfStmtClass, Empty) { }
=20
@@ -728,13 +820,13 @@
   /// \endcode
   VarDecl *getConditionVariable() const;
   void setConditionVariable(ASTContext &C, VarDecl *V);
- =20
+
   /// If this IfStmt has a condition variable, return the faux DeclStmt
   /// associated with the creation of that condition variable.
   const DeclStmt *getConditionVariableDeclStmt() const {
     return reinterpret_cast<DeclStmt*>(SubExprs[VAR]);
   }
- =20
+
   const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[CO=
ND]);}
   void setCond(Expr *E) { SubExprs[COND] =3D reinterpret_cast<Stmt *>(E); }
   const Stmt *getThen() const { return SubExprs[THEN]; }
@@ -751,7 +843,7 @@
   SourceLocation getElseLoc() const { return ElseLoc; }
   void setElseLoc(SourceLocation L) { ElseLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     if (SubExprs[ELSE])
       return SourceRange(IfLoc, SubExprs[ELSE]->getLocEnd());
     else
@@ -801,7 +893,7 @@
   /// \endcode
   VarDecl *getConditionVariable() const;
   void setConditionVariable(ASTContext &C, VarDecl *V);
- =20
+
   /// If this SwitchStmt has a condition variable, return the faux DeclStmt
   /// associated with the creation of that condition variable.
   const DeclStmt *getConditionVariableDeclStmt() const {
@@ -832,7 +924,8 @@
     SwitchLoc =3D SL;
   }
   void addSwitchCase(SwitchCase *SC) {
-    assert(!SC->getNextSwitchCase() && "case/default already added to a sw=
itch");
+    assert(!SC->getNextSwitchCase()
+           && "case/default already added to a switch");
     SC->setNextSwitchCase(FirstCase);
     FirstCase =3D SC;
   }
@@ -849,7 +942,7 @@
     return (bool) AllEnumCasesCovered;
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(SwitchLoc, SubExprs[BODY]->getLocEnd());
   }
   // Iterators
@@ -871,7 +964,7 @@
   Stmt* SubExprs[END_EXPR];
   SourceLocation WhileLoc;
 public:
-  WhileStmt(ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body,=20
+  WhileStmt(ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body,
             SourceLocation WL);
=20
   /// \brief Build an empty while statement.
@@ -904,7 +997,7 @@
   SourceLocation getWhileLoc() const { return WhileLoc; }
   void setWhileLoc(SourceLocation L) { WhileLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(WhileLoc, SubExprs[BODY]->getLocEnd());
   }
   static bool classof(const Stmt *T) {
@@ -953,7 +1046,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(DoLoc, RParenLoc);
   }
   static bool classof(const Stmt *T) {
@@ -979,14 +1072,14 @@
   SourceLocation LParenLoc, RParenLoc;
=20
 public:
-  ForStmt(ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, Expr *I=
nc,=20
+  ForStmt(ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar, Expr *I=
nc,
           Stmt *Body, SourceLocation FL, SourceLocation LP, SourceLocation=
 RP);
=20
   /// \brief Build an empty for statement.
   explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) { }
=20
   Stmt *getInit() { return SubExprs[INIT]; }
- =20
+
   /// \brief Retrieve the variable declared in this "for" statement, if an=
y.
   ///
   /// In the following example, "y" is the condition variable.
@@ -997,7 +1090,7 @@
   /// \endcode
   VarDecl *getConditionVariable() const;
   void setConditionVariable(ASTContext &C, VarDecl *V);
- =20
+
   /// If this ForStmt has a condition variable, return the faux DeclStmt
   /// associated with the creation of that condition variable.
   const DeclStmt *getConditionVariableDeclStmt() const {
@@ -1025,7 +1118,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation L) { RParenLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd());
   }
   static bool classof(const Stmt *T) {
@@ -1060,7 +1153,7 @@
   SourceLocation getLabelLoc() const { return LabelLoc; }
   void setLabelLoc(SourceLocation L) { LabelLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(GotoLoc, LabelLoc);
   }
   static bool classof(const Stmt *T) {
@@ -1104,7 +1197,7 @@
     return const_cast<IndirectGotoStmt*>(this)->getConstantTarget();
   }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(GotoLoc, Target->getLocEnd());
   }
=20
@@ -1131,7 +1224,7 @@
   SourceLocation getContinueLoc() const { return ContinueLoc; }
   void setContinueLoc(SourceLocation L) { ContinueLoc =3D L; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(ContinueLoc);
   }
=20
@@ -1157,7 +1250,7 @@
   SourceLocation getBreakLoc() const { return BreakLoc; }
   void setBreakLoc(SourceLocation L) { BreakLoc =3D L; }
=20
-  SourceRange getSourceRange() const { return SourceRange(BreakLoc); }
+  SourceRange getSourceRange() const LLVM_READONLY { return SourceRange(Br=
eakLoc); }
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D BreakStmtClass;
@@ -1182,7 +1275,7 @@
   Stmt *RetExpr;
   SourceLocation RetLoc;
   const VarDecl *NRVOCandidate;
- =20
+
 public:
   ReturnStmt(SourceLocation RL)
     : Stmt(ReturnStmtClass), RetExpr(0), RetLoc(RL), NRVOCandidate(0) { }
@@ -1208,8 +1301,8 @@
   /// also marked as an NRVO object.
   const VarDecl *getNRVOCandidate() const { return NRVOCandidate; }
   void setNRVOCandidate(const VarDecl *Var) { NRVOCandidate =3D Var; }
- =20
-  SourceRange getSourceRange() const;
+
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D ReturnStmtClass;
@@ -1242,16 +1335,16 @@
   StringLiteral **Constraints;
   Stmt **Exprs;
   StringLiteral **Clobbers;
- =20
+
 public:
-  AsmStmt(ASTContext &C, SourceLocation asmloc, bool issimple, bool isvola=
tile,=20
+  AsmStmt(ASTContext &C, SourceLocation asmloc, bool issimple, bool isvola=
tile,
           bool msasm, unsigned numoutputs, unsigned numinputs,
           IdentifierInfo **names, StringLiteral **constraints,
           Expr **exprs, StringLiteral *asmstr, unsigned numclobbers,
           StringLiteral **clobbers, SourceLocation rparenloc);
=20
   /// \brief Build an empty inline-assembly statement.
-  explicit AsmStmt(EmptyShell Empty) : Stmt(AsmStmtClass, Empty),=20
+  explicit AsmStmt(EmptyShell Empty) : Stmt(AsmStmtClass, Empty),
     Names(0), Constraints(0), Exprs(0), Clobbers(0) { }
=20
   SourceLocation getAsmLoc() const { return AsmLoc; }
@@ -1333,7 +1426,7 @@
   StringRef getOutputName(unsigned i) const {
     if (IdentifierInfo *II =3D getOutputIdentifier(i))
       return II->getName();
-   =20
+
     return StringRef();
   }
=20
@@ -1394,7 +1487,7 @@
=20
   Expr *getInputExpr(unsigned i);
   void setInputExpr(unsigned i, Expr *E);
- =20
+
   const Expr *getInputExpr(unsigned i) const {
     return const_cast<AsmStmt*>(this)->getInputExpr(i);
   }
@@ -1404,7 +1497,7 @@
                                       StringLiteral **Constraints,
                                       Stmt **Exprs,
                                       unsigned NumOutputs,
-                                      unsigned NumInputs,                 =
                    =20
+                                      unsigned NumInputs,
                                       StringLiteral **Clobbers,
                                       unsigned NumClobbers);
=20
@@ -1419,7 +1512,7 @@
   StringLiteral *getClobber(unsigned i) { return Clobbers[i]; }
   const StringLiteral *getClobber(unsigned i) const { return Clobbers[i]; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AsmLoc, RParenLoc);
   }
=20
@@ -1490,15 +1583,20 @@
                                SourceLocation ExceptLoc,
                                Expr *FilterExpr,
                                Stmt *Block);
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getExceptLoc(), getEndLoc());
   }
=20
   SourceLocation getExceptLoc() const { return Loc; }
   SourceLocation getEndLoc() const { return getBlock()->getLocEnd(); }
=20
-  Expr *getFilterExpr() const { return reinterpret_cast<Expr*>(Children[FI=
LTER_EXPR]); }
-  CompoundStmt *getBlock() const { return llvm::cast<CompoundStmt>(Childre=
n[BLOCK]); }
+  Expr *getFilterExpr() const {
+    return reinterpret_cast<Expr*>(Children[FILTER_EXPR]);
+  }
+
+  CompoundStmt *getBlock() const {
+    return llvm::cast<CompoundStmt>(Children[BLOCK]);
+  }
=20
   child_range children() {
     return child_range(Children,Children+2);
@@ -1528,7 +1626,7 @@
                                 SourceLocation FinallyLoc,
                                 Stmt *Block);
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getFinallyLoc(), getEndLoc());
   }
=20
@@ -1572,7 +1670,7 @@
                             Stmt *TryBlock,
                             Stmt *Handler);
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getTryLoc(), getEndLoc());
   }
=20
@@ -1580,7 +1678,11 @@
   SourceLocation getEndLoc() const { return Children[HANDLER]->getLocEnd()=
; }
=20
   bool getIsCXXTry() const { return IsCXXTry; }
-  CompoundStmt* getTryBlock() const { return llvm::cast<CompoundStmt>(Chil=
dren[TRY]); }
+
+  CompoundStmt* getTryBlock() const {
+    return llvm::cast<CompoundStmt>(Children[TRY]);
+  }
+
   Stmt *getHandler() const { return Children[HANDLER]; }
=20
   /// Returns 0 if not defined
@@ -1596,7 +1698,6 @@
   }
=20
   static bool classof(SEHTryStmt *) { return true; }
-
 };
=20
 }  // end namespace clang
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/StmtCXX.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/StmtCXX.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/StmtCXX.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #define LLVM_CLANG_AST_STMTCXX_H
=20
 #include "clang/AST/Stmt.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
=20
@@ -37,7 +38,7 @@
   CXXCatchStmt(EmptyShell Empty)
   : Stmt(CXXCatchStmtClass), ExceptionDecl(0), HandlerBlock(0) {}
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(CatchLoc, HandlerBlock->getLocEnd());
   }
=20
@@ -83,7 +84,7 @@
   static CXXTryStmt *Create(ASTContext &C, EmptyShell Empty,
                             unsigned numHandlers);
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getTryLoc(), getEndLoc());
   }
=20
@@ -148,7 +149,9 @@
=20
=20
   DeclStmt *getRangeStmt() { return cast<DeclStmt>(SubExprs[RANGE]); }
-  DeclStmt *getBeginEndStmt() { return cast_or_null<DeclStmt>(SubExprs[BEG=
INEND]); }
+  DeclStmt *getBeginEndStmt() {
+    return cast_or_null<DeclStmt>(SubExprs[BEGINEND]);
+  }
   Expr *getCond() { return cast_or_null<Expr>(SubExprs[COND]); }
   Expr *getInc() { return cast_or_null<Expr>(SubExprs[INC]); }
   DeclStmt *getLoopVarStmt() { return cast<DeclStmt>(SubExprs[LOOPVAR]); }
@@ -187,7 +190,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation Loc) { RParenLoc =3D Loc; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd());
   }
   static bool classof(const Stmt *T) {
@@ -201,6 +204,91 @@
   }
 };
=20
+/// \brief Representation of a Microsoft __if_exists or __if_not_exists
+/// statement with a dependent name.
+///
+/// The __if_exists statement can be used to include a sequence of stateme=
nts
+/// in the program only when a particular dependent name does not exist. F=
or
+/// example:
+///
+/// \code
+/// template<typename T>
+/// void call_foo(T &t) {
+///   __if_exists (T::foo) {
+///     t.foo(); // okay: only called when T::foo exists.
+///   }
+/// }
+/// \endcode
+///
+/// Similarly, the __if_not_exists statement can be used to include the
+/// statements when a particular name does not exist.
+///
+/// Note that this statement only captures __if_exists and __if_not_exists
+/// statements whose name is dependent. All non-dependent cases are handled
+/// directly in the parser, so that they don't introduce a new scope. Clang
+/// introduces scopes in the dependent case to keep names inside the compo=
und
+/// statement from leaking out into the surround statements, which would
+/// compromise the template instantiation model. This behavior differs from
+/// Visual C++ (which never introduces a scope), but is a fairly reasonable
+/// approximation of the VC++ behavior.
+class MSDependentExistsStmt : public Stmt {
+  SourceLocation KeywordLoc;
+  bool IsIfExists;
+  NestedNameSpecifierLoc QualifierLoc;
+  DeclarationNameInfo NameInfo;
+  Stmt *SubStmt;
+
+  friend class ASTReader;
+  friend class ASTStmtReader;
+
+public:
+  MSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists,
+                        NestedNameSpecifierLoc QualifierLoc,
+                        DeclarationNameInfo NameInfo,
+                        CompoundStmt *SubStmt)
+  : Stmt(MSDependentExistsStmtClass),
+    KeywordLoc(KeywordLoc), IsIfExists(IsIfExists),
+    QualifierLoc(QualifierLoc), NameInfo(NameInfo),
+    SubStmt(reinterpret_cast<Stmt *>(SubStmt)) { }
+
+  /// \brief Retrieve the location of the __if_exists or __if_not_exists
+  /// keyword.
+  SourceLocation getKeywordLoc() const { return KeywordLoc; }
+
+  /// \brief Determine whether this is an __if_exists statement.
+  bool isIfExists() const { return IsIfExists; }
+
+  /// \brief Determine whether this is an __if_exists statement.
+  bool isIfNotExists() const { return !IsIfExists; }
+
+  /// \brief Retrieve the nested-name-specifier that qualifies this name, =
if
+  /// any.
+  NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
+
+  /// \brief Retrieve the name of the entity we're testing for, along with
+  /// location information
+  DeclarationNameInfo getNameInfo() const { return NameInfo; }
+
+  /// \brief Retrieve the compound statement that will be included in the
+  /// program only if the existence of the symbol matches the initial keyw=
ord.
+  CompoundStmt *getSubStmt() const {
+    return reinterpret_cast<CompoundStmt *>(SubStmt);
+  }
+
+  SourceRange getSourceRange() const LLVM_READONLY {
+    return SourceRange(KeywordLoc, SubStmt->getLocEnd());
+  }
+
+  child_range children() {
+    return child_range(&SubStmt, &SubStmt+1);
+  }
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() =3D=3D MSDependentExistsStmtClass;
+  }
+
+  static bool classof(MSDependentExistsStmt *) { return true; }
+};
=20
 }  // end namespace clang
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/StmtIterator.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/StmtIterator.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/StmtIterator.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -90,14 +90,12 @@
   StmtIteratorImpl(const VariableArrayType *t) : StmtIteratorBase(t) {}
=20
   DERIVED& operator++() {
-    if (inDecl() || inDeclGroup()) {
-      if (getVAPtr()) NextVA();
-      else NextDecl();
-    }
-    else if (inSizeOfTypeVA())
+    if (inStmt())
+      ++stmt;
+    else if (getVAPtr())
       NextVA();
     else
-      ++stmt;
+      NextDecl();
=20
     return static_cast<DERIVED&>(*this);
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/StmtObjC.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/StmtObjC.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/StmtObjC.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #define LLVM_CLANG_AST_STMTOBJC_H
=20
 #include "clang/AST/Stmt.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
=20
@@ -55,7 +56,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation Loc) { RParenLoc =3D Loc; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(ForLoc, SubExprs[BODY]->getLocEnd());
   }
   static bool classof(const Stmt *T) {
@@ -103,7 +104,7 @@
   SourceLocation getRParenLoc() const { return RParenLoc; }
   void setRParenLoc(SourceLocation Loc) { RParenLoc =3D Loc; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtCatchLoc, Body->getLocEnd());
   }
=20
@@ -133,7 +134,7 @@
   Stmt *getFinallyBody() { return AtFinallyStmt; }
   void setFinallyBody(Stmt *S) { AtFinallyStmt =3D S; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtFinallyLoc, AtFinallyStmt->getLocEnd());
   }
=20
@@ -240,7 +241,7 @@
     getStmts()[1 + NumCatchStmts] =3D S;=20
   }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   static bool classof(const Stmt *T) {
     return T->getStmtClass() =3D=3D ObjCAtTryStmtClass;
@@ -294,7 +295,7 @@
   }
   void setSynchExpr(Stmt *S) { SubStmts[SYNC_EXPR] =3D S; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtSynchronizedLoc, getSynchBody()->getLocEnd());
   }
=20
@@ -327,7 +328,7 @@
   SourceLocation getThrowLoc() { return AtThrowLoc; }
   void setThrowLoc(SourceLocation Loc) { AtThrowLoc =3D Loc; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     if (Throw)
       return SourceRange(AtThrowLoc, Throw->getLocEnd());
     else
@@ -360,7 +361,7 @@
   Stmt *getSubStmt() { return SubStmt; }
   void setSubStmt(Stmt *S) { SubStmt =3D S; }
=20
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(AtLoc, SubStmt->getLocEnd());
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/StmtVisitor.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/StmtVisitor.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/StmtVisitor.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -42,7 +42,6 @@
     // below.
     if (PTR(BinaryOperator) BinOp =3D dyn_cast<BinaryOperator>(S)) {
       switch (BinOp->getOpcode()) {
-      default: llvm_unreachable("Unknown binary operator!");
       case BO_PtrMemD:   DISPATCH(BinPtrMemD,   BinaryOperator);
       case BO_PtrMemI:   DISPATCH(BinPtrMemI,   BinaryOperator);
       case BO_Mul:       DISPATCH(BinMul,       BinaryOperator);
@@ -80,7 +79,6 @@
       }
     } else if (PTR(UnaryOperator) UnOp =3D dyn_cast<UnaryOperator>(S)) {
       switch (UnOp->getOpcode()) {
-      default: llvm_unreachable("Unknown unary operator!");
       case UO_PostInc:   DISPATCH(UnaryPostInc,   UnaryOperator);
       case UO_PostDec:   DISPATCH(UnaryPostDec,   UnaryOperator);
       case UO_PreInc:    DISPATCH(UnaryPreInc,    UnaryOperator);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/TemplateBase.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/TemplateBase.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/TemplateBase.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -15,11 +15,12 @@
 #ifndef LLVM_CLANG_AST_TEMPLATEBASE_H
 #define LLVM_CLANG_AST_TEMPLATEBASE_H
=20
+#include "clang/AST/Type.h"
+#include "clang/AST/TemplateName.h"
 #include "llvm/ADT/APSInt.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "clang/AST/Type.h"
-#include "clang/AST/TemplateName.h"
=20
 namespace llvm {
   class FoldingSetNodeID;
@@ -100,7 +101,6 @@
   /// declaration, which is either an external declaration or a
   /// template declaration.
   TemplateArgument(Decl *D) : Kind(Declaration) {
-    // FIXME: Need to be sure we have the "canonical" declaration!
     TypeOrValue =3D reinterpret_cast<uintptr_t>(D);
   }
=20
@@ -457,7 +457,7 @@
   }
=20
   /// \brief - Fetches the full source range of the argument.
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   const TemplateArgument &getArgument() const {
     return Argument;
@@ -589,7 +589,42 @@
                       bool &ContainsUnexpandedParameterPack);
   void copyInto(TemplateArgumentListInfo &List) const;
   static std::size_t sizeFor(unsigned NumTemplateArgs);
-  static std::size_t sizeFor(const TemplateArgumentListInfo &List);
+};
+
+/// \brief Extends ASTTemplateArgumentListInfo with the source location
+/// information for the template keyword; this is used as part of the
+/// representation of qualified identifiers, such as S<T>::template apply<=
T>.
+struct ASTTemplateKWAndArgsInfo : public ASTTemplateArgumentListInfo {
+  typedef ASTTemplateArgumentListInfo Base;
+
+  // NOTE: the source location of the (optional) template keyword is
+  // stored after all template arguments.
+
+  /// \brief Get the source location of the template keyword.
+  SourceLocation getTemplateKeywordLoc() const {
+    return *reinterpret_cast<const SourceLocation*>
+      (getTemplateArgs() + NumTemplateArgs);
+  }
+
+  /// \brief Sets the source location of the template keyword.
+  void setTemplateKeywordLoc(SourceLocation TemplateKWLoc) {
+    *reinterpret_cast<SourceLocation*>
+      (getTemplateArgs() + NumTemplateArgs) =3D TemplateKWLoc;
+  }
+
+  static const ASTTemplateKWAndArgsInfo*
+  Create(ASTContext &C, SourceLocation TemplateKWLoc,
+         const TemplateArgumentListInfo &List);
+
+  void initializeFrom(SourceLocation TemplateKWLoc,
+                      const TemplateArgumentListInfo &List);
+  void initializeFrom(SourceLocation TemplateKWLoc,
+                      const TemplateArgumentListInfo &List,
+                      bool &Dependent, bool &InstantiationDependent,
+                      bool &ContainsUnexpandedParameterPack);
+  void initializeFrom(SourceLocation TemplateKWLoc);
+
+  static std::size_t sizeFor(unsigned NumTemplateArgs);
 };
=20
 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/Type.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/Type.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/Type.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -95,7 +95,7 @@
   class ExtQualsTypeCommonBase;
   struct PrintingPolicy;
=20
-  template <typename> class CanQual; =20
+  template <typename> class CanQual;
   typedef CanQual<Type> CanQualType;
=20
   // Provide forward declarations for all of the *Type classes
@@ -236,7 +236,7 @@
     qs.removeObjCGCAttr();
     return qs;
   }
-  Qualifiers withoutObjCGLifetime() const {
+  Qualifiers withoutObjCLifetime() const {
     Qualifiers qs =3D *this;
     qs.removeObjCLifetime();
     return qs;
@@ -252,7 +252,8 @@
   void removeObjCLifetime() { setObjCLifetime(OCL_None); }
   void addObjCLifetime(ObjCLifetime type) {
     assert(type);
-    setObjCLifetime(type);
+    assert(!hasObjCLifetime());
+    Mask |=3D (type << LifetimeShift);
   }
=20
   /// True if the lifetime is neither None or ExplicitNone.
@@ -266,7 +267,7 @@
     ObjCLifetime lifetime =3D getObjCLifetime();
     return (lifetime =3D=3D OCL_Strong || lifetime =3D=3D OCL_Weak);
   }
- =20
+
   bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
   unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
   void setAddressSpace(unsigned space) {
@@ -346,7 +347,7 @@
   /// Generally this answers the question of whether an object with the ot=
her
   /// qualifiers can be safely used as an object with these qualifiers.
   bool compatiblyIncludes(Qualifiers other) const {
-    return=20
+    return
       // Address spaces must match exactly.
       getAddressSpace() =3D=3D other.getAddressSpace() &&
       // ObjC GC qualifiers can match, be added, or be removed, but can't =
be
@@ -363,24 +364,24 @@
   /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
   ///
   /// One set of Objective-C lifetime qualifiers compatibly includes the o=
ther
-  /// if the lifetime qualifiers match, or if both are non-__weak and the=20
+  /// if the lifetime qualifiers match, or if both are non-__weak and the
   /// including set also contains the 'const' qualifier.
   bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
     if (getObjCLifetime() =3D=3D other.getObjCLifetime())
       return true;
-   =20
+
     if (getObjCLifetime() =3D=3D OCL_Weak || other.getObjCLifetime() =3D=
=3D OCL_Weak)
       return false;
-   =20
+
     return hasConst();
   }
- =20
+
   bool isSupersetOf(Qualifiers Other) const;
=20
   /// \brief Determine whether this set of qualifiers is a strict superset=
 of
   /// another set of qualifiers, not considering qualifier compatibility.
   bool isStrictSupersetOf(Qualifiers Other) const;
- =20
+
   bool operator=3D=3D(Qualifiers Other) const { return Mask =3D=3D Other.M=
ask; }
   bool operator!=3D(Qualifiers Other) const { return Mask !=3D Other.Mask;=
 }
=20
@@ -397,7 +398,7 @@
     L +=3D R;
     return L;
   }
- =20
+
   Qualifiers &operator-=3D(Qualifiers R) {
     Mask =3D Mask & ~(R.Mask);
     return *this;
@@ -408,7 +409,7 @@
     L -=3D R;
     return L;
   }
- =20
+
   std::string getAsString() const;
   std::string getAsString(const PrintingPolicy &Policy) const {
     std::string Buffer;
@@ -447,7 +448,32 @@
   CC_AAPCS_VFP    // __attribute__((pcs("aapcs-vfp")))
 };
=20
-typedef std::pair<const Type*, Qualifiers> SplitQualType;
+/// A std::pair-like structure for storing a qualified type split
+/// into its local qualifiers and its locally-unqualified type.
+struct SplitQualType {
+  /// The locally-unqualified type.
+  const Type *Ty;
+
+  /// The local qualifiers.
+  Qualifiers Quals;
+
+  SplitQualType() : Ty(0), Quals() {}
+  SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
+
+  SplitQualType getSingleStepDesugaredType() const; // end of this file
+
+  // Make llvm::tie work.
+  operator std::pair<const Type *,Qualifiers>() const {
+    return std::pair<const Type *,Qualifiers>(Ty, Quals);
+  }
+
+  friend bool operator=3D=3D(SplitQualType a, SplitQualType b) {
+    return a.Ty =3D=3D b.Ty && a.Quals =3D=3D b.Quals;
+  }
+  friend bool operator!=3D(SplitQualType a, SplitQualType b) {
+    return a.Ty !=3D b.Ty || a.Quals !=3D b.Quals;
+  }
+};
=20
 /// QualType - For efficiency, we don't store CV-qualified types as nodes =
on
 /// their own: instead each reference to a type stores the qualifiers.  Th=
is
@@ -501,7 +527,7 @@
   /// This function requires that the type not be NULL. If the type might =
be
   /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
   const Type *getTypePtr() const;
- =20
+
   const Type *getTypePtrOrNull() const;
=20
   /// Retrieves a pointer to the name of the base type.
@@ -534,27 +560,27 @@
     return Value.getPointer().isNull();
   }
=20
-  /// \brief Determine whether this particular QualType instance has the=20
+  /// \brief Determine whether this particular QualType instance has the
   /// "const" qualifier set, without looking through typedefs that may have
   /// added "const" at a different level.
   bool isLocalConstQualified() const {
     return (getLocalFastQualifiers() & Qualifiers::Const);
   }
- =20
+
   /// \brief Determine whether this type is const-qualified.
   bool isConstQualified() const;
- =20
-  /// \brief Determine whether this particular QualType instance has the=20
+
+  /// \brief Determine whether this particular QualType instance has the
   /// "restrict" qualifier set, without looking through typedefs that may =
have
   /// added "restrict" at a different level.
   bool isLocalRestrictQualified() const {
     return (getLocalFastQualifiers() & Qualifiers::Restrict);
   }
- =20
+
   /// \brief Determine whether this type is restrict-qualified.
   bool isRestrictQualified() const;
- =20
-  /// \brief Determine whether this particular QualType instance has the=20
+
+  /// \brief Determine whether this particular QualType instance has the
   /// "volatile" qualifier set, without looking through typedefs that may =
have
   /// added "volatile" at a different level.
   bool isLocalVolatileQualified() const {
@@ -563,9 +589,9 @@
=20
   /// \brief Determine whether this type is volatile-qualified.
   bool isVolatileQualified() const;
- =20
+
   /// \brief Determine whether this particular QualType instance has any
-  /// qualifiers, without looking through any typedefs that might add=20
+  /// qualifiers, without looking through any typedefs that might add
   /// qualifiers at a different level.
   bool hasLocalQualifiers() const {
     return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
@@ -573,7 +599,7 @@
=20
   /// \brief Determine whether this type has any qualifiers.
   bool hasQualifiers() const;
- =20
+
   /// \brief Determine whether this particular QualType instance has any
   /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
   /// instance.
@@ -588,15 +614,15 @@
=20
   /// \brief Retrieve the set of qualifiers applied to this type.
   Qualifiers getQualifiers() const;
- =20
-  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers=20
+
+  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
   /// local to this particular QualType instance, not including any qualif=
iers
   /// acquired through typedefs or other sugar.
   unsigned getLocalCVRQualifiers() const {
     return getLocalFastQualifiers();
   }
=20
-  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers=20
+  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
   /// applied to this type.
   unsigned getCVRQualifiers() const;
=20
@@ -612,10 +638,10 @@
   /// compilation's language.
   /// (C++0x [basic.types]p9)
   bool isCXX11PODType(ASTContext &Context) const;
- =20
+
   /// isTrivialType - Return true if this is a trivial type
   /// (C++0x [basic.types]p9)
-  bool isTrivialType(ASTContext &Context) const; =20
+  bool isTrivialType(ASTContext &Context) const;
=20
   /// isTriviallyCopyableType - Return true if this is a trivially
   /// copyable type (C++0x [basic.types]p9)
@@ -624,7 +650,7 @@
   // Don't promise in the API that anything besides 'const' can be
   // easily added.
=20
-  /// addConst - add the specified type qualifier to this QualType. =20
+  /// addConst - add the specified type qualifier to this QualType.
   void addConst() {
     addFastQualifiers(Qualifiers::Const);
   }
@@ -632,13 +658,21 @@
     return withFastQualifiers(Qualifiers::Const);
   }
=20
-  /// addVolatile - add the specified type qualifier to this QualType. =20
+  /// addVolatile - add the specified type qualifier to this QualType.
   void addVolatile() {
     addFastQualifiers(Qualifiers::Volatile);
   }
   QualType withVolatile() const {
     return withFastQualifiers(Qualifiers::Volatile);
   }
+ =20
+  /// Add the restrict qualifier to this QualType.
+  void addRestrict() {
+    addFastQualifiers(Qualifiers::Restrict);
+  }
+  QualType withRestrict() const {
+    return withFastQualifiers(Qualifiers::Restrict);
+  }
=20
   QualType withCVRQualifiers(unsigned CVR) const {
     return withFastQualifiers(CVR);
@@ -719,7 +753,7 @@
   /// type.  To strip qualifiers even from within an array type, use
   /// ASTContext::getUnqualifiedArrayType.
   inline SplitQualType getSplitUnqualifiedType() const;
- =20
+
   /// \brief Determine whether this type is more qualified than the other
   /// given type, requiring exact equality for non-CVR qualifiers.
   bool isMoreQualifiedThan(QualType Other) const;
@@ -727,19 +761,19 @@
   /// \brief Determine whether this type is at least as qualified as the o=
ther
   /// given type, requiring exact equality for non-CVR qualifiers.
   bool isAtLeastAsQualifiedAs(QualType Other) const;
- =20
+
   QualType getNonReferenceType() const;
=20
   /// \brief Determine the type of a (typically non-lvalue) expression wit=
h the
   /// specified result type.
-  ///                      =20
+  ///
   /// This routine should be used for expressions for which the return typ=
e is
   /// explicitly specified (e.g., in a cast or call) and isn't necessarily
-  /// an lvalue. It removes a top-level reference (since there are no=20
+  /// an lvalue. It removes a top-level reference (since there are no
   /// expressions of reference type) and deletes top-level cvr-qualifiers
   /// from non-class types (in C++) or all types (in C).
   QualType getNonLValueExprType(ASTContext &Context) const;
- =20
+
   /// getDesugaredType - Return the specified type with any "sugar" remove=
d from
   /// the type.  This takes off typedefs, typeof's etc.  If the outer leve=
l of
   /// the type is already concrete, it returns it unmodified.  This is sim=
ilar
@@ -757,12 +791,14 @@
   }
=20
   /// \brief Return the specified type with one level of "sugar" removed f=
rom
-  /// the type.=20
+  /// the type.
   ///
   /// This routine takes off the first typedef, typeof, etc. If the outer =
level
   /// of the type is already concrete, it returns it unmodified.
-  QualType getSingleStepDesugaredType(const ASTContext &Context) const;
- =20
+  QualType getSingleStepDesugaredType(const ASTContext &Context) const {
+    return getSingleStepDesugaredTypeImpl(*this, Context);
+  }
+
   /// IgnoreParens - Returns the specified type after dropping any
   /// outer-level parentheses.
   QualType IgnoreParens() const {
@@ -783,7 +819,7 @@
     return getAsString(split());
   }
   static std::string getAsString(SplitQualType split) {
-    return getAsString(split.first, split.second);
+    return getAsString(split.Ty, split.Quals);
   }
   static std::string getAsString(const Type *ty, Qualifiers qs);
=20
@@ -798,7 +834,7 @@
   }
   static void getAsStringInternal(SplitQualType split, std::string &out,
                                   const PrintingPolicy &policy) {
-    return getAsStringInternal(split.first, split.second, out, policy);
+    return getAsStringInternal(split.Ty, split.Quals, out, policy);
   }
   static void getAsStringInternal(const Type *ty, Qualifiers qs,
                                   std::string &out,
@@ -855,7 +891,7 @@
     return isDestructedTypeImpl(*this);
   }
=20
-  /// \brief Determine whether expressions of the given type are forbidden=20
+  /// \brief Determine whether expressions of the given type are forbidden
   /// from being lvalues in C.
   ///
   /// The expression types that are forbidden to be lvalues are:
@@ -870,7 +906,7 @@
   /// \brief Determine whether this type has trivial copy/move-assignment
   ///        semantics.
   bool hasTrivialAssignment(ASTContext &Context, bool Copying) const;
- =20
+
 private:
   // These methods are implemented in a separate translation unit;
   // "static"-ize them to avoid creating temporary QualTypes in the
@@ -879,6 +915,8 @@
   static QualType getDesugaredType(QualType T, const ASTContext &Context);
   static SplitQualType getSplitDesugaredType(QualType T);
   static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
+  static QualType getSingleStepDesugaredTypeImpl(QualType type,
+                                                 const ASTContext &C);
   static QualType IgnoreParens(QualType T);
   static DestructionKind isDestructedTypeImpl(QualType type);
 };
@@ -915,7 +953,7 @@
=20
 namespace clang {
=20
-/// \brief Base class that is common to both the \c ExtQuals and \c Type=20
+/// \brief Base class that is common to both the \c ExtQuals and \c Type
 /// classes, which allows \c QualType to access the common fields between =
the
 /// two.
 ///
@@ -926,7 +964,7 @@
   /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) =
or
   /// a self-referential pointer (for \c Type).
   ///
-  /// This pointer allows an efficient mapping from a QualType to its=20
+  /// This pointer allows an efficient mapping from a QualType to its
   /// underlying type pointer.
   const Type *const BaseType;
=20
@@ -937,14 +975,14 @@
   friend class Type;
   friend class ExtQuals;
 };
- =20
+
 /// ExtQuals - We can encode up to four bits in the low bits of a
 /// type pointer, but there are many more type qualifiers that we want
 /// to be able to apply to an arbitrary type.  Therefore we have this
 /// struct, intended to be heap-allocated and used by QualType to
 /// store qualifiers.
 ///
-/// The current design tags the 'const', 'restrict', and 'volatile' qualif=
iers=20
+/// The current design tags the 'const', 'restrict', and 'volatile' qualif=
iers
 /// in three low bits on the QualType pointer; a fourth bit records whether
 /// the pointer is an ExtQuals node. The extended qualifiers (address spac=
es,
 /// Objective-C GC attributes) are much more rare.
@@ -969,7 +1007,7 @@
   ExtQuals *this_() { return this; }
=20
 public:
-  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)=20
+  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
     : ExtQualsTypeCommonBase(baseType,
                              canon.isNull() ? QualType(this_(), 0) : canon=
),
       Quals(quals)
@@ -1008,8 +1046,8 @@
   }
 };
=20
-/// \brief The kind of C++0x ref-qualifier associated with a function type=
,=20
-/// which determines whether a member function's "this" object can be an=20
+/// \brief The kind of C++0x ref-qualifier associated with a function type,
+/// which determines whether a member function's "this" object can be an
 /// lvalue, rvalue, or neither.
 enum RefQualifierKind {
   /// \brief No ref-qualifier was provided.
@@ -1019,7 +1057,7 @@
   /// \brief An rvalue ref-qualifier was provided (\c &&).
   RQ_RValue
 };
- =20
+
 /// Type - This is the base class of the type hierarchy.  A central concept
 /// with types is that each type always has a canonical type.  A canonical=
 type
 /// is the type with any typedef names stripped out of it or the types it
@@ -1071,29 +1109,32 @@
     /// Note that this should stay at the end of the ivars for Type so that
     /// subclasses can pack their bitfields into the same word.
     unsigned Dependent : 1;
- =20
-    /// \brief Whether this type somehow involves a template parameter, ev=
en=20
+
+    /// \brief Whether this type somehow involves a template parameter, ev=
en
     /// if the resolution of the type does not depend on a template parame=
ter.
     unsigned InstantiationDependent : 1;
-   =20
+
     /// \brief Whether this type is a variably-modified type (C99 6.7.5).
     unsigned VariablyModified : 1;
=20
     /// \brief Whether this type contains an unexpanded parameter pack
     /// (for C++0x variadic templates).
     unsigned ContainsUnexpandedParameterPack : 1;
- =20
+
     /// \brief Nonzero if the cache (i.e. the bitfields here starting
     /// with 'Cache') is valid.  If so, then this is a
     /// LangOptions::VisibilityMode+1.
     mutable unsigned CacheValidAndVisibility : 2;
- =20
+
+    /// \brief True if the visibility was set explicitly in the source cod=
e.
+    mutable unsigned CachedExplicitVisibility : 1;
+
     /// \brief Linkage of this type.
     mutable unsigned CachedLinkage : 2;
=20
-    /// \brief Whether this type involves and local or unnamed types.=20
+    /// \brief Whether this type involves and local or unnamed types.
     mutable unsigned CachedLocalOrUnnamed : 1;
- =20
+
     /// \brief FromAST - Whether this type comes from an AST file.
     mutable unsigned FromAST : 1;
=20
@@ -1104,6 +1145,10 @@
       assert(isCacheValid() && "getting linkage from invalid cache");
       return static_cast<Visibility>(CacheValidAndVisibility-1);
     }
+    bool isVisibilityExplicit() const {
+      assert(isCacheValid() && "getting linkage from invalid cache");
+      return CachedExplicitVisibility;
+    }
     Linkage getLinkage() const {
       assert(isCacheValid() && "getting linkage from invalid cache");
       return static_cast<Linkage>(CachedLinkage);
@@ -1113,7 +1158,7 @@
       return CachedLocalOrUnnamed;
     }
   };
-  enum { NumTypeBits =3D 18 };
+  enum { NumTypeBits =3D 19 };
=20
 protected:
   // These classes allow subclasses to somewhat cleanly pack bitfields
@@ -1152,9 +1197,6 @@
     /// regparm and the calling convention.
     unsigned ExtInfo : 8;
=20
-    /// Whether the function is variadic.  Only used by FunctionProtoType.
-    unsigned Variadic : 1;
-
     /// TypeQuals - Used only by FunctionProtoType, put here to pack with =
the
     /// other bitfields.
     /// The qualifiers are part of FunctionProtoType because...
@@ -1162,7 +1204,7 @@
     /// C++ 8.3.5p4: The return type, the parameter type list and the
     /// cv-qualifier-seq, [...], are part of the function type.
     unsigned TypeQuals : 3;
-   =20
+
     /// \brief The ref-qualifier associated with a \c FunctionProtoType.
     ///
     /// This is a value of type \c RefQualifierKind.
@@ -1247,7 +1289,7 @@
=20
 private:
   /// \brief Set whether this type comes from an AST file.
-  void setFromAST(bool V =3D true) const {=20
+  void setFromAST(bool V =3D true) const {
     TypeBits.FromAST =3D V;
   }
=20
@@ -1256,7 +1298,7 @@
 protected:
   // silence VC++ warning C4355: 'this' : used in base member initializer =
list
   Type *this_() { return this; }
-  Type(TypeClass tc, QualType canon, bool Dependent,=20
+  Type(TypeClass tc, QualType canon, bool Dependent,
        bool InstantiationDependent, bool VariablyModified,
        bool ContainsUnexpandedParameterPack)
     : ExtQualsTypeCommonBase(this,
@@ -1267,20 +1309,21 @@
     TypeBits.VariablyModified =3D VariablyModified;
     TypeBits.ContainsUnexpandedParameterPack =3D ContainsUnexpandedParamet=
erPack;
     TypeBits.CacheValidAndVisibility =3D 0;
+    TypeBits.CachedExplicitVisibility =3D false;
     TypeBits.CachedLocalOrUnnamed =3D false;
     TypeBits.CachedLinkage =3D NoLinkage;
     TypeBits.FromAST =3D false;
   }
   friend class ASTContext;
=20
-  void setDependent(bool D =3D true) {=20
-    TypeBits.Dependent =3D D;=20
+  void setDependent(bool D =3D true) {
+    TypeBits.Dependent =3D D;
     if (D)
       TypeBits.InstantiationDependent =3D true;
   }
-  void setInstantiationDependent(bool D =3D true) {=20
+  void setInstantiationDependent(bool D =3D true) {
     TypeBits.InstantiationDependent =3D D; }
-  void setVariablyModified(bool VM =3D true) { TypeBits.VariablyModified =
=3D VM;=20
+  void setVariablyModified(bool VM =3D true) { TypeBits.VariablyModified =
=3D VM;
   }
   void setContainsUnexpandedParameterPack(bool PP =3D true) {
     TypeBits.ContainsUnexpandedParameterPack =3D PP;
@@ -1306,8 +1349,8 @@
   /// };
   /// \endcode
   ///
-  /// Note that this routine does not specify which=20
-  bool containsUnexpandedParameterPack() const {=20
+  /// Note that this routine does not specify which
+  bool containsUnexpandedParameterPack() const {
     return TypeBits.ContainsUnexpandedParameterPack;
   }
=20
@@ -1317,6 +1360,11 @@
     return CanonicalType =3D=3D QualType(this, 0);
   }
=20
+  /// Pull a single level of sugar off of this locally-unqualified type.
+  /// Users should generally prefer SplitQualType::getSingleStepDesugaredT=
ype()
+  /// or QualType::getSingleStepDesugaredType(const ASTContext&).
+  QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
+
   /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
   /// object types, function types, and incomplete types.
=20
@@ -1324,18 +1372,22 @@
   /// A type that can describe objects, but which lacks information needed=
 to
   /// determine its size (e.g. void, or a fwd declared struct). Clients of=
 this
   /// routine will need to determine if the size is actually required.
-  bool isIncompleteType() const;
+  ///
+  /// \brief Def If non-NULL, and the type refers to some kind of declarat=
ion
+  /// that can be completed (such as a C struct, C++ class, or Objective-C
+  /// class), will be set to the declaration.
+  bool isIncompleteType(NamedDecl **Def =3D 0) const;
=20
   /// isIncompleteOrObjectType - Return true if this is an incomplete or o=
bject
   /// type, in other words, not a function type.
   bool isIncompleteOrObjectType() const {
     return !isFunctionType();
   }
- =20
+
   /// \brief Determine whether this type is an object type.
   bool isObjectType() const {
     // C++ [basic.types]p8:
-    //   An object type is a (possibly cv-qualified) type that is not a=20
+    //   An object type is a (possibly cv-qualified) type that is not a
     //   function type, not a reference type, and not a void type.
     return !isReferenceType() && !isFunctionType() && !isVoidType();
   }
@@ -1367,6 +1419,10 @@
   /// isSpecificPlaceholderType - Test for a specific placeholder type.
   bool isSpecificPlaceholderType(unsigned K) const;
=20
+  /// isNonOverloadPlaceholderType - Test for a placeholder type
+  /// other than Overload;  see BuiltinType::isNonOverloadPlaceholderType.
+  bool isNonOverloadPlaceholderType() const;
+
   /// isIntegerType() does *not* include complex integers (a GCC extension=
).
   /// isComplexIntegerType() can be used to test for complex integers.
   bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
@@ -1378,13 +1434,13 @@
   bool isChar32Type() const;
   bool isAnyCharacterType() const;
   bool isIntegralType(ASTContext &Ctx) const;
- =20
+
   /// \brief Determine whether this type is an integral or enumeration typ=
e.
   bool isIntegralOrEnumerationType() const;
   /// \brief Determine whether this type is an integral or unscoped enumer=
ation
   /// type.
   bool isIntegralOrUnscopedEnumerationType() const;
-                                  =20
+
   /// Floating point categories.
   bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long do=
uble)
   /// isComplexType() does *not* include complex integers (a GCC extension=
).
@@ -1451,7 +1507,7 @@
   bool isCARCBridgableType() const;
   bool isTemplateTypeParmType() const;          // C++ template type param=
eter
   bool isNullPtrType() const;                   // C++0x nullptr_t
-  bool isAtomicType() const;                    // C1X _Atomic()
+  bool isAtomicType() const;                    // C11 _Atomic()
=20
   /// Determines if this type, which must satisfy
   /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
@@ -1479,32 +1535,32 @@
   /// that its definition somehow depends on a template parameter
   /// (C++ [temp.dep.type]).
   bool isDependentType() const { return TypeBits.Dependent; }
- =20
+
   /// \brief Determine whether this type is an instantiation-dependent typ=
e,
   /// meaning that the type involves a template parameter (even if the
   /// definition does not actually depend on the type substituted for that
   /// template parameter).
-  bool isInstantiationDependentType() const {=20
-    return TypeBits.InstantiationDependent;=20
-  }
- =20
+  bool isInstantiationDependentType() const {
+    return TypeBits.InstantiationDependent;
+  }
+
   /// \brief Whether this type is a variably-modified type (C99 6.7.5).
   bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
=20
   /// \brief Whether this type involves a variable-length array type
   /// with a definite size.
   bool hasSizedVLAType() const;
- =20
+
   /// \brief Whether this type is or contains a local or unnamed type.
   bool hasUnnamedOrLocalType() const;
- =20
+
   bool isOverloadableType() const;
=20
   /// \brief Determine wither this type is a C++ elaborated-type-specifier.
   bool isElaboratedTypeSpecifier() const;
=20
   bool canDecayToPointerType() const;
- =20
+
   /// hasPointerRepresentation - Whether this type is represented
   /// natively as a pointer; this includes pointers, references, block
   /// pointers, and Objective-C interface, qualified id, and qualified
@@ -1547,7 +1603,7 @@
   const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
=20
   /// \brief Retrieves the CXXRecordDecl that this type refers to, either
-  /// because the type is a RecordType or because it is the injected-class=
-name=20
+  /// because the type is a RecordType or because it is the injected-class=
-name
   /// type of a class template or class template partial specialization.
   CXXRecordDecl *getAsCXXRecordDecl() const;
=20
@@ -1555,7 +1611,7 @@
   /// an initializer of this type. This looks through declarators like poi=
nter
   /// types, but not through decltype or typedefs.
   AutoType *getContainedAutoType() const;
- =20
+
   /// Member-template getAs<specific type>'.  Look through sugar for
   /// an instance of <specific type>.   This scheme will eventually
   /// replace the specific getAsXXXX methods above.
@@ -1608,15 +1664,15 @@
   bool isSignedIntegerType() const;
=20
   /// isUnsignedIntegerType - Return true if this is an integer type that =
is
-  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],=20
+  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
   /// or an enum decl which has an unsigned representation.
   bool isUnsignedIntegerType() const;
=20
-  /// Determines whether this is an integer type that is signed or an=20
+  /// Determines whether this is an integer type that is signed or an
   /// enumeration types whose underlying type is a signed integer type.
   bool isSignedIntegerOrEnumerationType() const;
- =20
-  /// Determines whether this is an integer type that is unsigned or an=20
+
+  /// Determines whether this is an integer type that is unsigned or an
   /// enumeration types whose underlying type is a unsigned integer type.
   bool isUnsignedIntegerOrEnumerationType() const;
=20
@@ -1635,19 +1691,22 @@
   /// \brief Determine the visibility of this type.
   Visibility getVisibility() const;
=20
+  /// \brief Return true if the visibility was explicitly set is the code.
+  bool isVisibilityExplicit() const;
+
   /// \brief Determine the linkage and visibility of this type.
   std::pair<Linkage,Visibility> getLinkageAndVisibility() const;
- =20
+
   /// \brief Note that the linkage is no longer known.
   void ClearLinkageCache();
- =20
+
   const char *getTypeClassName() const;
=20
   QualType getCanonicalTypeInternal() const {
     return CanonicalType;
   }
   CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
-  void dump() const;
+  LLVM_ATTRIBUTE_USED void dump() const;
=20
   static bool classof(const Type *) { return true; }
=20
@@ -1677,81 +1736,9 @@
 class BuiltinType : public Type {
 public:
   enum Kind {
-    Void,
-
-    Bool,     // This is bool and/or _Bool.
-    Char_U,   // This is 'char' for targets where char is unsigned.
-    UChar,    // This is explicitly qualified unsigned char.
-    WChar_U,  // This is 'wchar_t' for C++, when unsigned.
-    Char16,   // This is 'char16_t' for C++.
-    Char32,   // This is 'char32_t' for C++.
-    UShort,
-    UInt,
-    ULong,
-    ULongLong,
-    UInt128,  // __uint128_t
-
-    Char_S,   // This is 'char' for targets where char is signed.
-    SChar,    // This is explicitly qualified signed char.
-    WChar_S,  // This is 'wchar_t' for C++, when signed.
-    Short,
-    Int,
-    Long,
-    LongLong,
-    Int128,   // __int128_t
-
-    Half,     // This is the 'half' type in OpenCL,
-              // __fp16 in case of ARM NEON.
-    Float, Double, LongDouble,
-
-    NullPtr,  // This is the type of C++0x 'nullptr'.
-
-    /// The primitive Objective C 'id' type.  The user-visible 'id'
-    /// type is a typedef of an ObjCObjectPointerType to an
-    /// ObjCObjectType with this as its base.  In fact, this only ever
-    /// shows up in an AST as the base type of an ObjCObjectType.
-    ObjCId,
-
-    /// The primitive Objective C 'Class' type.  The user-visible
-    /// 'Class' type is a typedef of an ObjCObjectPointerType to an
-    /// ObjCObjectType with this as its base.  In fact, this only ever
-    /// shows up in an AST as the base type of an ObjCObjectType.
-    ObjCClass,
-
-    /// The primitive Objective C 'SEL' type.  The user-visible 'SEL'
-    /// type is a typedef of a PointerType to this.
-    ObjCSel,
-
-    /// This represents the type of an expression whose type is
-    /// totally unknown, e.g. 'T::foo'.  It is permitted for this to
-    /// appear in situations where the structure of the type is
-    /// theoretically deducible.
-    Dependent,
-
-    /// The type of an unresolved overload set.  A placeholder type.
-    /// Expressions with this type have one of the following basic
-    /// forms, with parentheses generally permitted:
-    ///   foo          # possibly qualified, not if an implicit access
-    ///   foo          # possibly qualified, not if an implicit access
-    ///   &foo         # possibly qualified, not if an implicit access
-    ///   x->foo       # only if might be a static member function
-    ///   &x->foo      # only if might be a static member function
-    ///   &Class::foo  # when a pointer-to-member; sub-expr also has this =
type
-    /// OverloadExpr::find can be used to analyze the expression.
-    Overload,
-
-    /// The type of a bound C++ non-static member function.
-    /// A placeholder type.  Expressions with this type have one of the
-    /// following basic forms:
-    ///   foo          # if an implicit access
-    ///   x->foo       # if only contains non-static members
-    BoundMember,
-
-    /// __builtin_any_type.  A placeholder type.  Useful for clients
-    /// like debuggers that don't know what type to give something.
-    /// Only a small number of operations are valid on expressions of
-    /// unknown type, most notably explicit casts.
-    UnknownAny
+#define BUILTIN_TYPE(Id, SingletonId) Id,
+#define LAST_BUILTIN_TYPE(Id) LastKind =3D Id
+#include "clang/AST/BuiltinTypes.def"
   };
=20
 public:
@@ -1785,11 +1772,29 @@
     return getKind() >=3D Half && getKind() <=3D LongDouble;
   }
=20
+  /// Determines whether the given kind corresponds to a placeholder type.
+  static bool isPlaceholderTypeKind(Kind K) {
+    return K >=3D Overload;
+  }
+
   /// Determines whether this type is a placeholder type, i.e. a type
   /// which cannot appear in arbitrary positions in a fully-formed
   /// expression.
   bool isPlaceholderType() const {
-    return getKind() >=3D Overload;
+    return isPlaceholderTypeKind(getKind());
+  }
+
+  /// Determines whether this type is a placeholder type other than
+  /// Overload.  Most placeholder types require only syntactic
+  /// information about their context in order to be resolved (e.g.
+  /// whether it is a call expression), which means they can (and
+  /// should) be resolved in an earlier "phase" of analysis.
+  /// Overload expressions sometimes pick up further information
+  /// from their context, like whether the context expects a
+  /// specific function-pointer type, and so frequently need
+  /// special treatment.
+  bool isNonOverloadPlaceholderType() const {
+    return getKind() > Overload;
   }
=20
   static bool classof(const Type *T) { return T->getTypeClass() =3D=3D Bui=
ltin; }
@@ -1868,7 +1873,7 @@
     Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
          Pointee->isInstantiationDependentType(),
          Pointee->isVariablyModifiedType(),
-         Pointee->containsUnexpandedParameterPack()),=20
+         Pointee->containsUnexpandedParameterPack()),
     PointeeType(Pointee) {
   }
   friend class ASTContext;  // ASTContext creates these.
@@ -1905,7 +1910,7 @@
     PointeeType(Pointee) {
   }
   friend class ASTContext;  // ASTContext creates these.
- =20
+
 public:
=20
   // Get the pointee type. Pointee is required to always be a function typ=
e.
@@ -1938,17 +1943,17 @@
     Type(tc, CanonicalRef, Referencee->isDependentType(),
          Referencee->isInstantiationDependentType(),
          Referencee->isVariablyModifiedType(),
-         Referencee->containsUnexpandedParameterPack()),=20
-    PointeeType(Referencee)=20
+         Referencee->containsUnexpandedParameterPack()),
+    PointeeType(Referencee)
   {
     ReferenceTypeBits.SpelledAsLValue =3D SpelledAsLValue;
     ReferenceTypeBits.InnerRef =3D Referencee->isReferenceType();
   }
- =20
+
 public:
   bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValu=
e; }
   bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
- =20
+
   QualType getPointeeTypeAsWritten() const { return PointeeType; }
   QualType getPointeeType() const {
     // FIXME: this might strip inner qualifiers; okay?
@@ -2021,15 +2026,15 @@
   MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalP=
tr) :
     Type(MemberPointer, CanonicalPtr,
          Cls->isDependentType() || Pointee->isDependentType(),
-         (Cls->isInstantiationDependentType() ||=20
+         (Cls->isInstantiationDependentType() ||
           Pointee->isInstantiationDependentType()),
          Pointee->isVariablyModifiedType(),
-         (Cls->containsUnexpandedParameterPack() ||=20
+         (Cls->containsUnexpandedParameterPack() ||
           Pointee->containsUnexpandedParameterPack())),
     PointeeType(Pointee), Class(Cls) {
   }
   friend class ASTContext; // ASTContext creates these.
- =20
+
 public:
   QualType getPointeeType() const { return PointeeType; }
=20
@@ -2136,7 +2141,7 @@
 protected:
   ConstantArrayType(TypeClass tc, QualType et, QualType can,
                     const llvm::APInt &size, ArraySizeModifier sm, unsigne=
d tq)
-    : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()=
),=20
+    : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()=
),
       Size(size) {}
   friend class ASTContext;  // ASTContext creates these.
 public:
@@ -2144,17 +2149,17 @@
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
=20
- =20
+
   /// \brief Determine the number of bits required to address a member of
   // an array with the given element type and number of elements.
   static unsigned getNumAddressingBits(ASTContext &Context,
                                        QualType ElementType,
                                        const llvm::APInt &NumElements);
- =20
+
   /// \brief Determine the maximum number of active bits that an array's s=
ize
   /// can require, which limits the maximum size of the array.
   static unsigned getMaxSizeBits(ASTContext &Context);
- =20
+
   void Profile(llvm::FoldingSetNodeID &ID) {
     Profile(ID, getElementType(), getSize(),
             getSizeModifier(), getIndexTypeCVRQualifiers());
@@ -2180,7 +2185,7 @@
=20
   IncompleteArrayType(QualType et, QualType can,
                       ArraySizeModifier sm, unsigned tq)
-    : ArrayType(IncompleteArray, et, can, sm, tq,=20
+    : ArrayType(IncompleteArray, et, can, sm, tq,
                 et->containsUnexpandedParameterPack()) {}
   friend class ASTContext;  // ASTContext creates these.
 public:
@@ -2232,7 +2237,7 @@
   VariableArrayType(QualType et, QualType can, Expr *e,
                     ArraySizeModifier sm, unsigned tq,
                     SourceRange brackets)
-    : ArrayType(VariableArray, et, can, sm, tq,=20
+    : ArrayType(VariableArray, et, can, sm, tq,
                 et->containsUnexpandedParameterPack()),
       SizeExpr((Stmt*) e), Brackets(brackets) {}
   friend class ASTContext;  // ASTContext creates these.
@@ -2388,12 +2393,12 @@
=20
   VectorType(QualType vecType, unsigned nElements, QualType canonType,
              VectorKind vecKind);
- =20
+
   VectorType(TypeClass tc, QualType vecType, unsigned nElements,
              QualType canonType, VectorKind vecKind);
=20
   friend class ASTContext;  // ASTContext creates these.
- =20
+
 public:
=20
   QualType getElementType() const { return ElementType; }
@@ -2559,7 +2564,7 @@
     bool getNoReturn() const { return Bits & NoReturnMask; }
     bool getProducesResult() const { return Bits & ProducesResultMask; }
     bool getHasRegParm() const { return (Bits >> RegParmOffset) !=3D 0; }
-    unsigned getRegParm() const {=20
+    unsigned getRegParm() const {
       unsigned RegParm =3D Bits >> RegParmOffset;
       if (RegParm > 0)
         --RegParm;
@@ -2607,23 +2612,21 @@
   };
=20
 protected:
-  FunctionType(TypeClass tc, QualType res, bool variadic,
+  FunctionType(TypeClass tc, QualType res,
                unsigned typeQuals, RefQualifierKind RefQualifier,
                QualType Canonical, bool Dependent,
                bool InstantiationDependent,
-               bool VariablyModified, bool ContainsUnexpandedParameterPack=
,=20
+               bool VariablyModified, bool ContainsUnexpandedParameterPack,
                ExtInfo Info)
-    : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModif=
ied,=20
-           ContainsUnexpandedParameterPack),=20
+    : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModif=
ied,
+           ContainsUnexpandedParameterPack),
       ResultType(res) {
     FunctionTypeBits.ExtInfo =3D Info.Bits;
-    FunctionTypeBits.Variadic =3D variadic;
     FunctionTypeBits.TypeQuals =3D typeQuals;
     FunctionTypeBits.RefQualifier =3D static_cast<unsigned>(RefQualifier);
   }
-  bool isVariadic() const { return FunctionTypeBits.Variadic; }
   unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
- =20
+
   RefQualifierKind getRefQualifier() const {
     return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
   }
@@ -2640,7 +2643,7 @@
=20
   /// \brief Determine the type of an expression that calls a function of
   /// this type.
-  QualType getCallResultType(ASTContext &Context) const {=20
+  QualType getCallResultType(ASTContext &Context) const {
     return getResultType().getNonLValueExprType(Context);
   }
=20
@@ -2657,13 +2660,13 @@
 /// no information available about its arguments.
 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNo=
de {
   FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
-    : FunctionType(FunctionNoProto, Result, false, 0, RQ_None, Canonical,
+    : FunctionType(FunctionNoProto, Result, 0, RQ_None, Canonical,
                    /*Dependent=3D*/false, /*InstantiationDependent=3D*/fal=
se,
-                   Result->isVariablyModifiedType(),=20
+                   Result->isVariablyModifiedType(),
                    /*ContainsUnexpandedParameterPack=3D*/false, Info) {}
=20
   friend class ASTContext;  // ASTContext creates these.
- =20
+
 public:
   // No additional state past what FunctionType provides.
=20
@@ -2695,34 +2698,26 @@
   /// ExtProtoInfo - Extra information about a function prototype.
   struct ExtProtoInfo {
     ExtProtoInfo() :
-      Variadic(false), ExceptionSpecType(EST_None), TypeQuals(0),
-      RefQualifier(RQ_None), NumExceptions(0), Exceptions(0), NoexceptExpr=
(0),
-      ConsumedArguments(0) {}
+      Variadic(false), HasTrailingReturn(false), TypeQuals(0),
+      ExceptionSpecType(EST_None), RefQualifier(RQ_None),
+      NumExceptions(0), Exceptions(0), NoexceptExpr(0), ConsumedArguments(=
0) {}
=20
     FunctionType::ExtInfo ExtInfo;
-    bool Variadic;
+    bool Variadic : 1;
+    bool HasTrailingReturn : 1;
+    unsigned char TypeQuals;
     ExceptionSpecificationType ExceptionSpecType;
-    unsigned char TypeQuals;
     RefQualifierKind RefQualifier;
     unsigned NumExceptions;
-
-    /// Exceptions - A variable size array after that holds the exception =
types.
     const QualType *Exceptions;
-
-    /// NoexceptExpr - Instead of Exceptions, there may be a single Expr*
-    /// pointing to the expression in the noexcept() specifier.
     Expr *NoexceptExpr;
-   =20
-    /// ConsumedArgs - A variable size array, following Exceptions
-    /// and of length NumArgs, holding flags indicating which arguments
-    /// are consumed.  This only appears if HasAnyConsumedArgs is true.
     const bool *ConsumedArguments;
   };
=20
 private:
   /// \brief Determine whether there are any argument types that
   /// contain an unexpanded parameter pack.
-  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,=20
+  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
                                                  unsigned numArgs) {
     for (unsigned Idx =3D 0; Idx < numArgs; ++Idx)
       if (ArgArray[Idx]->containsUnexpandedParameterPack())
@@ -2735,7 +2730,7 @@
                     QualType canonical, const ExtProtoInfo &epi);
=20
   /// NumArgs - The number of arguments this function has, not counting '.=
..'.
-  unsigned NumArgs : 19;
+  unsigned NumArgs : 17;
=20
   /// NumExceptions - The number of types in the exception spec, if any.
   unsigned NumExceptions : 9;
@@ -2746,6 +2741,25 @@
   /// HasAnyConsumedArgs - Whether this function has any consumed argument=
s.
   unsigned HasAnyConsumedArgs : 1;
=20
+  /// Variadic - Whether the function is variadic.
+  unsigned Variadic : 1;
+
+  /// HasTrailingReturn - Whether this function has a trailing return type.
+  unsigned HasTrailingReturn : 1;
+
+  // ArgInfo - There is an variable size array after the class in memory t=
hat
+  // holds the argument types.
+
+  // Exceptions - There is another variable size array after ArgInfo that
+  // holds the exception types.
+
+  // NoexceptExpr - Instead of Exceptions, there may be a single Expr* poi=
nting
+  // to the expression in the noexcept() specifier.
+
+  // ConsumedArgs - A variable size array, following Exceptions
+  // and of length NumArgs, holding flags indicating which arguments
+  // are consumed.  This only appears if HasAnyConsumedArgs is true.
+
   friend class ASTContext;  // ASTContext creates these.
=20
   const bool *getConsumedArgsBuffer() const {
@@ -2772,6 +2786,7 @@
     ExtProtoInfo EPI;
     EPI.ExtInfo =3D getExtInfo();
     EPI.Variadic =3D isVariadic();
+    EPI.HasTrailingReturn =3D hasTrailingReturn();
     EPI.ExceptionSpecType =3D getExceptionSpecType();
     EPI.TypeQuals =3D static_cast<unsigned char>(getTypeQuals());
     EPI.RefQualifier =3D getRefQualifier();
@@ -2833,24 +2848,26 @@
     return getNoexceptSpec(Ctx) =3D=3D NR_Nothrow;
   }
=20
-  using FunctionType::isVariadic;
+  bool isVariadic() const { return Variadic; }
=20
   /// \brief Determines whether this function prototype contains a
   /// parameter pack at the end.
   ///
   /// A function template whose last parameter is a parameter pack can be
   /// called with an arbitrary number of arguments, much like a variadic
-  /// function. However,=20
+  /// function.
   bool isTemplateVariadic() const;
- =20
+
+  bool hasTrailingReturn() const { return HasTrailingReturn; }
+
   unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
=20
- =20
+
   /// \brief Retrieve the ref-qualifier associated with this function type.
   RefQualifierKind getRefQualifier() const {
     return FunctionType::getRefQualifier();
   }
- =20
+
   typedef const QualType *arg_type_iterator;
   arg_type_iterator arg_type_begin() const {
     return reinterpret_cast<const QualType *>(this+1);
@@ -2881,6 +2898,9 @@
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
=20
+  void printExceptionSpecification(std::string &S,=20
+                                   PrintingPolicy Policy) const;
+
   static bool classof(const Type *T) {
     return T->getTypeClass() =3D=3D FunctionProto;
   }
@@ -2901,7 +2921,7 @@
   UnresolvedUsingTypenameDecl *Decl;
=20
   UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
-    : Type(UnresolvedUsing, QualType(), true, true, false,=20
+    : Type(UnresolvedUsing, QualType(), true, true, false,
            /*ContainsUnexpandedParameterPack=3D*/false),
       Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
   friend class ASTContext; // ASTContext creates these.
@@ -2931,9 +2951,9 @@
   TypedefNameDecl *Decl;
 protected:
   TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
-    : Type(tc, can, can->isDependentType(),=20
+    : Type(tc, can, can->isDependentType(),
            can->isInstantiationDependentType(),
-           can->isVariablyModifiedType(),=20
+           can->isVariablyModifiedType(),
            /*ContainsUnexpandedParameterPack=3D*/false),
       Decl(const_cast<TypedefNameDecl*>(D)) {
     assert(!isa<TypedefType>(can) && "Invalid canonical type");
@@ -2996,10 +3016,10 @@
 class TypeOfType : public Type {
   QualType TOType;
   TypeOfType(QualType T, QualType can)
-    : Type(TypeOf, can, T->isDependentType(),=20
+    : Type(TypeOf, can, T->isDependentType(),
            T->isInstantiationDependentType(),
-           T->isVariablyModifiedType(),=20
-           T->containsUnexpandedParameterPack()),=20
+           T->isVariablyModifiedType(),
+           T->containsUnexpandedParameterPack()),
       TOType(T) {
     assert(!isa<TypedefType>(can) && "Invalid canonical type");
   }
@@ -3020,10 +3040,6 @@
 /// DecltypeType (C++0x)
 class DecltypeType : public Type {
   Expr *E;
-
-  // FIXME: We could get rid of UnderlyingType if we wanted to: We would h=
ave to
-  // Move getDesugaredType to ASTContext so that it can call getDecltypeFo=
rExpr
-  // from it.
   QualType UnderlyingType;
=20
 protected:
@@ -3089,7 +3105,7 @@
   QualType getBaseType() const { return BaseType; }
=20
   UTTKind getUTTKind() const { return UKind; }
- =20
+
   static bool classof(const Type *T) {
     return T->getTypeClass() =3D=3D UnaryTransform;
   }
@@ -3101,6 +3117,8 @@
   /// TagDecl that declares the entity.
   TagDecl * decl;
=20
+  friend class ASTReader;
+ =20
 protected:
   TagType(TypeClass TC, const TagDecl *D, QualType can);
=20
@@ -3115,8 +3133,6 @@
     return T->getTypeClass() >=3D TagFirst && T->getTypeClass() <=3D TagLa=
st;
   }
   static bool classof(const TagType *) { return true; }
-  static bool classof(const RecordType *) { return true; }
-  static bool classof(const EnumType *) { return true; }
 };
=20
 /// RecordType - This is a helper class that allows the use of isa/cast/dy=
ncast
@@ -3142,10 +3158,7 @@
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
=20
-  static bool classof(const TagType *T);
-  static bool classof(const Type *T) {
-    return isa<TagType>(T) && classof(cast<TagType>(T));
-  }
+  static bool classof(const Type *T) { return T->getTypeClass() =3D=3D Rec=
ord; }
   static bool classof(const RecordType *) { return true; }
 };
=20
@@ -3164,10 +3177,7 @@
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
=20
-  static bool classof(const TagType *T);
-  static bool classof(const Type *T) {
-    return isa<TagType>(T) && classof(cast<TagType>(T));
-  }
+  static bool classof(const Type *T) { return T->getTypeClass() =3D=3D Enu=
m; }
   static bool classof(const EnumType *) { return true; }
 };
=20
@@ -3284,7 +3294,7 @@
=20
   /// Build the canonical type.
   TemplateTypeParmType(unsigned D, unsigned I, bool PP)
-    : Type(TemplateTypeParm, QualType(this, 0),=20
+    : Type(TemplateTypeParm, QualType(this, 0),
            /*Dependent=3D*/true,
            /*InstantiationDependent=3D*/true,
            /*VariablyModified=3D*/false, PP) {
@@ -3389,7 +3399,7 @@
 ///
 /// When a pack expansion in the source code contains multiple parameter p=
acks
 /// and those parameter packs correspond to different levels of template
-/// parameter lists, this type node is used to represent a template type=20
+/// parameter lists, this type node is used to represent a template type
 /// parameter pack from an outer level, which has already had its argument=
 pack
 /// substituted but that still lives within a pack expansion that itself
 /// could not be instantiated. When actually performing a substitution into
@@ -3399,38 +3409,38 @@
 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSet=
Node {
   /// \brief The original type parameter.
   const TemplateTypeParmType *Replaced;
- =20
+
   /// \brief A pointer to the set of template arguments that this
   /// parameter pack is instantiated with.
   const TemplateArgument *Arguments;
- =20
+
   /// \brief The number of template arguments in \c Arguments.
   unsigned NumArguments;
- =20
-  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,=20
+
+  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
                                 QualType Canon,
                                 const TemplateArgument &ArgPack);
- =20
+
   friend class ASTContext;
- =20
+
 public:
   IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier()=
; }
- =20
+
   /// Gets the template parameter that was substituted for.
   const TemplateTypeParmType *getReplacedParameter() const {
     return Replaced;
   }
- =20
+
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
- =20
+
   TemplateArgument getArgumentPack() const;
- =20
+
   void Profile(llvm::FoldingSetNodeID &ID);
   static void Profile(llvm::FoldingSetNodeID &ID,
                       const TemplateTypeParmType *Replaced,
                       const TemplateArgument &ArgPack);
- =20
+
   static bool classof(const Type *T) {
     return T->getTypeClass() =3D=3D SubstTemplateTypeParmPack;
   }
@@ -3513,8 +3523,12 @@
=20
   /// \brief - The number of template arguments named in this class
   /// template specialization.
-  unsigned NumArgs;
-
+  unsigned NumArgs : 31;
+
+  /// \brief Whether this template specialization type is a substituted
+  /// type alias.
+  bool TypeAlias : 1;
+   =20
   TemplateSpecializationType(TemplateName T,
                              const TemplateArgument *Args,
                              unsigned NumArgs, QualType Canon,
@@ -3556,9 +3570,23 @@
     return isa<InjectedClassNameType>(getCanonicalTypeInternal());
   }
=20
-  /// True if this template specialization type is for a type alias
-  /// template.
-  bool isTypeAlias() const;
+  /// \brief Determine if this template specialization type is for a type =
alias
+  /// template that has been substituted.
+  ///
+  /// Nearly every template specialization type whose template is an alias
+  /// template will be substituted. However, this is not the case when
+  /// the specialization contains a pack expansion but the template alias
+  /// does not have a corresponding parameter pack, e.g.,
+  ///
+  /// \code
+  /// template<typename T, typename U, typename V> struct S;
+  /// template<typename T, typename U> using A =3D S<T, int, U>;
+  /// template<typename... Ts> struct X {
+  ///   typedef A<Ts...> type; // not a type alias
+  /// };
+  /// \endcode
+  bool isTypeAlias() const { return TypeAlias; }
+   =20
   /// Get the aliased type, if this is a specialization of a type alias
   /// template.
   QualType getAliasedType() const {
@@ -3646,7 +3674,7 @@
   InjectedClassNameType(CXXRecordDecl *D, QualType TST)
     : Type(InjectedClassName, QualType(), /*Dependent=3D*/true,
            /*InstantiationDependent=3D*/true,
-           /*VariablyModified=3D*/false,=20
+           /*VariablyModified=3D*/false,
            /*ContainsUnexpandedParameterPack=3D*/false),
       Decl(D), InjectedType(TST) {
     assert(isa<TemplateSpecializationType>(TST));
@@ -3708,10 +3736,10 @@
 class TypeWithKeyword : public Type {
 protected:
   TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
-                  QualType Canonical, bool Dependent,=20
-                  bool InstantiationDependent, bool VariablyModified,=20
+                  QualType Canonical, bool Dependent,
+                  bool InstantiationDependent, bool VariablyModified,
                   bool ContainsUnexpandedParameterPack)
-  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModifie=
d,=20
+  : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModifie=
d,
          ContainsUnexpandedParameterPack) {
     TypeWithKeywordBits.Keyword =3D Keyword;
   }
@@ -3815,12 +3843,12 @@
 };
=20
 /// \brief Represents a qualified type name for which the type name is
-/// dependent.=20
+/// dependent.
 ///
-/// DependentNameType represents a class of dependent types that involve a=20
-/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent=
)=20
+/// DependentNameType represents a class of dependent types that involve a
+/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
 /// name of a type. The DependentNameType may start with a "typename" (for=
 a
-/// typename-specifier), "class", "struct", "union", or "enum" (for a=20
+/// typename-specifier), "class", "struct", "union", or "enum" (for a
 /// dependent elaborated-type-specifier), or nothing (in contexts where we
 /// know that we must be referring to a type, e.g., in a base class specif=
ier).
 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetN=
ode {
@@ -3831,7 +3859,7 @@
   /// \brief The type that this typename specifier refers to.
   const IdentifierInfo *Name;
=20
-  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NN=
S,=20
+  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NN=
S,
                     const IdentifierInfo *Name, QualType CanonType)
     : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=3D*/t=
rue,
                       /*InstantiationDependent=3D*/true,
@@ -3948,7 +3976,7 @@
   }
   static bool classof(const DependentTemplateSpecializationType *T) {
     return true;
-  } =20
+  }
 };
=20
 /// \brief Represents a pack expansion of types.
@@ -3965,7 +3993,7 @@
 /// \code
 /// template<typename ...Types> struct tuple;
 ///
-/// template<typename ...Types>=20
+/// template<typename ...Types>
 /// struct tuple_of_references {
 ///   typedef tuple<Types&...> type;
 /// };
@@ -3978,24 +4006,24 @@
   QualType Pattern;
=20
   /// \brief The number of expansions that this pack expansion will
-  /// generate when substituted (+1), or indicates that=20
+  /// generate when substituted (+1), or indicates that
   ///
-  /// This field will only have a non-zero value when some of the paramete=
r=20
-  /// packs that occur within the pattern have been substituted but others=
 have=20
+  /// This field will only have a non-zero value when some of the parameter
+  /// packs that occur within the pattern have been substituted but others=
 have
   /// not.
   unsigned NumExpansions;
- =20
+
   PackExpansionType(QualType Pattern, QualType Canon,
                     llvm::Optional<unsigned> NumExpansions)
     : Type(PackExpansion, Canon, /*Dependent=3D*/true,
            /*InstantiationDependent=3D*/true,
            /*VariableModified=3D*/Pattern->isVariablyModifiedType(),
            /*ContainsUnexpandedParameterPack=3D*/false),
-      Pattern(Pattern),=20
+      Pattern(Pattern),
       NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
=20
   friend class ASTContext;  // ASTContext creates these
- =20
+
 public:
   /// \brief Retrieve the pattern of this pack expansion, which is the
   /// type that will be repeatedly instantiated when instantiating the
@@ -4007,10 +4035,10 @@
   llvm::Optional<unsigned> getNumExpansions() const {
     if (NumExpansions)
       return NumExpansions - 1;
-   =20
+
     return llvm::Optional<unsigned>();
   }
- =20
+
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
=20
@@ -4031,7 +4059,7 @@
   }
   static bool classof(const PackExpansionType *T) {
     return true;
-  } =20
+  }
 };
=20
 /// ObjCObjectType - Represents a class type in Objective C.
@@ -4075,7 +4103,7 @@
   ObjCProtocolDecl **getProtocolStorage();
=20
 protected:
-  ObjCObjectType(QualType Canonical, QualType Base,=20
+  ObjCObjectType(QualType Canonical, QualType Base,
                  ObjCProtocolDecl * const *Protocols, unsigned NumProtocol=
s);
=20
   enum Nonce_ObjCInterface { Nonce_ObjCInterface };
@@ -4132,7 +4160,7 @@
     assert(I < getNumProtocols() && "Out-of-range protocol access");
     return qual_begin()[I];
   }
- =20
+
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
=20
@@ -4153,7 +4181,7 @@
   // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
   // will need to be modified.
=20
-  ObjCObjectTypeImpl(QualType Canonical, QualType Base,=20
+  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
                      ObjCProtocolDecl * const *Protocols,
                      unsigned NumProtocols)
     : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
@@ -4162,8 +4190,8 @@
   void Profile(llvm::FoldingSetNodeID &ID);
   static void Profile(llvm::FoldingSetNodeID &ID,
                       QualType Base,
-                      ObjCProtocolDecl *const *protocols,=20
-                      unsigned NumProtocols); =20
+                      ObjCProtocolDecl *const *protocols,
+                      unsigned NumProtocols);
 };
=20
 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
@@ -4185,12 +4213,14 @@
 ///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
 ///     T->getBaseType() =3D=3D QualType(T, 0).
 class ObjCInterfaceType : public ObjCObjectType {
-  ObjCInterfaceDecl *Decl;
+  mutable ObjCInterfaceDecl *Decl;
=20
   ObjCInterfaceType(const ObjCInterfaceDecl *D)
     : ObjCObjectType(Nonce_ObjCInterface),
       Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
   friend class ASTContext;  // ASTContext creates these.
+  friend class ASTReader;
+  friend class ObjCInterfaceDecl;
=20
 public:
   /// getDecl - Get the declaration of this interface.
@@ -4300,7 +4330,7 @@
   bool isObjCClassType() const {
     return getObjectType()->isObjCUnqualifiedClass();
   }
- =20
+
   /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for so=
me
   /// non-empty set of protocols.
   bool isObjCQualifiedIdType() const {
@@ -4337,7 +4367,7 @@
   ObjCProtocolDecl *getProtocol(unsigned I) const {
     return getObjectType()->getProtocol(I);
   }
- =20
+
   bool isSugared() const { return false; }
   QualType desugar() const { return QualType(this, 0); }
=20
@@ -4396,7 +4426,7 @@
     addFastQualifiers(type.getLocalFastQualifiers());
     if (!type.hasLocalNonFastQualifiers())
       return type.getTypePtrUnsafe();
-     =20
+
     const ExtQuals *extQuals =3D type.getExtQualsUnsafe();
     addConsistentQualifiers(extQuals->getQualifiers());
     return extQuals->getBaseType();
@@ -4412,6 +4442,13 @@
=20
 // Inline function definitions.
=20
+inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
+  SplitQualType desugar =3D
+    Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
+  desugar.Quals.addConsistentQualifiers(Quals);
+  return desugar;
+}
+
 inline const Type *QualType::getTypePtr() const {
   return getCommonPtr()->BaseType;
 }
@@ -4463,7 +4500,7 @@
 inline bool QualType::isCanonicalAsParam() const {
   if (!isCanonical()) return false;
   if (hasLocalQualifiers()) return false;
- =20
+
   const Type *T =3D getTypePtr();
   if (T->isVariablyModifiedType() && T->hasSizedVLAType())
     return false;
@@ -4472,21 +4509,21 @@
 }
=20
 inline bool QualType::isConstQualified() const {
-  return isLocalConstQualified() ||=20
+  return isLocalConstQualified() ||
          getCommonPtr()->CanonicalType.isLocalConstQualified();
 }
=20
 inline bool QualType::isRestrictQualified() const {
-  return isLocalRestrictQualified() ||=20
+  return isLocalRestrictQualified() ||
          getCommonPtr()->CanonicalType.isLocalRestrictQualified();
 }
=20
=20
 inline bool QualType::isVolatileQualified() const {
-  return isLocalVolatileQualified() ||=20
+  return isLocalVolatileQualified() ||
          getCommonPtr()->CanonicalType.isLocalVolatileQualified();
 }
- =20
+
 inline bool QualType::hasQualifiers() const {
   return hasLocalQualifiers() ||
          getCommonPtr()->CanonicalType.hasLocalQualifiers();
@@ -4496,7 +4533,7 @@
   if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
     return QualType(getTypePtr(), 0);
=20
-  return QualType(getSplitUnqualifiedTypeImpl(*this).first, 0);
+  return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
 }
=20
 inline SplitQualType QualType::getSplitUnqualifiedType() const {
@@ -4505,7 +4542,7 @@
=20
   return getSplitUnqualifiedTypeImpl(*this);
 }
- =20
+
 inline void QualType::removeLocalConst() {
   removeLocalFastQualifiers(Qualifiers::Const);
 }
@@ -4616,7 +4653,8 @@
          isReferenceType() ||
   //    -- classes containing a sequence of objects of various types, [...=
];
          isRecordType() ||
-  //    -- unions, which ar classes capable of containing objects of diffe=
rent types at different times;
+  //    -- unions, which are classes capable of containing objects of diff=
erent
+  //               types at different times;
          isUnionType() ||
   //    -- enumerations, which comprise a set of named constant values. [.=
..];
          isEnumeralType() ||
@@ -4706,7 +4744,7 @@
   return isa<ObjCObjectType>(CanonicalType);
 }
 inline bool Type::isObjCObjectOrInterfaceType() const {
-  return isa<ObjCInterfaceType>(CanonicalType) ||=20
+  return isa<ObjCInterfaceType>(CanonicalType) ||
     isa<ObjCObjectType>(CanonicalType);
 }
 inline bool Type::isAtomicType() const {
@@ -4766,11 +4804,87 @@
 }
=20
 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
+  assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
   if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(this))
     return (BT->getKind() =3D=3D (BuiltinType::Kind) K);
   return false;
 }
=20
+inline bool Type::isNonOverloadPlaceholderType() const {
+  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(this))
+    return BT->isNonOverloadPlaceholderType();
+  return false;
+}
+
+inline bool Type::isVoidType() const {
+  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
+    return BT->getKind() =3D=3D BuiltinType::Void;
+  return false;
+}
+
+inline bool Type::isHalfType() const {
+  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
+    return BT->getKind() =3D=3D BuiltinType::Half;
+  // FIXME: Should we allow complex __fp16? Probably not.
+  return false;
+}
+
+inline bool Type::isNullPtrType() const {
+  if (const BuiltinType *BT =3D getAs<BuiltinType>())
+    return BT->getKind() =3D=3D BuiltinType::NullPtr;
+  return false;
+}
+
+extern bool IsEnumDeclComplete(EnumDecl *);
+extern bool IsEnumDeclScoped(EnumDecl *);
+
+inline bool Type::isIntegerType() const {
+  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
+    return BT->getKind() >=3D BuiltinType::Bool &&
+           BT->getKind() <=3D BuiltinType::Int128;
+  if (const EnumType *ET =3D dyn_cast<EnumType>(CanonicalType)) {
+    // Incomplete enum types are not treated as integer types.
+    // FIXME: In C++, enum types are never integer types.
+    return IsEnumDeclComplete(ET->getDecl()) &&
+      !IsEnumDeclScoped(ET->getDecl());
+  }
+  return false;
+}
+
+inline bool Type::isScalarType() const {
+  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
+    return BT->getKind() > BuiltinType::Void &&
+           BT->getKind() <=3D BuiltinType::NullPtr;
+  if (const EnumType *ET =3D dyn_cast<EnumType>(CanonicalType))
+    // Enums are scalar types, but only if they are defined.  Incomplete e=
nums
+    // are not treated as scalar types.
+    return IsEnumDeclComplete(ET->getDecl());
+  return isa<PointerType>(CanonicalType) ||
+         isa<BlockPointerType>(CanonicalType) ||
+         isa<MemberPointerType>(CanonicalType) ||
+         isa<ComplexType>(CanonicalType) ||
+         isa<ObjCObjectPointerType>(CanonicalType);
+}
+
+inline bool Type::isIntegralOrEnumerationType() const {
+  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
+    return BT->getKind() >=3D BuiltinType::Bool &&
+           BT->getKind() <=3D BuiltinType::Int128;
+
+  // Check for a complete enum type; incomplete enum types are not properl=
y an
+  // enumeration type in the sense required here.
+  if (const EnumType *ET =3D dyn_cast<EnumType>(CanonicalType))
+    return IsEnumDeclComplete(ET->getDecl());
+
+  return false; =20
+}
+
+inline bool Type::isBooleanType() const {
+  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
+    return BT->getKind() =3D=3D BuiltinType::Bool;
+  return false;
+}
+
 /// \brief Determines whether this is a type for which one can define
 /// an overloaded operator.
 inline bool Type::isOverloadableType() const {
@@ -4822,15 +4936,15 @@
          bool isArrayType =3D (llvm::is_same<T, ArrayType>::value ||
                              llvm::is_base_of<ArrayType, T>::value)>
 struct ArrayType_cannot_be_used_with_getAs { };
- =20
+
 template<typename T>
 struct ArrayType_cannot_be_used_with_getAs<T, true>;
- =20
+
 /// Member-template getAs<specific type>'.
 template <typename T> const T *Type::getAs() const {
   ArrayType_cannot_be_used_with_getAs<T> at;
   (void)at;
- =20
+
   // If this is directly a T type, return it.
   if (const T *Ty =3D dyn_cast<T>(this))
     return Ty;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/TypeLoc.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/TypeLoc.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/TypeLoc.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/TemplateBase.h"
 #include "clang/Basic/Specifiers.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
   class ASTContext;
@@ -93,9 +94,11 @@
   SourceLocation getEndLoc() const;
=20
   /// \brief Get the full source range.
-  SourceRange getSourceRange() const {
+  SourceRange getSourceRange() const LLVM_READONLY {
     return SourceRange(getBeginLoc(), getEndLoc());
   }
+  SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc();=
 }
+  SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
=20
   /// \brief Get the local source range.
   SourceRange getLocalSourceRange() const {
@@ -159,7 +162,8 @@
   static bool classof(const TypeLoc *TL) { return true; }
=20
 private:
-  static void initializeImpl(ASTContext &Context, TypeLoc TL, SourceLocati=
on Loc);
+  static void initializeImpl(ASTContext &Context, TypeLoc TL,
+                             SourceLocation Loc);
   static TypeLoc getNextTypeLocImpl(TypeLoc TL);
   static TypeLoc IgnoreParensImpl(TypeLoc TL);
   static SourceRange getLocalSourceRangeImpl(TypeLoc TL);
@@ -226,7 +230,7 @@
=20
   /// \brief Returns the size of the type source info data block.
   unsigned getFullDataSize() const {
-    return getLocalDataSize() +=20
+    return getLocalDataSize() +
       getFullDataSizeForType(getType().getLocalUnqualifiedType());
   }
=20
@@ -326,7 +330,7 @@
   void *getExtraLocalData() const {
     return getLocalData() + 1;
   }
- =20
+
   void *getNonLocalData() const {
     return static_cast<char*>(Base::Data) + asDerived()->getLocalDataSize(=
);
   }
@@ -392,7 +396,7 @@
=20
 /// \brief A reasonable base class for TypeLocs that correspond to
 /// types that are written as a type-specifier.
-class TypeSpecTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,=20
+class TypeSpecTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
                                                TypeSpecTypeLoc,
                                                Type,
                                                TypeSpecLocInfo> {
@@ -566,10 +570,11 @@
 public:
   TagDecl *getDecl() const { return getTypePtr()->getDecl(); }
=20
-  /// \brief True if the tag was defined in this type specifier.=20
+  /// \brief True if the tag was defined in this type specifier.
   bool isDefinition() const {
-    return getDecl()->isCompleteDefinition() &&
-         (getNameLoc().isInvalid() || getNameLoc() =3D=3D getDecl()->getLo=
cation());
+    TagDecl *D =3D getDecl();
+    return D->isCompleteDefinition() &&
+         (D->getIdentifier() =3D=3D 0 || D->getLocation() =3D=3D getNameLo=
c());
   }
 };
=20
@@ -789,7 +794,7 @@
     assert(i < getNumProtocols() && "Index is out of bounds!");
     return *(this->getTypePtr()->qual_begin() + i);
   }
- =20
+
   bool hasBaseTypeAsWritten() const {
     return getLocalData()->HasBaseTypeAsWritten;
   }
@@ -900,11 +905,11 @@
   SourceLocation StarLoc;
 };
=20
-/// A base class for=20
+/// A base class for
 template <class Derived, class TypeClass, class LocalData =3D PointerLikeL=
ocInfo>
 class PointerLikeTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc, Derived,
                                                   TypeClass, LocalData> {
-public: =20
+public:
   SourceLocation getSigilLoc() const {
     return this->getLocalData()->StarLoc;
   }
@@ -1077,6 +1082,10 @@
     getLocalData()->TrailingReturn =3D Trailing;
   }
=20
+  ArrayRef<ParmVarDecl *> getParams() const {
+    return ArrayRef<ParmVarDecl *>(getParmArray(), getNumArgs());
+  }
+
   // ParmVarDecls* are stored after Info, one for each argument.
   ParmVarDecl **getParmArray() const {
     return (ParmVarDecl**) getExtraLocalData();
@@ -1213,6 +1222,7 @@
 };
=20
 struct TemplateSpecializationLocInfo : TemplateNameLocInfo {
+  SourceLocation TemplateKWLoc;
   SourceLocation LAngleLoc;
   SourceLocation RAngleLoc;
 };
@@ -1223,6 +1233,13 @@
                            TemplateSpecializationType,
                            TemplateSpecializationLocInfo> {
 public:
+  SourceLocation getTemplateKeywordLoc() const {
+    return getLocalData()->TemplateKWLoc;
+  }
+  void setTemplateKeywordLoc(SourceLocation Loc) {
+    getLocalData()->TemplateKWLoc =3D Loc;
+  }
+
   SourceLocation getLAngleLoc() const {
     return getLocalData()->LAngleLoc;
   }
@@ -1271,13 +1288,17 @@
   }
=20
   SourceRange getLocalSourceRange() const {
-    return SourceRange(getTemplateNameLoc(), getRAngleLoc());
+    if (getTemplateKeywordLoc().isValid())
+      return SourceRange(getTemplateKeywordLoc(), getRAngleLoc());
+    else
+      return SourceRange(getTemplateNameLoc(), getRAngleLoc());
   }
=20
   void initializeLocal(ASTContext &Context, SourceLocation Loc) {
+    setTemplateKeywordLoc(Loc);
+    setTemplateNameLoc(Loc);
     setLAngleLoc(Loc);
     setRAngleLoc(Loc);
-    setTemplateNameLoc(Loc);
     initializeArgLocs(Context, getNumArgs(), getTypePtr()->getArgs(),
                       getArgInfos(), Loc);
   }
@@ -1475,10 +1496,8 @@
 };
=20
 struct ElaboratedLocInfo {
-  SourceLocation KeywordLoc;
- =20
-  /// \brief Opaque data pointer used to reconstruct a nested-name-specifi=
er
-  /// from=20
+  SourceLocation ElaboratedKWLoc;
+  /// \brief Data associated with the nested-name-specifier location.
   void *QualifierData;
 };
=20
@@ -1487,31 +1506,32 @@
                                                  ElaboratedType,
                                                  ElaboratedLocInfo> {
 public:
-  SourceLocation getKeywordLoc() const {
-    return this->getLocalData()->KeywordLoc;
+  SourceLocation getElaboratedKeywordLoc() const {
+    return this->getLocalData()->ElaboratedKWLoc;
   }
-  void setKeywordLoc(SourceLocation Loc) {
-    this->getLocalData()->KeywordLoc =3D Loc;
+  void setElaboratedKeywordLoc(SourceLocation Loc) {
+    this->getLocalData()->ElaboratedKWLoc =3D Loc;
   }
=20
   NestedNameSpecifierLoc getQualifierLoc() const {
-    return NestedNameSpecifierLoc(getTypePtr()->getQualifier(),=20
+    return NestedNameSpecifierLoc(getTypePtr()->getQualifier(),
                                   getLocalData()->QualifierData);
   }
-=20
+
   void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc) {
-    assert(QualifierLoc.getNestedNameSpecifier()=20
+    assert(QualifierLoc.getNestedNameSpecifier()
                                             =3D=3D getTypePtr()->getQualif=
ier() &&
            "Inconsistent nested-name-specifier pointer");
     getLocalData()->QualifierData =3D QualifierLoc.getOpaqueData();
   }
=20
   SourceRange getLocalSourceRange() const {
-    if (getKeywordLoc().isValid())
+    if (getElaboratedKeywordLoc().isValid())
       if (getQualifierLoc())
-        return SourceRange(getKeywordLoc(), getQualifierLoc().getEndLoc());
+        return SourceRange(getElaboratedKeywordLoc(),
+                           getQualifierLoc().getEndLoc());
       else
-        return SourceRange(getKeywordLoc());
+        return SourceRange(getElaboratedKeywordLoc());
     else
       return getQualifierLoc().getSourceRange();
   }
@@ -1537,9 +1557,6 @@
 // type is some sort of TypeDeclTypeLoc.
 struct DependentNameLocInfo : ElaboratedLocInfo {
   SourceLocation NameLoc;
- =20
-  /// \brief Data associated with the nested-name-specifier location.
-  void *QualifierData;
 };
=20
 class DependentNameTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc,
@@ -1547,25 +1564,25 @@
                                                     DependentNameType,
                                                     DependentNameLocInfo> {
 public:
-  SourceLocation getKeywordLoc() const {
-    return this->getLocalData()->KeywordLoc;
+  SourceLocation getElaboratedKeywordLoc() const {
+    return this->getLocalData()->ElaboratedKWLoc;
   }
-  void setKeywordLoc(SourceLocation Loc) {
-    this->getLocalData()->KeywordLoc =3D Loc;
+  void setElaboratedKeywordLoc(SourceLocation Loc) {
+    this->getLocalData()->ElaboratedKWLoc =3D Loc;
   }
=20
   NestedNameSpecifierLoc getQualifierLoc() const {
-    return NestedNameSpecifierLoc(getTypePtr()->getQualifier(),=20
+    return NestedNameSpecifierLoc(getTypePtr()->getQualifier(),
                                   getLocalData()->QualifierData);
   }
-     =20
+
   void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc) {
-    assert(QualifierLoc.getNestedNameSpecifier()=20
+    assert(QualifierLoc.getNestedNameSpecifier()
                                             =3D=3D getTypePtr()->getQualif=
ier() &&
            "Inconsistent nested-name-specifier pointer");
     getLocalData()->QualifierData =3D QualifierLoc.getOpaqueData();
   }
-                                                     =20
+
   SourceLocation getNameLoc() const {
     return this->getLocalData()->NameLoc;
   }
@@ -1574,8 +1591,8 @@
   }
=20
   SourceRange getLocalSourceRange() const {
-    if (getKeywordLoc().isValid())
-      return SourceRange(getKeywordLoc(), getNameLoc());
+    if (getElaboratedKeywordLoc().isValid())
+      return SourceRange(getElaboratedKeywordLoc(), getNameLoc());
     else
       return SourceRange(getQualifierLoc().getBeginLoc(), getNameLoc());
   }
@@ -1590,7 +1607,7 @@
 };
=20
 struct DependentTemplateSpecializationLocInfo : DependentNameLocInfo {
-  SourceLocation KeywordLoc;
+  SourceLocation TemplateKWLoc;
   SourceLocation LAngleLoc;
   SourceLocation RAngleLoc;
   // followed by a TemplateArgumentLocInfo[]
@@ -1602,41 +1619,48 @@
                            DependentTemplateSpecializationType,
                            DependentTemplateSpecializationLocInfo> {
 public:
-  SourceLocation getKeywordLoc() const {
-    return this->getLocalData()->KeywordLoc;
+  SourceLocation getElaboratedKeywordLoc() const {
+    return this->getLocalData()->ElaboratedKWLoc;
   }
-  void setKeywordLoc(SourceLocation Loc) {
-    this->getLocalData()->KeywordLoc =3D Loc;
+  void setElaboratedKeywordLoc(SourceLocation Loc) {
+    this->getLocalData()->ElaboratedKWLoc =3D Loc;
   }
=20
   NestedNameSpecifierLoc getQualifierLoc() const {
     if (!getLocalData()->QualifierData)
       return NestedNameSpecifierLoc();
-   =20
-    return NestedNameSpecifierLoc(getTypePtr()->getQualifier(),=20
+
+    return NestedNameSpecifierLoc(getTypePtr()->getQualifier(),
                                   getLocalData()->QualifierData);
   }
-  =20
+
   void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc) {
     if (!QualifierLoc) {
-      // Even if we have a nested-name-specifier in the dependent=20
+      // Even if we have a nested-name-specifier in the dependent
       // template specialization type, we won't record the nested-name-spe=
cifier
       // location information when this type-source location information is
       // part of a nested-name-specifier.
       getLocalData()->QualifierData =3D 0;
       return;
     }
-   =20
-    assert(QualifierLoc.getNestedNameSpecifier()=20
+
+    assert(QualifierLoc.getNestedNameSpecifier()
                                         =3D=3D getTypePtr()->getQualifier(=
) &&
            "Inconsistent nested-name-specifier pointer");
     getLocalData()->QualifierData =3D QualifierLoc.getOpaqueData();
   }
=20
-  SourceLocation getNameLoc() const {
+  SourceLocation getTemplateKeywordLoc() const {
+    return getLocalData()->TemplateKWLoc;
+  }
+  void setTemplateKeywordLoc(SourceLocation Loc) {
+    getLocalData()->TemplateKWLoc =3D Loc;
+  }
+
+  SourceLocation getTemplateNameLoc() const {
     return this->getLocalData()->NameLoc;
   }
-  void setNameLoc(SourceLocation Loc) {
+  void setTemplateNameLoc(SourceLocation Loc) {
     this->getLocalData()->NameLoc =3D Loc;
   }
=20
@@ -1670,12 +1694,14 @@
   }
=20
   SourceRange getLocalSourceRange() const {
-    if (getKeywordLoc().isValid())
-      return SourceRange(getKeywordLoc(), getRAngleLoc());
+    if (getElaboratedKeywordLoc().isValid())
+      return SourceRange(getElaboratedKeywordLoc(), getRAngleLoc());
     else if (getQualifierLoc())
       return SourceRange(getQualifierLoc().getBeginLoc(), getRAngleLoc());
+    else if (getTemplateKeywordLoc().isValid())
+      return SourceRange(getTemplateKeywordLoc(), getRAngleLoc());
     else
-      return SourceRange(getNameLoc(), getRAngleLoc());
+      return SourceRange(getTemplateNameLoc(), getRAngleLoc());
   }
=20
   void copy(DependentTemplateSpecializationTypeLoc Loc) {
@@ -1702,7 +1728,7 @@
 };
=20
 class PackExpansionTypeLoc
-  : public ConcreteTypeLoc<UnqualTypeLoc, PackExpansionTypeLoc,=20
+  : public ConcreteTypeLoc<UnqualTypeLoc, PackExpansionTypeLoc,
                            PackExpansionType, PackExpansionTypeLocInfo> {
 public:
   SourceLocation getEllipsisLoc() const {
@@ -1736,7 +1762,7 @@
=20
 class AtomicTypeLoc : public ConcreteTypeLoc<UnqualTypeLoc, AtomicTypeLoc,
                                              AtomicType, AtomicTypeLocInfo=
> {
-public: =20
+public:
   TypeLoc getValueLoc() const {
     return this->getInnerTypeLoc();
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/TypeVisitor.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/TypeVisitor.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/TypeVisitor.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -28,11 +28,11 @@
   RetTy Visit(const Type *T) {
     // Top switch stmt: dispatch to VisitFooType for each FooType.
     switch (T->getTypeClass()) {
-    default: llvm_unreachable("Unknown type class!");
 #define ABSTRACT_TYPE(CLASS, PARENT)
 #define TYPE(CLASS, PARENT) case Type::CLASS: DISPATCH(CLASS##Type);
 #include "clang/AST/TypeNodes.def"
     }
+    llvm_unreachable("Unknown type class!");
   }
=20
   // If the implementation chooses not to implement a certain visit method=
, fall
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/AST/VTableBuilder.h
--- a/head/contrib/llvm/tools/clang/include/clang/AST/VTableBuilder.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/AST/VTableBuilder.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -34,16 +34,16 @@
     CK_OffsetToTop,
     CK_RTTI,
     CK_FunctionPointer,
-   =20
+
     /// CK_CompleteDtorPointer - A pointer to the complete destructor.
     CK_CompleteDtorPointer,
-   =20
+
     /// CK_DeletingDtorPointer - A pointer to the deleting destructor.
     CK_DeletingDtorPointer,
-   =20
+
     /// CK_UnusedFunctionPointer - In some cases, a vtable function pointer
     /// will end up never being called. Such vtable function pointers are
-    /// represented as a CK_UnusedFunctionPointer.=20
+    /// represented as a CK_UnusedFunctionPointer.
     CK_UnusedFunctionPointer
   };
=20
@@ -60,34 +60,34 @@
   static VTableComponent MakeOffsetToTop(CharUnits Offset) {
     return VTableComponent(CK_OffsetToTop, Offset);
   }
- =20
+
   static VTableComponent MakeRTTI(const CXXRecordDecl *RD) {
     return VTableComponent(CK_RTTI, reinterpret_cast<uintptr_t>(RD));
   }
=20
   static VTableComponent MakeFunction(const CXXMethodDecl *MD) {
-    assert(!isa<CXXDestructorDecl>(MD) &&=20
+    assert(!isa<CXXDestructorDecl>(MD) &&
            "Don't use MakeFunction with destructors!");
=20
-    return VTableComponent(CK_FunctionPointer,=20
+    return VTableComponent(CK_FunctionPointer,
                            reinterpret_cast<uintptr_t>(MD));
   }
- =20
+
   static VTableComponent MakeCompleteDtor(const CXXDestructorDecl *DD) {
     return VTableComponent(CK_CompleteDtorPointer,
                            reinterpret_cast<uintptr_t>(DD));
   }
=20
   static VTableComponent MakeDeletingDtor(const CXXDestructorDecl *DD) {
-    return VTableComponent(CK_DeletingDtorPointer,=20
+    return VTableComponent(CK_DeletingDtorPointer,
                            reinterpret_cast<uintptr_t>(DD));
   }
=20
   static VTableComponent MakeUnusedFunction(const CXXMethodDecl *MD) {
-    assert(!isa<CXXDestructorDecl>(MD) &&=20
+    assert(!isa<CXXDestructorDecl>(MD) &&
            "Don't use MakeUnusedFunction with destructors!");
     return VTableComponent(CK_UnusedFunctionPointer,
-                           reinterpret_cast<uintptr_t>(MD));              =
            =20
+                           reinterpret_cast<uintptr_t>(MD));
   }
=20
   static VTableComponent getFromOpaqueInteger(uint64_t I) {
@@ -101,88 +101,88 @@
=20
   CharUnits getVCallOffset() const {
     assert(getKind() =3D=3D CK_VCallOffset && "Invalid component kind!");
-   =20
+
     return getOffset();
   }
=20
   CharUnits getVBaseOffset() const {
     assert(getKind() =3D=3D CK_VBaseOffset && "Invalid component kind!");
-   =20
+
     return getOffset();
   }
=20
   CharUnits getOffsetToTop() const {
     assert(getKind() =3D=3D CK_OffsetToTop && "Invalid component kind!");
-   =20
+
     return getOffset();
   }
- =20
+
   const CXXRecordDecl *getRTTIDecl() const {
     assert(getKind() =3D=3D CK_RTTI && "Invalid component kind!");
-   =20
+
     return reinterpret_cast<CXXRecordDecl *>(getPointer());
   }
- =20
+
   const CXXMethodDecl *getFunctionDecl() const {
     assert(getKind() =3D=3D CK_FunctionPointer);
-   =20
+
     return reinterpret_cast<CXXMethodDecl *>(getPointer());
   }
=20
   const CXXDestructorDecl *getDestructorDecl() const {
     assert((getKind() =3D=3D CK_CompleteDtorPointer ||
             getKind() =3D=3D CK_DeletingDtorPointer) && "Invalid component=
 kind!");
-   =20
+
     return reinterpret_cast<CXXDestructorDecl *>(getPointer());
   }
=20
   const CXXMethodDecl *getUnusedFunctionDecl() const {
     assert(getKind() =3D=3D CK_UnusedFunctionPointer);
-   =20
+
     return reinterpret_cast<CXXMethodDecl *>(getPointer());
   }
- =20
+
 private:
   VTableComponent(Kind ComponentKind, CharUnits Offset) {
-    assert((ComponentKind =3D=3D CK_VCallOffset ||=20
+    assert((ComponentKind =3D=3D CK_VCallOffset ||
             ComponentKind =3D=3D CK_VBaseOffset ||
             ComponentKind =3D=3D CK_OffsetToTop) && "Invalid component kin=
d!");
     assert(Offset.getQuantity() <=3D ((1LL << 56) - 1) && "Offset is too b=
ig!");
-   =20
+
     Value =3D ((Offset.getQuantity() << 3) | ComponentKind);
   }
=20
   VTableComponent(Kind ComponentKind, uintptr_t Ptr) {
-    assert((ComponentKind =3D=3D CK_RTTI ||=20
+    assert((ComponentKind =3D=3D CK_RTTI ||
             ComponentKind =3D=3D CK_FunctionPointer ||
             ComponentKind =3D=3D CK_CompleteDtorPointer ||
             ComponentKind =3D=3D CK_DeletingDtorPointer ||
             ComponentKind =3D=3D CK_UnusedFunctionPointer) &&
             "Invalid component kind!");
-   =20
+
     assert((Ptr & 7) =3D=3D 0 && "Pointer not sufficiently aligned!");
-   =20
+
     Value =3D Ptr | ComponentKind;
   }
- =20
+
   CharUnits getOffset() const {
     assert((getKind() =3D=3D CK_VCallOffset || getKind() =3D=3D CK_VBaseOf=
fset ||
             getKind() =3D=3D CK_OffsetToTop) && "Invalid component kind!");
-   =20
+
     return CharUnits::fromQuantity(Value >> 3);
   }
=20
   uintptr_t getPointer() const {
-    assert((getKind() =3D=3D CK_RTTI ||=20
+    assert((getKind() =3D=3D CK_RTTI ||
             getKind() =3D=3D CK_FunctionPointer ||
             getKind() =3D=3D CK_CompleteDtorPointer ||
             getKind() =3D=3D CK_DeletingDtorPointer ||
             getKind() =3D=3D CK_UnusedFunctionPointer) &&
            "Invalid component kind!");
-   =20
+
     return static_cast<uintptr_t>(Value & ~7ULL);
   }
- =20
+
   explicit VTableComponent(uint64_t Value)
     : Value(Value) { }
=20
@@ -210,7 +210,7 @@
   /// VTableThunks - Contains thunks needed by vtables.
   uint64_t NumVTableThunks;
   VTableThunkTy *VTableThunks;
- =20
+
   /// Address points - Address points for all vtables.
   AddressPointsMapTy AddressPoints;
=20
@@ -265,10 +265,10 @@
   ASTContext &Context;
=20
 public:
-  typedef SmallVector<std::pair<uint64_t, ThunkInfo>, 1>=20
+  typedef SmallVector<std::pair<uint64_t, ThunkInfo>, 1>
     VTableThunksTy;
   typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
- =20
+
 private:
   /// MethodVTableIndices - Contains the index (relative to the vtable add=
ress
   /// point) where the function pointer for a virtual function is stored.
@@ -279,22 +279,22 @@
     VTableLayoutMapTy;
   VTableLayoutMapTy VTableLayouts;
=20
-  /// NumVirtualFunctionPointers - Contains the number of virtual function=20
+  /// NumVirtualFunctionPointers - Contains the number of virtual function
   /// pointers in the vtable for a given record decl.
   llvm::DenseMap<const CXXRecordDecl *, uint64_t> NumVirtualFunctionPointe=
rs;
=20
   typedef std::pair<const CXXRecordDecl *,
                     const CXXRecordDecl *> ClassPairTy;
=20
-  /// VirtualBaseClassOffsetOffsets - Contains the vtable offset (relative=
 to=20
+  /// VirtualBaseClassOffsetOffsets - Contains the vtable offset (relative=
 to
   /// the address point) in chars where the offsets for virtual bases of a=
 class
   /// are stored.
-  typedef llvm::DenseMap<ClassPairTy, CharUnits>=20
+  typedef llvm::DenseMap<ClassPairTy, CharUnits>
     VirtualBaseClassOffsetOffsetsMapTy;
   VirtualBaseClassOffsetOffsetsMapTy VirtualBaseClassOffsetOffsets;
=20
   typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksM=
apTy;
- =20
+
   /// Thunks - Contains all thunks that a given method decl will need.
   ThunksMapTy Thunks;
=20
@@ -312,7 +312,7 @@
   const VTableLayout &getVTableLayout(const CXXRecordDecl *RD) {
     ComputeVTableRelatedInformation(RD);
     assert(VTableLayouts.count(RD) && "No layout for this record decl!");
-   =20
+
     return *VTableLayouts[RD];
   }
=20
@@ -337,14 +337,14 @@
   /// getNumVirtualFunctionPointers - Return the number of virtual function
   /// pointers in the vtable for a given record decl.
   uint64_t getNumVirtualFunctionPointers(const CXXRecordDecl *RD);
- =20
+
   /// getMethodVTableIndex - Return the index (relative to the vtable addr=
ess
   /// point) where the function pointer for the given virtual function is
   /// stored.
   uint64_t getMethodVTableIndex(GlobalDecl GD);
=20
   /// getVirtualBaseOffsetOffset - Return the offset in chars (relative to=
 the
-  /// vtable address point) where the offset of the virtual base that cont=
ains=20
+  /// vtable address point) where the offset of the virtual base that cont=
ains
   /// the given base is stored, otherwise, if no virtual base contains the=
 given
   /// class, return 0.  Base must be a virtual base class or an unambigious
   /// base.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/Analyses/FormatString.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/FormatS=
tring.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/FormatS=
tring.h	Tue Apr 17 11:51:51 2012 +0300
@@ -66,11 +66,14 @@
     AsChar,       // 'hh'
     AsShort,      // 'h'
     AsLong,       // 'l'
-    AsLongLong,   // 'll', 'q' (BSD, deprecated)
+    AsLongLong,   // 'll'
+    AsQuad,       // 'q' (BSD, deprecated, for 64-bit integer types)
     AsIntMax,     // 'j'
     AsSizeT,      // 'z'
     AsPtrDiff,    // 't'
     AsLongDouble, // 'L'
+    AsAllocate,   // for '%as', GNU extension to C90 scanf
+    AsMAllocate,  // for '%ms', GNU extension to scanf
     AsWideChar =3D AsLong // for '%ls', only makes sense for printf
   };
=20
@@ -104,7 +107,7 @@
   const char *Position;
   Kind kind;
 };
- =20
+
 class ConversionSpecifier {
 public:
   enum Kind {
@@ -113,14 +116,14 @@
     cArg,
     dArg,
     iArg,
-    IntArgBeg =3D cArg, IntArgEnd =3D iArg,   =20
-   =20
+    IntArgBeg =3D cArg, IntArgEnd =3D iArg,
+
     oArg,
     uArg,
     xArg,
     XArg,
     UIntArgBeg =3D oArg, UIntArgEnd =3D XArg,
-   =20
+
     fArg,
     FArg,
     eArg,
@@ -130,49 +133,49 @@
     aArg,
     AArg,
     DoubleArgBeg =3D fArg, DoubleArgEnd =3D AArg,
-   =20
+
     sArg,
     pArg,
     nArg,
     PercentArg,
     CArg,
     SArg,
-   =20
+
     // ** Printf-specific **
- =20
+
     // Objective-C specific specifiers.
     ObjCObjArg,  // '@'
     ObjCBeg =3D ObjCObjArg, ObjCEnd =3D ObjCObjArg,
-   =20
+
     // FreeBSD specific specifiers
     bArg,
     DArg,
     rArg,
-   =20
+
     // GlibC specific specifiers.
     PrintErrno,   // 'm'
-   =20
+
     PrintfConvBeg =3D ObjCObjArg, PrintfConvEnd =3D PrintErrno,
-   =20
-    // ** Scanf-specific **   =20
+
+    // ** Scanf-specific **
     ScanListArg, // '['
     ScanfConvBeg =3D ScanListArg, ScanfConvEnd =3D ScanListArg
   };
- =20
+
   ConversionSpecifier(bool isPrintf)
     : IsPrintf(isPrintf), Position(0), EndScanList(0), kind(InvalidSpecifi=
er) {}
- =20
+
   ConversionSpecifier(bool isPrintf, const char *pos, Kind k)
     : IsPrintf(isPrintf), Position(pos), EndScanList(0), kind(k) {}
- =20
+
   const char *getStart() const {
     return Position;
   }
- =20
+
   StringRef getCharacters() const {
     return StringRef(getStart(), getLength());
   }
- =20
+
   bool consumesDataArgument() const {
     switch (kind) {
       case PrintErrno:
@@ -183,15 +186,16 @@
         return true;
     }
   }
- =20
+
   Kind getKind() const { return kind; }
   void setKind(Kind k) { kind =3D k; }
   unsigned getLength() const {
     return EndScanList ? EndScanList - Position : 1;
   }
- =20
+
+  bool isUIntArg() const { return kind >=3D UIntArgBeg && kind <=3D UIntAr=
gEnd; }
   const char *toString() const;
- =20
+
   bool isPrintfKind() const { return IsPrintf; }
=20
 protected:
@@ -204,15 +208,18 @@
 class ArgTypeResult {
 public:
   enum Kind { UnknownTy, InvalidTy, SpecificTy, ObjCPointerTy, CPointerTy,
-    CStrTy, WCStrTy, WIntTy };
+              AnyCharTy, CStrTy, WCStrTy, WIntTy };
 private:
   const Kind K;
   QualType T;
-  ArgTypeResult(bool) : K(InvalidTy) {}
+  const char *Name;
+  ArgTypeResult(bool) : K(InvalidTy), Name(0) {}
 public:
-  ArgTypeResult(Kind k =3D UnknownTy) : K(k) {}
-  ArgTypeResult(QualType t) : K(SpecificTy), T(t) {}
-  ArgTypeResult(CanQualType t) : K(SpecificTy), T(t) {}
+  ArgTypeResult(Kind k =3D UnknownTy) : K(k), Name(0) {}
+  ArgTypeResult(Kind k, const char *n) : K(k), Name(n) {}
+  ArgTypeResult(QualType t) : K(SpecificTy), T(t), Name(0) {}
+  ArgTypeResult(QualType t, const char *n) : K(SpecificTy), T(t), Name(n) =
 {}
+  ArgTypeResult(CanQualType t) : K(SpecificTy), T(t), Name(0) {}
=20
   static ArgTypeResult Invalid() { return ArgTypeResult(true); }
=20
@@ -227,6 +234,8 @@
   bool matchesAnyObjCObjectRef() const { return K =3D=3D ObjCPointerTy; }
=20
   QualType getRepresentativeType(ASTContext &C) const;
+
+  std::string getRepresentativeTypeName(ASTContext &C) const;
 };
=20
 class OptionalAmount {
@@ -302,9 +311,9 @@
   LengthModifier LM;
   OptionalAmount FieldWidth;
   ConversionSpecifier CS;
-    /// Positional arguments, an IEEE extension:
-    ///  IEEE Std 1003.1, 2004 Edition
-    ///  http://www.opengroup.org/onlinepubs/009695399/functions/printf.ht=
ml
+  /// Positional arguments, an IEEE extension:
+  ///  IEEE Std 1003.1, 2004 Edition
+  ///  http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
   bool UsesPositionalArg;
   unsigned argIndex;
 public:
@@ -342,8 +351,14 @@
   }
=20
   bool usesPositionalArg() const { return UsesPositionalArg; }
- =20
+
   bool hasValidLengthModifier() const;
+
+  bool hasStandardLengthModifier() const;
+
+  bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const;
+
+  bool hasStandardLengthConversionCombination() const;
 };
=20
 } // end analyze_format_string namespace
@@ -353,7 +368,7 @@
=20
 namespace analyze_printf {
=20
-class PrintfConversionSpecifier :=20
+class PrintfConversionSpecifier :
   public analyze_format_string::ConversionSpecifier  {
 public:
   PrintfConversionSpecifier()
@@ -364,9 +379,8 @@
=20
   bool isObjCArg() const { return kind >=3D ObjCBeg && kind <=3D ObjCEnd; }
   bool isIntArg() const { return kind >=3D IntArgBeg && kind <=3D IntArgEn=
d; }
-  bool isUIntArg() const { return kind >=3D UIntArgBeg && kind <=3D UIntAr=
gEnd; }
-  bool isDoubleArg() const { return kind >=3D DoubleArgBeg &&=20
-                                    kind <=3D DoubleArgBeg; }
+  bool isDoubleArg() const { return kind >=3D DoubleArgBeg &&
+                                    kind <=3D DoubleArgEnd; }
   unsigned getLength() const {
       // Conversion specifiers currently only are represented by
       // single characters, but we be flexible.
@@ -443,7 +457,7 @@
   const OptionalAmount &getPrecision() const {
     return Precision;
   }
- =20
+
   bool consumesDataArgument() const {
     return getConversionSpecifier().consumesDataArgument();
   }
@@ -453,9 +467,9 @@
   /// will return null if the format specifier does not have
   /// a matching data argument or the matching argument matches
   /// more than one type.
-  ArgTypeResult getArgType(ASTContext &Ctx) const;
+  ArgTypeResult getArgType(ASTContext &Ctx, bool IsObjCLiteral) const;
=20
-  const OptionalFlag &hasThousandsGrouping() const {=20
+  const OptionalFlag &hasThousandsGrouping() const {
       return HasThousandsGrouping;
   }
   const OptionalFlag &isLeftJustified() const { return IsLeftJustified; }
@@ -465,14 +479,15 @@
   const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; }
   bool usesPositionalArg() const { return UsesPositionalArg; }
=20
-    /// Changes the specifier and length according to a QualType, retainin=
g any
-    /// flags or options. Returns true on success, or false when a convers=
ion
-    /// was not successful.
-  bool fixType(QualType QT);
+  /// Changes the specifier and length according to a QualType, retaining =
any
+  /// flags or options. Returns true on success, or false when a conversion
+  /// was not successful.
+  bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx,
+               bool IsObjCLiteral);
=20
   void toString(raw_ostream &os) const;
=20
-    // Validation methods - to check if any element results in undefined b=
ehavior
+  // Validation methods - to check if any element results in undefined beh=
avior
   bool hasValidPlusPrefix() const;
   bool hasValidAlternativeForm() const;
   bool hasValidLeadingZeros() const;
@@ -500,16 +515,41 @@
     : ConversionSpecifier(false, pos, k) {}
=20
   void setEndScanList(const char *pos) { EndScanList =3D pos; }
-     =20
+
   static bool classof(const analyze_format_string::ConversionSpecifier *CS=
) {
     return !CS->isPrintfKind();
-  }     =20
+  }
 };
=20
+using analyze_format_string::ArgTypeResult;
 using analyze_format_string::LengthModifier;
 using analyze_format_string::OptionalAmount;
 using analyze_format_string::OptionalFlag;
=20
+class ScanfArgTypeResult : public ArgTypeResult {
+public:
+  enum Kind { UnknownTy, InvalidTy, CStrTy, WCStrTy, PtrToArgTypeResultTy =
};
+private:
+  Kind K;
+  ArgTypeResult A;
+  const char *Name;
+  QualType getRepresentativeType(ASTContext &C) const;
+public:
+  ScanfArgTypeResult(Kind k =3D UnknownTy, const char* n =3D 0) : K(k), Na=
me(n) {}
+  ScanfArgTypeResult(ArgTypeResult a, const char *n =3D 0)
+      : K(PtrToArgTypeResultTy), A(a), Name(n) {
+    assert(A.isValid());
+  }
+
+  static ScanfArgTypeResult Invalid() { return ScanfArgTypeResult(InvalidT=
y); }
+
+  bool isValid() const { return K !=3D InvalidTy; }
+
+  bool matchesType(ASTContext& C, QualType argTy) const;
+
+  std::string getRepresentativeTypeName(ASTContext& C) const;
+};
+
 class ScanfSpecifier : public analyze_format_string::FormatSpecifier {
   OptionalFlag SuppressAssignment; // '*'
 public:
@@ -533,11 +573,17 @@
   const ScanfConversionSpecifier &getConversionSpecifier() const {
     return cast<ScanfConversionSpecifier>(CS);
   }
- =20
+
   bool consumesDataArgument() const {
     return CS.consumesDataArgument() && !SuppressAssignment;
   }
=20
+  ScanfArgTypeResult getArgType(ASTContext &Ctx) const;
+
+  bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx);
+
+  void toString(raw_ostream &os) const;
+
   static ScanfSpecifier Parse(const char *beg, const char *end);
 };
=20
@@ -557,6 +603,8 @@
=20
   virtual void HandleNullChar(const char *nullCharacter) {}
=20
+  virtual void HandlePosition(const char *startPos, unsigned posLen) {}
+
   virtual void HandleInvalidPosition(const char *startPos, unsigned posLen,
                                      PositionContext p) {}
=20
@@ -599,11 +647,10 @@
 };
=20
 bool ParsePrintfString(FormatStringHandler &H,
-                       const char *beg, const char *end,
-                       bool FormatExtensions);
+                       const char *beg, const char *end, const LangOptions=
 &LO);
=20
 bool ParseScanfString(FormatStringHandler &H,
-                       const char *beg, const char *end);
+                      const char *beg, const char *end, const LangOptions =
&LO);
=20
 } // end analyze_format_string namespace
 } // end clang namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/Analyses/LiveVariables.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/LiveVar=
iables.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/LiveVar=
iables.h	Tue Apr 17 11:51:51 2012 +0300
@@ -52,7 +52,9 @@
     friend class LiveVariables;   =20
   };
  =20
-  struct Observer {
+  class Observer {
+    virtual void anchor();
+  public:
     virtual ~Observer() {}
    =20
     /// A callback invoked right before invoking the
@@ -70,7 +72,7 @@
   virtual ~LiveVariables();
  =20
   /// Compute the liveness information for a given CFG.
-  static LiveVariables *computeLiveness(AnalysisContext &analysisContext,
+  static LiveVariables *computeLiveness(AnalysisDeclContext &analysisConte=
xt,
                                         bool killAtAssign);
  =20
   /// Return true if a variable is live at the end of a
@@ -93,7 +95,7 @@
=20
   void runOnAllBlocks(Observer &obs);
  =20
-  static LiveVariables *create(AnalysisContext &analysisContext) {
+  static LiveVariables *create(AnalysisDeclContext &analysisContext) {
     return computeLiveness(analysisContext, true);
   }
  =20
@@ -106,7 +108,7 @@
  =20
 class RelaxedLiveVariables : public LiveVariables {
 public:
-  static LiveVariables *create(AnalysisContext &analysisContext) {
+  static LiveVariables *create(AnalysisDeclContext &analysisContext) {
     return computeLiveness(analysisContext, false);
   }
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/Analyses/ReachableCode.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/Reachab=
leCode.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/Reachab=
leCode.h	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 }
=20
 namespace clang {
-  class AnalysisContext;
+  class AnalysisDeclContext;
   class CFGBlock;
 }
=20
@@ -37,6 +37,7 @@
 namespace reachable_code {
=20
 class Callback {
+  virtual void anchor();
 public:
   virtual ~Callback() {}
   virtual void HandleUnreachable(SourceLocation L, SourceRange R1,
@@ -48,7 +49,7 @@
 unsigned ScanReachableFromBlock(const CFGBlock *Start,
                                 llvm::BitVector &Reachable);
=20
-void FindUnreachableCode(AnalysisContext &AC, Callback &CB);
+void FindUnreachableCode(AnalysisDeclContext &AC, Callback &CB);
=20
 }} // end namespace clang::reachable_code
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/Analyses/ThreadSafety.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadS=
afety.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadS=
afety.h	Tue Apr 17 11:51:51 2012 +0300
@@ -67,7 +67,7 @@
 class ThreadSafetyHandler {
 public:
   typedef llvm::StringRef Name;
-  virtual ~ThreadSafetyHandler() =3D 0;
+  virtual ~ThreadSafetyHandler();
=20
   /// Warn about lock expressions which fail to resolve to lockable object=
s.
   /// \param Loc -- the SourceLocation of the unresolved expression.
@@ -93,9 +93,14 @@
   /// 3. or when a mutex is locked but not unlocked inside a function.
   /// \param LockName -- A StringRef name for the lock expression, to be p=
rinted
   /// in the error message.
-  /// \param Loc -- The location of the lock expression where the mutex is=
 locked
+  /// \param LocLocked -- The location of the lock expression where the mu=
tex is
+  ///               locked
+  /// \param LocEndOfScope -- The location of the end of the scope where t=
he
+  ///               mutex is no longer held
   /// \param LEK -- which of the three above cases we should warn for
-  virtual void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc,
+  virtual void handleMutexHeldEndOfScope(Name LockName,
+                                         SourceLocation LocLocked,
+                                         SourceLocation LocEndOfScope,
                                          LockErrorKind LEK){}
=20
   /// Warn when a mutex is held exclusively and shared at the same point. =
For
@@ -143,7 +148,8 @@
 /// We traverse the blocks in the CFG, compute the set of mutexes that are=
 held
 /// at the end of each block, and issue warnings for thread safety violati=
ons.
 /// Each block in the CFG is traversed exactly once.
-void runThreadSafetyAnalysis(AnalysisContext &AC, ThreadSafetyHandler &Han=
dler);
+void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
+                             ThreadSafetyHandler &Handler);
=20
 /// \brief Helper function that returns a LockKind required for the given =
level
 /// of access.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/Analyses/UninitializedValues.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/Uniniti=
alizedValues.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/Analyses/Uniniti=
alizedValues.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D UninitializedValues.h - Finding uses of uninitialized values --*- C+=
+ -*-=3D=3D//
+//=3D UninitializedValues.h - Finding uses of uninitialized values -*- C++=
 -*-=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -17,12 +17,12 @@
=20
 namespace clang {
=20
-class AnalysisContext;
-class CFG; =20
+class AnalysisDeclContext;
+class CFG;
 class DeclContext;
 class Expr;
 class VarDecl;
- =20
+
 class UninitVariablesHandler {
 public:
   UninitVariablesHandler() {}
@@ -32,7 +32,7 @@
   virtual void handleUseOfUninitVariable(const Expr *ex,
                                          const VarDecl *vd,
                                          bool isAlwaysUninit) {}
- =20
+
   /// Called when the uninitialized variable analysis detects the
   /// idiom 'int x =3D x'.  All other uses of 'x' within the initializer
   /// are handled by handleUseOfUninitVariable.
@@ -45,7 +45,7 @@
 };
=20
 void runUninitializedVariablesAnalysis(const DeclContext &dc, const CFG &c=
fg,
-                                       AnalysisContext &ac,
+                                       AnalysisDeclContext &ac,
                                        UninitVariablesHandler &handler,
                                        UninitVariablesAnalysisStats &stats=
);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/AnalysisContext.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/AnalysisContext.=
h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/AnalysisContext.=
h	Tue Apr 17 11:51:51 2012 +0300
@@ -7,8 +7,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-// This file defines AnalysisContext, a class that manages the analysis co=
ntext
-// data for path sensitive analysis.
+// This file defines AnalysisDeclContext, a class that manages the analysis
+// context data for path sensitive analysis.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -38,17 +38,19 @@
 class ImplicitParamDecl;
 class LocationContextManager;
 class StackFrameContext;
- =20
+class AnalysisDeclContextManager;
+class LocationContext;
+
 namespace idx { class TranslationUnit; }
=20
 /// The base class of a hierarchy of objects representing analyses tied
-/// to AnalysisContext.
+/// to AnalysisDeclContext.
 class ManagedAnalysis {
 protected:
   ManagedAnalysis() {}
 public:
   virtual ~ManagedAnalysis();
- =20
+
   // Subclasses need to implement:
   //
   //  static const void *getTag();
@@ -56,47 +58,55 @@
   // Which returns a fixed pointer address to distinguish classes of
   // analysis objects.  They also need to implement:
   //
-  //  static [Derived*] create(AnalysisContext &Ctx);
+  //  static [Derived*] create(AnalysisDeclContext &Ctx);
   //
-  // which creates the analysis object given an AnalysisContext.
+  // which creates the analysis object given an AnalysisDeclContext.
 };
- =20
-/// AnalysisContext contains the context data for the function or method u=
nder
-/// analysis.
-class AnalysisContext {
+
+
+/// AnalysisDeclContext contains the context data for the function or meth=
od
+/// under analysis.
+class AnalysisDeclContext {
+  /// Backpoint to the AnalysisManager object that created this
+  /// AnalysisDeclContext. This may be null.
+  AnalysisDeclContextManager *Manager;
+
   const Decl *D;
=20
   // TranslationUnit is NULL if we don't have multiple translation units.
   idx::TranslationUnit *TU;
=20
-  llvm::OwningPtr<CFG> cfg, completeCFG;
-  llvm::OwningPtr<CFGStmtMap> cfgStmtMap;
+  OwningPtr<CFG> cfg, completeCFG;
+  OwningPtr<CFGStmtMap> cfgStmtMap;
=20
   CFG::BuildOptions cfgBuildOptions;
   CFG::BuildOptions::ForcedBlkExprs *forcedBlkExprs;
- =20
+
   bool builtCFG, builtCompleteCFG;
=20
-  llvm::OwningPtr<LiveVariables> liveness;
-  llvm::OwningPtr<LiveVariables> relaxedLiveness;
-  llvm::OwningPtr<ParentMap> PM;
-  llvm::OwningPtr<PseudoConstantAnalysis> PCA;
-  llvm::OwningPtr<CFGReverseBlockReachabilityAnalysis> CFA;
+  OwningPtr<LiveVariables> liveness;
+  OwningPtr<LiveVariables> relaxedLiveness;
+  OwningPtr<ParentMap> PM;
+  OwningPtr<PseudoConstantAnalysis> PCA;
+  OwningPtr<CFGReverseBlockReachabilityAnalysis> CFA;
=20
   llvm::BumpPtrAllocator A;
=20
-  // FIXME: remove.
   llvm::DenseMap<const BlockDecl*,void*> *ReferencedBlockVars;
=20
   void *ManagedAnalyses;
=20
 public:
-  AnalysisContext(const Decl *d, idx::TranslationUnit *tu);
+  AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
+                  const Decl *D,
+                  idx::TranslationUnit *TU);
=20
-  AnalysisContext(const Decl *d, idx::TranslationUnit *tu,
-                  const CFG::BuildOptions &buildOptions);
+  AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
+                  const Decl *D,
+                  idx::TranslationUnit *TU,
+                  const CFG::BuildOptions &BuildOptions);
=20
-  ~AnalysisContext();
+  ~AnalysisDeclContext();
=20
   ASTContext &getASTContext() { return D->getASTContext(); }
   const Decl *getDecl() const { return D; }
@@ -111,12 +121,12 @@
   const CFG::BuildOptions &getCFGBuildOptions() const {
     return cfgBuildOptions;
   }
- =20
+
   /// getAddEHEdges - Return true iff we are adding exceptional edges from
   /// callExprs.  If this is false, then try/catch statements and blocks
   /// reachable from them can appear to be dead in the CFG, analysis passe=
s must
   /// cope with that.
-  bool getAddEHEdges() const { return cfgBuildOptions.AddEHEdges; } =20
+  bool getAddEHEdges() const { return cfgBuildOptions.AddEHEdges; }
   bool getUseUnoptimizedCFG() const {
       return !cfgBuildOptions.PruneTriviallyFalseEdges;
   }
@@ -125,18 +135,18 @@
=20
   void registerForcedBlockExpression(const Stmt *stmt);
   const CFGBlock *getBlockForRegisteredExpression(const Stmt *stmt);
- =20
+
   Stmt *getBody() const;
   CFG *getCFG();
- =20
+
   CFGStmtMap *getCFGStmtMap();
=20
   CFGReverseBlockReachabilityAnalysis *getCFGReachablityAnalysis();
- =20
+
   /// Return a version of the CFG without any edges pruned.
   CFG *getUnoptimizedCFG();
=20
-  void dumpCFG();
+  void dumpCFG(bool ShowColors);
=20
   /// \brief Returns true if we have built a CFG for this analysis context.
   /// Note that this doesn't correspond to whether or not a valid CFG exis=
ts, it
@@ -152,9 +162,14 @@
     getReferencedBlockVars(const BlockDecl *BD);
=20
   /// Return the ImplicitParamDecl* associated with 'self' if this
-  /// AnalysisContext wraps an ObjCMethodDecl.  Returns NULL otherwise.
+  /// AnalysisDeclContext wraps an ObjCMethodDecl.  Returns NULL otherwise.
   const ImplicitParamDecl *getSelfDecl() const;
- =20
+
+  const StackFrameContext *getStackFrame(LocationContext const *Parent,
+                                         const Stmt *S,
+                                         const CFGBlock *Blk,
+                                         unsigned Idx);
+
   /// Return the specified analysis object, lazily running the analysis if
   /// necessary.  Return NULL if the analysis could not run.
   template <typename T>
@@ -168,31 +183,8 @@
   }
 private:
   ManagedAnalysis *&getAnalysisImpl(const void* tag);
-};
=20
-class AnalysisContextManager {
-  typedef llvm::DenseMap<const Decl*, AnalysisContext*> ContextMap;
-  ContextMap Contexts;
-  CFG::BuildOptions cfgBuildOptions;
-public:
-  AnalysisContextManager(bool useUnoptimizedCFG =3D false,
-                         bool addImplicitDtors =3D false,
-                         bool addInitializers =3D false);
- =20
-  ~AnalysisContextManager();
-
-  AnalysisContext *getContext(const Decl *D, idx::TranslationUnit *TU =3D =
0);
-
-  bool getUseUnoptimizedCFG() const {
-    return !cfgBuildOptions.PruneTriviallyFalseEdges;
-  }
- =20
-  CFG::BuildOptions &getCFGBuildOptions() {
-    return cfgBuildOptions;
-  }
-
-  /// Discard all previously created AnalysisContexts.
-  void clear();
+  LocationContextManager &getLocationContextManager();
 };
=20
 class LocationContext : public llvm::FoldingSetNode {
@@ -202,13 +194,14 @@
 private:
   ContextKind Kind;
=20
-  // AnalysisContext can't be const since some methods may modify its memb=
er.
-  AnalysisContext *Ctx;
+  // AnalysisDeclContext can't be const since some methods may modify its
+  // member.
+  AnalysisDeclContext *Ctx;
=20
   const LocationContext *Parent;
=20
 protected:
-  LocationContext(ContextKind k, AnalysisContext *ctx,
+  LocationContext(ContextKind k, AnalysisDeclContext *ctx,
                   const LocationContext *parent)
     : Kind(k), Ctx(ctx), Parent(parent) {}
=20
@@ -217,27 +210,27 @@
=20
   ContextKind getKind() const { return Kind; }
=20
-  AnalysisContext *getAnalysisContext() const { return Ctx; }
+  AnalysisDeclContext *getAnalysisDeclContext() const { return Ctx; }
=20
-  idx::TranslationUnit *getTranslationUnit() const {=20
-    return Ctx->getTranslationUnit();=20
+  idx::TranslationUnit *getTranslationUnit() const {
+    return Ctx->getTranslationUnit();
   }
=20
   const LocationContext *getParent() const { return Parent; }
=20
   bool isParentOf(const LocationContext *LC) const;
=20
-  const Decl *getDecl() const { return getAnalysisContext()->getDecl(); }
+  const Decl *getDecl() const { return getAnalysisDeclContext()->getDecl()=
; }
=20
-  CFG *getCFG() const { return getAnalysisContext()->getCFG(); }
+  CFG *getCFG() const { return getAnalysisDeclContext()->getCFG(); }
=20
   template <typename T>
   T *getAnalysis() const {
-    return getAnalysisContext()->getAnalysis<T>();
+    return getAnalysisDeclContext()->getAnalysis<T>();
   }
=20
   ParentMap &getParentMap() const {
-    return getAnalysisContext()->getParentMap();
+    return getAnalysisDeclContext()->getParentMap();
   }
=20
   const ImplicitParamDecl *getSelfDecl() const {
@@ -255,7 +248,7 @@
 public:
   static void ProfileCommon(llvm::FoldingSetNodeID &ID,
                             ContextKind ck,
-                            AnalysisContext *ctx,
+                            AnalysisDeclContext *ctx,
                             const LocationContext *parent,
                             const void *data);
 };
@@ -271,8 +264,8 @@
   unsigned Index;
=20
   friend class LocationContextManager;
-  StackFrameContext(AnalysisContext *ctx, const LocationContext *parent,
-                    const Stmt *s, const CFGBlock *blk,=20
+  StackFrameContext(AnalysisDeclContext *ctx, const LocationContext *paren=
t,
+                    const Stmt *s, const CFGBlock *blk,
                     unsigned idx)
     : LocationContext(StackFrame, ctx, parent), CallSite(s),
       Block(blk), Index(idx) {}
@@ -288,7 +281,7 @@
=20
   void Profile(llvm::FoldingSetNodeID &ID);
=20
-  static void Profile(llvm::FoldingSetNodeID &ID, AnalysisContext *ctx,
+  static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ctx,
                       const LocationContext *parent, const Stmt *s,
                       const CFGBlock *blk, unsigned idx) {
     ProfileCommon(ID, StackFrame, ctx, parent, s);
@@ -305,7 +298,7 @@
   const Stmt *Enter;
=20
   friend class LocationContextManager;
-  ScopeContext(AnalysisContext *ctx, const LocationContext *parent,
+  ScopeContext(AnalysisDeclContext *ctx, const LocationContext *parent,
                const Stmt *s)
     : LocationContext(Scope, ctx, parent), Enter(s) {}
=20
@@ -314,7 +307,7 @@
=20
   void Profile(llvm::FoldingSetNodeID &ID);
=20
-  static void Profile(llvm::FoldingSetNodeID &ID, AnalysisContext *ctx,
+  static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ctx,
                       const LocationContext *parent, const Stmt *s) {
     ProfileCommon(ID, Scope, ctx, parent, s);
   }
@@ -331,7 +324,8 @@
=20
   friend class LocationContextManager;
=20
-  BlockInvocationContext(AnalysisContext *ctx, const LocationContext *pare=
nt,
+  BlockInvocationContext(AnalysisDeclContext *ctx,
+                         const LocationContext *parent,
                          const BlockDecl *bd)
     : LocationContext(Block, ctx, parent), BD(bd) {}
=20
@@ -342,7 +336,7 @@
=20
   void Profile(llvm::FoldingSetNodeID &ID);
=20
-  static void Profile(llvm::FoldingSetNodeID &ID, AnalysisContext *ctx,
+  static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ctx,
                       const LocationContext *parent, const BlockDecl *bd) {
     ProfileCommon(ID, Block, ctx, parent, bd);
   }
@@ -357,12 +351,12 @@
 public:
   ~LocationContextManager();
=20
-  const StackFrameContext *getStackFrame(AnalysisContext *ctx,
+  const StackFrameContext *getStackFrame(AnalysisDeclContext *ctx,
                                          const LocationContext *parent,
                                          const Stmt *s,
                                          const CFGBlock *blk, unsigned idx=
);
=20
-  const ScopeContext *getScope(AnalysisContext *ctx,
+  const ScopeContext *getScope(AnalysisDeclContext *ctx,
                                const LocationContext *parent,
                                const Stmt *s);
=20
@@ -370,10 +364,69 @@
   void clear();
 private:
   template <typename LOC, typename DATA>
-  const LOC *getLocationContext(AnalysisContext *ctx,
+  const LOC *getLocationContext(AnalysisDeclContext *ctx,
                                 const LocationContext *parent,
                                 const DATA *d);
 };
=20
+class AnalysisDeclContextManager {
+  typedef llvm::DenseMap<const Decl*, AnalysisDeclContext*> ContextMap;
+
+  ContextMap Contexts;
+  LocationContextManager LocContexts;
+  CFG::BuildOptions cfgBuildOptions;
+
+public:
+  AnalysisDeclContextManager(bool useUnoptimizedCFG =3D false,
+                         bool addImplicitDtors =3D false,
+                         bool addInitializers =3D false);
+
+  ~AnalysisDeclContextManager();
+
+  AnalysisDeclContext *getContext(const Decl *D, idx::TranslationUnit *TU =
=3D 0);
+
+  bool getUseUnoptimizedCFG() const {
+    return !cfgBuildOptions.PruneTriviallyFalseEdges;
+  }
+
+  CFG::BuildOptions &getCFGBuildOptions() {
+    return cfgBuildOptions;
+  }
+
+  const StackFrameContext *getStackFrame(AnalysisDeclContext *Ctx,
+                                         LocationContext const *Parent,
+                                         const Stmt *S,
+                                         const CFGBlock *Blk,
+                                         unsigned Idx) {
+    return LocContexts.getStackFrame(Ctx, Parent, S, Blk, Idx);
+  }
+
+  // Get the top level stack frame.
+  const StackFrameContext *getStackFrame(Decl const *D,
+                                         idx::TranslationUnit *TU) {
+    return LocContexts.getStackFrame(getContext(D, TU), 0, 0, 0, 0);
+  }
+
+  // Get a stack frame with parent.
+  StackFrameContext const *getStackFrame(const Decl *D,
+                                         LocationContext const *Parent,
+                                         const Stmt *S,
+                                         const CFGBlock *Blk,
+                                         unsigned Idx) {
+    return LocContexts.getStackFrame(getContext(D), Parent, S, Blk, Idx);
+  }
+
+
+  /// Discard all previously created AnalysisDeclContexts.
+  void clear();
+
+private:
+  friend class AnalysisDeclContext;
+
+  LocationContextManager &getLocationContextManager() {
+    return LocContexts;
+  }
+};
+
 } // end clang namespace
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/AnalysisDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/AnalysisDiagnost=
ic.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/AnalysisDiagnost=
ic.h	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
   namespace diag {
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
 #define ANALYSISSTART
 #include "clang/Basic/DiagnosticAnalysisKinds.inc"
 #undef DIAG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/CFG.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/CFG.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/CFG.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -67,22 +67,22 @@
=20
   CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 =3D 0)
     : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
-      Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {} =20
+      Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {}
=20
 public:
   CFGElement() {}
=20
-  Kind getKind() const {=20
+  Kind getKind() const {
     unsigned x =3D Data2.getInt();
     x <<=3D 2;
     x |=3D Data1.getInt();
     return (Kind) x;
   }
-   =20
+
   bool isValid() const { return getKind() !=3D Invalid; }
=20
   operator bool() const { return isValid(); }
- =20
+
   template<class ElemTy> const ElemTy *getAs() const {
     if (llvm::isa<ElemTy>(this))
       return static_cast<const ElemTy*>(this);
@@ -96,7 +96,7 @@
 public:
   CFGStmt(Stmt *S) : CFGElement(Statement, S) {}
=20
-  const Stmt *getStmt() const {=20
+  const Stmt *getStmt() const {
     return static_cast<const Stmt *>(Data1.getPointer());
   }
=20
@@ -125,9 +125,9 @@
 /// by compiler on various occasions.
 class CFGImplicitDtor : public CFGElement {
 protected:
-  CFGImplicitDtor(Kind kind, const void *data1, const void *data2 =3D 0)=20
+  CFGImplicitDtor(Kind kind, const void *data1, const void *data2 =3D 0)
     : CFGElement(kind, data1, data2) {
-    assert(kind >=3D DTOR_BEGIN && kind <=3D DTOR_END);   =20
+    assert(kind >=3D DTOR_BEGIN && kind <=3D DTOR_END);
   }
=20
 public:
@@ -272,12 +272,12 @@
     ImplTy Impl;
   public:
     ElementList(BumpVectorContext &C) : Impl(C, 4) {}
-   =20
+
     typedef std::reverse_iterator<ImplTy::iterator>       iterator;
     typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
     typedef ImplTy::iterator                              reverse_iterator;
-    typedef ImplTy::const_iterator                        const_reverse_it=
erator;
- =20
+    typedef ImplTy::const_iterator                       const_reverse_ite=
rator;
+
     void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e,=
 C); }
     reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
         BumpVectorContext &C) {
@@ -286,7 +286,7 @@
=20
     CFGElement front() const { return Impl.back(); }
     CFGElement back() const { return Impl.front(); }
-   =20
+
     iterator begin() { return Impl.rbegin(); }
     iterator end() { return Impl.rend(); }
     const_iterator begin() const { return Impl.rbegin(); }
@@ -300,7 +300,7 @@
      assert(i < Impl.size());
      return Impl[Impl.size() - 1 - i];
    }
-   =20
+
     size_t size() const { return Impl.size(); }
     bool empty() const { return Impl.empty(); }
   };
@@ -344,10 +344,14 @@
   /// storage if the memory usage of CFGBlock becomes an issue.
   unsigned HasNoReturnElement : 1;
=20
+  /// Parent - The parent CFG that owns this CFGBlock.
+  CFG *Parent;
+
 public:
-  explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
-    : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
-      BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false=
) {}
+  explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
+    : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),=20
+      BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false=
),
+      Parent(parent) {}
   ~CFGBlock() {}
=20
   // Statement iterators
@@ -489,16 +493,19 @@
=20
   unsigned getBlockID() const { return BlockID; }
=20
-  void dump(const CFG *cfg, const LangOptions &LO) const;
-  void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
+  CFG *getParent() const { return Parent; }
+
+  void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors =3D fal=
se) const;
+  void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
+             bool ShowColors) const;
   void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
- =20
+
   void addSuccessor(CFGBlock *Block, BumpVectorContext &C) {
     if (Block)
       Block->Preds.push_back(this, C);
     Succs.push_back(Block, C);
   }
- =20
+
   void appendStmt(Stmt *statement, BumpVectorContext &C) {
     Elements.push_back(CFGStmt(statement), C);
   }
@@ -515,7 +522,7 @@
   void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
     Elements.push_back(CFGMemberDtor(FD), C);
   }
- =20
+
   void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
     Elements.push_back(CFGTemporaryDtor(E), C);
   }
@@ -554,22 +561,22 @@
     llvm::BitVector alwaysAddMask;
   public:
     typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
-    ForcedBlkExprs **forcedBlkExprs;   =20
+    ForcedBlkExprs **forcedBlkExprs;
=20
     bool PruneTriviallyFalseEdges;
     bool AddEHEdges;
     bool AddInitializers;
     bool AddImplicitDtors;
-   =20
+
     bool alwaysAdd(const Stmt *stmt) const {
       return alwaysAddMask[stmt->getStmtClass()];
     }
-   =20
+
     BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val =3D tru=
e) {
       alwaysAddMask[stmtClass] =3D val;
       return *this;
     }
-   =20
+
     BuildOptions &setAllAlwaysAdd() {
       alwaysAddMask.set();
       return *this;
@@ -583,6 +590,55 @@
       ,AddImplicitDtors(false) {}
   };
=20
+  /// \brief Provides a custom implementation of the iterator class to hav=
e the
+  /// same interface as Function::iterator - iterator returns CFGBlock
+  /// (not a pointer to CFGBlock).
+  class graph_iterator {
+  public:
+    typedef const CFGBlock                  value_type;
+    typedef value_type&                     reference;
+    typedef value_type*                     pointer;
+    typedef BumpVector<CFGBlock*>::iterator ImplTy;
+
+    graph_iterator(const ImplTy &i) : I(i) {}
+
+    bool operator=3D=3D(const graph_iterator &X) const { return I =3D=3D X=
.I; }
+    bool operator!=3D(const graph_iterator &X) const { return I !=3D X.I; }
+
+    reference operator*()    const { return **I; }
+    pointer operator->()     const { return  *I; }
+    operator CFGBlock* ()          { return  *I; }
+
+    graph_iterator &operator++() { ++I; return *this; }
+    graph_iterator &operator--() { --I; return *this; }
+
+  private:
+    ImplTy I;
+  };
+
+  class const_graph_iterator {
+  public:
+    typedef const CFGBlock                  value_type;
+    typedef value_type&                     reference;
+    typedef value_type*                     pointer;
+    typedef BumpVector<CFGBlock*>::const_iterator ImplTy;
+
+    const_graph_iterator(const ImplTy &i) : I(i) {}
+
+    bool operator=3D=3D(const const_graph_iterator &X) const { return I =
=3D=3D X.I; }
+    bool operator!=3D(const const_graph_iterator &X) const { return I !=3D=
 X.I; }
+
+    reference operator*() const { return **I; }
+    pointer operator->()  const { return  *I; }
+    operator CFGBlock* () const { return  *I; }
+
+    const_graph_iterator &operator++() { ++I; return *this; }
+    const_graph_iterator &operator--() { --I; return *this; }
+
+  private:
+    ImplTy I;
+  };
+
   /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
   ///   constructed CFG belongs to the caller.
   static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
@@ -605,7 +661,7 @@
   // Block Iterators
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
=20
-  typedef BumpVector<CFGBlock*>                    CFGBlockListTy;   =20
+  typedef BumpVector<CFGBlock*>                    CFGBlockListTy;
   typedef CFGBlockListTy::iterator                 iterator;
   typedef CFGBlockListTy::const_iterator           const_iterator;
   typedef std::reverse_iterator<iterator>          reverse_iterator;
@@ -619,6 +675,15 @@
   const_iterator            begin()       const    { return Blocks.begin()=
; }
   const_iterator            end()         const    { return Blocks.end(); }
=20
+  graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); }
+  graph_iterator nodes_end() { return graph_iterator(Blocks.end()); }
+  const_graph_iterator nodes_begin() const {
+    return const_graph_iterator(Blocks.begin());
+  }
+  const_graph_iterator nodes_end() const {
+    return const_graph_iterator(Blocks.end());
+  }
+
   reverse_iterator          rbegin()               { return Blocks.rbegin(=
); }
   reverse_iterator          rend()                 { return Blocks.rend();=
 }
   const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(=
); }
@@ -631,7 +696,7 @@
=20
   CFGBlock *       getIndirectGotoBlock() { return IndirectGotoBlock; }
   const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock=
; }
- =20
+
   typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator;
   try_block_iterator try_blocks_begin() const {
     return TryDispatchBlocks.begin();
@@ -639,7 +704,7 @@
   try_block_iterator try_blocks_end() const {
     return TryDispatchBlocks.end();
   }
- =20
+
   void addTryDispatchBlock(const CFGBlock *block) {
     TryDispatchBlocks.push_back(block);
   }
@@ -681,13 +746,18 @@
   /// start at 0).
   unsigned getNumBlockIDs() const { return NumBlockIDs; }
=20
+  /// size - Return the total number of CFGBlocks within the CFG
+  /// This is simply a renaming of the getNumBlockIDs(). This is necessary=20
+  /// because the dominator implementation needs such an interface.
+  unsigned size() const { return NumBlockIDs; }
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // CFG Debugging: Pretty-Printing and Visualization.
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
=20
   void viewCFG(const LangOptions &LO) const;
-  void print(raw_ostream &OS, const LangOptions &LO) const;
-  void dump(const LangOptions &LO) const;
+  void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) cons=
t;
+  void dump(const LangOptions &LO, bool ShowColors) const;
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Internal: constructors and data.
@@ -701,7 +771,7 @@
   llvm::BumpPtrAllocator& getAllocator() {
     return BlkBVC.getAllocator();
   }
- =20
+
   BumpVectorContext &getBumpVectorContext() {
     return BlkBVC;
   }
@@ -717,11 +787,11 @@
   //  It represents a map from Expr* to integers to record the set of
   //  block-level expressions and their "statement number" in the CFG.
   void *    BlkExprMap;
- =20
+
   BumpVectorContext BlkBVC;
- =20
+
   CFGBlockListTy Blocks;
- =20
+
   /// C++ 'try' statements are modeled with an indirect dispatch block.
   /// This is the collection of such blocks present in the CFG.
   std::vector<const CFGBlock *> TryDispatchBlocks;
@@ -781,6 +851,20 @@
   { return N->succ_end(); }
 };
=20
+template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > {
+  typedef ::clang::CFGBlock NodeType;
+  typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
+
+  static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G)
+  { return G.Graph; }
+
+  static inline ChildIteratorType child_begin(NodeType* N)
+  { return N->pred_begin(); }
+
+  static inline ChildIteratorType child_end(NodeType* N)
+  { return N->pred_end(); }
+};
+
 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
   typedef const ::clang::CFGBlock NodeType;
   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
@@ -800,37 +884,55 @@
 template <> struct GraphTraits< ::clang::CFG* >
     : public GraphTraits< ::clang::CFGBlock *>  {
=20
-  typedef ::clang::CFG::iterator nodes_iterator;
+  typedef ::clang::CFG::graph_iterator nodes_iterator;
=20
-  static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
-  static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
-  static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
+  static NodeType     *getEntryNode(::clang::CFG* F) { return &F->getEntry=
(); }
+  static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_beg=
in();}
+  static nodes_iterator   nodes_end(::clang::CFG* F) { return F->nodes_end=
(); }
+  static unsigned              size(::clang::CFG* F) { return F->size(); }
 };
=20
 template <> struct GraphTraits<const ::clang::CFG* >
     : public GraphTraits<const ::clang::CFGBlock *>  {
=20
-  typedef ::clang::CFG::const_iterator nodes_iterator;
+  typedef ::clang::CFG::const_graph_iterator nodes_iterator;
=20
   static NodeType *getEntryNode( const ::clang::CFG* F) {
     return &F->getEntry();
   }
   static nodes_iterator nodes_begin( const ::clang::CFG* F) {
-    return F->begin();
+    return F->nodes_begin();
   }
   static nodes_iterator nodes_end( const ::clang::CFG* F) {
-    return F->end();
+    return F->nodes_end();
   }
+  static unsigned size(const ::clang::CFG* F) {
+    return F->size();
+  }
+};
+
+template <> struct GraphTraits<Inverse< ::clang::CFG*> >
+  : public GraphTraits<Inverse< ::clang::CFGBlock*> > {
+
+  typedef ::clang::CFG::graph_iterator nodes_iterator;
+
+  static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); }
+  static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_beg=
in();}
+  static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(=
); }
 };
=20
 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
   : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
=20
-  typedef ::clang::CFG::const_iterator nodes_iterator;
+  typedef ::clang::CFG::const_graph_iterator nodes_iterator;
=20
   static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExi=
t(); }
-  static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->beg=
in();}
-  static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end()=
; }
+  static nodes_iterator nodes_begin(const ::clang::CFG* F) {
+    return F->nodes_begin();
+  }
+  static nodes_iterator nodes_end(const ::clang::CFG* F) {
+    return F->nodes_end();
+  }
 };
 } // end llvm namespace
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/DomainSpecific/CocoaConventions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/DomainSpecific/C=
ocoaConventions.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/DomainSpecific/C=
ocoaConventions.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,25 +14,15 @@
 #ifndef LLVM_CLANG_ANALYSIS_DS_COCOA
 #define LLVM_CLANG_ANALYSIS_DS_COCOA
=20
-#include "clang/Basic/IdentifierTable.h"
+#include "clang/Basic/LLVM.h"
 #include "llvm/ADT/StringRef.h"
=20
 namespace clang {
 class FunctionDecl;
-class ObjCMethodDecl;
 class QualType;
  =20
 namespace ento {
 namespace cocoa {
-=20
-  enum NamingConvention { NoConvention, CreateRule, InitRule };
-
-  NamingConvention deriveNamingConvention(Selector S, const ObjCMethodDecl=
 *MD);
-
-  static inline bool followsFundamentalRule(Selector S,=20
-                                            const ObjCMethodDecl *MD) {
-    return deriveNamingConvention(S, MD) =3D=3D CreateRule;
-  }
  =20
   bool isRefType(QualType RetTy, StringRef Prefix,
                  StringRef Name =3D StringRef());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/ProgramPoint.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/ProgramPoint.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/ProgramPoint.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "clang/Analysis/CFG.h"
 #include "llvm/Support/DataTypes.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/ADT/StringRef.h"
@@ -28,7 +29,7 @@
=20
 namespace clang {
=20
-class AnalysisContext;
+class AnalysisDeclContext;
 class FunctionDecl;
 class LocationContext;
 class ProgramPointTag;
@@ -51,44 +52,72 @@
               CallEnterKind,
               CallExitKind,
               MinPostStmtKind =3D PostStmtKind,
-              MaxPostStmtKind =3D CallExitKind };
+              MaxPostStmtKind =3D CallExitKind,
+              EpsilonKind};
=20
 private:
-  std::pair<const void *, const void *> Data;
-  Kind K;
+  llvm::PointerIntPair<const void *, 2, unsigned> Data1;
+  llvm::PointerIntPair<const void *, 2, unsigned> Data2;
=20
   // The LocationContext could be NULL to allow ProgramPoint to be used in
   // context insensitive analysis.
-  const LocationContext *L;
+  llvm::PointerIntPair<const LocationContext *, 2, unsigned> L;
+
   const ProgramPointTag *Tag;
=20
   ProgramPoint();
  =20
 protected:
-  ProgramPoint(const void *P, Kind k, const LocationContext *l,
+  ProgramPoint(const void *P,
+               Kind k,
+               const LocationContext *l,
                const ProgramPointTag *tag =3D 0)
-    : Data(P, static_cast<const void*>(NULL)), K(k), L(l), Tag(tag) {}
-
-  ProgramPoint(const void *P1, const void *P2, Kind k, const LocationConte=
xt *l,
+    : Data1(P, ((unsigned) k) & 0x3),
+      Data2(0, (((unsigned) k) >> 2) & 0x3),
+      L(l, (((unsigned) k) >> 4) & 0x3),
+      Tag(tag) {
+        assert(getKind() =3D=3D k);
+        assert(getLocationContext() =3D=3D l);
+        assert(getData1() =3D=3D P);
+      }
+       =20
+  ProgramPoint(const void *P1,
+               const void *P2,
+               Kind k,
+               const LocationContext *l,
                const ProgramPointTag *tag =3D 0)
-    : Data(P1, P2), K(k), L(l), Tag(tag) {}
+    : Data1(P1, ((unsigned) k) & 0x3),
+      Data2(P2, (((unsigned) k) >> 2) & 0x3),
+      L(l, (((unsigned) k) >> 4) & 0x3),
+      Tag(tag) {}
=20
 protected:
-  const void *getData1() const { return Data.first; }
-  const void *getData2() const { return Data.second; }
+  const void *getData1() const { return Data1.getPointer(); }
+  const void *getData2() const { return Data2.getPointer(); }
+  void setData2(const void *d) { Data2.setPointer(d); }
=20
 public:
   /// Create a new ProgramPoint object that is the same as the original
   /// except for using the specified tag value.
   ProgramPoint withTag(const ProgramPointTag *tag) const {
-    return ProgramPoint(Data.first, Data.second, K, L, tag);
+    return ProgramPoint(getData1(), getData2(), getKind(),
+                        getLocationContext(), tag);
   }
=20
-  Kind getKind() const { return K; }
+  Kind getKind() const {
+    unsigned x =3D L.getInt();
+    x <<=3D 2;
+    x |=3D Data2.getInt();
+    x <<=3D 2;
+    x |=3D Data1.getInt();
+    return (Kind) x;
+  }
=20
   const ProgramPointTag *getTag() const { return Tag; }
=20
-  const LocationContext *getLocationContext() const { return L; }
+  const LocationContext *getLocationContext() const {
+    return L.getPointer();
+  }
=20
   // For use with DenseMap.  This hash is probably slow.
   unsigned getHashValue() const {
@@ -100,25 +129,30 @@
   static bool classof(const ProgramPoint*) { return true; }
=20
   bool operator=3D=3D(const ProgramPoint & RHS) const {
-    return K =3D=3D RHS.K && Data =3D=3D RHS.Data && L =3D=3D RHS.L && Tag=
 =3D=3D RHS.Tag;
+    return Data1 =3D=3D Data1 &&
+           Data2 =3D=3D RHS.Data2 &&
+           L =3D=3D RHS.L &&
+           Tag =3D=3D RHS.Tag;
   }
=20
   bool operator!=3D(const ProgramPoint &RHS) const {
-    return K !=3D RHS.K || Data !=3D RHS.Data || L !=3D RHS.L || Tag !=3D =
RHS.Tag;
+    return Data1 !=3D RHS.Data1 ||
+           Data2 !=3D RHS.Data2 ||
+           L !=3D RHS.L ||
+           Tag !=3D RHS.Tag;
   }
=20
   void Profile(llvm::FoldingSetNodeID& ID) const {
-    ID.AddInteger((unsigned) K);
-    ID.AddPointer(Data.first);
-    ID.AddPointer(Data.second);
-    ID.AddPointer(L);
+    ID.AddInteger((unsigned) getKind());
+    ID.AddPointer(getData1());
+    ID.AddPointer(getData2());
+    ID.AddPointer(getLocationContext());
     ID.AddPointer(Tag);
   }
=20
   static ProgramPoint getProgramPoint(const Stmt *S, ProgramPoint::Kind K,
                                       const LocationContext *LC,
                                       const ProgramPointTag *tag);
-
 };
=20
 class BlockEntrance : public ProgramPoint {
@@ -195,7 +229,7 @@
 class PostStmt : public StmtPoint {
 protected:
   PostStmt(const Stmt *S, const void *data, Kind k, const LocationContext =
*L,
-           const ProgramPointTag *tag =3D0)
+           const ProgramPointTag *tag =3D 0)
     : StmtPoint(S, data, k, L, tag) {}
=20
 public:
@@ -270,15 +304,29 @@
   }
 };
=20
+/// \class Represents a program point after a store evaluation.
 class PostStore : public PostStmt {
 public:
-  PostStore(const Stmt *S, const LocationContext *L,
+  /// Construct the post store point.
+  /// \param Loc can be used to store the information about the location=20
+  /// used in the form it was uttered in the code.
+  PostStore(const Stmt *S, const LocationContext *L, const void *Loc,
             const ProgramPointTag *tag =3D 0)
-    : PostStmt(S, PostStoreKind, L, tag) {}
+    : PostStmt(S, PostStoreKind, L, tag) {
+    assert(getData2() =3D=3D 0);
+    setData2(Loc);
+  }
=20
   static bool classof(const ProgramPoint* Location) {
     return Location->getKind() =3D=3D PostStoreKind;
   }
+ =20
+  /// \brief Returns the information about the location used in the store,
+  /// how it was uttered in the code.
+  const void *getLocationValue() const {
+    return getData2();
+  }
+
 };
=20
 class PostLValue : public PostStmt {
@@ -365,6 +413,21 @@
   }
 };
=20
+/// This is a meta program point, which should be skipped by all the diagn=
ostic
+/// reasoning etc.
+class EpsilonPoint : public ProgramPoint {
+public:
+  EpsilonPoint(const LocationContext *L, const void *Data1,
+               const void *Data2 =3D 0, const ProgramPointTag *tag =3D 0)
+    : ProgramPoint(Data1, Data2, EpsilonKind, L, tag) {}
+
+  const void *getData() const { return getData1(); }
+
+  static bool classof(const ProgramPoint* Location) {
+    return Location->getKind() =3D=3D EpsilonKind;
+  }
+};
+
 /// ProgramPoints can be "tagged" as representing points specific to a giv=
en
 /// analysis entity.  Tags are abstract annotations, with an associated
 /// description and potentially other information.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h
--- a/head/contrib/llvm/tools/clang/include/clang/Analysis/Visitors/CFGRecS=
tmtDeclVisitor.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Analysis/Visitors/CFGRecS=
tmtDeclVisitor.h	Tue Apr 17 11:51:51 2012 +0300
@@ -66,6 +66,7 @@
         DISPATCH_CASE(Record)    // FIXME: Refine.  VisitStructDecl?
         DISPATCH_CASE(CXXRecord)
         DISPATCH_CASE(Enum)
+        DISPATCH_CASE(Field)
         DISPATCH_CASE(UsingDirective)
         DISPATCH_CASE(Using)
       default:
@@ -82,8 +83,8 @@
   DEFAULT_DISPATCH(Typedef)
   DEFAULT_DISPATCH(Record)
   DEFAULT_DISPATCH(Enum)
+  DEFAULT_DISPATCH(Field)
   DEFAULT_DISPATCH(ObjCInterface)
-  DEFAULT_DISPATCH(ObjCClass)
   DEFAULT_DISPATCH(ObjCMethod)
   DEFAULT_DISPATCH(ObjCProtocol)
   DEFAULT_DISPATCH(ObjCCategory)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/Attr.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/Attr.td	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/Attr.td	Tue Apr 17 =
11:51:51 2012 +0300
@@ -93,6 +93,10 @@
   list<string> Namespaces =3D [];
   // Set to true for attributes with arguments which require delayed parsi=
ng.=20
   bit LateParsed =3D 0; =20
+  // Set to true for attributes which must be instantiated within templates
+  bit TemplateDependent =3D 0;
+  // Set to true for attributes which have handler in Sema.
+  bit SemaHandler =3D 1;
   // Any additional text that should be included verbatim in the class. =20
   code AdditionalMembers =3D [{}];
 }
@@ -122,6 +126,7 @@
=20
 def AlignMac68k : InheritableAttr {
   let Spellings =3D [];
+  let SemaHandler =3D 0;
 }
=20
 def AlwaysInline : InheritableAttr {
@@ -140,13 +145,14 @@
 def AsmLabel : InheritableAttr {
   let Spellings =3D [];
   let Args =3D [StringArgument<"Label">];
+  let SemaHandler =3D 0;
 }
=20
 def Availability : InheritableAttr {
   let Spellings =3D ["availability"];
   let Args =3D [IdentifierArgument<"platform">, VersionArgument<"introduce=
d">,
               VersionArgument<"deprecated">, VersionArgument<"obsoleted">,
-              BoolArgument<"unavailable">];
+              BoolArgument<"unavailable">, StringArgument<"message">];
   let AdditionalMembers =3D
 [{static llvm::StringRef getPrettyPlatformName(llvm::StringRef Platform) {
     return llvm::StringSwitch<llvm::StringRef>(Platform)
@@ -274,6 +280,7 @@
=20
 def Final : InheritableAttr {=20
   let Spellings =3D [];
+  let SemaHandler =3D 0;
 }
=20
 def MsStruct : InheritableAttr {
@@ -315,6 +322,7 @@
 def MaxFieldAlignment : InheritableAttr {
   let Spellings =3D [];
   let Args =3D [UnsignedArgument<"Alignment">];
+  let SemaHandler =3D 0;
 }
=20
 def MayAlias : InheritableAttr {
@@ -324,14 +332,17 @@
 def MSP430Interrupt : InheritableAttr {
   let Spellings =3D [];
   let Args =3D [UnsignedArgument<"Number">];
+  let SemaHandler =3D 0;
 }
=20
 def MBlazeInterruptHandler : InheritableAttr {
   let Spellings =3D [];
+  let SemaHandler =3D 0;
 }
=20
 def MBlazeSaveVolatiles : InheritableAttr {
   let Spellings =3D [];
+  let SemaHandler =3D 0;
 }
=20
 def Naked : InheritableAttr {
@@ -441,12 +452,18 @@
   let Subjects =3D [ObjCMethod];
 }
=20
+def ObjCRootClass : Attr {
+  let Spellings =3D ["objc_root_class"];
+  let Subjects =3D [ObjCInterface];
+}
+
 def Overloadable : Attr {
   let Spellings =3D ["overloadable"];
 }
=20
 def Override : InheritableAttr {=20
   let Spellings =3D [];
+  let SemaHandler =3D 0;
 }
=20
 def Ownership : InheritableAttr {
@@ -522,6 +539,12 @@
=20
 def ArcWeakrefUnavailable : InheritableAttr {
   let Spellings =3D ["objc_arc_weak_reference_unavailable"];
+  let Subjects =3D [ObjCInterface];
+}
+
+def ObjCRequiresPropertyDefs : InheritableAttr {
+  let Spellings =3D ["objc_requires_property_definitions"];
+  let Subjects =3D [ObjCInterface];
 }
=20
 def Unused : InheritableAttr {
@@ -570,6 +593,10 @@
   let Spellings =3D [];
 }
=20
+// AddressSafety attribute (e.g. for AddressSanitizer)
+def NoAddressSafetyAnalysis : InheritableAttr {
+  let Spellings =3D ["no_address_safety_analysis"];
+}
=20
 // C/C++ Thread safety attributes (e.g. for deadlock, data race checking)
=20
@@ -597,36 +624,42 @@
   let Spellings =3D ["guarded_by"];
   let Args =3D [ExprArgument<"Arg">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def PtGuardedBy : InheritableAttr {
   let Spellings =3D ["pt_guarded_by"];
   let Args =3D [ExprArgument<"Arg">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def AcquiredAfter : InheritableAttr {
   let Spellings =3D ["acquired_after"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def AcquiredBefore : InheritableAttr {
   let Spellings =3D ["acquired_before"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def ExclusiveLockFunction : InheritableAttr {
   let Spellings =3D ["exclusive_lock_function"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def SharedLockFunction : InheritableAttr {
   let Spellings =3D ["shared_lock_function"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 // The first argument is an integer or boolean value specifying the return=
 value
@@ -635,6 +668,7 @@
   let Spellings =3D ["exclusive_trylock_function"];
   let Args =3D [ExprArgument<"SuccessValue">, VariadicExprArgument<"Args">=
];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 // The first argument is an integer or boolean value specifying the return=
 value
@@ -643,34 +677,40 @@
   let Spellings =3D ["shared_trylock_function"];
   let Args =3D [ExprArgument<"SuccessValue">, VariadicExprArgument<"Args">=
];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def UnlockFunction : InheritableAttr {
   let Spellings =3D ["unlock_function"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def LockReturned : InheritableAttr {
   let Spellings =3D ["lock_returned"];
   let Args =3D [ExprArgument<"Arg">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def LocksExcluded : InheritableAttr {
   let Spellings =3D ["locks_excluded"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def ExclusiveLocksRequired : InheritableAttr {
   let Spellings =3D ["exclusive_locks_required"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
=20
 def SharedLocksRequired : InheritableAttr {
   let Spellings =3D ["shared_locks_required"];
   let Args =3D [VariadicExprArgument<"Args">];
   let LateParsed =3D 1;
+  let TemplateDependent =3D 1;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/Builtins.def
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/Builtins.def	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/Builtins.def	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -108,6 +108,8 @@
 BUILTIN(__builtin_inf  , "d"   , "nc")
 BUILTIN(__builtin_inff , "f"   , "nc")
 BUILTIN(__builtin_infl , "Ld"  , "nc")
+BUILTIN(__builtin_labs , "LiLi"  , "Fnc")
+BUILTIN(__builtin_llabs, "LLiLLi", "Fnc")
 BUILTIN(__builtin_ldexp , "ddi"  , "Fnc")
 BUILTIN(__builtin_ldexpf, "ffi"  , "Fnc")
 BUILTIN(__builtin_ldexpl, "LdLdi", "Fnc")
@@ -363,10 +365,12 @@
 BUILTIN(__builtin_signbitl, "iLd", "nc")
=20
 // Builtins for arithmetic.
+BUILTIN(__builtin_clzs , "iUs"  , "nc")
 BUILTIN(__builtin_clz  , "iUi"  , "nc")
 BUILTIN(__builtin_clzl , "iULi" , "nc")
 BUILTIN(__builtin_clzll, "iULLi", "nc")
 // TODO: int clzimax(uintmax_t)
+BUILTIN(__builtin_ctzs , "iUs"  , "nc")
 BUILTIN(__builtin_ctz  , "iUi"  , "nc")
 BUILTIN(__builtin_ctzl , "iULi" , "nc")
 BUILTIN(__builtin_ctzll, "iULLi", "nc")
@@ -448,12 +452,15 @@
 // GCC Object size checking builtins
 BUILTIN(__builtin_object_size, "zvC*i", "n")
 BUILTIN(__builtin___memcpy_chk, "v*v*vC*zz", "nF")
+BUILTIN(__builtin___memccpy_chk, "v*v*vC*iz", "nF")
 BUILTIN(__builtin___memmove_chk, "v*v*vC*zz", "nF")
 BUILTIN(__builtin___mempcpy_chk, "v*v*vC*zz", "nF")
 BUILTIN(__builtin___memset_chk, "v*v*izz", "nF")
 BUILTIN(__builtin___stpcpy_chk, "c*c*cC*z", "nF")
 BUILTIN(__builtin___strcat_chk, "c*c*cC*z", "nF")
 BUILTIN(__builtin___strcpy_chk, "c*c*cC*z", "nF")
+BUILTIN(__builtin___strlcat_chk, "c*c*cC*zz", "nF")
+BUILTIN(__builtin___strlcpy_chk, "c*c*cC*zz", "nF")
 BUILTIN(__builtin___strncat_chk, "c*c*cC*zz", "nF")
 BUILTIN(__builtin___strncpy_chk, "c*c*cC*zz", "nF")
 BUILTIN(__builtin___stpncpy_chk, "c*c*cC*zz", "nF")
@@ -587,18 +594,57 @@
 BUILTIN(__sync_swap_8, "LLiLLiD*LLi.", "tn")
 BUILTIN(__sync_swap_16, "LLLiLLLiD*LLLi.", "tn")
=20
-BUILTIN(__atomic_load, "v.", "t")
-BUILTIN(__atomic_store, "v.", "t")
-BUILTIN(__atomic_exchange, "v.", "t")
-BUILTIN(__atomic_compare_exchange_strong, "v.", "t")
-BUILTIN(__atomic_compare_exchange_weak, "v.", "t")
-BUILTIN(__atomic_fetch_add, "v.", "t")
-BUILTIN(__atomic_fetch_sub, "v.", "t")
-BUILTIN(__atomic_fetch_and, "v.", "t")
-BUILTIN(__atomic_fetch_or, "v.", "t")
-BUILTIN(__atomic_fetch_xor, "v.", "t")
+// Some of our atomics builtins are handled by AtomicExpr rather than
+// as normal builtin CallExprs. This macro is used for such builtins.
+#ifndef ATOMIC_BUILTIN
+#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) BUILTIN(ID, TYPE, ATTRS)
+#endif
+
+// C11 _Atomic operations for <stdatomic.h>.
+ATOMIC_BUILTIN(__c11_atomic_init, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_load, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_store, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_exchange, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_compare_exchange_strong, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_compare_exchange_weak, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_fetch_add, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_fetch_sub, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_fetch_and, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_fetch_or, "v.", "t")
+ATOMIC_BUILTIN(__c11_atomic_fetch_xor, "v.", "t")
+BUILTIN(__c11_atomic_thread_fence, "vi", "n")
+BUILTIN(__c11_atomic_signal_fence, "vi", "n")
+BUILTIN(__c11_atomic_is_lock_free, "iz", "n")
+
+// GNU atomic builtins.
+ATOMIC_BUILTIN(__atomic_load, "v.", "t")
+ATOMIC_BUILTIN(__atomic_load_n, "v.", "t")
+ATOMIC_BUILTIN(__atomic_store, "v.", "t")
+ATOMIC_BUILTIN(__atomic_store_n, "v.", "t")
+ATOMIC_BUILTIN(__atomic_exchange, "v.", "t")
+ATOMIC_BUILTIN(__atomic_exchange_n, "v.", "t")
+ATOMIC_BUILTIN(__atomic_compare_exchange, "v.", "t")
+ATOMIC_BUILTIN(__atomic_compare_exchange_n, "v.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_add, "v.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_sub, "v.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_and, "v.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_or, "v.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_xor, "v.", "t")
+ATOMIC_BUILTIN(__atomic_fetch_nand, "v.", "t")
+ATOMIC_BUILTIN(__atomic_add_fetch, "v.", "t")
+ATOMIC_BUILTIN(__atomic_sub_fetch, "v.", "t")
+ATOMIC_BUILTIN(__atomic_and_fetch, "v.", "t")
+ATOMIC_BUILTIN(__atomic_or_fetch, "v.", "t")
+ATOMIC_BUILTIN(__atomic_xor_fetch, "v.", "t")
+ATOMIC_BUILTIN(__atomic_nand_fetch, "v.", "t")
+BUILTIN(__atomic_test_and_set, "bvD*i", "n")
+BUILTIN(__atomic_clear, "vvD*i", "n")
 BUILTIN(__atomic_thread_fence, "vi", "n")
 BUILTIN(__atomic_signal_fence, "vi", "n")
+BUILTIN(__atomic_always_lock_free, "izvCD*", "n")
+BUILTIN(__atomic_is_lock_free, "izvCD*", "n")
+
+#undef ATOMIC_BUILTIN
=20
 // Non-overloaded atomic builtins.
 BUILTIN(__sync_synchronize, "v.", "n")
@@ -629,9 +675,12 @@
 LIBBUILTIN(realloc, "v*v*z",      "f",     "stdlib.h", ALL_LANGUAGES)
 // C99 string.h
 LIBBUILTIN(memcpy, "v*v*vC*z",    "f",     "string.h", ALL_LANGUAGES)
+LIBBUILTIN(memcmp, "ivC*vC*z",    "f",     "string.h", ALL_LANGUAGES)
 LIBBUILTIN(memmove, "v*v*vC*z",   "f",     "string.h", ALL_LANGUAGES)
 LIBBUILTIN(strcpy, "c*c*cC*",     "f",     "string.h", ALL_LANGUAGES)
 LIBBUILTIN(strncpy, "c*c*cC*z",   "f",     "string.h", ALL_LANGUAGES)
+LIBBUILTIN(strcmp, "icC*cC*",     "f",     "string.h", ALL_LANGUAGES)
+LIBBUILTIN(strncmp, "icC*cC*z",   "f",     "string.h", ALL_LANGUAGES)
 LIBBUILTIN(strcat, "c*c*cC*",     "f",     "string.h", ALL_LANGUAGES)
 LIBBUILTIN(strncat, "c*c*cC*z",   "f",     "string.h", ALL_LANGUAGES)
 LIBBUILTIN(strxfrm, "zc*cC*z",    "f",     "string.h", ALL_LANGUAGES)
@@ -655,7 +704,12 @@
 LIBBUILTIN(vfprintf, "i.",        "fP:1:", "stdio.h", ALL_LANGUAGES)
 LIBBUILTIN(vsnprintf, "ic*zcC*a", "fP:2:", "stdio.h", ALL_LANGUAGES)
 LIBBUILTIN(vsprintf, "ic*cC*a",   "fP:1:", "stdio.h", ALL_LANGUAGES)
-LIBBUILTIN(scanf, "icC*.",       "fs:0:", "stdio.h", ALL_LANGUAGES)
+LIBBUILTIN(scanf, "icC*R.",       "fs:0:", "stdio.h", ALL_LANGUAGES)
+LIBBUILTIN(fscanf, "iP*RcC*R.",   "fs:1:", "stdio.h", ALL_LANGUAGES)
+LIBBUILTIN(sscanf, "icC*RcC*R.",  "fs:1:", "stdio.h", ALL_LANGUAGES)
+LIBBUILTIN(vscanf, "icC*Ra",      "fS:0:", "stdio.h", ALL_LANGUAGES)
+LIBBUILTIN(vfscanf, "iP*RcC*Ra",  "fS:1:", "stdio.h", ALL_LANGUAGES)
+LIBBUILTIN(vsscanf, "icC*RcC*Ra", "fS:1:", "stdio.h", ALL_LANGUAGES)
 // C99
 LIBBUILTIN(longjmp, "vJi",        "fr",    "setjmp.h", ALL_LANGUAGES)
=20
@@ -671,6 +725,8 @@
 LIBBUILTIN(index, "c*cC*i",       "f",     "strings.h", ALL_LANGUAGES)
 LIBBUILTIN(rindex, "c*cC*i",      "f",     "strings.h", ALL_LANGUAGES)
 LIBBUILTIN(bzero, "vv*z",         "f",     "strings.h", ALL_LANGUAGES)
+LIBBUILTIN(strcasecmp, "icC*cC*", "f",     "strings.h", ALL_LANGUAGES)
+LIBBUILTIN(strncasecmp, "icC*cC*z", "f",   "strings.h", ALL_LANGUAGES)
 // POSIX unistd.h
 LIBBUILTIN(_exit, "vi",           "fr",    "unistd.h", ALL_LANGUAGES)
 LIBBUILTIN(vfork, "i",            "fj",    "unistd.h", ALL_LANGUAGES)
@@ -698,6 +754,8 @@
=20
 // long double objc_msgSend_fpret(id self, SEL op, ...)=20
 LIBBUILTIN(objc_msgSend_fpret, "LdGH.", "f", "objc/message.h", OBJC_LANG)
+// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
+LIBBUILTIN(objc_msgSend_fp2ret, "XLdGH.", "f", "objc/message.h", OBJC_LANG)
 // id objc_msgSend_stret (id, SEL, ...)
 LIBBUILTIN(objc_msgSend_stret, "GGH.", "f", "objc/message.h", OBJC_LANG)
 // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
@@ -712,34 +770,39 @@
 LIBBUILTIN(objc_enumerationMutation, "vG", "f", "objc/runtime.h", OBJC_LAN=
G)
=20
 // id objc_read_weak(id *location)
-LIBBUILTIN(objc_read_weak, "GG*", "f", "/objc/objc-auto.h", OBJC_LANG)
+LIBBUILTIN(objc_read_weak, "GG*", "f", "objc/objc-auto.h", OBJC_LANG)
 // id objc_assign_weak(id value, id *location)
-LIBBUILTIN(objc_assign_weak, "GGG*", "f", "/objc/objc-auto.h", OBJC_LANG)
+LIBBUILTIN(objc_assign_weak, "GGG*", "f", "objc/objc-auto.h", OBJC_LANG)
 // id objc_assign_ivar(id value, id dest, ptrdiff_t offset)
-LIBBUILTIN(objc_assign_ivar, "GGGY", "f", "/objc/objc-auto.h", OBJC_LANG)
+LIBBUILTIN(objc_assign_ivar, "GGGY", "f", "objc/objc-auto.h", OBJC_LANG)
 // id objc_assign_global(id val, id *dest)
-LIBBUILTIN(objc_assign_global, "GGG*", "f", "/objc/objc-auto.h", OBJC_LANG)
+LIBBUILTIN(objc_assign_global, "GGG*", "f", "objc/objc-auto.h", OBJC_LANG)
 // id objc_assign_strongCast(id val, id *dest
-LIBBUILTIN(objc_assign_strongCast, "GGG*", "f", "/objc/objc-auto.h", OBJC_=
LANG)
+LIBBUILTIN(objc_assign_strongCast, "GGG*", "f", "objc/objc-auto.h", OBJC_L=
ANG)
=20
 // id objc_exception_extract(void *localExceptionData)
-LIBBUILTIN(objc_exception_extract, "Gv*", "f", "/objc/objc-exception.h", O=
BJC_LANG)
+LIBBUILTIN(objc_exception_extract, "Gv*", "f", "objc/objc-exception.h", OB=
JC_LANG)
 // void objc_exception_try_enter(void *localExceptionData)
-LIBBUILTIN(objc_exception_try_enter, "vv*", "f", "/objc/objc-exception.h",=
 OBJC_LANG)
+LIBBUILTIN(objc_exception_try_enter, "vv*", "f", "objc/objc-exception.h", =
OBJC_LANG)
 // void objc_exception_try_exit(void *localExceptionData)
-LIBBUILTIN(objc_exception_try_exit, "vv*", "f", "/objc/objc-exception.h", =
OBJC_LANG)
+LIBBUILTIN(objc_exception_try_exit, "vv*", "f", "objc/objc-exception.h", O=
BJC_LANG)
 // int objc_exception_match(Class exceptionClass, id exception)
-LIBBUILTIN(objc_exception_match, "iGG", "f", "/objc/objc-exception.h", OBJ=
C_LANG)
+LIBBUILTIN(objc_exception_match, "iGG", "f", "objc/objc-exception.h", OBJC=
_LANG)
 // void objc_exception_throw(id exception)
-LIBBUILTIN(objc_exception_throw, "vG", "f", "/objc/objc-exception.h", OBJC=
_LANG)
+LIBBUILTIN(objc_exception_throw, "vG", "f", "objc/objc-exception.h", OBJC_=
LANG)
=20
 // int objc_sync_enter(id obj)
-LIBBUILTIN(objc_sync_enter, "iG", "f", "/objc/objc-sync.h", OBJC_LANG)
+LIBBUILTIN(objc_sync_enter, "iG", "f", "objc/objc-sync.h", OBJC_LANG)
 // int objc_sync_exit(id obj)
-LIBBUILTIN(objc_sync_exit, "iG", "f", "/objc/objc-sync.h", OBJC_LANG)
+LIBBUILTIN(objc_sync_exit, "iG", "f", "objc/objc-sync.h", OBJC_LANG)
=20
 BUILTIN(__builtin_objc_memmove_collectable, "v*v*vC*z", "nF")
=20
+// void NSLog(NSString *fmt, ...)
+LIBBUILTIN(NSLog, "vG.", "fp:0:", "Foundation/NSObjCRuntime.h", OBJC_LANG)
+// void NSLogv(NSString *fmt, va_list args)
+LIBBUILTIN(NSLogv, "vGa", "fP:0:", "Foundation/NSObjCRuntime.h", OBJC_LANG)
+
 // Builtin math library functions
 LIBBUILTIN(pow, "ddd", "fe", "math.h", ALL_LANGUAGES)
 LIBBUILTIN(powl, "LdLdLd", "fe", "math.h", ALL_LANGUAGES)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/BuiltinsX86.def
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsX86.def	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/BuiltinsX86.def	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -42,8 +42,6 @@
 BUILTIN(__builtin_ia32_pfrcpit2, "V2fV2fV2f", "nc")
 BUILTIN(__builtin_ia32_pfrsqrt, "V2fV2f", "nc")
 BUILTIN(__builtin_ia32_pfrsqit1, "V2fV2fV2f", "nc")
-// GCC has pfrsqrtit1, even though this is not the name of the instruction.
-BUILTIN(__builtin_ia32_pfrsqrtit1, "V2fV2fV2f", "nc")
 BUILTIN(__builtin_ia32_pfsub, "V2fV2fV2f", "nc")
 BUILTIN(__builtin_ia32_pfsubr, "V2fV2fV2f", "nc")
 BUILTIN(__builtin_ia32_pi2fd, "V2fV2i", "nc")
@@ -187,14 +185,14 @@
 BUILTIN(__builtin_ia32_ucomisdgt, "iV2dV2d", "")
 BUILTIN(__builtin_ia32_ucomisdge, "iV2dV2d", "")
 BUILTIN(__builtin_ia32_ucomisdneq, "iV2dV2d", "")
-BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fc", "")
-BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fc", "")
+BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "")
+BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "")
 BUILTIN(__builtin_ia32_minps, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_maxps, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_minss, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_maxss, "V4fV4fV4f", "")
-BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dc", "")
-BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dc", "")
+BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "")
+BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "")
 BUILTIN(__builtin_ia32_minpd, "V2dV2dV2d", "")
 BUILTIN(__builtin_ia32_maxpd, "V2dV2dV2d", "")
 BUILTIN(__builtin_ia32_minsd, "V2dV2dV2d", "")
@@ -210,19 +208,13 @@
 BUILTIN(__builtin_ia32_pmulhw128, "V8sV8sV8s", "")
 BUILTIN(__builtin_ia32_pavgb128, "V16cV16cV16c", "")
 BUILTIN(__builtin_ia32_pavgw128, "V8sV8sV8s", "")
-BUILTIN(__builtin_ia32_pcmpeqb128, "V16cV16cV16c", "")
-BUILTIN(__builtin_ia32_pcmpeqw128, "V8sV8sV8s", "")
-BUILTIN(__builtin_ia32_pcmpeqd128, "V4iV4iV4i", "")
-BUILTIN(__builtin_ia32_pcmpgtb128, "V16cV16cV16c", "")
-BUILTIN(__builtin_ia32_pcmpgtw128, "V8sV8sV8s", "")
-BUILTIN(__builtin_ia32_pcmpgtd128, "V4iV4iV4i", "")
 BUILTIN(__builtin_ia32_pmaxub128, "V16cV16cV16c", "")
 BUILTIN(__builtin_ia32_pmaxsw128, "V8sV8sV8s", "")
 BUILTIN(__builtin_ia32_pminub128, "V16cV16cV16c", "")
 BUILTIN(__builtin_ia32_pminsw128, "V8sV8sV8s", "")
-BUILTIN(__builtin_ia32_packsswb128, "V8sV8sV8s", "")
-BUILTIN(__builtin_ia32_packssdw128, "V4iV4iV4i", "")
-BUILTIN(__builtin_ia32_packuswb128, "V8sV8sV8s", "")
+BUILTIN(__builtin_ia32_packsswb128, "V16cV8sV8s", "")
+BUILTIN(__builtin_ia32_packssdw128, "V8sV4iV4i", "")
+BUILTIN(__builtin_ia32_packuswb128, "V16cV8sV8s", "")
 BUILTIN(__builtin_ia32_pmulhuw128, "V8sV8sV8s", "")
 BUILTIN(__builtin_ia32_addsubps, "V4fV4fV4f", "")
 BUILTIN(__builtin_ia32_addsubpd, "V2dV2dV2d", "")
@@ -236,7 +228,7 @@
 BUILTIN(__builtin_ia32_phsubw128, "V8sV8sV8s", "")
 BUILTIN(__builtin_ia32_phsubd128, "V4iV4iV4i", "")
 BUILTIN(__builtin_ia32_phsubsw128, "V8sV8sV8s", "")
-BUILTIN(__builtin_ia32_pmaddubsw128, "V16cV16cV16c", "")
+BUILTIN(__builtin_ia32_pmaddubsw128, "V8sV16cV16c", "")
 BUILTIN(__builtin_ia32_pmulhrsw128, "V8sV8sV8s", "")
 BUILTIN(__builtin_ia32_pshufb128, "V16cV16cV16c", "")
 BUILTIN(__builtin_ia32_psignb128, "V16cV16cV16c", "")
@@ -304,19 +296,19 @@
 BUILTIN(__builtin_ia32_psrlqi128, "V2LLiV2LLii", "")
 BUILTIN(__builtin_ia32_psrawi128, "V8sV8si", "")
 BUILTIN(__builtin_ia32_psradi128, "V4iV4ii", "")
-BUILTIN(__builtin_ia32_pmaddwd128, "V8sV8sV8s", "")
+BUILTIN(__builtin_ia32_pmaddwd128, "V4iV8sV8s", "")
 BUILTIN(__builtin_ia32_monitor, "vv*UiUi", "")
 BUILTIN(__builtin_ia32_mwait, "vUiUi", "")
 BUILTIN(__builtin_ia32_lddqu, "V16ccC*", "")
-BUILTIN(__builtin_ia32_palignr128, "V16cV16cV16cIc", "") // FIXME: Correct=
 type?
+BUILTIN(__builtin_ia32_palignr128, "V16cV16cV16cIc", "")
 BUILTIN(__builtin_ia32_insertps128, "V4fV4fV4fi", "")
=20
 BUILTIN(__builtin_ia32_storelv4si, "vV2i*V2LLi", "")
=20
 BUILTIN(__builtin_ia32_pblendvb128, "V16cV16cV16cV16c", "")
-BUILTIN(__builtin_ia32_pblendw128, "V8sV8sV8si", "")
-BUILTIN(__builtin_ia32_blendpd, "V2dV2dV2di", "")
-BUILTIN(__builtin_ia32_blendps, "V4fV4fV4fi", "")
+BUILTIN(__builtin_ia32_pblendw128, "V8sV8sV8sIi", "")
+BUILTIN(__builtin_ia32_blendpd, "V2dV2dV2dIi", "")
+BUILTIN(__builtin_ia32_blendps, "V4fV4fV4fIi", "")
 BUILTIN(__builtin_ia32_blendvpd, "V2dV2dV2dV2d", "")
 BUILTIN(__builtin_ia32_blendvps, "V4fV4fV4fV4f", "")
=20
@@ -353,28 +345,26 @@
 BUILTIN(__builtin_ia32_ptestz128, "iV2LLiV2LLi", "")
 BUILTIN(__builtin_ia32_ptestc128, "iV2LLiV2LLi", "")
 BUILTIN(__builtin_ia32_ptestnzc128, "iV2LLiV2LLi", "")
-BUILTIN(__builtin_ia32_pcmpeqq, "V2LLiV2LLiV2LLi", "")
 BUILTIN(__builtin_ia32_mpsadbw128, "V16cV16cV16ci", "")
+BUILTIN(__builtin_ia32_phminposuw128, "V8sV8s", "")
=20
 // SSE 4.2
-BUILTIN(__builtin_ia32_pcmpistrm128, "V16cV16cV16cc", "")
-BUILTIN(__builtin_ia32_pcmpistri128, "iV16cV16cc", "")
-BUILTIN(__builtin_ia32_pcmpestrm128, "V16cV16ciV16cic", "")
-BUILTIN(__builtin_ia32_pcmpestri128, "iV16ciV16cic","")
+BUILTIN(__builtin_ia32_pcmpistrm128, "V16cV16cV16cIc", "")
+BUILTIN(__builtin_ia32_pcmpistri128, "iV16cV16cIc", "")
+BUILTIN(__builtin_ia32_pcmpestrm128, "V16cV16ciV16ciIc", "")
+BUILTIN(__builtin_ia32_pcmpestri128, "iV16ciV16ciIc","")
=20
-BUILTIN(__builtin_ia32_pcmpistria128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpistric128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpistrio128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpistris128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpistriz128, "iV16ciV16cic","")
-
-BUILTIN(__builtin_ia32_pcmpestria128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpestric128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpestrio128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpestris128, "iV16ciV16cic","")
-BUILTIN(__builtin_ia32_pcmpestriz128, "iV16ciV16cic","")
-
-BUILTIN(__builtin_ia32_pcmpgtq, "V2LLiV2LLiV2LLi", "")
+// FIXME: These builtins are horribly broken; reenable when PR11305 is fix=
ed.
+//BUILTIN(__builtin_ia32_pcmpistria128, "iV16cV16cIc","")
+//BUILTIN(__builtin_ia32_pcmpistric128, "iV16cV16cIc","")
+//BUILTIN(__builtin_ia32_pcmpistrio128, "iV16cV16cIc","")
+//BUILTIN(__builtin_ia32_pcmpistris128, "iV16cV16cIc","")
+//BUILTIN(__builtin_ia32_pcmpistriz128, "iV16cV16cIc","")
+//BUILTIN(__builtin_ia32_pcmpestria128, "iV16ciV16ciIc","")
+//BUILTIN(__builtin_ia32_pcmpestric128, "iV16ciV16ciIc","")
+//BUILTIN(__builtin_ia32_pcmpestrio128, "iV16ciV16ciic","")
+//BUILTIN(__builtin_ia32_pcmpestris128, "iV16ciV16ciIc","")
+//BUILTIN(__builtin_ia32_pcmpestriz128, "iV16ciV16ciIc","")
=20
 BUILTIN(__builtin_ia32_crc32qi, "UiUiUc", "")
 BUILTIN(__builtin_ia32_crc32hi, "UiUiUs", "")
@@ -387,7 +377,7 @@
 BUILTIN(__builtin_ia32_aesdec128, "V2LLiV2LLiV2LLi", "")
 BUILTIN(__builtin_ia32_aesdeclast128, "V2LLiV2LLiV2LLi", "")
 BUILTIN(__builtin_ia32_aesimc128, "V2LLiV2LLi", "")
-BUILTIN(__builtin_ia32_aeskeygenassist128, "V2LLiV2LLic", "")
+BUILTIN(__builtin_ia32_aeskeygenassist128, "V2LLiV2LLiIc", "")
=20
 // AVX
 BUILTIN(__builtin_ia32_addsubpd256, "V4dV4dV4d", "")
@@ -404,16 +394,16 @@
 BUILTIN(__builtin_ia32_vpermilvarps, "V4fV4fV4i", "")
 BUILTIN(__builtin_ia32_vpermilvarpd256, "V4dV4dV4LLi", "")
 BUILTIN(__builtin_ia32_vpermilvarps256, "V8fV8fV8i", "")
-BUILTIN(__builtin_ia32_blendpd256, "V4dV4dV4di", "")
-BUILTIN(__builtin_ia32_blendps256, "V8fV8fV8fi", "")
+BUILTIN(__builtin_ia32_blendpd256, "V4dV4dV4dIi", "")
+BUILTIN(__builtin_ia32_blendps256, "V8fV8fV8fIi", "")
 BUILTIN(__builtin_ia32_blendvpd256, "V4dV4dV4dV4d", "")
 BUILTIN(__builtin_ia32_blendvps256, "V8fV8fV8fV8f", "")
-BUILTIN(__builtin_ia32_dpps256, "V8fV8fV8fi", "")
+BUILTIN(__builtin_ia32_dpps256, "V8fV8fV8fIi", "")
 BUILTIN(__builtin_ia32_cmppd256, "V4dV4dV4dc", "")
 BUILTIN(__builtin_ia32_cmpps256, "V8fV8fV8fc", "")
-BUILTIN(__builtin_ia32_vextractf128_pd256, "V2dV4dc", "")
-BUILTIN(__builtin_ia32_vextractf128_ps256, "V4fV8fc", "")
-BUILTIN(__builtin_ia32_vextractf128_si256, "V4iV8ic", "")
+BUILTIN(__builtin_ia32_vextractf128_pd256, "V2dV4dIc", "")
+BUILTIN(__builtin_ia32_vextractf128_ps256, "V4fV8fIc", "")
+BUILTIN(__builtin_ia32_vextractf128_si256, "V4iV8iIc", "")
 BUILTIN(__builtin_ia32_cvtdq2pd256, "V4dV4i", "")
 BUILTIN(__builtin_ia32_cvtdq2ps256, "V8fV8i", "")
 BUILTIN(__builtin_ia32_cvtpd2ps256, "V4fV4d", "")
@@ -422,22 +412,15 @@
 BUILTIN(__builtin_ia32_cvttpd2dq256, "V4iV4d", "")
 BUILTIN(__builtin_ia32_cvtpd2dq256, "V4iV4d", "")
 BUILTIN(__builtin_ia32_cvttps2dq256, "V8iV8f", "")
-BUILTIN(__builtin_ia32_vperm2f128_pd256, "V4dV4dV4dc", "")
-BUILTIN(__builtin_ia32_vperm2f128_ps256, "V8fV8fV8fc", "")
-BUILTIN(__builtin_ia32_vperm2f128_si256, "V8iV8iV8ic", "")
-BUILTIN(__builtin_ia32_vpermilpd, "V2dV2dc", "")
-BUILTIN(__builtin_ia32_vpermilps, "V4fV4fc", "")
-BUILTIN(__builtin_ia32_vpermilpd256, "V4dV4dc", "")
-BUILTIN(__builtin_ia32_vpermilps256, "V8fV8fc", "")
-BUILTIN(__builtin_ia32_vinsertf128_pd256, "V4dV4dV2dc", "")
-BUILTIN(__builtin_ia32_vinsertf128_ps256, "V8fV8fV4fc", "")
-BUILTIN(__builtin_ia32_vinsertf128_si256, "V8iV8iV4ic", "")
+BUILTIN(__builtin_ia32_vinsertf128_pd256, "V4dV4dV2dIc", "")
+BUILTIN(__builtin_ia32_vinsertf128_ps256, "V8fV8fV4fIc", "")
+BUILTIN(__builtin_ia32_vinsertf128_si256, "V8iV8iV4iIc", "")
 BUILTIN(__builtin_ia32_sqrtpd256, "V4dV4d", "")
 BUILTIN(__builtin_ia32_sqrtps256, "V8fV8f", "")
 BUILTIN(__builtin_ia32_rsqrtps256, "V8fV8f", "")
 BUILTIN(__builtin_ia32_rcpps256, "V8fV8f", "")
-BUILTIN(__builtin_ia32_roundpd256, "V4dV4di", "")
-BUILTIN(__builtin_ia32_roundps256, "V8fV8fi", "")
+BUILTIN(__builtin_ia32_roundpd256, "V4dV4dIi", "")
+BUILTIN(__builtin_ia32_roundps256, "V8fV8fIi", "")
 BUILTIN(__builtin_ia32_vtestzpd, "iV2dV2d", "")
 BUILTIN(__builtin_ia32_vtestcpd, "iV2dV2d", "")
 BUILTIN(__builtin_ia32_vtestnzcpd, "iV2dV2d", "")
@@ -462,11 +445,8 @@
 BUILTIN(__builtin_ia32_vbroadcastss256, "V8ffC*", "")
 BUILTIN(__builtin_ia32_vbroadcastf128_pd256, "V4dV2dC*", "")
 BUILTIN(__builtin_ia32_vbroadcastf128_ps256, "V8fV4fC*", "")
-BUILTIN(__builtin_ia32_loadupd256, "V4ddC*", "")
-BUILTIN(__builtin_ia32_loadups256, "V8ffC*", "")
 BUILTIN(__builtin_ia32_storeupd256, "vd*V4d", "")
 BUILTIN(__builtin_ia32_storeups256, "vf*V8f", "")
-BUILTIN(__builtin_ia32_loaddqu256, "V32ccC*", "")
 BUILTIN(__builtin_ia32_storedqu256, "vc*V32c", "")
 BUILTIN(__builtin_ia32_lddqu256, "V32ccC*", "")
 BUILTIN(__builtin_ia32_movntdq256, "vV4LLi*V4LLi", "")
@@ -481,4 +461,173 @@
 BUILTIN(__builtin_ia32_maskstorepd256, "vV4d*V4dV4d", "")
 BUILTIN(__builtin_ia32_maskstoreps256, "vV8f*V8fV8f", "")
=20
+// AVX2
+BUILTIN(__builtin_ia32_mpsadbw256, "V32cV32cV32ci", "")
+BUILTIN(__builtin_ia32_pabsb256, "V32cV32c", "")
+BUILTIN(__builtin_ia32_pabsw256, "V16sV16s", "")
+BUILTIN(__builtin_ia32_pabsd256, "V8iV8i", "")
+BUILTIN(__builtin_ia32_packsswb256, "V32cV16sV16s", "")
+BUILTIN(__builtin_ia32_packssdw256, "V16sV8iV8i", "")
+BUILTIN(__builtin_ia32_packuswb256, "V32cV16sV16s", "")
+BUILTIN(__builtin_ia32_packusdw256, "V16sV8iV8i", "")
+BUILTIN(__builtin_ia32_paddsb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_paddsw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_psubsb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_psubsw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_paddusb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_paddusw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_psubusb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_psubusw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_palignr256, "V32cV32cV32cIc", "")
+BUILTIN(__builtin_ia32_pavgb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_pavgw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pblendvb256, "V32cV32cV32cV32c", "")
+BUILTIN(__builtin_ia32_pblendw256, "V16sV16sV16sIi", "")
+BUILTIN(__builtin_ia32_phaddw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_phaddd256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_phaddsw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_phsubw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_phsubd256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_phsubsw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pmaddubsw256, "V16sV32cV32c", "")
+BUILTIN(__builtin_ia32_pmaddwd256, "V8iV16sV16s", "")
+BUILTIN(__builtin_ia32_pmaxub256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_pmaxuw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pmaxud256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_pmaxsb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_pmaxsw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pmaxsd256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_pminub256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_pminuw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pminud256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_pminsb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_pminsw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pminsd256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_pmovmskb256, "iV32c", "")
+BUILTIN(__builtin_ia32_pmovsxbw256, "V16sV16c", "")
+BUILTIN(__builtin_ia32_pmovsxbd256, "V8iV16c", "")
+BUILTIN(__builtin_ia32_pmovsxbq256, "V4LLiV16c", "")
+BUILTIN(__builtin_ia32_pmovsxwd256, "V8iV8s", "")
+BUILTIN(__builtin_ia32_pmovsxwq256, "V4LLiV8s", "")
+BUILTIN(__builtin_ia32_pmovsxdq256, "V4LLiV4i", "")
+BUILTIN(__builtin_ia32_pmovzxbw256, "V16sV16c", "")
+BUILTIN(__builtin_ia32_pmovzxbd256, "V8iV16c", "")
+BUILTIN(__builtin_ia32_pmovzxbq256, "V4LLiV16c", "")
+BUILTIN(__builtin_ia32_pmovzxwd256, "V8iV8s", "")
+BUILTIN(__builtin_ia32_pmovzxwq256, "V4LLiV8s", "")
+BUILTIN(__builtin_ia32_pmovzxdq256, "V4LLiV4i", "")
+BUILTIN(__builtin_ia32_pmuldq256, "V4LLiV8iV8i", "")
+BUILTIN(__builtin_ia32_pmulhrsw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pmulhuw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pmulhw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_pmuludq256, "V4LLiV8iV8i", "")
+BUILTIN(__builtin_ia32_psadbw256, "V4LLiV32cV32c", "")
+BUILTIN(__builtin_ia32_pshufb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_psignb256, "V32cV32cV32c", "")
+BUILTIN(__builtin_ia32_psignw256, "V16sV16sV16s", "")
+BUILTIN(__builtin_ia32_psignd256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_pslldqi256, "V4LLiV4LLiIi", "")
+BUILTIN(__builtin_ia32_psllwi256, "V16sV16si", "")
+BUILTIN(__builtin_ia32_psllw256, "V16sV16sV8s", "")
+BUILTIN(__builtin_ia32_pslldi256, "V8iV8ii", "")
+BUILTIN(__builtin_ia32_pslld256, "V8iV8iV4i", "")
+BUILTIN(__builtin_ia32_psllqi256, "V4LLiV4LLii", "")
+BUILTIN(__builtin_ia32_psllq256, "V4LLiV4LLiV2LLi", "")
+BUILTIN(__builtin_ia32_psrawi256, "V16sV16si", "")
+BUILTIN(__builtin_ia32_psraw256, "V16sV16sV8s", "")
+BUILTIN(__builtin_ia32_psradi256, "V8iV8ii", "")
+BUILTIN(__builtin_ia32_psrad256, "V8iV8iV4i", "")
+BUILTIN(__builtin_ia32_psrldqi256, "V4LLiV4LLiIi", "")
+BUILTIN(__builtin_ia32_psrlwi256, "V16sV16si", "")
+BUILTIN(__builtin_ia32_psrlw256, "V16sV16sV8s", "")
+BUILTIN(__builtin_ia32_psrldi256, "V8iV8ii", "")
+BUILTIN(__builtin_ia32_psrld256, "V8iV8iV4i", "")
+BUILTIN(__builtin_ia32_psrlqi256, "V4LLiV4LLii", "")
+BUILTIN(__builtin_ia32_psrlq256, "V4LLiV4LLiV2LLi", "")
+BUILTIN(__builtin_ia32_movntdqa256, "V4LLiV4LLi*", "")
+BUILTIN(__builtin_ia32_vbroadcastss_ps, "V4fV4f", "")
+BUILTIN(__builtin_ia32_vbroadcastss_ps256, "V8fV4f", "")
+BUILTIN(__builtin_ia32_vbroadcastsd_pd256, "V4dV2d", "")
+BUILTIN(__builtin_ia32_vbroadcastsi256, "V4LLiV2LLiC*", "")
+BUILTIN(__builtin_ia32_pblendd128, "V4iV4iV4iIi", "")
+BUILTIN(__builtin_ia32_pblendd256, "V8iV8iV8iIi", "")
+BUILTIN(__builtin_ia32_pbroadcastb256, "V32cV16c", "")
+BUILTIN(__builtin_ia32_pbroadcastw256, "V16sV8s", "")
+BUILTIN(__builtin_ia32_pbroadcastd256, "V8iV4i", "")
+BUILTIN(__builtin_ia32_pbroadcastq256, "V4LLiV2LLi", "")
+BUILTIN(__builtin_ia32_pbroadcastb128, "V16cV16c", "")
+BUILTIN(__builtin_ia32_pbroadcastw128, "V8sV8s", "")
+BUILTIN(__builtin_ia32_pbroadcastd128, "V4iV4i", "")
+BUILTIN(__builtin_ia32_pbroadcastq128, "V2LLiV2LLi", "")
+BUILTIN(__builtin_ia32_permvarsi256, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_permdf256, "V4dV4dIc", "")
+BUILTIN(__builtin_ia32_permvarsf256, "V8fV8fV8f", "")
+BUILTIN(__builtin_ia32_permdi256, "V4LLiV4LLiIc", "")
+BUILTIN(__builtin_ia32_extract128i256, "V2LLiV4LLiIc", "")
+BUILTIN(__builtin_ia32_insert128i256, "V4LLiV4LLiV2LLiIc", "")
+BUILTIN(__builtin_ia32_maskloadd256, "V8iV8iC*V8i", "")
+BUILTIN(__builtin_ia32_maskloadq256, "V4LLiV4LLiC*V4LLi", "")
+BUILTIN(__builtin_ia32_maskloadd, "V4iV4iC*V4i", "")
+BUILTIN(__builtin_ia32_maskloadq, "V2LLiV2LLiC*V2LLi", "")
+BUILTIN(__builtin_ia32_maskstored256, "vV8i*V8iV8i", "")
+BUILTIN(__builtin_ia32_maskstoreq256, "vV4LLi*V4LLiV4LLi", "")
+BUILTIN(__builtin_ia32_maskstored, "vV4i*V4iV4i", "")
+BUILTIN(__builtin_ia32_maskstoreq, "vV2LLi*V2LLiV2LLi", "")
+BUILTIN(__builtin_ia32_psllv8si, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_psllv4si, "V4iV4iV4i", "")
+BUILTIN(__builtin_ia32_psllv4di, "V4LLiV4LLiV4LLi", "")
+BUILTIN(__builtin_ia32_psllv2di, "V2LLiV2LLiV2LLi", "")
+BUILTIN(__builtin_ia32_psrav8si, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_psrav4si, "V4iV4iV4i", "")
+BUILTIN(__builtin_ia32_psrlv8si, "V8iV8iV8i", "")
+BUILTIN(__builtin_ia32_psrlv4si, "V4iV4iV4i", "")
+BUILTIN(__builtin_ia32_psrlv4di, "V4LLiV4LLiV4LLi", "")
+BUILTIN(__builtin_ia32_psrlv2di, "V2LLiV2LLiV2LLi", "")
+
+// BMI
+BUILTIN(__builtin_ia32_bextr_u32, "UiUiUi", "")
+BUILTIN(__builtin_ia32_bextr_u64, "ULLiULLiULLi", "")
+
+// BMI2
+BUILTIN(__builtin_ia32_bzhi_si, "UiUiUi", "")
+BUILTIN(__builtin_ia32_bzhi_di, "ULLiULLiULLi", "")
+BUILTIN(__builtin_ia32_pdep_si, "UiUiUi", "")
+BUILTIN(__builtin_ia32_pdep_di, "ULLiULLiULLi", "")
+BUILTIN(__builtin_ia32_pext_si, "UiUiUi", "")
+BUILTIN(__builtin_ia32_pext_di, "ULLiULLiULLi", "")
+
+// FMA4
+BUILTIN(__builtin_ia32_vfmaddps, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfmaddpd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfmaddss, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfmaddsd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfmsubps, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfmsubpd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfmsubss, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfmsubsd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfnmaddps, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfnmaddpd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfnmaddss, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfnmaddsd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfnmsubps, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfnmsubpd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfnmsubss, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfnmsubsd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfmaddsubps, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfmaddsubpd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfmsubaddps, "V4fV4fV4fV4f", "")
+BUILTIN(__builtin_ia32_vfmsubaddpd, "V2dV2dV2dV2d", "")
+BUILTIN(__builtin_ia32_vfmaddps256, "V8fV8fV8fV8f", "")
+BUILTIN(__builtin_ia32_vfmaddpd256, "V4dV4dV4dV4d", "")
+BUILTIN(__builtin_ia32_vfmsubps256, "V8fV8fV8fV8f", "")
+BUILTIN(__builtin_ia32_vfmsubpd256, "V4dV4dV4dV4d", "")
+BUILTIN(__builtin_ia32_vfnmaddps256, "V8fV8fV8fV8f", "")
+BUILTIN(__builtin_ia32_vfnmaddpd256, "V4dV4dV4dV4d", "")
+BUILTIN(__builtin_ia32_vfnmsubps256, "V8fV8fV8fV8f", "")
+BUILTIN(__builtin_ia32_vfnmsubpd256, "V4dV4dV4dV4d", "")
+BUILTIN(__builtin_ia32_vfmaddsubps256, "V8fV8fV8fV8f", "")
+BUILTIN(__builtin_ia32_vfmaddsubpd256, "V4dV4dV4dV4d", "")
+BUILTIN(__builtin_ia32_vfmsubaddps256, "V8fV8fV8fV8f", "")
+BUILTIN(__builtin_ia32_vfmsubaddpd256, "V4dV4dV4dV4d", "")
+
 #undef BUILTIN
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/ConvertUTF.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/ConvertUTF.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/ConvertUTF.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -98,7 +98,7 @@
     bit mask & shift operations.
 ------------------------------------------------------------------------ */
=20
-typedef unsigned long   UTF32;  /* at least 32 bits */
+typedef unsigned int    UTF32;  /* at least 32 bits */
 typedef unsigned short  UTF16;  /* at least 16 bits */
 typedef unsigned char   UTF8;   /* typically 8 bits */
 typedef unsigned char   Boolean; /* 0 or 1 */
@@ -131,15 +131,15 @@
   const UTF8** sourceStart, const UTF8* sourceEnd,
   UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
=20
+ConversionResult ConvertUTF8toUTF32 (
+  const UTF8** sourceStart, const UTF8* sourceEnd,
+  UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags);
+
 #ifdef CLANG_NEEDS_THESE_ONE_DAY
 ConversionResult ConvertUTF16toUTF8 (
   const UTF16** sourceStart, const UTF16* sourceEnd,
   UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
=20
-ConversionResult ConvertUTF8toUTF32 (
-  const UTF8** sourceStart, const UTF8* sourceEnd,
-  UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags);
-
 ConversionResult ConvertUTF32toUTF8 (
   const UTF32** sourceStart, const UTF32* sourceEnd,
   UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
@@ -151,9 +151,11 @@
 ConversionResult ConvertUTF32toUTF16 (
   const UTF32** sourceStart, const UTF32* sourceEnd,
   UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
+
+Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd);
 #endif
=20
-Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd);
+Boolean isLegalUTF8String(const UTF8 *source, const UTF8 *sourceEnd);
=20
 #ifdef __cplusplus
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DeclNodes.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DeclNodes.td	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DeclNodes.td	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -66,8 +66,6 @@
   def ObjCCompatibleAlias : DDecl<Named>;
 def LinkageSpec : Decl, DeclContext;
 def ObjCPropertyImpl : Decl;
-def ObjCForwardProtocol : Decl;
-def ObjCClass : Decl;
 def FileScopeAsm : Decl;
 def AccessSpec : Decl;
 def Friend : Decl;
@@ -75,3 +73,5 @@
 def StaticAssert : Decl;
 def Block : Decl, DeclContext;
 def ClassScopeFunctionSpecialization : Decl;
+def Import : Decl;
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/Diagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/Diagnostic.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/Diagnostic.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -50,13 +50,19 @@
   /// insertion hint.
   CharSourceRange RemoveRange;
=20
+  /// \brief Code in the specific range that should be inserted in the ins=
ertion
+  /// location.
+  CharSourceRange InsertFromRange;
+
   /// \brief The actual code to insert at the insertion location, as a
   /// string.
   std::string CodeToInsert;
=20
+  bool BeforePreviousInsertions;
+
   /// \brief Empty code modification hint, indicating that no code
   /// modification is known.
-  FixItHint() : RemoveRange() { }
+  FixItHint() : BeforePreviousInsertions(false) { }
=20
   bool isNull() const {
     return !RemoveRange.isValid();
@@ -65,11 +71,26 @@
   /// \brief Create a code modification hint that inserts the given
   /// code string at a specific location.
   static FixItHint CreateInsertion(SourceLocation InsertionLoc,
-                                   StringRef Code) {
+                                   StringRef Code,
+                                   bool BeforePreviousInsertions =3D false=
) {
     FixItHint Hint;
     Hint.RemoveRange =3D
       CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
     Hint.CodeToInsert =3D Code;
+    Hint.BeforePreviousInsertions =3D BeforePreviousInsertions;
+    return Hint;
+  }
+ =20
+  /// \brief Create a code modification hint that inserts the given
+  /// code from \arg FromRange at a specific location.
+  static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
+                                            CharSourceRange FromRange,
+                                        bool BeforePreviousInsertions =3D =
false) {
+    FixItHint Hint;
+    Hint.RemoveRange =3D
+      CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
+    Hint.InsertFromRange =3D FromRange;
+    Hint.BeforePreviousInsertions =3D BeforePreviousInsertions;
     return Hint;
   }
=20
@@ -105,7 +126,7 @@
 /// "report warnings as errors" and passes them off to the DiagnosticConsu=
mer
 /// for reporting to the user. DiagnosticsEngine is tied to one translatio=
n unit
 /// and one SourceManager.
-class DiagnosticsEngine : public llvm::RefCountedBase<DiagnosticsEngine> {
+class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
 public:
   /// Level - The level of the diagnostic, after it has been through mappi=
ng.
   enum Level {
@@ -158,8 +179,10 @@
   unsigned ErrorLimit;           // Cap of # errors emitted, 0 -> no limit.
   unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace s=
tack,
                                    // 0 -> no limit.
+  unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
+                                    // backtrace stack, 0 -> no limit.
   ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> Diags;
+  IntrusiveRefCntPtr<DiagnosticIDs> Diags;
   DiagnosticConsumer *Client;
   bool OwnsDiagClient;
   SourceManager *SourceMgr;
@@ -287,7 +310,7 @@
       unsigned NumPrevArgs,
       SmallVectorImpl<char> &Output,
       void *Cookie,
-      SmallVectorImpl<intptr_t> &QualTypeVals);
+      ArrayRef<intptr_t> QualTypeVals);
   void *ArgToStringCookie;
   ArgToStringFnTy ArgToStringFn;
=20
@@ -304,12 +327,12 @@
=20
 public:
   explicit DiagnosticsEngine(
-                      const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
+                      const IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
                       DiagnosticConsumer *client =3D 0,
                       bool ShouldOwnClient =3D true);
   ~DiagnosticsEngine();
=20
-  const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
+  const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
     return Diags;
   }
=20
@@ -363,13 +386,25 @@
   void setTemplateBacktraceLimit(unsigned Limit) {
     TemplateBacktraceLimit =3D Limit;
   }
- =20
+
   /// \brief Retrieve the maximum number of template instantiation
-  /// nodes to emit along with a given diagnostic.
+  /// notes to emit along with a given diagnostic.
   unsigned getTemplateBacktraceLimit() const {
     return TemplateBacktraceLimit;
   }
- =20
+
+  /// \brief Specify the maximum number of constexpr evaluation
+  /// notes to emit along with a given diagnostic.
+  void setConstexprBacktraceLimit(unsigned Limit) {
+    ConstexprBacktraceLimit =3D Limit;
+  }
+
+  /// \brief Retrieve the maximum number of constexpr evaluation
+  /// notes to emit along with a given diagnostic.
+  unsigned getConstexprBacktraceLimit() const {
+    return ConstexprBacktraceLimit;
+  }
+
   /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
   /// ignored.  If this and WarningsAsErrors are both set, then this one w=
ins.
   void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings =3D Val; }
@@ -450,18 +485,32 @@
   bool setDiagnosticGroupMapping(StringRef Group, diag::Mapping Map,
                                  SourceLocation Loc =3D SourceLocation());
=20
+  /// \brief Set the warning-as-error flag for the given diagnostic. This
+  /// function always only operates on the current diagnostic state.
+  void setDiagnosticWarningAsError(diag::kind Diag, bool Enabled);
+
   /// \brief Set the warning-as-error flag for the given diagnostic group.=
 This
   /// function always only operates on the current diagnostic state.
   ///
   /// \returns True if the given group is unknown, false otherwise.
   bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
=20
+  /// \brief Set the error-as-fatal flag for the given diagnostic. This fu=
nction
+  /// always only operates on the current diagnostic state.
+  void setDiagnosticErrorAsFatal(diag::kind Diag, bool Enabled);
+
   /// \brief Set the error-as-fatal flag for the given diagnostic group. T=
his
   /// function always only operates on the current diagnostic state.
   ///
   /// \returns True if the given group is unknown, false otherwise.
   bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
=20
+  /// \brief Add the specified mapping to all diagnostics. Mainly to be us=
ed
+  /// by -Wno-everything to disable all warnings but allow subsequent -W o=
ptions
+  /// to enable specific warnings.
+  void setMappingToAllDiagnostics(diag::Mapping Map,
+                                  SourceLocation Loc =3D SourceLocation());
+
   bool hasErrorOccurred() const { return ErrorOccurred; }
   bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
  =20
@@ -587,16 +636,22 @@
     /// MaxArguments - The maximum number of arguments we can hold. We cur=
rently
     /// only support up to 10 arguments (%0-%9).  A single diagnostic with=
 more
     /// than that almost certainly has to be simplified anyway.
-    MaxArguments =3D 10
+    MaxArguments =3D 10,
+
+    /// MaxRanges - The maximum number of ranges we can hold.
+    MaxRanges =3D 10,
+
+    /// MaxFixItHints - The maximum number of ranges we can hold.
+    MaxFixItHints =3D 10
   };
=20
   /// NumDiagArgs - This contains the number of entries in Arguments.
   signed char NumDiagArgs;
-  /// NumRanges - This is the number of ranges in the DiagRanges array.
+  /// NumDiagRanges - This is the number of ranges in the DiagRanges array.
   unsigned char NumDiagRanges;
-  /// \brief The number of code modifications hints in the
-  /// FixItHints array.
-  unsigned char NumFixItHints;
+  /// NumDiagFixItHints - This is the number of hints in the DiagFixItHints
+  /// array.
+  unsigned char NumDiagFixItHints;
=20
   /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind e=
num
   /// values, with one for each argument.  This specifies whether the argu=
ment
@@ -614,15 +669,27 @@
   /// sort of argument kind it is.
   intptr_t DiagArgumentsVal[MaxArguments];
=20
-  /// DiagRanges - The list of ranges added to this diagnostic.  It curren=
tly
-  /// only support 10 ranges, could easily be extended if needed.
-  CharSourceRange DiagRanges[10];
+  /// DiagRanges - The list of ranges added to this diagnostic.
+  CharSourceRange DiagRanges[MaxRanges];
=20
-  enum { MaxFixItHints =3D 6 };
+  /// FixItHints - If valid, provides a hint with some code to insert, rem=
ove,
+  /// or modify at a particular position.
+  FixItHint DiagFixItHints[MaxFixItHints];
=20
-  /// FixItHints - If valid, provides a hint with some code
-  /// to insert, remove, or modify at a particular position.
-  FixItHint FixItHints[MaxFixItHints];
+  DiagnosticMappingInfo makeMappingInfo(diag::Mapping Map, SourceLocation =
L) {
+    bool isPragma =3D L.isValid();
+    DiagnosticMappingInfo MappingInfo =3D DiagnosticMappingInfo::Make(
+      Map, /*IsUser=3D*/true, isPragma);
+
+    // If this is a pragma mapping, then set the diagnostic mapping flags =
so
+    // that we override command line options.
+    if (isPragma) {
+      MappingInfo.setNoWarningAsError(true);
+      MappingInfo.setNoErrorAsFatal(true);
+    }
+
+    return MappingInfo;
+  }
=20
   /// ProcessDiag - This is the method used to report a diagnostic that is
   /// finally fully formed.
@@ -633,6 +700,24 @@
     return Diags->ProcessDiag(*this);
   }
=20
+  /// @name Diagnostic Emission
+  /// @{
+protected:
+  // Sema requires access to the following functions because the current d=
esign
+  // of SFINAE requires it to use its own SemaDiagnosticBuilder, which nee=
ds to
+  // access us directly to ensure we minimize the emitted code for the com=
mon
+  // Sema::Diag() patterns.
+  friend class Sema;
+
+  /// \brief Emit the current diagnostic and clear the diagnostic state.
+  bool EmitCurrentDiagnostic();
+
+  unsigned getCurrentDiagID() const { return CurDiagID; }
+
+  SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
+
+  /// @}
+
   friend class ASTReader;
   friend class ASTWriter;
 };
@@ -685,37 +770,39 @@
 /// for example.
 class DiagnosticBuilder {
   mutable DiagnosticsEngine *DiagObj;
-  mutable unsigned NumArgs, NumRanges, NumFixItHints;
+  mutable unsigned NumArgs, NumRanges, NumFixits;
+
+  /// \brief Status variable indicating if this diagnostic is still active.
+  ///
+  // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj =3D=
=3D 0)),
+  // but LLVM is not currently smart enough to eliminate the null check th=
at
+  // Emit() would end up with if we used that as our status variable.
+  mutable bool IsActive;
=20
   void operator=3D(const DiagnosticBuilder&); // DO NOT IMPLEMENT
   friend class DiagnosticsEngine;
   explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
-    : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
+    : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixits(0), IsActive(t=
rue) {
+    assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngin=
e!");
+  }
=20
   friend class PartialDiagnostic;
=20
 protected:
-  void FlushCounts();
- =20
-public:
-  /// Copy constructor.  When copied, this "takes" the diagnostic info fro=
m the
-  /// input and neuters it.
-  DiagnosticBuilder(const DiagnosticBuilder &D) {
-    DiagObj =3D D.DiagObj;
-    D.DiagObj =3D 0;
-    NumArgs =3D D.NumArgs;
-    NumRanges =3D D.NumRanges;
-    NumFixItHints =3D D.NumFixItHints;
+  void FlushCounts() {
+    DiagObj->NumDiagArgs =3D NumArgs;
+    DiagObj->NumDiagRanges =3D NumRanges;
+    DiagObj->NumDiagFixItHints =3D NumFixits;
   }
=20
-  /// \brief Simple enumeration value used to give a name to the
-  /// suppress-diagnostic constructor.
-  enum SuppressKind { Suppress };
+  /// \brief Clear out the current diagnostic.
+  void Clear() const {
+    DiagObj =3D 0;
+    IsActive =3D false;
+  }
=20
-  /// \brief Create an empty DiagnosticBuilder object that represents
-  /// no actual diagnostic.
-  explicit DiagnosticBuilder(SuppressKind)
-    : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
+  /// isActive - Determine whether this diagnostic is still active.
+  bool isActive() const { return IsActive; }
=20
   /// \brief Force the diagnostic builder to emit the diagnostic now.
   ///
@@ -724,25 +811,40 @@
   ///
   /// \returns true if a diagnostic was emitted, false if the
   /// diagnostic was suppressed.
-  bool Emit();
+  bool Emit() {
+    // If this diagnostic is inactive, then its soul was stolen by the cop=
y ctor
+    // (or by a subclass, as in SemaDiagnosticBuilder).
+    if (!isActive()) return false;
=20
-  /// Destructor - The dtor emits the diagnostic if it hasn't already
-  /// been emitted.
-  ~DiagnosticBuilder() { Emit(); }
+    // When emitting diagnostics, we set the final argument count into
+    // the DiagnosticsEngine object.
+    FlushCounts();
=20
-  /// isActive - Determine whether this diagnostic is still active.
-  bool isActive() const { return DiagObj !=3D 0; }
+    // Process the diagnostic.
+    bool Result =3D DiagObj->EmitCurrentDiagnostic();
=20
-  /// \brief Retrieve the active diagnostic ID.
-  ///
-  /// \pre \c isActive()
-  unsigned getDiagID() const {
-    assert(isActive() && "DiagnosticsEngine is inactive");
-    return DiagObj->CurDiagID;
+    // This diagnostic is dead.
+    Clear();
+
+    return Result;
   }
  =20
-  /// \brief Clear out the current diagnostic.
-  void Clear() { DiagObj =3D 0; }
+public:
+  /// Copy constructor.  When copied, this "takes" the diagnostic info fro=
m the
+  /// input and neuters it.
+  DiagnosticBuilder(const DiagnosticBuilder &D) {
+    DiagObj =3D D.DiagObj;
+    IsActive =3D D.IsActive;
+    D.Clear();
+    NumArgs =3D D.NumArgs;
+    NumRanges =3D D.NumRanges;
+    NumFixits =3D D.NumFixits;
+  }
+
+  /// Destructor - The dtor emits the diagnostic.
+  ~DiagnosticBuilder() {
+    Emit();
+  }
  =20
   /// Operator bool: conversion of DiagnosticBuilder to bool always returns
   /// true.  This allows is to be used in boolean error contexts like:
@@ -750,38 +852,33 @@
   operator bool() const { return true; }
=20
   void AddString(StringRef S) const {
+    assert(isActive() && "Clients must not add to cleared diagnostic!");
     assert(NumArgs < DiagnosticsEngine::MaxArguments &&
            "Too many arguments to diagnostic!");
-    if (DiagObj) {
-      DiagObj->DiagArgumentsKind[NumArgs] =3D DiagnosticsEngine::ak_std_st=
ring;
-      DiagObj->DiagArgumentsStr[NumArgs++] =3D S;
-    }
+    DiagObj->DiagArgumentsKind[NumArgs] =3D DiagnosticsEngine::ak_std_stri=
ng;
+    DiagObj->DiagArgumentsStr[NumArgs++] =3D S;
   }
=20
   void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) cons=
t {
+    assert(isActive() && "Clients must not add to cleared diagnostic!");
     assert(NumArgs < DiagnosticsEngine::MaxArguments &&
            "Too many arguments to diagnostic!");
-    if (DiagObj) {
-      DiagObj->DiagArgumentsKind[NumArgs] =3D Kind;
-      DiagObj->DiagArgumentsVal[NumArgs++] =3D V;
-    }
+    DiagObj->DiagArgumentsKind[NumArgs] =3D Kind;
+    DiagObj->DiagArgumentsVal[NumArgs++] =3D V;
   }
=20
   void AddSourceRange(const CharSourceRange &R) const {
-    assert(NumRanges <
-           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
+    assert(isActive() && "Clients must not add to cleared diagnostic!");
+    assert(NumRanges < DiagnosticsEngine::MaxRanges &&
            "Too many arguments to diagnostic!");
-    if (DiagObj)
-      DiagObj->DiagRanges[NumRanges++] =3D R;
+    DiagObj->DiagRanges[NumRanges++] =3D R;
   }
=20
   void AddFixItHint(const FixItHint &Hint) const {
-    assert(NumFixItHints < DiagnosticsEngine::MaxFixItHints &&
-           "Too many fix-it hints!");
-    if (NumFixItHints >=3D DiagnosticsEngine::MaxFixItHints)
-      return;  // Don't crash in release builds
-    if (DiagObj)
-      DiagObj->FixItHints[NumFixItHints++] =3D Hint;
+    assert(isActive() && "Clients must not add to cleared diagnostic!");
+    assert(NumFixits < DiagnosticsEngine::MaxFixItHints &&
+           "Too many arguments to diagnostic!");
+    DiagObj->DiagFixItHints[NumFixits++] =3D Hint;
   }
 };
=20
@@ -849,7 +946,8 @@
  =20
 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
                                            const FixItHint &Hint) {
-  DB.AddFixItHint(Hint);
+  if (!Hint.isNull())
+    DB.AddFixItHint(Hint);
   return DB;
 }
=20
@@ -951,17 +1049,22 @@
     return DiagObj->DiagRanges[Idx];
   }
=20
+  /// \brief Return an array reference for this diagnostic's ranges.
+  ArrayRef<CharSourceRange> getRanges() const {
+    return llvm::makeArrayRef(DiagObj->DiagRanges, DiagObj->NumDiagRanges);
+  }
+
   unsigned getNumFixItHints() const {
-    return DiagObj->NumFixItHints;
+    return DiagObj->NumDiagFixItHints;
   }
=20
   const FixItHint &getFixItHint(unsigned Idx) const {
-    return DiagObj->FixItHints[Idx];
+    assert(Idx < getNumFixItHints() && "Invalid index!");
+    return DiagObj->DiagFixItHints[Idx];
   }
=20
   const FixItHint *getFixItHints() const {
-    return DiagObj->NumFixItHints?
-             &DiagObj->FixItHints[0] : 0;
+    return getNumFixItHints()? DiagObj->DiagFixItHints : 0;
   }
=20
   /// FormatDiagnostic - Format this diagnostic into a string, substitutin=
g the
@@ -1012,11 +1115,20 @@
   range_iterator range_begin() const { return Ranges.begin(); }
   range_iterator range_end() const { return Ranges.end(); }
   unsigned range_size() const { return Ranges.size(); }
+ =20
+  ArrayRef<CharSourceRange> getRanges() const {
+    return llvm::makeArrayRef(Ranges);
+  }
+
=20
   typedef std::vector<FixItHint>::const_iterator fixit_iterator;
   fixit_iterator fixit_begin() const { return FixIts.begin(); }
   fixit_iterator fixit_end() const { return FixIts.end(); }
   unsigned fixit_size() const { return FixIts.size(); }
+ =20
+  ArrayRef<FixItHint> getFixIts() const {
+    return llvm::makeArrayRef(FixIts);
+  }
 };
=20
 /// DiagnosticConsumer - This is an abstract interface implemented by clie=
nts of
@@ -1031,6 +1143,7 @@
=20
   unsigned getNumErrors() const { return NumErrors; }
   unsigned getNumWarnings() const { return NumWarnings; }
+  virtual void clear() { NumWarnings =3D NumErrors =3D 0; }
=20
   virtual ~DiagnosticConsumer();
=20
@@ -1053,6 +1166,10 @@
   /// objects made available via \see BeginSourceFile() are inaccessible.
   virtual void EndSourceFile() {}
=20
+  /// \brief Callback to inform the diagnostic client that processing of a=
ll
+  /// source files has ended.
+  virtual void finish() {}
+
   /// IncludeInDiagnosticCounts - This method (whose default implementation
   /// returns true) indicates whether the diagnostics handled by this
   /// DiagnosticConsumer should be included in the number of diagnostics
@@ -1075,6 +1192,7 @@
 /// IgnoringDiagConsumer - This is a diagnostic client that just ignores a=
ll
 /// diags.
 class IgnoringDiagConsumer : public DiagnosticConsumer {
+  virtual void anchor();
   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
                         const Diagnostic &Info) {
     // Just ignore it.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/Diagnostic.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/Diagnostic.td	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/Diagnostic.td	Tue A=
pr 17 11:51:51 2012 +0300
@@ -62,8 +62,6 @@
   DiagMapping DefaultMapping =3D defaultmapping;
   DiagGroup   Group;
   string      CategoryName =3D "";
-  string      Brief =3D "";
-  string      Explanation =3D "";
 }
=20
 class Error<string str>     : Diagnostic<str, CLASS_ERROR, MAP_ERROR>;
@@ -87,12 +85,6 @@
 class NoSFINAE { bit SFINAE =3D 0; }
 class AccessControl { bit AccessControl =3D 1; }
=20
-class Brief<string str> { string Brief =3D str; }
-class FullExplanation<string brief, string full> {
-  string Brief =3D brief;
-  string Explanation =3D full;
-}
-
 // Definitions for Diagnostics.
 include "DiagnosticASTKinds.td"
 include "DiagnosticAnalysisKinds.td"
@@ -102,4 +94,5 @@
 include "DiagnosticLexKinds.td"
 include "DiagnosticParseKinds.td"
 include "DiagnosticSemaKinds.td"
+include "DiagnosticSerializationKinds.td"
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticASTKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticASTKinds.=
td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticASTKinds.=
td	Tue Apr 17 11:51:51 2012 +0300
@@ -9,9 +9,103 @@
=20
 let Component =3D "AST" in {
=20
-//def note_comma_in_ice : Note<
-//  "C does not permit evaluated commas in an integer constant expression"=
>;
+// Constant expression diagnostics. These (and their users) belong in Sema.
 def note_expr_divide_by_zero : Note<"division by zero">;
+def note_constexpr_invalid_cast : Note<
+  "%select{reinterpret_cast|dynamic_cast|cast which performs the conversio=
ns of"
+  " a reinterpret_cast|cast from %1}0 is not allowed in a constant express=
ion">;
+def note_constexpr_invalid_downcast : Note<
+  "cannot cast object of dynamic type %0 to type %1">;
+def note_constexpr_overflow : Note<
+  "value %0 is outside the range of representable values of type %1">;
+def note_constexpr_negative_shift : Note<"negative shift count %0">;
+def note_constexpr_large_shift : Note<
+  "shift count %0 >=3D width of type %1 (%2 bit%s2)">;
+def note_constexpr_lshift_of_negative : Note<"left shift of negative value=
 %0">;
+def note_constexpr_lshift_discards : Note<"signed left shift discards bits=
">;
+def note_constexpr_invalid_function : Note<
+  "%select{non-constexpr|undefined}0 %select{function|constructor}1 %2 can=
not "
+  "be used in a constant expression">;
+def note_constexpr_virtual_call : Note<
+  "cannot evaluate virtual function call in a constant expression">;
+def note_constexpr_virtual_base : Note<
+  "cannot construct object of type %0 with virtual base class "
+  "in a constant expression">;
+def note_constexpr_nonliteral : Note<
+  "non-literal type %0 cannot be used in a constant expression">;
+def note_constexpr_non_global : Note<
+  "%select{pointer|reference}0 to %select{|subobject of }1"
+  "%select{temporary|%3}2 is not a constant expression">;
+def note_constexpr_array_index : Note<"cannot refer to element %0 of "
+  "%select{array of %2 elements|non-array object}1 in a constant expressio=
n">;
+def note_constexpr_float_arithmetic : Note<
+  "floating point arithmetic produces %select{an infinity|a NaN}0">;
+def note_constexpr_pointer_subtraction_not_same_array : Note<
+  "subtracted pointers are not elements of the same array">;
+def note_constexpr_pointer_comparison_base_classes : Note<
+  "comparison of addresses of subobjects of different base classes "
+  "has unspecified value">;
+def note_constexpr_pointer_comparison_base_field : Note<
+  "comparison of address of base class subobject %0 of class %1 to field %=
2 "
+  "has unspecified value">;
+def note_constexpr_pointer_comparison_differing_access : Note<
+  "comparison of address of fields %0 and %2 of %4 with differing access "
+  "specifiers (%1 vs %3) has unspecified value">;
+def note_constexpr_compare_virtual_mem_ptr : Note<
+  "comparison of pointer to virtual member function %0 has unspecified val=
ue">;
+def note_constexpr_past_end : Note<
+  "dereferenced pointer past the end of %select{|subobject of }0"
+  "%select{temporary|%2}1 is not a constant expression">;
+def note_constexpr_past_end_subobject : Note<
+  "cannot %select{access base class of|access derived class of|access fiel=
d of|"
+  "access array element of|ERROR|call member function on|"
+  "access real component of|access imaginary component of}0 "
+  "pointer past the end of object">;
+def note_constexpr_null_subobject : Note<
+  "cannot %select{access base class of|access derived class of|access fiel=
d of|"
+  "access array element of|perform pointer arithmetic on|"
+  "call member function on|access real component of|"
+  "access imaginary component of}0 null pointer">;
+def note_constexpr_var_init_non_constant : Note<
+  "initializer of %0 is not a constant expression">;
+def note_constexpr_typeid_polymorphic : Note<
+  "typeid applied to expression of polymorphic type %0 is "
+  "not allowed in a constant expression">;
+def note_constexpr_void_comparison : Note<
+  "comparison between unequal pointers to void has unspecified result">;
+def note_constexpr_temporary_here : Note<"temporary created here">;
+def note_constexpr_conditional_never_const : Note<
+  "both arms of conditional operator are unable to produce a "
+  "constant expression">;
+def note_constexpr_depth_limit_exceeded : Note<
+  "constexpr evaluation exceeded maximum depth of %0 calls">;
+def note_constexpr_call_limit_exceeded : Note<
+  "constexpr evaluation hit maximum call limit">;
+def note_constexpr_lifetime_ended : Note<
+  "read of %select{temporary|variable}0 whose lifetime has ended">;
+def note_constexpr_ltor_volatile_type : Note<
+  "read of volatile-qualified type %0 is not allowed in a constant express=
ion">;
+def note_constexpr_ltor_volatile_obj : Note<
+  "read of volatile %select{temporary|object %1|member %1}0 is not allowed=
 in "
+  "a constant expression">;
+def note_constexpr_ltor_mutable : Note<
+  "read of mutable member %0 is not allowed in a constant expression">;
+def note_constexpr_ltor_non_const_int : Note<
+  "read of non-const variable %0 is not allowed in a constant expression">;
+def note_constexpr_ltor_non_constexpr : Note<
+  "read of non-constexpr variable %0 is not allowed in a constant expressi=
on">;
+def note_constexpr_read_past_end : Note<
+  "read of dereferenced one-past-the-end pointer is not allowed in a "
+  "constant expression">;
+def note_constexpr_read_inactive_union_member : Note<
+  "read of member %0 of union with %select{active member %2|no active memb=
er}1 "
+  "is not allowed in a constant expression">;
+def note_constexpr_read_uninit : Note<
+  "read of uninitialized object is not allowed in a constant expression">;
+def note_constexpr_calls_suppressed : Note<
+  "(skipping %0 call%s0 in backtrace; use -fconstexpr-backtrace-limit=3D0 =
to "
+  "see all)">;
+def note_constexpr_call_here : Note<"in call to '%0'">;
=20
 // inline asm related.
 let CategoryName =3D "Inline Assembly Issue" in {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticAnalysisKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticAnalysisK=
inds.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticAnalysisK=
inds.td	Tue Apr 17 11:51:51 2012 +0300
@@ -9,7 +9,4 @@
=20
 let Component =3D "Analysis" in {
=20
-// CHECK: use of uninitialized values
-def warn_uninit_val : Warning<"use of uninitialized variable">;
-
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticCommonKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticCommonKin=
ds.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticCommonKin=
ds.td	Tue Apr 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 def fatal_too_many_errors
   : Error<"too many errors emitted, stopping now">, DefaultFatal;=20
=20
+def note_declared_at : Note<"declared here">;
 def note_previous_definition : Note<"previous definition is here">;
 def note_previous_declaration : Note<"previous declaration is here">;
 def note_previous_implicit_declaration : Note<
@@ -40,6 +41,12 @@
 def err_expected_colon_after_setter_name : Error<
   "method name referenced in property setter attribute "
   "must end with ':'">;
+def err_invalid_string_udl : Error<
+  "string literal with user-defined suffix cannot be used here">;
+def err_invalid_character_udl : Error<
+  "character literal with user-defined suffix cannot be used here">;
+def err_invalid_numeric_udl : Error<
+  "numeric literal with user-defined suffix cannot be used here">;
=20
 // Parse && Sema
 def ext_no_declarators : ExtWarn<"declaration does not declare anything">,
@@ -58,8 +65,6 @@
   InGroup<CXX98Compat>, DefaultIgnore;
 def err_default_special_members : Error<
   "only special member functions may be defaulted">;
-def err_friends_define_only_namespace_scope : Error<
-  "cannot define a function with non-namespace scope in a friend declarati=
on">;
 def err_deleted_non_function : Error<
   "only functions can have deleted definitions">;
 def err_module_not_found : Error<"module '%0' not found">, DefaultFatal;
@@ -83,8 +88,8 @@
   "integer constant is so large that it is unsigned">;
=20
 // Sema && AST
-def note_invalid_subexpr_in_ice : Note<
-  "subexpression not valid in an integer constant expression">;
+def note_invalid_subexpr_in_const_expr : Note<
+  "subexpression not valid in a constant expression">;
=20
 // Targets
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticDriverKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticDriverKin=
ds.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticDriverKin=
ds.td	Tue Apr 17 11:51:51 2012 +0300
@@ -18,6 +18,10 @@
 def err_drv_unknown_language : Error<"language not recognized: '%0'">;
 def err_drv_invalid_arch_name : Error<
   "invalid arch name '%0'">;
+def err_drv_invalid_rtlib_name : Error<
+  "invalid runtime library name in argument '%0'">;
+def err_drv_unsupported_rtlib_for_platform : Error<
+  "unsupported runtime library '%0' for platform '%1'">;
 def err_drv_invalid_stdlib_name : Error<
   "invalid library name in argument '%0'">;
 def err_drv_invalid_opt_with_multiple_archs : Error<
@@ -38,7 +42,7 @@
 def err_drv_invalid_darwin_version : Error<
   "invalid Darwin version number: %0">;
 def err_drv_missing_argument : Error<
-  "argument to '%0' is missing (expected %1 %plural{1:value|:values}1)">;
+  "argument to '%0' is missing (expected %1 value%s1)">;
 def err_drv_invalid_Xarch_argument_with_args : Error<
   "invalid Xarch argument: '%0', options requiring arguments are unsupport=
ed">;
 def err_drv_invalid_Xarch_argument_isdriver : Error<
@@ -62,11 +66,13 @@
 def err_drv_command_failed : Error<
   "%0 command failed with exit code %1 (use -v to see invocation)">;
 def err_drv_command_signalled : Error<
-  "%0 command failed due to signal %1 (use -v to see invocation)">;
+  "%0 command failed due to signal (use -v to see invocation)">;
 def err_drv_invalid_mfloat_abi : Error<
   "invalid float ABI '%0'">;
 def err_drv_invalid_libcxx_deployment : Error<
   "invalid deployment target for -stdlib=3Dlibc++ (requires %0 or later)">;
+def err_drv_invalid_feature : Error<
+  "invalid feature '%0' for CPU '%1'">;
=20
 def err_drv_I_dash_not_supported : Error<
   "'%0' not supported, please use -iquote instead">;
@@ -89,21 +95,23 @@
   "cannot specify both '-fobjc-arc' and '%0'">;
 def err_arc_nonfragile_abi : Error<
   "-fobjc-arc is not supported with fragile abi">;
+def err_arc_unsupported : Error<
+  "-fobjc-arc is not supported on current deployment target">;
 def err_drv_mg_requires_m_or_mm : Error<
   "option '-MG' requires '-M' or '-MM'">;
=20
 def warn_c_kext : Warning<
   "ignoring -fapple-kext which is valid for c++ and objective-c++ only">;
-def warn_drv_unsupported_option_argument : Warning<
-  "ignoring unsupported argument '%1' to option '%0'">;
 def warn_drv_input_file_unused : Warning<
   "%0: '%1' input unused when '%2' is present">;
 def warn_drv_preprocessed_input_file_unused : Warning<
   "%0: previously preprocessed input unused when '%1' is present">;
 def warn_drv_unused_argument : Warning<
-  "argument unused during compilation: '%0'">;
-def warn_drv_pipe_ignored_with_save_temps : Warning<
-  "-pipe ignored because -save-temps specified">;
+  "argument unused during compilation: '%0'">,
+  InGroup<DiagGroup<"unused-command-line-argument">>;
+def warn_drv_empty_joined_argument : Warning<
+  "joined argument expects addition arg: '%0'">,
+  InGroup<DiagGroup<"unused-command-line-argument">>;
 def warn_drv_not_using_clang_cpp : Warning<
   "not using the clang preprocessor due to user override">;
 def warn_drv_not_using_clang_cxx : Warning<
@@ -116,8 +124,6 @@
   "unknown platform, assuming -mfloat-abi=3D%0">;
 def warn_ignoring_ftabstop_value : Warning<
   "ignoring invalid -ftabstop value '%0', using default value %1">;
-def warn_drv_conflicting_deployment_targets : Warning<
-  "conflicting deployment targets, both MACOSX_DEPLOYMENT_TARGET '%0' and =
IPHONEOS_DEPLOYMENT_TARGET '%1' are present in environment">;
 def warn_drv_treating_input_as_cxx : Warning<
   "treating '%0' input as '%1' when in C++ mode, this behavior is deprecat=
ed">,
   InGroup<Deprecated>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticFrontendKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticFrontendK=
inds.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticFrontendK=
inds.td	Tue Apr 17 11:51:51 2012 +0300
@@ -13,12 +13,12 @@
 def err_fe_error_reading : Error<"error reading '%0'">;
 def err_fe_error_reading_stdin : Error<"error reading stdin">;
 def err_fe_error_backend : Error<"error in backend: %0">, DefaultFatal;
-def err_fe_invalid_ast_file : Error<"invalid AST file: '%0'">, DefaultFata=
l;
-def err_fe_invalid_ast_action : Error<"invalid action for AST input">,
-                                      DefaultFatal;
+
 // Error generated by the backend.
 def err_fe_inline_asm : Error<"%0">, CatInlineAsm;
 def note_fe_inline_asm_here : Note<"instantiated into assembly here">;
+def err_fe_cannot_link_module : Error<"cannot link module '%0': %1">,
+  DefaultFatal;
=20
=20
=20
@@ -26,16 +26,8 @@
     "cannot locate code-completion file %0">, DefaultFatal;
 def err_fe_stdout_binary : Error<"unable to change standard output to bina=
ry">,
   DefaultFatal;
-def err_fe_stderr_binary : Error<"unable to change standard error to binar=
y">,
-  DefaultFatal;
 def err_fe_dependency_file_requires_MT : Error<
     "-dependency-file requires at least one -MT or -MQ option">;
-def err_fe_incompatible_options : Error<
-    "'%0' cannot be used with '%1'">, DefaultFatal;
-def err_fe_no_fixit_and_codegen : Error<
-    "FIX-ITs cannot be applied when generating code">;
-def err_fe_unable_to_find_fixit_file : Error<
-    "FIX-IT could not find file '%0'">;
 def err_fe_invalid_plugin_name : Error<
     "unable to find plugin '%0'">;
 def err_fe_expected_compiler_job : Error<
@@ -54,19 +46,6 @@
     "unable to create target: '%0'">;
 def err_fe_unable_to_interface_with_target : Error<
     "unable to interface with target machine">;
-def err_fe_unable_to_read_pch_file : Error<
-    "unable to read PCH file: '%0'">;
-def err_fe_not_a_pch_file : Error<
-    "input is not a PCH file: '%0'">;
-def err_fe_pch_malformed : Error<
-    "malformed or corrupted PCH file: '%0'">, DefaultFatal;
-def err_fe_pch_malformed_block : Error<
-    "malformed block record in PCH file: '%0'">, DefaultFatal;
-def err_fe_pch_error_at_end_block : Error<
-    "error at end of module block in PCH file: '%0'">, DefaultFatal;
-def err_fe_pch_file_modified : Error<
-    "file '%0' has been modified since the precompiled header was built">,
-    DefaultFatal;
 def err_fe_unable_to_open_output : Error<
     "unable to open output file '%0': '%1'">;
 def err_fe_unable_to_rename_temp : Error<
@@ -82,6 +61,10 @@
 def warn_fe_cc_log_diagnostics_failure : Warning<
     "unable to open CC_LOG_DIAGNOSTICS file: %0 (using stderr)">;
=20
+def warn_fe_serialized_diag_failure : Warning<
+    "unable to open file %0 for serializing diagnostics (%1)">,
+    InGroup<DiagGroup<"serialized-diagnostics">>;
+
 def err_verify_missing_start : Error<
     "cannot find start ('{{') of expected %0">;
 def err_verify_missing_end : Error<
@@ -98,54 +81,25 @@
 def note_fixit_failed : Note<
     "FIX-IT unable to apply suggested code changes">;
 def note_fixit_unfixed_error : Note<"FIX-IT detected an error it cannot fi=
x">;
-def note_fixit_main_file_unchanged : Note<
-    "main file unchanged">;
 def warn_fixit_no_changes : Note<
     "FIX-IT detected errors it could not fix; no output will be generated"=
>;
=20
-def err_fe_invoking : Error<"error invoking%0: %1">, DefaultFatal;
-
 // PCH reader
 def err_relocatable_without_isysroot : Error<
     "must specify system root with -isysroot when building a relocatable "
     "PCH file">;
-def warn_pch_target_triple : Error<
-    "PCH file was compiled for the target '%0' but the current translation=
 "
-    "unit is being compiled for target '%1'">;
-def err_pch_langopt_mismatch : Error<"%0 was %select{disabled|enabled}1 in=
 "
-    "PCH file but is currently %select{disabled|enabled}2">;
-def err_pch_langopt_value_mismatch : Error<
-  "%0 differs in PCH file vs. current file">;
- =20
-def warn_pch_version_too_old : Error<
-    "PCH file uses an older PCH format that is no longer supported">;
-def warn_pch_version_too_new : Error<
-    "PCH file uses a newer PCH format that cannot be read">;
-def warn_pch_different_branch : Error<
-    "PCH file built from a different branch (%0) than the compiler (%1)">;
-def warn_cmdline_conflicting_macro_def : Error<
-    "definition of the macro '%0' conflicts with the definition used to "
-    "build the precompiled header">;
-def note_pch_macro_defined_as : Note<
-    "definition of macro '%0' in the precompiled header">;
-def warn_cmdline_missing_macro_defs : Warning<
-    "macro definitions used to build the precompiled header are missing">;
-def note_using_macro_def_from_pch : Note<
-    "using this macro definition from precompiled header">;
-def warn_macro_name_used_in_pch : Error<
-    "definition of macro %0 conflicts with an identifier used in the "
-    "precompiled header">;
-def warn_pch_compiler_options_mismatch : Error<
-    "compiler options used when building the precompiled header differ fro=
m "
-    "the options used when using the precompiled header">;
=20
-def err_not_a_pch_file : Error<
-    "'%0' does not appear to be a precompiled header file">, DefaultFatal;
 def warn_unknown_warning_option : Warning<
     "unknown warning option '%0'">,
     InGroup<DiagGroup<"unknown-warning-option"> >;
 def warn_unknown_negative_warning_option : Warning<
-    "unknown warning option '%0'">,
+    "unknown warning option '%0'?">,
+    InGroup<DiagGroup<"unknown-warning-option"> >, DefaultIgnore;
+def warn_unknown_warning_option_suggest : Warning<
+    "unknown warning option '%0'; did you mean '%1'?">,
+    InGroup<DiagGroup<"unknown-warning-option"> >;
+def warn_unknown_negative_warning_option_suggest : Warning<
+    "unknown warning option '%0'; did you mean '%1'?">,
     InGroup<DiagGroup<"unknown-warning-option"> >, DefaultIgnore;
 def warn_unknown_warning_specifier : Warning<
     "unknown %0 warning specifier: '%1'">,
@@ -158,4 +112,23 @@
     InGroup<DiagGroup<"analyzer-incompatible-plugin"> >;
 def note_incompatible_analyzer_plugin_api : Note<
     "current API version is '%0', but plugin was compiled with version '%1=
'">;
+   =20
+def err_module_map_not_found : Error<"module map file '%0' not found">,=20
+  DefaultFatal;
+def err_missing_module_name : Error<
+  "no module name provided; specify one with -fmodule-name=3D">,=20
+  DefaultFatal;
+def err_missing_module : Error<
+  "no module named '%0' declared in module map file '%1'">, DefaultFatal;
+def err_missing_umbrella_header : Error<
+  "cannot open umbrella header '%0': %1">, DefaultFatal;
+def err_no_submodule : Error<"no submodule named %0 in module '%1'">;
+def err_no_submodule_suggest : Error<
+  "no submodule named %0 in module '%1'; did you mean '%2'?">;
+def warn_missing_submodule : Warning<"missing submodule '%0'">,
+  InGroup<IncompleteUmbrella>;
+def err_module_map_temp_file : Error<
+  "unable to write temporary module map file '%0'">, DefaultFatal;
+def err_module_unavailable : Error<"module '%0' requires feature '%1'">;
+
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticGroups.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticGroups.td=
	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,14 @@
 def : DiagGroup<"attributes">;
 def : DiagGroup<"bad-function-cast">;
 def Availability : DiagGroup<"availability">;
-def BoolConversions : DiagGroup<"bool-conversions">;
+def AutoImport : DiagGroup<"auto-import">;
+def ConstantConversion : DiagGroup<"constant-conversion">;
+def LiteralConversion : DiagGroup<"literal-conversion">;
+def StringConversion : DiagGroup<"string-conversion">;
+def SignConversion : DiagGroup<"sign-conversion">;
+def BoolConversion : DiagGroup<"bool-conversion">;
+def IntConversion : DiagGroup<"int-conversion">;
+def NullConversion : DiagGroup<"null-conversion">;
 def BuiltinRequiresHeader : DiagGroup<"builtin-requires-header">;
 def CXXCompat: DiagGroup<"c++-compat">;
 def CastAlign : DiagGroup<"cast-align">;
@@ -55,34 +62,63 @@
 def FormatExtraArgs : DiagGroup<"format-extra-args">;
 def FormatZeroLength : DiagGroup<"format-zero-length">;
=20
-def CXX98Compat : DiagGroup<"c++98-compat">;
+def CXX98CompatBindToTemporaryCopy :
+  DiagGroup<"c++98-compat-bind-to-temporary-copy">;
+def CXX98CompatLocalTypeTemplateArgs :
+  DiagGroup<"c++98-compat-local-type-template-args">;
+def CXX98CompatUnnamedTypeTemplateArgs :
+  DiagGroup<"c++98-compat-unnamed-type-template-args">;
+
+def CXX98Compat : DiagGroup<"c++98-compat",
+                            [CXX98CompatBindToTemporaryCopy,
+                             CXX98CompatLocalTypeTemplateArgs,
+                             CXX98CompatUnnamedTypeTemplateArgs]>;
 // Warnings for C++11 features which are Extensions in C++98 mode.
 def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic", [CXX98Compat]=
>;
=20
 def CXX11Narrowing : DiagGroup<"c++11-narrowing">;
+
+// Original name of this warning in Clang
 def : DiagGroup<"c++0x-narrowing", [CXX11Narrowing]>;
=20
-def CXX11Compat : DiagGroup<"c++11-compat", [CXX11Narrowing]>;
+// Name of this warning in GCC
+def : DiagGroup<"narrowing", [CXX11Narrowing]>;
+
+def CXX11CompatReservedUserDefinedLiteral :
+  DiagGroup<"c++11-compat-reserved-user-defined-literal">;
+def ReservedUserDefinedLiteral :
+  DiagGroup<"reserved-user-defined-literal",
+            [CXX11CompatReservedUserDefinedLiteral]>;
+
+def CXX11Compat : DiagGroup<"c++11-compat",
+                            [CXX11Narrowing,
+                             CXX11CompatReservedUserDefinedLiteral]>;
 def : DiagGroup<"c++0x-compat", [CXX11Compat]>;
=20
 def : DiagGroup<"effc++">;
 def ExitTimeDestructors : DiagGroup<"exit-time-destructors">;
+def FlexibleArrayExtensions : DiagGroup<"flexible-array-extensions">;
 def FourByteMultiChar : DiagGroup<"four-char-constants">;
 def GlobalConstructors : DiagGroup<"global-constructors">;
 def : DiagGroup<"idiomatic-parentheses">;
 def BitwiseOpParentheses: DiagGroup<"bitwise-op-parentheses">;
 def LogicalOpParentheses: DiagGroup<"logical-op-parentheses">;
+def DanglingElse: DiagGroup<"dangling-else">;
 def IgnoredQualifiers : DiagGroup<"ignored-qualifiers">;
 def : DiagGroup<"import">;
 def IncompatiblePointerTypes : DiagGroup<"incompatible-pointer-types">;
+def IncompleteUmbrella : DiagGroup<"incomplete-umbrella">;
+def KNRPromotedParameter : DiagGroup<"knr-promoted-parameter">;
 def : DiagGroup<"init-self">;
 def : DiagGroup<"inline">;
 def : DiagGroup<"int-to-pointer-cast">;
 def : DiagGroup<"invalid-pch">;
 def LiteralRange : DiagGroup<"literal-range">;
-def LocalTypeTemplateArgs : DiagGroup<"local-type-template-args">;
+def LocalTypeTemplateArgs : DiagGroup<"local-type-template-args",
+                                      [CXX98CompatLocalTypeTemplateArgs]>;
 def MalformedWarningCheck : DiagGroup<"malformed-warning-check">;
 def Main : DiagGroup<"main">;
+def MainReturnType : DiagGroup<"main-return-type">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
 def : DiagGroup<"missing-format-attribute">;
@@ -95,31 +131,37 @@
 def MismatchedTags : DiagGroup<"mismatched-tags">;
 def MissingFieldInitializers : DiagGroup<"missing-field-initializers">;
 def ModuleBuild : DiagGroup<"module-build">;
+def NullCharacter : DiagGroup<"null-character">;
 def NullDereference : DiagGroup<"null-dereference">;
 def InitializerOverrides : DiagGroup<"initializer-overrides">;
 def NonNull : DiagGroup<"nonnull">;
 def : DiagGroup<"nonportable-cfstrings">;
 def NonVirtualDtor : DiagGroup<"non-virtual-dtor">;
+def OveralignedType : DiagGroup<"over-aligned">;
 def : DiagGroup<"old-style-cast">;
 def : DiagGroup<"old-style-definition">;
 def OutOfLineDeclaration : DiagGroup<"out-of-line-declaration">;
 def : DiagGroup<"overflow">;
 def OverlengthStrings : DiagGroup<"overlength-strings">;
 def OverloadedVirtual : DiagGroup<"overloaded-virtual">;
+def ObjCPropertyImpl : DiagGroup<"objc-property-implementation">;
 def ObjCMissingSuperCalls : DiagGroup<"objc-missing-super-calls">;
 def ObjCRetainBlockProperty : DiagGroup<"objc-noncopy-retain-block-propert=
y">;
-def ObjCContinuationPropertyType :DiagGroup<"objc-continuation-property-ty=
pe">;
+def ObjCReadonlyPropertyHasSetter : DiagGroup<"objc-readonly-with-setter-p=
roperty">;
+def ObjCRootClass : DiagGroup<"objc-root-class">;
 def Packed : DiagGroup<"packed">;
 def Padded : DiagGroup<"padded">;
 def PointerArith : DiagGroup<"pointer-arith">;
 def PoundWarning : DiagGroup<"#warnings">,
                    DiagCategory<"#warning Directive">;
-def PoundPragmaMessage : DiagGroup<"#pragma messages">,
+def PoundPragmaMessage : DiagGroup<"#pragma-messages">,
                          DiagCategory<"#pragma message Directive">;
 def : DiagGroup<"pointer-to-int-cast">;
 def : DiagGroup<"redundant-decls">;
-def ReturnType : DiagGroup<"return-type">;
-def BindToTemporaryCopy : DiagGroup<"bind-to-temporary-copy">;
+def ReturnTypeCLinkage : DiagGroup<"return-type-c-linkage">;
+def ReturnType : DiagGroup<"return-type", [ReturnTypeCLinkage]>;
+def BindToTemporaryCopy : DiagGroup<"bind-to-temporary-copy",
+                                    [CXX98CompatBindToTemporaryCopy]>;
 def SelfAssignment : DiagGroup<"self-assign">;
 def SemiBeforeMethodBody : DiagGroup<"semicolon-before-method-body">;
 def Sentinel : DiagGroup<"sentinel">;
@@ -133,6 +175,8 @@
 def : DiagGroup<"switch-default">;
 def : DiagGroup<"synth">;
 def SizeofArrayArgument : DiagGroup<"sizeof-array-argument">;
+def StringPlusInt : DiagGroup<"string-plus-int">;
+def StrncatSize : DiagGroup<"strncat-size">;
 def TautologicalCompare : DiagGroup<"tautological-compare">;
 def HeaderHygiene : DiagGroup<"header-hygiene">;
=20
@@ -155,18 +199,25 @@
 def : DiagGroup<"strict-overflow">;
=20
 def InvalidOffsetof : DiagGroup<"invalid-offsetof">;
+def LambdaExtensions : DiagGroup<"lambda-extensions">;
 def : DiagGroup<"strict-prototypes">;
 def StrictSelector : DiagGroup<"strict-selector-match">;
+def MethodDuplicate : DiagGroup<"duplicate-method-match">;
+def CoveredSwitchDefault : DiagGroup<"covered-switch-default">;
 def SwitchEnum     : DiagGroup<"switch-enum">;
-def Switch         : DiagGroup<"switch", [SwitchEnum]>;
+def Switch         : DiagGroup<"switch">;
 def Trigraphs      : DiagGroup<"trigraphs">;
=20
 def : DiagGroup<"type-limits">;
+def Unicode  : DiagGroup<"unicode">;
 def Uninitialized  : DiagGroup<"uninitialized">;
 def UninitializedMaybe : DiagGroup<"conditional-uninitialized">;
 def UnknownPragmas : DiagGroup<"unknown-pragmas">;
+def NSobjectAttribute : DiagGroup<"NSObject-attribute">;
 def UnknownAttributes : DiagGroup<"attributes">;
-def UnnamedTypeTemplateArgs : DiagGroup<"unnamed-type-template-args">;
+def IgnoredAttributes : DiagGroup<"ignored-attributes">;
+def UnnamedTypeTemplateArgs : DiagGroup<"unnamed-type-template-args",
+                                        [CXX98CompatUnnamedTypeTemplateArg=
s]>;
 def UnusedArgument : DiagGroup<"unused-argument">;
 def UnusedComparison : DiagGroup<"unused-comparison">;
 def UnusedExceptionParameter : DiagGroup<"unused-exception-parameter">;
@@ -205,9 +256,11 @@
 def OverridingMethodMismatch : DiagGroup<"overriding-method-mismatch">;
 def : DiagGroup<"variadic-macros">;
 def VariadicMacros : DiagGroup<"variadic-macros">;
-def VectorConversions : DiagGroup<"vector-conversions">;      // clang spe=
cific
+def VectorConversion : DiagGroup<"vector-conversion">;      // clang speci=
fic
+def VexingParse : DiagGroup<"vexing-parse">;
 def VLA : DiagGroup<"vla">;
 def VolatileRegisterVar : DiagGroup<"volatile-register-var">;
+def Visibility : DiagGroup<"visibility">;
=20
 // GCC calls -Wdeprecated-writable-strings -Wwrite-strings.
 def GCCWriteStrings : DiagGroup<"write-strings" , [DeprecatedWritableStr]>;
@@ -226,7 +279,8 @@
 def Parentheses : DiagGroup<"parentheses",
                             [LogicalOpParentheses,
                              BitwiseOpParentheses,
-                             ParenthesesOnEquality]>;
+                             ParenthesesOnEquality,
+                             DanglingElse]>;
=20
 // -Wconversion has its own warnings, but we split a few out for
 // legacy reasons:
@@ -234,13 +288,16 @@
 //   - conversion warnings with constant sources are on by default
 //   - conversion warnings for literals are on by default
 //   - bool-to-pointer conversion warnings are on by default
+//   - __null-to-integer conversion warnings are on by default
 def Conversion : DiagGroup<"conversion",
                            [DiagGroup<"shorten-64-to-32">,
-                            DiagGroup<"constant-conversion">,
-                            DiagGroup<"literal-conversion">,
-                            DiagGroup<"string-conversion">,
-                            DiagGroup<"sign-conversion">,
-                            BoolConversions]>,
+                            ConstantConversion,
+                            LiteralConversion,
+                            StringConversion,
+                            SignConversion,
+                            BoolConversion,
+                            NullConversion,
+                            IntConversion]>,
                  DiagCategory<"Value Conversion Issue">;
=20
 def Unused : DiagGroup<"unused",
@@ -253,6 +310,7 @@
 // Format settings.
 def FormatInvalidSpecifier : DiagGroup<"format-invalid-specifier">;
 def FormatSecurity : DiagGroup<"format-security">;
+def FormatNonStandard : DiagGroup<"format-non-iso">;
 def FormatY2K : DiagGroup<"format-y2k">;
 def Format : DiagGroup<"format",
                        [FormatExtraArgs, FormatZeroLength, NonNull,
@@ -284,8 +342,8 @@
     Reorder,
     ReturnType,
     SelfAssignment,
-    Switch,
     SizeofArrayArgument,
+    StringPlusInt,
     Trigraphs,
     Uninitialized,
     UnknownPragmas,
@@ -298,13 +356,23 @@
 // Thread Safety warnings=20
 def ThreadSafety : DiagGroup<"thread-safety">;
=20
-// -Wall is -Wmost -Wparentheses -Wtop-level-comparison
-def : DiagGroup<"all", [Most, Parentheses]>;
+// Note that putting warnings in -Wall will not disable them by default. I=
f a
+// warning should be active _only_ when -Wall is passed in, mark it as
+// DefaultIgnore in addition to putting it here.
+def : DiagGroup<"all", [Most, Parentheses, Switch]>;
=20
 // Aliases.
 def : DiagGroup<"", [Extra]>;                   // -W =3D -Wextra
 def : DiagGroup<"endif-labels", [ExtraTokens]>; // -Wendif-labels=3D-Wendi=
f-tokens
 def : DiagGroup<"comments", [Comment]>;         // -Wcomments =3D -Wcomment
+def : DiagGroup<"conversion-null",
+                [NullConversion]>; // -Wconversion-null =3D -Wnull-convers=
ion
+def : DiagGroup<"bool-conversions",
+                [BoolConversion]>; // -Wbool-conversions  =3D -Wbool-conve=
rsion
+def : DiagGroup<"int-conversions",
+                [IntConversion]>; // -Wint-conversions =3D -Wint-conversion
+def : DiagGroup<"vector-conversions",
+                [VectorConversion]>; // -Wvector-conversions =3D -Wvector-=
conversion
=20
 // A warning group for warnings that we want to have on by default in clan=
g,
 // but which aren't on by default in GCC.
@@ -318,11 +386,16 @@
 def DelegatingCtorCycles :
   DiagGroup<"delegating-ctor-cycles">;
=20
-// A warning group for warnings about using C1X features as extensions.
-def C1X : DiagGroup<"c1x-extensions">;
+// A warning group for warnings about using C11 features as extensions.
+def C11 : DiagGroup<"c11-extensions">;
+
+// A warning group for warnings about using C99 features as extensions.
+def C99 : DiagGroup<"c99-extensions">;
=20
 // A warning group for warnings about GCC extensions.
 def GNU : DiagGroup<"gnu", [GNUDesignator, VLA]>;
+// A warning group for warnings about code that clang accepts but gcc does=
n't.
+def GccCompat : DiagGroup<"gcc-compat">;
=20
 // A warning group for warnings about Microsoft extensions.
 def Microsoft : DiagGroup<"microsoft">;
@@ -330,3 +403,13 @@
 def ObjCNonUnifiedException : DiagGroup<"objc-nonunified-exceptions">;
=20
 def ObjCProtocolMethodImpl : DiagGroup<"objc-protocol-method-implementatio=
n">;
+
+// ObjC API warning groups.
+def ObjCRedundantLiteralUse : DiagGroup<"objc-redundant-literal-use">;
+def ObjCRedundantAPIUse : DiagGroup<"objc-redundant-api-use", [
+    ObjCRedundantLiteralUse
+  ]>;
+
+def ObjCCocoaAPI : DiagGroup<"objc-cocoa-api", [
+    ObjCRedundantAPIUse
+  ]>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticIDs.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticIDs.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticIDs.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -31,14 +31,15 @@
   namespace diag {
     // Start position for diagnostics.
     enum {
-      DIAG_START_DRIVER   =3D                        300,
-      DIAG_START_FRONTEND =3D DIAG_START_DRIVER   +  100,
-      DIAG_START_LEX      =3D DIAG_START_FRONTEND +  120,
-      DIAG_START_PARSE    =3D DIAG_START_LEX      +  300,
-      DIAG_START_AST      =3D DIAG_START_PARSE    +  300,
-      DIAG_START_SEMA     =3D DIAG_START_AST      +  100,
-      DIAG_START_ANALYSIS =3D DIAG_START_SEMA     + 3000,
-      DIAG_UPPER_LIMIT    =3D DIAG_START_ANALYSIS +  100
+      DIAG_START_DRIVER        =3D                               300,
+      DIAG_START_FRONTEND      =3D DIAG_START_DRIVER          +  100,
+      DIAG_START_SERIALIZATION =3D DIAG_START_FRONTEND        +  100,
+      DIAG_START_LEX           =3D DIAG_START_SERIALIZATION   +  120,
+      DIAG_START_PARSE         =3D DIAG_START_LEX             +  300,
+      DIAG_START_AST           =3D DIAG_START_PARSE           +  400,
+      DIAG_START_SEMA          =3D DIAG_START_AST             +  100,
+      DIAG_START_ANALYSIS      =3D DIAG_START_SEMA            + 3000,
+      DIAG_UPPER_LIMIT         =3D DIAG_START_ANALYSIS        +  100
     };
=20
     class CustomDiagInfo;
@@ -49,7 +50,7 @@
     // Get typedefs for common diagnostics.
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,CATEGORY,NOWERROR,SHOWINSYSHEADER,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,CATEGORY,NOWERROR,SHOWINSYSHEADER) ENUM,
 #include "clang/Basic/DiagnosticCommonKinds.inc"
       NUM_BUILTIN_COMMON_DIAGNOSTICS
 #undef DIAG
@@ -108,7 +109,7 @@
=20
 /// \brief Used for handling and querying diagnostic IDs. Can be used and =
shared
 /// by multiple Diagnostics for multiple translation units.
-class DiagnosticIDs : public llvm::RefCountedBase<DiagnosticIDs> {
+class DiagnosticIDs : public RefCountedBase<DiagnosticIDs> {
 public:
   /// Level - The level of the diagnostic, after it has been through mappi=
ng.
   enum Level {
@@ -182,6 +183,10 @@
   /// category.
   static StringRef getCategoryNameFromID(unsigned CategoryID);
  =20
+  /// isARCDiagnostic - Return true if a given diagnostic falls into an
+  /// ARC diagnostic category;
+  static bool isARCDiagnostic(unsigned DiagID);
+
   /// \brief Enumeration describing how the the emission of a diagnostic s=
hould
   /// be treated when it occurs during C++ template argument deduction.
   enum SFINAEResponse {
@@ -218,39 +223,6 @@
   /// are not SFINAE errors.
   static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID);
=20
-  /// getName - Given a diagnostic ID, return its name
-  static StringRef getName(unsigned DiagID);
- =20
-  /// getIdFromName - Given a diagnostic name, return its ID, or 0
-  static unsigned getIdFromName(StringRef Name);
- =20
-  /// getBriefExplanation - Given a diagnostic ID, return a brief explanat=
ion
-  /// of the issue
-  static StringRef getBriefExplanation(unsigned DiagID);
-
-  /// getFullExplanation - Given a diagnostic ID, return a full explanation
-  /// of the issue
-  static StringRef getFullExplanation(unsigned DiagID);
- =20
-  /// Iterator class used for traversing all statically declared
-  /// diagnostics.
-  class diag_iterator {
-    const void *impl;
-
-    friend class DiagnosticIDs;   =20
-    diag_iterator(const void *im) : impl(im) {}
-  public:
-    diag_iterator &operator++();
-    bool operator=3D=3D(const diag_iterator &x) const { return impl =3D=3D=
 x.impl; }
-    bool operator!=3D(const diag_iterator &x) const { return impl !=3D x.i=
mpl; }
-   =20
-    llvm::StringRef getDiagName() const;
-    unsigned getDiagID() const;   =20
-  };
-
-  static diag_iterator diags_begin();
-  static diag_iterator diags_end();
-
   /// \brief Get the set of all diagnostic IDs in the group with the given=
 name.
   ///
   /// \param Diags [out] - On return, the diagnostics in the group.
@@ -258,6 +230,13 @@
   bool getDiagnosticsInGroup(StringRef Group,
                              llvm::SmallVectorImpl<diag::kind> &Diags) con=
st;
=20
+  /// \brief Get the set of all diagnostic IDs.
+  void getAllDiagnostics(llvm::SmallVectorImpl<diag::kind> &Diags) const;
+
+  /// \brief Get the warning option with the closest edit distance to the =
given
+  /// group name.
+  static StringRef getNearestWarningOption(StringRef Group);
+
 private:
   /// \brief Get the set of all diagnostic IDs in the given group.
   ///
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticLexKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticLexKinds.=
td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticLexKinds.=
td	Tue Apr 17 11:51:51 2012 +0300
@@ -13,16 +13,19 @@
=20
 let Component =3D "Lex", CategoryName =3D "Lexical or Preprocessor Issue" =
in {
=20
-def null_in_string : Warning<"null character(s) preserved in string litera=
l">;
-def null_in_char : Warning<"null character(s) preserved in character liter=
al">;
-def null_in_file : Warning<"null character ignored">;
+def null_in_string : Warning<"null character(s) preserved in string litera=
l">,
+  InGroup<NullCharacter>;
+def null_in_char : Warning<"null character(s) preserved in character liter=
al">,
+  InGroup<NullCharacter>;
+def null_in_file : Warning<"null character ignored">, InGroup<NullCharacte=
r>;
 def warn_nested_block_comment : Warning<"'/*' within block comment">,
   InGroup<Comment>;
 def escaped_newline_block_comment_end : Warning<
   "escaped newline between */ characters at block comment end">,
   InGroup<Comment>;
 def backslash_newline_space : Warning<
-  "backslash and newline separated by space">;
+  "backslash and newline separated by space">,
+  InGroup<DiagGroup<"backslash-newline-escape">>;
=20
 // Digraphs.
 def warn_cxx98_compat_less_colon_colon : Warning<
@@ -45,14 +48,21 @@
   InGroup<Comment>;
 def ext_no_newline_eof : Extension<"no newline at end of file">,=20
   InGroup<DiagGroup<"newline-eof">>;
-def ext_dollar_in_identifier : Extension<"'$' in identifier">;
-def charize_microsoft_ext : Extension<"@# is a microsoft extension">;
+
+def warn_cxx98_compat_no_newline_eof : Warning<
+  "C++98 requires newline at end of file">,
+  InGroup<CXX98CompatPedantic>, DefaultIgnore;
+
+def ext_dollar_in_identifier : Extension<"'$' in identifier">,
+  InGroup<DiagGroup<"dollar-in-identifier-extension">>;
+def ext_charize_microsoft : Extension<"@# is a microsoft extension">,
+  InGroup<Microsoft>;
=20
 def ext_token_used : Extension<"extension used">,
   InGroup<DiagGroup<"language-extension-token">>;
=20
 def warn_cxx11_keyword : Warning<"'%0' is a keyword in C++11">,
-  InGroup<CXX11Compat>;
+  InGroup<CXX11Compat>, DefaultIgnore;
=20
 def warn_unterminated_string : ExtWarn<"missing terminating '\"' character=
">;
 def warn_unterminated_char : ExtWarn<"missing terminating ' character">;
@@ -90,7 +100,16 @@
 def err_ucn_escape_no_digits : Error<"\\u used with no following hex digit=
s">;
 def err_ucn_escape_invalid : Error<"invalid universal character">;
 def err_ucn_escape_incomplete : Error<"incomplete universal character name=
">;
-def err_ucn_escape_too_big : Error<"universal character name is too long">;
+def err_ucn_escape_basic_scs : Error<
+  "character '%0' cannot be specified by a universal character name">;
+def err_ucn_control_character : Error<
+  "universal character name refers to a control character">;
+def warn_cxx98_compat_literal_ucn_escape_basic_scs : Warning<
+  "specifying character '%0' with a universal character name "
+  "is incompatible with C++98">, InGroup<CXX98Compat>, DefaultIgnore;
+def warn_cxx98_compat_literal_ucn_control_character : Warning<
+  "universal character name referring to a control character "
+  "is incompatible with C++98">, InGroup<CXX98Compat>, DefaultIgnore;
 def err_invalid_decimal_digit : Error<"invalid digit '%0' in decimal const=
ant">;
 def err_invalid_binary_digit : Error<"invalid digit '%0' in binary constan=
t">;
 def err_invalid_octal_digit : Error<"invalid digit '%0' in octal constant"=
>;
@@ -102,10 +121,14 @@
   "extraneous characters in character constant ignored">;
 def warn_char_constant_too_large : Warning<
   "character constant too long for its type">;
+def err_multichar_utf_character_literal : Error<
+  "Unicode character literals may not contain multiple characters">;
 def err_exponent_has_no_digits : Error<"exponent has no digits">;
 def ext_imaginary_constant : Extension<"imaginary constants are an extensi=
on">;
 def err_hexconstant_requires_exponent : Error<
   "hexadecimal floating constants require an exponent">;
+def err_hexconstant_requires_digits : Error<
+  "hexadecimal floating constants require a significand">;
 def ext_hexconstant_invalid : Extension<
   "hexadecimal floating constants are a C99 feature">;
 def ext_binary_literal : Extension<
@@ -116,36 +139,69 @@
 def ext_string_too_long : Extension<"string literal of length %0 exceeds "
   "maximum length %1 that %select{C90|ISO C99|C++}2 compilers are required=
 to "
   "support">, InGroup<OverlengthStrings>;
-def warn_ucn_escape_too_large : ExtWarn<
-  "character unicode escape sequence too long for its type">;
+def err_character_too_large : Error<
+  "character too large for enclosing character literal type">;
 def warn_ucn_not_valid_in_c89 : ExtWarn<
-  "unicode escape sequences are only valid in C99 or C++">;
+  "unicode escape sequences are only valid in C99 or C++">, InGroup<Unicod=
e>;
 def warn_cxx98_compat_unicode_literal : Warning<
   "unicode literals are incompatible with C++98">,
   InGroup<CXX98Compat>, DefaultIgnore;
+def warn_cxx11_compat_user_defined_literal : Warning<
+  "identifier after literal will be treated as a user-defined literal suff=
ix "
+  "in C++11">, InGroup<CXX11Compat>, DefaultIgnore;
+def warn_cxx11_compat_reserved_user_defined_literal : Warning<
+  "identifier after literal will be treated as a reserved user-defined lit=
eral "
+  "suffix in C++11">,
+  InGroup<CXX11CompatReservedUserDefinedLiteral>, DefaultIgnore;
+def ext_reserved_user_defined_literal : ExtWarn<
+  "invalid suffix on literal; C++11 requires a space between literal and "
+  "identifier">, InGroup<ReservedUserDefinedLiteral>, DefaultError;
+def ext_ms_reserved_user_defined_literal : ExtWarn<
+  "invalid suffix on literal; C++11 requires a space between literal and "
+  "identifier">, InGroup<ReservedUserDefinedLiteral>;
 def err_unsupported_string_concat : Error<
   "unsupported non-standard concatenation of string literals">;
- =20
+def err_string_concat_mixed_suffix : Error<
+  "differing user-defined suffixes ('%0' and '%1') in string literal "
+  "concatenation">;
+def err_pp_invalid_udl : Error<
+  "%select{character|integer}0 literal with user-defined suffix "
+  "cannot be used in preprocessor constant expression">;
+def err_bad_string_encoding : Error<
+  "illegal character encoding in string literal">;
+def warn_bad_string_encoding : ExtWarn<
+  "illegal character encoding in string literal">,
+  InGroup<DiagGroup<"invalid-source-encoding">>;
+def err_bad_character_encoding : Error<
+  "illegal character encoding in character literal">;
+def warn_bad_character_encoding : ExtWarn<
+  "illegal character encoding in character literal">,
+  InGroup<DiagGroup<"invalid-source-encoding">>;
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PTH Diagnostics
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-def err_pth_cannot_read : Error<
-    "PTH file '%0' could not be read">;
 def err_invalid_pth_file : Error<
     "invalid or corrupt PTH file '%0'">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Preprocessor Diagnostics
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-def pp_hash_warning : Warning<"#warning%0">,
+
+let CategoryName =3D "User Defined Issues" in {
+def pp_hash_warning : Warning<"%0">,
   InGroup<PoundWarning>, DefaultWarnShowInSystemHeader;
+def err_pp_hash_error : Error<"%0">;
+}
+
 def pp_include_next_in_primary : Warning<
   "#include_next in primary source file">;
 def pp_include_macros_out_of_predefines : Error<
   "the #__include_macros directive is only for internal use by -imacros">;
 def pp_include_next_absolute_path : Warning<"#include_next with absolute p=
ath">;
 def ext_c99_whitespace_required_after_macro_name : ExtWarn<
-  "ISO C99 requires whitespace after the macro name">;
+  "ISO C99 requires whitespace after the macro name">, InGroup<C99>;
 def ext_missing_whitespace_after_macro_name : ExtWarn<
   "whitespace required after macro name">;
 def warn_missing_whitespace_after_macro_name : Warning<
@@ -160,6 +216,9 @@
 def pp_undef_builtin_macro : Warning<"undefining builtin macro">;
 def pp_redef_builtin_macro : Warning<"redefining builtin macro">,
   InGroup<DiagGroup<"builtin-macro-redefined">>;
+def pp_disabled_macro_expansion : Warning<
+  "disabled expansion of recursive macro">, DefaultIgnore,
+  InGroup<DiagGroup<"disabled-macro-expansion">>;
 def pp_macro_not_used : Warning<"macro is not used">, DefaultIgnore,
   InGroup<DiagGroup<"unused-macros">>;
 def warn_pp_undef_identifier : Warning<
@@ -175,7 +234,11 @@
 def warn_pp_convert_rhs_to_positive : Warning<
   "right side of operator converted from negative value to unsigned: %0">;
=20
-def ext_pp_import_directive : Extension<"#import is a language extension">;
+def ext_pp_import_directive : Extension<"#import is a language extension">,
+  InGroup<DiagGroup<"import-preprocessor-directive-pedantic">>;
+def err_pp_import_directive_ms : Error<
+  "#import of type library is an unsupported Microsoft feature">;
+
 def ext_pp_ident_directive : Extension<"#ident is a language extension">;
 def ext_pp_include_next_directive : Extension<
   "#include_next is a language extension">;
@@ -195,8 +258,11 @@
   InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def ext_named_variadic_macro : Extension<
   "named variadic macros are a GNU extension">, InGroup<VariadicMacros>;
+def err_embedded_include : Error<
+  "embedding a #%0 directive within macro arguments is not supported">;
 def ext_embedded_directive : Extension<
-  "embedding a directive within macro arguments is not portable">;
+  "embedding a directive within macro arguments has undefined behavior">,
+  InGroup<DiagGroup<"embedded-directive">>;
 def ext_missing_varargs_arg : Extension<
   "varargs argument missing, but tolerated as an extension">;
 def ext_empty_fnmacro_arg : Extension<
@@ -206,7 +272,6 @@
   InGroup<CXX98CompatPedantic>, DefaultIgnore;
=20
 def err_pp_invalid_directive : Error<"invalid preprocessing directive">;
-def err_pp_hash_error : Error<"#error%0">;
 def err_pp_file_not_found : Error<"'%0' file not found">, DefaultFatal;
 def err_pp_error_opening_file : Error<
   "error opening file '%0': %1">, DefaultFatal;
@@ -236,7 +301,6 @@
 def pp_err_elif_without_if : Error<"#elif without #if">;
 def err_pp_endif_without_if : Error<"#endif without #if">;
 def err_pp_expected_value_in_expr : Error<"expected value in expression">;
-def err_pp_missing_val_before_operator : Error<"missing value before opera=
tor">;
 def err_pp_expected_rparen : Error<"expected ')' in preprocessor expressio=
n">;
 def err_pp_expected_eol : Error<
   "expected end of line in preprocessor expression">;
@@ -266,6 +330,19 @@
    ExtWarn<"__has_warning expected option name (e.g. \"-Wundef\")">,
    InGroup<MalformedWarningCheck>;
=20
+def warn_pragma_include_alias_mismatch_angle :
+   ExtWarn<"angle-bracketed include <%0> cannot be aliased to double-quote=
d "
+   "include \"%1\"">, InGroup<UnknownPragmas>;
+def warn_pragma_include_alias_mismatch_quote :
+   ExtWarn<"double-quoted include \"%0\" cannot be aliased to angle-bracke=
ted "
+   "include <%1>">, InGroup<UnknownPragmas>;
+def warn_pragma_include_alias_expected :
+   ExtWarn<"pragma include_alias expected '%0'">,
+   InGroup<UnknownPragmas>;
+def warn_pragma_include_alias_expected_filename :
+   ExtWarn<"pragma include_alias expected include filename">,
+   InGroup<UnknownPragmas>;
+
 def err__Pragma_malformed : Error<
   "_Pragma takes a parenthesized string literal">;
 def err_pragma_comment_malformed : Error<
@@ -355,7 +432,7 @@
   "#line number greater than 32767 is incompatible with C++98">,
   InGroup<CXX98CompatPedantic>, DefaultIgnore;
=20
-def err_pp_export_non_macro : Error<"no macro named %0 to export">;
+def err_pp_visibility_non_macro : Error<"no macro named %0">;
=20
 def err_pp_arc_cf_code_audited_syntax : Error<"expected 'begin' or 'end'">;
 def err_pp_double_begin_of_arc_cf_code_audited : Error<
@@ -367,4 +444,60 @@
 def err_pp_eof_in_arc_cf_code_audited : Error<
   "'#pragma clang arc_cf_code_audited' was not ended within this file">;
=20
+// Module map parsing
+def err_mmap_unknown_token : Error<"skipping stray token">;
+def err_mmap_expected_module : Error<"expected module declaration">;
+def err_mmap_expected_module_name : Error<"expected module name">;
+def err_mmap_expected_lbrace : Error<"expected '{' to start module '%0'">;
+def err_mmap_expected_rbrace : Error<"expected '}'">;
+def note_mmap_lbrace_match : Note<"to match this '{'">;
+def err_mmap_expected_rsquare : Error<"expected ']' to close attribute">;
+def note_mmap_lsquare_match : Note<"to match this ']'">;
+def err_mmap_expected_member : Error<
+  "expected umbrella, header, submodule, or module export">;
+def err_mmap_expected_header : Error<"expected a header name after '%0'">;
+def err_mmap_module_redefinition : Error<
+  "redefinition of module '%0'">;
+def note_mmap_prev_definition : Note<"previously defined here">;
+def err_mmap_header_conflict : Error<
+  "header '%0' is already part of module '%1'">;
+def err_mmap_header_not_found : Error<
+  "%select{|umbrella }0header '%1' not found">;
+def err_mmap_umbrella_dir_not_found : Error<
+  "umbrella directory '%0' not found">;
+def err_mmap_umbrella_clash : Error<
+  "umbrella for module '%0' already covers this directory">;
+def err_mmap_export_module_id : Error<
+  "expected an exported module name or '*'">;
+def err_mmap_missing_module_unqualified : Error<
+  "no module named '%0' visible from '%1'">;
+def err_mmap_missing_module_qualified : Error<
+  "no module named '%0' in '%1'">;
+def err_mmap_top_level_inferred_submodule : Error<
+  "only submodules may be inferred with wildcard syntax">;
+def err_mmap_inferred_no_umbrella : Error<
+  "inferred submodules require a module with an umbrella">;
+def err_mmap_inferred_redef : Error<
+  "redefinition of inferred submodule">;
+def err_mmap_expected_lbrace_wildcard : Error<
+  "expected '{' to start inferred submodule">;
+def err_mmap_expected_wildcard_member : Error<
+  "expected module export wildcard">;
+def err_mmap_expected_export_wildcard : Error<
+  "only '*' can be exported from an inferred submodule">;
+def err_mmap_explicit_top_level : Error<
+  "'explicit' is not permitted on top-level modules">;
+def err_mmap_nested_submodule_id : Error<
+  "qualified module name can only be used to define modules at the top lev=
el">;
+def err_mmap_expected_feature : Error<"expected a feature name">;
+def err_mmap_expected_attribute : Error<"expected an attribute name">;
+def warn_mmap_unknown_attribute : Warning<"unknown attribute '%0'">,
+  InGroup<IgnoredAttributes>;
+
+def warn_auto_module_import : Warning<
+  "treating #%select{include|import|include_next|__include_macros}0 as an "
+  "import of module '%1'">, InGroup<AutoImport>, DefaultIgnore;
+def warn_uncovered_module_header : Warning<
+  "umbrella header does not include header '%0'">, InGroup<IncompleteUmbre=
lla>;
+
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticParseKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticParseKind=
s.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticParseKind=
s.td	Tue Apr 17 11:51:51 2012 +0300
@@ -23,6 +23,9 @@
 def ext_empty_source_file : Extension<"ISO C forbids an empty source file"=
>;
 def ext_top_level_semi : Extension<
   "extra ';' outside of a function">;
+def warn_cxx98_compat_top_level_semi : Warning<
+  "extra ';' outside of a function is incompatible with C++98">,
+  InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def ext_extra_struct_semi : Extension<
   "extra ';' inside a %0">;
 def ext_extra_ivar_semi : Extension<
@@ -35,9 +38,10 @@
   "complex integer types are an extension">;
 def ext_thread_before : Extension<"'__thread' before 'static'">;
=20
-def ext_empty_struct_union : Extension<"empty %select{struct|union}0 "
-  "(accepted as an extension) has size 0 in C, size 1 in C++">,=20
-  InGroup<CXXCompat>;
+def ext_empty_struct_union : Extension<
+  "empty %select{struct|union}0 is a GNU extension">, InGroup<GNU>;
+def warn_empty_struct_union_compat : Warning<"empty %select{struct|union}0=
 "
+  "has size 0 in C, size 1 in C++">, InGroup<CXXCompat>, DefaultIgnore;
 def error_empty_enum : Error<"use of empty enum">;
 def err_invalid_sign_spec : Error<"'%0' cannot be signed or unsigned">;
 def err_invalid_short_spec : Error<"'short %0' is invalid">;
@@ -49,12 +53,17 @@
 def ext_ident_list_in_param : Extension<
   "type-less parameter names in function declaration">;
 def ext_c99_variable_decl_in_for_loop : Extension<
-  "variable declaration in for loop is a C99-specific feature">;
+  "variable declaration in for loop is a C99-specific feature">, InGroup<C=
99>;
 def ext_c99_compound_literal : Extension<
-  "compound literals are a C99-specific feature">;
+  "compound literals are a C99-specific feature">, InGroup<C99>;
+def ext_c99_flexible_array_member : Extension<
+  "Flexible array members are a C99-specific feature">, InGroup<C99>;
 def ext_enumerator_list_comma : Extension<
   "commas at the end of enumerator lists are a %select{C99|C++11}0-specifi=
c "
   "feature">;
+def warn_cxx98_compat_enumerator_list_comma : Warning<
+  "commas at the end of enumerator lists are incompatible with C++98">,
+  InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def err_enumerator_list_missing_comma : Error<
   "missing ',' between enumerators">;
 def err_enumerator_unnamed_no_def : Error<
@@ -62,16 +71,26 @@
 def ext_ms_enum_fixed_underlying_type : Extension<
   "enumeration types with a fixed underlying type are a Microsoft extensio=
n">,=20
   InGroup<Microsoft>;
+def warn_cxx98_compat_enum_fixed_underlying_type : Warning<
+  "enumeration types with a fixed underlying type are incompatible with C+=
+98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def warn_cxx98_compat_alignof : Warning<
+  "alignof expressions are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
-def ext_c1x_generic_selection : Extension<
-  "generic selections are a C1X-specific feature">, InGroup<C1X>;
+def warn_microsoft_dependent_exists : Warning<
+  "dependent %select{__if_not_exists|__if_exists}0 declarations are ignore=
d">,=20
+  InGroup<DiagGroup<"microsoft-exists">>;
+
+def ext_c11_generic_selection : Extension<
+  "generic selections are a C11-specific feature">, InGroup<C11>;
 def err_duplicate_default_assoc : Error<
   "duplicate default generic association">;
 def note_previous_default_assoc : Note<
   "previous default generic association is here">;
=20
-def ext_c1x_alignas : Extension<
-  "_Alignas is a C1X-specific feature">, InGroup<C1X>;
+def ext_c11_alignas : Extension<
+  "_Alignas is a C11-specific feature">, InGroup<C11>;
=20
 def ext_gnu_indirect_goto : Extension<
   "use of GNU indirect-goto extension">, InGroup<GNU>;
@@ -98,10 +117,10 @@
   InGroup<GNU>;
=20
 // Generic errors.
-def err_parse_error : Error<"parse error">;
 def err_expected_expression : Error<"expected expression">;
 def err_expected_type : Error<"expected a type">;
 def err_expected_external_declaration : Error<"expected external declarati=
on">;
+def err_extraneous_closing_brace : Error<"extraneous closing brace ('}')">;
 def err_expected_ident : Error<"expected identifier">;
 def err_expected_ident_lparen : Error<"expected identifier or '('">;
 def err_expected_ident_lbrace : Error<"expected identifier or '{'">;
@@ -126,17 +145,24 @@
   "function definition declared 'typedef'">;
 def err_iboutletcollection_builtintype : Error<
   "type argument of iboutletcollection attribute cannot be a builtin type"=
>;
-
+def err_iboutletcollection_with_protocol : Error<
+  "invalid argument of iboutletcollection attribute">;
 def err_at_defs_cxx : Error<"@defs is not supported in Objective-C++">;
 def err_at_in_class : Error<"unexpected '@' in member specification">;
=20
 def err_expected_fn_body : Error<
   "expected function body after function declarator">;
+def warn_attribute_on_function_definition : Warning<
+  "GCC does not allow %0 attribute in this position on a function definiti=
on">,=20
+  InGroup<GccCompat>;
+def warn_attribute_no_decl : Warning<
+  "attribute %0 ignored, because it is not attached to a declaration">,=20
+  InGroup<IgnoredAttributes>;
 def err_expected_method_body : Error<"expected method body">;
 def err_invalid_token_after_toplevel_declarator : Error<
   "expected ';' after top level declarator">;
-def err_invalid_equalequal_after_declarator : Error<
-  "invalid '=3D=3D' at end of declaration; did you mean '=3D'?">;
+def err_invalid_token_after_declarator_suggest_equal : Error<
+  "invalid '%0' at end of declaration; did you mean '=3D'?">;
 def err_expected_statement : Error<"expected statement">;
 def err_expected_lparen_after : Error<"expected '(' after '%0'">;
 def err_expected_lparen_after_id : Error<"expected '(' after %0">;
@@ -174,8 +200,8 @@
 def err_address_of_label_outside_fn : Error<
   "use of address-of-label extension outside of a function body">;
 def err_expected_string_literal : Error<"expected string literal">;
-def err_expected_asm_operand : Error<
-  "expected string literal or '[' for asm operand">, CatInlineAsm;
+def err_asm_operand_wide_string_literal : Error<
+  "cannot use %select{unicode|wide}0 string literal in 'asm'">;
 def err_expected_selector_for_method : Error<
   "expected selector for Objective-C method">;
 def err_expected_property_name : Error<"expected property name">;
@@ -188,25 +214,45 @@
   "%0 declared as a reference to a reference">;
 def ext_rvalue_reference : ExtWarn<
   "rvalue references are a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_rvalue_reference : Warning<
+  "rvalue references are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def ext_ref_qualifier : ExtWarn<
   "reference qualifiers on functions are a C++11 extension">, InGroup<CXX1=
1>;
+def warn_cxx98_compat_ref_qualifier : Warning<
+  "reference qualifiers on functions are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def ext_inline_namespace : ExtWarn<
   "inline namespaces are a C++11 feature">, InGroup<CXX11>;
-def err_generalized_initializer_lists : Error<
-  "generalized initializer lists are a C++11 extension unsupported in Clan=
g">;
+def warn_cxx98_compat_inline_namespace : Warning<
+  "inline namespaces are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def ext_generalized_initializer_lists : ExtWarn<
-  "generalized initializer lists are a C++11 extension unsupported in Clan=
g">,
+  "generalized initializer lists are a C++11 extension">,
   InGroup<CXX11>;
+def warn_cxx98_compat_generalized_initializer_lists : Warning<
+  "generalized initializer lists are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def err_init_list_bin_op : Error<"initializer list cannot be used on the "
+  "%select{left|right}0 hand side of operator '%1'">;
+def warn_cxx98_compat_trailing_return_type : Warning<
+  "trailing return types are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def ext_auto_type_specifier : ExtWarn<
   "'auto' type specifier is a C++11 extension">, InGroup<CXX11>;
 def warn_auto_storage_class : Warning<
   "'auto' storage class specifier is redundant and incompatible with C++11=
">,
-  InGroup<CXX11Compat>;
+  InGroup<CXX11Compat>, DefaultIgnore;
 def ext_auto_storage_class : ExtWarn<
   "'auto' storage class specifier is not permitted in C++11, and will not "
-  "be supported in future releases">;
+  "be supported in future releases">, InGroup<DiagGroup<"auto-storage-clas=
s">>;
 def ext_for_range : ExtWarn<
   "range-based for loop is a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_for_range : Warning<
+  "range-based for loop is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def err_for_range_expected_decl : Error<
+  "for range declaration must declare a variable">;
 def err_argument_required_after_attribute : Error<
   "argument required after attribute">;
 def err_missing_param : Error<"expected parameter declarator">;
@@ -214,7 +260,14 @@
   "C requires a comma prior to the ellipsis in a variadic function type">;
 def err_unexpected_typedef_ident : Error<
   "unexpected type name %0: expected identifier">;
+def warn_cxx98_compat_decltype : Warning<
+  "'decltype' type specifier is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def err_unexpected_scope_on_base_decltype : Error<
+  "unexpected namespace scope prior to decltype">;
 def err_expected_class_name : Error<"expected class name">;
+def err_expected_class_name_not_template :=20
+  Error<"'typename' is redundant; base classes are implicitly types">;
 def err_unspecified_vla_size_with_static : Error<
   "'static' may not be used with an unspecified variable length array size=
">;
=20
@@ -228,9 +281,11 @@
   "type name does not allow storage class to be specified">;
 def err_typename_invalid_functionspec : Error<
   "type name does not allow function specifier to be specified">;
+def err_typename_invalid_constexpr : Error<
+  "type name does not allow constexpr specifier to be specified">;
 def err_typename_identifiers_only : Error<
   "typename is allowed for identifiers only">;
- =20
+
 def err_invalid_decl_spec_combination : Error<
   "cannot combine with previous '%0' declaration specifier">;
 def err_invalid_vector_decl_spec_combination : Error<
@@ -255,30 +310,40 @@
   "cannot template a using directive">;
 def err_templated_using_declaration : Error<
   "cannot template a using declaration">;
-def err_expected_ident_in_using : Error<
-  "expected an identifier in using directive">;
 def err_unexected_colon_in_nested_name_spec : Error<
   "unexpected ':' in nested name specifier">;
 def err_bool_redeclaration : Error<
   "redeclaration of C++ built-in type 'bool'">;
-def ext_c1x_static_assert : Extension<
-  "_Static_assert is a C1X-specific feature">, InGroup<C1X>;
+def ext_c11_static_assert : Extension<
+  "_Static_assert is a C11-specific feature">, InGroup<C11>;
+def warn_cxx98_compat_static_assert : Warning<
+  "static_assert declarations are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 /// Objective-C parser diagnostics
 def err_expected_minus_or_plus : Error<
   "method type specifier must start with '-' or '+'">;
 def err_objc_no_attributes_on_category : Error<
   "attributes may not be specified on a category">;
-def err_objc_missing_end : Error<"missing @end">;
+def err_objc_missing_end : Error<"missing '@end'">;
+def note_objc_container_start : Note<
+  "%select{class|protocol|category|class extension|implementation"
+  "|category implementation}0 started here">;
 def warn_objc_protocol_qualifier_missing_id : Warning<
   "protocol qualifiers without 'id' is archaic">;
 def err_objc_unknown_at : Error<"expected an Objective-C directive after '=
@'">;
 def err_illegal_super_cast : Error<
   "cannot cast 'super' (it isn't an expression)">;
+def err_nsnumber_nonliteral_unary : Error<
+  "@%0 must be followed by a number to form an NSNumber object">;
=20
-let CategoryName =3D "Automatic Reference Counting Issue" in {
+let CategoryName =3D "ARC Parse Issue" in {
 def err_arc_bridge_retain : Error<
   "unknown cast annotation __bridge_retain; did you mean __bridge_retained=
?">;
+// To be default mapped to an error later.
+def warn_arc_bridge_cast_nonarc : Warning<
+  "'%0' casts have no effect when not using ARC">,
+  InGroup<DiagGroup<"arc-bridge-casts-disallowed-in-nonarc">>;
 }
  =20
 def err_objc_illegal_visibility_spec : Error<
@@ -303,13 +368,8 @@
 def err_missing_catch_finally : Error<
   "@try statement without a @catch and @finally clause">;
 def err_objc_concat_string : Error<"unexpected token after Objective-C str=
ing">;
-def err_missing_sel_definition : Error<"cannot find definition of 'SEL'">;
-def err_missing_id_definition : Error<"cannot find definition of 'id'">;
-def err_missing_proto_definition : Error<
-  "cannot find definition of 'Protocol'">;
-def err_missing_class_definition : Error<"cannot find definition of 'Class=
'">;
-def err_expected_implementation : Error<
-  "@end must appear in an @implementation context">;
+def err_expected_objc_container : Error<
+  "'@end' must appear in an Objective-C context">;
 def error_property_ivar_decl : Error<
   "property synthesize requires specification of an ivar">;
 def err_synthesized_property_name : Error<
@@ -332,10 +392,16 @@
   "function definition does not declare parameters">;
 def err_expected_lparen_after_type : Error<
   "expected '(' for function-style cast or type construction">;
-def err_expected_equal_after_declarator : Error<
-  "expected '=3D' after declarator">;
+def err_expected_init_in_condition : Error<
+  "variable declaration in condition must have an initializer">;
+def err_expected_init_in_condition_lparen : Error<
+  "variable declaration in condition cannot have a parenthesized initializ=
er">;
 def warn_parens_disambiguated_as_function_decl : Warning<
-  "parentheses were disambiguated as a function declarator">;
+  "parentheses were disambiguated as a function declarator">,
+  InGroup<VexingParse>;
+def warn_dangling_else : Warning<
+  "add explicit braces to avoid dangling else">,
+  InGroup<DanglingElse>;
 def err_expected_member_or_base_name : Error<
   "expected class member or base class name">;
 def err_expected_lbrace_after_base_specifiers : Error<
@@ -344,8 +410,13 @@
   "exception specification of '...' is a Microsoft extension">;
 def err_dynamic_and_noexcept_specification : Error<
   "cannot have both throw() and noexcept() clause on the same function">;
+def warn_cxx98_compat_noexcept_decl : Warning<
+  "noexcept specifications are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_expected_catch : Error<"expected catch">;
 def err_expected_lbrace_or_comma : Error<"expected '{' or ','">;
+def err_expected_rbrace_or_comma : Error<"expected '}' or ','">;
+def err_expected_rsquare_or_comma : Error<"expected ']' or ','">;
 def err_using_namespace_in_class : Error<
   "'using namespace' is not allowed in classes">;
 def err_destructor_tilde_identifier : Error<
@@ -356,13 +427,24 @@
   "unexpected end of default argument expression">;
 def err_parser_impl_limit_overflow : Error<
   "parser recursion limit reached, program too complex">, DefaultFatal;
+def err_misplaced_ellipsis_in_declaration : Error<
+  "'...' must %select{immediately precede declared identifier|"
+  "be innermost component of anonymous pack declaration}0">;
=20
 // C++ derived classes
 def err_dup_virtual : Error<"duplicate 'virtual' in base specifier">;
=20
 // C++ operator overloading
-def err_operator_string_not_empty : Error<
+def err_literal_operator_string_prefix : Error<
+  "string literal after 'operator' cannot have an encoding prefix">;
+def err_literal_operator_string_not_empty : Error<
   "string literal after 'operator' must be '\"\"'">;
+def err_literal_operator_missing_space : Error<
+  "C++11 requires a space between the \"\" and the user-defined suffix in =
a "
+  "literal operator">;
+def warn_cxx98_compat_literal_operator : Warning<
+  "literal operators are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 // Classes.
 def err_anon_type_definition : Error<
@@ -371,16 +453,27 @@
   "'=3D %select{default|delete}0' is a function definition and must occur =
in a "
   "standalone declaration">;
=20
+def warn_cxx98_compat_noexcept_expr : Warning<
+  "noexcept expressions are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def warn_cxx98_compat_nullptr : Warning<
+  "'nullptr' is incompatible with C++98">, InGroup<CXX98Compat>, DefaultIg=
nore;
+
 def warn_cxx98_compat_alignas : Warning<"'alignas' is incompatible with C+=
+98">,
   InGroup<CXX98Compat>, DefaultIgnore;
 def warn_cxx98_compat_attribute : Warning<
   "attributes are incompatible with C++98">,
   InGroup<CXX98Compat>, DefaultIgnore;
-def err_cxx0x_attribute_forbids_arguments : Error<
-  "C++11 attribute '%0' cannot have an argument list">;
-def err_cxx0x_attribute_requires_arguments : Error<
-  "C++1 attribute '%0' must have an argument list">;
+def err_cxx11_attribute_forbids_arguments : Error<
+  "attribute '%0' cannot have an argument list">;
+def err_cxx11_attribute_forbids_ellipsis : Error<
+  "attribute '%0' cannot be used as an attribute pack">;
 def err_attributes_not_allowed : Error<"an attribute list cannot appear he=
re">;
+def err_l_square_l_square_not_attribute : Error<
+  "C++11 only allows consecutive left square brackets when "
+  "introducing an attribute">;
+def err_alignas_pack_exp_unsupported : Error<
+  "pack expansions in alignment specifiers are not supported yet">;
=20
 /// C++ Templates
 def err_expected_template : Error<"expected template">;
@@ -388,23 +481,22 @@
   "unknown template name %0">;
 def err_expected_comma_greater : Error<
   "expected ',' or '>' in template-parameter-list">;
-def err_expected_type_id_after : Error<"expected type-id after '%0'">;
-def err_expected_class_before : Error<"expected 'class' before '%0'">;
+def err_class_on_template_template_param : Error<
+  "template template parameter requires 'class' after the parameter list">;
 def err_template_spec_syntax_non_template : Error<
   "identifier followed by '<' indicates a class template specialization bu=
t "
   "%0 %select{does not refer to a template|refers to a function "
   "template|<unused>|refers to a template template parameter}1">;
 def err_id_after_template_in_nested_name_spec : Error<
   "expected template name after 'template' keyword in nested name specifie=
r">;
-def err_id_after_template_in_typename_spec : Error<
-  "expected template name after 'template' keyword in typename specifier">;
-def err_less_after_template_name_in_nested_name_spec : Error<
-  "expected '<' after 'template %0' in nested name specifier">;
 def err_two_right_angle_brackets_need_space : Error<
   "a space is required between consecutive right angle brackets (use '> >'=
)">;
 def warn_cxx0x_right_shift_in_template_arg : Warning<
   "use of right-shift operator ('>>') in template argument will require "
   "parentheses in C++11">;
+def warn_cxx98_compat_two_right_angle_brackets : Warning<
+  "consecutive right angle brackets are incompatible with C++98 (use '> >'=
)">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_multiple_template_declarators : Error<
     "%select{|a template declaration|an explicit template specialization|"
     "an explicit template instantiation}0 can "
@@ -414,12 +506,20 @@
     "definition is meant to be an explicit specialization, add '<>' after =
the "
     "'template' keyword">;
 def err_enum_template : Error<"enumeration cannot be a template">;
+def err_explicit_instantiation_enum : Error<
+    "enumerations cannot be explicitly instantiated">;
+def err_expected_template_parameter : Error<"expected template parameter">;
=20
 def err_missing_dependent_template_keyword : Error<
   "use 'template' keyword to treat '%0' as a dependent template name">;
 def warn_missing_dependent_template_keyword : ExtWarn<
   "use 'template' keyword to treat '%0' as a dependent template name">;
=20
+def ext_extern_template : Extension<
+  "extern templates are a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_extern_template : Warning<
+  "extern templates are incompatible with C++98">,
+  InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def warn_static_inline_explicit_inst_ignored : Warning<
   "ignoring '%select{static|inline}0' keyword on explicit template "
   "instantiation">;
@@ -457,23 +557,31 @@
   "missing ',' between base or member initializers">;
=20
 // C++ declarations
-def err_friend_decl_defines_class : Error<
+def err_friend_decl_defines_type : Error<
   "cannot define a type in a friend declaration">;
 def err_missing_whitespace_digraph : Error<
   "found '<::' after a "
   "%select{template name|const_cast|dynamic_cast|reinterpret_cast|static_c=
ast}0"
   " which forms the digraph '<:' (aka '[') and a ':', did you mean '< ::'?=
">;
=20
-def warn_deleted_function_accepted_as_extension: ExtWarn<
-  "deleted function definition accepted as a C++11 extension">, InGroup<CX=
X11>;
-def warn_defaulted_function_accepted_as_extension: ExtWarn<
-  "defaulted function definition accepted as a C++11 extension">,
-  InGroup<CXX11>;
+def ext_deleted_function : ExtWarn<
+  "deleted function definitions are a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_deleted_function : Warning<
+  "deleted function definitions are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def ext_defaulted_function : ExtWarn<
+  "defaulted function definitions are a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_defaulted_function : Warning<
+  "defaulted function definitions are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 // C++11 in-class member initialization
-def warn_nonstatic_member_init_accepted_as_extension: ExtWarn<
-  "in-class initialization of non-static data member accepted as a C++11 e=
xtension">,
+def ext_nonstatic_member_init : ExtWarn<
+  "in-class initialization of non-static data member is a C++11 extension"=
>,
   InGroup<CXX11>;
+def warn_cxx98_compat_nonstatic_member_init : Warning<
+  "in-class initialization of non-static data members is incompatible with=
 C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_bitfield_member_init: Error<
   "bitfield member cannot have an in-class initializer">;
 def err_incomplete_array_member_init: Error<
@@ -481,23 +589,30 @@
=20
 // C++11 alias-declaration
 def ext_alias_declaration : ExtWarn<
-  "alias declarations accepted as a C++11 extension">, InGroup<CXX11>;
+  "alias declarations are a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_alias_declaration : Warning<
+  "alias declarations are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_alias_declaration_not_identifier : Error<
   "name defined in alias declaration must be an identifier">;
 def err_alias_declaration_specialization : Error<
   "%select{partial specialization|explicit specialization|explicit instant=
iation}0 of alias templates is not permitted">;
    =20
 // C++11 override control
-def ext_override_control_keyword : Extension<
-  "'%0' keyword accepted as a C++11 extension">, InGroup<CXX11>;
+def ext_override_control_keyword : ExtWarn<
+  "'%0' keyword is a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_override_control_keyword : Warning<
+  "'%0' keyword is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 def err_duplicate_virt_specifier : Error<
   "class member already marked '%0'">;
-def err_duplicate_class_virt_specifier : Error<
-  "class already marked '%0'">;
=20
 def err_scoped_enum_missing_identifier : Error<
   "scoped enumeration requires a name">;
+def warn_cxx98_compat_scoped_enum : Warning<
+  "scoped enumerations are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 def err_expected_parameter_pack : Error<
   "expected the name of a parameter pack">;
@@ -514,6 +629,11 @@
 def err_expected_capture : Error<
   "expected variable name or 'this' in lambda capture list">;
 def err_expected_lambda_body : Error<"expected body of lambda expression">;
+def warn_cxx98_compat_lambda : Warning<
+  "lambda expressions are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def err_lambda_missing_parens : Error<
+  "lambda requires '()' before %select{'mutable'|return type}0">;
=20
 // Availability attribute
 def err_expected_version : Error<
@@ -554,8 +674,6 @@
 // - #pragma pack
 def warn_pragma_pack_invalid_action : Warning<
   "unknown action for '#pragma pack' - ignored">;
-def warn_pragma_pack_invalid_constant : Warning<
-  "invalid constant for '#pragma pack', expected %0 - ignored">;
 def warn_pragma_pack_malformed : Warning<
   "expected integer or identifier in '#pragma pack' - ignored">;
 // - #pragma unused
@@ -592,7 +710,7 @@
=20
 let CategoryName =3D "Modules Issue" in {
 def err_module_expected_ident : Error<
-  "expected a module name after '__import_module__'">;
+  "expected a module name after module import">;
 def err_module_expected_semi : Error<
   "expected a semicolon name after module name">;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/DiagnosticSemaKinds.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds=
.td	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/DiagnosticSemaKinds=
.td	Tue Apr 17 11:51:51 2012 +0300
@@ -16,10 +16,38 @@
=20
 // Constant expressions
 def err_expr_not_ice : Error<
-  "expression is not an integer constant expression">;
+  "expression is not an %select{integer|integral}0 constant expression">;
 def ext_expr_not_ice : Extension<
-  "expression is not integer constant expression "
-  "(but is allowed as an extension)">;
+  "expression is not an %select{integer|integral}0 constant expression; "
+  "folding it to a constant is a GNU extension">, InGroup<GNU>;
+def err_typecheck_converted_constant_expression : Error<
+  "value of type %0 is not implicitly convertible to %1">;
+def err_typecheck_converted_constant_expression_disallowed : Error<
+  "conversion from %0 to %1 is not allowed in a converted constant express=
ion">;
+def err_expr_not_cce : Error<
+  "%select{case value|enumerator value|non-type template argument}0 "
+  "is not a constant expression">;
+def err_cce_narrowing : ExtWarn<
+  "%select{case value|enumerator value|non-type template argument}0 "
+  "%select{cannot be narrowed from type %2 to %3|"
+  "evaluates to %2, which cannot be narrowed to type %3}1">,
+  InGroup<CXX11Narrowing>, DefaultError;
+def err_cce_narrowing_sfinae : Error<
+  "%select{case value|enumerator value|non-type template argument}0 "
+  "%select{cannot be narrowed from type %2 to %3|"
+  "evaluates to %2, which cannot be narrowed to type %3}1">;
+def err_ice_not_integral : Error<
+  "integral constant expression must have integral or unscoped enumeration=
 "
+  "type, not %0">;
+def err_ice_incomplete_type : Error<
+  "integral constant expression has incomplete class type %0">;
+def err_ice_explicit_conversion : Error<
+  "integral constant expression requires explicit conversion from %0 to %1=
">;
+def note_ice_conversion_here : Note<
+  "conversion to %select{integral|enumeration}0 type %1 declared here">;
+def err_ice_ambiguous_conversion : Error<
+  "ambiguous conversion from type %0 to an integral or unscoped "
+  "enumeration type">;
=20
 // Semantic analysis of constant literals.
 def ext_predef_outside_function : Warning<
@@ -35,8 +63,7 @@
   "double precision constant requires cl_khr_fp64, casting to single preci=
sion">;
=20
 // C99 variable-length arrays
-def ext_vla : Extension<
-  "variable length arrays are a C99 feature, accepted as an extension">,
+def ext_vla : Extension<"variable length arrays are a C99 feature">,
   InGroup<VLA>;
 def err_vla_non_pod : Error<"variable length array of non-POD element type=
 %0">;
 def err_vla_in_sfinae : Error<
@@ -63,8 +90,6 @@
 // C99 Designated Initializers
 def ext_designated_init : Extension<
   "designated initializers are a C99 feature">;
-def ext_designated_init_cxx : Extension<
-  "designated initializers are a C99 feature, accepted in C++ as an extens=
ion">;
 def err_array_designator_negative : Error<
   "array designator value '%0' is negative">;
 def err_array_designator_empty_range : Error<
@@ -100,8 +125,6 @@
   "flexible array initialization is a GNU extension">, InGroup<GNU>;
=20
 // Declarations.
-def ext_anon_param_requires_type_specifier : Extension<
-  "type specifier required for unnamed parameter, defaults to int">;
 def err_bad_variable_name : Error<
   "%0 cannot be the name of a variable or data member">;
 def err_bad_parameter_name : Error<
@@ -114,7 +137,20 @@
 def warn_unused_exception_param : Warning<"unused exception parameter %0">,
   InGroup<UnusedExceptionParameter>, DefaultIgnore;
 def warn_decl_in_param_list : Warning<
-  "declaration of %0 will not be visible outside of this function">;
+  "declaration of %0 will not be visible outside of this function">,
+  InGroup<Visibility>;
+def warn_redefinition_in_param_list : Warning<
+  "redefinition of %0 will not be visible outside of this function">,
+  InGroup<Visibility>;
+def warn_empty_parens_are_function_decl : Warning<
+  "empty parentheses interpreted as a function declaration">,
+  InGroup<VexingParse>;
+def note_empty_parens_function_call : Note<
+  "change this ',' to a ';' to call %0">;
+def note_empty_parens_default_ctor : Note<
+  "remove parentheses to declare a variable">;
+def note_empty_parens_zero_initialize : Note<
+  "replace parentheses with an initializer to declare a variable">;
 def warn_unused_function : Warning<"unused function %0">,
   InGroup<UnusedFunction>, DefaultIgnore;
 def warn_unused_member_function : Warning<"unused member function %0">,
@@ -134,13 +170,16 @@
 def warn_return_value_size: Warning<
   "return value of %0 is a large (%1 bytes) pass-by-value object; "
   "pass it by reference instead ?">, InGroup<LargeByValueCopy>;
-
+def warn_return_value_udt: Warning<
+  "%0 has C-linkage specified, but returns user-defined type %1 which is "
+  "incompatible with C">, InGroup<ReturnTypeCLinkage>;
 def warn_implicit_function_decl : Warning<
   "implicit declaration of function %0">,
   InGroup<ImplicitFunctionDeclare>, DefaultIgnore;
 def ext_implicit_function_decl : ExtWarn<
   "implicit declaration of function %0 is invalid in C99">,
   InGroup<ImplicitFunctionDeclare>;
+def note_function_suggestion : Note<"did you mean %0?">;
=20
 def err_ellipsis_first_arg : Error<
   "ISO C requires a named argument before '...'">;
@@ -192,6 +231,9 @@
   "using declaration can not refer to namespace">;
 def err_using_decl_constructor : Error<
   "using declaration can not refer to a constructor">;
+def warn_cxx98_compat_using_decl_constructor : Warning<
+  "inherited constructors are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_using_decl_destructor : Error<
   "using declaration can not refer to a destructor">;
 def err_using_decl_template_id : Error<
@@ -247,7 +289,7 @@
=20
 /// Built-in functions.
 def ext_implicit_lib_function_decl : ExtWarn<
-  "implicitly declaring C library function '%0' with type %1">;
+  "implicitly declaring library function '%0' with type %1">;
 def note_please_include_header : Note<
   "please include the header <%0> or explicitly provide a "
   "declaration for '%1'">;
@@ -269,7 +311,8 @@
 def err_builtin_definition : Error<"definition of builtin function %0">;
 def err_types_compatible_p_in_cplusplus : Error<
   "__builtin_types_compatible_p is not valid in C++">;
-def warn_builtin_unknown : Warning<"use of unknown builtin %0">, DefaultEr=
ror;
+def warn_builtin_unknown : Warning<"use of unknown builtin %0">,
+  InGroup<ImplicitFunctionDeclare>, DefaultError;
 def warn_dyn_class_memaccess : Warning<
   "%select{destination for|source of|first operand of|second operand of}0 =
this "
   "%1 call is a pointer to dynamic class %2; vtable pointer will be "
@@ -292,6 +335,15 @@
   InGroup<DiagGroup<"strlcpy-strlcat-size">>;
 def note_strlcpycat_wrong_size : Note<
   "change size argument to be the size of the destination">;
+ =20
+def warn_strncat_large_size : Warning<
+  "the value of the size argument in 'strncat' is too large, might lead to=
 a "=20
+  "buffer overflow">, InGroup<StrncatSize>, DefaultIgnore;
+def warn_strncat_src_size : Warning<"size argument in 'strncat' call appea=
rs "=20
+  "to be size of the source">, InGroup<StrncatSize>, DefaultIgnore;
+def note_strncat_wrong_size : Note<
+  "change the argument to be the free space in the destination buffer minu=
s "=20
+  "the terminating null byte">;
=20
 /// main()
 // static/inline main() are not errors in C, just in C++.
@@ -299,8 +351,12 @@
     InGroup<Main>;
 def err_static_main : Error<"'main' is not allowed to be declared static">;
 def err_inline_main : Error<"'main' is not allowed to be declared inline">;
+def err_constexpr_main : Error<
+  "'main' is not allowed to be declared constexpr">;
 def err_main_template_decl : Error<"'main' cannot be a template">;
 def err_main_returns_nonint : Error<"'main' must return 'int'">;
+def ext_main_returns_nonint : ExtWarn<"return type of 'main' is not 'int'"=
>,
+    InGroup<MainReturnType>;
 def err_main_surplus_args : Error<"too many parameters (%0) for 'main': "
     "must be 0, 2, or 3">;
 def warn_main_one_arg : Warning<"only one parameter on 'main' declaration"=
>,
@@ -339,8 +395,14 @@
   "undeclared variable %0 used as an argument for '#pragma unused'">;
 def warn_pragma_unused_expected_var_arg : Warning<
   "only variables can be arguments to '#pragma unused'">;
-def err_unsupported_pragma_weak : Error<
-  "using '#pragma weak' to refer to an undeclared identifier is not yet su=
pported">;
+def err_pragma_push_visibility_mismatch : Error<
+  "#pragma visibility push with no matching #pragma visibility pop">;
+def note_surrounding_namespace_ends_here : Note<
+  "surrounding namespace with visibility attribute ends here">;
+def err_pragma_pop_visibility_mismatch : Error<
+  "#pragma visibility pop with no matching #pragma visibility push">;
+def note_surrounding_namespace_starts_here : Note<
+  "surrounding namespace with visibility attribute starts here">;
=20
 /// Objective-C parser diagnostics
 def err_duplicate_class_def : Error<
@@ -370,12 +432,25 @@
 def warn_property_types_are_incompatible : Warning<
   "property type %0 is incompatible with type %1 inherited from %2">;
 def err_undef_interface : Error<"cannot find interface declaration for %0"=
>;
+def err_category_forward_interface : Error<
+  "cannot define %select{category|class extension}0 for undefined class %1=
">;
 def err_class_extension_after_impl : Error<
   "cannot declare class extension for %0 after class implementation">;
 def note_implementation_declared : Note<
   "class implementation is declared here">;
 def note_class_declared : Note<
   "class is declared here">;
+def note_receiver_is_id : Note<
+  "receiver is treated with 'id' type for purpose of method lookup">;
+def note_suppressed_class_declare : Note<
+  "class with specified objc_requires_property_definitions attribute is de=
clared here">;
+def err_objc_root_class_subclass : Error<
+  "objc_root_class attribute may only be specified on a root class declara=
tion">;
+def warn_objc_root_class_missing : Warning<
+	"class %0 defined without specifying a base class">,
+  InGroup<ObjCRootClass>, DefaultIgnore;
+def note_objc_needs_superclass : Note<
+  "add a super class to fix this problem">;
 def warn_dup_category_def : Warning<
   "duplicate definition of category %1 on interface %0">;
 def err_conflicting_super_class : Error<"conflicting super class name %0">;
@@ -479,11 +554,13 @@
   "multiple methods named %0 found">, InGroup<StrictSelector>, DefaultIgno=
re;
 def warn_accessor_property_type_mismatch : Warning<
   "type of property %0 does not match type of accessor %1">;
-def note_declared_at : Note<"declared here">;
-def note_method_declared_at : Note<"method declared here">;
+def not_conv_function_declared_at : Note<"type conversion function declare=
d here">;
+def note_method_declared_at : Note<"method %0 declared here">;
 def err_setter_type_void : Error<"type of setter must be void">;
 def err_duplicate_method_decl : Error<"duplicate declaration of method %0"=
>;
-def err_missing_atend : Error<"'@end' is missing in implementation context=
">;
+def warn_duplicate_method_decl :=20
+  Warning<"multiple declarations of method %0 found and ignored">,=20
+  InGroup<MethodDuplicate>, DefaultIgnore;
 def err_objc_var_decl_inclass :=20
     Error<"cannot declare variable inside @interface or @protocol">;
 def error_missing_method_context : Error<
@@ -495,6 +572,10 @@
 def warn_objc_property_no_assignment_attribute : Warning<
   "no 'assign', 'retain', or 'copy' attribute is specified - "
   "'assign' is assumed">;
+def warn_objc_isa_use : Warning<
+  "direct access to objective-c's isa is deprecated "
+  "in favor of object_setClass() and object_getClass()">,
+  InGroup<DiagGroup<"deprecated-objc-isa-usage">>;
 def warn_objc_property_default_assign_on_object : Warning<
   "default property attribute 'assign' not appropriate for non-gc object">;
 def warn_property_attr_mismatch : Warning<
@@ -505,19 +586,26 @@
 def warn_objc_property_retain_of_block : Warning<
     "retain'ed block property does not copy the block "
     "- use copy attribute instead">, InGroup<ObjCRetainBlockProperty>;
+def warn_objc_readonly_property_has_setter : Warning<
+    "setter cannot be specified for a readonly property">,
+    InGroup<ObjCReadonlyPropertyHasSetter>;
 def warn_atomic_property_rule : Warning<
   "writable atomic property %0 cannot pair a synthesized %select{getter|se=
tter}1 "
   "with a user defined %select{getter|setter}2">,
   InGroup<DiagGroup<"atomic-property-with-user-defined-accessor">>;
 def note_atomic_property_fixup_suggest : Note<"setter and getter must both=
 be "
   "synthesized, or both be user defined,or the property must be nonatomic"=
>;
-def warn_atomic_property_nontrivial_assign_op : Warning<
-  "atomic property of type %0 synthesizing setter using non-trivial assign=
ment"
-  " operator">, InGroup<DiagGroup<"objc-property-atomic-setter-synthesis">=
>;
+def err_atomic_property_nontrivial_assign_op : Error<
+  "atomic property of reference type %0 cannot have non-trivial assignment"
+  " operator">;
 def warn_owning_getter_rule : Warning<
   "property's synthesized getter follows Cocoa naming"
   " convention for returning 'owned' objects">,
   InGroup<DiagGroup<"objc-property-matches-cocoa-ownership-rule">>;
+def warn_auto_synthesizing_protocol_property :Warning<
+  "auto property synthesis will not synthesize property"
+  " declared in a protocol">,
+  InGroup<DiagGroup<"objc-protocol-property-synthesis">>;
 def warn_property_getter_owning_mismatch : Warning<
   "property declared as returning non-retained objects"
   "; getter returning retained objects">;
@@ -531,9 +619,9 @@
 def err_use_continuation_class : Error<
   "illegal redeclaration of property in continuation class %0"
   " (attribute must be 'readwrite', while its primary must be 'readonly')"=
>;
-def warn_type_mismatch_continuation_class : Warning<
+def err_type_mismatch_continuation_class : Error<
   "type of property %0 in continuation class does not match "
-  "property type in primary class">, InGroup<ObjCContinuationPropertyType>;
+  "property type in primary class">;
 def err_use_continuation_class_redeclaration_readwrite : Error<
   "illegal redeclaration of 'readwrite' property in continuation class %0"
   " (perhaps you intended this to be a 'readwrite' redeclaration of a "
@@ -571,6 +659,9 @@
   InGroup<DiagGroup<"arc-performSelector-leaks">>;
 def err_gc_weak_property_strong_type : Error<
   "weak attribute declared on a __strong type property in GC mode">;
+def warn_receiver_is_weak : Warning <
+  "weak receiver may be unpredictably null in ARC mode">,
+  InGroup<DiagGroup<"receiver-is-weak">>, DefaultIgnore;
=20
 def error_synthesized_ivar_yet_not_supported : Error<
   "instance variable synthesis not yet supported"
@@ -608,12 +699,12 @@
 def warn_unimplemented_selector:  Warning<
   "unimplemented selector %0">, InGroup<Selector>, DefaultIgnore;
 def warn_unimplemented_protocol_method : Warning<
-  "method in protocol not implemented">, InGroup<Protocol>;
+  "method %0 in protocol not implemented">, InGroup<Protocol>;
=20
 // C++ declarations
 def err_static_assert_expression_is_not_constant : Error<
   "static_assert expression is not an integral constant expression">;
-def err_static_assert_failed : Error<"static_assert failed \"%0\"">;
+def err_static_assert_failed : Error<"static_assert failed %0">;
=20
 def warn_inline_namespace_reopened_noninline : Warning<
   "inline namespace cannot be re-opened as a non-inline namespace">;
@@ -625,13 +716,25 @@
   "friends can only be classes or functions">;
 def ext_enum_friend : ExtWarn<
   "enumeration type %0 cannot be a friend">;
+def warn_cxx98_compat_enum_friend : Warning<
+  "befriending enumeration type %0 is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def ext_nonclass_type_friend : ExtWarn<
   "non-class friend type %0 is a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_nonclass_type_friend : Warning<
+  "non-class friend type %0 is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_friend_is_member : Error<
   "friends cannot be members of the declaring class">;
+def warn_cxx98_compat_friend_is_member : Warning<
+  "friend declaration naming a member of the declaring class is incompatib=
le "
+  "with C++98">, InGroup<CXX98Compat>, DefaultIgnore;
 def ext_unelaborated_friend_type : ExtWarn<
-  "specify '%select{struct|union|class|enum}0' to befriend %1; accepted "
-  "as a C++11 extension">, InGroup<CXX11>;
+  "unelaborated friend declaration is a C++11 extension; specify "
+  "'%select{struct|union|class|enum}0' to befriend %1">, InGroup<CXX11>;
+def warn_cxx98_compat_unelaborated_friend_type : Warning<
+  "befriending %1 without '%select{struct|union|class|enum}0' keyword is "
+  "incompatible with C++98">, InGroup<CXX98Compat>, DefaultIgnore;
 def err_qualified_friend_not_found : Error<
   "no function named %0 with type %1 was found in the specified scope">;
 def err_introducing_special_friend : Error<
@@ -681,6 +784,10 @@
   "%0 has no out-of-line virtual method definitions; its vtable will be "
   "emitted in every translation unit">,
   InGroup<DiagGroup<"weak-vtables">>, DefaultIgnore;
+def warn_weak_template_vtable : Warning<
+  "explicit template instantiation %0 will emit a vtable in every "
+  "translation unit">,
+  InGroup<DiagGroup<"weak-template-vtables">>, DefaultIgnore;
=20
 def ext_using_undefined_std : ExtWarn<
   "using directive refers to implicitly-defined namespace 'std'">;
@@ -720,9 +827,9 @@
   "%0 redeclared with '%1' access">;
 def err_access : Error<
   "%1 is a %select{private|protected}0 member of %3">, AccessControl;
-def war_ms_using_declaration_inaccessible : ExtWarn<
-  "using declaration refers to inaccessible member '%0', which refers "
-  "to accessible member '%1', accepted for Microsoft compatibility">,
+def ext_ms_using_declaration_inaccessible : ExtWarn<
+  "using declaration referring to inaccessible member '%0' (which refers "
+  "to accessible member '%1') is a Microsoft compatibility extension">,
     AccessControl, InGroup<Microsoft>;
 def err_access_ctor : Error<
   "calling a %select{private|protected}0 constructor of class %2">,=20
@@ -744,9 +851,6 @@
   "%select{default |copy |move |*ERROR* |*ERROR* |*ERROR* |}1constructor">,
   AccessControl;
=20
-def err_access_ctor_field :
-    Error<"field of type %1 has %select{private|protected}2 constructor">,
-    AccessControl;
 def err_access_dtor : Error<
   "calling a %select{private|protected}1 destructor of class %0">,=20
   AccessControl;
@@ -769,36 +873,27 @@
 def err_access_dtor_var :
     Error<"variable of type %1 has %select{private|protected}2 destructor"=
>,
     AccessControl;
-def err_access_assign_field :
-    Error<"field of type %1 has %select{private|protected}2 copy assignmen=
t"
-          " operator">,
-    AccessControl;
-def err_access_assign_base :
-    Error<"base class %0 has %select{private|protected}1 copy assignment"
-          " operator">,
-    AccessControl;
-def err_access_copy_field :
-    Error<"field of type %1 has %select{private|protected}2 copy construct=
or">,
-    AccessControl;
-def err_access_copy_base :
-    Error<"base class %0 has %select{private|protected}1 copy constructor"=
>,
-    AccessControl;
 def err_access_dtor_ivar :
     Error<"instance variable of type %0 has %select{private|protected}1 "
           "destructor">,
     AccessControl;
 def note_previous_access_declaration : Note<
   "previously declared '%1' here">;
-def err_access_outside_class : Error<
-  "access to %select{private|protected}0 member outside any class context"=
>,
-  AccessControl;
 def note_access_natural : Note<
   "%select{|implicitly }1declared %select{private|protected}0 here">;
 def note_access_constrained_by_path : Note<
   "constrained by %select{|implicitly }1%select{private|protected}0"
   " inheritance here">;
-def note_access_protected_restricted : Note<
-  "object type %select{|%1 }0must derive from context type %2">;
+def note_access_protected_restricted_noobject : Note<
+  "must name member using the type of the current context %0">;
+def note_access_protected_restricted_ctordtor : Note<
+  "protected %select{constructor|destructor}0 can only be used to "
+  "%select{construct|destroy}0 a base class subobject">;
+def note_access_protected_restricted_object : Note<
+  "can only access this member on an object of type %0">;
+def warn_cxx98_compat_sfinae_access_control : Warning<
+  "substitution failure due to access control is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore, NoSFINAE;
  =20
 // C++ name lookup
 def err_incomplete_nested_name_spec : Error<
@@ -821,6 +916,9 @@
   "member access into incomplete type %0">;
 def err_incomplete_type : Error<
   "incomplete type %0 where a complete type is required">;
+def warn_cxx98_compat_enum_nested_name_spec : Warning<
+  "enumeration type in nested name specifier is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
  =20
 // C++ class members
 def err_storageclass_invalid_for_member : Error<
@@ -885,6 +983,11 @@
   "%select{anonymous struct|union}0 member %1 has a non-trivial "
   "%select{constructor|copy constructor|move constructor|copy assignment "
   "operator|move assignment operator|destructor}2">;
+def warn_cxx98_compat_nontrivial_union_or_anon_struct_member : Warning<
+  "%select{anonymous struct|union}0 member %1 with a non-trivial "
+  "%select{constructor|copy constructor|move constructor|copy assignment "
+  "operator|move assignment operator|destructor}2 is incompatible with C++=
98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def note_nontrivial_has_virtual : Note<
   "because type %0 has a virtual %select{member function|base class}1">;
 def note_nontrivial_has_nontrivial : Note<
@@ -895,8 +998,13 @@
   "because type %0 has a user-declared %select{constructor|copy constructo=
r|"
   "move constructor|copy assignment operator|move assignment operator|"
   "destructor}1">;
-def err_static_data_member_not_allowed_in_union_or_anon_struct : Error<
-  "static data member %0 not allowed in %select{anonymous struct|union}1">=
;=20
+def err_static_data_member_not_allowed_in_anon_struct : Error<
+  "static data member %0 not allowed in anonymous struct">;
+def ext_static_data_member_in_union : ExtWarn<
+  "static data member %0 in union is a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_static_data_member_in_union : Warning<
+  "static data member %0 in union is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_union_member_of_reference_type : Error<
   "union member %0 has reference type %1">;
 def ext_anonymous_struct_union_qualified : Extension<
@@ -983,17 +1091,22 @@
   "cannot initialize %select{a variable|a parameter|return object|an "
   "exception object|a member subobject|an array element|a new value|a valu=
e|a "
   "base class|a constructor delegation|a vector element}0 of type %1 with =
an "
-  "%select{rvalue|lvalue}2 of type %3">;
+  "%select{rvalue|lvalue}2 of type %3"
+  "%select{|: different classes (%5 vs %6)"
+  "|: different number of parameters (%5 vs %6)"
+  "|: type mismatch at %ordinal5 parameter (%6 vs %7)"
+  "|: different return type (%5 vs %6)"
+  "|: different qualifiers ("
+  "%select{none|const|restrict|const and restrict|volatile|const and volat=
ile|"
+  "volatile and restrict|const, volatile, and restrict}5 vs "
+  "%select{none|const|restrict|const and restrict|volatile|const and volat=
ile|"
+  "volatile and restrict|const, volatile, and restrict}6)}4">;
=20
 def err_lvalue_to_rvalue_ref : Error<"rvalue reference to type %0 cannot b=
ind "
   "to lvalue of type %1">;
-def err_invalid_initialization : Error<
-"invalid initialization of reference of type %0 from expression of type %1=
">;
-def err_lvalue_to_rvalue_ambig_ref : Error<"rvalue reference cannot bind t=
o lvalue "
-                                           "due to multiple conversion fun=
ctions">;
-def err_not_reference_to_const_init : Error<
-  "%select{non-const|volatile}0 lvalue reference to type %1 cannot be "
-  "initialized with a %select{value|temporary}2 of type %3">;
+def err_lvalue_reference_bind_to_initlist : Error<
+  "%select{non-const|volatile}0 lvalue reference to type %1 cannot bind to=
 an "
+  "initializer list temporary">;
 def err_lvalue_reference_bind_to_temporary : Error<
   "%select{non-const|volatile}0 lvalue reference to type %1 cannot bind to=
 a "
   "temporary of type %2">;
@@ -1015,17 +1128,12 @@
     "%select{const|restrict|const or restrict|volatile|const or volatile|"
     "volatile or restrict|const, volatile, or restrict}2">;
=20
-def err_reference_init_drops_quals : Error<
-  "initialization of reference to type %0 with a %select{value|temporary}1=
 of type %2 drops "
-  "qualifiers">;
 def err_reference_bind_to_bitfield : Error<
   "%select{non-const|volatile}0 reference cannot bind to bit-field %1">;
 def err_reference_bind_to_vector_element : Error<
   "%select{non-const|volatile}0 reference cannot bind to vector element">;
 def err_reference_var_requires_init : Error<
   "declaration of reference variable %0 requires an initializer">;
-def err_const_var_requires_init : Error<
-  "declaration of const variable '%0' requires an initializer">;
 def err_reference_without_init : Error<
   "reference to type %0 requires an initializer">;
 def err_reference_has_multiple_inits : Error<
@@ -1055,6 +1163,11 @@
 def warn_maybe_uninit_var_captured_by_block : Warning<
   "variable %0 may be uninitialized when captured by block">,
   InGroup<UninitializedMaybe>, DefaultIgnore;
+def warn_uninit_byref_blockvar_captured_by_block : Warning<
+  "block pointer variable %0 is uninitialized when captured by block">,
+  InGroup<Uninitialized>, DefaultIgnore;
+def note_block_var_fixit_add_initialization : Note<
+  "maybe you meant to use __block %0">;
 def note_var_fixit_add_initialization : Note<
   "initialize the variable %0 to silence this warning">;
 def err_init_incomplete_type : Error<"initialization of incomplete type %0=
">;
@@ -1063,32 +1176,47 @@
   "no viable constructor %select{copying variable|copying parameter|"
   "returning object|throwing object|copying member subobject|copying array=
 "
   "element|allocating object|copying temporary|initializing base subobject=
|"
-  "initializing vector element}0 of type %1">;
+  "initializing vector element|capturing value}0 of type %1">;
 def ext_rvalue_to_reference_temp_copy_no_viable : ExtWarn<
   "no viable constructor %select{copying variable|copying parameter|"
   "returning object|throwing object|copying member subobject|copying array=
 "
   "element|allocating object|copying temporary|initializing base subobject=
|"
-  "initializing vector element}0 of type %1; C++98 requires a copy "
+  "initializing vector element|capturing value}0 of type %1; C++98 require=
s a copy "
   "constructor when binding a reference to a temporary">,
   InGroup<BindToTemporaryCopy>;
 def err_temp_copy_ambiguous : Error<
   "ambiguous constructor call when %select{copying variable|copying "
   "parameter|returning object|throwing object|copying member subobject|cop=
ying "
   "array element|allocating object|copying temporary|initializing base sub=
object|"
-  "initializing vector element}0 of type %1">;
+  "initializing vector element|capturing value}0 of type %1">;
 def err_temp_copy_deleted : Error<
   "%select{copying variable|copying parameter|returning object|throwing "
   "object|copying member subobject|copying array element|allocating object=
|"
-  "copying temporary|initializing base subobject|initializing vector eleme=
nt}0 "
-  "of type %1 invokes deleted constructor">;
+  "copying temporary|initializing base subobject|initializing vector eleme=
nt|"
+  "capturing value}0 of type %1 invokes deleted constructor">;
 def err_temp_copy_incomplete : Error<
   "copying a temporary object of incomplete type %0">;
+def warn_cxx98_compat_temp_copy : Warning<
+  "%select{copying variable|copying parameter|returning object|throwing "
+  "object|copying member subobject|copying array element|allocating object=
|"
+  "copying temporary|initializing base subobject|initializing vector eleme=
nt}1 "
+  "of type %2 when binding a reference to a temporary would %select{invoke=
 "
+  "an inaccessible constructor|find no viable constructor|find ambiguous "
+  "constructors|invoke a deleted constructor}0 in C++98">,
+  InGroup<CXX98CompatBindToTemporaryCopy>, DefaultIgnore;
+def err_selected_explicit_constructor : Error<
+  "chosen constructor is explicit in copy-initialization">;
+def note_constructor_declared_here : Note<
+  "constructor declared here">;
=20
 // C++11 decltype
-def err_cannot_determine_declared_type_of_overloaded_function : Error<
-    "cannot determine the type of an overloaded function">;
+def err_decltype_in_declarator : Error<
+    "'decltype' cannot be used to name a declaration">;
    =20
 // C++11 auto
+def warn_cxx98_compat_auto_type_specifier : Warning<
+  "'auto' type specifier is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_auto_variable_cannot_appear_in_own_initializer : Error<
   "variable %0 declared with 'auto' type cannot appear in its own initiali=
zer">;
 def err_illegal_decl_array_of_auto : Error<
@@ -1104,6 +1232,10 @@
   "declaration of variable %0 with type %1 requires an initializer">;
 def err_auto_new_requires_ctor_arg : Error<
   "new expression for type %0 requires a constructor argument">;
+def err_auto_new_requires_parens : Error<
+  "new expression for type %0 cannot use list-initialization">;
+def err_auto_var_init_no_expression : Error<
+  "initializer for variable %0 with type %1 is empty">;
 def err_auto_var_init_multiple_expressions : Error<
   "initializer for variable %0 with type %1 contains multiple expressions"=
>;
 def err_auto_new_ctor_multiple_expressions : Error<
@@ -1116,10 +1248,21 @@
   "trailing return type may not be nested within parentheses">;
 def err_auto_var_deduction_failure : Error<
   "variable %0 with type %1 has incompatible initializer of type %2">;
+def err_auto_var_deduction_failure_from_init_list : Error<
+  "cannot deduce actual type for variable %0 with type %1 from initializer=
 list">;
 def err_auto_new_deduction_failure : Error<
   "new expression for type %0 has incompatible constructor argument of typ=
e %1">;
 def err_auto_different_deductions : Error<
   "'auto' deduced as %0 in declaration of %1 and deduced as %2 in declarat=
ion of %3">;
+def err_implied_std_initializer_list_not_found : Error<
+  "cannot deduce type of initializer list because std::initializer_list wa=
s "
+  "not found; include <initializer_list>">;
+def err_malformed_std_initializer_list : Error<
+  "std::initializer_list must be a class template with a single type param=
eter">;
+def warn_dangling_std_initializer_list : Warning<
+  "array backing the initializer list will be destroyed at the end of "
+  "%select{the full-expression|the constructor}0">,
+  InGroup<DiagGroup<"dangling-initializer-list">>;
=20
 // C++11 override control
 def override_keyword_only_allowed_on_virtual_member_functions : Error<
@@ -1132,11 +1275,9 @@
 // C++11 attributes
 def err_repeat_attribute : Error<"'%0' attribute cannot be repeated">;
=20
-// C++11 [[final]]
+// C++11 final
 def err_final_function_overridden : Error<
   "declaration of %0 overrides a 'final' function">;
-def err_final_base : Error<
-  "derivation from 'final' %0">;
=20
 // C++11 scoped enumerations
 def err_enum_invalid_underlying : Error<
@@ -1154,14 +1295,18 @@
   "enumeration previously declared with %select{non|}0fixed underlying typ=
e">;
 def err_enum_redeclare_scoped_mismatch : Error<
   "enumeration previously declared as %select{un|}0scoped">;
+def err_enum_class_reference : Error<
+  "reference to %select{|scoped }0enumeration must use 'enum' "
+  "not 'enum class'">;
 def err_only_enums_have_underlying_types : Error<
   "only enumeration types have underlying types">;
-def err_incomplete_type_no_underlying_type : Error<
-  "an incomplete enumeration type has no underlying type yet">;
=20
 // C++11 delegating constructors
-def err_delegation_0x_only : Error<
+def err_delegating_ctor : Error<
   "delegating constructors are permitted only in C++11">;
+def warn_cxx98_compat_delegating_ctor : Warning<
+  "delegating constructors are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_delegating_initializer_alone : Error<
   "an initializer for a delegating constructor must appear alone">;
 def warn_delegating_ctor_cycle : Warning<
@@ -1171,8 +1316,6 @@
   "it delegates to">, InGroup<DelegatingCtorCycles>;
 def note_which_delegates_to : Note<
   "which delegates to">, InGroup<DelegatingCtorCycles>;
-def err_delegating_codegen_not_implemented : Error<
-  "code generation for delegating constructors not implemented">;
=20
 // C++11 range-based for loop
 def err_for_range_decl_must_be_var : Error<
@@ -1197,6 +1340,9 @@
   "selected '%select{begin|end}0' %select{function|template }1%2 with iter=
ator type %3">;
=20
 // C++11 constexpr
+def warn_cxx98_compat_constexpr : Warning<
+  "'constexpr' specifier is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_invalid_constexpr : Error<
   "%select{function parameter|typedef|non-static data member}0 "
   "cannot be constexpr">;
@@ -1207,37 +1353,27 @@
   "constexpr can only be used in variable and function declarations">;
 def err_invalid_constexpr_var_decl : Error<
   "constexpr variable declaration must be a definition">;
-def err_constexpr_var_requires_init : Error<
-  "declaration of constexpr variable %0 requires an initializer">;
+def err_constexpr_static_mem_var_requires_init : Error<
+  "declaration of constexpr static data member %0 requires an initializer"=
>;
+def err_constexpr_var_non_literal : Error<
+  "constexpr variable cannot have non-literal type %0">;
 def err_constexpr_var_requires_const_init : Error<
   "constexpr variable %0 must be initialized by a constant expression">;
 def err_constexpr_redecl_mismatch : Error<
   "%select{non-constexpr declaration of %0 follows constexpr declaration"
   "|constexpr declaration of %0 follows non-constexpr declaration}1">;
-def note_constexpr_redecl_mismatch : Note<
-  "previous declaration was %select{not |}0marked constexpr">;
 def err_constexpr_virtual : Error<"virtual function cannot be constexpr">;
-def note_constexpr_tmpl_virtual : Note<"function template instantiation is=
 not "
-  "constexpr because it is virtual">;
-def err_constexpr_virtual_base : Error<"constexpr constructor not allowed =
in "
-  "%select{class|struct}0 with virtual base %plural{1:class|:classes}1">;
-def note_constexpr_tmpl_virtual_base : Note<"constructor template instanti=
ation is "
-  "not constexpr because %select{class|struct}0 has virtual base "
-  "%plural{1:class|:classes}1">;
+def err_constexpr_virtual_base : Error<
+  "constexpr %select{member function|constructor}0 not allowed in "
+  "%select{class|struct}1 with virtual base %plural{1:class|:classes}2">;
 def note_non_literal_virtual_base : Note<"%select{class|struct}0 with virt=
ual "
   "base %plural{1:class|:classes}1 is not a literal type">;
 def note_constexpr_virtual_base_here : Note<"virtual base class declared h=
ere">;
 def err_constexpr_non_literal_return : Error<
   "constexpr function's return type %0 is not a literal type">;
-def note_constexpr_tmpl_non_literal_return : Note<
-  "function template instantiation is not constexpr because return type %0=
 is "
-  "not a literal type">;
 def err_constexpr_non_literal_param : Error<
   "constexpr %select{function|constructor}1's %ordinal0 parameter type %2 =
is "
   "not a literal type">;
-def note_constexpr_tmpl_non_literal_param : Note<
-  "%select{function|constructor}1 template instantiation is not constexpr "
-  "because %ordinal0 parameter type %2 is not a literal type">;
 def err_constexpr_body_invalid_stmt : Error<
   "statement not allowed in constexpr %select{function|constructor}0">;
 def err_constexpr_type_definition : Error<
@@ -1247,6 +1383,9 @@
   "%select{function|constructor}1">;
 def err_constexpr_var_declaration : Error<
   "variables cannot be declared in a constexpr %select{function|constructo=
r}0">;
+def err_constexpr_function_never_constant_expr : ExtWarn<
+  "constexpr %select{function|constructor}0 never produces a "
+  "constant expression">, InGroup<DiagGroup<"invalid-constexpr">>, Default=
Error;
 def err_constexpr_body_no_return : Error<
   "no return statement in constexpr function">;
 def err_constexpr_body_multiple_return : Error<
@@ -1269,21 +1408,24 @@
 def note_non_literal_base_class : Note<
   "%0 is not literal because it has base class %1 of non-literal type">;
 def note_non_literal_field : Note<
-  "%0 is not literal because it has data member %1 of non-literal type %2"=
>;
+  "%0 is not literal because it has data member %1 of "
+  "%select{non-literal|volatile}3 type %2">;
 def note_non_literal_user_provided_dtor : Note<
   "%0 is not literal because it has a user-provided destructor">;
 def note_non_literal_nontrivial_dtor : Note<
   "%0 is not literal because it has a non-trivial destructor">;
-def note_non_literal_mutable_field : Note<
-  "%0 is not literal because it has a mutable data member">;
+
+// C++11 char16_t/char32_t
+def warn_cxx98_compat_unicode_type : Warning<
+  "'%0' type specifier is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 =20
 // Objective-C++
 def err_objc_decls_may_only_appear_in_global_scope : Error<
   "Objective-C declarations may only appear in global scope">;
+// Attributes
 def err_nsobject_attribute : Error<
   "__attribute ((NSObject)) is for pointer types only">;
-
-// Attributes
 def err_attribute_can_be_applied_only_to_symbol_declaration : Error<
   "%0 attribute can be applied only to symbol declaration">;
 def err_attributes_are_not_compatible : Error<
@@ -1293,6 +1435,9 @@
   ":requires exactly %0 arguments}0">;
 def err_attribute_too_many_arguments : Error<
   "attribute takes no more than %0 argument%s0">;
+def err_suppress_autosynthesis : Error<
+  "objc_requires_property_definitions attribute may only be specified on a=
 class"
+  "to a class declaration">;
 def err_attribute_too_few_arguments : Error<
   "attribute takes at least %0 argument%s0">;
 def err_attribute_missing_parameter_name : Error<
@@ -1347,8 +1492,6 @@
   "can't convert between vector values of different size (%0 and %1)">;
 def err_typecheck_ext_vector_not_typedef : Error<
   "ext_vector_type only applies to types, not variables">;
-def err_unsupported_vector_size : Error<
-  "unsupported type %0 for vector_size attribute, please use on typedef">;
 def err_ext_vector_component_exceeds_length : Error<
   "vector component access exceeds type %0">;
 def err_ext_vector_component_name_illegal : Error<
@@ -1367,12 +1510,46 @@
   "automatic variable qualified with an address space">;
 def err_arg_with_address_space : Error<
   "parameter may not be qualified with an address space">;
-def err_attr_objc_ownership_bad_type : Error<
-  "the type %0 cannot be retained">;
 def err_attr_objc_ownership_redundant : Error<
-  "the type %0 already has retainment attributes set on it">;
+  "the type %0 is already explicitly ownership-qualified">;
 def err_attribute_not_string : Error<
   "argument to %0 attribute was not a string literal">;
+def err_undeclared_nsnumber : Error<
+  "NSNumber must be available to use Objective-C literals">;
+def err_invalid_nsnumber_type : Error<
+  "%0 is not a valid literal type for NSNumber">;
+def err_undeclared_nsarray : Error<
+  "NSArray must be available to use Objective-C array literals">;
+def err_undeclared_nsdictionary : Error<
+  "NSDictionary must be available to use Objective-C dictionary "
+  "literals">;
+def err_undeclared_arraywithobjects : Error<
+  "declaration of %0 is missing in NSArray class">;
+def err_undeclared_dictwithobjects : Error<
+  "declaration of %0 is missing in NSDictionary class">;
+def err_undeclared_nsnumber_method : Error<
+  "declaration of %0 is missing in NSNumber class">;
+def err_objc_literal_method_sig : Error<
+  "literal construction method %0 has incompatible signature">;
+def note_objc_literal_method_param : Note<
+  "%select{first|second|third}0 parameter has unexpected type %1 "
+  "(should be %2)">;
+def note_objc_literal_method_return : Note<
+  "method returns unexpected type %0 (should be an object type)">;
+def err_invalid_collection_element : Error<
+  "collection element of type %0 is not an Objective-C object">;
+def err_box_literal_collection : Error<
+  "%select{string|character|boolean|numeric}0 literal must be prefixed by =
'@' "
+  "in a collection">;
+
+let CategoryName =3D "Cocoa API Issue" in {
+def warn_objc_redundant_literal_use : Warning<
+  "using %0 with a literal is redundant">, InGroup<ObjCRedundantLiteralUse=
>;
+}
+
+def warn_bool_for_boolean_literal : Warning<
+  "BOOL of type %0 is non-intergal and unsuitable for a "
+  "boolean literal - ignored">, InGroup<DiagGroup<"numeric-literals">>;
 def err_only_annotate_after_access_spec : Error<
   "access specifier can only have annotation attributes">;
 def err_attribute_section_invalid_for_target : Error<
@@ -1386,6 +1563,8 @@
 def warn_attribute_ignored : Warning<"%0 attribute ignored">;
 def warn_unknown_attribute_ignored : Warning<
   "unknown attribute %0 ignored">, InGroup<UnknownAttributes>;
+def warn_declspec_attribute_ignored : Warning<
+  "attribute %0 is ignored, place it after \"%select{class|struct|union|en=
um}1\" to apply attribute to type declaration">, InGroup<IgnoredAttributes>;
 def warn_attribute_precede_definition : Warning<
   "attribute declaration must precede definition">;
 def warn_attribute_void_function_method : Warning<
@@ -1395,6 +1574,9 @@
   "__weak attribute cannot be specified on a field declaration">;
 def warn_gc_attribute_weak_on_local : Warning<
   "Objective-C GC does not allow weak variables on the stack">;
+def warn_nsobject_attribute : Warning<
+  "__attribute ((NSObject)) may be put on a typedef only, "
+  "attribute is ignored">, InGroup<NSobjectAttribute>;
 def warn_attribute_weak_on_local : Warning<
   "__weak attribute cannot be specified on an automatic variable">;
 def warn_weak_identifier_undeclared : Warning<
@@ -1414,16 +1596,15 @@
 def warn_attribute_wrong_decl_type : Warning<
   "%0 attribute only applies to %select{functions|unions|"
   "variables and functions|functions and methods|parameters|"
-  "parameters and methods|functions, methods and blocks|"
-  "classes and virtual methods|functions, methods, and parameters|"
-  "classes|virtual methods|class members|variables|methods|"
-  "variables, functions and labels|fields and global variables}1">;
+  "functions, methods and blocks|functions, methods, and parameters|"
+  "classes|variables|methods|variables, functions and labels|"
+  "fields and global variables|structs}1">;
 def err_attribute_wrong_decl_type : Error<
   "%0 attribute only applies to %select{functions|unions|"
   "variables and functions|functions and methods|parameters|"
-  "parameters and methods|functions, methods and blocks|"
-  "classes and virtual methods|functions, methods, and parameters|"
-  "classes|virtual methods|class members|variables|methods|structs}1">;
+  "functions, methods and blocks|functions, methods, and parameters|"
+  "classes|variables|methods|variables, functions and labels|"
+  "fields and global variables|structs}1">;
 def warn_function_attribute_wrong_type : Warning<
   "'%0' only applies to function types; type here is %1">;
 def warn_pointer_attribute_wrong_type : Warning<
@@ -1455,8 +1636,6 @@
 def warn_objc_precise_lifetime_meaningless : Error<
   "objc_precise_lifetime is not meaningful for "
   "%select{__unsafe_unretained|__autoreleasing}0 objects">;
-def warn_label_attribute_not_unused : Warning<
-  "The only valid attribute for labels is 'unused'">;
 def err_invalid_pcs : Error<"Invalid PCS type">;
 def err_attribute_can_be_applied_only_to_value_decl : Error<
   "%0 attribute can only be applied to value declarations">;
@@ -1479,12 +1658,18 @@
   "%plural{0:no parameters to index into|"
   "1:can only be 1, since there is one parameter|"
   ":must be between 1 and %2}2">;
-def err_attribute_argument_not_lockable : Error<
+def warn_attribute_argument_not_lockable : Warning<
   "%0 attribute requires arguments whose type is annotated "
-  "with 'lockable' attribute">;
-def err_attribute_decl_not_lockable : Error<
+  "with 'lockable' attribute; type here is '%1'">,
+  InGroup<ThreadSafety>, DefaultIgnore;
+def warn_attribute_decl_not_lockable : Warning<
   "%0 attribute can only be applied in a context annotated "
-  "with 'lockable' attribute">;
+  "with 'lockable' attribute">,
+  InGroup<ThreadSafety>, DefaultIgnore;
+def warn_attribute_argument_not_class : Warning<
+  "%0 attribute requires arguments that are class type or point to"
+  " class type; type here is '%1'">,
+  InGroup<ThreadSafety>, DefaultIgnore;  =20
 def warn_unlock_but_no_lock : Warning<
   "unlocking '%0' that was not locked">,
   InGroup<ThreadSafety>, DefaultIgnore;
@@ -1495,12 +1680,13 @@
   "mutex '%0' is still locked at the end of function">,
   InGroup<ThreadSafety>, DefaultIgnore;
 // FIXME: improve the error message about locks not in scope
-def warn_lock_at_end_of_scope : Warning<
-  "mutex '%0' is still locked at the end of its scope">,
+def warn_lock_some_predecessors : Warning<
+  "mutex '%0' is not locked on every path through here">,
   InGroup<ThreadSafety>, DefaultIgnore;
 def warn_expecting_lock_held_on_loop : Warning<
   "expecting mutex '%0' to be locked at start of each loop">,
   InGroup<ThreadSafety>, DefaultIgnore;
+def note_locked_here : Note<"mutex acquired here">;
 def warn_lock_exclusive_and_shared : Warning<
   "mutex '%0' is locked exclusively and shared in the same scope">,
   InGroup<ThreadSafety>, DefaultIgnore;
@@ -1530,7 +1716,7 @@
   "cannot call function '%0' while mutex '%1' is locked">,
   InGroup<ThreadSafety>, DefaultIgnore;
 def warn_cannot_resolve_lock : Warning<
-  "cannot resolve lock expression to a specific lockable object">,
+  "cannot resolve lock expression">,
   InGroup<ThreadSafety>, DefaultIgnore;
=20
=20
@@ -1548,10 +1734,10 @@
   InGroup<DiagGroup<"conversion">>, DefaultIgnore;
 def warn_impcast_integer_sign : Warning<
   "implicit conversion changes signedness: %0 to %1">,
-  InGroup<DiagGroup<"sign-conversion">>, DefaultIgnore;
+  InGroup<SignConversion>, DefaultIgnore;
 def warn_impcast_integer_sign_conditional : Warning<
   "operand of ? changes signedness: %0 to %1">,
-  InGroup<DiagGroup<"sign-conversion">>, DefaultIgnore;
+  InGroup<SignConversion>, DefaultIgnore;
 def warn_impcast_integer_precision : Warning<
   "implicit conversion loses integer precision: %0 to %1">,
   InGroup<DiagGroup<"conversion">>, DefaultIgnore;
@@ -1560,26 +1746,33 @@
   InGroup<DiagGroup<"shorten-64-to-32">>, DefaultIgnore;
 def warn_impcast_integer_precision_constant : Warning<
   "implicit conversion from %2 to %3 changes value from %0 to %1">,
-  InGroup<DiagGroup<"constant-conversion">>;
+  InGroup<ConstantConversion>;
 def warn_impcast_bitfield_precision_constant : Warning<
   "implicit truncation from %2 to bitfield changes value from %0 to %1">,
-  InGroup<DiagGroup<"constant-conversion">>;
+  InGroup<ConstantConversion>;
 def warn_impcast_literal_float_to_integer : Warning<
   "implicit conversion turns literal floating-point number into integer: "
   "%0 to %1">,
-  InGroup<DiagGroup<"literal-conversion">>, DefaultIgnore;
+  InGroup<LiteralConversion>;
 def warn_impcast_string_literal_to_bool : Warning<
   "implicit conversion turns string literal into bool: %0 to %1">,
-  InGroup<DiagGroup<"string-conversion">>, DefaultIgnore;
+  InGroup<StringConversion>, DefaultIgnore;
 def warn_impcast_different_enum_types : Warning<
   "implicit conversion from enumeration type %0 to different enumeration t=
ype "
   "%1">, InGroup<DiagGroup<"conversion">>;
 def warn_impcast_bool_to_null_pointer : Warning<
     "initialization of pointer of type %0 to null from a constant boolean "
-    "expression">, InGroup<BoolConversions>;
+    "expression">, InGroup<BoolConversion>;
 def warn_impcast_null_pointer_to_integer : Warning<
-    "implicit conversion of NULL constant to integer">,
-    InGroup<DiagGroup<"conversion">>, DefaultIgnore;
+    "implicit conversion of NULL constant to %0">,
+    InGroup<NullConversion>;
+def warn_impcast_function_to_bool : Warning<
+    "address of function %q0 will always evaluate to 'true'">,
+    InGroup<BoolConversion>;
+def note_function_to_bool_silence : Note<
+    "prefix with the address-of operator to silence this warning">;
+def note_function_to_bool_call : Note<
+    "suffix with parentheses to turn this into a function call">;
=20
 def warn_cast_align : Warning<
   "cast from %0 to %1 increases required alignment from %2 to %3">,
@@ -1605,6 +1798,9 @@
 def warn_attribute_type_not_supported : Warning<
   "'%0' attribute argument not supported: %1">;
 def warn_attribute_unknown_visibility : Warning<"unknown visibility '%0'">;
+def warn_attribute_protected_visibility :
+  Warning<"target does not support 'protected' visibility; using 'default'=
">,
+  InGroup<DiagGroup<"unsupported-visibility">>;
 def err_unknown_machine_mode : Error<"unknown machine mode %0">;
 def err_unsupported_machine_mode : Error<"unsupported machine mode %0">;
 def err_mode_not_primitive : Error<
@@ -1617,9 +1813,6 @@
   "'nonnull' attribute applied to function with no pointer arguments">;
 def warn_attribute_malloc_pointer_only : Warning<
   "'malloc' attribute only applies to functions returning a pointer type">;
-def warn_transparent_union_nonpointer : Warning<
-  "'transparent_union' attribute support incomplete; only supported for "
-  "pointer unions">;
 def warn_attribute_sentinel_named_arguments : Warning<
   "'sentinel' attribute requires named arguments">;
 def warn_attribute_sentinel_not_variadic : Warning<
@@ -1650,9 +1843,10 @@
   "ibaction attribute can only be applied to Objective-C instance methods"=
>;
 def err_iboutletcollection_type : Error<
   "invalid type %0 as argument of iboutletcollection attribute">;
-def err_iboutlet_object_type : Error<
+def warn_iboutlet_object_type : Warning<
   "%select{ivar|property}2 with %0 attribute must "
-  "be an object type (invalid %1)">;
+  "be an object type (invalid %1)">,
+  InGroup<DiagGroup<"invalid-iboutlet">>;
 def err_attribute_overloadable_not_function : Error<
   "'overloadable' attribute can only be applied to a function">;
 def err_attribute_overloadable_missing : Error<
@@ -1713,8 +1907,6 @@
   "cannot define the implicit default assignment operator for %0, because "
   "non-static %select{reference|const}1 member %2 can't use default "
   "assignment operator">;
-def note_first_required_here : Note<
-  "synthesized method is first required here">;
 def err_uninitialized_member_in_ctor : Error<
   "%select{|implicit default }0constructor for %1 must explicitly initiali=
ze "
   "the %select{reference|const}2 member %3">;
@@ -1733,7 +1925,8 @@
=20
 def ext_param_promoted_not_compatible_with_prototype : ExtWarn<
   "promoted type %0 of K&R function parameter is not compatible with the "
-  "parameter type %1 declared in a previous prototype">;
+  "parameter type %1 declared in a previous prototype">,
+  InGroup<KNRPromotedParameter>;
=20
=20
 // C++ Overloading Semantic Analysis.
@@ -1766,7 +1959,16 @@
     "is the implicit move constructor|"
     "is the implicit copy assignment operator|"
     "is the implicit move assignment operator|"
-    "is an inherited constructor}0%1">;
+    "is an inherited constructor}0%1"
+    "%select{| has different class (expected %3 but has %4)"
+    "| has different number of parameters (expected %3 but has %4)"
+    "| has type mismatch at %ordinal3 parameter (expected %4 but has %5)"
+    "| has different return type (%3 expected but has %4)"
+    "| has different qualifiers (expected "
+    "%select{none|const|restrict|const and restrict|volatile|const and vol=
atile"
+    "|volatile and restrict|const, volatile, and restrict}3 but found "
+    "%select{none|const|restrict|const and restrict|volatile|const and vol=
atile"
+    "|volatile and restrict|const, volatile, and restrict}4)}2">;
=20
 def note_ovl_candidate_inherited_constructor : Note<"inherited from here">;
 def note_ovl_candidate_bad_deduction : Note<
@@ -1811,8 +2013,9 @@
     "constructor (the implicit move constructor)|"
     "function (the implicit copy assignment operator)|"
     "function (the implicit move assignment operator)|"
-    "constructor (inherited)}0%1 "
-    "has been explicitly %select{made unavailable|deleted}2">;
+    "constructor (inherited)}0%1 has been "
+    "%select{explicitly made unavailable|explicitly deleted|"
+    "implicitly deleted}2">;
=20
 // Giving the index of the bad argument really clutters this message, and
 // it's relatively unimportant because 1) it's generally obvious which
@@ -1979,6 +2182,10 @@
   "reference initialization of type %0 with initializer of type %1 is ambi=
guous">;
 def err_ovl_deleted_init : Error<
   "call to %select{unavailable|deleted}0 constructor of %1">;
+def err_ovl_deleted_special_init : Error<
+  "call to implicitly-deleted %select{default constructor|copy constructor=
|"
+  "move constructor|copy assignment operator|move assignment operator|"
+  "destructor|function}0 of %1">;
 def err_ovl_ambiguous_oper_unary : Error<
   "use of overloaded operator '%0' is ambiguous (operand type %1)">;
 def err_ovl_ambiguous_oper_binary : Error<
@@ -1986,6 +2193,10 @@
 def err_ovl_no_viable_oper : Error<"no viable overloaded '%0'">;
 def err_ovl_deleted_oper : Error<
   "overload resolution selected %select{unavailable|deleted}0 operator '%1=
'%2">;
+def err_ovl_deleted_special_oper : Error<
+  "overload resolution selected implicitly-deleted %select{default constru=
ctor|"
+  "copy constructor|move constructor|copy assignment operator|move assignm=
ent "
+  "operator|destructor|'%1'}0%2">;
 def err_ovl_no_viable_subscript :
     Error<"no viable overloaded operator[] for type %0">;
 def err_ovl_no_oper :
@@ -2017,7 +2228,13 @@
   "address of overloaded function %0 cannot be converted to type %1">;
 def err_addr_ovl_no_qualifier : Error<
   "can't form member pointer of type %0 without '&' and class name">;
- =20
+
+// C++11 Literal Operators
+def err_ovl_no_viable_literal_operator : Error<
+  "no matching literal operator for call to %0"
+  "%select{| with argument of type %2| with arguments of types %2 and %3}1"
+  "%select{| or 'const char *', and no matching literal operator template}=
4">;
+
 // C++ Template Declarations
 def err_template_param_shadow : Error<
   "declaration of %0 shadows template parameter">;
@@ -2063,6 +2280,9 @@
 def ext_template_parameter_default_in_function_template : ExtWarn<
   "default template arguments for a function template are a C++11 extensio=
n">,
   InGroup<CXX11>;
+def warn_cxx98_compat_template_parameter_default_in_function_template : Wa=
rning<
+  "default template arguments for a function template are incompatible wit=
h C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_template_parameter_default_template_member : Error<
   "cannot add a default template argument to the definition of a member of=
 a "
   "class template">;
@@ -2103,6 +2323,12 @@
   "template argument uses local type %0">, InGroup<LocalTypeTemplateArgs>;
 def ext_template_arg_unnamed_type : ExtWarn<
   "template argument uses unnamed type">, InGroup<UnnamedTypeTemplateArgs>;
+def warn_cxx98_compat_template_arg_local_type : Warning<
+  "local type %0 as template argument is incompatible with C++98">,
+  InGroup<CXX98CompatLocalTypeTemplateArgs>, DefaultIgnore;
+def warn_cxx98_compat_template_arg_unnamed_type : Warning<
+  "unnamed type as template argument is incompatible with C++98">,
+  InGroup<CXX98CompatUnnamedTypeTemplateArgs>, DefaultIgnore;
 def note_template_unnamed_type_here : Note<
   "unnamed type used in template argument was declared here">;
 def err_template_arg_overload_type : Error<
@@ -2121,6 +2347,13 @@
 def err_template_arg_not_ice : Error<
   "non-type template argument of type %0 is not an integral constant "
   "expression">;
+def err_template_arg_not_address_constant : Error<
+  "non-type template argument of type %0 is not a constant expression">;
+def err_template_arg_untyped_null_constant : Error<
+  "null non-type template argument must be cast to template parameter type=
 %0">;
+def err_template_arg_wrongtype_null_constant : Error<
+ "null non-type template argument of type %0 does not match template param=
eter "
+ "of type %1">;
 def err_deduced_non_type_template_arg_type_mismatch : Error<
   "deduced non-type template argument does not have the same type as the "
   "its corresponding template parameter (%0 vs %1)">;
@@ -2156,20 +2389,31 @@
   "non-type template argument refers to non-static data member %0">;
 def err_template_arg_method : Error<
   "non-type template argument refers to non-static member function %0">;
-def err_template_arg_function_not_extern : Error<
-  "non-template argument refers to function %0 with internal linkage">;
-def err_template_arg_object_not_extern : Error<
-  "non-template argument refers to object %0 that does not have external "
-  "linkage">;
+def err_template_arg_object_no_linkage : Error<
+  "non-type template argument refers to %select{function|object}0 %1 that "
+  "does not have linkage">;
+def warn_cxx98_compat_template_arg_object_internal : Warning<
+  "non-type template argument referring to %select{function|object}0 %1 wi=
th "
+  "internal linkage is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+def ext_template_arg_object_internal : ExtWarn<
+  "non-type template argument referring to %select{function|object}0 %1 wi=
th "
+  "internal linkage is a C++11 extension">, InGroup<CXX11>;
+def err_template_arg_thread_local : Error<
+  "non-type template argument refers to thread-local object">;
 def note_template_arg_internal_object : Note<
-  "non-template argument refers to %select{function|object}0 here">;
-def note_template_arg_refers_here : Note<"non-template argument refers her=
e">;
+  "non-type template argument refers to %select{function|object}0 here">;
+def note_template_arg_refers_here : Note<
+  "non-type template argument refers here">;
 def err_template_arg_not_object_or_func : Error<
   "non-type template argument does not refer to an object or function">;
 def err_template_arg_not_pointer_to_member_form : Error<
   "non-type template argument is not a pointer to member constant">;
 def ext_template_arg_extra_parens : ExtWarn<
   "address non-type template argument cannot be surrounded by parentheses"=
>;
+def warn_cxx98_compat_template_arg_extra_parens : Warning<
+  "redundant parentheses surrounding address non-type template argument ar=
e "
+  "incompatible with C++98">, InGroup<CXX98Compat>, DefaultIgnore;
 def err_pointer_to_member_type : Error<
   "invalid use of pointer to member type after %select{.*|->*}0">;
 def err_pointer_to_member_call_drops_quals : Error<
@@ -2181,7 +2425,8 @@
 // C++ template specialization
 def err_template_spec_unknown_kind : Error<
   "can only provide an explicit specialization for a class template, funct=
ion "
-  "template, or a member function, static data member, or member class of =
a "
+  "template, or a member function, static data member, "
+  "%select{or member class|member class, or member enumeration}0 of a "
   "class template">;
 def note_specialized_entity : Note<
   "explicitly specialized declaration is here">;
@@ -2193,30 +2438,30 @@
   "cannot declare an explicit specialization in a friend">;
 def err_template_spec_decl_out_of_scope_global : Error<
   "%select{class template|class template partial|function template|member "
-  "function|static data member|member class}0 specialization of %1 must "
-  "originally be declared in the global scope">;
-def ext_template_spec_decl_out_of_scope_global : ExtWarn<
-  "%select{class template|class template partial|function template|member "
-  "function|static data member|member class}0 specialization of %1 must "
-  "originally be declared in the global scope; accepted as a C++11 extensi=
on">,
-  InGroup<CXX11>;
+  "function|static data member|member class|member enumeration}0 "
+  "specialization of %1 must originally be declared in the global scope">;
 def err_template_spec_decl_out_of_scope : Error<
   "%select{class template|class template partial|function template|member "
-  "function|static data member|member class}0 specialization of %1 must "
-  "originally be declared in namespace %2">;
+  "function|static data member|member class|member enumeration}0 "
+  "specialization of %1 must originally be declared in namespace %2">;
 def ext_template_spec_decl_out_of_scope : ExtWarn<
+  "first declaration of %select{class template|class template partial|"
+  "function template|member function|static data member|member class|"
+  "member enumeration}0 specialization of %1 outside namespace %2 is a "
+  "C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_template_spec_decl_out_of_scope : Warning<
   "%select{class template|class template partial|function template|member "
-  "function|static data member|member class}0 specialization of %1 must "
-  "originally be declared in namespace %2; accepted as a C++11 extension">,
-  InGroup<CXX11>;
+  "function|static data member|member class|member enumeration}0 "
+  "specialization of %1 outside namespace %2 is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_template_spec_redecl_out_of_scope : Error<
   "%select{class template|class template partial|function template|member "
-  "function|static data member|member class}0 specialization of %1 not in =
a "
-  "namespace enclosing %2">;
+  "function|static data member|member class|member enumeration}0 "
+  "specialization of %1 not in a namespace enclosing %2">;
 def err_template_spec_redecl_global_scope : Error<
   "%select{class template|class template partial|function template|member "
-  "function|static data member|member class}0 specialization of %1 must oc=
cur "
-  "at global scope">;
+  "function|static data member|member class|member enumeration}0 "
+  "specialization of %1 must occur at global scope">;
 def err_spec_member_not_instantiated : Error<
   "specialization of member %q0 does not specialize an instantiated member=
">;
 def note_specialized_decl : Note<"attempt to specialize declaration here">;
@@ -2303,7 +2548,7 @@
     "no function template matches function template specialization %0">;
 def err_function_template_spec_ambiguous : Error<
     "function template specialization %0 ambiguously refers to more than o=
ne "
-    "function template; explicitly specify%select{|additional }1 template "
+    "function template; explicitly specify%select{| additional}1 template "
     "arguments to identify a particular function template">;
 def note_function_template_spec_matched : Note<
     "function template matches specialization %0">;
@@ -2315,7 +2560,7 @@
   "recursive template instantiation exceeded maximum depth of %0">,
   DefaultFatal, NoSFINAE;
 def note_template_recursion_depth : Note<
-  "use -ftemplate-depth-N to increase recursive template instantiation dep=
th">;
+  "use -ftemplate-depth=3DN to increase recursive template instantiation d=
epth">;
=20
 def err_template_instantiate_within_definition : Error<
   "%select{implicit|explicit}0 instantiation of template %1 within its"
@@ -2334,6 +2579,8 @@
   "in instantiation of function template specialization %q0 requested here=
">;
 def note_template_static_data_member_def_here : Note<
   "in instantiation of static data member %q0 requested here">;
+def note_template_enum_def_here : Note<
+  "in instantiation of enumeration %q0 requested here">;
 def note_template_type_alias_instantiation_here : Note<
   "in instantiation of template type alias %0 requested here">;
  =20
@@ -2376,10 +2623,12 @@
     "explicit instantiation of %0 that occurs after an explicit "
     "specialization will be ignored (C++11 extension)">,
     InGroup<CXX11>;
+def warn_cxx98_compat_explicit_instantiation_after_specialization : Warnin=
g<
+    "explicit instantiation of %0 that occurs after an explicit "
+    "specialization is incompatible with C++98">,
+    InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def note_previous_template_specialization : Note<
     "previous template specialization is here">;
-def err_explicit_instantiation_enum : Error<
-    "explicit instantiation of enumeration type %0">;
 def err_explicit_instantiation_nontemplate_type : Error<
     "explicit instantiation of non-templated type %0">;
 def note_nontemplate_decl_here : Note<
@@ -2392,10 +2641,10 @@
   "explicit instantiation of %0 must occur at global scope">;
 def warn_explicit_instantiation_out_of_scope_0x : Warning<
   "explicit instantiation of %0 not in a namespace enclosing %1">,=20
-  InGroup<CXX11Compat>;
+  InGroup<CXX11Compat>, DefaultIgnore;
 def warn_explicit_instantiation_must_be_global_0x : Warning<
   "explicit instantiation of %0 must occur at global scope">,=20
-  InGroup<CXX11Compat>;
+  InGroup<CXX11Compat>, DefaultIgnore;
  =20
 def err_explicit_instantiation_requires_name : Error<
   "explicit instantiation declaration requires a name">;
@@ -2420,16 +2669,19 @@
   "explicit instantiation candidate function template here %0">;
 def err_explicit_instantiation_inline : Error<
   "explicit instantiation cannot be 'inline'">;
+def warn_explicit_instantiation_inline_0x : Warning<
+  "explicit instantiation cannot be 'inline'">, InGroup<CXX11Compat>,
+  DefaultIgnore;
 def err_explicit_instantiation_constexpr : Error<
   "explicit instantiation cannot be 'constexpr'">;
 def ext_explicit_instantiation_without_qualified_id : Extension<
   "qualifier in explicit instantiation of %q0 requires a template-id "
   "(a typedef is not permitted)">;
 def err_explicit_instantiation_unqualified_wrong_namespace : Error<
-  "explicit instantiation of %q0 must occur in %1">;
+  "explicit instantiation of %q0 must occur in namespace %1">;
 def warn_explicit_instantiation_unqualified_wrong_namespace_0x : Warning<
-  "explicit instantiation of %q0 must occur in %1">,=20
-  InGroup<CXX11Compat>;
+  "explicit instantiation of %q0 must occur in namespace %1">,
+  InGroup<CXX11Compat>, DefaultIgnore;
 def err_explicit_instantiation_undefined_member : Error<
   "explicit instantiation of undefined %select{member class|member functio=
n|"
   "static data member}0 %1 of class template %2">;
@@ -2454,6 +2706,9 @@
   InGroup<DiagGroup<"typename-missing">>;
 def ext_typename_outside_of_template : ExtWarn<
   "'typename' occurs outside of a template">, InGroup<CXX11>;
+def warn_cxx98_compat_typename_outside_of_template : Warning<
+  "use of 'typename' outside of a template is incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_typename_refers_to_using_value_decl : Error<
   "typename specifier refers to a dependent using declaration for a value "
   "%0 in %1">;
@@ -2462,8 +2717,6 @@
=20
 def err_template_kw_refers_to_non_template : Error<
     "%0 following the 'template' keyword does not refer to a template">;
-def err_template_kw_refers_to_function_template : Error<
-    "%0 following the 'template' keyword refers to a function template">;
 def err_template_kw_refers_to_class_template : Error<
     "'%0%1' instantiated to a class template, not a function template">;
 def note_referenced_class_template : Error<
@@ -2472,6 +2725,9 @@
   "missing 'template' keyword prior to dependent template name '%0%1'">;
 def ext_template_outside_of_template : ExtWarn<
   "'template' keyword outside of a template">, InGroup<CXX11>;
+def warn_cxx98_compat_template_outside_of_template : Warning<
+  "use of 'template' keyword outside of a template is incompatible with C+=
+98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 def err_non_type_template_in_nested_name_specifier : Error<
   "qualified name refers into a specialization of function template '%0'">;
@@ -2480,6 +2736,8 @@
 def note_template_declared_here : Note<
   "%select{function template|class template|type alias template|template t=
emplate parameter}0 "
   "%1 declared here">;
+def note_parameter_type : Note<
+  "parameter of type %0 is declared here">;
=20
 // C++11 Variadic Templates
 def err_template_param_pack_default_arg : Error<
@@ -2503,25 +2761,29 @@
   "%select{expression|base type|declaration type|data member type|bit-fiel=
d "
   "size|static assertion|fixed underlying type|enumerator value|"
   "using declaration|friend declaration|qualifier|initializer|default argu=
ment|"
-  "non-type template parameter type|exception type|partial specialization}=
0 "
+  "non-type template parameter type|exception type|partial specialization|"
+  "__if_exists name|__if_not_exists name}0 "
   "contains an unexpanded parameter pack">;
 def err_unexpanded_parameter_pack_1 : Error<
   "%select{expression|base type|declaration type|data member type|bit-fiel=
d "
   "size|static assertion|fixed underlying type|enumerator value|"
   "using declaration|friend declaration|qualifier|initializer|default argu=
ment|"
-  "non-type template parameter type|exception type|partial specialization}=
0 "
+  "non-type template parameter type|exception type|partial specialization|"
+  "__if_exists name|__if_not_exists name}0 "
   "contains unexpanded parameter pack %1">;
 def err_unexpanded_parameter_pack_2 : Error<
   "%select{expression|base type|declaration type|data member type|bit-fiel=
d "
   "size|static assertion|fixed underlying type|enumerator value|"
   "using declaration|friend declaration|qualifier|initializer|default argu=
ment|"
-  "non-type template parameter type|exception type|partial specialization}=
0 "
+  "non-type template parameter type|exception type|partial specialization|"
+  "__if_exists name|__if_not_exists name}0 "
   "contains unexpanded parameter packs %1 and %2">;
 def err_unexpanded_parameter_pack_3_or_more : Error<
   "%select{expression|base type|declaration type|data member type|bit-fiel=
d "
   "size|static assertion|fixed underlying type|enumerator value|"
   "using declaration|friend declaration|qualifier|initializer|default argu=
ment|"
-  "non-type template parameter type|exception type|partial specialization}=
0 "
+  "non-type template parameter type|exception type|partial specialization|"
+  "__if_exists name|__if_not_exists name}0 "
   "contains unexpanded parameter packs %1, %2, ...">;
=20
 def err_pack_expansion_without_parameter_packs : Error<
@@ -2576,6 +2838,8 @@
 def note_unavailable_here : Note<
   "%select{declaration|function}0 has been explicitly marked "
   "%select{unavailable|deleted|deprecated}1 here">;
+def note_implicitly_deleted : Note<
+  "explicitly defaulted function was implicitly deleted here">;
 def warn_not_enough_argument : Warning<
   "not enough variable arguments in %0 declaration to fit a sentinel">,
   InGroup<Sentinel>;
@@ -2599,6 +2863,37 @@
 def err_redefinition_extern_inline : Error<
   "redefinition of a 'extern inline' function %0 is not supported in "
   "%select{C99 mode|C++}1">;
+def warn_cxx98_compat_friend_redefinition : Warning<
+  "friend function %0 would be implicitly redefined in C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
+
+def note_deleted_dtor_no_operator_delete : Note<
+  "virtual destructor requires an unambiguous, accessible 'operator delete=
'">;
+def note_deleted_special_member_class_subobject : Note<
+  "%select{default constructor|copy constructor|move constructor|"
+  "copy assignment operator|move assignment operator|destructor}0 of "
+  "%select{||||union }4%1 is implicitly deleted because "
+  "%select{base class %3|field %3}2 has "
+  "%select{no|a deleted|multiple|an inaccessible|a non-trivial}4 "
+  "%select{%select{default constructor|copy constructor|move constructor|c=
opy "
+  "assignment operator|move assignment operator|destructor}0|destructor}5"
+  "%select{||s||}4">;
+def note_deleted_default_ctor_uninit_field : Note<
+  "default constructor of %0 is implicitly deleted because field %1 of "
+  "%select{reference|const-qualified}3 type %2 would not be initialized">;
+def note_deleted_default_ctor_all_const : Note<
+  "default constructor of %0 is implicitly deleted because all "
+  "%select{data members|data members of an anonymous union member}1"
+  " are const-qualified">;
+def note_deleted_copy_ctor_rvalue_reference : Note<
+  "copy constructor of %0 is implicitly deleted because field %1 is of "
+  "rvalue reference type %2">;
+def note_deleted_copy_user_declared_move : Note<
+  "copy %select{constructor|assignment operator}0 is implicitly deleted be=
cause"
+  " %1 has a user-declared move %select{constructor|assignment operator}2"=
>;
+def note_deleted_assign_field : Note<
+  "%select{copy|move}0 assignment operator of %0 is implicitly deleted "
+  "because field %1 is of %select{reference|const-qualified}3 type %2">;
=20
 // This should eventually be an error.
 def warn_undefined_internal : Warning<
@@ -2606,9 +2901,11 @@
   DiagGroup<"undefined-internal">;
 def note_used_here : Note<"used here">;
=20
-def warn_redefinition_of_typedef : Warning<
-  "redefinition of typedef %0 is invalid in C">,
-  InGroup<DiagGroup<"typedef-redefinition"> >, DefaultError;
+def warn_redefinition_of_typedef : ExtWarn<
+  "redefinition of typedef %0 is a C11 feature">,
+  InGroup<DiagGroup<"typedef-redefinition"> >;
+def err_redefinition_variably_modified_typedef : Error<
+  "redefinition of %select{typedef|type alias}0 for variably-modified type=
 %1">;
=20
 def err_inline_declaration_block_scope : Error<
   "inline declaration of %0 not allowed in block scope">;
@@ -2632,6 +2929,9 @@
   "redefinition of %0 with a different type">;
 def err_redefinition_different_kind : Error<
   "redefinition of %0 as different kind of symbol">;
+def warn_forward_class_redefinition : Warning<
+  "redefinition of forward class %0 of a typedef name of an object type is=
 ignored">,
+  InGroup<DiagGroup<"objc-forward-class-redefinition">>;
 def err_redefinition_different_typedef : Error<
   "%select{typedef|type alias|type alias template}0 redefinition with diff=
erent types (%1 vs %2)">;
 def err_tag_reference_non_tag : Error<
@@ -2692,6 +2992,9 @@
   "function declaration cannot have variably modified type">;
 def err_array_too_large : Error<
   "array is too large (%0 elements)">;
+def warn_array_new_too_large : Warning<"array is too large (%0 elements)">,
+  // FIXME PR11644: ", will throw std::bad_array_new_length at runtime"
+  InGroup<DiagGroup<"bad-array-new-length">>;
=20
 // -Wpadded, -Wpacked
 def warn_padded_struct_field : Warning<
@@ -2707,6 +3010,9 @@
   "packed attribute is unnecessary for %0">, InGroup<Packed>, DefaultIgnor=
e;
=20
 def err_typecheck_negative_array_size : Error<"array size is negative">;
+def warn_typecheck_negative_array_new_size : Warning<"array size is negati=
ve">,
+  // FIXME PR11644: ", will throw std::bad_array_new_length at runtime"
+  InGroup<DiagGroup<"bad-array-new-length">>;
 def warn_typecheck_function_qualifiers : Warning<
   "qualifier on function type %0 has unspecified behavior">;
 def err_typecheck_invalid_restrict_not_pointer : Error<
@@ -2719,8 +3025,9 @@
   "zero size arrays are an extension">;
 def err_typecheck_zero_array_size : Error<
   "zero-length arrays are not permitted in C++">;
-def err_at_least_one_initializer_needed_to_size_array : Error<
-  "at least one initializer value required to size array">;
+def warn_typecheck_zero_static_array_size : Warning<
+  "'static' has no effect on zero-length arrays">,
+  InGroup<DiagGroup<"array-bounds">>;
 def err_array_size_non_int : Error<"size of array has non-integer type %0"=
>;
 def err_init_element_not_constant : Error<
   "initializer element is not a compile-time constant">;
@@ -2731,8 +3038,6 @@
 def warn_extern_init : Warning<"'extern' variable has an initializer">;
 def err_variable_object_no_init : Error<
   "variable-sized object may not be initialized">;
-def err_array_init_list_required : Error<
-  "initialization with '{...}' expected for array">;
 def err_excess_initializers : Error<
   "excess elements in %select{array|vector|scalar|union|struct}0 initializ=
er">;
 def warn_excess_initializers : ExtWarn<
@@ -2756,14 +3061,31 @@
   "complex initialization specifying real and imaginary components "
   "is an extension">, InGroup<DiagGroup<"complex-component-init">>;
 def err_empty_scalar_initializer : Error<"scalar initializer cannot be emp=
ty">;
+def warn_cxx98_compat_empty_scalar_initializer : Warning<
+  "scalar initialized from empty initializer list is incompatible with C++=
98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_illegal_initializer : Error<
   "illegal initializer (only variables can be initialized)">;
 def err_illegal_initializer_type : Error<"illegal initializer type %0">;
-def err_init_list_variable_narrowing : Error<
+def err_init_list_type_narrowing_sfinae : Error<
+  "type %0 cannot be narrowed to %1 in initializer list">;
+def err_init_list_type_narrowing : ExtWarn<
+  "type %0 cannot be narrowed to %1 in initializer list">,=20
+  InGroup<CXX11Narrowing>, DefaultError;
+def err_init_list_variable_narrowing_sfinae : Error<
   "non-constant-expression cannot be narrowed from type %0 to %1 in "
   "initializer list">;
-def err_init_list_constant_narrowing : Error<
+def err_init_list_variable_narrowing : ExtWarn<
+  "non-constant-expression cannot be narrowed from type %0 to %1 in "
+  "initializer list">, InGroup<CXX11Narrowing>, DefaultError;
+def err_init_list_constant_narrowing_sfinae : Error<
   "constant expression evaluates to %0 which cannot be narrowed to type %1=
">;
+def err_init_list_constant_narrowing : ExtWarn<
+  "constant expression evaluates to %0 which cannot be narrowed to type %1=
">,
+  InGroup<CXX11Narrowing>, DefaultError;
+def warn_init_list_type_narrowing : Warning<
+  "type %0 cannot be narrowed to %1 in initializer list in C++11">,
+  InGroup<CXX11Narrowing>, DefaultIgnore;
 def warn_init_list_variable_narrowing : Warning<
   "non-constant-expression cannot be narrowed from type %0 to %1 in "
   "initializer list in C++11">,
@@ -2789,7 +3111,7 @@
   "size of anonymous bit-field (%0 bits) exceeds size of its type (%1 bits=
)">;
 def err_incorrect_number_of_vector_initializers : Error<
   "number of elements must be either one or match the size of the vector">;
- =20
+
 // Used by C++ which allows bit-fields that are wider than the type.
 def warn_bitfield_width_exceeds_type_size: Warning<
   "size of bit-field %0 (%1 bits) exceeds the size of its type; value will=
 be "
@@ -2801,6 +3123,9 @@
 def warn_missing_braces : Warning<
   "suggest braces around initialization of subobject">,
   InGroup<DiagGroup<"missing-braces">>, DefaultIgnore;
+def err_missing_braces : Error<
+  "cannot omit braces around initialization of subobject when using direct=
 "
+  "list-initialization">;
=20
 def err_redefinition_of_label : Error<"redefinition of label %0">;
 def err_undeclared_label_use : Error<"use of undeclared label %0">;
@@ -2810,17 +3135,28 @@
 def err_goto_into_protected_scope : Error<"goto into protected scope">;
 def warn_goto_into_protected_scope : ExtWarn<"goto into protected scope">,
   InGroup<Microsoft>;
+def warn_cxx98_compat_goto_into_protected_scope : Warning<
+  "goto would jump into protected scope in C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_switch_into_protected_scope : Error<
   "switch case is in protected scope">;
+def warn_cxx98_compat_switch_into_protected_scope : Warning<
+  "switch case would be in a protected scope in C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def err_indirect_goto_without_addrlabel : Error<
   "indirect goto in function with no address-of-label expressions">;
 def err_indirect_goto_in_protected_scope : Error<
   "indirect goto might cross protected scopes">;
+def warn_cxx98_compat_indirect_goto_in_protected_scope : Warning<
+  "indirect goto might cross protected scopes in C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
 def note_indirect_goto_target : Note<"possible target of indirect goto">;
 def note_protected_by_variable_init : Note<
   "jump bypasses variable initialization">;
 def note_protected_by_variable_nontriv_destructor : Note<
   "jump bypasses variable with a non-trivial destructor">;
+def note_protected_by_variable_non_pod : Note<
+  "jump bypasses initialization of non-POD variable">;
 def note_protected_by_cleanup : Note<
   "jump bypasses initialization of variable with __attribute__((cleanup))"=
>;
 def note_protected_by_vla_typedef : Note<
@@ -2896,9 +3232,11 @@
 def err_flexible_array_has_nonpod_type : Error<
   "flexible array member %0 of non-POD element type %1">;
 def ext_flexible_array_in_struct : Extension<
-  "%0 may not be nested in a struct due to flexible array member">;
+  "%0 may not be nested in a struct due to flexible array member">,
+  InGroup<FlexibleArrayExtensions>;
 def ext_flexible_array_in_array : Extension<
-  "%0 may not be used as an array element due to flexible array member">;
+  "%0 may not be used as an array element due to flexible array member">,
+  InGroup<FlexibleArrayExtensions>;
 def err_flexible_array_init : Error<
   "initialization of flexible array member is not allowed">;
 def ext_flexible_array_empty_aggregate_ms : Extension<
@@ -2913,18 +3251,29 @@
 def ext_flexible_array_union_gnu : Extension<
   "flexible array member %0 in a union is a GNU extension">, InGroup<GNU>;
=20
-let CategoryName =3D "Automatic Reference Counting Issue" in {
+let CategoryName =3D "ARC Semantic Issue" in {
=20
 // ARC-mode diagnostics.
+
+let CategoryName =3D "ARC Weak References" in {
+
 def err_arc_weak_no_runtime : Error<
   "the current deployment target does not support automated __weak referen=
ces">;
 def err_arc_unsupported_weak_class : Error<
   "class is incompatible with __weak references">;
 def err_arc_weak_unavailable_assign : Error<
   "assignment of a weak-unavailable object to a __weak object">;
+def err_arc_weak_unavailable_property : Error<
+  "synthesis of a weak-unavailable property is disallowed "
+  "because it requires synthesis of an ivar of the __weak object">;
 def err_arc_convesion_of_weak_unavailable : Error<
   "%select{implicit conversion|cast}0 of weak-unavailable object of type %=
1 to"
   " a __weak object of type %2">;
+
+} // end "ARC Weak References" category
+
+let CategoryName =3D "ARC Restrictions" in {
+
 def err_arc_illegal_explicit_message : Error<
   "ARC forbids explicit message send of %0">;
 def err_arc_unused_init_message : Error<
@@ -2935,8 +3284,10 @@
   "%select{%2|a non-Objective-C pointer type %2|a block pointer|"
   "an Objective-C pointer|an indirect pointer to an Objective-C pointer}1"
   " to %3 is disallowed with ARC">;
+def err_arc_nolifetime_behavior : Error<
+  "explicit ownership qualifier on cast result has no effect">;
 def err_arc_objc_object_in_struct : Error<
-  "ARC forbids Objective-C objects in structs or unions">;
+  "ARC forbids %select{Objective-C objects|blocks}0 in structs or unions">;
 def err_arc_objc_property_default_assign_on_object : Error<
   "ARC forbids synthesizing a property of an Objective-C object "
   "with unspecified ownership or storage attribute">;
@@ -2944,6 +3295,9 @@
   "ARC forbids use of %0 in a @selector">;
 def err_arc_illegal_method_def : Error<
   "ARC forbids implementation of %0">;
+ =20
+} // end "ARC Restrictions" category
+ =20
 def err_arc_lost_method_convention : Error<
   "method was declared as %select{an 'alloc'|a 'copy'|an 'init'|a 'new'}0 "
   "method, but its implementation doesn't match because %select{"
@@ -2956,8 +3310,10 @@
   "declaration in interface is not in the '%select{alloc|copy|init|new}0' "
   "family because %select{its result type is not an object pointer|"
   "its result type is unrelated to its receiver type}1">;
-def err_typecheck_arr_assign_self : Error<
+def err_typecheck_arc_assign_self : Error<
   "cannot assign to 'self' outside of a method in the init family">;
+def err_typecheck_arc_assign_self_class_method : Error<
+  "cannot assign to 'self' in a class method">;
 def err_typecheck_arr_assign_enumeration : Error<
   "fast enumeration variables can't be modified in ARC by default; "
   "declare the variable __strong to allow this">;
@@ -2988,6 +3344,9 @@
 def err_arc_autoreleasing_var : Error<
   "%select{__block variables|global variables|fields|ivars}0 cannot have "
   "__autoreleasing ownership">;
+def err_arc_autoreleasing_capture : Error<
+  "cannot capture __autoreleasing variable in a "
+  "%select{block|lambda by copy}0">;
 def err_arc_thread_ownership : Error<
   "thread-local variable has non-trivial ownership: type is %0">;
 def err_arc_indirect_no_ownership : Error<
@@ -3011,17 +3370,26 @@
   "no visible @interface for %0 declares the selector %1">;
 def err_arc_receiver_forward_instance : Error<
   "receiver type %0 for instance message is a forward declaration">;
+def warn_receiver_forward_instance : Warning<
+  "receiver type %0 for instance message is a forward declaration">,
+  InGroup<DiagGroup<"receiver-forward-class">>, DefaultIgnore;
 def err_arc_collection_forward : Error<
   "collection expression type %0 is a forward declaration">;
 def err_arc_multiple_method_decl : Error<=20
   "multiple methods named %0 found with mismatched result, "
   "parameter type or attributes">;
+
+let CategoryName =3D "ARC Retain Cycle" in {
+
 def warn_arc_retain_cycle : Warning<
   "capturing %0 strongly in this block is likely to lead to a retain cycle=
">,
   InGroup<ARCRetainCycles>;
 def note_arc_retain_cycle_owner : Note<
   "block will be retained by %select{the captured object|an object strongl=
y "
   "retained by the captured object}0">;
+
+} // end "ARC Retain Cycle" category
+
 def note_nontrivial_objc_ownership : Note<
   "because type %0 has %select{no|no|__strong|__weak|__autoreleasing}1 "
   "ownership">;
@@ -3029,6 +3397,8 @@
   "%select{destination for|source of}0 this %1 call is a pointer to "
   "ownership-qualified type %2">, InGroup<ARCNonPodMemAccess>;
=20
+let CategoryName =3D "ARC and @properties" in {
+
 def err_arc_strong_property_ownership : Error<
   "existing ivar %1 for strong property %0 may not be "
   "%select{|__unsafe_unretained||__weak}2">;
@@ -3038,10 +3408,15 @@
 def err_arc_inconsistent_property_ownership : Error<
   "%select{|unsafe_unretained|strong|weak}1 property %0 may not also be "
   "declared %select{|__unsafe_unretained|__strong|__weak|__autoreleasing}2=
">;
+
+} // end "ARC and @properties" category
+
 def err_arc_atomic_ownership : Error<
   "cannot perform atomic operation on a pointer to type %0: type has "
   "non-trivial ownership">;
=20
+let CategoryName =3D "ARC Casting Rules" in {
+
 def err_arc_bridge_cast_incompatible : Error<
   "incompatible types casting %0 to %1 with a %select{__bridge|"
   "__bridge_transfer|__bridge_retained}2 cast">;
@@ -3050,14 +3425,19 @@
   "%select{Objective-C|block|C}2 pointer type %3 cannot use %select{__brid=
ge|"
   "__bridge_transfer|__bridge_retained}4">;
 def err_arc_cast_requires_bridge : Error<
-  "cast of %select{Objective-C|block|C}0 pointer type %1 to "
-  "%select{Objective-C|block|C}2 pointer type %3 requires a bridged cast">;
+  "%select{cast|implicit conversion}0 of %select{Objective-C|block|C}1 "
+  "pointer type %2 to %select{Objective-C|block|C}3 pointer type %4 "
+  "requires a bridged cast">;
 def note_arc_bridge : Note<
   "use __bridge to convert directly (no change in ownership)">;
 def note_arc_bridge_transfer : Note<
-  "use __bridge_transfer to transfer ownership of a +1 %0 into ARC">;
+  "use %select{__bridge_transfer|CFBridgingRelease call}1 to transfer "
+  "ownership of a +1 %0 into ARC">;
 def note_arc_bridge_retained : Note<
-  "use __bridge_retained to make an ARC object available as a +1 %0">;
+  "use %select{__bridge_retained|CFBridgingRetain call}1 to make an "
+  "ARC object available as a +1 %0">;
+
+} // ARC Casting category
=20
 } // ARC category name
=20
@@ -3086,15 +3466,11 @@
 def err_mempointer_in_nonclass_type : Error<
   "member pointer refers into non-class type %0">;
 def err_reference_to_void : Error<"cannot form a reference to 'void'">;
-def err_qualified_block_pointer_type : Error<
-  "qualifier specification on block pointer type not allowed">;
 def err_nonfunction_block_type : Error<
   "block pointer to non-function type is invalid">;
 def err_return_block_has_expr : Error<"void block should not return a valu=
e">;
 def err_block_return_missing_expr : Error<
   "non-void block should return a value">;
-def err_block_with_return_type_requires_args : Error<
-  "block with explicit return type requires argument list">;
 def err_func_def_incomplete_result : Error<
   "incomplete result type %0 in function definition">;
 def err_atomic_specifier_bad_type : Error<
@@ -3105,9 +3481,6 @@
 // Expressions.
 def ext_sizeof_function_type : Extension<
   "invalid application of 'sizeof' to a function type">, InGroup<PointerAr=
ith>;
-def err_sizeof_alignof_overloaded_function_type : Error<
-  "invalid application of '%select{sizeof|__alignof|vec_step}0' to an "
-  "overloaded function">;
 def ext_sizeof_void_type : Extension<
   "invalid application of '%select{sizeof|__alignof|vec_step}0' to a void "
   "type">, InGroup<PointerArith>;
@@ -3124,7 +3497,8 @@
   "offsetof requires struct, union, or class type, %0 invalid">;
 def err_offsetof_array_type : Error<"offsetof requires array type, %0 inva=
lid">;
 def ext_offsetof_extended_field_designator : Extension<
-  "using extended field designator is an extension">;
+  "using extended field designator is an extension">,
+  InGroup<DiagGroup<"extended-offsetof">>;
 def warn_offsetof_non_pod_type : ExtWarn<"offset of on non-POD type %0">,
   InGroup<InvalidOffsetof>;
 def err_offsetof_bitfield : Error<"cannot compute offset of bit-field %0">;
@@ -3185,6 +3559,12 @@
   "explicitly assigning a variable of type %0 to itself">,
   InGroup<SelfAssignment>, DefaultIgnore;
=20
+def warn_string_plus_int : Warning<
+  "adding %0 to a string does not append to the string">,
+  InGroup<StringPlusInt>;
+def note_string_plus_int_silence : Note<
+  "use array indexing to silence this warning">;
+
 def warn_sizeof_array_param : Warning<
   "sizeof on array function parameter will return size of %0 instead of %1=
">,
   InGroup<SizeofArrayArgument>;
@@ -3232,7 +3612,7 @@
   "cannot refer to member %0 in %1 with '%select{.|->}2'">;
 def err_member_reference_needs_call : Error<
   "base of member reference is a function; perhaps you meant to call "
-  "it%select{| with no arguments}?">;
+  "it%select{| with no arguments}0?">;
 def warn_subscript_is_char : Warning<"array subscript is of type 'char'">,
   InGroup<CharSubscript>, DefaultIgnore;
=20
@@ -3244,6 +3624,11 @@
 def note_non_instantiated_member_here : Note<
   "not-yet-instantiated member is declared here">;
=20
+def err_enumerator_does_not_exist : Error<
+  "enumerator %0 does not exist in instantiation of %1">;
+def note_enum_specialized_here : Note<
+  "enum %0 was explicitly specialized here">;
+
 def err_member_redeclared : Error<"class member cannot be redeclared">;
 def err_member_name_of_class : Error<"member %0 has the same name as its c=
lass">;
 def err_member_def_undefined_record : Error<
@@ -3252,13 +3637,11 @@
   "out-of-line definition of %0 does not match any declaration in %1">;
 def err_member_def_does_not_match_suggest : Error<
   "out-of-line definition of %0 does not match any declaration in %1; "
-  "did you mean %2">;
+  "did you mean %2?">;
 def err_member_def_does_not_match_ret_type : Error<
   "out-of-line definition of %q0 differs from the declaration in the retur=
n type">;
 def err_nonstatic_member_out_of_line : Error<
   "non-static data member defined out-of-line">;
-def err_nonstatic_flexible_variable : Error<
-  "non-static initialization of a variable with flexible array member">;
 def err_qualified_typedef_declarator : Error<
   "typedef declarator cannot be qualified">;
 def err_qualified_param_declarator : Error<
@@ -3313,7 +3696,11 @@
   "cannot initialize array of type %0 with non-constant array of type %1">;
 def ext_array_init_copy : Extension<
   "initialization of an array of type %0 from a compound literal of type %=
1 is "
-  "a GNU extension">;
+  "a GNU extension">, InGroup<GNU>;
+// This is intentionally not disabled by -Wno-gnu.
+def ext_array_init_parens : ExtWarn<
+  "parenthesized initialization of a member array is a GNU extension">,
+  InGroup<DiagGroup<"gnu-array-member-paren-init">>, DefaultError;
 def warn_deprecated_string_literal_conversion : Warning<
   "conversion from string literal to %0 is deprecated">, InGroup<Deprecate=
dWritableStr>;
 def err_realimag_invalid_type : Error<"invalid type %0 to %1 operator">;
@@ -3355,14 +3742,10 @@
   "behavior.">,
   InGroup<DiagGroup<"undefined-reinterpret-cast">>, DefaultIgnore;
=20
-def err_assignment_requires_nonfragile_object : Error<
-  "cannot assign to class object in non-fragile ABI (%0 invalid)">;
-def err_direct_interface_unsupported : Error<
-  "indirection to an interface is not supported (%0 invalid)">;
+def err_objc_object_assignment : Error<
+  "cannot assign to class object (%0 invalid)">;
 def err_typecheck_invalid_operands : Error<
   "invalid operands to binary expression (%0 and %1)">;
-def err_typecheck_sub_ptr_object : Error<
-  "subtraction of pointer %0 requires pointee to be a complete object type=
">;
 def err_typecheck_sub_ptr_compatible : Error<
   "%0 and %1 are not pointers to compatible types">;
 def ext_typecheck_ordered_comparison_of_pointer_integer : ExtWarn<
@@ -3383,13 +3766,13 @@
   "comparison of distinct pointer types (%0 and %1)">;
 def ext_typecheck_cond_incompatible_operands : ExtWarn<
   "incompatible operand types (%0 and %1)">;
+def err_cond_voidptr_arc : Error <
+  "operands to conditional of types %0 and %1 are incompatible in ARC mode=
">;
 def err_typecheck_comparison_of_distinct_pointers : Error<
   "comparison of distinct pointer types (%0 and %1)">;
 def ext_typecheck_comparison_of_distinct_pointers_nonstandard : ExtWarn<
   "comparison of distinct pointer types (%0 and %1) uses non-standard "
   "composite pointer type %2">;
-def err_typecheck_vector_comparison : Error<
-  "comparison of vector types (%0 and %1) not supported yet">;
 def err_typecheck_assign_const : Error<"read-only variable is not assignab=
le">;
 def err_stmtexpr_file_scope : Error<
   "statement expression not allowed at file scope">;
@@ -3414,26 +3797,15 @@
   InGroup<DiagGroup<"null-arithmetic">>;
=20
 def err_invalid_this_use : Error<
-  "invalid use of 'this' outside of a nonstatic member function">;
+  "invalid use of 'this' outside of a non-static member function">;
 def err_invalid_member_use_in_static_method : Error<
   "invalid use of member %0 in static member function">;
 def err_invalid_qualified_function_type : Error<
-  "type qualifier is not allowed on this function">;
-def err_invalid_ref_qualifier_function_type : Error<
-  "ref-qualifier '%select{&&|&}0' is only allowed on non-static member fun=
ctions,"
-  " member function pointers, and typedefs of function types">;
-def ext_qualified_function_type_template_arg : ExtWarn<
-  "template argument of '%0' qualified function type is a GNU extension">,=20
-  InGroup<GNU>;
-
-def err_invalid_qualified_function_pointer : Error<
-  "type qualifier is not allowed on this function %select{pointer|referenc=
e}0">;
-def err_invalid_qualified_typedef_function_type_use : Error<
-  "a qualified function type cannot be used to declare a "
-  "%select{static member|nonmember}0 function">;
-def err_invalid_ref_qualifier_typedef_function_type_use : Error<
-  "%select{static member|nonmember}0 function cannot have a ref-qualifier "
-  "'%select{&&|&}1'">;
+  "%select{static |non-}0member function %select{of type %2 |}1"
+  "cannot have '%3' qualifier">;
+def err_compound_qualified_function_type : Error<
+  "%select{block pointer|pointer|reference}0 to function type %select{%2 |=
}1"
+  "cannot have '%3' qualifier">;
=20
 def err_ref_qualifier_overload : Error<
   "cannot overload a member function %select{without a ref-qualifier|with "
@@ -3441,13 +3813,17 @@
   "without a ref-qualifier|with ref-qualifier '&'|with ref-qualifier '&&'}=
1">;
=20
 def err_invalid_non_static_member_use : Error<
-  "invalid use of nonstatic data member %0">;
+  "invalid use of non-static data member %0">;
+def err_nested_non_static_member_use : Error<
+  "%select{call to non-static member function|use of non-static data membe=
r}0 "
+  "%2 of %1 from nested type %3">;
+def warn_cxx98_compat_non_static_member_use : Warning<
+  "use of non-static data member %0 in an unevaluated context is "
+  "incompatible with C++98">, InGroup<CXX98Compat>, DefaultIgnore;
 def err_invalid_incomplete_type_use : Error<
   "invalid use of incomplete type %0">;
 def err_builtin_func_cast_more_than_one_arg : Error<
   "function-style cast to a builtin type can only take one argument">;
-def err_builtin_direct_init_more_than_one_arg : Error<
-  "initializer of a builtin type can only take one argument">;
 def err_value_init_for_array_type : Error<
   "array types cannot be value-initialized">;
 def warn_format_nonliteral_noargs : Warning<
@@ -3470,13 +3846,43 @@
   "%0 is not a valid property name (accessing an object of type %1)">;
 def err_getter_not_found : Error<
   "expected getter method not found on object of type %0">;
+def err_objc_subscript_method_not_found : Error<
+  "expected method to %select{read|write}1 %select{dictionary|array}2 elem=
ent not "
+  "found on object of type %0">;
+def err_objc_subscript_index_type : Error<
+  "method index parameter type %0 is not integral type">;
+def err_objc_subscript_key_type : Error<
+  "method key parameter type %0 is not object type">;
+def err_objc_subscript_dic_object_type : Error<
+  "method object parameter type %0 is not object type">;
+def err_objc_subscript_object_type : Error<
+  "cannot assign to this %select{dictionary|array}1 because assigning meth=
od's 2nd parameter"
+  " of type %0 is not an objective-C pointer type">;
+def err_objc_subscript_base_type : Error<
+  "%select{dictionary|array}1 subscript base type %0 is not an Objective-C=
 object">;
+def err_objc_multiple_subscript_type_conversion : Error<
+  "indexing expression is invalid because subscript type %0 has "
+  "multiple type conversion functions">;
+def err_objc_subscript_type_conversion : Error<
+  "indexing expression is invalid because subscript type %0 is not an inte=
gral"
+  " or objective-C pointer type">;
+def err_objc_subscript_pointer : Error<
+  "indexing expression is invalid because subscript type %0 is not an"
+  " objective-C pointer">;
+def err_objc_indexing_method_result_type : Error<
+  "method for accessing %select{dictionary|array}1 element must have Objec=
tive-C"
+  " object return type instead of %0">;
+def err_objc_index_incomplete_class_type : Error<
+  "objective-C index expression has incomplete class type %0">;
+def err_illegal_container_subscripting_op : Error<
+  "illegal operation on objective-c container subscripting">;
 def err_property_not_found_forward_class : Error<
   "property %0 cannot be found in forward class object %1">;
 def err_property_not_as_forward_class : Error<
   "property %0 refers to an incomplete Objective-C class %1 "
   "(with no @interface available)">;
 def note_forward_class : Note<
-  "forward class is declared here">;
+  "forward declaration of class here">;
 def err_duplicate_property : Error<
   "property has a previous declaration">;
 def ext_gnu_void_ptr : Extension<
@@ -3486,16 +3892,22 @@
   "arithmetic on%select{ a|}0 pointer%select{|s}0 to%select{ the|}2 functi=
on "
   "type%select{|s}2 %1%select{| and %3}2 is a GNU extension">,
   InGroup<PointerArith>;
-def error_readonly_property_assignment : Error<
-  "assigning to property with 'readonly' attribute not allowed">;
 def error_readonly_message_assignment : Error<
   "assigning to 'readonly' return result of an objective-c message not all=
owed">;
 def ext_integer_increment_complex : Extension<
   "ISO C does not support '++'/'--' on complex integer type %0">;
 def ext_integer_complement_complex : Extension<
   "ISO C does not support '~' for complex conjugation of %0">;
-def error_nosetter_property_assignment : Error<
-  "setter method is needed to assign to object using property" " assignmen=
t syntax">;
+def err_nosetter_property_assignment : Error<
+  "%select{assignment to readonly property|"
+  "no setter method %1 for assignment to property}0">;
+def err_nosetter_property_incdec : Error<
+  "%select{%select{increment|decrement}1 of readonly property|"
+  "no setter method %2 for %select{increment|decrement}1 of property}0">;
+def err_nogetter_property_compound_assignment : Error<
+  "a getter method is needed to perform a compound assignment on a propert=
y">;
+def err_nogetter_property_incdec : Error<
+  "no getter method %1 for %select{increment|decrement} of property">;
 def error_no_subobject_property_setting : Error<
   "expression is not assignable">;
 def err_qualified_objc_access : Error<
@@ -3553,8 +3965,6 @@
   "'register' storage specifier on @catch parameter will be ignored">;
 def err_qualified_objc_catch_parm : Error<
   "@catch parameter declarator cannot be qualified">;
-def err_objc_pointer_cxx_catch_gnu : Error<
-  "can't catch Objective C exceptions in C++ in the GNU runtime">;
 def warn_objc_pointer_cxx_catch_fragile : Warning<
   "can not catch an exception thrown with @throw in C++ in the non-unified=
 "
   "exception model">, InGroup<ObjCNonUnifiedException>;
@@ -3566,12 +3976,12 @@
 def warn_setter_getter_impl_required : Warning<
   "property %0 requires method %1 to be defined - "
   "use @synthesize, @dynamic or provide a method implementation "
-  "in this class implementation">;
+  "in this class implementation">,
+  InGroup<ObjCPropertyImpl>;
 def warn_setter_getter_impl_required_in_category : Warning<
   "property %0 requires method %1 to be defined - "
-  "use @dynamic or provide a method implementation in this category">;
-def note_property_impl_required : Note<
-  "implementation is here">;
+  "use @dynamic or provide a method implementation in this category">,
+  InGroup<ObjCPropertyImpl>;
 def note_parameter_named_here : Note<
   "passing argument to parameter %0 here">;
 def note_parameter_here : Note<
@@ -3604,6 +4014,9 @@
   "which is not a reference, pointer-to-object, or pointer-to-data-member"=
>;
 def ext_cast_fn_obj : Extension<
   "cast between pointer-to-function and pointer-to-object is an extension"=
>;
+def warn_cxx98_compat_cast_fn_obj : Warning<
+  "cast between pointer-to-function and pointer-to-object is incompatible =
with C++98">,
+  InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def err_bad_reinterpret_cast_small_int : Error<
   "cast from pointer to smaller type %2 loses information">;
 def err_bad_cxx_cast_vector_to_scalar_different_size : Error<
@@ -3625,7 +4038,6 @@
 def err_bad_cxx_cast_member_pointer_size : Error<
   "cannot %select{||reinterpret_cast||C-style cast|}0 from member pointer "
   "type %1 to member pointer type %2 of different size">;
-def err_bad_static_cast_incomplete : Error<"%0 is an incomplete type">;
 def err_bad_reinterpret_cast_reference : Error<
   "reinterpret_cast of a %0 to %1 needs its address which is not allowed">;
 def warn_undefined_reinterpret_cast : Warning<
@@ -3675,7 +4087,8 @@
   "'new' expression with placement arguments refers to non-placement "
   "'operator delete'">;
 def err_array_size_not_integral : Error<
-  "array size expression must have integral or enumerated type, not %0">;
+  "array size expression must have integral or %select{|unscoped }0"
+  "enumeration type, not %1">;
 def err_array_size_incomplete_type : Error<
   "array size expression has incomplete class type %0">;
 def err_array_size_explicit_conversion : Error<
@@ -3689,6 +4102,10 @@
   "implicit conversion from array size expression of type %0 to "
   "%select{integral|enumeration}1 type %2 is a C++11 extension">,
   InGroup<CXX11>;
+def warn_cxx98_compat_array_size_conversion : Warning<
+  "implicit conversion from array size expression of type %0 to "
+  "%select{integral|enumeration}1 type %2 is incompatible with C++98">,
+  InGroup<CXX98CompatPedantic>, DefaultIgnore;
 def err_address_space_qualified_new : Error<
   "'new' cannot allocate objects of type %0 in address space '%1'">;
 def err_address_space_qualified_delete : Error<
@@ -3703,7 +4120,8 @@
 def err_ambiguous_delete_operand : Error<"ambiguous conversion of delete "
                                          "expression of type %0 to a point=
er">;
 def warn_delete_incomplete : Warning<
-  "deleting pointer to incomplete type %0 may cause undefined behaviour">;
+  "deleting pointer to incomplete type %0 may cause undefined behaviour">,
+  InGroup<DiagGroup<"delete-incomplete">>;
 def err_delete_incomplete_class_type : Error<
   "deleting incomplete class type %0; no conversions to pointer type">;
 def warn_delete_array_type : Warning<
@@ -3717,10 +4135,10 @@
 def err_decrement_bool : Error<"cannot decrement expression of type bool">;
 def warn_increment_bool : Warning<
   "incrementing expression of type bool is deprecated">, InGroup<Deprecate=
d>;
-def ext_catch_incomplete_ptr : ExtWarn<
-  "ISO C++ forbids catching a pointer to incomplete type %0">;
-def ext_catch_incomplete_ref : ExtWarn<
-  "ISO C++ forbids catching a reference to incomplete type %0">;
+def err_catch_incomplete_ptr : Error<
+  "cannot catch pointer to incomplete type %0">;
+def err_catch_incomplete_ref : Error<
+  "cannot catch reference to incomplete type %0">;
 def err_catch_incomplete : Error<"cannot catch incomplete type %0">;
 def err_catch_rvalue_ref : Error<"cannot catch exceptions by rvalue refere=
nce">;
 def err_qualified_catch_declarator : Error<
@@ -3728,8 +4146,6 @@
 def err_early_catch_all : Error<"catch-all handler must come last">;
 def err_bad_memptr_rhs : Error<
   "right hand operand to %0 has non pointer-to-member type %1">;
-def err_memptr_rhs_to_incomplete : Error<
-  "cannot dereference pointer into incomplete class type %0">;
 def err_bad_memptr_lhs : Error<
   "left hand operand to %0 must be a %select{|pointer to }1class "
   "compatible with the right hand operand, but is %2">;
@@ -3757,6 +4173,10 @@
 def warn_using_directive_in_header : Warning<
   "using namespace directive in global context in header">,
   InGroup<HeaderHygiene>, DefaultIgnore;
+def warn_overaligned_type : Warning<
+  "type %0 requires %1 bytes of alignment and the default allocator only "
+  "guarantees %2 bytes">,
+  InGroup<OveralignedType>, DefaultIgnore;
=20
 def err_conditional_void_nonvoid : Error<
   "%select{left|right}1 operand to ? is void, but %select{right|left}1 ope=
rand "
@@ -3775,11 +4195,79 @@
 def err_return_in_constructor_handler : Error<
   "return in the catch of a function try block of a constructor is illegal=
">;
=20
+let CategoryName =3D "Lambda Issue" in {
+  def err_capture_more_than_once : Error<
+    "%0 can appear only once in a capture list">;
+  def err_reference_capture_with_reference_default : Error<
+    "'&' cannot precede a capture when the capture default is '&'">;
+  def err_this_capture_with_copy_default : Error<
+    "'this' cannot be explicitly captured when the capture default is '=3D=
'">;
+  def err_copy_capture_with_copy_default : Error<
+    "'&' must precede a capture when the capture default is '=3D'">;
+  def err_capture_does_not_name_variable : Error<
+    "%0 in capture list does not name a variable">;
+  def err_capture_non_automatic_variable : Error<
+    "%0 cannot be captured because it does not have automatic storage "
+    "duration">;
+  def err_this_capture : Error<
+    "'this' cannot be %select{implicitly |}0captured in this context">;
+  def err_lambda_capture_block : Error<
+    "__block variable %0 cannot be captured in a lambda expression">;
+  def err_lambda_capture_anonymous_var : Error<
+    "unnamed variable cannot be implicitly captured in a lambda expression=
">;
+  def err_lambda_capture_vm_type : Error<
+    "variable %0 with variably modified type cannot be captured in "
+    "a lambda expression">;
+  def err_lambda_impcap : Error<
+    "variable %0 cannot be implicitly captured in a lambda with no "
+    "capture-default specified">;
+  def note_lambda_decl : Note<"lambda expression begins here">;
+  def err_lambda_unevaluated_operand : Error<
+    "lambda expression in an unevaluated operand">;
+  def ext_lambda_implies_void_return : ExtWarn<
+    "C++11 requires lambda with omitted result type to consist of a single=
 "
+    "return statement">,
+    InGroup<LambdaExtensions>;
+  def err_lambda_return_init_list : Error<
+    "cannot deduce lambda return type from initializer list">;
+  def err_lambda_capture_default_arg : Error<
+    "lambda expression in default argument cannot capture any entity">;
+  def err_lambda_unexpanded_pack : Error<
+    "unexpanded function parameter pack capture is unsupported">;
+  def err_lambda_incomplete_result : Error<
+    "incomplete result type %0 in lambda expression">;
+  def err_lambda_objc_object_result : Error<
+    "non-pointer Objective-C class type %0 in lambda expression result">;
+  def ext_lambda_default_arguments : ExtWarn<
+    "C++11 forbids default arguments for lambda expressions">,
+    InGroup<LambdaExtensions>;
+  def err_noreturn_lambda_has_return_expr : Error<
+    "lambda declared 'noreturn' should not return">;
+  def warn_maybe_falloff_nonvoid_lambda : Warning<
+    "control may reach end of non-void lambda">,
+    InGroup<ReturnType>;
+  def warn_falloff_nonvoid_lambda : Warning<
+    "control reaches end of non-void lambda">,
+    InGroup<ReturnType>;
+  def err_access_lambda_capture : Error<
+    // The ERRORs represent other special members that aren't constructors=
, in
+    // hopes that someone will bother noticing and reporting if they appear
+    "capture of variable '%0' as type %1 calls %select{private|protected}3=
 "
+    "%select{default |copy |move |*ERROR* |*ERROR* |*ERROR* |}2constructor=
">,
+    AccessControl;
+  def note_lambda_to_block_conv : Note<
+    "implicit capture of lambda object due to conversion to block pointer "
+    "here">;
+}
+
 def err_operator_arrow_circular : Error<
   "circular pointer delegation detected">;
 def err_pseudo_dtor_base_not_scalar : Error<
   "object expression of non-scalar type %0 cannot be used in a "
   "pseudo-destructor expression">;
+def ext_pseudo_dtor_on_void : ExtWarn<
+  "pseudo-destructors on type void are a Microsoft extension">,
+  InGroup<Microsoft>;
 def err_pseudo_dtor_type_mismatch : Error<
   "the type of object expression (%0) does not match the type being destro=
yed "
   "(%1) in pseudo-destructor expression">;
@@ -3791,9 +4279,6 @@
 def err_pseudo_dtor_destructor_non_type : Error<
   "%0 does not refer to a type name in pseudo-destructor expression; expec=
ted "
   "the name of type %1">;
-def err_pseudo_dtor_template : Error<
-  "specialization of template %0 does not refer to a scalar type in pseudo=
-"
-  "destructor expression">;
 def err_invalid_use_of_function_type : Error<
   "a function type is not allowed here">;
 def err_invalid_use_of_array_type : Error<"an array type is not allowed he=
re">;
@@ -3809,10 +4294,10 @@
   "conversion function from %0 to %1 invokes a deleted function">;
  =20
 def err_expected_class_or_namespace : Error<"expected a class or namespace=
">;
-def err_missing_qualified_for_redecl : Error<
-  "must qualify the name %0 to declare %q1 in this scope">;
-def err_invalid_declarator_scope : Error<
-  "definition or redeclaration of %0 not in a namespace enclosing %1">;
+def err_expected_class : Error<"%0 is not a class%select{ or namespace|, "
+  "namespace, or scoped enumeration}1">;
+def err_invalid_declarator_scope : Error<"cannot define or redeclare %0 he=
re "
+  "because namespace %1 does not enclose namespace %2">;
 def err_invalid_declarator_global_scope : Error<
   "definition or redeclaration of %0 cannot name the global scope">;
 def err_invalid_declarator_in_function : Error<
@@ -3824,8 +4309,6 @@
   "cannot form a pointer-to-member to member %0 of reference type %1">;
 def err_incomplete_object_call : Error<
   "incomplete type in call to object of type %0">;
-def err_incomplete_pointer_to_member_return : Error<
-  "incomplete return type %0 of pointer-to-member constant">;
=20
 def warn_condition_is_assignment : Warning<"using the result of an "
   "assignment as a condition without parentheses">,
@@ -3848,12 +4331,6 @@
 def note_equality_comparison_silence : Note<
   "remove extraneous parentheses around the comparison to silence this war=
ning">;
=20
-def warn_synthesized_ivar_access : Warning<
-  "direct access of synthesized ivar by using property access %0">,
-  InGroup<NonfragileAbi2>, DefaultIgnore;
-
-def note_global_declared_at : Note<"global variable declared here">;
-
 // assignment related diagnostics (also for argument passing, returning, e=
tc).
 // In most of these diagnostics the %2 is a value from the
 // Sema::AssignmentAction enumeration
@@ -3863,11 +4340,24 @@
   "%select{from incompatible type|to parameter of incompatible type|"
   "from a function with incompatible result type|to incompatible type|"
   "with an expression of incompatible type|to parameter of incompatible ty=
pe|"
-  "to incompatible type}2 %1; "
-  "%select{|dereference with *|"
-  "take the address with &|"
-  "remove *|"
-  "remove &}3">;
+  "to incompatible type}2 %1"
+  "%select{|; dereference with *|"
+  "; take the address with &|"
+  "; remove *|"
+  "; remove &}3"
+  "%select{|: different classes (%5 vs %6)"
+  "|: different number of parameters (%5 vs %6)"
+  "|: type mismatch at %ordinal5 parameter (%6 vs %7)"
+  "|: different return type (%5 vs %6)"
+  "|: different qualifiers ("
+  "%select{none|const|restrict|const and restrict|volatile|const and volat=
ile|"
+  "volatile and restrict|const, volatile, and restrict}5 vs "
+  "%select{none|const|restrict|const and restrict|volatile|const and volat=
ile|"
+  "volatile and restrict|const, volatile, and restrict}6)}4">;
+def err_typecheck_missing_return_type_incompatible : Error<
+  "return type %0 must match previous return type %1 when %select{block "
+  "literal|lambda expression}2 has unspecified explicit return type">;
+
 def warn_incompatible_qualified_id : Warning<
   "%select{assigning to|passing|returning|converting|initializing|sending|=
casting}2"
   " %0 "
@@ -3880,21 +4370,23 @@
   "%select{assigning to|passing|returning|converting|initializing|sending|=
casting}2"
   " %0 "
   "%select{from|to parameter of type|from a function with result type|to t=
ype|"
-  "with an expression of type|to parameter of type|to type}2 %1; "
-  "%select{|dereference with *|"
-  "take the address with &|"
-  "remove *|"
-  "remove &}3">;
+  "with an expression of type|to parameter of type|to type}2 %1"
+  "%select{|; dereference with *|"
+  "; take the address with &|"
+  "; remove *|"
+  "; remove &}3">,
+  InGroup<IntConversion>;
 def ext_typecheck_convert_int_pointer : ExtWarn<
   "incompatible integer to pointer conversion "
   "%select{assigning to|passing|returning|converting|initializing|sending|=
casting}2"
   " %0 "
   "%select{from|to parameter of type|from a function with result type|to t=
ype|"
-  "with an expression of type|to parameter of type|to type}2 %1; "
-  "%select{|dereference with *|"
-  "take the address with &|"
-  "remove *|"
-  "remove &}3">;
+  "with an expression of type|to parameter of type|to type}2 %1"
+  "%select{|; dereference with *|"
+  "; take the address with &|"
+  "; remove *|"
+  "; remove &}3">,
+  InGroup<IntConversion>;
 def ext_typecheck_convert_pointer_void_func : Extension<
   "%select{assigning to|passing|returning|converting|initializing|sending|=
casting}2"
   " %0 "
@@ -3914,10 +4406,10 @@
   " %0 "
   "%select{from|to parameter of type|from a function with result type|to t=
ype|"
   "with an expression of type|to parameter of type|to type}2 %1"
-  "%select{|dereference with *|"
-  "take the address with &|"
-  "remove *|"
-  "remove &}3">,
+  "%select{|; dereference with *|"
+  "; take the address with &|"
+  "; remove *|"
+  "; remove &}3">,
   InGroup<IncompatiblePointerTypes>;
 def ext_typecheck_convert_discards_qualifiers : ExtWarn<
   "%select{assigning to|passing|returning|converting|initializing|sending|=
casting}2"
@@ -3939,7 +4431,7 @@
   " %0 "
   "%select{from|to parameter of type|from a function with result type|to t=
ype|"
   "with an expression of type|to parameter of type|to type}2 %1">,
-  InGroup<VectorConversions>, DefaultIgnore;
+  InGroup<VectorConversion>, DefaultIgnore;
 def err_int_to_block_pointer : Error<
   "invalid block pointer conversion "
   "%select{assigning to|passing|returning|converting|initializing|sending|=
casting}2"
@@ -3970,8 +4462,6 @@
   "|sending %0 to parameter of type %1"
   "|casting %0 to type %1}2"
   " changes retain/release properties of pointer">;
-def err_typecheck_convert_ambiguous : Error<
-  "ambiguity in initializing value of type %0 with initializer of type %1"=
>;
 def err_typecheck_comparison_of_distinct_blocks : Error<
   "comparison of distinct block types (%0 and %1)">;
=20
@@ -3990,6 +4480,8 @@
   "vector is not assignable (contains duplicate components)">;
 def err_block_decl_ref_not_modifiable_lvalue : Error<
   "variable is not assignable (missing __block type specifier)">;
+def err_lambda_decl_ref_not_modifiable_lvalue : Error<
+  "cannot assign to a variable captured by copy in a non-mutable lambda">;
 def err_typecheck_call_not_function : Error<
   "called object type %0 is not a function or function pointer">;
 def err_call_incomplete_return : Error<
@@ -4018,6 +4510,8 @@
   "expected at most %1, have %2">;
 def note_callee_decl : Note<
   "%0 declared here">;
+def note_defined_here : Note<"%0 defined here">;
+
 def warn_call_wrong_number_of_arguments : Warning<
   "too %select{few|many}0 arguments in call to %1">;
 def err_atomic_builtin_must_be_pointer : Error<
@@ -4031,12 +4525,15 @@
 def err_atomic_op_needs_atomic : Error<
   "first argument to atomic operation must be a pointer to _Atomic "
   "type (%0 invalid)">;
+def err_atomic_op_needs_trivial_copy : Error<
+  "first argument to atomic operation must be a pointer to a trivially-cop=
yable"
+  " type (%0 invalid)">;
 def err_atomic_op_needs_atomic_int_or_ptr : Error<
-  "first argument to atomic operation must be a pointer to atomic "
-  "integer or pointer (%0 invalid)">;
-def err_atomic_op_logical_needs_atomic_int : Error<
-  "first argument to logical atomic operation must be a pointer to atomic "
-  "integer (%0 invalid)">;
+  "first argument to atomic operation must be a pointer to %select{|atomic=
 }0"
+  "integer or pointer (%1 invalid)">;
+def err_atomic_op_bitwise_needs_atomic_int : Error<
+  "first argument to bitwise atomic operation must be a pointer to "
+  "%select{|atomic }0integer (%1 invalid)">;
=20
 def err_deleted_function_use : Error<"attempt to use a deleted function">;
=20
@@ -4061,6 +4558,10 @@
   "cannot pass object of %select{non-POD|non-trivial}0 type %1 through var=
iadic"
   " %select{function|block|method|constructor}2; call will abort at runtim=
e">,
   InGroup<DiagGroup<"non-pod-varargs">>, DefaultError;
+def warn_cxx98_compat_pass_non_pod_arg_to_vararg : Warning<
+  "passing object of trivial but non-POD type %0 through variadic"
+  " %select{function|block|method|constructor}1 is incompatible with C++98=
">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 def err_typecheck_call_invalid_ordered_compare : Error<
   "ordered compare requires two args of floating point type (%0 and %1)">;
@@ -4101,9 +4602,6 @@
   InGroup<DiagGroup<"conditional-type-mismatch">>;
 def err_typecheck_choose_expr_requires_constant : Error<
   "'__builtin_choose_expr' requires a constant expression">;
-def ext_typecheck_expression_not_constant_but_accepted : Extension<
-  "expression is not a constant, but is accepted as one by GNU extensions"=
>,=20
-  InGroup<GNU>;
 def warn_unused_expr : Warning<"expression result unused">,
   InGroup<UnusedValue>;
 def warn_unused_voidptr : Warning<
@@ -4112,6 +4610,9 @@
 def warn_unused_property_expr : Warning<
  "property access result unused - getters should not be used for side effe=
cts">,
   InGroup<UnusedValue>;
+def warn_unused_container_subscript_expr : Warning<
+ "container access result unused - container access should not be used for=
 side effects">,
+  InGroup<UnusedValue>;
 def warn_unused_call : Warning<
   "ignoring return value of function declared with %0 attribute">,
   InGroup<UnusedValue>;
@@ -4126,6 +4627,10 @@
=20
 def err_incomplete_type_used_in_type_trait_expr : Error<
   "incomplete type %0 used in type trait expression">;
+def err_type_trait_arity : Error<
+  "type trait requires %0%select{| or more}1 argument%select{|s}2; have "
+  "%3 argument%s3">;
+ =20
 def err_dimension_expr_not_constant_integer : Error<
   "dimension expression does not evaluate to a constant unsigned int">;
 def err_expected_ident_or_lparen : Error<"expected identifier or '('">;
@@ -4171,10 +4676,6 @@
=20
 def err_invalid_conversion_between_vector_and_scalar : Error<
   "invalid conversion between vector type %0 and scalar type %1">;
-def err_overload_expr_requires_non_zero_constant : Error<
-  "overload requires a non-zero constant expression as first argument">;
-def err_overload_incorrect_fntype : Error<
-  "argument is not a function, or has wrong number of parameters">;
=20
 // C++ member initializers.
 def err_only_constructors_take_base_inits : Error<
@@ -4183,7 +4684,7 @@
 def err_multiple_mem_initialization : Error <
   "multiple initializations given for non-static member %0">;
 def err_multiple_mem_union_initialization : Error <
-  "initializing multiple members of anonymous union">;
+  "initializing multiple members of union">;
 def err_multiple_base_initialization : Error <
   "multiple initializations given for base %0">;
=20
@@ -4219,16 +4720,19 @@
   "in-class initializer for static data member of type %0 requires "
   "'constexpr' specifier">;
 def err_in_class_initializer_non_constant : Error<
-  "in-class initializer is not a constant expression">;
+  "in-class initializer for static data member is not a constant expressio=
n">;
=20
 def ext_in_class_initializer_non_constant : Extension<
- "in-class initializer is not a constant expression, accepted as an extens=
ion">;
+  "in-class initializer for static data member is not a constant expressio=
n; "
+  "folding it to a constant is a GNU extension">;
=20
 // C++ anonymous unions and GNU anonymous structs/unions
 def ext_anonymous_union : Extension<
-  "anonymous unions are a GNU extension in C">, InGroup<GNU>;
-def ext_anonymous_struct : Extension<
+  "anonymous unions are a C11 extension">, InGroup<C11>;
+def ext_gnu_anonymous_struct : Extension<
   "anonymous structs are a GNU extension">, InGroup<GNU>;
+def ext_c11_anonymous_struct : Extension<
+  "anonymous structs are a C11 extension">, InGroup<C11>;
 def err_anonymous_union_not_static : Error<
   "anonymous unions at namespace or global scope must be declared 'static'=
">;
 def err_anonymous_union_with_storage_spec : Error<
@@ -4259,7 +4763,14 @@
=20
 // C++ local classes
 def err_reference_to_local_var_in_enclosing_function : Error<
-  "reference to local variable %0 declared in enclosed function %1">;
+  "reference to local variable %0 declared in enclosing function %1">;
+def err_reference_to_local_var_in_enclosing_block : Error<
+  "reference to local variable %0 declared in enclosing block literal">;
+def err_reference_to_local_var_in_enclosing_lambda : Error<
+  "reference to local variable %0 declared in enclosing lambda expression"=
>;
+def err_reference_to_local_var_in_enclosing_context : Error<
+  "reference to local variable %0 declared in enclosing context">;
+
 def note_local_variable_declared_here : Note<
   "%0 declared here">;
 def err_static_data_member_not_allowed_in_local_class : Error<
@@ -4283,14 +4794,6 @@
   "conversion from pointer to member of class %0 to pointer to member "
   "of class %1 via virtual base %2 is not allowed">;
=20
-// C++ access control
-def err_conv_to_inaccessible_base : Error<
-  "conversion from %0 to inaccessible base class %1">, AccessControl;
-def note_inheritance_specifier_here : Note<
-  "'%0' inheritance specifier here">;
-def note_inheritance_implicitly_private_here : Note<
-  "inheritance is implicitly 'private'">;
-
 // C++ member name lookup
 def err_ambiguous_member_multiple_subobjects : Error<
   "non-static member %0 found in multiple base-class subobjects of type %1=
:%2">;
@@ -4353,16 +4856,18 @@
 // C++ literal operators
 def err_literal_operator_outside_namespace : Error<
   "literal operator %0 must be in a namespace or global scope">;
+def err_literal_operator_default_argument : Error<
+  "literal operator cannot have a default argument">;
 // FIXME: This diagnostic sucks
 def err_literal_operator_params : Error<
   "parameter declaration for literal operator %0 is not valid">;
-def warn_user_literal_hexfloat : Warning<
-  "user-defined literal with suffix '%0' is preempted by C99 hexfloat "
-  "extension">, InGroup<UserDefinedLiterals>;
+def err_literal_operator_extern_c : Error<
+  "literal operator must have C++ linkage">;
 def warn_user_literal_reserved : Warning<
-  "user-defined literals not starting with '_' are reserved by the "
-  "implementation">, InGroup<UserDefinedLiterals>;
- =20
+  "user-defined literal suffixes not starting with '_' are reserved; "
+  "no literal will invoke this operator">,
+  InGroup<UserDefinedLiterals>;
+
 // C++ conversion functions
 def err_conv_function_not_member : Error<
   "conversion function must be a non-static member function">;
@@ -4391,8 +4896,11 @@
   "use of unary operator that may be intended as compound assignment (%0=
=3D)">;
=20
 // C++11 explicit conversion operators
-def warn_explicit_conversion_functions : Warning<
+def ext_explicit_conversion_functions : ExtWarn<
   "explicit conversion functions are a C++11 extension">, InGroup<CXX11>;
+def warn_cxx98_compat_explicit_conversion_functions : Warning<
+  "explicit conversion functions are incompatible with C++98">,
+  InGroup<CXX98Compat>, DefaultIgnore;
=20
 // C++11 defaulted functions
 def err_defaulted_default_ctor_params : Error<
@@ -4454,6 +4962,9 @@
   "copy constructor|move constructor|copy assignment operator|move assignm=
ent "
   "operator|destructor}0 does not match the "
   "calculated one">;
+def err_incorrect_defaulted_constexpr : Error<
+  "defaulted definition of %select{default constructor|copy constructor|"
+  "move constructor}0 is not constexpr">;
 def err_out_of_line_default_deletes : Error<
   "defaulting this %select{default constructor|copy constructor|move "
   "constructor|copy assignment operator|move assignment operator|destructo=
r}0 "
@@ -4467,10 +4978,10 @@
   "contains %1 element%s2)">,
   InGroup<DiagGroup<"array-bounds-pointer-arithmetic">>, DefaultIgnore;
 def warn_array_index_precedes_bounds : Warning<
-  "array index of '%0' indexes before the beginning of the array">,
+  "array index %0 is before the beginning of the array">,
   InGroup<DiagGroup<"array-bounds">>;
 def warn_array_index_exceeds_bounds : Warning<
-  "array index of '%0' indexes past the end of an array (that contains %1 "
+  "array index %0 is past the end of the array (which contains %1 "
   "element%s2)">, InGroup<DiagGroup<"array-bounds">>;
 def note_array_index_out_of_bounds : Note<
   "array %0 declared here">;
@@ -4492,7 +5003,7 @@
   "zero field width in scanf format string is unused">,
   InGroup<Format>;
 def warn_printf_conversion_argument_type_mismatch : Warning<
-  "conversion specifies type %0 but the argument has type %1">,
+  "format specifies type %0 but the argument has type %1">,
   InGroup<Format>;
 def warn_printf_positional_arg_exceeds_data_args : Warning <
   "data argument position '%0' exceeds the number of data arguments (%1)">,
@@ -4506,9 +5017,11 @@
 def warn_format_mix_positional_nonpositional_args : Warning<
   "cannot mix positional and non-positional arguments in format string">,
   InGroup<Format>;
-def warn_null_arg : Warning<
-  "null passed to a callee which requires a non-null argument">,
-  InGroup<NonNull>;
+def warn_static_array_too_small : Warning<
+  "array argument is too small; contains %0 elements, callee requires at l=
east %1">,
+  InGroup<DiagGroup<"array-bounds">>;
+def note_callee_static_array : Note<
+  "callee declares array parameter as static here">;
 def warn_empty_format_string : Warning<
   "format string is empty">, InGroup<FormatZeroLength>;
 def warn_format_string_is_wide_literal : Warning<
@@ -4529,13 +5042,26 @@
 def warn_format_nonsensical_length: Warning<
   "length modifier '%0' results in undefined behavior or no effect with '%=
1' conversion specifier">,
   InGroup<Format>;
+def warn_format_non_standard_positional_arg: ExtWarn<
+  "positional arguments are not supported by ISO C">, InGroup<FormatNonSta=
ndard>, DefaultIgnore;
+def warn_format_non_standard: ExtWarn<
+  "'%0' %select{length modifier|conversion specifier}1 is not supported by=
 ISO C">,
+  InGroup<FormatNonStandard>, DefaultIgnore;
+def warn_format_non_standard_conversion_spec: ExtWarn<
+  "using length modifier '%0' with conversion specifier '%1' is not suppor=
ted by ISO C">,
+  InGroup<FormatNonStandard>, DefaultIgnore;
 def warn_printf_ignored_flag: Warning<
   "flag '%0' is ignored when flag '%1' is present">,
   InGroup<Format>;
 def warn_scanf_scanlist_incomplete : Warning<
   "no closing ']' for '%%[' in scanf format string">,
   InGroup<Format>;
- =20
+def note_format_string_defined : Note<"format string is defined here">;
+=20
+def warn_null_arg : Warning<
+  "null passed to a callee which requires a non-null argument">,
+  InGroup<NonNull>;
+
 // CHECK: returning address/reference of stack memory
 def warn_ret_stack_addr : Warning<
   "address of stack memory associated with local variable %0 returned">,
@@ -4603,9 +5129,6 @@
 // Blocks
 def err_blocks_disable : Error<"blocks support disabled - compile with -fb=
locks"
   " or pick a deployment target that supports them">;
-def err_expected_block_lbrace : Error<"expected '{' in block literal">;
-def err_return_in_block_expression : Error<
-  "return not allowed in block expression literal">;
 def err_block_returning_array_function : Error<
   "block cannot return %select{array|function}0 type %1">;
=20
@@ -4639,20 +5162,37 @@
 def warn_case_empty_range : Warning<"empty case range specified">;
 def warn_missing_case_for_condition :
   Warning<"no case matching constant switch condition '%0'">;
+
+def warn_def_missing_case1 : Warning<
+  "enumeration value %0 not explicitly handled in switch">,
+  InGroup<SwitchEnum>, DefaultIgnore;
+def warn_def_missing_case2 : Warning<
+  "enumeration values %0 and %1 not explicitly handled in switch">,
+  InGroup<SwitchEnum>, DefaultIgnore;
+def warn_def_missing_case3 : Warning<
+  "enumeration values %0, %1, and %2 not explicitly handled in switch">,
+  InGroup<SwitchEnum>, DefaultIgnore;
+def warn_def_missing_cases : Warning<
+  "%0 enumeration values not explicitly handled in switch: %1, %2, %3...">,
+  InGroup<SwitchEnum>, DefaultIgnore;
+
 def warn_missing_case1 : Warning<"enumeration value %0 not handled in swit=
ch">,
-  InGroup<DiagGroup<"switch-enum"> >;
+  InGroup<Switch>;
 def warn_missing_case2 : Warning<
   "enumeration values %0 and %1 not handled in switch">,
-  InGroup<DiagGroup<"switch-enum"> >;
+  InGroup<Switch>;
 def warn_missing_case3 : Warning<
   "enumeration values %0, %1, and %2 not handled in switch">,
-  InGroup<DiagGroup<"switch-enum"> >;
+  InGroup<Switch>;
 def warn_missing_cases : Warning<
   "%0 enumeration values not handled in switch: %1, %2, %3...">,
-  InGroup<DiagGroup<"switch-enum"> >;
-
+  InGroup<Switch>;
+
+def warn_unreachable_default : Warning<
+  "default label in switch which covers all enumeration values">,
+  InGroup<CoveredSwitchDefault>, DefaultIgnore;
 def warn_not_in_enum : Warning<"case value not in enumerated type %0">,
-  InGroup<DiagGroup<"switch-enum"> >;=20
+  InGroup<Switch>;
 def err_typecheck_statement_requires_scalar : Error<
   "statement requires expression of scalar type (%0 invalid)">;
 def err_typecheck_statement_requires_integer : Error<
@@ -4668,8 +5208,20 @@
   "switch condition type %0 requires explicit conversion to %1">;
 def err_switch_incomplete_class_type : Error<
   "switch condition has incomplete class type %0">;
+
 def warn_empty_if_body : Warning<
   "if statement has empty body">, InGroup<EmptyBody>;
+def warn_empty_for_body : Warning<
+  "for loop has empty body">, InGroup<EmptyBody>;
+def warn_empty_range_based_for_body : Warning<
+  "range-based for loop has empty body">, InGroup<EmptyBody>;
+def warn_empty_while_body : Warning<
+  "while loop has empty body">, InGroup<EmptyBody>;
+def warn_empty_switch_body : Warning<
+  "switch statement has empty body">, InGroup<EmptyBody>;
+def note_empty_body_on_separate_line : Note<
+  "put the semicolon on a separate line to silence this warning">,
+  InGroup<EmptyBody>;
=20
 def err_va_start_used_in_non_variadic_function : Error<
   "'va_start' used in function with fixed args">;
@@ -4702,7 +5254,10 @@
   "should not return a value">,
   DefaultError, InGroup<ReturnType>;
 def ext_return_has_void_expr : Extension<
-  "void %select{function|method}1 %0 should not return void expression">;
+  "void %select{function|method|block}1 %0 should not return void expressi=
on">;
+def err_return_init_list : Error<
+  "%select{void function|void method|constructor|destructor}1 %0 "
+  "must not return a value">;
 def warn_noreturn_function_has_return_expr : Warning<
   "function %0 declared 'noreturn' should not return">,
   InGroup<DiagGroup<"invalid-noreturn">>;
@@ -4775,14 +5330,14 @@
   "GNU decimal type extension not supported">;
 def err_missing_type_specifier : Error<
   "C++ requires a type specifier for all declarations">;
-def err_missing_param_declspec : Error<
-  "parameter requires a declaration specifier">;
 def err_objc_array_of_interfaces : Error<
   "array of interface %0 is invalid (probably should be an array of pointe=
rs)">;
 def ext_c99_array_usage : Extension<
-  "use of C99-specific array features, accepted as an extension">;
+  "%select{qualifier in |static |}0array size %select{||'[*] '}0is a C99 "
+  "feature">, InGroup<C99>;
 def err_c99_array_usage_cxx : Error<
-  "C99-specific array features are not permitted in C++">;
+  "%select{qualifier in |static |}0array size %select{||'[*] '}0is a C99 "
+  "feature, not permitted in C++">;
 def err_double_requires_fp64 : Error<
   "use of type 'double' requires cl_khr_fp64 extension to be enabled">;
 def err_nsconsumed_attribute_mismatch : Error<
@@ -4809,7 +5364,8 @@
   AccessControl;
 def warn_maynot_respond : Warning<"%0 may not respond to %1">;
 def warn_attribute_method_def : Warning<
-  "method attribute can only be specified on method declarations">;
+  "attributes on method implementation and its declaration must match">,
+  InGroup<DiagGroup<"mismatched-method-attributes">>;
 def ext_typecheck_base_super : Warning<
   "method parameter type %0 does not match "
   "super class method parameter type %1">, InGroup<SuperSubClassMismatch>,=
 DefaultIgnore;
@@ -4916,8 +5472,6 @@
 }
=20
 let CategoryName =3D "Modules Issue" in {
-def err_module_private_follows_public : Error<
-  "__module_private__ declaration of %0 follows public declaration">;
 def err_module_private_specialization : Error<
   "%select{template|partial|member}0 specialization cannot be "
   "declared __module_private__">;
@@ -4927,6 +5481,8 @@
 def err_module_private_local_class : Error<
   "local %select{struct|union|class|enum}0 cannot be declared "
   "__module_private__">;
+def err_module_private_definition : Error<
+  "definition of %0 must be imported before it is required">;
 }
=20
 } // end of sema component.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/ExpressionTraits.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/ExpressionTraits.h	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/ExpressionTraits.h	=
Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D--- ExpressionTraits.h - C++ Expression Traits Support Enumerat=
ions ----*- C++ -*-=3D=3D=3D//
+//=3D=3D=3D- ExpressionTraits.h - C++ Expression Traits Support Enums -*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/FileManager.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/FileManager.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/FileManager.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
 namespace clang {
 class FileManager;
 class FileSystemStatCache;
- =20
+
 /// DirectoryEntry - Cached information about one directory (either on
 /// the disk or in the virtual file system).
 ///
@@ -64,12 +64,12 @@
   dev_t Device;               // ID for the device containing the file.
   ino_t Inode;                // Inode number for the file.
   mode_t FileMode;            // The file mode as returned by 'stat'.
- =20
+
   /// FD - The file descriptor for the file entry if it is opened and owned
   /// by the FileEntry.  If not, this is set to -1.
   mutable int FD;
   friend class FileManager;
- =20
+
 public:
   FileEntry(dev_t device, ino_t inode, mode_t m)
     : Name(0), Device(device), Inode(inode), FileMode(m), FD(-1) {}
@@ -80,7 +80,7 @@
     memcpy(this, &FE, sizeof(FE));
     assert(FD =3D=3D -1 && "Cannot copy a file-owning FileEntry");
   }
- =20
+
   void operator=3D(const FileEntry &FE) {
     memcpy(this, &FE, sizeof(FE));
     assert(FD =3D=3D -1 && "Cannot assign a file-owning FileEntry");
@@ -110,13 +110,14 @@
 /// properties, such as uniquing files based on "inode", so that a file wi=
th two
 /// names (e.g. symlinked) will be treated as a single file.
 ///
-class FileManager : public llvm::RefCountedBase<FileManager> {
+class FileManager : public RefCountedBase<FileManager> {
   FileSystemOptions FileSystemOpts;
=20
   class UniqueDirContainer;
   class UniqueFileContainer;
=20
-  /// UniqueRealDirs/UniqueRealFiles - Cache for existing real directories=
/files.
+  /// UniqueRealDirs/UniqueRealFiles - Cache for existing real
+  /// directories/files.
   ///
   UniqueDirContainer &UniqueRealDirs;
   UniqueFileContainer &UniqueRealFiles;
@@ -147,7 +148,7 @@
   unsigned NumDirCacheMisses, NumFileCacheMisses;
=20
   // Caching.
-  llvm::OwningPtr<FileSystemStatCache> StatCache;
+  OwningPtr<FileSystemStatCache> StatCache;
=20
   bool getStatValue(const char *Path, struct stat &StatBuf,
                     int *FileDescriptor);
@@ -224,7 +225,7 @@
   /// file to the corresponding FileEntry pointer.
   void GetUniqueIDMapping(
                     SmallVectorImpl<const FileEntry *> &UIDToFiles) const;
- =20
+
   void PrintStats() const;
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/FileSystemStatCache.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/FileSystemStatCache=
.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/FileSystemStatCache=
.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_FILESYSTEMSTATCACHE_H
 #define LLVM_CLANG_FILESYSTEMSTATCACHE_H
=20
+#include "clang/Basic/LLVM.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/StringMap.h"
 #include <sys/types.h>
@@ -25,8 +26,9 @@
 /// system calls, which is used by precompiled and pretokenized headers to
 /// improve performance.
 class FileSystemStatCache {
+  virtual void anchor();
 protected:
-  llvm::OwningPtr<FileSystemStatCache> NextStatCache;
+  OwningPtr<FileSystemStatCache> NextStatCache;
  =20
 public:
   virtual ~FileSystemStatCache() {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/IdentifierTable.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/IdentifierTable.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/IdentifierTable.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -20,11 +20,9 @@
 #include "clang/Basic/LLVM.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/Support/PointerLikeTypeTraits.h"
 #include <cassert>
-#include <cctype>
 #include <string>
=20
 namespace llvm {
@@ -49,8 +47,6 @@
 /// variable or function name).  The preprocessor keeps this information i=
n a
 /// set, and all tok::identifier tokens have a pointer to one of these.
 class IdentifierInfo {
-  // Note: DON'T make TokenID a 'tok::TokenKind'; MSVC will treat it as a
-  //       signed char and TokenKinds > 255 won't be handled correctly.
   unsigned TokenID            : 9; // Front-end token ID or tok::identifie=
r.
   // Objective-C keyword ('protocol' in '@protocol') or builtin (__builtin=
_inf).
   // First NUM_OBJC_KEYWORDS values are for Objective-C, the remaining val=
ues
@@ -62,11 +58,19 @@
   bool IsPoisoned             : 1; // True if identifier is poisoned.
   bool IsCPPOperatorKeyword   : 1; // True if ident is a C++ operator keyw=
ord.
   bool NeedsHandleIdentifier  : 1; // See "RecomputeNeedsHandleIdentifier".
-  bool IsFromAST              : 1; // True if identfier first appeared in =
an AST
-                                   // file and wasn't modified since.
+  bool IsFromAST              : 1; // True if identifier was loaded (at le=
ast=20
+                                   // partially) from an AST file.
+  bool ChangedAfterLoad       : 1; // True if identifier has changed from =
the
+                                   // definition loaded from an AST file.
   bool RevertedTokenID        : 1; // True if RevertTokenIDToIdentifier was
                                    // called.
-  // 5 bits left in 32-bit word.
+  bool OutOfDate              : 1; // True if there may be additional
+                                   // information about this identifier
+                                   // stored externally.
+  bool IsModulesImport               : 1; // True if this is the 'import' =
contextual
+                                   // keyword.
+  // 1 bit left in 32-bit word.
+ =20
   void *FETokenInfo;               // Managed by the language front-end.
   llvm::StringMapEntry<IdentifierInfo*> *Entry;
=20
@@ -132,7 +136,6 @@
       NeedsHandleIdentifier =3D 1;
     else
       RecomputeNeedsHandleIdentifier();
-    IsFromAST =3D false;
   }
=20
   /// getTokenID - If this is a source-language token (e.g. 'for'), this A=
PI
@@ -221,7 +224,6 @@
       NeedsHandleIdentifier =3D 1;
     else
       RecomputeNeedsHandleIdentifier();
-    IsFromAST =3D false;
   }
=20
   /// isPoisoned - Return true if this token has been poisoned.
@@ -253,8 +255,48 @@
   /// from an AST file.
   bool isFromAST() const { return IsFromAST; }
=20
-  void setIsFromAST(bool FromAST =3D true) { IsFromAST =3D FromAST; }
+  void setIsFromAST() { IsFromAST =3D true; }
=20
+  /// \brief Determine whether this identifier has changed since it was lo=
aded
+  /// from an AST file.
+  bool hasChangedSinceDeserialization() const {
+    return ChangedAfterLoad;
+  }
+ =20
+  /// \brief Note that this identifier has changed since it was loaded from
+  /// an AST file.
+  void setChangedSinceDeserialization() {
+    ChangedAfterLoad =3D true;
+  }
+
+  /// \brief Determine whether the information for this identifier is out =
of
+  /// date with respect to the external source.
+  bool isOutOfDate() const { return OutOfDate; }
+ =20
+  /// \brief Set whether the information for this identifier is out of
+  /// date with respect to the external source.
+  void setOutOfDate(bool OOD) {
+    OutOfDate =3D OOD;
+    if (OOD)
+      NeedsHandleIdentifier =3D true;
+    else
+      RecomputeNeedsHandleIdentifier();
+  }
+ =20
+  /// \brief Determine whether this is the contextual keyword
+  /// '__experimental_modules_import'.
+  bool isModulesImport() const { return IsModulesImport; }
+ =20
+  /// \brief Set whether this identifier is the contextual keyword=20
+  /// '__experimental_modules_import'.
+  void setModulesImport(bool I) {
+    IsModulesImport =3D I;
+    if (I)
+      NeedsHandleIdentifier =3D true;
+    else
+      RecomputeNeedsHandleIdentifier();
+  }
+ =20
 private:
   /// RecomputeNeedsHandleIdentifier - The Preprocessor::HandleIdentifier =
does
   /// several special (but rare) things to identifiers of various sorts.  =
For
@@ -266,8 +308,8 @@
   void RecomputeNeedsHandleIdentifier() {
     NeedsHandleIdentifier =3D
       (isPoisoned() | hasMacroDefinition() | isCPlusPlusOperatorKeyword() |
-       isExtensionToken() | isCXX11CompatKeyword() ||
-       (getTokenID() =3D=3D tok::kw___import_module__));
+       isExtensionToken() | isCXX11CompatKeyword() || isOutOfDate() ||
+       isModulesImport());
   }
 };
=20
@@ -449,6 +491,10 @@
       // Make sure getName() knows how to find the IdentifierInfo
       // contents.
       II->Entry =3D &Entry;
+     =20
+      // If this is the 'import' contextual keyword, mark it as such.
+      if (Name.equals("import"))
+        II->setModulesImport(true);
     }
=20
     return *II;
@@ -662,14 +708,7 @@
   /// has been capitalized.
   static Selector constructSetterName(IdentifierTable &Idents,
                                       SelectorTable &SelTable,
-                                      const IdentifierInfo *Name) {
-    llvm::SmallString<100> SelectorName;
-    SelectorName =3D "set";
-    SelectorName +=3D Name->getName();
-    SelectorName[3] =3D toupper(SelectorName[3]);
-    IdentifierInfo *SetterName =3D &Idents.get(SelectorName);
-    return SelTable.getUnarySelector(SetterName);
-  }
+                                      const IdentifierInfo *Name);
 };
=20
 /// DeclarationNameExtra - Common base of the MultiKeywordSelector,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/LLVM.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/LLVM.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/LLVM.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -24,9 +24,20 @@
   class StringRef;
   class Twine;
   template<typename T> class ArrayRef;
+  template<class T> class OwningPtr;
+  template<unsigned InternalLen> class SmallString;
   template<typename T, unsigned N> class SmallVector;
   template<typename T> class SmallVectorImpl;
=20
+  template<typename T>
+  struct SaveAndRestore;
+
+  // Reference counting.
+  template <typename T> class IntrusiveRefCntPtr;
+  template <typename T> struct IntrusiveRefCntPtrInfo;
+  template <class Derived> class RefCountedBase;
+  class RefCountedBaseVPTR;
+
   class raw_ostream;
   // TODO: DenseMap, ...
 }
@@ -44,9 +55,18 @@
   using llvm::StringRef;
   using llvm::Twine;
   using llvm::ArrayRef;
+  using llvm::OwningPtr;
+  using llvm::SmallString;
   using llvm::SmallVector;
   using llvm::SmallVectorImpl;
- =20
+  using llvm::SaveAndRestore;
+
+  // Reference counting.
+  using llvm::IntrusiveRefCntPtr;
+  using llvm::IntrusiveRefCntPtrInfo;
+  using llvm::RefCountedBase;
+  using llvm::RefCountedBaseVPTR;
+
   using llvm::raw_ostream;
 } // end namespace clang.
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/LangOptions.def
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.def	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.def	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -42,7 +42,7 @@
 #endif
=20
 LANGOPT(C99               , 1, 0, "C99")
-LANGOPT(C1X               , 1, 0, "C1X")
+LANGOPT(C11               , 1, 0, "C11")
 LANGOPT(MicrosoftExt      , 1, 0, "Microsoft extensions")
 LANGOPT(MicrosoftMode     , 1, 0, "Microsoft compatibility mode")
 LANGOPT(Borland           , 1, 0, "Borland extensions")
@@ -91,16 +91,18 @@
 BENIGN_LANGOPT(EmitAllDecls      , 1, 0, "support for emitting all declara=
tions")
 LANGOPT(MathErrno         , 1, 1, "errno support for math functions")
 BENIGN_LANGOPT(HeinousExtensions , 1, 0, "Extensions that we really don't =
like and may be ripped out at any time")
-
+LANGOPT(Modules           , 1, 0, "modules extension to C")
 LANGOPT(Optimize          , 1, 0, "__OPTIMIZE__ predefined macro")
 LANGOPT(OptimizeSize      , 1, 0, "__OPTIMIZE_SIZE__ predefined macro")
 LANGOPT(Static            , 1, 0, "__STATIC__ predefined macro (as opposed=
 to __DYNAMIC__)")
 VALUE_LANGOPT(PackStruct  , 32, 0,=20
               "default struct packing maximum alignment")
-VALUE_LANGOPT(PICLevel          , 2, 0, "__PIC__ level")
+VALUE_LANGOPT(PICLevel    , 2, 0, "__PIC__ level")
+VALUE_LANGOPT(PIELevel    , 2, 0, "__PIE__ level")
 LANGOPT(GNUInline         , 1, 0, "GNU inline semantics")
-LANGOPT(NoInline          , 1, 0, "__NO_INLINE__ predefined macro")
+LANGOPT(NoInlineDefine    , 1, 0, "__NO_INLINE__ predefined macro")
 LANGOPT(Deprecated        , 1, 0, "__DEPRECATED predefined macro")
+LANGOPT(FastMath          , 1, 0, "__FAST_MATH__ predefined macro")
=20
 BENIGN_LANGOPT(ObjCGCBitmapPrint , 1, 0, "printing of GC's bitmap layout f=
or __weak/__strong ivars")
=20
@@ -117,17 +119,23 @@
 BENIGN_LANGOPT(ElideConstructors , 1, 1, "C++ copy constructor elision")
 BENIGN_LANGOPT(CatchUndefined    , 1, 0, "catching undefined behavior at r=
un time")
 BENIGN_LANGOPT(DumpRecordLayouts , 1, 0, "dumping the layout of IRgen'd re=
cords")
+BENIGN_LANGOPT(DumpRecordLayoutsSimple , 1, 0, "dumping the layout of IRge=
n'd records in a simple form")
 BENIGN_LANGOPT(DumpVTableLayouts , 1, 0, "dumping the layouts of emitted v=
tables")
 LANGOPT(NoConstantCFStrings , 1, 0, "no constant CoreFoundation strings")
 BENIGN_LANGOPT(InlineVisibilityHidden , 1, 0, "hidden default visibility f=
or inline C++ methods")
 BENIGN_LANGOPT(ParseUnknownAnytype, 1, 0, "__unknown_anytype")
 BENIGN_LANGOPT(DebuggerSupport , 1, 0, "debugger support")
+BENIGN_LANGOPT(DebuggerCastResultToId, 1, 0, "for 'po' in the debugger, ca=
st the result to id if it is of unknown type")
+BENIGN_LANGOPT(DebuggerObjCLiteral , 1, 0, "debugger objective-C literals =
and subscripting support")
+BENIGN_LANGOPT(AddressSanitizer , 1, 0, "AddressSanitizer enabled")
+BENIGN_LANGOPT(ThreadSanitizer , 1, 0, "ThreadSanitizer enabled")
=20
 BENIGN_LANGOPT(SpellChecking , 1, 1, "spell-checking")
 LANGOPT(SinglePrecisionConstants , 1, 0, "treating double-precision floati=
ng point constants as single precision constants")
 LANGOPT(FastRelaxedMath , 1, 0, "OpenCL fast relaxed math")
 LANGOPT(DefaultFPContract , 1, 0, "FP_CONTRACT")
 LANGOPT(NoBitFieldTypeAlign , 1, 0, "bit-field type alignment")
+LANGOPT(HexagonQdsp6Compat , 1, 0, "hexagon-qdsp6 backward compatibility")
 LANGOPT(ObjCAutoRefCount , 1, 0, "Objective-C automated reference counting=
")
 LANGOPT(ObjCRuntimeHasWeak , 1, 0, "__weak support in the ARC runtime")
 LANGOPT(FakeAddressSpaceMap , 1, 0, "OpenCL fake address space map")
@@ -146,11 +154,15 @@
=20
 BENIGN_LANGOPT(InstantiationDepth, 32, 1024,=20
                "maximum template instantiation depth")
+BENIGN_LANGOPT(ConstexprCallDepth, 32, 512,
+               "maximum constexpr call depth")
 BENIGN_LANGOPT(NumLargeByValueCopy, 32, 0,=20
         "if non-zero, warn about parameter or return Warn if parameter/ret=
urn value is larger in bytes than this setting. 0 is no check.")
 VALUE_LANGOPT(MSCVersion, 32, 0,=20
               "version of Microsoft Visual C/C++")
=20
+LANGOPT(ApplePragmaPack, 1, 0, "Apple gcc-compatible #pragma pack handling=
")
+
 #undef LANGOPT
 #undef VALUE_LANGOPT
 #undef BENIGN_LANGOPT
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/LangOptions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/LangOptions.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -15,13 +15,33 @@
 #define LLVM_CLANG_LANGOPTIONS_H
=20
 #include <string>
+#include "clang/Basic/LLVM.h"
 #include "clang/Basic/Visibility.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
=20
 namespace clang {
=20
+/// Bitfields of LangOptions, split out from LangOptions in order to ensur=
e that
+/// this large collection of bitfields is a trivial class type.
+class LangOptionsBase {
+public:
+  // Define simple language options (with no accessors).
+#define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
+#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)
+#include "clang/Basic/LangOptions.def"
+
+protected:
+  // Define language options of enumeration type. These are private, and w=
ill
+  // have accessors (below).
+#define LANGOPT(Name, Bits, Default, Description)
+#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
+  unsigned Name : Bits;
+#include "clang/Basic/LangOptions.def"
+};
+
 /// LangOptions - This class keeps track of the various options that can be
 /// enabled, which controls the dialect of C that is accepted.
-class LangOptions {
+class LangOptions : public RefCountedBase<LangOptions>, public LangOptions=
Base {
 public:
   typedef clang::Visibility Visibility;
  =20
@@ -34,19 +54,6 @@
     SOB_Trapping    // -ftrapv
   };
=20
-  // Define simple language options (with no accessors).
-#define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
-#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)
-#include "clang/Basic/LangOptions.def"
- =20
-private:
-  // Define language options of enumeration type. These are private, and w=
ill
-  // have accessors (below).
-#define LANGOPT(Name, Bits, Default, Description)=20
-#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
-  unsigned Name : Bits;
-#include "clang/Basic/LangOptions.def"
- =20
 public:
   std::string ObjCConstantStringClass;
  =20
@@ -54,6 +61,9 @@
   /// If none is specified, abort (GCC-compatible behaviour).
   std::string OverflowHandler;
=20
+  /// \brief The name of the current module.
+  std::string CurrentModule;
+ =20
   LangOptions();
=20
   // Define accessors/mutators for language options of enumeration type.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/Linkage.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/Linkage.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/Linkage.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
   InternalLinkage,
=20
   /// \brief External linkage within a unique namespace. From the
-  /// langauge perspective, these entities have external
+  /// language perspective, these entities have external
   /// linkage. However, since they reside in an anonymous namespace,
   /// their names are unique to this translation unit, which is
   /// equivalent to having internal linkage from the code-generation
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/OnDiskHashTable.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/OnDiskHashTable.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/OnDiskHashTable.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -356,7 +356,7 @@
     friend bool operator!=3D(const key_iterator& X, const key_iterator &Y)=
 {
       return X.NumEntriesLeft !=3D Y.NumEntriesLeft;
     }
-   =20
+
     key_iterator& operator++() {  // Preincrement
       if (!NumItemsInBucketLeft) {
         // 'Items' starts with a 16-bit unsigned integer representing the
@@ -421,7 +421,7 @@
     bool operator!=3D(const item_iterator& X) const {
       return X.NumEntriesLeft !=3D NumEntriesLeft;
     }
-   =20
+
     item_iterator& operator++() {  // Preincrement
       if (!NumItemsInBucketLeft) {
         // 'Items' starts with a 16-bit unsigned integer representing the
@@ -449,7 +449,7 @@
       LocalPtr +=3D 4; // Skip the hash.
=20
       // Determine the length of the key and the data.
-      const std::pair<unsigned, unsigned>& L =3D Info::ReadKeyDataLength(L=
ocalPtr);
+      const std::pair<unsigned, unsigned>& L =3DInfo::ReadKeyDataLength(Lo=
calPtr);
=20
       // Read the key.
       const internal_key_type& Key =3D
@@ -458,14 +458,14 @@
                           InfoObj->ReadData(Key, LocalPtr + L.first, L.sec=
ond));
     }
   };
- =20
+
   item_iterator item_begin() {
     return item_iterator(Base + 4, getNumEntries(), &InfoObj);
   }
   item_iterator item_end() { return item_iterator(); }
=20
   Info &getInfoObj() { return InfoObj; }
- =20
+
   static OnDiskChainedHashTable* Create(const unsigned char* buckets,
                                         const unsigned char* const base,
                                         const Info &InfoObj =3D Info()) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/PartialDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/PartialDiagnostic.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/PartialDiagnostic.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -25,88 +25,90 @@
=20
 class PartialDiagnostic {
 public:
+  enum {
+      // The MaxArguments and MaxFixItHints member enum values from
+      // DiagnosticsEngine are private but DiagnosticsEngine declares
+      // PartialDiagnostic a friend.  These enum values are redeclared
+      // here so that the nested Storage class below can access them.
+      MaxArguments =3D DiagnosticsEngine::MaxArguments
+  };
+
   struct Storage {
-    Storage() : NumDiagArgs(0), NumDiagRanges(0), NumFixItHints(0) { }
+    Storage() : NumDiagArgs(0), NumDiagRanges(0) { }
=20
     enum {
-        /// MaxArguments - The maximum number of arguments we can hold. We=20
+        /// MaxArguments - The maximum number of arguments we can hold. We
         /// currently only support up to 10 arguments (%0-%9).
         /// A single diagnostic with more than that almost certainly has to
         /// be simplified anyway.
-        MaxArguments =3D DiagnosticsEngine::MaxArguments
+        MaxArguments =3D PartialDiagnostic::MaxArguments
     };
- =20
+
     /// NumDiagArgs - This contains the number of entries in Arguments.
     unsigned char NumDiagArgs;
- =20
+
     /// NumDiagRanges - This is the number of ranges in the DiagRanges arr=
ay.
     unsigned char NumDiagRanges;
=20
-    /// \brief The number of code modifications hints in the
-    /// FixItHints array.
-    unsigned char NumFixItHints;
-   =20
     /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind=
 enum
     /// values, with one for each argument.  This specifies whether the ar=
gument
     /// is in DiagArgumentsStr or in DiagArguments.
     unsigned char DiagArgumentsKind[MaxArguments];
- =20
-    /// DiagArgumentsVal - The values for the various substitution positio=
ns.=20
-    /// This is used when the argument is not an std::string. The specific=
 value=20
+
+    /// DiagArgumentsVal - The values for the various substitution positio=
ns.
+    /// This is used when the argument is not an std::string. The specific=
 value
     /// is mangled into an intptr_t and the interpretation depends on exac=
tly
     /// what sort of argument kind it is.
     intptr_t DiagArgumentsVal[MaxArguments];
- =20
+
     /// \brief The values for the various substitution positions that have
     /// string arguments.
     std::string DiagArgumentsStr[MaxArguments];
-   =20
+
     /// DiagRanges - The list of ranges added to this diagnostic.  It curr=
ently
     /// only support 10 ranges, could easily be extended if needed.
     CharSourceRange DiagRanges[10];
-   =20
-    enum { MaxFixItHints =3D DiagnosticsEngine::MaxFixItHints };
-   =20
+
     /// FixItHints - If valid, provides a hint with some code
     /// to insert, remove, or modify at a particular position.
-    FixItHint FixItHints[MaxFixItHints];   =20
+    SmallVector<FixItHint, 6>  FixItHints;
   };
=20
-  /// \brief An allocator for Storage objects, which uses a small cache to=20
+  /// \brief An allocator for Storage objects, which uses a small cache to
   /// objects, used to reduce malloc()/free() traffic for partial diagnost=
ics.
   class StorageAllocator {
     static const unsigned NumCached =3D 16;
     Storage Cached[NumCached];
     Storage *FreeList[NumCached];
     unsigned NumFreeListEntries;
-   =20
+
   public:
     StorageAllocator();
     ~StorageAllocator();
-   =20
+
     /// \brief Allocate new storage.
     Storage *Allocate() {
       if (NumFreeListEntries =3D=3D 0)
         return new Storage;
-     =20
+
       Storage *Result =3D FreeList[--NumFreeListEntries];
       Result->NumDiagArgs =3D 0;
       Result->NumDiagRanges =3D 0;
-      Result->NumFixItHints =3D 0;
+      Result->FixItHints.clear();
       return Result;
     }
-   =20
+
     /// \brief Free the given storage object.
     void Deallocate(Storage *S) {
       if (S >=3D Cached && S <=3D Cached + NumCached) {
         FreeList[NumFreeListEntries++] =3D S;
         return;
       }
-     =20
+
       delete S;
     }
   };
- =20
+
 private:
   // NOTE: Sema assumes that PartialDiagnostic is location-invariant
   // in the sense that its bits can be safely memcpy'ed and destructed
@@ -114,18 +116,18 @@
=20
   /// DiagID - The diagnostic ID.
   mutable unsigned DiagID;
- =20
+
   /// DiagStorage - Storage for args and ranges.
   mutable Storage *DiagStorage;
=20
   /// \brief Allocator used to allocate storage for this diagnostic.
   StorageAllocator *Allocator;
- =20
+
   /// \brief Retrieve storage for this particular diagnostic.
   Storage *getStorage() const {
     if (DiagStorage)
       return DiagStorage;
-   =20
+
     if (Allocator)
       DiagStorage =3D Allocator->Allocate();
     else {
@@ -134,48 +136,53 @@
     }
     return DiagStorage;
   }
- =20
-  void freeStorage() {=20
+
+  void freeStorage() {
     if (!DiagStorage)
       return;
-   =20
+
+    // The hot path for PartialDiagnostic is when we just used it to wrap =
an ID
+    // (typically so we have the flexibility of passing a more complex
+    // diagnostic into the callee, but that does not commonly occur).
+    //
+    // Split this out into a slow function for silly compilers (*cough*) w=
hich
+    // can't do decent partial inlining.
+    freeStorageSlow();
+  }
+
+  void freeStorageSlow() {
     if (Allocator)
       Allocator->Deallocate(DiagStorage);
     else if (Allocator !=3D reinterpret_cast<StorageAllocator *>(~uintptr_=
t(0)))
       delete DiagStorage;
     DiagStorage =3D 0;
   }
- =20
+
   void AddSourceRange(const CharSourceRange &R) const {
     if (!DiagStorage)
       DiagStorage =3D getStorage();
=20
-    assert(DiagStorage->NumDiagRanges <=20
+    assert(DiagStorage->NumDiagRanges <
            llvm::array_lengthof(DiagStorage->DiagRanges) &&
            "Too many arguments to diagnostic!");
     DiagStorage->DiagRanges[DiagStorage->NumDiagRanges++] =3D R;
-  } =20
+  }
=20
   void AddFixItHint(const FixItHint &Hint) const {
     if (Hint.isNull())
       return;
-   =20
+
     if (!DiagStorage)
       DiagStorage =3D getStorage();
=20
-    assert(DiagStorage->NumFixItHints < Storage::MaxFixItHints &&
-           "Too many code modification hints!");
-    if (DiagStorage->NumFixItHints >=3D Storage::MaxFixItHints)
-      return;  // Don't crash in release builds
-    DiagStorage->FixItHints[DiagStorage->NumFixItHints++]
-      =3D Hint;
+    DiagStorage->FixItHints.push_back(Hint);
   }
- =20
+
 public:
   PartialDiagnostic(unsigned DiagID, StorageAllocator &Allocator)
     : DiagID(DiagID), DiagStorage(0), Allocator(&Allocator) { }
- =20
-  PartialDiagnostic(const PartialDiagnostic &Other)=20
+
+  PartialDiagnostic(const PartialDiagnostic &Other)
     : DiagID(Other.DiagID), DiagStorage(0), Allocator(Other.Allocator)
   {
     if (Other.DiagStorage) {
@@ -184,14 +191,14 @@
     }
   }
=20
-  PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage)=20
-    : DiagID(Other.DiagID), DiagStorage(DiagStorage),=20
+  PartialDiagnostic(const PartialDiagnostic &Other, Storage *DiagStorage)
+    : DiagID(Other.DiagID), DiagStorage(DiagStorage),
       Allocator(reinterpret_cast<StorageAllocator *>(~uintptr_t(0)))
   {
     if (Other.DiagStorage)
       *this->DiagStorage =3D *Other.DiagStorage;
   }
- =20
+
   PartialDiagnostic(const Diagnostic &Other, StorageAllocator &Allocator)
     : DiagID(Other.getID()), DiagStorage(0), Allocator(&Allocator)
   {
@@ -202,22 +209,22 @@
       else
         AddTaggedVal(Other.getRawArg(I), Other.getArgKind(I));
     }
-   =20
+
     // Copy source ranges.
     for (unsigned I =3D 0, N =3D Other.getNumRanges(); I !=3D N; ++I)
       AddSourceRange(Other.getRange(I));
-   =20
+
     // Copy fix-its.
     for (unsigned I =3D 0, N =3D Other.getNumFixItHints(); I !=3D N; ++I)
       AddFixItHint(Other.getFixItHint(I));
   }
- =20
+
   PartialDiagnostic &operator=3D(const PartialDiagnostic &Other) {
     DiagID =3D Other.DiagID;
     if (Other.DiagStorage) {
       if (!DiagStorage)
         DiagStorage =3D getStorage();
-     =20
+
       *DiagStorage =3D *Other.DiagStorage;
     } else {
       freeStorage();
@@ -245,7 +252,7 @@
   void AddString(StringRef V) const {
     if (!DiagStorage)
       DiagStorage =3D getStorage();
-   =20
+
     assert(DiagStorage->NumDiagArgs < Storage::MaxArguments &&
            "Too many arguments to diagnostic!");
     DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs]
@@ -256,7 +263,7 @@
   void Emit(const DiagnosticBuilder &DB) const {
     if (!DiagStorage)
       return;
-   =20
+
     // Add all arguments.
     for (unsigned i =3D 0, e =3D DiagStorage->NumDiagArgs; i !=3D e; ++i) {
       if ((DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKind[=
i]
@@ -266,25 +273,25 @@
         DB.AddTaggedVal(DiagStorage->DiagArgumentsVal[i],
             (DiagnosticsEngine::ArgumentKind)DiagStorage->DiagArgumentsKin=
d[i]);
     }
-   =20
+
     // Add all ranges.
     for (unsigned i =3D 0, e =3D DiagStorage->NumDiagRanges; i !=3D e; ++i)
       DB.AddSourceRange(DiagStorage->DiagRanges[i]);
-   =20
+
     // Add all fix-its.
-    for (unsigned i =3D 0, e =3D DiagStorage->NumFixItHints; i !=3D e; ++i)
+    for (unsigned i =3D 0, e =3D DiagStorage->FixItHints.size(); i !=3D e;=
 ++i)
       DB.AddFixItHint(DiagStorage->FixItHints[i]);
   }
- =20
+
   /// \brief Clear out this partial diagnostic, giving it a new diagnostic=
 ID
   /// and removing all of its arguments, ranges, and fix-it hints.
   void Reset(unsigned DiagID =3D 0) {
     this->DiagID =3D DiagID;
     freeStorage();
   }
- =20
+
   bool hasStorage() const { return DiagStorage !=3D 0; }
- =20
+
   friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
                                              unsigned I) {
     PD.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
@@ -306,11 +313,11 @@
=20
   friend inline const PartialDiagnostic &operator<<(const PartialDiagnosti=
c &PD,
                                                     StringRef S) {
-   =20
+
     PD.AddString(S);
     return PD;
   }
- =20
+
   friend inline const PartialDiagnostic &operator<<(const PartialDiagnosti=
c &PD,
                                                     const SourceRange &R) {
     PD.AddSourceRange(CharSourceRange::getTokenRange(R));
@@ -322,13 +329,13 @@
     PD.AddSourceRange(R);
     return PD;
   }
- =20
+
   friend const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
                                              const FixItHint &Hint) {
     PD.AddFixItHint(Hint);
     return PD;
   }
- =20
+
 };
=20
 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
@@ -336,7 +343,7 @@
   PD.Emit(DB);
   return DB;
 }
- =20
+
 /// \brief A partial diagnostic along with the source location where this
 /// diagnostic occurs.
 typedef std::pair<SourceLocation, PartialDiagnostic> PartialDiagnosticAt;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/SourceLocation.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/SourceLocation.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/SourceLocation.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
=20
 #include "clang/Basic/LLVM.h"
 #include "llvm/Support/PointerLikeTypeTraits.h"
+#include "llvm/Support/Compiler.h"
 #include <utility>
 #include <functional>
 #include <cassert>
@@ -245,6 +246,7 @@
   /// the last token.  Return false if the end of this range specifies the=
 last
   /// character in the range.
   bool isTokenRange() const { return IsTokenRange; }
+  bool isCharRange() const { return !IsTokenRange; }
  =20
   SourceLocation getBegin() const { return Range.getBegin(); }
   SourceLocation getEnd() const { return Range.getEnd(); }
@@ -323,7 +325,7 @@
=20
   /// Prints information about this FullSourceLoc to stderr. Useful for
   ///  debugging.
-  void dump() const { SourceLocation::dump(*SrcMgr); }
+  LLVM_ATTRIBUTE_USED void dump() const;
=20
   friend inline bool
   operator=3D=3D(const FullSourceLoc &LHS, const FullSourceLoc &RHS) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/SourceManager.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/SourceManager.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -102,7 +102,39 @@
=20
     /// NumLines - The number of lines in this ContentCache.  This is only=
 valid
     /// if SourceLineCache is non-null.
-    unsigned NumLines;
+    unsigned NumLines : 31;
+
+    /// \brief Indicates whether the buffer itself was provided to override
+    /// the actual file contents.
+    ///
+    /// When true, the original entry may be a virtual file that does not
+    /// exist.
+    unsigned BufferOverridden : 1;
+   =20
+    ContentCache(const FileEntry *Ent =3D 0)
+      : Buffer(0, false), OrigEntry(Ent), ContentsEntry(Ent),
+        SourceLineCache(0), NumLines(0), BufferOverridden(false) {}
+   =20
+    ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
+      : Buffer(0, false), OrigEntry(Ent), ContentsEntry(contentEnt),
+        SourceLineCache(0), NumLines(0), BufferOverridden(false) {}
+   =20
+    ~ContentCache();
+   =20
+    /// The copy ctor does not allow copies where source object has either
+    ///  a non-NULL Buffer or SourceLineCache.  Ownership of allocated mem=
ory
+    ///  is not transferred, so this is a logical error.
+    ContentCache(const ContentCache &RHS)
+      : Buffer(0, false), SourceLineCache(0), BufferOverridden(false)
+    {
+      OrigEntry =3D RHS.OrigEntry;
+      ContentsEntry =3D RHS.ContentsEntry;
+     =20
+      assert (RHS.Buffer.getPointer() =3D=3D 0 && RHS.SourceLineCache =3D=
=3D 0 &&
+              "Passed ContentCache object cannot own a buffer.");
+     =20
+      NumLines =3D RHS.NumLines;
+    }
=20
     /// getBuffer - Returns the memory buffer for the associated content.
     ///
@@ -159,31 +191,6 @@
       return (Buffer.getInt() & DoNotFreeFlag) =3D=3D 0;
     }
=20
-    ContentCache(const FileEntry *Ent =3D 0)
-      : Buffer(0, false), OrigEntry(Ent), ContentsEntry(Ent),
-        SourceLineCache(0), NumLines(0) {}
-
-    ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
-      : Buffer(0, false), OrigEntry(Ent), ContentsEntry(contentEnt),
-        SourceLineCache(0), NumLines(0) {}
-
-    ~ContentCache();
-
-    /// The copy ctor does not allow copies where source object has either
-    ///  a non-NULL Buffer or SourceLineCache.  Ownership of allocated mem=
ory
-    ///  is not transferred, so this is a logical error.
-    ContentCache(const ContentCache &RHS)
-      : Buffer(0, false), SourceLineCache(0)
-    {
-      OrigEntry =3D RHS.OrigEntry;
-      ContentsEntry =3D RHS.ContentsEntry;
-
-      assert (RHS.Buffer.getPointer() =3D=3D 0 && RHS.SourceLineCache =3D=
=3D 0 &&
-              "Passed ContentCache object cannot own a buffer.");
-
-      NumLines =3D RHS.NumLines;
-    }
-
   private:
     // Disable assignments.
     ContentCache &operator=3D(const ContentCache& RHS);
@@ -293,6 +300,11 @@
         SourceLocation::getFromRawEncoding(ExpansionLocEnd).isInvalid();
     }
=20
+    bool isFunctionMacroExpansion() const {
+      return getExpansionLocStart().isValid() &&
+          getExpansionLocStart() !=3D getExpansionLocEnd();
+    }
+
     /// create - Return a ExpansionInfo for an expansion. Start and End sp=
ecify
     /// the expansion range (where the macro is expanded), and SpellingLoc
     /// specifies the spelling location (where the characters from the tok=
en
@@ -431,8 +443,7 @@
     // to determine which came first. This will also take care the case wh=
ere
     // one of the locations points at the inclusion/expansion point of the=
 other
     // in which case its FileID will come before the other.
-    if (LOffset =3D=3D ROffset &&
-        (LQueryFID !=3D CommonFID || RQueryFID !=3D CommonFID))
+    if (LOffset =3D=3D ROffset)
       return IsLQFIDBeforeRQFID;
=20
     return LOffset < ROffset;
@@ -472,7 +483,7 @@
 /// the case of a macro expansion, for example, the spelling location indi=
cates
 /// where the expanded token came from and the expansion location specifies
 /// where it was expanded.
-class SourceManager : public llvm::RefCountedBase<SourceManager> {
+class SourceManager : public RefCountedBase<SourceManager> {
   /// \brief DiagnosticsEngine object.
   DiagnosticsEngine &Diag;
=20
@@ -508,7 +519,7 @@
   ///
   /// Negative FileIDs are indexes into this table. To get from ID to an i=
ndex,
   /// use (-ID - 2).
-  std::vector<SrcMgr::SLocEntry> LoadedSLocEntryTable;
+  mutable std::vector<SrcMgr::SLocEntry> LoadedSLocEntryTable;
=20
   /// \brief The starting offset of the next local SLocEntry.
   ///
@@ -565,11 +576,13 @@
   // Cache for the "fake" buffer used for error-recovery purposes.
   mutable llvm::MemoryBuffer *FakeBufferForRecovery;
=20
+  mutable SrcMgr::ContentCache *FakeContentCacheForRecovery;
+
   /// \brief Lazily computed map of macro argument chunks to their expanded
   /// source location.
   typedef std::map<unsigned, SourceLocation> MacroArgsMap;
=20
-  mutable llvm::DenseMap<FileID, MacroArgsMap *> MacroArgsCacheMap;=20
+  mutable llvm::DenseMap<FileID, MacroArgsMap *> MacroArgsCacheMap;
=20
   // SourceManager doesn't support copy construction.
   explicit SourceManager(const SourceManager&);
@@ -607,12 +620,19 @@
   FileID getMainFileID() const { return MainFileID; }
=20
   /// createMainFileID - Create the FileID for the main source file.
-  FileID createMainFileID(const FileEntry *SourceFile) {
+  FileID createMainFileID(const FileEntry *SourceFile,=20
+                          SrcMgr::CharacteristicKind Kind =3D SrcMgr::C_Us=
er) {
     assert(MainFileID.isInvalid() && "MainFileID already set!");
-    MainFileID =3D createFileID(SourceFile, SourceLocation(), SrcMgr::C_Us=
er);
+    MainFileID =3D createFileID(SourceFile, SourceLocation(), Kind);
     return MainFileID;
   }
=20
+  /// \brief Set the file ID for the main source file.
+  void setMainFileID(FileID FID) {
+    assert(MainFileID.isInvalid() && "MainFileID already set!");
+    MainFileID =3D FID;
+  }
+
   /// \brief Set the file ID for the precompiled preamble.
   void setPreambleFileID(FileID Preamble) {
     assert(PreambleFileID.isInvalid() && "PreambleFileID already set!");
@@ -641,8 +661,9 @@
   /// specified memory buffer.  This does no caching of the buffer and tak=
es
   /// ownership of the MemoryBuffer, so only pass a MemoryBuffer to this o=
nce.
   FileID createFileIDForMemBuffer(const llvm::MemoryBuffer *Buffer,
-                                  int LoadedID =3D 0, unsigned LoadedOffse=
t =3D 0) {
-    return createFileID(createMemBufferContentCache(Buffer), SourceLocatio=
n(),
+                                  int LoadedID =3D 0, unsigned LoadedOffse=
t =3D 0,
+                                 SourceLocation IncludeLoc =3D SourceLocat=
ion()) {
+    return createFileID(createMemBufferContentCache(Buffer), IncludeLoc,
                         SrcMgr::C_User, LoadedID, LoadedOffset);
   }
=20
@@ -738,13 +759,19 @@
     if (MyInvalid || !Entry.isFile())
       return 0;
=20
-    return Entry.getFile().getContentCache()->OrigEntry;
+    const SrcMgr::ContentCache *Content =3D Entry.getFile().getContentCach=
e();
+    if (!Content)
+      return 0;
+    return Content->OrigEntry;
   }
=20
   /// Returns the FileEntry record for the provided SLocEntry.
   const FileEntry *getFileEntryForSLocEntry(const SrcMgr::SLocEntry &sloc)=
 const
   {
-    return sloc.getFile().getContentCache()->OrigEntry;
+    const SrcMgr::ContentCache *Content =3D sloc.getFile().getContentCache=
();
+    if (!Content)
+      return 0;
+    return Content->OrigEntry;
   }
=20
   /// getBufferData - Return a StringRef to the source buffer data for the
@@ -755,7 +782,7 @@
   StringRef getBufferData(FileID FID, bool *Invalid =3D 0) const;
=20
   /// \brief Get the number of FileIDs (files and macros) that were created
-  /// during preprocessing of \arg FID, including it.
+  /// during preprocessing of \p FID, including it.
   unsigned getNumCreatedFIDsForFileID(FileID FID) const {
     bool Invalid =3D false;
     const SrcMgr::SLocEntry &Entry =3D getSLocEntry(FID, &Invalid);
@@ -766,7 +793,7 @@
   }
=20
   /// \brief Set the number of FileIDs (files and macros) that were created
-  /// during preprocessing of \arg FID, including it.
+  /// during preprocessing of \p FID, including it.
   void setNumCreatedFIDsForFileID(FileID FID, unsigned NumFIDs) const {
     bool Invalid =3D false;
     const SrcMgr::SLocEntry &Entry =3D getSLocEntry(FID, &Invalid);
@@ -807,8 +834,20 @@
     unsigned FileOffset =3D Entry.getOffset();
     return SourceLocation::getFileLoc(FileOffset);
   }
+ =20
+  /// \brief Return the source location corresponding to the last byte of =
the
+  /// specified file.
+  SourceLocation getLocForEndOfFile(FileID FID) const {
+    bool Invalid =3D false;
+    const SrcMgr::SLocEntry &Entry =3D getSLocEntry(FID, &Invalid);
+    if (Invalid || !Entry.isFile())
+      return SourceLocation();
+   =20
+    unsigned FileOffset =3D Entry.getOffset();
+    return SourceLocation::getFileLoc(FileOffset + getFileIDSize(FID) - 1);
+  }
=20
-  /// \brief Returns the include location if \arg FID is a #include'd file
+  /// \brief Returns the include location if \p FID is a #include'd file
   /// otherwise it returns an invalid location.
   SourceLocation getIncludeLoc(FileID FID) const {
     bool Invalid =3D false;
@@ -828,7 +867,7 @@
     return getExpansionLocSlowCase(Loc);
   }
=20
-  /// \brief Given \arg Loc, if it is a macro location return the expansion
+  /// \brief Given \p Loc, if it is a macro location return the expansion
   /// location or the spelling location, depending on if it comes from a
   /// macro argument or not.
   SourceLocation getFileLoc(SourceLocation Loc) const {
@@ -868,7 +907,11 @@
   /// offset from the start of the buffer of the location.
   std::pair<FileID, unsigned> getDecomposedLoc(SourceLocation Loc) const {
     FileID FID =3D getFileID(Loc);
-    return std::make_pair(FID, Loc.getOffset()-getSLocEntry(FID).getOffset=
());
+    bool Invalid =3D false;
+    const SrcMgr::SLocEntry &E =3D getSLocEntry(FID, &Invalid);
+    if (Invalid)
+      return std::make_pair(FileID(), 0);
+    return std::make_pair(FID, Loc.getOffset()-E.getOffset());
   }
=20
   /// getDecomposedExpansionLoc - Decompose the specified location into a =
raw
@@ -877,7 +920,10 @@
   std::pair<FileID, unsigned>
   getDecomposedExpansionLoc(SourceLocation Loc) const {
     FileID FID =3D getFileID(Loc);
-    const SrcMgr::SLocEntry *E =3D &getSLocEntry(FID);
+    bool Invalid =3D false;
+    const SrcMgr::SLocEntry *E =3D &getSLocEntry(FID, &Invalid);
+    if (Invalid)
+      return std::make_pair(FileID(), 0);
=20
     unsigned Offset =3D Loc.getOffset()-E->getOffset();
     if (Loc.isFileID())
@@ -892,7 +938,10 @@
   std::pair<FileID, unsigned>
   getDecomposedSpellingLoc(SourceLocation Loc) const {
     FileID FID =3D getFileID(Loc);
-    const SrcMgr::SLocEntry *E =3D &getSLocEntry(FID);
+    bool Invalid =3D false;
+    const SrcMgr::SLocEntry *E =3D &getSLocEntry(FID, &Invalid);
+    if (Invalid)
+      return std::make_pair(FileID(), 0);
=20
     unsigned Offset =3D Loc.getOffset()-E->getOffset();
     if (Loc.isFileID())
@@ -914,10 +963,10 @@
   /// expanded.
   bool isMacroArgExpansion(SourceLocation Loc) const;
=20
-  /// \brief Returns true if \arg Loc is inside the [\arg Start, +\arg Len=
gth)
+  /// \brief Returns true if \p Loc is inside the [\p Start, +\p Length)
   /// chunk of the source location address space.
-  /// If it's true and \arg RelativeOffset is non-null, it will be set to =
the
-  /// relative offset of \arg Loc inside the chunk.
+  /// If it's true and \p RelativeOffset is non-null, it will be set to the
+  /// relative offset of \p Loc inside the chunk.
   bool isInSLocAddrSpace(SourceLocation Loc,
                          SourceLocation Start, unsigned Length,
                          unsigned *RelativeOffset =3D 0) const {
@@ -938,10 +987,10 @@
     return false;
   }
=20
-  /// \brief Return true if both \arg LHS and \arg RHS are in the local so=
urce
-  /// location address space or the loaded one. If it's true and
-  /// \arg RelativeOffset is non-null, it will be set to the offset of \ar=
g RHS
-  /// relative to \arg LHS.
+  /// \brief Return true if both \p LHS and \p RHS are in the local source
+  /// location address space or the loaded one. If it's true and \p
+  /// RelativeOffset is non-null, it will be set to the offset of \p RHS
+  /// relative to \p LHS.
   bool isInSameSLocAddrSpace(SourceLocation LHS, SourceLocation RHS,
                              int *RelativeOffset) const {
     unsigned LHSOffs =3D LHS.getOffset(), RHSOffs =3D RHS.getOffset();
@@ -1041,12 +1090,17 @@
     return getFileCharacteristic(Loc) =3D=3D SrcMgr::C_ExternCSystem;
   }
=20
-  /// \brief The size of the SLocEnty that \arg FID represents.
+  /// \brief Returns whether \p Loc is expanded from a macro in a system h=
eader.
+  bool isInSystemMacro(SourceLocation loc) {
+    return loc.isMacroID() && isInSystemHeader(getSpellingLoc(loc));
+  }
+
+  /// \brief The size of the SLocEnty that \p FID represents.
   unsigned getFileIDSize(FileID FID) const;
=20
-  /// \brief Given a specific FileID, returns true if \arg Loc is inside t=
hat
-  /// FileID chunk and sets relative offset (offset of \arg Loc from begin=
ning
-  /// of FileID) to \arg relativeOffset.
+  /// \brief Given a specific FileID, returns true if \p Loc is inside that
+  /// FileID chunk and sets relative offset (offset of \p Loc from beginni=
ng
+  /// of FileID) to \p relativeOffset.
   bool isInFileID(SourceLocation Loc, FileID FID,
                   unsigned *RelativeOffset =3D 0) const {
     unsigned Offs =3D Loc.getOffset();
@@ -1124,12 +1178,12 @@
   /// first inclusion.
   FileID translateFile(const FileEntry *SourceFile) const;
=20
-  /// \brief Get the source location in \arg FID for the given line:col.
-  /// Returns null location if \arg FID is not a file SLocEntry.
+  /// \brief Get the source location in \p FID for the given line:col.
+  /// Returns null location if \p FID is not a file SLocEntry.
   SourceLocation translateLineCol(FileID FID,
                                   unsigned Line, unsigned Col) const;
=20
-  /// \brief If \arg Loc points inside a function macro argument, the retu=
rned
+  /// \brief If \p Loc points inside a function macro argument, the return=
ed
   /// location will be the macro location in which the argument was expand=
ed.
   /// If a macro argument is used multiple times, the expanded location wi=
ll
   /// be at the first expansion of the argument.
@@ -1205,14 +1259,19 @@
   unsigned loaded_sloc_entry_size() const { return LoadedSLocEntryTable.si=
ze();}
=20
   /// \brief Get a loaded SLocEntry. This is exposed for indexing.
-  const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index, bool *Invali=
d=3D0) const {
+  const SrcMgr::SLocEntry &getLoadedSLocEntry(unsigned Index,
+                                              bool *Invalid =3D 0) const {
     assert(Index < LoadedSLocEntryTable.size() && "Invalid index");
-    if (!SLocEntryLoaded[Index])
-      ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2));
-    return LoadedSLocEntryTable[Index];
+    if (SLocEntryLoaded[Index])
+      return LoadedSLocEntryTable[Index];
+    return loadSLocEntry(Index, Invalid);
   }
=20
   const SrcMgr::SLocEntry &getSLocEntry(FileID FID, bool *Invalid =3D 0) c=
onst {
+    if (FID.ID =3D=3D 0 || FID.ID =3D=3D -1) {
+      if (Invalid) *Invalid =3D true;
+      return LocalSLocEntryTable[0];
+    }
     return getSLocEntryByID(FID.ID);
   }
=20
@@ -1233,18 +1292,32 @@
   std::pair<int, unsigned>
   AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize);
=20
-  /// \brief Returns true if \arg Loc came from a PCH/Module.
+  /// \brief Returns true if \p Loc came from a PCH/Module.
   bool isLoadedSourceLocation(SourceLocation Loc) const {
     return Loc.getOffset() >=3D CurrentLoadedOffset;
   }
=20
-  /// \brief Returns true if \arg Loc did not come from a PCH/Module.
+  /// \brief Returns true if \p Loc did not come from a PCH/Module.
   bool isLocalSourceLocation(SourceLocation Loc) const {
     return Loc.getOffset() < NextLocalOffset;
   }
=20
+  /// \brief Returns true if \p FID came from a PCH/Module.
+  bool isLoadedFileID(FileID FID) const {
+    assert(FID.ID !=3D -1 && "Using FileID sentinel value");
+    return FID.ID < 0;
+  }
+
+  /// \brief Returns true if \p FID did not come from a PCH/Module.
+  bool isLocalFileID(FileID FID) const {
+    return !isLoadedFileID(FID);
+  }
+
 private:
   const llvm::MemoryBuffer *getFakeBufferForRecovery() const;
+  const SrcMgr::ContentCache *getFakeContentCacheForRecovery() const;
+
+  const SrcMgr::SLocEntry &loadSLocEntry(unsigned Index, bool *Invalid) co=
nst;
=20
   /// \brief Get the entry with the given unwrapped FileID.
   const SrcMgr::SLocEntry &getSLocEntryByID(int ID) const {
@@ -1254,8 +1327,9 @@
     return getLocalSLocEntry(static_cast<unsigned>(ID));
   }
=20
-  const SrcMgr::SLocEntry &getLoadedSLocEntryByID(int ID) const {
-    return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2));
+  const SrcMgr::SLocEntry &getLoadedSLocEntryByID(int ID,
+                                                  bool *Invalid =3D 0) con=
st {
+    return getLoadedSLocEntry(static_cast<unsigned>(-ID - 2), Invalid);
   }
=20
   /// createExpansionLoc - Implements the common elements of storing an
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/Specifiers.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/Specifiers.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/Specifiers.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -40,6 +40,7 @@
     TST_char16,       // C++0x char16_t
     TST_char32,       // C++0x char32_t
     TST_int,
+    TST_int128,
     TST_half,         // OpenCL half, ARM NEON __fp16
     TST_float,
     TST_double,
@@ -58,7 +59,7 @@
     TST_underlyingType, // __underlying_type for C++0x
     TST_auto,         // C++0x auto
     TST_unknown_anytype, // __unknown_anytype extension
-    TST_atomic,       // C1X _Atomic
+    TST_atomic,       // C11 _Atomic
     TST_error         // erroneous type
   };
  =20
@@ -113,7 +114,12 @@
=20
     /// An Objective C property is a logical field of an Objective-C
     /// object which is read and written via Objective C method calls.
-    OK_ObjCProperty
+    OK_ObjCProperty,
+   =20
+    /// An Objective C array/dictionary subscripting which reads an object
+    /// or writes at the subscripted array/dictionary element via
+    /// Objective C method calls.
+    OK_ObjCSubscript
   };
=20
   // \brief Describes the kind of template specialization that a
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/StmtNodes.td
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/StmtNodes.td	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/StmtNodes.td	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -77,6 +77,7 @@
 def ParenListExpr : DStmt<Expr>;
 def VAArgExpr : DStmt<Expr>;
 def GenericSelectionExpr : DStmt<Expr>;
+def PseudoObjectExpr : DStmt<Expr>;
=20
 // Atomic expressions
 def AtomicExpr : DStmt<Expr>;
@@ -97,6 +98,7 @@
 def CXXConstCastExpr : DStmt<CXXNamedCastExpr>;
 def CXXFunctionalCastExpr : DStmt<ExplicitCastExpr>;
 def CXXTypeidExpr : DStmt<Expr>;
+def UserDefinedLiteral : DStmt<CallExpr>;
 def CXXBoolLiteralExpr : DStmt<Expr>;
 def CXXNullPtrLiteralExpr : DStmt<Expr>;
 def CXXThisExpr : DStmt<Expr>;
@@ -106,6 +108,7 @@
 def CXXNewExpr : DStmt<Expr>;
 def CXXDeleteExpr : DStmt<Expr>;
 def CXXPseudoDestructorExpr : DStmt<Expr>;
+def TypeTraitExpr : DStmt<Expr>;
 def UnaryTypeTraitExpr : DStmt<Expr>;
 def BinaryTypeTraitExpr : DStmt<Expr>;
 def ArrayTypeTraitExpr : DStmt<Expr>;
@@ -126,9 +129,13 @@
 def SubstNonTypeTemplateParmExpr : DStmt<Expr>;
 def SubstNonTypeTemplateParmPackExpr : DStmt<Expr>;
 def MaterializeTemporaryExpr : DStmt<Expr>;
+def LambdaExpr : DStmt<Expr>;
=20
 // Obj-C Expressions.
 def ObjCStringLiteral : DStmt<Expr>;
+def ObjCNumericLiteral : DStmt<Expr>;
+def ObjCArrayLiteral : DStmt<Expr>;
+def ObjCDictionaryLiteral : DStmt<Expr>;
 def ObjCEncodeExpr : DStmt<Expr>;
 def ObjCMessageExpr : DStmt<Expr>;
 def ObjCSelectorExpr : DStmt<Expr>;
@@ -137,6 +144,8 @@
 def ObjCPropertyRefExpr : DStmt<Expr>;
 def ObjCIsaExpr : DStmt<Expr>;
 def ObjCIndirectCopyRestoreExpr : DStmt<Expr>;
+def ObjCBoolLiteralExpr : DStmt<Expr>;
+def ObjCSubscriptRefExpr : DStmt<Expr>;
=20
 // Obj-C ARC Expressions.
 def ObjCBridgedCastExpr : DStmt<ExplicitCastExpr>;
@@ -147,7 +156,6 @@
 // Clang Extensions.
 def ShuffleVectorExpr : DStmt<Expr>;
 def BlockExpr : DStmt<Expr>;
-def BlockDeclRefExpr : DStmt<Expr>;
 def OpaqueValueExpr : DStmt<Expr>;
=20
 // Microsoft Extensions.
@@ -155,6 +163,7 @@
 def SEHTryStmt : Stmt;
 def SEHExceptStmt : Stmt;
 def SEHFinallyStmt : Stmt;
+def MSDependentExistsStmt : Stmt;
=20
 // OpenCL Extensions.
 def AsTypeExpr : DStmt<Expr>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/TargetBuiltins.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/TargetBuiltins.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/TargetBuiltins.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -56,6 +56,55 @@
     };
   }
=20
+  /// NeonTypeFlags - Flags to identify the types for overloaded Neon
+  /// builtins.  These must be kept in sync with the flags in
+  /// utils/TableGen/NeonEmitter.h.
+  class NeonTypeFlags {
+    enum {
+      EltTypeMask =3D 0xf,
+      UnsignedFlag =3D 0x10,
+      QuadFlag =3D 0x20
+    };
+    uint32_t Flags;
+
+  public:
+    enum EltType {
+      Int8,
+      Int16,
+      Int32,
+      Int64,
+      Poly8,
+      Poly16,
+      Float16,
+      Float32
+    };
+
+    NeonTypeFlags(unsigned F) : Flags(F) {}
+    NeonTypeFlags(EltType ET, bool IsUnsigned, bool IsQuad) : Flags(ET) {
+      if (IsUnsigned)
+        Flags |=3D UnsignedFlag;
+      if (IsQuad)
+        Flags |=3D QuadFlag;
+    }
+
+    EltType getEltType() const { return (EltType)(Flags & EltTypeMask); }
+    bool isPoly() const {
+      EltType ET =3D getEltType();
+      return ET =3D=3D Poly8 || ET =3D=3D Poly16;
+    }
+    bool isUnsigned() const { return (Flags & UnsignedFlag) !=3D 0; }
+    bool isQuad() const { return (Flags & QuadFlag) !=3D 0; }
+  };
+
+  /// Hexagon builtins
+  namespace Hexagon {
+    enum {
+        LastTIBuiltin =3D clang::Builtin::FirstTSBuiltin-1,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/BuiltinsHexagon.def"
+        LastTSBuiltin
+    };
+  }
 } // end namespace clang.
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/TargetInfo.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/TargetInfo.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/TargetInfo.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -59,11 +59,12 @@
=20
 /// TargetInfo - This class exposes information about the current target.
 ///
-class TargetInfo : public llvm::RefCountedBase<TargetInfo> {
+class TargetInfo : public RefCountedBase<TargetInfo> {
   llvm::Triple Triple;
 protected:
   // Target values set by the ctor of the actual target implementation.  D=
efault
   // values are specified by the TargetInfo constructor.
+  bool BigEndian;
   bool TLSSupported;
   bool NoAsmVariants;  // True if {|} are normal characters.
   unsigned char PointerWidth, PointerAlign;
@@ -76,6 +77,7 @@
   unsigned char LargeArrayMinWidth, LargeArrayAlign;
   unsigned char LongWidth, LongAlign;
   unsigned char LongLongWidth, LongLongAlign;
+  unsigned char SuitableAlign;
   unsigned char MaxAtomicPromoteWidth, MaxAtomicInlineWidth;
   const char *DescriptionString;
   const char *UserLabelPrefix;
@@ -91,6 +93,7 @@
=20
   unsigned HasAlignMac68kSupport : 1;
   unsigned RealTypeUsesObjCFPRet : 3;
+  unsigned ComplexLongDoubleUsesFP2Ret : 1;
=20
   // TargetInfo Constructor.  Default initializes all fields.
   TargetInfo(const std::string &T);
@@ -211,6 +214,10 @@
   unsigned getLongLongWidth() const { return LongLongWidth; }
   unsigned getLongLongAlign() const { return LongLongAlign; }
=20
+  /// getSuitableAlign - Return the alignment that is suitable for storing=
 any
+  /// object with a fundamental alignment requirement.
+  unsigned getSuitableAlign() const { return SuitableAlign; }
+
   /// getWCharWidth/Align - Return the size of 'wchar_t' for this target, =
in
   /// bits.
   unsigned getWCharWidth() const { return getTypeWidth(WCharType); }
@@ -249,6 +256,9 @@
     return *LongDoubleFormat;
   }
=20
+  /// getFloatEvalMethod - Return the value for the C99 FLT_EVAL_METHOD ma=
cro.
+  virtual unsigned getFloatEvalMethod() const { return 0; }
+
   // getLargeArrayMinWidth/Align - Return the minimum array size that is
   // 'large' and its alignment.
   unsigned getLargeArrayMinWidth() const { return LargeArrayMinWidth; }
@@ -327,6 +337,12 @@
     return RealTypeUsesObjCFPRet & (1 << T);
   }
=20
+  /// \brief Check whether _Complex long double should use the "fp2ret" fl=
avor
+  /// of Obj-C message passing on this target.
+  bool useObjCFP2RetForComplexLongDouble() const {
+    return ComplexLongDoubleUsesFP2Ret;
+  }
+
   ///=3D=3D=3D---- Other target property query methods -------------------=
-------=3D=3D=3D//
=20
   /// getTargetDefines - Appends the target-specific #define values for th=
is
@@ -341,6 +357,13 @@
   virtual void getTargetBuiltins(const Builtin::Info *&Records,
                                  unsigned &NumRecords) const =3D 0;
=20
+  /// isCLZForZeroUndef - The __builtin_clz* and __builtin_ctz* built-in
+  /// functions are specified to have undefined results for zero inputs, b=
ut
+  /// on targets that support these operations in a way that provides
+  /// well-defined results for zero without loss of performance, it is a g=
ood
+  /// idea to avoid optimizing based on that undef behavior.
+  virtual bool isCLZForZeroUndef() const { return true; }
+
   /// getVAListDeclaration - Return the declaration to use for
   /// __builtin_va_list, which is target-specific.
   virtual const char *getVAListDeclaration() const =3D 0;
@@ -456,6 +479,19 @@
     const unsigned RegNum;
   };
=20
+  /// hasProtectedVisibility - Does this target support "protected"
+  /// visibility?
+  ///
+  /// Any target which dynamic libraries will naturally support
+  /// something like "default" (meaning that the symbol is visible
+  /// outside this shared object) and "hidden" (meaning that it isn't)
+  /// visibilities, but "protected" is really an ELF-specific concept
+  /// with wierd semantics designed around the convenience of dynamic
+  /// linker implementations.  Which is not to suggest that there's
+  /// consistent target-independent semantics for "default" visibility
+  /// either; the entire thing is pretty badly mangled.
+  virtual bool hasProtectedVisibility() const { return true; }
+
   virtual bool useGlobalsForAutomaticVariables() const { return false; }
=20
   /// getCFStringSection - Return the section to use for CFString
@@ -551,7 +587,7 @@
   ///
   /// \return - False on error (invalid feature name).
   virtual bool setFeatureEnabled(llvm::StringMap<bool> &Features,
-                                 const std::string &Name,
+                                 StringRef Name,
                                  bool Enabled) const {
     return false;
   }
@@ -565,6 +601,11 @@
   virtual void HandleTargetFeatures(std::vector<std::string> &Features) {
   }
=20
+  /// \brief Determine whether the given target has the given feature.
+  virtual bool hasFeature(StringRef Feature) const {
+    return false;
+  }
+ =20
   // getRegParmMax - Returns maximal number of args passed in registers.
   unsigned getRegParmMax() const {
     assert(RegParmMax < 7 && "RegParmMax value is larger than AST can hand=
le");
@@ -609,6 +650,8 @@
   /// which the program should be compiled.
   VersionTuple getPlatformMinVersion() const { return PlatformMinVersion; }
=20
+  bool isBigEndian() const { return BigEndian; }
+
 protected:
   virtual uint64_t getPointerWidthV(unsigned AddrSpace) const {
     return PointerWidth;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/TokenKinds.def
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/TokenKinds.def	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/TokenKinds.def	Tue =
Apr 17 11:51:51 2012 +0300
@@ -90,7 +90,8 @@
 PPKEYWORD(unassert)
=20
 // Clang extensions
-PPKEYWORD(__export_macro__)
+PPKEYWORD(__public_macro)
+PPKEYWORD(__private_macro)
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Language keywords.
@@ -203,7 +204,7 @@
 //              is a keyword in the implementation namespace that should
 //              always be treated as a keyword
 //   KEYC99   - This is a keyword introduced to C in C99
-//   KEYC1X   - This is a keyword introduced to C in C1X
+//   KEYC11   - This is a keyword introduced to C in C11
 //   KEYCXX   - This is a C++ keyword, or a C++-specific keyword in the
 //              implementation namespace
 //   KEYNOCXX - This is a keyword in every non-C++ dialect.
@@ -257,6 +258,9 @@
 KEYWORD(_Imaginary                  , KEYALL)
 KEYWORD(_Static_assert              , KEYALL)
 KEYWORD(__func__                    , KEYALL)
+KEYWORD(__objc_yes                  , KEYALL)
+KEYWORD(__objc_no                   , KEYALL)
+
=20
 // C++ 2.11p1: Keywords.
 KEYWORD(asm                         , KEYCXX|KEYGNU)
@@ -328,6 +332,7 @@
 KEYWORD(__builtin_va_arg            , KEYALL)
 KEYWORD(__extension__               , KEYALL)
 KEYWORD(__imag                      , KEYALL)
+KEYWORD(__int128                    , KEYALL)
 KEYWORD(__label__                   , KEYALL)
 KEYWORD(__real                      , KEYALL)
 KEYWORD(__thread                    , KEYALL)
@@ -352,6 +357,7 @@
 KEYWORD(__is_convertible_to         , KEYCXX)
 KEYWORD(__is_empty                  , KEYCXX)
 KEYWORD(__is_enum                   , KEYCXX)
+KEYWORD(__is_final                  , KEYCXX)
 // Tentative name - there's no implementation of std::is_literal_type yet.
 KEYWORD(__is_literal                , KEYCXX)
 // Name for GCC 4.6 compatibility - people have already written libraries =
using
@@ -363,7 +369,9 @@
 KEYWORD(__is_union                  , KEYCXX)
=20
 // Clang-only C++ Type Traits
+KEYWORD(__is_trivially_constructible, KEYCXX)
 KEYWORD(__is_trivially_copyable     , KEYCXX)
+KEYWORD(__is_trivially_assignable   , KEYCXX)
 KEYWORD(__underlying_type           , KEYCXX)
=20
 // Embarcadero Expression Traits
@@ -403,7 +411,6 @@
=20
 // Apple Extension.
 KEYWORD(__private_extern__          , KEYALL)
-KEYWORD(__import_module__           , KEYALL)
 KEYWORD(__module_private__          , KEYALL)
=20
 // Microsoft Extension.
@@ -484,7 +491,6 @@
 KEYWORD(__w64                     , KEYMS)
 KEYWORD(__uuidof                  , KEYMS | KEYBORLAND)
 KEYWORD(__try                     , KEYMS | KEYBORLAND)
-KEYWORD(__except                  , KEYMS | KEYBORLAND)
 KEYWORD(__finally                 , KEYMS | KEYBORLAND)
 KEYWORD(__leave                   , KEYMS | KEYBORLAND)
 KEYWORD(__int64                   , KEYMS)
@@ -501,7 +507,7 @@
 ALIAS("_uuidof"      , __uuidof   , KEYMS | KEYBORLAND)
 ALIAS("_inline"      , inline     , KEYMS)
 ALIAS("_declspec"    , __declspec , KEYMS)
-ALIAS("__interface"  , class      , KEYMS)
+ALIAS("__interface"  , struct     , KEYMS)
=20
 // Borland Extensions which should be disabled in strict conformance mode.
 ALIAS("_pascal"      , __pascal   , KEYBORLAND)
@@ -547,6 +553,7 @@
 OBJC2_AT_KEYWORD(optional)
 OBJC2_AT_KEYWORD(synthesize)
 OBJC2_AT_KEYWORD(dynamic)
+OBJC2_AT_KEYWORD(__experimental_modules_import)
=20
 // TODO: What to do about context-sensitive keywords like:
 //       bycopy/byref/in/inout/oneway/out?
@@ -559,12 +566,24 @@
                          // function template specialization (not a type),
                          // e.g., "std::swap<int>"
 ANNOTATION(primary_expr) // annotation for a primary expression
+ANNOTATION(decltype)     // annotation for a decltype expression,
+                         // e.g., "decltype(foo.bar())"
=20
 // Annotation for #pragma unused(...)
 // For each argument inside the parentheses the pragma handler will produce
 // one 'pragma_unused' annotation token followed by the argument token.
 ANNOTATION(pragma_unused)
=20
+// Annotation for #pragma GCC visibility...
+// The lexer produces these so that they only take effect when the parser
+// handles them.
+ANNOTATION(pragma_vis)
+
+// Annotation for #pragma pack...
+// The lexer produces these so that they only take effect when the parser
+// handles them.
+ANNOTATION(pragma_pack)
+
 #undef ANNOTATION
 #undef TESTING_KEYWORD
 #undef OBJC2_AT_KEYWORD
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/TypeTraits.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/TypeTraits.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/TypeTraits.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -35,6 +35,7 @@
     UTT_IsConst,
     UTT_IsEmpty,
     UTT_IsEnum,
+    UTT_IsFinal,
     UTT_IsFloatingPoint,
     UTT_IsFunction,
     UTT_IsFundamental,
@@ -67,7 +68,8 @@
     BTT_IsConvertible,
     BTT_IsConvertibleTo,
     BTT_IsSame,
-    BTT_TypeCompatible
+    BTT_TypeCompatible,
+    BTT_IsTriviallyAssignable
   };
=20
   /// ArrayTypeTrait - Names for the array type traits.
@@ -82,6 +84,12 @@
     UETT_AlignOf,
     UETT_VecStep
   };
+ =20
+  /// \brief Names for type traits that operate specifically on types.
+  enum TypeTrait {
+    TT_IsTriviallyConstructible
+  };
+ =20
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Basic/Version.h
--- a/head/contrib/llvm/tools/clang/include/clang/Basic/Version.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Basic/Version.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -7,7 +7,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-// This header defines version macros and version-related utility function=
s=20
+// This header defines version macros and version-related utility functions
 // for Clang.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -29,7 +29,8 @@
 /// \brief A string that describes the Clang version number, e.g.,
 /// "1.0".
 #define CLANG_VERSION_STRING \
-  CLANG_MAKE_VERSION_STRING(CLANG_VERSION_MAJOR,CLANG_VERSION_MINOR,CLANG_=
VERSION_PATCHLEVEL)
+  CLANG_MAKE_VERSION_STRING(CLANG_VERSION_MAJOR,CLANG_VERSION_MINOR, \
+                            CLANG_VERSION_PATCHLEVEL)
 #else
 /// \brief Helper macro for CLANG_VERSION_STRING.
 #define CLANG_MAKE_VERSION_STRING(X,Y) CLANG_MAKE_VERSION_STRING2(X.Y)
@@ -41,21 +42,30 @@
 #endif
=20
 namespace clang {
-  /// \brief Retrieves the repository path (e.g., Subversion path) that=20
+  /// \brief Retrieves the repository path (e.g., Subversion path) that
   /// identifies the particular Clang branch, tag, or trunk from which this
   /// Clang was built.
   std::string getClangRepositoryPath();
- =20
+
+  /// \brief Retrieves the repository path from which LLVM was built. Supp=
orts
+  /// LLVM residing in a separate repository from clang.
+  std::string getLLVMRepositoryPath();
+
   /// \brief Retrieves the repository revision number (or identifer) from =
which
   ///  this Clang was built.
   std::string getClangRevision();
- =20
+
+  /// \brief Retrieves the repository revision number (or identifer) from =
which
+  /// LLVM was built. If Clang and LLVM are in the same repository, this r=
eturns
+  /// the same string as getClangRevision.
+  std::string getLLVMRevision();
+
   /// \brief Retrieves the full repository version that is an amalgamation=
 of
   ///  the information in getClangRepositoryPath() and getClangRevision().
   std::string getClangFullRepositoryVersion();
- =20
+
   /// \brief Retrieves a string representing the complete clang version,
-  ///   which includes the clang version number, the repository version,=20
+  ///   which includes the clang version number, the repository version,
   ///   and the vendor tag.
   std::string getClangFullVersion();
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/CodeGen/CodeGenAction.h
--- a/head/contrib/llvm/tools/clang/include/clang/CodeGen/CodeGenAction.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/CodeGen/CodeGenAction.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,8 @@
 class CodeGenAction : public ASTFrontendAction {
 private:
   unsigned Act;
-  llvm::OwningPtr<llvm::Module> TheModule;
+  OwningPtr<llvm::Module> TheModule;
+  llvm::Module *LinkModule;
   llvm::LLVMContext *VMContext;
   bool OwnsVMContext;
=20
@@ -46,6 +47,11 @@
 public:
   ~CodeGenAction();
=20
+  /// setLinkModule - Set the link module to be used by this action.  If a=
 link
+  /// module is not provided, and CodeGenOptions::LinkBitcodeFile is non-e=
mpty,
+  /// the action will load it from the specified file.
+  void setLinkModule(llvm::Module *Mod) { LinkModule =3D Mod; }
+
   /// takeModule - Take the generated LLVM module, for use after the actio=
n has
   /// been run. The result may be null on failure.
   llvm::Module *takeModule();
@@ -57,31 +63,37 @@
 };
=20
 class EmitAssemblyAction : public CodeGenAction {
+  virtual void anchor();
 public:
   EmitAssemblyAction(llvm::LLVMContext *_VMContext =3D 0);
 };
=20
 class EmitBCAction : public CodeGenAction {
+  virtual void anchor();
 public:
   EmitBCAction(llvm::LLVMContext *_VMContext =3D 0);
 };
=20
 class EmitLLVMAction : public CodeGenAction {
+  virtual void anchor();
 public:
   EmitLLVMAction(llvm::LLVMContext *_VMContext =3D 0);
 };
=20
 class EmitLLVMOnlyAction : public CodeGenAction {
+  virtual void anchor();
 public:
   EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext =3D 0);
 };
=20
 class EmitCodeGenOnlyAction : public CodeGenAction {
+  virtual void anchor();
 public:
   EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext =3D 0);
 };
=20
 class EmitObjAction : public CodeGenAction {
+  virtual void anchor();
 public:
   EmitObjAction(llvm::LLVMContext *_VMContext =3D 0);
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/CodeGen/ModuleBuilder.h
--- a/head/contrib/llvm/tools/clang/include/clang/CodeGen/ModuleBuilder.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/CodeGen/ModuleBuilder.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -28,6 +28,7 @@
   class CodeGenOptions;
=20
   class CodeGenerator : public ASTConsumer {
+    virtual void anchor();
   public:
     virtual llvm::Module* GetModule() =3D 0;
     virtual llvm::Module* ReleaseModule() =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/Action.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/Action.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/Action.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -39,6 +39,7 @@
     PreprocessJobClass,
     PrecompileJobClass,
     AnalyzeJobClass,
+    MigrateJobClass,
     CompileJobClass,
     AssembleJobClass,
     LinkJobClass,
@@ -94,6 +95,7 @@
 };
=20
 class InputAction : public Action {
+  virtual void anchor();
   const Arg &Input;
 public:
   InputAction(const Arg &_Input, types::ID _Type);
@@ -107,6 +109,7 @@
 };
=20
 class BindArchAction : public Action {
+  virtual void anchor();
   /// The architecture to bind, or 0 if the default architecture
   /// should be bound.
   const char *ArchName;
@@ -123,6 +126,7 @@
 };
=20
 class JobAction : public Action {
+  virtual void anchor();
 protected:
   JobAction(ActionClass Kind, Action *Input, types::ID Type);
   JobAction(ActionClass Kind, const ActionList &Inputs, types::ID Type);
@@ -136,6 +140,7 @@
 };
=20
 class PreprocessJobAction : public JobAction {
+  virtual void anchor();
 public:
   PreprocessJobAction(Action *Input, types::ID OutputType);
=20
@@ -146,6 +151,7 @@
 };
=20
 class PrecompileJobAction : public JobAction {
+  virtual void anchor();
 public:
   PrecompileJobAction(Action *Input, types::ID OutputType);
=20
@@ -156,6 +162,7 @@
 };
=20
 class AnalyzeJobAction : public JobAction {
+  virtual void anchor();
 public:
   AnalyzeJobAction(Action *Input, types::ID OutputType);
=20
@@ -165,7 +172,19 @@
   static bool classof(const AnalyzeJobAction *) { return true; }
 };
=20
+class MigrateJobAction : public JobAction {
+  virtual void anchor();
+public:
+  MigrateJobAction(Action *Input, types::ID OutputType);
+
+  static bool classof(const Action *A) {
+    return A->getKind() =3D=3D MigrateJobClass;
+  }
+  static bool classof(const MigrateJobAction *) { return true; }
+};
+
 class CompileJobAction : public JobAction {
+  virtual void anchor();
 public:
   CompileJobAction(Action *Input, types::ID OutputType);
=20
@@ -176,6 +195,7 @@
 };
=20
 class AssembleJobAction : public JobAction {
+  virtual void anchor();
 public:
   AssembleJobAction(Action *Input, types::ID OutputType);
=20
@@ -186,6 +206,7 @@
 };
=20
 class LinkJobAction : public JobAction {
+  virtual void anchor();
 public:
   LinkJobAction(ActionList &Inputs, types::ID Type);
=20
@@ -196,6 +217,7 @@
 };
=20
 class LipoJobAction : public JobAction {
+  virtual void anchor();
 public:
   LipoJobAction(ActionList &Inputs, types::ID Type);
=20
@@ -206,6 +228,7 @@
 };
=20
 class DsymutilJobAction : public JobAction {
+  virtual void anchor();
 public:
   DsymutilJobAction(ActionList &Inputs, types::ID Type);
=20
@@ -216,6 +239,7 @@
 };
=20
 class VerifyJobAction : public JobAction {
+  virtual void anchor();
 public:
   VerifyJobAction(ActionList &Inputs, types::ID Type);
   static bool classof(const Action *A) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/ArgList.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/ArgList.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/ArgList.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -185,6 +185,8 @@
     Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2) =
const;
     Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
                     OptSpecifier Id3) const;
+    Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
+                    OptSpecifier Id3, OptSpecifier Id4) const;
=20
     /// getArgString - Return the input argument string at \arg Index.
     virtual const char *getArgString(unsigned Index) const =3D 0;
@@ -203,9 +205,17 @@
                                     StringRef Default =3D "") const;
=20
     /// getLastArgValue - Return the value of the last argument as an inte=
ger,
+    /// or a default. If Diags is non-null, emits an error if the argument
+    /// is given, but non-integral.
+    int getLastArgIntValue(OptSpecifier Id, int Default,
+                           DiagnosticsEngine *Diags =3D 0) const;
+
+    /// getLastArgValue - Return the value of the last argument as an inte=
ger,
     /// or a default. Emits an error if the argument is given, but non-int=
egral.
     int getLastArgIntValue(OptSpecifier Id, int Default,
-                           DiagnosticsEngine &Diags) const;
+                           DiagnosticsEngine &Diags) const {
+      return getLastArgIntValue(Id, Default, &Diags);
+    }
=20
     /// getAllArgValues - Get the values of all instances of the given arg=
ument
     /// as strings.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/CC1AsOptions.td
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/CC1AsOptions.td	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/CC1AsOptions.td	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -20,6 +20,10 @@
=20
 def triple : Separate<"-triple">,
   HelpText<"Specify target triple (e.g. x86_64-pc-linux-gnu)">;
+def target_cpu : Separate<"-target-cpu">,
+  HelpText<"Target a specific cpu type">;
+def target_feature : Separate<"-target-feature">,
+  HelpText<"Target specific attributes">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Language Options
@@ -80,3 +84,8 @@
=20
 def fatal_warnings : Flag<"--fatal-warnings">,
     HelpText<"Consider warnings as errors">;
+
+def g : Flag<"-g">, HelpText<"Generate source level debug information">;
+
+def dwarf_debug_flags : Separate<"-dwarf-debug-flags">,
+  HelpText<"The string to embed in the Dwarf debug flags record.">;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/CC1Options.td
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/CC1Options.td	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/CC1Options.td	Tue =
Apr 17 11:51:51 2012 +0300
@@ -80,12 +80,34 @@
   HelpText<"Display exploded graph using GraphViz">;
 def analyzer_viz_egraph_ubigraph : Flag<"-analyzer-viz-egraph-ubigraph">,
   HelpText<"Display exploded graph using Ubigraph">;
-def analyzer_inline_call : Flag<"-analyzer-inline-call">,
-  HelpText<"Experimental transfer function inlining callees when its defin=
ition is available.">;
+
+def analyzer_inline_max_stack_depth : Separate<"-analyzer-inline-max-stack=
-depth">,
+  HelpText<"Bound on stack depth while inlining (4 by default)">;
+def analyzer_inline_max_stack_depth_EQ : Joined<"-analyzer-inline-max-stac=
k-depth=3D">,=20
+  Alias<analyzer_inline_max_stack_depth>;
+ =20
+def analyzer_inline_max_function_size : Separate<"-analyzer-inline-max-fun=
ction-size">,
+  HelpText<"Bound on the number of basic blocks in an inlined function (20=
0 by default)">;
+def analyzer_inline_max_function_size_EQ : Joined<"-analyzer-inline-max-fu=
nction-size=3D">,=20
+  Alias<analyzer_inline_max_function_size>;
+
+def analyzer_ipa : Separate<"-analyzer-ipa">,
+  HelpText<"Specify the inter-procedural analysis mode">;
+def analyzer_ipa_EQ : Joined<"-analyzer-ipa=3D">, Alias<analyzer_ipa>;
+ =20
+def analyzer_inlining_mode : Separate<"-analyzer-inlining-mode">,
+  HelpText<"Specify the function selection heuristic used during inlining"=
>;
+def analyzer_inlining_mode_EQ : Joined<"-analyzer-inlining-mode=3D">, Alia=
s<analyzer_inlining_mode>;
+
+def analyzer_disable_retry_exhausted : Flag<"-analyzer-disable-retry-exhau=
sted">,
+  HelpText<"Do not re-analyze paths leading to exhausted nodes with a diff=
erent strategy (may decrease code coverage)">;
+ =20
 def analyzer_max_nodes : Separate<"-analyzer-max-nodes">,
   HelpText<"The maximum number of nodes the analyzer can generate (150000 =
default, 0 =3D no limit)">;
 def analyzer_max_loop : Separate<"-analyzer-max-loop">,
   HelpText<"The maximum number of times the analyzer will go through a loo=
p">;
+def analyzer_stats : Flag<"-analyzer-stats">,
+  HelpText<"Print internal analyzer statistics.">;
=20
 def analyzer_checker : Separate<"-analyzer-checker">,
   HelpText<"Choose analyzer checkers to enable">;
@@ -101,6 +123,15 @@
   HelpText<"Display the list of analyzer checkers that are available">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Migrator Options
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+def migrator_no_nsalloc_error : Flag<"-no-ns-alloc-error">,
+  HelpText<"Do not error on use of NSAllocateCollectable/NSReallocateColle=
ctable">;
+
+def migrator_no_finalize_removal : Flag<"-no-finalize-removal">,
+  HelpText<"Do not remove finalize method in gc mode">;
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // CodeGen Options
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -110,13 +141,21 @@
   HelpText<"Don't run the LLVM IR verifier pass">;
 def disable_red_zone : Flag<"-disable-red-zone">,
   HelpText<"Do not emit code that uses the red zone.">;
+def fdebug_compilation_dir : Separate<"-fdebug-compilation-dir">,
+  HelpText<"The compilation directory to embed in the debug info.">;
 def dwarf_debug_flags : Separate<"-dwarf-debug-flags">,
   HelpText<"The string to embed in the Dwarf debug flags record.">;
+def faddress_sanitizer: Flag<"-faddress-sanitizer">,
+  HelpText<"Enable AddressSanitizer instrumentation (memory error detectio=
n)">;
+def fthread_sanitizer: Flag<"-fthread-sanitizer">,
+  HelpText<"Enable ThreadSanitizer instrumentation (race detection)">;
 def fforbid_guard_variables : Flag<"-fforbid-guard-variables">,
   HelpText<"Emit an error if a C++ static local initializer would need a g=
uard variable">;
 def g : Flag<"-g">, HelpText<"Generate source level debug information">;
 def fno_dwarf2_cfi_asm : Flag<"-fno-dwarf2-cfi-asm">,
   HelpText<"Don't use the cfi directives">;
+def fno_dwarf_directory_asm : Flag<"-fno-dwarf-directory-asm">,
+  HelpText<"Don't separate directory and filename in .file directives">;
 def fcatch_undefined_behavior : Flag<"-fcatch-undefined-behavior">,
   HelpText<"Generate runtime checks for undefined behavior.">;
 def flimit_debug_info : Flag<"-flimit-debug-info">,
@@ -127,6 +166,8 @@
   HelpText<"Don't generate implicit floating point instructions (x86-only)=
">;
 def finstrument_functions : Flag<"-finstrument-functions">,
   HelpText<"Generate calls to instrument function entry and exit">;
+def fno_limit_debug_info : Flag<"-fno-limit-debug-info">,
+  HelpText<"Do not limit debug information produced to reduce size of debu=
g binary">;
 def fno_merge_all_constants : Flag<"-fno-merge-all-constants">,
   HelpText<"Disallow merging of constants.">;
 def fno_threadsafe_statics : Flag<"-fno-threadsafe-statics">,
@@ -137,6 +178,11 @@
   HelpText<"Place each function in its own section (ELF Only)">;
 def fdata_sections : Flag<"-fdata-sections">,
   HelpText<"Place each data in its own section (ELF Only)">;
+def fstrict_enums : Flag<"-fstrict-enums">,
+  HelpText<"Enable optimizations based on the strict definition of an enum=
's "
+           "value range.">;
+def ftrap_function_EQ : Joined<"-ftrap-function=3D">,
+  HelpText<"Issue call to specified function rather than a trap instructio=
n">;
 def funroll_loops : Flag<"-funroll-loops">,
   HelpText<"Turn on loop unroller">;
 def femit_coverage_notes : Flag<"-femit-coverage-notes">,
@@ -158,6 +204,15 @@
   HelpText<"Enable additional debug output">;
 def mdisable_fp_elim : Flag<"-mdisable-fp-elim">,
   HelpText<"Disable frame pointer elimination optimization">;
+def mdisable_tail_calls : Flag<"-mdisable-tail-calls">,
+  HelpText<"Disable tail call optimization, keeping the call stack accurat=
e">;
+def menable_no_infinities : Flag<"-menable-no-infs">,
+  HelpText<"Allow optimization to assume there are no infinities.">;
+def menable_no_nans : Flag<"-menable-no-nans">,
+  HelpText<"Allow optimization to assume there are no NaNs.">;
+def menable_unsafe_fp_math : Flag<"-menable-unsafe-fp-math">,
+  HelpText<"Allow unsafe floating-point math optimizations which may decre=
ase "
+           "precision">;
 def mfloat_abi : Separate<"-mfloat-abi">,
   HelpText<"The float ABI to use">;
 def mno_global_merge : Flag<"-mno-global-merge">,
@@ -192,6 +247,10 @@
   HelpText<"Set the default structure layout to be compatible with the Mic=
rosoft compiler standard.">;
 def mstackrealign : Flag<"-mstackrealign">,
   HelpText<"Force realign the stack at entry to every function.">;
+def mstack_alignment : Joined<"-mstack-alignment=3D">,
+  HelpText<"Set the stack alignment">;
+def mlink_bitcode_file : Separate<"-mlink-bitcode-file">,
+  HelpText<"Link the given bitcode file before performing optimizations.">;
 def O : Joined<"-O">, HelpText<"Optimization level">;
 def Os : Flag<"-Os">, HelpText<"Optimize for size">;
 def Oz : Flag<"-Oz">, HelpText<"Optimize for size, regardless of performan=
ce">;
@@ -203,6 +262,8 @@
=20
 def dependency_file : Separate<"-dependency-file">,
   HelpText<"Filename (or -) to write dependency output to">;
+def dependency_dot : Separate<"-dependency-dot">,
+  HelpText<"Filename to write DOT-formatted header dependencies to">;
 def sys_header_deps : Flag<"-sys-header-deps">,
   HelpText<"Include system headers in dependency output">;
 def header_include_file : Separate<"-header-include-file">,
@@ -224,6 +285,9 @@
   HelpText<"output a dump of some build information to a file">;
 def diagnostic_log_file : Separate<"-diagnostic-log-file">,
   HelpText<"Filename (or -) to log diagnostics to">;
+def diagnostic_serialized_file : Separate<"-serialize-diagnostic-file">,
+  MetaVarName<"<filename>">,
+  HelpText<"File for serializing diagnostics in a binary format">;
 def fno_show_column : Flag<"-fno-show-column">,
   HelpText<"Do not include column number on diagnostics">;
 def fshow_column : Flag<"-fshow-column">,
@@ -253,8 +317,6 @@
   HelpText<"Print source range spans in numeric form">;
 def fdiagnostics_parseable_fixits : Flag<"-fdiagnostics-parseable-fixits">,
   HelpText<"Print fix-its in machine parseable form">;
-def fdiagnostics_show_name : Flag<"-fdiagnostics-show-name">,
-  HelpText<"Print diagnostic name">;
 def fdiagnostics_show_option : Flag<"-fdiagnostics-show-option">,
   HelpText<"Print option name with mappable diagnostics">;
 def fdiagnostics_format : Separate<"-fdiagnostics-format">,
@@ -272,6 +334,8 @@
   HelpText<"Set the maximum number of entries to print in a macro expansio=
n backtrace (0 =3D no limit).">;
 def ftemplate_backtrace_limit : Separate<"-ftemplate-backtrace-limit">, Me=
taVarName<"<N>">,
   HelpText<"Set the maximum number of entries to print in a template insta=
ntiation backtrace (0 =3D no limit).">;
+def fconstexpr_backtrace_limit : Separate<"-fconstexpr-backtrace-limit">, =
MetaVarName<"<N>">,
+  HelpText<"Set the maximum number of entries to print in a constexpr eval=
uation backtrace (0 =3D no limit).">;
 def fmessage_length : Separate<"-fmessage-length">, MetaVarName<"<N>">,
   HelpText<"Format message diagnostics so that they fit within N columns o=
r fewer, when possible.">;
 def fcolor_diagnostics : Flag<"-fcolor-diagnostics">,
@@ -364,8 +428,11 @@
   HelpText<"Build ASTs and view them with GraphViz">;
 def print_decl_contexts : Flag<"-print-decl-contexts">,
   HelpText<"Print DeclContexts and their Decls">;
+def pubnames_dump : Flag<"-pubnames-dump">,=20
+  HelpText<"Print all of the public (global) names in the source, e.g., th=
e "
+           "names of all global declarations and macros">;
 def emit_module : Flag<"-emit-module">,
-  HelpText<"Generate pre-compiled module file">;
+  HelpText<"Generate pre-compiled module file from a module map">;
 def emit_pth : Flag<"-emit-pth">,
   HelpText<"Generate pre-tokenized header file">;
 def emit_pch : Flag<"-emit-pch">,
@@ -388,21 +455,28 @@
   HelpText<"Rewrite ObjC into C (code rewriter example)">;
 def rewrite_macros : Flag<"-rewrite-macros">,
   HelpText<"Expand macros without full preprocessing">;
+def migrate : Flag<"-migrate">,
+  HelpText<"Migrate source code">;
 }
=20
+def mt_migrate_directory : Separate<"-mt-migrate-directory">,
+  HelpText<"Directory for temporary files produced during ARC or ObjC migr=
ation">;
 def arcmt_check : Flag<"-arcmt-check">,
   HelpText<"Check for ARC migration issues that need manual handling">;
 def arcmt_modify : Flag<"-arcmt-modify">,
   HelpText<"Apply modifications to files to conform to ARC">;
 def arcmt_migrate : Flag<"-arcmt-migrate">,
   HelpText<"Apply modifications and produces temporary files that conform =
to ARC">;
-def arcmt_migrate_directory : Separate<"-arcmt-migrate-directory">,
-  HelpText<"Directory for temporary files produced during ARC migration">;
 def arcmt_migrate_report_output : Separate<"-arcmt-migrate-report-output">,
   HelpText<"Output path for the plist report">;
 def arcmt_migrate_emit_arc_errors : Flag<"-arcmt-migrate-emit-errors">,
   HelpText<"Emit ARC errors even if the migrator can fix them">;
=20
+def objcmt_migrate_literals : Flag<"-objcmt-migrate-literals">,
+  HelpText<"Enable migration to modern ObjC literals">;
+def objcmt_migrate_subscripting : Flag<"-objcmt-migrate-subscripting">,
+  HelpText<"Enable migration to modern ObjC subscripting">;
+
 def working_directory : JoinedOrSeparate<"-working-directory">,
   HelpText<"Resolve file paths relative to the specified directory">;
 def working_directory_EQ : Joined<"-working-directory=3D">,
@@ -416,14 +490,25 @@
   HelpText<"Print the amount of time each phase of compilation takes">;
 def fdump_record_layouts : Flag<"-fdump-record-layouts">,
   HelpText<"Dump record layout information">;
+def fdump_record_layouts_simple : Flag<"-fdump-record-layouts-simple">,
+  HelpText<"Dump record layout information in a simple form used for testi=
ng">;
 def fix_what_you_can : Flag<"-fix-what-you-can">,
   HelpText<"Apply fix-it advice even in the presence of unfixable errors">;
+def fix_only_warnings : Flag<"-fix-only-warnings">,
+  HelpText<"Apply fix-it advice only for warnings, not errors">;
+def fixit_recompile : Flag<"-fixit-recompile">,
+  HelpText<"Apply fix-it changes and recompile">;
+def fixit_to_temp : Flag<"-fixit-to-temporary">,
+  HelpText<"Apply fix-it changes to temporary files">;
=20
 // Generic forwarding to LLVM options. This should only be used for debugg=
ing
 // and experimental features.
 def mllvm : Separate<"-mllvm">,
   HelpText<"Additional arguments to forward to LLVM's option processing">;
=20
+def foverride_record_layout_EQ : Joined<"-foverride-record-layout=3D">,
+  HelpText<"Override record layouts with those in the given file">;
+ =20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Language Options
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -440,6 +525,10 @@
   HelpText<"Allow GNU-extension keywords regardless of language standard">;
 def fgnu89_inline : Flag<"-fgnu89-inline">,
   HelpText<"Use the gnu89 inline semantics">;
+def fno_inline : Flag<"-fno-inline">,
+  HelpText<"Disable use of the inline keyword">;
+def fno_inline_functions : Flag<"-fno-inline-functions">,
+  HelpText<"Disable automatic function inlining">;
 def fno_gnu_keywords : Flag<"-fno-gnu-keywords">,
   HelpText<"Disallow GNU-extension keywords regardless of language standar=
d">;
 def fdollars_in_identifiers : Flag<"-fdollars-in-identifiers">,
@@ -461,6 +550,10 @@
   HelpText<"Enable C++ exceptions">;
 def fsjlj_exceptions : Flag<"-fsjlj-exceptions">,
   HelpText<"Use SjLj style exceptions">;
+def ffast_math : Flag<"-ffast-math">,
+  HelpText<"Enable the *frontend*'s 'fast-math' mode. This has no effect o=
n "
+           "optimizations, but provides a preprocessor macro __FAST_MATH__=
 the "
+           "same as GCC's -ffast-math flag.">;
 def ffreestanding : Flag<"-ffreestanding">,
   HelpText<"Assert that the compilation takes place in a freestanding envi=
ronment">;
 def fformat_extensions : Flag<"-fformat-extensions">,
@@ -541,6 +634,8 @@
   HelpText<"Treat signed integer overflow as two's complement">;
 def pic_level : Separate<"-pic-level">,
   HelpText<"Value for __PIC__">;
+def pie_level : Separate<"-pie-level">,
+  HelpText<"Value for __PIE__">;
 def pthread : Flag<"-pthread">,
   HelpText<"Support POSIX threads in generated code">;
 def fpack_struct : Separate<"-fpack-struct">,
@@ -555,6 +650,8 @@
   HelpText<"Dump declarations that are deserialized from PCH, for testing"=
>;
 def error_on_deserialized_pch_decl : Separate<"-error-on-deserialized-decl=
">,
   HelpText<"Emit error if a specific declaration is deserialized from PCH,=
 for testing">;
+def error_on_deserialized_pch_decl_EQ : Joined<"-error-on-deserialized-dec=
l=3D">,
+  Alias<error_on_deserialized_pch_decl>;
 def fshort_wchar : Flag<"-fshort-wchar">,
   HelpText<"Force wchar_t to be a short unsigned int">;
 def fshort_enums : Flag<"-fshort-enums">,
@@ -569,6 +666,8 @@
   HelpText<"Give inline C++ member functions default visibility by default=
">;
 def ftemplate_depth : Separate<"-ftemplate-depth">,
   HelpText<"Maximum depth of recursive template instantiation">;
+def fconstexpr_depth : Separate<"-fconstexpr-depth">,
+  HelpText<"Maximum depth of recursive constexpr function calls">;
 def Wlarge_by_value_copy : Separate<"-Wlarge-by-value-copy">,
   HelpText<"Warn if a function definition returns or accepts an object lar=
ger "
            "in bytes that a given value">;
@@ -595,10 +694,16 @@
   HelpText<"Enable parser support for the __unknown_anytype type; for test=
ing purposes only">;
 def fdebugger_support : Flag<"-fdebugger-support">,
   HelpText<"Enable special debugger support behavior">;
+def fdebugger_cast_result_to_id : Flag<"-fdebugger-cast-result-to-id">,
+  HelpText<"Enable casting unknown expression results to id">;
+def fdebugger_objc_literal : Flag<"-fdebugger-objc-literal">,
+  HelpText<"Enable special debugger support for objective-C subscripting a=
nd literals">;
 def fdeprecated_macro : Flag<"-fdeprecated-macro">,
   HelpText<"Defines the __DEPRECATED macro">;
 def fno_deprecated_macro : Flag<"-fno-deprecated-macro">,
   HelpText<"Undefines the __DEPRECATED macro">;
+def fapple_pragma_pack : Flag<"-fapple-pragma-pack">,
+  HelpText<"Enable Apple gcc-compatible #pragma pack handling">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Header Search Options
@@ -613,11 +718,13 @@
 def fmodule_cache_path : Separate<"-fmodule-cache-path">,=20
   MetaVarName<"<directory>">,
   HelpText<"Specify the module cache path">;          =20
+def fmodule_name : Joined<"-fmodule-name=3D">,=20
+  MetaVarName<"<name>">,
+  HelpText<"Specify the name of the module to build">;          =20
 def fdisable_module_hash : Flag<"-fdisable-module-hash">,
   HelpText<"Disable the module hash">;
-def fauto_module_import : Flag<"-fauto-module-import">,
-  HelpText<"Automatically translate #include/#import into module imports "
-           "when possible">;
+def fmodules : Flag<"-fmodules">,
+  HelpText<"Enable the 'modules' language feature">;
           =20
 def F : JoinedOrSeparate<"-F">, MetaVarName<"<directory>">,
   HelpText<"Add directory to framework include search path">;
@@ -639,6 +746,8 @@
 def objcxx_isystem : JoinedOrSeparate<"-objcxx-isystem">,
   MetaVarName<"<directory>">,
   HelpText<"Add directory to the ObjC++ SYSTEM include search path">;
+def iframework : JoinedOrSeparate<"-iframework">, MetaVarName<"<directory>=
">,
+  HelpText<"Add directory to SYSTEM framework search path">;
 def isystem : JoinedOrSeparate<"-isystem">, MetaVarName<"<directory>">,
   HelpText<"Add directory to SYSTEM include search path">;
 def iwithsysroot : JoinedOrSeparate<"-iwithsysroot">,MetaVarName<"<directo=
ry>">,
@@ -693,6 +802,8 @@
   HelpText<"undef all system defines">;
 def detailed_preprocessing_record : Flag<"-detailed-preprocessing-record">,
   HelpText<"include a detailed record of preprocessing actions">;
+def mqdsp6_compat : Flag<"-mqdsp6-compat">,
+  HelpText<"Enable hexagon-qdsp6 backward compatibility">;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Preprocessed Output Options
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/Compilation.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/Compilation.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/Compilation.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -56,6 +56,10 @@
   /// Result files which should be removed on failure.
   ArgStringList ResultFiles;
=20
+  /// Result files which are generated correctly on failure, and which sho=
uld
+  /// only be removed if we crash.
+  ArgStringList FailureResultFiles;
+
   /// Redirection for stdout, stderr, etc.
   const llvm::sys::Path **Redirects;
=20
@@ -84,6 +88,10 @@
=20
   const ArgStringList &getResultFiles() const { return ResultFiles; }
=20
+  const ArgStringList &getFailureResultFiles() const {
+    return FailureResultFiles;
+  }
+
   /// getArgsForToolChain - Return the derived argument list for the
   /// tool chain \arg TC (or the default tool chain, if TC is not
   /// specified).
@@ -106,6 +114,13 @@
     return Name;
   }
=20
+  /// addFailureResultFile - Add a file to remove if we crash, and returns=
 its
+  /// argument.
+  const char *addFailureResultFile(const char *Name) {
+    FailureResultFiles.push_back(Name);
+    return Name;
+  }
+
   /// CleanupFileList - Remove the files in the given list.
   ///
   /// \param IssueErrors - Report failures as errors.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/Driver.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/Driver.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/Driver.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "clang/Driver/Types.h"
 #include "clang/Driver/Util.h"
=20
+#include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Support/Path.h" // FIXME: Kill when CompilationInfo
@@ -35,7 +36,6 @@
   class Command;
   class Compilation;
   class DerivedArgList;
-  class HostInfo;
   class InputArgList;
   class InputInfo;
   class JobAction;
@@ -86,8 +86,8 @@
   /// If the standard library is used
   bool UseStdLib;
=20
-  /// Default host triple.
-  std::string DefaultHostTriple;
+  /// Default target triple.
+  std::string DefaultTargetTriple;
=20
   /// Default name for linked images (e.g., "a.out").
   std::string DefaultImageName;
@@ -95,10 +95,6 @@
   /// Driver title to use with help.
   std::string DriverTitle;
=20
-  /// Host information for the platform the driver is running as. This
-  /// will generally be the actual host platform, but not always.
-  const HostInfo *Host;
-
   /// Information about the host which can be overridden by the user.
   std::string HostBits, HostMachine, HostSystem, HostRelease;
=20
@@ -117,7 +113,7 @@
   /// Whether the driver should follow g++ like behavior.
   unsigned CCCIsCXX : 1;
=20
-  /// Whether the driver is just the preprocessor
+  /// Whether the driver is just the preprocessor.
   unsigned CCCIsCPP : 1;
=20
   /// Echo commands while executing (in -v style).
@@ -175,6 +171,13 @@
   std::list<std::string> TempFiles;
   std::list<std::string> ResultFiles;
=20
+  /// \brief Cache of all the ToolChains in use by the driver.
+  ///
+  /// This maps from the string representation of a triple to a ToolChain
+  /// created targetting that triple. The driver owns all the ToolChain ob=
jects
+  /// stored in it, and will clean them up when torn down.
+  mutable llvm::StringMap<ToolChain *> ToolChains;
+
 private:
   /// TranslateInputArgs - Create a new derived argument list from the inp=
ut
   /// arguments, after applying the standard argument translations.
@@ -187,7 +190,7 @@
=20
 public:
   Driver(StringRef _ClangExecutable,
-         StringRef _DefaultHostTriple,
+         StringRef _DefaultTargetTriple,
          StringRef _DefaultImageName,
          bool IsProduction,
          DiagnosticsEngine &_Diags);
@@ -379,10 +382,6 @@
   /// GCC goes to extra lengths here to be a bit more robust.
   std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const;
=20
-  /// GetHostInfo - Construct a new host info object for the given
-  /// host triple.
-  const HostInfo *GetHostInfo(const char *HostTriple) const;
-
   /// ShouldUseClangCompilar - Should the clang compiler be used to
   /// handle this action.
   bool ShouldUseClangCompiler(const Compilation &C, const JobAction &JA,
@@ -390,8 +389,17 @@
=20
   bool IsUsingLTO(const ArgList &Args) const;
=20
+private:
+  /// \brief Retrieves a ToolChain for a particular target triple.
+  ///
+  /// Will cache ToolChains for the life of the driver object, and create =
them
+  /// on-demand.
+  const ToolChain &getToolChain(const ArgList &Args,
+                                StringRef DarwinArchName =3D "") const;
+
   /// @}
=20
+public:
   /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and
   /// return the grouped values as integers. Numbers which are not
   /// provided are set to 0.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/DriverDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/DriverDiagnostic.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/DriverDiagnostic.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
   namespace diag {
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
 #define DRIVERSTART
 #include "clang/Basic/DiagnosticDriverKinds.inc"
 #undef DIAG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/Job.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/Job.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/Job.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -46,6 +46,8 @@
   /// Command - An executable path/name and argument vector to
   /// execute.
 class Command : public Job {
+  virtual void anchor();
+
   /// Source - The action which caused the creation of this job.
   const Action &Source;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/ObjCRuntime.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/ObjCRuntime.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/ObjCRuntime.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -30,6 +30,9 @@
   /// True if the runtime supports ARC zeroing __weak.
   unsigned HasWeak : 1;
=20
+  /// \brief True if the runtime supports subscripting methods.
+  unsigned HasSubscripting : 1;
+
   /// True if the runtime provides the following entrypoint:
   ///   void objc_terminate(void);
   /// If available, this will be called instead of abort() when an
@@ -37,7 +40,7 @@
   unsigned HasTerminate : 1;
=20
   ObjCRuntime() : RuntimeKind(NeXT), HasARC(false), HasWeak(false),
-    HasTerminate(false) {}
+    HasSubscripting(false), HasTerminate(false) {}
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/OptTable.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/OptTable.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/OptTable.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -49,8 +49,8 @@
       const char *HelpText;
       const char *MetaVar;
       unsigned char Kind;
+      unsigned char Param;
       unsigned short Flags;
-      unsigned char Param;
       unsigned short GroupID;
       unsigned short AliasID;
     };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/Options.td
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/Options.td	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/Options.td	Tue Apr=
 17 11:51:51 2012 +0300
@@ -21,6 +21,7 @@
 def CompileOnly_Group     : OptionGroup<"<CompileOnly group>">;
=20
 def I_Group               : OptionGroup<"<I group>">, Group<CompileOnly_Gr=
oup>;
+def L_Group               : OptionGroup<"<L group>">, Group<CompileOnly_Gr=
oup>;
 def M_Group               : OptionGroup<"<M group>">, Group<CompileOnly_Gr=
oup>;
 def T_Group               : OptionGroup<"<T group>">;
 def O_Group               : OptionGroup<"<O group>">, Group<CompileOnly_Gr=
oup>;
@@ -101,8 +102,6 @@
   HelpText<"Use pretokenized headers for precompiled headers">;
=20
 class CCCDebugOpt : Group<ccc_debug_Group>, Flags<[DriverOption, HelpHidde=
n]>;
-def ccc_host_triple : Separate<"-ccc-host-triple">, CCCDebugOpt,
-  HelpText<"Simulate running on the given target">;
 def ccc_install_dir : Separate<"-ccc-install-dir">, CCCDebugOpt,
   HelpText<"Simulate installation in the given directory">;
 def ccc_print_options : Flag<"-ccc-print-options">, CCCDebugOpt,
@@ -120,13 +119,21 @@
 def ccc_arrmt_modify : Flag<"-ccc-arrmt-modify">, Alias<ccc_arcmt_modify>;
 def ccc_arcmt_migrate : Separate<"-ccc-arcmt-migrate">, CCCDriverOpt,
   HelpText<"Apply modifications and produces temporary files that conform =
to ARC">;
-def ccc_arcmt_migrate_EQ : Joined<"-ccc-arcmt-migrate=3D">, CCCDriverOpt,
-  Alias<ccc_arcmt_migrate>;
 def arcmt_migrate_report_output : Separate<"-arcmt-migrate-report-output">,
   HelpText<"Output path for the plist report">;
 def arcmt_migrate_emit_arc_errors : Flag<"-arcmt-migrate-emit-errors">,
   HelpText<"Emit ARC errors even if the migrator can fix them">;
=20
+def _migrate : Flag<"--migrate">, Flags<[DriverOption]>,
+  HelpText<"Run the migrator">;
+def ccc_objcmt_migrate : Separate<"-ccc-objcmt-migrate">, CCCDriverOpt,
+  HelpText<"Apply modifications and produces temporary files to migrate to=
 "
+   "modern ObjC syntax">;
+def objcmt_migrate_literals : Flag<"-objcmt-migrate-literals">,
+  HelpText<"Enable migration to modern ObjC literals">;
+def objcmt_migrate_subscripting : Flag<"-objcmt-migrate-subscripting">,
+  HelpText<"Enable migration to modern ObjC subscripting">;
+
 // Make sure all other -ccc- options are rejected.
 def ccc_ : Joined<"-ccc-">, Group<ccc_Group>, Flags<[Unsupported]>;
=20
@@ -145,6 +152,7 @@
 def E : Flag<"-E">, Flags<[DriverOption]>,
   HelpText<"Only run the preprocessor">;
 def F : JoinedOrSeparate<"-F">, Flags<[RenderJoined]>;
+def G : Separate<"-G">, Flags<[DriverOption]>;
 def H : Flag<"-H">;
 def I_ : Flag<"-I-">, Group<I_Group>;
 def I : JoinedOrSeparate<"-I">, Group<I_Group>;
@@ -229,7 +237,7 @@
 def combine : Flag<"-combine">, Flags<[DriverOption, Unsupported]>;
 def compatibility__version : JoinedOrSeparate<"-compatibility_version">;
 def coverage : Flag<"-coverage">;
-def cpp_precomp : Flag<"-cpp-precomp">;
+def cpp_precomp : Flag<"-cpp-precomp">, Group<clang_ignored_f_Group>;
 def current__version : JoinedOrSeparate<"-current_version">;
 def cxx_isystem : JoinedOrSeparate<"-cxx-isystem">, Group<clang_i_Group>;
 def c : Flag<"-c">, Flags<[DriverOption]>,
@@ -256,11 +264,18 @@
 def exported__symbols__list : Separate<"-exported_symbols_list">;
 def e : JoinedOrSeparate<"-e">;
 def fPIC : Flag<"-fPIC">, Group<f_Group>;
-def fPIE : Flag<"-fPIE">, Group<f_Group>, Flags<[NoArgumentUnused]>;
-def fno_PIE : Flag<"-fno-PIE">, Group<f_Group>, Flags<[NoArgumentUnused]>;
+def fno_PIC : Flag<"-fno-PIC">, Group<f_Group>;
+def fPIE : Flag<"-fPIE">, Group<f_Group>;
+def fno_PIE : Flag<"-fno-PIE">, Group<f_Group>;
 def faccess_control : Flag<"-faccess-control">, Group<f_Group>;
 def fallow_unsupported : Flag<"-fallow-unsupported">, Group<f_Group>;
+def faltivec : Flag<"-faltivec">, Group<f_Group>;
 def fapple_kext : Flag<"-fapple-kext">, Group<f_Group>;
+def fapple_pragma_pack : Flag<"-fapple-pragma-pack">, Group<f_Group>;
+def faddress_sanitizer : Flag<"-faddress-sanitizer">, Group<f_Group>;
+def fno_address_sanitizer : Flag<"-fno-address-sanitizer">, Group<f_Group>;
+def fthread_sanitizer : Flag<"-fthread-sanitizer">, Group<f_Group>;
+def fno_thread_sanitizer : Flag<"-fno-thread-sanitizer">, Group<f_Group>;
 def fasm : Flag<"-fasm">, Group<f_Group>;
=20
 def fasm_blocks : Flag<"-fasm-blocks">, Group<f_Group>;
@@ -286,21 +301,27 @@
 def fcompile_resource_EQ : Joined<"-fcompile-resource=3D">, Group<f_Group>;
 def fconstant_cfstrings : Flag<"-fconstant-cfstrings">, Group<f_Group>;
 def fconstant_string_class_EQ : Joined<"-fconstant-string-class=3D">, Grou=
p<f_Group>;
+def fconstexpr_depth_EQ : Joined<"-fconstexpr-depth=3D">, Group<f_Group>;
+def fconstexpr_backtrace_limit_EQ : Joined<"-fconstexpr-backtrace-limit=3D=
">,
+                                    Group<f_Group>;
+def fno_crash_diagnostics : Flag<"-fno-crash-diagnostics">, Group<f_clang_=
Group>, Flags<[NoArgumentUnused]>;
 def fcreate_profile : Flag<"-fcreate-profile">, Group<f_Group>;
 def fcxx_exceptions: Flag<"-fcxx-exceptions">, Group<f_Group>;
+def fcxx_modules : Flag <"-fcxx-modules">, Group<f_Group>, Flags<[NoForwar=
d]>;
 def fdebug_pass_arguments : Flag<"-fdebug-pass-arguments">, Group<f_Group>;
 def fdebug_pass_structure : Flag<"-fdebug-pass-structure">, Group<f_Group>;
 def fdiagnostics_fixit_info : Flag<"-fdiagnostics-fixit-info">, Group<f_cl=
ang_Group>;
 def fdiagnostics_print_source_range_info : Flag<"-fdiagnostics-print-sourc=
e-range-info">, Group<f_clang_Group>;
 def fdiagnostics_parseable_fixits : Flag<"-fdiagnostics-parseable-fixits">=
, Group<f_clang_Group>;
 def fdiagnostics_show_option : Flag<"-fdiagnostics-show-option">, Group<f_=
Group>;
-def fdiagnostics_show_name : Flag<"-fdiagnostics-show-name">, Group<f_Grou=
p>;
 def fdiagnostics_show_note_include_stack : Flag<"-fdiagnostics-show-note-i=
nclude-stack">, Group<f_Group>;
 def fdiagnostics_format_EQ : Joined<"-fdiagnostics-format=3D">, Group<f_cl=
ang_Group>;
 def fdiagnostics_show_category_EQ : Joined<"-fdiagnostics-show-category=3D=
">, Group<f_clang_Group>;
 def fdollars_in_identifiers : Flag<"-fdollars-in-identifiers">, Group<f_Gr=
oup>;
 def fdwarf2_cfi_asm : Flag<"-fdwarf2-cfi-asm">, Group<f_Group>;
 def fno_dwarf2_cfi_asm : Flag<"-fno-dwarf2-cfi-asm">, Group<f_Group>;
+def fdwarf_directory_asm : Flag<"-fdwarf-directory-asm">, Group<f_Group>;
+def fno_dwarf_directory_asm : Flag<"-fno-dwarf-directory-asm">, Group<f_Gr=
oup>;
 def felide_constructors : Flag<"-felide-constructors">, Group<f_Group>;
 def feliminate_unused_debug_symbols : Flag<"-feliminate-unused-debug-symbo=
ls">, Group<f_Group>;
 def femit_all_decls : Flag<"-femit-all-decls">, Group<f_Group>;
@@ -309,8 +330,34 @@
 def fexceptions : Flag<"-fexceptions">, Group<f_Group>;
 def fextdirs_EQ : Joined<"-fextdirs=3D">, Group<f_Group>;
 def fhosted : Flag<"-fhosted">, Group<f_Group>;
-def ffast_math : Flag<"-ffast-math">, Group<clang_ignored_f_Group>;
-def ffinite_math_only : Flag<"-ffinite-math-only">, Group<clang_ignored_f_=
Group>;
+def ffast_math : Flag<"-ffast-math">, Group<f_Group>;
+def fmath_errno : Flag<"-fmath-errno">, Group<f_Group>;
+def fno_math_errno : Flag<"-fno-math-errno">, Group<f_Group>;
+def fsignaling_math : Flag<"-fsignaling-math">, Group<f_Group>;
+def fno_signaling_math : Flag<"-fno-signaling-math">, Group<f_Group>;
+def funsafe_math_optimizations : Flag<"-funsafe-math-optimizations">,
+  Group<f_Group>;
+def fno_unsafe_math_optimizations : Flag<"-fno-unsafe-math-optimizations">,
+  Group<f_Group>;
+def fassociative_math : Flag<"-fassociative-math">, Group<f_Group>;
+def fno_associative_math : Flag<"-fno-associative-math">, Group<f_Group>;
+def freciprocal_math : Flag<"-freciprocal-math">, Group<f_Group>;
+def fno_reciprocal_math : Flag<"-fno-reciprocal-math">, Group<f_Group>;
+def ffinite_math_only : Flag<"-ffinite-math-only">, Group<f_Group>;
+def fno_finite_math_only : Flag<"-fno-finite-math-only">, Group<f_Group>;
+def fsigned_zeros : Flag<"-fsigned-zeros">, Group<f_Group>;
+def fno_signed_zeros : Flag<"-fno-signed-zeros">, Group<f_Group>;
+def fhonor_nans : Flag<"-fhonor-nans">, Group<f_Group>;
+def fno_honor_nans : Flag<"-fno-honor-nans">, Group<f_Group>;
+def fhonor_infinities : Flag<"-fhonor-infinities">, Group<f_Group>;
+def fno_honor_infinities : Flag<"-fno-honor-infinities">, Group<f_Group>;
+// Sic. This option was misspelled originally.
+def fhonor_infinites : Flag<"-fhonor-infinites">, Group<f_Group>,
+    Alias<fhonor_infinities>;
+def fno_honor_infinites : Flag<"-fno-honor-infinites">, Group<f_Group>,
+    Alias<fno_honor_infinities>;
+def ftrapping_math : Flag<"-ftrapping-math">, Group<f_Group>;
+def fno_trapping_math : Flag<"-fno-trapping-math">, Group<f_Group>;
=20
 def ffor_scope : Flag<"-ffor-scope">, Group<f_Group>;
 def fno_for_scope : Flag<"-fno-for-scope">, Group<f_Group>;
@@ -337,7 +384,6 @@
 def fno_lto : Flag<"-fno-lto">, Group<f_Group>;
 def fmacro_backtrace_limit_EQ : Joined<"-fmacro-backtrace-limit=3D">,
                                 Group<f_Group>;
-def fmath_errno : Flag<"-fmath-errno">, Group<f_Group>;
 def fmerge_all_constants : Flag<"-fmerge-all-constants">, Group<f_Group>;
 def fmessage_length_EQ : Joined<"-fmessage-length=3D">, Group<f_Group>;
 def fms_extensions : Flag<"-fms-extensions">, Group<f_Group>;
@@ -346,14 +392,14 @@
 def fdelayed_template_parsing : Flag<"-fdelayed-template-parsing">, Group<=
f_Group>;
 def fmodule_cache_path : Separate<"-fmodule-cache-path">, Group<i_Group>,=20
   Flags<[NoForward]>;
-def fauto_module_import : Flag <"-fauto-module-import">, Group<f_Group>,
-  Flags<[NoForward]>;
+def fmodules : Flag <"-fmodules">, Group<f_Group>, Flags<[NoForward]>;
  =20
 def fmudflapth : Flag<"-fmudflapth">, Group<f_Group>;
 def fmudflap : Flag<"-fmudflap">, Group<f_Group>;
 def fnested_functions : Flag<"-fnested-functions">, Group<f_Group>;
 def fnext_runtime : Flag<"-fnext-runtime">, Group<f_Group>;
 def fno_access_control : Flag<"-fno-access-control">, Group<f_Group>;
+def fno_apple_pragma_pack : Flag<"-fno-apple-pragma-pack">, Group<f_Group>;
 def fno_asm : Flag<"-fno-asm">, Group<f_Group>;
 def fno_asynchronous_unwind_tables : Flag<"-fno-asynchronous-unwind-tables=
">, Group<f_Group>;
 def fno_assume_sane_operator_new : Flag<"-fno-assume-sane-operator-new">, =
Group<f_Group>;
@@ -367,30 +413,30 @@
 def fno_common : Flag<"-fno-common">, Group<f_Group>;
 def fno_constant_cfstrings : Flag<"-fno-constant-cfstrings">, Group<f_Grou=
p>;
 def fno_cxx_exceptions: Flag<"-fno-cxx-exceptions">, Group<f_Group>;
+def fno_cxx_modules : Flag <"-fno-cxx-modules">, Group<f_Group>, Flags<[No=
Forward]>;
 def fno_diagnostics_fixit_info : Flag<"-fno-diagnostics-fixit-info">, Grou=
p<f_Group>;
-def fno_diagnostics_show_name : Flag<"-fno-diagnostics-show-name">, Group<=
f_Group>;
 def fno_diagnostics_show_option : Flag<"-fno-diagnostics-show-option">, Gr=
oup<f_Group>;
 def fno_diagnostics_show_note_include_stack : Flag<"-fno-diagnostics-show-=
note-include-stack">, Group<f_Group>;
 def fno_dollars_in_identifiers : Flag<"-fno-dollars-in-identifiers">, Grou=
p<f_Group>;
 def fno_elide_constructors : Flag<"-fno-elide-constructors">, Group<f_Grou=
p>;
 def fno_eliminate_unused_debug_symbols : Flag<"-fno-eliminate-unused-debug=
-symbols">, Group<f_Group>;
 def fno_exceptions : Flag<"-fno-exceptions">, Group<f_Group>;
-def fno_finite_math_only : Flag<"-fno-finite-math-only">, Group<clang_igno=
red_f_Group>;
 def fno_gnu_keywords : Flag<"-fno-gnu-keywords">, Group<f_Group>;
-def fno_inline_functions : Flag<"-fno-inline-functions">, Group<clang_igno=
red_f_Group>;
-def fno_inline : Flag<"-fno-inline">, Group<clang_ignored_f_Group>;
+def fno_inline_functions : Flag<"-fno-inline-functions">, Group<f_Group>;
+def fno_inline : Flag<"-fno-inline">, Group<f_Group>;
 def fno_keep_inline_functions : Flag<"-fno-keep-inline-functions">, Group<=
clang_ignored_f_Group>;
 def fno_lax_vector_conversions : Flag<"-fno-lax-vector-conversions">, Grou=
p<f_Group>;
-def fno_math_errno : Flag<"-fno-math-errno">, Group<f_Group>;
+def fno_limit_debug_info : Flag<"-fno-limit-debug-info">, Group<f_Group>,
+  HelpText<"Do not limit debug information produced to reduce size of debu=
g binary">;
 def fno_merge_all_constants : Flag<"-fno-merge-all-constants">, Group<f_Gr=
oup>;
+def fno_modules : Flag <"-fno-modules">, Group<f_Group>, Flags<[NoForward]=
>;
 def fno_ms_extensions : Flag<"-fno-ms-extensions">, Group<f_Group>;
 def fno_ms_compatibility : Flag<"-fno-ms-compatibility">, Group<f_Group>;
 def fno_delayed_template_parsing : Flag<"-fno-delayed-template-parsing">, =
Group<f_Group>;
-def fno_objc_default_synthesize_properties=20
-  : Flag<"-fno-objc-default-synthesize-properties">, Group<f_Group>;
 def fno_objc_exceptions: Flag<"-fno-objc-exceptions">, Group<f_Group>;
 def fno_objc_legacy_dispatch : Flag<"-fno-objc-legacy-dispatch">, Group<f_=
Group>;
 def fno_omit_frame_pointer : Flag<"-fno-omit-frame-pointer">, Group<f_Grou=
p>;
+def fno_operator_names : Flag<"-fno-operator-names">, Group<f_Group>;
 def fno_pascal_strings : Flag<"-fno-pascal-strings">, Group<f_Group>;
 def fno_rtti : Flag<"-fno-rtti">, Group<f_Group>;
 def fno_short_enums : Flag<"-fno-short-enums">, Group<f_Group>;
@@ -399,6 +445,7 @@
 def fno_spell_checking : Flag<"-fno-spell-checking">, Group<f_Group>;
 def fno_stack_protector : Flag<"-fno-stack-protector">, Group<f_Group>;
 def fno_strict_aliasing : Flag<"-fno-strict-aliasing">, Group<f_Group>;
+def fno_strict_enums : Flag<"-fno-strict-enums">, Group<f_Group>;
 def fno_strict_overflow : Flag<"-fno-strict-overflow">, Group<f_Group>;
 def fno_threadsafe_statics : Flag<"-fno-threadsafe-statics">, Group<f_Grou=
p>;
 def fno_use_cxa_atexit : Flag<"-fno-use-cxa-atexit">, Group<f_Group>;
@@ -414,8 +461,6 @@
 def fno_objc_arc_exceptions : Flag<"-fno-objc-arc-exceptions">, Group<f_Gr=
oup>;
 def fobjc_atdefs : Flag<"-fobjc-atdefs">, Group<clang_ignored_f_Group>;
 def fobjc_call_cxx_cdtors : Flag<"-fobjc-call-cxx-cdtors">, Group<clang_ig=
nored_f_Group>;
-def fobjc_default_synthesize_properties :=20
-  Flag<"-fobjc-default-synthesize-properties">, Group<f_Group>;
 def fobjc_exceptions: Flag<"-fobjc-exceptions">, Group<f_Group>;
=20
 def fobjc_gc_only : Flag<"-fobjc-gc-only">, Group<f_Group>;
@@ -426,6 +471,7 @@
                                       Group<f_Group>;
 def fno_objc_infer_related_result_type : Flag<
   "-fno-objc-infer-related-result-type">, Group<f_Group>;
+def fobjc_link_runtime: Flag<"-fobjc-link-runtime">, Group<f_Group>;
=20
 // Objective-C ABI options.
 def fobjc_abi_version_EQ : Joined<"-fobjc-abi-version=3D">, Group<f_Group>;
@@ -437,6 +483,8 @@
 def fobjc : Flag<"-fobjc">, Group<f_Group>;
 def fomit_frame_pointer : Flag<"-fomit-frame-pointer">, Group<f_Group>;
 def fopenmp : Flag<"-fopenmp">, Group<f_Group>;
+def fno_optimize_sibling_calls : Flag<"-fno-optimize-sibling-calls">, Grou=
p<f_Group>;
+def foptimize_sibling_calls : Flag<"-foptimize-sibling-calls">, Group<f_Gr=
oup>;
 def force__cpusubtype__ALL : Flag<"-force_cpusubtype_ALL">;
 def force__flat__namespace : Flag<"-force_flat_namespace">;
 def force__load : Separate<"-force_load">;
@@ -447,8 +495,9 @@
 def fpascal_strings : Flag<"-fpascal-strings">, Group<f_Group>;
 def fpch_preprocess : Flag<"-fpch-preprocess">, Group<f_Group>;
 def fpic : Flag<"-fpic">, Group<f_Group>;
-def fpie : Flag<"-fpie">, Group<f_Group>, Flags<[NoArgumentUnused]>;
-def fno_pie : Flag<"-fno-pie">, Group<f_Group>, Flags<[NoArgumentUnused]>;
+def fno_pic : Flag<"-fno-pic">, Group<f_Group>;
+def fpie : Flag<"-fpie">, Group<f_Group>;
+def fno_pie : Flag<"-fno-pie">, Group<f_Group>;
 def fprofile_arcs : Flag<"-fprofile-arcs">, Group<f_Group>;
 def fprofile_generate : Flag<"-fprofile-generate">, Group<f_Group>;
 def framework : Separate<"-framework">, Flags<[LinkerInput]>;
@@ -467,9 +516,11 @@
 def fstack_protector_all : Flag<"-fstack-protector-all">, Group<f_Group>;
 def fstack_protector : Flag<"-fstack-protector">, Group<f_Group>;
 def fstrict_aliasing : Flag<"-fstrict-aliasing">, Group<f_Group>;
+def fstrict_enums : Flag<"-fstrict-enums">, Group<f_Group>;
 def fstrict_overflow : Flag<"-fstrict-overflow">, Group<f_Group>;
 def fsyntax_only : Flag<"-fsyntax-only">, Flags<[DriverOption]>;
 def ftabstop_EQ : Joined<"-ftabstop=3D">, Group<f_Group>;
+def ftemplate_depth_EQ : Joined<"-ftemplate-depth=3D">, Group<f_Group>;
 def ftemplate_depth_ : Joined<"-ftemplate-depth-">, Group<f_Group>;
 def ftemplate_backtrace_limit_EQ : Joined<"-ftemplate-backtrace-limit=3D">,
                                    Group<f_Group>;
@@ -506,17 +557,22 @@
 def ffunction_sections: Flag <"-ffunction-sections">, Group<f_Group>;
 def fdata_sections : Flag <"-fdata-sections">, Group<f_Group>;
 def f : Joined<"-f">, Group<f_Group>;
-def g0 : Joined<"-g0">, Group<g_Group>;
-def g3 : Joined<"-g3">, Group<g_Group>;
-def gfull : Joined<"-gfull">, Group<g_Group>;
-def gstabs : Joined<"-gstabs">, Group<g_Group>;
-def gused : Joined<"-gused">, Group<g_Group>;
+def g0 : Flag<"-g0">, Group<g_Group>;
+def g2 : Flag<"-g2">, Group<g_Group>;
+def g3 : Flag<"-g3">, Group<g_Group>;
+def gdwarf2 : Flag<"-gdwarf-2">, Group<g_Group>;
+def gfull : Flag<"-gfull">, Group<g_Group>;
+def ggdb : Flag<"-ggdb">, Group<g_Group>;
+def gstabs : Flag<"-gstabs">, Group<g_Group>;
+def gstabsplus : Flag<"-gstabs+">, Group<g_Group>;
+def gstabs1 : Flag<"-gstabs1">, Group<g_Group>;
+def gstabs2 : Flag<"-gstabs2">, Group<g_Group>;
+def gused : Flag<"-gused">, Group<g_Group>;
 def g_Flag : Flag<"-g">, Group<g_Group>;
-def g_Joined : Joined<"-g">, Group<g_Group>;
 def headerpad__max__install__names : Joined<"-headerpad_max_install_names"=
>;
 def index_header_map : Flag<"-index-header-map">;
 def idirafter : JoinedOrSeparate<"-idirafter">, Group<clang_i_Group>;
-def iframework : JoinedOrSeparate<"-iframework">, Group<clang_i_Group>;
+def iframework : Joined<"-iframework">, Group<clang_i_Group>;
 def imacros : JoinedOrSeparate<"-imacros">, Group<clang_i_Group>;
 def image__base : Separate<"-image_base">;
 def include_ : JoinedOrSeparate<"-include">, Group<clang_i_Group>, EnumNam=
e<"include">;
@@ -534,7 +590,10 @@
 def i : Joined<"-i">, Group<i_Group>;
 def keep__private__externs : Flag<"-keep_private_externs">;
 def l : JoinedOrSeparate<"-l">, Flags<[LinkerInput, RenderJoined]>;
+def lazy__framework : Separate<"-lazy_framework">, Flags<[LinkerInput]>;
+def lazy__library : Separate<"-lazy_library">, Flags<[LinkerInput]>;
 def m32 : Flag<"-m32">, Group<m_Group>, Flags<[DriverOption]>;
+def mqdsp6_compat : Flag<"-mqdsp6-compat">, Group<m_Group>, Flags<[DriverO=
ption]>;
 def m3dnowa : Flag<"-m3dnowa">, Group<m_x86_Features_Group>;
 def m3dnow : Flag<"-m3dnow">, Group<m_x86_Features_Group>;
 def m64 : Flag<"-m64">, Group<m_Group>, Flags<[DriverOption]>;
@@ -543,9 +602,10 @@
 def mcmodel_EQ : Joined<"-mcmodel=3D">, Group<m_Group>;
 def mconstant_cfstrings : Flag<"-mconstant-cfstrings">, Group<clang_ignore=
d_m_Group>;
 def mcpu_EQ : Joined<"-mcpu=3D">, Group<m_Group>;
-def mdynamic_no_pic : Joined<"-mdynamic-no-pic">, Group<m_Group>, Flags<[N=
oArgumentUnused]>;
+def mdynamic_no_pic : Joined<"-mdynamic-no-pic">, Group<m_Group>;
 def mfix_and_continue : Flag<"-mfix-and-continue">, Group<clang_ignored_m_=
Group>;
 def mfloat_abi_EQ : Joined<"-mfloat-abi=3D">, Group<m_Group>;
+def mfpmath_EQ : Joined<"-mfpmath=3D">, Group<m_Group>;
 def mfpu_EQ : Joined<"-mfpu=3D">, Group<m_Group>;
 def mglobal_merge : Flag<"-mglobal-merge">, Group<m_Group>;
 def mhard_float : Flag<"-mhard-float">, Group<m_Group>;
@@ -558,6 +618,7 @@
 def mmacosx_version_min_EQ : Joined<"-mmacosx-version-min=3D">, Group<m_Gr=
oup>;
 def mms_bitfields : Flag<"-mms-bitfields">, Group<m_Group>;
 def mstackrealign : Flag<"-mstackrealign">, Group<m_Group>;
+def mstack_alignment : Joined<"-mstack-alignment=3D">, Group<m_Group>;
 def mmmx : Flag<"-mmmx">, Group<m_x86_Features_Group>;
 def mno_3dnowa : Flag<"-mno-3dnowa">, Group<m_x86_Features_Group>;
 def mno_3dnow : Flag<"-mno-3dnow">, Group<m_x86_Features_Group>;
@@ -569,6 +630,7 @@
 def mno_relax_all : Flag<"-mno-relax-all">, Group<m_Group>;
 def mno_rtd: Flag<"-mno-rtd">, Group<m_Group>;
 def mno_soft_float : Flag<"-mno-soft-float">, Group<m_Group>;
+def mno_stackrealign : Flag<"-mno-stackrealign">, Group<m_Group>;
 def mno_sse2 : Flag<"-mno-sse2">, Group<m_x86_Features_Group>;
 def mno_sse3 : Flag<"-mno-sse3">, Group<m_x86_Features_Group>;
 def mno_sse4a : Flag<"-mno-sse4a">, Group<m_x86_Features_Group>;
@@ -579,6 +641,12 @@
 def mno_ssse3 : Flag<"-mno-ssse3">, Group<m_x86_Features_Group>;
 def mno_aes : Flag<"-mno-aes">, Group<m_x86_Features_Group>;
 def mno_avx : Flag<"-mno-avx">, Group<m_x86_Features_Group>;
+def mno_avx2 : Flag<"-mno-avx2">, Group<m_x86_Features_Group>;
+def mno_lzcnt : Flag<"-mno-lzcnt">, Group<m_x86_Features_Group>;
+def mno_bmi : Flag<"-mno-bmi">, Group<m_x86_Features_Group>;
+def mno_bmi2 : Flag<"-mno-bmi2">, Group<m_x86_Features_Group>;
+def mno_popcnt : Flag<"-mno-popcnt">, Group<m_x86_Features_Group>;
+def mno_fma4 : Flag<"-mno-fma4">, Group<m_x86_Features_Group>;
=20
 def mno_thumb : Flag<"-mno-thumb">, Group<m_Group>;
 def marm : Flag<"-marm">, Alias<mno_thumb>;
@@ -591,6 +659,7 @@
 def mregparm_EQ : Joined<"-mregparm=3D">, Group<m_Group>;
 def mrelax_all : Flag<"-mrelax-all">, Group<m_Group>;
 def mrtd: Flag<"-mrtd">, Group<m_Group>;
+def msmall_data_threshold_EQ : Joined <"-msmall-data-threshold=3D">, Group=
<m_Group>;
 def msoft_float : Flag<"-msoft-float">, Group<m_Group>;
 def msse2 : Flag<"-msse2">, Group<m_x86_Features_Group>;
 def msse3 : Flag<"-msse3">, Group<m_x86_Features_Group>;
@@ -602,6 +671,12 @@
 def mssse3 : Flag<"-mssse3">, Group<m_x86_Features_Group>;
 def maes : Flag<"-maes">, Group<m_x86_Features_Group>;
 def mavx : Flag<"-mavx">, Group<m_x86_Features_Group>;
+def mavx2 : Flag<"-mavx2">, Group<m_x86_Features_Group>;
+def mlzcnt : Flag<"-mlzcnt">, Group<m_x86_Features_Group>;
+def mbmi : Flag<"-mbmi">, Group<m_x86_Features_Group>;
+def mbmi2 : Flag<"-mbmi2">, Group<m_x86_Features_Group>;
+def mpopcnt : Flag<"-mpopcnt">, Group<m_x86_Features_Group>;
+def mfma4 : Flag<"-mfma4">, Group<m_x86_Features_Group>;
 def mthumb : Flag<"-mthumb">, Group<m_Group>;
 def mtune_EQ : Joined<"-mtune=3D">, Group<m_Group>;
 def multi__module : Flag<"-multi_module">;
@@ -612,7 +687,7 @@
 def m_Joined : Joined<"-m">, Group<m_Group>;
 def no_canonical_prefixes : Flag<"-no-canonical-prefixes">, Flags<[HelpHid=
den]>,
   HelpText<"Use relative instead of canonical paths">;
-def no_cpp_precomp : Flag<"-no-cpp-precomp">;
+def no_cpp_precomp : Flag<"-no-cpp-precomp">, Group<clang_ignored_f_Group>;
 def no_integrated_as : Flag<"-no-integrated-as">, Flags<[DriverOption]>;
 def no_integrated_cpp : Flag<"-no-integrated-cpp">, Flags<[DriverOption]>;
 def no__dead__strip__inits__and__terms : Flag<"-no_dead_strip_inits_and_te=
rms">;
@@ -662,8 +737,11 @@
 def remap : Flag<"-remap">;
 def rewrite_objc : Flag<"-rewrite-objc">, Flags<[DriverOption]>,
   HelpText<"Rewrite Objective-C source to C++">;
+def rewrite_legacy_objc : Flag<"-rewrite-legacy-objc">, Flags<[DriverOptio=
n]>,
+  HelpText<"Rewrite Legacy Objective-C source to C++">;
 def rdynamic : Flag<"-rdynamic">;
 def rpath : Separate<"-rpath">, Flags<[LinkerInput]>;
+def rtlib_EQ : Joined<"-rtlib=3D">;
 def r : Flag<"-r">;
 def save_temps : Flag<"-save-temps">, Flags<[DriverOption]>,
   HelpText<"Save intermediate compilation results">;
@@ -687,13 +765,20 @@
 def specs_EQ : Joined<"-specs=3D">;
 def specs : Separate<"-specs">, Flags<[Unsupported]>;
 def static_libgcc : Flag<"-static-libgcc">;
+def static_libstdcxx : Flag<"-static-libstdc++">;
 def static : Flag<"-static">, Flags<[NoArgumentUnused]>;
 def std_default_EQ : Joined<"-std-default=3D">;
-def std_EQ : Joined<"-std=3D">;
+def std_EQ : Joined<"-std=3D">, Group<L_Group>;
 def stdlib_EQ : Joined<"-stdlib=3D">;
 def sub__library : JoinedOrSeparate<"-sub_library">;
 def sub__umbrella : JoinedOrSeparate<"-sub_umbrella">;
 def s : Flag<"-s">;
+def target : Separate<"-target">, Flags<[DriverOption]>,
+  HelpText<"Generate code for the given target">;
+def gcc_toolchain : Separate<"-gcc-toolchain">, Flags<[DriverOption]>,
+  HelpText<"Use the gcc toolchain at the given directory">;
+// We should deprecate the use of -ccc-host-triple, and then remove.
+def ccc_host_triple : Separate<"-ccc-host-triple">, Alias<target>;
 def time : Flag<"-time">,
   HelpText<"Time individual commands">;
 def traditional_cpp : Flag<"-traditional-cpp">;
@@ -835,7 +920,11 @@
   HelpText<"Build a relocatable precompiled header">;
 def _resource_EQ : Joined<"--resource=3D">, Alias<fcompile_resource_EQ>;
 def _resource : Separate<"--resource">, Alias<fcompile_resource_EQ>;
+def _rtlib_EQ : Joined<"--rtlib=3D">, Alias<rtlib_EQ>;
+def _rtlib : Separate<"--rtlib">, Alias<rtlib_EQ>;
 def _save_temps : Flag<"--save-temps">, Alias<save_temps>;
+def _serialize_diags : Separate<"--serialize-diagnostics">, Flags<[DriverO=
ption]>,
+  HelpText<"Serialize compiler diagnostics to a file">;
 def _shared : Flag<"--shared">, Alias<shared>;
 def _signed_char : Flag<"--signed-char">, Alias<fsigned_char>;
 def _specs_EQ : Joined<"--specs=3D">, Alias<specs_EQ>;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/Tool.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/Tool.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/Tool.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -49,6 +49,7 @@
=20
   virtual bool hasIntegratedAssembler() const { return false; }
   virtual bool hasIntegratedCPP() const =3D 0;
+  virtual bool isLinkJob() const { return false; }
=20
   /// \brief Does this tool have "good" standardized diagnostics, or shoul=
d the
   /// driver add an additional "command failed" diagnostic on failures.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/ToolChain.h
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/ToolChain.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/ToolChain.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -23,7 +23,6 @@
   class Compilation;
   class DerivedArgList;
   class Driver;
-  class HostInfo;
   class InputArgList;
   class JobAction;
   class ObjCRuntime;
@@ -39,8 +38,13 @@
     CST_Libstdcxx
   };
=20
+  enum RuntimeLibType {
+    RLT_CompilerRT,
+    RLT_Libgcc
+  };
+
 private:
-  const HostInfo &Host;
+  const Driver &D;
   const llvm::Triple Triple;
=20
   /// The list of toolchain specific path prefixes to search for
@@ -52,7 +56,20 @@
   path_list ProgramPaths;
=20
 protected:
-  ToolChain(const HostInfo &Host, const llvm::Triple &_Triple);
+  ToolChain(const Driver &D, const llvm::Triple &T);
+
+  /// \name Utilities for implementing subclasses.
+  ///@{
+  static void addSystemInclude(const ArgList &DriverArgs,
+                               ArgStringList &CC1Args,
+                               const Twine &Path);
+  static void addExternCSystemInclude(const ArgList &DriverArgs,
+                                      ArgStringList &CC1Args,
+                                      const Twine &Path);
+  static void addSystemIncludes(const ArgList &DriverArgs,
+                                ArgStringList &CC1Args,
+                                ArrayRef<StringRef> Paths);
+  ///@}
=20
 public:
   virtual ~ToolChain();
@@ -131,7 +148,7 @@
   /// IsObjCLegacyDispatchDefault - Does this tool chain set
   /// -fobjc-legacy-dispatch by default (this is only used with the non-fr=
agile
   /// ABI).
-  virtual bool IsObjCLegacyDispatchDefault() const { return false; }
+  virtual bool IsObjCLegacyDispatchDefault() const { return true; }
=20
   /// UseObjCMixedDispatchDefault - When using non-legacy dispatch, should=
 the
   /// mixed dispatch method be used?
@@ -143,6 +160,11 @@
     return 0;
   }
=20
+  /// GetDefaultRuntimeLibType - Get the default runtime library variant t=
o use.
+  virtual RuntimeLibType GetDefaultRuntimeLibType() const {
+    return ToolChain::RLT_Libgcc;
+  }
+
   /// IsUnwindTablesDefault - Does this tool chain use -funwind-tables
   /// by default.
   virtual bool IsUnwindTablesDefault() const =3D 0;
@@ -162,6 +184,9 @@
   /// Does this tool chain support Objective-C garbage collection.
   virtual bool SupportsObjCGC() const { return true; }
=20
+  /// Does this tool chain support Objective-C ARC.
+  virtual bool SupportsObjCARC() const { return true; }
+
   /// UseDwarfDebugFlags - Embed the compile options to clang into the Dwa=
rf
   /// compile unit information.
   virtual bool UseDwarfDebugFlags() const { return false; }
@@ -202,6 +227,10 @@
   virtual void AddClangSystemIncludeArgs(const ArgList &DriverArgs,
                                          ArgStringList &CC1Args) const;
=20
+  // GetRuntimeLibType - Determine the runtime library type to use with the
+  // given compilation arguments.
+  virtual RuntimeLibType GetRuntimeLibType(const ArgList &Args) const;
+
   // GetCXXStdlibType - Determine the C++ standard library type to use wit=
h the
   // given compilation arguments.
   virtual CXXStdlibType GetCXXStdlibType(const ArgList &Args) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Driver/Types.def
--- a/head/contrib/llvm/tools/clang/include/clang/Driver/Types.def	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Driver/Types.def	Tue Apr =
17 11:51:51 2012 +0300
@@ -82,6 +82,8 @@
 TYPE("ast",                      AST,          INVALID,         "ast",   "=
u")
 TYPE("plist",                    Plist,        INVALID,         "plist", "=
")
 TYPE("rewritten-objc",           RewrittenObjC,INVALID,         "cpp",   "=
")
+TYPE("rewritten-legacy-objc",    RewrittenLegacyObjC,INVALID,   "cpp",   "=
")
+TYPE("remap",                    Remap,        INVALID,         "remap", "=
")
 TYPE("precompiled-header",       PCH,          INVALID,         "gch",   "=
A")
 TYPE("object",                   Object,       INVALID,         "o",     "=
")
 TYPE("treelang",                 Treelang,     INVALID,         0,       "=
u")
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/ASTUnit.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/ASTUnit.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/ASTUnit.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Lex/ModuleLoader.h"
 #include "clang/Lex/PreprocessingRecord.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemOptions.h"
@@ -45,6 +46,7 @@
 class ASTReader;
 class CodeCompleteConsumer;
 class CompilerInvocation;
+class CompilerInstance;
 class Decl;
 class DiagnosticsEngine;
 class FileEntry;
@@ -57,39 +59,33 @@
=20
 using namespace idx;
  =20
-/// \brief Allocator for a cached set of global code completions.
-class GlobalCodeCompletionAllocator=20
-  : public CodeCompletionAllocator,
-    public llvm::RefCountedBase<GlobalCodeCompletionAllocator>=20
-{
-
-};
- =20
 /// \brief Utility class for loading a ASTContext from an AST file.
 ///
 class ASTUnit : public ModuleLoader {
 private:
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
-  llvm::IntrusiveRefCntPtr<FileManager>       FileMgr;
-  llvm::IntrusiveRefCntPtr<SourceManager>     SourceMgr;
-  llvm::OwningPtr<HeaderSearch>               HeaderInfo;
-  llvm::IntrusiveRefCntPtr<TargetInfo>        Target;
-  llvm::IntrusiveRefCntPtr<Preprocessor>      PP;
-  llvm::IntrusiveRefCntPtr<ASTContext>        Ctx;
+  IntrusiveRefCntPtr<LangOptions>       LangOpts;
+  IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
+  IntrusiveRefCntPtr<FileManager>       FileMgr;
+  IntrusiveRefCntPtr<SourceManager>     SourceMgr;
+  OwningPtr<HeaderSearch>               HeaderInfo;
+  IntrusiveRefCntPtr<TargetInfo>        Target;
+  IntrusiveRefCntPtr<Preprocessor>      PP;
+  IntrusiveRefCntPtr<ASTContext>        Ctx;
+  ASTReader *Reader;
=20
   FileSystemOptions FileSystemOpts;
=20
   /// \brief The AST consumer that received information about the translat=
ion
   /// unit as it was parsed or loaded.
-  llvm::OwningPtr<ASTConsumer> Consumer;
+  OwningPtr<ASTConsumer> Consumer;
  =20
   /// \brief The semantic analysis object used to type-check the translati=
on
   /// unit.
-  llvm::OwningPtr<Sema> TheSema;
+  OwningPtr<Sema> TheSema;
  =20
   /// Optional owned invocation, just used to make the invocation used in
   /// LoadFromCommandLine available.
-  llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation;
+  IntrusiveRefCntPtr<CompilerInvocation> Invocation;
  =20
   /// \brief The set of target features.
   ///
@@ -126,6 +122,14 @@
   // source. In the long term we should make the Index library use efficie=
nt and
   // more scalable search mechanisms.
   std::vector<Decl*> TopLevelDecls;
+
+  /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
+  typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
+  typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
+
+  /// \brief Map from FileID to the file-level declarations that it contai=
ns.
+  /// The files and decls are only local (and non-preamble) ones.
+  FileDeclsTy FileDecls;
  =20
   /// The name of the original source file used to generate this ASTUnit.
   std::string OriginalSourceFile;
@@ -140,6 +144,10 @@
   /// translation unit.
   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
=20
+  /// \brief The set of diagnostics produced when failing to parse, e.g. d=
ue
+  /// to failure to load the PCH.
+  SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
+
   /// \brief The number of stored diagnostics that come from the driver
   /// itself.
   ///
@@ -147,10 +155,6 @@
   /// the next.
   unsigned NumStoredDiagnosticsFromDriver;
  =20
-  /// \brief Temporary files that should be removed when the ASTUnit is=20
-  /// destroyed.
-  SmallVector<llvm::sys::Path, 4> TemporaryFiles;
- =20
   /// \brief Counter that determines when we want to try building a
   /// precompiled preamble.
   ///
@@ -161,10 +165,7 @@
   /// building the precompiled preamble fails, we won't try again for
   /// some number of calls.
   unsigned PreambleRebuildCounter;
- =20
-  /// \brief The file in which the precompiled preamble is stored.
-  std::string PreambleFile;
- =20
+
 public:
   class PreambleData {
     const FileEntry *File;
@@ -254,15 +255,11 @@
  =20
   /// \brief Whether we should be caching code-completion results.
   bool ShouldCacheCodeCompletionResults;
- =20
-  /// \brief Whether we want to include nested macro expansions in the
-  /// detailed preprocessing record.
-  bool NestedMacroExpansions;
 =20
   /// \brief The language options used when we load an AST file.
   LangOptions ASTFileLangOpts;
=20
-  static void ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &=
Diags,
+  static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
                              const char **ArgBegin, const char **ArgEnd,
                              ASTUnit &AST, bool CaptureDiagnostics);
=20
@@ -271,6 +268,8 @@
                       const SmallVectorImpl<StoredDiagnostic> &Diags,
                             SmallVectorImpl<StoredDiagnostic> &Out);
=20
+  void clearFileLevelDecls();
+
 public:
   /// \brief A cached code-completion result, which may be introduced in o=
ne of
   /// many different contexts.
@@ -318,29 +317,24 @@
   }
  =20
   /// \brief Retrieve the allocator used to cache global code completions.
-  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>=20
+  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
   getCachedCompletionAllocator() {
     return CachedCompletionAllocator;
   }
- =20
-  /// \brief Retrieve the allocator used to cache global code completions.
-  /// Creates the allocator if it doesn't already exist.
-  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
-  getCursorCompletionAllocator() {
-    if (!CursorCompletionAllocator.getPtr()) {
-      CursorCompletionAllocator =3D new GlobalCodeCompletionAllocator;
-    }
-    return CursorCompletionAllocator;
+
+  CodeCompletionTUInfo &getCodeCompletionTUInfo() {
+    if (!CCTUInfo)
+      CCTUInfo.reset(new CodeCompletionTUInfo(
+                                            new GlobalCodeCompletionAlloca=
tor));
+    return *CCTUInfo;
   }
- =20
+
 private:
   /// \brief Allocator used to store cached code completions.
-  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
+  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
     CachedCompletionAllocator;
  =20
-  /// \brief Allocator used to store code completions for arbitrary cursor=
s.
-  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
-    CursorCompletionAllocator;
+  OwningPtr<CodeCompletionTUInfo> CCTUInfo;
=20
   /// \brief The set of cached code-completion results.
   std::vector<CachedCodeCompletionResult> CachedCompletionResults;
@@ -395,7 +389,11 @@
                                                      bool AllowRebuild =3D=
 true,
                                                         unsigned MaxLines =
=3D 0);
   void RealizeTopLevelDeclsFromPreamble();
- =20
+
+  /// \brief Transfers ownership of the objects (like SourceManager) from
+  /// \param CI to this ASTUnit.
+  void transferASTDataFromCompilerInstance(CompilerInstance &CI);
+
   /// \brief Allows us to assert that ASTUnit is not being used concurrent=
ly,
   /// which is not supported.
   ///
@@ -451,6 +449,7 @@
         ASTContext &getASTContext()       { return *Ctx; }
=20
   void setASTContext(ASTContext *ctx) { Ctx =3D ctx; }
+  void setPreprocessor(Preprocessor *pp);
=20
   bool hasSema() const { return TheSema; }
   Sema &getSema() const {=20
@@ -468,9 +467,7 @@
   /// \brief Add a temporary file that the ASTUnit depends on.
   ///
   /// This file will be erased when the ASTUnit is destroyed.
-  void addTemporaryFile(const llvm::sys::Path &TempFile) {
-    TemporaryFiles.push_back(TempFile);
-  }
+  void addTemporaryFile(const llvm::sys::Path &TempFile);
                        =20
   bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
=20
@@ -514,6 +511,15 @@
     TopLevelDecls.push_back(D);
   }
=20
+  /// \brief Add a new local file-level declaration.
+  void addFileLevelDecl(Decl *D);
+
+  /// \brief Get the decls that are contained in a file in the Offset/Leng=
th
+  /// range. \arg Length can be 0 to indicate a point at \arg Offset inste=
ad of
+  /// a range.=20
+  void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
+                           SmallVectorImpl<Decl *> &Decls);
+
   /// \brief Add a new top-level declaration, identified by its ID in
   /// the precompiled preamble.
   void addTopLevelDeclFromPreamble(serialization::DeclID D) {
@@ -546,6 +552,11 @@
   /// preamble, otherwise it returns \arg Loc.
   SourceLocation mapLocationToPreamble(SourceLocation Loc);
=20
+  bool isInPreambleFileID(SourceLocation Loc);
+  bool isInMainFileID(SourceLocation Loc);
+  SourceLocation getStartOfMainFileID();
+  SourceLocation getEndOfPreambleFileID();
+
   /// \brief \see mapLocationFromPreamble.
   SourceRange mapRangeFromPreamble(SourceRange R) {
     return SourceRange(mapLocationFromPreamble(R.getBegin()),
@@ -559,17 +570,26 @@
   }
  =20
   // Retrieve the diagnostics associated with this AST
-  typedef const StoredDiagnostic *stored_diag_iterator;
-  stored_diag_iterator stored_diag_begin() const {=20
+  typedef StoredDiagnostic *stored_diag_iterator;
+  typedef const StoredDiagnostic *stored_diag_const_iterator;
+  stored_diag_const_iterator stored_diag_begin() const {=20
     return StoredDiagnostics.begin();=20
   }
-  stored_diag_iterator stored_diag_end() const {=20
+  stored_diag_iterator stored_diag_begin() {=20
+    return StoredDiagnostics.begin();=20
+  }
+  stored_diag_const_iterator stored_diag_end() const {=20
+    return StoredDiagnostics.end();=20
+  }
+  stored_diag_iterator stored_diag_end() {=20
     return StoredDiagnostics.end();=20
   }
   unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
- =20
-  SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() {=20
-    return StoredDiagnostics;=20
+
+  stored_diag_iterator stored_diag_afterDriver_begin() {
+    if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
+      NumStoredDiagnosticsFromDriver =3D 0;
+    return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;=20
   }
=20
   typedef std::vector<CachedCodeCompletionResult>::iterator
@@ -601,7 +621,8 @@
=20
   /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvoca=
tion.=20
   static ASTUnit *create(CompilerInvocation *CI,
-                         llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags=
);
+                         IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
+                         bool CaptureDiagnostics =3D false);
=20
   /// \brief Create a ASTUnit from an AST file.
   ///
@@ -612,12 +633,13 @@
   ///
   /// \returns - The initialized ASTUnit or null if the AST failed to load.
   static ASTUnit *LoadFromASTFile(const std::string &Filename,
-                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
+                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
                                   const FileSystemOptions &FileSystemOpts,
                                   bool OnlyLocalDecls =3D false,
                                   RemappedFile *RemappedFiles =3D 0,
                                   unsigned NumRemappedFiles =3D 0,
-                                  bool CaptureDiagnostics =3D false);
+                                  bool CaptureDiagnostics =3D false,
+                                  bool AllowPCHWithCompilerErrors =3D fals=
e);
=20
 private:
   /// \brief Helper function for \c LoadFromCompilerInvocation() and
@@ -646,10 +668,28 @@
   ///
   /// \param Unit - optionally an already created ASTUnit. Its ownership i=
s not
   /// transfered.
+  ///
+  /// \param Persistent - if true the returned ASTUnit will be complete.
+  /// false means the caller is only interested in getting info through the
+  /// provided \see Action.
+  ///
+  /// \param ErrAST - If non-null and parsing failed without any AST to re=
turn
+  /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
+  /// mainly to allow the caller to see the diagnostics.
+  /// This will only receive an ASTUnit if a new one was created. If an al=
ready
+  /// created ASTUnit was passed in \param Unit then the caller can check =
that.
+  ///
   static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
-                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
+                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
                                              ASTFrontendAction *Action =3D=
 0,
-                                             ASTUnit *Unit =3D 0);
+                                             ASTUnit *Unit =3D 0,
+                                             bool Persistent =3D true,
+                                      StringRef ResourceFilesPath =3D Stri=
ngRef(),
+                                             bool OnlyLocalDecls =3D false,
+                                             bool CaptureDiagnostics =3D f=
alse,
+                                             bool PrecompilePreamble =3D f=
alse,
+                                       bool CacheCodeCompletionResults =3D=
 false,
+                                       OwningPtr<ASTUnit> *ErrAST =3D 0);
=20
   /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, v=
ia a
   /// CompilerInvocation object.
@@ -663,13 +703,12 @@
   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUni=
t, we
   // shouldn't need to specify them at construction time.
   static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
-                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
+                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
                                              bool OnlyLocalDecls =3D false,
                                              bool CaptureDiagnostics =3D f=
alse,
                                              bool PrecompilePreamble =3D f=
alse,
                                       TranslationUnitKind TUKind =3D TU_Co=
mplete,
-                                       bool CacheCodeCompletionResults =3D=
 false,
-                                       bool NestedMacroExpansions =3D true=
);
+                                       bool CacheCodeCompletionResults =3D=
 false);
=20
   /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
   /// arguments, which must specify exactly one source file.
@@ -682,12 +721,16 @@
   /// lifetime is expected to extend past that of the returned ASTUnit.
   ///
   /// \param ResourceFilesPath - The path to the compiler resource files.
-  //
+  ///
+  /// \param ErrAST - If non-null and parsing failed without any AST to re=
turn
+  /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
+  /// mainly to allow the caller to see the diagnostics.
+  ///
   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUni=
t, we
   // shouldn't need to specify them at construction time.
   static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
                                       const char **ArgEnd,
-                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
+                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
                                       StringRef ResourceFilesPath,
                                       bool OnlyLocalDecls =3D false,
                                       bool CaptureDiagnostics =3D false,
@@ -697,7 +740,9 @@
                                       bool PrecompilePreamble =3D false,
                                       TranslationUnitKind TUKind =3D TU_Co=
mplete,
                                       bool CacheCodeCompletionResults =3D =
false,
-                                      bool NestedMacroExpansions =3D true);
+                                      bool AllowPCHWithCompilerErrors =3D =
false,
+                                      bool SkipFunctionBodies =3D false,
+                                      OwningPtr<ASTUnit> *ErrAST =3D 0);
  =20
   /// \brief Reparse the source files using the same command-line options =
that
   /// were originally used to produce this translation unit.
@@ -743,9 +788,9 @@
   /// \returns True if an error occurred, false otherwise.
   bool serialize(raw_ostream &OS);
  =20
-  virtual ModuleKey loadModule(SourceLocation ImportLoc,=20
-                               IdentifierInfo &ModuleName,
-                               SourceLocation ModuleNameLoc) {
+  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
+                             Module::NameVisibilityKind Visibility,
+                             bool IsInclusionDirective) {
     // ASTUnit doesn't know how to load modules (not that this matters).
     return 0;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/Analyses.def
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/Analyses.def	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/Analyses.def	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -30,6 +30,7 @@
=20
 ANALYSIS_DIAGNOSTICS(HTML,  "html",  "Output analysis results using HTML",=
   createHTMLDiagnosticConsumer, false)
 ANALYSIS_DIAGNOSTICS(PLIST, "plist", "Output analysis results using Plists=
", createPlistDiagnosticConsumer, true)
+ANALYSIS_DIAGNOSTICS(PLIST_MULTI_FILE, "plist-multi-file", "Output analysi=
s results using Plists (allowing for mult-file bugs)", createPlistMultiFile=
DiagnosticConsumer, true)
 ANALYSIS_DIAGNOSTICS(PLIST_HTML, "plist-html", "Output analysis results us=
ing HTML wrapped with Plists", createPlistHTMLDiagnosticConsumer, true)
 ANALYSIS_DIAGNOSTICS(TEXT, "text", "Text output of analysis results", crea=
teTextPathDiagnosticConsumer, true)
=20
@@ -41,8 +42,24 @@
 ANALYSIS_PURGE(PurgeBlock, "block", "Purge symbols, bindings, and constrai=
nts before every basic block")
 ANALYSIS_PURGE(PurgeNone,  "none", "Do not purge symbols, bindings, or con=
straints")
=20
+#ifndef ANALYSIS_IPA
+#define ANALYSIS_IPA(NAME, CMDFLAG, DESC)
+#endif
+
+ANALYSIS_IPA(None, "none", "Perform only intra-procedural analysis")
+ANALYSIS_IPA(Inlining, "inlining", "Experimental: Inline callees when thei=
r definitions are available")
+
+#ifndef ANALYSIS_INLINING_MODE
+#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC)
+#endif
+
+ANALYSIS_INLINING_MODE(All,  "all", "Analyze all functions in the order de=
fined in the TU")
+ANALYSIS_INLINING_MODE(NoRedundancy, "noredundancy", "Do not analyze a fun=
ction which has been previously inlined, use call graph to order")
+
 #undef ANALYSIS_STORE
 #undef ANALYSIS_CONSTRAINTS
 #undef ANALYSIS_DIAGNOSTICS
 #undef ANALYSIS_PURGE
+#undef ANALYSIS_INLINING_MODE
+#undef ANALYSIS_IPA
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/AnalyzerOptions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/AnalyzerOptions.=
h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/AnalyzerOptions.=
h	Tue Apr 17 11:51:51 2012 +0300
@@ -60,6 +60,20 @@
 NumPurgeModes
 };
=20
+/// AnalysisIPAMode - Set of inter-procedural modes.
+enum AnalysisIPAMode {
+#define ANALYSIS_IPA(NAME, CMDFLAG, DESC) NAME,
+#include "clang/Frontend/Analyses.def"
+NumIPAModes
+};
+
+/// AnalysisInlineFunctionSelection - Set of inlining function selection h=
euristics.
+enum AnalysisInliningMode {
+#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) NAME,
+#include "clang/Frontend/Analyses.def"
+NumInliningModes
+};
+
 class AnalyzerOptions {
 public:
   /// \brief Pair of checker name and enable/disable.
@@ -68,6 +82,7 @@
   AnalysisConstraints AnalysisConstraintsOpt;
   AnalysisDiagClients AnalysisDiagOpt;
   AnalysisPurgeMode AnalysisPurgeOpt;
+  AnalysisIPAMode IPAMode;
   std::string AnalyzeSpecificFunction;
   unsigned MaxNodes;
   unsigned MaxLoop;
@@ -79,11 +94,15 @@
   unsigned TrimGraph : 1;
   unsigned VisualizeEGDot : 1;
   unsigned VisualizeEGUbi : 1;
-  unsigned InlineCall : 1;
   unsigned UnoptimizedCFG : 1;
   unsigned CFGAddImplicitDtors : 1;
   unsigned CFGAddInitializers : 1;
   unsigned EagerlyTrimEGraph : 1;
+  unsigned PrintStats : 1;
+  unsigned NoRetryExhausted : 1;
+  unsigned InlineMaxStackDepth;
+  unsigned InlineMaxFunctionSize;
+  AnalysisInliningMode InliningMode;
=20
 public:
   AnalyzerOptions() {
@@ -91,6 +110,7 @@
     AnalysisConstraintsOpt =3D RangeConstraintsModel;
     AnalysisDiagOpt =3D PD_HTML;
     AnalysisPurgeOpt =3D PurgeStmt;
+    IPAMode =3D Inlining;
     ShowCheckerHelp =3D 0;
     AnalyzeAll =3D 0;
     AnalyzerDisplayProgress =3D 0;
@@ -99,11 +119,16 @@
     TrimGraph =3D 0;
     VisualizeEGDot =3D 0;
     VisualizeEGUbi =3D 0;
-    InlineCall =3D 0;
     UnoptimizedCFG =3D 0;
     CFGAddImplicitDtors =3D 0;
     CFGAddInitializers =3D 0;
     EagerlyTrimEGraph =3D 0;
+    PrintStats =3D 0;
+    NoRetryExhausted =3D 0;
+    // Cap the stack depth at 4 calls (5 stack frames, base + 4 calls).
+    InlineMaxStackDepth =3D 5;
+    InlineMaxFunctionSize =3D 200;
+    InliningMode =3D NoRedundancy;
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/ChainedDiagnosticConsumer.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/ChainedDiagnosti=
cConsumer.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/ChainedDiagnosti=
cConsumer.h	Tue Apr 17 11:51:51 2012 +0300
@@ -21,8 +21,9 @@
 /// should be the "primary" client, and will be used for computing whether=
 the
 /// diagnostics should be included in counts.
 class ChainedDiagnosticConsumer : public DiagnosticConsumer {
-  llvm::OwningPtr<DiagnosticConsumer> Primary;
-  llvm::OwningPtr<DiagnosticConsumer> Secondary;
+  virtual void anchor();
+  OwningPtr<DiagnosticConsumer> Primary;
+  OwningPtr<DiagnosticConsumer> Secondary;
=20
 public:
   ChainedDiagnosticConsumer(DiagnosticConsumer *_Primary,
@@ -42,6 +43,11 @@
     Primary->EndSourceFile();
   }
=20
+  virtual void finish() {
+    Secondary->finish();
+    Primary->finish();
+  }
+
   virtual bool IncludeInDiagnosticCounts() const {
     return Primary->IncludeInDiagnosticCounts();
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/CodeGenOptions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/CodeGenOptions.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -50,6 +50,7 @@
                                   /// internal state before optimizations =
are
                                   /// done.
   unsigned DisableRedZone    : 1; /// Set when -mno-red-zone is enabled.
+  unsigned DisableTailCalls  : 1; /// Do not emit tail calls.
   unsigned EmitDeclMetadata  : 1; /// Emit special metadata indicating what
                                   /// Decl* various IR entities came from.=
  Only
                                   /// useful when running CodeGen as a
@@ -71,10 +72,14 @@
   unsigned MergeAllConstants : 1; /// Merge identical constants.
   unsigned NoCommon          : 1; /// Set when -fno-common or C++ is enabl=
ed.
   unsigned NoDwarf2CFIAsm    : 1; /// Set when -fno-dwarf2-cfi-asm is enab=
led.
+  unsigned NoDwarfDirectoryAsm : 1; /// Set when -fno-dwarf-directory-asm =
is
+                                    /// enabled.
   unsigned NoExecStack       : 1; /// Set when -Wa,--noexecstack is enable=
d.
   unsigned NoGlobalMerge     : 1; /// Set when -mno-global-merge is enable=
d.
   unsigned NoImplicitFloat   : 1; /// Set when -mno-implicit-float is enab=
led.
   unsigned NoInfsFPMath      : 1; /// Assume FP arguments, results not +-I=
nf.
+  unsigned NoInline          : 1; /// Set when -fno-inline is enabled. Dis=
ables
+                                  /// use of the inline keyword.
   unsigned NoNaNsFPMath      : 1; /// Assume FP arguments, results not NaN.
   unsigned NoZeroInitializedInBSS : 1; /// -fno-zero-initialized-in-bss
   unsigned ObjCDispatchMethod : 2; /// Method of Objective-C dispatch to u=
se.
@@ -89,6 +94,7 @@
   unsigned SaveTempLabels    : 1; /// Save temporary labels.
   unsigned SimplifyLibCalls  : 1; /// Set when -fbuiltin is enabled.
   unsigned SoftFloat         : 1; /// -soft-float.
+  unsigned StrictEnums       : 1; /// Optimize based on strict enum defini=
tion.
   unsigned TimePasses        : 1; /// Set when -ftime-report is enabled.
   unsigned UnitAtATime       : 1; /// Unused. For mirroring GCC optimizati=
on
                                   /// selection.
@@ -103,6 +109,11 @@
   unsigned VerifyModule      : 1; /// Control whether the module should be=
 run
                                   /// through the LLVM Verifier.
=20
+  unsigned StackRealignment  : 1; /// Control whether to permit stack
+                                  /// realignment.
+  unsigned StackAlignment;        /// Overrides default stack alignment,
+                                  /// if not 0.
+
   /// The code model to use (-mcmodel).
   std::string CodeModel;
=20
@@ -113,6 +124,9 @@
   /// Enable additional debugging information.
   std::string DebugPass;
=20
+  /// The string to embed in debug information as the current working dire=
ctory.
+  std::string DebugCompilationDir;
+
   /// The string to embed in the debug information for the compile unit, if
   /// non-empty.
   std::string DwarfDebugFlags;
@@ -123,6 +137,9 @@
   /// The float precision limit to use, if non-empty.
   std::string LimitFloatPrecision;
=20
+  /// The name of the bitcode file to link before optzns.
+  std::string LinkBitcodeFile;
+
   /// The kind of inlining to perform.
   InliningMethod Inlining;
=20
@@ -134,6 +151,10 @@
   /// The name of the relocation model to use.
   std::string RelocationModel;
=20
+  /// If not an empty string, trap intrinsics are lowered to calls to this
+  /// function instead of to trap instructions.
+  std::string TrapFuncName;
+
   /// A list of command-line options to forward to the LLVM backend.
   std::vector<std::string> BackendOptions;
=20
@@ -153,6 +174,7 @@
     DisableFPElim =3D 0;
     DisableLLVMOpts =3D 0;
     DisableRedZone =3D 0;
+    DisableTailCalls =3D 0;
     EmitDeclMetadata =3D 0;
     EmitGcovArcs =3D 0;
     EmitGcovNotes =3D 0;
@@ -168,6 +190,7 @@
     NoDwarf2CFIAsm =3D 0;
     NoImplicitFloat =3D 0;
     NoInfsFPMath =3D 0;
+    NoInline =3D 0;
     NoNaNsFPMath =3D 0;
     NoZeroInitializedInBSS =3D 0;
     NumRegisterParameters =3D 0;
@@ -183,6 +206,7 @@
     SaveTempLabels =3D 0;
     SimplifyLibCalls =3D 1;
     SoftFloat =3D 0;
+    StrictEnums =3D 0;
     TimePasses =3D 0;
     UnitAtATime =3D 1;
     UnrollLoops =3D 0;
@@ -190,6 +214,8 @@
     UnwindTables =3D 0;
     UseRegisterSizedBitfieldAccess =3D 0;
     VerifyModule =3D 1;
+    StackRealignment =3D 0;
+    StackAlignment =3D 0;
=20
     Inlining =3D NoInlining;
     RelocationModel =3D "pic";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/CompilerInstance.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/CompilerInstance=
.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/CompilerInstance=
.h	Tue Apr 17 11:51:51 2012 +0300
@@ -11,13 +11,17 @@
 #define LLVM_CLANG_FRONTEND_COMPILERINSTANCE_H_
=20
 #include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/Lex/ModuleLoader.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/OwningPtr.h"
 #include <cassert>
 #include <list>
 #include <string>
+#include <utility>
=20
 namespace llvm {
 class raw_fd_ostream;
@@ -32,8 +36,10 @@
 class DiagnosticsEngine;
 class DiagnosticConsumer;
 class ExternalASTSource;
+class FileEntry;
 class FileManager;
 class FrontendAction;
+class Module;
 class Preprocessor;
 class Sema;
 class SourceManager;
@@ -59,41 +65,53 @@
 /// and a long form that takes explicit instances of any required objects.
 class CompilerInstance : public ModuleLoader {
   /// The options used in this compiler instance.
-  llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation;
+  IntrusiveRefCntPtr<CompilerInvocation> Invocation;
=20
   /// The diagnostics engine instance.
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
+  IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
=20
   /// The target being compiled for.
-  llvm::IntrusiveRefCntPtr<TargetInfo> Target;
+  IntrusiveRefCntPtr<TargetInfo> Target;
=20
   /// The file manager.
-  llvm::IntrusiveRefCntPtr<FileManager> FileMgr;
+  IntrusiveRefCntPtr<FileManager> FileMgr;
=20
   /// The source manager.
-  llvm::IntrusiveRefCntPtr<SourceManager> SourceMgr;
+  IntrusiveRefCntPtr<SourceManager> SourceMgr;
=20
   /// The preprocessor.
-  llvm::IntrusiveRefCntPtr<Preprocessor> PP;
+  IntrusiveRefCntPtr<Preprocessor> PP;
=20
   /// The AST context.
-  llvm::IntrusiveRefCntPtr<ASTContext> Context;
+  IntrusiveRefCntPtr<ASTContext> Context;
=20
   /// The AST consumer.
-  llvm::OwningPtr<ASTConsumer> Consumer;
+  OwningPtr<ASTConsumer> Consumer;
=20
   /// The code completion consumer.
-  llvm::OwningPtr<CodeCompleteConsumer> CompletionConsumer;
+  OwningPtr<CodeCompleteConsumer> CompletionConsumer;
=20
   /// \brief The semantic analysis object.
-  llvm::OwningPtr<Sema> TheSema;
+  OwningPtr<Sema> TheSema;
  =20
   /// \brief The frontend timer
-  llvm::OwningPtr<llvm::Timer> FrontendTimer;
+  OwningPtr<llvm::Timer> FrontendTimer;
=20
   /// \brief Non-owning reference to the ASTReader, if one exists.
   ASTReader *ModuleManager;
=20
+  /// \brief The set of top-level modules that has already been loaded,
+  /// along with the module map
+  llvm::DenseMap<const IdentifierInfo *, Module *> KnownModules;
+ =20
+  /// \brief The location of the module-import keyword for the last module
+  /// import.=20
+  SourceLocation LastModuleImportLoc;
+ =20
+  /// \brief The result of the last module import.
+  ///
+  Module *LastModuleImportResult;
+ =20
   /// \brief Holds information about the output file.
   ///
   /// If TempFilename is not empty we must rename it to Filename at the en=
d.
@@ -218,10 +236,10 @@
   }
=20
   LangOptions &getLangOpts() {
-    return Invocation->getLangOpts();
+    return *Invocation->getLangOpts();
   }
   const LangOptions &getLangOpts() const {
-    return Invocation->getLangOpts();
+    return *Invocation->getLangOpts();
   }
=20
   PreprocessorOptions &getPreprocessorOpts() {
@@ -491,7 +509,7 @@
   /// used by some diagnostics printers (for logging purposes only).
   ///
   /// \return The new object on success, or null on failure.
-  static llvm::IntrusiveRefCntPtr<DiagnosticsEngine>=20
+  static IntrusiveRefCntPtr<DiagnosticsEngine>
   createDiagnostics(const DiagnosticOptions &Opts, int Argc,
                     const char* const *Argv,
                     DiagnosticConsumer *Client =3D 0,
@@ -517,6 +535,7 @@
   void createPCHExternalASTSource(StringRef Path,
                                   bool DisablePCHValidation,
                                   bool DisableStatCache,
+                                  bool AllowPCHWithCompilerErrors,
                                   void *DeserializationListener);
=20
   /// Create an external AST source to read a PCH file.
@@ -526,6 +545,7 @@
   createPCHExternalASTSource(StringRef Path, const std::string &Sysroot,
                              bool DisablePCHValidation,
                              bool DisableStatCache,
+                             bool AllowPCHWithCompilerErrors,
                              Preprocessor &PP, ASTContext &Context,
                              void *DeserializationListener, bool Preamble);
=20
@@ -554,6 +574,10 @@
   /// Create the default output file (from the invocation's options) and a=
dd it
   /// to the list of tracked output files.
   ///
+  /// The files created by this function always use temporary files to wri=
te to
+  /// their result (that is, the data is written to a temporary file which=
 will
+  /// atomically replace the target output on success).
+  ///
   /// \return - Null on error.
   llvm::raw_fd_ostream *
   createDefaultOutputFile(bool Binary =3D true, StringRef BaseInput =3D "",
@@ -568,7 +592,8 @@
                    bool Binary =3D true, bool RemoveFileOnSignal =3D true,
                    StringRef BaseInput =3D "",
                    StringRef Extension =3D "",
-                   bool UseTemporary =3D false);
+                   bool UseTemporary =3D false,
+                   bool CreateMissingDirectories =3D false);
=20
   /// Create a new output file, optionally deriving the output path name.
   ///
@@ -588,7 +613,9 @@
   /// llvm::sys::RemoveFileOnSignal. Note that this is not safe for
   /// multithreaded use, as the underlying signal mechanism is not reentra=
nt
   /// \param UseTemporary - Create a new temporary file that must be renam=
ed to
-  ///         OutputPath in the end
+  /// OutputPath in the end.
+  /// \param CreateMissingDirectories - When \arg UseTemporary is true, cr=
eate
+  /// missing directories in the output path.
   /// \param ResultPathName [out] - If given, the result path name will be
   /// stored here on success.
   /// \param TempPathName [out] - If given, the temporary file path name
@@ -599,6 +626,7 @@
                    StringRef BaseInput =3D "",
                    StringRef Extension =3D "",
                    bool UseTemporary =3D false,
+                   bool CreateMissingDirectories =3D false,
                    std::string *ResultPathName =3D 0,
                    std::string *TempPathName =3D 0);
=20
@@ -610,23 +638,25 @@
   /// as the main file.
   ///
   /// \return True on success.
-  bool InitializeSourceManager(StringRef InputFile);
+  bool InitializeSourceManager(StringRef InputFile,
+         SrcMgr::CharacteristicKind Kind =3D SrcMgr::C_User);
=20
   /// InitializeSourceManager - Initialize the source manager to set Input=
File
   /// as the main file.
   ///
   /// \return True on success.
   static bool InitializeSourceManager(StringRef InputFile,
-                                      DiagnosticsEngine &Diags,
-                                      FileManager &FileMgr,
-                                      SourceManager &SourceMgr,
-                                      const FrontendOptions &Opts);
+                SrcMgr::CharacteristicKind Kind,
+                DiagnosticsEngine &Diags,
+                FileManager &FileMgr,
+                SourceManager &SourceMgr,
+                const FrontendOptions &Opts);
=20
   /// }
  =20
-  virtual ModuleKey loadModule(SourceLocation ImportLoc,=20
-                               IdentifierInfo &ModuleName,
-                               SourceLocation ModuleNameLoc);
+  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
+                             Module::NameVisibilityKind Visibility,
+                             bool IsInclusionDirective);
 };
=20
 } // end namespace clang
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/CompilerInvocation.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/CompilerInvocati=
on.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/CompilerInvocati=
on.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #include "clang/Basic/TargetOptions.h"
 #include "clang/Basic/FileSystemOptions.h"
 #include "clang/Frontend/AnalyzerOptions.h"
+#include "clang/Frontend/MigratorOptions.h"
 #include "clang/Frontend/CodeGenOptions.h"
 #include "clang/Frontend/DependencyOutputOptions.h"
 #include "clang/Frontend/DiagnosticOptions.h"
@@ -30,18 +31,45 @@
=20
 namespace clang {
=20
+class CompilerInvocation;
 class DiagnosticsEngine;
=20
+namespace driver {
+class ArgList;
+}
+
+/// CompilerInvocation - Fill out Opts based on the options given in Args.
+/// Args must have been created from the OptTable returned by
+/// createCC1OptTable(). When errors are encountered, return false and,
+/// if Diags is non-null, report the error(s).
+bool ParseDiagnosticArgs(DiagnosticOptions &Opts, driver::ArgList &Args,
+                         DiagnosticsEngine *Diags =3D 0);
+ =20
+class CompilerInvocationBase : public RefCountedBase<CompilerInvocation> {
+protected:
+  /// Options controlling the language variant.
+  IntrusiveRefCntPtr<LangOptions> LangOpts;
+public:
+  CompilerInvocationBase();
+
+  CompilerInvocationBase(const CompilerInvocationBase &X);
+ =20
+  LangOptions *getLangOpts() { return LangOpts.getPtr(); }
+  const LangOptions *getLangOpts() const { return LangOpts.getPtr(); }
+};
+ =20
 /// CompilerInvocation - Helper class for holding the data necessary to in=
voke
 /// the compiler.
 ///
 /// This class is designed to represent an abstract "invocation" of the
 /// compiler, including data such as the include paths, the code generation
 /// options, the warning flags, and so on.
-class CompilerInvocation : public llvm::RefCountedBase<CompilerInvocation>=
 {
+class CompilerInvocation : public CompilerInvocationBase {
   /// Options controlling the static analyzer.
   AnalyzerOptions AnalyzerOpts;
=20
+  MigratorOptions MigratorOpts;
+ =20
   /// Options controlling IRgen and the backend.
   CodeGenOptions CodeGenOpts;
=20
@@ -60,9 +88,6 @@
   /// Options controlling the #include directive.
   HeaderSearchOptions HeaderSearchOpts;
=20
-  /// Options controlling the language variant.
-  LangOptions LangOpts;
-
   /// Options controlling the preprocessor (aside from #include handling).
   PreprocessorOptions PreprocessorOpts;
=20
@@ -79,13 +104,13 @@
   /// @{
=20
   /// CreateFromArgs - Create a compiler invocation from a list of input
-  /// options.
+  /// options. Returns true on success.
   ///
   /// \param Res [out] - The resulting invocation.
   /// \param ArgBegin - The first element in the argument vector.
   /// \param ArgEnd - The last element in the argument vector.
   /// \param Diags - The diagnostic engine to use for errors.
-  static void CreateFromArgs(CompilerInvocation &Res,
+  static bool CreateFromArgs(CompilerInvocation &Res,
                              const char* const *ArgBegin,
                              const char* const *ArgEnd,
                              DiagnosticsEngine &Diags);
@@ -111,7 +136,7 @@
   /// \param LangStd - The input language standard.
   void setLangDefaults(InputKind IK,
                   LangStandard::Kind LangStd =3D LangStandard::lang_unspec=
ified) {
-    setLangDefaults(LangOpts, IK, LangStd);
+    setLangDefaults(*getLangOpts(), IK, LangStd);
   }
=20
   /// setLangDefaults - Set language defaults for the given input language=
 and
@@ -136,6 +161,11 @@
     return AnalyzerOpts;
   }
=20
+  MigratorOptions &getMigratorOpts() { return MigratorOpts; }
+  const MigratorOptions &getMigratorOpts() const {
+    return MigratorOpts;
+  }
+ =20
   CodeGenOptions &getCodeGenOpts() { return CodeGenOpts; }
   const CodeGenOptions &getCodeGenOpts() const {
     return CodeGenOpts;
@@ -166,9 +196,6 @@
     return FrontendOpts;
   }
=20
-  LangOptions &getLangOpts() { return LangOpts; }
-  const LangOptions &getLangOpts() const { return LangOpts; }
-
   PreprocessorOptions &getPreprocessorOpts() { return PreprocessorOpts; }
   const PreprocessorOptions &getPreprocessorOpts() const {
     return PreprocessorOpts;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/DependencyOutputOptions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/DependencyOutput=
Options.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/DependencyOutput=
Options.h	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
                                      /// dependency, which can avoid some =
'make'
                                      /// problems.
   unsigned AddMissingHeaderDeps : 1; ///< Add missing headers to dependenc=
y list
-
+ =20
   /// The file to write dependency output to.
   std::string OutputFile;
=20
@@ -39,6 +39,9 @@
   /// must contain at least one entry.
   std::vector<std::string> Targets;
=20
+  /// \brief The file to write GraphViz-formatted header dependencies to.
+  std::string DOTOutputFile;
+ =20
 public:
   DependencyOutputOptions() {
     IncludeSystemHeaders =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/DiagnosticOptions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/DiagnosticOption=
s.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/DiagnosticOption=
s.h	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,6 @@
   unsigned ShowFixits : 1;       /// Show fixit information.
   unsigned ShowSourceRanges : 1; /// Show source ranges in numeric form.
   unsigned ShowParseableFixits : 1; /// Show machine parseable fix-its.
-  unsigned ShowNames : 1;        /// Show the diagnostic name
   unsigned ShowOptionNames : 1;  /// Show the option name for mappable
                                  /// diagnostics.
   unsigned ShowNoteIncludeStack : 1; /// Show include stacks for notes.
@@ -51,12 +50,14 @@
   unsigned ErrorLimit;           /// Limit # errors emitted.
   unsigned MacroBacktraceLimit;  /// Limit depth of macro expansion backtr=
ace.
   unsigned TemplateBacktraceLimit; /// Limit depth of instantiation backtr=
ace.
+  unsigned ConstexprBacktraceLimit; /// Limit depth of constexpr backtrace.
=20
   /// The distance between tab stops.
   unsigned TabStop;
   enum { DefaultTabStop =3D 8, MaxTabStop =3D 100,=20
          DefaultMacroBacktraceLimit =3D 6,
-         DefaultTemplateBacktraceLimit =3D 10 };
+         DefaultTemplateBacktraceLimit =3D 10,
+         DefaultConstexprBacktraceLimit =3D 10 };
=20
   /// Column limit for formatting message diagnostics, or 0 if unused.
   unsigned MessageLength;
@@ -67,6 +68,9 @@
=20
   /// The file to log diagnostic output to.
   std::string DiagnosticLogFile;
+ =20
+  /// The file to serialize diagnostics to (non-appending).
+  std::string DiagnosticSerializationFile;
=20
   /// The list of -W... options used to alter the diagnostic mappings, wit=
h the
   /// prefixes removed.
@@ -86,7 +90,6 @@
     ShowColumn =3D 1;
     ShowFixits =3D 1;
     ShowLocation =3D 1;
-    ShowNames =3D 0;
     ShowOptionNames =3D 0;
     ShowCategories =3D 0;
     Format =3D Clang;
@@ -96,6 +99,7 @@
     ErrorLimit =3D 0;
     TemplateBacktraceLimit =3D DefaultTemplateBacktraceLimit;
     MacroBacktraceLimit =3D DefaultMacroBacktraceLimit;
+    ConstexprBacktraceLimit =3D DefaultConstexprBacktraceLimit;
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/FrontendAction.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendAction.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendAction.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -12,6 +12,7 @@
=20
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Frontend/FrontendOptions.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/OwningPtr.h"
 #include <string>
@@ -23,30 +24,11 @@
 class ASTUnit;
 class CompilerInstance;
=20
-enum InputKind {
-  IK_None,
-  IK_Asm,
-  IK_C,
-  IK_CXX,
-  IK_ObjC,
-  IK_ObjCXX,
-  IK_PreprocessedC,
-  IK_PreprocessedCXX,
-  IK_PreprocessedObjC,
-  IK_PreprocessedObjCXX,
-  IK_OpenCL,
-  IK_CUDA,
-  IK_AST,
-  IK_LLVM_IR
-};
-
-
 /// FrontendAction - Abstract base class for actions which can be performe=
d by
 /// the frontend.
 class FrontendAction {
-  std::string CurrentFile;
-  InputKind CurrentFileKind;
-  llvm::OwningPtr<ASTUnit> CurrentASTUnit;
+  FrontendInputFile CurrentInput;
+  OwningPtr<ASTUnit> CurrentASTUnit;
   CompilerInstance *Instance;
   friend class ASTMergeAction;
   friend class WrapperFrontendAction;
@@ -103,7 +85,7 @@
=20
   /// EndSourceFileAction - Callback at the end of processing a single inp=
ut;
   /// this is guaranteed to only be called following a successful call to
-  /// BeginSourceFileAction (and BeingSourceFile).
+  /// BeginSourceFileAction (and BeginSourceFile).
   virtual void EndSourceFileAction() {}
=20
   /// @}
@@ -127,18 +109,22 @@
   /// @{
=20
   bool isCurrentFileAST() const {
-    assert(!CurrentFile.empty() && "No current file!");
+    assert(!CurrentInput.File.empty() && "No current file!");
     return CurrentASTUnit !=3D 0;
   }
=20
+  const FrontendInputFile &getCurrentInput() const {
+    return CurrentInput;
+  }
+ =20
   const std::string &getCurrentFile() const {
-    assert(!CurrentFile.empty() && "No current file!");
-    return CurrentFile;
+    assert(!CurrentInput.File.empty() && "No current file!");
+    return CurrentInput.File;
   }
=20
   InputKind getCurrentFileKind() const {
-    assert(!CurrentFile.empty() && "No current file!");
-    return CurrentFileKind;
+    assert(!CurrentInput.File.empty() && "No current file!");
+    return CurrentInput.Kind;
   }
=20
   ASTUnit &getCurrentASTUnit() const {
@@ -150,7 +136,7 @@
     return CurrentASTUnit.take();
   }
=20
-  void setCurrentFile(StringRef Value, InputKind Kind, ASTUnit *AST =3D 0);
+  void setCurrentInput(const FrontendInputFile &CurrentInput, ASTUnit *AST=
 =3D 0);
=20
   /// @}
   /// @name Supported Modes
@@ -189,10 +175,7 @@
   /// action may store and use this object up until the matching EndSource=
File
   /// action.
   ///
-  /// \param Filename - The input filename, which will be made available to
-  /// clients via \see getCurrentFile().
-  ///
-  /// \param InputKind - The type of input. Some input kinds are handled
+  /// \param Input - The input filename and kind. Some input kinds are han=
dled
   /// specially, for example AST inputs, since the AST file itself contains
   /// several objects which would normally be owned by the
   /// CompilerInstance. When processing AST input files, these objects sho=
uld
@@ -200,10 +183,9 @@
   /// automatically be shared with the AST file in between \see
   /// BeginSourceFile() and \see EndSourceFile().
   ///
-  /// \return True on success; the compilation of this file should be abor=
ted
-  /// and neither Execute nor EndSourceFile should be called.
-  bool BeginSourceFile(CompilerInstance &CI, StringRef Filename,
-                       InputKind Kind);
+  /// \return True on success; on failure the compilation of this file sho=
uld
+  /// be aborted and neither Execute nor EndSourceFile should be called.
+  bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Inpu=
t);
=20
   /// Execute - Set the source managers main input file, and run the actio=
n.
   void Execute();
@@ -231,6 +213,7 @@
 };
=20
 class PluginASTAction : public ASTFrontendAction {
+  virtual void anchor();
 protected:
   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
                                          StringRef InFile) =3D 0;
@@ -265,7 +248,7 @@
 /// implements every virtual method in the FrontendAction interface by
 /// forwarding to the wrapped action.
 class WrapperFrontendAction : public FrontendAction {
-  llvm::OwningPtr<FrontendAction> WrappedAction;
+  OwningPtr<FrontendAction> WrappedAction;
=20
 protected:
   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/FrontendActions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendActions.=
h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendActions.=
h	Tue Apr 17 11:51:51 2012 +0300
@@ -16,6 +16,8 @@
=20
 namespace clang {
=20
+class Module;
+ =20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Custom Consumer Actions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -67,21 +69,43 @@
 };
=20
 class GeneratePCHAction : public ASTFrontendAction {
-  bool MakeModule;
- =20
 protected:
   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
                                          StringRef InFile);
=20
-  virtual TranslationUnitKind getTranslationUnitKind() {=20
-    return MakeModule? TU_Module : TU_Prefix;
+  virtual TranslationUnitKind getTranslationUnitKind() {
+    return TU_Prefix;
   }
=20
   virtual bool hasASTFileSupport() const { return false; }
=20
 public:
-  /// \brief Create a new action
-  explicit GeneratePCHAction(bool MakeModule) : MakeModule(MakeModule) { }
+  /// \brief Compute the AST consumer arguments that will be used to
+  /// create the PCHGenerator instance returned by CreateASTConsumer.
+  ///
+  /// \returns true if an error occurred, false otherwise.
+  static bool ComputeASTConsumerArguments(CompilerInstance &CI,
+                                          StringRef InFile,
+                                          std::string &Sysroot,
+                                          std::string &OutputFile,
+                                          raw_ostream *&OS);
+};
+
+class GenerateModuleAction : public ASTFrontendAction {
+  clang::Module *Module;
+ =20
+protected:
+  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
+                                         StringRef InFile);
+ =20
+  virtual TranslationUnitKind getTranslationUnitKind() {=20
+    return TU_Module;
+  }
+ =20
+  virtual bool hasASTFileSupport() const { return false; }
+ =20
+public:
+  virtual bool BeginSourceFileAction(CompilerInstance &CI, StringRef Filen=
ame);
  =20
   /// \brief Compute the AST consumer arguments that will be used to
   /// create the PCHGenerator instance returned by CreateASTConsumer.
@@ -93,7 +117,7 @@
                                           std::string &OutputFile,
                                           raw_ostream *&OS);
 };
-
+ =20
 class SyntaxOnlyAction : public ASTFrontendAction {
 protected:
   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
@@ -129,8 +153,7 @@
   virtual void EndSourceFileAction();
=20
 public:
-  ASTMergeAction(FrontendAction *AdaptedAction,
-                 std::string *ASTFiles, unsigned NumASTFiles);
+  ASTMergeAction(FrontendAction *AdaptedAction, ArrayRef<std::string> ASTF=
iles);
   virtual ~ASTMergeAction();
=20
   virtual bool usesPreprocessorOnly() const;
@@ -150,6 +173,15 @@
   virtual bool usesPreprocessorOnly() const { return true; }
 };
  =20
+class PubnamesDumpAction : public ASTFrontendAction {
+protected:
+  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
+                                         StringRef InFile);
+ =20
+public:
+  virtual bool hasCodeCompletionSupport() const { return false; }
+};
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Preprocessor Actions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/FrontendDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendDiagnost=
ic.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendDiagnost=
ic.h	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
   namespace diag {
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
 #define FRONTENDSTART
 #include "clang/Basic/DiagnosticFrontendKinds.inc"
 #undef DIAG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/FrontendOptions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendOptions.=
h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/FrontendOptions.=
h	Tue Apr 17 11:51:51 2012 +0300
@@ -11,7 +11,6 @@
 #define LLVM_CLANG_FRONTEND_FRONTENDOPTIONS_H
=20
 #include "clang/Frontend/CommandLineSourceLoc.h"
-#include "clang/Frontend/FrontendAction.h"
 #include "llvm/ADT/StringRef.h"
 #include <string>
 #include <vector>
@@ -43,14 +42,50 @@
     PrintDeclContext,       ///< Print DeclContext and their Decls.
     PrintPreamble,          ///< Print the "preamble" of the input file
     PrintPreprocessedInput, ///< -E mode.
+    PubnamesDump,           ///< Print all of the "public" names in the so=
urce.
     RewriteMacros,          ///< Expand macros but not #includes.
     RewriteObjC,            ///< ObjC->C Rewriter.
     RewriteTest,            ///< Rewriter playground
     RunAnalysis,            ///< Run one or more source code analyses.
+    MigrateSource,          ///< Run migrator.
     RunPreprocessorOnly     ///< Just lex, no output.
   };
 }
=20
+enum InputKind {
+  IK_None,
+  IK_Asm,
+  IK_C,
+  IK_CXX,
+  IK_ObjC,
+  IK_ObjCXX,
+  IK_PreprocessedC,
+  IK_PreprocessedCXX,
+  IK_PreprocessedObjC,
+  IK_PreprocessedObjCXX,
+  IK_OpenCL,
+  IK_CUDA,
+  IK_AST,
+  IK_LLVM_IR
+};
+
+ =20
+/// \brief An input file for the front end.
+struct FrontendInputFile {
+  /// \brief The file name, or "-" to read from standard input.
+  std::string File;
+
+  /// \brief The kind of input, e.g., C source, AST file, LLVM IR.
+  InputKind Kind;
+
+  /// \brief Whether we're dealing with a 'system' input (vs. a 'user' inp=
ut).
+  bool IsSystem;
+ =20
+  FrontendInputFile() : Kind(IK_None) { }
+  FrontendInputFile(StringRef File, InputKind Kind, bool IsSystem =3D fals=
e)
+    : File(File.str()), Kind(Kind), IsSystem(IsSystem) { }
+};
+ =20
 /// FrontendOptions - Options for controlling the behavior of the frontend.
 class FrontendOptions {
 public:
@@ -72,8 +107,15 @@
   unsigned ShowVersion : 1;                ///< Show the -version text.
   unsigned FixWhatYouCan : 1;              ///< Apply fixes even if there =
are
                                            /// unfixable errors.
+  unsigned FixOnlyWarnings : 1;            ///< Apply fixes only for warni=
ngs.
+  unsigned FixAndRecompile : 1;            ///< Apply fixes and recompile.
+  unsigned FixToTemporaries : 1;           ///< Apply fixes to temporary f=
iles.
   unsigned ARCMTMigrateEmitARCErrors : 1;  /// Emit ARC errors even if the
                                            /// migrator can fix them
+  unsigned SkipFunctionBodies : 1;         ///< Skip over function bodies =
to
+                                           /// speed up parsing in cases y=
ou do
+                                           /// not need them (e.g. with co=
de
+                                           /// completion).
=20
   enum {
     ARCMT_None,
@@ -82,11 +124,20 @@
     ARCMT_Migrate
   } ARCMTAction;
=20
-  std::string ARCMTMigrateDir;
+  enum {
+    ObjCMT_None =3D 0,
+    /// \brief Enable migration to modern ObjC literals.
+    ObjCMT_Literals =3D 0x1,
+    /// \brief Enable migration to modern ObjC subscripting.
+    ObjCMT_Subscripting =3D 0x2
+  };
+  unsigned ObjCMTAction;
+
+  std::string MTMigrateDir;
   std::string ARCMTMigrateReportOut;
=20
   /// The input files and their types.
-  std::vector<std::pair<InputKind, std::string> > Inputs;
+  std::vector<FrontendInputFile> Inputs;
=20
   /// The output file, if any.
   std::string OutputFile;
@@ -122,6 +173,10 @@
   /// should only be used for debugging and experimental features.
   std::vector<std::string> LLVMArgs;
=20
+  /// \brief File name of the file that will provide record layouts
+  /// (in the format produced by -fdump-record-layouts).
+  std::string OverrideRecordLayoutsFile;
+ =20
 public:
   FrontendOptions() {
     DisableFree =3D 0;
@@ -137,6 +192,8 @@
     ShowVersion =3D 0;
     ARCMTAction =3D ARCMT_None;
     ARCMTMigrateEmitARCErrors =3D 0;
+    SkipFunctionBodies =3D 0;
+    ObjCMTAction =3D ObjCMT_None;
   }
=20
   /// getInputKindForExtension - Return the appropriate input kind for a f=
ile
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/LangStandard.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/LangStandard.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/LangStandard.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
   BCPLComment =3D (1 << 0),
   C89 =3D (1 << 1),
   C99 =3D (1 << 2),
-  C1X =3D (1 << 3),
+  C11 =3D (1 << 3),
   CPlusPlus =3D (1 << 4),
   CPlusPlus0x =3D (1 << 5),
   Digraphs =3D (1 << 6),
@@ -62,8 +62,8 @@
   /// isC99 - Language is a superset of C99.
   bool isC99() const { return Flags & frontend::C99; }
=20
-  /// isC1X - Language is a superset of C1X.
-  bool isC1X() const { return Flags & frontend::C1X; }
+  /// isC11 - Language is a superset of C11.
+  bool isC11() const { return Flags & frontend::C11; }
=20
   /// isCPlusPlus - Language is a C++ variant.
   bool isCPlusPlus() const { return Flags & frontend::CPlusPlus; }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/LangStandards.def
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/LangStandards.de=
f	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/LangStandards.de=
f	Tue Apr 17 11:51:51 2012 +0300
@@ -62,17 +62,26 @@
              "ISO C 1999 with GNU extensions",
              BCPLComment | C99 | Digraphs | GNUMode | HexFloat)
=20
-// C1X modes
+// C11 modes
+LANGSTANDARD(c11, "c11",
+             "ISO C 2011",
+             BCPLComment | C99 | C11 | Digraphs | HexFloat)
 LANGSTANDARD(c1x, "c1x",
-             "ISO C 201X",
-             BCPLComment | C99 | C1X | Digraphs | HexFloat)
+             "ISO C 2011",
+             BCPLComment | C99 | C11 | Digraphs | HexFloat)
+LANGSTANDARD(iso9899_2011,
+             "iso9899:2011", "ISO C 2011",
+             BCPLComment | C99 | C11 | Digraphs | HexFloat)
 LANGSTANDARD(iso9899_201x,
-             "iso9899:201x", "ISO C 201X",
-             BCPLComment | C99 | C1X | Digraphs | HexFloat)
+             "iso9899:2011", "ISO C 2011",
+             BCPLComment | C99 | C11 | Digraphs | HexFloat)
=20
+LANGSTANDARD(gnu11, "gnu11",
+             "ISO C 2011 with GNU extensions",
+             BCPLComment | C99 | C11 | Digraphs | GNUMode | HexFloat)
 LANGSTANDARD(gnu1x, "gnu1x",
-             "ISO C 201X with GNU extensions",
-             BCPLComment | C99 | C1X | Digraphs | GNUMode | HexFloat)
+             "ISO C 2011 with GNU extensions",
+             BCPLComment | C99 | C11 | Digraphs | GNUMode | HexFloat)
=20
 // C++ modes
 LANGSTANDARD(cxx98, "c++98",
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/MultiplexConsumer.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/MultiplexConsume=
r.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/MultiplexConsume=
r.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,9 @@
 #ifndef CLANG_FRONTEND_MULTIPLEXCONSUMER_H
 #define CLANG_FRONTEND_MULTIPLEXCONSUMER_H
=20
+#include "clang/Basic/LLVM.h"
 #include "clang/Sema/SemaConsumer.h"
+#include "clang/Basic/LLVM.h"
 #include "llvm/ADT/OwningPtr.h"
 #include <vector>
=20
@@ -28,15 +30,18 @@
 class MultiplexConsumer : public SemaConsumer {
 public:
   // Takes ownership of the pointers in C.
-  MultiplexConsumer(const std::vector<ASTConsumer*>& C);
+  MultiplexConsumer(ArrayRef<ASTConsumer*> C);
   ~MultiplexConsumer();
=20
   // ASTConsumer
   virtual void Initialize(ASTContext &Context);
-  virtual void HandleTopLevelDecl(DeclGroupRef D);
+  virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
+  virtual bool HandleTopLevelDecl(DeclGroupRef D);
   virtual void HandleInterestingDecl(DeclGroupRef D);
   virtual void HandleTranslationUnit(ASTContext &Ctx);
   virtual void HandleTagDeclDefinition(TagDecl *D);
+  virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D);
+  virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D);
   virtual void CompleteTentativeDefinition(VarDecl *D);
   virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired);
   virtual ASTMutationListener *GetASTMutationListener();
@@ -50,8 +55,8 @@
   static bool classof(const MultiplexConsumer *) { return true; }
 private:
   std::vector<ASTConsumer*> Consumers;  // Owns these.
-  llvm::OwningPtr<MultiplexASTMutationListener> MutationListener;
-  llvm::OwningPtr<MultiplexASTDeserializationListener> DeserializationList=
ener;
+  OwningPtr<MultiplexASTMutationListener> MutationListener;
+  OwningPtr<MultiplexASTDeserializationListener> DeserializationListener;
 };
=20
 }  // end namespace clang
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/PreprocessorOptions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/PreprocessorOpti=
ons.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/PreprocessorOpti=
ons.h	Tue Apr 17 11:51:51 2012 +0300
@@ -10,6 +10,7 @@
 #ifndef LLVM_CLANG_FRONTEND_PREPROCESSOROPTIONS_H_
 #define LLVM_CLANG_FRONTEND_PREPROCESSOROPTIONS_H_
=20
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include <cassert>
 #include <string>
@@ -49,14 +50,10 @@
   unsigned DetailedRecord : 1; /// Whether we should maintain a detailed
                                /// record of all macro definitions and
                                /// expansions.
- =20
-  /// \brief Whether we should automatically translate #include or #import
-  /// operations into module imports when possible.
-  unsigned AutoModuleImport : 1;
-
-  /// \brief Whether the detailed preprocessing record includes nested mac=
ro=20
-  /// expansions.
-  unsigned DetailedRecordIncludesNestedMacroExpansions : 1;
+  unsigned DetailedRecordConditionalDirectives : 1; /// Whether in the
+                               /// preprocessing record we should also keep
+                               /// track of locations of conditional direc=
tives
+                               /// in non-system files.
  =20
   /// The implicit PCH included at the start of the translation unit, or e=
mpty.
   std::string ImplicitPCHInclude;
@@ -72,6 +69,9 @@
   /// precompiled header or AST file.
   bool DisableStatCache;
=20
+  /// \brief When true, a PCH with compiler errors will not be rejected.
+  bool AllowPCHWithCompilerErrors;
+
   /// \brief Dump declarations that are deserialized from PCH, for testing.
   bool DumpDeserializedPCHDecls;
=20
@@ -166,9 +166,9 @@
  =20
 public:
   PreprocessorOptions() : UsePredefines(true), DetailedRecord(false),
-                          AutoModuleImport(false),
-                          DetailedRecordIncludesNestedMacroExpansions(true=
),
+                          DetailedRecordConditionalDirectives(false),
                           DisablePCHValidation(false), DisableStatCache(fa=
lse),
+                          AllowPCHWithCompilerErrors(false),
                           DumpDeserializedPCHDecls(false),
                           PrecompiledPreambleBytes(0, true),
                           RemappedFilesKeepOriginalName(true),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/TextDiagnosticPrinter.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/TextDiagnosticPr=
inter.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/TextDiagnosticPr=
inter.h	Tue Apr 17 11:51:51 2012 +0300
@@ -16,25 +16,28 @@
 #define LLVM_CLANG_FRONTEND_TEXT_DIAGNOSTIC_PRINTER_H_
=20
 #include "clang/Basic/Diagnostic.h"
-#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/OwningPtr.h"
=20
 namespace clang {
 class DiagnosticOptions;
 class LangOptions;
+class TextDiagnostic;
=20
 class TextDiagnosticPrinter : public DiagnosticConsumer {
   raw_ostream &OS;
   const LangOptions *LangOpts;
   const DiagnosticOptions *DiagOpts;
+  const SourceManager *SM;
=20
-  SourceLocation LastWarningLoc;
-  FullSourceLoc LastLoc;
-  unsigned LastCaretDiagnosticWasNote : 1;
-  unsigned OwnsOutputStream : 1;
+  /// \brief Handle to the currently active text diagnostic emitter.
+  OwningPtr<TextDiagnostic> TextDiag;
=20
   /// A string to prefix to error messages.
   std::string Prefix;
=20
+  unsigned OwnsOutputStream : 1;
+
 public:
   TextDiagnosticPrinter(raw_ostream &os, const DiagnosticOptions &diags,
                         bool OwnsOutputStream =3D false);
@@ -45,27 +48,10 @@
   /// used.
   void setPrefix(std::string Value) { Prefix =3D Value; }
=20
-  void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) {
-    LangOpts =3D &LO;
-  }
-
-  void EndSourceFile() {
-    LangOpts =3D 0;
-  }
-
-  void PrintIncludeStack(DiagnosticsEngine::Level Level, SourceLocation Lo=
c,
-                         const SourceManager &SM);
-
-  virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
-                                const Diagnostic &Info);
-
+  void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP);
+  void EndSourceFile();
+  void HandleDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &=
Info);
   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const;
-
-private:
-  void EmitDiagnosticLoc(DiagnosticsEngine::Level Level,
-                         const Diagnostic &Info,
-                         const SourceManager &SM,
-                         PresumedLoc PLoc);
 };
=20
 } // end namespace clang
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/Utils.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/Utils.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/Utils.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -15,13 +15,11 @@
 #define LLVM_CLANG_FRONTEND_UTILS_H
=20
 #include "clang/Basic/Diagnostic.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/ADT/ArrayRef.h"
-#include "llvm/ADT/IntrusiveRefCntPtr.h"
-#include "llvm/Support/raw_ostream.h"
-#include "clang/Basic/Diagnostic.h"
=20
 namespace llvm {
+class raw_fd_ostream;
 class Triple;
 }
=20
@@ -46,11 +44,6 @@
 class TargetInfo;
 class FrontendOptions;
=20
-/// Normalize \arg File for use in a user defined #include directive (in t=
he
-/// predefines buffer).
-std::string NormalizeDashIncludePath(StringRef File,
-                                     FileManager &FileMgr);
-
 /// Apply the header search options to get given HeaderSearch object.
 void ApplyHeaderSearchOptions(HeaderSearch &HS,
                               const HeaderSearchOptions &HSOpts,
@@ -66,7 +59,8 @@
=20
 /// ProcessWarningOptions - Initialize the diagnostic client and process t=
he
 /// warning options specified on the command line.
-void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptio=
ns &Opts);
+void ProcessWarningOptions(DiagnosticsEngine &Diags,
+                           const DiagnosticOptions &Opts);
=20
 /// DoPrintPreprocessedInput - Implement -E mode.
 void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream* OS,
@@ -77,6 +71,11 @@
 void AttachDependencyFileGen(Preprocessor &PP,
                              const DependencyOutputOptions &Opts);
=20
+/// AttachDependencyGraphGen - Create a dependency graph generator, and at=
tach
+/// it to the given preprocessor.
+  void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
+                                StringRef SysRoot);
+
 /// AttachHeaderIncludeGen - Create a header include list generator, and a=
ttach
 /// it to the given preprocessor.
 ///
@@ -101,8 +100,8 @@
 /// argument vector.
 CompilerInvocation *
 createInvocationFromCommandLine(ArrayRef<const char *> Args,
-                            llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Di=
ags =3D
-                                llvm::IntrusiveRefCntPtr<DiagnosticsEngine=
>());
+                            IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
=3D
+                                IntrusiveRefCntPtr<DiagnosticsEngine>());
=20
 }  // end namespace clang
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Frontend/VerifyDiagnosticConsumer.h
--- a/head/contrib/llvm/tools/clang/include/clang/Frontend/VerifyDiagnostic=
Consumer.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Frontend/VerifyDiagnostic=
Consumer.h	Tue Apr 17 11:51:51 2012 +0300
@@ -67,7 +67,7 @@
   DiagnosticsEngine &Diags;
   DiagnosticConsumer *PrimaryClient;
   bool OwnsPrimaryClient;
-  llvm::OwningPtr<TextDiagnosticBuffer> Buffer;
+  OwningPtr<TextDiagnosticBuffer> Buffer;
   Preprocessor *CurrentPreprocessor;
=20
 private:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Index/ASTLocation.h
--- a/head/contrib/llvm/tools/clang/include/clang/Index/ASTLocation.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Index/ASTLocation.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
=20
 #include "clang/AST/TypeLoc.h"
 #include "llvm/ADT/PointerIntPair.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
   class Decl;
@@ -42,7 +43,7 @@
   struct NamedRef {
     NamedDecl *ND;
     SourceLocation Loc;
-   =20
+
     NamedRef() : ND(0) { }
     NamedRef(NamedDecl *nd, SourceLocation loc) : ND(nd), Loc(loc) { }
   };
@@ -95,14 +96,14 @@
=20
   bool isValid() const { return ParentDecl.getPointer() !=3D 0; }
   bool isInvalid() const { return !isValid(); }
- =20
+
   NodeKind getKind() const {
     assert(isValid());
     return (NodeKind)ParentDecl.getInt();
   }
- =20
+
   Decl *getParentDecl() const { return ParentDecl.getPointer(); }
- =20
+
   Decl *AsDecl() const {
     assert(getKind() =3D=3D N_Decl);
     return D;
@@ -121,14 +122,16 @@
   }
=20
   Decl *dyn_AsDecl() const { return isValid() && getKind() =3D=3D N_Decl ?=
 D : 0; }
-  Stmt *dyn_AsStmt() const { return isValid() && getKind() =3D=3D N_Stmt ?=
 Stm : 0; }
+  Stmt *dyn_AsStmt() const {
+    return isValid() && getKind() =3D=3D N_Stmt ? Stm : 0;
+  }
   NamedRef dyn_AsNamedRef() const {
     return getKind() =3D=3D N_Type ? AsNamedRef() : NamedRef();
   }
   TypeLoc dyn_AsTypeLoc() const {
     return getKind() =3D=3D N_Type ? AsTypeLoc() : TypeLoc();
   }
- =20
+
   bool isDecl() const { return isValid() && getKind() =3D=3D N_Decl; }
   bool isStmt() const { return isValid() && getKind() =3D=3D N_Stmt; }
   bool isNamedRef() const { return isValid() && getKind() =3D=3D N_NamedRe=
f; }
@@ -144,7 +147,7 @@
     return const_cast<ASTLocation*>(this)->getReferencedDecl();
   }
=20
-  SourceRange getSourceRange() const;
+  SourceRange getSourceRange() const LLVM_READONLY;
=20
   void print(raw_ostream &OS) const;
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/DirectoryLookup.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/DirectoryLookup.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/DirectoryLookup.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,8 @@
 class DirectoryEntry;
 class FileEntry;
 class HeaderSearch;
-
+class Module;
+ =20
 /// DirectoryLookup - This class represents one entry in the search list t=
hat
 /// specifies the search order for directories in #include directives.  It
 /// represents either a directory, a framework, or a headermap.
@@ -141,24 +142,26 @@
   /// SearchPath at which the file was found. This only differs from the
   /// Filename for framework includes.
   ///
-  /// \param BuildingModule The name of the module we're currently buildin=
g.
+  /// \param SuggestedModule If non-null, and the file found is semantical=
ly
+  /// part of a known module, this will be set to the module that should
+  /// be imported instead of preprocessing/parsing the file found.
   ///
-  /// \param SuggestedModule If non-null, and the file found is semantical=
ly
-  /// part of a known module, this will be set to the name of the module t=
hat
-  /// could be imported instead of preprocessing/parsing the file found.
+  /// \param InUserSpecifiedSystemHeader [out] If the file is found, set t=
o true
+  /// if the file is located in a framework that has been user-specified t=
o be
+  /// treated as a system framework.
   const FileEntry *LookupFile(StringRef Filename, HeaderSearch &HS,
                               SmallVectorImpl<char> *SearchPath,
                               SmallVectorImpl<char> *RelativePath,
-                              StringRef BuildingModule,
-                              StringRef *SuggestedModule) const;
+                              Module **SuggestedModule,
+                              bool &InUserSpecifiedSystemHeader) const;
=20
 private:
   const FileEntry *DoFrameworkLookup(
       StringRef Filename, HeaderSearch &HS,
       SmallVectorImpl<char> *SearchPath,
       SmallVectorImpl<char> *RelativePath,
-      StringRef BuildingModule,
-      StringRef *SuggestedModule) const;
+      Module **SuggestedModule,
+      bool &InUserSpecifiedSystemHeader) const;
=20
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/ExternalPreprocessorSource.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/ExternalPreprocessorS=
ource.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/ExternalPreprocessorS=
ource.h	Tue Apr 17 11:51:51 2012 +0300
@@ -30,6 +30,9 @@
  =20
   /// \brief Read the definition for the given macro.
   virtual void LoadMacroDefinition(IdentifierInfo *II) =3D 0;
+ =20
+  /// \brief Update an out-of-date identifier.
+  virtual void updateOutOfDateIdentifier(IdentifierInfo &II) =3D 0;
 };
  =20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/HeaderSearch.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/HeaderSearch.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -15,13 +15,16 @@
 #define LLVM_CLANG_LEX_HEADERSEARCH_H
=20
 #include "clang/Lex/DirectoryLookup.h"
+#include "clang/Lex/ModuleMap.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Allocator.h"
+#include "llvm/ADT/OwningPtr.h"
 #include <vector>
=20
 namespace clang {
-
+ =20
+class DiagnosticsEngine; =20
 class ExternalIdentifierLookup;
 class FileEntry;
 class FileManager;
@@ -117,7 +120,19 @@
 /// HeaderSearch - This class encapsulates the information needed to find =
the
 /// file referenced by a #include or #include_next, (sub-)framework lookup=
, etc.
 class HeaderSearch {
+  /// This structure is used to record entries in our framework cache.
+  struct FrameworkCacheEntry {
+    /// The directory entry which should be used for the cached framework.
+    const DirectoryEntry *Directory;
+
+    /// Whether this framework has been "user-specified" to be treated as =
if it
+    /// were a system framework (even if it was found outside a system fra=
mework
+    /// directory).
+    bool IsUserSpecifiedSystemFramework;
+  };
+
   FileManager &FileMgr;
+  DiagnosticsEngine &Diags;
   /// #include search path information.  Requests for #include "x" search =
the
   /// directory of the #including file first, then each directory in Searc=
hDirs
   /// consecutively. Requests for <x> search the current dir first, then e=
ach
@@ -132,9 +147,6 @@
   /// \brief The path to the module cache.
   std::string ModuleCachePath;
  =20
-  /// \brief The name of the module we're building.
-  std::string BuildingModule;
- =20
   /// FileInfo - This contains all of the preprocessor-specific data about=
 files
   /// that are included.  The vector is indexed by the FileEntry's UID.
   ///
@@ -149,16 +161,27 @@
   llvm::StringMap<std::pair<unsigned, unsigned>, llvm::BumpPtrAllocator>
     LookupFileCache;
=20
-
   /// FrameworkMap - This is a collection mapping a framework or subframew=
ork
   /// name like "Carbon" to the Carbon.framework directory.
-  llvm::StringMap<const DirectoryEntry *, llvm::BumpPtrAllocator>
-    FrameworkMap;
+  llvm::StringMap<FrameworkCacheEntry, llvm::BumpPtrAllocator> FrameworkMa=
p;
+
+  /// IncludeAliases - maps include file names (including the quotes or
+  /// angle brackets) to other include file names.  This is used to suppor=
t the
+  /// include_alias pragma for Microsoft compatibility.
+  typedef llvm::StringMap<std::string, llvm::BumpPtrAllocator>
+    IncludeAliasMap;
+  OwningPtr<IncludeAliasMap> IncludeAliases;
=20
   /// HeaderMaps - This is a mapping from FileEntry -> HeaderMap, uniquing
   /// headermaps.  This vector owns the headermap.
   std::vector<std::pair<const FileEntry*, const HeaderMap*> > HeaderMaps;
=20
+  /// \brief The mapping between modules and headers.
+  ModuleMap ModMap;
+ =20
+  /// \brief Describes whether a given directory has a module map in it.
+  llvm::DenseMap<const DirectoryEntry *, bool> DirectoryHasModuleMap;
+ =20
   /// \brief Uniqued set of framework names, which is used to track which=20
   /// headers were included as framework headers.
   llvm::StringSet<llvm::BumpPtrAllocator> FrameworkNames;
@@ -179,8 +202,12 @@
   explicit HeaderSearch();
   explicit HeaderSearch(const HeaderSearch&);
   void operator=3D(const HeaderSearch&);
+ =20
+  friend class DirectoryLookup;
+ =20
 public:
-  HeaderSearch(FileManager &FM);
+  HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags,
+               const LangOptions &LangOpts, const TargetInfo *Target);
   ~HeaderSearch();
=20
   FileManager &getFileMgr() const { return FileMgr; }
@@ -199,13 +226,51 @@
     //LookupFileCache.clear();
   }
=20
-  /// \brief Set the path to the module cache and the name of the module
-  /// we're building
-  void configureModules(StringRef CachePath, StringRef BuildingModule) {
+  /// AddSearchPath - Add an additional search path.
+  void AddSearchPath(const DirectoryLookup &dir, bool isAngled) {
+    unsigned idx =3D isAngled ? SystemDirIdx : AngledDirIdx;
+    SearchDirs.insert(SearchDirs.begin() + idx, dir);
+    if (!isAngled)
+      AngledDirIdx++;
+    SystemDirIdx++;
+  }
+
+  /// HasIncludeAliasMap - Checks whether the map exists or not
+  bool HasIncludeAliasMap() const {
+    return IncludeAliases;
+  }
+
+  /// AddIncludeAlias - Map the source include name to the dest include na=
me.
+  /// The Source should include the angle brackets or quotes, the dest=20
+  /// should not.  This allows for distinction between <> and "" headers.
+  void AddIncludeAlias(StringRef Source, StringRef Dest) {
+    if (!IncludeAliases)
+      IncludeAliases.reset(new IncludeAliasMap);
+    (*IncludeAliases)[Source] =3D Dest;
+  }
+
+  /// MapHeaderToIncludeAlias - Maps one header file name to a different h=
eader
+  /// file name, for use with the include_alias pragma.  Note that the sou=
rce
+  /// file name should include the angle brackets or quotes.  Returns Stri=
ngRef
+  /// as null if the header cannot be mapped.
+  StringRef MapHeaderToIncludeAlias(StringRef Source) {
+    assert(IncludeAliases && "Trying to map headers when there's no map");
+
+    // Do any filename replacements before anything else
+    IncludeAliasMap::const_iterator Iter =3D IncludeAliases->find(Source);
+    if (Iter !=3D IncludeAliases->end())
+      return Iter->second;
+    return StringRef();
+  }
+
+  /// \brief Set the path to the module cache.
+  void setModuleCachePath(StringRef CachePath) {
     ModuleCachePath =3D CachePath;
-    this->BuildingModule =3D BuildingModule;
   }
  =20
+  /// \brief Retrieve the path to the module cache.
+  StringRef getModuleCachePath() const { return ModuleCachePath; }
+ =20
   /// ClearFileInfo - Forget everything we know about headers so far.
   void ClearFileInfo() {
     FileInfo.clear();
@@ -224,6 +289,10 @@
     ExternalSource =3D ES;
   }
  =20
+  /// \brief Set the target information for the header search, if not
+  /// already known.
+  void setTarget(const TargetInfo &Target);
+ =20
   /// LookupFile - Given a "foo" or <foo> reference, look up the indicated=
 file,
   /// return null on failure.
   ///
@@ -247,15 +316,16 @@
   /// Filename for framework includes.
   ///
   /// \param SuggestedModule If non-null, and the file found is semantical=
ly
-  /// part of a known module, this will be set to the name of the module t=
hat
-  /// could be imported instead of preprocessing/parsing the file found.
+  /// part of a known module, this will be set to the module that should
+  /// be imported instead of preprocessing/parsing the file found.
   const FileEntry *LookupFile(StringRef Filename, bool isAngled,
                               const DirectoryLookup *FromDir,
                               const DirectoryLookup *&CurDir,
                               const FileEntry *CurFileEnt,
                               SmallVectorImpl<char> *SearchPath,
                               SmallVectorImpl<char> *RelativePath,
-                              StringRef *SuggestedModule);
+                              Module **SuggestedModule,
+                              bool SkipCache =3D false);
=20
   /// LookupSubframeworkHeader - Look up a subframework for the specified
   /// #include file.  For example, if #include'ing <HIToolbox/HIToolbox.h>=
 from
@@ -271,7 +341,7 @@
   /// LookupFrameworkCache - Look up the specified framework name in our
   /// framework cache, returning the DirectoryEntry it is in if we know,
   /// otherwise, return null.
-  const DirectoryEntry *&LookupFrameworkCache(StringRef FWName) {
+  FrameworkCacheEntry &LookupFrameworkCache(StringRef FWName) {
     return FrameworkMap.GetOrCreateValue(FWName).getValue();
   }
=20
@@ -326,33 +396,96 @@
   /// FileEntry, uniquing them through the the 'HeaderMaps' datastructure.
   const HeaderMap *CreateHeaderMap(const FileEntry *FE);
=20
-  /// \brief Search in the module cache path for a module with the given
-  /// name.
+  /// \brief Retrieve the name of the module file that should be used to=20
+  /// load the given module.
   ///
-  /// \param If non-NULL, will be set to the module file name we expected =
to
-  /// find (regardless of whether it was actually found or not).
+  /// \param Module The module whose module file name will be returned.
   ///
-  /// \param UmbrellaHeader If non-NULL, and no module was found in the mo=
dule
-  /// cache, this routine will search in the framework paths to determine
-  /// whether a module can be built from an umbrella header. If so, the po=
intee
-  /// will be set to the path of the umbrella header.
+  /// \returns The name of the module file that corresponds to this module,
+  /// or an empty string if this module does not correspond to any module =
file.
+  std::string getModuleFileName(Module *Module);
+
+  /// \brief Retrieve the name of the module file that should be used to=20
+  /// load a module with the given name.
   ///
-  /// \returns A file describing the named module, if available, or NULL to
-  /// indicate that the module could not be found.
-  const FileEntry *lookupModule(StringRef ModuleName,
-                                std::string *ModuleFileName =3D 0,
-                                std::string *UmbrellaHeader =3D 0);
+  /// \param Module The module whose module file name will be returned.
+  ///
+  /// \returns The name of the module file that corresponds to this module,
+  /// or an empty string if this module does not correspond to any module =
file.
+  std::string getModuleFileName(StringRef ModuleName);
+
+  /// \brief Lookup a module Search for a module with the given name.
+  ///
+  /// \param ModuleName The name of the module we're looking for.
+  ///
+  /// \param AllowSearch Whether we are allowed to search in the various
+  /// search directories to produce a module definition. If not, this look=
up
+  /// will only return an already-known module.
+  ///
+  /// \returns The module with the given name.
+  Module *lookupModule(StringRef ModuleName, bool AllowSearch =3D true);
  =20
   void IncrementFrameworkLookupCount() { ++NumFrameworkLookups; }
=20
-  typedef std::vector<HeaderFileInfo>::const_iterator header_file_iterator;
-  header_file_iterator header_file_begin() const { return FileInfo.begin()=
; }
-  header_file_iterator header_file_end() const { return FileInfo.end(); }
+  /// \brief Determine whether there is a module map that may map the head=
er
+  /// with the given file name to a (sub)module.
+  ///
+  /// \param Filename The name of the file.
+  ///
+  /// \param Root The "root" directory, at which we should stop looking for
+  /// module maps.
+  bool hasModuleMap(StringRef Filename, const DirectoryEntry *Root);
+ =20
+  /// \brief Retrieve the module that corresponds to the given file, if an=
y.
+  ///
+  /// \param File The header that we wish to map to a module.
+  Module *findModuleForHeader(const FileEntry *File);
+ =20
+  /// \brief Read the contents of the given module map file.
+  ///
+  /// \param File The module map file.
+  ///
+  /// \param OnlyModule If non-NULL, this will receive the=20
+  ///
+  /// \returns true if an error occurred, false otherwise.
+  bool loadModuleMapFile(const FileEntry *File);
+
+  /// \brief Collect the set of all known, top-level modules.
+  ///
+  /// \param Modules Will be filled with the set of known, top-level modul=
es.
+  void collectAllModules(llvm::SmallVectorImpl<Module *> &Modules);
+                        =20
+private:
+  /// \brief Retrieve a module with the given name, which may be part of t=
he
+  /// given framework.
+  ///
+  /// \param Name The name of the module to retrieve.
+  ///
+  /// \param Dir The framework directory (e.g., ModuleName.framework).
+  ///
+  /// \param IsSystem Whether the framework directory is part of the system
+  /// frameworks.
+  ///
+  /// \returns The module, if found; otherwise, null.
+  Module *loadFrameworkModule(StringRef Name,=20
+                              const DirectoryEntry *Dir,
+                              bool IsSystem);
+ =20
+public:
+  /// \brief Retrieve the module map.
+  ModuleMap &getModuleMap() { return ModMap; }
+ =20
   unsigned header_file_size() const { return FileInfo.size(); }
=20
   // Used by ASTReader.
   void setHeaderFileInfoForUID(HeaderFileInfo HFI, unsigned UID);
=20
+  /// getFileInfo - Return the HeaderFileInfo structure for the specified
+  /// FileEntry.
+  const HeaderFileInfo &getFileInfo(const FileEntry *FE) const {
+    return const_cast<HeaderSearch*>(this)->getFileInfo(FE);
+  }
+
   // Used by external tools
   typedef std::vector<DirectoryLookup>::const_iterator search_dir_iterator;
   search_dir_iterator search_dir_begin() const { return SearchDirs.begin()=
; }
@@ -385,7 +518,39 @@
  =20
   size_t getTotalMemory() const;
=20
+  static std::string NormalizeDashIncludePath(StringRef File,
+                                              FileManager &FileMgr);
+
 private:
+  /// \brief Describes what happened when we tried to load a module map fi=
le.
+  enum LoadModuleMapResult {
+    /// \brief The module map file had already been loaded.
+    LMM_AlreadyLoaded,
+    /// \brief The module map file was loaded by this invocation.
+    LMM_NewlyLoaded,
+    /// \brief There is was directory with the given name.
+    LMM_NoDirectory,
+    /// \brief There was either no module map file or the module map file =
was
+    /// invalid.
+    LMM_InvalidModuleMap
+  };
+ =20
+  /// \brief Try to load the module map file in the given directory.
+  ///
+  /// \param DirName The name of the directory where we will look for a mo=
dule
+  /// map file.
+  ///
+  /// \returns The result of attempting to load the module map file from t=
he
+  /// named directory.
+  LoadModuleMapResult loadModuleMapFile(StringRef DirName);
+
+  /// \brief Try to load the module map file in the given directory.
+  ///
+  /// \param Dir The directory where we will look for a module map file.
+  ///
+  /// \returns The result of attempting to load the module map file from t=
he
+  /// named directory.
+  LoadModuleMapResult loadModuleMapFile(const DirectoryEntry *Dir);
=20
   /// getFileInfo - Return the HeaderFileInfo structure for the specified
   /// FileEntry.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/LexDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/LexDiagnostic.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/LexDiagnostic.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
   namespace diag {
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
 #define LEXSTART
 #include "clang/Basic/DiagnosticLexKinds.inc"
 #undef DIAG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/Lexer.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/Lexer.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/Lexer.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -44,12 +44,14 @@
 /// or buffering/seeking of tokens, only forward lexing is supported.  It =
relies
 /// on the specified Preprocessor object to handle preprocessor directives=
, etc.
 class Lexer : public PreprocessorLexer {
+  virtual void anchor();
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Constant configuration values for this lexer.
   const char *BufferStart;       // Start of the buffer.
   const char *BufferEnd;         // End of the buffer.
   SourceLocation FileLoc;        // Location for start of file.
-  LangOptions Features;          // Features enabled by this language (cac=
he).
+  LangOptions LangOpts;          // LangOpts enabled by this language (cac=
he).
   bool Is_PragmaLexer;           // True if lexer for _Pragma handling.
  =20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
@@ -97,14 +99,14 @@
   /// Lexer constructor - Create a new raw lexer object.  This object is o=
nly
   /// suitable for calls to 'LexRawToken'.  This lexer assumes that the te=
xt
   /// range will outlive it, so it doesn't take ownership of it.
-  Lexer(SourceLocation FileLoc, const LangOptions &Features,
+  Lexer(SourceLocation FileLoc, const LangOptions &LangOpts,
         const char *BufStart, const char *BufPtr, const char *BufEnd);
=20
   /// Lexer constructor - Create a new raw lexer object.  This object is o=
nly
   /// suitable for calls to 'LexRawToken'.  This lexer assumes that the te=
xt
   /// range will outlive it, so it doesn't take ownership of it.
   Lexer(FileID FID, const llvm::MemoryBuffer *InputBuffer,
-        const SourceManager &SM, const LangOptions &Features);
+        const SourceManager &SM, const LangOptions &LangOpts);
=20
   /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
   /// _Pragma expansion.  This has a variety of magic semantics that this =
method
@@ -115,9 +117,9 @@
                                    unsigned TokLen, Preprocessor &PP);
=20
=20
-  /// getFeatures - Return the language features currently enabled.  NOTE:=
 this
-  /// lexer modifies features as a file is parsed!
-  const LangOptions &getFeatures() const { return Features; }
+  /// getLangOpts - Return the language features currently enabled.
+  /// NOTE: this lexer modifies features as a file is parsed!
+  const LangOptions &getLangOpts() const { return LangOpts; }
=20
   /// getFileLoc - Return the File Location for the file we are lexing out=
 of.
   /// The physical location encodes the location where the characters come=
 from,
@@ -238,7 +240,7 @@
   /// if an internal buffer is returned.
   static unsigned getSpelling(const Token &Tok, const char *&Buffer,=20
                               const SourceManager &SourceMgr,
-                              const LangOptions &Features,
+                              const LangOptions &LangOpts,
                               bool *Invalid =3D 0);
  =20
   /// getSpelling() - Return the 'spelling' of the Tok token.  The spellin=
g of a
@@ -248,7 +250,7 @@
   /// UCNs, etc.
   static std::string getSpelling(const Token &Tok,
                                  const SourceManager &SourceMgr,
-                                 const LangOptions &Features,=20
+                                 const LangOptions &LangOpts,=20
                                  bool *Invalid =3D 0);
=20
   /// getSpelling - This method is used to get the spelling of the
@@ -262,7 +264,7 @@
   static StringRef getSpelling(SourceLocation loc,
                                      SmallVectorImpl<char> &buffer,
                                      const SourceManager &SourceMgr,
-                                     const LangOptions &Features,
+                                     const LangOptions &LangOpts,
                                      bool *invalid =3D 0);
  =20
   /// MeasureTokenLength - Relex the token at the specified location and r=
eturn
@@ -288,7 +290,7 @@
   static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
                                                 unsigned Character,
                                                 const SourceManager &SM,
-                                                const LangOptions &Feature=
s);
+                                                const LangOptions &LangOpt=
s);
  =20
   /// \brief Computes the source location just past the end of the
   /// token at this source location.
@@ -307,19 +309,52 @@
   /// a source location pointing to the last character in the token, etc.
   static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned O=
ffset,
                                             const SourceManager &SM,
-                                            const LangOptions &Features);
+                                            const LangOptions &LangOpts);
=20
   /// \brief Returns true if the given MacroID location points at the first
   /// token of the macro expansion.
+  ///
+  /// \param MacroBegin If non-null and function returns true, it is set to
+  /// begin location of the macro.
   static bool isAtStartOfMacroExpansion(SourceLocation loc,
-                                            const SourceManager &SM,
-                                            const LangOptions &LangOpts);
+                                        const SourceManager &SM,
+                                        const LangOptions &LangOpts,
+                                        SourceLocation *MacroBegin =3D 0);
=20
   /// \brief Returns true if the given MacroID location points at the last
   /// token of the macro expansion.
+  ///
+  /// \param MacroBegin If non-null and function returns true, it is set to
+  /// end location of the macro.
   static bool isAtEndOfMacroExpansion(SourceLocation loc,
-                                          const SourceManager &SM,
-                                          const LangOptions &LangOpts);
+                                      const SourceManager &SM,
+                                      const LangOptions &LangOpts,
+                                      SourceLocation *MacroEnd =3D 0);
+
+  /// \brief Accepts a range and returns a character range with file locat=
ions.
+  ///
+  /// Returns a null range if a part of the range resides inside a macro
+  /// expansion or the range does not reside on the same FileID.
+  static CharSourceRange makeFileCharRange(CharSourceRange Range,
+                                           const SourceManager &SM,
+                                           const LangOptions &LangOpts);
+
+  /// \brief Returns a string for the source that the range encompasses.
+  static StringRef getSourceText(CharSourceRange Range,
+                                 const SourceManager &SM,
+                                 const LangOptions &LangOpts,
+                                 bool *Invalid =3D 0);
+
+  /// \brief Retrieve the name of the immediate macro expansion.
+  ///
+  /// This routine starts from a source location, and finds the name of th=
e macro
+  /// responsible for its immediate expansion. It looks through any interv=
ening
+  /// macro argument expansions to compute this. It returns a StringRef wh=
ich
+  /// refers to the SourceManager-owned buffer of the source where that ma=
cro
+  /// name is spelled. Thus, the result shouldn't out-live that SourceMana=
ger.
+  static StringRef getImmediateMacroName(SourceLocation Loc,
+                                         const SourceManager &SM,
+                                         const LangOptions &LangOpts);
=20
   /// \brief Compute the preamble of the given file.
   ///
@@ -337,7 +372,7 @@
   /// of the file begins along with a boolean value indicating whether=20
   /// the preamble ends at the beginning of a new line.
   static std::pair<unsigned, bool>
-  ComputePreamble(const llvm::MemoryBuffer *Buffer, const LangOptions &Fea=
tures,
+  ComputePreamble(const llvm::MemoryBuffer *Buffer, const LangOptions &Lan=
gOpts,
                   unsigned MaxLines =3D 0);
                                        =20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
@@ -451,7 +486,7 @@
   /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not =
ever
   /// emit a warning.
   static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
-                                          const LangOptions &Features) {
+                                          const LangOptions &LangOpts) {
     // If this is not a trigraph and not a UCN or escaped newline, return
     // quickly.
     if (isObviouslySimpleCharacter(Ptr[0])) {
@@ -460,7 +495,7 @@
     }
=20
     Size =3D 0;
-    return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
+    return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
   }
=20
   /// getEscapedNewLineSize - Return the size of the specified escaped new=
line,
@@ -489,12 +524,14 @@
   /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emi=
ts a
   /// diagnostic.
   static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
-                                       const LangOptions &Features);
+                                       const LangOptions &LangOpts);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Other lexer functions.
=20
   void SkipBytes(unsigned Bytes, bool StartOfLine);
+
+  const char *LexUDSuffix(Token &Result, const char *CurPtr);
  =20
   // Helper functions to lex the remainder of a token of the specific type.
   void LexIdentifier         (Token &Result, const char *CurPtr);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/LiteralSupport.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/LiteralSupport.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/LiteralSupport.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -45,7 +45,7 @@
=20
   unsigned radix;
=20
-  bool saw_exponent, saw_period;
+  bool saw_exponent, saw_period, saw_ud_suffix;
=20
 public:
   NumericLiteralParser(const char *begin, const char *end,
@@ -64,8 +64,17 @@
   bool isFloatingLiteral() const {
     return saw_period || saw_exponent;
   }
-  bool hasSuffix() const {
-    return SuffixBegin !=3D ThisTokEnd;
+
+  bool hasUDSuffix() const {
+    return saw_ud_suffix;
+  }
+  StringRef getUDSuffix() const {
+    assert(saw_ud_suffix);
+    return StringRef(SuffixBegin, ThisTokEnd - SuffixBegin);
+  }
+  unsigned getUDSuffixOffset() const {
+    assert(saw_ud_suffix);
+    return SuffixBegin - ThisTokBegin;
   }
=20
   unsigned getRadix() const { return radix; }
@@ -128,6 +137,8 @@
   tok::TokenKind Kind;
   bool IsMultiChar;
   bool HadError;
+  SmallString<32> UDSuffixBuf;
+  unsigned UDSuffixOffset;
 public:
   CharLiteralParser(const char *begin, const char *end,
                     SourceLocation Loc, Preprocessor &PP,
@@ -140,6 +151,11 @@
   bool isUTF32() const { return Kind =3D=3D tok::utf32_char_constant; }
   bool isMultiChar() const { return IsMultiChar; }
   uint64_t getValue() const { return Value; }
+  StringRef getUDSuffix() const { return UDSuffixBuf; }
+  unsigned getUDSuffixOffset() const {
+    assert(!UDSuffixBuf.empty() && "no ud-suffix");
+    return UDSuffixOffset;
+  }
 };
=20
 /// StringLiteralParser - This decodes string escape characters and perfor=
ms
@@ -155,8 +171,11 @@
   unsigned SizeBound;
   unsigned CharByteWidth;
   tok::TokenKind Kind;
-  llvm::SmallString<512> ResultBuf;
+  SmallString<512> ResultBuf;
   char *ResultPtr; // cursor
+  SmallString<32> UDSuffixBuf;
+  unsigned UDSuffixToken;
+  unsigned UDSuffixOffset;
 public:
   StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
                       Preprocessor &PP, bool Complain =3D true);
@@ -189,15 +208,30 @@
   /// checking of the string literal and emit errors and warnings.
   unsigned getOffsetOfStringByte(const Token &TheTok, unsigned ByteNo) con=
st;
=20
-  bool isAscii() { return Kind =3D=3D tok::string_literal; }
-  bool isWide() { return Kind =3D=3D tok::wide_string_literal; }
-  bool isUTF8() { return Kind =3D=3D tok::utf8_string_literal; }
-  bool isUTF16() { return Kind =3D=3D tok::utf16_string_literal; }
-  bool isUTF32() { return Kind =3D=3D tok::utf32_string_literal; }
+  bool isAscii() const { return Kind =3D=3D tok::string_literal; }
+  bool isWide() const { return Kind =3D=3D tok::wide_string_literal; }
+  bool isUTF8() const { return Kind =3D=3D tok::utf8_string_literal; }
+  bool isUTF16() const { return Kind =3D=3D tok::utf16_string_literal; }
+  bool isUTF32() const { return Kind =3D=3D tok::utf32_string_literal; }
+  bool isPascal() const { return Pascal; }
+
+  StringRef getUDSuffix() const { return UDSuffixBuf; }
+
+  /// Get the index of a token containing a ud-suffix.
+  unsigned getUDSuffixToken() const {
+    assert(!UDSuffixBuf.empty() && "no ud-suffix");
+    return UDSuffixToken;
+  }
+  /// Get the spelling offset of the first byte of the ud-suffix.
+  unsigned getUDSuffixOffset() const {
+    assert(!UDSuffixBuf.empty() && "no ud-suffix");
+    return UDSuffixOffset;
+  }
=20
 private:
   void init(const Token *StringToks, unsigned NumStringToks);
-  void CopyStringFragment(StringRef Fragment);
+  bool CopyStringFragment(StringRef Fragment);
+  bool DiagnoseBadString(const Token& Tok);
 };
=20
 }  // end namespace clang
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/MacroInfo.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/MacroInfo.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/MacroInfo.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -39,10 +39,11 @@
   IdentifierInfo **ArgumentList;
   unsigned NumArguments;
=20
-  /// \brief The location at which this macro was exported from its module.
+  /// \brief The location at which this macro was either explicitly export=
ed
+  /// from its module or marked as private.
   ///
-  /// If invalid, this macro has not been explicitly exported.
-  SourceLocation ExportLocation;
+  /// If invalid, this macro has not been explicitly given any visibility.
+  SourceLocation VisibilityLocation;
  =20
   /// ReplacementTokens - This is the list of tokens that the macro is def=
ined
   /// to.
@@ -97,6 +98,9 @@
   /// \brief Must warn if the macro is unused at the end of translation un=
it.
   bool IsWarnIfUnused : 1;
   =20
+  /// \brief Whether the macro has public (when described in a module).
+  bool IsPublic : 1;
+ =20
    ~MacroInfo() {
     assert(ArgumentList =3D=3D 0 && "Didn't call destroy before dtor!");
   }
@@ -279,17 +283,18 @@
   }
=20
   /// \brief Set the export location for this macro.
-  void setExportLocation(SourceLocation ExportLoc) {
-    ExportLocation =3D ExportLoc;
+  void setVisibility(bool Public, SourceLocation Loc) {
+    VisibilityLocation =3D Loc;
+    IsPublic =3D Public;
   }
=20
-  /// \brief Determine whether this macro was explicitly exported from its
+  /// \brief Determine whether this macro is part of the public API of its
   /// module.
-  bool isExported() const { return ExportLocation.isValid(); }
+  bool isPublic() const { return IsPublic; }
  =20
-  /// \brief Determine the location where this macro was explicitly export=
ed
-  /// from its module.
-  SourceLocation getExportLocation() { return ExportLocation; }
+  /// \brief Determine the location where this macro was explicitly made
+  /// public or private within its module.
+  SourceLocation getVisibilityLocation() { return VisibilityLocation; }
  =20
 private:
   unsigned getDefinitionLengthSlow(SourceManager &SM) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/ModuleLoader.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/ModuleLoader.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/ModuleLoader.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -14,15 +14,18 @@
 #ifndef LLVM_CLANG_LEX_MODULE_LOADER_H
 #define LLVM_CLANG_LEX_MODULE_LOADER_H
=20
+#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/ArrayRef.h"
=20
 namespace clang {
=20
 class IdentifierInfo;
  =20
-/// \brief An opaque key that is used to describe the module and can be=20
-/// interpreted by the module loader itself.
-typedef void *ModuleKey;
+/// \brief A sequence of identifier/location pairs used to describe a part=
icular
+/// module or submodule, e.g., std.vector.
+typedef llvm::ArrayRef<std::pair<IdentifierInfo*, SourceLocation> >=20
+  ModuleIdPath;
  =20
 /// \brief Abstract interface for a module loader.
 ///
@@ -39,15 +42,22 @@
   /// parameters.
   ///
   /// \param ImportLoc The location of the 'import' keyword.
-  /// \param ModuleName The name of the module to be loaded.
-  /// \param ModuleNameLoc The location of the module name.
   ///
-  /// \returns If successful, a non-NULL module key describing this module.
-  /// Otherwise, returns NULL to indicate that the module could not be
-  /// loaded.
-  virtual ModuleKey loadModule(SourceLocation ImportLoc,=20
-                               IdentifierInfo &ModuleName,
-                               SourceLocation ModuleNameLoc) =3D 0;
+  /// \param Path The identifiers (and their locations) of the module
+  /// "path", e.g., "std.vector" would be split into "std" and "vector".
+  ///=20
+  /// \param Visibility The visibility provided for the names in the loaded
+  /// module.
+  ///
+  /// \param IsInclusionDirective Indicates that this module is being load=
ed
+  /// implicitly, due to the presence of an inclusion directive. Otherwise,
+  /// it is being loaded due to an import declaration.
+  ///
+  /// \returns If successful, returns the loaded module. Otherwise, return=
s=20
+  /// NULL to indicate that the module could not be loaded.
+  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
+                             Module::NameVisibilityKind Visibility,
+                             bool IsInclusionDirective) =3D 0;
 };
  =20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/PPCallbacks.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/PPCallbacks.h	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/PPCallbacks.h	Tue Apr=
 17 11:51:51 2012 +0300
@@ -58,6 +58,23 @@
                            SrcMgr::CharacteristicKind FileType) {
   }
=20
+  /// FileNotFound - This callback is invoked whenever an inclusion direct=
ive
+  /// results in a file-not-found error.
+  ///
+  /// \param FileName The name of the file being included, as written in t=
he=20
+  /// source code.
+  ///
+  /// \param RecoveryPath If this client indicates that it can recover fro=
m=20
+  /// this missing file, the client should set this as an additional header
+  /// search patch.
+  ///
+  /// \returns true to indicate that the preprocessor should attempt to re=
cover
+  /// by adding \p RecoveryPath as a header search path.
+  virtual bool FileNotFound(StringRef FileName,
+                            SmallVectorImpl<char> &RecoveryPath) {
+    return false;
+  }
+
   /// \brief This callback is invoked whenever an inclusion directive of
   /// any kind (\c #include, \c #import, etc.) has been processed, regardl=
ess
   /// of whether the inclusion will actually result in an inclusion.
@@ -173,40 +190,49 @@
   }
=20
   /// If -- This hook is called whenever an #if is seen.
-  /// \param Range The SourceRange of the expression being tested.
+  /// \param Loc the source location of the directive.
+  /// \param ConditionRange The SourceRange of the expression being tested.
   // FIXME: better to pass in a list (or tree!) of Tokens.
-  virtual void If(SourceRange Range) {
+  virtual void If(SourceLocation Loc, SourceRange ConditionRange) {
   }
=20
   /// Elif -- This hook is called whenever an #elif is seen.
-  /// \param Range The SourceRange of the expression being tested.
+  /// \param Loc the source location of the directive.
+  /// \param ConditionRange The SourceRange of the expression being tested.
+  /// \param IfLoc the source location of the #if/#ifdef/#ifndef directive.
   // FIXME: better to pass in a list (or tree!) of Tokens.
-  virtual void Elif(SourceRange Range) {
+  virtual void Elif(SourceLocation Loc, SourceRange ConditionRange,
+                    SourceLocation IfLoc) {
   }
=20
   /// Ifdef -- This hook is called whenever an #ifdef is seen.
-  /// \param Loc The location of the token being tested.
+  /// \param Loc the source location of the directive.
   /// \param II Information on the token being tested.
-  virtual void Ifdef(const Token &MacroNameTok) {
+  virtual void Ifdef(SourceLocation Loc, const Token &MacroNameTok) {
   }
=20
   /// Ifndef -- This hook is called whenever an #ifndef is seen.
-  /// \param Loc The location of the token being tested.
+  /// \param Loc the source location of the directive.
   /// \param II Information on the token being tested.
-  virtual void Ifndef(const Token &MacroNameTok) {
+  virtual void Ifndef(SourceLocation Loc, const Token &MacroNameTok) {
   }
=20
   /// Else -- This hook is called whenever an #else is seen.
-  virtual void Else() {
+  /// \param Loc the source location of the directive.
+  /// \param IfLoc the source location of the #if/#ifdef/#ifndef directive.
+  virtual void Else(SourceLocation Loc, SourceLocation IfLoc) {
   }
=20
   /// Endif -- This hook is called whenever an #endif is seen.
-  virtual void Endif() {
+  /// \param Loc the source location of the directive.
+  /// \param IfLoc the source location of the #if/#ifdef/#ifndef directive.
+  virtual void Endif(SourceLocation Loc, SourceLocation IfLoc) {
   }
 };
=20
 /// PPChainedCallbacks - Simple wrapper class for chaining callbacks.
 class PPChainedCallbacks : public PPCallbacks {
+  virtual void anchor();
   PPCallbacks *First, *Second;
=20
 public:
@@ -231,6 +257,12 @@
     Second->FileSkipped(ParentFile, FilenameTok, FileType);
   }
=20
+  virtual bool FileNotFound(StringRef FileName,
+                            SmallVectorImpl<char> &RecoveryPath) {
+    return First->FileNotFound(FileName, RecoveryPath) ||
+           Second->FileNotFound(FileName, RecoveryPath);
+  }
+
   virtual void InclusionDirective(SourceLocation HashLoc,
                                   const Token &IncludeTok,
                                   StringRef FileName,
@@ -311,39 +343,40 @@
   }
=20
   /// If -- This hook is called whenever an #if is seen.
-  virtual void If(SourceRange Range) {
-    First->If(Range);
-    Second->If(Range);
+  virtual void If(SourceLocation Loc, SourceRange ConditionRange) {
+    First->If(Loc, ConditionRange);
+    Second->If(Loc, ConditionRange);
   }
=20
   /// Elif -- This hook is called whenever an #if is seen.
-  virtual void Elif(SourceRange Range) {
-    First->Elif(Range);
-    Second->Elif(Range);
+  virtual void Elif(SourceLocation Loc, SourceRange ConditionRange,
+                    SourceLocation IfLoc) {
+    First->Elif(Loc, ConditionRange, IfLoc);
+    Second->Elif(Loc, ConditionRange, IfLoc);
   }
=20
   /// Ifdef -- This hook is called whenever an #ifdef is seen.
-  virtual void Ifdef(const Token &MacroNameTok) {
-    First->Ifdef(MacroNameTok);
-    Second->Ifdef(MacroNameTok);
+  virtual void Ifdef(SourceLocation Loc, const Token &MacroNameTok) {
+    First->Ifdef(Loc, MacroNameTok);
+    Second->Ifdef(Loc, MacroNameTok);
   }
=20
   /// Ifndef -- This hook is called whenever an #ifndef is seen.
-  virtual void Ifndef(const Token &MacroNameTok) {
-    First->Ifndef(MacroNameTok);
-    Second->Ifndef(MacroNameTok);
+  virtual void Ifndef(SourceLocation Loc, const Token &MacroNameTok) {
+    First->Ifndef(Loc, MacroNameTok);
+    Second->Ifndef(Loc, MacroNameTok);
   }
=20
   /// Else -- This hook is called whenever an #else is seen.
-  virtual void Else() {
-    First->Else();
-    Second->Else();
+  virtual void Else(SourceLocation Loc, SourceLocation IfLoc) {
+    First->Else(Loc, IfLoc);
+    Second->Else(Loc, IfLoc);
   }
=20
   /// Endif -- This hook is called whenever an #endif is seen.
-  virtual void Endif() {
-    First->Endif();
-    Second->Endif();
+  virtual void Endif(SourceLocation Loc, SourceLocation IfLoc) {
+    First->Endif(Loc, IfLoc);
+    Second->Endif(Loc, IfLoc);
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/PreprocessingRecord.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/PreprocessingRecord.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/PreprocessingRecord.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -17,8 +17,11 @@
 #include "clang/Lex/PPCallbacks.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Optional.h"
 #include "llvm/Support/Allocator.h"
+#include "llvm/Support/Compiler.h"
 #include <vector>
=20
 namespace clang {
@@ -85,7 +88,7 @@
    =20
     /// \brief Retrieve the source range that covers this entire preproces=
sed=20
     /// entity.
-    SourceRange getSourceRange() const { return Range; }
+    SourceRange getSourceRange() const LLVM_READONLY { return Range; }
=20
     /// \brief Returns true if there was a problem loading the preprocessed
     /// entity.
@@ -269,6 +272,13 @@
     /// preprocessed entities that \arg Range encompasses.
     virtual std::pair<unsigned, unsigned>
         findPreprocessedEntitiesInRange(SourceRange Range) =3D 0;
+
+    /// \brief Optionally returns true or false if the preallocated prepro=
cessed
+    /// entity with index \arg Index came from file \arg FID.
+    virtual llvm::Optional<bool> isPreprocessedEntityInFileID(unsigned Ind=
ex,
+                                                              FileID FID) {
+      return llvm::Optional<bool>();
+    }
   };
  =20
   /// \brief A record of the steps taken while preprocessing a source file,
@@ -276,10 +286,6 @@
   /// expanded, etc.
   class PreprocessingRecord : public PPCallbacks {
     SourceManager &SourceMgr;
-
-    /// \brief Whether we should include nested macro expansions in
-    /// the preprocessing record.
-    bool IncludeNestedMacroExpansions;
    =20
     /// \brief Allocator used to store preprocessing objects.
     llvm::BumpPtrAllocator BumpAlloc;
@@ -295,6 +301,44 @@
     /// and are referenced by the iterator using negative indices.
     std::vector<PreprocessedEntity *> LoadedPreprocessedEntities;
=20
+    bool RecordCondDirectives;
+    unsigned CondDirectiveNextIdx;
+    SmallVector<unsigned, 6> CondDirectiveStack;=20
+
+    class CondDirectiveLoc {
+      SourceLocation Loc;
+      unsigned Idx;
+
+    public:
+      CondDirectiveLoc(SourceLocation Loc, unsigned Idx) : Loc(Loc), Idx(I=
dx) {}
+
+      SourceLocation getLoc() const { return Loc; }
+      unsigned getIdx() const { return Idx; }
+
+      class Comp {
+        SourceManager &SM;
+      public:
+        explicit Comp(SourceManager &SM) : SM(SM) {}
+        bool operator()(const CondDirectiveLoc &LHS,
+                        const CondDirectiveLoc &RHS) {
+          return SM.isBeforeInTranslationUnit(LHS.getLoc(), RHS.getLoc());
+        }
+        bool operator()(const CondDirectiveLoc &LHS, SourceLocation RHS) {
+          return SM.isBeforeInTranslationUnit(LHS.getLoc(), RHS);
+        }
+        bool operator()(SourceLocation LHS, const CondDirectiveLoc &RHS) {
+          return SM.isBeforeInTranslationUnit(LHS, RHS.getLoc());
+        }
+      };
+    };
+
+    typedef std::vector<CondDirectiveLoc> CondDirectiveLocsTy;=20
+    /// \brief The locations of conditional directives in source order.
+    CondDirectiveLocsTy CondDirectiveLocs;
+
+    void addCondDirectiveLoc(CondDirectiveLoc DirLoc);
+    unsigned findCondDirectiveIdx(SourceLocation Loc) const;
+
     /// \brief Global (loaded or local) ID for a preprocessed entity.
     /// Negative values are used to indicate preprocessed entities
     /// loaded from the external source while non-negative values are used=
 to
@@ -345,7 +389,7 @@
    =20
   public:
     /// \brief Construct a new preprocessing record.
-    PreprocessingRecord(SourceManager &SM, bool IncludeNestedMacroExpansio=
ns);
+    PreprocessingRecord(SourceManager &SM, bool RecordConditionalDirective=
s);
    =20
     /// \brief Allocate memory in the preprocessing record.
     void *Allocate(unsigned Size, unsigned Align =3D 8) {
@@ -386,7 +430,7 @@
      =20
       iterator() : Self(0), Position(0) { }
      =20
-      iterator(PreprocessingRecord *Self, int Position)=20
+      iterator(PreprocessingRecord *Self, PPEntityID Position)=20
         : Self(Self), Position(Position) { }
      =20
       value_type operator*() const {
@@ -471,6 +515,7 @@
         X.Position -=3D D;
         return X;
       }
+      friend class PreprocessingRecord;
     };
     friend class iterator;
=20
@@ -496,11 +541,41 @@
=20
     /// \brief Returns a pair of [Begin, End) iterators of preprocessed en=
tities
     /// that source range \arg R encompasses.
+    ///
+    /// \param R the range to look for preprocessed entities.
+    ///
     std::pair<iterator, iterator> getPreprocessedEntitiesInRange(SourceRan=
ge R);
=20
+    /// \brief Returns true if the preprocessed entity that \arg PPEI iter=
ator
+    /// points to is coming from the file \arg FID.
+    ///
+    /// Can be used to avoid implicit deserializations of preallocated
+    /// preprocessed entities if we only care about entities of a specific=
 file
+    /// and not from files #included in the range given at
+    /// \see getPreprocessedEntitiesInRange.
+    bool isEntityInFileID(iterator PPEI, FileID FID);
+
     /// \brief Add a new preprocessed entity to this record.
-    void addPreprocessedEntity(PreprocessedEntity *Entity);
-   =20
+    PPEntityID addPreprocessedEntity(PreprocessedEntity *Entity);
+
+    /// \brief Returns true if this PreprocessingRecord is keeping track of
+    /// conditional directives locations.
+    bool isRecordingConditionalDirectives() const {
+      return RecordCondDirectives;
+    }
+
+    /// \brief Returns true if the given range intersects with a condition=
al
+    /// directive. if a #if/#endif block is fully contained within the ran=
ge,
+    /// this function will return false.
+    bool rangeIntersectsConditionalDirective(SourceRange Range) const;
+
+    /// \brief Returns true if the given locations are in different region=
s,
+    /// separated by conditional directive blocks.
+    bool areInDifferentConditionalDirectiveRegion(SourceLocation LHS,
+                                                  SourceLocation RHS) cons=
t {
+      return findCondDirectiveIdx(LHS) !=3D findCondDirectiveIdx(RHS);
+    }
+
     /// \brief Set the external source for preprocessed entities.
     void SetExternalSource(ExternalPreprocessingRecordSource &Source);
=20
@@ -513,6 +588,7 @@
     /// \c MacroInfo.
     MacroDefinition *findMacroDefinition(const MacroInfo *MI);
        =20
+  private:
     virtual void MacroExpands(const Token &Id, const MacroInfo* MI,
                               SourceRange Range);
     virtual void MacroDefined(const Token &Id, const MacroInfo *MI);
@@ -525,6 +601,23 @@
                                     SourceLocation EndLoc,
                                     StringRef SearchPath,
                                     StringRef RelativePath);
+    virtual void If(SourceLocation Loc, SourceRange ConditionRange);
+    virtual void Elif(SourceLocation Loc, SourceRange ConditionRange,
+                      SourceLocation IfLoc);
+    virtual void Ifdef(SourceLocation Loc, const Token &MacroNameTok);
+    virtual void Ifndef(SourceLocation Loc, const Token &MacroNameTok);
+    virtual void Else(SourceLocation Loc, SourceLocation IfLoc);
+    virtual void Endif(SourceLocation Loc, SourceLocation IfLoc);
+
+    /// \brief Cached result of the last \see getPreprocessedEntitiesInRan=
ge
+    /// query.
+    struct {
+      SourceRange Range;
+      std::pair<PPEntityID, PPEntityID> Result;
+    } CachedRangeQuery;
+
+    std::pair<PPEntityID, PPEntityID>
+      getPreprocessedEntitiesInRangeSlow(SourceRange R);
=20
     friend class ASTReader;
     friend class ASTWriter;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/Preprocessor.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/Preprocessor.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -33,6 +33,10 @@
 #include "llvm/Support/Allocator.h"
 #include <vector>
=20
+namespace llvm {
+  template<unsigned InternalLen> class SmallString;
+}
+
 namespace clang {
=20
 class SourceManager;
@@ -50,15 +54,15 @@
 class DirectoryLookup;
 class PreprocessingRecord;
 class ModuleLoader;
- =20
+
 /// Preprocessor - This object engages in a tight little dance with the le=
xer to
 /// efficiently preprocess tokens.  Lexers know only about tokens within a
 /// single source file, and don't know anything about preprocessor-level i=
ssues
 /// like the #include stack, token expansion, etc.
 ///
-class Preprocessor : public llvm::RefCountedBase<Preprocessor> {
+class Preprocessor : public RefCountedBase<Preprocessor> {
   DiagnosticsEngine        *Diags;
-  LangOptions       &Features;
+  LangOptions       &LangOpts;
   const TargetInfo  *Target;
   FileManager       &FileMgr;
   SourceManager     &SourceMgr;
@@ -69,10 +73,10 @@
   /// \brief External source of macros.
   ExternalPreprocessorSource *ExternalSource;
=20
- =20
+
   /// PTH - An optional PTHManager object used for getting tokens from
   ///  a token cache rather than lexing the original source file.
-  llvm::OwningPtr<PTHManager> PTH;
+  OwningPtr<PTHManager> PTH;
=20
   /// BP - A BumpPtrAllocator object used to quickly allocate and release
   ///  objects internal to the Preprocessor.
@@ -107,8 +111,7 @@
   bool KeepComments : 1;
   bool KeepMacroComments : 1;
   bool SuppressIncludeNotFoundError : 1;
-  bool AutoModuleImport : 1;
- =20
+
   // State that changes while the preprocessor runs:
   bool InMacroArgs : 1;            // True if parsing fn macro invocation =
args.
=20
@@ -121,6 +124,9 @@
   /// \brief Whether we have already loaded macros from the external sourc=
e.
   mutable bool ReadMacrosFromExternalSource : 1;
=20
+  /// \brief True if we are pre-expanding macro arguments.
+  bool InMacroArgPreExpansion;
+
   /// Identifiers - This is mapping/lookup information for all identifiers=
 in
   /// the program, including program keywords.
   mutable IdentifierTable Identifiers;
@@ -145,9 +151,13 @@
   /// with this preprocessor.
   std::vector<CommentHandler *> CommentHandlers;
=20
+  /// \brief True if we want to ignore EOF token and continue later on (th=
us=20
+  /// avoid tearing the Lexer and etc. down).
+  bool IncrementalProcessing;
+
   /// \brief The code-completion handler.
   CodeCompletionHandler *CodeComplete;
- =20
+
   /// \brief The file that we're performing code-completion for, if any.
   const FileEntry *CodeCompletionFile;
=20
@@ -163,14 +173,22 @@
   /// for preprocessing.
   SourceLocation CodeCompletionFileLoc;
=20
-  /// \brief The source location of the __import_module__ keyword we just
+  /// \brief The source location of the 'import' contextual keyword we jus=
t=20
   /// lexed, if any.
   SourceLocation ModuleImportLoc;
=20
+  /// \brief The module import path that we're currently processing.
+  llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2>=20
+    ModuleImportPath;
+ =20
+  /// \brief Whether the module import expectes an identifier next. Otherw=
ise,
+  /// it expects a '.' or ';'.
+  bool ModuleImportExpectsIdentifier;
+ =20
   /// \brief The source location of the currently-active
   /// #pragma clang arc_cf_code_audited begin.
   SourceLocation PragmaARCCFCodeAuditedLoc;
- =20
+
   /// \brief True if we hit the code-completion point.
   bool CodeCompletionReached;
=20
@@ -179,22 +197,22 @@
   /// with a flag that indicates whether skipping this number of bytes will
   /// place the lexer at the start of a line.
   std::pair<unsigned, bool> SkipMainFilePreamble;
- =20
+
   /// CurLexer - This is the current top of the stack that we're lexing fr=
om if
   /// not expanding a macro and we are lexing directly from source code.
   ///  Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-nul=
l.
-  llvm::OwningPtr<Lexer> CurLexer;
+  OwningPtr<Lexer> CurLexer;
=20
   /// CurPTHLexer - This is the current top of stack that we're lexing fro=
m if
   ///  not expanding from a macro and we are lexing from a PTH cache.
   ///  Only one of CurLexer, CurPTHLexer, or CurTokenLexer will be non-nul=
l.
-  llvm::OwningPtr<PTHLexer> CurPTHLexer;
+  OwningPtr<PTHLexer> CurPTHLexer;
=20
   /// CurPPLexer - This is the current top of the stack what we're lexing =
from
   ///  if not expanding a macro.  This is an alias for either CurLexer or
   ///  CurPTHLexer.
   PreprocessorLexer *CurPPLexer;
-   =20
+
   /// CurLookup - The DirectoryLookup structure used to find the current
   /// FileEntry, if CurLexer is non-null and if applicable.  This allows u=
s to
   /// implement #include_next and find directory-specific properties.
@@ -202,13 +220,13 @@
=20
   /// CurTokenLexer - This is the current macro we are expanding, if we are
   /// expanding a macro.  One of CurLexer and CurTokenLexer must be null.
-  llvm::OwningPtr<TokenLexer> CurTokenLexer;
+  OwningPtr<TokenLexer> CurTokenLexer;
=20
   /// \brief The kind of lexer we're currently working with.
-  enum CurLexerKind {=20
-    CLK_Lexer,=20
-    CLK_PTHLexer,=20
-    CLK_TokenLexer,=20
+  enum CurLexerKind {
+    CLK_Lexer,
+    CLK_PTHLexer,
+    CLK_TokenLexer,
     CLK_CachingLexer,
     CLK_LexAfterModuleImport
   } CurLexerKind;
@@ -224,10 +242,10 @@
     TokenLexer            *TheTokenLexer;
     const DirectoryLookup *TheDirLookup;
=20
-    IncludeStackInfo(enum CurLexerKind K, Lexer *L, PTHLexer* P,=20
+    IncludeStackInfo(enum CurLexerKind K, Lexer *L, PTHLexer* P,
                      PreprocessorLexer* PPL,
                      TokenLexer* TL, const DirectoryLookup *D)
-      : CurLexerKind(K), TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL),=20
+      : CurLexerKind(K), TheLexer(L), ThePTHLexer(P), ThePPLexer(PPL),
         TheTokenLexer(TL), TheDirLookup(D) {}
   };
   std::vector<IncludeStackInfo> IncludeMacroStack;
@@ -254,9 +272,9 @@
   /// reused for quick allocation.
   MacroArgs *MacroArgCache;
   friend class MacroArgs;
-=20
-  /// PragmaPushMacroInfo - For each IdentifierInfo used in a #pragma=20
-  /// push_macro directive, we keep a MacroInfo stack used to restore=20
+
+  /// PragmaPushMacroInfo - For each IdentifierInfo used in a #pragma
+  /// push_macro directive, we keep a MacroInfo stack used to restore
   /// previous macro value.
   llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> > PragmaPushMacr=
oInfo;
=20
@@ -286,12 +304,12 @@
   std::vector<std::pair<TokenLexer *, size_t> > MacroExpandingLexersStack;
=20
   /// \brief A record of the macro definitions and expansions that
-  /// occurred during preprocessing.=20
+  /// occurred during preprocessing.
   ///
   /// This is an optional side structure that can be enabled with
   /// \c createPreprocessingRecord() prior to preprocessing.
   PreprocessingRecord *Record;
- =20
+
 private:  // Cached tokens state.
   typedef SmallVector<Token, 1> CachedTokensTy;
=20
@@ -325,7 +343,7 @@
   MacroInfoChain *MICache;
=20
   MacroInfo *getInfoForMacro(IdentifierInfo *II) const;
- =20
+
 public:
   Preprocessor(DiagnosticsEngine &diags, LangOptions &opts,
                const TargetInfo *target,
@@ -333,7 +351,8 @@
                ModuleLoader &TheModuleLoader,
                IdentifierInfoLookup *IILookup =3D 0,
                bool OwnsHeaderSearch =3D false,
-               bool DelayInitialization =3D false);
+               bool DelayInitialization =3D false,
+               bool IncrProcessing =3D false);
=20
   ~Preprocessor();
=20
@@ -342,11 +361,11 @@
   ///
   /// \param Target Information about the target.
   void Initialize(const TargetInfo &Target);
- =20
+
   DiagnosticsEngine &getDiagnostics() const { return *Diags; }
   void setDiagnostics(DiagnosticsEngine &D) { Diags =3D &D; }
=20
-  const LangOptions &getLangOptions() const { return Features; }
+  const LangOptions &getLangOpts() const { return LangOpts; }
   const TargetInfo &getTargetInfo() const { return *Target; }
   FileManager &getFileManager() const { return FileMgr; }
   SourceManager &getSourceManager() const { return SourceMgr; }
@@ -371,7 +390,7 @@
=20
   /// \brief Retrieve the module loader associated with this preprocessor.
   ModuleLoader &getModuleLoader() const { return TheModuleLoader; }
- =20
+
   /// SetCommentRetentionState - Control whether or not the preprocessor r=
etains
   /// comments in output.
   void SetCommentRetentionState(bool KeepComments, bool KeepMacroComments)=
 {
@@ -389,11 +408,6 @@
     return SuppressIncludeNotFoundError;
   }
=20
-  /// \brief Specify whether automatic module imports are enabled.
-  void setAutoModuleImport(bool AutoModuleImport =3D true) {
-    this->AutoModuleImport =3D AutoModuleImport;
-  }
- =20
   /// isCurrentLexer - Return true if we are lexing directly from the spec=
ified
   /// lexer.
   bool isCurrentLexer(const PreprocessorLexer *L) const {
@@ -425,13 +439,14 @@
   MacroInfo *getMacroInfo(IdentifierInfo *II) const {
     if (!II->hasMacroDefinition())
       return 0;
-   =20
+
     return getInfoForMacro(II);
   }
=20
   /// setMacroInfo - Specify a macro for this identifier.
   ///
-  void setMacroInfo(IdentifierInfo *II, MacroInfo *MI);
+  void setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
+                    bool LoadedFromAST =3D false);
=20
   /// macro_iterator/macro_begin/macro_end - This allows you to walk the c=
urrent
   /// state of the macro table.  This visits every currently-defined macro.
@@ -484,29 +499,29 @@
   void setCodeCompletionHandler(CodeCompletionHandler &Handler) {
     CodeComplete =3D &Handler;
   }
- =20
+
   /// \brief Retrieve the current code-completion handler.
   CodeCompletionHandler *getCodeCompletionHandler() const {
     return CodeComplete;
   }
- =20
+
   /// \brief Clear out the code completion handler.
   void clearCodeCompletionHandler() {
     CodeComplete =3D 0;
   }
- =20
+
   /// \brief Hook used by the lexer to invoke the "natural language" code
   /// completion point.
   void CodeCompleteNaturalLanguage();
- =20
+
   /// \brief Retrieve the preprocessing record, or NULL if there is no
   /// preprocessing record.
   PreprocessingRecord *getPreprocessingRecord() const { return Record; }
- =20
-  /// \brief Create a new preprocessing record, which will keep track of=20
+
+  /// \brief Create a new preprocessing record, which will keep track of
   /// all macro expansions, macro definitions, etc.
-  void createPreprocessingRecord(bool IncludeNestedMacroExpansions);
- =20
+  void createPreprocessingRecord(bool RecordConditionalDirectives);
+
   /// EnterMainSourceFile - Enter the specified FileID as the main source =
file,
   /// which implicitly adds the builtin defines etc.
   void EnterMainSourceFile();
@@ -588,7 +603,7 @@
   }
=20
   void LexAfterModuleImport(Token &Result);
- =20
+
   /// LexNonComment - Lex a token.  If it's a comment, keep lexing until w=
e get
   /// something not a comment.  This is useful in -E -C mode where comments
   /// would foul up preprocessor directive handling.
@@ -681,6 +696,18 @@
       CachedTokens[CachedLexPos-1] =3D Tok;
   }
=20
+  /// \brief Recompute the current lexer kind based on the CurLexer/CurPTH=
Lexer/
+  /// CurTokenLexer pointers.
+  void recomputeCurLexerKind();
+
+  /// \brief Returns true if incremental processing is enabled
+  bool isIncrementalProcessingEnabled() const { return IncrementalProcessi=
ng; }
+
+  /// \brief Enables the incremental processing
+  void enableIncrementalProcessing(bool value =3D true) {
+    IncrementalProcessing =3D value;
+  }
+ =20
   /// \brief Specify the point at which code-completion will be performed.
   ///
   /// \param File the file in which code completion should occur. If
@@ -745,11 +772,11 @@
   ///
   /// \brief StartOfLine Whether skipping these bytes puts the lexer at the
   /// start of a line.
-  void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {=20
+  void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine) {
     SkipMainFilePreamble.first =3D Bytes;
     SkipMainFilePreamble.second =3D StartOfLine;
   }
- =20
+
   /// Diag - Forwarding function for diagnostics.  This emits a diagnostic=
 at
   /// the specified Token's location, translating the token's start
   /// position in the current buffer into a SourcePosition object for rend=
ering.
@@ -771,7 +798,7 @@
   StringRef getSpelling(SourceLocation loc,
                               SmallVectorImpl<char> &buffer,
                               bool *invalid =3D 0) const {
-    return Lexer::getSpelling(loc, buffer, SourceMgr, Features, invalid);
+    return Lexer::getSpelling(loc, buffer, SourceMgr, LangOpts, invalid);
   }
=20
   /// getSpelling() - Return the 'spelling' of the Tok token.  The spellin=
g of a
@@ -782,7 +809,7 @@
   ///
   /// \param Invalid If non-null, will be set \c true if an error occurs.
   std::string getSpelling(const Token &Tok, bool *Invalid =3D 0) const {
-    return Lexer::getSpelling(Tok, SourceMgr, Features, Invalid);
+    return Lexer::getSpelling(Tok, SourceMgr, LangOpts, Invalid);
   }
=20
   /// getSpelling - This method is used to get the spelling of a token int=
o a
@@ -795,21 +822,21 @@
   /// to point to a constant buffer with the data already in it (avoiding a
   /// copy).  The caller is not allowed to modify the returned buffer poin=
ter
   /// if an internal buffer is returned.
-  unsigned getSpelling(const Token &Tok, const char *&Buffer,=20
+  unsigned getSpelling(const Token &Tok, const char *&Buffer,
                        bool *Invalid =3D 0) const {
-    return Lexer::getSpelling(Tok, Buffer, SourceMgr, Features, Invalid);
+    return Lexer::getSpelling(Tok, Buffer, SourceMgr, LangOpts, Invalid);
   }
=20
   /// getSpelling - This method is used to get the spelling of a token int=
o a
   /// SmallVector. Note that the returned StringRef may not point to the
   /// supplied buffer if a copy can be avoided.
   StringRef getSpelling(const Token &Tok,
-                              SmallVectorImpl<char> &Buffer,=20
-                              bool *Invalid =3D 0) const;
+                        SmallVectorImpl<char> &Buffer,
+                        bool *Invalid =3D 0) const;
=20
   /// getSpellingOfSingleCharacterNumericConstant - Tok is a numeric const=
ant
   /// with length 1, return the character.
-  char getSpellingOfSingleCharacterNumericConstant(const Token &Tok,=20
+  char getSpellingOfSingleCharacterNumericConstant(const Token &Tok,
                                                    bool *Invalid =3D 0) co=
nst {
     assert(Tok.is(tok::numeric_constant) &&
            Tok.getLength() =3D=3D 1 && "Called on unsupported token");
@@ -824,6 +851,17 @@
     return *SourceMgr.getCharacterData(Tok.getLocation(), Invalid);
   }
=20
+  /// \brief Retrieve the name of the immediate macro expansion.
+  ///
+  /// This routine starts from a source location, and finds the name of th=
e macro
+  /// responsible for its immediate expansion. It looks through any interv=
ening
+  /// macro argument expansions to compute this. It returns a StringRef wh=
ich
+  /// refers to the SourceManager-owned buffer of the source where that ma=
cro
+  /// name is spelled. Thus, the result shouldn't out-live the SourceManag=
er.
+  StringRef getImmediateMacroName(SourceLocation Loc) {
+    return Lexer::getImmediateMacroName(Loc, SourceMgr, getLangOpts());
+  }
+
   /// CreateString - Plop the specified string into a scratch buffer and s=
et the
   /// specified token's location and length to it.  If specified, the sour=
ce
   /// location provides a location of the expansion point of the token.
@@ -847,19 +885,28 @@
   /// location pointing just past the end of the token; an offset of 1 pro=
duces
   /// a source location pointing to the last character in the token, etc.
   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset =
=3D 0) {
-    return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, Features);
+    return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
   }
=20
   /// \brief Returns true if the given MacroID location points at the first
   /// token of the macro expansion.
-  bool isAtStartOfMacroExpansion(SourceLocation loc) const {
-    return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, Features);
+  ///
+  /// \param MacroBegin If non-null and function returns true, it is set to
+  /// begin location of the macro.
+  bool isAtStartOfMacroExpansion(SourceLocation loc,
+                                 SourceLocation *MacroBegin =3D 0) const {
+    return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts,
+                                            MacroBegin);
   }
=20
   /// \brief Returns true if the given MacroID location points at the last
   /// token of the macro expansion.
-  bool isAtEndOfMacroExpansion(SourceLocation loc) const {
-    return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, Features);
+  ///
+  /// \param MacroBegin If non-null and function returns true, it is set to
+  /// end location of the macro.
+  bool isAtEndOfMacroExpansion(SourceLocation loc,
+                               SourceLocation *MacroEnd =3D 0) const {
+    return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroE=
nd);
   }
=20
   /// DumpToken - Print the token to stderr, used for debugging.
@@ -872,7 +919,7 @@
   /// token, return a new location that specifies a character within the t=
oken.
   SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
                                          unsigned Char) const {
-    return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, Featu=
res);
+    return Lexer::AdvanceToTokenCharacter(TokStart, Char, SourceMgr, LangO=
pts);
   }
=20
   /// IncrementPasteCounter - Increment the counters for the number of tok=
en
@@ -930,9 +977,18 @@
 private:
   /// Identifiers used for SEH handling in Borland. These are only
   /// allowed in particular circumstances
-  IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_G=
etExceptionCode; // __except block
-  IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_G=
etExceptionInfo; // __except filter expression
-  IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_terminati=
on, *Ident_AbnormalTermination; // __finally
+  // __except block
+  IdentifierInfo *Ident__exception_code,
+                 *Ident___exception_code,
+                 *Ident_GetExceptionCode;
+  // __except filter expression
+  IdentifierInfo *Ident__exception_info,
+                 *Ident___exception_info,
+                 *Ident_GetExceptionInfo;
+  // __finally
+  IdentifierInfo *Ident__abnormal_termination,
+                 *Ident___abnormal_termination,
+                 *Ident_AbnormalTermination;
 public:
   void PoisonSEHIdentifiers(bool Poison =3D true); // Borland
=20
@@ -976,6 +1032,9 @@
   unsigned getCounterValue() const { return CounterValue; }
   void setCounterValue(unsigned V) { CounterValue =3D V; }
=20
+  /// \brief Retrieves the module that we're currently building, if any.
+  Module *getCurrentModule();
+ =20
   /// AllocateMacroInfo - Allocate a new MacroInfo object with the provide
   ///  SourceLocation.
   MacroInfo *AllocateMacroInfo(SourceLocation L);
@@ -999,7 +1058,8 @@
                               const DirectoryLookup *&CurDir,
                               SmallVectorImpl<char> *SearchPath,
                               SmallVectorImpl<char> *RelativePath,
-                              StringRef *SuggestedModule);
+                              Module **SuggestedModule,
+                              bool SkipCache =3D false);
=20
   /// GetCurLookup - The DirectoryLookup structure used to find the current
   /// FileEntry, if CurLexer is non-null and if applicable.  This allows u=
s to
@@ -1020,7 +1080,7 @@
   /// This code concatenates and consumes tokens up to the '>' token.  It
   /// returns false if the > was found, otherwise it returns true if it fi=
nds
   /// and consumes the EOD marker.
-  bool ConcatenateIncludeName(llvm::SmallString<128> &FilenameBuffer,
+  bool ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
                               SourceLocation &End);
=20
   /// LexOnOffSwitch - Lex an on-off-switch (C99 6.10.6p2) and verify that=
 it is
@@ -1063,9 +1123,10 @@
=20
   /// ReadMacroDefinitionArgList - The ( starting an argument list of a ma=
cro
   /// definition has just been read.  Lex the rest of the arguments and the
-  /// closing ), updating MI with what we learn.  Return true if an error =
occurs
-  /// parsing the arg list.
-  bool ReadMacroDefinitionArgList(MacroInfo *MI);
+  /// closing ), updating MI with what we learn and saving in LastTok the
+  /// last token read.
+  /// Return true if an error occurs parsing the arg list.
+  bool ReadMacroDefinitionArgList(MacroInfo *MI, Token& LastTok);
=20
   /// SkipExcludedConditionalBlock - We just read a #if or related directi=
ve and
   /// decided that the subsequent tokens are in the #if'd out portion of t=
he
@@ -1163,7 +1224,7 @@
   bool InCachingLexMode() const {
     // If the Lexer pointers are 0 and IncludeMacroStack is empty, it means
     // that we are past EOF, not that we are in CachingLex mode.
-    return CurPPLexer =3D=3D 0 && CurTokenLexer =3D=3D 0 && CurPTHLexer =
=3D=3D 0 &&=20
+    return CurPPLexer =3D=3D 0 && CurTokenLexer =3D=3D 0 && CurPTHLexer =
=3D=3D 0 &&
            !IncludeMacroStack.empty();
   }
   void EnterCachingLexMode();
@@ -1182,8 +1243,9 @@
   void HandleDigitDirective(Token &Tok);
   void HandleUserDiagnosticDirective(Token &Tok, bool isWarning);
   void HandleIdentSCCSDirective(Token &Tok);
-  void HandleMacroExportDirective(Token &Tok);
- =20
+  void HandleMacroPublicDirective(Token &Tok);
+  void HandleMacroPrivateDirective(Token &Tok);
+
   // File inclusion.
   void HandleIncludeDirective(SourceLocation HashLoc,
                               Token &Tok,
@@ -1192,6 +1254,7 @@
   void HandleIncludeNextDirective(SourceLocation HashLoc, Token &Tok);
   void HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &Tok);
   void HandleImportDirective(SourceLocation HashLoc, Token &Tok);
+  void HandleMicrosoftImportDirective(Token &Tok);
=20
   // Macro handling.
   void HandleDefineDirective(Token &Tok);
@@ -1217,6 +1280,7 @@
   void HandlePragmaMessage(Token &MessageTok);
   void HandlePragmaPushMacro(Token &Tok);
   void HandlePragmaPopMacro(Token &Tok);
+  void HandlePragmaIncludeAlias(Token &Tok);
   IdentifierInfo *ParsePragmaPushOrPopMacro(Token &Tok);
=20
   // Return true and store the first token only if any CommentHandler
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/PreprocessorLexer.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/PreprocessorLexer.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/PreprocessorLexer.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -24,6 +24,7 @@
 class Preprocessor;
=20
 class PreprocessorLexer {
+  virtual void anchor();
 protected:
   Preprocessor *PP;              // Preprocessor object controlling lexing.
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Lex/Token.h
--- a/head/contrib/llvm/tools/clang/include/clang/Lex/Token.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Lex/Token.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -75,7 +75,8 @@
     LeadingSpace  =3D 0x02,  // Whitespace exists before this token.
     DisableExpand =3D 0x04,  // This identifier may never be macro expande=
d.
     NeedsCleaning =3D 0x08,   // Contained an escaped newline or trigraph.
-    LeadingEmptyMacro =3D 0x10 // Empty macro exists before this token.
+    LeadingEmptyMacro =3D 0x10, // Empty macro exists before this token.
+    HasUDSuffix =3D 0x20     // This string or character literal has a ud-=
suffix.
   };
=20
   tok::TokenKind getKind() const { return (tok::TokenKind)Kind; }
@@ -263,6 +264,9 @@
     return (Flags & LeadingEmptyMacro) ? true : false;
   }
=20
+  /// \brief Return true if this token is a string or character literal wh=
ich
+  /// has a ud-suffix.
+  bool hasUDSuffix() const { return (Flags & HasUDSuffix) ? true : false; }
 };
=20
 /// PPConditionalInfo - Information about the conditional stack (#if direc=
tives)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Parse/ParseAST.h
--- a/head/contrib/llvm/tools/clang/include/clang/Parse/ParseAST.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Parse/ParseAST.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -36,11 +36,13 @@
   void ParseAST(Preprocessor &pp, ASTConsumer *C,
                 ASTContext &Ctx, bool PrintStats =3D false,
                 TranslationUnitKind TUKind =3D TU_Complete,
-                CodeCompleteConsumer *CompletionConsumer =3D 0);
+                CodeCompleteConsumer *CompletionConsumer =3D 0,
+                bool SkipFunctionBodies =3D false);
=20
   /// \brief Parse the main file known to the preprocessor, producing an=20
   /// abstract syntax tree.
-  void ParseAST(Sema &S, bool PrintStats =3D false);
+  void ParseAST(Sema &S, bool PrintStats =3D false,
+                bool SkipFunctionBodies =3D false);
  =20
 }  // end namespace clang
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Parse/ParseDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Parse/ParseDiagnostic.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Parse/ParseDiagnostic.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
   namespace diag {
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
 #define PARSESTART
 #include "clang/Basic/DiagnosticParseKinds.inc"
 #undef DIAG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Parse/Parser.h
--- a/head/contrib/llvm/tools/clang/include/clang/Parse/Parser.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Parse/Parser.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -20,9 +20,10 @@
 #include "clang/Lex/CodeCompletionHandler.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Sema/DeclSpec.h"
-#include "llvm/Support/PrettyStackTrace.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/PrettyStackTrace.h"
 #include <stack>
=20
 namespace clang {
@@ -36,7 +37,7 @@
   class InMessageExpressionRAIIObject;
   class PoisonSEHIdentifiersRAIIObject;
   class VersionTuple;
- =20
+
 /// PrettyStackTraceParserEntry - If a crash happens while the parser is a=
ctive,
 /// an entry is printed for it.
 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
@@ -96,7 +97,7 @@
   unsigned short ParenCount, BracketCount, BraceCount;
=20
   /// Actions - These are the callbacks we invoke as we parse various cons=
tructs
-  /// in the file.=20
+  /// in the file.
   Sema &Actions;
=20
   DiagnosticsEngine &Diags;
@@ -108,9 +109,21 @@
=20
   /// Identifiers used for SEH handling in Borland. These are only
   /// allowed in particular circumstances
-  IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_G=
etExceptionCode; // __except block
-  IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_G=
etExceptionInfo; // __except filter expression
-  IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_terminati=
on, *Ident_AbnormalTermination; // __finally
+  // __except block
+  IdentifierInfo *Ident__exception_code,
+                 *Ident___exception_code,
+                 *Ident_GetExceptionCode;
+  // __except filter expression
+  IdentifierInfo *Ident__exception_info,
+                 *Ident___exception_info,
+                 *Ident_GetExceptionInfo;
+  // __finally
+  IdentifierInfo *Ident__abnormal_termination,
+                 *Ident___abnormal_termination,
+                 *Ident_AbnormalTermination;
+
+  /// Contextual keywords for Microsoft extensions.
+  IdentifierInfo *Ident__except;
=20
   /// Ident_super - IdentifierInfo for "super", to support fast
   /// comparison.
@@ -123,7 +136,7 @@
=20
   /// Objective-C contextual keywords.
   mutable IdentifierInfo *Ident_instancetype;
- =20
+
   /// \brief Identifier for "introduced".
   IdentifierInfo *Ident_introduced;
=20
@@ -135,43 +148,47 @@
=20
   /// \brief Identifier for "unavailable".
   IdentifierInfo *Ident_unavailable;
+ =20
+  /// \brief Identifier for "message".
+  IdentifierInfo *Ident_message;
=20
-  /// C++0x contextual keywords.=20
+  /// C++0x contextual keywords.
   mutable IdentifierInfo *Ident_final;
   mutable IdentifierInfo *Ident_override;
=20
-  llvm::OwningPtr<PragmaHandler> AlignHandler;
-  llvm::OwningPtr<PragmaHandler> GCCVisibilityHandler;
-  llvm::OwningPtr<PragmaHandler> OptionsHandler;
-  llvm::OwningPtr<PragmaHandler> PackHandler;
-  llvm::OwningPtr<PragmaHandler> MSStructHandler;
-  llvm::OwningPtr<PragmaHandler> UnusedHandler;
-  llvm::OwningPtr<PragmaHandler> WeakHandler;
-  llvm::OwningPtr<PragmaHandler> FPContractHandler;
-  llvm::OwningPtr<PragmaHandler> OpenCLExtensionHandler;
+  OwningPtr<PragmaHandler> AlignHandler;
+  OwningPtr<PragmaHandler> GCCVisibilityHandler;
+  OwningPtr<PragmaHandler> OptionsHandler;
+  OwningPtr<PragmaHandler> PackHandler;
+  OwningPtr<PragmaHandler> MSStructHandler;
+  OwningPtr<PragmaHandler> UnusedHandler;
+  OwningPtr<PragmaHandler> WeakHandler;
+  OwningPtr<PragmaHandler> RedefineExtnameHandler;
+  OwningPtr<PragmaHandler> FPContractHandler;
+  OwningPtr<PragmaHandler> OpenCLExtensionHandler;
=20
   /// Whether the '>' token acts as an operator or not. This will be
   /// true except when we are parsing an expression within a C++
   /// template argument list, where the '>' closes the template
   /// argument list.
   bool GreaterThanIsOperator;
- =20
+
   /// ColonIsSacred - When this is false, we aggressively try to recover f=
rom
   /// code like "foo : bar" as if it were a typo for "foo :: bar".  This i=
s not
   /// safe in case statements and a few other things.  This is managed by =
the
   /// ColonProtectionRAIIObject RAII object.
   bool ColonIsSacred;
=20
-  /// \brief When true, we are directly inside an Objective-C messsage=20
+  /// \brief When true, we are directly inside an Objective-C messsage
   /// send expression.
   ///
   /// This is managed by the \c InMessageExpressionRAIIObject class, and
   /// should not be set directly.
   bool InMessageExpression;
- =20
+
   /// The "depth" of the template parameters currently being parsed.
   unsigned TemplateParameterDepth;
- =20
+
   /// Factory object for creating AttributeList objects.
   AttributeFactory AttrFactory;
=20
@@ -179,20 +196,24 @@
   /// declaration is finished.
   DelayedCleanupPool TopLevelDeclCleanupPool;
=20
+  IdentifierInfo *getSEHExceptKeyword();
+
+  bool SkipFunctionBodies;
+
 public:
-  Parser(Preprocessor &PP, Sema &Actions);
+  Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
   ~Parser();
=20
-  const LangOptions &getLang() const { return PP.getLangOptions(); }
+  const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
   const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
   Preprocessor &getPreprocessor() const { return PP; }
   Sema &getActions() const { return Actions; }
=20
   const Token &getCurToken() const { return Tok; }
   Scope *getCurScope() const { return Actions.getCurScope(); }
-   =20
+
   Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext();=
 }
- =20
+
   // Type forwarding.  All of these are statically 'void*', but they may a=
ll be
   // different actual classes based on the actions in place.
   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
@@ -241,8 +262,6 @@
   /// the EOF was encountered.
   bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
=20
-  DeclGroupPtrTy FinishPendingObjCActions();
-
 private:
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Low-Level token peeking and consumption methods.
@@ -271,10 +290,9 @@
            Tok.getKind() =3D=3D tok::utf32_string_literal;
   }
=20
-  /// \brief Returns true if the current token is a '=3D' or '=3D=3D' and
-  /// false otherwise. If it's '=3D=3D', we assume that it's a typo and we=
 emit
-  /// DiagID and a fixit hint to turn '=3D=3D' -> '=3D'.
-  bool isTokenEqualOrMistypedEqualEqual(unsigned DiagID);
+  /// \brief Returns true if the current token is '=3D' or is a type of '=
=3D'.
+  /// For typos, give a fixit to '=3D'
+  bool isTokenEqualOrEqualTypo();
=20
   /// ConsumeToken - Consume the current 'peek token' and lex the next one.
   /// This does not work with all kinds of tokens: strings and specific ot=
her
@@ -370,9 +388,9 @@
     assert(Tok.is(tok::code_completion));
     PrevTokLocation =3D Tok.getLocation();
     PP.Lex(Tok);
-    return PrevTokLocation;   =20
+    return PrevTokLocation;
   }
- =20
+
   ///\ brief When we are consuming a code-completion token without having
   /// matched specific position in the grammar, provide code-completion re=
sults
   /// based on context.
@@ -391,6 +409,14 @@
   /// \brief Handle the annotation token produced for #pragma unused(...)
   void HandlePragmaUnused();
=20
+  /// \brief Handle the annotation token produced for
+  /// #pragma GCC visibility...
+  void HandlePragmaVisibility();
+
+  /// \brief Handle the annotation token produced for
+  /// #pragma pack...
+  void HandlePragmaPack();
+
   /// GetLookAheadToken - This peeks ahead N tokens and returns that token
   /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead=
(1)
   /// returns the token after Tok, etc.
@@ -409,84 +435,78 @@
     return PP.LookAhead(0);
   }
=20
-  /// \brief Tracks information about the current nesting depth of=20
-  /// opening delimiters of each kind.
-  class DelimiterTracker {
-  private:
-    friend class Parser;
-
-    unsigned Paren, Brace, Square, Less, LLLess;
-    unsigned& get(tok::TokenKind t) {
-      switch (t) {
-      default: llvm_unreachable("Unexpected balanced token");
-      case tok::l_brace:  return Brace;
-      case tok::l_paren:  return Paren;
-      case tok::l_square: return Square;
-      case tok::less:  return Less;
-      case tok::lesslessless:  return LLLess;
-      }
-    }
-
-    void push(tok::TokenKind t) {
-      get(t)++;
-    }
-
-    void pop(tok::TokenKind t) {
-      get(t)--;
-    }
-
-    unsigned getDepth(tok::TokenKind t) {
-      return get(t);
-    }
-
-  public:
-    DelimiterTracker() : Paren(0), Brace(0), Square(0), Less(0), LLLess(0)=
 { }
-  };
-
   /// \brief RAII class that helps handle the parsing of an open/close del=
imiter
   /// pair, such as braces { ... } or parentheses ( ... ).
   class BalancedDelimiterTracker {
+    Parser& P;
     tok::TokenKind Kind, Close;
-    Parser& P;
-    bool Cleanup;
-    const unsigned MaxDepth;
+    SourceLocation (Parser::*Consumer)();
     SourceLocation LOpen, LClose;
- =20
-    void assignClosingDelimiter() {
+
+    unsigned short &getDepth() {
+      switch (Kind) {
+      case tok::l_brace: return P.BraceCount;
+      case tok::l_square: return P.BracketCount;
+      case tok::l_paren: return P.ParenCount;
+      default: llvm_unreachable("Wrong token kind");
+      }
+    }
+   =20
+    enum { MaxDepth =3D 512 };
+   =20
+    bool diagnoseOverflow();
+    bool diagnoseMissingClose();
+   =20
+  public:
+    BalancedDelimiterTracker(Parser& p, tok::TokenKind k) : P(p), Kind(k) {
       switch (Kind) {
       default: llvm_unreachable("Unexpected balanced token");
-      case tok::l_brace:  Close =3D tok::r_brace; break;
-      case tok::l_paren:  Close =3D tok::r_paren; break;
-      case tok::l_square: Close =3D tok::r_square; break;
-      case tok::less:  Close =3D tok::greater; break;
-      case tok::lesslessless:  Close =3D tok::greatergreatergreater; break;
-      }
-    }
-
-  public:
-    BalancedDelimiterTracker(Parser& p, tok::TokenKind k)=20
-      : Kind(k), P(p), Cleanup(false), MaxDepth(256) {
-      assignClosingDelimiter();
-    }
-
-    ~BalancedDelimiterTracker() {
-      if (Cleanup)
-        P.QuantityTracker.pop(Kind);
+      case tok::l_brace:
+        Close =3D tok::r_brace;=20
+        Consumer =3D &Parser::ConsumeBrace;
+        break;
+      case tok::l_paren:
+        Close =3D tok::r_paren;=20
+        Consumer =3D &Parser::ConsumeParen;
+        break;
+       =20
+      case tok::l_square:
+        Close =3D tok::r_square;=20
+        Consumer =3D &Parser::ConsumeBracket;
+        break;
+      }     =20
     }
=20
     SourceLocation getOpenLocation() const { return LOpen; }
     SourceLocation getCloseLocation() const { return LClose; }
     SourceRange getRange() const { return SourceRange(LOpen, LClose); }
=20
-    bool consumeOpen();
-    bool expectAndConsume(unsigned DiagID,=20
-                          const char *Msg =3D "",=20
+    bool consumeOpen() {
+      if (!P.Tok.is(Kind))
+        return true;
+     =20
+      if (getDepth() < MaxDepth) {
+        LOpen =3D (P.*Consumer)();
+        return false;
+      }
+     =20
+      return diagnoseOverflow();
+    }
+   =20
+    bool expectAndConsume(unsigned DiagID,
+                          const char *Msg =3D "",
                           tok::TokenKind SkipToTok =3D tok::unknown);
-    bool consumeClose();
+    bool consumeClose() {
+      if (P.Tok.is(Close)) {
+        LClose =3D (P.*Consumer)();
+        return false;
+      }=20
+
+      return diagnoseMissingClose();
+    }
+    void skipToEnd();
   };
=20
-  DelimiterTracker QuantityTracker;
-
   /// getTypeAnnotation - Read a parsed type out of an annotation token.
   static ParsedType getTypeAnnotation(Token &Tok) {
     return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
@@ -495,16 +515,16 @@
   static void setTypeAnnotation(Token &Tok, ParsedType T) {
     Tok.setAnnotationValue(T.getAsOpaquePtr());
   }
- =20
+
   /// \brief Read an already-translated primary expression out of an annot=
ation
   /// token.
   static ExprResult getExprAnnotation(Token &Tok) {
     if (Tok.getAnnotationValue())
       return ExprResult((Expr *)Tok.getAnnotationValue());
-   =20
+
     return ExprResult(true);
   }
- =20
+
   /// \brief Set the primary expression corresponding to the given annotat=
ion
   /// token.
   static void setExprAnnotation(Token &Tok, ExprResult ER) {
@@ -526,11 +546,11 @@
   bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
                        const char *&PrevSpec, unsigned &DiagID,
                        bool &isInvalid) {
-    if (!getLang().AltiVec ||
+    if (!getLangOpts().AltiVec ||
         (Tok.getIdentifierInfo() !=3D Ident_vector &&
          Tok.getIdentifierInfo() !=3D Ident_pixel))
       return false;
-   =20
+
     return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
   }
=20
@@ -538,11 +558,11 @@
   /// identifier token, replacing it with the non-context-sensitive __vect=
or.
   /// This returns true if the token was replaced.
   bool TryAltiVecVectorToken() {
-    if (!getLang().AltiVec ||
+    if (!getLangOpts().AltiVec ||
         Tok.getIdentifierInfo() !=3D Ident_vector) return false;
     return TryAltiVecVectorTokenOutOfLine();
   }
- =20
+
   bool TryAltiVecVectorTokenOutOfLine();
   bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
                                 const char *&PrevSpec, unsigned &DiagID,
@@ -598,14 +618,14 @@
     Parser &P;
     Decl *DC;
   public:
-    explicit ObjCDeclContextSwitch(Parser &p) : P(p),=20
+    explicit ObjCDeclContextSwitch(Parser &p) : P(p),
                DC(p.getObjCDeclContext()) {
       if (DC)
-        P.Actions.ActOnObjCTemporaryExitContainerContext();
+        P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>=
(DC));
     }
     ~ObjCDeclContextSwitch() {
       if (DC)
-        P.Actions.ActOnObjCReenterContainerContext();
+        P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
     }
   };
=20
@@ -625,7 +645,7 @@
   /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') =
prior
   /// to the semicolon, consumes that extra token.
   bool ExpectAndConsumeSemi(unsigned DiagID);
- =20
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Scope manipulation
=20
@@ -695,6 +715,7 @@
 private:
   void SuggestParentheses(SourceLocation Loc, unsigned DK,
                           SourceRange ParenRange);
+  void CheckNestedObjCContexts(SourceLocation AtLoc);
=20
   /// SkipUntil - Read tokens until we get to the specified token, then co=
nsume
   /// it (unless DontConsume is true).  Because we cannot guarantee that t=
he
@@ -706,16 +727,26 @@
   /// returns false.
   bool SkipUntil(tok::TokenKind T, bool StopAtSemi =3D true,
                  bool DontConsume =3D false, bool StopAtCodeCompletion =3D=
 false) {
-    return SkipUntil(&T, 1, StopAtSemi, DontConsume, StopAtCodeCompletion);
+    return SkipUntil(llvm::makeArrayRef(T), StopAtSemi, DontConsume,
+                     StopAtCodeCompletion);
   }
   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi =3D=
 true,
                  bool DontConsume =3D false, bool StopAtCodeCompletion =3D=
 false) {
     tok::TokenKind TokArray[] =3D {T1, T2};
-    return SkipUntil(TokArray, 2, StopAtSemi, DontConsume,StopAtCodeComple=
tion);
+    return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletio=
n);
   }
-  bool SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
+  bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
                  bool StopAtSemi =3D true, bool DontConsume =3D false,
-                 bool StopAtCodeCompletion =3D false);
+                 bool StopAtCodeCompletion =3D false) {
+    tok::TokenKind TokArray[] =3D {T1, T2, T3};
+    return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletio=
n);
+  }
+  bool SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi =3D true,
+                 bool DontConsume =3D false, bool StopAtCodeCompletion =3D=
 false);
+
+  /// SkipMalformedDecl - Read tokens until we get to some likely good sto=
pping
+  /// point for skipping past a simple-declaration.
+  void SkipMalformedDecl();
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Lexing and parsing of C++ inline methods.
@@ -757,9 +788,9 @@
     ParsingClass *Class;
   };
=20
-  /// Contains the lexed tokens of an attribute with arguments that=20
-  /// may reference member variables and so need to be parsed at the=20
-  /// end of the class declaration after parsing all other member=20
+  /// Contains the lexed tokens of an attribute with arguments that
+  /// may reference member variables and so need to be parsed at the
+  /// end of the class declaration after parsing all other member
   /// member declarations.
   /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
   /// LateParsedTokens.
@@ -768,15 +799,15 @@
     CachedTokens Toks;
     IdentifierInfo &AttrName;
     SourceLocation AttrNameLoc;
-    Decl *D;
+    SmallVector<Decl*, 2> Decls;
=20
-    explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,=20
+    explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
                                  SourceLocation Loc)
-      : Self(P), AttrName(Name), AttrNameLoc(Loc), D(0)  {}
+      : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
=20
     virtual void ParseLexedAttributes();
=20
-    void setDecl(Decl *Dec) { D =3D Dec; }
+    void addDecl(Decl *D) { Decls.push_back(D); }
   };
=20
   /// A list of late parsed attributes.  Used by ParseGNUAttributes.
@@ -872,8 +903,9 @@
   /// C++ class, its method declarations that contain parts that won't be
   /// parsed until after the definition is completed (C++ [class.mem]p2),
   /// the method declarations and possibly attached inline definitions
-  /// will be stored here with the tokens that will be parsed to create th=
ose entities.
-  typedef SmallVector<LateParsedDeclaration*, 2> LateParsedDeclarationsCon=
tainer;
+  /// will be stored here with the tokens that will be parsed to create th=
ose=20
+  /// entities.
+  typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsCont=
ainer;
=20
   /// \brief Representation of a class that has been parsed, including
   /// any member function declarations or definitions that need to be
@@ -965,7 +997,7 @@
       Popped =3D Other.Popped;
       Other.Popped =3D true;
     }
-   =20
+
     void push() {
       State =3D Actions.PushParsingDeclaration();
       Popped =3D false;
@@ -1060,7 +1092,7 @@
                        bool isSpecialization,
                        bool lastParameterListWasEmpty =3D false)
       : Kind(isSpecialization? ExplicitSpecialization : Template),
-        TemplateParams(TemplateParams),=20
+        TemplateParams(TemplateParams),
         LastParameterListWasEmpty(lastParameterListWasEmpty) { }
=20
     explicit ParsedTemplateInfo(SourceLocation ExternLoc,
@@ -1092,23 +1124,23 @@
     /// \brief The location of the 'template' keyword, for an explicit
     /// instantiation.
     SourceLocation TemplateLoc;
-   =20
+
     /// \brief Whether the last template parameter list was empty.
     bool LastParameterListWasEmpty;
=20
-    SourceRange getSourceRange() const;
+    SourceRange getSourceRange() const LLVM_READONLY;
   };
=20
   /// \brief Contains a late templated function.
   /// Will be parsed at the end of the translation unit.
   struct LateParsedTemplatedFunction {
-    explicit LateParsedTemplatedFunction(Parser* P, Decl *MD)
+    explicit LateParsedTemplatedFunction(Decl *MD)
       : D(MD) {}
=20
     CachedTokens Toks;
-   =20
+
     /// \brief The template function declaration to be late parsed.
-    Decl *D;=20
+    Decl *D;
   };
=20
   void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
@@ -1128,10 +1160,15 @@
   Decl *ParseCXXInlineMethodDef(AccessSpecifier AS, AttributeList *AccessA=
ttrs,
                                 ParsingDeclarator &D,
                                 const ParsedTemplateInfo &TemplateInfo,
-                                const VirtSpecifiers& VS, ExprResult& Init=
);
+                                const VirtSpecifiers& VS,
+                                FunctionDefinitionKind DefinitionKind,
+                                ExprResult& Init);
   void ParseCXXNonStaticMemberInitializer(Decl *VarD);
   void ParseLexedAttributes(ParsingClass &Class);
-  void ParseLexedAttribute(LateParsedAttribute &LA);
+  void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
+                               bool EnterScope, bool OnDefinition);
+  void ParseLexedAttribute(LateParsedAttribute &LA,
+                           bool EnterScope, bool OnDefinition);
   void ParseLexedMethodDeclarations(ParsingClass &Class);
   void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
   void ParseLexedMethodDefs(ParsingClass &Class);
@@ -1168,9 +1205,10 @@
                                                   AccessSpecifier AS =3D A=
S_none);
   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
                                                   AccessSpecifier AS =3D A=
S_none);
- =20
+
   Decl *ParseFunctionDefinition(ParsingDeclarator &D,
-                 const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplate=
Info());
+                 const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplate=
Info(),
+                 LateParsedAttrList *LateParsedAttrs =3D 0);
   void ParseKNRParamDeclarations(Declarator &D);
   // EndLoc, if non-NULL, is filled with the location of the last token of
   // the simple-asm.
@@ -1178,9 +1216,9 @@
   ExprResult ParseAsmStringLiteral();
=20
   // Objective-C External Declarations
-  Parser::DeclGroupPtrTy ParseObjCAtDirectives();
-  Parser::DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
-  Decl *ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,
+  DeclGroupPtrTy ParseObjCAtDirectives();
+  DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
+  Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
                                         ParsedAttributes &prefixAttrs);
   void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
                                        tok::ObjCKeywordKind visibility,
@@ -1193,15 +1231,31 @@
   bool ParseObjCProtocolQualifiers(DeclSpec &DS);
   void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
                                   Decl *CDecl);
-  Decl *ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
-                                       ParsedAttributes &prefixAttrs);
+  DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
+                                                ParsedAttributes &prefixAt=
trs);
=20
-  Decl *ObjCImpDecl;
-  SmallVector<Decl *, 4> PendingObjCImpDecl;
-  typedef SmallVector<LexedMethod*, 2> LateParsedObjCMethodContainer;
-  LateParsedObjCMethodContainer LateParsedObjCMethods;
+  struct ObjCImplParsingDataRAII {
+    Parser &P;
+    Decl *Dcl;
+    typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
+    LateParsedObjCMethodContainer LateParsedObjCMethods;
=20
-  Decl *ParseObjCAtImplementationDeclaration(SourceLocation atLoc);
+    ObjCImplParsingDataRAII(Parser &parser, Decl *D)
+      : P(parser), Dcl(D) {
+      P.CurParsedObjCImpl =3D this;
+      Finished =3D false;
+    }
+    ~ObjCImplParsingDataRAII();
+
+    void finish(SourceRange AtEnd);
+    bool isFinished() const { return Finished; }
+
+  private:
+    bool Finished;
+  };
+  ObjCImplParsingDataRAII *CurParsedObjCImpl;
+
+  DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc=
);
   DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
   Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
   Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
@@ -1232,11 +1286,18 @@
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C99 6.5: Expressions.
- =20
-  ExprResult ParseExpression();
-  ExprResult ParseConstantExpression();
+
+  /// TypeCastState - State whether an expression is or may be a type cast.
+  enum TypeCastState {
+    NotTypeCast =3D 0,
+    MaybeTypeCast,
+    IsTypeCast
+  };
+
+  ExprResult ParseExpression(TypeCastState isTypeCast =3D NotTypeCast);
+  ExprResult ParseConstantExpression(TypeCastState isTypeCast =3D NotTypeC=
ast);
   // Expr that doesn't include commas.
-  ExprResult ParseAssignmentExpression();
+  ExprResult ParseAssignmentExpression(TypeCastState isTypeCast =3D NotTyp=
eCast);
=20
   ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
=20
@@ -1247,10 +1308,10 @@
   ExprResult ParseCastExpression(bool isUnaryExpression,
                                  bool isAddressOfOperand,
                                  bool &NotCastExpr,
-                                 bool isTypeCast);
+                                 TypeCastState isTypeCast);
   ExprResult ParseCastExpression(bool isUnaryExpression,
                                  bool isAddressOfOperand =3D false,
-                                 bool isTypeCast =3D false);
+                                 TypeCastState isTypeCast =3D NotTypeCast);
=20
   /// Returns true if the next token would start a postfix-expression
   /// suffix.
@@ -1278,8 +1339,7 @@
                            SmallVectorImpl<SourceLocation> &CommaLocs,
                            void (Sema::*Completer)(Scope *S,
                                                    Expr *Data,
-                                                   Expr **Args,
-                                                   unsigned NumArgs) =3D 0,
+                                             llvm::ArrayRef<Expr *> Args) =
=3D 0,
                            Expr *Data =3D 0);
=20
   /// ParenParseOption - Control what ParseParenExpression will parse.
@@ -1302,9 +1362,11 @@
                                                   SourceLocation LParenLoc,
                                                   SourceLocation RParenLoc=
);
=20
-  ExprResult ParseStringLiteralExpression();
+  ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral =3D=
 false);
=20
   ExprResult ParseGenericSelectionExpression();
+ =20
+  ExprResult ParseObjCBoolLiteral();
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ Expressions
@@ -1420,6 +1482,7 @@
       return ParseAssignmentExpression();
     return ParseBraceInitializer();
   }
+  bool MayBeDesignationStart();
   ExprResult ParseBraceInitializer();
   ExprResult ParseInitializerWithPotentialDesignator();
=20
@@ -1432,29 +1495,35 @@
   // Objective-C Expressions
   ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
   ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
+  ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
+  ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
+  ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
+  ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
+  ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
   ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
   ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
   bool isSimpleObjCMessageExpression();
   ExprResult ParseObjCMessageExpression();
   ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
-                                                  SourceLocation SuperLoc,
-                                                  ParsedType ReceiverType,
-                                                  ExprArg ReceiverExpr);
+                                            SourceLocation SuperLoc,
+                                            ParsedType ReceiverType,
+                                            ExprArg ReceiverExpr);
   ExprResult ParseAssignmentExprWithObjCMessageExprStart(
       SourceLocation LBracloc, SourceLocation SuperLoc,
       ParsedType ReceiverType, ExprArg ReceiverExpr);
   bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
-
+   =20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C99 6.8: Statements and Blocks.
=20
-  StmtResult ParseStatement() {
+  StmtResult ParseStatement(SourceLocation *TrailingElseLoc =3D NULL) {
     StmtVector Stmts(Actions);
-    return ParseStatementOrDeclaration(Stmts, true);
+    return ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
   }
   StmtResult ParseStatementOrDeclaration(StmtVector& Stmts,
-                                         bool OnlyStatement =3D false);
+                                         bool OnlyStatement,
+                                        SourceLocation *TrailingElseLoc =
=3D NULL);
   StmtResult ParseExprStatement(ParsedAttributes &Attrs);
   StmtResult ParseLabeledStatement(ParsedAttributes &Attr);
   StmtResult ParseCaseStatement(ParsedAttributes &Attr,
@@ -1471,22 +1540,61 @@
                                  Decl *&DeclResult,
                                  SourceLocation Loc,
                                  bool ConvertToBoolean);
-  StmtResult ParseIfStatement(ParsedAttributes &Attr);
-  StmtResult ParseSwitchStatement(ParsedAttributes &Attr);
-  StmtResult ParseWhileStatement(ParsedAttributes &Attr);
+  StmtResult ParseIfStatement(ParsedAttributes &Attr,
+                              SourceLocation *TrailingElseLoc);
+  StmtResult ParseSwitchStatement(ParsedAttributes &Attr,
+                                  SourceLocation *TrailingElseLoc);
+  StmtResult ParseWhileStatement(ParsedAttributes &Attr,
+                                 SourceLocation *TrailingElseLoc);
   StmtResult ParseDoStatement(ParsedAttributes &Attr);
-  StmtResult ParseForStatement(ParsedAttributes &Attr);
+  StmtResult ParseForStatement(ParsedAttributes &Attr,
+                               SourceLocation *TrailingElseLoc);
   StmtResult ParseGotoStatement(ParsedAttributes &Attr);
   StmtResult ParseContinueStatement(ParsedAttributes &Attr);
   StmtResult ParseBreakStatement(ParsedAttributes &Attr);
   StmtResult ParseReturnStatement(ParsedAttributes &Attr);
   StmtResult ParseAsmStatement(bool &msAsm);
   StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
-  bool ParseMicrosoftIfExistsCondition(bool& Result);
+
+  /// \brief Describes the behavior that should be taken for an __if_exists
+  /// block.
+  enum IfExistsBehavior {
+    /// \brief Parse the block; this code is always used.
+    IEB_Parse,
+    /// \brief Skip the block entirely; this code is never used.
+    IEB_Skip,
+    /// \brief Parse the block as a dependent block, which may be used in
+    /// some template instantiations but not others.
+    IEB_Dependent
+  };
+
+  /// \brief Describes the condition of a Microsoft __if_exists or
+  /// __if_not_exists block.
+  struct IfExistsCondition {
+    /// \brief The location of the initial keyword.
+    SourceLocation KeywordLoc;
+    /// \brief Whether this is an __if_exists block (rather than an
+    /// __if_not_exists block).
+    bool IsIfExists;
+
+    /// \brief Nested-name-specifier preceding the name.
+    CXXScopeSpec SS;
+
+    /// \brief The name we're looking for.
+    UnqualifiedId Name;
+
+    /// \brief The behavior of this __if_exists or __if_not_exists block
+    /// should.
+    IfExistsBehavior Behavior;
+};
+
+  bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
   void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
   void ParseMicrosoftIfExistsExternalDeclaration();
   void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
                                               AccessSpecifier& CurAS);
+  bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
+                                              bool &InitExprsOk);
   bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
                            SmallVectorImpl<Expr *> &Constraints,
                            SmallVectorImpl<Expr *> &Exprs);
@@ -1525,6 +1633,8 @@
   enum DeclSpecContext {
     DSC_normal, // normal context
     DSC_class,  // class context, enables 'friend'
+    DSC_type_specifier, // C++ type-specifier-seq
+    DSC_trailing, // C++11 trailing-type-specifier in a trailing return ty=
pe
     DSC_top_level // top-level/namespace declaration context
   };
=20
@@ -1546,13 +1656,14 @@
                                         ParsedAttributes &attrs,
                                         bool RequireSemi,
                                         ForRangeInit *FRI =3D 0);
+  bool MightBeDeclarator(unsigned Context);
   DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
                                 bool AllowFunctionDefinitions,
                                 SourceLocation *DeclEnd =3D 0,
                                 ForRangeInit *FRI =3D 0);
   Decl *ParseDeclarationAfterDeclarator(Declarator &D,
                const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplateIn=
fo());
-  bool ParseAttributesAfterDeclarator(Declarator &D);
+  bool ParseAsmAttributesAfterDeclarator(Declarator &D);
   Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
                const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplateIn=
fo());
   Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
@@ -1562,30 +1673,27 @@
   /// unless the body contains the code-completion point.
   ///
   /// \returns true if the function body was skipped.
-  bool trySkippingFunctionBodyForCodeCompletion();
+  bool trySkippingFunctionBody();
=20
   bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
                         const ParsedTemplateInfo &TemplateInfo,
-                        AccessSpecifier AS);
+                        AccessSpecifier AS, DeclSpecContext DSC);
   DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context=
);
   void ParseDeclarationSpecifiers(DeclSpec &DS,
                 const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplateI=
nfo(),
                                   AccessSpecifier AS =3D AS_none,
-                                  DeclSpecContext DSC =3D DSC_normal);
-  bool ParseOptionalTypeSpecifier(DeclSpec &DS, bool &isInvalid,
-                                  const char *&PrevSpec,
-                                  unsigned &DiagID,
-               const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplateIn=
fo(),
-                                  bool SuppressDeclarations =3D false);
+                                  DeclSpecContext DSC =3D DSC_normal,
+                                  LateParsedAttrList *LateAttrs =3D 0);
=20
-  void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS =3D AS=
_none);
+  void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS =3D AS=
_none,
+                                   DeclSpecContext DSC =3D DSC_normal);
=20
   void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
                                   Declarator::TheContext Context);
=20
   void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
-                const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplateI=
nfo(),
-                AccessSpecifier AS =3D AS_none);
+                          const ParsedTemplateInfo &TemplateInfo,
+                          AccessSpecifier AS, DeclSpecContext DSC);
   void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
   void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
                             Decl *TagDecl);
@@ -1604,7 +1712,7 @@
   bool isDeclarationSpecifier(bool DisambiguatingWithExpression =3D false);
   bool isTypeSpecifierQualifier();
   bool isTypeQualifier() const;
- =20
+
   /// isKnownToBeTypeSpecifier - Return true if we know that the specified=
 token
   /// is definitely a type-specifier.  Return false if it isn't part of a =
type
   /// specifier or if we're not sure.
@@ -1614,25 +1722,25 @@
   /// expression statement, when parsing function bodies.
   /// Returns true for declaration, false for expression.
   bool isDeclarationStatement() {
-    if (getLang().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       return isCXXDeclarationStatement();
     return isDeclarationSpecifier(true);
   }
=20
-  /// isSimpleDeclaration - Disambiguates between a declaration or an
-  /// expression, mainly used for the C 'clause-1' or the C++
+  /// isForInitDeclaration - Disambiguates between a declaration or an
+  /// expression in the context of the C 'clause-1' or the C++
   // 'for-init-statement' part of a 'for' statement.
   /// Returns true for declaration, false for expression.
-  bool isSimpleDeclaration() {
-    if (getLang().CPlusPlus)
-      return isCXXSimpleDeclaration();
+  bool isForInitDeclaration() {
+    if (getLangOpts().CPlusPlus)
+      return isCXXSimpleDeclaration(/*AllowForRangeDecl=3D*/true);
     return isDeclarationSpecifier(true);
   }
=20
   /// \brief Determine whether we are currently at the start of an Objecti=
ve-C
   /// class message that appears to be missing the open bracket '['.
   bool isStartOfObjCClassMessageMissingOpenBracket();
- =20
+
   /// \brief Starting with a scope specifier, identifier, or
   /// template-id that refers to the current class, determine whether
   /// this is a constructor declarator.
@@ -1650,7 +1758,7 @@
   /// whether the parens contain an expression or a type-id.
   /// Returns true for a type-id and false for an expression.
   bool isTypeIdInParens(bool &isAmbiguous) {
-    if (getLang().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       return isCXXTypeId(TypeIdInParens, isAmbiguous);
     isAmbiguous =3D false;
     return isTypeSpecifierQualifier();
@@ -1670,7 +1778,7 @@
   /// If during the disambiguation process a parsing error is encountered,
   /// the function returns true to let the declaration parsing code handle=
 it.
   /// Returns false if the statement is disambiguated as expression.
-  bool isCXXSimpleDeclaration();
+  bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
=20
   /// isCXXFunctionDeclarator - Disambiguates between a function declarato=
r or
   /// a constructor-style initializer, when parsing declaration statements.
@@ -1732,10 +1840,12 @@
   /// declaration specifier, TPResult::False() if it is not,
   /// TPResult::Ambiguous() if it could be either a decl-specifier or a
   /// function-style cast, and TPResult::Error() if a parsing error was
-  /// encountered.
+  /// encountered. If it could be a braced C++11 function-style cast, retu=
rns
+  /// BracedCastResult.
   /// Doesn't consume tokens.
-  TPResult isCXXDeclarationSpecifier();
- =20
+  TPResult
+  isCXXDeclarationSpecifier(TPResult BracedCastResult =3D TPResult::False(=
));
+
   // "Tentative parsing" functions, used for disambiguation. If a parsing =
error
   // is encountered they will return TPResult::Error().
   // Returning TPResult::True()/False() indicates that the ambiguity was
@@ -1744,7 +1854,7 @@
   // They all consume tokens, so backtracking should be used after calling=
 them.
=20
   TPResult TryParseDeclarationSpecifier();
-  TPResult TryParseSimpleDeclaration();
+  TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
   TPResult TryParseTypeofSpecifier();
   TPResult TryParseProtocolQualifiers();
   TPResult TryParseInitDeclaratorList();
@@ -1760,6 +1870,16 @@
                            Decl **OwnedType =3D 0);
   void ParseBlockId();
=20
+  // Check for the start of a C++11 attribute-specifier-seq in a context w=
here
+  // an attribute is not allowed.
+  bool CheckProhibitedCXX11Attribute() {
+    assert(Tok.is(tok::l_square));
+    if (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))
+      return false;
+    return DiagnoseProhibitedCXX11Attribute();
+  }
+  bool DiagnoseProhibitedCXX11Attribute();
+
   void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
     if (!attrs.Range.isValid()) return;
     DiagnoseProhibitedAttributes(attrs);
@@ -1790,35 +1910,38 @@
                              SourceLocation *EndLoc);
=20
   void MaybeParseCXX0XAttributes(Declarator &D) {
-    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
+    if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) {
       ParsedAttributesWithRange attrs(AttrFactory);
       SourceLocation endLoc;
-      ParseCXX0XAttributes(attrs, &endLoc);
+      ParseCXX11Attributes(attrs, &endLoc);
       D.takeAttributes(attrs, endLoc);
     }
   }
   void MaybeParseCXX0XAttributes(ParsedAttributes &attrs,
                                  SourceLocation *endLoc =3D 0) {
-    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
+    if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) {
       ParsedAttributesWithRange attrsWithRange(AttrFactory);
-      ParseCXX0XAttributes(attrsWithRange, endLoc);
+      ParseCXX11Attributes(attrsWithRange, endLoc);
       attrs.takeAllFrom(attrsWithRange);
     }
   }
   void MaybeParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
-                                 SourceLocation *endLoc =3D 0) {
-    if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
-      ParseCXX0XAttributes(attrs, endLoc);
+                                 SourceLocation *endLoc =3D 0,
+                                 bool OuterMightBeMessageSend =3D false) {
+    if (getLangOpts().CPlusPlus0x &&
+        isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
+      ParseCXX11Attributes(attrs, endLoc);
   }
=20
-  void ParseCXX0XAttributeSpecifier(ParsedAttributes &attrs,
+  void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
                                     SourceLocation *EndLoc =3D 0);
-  void ParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
+  void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
                             SourceLocation *EndLoc =3D 0);
+  IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
=20
   void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
                                      SourceLocation *endLoc =3D 0) {
-    if (getLang().MicrosoftExt && Tok.is(tok::l_square))
+    if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
       ParseMicrosoftAttributes(attrs, endLoc);
   }
   void ParseMicrosoftAttributes(ParsedAttributes &attrs,
@@ -1843,15 +1966,22 @@
=20
=20
   void ParseTypeofSpecifier(DeclSpec &DS);
-  void ParseDecltypeSpecifier(DeclSpec &DS);
+  SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
+  void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,=20
+                                         SourceLocation StartLoc,
+                                         SourceLocation EndLoc);
   void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
   void ParseAtomicSpecifier(DeclSpec &DS);
=20
-  ExprResult ParseAlignArgument(SourceLocation Start);
+  ExprResult ParseAlignArgument(SourceLocation Start,
+                                SourceLocation &EllipsisLoc);
   void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
                                SourceLocation *endLoc =3D 0);
=20
-  VirtSpecifiers::Specifier isCXX0XVirtSpecifier() const;
+  VirtSpecifiers::Specifier isCXX0XVirtSpecifier(const Token &Tok) const;
+  VirtSpecifiers::Specifier isCXX0XVirtSpecifier() const {
+    return isCXX0XVirtSpecifier(Tok);
+  }
   void ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS);
=20
   bool isCXX0XFinalKeyword() const;
@@ -1918,9 +2048,20 @@
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ 7: Declarations [dcl.dcl]
=20
-  bool isCXX0XAttributeSpecifier(bool FullLookahead =3D false,=20
-                                 tok::TokenKind *After =3D 0);
- =20
+  /// The kind of attribute specifier we have found.
+  enum CXX11AttributeKind {
+    /// This is not an attribute specifier.
+    CAK_NotAttributeSpecifier,
+    /// This should be treated as an attribute-specifier.
+    CAK_AttributeSpecifier,
+    /// The next tokens are '[[', but this is not an attribute-specifier. =
This
+    /// is ill-formed by C++11 [dcl.attr.grammar]p6.
+    CAK_InvalidAttributeSpecifier
+  };
+  CXX11AttributeKind
+  isCXX11AttributeSpecifier(bool Disambiguate =3D false,
+                            bool OuterMightBeMessageSend =3D false);
+
   Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
                        SourceLocation InlineLoc =3D SourceLocation());
   void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
@@ -1952,15 +2093,13 @@
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ 9: classes [class] and C structs/unions.
-  TypeResult ParseClassName(SourceLocation &EndLocation, CXXScopeSpec &SS);
   void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLo=
c,
-                           DeclSpec &DS,
-                const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplateI=
nfo(),
-                           AccessSpecifier AS =3D AS_none,
-                           bool SuppressDeclarations =3D false);
+                           DeclSpec &DS, const ParsedTemplateInfo &Templat=
eInfo,
+                           AccessSpecifier AS, bool EnteringContext,
+                           DeclSpecContext DSC);
   void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagTy=
pe,
                                    Decl *TagDecl);
-  ExprResult ParseCXXMemberInitializer(bool IsFunction,
+  ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
                                        SourceLocation &EqualLoc);
   void ParseCXXClassMemberDeclaration(AccessSpecifier AS, AttributeList *A=
ttr,
                 const ParsedTemplateInfo &TemplateInfo =3D ParsedTemplateI=
nfo(),
@@ -1972,18 +2111,20 @@
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ 10: Derived classes [class.derived]
+  TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
+                                    SourceLocation &EndLocation);
   void ParseBaseClause(Decl *ClassDecl);
   BaseResult ParseBaseSpecifier(Decl *ClassDecl);
   AccessSpecifier getAccessSpecifierIfPresent() const;
=20
-  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,=20
+  bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
+                                    SourceLocation TemplateKWLoc,
                                     IdentifierInfo *Name,
                                     SourceLocation NameLoc,
                                     bool EnteringContext,
                                     ParsedType ObjectType,
                                     UnqualifiedId &Id,
-                                    bool AssumeTemplateId,
-                                    SourceLocation TemplateKWLoc);
+                                    bool AssumeTemplateId);
   bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
                                   ParsedType ObjectType,
                                   UnqualifiedId &Result);
@@ -1991,8 +2132,9 @@
                           bool AllowDestructorName,
                           bool AllowConstructorName,
                           ParsedType ObjectType,
+                          SourceLocation& TemplateKWLoc,
                           UnqualifiedId &Result);
-   =20
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ 14: Templates [temp]
=20
@@ -2036,27 +2178,30 @@
=20
   bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
                                CXXScopeSpec &SS,
+                               SourceLocation TemplateKWLoc,
                                UnqualifiedId &TemplateName,
-                               SourceLocation TemplateKWLoc =3D SourceLoca=
tion(),
                                bool AllowTypeAnnotation =3D true);
   void AnnotateTemplateIdTokenAsType();
   bool IsTemplateArgumentList(unsigned Skip =3D 0);
   bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
   ParsedTemplateArgument ParseTemplateTemplateArgument();
   ParsedTemplateArgument ParseTemplateArgument();
-  Decl *ParseExplicitInstantiation(SourceLocation ExternLoc,
-                                        SourceLocation TemplateLoc,
-                                        SourceLocation &DeclEnd);
+  Decl *ParseExplicitInstantiation(unsigned Context,
+                                   SourceLocation ExternLoc,
+                                   SourceLocation TemplateLoc,
+                                   SourceLocation &DeclEnd,
+                                   AccessSpecifier AS =3D AS_none);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Modules
-  DeclGroupPtrTy ParseModuleImport();
- =20
+  DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
   ExprResult ParseUnaryTypeTrait();
   ExprResult ParseBinaryTypeTrait();
-
+  ExprResult ParseTypeTrait();
+ =20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // Embarcadero: Arary and Expression Traits
   ExprResult ParseArrayTypeTrait();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Rewrite/ASTConsumers.h
--- a/head/contrib/llvm/tools/clang/include/clang/Rewrite/ASTConsumers.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Rewrite/ASTConsumers.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -31,6 +31,11 @@
                                 DiagnosticsEngine &Diags,
                                 const LangOptions &LOpts,
                                 bool SilenceRewriteMacroWarning);
+ASTConsumer *CreateModernObjCRewriter(const std::string &InFile,
+                                raw_ostream *OS,
+                                DiagnosticsEngine &Diags,
+                                const LangOptions &LOpts,
+                                bool SilenceRewriteMacroWarning);
=20
 /// CreateHTMLPrinter - Create an AST consumer which rewrites source code =
to
 /// HTML with syntax highlighting suitable for viewing in a web-browser.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Rewrite/FixItRewriter.h
--- a/head/contrib/llvm/tools/clang/include/clang/Rewrite/FixItRewriter.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Rewrite/FixItRewriter.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Rewrite/Rewriter.h"
+#include "clang/Edit/EditedSource.h"
=20
 namespace clang {
=20
@@ -26,20 +27,38 @@
=20
 class FixItOptions {
 public:
+  FixItOptions() : FixWhatYouCan(false),
+                   FixOnlyWarnings(false), Silent(false) { }
+
   virtual ~FixItOptions();
=20
   /// \brief This file is about to be rewritten. Return the name of the fi=
le
   /// that is okay to write to.
-  virtual std::string RewriteFilename(const std::string &Filename) =3D 0;
+  ///
+  /// \param fd out parameter for file descriptor. After the call it may b=
e set
+  /// to an open file descriptor for the returned filename, or it will be =
-1
+  /// otherwise.
+  ///
+  virtual std::string RewriteFilename(const std::string &Filename, int &fd=
) =3D 0;
=20
   /// \brief Whether to abort fixing a file when not all errors could be f=
ixed.
   bool FixWhatYouCan;
+
+  /// \brief Whether to only fix warnings and not errors.
+  bool FixOnlyWarnings;
+
+  /// \brief If true, only pass the diagnostic to the actual diagnostic co=
nsumer
+  /// if it is an error or a fixit was applied as part of the diagnostic.
+  /// It basically silences warnings without accompanying fixits.
+  bool Silent;
 };
=20
 class FixItRewriter : public DiagnosticConsumer {
   /// \brief The diagnostics machinery.
   DiagnosticsEngine &Diags;
=20
+  edit::EditedSource Editor;
+
   /// \brief The rewriter used to perform the various code
   /// modifications.
   Rewriter Rewrite;
@@ -47,6 +66,7 @@
   /// \brief The diagnostic client that performs the actual formatting
   /// of error messages.
   DiagnosticConsumer *Client;
+  bool OwnsClient;
=20
   /// \brief Turn an input path into an output path. NULL implies overwrit=
ing
   /// the original.
@@ -55,6 +75,9 @@
   /// \brief The number of rewriter failures.
   unsigned NumFailures;
=20
+  /// \brief Whether the previous diagnostic was not passed to the consume=
r.
+  bool PrevDiagSilenced;
+
 public:
   typedef Rewriter::buffer_iterator iterator;
=20
@@ -82,7 +105,8 @@
   /// \brief Write the modified source files.
   ///
   /// \returns true if there was an error, false otherwise.
-  bool WriteFixedFiles();
+  bool WriteFixedFiles(
+         std::vector<std::pair<std::string, std::string> > *RewrittenFiles=
 =3D 0);
=20
   /// IncludeInDiagnosticCounts - This method (whose default implementation
   /// returns true) indicates whether the diagnostics handled by this
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Rewrite/FrontendActions.h
--- a/head/contrib/llvm/tools/clang/include/clang/Rewrite/FrontendActions.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Rewrite/FrontendActions.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -28,8 +28,8 @@
=20
 class FixItAction : public ASTFrontendAction {
 protected:
-  llvm::OwningPtr<FixItRewriter> Rewriter;
-  llvm::OwningPtr<FixItOptions> FixItOpts;
+  OwningPtr<FixItRewriter> Rewriter;
+  OwningPtr<FixItOptions> FixItOpts;
=20
   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
                                          StringRef InFile);
@@ -46,6 +46,17 @@
   ~FixItAction();
 };
=20
+/// \brief Emits changes to temporary files and uses them for the original
+/// frontend action.
+class FixItRecompile : public WrapperFrontendAction {
+public:
+  FixItRecompile(FrontendAction *WrappedAction)
+    : WrapperFrontendAction(WrappedAction) {}
+
+protected:
+  virtual bool BeginInvocation(CompilerInstance &CI);
+};
+
 class RewriteObjCAction : public ASTFrontendAction {
 protected:
   virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Rewrite/TokenRewriter.h
--- a/head/contrib/llvm/tools/clang/include/clang/Rewrite/TokenRewriter.h	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Rewrite/TokenRewriter.h	T=
ue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
=20
     /// ScratchBuf - This is the buffer that we create scratch tokens from.
     ///
-    llvm::OwningPtr<ScratchBuffer> ScratchBuf;
+    OwningPtr<ScratchBuffer> ScratchBuf;
=20
     TokenRewriter(const TokenRewriter&);  // DO NOT IMPLEMENT
     void operator=3D(const TokenRewriter&); // DO NOT IMPLEMENT.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/AttributeList.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/AttributeList.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/AttributeList.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -85,6 +85,8 @@
   /// \brief The location of the 'unavailable' keyword in an
   /// availability attribute.
   SourceLocation UnavailableLoc;
+ =20
+  const Expr *MessageExpr;
=20
   /// The next attribute in the current position.
   AttributeList *NextInPosition;
@@ -138,13 +140,15 @@
                 const AvailabilityChange &introduced,
                 const AvailabilityChange &deprecated,
                 const AvailabilityChange &obsoleted,
-                SourceLocation unavailable,
+                SourceLocation unavailable,=20
+                const Expr *messageExpr,
                 bool declspec, bool cxx0x)
     : AttrName(attrName), ScopeName(scopeName), ParmName(parmName),
       AttrRange(attrRange), ScopeLoc(scopeLoc), ParmLoc(parmLoc),
       NumArgs(0), DeclspecAttribute(declspec), CXX0XAttribute(cxx0x),
       Invalid(false), UsedAsTypeAttr(false), IsAvailability(true),
-      UnavailableLoc(unavailable), NextInPosition(0), NextInPool(0) {
+      UnavailableLoc(unavailable), MessageExpr(messageExpr),
+      NextInPosition(0), NextInPool(0) {
     new (&getAvailabilitySlot(IntroducedSlot)) AvailabilityChange(introduc=
ed);
     new (&getAvailabilitySlot(DeprecatedSlot)) AvailabilityChange(deprecat=
ed);
     new (&getAvailabilitySlot(ObsoletedSlot)) AvailabilityChange(obsoleted=
);
@@ -155,122 +159,21 @@
   friend class AttributeFactory;
=20
 public:
-  enum Kind {             // Please keep this list alphabetized.
-    AT_acquired_after,
-    AT_acquired_before,
-    AT_address_space,
-    AT_alias,
-    AT_aligned,
-    AT_always_inline,
-    AT_analyzer_noreturn,
-    AT_annotate,
-    AT_arc_weakref_unavailable,
-    AT_availability,      // Clang-specific
-    AT_base_check,
-    AT_blocks,
-    AT_carries_dependency,
-    AT_cdecl,
-    AT_cf_audited_transfer,     // Clang-specific.
-    AT_cf_consumed,             // Clang-specific.
-    AT_cf_returns_autoreleased, // Clang-specific.
-    AT_cf_returns_not_retained, // Clang-specific.
-    AT_cf_returns_retained,     // Clang-specific.
-    AT_cf_unknown_transfer,     // Clang-specific.
-    AT_cleanup,
-    AT_common,
-    AT_const,
-    AT_constant,
-    AT_constructor,
-    AT_deprecated,
-    AT_destructor,
-    AT_device,
-    AT_dllexport,
-    AT_dllimport,
-    AT_exclusive_lock_function,
-    AT_exclusive_locks_required,
-    AT_exclusive_trylock_function,
-    AT_ext_vector_type,
-    AT_fastcall,
-    AT_format,
-    AT_format_arg,
-    AT_global,
-    AT_gnu_inline,
-    AT_guarded_by,
-    AT_guarded_var,
-    AT_host,
-    AT_IBAction,          // Clang-specific.
-    AT_IBOutlet,          // Clang-specific.
-    AT_IBOutletCollection, // Clang-specific.
-    AT_init_priority,
-    AT_launch_bounds,
-    AT_lock_returned,
-    AT_lockable,
-    AT_locks_excluded,
-    AT_malloc,
-    AT_may_alias,
-    AT_mode,
-    AT_MsStruct,
-    AT_naked,
-    AT_neon_polyvector_type,    // Clang-specific.
-    AT_neon_vector_type,        // Clang-specific.
-    AT_no_instrument_function,
-    AT_no_thread_safety_analysis,
-    AT_nocommon,
-    AT_nodebug,
-    AT_noinline,
-    AT_nonnull,
-    AT_noreturn,
-    AT_nothrow,
-    AT_ns_bridged,              // Clang-specific.
-    AT_ns_consumed,             // Clang-specific.
-    AT_ns_consumes_self,        // Clang-specific.
-    AT_ns_returns_autoreleased, // Clang-specific.
-    AT_ns_returns_not_retained, // Clang-specific.
-    AT_ns_returns_retained,     // Clang-specific.
-    AT_nsobject,
-    AT_objc_exception,
-    AT_objc_gc,
-    AT_objc_method_family,
-    AT_objc_ownership,          // Clang-specific.
-    AT_objc_precise_lifetime,   // Clang-specific.
-    AT_objc_returns_inner_pointer, // Clang-specific.
-    AT_opencl_image_access,     // OpenCL-specific.
-    AT_opencl_kernel_function,  // OpenCL-specific.
-    AT_overloadable,       // Clang-specific.
-    AT_ownership_holds,    // Clang-specific.
-    AT_ownership_returns,  // Clang-specific.
-    AT_ownership_takes,    // Clang-specific.
-    AT_packed,
-    AT_pascal,
-    AT_pcs,  // ARM specific
-    AT_pt_guarded_by,
-    AT_pt_guarded_var,
-    AT_pure,
-    AT_regparm,
-    AT_reqd_wg_size,
-    AT_scoped_lockable,
-    AT_section,
-    AT_sentinel,
-    AT_shared,
-    AT_shared_lock_function,
-    AT_shared_locks_required,
-    AT_shared_trylock_function,
-    AT_stdcall,
-    AT_thiscall,
-    AT_transparent_union,
-    AT_unavailable,
-    AT_unlock_function,
-    AT_unused,
-    AT_used,
-    AT_uuid,
-    AT_vecreturn,     // PS3 PPU-specific.
-    AT_vector_size,
-    AT_visibility,
-    AT_warn_unused_result,
-    AT_weak,
-    AT_weak_import,
-    AT_weakref,
-    AT_returns_twice,
+  enum Kind {          =20
+    #define PARSED_ATTR(NAME) AT_##NAME,
+    #include "clang/Sema/AttrParsedAttrList.inc"
+    PARSED_ATTR(address_space)
+    PARSED_ATTR(base_check)
+    PARSED_ATTR(cf_returns_autoreleased)
+    PARSED_ATTR(ext_vector_type)
+    PARSED_ATTR(mode)
+    PARSED_ATTR(neon_polyvector_type)
+    PARSED_ATTR(neon_vector_type)
+    PARSED_ATTR(objc_gc)
+    PARSED_ATTR(objc_ownership)
+    PARSED_ATTR(opencl_image_access)
+    PARSED_ATTR(vector_size)
+    #undef PARSED_ATTR
     IgnoredAttribute,
     UnknownAttribute
   };
@@ -371,6 +274,11 @@
     assert(getKind() =3D=3D AT_availability && "Not an availability attrib=
ute");
     return UnavailableLoc;
   }
+ =20
+  const Expr * getMessageExpr() const {
+    assert(getKind() =3D=3D AT_availability && "Not an availability attrib=
ute");
+    return MessageExpr;
+  }
 };
=20
 /// A factory, from which one makes pools, from which one creates
@@ -492,13 +400,14 @@
                         const AvailabilityChange &deprecated,
                         const AvailabilityChange &obsoleted,
                         SourceLocation unavailable,
+                        const Expr *MessageExpr,
                         bool declspec =3D false, bool cxx0x =3D false) {
     void *memory =3D allocate(AttributeFactory::AvailabilityAllocSize);
     return add(new (memory) AttributeList(attrName, attrRange,
                                           scopeName, scopeLoc,
                                           parmName, parmLoc,
                                           introduced, deprecated, obsolete=
d,
-                                          unavailable,
+                                          unavailable, MessageExpr,
                                           declspec, cxx0x));
   }
=20
@@ -616,10 +525,12 @@
                         const AvailabilityChange &deprecated,
                         const AvailabilityChange &obsoleted,
                         SourceLocation unavailable,
+                        const Expr *MessageExpr,
                         bool declspec =3D false, bool cxx0x =3D false) {
     AttributeList *attr =3D
       pool.create(attrName, attrRange, scopeName, scopeLoc, parmName, parm=
Loc,
                   introduced, deprecated, obsoleted, unavailable,
+                  MessageExpr,
                   declspec, cxx0x);
     add(attr);
     return attr;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/CodeCompleteConsumer.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/CodeCompleteConsumer=
.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/CodeCompleteConsumer=
.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,14 +24,14 @@
 namespace clang {
=20
 class Decl;
- =20
+
 /// \brief Default priority values for code-completion results based
 /// on their kind.
 enum {
   /// \brief Priority for the next initialization in a constructor initial=
izer
   /// list.
   CCP_NextInitializer =3D 7,
-  /// \brief Priority for an enumeration constant inside a switch whose=20
+  /// \brief Priority for an enumeration constant inside a switch whose
   /// condition is of the enumeration type.
   CCP_EnumInCase =3D 7,
   /// \brief Priority for a send-to-super completion.
@@ -59,7 +59,7 @@
   /// \brief Priority for a result that isn't likely to be what the user w=
ants,
   /// but is included for completeness.
   CCP_Unlikely =3D 80,
- =20
+
   /// \brief Priority for the Objective-C "_cmd" implicit parameter.
   CCP_ObjC_cmd =3D CCP_Unlikely
 };
@@ -76,15 +76,15 @@
   /// of the current method, which might imply that some kind of delegation
   /// is occurring.
   CCD_SelectorMatch =3D -3,
- =20
+
   /// \brief Adjustment to the "bool" type in Objective-C, where the typed=
ef
   /// "BOOL" is preferred.
   CCD_bool_in_ObjC =3D 1,
- =20
+
   /// \brief Adjustment for KVC code pattern priorities when it doesn't lo=
ok
   /// like the
   CCD_ProbablyNotObjCCollection =3D 15,
- =20
+
   /// \brief An Objective-C method being used as a property.
   CCD_MethodAsProperty =3D 2
 };
@@ -114,14 +114,14 @@
   STC_Record,
   STC_Void
 };
- =20
+
 /// \brief Determine the simplified type class of the given canonical type.
 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
- =20
+
 /// \brief Determine the type that this declaration will have if it is used
 /// as a type or in an expression.
 QualType getDeclUsageType(ASTContext &C, NamedDecl *ND);
- =20
+
 /// \brief Determine the priority to be given to a macro code completion r=
esult
 /// with the given name.
 ///
@@ -131,14 +131,14 @@
 ///
 /// \param PreferredTypeIsPointer Whether the preferred type for the conte=
xt
 /// of this macro is a pointer type.
-unsigned getMacroUsagePriority(StringRef MacroName,=20
+unsigned getMacroUsagePriority(StringRef MacroName,
                                const LangOptions &LangOpts,
                                bool PreferredTypeIsPointer =3D false);
=20
 /// \brief Determine the libclang cursor kind associated with the given
 /// declaration.
 CXCursorKind getCursorKindForDecl(Decl *D);
- =20
+
 class FunctionDecl;
 class FunctionType;
 class FunctionTemplateDecl;
@@ -182,22 +182,22 @@
     /// \brief Code completion occurred on the right-hand side of a member
     /// access expression using the dot operator.
     ///
-    /// The results of this completion are the members of the type being=20
-    /// accessed. The type itself is available via=20
+    /// The results of this completion are the members of the type being
+    /// accessed. The type itself is available via
     /// \c CodeCompletionContext::getType().
     CCC_DotMemberAccess,
     /// \brief Code completion occurred on the right-hand side of a member
     /// access expression using the arrow operator.
     ///
-    /// The results of this completion are the members of the type being=20
-    /// accessed. The type itself is available via=20
+    /// The results of this completion are the members of the type being
+    /// accessed. The type itself is available via
     /// \c CodeCompletionContext::getType().
     CCC_ArrowMemberAccess,
     /// \brief Code completion occurred on the right-hand side of an Objec=
tive-C
     /// property access expression.
     ///
-    /// The results of this completion are the members of the type being=20
-    /// accessed. The type itself is available via=20
+    /// The results of this completion are the members of the type being
+    /// accessed. The type itself is available via
     /// \c CodeCompletionContext::getType().
     CCC_ObjCPropertyAccess,
     /// \brief Code completion occurred after the "enum" keyword, to indic=
ate
@@ -228,7 +228,7 @@
     CCC_MacroNameUse,
     /// \brief Code completion occurred within a preprocessor expression.
     CCC_PreprocessorExpression,
-    /// \brief Code completion occurred where a preprocessor directive is=20
+    /// \brief Code completion occurred where a preprocessor directive is
     /// expected.
     CCC_PreprocessorDirective,
     /// \brief Code completion occurred in a context where natural languag=
e is
@@ -246,14 +246,14 @@
     CCC_ParenthesizedExpression,
     /// \brief Code completion where an Objective-C instance message is ex=
pcted.
     CCC_ObjCInstanceMessage,
-    /// \brief Code completion where an Objective-C class message is expec=
ted.=20
+    /// \brief Code completion where an Objective-C class message is expec=
ted.
     CCC_ObjCClassMessage,
     /// \brief Code completion where the name of an Objective-C class is
     /// expected.
     CCC_ObjCInterfaceName,
     /// \brief Code completion where an Objective-C category name is expec=
ted.
     CCC_ObjCCategoryName,
-    /// \brief An unknown context, in which we are recovering from a parsi=
ng=20
+    /// \brief An unknown context, in which we are recovering from a parsi=
ng
     /// error and don't know which completions we should give.
     CCC_Recovery
   };
@@ -264,27 +264,27 @@
   /// \brief The type that would prefer to see at this point (e.g., the ty=
pe
   /// of an initializer or function parameter).
   QualType PreferredType;
- =20
+
   /// \brief The type of the base object in a member access expression.
   QualType BaseType;
- =20
+
   /// \brief The identifiers for Objective-C selector parts.
   IdentifierInfo **SelIdents;
- =20
+
   /// \brief The number of Objective-C selector parts.
   unsigned NumSelIdents;
- =20
+
 public:
   /// \brief Construct a new code-completion context of the given kind.
-  CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(NULL),=20
+  CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(NULL),
                                           NumSelIdents(0) { }
- =20
+
   /// \brief Construct a new code-completion context of the given kind.
   CodeCompletionContext(enum Kind Kind, QualType T,
                         IdentifierInfo **SelIdents =3D NULL,
                         unsigned NumSelIdents =3D 0) : Kind(Kind),
                                                      SelIdents(SelIdents),
-                                                    NumSelIdents(NumSelIde=
nts) {=20
+                                                    NumSelIdents(NumSelIde=
nts) {
     if (Kind =3D=3D CCC_DotMemberAccess || Kind =3D=3D CCC_ArrowMemberAcce=
ss ||
         Kind =3D=3D CCC_ObjCPropertyAccess || Kind =3D=3D CCC_ObjCClassMes=
sage ||
         Kind =3D=3D CCC_ObjCInstanceMessage)
@@ -292,22 +292,22 @@
     else
       PreferredType =3D T;
   }
- =20
+
   /// \brief Retrieve the kind of code-completion context.
   enum Kind getKind() const { return Kind; }
- =20
+
   /// \brief Retrieve the type that this expression would prefer to have, =
e.g.,
   /// if the expression is a variable initializer or a function argument, =
the
   /// type of the corresponding variable or function parameter.
   QualType getPreferredType() const { return PreferredType; }
- =20
-  /// \brief Retrieve the type of the base object in a member-access=20
+
+  /// \brief Retrieve the type of the base object in a member-access
   /// expression.
   QualType getBaseType() const { return BaseType; }
- =20
+
   /// \brief Retrieve the Objective-C selector identifiers.
   IdentifierInfo **getSelIdents() const { return SelIdents; }
- =20
+
   /// \brief Retrieve the number of Objective-C selector identifiers.
   unsigned getNumSelIdents() const { return NumSelIdents; }
=20
@@ -320,10 +320,10 @@
 /// \brief A "string" used to describe how code completion can
 /// be performed for an entity.
 ///
-/// A code completion string typically shows how a particular entity can b=
e=20
+/// A code completion string typically shows how a particular entity can be
 /// used. For example, the code completion string for a function would show
-/// the syntax to call it, including the parentheses, placeholders for the=20
-/// arguments, etc. =20
+/// the syntax to call it, including the parentheses, placeholders for the
+/// arguments, etc.
 class CodeCompletionString {
 public:
   /// \brief The different kinds of "chunks" that can occur within a code
@@ -340,7 +340,7 @@
     /// an optional code completion string that describes the default argu=
ments
     /// in a function call.
     CK_Optional,
-    /// \brief A string that acts as a placeholder for, e.g., a function=20
+    /// \brief A string that acts as a placeholder for, e.g., a function
     /// call argument.
     CK_Placeholder,
     /// \brief A piece of text that describes something about the result b=
ut
@@ -383,30 +383,30 @@
     /// platform).
     CK_VerticalSpace
   };
- =20
+
   /// \brief One piece of the code completion string.
   struct Chunk {
-    /// \brief The kind of data stored in this piece of the code completio=
n=20
+    /// \brief The kind of data stored in this piece of the code completion
     /// string.
     ChunkKind Kind;
-   =20
+
     union {
       /// \brief The text string associated with a CK_Text, CK_Placeholder,
       /// CK_Informative, or CK_Comma chunk.
-      /// The string is owned by the chunk and will be deallocated=20
+      /// The string is owned by the chunk and will be deallocated
       /// (with delete[]) when the chunk is destroyed.
       const char *Text;
-     =20
+
       /// \brief The code completion string associated with a CK_Optional =
chunk.
       /// The optional code completion string is owned by the chunk, and w=
ill
       /// be deallocated (with delete) when the chunk is destroyed.
       CodeCompletionString *Optional;
     };
-   =20
+
     Chunk() : Kind(CK_Text), Text(0) { }
-   =20
-    Chunk(ChunkKind Kind, const char *Text =3D "");
-   =20
+
+    explicit Chunk(ChunkKind Kind, const char *Text =3D "");
+
     /// \brief Create a new text chunk.
     static Chunk CreateText(const char *Text);
=20
@@ -425,49 +425,56 @@
     /// \brief Create a new current-parameter chunk.
     static Chunk CreateCurrentParameter(const char *CurrentParameter);
   };
- =20
+
 private:
   /// \brief The number of chunks stored in this string.
   unsigned NumChunks : 16;
- =20
+
   /// \brief The number of annotations for this code-completion result.
   unsigned NumAnnotations : 16;
=20
   /// \brief The priority of this code-completion string.
-  unsigned Priority : 30;
- =20
+  unsigned Priority : 16;
+
   /// \brief The availability of this code-completion result.
   unsigned Availability : 2;
=20
+  /// \brief The kind of the parent context.
+  unsigned ParentKind : 14;
+ =20
+  /// \brief The name of the parent context.
+  StringRef ParentName;
+ =20
   CodeCompletionString(const CodeCompletionString &); // DO NOT IMPLEMENT
   CodeCompletionString &operator=3D(const CodeCompletionString &); // DITTO
- =20
+
   CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
                        unsigned Priority, CXAvailabilityKind Availability,
-                       const char **Annotations, unsigned NumAnnotations);
+                       const char **Annotations, unsigned NumAnnotations,
+                       CXCursorKind ParentKind, StringRef ParentName);
   ~CodeCompletionString() { }
- =20
+
   friend class CodeCompletionBuilder;
   friend class CodeCompletionResult;
- =20
+
 public:
   typedef const Chunk *iterator;
   iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1=
); }
   iterator end() const { return begin() + NumChunks; }
   bool empty() const { return NumChunks =3D=3D 0; }
   unsigned size() const { return NumChunks; }
- =20
+
   const Chunk &operator[](unsigned I) const {
     assert(I < size() && "Chunk index out-of-range");
     return begin()[I];
   }
- =20
+
   /// \brief Returns the text in the TypedText chunk.
   const char *getTypedText() const;
=20
   /// \brief Retrieve the priority of this code completion result.
   unsigned getPriority() const { return Priority; }
- =20
+
   /// \brief Retrieve the availability of this code completion result.
   unsigned getAvailability() const { return Availability; }
=20
@@ -476,106 +483,156 @@
=20
   /// \brief Retrieve the annotation string specified by \c AnnotationNr.
   const char *getAnnotation(unsigned AnnotationNr) const;
+
+  /// \brief Retrieve parent context's cursor kind.
+  CXCursorKind getParentContextKind() const {
+    return (CXCursorKind)ParentKind;
+  }
+ =20
+  /// \brief Retrieve the name of the parent context.
+  StringRef getParentContextName() const {
+    return ParentName;
+  }
  =20
   /// \brief Retrieve a string representation of the code completion strin=
g,
   /// which is mainly useful for debugging.
-  std::string getAsString() const;  =20
+  std::string getAsString() const;
 };
=20
 /// \brief An allocator used specifically for the purpose of code completi=
on.
-class CodeCompletionAllocator : public llvm::BumpPtrAllocator {=20
+class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
 public:
   /// \brief Copy the given string into this allocator.
   const char *CopyString(StringRef String);
=20
   /// \brief Copy the given string into this allocator.
   const char *CopyString(Twine String);
- =20
+
   // \brief Copy the given string into this allocator.
   const char *CopyString(const char *String) {
     return CopyString(StringRef(String));
   }
- =20
+
   /// \brief Copy the given string into this allocator.
   const char *CopyString(const std::string &String) {
     return CopyString(StringRef(String));
   }
 };
- =20
+
+/// \brief Allocator for a cached set of global code completions.
+class GlobalCodeCompletionAllocator=20
+  : public CodeCompletionAllocator,
+    public RefCountedBase<GlobalCodeCompletionAllocator>
+{
+
+};
+
+class CodeCompletionTUInfo {
+  llvm::DenseMap<DeclContext *, StringRef> ParentNames;
+  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef;
+
+public:
+  explicit CodeCompletionTUInfo(
+                    IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allo=
cator)
+    : AllocatorRef(Allocator) { }
+
+  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() cons=
t {
+    return AllocatorRef;
+  }
+  CodeCompletionAllocator &getAllocator() const {
+    assert(AllocatorRef);
+    return *AllocatorRef;
+  }
+
+  StringRef getParentName(DeclContext *DC);
+};
+
+} // end namespace clang
+
+namespace llvm {
+  template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
+    static const bool value =3D true;
+  };
+}
+
+namespace clang {
+
 /// \brief A builder class used to construct new code-completion strings.
 class CodeCompletionBuilder {
-public: =20
+public:
   typedef CodeCompletionString::Chunk Chunk;
- =20
+
 private:
   CodeCompletionAllocator &Allocator;
+  CodeCompletionTUInfo &CCTUInfo;
   unsigned Priority;
   CXAvailabilityKind Availability;
+  CXCursorKind ParentKind;
+  StringRef ParentName;
  =20
   /// \brief The chunks stored in this string.
   SmallVector<Chunk, 4> Chunks;
=20
   SmallVector<const char *, 2> Annotations;
- =20
+
 public:
-  CodeCompletionBuilder(CodeCompletionAllocator &Allocator)=20
-    : Allocator(Allocator), Priority(0), Availability(CXAvailability_Avail=
able){
-  }
- =20
   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
-                        unsigned Priority, CXAvailabilityKind Availability=
)=20
-    : Allocator(Allocator), Priority(Priority), Availability(Availability)=
 { }
+                        CodeCompletionTUInfo &CCTUInfo)
+    : Allocator(Allocator), CCTUInfo(CCTUInfo),
+      Priority(0), Availability(CXAvailability_Available),
+      ParentKind(CXCursor_NotImplemented) { }
+
+  CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
+                        CodeCompletionTUInfo &CCTUInfo,
+                        unsigned Priority, CXAvailabilityKind Availability)
+    : Allocator(Allocator), CCTUInfo(CCTUInfo),
+      Priority(Priority), Availability(Availability),
+      ParentKind(CXCursor_NotImplemented) { }
=20
   /// \brief Retrieve the allocator into which the code completion
   /// strings should be allocated.
   CodeCompletionAllocator &getAllocator() const { return Allocator; }
- =20
-  /// \brief Take the resulting completion string.=20
+
+  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo;=
 }
+
+  /// \brief Take the resulting completion string.
   ///
   /// This operation can only be performed once.
   CodeCompletionString *TakeString();
- =20
+
   /// \brief Add a new typed-text chunk.
-  void AddTypedTextChunk(const char *Text) {=20
-    Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
-  }
- =20
+  void AddTypedTextChunk(const char *Text);
+
   /// \brief Add a new text chunk.
-  void AddTextChunk(const char *Text) {=20
-    Chunks.push_back(Chunk::CreateText(Text));=20
-  }
+  void AddTextChunk(const char *Text);
=20
   /// \brief Add a new optional chunk.
-  void AddOptionalChunk(CodeCompletionString *Optional) {
-    Chunks.push_back(Chunk::CreateOptional(Optional));
-  }
- =20
+  void AddOptionalChunk(CodeCompletionString *Optional);
+
   /// \brief Add a new placeholder chunk.
-  void AddPlaceholderChunk(const char *Placeholder) {
-    Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
-  }
- =20
+  void AddPlaceholderChunk(const char *Placeholder);
+
   /// \brief Add a new informative chunk.
-  void AddInformativeChunk(const char *Text) {
-    Chunks.push_back(Chunk::CreateInformative(Text));
-  }
- =20
+  void AddInformativeChunk(const char *Text);
+
   /// \brief Add a new result-type chunk.
-  void AddResultTypeChunk(const char *ResultType) {
-    Chunks.push_back(Chunk::CreateResultType(ResultType));
-  }
- =20
+  void AddResultTypeChunk(const char *ResultType);
+
   /// \brief Add a new current-parameter chunk.
-  void AddCurrentParameterChunk(const char *CurrentParameter) {
-    Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
-  }
- =20
+  void AddCurrentParameterChunk(const char *CurrentParameter);
+
   /// \brief Add a new chunk.
-  void AddChunk(Chunk C) { Chunks.push_back(C); }
+  void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text =3D "=
");
=20
   void AddAnnotation(const char *A) { Annotations.push_back(A); }
+
+  /// \brief Add the parent context information to this code completion.
+  void addParentContext(DeclContext *DC);
+ =20
+  CXCursorKind getParentKind() const { return ParentKind; }
+  StringRef getParentName() const { return ParentName; }
 };
- =20
+
 /// \brief Captures a result of code completion.
 class CodeCompletionResult {
 public:
@@ -586,23 +643,23 @@
     RK_Macro,           //< Refers to a macro
     RK_Pattern          //< Refers to a precomputed pattern.
   };
-   =20
+
   /// \brief The kind of result stored here.
   ResultKind Kind;
-   =20
+
+  /// \brief When Kind =3D=3D RK_Declaration or RK_Pattern, the declaratio=
n we are
+  /// referring to. In the latter case, the declaration might be NULL.
+  NamedDecl *Declaration;
+
   union {
-    /// \brief When Kind =3D=3D RK_Declaration, the declaration we are ref=
erring
-    /// to.
-    NamedDecl *Declaration;
-     =20
-    /// \brief When Kind =3D=3D RK_Keyword, the string representing the ke=
yword=20
+    /// \brief When Kind =3D=3D RK_Keyword, the string representing the ke=
yword
     /// or symbol's spelling.
     const char *Keyword;
-     =20
+
     /// \brief When Kind =3D=3D RK_Pattern, the code-completion string that
     /// describes the completion text to insert.
     CodeCompletionString *Pattern;
-     =20
+
     /// \brief When Kind =3D=3D RK_Macro, the identifier that refers to a =
macro.
     IdentifierInfo *Macro;
   };
@@ -612,21 +669,21 @@
=20
   /// \brief The cursor kind that describes this result.
   CXCursorKind CursorKind;
-   =20
+
   /// \brief The availability of this result.
   CXAvailabilityKind Availability;
-   =20
+
   /// \brief Specifies which parameter (of a function, Objective-C method,
   /// macro, etc.) we should start with when formatting the result.
   unsigned StartParameter;
-   =20
+
   /// \brief Whether this result is hidden by another name.
   bool Hidden : 1;
-   =20
+
   /// \brief Whether this result was found via lookup into a base class.
   bool QualifierIsInformative : 1;
-   =20
-  /// \brief Whether this declaration is the beginning of a=20
+
+  /// \brief Whether this declaration is the beginning of a
   /// nested-name-specifier and, therefore, should be followed by '::'.
   bool StartsNestedNameSpecifier : 1;
=20
@@ -637,43 +694,43 @@
   /// \brief Whether we're completing a declaration of the given entity,
   /// rather than a use of that entity.
   bool DeclaringEntity : 1;
-   =20
+
   /// \brief If the result should have a nested-name-specifier, this is it.
-  /// When \c QualifierIsInformative, the nested-name-specifier is=20
+  /// When \c QualifierIsInformative, the nested-name-specifier is
   /// informative rather than required.
   NestedNameSpecifier *Qualifier;
-   =20
+
   /// \brief Build a result that refers to a declaration.
-  CodeCompletionResult(NamedDecl *Declaration,=20
+  CodeCompletionResult(NamedDecl *Declaration,
                        NestedNameSpecifier *Qualifier =3D 0,
                        bool QualifierIsInformative =3D false,
                        bool Accessible =3D true)
-    : Kind(RK_Declaration), Declaration(Declaration),=20
-      Priority(getPriorityFromDecl(Declaration)),=20
-      Availability(CXAvailability_Available), StartParameter(0),=20
+    : Kind(RK_Declaration), Declaration(Declaration),
+      Priority(getPriorityFromDecl(Declaration)),
+      Availability(CXAvailability_Available), StartParameter(0),
       Hidden(false), QualifierIsInformative(QualifierIsInformative),
       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
-      DeclaringEntity(false), Qualifier(Qualifier) {=20
+      DeclaringEntity(false), Qualifier(Qualifier) {
     computeCursorKindAndAvailability(Accessible);
   }
-   =20
+
   /// \brief Build a result that refers to a keyword or symbol.
   CodeCompletionResult(const char *Keyword, unsigned Priority =3D CCP_Keyw=
ord)
-    : Kind(RK_Keyword), Keyword(Keyword), Priority(Priority),=20
-      Availability(CXAvailability_Available),=20
-      StartParameter(0), Hidden(false), QualifierIsInformative(0),=20
+    : Kind(RK_Keyword), Declaration(0), Keyword(Keyword), Priority(Priorit=
y),
+      Availability(CXAvailability_Available),
+      StartParameter(0), Hidden(false), QualifierIsInformative(0),
       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
       DeclaringEntity(false), Qualifier(0) {
     computeCursorKindAndAvailability();
   }
-   =20
+
   /// \brief Build a result that refers to a macro.
   CodeCompletionResult(IdentifierInfo *Macro, unsigned Priority =3D CCP_Ma=
cro)
-    : Kind(RK_Macro), Macro(Macro), Priority(Priority),=20
-      Availability(CXAvailability_Available), StartParameter(0),=20
-      Hidden(false), QualifierIsInformative(0),=20
+    : Kind(RK_Macro), Declaration(0), Macro(Macro), Priority(Priority),
+      Availability(CXAvailability_Available), StartParameter(0),
+      Hidden(false), QualifierIsInformative(0),
       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
-      DeclaringEntity(false), Qualifier(0) {=20
+      DeclaringEntity(false), Qualifier(0) {
     computeCursorKindAndAvailability();
   }
=20
@@ -681,27 +738,40 @@
   CodeCompletionResult(CodeCompletionString *Pattern,
                        unsigned Priority =3D CCP_CodePattern,
                        CXCursorKind CursorKind =3D CXCursor_NotImplemented,
-                   CXAvailabilityKind Availability =3D CXAvailability_Avai=
lable)
-    : Kind(RK_Pattern), Pattern(Pattern), Priority(Priority),=20
-      CursorKind(CursorKind), Availability(Availability), StartParameter(0=
),=20
-      Hidden(false), QualifierIsInformative(0),=20
-      StartsNestedNameSpecifier(false), AllParametersAreInformative(false)=
,=20
-      DeclaringEntity(false), Qualifier(0)=20
-  {=20
+                   CXAvailabilityKind Availability =3D CXAvailability_Avai=
lable,
+                       NamedDecl *D =3D 0)
+    : Kind(RK_Pattern), Declaration(D), Pattern(Pattern), Priority(Priorit=
y),
+      CursorKind(CursorKind), Availability(Availability), StartParameter(0=
),
+      Hidden(false), QualifierIsInformative(0),
+      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
+      DeclaringEntity(false), Qualifier(0)
+  {
   }
-   =20
+
+  /// \brief Build a result that refers to a pattern with an associated
+  /// declaration.
+  CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D,
+                       unsigned Priority)
+    : Kind(RK_Pattern), Declaration(D), Pattern(Pattern), Priority(Priorit=
y),
+      Availability(CXAvailability_Available), StartParameter(0),
+      Hidden(false), QualifierIsInformative(false),
+      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
+      DeclaringEntity(false), Qualifier(0) {
+    computeCursorKindAndAvailability();
+  } =20
+ =20
   /// \brief Retrieve the declaration stored in this result.
   NamedDecl *getDeclaration() const {
     assert(Kind =3D=3D RK_Declaration && "Not a declaration result");
     return Declaration;
   }
-   =20
+
   /// \brief Retrieve the keyword stored in this result.
   const char *getKeyword() const {
     assert(Kind =3D=3D RK_Keyword && "Not a keyword result");
     return Keyword;
   }
-   =20
+
   /// \brief Create a new code-completion string that describes how to ins=
ert
   /// this result into a program.
   ///
@@ -710,37 +780,42 @@
   /// \param Allocator The allocator that will be used to allocate the
   /// string itself.
   CodeCompletionString *CreateCodeCompletionString(Sema &S,
-                                           CodeCompletionAllocator &Alloca=
tor);
-   =20
+                                           CodeCompletionAllocator &Alloca=
tor,
+                                           CodeCompletionTUInfo &CCTUInfo);
+  CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
+                                                   Preprocessor &PP,
+                                           CodeCompletionAllocator &Alloca=
tor,
+                                           CodeCompletionTUInfo &CCTUInfo);
+
   /// \brief Determine a base priority for the given declaration.
   static unsigned getPriorityFromDecl(NamedDecl *ND);
-   =20
+
 private:
   void computeCursorKindAndAvailability(bool Accessible =3D true);
 };
- =20
+
 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &=
Y);
- =20
-inline bool operator>(const CodeCompletionResult &X,=20
+
+inline bool operator>(const CodeCompletionResult &X,
                       const CodeCompletionResult &Y) {
   return Y < X;
 }
- =20
-inline bool operator<=3D(const CodeCompletionResult &X,=20
+
+inline bool operator<=3D(const CodeCompletionResult &X,
                       const CodeCompletionResult &Y) {
   return !(Y < X);
 }
=20
-inline bool operator>=3D(const CodeCompletionResult &X,=20
+inline bool operator>=3D(const CodeCompletionResult &X,
                        const CodeCompletionResult &Y) {
   return !(X < Y);
 }
=20
- =20
-raw_ostream &operator<<(raw_ostream &OS,=20
+
+raw_ostream &operator<<(raw_ostream &OS,
                               const CodeCompletionString &CCS);
=20
-/// \brief Abstract interface for a consumer of code-completion=20
+/// \brief Abstract interface for a consumer of code-completion
 /// information.
 class CodeCompleteConsumer {
 protected:
@@ -750,15 +825,15 @@
   /// \brief Whether to include code patterns (such as for loops) within
   /// the completion results.
   bool IncludeCodePatterns;
- =20
+
   /// \brief Whether to include global (top-level) declarations and names =
in
   /// the completion results.
   bool IncludeGlobals;
- =20
+
   /// \brief Whether the output format for the code-completion consumer is
   /// binary.
   bool OutputIsBinary;
- =20
+
 public:
   class OverloadCandidate {
   public:
@@ -772,25 +847,25 @@
       /// for which we only have a function prototype.
       CK_FunctionType
     };
-   =20
+
   private:
     /// \brief The kind of overload candidate.
     CandidateKind Kind;
-   =20
+
     union {
-      /// \brief The function overload candidate, available when=20
+      /// \brief The function overload candidate, available when
       /// Kind =3D=3D CK_Function.
       FunctionDecl *Function;
-     =20
+
       /// \brief The function template overload candidate, available when
       /// Kind =3D=3D CK_FunctionTemplate.
       FunctionTemplateDecl *FunctionTemplate;
-     =20
+
       /// \brief The function type that describes the entity being called,
       /// when Kind =3D=3D CK_FunctionType.
       const FunctionType *Type;
     };
-   =20
+
   public:
     OverloadCandidate(FunctionDecl *Function)
       : Kind(CK_Function), Function(Function) { }
@@ -803,55 +878,56 @@
=20
     /// \brief Determine the kind of overload candidate.
     CandidateKind getKind() const { return Kind; }
-   =20
-    /// \brief Retrieve the function overload candidate or the templated=20
+
+    /// \brief Retrieve the function overload candidate or the templated
     /// function declaration for a function template.
     FunctionDecl *getFunction() const;
-   =20
+
     /// \brief Retrieve the function template overload candidate.
     FunctionTemplateDecl *getFunctionTemplate() const {
       assert(getKind() =3D=3D CK_FunctionTemplate && "Not a function templ=
ate");
       return FunctionTemplate;
     }
-   =20
+
     /// \brief Retrieve the function type of the entity, regardless of how=
 the
     /// function is stored.
     const FunctionType *getFunctionType() const;
-   =20
+
     /// \brief Create a new code-completion string that describes the func=
tion
     /// signature of this overload candidate.
-    CodeCompletionString *CreateSignatureString(unsigned CurrentArg,=20
+    CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
                                                 Sema &S,
-                                      CodeCompletionAllocator &Allocator) =
const;
+                                      CodeCompletionAllocator &Allocator,
+                                      CodeCompletionTUInfo &CCTUInfo) cons=
t;
   };
- =20
+
   CodeCompleteConsumer() : IncludeMacros(false), IncludeCodePatterns(false=
),
                            IncludeGlobals(true), OutputIsBinary(false) { }
- =20
+
   CodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
                        bool IncludeGlobals, bool OutputIsBinary)
     : IncludeMacros(IncludeMacros), IncludeCodePatterns(IncludeCodePattern=
s),
       IncludeGlobals(IncludeGlobals), OutputIsBinary(OutputIsBinary) { }
- =20
+
   /// \brief Whether the code-completion consumer wants to see macros.
   bool includeMacros() const { return IncludeMacros; }
=20
   /// \brief Whether the code-completion consumer wants to see code patter=
ns.
   bool includeCodePatterns() const { return IncludeCodePatterns; }
- =20
+
   /// \brief Whether to include global (top-level) declaration results.
   bool includeGlobals() const { return IncludeGlobals; }
- =20
+
   /// \brief Determine whether the output of this consumer is binary.
   bool isOutputBinary() const { return OutputIsBinary; }
- =20
+
   /// \brief Deregisters and destroys this code-completion consumer.
   virtual ~CodeCompleteConsumer();
=20
   /// \name Code-completion callbacks
   //@{
   /// \brief Process the finalized code-completion results.
-  virtual void ProcessCodeCompleteResults(Sema &S,=20
+  virtual void ProcessCodeCompleteResults(Sema &S,
                                           CodeCompletionContext Context,
                                           CodeCompletionResult *Results,
                                           unsigned NumResults) { }
@@ -868,20 +944,22 @@
                                          OverloadCandidate *Candidates,
                                          unsigned NumCandidates) { }
   //@}
- =20
+
   /// \brief Retrieve the allocator that will be used to allocate
   /// code completion strings.
   virtual CodeCompletionAllocator &getAllocator() =3D 0;
+
+  virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() =3D 0;
 };
=20
-/// \brief A simple code-completion consumer that prints the results it=20
+/// \brief A simple code-completion consumer that prints the results it
 /// receives in a simple format.
 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
   /// \brief The raw output stream.
   raw_ostream &OS;
-   =20
-  CodeCompletionAllocator Allocator;
- =20
+
+  CodeCompletionTUInfo CCTUInfo;
+
 public:
   /// \brief Create a new printing code-completion consumer that prints its
   /// results to the given raw output stream.
@@ -889,21 +967,26 @@
                                bool IncludeGlobals,
                                raw_ostream &OS)
     : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlob=
als,
-                           false), OS(OS) {}
- =20
+                           false), OS(OS),
+      CCTUInfo(new GlobalCodeCompletionAllocator) {}
+
   /// \brief Prints the finalized code-completion results.
-  virtual void ProcessCodeCompleteResults(Sema &S,=20
+  virtual void ProcessCodeCompleteResults(Sema &S,
                                           CodeCompletionContext Context,
                                           CodeCompletionResult *Results,
                                           unsigned NumResults);
- =20
+
   virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
                                          OverloadCandidate *Candidates,
-                                         unsigned NumCandidates); =20
- =20
-  virtual CodeCompletionAllocator &getAllocator() { return Allocator; }
+                                         unsigned NumCandidates);
+
+  virtual CodeCompletionAllocator &getAllocator() {
+    return CCTUInfo.getAllocator();
+  }
+
+  virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() { return CCTUInf=
o; }
 };
- =20
+
 } // end namespace clang
=20
 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/DeclSpec.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/DeclSpec.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/DeclSpec.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -25,9 +25,11 @@
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/Lex/Token.h"
 #include "clang/Basic/ExceptionSpecificationType.h"
+#include "clang/Basic/Lambda.h"
 #include "clang/Basic/OperatorKinds.h"
 #include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
=20
 namespace clang {
@@ -243,6 +245,7 @@
   static const TST TST_char16 =3D clang::TST_char16;
   static const TST TST_char32 =3D clang::TST_char32;
   static const TST TST_int =3D clang::TST_int;
+  static const TST TST_int128 =3D clang::TST_int128;
   static const TST TST_half =3D clang::TST_half;
   static const TST TST_float =3D clang::TST_float;
   static const TST TST_double =3D clang::TST_double;
@@ -445,7 +448,10 @@
   CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
   const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
=20
-  const SourceRange &getSourceRange() const { return Range; }
+  const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
+  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin=
(); }
+  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
+
   SourceLocation getTypeSpecWidthLoc() const { return TSWLoc; }
   SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
   SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
@@ -609,6 +615,11 @@
   bool isConstexprSpecified() const { return Constexpr_specified; }
   SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
=20
+  void ClearConstexprSpec() {
+    Constexpr_specified =3D false;
+    ConstexprLoc =3D SourceLocation();
+  }
+
   AttributePool &getAttributePool() const {
     return Attrs.getPool();
   }
@@ -962,9 +973,11 @@
   void setTemplateId(TemplateIdAnnotation *TemplateId);
=20
   /// \brief Return the source range that covers this unqualified-id.
-  SourceRange getSourceRange() const {=20
+  SourceRange getSourceRange() const LLVM_READONLY {=20
     return SourceRange(StartLocation, EndLocation);=20
   }
+  SourceLocation getLocStart() const LLVM_READONLY { return StartLocation;=
 }
+  SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
 };
  =20
 /// CachedTokens - A set of tokens that has been cached for later
@@ -1105,6 +1118,16 @@
     /// If this is an invalid location, there is no ref-qualifier.
     unsigned RefQualifierLoc;
=20
+    /// \brief The location of the const-qualifier, if any.
+    ///
+    /// If this is an invalid location, there is no const-qualifier.
+    unsigned ConstQualifierLoc;
+
+    /// \brief The location of the volatile-qualifier, if any.
+    ///
+    /// If this is an invalid location, there is no volatile-qualifier.
+    unsigned VolatileQualifierLoc;
+
     /// \brief The location of the 'mutable' qualifer in a lambda-declarat=
or, if
     /// any.
     unsigned MutableLoc;
@@ -1170,6 +1193,16 @@
       return SourceLocation::getFromRawEncoding(RefQualifierLoc);
     }
=20
+    /// \brief Retrieve the location of the ref-qualifier, if any.
+    SourceLocation getConstQualifierLoc() const {
+      return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
+    }
+
+    /// \brief Retrieve the location of the ref-qualifier, if any.
+    SourceLocation getVolatileQualifierLoc() const {
+      return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
+    }
+
     /// \brief Retrieve the location of the 'mutable' qualifier, if any.
     SourceLocation getMutableLoc() const {
       return SourceLocation::getFromRawEncoding(MutableLoc);
@@ -1230,7 +1263,6 @@
=20
   void destroy() {
     switch (Kind) {
-    default: llvm_unreachable("Unknown decl type!");
     case DeclaratorChunk::Function:      return Fun.destroy();
     case DeclaratorChunk::Pointer:       return Ptr.destroy();
     case DeclaratorChunk::BlockPointer:  return Cls.destroy();
@@ -1306,6 +1338,8 @@
                                      unsigned TypeQuals,=20
                                      bool RefQualifierIsLvalueRef,
                                      SourceLocation RefQualifierLoc,
+                                     SourceLocation ConstQualifierLoc,
+                                     SourceLocation VolatileQualifierLoc,
                                      SourceLocation MutableLoc,
                                      ExceptionSpecificationType ESpecType,
                                      SourceLocation ESpecLoc,
@@ -1357,6 +1391,15 @@
=20
 };
=20
+/// \brief Described the kind of function definition (if any) provided for
+/// a function.
+enum FunctionDefinitionKind {
+  FDK_Declaration,
+  FDK_Definition,
+  FDK_Defaulted,
+  FDK_Deleted
+};
+ =20
 /// Declarator - Information about one declarator, including the parsed ty=
pe
 /// information and the identifier.  When the declarator is fully formed, =
this
 /// is turned into the appropriate Decl object.
@@ -1385,9 +1428,11 @@
     CXXCatchContext,     // C++ catch exception-declaration
     ObjCCatchContext,    // Objective-C catch exception-declaration
     BlockLiteralContext,  // Block literal declarator.
+    LambdaExprContext,   // Lambda-expression declarator.
+    TrailingReturnContext, // C++11 trailing-type-specifier.
     TemplateTypeArgContext, // Template type argument.
-    AliasDeclContext,    // C++0x alias-declaration.
-    AliasTemplateContext // C++0x alias-declaration template.
+    AliasDeclContext,    // C++11 alias-declaration.
+    AliasTemplateContext // C++11 alias-declaration template.
   };
=20
 private:
@@ -1412,8 +1457,11 @@
   /// GroupingParens - Set by Parser::ParseParenDeclarator().
   bool GroupingParens : 1;
=20
-  /// FunctionDefinition - Is this Declarator for a function or member def=
intion
-  bool FunctionDefinition : 1;
+  /// FunctionDefinition - Is this Declarator for a function or member=20
+  /// definition and, if so, what kind?
+  ///
+  /// Actually a FunctionDefinitionKind.
+  unsigned FunctionDefinition : 2;
=20
   // Redeclaration - Is this Declarator is a redeclaration.
   bool Redeclaration : 1;
@@ -1433,6 +1481,10 @@
   /// Extension - true if the declaration is preceded by __extension__.
   bool Extension : 1;
=20
+  /// \brief If this is the second or subsequent declarator in this declar=
ation,
+  /// the location of the comma before this declarator.
+  SourceLocation CommaLoc;
+
   /// \brief If provided, the source location of the ellipsis used to desc=
ribe
   /// this declarator as a parameter pack.
   SourceLocation EllipsisLoc;
@@ -1443,7 +1495,8 @@
   Declarator(const DeclSpec &ds, TheContext C)
     : DS(ds), Range(ds.getSourceRange()), Context(C),
       InvalidType(DS.getTypeSpecType() =3D=3D DeclSpec::TST_error),
-      GroupingParens(false), FunctionDefinition(false), Redeclaration(fals=
e),
+      GroupingParens(false), FunctionDefinition(FDK_Declaration),=20
+      Redeclaration(false),
       Attrs(ds.getAttributePool().getFactory()), AsmLabel(0),
       InlineParamsUsed(false), Extension(false) {
   }
@@ -1484,7 +1537,9 @@
   }
=20
   /// getSourceRange - Get the source range that spans this declarator.
-  const SourceRange &getSourceRange() const { return Range; }
+  const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
+  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin=
(); }
+  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
=20
   void SetSourceRange(SourceRange R) { Range =3D R; }
   /// SetRangeBegin - Set the start of the source range to Loc, unless it's
@@ -1521,6 +1576,8 @@
     Attrs.clear();
     AsmLabel =3D 0;
     InlineParamsUsed =3D false;
+    CommaLoc =3D SourceLocation();
+    EllipsisLoc =3D SourceLocation();
   }
=20
   /// mayOmitIdentifier - Return true if the identifier is either optional=
 or
@@ -1547,7 +1604,9 @@
     case CXXCatchContext:
     case ObjCCatchContext:
     case BlockLiteralContext:
+    case LambdaExprContext:
     case TemplateTypeArgContext:
+    case TrailingReturnContext:
       return true;
     }
     llvm_unreachable("unknown context kind!");
@@ -1577,7 +1636,9 @@
     case ObjCParameterContext:
     case ObjCResultContext:
     case BlockLiteralContext:
+    case LambdaExprContext:
     case TemplateTypeArgContext:
+    case TrailingReturnContext:
       return false;
     }
     llvm_unreachable("unknown context kind!");
@@ -1588,15 +1649,31 @@
   bool mayBeFollowedByCXXDirectInit() const {
     if (hasGroupingParens()) return false;
=20
+    if (getDeclSpec().getStorageClassSpec() =3D=3D DeclSpec::SCS_typedef)
+      return false;
+
+    if (getDeclSpec().getStorageClassSpec() =3D=3D DeclSpec::SCS_extern &&
+        Context !=3D FileContext)
+      return false;
+
+    // Special names can't have direct initializers.
+    if (Name.getKind() !=3D UnqualifiedId::IK_Identifier)
+      return false;
+
     switch (Context) {
     case FileContext:
     case BlockContext:
     case ForContext:
       return true;
=20
+    case ConditionContext:
+      // This may not be followed by a direct initializer, but it can't be=
 a
+      // function declaration either, and we'd prefer to perform a tentati=
ve
+      // parse in order to produce the right diagnostic.
+      return true;
+
     case KNRTypeListContext:
     case MemberContext:
-    case ConditionContext:
     case PrototypeContext:
     case ObjCParameterContext:
     case ObjCResultContext:
@@ -1608,7 +1685,9 @@
     case AliasDeclContext:
     case AliasTemplateContext:
     case BlockLiteralContext:
+    case LambdaExprContext:
     case TemplateTypeArgContext:
+    case TrailingReturnContext:
       return false;
     }
     llvm_unreachable("unknown context kind!");
@@ -1696,7 +1775,6 @@
         return !DeclTypeInfo[i].Arr.NumElts;
       }
       llvm_unreachable("Invalid type chunk");
-      return false;
     }
     return false;
   }
@@ -1721,7 +1799,6 @@
         return false;
       }
       llvm_unreachable("Invalid type chunk");
-      return false;
     }
     return false;
   }
@@ -1800,13 +1877,26 @@
=20
   void setGroupingParens(bool flag) { GroupingParens =3D flag; }
   bool hasGroupingParens() const { return GroupingParens; }
- =20
+
+  bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
+  SourceLocation getCommaLoc() const { return CommaLoc; }
+  void setCommaLoc(SourceLocation CL) { CommaLoc =3D CL; }
+
   bool hasEllipsis() const { return EllipsisLoc.isValid(); }
   SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
   void setEllipsisLoc(SourceLocation EL) { EllipsisLoc =3D EL; }
=20
-  void setFunctionDefinition(bool Val) { FunctionDefinition =3D Val; }
-  bool isFunctionDefinition() const { return FunctionDefinition; }
+  void setFunctionDefinitionKind(FunctionDefinitionKind Val) {=20
+    FunctionDefinition =3D Val;=20
+  }
+ =20
+  bool isFunctionDefinition() const {
+    return getFunctionDefinitionKind() !=3D FDK_Declaration;
+  }
+ =20
+  FunctionDefinitionKind getFunctionDefinitionKind() const {=20
+    return (FunctionDefinitionKind)FunctionDefinition;=20
+  }
=20
   void setRedeclaration(bool Val) { Redeclaration =3D Val; }
   bool isRedeclaration() const { return Redeclaration; }
@@ -1855,38 +1945,24 @@
   SourceLocation LastLocation;
 };
=20
-/// LambdaCaptureDefault - The default, if any, capture method for a
-/// lambda expression.
-enum LambdaCaptureDefault {
-  LCD_None,
-  LCD_ByCopy,
-  LCD_ByRef
-};
-
-/// LambdaCaptureKind - The different capture forms in a lambda
-/// introducer: 'this' or a copied or referenced variable.
-enum LambdaCaptureKind {
-  LCK_This,
-  LCK_ByCopy,
-  LCK_ByRef
-};
-
 /// LambdaCapture - An individual capture in a lambda introducer.
 struct LambdaCapture {
   LambdaCaptureKind Kind;
   SourceLocation Loc;
   IdentifierInfo* Id;
-
-  LambdaCapture(LambdaCaptureKind Kind,
-                     SourceLocation Loc,
-                     IdentifierInfo* Id =3D 0)
-    : Kind(Kind), Loc(Loc), Id(Id)
+  SourceLocation EllipsisLoc;
+ =20
+  LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
+                IdentifierInfo* Id =3D 0,
+                SourceLocation EllipsisLoc =3D SourceLocation())
+    : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc)
   {}
 };
=20
 /// LambdaIntroducer - Represents a complete lambda introducer.
 struct LambdaIntroducer {
   SourceRange Range;
+  SourceLocation DefaultLoc;
   LambdaCaptureDefault Default;
   llvm::SmallVector<LambdaCapture, 4> Captures;
=20
@@ -1896,8 +1972,9 @@
   /// addCapture - Append a capture in a lambda introducer.
   void addCapture(LambdaCaptureKind Kind,
                   SourceLocation Loc,
-                  IdentifierInfo* Id =3D 0) {
-    Captures.push_back(LambdaCapture(Kind, Loc, Id));
+                  IdentifierInfo* Id =3D 0,=20
+                  SourceLocation EllipsisLoc =3D SourceLocation()) {
+    Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc));
   }
=20
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/DelayedDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/DelayedDiagnostic.h	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/DelayedDiagnostic.h	=
Tue Apr 17 11:51:51 2012 +0300
@@ -122,8 +122,9 @@
   void Destroy();
=20
   static DelayedDiagnostic makeDeprecation(SourceLocation Loc,
-                                           const NamedDecl *D,
-                                           StringRef Msg);
+           const NamedDecl *D,
+           const ObjCInterfaceDecl *UnknownObjCClass,
+           StringRef Msg);
=20
   static DelayedDiagnostic makeAccess(SourceLocation Loc,
                                       const AccessedEntity &Entity) {
@@ -187,12 +188,17 @@
     assert(Kind =3D=3D ForbiddenType && "not a forbidden-type diagnostic");
     return QualType::getFromOpaquePtr(ForbiddenTypeData.OperandType);
   }
+ =20
+  const ObjCInterfaceDecl *getUnknownObjCClass() const {
+    return DeprecationData.UnknownObjCClass;
+  }
=20
 private:
   union {
     /// Deprecation.
     struct {
       const NamedDecl *Decl;
+      const ObjCInterfaceDecl *UnknownObjCClass;
       const char *Message;
       size_t MessageLen;
     } DeprecationData;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/ExternalSemaSource.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/ExternalSemaSource.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/ExternalSemaSource.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -59,10 +59,7 @@
=20
   /// \brief Load the contents of the global method pool for a given
   /// selector.
-  ///
-  /// \returns a pair of Objective-C methods lists containing the
-  /// instance and factory methods, respectively, with this selector.
-  virtual std::pair<ObjCMethodList,ObjCMethodList> ReadMethodPool(Selector=
 Sel);
+  virtual void ReadMethodPool(Selector Sel);
=20
   /// \brief Load the set of namespaces that are known to the external sou=
rce,
   /// which will be used during typo correction.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/IdentifierResolver.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/IdentifierResolver.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/IdentifierResolver.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #define LLVM_CLANG_AST_SEMA_IDENTIFIERRESOLVER_H
=20
 #include "clang/Basic/IdentifierTable.h"
+#include "llvm/ADT/SmallVector.h"
=20
 namespace clang {
=20
@@ -23,9 +24,11 @@
 class Decl;
 class DeclContext;
 class DeclarationName;
+class ExternalPreprocessorSource;
 class NamedDecl;
+class Preprocessor;
 class Scope;
-
+ =20
 /// IdentifierResolver - Keeps track of shadowed decls on enclosing
 /// scopes.  It manages the shadowing chains of declaration names and
 /// implements efficient decl lookup based on a declaration name.
@@ -141,10 +144,10 @@
   };
=20
   /// begin - Returns an iterator for decls with the name 'Name'.
-  static iterator begin(DeclarationName Name);
+  iterator begin(DeclarationName Name);
=20
   /// end - Returns an iterator that has 'finished'.
-  static iterator end() {
+  iterator end() {
     return iterator();
   }
=20
@@ -175,23 +178,29 @@
   /// position.
   void InsertDeclAfter(iterator Pos, NamedDecl *D);
=20
-  /// \brief Link the declaration into the chain of declarations for
-  /// the given identifier.
+  /// \brief Try to add the given declaration to the top level scope, if it
+  /// (or a redeclaration of it) hasn't already been added.
   ///
-  /// This is a lower-level routine used by the AST reader to link a
-  /// declaration into a specific IdentifierInfo before the
-  /// declaration actually has a name.
-  void AddDeclToIdentifierChain(IdentifierInfo *II, NamedDecl *D);
-
-  explicit IdentifierResolver(const LangOptions &LangOpt);
+  /// \param D The externally-produced declaration to add.
+  ///
+  /// \param Name The name of the externally-produced declaration.
+  ///
+  /// \returns true if the declaration was added, false otherwise.
+  bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name);
+ =20
+  explicit IdentifierResolver(Preprocessor &PP);
   ~IdentifierResolver();
=20
 private:
   const LangOptions &LangOpt;
-
+  Preprocessor &PP;
+ =20
   class IdDeclInfoMap;
   IdDeclInfoMap *IdDeclInfos;
=20
+  void updatingIdentifier(IdentifierInfo &II);
+  void readingIdentifier(IdentifierInfo &II);
+ =20
   /// FETokenInfo contains a Decl pointer if lower bit =3D=3D 0.
   static inline bool isDeclPtr(void *Ptr) {
     return (reinterpret_cast<uintptr_t>(Ptr) & 0x1) =3D=3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/Initialization.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/Initialization.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/Initialization.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D--- SemaInit.h - Semantic Analysis for Initializers --------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D--- Initialization.h - Semantic Analysis for Initializers --*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -70,7 +70,10 @@
     EK_BlockElement,
     /// \brief The entity being initialized is the real or imaginary part =
of a
     /// complex number.
-    EK_ComplexElement
+    EK_ComplexElement,
+    /// \brief The entity being initialized is the field that captures a=20
+    /// variable in a lambda.
+    EK_LambdaCapture
   };
  =20
 private:
@@ -85,7 +88,7 @@
   QualType Type;
  =20
   union {
-    /// \brief When Kind =3D=3D EK_Variable or EK_Member, the VarDecl or
+    /// \brief When Kind =3D=3D EK_Variable, or EK_Member, the VarDecl or
     /// FieldDecl, respectively.
     DeclaratorDecl *VariableOrMember;
=20
@@ -98,7 +101,7 @@
     TypeSourceInfo *TypeInfo;
    =20
     struct {
-      /// \brief When Kind =3D=3D EK_Result, EK_Exception, or EK_New, the
+      /// \brief When Kind =3D=3D EK_Result, EK_Exception, EK_New, the
       /// location of the 'return', 'throw', or 'new' keyword,
       /// respectively. When Kind =3D=3D EK_Temporary, the location where
       /// the temporary is being created.
@@ -118,6 +121,14 @@
     /// EK_ComplexElement, the index of the array or vector element being
     /// initialized.=20
     unsigned Index;
+   =20
+    struct {
+      /// \brief The variable being captured by an EK_LambdaCapture.
+      VarDecl *Var;
+     =20
+      /// \brief The source location at which the capture occurs.
+      unsigned Location;
+    } Capture;
   };
=20
   InitializedEntity() { }
@@ -147,6 +158,14 @@
   InitializedEntity(ASTContext &Context, unsigned Index,=20
                     const InitializedEntity &Parent);
=20
+  /// \brief Create the initialization entity for a lambda capture.
+  InitializedEntity(VarDecl *Var, FieldDecl *Field, SourceLocation Loc)
+    : Kind(EK_LambdaCapture), Parent(0), Type(Field->getType())=20
+  {
+    Capture.Var =3D Var;
+    Capture.Location =3D Loc.getRawEncoding();
+  }
+ =20
 public:
   /// \brief Create the initialization entity for a variable.
   static InitializedEntity InitializeVariable(VarDecl *Var) {
@@ -156,7 +175,7 @@
   /// \brief Create the initialization entity for a parameter.
   static InitializedEntity InitializeParameter(ASTContext &Context,
                                                ParmVarDecl *Parm) {
-    bool Consumed =3D (Context.getLangOptions().ObjCAutoRefCount &&
+    bool Consumed =3D (Context.getLangOpts().ObjCAutoRefCount &&
                      Parm->hasAttr<NSConsumedAttr>());
=20
     InitializedEntity Entity;
@@ -246,6 +265,13 @@
     return InitializedEntity(Context, Index, Parent);
   }
=20
+  /// \brief Create the initialization entity for a lambda capture.
+  static InitializedEntity InitializeLambdaCapture(VarDecl *Var,
+                                                   FieldDecl *Field,
+                                                   SourceLocation Loc) {
+    return InitializedEntity(Var, Field, Loc);
+  }
+                                                  =20
   /// \brief Determine the kind of initialization.
   EntityKind getKind() const { return Kind; }
  =20
@@ -314,9 +340,22 @@
   /// element, sets the element index.
   void setElementIndex(unsigned Index) {
     assert(getKind() =3D=3D EK_ArrayElement || getKind() =3D=3D EK_VectorE=
lement ||
-           EK_ComplexElement);
+           getKind() =3D=3D EK_ComplexElement);
     this->Index =3D Index;
   }
+
+  /// \brief Retrieve the variable for a captured variable in a lambda.
+  VarDecl *getCapturedVar() const {
+    assert(getKind() =3D=3D EK_LambdaCapture && "Not a lambda capture!");
+    return Capture.Var;
+  }
+ =20
+  /// \brief Determine the location of the capture when initializing
+  /// field from a captured variable in a lambda.
+  SourceLocation getCaptureLoc() const {
+    assert(getKind() =3D=3D EK_LambdaCapture && "Not a lambda capture!");
+    return SourceLocation::getFromRawEncoding(Capture.Location);
+  }
 };
  =20
 /// \brief Describes the kind of initialization being performed, along wit=
h=20
@@ -326,36 +365,36 @@
 public:
   /// \brief The kind of initialization being performed.
   enum InitKind {
-    IK_Direct,  ///< Direct initialization
-    IK_Copy,    ///< Copy initialization
-    IK_Default, ///< Default initialization
-    IK_Value    ///< Value initialization
+    IK_Direct,       ///< Direct initialization
+    IK_DirectList,   ///< Direct list-initialization
+    IK_Copy,         ///< Copy initialization
+    IK_Default,      ///< Default initialization
+    IK_Value         ///< Value initialization
   };
  =20
 private:
-  /// \brief The kind of initialization that we're storing.
-  enum StoredInitKind {
-    SIK_Direct =3D IK_Direct,   ///< Direct initialization
-    SIK_Copy =3D IK_Copy,       ///< Copy initialization
-    SIK_Default =3D IK_Default, ///< Default initialization
-    SIK_Value =3D IK_Value,     ///< Value initialization
-    SIK_ImplicitValue,        ///< Implicit value initialization
-    SIK_DirectCast,  ///< Direct initialization due to a cast
-    /// \brief Direct initialization due to a C-style cast.
-    SIK_DirectCStyleCast,
-    /// \brief Direct initialization due to a functional-style cast.
-    SIK_DirectFunctionalCast
+  /// \brief The context of the initialization.
+  enum InitContext {
+    IC_Normal,         ///< Normal context
+    IC_ExplicitConvs,  ///< Normal context, but allows explicit conversion=
 funcs
+    IC_Implicit,       ///< Implicit context (value initialization)
+    IC_StaticCast,     ///< Static cast context
+    IC_CStyleCast,     ///< C-style cast context
+    IC_FunctionalCast  ///< Functional cast context
   };
  =20
   /// \brief The kind of initialization being performed.
-  StoredInitKind Kind;
+  InitKind Kind : 8;
+
+  /// \brief The context of the initialization.
+  InitContext Context : 8;
  =20
   /// \brief The source locations involved in the initialization.
   SourceLocation Locations[3];
  =20
-  InitializationKind(StoredInitKind Kind, SourceLocation Loc1,=20
+  InitializationKind(InitKind Kind, InitContext Context, SourceLocation Lo=
c1,=20
                      SourceLocation Loc2, SourceLocation Loc3)
-    : Kind(Kind)=20
+    : Kind(Kind), Context(Context)
   {
     Locations[0] =3D Loc1;
     Locations[1] =3D Loc2;
@@ -367,41 +406,53 @@
   static InitializationKind CreateDirect(SourceLocation InitLoc,
                                          SourceLocation LParenLoc,
                                          SourceLocation RParenLoc) {
-    return InitializationKind(SIK_Direct, InitLoc, LParenLoc, RParenLoc);
+    return InitializationKind(IK_Direct, IC_Normal,
+                              InitLoc, LParenLoc, RParenLoc);
+  }
+
+  static InitializationKind CreateDirectList(SourceLocation InitLoc) {
+    return InitializationKind(IK_DirectList, IC_Normal,
+                              InitLoc, InitLoc, InitLoc);
   }
=20
   /// \brief Create a direct initialization due to a cast that isn't a C-s=
tyle=20
   /// or functional cast.
   static InitializationKind CreateCast(SourceRange TypeRange) {
-    return InitializationKind(SIK_DirectCast,
-                              TypeRange.getBegin(), TypeRange.getBegin(),=20
-                              TypeRange.getEnd());
+    return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin=
(),
+                              TypeRange.getBegin(), TypeRange.getEnd());
   }
  =20
   /// \brief Create a direct initialization for a C-style cast.
   static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
-                                             SourceRange TypeRange) {
-    return InitializationKind(SIK_DirectCStyleCast,
-                              StartLoc, TypeRange.getBegin(),=20
+                                             SourceRange TypeRange,
+                                             bool InitList) {
+    // C++ cast syntax doesn't permit init lists, but C compound literals =
are
+    // exactly that.
+    return InitializationKind(InitList ? IK_DirectList : IK_Direct,
+                              IC_CStyleCast, StartLoc, TypeRange.getBegin(=
),
                               TypeRange.getEnd());
   }
=20
   /// \brief Create a direct initialization for a functional cast.
-  static InitializationKind CreateFunctionalCast(SourceRange TypeRange) {
-    return InitializationKind(SIK_DirectFunctionalCast,
-                              TypeRange.getBegin(), TypeRange.getBegin(),=20
-                              TypeRange.getEnd());
+  static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
+                                                 bool InitList) {
+    return InitializationKind(InitList ? IK_DirectList : IK_Direct,
+                              IC_FunctionalCast, TypeRange.getBegin(),
+                              TypeRange.getBegin(), TypeRange.getEnd());
   }
=20
   /// \brief Create a copy initialization.
   static InitializationKind CreateCopy(SourceLocation InitLoc,
-                                       SourceLocation EqualLoc) {
-    return InitializationKind(SIK_Copy, InitLoc, EqualLoc, EqualLoc);
+                                       SourceLocation EqualLoc,
+                                       bool AllowExplicitConvs =3D false) {
+    return InitializationKind(IK_Copy,=20
+                              AllowExplicitConvs? IC_ExplicitConvs : IC_No=
rmal,
+                              InitLoc, EqualLoc, EqualLoc);
   }
  =20
   /// \brief Create a default initialization.
   static InitializationKind CreateDefault(SourceLocation InitLoc) {
-    return InitializationKind(SIK_Default, InitLoc, InitLoc, InitLoc);
+    return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, Ini=
tLoc);
   }
  =20
   /// \brief Create a value initialization.
@@ -409,46 +460,39 @@
                                         SourceLocation LParenLoc,
                                         SourceLocation RParenLoc,
                                         bool isImplicit =3D false) {
-    return InitializationKind(isImplicit? SIK_ImplicitValue : SIK_Value,=20
+    return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Norm=
al,
                               InitLoc, LParenLoc, RParenLoc);
   }
  =20
   /// \brief Determine the initialization kind.
   InitKind getKind() const {
-    if (Kind > SIK_ImplicitValue)
-      return IK_Direct;
-    if (Kind =3D=3D SIK_ImplicitValue)
-      return IK_Value;
-
-    return (InitKind)Kind;
+    return Kind;
   }
  =20
   /// \brief Determine whether this initialization is an explicit cast.
   bool isExplicitCast() const {
-    return Kind =3D=3D SIK_DirectCast ||=20
-           Kind =3D=3D SIK_DirectCStyleCast ||
-           Kind =3D=3D SIK_DirectFunctionalCast;
+    return Context >=3D IC_StaticCast;
   }
  =20
   /// \brief Determine whether this initialization is a C-style cast.
   bool isCStyleOrFunctionalCast() const {=20
-    return Kind =3D=3D SIK_DirectCStyleCast || Kind =3D=3D SIK_DirectFunct=
ionalCast;=20
+    return Context >=3D IC_CStyleCast;=20
   }
=20
-  /// brief Determine whether this is a C-style cast.
+  /// \brief Determine whether this is a C-style cast.
   bool isCStyleCast() const {
-    return Kind =3D=3D SIK_DirectCStyleCast;
+    return Context =3D=3D IC_CStyleCast;
   }
=20
-  /// brief Determine whether this is a functional-style cast.
+  /// \brief Determine whether this is a functional-style cast.
   bool isFunctionalCast() const {
-    return Kind =3D=3D SIK_DirectFunctionalCast;
+    return Context =3D=3D IC_FunctionalCast;
   }
=20
   /// \brief Determine whether this initialization is an implicit
   /// value-initialization, e.g., as occurs during aggregate
   /// initialization.
-  bool isImplicitValueInit() const { return Kind =3D=3D SIK_ImplicitValue;=
 }
+  bool isImplicitValueInit() const { return Context =3D=3D IC_Implicit; }
=20
   /// \brief Retrieve the location at which initialization is occurring.
   SourceLocation getLocation() const { return Locations[0]; }
@@ -461,16 +505,26 @@
   /// \brief Retrieve the location of the equal sign for copy initializati=
on
   /// (if present).
   SourceLocation getEqualLoc() const {
-    assert(Kind =3D=3D SIK_Copy && "Only copy initialization has an '=3D'"=
);
+    assert(Kind =3D=3D IK_Copy && "Only copy initialization has an '=3D'");
     return Locations[1];
   }
- =20
-  bool isCopyInit() const { return Kind =3D=3D SIK_Copy; }
+
+  bool isCopyInit() const { return Kind =3D=3D IK_Copy; }
+
+  /// \brief Retrieve whether this initialization allows the use of explic=
it
+  ///        constructors.
+  bool AllowExplicit() const { return !isCopyInit(); }
+
+  /// \brief Retrieve whether this initialization allows the use of explic=
it
+  /// conversion functions.
+  bool allowExplicitConversionFunctions() const {
+    return !isCopyInit() || Context =3D=3D IC_ExplicitConvs;
+  }
  =20
   /// \brief Retrieve the source range containing the locations of the open
   /// and closing parentheses for value and direct initializations.
   SourceRange getParenRange() const {
-    assert((getKind() =3D=3D IK_Direct || Kind =3D=3D SIK_Value) &&
+    assert((Kind =3D=3D IK_Direct || Kind =3D=3D IK_Value) &&
            "Only direct- and value-initialization have parentheses");
     return SourceRange(Locations[1], Locations[2]);
   }
@@ -530,6 +584,10 @@
     SK_ListInitialization,
     /// \brief Perform list-initialization with a constructor.
     SK_ListConstructorCall,
+    /// \brief Unwrap the single-element initializer list for a reference.
+    SK_UnwrapInitList,
+    /// \brief Rewrap the single-element initializer list for a reference.
+    SK_RewrapInitList,
     /// \brief Perform initialization via a constructor.
     SK_ConstructorInitialization,
     /// \brief Zero-initialize the object
@@ -544,12 +602,17 @@
     /// \brief Array initialization (from an array rvalue).
     /// This is a GNU C extension.
     SK_ArrayInit,
+    /// \brief Array initialization from a parenthesized initializer list.
+    /// This is a GNU C++ extension.
+    SK_ParenthesizedArrayInit,
     /// \brief Pass an object by indirect copy-and-restore.
     SK_PassByIndirectCopyRestore,
     /// \brief Pass an object by indirect restore.
     SK_PassByIndirectRestore,
     /// \brief Produce an Objective-C object pointer.
-    SK_ProduceObjCObject
+    SK_ProduceObjCObject,
+    /// \brief Construct a std::initializer_list from an initializer list.
+    SK_StdInitializerList
   };
  =20
   /// \brief A single step in the initialization sequence.
@@ -579,8 +642,12 @@
       } Function;
=20
       /// \brief When Kind =3D SK_ConversionSequence, the implicit convers=
ion
-      /// sequence=20
+      /// sequence.
       ImplicitConversionSequence *ICS;
+
+      /// \brief When Kind =3D SK_RewrapInitList, the syntactic form of the
+      /// wrapping list.
+      InitListExpr *WrappingSyntacticList;
     };
=20
     void Destroy();
@@ -635,14 +702,26 @@
     FK_InitListBadDestinationType,
     /// \brief Overloading for a user-defined conversion failed.
     FK_UserConversionOverloadFailed,
-    /// \brief Overloaded for initialization by constructor failed.
+    /// \brief Overloading for initialization by constructor failed.
     FK_ConstructorOverloadFailed,
+    /// \brief Overloading for list-initialization by constructor failed.
+    FK_ListConstructorOverloadFailed,
     /// \brief Default-initialization of a 'const' object.
     FK_DefaultInitOfConst,
     /// \brief Initialization of an incomplete type.
     FK_Incomplete,
+    /// \brief Variable-length array must not have an initializer.
+    FK_VariableLengthArrayHasInitializer,
     /// \brief List initialization failed at some point.
-    FK_ListInitializationFailed
+    FK_ListInitializationFailed,
+    /// \brief Initializer has a placeholder type which cannot be
+    /// resolved by initialization.
+    FK_PlaceholderType,
+    /// \brief Failed to initialize a std::initializer_list because copy
+    /// construction of some element failed.
+    FK_InitListElementCopyFailure,
+    /// \brief List-copy-initialization chose an explicit constructor.
+    FK_ExplicitConstructor
   };
  =20
 private:
@@ -655,6 +734,9 @@
   /// \brief The candidate set created when initialization failed.
   OverloadCandidateSet FailedCandidateSet;
=20
+  /// \brief The incomplete type that caused a failure.
+  QualType FailedIncompleteType;
+ =20
   /// \brief Prints a follow-up note that highlights the location of
   /// the initialized entity, if it's remote.
   void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
@@ -763,8 +845,9 @@
   /// \param Function the function to which the overloaded function refere=
nce
   /// resolves.
   void AddAddressOverloadResolutionStep(FunctionDecl *Function,
-                                        DeclAccessPair Found);
- =20
+                                        DeclAccessPair Found,
+                                        bool HadMultipleCandidates);
+
   /// \brief Add a new step in the initialization that performs a derived-=
to-
   /// base cast.
   ///
@@ -801,8 +884,9 @@
   /// a constructor or a conversion function.
   void AddUserConversionStep(FunctionDecl *Function,
                              DeclAccessPair FoundDecl,
-                             QualType T);
- =20
+                             QualType T,
+                             bool HadMultipleCandidates);
+
   /// \brief Add a new step that performs a qualification conversion to the
   /// given type.
   void AddQualificationConversionStep(QualType Ty,
@@ -812,17 +896,23 @@
   void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
                                  QualType T);
=20
-  /// \brief Add a list-initialiation step.
+  /// \brief Add a list-initialization step.
   void AddListInitializationStep(QualType T);
=20
   /// \brief Add a constructor-initialization step.
+  ///
+  /// \arg FromInitList The constructor call is syntactically an initializ=
er
+  /// list.
+  /// \arg AsInitList The constructor is called as an init list constructo=
r.
   void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
                                         AccessSpecifier Access,
-                                        QualType T);
+                                        QualType T,
+                                        bool HadMultipleCandidates,
+                                        bool FromInitList, bool AsInitList=
);
=20
   /// \brief Add a zero-initialization step.
   void AddZeroInitializationStep(QualType T);
- =20
+
   /// \brief Add a C assignment step.
   //
   // FIXME: It isn't clear whether this should ever be needed;
@@ -840,6 +930,9 @@
   /// \brief Add an array initialization step.
   void AddArrayInitStep(QualType T);
=20
+  /// \brief Add a parenthesized array initialization step.
+  void AddParenthesizedArrayInitStep(QualType T);
+
   /// \brief Add a step to pass an object by indirect copy-restore.
   void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
=20
@@ -847,10 +940,20 @@
   /// retaining it).
   void AddProduceObjCObjectStep(QualType T);
=20
+  /// \brief Add a step to construct a std::initializer_list object from an
+  /// initializer list.
+  void AddStdInitializerListConstructionStep(QualType T);
+
+  /// \brief Add steps to unwrap a initializer list for a reference around=
 a
+  /// single element and rewrap it at the end.
+  void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
+
   /// \brief Note that this initialization sequence failed.
   void SetFailed(FailureKind Failure) {
     SequenceKind =3D FailedSequence;
     this->Failure =3D Failure;
+    assert((Failure !=3D FK_Incomplete || !FailedIncompleteType.isNull()) =
&&
+           "Incomplete type failure requires a type!");
   }
  =20
   /// \brief Note that this initialization sequence failed due to failed
@@ -863,12 +966,19 @@
     return FailedCandidateSet;
   }
=20
-  /// brief Get the overloading result, for when the initialization
+  /// \brief Get the overloading result, for when the initialization
   /// sequence failed due to a bad overload.
   OverloadingResult getFailedOverloadResult() const {
     return FailedOverloadResult;
   }
=20
+  /// \brief Note that this initialization sequence failed due to an
+  /// incomplete type.
+  void setIncompleteTypeFailure(QualType IncompleteType) {
+    FailedIncompleteType =3D IncompleteType;
+    SetFailed(FK_Incomplete);
+  }
+
   /// \brief Determine why initialization failed.
   FailureKind getFailureKind() const {
     assert(Failed() && "Not an initialization failure!");
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/LocInfoType.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/LocInfoType.h	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/LocInfoType.h	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -36,16 +36,16 @@
   TypeSourceInfo *DeclInfo;
=20
   LocInfoType(QualType ty, TypeSourceInfo *TInfo)
-    : Type((TypeClass)LocInfo, ty, ty->isDependentType(),=20
+    : Type((TypeClass)LocInfo, ty, ty->isDependentType(),
            ty->isInstantiationDependentType(),
            ty->isVariablyModifiedType(),
-           ty->containsUnexpandedParameterPack()),=20
-    DeclInfo(TInfo) {
-      assert(getTypeClass() =3D=3D (TypeClass)LocInfo && "LocInfo didn't f=
it in TC?");
-    }
+           ty->containsUnexpandedParameterPack()),
+      DeclInfo(TInfo) {
+    assert(getTypeClass() =3D=3D (TypeClass)LocInfo && "LocInfo didn't fit=
 in TC?");
+  }
   friend class Sema;
=20
- public:
+public:
   QualType getType() const { return getCanonicalTypeInternal(); }
   TypeSourceInfo *getTypeSourceInfo() const { return DeclInfo; }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/Lookup.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/Lookup.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/Lookup.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -214,6 +214,12 @@
     return Redecl;
   }
=20
+  /// \brief Determine whether this lookup is permitted to see hidden
+  /// declarations, such as those in modules that have not yet been import=
ed.
+  bool isHiddenDeclarationVisible() const {
+    return Redecl || LookupKind =3D=3D Sema::LookupTagName;
+  }
+ =20
   /// Sets whether tag declarations should be hidden by non-tag
   /// declarations during resolution.  The default is true.
   void setHideTags(bool Hide) {
@@ -266,23 +272,35 @@
     return Paths;
   }
=20
-  /// \brief Tests whether the given declaration is acceptable.
-  bool isAcceptableDecl(NamedDecl *D) const {
-    if (!D->isInIdentifierNamespace(IDNS))
-      return false;
+  /// \brief Determine whether the given declaration is visible to the
+  /// program.
+  static bool isVisible(NamedDecl *D) {
+    // If this declaration is not hidden, it's visible.
+    if (!D->isHidden())
+      return true;
    =20
-    // So long as this declaration is not module-private or was parsed as
-    // part of this translation unit (i.e., in the module), we're allowed =
to
-    // find it.
-    if (!D->isModulePrivate() || !D->isFromASTFile())
-      return true;
-
     // FIXME: We should be allowed to refer to a module-private name from=20
     // within the same module, e.g., during template instantiation.
     // This requires us know which module a particular declaration came fr=
om.
     return false;
   }
-
+ =20
+  /// \brief Retrieve the accepted (re)declaration of the given declaratio=
n,
+  /// if there is one.
+  NamedDecl *getAcceptableDecl(NamedDecl *D) const {
+    if (!D->isInIdentifierNamespace(IDNS))
+      return 0;
+   =20
+    if (isHiddenDeclarationVisible() || isVisible(D))
+      return D;
+   =20
+    return getAcceptableDeclSlow(D);
+  }
+ =20
+private:
+  NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
+public:
+ =20
   /// \brief Returns the identifier namespace mask for this lookup.
   unsigned getIdentifierNamespace() const {
     return IDNS;
@@ -532,6 +550,11 @@
       return *I++;
     }
=20
+    /// Restart the iteration.
+    void restart() {
+      I =3D Results.begin();
+    }
+
     /// Erase the last element returned from this iterator.
     void erase() {
       Results.Decls.erase(--I);
@@ -569,7 +592,7 @@
   void diagnose() {
     if (isAmbiguous())
       SemaRef.DiagnoseAmbiguousLookup(*this);
-    else if (isClassLookup() && SemaRef.getLangOptions().AccessControl)
+    else if (isClassLookup() && SemaRef.getLangOpts().AccessControl)
       SemaRef.CheckLookupAccess(*this);
   }
=20
@@ -582,7 +605,13 @@
   void configure();
=20
   // Sanity checks.
-  void sanity() const;
+  void sanityImpl() const;
+
+  void sanity() const {
+#ifndef NDEBUG
+    sanityImpl();
+#endif
+  }
=20
   bool sanityCheckUnresolved() const {
     for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/Overload.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/Overload.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/Overload.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -24,6 +24,7 @@
 #include "clang/Sema/SemaFixItUtils.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/Support/Allocator.h"
=20
 namespace clang {
   class ASTContext;
@@ -111,6 +112,23 @@
=20
   ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
=20
+  /// NarrowingKind - The kind of narrowing conversion being performed by a
+  /// standard conversion sequence according to C++11 [dcl.init.list]p7.
+  enum NarrowingKind {
+    /// Not a narrowing conversion.
+    NK_Not_Narrowing,
+
+    /// A narrowing conversion by virtue of the source and destination typ=
es.
+    NK_Type_Narrowing,
+
+    /// A narrowing conversion, because a constant expression got narrowed.
+    NK_Constant_Narrowing,
+
+    /// A narrowing conversion, because a non-constant-expression variable=
 might
+    /// have got narrowed.
+    NK_Variable_Narrowing
+  };
+
   /// StandardConversionSequence - represents a standard conversion
   /// sequence (C++ 13.3.3.1.1). A standard conversion sequence
   /// contains between zero and three conversions. If a particular
@@ -217,6 +235,9 @@
     }
    =20
     ImplicitConversionRank getRank() const;
+    NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Conver=
ted,
+                                   APValue &ConstantValue,
+                                   QualType &ConstantType) const;
     bool isPointerConversionToBool() const;
     bool isPointerConversionToVoidPointer(ASTContext& Context) const;
     void DebugPrint() const;
@@ -225,9 +246,10 @@
   /// UserDefinedConversionSequence - Represents a user-defined
   /// conversion sequence (C++ 13.3.3.1.2).
   struct UserDefinedConversionSequence {
-    /// Before - Represents the standard conversion that occurs before
-    /// the actual user-defined conversion. (C++ 13.3.3.1.2p1):
+    /// \brief Represents the standard conversion that occurs before
+    /// the actual user-defined conversion.
     ///
+    /// C++11 13.3.3.1.2p1:
     ///   If the user-defined conversion is specified by a constructor
     ///   (12.3.1), the initial standard conversion sequence converts
     ///   the source type to the type required by the argument of the
@@ -255,14 +277,15 @@
     StandardConversionSequence After;
=20
     /// ConversionFunction - The function that will perform the
-    /// user-defined conversion.
+    /// user-defined conversion. Null if the conversion is an
+    /// aggregate initialization from an initializer list.
     FunctionDecl* ConversionFunction;
=20
     /// \brief The declaration that we found via name lookup, which might =
be
     /// the same as \c ConversionFunction or it might be a using declarati=
on
     /// that refers to \c ConversionFunction.
     DeclAccessPair FoundConversionFunction;
-   =20
+
     void DebugPrint() const;
   };
=20
@@ -379,7 +402,14 @@
     };
=20
     /// ConversionKind - The kind of implicit conversion sequence.
-    unsigned ConversionKind;
+    unsigned ConversionKind : 30;
+
+    /// \brief Whether the argument is an initializer list.
+    bool ListInitializationSequence : 1;
+
+    /// \brief Whether the target is really a std::initializer_list, and t=
he
+    /// sequence only represents the worst element conversion.
+    bool StdInitializerListElement : 1;
=20
     void setKind(Kind K) {
       destruct();
@@ -409,12 +439,17 @@
       BadConversionSequence Bad;
     };
=20
-    ImplicitConversionSequence() : ConversionKind(Uninitialized) {}
+    ImplicitConversionSequence()=20
+      : ConversionKind(Uninitialized), ListInitializationSequence(false),
+        StdInitializerListElement(false)
+    {}
     ~ImplicitConversionSequence() {
       destruct();
     }
     ImplicitConversionSequence(const ImplicitConversionSequence &Other)
-      : ConversionKind(Other.ConversionKind)
+      : ConversionKind(Other.ConversionKind),=20
+        ListInitializationSequence(Other.ListInitializationSequence),
+        StdInitializerListElement(Other.StdInitializerListElement)
     {
       switch (ConversionKind) {
       case Uninitialized: break;
@@ -461,7 +496,7 @@
         return 3;
       }
=20
-      return 3;
+      llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
     }
=20
     bool isBad() const { return getKind() =3D=3D BadConversion; }
@@ -499,6 +534,26 @@
       Ambiguous.construct();
     }
=20
+    /// \brief Whether this sequence was created by the rules of
+    /// list-initialization sequences.
+    bool isListInitializationSequence() const {
+      return ListInitializationSequence;
+    }
+
+    void setListInitializationSequence() {
+      ListInitializationSequence =3D true;
+    }
+
+    /// \brief Whether the target is really a std::initializer_list, and t=
he
+    /// sequence only represents the worst element conversion.
+    bool isStdInitializerListElement() const {
+      return StdInitializerListElement;
+    }
+
+    void setStdInitializerListElement(bool V =3D true) {
+      StdInitializerListElement =3D V;
+    }
+
     // The result of a comparison between implicit conversion
     // sequences. Use Sema::CompareImplicitConversionSequences to
     // actually perform the comparison.
@@ -565,12 +620,17 @@
     CXXConversionDecl *Surrogate;
=20
     /// Conversions - The conversion sequences used to convert the
-    /// function arguments to the function parameters.
-    SmallVector<ImplicitConversionSequence, 4> Conversions;
+    /// function arguments to the function parameters, the pointer points =
to a
+    /// fixed size array with NumConversions elements. The memory is owned=
 by
+    /// the OverloadCandidateSet.
+    ImplicitConversionSequence *Conversions;
=20
     /// The FixIt hints which can be used to fix the Bad candidate.
     ConversionFixItGenerator Fix;
=20
+    /// NumConversions - The number of elements in the Conversions array.
+    unsigned NumConversions;
+
     /// Viable - True to indicate that this overload candidate is viable.
     bool Viable;
=20
@@ -639,10 +699,9 @@
     /// hasAmbiguousConversion - Returns whether this overload
     /// candidate requires an ambiguous conversion or not.
     bool hasAmbiguousConversion() const {
-      for (SmallVectorImpl<ImplicitConversionSequence>::const_iterator
-             I =3D Conversions.begin(), E =3D Conversions.end(); I !=3D E;=
 ++I) {
-        if (!I->isInitialized()) return false;
-        if (I->isAmbiguous()) return true;
+      for (unsigned i =3D 0, e =3D NumConversions; i !=3D e; ++i) {
+        if (!Conversions[i].isInitialized()) return false;
+        if (Conversions[i].isAmbiguous()) return true;
       }
       return false;
     }
@@ -663,17 +722,29 @@
=20
   /// OverloadCandidateSet - A set of overload candidates, used in C++
   /// overload resolution (C++ 13.3).
-  class OverloadCandidateSet : public SmallVector<OverloadCandidate, 16> {
-    typedef SmallVector<OverloadCandidate, 16> inherited;
+  class OverloadCandidateSet {
+    SmallVector<OverloadCandidate, 16> Candidates;
     llvm::SmallPtrSet<Decl *, 16> Functions;
=20
-    SourceLocation Loc;   =20
-   =20
+    // Allocator for OverloadCandidate::Conversions. We store the first few
+    // elements inline to avoid allocation for small sets.
+    llvm::BumpPtrAllocator ConversionSequenceAllocator;
+
+    SourceLocation Loc;
+
+    unsigned NumInlineSequences;
+    char InlineSpace[16 * sizeof(ImplicitConversionSequence)];
+
     OverloadCandidateSet(const OverloadCandidateSet &);
     OverloadCandidateSet &operator=3D(const OverloadCandidateSet &);
    =20
   public:
-    OverloadCandidateSet(SourceLocation Loc) : Loc(Loc) {}
+    OverloadCandidateSet(SourceLocation Loc) : Loc(Loc), NumInlineSequence=
s(0){}
+    ~OverloadCandidateSet() {
+      for (iterator i =3D begin(), e =3D end(); i !=3D e; ++i)
+        for (unsigned ii =3D 0, ie =3D i->NumConversions; ii !=3D ie; ++ii)
+          i->Conversions[ii].~ImplicitConversionSequence();
+    }
=20
     SourceLocation getLocation() const { return Loc; }
=20
@@ -686,6 +757,40 @@
     /// \brief Clear out all of the candidates.
     void clear();
=20
+    typedef SmallVector<OverloadCandidate, 16>::iterator iterator;
+    iterator begin() { return Candidates.begin(); }
+    iterator end() { return Candidates.end(); }
+
+    size_t size() const { return Candidates.size(); }
+    bool empty() const { return Candidates.empty(); }
+
+    /// \brief Add a new candidate with NumConversions conversion sequence=
 slots
+    /// to the overload set.
+    OverloadCandidate &addCandidate(unsigned NumConversions =3D 0) {
+      Candidates.push_back(OverloadCandidate());
+      OverloadCandidate &C =3D Candidates.back();
+
+      // Assign space from the inline array if there are enough free slots
+      // available.
+      if (NumConversions + NumInlineSequences <=3D 16) {
+        ImplicitConversionSequence *I =3D
+          (ImplicitConversionSequence*)InlineSpace;
+        C.Conversions =3D &I[NumInlineSequences];
+        NumInlineSequences +=3D NumConversions;
+      } else {
+        // Otherwise get memory from the allocator.
+        C.Conversions =3D ConversionSequenceAllocator
+                          .Allocate<ImplicitConversionSequence>(NumConvers=
ions);
+      }
+
+      // Construct the new objects.
+      for (unsigned i =3D 0; i !=3D NumConversions; ++i)
+        new (&C.Conversions[i]) ImplicitConversionSequence();
+
+      C.NumConversions =3D NumConversions;
+      return C;
+    }
+
     /// Find the best viable function on this overload set, if it exists.
     OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
                                          OverloadCandidateSet::iterator& B=
est,
@@ -693,7 +798,7 @@
=20
     void NoteCandidates(Sema &S,
                         OverloadCandidateDisplayKind OCD,
-                        Expr **Args, unsigned NumArgs,
+                        llvm::ArrayRef<Expr *> Args,
                         const char *Opc =3D 0,
                         SourceLocation Loc =3D SourceLocation());
   };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/ParsedTemplate.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/ParsedTemplate.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/ParsedTemplate.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -141,7 +141,11 @@
   struct TemplateIdAnnotation {
     /// \brief The nested-name-specifier that precedes the template name.
     CXXScopeSpec SS;
-   =20
+
+    /// TemplateKWLoc - The location of the template keyword within the
+    /// source.
+    SourceLocation TemplateKWLoc;
+
     /// TemplateNameLoc - The location of the template name within the
     /// source.
     SourceLocation TemplateNameLoc;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/PrettyDeclStackTrace.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/PrettyDeclStackTrace=
.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/PrettyDeclStackTrace=
.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,9 +33,10 @@
   Decl *TheDecl;
   SourceLocation Loc;
   const char *Message;
- =20
+
 public:
-  PrettyDeclStackTraceEntry(Sema &S, Decl *D, SourceLocation Loc, const ch=
ar *Msg)
+  PrettyDeclStackTraceEntry(Sema &S, Decl *D, SourceLocation Loc,
+                            const char *Msg)
     : S(S), TheDecl(D), Loc(Loc), Message(Msg) {}
=20
   virtual void print(raw_ostream &OS) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/Scope.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/Scope.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/Scope.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -57,7 +57,7 @@
     /// BlockScope - This is a scope that corresponds to a block/closure o=
bject.
     /// Blocks serve as top-level scopes for some objects like labels, they
     /// also prevent things like break and continue.  BlockScopes always h=
ave
-    /// the FnScope, BreakScope, ContinueScope, and DeclScope flags set as=
 well.
+    /// the FnScope and DeclScope flags set as well.
     BlockScope =3D 0x40,
=20
     /// TemplateParamScope - This is a scope that corresponds to the
@@ -114,16 +114,12 @@
   /// pointer is non-null and points to it.  This is used for label proces=
sing.
   Scope *FnParent;
=20
-  /// BreakParent/ContinueParent - This is a direct link to the immediately
-  /// preceding BreakParent/ContinueParent if this scope is not one, or nu=
ll if
-  /// there is no containing break/continue scope.
+  /// BreakParent/ContinueParent - This is a direct link to the innermost
+  /// BreakScope/ContinueScope which contains the contents of this scope
+  /// for control flow purposes (and might be this scope itself), or null
+  /// if there is no such scope.
   Scope *BreakParent, *ContinueParent;
=20
-  /// ControlParent - This is a direct link to the immediately
-  /// preceding ControlParent if this scope is not one, or null if
-  /// there is no containing control scope.
-  Scope *ControlParent;
-
   /// BlockParent - This is a direct link to the immediately containing
   /// BlockScope if this scope is not one, or null if there is none.
   Scope *BlockParent;
@@ -180,12 +176,9 @@
   Scope *getFnParent() { return FnParent; }
=20
   /// getContinueParent - Return the closest scope that a continue stateme=
nt
-  /// would be affected by.  If the closest scope is a closure scope, we k=
now
-  /// that there is no loop *inside* the closure.
+  /// would be affected by.
   Scope *getContinueParent() {
-    if (ContinueParent && !ContinueParent->isBlockScope())
-      return ContinueParent;
-    return 0;
+    return ContinueParent;
   }
=20
   const Scope *getContinueParent() const {
@@ -193,20 +186,14 @@
   }
=20
   /// getBreakParent - Return the closest scope that a break statement
-  /// would be affected by.  If the closest scope is a block scope, we know
-  /// that there is no loop *inside* the block.
+  /// would be affected by.
   Scope *getBreakParent() {
-    if (BreakParent && !BreakParent->isBlockScope())
-      return BreakParent;
-    return 0;
+    return BreakParent;
   }
   const Scope *getBreakParent() const {
     return const_cast<Scope*>(this)->getBreakParent();
   }
=20
-  Scope *getControlParent() { return ControlParent; }
-  const Scope *getControlParent() const { return ControlParent; }
-
   Scope *getBlockParent() { return BlockParent; }
   const Scope *getBlockParent() const { return BlockParent; }
=20
@@ -310,6 +297,10 @@
   /// \brief Determine whether this scope is a C++ 'try' block.
   bool isTryScope() const { return getFlags() & Scope::TryScope; }
=20
+  /// containedInPrototypeScope - Return true if this or a parent scope
+  /// is a FunctionPrototypeScope.
+  bool containedInPrototypeScope() const;
+
   typedef UsingDirectivesTy::iterator udir_iterator;
   typedef UsingDirectivesTy::const_iterator const_udir_iterator;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/ScopeInfo.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/ScopeInfo.h	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/ScopeInfo.h	Tue Apr =
17 11:51:51 2012 +0300
@@ -18,19 +18,36 @@
 #include "clang/Basic/PartialDiagnostic.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/SetVector.h"
=20
 namespace clang {
=20
 class BlockDecl;
+class CXXMethodDecl;
 class IdentifierInfo;
 class LabelDecl;
 class ReturnStmt;
 class Scope;
 class SwitchStmt;
+class VarDecl;
=20
 namespace sema {
=20
+/// \brief Contains information about the compound statement currently bei=
ng
+/// parsed.
+class CompoundScopeInfo {
+public:
+  CompoundScopeInfo()
+    : HasEmptyLoopBodies(false) { }
+
+  /// \brief Whether this compound stamement contains `for' or `while' loo=
ps
+  /// with empty bodies.
+  bool HasEmptyLoopBodies;
+
+  void setHasEmptyLoopBodies() {
+    HasEmptyLoopBodies =3D true;
+  }
+};
+
 class PossiblyUnreachableDiag {
 public:
   PartialDiagnostic PD;
@@ -45,11 +62,17 @@
 /// \brief Retains information about a function, method, or block that is
 /// currently being parsed.
 class FunctionScopeInfo {
+protected:
+  enum ScopeKind {
+    SK_Function,
+    SK_Block,
+    SK_Lambda
+  };
+ =20
 public:
-
-  /// \brief Whether this scope information structure defined information =
for
-  /// a block.
-  bool IsBlockInfo;
+  /// \brief What kind of scope we are describing.
+  ///
+  ScopeKind Kind;
=20
   /// \brief Whether this function contains a VLA, @try, try, C++
   /// initializer, or anything else that can't be jumped past.
@@ -72,7 +95,11 @@
   /// block, if there is any chance of applying the named return value
   /// optimization.
   SmallVector<ReturnStmt*, 4> Returns;
- =20
+
+  /// \brief The stack of currently active compound stamement scopes in the
+  /// function.
+  SmallVector<CompoundScopeInfo, 4> CompoundScopes;
+
   /// \brief A list of PartialDiagnostics created but delayed within the
   /// current function scope.  These diagnostics are vetted for reachabili=
ty
   /// prior to being emitted.
@@ -96,7 +123,7 @@
   }
  =20
   FunctionScopeInfo(DiagnosticsEngine &Diag)
-    : IsBlockInfo(false),
+    : Kind(SK_Function),
       HasBranchProtectedScope(false),
       HasBranchIntoScope(false),
       HasIndirectGoto(false),
@@ -111,8 +138,162 @@
   static bool classof(const FunctionScopeInfo *FSI) { return true; }
 };
=20
+class CapturingScopeInfo : public FunctionScopeInfo {
+public:
+  enum ImplicitCaptureStyle {
+    ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block
+  };
+
+  ImplicitCaptureStyle ImpCaptureStyle;
+
+  class Capture {
+    // There are two categories of capture: capturing 'this', and capturing
+    // local variables.  There are three ways to capture a local variable:
+    // capture by copy in the C++11 sense, capture by reference
+    // in the C++11 sense, and __block capture.  Lambdas explicitly specify
+    // capture by copy or capture by reference.  For blocks, __block captu=
re
+    // applies to variables with that annotation, variables of reference t=
ype
+    // are captured by reference, and other variables are captured by copy.
+    enum CaptureKind {
+      Cap_This, Cap_ByCopy, Cap_ByRef, Cap_Block
+    };
+
+    // The variable being captured (if we are not capturing 'this'),
+    // and misc bits descibing the capture.
+    llvm::PointerIntPair<VarDecl*, 2, CaptureKind> VarAndKind;
+
+    // Expression to initialize a field of the given type, and whether this
+    // is a nested capture; the expression is only required if we are
+    // capturing ByVal and the variable's type has a non-trivial
+    // copy constructor.
+    llvm::PointerIntPair<Expr*, 1, bool> CopyExprAndNested;
+
+    /// \brief The source location at which the first capture occurred..
+    SourceLocation Loc;
+   =20
+    /// \brief The location of the ellipsis that expands a parameter pack.
+    SourceLocation EllipsisLoc;
+   =20
+    /// \brief The type as it was captured, which is in effect the type of=
 the
+    /// non-static data member that would hold the capture.
+    QualType CaptureType;
+   =20
+  public:
+    Capture(VarDecl *Var, bool block, bool byRef, bool isNested,=20
+            SourceLocation Loc, SourceLocation EllipsisLoc,=20
+            QualType CaptureType, Expr *Cpy)
+      : VarAndKind(Var, block ? Cap_Block : byRef ? Cap_ByRef : Cap_ByCopy=
),
+        CopyExprAndNested(Cpy, isNested), Loc(Loc), EllipsisLoc(EllipsisLo=
c),
+        CaptureType(CaptureType){}
+
+    enum IsThisCapture { ThisCapture };
+    Capture(IsThisCapture, bool isNested, SourceLocation Loc,=20
+            QualType CaptureType, Expr *Cpy)
+      : VarAndKind(0, Cap_This), CopyExprAndNested(Cpy, isNested), Loc(Loc=
),
+        EllipsisLoc(), CaptureType(CaptureType) { }
+
+    bool isThisCapture() const { return VarAndKind.getInt() =3D=3D Cap_Thi=
s; }
+    bool isVariableCapture() const { return !isThisCapture(); }
+    bool isCopyCapture() const { return VarAndKind.getInt() =3D=3D Cap_ByC=
opy; }
+    bool isReferenceCapture() const { return VarAndKind.getInt() =3D=3D Ca=
p_ByRef; }
+    bool isBlockCapture() const { return VarAndKind.getInt() =3D=3D Cap_Bl=
ock; }
+    bool isNested() { return CopyExprAndNested.getInt(); }
+
+    VarDecl *getVariable() const {
+      return VarAndKind.getPointer();
+    }
+   =20
+    /// \brief Retrieve the location at which this variable was captured.
+    SourceLocation getLocation() const { return Loc; }
+   =20
+    /// \brief Retrieve the source location of the ellipsis, whose presence
+    /// indicates that the capture is a pack expansion.
+    SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
+   =20
+    /// \brief Retrieve the capture type for this capture, which is effect=
ively
+    /// the type of the non-static data member in the lambda/block structu=
re
+    /// that would store this capture.
+    QualType getCaptureType() const { return CaptureType; }
+   =20
+    Expr *getCopyExpr() const {
+      return CopyExprAndNested.getPointer();
+    }
+  };
+
+  CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
+    : FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex=
(0),
+      HasImplicitReturnType(false)
+     {}
+
+  /// CaptureMap - A map of captured variables to (index+1) into Captures.
+  llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
+
+  /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
+  /// zero if 'this' is not captured.
+  unsigned CXXThisCaptureIndex;
+
+  /// Captures - The captures.
+  SmallVector<Capture, 4> Captures;
+
+  /// \brief - Whether the target type of return statements in this context
+  /// is deduced (e.g. a lambda or block with omitted return type).
+  bool HasImplicitReturnType;
+
+  /// ReturnType - The target type of return statements in this context,
+  /// or null if unknown.
+  QualType ReturnType;
+
+  void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
+                  SourceLocation Loc, SourceLocation EllipsisLoc,=20
+                  QualType CaptureType, Expr *Cpy) {
+    Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,=20
+                               EllipsisLoc, CaptureType, Cpy));
+    CaptureMap[Var] =3D Captures.size();
+  }
+
+  void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureT=
ype,
+                      Expr *Cpy) {
+    Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, Captur=
eType,
+                               Cpy));
+    CXXThisCaptureIndex =3D Captures.size();
+  }
+
+  /// \brief Determine whether the C++ 'this' is captured.
+  bool isCXXThisCaptured() const { return CXXThisCaptureIndex !=3D 0; }
+ =20
+  /// \brief Retrieve the capture of C++ 'this', if it has been captured.
+  Capture &getCXXThisCapture() {
+    assert(isCXXThisCaptured() && "this has not been captured");
+    return Captures[CXXThisCaptureIndex - 1];
+  }
+ =20
+  /// \brief Determine whether the given variable has been captured.
+  bool isCaptured(VarDecl *Var) const {
+    return CaptureMap.count(Var);
+  }
+ =20
+  /// \brief Retrieve the capture of the given variable, if it has been
+  /// captured already.
+  Capture &getCapture(VarDecl *Var) {
+    assert(isCaptured(Var) && "Variable has not been captured");
+    return Captures[CaptureMap[Var] - 1];
+  }
+
+  const Capture &getCapture(VarDecl *Var) const {
+    llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
+      =3D CaptureMap.find(Var);
+    assert(Known !=3D CaptureMap.end() && "Variable has not been captured"=
);
+    return Captures[Known->second - 1];
+  }
+
+  static bool classof(const FunctionScopeInfo *FSI) {=20
+    return FSI->Kind =3D=3D SK_Block || FSI->Kind =3D=3D SK_Lambda;=20
+  }
+  static bool classof(const CapturingScopeInfo *BSI) { return true; }
+};
+
 /// \brief Retains information about a block that is currently being parse=
d.
-class BlockScopeInfo : public FunctionScopeInfo {
+class BlockScopeInfo : public CapturingScopeInfo {
 public:
   BlockDecl *TheDecl;
  =20
@@ -120,36 +301,79 @@
   /// arguments etc.
   Scope *TheScope;
=20
-  /// ReturnType - The return type of the block, or null if the block
-  /// signature didn't provide an explicit return type.
-  QualType ReturnType;
-
   /// BlockType - The function type of the block, if one was given.
   /// Its return type may be BuiltinType::Dependent.
   QualType FunctionType;
=20
-  /// CaptureMap - A map of captured variables to (index+1) into Captures.
-  llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
-
-  /// Captures - The captured variables.
-  SmallVector<BlockDecl::Capture, 4> Captures;
-
-  /// CapturesCXXThis - Whether this block captures 'this'.
-  bool CapturesCXXThis;
-
   BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Bl=
ock)
-    : FunctionScopeInfo(Diag), TheDecl(Block), TheScope(BlockScope),
-      CapturesCXXThis(false)
+    : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
+      TheScope(BlockScope)
   {
-    IsBlockInfo =3D true;
+    Kind =3D SK_Block;
   }
=20
   virtual ~BlockScopeInfo();
=20
-  static bool classof(const FunctionScopeInfo *FSI) { return FSI->IsBlockI=
nfo; }
+  static bool classof(const FunctionScopeInfo *FSI) {=20
+    return FSI->Kind =3D=3D SK_Block;=20
+  }
   static bool classof(const BlockScopeInfo *BSI) { return true; }
 };
=20
+class LambdaScopeInfo : public CapturingScopeInfo {
+public:
+  /// \brief The class that describes the lambda.
+  CXXRecordDecl *Lambda;
+
+  /// \brief The class that describes the lambda.
+  CXXMethodDecl *CallOperator;
+
+  /// \brief Source range covering the lambda introducer [...].
+  SourceRange IntroducerRange;
+
+  /// \brief The number of captures in the \c Captures list that are=20
+  /// explicit captures.
+  unsigned NumExplicitCaptures;
+
+  /// \brief Whether this is a mutable lambda.
+  bool Mutable;
+ =20
+  /// \brief Whether the (empty) parameter list is explicit.
+  bool ExplicitParams;
+
+  /// \brief Whether any of the capture expressions requires cleanups.
+  bool ExprNeedsCleanups;
+
+  /// \brief Variables used to index into by-copy array captures.
+  llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
+
+  /// \brief Offsets into the ArrayIndexVars array at which each capture s=
tarts
+  /// its list of array index variables.
+  llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
+ =20
+  LambdaScopeInfo(DiagnosticsEngine &Diag, CXXRecordDecl *Lambda,
+                  CXXMethodDecl *CallOperator)
+    : CapturingScopeInfo(Diag, ImpCap_None), Lambda(Lambda),
+      CallOperator(CallOperator), NumExplicitCaptures(0), Mutable(false),
+      ExprNeedsCleanups(false)
+  {
+    Kind =3D SK_Lambda;
+  }
+
+  virtual ~LambdaScopeInfo();
+
+  /// \brief Note when=20
+  void finishedExplicitCaptures() {
+    NumExplicitCaptures =3D Captures.size();
+  }
+ =20
+  static bool classof(const FunctionScopeInfo *FSI) {=20
+    return FSI->Kind =3D=3D SK_Lambda;=20
+  }
+  static bool classof(const LambdaScopeInfo *BSI) { return true; }
+
+};
+
 }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/Sema.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/Sema.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/Sema.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -22,13 +22,15 @@
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/ExternalSemaSource.h"
 #include "clang/Sema/LocInfoType.h"
-#include "clang/Sema/MultiInitializer.h"
 #include "clang/Sema/TypoCorrection.h"
 #include "clang/Sema/Weak.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/AST/DeclarationName.h"
 #include "clang/AST/ExternalASTSource.h"
 #include "clang/AST/TypeLoc.h"
+#include "clang/AST/NSAPI.h"
+#include "clang/Lex/ModuleLoader.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TemplateKinds.h"
 #include "clang/Basic/TypeTraits.h"
@@ -44,6 +46,7 @@
   class APSInt;
   template <typename ValueT> struct DenseMapInfo;
   template <typename ValueT, typename ValueInfoT> class DenseSet;
+  class SmallBitVector;
 }
=20
 namespace clang {
@@ -58,6 +61,7 @@
   class BlockDecl;
   class CXXBasePath;
   class CXXBasePaths;
+  class CXXBindTemporaryExpr;
   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
   class CXXConstructorDecl;
   class CXXConversionDecl;
@@ -74,6 +78,7 @@
   class ClassTemplateSpecializationDecl;
   class CodeCompleteConsumer;
   class CodeCompletionAllocator;
+  class CodeCompletionTUInfo;
   class CodeCompletionResult;
   class Decl;
   class DeclAccessPair;
@@ -100,6 +105,7 @@
   class InitializedEntity;
   class IntegerLiteral;
   class LabelStmt;
+  class LambdaExpr;
   class LangOptions;
   class LocalInstantiationScope;
   class LookupResult;
@@ -126,6 +132,7 @@
   class ParmVarDecl;
   class Preprocessor;
   class PseudoDestructorTypeStorage;
+  class PseudoObjectExpr;
   class QualType;
   class StandardConversionSequence;
   class Stmt;
@@ -156,12 +163,15 @@
   class VisibilityAttr;
   class VisibleDeclConsumer;
   class IndirectFieldDecl;
- =20
+
 namespace sema {
   class AccessedEntity;
   class BlockScopeInfo;
+  class CompoundScopeInfo;
   class DelayedDiagnostic;
   class FunctionScopeInfo;
+  class LambdaScopeInfo;
+  class PossiblyUnreachableDiag;
   class TemplateDeductionInfo;
 }
=20
@@ -213,7 +223,7 @@
   /// PackContext - Manages the stack for #pragma pack. An alignment
   /// of 0 indicates default alignment.
   void *PackContext; // Really a "PragmaPackStack*"
-   =20
+
   bool MSStructPragmaOn; // True when #pragma ms_struct on
=20
   /// VisContext - Manages the stack for #pragma GCC visibility.
@@ -223,6 +233,13 @@
   /// requires cleanups to be run at its conclusion.
   bool ExprNeedsCleanups;
=20
+  /// ExprCleanupObjects - This is the stack of objects requiring
+  /// cleanup that are created by the current full expression.  The
+  /// element type here is ExprWithCleanups::Object.
+  SmallVector<BlockDecl*, 8> ExprCleanupObjects;
+
+  llvm::SmallPtrSet<Expr*, 8> MaybeODRUseExprs;
+
   /// \brief Stack containing information about each of the nested
   /// function, block, and method scopes that are currently active.
   ///
@@ -231,11 +248,7 @@
   /// that's used to parse every top-level function.
   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
=20
-  /// ExprTemporaries - This is the stack of temporaries that are created =
by
-  /// the current full expression.
-  SmallVector<CXXTemporary*, 8> ExprTemporaries;
-
-  typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,=20
+  typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
     ExtVectorDeclsType;
=20
@@ -244,15 +257,21 @@
   /// This is only necessary for issuing pretty diagnostics.
   ExtVectorDeclsType ExtVectorDecls;
=20
+  /// \brief The set of types for which we have already complained about t=
he
+  /// definitions being hidden.
+  ///
+  /// This set is used to suppress redundant diagnostics.
+  llvm::SmallPtrSet<NamedDecl *, 4> HiddenDefinitions;
+ =20
   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classe=
s.
-  llvm::OwningPtr<CXXFieldCollector> FieldCollector;
+  OwningPtr<CXXFieldCollector> FieldCollector;
=20
   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
=20
   /// PureVirtualClassDiagSet - a set of class declarations which we have
   /// emitted a list of pure virtual functions. Used to prevent emitting t=
he
   /// same list more than once.
-  llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
+  OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet;
=20
   /// ParsingInitForAutoVars - a set of declarations with auto types for w=
hich
   /// we are currently parsing the initializer.
@@ -284,27 +303,27 @@
   ///     we find this declaration of "foo" and complain that it is
   ///     not visible.
   llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls;
- =20
+
   /// \brief Look for a locally scoped external declaration by the given n=
ame.
   llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
   findLocallyScopedExternalDecl(DeclarationName Name);
- =20
-  typedef LazyVector<VarDecl *, ExternalSemaSource,=20
+
+  typedef LazyVector<VarDecl *, ExternalSemaSource,
                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
     TentativeDefinitionsType;
=20
   /// \brief All the tentative definitions encountered in the TU.
   TentativeDefinitionsType TentativeDefinitions;
=20
-  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,=20
+  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
     UnusedFileScopedDeclsType;
- =20
+
   /// \brief The set of file scoped decls seen so far that have not been u=
sed
   /// and must warn if not used. Only contains the first declaration.
   UnusedFileScopedDeclsType UnusedFileScopedDecls;
=20
-  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,=20
+  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
     DelegatingCtorDeclsType;
=20
@@ -322,11 +341,11 @@
   /// \brief Callback to the parser to parse templated functions when need=
ed.
   typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD);
   LateTemplateParserCB *LateTemplateParser;
-  void *OpaqueParser;=20
+  void *OpaqueParser;
=20
   void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
     LateTemplateParser =3D LTP;
-    OpaqueParser =3D P;=20
+    OpaqueParser =3D P;
   }
=20
   class DelayedDiagnostics;
@@ -418,7 +437,7 @@
       assert(ParsingDepth =3D=3D 0);
       ActiveStackBase =3D state.SavedActiveStackBase;
       ParsingDepth =3D state.SavedParsingDepth;
-    } =20
+    }
   } DelayedDiagnostics;
=20
   /// A RAII object to temporarily push a declaration context.
@@ -427,11 +446,11 @@
     Sema &S;
     DeclContext *SavedContext;
     ProcessingContextState SavedContextState;
-   =20
+
   public:
     ContextRAII(Sema &S, DeclContext *ContextToPush)
-      : S(S), SavedContext(S.CurContext),=20
-        SavedContextState(S.DelayedDiagnostics.pushContext())=20
+      : S(S), SavedContext(S.CurContext),
+        SavedContextState(S.DelayedDiagnostics.pushContext())
     {
       assert(ContextToPush && "pushing null context");
       S.CurContext =3D ContextToPush;
@@ -454,9 +473,16 @@
   /// identifier, declared or undeclared
   llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers;
=20
+  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
+  /// #pragma redefine_extname before declared.  Used in Solaris system he=
aders
+  /// to define functions that occur in multiple standards to call the ver=
sion
+  /// in the currently selected standard.
+  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifie=
rs;
+
+
   /// \brief Load weak undeclared identifiers from the external source.
   void LoadExternalWeakUndeclaredIdentifiers();
- =20
+
   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
   /// #pragma weak during processing of other Decls.
   /// I couldn't figure out a clean way to generate these in-line, so
@@ -478,17 +504,44 @@
   /// standard library.
   LazyDeclPtr StdBadAlloc;
=20
+  /// \brief The C++ "std::initializer_list" template, which is defined in
+  /// <initializer_list>.
+  ClassTemplateDecl *StdInitializerList;
+
   /// \brief The C++ "type_info" declaration, which is defined in <typeinf=
o>.
   RecordDecl *CXXTypeInfoDecl;
- =20
+
   /// \brief The MSVC "_GUID" struct, which is defined in MSVC header file=
s.
   RecordDecl *MSVCGuidDecl;
=20
+  /// \brief Caches identifiers/selectors for NSFoundation APIs.
+  llvm::OwningPtr<NSAPI> NSAPIObj;
+
+  /// \brief The declaration of the Objective-C NSNumber class.
+  ObjCInterfaceDecl *NSNumberDecl;
+ =20
+  /// \brief The Objective-C NSNumber methods used to create NSNumber lite=
rals.
+  ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
+ =20
+  /// \brief The declaration of the Objective-C NSArray class.
+  ObjCInterfaceDecl *NSArrayDecl;
+
+  /// \brief The declaration of the arrayWithObjects:count: method.
+  ObjCMethodDecl *ArrayWithObjectsMethod;
+ =20
+  /// \brief The declaration of the Objective-C NSDictionary class.
+  ObjCInterfaceDecl *NSDictionaryDecl;
+
+  /// \brief The declaration of the dictionaryWithObjects:forKeys:count: m=
ethod.
+  ObjCMethodDecl *DictionaryWithObjectsMethod;
+
+  /// \brief id<NSCopying> type.
+  QualType QIDNSCopying;
+
   /// A flag to remember whether the implicit forms of operator new and de=
lete
   /// have been declared.
   bool GlobalNewDeleteDeclared;
=20
-
   /// A flag that is set when parsing a -dealloc method and no [super deal=
loc]
   /// call was found yet.
   bool ObjCShouldCallSuperDealloc;
@@ -496,37 +549,26 @@
   /// call was found yet.
   bool ObjCShouldCallSuperFinalize;
=20
-  /// \brief The set of declarations that have been referenced within
-  /// a potentially evaluated expression.
-  typedef SmallVector<std::pair<SourceLocation, Decl *>, 10>
-    PotentiallyReferencedDecls;
-
-  /// \brief A set of diagnostics that may be emitted.
-  typedef SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10>
-    PotentiallyEmittedDiagnostics;
-
   /// \brief Describes how the expressions currently being parsed are
   /// evaluated at run-time, if at all.
   enum ExpressionEvaluationContext {
     /// \brief The current expression and its subexpressions occur within =
an
-    /// unevaluated operand (C++0x [expr]p8), such as a constant expression
-    /// or the subexpression of \c sizeof, where the type or the value of =
the
-    /// expression may be significant but no code will be generated to eva=
luate
-    /// the value of the expression at run time.
+    /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
+    /// \c sizeof, where the type of the expression may be significant but
+    /// no code will be generated to evaluate the value of the expression =
at
+    /// run time.
     Unevaluated,
=20
+    /// \brief The current context is "potentially evaluated" in C++11 ter=
ms,
+    /// but the expression is evaluated at compile-time (like the values of
+    /// cases in a switch statment).
+    ConstantEvaluated,
+
     /// \brief The current expression is potentially evaluated at run time,
     /// which means that code may be generated to evaluate the value of the
     /// expression at run time.
     PotentiallyEvaluated,
=20
-    /// \brief The current expression may be potentially evaluated or it m=
ay
-    /// be unevaluated, but it is impossible to tell from the lexical cont=
ext.
-    /// This evaluation context is used primary for the operand of the C++
-    /// \c typeid expression, whose argument is potentially evaluated only=
 when
-    /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2).
-    PotentiallyPotentiallyEvaluated,
-   =20
     /// \brief The current expression is potentially evaluated, but any
     /// declarations referenced inside that expression are only used if
     /// in fact the current expression is used.
@@ -547,47 +589,58 @@
     /// \brief Whether the enclosing context needed a cleanup.
     bool ParentNeedsCleanups;
=20
-    /// \brief The number of temporaries that were active when we
-    /// entered this expression evaluation context.
-    unsigned NumTemporaries;
-
-    /// \brief The set of declarations referenced within a
-    /// potentially potentially-evaluated context.
+    /// \brief Whether we are in a decltype expression.
+    bool IsDecltype;
+
+    /// \brief The number of active cleanup objects when we entered
+    /// this expression evaluation context.
+    unsigned NumCleanupObjects;
+
+    llvm::SmallPtrSet<Expr*, 8> SavedMaybeODRUseExprs;
+
+    /// \brief The lambdas that are present within this context, if it
+    /// is indeed an unevaluated context.
+    llvm::SmallVector<LambdaExpr *, 2> Lambdas;
+
+    /// \brief The declaration that provides context for the lambda expres=
sion
+    /// if the normal declaration context does not suffice, e.g., in a=20
+    /// default function argument.
+    Decl *LambdaContextDecl;
+   =20
+    /// \brief The context information used to mangle lambda expressions
+    /// within this context.
     ///
-    /// When leaving a potentially potentially-evaluated context, each
-    /// of these elements will be as referenced if the corresponding
-    /// potentially potentially evaluated expression is potentially
-    /// evaluated.
-    PotentiallyReferencedDecls *PotentiallyReferenced;
-
-    /// \brief The set of diagnostics to emit should this potentially
-    /// potentially-evaluated context become evaluated.
-    PotentiallyEmittedDiagnostics *PotentiallyDiagnosed;
-
+    /// This mangling information is allocated lazily, since most contexts
+    /// do not have lambda expressions.
+    LambdaMangleContext *LambdaMangle;
+
+    /// \brief If we are processing a decltype type, a set of call express=
ions
+    /// for which we have deferred checking the completeness of the return=
 type.
+    llvm::SmallVector<CallExpr*, 8> DelayedDecltypeCalls;
+
+    /// \brief If we are processing a decltype type, a set of temporary bi=
nding
+    /// expressions for which we have deferred checking the destructor.
+    llvm::SmallVector<CXXBindTemporaryExpr*, 8> DelayedDecltypeBinds;
+   =20
     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
-                                      unsigned NumTemporaries,
-                                      bool ParentNeedsCleanups)
+                                      unsigned NumCleanupObjects,
+                                      bool ParentNeedsCleanups,
+                                      Decl *LambdaContextDecl,
+                                      bool IsDecltype)
       : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
-        NumTemporaries(NumTemporaries),
-        PotentiallyReferenced(0), PotentiallyDiagnosed(0) { }
-
-    void addReferencedDecl(SourceLocation Loc, Decl *Decl) {
-      if (!PotentiallyReferenced)
-        PotentiallyReferenced =3D new PotentiallyReferencedDecls;
-      PotentiallyReferenced->push_back(std::make_pair(Loc, Decl));
+        IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
+        LambdaContextDecl(LambdaContextDecl), LambdaMangle() { }
+   =20
+    ~ExpressionEvaluationContextRecord() {
+      delete LambdaMangle;
     }
-
-    void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) {
-      if (!PotentiallyDiagnosed)
-        PotentiallyDiagnosed =3D new PotentiallyEmittedDiagnostics;
-      PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD));
-    }
-
-    void Destroy() {
-      delete PotentiallyReferenced;
-      delete PotentiallyDiagnosed;
-      PotentiallyReferenced =3D 0;
-      PotentiallyDiagnosed =3D 0;
+   =20
+    /// \brief Retrieve the mangling context for lambdas.
+    LambdaMangleContext &getLambdaMangleContext() {
+      assert(LambdaContextDecl && "Need to have a lambda context declarati=
on");
+      if (!LambdaMangle)
+        LambdaMangle =3D new LambdaMangleContext;
+      return *LambdaMangle;
     }
   };
=20
@@ -608,7 +661,17 @@
   /// This is used for determining parameter types of other objects and is
   /// utterly meaningless on other types of special members.
   class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
+  public:
+    enum Kind {
+      NoMemberOrDeleted,
+      Ambiguous,
+      SuccessNonConst,
+      SuccessConst
+    };
+
+  private:
     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
+
   public:
     SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
       : FastFoldingSetNode(ID)
@@ -617,15 +680,11 @@
     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
=20
-    bool hasSuccess() const { return Pair.getInt() & 0x1; }
-    void setSuccess(bool B) {
-      Pair.setInt(unsigned(B) | hasConstParamMatch() << 1);
-    }
-
-    bool hasConstParamMatch() const { return Pair.getInt() & 0x2; }
-    void setConstParamMatch(bool B) {
-      Pair.setInt(B << 1 | unsigned(hasSuccess()));
-    }
+    Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
+    void setKind(Kind K) { Pair.setInt(K); }
+
+    bool hasSuccess() const { return getKind() >=3D SuccessNonConst; }
+    bool hasConstParamMatch() const { return getKind() =3D=3D SuccessConst=
; }
   };
=20
   /// \brief A cache of special member function overload resolution results
@@ -648,16 +707,16 @@
=20
   typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> >
     UnparsedDefaultArgInstantiationsMap;
- =20
+
   /// \brief A mapping from parameters with unparsed default arguments to =
the
   /// set of instantiations of each parameter.
   ///
   /// This mapping is a temporary data structure used when parsing
   /// nested class templates or nested classes of class templates,
   /// where we might end up instantiating an inner class before the
-  /// default arguments of its methods have been parsed.=20
+  /// default arguments of its methods have been parsed.
   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
- =20
+
   // Contains the locations of the beginning of unparsed default
   // argument locations.
   llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs;
@@ -675,25 +734,31 @@
   /// of selectors are "overloaded").
   GlobalMethodPool MethodPool;
=20
-  /// Method selectors used in a @selector expression. Used for implementa=
tion=20
+  /// Method selectors used in a @selector expression. Used for implementa=
tion
   /// of -Wselector.
   llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors;
=20
-  GlobalMethodPool::iterator ReadMethodPool(Selector Sel);
+  void ReadMethodPool(Selector Sel);
=20
   /// Private Helper predicate to check for 'self'.
   bool isSelfExpr(Expr *RExpr);
+
+  /// \brief Cause the active diagnostic on the DiagosticsEngine to be
+  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class =
and
+  /// should not be used elsewhere.
+  void EmitCurrentDiagnostic(unsigned DiagID);
+
 public:
   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
        TranslationUnitKind TUKind =3D TU_Complete,
        CodeCompleteConsumer *CompletionConsumer =3D 0);
   ~Sema();
- =20
+
   /// \brief Perform initialization that occurs after the parser has been
   /// initialized but before it parses anything.
   void Initialize();
- =20
-  const LangOptions &getLangOptions() const { return LangOpts; }
+
+  const LangOptions &getLangOpts() const { return LangOpts; }
   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
   FPOptions     &getFPOptions() { return FPFeatures; }
=20
@@ -724,14 +789,32 @@
     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned D=
iagID)
       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
=20
-    explicit SemaDiagnosticBuilder(Sema &SemaRef)
-      : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) {=
 }
-
-    ~SemaDiagnosticBuilder();
+    ~SemaDiagnosticBuilder() {
+      // If we aren't active, there is nothing to do.
+      if (!isActive()) return;
+
+      // Otherwise, we need to emit the diagnostic. First flush the underl=
ying
+      // DiagnosticBuilder data, and clear the diagnostic builder itself s=
o it
+      // won't emit the diagnostic in its own destructor.
+      //
+      // This seems wasteful, in that as written the DiagnosticBuilder dto=
r will
+      // do its own needless checks to see if the diagnostic needs to be
+      // emitted. However, because we take care to ensure that the builder
+      // objects never escape, a sufficiently smart compiler will be able =
to
+      // eliminate that code.
+      FlushCounts();
+      Clear();
+
+      // Dispatch to Sema to emit the diagnostic.
+      SemaRef.EmitCurrentDiagnostic(DiagID);
+    }
   };
=20
   /// \brief Emit a diagnostic.
-  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
+  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
+    DiagnosticBuilder DB =3D Diags.Report(Loc, DiagID);
+    return SemaDiagnosticBuilder(DB, *this, DiagID);
+  }
=20
   /// \brief Emit a partial diagnostic.
   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& =
PD);
@@ -741,6 +824,9 @@
=20
   bool findMacroSpelling(SourceLocation &loc, StringRef name);
=20
+  /// \brief Get a string to suggest for zero-initialization of a type.
+  const char *getFixItZeroInitializerForType(QualType T) const;
+
   ExprResult Owned(Expr* E) { return E; }
   ExprResult Owned(ExprResult R) { return R; }
   StmtResult Owned(Stmt* S) { return S; }
@@ -753,18 +839,27 @@
=20
   void PushFunctionScope();
   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
-  void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *=
WP =3D0,
-                               const Decl *D =3D 0, const BlockExpr *blkEx=
pr =3D 0);
+  void PushLambdaScope(CXXRecordDecl *Lambda, CXXMethodDecl *CallOperator);
+  void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =
=3D0,
+                            const Decl *D =3D 0, const BlockExpr *blkExpr =
=3D 0);
=20
   sema::FunctionScopeInfo *getCurFunction() const {
     return FunctionScopes.back();
   }
=20
+  void PushCompoundScope();
+  void PopCompoundScope();
+
+  sema::CompoundScopeInfo &getCurCompoundScope() const;
+
   bool hasAnyUnrecoverableErrorsInThisFunction() const;
=20
   /// \brief Retrieve the current block, if any.
   sema::BlockScopeInfo *getCurBlock();
=20
+  /// \brief Retrieve the current lambda expression, if any.
+  sema::LambdaScopeInfo *getCurLambda();
+
   /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls
   SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
=20
@@ -787,8 +882,8 @@
                               SourceLocation AttrLoc);
   QualType BuildFunctionType(QualType T,
                              QualType *ParamTypes, unsigned NumParamTypes,
-                             bool Variadic, unsigned Quals,=20
-                             RefQualifierKind RefQualifier,
+                             bool Variadic, bool HasTrailingReturn,
+                             unsigned Quals, RefQualifierKind RefQualifier,
                              SourceLocation Loc, DeclarationName Entity,
                              FunctionType::ExtInfo Info);
   QualType BuildMemberPointerType(QualType T, QualType Class,
@@ -831,11 +926,11 @@
       const FunctionProtoType *Source, SourceLocation SourceLoc);
=20
   TypeResult ActOnTypeName(Scope *S, Declarator &D);
- =20
+
   /// \brief The parser has parsed the context-sensitive type 'instancetyp=
e'
   /// in an Objective-C message declaration. Return the appropriate type.
   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
- =20
+
   bool RequireCompleteType(SourceLocation Loc, QualType T,
                            const PartialDiagnostic &PD,
                            std::pair<SourceLocation, PartialDiagnostic> No=
te);
@@ -848,8 +943,7 @@
                                          PartialDiagnostic> Note);
=20
   bool RequireLiteralType(SourceLocation Loc, QualType T,
-                          const PartialDiagnostic &PD,
-                          bool AllowIncompleteType =3D false);
+                          const PartialDiagnostic &PD);
=20
   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
                              const CXXScopeSpec &SS, QualType T);
@@ -864,6 +958,17 @@
   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
   //
=20
+  /// List of decls defined in a function prototype. This contains EnumCon=
stants
+  /// that incorrectly end up in translation unit scope because there is no
+  /// function to pin them on. ActOnFunctionDeclarator reads this list and=
 patches
+  /// them into the FunctionDecl.
+  std::vector<NamedDecl*> DeclsInPrototypeScope;
+  /// Nonzero if we are currently parsing a function declarator. This is a=
 counter
+  /// as opposed to a boolean so we can deal with nested function declarat=
ors
+  /// such as:
+  ///     void f(void (*g)(), ...)
+  unsigned InFunctionDeclarator;
+
   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType =3D 0);
=20
   void DiagnoseUseOfUnimplementedSelectors();
@@ -873,6 +978,7 @@
                          bool isClassName =3D false,
                          bool HasTrailingDot =3D false,
                          ParsedType ObjectType =3D ParsedType(),
+                         bool IsCtorOrDtorName =3D false,
                          bool WantNontrivialTypeSourceInfo =3D false,
                          IdentifierInfo **CorrectedII =3D 0);
   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
@@ -895,36 +1001,36 @@
     NC_TypeTemplate,
     NC_FunctionTemplate
   };
- =20
+
   class NameClassification {
     NameClassificationKind Kind;
     ExprResult Expr;
     TemplateName Template;
     ParsedType Type;
     const IdentifierInfo *Keyword;
-   =20
+
     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) =
{}
-   =20
+
   public:
     NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) =
{}
-   =20
+
     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
-   =20
-    NameClassification(const IdentifierInfo *Keyword)=20
+
+    NameClassification(const IdentifierInfo *Keyword)
       : Kind(NC_Keyword), Keyword(Keyword) { }
-   =20
-    static NameClassification Error() {=20
-      return NameClassification(NC_Error);=20
+
+    static NameClassification Error() {
+      return NameClassification(NC_Error);
     }
-   =20
-    static NameClassification Unknown() {=20
-      return NameClassification(NC_Unknown);=20
+
+    static NameClassification Unknown() {
+      return NameClassification(NC_Unknown);
     }
-   =20
+
     static NameClassification NestedNameSpecifier() {
       return NameClassification(NC_NestedNameSpecifier);
     }
-   =20
+
     static NameClassification TypeTemplate(TemplateName Name) {
       NameClassification Result(NC_TypeTemplate);
       Result.Template =3D Name;
@@ -936,19 +1042,19 @@
       Result.Template =3D Name;
       return Result;
     }
-   =20
+
     NameClassificationKind getKind() const { return Kind; }
-   =20
+
     ParsedType getType() const {
       assert(Kind =3D=3D NC_Type);
       return Type;
     }
-   =20
+
     ExprResult getExpression() const {
       assert(Kind =3D=3D NC_Expression);
       return Expr;
     }
-   =20
+
     TemplateName getTemplateName() const {
       assert(Kind =3D=3D NC_TypeTemplate || Kind =3D=3D NC_FunctionTemplat=
e);
       return Template;
@@ -959,7 +1065,7 @@
       return Kind =3D=3D NC_TypeTemplate? TNK_Type_template : TNK_Function=
_template;
     }
 };
- =20
+
   /// \brief Perform name lookup on the given name, classifying it based on
   /// the results of name lookup and the following token.
   ///
@@ -976,14 +1082,14 @@
   ///
   /// \param NameLoc The location of the identifier.
   ///
-  /// \param NextToken The token following the identifier. Used to help=20
+  /// \param NextToken The token following the identifier. Used to help
   /// disambiguate the name.
   NameClassification ClassifyName(Scope *S,
                                   CXXScopeSpec &SS,
                                   IdentifierInfo *&Name,
                                   SourceLocation NameLoc,
                                   const Token &NextToken);
- =20
+
   Decl *ActOnDeclarator(Scope *S, Declarator &D);
=20
   Decl *HandleDeclarator(Scope *S, Declarator &D,
@@ -992,6 +1098,9 @@
                                         const LookupResult &Previous,
                                         Scope *S);
   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
+  bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
+                                    DeclarationName Name,
+                                    SourceLocation Loc);
   void DiagnoseFunctionSpecifiers(Declarator& D);
   void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
   void CheckShadow(Scope *S, VarDecl *D);
@@ -1009,6 +1118,8 @@
   // Returns true if the variable declaration is a redeclaration
   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
   void CheckCompleteVariableDeclaration(VarDecl *var);
+  void ActOnStartFunctionDeclarator();
+  void ActOnEndFunctionDeclarator();
   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext*=
 DC,
                                      TypeSourceInfo *TInfo,
                                      LookupResult &Previous,
@@ -1016,20 +1127,7 @@
                                      bool &AddToScope);
   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
=20
-  /// \brief The kind of constexpr declaration checking we are performing.
-  ///
-  /// The kind affects which diagnostics (if any) are emitted if the funct=
ion
-  /// does not satisfy the requirements of a constexpr function declaratio=
n.
-  enum CheckConstexprKind {
-    /// \brief Check a constexpr function declaration, and produce errors =
if it
-    /// does not satisfy the requirements.
-    CCK_Declaration,
-    /// \brief Check a constexpr function template instantiation.
-    CCK_Instantiation,
-    /// \brief Produce notes explaining why an instantiation was not const=
expr.
-    CCK_NoteNonConstexprInstantiation
-  };
-  bool CheckConstexprFunctionDecl(const FunctionDecl *FD, CheckConstexprKi=
nd CCK);
+  bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
   bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
=20
   void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
@@ -1105,23 +1203,22 @@
=20
   /// \brief The parser has processed a module import declaration.
   ///
-  /// \param ImportLoc The location of the '__import_module__' keyword.
-  ///
-  /// \param ModuleName The name of the module.
-  ///
-  /// \param ModuleNameLoc The location of the module name.
-  DeclResult ActOnModuleImport(SourceLocation ImportLoc,
-                               IdentifierInfo &ModuleName,
-                               SourceLocation ModuleNameLoc);
- =20
-  /// \brief Diagnose that \p New is a module-private redeclaration of
-  /// \p Old.
-  void diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old,
-                                          SourceLocation ModulePrivateKeyw=
ord
-                                            =3D SourceLocation());
- =20
+  /// \param AtLoc The location of the '@' symbol, if any.
+  ///
+  /// \param ImportLoc The location of the 'import' keyword.
+  ///
+  /// \param Path The module access path.
+  DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation Import=
Loc,=20
+                               ModuleIdPath Path);
+
   /// \brief Retrieve a suitable printing policy.
-  PrintingPolicy getPrintingPolicy() const;
+  PrintingPolicy getPrintingPolicy() const {
+    return getPrintingPolicy(Context, PP);
+  }
+
+  /// \brief Retrieve a suitable printing policy.
+  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
+                                          const Preprocessor &PP);
=20
   /// Scope actions.
   void ActOnPopScope(SourceLocation Loc, Scope *S);
@@ -1132,14 +1229,12 @@
   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
                                    DeclSpec &DS,
                                    MultiTemplateParamsArg TemplateParams);
- =20
-  StmtResult ActOnVlaStmt(const DeclSpec &DS);
=20
   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
                                     AccessSpecifier AS,
                                     RecordDecl *Record);
=20
-  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,=20
+  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
                                        RecordDecl *Record);
=20
   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
@@ -1160,7 +1255,8 @@
                  AttributeList *Attr, AccessSpecifier AS,
                  SourceLocation ModulePrivateLoc,
                  MultiTemplateParamsArg TemplateParameterLists,
-                 bool &OwnedDecl, bool &IsDependent, bool ScopedEnum,
+                 bool &OwnedDecl, bool &IsDependent,
+                 SourceLocation ScopedEnumKWLoc,
                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType);
=20
   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
@@ -1208,7 +1304,7 @@
   bool CheckNontrivialField(FieldDecl *FD);
   void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem);
   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
-  void ActOnLastBitfield(SourceLocation DeclStart,=20
+  void ActOnLastBitfield(SourceLocation DeclStart,
                          SmallVectorImpl<Decl *> &AllIvarDecls);
   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
                   Declarator &D, Expr *BitfieldWidth,
@@ -1245,8 +1341,8 @@
   /// scope for parsing/looking-up C constructs.
   ///
   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
-  void ActOnObjCTemporaryExitContainerContext();
-  void ActOnObjCReenterContainerContext();
+  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
+  void ActOnObjCReenterContainerContext(DeclContext *DC);
=20
   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
   /// error parsing the definition of a tag.
@@ -1257,6 +1353,9 @@
                                       SourceLocation IdLoc,
                                       IdentifierInfo *Id,
                                       Expr *val);
+  bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
+  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
+                              QualType EnumUnderlyingTy, const EnumDecl *P=
rev);
=20
   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
                           SourceLocation IdLoc, IdentifierInfo *Id,
@@ -1280,7 +1379,7 @@
=20
   /// Push the parameters of D, which must be a function, into scope.
   void ActOnReenterFunctionContext(Scope* S, Decl* D);
-  void ActOnExitFunctionContext() { PopDeclContext(); }
+  void ActOnExitFunctionContext();
=20
   DeclContext *getFunctionLevelDeclContext();
=20
@@ -1302,6 +1401,14 @@
   /// Add this decl to the scope shadowed decl chains.
   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext =3D tru=
e);
=20
+  /// \brief Make the given externally-produced declaration visible at the
+  /// top level scope.
+  ///
+  /// \param D The externally-produced declaration to push.
+  ///
+  /// \param Name The name of the externally-produced declaration.
+  void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
+
   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns=
 true
   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope r=
eturns
   /// true if 'D' belongs to the given declaration context.
@@ -1319,14 +1426,17 @@
   /// Subroutines of ActOnDeclarator().
   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
                                 TypeSourceInfo *TInfo);
+  bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
+  void mergeDeclAttributes(Decl *New, Decl *Old, bool MergeDeprecation =3D=
 true);
   void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
-  bool MergeFunctionDecl(FunctionDecl *New, Decl *Old);
-  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old);
-  void mergeObjCMethodDecls(ObjCMethodDecl *New, const ObjCMethodDecl *Old=
);
+  bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S);
+  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
+                                    Scope *S);
+  void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
   void MergeVarDecl(VarDecl *New, LookupResult &OldDecls);
   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old);
   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
-  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old);
+  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S=
);
=20
   // AssignmentAction - This is used by all the assignment diagnostic func=
tions
   // to represent what is actually causing the operation
@@ -1355,7 +1465,7 @@
     Ovl_NonFunction
   };
   OverloadKind CheckOverload(Scope *S,
-                             FunctionDecl *New,=20
+                             FunctionDecl *New,
                              const LookupResult &OldDecls,
                              NamedDecl *&OldDecl,
                              bool IsForUsingDecl);
@@ -1388,9 +1498,12 @@
                                  QualType &ConvertedType);
   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
                                 QualType& ConvertedType);
-  bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,=20
-                                const FunctionProtoType *NewType);
- =20
+  bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
+                                const FunctionProtoType *NewType,
+                                unsigned *ArgPos =3D 0);
+  void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
+                                  QualType FromType, QualType ToType);
+
   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
   bool CheckPointerConversion(Expr *From, QualType ToType,
                               CastKind &Kind,
@@ -1421,7 +1534,8 @@
   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
                                        SourceLocation EqualLoc,
                                        ExprResult Init,
-                                       bool TopLevelOfInitList =3D false);
+                                       bool TopLevelOfInitList =3D false,
+                                       bool AllowExplicit =3D false);
   ExprResult PerformObjectArgumentInitialization(Expr *From,
                                                  NestedNameSpecifier *Qual=
ifier,
                                                  NamedDecl *FoundDecl,
@@ -1430,7 +1544,16 @@
   ExprResult PerformContextuallyConvertToBool(Expr *From);
   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
=20
-  ExprResult=20
+  /// Contexts in which a converted constant expression is required.
+  enum CCEKind {
+    CCEK_CaseValue,  ///< Expression in a case label.
+    CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
+    CCEK_TemplateArg ///< Value of a non-type template parameter.
+  };
+  ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
+                                              llvm::APSInt &Value, CCEKind=
 CCE);
+
+  ExprResult
   ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE,
                                      const PartialDiagnostic &NotIntDiag,
                                      const PartialDiagnostic &IncompleteDi=
ag,
@@ -1438,8 +1561,15 @@
                                      const PartialDiagnostic &ExplicitConv=
Note,
                                      const PartialDiagnostic &AmbigDiag,
                                      const PartialDiagnostic &AmbigNote,
-                                     const PartialDiagnostic &ConvDiag);
- =20
+                                     const PartialDiagnostic &ConvDiag,
+                                     bool AllowScopedEnumerations);
+  enum ObjCSubscriptKind {
+    OS_Array,
+    OS_Dictionary,
+    OS_Error
+  };
+  ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
+
   ExprResult PerformObjectMemberConversion(Expr *From,
                                            NestedNameSpecifier *Qualifier,
                                            NamedDecl *FoundDecl,
@@ -1450,21 +1580,18 @@
   typedef llvm::SmallPtrSet<DeclContext   *, 16> AssociatedNamespaceSet;
   typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
=20
-  void AddOverloadCandidate(NamedDecl *Function,
-                            DeclAccessPair FoundDecl,
-                            Expr **Args, unsigned NumArgs,
-                            OverloadCandidateSet &CandidateSet);
-
   void AddOverloadCandidate(FunctionDecl *Function,
                             DeclAccessPair FoundDecl,
-                            Expr **Args, unsigned NumArgs,
+                            llvm::ArrayRef<Expr *> Args,
                             OverloadCandidateSet& CandidateSet,
                             bool SuppressUserConversions =3D false,
-                            bool PartialOverloading =3D false);
+                            bool PartialOverloading =3D false,
+                            bool AllowExplicit =3D false);
   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
-                             Expr **Args, unsigned NumArgs,
+                             llvm::ArrayRef<Expr *> Args,
                              OverloadCandidateSet& CandidateSet,
-                             bool SuppressUserConversions =3D false);
+                             bool SuppressUserConversions =3D false,
+                            TemplateArgumentListInfo *ExplicitTemplateArgs=
 =3D 0);
   void AddMethodCandidate(DeclAccessPair FoundDecl,
                           QualType ObjectType,
                           Expr::Classification ObjectClassification,
@@ -1475,7 +1602,7 @@
                           DeclAccessPair FoundDecl,
                           CXXRecordDecl *ActingContext, QualType ObjectTyp=
e,
                           Expr::Classification ObjectClassification,
-                          Expr **Args, unsigned NumArgs,
+                          llvm::ArrayRef<Expr *> Args,
                           OverloadCandidateSet& CandidateSet,
                           bool SuppressUserConversions =3D false);
   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
@@ -1484,13 +1611,13 @@
                                  TemplateArgumentListInfo *ExplicitTemplat=
eArgs,
                                   QualType ObjectType,
                                   Expr::Classification ObjectClassificatio=
n,
-                                  Expr **Args, unsigned NumArgs,
+                                  llvm::ArrayRef<Expr *> Args,
                                   OverloadCandidateSet& CandidateSet,
                                   bool SuppressUserConversions =3D false);
   void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
                                     DeclAccessPair FoundDecl,
                                  TemplateArgumentListInfo *ExplicitTemplat=
eArgs,
-                                    Expr **Args, unsigned NumArgs,
+                                    llvm::ArrayRef<Expr *> Args,
                                     OverloadCandidateSet& CandidateSet,
                                     bool SuppressUserConversions =3D false=
);
   void AddConversionCandidate(CXXConversionDecl *Conversion,
@@ -1507,7 +1634,7 @@
                              DeclAccessPair FoundDecl,
                              CXXRecordDecl *ActingContext,
                              const FunctionProtoType *Proto,
-                             Expr *Object, Expr **Args, unsigned NumArgs,
+                             Expr *Object, llvm::ArrayRef<Expr*> Args,
                              OverloadCandidateSet& CandidateSet);
   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
                                    SourceLocation OpLoc,
@@ -1524,20 +1651,20 @@
                                     Expr **Args, unsigned NumArgs,
                                     OverloadCandidateSet& CandidateSet);
   void AddArgumentDependentLookupCandidates(DeclarationName Name,
-                                            bool Operator,
-                                            Expr **Args, unsigned NumArgs,
+                                            bool Operator, SourceLocation =
Loc,
+                                            llvm::ArrayRef<Expr *> Args,
                                 TemplateArgumentListInfo *ExplicitTemplate=
Args,
                                             OverloadCandidateSet& Candidat=
eSet,
                                             bool PartialOverloading =3D fa=
lse,
                                         bool StdNamespaceIsAssociated =3D =
false);
=20
   // Emit as a 'note' the specific overload candidate
-  void NoteOverloadCandidate(FunctionDecl *Fn);
-  =20
+  void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType =3D QualT=
ype());
+
   // Emit as a series of 'note's all template and non-templates
   // identified by the expression Expr
-  void NoteAllOverloadCandidates(Expr* E);
- =20
+  void NoteAllOverloadCandidates(Expr* E, QualType DestType =3D QualType()=
);
+
   // [PossiblyAFunctionType]  -->   [Return]
   // NonFunctionType --> NonFunctionType
   // R (A) --> R(A)
@@ -1546,9 +1673,12 @@
   // R (S::*)(A) --> R (A)
   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
=20
-  FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, Qu=
alType TargetType,
-                                                   bool Complain,
-                                                   DeclAccessPair &Found);
+  FunctionDecl *
+  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
+                                     QualType TargetType,
+                                     bool Complain,
+                                     DeclAccessPair &Found,
+                                     bool *pHadMultipleCandidates =3D 0);
=20
   FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *=
ovl,
                                                    bool Complain =3D false,
@@ -1557,9 +1687,9 @@
   bool ResolveAndFixSingleFunctionTemplateSpecialization(
                       ExprResult &SrcExpr,
                       bool DoFunctionPointerConverion =3D false,
-                      bool Complain =3D false,=20
-                      const SourceRange& OpRangeForComplaining =3D SourceR=
ange(),=20
-                      QualType DestTypeForComplaining =3D QualType(),=20
+                      bool Complain =3D false,
+                      const SourceRange& OpRangeForComplaining =3D SourceR=
ange(),
+                      QualType DestTypeForComplaining =3D QualType(),
                       unsigned DiagIDForComplaining =3D 0);
=20
=20
@@ -1571,7 +1701,7 @@
                                             FunctionDecl *Fn);
=20
   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
-                                   Expr **Args, unsigned NumArgs,
+                                   llvm::ArrayRef<Expr *> Args,
                                    OverloadCandidateSet &CandidateSet,
                                    bool PartialOverloading =3D false);
=20
@@ -1580,7 +1710,8 @@
                                      SourceLocation LParenLoc,
                                      Expr **Args, unsigned NumArgs,
                                      SourceLocation RParenLoc,
-                                     Expr *ExecConfig);
+                                     Expr *ExecConfig,
+                                     bool AllowTypoCorrection=3Dtrue);
=20
   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
                                      unsigned Opc,
@@ -1702,8 +1833,21 @@
     ForRedeclaration
   };
=20
-private:
-  bool CppLookupName(LookupResult &R, Scope *S);
+  /// \brief The possible outcomes of name lookup for a literal operator.
+  enum LiteralOperatorLookupResult {
+    /// \brief The lookup resulted in an error.
+    LOLR_Error,
+    /// \brief The lookup found a single 'cooked' literal operator, which
+    /// expects a normal literal to be built and passed to it.
+    LOLR_Cooked,
+    /// \brief The lookup found a single 'raw' literal operator, which exp=
ects
+    /// a string literal containing the spelling of the literal token.
+    LOLR_Raw,
+    /// \brief The lookup found an overload set of literal operator templa=
tes,
+    /// which expect the characters of the spelling of the literal token t=
o be
+    /// passed as a non-type template argument pack.
+    LOLR_Template
+  };
=20
   SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
                                                    CXXSpecialMember SM,
@@ -1713,6 +1857,9 @@
                                                    bool ConstThis,
                                                    bool VolatileThis);
=20
+private:
+  bool CppLookupName(LookupResult &R, Scope *S);
+
   // \brief The set of known/encountered (unique, canonicalized) Namespace=
Decls.
   //
   // The boolean value will be true to indicate that the namespace was loa=
ded
@@ -1722,7 +1869,7 @@
   /// \brief Whether we have already loaded known namespaces from an exten=
al
   /// source.
   bool LoadedExternalKnownNamespaces;
- =20
+
 public:
   /// \brief Look up a name, looking for a single declaration.  Return
   /// null if the results were absent, ambiguous, or overloaded.
@@ -1741,7 +1888,9 @@
   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
                         bool AllowBuiltinCreation =3D false,
                         bool EnteringContext =3D false);
-  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLo=
c);
+  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLo=
c,
+                                   RedeclarationKind Redecl
+                                     =3D NotForRedeclaration);
=20
   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
                                     QualType T1, QualType T2,
@@ -1763,8 +1912,13 @@
                                         unsigned ThisQuals);
   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
=20
+  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult=
 &R,
+                                                    ArrayRef<QualType> Arg=
Tys,
+                                                    bool AllowRawAndTempla=
te);
+
   void ArgumentDependentLookup(DeclarationName Name, bool Operator,
-                               Expr **Args, unsigned NumArgs,
+                               SourceLocation Loc,
+                               llvm::ArrayRef<Expr *> Args,
                                ADLResult &Functions,
                                bool StdNamespaceIsAssociated =3D false);
=20
@@ -1774,43 +1928,16 @@
   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
                           VisibleDeclConsumer &Consumer,
                           bool IncludeGlobalScope =3D true);
- =20
-  /// \brief The context in which typo-correction occurs.
-  ///
-  /// The typo-correction context affects which keywords (if any) are
-  /// considered when trying to correct for typos.
-  enum CorrectTypoContext {
-    /// \brief An unknown context, where any keyword might be valid.
-    CTC_Unknown,
-    /// \brief A context where no keywords are used (e.g. we expect an act=
ual
-    /// name).
-    CTC_NoKeywords,
-    /// \brief A context where we're correcting a type name.
-    CTC_Type,
-    /// \brief An expression context.
-    CTC_Expression,
-    /// \brief A type cast, or anything else that can be followed by a '<'.
-    CTC_CXXCasts,
-    /// \brief A member lookup context.
-    CTC_MemberLookup,
-    /// \brief An Objective-C ivar lookup context (e.g., self->ivar).
-    CTC_ObjCIvarLookup,
-    /// \brief An Objective-C property lookup context (e.g., self.prop).
-    CTC_ObjCPropertyLookup,
-    /// \brief The receiver of an Objective-C message send within an
-    /// Objective-C method where 'super' is a valid keyword.
-    CTC_ObjCMessageReceiver
-  };
=20
   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
                              Sema::LookupNameKind LookupKind,
                              Scope *S, CXXScopeSpec *SS,
-                             DeclContext *MemberContext =3D NULL,
+                             CorrectionCandidateCallback &CCC,
+                             DeclContext *MemberContext =3D 0,
                              bool EnteringContext =3D false,
-                             CorrectTypoContext CTC =3D CTC_Unknown,
-                             const ObjCObjectPointerType *OPT =3D NULL);
-
-  void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
+                             const ObjCObjectPointerType *OPT =3D 0);
+
+  void FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
                                    AssociatedNamespaceSet &AssociatedNames=
paces,
                                    AssociatedClassSet &AssociatedClasses);
=20
@@ -1852,7 +1979,7 @@
   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
                                    ObjCMethodDecl *MethodDecl,
                                    bool IsProtocolMethodDecl);
- =20
+
   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
                                    ObjCMethodDecl *Overridden,
                                    bool IsProtocolMethodDecl);
@@ -1868,7 +1995,7 @@
=20
   typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > Selector=
Set;
   typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
-                        =20
+
   /// CheckProtocolMethodDefs - This routine checks unimplemented
   /// methods declared in protocol, and those referenced by it.
   /// \param IDecl - Used for checking for methods which may have been
@@ -1898,18 +2025,18 @@
                                        ObjCContainerDecl *CDecl,
                                        const SelectorSet &InsMap);
=20
-  /// DefaultSynthesizeProperties - This routine default synthesizes all=20
+  /// DefaultSynthesizeProperties - This routine default synthesizes all
   /// properties which must be synthesized in class's @implementation.
   void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
                                     ObjCInterfaceDecl *IDecl);
   void DefaultSynthesizeProperties(Scope *S, Decl *D);
- =20
+
   /// CollectImmediateProperties - This routine collects all properties in
   /// the class and its conforming protocols; but not those it its super c=
lass.
   void CollectImmediateProperties(ObjCContainerDecl *CDecl,
             llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
             llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperProp=
Map);
- =20
+
=20
   /// LookupPropertyDecl - Looks up a property in the current class and all
   /// its protocols.
@@ -1920,12 +2047,14 @@
   ////  class extensions.
   Decl *HandlePropertyInClassExtension(Scope *S,
                                        SourceLocation AtLoc,
+                                       SourceLocation LParenLoc,
                                        FieldDeclarator &FD,
                                        Selector GetterSel,
                                        Selector SetterSel,
                                        const bool isAssign,
                                        const bool isReadWrite,
                                        const unsigned Attributes,
+                                       const unsigned AttributesAsWritten,
                                        bool *isOverridingProperty,
                                        TypeSourceInfo *T,
                                        tok::ObjCKeywordKind MethodImplKind=
);
@@ -1935,12 +2064,14 @@
   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
                                        ObjCContainerDecl *CDecl,
                                        SourceLocation AtLoc,
+                                       SourceLocation LParenLoc,
                                        FieldDeclarator &FD,
                                        Selector GetterSel,
                                        Selector SetterSel,
                                        const bool isAssign,
                                        const bool isReadWrite,
                                        const unsigned Attributes,
+                                       const unsigned AttributesAsWritten,
                                        TypeSourceInfo *T,
                                        tok::ObjCKeywordKind MethodImplKind,
                                        DeclContext *lexicalDC =3D 0);
@@ -1976,13 +2107,16 @@
                                   ObjCContainerDecl* IDecl,
                                   bool &IncompleteImpl,
                                   bool ImmediateClass,
-                                  bool WarnExactMatch=3Dfalse);
+                                  bool WarnCategoryMethodImpl=3Dfalse);
=20
   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented =
in
   /// category matches with those implemented in its primary class and
-  /// warns each time an exact match is found.=20
+  /// warns each time an exact match is found.
   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
=20
+  /// \brief Add the given method to the list of globally-known methods.
+  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
+ =20
 private:
   /// AddMethodToGlobalPool - Add an instance or factory method to the glo=
bal
   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
@@ -2017,7 +2151,7 @@
   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRan=
ge R,
                                                    bool receiverIdOrClass=
=3Dfalse,
                                                    bool warn=3Dtrue) {
-    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,=20
+    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
                                     warn, /*instance*/true);
   }
=20
@@ -2045,7 +2179,7 @@
   class FullExprArg {
   public:
     FullExprArg(Sema &actions) : E(0) { }
-               =20
+
     // FIXME: The const_cast here is ugly. RValue references would make th=
is
     // much nicer (or we could duplicate a bunch of the move semantics
     // emulation code from Ownership.h).
@@ -2079,9 +2213,28 @@
=20
   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
                            bool HasLeadingEmptyMacro =3D false);
+
+  void ActOnStartOfCompoundStmt();
+  void ActOnFinishOfCompoundStmt();
   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
                                        MultiStmtArg Elts,
                                        bool isStmtExpr);
+
+  /// \brief A RAII object to enter scope of a compound statement.
+  class CompoundScopeRAII {
+  public:
+    CompoundScopeRAII(Sema &S): S(S) {
+      S.ActOnStartOfCompoundStmt();
+    }
+
+    ~CompoundScopeRAII() {
+      S.ActOnFinishOfCompoundStmt();
+    }
+
+  private:
+    Sema &S;
+  };
+
   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
                                    SourceLocation StartLoc,
                                    SourceLocation EndLoc);
@@ -2097,7 +2250,7 @@
                                       Stmt *SubStmt, Scope *CurScope);
   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
                             SourceLocation ColonLoc, Stmt *SubStmt);
-   =20
+
   StmtResult ActOnIfStmt(SourceLocation IfLoc,
                          FullExprArg CondVal, Decl *CondVar,
                          Stmt *ThenVal,
@@ -2151,9 +2304,9 @@
=20
   const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
                                          bool AllowFunctionParameters);
- =20
+
   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
-  StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValEx=
p);
+  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetVa=
lExp);
=20
   StmtResult ActOnAsmStmt(SourceLocation AsmLoc,
                           bool IsSimple, bool IsVolatile,
@@ -2220,7 +2373,7 @@
   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
=20
   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
- =20
+
   /// \brief If it's a file scoped decl that must warn if not used, keep t=
rack
   /// of it.
   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
@@ -2229,7 +2382,22 @@
   /// whose result is unused, warn.
   void DiagnoseUnusedExprResult(const Stmt *S);
   void DiagnoseUnusedDecl(const NamedDecl *ND);
- =20
+
+  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious n=
ull
+  /// statement as a \p Body, and it is located on the same line.
+  ///
+  /// This helps prevent bugs due to typos, such as:
+  ///     if (condition);
+  ///       do_stuff();
+  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
+                             const Stmt *Body,
+                             unsigned DiagID);
+
+  /// Warn if a for/while loop statement \p S, which is followed by
+  /// \p PossibleBody, has a suspicious null statement as a body.
+  void DiagnoseEmptyLoopBody(const Stmt *S,
+                             const Stmt *PossibleBody);
+
   ParsingDeclState PushParsingDeclaration() {
     return DelayedDiagnostics.pushParsingDecl();
   }
@@ -2246,7 +2414,7 @@
   }
=20
   void EmitDeprecationWarning(NamedDecl *D, StringRef Message,
-                              SourceLocation Loc,=20
+                              SourceLocation Loc,
                               const ObjCInterfaceDecl *UnknownObjCClass=3D=
0);
=20
   void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ct=
x);
@@ -2260,6 +2428,7 @@
   bool CanUseDecl(NamedDecl *D);
   bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
                          const ObjCInterfaceDecl *UnknownObjCClass=3D0);
+  void NoteDeletedFunction(FunctionDecl *FD);
   std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
                                         ObjCMethodDecl *Getter,
@@ -2267,15 +2436,82 @@
   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
                              Expr **Args, unsigned NumArgs);
=20
-  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewCont=
ext);
+  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewCont=
ext,
+                                       Decl *LambdaContextDecl =3D 0,
+                                       bool IsDecltype =3D false);
=20
   void PopExpressionEvaluationContext();
=20
   void DiscardCleanupsInEvaluationContext();
=20
-  void MarkDeclarationReferenced(SourceLocation Loc, Decl *D);
+  ExprResult TranformToPotentiallyEvaluated(Expr *E);
+  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
+
+  ExprResult ActOnConstantExpression(ExprResult Res);
+
+  // Functions for marking a declaration referenced.  These functions also
+  // contain the relevant logic for marking if a reference to a function or
+  // variable is an odr-use (in the C++11 sense).  There are separate vari=
ants
+  // for expressions referring to a decl; these exist because odr-use mark=
ing
+  // needs to be delayed for some constant variables when we build one of =
the
+  // named expressions.
+  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D);
+  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func);
+  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
+  void MarkDeclRefReferenced(DeclRefExpr *E);
+  void MarkMemberReferenced(MemberExpr *E);
+
+  void UpdateMarkingForLValueToRValue(Expr *E);
+  void CleanupVarDeclMarking();
+
+  enum TryCaptureKind {
+    TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
+  };
+
+  /// \brief Try to capture the given variable.
+  ///
+  /// \param Var The variable to capture.
+  ///
+  /// \param Loc The location at which the capture occurs.
+  ///
+  /// \param Kind The kind of capture, which may be implicit (for either a=20
+  /// block or a lambda), or explicit by-value or by-reference (for a lamb=
da).
+  ///
+  /// \param EllipsisLoc The location of the ellipsis, if one is provided =
in
+  /// an explicit lambda capture.
+  ///
+  /// \param BuildAndDiagnose Whether we are actually supposed to add the=20
+  /// captures or diagnose errors. If false, this routine merely check whe=
ther
+  /// the capture can occur without performing the capture itself or compl=
aining
+  /// if the variable cannot be captured.
+  ///
+  /// \param CaptureType Will be set to the type of the field used to capt=
ure
+  /// this variable in the innermost block or lambda. Only valid when the
+  /// variable can be captured.
+  ///
+  /// \param DeclRefType Will be set to the type of a refernce to the capt=
ure
+  /// from within the current scope. Only valid when the variable can be=20
+  /// captured.
+  ///
+  /// \returns true if an error occurred (i.e., the variable cannot be
+  /// captured) and false if the capture succeeded.
+  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind=
 Kind,
+                          SourceLocation EllipsisLoc, bool BuildAndDiagnos=
e,=20
+                          QualType &CaptureType,
+                          QualType &DeclRefType);
+
+  /// \brief Try to capture the given variable.
+  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
+                          TryCaptureKind Kind =3D TryCapture_Implicit,
+                          SourceLocation EllipsisLoc =3D SourceLocation());
+ =20
+  /// \brief Given a variable, determine the type that a reference to that
+  /// variable will have in the given scope.
+  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
+ =20
   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
-  void MarkDeclarationsReferencedInExpr(Expr *E);
+  void MarkDeclarationsReferencedInExpr(Expr *E,=20
+                                        bool SkipLocalVariables =3D false);
=20
   /// \brief Try to recover by turning the given expression into a
   /// call.  Returns true if recovery was attempted or an error was
@@ -2300,9 +2536,12 @@
=20
   // Primary Expressions.
   SourceRange getExprRange(Expr *E) const;
- =20
-  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &=
Id,
-                               bool HasTrailingLParen, bool IsAddressOfOpe=
rand);
+
+  ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
+                               SourceLocation TemplateKWLoc,
+                               UnqualifiedId &Id,
+                               bool HasTrailingLParen, bool IsAddressOfOpe=
rand,
+                               CorrectionCandidateCallback *CCC =3D 0);
=20
   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
                               TemplateArgumentListInfo &Buffer,
@@ -2310,15 +2549,16 @@
                               const TemplateArgumentListInfo *&TemplateArg=
s);
=20
   bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
-                           CorrectTypoContext CTC =3D CTC_Unknown,
+                           CorrectionCandidateCallback &CCC,
                            TemplateArgumentListInfo *ExplicitTemplateArgs =
=3D 0,
-                           Expr **Args =3D 0, unsigned NumArgs =3D 0);
+                       llvm::ArrayRef<Expr *> Args =3D llvm::ArrayRef<Expr=
 *>());
=20
   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
                                 IdentifierInfo *II,
                                 bool AllowBuiltinCreation=3Dfalse);
=20
   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
+                                        SourceLocation TemplateKWLoc,
                                         const DeclarationNameInfo &NameInf=
o,
                                         bool isAddressOfOperand,
                                 const TemplateArgumentListInfo *TemplateAr=
gs);
@@ -2338,9 +2578,11 @@
                                            Expr *baseObjectExpr =3D 0,
                                       SourceLocation opLoc =3D SourceLocat=
ion());
   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
+                                             SourceLocation TemplateKWLoc,
                                              LookupResult &R,
                                 const TemplateArgumentListInfo *TemplateAr=
gs);
   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
+                                     SourceLocation TemplateKWLoc,
                                      LookupResult &R,
                                 const TemplateArgumentListInfo *TemplateAr=
gs,
                                      bool IsDefiniteInstance);
@@ -2351,6 +2593,7 @@
   ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
                                          const DeclarationNameInfo &NameIn=
fo);
   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
+                                       SourceLocation TemplateKWLoc,
                                 const DeclarationNameInfo &NameInfo,
                                 const TemplateArgumentListInfo *TemplateAr=
gs);
=20
@@ -2361,18 +2604,25 @@
                                       const DeclarationNameInfo &NameInfo,
                                       NamedDecl *D);
=20
+  ExprResult BuildLiteralOperatorCall(LookupResult &R,
+                                      DeclarationNameInfo &SuffixInfo,
+                                      ArrayRef<Expr*> Args,
+                                      SourceLocation LitEndLoc,
+                            TemplateArgumentListInfo *ExplicitTemplateArgs=
 =3D 0);
+
   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
-  ExprResult ActOnNumericConstant(const Token &Tok);
-  ExprResult ActOnCharacterConstant(const Token &Tok);
+  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
+  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope =3D 0);
+  ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope =3D =
0);
   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
-  ExprResult ActOnParenOrParenListExpr(SourceLocation L,
-                                       SourceLocation R,
-                                       MultiExprArg Val);
+  ExprResult ActOnParenListExpr(SourceLocation L,
+                                SourceLocation R,
+                                MultiExprArg Val);
=20
   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
   /// fragments (e.g. "foo" "bar" L"baz").
-  ExprResult ActOnStringLiteral(const Token *StringToks,
-                                unsigned NumStringToks);
+  ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStrin=
gToks,
+                                Scope *UDLScope =3D 0);
=20
   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
                                        SourceLocation DefaultLoc,
@@ -2431,6 +2681,7 @@
   ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
                                       SourceLocation OpLoc, bool IsArrow,
                                       CXXScopeSpec &SS,
+                                      SourceLocation TemplateKWLoc,
                                       NamedDecl *FirstQualifierInScope,
                                 const DeclarationNameInfo &NameInfo,
                                 const TemplateArgumentListInfo *TemplateAr=
gs);
@@ -2438,11 +2689,13 @@
   ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
                                       SourceLocation OpLoc, bool IsArrow,
                                       const CXXScopeSpec &SS,
+                                      SourceLocation TemplateKWLoc,
                                       NamedDecl *FirstQualifierInScope,
                                       LookupResult &R,
                                  const TemplateArgumentListInfo *TemplateA=
rgs,
                                       bool SuppressQualifierCheck =3D fals=
e);
=20
+  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
   ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base,
                               bool &IsArrow, SourceLocation OpLoc,
                               CXXScopeSpec &SS,
@@ -2456,6 +2709,7 @@
   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
                                       bool IsArrow, SourceLocation OpLoc,
                                       const CXXScopeSpec &SS,
+                                      SourceLocation TemplateKWLoc,
                                       NamedDecl *FirstQualifierInScope,
                                const DeclarationNameInfo &NameInfo,
                                const TemplateArgumentListInfo *TemplateArg=
s);
@@ -2464,6 +2718,7 @@
                                    SourceLocation OpLoc,
                                    tok::TokenKind OpKind,
                                    CXXScopeSpec &SS,
+                                   SourceLocation TemplateKWLoc,
                                    UnqualifiedId &Member,
                                    Decl *ObjCImpDecl,
                                    bool HasTrailingLParen);
@@ -2475,6 +2730,9 @@
                                Expr **Args, unsigned NumArgs,
                                SourceLocation RParenLoc,
                                bool ExecConfig =3D false);
+  void CheckStaticArrayArgument(SourceLocation CallLoc,
+                                ParmVarDecl *Param,
+                                const Expr *ArgExpr);
=20
   /// ActOnCallExpr - Handle a call to Fn with the specified array of argu=
ments.
   /// This provides the location of the left/right parens and a list of co=
mma
@@ -2544,9 +2802,11 @@
   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
                             LabelDecl *TheDecl);
- =20
+
+  void ActOnStartStmtExpr();
   ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
                            SourceLocation RPLoc); // "({..})"
+  void ActOnStmtExprError();
=20
   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
   struct OffsetOfComponent {
@@ -2588,7 +2848,40 @@
=20
   bool CheckCaseExpression(Expr *E);
=20
-  bool CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS, UnqualifiedId &Name);
+  /// \brief Describes the result of an "if-exists" condition check.
+  enum IfExistsResult {
+    /// \brief The symbol exists.
+    IER_Exists,
+
+    /// \brief The symbol does not exist.
+    IER_DoesNotExist,
+
+    /// \brief The name is a dependent name, so the results will differ
+    /// from one instantiation to the next.
+    IER_Dependent,
+
+    /// \brief An error occurred.
+    IER_Error
+  };
+
+  IfExistsResult
+  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
+                               const DeclarationNameInfo &TargetNameInfo);
+
+  IfExistsResult
+  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
+                               bool IsIfExists, CXXScopeSpec &SS,
+                               UnqualifiedId &Name);
+
+  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
+                                        bool IsIfExists,
+                                        NestedNameSpecifierLoc QualifierLo=
c,
+                                        DeclarationNameInfo NameInfo,
+                                        Stmt *Nested);
+  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
+                                        bool IsIfExists,
+                                        CXXScopeSpec &SS, UnqualifiedId &N=
ame,
+                                        Stmt *Nested);
=20
   //=3D=3D=3D------------------------- "Block" Extension -----------------=
-------=3D=3D=3D//
=20
@@ -2610,12 +2903,12 @@
                                 Scope *CurScope);
=20
   //=3D=3D=3D---------------------------- OpenCL Features ----------------=
-------=3D=3D=3D//
-   =20
+
   /// __builtin_astype(...)
   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
-                             SourceLocation BuiltinLoc,=20
+                             SourceLocation BuiltinLoc,
                              SourceLocation RParenLoc);
- =20
+
   //=3D=3D=3D---------------------------- C++ Features -------------------=
-------=3D=3D=3D//
=20
   // Act on C++ namespaces
@@ -2632,6 +2925,20 @@
=20
   CXXRecordDecl *getStdBadAlloc() const;
=20
+  /// \brief Tests whether Ty is an instance of std::initializer_list and,=
 if
+  /// it is and Element is not NULL, assigns the element type to Element.
+  bool isStdInitializerList(QualType Ty, QualType *Element);
+
+  /// \brief Looks for the std::initializer_list template and instantiates=
 it
+  /// with Element, or emits an error if it's not found.
+  ///
+  /// \returns The instantiated template, or null on error.
+  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
+
+  /// \brief Determine whether Ctor is an initializer-list constructor, as
+  /// defined in [dcl.init.list]p2.
+  bool isInitListConstructor(const CXXConstructorDecl *Ctor);
+
   Decl *ActOnUsingDirective(Scope *CurScope,
                             SourceLocation UsingLoc,
                             SourceLocation NamespcLoc,
@@ -2674,7 +2981,7 @@
                                    bool IsTypeName,
                                    SourceLocation TypenameLoc);
=20
-  bool CheckInheritedConstructorUsingDecl(UsingDecl *UD);
+  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
=20
   Decl *ActOnUsingDeclaration(Scope *CurScope,
                               AccessSpecifier AS,
@@ -2692,15 +2999,6 @@
                               UnqualifiedId &Name,
                               TypeResult Type);
=20
-  /// AddCXXDirectInitializerToDecl - This action is called immediately af=
ter
-  /// ActOnDeclarator, when a C++ direct initializer is present.
-  /// e.g: "int x(1);"
-  void AddCXXDirectInitializerToDecl(Decl *Dcl,
-                                     SourceLocation LParenLoc,
-                                     MultiExprArg Exprs,
-                                     SourceLocation RParenLoc,
-                                     bool TypeMayContainAuto);
-
   /// InitializeVarWithConstructor - Creates an CXXConstructExpr
   /// and sets it as the initializer for the the passed in VarDecl.
   bool InitializeVarWithConstructor(VarDecl *VD,
@@ -2737,7 +3035,7 @@
   /// constructed variable.
   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitTy=
pe);
=20
-  /// \brief Helper class that collects exception specifications for=20
+  /// \brief Helper class that collects exception specifications for
   /// implicitly-declared special member functions.
   class ImplicitExceptionSpecification {
     // Pointer to allow copying
@@ -2765,9 +3063,9 @@
     }
=20
   public:
-    explicit ImplicitExceptionSpecification(ASTContext &Context)=20
+    explicit ImplicitExceptionSpecification(ASTContext &Context)
       : Context(&Context), ComputedEST(EST_BasicNoexcept) {
-      if (!Context.getLangOptions().CPlusPlus0x)
+      if (!Context.getLangOpts().CPlusPlus0x)
         ComputedEST =3D EST_DynamicNone;
     }
=20
@@ -2839,28 +3137,18 @@
=20
   /// \brief Determine if a special member function should have a deleted
   /// definition when it is defaulted.
-  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM);
-
-  /// \brief Determine if a defaulted copy assignment operator ought to be
-  /// deleted.
-  bool ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD);
-
-  /// \brief Determine if a defaulted move assignment operator ought to be
-  /// deleted.
-  bool ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD);
-
-  /// \brief Determine if a defaulted destructor ought to be deleted.
-  bool ShouldDeleteDestructor(CXXDestructorDecl *DD);
+  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
+                                 bool Diagnose =3D false);
=20
   /// \brief Declare the implicit default constructor for the given class.
   ///
-  /// \param ClassDecl The class declaration into which the implicit=20
+  /// \param ClassDecl The class declaration into which the implicit
   /// default constructor will be added.
   ///
   /// \returns The implicitly-declared default constructor.
   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
                                                      CXXRecordDecl *ClassD=
ecl);
- =20
+
   /// DefineImplicitDefaultConstructor - Checks for feasibility of
   /// defining this constructor as the default constructor.
   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
@@ -2868,12 +3156,12 @@
=20
   /// \brief Declare the implicit destructor for the given class.
   ///
-  /// \param ClassDecl The class declaration into which the implicit=20
+  /// \param ClassDecl The class declaration into which the implicit
   /// destructor will be added.
   ///
   /// \returns The implicitly-declared destructor.
   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
-                                              =20
+
   /// DefineImplicitDestructor - Checks for feasibility of
   /// defining this destructor as the default destructor.
   void DefineImplicitDestructor(SourceLocation CurrentLocation,
@@ -2894,12 +3182,12 @@
=20
   /// \brief Declare the implicit copy constructor for the given class.
   ///
-  /// \param ClassDecl The class declaration into which the implicit=20
+  /// \param ClassDecl The class declaration into which the implicit
   /// copy constructor will be added.
   ///
   /// \returns The implicitly-declared copy constructor.
   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassD=
ecl);
-                                                    =20
+
   /// DefineImplicitCopyConstructor - Checks for feasibility of
   /// defining this constructor as the copy constructor.
   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
@@ -2913,7 +3201,7 @@
   /// \returns The implicitly-declared move constructor, or NULL if it was=
n't
   /// declared.
   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassD=
ecl);
-                                                    =20
+
   /// DefineImplicitMoveConstructor - Checks for feasibility of
   /// defining this constructor as the move constructor.
   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
@@ -2921,12 +3209,12 @@
=20
   /// \brief Declare the implicit copy assignment operator for the given c=
lass.
   ///
-  /// \param ClassDecl The class declaration into which the implicit=20
+  /// \param ClassDecl The class declaration into which the implicit
   /// copy assignment operator will be added.
   ///
   /// \returns The implicitly-declared copy assignment operator.
   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
- =20
+
   /// \brief Defines an implicitly-declared copy assignment operator.
   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
                                     CXXMethodDecl *MethodDecl);
@@ -2939,7 +3227,7 @@
   /// \returns The implicitly-declared move assignment operator, or NULL i=
f it
   /// wasn't declared.
   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
- =20
+
   /// \brief Defines an implicitly-declared move assignment operator.
   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
                                     CXXMethodDecl *MethodDecl);
@@ -2947,6 +3235,10 @@
   /// \brief Force the declaration of any implicitly-declared members of t=
his
   /// class.
   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
+
+  /// \brief Determine whether the given function is an implicitly-deleted
+  /// special member function.
+  bool isImplicitlyDeleted(FunctionDecl *FD);
  =20
   /// MaybeBindToTemporary - If the passed in expression has a record type=
 with
   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Oth=
erwise
@@ -2956,7 +3248,8 @@
   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
                                MultiExprArg ArgsPtr,
                                SourceLocation Loc,
-                               ASTOwningVector<Expr*> &ConvertedArgs);
+                               ASTOwningVector<Expr*> &ConvertedArgs,
+                               bool AllowExplicit =3D false);
=20
   ParsedType getDestructorName(SourceLocation TildeLoc,
                                IdentifierInfo &II, SourceLocation NameLoc,
@@ -2964,6 +3257,8 @@
                                ParsedType ObjectType,
                                bool EnteringContext);
=20
+  ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
+
   // Checks that reinterpret casts don't have undefined behavior.
   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
                                       bool IsDereference, SourceRange Rang=
e);
@@ -3019,21 +3314,37 @@
   //// ActOnCXXThis -  Parse 'this' pointer.
   ExprResult ActOnCXXThis(SourceLocation loc);
=20
-  /// getAndCaptureCurrentThisType - Try to capture a 'this' pointer.  Ret=
urns
-  /// the type of the 'this' pointer, or a null type if this is not possib=
le.
-  QualType getAndCaptureCurrentThisType();
+  /// \brief Try to retrieve the type of the 'this' pointer.
+  ///
+  /// \param Capture If true, capture 'this' in this context.
+  ///
+  /// \returns The type of 'this', if possible. Otherwise, returns a NULL =
type.
+  QualType getCurrentThisType();
+
+  /// \brief Make sure the value of 'this' is actually available in the cu=
rrent
+  /// context, if it is a potentially evaluated context.
+  ///
+  /// \param Loc The location at which the capture of 'this' occurs.
+  ///
+  /// \param Explicit Whether 'this' is explicitly captured in a lambda
+  /// capture list.
+  void CheckCXXThisCapture(SourceLocation Loc, bool Explicit =3D false);
=20
   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind=
);
+ =20
+ =20
+  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
+  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kin=
d);
=20
   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
=20
   //// ActOnCXXThrow -  Parse throw expressions.
   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
-  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,=20
+  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
                            bool IsThrownVarInScope);
-  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,=20
+  ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
                                   bool IsThrownVarInScope);
=20
   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
@@ -3056,9 +3367,7 @@
                          MultiExprArg PlacementArgs,
                          SourceLocation PlacementRParen,
                          SourceRange TypeIdParens, Declarator &D,
-                         SourceLocation ConstructorLParen,
-                         MultiExprArg ConstructorArgs,
-                         SourceLocation ConstructorRParen);
+                         Expr *Initializer);
   ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
                          SourceLocation PlacementLParen,
                          MultiExprArg PlacementArgs,
@@ -3067,9 +3376,8 @@
                          QualType AllocType,
                          TypeSourceInfo *AllocTypeInfo,
                          Expr *ArraySize,
-                         SourceLocation ConstructorLParen,
-                         MultiExprArg ConstructorArgs,
-                         SourceLocation ConstructorRParen,
+                         SourceRange DirectInitRange,
+                         Expr *Initializer,
                          bool TypeMayContainAuto =3D true);
=20
   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
@@ -3134,6 +3442,14 @@
                                   TypeSourceInfo *RhsT,
                                   SourceLocation RParen);
=20
+  /// \brief Parsed one of the type trait support pseudo-functions.
+  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
+                            ArrayRef<ParsedType> Args,
+                            SourceLocation RParenLoc);
+  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
+                            ArrayRef<TypeSourceInfo *> Args,
+                            SourceLocation RParenLoc);
+ =20
   /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
   /// pseudo-functions.
   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
@@ -3189,6 +3505,13 @@
                                        UnqualifiedId &SecondTypeName,
                                        bool HasTrailingLParen);
=20
+  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
+                                       SourceLocation OpLoc,
+                                       tok::TokenKind OpKind,
+                                       SourceLocation TildeLoc,=20
+                                       const DeclSpec& DS,
+                                       bool HasTrailingLParen);
+
   /// MaybeCreateExprWithCleanups - If the current full-expression
   /// requires any cleanups, surround it with a ExprWithCleanups node.
   /// Otherwise, just returns the passed-in expression.
@@ -3221,7 +3544,7 @@
   /// \returns true if an error occurred, false otherwise.
   bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
                                     CXXScopeSpec &SS);
- =20
+
   bool isAcceptableNestedNameSpecifier(NamedDecl *SD);
   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
=20
@@ -3250,7 +3573,7 @@
   ///
   /// \param CCLoc The location of the '::'.
   ///
-  /// \param ObjectType The type of the object, if we're parsing=20
+  /// \param ObjectType The type of the object, if we're parsing
   /// nested-name-specifier in a member access expression.
   ///
   /// \param EnteringContext Whether we're entering the context nominated =
by
@@ -3270,6 +3593,12 @@
                                    bool EnteringContext,
                                    CXXScopeSpec &SS);
=20
+  ExprResult ActOnDecltypeExpression(Expr *E);
+
+  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
+                                           const DeclSpec &DS,=20
+                                           SourceLocation ColonColonLoc);
+
   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
                                  IdentifierInfo &Identifier,
                                  SourceLocation IdentifierLoc,
@@ -3277,34 +3606,32 @@
                                  ParsedType ObjectType,
                                  bool EnteringContext);
=20
-  /// \brief The parser has parsed a nested-name-specifier=20
+  /// \brief The parser has parsed a nested-name-specifier
   /// 'template[opt] template-name < template-args >::'.
   ///
   /// \param S The scope in which this nested-name-specifier occurs.
   ///
-  /// \param TemplateLoc The location of the 'template' keyword, if any.
-  ///
   /// \param SS The nested-name-specifier, which is both an input
   /// parameter (the nested-name-specifier before this type) and an
   /// output parameter (containing the full nested-name-specifier,
   /// including this new type).
-  ///=20
-  /// \param TemplateLoc the location of the 'template' keyword, if any.
+  ///
+  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
   /// \param TemplateName The template name.
   /// \param TemplateNameLoc The location of the template name.
   /// \param LAngleLoc The location of the opening angle bracket  ('<').
   /// \param TemplateArgs The template arguments.
   /// \param RAngleLoc The location of the closing angle bracket  ('>').
   /// \param CCLoc The location of the '::'.
- =20
-  /// \param EnteringContext Whether we're entering the context of the=20
+  ///
+  /// \param EnteringContext Whether we're entering the context of the
   /// nested-name-specifier.
   ///
   ///
   /// \returns true if an error occurred, false otherwise.
   bool ActOnCXXNestedNameSpecifier(Scope *S,
-                                   SourceLocation TemplateLoc,=20
-                                   CXXScopeSpec &SS,=20
+                                   CXXScopeSpec &SS,
+                                   SourceLocation TemplateKWLoc,
                                    TemplateTy Template,
                                    SourceLocation TemplateNameLoc,
                                    SourceLocation LAngleLoc,
@@ -3314,29 +3641,29 @@
                                    bool EnteringContext);
=20
   /// \brief Given a C++ nested-name-specifier, produce an annotation value
-  /// that the parser can use later to reconstruct the given=20
+  /// that the parser can use later to reconstruct the given
   /// nested-name-specifier.
   ///
   /// \param SS A nested-name-specifier.
   ///
-  /// \returns A pointer containing all of the information in the=20
+  /// \returns A pointer containing all of the information in the
   /// nested-name-specifier \p SS.
   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
- =20
-  /// \brief Given an annotation pointer for a nested-name-specifier, rest=
ore=20
+
+  /// \brief Given an annotation pointer for a nested-name-specifier, rest=
ore
   /// the nested-name-specifier structure.
   ///
-  /// \param Annotation The annotation pointer, produced by=20
+  /// \param Annotation The annotation pointer, produced by
   /// \c SaveNestedNameSpecifierAnnotation().
   ///
   /// \param AnnotationRange The source range corresponding to the annotat=
ion.
   ///
   /// \param SS The nested-name-specifier that will be updated with the co=
ntents
   /// of the annotation pointer.
-  void RestoreNestedNameSpecifierAnnotation(void *Annotation,=20
+  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
                                             SourceRange AnnotationRange,
                                             CXXScopeSpec &SS);
- =20
+
   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
=20
   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (gl=
obal
@@ -3365,16 +3692,107 @@
   /// initializer for the declaration 'Dcl'.
   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
=20
+  /// \brief Create a new lambda closure type.
+  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
+                                         bool KnownDependent =3D false);
+ =20
+  /// \brief Start the definition of a lambda expression.
+  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
+                                       SourceRange IntroducerRange,
+                                       TypeSourceInfo *MethodType,
+                                       SourceLocation EndLoc,
+                                       llvm::ArrayRef<ParmVarDecl *> Param=
s,
+                                       llvm::Optional<unsigned> ManglingNu=
mber=20
+                                         =3D llvm::Optional<unsigned>(),
+                                       Decl *ContextDecl =3D 0);
+ =20
+  /// \brief Introduce the scope for a lambda expression.
+  sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator,
+                                          SourceRange IntroducerRange,
+                                          LambdaCaptureDefault CaptureDefa=
ult,
+                                          bool ExplicitParams,
+                                          bool ExplicitResultType,
+                                          bool Mutable);
+ =20
+  /// \brief Note that we have finished the explicit captures for the
+  /// given lambda.
+  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
+ =20
+  /// \brief Introduce the lambda parameters into scope.
+  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
+ =20
+  /// ActOnStartOfLambdaDefinition - This is called just before we start
+  /// parsing the body of a lambda; it analyzes the explicit captures and=20
+  /// arguments, and sets up various data-structures for the body of the
+  /// lambda.
+  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
+                                    Declarator &ParamInfo, Scope *CurScope=
);
+
+  /// ActOnLambdaError - If there is an error parsing a lambda, this callb=
ack
+  /// is invoked to pop the information about the lambda.
+  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
+                        bool IsInstantiation =3D false);
+
+  /// ActOnLambdaExpr - This is called when the body of a lambda expression
+  /// was successfully completed.
+  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
+                             Scope *CurScope,=20
+                             bool IsInstantiation =3D false);
+
+  /// \brief Define the "body" of the conversion from a lambda object to a=20
+  /// function pointer.
+  ///
+  /// This routine doesn't actually define a sensible body; rather, it fil=
ls
+  /// in the initialization expression needed to copy the lambda object in=
to
+  /// the block, and IR generation actually generates the real body of the
+  /// block pointer conversion.
+  void DefineImplicitLambdaToFunctionPointerConversion(
+         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
+
+  /// \brief Define the "body" of the conversion from a lambda object to a=20
+  /// block pointer.
+  ///
+  /// This routine doesn't actually define a sensible body; rather, it fil=
ls
+  /// in the initialization expression needed to copy the lambda object in=
to
+  /// the block, and IR generation actually generates the real body of the
+  /// block pointer conversion.
+  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation Current=
Loc,
+                                                    CXXConversionDecl *Con=
v);
+
+  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
+                                           SourceLocation ConvLocation,
+                                           CXXConversionDecl *Conv,
+                                           Expr *Src);
+
   // ParseObjCStringLiteral - Parse Objective-C string literals.
   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
                                     Expr **Strings,
                                     unsigned NumStrings);
-
+   =20
+  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S=
);
+ =20
+  /// BuildObjCNumericLiteral - builds an ObjCNumericLiteral AST node for =
the
+  /// numeric literal expression. Type of the expression will be "NSNumber=
 *"
+  /// or "id" if NSNumber is unavailable.
+  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
+  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation Val=
ueLoc,
+                                  bool Value);
+  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
+ =20
+  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExp=
r,
+                                          Expr *IndexExpr,
+                                          ObjCMethodDecl *getterMethod,
+                                          ObjCMethodDecl *setterMethod);
+   =20
+  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,                   =
                     =20
+                                        ObjCDictionaryElement *Elements,
+                                        unsigned NumElements);
+=20
   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
                                   TypeSourceInfo *EncodedTypeInfo,
                                   SourceLocation RParenLoc);
   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
-                                    CXXMethodDecl *Method,
+                                    CXXConversionDecl *Method,
                                     bool HadMultipleCandidates);
=20
   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
@@ -3434,6 +3852,7 @@
                                     CXXScopeSpec &SS,
                                     IdentifierInfo *MemberOrBase,
                                     ParsedType TemplateTypeTy,
+                                    const DeclSpec &DS,
                                     SourceLocation IdLoc,
                                     SourceLocation LParenLoc,
                                     Expr **Args, unsigned NumArgs,
@@ -3445,6 +3864,7 @@
                                     CXXScopeSpec &SS,
                                     IdentifierInfo *MemberOrBase,
                                     ParsedType TemplateTypeTy,
+                                    const DeclSpec &DS,
                                     SourceLocation IdLoc,
                                     Expr *InitList,
                                     SourceLocation EllipsisLoc);
@@ -3454,23 +3874,23 @@
                                     CXXScopeSpec &SS,
                                     IdentifierInfo *MemberOrBase,
                                     ParsedType TemplateTypeTy,
+                                    const DeclSpec &DS,
                                     SourceLocation IdLoc,
-                                    const MultiInitializer &Init,
+                                    Expr *Init,
                                     SourceLocation EllipsisLoc);
=20
   MemInitResult BuildMemberInitializer(ValueDecl *Member,
-                                       const MultiInitializer &Args,
+                                       Expr *Init,
                                        SourceLocation IdLoc);
=20
   MemInitResult BuildBaseInitializer(QualType BaseType,
                                      TypeSourceInfo *BaseTInfo,
-                                     const MultiInitializer &Args,
+                                     Expr *Init,
                                      CXXRecordDecl *ClassDecl,
                                      SourceLocation EllipsisLoc);
=20
   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
-                                           const MultiInitializer &Args,
-                                           SourceLocation BaseLoc,
+                                           Expr *Init,
                                            CXXRecordDecl *ClassDecl);
=20
   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
@@ -3479,9 +3899,9 @@
   bool SetCtorInitializers(CXXConstructorDecl *Constructor,
                            CXXCtorInitializer **Initializers,
                            unsigned NumInitializers, bool AnyErrors);
- =20
+
   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
-                          =20
+
=20
   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
   /// mark all the non-trivial destructors of its members and bases as
@@ -3506,8 +3926,8 @@
=20
   /// \brief Load any externally-stored vtable uses.
   void LoadExternalVTableUses();
- =20
-  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,=20
+
+  typedef LazyVector<CXXRecordDecl *, ExternalSemaSource,
                      &ExternalSemaSource::ReadDynamicClasses, 2, 2>
     DynamicClassesType;
=20
@@ -3563,7 +3983,8 @@
                                      Expr *AssertMessageExpr,
                                      SourceLocation RParenLoc);
=20
-  FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc,
+  FriendDecl *CheckFriendTypeDecl(SourceLocation Loc,
+                                  SourceLocation FriendLoc,
                                   TypeSourceInfo *TSInfo);
   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
                             MultiTemplateParamsArg TemplateParams);
@@ -3602,7 +4023,7 @@
   BaseResult ActOnBaseSpecifier(Decl *classdecl,
                                 SourceRange SpecifierRange,
                                 bool Virtual, AccessSpecifier Access,
-                                ParsedType basetype,=20
+                                ParsedType basetype,
                                 SourceLocation BaseLoc,
                                 SourceLocation EllipsisLoc);
=20
@@ -3652,7 +4073,7 @@
   /// C++0x [class.virtual]p3.
   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
                                               const CXXMethodDecl *Old);
- =20
+
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ Access Control
@@ -3685,11 +4106,13 @@
                                       bool IsCopyBindingRefToTemp =3D fals=
e);
   AccessResult CheckConstructorAccess(SourceLocation Loc,
                                       CXXConstructorDecl *D,
+                                      const InitializedEntity &Entity,
                                       AccessSpecifier Access,
-                                      PartialDiagnostic PD);
+                                      const PartialDiagnostic &PDiag);
   AccessResult CheckDestructorAccess(SourceLocation Loc,
                                      CXXDestructorDecl *Dtor,
-                                     const PartialDiagnostic &PDiag);
+                                     const PartialDiagnostic &PDiag,
+                                     QualType objectType =3D QualType());
   AccessResult CheckDirectMemberAccess(SourceLocation Loc,
                                        NamedDecl *D,
                                        const PartialDiagnostic &PDiag);
@@ -3706,7 +4129,10 @@
                                     bool ForceCheck =3D false,
                                     bool ForceUnprivileged =3D false);
   void CheckLookupAccess(const LookupResult &R);
-  bool IsSimplyAccessible(NamedDecl *decl, CXXRecordDecl *Class);
+  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
+  bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
+                                            AccessSpecifier access,
+                                            QualType objectType);
=20
   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
                          const MultiLevelTemplateArgumentList &TemplateArg=
s);
@@ -3721,7 +4147,27 @@
   /// \brief When true, access checking violations are treated as SFINAE
   /// failures rather than hard errors.
   bool AccessCheckingSFINAE;
- =20
+
+  /// \brief RAII object used to temporarily suppress access checking.
+  class SuppressAccessChecksRAII {
+    Sema &S;
+    bool SuppressingAccess;
+
+  public:
+    SuppressAccessChecksRAII(Sema &S, bool Suppress)
+      : S(S), SuppressingAccess(Suppress) {
+      if (Suppress) S.ActOnStartSuppressingAccessChecks();
+    }
+    ~SuppressAccessChecksRAII() {
+      done();
+    }
+    void done() {
+      if (!SuppressingAccess) return;
+      S.ActOnStopSuppressingAccessChecks();
+      SuppressingAccess =3D false;
+    }
+  };
+
   void ActOnStartSuppressingAccessChecks();
   void ActOnStopSuppressingAccessChecks();
=20
@@ -3752,9 +4198,11 @@
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ Templates [C++ 14]
   //
-  void FilterAcceptableTemplateNames(LookupResult &R);
-  bool hasAnyAcceptableTemplateNames(LookupResult &R);
- =20
+  void FilterAcceptableTemplateNames(LookupResult &R,=20
+                                     bool AllowFunctionTemplates =3D true);
+  bool hasAnyAcceptableTemplateNames(LookupResult &R,=20
+                                     bool AllowFunctionTemplates =3D true);
+
   void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
                           QualType ObjectType, bool EnteringContext,
                           bool &MemberOfUnknownSpecialization);
@@ -3775,7 +4223,7 @@
                                    TemplateTy &SuggestedTemplate,
                                    TemplateNameKind &SuggestedKind);
=20
-  bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
+  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
=20
   Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
@@ -3841,7 +4289,7 @@
                                 IdentifierInfo *Name, SourceLocation NameL=
oc,
                                 AttributeList *Attr,
                                 TemplateParameterList *TemplateParams,
-                                AccessSpecifier AS,=20
+                                AccessSpecifier AS,
                                 SourceLocation ModulePrivateLoc,
                                 unsigned NumOuterTemplateParamLists,
                             TemplateParameterList **OuterTemplateParamList=
s);
@@ -3850,44 +4298,49 @@
                                   TemplateArgumentListInfo &Out);
=20
   void NoteAllFoundTemplates(TemplateName Name);
- =20
+
   QualType CheckTemplateIdType(TemplateName Template,
                                SourceLocation TemplateLoc,
                               TemplateArgumentListInfo &TemplateArgs);
=20
   TypeResult
-  ActOnTemplateIdType(CXXScopeSpec &SS,
+  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
                       TemplateTy Template, SourceLocation TemplateLoc,
                       SourceLocation LAngleLoc,
                       ASTTemplateArgsPtr TemplateArgs,
-                      SourceLocation RAngleLoc);
+                      SourceLocation RAngleLoc,
+                      bool IsCtorOrDtorName =3D false);
=20
   /// \brief Parsed an elaborated-type-specifier that refers to a template=
-id,
   /// such as \c class T::template apply<U>.
   ///
-  /// \param TUK=20
+  /// \param TUK
   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
                                     TypeSpecifierType TagSpec,
                                     SourceLocation TagLoc,
                                     CXXScopeSpec &SS,
-                                    TemplateTy TemplateD,=20
+                                    SourceLocation TemplateKWLoc,
+                                    TemplateTy TemplateD,
                                     SourceLocation TemplateLoc,
                                     SourceLocation LAngleLoc,
                                     ASTTemplateArgsPtr TemplateArgsIn,
                                     SourceLocation RAngleLoc);
=20
- =20
+
   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
+                                 SourceLocation TemplateKWLoc,
                                  LookupResult &R,
                                  bool RequiresADL,
-                               const TemplateArgumentListInfo &TemplateArg=
s);
+                               const TemplateArgumentListInfo *TemplateArg=
s);
+
   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
+                                          SourceLocation TemplateKWLoc,
                                const DeclarationNameInfo &NameInfo,
-                               const TemplateArgumentListInfo &TemplateArg=
s);
+                               const TemplateArgumentListInfo *TemplateArg=
s);
=20
   TemplateNameKind ActOnDependentTemplateName(Scope *S,
+                                              CXXScopeSpec &SS,
                                               SourceLocation TemplateKWLoc,
-                                              CXXScopeSpec &SS,
                                               UnqualifiedId &Name,
                                               ParsedType ObjectType,
                                               bool EnteringContext,
@@ -4013,12 +4466,18 @@
   /// \param Converted Will receive the converted, canonicalized template
   /// arguments.
   ///
+  ///
+  /// \param ExpansionIntoFixedList If non-NULL, will be set true to indic=
ate
+  /// when the template arguments contain a pack expansion that is being
+  /// expanded into a fixed parameter list.
+  ///
   /// \returns True if an error occurred, false otherwise.
   bool CheckTemplateArgumentList(TemplateDecl *Template,
                                  SourceLocation TemplateLoc,
                                  TemplateArgumentListInfo &TemplateArgs,
                                  bool PartialTemplateArgs,
-                           SmallVectorImpl<TemplateArgument> &Converted);
+                           SmallVectorImpl<TemplateArgument> &Converted,
+                                 bool *ExpansionIntoFixedList =3D 0);
=20
   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
                                  const TemplateArgumentLoc &Arg,
@@ -4026,12 +4485,10 @@
=20
   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
                              TypeSourceInfo *Arg);
-  bool CheckTemplateArgumentPointerToMember(Expr *Arg,
-                                            TemplateArgument &Converted);
   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
                                    QualType InstantiatedParamType, Expr *A=
rg,
                                    TemplateArgument &Converted,
-                                   CheckTemplateArgumentKind CTAK =3D CTAK=
_Specified);
+                               CheckTemplateArgumentKind CTAK =3D CTAK_Spe=
cified);
   bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
                              const TemplateArgumentLoc &Arg);
=20
@@ -4095,8 +4552,8 @@
   /// \param II the identifier we're retrieving (e.g., 'type' in the examp=
le).
   /// \param IdLoc the location of the identifier.
   TypeResult
-  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,=20
-                    const CXXScopeSpec &SS, const IdentifierInfo &II,=20
+  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
+                    const CXXScopeSpec &SS, const IdentifierInfo &II,
                     SourceLocation IdLoc);
=20
   /// \brief Called when the parser has parsed a C++ typename
@@ -4113,9 +4570,9 @@
   /// \param TemplateArgs The template arguments.
   /// \param RAngleLoc The location of the closing angle bracket  ('>').
   TypeResult
-  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,=20
-                    const CXXScopeSpec &SS,=20
-                    SourceLocation TemplateLoc,=20
+  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
+                    const CXXScopeSpec &SS,
+                    SourceLocation TemplateLoc,
                     TemplateTy Template,
                     SourceLocation TemplateNameLoc,
                     SourceLocation LAngleLoc,
@@ -4136,7 +4593,7 @@
   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
   bool RebuildTemplateParamsInCurrentInstantiation(
                                                 TemplateParameterList *Par=
ams);
- =20
+
   std::string
   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
                                   const TemplateArgumentList &Args);
@@ -4191,19 +4648,37 @@
=20
     /// \brief An initializer.
     UPPC_Initializer,
-   =20
+
     /// \brief A default argument.
     UPPC_DefaultArgument,
-   =20
+
     /// \brief The type of a non-type template parameter.
     UPPC_NonTypeTemplateParameterType,
=20
     /// \brief The type of an exception.
     UPPC_ExceptionType,
-   =20
+
     /// \brief Partial specialization.
-    UPPC_PartialSpecialization
-  };
+    UPPC_PartialSpecialization,
+
+    /// \brief Microsoft __if_exists.
+    UPPC_IfExists,
+
+    /// \brief Microsoft __if_not_exists.
+    UPPC_IfNotExists
+};
+
+  /// \brief Diagnose unexpanded parameter packs.
+  ///
+  /// \param Loc The location at which we should emit the diagnostic.
+  ///
+  /// \param UPPC The context in which we are diagnosing unexpanded
+  /// parameter packs.
+  ///
+  /// \param Unexpanded the set of unexpanded parameter packs.
+  void DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
+                                        UnexpandedParameterPackContext UPP=
C,
+                                  ArrayRef<UnexpandedParameterPack> Unexpa=
nded);
=20
   /// \brief If the given type contains an unexpanded parameter pack,
   /// diagnose the error.
@@ -4252,7 +4727,7 @@
   ///
   /// \param Loc The location of the template name.
   ///
-  /// \param Template The template name that is being checked for unexpand=
ed=20
+  /// \param Template The template name that is being checked for unexpand=
ed
   /// parameter packs.
   ///
   /// \returns true if an error occurred, false otherwise.
@@ -4260,18 +4735,18 @@
                                        TemplateName Template,
                                        UnexpandedParameterPackContext UPPC=
);
=20
-  /// \brief If the given template argument contains an unexpanded paramet=
er=20
+  /// \brief If the given template argument contains an unexpanded paramet=
er
   /// pack, diagnose the error.
   ///
-  /// \param Arg The template argument that is being checked for unexpande=
d=20
+  /// \param Arg The template argument that is being checked for unexpanded
   /// parameter packs.
   ///
   /// \returns true if an error occurred, false otherwise.
   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
                                        UnexpandedParameterPackContext UPPC=
);
- =20
+
   /// \brief Collect the set of unexpanded parameter packs within the given
-  /// template argument. =20
+  /// template argument.
   ///
   /// \param Arg The template argument that will be traversed to find
   /// unexpanded parameter packs.
@@ -4279,7 +4754,7 @@
                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
=20
   /// \brief Collect the set of unexpanded parameter packs within the given
-  /// template argument. =20
+  /// template argument.
   ///
   /// \param Arg The template argument that will be traversed to find
   /// unexpanded parameter packs.
@@ -4287,7 +4762,7 @@
                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
=20
   /// \brief Collect the set of unexpanded parameter packs within the given
-  /// type. =20
+  /// type.
   ///
   /// \param T The type that will be traversed to find
   /// unexpanded parameter packs.
@@ -4295,13 +4770,29 @@
                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
=20
   /// \brief Collect the set of unexpanded parameter packs within the given
-  /// type. =20
+  /// type.
   ///
   /// \param TL The type that will be traversed to find
   /// unexpanded parameter packs.
   void collectUnexpandedParameterPacks(TypeLoc TL,
                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
=20
+  /// \brief Collect the set of unexpanded parameter packs within the given
+  /// nested-name-specifier.
+  ///
+  /// \param SS The nested-name-specifier that will be traversed to find
+  /// unexpanded parameter packs.
+  void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
+                         SmallVectorImpl<UnexpandedParameterPack> &Unexpan=
ded);
+
+  /// \brief Collect the set of unexpanded parameter packs within the given
+  /// name.
+  ///
+  /// \param NameInfo The name that will be traversed to find
+  /// unexpanded parameter packs.
+  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
+                         SmallVectorImpl<UnexpandedParameterPack> &Unexpan=
ded);
+
   /// \brief Invoked when parsing a template argument followed by an
   /// ellipsis, which creates a pack expansion.
   ///
@@ -4363,7 +4854,7 @@
   /// \param PatternRange The source range that covers the entire pattern =
of
   /// the pack expansion.
   ///
-  /// \param Unexpanded The set of unexpanded parameter packs within the=20
+  /// \param Unexpanded The set of unexpanded parameter packs within the
   /// pattern.
   ///
   /// \param NumUnexpanded The number of unexpanded parameter packs in
@@ -4386,9 +4877,9 @@
   /// The callee must set this value when \c ShouldExpand is \c true; it m=
ay
   /// set this value in other cases.
   ///
-  /// \returns true if an error occurred (e.g., because the parameter pack=
s=20
-  /// are to be instantiated with arguments of different lengths), false=20
-  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)=20
+  /// \returns true if an error occurred (e.g., because the parameter packs
+  /// are to be instantiated with arguments of different lengths), false
+  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
   /// must be set.
   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
                                        SourceRange PatternRange,
@@ -4404,9 +4895,9 @@
   /// This routine already assumes that the pack expansion type can be
   /// expanded and that the number of arguments in the expansion is
   /// consistent across all of the unexpanded parameter packs in its patte=
rn.
-  unsigned getNumArgumentsInExpansion(QualType T,=20
+  unsigned getNumArgumentsInExpansion(QualType T,
                             const MultiLevelTemplateArgumentList &Template=
Args);
- =20
+
   /// \brief Determine whether the given declarator contains any unexpanded
   /// parameter packs.
   ///
@@ -4423,11 +4914,11 @@
   /// \returns true if the declarator contains any unexpanded parameter pa=
cks,
   /// false otherwise.
   bool containsUnexpandedParameterPacks(Declarator &D);
- =20
+
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ Template Argument Deduction (C++ [temp.deduct])
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
- =20
+
   /// \brief Describes the result of template argument deduction.
   ///
   /// The TemplateDeductionResult enumeration describes the result of
@@ -4489,20 +4980,20 @@
                                       QualType *FunctionType,
                                       sema::TemplateDeductionInfo &Info);
=20
-  /// brief A function argument from which we performed template argument=20
+  /// brief A function argument from which we performed template argument
   // deduction for a call.
   struct OriginalCallArg {
     OriginalCallArg(QualType OriginalParamType,
                     unsigned ArgIdx,
                     QualType OriginalArgType)
-      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),=20
+      : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
         OriginalArgType(OriginalArgType) { }
-   =20
+
     QualType OriginalParamType;
     unsigned ArgIdx;
     QualType OriginalArgType;
   };
- =20
+
   TemplateDeductionResult
   FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
@@ -4514,7 +5005,7 @@
   TemplateDeductionResult
   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
                           TemplateArgumentListInfo *ExplicitTemplateArgs,
-                          Expr **Args, unsigned NumArgs,
+                          llvm::ArrayRef<Expr *> Args,
                           FunctionDecl *&Specialization,
                           sema::TemplateDeductionInfo &Info);
=20
@@ -4537,8 +5028,16 @@
                           FunctionDecl *&Specialization,
                           sema::TemplateDeductionInfo &Info);
=20
-  bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer,
-                      TypeSourceInfo *&Result);
+  /// \brief Result type of DeduceAutoType.
+  enum DeduceAutoResult {
+    DAR_Succeeded,
+    DAR_Failed,
+    DAR_FailedAlreadyDiagnosed
+  };
+
+  DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initial=
izer,
+                                  TypeSourceInfo *&Result);
+  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
=20
   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *F=
T1,
                                                    FunctionTemplateDecl *F=
T2,
@@ -4553,7 +5052,8 @@
                                            const PartialDiagnostic &NoneDi=
ag,
                                            const PartialDiagnostic &AmbigD=
iag,
                                         const PartialDiagnostic &Candidate=
Diag,
-                                        bool Complain =3D true);
+                                        bool Complain =3D true,
+                                        QualType TargetType =3D QualType()=
);
=20
   ClassTemplatePartialSpecializationDecl *
   getMoreSpecializedPartialSpecialization(
@@ -4564,9 +5064,14 @@
   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
                                   bool OnlyDeduced,
                                   unsigned Depth,
-                                  SmallVectorImpl<bool> &Used);
+                                  llvm::SmallBitVector &Used);
   void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplat=
e,
-                                     SmallVectorImpl<bool> &Deduced);
+                                     llvm::SmallBitVector &Deduced) {
+    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduce=
d);
+  }
+  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
+                                         FunctionTemplateDecl *FunctionTem=
plate,
+                                         llvm::SmallBitVector &Deduced);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   // C++ Template Instantiation
@@ -4621,8 +5126,8 @@
     /// \brief The point of instantiation within the source code.
     SourceLocation PointOfInstantiation;
=20
-    /// \brief The template (or partial specialization) in which we are=20
-    /// performing the instantiation, for substitutions of prior template=20
+    /// \brief The template (or partial specialization) in which we are
+    /// performing the instantiation, for substitutions of prior template
     /// arguments.
     NamedDecl *Template;
=20
@@ -4636,7 +5141,7 @@
     /// \brief The number of template arguments in TemplateArgs.
     unsigned NumTemplateArgs;
=20
-    /// \brief The template deduction info object associated with the=20
+    /// \brief The template deduction info object associated with the
     /// substitution or checking of explicit or deduced template arguments.
     sema::TemplateDeductionInfo *DeductionInfo;
=20
@@ -4680,7 +5185,7 @@
=20
       }
=20
-      return true;
+      llvm_unreachable("Invalid InstantiationKind!");
     }
=20
     friend bool operator!=3D(const ActiveTemplateInstantiation &X,
@@ -4704,7 +5209,7 @@
   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outsi=
de
   /// of a template instantiation or template argument deduction.
   bool InNonInstantiationSFINAEContext;
- =20
+
   /// \brief The number of ActiveTemplateInstantiation entries in
   /// \c ActiveTemplateInstantiations that are not actual instantiations a=
nd,
   /// therefore, should not be counted as part of the instantiation depth.
@@ -4722,7 +5227,7 @@
   /// \brief The current index into pack expansion arguments that will be
   /// used for substitution of parameter packs.
   ///
-  /// The pack expansion index will be -1 to indicate that parameter packs=20
+  /// The pack expansion index will be -1 to indicate that parameter packs
   /// should be instantiated as themselves. Otherwise, the index specifies
   /// which argument within the parameter pack will be used for substituti=
on.
   int ArgumentPackSubstitutionIndex;
@@ -4734,26 +5239,26 @@
   class ArgumentPackSubstitutionIndexRAII {
     Sema &Self;
     int OldSubstitutionIndex;
-   =20
+
   public:
     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionInde=
x) {
       Self.ArgumentPackSubstitutionIndex =3D NewSubstitutionIndex;
     }
-   =20
+
     ~ArgumentPackSubstitutionIndexRAII() {
       Self.ArgumentPackSubstitutionIndex =3D OldSubstitutionIndex;
     }
   };
- =20
+
   friend class ArgumentPackSubstitutionRAII;
- =20
+
   /// \brief The stack of calls expression undergoing template instantiati=
on.
   ///
   /// The top of this stack is used by a fixit instantiating unresolved
   /// function calls to fix the AST to match the textual change it prints.
   SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
- =20
+
   /// \brief For each declaration that involved template argument deductio=
n, the
   /// set of diagnostics that were suppressed during that template argument
   /// deduction.
@@ -4761,7 +5266,7 @@
   /// FIXME: Serialize this structure to the AST file.
   llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
     SuppressedDiagnostics;
- =20
+
   /// \brief A stack object to be created when performing template
   /// instantiation.
   ///
@@ -4863,15 +5368,15 @@
   };
=20
   void PrintInstantiationStack();
- =20
+
   /// \brief Determines whether we are currently in a context where
   /// template argument substitution failures are not considered
   /// errors.
   ///
   /// \returns An empty \c llvm::Optional if we're not in a SFINAE context.
-  /// Otherwise, contains a pointer that, if non-NULL, contains the neares=
t=20
-  /// template-deduction context object, which can be used to capture=20
-  /// diagnostics that will be suppressed.=20
+  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
+  /// template-deduction context object, which can be used to capture
+  /// diagnostics that will be suppressed.
   llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
=20
   /// \brief RAII class used to determine whether SFINAE has
@@ -4882,22 +5387,22 @@
     unsigned PrevSFINAEErrors;
     bool PrevInNonInstantiationSFINAEContext;
     bool PrevAccessCheckingSFINAE;
-   =20
+
   public:
     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE =3D false)
       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
         PrevInNonInstantiationSFINAEContext(
                                       SemaRef.InNonInstantiationSFINAECont=
ext),
         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
-    {=20
+    {
       if (!SemaRef.isSFINAEContext())
         SemaRef.InNonInstantiationSFINAEContext =3D true;
       SemaRef.AccessCheckingSFINAE =3D AccessCheckingSFINAE;
     }
=20
-    ~SFINAETrap() {=20
-      SemaRef.NumSFINAEErrors =3D PrevSFINAEErrors;=20
-      SemaRef.InNonInstantiationSFINAEContext=20
+    ~SFINAETrap() {
+      SemaRef.NumSFINAEErrors =3D PrevSFINAEErrors;
+      SemaRef.InNonInstantiationSFINAEContext
         =3D PrevInNonInstantiationSFINAEContext;
       SemaRef.AccessCheckingSFINAE =3D PrevAccessCheckingSFINAE;
     }
@@ -4917,7 +5422,7 @@
=20
   typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection>
     UnqualifiedTyposCorrectedMap;
- =20
+
   /// \brief A cache containing the results of typo correction for unquali=
fied
   /// name lookup.
   ///
@@ -4925,7 +5430,7 @@
   /// there was no correction), while the boolean will be true when the
   /// string represents a keyword.
   UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected;
- =20
+
   /// \brief Worker object for performing CFG-based warnings.
   sema::AnalysisBasedWarnings AnalysisWarnings;
=20
@@ -4973,15 +5478,16 @@
   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
                             const MultiLevelTemplateArgumentList &Template=
Args,
                                 int indexAdjustment,
-                                llvm::Optional<unsigned> NumExpansions);
-  bool SubstParmTypes(SourceLocation Loc,=20
+                                llvm::Optional<unsigned> NumExpansions,
+                                bool ExpectParameterPack);
+  bool SubstParmTypes(SourceLocation Loc,
                       ParmVarDecl **Params, unsigned NumParams,
                       const MultiLevelTemplateArgumentList &TemplateArgs,
                       SmallVectorImpl<QualType> &ParamTypes,
                       SmallVectorImpl<ParmVarDecl *> *OutParams =3D 0);
   ExprResult SubstExpr(Expr *E,
                        const MultiLevelTemplateArgumentList &TemplateArgs);
- =20
+
   /// \brief Substitute the given template arguments into a list of
   /// expressions, expanding pack expansions if required.
   ///
@@ -5007,6 +5513,10 @@
   Decl *SubstDecl(Decl *D, DeclContext *Owner,
                   const MultiLevelTemplateArgumentList &TemplateArgs);
=20
+  ExprResult SubstInitializer(Expr *E,
+                       const MultiLevelTemplateArgumentList &TemplateArgs,
+                       bool CXXDirectInit);
+
   bool
   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
                       CXXRecordDecl *Pattern,
@@ -5019,8 +5529,27 @@
                    TemplateSpecializationKind TSK,
                    bool Complain =3D true);
=20
+  bool InstantiateEnum(SourceLocation PointOfInstantiation,
+                       EnumDecl *Instantiation, EnumDecl *Pattern,
+                       const MultiLevelTemplateArgumentList &TemplateArgs,
+                       TemplateSpecializationKind TSK);
+
+  struct LateInstantiatedAttribute {
+    const Attr *TmplAttr;
+    LocalInstantiationScope *Scope;
+    Decl *NewDecl;
+
+    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
+                              Decl *D)
+      : TmplAttr(A), Scope(S), NewDecl(D)
+    { }
+  };
+  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrV=
ec;
+
   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
-                        const Decl *Pattern, Decl *Inst);
+                        const Decl *Pattern, Decl *Inst,
+                        LateInstantiatedAttrVec *LateAttrs =3D 0,
+                        LocalInstantiationScope *OuterMostScope =3D 0);
=20
   bool
   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiati=
on,
@@ -5046,7 +5575,7 @@
   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
                            const MultiLevelTemplateArgumentList &TemplateA=
rgs);
   TemplateName
-  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name=
,=20
+  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
                     SourceLocation Loc,
                     const MultiLevelTemplateArgumentList &TemplateArgs);
   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
@@ -5066,11 +5595,6 @@
   void InstantiateMemInitializers(CXXConstructorDecl *New,
                                   const CXXConstructorDecl *Tmpl,
                             const MultiLevelTemplateArgumentList &Template=
Args);
-  bool InstantiateInitializer(Expr *Init,
-                            const MultiLevelTemplateArgumentList &Template=
Args,
-                              SourceLocation &LParenLoc,
-                              ASTOwningVector<Expr*> &NewArgs,
-                              SourceLocation &RParenLoc);
=20
   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
                           const MultiLevelTemplateArgumentList &TemplateAr=
gs);
@@ -5078,6 +5602,17 @@
                           const MultiLevelTemplateArgumentList &TemplateAr=
gs);
=20
   // Objective-C declarations.
+  enum ObjCContainerKind {
+    OCK_None =3D -1,
+    OCK_Interface =3D 0,
+    OCK_Protocol,
+    OCK_Category,
+    OCK_ClassExtension,
+    OCK_Implementation,
+    OCK_CategoryImplementation
+  };
+  ObjCContainerKind getObjCContainerKind() const;
+
   Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
                                  IdentifierInfo *ClassName,
                                  SourceLocation ClassLoc,
@@ -5129,12 +5664,15 @@
                                          IdentifierInfo *CatName,
                                          SourceLocation CatLoc);
=20
+  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
+                                               ArrayRef<Decl *> Decls);
+
   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
                                      IdentifierInfo **IdentList,
                                      SourceLocation *IdentLocs,
                                      unsigned NumElts);
=20
-  Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
+  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclL=
oc,
                                         const IdentifierLocPair *IdentList,
                                         unsigned NumElts,
                                         AttributeList *attrList);
@@ -5155,7 +5693,7 @@
   /// setters and getters as needed.
   /// \param property The property declaration being processed
   /// \param DC The semantic container for the property
-  /// \param redeclaredProperty Declaration for property if redeclared=20
+  /// \param redeclaredProperty Declaration for property if redeclared
   ///        in class extension.
   /// \param lexicalDC Container for redeclaredProperty.
   void ProcessPropertyDecl(ObjCPropertyDecl *property,
@@ -5180,12 +5718,13 @@
   void MatchOneProtocolPropertiesInClass(Decl *CDecl,
                                          ObjCProtocolDecl *PDecl);
=20
-  void ActOnAtEnd(Scope *S, SourceRange AtEnd,
-                  Decl **allMethods =3D 0, unsigned allNum =3D 0,
-                  Decl **allProperties =3D 0, unsigned pNum =3D 0,
-                  DeclGroupPtrTy *allTUVars =3D 0, unsigned tuvNum =3D 0);
+  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
+                   Decl **allMethods =3D 0, unsigned allNum =3D 0,
+                   Decl **allProperties =3D 0, unsigned pNum =3D 0,
+                   DeclGroupPtrTy *allTUVars =3D 0, unsigned tuvNum =3D 0);
=20
   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
+                      SourceLocation LParenLoc,
                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
                       Selector GetterSel, Selector SetterSel,
                       bool *OverridingProperty,
@@ -5246,9 +5785,11 @@
   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
                                               const ObjCObjectPointerType =
*OPT,
                                               bool IsInstance);
+  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
+                                           bool IsInstance);
=20
   bool inferObjCARCLifetime(ValueDecl *decl);
-   =20
+
   ExprResult
   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
                             Expr *BaseExpr,
@@ -5264,7 +5805,7 @@
                             SourceLocation receiverNameLoc,
                             SourceLocation propertyNameLoc);
=20
-  ObjCMethodDecl *tryCaptureObjCSelf();
+  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
=20
   /// \brief Describes the kind of message expression indicated by a messa=
ge
   /// send that starts with an identifier.
@@ -5277,7 +5818,7 @@
     /// name.
     ObjCClassMessage
   };
- =20
+
   ObjCMessageKind getObjCMessageKind(Scope *S,
                                      IdentifierInfo *Name,
                                      SourceLocation NameLoc,
@@ -5300,7 +5841,15 @@
                                SourceLocation LBracLoc,
                                ArrayRef<SourceLocation> SelectorLocs,
                                SourceLocation RBracLoc,
-                               MultiExprArg Args);
+                               MultiExprArg Args,
+                               bool isImplicit =3D false);
+
+  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
+                                       bool isSuperReceiver,
+                                       SourceLocation Loc,
+                                       Selector Sel,
+                                       ObjCMethodDecl *Method,
+                                       MultiExprArg Args);
=20
   ExprResult ActOnClassMessage(Scope *S,
                                ParsedType Receiver,
@@ -5318,7 +5867,15 @@
                                   SourceLocation LBracLoc,
                                   ArrayRef<SourceLocation> SelectorLocs,
                                   SourceLocation RBracLoc,
-                                  MultiExprArg Args);
+                                  MultiExprArg Args,
+                                  bool isImplicit =3D false);
+
+  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
+                                          QualType ReceiverType,
+                                          SourceLocation Loc,
+                                          Selector Sel,
+                                          ObjCMethodDecl *Method,
+                                          MultiExprArg Args);
=20
   ExprResult ActOnInstanceMessage(Scope *S,
                                   Expr *Receiver,
@@ -5333,7 +5890,7 @@
                                   SourceLocation BridgeKeywordLoc,
                                   TypeSourceInfo *TSInfo,
                                   Expr *SubExpr);
- =20
+
   ExprResult ActOnObjCBridgedCast(Scope *S,
                                   SourceLocation LParenLoc,
                                   ObjCBridgeCastKind Kind,
@@ -5341,19 +5898,19 @@
                                   ParsedType Type,
                                   SourceLocation RParenLoc,
                                   Expr *SubExpr);
- =20
+
   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall=
);
- =20
+
   /// \brief Check whether the given new method is a valid override of the
   /// given overridden method, and set any properties that should be inher=
ited.
-  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,=20
+  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
                                const ObjCMethodDecl *Overridden,
                                bool IsImplementation);
=20
   /// \brief Check whether the given method overrides any methods in its c=
lass,
   /// calling \c CheckObjCMethodOverride for each overridden method.
   bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC=
);
- =20
+
   enum PragmaOptionsAlignKind {
     POAK_Native,  // #pragma options align=3Dnative
     POAK_Natural, // #pragma options align=3Dnatural
@@ -5387,7 +5944,7 @@
                        SourceLocation PragmaLoc,
                        SourceLocation LParenLoc,
                        SourceLocation RParenLoc);
-   =20
+
   /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|of=
f].
   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
=20
@@ -5397,7 +5954,7 @@
                          SourceLocation PragmaLoc);
=20
   /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility=
... .
-  void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType,
+  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
                              SourceLocation PragmaLoc);
=20
   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
@@ -5409,6 +5966,14 @@
                          SourceLocation PragmaLoc,
                          SourceLocation WeakNameLoc);
=20
+  /// ActOnPragmaRedefineExtname - Called on well formed=20
+  /// #pragma redefine_extname oldname newname.
+  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
+                                  IdentifierInfo* AliasName,
+                                  SourceLocation PragmaLoc,
+                                  SourceLocation WeakNameLoc,
+                                  SourceLocation AliasNameLoc);
+
   /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident =3D =
ident.
   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
                             IdentifierInfo* AliasName,
@@ -5432,7 +5997,8 @@
=20
   /// PushNamespaceVisibilityAttr - Note that we've entered a
   /// namespace with a visibility attribute.
-  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr);
+  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
+                                   SourceLocation Loc);
=20
   /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used,
   /// add an appropriate visibility attribute.
@@ -5440,7 +6006,7 @@
=20
   /// PopPragmaVisibility - Pop the top element of the visibility stack; u=
sed
   /// for '#pragma GCC visibility' and visibility attributes on namespaces.
-  void PopPragmaVisibility();
+  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
=20
   /// FreeVisContext - Deallocate and null out VisContext.
   void FreeVisContext();
@@ -5472,7 +6038,7 @@
   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
                                ExprValueKind VK =3D VK_RValue,
                                const CXXCastPath *BasePath =3D 0,
-                               CheckedConversionKind CCK=20
+                               CheckedConversionKind CCK
                                   =3D CCK_ImplicitConversion);
=20
   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
@@ -5525,7 +6091,8 @@
                               unsigned FirstProtoArg,
                               Expr **Args, unsigned NumArgs,
                               SmallVector<Expr *, 8> &AllArgs,
-                              VariadicCallType CallType =3D VariadicDoesNo=
tApply);
+                              VariadicCallType CallType =3D VariadicDoesNo=
tApply,
+                              bool AllowExplicit =3D false);
=20
   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
   // will warn if the resulting type is not a POD type.
@@ -5566,9 +6133,9 @@
     IncompatiblePointer,
=20
     /// IncompatiblePointer - The assignment is between two pointers types=
 which
-    /// point to integers which have a different sign, but are otherwise i=
dentical.
-    /// This is a subset of the above, but broken out because it's by far =
the most
-    /// common case of incompatible pointers.
+    /// point to integers which have a different sign, but are otherwise
+    /// identical. This is a subset of the above, but broken out because i=
t's by
+    /// far the most common case of incompatible pointers.
     IncompatiblePointerSign,
=20
     /// CompatiblePointerDiscardsQualifiers - The assignment discards
@@ -5652,13 +6219,11 @@
=20
   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
                                        AssignmentAction Action,
-                                       bool AllowExplicit =3D false,
-                                       bool Diagnose =3D true);
+                                       bool AllowExplicit =3D false);
   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
                                        AssignmentAction Action,
                                        bool AllowExplicit,
-                                       ImplicitConversionSequence& ICS,
-                                       bool Diagnose =3D true);
+                                       ImplicitConversionSequence& ICS);
   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
                                        const ImplicitConversionSequence& I=
CS,
                                        AssignmentAction Action,
@@ -5685,7 +6250,7 @@
     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
     bool IsCompAssign =3D false);
   QualType CheckAdditionOperands( // C99 6.5.6
-    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
+    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
     QualType* CompLHSTy =3D 0);
   QualType CheckSubtractionOperands( // C99 6.5.6
     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
@@ -5706,11 +6271,15 @@
   // For compound assignment, pass both expressions and the converted type.
   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundT=
ype);
- =20
-  void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
-                                QualType& LHSTy);
-  ExprResult ConvertPropertyForRValue(Expr *E);
-                                  =20
+
+  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
+                                     UnaryOperatorKind Opcode, Expr *Op);
+  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
+                                         BinaryOperatorKind Opcode,
+                                         Expr *LHS, Expr *RHS);
+  ExprResult checkPseudoObjectRValue(Expr *E);
+  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
+
   QualType CheckConditionalOperands( // C99 6.5.15
     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
@@ -5719,10 +6288,12 @@
     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&=
E2,
                                     bool *NonStandardCompositeType =3D 0);
-  QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, Ex=
prResult &E2,
+  QualType FindCompositePointerType(SourceLocation Loc,
+                                    ExprResult &E1, ExprResult &E2,
                                     bool *NonStandardCompositeType =3D 0) {
     Expr *E1Tmp =3D E1.take(), *E2Tmp =3D E2.take();
-    QualType Composite =3D FindCompositePointerType(Loc, E1Tmp, E2Tmp, Non=
StandardCompositeType);
+    QualType Composite =3D FindCompositePointerType(Loc, E1Tmp, E2Tmp,
+                                                  NonStandardCompositeType=
);
     E1 =3D Owned(E1Tmp);
     E2 =3D Owned(E2Tmp);
     return Composite;
@@ -5737,8 +6308,11 @@
   /// type checking for vector binary operators.
   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
                                SourceLocation Loc, bool IsCompAssign);
+  QualType GetSignedVectorType(QualType V);
   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
                                       SourceLocation Loc, bool isRelationa=
l);
+  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
+                                      SourceLocation Loc);
=20
   /// type checking declaration initializers (C99 6.7.8)
   bool CheckForConstantInitializer(Expr *e, QualType t);
@@ -5776,6 +6350,10 @@
                                  Expr *CastExpr, CastKind &CastKind,
                                  ExprValueKind &VK, CXXCastPath &Path);
=20
+  /// \brief Force an expression with unknown-type to an expression of the
+  /// given type.
+  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
+                            =20
   // CheckVectorCast - check type constraints for vectors.
   // Since vectors are an extension, there are no C standard reference for=
 this.
   // We allow casting between vectors and integer datatypes of the same si=
ze.
@@ -5796,11 +6374,17 @@
                                         Expr *CastExpr,
                                         SourceLocation RParenLoc);
=20
+  enum ARCConversionResult { ACR_okay, ACR_unbridged };
+
   /// \brief Checks for invalid conversions and casts between
   /// retainable pointers and other pointer kinds.
-  void CheckObjCARCConversion(SourceRange castRange, QualType castType,=20
-                              Expr *&op, CheckedConversionKind CCK);
-   =20
+  ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
+                                             QualType castType, Expr *&op,
+                                             CheckedConversionKind CCK);
+
+  Expr *stripARCUnbridgedCast(Expr *e);
+  void diagnoseARCUnbridgedCast(Expr *e);
+
   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
                                              QualType ExprType);
=20
@@ -5838,7 +6422,7 @@
   /// \brief If the given expression involves a message send to a method
   /// with a related result type, emit a note describing what happened.
   void EmitRelatedResultTypeNote(const Expr *E);
- =20
+
   /// CheckBooleanCondition - Diagnose problems involving the use of
   /// the given expression as a boolean condition (e.g. in an if
   /// statement).  Also performs the standard function and array
@@ -5851,7 +6435,7 @@
=20
   ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
                                    Expr *SubExpr);
- =20
+
   /// DiagnoseAssignmentAsCondition - Given that an expression is
   /// being used as a boolean condition, warn if it's an assignment.
   void DiagnoseAssignmentAsCondition(Expr *E);
@@ -5875,18 +6459,28 @@
   /// in the global scope.
   bool CheckObjCDeclScope(Decl *D);
=20
-  /// VerifyIntegerConstantExpression - verifies that an expression is an =
ICE,
+  /// VerifyIntegerConstantExpression - Verifies that an expression is an =
ICE,
   /// and reports the appropriate diagnostics. Returns false on success.
   /// Can optionally return the value of the expression.
-  bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result=
 =3D 0);
+  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
+                                             PartialDiagnostic Diag,
+                                             bool AllowFold,
+                                             PartialDiagnostic FoldDiag);
+  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
+                                             PartialDiagnostic Diag,
+                                             bool AllowFold =3D true) {
+    return VerifyIntegerConstantExpression(E, Result, Diag, AllowFold,
+                                           PDiag(0));
+  }
+  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=
 =3D 0);
=20
   /// VerifyBitField - verifies that a bit field expression is an ICE and =
has
   /// the correct width, and that the field type is valid.
   /// Returns false on success.
   /// Can optionally return whether the bit-field is of width 0
-  bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
-                      QualType FieldTy, const Expr *BitWidth,
-                      bool *ZeroWidth =3D 0);
+  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *Field=
Name,
+                            QualType FieldTy, Expr *BitWidth,
+                            bool *ZeroWidth =3D 0);
=20
   enum CUDAFunctionTarget {
     CFT_Device,
@@ -5939,7 +6533,7 @@
     /// \brief Code completion occurs within the condition of an if,
     /// while, switch, or for statement.
     PCC_Condition,
-    /// \brief Code completion occurs within the body of a function on a=20
+    /// \brief Code completion occurs within the body of a function on a
     /// recovery path, where we do not have a specific handle on our posit=
ion
     /// in the grammar.
     PCC_RecoveryInFunction,
@@ -5948,19 +6542,20 @@
     /// \brief Code completion occurs in a parenthesized expression, which
     /// might also be a type cast.
     PCC_ParenthesizedExpression,
-    /// \brief Code completion occurs within a sequence of declaration=20
+    /// \brief Code completion occurs within a sequence of declaration
     /// specifiers within a function, method, or block.
     PCC_LocalDeclarationSpecifiers
   };
=20
+  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Pat=
h);
   void CodeCompleteOrdinaryName(Scope *S,
                                 ParserCompletionContext CompletionContext);
   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
                             bool AllowNonIdentifiers,
                             bool AllowNestedNameSpecifiers);
- =20
+
   struct CodeCompleteExpressionData;
-  void CodeCompleteExpression(Scope *S,=20
+  void CodeCompleteExpression(Scope *S,
                               const CodeCompleteExpressionData &Data);
   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
                                        SourceLocation OpLoc,
@@ -5969,12 +6564,12 @@
   void CodeCompleteTag(Scope *S, unsigned TagSpec);
   void CodeCompleteTypeQualifiers(DeclSpec &DS);
   void CodeCompleteCase(Scope *S);
-  void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs);
+  void CodeCompleteCall(Scope *S, Expr *Fn, llvm::ArrayRef<Expr *> Args);
   void CodeCompleteInitializer(Scope *S, Decl *D);
   void CodeCompleteReturn(Scope *S);
   void CodeCompleteAfterIf(Scope *S);
   void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
- =20
+
   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
                                bool EnteringContext);
   void CodeCompleteUsing(Scope *S);
@@ -5985,7 +6580,9 @@
   void CodeCompleteConstructorInitializer(Decl *Constructor,
                                           CXXCtorInitializer** Initializer=
s,
                                           unsigned NumInitializers);
- =20
+  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
+                                    bool AfterAmpersand);
+
   void CodeCompleteObjCAtDirective(Scope *S);
   void CodeCompleteObjCAtVisibility(Scope *S);
   void CodeCompleteObjCAtStatement(Scope *S);
@@ -5993,7 +6590,7 @@
   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
   void CodeCompleteObjCPropertyGetter(Scope *S);
   void CodeCompleteObjCPropertySetter(Scope *S);
-  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,=20
+  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
                                    bool IsParameter);
   void CodeCompleteObjCMessageReceiver(Scope *S);
   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
@@ -6010,7 +6607,7 @@
                                        unsigned NumSelIdents,
                                        bool AtArgumentExpression,
                                        ObjCInterfaceDecl *Super =3D 0);
-  void CodeCompleteObjCForCollection(Scope *S,=20
+  void CodeCompleteObjCForCollection(Scope *S,
                                      DeclGroupPtrTy IterationVar);
   void CodeCompleteObjCSelector(Scope *S,
                                 IdentifierInfo **SelIdents,
@@ -6035,7 +6632,7 @@
   void CodeCompleteObjCMethodDecl(Scope *S,
                                   bool IsInstanceMethod,
                                   ParsedType ReturnType);
-  void CodeCompleteObjCMethodDeclSelector(Scope *S,=20
+  void CodeCompleteObjCMethodDeclSelector(Scope *S,
                                           bool IsInstanceMethod,
                                           bool AtParameterName,
                                           ParsedType ReturnType,
@@ -6051,6 +6648,7 @@
                                              unsigned Argument);
   void CodeCompleteNaturalLanguage();
   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
+                                   CodeCompletionTUInfo &CCTUInfo,
                   SmallVectorImpl<CodeCompletionResult> &Results);
   //@}
=20
@@ -6061,14 +6659,16 @@
   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
                                                 unsigned ByteNo) const;
=20
-private: =20
+private:
   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
-                        bool isSubscript=3Dfalse, bool AllowOnePastEnd=3Dt=
rue);
+                        const ArraySubscriptExpr *ASE=3D0,
+                        bool AllowOnePastEnd=3Dtrue, bool IndexNegated=3Df=
alse);
   void CheckArrayAccess(const Expr *E);
   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
+  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,=20
+                           Expr **Args, unsigned NumArgs);
   bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall);
=20
-  bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall);
   bool CheckObjCString(Expr *Arg);
=20
   ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCal=
l);
@@ -6092,43 +6692,49 @@
   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
                               llvm::APSInt &Result);
=20
-  bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
+  enum FormatStringType {
+    FST_Scanf,
+    FST_Printf,
+    FST_NSString,
+    FST_Strftime,
+    FST_Strfmon,
+    FST_Kprintf,
+    FST_Unknown
+  };
+  static FormatStringType GetFormatStringType(const FormatAttr *Format);
+  bool SemaCheckStringLiteral(const Expr *E, Expr **Args, unsigned NumArgs,
                               bool HasVAListArg, unsigned format_idx,
-                              unsigned firstDataArg, bool isPrintf);
+                              unsigned firstDataArg, FormatStringType Type,
+                              bool inFunctionCall =3D true);
=20
   void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigForma=
tExpr,
-                         const CallExpr *TheCall, bool HasVAListArg,
+                         Expr **Args, unsigned NumArgs, bool HasVAListArg,
                          unsigned format_idx, unsigned firstDataArg,
-                         bool isPrintf);
+                         FormatStringType Type, bool inFunctionCall);
+
+  void CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall);
+  void CheckFormatArguments(const FormatAttr *Format, Expr **Args,
+                            unsigned NumArgs, bool IsCXXMember,
+                            SourceLocation Loc, SourceRange Range);
+  void CheckFormatArguments(Expr **Args, unsigned NumArgs,
+                            bool HasVAListArg, unsigned format_idx,
+                            unsigned firstDataArg, FormatStringType Type,
+                            SourceLocation Loc, SourceRange range);
=20
   void CheckNonNullArguments(const NonNullAttr *NonNull,
                              const Expr * const *ExprArgs,
                              SourceLocation CallSiteLoc);
=20
-  void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListAr=
g,
-                                 unsigned format_idx, unsigned firstDataAr=
g,
-                                 bool isPrintf);
-
-  /// \brief Enumeration used to describe which of the memory setting or c=
opying
-  /// functions is being checked by \c CheckMemaccessArguments().
-  enum CheckedMemoryFunction {
-    CMF_Memset,
-    CMF_Memcpy,
-    CMF_Memmove,
-    CMF_Memcmp,
-    CMF_Strncpy,
-    CMF_Strncmp,
-    CMF_Strncasecmp,
-    CMF_Strncat,
-    CMF_Strndup
-  };
- =20
-  void CheckMemaccessArguments(const CallExpr *Call, CheckedMemoryFunction=
 CMF,
+  void CheckMemaccessArguments(const CallExpr *Call,
+                               unsigned BId,
                                IdentifierInfo *FnName);
=20
   void CheckStrlcpycatArguments(const CallExpr *Call,
                                 IdentifierInfo *FnName);
=20
+  void CheckStrncatArguments(const CallExpr *Call,
+                             IdentifierInfo *FnName);
+
   void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
                             SourceLocation ReturnLoc);
   void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
@@ -6141,13 +6747,13 @@
   ///
   /// The parser maintains this state here.
   Scope *CurScope;
- =20
+
 protected:
   friend class Parser;
-  friend class InitializationSequence; =20
+  friend class InitializationSequence;
   friend class ASTReader;
   friend class ASTWriter;
- =20
+
 public:
   /// \brief Retrieve the parser's current scope.
   ///
@@ -6158,7 +6764,7 @@
   /// itself and in routines directly invoked from the parser and *never* =
from
   /// template substitution or instantiation.
   Scope *getCurScope() const { return CurScope; }
-   =20
+
   Decl *getObjCDeclContext() const;
=20
   DeclContext *getCurLexicalContext() const {
@@ -6174,9 +6780,12 @@
=20
 public:
   EnterExpressionEvaluationContext(Sema &Actions,
-                                   Sema::ExpressionEvaluationContext NewCo=
ntext)
+                                   Sema::ExpressionEvaluationContext NewCo=
ntext,
+                                   Decl *LambdaContextDecl =3D 0,
+                                   bool IsDecltype =3D false)
     : Actions(Actions) {
-    Actions.PushExpressionEvaluationContext(NewContext);
+    Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
+                                            IsDecltype);
   }
=20
   ~EnterExpressionEvaluationContext() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/SemaConsumer.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/SemaConsumer.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/SemaConsumer.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -24,6 +24,7 @@
   /// clients that read ASTs and then require further semantic
   /// analysis of the entities in those ASTs.
   class SemaConsumer : public ASTConsumer {
+    virtual void anchor();
   public:
     SemaConsumer() {
       ASTConsumer::SemaConsumer =3D true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/SemaDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/SemaDiagnostic.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/SemaDiagnostic.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
   namespace diag {
     enum {
 #define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
-             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY,BRIEF,FULL) E=
NUM,
+             SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
 #define SEMASTART
 #include "clang/Basic/DiagnosticSemaKinds.inc"
 #undef DIAG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/SemaFixItUtils.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/SemaFixItUtils.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/SemaFixItUtils.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
                                  ExprValueKind FromVK);
=20
   /// The list of Hints generated so far.
-  SmallVector<FixItHint, 1> Hints;
+  std::vector<FixItHint> Hints;
=20
   /// The number of Conversions fixed. This can be different from the size
   /// of the Hints vector since we allow multiple FixIts per conversion.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/Template.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/Template.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/Template.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -268,6 +268,50 @@
       Exited =3D true;
     }
=20
+    /// \brief Clone this scope, and all outer scopes, down to the given
+    /// outermost scope.
+    LocalInstantiationScope *cloneScopes(LocalInstantiationScope *Outermos=
t) {
+      if (this =3D=3D Outermost) return this;
+      LocalInstantiationScope *newScope =3D
+        new LocalInstantiationScope(SemaRef, CombineWithOuterScope);
+
+      newScope->Outer =3D 0;
+      if (Outer)
+        newScope->Outer =3D Outer->cloneScopes(Outermost);
+
+      newScope->PartiallySubstitutedPack =3D PartiallySubstitutedPack;
+      newScope->ArgsInPartiallySubstitutedPack =3D ArgsInPartiallySubstitu=
tedPack;
+      newScope->NumArgsInPartiallySubstitutedPack =3D
+        NumArgsInPartiallySubstitutedPack;
+
+      for (LocalDeclsMap::iterator I =3D LocalDecls.begin(), E =3D LocalDe=
cls.end();
+           I !=3D E; ++I) {
+        const Decl *D =3D I->first;
+        llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored =3D
+          newScope->LocalDecls[D];
+        if (I->second.is<Decl *>()) {
+          Stored =3D I->second.get<Decl *>();
+        } else {
+          DeclArgumentPack *OldPack =3D I->second.get<DeclArgumentPack *>(=
);
+          DeclArgumentPack *NewPack =3D new DeclArgumentPack(*OldPack);
+          Stored =3D NewPack;
+          newScope->ArgumentPacks.push_back(NewPack);
+        }
+      }
+      return newScope;
+    }
+
+    /// \brief deletes the given scope, and all otuer scopes, down to the
+    /// given outermost scope.
+    static void deleteScopes(LocalInstantiationScope *Scope,
+                             LocalInstantiationScope *Outermost) {
+      while (Scope && Scope !=3D Outermost) {
+        LocalInstantiationScope *Out =3D Scope->Outer;
+        delete Scope;
+        Scope =3D Out;
+      }
+    }
+
     /// \brief Find the instantiation of the declaration D within the curr=
ent
     /// instantiation scope.
     ///
@@ -314,6 +358,8 @@
     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex;
     DeclContext *Owner;
     const MultiLevelTemplateArgumentList &TemplateArgs;
+    Sema::LateInstantiatedAttrVec* LateAttrs;
+    LocalInstantiationScope *StartingScope;
=20
     /// \brief A list of out-of-line class template partial
     /// specializations that will need to be instantiated after the
@@ -326,7 +372,7 @@
     TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
                              const MultiLevelTemplateArgumentList &Templat=
eArgs)
       : SemaRef(SemaRef), SubstIndex(SemaRef, -1), Owner(Owner),=20
-        TemplateArgs(TemplateArgs) { }
+        TemplateArgs(TemplateArgs), LateAttrs(0), StartingScope(0) { }
=20
     // FIXME: Once we get closer to completion, replace these manually-wri=
tten
     // declarations with automatically-generated ones from
@@ -382,6 +428,21 @@
       return 0;
     }
    =20
+    // Enable late instantiation of attributes.  Late instantiated attribu=
tes
+    // will be stored in LA.
+    void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *L=
A) {
+      LateAttrs =3D LA;
+      StartingScope =3D SemaRef.CurrentInstantiationScope;
+    }
+
+    // Disable late instantiation of attributes.
+    void disableLateAttributeInstantiation() {
+      LateAttrs =3D 0;
+      StartingScope =3D 0;
+    }
+
+    LocalInstantiationScope *getStartingScope() const { return StartingSco=
pe; }
+
     typedef=20
       SmallVectorImpl<std::pair<ClassTemplateDecl *,
                                      ClassTemplatePartialSpecializationDec=
l *> >
@@ -423,6 +484,7 @@
     InstantiateClassTemplatePartialSpecialization(
                                               ClassTemplateDecl *ClassTemp=
late,
                            ClassTemplatePartialSpecializationDecl *Partial=
Spec);
+    void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern);
   }; =20
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/TemplateDeduction.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/TemplateDeduction.h	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/TemplateDeduction.h	=
Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 class TemplateArgumentList;
=20
 namespace sema {
- =20
+
 /// \brief Provides information about an attempted template argument
 /// deduction, whose success or failure was described by a
 /// TemplateDeductionResult value.
@@ -39,10 +39,10 @@
   /// deduction is occurring.
   SourceLocation Loc;
=20
-  /// \brief Warnings (and follow-on notes) that were suppressed due to=20
+  /// \brief Warnings (and follow-on notes) that were suppressed due to
   /// SFINAE while performing template argument deduction.
   SmallVector<PartialDiagnosticAt, 4> SuppressedDiagnostics;
- =20
+
   // do not implement these
   TemplateDeductionInfo(const TemplateDeductionInfo&);
   TemplateDeductionInfo &operator=3D(const TemplateDeductionInfo&);
@@ -75,23 +75,24 @@
     Deduced =3D NewDeduced;
   }
=20
-  /// \brief Add a new diagnostic to the set of diagnostics=20
-  void addSuppressedDiagnostic(SourceLocation Loc, const PartialDiagnostic=
 &PD) {
+  /// \brief Add a new diagnostic to the set of diagnostics
+  void addSuppressedDiagnostic(SourceLocation Loc,
+                               const PartialDiagnostic &PD) {
     SuppressedDiagnostics.push_back(std::make_pair(Loc, PD));
   }
- =20
+
   /// \brief Iterator over the set of suppressed diagnostics.
-  typedef SmallVectorImpl<PartialDiagnosticAt>::const_iterator=20
+  typedef SmallVectorImpl<PartialDiagnosticAt>::const_iterator
     diag_iterator;
- =20
+
   /// \brief Returns an iterator at the beginning of the sequence of suppr=
essed
   /// diagnostics.
   diag_iterator diag_begin() const { return SuppressedDiagnostics.begin();=
 }
- =20
+
   /// \brief Returns an iterator at the end of the sequence of suppressed
   /// diagnostics.
   diag_iterator diag_end() const { return SuppressedDiagnostics.end(); }
- =20
+
   /// \brief The template parameter to which a template argument
   /// deduction failure refers.
   ///
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Sema/TypoCorrection.h
--- a/head/contrib/llvm/tools/clang/include/clang/Sema/TypoCorrection.h	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Sema/TypoCorrection.h	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -23,32 +23,46 @@
 /// @brief Simple class containing the result of Sema::CorrectTypo
 class TypoCorrection {
 public:
+  // "Distance" for unusable corrections
+  static const unsigned InvalidDistance =3D ~0U;
+  // The largest distance still considered valid (larger edit distances are
+  // mapped to InvalidDistance by getEditDistance).
+  static const unsigned MaximumDistance =3D 10000U;
+
+  // Relative weightings of the "edit distance" components. The higher the
+  // weight, the more of a penalty to fitness the component will give (hig=
her
+  // weights mean greater contribution to the total edit distance, with the
+  // best correction candidates having the lowest edit distance).
+  static const unsigned CharDistanceWeight =3D 100U;
+  static const unsigned QualifierDistanceWeight =3D 110U;
+  static const unsigned CallbackDistanceWeight =3D 150U;
+
   TypoCorrection(const DeclarationName &Name, NamedDecl *NameDecl,
-                 NestedNameSpecifier *NNS=3D0, unsigned distance=3D0)
-      : CorrectionName(Name),
-        CorrectionNameSpec(NNS),
-        EditDistance(distance) {
+                 NestedNameSpecifier *NNS=3D0, unsigned CharDistance=3D0,
+                 unsigned QualifierDistance=3D0)
+      : CorrectionName(Name), CorrectionNameSpec(NNS),
+      CharDistance(CharDistance), QualifierDistance(QualifierDistance),
+      CallbackDistance(0) {
     if (NameDecl)
       CorrectionDecls.push_back(NameDecl);
   }
=20
   TypoCorrection(NamedDecl *Name, NestedNameSpecifier *NNS=3D0,
-                 unsigned distance=3D0)
-      : CorrectionName(Name->getDeclName()),
-        CorrectionNameSpec(NNS),
-        EditDistance(distance) {
+                 unsigned CharDistance=3D0)
+      : CorrectionName(Name->getDeclName()), CorrectionNameSpec(NNS),
+      CharDistance(CharDistance), QualifierDistance(0), CallbackDistance(0=
) {
     if (Name)
       CorrectionDecls.push_back(Name);
   }
=20
   TypoCorrection(DeclarationName Name, NestedNameSpecifier *NNS=3D0,
-                 unsigned distance=3D0)
-      : CorrectionName(Name),
-        CorrectionNameSpec(NNS),
-        EditDistance(distance) {}
+                 unsigned CharDistance=3D0)
+      : CorrectionName(Name), CorrectionNameSpec(NNS),
+      CharDistance(CharDistance), QualifierDistance(0), CallbackDistance(0=
) {}
=20
   TypoCorrection()
-      : CorrectionNameSpec(0), EditDistance(0) {}
+      : CorrectionNameSpec(0), CharDistance(0), QualifierDistance(0),
+      CallbackDistance(0) {}
=20
   /// \brief Gets the DeclarationName of the typo correction
   DeclarationName getCorrection() const { return CorrectionName; }
@@ -64,8 +78,41 @@
     CorrectionNameSpec =3D NNS;
   }
=20
-  /// \brief Gets the "edit distance" of the typo correction from the typo
-  unsigned getEditDistance() const { return EditDistance; }
+  void setQualifierDistance(unsigned ED) {
+    QualifierDistance =3D ED;
+  }
+
+  void setCallbackDistance(unsigned ED) {
+    CallbackDistance =3D ED;
+  }
+
+  // Convert the given weighted edit distance to a roughly equivalent numb=
er of
+  // single-character edits (typically for comparison to the length of the
+  // string being edited).
+  static unsigned NormalizeEditDistance(unsigned ED) {
+    if (ED > MaximumDistance)
+      return InvalidDistance;
+    return (ED + CharDistanceWeight / 2) / CharDistanceWeight;
+  }
+
+  /// \brief Gets the "edit distance" of the typo correction from the typo.
+  /// If Normalized is true, scale the distance down by the CharDistanceWe=
ight
+  /// to return the edit distance in terms of single-character edits.
+  unsigned getEditDistance(bool Normalized =3D true) const {
+    if (CharDistance > MaximumDistance || QualifierDistance > MaximumDista=
nce ||
+        CallbackDistance > MaximumDistance)
+      return InvalidDistance;
+    unsigned ED =3D
+        CharDistance * CharDistanceWeight +
+        QualifierDistance * QualifierDistanceWeight +
+        CallbackDistance * CallbackDistanceWeight;
+    if (ED > MaximumDistance)
+      return InvalidDistance;
+    // Half the CharDistanceWeight is added to ED to simulate rounding sin=
ce
+    // integer division truncates the value (i.e. round-to-nearest-int ins=
tead
+    // of round-to-zero).
+    return Normalized ? NormalizeEditDistance(ED) : ED;
+  }
=20
   /// \brief Gets the pointer to the declaration of the typo correction
   NamedDecl* getCorrectionDecl() const {
@@ -110,6 +157,12 @@
         CorrectionDecls.front() =3D=3D 0;
   }
=20
+  // Check if this TypoCorrection is the given keyword.
+  template<std::size_t StrLen>
+  bool isKeyword(const char (&Str)[StrLen]) const {
+    return isKeyword() && getCorrectionAsIdentifierInfo()->isStr(Str);
+  }
+
   // Returns true if the correction either is a keyword or has a known dec=
l.
   bool isResolved() const { return !CorrectionDecls.empty(); }
=20
@@ -122,6 +175,11 @@
     return isKeyword() ? CorrectionDecls.end() : CorrectionDecls.begin();
   }
   decl_iterator end() { return CorrectionDecls.end(); }
+  typedef llvm::SmallVector<NamedDecl*, 1>::const_iterator const_decl_iter=
ator;
+  const_decl_iterator begin() const {
+    return isKeyword() ? CorrectionDecls.end() : CorrectionDecls.begin();
+  }
+  const_decl_iterator end() const { return CorrectionDecls.end(); }
=20
 private:
   bool hasCorrectionDecl() const {
@@ -132,7 +190,65 @@
   DeclarationName CorrectionName;
   NestedNameSpecifier *CorrectionNameSpec;
   llvm::SmallVector<NamedDecl*, 1> CorrectionDecls;
-  unsigned EditDistance;
+  unsigned CharDistance;
+  unsigned QualifierDistance;
+  unsigned CallbackDistance;
+};
+
+/// @brief Base class for callback objects used by Sema::CorrectTypo to ch=
eck
+/// the validity of a potential typo correction.
+class CorrectionCandidateCallback {
+ public:
+  static const unsigned InvalidDistance =3D TypoCorrection::InvalidDistanc=
e;
+
+  CorrectionCandidateCallback()
+      : WantTypeSpecifiers(true), WantExpressionKeywords(true),
+        WantCXXNamedCasts(true), WantRemainingKeywords(true),
+        WantObjCSuper(false),
+        IsObjCIvarLookup(false) {}
+
+  virtual ~CorrectionCandidateCallback() {}
+
+  /// \brief Simple predicate used by the default RankCandidate to
+  /// determine whether to return an edit distance of 0 or InvalidDistance.
+  /// This can be overrided by validators that only need to determine if a
+  /// candidate is viable, without ranking potentially viable candidates.
+  /// Only ValidateCandidate or RankCandidate need to be overriden by a
+  /// callback wishing to check the viability of correction candidates.
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    return true;
+  }
+
+  /// \brief Method used by Sema::CorrectTypo to assign an "edit distance"=
 rank
+  /// to a candidate (where a lower value represents a better candidate), =
or
+  /// returning InvalidDistance if the candidate is not at all viable. For
+  /// validation callbacks that only need to determine if a candidate is v=
iable,
+  /// the default RankCandidate returns either 0 or InvalidDistance depend=
ing
+  /// whether ValidateCandidate returns true or false.
+  virtual unsigned RankCandidate(const TypoCorrection &candidate) {
+    return ValidateCandidate(candidate) ? 0 : InvalidDistance;
+  }
+
+  // Flags for context-dependent keywords.
+  // TODO: Expand these to apply to non-keywords or possibly remove them.
+  bool WantTypeSpecifiers;
+  bool WantExpressionKeywords;
+  bool WantCXXNamedCasts;
+  bool WantRemainingKeywords;
+  bool WantObjCSuper;
+  // Temporary hack for the one case where a CorrectTypoContext enum is us=
ed
+  // when looking up results.
+  bool IsObjCIvarLookup;
+};
+
+/// @brief Simple template class for restricting typo correction candidates
+/// to ones having a single Decl* of the given type.
+template <class C>
+class DeclFilterCCC : public CorrectionCandidateCallback {
+ public:
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    return candidate.getCorrectionDeclAs<C>();
+  }
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Serialization/ASTBitCodes.h
--- a/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTBitCodes=
.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTBitCodes=
.h	Tue Apr 17 11:51:51 2012 +0300
@@ -127,7 +127,7 @@
     /// \brief The number of predefined identifier IDs.
     const unsigned int NUM_PREDEF_IDENT_IDS =3D 1;
    =20
-    /// \brief An ID number that refers to an ObjC selctor in an AST file.
+    /// \brief An ID number that refers to an ObjC selector in an AST file.
     typedef uint32_t SelectorID;
=20
     /// \brief The number of predefined selector IDs.
@@ -141,6 +141,12 @@
     /// preprocessing record.
     typedef uint32_t PreprocessedEntityID;
=20
+    /// \brief An ID number that refers to a submodule in a module file.
+    typedef uint32_t SubmoduleID;
+   =20
+    /// \brief The number of predefined submodule IDs.
+    const unsigned int NUM_PREDEF_SUBMODULE_IDS =3D 1;
+
     /// \brief Source range/offset of a preprocessed entity.
     struct PPEntityOffset {
       /// \brief Raw source location of beginning of range.
@@ -156,6 +162,22 @@
           BitOffset(BitOffset) { }
     };
=20
+    /// \brief Source range/offset of a preprocessed entity.
+    struct DeclOffset {
+      /// \brief Raw source location.
+      unsigned Loc;
+      /// \brief Offset in the AST file.
+      uint32_t BitOffset;
+
+      DeclOffset() : Loc(0), BitOffset(0) { }
+      DeclOffset(SourceLocation Loc, uint32_t BitOffset)
+        : Loc(Loc.getRawEncoding()),
+          BitOffset(BitOffset) { }
+      void setLocation(SourceLocation L) {
+        Loc =3D L.getRawEncoding();
+      }
+    };
+
     /// \brief The number of predefined preprocessed entity IDs.
     const unsigned int NUM_PREDEF_PP_ENTITY_IDS =3D 1;
=20
@@ -182,7 +204,10 @@
       DECL_UPDATES_BLOCK_ID,
      =20
       /// \brief The block containing the detailed preprocessing record.
-      PREPROCESSOR_DETAIL_BLOCK_ID
+      PREPROCESSOR_DETAIL_BLOCK_ID,
+     =20
+      /// \brief The block containing the submodule structure.
+      SUBMODULE_BLOCK_ID
     };
=20
     /// \brief Record types that occur within the AST block itself.
@@ -341,10 +366,11 @@
       /// \brief Record code for an update to the TU's lexically contained
       /// declarations.
       TU_UPDATE_LEXICAL =3D 28,
-
-      /// \brief Record code for an update to first decls pointing to the
-      /// latest redeclarations.
-      REDECLS_UPDATE_LATEST =3D 29,
+     =20
+      /// \brief Record code for the array describing the locations (in the
+      /// LOCAL_REDECLARATIONS record) of the redeclaration chains, indexe=
d by
+      /// the first known ID.
+      LOCAL_REDECLARATIONS_MAP =3D 29,
=20
       /// \brief Record code for declarations that Sema keeps references o=
f.
       SEMA_DECL_REFS =3D 30,
@@ -418,9 +444,32 @@
       /// which stores information about #line directives.
       SOURCE_MANAGER_LINE_TABLE =3D 48,
=20
-      /// \brief Record code for ObjC categories in a module that are chai=
ned to
-      /// an interface.
-      OBJC_CHAINED_CATEGORIES
+      /// \brief Record code for map of Objective-C class definition IDs t=
o the=20
+      /// ObjC categories in a module that are attached to that class.
+      OBJC_CATEGORIES_MAP =3D 49,
+
+      /// \brief Record code for a file sorted array of DeclIDs in a modul=
e.
+      FILE_SORTED_DECLS =3D 50,
+     =20
+      /// \brief Record code for an array of all of the (sub)modules that =
were
+      /// imported by the AST file.
+      IMPORTED_MODULES =3D 51,
+     =20
+      /// \brief Record code for the set of merged declarations in an AST =
file.
+      MERGED_DECLARATIONS =3D 52,
+     =20
+      /// \brief Record code for the array of redeclaration chains.
+      ///
+      /// This array can only be interpreted properly using the local=20
+      /// redeclarations map.
+      LOCAL_REDECLARATIONS =3D 53,
+     =20
+      /// \brief Record code for the array of Objective-C categories (incl=
uding
+      /// extensions).
+      ///
+      /// This array can only be interpreted properly using the Objective-C
+      /// categories map.
+      OBJC_CATEGORIES
     };
=20
     /// \brief Record types used within a source manager block.
@@ -433,7 +482,8 @@
       SM_SLOC_BUFFER_ENTRY =3D 2,
       /// \brief Describes a blob that contains the data for a buffer
       /// entry. This kind of record always directly follows a
-      /// SM_SLOC_BUFFER_ENTRY record.
+      /// SM_SLOC_BUFFER_ENTRY record or a SM_SLOC_FILE_ENTRY with an
+      /// overridden buffer.
       SM_SLOC_BUFFER_BLOB =3D 3,
       /// \brief Describes a source location entry (SLocEntry) for a
       /// macro expansion.
@@ -472,6 +522,30 @@
       PPD_INCLUSION_DIRECTIVE =3D 2
     };
    =20
+    /// \brief Record types used within a submodule description block.
+    enum SubmoduleRecordTypes {
+      /// \brief Metadata for submodules as a whole.
+      SUBMODULE_METADATA =3D 0,
+      /// \brief Defines the major attributes of a submodule, including its
+      /// name and parent.
+      SUBMODULE_DEFINITION =3D 1,
+      /// \brief Specifies the umbrella header used to create this module,
+      /// if any.
+      SUBMODULE_UMBRELLA_HEADER =3D 2,
+      /// \brief Specifies a header that falls into this (sub)module.
+      SUBMODULE_HEADER =3D 3,
+      /// \brief Specifies an umbrella directory.
+      SUBMODULE_UMBRELLA_DIR =3D 4,
+      /// \brief Specifies the submodules that are imported by this=20
+      /// submodule.
+      SUBMODULE_IMPORTS =3D 5,
+      /// \brief Specifies the submodules that are re-exported from this=20
+      /// submodule.
+      SUBMODULE_EXPORTS =3D 6,
+      /// \brief Specifies a required feature.
+      SUBMODULE_REQUIRES =3D 7
+    };
+   =20
     /// \defgroup ASTAST AST file AST constants
     ///
     /// The constants in this group describe various components of the
@@ -554,7 +628,11 @@
       /// \brief The "auto &&" deduction type.
       PREDEF_TYPE_AUTO_RREF_DEDUCT =3D 32,
       /// \brief The OpenCL 'half' / ARM NEON __fp16 type.
-      PREDEF_TYPE_HALF_ID       =3D 33
+      PREDEF_TYPE_HALF_ID       =3D 33,
+      /// \brief ARC's unbridged-cast placeholder type.
+      PREDEF_TYPE_ARC_UNBRIDGED_CAST =3D 34,
+      /// \brief The pseudo-object placeholder type.
+      PREDEF_TYPE_PSEUDO_OBJECT =3D 35
     };
=20
     /// \brief The number of predefined type IDs that are reserved for
@@ -662,28 +740,26 @@
     enum SpecialTypeIDs {
       /// \brief __builtin_va_list
       SPECIAL_TYPE_BUILTIN_VA_LIST             =3D 0,
-      /// \brief Objective-C Protocol type
-      SPECIAL_TYPE_OBJC_PROTOCOL               =3D 1,
       /// \brief CFConstantString type
-      SPECIAL_TYPE_CF_CONSTANT_STRING          =3D 2,
+      SPECIAL_TYPE_CF_CONSTANT_STRING          =3D 1,
       /// \brief C FILE typedef type
-      SPECIAL_TYPE_FILE                        =3D 3,
+      SPECIAL_TYPE_FILE                        =3D 2,
       /// \brief C jmp_buf typedef type
-      SPECIAL_TYPE_jmp_buf                     =3D 4,
+      SPECIAL_TYPE_JMP_BUF                     =3D 3,
       /// \brief C sigjmp_buf typedef type
-      SPECIAL_TYPE_sigjmp_buf                  =3D 5,
+      SPECIAL_TYPE_SIGJMP_BUF                  =3D 4,
       /// \brief Objective-C "id" redefinition type
-      SPECIAL_TYPE_OBJC_ID_REDEFINITION        =3D 6,
+      SPECIAL_TYPE_OBJC_ID_REDEFINITION        =3D 5,
       /// \brief Objective-C "Class" redefinition type
-      SPECIAL_TYPE_OBJC_CLASS_REDEFINITION     =3D 7,
+      SPECIAL_TYPE_OBJC_CLASS_REDEFINITION     =3D 6,
       /// \brief Objective-C "SEL" redefinition type
-      SPECIAL_TYPE_OBJC_SEL_REDEFINITION       =3D 8,
+      SPECIAL_TYPE_OBJC_SEL_REDEFINITION       =3D 7,
       /// \brief C ucontext_t typedef type
-      SPECIAL_TYPE_UCONTEXT_T                  =3D 9
+      SPECIAL_TYPE_UCONTEXT_T                  =3D 8
     };
    =20
     /// \brief The number of special type IDs.
-    const unsigned NumSpecialTypeIDs =3D 0;
+    const unsigned NumSpecialTypeIDs =3D 9;
=20
     /// \brief Predefined declaration IDs.
     ///
@@ -706,22 +782,25 @@
      =20
       /// \brief The Objective-C 'Class' type.
       PREDEF_DECL_OBJC_CLASS_ID =3D 4,
+           =20
+      /// \brief The Objective-C 'Protocol' type.
+      PREDEF_DECL_OBJC_PROTOCOL_ID =3D 5,
      =20
       /// \brief The signed 128-bit integer type.
-      PREDEF_DECL_INT_128_ID =3D 5,
+      PREDEF_DECL_INT_128_ID =3D 6,
=20
       /// \brief The unsigned 128-bit integer type.
-      PREDEF_DECL_UNSIGNED_INT_128_ID =3D 6,
+      PREDEF_DECL_UNSIGNED_INT_128_ID =3D 7,
      =20
       /// \brief The internal 'instancetype' typedef.
-      PREDEF_DECL_OBJC_INSTANCETYPE_ID =3D 7
+      PREDEF_DECL_OBJC_INSTANCETYPE_ID =3D 8
     };
=20
     /// \brief The number of declaration IDs that are predefined.
     ///
     /// For more information about predefined declarations, see the
     /// \c PredefinedDeclIDs type and the PREDEF_DECL_*_ID constants.
-    const unsigned int NUM_PREDEF_DECL_IDS =3D 8;
+    const unsigned int NUM_PREDEF_DECL_IDS =3D 9;
    =20
     /// \brief Record codes for each kind of declaration.
     ///
@@ -752,10 +831,6 @@
       DECL_OBJC_IVAR,
       /// \brief A ObjCAtDefsFieldDecl record.
       DECL_OBJC_AT_DEFS_FIELD,
-      /// \brief A ObjCClassDecl record.
-      DECL_OBJC_CLASS,
-      /// \brief A ObjCForwardProtocolDecl record.
-      DECL_OBJC_FORWARD_PROTOCOL,
       /// \brief A ObjCCategoryDecl record.
       DECL_OBJC_CATEGORY,
       /// \brief A ObjCCategoryImplDecl record.
@@ -859,7 +934,9 @@
       DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK,
       /// \brief A ClassScopeFunctionSpecializationDecl record a class sco=
pe
       /// function specialization. (Microsoft extension).
-      DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION
+      DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION,
+      /// \brief An ImportDecl recording a module import.
+      DECL_IMPORT
     };
=20
     /// \brief Record codes for each kind of statement or expression.
@@ -875,6 +952,8 @@
       STMT_STOP =3D 100,
       /// \brief A NULL expression.
       STMT_NULL_PTR,
+      /// \brief A reference to a previously [de]serialized Stmt record.
+      STMT_REF_PTR,
       /// \brief A NullStmt record.
       STMT_NULL,
       /// \brief A CompoundStmt record.
@@ -973,10 +1052,10 @@
       EXPR_SHUFFLE_VECTOR,
       /// \brief BlockExpr
       EXPR_BLOCK,
-      /// \brief A BlockDeclRef record.
-      EXPR_BLOCK_DECL_REF,
       /// \brief A GenericSelectionExpr record.
       EXPR_GENERIC_SELECTION,
+      /// \brief A PseudoObjectExpr record.
+      EXPR_PSEUDO_OBJECT,
       /// \brief An AtomicExpr record.
       EXPR_ATOMIC,
=20
@@ -984,6 +1063,12 @@
=20
       /// \brief An ObjCStringLiteral record.
       EXPR_OBJC_STRING_LITERAL,
+
+      EXPR_OBJC_NUMERIC_LITERAL,
+      EXPR_OBJC_ARRAY_LITERAL,
+      EXPR_OBJC_DICTIONARY_LITERAL,
+
+   =20
       /// \brief An ObjCEncodeExpr record.
       EXPR_OBJC_ENCODE,
       /// \brief An ObjCSelectorExpr record.
@@ -994,6 +1079,8 @@
       EXPR_OBJC_IVAR_REF_EXPR,
       /// \brief An ObjCPropertyRefExpr record.
       EXPR_OBJC_PROPERTY_REF_EXPR,
+      /// \brief An ObjCSubscriptRefExpr record.
+      EXPR_OBJC_SUBSCRIPT_REF_EXPR,
       /// \brief UNUSED
       EXPR_OBJC_KVC_REF_EXPR,
       /// \brief An ObjCMessageExpr record.
@@ -1017,6 +1104,8 @@
       STMT_OBJC_AT_THROW,
       /// \brief An ObjCAutoreleasePoolStmt record.
       STMT_OBJC_AUTORELEASE_POOL,
+      /// \brief A ObjCBoolLiteralExpr record.
+      EXPR_OBJC_BOOL_LITERAL,
=20
       // C++
      =20
@@ -1045,6 +1134,8 @@
       EXPR_CXX_CONST_CAST,
       /// \brief A CXXFunctionalCastExpr record.
       EXPR_CXX_FUNCTIONAL_CAST,
+      /// \brief A UserDefinedLiteral record.
+      EXPR_USER_DEFINED_LITERAL,
       /// \brief A CXXBoolLiteralExpr record.
       EXPR_CXX_BOOL_LITERAL,
       EXPR_CXX_NULL_PTR_LITERAL,  // CXXNullPtrLiteralExpr
@@ -1075,6 +1166,7 @@
       EXPR_OPAQUE_VALUE,          // OpaqueValueExpr
       EXPR_BINARY_CONDITIONAL_OPERATOR,  // BinaryConditionalOperator
       EXPR_BINARY_TYPE_TRAIT,     // BinaryTypeTraitExpr
+      EXPR_TYPE_TRAIT,            // TypeTraitExpr
       EXPR_ARRAY_TYPE_TRAIT,      // ArrayTypeTraitIntExpr
      =20
       EXPR_PACK_EXPANSION,        // PackExpansionExpr
@@ -1097,7 +1189,10 @@
       STMT_SEH_TRY,               // SEHTryStmt
      =20
       // ARC
-      EXPR_OBJC_BRIDGED_CAST       // ObjCBridgedCastExpr
+      EXPR_OBJC_BRIDGED_CAST,     // ObjCBridgedCastExpr
+     =20
+      STMT_MS_DEPENDENT_EXISTS,   // MSDependentExistsStmt
+      EXPR_LAMBDA                 // LambdaExpr
     };
=20
     /// \brief The kinds of designators that can occur in a
@@ -1123,6 +1218,58 @@
       CTOR_INITIALIZER_INDIRECT_MEMBER
     };
=20
+    /// \brief Describes the redeclarations of a declaration.
+    struct LocalRedeclarationsInfo {
+      DeclID FirstID;      // The ID of the first declaration
+      unsigned Offset;     // Offset into the array of redeclaration chain=
s.
+     =20
+      friend bool operator<(const LocalRedeclarationsInfo &X,
+                            const LocalRedeclarationsInfo &Y) {
+        return X.FirstID < Y.FirstID;
+      }
+     =20
+      friend bool operator>(const LocalRedeclarationsInfo &X,
+                            const LocalRedeclarationsInfo &Y) {
+        return X.FirstID > Y.FirstID;
+      }
+     =20
+      friend bool operator<=3D(const LocalRedeclarationsInfo &X,
+                             const LocalRedeclarationsInfo &Y) {
+        return X.FirstID <=3D Y.FirstID;
+      }
+     =20
+      friend bool operator>=3D(const LocalRedeclarationsInfo &X,
+                             const LocalRedeclarationsInfo &Y) {
+        return X.FirstID >=3D Y.FirstID;
+      }
+    };
+
+    /// \brief Describes the categories of an Objective-C class.
+    struct ObjCCategoriesInfo {
+      DeclID DefinitionID; // The ID of the definition
+      unsigned Offset;     // Offset into the array of category lists.
+     =20
+      friend bool operator<(const ObjCCategoriesInfo &X,
+                            const ObjCCategoriesInfo &Y) {
+        return X.DefinitionID < Y.DefinitionID;
+      }
+     =20
+      friend bool operator>(const ObjCCategoriesInfo &X,
+                            const ObjCCategoriesInfo &Y) {
+        return X.DefinitionID > Y.DefinitionID;
+      }
+     =20
+      friend bool operator<=3D(const ObjCCategoriesInfo &X,
+                             const ObjCCategoriesInfo &Y) {
+        return X.DefinitionID <=3D Y.DefinitionID;
+      }
+     =20
+      friend bool operator>=3D(const ObjCCategoriesInfo &X,
+                             const ObjCCategoriesInfo &Y) {
+        return X.DefinitionID >=3D Y.DefinitionID;
+      }
+    };
+
     /// @}
   }
 } // end namespace clang
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Serialization/ASTDeserializationListener.h
--- a/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTDeserial=
izationListener.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTDeserial=
izationListener.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,6 +23,7 @@
 class ASTReader;
 class QualType;
 class MacroDefinition;
+class Module;
  =20
 class ASTDeserializationListener {
 protected:
@@ -47,6 +48,11 @@
   /// \brief A macro definition was read from the AST file.
   virtual void MacroDefinitionRead(serialization::PreprocessedEntityID,=20
                                    MacroDefinition *MD) { }
+  /// \brief A macro definition that had previously been deserialized=20
+  /// (and removed via IdentifierRead) has now been made visible.
+  virtual void MacroVisible(IdentifierInfo *II) { }
+  /// \brief A module definition was read from the AST file.
+  virtual void ModuleRead(serialization::SubmoduleID ID, Module *Mod) { }
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Serialization/ASTReader.h
--- a/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -34,6 +34,8 @@
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/APSInt.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/DenseSet.h"
@@ -162,16 +164,16 @@
   void Error(const char *Msg);
 };
=20
-namespace serialization {   =20
+namespace serialization {
=20
 class ReadMethodPoolVisitor;
- =20
+
 namespace reader {
   class ASTIdentifierLookupTrait;
 }
- =20
+
 } // end namespace serialization
- =20
+
 /// \brief Reads an AST files chain containing the contents of a translati=
on
 /// unit.
 ///
@@ -191,7 +193,7 @@
     public ExternalSemaSource,
     public IdentifierInfoLookup,
     public ExternalIdentifierLookup,
-    public ExternalSLocEntrySource=20
+    public ExternalSLocEntrySource
 {
 public:
   enum ASTReadResult { Success, Failure, IgnorePCH };
@@ -205,18 +207,18 @@
   friend class ASTWriter;
   friend class ASTUnit; // ASTUnit needs to remap source locations.
   friend class serialization::ReadMethodPoolVisitor;
- =20
-  typedef serialization::Module Module;
+
+  typedef serialization::ModuleFile ModuleFile;
   typedef serialization::ModuleKind ModuleKind;
   typedef serialization::ModuleManager ModuleManager;
- =20
+
   typedef ModuleManager::ModuleIterator ModuleIterator;
   typedef ModuleManager::ModuleConstIterator ModuleConstIterator;
   typedef ModuleManager::ModuleReverseIterator ModuleReverseIterator;
=20
 private:
   /// \brief The receiver of some callbacks invoked by ASTReader.
-  llvm::OwningPtr<ASTReaderListener> Listener;
+  OwningPtr<ASTReaderListener> Listener;
=20
   /// \brief The receiver of deserialization events.
   ASTDeserializationListener *DeserializationListener;
@@ -224,7 +226,7 @@
   SourceManager &SourceMgr;
   FileManager &FileMgr;
   DiagnosticsEngine &Diags;
- =20
+
   /// \brief The semantic analysis object that will be processing the
   /// AST files and the translation unit that uses it.
   Sema *SemaObj;
@@ -234,7 +236,7 @@
=20
   /// \brief The AST context into which we'll read the AST files.
   ASTContext &Context;
-     =20
+
   /// \brief The AST consumer.
   ASTConsumer *Consumer;
=20
@@ -243,24 +245,24 @@
=20
   /// \brief A map of global bit offsets to the module that stores entities
   /// at those bit offsets.
-  ContinuousRangeMap<uint64_t, Module*, 4> GlobalBitOffsetsMap;
+  ContinuousRangeMap<uint64_t, ModuleFile*, 4> GlobalBitOffsetsMap;
=20
   /// \brief A map of negated SLocEntryIDs to the modules containing them.
-  ContinuousRangeMap<unsigned, Module*, 64> GlobalSLocEntryMap;
+  ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocEntryMap;
=20
-  typedef ContinuousRangeMap<unsigned, Module*, 64> GlobalSLocOffsetMapTyp=
e;
- =20
+  typedef ContinuousRangeMap<unsigned, ModuleFile*, 64> GlobalSLocOffsetMa=
pType;
+
   /// \brief A map of reversed (SourceManager::MaxLoadedOffset - SLocOffse=
t)
   /// SourceLocation offsets to the modules containing them.
   GlobalSLocOffsetMapType GlobalSLocOffsetMap;
- =20
+
   /// \brief Types that have already been loaded from the chain.
   ///
   /// When the pointer at index I is non-NULL, the type with
   /// ID =3D (I + 1) << FastQual::Width has already been loaded
   std::vector<QualType> TypesLoaded;
=20
-  typedef ContinuousRangeMap<serialization::TypeID, Module *, 4>
+  typedef ContinuousRangeMap<serialization::TypeID, ModuleFile *, 4>
     GlobalTypeMapType;
=20
   /// \brief Mapping from global type IDs to the module in which the
@@ -274,60 +276,67 @@
   /// =3D I + 1 has already been loaded.
   std::vector<Decl *> DeclsLoaded;
=20
-  typedef ContinuousRangeMap<serialization::DeclID, Module *, 4>=20
+  typedef ContinuousRangeMap<serialization::DeclID, ModuleFile *, 4>
     GlobalDeclMapType;
- =20
+
   /// \brief Mapping from global declaration IDs to the module in which the
   /// declaration resides.
   GlobalDeclMapType GlobalDeclMap;
- =20
-  typedef std::pair<Module *, uint64_t> FileOffset;
+
+  typedef std::pair<ModuleFile *, uint64_t> FileOffset;
   typedef SmallVector<FileOffset, 2> FileOffsetsTy;
   typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
       DeclUpdateOffsetsMap;
- =20
+
   /// \brief Declarations that have modifications residing in a later file
   /// in the chain.
   DeclUpdateOffsetsMap DeclUpdateOffsets;
=20
-  typedef llvm::DenseMap<serialization::DeclID,
-                         std::pair<Module *, uint64_t> >
+  struct ReplacedDeclInfo {
+    ModuleFile *Mod;
+    uint64_t Offset;
+    unsigned RawLoc;
+
+    ReplacedDeclInfo() : Mod(0), Offset(0), RawLoc(0) {}
+    ReplacedDeclInfo(ModuleFile *Mod, uint64_t Offset, unsigned RawLoc)
+      : Mod(Mod), Offset(Offset), RawLoc(RawLoc) {}
+  };
+
+  typedef llvm::DenseMap<serialization::DeclID, ReplacedDeclInfo>
       DeclReplacementMap;
   /// \brief Declarations that have been replaced in a later file in the c=
hain.
   DeclReplacementMap ReplacedDecls;
=20
+  struct FileDeclsInfo {
+    ModuleFile *Mod;
+    ArrayRef<serialization::LocalDeclID> Decls;
+
+    FileDeclsInfo() : Mod(0) {}
+    FileDeclsInfo(ModuleFile *Mod, ArrayRef<serialization::LocalDeclID> De=
cls)
+      : Mod(Mod), Decls(Decls) {}
+  };
+
+  /// \brief Map from a FileID to the file-level declarations that it cont=
ains.
+  llvm::DenseMap<FileID, FileDeclsInfo> FileDeclIDs;
+
   // Updates for visible decls can occur for other contexts than just the
   // TU, and when we read those update records, the actual context will not
   // be available yet (unless it's the TU), so have this pending map using=
 the
   // ID as a key. It will be realized when the context is actually loaded.
-  typedef SmallVector<std::pair<void *, Module*>, 1> DeclContextVisibleUpd=
ates;
+  typedef SmallVector<std::pair<void *, ModuleFile*>, 1> DeclContextVisibl=
eUpdates;
   typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
       DeclContextVisibleUpdatesPending;
=20
   /// \brief Updates to the visible declarations of declaration contexts t=
hat
   /// haven't been loaded yet.
   DeclContextVisibleUpdatesPending PendingVisibleUpdates;
-
-  typedef SmallVector<CXXRecordDecl *, 4> ForwardRefs;
-  typedef llvm::DenseMap<const CXXRecordDecl *, ForwardRefs>
-      PendingForwardRefsMap;
-  /// \brief Forward references that have a definition but the definition =
decl
-  /// is still initializing. When the definition gets read it will update
-  /// the DefinitionData pointer of all pending references.
-  PendingForwardRefsMap PendingForwardRefs;
-
-  typedef llvm::DenseMap<serialization::DeclID, serialization::DeclID>
-      FirstLatestDeclIDMap;
-  /// \brief Map of first declarations from a chained PCH that point to the
-  /// most recent declarations in another AST file.
-  FirstLatestDeclIDMap FirstLatestDeclIDs;
-
-  /// \brief Set of ObjC interfaces that have categories chained to them in
-  /// other modules.
-  llvm::DenseSet<serialization::GlobalDeclID> ObjCChainedCategoriesInterfa=
ces;
-
+ =20
+  /// \brief The set of C++ or Objective-C classes that have forward=20
+  /// declarations that have not yet been linked to their definitions.
+  llvm::SmallPtrSet<Decl *, 4> PendingDefinitions;
+ =20
   /// \brief Read the records that describe the contents of declcontexts.
-  bool ReadDeclContextStorage(Module &M,=20
+  bool ReadDeclContextStorage(ModuleFile &M,
                               llvm::BitstreamCursor &Cursor,
                               const std::pair<uint64_t, uint64_t> &Offsets,
                               serialization::DeclContextInfo &Info);
@@ -340,14 +349,62 @@
   /// been loaded.
   std::vector<IdentifierInfo *> IdentifiersLoaded;
=20
-  typedef ContinuousRangeMap<serialization::IdentID, Module *, 4>=20
+  typedef ContinuousRangeMap<serialization::IdentID, ModuleFile *, 4>
     GlobalIdentifierMapType;
- =20
+
   /// \brief Mapping from global identifer IDs to the module in which the
   /// identifier resides along with the offset that should be added to the
   /// global identifier ID to produce a local ID.
   GlobalIdentifierMapType GlobalIdentifierMap;
=20
+  /// \brief A vector containing submodules that have already been loaded.
+  ///
+  /// This vector is indexed by the Submodule ID (-1). NULL submodule entr=
ies
+  /// indicate that the particular submodule ID has not yet been loaded.
+  SmallVector<Module *, 2> SubmodulesLoaded;
+ =20
+  typedef ContinuousRangeMap<serialization::SubmoduleID, ModuleFile *, 4>
+    GlobalSubmoduleMapType;
+ =20
+  /// \brief Mapping from global submodule IDs to the module file in which=
 the
+  /// submodule resides along with the offset that should be added to the
+  /// global submodule ID to produce a local ID.
+  GlobalSubmoduleMapType GlobalSubmoduleMap;
+
+  /// \brief A set of hidden declarations.
+  typedef llvm::SmallVector<llvm::PointerUnion<Decl *, IdentifierInfo *>, =
2>
+    HiddenNames;
+ =20
+  typedef llvm::DenseMap<Module *, HiddenNames> HiddenNamesMapType;
+
+  /// \brief A mapping from each of the hidden submodules to the deseriali=
zed
+  /// declarations in that submodule that could be made visible.
+  HiddenNamesMapType HiddenNamesMap;
+ =20
+ =20
+  /// \brief A module import or export that hasn't yet been resolved.
+  struct UnresolvedModuleImportExport {
+    /// \brief The file in which this module resides.
+    ModuleFile *File;
+   =20
+    /// \brief The module that is importing or exporting.
+    Module *Mod;
+   =20
+    /// \brief The local ID of the module that is being exported.
+    unsigned ID;
+   =20
+    /// \brief Whether this is an import (vs. an export).
+    unsigned IsImport : 1;
+   =20
+    /// \brief Whether this is a wildcard export.
+    unsigned IsWildcard : 1;
+  };
+ =20
+  /// \brief The set of module imports and exports that still need to be=20
+  /// resolved.
+  llvm::SmallVector<UnresolvedModuleImportExport, 2>=20
+    UnresolvedModuleImportExports;
+ =20
   /// \brief A vector containing selectors that have already been loaded.
   ///
   /// This vector is indexed by the Selector ID (-1). NULL selector
@@ -355,27 +412,31 @@
   /// been loaded.
   SmallVector<Selector, 16> SelectorsLoaded;
=20
-  typedef ContinuousRangeMap<serialization::SelectorID, Module *, 4>=20
+  typedef ContinuousRangeMap<serialization::SelectorID, ModuleFile *, 4>
     GlobalSelectorMapType;
- =20
+
   /// \brief Mapping from global selector IDs to the module in which the
   /// selector resides along with the offset that should be added to the
   /// global selector ID to produce a local ID.
   GlobalSelectorMapType GlobalSelectorMap;
=20
+  /// \brief The generation number of the last time we loaded data from the
+  /// global method pool for this selector.
+  llvm::DenseMap<Selector, unsigned> SelectorGeneration;
+
   /// \brief Mapping from identifiers that represent macros whose definiti=
ons
   /// have not yet been deserialized to the global offset where the macro
   /// record resides.
   llvm::DenseMap<IdentifierInfo *, uint64_t> UnreadMacroRecordOffsets;
=20
-  typedef ContinuousRangeMap<unsigned, Module *, 4>=20
+  typedef ContinuousRangeMap<unsigned, ModuleFile *, 4>
     GlobalPreprocessedEntityMapType;
- =20
+
   /// \brief Mapping from global preprocessing entity IDs to the module in
   /// which the preprocessed entity resides along with the offset that sho=
uld be
   /// added to the global preprocessing entitiy ID to produce a local ID.
   GlobalPreprocessedEntityMapType GlobalPreprocessedEntityMap;
- =20
+
   /// \name CodeGen-relevant special data
   /// \brief Fields containing data that is relevant to CodeGen.
   //@{
@@ -423,7 +484,7 @@
   /// \brief A list of all the delegating constructors we've seen, to diag=
nose
   /// cycles.
   SmallVector<uint64_t, 4> DelegatingCtorDecls;
- =20
+
   /// \brief Method selectors used in a @selector expression. Used for
   /// implementation of -Wselector.
   SmallVector<uint64_t, 64> ReferencedSelectorsData;
@@ -480,6 +541,9 @@
   /// \brief A list of the namespaces we've seen.
   SmallVector<uint64_t, 4> KnownNamespaces;
=20
+  /// \brief A list of modules that were imported by precompiled headers or
+  /// any other non-module AST file.
+  SmallVector<serialization::SubmoduleID, 2> ImportedModules;
   //@}
=20
   /// \brief The original file name that was used to build the primary AST=
 file,
@@ -493,7 +557,7 @@
   /// \brief The file ID for the original file that was used to build the
   /// primary AST file.
   FileID OriginalFileID;
- =20
+
   /// \brief The directory that the PCH was originally created in. Used to
   /// allow resolving headers even after headers+PCH was moved to a new pa=
th.
   std::string OriginalDir;
@@ -511,19 +575,23 @@
   /// \brief Whether to disable the normal validation performed on precomp=
iled
   /// headers when they are loaded.
   bool DisableValidation;
-     =20
+
   /// \brief Whether to disable the use of stat caches in AST files.
   bool DisableStatCache;
=20
+  /// \brief Whether to accept an AST file with compiler errors.
+  bool AllowASTWithCompilerErrors;
+
+  /// \brief The current "generation" of the module file import stack, whi=
ch=20
+  /// indicates how many separate module file load operations have occurre=
d.
+  unsigned CurrentGeneration;
+
   /// \brief Mapping from switch-case IDs in the chain to switch-case stat=
ements
   ///
   /// Statements usually don't have IDs, but switch cases need them, so th=
at the
   /// switch statement can refer to them.
   std::map<unsigned, SwitchCase *> SwitchCaseStmts;
=20
-  /// \brief Mapping from opaque value IDs to OpaqueValueExprs.
-  std::map<unsigned, OpaqueValueExpr*> OpaqueValueExprs;
-
   /// \brief The number of stat() calls that hit/missed the stat
   /// cache.
   unsigned NumStatHits, NumStatMisses;
@@ -567,13 +635,19 @@
=20
   /// Number of visible decl contexts read/total.
   unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
- =20
+
   /// Total size of modules, in bits, currently loaded
   uint64_t TotalModulesSizeInBits;
=20
   /// \brief Number of Decl/types that are currently deserializing.
   unsigned NumCurrentElementsDeserializing;
=20
+  /// \brief Set true while we are in the process of passing deserialized
+  /// "interesting" decls to consumer inside FinishedDeserializing().
+  /// This is used as a guard to avoid recursively repeating the process of
+  /// passing decls to consumer.
+  bool PassingDeclsToConsumer;
+
   /// Number of CXX base specifiers currently loaded
   unsigned NumCXXBaseSpecifiersLoaded;
=20
@@ -591,6 +665,10 @@
   /// loaded once the recursive loading has completed.
   std::deque<PendingIdentifierInfo> PendingIdentifierInfos;
=20
+  /// \brief The generation number of each identifier, which keeps track of
+  /// the last time we loaded information about this identifier.
+  llvm::DenseMap<IdentifierInfo *, unsigned> IdentifierGeneration;
+ =20
   /// \brief Contains declarations and definitions that will be
   /// "interesting" to the ASTConsumer, when we get that AST consumer.
   ///
@@ -599,10 +677,58 @@
   /// Objective-C protocols.
   std::deque<Decl *> InterestingDecls;
=20
-  /// \brief We delay loading of the previous declaration chain to avoid
-  /// deeply nested calls when there are many redeclarations.
-  std::deque<std::pair<Decl *, serialization::DeclID> > PendingPreviousDec=
ls;
+  /// \brief The set of redeclarable declaraations that have been deserial=
ized
+  /// since the last time the declaration chains were linked.
+  llvm::SmallPtrSet<Decl *, 16> RedeclsDeserialized;
+ =20
+  /// \brief The list of redeclaration chains that still need to be=20
+  /// reconstructed.
+  ///
+  /// Each element is the global declaration ID of the first declaration in
+  /// the chain. Elements in this vector should be unique; use=20
+  /// PendingDeclChainsKnown to ensure uniqueness.
+  llvm::SmallVector<serialization::DeclID, 16> PendingDeclChains;
=20
+  /// \brief Keeps track of the elements added to PendingDeclChains.
+  llvm::SmallSet<serialization::DeclID, 16> PendingDeclChainsKnown;
+
+  /// \brief The set of Objective-C categories that have been deserialized
+  /// since the last time the declaration chains were linked.
+  llvm::SmallPtrSet<ObjCCategoryDecl *, 16> CategoriesDeserialized;
+
+  /// \brief The set of Objective-C class definitions that have already be=
en
+  /// loaded, for which we will need to check for categories whenever a new
+  /// module is loaded.
+  llvm::SmallVector<ObjCInterfaceDecl *, 16> ObjCClassesLoaded;
+ =20
+  typedef llvm::DenseMap<Decl *, llvm::SmallVector<serialization::DeclID, =
2> >
+    MergedDeclsMap;
+   =20
+  /// \brief A mapping from canonical declarations to the set of additional
+  /// (global, previously-canonical) declaration IDs that have been merged=
 with
+  /// that canonical declaration.
+  MergedDeclsMap MergedDecls;
+ =20
+  typedef llvm::DenseMap<serialization::GlobalDeclID,=20
+                         llvm::SmallVector<serialization::DeclID, 2> >
+    StoredMergedDeclsMap;
+ =20
+  /// \brief A mapping from canonical declaration IDs to the set of additi=
onal
+  /// declaration IDs that have been merged with that canonical declaratio=
n.
+  ///
+  /// This is the deserialized representation of the entries in MergedDecl=
s.
+  /// When we query entries in MergedDecls, they will be augmented with en=
tries
+  /// from StoredMergedDecls.
+  StoredMergedDeclsMap StoredMergedDecls;
+ =20
+  /// \brief Combine the stored merged declarations for the given canonical
+  /// declaration into the set of merged declarations.
+  ///
+  /// \returns An iterator into MergedDecls that corresponds to the positi=
on of
+  /// the given canonical declaration.
+  MergedDeclsMap::iterator
+  combineStoredMergedDecls(Decl *Canon, serialization::GlobalDeclID CanonI=
D);
+ =20
   /// \brief Ready to load the previous declaration of the given Decl.
   void loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID);
=20
@@ -614,7 +740,7 @@
     Read_Decl, Read_Type, Read_Stmt
   };
=20
-  /// \brief What kind of records we are reading.=20
+  /// \brief What kind of records we are reading.
   ReadingKind ReadingKind;
=20
   /// \brief RAII object to change the reading kind.
@@ -649,7 +775,7 @@
   std::string SuggestedPredefines;
=20
   /// \brief Reads a statement from the specified cursor.
-  Stmt *ReadStmtFromStream(Module &F);
+  Stmt *ReadStmtFromStream(ModuleFile &F);
=20
   /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we=
 take
   /// into account all the necessary relocations.
@@ -658,20 +784,21 @@
   void MaybeAddSystemRootToFilename(std::string &Filename);
=20
   ASTReadResult ReadASTCore(StringRef FileName, ModuleKind Type,
-                            Module *ImportedBy);
-  ASTReadResult ReadASTBlock(Module &F);
+                            ModuleFile *ImportedBy);
+  ASTReadResult ReadASTBlock(ModuleFile &F);
   bool CheckPredefinesBuffers();
-  bool ParseLineTable(Module &F, SmallVectorImpl<uint64_t> &Record);
-  ASTReadResult ReadSourceManagerBlock(Module &F);
+  bool ParseLineTable(ModuleFile &F, SmallVectorImpl<uint64_t> &Record);
+  ASTReadResult ReadSourceManagerBlock(ModuleFile &F);
   ASTReadResult ReadSLocEntryRecord(int ID);
   llvm::BitstreamCursor &SLocCursorForID(int ID);
-  SourceLocation getImportLocation(Module *F);
+  SourceLocation getImportLocation(ModuleFile *F);
+  ASTReadResult ReadSubmoduleBlock(ModuleFile &F);
   bool ParseLanguageOptions(const SmallVectorImpl<uint64_t> &Record);
-
+ =20
   struct RecordLocation {
-    RecordLocation(Module *M, uint64_t O)
+    RecordLocation(ModuleFile *M, uint64_t O)
       : F(M), Offset(O) {}
-    Module *F;
+    ModuleFile *F;
     uint64_t Offset;
   };
=20
@@ -679,19 +806,22 @@
   RecordLocation TypeCursorForIndex(unsigned Index);
   void LoadedDecl(unsigned Index, Decl *D);
   Decl *ReadDeclRecord(serialization::DeclID ID);
-  RecordLocation DeclCursorForID(serialization::DeclID ID);
+  RecordLocation DeclCursorForID(serialization::DeclID ID,
+                                 unsigned &RawLocation);
   void loadDeclUpdateRecords(serialization::DeclID ID, Decl *D);
-  void loadObjCChainedCategories(serialization::GlobalDeclID ID,
-                                 ObjCInterfaceDecl *D);
- =20
+  void loadPendingDeclChain(serialization::GlobalDeclID ID);
+  void loadObjCCategories(serialization::GlobalDeclID ID, ObjCInterfaceDec=
l *D,
+                          unsigned PreviousGeneration =3D 0);
+
   RecordLocation getLocalBitOffset(uint64_t GlobalOffset);
-  uint64_t getGlobalBitOffset(Module &M, uint32_t LocalOffset);
+  uint64_t getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset);
=20
   /// \brief Returns the first preprocessed entity ID that ends after \arg=
 BLoc.
   serialization::PreprocessedEntityID
     findBeginPreprocessedEntity(SourceLocation BLoc) const;
=20
-  /// \brief Returns the first preprocessed entity ID that begins after \a=
rg ELoc.
+  /// \brief Returns the first preprocessed entity ID that begins after \a=
rg
+  /// ELoc.
   serialization::PreprocessedEntityID
     findEndPreprocessedEntity(SourceLocation ELoc) const;
=20
@@ -703,7 +833,15 @@
     findNextPreprocessedEntity(
                         GlobalSLocOffsetMapType::const_iterator SLocMapI) =
const;
=20
+  /// \brief Returns (ModuleFile, Local index) pair for \arg GlobalIndex o=
f a
+  /// preprocessed entity.
+  std::pair<ModuleFile *, unsigned>
+    getModulePreprocessedEntity(unsigned GlobalIndex);
+
   void PassInterestingDeclsToConsumer();
+  void PassInterestingDeclToConsumer(Decl *D);
+
+  void finishPendingActions();
=20
   /// \brief Produce an error diagnostic and return true.
   ///
@@ -740,20 +878,38 @@
   /// help when an AST file is being used in cases where the
   /// underlying files in the file system may have changed, but
   /// parsing should still continue.
+  ///
+  /// \param AllowASTWithCompilerErrors If true, the AST reader will accep=
t an
+  /// AST file the was created out of an AST with compiler errors,
+  /// otherwise it will reject it.
   ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot =3D =
"",
-            bool DisableValidation =3D false, bool DisableStatCache =3D fa=
lse);
+            bool DisableValidation =3D false, bool DisableStatCache =3D fa=
lse,
+            bool AllowASTWithCompilerErrors =3D false);
=20
   ~ASTReader();
=20
   SourceManager &getSourceManager() const { return SourceMgr; }
- =20
+
   /// \brief Load the AST file designated by the given file name.
   ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type);
=20
   /// \brief Checks that no file that is stored in PCH is out-of-sync with
   /// the actual file in the file system.
-  ASTReadResult validateFileEntries(Module &M);
+  ASTReadResult validateFileEntries(ModuleFile &M);
=20
+  /// \brief Make the entities in the given module and any of its (non-exp=
licit)
+  /// submodules visible to name lookup.
+  ///
+  /// \param Mod The module whose names should be made visible.
+  ///
+  /// \param Visibility The level of visibility to give the names in the m=
odule.
+  /// Visibility can only be increased over time.
+  void makeModuleVisible(Module *Mod,=20
+                         Module::NameVisibilityKind NameVisibility);
+ =20
+  /// \brief Make the names within this set of hidden names visible.
+  void makeNamesVisible(const HiddenNames &Names);
+ =20
   /// \brief Set the AST callbacks listener.
   void setListener(ASTReaderListener *listener) {
     Listener.reset(listener);
@@ -770,12 +926,19 @@
     ModuleMgr.addInMemoryBuffer(FileName, Buffer);
   }
=20
+  /// \brief Finalizes the AST reader's state before writing an AST file to
+  /// disk.
+  ///
+  /// This operation may undo temporary state in the AST that should not be
+  /// emitted.
+  void finalizeForWriting();
+
   /// \brief Retrieve the module manager.
   ModuleManager &getModuleManager() { return ModuleMgr; }
=20
   /// \brief Retrieve the preprocessor.
   Preprocessor &getPreprocessor() const { return PP; }
- =20
+
   /// \brief Retrieve the name of the original source file name
   const std::string &getOriginalSourceFile() { return OriginalFileName; }
=20
@@ -801,6 +964,11 @@
   virtual std::pair<unsigned, unsigned>
       findPreprocessedEntitiesInRange(SourceRange Range);
=20
+  /// \brief Optionally returns true or false if the preallocated preproce=
ssed
+  /// entity with index \arg Index came from file \arg FID.
+  virtual llvm::Optional<bool> isPreprocessedEntityInFileID(unsigned Index,
+                                                            FileID FID);
+
   /// \brief Read the header file information for the given file entry.
   virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE);
=20
@@ -826,6 +994,11 @@
     return static_cast<unsigned>(DeclsLoaded.size());
   }
=20
+  /// \brief Returns the number of submodules known.
+  unsigned getTotalNumSubmodules() const {
+    return static_cast<unsigned>(SubmodulesLoaded.size());
+  }
+ =20
   /// \brief Returns the number of selectors found in the chain.
   unsigned getTotalNumSelectors() const {
     return static_cast<unsigned>(SelectorsLoaded.size());
@@ -839,28 +1012,28 @@
         E =3D ModuleMgr.end(); I !=3D E; ++I) {
       Result +=3D (*I)->NumPreprocessedEntities;
     }
-   =20
+
     return Result;
   }
-     =20
+
   /// \brief Returns the number of C++ base specifiers found in the chain.
   unsigned getTotalNumCXXBaseSpecifiers() const {
     return NumCXXBaseSpecifiersLoaded;
   }
-     =20
+
   /// \brief Reads a TemplateArgumentLocInfo appropriate for the
   /// given TemplateArgument kind.
   TemplateArgumentLocInfo
-  GetTemplateArgumentLocInfo(Module &F, TemplateArgument::ArgKind Kind,
+  GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind,
                              const RecordData &Record, unsigned &Idx);
=20
   /// \brief Reads a TemplateArgumentLoc.
   TemplateArgumentLoc
-  ReadTemplateArgumentLoc(Module &F,
+  ReadTemplateArgumentLoc(ModuleFile &F,
                           const RecordData &Record, unsigned &Idx);
=20
   /// \brief Reads a declarator info from the given record.
-  TypeSourceInfo *GetTypeSourceInfo(Module &F,
+  TypeSourceInfo *GetTypeSourceInfo(ModuleFile &F,
                                     const RecordData &Record, unsigned &Id=
x);
=20
   /// \brief Resolve a type ID into a type, potentially building a new
@@ -868,35 +1041,42 @@
   QualType GetType(serialization::TypeID ID);
=20
   /// \brief Resolve a local type ID within a given AST file into a type.
-  QualType getLocalType(Module &F, unsigned LocalID);
- =20
+  QualType getLocalType(ModuleFile &F, unsigned LocalID);
+
   /// \brief Map a local type ID within a given AST file into a global typ=
e ID.
-  serialization::TypeID getGlobalTypeID(Module &F, unsigned LocalID) const;
- =20
-  /// \brief Read a type from the current position in the given record, wh=
ich=20
+  serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) c=
onst;
+
+  /// \brief Read a type from the current position in the given record, wh=
ich
   /// was read from the given AST file.
-  QualType readType(Module &F, const RecordData &Record, unsigned &Idx) {
+  QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx=
) {
     if (Idx >=3D Record.size())
       return QualType();
-   =20
+
     return getLocalType(F, Record[Idx++]);
   }
- =20
-  /// \brief Map from a local declaration ID within a given module to a=20
+
+  /// \brief Map from a local declaration ID within a given module to a
   /// global declaration ID.
-  serialization::DeclID getGlobalDeclID(Module &F, unsigned LocalID) const;
+  serialization::DeclID getGlobalDeclID(ModuleFile &F, unsigned LocalID) c=
onst;
=20
   /// \brief Returns true if global DeclID \arg ID originated from module
   /// \arg M.
-  bool isDeclIDFromModule(serialization::GlobalDeclID ID, Module &M) const;
+  bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) c=
onst;
+
+  /// \brief Retrieve the module file that owns the given declaration, or =
NULL
+  /// if the declaration is not from a module file.
+  ModuleFile *getOwningModuleFile(Decl *D);
  =20
+  /// \brief Returns the source location for the decl \arg ID.
+  SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID=
);
+
   /// \brief Resolve a declaration ID into a declaration, potentially
   /// building a new declaration.
   Decl *GetDecl(serialization::DeclID ID);
   virtual Decl *GetExternalDecl(uint32_t ID);
=20
   /// \brief Reads a declaration with the given local ID in the given modu=
le.
-  Decl *GetLocalDecl(Module &F, uint32_t LocalID) {
+  Decl *GetLocalDecl(ModuleFile &F, uint32_t LocalID) {
     return GetDecl(getGlobalDeclID(F, LocalID));
   }
=20
@@ -904,40 +1084,49 @@
   ///
   /// \returns The requested declaration, casted to the given return type.
   template<typename T>
-  T *GetLocalDeclAs(Module &F, uint32_t LocalID) {
+  T *GetLocalDeclAs(ModuleFile &F, uint32_t LocalID) {
     return cast_or_null<T>(GetLocalDecl(F, LocalID));
   }
=20
-  /// \brief Reads a declaration ID from the given position in a record in=
 the=20
+  /// \brief Map a global declaration ID into the declaration ID used to=20
+  /// refer to this declaration within the given module fule.
+  ///
+  /// \returns the global ID of the given declaration as known in the given
+  /// module file.
+  serialization::DeclID=20
+  mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
+                                  serialization::DeclID GlobalID);
+ =20
+  /// \brief Reads a declaration ID from the given position in a record in=
 the
   /// given module.
   ///
   /// \returns The declaration ID read from the record, adjusted to a glob=
al ID.
-  serialization::DeclID ReadDeclID(Module &F, const RecordData &Record,
+  serialization::DeclID ReadDeclID(ModuleFile &F, const RecordData &Record,
                                    unsigned &Idx);
- =20
+
   /// \brief Reads a declaration from the given position in a record in the
   /// given module.
-  Decl *ReadDecl(Module &F, const RecordData &R, unsigned &I) {
+  Decl *ReadDecl(ModuleFile &F, const RecordData &R, unsigned &I) {
     return GetDecl(ReadDeclID(F, R, I));
   }
- =20
+
   /// \brief Reads a declaration from the given position in a record in the
   /// given module.
   ///
   /// \returns The declaration read from this location, casted to the given
   /// result type.
   template<typename T>
-  T *ReadDeclAs(Module &F, const RecordData &R, unsigned &I) {
+  T *ReadDeclAs(ModuleFile &F, const RecordData &R, unsigned &I) {
     return cast_or_null<T>(GetDecl(ReadDeclID(F, R, I)));
   }
=20
   /// \brief Read a CXXBaseSpecifiers ID form the given record and
   /// return its global bit offset.
-  uint64_t readCXXBaseSpecifiers(Module &M, const RecordData &Record,=20
+  uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
                                  unsigned &Idx);
-     =20
+
   virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
-     =20
+
   /// \brief Resolve the offset of a statement into a statement.
   ///
   /// This operation will read a new statement from the external
@@ -974,6 +1163,12 @@
                                         bool (*isKindWeWant)(Decl::Kind),
                                         SmallVectorImpl<Decl*> &Decls);
=20
+  /// \brief Get the decls that are contained in a file in the Offset/Leng=
th
+  /// range. \arg Length can be 0 to indicate a point at \arg Offset inste=
ad of
+  /// a range.
+  virtual void FindFileRegionDecls(FileID File, unsigned Offset,unsigned L=
ength,
+                                   SmallVectorImpl<Decl *> &Decls);
+
   /// \brief Notify ASTReader that we started deserialization of
   /// a decl or type so until FinishedDeserializing is called there may be
   /// decls that are initializing. Must be paired with FinishedDeserializi=
ng.
@@ -995,7 +1190,7 @@
=20
   /// \brief Dump information about the AST reader to standard error.
   void dump();
- =20
+
   /// Return the amount of memory used by memory buffers, breaking down
   /// by heap-backed versus mmap'ed memory.
   virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
@@ -1025,11 +1220,7 @@
=20
   /// \brief Load the contents of the global method pool for a given
   /// selector.
-  ///
-  /// \returns a pair of Objective-C methods lists containing the
-  /// instance and factory methods, respectively, with this selector.
-  virtual std::pair<ObjCMethodList, ObjCMethodList>
-    ReadMethodPool(Selector Sel);
+  virtual void ReadMethodPool(Selector Sel);
=20
   /// \brief Load the set of namespaces that are known to the external sou=
rce,
   /// which will be used during typo correction.
@@ -1051,7 +1242,7 @@
=20
   virtual void ReadLocallyScopedExternalDecls(
                  SmallVectorImpl<NamedDecl *> &Decls);
- =20
+
   virtual void ReadReferencedSelectors(
                  SmallVectorImpl<std::pair<Selector, SourceLocation> > &Se=
ls);
=20
@@ -1061,7 +1252,7 @@
   virtual void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables=
);
=20
   virtual void ReadPendingInstantiations(
-                 SmallVectorImpl<std::pair<ValueDecl *,=20
+                 SmallVectorImpl<std::pair<ValueDecl *,
                                            SourceLocation> > &Pending);
=20
   /// \brief Load a selector from disk, registering its ID if it exists.
@@ -1080,7 +1271,7 @@
=20
   IdentifierInfo *DecodeIdentifierInfo(serialization::IdentifierID ID);
=20
-  IdentifierInfo *GetIdentifierInfo(Module &M, const RecordData &Record,=20
+  IdentifierInfo *GetIdentifierInfo(ModuleFile &M, const RecordData &Recor=
d,
                                     unsigned &Idx) {
     return DecodeIdentifierInfo(getGlobalIdentifierID(M, Record[Idx++]));
   }
@@ -1089,101 +1280,110 @@
     return DecodeIdentifierInfo(ID);
   }
=20
-  IdentifierInfo *getLocalIdentifier(Module &M, unsigned LocalID);
- =20
-  serialization::IdentifierID getGlobalIdentifierID(Module &M,=20
+  IdentifierInfo *getLocalIdentifier(ModuleFile &M, unsigned LocalID);
+
+  serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M,
                                                     unsigned LocalID);
-                                =20
+
   /// \brief Read the source location entry with index ID.
   virtual bool ReadSLocEntry(int ID);
=20
+  /// \brief Retrieve the global submodule ID given a module and its local=
 ID
+  /// number.
+  serialization::SubmoduleID=20
+  getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID);
+ =20
+  /// \brief Retrieve the submodule that corresponds to a global submodule=
 ID.
+  ///
+  Module *getSubmodule(serialization::SubmoduleID GlobalID);
+ =20
   /// \brief Retrieve a selector from the given module with its local ID
   /// number.
-  Selector getLocalSelector(Module &M, unsigned LocalID);
+  Selector getLocalSelector(ModuleFile &M, unsigned LocalID);
=20
   Selector DecodeSelector(serialization::SelectorID Idx);
=20
   virtual Selector GetExternalSelector(serialization::SelectorID ID);
   uint32_t GetNumExternalSelectors();
=20
-  Selector ReadSelector(Module &M, const RecordData &Record, unsigned &Idx=
) {
+  Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned =
&Idx) {
     return getLocalSelector(M, Record[Idx++]);
   }
- =20
+
   /// \brief Retrieve the global selector ID that corresponds to this
   /// the local selector ID in a given module.
-  serialization::SelectorID getGlobalSelectorID(Module &F,=20
+  serialization::SelectorID getGlobalSelectorID(ModuleFile &F,
                                                 unsigned LocalID) const;
=20
   /// \brief Read a declaration name.
-  DeclarationName ReadDeclarationName(Module &F,=20
+  DeclarationName ReadDeclarationName(ModuleFile &F,
                                       const RecordData &Record, unsigned &=
Idx);
-  void ReadDeclarationNameLoc(Module &F,
+  void ReadDeclarationNameLoc(ModuleFile &F,
                               DeclarationNameLoc &DNLoc, DeclarationName N=
ame,
                               const RecordData &Record, unsigned &Idx);
-  void ReadDeclarationNameInfo(Module &F, DeclarationNameInfo &NameInfo,
+  void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInf=
o,
                                const RecordData &Record, unsigned &Idx);
=20
-  void ReadQualifierInfo(Module &F, QualifierInfo &Info,
+  void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
                          const RecordData &Record, unsigned &Idx);
=20
-  NestedNameSpecifier *ReadNestedNameSpecifier(Module &F,
+  NestedNameSpecifier *ReadNestedNameSpecifier(ModuleFile &F,
                                                const RecordData &Record,
                                                unsigned &Idx);
=20
-  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(Module &F,=20
+  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F,
                                                     const RecordData &Reco=
rd,
                                                     unsigned &Idx);
=20
   /// \brief Read a template name.
-  TemplateName ReadTemplateName(Module &F, const RecordData &Record,=20
+  TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record,
                                 unsigned &Idx);
=20
   /// \brief Read a template argument.
-  TemplateArgument ReadTemplateArgument(Module &F,
+  TemplateArgument ReadTemplateArgument(ModuleFile &F,
                                         const RecordData &Record,unsigned =
&Idx);
- =20
+
   /// \brief Read a template parameter list.
-  TemplateParameterList *ReadTemplateParameterList(Module &F,
+  TemplateParameterList *ReadTemplateParameterList(ModuleFile &F,
                                                    const RecordData &Recor=
d,
                                                    unsigned &Idx);
- =20
+
   /// \brief Read a template argument array.
   void
   ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
-                           Module &F, const RecordData &Record,
+                           ModuleFile &F, const RecordData &Record,
                            unsigned &Idx);
=20
   /// \brief Read a UnresolvedSet structure.
-  void ReadUnresolvedSet(Module &F, UnresolvedSetImpl &Set,
+  void ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
                          const RecordData &Record, unsigned &Idx);
=20
   /// \brief Read a C++ base specifier.
-  CXXBaseSpecifier ReadCXXBaseSpecifier(Module &F,
+  CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F,
                                         const RecordData &Record,unsigned =
&Idx);
=20
   /// \brief Read a CXXCtorInitializer array.
   std::pair<CXXCtorInitializer **, unsigned>
-  ReadCXXCtorInitializers(Module &F, const RecordData &Record,
+  ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
                           unsigned &Idx);
=20
   /// \brief Read a source location from raw form.
-  SourceLocation ReadSourceLocation(Module &Module, unsigned Raw) const {
+  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) =
const {
     SourceLocation Loc =3D SourceLocation::getFromRawEncoding(Raw);
-    assert(Module.SLocRemap.find(Loc.getOffset()) !=3D Module.SLocRemap.en=
d() &&
+    assert(ModuleFile.SLocRemap.find(Loc.getOffset()) !=3D ModuleFile.SLoc=
Remap.end() &&
            "Cannot find offset to remap.");
-    int Remap =3D Module.SLocRemap.find(Loc.getOffset())->second;
+    int Remap =3D ModuleFile.SLocRemap.find(Loc.getOffset())->second;
     return Loc.getLocWithOffset(Remap);
   }
=20
   /// \brief Read a source location.
-  SourceLocation ReadSourceLocation(Module &Module,
+  SourceLocation ReadSourceLocation(ModuleFile &ModuleFile,
                                     const RecordData &Record, unsigned& Id=
x) {
-    return ReadSourceLocation(Module, Record[Idx++]);
+    return ReadSourceLocation(ModuleFile, Record[Idx++]);
   }
=20
   /// \brief Read a source range.
-  SourceRange ReadSourceRange(Module &F,
+  SourceRange ReadSourceRange(ModuleFile &F,
                               const RecordData &Record, unsigned& Idx);
=20
   /// \brief Read an integral value
@@ -1201,18 +1401,18 @@
   /// \brief Read a version tuple.
   VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
=20
-  CXXTemporary *ReadCXXTemporary(Module &F, const RecordData &Record,=20
+  CXXTemporary *ReadCXXTemporary(ModuleFile &F, const RecordData &Record,
                                  unsigned &Idx);
-     =20
+
   /// \brief Reads attributes from the current stream position.
-  void ReadAttributes(Module &F, AttrVec &Attrs,
+  void ReadAttributes(ModuleFile &F, AttrVec &Attrs,
                       const RecordData &Record, unsigned &Idx);
=20
   /// \brief Reads a statement.
-  Stmt *ReadStmt(Module &F);
+  Stmt *ReadStmt(ModuleFile &F);
=20
   /// \brief Reads an expression.
-  Expr *ReadExpr(Module &F);
+  Expr *ReadExpr(ModuleFile &F);
=20
   /// \brief Reads a sub-statement operand during statement reading.
   Stmt *ReadSubStmt() {
@@ -1228,29 +1428,47 @@
   Expr *ReadSubExpr();
=20
   /// \brief Reads the macro record located at the given offset.
-  void ReadMacroRecord(Module &F, uint64_t Offset);
-     =20
+  void ReadMacroRecord(ModuleFile &F, uint64_t Offset);
+
   /// \brief Determine the global preprocessed entity ID that corresponds =
to
   /// the given local ID within the given module.
-  serialization::PreprocessedEntityID=20
-  getGlobalPreprocessedEntityID(Module &M, unsigned LocalID) const;
- =20
+  serialization::PreprocessedEntityID
+  getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const;
+
   /// \brief Note that the identifier is a macro whose record will be load=
ed
   /// from the given AST file at the given (file-local) offset.
-  void SetIdentifierIsMacro(IdentifierInfo *II, Module &F,
-                            uint64_t Offset);
-     =20
+  ///
+  /// \param II The name of the macro.
+  ///
+  /// \param F The module file from which the macro definition was deseria=
lized.
+  ///
+  /// \param Offset The offset into the module file at which the macro=20
+  /// definition is located.
+  ///
+  /// \param Visible Whether the macro should be made visible.
+  void setIdentifierIsMacro(IdentifierInfo *II, ModuleFile &F,
+                            uint64_t Offset, bool Visible);
+
   /// \brief Read the set of macros defined by this external macro source.
   virtual void ReadDefinedMacros();
=20
   /// \brief Read the macro definition for this identifier.
   virtual void LoadMacroDefinition(IdentifierInfo *II);
=20
+  /// \brief Update an out-of-date identifier.
+  virtual void updateOutOfDateIdentifier(IdentifierInfo &II);
+
+  /// \brief Note that this identifier is up-to-date.
+  void markIdentifierUpToDate(IdentifierInfo *II);
+ =20
   /// \brief Read the macro definition corresponding to this iterator
   /// into the unread macro record offsets table.
   void LoadMacroDefinition(
                      llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator =
Pos);
- =20
+
+  /// \brief Load all external visible decls in the given DeclContext.
+  void completeVisibleDeclsMap(DeclContext *DC);
+
   /// \brief Retrieve the AST context that this AST reader supplements.
   ASTContext &getContext() { return Context; }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Serialization/ASTWriter.h
--- a/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTWriter.h=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Serialization/ASTWriter.h=
	Tue Apr 17 11:51:51 2012 +0300
@@ -24,6 +24,8 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SetVector.h"
 #include "llvm/Bitcode/BitstreamWriter.h"
 #include <map>
 #include <queue>
@@ -43,11 +45,13 @@
 class CXXCtorInitializer;
 class FPOptions;
 class HeaderSearch;
+class IdentifierResolver;
 class MacroDefinition;
 class MemorizeStatCalls;
 class OpaqueValueExpr;
 class OpenCLOptions;
 class ASTReader;
+class Module;
 class PreprocessedEntity;
 class PreprocessingRecord;
 class Preprocessor;
@@ -57,6 +61,8 @@
 class TargetInfo;
 class VersionTuple;
=20
+namespace SrcMgr { class SLocEntry; }
+
 /// \brief Writes an AST file containing the contents of a translation uni=
t.
 ///
 /// The ASTWriter class produces a bitstream containing the serialized
@@ -80,7 +86,7 @@
   /// allow for the const/volatile qualifiers.
   ///
   /// Keys in the map never have const/volatile qualifiers.
-  typedef llvm::DenseMap<QualType, serialization::TypeIdx,=20
+  typedef llvm::DenseMap<QualType, serialization::TypeIdx,
                          serialization::UnsafeQualTypeDenseMapInfo>
     TypeIdxMap;
=20
@@ -89,33 +95,42 @@
=20
   /// \brief The ASTContext we're writing.
   ASTContext *Context;
-                   =20
+
+  /// \brief The preprocessor we're writing.
+  Preprocessor *PP;
+
   /// \brief The reader of existing AST files, if we're chaining.
   ASTReader *Chain;
-                  =20
-  /// \brief Indicates when the AST writing is actively performing=20
+
+  /// \brief The module we're currently writing, if any.
+  Module *WritingModule;
+                   =20
+  /// \brief Indicates when the AST writing is actively performing
   /// serialization, rather than just queueing updates.
   bool WritingAST;
-                   =20
+
+  /// \brief Indicates that the AST contained compiler errors.
+  bool ASTHasCompilerErrors;
+
   /// \brief Stores a declaration or a type to be written to the AST file.
   class DeclOrType {
   public:
     DeclOrType(Decl *D) : Stored(D), IsType(false) { }
     DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
-   =20
+
     bool isType() const { return IsType; }
     bool isDecl() const { return !IsType; }
-   =20
+
     QualType getType() const {
       assert(isType() && "Not a type!");
       return QualType::getFromOpaquePtr(Stored);
     }
-   =20
+
     Decl *getDecl() const {
       assert(isDecl() && "Not a decl!");
       return static_cast<Decl *>(Stored);
     }
-   =20
+
   private:
     void *Stored;
     bool IsType;
@@ -140,7 +155,25 @@
=20
   /// \brief Offset of each declaration in the bitstream, indexed by
   /// the declaration's ID.
-  std::vector<uint32_t> DeclOffsets;
+  std::vector<serialization::DeclOffset> DeclOffsets;
+
+  /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
+  typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
+    LocDeclIDsTy;
+  struct DeclIDInFileInfo {
+    LocDeclIDsTy DeclIDs;
+    /// \brief Set when the DeclIDs vectors from all files are joined, this
+    /// indicates the index that this particular vector has in the global =
one.
+    unsigned FirstDeclIndex;
+  };
+  typedef llvm::DenseMap<const SrcMgr::SLocEntry *,
+                         DeclIDInFileInfo *> FileDeclIDsTy;
+
+  /// \brief Map from file SLocEntries to info about the file-level declar=
ations
+  /// that it contains.
+  FileDeclIDsTy FileDeclIDs;
+
+  void associateDeclWithFile(const Decl *D, serialization::DeclID);
=20
   /// \brief The first ID number we can use for our own types.
   serialization::TypeID FirstTypeID;
@@ -177,14 +210,32 @@
   /// IdentifierInfo.
   llvm::DenseMap<const IdentifierInfo *, serialization::IdentID> Identifie=
rIDs;
=20
+  /// @name FlushStmt Caches
+  /// @{
+
+  /// \brief Set of parent Stmts for the currently serializing sub stmt.
+  llvm::DenseSet<Stmt *> ParentStmts;
+
+  /// \brief Offsets of sub stmts already serialized. The offset points
+  /// just after the stmt record.
+  llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
+
+  /// @}
+
   /// \brief Offsets of each of the identifier IDs into the identifier
   /// table.
   std::vector<uint32_t> IdentifierOffsets;
=20
+  /// \brief The first ID number we can use for our own submodules.
+  serialization::SubmoduleID FirstSubmoduleID;
+ =20
+  /// \brief The submodule ID that will be assigned to the next new submod=
ule.
+  serialization::SubmoduleID NextSubmoduleID;
+
   /// \brief The first ID number we can use for our own selectors.
   serialization::SelectorID FirstSelectorID;
=20
-  /// \brief The selector ID that will be assigned to the next new identif=
ier.
+  /// \brief The selector ID that will be assigned to the next new selecto=
r.
   serialization::SelectorID NextSelectorID;
=20
   /// \brief Map that provides the ID numbers of each Selector.
@@ -193,7 +244,7 @@
   /// \brief Offset of each selector within the method pool/selector
   /// table, indexed by the Selector ID (-1).
   std::vector<uint32_t> SelectorOffsets;
- =20
+
   /// \brief Offsets of each of the macro identifiers into the
   /// bitstream.
   ///
@@ -204,7 +255,7 @@
=20
   /// \brief The set of identifiers that had macro definitions at some poi=
nt.
   std::vector<const IdentifierInfo *> DeserializedMacroNames;
- =20
+
   /// \brief Mapping from macro definitions (as they occur in the preproce=
ssing
   /// record) to the macro IDs.
   llvm::DenseMap<const MacroDefinition *, serialization::PreprocessedEntit=
yID>
@@ -220,7 +271,7 @@
   /// \brief Map of first declarations from a chained PCH that point to the
   /// most recent declarations in another PCH.
   FirstLatestDeclMap FirstLatestDecls;
- =20
+
   /// \brief Declarations encountered that might be external
   /// definitions.
   ///
@@ -238,31 +289,30 @@
   /// \brief DeclContexts that have received extensions since their serial=
ized
   /// form.
   ///
-  /// For namespaces, when we're chaining and encountering a namespace, we=
 check if
-  /// its primary namespace comes from the chain. If it does, we add the p=
rimary
-  /// to this set, so that we can write out lexical content updates for it.
+  /// For namespaces, when we're chaining and encountering a namespace, we=
 check
+  /// if its primary namespace comes from the chain. If it does, we add the
+  /// primary to this set, so that we can write out lexical content update=
s for
+  /// it.
   llvm::SmallPtrSet<const DeclContext *, 16> UpdatedDeclContexts;
=20
   typedef llvm::SmallPtrSet<const Decl *, 16> DeclsToRewriteTy;
   /// \brief Decls that will be replaced in the current dependent AST file.
   DeclsToRewriteTy DeclsToRewrite;
=20
-  struct ChainedObjCCategoriesData {
-    /// \brief The interface in the imported module.
-    const ObjCInterfaceDecl *Interface;
-    /// \brief The local tail category ID that got chained to the imported
-    /// interface.
-    const ObjCCategoryDecl *TailCategory;
-   =20
-    /// \brief ID corresponding to \c Interface.
-    serialization::DeclID InterfaceID;
-   =20
-    /// \brief ID corresponding to TailCategoryID.
-    serialization::DeclID TailCategoryID;
+  /// \brief The set of Objective-C class that have categories we
+  /// should serialize.
+  llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
+                   =20
+  struct ReplacedDeclInfo {
+    serialization::DeclID ID;
+    uint64_t Offset;
+    unsigned Loc;
+
+    ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {}
+    ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset,
+                     SourceLocation Loc)
+      : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {}
   };
-  /// \brief ObjC categories that got chained to an interface imported from
-  /// another module.
-  SmallVector<ChainedObjCCategoriesData, 16> LocalChainedObjCCategories;
=20
   /// \brief Decls that have been replaced in the current dependent AST fi=
le.
   ///
@@ -270,23 +320,24 @@
   /// happen, but the ObjC AST nodes are designed this way), it will be
   /// serialized again. In this case, it is registered here, so that the r=
eader
   /// knows to read the updated version.
-  SmallVector<std::pair<serialization::DeclID, uint64_t>, 16>
-      ReplacedDecls;
-
+  SmallVector<ReplacedDeclInfo, 16> ReplacedDecls;
+                =20
+  /// \brief The set of declarations that may have redeclaration chains th=
at
+  /// need to be serialized.
+  llvm::SetVector<Decl *, llvm::SmallVector<Decl *, 4>,=20
+                  llvm::SmallPtrSet<Decl *, 4> > Redeclarations;
+                                     =20
   /// \brief Statements that we've encountered while serializing a
   /// declaration or type.
   SmallVector<Stmt *, 16> StmtsToEmit;
=20
   /// \brief Statements collection to use for ASTWriter::AddStmt().
-  /// It will point to StmtsToEmit unless it is overriden.=20
+  /// It will point to StmtsToEmit unless it is overriden.
   SmallVector<Stmt *, 16> *CollectedStmts;
=20
   /// \brief Mapping from SwitchCase statements to IDs.
   std::map<SwitchCase *, unsigned> SwitchCaseIDs;
=20
-  /// \brief Mapping from OpaqueValueExpr expressions to IDs.
-  llvm::DenseMap<OpaqueValueExpr *, unsigned> OpaqueValues;
-
   /// \brief The number of statements written to the AST file.
   unsigned NumStatements;
=20
@@ -303,35 +354,44 @@
=20
   /// \brief The offset of each CXXBaseSpecifier set within the AST.
   SmallVector<uint32_t, 4> CXXBaseSpecifiersOffsets;
-                   =20
+
   /// \brief The first ID number we can use for our own base specifiers.
   serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID;
- =20
-  /// \brief The base specifiers ID that will be assigned to the next new=20
+
+  /// \brief The base specifiers ID that will be assigned to the next new
   /// set of C++ base specifiers.
   serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID;
=20
-  /// \brief A set of C++ base specifiers that is queued to be written int=
o the=20
-  /// AST file.                   =20
+  /// \brief A set of C++ base specifiers that is queued to be written int=
o the
+  /// AST file.
   struct QueuedCXXBaseSpecifiers {
     QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { }
-   =20
+
     QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID,
                             CXXBaseSpecifier const *Bases,
                             CXXBaseSpecifier const *BasesEnd)
       : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { }
-                           =20
+
     serialization::CXXBaseSpecifiersID ID;
     CXXBaseSpecifier const * Bases;
     CXXBaseSpecifier const * BasesEnd;
   };
-                   =20
+
   /// \brief Queue of C++ base specifiers to be written to the AST file,
   /// in the order they should be written.
   SmallVector<QueuedCXXBaseSpecifiers, 2> CXXBaseSpecifiersToWrite;
+
+  /// \brief A mapping from each known submodule to its ID number, which w=
ill
+  /// be a positive integer.
+  llvm::DenseMap<Module *, unsigned> SubmoduleIDs;
+                   =20
+  /// \brief Retrieve or create a submodule ID for this module.
+  unsigned getSubmoduleID(Module *Mod);
                    =20
   /// \brief Write the given subexpression to the bitstream.
-  void WriteSubStmt(Stmt *S);
+  void WriteSubStmt(Stmt *S,
+                    llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntries,
+                    llvm::DenseSet<Stmt *> &ParentStmts);
=20
   void WriteBlockInfoBlock();
   void WriteMetadata(ASTContext &Context, StringRef isysroot,
@@ -342,27 +402,32 @@
                                const Preprocessor &PP,
                                StringRef isysroot);
   void WritePreprocessor(const Preprocessor &PP, bool IsModule);
-  void WriteHeaderSearch(HeaderSearch &HS, StringRef isysroot);
+  void WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot);
   void WritePreprocessorDetail(PreprocessingRecord &PPRec);
+  void WriteSubmodules(Module *WritingModule);
+                                       =20
   void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag);
   void WriteCXXBaseSpecifiersOffsets();
   void WriteType(QualType T);
   uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *=
DC);
   uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *=
DC);
   void WriteTypeDeclOffsets();
+  void WriteFileDeclIDsMap();
   void WriteSelectors(Sema &SemaRef);
   void WriteReferencedSelectorsPool(Sema &SemaRef);
-  void WriteIdentifierTable(Preprocessor &PP, bool IsModule);
+  void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolv=
er,
+                            bool IsModule);
   void WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record);
   void ResolveDeclUpdatesBlocks();
   void WriteDeclUpdatesBlocks();
   void WriteDeclReplacementsBlock();
-  void ResolveChainedObjCCategories();
-  void WriteChainedObjCCategories();
   void WriteDeclContextVisibleUpdate(const DeclContext *DC);
   void WriteFPPragmaOptions(const FPOptions &Opts);
   void WriteOpenCLExtensions(Sema &SemaRef);
-
+  void WriteObjCCategories();
+  void WriteRedeclarations();
+  void WriteMergedDecls();
+                       =20
   unsigned DeclParmVarAbbrev;
   unsigned DeclContextLexicalAbbrev;
   unsigned DeclContextVisibleLookupAbbrev;
@@ -382,13 +447,14 @@
=20
   void WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
                     StringRef isysroot, const std::string &OutputFile,
-                    bool IsModule);
- =20
+                    Module *WritingModule);
+
 public:
   /// \brief Create a new precompiled header writer that outputs to
   /// the given bitstream.
   ASTWriter(llvm::BitstreamWriter &Stream);
-                   =20
+  ~ASTWriter();
+
   /// \brief Write a precompiled header for the given semantic analysis.
   ///
   /// \param SemaRef a reference to the semantic analysis object that proc=
essed
@@ -397,21 +463,22 @@
   /// \param StatCalls the object that cached all of the stat() calls made=
 while
   /// searching for source files and headers.
   ///
-  /// \param IsModule Whether we're writing a module (otherwise, we're wri=
ting a
-  /// precompiled header).
+  /// \param WritingModule The module that we are writing. If null, we are
+  /// writing a precompiled header.
   ///
   /// \param isysroot if non-empty, write a relocatable file whose headers
   /// are relative to the given system root.
   void WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
                 const std::string &OutputFile,
-                bool IsModule, StringRef isysroot);
+                Module *WritingModule, StringRef isysroot,
+                bool hasErrors =3D false);
=20
   /// \brief Emit a source location.
   void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
=20
   /// \brief Emit a source range.
   void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
- =20
+
   /// \brief Emit an integral value.
   void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record);
=20
@@ -434,10 +501,10 @@
   void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
                                CXXBaseSpecifier const *BasesEnd,
                                RecordDataImpl &Record);
-                   =20
+
   /// \brief Get the unique number used to refer to the given selector.
   serialization::SelectorID getSelectorRef(Selector Sel);
- =20
+
   /// \brief Get the unique number used to refer to the given identifier.
   serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
=20
@@ -450,7 +517,7 @@
            "Identifier does not name a macro");
     return MacroOffsets[II];
   }
- =20
+
   /// \brief Emit a reference to a type.
   void AddTypeRef(QualType T, RecordDataImpl &Record);
=20
@@ -484,7 +551,7 @@
   /// \brief Emit a reference to a declaration.
   void AddDeclRef(const Decl *D, RecordDataImpl &Record);
=20
-                   =20
+
   /// \brief Force a declaration to be emitted and get its ID.
   serialization::DeclID GetDeclRef(const Decl *D);
=20
@@ -505,9 +572,9 @@
   void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Re=
cord);
=20
   /// \brief Emit a nested name specifier with source-location information.
-  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,=20
+  void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
                                  RecordDataImpl &Record);
- =20
+
   /// \brief Emit a template name.
   void AddTemplateName(TemplateName Name, RecordDataImpl &Record);
=20
@@ -526,7 +593,8 @@
   void AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Reco=
rd);
=20
   /// \brief Emit a C++ base specifier.
-  void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, RecordDataImpl &R=
ecord);
+  void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
+                           RecordDataImpl &Record);
=20
   /// \brief Emit a CXXCtorInitializer array.
   void AddCXXCtorInitializers(
@@ -549,10 +617,16 @@
=20
   void RewriteDecl(const Decl *D) {
     DeclsToRewrite.insert(D);
-    // Reset the flag, so that we don't add this decl multiple times.
-    const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
   }
=20
+  bool isRewritten(const Decl *D) const {
+    return DeclsToRewrite.count(D);
+  }
+
+  /// \brief Infer the submodule ID that contains an entity at the given
+  /// source location.
+  serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation L=
oc);
+
   /// \brief Note that the identifier II occurs at the given offset
   /// within the identifier table.
   void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
@@ -577,10 +651,10 @@
   /// been added to the queue via AddStmt().
   void FlushStmts();
=20
-  /// \brief Flush all of the C++ base specifier sets that have been added=20
+  /// \brief Flush all of the C++ base specifier sets that have been added
   /// via \c AddCXXBaseSpecifiersRef().
   void FlushCXXBaseSpecifiers();
-                   =20
+
   /// \brief Record an ID for the given switch-case statement.
   unsigned RecordSwitchCaseID(SwitchCase *S);
=20
@@ -589,9 +663,6 @@
=20
   void ClearSwitchCaseIDs();
=20
-  /// \brief Retrieve the ID for the given opaque value expression.
-  unsigned getOpaqueValueID(OpaqueValueExpr *e);
-
   unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
   unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
   unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbr=
ev; }
@@ -609,11 +680,12 @@
   void ReaderInitialized(ASTReader *Reader);
   void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II);
   void TypeRead(serialization::TypeIdx Idx, QualType T);
-  void DeclRead(serialization::DeclID ID, const Decl *D);
   void SelectorRead(serialization::SelectorID ID, Selector Sel);
   void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
                            MacroDefinition *MD);
-
+  void MacroVisible(IdentifierInfo *II);
+  void ModuleRead(serialization::SubmoduleID ID, Module *Mod);
+                   =20
   // ASTMutationListener implementation.
   virtual void CompletedTagDefinition(const TagDecl *D);
   virtual void AddedVisibleDecl(const DeclContext *DC, const Decl *D);
@@ -626,6 +698,9 @@
   virtual void StaticDataMemberInstantiated(const VarDecl *D);
   virtual void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
                                             const ObjCInterfaceDecl *IFD);
+  virtual void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *P=
rop,
+                                            const ObjCPropertyDecl *OrigPr=
op,
+                                            const ObjCCategoryDecl *ClassE=
xt);
 };
=20
 /// \brief AST and semantic-analysis consumer that generates a
@@ -633,12 +708,12 @@
 class PCHGenerator : public SemaConsumer {
   const Preprocessor &PP;
   std::string OutputFile;
-  bool IsModule;
+  clang::Module *Module;
   std::string isysroot;
   raw_ostream *Out;
   Sema *SemaPtr;
   MemorizeStatCalls *StatCalls; // owned by the FileManager
-  std::vector<unsigned char> Buffer;
+  llvm::SmallVector<char, 128> Buffer;
   llvm::BitstreamWriter Stream;
   ASTWriter Writer;
=20
@@ -647,8 +722,8 @@
   const ASTWriter &getWriter() const { return Writer; }
=20
 public:
-  PCHGenerator(const Preprocessor &PP, StringRef OutputFile,=20
-               bool IsModule,
+  PCHGenerator(const Preprocessor &PP, StringRef OutputFile,
+               clang::Module *Module,
                StringRef isysroot, raw_ostream *Out);
   ~PCHGenerator();
   virtual void InitializeSema(Sema &S) { SemaPtr =3D &S; }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Serialization/ContinuousRangeMap.h
--- a/head/contrib/llvm/tools/clang/include/clang/Serialization/ContinuousR=
angeMap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Serialization/ContinuousR=
angeMap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -68,6 +68,16 @@
            "Must insert keys in order.");
     Rep.push_back(Val);
   }
+ =20
+  void insertOrReplace(const value_type &Val) {
+    iterator I =3D std::lower_bound(Rep.begin(), Rep.end(), Val, Compare()=
);
+    if (I !=3D Rep.end() && I->first =3D=3D Val.first) {
+      I->second =3D Val.second;
+      return;
+    }
+   =20
+    Rep.insert(I, Val);
+  }
=20
   typedef typename Representation::iterator iterator;
   typedef typename Representation::const_iterator const_iterator;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Serialization/Module.h
--- a/head/contrib/llvm/tools/clang/include/clang/Serialization/Module.h	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Serialization/Module.h	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -23,12 +23,13 @@
 #include "llvm/Bitcode/BitstreamReader.h"
 #include <string>
=20
-namespace clang {=20
+namespace clang {
=20
 class DeclContext;
+class Module;
  =20
 namespace serialization {
-  =20
+
 /// \brief Specifies the kind of module that has been loaded.
 enum ModuleKind {
   MK_Module,   ///< File is a module proper.
@@ -39,9 +40,9 @@
=20
 /// \brief Information about the contents of a DeclContext.
 struct DeclContextInfo {
-  DeclContextInfo()=20
+  DeclContextInfo()
     : NameLookupTableData(), LexicalDecls(), NumLexicalDecls() {}
- =20
+
   void *NameLookupTableData; // an ASTDeclContextNameLookupTable.
   const KindDeclIDPair *LexicalDecls;
   unsigned NumLexicalDecls;
@@ -49,265 +50,303 @@
=20
 /// \brief Information about a module that has been loaded by the ASTReade=
r.
 ///
-/// Each instance of the Module class corresponds to a single AST file, wh=
ich=20
-/// may be a precompiled header, precompiled preamble, a module, or an AST=
 file=20
-/// of some sort loaded as the main file, all of which are specific formul=
ations of
-/// the general notion of a "module". A module may depend on any number of
+/// Each instance of the Module class corresponds to a single AST file, wh=
ich
+/// may be a precompiled header, precompiled preamble, a module, or an AST=
 file
+/// of some sort loaded as the main file, all of which are specific formul=
ations
+/// of the general notion of a "module". A module may depend on any number=
 of
 /// other modules.
-class Module {
-public: =20
-  Module(ModuleKind Kind);
-  ~Module();
- =20
+class ModuleFile {
+public:
+  ModuleFile(ModuleKind Kind, unsigned Generation);
+  ~ModuleFile();
+
   // =3D=3D=3D General information =3D=3D=3D
- =20
+
   /// \brief The type of this module.
   ModuleKind Kind;
- =20
+
   /// \brief The file name of the module file.
   std::string FileName;
- =20
+
   /// \brief Whether this module has been directly imported by the
   /// user.
   bool DirectlyImported;
+
+  /// \brief The generation of which this module file is a part.
+  unsigned Generation;
  =20
   /// \brief The memory buffer that stores the data associated with
   /// this AST file.
-  llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
- =20
+  OwningPtr<llvm::MemoryBuffer> Buffer;
+
   /// \brief The size of this file, in bits.
   uint64_t SizeInBits;
- =20
+
   /// \brief The global bit offset (or base) of this module
   uint64_t GlobalBitOffset;
- =20
+
   /// \brief The bitstream reader from which we'll read the AST file.
   llvm::BitstreamReader StreamFile;
- =20
+
   /// \brief The main bitstream cursor for the main block.
   llvm::BitstreamCursor Stream;
- =20
+
   /// \brief The source location where this module was first imported.
   SourceLocation ImportLoc;
- =20
+
   /// \brief The first source location in this module.
   SourceLocation FirstLoc;
- =20
+
   // =3D=3D=3D Source Locations =3D=3D=3D
- =20
+
   /// \brief Cursor used to read source location entries.
   llvm::BitstreamCursor SLocEntryCursor;
- =20
+
   /// \brief The number of source location entries in this AST file.
   unsigned LocalNumSLocEntries;
- =20
+
   /// \brief The base ID in the source manager's view of this module.
   int SLocEntryBaseID;
- =20
+
   /// \brief The base offset in the source manager's view of this module.
   unsigned SLocEntryBaseOffset;
- =20
+
   /// \brief Offsets for all of the source location entries in the
   /// AST file.
   const uint32_t *SLocEntryOffsets;
- =20
+
   /// \brief SLocEntries that we're going to preload.
   SmallVector<uint64_t, 4> PreloadSLocEntries;
=20
   /// \brief The number of source location file entries in this AST file.
   unsigned LocalNumSLocFileEntries;
- =20
+
   /// \brief Offsets for all of the source location file entries in the
   /// AST file.
   const uint32_t *SLocFileOffsets;
- =20
+
   /// \brief Remapping table for source locations in this module.
   ContinuousRangeMap<uint32_t, int, 2> SLocRemap;
- =20
+
   // =3D=3D=3D Identifiers =3D=3D=3D
- =20
+
   /// \brief The number of identifiers in this AST file.
   unsigned LocalNumIdentifiers;
- =20
+
   /// \brief Offsets into the identifier table data.
   ///
   /// This array is indexed by the identifier ID (-1), and provides
   /// the offset into IdentifierTableData where the string data is
   /// stored.
   const uint32_t *IdentifierOffsets;
- =20
+
   /// \brief Base identifier ID for identifiers local to this module.
   serialization::IdentID BaseIdentifierID;
- =20
+
   /// \brief Remapping table for identifier IDs in this module.
   ContinuousRangeMap<uint32_t, int, 2> IdentifierRemap;
- =20
+
   /// \brief Actual data for the on-disk hash table of identifiers.
   ///
   /// This pointer points into a memory buffer, where the on-disk hash
   /// table for identifiers actually lives.
   const char *IdentifierTableData;
- =20
+
   /// \brief A pointer to an on-disk hash table of opaque type
   /// IdentifierHashTable.
   void *IdentifierLookupTable;
- =20
+
   // =3D=3D=3D Macros =3D=3D=3D
- =20
+
   /// \brief The cursor to the start of the preprocessor block, which stor=
es
   /// all of the macro definitions.
   llvm::BitstreamCursor MacroCursor;
- =20
+
   /// \brief The offset of the start of the set of defined macros.
   uint64_t MacroStartOffset;
- =20
+
   // =3D=3D=3D Detailed PreprocessingRecord =3D=3D=3D
- =20
-  /// \brief The cursor to the start of the (optional) detailed preprocess=
ing=20
+
+  /// \brief The cursor to the start of the (optional) detailed preprocess=
ing
   /// record block.
   llvm::BitstreamCursor PreprocessorDetailCursor;
- =20
+
   /// \brief The offset of the start of the preprocessor detail cursor.
   uint64_t PreprocessorDetailStartOffset;
- =20
-  /// \brief Base preprocessed entity ID for preprocessed entities local t=
o=20
+
+  /// \brief Base preprocessed entity ID for preprocessed entities local to
   /// this module.
   serialization::PreprocessedEntityID BasePreprocessedEntityID;
- =20
+
   /// \brief Remapping table for preprocessed entity IDs in this module.
   ContinuousRangeMap<uint32_t, int, 2> PreprocessedEntityRemap;
- =20
+
   const PPEntityOffset *PreprocessedEntityOffsets;
   unsigned NumPreprocessedEntities;
- =20
+
   // =3D=3D=3D Header search information =3D=3D=3D
- =20
+
   /// \brief The number of local HeaderFileInfo structures.
   unsigned LocalNumHeaderFileInfos;
- =20
-  /// \brief Actual data for the on-disk hash table of header file=20
+
+  /// \brief Actual data for the on-disk hash table of header file
   /// information.
   ///
   /// This pointer points into a memory buffer, where the on-disk hash
   /// table for header file information actually lives.
   const char *HeaderFileInfoTableData;
- =20
+
   /// \brief The on-disk hash table that contains information about each of
   /// the header files.
   void *HeaderFileInfoTable;
- =20
+
   /// \brief Actual data for the list of framework names used in the header
   /// search information.
   const char *HeaderFileFrameworkStrings;
+
+  // =3D=3D=3D Submodule information =3D=3D=3D =20
+  /// \brief The number of submodules in this module.
+  unsigned LocalNumSubmodules;
+ =20
+  /// \brief Base submodule ID for submodules local to this module.
+  serialization::SubmoduleID BaseSubmoduleID;
+ =20
+  /// \brief Remapping table for submodule IDs in this module.
+  ContinuousRangeMap<uint32_t, int, 2> SubmoduleRemap;
  =20
   // =3D=3D=3D Selectors =3D=3D=3D
- =20
+
   /// \brief The number of selectors new to this file.
   ///
   /// This is the number of entries in SelectorOffsets.
   unsigned LocalNumSelectors;
- =20
+
   /// \brief Offsets into the selector lookup table's data array
   /// where each selector resides.
   const uint32_t *SelectorOffsets;
- =20
+
   /// \brief Base selector ID for selectors local to this module.
   serialization::SelectorID BaseSelectorID;
- =20
+
   /// \brief Remapping table for selector IDs in this module.
   ContinuousRangeMap<uint32_t, int, 2> SelectorRemap;
- =20
+
   /// \brief A pointer to the character data that comprises the selector t=
able
   ///
   /// The SelectorOffsets table refers into this memory.
   const unsigned char *SelectorLookupTableData;
- =20
+
   /// \brief A pointer to an on-disk hash table of opaque type
   /// ASTSelectorLookupTable.
   ///
   /// This hash table provides the IDs of all selectors, and the associated
   /// instance and factory methods.
   void *SelectorLookupTable;
- =20
+
   // =3D=3D=3D Declarations =3D=3D=3D
- =20
+
   /// DeclsCursor - This is a cursor to the start of the DECLS_BLOCK block=
. It
   /// has read all the abbreviations at the start of the block and is read=
y to
   /// jump around with these in context.
   llvm::BitstreamCursor DeclsCursor;
- =20
+
   /// \brief The number of declarations in this AST file.
   unsigned LocalNumDecls;
- =20
+
   /// \brief Offset of each declaration within the bitstream, indexed
   /// by the declaration ID (-1).
-  const uint32_t *DeclOffsets;
- =20
+  const DeclOffset *DeclOffsets;
+
   /// \brief Base declaration ID for declarations local to this module.
   serialization::DeclID BaseDeclID;
- =20
+
   /// \brief Remapping table for declaration IDs in this module.
   ContinuousRangeMap<uint32_t, int, 2> DeclRemap;
- =20
+
+  /// \brief Mapping from the module files that this module file depends on
+  /// to the base declaration ID for that module as it is understood withi=
n this
+  /// module.
+  ///
+  /// This is effectively a reverse global-to-local mapping for declaration
+  /// IDs, so that we can interpret a true global ID (for this translation=
 unit)
+  /// as a local ID (for this module file).
+  llvm::DenseMap<ModuleFile *, serialization::DeclID> GlobalToLocalDeclIDs;
+
   /// \brief The number of C++ base specifier sets in this AST file.
   unsigned LocalNumCXXBaseSpecifiers;
- =20
+
   /// \brief Offset of each C++ base specifier set within the bitstream,
   /// indexed by the C++ base specifier set ID (-1).
   const uint32_t *CXXBaseSpecifiersOffsets;
- =20
+
   typedef llvm::DenseMap<const DeclContext *, DeclContextInfo>
   DeclContextInfosMap;
- =20
+
   /// \brief Information about the lexical and visible declarations
   /// for each DeclContext.
   DeclContextInfosMap DeclContextInfos;
=20
-  typedef llvm::DenseMap<serialization::GlobalDeclID,
-             std::pair<serialization::LocalDeclID, serialization::LocalDec=
lID> >
-    ChainedObjCCategoriesMap;
-  /// \brief ObjC categories that got chained to an interface from another
+  /// \brief Array of file-level DeclIDs sorted by file.
+  const serialization::DeclID *FileSortedDecls;
+
+  /// \brief Array of redeclaration chain location information within this=20
+  /// module file, sorted by the first declaration ID.
+  const serialization::LocalRedeclarationsInfo *RedeclarationsMap;
+
+  /// \brief The number of redeclaration info entries in RedeclarationsMap.
+  unsigned LocalNumRedeclarationsInMap;
+ =20
+  /// \brief The redeclaration chains for declarations local to this
+  /// module file.
+  SmallVector<uint64_t, 1> RedeclarationChains;
+ =20
+  /// \brief Array of category list location information within this=20
+  /// module file, sorted by the definition ID.
+  const serialization::ObjCCategoriesInfo *ObjCCategoriesMap;
+ =20
+  /// \brief The number of redeclaration info entries in ObjCCategoriesMap.
+  unsigned LocalNumObjCCategoriesInMap;
+ =20
+  /// \brief The Objective-C category lists for categories known to this
   /// module.
-  /// Key is the ID of the interface.
-  /// Value is a pair of linked category DeclIDs (head category, tail cate=
gory).
-  ChainedObjCCategoriesMap ChainedObjCCategories;
- =20
+  SmallVector<uint64_t, 1> ObjCCategories;
+
   // =3D=3D=3D Types =3D=3D=3D
- =20
+
   /// \brief The number of types in this AST file.
   unsigned LocalNumTypes;
- =20
+
   /// \brief Offset of each type within the bitstream, indexed by the
   /// type ID, or the representation of a Type*.
   const uint32_t *TypeOffsets;
- =20
-  /// \brief Base type ID for types local to this module as represented in=20
+
+  /// \brief Base type ID for types local to this module as represented in
   /// the global type ID space.
   serialization::TypeID BaseTypeIndex;
- =20
+
   /// \brief Remapping table for type IDs in this module.
   ContinuousRangeMap<uint32_t, int, 2> TypeRemap;
- =20
+
   // =3D=3D=3D Miscellaneous =3D=3D=3D
- =20
+
   /// \brief Diagnostic IDs and their mappings that the user changed.
   SmallVector<uint64_t, 8> PragmaDiagMappings;
- =20
+
   /// \brief The AST stat cache installed for this file, if any.
   ///
   /// The dynamic type of this stat cache is always ASTStatCache
   void *StatCache;
- =20
+
   /// \brief List of modules which depend on this module
-  llvm::SetVector<Module *> ImportedBy;
- =20
+  llvm::SetVector<ModuleFile *> ImportedBy;
+
   /// \brief List of modules which this module depends on
-  llvm::SetVector<Module *> Imports;
- =20
+  llvm::SetVector<ModuleFile *> Imports;
+
   /// \brief Determine whether this module was directly imported at
   /// any point during translation.
   bool isDirectlyImported() const { return DirectlyImported; }
- =20
+
   /// \brief Dump debugging output for this module.
   void dump();
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/Serialization/ModuleManager.h
--- a/head/contrib/llvm/tools/clang/include/clang/Serialization/ModuleManag=
er.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/Serialization/ModuleManag=
er.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,10 +27,10 @@
 class ModuleManager {
   /// \brief The chain of AST files. The first entry is the one named by t=
he
   /// user, the last one is the one that doesn't depend on anything furthe=
r.
-  llvm::SmallVector<Module*, 2> Chain;
+  llvm::SmallVector<ModuleFile*, 2> Chain;
  =20
   /// \brief All loaded modules, indexed by name.
-  llvm::DenseMap<const FileEntry *, Module *> Modules;
+  llvm::DenseMap<const FileEntry *, ModuleFile *> Modules;
  =20
   /// \brief FileManager that handles translating between filenames and
   /// FileEntry *.
@@ -40,9 +40,9 @@
   llvm::DenseMap<const FileEntry *, llvm::MemoryBuffer *> InMemoryBuffers;
  =20
 public:
-  typedef SmallVector<Module*, 2>::iterator ModuleIterator;
-  typedef SmallVector<Module*, 2>::const_iterator ModuleConstIterator;
-  typedef SmallVector<Module*, 2>::reverse_iterator ModuleReverseIterator;
+  typedef SmallVector<ModuleFile*, 2>::iterator ModuleIterator;
+  typedef SmallVector<ModuleFile*, 2>::const_iterator ModuleConstIterator;
+  typedef SmallVector<ModuleFile*, 2>::reverse_iterator ModuleReverseItera=
tor;
   typedef std::pair<uint32_t, StringRef> ModuleOffset;
  =20
   ModuleManager(const FileSystemOptions &FSO);
@@ -68,17 +68,17 @@
  =20
   /// \brief Returns the primary module associated with the manager, that =
is,
   /// the first module loaded
-  Module &getPrimaryModule() { return *Chain[0]; }
+  ModuleFile &getPrimaryModule() { return *Chain[0]; }
  =20
   /// \brief Returns the primary module associated with the manager, that =
is,
   /// the first module loaded.
-  Module &getPrimaryModule() const { return *Chain[0]; }
+  ModuleFile &getPrimaryModule() const { return *Chain[0]; }
  =20
   /// \brief Returns the module associated with the given index
-  Module &operator[](unsigned Index) const { return *Chain[Index]; }
+  ModuleFile &operator[](unsigned Index) const { return *Chain[Index]; }
  =20
   /// \brief Returns the module associated with the given name
-  Module *lookup(StringRef Name);
+  ModuleFile *lookup(StringRef Name);
  =20
   /// \brief Returns the in-memory (virtual file) buffer with the given na=
me
   llvm::MemoryBuffer *lookupBuffer(StringRef Name);
@@ -95,14 +95,16 @@
   /// \param ImportedBy The module that is importing this module, or NULL =
if
   /// this module is imported directly by the user.
   ///
+  /// \param Generation The generation in which this module was loaded.
+  ///
   /// \param ErrorStr Will be set to a non-empty string if any errors occu=
rred
   /// while trying to load the module.
   ///
   /// \return A pointer to the module that corresponds to this file name,
   /// and a boolean indicating whether the module was newly added.
-  std::pair<Module *, bool>=20
-  addModule(StringRef FileName, ModuleKind Type, Module *ImportedBy,
-            std::string &ErrorStr);
+  std::pair<ModuleFile *, bool>=20
+  addModule(StringRef FileName, ModuleKind Type, ModuleFile *ImportedBy,
+            unsigned Generation, std::string &ErrorStr);
  =20
   /// \brief Add an in-memory buffer the list of known buffers
   void addInMemoryBuffer(StringRef FileName, llvm::MemoryBuffer *Buffer);
@@ -125,7 +127,7 @@
   ///
   /// \param UserData User data associated with the visitor object, which
   /// will be passed along to the visitor.
-  void visit(bool (*Visitor)(Module &M, void *UserData), void *UserData);
+  void visit(bool (*Visitor)(ModuleFile &M, void *UserData), void *UserDat=
a);
  =20
   /// \brief Visit each of the modules with a depth-first traversal.
   ///
@@ -143,7 +145,7 @@
   ///
   /// \param UserData User data ssociated with the visitor object,
   /// which will be passed along to the user.
-  void visitDepthFirst(bool (*Visitor)(Module &M, bool Preorder,=20
+  void visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Preorder,=20
                                        void *UserData),=20
                        void *UserData);
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/BugReporter/BugReporter.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/BugReporter.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/BugReporter.h	Tue Apr 17 11:51:51 2012 +0300
@@ -20,10 +20,10 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "llvm/ADT/FoldingSet.h"
-#include "llvm/ADT/ImmutableList.h"
+#include "llvm/ADT/ilist.h"
+#include "llvm/ADT/ilist_node.h"
 #include "llvm/ADT/ImmutableSet.h"
-#include "llvm/ADT/SmallSet.h"
-#include <list>
+#include "llvm/ADT/DenseSet.h"
=20
 namespace clang {
=20
@@ -49,9 +49,10 @@
=20
 /// This class provides an interface through which checkers can create
 /// individual bug reports.
-class BugReport {
-public:
+class BugReport : public llvm::ilist_node<BugReport> {
+public: =20
   class NodeResolver {
+    virtual void anchor();
   public:
     virtual ~NodeResolver() {}
     virtual const ExplodedNode*
@@ -59,7 +60,8 @@
   };
=20
   typedef const SourceRange *ranges_iterator;
-  typedef llvm::ImmutableList<BugReporterVisitor*>::iterator visitor_itera=
tor;
+  typedef SmallVector<BugReporterVisitor *, 8> VisitorList;
+  typedef VisitorList::iterator visitor_iterator;
   typedef SmallVector<StringRef, 2> ExtraTextList;
=20
 protected:
@@ -67,32 +69,65 @@
   friend class BugReportEquivClass;
=20
   BugType& BT;
+  const Decl *DeclWithIssue;
   std::string ShortDescription;
   std::string Description;
   PathDiagnosticLocation Location;
+  PathDiagnosticLocation UniqueingLocation;
   const ExplodedNode *ErrorNode;
   SmallVector<SourceRange, 4> Ranges;
   ExtraTextList ExtraText;
+ =20
+  typedef llvm::DenseSet<SymbolRef> Symbols;
+  typedef llvm::DenseSet<const MemRegion *> Regions;
=20
-  // Not the most efficient data structure, but we use an ImmutableList fo=
r the
-  // Callbacks because it is safe to make additions to list during iterati=
on.
-  llvm::ImmutableList<BugReporterVisitor*>::Factory F;
-  llvm::ImmutableList<BugReporterVisitor*> Callbacks;
+  /// A set of symbols that are registered with this report as being
+  /// "interesting", and thus used to help decide which diagnostics
+  /// to include when constructing the final path diagnostic.
+  Symbols interestingSymbols;
+
+  /// A set of regions that are registered with this report as being
+  /// "interesting", and thus used to help decide which diagnostics
+  /// to include when constructing the final path diagnostic.
+  Regions interestingRegions;
+
+  /// A set of custom visitors which generate "event" diagnostics at
+  /// interesting points in the path.
+  VisitorList Callbacks;
+
+  /// Used for ensuring the visitors are only added once.
   llvm::FoldingSet<BugReporterVisitor> CallbacksSet;
=20
+  /// Used for clients to tell if the report's configuration has changed
+  /// since the last time they checked.
+  unsigned ConfigurationChangeToken;
+
 public:
   BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode)
-    : BT(bt), Description(desc), ErrorNode(errornode),
-      Callbacks(F.getEmptyList()) {}
+    : BT(bt), DeclWithIssue(0), Description(desc), ErrorNode(errornode),
+      ConfigurationChangeToken(0) {}
=20
   BugReport(BugType& bt, StringRef shortDesc, StringRef desc,
             const ExplodedNode *errornode)
-    : BT(bt), ShortDescription(shortDesc), Description(desc),
-      ErrorNode(errornode), Callbacks(F.getEmptyList()) {}
+    : BT(bt), DeclWithIssue(0), ShortDescription(shortDesc), Description(d=
esc),
+      ErrorNode(errornode), ConfigurationChangeToken(0) {}
=20
   BugReport(BugType& bt, StringRef desc, PathDiagnosticLocation l)
-    : BT(bt), Description(desc), Location(l), ErrorNode(0),
-      Callbacks(F.getEmptyList()) {}
+    : BT(bt), DeclWithIssue(0), Description(desc), Location(l), ErrorNode(=
0),
+      ConfigurationChangeToken(0) {}
+
+  /// \brief Create a BugReport with a custom uniqueing location.
+  ///
+  /// The reports that have the same report location, description, bug typ=
e, and
+  /// ranges are uniqued - only one of the equivalent reports will be pres=
ented
+  /// to the user. This method allows to rest the location which should be=
 used
+  /// for uniquing reports. For example, memory leaks checker, could set t=
his to
+  /// the allocation site, rather then the location where the bug is repor=
ted.
+  BugReport(BugType& bt, StringRef desc, const ExplodedNode *errornode,
+            PathDiagnosticLocation LocationToUnique)
+    : BT(bt), DeclWithIssue(0), Description(desc),
+      UniqueingLocation(LocationToUnique),
+      ErrorNode(errornode), ConfigurationChangeToken(0) {}
=20
   virtual ~BugReport();
=20
@@ -107,6 +142,28 @@
     return ShortDescription.empty() ? Description : ShortDescription;
   }
=20
+  void markInteresting(SymbolRef sym);
+  void markInteresting(const MemRegion *R);
+  void markInteresting(SVal V);
+ =20
+  bool isInteresting(SymbolRef sym) const;
+  bool isInteresting(const MemRegion *R) const;
+  bool isInteresting(SVal V) const;
+
+  unsigned getConfigurationChangeToken() const {
+    return ConfigurationChangeToken;
+  }
+ =20
+  /// Return the canonical declaration, be it a method or class, where
+  /// this issue semantically occurred.
+  const Decl *getDeclWithIssue() const;
+ =20
+  /// Specifically set the Decl where an issue occurred.  This isn't neces=
sary
+  /// for BugReports that cover a path as it will be automatically inferre=
d.
+  void setDeclWithIssue(const Decl *declWithIssue) {
+    DeclWithIssue =3D declWithIssue;
+  }
+ =20
   /// \brief This allows for addition of meta data to the diagnostic.
   ///
   /// Currently, only the HTMLDiagnosticClient knows how to display it.=20
@@ -162,13 +219,38 @@
   virtual void Profile(llvm::FoldingSetNodeID& hash) const;
 };
=20
+} // end ento namespace
+} // end clang namespace
+
+namespace llvm {
+  template<> struct ilist_traits<clang::ento::BugReport>
+    : public ilist_default_traits<clang::ento::BugReport> {
+    clang::ento::BugReport *createSentinel() const {
+      return static_cast<clang::ento::BugReport *>(&Sentinel);
+    }
+    void destroySentinel(clang::ento::BugReport *) const {}
+
+    clang::ento::BugReport *provideInitialHead() const {
+      return createSentinel();
+    }
+    clang::ento::BugReport *ensureHead(clang::ento::BugReport *) const {
+      return createSentinel();
+    }
+  private:
+    mutable ilist_half_node<clang::ento::BugReport> Sentinel;
+  };
+}
+
+namespace clang {
+namespace ento {
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // BugTypes (collections of related reports).
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 class BugReportEquivClass : public llvm::FoldingSetNode {
   /// List of *owned* BugReport objects.
-  std::list<BugReport*> Reports;
+  llvm::ilist<BugReport> Reports;
=20
   friend class BugReporter;
   void AddReport(BugReport* R) { Reports.push_back(R); }
@@ -178,36 +260,17 @@
=20
   void Profile(llvm::FoldingSetNodeID& ID) const {
     assert(!Reports.empty());
-    (*Reports.begin())->Profile(ID);
+    Reports.front().Profile(ID);
   }
=20
-  class iterator {
-    std::list<BugReport*>::iterator impl;
-  public:
-    iterator(std::list<BugReport*>::iterator i) : impl(i) {}
-    iterator &operator++() { ++impl; return *this; }
-    bool operator=3D=3D(const iterator &I) const { return I.impl =3D=3D im=
pl; }
-    bool operator!=3D(const iterator &I) const { return I.impl !=3D impl; }
-    BugReport* operator*() const { return *impl; }
-    BugReport* operator->() const { return *impl; }
-  };
+  typedef llvm::ilist<BugReport>::iterator iterator;
+  typedef llvm::ilist<BugReport>::const_iterator const_iterator;
=20
-  class const_iterator {
-    std::list<BugReport*>::const_iterator impl;
-  public:
-    const_iterator(std::list<BugReport*>::const_iterator i) : impl(i) {}
-    const_iterator &operator++() { ++impl; return *this; }
-    bool operator=3D=3D(const const_iterator &I) const { return I.impl =3D=
=3D impl; }
-    bool operator!=3D(const const_iterator &I) const { return I.impl !=3D =
impl; }
-    const BugReport* operator*() const { return *impl; }
-    const BugReport* operator->() const { return *impl; }
-  };
+  iterator begin() { return Reports.begin(); }
+  iterator end() { return Reports.end(); }
=20
-  iterator begin() { return iterator(Reports.begin()); }
-  iterator end() { return iterator(Reports.end()); }
-
-  const_iterator begin() const { return const_iterator(Reports.begin()); }
-  const_iterator end() const { return const_iterator(Reports.end()); }
+  const_iterator begin() const { return Reports.begin(); }
+  const_iterator end() const { return Reports.end(); }
 };
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -294,34 +357,22 @@
   /// reports.
   void EmitReport(BugReport *R);
=20
-  void EmitBasicReport(StringRef BugName, StringRef BugStr,
-                       PathDiagnosticLocation Loc,
-                       SourceRange* RangeBeg, unsigned NumRanges);
-
-  void EmitBasicReport(StringRef BugName, StringRef BugCategory,
+  void EmitBasicReport(const Decl *DeclWithIssue,
+                       StringRef BugName, StringRef BugCategory,
                        StringRef BugStr, PathDiagnosticLocation Loc,
                        SourceRange* RangeBeg, unsigned NumRanges);
=20
-
-  void EmitBasicReport(StringRef BugName, StringRef BugStr,
-                       PathDiagnosticLocation Loc) {
-    EmitBasicReport(BugName, BugStr, Loc, 0, 0);
+  void EmitBasicReport(const Decl *DeclWithIssue,
+                       StringRef BugName, StringRef BugCategory,
+                       StringRef BugStr, PathDiagnosticLocation Loc) {
+    EmitBasicReport(DeclWithIssue, BugName, BugCategory, BugStr, Loc, 0, 0=
);
   }
=20
-  void EmitBasicReport(StringRef BugName, StringRef BugCategory,
-                       StringRef BugStr, PathDiagnosticLocation Loc) {
-    EmitBasicReport(BugName, BugCategory, BugStr, Loc, 0, 0);
-  }
-
-  void EmitBasicReport(StringRef BugName, StringRef BugStr,
-                       PathDiagnosticLocation Loc, SourceRange R) {
-    EmitBasicReport(BugName, BugStr, Loc, &R, 1);
-  }
-
-  void EmitBasicReport(StringRef BugName, StringRef Category,
+  void EmitBasicReport(const Decl *DeclWithIssue,
+                       StringRef BugName, StringRef Category,
                        StringRef BugStr, PathDiagnosticLocation Loc,
                        SourceRange R) {
-    EmitBasicReport(BugName, Category, BugStr, Loc, &R, 1);
+    EmitBasicReport(DeclWithIssue, BugName, Category, BugStr, Loc, &R, 1);
   }
=20
   static bool classof(const BugReporter* R) { return true; }
@@ -337,7 +388,6 @@
 // FIXME: Get rid of GRBugReporter.  It's the wrong abstraction.
 class GRBugReporter : public BugReporter {
   ExprEngine& Eng;
-  llvm::SmallSet<SymbolRef, 10> NotableSymbols;
 public:
   GRBugReporter(BugReporterData& d, ExprEngine& eng)
     : BugReporter(d, GRBugReporterKind), Eng(eng) {}
@@ -359,14 +409,6 @@
   virtual void GeneratePathDiagnostic(PathDiagnostic &pathDiagnostic,
                      SmallVectorImpl<BugReport*> &bugReports);
=20
-  void addNotableSymbol(SymbolRef Sym) {
-    NotableSymbols.insert(Sym);
-  }
-
-  bool isNotable(SymbolRef Sym) const {
-    return (bool) NotableSymbols.count(Sym);
-  }
-
   /// classof - Used by isa<>, cast<>, and dyn_cast<>.
   static bool classof(const BugReporter* R) {
     return R->getKind() =3D=3D GRBugReporterKind;
@@ -374,6 +416,7 @@
 };
=20
 class BugReporterContext {
+  virtual void anchor();
   GRBugReporter &BR;
 public:
   BugReporterContext(GRBugReporter& br) : BR(br) {}
@@ -384,16 +427,6 @@
=20
   ExplodedGraph &getGraph() { return BR.getGraph(); }
=20
-  void addNotableSymbol(SymbolRef Sym) {
-    // FIXME: For now forward to GRBugReporter.
-    BR.addNotableSymbol(Sym);
-  }
-
-  bool isNotable(SymbolRef Sym) const {
-    // FIXME: For now forward to GRBugReporter.
-    return BR.isNotable(Sym);
-  }
-
   ProgramStateManager& getStateManager() {
     return BR.getStateManager();
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/BugReporterVisitor.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/BugReporterVisitor.h	Tue Apr 17 11:51:51 2012 +0300
@@ -28,10 +28,28 @@
 class MemRegion;
 class PathDiagnosticPiece;
=20
+/// \brief BugReporterVisitors are used to add custom diagnostics along a =
path.
+///
+/// Custom visitors should subclass the BugReporterVisitorImpl class for a
+/// default implementation of the clone() method.
+/// (Warning: if you have a deep subclass of BugReporterVisitorImpl, the
+/// default implementation of clone() will NOT do the right thing, and you
+/// will have to provide your own implementation.)
 class BugReporterVisitor : public llvm::FoldingSetNode {
 public:
   virtual ~BugReporterVisitor();
=20
+  /// \brief Returns a copy of this BugReporter.
+  ///
+  /// Custom BugReporterVisitors should not override this method directly.
+  /// Instead, they should inherit from BugReporterVisitorImpl and provide
+  /// a protected or public copy constructor.
+  ///
+  /// (Warning: if you have a deep subclass of BugReporterVisitorImpl, the
+  /// default implementation of clone() will NOT do the right thing, and y=
ou
+  /// will have to provide your own implementation.)
+  virtual BugReporterVisitor *clone() const =3D 0;
+
   /// \brief Return a diagnostic piece which should be associated with the
   /// given node.
   ///
@@ -61,7 +79,24 @@
=20
 };
=20
-class FindLastStoreBRVisitor : public BugReporterVisitor {
+/// This class provides a convenience implementation for clone() using the
+/// Curiously-Recurring Template Pattern. If you are implementing a custom
+/// BugReporterVisitor, subclass BugReporterVisitorImpl and provide a publ=
ic
+/// or protected copy constructor.
+///
+/// (Warning: if you have a deep subclass of BugReporterVisitorImpl, the
+/// default implementation of clone() will NOT do the right thing, and you
+/// will have to provide your own implementation.)
+template <class DERIVED>
+class BugReporterVisitorImpl : public BugReporterVisitor {
+  virtual BugReporterVisitor *clone() const {
+    return new DERIVED(*static_cast<const DERIVED *>(this));
+  }
+};
+
+class FindLastStoreBRVisitor
+  : public BugReporterVisitorImpl<FindLastStoreBRVisitor>
+{
   const MemRegion *R;
   SVal V;
   bool satisfied;
@@ -94,7 +129,9 @@
                                  BugReport &BR);
 };
=20
-class TrackConstraintBRVisitor : public BugReporterVisitor {
+class TrackConstraintBRVisitor
+  : public BugReporterVisitorImpl<TrackConstraintBRVisitor>
+{
   DefinedSVal Constraint;
   const bool Assumption;
   bool isSatisfied;
@@ -111,7 +148,9 @@
                                  BugReport &BR);
 };
=20
-class NilReceiverBRVisitor : public BugReporterVisitor {
+class NilReceiverBRVisitor
+  : public BugReporterVisitorImpl<NilReceiverBRVisitor>
+{
 public:
   void Profile(llvm::FoldingSetNodeID &ID) const {
     static int x =3D 0;
@@ -125,50 +164,71 @@
 };
=20
 /// Visitor that tries to report interesting diagnostics from conditions.
-class ConditionBRVisitor : public BugReporterVisitor {
+class ConditionBRVisitor : public BugReporterVisitorImpl<ConditionBRVisito=
r> {
 public:
   void Profile(llvm::FoldingSetNodeID &ID) const {
     static int x =3D 0;
     ID.AddPointer(&x);
   }
=20
+ =20
   virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
                                          const ExplodedNode *Prev,
                                          BugReporterContext &BRC,
                                          BugReport &BR);
=20
+  PathDiagnosticPiece *VisitNodeImpl(const ExplodedNode *N,
+                                     const ExplodedNode *Prev,
+                                     BugReporterContext &BRC,
+                                     BugReport &BR);
+ =20
   PathDiagnosticPiece *VisitTerminator(const Stmt *Term,
                                        const ExplodedNode *N,
                                        const CFGBlock *srcBlk,
                                        const CFGBlock *dstBlk,
+                                       BugReport &R,
                                        BugReporterContext &BRC);
=20
   PathDiagnosticPiece *VisitTrueTest(const Expr *Cond,
                                      bool tookTrue,
                                      BugReporterContext &BRC,
-                                     const LocationContext *LC);
+                                     BugReport &R,
+                                     const ExplodedNode *N);
=20
   PathDiagnosticPiece *VisitTrueTest(const Expr *Cond,
                                      const DeclRefExpr *DR,
                                      const bool tookTrue,
                                      BugReporterContext &BRC,
-                                     const LocationContext *LC);
+                                     BugReport &R,
+                                     const ExplodedNode *N);
=20
   PathDiagnosticPiece *VisitTrueTest(const Expr *Cond,
                                      const BinaryOperator *BExpr,
                                      const bool tookTrue,
                                      BugReporterContext &BRC,
-                                     const LocationContext *LC);
+                                     BugReport &R,
+                                     const ExplodedNode *N);
+ =20
+  PathDiagnosticPiece *VisitConditionVariable(StringRef LhsString,
+                                              const Expr *CondVarExpr,
+                                              const bool tookTrue,
+                                              BugReporterContext &BRC,
+                                              BugReport &R,
+                                              const ExplodedNode *N);
=20
   bool patternMatch(const Expr *Ex,
                     llvm::raw_ostream &Out,
-                    BugReporterContext &BRC);
+                    BugReporterContext &BRC,
+                    BugReport &R,
+                    const ExplodedNode *N,
+                    llvm::Optional<bool> &prunable);
 };
-
+ =20
 namespace bugreporter {
=20
 BugReporterVisitor *getTrackNullOrUndefValueVisitor(const ExplodedNode *N,
-                                                    const Stmt *S);
+                                                    const Stmt *S,
+                                                    BugReport *R);
=20
 const Stmt *GetDerefExpr(const ExplodedNode *N);
 const Stmt *GetDenomExpr(const ExplodedNode *N);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/BugReporter/BugType.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/BugType.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/BugType.h	Tue Apr 17 11:51:51 2012 +0300
@@ -49,6 +49,7 @@
 };
=20
 class BuiltinBug : public BugType {
+  virtual void anchor();
   const std::string desc;
 public:
   BuiltinBug(const char *name, const char *description)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/PathDiagnostic.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/BugRe=
porter/PathDiagnostic.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,9 +14,12 @@
 #ifndef LLVM_CLANG_PATH_DIAGNOSTIC_H
 #define LLVM_CLANG_PATH_DIAGNOSTIC_H
=20
-#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Analysis/ProgramPoint.h"
 #include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/Optional.h"
 #include <deque>
 #include <iterator>
 #include <string>
@@ -24,7 +27,7 @@
=20
 namespace clang {
=20
-class AnalysisContext;
+class AnalysisDeclContext;
 class BinaryOperator;
 class CompoundStmt;
 class Decl;
@@ -38,6 +41,8 @@
 namespace ento {
=20
 class ExplodedNode;
+class SymExpr;
+typedef const SymExpr* SymbolRef;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // High-level interface for handlers of path-sensitive diagnostics.
@@ -46,33 +51,34 @@
 class PathDiagnostic;
=20
 class PathDiagnosticConsumer {
+  virtual void anchor();
 public:
-  PathDiagnosticConsumer() {}
+  PathDiagnosticConsumer() : flushed(false) {}
+  virtual ~PathDiagnosticConsumer();
=20
-  virtual ~PathDiagnosticConsumer() {}
- =20
-  virtual void
-  FlushDiagnostics(SmallVectorImpl<std::string> *FilesMade =3D 0) =3D 0;
- =20
-  void FlushDiagnostics(SmallVectorImpl<std::string> &FilesMade) {
-    FlushDiagnostics(&FilesMade);
-  }
- =20
+  void FlushDiagnostics(SmallVectorImpl<std::string> *FilesMade);
+
+  virtual void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &D=
iags,
+                                    SmallVectorImpl<std::string> *FilesMad=
e)
+                                    =3D 0;
+
   virtual StringRef getName() const =3D 0;
  =20
-  void HandlePathDiagnostic(const PathDiagnostic* D);
+  void HandlePathDiagnostic(PathDiagnostic *D);
=20
   enum PathGenerationScheme { Minimal, Extensive };
   virtual PathGenerationScheme getGenerationScheme() const { return Minima=
l; }
   virtual bool supportsLogicalOpControlFlow() const { return false; }
   virtual bool supportsAllBlockEdges() const { return false; }
   virtual bool useVerboseDescription() const { return true; }
+ =20
+  /// Return true if the PathDiagnosticConsumer supports individual
+  /// PathDiagnostics that span multiple files.
+  virtual bool supportsCrossFileDiagnostics() const { return false; }
=20
 protected:
-  /// The actual logic for handling path diagnostics, as implemented
-  /// by subclasses of PathDiagnosticConsumer.
-  virtual void HandlePathDiagnosticImpl(const PathDiagnostic* D) =3D 0;
-
+  bool flushed;
+  llvm::FoldingSet<PathDiagnostic> Diags;
 };
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -89,8 +95,8 @@
   PathDiagnosticRange() : isPoint(false) {}
 };
=20
-typedef llvm::PointerUnion<const LocationContext*, AnalysisContext*>
-                                                   LocationOrAnalysisConte=
xt;
+typedef llvm::PointerUnion<const LocationContext*, AnalysisDeclContext*>
+                                                   LocationOrAnalysisDeclC=
ontext;
=20
 class PathDiagnosticLocation {
 private:
@@ -111,10 +117,10 @@
=20
   FullSourceLoc
     genLocation(SourceLocation L =3D SourceLocation(),
-                LocationOrAnalysisContext LAC =3D (AnalysisContext*)0) con=
st;
+                LocationOrAnalysisDeclContext LAC =3D (AnalysisDeclContext=
*)0) const;
=20
   PathDiagnosticRange
-    genRange(LocationOrAnalysisContext LAC =3D (AnalysisContext*)0) const;
+    genRange(LocationOrAnalysisDeclContext LAC =3D (AnalysisDeclContext*)0=
) const;
=20
 public:
   /// Create an invalid location.
@@ -124,10 +130,11 @@
   /// Create a location corresponding to the given statement.
   PathDiagnosticLocation(const Stmt *s,
                          const SourceManager &sm,
-                         LocationOrAnalysisContext lac)
+                         LocationOrAnalysisDeclContext lac)
     : K(StmtK), S(s), D(0), SM(&sm),
       Loc(genLocation(SourceLocation(), lac)),
       Range(genRange(lac)) {
+    assert(S);
     assert(Loc.isValid());
     assert(Range.isValid());
   }
@@ -136,6 +143,7 @@
   PathDiagnosticLocation(const Decl *d, const SourceManager &sm)
     : K(DeclK), S(0), D(d), SM(&sm),
       Loc(genLocation()), Range(genRange()) {
+    assert(D);
     assert(Loc.isValid());
     assert(Range.isValid());
   }
@@ -153,7 +161,7 @@
   /// Create a location for the beginning of the statement.
   static PathDiagnosticLocation createBegin(const Stmt *S,
                                             const SourceManager &SM,
-                                            const LocationOrAnalysisContex=
t LAC);
+                                            const LocationOrAnalysisDeclCo=
ntext LAC);
=20
   /// Create the location for the operator of the binary expression.
   /// Assumes the statement has a valid location.
@@ -260,14 +268,13 @@
 // Path "pieces" for path-sensitive diagnostics.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-class PathDiagnosticPiece {
+class PathDiagnosticPiece : public RefCountedBaseVPTR {
 public:
-  enum Kind { ControlFlow, Event, Macro };
+  enum Kind { ControlFlow, Event, Macro, Call };
   enum DisplayHint { Above, Below };
=20
 private:
   const std::string str;
-  std::vector<FixItHint> FixItHints;
   const Kind kind;
   const DisplayHint Hint;
   std::vector<SourceRange> ranges;
@@ -308,10 +315,6 @@
     ranges.push_back(SourceRange(B,E));
   }
=20
-  void addFixItHint(const FixItHint& Hint) {
-    FixItHints.push_back(Hint);
-  }
-
   typedef const SourceRange* range_iterator;
=20
   range_iterator ranges_begin() const {
@@ -322,23 +325,19 @@
     return ranges_begin() + ranges.size();
   }
=20
-  typedef const FixItHint *fixit_iterator;
-
-  fixit_iterator fixit_begin() const {
-    return FixItHints.empty()? 0 : &FixItHints[0];
-  }
-
-  fixit_iterator fixit_end() const {
-    return FixItHints.empty()? 0
-                   : &FixItHints[0] + FixItHints.size();
-  }
-
   static inline bool classof(const PathDiagnosticPiece *P) {
     return true;
   }
  =20
   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
 };
+ =20
+ =20
+class PathPieces :
+  public std::deque<IntrusiveRefCntPtr<PathDiagnosticPiece> > {
+public:
+  ~PathPieces(); =20
+};
=20
 class PathDiagnosticSpotPiece : public PathDiagnosticPiece {
 private:
@@ -360,20 +359,170 @@
   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
 };
=20
+/// \brief Interface for classes constructing Stack hints.
+///
+/// If a PathDiagnosticEvent occurs in a different frame than the final=20
+/// diagnostic the hints can be used to summarise the effect of the call.
+class StackHintGenerator {
+public:
+  virtual ~StackHintGenerator() =3D 0;
+
+  /// \brief Construct the Diagnostic message for the given ExplodedNode.
+  virtual std::string getMessage(const ExplodedNode *N) =3D 0;
+};
+
+/// \brief Constructs a Stack hint for the given symbol.
+///
+/// The class knows how to construct the stack hint message based on
+/// traversing the CallExpr associated with the call and checking if the g=
iven
+/// symbol is returned or is one of the arguments.
+/// The hint can be customized by redefining 'getMessageForX()' methods.
+class StackHintGeneratorForSymbol : public StackHintGenerator {
+private:
+  SymbolRef Sym;
+  std::string Msg;
+
+public:
+  StackHintGeneratorForSymbol(SymbolRef S, StringRef M) : Sym(S), Msg(M) {}
+  virtual ~StackHintGeneratorForSymbol() {}
+
+  /// \brief Search the call expression for the symbol Sym and dispatch the
+  /// 'getMessageForX()' methods to construct a specific message.
+  virtual std::string getMessage(const ExplodedNode *N);
+
+  /// Prints the ordinal form of the given integer,
+  /// only valid for ValNo : ValNo > 0.
+  void printOrdinal(unsigned ValNo, llvm::raw_svector_ostream &Out);
+
+  /// Produces the message of the following form:
+  ///   'Msg via Nth parameter'
+  virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex=
);
+  virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
+    return Msg;
+  }
+  virtual std::string getMessageForSymbolNotFound() {
+    return Msg;
+  }
+};
+
 class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece {
+  llvm::Optional<bool> IsPrunable;
+
+  /// If the event occurs in a different frame than the final diagnostic,
+  /// supply a message that will be used to construct an extra hint on the
+  /// returns from all the calls on the stack from this event to the final
+  /// diagnostic.
+  llvm::OwningPtr<StackHintGenerator> CallStackHint;
=20
 public:
   PathDiagnosticEventPiece(const PathDiagnosticLocation &pos,
-                           StringRef s, bool addPosRange =3D true)
-    : PathDiagnosticSpotPiece(pos, s, Event, addPosRange) {}
+                           StringRef s, bool addPosRange =3D true,
+                           StackHintGenerator *stackHint =3D 0)
+    : PathDiagnosticSpotPiece(pos, s, Event, addPosRange),
+      CallStackHint(stackHint) {}
=20
   ~PathDiagnosticEventPiece();
=20
+  /// Mark the diagnostic piece as being potentially prunable.  This
+  /// flag may have been previously set, at which point it will not
+  /// be reset unless one specifies to do so.
+  void setPrunable(bool isPrunable, bool override =3D false) {
+    if (IsPrunable.hasValue() && !override)
+     return;
+    IsPrunable =3D isPrunable;
+  }
+
+  /// Return true if the diagnostic piece is prunable.
+  bool isPrunable() const {
+    return IsPrunable.hasValue() ? IsPrunable.getValue() : false;
+  }
+ =20
+  bool hasCallStackHint() {
+    return (CallStackHint !=3D 0);
+  }
+
+  /// Produce the hint for the given node. The node contains=20
+  /// information about the call for which the diagnostic can be generated.
+  std::string getCallStackMessage(const ExplodedNode *N) {
+    if (CallStackHint)
+      return CallStackHint->getMessage(N);
+    return ""; =20
+  }
+
   static inline bool classof(const PathDiagnosticPiece *P) {
     return P->getKind() =3D=3D Event;
   }
 };
=20
+class PathDiagnosticCallPiece : public PathDiagnosticPiece {
+  PathDiagnosticCallPiece(const Decl *callerD,
+                          const PathDiagnosticLocation &callReturnPos)
+    : PathDiagnosticPiece(Call), Caller(callerD), Callee(0),
+      NoExit(false), callReturn(callReturnPos) {}
+
+  PathDiagnosticCallPiece(PathPieces &oldPath, const Decl *caller)
+    : PathDiagnosticPiece(Call), Caller(caller), Callee(0),
+      NoExit(true), path(oldPath) {}
+ =20
+  const Decl *Caller;
+  const Decl *Callee;
+
+  // Flag signifying that this diagnostic has only call enter and no match=
ing
+  // call exit.
+  bool NoExit;
+
+  // The custom string, which should appear after the call Return Diagnost=
ic.
+  // TODO: Should we allow multiple diagnostics?
+  std::string CallStackMessage;
+
+public:
+  PathDiagnosticLocation callEnter;
+  PathDiagnosticLocation callEnterWithin;
+  PathDiagnosticLocation callReturn; =20
+  PathPieces path;
+ =20
+  virtual ~PathDiagnosticCallPiece();
+ =20
+  const Decl *getCaller() const { return Caller; }
+ =20
+  const Decl *getCallee() const { return Callee; }
+  void setCallee(const CallEnter &CE, const SourceManager &SM);
+ =20
+  bool hasCallStackMessage() { return !CallStackMessage.empty(); }
+  void setCallStackMessage(StringRef st) {
+    CallStackMessage =3D st;
+  }
+
+  virtual PathDiagnosticLocation getLocation() const {
+    return callEnter;
+  }
+ =20
+  IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallEnterEvent() const;
+  IntrusiveRefCntPtr<PathDiagnosticEventPiece>
+    getCallEnterWithinCallerEvent() const;
+  IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallExitEvent() const;
+
+  virtual void flattenLocations() {
+    callEnter.flatten();
+    callReturn.flatten();
+    for (PathPieces::iterator I =3D path.begin(),=20
+         E =3D path.end(); I !=3D E; ++I) (*I)->flattenLocations();
+  }
+ =20
+  static PathDiagnosticCallPiece *construct(const ExplodedNode *N,
+                                            const CallExit &CE,
+                                            const SourceManager &SM);
+ =20
+  static PathDiagnosticCallPiece *construct(PathPieces &pieces,
+                                            const Decl *caller);
+ =20
+  virtual void Profile(llvm::FoldingSetNodeID &ID) const;
+
+  static inline bool classof(const PathDiagnosticPiece *P) {
+    return P->getKind() =3D=3D Call;
+  }
+};
+
 class PathDiagnosticControlFlowPiece : public PathDiagnosticPiece {
   std::vector<PathDiagnosticLocationPair> LPairs;
 public:
@@ -431,30 +580,22 @@
 };
=20
 class PathDiagnosticMacroPiece : public PathDiagnosticSpotPiece {
-  std::vector<PathDiagnosticPiece*> SubPieces;
 public:
   PathDiagnosticMacroPiece(const PathDiagnosticLocation &pos)
     : PathDiagnosticSpotPiece(pos, "", Macro) {}
=20
   ~PathDiagnosticMacroPiece();
=20
+  PathPieces subPieces;
+ =20
   bool containsEvent() const;
=20
-  void push_back(PathDiagnosticPiece *P) { SubPieces.push_back(P); }
-
-  typedef std::vector<PathDiagnosticPiece*>::iterator iterator;
-  iterator begin() { return SubPieces.begin(); }
-  iterator end() { return SubPieces.end(); }
-
   virtual void flattenLocations() {
     PathDiagnosticSpotPiece::flattenLocations();
-    for (iterator I=3Dbegin(), E=3Dend(); I!=3DE; ++I) (*I)->flattenLocati=
ons();
+    for (PathPieces::iterator I =3D subPieces.begin(),=20
+         E =3D subPieces.end(); I !=3D E; ++I) (*I)->flattenLocations();
   }
=20
-  typedef std::vector<PathDiagnosticPiece*>::const_iterator const_iterator;
-  const_iterator begin() const { return SubPieces.begin(); }
-  const_iterator end() const { return SubPieces.end(); }
-
   static inline bool classof(const PathDiagnosticPiece *P) {
     return P->getKind() =3D=3D Macro;
   }
@@ -466,17 +607,41 @@
 ///  diagnostic.  It represents an ordered-collection of PathDiagnosticPie=
ces,
 ///  each which represent the pieces of the path.
 class PathDiagnostic : public llvm::FoldingSetNode {
-  std::deque<PathDiagnosticPiece*> path;
-  unsigned Size;
+  const Decl *DeclWithIssue;
   std::string BugType;
   std::string Desc;
   std::string Category;
   std::deque<std::string> OtherDesc;
+  PathPieces pathImpl;
+  llvm::SmallVector<PathPieces *, 3> pathStack;
+ =20
+  PathDiagnostic(); // Do not implement.
+public:
+  const PathPieces &path;
=20
-public:
-  PathDiagnostic();
+  /// Return the path currently used by builders for constructing the=20
+  /// PathDiagnostic.
+  PathPieces &getActivePath() {
+    if (pathStack.empty())
+      return pathImpl;
+    return *pathStack.back();
+  }
+ =20
+  /// Return a mutable version of 'path'.
+  PathPieces &getMutablePieces() {
+    return pathImpl;
+  }
+   =20
+  /// Return the unrolled size of the path.
+  unsigned full_size();
=20
-  PathDiagnostic(StringRef bugtype, StringRef desc,
+  void pushActivePath(PathPieces *p) { pathStack.push_back(p); }
+  void popActivePath() { if (!pathStack.empty()) pathStack.pop_back(); }
+ =20
+  //  PathDiagnostic();
+  PathDiagnostic(const Decl *DeclWithIssue,
+                 StringRef bugtype,
+                 StringRef desc,
                  StringRef category);
=20
   ~PathDiagnostic();
@@ -485,115 +650,26 @@
   StringRef getBugType() const { return BugType; }
   StringRef getCategory() const { return Category; }
=20
+  /// Return the semantic context where an issue occurred.  If the
+  /// issue occurs along a path, this represents the "central" area
+  /// where the bug manifests.
+  const Decl *getDeclWithIssue() const { return DeclWithIssue; }
+
   typedef std::deque<std::string>::const_iterator meta_iterator;
   meta_iterator meta_begin() const { return OtherDesc.begin(); }
   meta_iterator meta_end() const { return OtherDesc.end(); }
   void addMeta(StringRef s) { OtherDesc.push_back(s); }
=20
-  PathDiagnosticLocation getLocation() const {
-    assert(Size > 0 && "getLocation() requires a non-empty PathDiagnostic.=
");
-    return rbegin()->getLocation();
-  }
-
-  void push_front(PathDiagnosticPiece *piece) {
-    assert(piece);
-    path.push_front(piece);
-    ++Size;
-  }
-
-  void push_back(PathDiagnosticPiece *piece) {
-    assert(piece);
-    path.push_back(piece);
-    ++Size;
-  }
-
-  PathDiagnosticPiece *back() {
-    return path.back();
-  }
-
-  const PathDiagnosticPiece *back() const {
-    return path.back();
-  }
-
-  unsigned size() const { return Size; }
-  bool empty() const { return Size =3D=3D 0; }
-
-  void resetPath(bool deletePieces =3D true);
-
-  class iterator {
-  public:
-    typedef std::deque<PathDiagnosticPiece*>::iterator ImplTy;
-
-    typedef PathDiagnosticPiece              value_type;
-    typedef value_type&                      reference;
-    typedef value_type*                      pointer;
-    typedef ptrdiff_t                        difference_type;
-    typedef std::bidirectional_iterator_tag  iterator_category;
-
-  private:
-    ImplTy I;
-
-  public:
-    iterator(const ImplTy& i) : I(i) {}
-
-    bool operator=3D=3D(const iterator &X) const { return I =3D=3D X.I; }
-    bool operator!=3D(const iterator &X) const { return I !=3D X.I; }
-
-    PathDiagnosticPiece& operator*() const { return **I; }
-    PathDiagnosticPiece *operator->() const { return *I; }
-
-    iterator &operator++() { ++I; return *this; }
-    iterator &operator--() { --I; return *this; }
-  };
-
-  class const_iterator {
-  public:
-    typedef std::deque<PathDiagnosticPiece*>::const_iterator ImplTy;
-
-    typedef const PathDiagnosticPiece        value_type;
-    typedef value_type&                      reference;
-    typedef value_type*                      pointer;
-    typedef ptrdiff_t                        difference_type;
-    typedef std::bidirectional_iterator_tag  iterator_category;
-
-  private:
-    ImplTy I;
-
-  public:
-    const_iterator(const ImplTy& i) : I(i) {}
-
-    bool operator=3D=3D(const const_iterator &X) const { return I =3D=3D X=
.I; }
-    bool operator!=3D(const const_iterator &X) const { return I !=3D X.I; }
-
-    reference operator*() const { return **I; }
-    pointer operator->() const { return *I; }
-
-    const_iterator &operator++() { ++I; return *this; }
-    const_iterator &operator--() { --I; return *this; }
-  };
-
-  typedef std::reverse_iterator<iterator>       reverse_iterator;
-  typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
-
-  // forward iterator creation methods.
-
-  iterator begin() { return path.begin(); }
-  iterator end() { return path.end(); }
-
-  const_iterator begin() const { return path.begin(); }
-  const_iterator end() const { return path.end(); }
-
-  // reverse iterator creation methods.
-  reverse_iterator rbegin()            { return reverse_iterator(end()); }
-  const_reverse_iterator rbegin() const{ return const_reverse_iterator(end=
()); }
-  reverse_iterator rend()              { return reverse_iterator(begin());=
 }
-  const_reverse_iterator rend() const { return const_reverse_iterator(begi=
n());}
+  PathDiagnosticLocation getLocation() const;
=20
   void flattenLocations() {
-    for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I) I->flattenLoc=
ations();
+    for (PathPieces::iterator I =3D pathImpl.begin(), E =3D pathImpl.end()=
;=20
+         I !=3D E; ++I) (*I)->flattenLocations();
   }
  =20
   void Profile(llvm::FoldingSetNodeID &ID) const;
+ =20
+  void FullProfile(llvm::FoldingSetNodeID &ID) const;
 }; =20
=20
 } // end GR namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/Checker.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Check=
er.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Check=
er.h	Tue Apr 17 11:51:51 2012 +0300
@@ -199,9 +199,9 @@
=20
 class EndPath {
   template <typename CHECKER>
-  static void _checkEndPath(void *checker, EndOfFunctionNodeBuilder &B,
-                            ExprEngine &Eng) {
-    ((const CHECKER *)checker)->checkEndPath(B, Eng);
+  static void _checkEndPath(void *checker,
+                            CheckerContext &C) {
+    ((const CHECKER *)checker)->checkEndPath(C);
   }
=20
 public:
@@ -214,9 +214,9 @@
=20
 class BranchCondition {
   template <typename CHECKER>
-  static void _checkBranchCondition(void *checker, const Stmt *condition,
-                                    BranchNodeBuilder &B, ExprEngine &Eng)=
 {
-    ((const CHECKER *)checker)->checkBranchCondition(condition, B, Eng);
+  static void _checkBranchCondition(void *checker, const Stmt *Condition,
+                                    CheckerContext & C) {
+    ((const CHECKER *)checker)->checkBranchCondition(Condition, C);
   }
=20
 public:
@@ -230,7 +230,7 @@
=20
 class LiveSymbols {
   template <typename CHECKER>
-  static void _checkLiveSymbols(void *checker, const ProgramState *state,
+  static void _checkLiveSymbols(void *checker, ProgramStateRef state,
                                 SymbolReaper &SR) {
     ((const CHECKER *)checker)->checkLiveSymbols(state, SR);
   }
@@ -260,18 +260,19 @@
=20
 class RegionChanges {
   template <typename CHECKER>
-  static const ProgramState *
+  static ProgramStateRef=20
   _checkRegionChanges(void *checker,
-                      const ProgramState *state,
+                      ProgramStateRef state,
                       const StoreManager::InvalidatedSymbols *invalidated,
                       ArrayRef<const MemRegion *> Explicits,
-                      ArrayRef<const MemRegion *> Regions) {
+                      ArrayRef<const MemRegion *> Regions,
+                      const CallOrObjCMessage *Call) {
     return ((const CHECKER *)checker)->checkRegionChanges(state, invalidat=
ed,
-                                                          Explicits, Regio=
ns);
+                                                      Explicits, Regions, =
Call);
   }
   template <typename CHECKER>
   static bool _wantsRegionChangeUpdate(void *checker,
-                                       const ProgramState *state) {
+                                       ProgramStateRef state) {
     return ((const CHECKER *)checker)->wantsRegionChangeUpdate(state);
   }
=20
@@ -306,8 +307,8 @@
=20
 class Assume {
   template <typename CHECKER>
-  static const ProgramState *_evalAssume(void *checker,
-                                         const ProgramState *state,
+  static ProgramStateRef _evalAssume(void *checker,
+                                         ProgramStateRef state,
                                          const SVal &cond,
                                          bool assumption) {
     return ((const CHECKER *)checker)->evalAssume(state, cond, assumption);
@@ -359,7 +360,7 @@
   StringRef getTagDescription() const;
=20
   /// See CheckerManager::runCheckersForPrintState.
-  virtual void printState(raw_ostream &Out, const ProgramState *State,
+  virtual void printState(raw_ostream &Out, ProgramStateRef State,
                           const char *NL, const char *Sep) const { }
 };
  =20
@@ -370,7 +371,8 @@
           typename CHECK9=3Dcheck::_VoidCheck, typename CHECK10=3Dcheck::_=
VoidCheck,
           typename CHECK11=3Dcheck::_VoidCheck,typename CHECK12=3Dcheck::_=
VoidCheck,
           typename CHECK13=3Dcheck::_VoidCheck,typename CHECK14=3Dcheck::_=
VoidCheck,
-          typename CHECK15=3Dcheck::_VoidCheck,typename CHECK16=3Dcheck::_=
VoidCheck>
+          typename CHECK15=3Dcheck::_VoidCheck,typename CHECK16=3Dcheck::_=
VoidCheck,
+          typename CHECK17=3Dcheck::_VoidCheck,typename CHECK18=3Dcheck::_=
VoidCheck>
 class Checker;
=20
 template <>
@@ -379,9 +381,10 @@
                 check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
                 check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
                 check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
-                check::_VoidCheck>=20
+                check::_VoidCheck, check::_VoidCheck, check::_VoidCheck>
   : public CheckerBase=20
 {
+  virtual void anchor();
 public:
   static void _register(void *checker, CheckerManager &mgr) { }
 };
@@ -389,19 +392,20 @@
 template <typename CHECK1, typename CHECK2, typename CHECK3, typename CHEC=
K4,
           typename CHECK5, typename CHECK6, typename CHECK7, typename CHEC=
K8,
           typename CHECK9, typename CHECK10,typename CHECK11,typename CHEC=
K12,
-          typename CHECK13,typename CHECK14,typename CHECK15,typename CHEC=
K16>
+          typename CHECK13,typename CHECK14,typename CHECK15,typename CHEC=
K16,
+          typename CHECK17,typename CHECK18>
 class Checker
     : public CHECK1,
       public Checker<CHECK2, CHECK3, CHECK4, CHECK5, CHECK6, CHECK7, CHECK=
8,
                      CHECK9, CHECK10,CHECK11,CHECK12,CHECK13,CHECK14,CHECK=
15,
-                     CHECK16> {
+                     CHECK16,CHECK17,CHECK18> {
 public:
   template <typename CHECKER>
   static void _register(CHECKER *checker, CheckerManager &mgr) {
     CHECK1::_register(checker, mgr);
     Checker<CHECK2, CHECK3, CHECK4, CHECK5, CHECK6, CHECK7, CHECK8,
             CHECK9, CHECK10,CHECK11,CHECK12,CHECK13,CHECK14,CHECK15,
-            CHECK16>::_register(checker, mgr);
+            CHECK16,CHECK17,CHECK18>::_register(checker, mgr);
   }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/CheckerManager.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Check=
erManager.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Check=
erManager.h	Tue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
+#include "clang/Analysis/ProgramPoint.h"
 #include <vector>
=20
 namespace clang {
@@ -38,8 +39,8 @@
   class ExplodedNodeSet;
   class ExplodedGraph;
   class ProgramState;
-  class EndOfFunctionNodeBuilder;
-  class BranchNodeBuilder;
+  class NodeBuilder;
+  struct NodeBuilderContext;
   class MemRegion;
   class SymbolReaper;
=20
@@ -51,6 +52,19 @@
=20
 template <typename T> class CheckerFn;
=20
+template <typename RET, typename P1, typename P2, typename P3, typename P4,
+          typename P5>
+class CheckerFn<RET(P1, P2, P3, P4, P5)> {
+  typedef RET (*Func)(void *, P1, P2, P3, P4, P5);
+  Func Fn;
+public:
+  CheckerBase *Checker;
+  CheckerFn(CheckerBase *checker, Func fn) : Fn(fn), Checker(checker) { }
+  RET operator()(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) const {
+    return Fn(Checker, p1, p2, p3, p4, p5);
+  }
+};
+
 template <typename RET, typename P1, typename P2, typename P3, typename P4>
 class CheckerFn<RET(P1, P2, P3, P4)> {
   typedef RET (*Func)(void *, P1, P2, P3, P4);
@@ -114,7 +128,7 @@
=20
   void finishedCheckerRegistration();
=20
-  const LangOptions &getLangOptions() const { return LangOpts; }
+  const LangOptions &getLangOpts() const { return LangOpts; }
=20
   typedef CheckerBase *CheckerRef;
   typedef const void *CheckerTag;
@@ -179,14 +193,16 @@
   void runCheckersForPostStmt(ExplodedNodeSet &Dst,
                               const ExplodedNodeSet &Src,
                               const Stmt *S,
-                              ExprEngine &Eng) {
-    runCheckersForStmt(/*isPreVisit=3D*/false, Dst, Src, S, Eng);
+                              ExprEngine &Eng,
+                              bool wasInlined =3D false) {
+    runCheckersForStmt(/*isPreVisit=3D*/false, Dst, Src, S, Eng, wasInline=
d);
   }
=20
   /// \brief Run checkers for visiting Stmts.
   void runCheckersForStmt(bool isPreVisit,
                           ExplodedNodeSet &Dst, const ExplodedNodeSet &Src,
-                          const Stmt *S, ExprEngine &Eng);
+                          const Stmt *S, ExprEngine &Eng,
+                          bool wasInlined =3D false);
=20
   /// \brief Run checkers for pre-visiting obj-c messages.
   void runCheckersForPreObjCMessage(ExplodedNodeSet &Dst,
@@ -213,33 +229,39 @@
   /// \brief Run checkers for load/store of a location.
   void runCheckersForLocation(ExplodedNodeSet &Dst,
                               const ExplodedNodeSet &Src,
-                              SVal location, bool isLoad,
-                              const Stmt *S,
+                              SVal location,
+                              bool isLoad,
+                              const Stmt *NodeEx,
+                              const Stmt *BoundEx,
                               ExprEngine &Eng);
=20
   /// \brief Run checkers for binding of a value to a location.
   void runCheckersForBind(ExplodedNodeSet &Dst,
                           const ExplodedNodeSet &Src,
                           SVal location, SVal val,
-                          const Stmt *S, ExprEngine &Eng);
+                          const Stmt *S, ExprEngine &Eng,
+                          ProgramPoint::Kind PointKind);
=20
   /// \brief Run checkers for end of analysis.
   void runCheckersForEndAnalysis(ExplodedGraph &G, BugReporter &BR,
                                  ExprEngine &Eng);
=20
   /// \brief Run checkers for end of path.
-  void runCheckersForEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng);
+  void runCheckersForEndPath(NodeBuilderContext &BC,
+                             ExplodedNodeSet &Dst,
+                             ExprEngine &Eng);
=20
   /// \brief Run checkers for branch condition.
   void runCheckersForBranchCondition(const Stmt *condition,
-                                     BranchNodeBuilder &B, ExprEngine &Eng=
);
+                                     ExplodedNodeSet &Dst, ExplodedNode *P=
red,
+                                     ExprEngine &Eng);
=20
   /// \brief Run checkers for live symbols.
   ///
   /// Allows modifying SymbolReaper object. For example, checkers can expl=
icitly
   /// register symbols of interest as live. These symbols will not be mark=
ed
   /// dead and removed.
-  void runCheckersForLiveSymbols(const ProgramState *state,
+  void runCheckersForLiveSymbols(ProgramStateRef state,
                                  SymbolReaper &SymReaper);
=20
   /// \brief Run checkers for dead symbols.
@@ -253,7 +275,7 @@
                                  ExprEngine &Eng);
=20
   /// \brief True if at least one checker wants to check region changes.
-  bool wantsRegionChangeUpdate(const ProgramState *state);
+  bool wantsRegionChangeUpdate(ProgramStateRef state);
=20
   /// \brief Run checkers for region changes.
   ///
@@ -264,15 +286,18 @@
   ///   For example, in the case of a function call, these would be argume=
nts.
   /// \param Regions The transitive closure of accessible regions,
   ///   i.e. all regions that may have been touched by this change.
-  const ProgramState *
-  runCheckersForRegionChanges(const ProgramState *state,
+  /// \param The call expression wrapper if the regions are invalidated by=
 a
+  ///   call.
+  ProgramStateRef=20
+  runCheckersForRegionChanges(ProgramStateRef state,
                             const StoreManager::InvalidatedSymbols *invali=
dated,
                               ArrayRef<const MemRegion *> ExplicitRegions,
-                              ArrayRef<const MemRegion *> Regions);
+                              ArrayRef<const MemRegion *> Regions,
+                              const CallOrObjCMessage *Call);
=20
   /// \brief Run checkers for handling assumptions on symbolic values.
-  const ProgramState *runCheckersForEvalAssume(const ProgramState *state,
-                                          SVal Cond, bool Assumption);
+  ProgramStateRef runCheckersForEvalAssume(ProgramStateRef state,
+                                               SVal Cond, bool Assumption);
=20
   /// \brief Run checkers for evaluating a call.
   void runCheckersForEvalCall(ExplodedNodeSet &Dst,
@@ -293,7 +318,7 @@
   /// \param State The state being printed
   /// \param NL The preferred representation of a newline.
   /// \param Sep The preferred separator between different kinds of data.
-  void runCheckersForPrintState(raw_ostream &Out, const ProgramState *Stat=
e,
+  void runCheckersForPrintState(raw_ostream &Out, ProgramStateRef State,
                                 const char *NL, const char *Sep);
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -320,7 +345,8 @@
   typedef CheckerFn<void (const ObjCMessage &, CheckerContext &)>
       CheckObjCMessageFunc;
  =20
-  typedef CheckerFn<void (const SVal &location, bool isLoad, const Stmt *S,
+  typedef CheckerFn<void (const SVal &location, bool isLoad,
+                          const Stmt *S,
                           CheckerContext &)>
       CheckLocationFunc;
  =20
@@ -331,26 +357,27 @@
   typedef CheckerFn<void (ExplodedGraph &, BugReporter &, ExprEngine &)>
       CheckEndAnalysisFunc;
  =20
-  typedef CheckerFn<void (EndOfFunctionNodeBuilder &, ExprEngine &)>
+  typedef CheckerFn<void (CheckerContext &)>
       CheckEndPathFunc;
  =20
-  typedef CheckerFn<void (const Stmt *, BranchNodeBuilder &, ExprEngine &)>
+  typedef CheckerFn<void (const Stmt *, CheckerContext &)>
       CheckBranchConditionFunc;
  =20
   typedef CheckerFn<void (SymbolReaper &, CheckerContext &)>
       CheckDeadSymbolsFunc;
  =20
-  typedef CheckerFn<void (const ProgramState *,SymbolReaper &)> CheckLiveS=
ymbolsFunc;
+  typedef CheckerFn<void (ProgramStateRef,SymbolReaper &)> CheckLiveSymbol=
sFunc;
  =20
-  typedef CheckerFn<const ProgramState * (const ProgramState *,
+  typedef CheckerFn<ProgramStateRef (ProgramStateRef,
                                 const StoreManager::InvalidatedSymbols *sy=
mbols,
-                                    ArrayRef<const MemRegion *> ExplicitRe=
gions,
-                                          ArrayRef<const MemRegion *> Regi=
ons)>
+                                ArrayRef<const MemRegion *> ExplicitRegion=
s,
+                                ArrayRef<const MemRegion *> Regions,
+                                const CallOrObjCMessage *Call)>
       CheckRegionChangesFunc;
  =20
-  typedef CheckerFn<bool (const ProgramState *)> WantsRegionChangeUpdateFu=
nc;
+  typedef CheckerFn<bool (ProgramStateRef)> WantsRegionChangeUpdateFunc;
  =20
-  typedef CheckerFn<const ProgramState * (const ProgramState *,
+  typedef CheckerFn<ProgramStateRef (ProgramStateRef,
                                           const SVal &cond, bool assumptio=
n)>
       EvalAssumeFunc;
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/CheckerRegistry.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Check=
erRegistry.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/Check=
erRegistry.h	Tue Apr 17 11:51:51 2012 +0300
@@ -107,7 +107,9 @@
   /// checker does not require any custom initialization.
   template <class T>
   void addChecker(StringRef fullName, StringRef desc) {
-    addChecker(&initializeManager<T>, fullName, desc);
+    // Avoid MSVC's Compiler Error C2276:
+    // http://msdn.microsoft.com/en-us/library/850cstw1(v=3DVS.80).aspx
+    addChecker(&CheckerRegistry::initializeManager<T>, fullName, desc);
   }
=20
   /// Initializes a CheckerManager by calling the initialization functions=
 for
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathD=
iagnosticConsumers.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathD=
iagnosticConsumers.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,6 +32,10 @@
                               PathDiagnosticConsumer *SubPD =3D 0);
=20
 PathDiagnosticConsumer*
+createPlistMultiFileDiagnosticConsumer(const std::string& prefix,
+                                       const Preprocessor &PP);
+
+PathDiagnosticConsumer*
 createTextPathDiagnosticConsumer(const std::string& prefix,
                                  const Preprocessor &PP);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/AnalysisManager.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/AnalysisManager.h	Tue Apr 17 11:51:51 2012 +0300
@@ -31,14 +31,14 @@
   class CheckerManager;
=20
 class AnalysisManager : public BugReporterData {
-  AnalysisContextManager AnaCtxMgr;
-  LocationContextManager LocCtxMgr;
+  virtual void anchor();
+  AnalysisDeclContextManager AnaCtxMgr;
=20
   ASTContext &Ctx;
   DiagnosticsEngine &Diags;
-  const LangOptions &LangInfo;
+  const LangOptions &LangOpts;
=20
-  llvm::OwningPtr<PathDiagnosticConsumer> PD;
+  OwningPtr<PathDiagnosticConsumer> PD;
=20
   // Configurable components creators.
   StoreManagerCreator CreateStoreMgr;
@@ -53,29 +53,47 @@
=20
   enum AnalysisScope { ScopeTU, ScopeDecl } AScope;
=20
-  // The maximum number of exploded nodes the analyzer will generate.
+  /// \brief The maximum number of exploded nodes the analyzer will genera=
te.
   unsigned MaxNodes;
=20
-  // The maximum number of times the analyzer visit a block.
+  /// \brief The maximum number of times the analyzer visits a block.
   unsigned MaxVisit;
=20
   bool VisualizeEGDot;
   bool VisualizeEGUbi;
   AnalysisPurgeMode PurgeDead;
=20
-  /// EargerlyAssume - A flag indicating how the engine should handle
-  //   expressions such as: 'x =3D (y !=3D 0)'.  When this flag is true th=
en
-  //   the subexpression 'y !=3D 0' will be eagerly assumed to be true or =
false,
-  //   thus evaluating it to the integers 0 or 1 respectively.  The upside
-  //   is that this can increase analysis precision until we have a better=
 way
-  //   to lazily evaluate such logic.  The downside is that it eagerly
-  //   bifurcates paths.
+  /// \brief The flag regulates if we should eagerly assume evaluations of
+  /// conditionals, thus, bifurcating the path.
+  ///
+  /// EagerlyAssume - A flag indicating how the engine should handle
+  ///   expressions such as: 'x =3D (y !=3D 0)'.  When this flag is true t=
hen
+  ///   the subexpression 'y !=3D 0' will be eagerly assumed to be true or=
 false,
+  ///   thus evaluating it to the integers 0 or 1 respectively.  The upside
+  ///   is that this can increase analysis precision until we have a bette=
r way
+  ///   to lazily evaluate such logic.  The downside is that it eagerly
+  ///   bifurcates paths.
   bool EagerlyAssume;
   bool TrimGraph;
-  bool InlineCall;
   bool EagerlyTrimEGraph;
=20
 public:
+  // \brief inter-procedural analysis mode.
+  AnalysisIPAMode IPAMode;
+
+  // Settings for inlining tuning.
+  /// \brief The inlining stack depth limit.
+  unsigned InlineMaxStackDepth;
+  /// \brief The max number of basic blocks in a function being inlined.
+  unsigned InlineMaxFunctionSize;
+  /// \brief The mode of function selection used during inlining.
+  AnalysisInliningMode InliningMode;
+
+  /// \brief Do not re-analyze paths leading to exhausted nodes with a dif=
ferent
+  /// strategy. We get better code coverage when retry is enabled.
+  bool NoRetryExhausted;
+
+public:
   AnalysisManager(ASTContext &ctx, DiagnosticsEngine &diags,=20
                   const LangOptions &lang, PathDiagnosticConsumer *pd,
                   StoreManagerCreator storemgr,
@@ -85,9 +103,14 @@
                   unsigned maxnodes, unsigned maxvisit,
                   bool vizdot, bool vizubi, AnalysisPurgeMode purge,
                   bool eager, bool trim,
-                  bool inlinecall, bool useUnoptimizedCFG,
+                  bool useUnoptimizedCFG,
                   bool addImplicitDtors, bool addInitializers,
-                  bool eagerlyTrimEGraph);
+                  bool eagerlyTrimEGraph,
+                  AnalysisIPAMode ipa,
+                  unsigned inlineMaxStack,
+                  unsigned inlineMaxFunctionSize,
+                  AnalysisInliningMode inliningMode,
+                  bool NoRetry);
=20
   /// Construct a clone of the given AnalysisManager with the given ASTCon=
text
   /// and DiagnosticsEngine.
@@ -97,11 +120,10 @@
   ~AnalysisManager() { FlushDiagnostics(); }
  =20
   void ClearContexts() {
-    LocCtxMgr.clear();
     AnaCtxMgr.clear();
   }
  =20
-  AnalysisContextManager& getAnalysisContextManager() {
+  AnalysisDeclContextManager& getAnalysisDeclContextManager() {
     return AnaCtxMgr;
   }
=20
@@ -129,8 +151,8 @@
     return Diags;
   }
=20
-  const LangOptions &getLangOptions() const {
-    return LangInfo;
+  const LangOptions &getLangOpts() const {
+    return LangOpts;
   }
=20
   virtual PathDiagnosticConsumer *getPathDiagnosticConsumer() {
@@ -139,7 +161,7 @@
  =20
   void FlushDiagnostics() {
     if (PD.get())
-      PD->FlushDiagnostics();
+      PD->FlushDiagnostics(0);
   }
=20
   unsigned getMaxNodes() const { return MaxNodes; }
@@ -162,11 +184,11 @@
=20
   bool shouldEagerlyAssume() const { return EagerlyAssume; }
=20
-  bool shouldInlineCall() const { return InlineCall; }
+  bool shouldInlineCall() const { return (IPAMode =3D=3D Inlining); }
=20
   bool hasIndexer() const { return Idxer !=3D 0; }
=20
-  AnalysisContext *getAnalysisContextInAnotherTU(const Decl *D);
+  AnalysisDeclContext *getAnalysisDeclContextInAnotherTU(const Decl *D);
=20
   CFG *getCFG(Decl const *D) {
     return AnaCtxMgr.getContext(D)->getCFG();
@@ -181,38 +203,17 @@
     return AnaCtxMgr.getContext(D)->getParentMap();
   }
=20
-  AnalysisContext *getAnalysisContext(const Decl *D) {
+  AnalysisDeclContext *getAnalysisDeclContext(const Decl *D) {
     return AnaCtxMgr.getContext(D);
   }
=20
-  AnalysisContext *getAnalysisContext(const Decl *D, idx::TranslationUnit =
*TU) {
+  AnalysisDeclContext *getAnalysisDeclContext(const Decl *D, idx::Translat=
ionUnit *TU) {
     return AnaCtxMgr.getContext(D, TU);
   }
=20
-  const StackFrameContext *getStackFrame(AnalysisContext *Ctx,
-                                         LocationContext const *Parent,
-                                         const Stmt *S,
-                                         const CFGBlock *Blk, unsigned Idx=
) {
-    return LocCtxMgr.getStackFrame(Ctx, Parent, S, Blk, Idx);
-  }
-
-  // Get the top level stack frame.
-  const StackFrameContext *getStackFrame(Decl const *D,=20
-                                         idx::TranslationUnit *TU) {
-    return LocCtxMgr.getStackFrame(AnaCtxMgr.getContext(D, TU), 0, 0, 0, 0=
);
-  }
-
-  // Get a stack frame with parent.
-  StackFrameContext const *getStackFrame(const Decl *D,=20
-                                         LocationContext const *Parent,
-                                         const Stmt *S,
-                                         const CFGBlock *Blk, unsigned Idx=
) {
-    return LocCtxMgr.getStackFrame(AnaCtxMgr.getContext(D), Parent, S,
-                                   Blk,Idx);
-  }
 };
=20
-} // end GR namespace
+} // enAnaCtxMgrspace
=20
 } // end clang namespace
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/BasicValueFactory.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/BasicValueFactory.h	Tue Apr 17 11:51:51 2012 +0300
@@ -18,17 +18,10 @@
=20
 #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
-#include "clang/AST/ASTContext.h"
-#include "llvm/ADT/FoldingSet.h"
-#include "llvm/ADT/APSInt.h"
-#include "llvm/ADT/ImmutableList.h"
=20
 namespace clang {
-
 namespace ento {
=20
-class ProgramState;
-
 class CompoundValData : public llvm::FoldingSetNode {
   QualType T;
   llvm::ImmutableList<SVal> L;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/CheckerContext.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/CheckerContext.h	Tue Apr 17 11:51:51 2012 +0300
@@ -15,48 +15,41 @@
 #ifndef LLVM_CLANG_SA_CORE_PATHSENSITIVE_CHECKERCONTEXT
 #define LLVM_CLANG_SA_CORE_PATHSENSITIVE_CHECKERCONTEXT
=20
-#include "clang/Analysis/Support/SaveAndRestore.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
=20
 namespace clang {
-
 namespace ento {
=20
 class CheckerContext {
-  ExplodedNodeSet &Dst;
-  StmtNodeBuilder &B;
   ExprEngine &Eng;
+  /// The current exploded(symbolic execution) graph node.
   ExplodedNode *Pred;
-  SaveAndRestore<bool> OldSink;
-  SaveOr OldHasGen;
+  /// The flag is true if the (state of the execution) has been modified
+  /// by the checker using this context. For example, a new transition has=
 been
+  /// added or a bug report issued.
+  bool Changed;
+  /// The tagged location, which is used to generate all new nodes.
   const ProgramPoint Location;
-  const ProgramState *ST;
-  const unsigned size;
+  NodeBuilder &NB;
+
 public:
-  bool *respondsToCallback;
-public:
-  CheckerContext(ExplodedNodeSet &dst,
-                 StmtNodeBuilder &builder,
+  /// If we are post visiting a call, this flag will be set if the
+  /// call was inlined.  In all other cases it will be false.
+  const bool wasInlined;
+ =20
+  CheckerContext(NodeBuilder &builder,
                  ExprEngine &eng,
                  ExplodedNode *pred,
                  const ProgramPoint &loc,
-                 bool *respondsToCB =3D 0,
-                 const ProgramState *st =3D 0)
-    : Dst(dst),
-      B(builder),
-      Eng(eng),
+                 bool wasInlined =3D false)
+    : Eng(eng),
       Pred(pred),
-      OldSink(B.BuildSinks),
-      OldHasGen(B.hasGeneratedNode),
+      Changed(false),
       Location(loc),
-      ST(st),
-      size(Dst.size()),
-      respondsToCallback(respondsToCB) {}
-
-  ~CheckerContext();
-
-  ExprEngine &getEngine() {
-    return Eng;
+      NB(builder),
+      wasInlined(wasInlined) {
+    assert(Pred->getState() &&
+           "We should not call the checkers on an empty state.");
   }
=20
   AnalysisManager &getAnalysisManager() {
@@ -71,18 +64,34 @@
     return Eng.getStoreManager();
   }
=20
-  ExplodedNodeSet &getNodeSet() { return Dst; }
-  ExplodedNode *&getPredecessor() { return Pred; }
-  const ProgramState *getState() { return ST ? ST : Pred->getState(); }
+  /// \brief Returns the previous node in the exploded graph, which includ=
es
+  /// the state of the program before the checker ran. Note, checkers shou=
ld
+  /// not retain the node in their state since the nodes might get invalid=
ated.
+  ExplodedNode *getPredecessor() { return Pred; }
+  ProgramStateRef getState() const { return Pred->getState(); }
+
+  /// \brief Check if the checker changed the state of the execution; ex: =
added
+  /// a new transition or a bug report.
+  bool isDifferent() { return Changed; }
=20
   /// \brief Returns the number of times the current block has been visited
   /// along the analyzed path.
-  unsigned getCurrentBlockCount() {return B.getCurrentBlockCount();}
+  unsigned getCurrentBlockCount() const {
+    return NB.getContext().getCurrentBlockCount();
+  }
=20
   ASTContext &getASTContext() {
     return Eng.getContext();
   }
- =20
+
+  const LangOptions &getLangOpts() const {
+    return Eng.getContext().getLangOpts();
+  }
+
+  const LocationContext *getLocationContext() const {
+    return Pred->getLocationContext();
+  }
+
   BugReporter &getBugReporter() {
     return Eng.getBugReporter();
   }
@@ -99,83 +108,130 @@
     return getSValBuilder().getSymbolManager();
   }
=20
-  bool isObjCGCEnabled() {
+  bool isObjCGCEnabled() const {
     return Eng.isObjCGCEnabled();
   }
=20
-  /// \brief Generate a default checker node (containing checker tag but no
-  /// checker state changes).
-  ExplodedNode *generateNode(bool autoTransition =3D true) {
-    return generateNode(getState(), autoTransition);
-  }
- =20
-  /// \brief Generate a new checker node with the given predecessor.
-  /// Allows checkers to generate a chain of nodes.
-  ExplodedNode *generateNode(const ProgramState *state,
-                             ExplodedNode *pred,
-                             const ProgramPointTag *tag =3D 0,
-                             bool autoTransition =3D true) {
-    ExplodedNode *N =3D generateNodeImpl(state, false, pred, tag);
-    if (N && autoTransition)
-      addTransition(N);
-    return N;
+  ProgramStateManager &getStateManager() {
+    return Eng.getStateManager();
   }
=20
-  /// \brief Generate a new checker node.
-  ExplodedNode *generateNode(const ProgramState *state,
-                             bool autoTransition =3D true,
-                             const ProgramPointTag *tag =3D 0) {
-    ExplodedNode *N =3D generateNodeImpl(state, false, 0, tag);
-    if (N && autoTransition)
-      addTransition(N);
-    return N;
+  AnalysisDeclContext *getCurrentAnalysisDeclContext() const {
+    return Pred->getLocationContext()->getAnalysisDeclContext();
+  }
+
+  /// \brief If the given node corresponds to a PostStore program point, r=
etrieve
+  /// the location region as it was uttered in the code.
+  ///
+  /// This utility can be useful for generating extensive diagnostics, for
+  /// example, for finding variables that the given symbol was assigned to.
+  static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode =
*N) {
+    ProgramPoint L =3D N->getLocation();
+    if (const PostStore *PSL =3D dyn_cast<PostStore>(&L))
+      return reinterpret_cast<const MemRegion*>(PSL->getLocationValue());
+    return 0;
+  }
+
+  /// \brief Generates a new transition in the program state graph
+  /// (ExplodedGraph). Uses the default CheckerContext predecessor node.
+  ///
+  /// @param State The state of the generated node.
+  /// @param Tag The tag is used to uniquely identify the creation site. I=
f no
+  ///        tag is specified, a default tag, unique to the given checker,
+  ///        will be used. Tags are used to prevent states generated at
+  ///        different sites from caching out.
+  ExplodedNode *addTransition(ProgramStateRef State,
+                              const ProgramPointTag *Tag =3D 0) {
+    return addTransitionImpl(State, false, 0, Tag);
+  }
+
+  /// \brief Generates a default transition (containing checker tag but no
+  /// checker state changes).
+  ExplodedNode *addTransition() {
+    return addTransition(getState());
+  }
+
+  /// \brief Generates a new transition with the given predecessor.
+  /// Allows checkers to generate a chain of nodes.
+  ///
+  /// @param State The state of the generated node.
+  /// @param Pred The transition will be generated from the specified Pred=
 node
+  ///             to the newly generated node.
+  /// @param Tag The tag to uniquely identify the creation site.
+  /// @param IsSink Mark the new node as sink, which will stop exploration=
 of
+  ///               the given path.
+  ExplodedNode *addTransition(ProgramStateRef State,
+                             ExplodedNode *Pred,
+                             const ProgramPointTag *Tag =3D 0,
+                             bool IsSink =3D false) {
+    return addTransitionImpl(State, IsSink, Pred, Tag);
   }
=20
   /// \brief Generate a sink node. Generating sink stops exploration of the
   /// given path.
-  ExplodedNode *generateSink(const ProgramState *state =3D 0) {
-    return generateNodeImpl(state ? state : getState(), true);
+  ExplodedNode *generateSink(ProgramStateRef state =3D 0) {
+    return addTransitionImpl(state ? state : getState(), true);
   }
=20
-  void addTransition(ExplodedNode *node) {
-    Dst.Add(node);
-  }
- =20
-  void addTransition(const ProgramState *state,
-                     const ProgramPointTag *tag =3D 0) {
-    assert(state);
-    // If the 'state' is not new, we need to check if the cached state 'ST'
-    // is new.
-    if (state !=3D getState() || (ST && ST !=3D Pred->getState()))
-      // state is new or equals to ST.
-      generateNode(state, true, tag);
-    else
-      Dst.Add(Pred);
-  }
-
+  /// \brief Emit the diagnostics report.
   void EmitReport(BugReport *R) {
+    Changed =3D true;
     Eng.getBugReporter().EmitReport(R);
   }
=20
-  AnalysisContext *getCurrentAnalysisContext() const {
-    return Pred->getLocationContext()->getAnalysisContext();
+  /// \brief Get the declaration of the called function (path-sensitive).
+  const FunctionDecl *getCalleeDecl(const CallExpr *CE) const;
+
+  /// \brief Get the name of the called function (path-sensitive).
+  StringRef getCalleeName(const FunctionDecl *FunDecl) const;
+
+  /// \brief Get the name of the called function (path-sensitive).
+  StringRef getCalleeName(const CallExpr *CE) const {
+    const FunctionDecl *FunDecl =3D getCalleeDecl(CE);
+    return getCalleeName(FunDecl);
   }
=20
+  /// Given a function declaration and a name checks if this is a C lib
+  /// function with the given name.
+  bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name);
+  static bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name,
+                                 ASTContext &Context);
+
+  /// \brief Depending on wither the location corresponds to a macro, retu=
rn=20
+  /// either the macro name or the token spelling.
+  ///
+  /// This could be useful when checkers' logic depends on whether a funct=
ion
+  /// is called with a given macro argument. For example:
+  ///   s =3D socket(AF_INET,..)
+  /// If AF_INET is a macro, the result should be treated as a source of t=
aint.
+  ///
+  /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName=
().
+  StringRef getMacroNameOrSpelling(SourceLocation &Loc);
+
 private:
-  ExplodedNode *generateNodeImpl(const ProgramState *state,
-                                 bool markAsSink,
-                                 ExplodedNode *pred =3D 0,
-                                 const ProgramPointTag *tag =3D 0) {
+  ExplodedNode *addTransitionImpl(ProgramStateRef State,
+                                 bool MarkAsSink,
+                                 ExplodedNode *P =3D 0,
+                                 const ProgramPointTag *Tag =3D 0) {
+    if (!State || (State =3D=3D Pred->getState() && !Tag && !MarkAsSink))
+      return Pred;
=20
-    ExplodedNode *node =3D B.generateNode(tag ? Location.withTag(tag) : Lo=
cation,
-                                        state,
-                                        pred ? pred : Pred);
-    if (markAsSink && node)
-      node->markAsSink();
+    Changed =3D true;
+    ExplodedNode *node =3D NB.generateNode(Tag ? Location.withTag(Tag) : L=
ocation,
+                                        State,
+                                        P ? P : Pred, MarkAsSink);
     return node;
   }
 };
=20
+/// \brief A helper class which wraps a boolean value set to false by defa=
ult.
+struct DefaultBool {
+  bool Val;
+  DefaultBool() : Val(false) {}
+  operator bool() const { return Val; }
+  DefaultBool &operator=3D(bool b) { Val =3D b; return *this; }
+};
+
 } // end GR namespace
=20
 } // end clang namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ConstraintManager.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ConstraintManager.h	Tue Apr 17 11:51:51 2012 +0300
@@ -22,44 +22,45 @@
 }
=20
 namespace clang {
-
 namespace ento {
=20
-class ProgramState;
-class ProgramStateManager;
 class SubEngine;
=20
 class ConstraintManager {
 public:
   virtual ~ConstraintManager();
-  virtual const ProgramState *assume(const ProgramState *state,
+  virtual ProgramStateRef assume(ProgramStateRef state,
                                      DefinedSVal Cond,
                                      bool Assumption) =3D 0;
=20
-  std::pair<const ProgramState*, const ProgramState*>
-    assumeDual(const ProgramState *state, DefinedSVal Cond)
+  std::pair<ProgramStateRef, ProgramStateRef >
+    assumeDual(ProgramStateRef state, DefinedSVal Cond)
   {
-    return std::make_pair(assume(state, Cond, true),
-                          assume(state, Cond, false));
+    std::pair<ProgramStateRef, ProgramStateRef > res =3D
+      std::make_pair(assume(state, Cond, true), assume(state, Cond, false)=
);
+
+    assert(!(!res.first && !res.second) && "System is over constrained.");
+    return res;
   }
=20
-  virtual const llvm::APSInt* getSymVal(const ProgramState *state,
+  virtual const llvm::APSInt* getSymVal(ProgramStateRef state,
                                         SymbolRef sym) const =3D 0;
=20
-  virtual bool isEqual(const ProgramState *state,
+  virtual bool isEqual(ProgramStateRef state,
                        SymbolRef sym,
                        const llvm::APSInt& V) const =3D 0;
=20
-  virtual const ProgramState *removeDeadBindings(const ProgramState *state,
+  virtual ProgramStateRef removeDeadBindings(ProgramStateRef state,
                                                  SymbolReaper& SymReaper) =
=3D 0;
=20
-  virtual void print(const ProgramState *state,
+  virtual void print(ProgramStateRef state,
                      raw_ostream &Out,
                      const char* nl,
                      const char *sep) =3D 0;
=20
-  virtual void EndPath(const ProgramState *state) {}
+  virtual void EndPath(ProgramStateRef state) {}
=20
+protected:
   /// canReasonAbout - Not all ConstraintManagers can accurately reason ab=
out
   ///  all SVal values.  This method returns true if the ConstraintManager=
 can
   ///  reasonably handle a given SVal value.  This is typically queried by
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/CoreEngine.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/CoreEngine.h	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,9 @@
 #define LLVM_CLANG_GR_COREENGINE
=20
 #include "clang/AST/Expr.h"
+#include "clang/Analysis/AnalysisContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/WorkList.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/BlockCounter.h"
 #include "llvm/ADT/OwningPtr.h"
@@ -27,6 +29,8 @@
  =20
 namespace ento {
=20
+class NodeBuilder;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 /// CoreEngine - Implements the core logic of the graph-reachability
 ///   analysis. It traverses the CFG and generates the ExplodedGraph.
@@ -37,15 +41,13 @@
 ///   at the statement and block-level.  The analyses themselves must impl=
ement
 ///   any transfer function logic and the sub-expression level (if any).
 class CoreEngine {
-  friend class StmtNodeBuilder;
-  friend class GenericNodeBuilderImpl;
-  friend class BranchNodeBuilder;
+  friend struct NodeBuilderContext;
+  friend class NodeBuilder;
+  friend class ExprEngine;
+  friend class CommonNodeBuilder;
   friend class IndirectGotoNodeBuilder;
   friend class SwitchNodeBuilder;
   friend class EndOfFunctionNodeBuilder;
-  friend class CallEnterNodeBuilder;
-  friend class CallExitNodeBuilder;
-
 public:
   typedef std::vector<std::pair<BlockEdge, const ExplodedNode*> >
             BlocksExhausted;
@@ -58,7 +60,7 @@
   SubEngine& SubEng;
=20
   /// G - The simulation graph.  Each node is a (location,state) pair.
-  llvm::OwningPtr<ExplodedGraph> G;
+  OwningPtr<ExplodedGraph> G;
=20
   /// WList - A set of queued nodes that need to be processed by the
   ///  worklist algorithm.  It is up to the implementation of WList to dec=
ide
@@ -78,8 +80,16 @@
   /// usually because it could not reason about something.
   BlocksAborted blocksAborted;
=20
+  /// The functions which have been analyzed through inlining. This is own=
ed by
+  /// AnalysisConsumer. It can be null.
+  SetOfConstDecls *AnalyzedCallees;
+
+  /// The information about functions shared by the whole translation unit.
+  /// (This data is owned by AnalysisConsumer.)
+  FunctionSummariesTy *FunctionSummaries;
+
   void generateNode(const ProgramPoint &Loc,
-                    const ProgramState *State,
+                    ProgramStateRef State,
                     ExplodedNode *Pred);
=20
   void HandleBlockEdge(const BlockEdge &E, ExplodedNode *Pred);
@@ -89,28 +99,23 @@
=20
   void HandleBranch(const Stmt *Cond, const Stmt *Term, const CFGBlock *B,
                     ExplodedNode *Pred);
-  void HandleCallEnter(const CallEnter &L, const CFGBlock *Block,
-                       unsigned Index, ExplodedNode *Pred);
-  void HandleCallExit(const CallExit &L, ExplodedNode *Pred);
=20
 private:
   CoreEngine(const CoreEngine&); // Do not implement.
   CoreEngine& operator=3D(const CoreEngine&);
=20
+  ExplodedNode *generateCallExitNode(ExplodedNode *N);
+
 public:
   /// Construct a CoreEngine object to analyze the provided CFG using
   ///  a DFS exploration of the exploded graph.
-  CoreEngine(SubEngine& subengine)
+  CoreEngine(SubEngine& subengine, SetOfConstDecls *VisitedCallees,
+             FunctionSummariesTy *FS)
     : SubEng(subengine), G(new ExplodedGraph()),
       WList(WorkList::makeBFS()),
-      BCounterFactory(G->getAllocator()) {}
-
-  /// Construct a CoreEngine object to analyze the provided CFG and to
-  ///  use the provided worklist object to execute the worklist algorithm.
-  ///  The CoreEngine object assumes ownership of 'wlist'.
-  CoreEngine(WorkList* wlist, SubEngine& subengine)
-    : SubEng(subengine), G(new ExplodedGraph()), WList(wlist),
-      BCounterFactory(G->getAllocator()) {}
+      BCounterFactory(G->getAllocator()),
+      AnalyzedCallees(VisitedCallees),
+      FunctionSummaries(FS){}
=20
   ~CoreEngine() {
     delete WList;
@@ -126,12 +131,18 @@
   /// ExecuteWorkList - Run the worklist algorithm for a maximum number of
   ///  steps.  Returns true if there is still simulation state on the work=
list.
   bool ExecuteWorkList(const LocationContext *L, unsigned Steps,
-                       const ProgramState *InitState);
-  void ExecuteWorkListWithInitialState(const LocationContext *L,
+                       ProgramStateRef InitState);
+  /// Returns true if there is still simulation state on the worklist.
+  bool ExecuteWorkListWithInitialState(const LocationContext *L,
                                        unsigned Steps,
-                                       const ProgramState *InitState,=20
+                                       ProgramStateRef InitState,=20
                                        ExplodedNodeSet &Dst);
=20
+  /// Dispatch the work list item based on the given location information.
+  /// Use Pred parameter as the predecessor state.
+  void dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
+                        const WorkListUnit& WU);
+
   // Functions for external checking of whether we have unfinished work
   bool wasBlockAborted() const { return !blocksAborted.empty(); }
   bool wasBlocksExhausted() const { return !blocksExhausted.empty(); }
@@ -159,160 +170,254 @@
   BlocksAborted::const_iterator blocks_aborted_end() const {
     return blocksAborted.end();
   }
+
+  /// \brief Enqueue the given set of nodes onto the work list.
+  void enqueue(ExplodedNodeSet &Set);
+
+  /// \brief Enqueue nodes that were created as a result of processing
+  /// a statement onto the work list.
+  void enqueue(ExplodedNodeSet &Set, const CFGBlock *Block, unsigned Idx);
+
+  /// \brief enqueue the nodes corresponding to the end of function onto t=
he
+  /// end of path / work list.
+  void enqueueEndOfFunction(ExplodedNodeSet &Set);
+
+  /// \brief Enqueue a single node created as a result of statement proces=
sing.
+  void enqueueStmtNode(ExplodedNode *N, const CFGBlock *Block, unsigned Id=
x);
 };
=20
-class StmtNodeBuilder {
-  CoreEngine& Eng;
-  const CFGBlock &B;
-  const unsigned Idx;
+// TODO: Turn into a calss.
+struct NodeBuilderContext {
+  CoreEngine &Eng;
+  const CFGBlock *Block;
   ExplodedNode *Pred;
+  NodeBuilderContext(CoreEngine &E, const CFGBlock *B, ExplodedNode *N)
+    : Eng(E), Block(B), Pred(N) { assert(B); assert(!N->isSink()); }
=20
+  ExplodedNode *getPred() const { return Pred; }
+
+  /// \brief Return the CFGBlock associated with this builder.
+  const CFGBlock *getBlock() const { return Block; }
+
+  /// \brief Returns the number of times the current basic block has been
+  /// visited on the exploded graph path.
+  unsigned getCurrentBlockCount() const {
+    return Eng.WList->getBlockCounter().getNumVisited(
+                    Pred->getLocationContext()->getCurrentStackFrame(),
+                    Block->getBlockID());
+  }
+};
+
+/// \class NodeBuilder
+/// \brief This is the simplest builder which generates nodes in the
+/// ExplodedGraph.
+///
+/// The main benefit of the builder is that it automatically tracks the
+/// frontier nodes (or destination set). This is the set of nodes which sh=
ould
+/// be propagated to the next step / builder. They are the nodes which hav=
e been
+/// added to the builder (either as the input node set or as the newly
+/// constructed nodes) but did not have any outgoing transitions added.
+class NodeBuilder {
+  virtual void anchor();
+protected:
+  const NodeBuilderContext &C;
+
+  /// Specifies if the builder results have been finalized. For example, i=
f it
+  /// is set to false, autotransitions are yet to be generated.
+  bool Finalized;
+  bool HasGeneratedNodes;
+  /// \brief The frontier set - a set of nodes which need to be propagated=
 after
+  /// the builder dies.
+  ExplodedNodeSet &Frontier;
+
+  /// Checkes if the results are ready.
+  virtual bool checkResults() {
+    if (!Finalized)
+      return false;
+    return true;
+  }
+
+  bool hasNoSinksInFrontier() {
+    for (iterator I =3D Frontier.begin(), E =3D Frontier.end(); I !=3D E; =
++I) {
+      if ((*I)->isSink())
+        return false;
+    }
+    return true;
+  }
+
+  /// Allow subclasses to finalize results before result_begin() is execut=
ed.
+  virtual void finalizeResults() {}
+ =20
+  ExplodedNode *generateNodeImpl(const ProgramPoint &PP,
+                                 ProgramStateRef State,
+                                 ExplodedNode *Pred,
+                                 bool MarkAsSink =3D false);
=20
 public:
-  bool PurgingDeadSymbols;
-  bool BuildSinks;
-  bool hasGeneratedNode;
-  ProgramPoint::Kind PointKind;
-  const ProgramPointTag *Tag;
+  NodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
+              const NodeBuilderContext &Ctx, bool F =3D true)
+    : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) {
+    Frontier.Add(SrcNode);
+  }
=20
-  typedef llvm::SmallPtrSet<ExplodedNode*,5> DeferredTy;
-  DeferredTy Deferred;
+  NodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
+              const NodeBuilderContext &Ctx, bool F =3D true)
+    : C(Ctx), Finalized(F), HasGeneratedNodes(false), Frontier(DstSet) {
+    Frontier.insert(SrcSet);
+    assert(hasNoSinksInFrontier());
+  }
=20
-  void GenerateAutoTransition(ExplodedNode *N);
+  virtual ~NodeBuilder() {}
+
+  /// \brief Generates a node in the ExplodedGraph.
+  ///
+  /// When a node is marked as sink, the exploration from the node is stop=
ped -
+  /// the node becomes the last node on the path.
+  ExplodedNode *generateNode(const ProgramPoint &PP,
+                             ProgramStateRef State,
+                             ExplodedNode *Pred,
+                             bool MarkAsSink =3D false) {
+    return generateNodeImpl(PP, State, Pred, MarkAsSink);
+  }
+
+  const ExplodedNodeSet &getResults() {
+    finalizeResults();
+    assert(checkResults());
+    return Frontier;
+  }
+
+  typedef ExplodedNodeSet::iterator iterator;
+  /// \brief Iterators through the results frontier.
+  inline iterator begin() {
+    finalizeResults();
+    assert(checkResults());
+    return Frontier.begin();
+  }
+  inline iterator end() {
+    finalizeResults();
+    return Frontier.end();
+  }
+
+  const NodeBuilderContext &getContext() { return C; }
+  bool hasGeneratedNodes() { return HasGeneratedNodes; }
+
+  void takeNodes(const ExplodedNodeSet &S) {
+    for (ExplodedNodeSet::iterator I =3D S.begin(), E =3D S.end(); I !=3D =
E; ++I )
+      Frontier.erase(*I);
+  }
+  void takeNodes(ExplodedNode *N) { Frontier.erase(N); }
+  void addNodes(const ExplodedNodeSet &S) { Frontier.insert(S); }
+  void addNodes(ExplodedNode *N) { Frontier.Add(N); }
+};
+
+/// \class NodeBuilderWithSinks
+/// \brief This node builder keeps track of the generated sink nodes.
+class NodeBuilderWithSinks: public NodeBuilder {
+  virtual void anchor();
+protected:
+  SmallVector<ExplodedNode*, 2> sinksGenerated;
+  ProgramPoint &Location;
=20
 public:
-  StmtNodeBuilder(const CFGBlock *b,
-                  unsigned idx,
-                  ExplodedNode *N,
-                  CoreEngine* e);
+  NodeBuilderWithSinks(ExplodedNode *Pred, ExplodedNodeSet &DstSet,
+                       const NodeBuilderContext &Ctx, ProgramPoint &L)
+    : NodeBuilder(Pred, DstSet, Ctx), Location(L) {}
+  ExplodedNode *generateNode(ProgramStateRef State,
+                             ExplodedNode *Pred,
+                             const ProgramPointTag *Tag =3D 0,
+                             bool MarkAsSink =3D false) {
+    ProgramPoint LocalLoc =3D (Tag ? Location.withTag(Tag): Location);
=20
-  ~StmtNodeBuilder();
-
-  ExplodedNode *getPredecessor() const { return Pred; }
-
-  // FIXME: This should not be exposed.
-  WorkList *getWorkList() { return Eng.WList; }
-
-  BlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter=
();}
-
-  unsigned getCurrentBlockCount() const {
-    return getBlockCounter().getNumVisited(
-                            Pred->getLocationContext()->getCurrentStackFra=
me(),
-                                           B.getBlockID());
+    ExplodedNode *N =3D generateNodeImpl(LocalLoc, State, Pred, MarkAsSink=
);
+    if (N && N->isSink())
+      sinksGenerated.push_back(N);
+    return N;
   }
=20
-  ExplodedNode *generateNode(const Stmt *S,
-                             const ProgramState *St,
-                             ExplodedNode *Pred,
-                             ProgramPoint::Kind K,
-                             const ProgramPointTag *tag =3D 0) {
-    hasGeneratedNode =3D true;
+  const SmallVectorImpl<ExplodedNode*> &getSinks() const {
+    return sinksGenerated;
+  }
+};
=20
-    if (PurgingDeadSymbols)
-      K =3D ProgramPoint::PostPurgeDeadSymbolsKind;
+/// \class StmtNodeBuilder
+/// \brief This builder class is useful for generating nodes that resulted=
 from
+/// visiting a statement. The main difference from it's parent NodeBuilder=
 is
+/// that it creates a statement specific ProgramPoint.
+class StmtNodeBuilder: public NodeBuilder {
+  NodeBuilder *EnclosingBldr;
+public:
=20
-    return generateNodeInternal(S, St, Pred, K, tag ? tag : Tag);
+  /// \brief Constructs a StmtNodeBuilder. If the builder is going to proc=
ess
+  /// nodes currently owned by another builder(with larger scope), use
+  /// Enclosing builder to transfer ownership.
+  StmtNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
+                      const NodeBuilderContext &Ctx, NodeBuilder *Enclosin=
g =3D 0)
+    : NodeBuilder(SrcNode, DstSet, Ctx), EnclosingBldr(Enclosing) {
+    if (EnclosingBldr)
+      EnclosingBldr->takeNodes(SrcNode);
   }
=20
+  StmtNodeBuilder(ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
+                      const NodeBuilderContext &Ctx, NodeBuilder *Enclosin=
g =3D 0)
+    : NodeBuilder(SrcSet, DstSet, Ctx), EnclosingBldr(Enclosing) {
+    if (EnclosingBldr)
+      for (ExplodedNodeSet::iterator I =3D SrcSet.begin(),
+                                     E =3D SrcSet.end(); I !=3D E; ++I )
+        EnclosingBldr->takeNodes(*I);
+  }
+
+  virtual ~StmtNodeBuilder();
+
   ExplodedNode *generateNode(const Stmt *S,
-                             const ProgramState *St,
                              ExplodedNode *Pred,
-                             const ProgramPointTag *tag =3D 0) {
-    return generateNode(S, St, Pred, PointKind, tag);
+                             ProgramStateRef St,
+                             bool MarkAsSink =3D false,
+                             const ProgramPointTag *tag =3D 0,
+                             ProgramPoint::Kind K =3D ProgramPoint::PostSt=
mtKind){
+    const ProgramPoint &L =3D ProgramPoint::getProgramPoint(S, K,
+                                  Pred->getLocationContext(), tag);
+    return generateNodeImpl(L, St, Pred, MarkAsSink);
   }
=20
   ExplodedNode *generateNode(const ProgramPoint &PP,
-                             const ProgramState *State,
-                             ExplodedNode *Pred) {
-    hasGeneratedNode =3D true;
-    return generateNodeInternal(PP, State, Pred);
-  }
-
-  ExplodedNode*
-  generateNodeInternal(const ProgramPoint &PP,
-                       const ProgramState *State,
-                       ExplodedNode *Pred);
-
-  ExplodedNode*
-  generateNodeInternal(const Stmt *S,
-                       const ProgramState *State,
-                       ExplodedNode *Pred,
-                       ProgramPoint::Kind K,
-                       const ProgramPointTag *tag =3D 0);
-
-  /// getStmt - Return the current block-level expression associated with
-  ///  this builder.
-  const Stmt *getStmt() const {=20
-    const CFGStmt *CS =3D B[Idx].getAs<CFGStmt>();
-    return CS ? CS->getStmt() : 0;
-  }
-
-  /// getBlock - Return the CFGBlock associated with the block-level expre=
ssion
-  ///  of this builder.
-  const CFGBlock *getBlock() const { return &B; }
-
-  unsigned getIndex() const { return Idx; }
-
-  ExplodedNode *MakeNode(ExplodedNodeSet &Dst,
-                         const Stmt *S,=20
-                         ExplodedNode *Pred,
-                         const ProgramState *St) {
-    return MakeNode(Dst, S, Pred, St, PointKind);
-  }
-
-  ExplodedNode *MakeNode(ExplodedNodeSet &Dst,
-                         const Stmt *S,
-                         ExplodedNode *Pred,
-                         const ProgramState *St,
-                         ProgramPoint::Kind K);
-
-  ExplodedNode *MakeSinkNode(ExplodedNodeSet &Dst,
-                             const Stmt *S,
                              ExplodedNode *Pred,
-                             const ProgramState *St) {
-    bool Tmp =3D BuildSinks;
-    BuildSinks =3D true;
-    ExplodedNode *N =3D MakeNode(Dst, S, Pred, St);
-    BuildSinks =3D Tmp;
-    return N;
+                             ProgramStateRef State,
+                             bool MarkAsSink =3D false) {
+    return generateNodeImpl(PP, State, Pred, MarkAsSink);
   }
 };
=20
-class BranchNodeBuilder {
-  CoreEngine& Eng;
-  const CFGBlock *Src;
+/// \brief BranchNodeBuilder is responsible for constructing the nodes
+/// corresponding to the two branches of the if statement - true and false.
+class BranchNodeBuilder: public NodeBuilder {
+  virtual void anchor();
   const CFGBlock *DstT;
   const CFGBlock *DstF;
-  ExplodedNode *Pred;
=20
-  typedef SmallVector<ExplodedNode*,3> DeferredTy;
-  DeferredTy Deferred;
-
-  bool GeneratedTrue;
-  bool GeneratedFalse;
   bool InFeasibleTrue;
   bool InFeasibleFalse;
=20
 public:
-  BranchNodeBuilder(const CFGBlock *src, const CFGBlock *dstT,=20
-                      const CFGBlock *dstF, ExplodedNode *pred, CoreEngine=
* e)
-  : Eng(*e), Src(src), DstT(dstT), DstF(dstF), Pred(pred),
-    GeneratedTrue(false), GeneratedFalse(false),
-    InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {}
+  BranchNodeBuilder(ExplodedNode *SrcNode, ExplodedNodeSet &DstSet,
+                    const NodeBuilderContext &C,
+                    const CFGBlock *dstT, const CFGBlock *dstF)
+  : NodeBuilder(SrcNode, DstSet, C), DstT(dstT), DstF(dstF),
+    InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {
+    // The branch node builder does not generate autotransitions.
+    // If there are no successors it means that both branches are infeasib=
le.
+    takeNodes(SrcNode);
+  }
=20
-  ~BranchNodeBuilder();
+  BranchNodeBuilder(const ExplodedNodeSet &SrcSet, ExplodedNodeSet &DstSet,
+                    const NodeBuilderContext &C,
+                    const CFGBlock *dstT, const CFGBlock *dstF)
+  : NodeBuilder(SrcSet, DstSet, C), DstT(dstT), DstF(dstF),
+    InFeasibleTrue(!DstT), InFeasibleFalse(!DstF) {
+    takeNodes(SrcSet);
+  }
=20
-  ExplodedNode *getPredecessor() const { return Pred; }
-
-  const ExplodedGraph& getGraph() const { return *Eng.G; }
-
-  BlockCounter getBlockCounter() const { return Eng.WList->getBlockCounter=
();}
-
-  /// This function generates a new ExplodedNode but not a new
-  /// branch(block edge).
-  ExplodedNode *generateNode(const Stmt *Condition, const ProgramState *St=
ate);
-
-  ExplodedNode *generateNode(const ProgramState *State, bool branch);
+  ExplodedNode *generateNode(ProgramStateRef State, bool branch,
+                             ExplodedNode *Pred);
=20
   const CFGBlock *getTargetBlock(bool branch) const {
     return branch ? DstT : DstF;
@@ -320,18 +425,14 @@
=20
   void markInfeasible(bool branch) {
     if (branch)
-      InFeasibleTrue =3D GeneratedTrue =3D true;
+      InFeasibleTrue =3D true;
     else
-      InFeasibleFalse =3D GeneratedFalse =3D true;
+      InFeasibleFalse =3D true;
   }
=20
   bool isFeasible(bool branch) {
     return branch ? !InFeasibleTrue : !InFeasibleFalse;
   }
-
-  const ProgramState *getState() const {
-    return getPredecessor()->getState();
-  }
 };
=20
 class IndirectGotoNodeBuilder {
@@ -369,12 +470,16 @@
   iterator end() { return iterator(DispatchBlock.succ_end()); }
=20
   ExplodedNode *generateNode(const iterator &I,
-                             const ProgramState *State,
+                             ProgramStateRef State,
                              bool isSink =3D false);
=20
   const Expr *getTarget() const { return E; }
=20
-  const ProgramState *getState() const { return Pred->State; }
+  ProgramStateRef getState() const { return Pred->State; }
+ =20
+  const LocationContext *getLocationContext() const {
+    return Pred->getLocationContext();
+  }
 };
=20
 class SwitchNodeBuilder {
@@ -416,167 +521,21 @@
   }
=20
   ExplodedNode *generateCaseStmtNode(const iterator &I,
-                                     const ProgramState *State);
+                                     ProgramStateRef State);
=20
-  ExplodedNode *generateDefaultCaseNode(const ProgramState *State,
+  ExplodedNode *generateDefaultCaseNode(ProgramStateRef State,
                                         bool isSink =3D false);
=20
   const Expr *getCondition() const { return Condition; }
=20
-  const ProgramState *getState() const { return Pred->State; }
-};
-
-class GenericNodeBuilderImpl {
-protected:
-  CoreEngine &engine;
-  ExplodedNode *pred;
-  ProgramPoint pp;
-  SmallVector<ExplodedNode*, 2> sinksGenerated; =20
-
-  ExplodedNode *generateNodeImpl(const ProgramState *state,
-                                 ExplodedNode *pred,
-                                 ProgramPoint programPoint,
-                                 bool asSink);
-
-  GenericNodeBuilderImpl(CoreEngine &eng, ExplodedNode *pr, ProgramPoint p)
-    : engine(eng), pred(pr), pp(p), hasGeneratedNode(false) {}
-
-public:
-  bool hasGeneratedNode;
+  ProgramStateRef getState() const { return Pred->State; }
  =20
-  WorkList &getWorkList() { return *engine.WList; }
- =20
-  ExplodedNode *getPredecessor() const { return pred; }
- =20
-  BlockCounter getBlockCounter() const {
-    return engine.WList->getBlockCounter();
-  }
- =20
-  const SmallVectorImpl<ExplodedNode*> &sinks() const {
-    return sinksGenerated;
+  const LocationContext *getLocationContext() const {
+    return Pred->getLocationContext();
   }
 };
=20
-template <typename PP_T>
-class GenericNodeBuilder : public GenericNodeBuilderImpl {
-public:
-  GenericNodeBuilder(CoreEngine &eng, ExplodedNode *pr, const PP_T &p)
-    : GenericNodeBuilderImpl(eng, pr, p) {}
-
-  ExplodedNode *generateNode(const ProgramState *state, ExplodedNode *pred,
-                             const ProgramPointTag *tag, bool asSink) {
-    return generateNodeImpl(state, pred, cast<PP_T>(pp).withTag(tag),
-                            asSink);
-  }
- =20
-  const PP_T &getProgramPoint() const { return cast<PP_T>(pp); }
-};
-
-class EndOfFunctionNodeBuilder {
-  CoreEngine &Eng;
-  const CFGBlock &B;
-  ExplodedNode *Pred;
-  const ProgramPointTag *Tag;
-
-public:
-  bool hasGeneratedNode;
-
-public:
-  EndOfFunctionNodeBuilder(const CFGBlock *b, ExplodedNode *N, CoreEngine*=
 e,
-                           const ProgramPointTag *tag =3D 0)
-    : Eng(*e), B(*b), Pred(N), Tag(tag), hasGeneratedNode(false) {}
-
-  ~EndOfFunctionNodeBuilder();
-
-  EndOfFunctionNodeBuilder withCheckerTag(const ProgramPointTag *tag) {
-    return EndOfFunctionNodeBuilder(&B, Pred, &Eng, tag);
-  }
-
-  WorkList &getWorkList() { return *Eng.WList; }
-
-  ExplodedNode *getPredecessor() const { return Pred; }
-
-  BlockCounter getBlockCounter() const {
-    return Eng.WList->getBlockCounter();
-  }
-
-  unsigned getCurrentBlockCount() const {
-    return getBlockCounter().getNumVisited(
-                            Pred->getLocationContext()->getCurrentStackFra=
me(),
-                                           B.getBlockID());
-  }
-
-  ExplodedNode *generateNode(const ProgramState *State,
-                             ExplodedNode *P =3D 0,
-                             const ProgramPointTag *tag =3D 0);
-
-  void GenerateCallExitNode(const ProgramState *state);
-
-  const CFGBlock *getBlock() const { return &B; }
-
-  const ProgramState *getState() const {
-    return getPredecessor()->getState();
-  }
-};
-
-class CallEnterNodeBuilder {
-  CoreEngine &Eng;
-
-  const ExplodedNode *Pred;
-
-  // The call site. For implicit automatic object dtor, this is the trigge=
r=20
-  // statement.
-  const Stmt *CE;
-
-  // The context of the callee.
-  const StackFrameContext *CalleeCtx;
-
-  // The parent block of the CallExpr.
-  const CFGBlock *Block;
-
-  // The CFGBlock index of the CallExpr.
-  unsigned Index;
-
-public:
-  CallEnterNodeBuilder(CoreEngine &eng, const ExplodedNode *pred,=20
-                         const Stmt *s, const StackFrameContext *callee,=20
-                         const CFGBlock *blk, unsigned idx)
-    : Eng(eng), Pred(pred), CE(s), CalleeCtx(callee), Block(blk), Index(id=
x) {}
-
-  const ProgramState *getState() const { return Pred->getState(); }
-
-  const LocationContext *getLocationContext() const {=20
-    return Pred->getLocationContext();
-  }
-
-  const Stmt *getCallExpr() const { return CE; }
-
-  const StackFrameContext *getCalleeContext() const { return CalleeCtx; }
-
-  const CFGBlock *getBlock() const { return Block; }
-
-  unsigned getIndex() const { return Index; }
-
-  void generateNode(const ProgramState *state);
-};
-
-class CallExitNodeBuilder {
-  CoreEngine &Eng;
-  const ExplodedNode *Pred;
-
-public:
-  CallExitNodeBuilder(CoreEngine &eng, const ExplodedNode *pred)
-    : Eng(eng), Pred(pred) {}
-
-  const ExplodedNode *getPredecessor() const { return Pred; }
-
-  const ProgramState *getState() const { return Pred->getState(); }
-
-  void generateNode(const ProgramState *state);
-};=20
-
-} // end GR namespace
-
+} // end ento namespace
 } // end clang namespace
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/Environment.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/Environment.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/Environment.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_GR_ENVIRONMENT_H
 #define LLVM_CLANG_GR_ENVIRONMENT_H
=20
+#include "clang/Analysis/AnalysisContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "llvm/ADT/ImmutableMap.h"
=20
@@ -26,15 +27,39 @@
 class EnvironmentManager;
 class SValBuilder;
=20
-/// Environment - An immutable map from Stmts to their current
-///  symbolic values (SVals).
-///
+/// An entry in the environment consists of a Stmt and an LocationContext.
+/// This allows the environment to manage context-sensitive bindings,
+/// which is essentially for modeling recursive function analysis, among
+/// other things.
+class EnvironmentEntry : public std::pair<const Stmt*,
+                                          const StackFrameContext *> {
+public:
+  EnvironmentEntry(const Stmt *s, const LocationContext *L)
+    : std::pair<const Stmt*,
+                const StackFrameContext*>(s, L ? L->getCurrentStackFrame()=
:0) {}
+
+  const Stmt *getStmt() const { return first; }
+  const LocationContext *getLocationContext() const { return second; }
+ =20
+  /// Profile an EnvironmentEntry for inclusion in a FoldingSet.
+  static void Profile(llvm::FoldingSetNodeID &ID,
+                      const EnvironmentEntry &E) {
+    ID.AddPointer(E.getStmt());
+    ID.AddPointer(E.getLocationContext());
+  }
+ =20
+  void Profile(llvm::FoldingSetNodeID &ID) const {
+    Profile(ID, *this);
+  }
+};
+
+/// An immutable map from EnvironemntEntries to SVals.
 class Environment {
 private:
   friend class EnvironmentManager;
=20
   // Type definitions.
-  typedef llvm::ImmutableMap<const Stmt*,SVal> BindingsTy;
+  typedef llvm::ImmutableMap<EnvironmentEntry, SVal> BindingsTy;
=20
   // Data.
   BindingsTy ExprBindings;
@@ -42,18 +67,18 @@
   Environment(BindingsTy eb)
     : ExprBindings(eb) {}
=20
-  SVal lookupExpr(const Stmt *E) const;
+  SVal lookupExpr(const EnvironmentEntry &E) const;
=20
 public:
   typedef BindingsTy::iterator iterator;
   iterator begin() const { return ExprBindings.begin(); }
   iterator end() const { return ExprBindings.end(); }
=20
-
-  /// getSVal - Fetches the current binding of the expression in the
-  ///  Environment.
-  SVal getSVal(const Stmt *Ex, SValBuilder& svalBuilder,
-	       bool useOnlyDirectBindings =3D false) const;
+  /// Fetches the current binding of the expression in the
+  /// Environment.
+  SVal getSVal(const EnvironmentEntry &E,
+               SValBuilder &svalBuilder,
+               bool useOnlyDirectBindings =3D false) const;
=20
   /// Profile - Profile the contents of an Environment object for use
   ///  in a FoldingSet.
@@ -70,6 +95,12 @@
   bool operator=3D=3D(const Environment& RHS) const {
     return ExprBindings =3D=3D RHS.ExprBindings;
   }
+ =20
+  void print(raw_ostream &Out, const char *NL, const char *Sep) const;
+ =20
+private:
+  void printAux(raw_ostream &Out, bool printLocations,
+                const char *NL, const char *Sep) const;
 };
=20
 class EnvironmentManager {
@@ -85,17 +116,20 @@
     return Environment(F.getEmptyMap());
   }
=20
-  /// Bind the value 'V' to the statement 'S'.
-  Environment bindExpr(Environment Env, const Stmt *S, SVal V,
+  /// Bind a symbolic value to the given environment entry.
+  Environment bindExpr(Environment Env, const EnvironmentEntry &E, SVal V,
                        bool Invalidate);
  =20
-  /// Bind the location 'location' and value 'V' to the statement 'S'.  Th=
is
-  /// is used when simulating loads/stores.
-  Environment bindExprAndLocation(Environment Env, const Stmt *S, SVal loc=
ation,
+  /// Bind the location 'location' and value 'V' to the specified
+  /// environment entry.
+  Environment bindExprAndLocation(Environment Env,
+                                  const EnvironmentEntry &E,
+                                  SVal location,
                                   SVal V);
=20
   Environment removeDeadBindings(Environment Env,
-                                 SymbolReaper &SymReaper, const ProgramSta=
te *ST);
+                                 SymbolReaper &SymReaper,
+                                 ProgramStateRef state);
 };
=20
 } // end GR namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ExplodedGraph.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ExplodedGraph.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,6 +32,7 @@
 #include "llvm/Support/Casting.h"
 #include "clang/Analysis/Support/BumpVector.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include <vector>
=20
 namespace clang {
=20
@@ -53,7 +54,7 @@
 class ExplodedNode : public llvm::FoldingSetNode {
   friend class ExplodedGraph;
   friend class CoreEngine;
-  friend class StmtNodeBuilder;
+  friend class NodeBuilder;
   friend class BranchNodeBuilder;
   friend class IndirectGotoNodeBuilder;
   friend class SwitchNodeBuilder;
@@ -106,7 +107,7 @@
   const ProgramPoint Location;
=20
   /// State - The state associated with this node.
-  const ProgramState *State;
+  ProgramStateRef State;
=20
   /// Preds - The predecessors of this node.
   NodeGroup Preds;
@@ -116,14 +117,14 @@
=20
 public:
=20
-  explicit ExplodedNode(const ProgramPoint &loc, const ProgramState *state)
+  explicit ExplodedNode(const ProgramPoint &loc, ProgramStateRef state,
+                        bool IsSink)
     : Location(loc), State(state) {
-    const_cast<ProgramState*>(State)->incrementReferenceCount();
+    if (IsSink)
+      Succs.setFlag();
   }
  =20
-  ~ExplodedNode() {
-    const_cast<ProgramState*>(State)->decrementReferenceCount();
-  }
+  ~ExplodedNode() {}
=20
   /// getLocation - Returns the edge associated with the given node.
   ProgramPoint getLocation() const { return Location; }
@@ -143,19 +144,22 @@
     return *getLocationContext()->getAnalysis<T>();
   }
=20
-  const ProgramState *getState() const { return State; }
+  ProgramStateRef getState() const { return State; }
=20
   template <typename T>
   const T* getLocationAs() const { return llvm::dyn_cast<T>(&Location); }
=20
   static void Profile(llvm::FoldingSetNodeID &ID,
-                      const ProgramPoint &Loc, const ProgramState *state) {
+                      const ProgramPoint &Loc,
+                      ProgramStateRef state,
+                      bool IsSink) {
     ID.Add(Loc);
-    ID.AddPointer(state);
+    ID.AddPointer(state.getPtr());
+    ID.AddBoolean(IsSink);
   }
=20
   void Profile(llvm::FoldingSetNodeID& ID) const {
-    Profile(ID, getLocation(), getState());
+    Profile(ID, getLocation(), getState(), isSink());
   }
=20
   /// addPredeccessor - Adds a predecessor to the current node, and
@@ -168,7 +172,10 @@
   bool pred_empty() const { return Preds.empty(); }
=20
   bool isSink() const { return Succs.getFlag(); }
-  void markAsSink() { Succs.setFlag(); }
+
+   bool hasSinglePred() const {
+    return (pred_size() =3D=3D 1);
+  }
=20
   ExplodedNode *getFirstPred() {
     return pred_empty() ? NULL : *(pred_begin());
@@ -223,6 +230,7 @@
=20
 // FIXME: Is this class necessary?
 class InterExplodedGraphMap {
+  virtual void anchor();
   llvm::DenseMap<const ExplodedNode*, ExplodedNode*> M;
   friend class ExplodedGraph;
=20
@@ -238,18 +246,17 @@
   friend class CoreEngine;
=20
   // Type definitions.
-  typedef SmallVector<ExplodedNode*,2>    RootsTy;
-  typedef SmallVector<ExplodedNode*,10>   EndNodesTy;
+  typedef std::vector<ExplodedNode *> NodeVector;
=20
-  /// Roots - The roots of the simulation graph. Usually there will be only
+  /// The roots of the simulation graph. Usually there will be only
   /// one, but clients are free to establish multiple subgraphs within a s=
ingle
   /// SimulGraph. Moreover, these subgraphs can often merge when paths from
   /// different roots reach the same state at the same program location.
-  RootsTy Roots;
+  NodeVector Roots;
=20
-  /// EndNodes - The nodes in the simulation graph which have been
-  ///  specially marked as the endpoint of an abstract simulation path.
-  EndNodesTy EndNodes;
+  /// The nodes in the simulation graph which have been
+  /// specially marked as the endpoint of an abstract simulation path.
+  NodeVector EndNodes;
=20
   /// Nodes - The nodes in the graph.
   llvm::FoldingSet<ExplodedNode> Nodes;
@@ -262,21 +269,25 @@
   unsigned NumNodes;
  =20
   /// A list of recently allocated nodes that can potentially be recycled.
-  void *recentlyAllocatedNodes;
+  NodeVector ChangedNodes;
  =20
   /// A list of nodes that can be reused.
-  void *freeNodes;
+  NodeVector FreeNodes;
  =20
   /// A flag that indicates whether nodes should be recycled.
   bool reclaimNodes;
+ =20
+  /// Counter to determine when to reclaim nodes.
+  unsigned reclaimCounter;
=20
 public:
-  /// getNode - Retrieve the node associated with a (Location,State) pair,
+
+  /// \brief Retrieve the node associated with a (Location,State) pair,
   ///  where the 'Location' is a ProgramPoint in the CFG.  If no node for
-  ///  this pair exists, it is created.  IsNew is set to true if
+  ///  this pair exists, it is created. IsNew is set to true if
   ///  the node was freshly created.
-
-  ExplodedNode *getNode(const ProgramPoint &L, const ProgramState *State,
+  ExplodedNode *getNode(const ProgramPoint &L, ProgramStateRef State,
+                        bool IsSink =3D false,
                         bool* IsNew =3D 0);
=20
   ExplodedGraph* MakeEmptyGraph() const {
@@ -295,9 +306,7 @@
     return V;
   }
=20
-  ExplodedGraph()
-    : NumNodes(0), recentlyAllocatedNodes(0),
-      freeNodes(0), reclaimNodes(false) {}
+  ExplodedGraph();
=20
   ~ExplodedGraph();
  =20
@@ -310,10 +319,10 @@
   // Iterators.
   typedef ExplodedNode                        NodeTy;
   typedef llvm::FoldingSet<ExplodedNode>      AllNodesTy;
-  typedef NodeTy**                            roots_iterator;
-  typedef NodeTy* const *                     const_roots_iterator;
-  typedef NodeTy**                            eop_iterator;
-  typedef NodeTy* const *                     const_eop_iterator;
+  typedef NodeVector::iterator                roots_iterator;
+  typedef NodeVector::const_iterator          const_roots_iterator;
+  typedef NodeVector::iterator                eop_iterator;
+  typedef NodeVector::const_iterator          const_eop_iterator;
   typedef AllNodesTy::iterator                node_iterator;
   typedef AllNodesTy::const_iterator          const_node_iterator;
=20
@@ -362,6 +371,10 @@
   /// Reclaim "uninteresting" nodes created since the last time this method
   /// was called.
   void reclaimRecentlyAllocatedNodes();
+
+private:
+  bool shouldCollect(const ExplodedNode *node);
+  void collectNode(ExplodedNode *node);
 };
=20
 class ExplodedNodeSet {
@@ -380,19 +393,16 @@
     if (N && !static_cast<ExplodedNode*>(N)->isSink()) Impl.insert(N);
   }
=20
-  ExplodedNodeSet &operator=3D(const ExplodedNodeSet &X) {
-    Impl =3D X.Impl;
-    return *this;
-  }
-
   typedef ImplTy::iterator       iterator;
   typedef ImplTy::const_iterator const_iterator;
=20
   unsigned size() const { return Impl.size();  }
   bool empty()    const { return Impl.empty(); }
+  bool erase(ExplodedNode *N) { return Impl.erase(N); }
=20
   void clear() { Impl.clear(); }
   void insert(const ExplodedNodeSet &S) {
+    assert(&S !=3D this);
     if (empty())
       Impl =3D S.Impl;
     else
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ExprEngine.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ExprEngine.h	Tue Apr 17 11:51:51 2012 +0300
@@ -20,16 +20,24 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/Type.h"
-#include "clang/AST/ExprObjC.h"
-#include "clang/AST/ExprCXX.h"
-#include "clang/AST/StmtObjC.h"
=20
 namespace clang {
=20
+class AnalysisDeclContextManager;
+class CXXCatchStmt;
+class CXXConstructExpr;
+class CXXDeleteExpr;
+class CXXNewExpr;
+class CXXTemporaryObjectExpr;
+class CXXThisExpr;
+class MaterializeTemporaryExpr;
+class ObjCAtSynchronizedStmt;
 class ObjCForCollectionStmt;
-
+ =20
 namespace ento {
=20
 class AnalysisManager;
@@ -38,16 +46,14 @@
=20
 class ExprEngine : public SubEngine {
   AnalysisManager &AMgr;
+ =20
+  AnalysisDeclContextManager &AnalysisDeclContexts;
=20
   CoreEngine Engine;
=20
   /// G - the simulation graph.
   ExplodedGraph& G;
=20
-  /// Builder - The current StmtNodeBuilder which is used when building the
-  ///  nodes for a given statement.
-  StmtNodeBuilder* Builder;
-
   /// StateMgr - Object that manages the data for all created states.
   ProgramStateManager StateMgr;
=20
@@ -62,10 +68,12 @@
=20
   /// CleanedState - The state for EntryNode "cleaned" of all dead
   ///  variables and symbols (as determined by a liveness analysis).
-  const ProgramState *CleanedState;
+  ProgramStateRef CleanedState;
=20
   /// currentStmt - The current block-level statement.
   const Stmt *currentStmt;
+  unsigned int currentStmtIdx;
+  const NodeBuilderContext *currentBuilderContext;
=20
   /// Obj-C Class Identifiers.
   IdentifierInfo* NSExceptionII;
@@ -83,21 +91,25 @@
   GRBugReporter BR;
=20
 public:
-  ExprEngine(AnalysisManager &mgr, bool gcEnabled);
+  ExprEngine(AnalysisManager &mgr, bool gcEnabled,
+             SetOfConstDecls *VisitedCallees,
+             FunctionSummariesTy *FS);
=20
   ~ExprEngine();
=20
-  void ExecuteWorkList(const LocationContext *L, unsigned Steps =3D 150000=
) {
-    Engine.ExecuteWorkList(L, Steps, 0);
+  /// Returns true if there is still simulation state on the worklist.
+  bool ExecuteWorkList(const LocationContext *L, unsigned Steps =3D 150000=
) {
+    return Engine.ExecuteWorkList(L, Steps, 0);
   }
=20
   /// Execute the work list with an initial state. Nodes that reaches the =
exit
   /// of the function are added into the Dst set, which represent the exit
-  /// state of the function call.
-  void ExecuteWorkListWithInitialState(const LocationContext *L, unsigned =
Steps,
-                                       const ProgramState *InitState,=20
+  /// state of the function call. Returns true if there is still simulation
+  /// state on the worklist.
+  bool ExecuteWorkListWithInitialState(const LocationContext *L, unsigned =
Steps,
+                                       ProgramStateRef InitState,=20
                                        ExplodedNodeSet &Dst) {
-    Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst);
+    return Engine.ExecuteWorkListWithInitialState(L, Steps, InitState, Dst=
);
   }
=20
   /// getContext - Return the ASTContext associated with this analysis.
@@ -113,10 +125,19 @@
=20
   BugReporter& getBugReporter() { return BR; }
=20
-  StmtNodeBuilder &getBuilder() { assert(Builder); return *Builder; }
+  const NodeBuilderContext &getBuilderContext() {
+    assert(currentBuilderContext);
+    return *currentBuilderContext;
+  }
=20
   bool isObjCGCEnabled() { return ObjCGCEnabled; }
=20
+  const Stmt *getStmt() const;
+
+  void GenerateAutoTransition(ExplodedNode *N);
+  void enqueueEndOfPath(ExplodedNodeSet &S);
+  void GenerateCallExitNode(ExplodedNode *N);
+
   /// ViewGraph - Visualize the ExplodedGraph created by executing the
   ///  simulation.
   void ViewGraph(bool trim =3D false);
@@ -125,36 +146,43 @@
=20
   /// getInitialState - Return the initial state used for the root vertex
   ///  in the ExplodedGraph.
-  const ProgramState *getInitialState(const LocationContext *InitLoc);
+  ProgramStateRef getInitialState(const LocationContext *InitLoc);
=20
   ExplodedGraph& getGraph() { return G; }
   const ExplodedGraph& getGraph() const { return G; }
=20
   /// processCFGElement - Called by CoreEngine. Used to generate new succe=
ssor
   ///  nodes by processing the 'effects' of a CFG element.
-  void processCFGElement(const CFGElement E, StmtNodeBuilder& builder);
+  void processCFGElement(const CFGElement E, ExplodedNode *Pred,
+                         unsigned StmtIdx, NodeBuilderContext *Ctx);
=20
-  void ProcessStmt(const CFGStmt S, StmtNodeBuilder &builder);
+  void ProcessStmt(const CFGStmt S, ExplodedNode *Pred);
=20
-  void ProcessInitializer(const CFGInitializer I, StmtNodeBuilder &builder=
);
+  void ProcessInitializer(const CFGInitializer I, ExplodedNode *Pred);
=20
-  void ProcessImplicitDtor(const CFGImplicitDtor D, StmtNodeBuilder &build=
er);
+  void ProcessImplicitDtor(const CFGImplicitDtor D, ExplodedNode *Pred);
=20
   void ProcessAutomaticObjDtor(const CFGAutomaticObjDtor D,=20
-                            StmtNodeBuilder &builder);
-  void ProcessBaseDtor(const CFGBaseDtor D, StmtNodeBuilder &builder);
-  void ProcessMemberDtor(const CFGMemberDtor D, StmtNodeBuilder &builder);
+                               ExplodedNode *Pred, ExplodedNodeSet &Dst);
+  void ProcessBaseDtor(const CFGBaseDtor D,
+                       ExplodedNode *Pred, ExplodedNodeSet &Dst);
+  void ProcessMemberDtor(const CFGMemberDtor D,
+                         ExplodedNode *Pred, ExplodedNodeSet &Dst);
   void ProcessTemporaryDtor(const CFGTemporaryDtor D,=20
-                            StmtNodeBuilder &builder);
+                            ExplodedNode *Pred, ExplodedNodeSet &Dst);
=20
   /// Called by CoreEngine when processing the entrance of a CFGBlock.
-  virtual void processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
-                                GenericNodeBuilder<BlockEntrance> &nodeBui=
lder);
+  virtual void processCFGBlockEntrance(const BlockEdge &L,
+                                       NodeBuilderWithSinks &nodeBuilder);
  =20
   /// ProcessBranch - Called by CoreEngine.  Used to generate successor
   ///  nodes by processing the 'effects' of a branch condition.
   void processBranch(const Stmt *Condition, const Stmt *Term,=20
-                     BranchNodeBuilder& builder);
+                     NodeBuilderContext& BuilderCtx,
+                     ExplodedNode *Pred,
+                     ExplodedNodeSet &Dst,
+                     const CFGBlock *DstT,
+                     const CFGBlock *DstF);
=20
   /// processIndirectGoto - Called by CoreEngine.  Used to generate succes=
sor
   ///  nodes by processing the 'effects' of a computed goto jump.
@@ -166,35 +194,36 @@
=20
   /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
   ///  nodes when the control reaches the end of a function.
-  void processEndOfFunction(EndOfFunctionNodeBuilder& builder);
+  void processEndOfFunction(NodeBuilderContext& BC);
=20
   /// Generate the entry node of the callee.
-  void processCallEnter(CallEnterNodeBuilder &builder);
+  void processCallEnter(CallEnter CE, ExplodedNode *Pred);
=20
   /// Generate the first post callsite node.
-  void processCallExit(CallExitNodeBuilder &builder);
+  void processCallExit(ExplodedNode *Pred);
=20
   /// Called by CoreEngine when the analysis worklist has terminated.
   void processEndWorklist(bool hasWorkRemaining);
=20
   /// evalAssume - Callback function invoked by the ConstraintManager when
   ///  making assumptions about state values.
-  const ProgramState *processAssume(const ProgramState *state, SVal cond,b=
ool assumption);
+  ProgramStateRef processAssume(ProgramStateRef state, SVal cond,bool assu=
mption);
=20
   /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine=
 if a
   ///  region change should trigger a processRegionChanges update.
-  bool wantsRegionChangeUpdate(const ProgramState *state);
+  bool wantsRegionChangeUpdate(ProgramStateRef state);
=20
   /// processRegionChanges - Called by ProgramStateManager whenever a chan=
ge is made
   ///  to the store. Used to update checkers that track region values.
-  const ProgramState *
-  processRegionChanges(const ProgramState *state,
+  ProgramStateRef=20
+  processRegionChanges(ProgramStateRef state,
                        const StoreManager::InvalidatedSymbols *invalidated,
                        ArrayRef<const MemRegion *> ExplicitRegions,
-                       ArrayRef<const MemRegion *> Regions);
+                       ArrayRef<const MemRegion *> Regions,
+                       const CallOrObjCMessage *Call);
=20
   /// printState - Called by ProgramStateManager to print checker-specific=
 data.
-  void printState(raw_ostream &Out, const ProgramState *State,
+  void printState(raw_ostream &Out, ProgramStateRef State,
                   const char *NL, const char *Sep);
=20
   virtual ProgramStateManager& getStateManager() { return StateMgr; }
@@ -225,11 +254,6 @@
   const CoreEngine &getCoreEngine() const { return Engine; }
=20
 public:
-  ExplodedNode *MakeNode(ExplodedNodeSet &Dst, const Stmt *S,=20
-                         ExplodedNode *Pred, const ProgramState *St,
-                         ProgramPoint::Kind K =3D ProgramPoint::PostStmtKi=
nd,
-                         const ProgramPointTag *tag =3D 0);
-
   /// Visit - Transfer function logic for all statements.  Dispatches to
   ///  other functions that handle specific kinds of statements.
   void Visit(const Stmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst);
@@ -241,16 +265,6 @@
=20
   /// VisitAsmStmt - Transfer function logic for inline asm.
   void VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred, ExplodedNodeSet =
&Dst);
-
-  void VisitAsmStmtHelperOutputs(const AsmStmt *A,
-                                 AsmStmt::const_outputs_iterator I,
-                                 AsmStmt::const_outputs_iterator E,
-                                 ExplodedNode *Pred, ExplodedNodeSet &Dst);
-
-  void VisitAsmStmtHelperInputs(const AsmStmt *A,
-                                AsmStmt::const_inputs_iterator I,
-                                AsmStmt::const_inputs_iterator E,
-                                ExplodedNode *Pred, ExplodedNodeSet &Dst);
  =20
   /// VisitBlockExpr - Transfer function logic for BlockExprs.
   void VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,=20
@@ -328,13 +342,19 @@
   void VisitUnaryOperator(const UnaryOperator* B, ExplodedNode *Pred,=20
                           ExplodedNodeSet &Dst);
=20
+  /// Handle ++ and -- (both pre- and post-increment).
+  void VisitIncrementDecrementOperator(const UnaryOperator* U,
+                                       ExplodedNode *Pred,
+                                       ExplodedNodeSet &Dst);
+ =20
+  void VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred,
+                         ExplodedNodeSet &Dst);
+
   void VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,=20
                         ExplodedNodeSet & Dst);
=20
   void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *expr,
-                                   ExplodedNode *Pred, ExplodedNodeSet &Ds=
t) {
-    VisitCXXConstructExpr(expr, 0, Pred, Dst);
-  }
+                                   ExplodedNode *Pred, ExplodedNodeSet &Ds=
t);
=20
   void VisitCXXConstructExpr(const CXXConstructExpr *E, const MemRegion *D=
est,
                              ExplodedNode *Pred, ExplodedNodeSet &Dst);
@@ -349,9 +369,6 @@
   void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, ExplodedNode *Pred,
                           ExplodedNodeSet &Dst);
=20
-  void VisitAggExpr(const Expr *E, const MemRegion *Dest, ExplodedNode *Pr=
ed,
-                    ExplodedNodeSet &Dst);
-
   /// Create a C++ temporary object for an rvalue.
   void CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
                                 ExplodedNode *Pred,=20
@@ -363,17 +380,7 @@
=20
   const CXXThisRegion *getCXXThisRegion(const CXXMethodDecl *decl,
                                         const StackFrameContext *frameCtx);
-
-  /// Evaluate arguments with a work list algorithm.
-  void evalArguments(ConstExprIterator AI, ConstExprIterator AE,
-                     const FunctionProtoType *FnType,=20
-                     ExplodedNode *Pred, ExplodedNodeSet &Dst,
-                     bool FstArgAsLValue =3D false);
  =20
-  /// Evaluate callee expression (for a function call).
-  void evalCallee(const CallExpr *callExpr, const ExplodedNodeSet &src,
-                  ExplodedNodeSet &dest);
-
   /// evalEagerlyAssume - Given the nodes in 'Src', eagerly assume symbolic
   ///  expressions of the form 'x !=3D 0' and generate new nodes (stored i=
n Dst)
   ///  with those assumptions.
@@ -393,31 +400,34 @@
=20
 public:
=20
-  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
+  SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
                  NonLoc L, NonLoc R, QualType T) {
     return svalBuilder.evalBinOpNN(state, op, L, R, T);
   }
=20
-  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
+  SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
                  NonLoc L, SVal R, QualType T) {
     return R.isValid() ? svalBuilder.evalBinOpNN(state,op,L, cast<NonLoc>(=
R), T) : R;
   }
=20
-  SVal evalBinOp(const ProgramState *ST, BinaryOperator::Opcode Op,
+  SVal evalBinOp(ProgramStateRef ST, BinaryOperator::Opcode Op,
                  SVal LHS, SVal RHS, QualType T) {
     return svalBuilder.evalBinOp(ST, Op, LHS, RHS, T);
   }
  =20
 protected:
-  void evalObjCMessage(ExplodedNodeSet &Dst, const ObjCMessage &msg,=20
-                       ExplodedNode *Pred, const ProgramState *state);
+  void evalObjCMessage(StmtNodeBuilder &Bldr, const ObjCMessage &msg,
+                       ExplodedNode *Pred, ProgramStateRef state,
+                       bool GenSink);
=20
-  const ProgramState *invalidateArguments(const ProgramState *State,
+  ProgramStateRef invalidateArguments(ProgramStateRef State,
                                           const CallOrObjCMessage &Call,
                                           const LocationContext *LC);
=20
-  const ProgramState *MarkBranch(const ProgramState *St, const Stmt *Termi=
nator,
-                            bool branchTaken);
+  ProgramStateRef MarkBranch(ProgramStateRef state,
+                                 const Stmt *Terminator,
+                                 const LocationContext *LCtx,
+                                 bool branchTaken);
=20
   /// evalBind - Handle the semantics of binding a value to a specific loc=
ation.
   ///  This method is used by evalStore, VisitDeclStmt, and others.
@@ -431,34 +441,52 @@
   // be the same as Pred->state, and when 'location' may not be the
   // same as state->getLValue(Ex).
   /// Simulate a read of the result of Ex.
-  void evalLoad(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *Pred,
-                const ProgramState *St, SVal location, const ProgramPointT=
ag *tag =3D 0,
+  void evalLoad(ExplodedNodeSet &Dst,
+                const Expr *NodeEx,  /* Eventually will be a CFGStmt */
+                const Expr *BoundExpr,
+                ExplodedNode *Pred,
+                ProgramStateRef St,
+                SVal location,
+                const ProgramPointTag *tag =3D 0,
                 QualType LoadTy =3D QualType());
=20
   // FIXME: 'tag' should be removed, and a LocationContext should be used
   // instead.
   void evalStore(ExplodedNodeSet &Dst, const Expr *AssignE, const Expr *St=
oreE,
-                 ExplodedNode *Pred, const ProgramState *St, SVal TargetLV=
, SVal Val,
+                 ExplodedNode *Pred, ProgramStateRef St, SVal TargetLV, SV=
al Val,
                  const ProgramPointTag *tag =3D 0);
 private:
-  void evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex, ExplodedNode *=
Pred,
-                      const ProgramState *St, SVal location, const Program=
PointTag *tag,
+  void evalLoadCommon(ExplodedNodeSet &Dst,
+                      const Expr *NodeEx,  /* Eventually will be a CFGStmt=
 */
+                      const Expr *BoundEx,
+                      ExplodedNode *Pred,
+                      ProgramStateRef St,
+                      SVal location,
+                      const ProgramPointTag *tag,
                       QualType LoadTy);
=20
   // FIXME: 'tag' should be removed, and a LocationContext should be used
   // instead.
-  void evalLocation(ExplodedNodeSet &Dst, const Stmt *S, ExplodedNode *Pre=
d,
-                    const ProgramState *St, SVal location,
+  void evalLocation(ExplodedNodeSet &Dst,
+                    const Stmt *NodeEx, /* This will eventually be a CFGSt=
mt */
+                    const Stmt *BoundEx,
+                    ExplodedNode *Pred,
+                    ProgramStateRef St, SVal location,
                     const ProgramPointTag *tag, bool isLoad);
=20
+  bool shouldInlineDecl(const FunctionDecl *FD, ExplodedNode *Pred);
   bool InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE, ExplodedNode *=
Pred);
- =20
- =20
-public:
-  /// Returns true if calling the specific function or method would possib=
ly
-  /// cause global variables to be invalidated.
-  bool doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const;
- =20
+
+  bool replayWithoutInlining(ExplodedNode *P, const LocationContext *Calle=
eLC);
+};
+
+/// Traits for storing the call processing policy inside GDM.
+/// The GDM stores the corresponding CallExpr pointer.
+struct ReplayWithoutInlining{};
+template <>
+struct ProgramStateTrait<ReplayWithoutInlining> :
+  public ProgramStatePartialTrait<void*> {
+  static void *GDMIndex() { static int index =3D 0; return &index; }
 };
=20
 } // end ento namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/MemRegion.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/MemRegion.h	Tue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
=20
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/Decl.h"
-#include "clang/AST/DeclObjC.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -73,12 +73,16 @@
     StackArgumentsSpaceRegionKind,
     HeapSpaceRegionKind,
     UnknownSpaceRegionKind,
-    NonStaticGlobalSpaceRegionKind,
     StaticGlobalSpaceRegionKind,
-    BEG_GLOBAL_MEMSPACES =3D NonStaticGlobalSpaceRegionKind,
-    END_GLOBAL_MEMSPACES =3D StaticGlobalSpaceRegionKind,
+    GlobalInternalSpaceRegionKind,
+    GlobalSystemSpaceRegionKind,
+    GlobalImmutableSpaceRegionKind,
+    BEG_NON_STATIC_GLOBAL_MEMSPACES =3D GlobalInternalSpaceRegionKind,
+    END_NON_STATIC_GLOBAL_MEMSPACES =3D GlobalImmutableSpaceRegionKind,
+    BEG_GLOBAL_MEMSPACES =3D StaticGlobalSpaceRegionKind,
+    END_GLOBAL_MEMSPACES =3D GlobalImmutableSpaceRegionKind,
     BEG_MEMSPACES =3D GenericMemSpaceRegionKind,
-    END_MEMSPACES =3D StaticGlobalSpaceRegionKind,
+    END_MEMSPACES =3D GlobalImmutableSpaceRegionKind,
     // Untyped regions.
     SymbolicRegionKind,
     AllocaRegionKind,
@@ -91,6 +95,7 @@
     CompoundLiteralRegionKind =3D BEG_TYPED_VALUE_REGIONS,
     CXXThisRegionKind,
     StringRegionKind,
+    ObjCStringRegionKind,
     ElementRegionKind,
     // Decl Regions.
     BEG_DECL_REGIONS,
@@ -118,8 +123,6 @@
=20
   virtual MemRegionManager* getMemRegionManager() const =3D 0;
=20
-  std::string getString() const;
-
   const MemSpaceRegion *getMemorySpace() const;
=20
   const MemRegion *getBaseRegion() const;
@@ -137,10 +140,16 @@
   /// Compute the offset within the top level memory object.
   RegionOffset getAsOffset() const;
=20
+  /// \brief Get a string representation of a region for debug use.
+  std::string getString() const;
+
   virtual void dumpToStream(raw_ostream &os) const;
=20
   void dump() const;
=20
+  /// \brief Print the region for use in diagnostics.
+  virtual void dumpPretty(raw_ostream &os) const;
+
   Kind getKind() const { return kind; }
=20
   template<typename RegionTy> const RegionTy* getAs() const;
@@ -150,7 +159,7 @@
   static bool classof(const MemRegion*) { return true; }
 };
=20
-/// MemSpaceRegion - A memory region that represents and "memory space";
+/// MemSpaceRegion - A memory region that represents a "memory space";
 ///  for example, the set of global variables, the stack frame, etc.
 class MemSpaceRegion : public MemRegion {
 protected:
@@ -177,6 +186,7 @@
 };
  =20
 class GlobalsSpaceRegion : public MemSpaceRegion {
+  virtual void anchor();
 protected:
   GlobalsSpaceRegion(MemRegionManager *mgr, Kind k)
     : MemSpaceRegion(mgr, k) {}
@@ -186,7 +196,11 @@
     return k >=3D BEG_GLOBAL_MEMSPACES && k <=3D END_GLOBAL_MEMSPACES;
   }
 };
- =20
+
+/// \class The region of the static variables within the current CodeTextR=
egion
+/// scope.
+/// Currently, only the static locals are placed there, so we know that th=
ese
+/// variables do not get invalidated by calls to other functions.
 class StaticGlobalSpaceRegion : public GlobalsSpaceRegion {
   friend class MemRegionManager;
=20
@@ -206,23 +220,88 @@
     return R->getKind() =3D=3D StaticGlobalSpaceRegionKind;
   }
 };
- =20
+
+/// \class The region for all the non-static global variables.
+///
+/// This class is further split into subclasses for efficient implementati=
on of
+/// invalidating a set of related global values as is done in
+/// RegionStoreManager::invalidateRegions (instead of finding all the depe=
ndent
+/// globals, we invalidate the whole parent region).
 class NonStaticGlobalSpaceRegion : public GlobalsSpaceRegion {
   friend class MemRegionManager;
  =20
-  NonStaticGlobalSpaceRegion(MemRegionManager *mgr)
-    : GlobalsSpaceRegion(mgr, NonStaticGlobalSpaceRegionKind) {}
+protected:
+  NonStaticGlobalSpaceRegion(MemRegionManager *mgr, Kind k)
+    : GlobalsSpaceRegion(mgr, k) {}
  =20
 public:
=20
   void dumpToStream(raw_ostream &os) const;
=20
   static bool classof(const MemRegion *R) {
-    return R->getKind() =3D=3D NonStaticGlobalSpaceRegionKind;
+    Kind k =3D R->getKind();
+    return k >=3D BEG_NON_STATIC_GLOBAL_MEMSPACES &&
+           k <=3D END_NON_STATIC_GLOBAL_MEMSPACES;
   }
 };
- =20
+
+/// \class The region containing globals which are defined in system/exter=
nal
+/// headers and are considered modifiable by system calls (ex: errno).
+class GlobalSystemSpaceRegion : public NonStaticGlobalSpaceRegion {
+  friend class MemRegionManager;
+
+  GlobalSystemSpaceRegion(MemRegionManager *mgr)
+    : NonStaticGlobalSpaceRegion(mgr, GlobalSystemSpaceRegionKind) {}
+
+public:
+
+  void dumpToStream(raw_ostream &os) const;
+
+  static bool classof(const MemRegion *R) {
+    return R->getKind() =3D=3D GlobalSystemSpaceRegionKind;
+  }
+};
+
+/// \class The region containing globals which are considered not to be mo=
dified
+/// or point to data which could be modified as a result of a function call
+/// (system or internal). Ex: Const global scalars would be modeled as par=
t of
+/// this region. This region also includes most system globals since they =
have
+/// low chance of being modified.
+class GlobalImmutableSpaceRegion : public NonStaticGlobalSpaceRegion {
+  friend class MemRegionManager;
+
+  GlobalImmutableSpaceRegion(MemRegionManager *mgr)
+    : NonStaticGlobalSpaceRegion(mgr, GlobalImmutableSpaceRegionKind) {}
+
+public:
+
+  void dumpToStream(raw_ostream &os) const;
+
+  static bool classof(const MemRegion *R) {
+    return R->getKind() =3D=3D GlobalImmutableSpaceRegionKind;
+  }
+};
+
+/// \class The region containing globals which can be modified by calls to
+/// "internally" defined functions - (for now just) functions other then s=
ystem
+/// calls.
+class GlobalInternalSpaceRegion : public NonStaticGlobalSpaceRegion {
+  friend class MemRegionManager;
+
+  GlobalInternalSpaceRegion(MemRegionManager *mgr)
+    : NonStaticGlobalSpaceRegion(mgr, GlobalInternalSpaceRegionKind) {}
+
+public:
+
+  void dumpToStream(raw_ostream &os) const;
+
+  static bool classof(const MemRegion *R) {
+    return R->getKind() =3D=3D GlobalInternalSpaceRegionKind;
+  }
+};
+
 class HeapSpaceRegion : public MemSpaceRegion {
+  virtual void anchor();
   friend class MemRegionManager;
  =20
   HeapSpaceRegion(MemRegionManager *mgr)
@@ -234,6 +313,7 @@
 };
  =20
 class UnknownSpaceRegion : public MemSpaceRegion {
+  virtual void anchor();
   friend class MemRegionManager;
   UnknownSpaceRegion(MemRegionManager *mgr)
     : MemSpaceRegion(mgr, UnknownSpaceRegionKind) {}
@@ -266,7 +346,7 @@
 };
  =20
 class StackLocalsSpaceRegion : public StackSpaceRegion {
-private:
+  virtual void anchor();
   friend class MemRegionManager;
   StackLocalsSpaceRegion(MemRegionManager *mgr, const StackFrameContext *s=
fc)
     : StackSpaceRegion(mgr, StackLocalsSpaceRegionKind, sfc) {}
@@ -278,6 +358,7 @@
=20
 class StackArgumentsSpaceRegion : public StackSpaceRegion {
 private:
+  virtual void anchor();
   friend class MemRegionManager;
   StackArgumentsSpaceRegion(MemRegionManager *mgr, const StackFrameContext=
 *sfc)
     : StackSpaceRegion(mgr, StackArgumentsSpaceRegionKind, sfc) {}
@@ -291,6 +372,8 @@
 /// SubRegion - A region that subsets another larger region.  Most regions
 ///  are subclasses of SubRegion.
 class SubRegion : public MemRegion {
+private:
+  virtual void anchor();
 protected:
   const MemRegion* superRegion;
   SubRegion(const MemRegion* sReg, Kind k) : MemRegion(k), superRegion(sRe=
g) {}
@@ -351,6 +434,8 @@
=20
 /// TypedRegion - An abstract class representing regions that are typed.
 class TypedRegion : public SubRegion {
+public:
+  virtual void anchor();
 protected:
   TypedRegion(const MemRegion* sReg, Kind k) : SubRegion(sReg, k) {}
=20
@@ -371,6 +456,8 @@
=20
 /// TypedValueRegion - An abstract class representing regions having a typ=
ed value.
 class TypedValueRegion : public TypedRegion {
+public:
+  virtual void anchor();
 protected:
   TypedValueRegion(const MemRegion* sReg, Kind k) : TypedRegion(sReg, k) {}
=20
@@ -399,6 +486,8 @@
=20
=20
 class CodeTextRegion : public TypedRegion {
+public:
+  virtual void anchor();
 protected:
   CodeTextRegion(const MemRegion *sreg, Kind k) : TypedRegion(sreg, k) {}
 public:
@@ -448,11 +537,11 @@
   friend class MemRegionManager;
=20
   const BlockDecl *BD;
-  AnalysisContext *AC;
+  AnalysisDeclContext *AC;
   CanQualType locTy;
=20
   BlockTextRegion(const BlockDecl *bd, CanQualType lTy,
-                  AnalysisContext *ac, const MemRegion* sreg)
+                  AnalysisDeclContext *ac, const MemRegion* sreg)
     : CodeTextRegion(sreg, BlockTextRegionKind), BD(bd), AC(ac), locTy(lTy=
) {}
=20
 public:
@@ -464,14 +553,14 @@
     return BD;
   }
=20
-  AnalysisContext *getAnalysisContext() const { return AC; }
+  AnalysisDeclContext *getAnalysisDeclContext() const { return AC; }
    =20
   virtual void dumpToStream(raw_ostream &os) const;
  =20
   void Profile(llvm::FoldingSetNodeID& ID) const;
  =20
   static void ProfileRegion(llvm::FoldingSetNodeID& ID, const BlockDecl *B=
D,
-                            CanQualType, const AnalysisContext*,
+                            CanQualType, const AnalysisDeclContext*,
                             const MemRegion*);
  =20
   static bool classof(const MemRegion* R) {
@@ -611,6 +700,40 @@
     return R->getKind() =3D=3D StringRegionKind;
   }
 };
+ =20
+/// The region associated with an ObjCStringLiteral.
+class ObjCStringRegion : public TypedValueRegion {
+  friend class MemRegionManager;
+  const ObjCStringLiteral* Str;
+protected:
+ =20
+  ObjCStringRegion(const ObjCStringLiteral* str, const MemRegion* sreg)
+  : TypedValueRegion(sreg, ObjCStringRegionKind), Str(str) {}
+ =20
+  static void ProfileRegion(llvm::FoldingSetNodeID& ID,
+                            const ObjCStringLiteral* Str,
+                            const MemRegion* superRegion);
+ =20
+public:
+ =20
+  const ObjCStringLiteral* getObjCStringLiteral() const { return Str; }
+ =20
+  QualType getValueType() const {
+    return Str->getType();
+  }
+ =20
+  bool isBoundable() const { return false; }
+ =20
+  void Profile(llvm::FoldingSetNodeID& ID) const {
+    ProfileRegion(ID, Str, superRegion);
+  }
+ =20
+  void dumpToStream(raw_ostream &os) const;
+ =20
+  static bool classof(const MemRegion* R) {
+    return R->getKind() =3D=3D ObjCStringRegionKind;
+  }
+};
=20
 /// CompoundLiteralRegion - A memory region representing a compound litera=
l.
 ///   Compound literals are essentially temporaries that are stack allocat=
ed
@@ -695,6 +818,8 @@
   static bool classof(const MemRegion* R) {
     return R->getKind() =3D=3D VarRegionKind;
   }
+
+  void dumpPretty(raw_ostream &os) const;
 };
  =20
 /// CXXThisRegion - Represents the region for the implicit 'this' parameter
@@ -734,9 +859,6 @@
     : DeclRegion(fd, sReg, FieldRegionKind) {}
=20
 public:
-
-  void dumpToStream(raw_ostream &os) const;
-
   const FieldDecl *getDecl() const { return cast<FieldDecl>(D); }
=20
   QualType getValueType() const {
@@ -754,23 +876,23 @@
   static bool classof(const MemRegion* R) {
     return R->getKind() =3D=3D FieldRegionKind;
   }
+
+  void dumpToStream(raw_ostream &os) const;
+  void dumpPretty(raw_ostream &os) const;
 };
=20
 class ObjCIvarRegion : public DeclRegion {
=20
   friend class MemRegionManager;
=20
-  ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg)
-    : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {}
+  ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* sReg);
=20
   static void ProfileRegion(llvm::FoldingSetNodeID& ID, const ObjCIvarDecl=
 *ivd,
-                            const MemRegion* superRegion) {
-    DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind);
-  }
+                            const MemRegion* superRegion);
=20
 public:
-  const ObjCIvarDecl *getDecl() const { return cast<ObjCIvarDecl>(D); }
-  QualType getValueType() const { return getDecl()->getType(); }
+  const ObjCIvarDecl *getDecl() const;
+  QualType getValueType() const;
=20
   void dumpToStream(raw_ostream &os) const;
=20
@@ -803,6 +925,7 @@
   void dump() const;
 };
=20
+/// \brief ElementRegin is used to represent both array elements and casts.
 class ElementRegion : public TypedValueRegion {
   friend class MemRegionManager;
=20
@@ -915,7 +1038,10 @@
   llvm::BumpPtrAllocator& A;
   llvm::FoldingSet<MemRegion> Regions;
=20
-  NonStaticGlobalSpaceRegion *globals;
+  GlobalInternalSpaceRegion *InternalGlobals;
+  GlobalSystemSpaceRegion *SystemGlobals;
+  GlobalImmutableSpaceRegion *ImmutableGlobals;
+
  =20
   llvm::DenseMap<const StackFrameContext *, StackLocalsSpaceRegion *>=20
     StackLocalsSpaceRegions;
@@ -930,7 +1056,8 @@
=20
 public:
   MemRegionManager(ASTContext &c, llvm::BumpPtrAllocator& a)
-    : C(c), A(a), globals(0), heap(0), unknown(0), code(0) {}
+    : C(c), A(a), InternalGlobals(0), SystemGlobals(0), ImmutableGlobals(0=
),
+      heap(0), unknown(0), code(0) {}
=20
   ~MemRegionManager();
=20
@@ -950,7 +1077,9 @@
=20
   /// getGlobalsRegion - Retrieve the memory region associated with
   ///  global variables.
-  const GlobalsSpaceRegion *getGlobalsRegion(const CodeTextRegion *R =3D 0=
);
+  const GlobalsSpaceRegion *getGlobalsRegion(
+      MemRegion::Kind K =3D MemRegion::GlobalInternalSpaceRegionKind,
+      const CodeTextRegion *R =3D 0);
=20
   /// getHeapRegion - Retrieve the memory region associated with the
   ///  generic "heap".
@@ -980,7 +1109,9 @@
   /// getSymbolicRegion - Retrieve or create a "symbolic" memory region.
   const SymbolicRegion* getSymbolicRegion(SymbolRef sym);
=20
-  const StringRegion* getStringRegion(const StringLiteral* Str);
+  const StringRegion *getStringRegion(const StringLiteral* Str);
+
+  const ObjCStringRegion *getObjCStringRegion(const ObjCStringLiteral *Str=
);
=20
   /// getVarRegion - Retrieve or create the memory region associated with
   ///  a specified VarDecl and LocationContext.
@@ -1038,7 +1169,7 @@
   const FunctionTextRegion *getFunctionTextRegion(const FunctionDecl *FD);
   const BlockTextRegion *getBlockTextRegion(const BlockDecl *BD,
                                             CanQualType locTy,
-                                            AnalysisContext *AC);
+                                            AnalysisDeclContext *AC);
  =20
   /// getBlockDataRegion - Get the memory region associated with an instan=
ce
   ///  of a block.  Unlike many other MemRegions, the LocationContext*
@@ -1047,11 +1178,6 @@
   const BlockDataRegion *getBlockDataRegion(const BlockTextRegion *bc,
                                             const LocationContext *lc =3D =
NULL);
=20
-  bool isGlobalsRegion(const MemRegion* R) {
-    assert(R);
-    return R =3D=3D globals;
-  }
- =20
 private:
   template <typename RegionTy, typename A1>
   RegionTy* getRegion(const A1 a1);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ObjCMessage.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ObjCMessage.h	Tue Apr 17 11:51:51 2012 +0300
@@ -19,82 +19,72 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/Compiler.h"
=20
 namespace clang {
 namespace ento {
+using llvm::StrInStrNoCase;
=20
 /// \brief Represents both explicit ObjC message expressions and implicit
 /// messages that are sent for handling properties in dot syntax.
 class ObjCMessage {
-  const Expr *MsgOrPropE;
-  const Expr *OriginE;
-  bool IsPropSetter;
-  SVal SetterArgV;
+  const ObjCMessageExpr *Msg;
+  const ObjCPropertyRefExpr *PE;
+  const bool IsPropSetter;
+public:
+  ObjCMessage() : Msg(0), PE(0), IsPropSetter(false) {}
=20
-protected:
-  ObjCMessage(const Expr *E, const Expr *origE, bool isSetter, SVal setArg=
V)
-    : MsgOrPropE(E), OriginE(origE),
-      IsPropSetter(isSetter), SetterArgV(setArgV) { }
-
-public:
-  ObjCMessage() : MsgOrPropE(0), OriginE(0) { }
-
-  ObjCMessage(const ObjCMessageExpr *E)
-    : MsgOrPropE(E), OriginE(E) {
+  ObjCMessage(const ObjCMessageExpr *E, const ObjCPropertyRefExpr *pe =3D =
0,
+              bool isSetter =3D false)
+    : Msg(E), PE(pe), IsPropSetter(isSetter) {
     assert(E && "should not be initialized with null expression");
   }
=20
-  bool isValid() const { return MsgOrPropE !=3D 0; }
-  bool isInvalid() const { return !isValid(); }
+  bool isValid() const { return Msg; }
+ =20
+  bool isPureMessageExpr() const { return !PE; }
=20
-  bool isMessageExpr() const {
-    return isValid() && isa<ObjCMessageExpr>(MsgOrPropE);
+  bool isPropertyGetter() const { return PE && !IsPropSetter; }
+
+  bool isPropertySetter() const {
+    return IsPropSetter;
   }
=20
-  bool isPropertyGetter() const {
-    return isValid() &&
-           isa<ObjCPropertyRefExpr>(MsgOrPropE) && !IsPropSetter;
+  const Expr *getMessageExpr() const {=20
+    return Msg;
   }
=20
-  bool isPropertySetter() const {
-    return isValid() &&
-           isa<ObjCPropertyRefExpr>(MsgOrPropE) && IsPropSetter;
+  QualType getType(ASTContext &ctx) const {
+    return Msg->getType();
   }
- =20
-  const Expr *getOriginExpr() const { return OriginE; }
-
-  QualType getType(ASTContext &ctx) const;
=20
   QualType getResultType(ASTContext &ctx) const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      if (const ObjCMethodDecl *MD =3D msgE->getMethodDecl())
-        return MD->getResultType();
+    if (const ObjCMethodDecl *MD =3D Msg->getMethodDecl())
+      return MD->getResultType();
     return getType(ctx);
   }
=20
-  ObjCMethodFamily getMethodFamily() const;
+  ObjCMethodFamily getMethodFamily() const {
+    return Msg->getMethodFamily();
+  }
=20
-  Selector getSelector() const;
+  Selector getSelector() const {
+    return Msg->getSelector();
+  }
=20
   const Expr *getInstanceReceiver() const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      return msgE->getInstanceReceiver();
-    const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrPr=
opE);
-    if (propE->isObjectReceiver())
-      return propE->getBase();
-    return 0;
+    return Msg->getInstanceReceiver();
   }
=20
-  SVal getInstanceReceiverSVal(const ProgramState *State,
+  SVal getInstanceReceiverSVal(ProgramStateRef State,
                                const LocationContext *LC) const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
     if (!isInstanceMessage())
       return UndefinedVal();
     if (const Expr *Ex =3D getInstanceReceiver())
-      return State->getSValAsScalarOrLoc(Ex);
+      return State->getSValAsScalarOrLoc(Ex, LC);
=20
     // An instance message with no expression means we are sending to supe=
r.
     // In this case the object reference is the same as 'self'.
@@ -104,99 +94,66 @@
   }
=20
   bool isInstanceMessage() const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      return msgE->isInstanceMessage();
-    const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrPr=
opE);
-    // FIXME: 'super' may be super class.
-    return propE->isObjectReceiver() || propE->isSuperReceiver();
+    return Msg->isInstanceMessage();
   }
=20
-  const ObjCMethodDecl *getMethodDecl() const;
+  const ObjCMethodDecl *getMethodDecl() const {
+    return Msg->getMethodDecl();
+  }
=20
-  const ObjCInterfaceDecl *getReceiverInterface() const;
+  const ObjCInterfaceDecl *getReceiverInterface() const {
+    return Msg->getReceiverInterface();
+  }
=20
   SourceLocation getSuperLoc() const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      return msgE->getSuperLoc();
-    return cast<ObjCPropertyRefExpr>(MsgOrPropE)->getReceiverLocation();
-  }
+    if (PE)
+      return PE->getReceiverLocation();
+    return Msg->getSuperLoc();
+  } =20
=20
-  const Expr *getMsgOrPropExpr() const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    return MsgOrPropE;
-  }
-
-  SourceRange getSourceRange() const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    return MsgOrPropE->getSourceRange();
+  SourceRange getSourceRange() const LLVM_READONLY {
+    if (PE)
+      return PE->getSourceRange();
+    return Msg->getSourceRange();
   }
=20
   unsigned getNumArgs() const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      return msgE->getNumArgs();
-    return isPropertySetter() ? 1 : 0;
+    return Msg->getNumArgs();
   }
=20
-  SVal getArgSVal(unsigned i, const ProgramState *state) const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
+  SVal getArgSVal(unsigned i,
+                  const LocationContext *LCtx,
+                  ProgramStateRef state) const {
     assert(i < getNumArgs() && "Invalid index for argument");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      return state->getSVal(msgE->getArg(i));
-    assert(isPropertySetter());
-    return SetterArgV;
+    return state->getSVal(Msg->getArg(i), LCtx);
   }
=20
   QualType getArgType(unsigned i) const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
     assert(i < getNumArgs() && "Invalid index for argument");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      return msgE->getArg(i)->getType();
-    assert(isPropertySetter());
-    return cast<ObjCPropertyRefExpr>(MsgOrPropE)->getType();
+    return Msg->getArg(i)->getType();
   }
=20
-  const Expr *getArgExpr(unsigned i) const;
+  const Expr *getArgExpr(unsigned i) const {
+    assert(i < getNumArgs() && "Invalid index for argument");
+    return Msg->getArg(i);
+  }
=20
   SourceRange getArgSourceRange(unsigned i) const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    assert(i < getNumArgs() && "Invalid index for argument");
-    if (const Expr *argE =3D getArgExpr(i))
-      return argE->getSourceRange();
-    return OriginE->getSourceRange();
+    const Expr *argE =3D getArgExpr(i);
+    return argE->getSourceRange();
   }
=20
   SourceRange getReceiverSourceRange() const {
-    assert(isValid() && "This ObjCMessage is uninitialized!");
-    if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPro=
pE))
-      return msgE->getReceiverRange();
-
-    const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrPr=
opE);
-    if (propE->isObjectReceiver())
-      return propE->getBase()->getSourceRange();
+    if (PE) {
+      if (PE->isObjectReceiver())
+        return PE->getBase()->getSourceRange();
+    }
+    else {
+      return Msg->getReceiverRange();
+    }
=20
     // FIXME: This isn't a range.
-    return propE->getReceiverLocation();
-  }
-};
-
-class ObjCPropertyGetter : public ObjCMessage {
-public:
-  ObjCPropertyGetter(const ObjCPropertyRefExpr *propE, const Expr *originE)
-    : ObjCMessage(propE, originE, false, SVal()) {
-    assert(propE && originE &&
-           "should not be initialized with null expressions");
-  }
-};
-
-class ObjCPropertySetter : public ObjCMessage {
-public:
-  ObjCPropertySetter(const ObjCPropertyRefExpr *propE, const Expr *storeE,
-                     SVal argV)
-    : ObjCMessage(propE, storeE, true, argV) {
-    assert(propE && storeE &&"should not be initialized with null expressi=
ons");
+    return PE->getReceiverLocation();
   }
 };
=20
@@ -205,14 +162,18 @@
 class CallOrObjCMessage {
   llvm::PointerUnion<const CallExpr *, const CXXConstructExpr *> CallE;
   ObjCMessage Msg;
-  const ProgramState *State;
+  ProgramStateRef State;
+  const LocationContext *LCtx;
 public:
-  CallOrObjCMessage(const CallExpr *callE, const ProgramState *state)
-    : CallE(callE), State(state) {}
-  CallOrObjCMessage(const CXXConstructExpr *consE, const ProgramState *sta=
te)
-    : CallE(consE), State(state) {}
-  CallOrObjCMessage(const ObjCMessage &msg, const ProgramState *state)
-    : CallE((CallExpr *)0), Msg(msg), State(state) {}
+  CallOrObjCMessage(const CallExpr *callE, ProgramStateRef state,
+                    const LocationContext *lctx)
+    : CallE(callE), State(state), LCtx(lctx) {}
+  CallOrObjCMessage(const CXXConstructExpr *consE, ProgramStateRef state,
+                    const LocationContext *lctx)
+    : CallE(consE), State(state), LCtx(lctx) {}
+  CallOrObjCMessage(const ObjCMessage &msg, ProgramStateRef state,
+                    const LocationContext *lctx)
+    : CallE((CallExpr *)0), Msg(msg), State(state), LCtx(lctx) {}
=20
   QualType getResultType(ASTContext &ctx) const;
  =20
@@ -233,9 +194,19 @@
     return ActualCallE && isa<CXXMemberCallExpr>(ActualCallE);
   }
=20
+  /// Check if the callee is declared in the system header.
+  bool isInSystemHeader() const {
+    if (const Decl *FD =3D getDecl()) {
+      const SourceManager &SM =3D
+        State->getStateManager().getContext().getSourceManager();
+      return SM.isInSystemHeader(FD->getLocation());
+    }
+    return false;
+  }
+
   const Expr *getOriginExpr() const {
     if (!CallE)
-      return Msg.getOriginExpr();
+      return Msg.getMessageExpr();
     if (const CXXConstructExpr *Ctor =3D
           CallE.dyn_cast<const CXXConstructExpr *>())
       return Ctor;
@@ -246,6 +217,9 @@
   SVal getCXXCallee() const;
   SVal getInstanceMessageReceiver(const LocationContext *LC) const;
=20
+  /// Get the declaration of the function or method.
+  const Decl *getDecl() const;
+
   unsigned getNumArgs() const {
     if (!CallE)
       return Msg.getNumArgs();
@@ -258,8 +232,8 @@
   SVal getArgSVal(unsigned i) const {
     assert(i < getNumArgs());
     if (!CallE)
-      return Msg.getArgSVal(i, State);
-    return State->getSVal(getArg(i));
+      return Msg.getArgSVal(i, LCtx, State);
+    return State->getSVal(getArg(i), LCtx);
   }
=20
   const Expr *getArg(unsigned i) const {
@@ -283,6 +257,34 @@
     assert(isObjCMessage());
     return Msg.getReceiverSourceRange();
   }
+
+  /// \brief Check if the name corresponds to a CoreFoundation or CoreGrap=
hics=20
+  /// function that allows objects to escape.
+  ///
+  /// Many methods allow a tracked object to escape.  For example:
+  ///
+  ///   CFMutableDictionaryRef x =3D CFDictionaryCreateMutable(..., custom=
Deallocator);
+  ///   CFDictionaryAddValue(y, key, x);
+  ///
+  /// We handle this and similar cases with the following heuristic.  If t=
he
+  /// function name contains "InsertValue", "SetValue", "AddValue",
+  /// "AppendValue", or "SetAttribute", then we assume that arguments may
+  /// escape.
+  //
+  // TODO: To reduce false negatives here, we should track the container
+  // allocation site and check if a proper deallocator was set there.
+  static bool isCFCGAllowingEscape(StringRef FName) {
+    if (FName[0] =3D=3D 'C' && (FName[1] =3D=3D 'F' || FName[1] =3D=3D 'G'=
))
+           if (StrInStrNoCase(FName, "InsertValue") !=3D StringRef::npos||
+               StrInStrNoCase(FName, "AddValue") !=3D StringRef::npos ||
+               StrInStrNoCase(FName, "SetValue") !=3D StringRef::npos ||
+               StrInStrNoCase(FName, "WithData") !=3D StringRef::npos ||
+               StrInStrNoCase(FName, "AppendValue") !=3D StringRef::npos||
+               StrInStrNoCase(FName, "SetAttribute") !=3D StringRef::npos)=
 {
+         return true;
+       }
+    return false;
+  }
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ProgramState.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ProgramState.h	Tue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,8 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/TaintTag.h"
 #include "llvm/ADT/PointerIntPair.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableMap.h"
@@ -33,7 +35,7 @@
=20
 namespace ento {
=20
-class ProgramStateManager;
+class CallOrObjCMessage;
=20
 typedef ConstraintManager* (*ConstraintManagerCreator)(ProgramStateManager=
&,
                                                        SubEngine&);
@@ -54,8 +56,6 @@
   }
 };
=20
-class ProgramStateManager;
-
 /// \class ProgramState
 /// ProgramState - This class encapsulates:
 ///
@@ -88,12 +88,11 @@
=20
   /// makeWithStore - Return a ProgramState with the same values as the cu=
rrent
   ///  state with the exception of using the specified Store.
-  const ProgramState *makeWithStore(const StoreRef &store) const;
+  ProgramStateRef makeWithStore(const StoreRef &store) const;
=20
   void setStore(const StoreRef &storeRef);
=20
 public:
-
   /// This ctor is used when creating the first ProgramState object.
   ProgramState(ProgramStateManager *mgr, const Environment& env,
           StoreRef st, GenericDataMap gdm);
@@ -107,9 +106,6 @@
   /// Return the ProgramStateManager associated with this state.
   ProgramStateManager &getStateManager() const { return *stateMgr; }
=20
-  /// Return true if this state is referenced by a persistent ExplodedNode.
-  bool referencedByExplodedNode() const { return refCount > 0; }
-
   /// getEnvironment - Return the environment associated with this state.
   ///  The environment is the mapping from expressions to values.
   const Environment& getEnvironment() const { return Env; }
@@ -168,17 +164,18 @@
   // If no new state is feasible, NULL is returned.
   //
=20
-  const ProgramState *assume(DefinedOrUnknownSVal cond, bool assumption) c=
onst;
+  ProgramStateRef assume(DefinedOrUnknownSVal cond, bool assumption) const;
=20
   /// This method assumes both "true" and "false" for 'cond', and
   ///  returns both corresponding states.  It's shorthand for doing
   ///  'assume' twice.
-  std::pair<const ProgramState*, const ProgramState*>
+  std::pair<ProgramStateRef , ProgramStateRef >
   assume(DefinedOrUnknownSVal cond) const;
=20
-  const ProgramState *assumeInBound(DefinedOrUnknownSVal idx,
+  ProgramStateRef assumeInBound(DefinedOrUnknownSVal idx,
                                DefinedOrUnknownSVal upperBound,
-                               bool assumption) const;
+                               bool assumption,
+                               QualType IndexType =3D QualType()) const;
=20
   /// Utility method for getting regions.
   const VarRegion* getRegion(const VarDecl *D, const LocationContext *LC) =
const;
@@ -189,49 +186,50 @@
=20
   /// BindCompoundLiteral - Return the state that has the bindings current=
ly
   ///  in this state plus the bindings for the CompoundLiteral.
-  const ProgramState *bindCompoundLiteral(const CompoundLiteralExpr *CL,
+  ProgramStateRef bindCompoundLiteral(const CompoundLiteralExpr *CL,
                                      const LocationContext *LC,
                                      SVal V) const;
=20
   /// Create a new state by binding the value 'V' to the statement 'S' in =
the
   /// state's environment.
-  const ProgramState *BindExpr(const Stmt *S, SVal V, bool Invalidate =3D =
true) const;
+  ProgramStateRef BindExpr(const Stmt *S, const LocationContext *LCtx,
+                               SVal V, bool Invalidate =3D true) const;
=20
   /// Create a new state by binding the value 'V' and location 'locaton' t=
o the
   /// statement 'S' in the state's environment.
-  const ProgramState *bindExprAndLocation(const Stmt *S, SVal location, SV=
al V)
-    const;
+  ProgramStateRef bindExprAndLocation(const Stmt *S,
+                                          const LocationContext *LCtx,
+                                          SVal location, SVal V) const;
  =20
-  const ProgramState *bindDecl(const VarRegion *VR, SVal V) const;
+  ProgramStateRef bindDecl(const VarRegion *VR, SVal V) const;
=20
-  const ProgramState *bindDeclWithNoInit(const VarRegion *VR) const;
+  ProgramStateRef bindDeclWithNoInit(const VarRegion *VR) const;
=20
-  const ProgramState *bindLoc(Loc location, SVal V) const;
+  ProgramStateRef bindLoc(Loc location, SVal V) const;
=20
-  const ProgramState *bindLoc(SVal location, SVal V) const;
+  ProgramStateRef bindLoc(SVal location, SVal V) const;
=20
-  const ProgramState *bindDefault(SVal loc, SVal V) const;
+  ProgramStateRef bindDefault(SVal loc, SVal V) const;
=20
-  const ProgramState *unbindLoc(Loc LV) const;
+  ProgramStateRef unbindLoc(Loc LV) const;
=20
   /// invalidateRegions - Returns the state with bindings for the given re=
gions
   ///  cleared from the store. The regions are provided as a continuous ar=
ray
   ///  from Begin to End. Optionally invalidates global regions as well.
-  const ProgramState *invalidateRegions(ArrayRef<const MemRegion *> Region=
s,
-                                   const Expr *E, unsigned BlockCount,
-                                   StoreManager::InvalidatedSymbols *IS =
=3D 0,
-                                   bool invalidateGlobals =3D false) const;
+  ProgramStateRef invalidateRegions(ArrayRef<const MemRegion *> Regions,
+                               const Expr *E, unsigned BlockCount,
+                               const LocationContext *LCtx,
+                               StoreManager::InvalidatedSymbols *IS =3D 0,
+                               const CallOrObjCMessage *Call =3D 0) const;
=20
   /// enterStackFrame - Returns the state for entry to the given stack fra=
me,
   ///  preserving the current state.
-  const ProgramState *enterStackFrame(const StackFrameContext *frame) cons=
t;
+  ProgramStateRef enterStackFrame(const LocationContext *callerCtx,
+                                      const StackFrameContext *calleeCtx) =
const;
=20
   /// Get the lvalue for a variable reference.
   Loc getLValue(const VarDecl *D, const LocationContext *LC) const;
=20
-  /// Get the lvalue for a StringLiteral.
-  Loc getLValue(const StringLiteral *literal) const;
-
   Loc getLValue(const CompoundLiteralExpr *literal,=20
                 const LocationContext *LC) const;
=20
@@ -247,15 +245,20 @@
   const llvm::APSInt *getSymVal(SymbolRef sym) const;
=20
   /// Returns the SVal bound to the statement 'S' in the state's environme=
nt.
-  SVal getSVal(const Stmt *S, bool useOnlyDirectBindings =3D false) const;
+  SVal getSVal(const Stmt *S, const LocationContext *LCtx,
+               bool useOnlyDirectBindings =3D false) const;
  =20
-  SVal getSValAsScalarOrLoc(const Stmt *Ex) const;
+  SVal getSValAsScalarOrLoc(const Stmt *Ex, const LocationContext *LCtx) c=
onst;
=20
+  /// \brief Return the value bound to the specified location.
+  /// Returns UnknownVal() if none found.
   SVal getSVal(Loc LV, QualType T =3D QualType()) const;
=20
   /// Returns the "raw" SVal bound to LV before any value simplfication.
   SVal getRawSVal(Loc LV, QualType T=3D QualType()) const;
=20
+  /// \brief Return the value bound to the specified location.
+  /// Returns UnknownVal() if none found.
   SVal getSVal(const MemRegion* R) const;
=20
   SVal getSValAsScalarOrLoc(const MemRegion *R) const;
@@ -288,6 +291,25 @@
   scanReachableSymbols(const MemRegion * const *beg,
                        const MemRegion * const *end) const;
=20
+  /// Create a new state in which the statement is marked as tainted.
+  ProgramStateRef addTaint(const Stmt *S, const LocationContext *LCtx,
+                               TaintTagType Kind =3D TaintTagGeneric) cons=
t;
+
+  /// Create a new state in which the symbol is marked as tainted.
+  ProgramStateRef addTaint(SymbolRef S,
+                               TaintTagType Kind =3D TaintTagGeneric) cons=
t;
+
+  /// Create a new state in which the region symbol is marked as tainted.
+  ProgramStateRef addTaint(const MemRegion *R,
+                               TaintTagType Kind =3D TaintTagGeneric) cons=
t;
+
+  /// Check if the statement is tainted in the current state.
+  bool isTainted(const Stmt *S, const LocationContext *LCtx,
+                 TaintTagType Kind =3D TaintTagGeneric) const;
+  bool isTainted(SVal V, TaintTagType Kind =3D TaintTagGeneric) const;
+  bool isTainted(SymbolRef Sym, TaintTagType Kind =3D TaintTagGeneric) con=
st;
+  bool isTainted(const MemRegion *Reg, TaintTagType Kind=3DTaintTagGeneric=
) const;
+
   //=3D=3D----------------------------------------------------------------=
-----=3D=3D//
   // Accessing the Generic Data Map (GDM).
   //=3D=3D----------------------------------------------------------------=
-----=3D=3D//
@@ -295,7 +317,7 @@
   void *const* FindGDM(void *K) const;
=20
   template<typename T>
-  const ProgramState *add(typename ProgramStateTrait<T>::key_type K) const;
+  ProgramStateRef add(typename ProgramStateTrait<T>::key_type K) const;
=20
   template <typename T>
   typename ProgramStateTrait<T>::data_type
@@ -315,23 +337,23 @@
=20
=20
   template<typename T>
-  const ProgramState *remove(typename ProgramStateTrait<T>::key_type K) co=
nst;
+  ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K) const;
=20
   template<typename T>
-  const ProgramState *remove(typename ProgramStateTrait<T>::key_type K,
+  ProgramStateRef remove(typename ProgramStateTrait<T>::key_type K,
                         typename ProgramStateTrait<T>::context_type C) con=
st;
   template <typename T>
-  const ProgramState *remove() const;
+  ProgramStateRef remove() const;
=20
   template<typename T>
-  const ProgramState *set(typename ProgramStateTrait<T>::data_type D) cons=
t;
+  ProgramStateRef set(typename ProgramStateTrait<T>::data_type D) const;
=20
   template<typename T>
-  const ProgramState *set(typename ProgramStateTrait<T>::key_type K,
+  ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
                      typename ProgramStateTrait<T>::value_type E) const;
=20
   template<typename T>
-  const ProgramState *set(typename ProgramStateTrait<T>::key_type K,
+  ProgramStateRef set(typename ProgramStateTrait<T>::key_type K,
                      typename ProgramStateTrait<T>::value_type E,
                      typename ProgramStateTrait<T>::context_type C) const;
=20
@@ -342,61 +364,25 @@
   }
=20
   // Pretty-printing.
-  void print(raw_ostream &Out, CFG &C, const char *nl =3D "\n",
+  void print(raw_ostream &Out, const char *nl =3D "\n",
              const char *sep =3D "") const;
+  void printDOT(raw_ostream &Out) const;
+  void printTaint(raw_ostream &Out, const char *nl =3D "\n",
+                  const char *sep =3D "") const;
=20
-  void printStdErr(CFG &C) const;
-
-  void printDOT(raw_ostream &Out, CFG &C) const;
+  void dump() const;
+  void dumpTaint() const;
=20
 private:
-  /// Increments the number of times this state is referenced by ExplodeNo=
des.
-  void incrementReferenceCount() { ++refCount; }
-
-  /// Decrement the number of times this state is referenced by ExplodeNod=
es.
-  void decrementReferenceCount() {
-    assert(refCount > 0);
-    --refCount;
-  }
+  friend void ProgramStateRetain(const ProgramState *state);
+  friend void ProgramStateRelease(const ProgramState *state);
  =20
-  const ProgramState *
+  ProgramStateRef=20
   invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
                         const Expr *E, unsigned BlockCount,
+                        const LocationContext *LCtx,
                         StoreManager::InvalidatedSymbols &IS,
-                        bool invalidateGlobals) const;
-};
-
-class ProgramStateSet {
-  typedef llvm::SmallPtrSet<const ProgramState*,5> ImplTy;
-  ImplTy Impl;
-public:
-  ProgramStateSet() {}
-
-  inline void Add(const ProgramState *St) {
-    Impl.insert(St);
-  }
-
-  typedef ImplTy::const_iterator iterator;
-
-  inline unsigned size() const { return Impl.size();  }
-  inline bool empty()    const { return Impl.empty(); }
-
-  inline iterator begin() const { return Impl.begin(); }
-  inline iterator end() const { return Impl.end();   }
-
-  class AutoPopulate {
-    ProgramStateSet &S;
-    unsigned StartSize;
-    const ProgramState *St;
-  public:
-    AutoPopulate(ProgramStateSet &s, const ProgramState *st)
-      : S(s), StartSize(S.size()), St(st) {}
-
-    ~AutoPopulate() {
-      if (StartSize =3D=3D S.size())
-        S.Add(St);
-    }
-  };
+                        const CallOrObjCMessage *Call) const;
 };
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -405,13 +391,14 @@
=20
 class ProgramStateManager {
   friend class ProgramState;
+  friend void ProgramStateRelease(const ProgramState *state);
 private:
   /// Eng - The SubEngine that owns this state manager.
   SubEngine *Eng; /* Can be null. */
=20
   EnvironmentManager                   EnvMgr;
-  llvm::OwningPtr<StoreManager>        StoreMgr;
-  llvm::OwningPtr<ConstraintManager>   ConstraintMgr;
+  OwningPtr<StoreManager>              StoreMgr;
+  OwningPtr<ConstraintManager>         ConstraintMgr;
=20
   ProgramState::GenericDataMap::Factory     GDMFactory;
=20
@@ -423,14 +410,10 @@
   llvm::FoldingSet<ProgramState> StateSet;
=20
   /// Object that manages the data for all created SVals.
-  llvm::OwningPtr<SValBuilder> svalBuilder;
+  OwningPtr<SValBuilder> svalBuilder;
=20
   /// A BumpPtrAllocator to allocate states.
   llvm::BumpPtrAllocator &Alloc;
-
-  /// A vector of recently allocated ProgramStates that can potentially be
-  /// reused.
-  std::vector<ProgramState *> recentlyAllocatedStates;
  =20
   /// A vector of ProgramStates that we can reuse.
   std::vector<ProgramState *> freeStates;
@@ -465,7 +448,7 @@
=20
   ~ProgramStateManager();
=20
-  const ProgramState *getInitialState(const LocationContext *InitLoc);
+  ProgramStateRef getInitialState(const LocationContext *InitLoc);
=20
   ASTContext &getContext() { return svalBuilder->getContext(); }
   const ASTContext &getContext() const { return svalBuilder->getContext();=
 }
@@ -501,13 +484,13 @@
   ConstraintManager& getConstraintManager() { return *ConstraintMgr; }
   SubEngine* getOwningEngine() { return Eng; }
=20
-  const ProgramState *removeDeadBindings(const ProgramState *St,
+  ProgramStateRef removeDeadBindings(ProgramStateRef St,
                                     const StackFrameContext *LCtx,
                                     SymbolReaper& SymReaper);
=20
   /// Marshal a new state for the callee in another translation unit.
   /// 'state' is owned by the caller's engine.
-  const ProgramState *MarshalState(const ProgramState *state, const StackF=
rameContext *L);
+  ProgramStateRef MarshalState(ProgramStateRef state, const StackFrameCont=
ext *L);
=20
 public:
=20
@@ -516,31 +499,27 @@
   }
=20
   // Methods that manipulate the GDM.
-  const ProgramState *addGDM(const ProgramState *St, void *Key, void *Data=
);
-  const ProgramState *removeGDM(const ProgramState *state, void *Key);
+  ProgramStateRef addGDM(ProgramStateRef St, void *Key, void *Data);
+  ProgramStateRef removeGDM(ProgramStateRef state, void *Key);
=20
   // Methods that query & manipulate the Store.
=20
-  void iterBindings(const ProgramState *state, StoreManager::BindingsHandl=
er& F) {
+  void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler& =
F) {
     StoreMgr->iterBindings(state->getStore(), F);
   }
=20
-  const ProgramState *getPersistentState(ProgramState &Impl);
-  const ProgramState *getPersistentStateWithGDM(const ProgramState *FromSt=
ate,
-                                           const ProgramState *GDMState);
+  ProgramStateRef getPersistentState(ProgramState &Impl);
+  ProgramStateRef getPersistentStateWithGDM(ProgramStateRef FromState,
+                                           ProgramStateRef GDMState);
=20
-  bool haveEqualEnvironments(const ProgramState * S1, const ProgramState *=
 S2) {
+  bool haveEqualEnvironments(ProgramStateRef S1, ProgramStateRef S2) {
     return S1->Env =3D=3D S2->Env;
   }
=20
-  bool haveEqualStores(const ProgramState * S1, const ProgramState * S2) {
+  bool haveEqualStores(ProgramStateRef S1, ProgramStateRef S2) {
     return S1->store =3D=3D S2->store;
   }
=20
-  /// Periodically called by ExprEngine to recycle ProgramStates that were
-  /// created but never used for creating an ExplodedNode.
-  void recycleUnusedStates();
-
   //=3D=3D----------------------------------------------------------------=
-----=3D=3D//
   // Generic Data Map methods.
   //=3D=3D----------------------------------------------------------------=
-----=3D=3D//
@@ -561,13 +540,13 @@
=20
   // Trait based GDM dispatch.
   template <typename T>
-  const ProgramState *set(const ProgramState *st, typename ProgramStateTra=
it<T>::data_type D) {
+  ProgramStateRef set(ProgramStateRef st, typename ProgramStateTrait<T>::d=
ata_type D) {
     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
                   ProgramStateTrait<T>::MakeVoidPtr(D));
   }
=20
   template<typename T>
-  const ProgramState *set(const ProgramState *st,
+  ProgramStateRef set(ProgramStateRef st,
                      typename ProgramStateTrait<T>::key_type K,
                      typename ProgramStateTrait<T>::value_type V,
                      typename ProgramStateTrait<T>::context_type C) {
@@ -577,7 +556,7 @@
   }
=20
   template <typename T>
-  const ProgramState *add(const ProgramState *st,
+  ProgramStateRef add(ProgramStateRef st,
                      typename ProgramStateTrait<T>::key_type K,
                      typename ProgramStateTrait<T>::context_type C) {
     return addGDM(st, ProgramStateTrait<T>::GDMIndex(),
@@ -585,7 +564,7 @@
   }
=20
   template <typename T>
-  const ProgramState *remove(const ProgramState *st,
+  ProgramStateRef remove(ProgramStateRef st,
                         typename ProgramStateTrait<T>::key_type K,
                         typename ProgramStateTrait<T>::context_type C) {
=20
@@ -594,7 +573,7 @@
   }
=20
   template <typename T>
-  const ProgramState *remove(const ProgramState *st) {
+  ProgramStateRef remove(ProgramStateRef st) {
     return removeGDM(st, ProgramStateTrait<T>::GDMIndex());
   }
=20
@@ -611,11 +590,11 @@
     return ProgramStateTrait<T>::MakeContext(p);
   }
=20
-  const llvm::APSInt* getSymVal(const ProgramState *St, SymbolRef sym) {
+  const llvm::APSInt* getSymVal(ProgramStateRef St, SymbolRef sym) {
     return ConstraintMgr->getSymVal(St, sym);
   }
=20
-  void EndPath(const ProgramState *St) {
+  void EndPath(ProgramStateRef St) {
     ConstraintMgr->EndPath(St);
   }
 };
@@ -626,11 +605,12 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 inline const VarRegion* ProgramState::getRegion(const VarDecl *D,
-                                           const LocationContext *LC) cons=
t {
+                                                const LocationContext *LC)=
 const=20
+{
   return getStateManager().getRegionManager().getVarRegion(D, LC);
 }
=20
-inline const ProgramState *ProgramState::assume(DefinedOrUnknownSVal Cond,
+inline ProgramStateRef ProgramState::assume(DefinedOrUnknownSVal Cond,
                                       bool Assumption) const {
   if (Cond.isUnknown())
     return this;
@@ -639,7 +619,7 @@
                                                  Assumption);
 }
  =20
-inline std::pair<const ProgramState*, const ProgramState*>
+inline std::pair<ProgramStateRef , ProgramStateRef >
 ProgramState::assume(DefinedOrUnknownSVal Cond) const {
   if (Cond.isUnknown())
     return std::make_pair(this, this);
@@ -648,7 +628,7 @@
                                                      cast<DefinedSVal>(Con=
d));
 }
=20
-inline const ProgramState *ProgramState::bindLoc(SVal LV, SVal V) const {
+inline ProgramStateRef ProgramState::bindLoc(SVal LV, SVal V) const {
   return !isa<Loc>(LV) ? this : bindLoc(cast<Loc>(LV), V);
 }
=20
@@ -657,10 +637,6 @@
   return getStateManager().StoreMgr->getLValueVar(VD, LC);
 }
=20
-inline Loc ProgramState::getLValue(const StringLiteral *literal) const {
-  return getStateManager().StoreMgr->getLValueString(literal);
-}
-
 inline Loc ProgramState::getLValue(const CompoundLiteralExpr *literal,
                                const LocationContext *LC) const {
   return getStateManager().StoreMgr->getLValueCompoundLiteral(literal, LC);
@@ -684,27 +660,32 @@
   return getStateManager().getSymVal(this, sym);
 }
=20
-inline SVal ProgramState::getSVal(const Stmt *Ex, bool useOnlyDirectBindin=
gs) const{
-  return Env.getSVal(Ex, *getStateManager().svalBuilder,
+inline SVal ProgramState::getSVal(const Stmt *Ex, const LocationContext *L=
Ctx,
+                                  bool useOnlyDirectBindings) const{
+  return Env.getSVal(EnvironmentEntry(Ex, LCtx),
+                     *getStateManager().svalBuilder,
                      useOnlyDirectBindings);
 }
=20
-inline SVal ProgramState::getSValAsScalarOrLoc(const Stmt *S) const {
+inline SVal
+ProgramState::getSValAsScalarOrLoc(const Stmt *S,
+                                   const LocationContext *LCtx) const {
   if (const Expr *Ex =3D dyn_cast<Expr>(S)) {
     QualType T =3D Ex->getType();
     if (Ex->isLValue() || Loc::isLocType(T) || T->isIntegerType())
-      return getSVal(S);
+      return getSVal(S, LCtx);
   }
=20
   return UnknownVal();
 }
=20
 inline SVal ProgramState::getRawSVal(Loc LV, QualType T) const {
-  return getStateManager().StoreMgr->Retrieve(getStore(), LV, T);
+  return getStateManager().StoreMgr->getBinding(getStore(), LV, T);
 }
=20
 inline SVal ProgramState::getSVal(const MemRegion* R) const {
-  return getStateManager().StoreMgr->Retrieve(getStore(), loc::MemRegionVa=
l(R));
+  return getStateManager().StoreMgr->getBinding(getStore(),
+                                                loc::MemRegionVal(R));
 }
=20
 inline BasicValueFactory &ProgramState::getBasicVals() const {
@@ -716,7 +697,7 @@
 }
=20
 template<typename T>
-const ProgramState *ProgramState::add(typename ProgramStateTrait<T>::key_t=
ype K) const {
+ProgramStateRef ProgramState::add(typename ProgramStateTrait<T>::key_type =
K) const {
   return getStateManager().add<T>(this, K, get_context<T>());
 }
=20
@@ -726,34 +707,34 @@
 }
=20
 template<typename T>
-const ProgramState *ProgramState::remove(typename ProgramStateTrait<T>::ke=
y_type K) const {
+ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_ty=
pe K) const {
   return getStateManager().remove<T>(this, K, get_context<T>());
 }
=20
 template<typename T>
-const ProgramState *ProgramState::remove(typename ProgramStateTrait<T>::ke=
y_type K,
+ProgramStateRef ProgramState::remove(typename ProgramStateTrait<T>::key_ty=
pe K,
                                typename ProgramStateTrait<T>::context_type=
 C) const {
   return getStateManager().remove<T>(this, K, C);
 }
=20
 template <typename T>
-const ProgramState *ProgramState::remove() const {
+ProgramStateRef ProgramState::remove() const {
   return getStateManager().remove<T>(this);
 }
=20
 template<typename T>
-const ProgramState *ProgramState::set(typename ProgramStateTrait<T>::data_=
type D) const {
+ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::data_type=
 D) const {
   return getStateManager().set<T>(this, D);
 }
=20
 template<typename T>
-const ProgramState *ProgramState::set(typename ProgramStateTrait<T>::key_t=
ype K,
+ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type =
K,
                             typename ProgramStateTrait<T>::value_type E) c=
onst {
   return getStateManager().set<T>(this, K, E, get_context<T>());
 }
=20
 template<typename T>
-const ProgramState *ProgramState::set(typename ProgramStateTrait<T>::key_t=
ype K,
+ProgramStateRef ProgramState::set(typename ProgramStateTrait<T>::key_type =
K,
                             typename ProgramStateTrait<T>::value_type E,
                             typename ProgramStateTrait<T>::context_type C)=
 const {
   return getStateManager().set<T>(this, K, E, C);
@@ -785,15 +766,16 @@
 /// A Utility class that allows to visit the reachable symbols using a cus=
tom
 /// SymbolVisitor.
 class ScanReachableSymbols : public SubRegionMap::Visitor  {
+  virtual void anchor();
   typedef llvm::DenseMap<const void*, unsigned> VisitedItems;
=20
   VisitedItems visited;
-  const ProgramState *state;
+  ProgramStateRef state;
   SymbolVisitor &visitor;
-  llvm::OwningPtr<SubRegionMap> SRM;
+  OwningPtr<SubRegionMap> SRM;
 public:
=20
-  ScanReachableSymbols(const ProgramState *st, SymbolVisitor& v)
+  ScanReachableSymbols(ProgramStateRef st, SymbolVisitor& v)
     : state(st), visitor(v) {}
=20
   bool scan(nonloc::CompoundVal val);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ProgramStateTrait.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/ProgramStateTrait.h	Tue Apr 17 11:51:51 2012 +0300
@@ -9,8 +9,8 @@
 //
 //  This file defines partial implementations of template specializations =
of
 //  the class ProgramStateTrait<>.  ProgramStateTrait<> is used by Program=
State=20
-//  to implement set/get methods for mapulating a ProgramState's
-// generic data map.
+//  to implement set/get methods for manipulating a ProgramState's
+//  generic data map.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -176,7 +176,20 @@
       return (void*) (uintptr_t) d;
     }
   };
- =20
+
+  // Partial specialization for void*.
+  template <> struct ProgramStatePartialTrait<void*> {
+    typedef void *data_type;
+
+    static inline data_type MakeData(void *const* p) {
+      return p ? *p
+               : data_type();
+    }
+    static inline void *MakeVoidPtr(data_type d) {
+      return d;
+    }
+  };
+
 } // end GR namespace
=20
 } // end clang namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SValBuilder.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SValBuilder.h	Tue Apr 17 11:51:51 2012 +0300
@@ -17,17 +17,19 @@
=20
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
=20
 namespace clang {
=20
+class CXXBoolLiteralExpr;
+
 namespace ento {
=20
-class ProgramState;
-
 class SValBuilder {
+  virtual void anchor();
 protected:
   ASTContext &Context;
  =20
@@ -48,11 +50,13 @@
   /// The width of the scalar type used for array indices.
   const unsigned ArrayIndexWidth;
=20
+  virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy) =3D 0;
+  virtual SVal evalCastFromLoc(Loc val, QualType castTy) =3D 0;
+
 public:
   // FIXME: Make these protected again once RegionStoreManager correctly
   // handles loads from different bound value types.
-  virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy) =3D 0;
-  virtual SVal evalCastFromLoc(Loc val, QualType castTy) =3D 0;
+  virtual SVal dispatchCast(SVal val, QualType castTy) =3D 0;
=20
 public:
   SValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
@@ -66,29 +70,54 @@
=20
   virtual ~SValBuilder() {}
=20
+  bool haveSameType(const SymExpr *Sym1, const SymExpr *Sym2) {
+    return haveSameType(Sym1->getType(Context), Sym2->getType(Context));
+  }
+
+  bool haveSameType(QualType Ty1, QualType Ty2) {
+    // FIXME: Remove the second disjunct when we support symbolic
+    // truncation/extension.
+    return (Context.getCanonicalType(Ty1) =3D=3D Context.getCanonicalType(=
Ty2) ||
+            (Ty2->isIntegerType() && Ty2->isIntegerType()));
+  }
+
   SVal evalCast(SVal val, QualType castTy, QualType originalType);
  =20
   virtual SVal evalMinus(NonLoc val) =3D 0;
=20
   virtual SVal evalComplement(NonLoc val) =3D 0;
=20
-  virtual SVal evalBinOpNN(const ProgramState *state, BinaryOperator::Opco=
de op,
+  /// Create a new value which represents a binary expression with two non
+  /// location operands.
+  virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode o=
p,
                            NonLoc lhs, NonLoc rhs, QualType resultTy) =3D =
0;
=20
-  virtual SVal evalBinOpLL(const ProgramState *state, BinaryOperator::Opco=
de op,
+  /// Create a new value which represents a binary expression with two mem=
ory
+  /// location operands.
+  virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode o=
p,
                            Loc lhs, Loc rhs, QualType resultTy) =3D 0;
=20
-  virtual SVal evalBinOpLN(const ProgramState *state, BinaryOperator::Opco=
de op,
+  /// Create a new value which represents a binary expression with a memory
+  /// location and non location operands. For example, this would be used =
to
+  /// evaluate a pointer arithmetic operation.
+  virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode o=
p,
                            Loc lhs, NonLoc rhs, QualType resultTy) =3D 0;
=20
-  /// getKnownValue - evaluates a given SVal. If the SVal has only one pos=
sible
-  ///  (integer) value, that value is returned. Otherwise, returns NULL.
-  virtual const llvm::APSInt *getKnownValue(const ProgramState *state, SVa=
l val) =3D 0;
+  /// Evaluates a given SVal. If the SVal has only one possible (integer) =
value,
+  /// that value is returned. Otherwise, returns NULL.
+  virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal va=
l) =3D 0;
  =20
-  SVal evalBinOp(const ProgramState *state, BinaryOperator::Opcode op,
+  /// Handles generation of the value in case the builder is not smart eno=
ugh to
+  /// handle the given binary expression. Depending on the state, decides =
to
+  /// either keep the expression or forget the history and generate an
+  /// UnknownVal.
+  SVal makeGenericVal(ProgramStateRef state, BinaryOperator::Opcode op,
+                          NonLoc lhs, NonLoc rhs, QualType resultTy);
+
+  SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
                  SVal lhs, SVal rhs, QualType type);
  =20
-  DefinedOrUnknownSVal evalEQ(const ProgramState *state, DefinedOrUnknownS=
Val lhs,
+  DefinedOrUnknownSVal evalEQ(ProgramStateRef state, DefinedOrUnknownSVal =
lhs,
                               DefinedOrUnknownSVal rhs);
=20
   ASTContext &getContext() { return Context; }
@@ -115,28 +144,47 @@
=20
   // Forwarding methods to SymbolManager.
=20
-  const SymbolConjured* getConjuredSymbol(const Stmt *stmt, QualType type,
+  const SymbolConjured* getConjuredSymbol(const Stmt *stmt,
+                                          const LocationContext *LCtx,
+                                          QualType type,
                                           unsigned visitCount,
                                           const void *symbolTag =3D 0) {
-    return SymMgr.getConjuredSymbol(stmt, type, visitCount, symbolTag);
+    return SymMgr.getConjuredSymbol(stmt, LCtx, type, visitCount, symbolTa=
g);
   }
=20
-  const SymbolConjured* getConjuredSymbol(const Expr *expr, unsigned visit=
Count,
+  const SymbolConjured* getConjuredSymbol(const Expr *expr,
+                                          const LocationContext *LCtx,
+                                          unsigned visitCount,
                                           const void *symbolTag =3D 0) {
-    return SymMgr.getConjuredSymbol(expr, visitCount, symbolTag);
+    return SymMgr.getConjuredSymbol(expr, LCtx, visitCount, symbolTag);
   }
=20
-  /// makeZeroVal - Construct an SVal representing '0' for the specified t=
ype.
+  /// Construct an SVal representing '0' for the specified type.
   DefinedOrUnknownSVal makeZeroVal(QualType type);
=20
-  /// getRegionValueSymbolVal - make a unique symbol for value of region.
+  /// Make a unique symbol for value of region.
   DefinedOrUnknownSVal getRegionValueSymbolVal(const TypedValueRegion *reg=
ion);
=20
+  /// \brief Create a new symbol with a unique 'name'.
+  ///
+  /// We resort to conjured symbols when we cannot construct a derived sym=
bol.
+  /// The advantage of symbols derived/built from other symbols is that we
+  /// preserve the relation between related(or even equivalent) expression=
s, so
+  /// conjured symbols should be used sparingly.
   DefinedOrUnknownSVal getConjuredSymbolVal(const void *symbolTag,
-                                            const Expr *expr, unsigned cou=
nt);
+                                            const Expr *expr,
+                                            const LocationContext *LCtx,
+                                            unsigned count);
   DefinedOrUnknownSVal getConjuredSymbolVal(const void *symbolTag,
-                                            const Expr *expr, QualType typ=
e,
+                                            const Expr *expr,
+                                            const LocationContext *LCtx,
+                                            QualType type,
                                             unsigned count);
+ =20
+  DefinedOrUnknownSVal getConjuredSymbolVal(const Stmt *stmt,
+                                            const LocationContext *LCtx,
+                                            QualType type,
+                                            unsigned visitCount);
=20
   DefinedOrUnknownSVal getDerivedRegionValueSymbolVal(
       SymbolRef parentSymbol, const TypedValueRegion *region);
@@ -175,10 +223,12 @@
         BasicVals.getValue(integer->getValue(),
                      integer->getType()->isUnsignedIntegerOrEnumerationTyp=
e()));
   }
+ =20
+  nonloc::ConcreteInt makeBoolVal(const ObjCBoolLiteralExpr *boolean) {
+    return makeTruthVal(boolean->getValue(), boolean->getType());
+  }
=20
-  nonloc::ConcreteInt makeBoolVal(const CXXBoolLiteralExpr *boolean) {
-    return makeTruthVal(boolean->getValue());
-  }
+  nonloc::ConcreteInt makeBoolVal(const CXXBoolLiteralExpr *boolean);
=20
   nonloc::ConcreteInt makeIntVal(const llvm::APSInt& integer) {
     return nonloc::ConcreteInt(BasicVals.getValue(integer));
@@ -220,9 +270,15 @@
   NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
                     const llvm::APSInt& rhs, QualType type);
=20
+  NonLoc makeNonLoc(const llvm::APSInt& rhs, BinaryOperator::Opcode op,
+                    const SymExpr *lhs, QualType type);
+
   NonLoc makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
                     const SymExpr *rhs, QualType type);
=20
+  /// \brief Create a NonLoc value for cast.
+  NonLoc makeNonLoc(const SymExpr *operand, QualType fromTy, QualType toTy=
);
+
   nonloc::ConcreteInt makeTruthVal(bool b, QualType type) {
     return nonloc::ConcreteInt(BasicVals.getTruthValue(b, type));
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/SVals.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SVals.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SVals.h	Tue Apr 17 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
=20
 #include "clang/Basic/LLVM.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
 #include "llvm/ADT/ImmutableList.h"
=20
 //=3D=3D------------------------------------------------------------------=
------=3D=3D//
@@ -121,50 +122,39 @@
   /// Otherwise return 0.
   const FunctionDecl *getAsFunctionDecl() const;
=20
-  /// getAsLocSymbol - If this SVal is a location (subclasses Loc) and
-  ///  wraps a symbol, return that SymbolRef.  Otherwise return NULL.
+  /// If this SVal is a location (subclasses Loc) and
+  /// wraps a symbol, return that SymbolRef.  Otherwise return 0.
   SymbolRef getAsLocSymbol() const;
=20
   /// Get the symbol in the SVal or its base region.
   SymbolRef getLocSymbolInBase() const;
=20
-  /// getAsSymbol - If this Sval wraps a symbol return that SymbolRef.
-  ///  Otherwise return a SymbolRef where 'isValid()' returns false.
+  /// If this SVal wraps a symbol return that SymbolRef.
+  /// Otherwise, return 0.
   SymbolRef getAsSymbol() const;
=20
   /// getAsSymbolicExpression - If this Sval wraps a symbolic expression t=
hen
   ///  return that expression.  Otherwise return NULL.
   const SymExpr *getAsSymbolicExpression() const;
=20
+  const SymExpr* getAsSymExpr() const;
+
   const MemRegion *getAsRegion() const;
=20
   void dumpToStream(raw_ostream &OS) const;
   void dump() const;
=20
-  // Iterators.
-  class symbol_iterator {
-    SmallVector<const SymExpr*, 5> itr;
-    void expand();
-  public:
-    symbol_iterator() {}
-    symbol_iterator(const SymExpr *SE);
-
-    symbol_iterator &operator++();
-    SymbolRef operator*();
-
-    bool operator=3D=3D(const symbol_iterator &X) const;
-    bool operator!=3D(const symbol_iterator &X) const;
-  };
-
-  symbol_iterator symbol_begin() const {
+  SymExpr::symbol_iterator symbol_begin() const {
     const SymExpr *SE =3D getAsSymbolicExpression();
     if (SE)
-      return symbol_iterator(SE);
+      return SE->symbol_begin();
     else
-      return symbol_iterator();
+      return SymExpr::symbol_iterator();
   }
=20
-  symbol_iterator symbol_end() const { return symbol_iterator(); }
+  SymExpr::symbol_iterator symbol_end() const {=20
+    return SymExpr::symbol_end();
+  }
=20
   // Implement isa<T> support.
   static inline bool classof(const SVal*) { return true; }
@@ -274,12 +264,17 @@
 enum Kind { ConcreteIntKind, SymbolValKind, SymExprValKind,
             LocAsIntegerKind, CompoundValKind, LazyCompoundValKind };
=20
+/// \brief Represents symbolic expression.
 class SymbolVal : public NonLoc {
 public:
   SymbolVal(SymbolRef sym) : NonLoc(SymbolValKind, sym) {}
=20
   SymbolRef getSymbol() const {
-    return (const SymbolData*) Data;
+    return (const SymExpr*) Data;
+  }
+
+  bool isExpression() {
+    return !isa<SymbolData>(getSymbol());
   }
=20
   static inline bool classof(const SVal* V) {
@@ -292,25 +287,7 @@
   }
 };
=20
-class SymExprVal : public NonLoc {
-public:
-  explicit SymExprVal(const SymExpr *SE)
-    : NonLoc(SymExprValKind, reinterpret_cast<const void*>(SE)) {}
-
-  const SymExpr *getSymbolicExpression() const {
-    return reinterpret_cast<const SymExpr*>(Data);
-  }
-
-  static inline bool classof(const SVal* V) {
-    return V->getBaseKind() =3D=3D NonLocKind &&
-           V->getSubKind() =3D=3D SymExprValKind;
-  }
-
-  static inline bool classof(const NonLoc* V) {
-    return V->getSubKind() =3D=3D SymExprValKind;
-  }
-};
-
+/// \brief Value representing integer constant.
 class ConcreteInt : public NonLoc {
 public:
   explicit ConcreteInt(const llvm::APSInt& V) : NonLoc(ConcreteIntKind, &V=
) {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/Store.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/Store.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/Store.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,6 +29,7 @@
=20
 namespace ento {
=20
+class CallOrObjCMessage;
 class ProgramState;
 class ProgramStateManager;
 class SubRegionMap;
@@ -54,7 +55,7 @@
   ///   expected type of the returned value.  This is used if the value is
   ///   lazily computed.
   /// \return The value bound to the location \c loc.
-  virtual SVal Retrieve(Store store, Loc loc, QualType T =3D QualType()) =
=3D 0;
+  virtual SVal getBinding(Store store, Loc loc, QualType T =3D QualType())=
 =3D 0;
=20
   /// Return a state with the specified value bound to the given location.
   /// \param[in] state The analysis state.
@@ -93,18 +94,12 @@
     return svalBuilder.makeLoc(MRMgr.getVarRegion(VD, LC));
   }
=20
-  virtual Loc getLValueString(const StringLiteral* S) {
-    return svalBuilder.makeLoc(MRMgr.getStringRegion(S));
-  }
-
   Loc getLValueCompoundLiteral(const CompoundLiteralExpr *CL,
                                const LocationContext *LC) {
     return loc::MemRegionVal(MRMgr.getCompoundLiteralRegion(CL, LC));
   }
=20
-  virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
-    return getLValueFieldOrIvar(decl, base);
-  }
+  virtual SVal getLValueIvar(const ObjCIvarDecl *decl, SVal base);
=20
   virtual SVal getLValueField(const FieldDecl *D, SVal Base) {
     return getLValueFieldOrIvar(D, Base);
@@ -114,7 +109,7 @@
=20
   // FIXME: This should soon be eliminated altogether; clients should deal=
 with
   // region extents directly.
-  virtual DefinedOrUnknownSVal getSizeInElements(const ProgramState *state=
,=20
+  virtual DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,=20
                                                  const MemRegion *region,
                                                  QualType EleTy) {
     return UnknownVal();
@@ -125,17 +120,26 @@
   virtual SVal ArrayToPointer(Loc Array) =3D 0;
=20
   /// Evaluates DerivedToBase casts.
-  virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType) {
-    return UnknownVal();
-  }
+  virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType) =3D 0;
+
+  /// \brief Evaluates C++ dynamic_cast cast.
+  /// The callback may result in the following 3 scenarios:
+  ///  - Successful cast (ex: derived is subclass of base).
+  ///  - Failed cast (ex: derived is definitely not a subclass of base).
+  ///  - We don't know (base is a symbolic region and we don't have=20
+  ///    enough info to determine if the cast will succeed at run time).
+  /// The function returns an SVal representing the derived class; it's
+  /// valid only if Failed flag is set to false.
+  virtual SVal evalDynamicCast(SVal base, QualType derivedPtrType,
+                                 bool &Failed) =3D 0;
=20
   class CastResult {
-    const ProgramState *state;
+    ProgramStateRef state;
     const MemRegion *region;
   public:
-    const ProgramState *getState() const { return state; }
+    ProgramStateRef getState() const { return state; }
     const MemRegion* getRegion() const { return region; }
-    CastResult(const ProgramState *s, const MemRegion* r =3D 0) : state(s)=
, region(r){}
+    CastResult(ProgramStateRef s, const MemRegion* r =3D 0) : state(s), re=
gion(r){}
   };
=20
   const ElementRegion *GetElementZeroRegion(const MemRegion *R, QualType T=
);
@@ -180,8 +184,8 @@
   ///   symbols to mark the values of invalidated regions.
   /// \param[in,out] IS A set to fill with any symbols that are no longer
   ///   accessible. Pass \c NULL if this information will not be used.
-  /// \param[in] invalidateGlobals If \c true, any non-static global regio=
ns
-  ///   are invalidated as well.
+  /// \param[in] Call The call expression which will be used to determine =
which
+  ///   globals should get invalidated.
   /// \param[in,out] Regions A vector to fill with any regions being
   ///   invalidated. This should include any regions explicitly invalidated
   ///   even if they do not currently have bindings. Pass \c NULL if this
@@ -189,14 +193,16 @@
   virtual StoreRef invalidateRegions(Store store,
                                      ArrayRef<const MemRegion *> Regions,
                                      const Expr *E, unsigned Count,
+                                     const LocationContext *LCtx,
                                      InvalidatedSymbols &IS,
-                                     bool invalidateGlobals,
+                                     const CallOrObjCMessage *Call,
                                      InvalidatedRegions *Invalidated) =3D =
0;
=20
   /// enterStackFrame - Let the StoreManager to do something when execution
   /// engine is about to execute into a callee.
-  virtual StoreRef enterStackFrame(const ProgramState *state,
-                                   const StackFrameContext *frame);
+  virtual StoreRef enterStackFrame(ProgramStateRef state,
+                                   const LocationContext *callerCtx,
+                                   const StackFrameContext *calleeCtx);
=20
   virtual void print(Store store, raw_ostream &Out,
                      const char* nl, const char *sep) =3D 0;
@@ -208,6 +214,21 @@
                                const MemRegion *region, SVal val) =3D 0;
   };
=20
+  class FindUniqueBinding :
+  public BindingsHandler {
+    SymbolRef Sym;
+    const MemRegion* Binding;
+    bool First;
+
+  public:
+    FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
+
+    bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
+                       SVal val);
+    operator bool() { return First && Binding; }
+    const MemRegion *getRegion() { return Binding; }
+  };
+
   /// iterBindings - Iterate over the bindings in the Store.
   virtual void iterBindings(Store store, BindingsHandler& f) =3D 0;
=20
@@ -258,10 +279,12 @@
 /// SubRegionMap - An abstract interface that represents a queryable map
 ///  between MemRegion objects and their subregions.
 class SubRegionMap {
+  virtual void anchor();
 public:
   virtual ~SubRegionMap() {}
=20
   class Visitor {
+    virtual void anchor();
   public:
     virtual ~Visitor() {}
     virtual bool Visit(const MemRegion* Parent, const MemRegion* SubRegion=
) =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SubEngine.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SubEngine.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,27 +26,26 @@
=20
 namespace ento {
  =20
-template <typename PP> class GenericNodeBuilder;
+struct NodeBuilderContext;
 class AnalysisManager;
 class ExplodedNodeSet;
 class ExplodedNode;
 class ProgramState;
 class ProgramStateManager;
 class BlockCounter;
-class StmtNodeBuilder;
 class BranchNodeBuilder;
 class IndirectGotoNodeBuilder;
 class SwitchNodeBuilder;
 class EndOfFunctionNodeBuilder;
-class CallEnterNodeBuilder;
-class CallExitNodeBuilder;
+class NodeBuilderWithSinks;
 class MemRegion;
=20
 class SubEngine {
+  virtual void anchor();
 public:
   virtual ~SubEngine() {}
=20
-  virtual const ProgramState *getInitialState(const LocationContext *InitL=
oc) =3D 0;
+  virtual ProgramStateRef getInitialState(const LocationContext *InitLoc) =
=3D 0;
=20
   virtual AnalysisManager &getAnalysisManager() =3D 0;
=20
@@ -54,18 +53,23 @@
=20
   /// Called by CoreEngine. Used to generate new successor
   /// nodes by processing the 'effects' of a block-level statement.
-  virtual void processCFGElement(const CFGElement E, StmtNodeBuilder& buil=
der)=3D0;
+  virtual void processCFGElement(const CFGElement E, ExplodedNode* Pred,
+                                 unsigned StmtIdx, NodeBuilderContext *Ctx=
)=3D0;
=20
   /// Called by CoreEngine when it starts processing a CFGBlock.  The
   /// SubEngine is expected to populate dstNodes with new nodes representi=
ng
   /// updated analysis state, or generate no nodes at all if it doesn't.
-  virtual void processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
-                            GenericNodeBuilder<BlockEntrance> &nodeBuilder=
) =3D 0;
+  virtual void processCFGBlockEntrance(const BlockEdge &L,
+                                       NodeBuilderWithSinks &nodeBuilder) =
=3D 0;
=20
   /// Called by CoreEngine.  Used to generate successor
   ///  nodes by processing the 'effects' of a branch condition.
   virtual void processBranch(const Stmt *Condition, const Stmt *Term,
-                             BranchNodeBuilder& builder) =3D 0;
+                             NodeBuilderContext& BuilderCtx,
+                             ExplodedNode *Pred,
+                             ExplodedNodeSet &Dst,
+                             const CFGBlock *DstT,
+                             const CFGBlock *DstF) =3D 0;
=20
   /// Called by CoreEngine.  Used to generate successor
   /// nodes by processing the 'effects' of a computed goto jump.
@@ -77,40 +81,41 @@
=20
   /// Called by CoreEngine.  Used to generate end-of-path
   /// nodes when the control reaches the end of a function.
-  virtual void processEndOfFunction(EndOfFunctionNodeBuilder& builder) =3D=
 0;
+  virtual void processEndOfFunction(NodeBuilderContext& BC) =3D 0;
=20
   // Generate the entry node of the callee.
-  virtual void processCallEnter(CallEnterNodeBuilder &builder) =3D 0;
+  virtual void processCallEnter(CallEnter CE, ExplodedNode *Pred) =3D 0;
=20
   // Generate the first post callsite node.
-  virtual void processCallExit(CallExitNodeBuilder &builder) =3D 0;
+  virtual void processCallExit(ExplodedNode *Pred) =3D 0;
=20
   /// Called by ConstraintManager. Used to call checker-specific
   /// logic for handling assumptions on symbolic values.
-  virtual const ProgramState *processAssume(const ProgramState *state,
+  virtual ProgramStateRef processAssume(ProgramStateRef state,
                                        SVal cond, bool assumption) =3D 0;
=20
   /// wantsRegionChangeUpdate - Called by ProgramStateManager to determine=
 if a
   ///  region change should trigger a processRegionChanges update.
-  virtual bool wantsRegionChangeUpdate(const ProgramState *state) =3D 0;
+  virtual bool wantsRegionChangeUpdate(ProgramStateRef state) =3D 0;
=20
-  /// processRegionChanges - Called by ProgramStateManager whenever a chan=
ge is made
-  ///  to the store. Used to update checkers that track region values.
-  virtual const ProgramState *
-  processRegionChanges(const ProgramState *state,
+  /// processRegionChanges - Called by ProgramStateManager whenever a chan=
ge is
+  /// made to the store. Used to update checkers that track region values.
+  virtual ProgramStateRef=20
+  processRegionChanges(ProgramStateRef state,
                        const StoreManager::InvalidatedSymbols *invalidated,
                        ArrayRef<const MemRegion *> ExplicitRegions,
-                       ArrayRef<const MemRegion *> Regions) =3D 0;
+                       ArrayRef<const MemRegion *> Regions,
+                       const CallOrObjCMessage *Call) =3D 0;
=20
=20
-  inline const ProgramState *
-  processRegionChange(const ProgramState *state,
+  inline ProgramStateRef=20
+  processRegionChange(ProgramStateRef state,
                       const MemRegion* MR) {
-    return processRegionChanges(state, 0, MR, MR);
+    return processRegionChanges(state, 0, MR, MR, 0);
   }
=20
   /// printState - Called by ProgramStateManager to print checker-specific=
 data.
-  virtual void printState(raw_ostream &Out, const ProgramState *State,
+  virtual void printState(raw_ostream &Out, ProgramStateRef State,
                           const char *NL, const char *Sep) =3D 0;
=20
   /// Called by CoreEngine when the analysis worklist is either empty or t=
he
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SymbolManager.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/SymbolManager.h	Tue Apr 17 11:51:51 2012 +0300
@@ -40,13 +40,16 @@
   class TypedValueRegion;
   class VarRegion;
=20
+/// \brief Symbolic value. These values used to capture symbolic execution=
 of
+/// the program.
 class SymExpr : public llvm::FoldingSetNode {
+  virtual void anchor();
 public:
   enum Kind { RegionValueKind, ConjuredKind, DerivedKind, ExtentKind,
               MetadataKind,
               BEGIN_SYMBOLS =3D RegionValueKind,
               END_SYMBOLS =3D MetadataKind,
-              SymIntKind, SymSymKind };
+              SymIntKind, IntSymKind, SymSymKind, CastSymbolKind };
 private:
   Kind K;
=20
@@ -58,21 +61,49 @@
=20
   Kind getKind() const { return K; }
=20
-  void dump() const;
+  virtual void dump() const;
=20
-  virtual void dumpToStream(raw_ostream &os) const =3D 0;
+  virtual void dumpToStream(raw_ostream &os) const {}
=20
   virtual QualType getType(ASTContext&) const =3D 0;
   virtual void Profile(llvm::FoldingSetNodeID& profile) =3D 0;
=20
   // Implement isa<T> support.
   static inline bool classof(const SymExpr*) { return true; }
+
+  /// \brief Iterator over symbols that the current symbol depends on.
+  ///
+  /// For SymbolData, it's the symbol itself; for expressions, it's the
+  /// expression symbol and all the operands in it. Note, SymbolDerived is
+  /// treated as SymbolData - the iterator will NOT visit the parent regio=
n.
+  class symbol_iterator {
+    SmallVector<const SymExpr*, 5> itr;
+    void expand();
+  public:
+    symbol_iterator() {}
+    symbol_iterator(const SymExpr *SE);
+
+    symbol_iterator &operator++();
+    const SymExpr* operator*();
+
+    bool operator=3D=3D(const symbol_iterator &X) const;
+    bool operator!=3D(const symbol_iterator &X) const;
+  };
+
+  symbol_iterator symbol_begin() const {
+    return symbol_iterator(this);
+  }
+  static symbol_iterator symbol_end() { return symbol_iterator(); }
 };
=20
+typedef const SymExpr* SymbolRef;
+typedef llvm::SmallVector<SymbolRef, 2> SymbolRefSmallVectorTy;
+
 typedef unsigned SymbolID;
-
+/// \brief A symbol representing data which can be stored in a memory loca=
tion
+/// (region).
 class SymbolData : public SymExpr {
-private:
+  virtual void anchor();
   const SymbolID Sym;
=20
 protected:
@@ -90,10 +121,7 @@
   }
 };
=20
-typedef const SymbolData* SymbolRef;
-typedef llvm::SmallVector<SymbolRef, 2> SymbolRefSmallVectorTy;
-
-/// A symbol representing the value of a MemRegion.
+///\brief A symbol representing the value stored at a MemRegion.
 class SymbolRegionValue : public SymbolData {
   const TypedValueRegion *R;
=20
@@ -112,7 +140,7 @@
     Profile(profile, R);
   }
=20
-  void dumpToStream(raw_ostream &os) const;
+  virtual void dumpToStream(raw_ostream &os) const;
=20
   QualType getType(ASTContext&) const;
=20
@@ -122,17 +150,21 @@
   }
 };
=20
-/// A symbol representing the result of an expression.
+/// A symbol representing the result of an expression in the case when we =
do
+/// not know anything about what the expression is.
 class SymbolConjured : public SymbolData {
   const Stmt *S;
   QualType T;
   unsigned Count;
+  const LocationContext *LCtx;
   const void *SymbolTag;
=20
 public:
-  SymbolConjured(SymbolID sym, const Stmt *s, QualType t, unsigned count,
+  SymbolConjured(SymbolID sym, const Stmt *s, const LocationContext *lctx,
+		 QualType t, unsigned count,
                  const void *symbolTag)
     : SymbolData(ConjuredKind, sym), S(s), T(t), Count(count),
+      LCtx(lctx),
       SymbolTag(symbolTag) {}
=20
   const Stmt *getStmt() const { return S; }
@@ -141,19 +173,21 @@
=20
   QualType getType(ASTContext&) const;
=20
-  void dumpToStream(raw_ostream &os) const;
+  virtual void dumpToStream(raw_ostream &os) const;
=20
   static void Profile(llvm::FoldingSetNodeID& profile, const Stmt *S,
-                      QualType T, unsigned Count, const void *SymbolTag) {
+                      QualType T, unsigned Count, const LocationContext *L=
Ctx,
+                      const void *SymbolTag) {
     profile.AddInteger((unsigned) ConjuredKind);
     profile.AddPointer(S);
+    profile.AddPointer(LCtx);
     profile.Add(T);
     profile.AddInteger(Count);
     profile.AddPointer(SymbolTag);
   }
=20
   virtual void Profile(llvm::FoldingSetNodeID& profile) {
-    Profile(profile, S, T, Count, SymbolTag);
+    Profile(profile, S, T, Count, LCtx, SymbolTag);
   }
=20
   // Implement isa<T> support.
@@ -177,7 +211,7 @@
=20
   QualType getType(ASTContext&) const;
=20
-  void dumpToStream(raw_ostream &os) const;
+  virtual void dumpToStream(raw_ostream &os) const;
=20
   static void Profile(llvm::FoldingSetNodeID& profile, SymbolRef parent,
                       const TypedValueRegion *r) {
@@ -210,7 +244,7 @@
=20
   QualType getType(ASTContext&) const;
=20
-  void dumpToStream(raw_ostream &os) const;
+  virtual void dumpToStream(raw_ostream &os) const;
=20
   static void Profile(llvm::FoldingSetNodeID& profile, const SubRegion *R)=
 {
     profile.AddInteger((unsigned) ExtentKind);
@@ -249,7 +283,7 @@
=20
   QualType getType(ASTContext&) const;
=20
-  void dumpToStream(raw_ostream &os) const;
+  virtual void dumpToStream(raw_ostream &os) const;
=20
   static void Profile(llvm::FoldingSetNodeID& profile, const MemRegion *R,
                       const Stmt *S, QualType T, unsigned Count,
@@ -272,6 +306,42 @@
   }
 };
=20
+/// \brief Represents a cast expression.
+class SymbolCast : public SymExpr {
+  const SymExpr *Operand;
+  /// Type of the operand.
+  QualType FromTy;
+  /// The type of the result.
+  QualType ToTy;
+
+public:
+  SymbolCast(const SymExpr *In, QualType From, QualType To) :
+    SymExpr(CastSymbolKind), Operand(In), FromTy(From), ToTy(To) { }
+
+  QualType getType(ASTContext &C) const { return ToTy; }
+
+  const SymExpr *getOperand() const { return Operand; }
+
+  virtual void dumpToStream(raw_ostream &os) const;
+
+  static void Profile(llvm::FoldingSetNodeID& ID,
+                      const SymExpr *In, QualType From, QualType To) {
+    ID.AddInteger((unsigned) CastSymbolKind);
+    ID.AddPointer(In);
+    ID.Add(From);
+    ID.Add(To);
+  }
+
+  void Profile(llvm::FoldingSetNodeID& ID) {
+    Profile(ID, Operand, FromTy, ToTy);
+  }
+
+  // Implement isa<T> support.
+  static inline bool classof(const SymExpr *SE) {
+    return SE->getKind() =3D=3D CastSymbolKind;
+  }
+};
+
 /// SymIntExpr - Represents symbolic expression like 'x' + 3.
 class SymIntExpr : public SymExpr {
   const SymExpr *LHS;
@@ -290,7 +360,7 @@
=20
   BinaryOperator::Opcode getOpcode() const { return Op; }
=20
-  void dumpToStream(raw_ostream &os) const;
+  virtual void dumpToStream(raw_ostream &os) const;
=20
   const SymExpr *getLHS() const { return LHS; }
   const llvm::APSInt &getRHS() const { return RHS; }
@@ -315,6 +385,47 @@
   }
 };
=20
+/// IntSymExpr - Represents symbolic expression like 3 - 'x'.
+class IntSymExpr : public SymExpr {
+  const llvm::APSInt& LHS;
+  BinaryOperator::Opcode Op;
+  const SymExpr *RHS;
+  QualType T;
+
+public:
+  IntSymExpr(const llvm::APSInt& lhs, BinaryOperator::Opcode op,
+             const SymExpr *rhs, QualType t)
+    : SymExpr(IntSymKind), LHS(lhs), Op(op), RHS(rhs), T(t) {}
+
+  QualType getType(ASTContext &C) const { return T; }
+
+  BinaryOperator::Opcode getOpcode() const { return Op; }
+
+  virtual void dumpToStream(raw_ostream &os) const;
+
+  const SymExpr *getRHS() const { return RHS; }
+  const llvm::APSInt &getLHS() const { return LHS; }
+
+  static void Profile(llvm::FoldingSetNodeID& ID, const llvm::APSInt& lhs,
+                      BinaryOperator::Opcode op, const SymExpr *rhs,
+                      QualType t) {
+    ID.AddInteger((unsigned) IntSymKind);
+    ID.AddPointer(&lhs);
+    ID.AddInteger(op);
+    ID.AddPointer(rhs);
+    ID.Add(t);
+  }
+
+  void Profile(llvm::FoldingSetNodeID& ID) {
+    Profile(ID, LHS, Op, RHS, T);
+  }
+
+  // Implement isa<T> support.
+  static inline bool classof(const SymExpr *SE) {
+    return SE->getKind() =3D=3D IntSymKind;
+  }
+};
+
 /// SymSymExpr - Represents symbolic expression like 'x' + 'y'.
 class SymSymExpr : public SymExpr {
   const SymExpr *LHS;
@@ -335,7 +446,7 @@
   // generation of virtual functions.
   QualType getType(ASTContext &C) const { return T; }
=20
-  void dumpToStream(raw_ostream &os) const;
+  virtual void dumpToStream(raw_ostream &os) const;
=20
   static void Profile(llvm::FoldingSetNodeID& ID, const SymExpr *lhs,
                     BinaryOperator::Opcode op, const SymExpr *rhs, QualTyp=
e t) {
@@ -382,13 +493,18 @@
   /// \brief Make a unique symbol for MemRegion R according to its kind.
   const SymbolRegionValue* getRegionValueSymbol(const TypedValueRegion* R);
=20
-  const SymbolConjured* getConjuredSymbol(const Stmt *E, QualType T,
+  const SymbolConjured* getConjuredSymbol(const Stmt *E,
+					  const LocationContext *LCtx,
+					  QualType T,
                                           unsigned VisitCount,
                                           const void *SymbolTag =3D 0);
=20
-  const SymbolConjured* getConjuredSymbol(const Expr *E, unsigned VisitCou=
nt,
+  const SymbolConjured* getConjuredSymbol(const Expr *E,
+					  const LocationContext *LCtx,
+					  unsigned VisitCount,
                                           const void *SymbolTag =3D 0) {
-    return getConjuredSymbol(E, E->getType(), VisitCount, SymbolTag);
+    return getConjuredSymbol(E, LCtx, E->getType(),
+			     VisitCount, SymbolTag);
   }
=20
   const SymbolDerived *getDerivedSymbol(SymbolRef parentSymbol,
@@ -404,6 +520,9 @@
                                           QualType T, unsigned VisitCount,
                                           const void *SymbolTag =3D 0);
=20
+  const SymbolCast* getCastSymbol(const SymExpr *Operand,
+                                  QualType From, QualType To);
+
   const SymIntExpr *getSymIntExpr(const SymExpr *lhs, BinaryOperator::Opco=
de op,
                                   const llvm::APSInt& rhs, QualType t);
=20
@@ -412,6 +531,10 @@
     return getSymIntExpr(&lhs, op, rhs, t);
   }
=20
+  const IntSymExpr *getIntSymExpr(const llvm::APSInt& lhs,
+                                  BinaryOperator::Opcode op,
+                                  const SymExpr *rhs, QualType t);
+
   const SymSymExpr *getSymSymExpr(const SymExpr *lhs, BinaryOperator::Opco=
de op,
                                   const SymExpr *rhs, QualType t);
=20
@@ -464,7 +587,7 @@
=20
   bool isLive(SymbolRef sym);
   bool isLiveRegion(const MemRegion *region);
-  bool isLive(const Stmt *ExprVal) const;
+  bool isLive(const Stmt *ExprVal, const LocationContext *LCtx) const;
   bool isLive(const VarRegion *VR, bool includeStoreBindings =3D false) co=
nst;
=20
   /// \brief Unconditionally marks a symbol as live.
@@ -537,7 +660,7 @@
=20
 namespace llvm {
 static inline raw_ostream &operator<<(raw_ostream &os,
-                                            const clang::ento::SymExpr *SE=
) {
+                                      const clang::ento::SymExpr *SE) {
   SE->dumpToStream(os);
   return os;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/include/=
clang/StaticAnalyzer/Core/PathSensitive/WorkList.h
--- a/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/WorkList.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/include/clang/StaticAnalyzer/Core/PathS=
ensitive/WorkList.h	Tue Apr 17 11:51:51 2012 +0300
@@ -73,6 +73,7 @@
   }
=20
   void enqueue(ExplodedNode *N) {
+    assert(N->getLocation().getKind() !=3D ProgramPoint::PostStmtKind);
     enqueue(WorkListUnit(N, CurrentCounter));
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/ARCMT.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/ARCMT.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/ARCMT.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -10,6 +10,7 @@
 #include "Internals.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Frontend/Utils.h"
 #include "clang/AST/ASTConsumer.h"
@@ -98,7 +99,7 @@
=20
   virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
                                 const Diagnostic &Info) {
-    if (arcmt::isARCDiagnostic(Info.getID(), Diags) ||
+    if (DiagnosticIDs::isARCDiagnostic(Info.getID()) ||
         level >=3D DiagnosticsEngine::Error || level =3D=3D DiagnosticsEng=
ine::Note) {
       CapturedDiags.push_back(StoredDiagnostic(level, Info));
       return;
@@ -184,18 +185,19 @@
=20
 static CompilerInvocation *
 createInvocationForMigration(CompilerInvocation &origCI) {
-  llvm::OwningPtr<CompilerInvocation> CInvok;
+  OwningPtr<CompilerInvocation> CInvok;
   CInvok.reset(new CompilerInvocation(origCI));
   CInvok->getPreprocessorOpts().ImplicitPCHInclude =3D std::string();
   CInvok->getPreprocessorOpts().ImplicitPTHInclude =3D std::string();
   std::string define =3D getARCMTMacroName();
   define +=3D '=3D';
   CInvok->getPreprocessorOpts().addMacroDef(define);
-  CInvok->getLangOpts().ObjCAutoRefCount =3D true;
+  CInvok->getLangOpts()->ObjCAutoRefCount =3D true;
+  CInvok->getLangOpts()->setGC(LangOptions::NonGC);
   CInvok->getDiagnosticOpts().ErrorLimit =3D 0;
   CInvok->getDiagnosticOpts().Warnings.push_back(
                                             "error=3Darc-unsafe-retained-a=
ssign");
-  CInvok->getLangOpts().ObjCRuntimeHasWeak =3D HasARCRuntime(origCI);
+  CInvok->getLangOpts()->ObjCRuntimeHasWeak =3D HasARCRuntime(origCI);
=20
   return CInvok.take();
 }
@@ -204,12 +206,12 @@
                                    const DiagnosticOptions &diagOpts,
                                    Preprocessor &PP) {
   TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
       new DiagnosticsEngine(DiagID, &printer, /*ShouldOwnClient=3D*/false)=
);
   Diags->setSourceManager(&PP.getSourceManager());
  =20
-  printer.BeginSourceFile(PP.getLangOptions(), &PP);
+  printer.BeginSourceFile(PP.getLangOpts(), &PP);
   arcDiags.reportDiagnostics(*Diags);
   printer.EndSourceFile();
 }
@@ -219,33 +221,38 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
-                                 StringRef Filename, InputKind Kind,
+                                 const FrontendInputFile &Input,
                                  DiagnosticConsumer *DiagClient,
                                  bool emitPremigrationARCErrors,
                                  StringRef plistOut) {
-  if (!origCI.getLangOpts().ObjC1)
+  if (!origCI.getLangOpts()->ObjC1)
     return false;
=20
-  std::vector<TransformFn> transforms =3D arcmt::getAllTransformations();
+  LangOptions::GCMode OrigGCMode =3D origCI.getLangOpts()->getGC();
+  bool NoNSAllocReallocError =3D origCI.getMigratorOpts().NoNSAllocRealloc=
Error;
+  bool NoFinalizeRemoval =3D origCI.getMigratorOpts().NoFinalizeRemoval;
+
+  std::vector<TransformFn> transforms =3D arcmt::getAllTransformations(Ori=
gGCMode,
+                                                                     NoFin=
alizeRemoval);
   assert(!transforms.empty());
=20
-  llvm::OwningPtr<CompilerInvocation> CInvok;
+  OwningPtr<CompilerInvocation> CInvok;
   CInvok.reset(createInvocationForMigration(origCI));
   CInvok->getFrontendOpts().Inputs.clear();
-  CInvok->getFrontendOpts().Inputs.push_back(std::make_pair(Kind, Filename=
));
+  CInvok->getFrontendOpts().Inputs.push_back(Input);
=20
   CapturedDiagList capturedDiags;
=20
   assert(DiagClient);
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
       new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=3D*/fals=
e));
=20
   // Filter of all diagnostics.
   CaptureDiagnosticConsumer errRec(*Diags, capturedDiags);
   Diags->setClient(&errRec, /*ShouldOwnClient=3D*/false);
=20
-  llvm::OwningPtr<ASTUnit> Unit(
+  OwningPtr<ASTUnit> Unit(
       ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
   if (!Unit)
     return true;
@@ -257,7 +264,7 @@
=20
   if (Diags->hasFatalErrorOccurred()) {
     Diags->Reset();
-    DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocess=
or());
+    DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor(=
));
     capturedDiags.reportDiagnostics(*Diags);
     DiagClient->EndSourceFile();
     return true;
@@ -272,7 +279,7 @@
            I =3D capturedDiags.begin(), E =3D capturedDiags.end(); I !=3D =
E; ++I)
       arcDiags.push_back(*I);
     writeARCDiagsToPlist(plistOut, arcDiags,
-                         Ctx.getSourceManager(), Ctx.getLangOptions());
+                         Ctx.getSourceManager(), Ctx.getLangOpts());
   }
=20
   // After parsing of source files ended, we want to reuse the
@@ -280,14 +287,16 @@
   // We call BeginSourceFile because DiagnosticConsumer requires that=20
   // diagnostics with source range information are emitted only in between
   // BeginSourceFile() and EndSourceFile().
-  DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor=
());
+  DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
=20
   // No macros will be added since we are just checking and we won't modify
   // source code.
   std::vector<SourceLocation> ARCMTMacroLocs;
=20
   TransformActions testAct(*Diags, capturedDiags, Ctx, Unit->getPreprocess=
or());
-  MigrationPass pass(Ctx, Unit->getSema(), testAct, ARCMTMacroLocs);
+  MigrationPass pass(Ctx, OrigGCMode, Unit->getSema(), testAct, ARCMTMacro=
Locs);
+  pass.setNSAllocReallocError(NoNSAllocReallocError);
+  pass.setNoFinalizeRemoval(NoFinalizeRemoval);
=20
   for (unsigned i=3D0, e =3D transforms.size(); i !=3D e; ++i)
     transforms[i](pass);
@@ -298,7 +307,7 @@
=20
   // If we are migrating code that gets the '-fobjc-arc' flag, make sure
   // to remove it so that we don't get errors from normal compilation.
-  origCI.getLangOpts().ObjCAutoRefCount =3D false;
+  origCI.getLangOpts()->ObjCAutoRefCount =3D false;
=20
   return capturedDiags.hasErrors() || testAct.hasReportedErrors();
 }
@@ -308,27 +317,31 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 static bool applyTransforms(CompilerInvocation &origCI,
-                            StringRef Filename, InputKind Kind,
+                            const FrontendInputFile &Input,
                             DiagnosticConsumer *DiagClient,
                             StringRef outputDir,
                             bool emitPremigrationARCErrors,
                             StringRef plistOut) {
-  if (!origCI.getLangOpts().ObjC1)
+  if (!origCI.getLangOpts()->ObjC1)
     return false;
=20
+  LangOptions::GCMode OrigGCMode =3D origCI.getLangOpts()->getGC();
+
   // Make sure checking is successful first.
   CompilerInvocation CInvokForCheck(origCI);
-  if (arcmt::checkForManualIssues(CInvokForCheck, Filename, Kind, DiagClie=
nt,
+  if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
                                   emitPremigrationARCErrors, plistOut))
     return true;
=20
   CompilerInvocation CInvok(origCI);
   CInvok.getFrontendOpts().Inputs.clear();
-  CInvok.getFrontendOpts().Inputs.push_back(std::make_pair(Kind, Filename)=
);
+  CInvok.getFrontendOpts().Inputs.push_back(Input);
  =20
   MigrationProcess migration(CInvok, DiagClient, outputDir);
+  bool NoFinalizeRemoval =3D origCI.getMigratorOpts().NoFinalizeRemoval;
=20
-  std::vector<TransformFn> transforms =3D arcmt::getAllTransformations();
+  std::vector<TransformFn> transforms =3D arcmt::getAllTransformations(Ori=
gGCMode,
+                                                                     NoFin=
alizeRemoval);
   assert(!transforms.empty());
=20
   for (unsigned i=3D0, e =3D transforms.size(); i !=3D e; ++i) {
@@ -336,36 +349,36 @@
     if (err) return true;
   }
=20
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
       new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=3D*/fals=
e));
=20
   if (outputDir.empty()) {
-    origCI.getLangOpts().ObjCAutoRefCount =3D true;
+    origCI.getLangOpts()->ObjCAutoRefCount =3D true;
     return migration.getRemapper().overwriteOriginal(*Diags);
   } else {
     // If we are migrating code that gets the '-fobjc-arc' flag, make sure
     // to remove it so that we don't get errors from normal compilation.
-    origCI.getLangOpts().ObjCAutoRefCount =3D false;
+    origCI.getLangOpts()->ObjCAutoRefCount =3D false;
     return migration.getRemapper().flushToDisk(outputDir, *Diags);
   }
 }
=20
 bool arcmt::applyTransformations(CompilerInvocation &origCI,
-                                 StringRef Filename, InputKind Kind,
+                                 const FrontendInputFile &Input,
                                  DiagnosticConsumer *DiagClient) {
-  return applyTransforms(origCI, Filename, Kind, DiagClient,
+  return applyTransforms(origCI, Input, DiagClient,
                          StringRef(), false, StringRef());
 }
=20
 bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
-                                      StringRef Filename, InputKind Kind,
+                                      const FrontendInputFile &Input,
                                       DiagnosticConsumer *DiagClient,
                                       StringRef outputDir,
                                       bool emitPremigrationARCErrors,
                                       StringRef plistOut) {
   assert(!outputDir.empty() && "Expected output directory path");
-  return applyTransforms(origCI, Filename, Kind, DiagClient,
+  return applyTransforms(origCI, Input, DiagClient,
                          outputDir, emitPremigrationARCErrors, plistOut);
 }
=20
@@ -375,8 +388,8 @@
                               DiagnosticConsumer *DiagClient) {
   assert(!outputDir.empty());
=20
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
       new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=3D*/fals=
e));
=20
   FileRemapper remapper;
@@ -385,13 +398,51 @@
   if (err)
     return true;
=20
-  CompilerInvocation CI;
-  remapper.applyMappings(CI);
-  remap =3D CI.getPreprocessorOpts().RemappedFiles;
+  PreprocessorOptions PPOpts;
+  remapper.applyMappings(PPOpts);
+  remap =3D PPOpts.RemappedFiles;
=20
   return false;
 }
=20
+bool arcmt::getFileRemappingsFromFileList(
+                        std::vector<std::pair<std::string,std::string> > &=
remap,
+                        ArrayRef<StringRef> remapFiles,
+                        DiagnosticConsumer *DiagClient) {
+  bool hasErrorOccurred =3D false;
+  llvm::StringMap<bool> Uniquer;
+
+  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
+      new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=3D*/fals=
e));
+
+  for (ArrayRef<StringRef>::iterator
+         I =3D remapFiles.begin(), E =3D remapFiles.end(); I !=3D E; ++I) {
+    StringRef file =3D *I;
+
+    FileRemapper remapper;
+    bool err =3D remapper.initFromFile(file, *Diags,
+                                     /*ignoreIfFilesChanged=3D*/true);
+    hasErrorOccurred =3D hasErrorOccurred || err;
+    if (err)
+      continue;
+
+    PreprocessorOptions PPOpts;
+    remapper.applyMappings(PPOpts);
+    for (PreprocessorOptions::remapped_file_iterator
+           RI =3D PPOpts.remapped_file_begin(), RE =3D PPOpts.remapped_fil=
e_end();
+           RI !=3D RE; ++RI) {
+      bool &inserted =3D Uniquer[RI->first];
+      if (inserted)
+        continue;
+      inserted =3D true;
+      remap.push_back(*RI);
+    }
+  }
+
+  return hasErrorOccurred;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // CollectTransformActions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -478,8 +529,8 @@
                                    StringRef outputDir)
   : OrigCI(CI), DiagClient(diagClient) {
   if (!outputDir.empty()) {
-    llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
-    llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
+    IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
       new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=3D*/fals=
e));
     Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=3D*/tr=
ue);
   }
@@ -487,28 +538,28 @@
=20
 bool MigrationProcess::applyTransform(TransformFn trans,
                                       RewriteListener *listener) {
-  llvm::OwningPtr<CompilerInvocation> CInvok;
+  OwningPtr<CompilerInvocation> CInvok;
   CInvok.reset(createInvocationForMigration(OrigCI));
   CInvok->getDiagnosticOpts().IgnoreWarnings =3D true;
=20
-  Remapper.applyMappings(*CInvok);
+  Remapper.applyMappings(CInvok->getPreprocessorOpts());
=20
   CapturedDiagList capturedDiags;
   std::vector<SourceLocation> ARCMTMacroLocs;
=20
   assert(DiagClient);
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
       new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=3D*/fals=
e));
=20
   // Filter of all diagnostics.
   CaptureDiagnosticConsumer errRec(*Diags, capturedDiags);
   Diags->setClient(&errRec, /*ShouldOwnClient=3D*/false);
=20
-  llvm::OwningPtr<ARCMTMacroTrackerAction> ASTAction;
+  OwningPtr<ARCMTMacroTrackerAction> ASTAction;
   ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
=20
-  llvm::OwningPtr<ASTUnit> Unit(
+  OwningPtr<ASTUnit> Unit(
       ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
                                                 ASTAction.get()));
   if (!Unit)
@@ -522,7 +573,7 @@
=20
   if (Diags->hasFatalErrorOccurred()) {
     Diags->Reset();
-    DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocess=
or());
+    DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor(=
));
     capturedDiags.reportDiagnostics(*Diags);
     DiagClient->EndSourceFile();
     return true;
@@ -533,11 +584,12 @@
   // We call BeginSourceFile because DiagnosticConsumer requires that=20
   // diagnostics with source range information are emitted only in between
   // BeginSourceFile() and EndSourceFile().
-  DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor=
());
+  DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
=20
-  Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOptions());
+  Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
   TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
-  MigrationPass pass(Ctx, Unit->getSema(), TA, ARCMTMacroLocs);
+  MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
+                     Unit->getSema(), TA, ARCMTMacroLocs);
=20
   trans(pass);
=20
@@ -559,25 +611,16 @@
     assert(file);
     std::string newFname =3D file->getName();
     newFname +=3D "-trans";
-    llvm::SmallString<512> newText;
+    SmallString<512> newText;
     llvm::raw_svector_ostream vecOS(newText);
     buf.write(vecOS);
     vecOS.flush();
     llvm::MemoryBuffer *memBuf =3D llvm::MemoryBuffer::getMemBufferCopy(
                    StringRef(newText.data(), newText.size()), newFname);
-    llvm::SmallString<64> filePath(file->getName());
+    SmallString<64> filePath(file->getName());
     Unit->getFileManager().FixupRelativePath(filePath);
     Remapper.remap(filePath.str(), memBuf);
   }
=20
   return false;
 }
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// isARCDiagnostic.
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-bool arcmt::isARCDiagnostic(unsigned diagID, DiagnosticsEngine &Diag) {
-  return Diag.getDiagnosticIDs()->getCategoryNumberForDiag(diagID) =3D=3D
-           diag::DiagCat_Automatic_Reference_Counting_Issue;
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/ARCMTActions.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/ARCMTActions.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/ARCMTActions.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -15,8 +15,7 @@
 using namespace arcmt;
=20
 bool CheckAction::BeginInvocation(CompilerInstance &CI) {
-  if (arcmt::checkForManualIssues(CI.getInvocation(), getCurrentFile(),
-                                  getCurrentFileKind(),
+  if (arcmt::checkForManualIssues(CI.getInvocation(), getCurrentInput(),
                                   CI.getDiagnostics().getClient()))
     return false; // errors, stop the action.
=20
@@ -29,8 +28,7 @@
   : WrapperFrontendAction(WrappedAction) {}
=20
 bool ModifyAction::BeginInvocation(CompilerInstance &CI) {
-  return !arcmt::applyTransformations(CI.getInvocation(),
-                                      getCurrentFile(), getCurrentFileKind=
(),
+  return !arcmt::applyTransformations(CI.getInvocation(), getCurrentInput(=
),
                                       CI.getDiagnostics().getClient());
 }
=20
@@ -39,12 +37,11 @@
=20
 bool MigrateAction::BeginInvocation(CompilerInstance &CI) {
   if (arcmt::migrateWithTemporaryFiles(CI.getInvocation(),
-                                           getCurrentFile(),
-                                           getCurrentFileKind(),
-                                           CI.getDiagnostics().getClient(),
-                                           MigrateDir,
-                                           EmitPremigrationARCErros,
-                                           PlistOut))
+                                       getCurrentInput(),
+                                       CI.getDiagnostics().getClient(),
+                                       MigrateDir,
+                                       EmitPremigrationARCErros,
+                                       PlistOut))
     return false; // errors, stop the action.
=20
   // We only want to see diagnostics emitted by migrateWithTemporaryFiles.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/FileRemapper.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/FileRemapper.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/FileRemapper.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -8,8 +8,9 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/ARCMigrate/FileRemapper.h"
-#include "clang/Frontend/CompilerInvocation.h"
+#include "clang/Frontend/PreprocessorOptions.h"
 #include "clang/Basic/FileManager.h"
+#include "clang/Basic/Diagnostic.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/FileSystem.h"
@@ -50,9 +51,15 @@
=20
 bool FileRemapper::initFromDisk(StringRef outputDir, DiagnosticsEngine &Di=
ag,
                                 bool ignoreIfFilesChanged) {
+  std::string infoFile =3D getRemapInfoFile(outputDir);
+  return initFromFile(infoFile, Diag, ignoreIfFilesChanged);
+}
+
+bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Dia=
g,
+                                bool ignoreIfFilesChanged) {
   assert(FromToMappings.empty() &&
          "initFromDisk should be called before any remap calls");
-  std::string infoFile =3D getRemapInfoFile(outputDir);
+  std::string infoFile =3D filePath;
   bool fileExists =3D false;
   llvm::sys::fs::exists(infoFile, fileExists);
   if (!fileExists)
@@ -60,9 +67,8 @@
=20
   std::vector<std::pair<const FileEntry *, const FileEntry *> > pairs;
  =20
-  llvm::OwningPtr<llvm::MemoryBuffer> fileBuf;
-  if (llvm::error_code ec =3D llvm::MemoryBuffer::getFile(infoFile.c_str(),
-                                                        fileBuf))
+  OwningPtr<llvm::MemoryBuffer> fileBuf;
+  if (llvm::MemoryBuffer::getFile(infoFile.c_str(), fileBuf))
     return report("Error opening file: " + infoFile, Diag);
  =20
   SmallVector<StringRef, 64> lines;
@@ -109,8 +115,15 @@
   if (fs::create_directory(outputDir, existed) !=3D llvm::errc::success)
     return report("Could not create directory: " + outputDir, Diag);
=20
+  std::string infoFile =3D getRemapInfoFile(outputDir);
+  return flushToFile(infoFile, Diag);
+}
+
+bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Di=
ag) {
+  using namespace llvm::sys;
+
   std::string errMsg;
-  std::string infoFile =3D getRemapInfoFile(outputDir);
+  std::string infoFile =3D outputPath;
   llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg,
                                llvm::raw_fd_ostream::F_Binary);
   if (!errMsg.empty())
@@ -120,18 +133,18 @@
          I =3D FromToMappings.begin(), E =3D FromToMappings.end(); I !=3D =
E; ++I) {
=20
     const FileEntry *origFE =3D I->first;
-    llvm::SmallString<200> origPath =3D StringRef(origFE->getName());
+    SmallString<200> origPath =3D StringRef(origFE->getName());
     fs::make_absolute(origPath);
     infoOut << origPath << '\n';
     infoOut << (uint64_t)origFE->getModificationTime() << '\n';
=20
     if (const FileEntry *FE =3D I->second.dyn_cast<const FileEntry *>()) {
-      llvm::SmallString<200> newPath =3D StringRef(FE->getName());
+      SmallString<200> newPath =3D StringRef(FE->getName());
       fs::make_absolute(newPath);
       infoOut << newPath << '\n';
     } else {
=20
-      llvm::SmallString<64> tempPath;
+      SmallString<64> tempPath;
       tempPath =3D path::filename(origFE->getName());
       tempPath +=3D "-%%%%%%%%";
       tempPath +=3D path::extension(origFE->getName());
@@ -190,8 +203,7 @@
   return false;
 }
=20
-void FileRemapper::applyMappings(CompilerInvocation &CI) const {
-  PreprocessorOptions &PPOpts =3D CI.getPreprocessorOpts();
+void FileRemapper::applyMappings(PreprocessorOptions &PPOpts) const {
   for (MappingsTy::const_iterator
          I =3D FromToMappings.begin(), E =3D FromToMappings.end(); I !=3D =
E; ++I) {
     if (const FileEntry *FE =3D I->second.dyn_cast<const FileEntry *>()) {
@@ -205,8 +217,7 @@
   PPOpts.RetainRemappedFileBuffers =3D true;
 }
=20
-void FileRemapper::transferMappingsAndClear(CompilerInvocation &CI) {
-  PreprocessorOptions &PPOpts =3D CI.getPreprocessorOpts();
+void FileRemapper::transferMappingsAndClear(PreprocessorOptions &PPOpts) {
   for (MappingsTy::iterator
          I =3D FromToMappings.begin(), E =3D FromToMappings.end(); I !=3D =
E; ++I) {
     if (const FileEntry *FE =3D I->second.dyn_cast<const FileEntry *>()) {
@@ -269,15 +280,12 @@
     delete oldmem;
   } else {
     const FileEntry *toFE =3D targ.get<const FileEntry *>();
-    llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator
-      I =3D ToFromMappings.find(toFE);
-    if (I !=3D ToFromMappings.end())
-      ToFromMappings.erase(I);
+    ToFromMappings.erase(toFE);
   }
 }
=20
 bool FileRemapper::report(const Twine &err, DiagnosticsEngine &Diag) {
-  llvm::SmallString<128> buf;
+  SmallString<128> buf;
   unsigned ID =3D Diag.getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::=
Error,
                                                          err.toStringRef(b=
uf));
   Diag.Report(ID);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/Internals.h
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/Internals.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/Internals.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -94,6 +94,8 @@
=20
   void reportError(StringRef error, SourceLocation loc,
                    SourceRange range =3D SourceRange());
+  void reportWarning(StringRef warning, SourceLocation loc,
+                   SourceRange range =3D SourceRange());
   void reportNote(StringRef note, SourceLocation loc,
                   SourceRange range =3D SourceRange());
=20
@@ -137,17 +139,26 @@
 class MigrationPass {
 public:
   ASTContext &Ctx;
+  LangOptions::GCMode OrigGCMode;
+  MigratorOptions MigOptions;
   Sema &SemaRef;
   TransformActions &TA;
   std::vector<SourceLocation> &ARCMTMacroLocs;
=20
-  MigrationPass(ASTContext &Ctx, Sema &sema, TransformActions &TA,
+  MigrationPass(ASTContext &Ctx, LangOptions::GCMode OrigGCMode,
+                Sema &sema, TransformActions &TA,
                 std::vector<SourceLocation> &ARCMTMacroLocs)
-    : Ctx(Ctx), SemaRef(sema), TA(TA), ARCMTMacroLocs(ARCMTMacroLocs) { }
+    : Ctx(Ctx), OrigGCMode(OrigGCMode), MigOptions(),
+      SemaRef(sema), TA(TA),
+      ARCMTMacroLocs(ARCMTMacroLocs) { }
+
+  bool isGCMigration() const { return OrigGCMode !=3D LangOptions::NonGC; }
+  bool noNSAllocReallocError() const { return MigOptions.NoNSAllocReallocE=
rror; }
+  void setNSAllocReallocError(bool val) { MigOptions.NoNSAllocReallocError=
 =3D val; }
+  bool noFinalizeRemoval() const { return MigOptions.NoFinalizeRemoval; }
+  void setNoFinalizeRemoval(bool val) {MigOptions.NoFinalizeRemoval =3D va=
l; }
 };
=20
-bool isARCDiagnostic(unsigned diagID, DiagnosticsEngine &Diag);
-
 static inline StringRef getARCMTMacroName() {
   return "__IMPL_ARCMT_REMOVED_EXPR__";
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransARCAssign.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransARCAssign.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransARCAssign.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -39,6 +39,9 @@
   ARCAssignChecker(MigrationPass &pass) : Pass(pass) { }
=20
   bool VisitBinaryOperator(BinaryOperator *Exp) {
+    if (Exp->getType()->isDependentType())
+      return true;
+
     Expr *E =3D Exp->getLHS();
     SourceLocation OrigLoc =3D E->getExprLoc();
     SourceLocation Loc =3D OrigLoc;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransAutoreleasePool.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransAutoreleasePool.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransAutoreleasePool.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -263,10 +263,6 @@
       return checkRef(E->getLocation(), E->getDecl()->getLocation());
     }
=20
-    bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
-      return checkRef(E->getLocation(), E->getDecl()->getLocation());
-    }
-
     bool VisitTypedefTypeLoc(TypedefTypeLoc TL) {
       return checkRef(TL.getBeginLoc(), TL.getTypedefNameDecl()->getLocati=
on());
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransBlockObjCVariable.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransBlockObjCVariable.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransBlockObjCVariable.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -38,7 +38,7 @@
 class RootBlockObjCVarRewriter :
                           public RecursiveASTVisitor<RootBlockObjCVarRewri=
ter> {
   MigrationPass &Pass;
-  llvm::DenseSet<VarDecl *> CheckedVars;
+  llvm::DenseSet<VarDecl *> &VarsToChange;
=20
   class BlockVarChecker : public RecursiveASTVisitor<BlockVarChecker> {
     VarDecl *Var;
@@ -48,13 +48,13 @@
     BlockVarChecker(VarDecl *var) : Var(var) { }
  =20
     bool TraverseImplicitCastExpr(ImplicitCastExpr *castE) {
-      if (BlockDeclRefExpr *
-            ref =3D dyn_cast<BlockDeclRefExpr>(castE->getSubExpr())) {
+      if (DeclRefExpr *
+            ref =3D dyn_cast<DeclRefExpr>(castE->getSubExpr())) {
         if (ref->getDecl() =3D=3D Var) {
           if (castE->getCastKind() =3D=3D CK_LValueToRValue)
             return true; // Using the value of the variable.
           if (castE->getCastKind() =3D=3D CK_NoOp && castE->isLValue() &&
-              Var->getASTContext().getLangOptions().CPlusPlus)
+              Var->getASTContext().getLangOpts().CPlusPlus)
             return true; // Binding to const C++ reference.
         }
       }
@@ -62,7 +62,7 @@
       return base::TraverseImplicitCastExpr(castE);
     }
=20
-    bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
+    bool VisitDeclRefExpr(DeclRefExpr *E) {
       if (E->getDecl() =3D=3D Var)
         return false; // The reference of the variable, and not just its v=
alue,
                       //  is needed.
@@ -71,7 +71,9 @@
   };
=20
 public:
-  RootBlockObjCVarRewriter(MigrationPass &pass) : Pass(pass) { }
+  RootBlockObjCVarRewriter(MigrationPass &pass,
+                           llvm::DenseSet<VarDecl *> &VarsToChange)
+    : Pass(pass), VarsToChange(VarsToChange) { }
=20
   bool VisitBlockDecl(BlockDecl *block) {
     SmallVector<VarDecl *, 4> BlockVars;
@@ -80,7 +82,6 @@
            I =3D block->capture_begin(), E =3D block->capture_end(); I !=
=3D E; ++I) {
       VarDecl *var =3D I->getVariable();
       if (I->isByRef() &&
-          !isAlreadyChecked(var) &&
           var->getType()->isObjCObjectPointerType() &&
           isImplicitStrong(var->getType())) {
         BlockVars.push_back(var);
@@ -89,32 +90,19 @@
=20
     for (unsigned i =3D 0, e =3D BlockVars.size(); i !=3D e; ++i) {
       VarDecl *var =3D BlockVars[i];
-      CheckedVars.insert(var);
=20
       BlockVarChecker checker(var);
       bool onlyValueOfVarIsNeeded =3D checker.TraverseStmt(block->getBody(=
));
-      if (onlyValueOfVarIsNeeded) {
-        BlocksAttr *attr =3D var->getAttr<BlocksAttr>();
-        if(!attr)
-          continue;
-        bool useWeak =3D canApplyWeak(Pass.Ctx, var->getType());
-        SourceManager &SM =3D Pass.Ctx.getSourceManager();
-        Transaction Trans(Pass.TA);
-        Pass.TA.replaceText(SM.getExpansionLoc(attr->getLocation()),
-                            "__block",
-                            useWeak ? "__weak" : "__unsafe_unretained");
-      }
-
+      if (onlyValueOfVarIsNeeded)
+        VarsToChange.insert(var);
+      else
+        VarsToChange.erase(var);
     }
=20
     return true;
   }
=20
 private:
-  bool isAlreadyChecked(VarDecl *VD) {
-    return CheckedVars.count(VD);
-  }
-
   bool isImplicitStrong(QualType ty) {
     if (isa<AttributedType>(ty.getTypePtr()))
       return false;
@@ -124,19 +112,39 @@
=20
 class BlockObjCVarRewriter : public RecursiveASTVisitor<BlockObjCVarRewrit=
er> {
   MigrationPass &Pass;
+  llvm::DenseSet<VarDecl *> &VarsToChange;
=20
 public:
-  BlockObjCVarRewriter(MigrationPass &pass) : Pass(pass) { }
+  BlockObjCVarRewriter(MigrationPass &pass,
+                       llvm::DenseSet<VarDecl *> &VarsToChange)
+    : Pass(pass), VarsToChange(VarsToChange) { }
=20
   bool TraverseBlockDecl(BlockDecl *block) {
-    RootBlockObjCVarRewriter(Pass).TraverseDecl(block);
+    RootBlockObjCVarRewriter(Pass, VarsToChange).TraverseDecl(block);
     return true;
   }
 };
=20
 } // anonymous namespace
=20
-void trans::rewriteBlockObjCVariable(MigrationPass &pass) {
-  BlockObjCVarRewriter trans(pass);
-  trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());
+void BlockObjCVariableTraverser::traverseBody(BodyContext &BodyCtx) {
+  MigrationPass &Pass =3D BodyCtx.getMigrationContext().Pass;
+  llvm::DenseSet<VarDecl *> VarsToChange;
+
+  BlockObjCVarRewriter trans(Pass, VarsToChange);
+  trans.TraverseStmt(BodyCtx.getTopStmt());
+
+  for (llvm::DenseSet<VarDecl *>::iterator
+         I =3D VarsToChange.begin(), E =3D VarsToChange.end(); I !=3D E; +=
+I) {
+    VarDecl *var =3D *I;
+    BlocksAttr *attr =3D var->getAttr<BlocksAttr>();
+    if(!attr)
+      continue;
+    bool useWeak =3D canApplyWeak(Pass.Ctx, var->getType());
+    SourceManager &SM =3D Pass.Ctx.getSourceManager();
+    Transaction Trans(Pass.TA);
+    Pass.TA.replaceText(SM.getExpansionLoc(attr->getLocation()),
+                        "__block",
+                        useWeak ? "__weak" : "__unsafe_unretained");
+  }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransEmptyStatementsAndDealloc.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransEmptyStatementsAndD=
ealloc.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransEmptyStatementsAndD=
ealloc.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -196,35 +196,60 @@
   return true;
 }
=20
-static void removeDeallocMethod(MigrationPass &pass) {
+static void cleanupDeallocOrFinalize(MigrationPass &pass) {
   ASTContext &Ctx =3D pass.Ctx;
   TransformActions &TA =3D pass.TA;
   DeclContext *DC =3D Ctx.getTranslationUnitDecl();
+  Selector FinalizeSel =3D
+      Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
=20
   typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
     impl_iterator;
   for (impl_iterator I =3D impl_iterator(DC->decls_begin()),
                      E =3D impl_iterator(DC->decls_end()); I !=3D E; ++I) {
+    ObjCMethodDecl *DeallocM =3D 0;
+    ObjCMethodDecl *FinalizeM =3D 0;
     for (ObjCImplementationDecl::instmeth_iterator
            MI =3D (*I)->instmeth_begin(),
            ME =3D (*I)->instmeth_end(); MI !=3D ME; ++MI) {
       ObjCMethodDecl *MD =3D *MI;
+      if (!MD->hasBody())
+        continue;
+ =20
       if (MD->getMethodFamily() =3D=3D OMF_dealloc) {
-        if (MD->hasBody() &&
-            isBodyEmpty(MD->getCompoundBody(), Ctx, pass.ARCMTMacroLocs)) {
-          Transaction Trans(TA);
-          TA.remove(MD->getSourceRange());
-        }
-        break;
+        DeallocM =3D MD;
+      } else if (MD->isInstanceMethod() && MD->getSelector() =3D=3D Finali=
zeSel) {
+        FinalizeM =3D MD;
+      }
+    }
+
+    if (DeallocM) {
+      if (isBodyEmpty(DeallocM->getCompoundBody(), Ctx, pass.ARCMTMacroLoc=
s)) {
+        Transaction Trans(TA);
+        TA.remove(DeallocM->getSourceRange());
+      }
+
+      if (FinalizeM) {
+        Transaction Trans(TA);
+        TA.remove(FinalizeM->getSourceRange());
+      }
+
+    } else if (FinalizeM) {
+      if (isBodyEmpty(FinalizeM->getCompoundBody(), Ctx, pass.ARCMTMacroLo=
cs)) {
+        Transaction Trans(TA);
+        TA.remove(FinalizeM->getSourceRange());
+      } else {
+        Transaction Trans(TA);
+        TA.replaceText(FinalizeM->getSelectorStartLoc(), "finalize", "deal=
loc");
       }
     }
   }
 }
=20
-void trans::removeEmptyStatementsAndDealloc(MigrationPass &pass) {
+void trans::removeEmptyStatementsAndDeallocFinalize(MigrationPass &pass) {
   EmptyStatementsRemover(pass).TraverseDecl(pass.Ctx.getTranslationUnitDec=
l());
=20
-  removeDeallocMethod(pass);
+  cleanupDeallocOrFinalize(pass);
=20
   for (unsigned i =3D 0, e =3D pass.ARCMTMacroLocs.size(); i !=3D e; ++i) {
     Transaction Trans(pass.TA);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransProperties.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransProperties.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransProperties.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -44,8 +44,17 @@
 namespace {
=20
 class PropertiesRewriter {
+  MigrationContext &MigrateCtx;
   MigrationPass &Pass;
   ObjCImplementationDecl *CurImplD;
+ =20
+  enum PropActionKind {
+    PropAction_None,
+    PropAction_RetainReplacedWithStrong,
+    PropAction_AssignRemoved,
+    PropAction_AssignRewritten,
+    PropAction_MaybeAddWeakOrUnsafe
+  };
=20
   struct PropData {
     ObjCPropertyDecl *PropD;
@@ -58,9 +67,27 @@
   typedef SmallVector<PropData, 2> PropsTy;
   typedef std::map<unsigned, PropsTy> AtPropDeclsTy;
   AtPropDeclsTy AtProps;
+  llvm::DenseMap<IdentifierInfo *, PropActionKind> ActionOnProp;
=20
 public:
-  PropertiesRewriter(MigrationPass &pass) : Pass(pass) { }
+  explicit PropertiesRewriter(MigrationContext &MigrateCtx)
+    : MigrateCtx(MigrateCtx), Pass(MigrateCtx.Pass) { }
+
+  static void collectProperties(ObjCContainerDecl *D, AtPropDeclsTy &AtPro=
ps,
+                                AtPropDeclsTy *PrevAtProps =3D 0) {
+    for (ObjCInterfaceDecl::prop_iterator
+           propI =3D D->prop_begin(),
+           propE =3D D->prop_end(); propI !=3D propE; ++propI) {
+      if (propI->getAtLoc().isInvalid())
+        continue;
+      unsigned RawLoc =3D propI->getAtLoc().getRawEncoding();
+      if (PrevAtProps)
+        if (PrevAtProps->find(RawLoc) !=3D PrevAtProps->end())
+          continue;
+      PropsTy &props =3D AtProps[RawLoc];
+      props.push_back(*propI);
+    }
+  }
=20
   void doTransform(ObjCImplementationDecl *D) {
     CurImplD =3D D;
@@ -68,14 +95,7 @@
     if (!iface)
       return;
=20
-    for (ObjCInterfaceDecl::prop_iterator
-           propI =3D iface->prop_begin(),
-           propE =3D iface->prop_end(); propI !=3D propE; ++propI) {
-      if (propI->getAtLoc().isInvalid())
-        continue;
-      PropsTy &props =3D AtProps[propI->getAtLoc().getRawEncoding()];
-      props.push_back(*propI);
-    }
+    collectProperties(iface, AtProps);
=20
     typedef DeclContext::specific_decl_iterator<ObjCPropertyImplDecl>
         prop_impl_iterator;
@@ -110,19 +130,66 @@
            I =3D AtProps.begin(), E =3D AtProps.end(); I !=3D E; ++I) {
       SourceLocation atLoc =3D SourceLocation::getFromRawEncoding(I->first=
);
       PropsTy &props =3D I->second;
-      QualType ty =3D getPropertyType(props);
-      if (!ty->isObjCRetainableType())
+      if (!getPropertyType(props)->isObjCRetainableType())
         continue;
-      if (hasIvarWithExplicitOwnership(props))
+      if (hasIvarWithExplicitARCOwnership(props))
         continue;
      =20
       Transaction Trans(Pass.TA);
       rewriteProperty(props, atLoc);
     }
+
+    AtPropDeclsTy AtExtProps;
+    // Look through extensions.
+    for (ObjCCategoryDecl *Cat =3D iface->getCategoryList();
+           Cat; Cat =3D Cat->getNextClassCategory())
+      if (Cat->IsClassExtension())
+        collectProperties(Cat, AtExtProps, &AtProps);
+
+    for (AtPropDeclsTy::iterator
+           I =3D AtExtProps.begin(), E =3D AtExtProps.end(); I !=3D E; ++I=
) {
+      SourceLocation atLoc =3D SourceLocation::getFromRawEncoding(I->first=
);
+      PropsTy &props =3D I->second;
+      Transaction Trans(Pass.TA);
+      doActionForExtensionProp(props, atLoc);
+    }
   }
=20
 private:
-  void rewriteProperty(PropsTy &props, SourceLocation atLoc) const {
+  void doPropAction(PropActionKind kind,
+                    PropsTy &props, SourceLocation atLoc,
+                    bool markAction =3D true) {
+    if (markAction)
+      for (PropsTy::iterator I =3D props.begin(), E =3D props.end(); I !=
=3D E; ++I)
+        ActionOnProp[I->PropD->getIdentifier()] =3D kind;
+
+    switch (kind) {
+    case PropAction_None:
+      return;
+    case PropAction_RetainReplacedWithStrong: {
+      StringRef toAttr =3D "strong";
+      MigrateCtx.rewritePropertyAttribute("retain", toAttr, atLoc);
+      return;
+    }
+    case PropAction_AssignRemoved:
+      return removeAssignForDefaultStrong(props, atLoc);
+    case PropAction_AssignRewritten:
+      return rewriteAssign(props, atLoc);
+    case PropAction_MaybeAddWeakOrUnsafe:
+      return maybeAddWeakOrUnsafeUnretainedAttr(props, atLoc);
+    }
+  }
+
+  void doActionForExtensionProp(PropsTy &props, SourceLocation atLoc) {
+    llvm::DenseMap<IdentifierInfo *, PropActionKind>::iterator I;
+    I =3D ActionOnProp.find(props[0].PropD->getIdentifier());
+    if (I =3D=3D ActionOnProp.end())
+      return;
+
+    doPropAction(I->second, props, atLoc, false);
+  }
+
+  void rewriteProperty(PropsTy &props, SourceLocation atLoc) {
     ObjCPropertyDecl::PropertyAttributeKind propAttrs =3D getPropertyAttrs=
(props);
    =20
     if (propAttrs & (ObjCPropertyDecl::OBJC_PR_copy |
@@ -132,37 +199,59 @@
       return;
=20
     if (propAttrs & ObjCPropertyDecl::OBJC_PR_retain) {
-      rewriteAttribute("retain", "strong", atLoc);
-      return;
+      // strong is the default.
+      return doPropAction(PropAction_RetainReplacedWithStrong, props, atLo=
c);
     }
=20
+    bool HasIvarAssignedAPlusOneObject =3D hasIvarAssignedAPlusOneObject(p=
rops);
+
     if (propAttrs & ObjCPropertyDecl::OBJC_PR_assign) {
-      if (hasIvarAssignedAPlusOneObject(props)) {
-        rewriteAttribute("assign", "strong", atLoc);
-        return;
-      }
-      return rewriteAssign(props, atLoc);
+      if (HasIvarAssignedAPlusOneObject)
+        return doPropAction(PropAction_AssignRemoved, props, atLoc);
+      return doPropAction(PropAction_AssignRewritten, props, atLoc);
     }
=20
-    if (hasIvarAssignedAPlusOneObject(props))
-      return maybeAddStrongAttr(props, atLoc);
+    if (HasIvarAssignedAPlusOneObject ||
+        (Pass.isGCMigration() && !hasGCWeak(props, atLoc)))
+      return; // 'strong' by default.
=20
-    return maybeAddWeakOrUnsafeUnretainedAttr(props, atLoc);
+    return doPropAction(PropAction_MaybeAddWeakOrUnsafe, props, atLoc);
+  }
+
+  void removeAssignForDefaultStrong(PropsTy &props,
+                                    SourceLocation atLoc) const {
+    removeAttribute("retain", atLoc);
+    if (!removeAttribute("assign", atLoc))
+      return;
+
+    for (PropsTy::iterator I =3D props.begin(), E =3D props.end(); I !=3D =
E; ++I) {
+      if (I->ImplD)
+        Pass.TA.clearDiagnostic(diag::err_arc_assign_property_ownership,
+                                I->ImplD->getLocation());
+    }
   }
=20
   void rewriteAssign(PropsTy &props, SourceLocation atLoc) const {
-    bool canUseWeak =3D canApplyWeak(Pass.Ctx, getPropertyType(props));
+    bool canUseWeak =3D canApplyWeak(Pass.Ctx, getPropertyType(props),
+                                  /*AllowOnUnknownClass=3D*/Pass.isGCMigra=
tion());
+    const char *toWhich =3D=20
+      (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "strong" :
+      (canUseWeak ? "weak" : "unsafe_unretained");
=20
-    bool rewroteAttr =3D rewriteAttribute("assign",
-                                     canUseWeak ? "weak" : "unsafe_unretai=
ned",
-                                         atLoc);
+    bool rewroteAttr =3D rewriteAttribute("assign", toWhich, atLoc);
     if (!rewroteAttr)
       canUseWeak =3D false;
=20
     for (PropsTy::iterator I =3D props.begin(), E =3D props.end(); I !=3D =
E; ++I) {
-      if (isUserDeclared(I->IvarD))
-        Pass.TA.insert(I->IvarD->getLocation(),
-                       canUseWeak ? "__weak " : "__unsafe_unretained ");
+      if (isUserDeclared(I->IvarD)) {
+        if (I->IvarD &&
+            I->IvarD->getType().getObjCLifetime() !=3D Qualifiers::OCL_Wea=
k) {
+          const char *toWhich =3D=20
+            (Pass.isGCMigration() && !hasGCWeak(props, atLoc)) ? "__strong=
 " :
+              (canUseWeak ? "__weak " : "__unsafe_unretained ");
+          Pass.TA.insert(I->IvarD->getLocation(), toWhich);
+        }
+      }
       if (I->ImplD)
         Pass.TA.clearDiagnostic(diag::err_arc_assign_property_ownership,
                                 I->ImplD->getLocation());
@@ -171,21 +260,21 @@
=20
   void maybeAddWeakOrUnsafeUnretainedAttr(PropsTy &props,
                                           SourceLocation atLoc) const {
-    ObjCPropertyDecl::PropertyAttributeKind propAttrs =3D getPropertyAttrs=
(props);
+    bool canUseWeak =3D canApplyWeak(Pass.Ctx, getPropertyType(props),
+                                  /*AllowOnUnknownClass=3D*/Pass.isGCMigra=
tion());
=20
-    bool canUseWeak =3D canApplyWeak(Pass.Ctx, getPropertyType(props));
-    if (!(propAttrs & ObjCPropertyDecl::OBJC_PR_readonly) ||
-        !hasAllIvarsBacked(props)) {
-      bool addedAttr =3D addAttribute(canUseWeak ? "weak" : "unsafe_unreta=
ined",
-                                    atLoc);
-      if (!addedAttr)
-        canUseWeak =3D false;
-    }
+    bool addedAttr =3D addAttribute(canUseWeak ? "weak" : "unsafe_unretain=
ed",
+                                  atLoc);
+    if (!addedAttr)
+      canUseWeak =3D false;
=20
     for (PropsTy::iterator I =3D props.begin(), E =3D props.end(); I !=3D =
E; ++I) {
-      if (isUserDeclared(I->IvarD))
-        Pass.TA.insert(I->IvarD->getLocation(),
-                       canUseWeak ? "__weak " : "__unsafe_unretained ");
+      if (isUserDeclared(I->IvarD)) {
+        if (I->IvarD &&
+            I->IvarD->getType().getObjCLifetime() !=3D Qualifiers::OCL_Wea=
k)
+          Pass.TA.insert(I->IvarD->getLocation(),
+                         canUseWeak ? "__weak " : "__unsafe_unretained ");
+      }
       if (I->ImplD) {
         Pass.TA.clearDiagnostic(diag::err_arc_assign_property_ownership,
                                 I->ImplD->getLocation());
@@ -196,127 +285,17 @@
     }
   }
=20
-  void maybeAddStrongAttr(PropsTy &props, SourceLocation atLoc) const {
-    ObjCPropertyDecl::PropertyAttributeKind propAttrs =3D getPropertyAttrs=
(props);
-
-    if (!(propAttrs & ObjCPropertyDecl::OBJC_PR_readonly) ||
-        !hasAllIvarsBacked(props)) {
-      addAttribute("strong", atLoc);
-    }
-
-    for (PropsTy::iterator I =3D props.begin(), E =3D props.end(); I !=3D =
E; ++I) {
-      if (I->ImplD) {
-        Pass.TA.clearDiagnostic(diag::err_arc_assign_property_ownership,
-                                I->ImplD->getLocation());
-        Pass.TA.clearDiagnostic(
-                           diag::err_arc_objc_property_default_assign_on_o=
bject,
-                           I->ImplD->getLocation());
-      }
-    }
+  bool removeAttribute(StringRef fromAttr, SourceLocation atLoc) const {
+    return MigrateCtx.removePropertyAttribute(fromAttr, atLoc);
   }
=20
   bool rewriteAttribute(StringRef fromAttr, StringRef toAttr,
                         SourceLocation atLoc) const {
-    if (atLoc.isMacroID())
-      return false;
-
-    SourceManager &SM =3D Pass.Ctx.getSourceManager();
-
-    // Break down the source location.
-    std::pair<FileID, unsigned> locInfo =3D SM.getDecomposedLoc(atLoc);
-
-    // Try to load the file buffer.
-    bool invalidTemp =3D false;
-    StringRef file =3D SM.getBufferData(locInfo.first, &invalidTemp);
-    if (invalidTemp)
-      return false;
-
-    const char *tokenBegin =3D file.data() + locInfo.second;
-
-    // Lex from the start of the given location.
-    Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
-                Pass.Ctx.getLangOptions(),
-                file.begin(), tokenBegin, file.end());
-    Token tok;
-    lexer.LexFromRawLexer(tok);
-    if (tok.isNot(tok::at)) return false;
-    lexer.LexFromRawLexer(tok);
-    if (tok.isNot(tok::raw_identifier)) return false;
-    if (StringRef(tok.getRawIdentifierData(), tok.getLength())
-          !=3D "property")
-      return false;
-    lexer.LexFromRawLexer(tok);
-    if (tok.isNot(tok::l_paren)) return false;
-   =20
-    lexer.LexFromRawLexer(tok);
-    if (tok.is(tok::r_paren))
-      return false;
-
-    while (1) {
-      if (tok.isNot(tok::raw_identifier)) return false;
-      StringRef ident(tok.getRawIdentifierData(), tok.getLength());
-      if (ident =3D=3D fromAttr) {
-        Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
-        return true;
-      }
-
-      do {
-        lexer.LexFromRawLexer(tok);
-      } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
-      if (tok.is(tok::r_paren))
-        break;
-      lexer.LexFromRawLexer(tok);
-    }
-
-    return false;
+    return MigrateCtx.rewritePropertyAttribute(fromAttr, toAttr, atLoc);
   }
=20
   bool addAttribute(StringRef attr, SourceLocation atLoc) const {
-    if (atLoc.isMacroID())
-      return false;
-
-    SourceManager &SM =3D Pass.Ctx.getSourceManager();
-
-    // Break down the source location.
-    std::pair<FileID, unsigned> locInfo =3D SM.getDecomposedLoc(atLoc);
-
-    // Try to load the file buffer.
-    bool invalidTemp =3D false;
-    StringRef file =3D SM.getBufferData(locInfo.first, &invalidTemp);
-    if (invalidTemp)
-      return false;
-
-    const char *tokenBegin =3D file.data() + locInfo.second;
-
-    // Lex from the start of the given location.
-    Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
-                Pass.Ctx.getLangOptions(),
-                file.begin(), tokenBegin, file.end());
-    Token tok;
-    lexer.LexFromRawLexer(tok);
-    if (tok.isNot(tok::at)) return false;
-    lexer.LexFromRawLexer(tok);
-    if (tok.isNot(tok::raw_identifier)) return false;
-    if (StringRef(tok.getRawIdentifierData(), tok.getLength())
-          !=3D "property")
-      return false;
-    lexer.LexFromRawLexer(tok);
-
-    if (tok.isNot(tok::l_paren)) {
-      Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ")=
 ");
-      return true;
-    }
-   =20
-    lexer.LexFromRawLexer(tok);
-    if (tok.is(tok::r_paren)) {
-      Pass.TA.insert(tok.getLocation(), attr);
-      return true;
-    }
-
-    if (tok.isNot(tok::raw_identifier)) return false;
-
-    Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
-    return true;
+    return MigrateCtx.addPropertyAttribute(attr, atLoc);
   }
=20
   class PlusOneAssign : public RecursiveASTVisitor<PlusOneAssign> {
@@ -358,7 +337,10 @@
     return false;
   }
=20
-  bool hasIvarWithExplicitOwnership(PropsTy &props) const {
+  bool hasIvarWithExplicitARCOwnership(PropsTy &props) const {
+    if (Pass.isGCMigration())
+      return false;
+
     for (PropsTy::iterator I =3D props.begin(), E =3D props.end(); I !=3D =
E; ++I) {
       if (isUserDeclared(I->IvarD)) {
         if (isa<AttributedType>(I->IvarD->getType()))
@@ -380,17 +362,26 @@
     return true;
   }
=20
+  // \brief Returns true if all declarations in the @property have GC __we=
ak.
+  bool hasGCWeak(PropsTy &props, SourceLocation atLoc) const {
+    if (!Pass.isGCMigration())
+      return false;
+    if (props.empty())
+      return false;
+    return MigrateCtx.AtPropsWeak.count(atLoc.getRawEncoding());
+  }
+
   bool isUserDeclared(ObjCIvarDecl *ivarD) const {
     return ivarD && !ivarD->getSynthesize();
   }
=20
   QualType getPropertyType(PropsTy &props) const {
     assert(!props.empty());
-    QualType ty =3D props[0].PropD->getType();
+    QualType ty =3D props[0].PropD->getType().getUnqualifiedType();
=20
 #ifndef NDEBUG
     for (PropsTy::iterator I =3D props.begin(), E =3D props.end(); I !=3D =
E; ++I)
-      assert(ty =3D=3D I->PropD->getType());
+      assert(ty =3D=3D I->PropD->getType().getUnqualifiedType());
 #endif
=20
     return ty;
@@ -411,21 +402,10 @@
   }
 };
=20
-class ImplementationChecker :
-                             public RecursiveASTVisitor<ImplementationChec=
ker> {
-  MigrationPass &Pass;
-
-public:
-  ImplementationChecker(MigrationPass &pass) : Pass(pass) { }
-
-  bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
-    PropertiesRewriter(Pass).doTransform(D);
-    return true;
-  }
-};
-
 } // anonymous namespace
=20
-void trans::rewriteProperties(MigrationPass &pass) {
-  ImplementationChecker(pass).TraverseDecl(pass.Ctx.getTranslationUnitDecl=
());
+void PropertyRewriteTraverser::traverseObjCImplementation(
+                                           ObjCImplementationContext &Impl=
Ctx) {
+  PropertiesRewriter(ImplCtx.getMigrationContext())
+                                  .doTransform(ImplCtx.getImplementationDe=
cl());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransRetainReleaseDealloc.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransRetainReleaseDeallo=
c.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransRetainReleaseDeallo=
c.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -21,6 +21,8 @@
 #include "Internals.h"
 #include "clang/Sema/SemaDiagnostic.h"
 #include "clang/AST/ParentMap.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Basic/SourceManager.h"
=20
 using namespace clang;
 using namespace arcmt;
@@ -34,15 +36,17 @@
   MigrationPass &Pass;
=20
   ExprSet Removables;
-  llvm::OwningPtr<ParentMap> StmtMap;
+  OwningPtr<ParentMap> StmtMap;
=20
-  Selector DelegateSel;
+  Selector DelegateSel, FinalizeSel;
=20
 public:
   RetainReleaseDeallocRemover(MigrationPass &pass)
     : Body(0), Pass(pass) {
     DelegateSel =3D
         Pass.Ctx.Selectors.getNullarySelector(&Pass.Ctx.Idents.get("delega=
te"));
+    FinalizeSel =3D
+        Pass.Ctx.Selectors.getNullarySelector(&Pass.Ctx.Idents.get("finali=
ze"));
   }
=20
   void transformBody(Stmt *body) {
@@ -55,6 +59,8 @@
   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
     switch (E->getMethodFamily()) {
     default:
+      if (E->isInstanceMessage() && E->getSelector() =3D=3D FinalizeSel)
+        break;
       return true;
     case OMF_autorelease:
       if (isRemovable(E)) {
@@ -124,27 +130,105 @@
     Transaction Trans(Pass.TA);
     clearDiagnostics(rec->getExprLoc());
=20
-    if (E->getMethodFamily() =3D=3D OMF_release &&
-        isRemovable(E) && isInAtFinally(E)) {
+    ObjCMessageExpr *Msg =3D E;
+    Expr *RecContainer =3D Msg;
+    SourceRange RecRange =3D rec->getSourceRange();
+    checkForGCDOrXPC(Msg, RecContainer, rec, RecRange);
+
+    if (Msg->getMethodFamily() =3D=3D OMF_release &&
+        isRemovable(RecContainer) && isInAtFinally(RecContainer)) {
       // Change the -release to "receiver =3D nil" in a finally to avoid a=
 leak
       // when an exception is thrown.
-      Pass.TA.replace(E->getSourceRange(), rec->getSourceRange());
+      Pass.TA.replace(RecContainer->getSourceRange(), RecRange);
       std::string str =3D " =3D ";
       str +=3D getNilString(Pass.Ctx);
-      Pass.TA.insertAfterToken(rec->getLocEnd(), str);
+      Pass.TA.insertAfterToken(RecRange.getEnd(), str);
       return true;
     }
=20
-    if (!hasSideEffects(E, Pass.Ctx)) {
-      if (tryRemoving(E))
+    if (!hasSideEffects(rec, Pass.Ctx)) {
+      if (tryRemoving(RecContainer))
         return true;
     }
-    Pass.TA.replace(E->getSourceRange(), rec->getSourceRange());
+    Pass.TA.replace(RecContainer->getSourceRange(), RecRange);
=20
     return true;
   }
=20
 private:
+  /// \brief Check if the retain/release is due to a GCD/XPC macro that are
+  /// defined as:
+  ///
+  /// #define dispatch_retain(object) ({ dispatch_object_t _o =3D (object)=
; _dispatch_object_validate(_o); (void)[_o retain]; })
+  /// #define dispatch_release(object) ({ dispatch_object_t _o =3D (object=
); _dispatch_object_validate(_o); [_o release]; })
+  /// #define xpc_retain(object) ({ xpc_object_t _o =3D (object); _xpc_obj=
ect_validate(_o); [_o retain]; })
+  /// #define xpc_release(object) ({ xpc_object_t _o =3D (object); _xpc_ob=
ject_validate(_o); [_o release]; })
+  ///
+  /// and return the top container which is the StmtExpr and the macro arg=
ument
+  /// expression.
+  void checkForGCDOrXPC(ObjCMessageExpr *Msg, Expr *&RecContainer,
+                        Expr *&Rec, SourceRange &RecRange) {
+    SourceLocation Loc =3D Msg->getExprLoc();
+    if (!Loc.isMacroID())
+      return;
+    SourceManager &SM =3D Pass.Ctx.getSourceManager();
+    StringRef MacroName =3D Lexer::getImmediateMacroName(Loc, SM,
+                                                     Pass.Ctx.getLangOpts(=
));
+    bool isGCDOrXPC =3D llvm::StringSwitch<bool>(MacroName)
+        .Case("dispatch_retain", true)
+        .Case("dispatch_release", true)
+        .Case("xpc_retain", true)
+        .Case("xpc_release", true)
+        .Default(false);
+    if (!isGCDOrXPC)
+      return;
+
+    StmtExpr *StmtE =3D 0;
+    Stmt *S =3D Msg;
+    while (S) {
+      if (StmtExpr *SE =3D dyn_cast<StmtExpr>(S)) {
+        StmtE =3D SE;
+        break;
+      }
+      S =3D StmtMap->getParent(S);
+    }
+
+    if (!StmtE)
+      return;
+
+    Stmt::child_range StmtExprChild =3D StmtE->children();
+    if (!StmtExprChild)
+      return;
+    CompoundStmt *CompS =3D dyn_cast_or_null<CompoundStmt>(*StmtExprChild);
+    if (!CompS)
+      return;
+
+    Stmt::child_range CompStmtChild =3D CompS->children();
+    if (!CompStmtChild)
+      return;
+    DeclStmt *DeclS =3D dyn_cast_or_null<DeclStmt>(*CompStmtChild);
+    if (!DeclS)
+      return;
+    if (!DeclS->isSingleDecl())
+      return;
+    VarDecl *VD =3D dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl());
+    if (!VD)
+      return;
+    Expr *Init =3D VD->getInit();
+    if (!Init)
+      return;
+
+    RecContainer =3D StmtE;
+    Rec =3D Init->IgnoreParenImpCasts();
+    if (ExprWithCleanups *EWC =3D dyn_cast<ExprWithCleanups>(Rec))
+      Rec =3D EWC->getSubExpr()->IgnoreParenImpCasts();
+    RecRange =3D Rec->getSourceRange();
+    if (SM.isMacroArgExpansion(RecRange.getBegin()))
+      RecRange.setBegin(SM.getImmediateSpellingLoc(RecRange.getBegin()));
+    if (SM.isMacroArgExpansion(RecRange.getEnd()))
+      RecRange.setEnd(SM.getImmediateSpellingLoc(RecRange.getEnd()));
+  }
+
   void clearDiagnostics(SourceLocation loc) const {
     Pass.TA.clearDiagnostic(diag::err_arc_illegal_explicit_message,
                             diag::err_unavailable,
@@ -156,12 +240,14 @@
     if (!E) return false;
=20
     E =3D E->IgnoreParenCasts();
+
+    // Also look through property-getter sugar.
+    if (PseudoObjectExpr *pseudoOp =3D dyn_cast<PseudoObjectExpr>(E))
+      E =3D pseudoOp->getResultExpr()->IgnoreImplicit();
+
     if (ObjCMessageExpr *ME =3D dyn_cast<ObjCMessageExpr>(E))
       return (ME->isInstanceMessage() && ME->getSelector() =3D=3D Delegate=
Sel);
=20
-    if (ObjCPropertyRefExpr *propE =3D dyn_cast<ObjCPropertyRefExpr>(E))
-      return propE->getGetterSelector() =3D=3D DelegateSel;
-
     return false;
   }
=20
@@ -211,7 +297,7 @@
=20
 } // anonymous namespace
=20
-void trans::removeRetainReleaseDealloc(MigrationPass &pass) {
+void trans::removeRetainReleaseDeallocFinalize(MigrationPass &pass) {
   BodyTransform<RetainReleaseDeallocRemover> trans(pass);
   trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransUnbridgedCasts.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransUnbridgedCasts.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -38,6 +38,7 @@
 #include "clang/Sema/SemaDiagnostic.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/Basic/SourceManager.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace arcmt;
@@ -48,7 +49,7 @@
 class UnbridgedCastRewriter : public RecursiveASTVisitor<UnbridgedCastRewr=
iter>{
   MigrationPass &Pass;
   IdentifierInfo *SelfII;
-  llvm::OwningPtr<ParentMap> StmtMap;
+  OwningPtr<ParentMap> StmtMap;
=20
 public:
   UnbridgedCastRewriter(MigrationPass &pass) : Pass(pass) {
@@ -128,6 +129,21 @@
           if (fname.endswith("Retain") ||
               fname.find("Create") !=3D StringRef::npos ||
               fname.find("Copy") !=3D StringRef::npos) {
+            // Do not migrate to couple of bridge transfer casts which
+            // cancel each other out. Leave it unchanged so error gets user
+            // attention instead.
+            if (FD->getName() =3D=3D "CFRetain" &&=20
+                FD->getNumParams() =3D=3D 1 &&
+                FD->getParent()->isTranslationUnit() &&
+                FD->getLinkage() =3D=3D ExternalLinkage) {
+              Expr *Arg =3D callE->getArg(0);
+              if (const ImplicitCastExpr *ICE =3D dyn_cast<ImplicitCastExp=
r>(Arg)) {
+                const Expr *sub =3D ICE->getSubExpr();
+                QualType T =3D sub->getType();
+                if (T->isObjCObjectPointerType())
+                  return;
+              }
+            }
             castToObjCObject(E, /*retained=3D*/true);
             return;
           }
@@ -179,7 +195,7 @@
       TA.insertAfterToken(CCE->getLParenLoc(), bridge);
     } else {
       SourceLocation insertLoc =3D E->getSubExpr()->getLocStart();
-      llvm::SmallString<128> newCast;
+      SmallString<128> newCast;
       newCast +=3D '(';
       newCast +=3D bridge;
       newCast +=3D E->getType().getAsString(Pass.Ctx.getPrintingPolicy());
@@ -236,7 +252,15 @@
       }
     }
=20
-    if (ImplicitCastExpr *implCE =3D dyn_cast<ImplicitCastExpr>(E->getSubE=
xpr())){
+    Expr *subExpr =3D E->getSubExpr();
+
+    // Look through pseudo-object expressions.
+    if (PseudoObjectExpr *pseudo =3D dyn_cast<PseudoObjectExpr>(subExpr)) {
+      subExpr =3D pseudo->getResultExpr();
+      assert(subExpr && "no result for pseudo-object of non-void type?");
+    }
+
+    if (ImplicitCastExpr *implCE =3D dyn_cast<ImplicitCastExpr>(subExpr)) {
       if (implCE->getCastKind() =3D=3D CK_ARCConsumeObject)
         return rewriteToBridgedCast(E, OBC_BridgeRetained);
       if (implCE->getCastKind() =3D=3D CK_ARCReclaimReturnedObject)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransUnusedInitDelegate.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransUnusedInitDelegate.=
cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransUnusedInitDelegate.=
cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -54,7 +54,11 @@
       Transaction Trans(Pass.TA);
       Pass.TA.clearDiagnostic(diag::err_arc_unused_init_message,
                               ME->getExprLoc());
-      Pass.TA.insert(ME->getExprLoc(), "self =3D ");
+      SourceRange ExprRange =3D ME->getSourceRange();
+      Pass.TA.insert(ExprRange.getBegin(), "if (!(self =3D ");
+      std::string retStr =3D ")) return ";
+      retStr +=3D getNilString(Pass.Ctx);
+      Pass.TA.insertAfterToken(ExprRange.getEnd(), retStr);
     }
     return true;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransZeroOutPropsInDealloc.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransZeroOutPropsInDeall=
oc.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransZeroOutPropsInDeall=
oc.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -31,9 +31,13 @@
   llvm::DenseMap<ObjCPropertyDecl*, ObjCPropertyImplDecl*> SynthesizedProp=
erties;
   ImplicitParamDecl *SelfD;
   ExprSet Removables;
+  Selector FinalizeSel;
=20
 public:
-  ZeroOutInDeallocRemover(MigrationPass &pass) : Pass(pass), SelfD(0) { }
+  ZeroOutInDeallocRemover(MigrationPass &pass) : Pass(pass), SelfD(0) {
+    FinalizeSel =3D
+        Pass.Ctx.Selectors.getNullarySelector(&Pass.Ctx.Idents.get("finali=
ze"));
+  }
=20
   bool VisitObjCMessageExpr(ObjCMessageExpr *ME) {
     ASTContext &Ctx =3D Pass.Ctx;
@@ -74,6 +78,15 @@
     return true;
   }
=20
+  bool VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
+    if (isZeroingPropIvar(POE) && isRemovable(POE)) {
+      Transaction Trans(Pass.TA);
+      Pass.TA.removeStmt(POE);
+    }
+
+    return true;
+  }
+
   bool VisitBinaryOperator(BinaryOperator *BOE) {
     if (isZeroingPropIvar(BOE) && isRemovable(BOE)) {
       Transaction Trans(Pass.TA);
@@ -84,7 +97,8 @@
   }
=20
   bool TraverseObjCMethodDecl(ObjCMethodDecl *D) {
-    if (D->getMethodFamily() !=3D OMF_dealloc)
+    if (D->getMethodFamily() !=3D OMF_dealloc &&
+        !(D->isInstanceMethod() && D->getSelector() =3D=3D FinalizeSel))
       return true;
     if (!D->hasBody())
       return true;
@@ -137,17 +151,21 @@
   }
=20
   bool isZeroingPropIvar(Expr *E) {
-    BinaryOperator *BOE =3D dyn_cast_or_null<BinaryOperator>(E);
-    if (!BOE) return false;
+    E =3D E->IgnoreParens();
+    if (BinaryOperator *BO =3D dyn_cast<BinaryOperator>(E))
+      return isZeroingPropIvar(BO);
+    if (PseudoObjectExpr *PO =3D dyn_cast<PseudoObjectExpr>(E))
+      return isZeroingPropIvar(PO);
+    return false;
+  }
=20
+  bool isZeroingPropIvar(BinaryOperator *BOE) {
     if (BOE->getOpcode() =3D=3D BO_Comma)
       return isZeroingPropIvar(BOE->getLHS()) &&
              isZeroingPropIvar(BOE->getRHS());
=20
     if (BOE->getOpcode() !=3D BO_Assign)
-        return false;
-
-    ASTContext &Ctx =3D Pass.Ctx;
+      return false;
=20
     Expr *LHS =3D BOE->getLHS();
     if (ObjCIvarRefExpr *IV =3D dyn_cast<ObjCIvarRefExpr>(LHS)) {
@@ -167,31 +185,44 @@
       if (!IvarBacksPropertySynthesis)
         return false;
     }
-    else if (ObjCPropertyRefExpr *PropRefExp =3D dyn_cast<ObjCPropertyRefE=
xpr>(LHS)) {
-      // TODO: Using implicit property decl.
-      if (PropRefExp->isImplicitProperty())
-        return false;
-      if (ObjCPropertyDecl *PDecl =3D PropRefExp->getExplicitProperty()) {
-        if (!SynthesizedProperties.count(PDecl))
-          return false;
-      }
-    }
     else
         return false;
=20
-    Expr *RHS =3D BOE->getRHS();
-    bool RHSIsNull =3D RHS->isNullPointerConstant(Ctx,
-                                                Expr::NPC_ValueDependentIs=
Null);
-    if (RHSIsNull)
+    return isZero(BOE->getRHS());
+  }
+
+  bool isZeroingPropIvar(PseudoObjectExpr *PO) {
+    BinaryOperator *BO =3D dyn_cast<BinaryOperator>(PO->getSyntacticForm()=
);
+    if (!BO) return false;
+    if (BO->getOpcode() !=3D BO_Assign) return false;
+
+    ObjCPropertyRefExpr *PropRefExp =3D
+      dyn_cast<ObjCPropertyRefExpr>(BO->getLHS()->IgnoreParens());
+    if (!PropRefExp) return false;
+
+    // TODO: Using implicit property decl.
+    if (PropRefExp->isImplicitProperty())
+      return false;
+
+    if (ObjCPropertyDecl *PDecl =3D PropRefExp->getExplicitProperty()) {
+      if (!SynthesizedProperties.count(PDecl))
+        return false;
+    }
+
+    return isZero(cast<OpaqueValueExpr>(BO->getRHS())->getSourceExpr());
+  }
+
+  bool isZero(Expr *E) {
+    if (E->isNullPointerConstant(Pass.Ctx, Expr::NPC_ValueDependentIsNull))
       return true;
=20
-    return isZeroingPropIvar(RHS);
+    return isZeroingPropIvar(E);
   }
 };
=20
 } // anonymous namespace
=20
-void trans::removeZeroOutPropsInDealloc(MigrationPass &pass) {
+void trans::removeZeroOutPropsInDeallocFinalize(MigrationPass &pass) {
   ZeroOutInDeallocRemover trans(pass);
   trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/TransformActions.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransformActions.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/TransformActions.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -122,6 +122,8 @@
                        ASTContext &ctx, Preprocessor &PP)
     : CapturedDiags(capturedDiags), Ctx(ctx), PP(PP), IsInTransaction(fals=
e) { }
=20
+  ASTContext &getASTContext() { return Ctx; }
+
   void startTransaction();
   bool commitTransaction();
   void abortTransaction();
@@ -674,6 +676,12 @@
                                    SourceRange range) {
   assert(!static_cast<TransformActionsImpl*>(Impl)->isInTransaction() &&
          "Errors should be emitted out of a transaction");
+
+  SourceManager &SM =3D static_cast<TransformActionsImpl*>(Impl)->
+                                             getASTContext().getSourceMana=
ger();
+  if (SM.isInSystemHeader(SM.getExpansionLoc(loc)))
+    return;
+
   // FIXME: Use a custom category name to distinguish rewriter errors.
   std::string rewriteErr =3D "[rewriter] ";
   rewriteErr +=3D error;
@@ -684,10 +692,35 @@
   ReportedErrors =3D true;
 }
=20
+void TransformActions::reportWarning(StringRef warning, SourceLocation loc,
+                                   SourceRange range) {
+  assert(!static_cast<TransformActionsImpl*>(Impl)->isInTransaction() &&
+         "Warning should be emitted out of a transaction");
+ =20
+  SourceManager &SM =3D static_cast<TransformActionsImpl*>(Impl)->
+    getASTContext().getSourceManager();
+  if (SM.isInSystemHeader(SM.getExpansionLoc(loc)))
+    return;
+ =20
+  // FIXME: Use a custom category name to distinguish rewriter errors.
+  std::string rewriterWarn =3D "[rewriter] ";
+  rewriterWarn +=3D warning;
+  unsigned diagID
+  =3D Diags.getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Warning,
+                                              rewriterWarn);
+  Diags.Report(loc, diagID) << range;
+}
+
 void TransformActions::reportNote(StringRef note, SourceLocation loc,
                                   SourceRange range) {
   assert(!static_cast<TransformActionsImpl*>(Impl)->isInTransaction() &&
          "Errors should be emitted out of a transaction");
+
+  SourceManager &SM =3D static_cast<TransformActionsImpl*>(Impl)->
+                                             getASTContext().getSourceMana=
ger();
+  if (SM.isInSystemHeader(SM.getExpansionLoc(loc)))
+    return;
+
   // FIXME: Use a custom category name to distinguish rewriter errors.
   std::string rewriteNote =3D "[rewriter] ";
   rewriteNote +=3D note;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/Transforms.cpp
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/Transforms.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/Transforms.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -12,8 +12,6 @@
 #include "clang/Sema/SemaDiagnostic.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
-#include "clang/AST/ParentMap.h"
-#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/StringSwitch.h"
@@ -24,62 +22,35 @@
 using namespace arcmt;
 using namespace trans;
=20
+ASTTraverser::~ASTTraverser() { }
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Helpers.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-/// \brief True if the class is one that does not support weak.
-static bool isClassInWeakBlacklist(ObjCInterfaceDecl *cls) {
-  if (!cls)
-    return false;
-
-  bool inList =3D llvm::StringSwitch<bool>(cls->getName())
-                 .Case("NSColorSpace", true)
-                 .Case("NSFont", true)
-                 .Case("NSFontPanel", true)
-                 .Case("NSImage", true)
-                 .Case("NSLazyBrowserCell", true)
-                 .Case("NSWindow", true)
-                 .Case("NSWindowController", true)
-                 .Case("NSMenuView", true)
-                 .Case("NSPersistentUIWindowInfo", true)
-                 .Case("NSTableCellView", true)
-                 .Case("NSATSTypeSetter", true)
-                 .Case("NSATSGlyphStorage", true)
-                 .Case("NSLineFragmentRenderingContext", true)
-                 .Case("NSAttributeDictionary", true)
-                 .Case("NSParagraphStyle", true)
-                 .Case("NSTextTab", true)
-                 .Case("NSSimpleHorizontalTypesetter", true)
-                 .Case("_NSCachedAttributedString", true)
-                 .Case("NSStringDrawingTextStorage", true)
-                 .Case("NSTextView", true)
-                 .Case("NSSubTextStorage", true)
-                 .Default(false);
-
-  if (inList)
-    return true;
-
-  return isClassInWeakBlacklist(cls->getSuperClass());
-}
-
-bool trans::canApplyWeak(ASTContext &Ctx, QualType type) {
-  if (!Ctx.getLangOptions().ObjCRuntimeHasWeak)
+bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
+                         bool AllowOnUnknownClass) {
+  if (!Ctx.getLangOpts().ObjCRuntimeHasWeak)
     return false;
=20
   QualType T =3D type;
+  if (T.isNull())
+    return false;
+
+  // iOS is always safe to use 'weak'.
+  if (Ctx.getTargetInfo().getTriple().getOS() =3D=3D llvm::Triple::IOS)
+    AllowOnUnknownClass =3D true;
+
   while (const PointerType *ptr =3D T->getAs<PointerType>())
     T =3D ptr->getPointeeType();
   if (const ObjCObjectPointerType *ObjT =3D T->getAs<ObjCObjectPointerType=
>()) {
     ObjCInterfaceDecl *Class =3D ObjT->getInterfaceDecl();
-    if (!Class || Class->getName() =3D=3D "NSObject")
+    if (!AllowOnUnknownClass && (!Class || Class->getName() =3D=3D "NSObje=
ct"))
       return false; // id/NSObject is not safe for weak.
-    if (Class->isForwardDecl())
+    if (!AllowOnUnknownClass && !Class->hasDefinition())
       return false; // forward classes are not verifiable, therefore not s=
afe.
     if (Class->isArcWeakrefUnavailable())
       return false;
-    if (isClassInWeakBlacklist(Class))
-      return false;
   }
=20
   return true;
@@ -105,11 +76,10 @@
                                             ASTContext &Ctx) {
   SourceManager &SM =3D Ctx.getSourceManager();
   if (loc.isMacroID()) {
-    if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOptions()))
+    if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
       return SourceLocation();
-    loc =3D SM.getExpansionRange(loc).second;
   }
-  loc =3D Lexer::getLocForEndOfToken(loc, /*Offset=3D*/0, SM, Ctx.getLangO=
ptions());
+  loc =3D Lexer::getLocForEndOfToken(loc, /*Offset=3D*/0, SM, Ctx.getLangO=
pts());
=20
   // Break down the source location.
   std::pair<FileID, unsigned> locInfo =3D SM.getDecomposedLoc(loc);
@@ -124,7 +94,7 @@
=20
   // Lex from the start of the given location.
   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
-              Ctx.getLangOptions(),
+              Ctx.getLangOpts(),
               file.begin(), tokenBegin, file.end());
   Token tok;
   lexer.LexFromRawLexer(tok);
@@ -189,7 +159,6 @@
 public:
   ReferenceClear(ExprSet &refs) : Refs(refs) { }
   bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
-  bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { Refs.erase(E); return =
true; }
 };
=20
 class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
@@ -205,12 +174,6 @@
       Refs.insert(E);
     return true;
   }
-
-  bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
-    if (E->getDecl() =3D=3D Dcl)
-      Refs.insert(E);
-    return true;
-  }
 };
=20
 class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector=
> {
@@ -290,27 +253,290 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// MigrationContext
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+
+class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
+  MigrationContext &MigrateCtx;
+  typedef RecursiveASTVisitor<ASTTransform> base;
+
+public:
+  ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
+
+  bool shouldWalkTypesOfTypeLocs() const { return false; }
+
+  bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
+    ObjCImplementationContext ImplCtx(MigrateCtx, D);
+    for (MigrationContext::traverser_iterator
+           I =3D MigrateCtx.traversers_begin(),
+           E =3D MigrateCtx.traversers_end(); I !=3D E; ++I)
+      (*I)->traverseObjCImplementation(ImplCtx);
+
+    return base::TraverseObjCImplementationDecl(D);
+  }
+
+  bool TraverseStmt(Stmt *rootS) {
+    if (!rootS)
+      return true;
+
+    BodyContext BodyCtx(MigrateCtx, rootS);
+    for (MigrationContext::traverser_iterator
+           I =3D MigrateCtx.traversers_begin(),
+           E =3D MigrateCtx.traversers_end(); I !=3D E; ++I)
+      (*I)->traverseBody(BodyCtx);
+
+    return true;
+  }
+};
+
+}
+
+MigrationContext::~MigrationContext() {
+  for (traverser_iterator
+         I =3D traversers_begin(), E =3D traversers_end(); I !=3D E; ++I)
+    delete *I;
+}
+
+bool MigrationContext::isGCOwnedNonObjC(QualType T) {
+  while (!T.isNull()) {
+    if (const AttributedType *AttrT =3D T->getAs<AttributedType>()) {
+      if (AttrT->getAttrKind() =3D=3D AttributedType::attr_objc_ownership)
+        return !AttrT->getModifiedType()->isObjCRetainableType();
+    }
+
+    if (T->isArrayType())
+      T =3D Pass.Ctx.getBaseElementType(T);
+    else if (const PointerType *PT =3D T->getAs<PointerType>())
+      T =3D PT->getPointeeType();
+    else if (const ReferenceType *RT =3D T->getAs<ReferenceType>())
+      T =3D RT->getPointeeType();
+    else
+      break;
+  }
+
+  return false;
+}
+
+bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
+                                                StringRef toAttr,
+                                                SourceLocation atLoc) {
+  if (atLoc.isMacroID())
+    return false;
+
+  SourceManager &SM =3D Pass.Ctx.getSourceManager();
+
+  // Break down the source location.
+  std::pair<FileID, unsigned> locInfo =3D SM.getDecomposedLoc(atLoc);
+
+  // Try to load the file buffer.
+  bool invalidTemp =3D false;
+  StringRef file =3D SM.getBufferData(locInfo.first, &invalidTemp);
+  if (invalidTemp)
+    return false;
+
+  const char *tokenBegin =3D file.data() + locInfo.second;
+
+  // Lex from the start of the given location.
+  Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
+              Pass.Ctx.getLangOpts(),
+              file.begin(), tokenBegin, file.end());
+  Token tok;
+  lexer.LexFromRawLexer(tok);
+  if (tok.isNot(tok::at)) return false;
+  lexer.LexFromRawLexer(tok);
+  if (tok.isNot(tok::raw_identifier)) return false;
+  if (StringRef(tok.getRawIdentifierData(), tok.getLength())
+        !=3D "property")
+    return false;
+  lexer.LexFromRawLexer(tok);
+  if (tok.isNot(tok::l_paren)) return false;
+ =20
+  Token BeforeTok =3D tok;
+  Token AfterTok;
+  AfterTok.startToken();
+  SourceLocation AttrLoc;
+ =20
+  lexer.LexFromRawLexer(tok);
+  if (tok.is(tok::r_paren))
+    return false;
+
+  while (1) {
+    if (tok.isNot(tok::raw_identifier)) return false;
+    StringRef ident(tok.getRawIdentifierData(), tok.getLength());
+    if (ident =3D=3D fromAttr) {
+      if (!toAttr.empty()) {
+        Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
+        return true;
+      }
+      // We want to remove the attribute.
+      AttrLoc =3D tok.getLocation();
+    }
+
+    do {
+      lexer.LexFromRawLexer(tok);
+      if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
+        AfterTok =3D tok;
+    } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
+    if (tok.is(tok::r_paren))
+      break;
+    if (AttrLoc.isInvalid())
+      BeforeTok =3D tok;
+    lexer.LexFromRawLexer(tok);
+  }
+
+  if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown))=
 {
+    // We want to remove the attribute.
+    if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
+      Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
+                                 AfterTok.getLocation()));
+    } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
+      Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
+    } else {
+      Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
+    }
+
+    return true;
+  }
+ =20
+  return false;
+}
+
+bool MigrationContext::addPropertyAttribute(StringRef attr,
+                                            SourceLocation atLoc) {
+  if (atLoc.isMacroID())
+    return false;
+
+  SourceManager &SM =3D Pass.Ctx.getSourceManager();
+
+  // Break down the source location.
+  std::pair<FileID, unsigned> locInfo =3D SM.getDecomposedLoc(atLoc);
+
+  // Try to load the file buffer.
+  bool invalidTemp =3D false;
+  StringRef file =3D SM.getBufferData(locInfo.first, &invalidTemp);
+  if (invalidTemp)
+    return false;
+
+  const char *tokenBegin =3D file.data() + locInfo.second;
+
+  // Lex from the start of the given location.
+  Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
+              Pass.Ctx.getLangOpts(),
+              file.begin(), tokenBegin, file.end());
+  Token tok;
+  lexer.LexFromRawLexer(tok);
+  if (tok.isNot(tok::at)) return false;
+  lexer.LexFromRawLexer(tok);
+  if (tok.isNot(tok::raw_identifier)) return false;
+  if (StringRef(tok.getRawIdentifierData(), tok.getLength())
+        !=3D "property")
+    return false;
+  lexer.LexFromRawLexer(tok);
+
+  if (tok.isNot(tok::l_paren)) {
+    Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") "=
);
+    return true;
+  }
+ =20
+  lexer.LexFromRawLexer(tok);
+  if (tok.is(tok::r_paren)) {
+    Pass.TA.insert(tok.getLocation(), attr);
+    return true;
+  }
+
+  if (tok.isNot(tok::raw_identifier)) return false;
+
+  Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
+  return true;
+}
+
+void MigrationContext::traverse(TranslationUnitDecl *TU) {
+  for (traverser_iterator
+         I =3D traversers_begin(), E =3D traversers_end(); I !=3D E; ++I)
+    (*I)->traverseTU(*this);
+
+  ASTTransform(*this).TraverseDecl(TU);
+}
+
+static void GCRewriteFinalize(MigrationPass &pass) {
+  ASTContext &Ctx =3D pass.Ctx;
+  TransformActions &TA =3D pass.TA;
+  DeclContext *DC =3D Ctx.getTranslationUnitDecl();
+  Selector FinalizeSel =3D
+   Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
+ =20
+  typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
+  impl_iterator;
+  for (impl_iterator I =3D impl_iterator(DC->decls_begin()),
+       E =3D impl_iterator(DC->decls_end()); I !=3D E; ++I) {
+    for (ObjCImplementationDecl::instmeth_iterator
+         MI =3D (*I)->instmeth_begin(),
+         ME =3D (*I)->instmeth_end(); MI !=3D ME; ++MI) {
+      ObjCMethodDecl *MD =3D *MI;
+      if (!MD->hasBody())
+        continue;
+     =20
+      if (MD->isInstanceMethod() && MD->getSelector() =3D=3D FinalizeSel) {
+        ObjCMethodDecl *FinalizeM =3D MD;
+        Transaction Trans(TA);
+        TA.insert(FinalizeM->getSourceRange().getBegin(),=20
+                  "#if !__has_feature(objc_arc)\n");
+        CharSourceRange::getTokenRange(FinalizeM->getSourceRange());
+        const SourceManager &SM =3D pass.Ctx.getSourceManager();
+        const LangOptions &LangOpts =3D pass.Ctx.getLangOpts();
+        bool Invalid;
+        std::string str =3D "\n#endif\n";
+        str +=3D Lexer::getSourceText(
+                  CharSourceRange::getTokenRange(FinalizeM->getSourceRange=
()),=20
+                                    SM, LangOpts, &Invalid);
+        TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str);
+       =20
+        break;
+      }
+    }
+  }
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // getAllTransformations.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+static void traverseAST(MigrationPass &pass) {
+  MigrationContext MigrateCtx(pass);
+
+  if (pass.isGCMigration()) {
+    MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
+    MigrateCtx.addTraverser(new GCAttrsTraverser());
+  }
+  MigrateCtx.addTraverser(new PropertyRewriteTraverser());
+  MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
+
+  MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
+}
+
 static void independentTransforms(MigrationPass &pass) {
   rewriteAutoreleasePool(pass);
-  rewriteProperties(pass);
-  removeRetainReleaseDealloc(pass);
+  removeRetainReleaseDeallocFinalize(pass);
   rewriteUnusedInitDelegate(pass);
-  removeZeroOutPropsInDealloc(pass);
+  removeZeroOutPropsInDeallocFinalize(pass);
   makeAssignARCSafe(pass);
   rewriteUnbridgedCasts(pass);
-  rewriteBlockObjCVariable(pass);
   checkAPIUses(pass);
+  traverseAST(pass);
 }
=20
-std::vector<TransformFn> arcmt::getAllTransformations() {
+std::vector<TransformFn> arcmt::getAllTransformations(
+                                               LangOptions::GCMode OrigGCM=
ode,
+                                               bool NoFinalizeRemoval) {
   std::vector<TransformFn> transforms;
=20
+  if (OrigGCMode =3D=3D  LangOptions::GCOnly && NoFinalizeRemoval)
+    transforms.push_back(GCRewriteFinalize);
   transforms.push_back(independentTransforms);
   // This depends on previous transformations removing various expressions.
-  transforms.push_back(removeEmptyStatementsAndDealloc);
+  transforms.push_back(removeEmptyStatementsAndDeallocFinalize);
=20
   return transforms;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/ARCM=
igrate/Transforms.h
--- a/head/contrib/llvm/tools/clang/lib/ARCMigrate/Transforms.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/ARCMigrate/Transforms.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -11,6 +11,7 @@
 #define LLVM_CLANG_LIB_ARCMIGRATE_TRANSFORMS_H
=20
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/ParentMap.h"
 #include "llvm/ADT/DenseSet.h"
=20
 namespace clang {
@@ -25,6 +26,8 @@
=20
 namespace trans {
=20
+  class MigrationContext;
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Transformations.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -32,21 +35,124 @@
 void rewriteAutoreleasePool(MigrationPass &pass);
 void rewriteUnbridgedCasts(MigrationPass &pass);
 void makeAssignARCSafe(MigrationPass &pass);
-void removeRetainReleaseDealloc(MigrationPass &pass);
-void removeZeroOutPropsInDealloc(MigrationPass &pass);
-void rewriteProperties(MigrationPass &pass);
-void rewriteBlockObjCVariable(MigrationPass &pass);
+void removeRetainReleaseDeallocFinalize(MigrationPass &pass);
+void removeZeroOutPropsInDeallocFinalize(MigrationPass &pass);
 void rewriteUnusedInitDelegate(MigrationPass &pass);
 void checkAPIUses(MigrationPass &pass);
=20
-void removeEmptyStatementsAndDealloc(MigrationPass &pass);
+void removeEmptyStatementsAndDeallocFinalize(MigrationPass &pass);
+
+class BodyContext {
+  MigrationContext &MigrateCtx;
+  ParentMap PMap;
+  Stmt *TopStmt;
+
+public:
+  BodyContext(MigrationContext &MigrateCtx, Stmt *S)
+    : MigrateCtx(MigrateCtx), PMap(S), TopStmt(S) {}
+
+  MigrationContext &getMigrationContext() { return MigrateCtx; }
+  ParentMap &getParentMap() { return PMap; }
+  Stmt *getTopStmt() { return TopStmt; }
+};
+
+class ObjCImplementationContext {
+  MigrationContext &MigrateCtx;
+  ObjCImplementationDecl *ImpD;
+
+public:
+  ObjCImplementationContext(MigrationContext &MigrateCtx,
+                            ObjCImplementationDecl *D)
+    : MigrateCtx(MigrateCtx), ImpD(D) {}
+
+  MigrationContext &getMigrationContext() { return MigrateCtx; }
+  ObjCImplementationDecl *getImplementationDecl() { return ImpD; }
+};
+
+class ASTTraverser {
+public:
+  virtual ~ASTTraverser();
+  virtual void traverseTU(MigrationContext &MigrateCtx) { }
+  virtual void traverseBody(BodyContext &BodyCtx) { }
+  virtual void traverseObjCImplementation(ObjCImplementationContext &ImplC=
tx) {}
+};
+
+class MigrationContext {
+  std::vector<ASTTraverser *> Traversers;
+
+public:
+  MigrationPass &Pass;
+
+  struct GCAttrOccurrence {
+    enum AttrKind { Weak, Strong } Kind;
+    SourceLocation Loc;
+    QualType ModifiedType;
+    Decl *Dcl;
+    /// \brief true if the attribute is owned, e.g. it is in a body and no=
t just
+    /// in an interface.
+    bool FullyMigratable;
+  };
+  std::vector<GCAttrOccurrence> GCAttrs;
+  llvm::DenseSet<unsigned> AttrSet;
+  llvm::DenseSet<unsigned> RemovedAttrSet;
+
+  /// \brief Set of raw '@' locations for 'assign' properties group that c=
ontain
+  /// GC __weak.
+  llvm::DenseSet<unsigned> AtPropsWeak;
+
+  explicit MigrationContext(MigrationPass &pass) : Pass(pass) {}
+  ~MigrationContext();
+ =20
+  typedef std::vector<ASTTraverser *>::iterator traverser_iterator;
+  traverser_iterator traversers_begin() { return Traversers.begin(); }
+  traverser_iterator traversers_end() { return Traversers.end(); }
+
+  void addTraverser(ASTTraverser *traverser) {
+    Traversers.push_back(traverser);
+  }
+
+  bool isGCOwnedNonObjC(QualType T);
+  bool removePropertyAttribute(StringRef fromAttr, SourceLocation atLoc) {
+    return rewritePropertyAttribute(fromAttr, StringRef(), atLoc);
+  }
+  bool rewritePropertyAttribute(StringRef fromAttr, StringRef toAttr,
+                                SourceLocation atLoc);
+  bool addPropertyAttribute(StringRef attr, SourceLocation atLoc);
+
+  void traverse(TranslationUnitDecl *TU);
+
+  void dumpGCAttrs();
+};
+
+class PropertyRewriteTraverser : public ASTTraverser {
+public:
+  virtual void traverseObjCImplementation(ObjCImplementationContext &ImplC=
tx);
+};
+
+class BlockObjCVariableTraverser : public ASTTraverser {
+public:
+  virtual void traverseBody(BodyContext &BodyCtx);
+};
+
+// GC transformations
+
+class GCAttrsTraverser : public ASTTraverser {
+public:
+  virtual void traverseTU(MigrationContext &MigrateCtx);
+};
+
+class GCCollectableCallsTraverser : public ASTTraverser {
+public:
+  virtual void traverseBody(BodyContext &BodyCtx);
+};
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Helpers.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 /// \brief Determine whether we can add weak to the given type.
-bool canApplyWeak(ASTContext &Ctx, QualType type);
+bool canApplyWeak(ASTContext &Ctx, QualType type,
+                  bool AllowOnUnknownClass =3D false);
=20
 /// \brief 'Loc' is the end of a statement range. This returns the location
 /// immediately after the semicolon following the statement.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
APValue.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/APValue.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/APValue.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -12,7 +12,11 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/AST/APValue.h"
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/CharUnits.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
 #include "clang/Basic/Diagnostic.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
@@ -20,49 +24,169 @@
 using namespace clang;
=20
 namespace {
-  struct LV {
-    const Expr* Base;
+  struct LVBase {
+    llvm::PointerIntPair<APValue::LValueBase, 1, bool> BaseAndIsOnePastThe=
End;
     CharUnits Offset;
+    unsigned PathLength;
+    unsigned CallIndex;
   };
 }
=20
-APValue::APValue(const Expr* B) : Kind(Uninitialized) {
-  MakeLValue(); setLValue(B, CharUnits::Zero());
+struct APValue::LV : LVBase {
+  static const unsigned InlinePathSpace =3D
+      (MaxSize - sizeof(LVBase)) / sizeof(LValuePathEntry);
+
+  /// Path - The sequence of base classes, fields and array indices to fol=
low to
+  /// walk from Base to the subobject. When performing GCC-style folding, =
there
+  /// may not be such a path.
+  union {
+    LValuePathEntry Path[InlinePathSpace];
+    LValuePathEntry *PathPtr;
+  };
+
+  LV() { PathLength =3D (unsigned)-1; }
+  ~LV() { resizePath(0); }
+
+  void resizePath(unsigned Length) {
+    if (Length =3D=3D PathLength)
+      return;
+    if (hasPathPtr())
+      delete [] PathPtr;
+    PathLength =3D Length;
+    if (hasPathPtr())
+      PathPtr =3D new LValuePathEntry[Length];
+  }
+
+  bool hasPath() const { return PathLength !=3D (unsigned)-1; }
+  bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpa=
ce; }
+
+  LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; }
+  const LValuePathEntry *getPath() const {
+    return hasPathPtr() ? PathPtr : Path;
+  }
+};
+
+namespace {
+  struct MemberPointerBase {
+    llvm::PointerIntPair<const ValueDecl*, 1, bool> MemberAndIsDerivedMemb=
er;
+    unsigned PathLength;
+  };
 }
=20
-const APValue &APValue::operator=3D(const APValue &RHS) {
-  if (Kind !=3D RHS.Kind) {
-    MakeUninit();
-    if (RHS.isInt())
-      MakeInt();
-    else if (RHS.isFloat())
-      MakeFloat();
-    else if (RHS.isVector())
-      MakeVector();
-    else if (RHS.isComplexInt())
-      MakeComplexInt();
-    else if (RHS.isComplexFloat())
-      MakeComplexFloat();
-    else if (RHS.isLValue())
-      MakeLValue();
+struct APValue::MemberPointerData : MemberPointerBase {
+  static const unsigned InlinePathSpace =3D
+      (MaxSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*);
+  typedef const CXXRecordDecl *PathElem;
+  union {
+    PathElem Path[InlinePathSpace];
+    PathElem *PathPtr;
+  };
+
+  MemberPointerData() { PathLength =3D 0; }
+  ~MemberPointerData() { resizePath(0); }
+
+  void resizePath(unsigned Length) {
+    if (Length =3D=3D PathLength)
+      return;
+    if (hasPathPtr())
+      delete [] PathPtr;
+    PathLength =3D Length;
+    if (hasPathPtr())
+      PathPtr =3D new PathElem[Length];
   }
-  if (isInt())
+
+  bool hasPathPtr() const { return PathLength > InlinePathSpace; }
+
+  PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; }
+  const PathElem *getPath() const {
+    return hasPathPtr() ? PathPtr : Path;
+  }
+};
+
+// FIXME: Reduce the malloc traffic here.
+
+APValue::Arr::Arr(unsigned NumElts, unsigned Size) :
+  Elts(new APValue[NumElts + (NumElts !=3D Size ? 1 : 0)]),
+  NumElts(NumElts), ArrSize(Size) {}
+APValue::Arr::~Arr() { delete [] Elts; }
+
+APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) :
+  Elts(new APValue[NumBases+NumFields]),
+  NumBases(NumBases), NumFields(NumFields) {}
+APValue::StructData::~StructData() {
+  delete [] Elts;
+}
+
+APValue::UnionData::UnionData() : Field(0), Value(new APValue) {}
+APValue::UnionData::~UnionData () {
+  delete Value;
+}
+
+APValue::APValue(const APValue &RHS) : Kind(Uninitialized) {
+  switch (RHS.getKind()) {
+  case Uninitialized:
+    break;
+  case Int:
+    MakeInt();
     setInt(RHS.getInt());
-  else if (isFloat())
+    break;
+  case Float:
+    MakeFloat();
     setFloat(RHS.getFloat());
-  else if (isVector())
+    break;
+  case Vector:
+    MakeVector();
     setVector(((const Vec *)(const char *)RHS.Data)->Elts,
               RHS.getVectorLength());
-  else if (isComplexInt())
+    break;
+  case ComplexInt:
+    MakeComplexInt();
     setComplexInt(RHS.getComplexIntReal(), RHS.getComplexIntImag());
-  else if (isComplexFloat())
+    break;
+  case ComplexFloat:
+    MakeComplexFloat();
     setComplexFloat(RHS.getComplexFloatReal(), RHS.getComplexFloatImag());
-  else if (isLValue())
-    setLValue(RHS.getLValueBase(), RHS.getLValueOffset());
-  return *this;
+    break;
+  case LValue:
+    MakeLValue();
+    if (RHS.hasLValuePath())
+      setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), RHS.getLValueP=
ath(),
+                RHS.isLValueOnePastTheEnd(), RHS.getLValueCallIndex());
+    else
+      setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), NoLValuePath(),
+                RHS.getLValueCallIndex());
+    break;
+  case Array:
+    MakeArray(RHS.getArrayInitializedElts(), RHS.getArraySize());
+    for (unsigned I =3D 0, N =3D RHS.getArrayInitializedElts(); I !=3D N; =
++I)
+      getArrayInitializedElt(I) =3D RHS.getArrayInitializedElt(I);
+    if (RHS.hasArrayFiller())
+      getArrayFiller() =3D RHS.getArrayFiller();
+    break;
+  case Struct:
+    MakeStruct(RHS.getStructNumBases(), RHS.getStructNumFields());
+    for (unsigned I =3D 0, N =3D RHS.getStructNumBases(); I !=3D N; ++I)
+      getStructBase(I) =3D RHS.getStructBase(I);
+    for (unsigned I =3D 0, N =3D RHS.getStructNumFields(); I !=3D N; ++I)
+      getStructField(I) =3D RHS.getStructField(I);
+    break;
+  case Union:
+    MakeUnion();
+    setUnion(RHS.getUnionField(), RHS.getUnionValue());
+    break;
+  case MemberPointer:
+    MakeMemberPointer(RHS.getMemberPointerDecl(),
+                      RHS.isMemberPointerToDerivedMember(),
+                      RHS.getMemberPointerPath());
+    break;
+  case AddrLabelDiff:
+    MakeAddrLabelDiff();
+    setAddrLabelDiff(RHS.getAddrLabelDiffLHS(), RHS.getAddrLabelDiffRHS());
+    break;
+  }
 }
=20
-void APValue::MakeUninit() {
+void APValue::DestroyDataAndMakeUninit() {
   if (Kind =3D=3D Int)
     ((APSInt*)(char*)Data)->~APSInt();
   else if (Kind =3D=3D Float)
@@ -73,14 +197,31 @@
     ((ComplexAPSInt*)(char*)Data)->~ComplexAPSInt();
   else if (Kind =3D=3D ComplexFloat)
     ((ComplexAPFloat*)(char*)Data)->~ComplexAPFloat();
-  else if (Kind =3D=3D LValue) {
+  else if (Kind =3D=3D LValue)
     ((LV*)(char*)Data)->~LV();
-  }
+  else if (Kind =3D=3D Array)
+    ((Arr*)(char*)Data)->~Arr();
+  else if (Kind =3D=3D Struct)
+    ((StructData*)(char*)Data)->~StructData();
+  else if (Kind =3D=3D Union)
+    ((UnionData*)(char*)Data)->~UnionData();
+  else if (Kind =3D=3D MemberPointer)
+    ((MemberPointerData*)(char*)Data)->~MemberPointerData();
+  else if (Kind =3D=3D AddrLabelDiff)
+    ((AddrLabelDiffData*)(char*)Data)->~AddrLabelDiffData();
   Kind =3D Uninitialized;
 }
=20
+void APValue::swap(APValue &RHS) {
+  std::swap(Kind, RHS.Kind);
+  char TmpData[MaxSize];
+  memcpy(TmpData, Data, MaxSize);
+  memcpy(Data, RHS.Data, MaxSize);
+  memcpy(RHS.Data, TmpData, MaxSize);
+}
+
 void APValue::dump() const {
-  print(llvm::errs());
+  dump(llvm::errs());
   llvm::errs() << '\n';
 }
=20
@@ -92,9 +233,8 @@
   return V.convertToDouble();
 }
=20
-void APValue::print(raw_ostream &OS) const {
+void APValue::dump(raw_ostream &OS) const {
   switch (getKind()) {
-  default: llvm_unreachable("Unknown APValue kind!");
   case Uninitialized:
     OS << "Uninitialized";
     return;
@@ -105,9 +245,12 @@
     OS << "Float: " << GetApproxValue(getFloat());
     return;
   case Vector:
-    OS << "Vector: " << getVectorElt(0);
-    for (unsigned i =3D 1; i !=3D getVectorLength(); ++i)
-      OS << ", " << getVectorElt(i);
+    OS << "Vector: ";
+    getVectorElt(0).dump(OS);
+    for (unsigned i =3D 1; i !=3D getVectorLength(); ++i) {
+      OS << ", ";
+      getVectorElt(i).dump(OS);
+    }
     return;
   case ComplexInt:
     OS << "ComplexInt: " << getComplexIntReal() << ", " << getComplexIntIm=
ag();
@@ -115,74 +258,350 @@
   case ComplexFloat:
     OS << "ComplexFloat: " << GetApproxValue(getComplexFloatReal())
        << ", " << GetApproxValue(getComplexFloatImag());
+    return;
   case LValue:
     OS << "LValue: <todo>";
     return;
+  case Array:
+    OS << "Array: ";
+    for (unsigned I =3D 0, N =3D getArrayInitializedElts(); I !=3D N; ++I)=
 {
+      getArrayInitializedElt(I).dump(OS);
+      if (I !=3D getArraySize() - 1) OS << ", ";
+    }
+    if (hasArrayFiller()) {
+      OS << getArraySize() - getArrayInitializedElts() << " x ";
+      getArrayFiller().dump(OS);
+    }
+    return;
+  case Struct:
+    OS << "Struct ";
+    if (unsigned N =3D getStructNumBases()) {
+      OS << " bases: ";
+      getStructBase(0).dump(OS);
+      for (unsigned I =3D 1; I !=3D N; ++I) {
+        OS << ", ";
+        getStructBase(I).dump(OS);
+      }
+    }
+    if (unsigned N =3D getStructNumFields()) {
+      OS << " fields: ";
+      getStructField(0).dump(OS);
+      for (unsigned I =3D 1; I !=3D N; ++I) {
+        OS << ", ";
+        getStructField(I).dump(OS);
+      }
+    }
+    return;
+  case Union:
+    OS << "Union: ";
+    getUnionValue().dump(OS);
+    return;
+  case MemberPointer:
+    OS << "MemberPointer: <todo>";
+    return;
+  case AddrLabelDiff:
+    OS << "AddrLabelDiff: <todo>";
+    return;
   }
+  llvm_unreachable("Unknown APValue kind!");
 }
=20
-static void WriteShortAPValueToStream(raw_ostream& Out,
-                                      const APValue& V) {
-  switch (V.getKind()) {
-  default: llvm_unreachable("Unknown APValue kind!");
+void APValue::printPretty(raw_ostream &Out, ASTContext &Ctx, QualType Ty) =
const{
+  switch (getKind()) {
   case APValue::Uninitialized:
-    Out << "Uninitialized";
-    break;
+    Out << "<uninitialized>";
+    return;
   case APValue::Int:
-    Out << V.getInt();
-    break;
+    if (Ty->isBooleanType())
+      Out << (getInt().getBoolValue() ? "true" : "false");
+    else
+      Out << getInt();
+    return;
   case APValue::Float:
-    Out << GetApproxValue(V.getFloat());
-    break;
-  case APValue::Vector:
-    Out << '[';
-    WriteShortAPValueToStream(Out, V.getVectorElt(0));
-    for (unsigned i =3D 1; i !=3D V.getVectorLength(); ++i) {
+    Out << GetApproxValue(getFloat());
+    return;
+  case APValue::Vector: {
+    Out << '{';
+    QualType ElemTy =3D Ty->getAs<VectorType>()->getElementType();
+    getVectorElt(0).printPretty(Out, Ctx, ElemTy);
+    for (unsigned i =3D 1; i !=3D getVectorLength(); ++i) {
       Out << ", ";
-      WriteShortAPValueToStream(Out, V.getVectorElt(i));
+      getVectorElt(i).printPretty(Out, Ctx, ElemTy);
     }
-    Out << ']';
-    break;
+    Out << '}';
+    return;
+  }
   case APValue::ComplexInt:
-    Out << V.getComplexIntReal() << "+" << V.getComplexIntImag() << "i";
-    break;
+    Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
+    return;
   case APValue::ComplexFloat:
-    Out << GetApproxValue(V.getComplexFloatReal()) << "+"
-        << GetApproxValue(V.getComplexFloatImag()) << "i";
-    break;
-  case APValue::LValue:
-    Out << "LValue: <todo>";
-    break;
+    Out << GetApproxValue(getComplexFloatReal()) << "+"
+        << GetApproxValue(getComplexFloatImag()) << "i";
+    return;
+  case APValue::LValue: {
+    LValueBase Base =3D getLValueBase();
+    if (!Base) {
+      Out << "0";
+      return;
+    }
+
+    bool IsReference =3D Ty->isReferenceType();
+    QualType InnerTy
+      =3D IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
+
+    if (!hasLValuePath()) {
+      // No lvalue path: just print the offset.
+      CharUnits O =3D getLValueOffset();
+      CharUnits S =3D Ctx.getTypeSizeInChars(InnerTy);
+      if (!O.isZero()) {
+        if (IsReference)
+          Out << "*(";
+        if (O % S) {
+          Out << "(char*)";
+          S =3D CharUnits::One();
+        }
+        Out << '&';
+      } else if (!IsReference)
+        Out << '&';
+
+      if (const ValueDecl *VD =3D Base.dyn_cast<const ValueDecl*>())
+        Out << *VD;
+      else
+        Base.get<const Expr*>()->printPretty(Out, Ctx, 0,
+                                             Ctx.getPrintingPolicy());
+      if (!O.isZero()) {
+        Out << " + " << (O / S);
+        if (IsReference)
+          Out << ')';
+      }
+      return;
+    }
+
+    // We have an lvalue path. Print it out nicely.
+    if (!IsReference)
+      Out << '&';
+    else if (isLValueOnePastTheEnd())
+      Out << "*(&";
+
+    QualType ElemTy;
+    if (const ValueDecl *VD =3D Base.dyn_cast<const ValueDecl*>()) {
+      Out << *VD;
+      ElemTy =3D VD->getType();
+    } else {
+      const Expr *E =3D Base.get<const Expr*>();
+      E->printPretty(Out, Ctx, 0,Ctx.getPrintingPolicy());
+      ElemTy =3D E->getType();
+    }
+
+    ArrayRef<LValuePathEntry> Path =3D getLValuePath();
+    const CXXRecordDecl *CastToBase =3D 0;
+    for (unsigned I =3D 0, N =3D Path.size(); I !=3D N; ++I) {
+      if (ElemTy->getAs<RecordType>()) {
+        // The lvalue refers to a class type, so the next path entry is a =
base
+        // or member.
+        const Decl *BaseOrMember =3D
+        BaseOrMemberType::getFromOpaqueValue(Path[I].BaseOrMember).getPoin=
ter();
+        if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(BaseOrMemb=
er)) {
+          CastToBase =3D RD;
+          ElemTy =3D Ctx.getRecordType(RD);
+        } else {
+          const ValueDecl *VD =3D cast<ValueDecl>(BaseOrMember);
+          Out << ".";
+          if (CastToBase)
+            Out << *CastToBase << "::";
+          Out << *VD;
+          ElemTy =3D VD->getType();
+        }
+      } else {
+        // The lvalue must refer to an array.
+        Out << '[' << Path[I].ArrayIndex << ']';
+        ElemTy =3D Ctx.getAsArrayType(ElemTy)->getElementType();
+      }
+    }
+
+    // Handle formatting of one-past-the-end lvalues.
+    if (isLValueOnePastTheEnd()) {
+      // FIXME: If CastToBase is non-0, we should prefix the output with
+      // "(CastToBase*)".
+      Out << " + 1";
+      if (IsReference)
+        Out << ')';
+    }
+    return;
   }
+  case APValue::Array: {
+    const ArrayType *AT =3D Ctx.getAsArrayType(Ty);
+    QualType ElemTy =3D AT->getElementType();
+    Out << '{';
+    if (unsigned N =3D getArrayInitializedElts()) {
+      getArrayInitializedElt(0).printPretty(Out, Ctx, ElemTy);
+      for (unsigned I =3D 1; I !=3D N; ++I) {
+        Out << ", ";
+        if (I =3D=3D 10) {
+          // Avoid printing out the entire contents of large arrays.
+          Out << "...";
+          break;
+        }
+        getArrayInitializedElt(I).printPretty(Out, Ctx, ElemTy);
+      }
+    }
+    Out << '}';
+    return;
+  }
+  case APValue::Struct: {
+    Out << '{';
+    const RecordDecl *RD =3D Ty->getAs<RecordType>()->getDecl();
+    bool First =3D true;
+    if (unsigned N =3D getStructNumBases()) {
+      const CXXRecordDecl *CD =3D cast<CXXRecordDecl>(RD);
+      CXXRecordDecl::base_class_const_iterator BI =3D CD->bases_begin();
+      for (unsigned I =3D 0; I !=3D N; ++I, ++BI) {
+        assert(BI !=3D CD->bases_end());
+        if (!First)
+          Out << ", ";
+        getStructBase(I).printPretty(Out, Ctx, BI->getType());
+        First =3D false;
+      }
+    }
+    for (RecordDecl::field_iterator FI =3D RD->field_begin();
+         FI !=3D RD->field_end(); ++FI) {
+      if (!First)
+        Out << ", ";
+      if ((*FI)->isUnnamedBitfield()) continue;
+      getStructField((*FI)->getFieldIndex()).
+        printPretty(Out, Ctx, (*FI)->getType());
+      First =3D false;
+    }
+    Out << '}';
+    return;
+  }
+  case APValue::Union:
+    Out << '{';
+    if (const FieldDecl *FD =3D getUnionField()) {
+      Out << "." << *FD << " =3D ";
+      getUnionValue().printPretty(Out, Ctx, FD->getType());
+    }
+    Out << '}';
+    return;
+  case APValue::MemberPointer:
+    // FIXME: This is not enough to unambiguously identify the member in a
+    // multiple-inheritance scenario.
+    if (const ValueDecl *VD =3D getMemberPointerDecl()) {
+      Out << '&' << *cast<CXXRecordDecl>(VD->getDeclContext()) << "::" << =
*VD;
+      return;
+    }
+    Out << "0";
+    return;
+  case APValue::AddrLabelDiff:
+    Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
+    Out << " - ";
+    Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
+    return;
+  }
+  llvm_unreachable("Unknown APValue kind!");
 }
=20
-const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
-                                           const APValue &V) {
-  llvm::SmallString<64> Buffer;
-  llvm::raw_svector_ostream Out(Buffer);
-  WriteShortAPValueToStream(Out, V);
-  return DB << Out.str();
+std::string APValue::getAsString(ASTContext &Ctx, QualType Ty) const {
+  std::string Result;
+  llvm::raw_string_ostream Out(Result);
+  printPretty(Out, Ctx, Ty);
+  Out.flush();
+  return Result;
 }
=20
-const Expr* APValue::getLValueBase() const {
+const APValue::LValueBase APValue::getLValueBase() const {
   assert(isLValue() && "Invalid accessor");
-  return ((const LV*)(const void*)Data)->Base;
+  return ((const LV*)(const void*)Data)->BaseAndIsOnePastTheEnd.getPointer=
();
 }
=20
-CharUnits APValue::getLValueOffset() const {
-    assert(isLValue() && "Invalid accessor");
-    return ((const LV*)(const void*)Data)->Offset;
+bool APValue::isLValueOnePastTheEnd() const {
+  assert(isLValue() && "Invalid accessor");
+  return ((const LV*)(const void*)Data)->BaseAndIsOnePastTheEnd.getInt();
 }
=20
-void APValue::setLValue(const Expr *B, const CharUnits &O) {
+CharUnits &APValue::getLValueOffset() {
   assert(isLValue() && "Invalid accessor");
-  ((LV*)(char*)Data)->Base =3D B;
-  ((LV*)(char*)Data)->Offset =3D O;
+  return ((LV*)(void*)Data)->Offset;
+}
+
+bool APValue::hasLValuePath() const {
+  assert(isLValue() && "Invalid accessor");
+  return ((const LV*)(const char*)Data)->hasPath();
+}
+
+ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
+  assert(isLValue() && hasLValuePath() && "Invalid accessor");
+  const LV &LVal =3D *((const LV*)(const char*)Data);
+  return ArrayRef<LValuePathEntry>(LVal.getPath(), LVal.PathLength);
+}
+
+unsigned APValue::getLValueCallIndex() const {
+  assert(isLValue() && "Invalid accessor");
+  return ((const LV*)(const char*)Data)->CallIndex;
+}
+
+void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
+                        unsigned CallIndex) {
+  assert(isLValue() && "Invalid accessor");
+  LV &LVal =3D *((LV*)(char*)Data);
+  LVal.BaseAndIsOnePastTheEnd.setPointer(B);
+  LVal.BaseAndIsOnePastTheEnd.setInt(false);
+  LVal.Offset =3D O;
+  LVal.CallIndex =3D CallIndex;
+  LVal.resizePath((unsigned)-1);
+}
+
+void APValue::setLValue(LValueBase B, const CharUnits &O,
+                        ArrayRef<LValuePathEntry> Path, bool IsOnePastTheE=
nd,
+                        unsigned CallIndex) {
+  assert(isLValue() && "Invalid accessor");
+  LV &LVal =3D *((LV*)(char*)Data);
+  LVal.BaseAndIsOnePastTheEnd.setPointer(B);
+  LVal.BaseAndIsOnePastTheEnd.setInt(IsOnePastTheEnd);
+  LVal.Offset =3D O;
+  LVal.CallIndex =3D CallIndex;
+  LVal.resizePath(Path.size());
+  memcpy(LVal.getPath(), Path.data(), Path.size() * sizeof(LValuePathEntry=
));
+}
+
+const ValueDecl *APValue::getMemberPointerDecl() const {
+  assert(isMemberPointer() && "Invalid accessor");
+  const MemberPointerData &MPD =3D *((const MemberPointerData*)(const char=
*)Data);
+  return MPD.MemberAndIsDerivedMember.getPointer();
+}
+
+bool APValue::isMemberPointerToDerivedMember() const {
+  assert(isMemberPointer() && "Invalid accessor");
+  const MemberPointerData &MPD =3D *((const MemberPointerData*)(const char=
*)Data);
+  return MPD.MemberAndIsDerivedMember.getInt();
+}
+
+ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
+  assert(isMemberPointer() && "Invalid accessor");
+  const MemberPointerData &MPD =3D *((const MemberPointerData*)(const char=
*)Data);
+  return ArrayRef<const CXXRecordDecl*>(MPD.getPath(), MPD.PathLength);
 }
=20
 void APValue::MakeLValue() {
   assert(isUninit() && "Bad state change");
+  assert(sizeof(LV) <=3D MaxSize && "LV too big");
   new ((void*)(char*)Data) LV();
   Kind =3D LValue;
 }
=20
+void APValue::MakeArray(unsigned InitElts, unsigned Size) {
+  assert(isUninit() && "Bad state change");
+  new ((void*)(char*)Data) Arr(InitElts, Size);
+  Kind =3D Array;
+}
+
+void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMem=
ber,
+                                ArrayRef<const CXXRecordDecl*> Path) {
+  assert(isUninit() && "Bad state change");
+  MemberPointerData *MPD =3D new ((void*)(char*)Data) MemberPointerData;
+  Kind =3D MemberPointer;
+  MPD->MemberAndIsDerivedMember.setPointer(Member);
+  MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
+  MPD->resizePath(Path.size());
+  memcpy(MPD->getPath(), Path.data(), Path.size()*sizeof(const CXXRecordDe=
cl*));
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ASTConsumer.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ASTConsumer.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ASTConsumer.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,8 +15,12 @@
 #include "clang/AST/DeclGroup.h"
 using namespace clang;
=20
-void ASTConsumer::HandleTopLevelDecl(DeclGroupRef D) {}
+bool ASTConsumer::HandleTopLevelDecl(DeclGroupRef D) {
+  return true;
+}
=20
 void ASTConsumer::HandleInterestingDecl(DeclGroupRef D) {
   HandleTopLevelDecl(D);
 }
+
+void ASTConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ASTContext.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -74,12 +74,14 @@
     if (NonTypeTemplateParmDecl *NTTP =3D dyn_cast<NonTypeTemplateParmDecl=
>(*P)) {
       ID.AddInteger(1);
       ID.AddBoolean(NTTP->isParameterPack());
-      ID.AddPointer(NTTP->getType().getAsOpaquePtr());
+      ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
       if (NTTP->isExpandedParameterPack()) {
         ID.AddBoolean(true);
         ID.AddInteger(NTTP->getNumExpansionTypes());
-        for (unsigned I =3D 0, N =3D NTTP->getNumExpansionTypes(); I !=3D =
N; ++I)
-          ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
+        for (unsigned I =3D 0, N =3D NTTP->getNumExpansionTypes(); I !=3D =
N; ++I) {
+          QualType T =3D NTTP->getExpansionType(I);
+          ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
+        }
       } else=20
         ID.AddBoolean(false);
       continue;
@@ -193,7 +195,7 @@
   case CXXABI_Microsoft:
     return CreateMicrosoftCXXABI(*this);
   }
-  return 0;
+  llvm_unreachable("Invalid CXXABI type!");
 }
=20
 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
@@ -224,13 +226,14 @@
     SubstTemplateTemplateParmPacks(this_()),
     GlobalNestedNameSpecifier(0),=20
     Int128Decl(0), UInt128Decl(0),
-    ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
+    ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl=
(0),
     CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
     FILEDecl(0),=20
     jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
     BlockDescriptorType(0), BlockDescriptorExtendedType(0),
     cudaConfigureCallDecl(0),
-    NullTypeSourceInfo(QualType()),
+    NullTypeSourceInfo(QualType()),=20
+    FirstLocalImport(), LastLocalImport(),
     SourceMgr(SM), LangOpts(LOpts),=20
     AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
     Idents(idents), Selectors(sels),
@@ -258,12 +261,6 @@
   for (unsigned I =3D 0, N =3D Deallocations.size(); I !=3D N; ++I)
     Deallocations[I].first(Deallocations[I].second);
  =20
-  // Release all of the memory associated with overridden C++ methods.
-  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator=20
-         OM =3D OverriddenMethods.begin(), OMEnd =3D OverriddenMethods.end=
();
-       OM !=3D OMEnd; ++OM)
-    OM->second.Destroy();
- =20
   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
   // because they can contain DenseMaps.
   for (llvm::DenseMap<const ObjCContainerDecl*,
@@ -291,7 +288,7 @@
 }
=20
 void
-ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
+ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
   ExternalSource.reset(Source.take());
 }
=20
@@ -331,14 +328,14 @@
   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
                << NumImplicitCopyConstructors
                << " implicit copy constructors created\n";
-  if (getLangOptions().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
                  << NumImplicitMoveConstructors
                  << " implicit move constructors created\n";
   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
                << NumImplicitCopyAssignmentOperators
                << " implicit copy assignment operators created\n";
-  if (getLangOptions().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
                  << NumImplicitMoveAssignmentOperators
                  << " implicit move assignment operators created\n";
@@ -462,9 +459,15 @@
   // Placeholder type for bound members.
   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
=20
+  // Placeholder type for pseudo-objects.
+  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
+
   // "any" type; useful for debugger-like clients.
   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
=20
+  // Placeholder type for unbridged ARC casts.
+  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
+
   // C99 6.2.5p11.
   FloatComplexTy      =3D getComplexType(FloatTy);
   DoubleComplexTy     =3D getComplexType(DoubleTy);
@@ -476,7 +479,10 @@
   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
-
+ =20
+  // Builtin type for __objc_yes and __objc_no
+  ObjCBuiltinBoolTy =3D SignedCharTy;
+ =20
   ObjCConstantStringType =3D QualType();
=20
   // void * type
@@ -676,6 +682,19 @@
   OverriddenMethods[Method].push_back(Overridden);
 }
=20
+void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
+  assert(!Import->NextLocalImport && "Import declaration already in the ch=
ain");
+  assert(!Import->isFromASTFile() && "Non-local import declaration");
+  if (!FirstLocalImport) {
+    FirstLocalImport =3D Import;
+    LastLocalImport =3D Import;
+    return;
+  }
+ =20
+  LastLocalImport->NextLocalImport =3D Import;
+  LastLocalImport =3D Import;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                         Type Sizing and Analysis
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -796,14 +815,24 @@
   return getTypeInfoInChars(T.getTypePtr());
 }
=20
-/// getTypeSize - Return the size of the specified type, in bits.  This me=
thod
-/// does not work on incomplete types.
+std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const=
 {
+  TypeInfoMap::iterator it =3D MemoizedTypeInfo.find(T);
+  if (it !=3D MemoizedTypeInfo.end())
+    return it->second;
+
+  std::pair<uint64_t, unsigned> Info =3D getTypeInfoImpl(T);
+  MemoizedTypeInfo.insert(std::make_pair(T, Info));
+  return Info;
+}
+
+/// getTypeInfoImpl - Return the size of the specified type, in bits.  This
+/// method does not work on incomplete types.
 ///
 /// FIXME: Pointers into different addr spaces could have different sizes =
and
 /// alignment requirements: getPointerInfo should take an AddrSpace, this
 /// should take a QualType, &c.
 std::pair<uint64_t, unsigned>
-ASTContext::getTypeInfo(const Type *T) const {
+ASTContext::getTypeInfoImpl(const Type *T) const {
   uint64_t Width=3D0;
   unsigned Align=3D8;
   switch (T->getTypeClass()) {
@@ -813,7 +842,6 @@
 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
 #include "clang/AST/TypeNodes.def"
     llvm_unreachable("Should not see dependent types");
-    break;
=20
   case Type::FunctionNoProto:
   case Type::FunctionProto:
@@ -832,7 +860,10 @@
     const ConstantArrayType *CAT =3D cast<ConstantArrayType>(T);
=20
     std::pair<uint64_t, unsigned> EltInfo =3D getTypeInfo(CAT->getElementT=
ype());
-    Width =3D EltInfo.first*CAT->getSize().getZExtValue();
+    uint64_t Size =3D CAT->getSize().getZExtValue();
+    assert((Size =3D=3D 0 || EltInfo.first <=3D (uint64_t)(-1)/Size) &&=20
+           "Overflow in array type bit size evaluation");
+    Width =3D EltInfo.first*Size;
     Align =3D EltInfo.second;
     Width =3D llvm::RoundUpToAlignment(Width, Align);
     break;
@@ -1134,7 +1165,8 @@
   if (const ComplexType* CT =3D T->getAs<ComplexType>())
     T =3D CT->getElementType().getTypePtr();
   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
-      T->isSpecificBuiltinType(BuiltinType::LongLong))
+      T->isSpecificBuiltinType(BuiltinType::LongLong) ||
+      T->isSpecificBuiltinType(BuiltinType::ULongLong))
     return std::max(ABIAlign, (unsigned)getTypeSize(T));
=20
   return ABIAlign;
@@ -1173,10 +1205,10 @@
     for (ObjCInterfaceDecl::all_protocol_iterator P =3D OI->all_referenced=
_protocol_begin(),
          PE =3D OI->all_referenced_protocol_end(); P !=3D PE; ++P) {
       ObjCProtocolDecl *Proto =3D (*P);
-      Protocols.insert(Proto);
+      Protocols.insert(Proto->getCanonicalDecl());
       for (ObjCProtocolDecl::protocol_iterator P =3D Proto->protocol_begin=
(),
            PE =3D Proto->protocol_end(); P !=3D PE; ++P) {
-        Protocols.insert(*P);
+        Protocols.insert((*P)->getCanonicalDecl());
         CollectInheritedProtocols(*P, Protocols);
       }
     }
@@ -1194,7 +1226,7 @@
     for (ObjCCategoryDecl::protocol_iterator P =3D OC->protocol_begin(),
          PE =3D OC->protocol_end(); P !=3D PE; ++P) {
       ObjCProtocolDecl *Proto =3D (*P);
-      Protocols.insert(Proto);
+      Protocols.insert(Proto->getCanonicalDecl());
       for (ObjCProtocolDecl::protocol_iterator P =3D Proto->protocol_begin=
(),
            PE =3D Proto->protocol_end(); P !=3D PE; ++P)
         CollectInheritedProtocols(*P, Protocols);
@@ -1203,7 +1235,7 @@
     for (ObjCProtocolDecl::protocol_iterator P =3D OP->protocol_begin(),
          PE =3D OP->protocol_end(); P !=3D PE; ++P) {
       ObjCProtocolDecl *Proto =3D (*P);
-      Protocols.insert(Proto);
+      Protocols.insert(Proto->getCanonicalDecl());
       for (ObjCProtocolDecl::protocol_iterator P =3D Proto->protocol_begin=
(),
            PE =3D Proto->protocol_end(); P !=3D PE; ++P)
         CollectInheritedProtocols(*P, Protocols);
@@ -1226,6 +1258,24 @@
   return count;
 }
=20
+bool ASTContext::isSentinelNullExpr(const Expr *E) {
+  if (!E)
+    return false;
+
+  // nullptr_t is always treated as null.
+  if (E->getType()->isNullPtrType()) return true;
+
+  if (E->getType()->isAnyPointerType() &&
+      E->IgnoreParenCasts()->isNullPointerConstant(*this,
+                                                Expr::NPC_ValueDependentIs=
Null))
+    return true;
+
+  // Unfortunately, __null has type 'int'.
+  if (isa<GNUNullExpr>(E)) return true;
+
+  return false;
+}
+
 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exi=
sts.
 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDec=
l *D) {
   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
@@ -1256,6 +1306,17 @@
   ObjCImpls[CatD] =3D ImplD;
 }
=20
+ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) co=
nst {
+  if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(ND->getDeclCon=
text()))
+    return ID;
+  if (ObjCCategoryDecl *CD =3D dyn_cast<ObjCCategoryDecl>(ND->getDeclConte=
xt()))
+    return CD->getClassInterface();
+  if (ObjCImplDecl *IMD =3D dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
+    return IMD->getClassInterface();
+
+  return 0;
+}
+
 /// \brief Get the copy initialization expression of VarDecl,or NULL if=20
 /// none exists.
 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
@@ -1337,8 +1398,8 @@
   QualType canon;
   if (!baseType->isCanonicalUnqualified()) {
     SplitQualType canonSplit =3D baseType->getCanonicalTypeInternal().spli=
t();
-    canonSplit.second.addConsistentQualifiers(quals);
-    canon =3D getExtQualType(canonSplit.first, canonSplit.second);
+    canonSplit.Quals.addConsistentQualifiers(quals);
+    canon =3D getExtQualType(canonSplit.Ty, canonSplit.Quals);
=20
     // Re-find the insert position.
     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
@@ -1640,9 +1701,9 @@
   QualType Canon;
   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
     SplitQualType canonSplit =3D getCanonicalType(EltTy).split();
-    Canon =3D getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
+    Canon =3D getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
                                  ASM, IndexTypeQuals);
-    Canon =3D getQualifiedType(Canon, canonSplit.second);
+    Canon =3D getQualifiedType(Canon, canonSplit.Quals);
=20
     // Get the new insert position for the node we care about.
     ConstantArrayType *NewIP =3D
@@ -1667,7 +1728,7 @@
   QualType result;
=20
   SplitQualType split =3D type.getSplitDesugaredType();
-  const Type *ty =3D split.first;
+  const Type *ty =3D split.Ty;
   switch (ty->getTypeClass()) {
 #define TYPE(Class, Base)
 #define ABSTRACT_TYPE(Class, Base)
@@ -1786,7 +1847,7 @@
   }
=20
   // Apply the top-level qualifiers from the original.
-  return getQualifiedType(result, split.second);
+  return getQualifiedType(result, split.Quals);
 }
=20
 /// getVariableArrayType - Returns a non-unique reference to the type for a
@@ -1803,9 +1864,9 @@
   // Be sure to pull qualifiers off the element type.
   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
     SplitQualType canonSplit =3D getCanonicalType(EltTy).split();
-    Canon =3D getVariableArrayType(QualType(canonSplit.first, 0), NumElts,=
 ASM,
+    Canon =3D getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, AS=
M,
                                  IndexTypeQuals, Brackets);
-    Canon =3D getQualifiedType(Canon, canonSplit.second);
+    Canon =3D getQualifiedType(Canon, canonSplit.Quals);
   }
  =20
   VariableArrayType *New =3D new(*this, TypeAlignment)
@@ -1850,7 +1911,7 @@
   void *insertPos =3D 0;
   llvm::FoldingSetNodeID ID;
   DependentSizedArrayType::Profile(ID, *this,
-                                   QualType(canonElementType.first, 0),
+                                   QualType(canonElementType.Ty, 0),
                                    ASM, elementTypeQuals, numElements);
=20
   // Look for an existing type with these properties.
@@ -1860,7 +1921,7 @@
   // If we don't have one, build one.
   if (!canonTy) {
     canonTy =3D new (*this, TypeAlignment)
-      DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
+      DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
                               QualType(), numElements, ASM, elementTypeQua=
ls,
                               brackets);
     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
@@ -1869,11 +1930,11 @@
=20
   // Apply qualifiers from the element type to the array.
   QualType canon =3D getQualifiedType(QualType(canonTy,0),
-                                    canonElementType.second);
+                                    canonElementType.Quals);
=20
   // If we didn't need extra canonicalization for the element type,
   // then just use that as our result.
-  if (QualType(canonElementType.first, 0) =3D=3D elementType)
+  if (QualType(canonElementType.Ty, 0) =3D=3D elementType)
     return canon;
=20
   // Otherwise, we need to build a type which follows the spelling
@@ -1904,9 +1965,9 @@
=20
   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
     SplitQualType canonSplit =3D getCanonicalType(elementType).split();
-    canon =3D getIncompleteArrayType(QualType(canonSplit.first, 0),
+    canon =3D getIncompleteArrayType(QualType(canonSplit.Ty, 0),
                                    ASM, elementTypeQuals);
-    canon =3D getQualifiedType(canon, canonSplit.second);
+    canon =3D getQualifiedType(canon, canonSplit.Quals);
=20
     // Get the new insert position for the node we care about.
     IncompleteArrayType *existing =3D
@@ -2082,7 +2143,9 @@
     return QualType(FTP, 0);
=20
   // Determine whether the type being created is already canonical or not.
-  bool isCanonical=3D EPI.ExceptionSpecType =3D=3D EST_None && ResultTy.is=
Canonical();
+  bool isCanonical =3D
+    EPI.ExceptionSpecType =3D=3D EST_None && ResultTy.isCanonical() &&
+    !EPI.HasTrailingReturn;
   for (unsigned i =3D 0; i !=3D NumArgs && isCanonical; ++i)
     if (!ArgArray[i].isCanonicalAsParam())
       isCanonical =3D false;
@@ -2101,6 +2164,7 @@
       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
=20
     FunctionProtoType::ExtProtoInfo CanonicalEPI =3D EPI;
+    CanonicalEPI.HasTrailingReturn =3D false;
     CanonicalEPI.ExceptionSpecType =3D EST_None;
     CanonicalEPI.NumExceptions =3D 0;
     CanonicalEPI.ExtInfo
@@ -2162,7 +2226,7 @@
   assert(NeedsInjectedClassNameType(Decl));
   if (Decl->TypeForDecl) {
     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
-  } else if (CXXRecordDecl *PrevDecl =3D Decl->getPreviousDeclaration()) {
+  } else if (CXXRecordDecl *PrevDecl =3D Decl->getPreviousDecl()) {
     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
     Decl->TypeForDecl =3D PrevDecl->TypeForDecl;
     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
@@ -2188,12 +2252,12 @@
          "Template type parameter types are always available.");
=20
   if (const RecordDecl *Record =3D dyn_cast<RecordDecl>(Decl)) {
-    assert(!Record->getPreviousDeclaration() &&
+    assert(!Record->getPreviousDecl() &&
            "struct/union has previous declaration");
     assert(!NeedsInjectedClassNameType(Record));
     return getRecordType(Record);
   } else if (const EnumDecl *Enum =3D dyn_cast<EnumDecl>(Decl)) {
-    assert(!Enum->getPreviousDeclaration() &&
+    assert(!Enum->getPreviousDecl() &&
            "enum has previous declaration");
     return getEnumType(Enum);
   } else if (const UnresolvedUsingTypenameDecl *Using =3D
@@ -2226,7 +2290,7 @@
 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
=20
-  if (const RecordDecl *PrevDecl =3D Decl->getPreviousDeclaration())
+  if (const RecordDecl *PrevDecl =3D Decl->getPreviousDecl())
     if (PrevDecl->TypeForDecl)
       return QualType(Decl->TypeForDecl =3D PrevDecl->TypeForDecl, 0);=20
=20
@@ -2239,7 +2303,7 @@
 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
=20
-  if (const EnumDecl *PrevDecl =3D Decl->getPreviousDeclaration())
+  if (const EnumDecl *PrevDecl =3D Decl->getPreviousDecl())
     if (PrevDecl->TypeForDecl)
       return QualType(Decl->TypeForDecl =3D PrevDecl->TypeForDecl, 0);=20
=20
@@ -2374,6 +2438,7 @@
   TypeSourceInfo *DI =3D CreateTypeSourceInfo(TST);
   TemplateSpecializationTypeLoc TL
     =3D cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
+  TL.setTemplateKeywordLoc(SourceLocation());
   TL.setTemplateNameLoc(NameLoc);
   TL.setLAngleLoc(Args.getLAngleLoc());
   TL.setRAngleLoc(Args.getRAngleLoc());
@@ -2400,6 +2465,17 @@
                                        Underlying);
 }
=20
+#ifndef NDEBUG
+static bool hasAnyPackExpansions(const TemplateArgument *Args,
+                                 unsigned NumArgs) {
+  for (unsigned I =3D 0; I !=3D NumArgs; ++I)
+    if (Args[I].isPackExpansion())
+      return true;
+ =20
+  return true;
+}
+#endif
+
 QualType
 ASTContext::getTemplateSpecializationType(TemplateName Template,
                                           const TemplateArgument *Args,
@@ -2411,16 +2487,18 @@
   if (QualifiedTemplateName *QTN =3D Template.getAsQualifiedTemplateName())
     Template =3D TemplateName(QTN->getTemplateDecl());
  =20
-  bool isTypeAlias =3D=20
+  bool IsTypeAlias =3D=20
     Template.getAsTemplateDecl() &&
     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
-
   QualType CanonType;
   if (!Underlying.isNull())
     CanonType =3D getCanonicalType(Underlying);
   else {
-    assert(!isTypeAlias &&
-           "Underlying type for template alias must be computed by caller"=
);
+    // We can get here with an alias template when the specialization cont=
ains
+    // a pack expansion that does not match up with a parameter pack.
+    assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
+           "Caller must compute aliased type");
+    IsTypeAlias =3D false;
     CanonType =3D getCanonicalTemplateSpecializationType(Template, Args,
                                                        NumArgs);
   }
@@ -2430,13 +2508,11 @@
   // we don't unique and don't want to lose.
   void *Mem =3D Allocate(sizeof(TemplateSpecializationType) +
                        sizeof(TemplateArgument) * NumArgs +
-                       (isTypeAlias ? sizeof(QualType) : 0),
+                       (IsTypeAlias? sizeof(QualType) : 0),
                        TypeAlignment);
   TemplateSpecializationType *Spec
-    =3D new (Mem) TemplateSpecializationType(Template,
-                                           Args, NumArgs,
-                                           CanonType,
-                                         isTypeAlias ? Underlying : QualTy=
pe());
+    =3D new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Cano=
nType,
+                                         IsTypeAlias ? Underlying : QualTy=
pe());
=20
   Types.push_back(Spec);
   return QualType(Spec, 0);
@@ -2448,9 +2524,6 @@
                                                    unsigned NumArgs) const=
 {
   assert(!Template.getAsDependentTemplateName() &&=20
          "No dependent template names here!");
-  assert((!Template.getAsTemplateDecl() ||
-          !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
-         "Underlying type for template alias must be computed by caller");
=20
   // Look through qualified template names.
   if (QualifiedTemplateName *QTN =3D Template.getAsQualifiedTemplateName())
@@ -2677,8 +2750,12 @@
                                 unsigned NumProtocols) {
   if (NumProtocols =3D=3D 0) return true;
=20
+  if (Protocols[0]->getCanonicalDecl() !=3D Protocols[0])
+    return false;
+ =20
   for (unsigned i =3D 1; i !=3D NumProtocols; ++i)
-    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
+    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
+        Protocols[i]->getCanonicalDecl() !=3D Protocols[i])
       return false;
   return true;
 }
@@ -2690,6 +2767,10 @@
   // Sort protocols, keyed by name.
   std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
=20
+  // Canonicalize.
+  for (unsigned I =3D 0, N =3D NumProtocols; I !=3D N; ++I)
+    Protocols[I] =3D Protocols[I]->getCanonicalDecl();
+ =20
   // Remove duplicates.
   ProtocolsEnd =3D std::unique(Protocols, ProtocolsEnd);
   NumProtocols =3D ProtocolsEnd-Protocols;
@@ -2775,11 +2856,21 @@
=20
 /// getObjCInterfaceType - Return the unique reference to the type for the
 /// specified ObjC interface decl. The list of protocols is optional.
-QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) c=
onst {
+QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
+                                          ObjCInterfaceDecl *PrevDecl) con=
st {
   if (Decl->TypeForDecl)
     return QualType(Decl->TypeForDecl, 0);
=20
-  // FIXME: redeclarations?
+  if (PrevDecl) {
+    assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
+    Decl->TypeForDecl =3D PrevDecl->TypeForDecl;
+    return QualType(PrevDecl->TypeForDecl, 0);
+  }
+
+  // Prefer the definition, if there is one.
+  if (const ObjCInterfaceDecl *Def =3D Decl->getDefinition())
+    Decl =3D Def;
+ =20
   void *Mem =3D Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
   ObjCInterfaceType *T =3D new (Mem) ObjCInterfaceType(Decl);
   Decl->TypeForDecl =3D T;
@@ -2833,44 +2924,13 @@
   return QualType(tot, 0);
 }
=20
-/// getDecltypeForExpr - Given an expr, will return the decltype for that
-/// expression, according to the rules in C++0x [dcl.type.simple]p4
-static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Contex=
t) {
-  if (e->isTypeDependent())
-    return Context.DependentTy;
-
-  // If e is an id expression or a class member access, decltype(e) is def=
ined
-  // as the type of the entity named by e.
-  if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(e)) {
-    if (const ValueDecl *VD =3D dyn_cast<ValueDecl>(DRE->getDecl()))
-      return VD->getType();
-  }
-  if (const MemberExpr *ME =3D dyn_cast<MemberExpr>(e)) {
-    if (const FieldDecl *FD =3D dyn_cast<FieldDecl>(ME->getMemberDecl()))
-      return FD->getType();
-  }
-  // If e is a function call or an invocation of an overloaded operator,
-  // (parentheses around e are ignored), decltype(e) is defined as the
-  // return type of that function.
-  if (const CallExpr *CE =3D dyn_cast<CallExpr>(e->IgnoreParens()))
-    return CE->getCallReturnType();
-
-  QualType T =3D e->getType();
-
-  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
-  // defined as T&, otherwise decltype(e) is defined as T.
-  if (e->isLValue())
-    T =3D Context.getLValueReferenceType(T);
-
-  return T;
-}
=20
 /// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
 /// DecltypeType AST's. The only motivation to unique these nodes would be
 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't =
be
 /// an issue. This doesn't effect the type checker, since it operates
-/// on canonical type's (which are always unique).
-QualType ASTContext::getDecltypeType(Expr *e) const {
+/// on canonical types (which are always unique).
+QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) con=
st {
   DecltypeType *dt;
  =20
   // C++0x [temp.type]p2:
@@ -2896,8 +2956,8 @@
       dt =3D Canon;
     }
   } else {
-    QualType T =3D getDecltypeForExpr(e, *this);
-    dt =3D new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(=
T));
+    dt =3D new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,=20
+                                      getCanonicalType(UnderlyingType));
   }
   Types.push_back(dt);
   return QualType(dt, 0);
@@ -2913,7 +2973,7 @@
     new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingTyp=
e,=20
                                                    Kind,
                                  UnderlyingType->isDependentType() ?
-                                    QualType() : UnderlyingType);
+                                 QualType() : getCanonicalType(UnderlyingT=
ype));
   Types.push_back(Ty);
   return QualType(Ty, 0);
 }
@@ -2996,6 +3056,16 @@
   return getFromTargetType(Target->getSizeType());
 }
=20
+/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
+CanQualType ASTContext::getIntMaxType() const {
+  return getFromTargetType(Target->getIntMaxType());
+}
+
+/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
+CanQualType ASTContext::getUIntMaxType() const {
+  return getFromTargetType(Target->getUIntMaxType());
+}
+
 /// getSignedWCharType - Return the type of "signed wchar_t".
 /// Used when in C++, as a GCC extension.
 QualType ASTContext::getSignedWCharType() const {
@@ -3010,7 +3080,7 @@
   return UnsignedIntTy;
 }
=20
-/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
+/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
 QualType ASTContext::getPointerDiffType() const {
   return getFromTargetType(Target->getPtrDiffType(0));
@@ -3047,12 +3117,12 @@
   // We then have to strip that sugar back off with
   // getUnqualifiedDesugaredType(), which is silly.
   const ArrayType *AT =3D
-    dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
+    dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
=20
   // If we don't have an array, just use the results in splitType.
   if (!AT) {
-    quals =3D splitType.second;
-    return QualType(splitType.first, 0);
+    quals =3D splitType.Quals;
+    return QualType(splitType.Ty, 0);
   }
=20
   // Otherwise, recurse on the array's element type.
@@ -3063,13 +3133,13 @@
   // can just use the results in splitType.
   if (elementType =3D=3D unqualElementType) {
     assert(quals.empty()); // from the recursive call
-    quals =3D splitType.second;
-    return QualType(splitType.first, 0);
+    quals =3D splitType.Quals;
+    return QualType(splitType.Ty, 0);
   }
=20
   // Otherwise, add in the qualifiers from the outermost type, then
   // build the type back up.
-  quals.addConsistentQualifiers(splitType.second);
+  quals.addConsistentQualifiers(splitType.Quals);
=20
   if (const ConstantArrayType *CAT =3D dyn_cast<ConstantArrayType>(AT)) {
     return getConstantArrayType(unqualElementType, CAT->getSize(),
@@ -3121,7 +3191,7 @@
     return true;
   }
  =20
-  if (getLangOptions().ObjC1) {
+  if (getLangOpts().ObjC1) {
     const ObjCObjectPointerType *T1OPType =3D T1->getAs<ObjCObjectPointerT=
ype>(),
                                 *T2OPType =3D T2->getAs<ObjCObjectPointerT=
ype>();
     if (T1OPType && T2OPType) {
@@ -3243,8 +3313,11 @@
     case TemplateArgument::Expression:
       return Arg;
=20
-    case TemplateArgument::Declaration:
-      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
+    case TemplateArgument::Declaration: {
+      if (Decl *D =3D Arg.getAsDecl())
+          return TemplateArgument(D->getCanonicalDecl());
+      return TemplateArgument((Decl*)0);
+    }
=20
     case TemplateArgument::Template:
       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()=
));
@@ -3317,26 +3390,13 @@
     // types, e.g.,
     //   typedef typename T::type T1;
     //   typedef typename T1::type T2;
-    if (const DependentNameType *DNT =3D T->getAs<DependentNameType>()) {
-      NestedNameSpecifier *Prefix
-        =3D getCanonicalNestedNameSpecifier(DNT->getQualifier());
-      return NestedNameSpecifier::Create(*this, Prefix,=20
+    if (const DependentNameType *DNT =3D T->getAs<DependentNameType>())
+      return NestedNameSpecifier::Create(*this, DNT->getQualifier(),=20
                            const_cast<IdentifierInfo *>(DNT->getIdentifier=
()));
-    }   =20
-
-    // Do the same thing as above, but with dependent-named specialization=
s.
-    if (const DependentTemplateSpecializationType *DTST
-          =3D T->getAs<DependentTemplateSpecializationType>()) {
-      NestedNameSpecifier *Prefix
-        =3D getCanonicalNestedNameSpecifier(DTST->getQualifier());
-     =20
-      T =3D getDependentTemplateSpecializationType(DTST->getKeyword(),
-                                                 Prefix, DTST->getIdentifi=
er(),
-                                                 DTST->getNumArgs(),
-                                                 DTST->getArgs());
-      T =3D getCanonicalType(T);
-    }
-   =20
+
+    // Otherwise, just canonicalize the type, and force it to be a TypeSpe=
c.
+    // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
+    // first place?
     return NestedNameSpecifier::Create(*this, 0, false,
                                        const_cast<Type*>(T.getTypePtr()));
   }
@@ -3346,8 +3406,7 @@
     return NNS;
   }
=20
-  // Required to silence a GCC warning
-  return 0;
+  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
 }
=20
=20
@@ -3372,10 +3431,10 @@
   // we must propagate them down into the element type.
=20
   SplitQualType split =3D T.getSplitDesugaredType();
-  Qualifiers qs =3D split.second;
+  Qualifiers qs =3D split.Quals;
=20
   // If we have a simple case, just return now.
-  const ArrayType *ATy =3D dyn_cast<ArrayType>(split.first);
+  const ArrayType *ATy =3D dyn_cast<ArrayType>(split.Ty);
   if (ATy =3D=3D 0 || qs.empty())
     return ATy;
=20
@@ -3462,11 +3521,11 @@
   Qualifiers qs;
   while (true) {
     SplitQualType split =3D type.getSplitDesugaredType();
-    const ArrayType *array =3D split.first->getAsArrayTypeUnsafe();
+    const ArrayType *array =3D split.Ty->getAsArrayTypeUnsafe();
     if (!array) break;
=20
     type =3D array->getElementType();
-    qs.addConsistentQualifiers(split.second);
+    qs.addConsistentQualifiers(split.Quals);
   }
=20
   return getQualifiedType(type, qs);
@@ -3508,7 +3567,7 @@
   FloatingRank EltRank =3D getFloatingRank(Size);
   if (Domain->isComplexType()) {
     switch (EltRank) {
-    default: llvm_unreachable("getFloatingRank(): illegal value for rank");
+    case HalfRank: llvm_unreachable("Complex half is not supported");
     case FloatRank:      return FloatComplexTy;
     case DoubleRank:     return DoubleComplexTy;
     case LongDoubleRank: return LongDoubleComplexTy;
@@ -3517,11 +3576,12 @@
=20
   assert(Domain->isRealFloatingType() && "Unknown domain!");
   switch (EltRank) {
-  default: llvm_unreachable("getFloatingRank(): illegal value for rank");
+  case HalfRank: llvm_unreachable("Half ranks are not valid here");
   case FloatRank:      return FloatTy;
   case DoubleRank:     return DoubleTy;
   case LongDoubleRank: return LongDoubleTy;
   }
+  llvm_unreachable("getFloatingRank(): illegal value for rank");
 }
=20
 /// getFloatingTypeOrder - Compare the rank of the two specified floating
@@ -3544,18 +3604,6 @@
 /// or if it is not canonicalized.
 unsigned ASTContext::getIntegerRank(const Type *T) const {
   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
-  if (const EnumType* ET =3D dyn_cast<EnumType>(T))
-    T =3D ET->getDecl()->getPromotionType().getTypePtr();
-
-  if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
-      T->isSpecificBuiltinType(BuiltinType::WChar_U))
-    T =3D getFromTargetType(Target->getWCharType()).getTypePtr();
-
-  if (T->isSpecificBuiltinType(BuiltinType::Char16))
-    T =3D getFromTargetType(Target->getChar16Type()).getTypePtr();
-
-  if (T->isSpecificBuiltinType(BuiltinType::Char32))
-    T =3D getFromTargetType(Target->getChar32Type()).getTypePtr();
=20
   switch (cast<BuiltinType>(T)->getKind()) {
   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
@@ -3625,6 +3673,34 @@
   assert(Promotable->isPromotableIntegerType());
   if (const EnumType *ET =3D Promotable->getAs<EnumType>())
     return ET->getDecl()->getPromotionType();
+
+  if (const BuiltinType *BT =3D Promotable->getAs<BuiltinType>()) {
+    // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
+    // (3.9.1) can be converted to a prvalue of the first of the following
+    // types that can represent all the values of its underlying type:
+    // int, unsigned int, long int, unsigned long int, long long int, or
+    // unsigned long long int [...]
+    // FIXME: Is there some better way to compute this?
+    if (BT->getKind() =3D=3D BuiltinType::WChar_S ||
+        BT->getKind() =3D=3D BuiltinType::WChar_U ||
+        BT->getKind() =3D=3D BuiltinType::Char16 ||
+        BT->getKind() =3D=3D BuiltinType::Char32) {
+      bool FromIsSigned =3D BT->getKind() =3D=3D BuiltinType::WChar_S;
+      uint64_t FromSize =3D getTypeSize(BT);
+      QualType PromoteTypes[] =3D { IntTy, UnsignedIntTy, LongTy, Unsigned=
LongTy,
+                                  LongLongTy, UnsignedLongLongTy };
+      for (size_t Idx =3D 0; Idx < llvm::array_lengthof(PromoteTypes); ++I=
dx) {
+        uint64_t ToSize =3D getTypeSize(PromoteTypes[Idx]);
+        if (FromSize < ToSize ||
+            (FromSize =3D=3D ToSize &&
+             FromIsSigned =3D=3D PromoteTypes[Idx]->isSignedIntegerType()))
+          return PromoteTypes[Idx];
+      }
+      llvm_unreachable("char type should fit into long long");
+    }
+  }
+
+  // At this point, we should have a signed or unsigned integer type.
   if (Promotable->isSignedIntegerType())
     return IntTy;
   uint64_t PromotableSize =3D getTypeSize(Promotable);
@@ -3697,7 +3773,7 @@
 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
                  DeclContext *DC, IdentifierInfo *Id) {
   SourceLocation Loc;
-  if (Ctx.getLangOptions().CPlusPlus)
+  if (Ctx.getLangOpts().CPlusPlus)
     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
   else
     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
@@ -3832,7 +3908,7 @@
 bool ASTContext::BlockRequiresCopying(QualType Ty) const {
   if (Ty->isObjCRetainableType())
     return true;
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     if (const RecordType *RT =3D Ty->getAs<RecordType>()) {
       CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RT->getDecl());
       return RD->hasConstCopyConstructor();
@@ -3857,7 +3933,7 @@
   bool HasCopyAndDispose =3D BlockRequiresCopying(Ty);
=20
   // FIXME: Move up
-  llvm::SmallString<36> Name;
+  SmallString<36> Name;
   llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
                                   ++UniqueBlockByRefTypeID << '_' << DeclN=
ame;
   RecordDecl *T;
@@ -4037,15 +4113,32 @@
   return false;
 }
=20
+/// getObjCEncodingForMethodParameter - Return the encoded type for a sing=
le
+/// method parameter or return type. If Extended, include class names and=20
+/// block object types.
+void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier=
 QT,
+                                                   QualType T, std::string=
& S,
+                                                   bool Extended) const {
+  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
+  getObjCEncodingForTypeQualifier(QT, S);
+  // Encode parameter type.
+  getObjCEncodingForTypeImpl(T, S, true, true, 0,
+                             true     /*OutermostType*/,
+                             false    /*EncodingProperty*/,=20
+                             false    /*StructField*/,=20
+                             Extended /*EncodeBlockParameters*/,=20
+                             Extended /*EncodeClassNames*/);
+}
+
 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
 /// declaration.
 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
-                                              std::string& S) const {
+                                              std::string& S,=20
+                                              bool Extended) const {
   // FIXME: This is not very efficient.
-  // Encode type qualifer, 'in', 'inout', etc. for the return type.
-  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
-  // Encode result type.
-  getObjCEncodingForType(Decl->getResultType(), S);
+  // Encode return type.
+  getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),=20
+                                    Decl->getResultType(), S, Extended);
   // Compute size of all parameters.
   // Start with computing size of a pointer in number of bytes.
   // FIXME: There might(should) be a better way of doing this computation!
@@ -4083,10 +4176,8 @@
         PType =3D PVDecl->getType();
     } else if (PType->isFunctionType())
       PType =3D PVDecl->getType();
-    // Process argument qualifiers for user supplied arguments; such as,
-    // 'in', 'inout', etc.
-    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
-    getObjCEncodingForType(PType, S);
+    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),=20
+                                      PType, S, Extended);
     S +=3D charUnitsToString(ParmOffset);
     ParmOffset +=3D getObjCEncodingTypeSize(PType);
   }
@@ -4113,7 +4204,7 @@
 /// kPropertyGetter =3D 'G',     // followed by getter selector name
 /// kPropertySetter =3D 'S',     // followed by setter selector name
 /// kPropertyInstanceVariable =3D 'V'  // followed by instance variable  n=
ame
-/// kPropertyType =3D 't'              // followed by old-style type encod=
ing.
+/// kPropertyType =3D 'T'              // followed by old-style type encod=
ing.
 /// kPropertyWeak =3D 'W'              // 'weak' property
 /// kPropertyStrong =3D 'P'            // property GC'able
 /// kPropertyNonAtomic =3D 'N'         // property non-atomic
@@ -4293,7 +4384,7 @@
   // information is not especially sensible, but we're stuck with it for
   // compatibility with GCC, although providing it breaks anything that
   // actually uses runtime introspection and wants to work on both runtime=
s...
-  if (!Ctx->getLangOptions().NeXTRuntime) {
+  if (!Ctx->getLangOpts().NeXTRuntime) {
     const RecordDecl *RD =3D FD->getParent();
     const ASTRecordLayout &RL =3D Ctx->getASTRecordLayout(RD);
     S +=3D llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
@@ -4312,7 +4403,9 @@
                                             const FieldDecl *FD,
                                             bool OutermostType,
                                             bool EncodingProperty,
-                                            bool StructField) const {
+                                            bool StructField,
+                                            bool EncodeBlockParameters,
+                                            bool EncodeClassNames) const {
   if (T->getAs<BuiltinType>()) {
     if (FD && FD->isBitField())
       return EncodeBitField(this, S, T, FD);
@@ -4491,8 +4584,40 @@
     return;
   }
=20
-  if (T->isBlockPointerType()) {
+  if (const BlockPointerType *BT =3D T->getAs<BlockPointerType>()) {
     S +=3D "@?"; // Unlike a pointer-to-function, which is "^?".
+    if (EncodeBlockParameters) {
+      const FunctionType *FT =3D BT->getPointeeType()->getAs<FunctionType>=
();
+     =20
+      S +=3D '<';
+      // Block return type
+      getObjCEncodingForTypeImpl(FT->getResultType(), S,=20
+                                 ExpandPointedToStructures, ExpandStructur=
es,=20
+                                 FD,=20
+                                 false /* OutermostType */,=20
+                                 EncodingProperty,=20
+                                 false /* StructField */,=20
+                                 EncodeBlockParameters,=20
+                                 EncodeClassNames);
+      // Block self
+      S +=3D "@?";
+      // Block parameters
+      if (const FunctionProtoType *FPT =3D dyn_cast<FunctionProtoType>(FT)=
) {
+        for (FunctionProtoType::arg_type_iterator I =3D FPT->arg_type_begi=
n(),
+               E =3D FPT->arg_type_end(); I && (I !=3D E); ++I) {
+          getObjCEncodingForTypeImpl(*I, S,=20
+                                     ExpandPointedToStructures,=20
+                                     ExpandStructures,=20
+                                     FD,=20
+                                     false /* OutermostType */,=20
+                                     EncodingProperty,=20
+                                     false /* StructField */,=20
+                                     EncodeBlockParameters,=20
+                                     EncodeClassNames);
+        }
+      }
+      S +=3D '>';
+    }
     return;
   }
=20
@@ -4538,7 +4663,7 @@
       getObjCEncodingForTypeImpl(getObjCIdType(), S,
                                  ExpandPointedToStructures,
                                  ExpandStructures, FD);
-      if (FD || EncodingProperty) {
+      if (FD || EncodingProperty || EncodeClassNames) {
         // Note that we do extended encoding of protocol qualifer list
         // Only when doing ivar or property encoding.
         S +=3D '"';
@@ -4567,7 +4692,8 @@
     }
=20
     S +=3D '@';
-    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
+    if (OPT->getInterfaceDecl() &&=20
+        (FD || EncodingProperty || EncodeClassNames)) {
       S +=3D '"';
       S +=3D OPT->getInterfaceDecl()->getIdentifier()->getName();
       for (ObjCObjectPointerType::qual_iterator I =3D OPT->qual_begin(),
@@ -4780,10 +4906,6 @@
   return ObjCSelDecl;
 }
=20
-void ASTContext::setObjCProtoType(QualType QT) {
-  ObjCProtoType =3D QT;
-}
-
 TypedefDecl *ASTContext::getObjCClassDecl() const {
   if (!ObjCClassDecl) {
     QualType T =3D getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
@@ -4798,6 +4920,19 @@
   return ObjCClassDecl;
 }
=20
+ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
+  if (!ObjCProtocolClassDecl) {
+    ObjCProtocolClassDecl=20
+      =3D ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),=20
+                                  SourceLocation(),
+                                  &Idents.get("Protocol"),
+                                  /*PrevDecl=3D*/0,
+                                  SourceLocation(), true);   =20
+  }
+ =20
+  return ObjCProtocolClassDecl;
+}
+
 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
   assert(ObjCConstantStringType.isNull() &&
          "'NSConstantString' type already set!");
@@ -4987,10 +5122,10 @@
 /// garbage collection attribute.
 ///
 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
-  if (getLangOptions().getGC() =3D=3D LangOptions::NonGC)
+  if (getLangOpts().getGC() =3D=3D LangOptions::NonGC)
     return Qualifiers::GCNone;
=20
-  assert(getLangOptions().ObjC1);
+  assert(getLangOpts().ObjC1);
   Qualifiers::GC GCAttrs =3D Ty.getObjCGCAttr();
=20
   // Default behaviour under objective-C's gc is for ObjC pointers
@@ -5059,7 +5194,7 @@
 bool
 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
                                            ObjCProtocolDecl *rProto) const=
 {
-  if (lProto =3D=3D rProto)
+  if (declaresSameEntity(lProto, rProto))
     return true;
   for (ObjCProtocolDecl::protocol_iterator PI =3D rProto->protocol_begin(),
        E =3D rProto->protocol_end(); PI !=3D E; ++PI)
@@ -5360,7 +5495,7 @@
   const ObjCObjectType *RHS =3D Rptr->getObjectType();
   const ObjCInterfaceDecl* LDecl =3D LHS->getInterface();
   const ObjCInterfaceDecl* RDecl =3D RHS->getInterface();
-  if (!LDecl || !RDecl || (LDecl =3D=3D RDecl))
+  if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
     return QualType();
  =20
   do {
@@ -5484,7 +5619,7 @@
 /// same. See 6.7.[2,3,5] for additional rules.
 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
                                     bool CompareUnqualified) {
-  if (getLangOptions().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     return hasSameType(LHS, RHS);
  =20
   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
@@ -5791,14 +5926,23 @@
     // Compatibility is based on the underlying type, not the promotion
     // type.
     if (const EnumType* ETy =3D LHS->getAs<EnumType>()) {
-      if (ETy->getDecl()->getIntegerType() =3D=3D RHSCan.getUnqualifiedTyp=
e())
+      QualType TINT =3D ETy->getDecl()->getIntegerType();
+      if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
         return RHS;
     }
     if (const EnumType* ETy =3D RHS->getAs<EnumType>()) {
-      if (ETy->getDecl()->getIntegerType() =3D=3D LHSCan.getUnqualifiedTyp=
e())
+      QualType TINT =3D ETy->getDecl()->getIntegerType();
+      if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
         return LHS;
     }
-
+    // allow block pointer type to match an 'id' type.
+    if (OfBlockPointer && !BlockReturnType) {
+       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
+         return LHS;
+      if (RHS->isObjCIdType() && LHS->isBlockPointerType())
+        return RHS;
+    }
+   =20
     return QualType();
   }
=20
@@ -5959,7 +6103,7 @@
                                           LHS->getAs<ObjCObjectPointerType=
>(),
                                           RHS->getAs<ObjCObjectPointerType=
>(),
                                           BlockReturnType))
-      return LHS;
+        return LHS;
       return QualType();
     }
     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
@@ -5967,10 +6111,10 @@
       return LHS;
=20
     return QualType();
-    }
-  }
-
-  return QualType();
+  }
+  }
+
+  llvm_unreachable("Invalid Type::Class!");
 }
=20
 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
@@ -6333,6 +6477,9 @@
     case 'D':
       Type =3D Context.getVolatileType(Type);
       break;
+    case 'R':
+      Type =3D Type.withRestrict();
+      break;
     }
   }
  =20
@@ -6425,7 +6572,7 @@
   if (!FD->isInlined())
     return External;
    =20
-  if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
+  if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
     // GNU or C99 inline semantics. Determine whether this symbol should be
     // externally visible.
     if (FD->isInlineDefinitionExternallyVisible())
@@ -6457,7 +6604,7 @@
     TSK =3D VD->getTemplateSpecializationKind();
=20
   Linkage L =3D VD->getLinkage();
-  if (L =3D=3D ExternalLinkage && getLangOptions().CPlusPlus &&
+  if (L =3D=3D ExternalLinkage && getLangOpts().CPlusPlus &&
       VD->getType()->getLinkage() =3D=3D UniqueExternalLinkage)
     L =3D UniqueExternalLinkage;
=20
@@ -6485,7 +6632,7 @@
     }
   }
=20
-  return GVA_StrongExternal;
+  llvm_unreachable("Invalid Linkage!");
 }
=20
 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
@@ -6602,6 +6749,13 @@
     + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
 }
=20
+unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
+  CXXRecordDecl *Lambda =3D CallOperator->getParent();
+  return LambdaMangleContexts[Lambda->getDeclContext()]
+           .getManglingNumber(CallOperator);
+}
+
+
 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int inde=
x) {
   ParamIndices[D] =3D index;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ASTDiagnostic.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ASTDiagnostic.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ASTDiagnostic.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -154,26 +154,34 @@
 ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
                               const DiagnosticsEngine::ArgumentValue *Prev=
Args,
                               unsigned NumPrevArgs,
-                              SmallVectorImpl<intptr_t> &QualTypeVals) {
+                              ArrayRef<intptr_t> QualTypeVals) {
   // FIXME: Playing with std::string is really slow.
   bool ForceAKA =3D false;
   QualType CanTy =3D Ty.getCanonicalType();
   std::string S =3D Ty.getAsString(Context.getPrintingPolicy());
   std::string CanS =3D CanTy.getAsString(Context.getPrintingPolicy());
=20
-  for (SmallVectorImpl<intptr_t>::iterator I =3D QualTypeVals.begin(),
-       E =3D QualTypeVals.end(); I !=3D E; ++I) {
+  for (unsigned I =3D 0, E =3D QualTypeVals.size(); I !=3D E; ++I) {
     QualType CompareTy =3D
-        QualType::getFromOpaquePtr(reinterpret_cast<void*>(*I));
+        QualType::getFromOpaquePtr(reinterpret_cast<void*>(QualTypeVals[I]=
));
+    if (CompareTy.isNull())
+      continue;
     if (CompareTy =3D=3D Ty)
       continue;  // Same types
     QualType CompareCanTy =3D CompareTy.getCanonicalType();
     if (CompareCanTy =3D=3D CanTy)
       continue;  // Same canonical types
     std::string CompareS =3D CompareTy.getAsString(Context.getPrintingPoli=
cy());
-    if (CompareS !=3D S)
-      continue;  // Original strings are different
-    std::string CompareCanS =3D CompareCanTy.getAsString(Context.getPrinti=
ngPolicy());
+    bool aka;
+    QualType CompareDesugar =3D Desugar(Context, CompareTy, aka);
+    std::string CompareDesugarStr =3D
+        CompareDesugar.getAsString(Context.getPrintingPolicy());
+    if (CompareS !=3D S && CompareDesugarStr !=3D S)
+      continue;  // The type string is different than the comparison string
+                 // and the desugared comparison string.
+    std::string CompareCanS =3D
+        CompareCanTy.getAsString(Context.getPrintingPolicy());
+   =20
     if (CompareCanS =3D=3D CanS)
       continue;  // No new info from canonical type
=20
@@ -228,7 +236,7 @@
     unsigned NumPrevArgs,
     SmallVectorImpl<char> &Output,
     void *Cookie,
-    SmallVectorImpl<intptr_t> &QualTypeVals) {
+    ArrayRef<intptr_t> QualTypeVals) {
   ASTContext &Context =3D *static_cast<ASTContext*>(Cookie);
  =20
   std::string S;
@@ -286,7 +294,7 @@
      =20
       if (DC->isTranslationUnit()) {
         // FIXME: Get these strings from some localized place
-        if (Context.getLangOptions().CPlusPlus)
+        if (Context.getLangOpts().CPlusPlus)
           S =3D "the global namespace";
         else
           S =3D "the global scope";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ASTImporter.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -25,9 +25,7 @@
 #include "llvm/Support/MemoryBuffer.h"
 #include <deque>
=20
-using namespace clang;
-
-namespace {
+namespace clang {
   class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
                           public DeclVisitor<ASTNodeImporter, Decl *>,
                           public StmtVisitor<ASTNodeImporter, Stmt *> {
@@ -80,7 +78,7 @@
     QualType VisitObjCObjectType(const ObjCObjectType *T);
     QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
                            =20
-    // Importing declarations
+    // Importing declarations                           =20
     bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,=20
                          DeclContext *&LexicalDC, DeclarationName &Name,=20
                          SourceLocation &Loc);
@@ -88,10 +86,33 @@
     void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
                                   DeclarationNameInfo& To);
     void ImportDeclContext(DeclContext *FromDC, bool ForceImport =3D false=
);
+                       =20
+    /// \brief What we should import from the definition.
+    enum ImportDefinitionKind {=20
+      /// \brief Import the default subset of the definition, which might =
be
+      /// nothing (if minimal import is set) or might be everything (if mi=
nimal
+      /// import is not set).
+      IDK_Default,
+      /// \brief Import everything.
+      IDK_Everything,
+      /// \brief Import only the bare bones needed to establish a valid
+      /// DeclContext.
+      IDK_Basic
+    };
+
+    bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
+      return IDK =3D=3D IDK_Everything ||
+             (IDK =3D=3D IDK_Default && !Importer.isMinimalImport());
+    }
+
     bool ImportDefinition(RecordDecl *From, RecordDecl *To,=20
-                          bool ForceImport =3D false);
+                          ImportDefinitionKind Kind =3D IDK_Default);
     bool ImportDefinition(EnumDecl *From, EnumDecl *To,
-                          bool ForceImport =3D false);
+                          ImportDefinitionKind Kind =3D IDK_Default);
+    bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
+                          ImportDefinitionKind Kind =3D IDK_Default);
+    bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
+                          ImportDefinitionKind Kind =3D IDK_Default);
     TemplateParameterList *ImportTemplateParameterList(
                                                  TemplateParameterList *Pa=
rams);
     TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
@@ -102,6 +123,7 @@
     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
     bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
     Decl *VisitDecl(Decl *D);
+    Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
     Decl *VisitNamespaceDecl(NamespaceDecl *D);
     Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
     Decl *VisitTypedefDecl(TypedefDecl *D);
@@ -128,8 +150,6 @@
     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
     Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
-    Decl *VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
-    Decl *VisitObjCClassDecl(ObjCClassDecl *D);
     Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
     Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
     Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
@@ -154,6 +174,7 @@
     Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
   };
 }
+using namespace clang;
=20
 //------------------------------------------------------------------------=
----
 // Structural Equivalence
@@ -304,6 +325,8 @@
     return IsSameValue(*Arg1.getAsIntegral(), *Arg2.getAsIntegral());
      =20
   case TemplateArgument::Declaration:
+    if (!Arg1.getAsDecl() || !Arg2.getAsDecl())
+      return !Arg1.getAsDecl() && !Arg2.getAsDecl();
     return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDe=
cl());
      =20
   case TemplateArgument::Template:
@@ -334,7 +357,6 @@
   }
  =20
   llvm_unreachable("Invalid template argument kind");
-  return true;
 }
=20
 /// \brief Determine structural equivalence for the common part of array=20
@@ -945,10 +967,10 @@
                                       Base1->getType(), Base2->getType()))=
 {
           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsi=
stent)
             << Context.C2.getTypeDeclType(D2);
-          Context.Diag2(Base2->getSourceRange().getBegin(), diag::note_odr=
_base)
+          Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
             << Base2->getType()
             << Base2->getSourceRange();
-          Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr=
_base)
+          Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
             << Base1->getType()
             << Base1->getSourceRange();
           return false;
@@ -958,10 +980,10 @@
         if (Base1->isVirtual() !=3D Base2->isVirtual()) {
           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsi=
stent)
             << Context.C2.getTypeDeclType(D2);
-          Context.Diag2(Base2->getSourceRange().getBegin(),
+          Context.Diag2(Base2->getLocStart(),
                         diag::note_odr_virtual_base)
             << Base2->isVirtual() << Base2->getSourceRange();
-          Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr=
_base)
+          Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
             << Base1->isVirtual()
             << Base1->getSourceRange();
           return false;
@@ -971,7 +993,7 @@
       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsisten=
t)
         << Context.C2.getTypeDeclType(D2);
       const CXXBaseSpecifier *Base1 =3D D1CXX->bases_begin();
-      Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_bas=
e)
+      Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
         << Base1->getType()
         << Base1->getSourceRange();
       Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
@@ -1324,82 +1346,43 @@
=20
 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
   switch (T->getKind()) {
-  case BuiltinType::Void: return Importer.getToContext().VoidTy;
-  case BuiltinType::Bool: return Importer.getToContext().BoolTy;
-   =20
+#define SHARED_SINGLETON_TYPE(Expansion)
+#define BUILTIN_TYPE(Id, SingletonId) \
+  case BuiltinType::Id: return Importer.getToContext().SingletonId;
+#include "clang/AST/BuiltinTypes.def"
+
+  // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
+  // context supports C++.
+
+  // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
+  // context supports ObjC.
+
   case BuiltinType::Char_U:
     // The context we're importing from has an unsigned 'char'. If we're=20
     // importing into a context with a signed 'char', translate to=20
     // 'unsigned char' instead.
-    if (Importer.getToContext().getLangOptions().CharIsSigned)
+    if (Importer.getToContext().getLangOpts().CharIsSigned)
       return Importer.getToContext().UnsignedCharTy;
    =20
     return Importer.getToContext().CharTy;
=20
-  case BuiltinType::UChar: return Importer.getToContext().UnsignedCharTy;
-   =20
-  case BuiltinType::Char16:
-    // FIXME: Make sure that the "to" context supports C++!
-    return Importer.getToContext().Char16Ty;
-   =20
-  case BuiltinType::Char32:=20
-    // FIXME: Make sure that the "to" context supports C++!
-    return Importer.getToContext().Char32Ty;
-
-  case BuiltinType::UShort: return Importer.getToContext().UnsignedShortTy;
-  case BuiltinType::UInt: return Importer.getToContext().UnsignedIntTy;
-  case BuiltinType::ULong: return Importer.getToContext().UnsignedLongTy;
-  case BuiltinType::ULongLong:=20
-    return Importer.getToContext().UnsignedLongLongTy;
-  case BuiltinType::UInt128: return Importer.getToContext().UnsignedInt128=
Ty;
-   =20
   case BuiltinType::Char_S:
     // The context we're importing from has an unsigned 'char'. If we're=20
     // importing into a context with a signed 'char', translate to=20
     // 'unsigned char' instead.
-    if (!Importer.getToContext().getLangOptions().CharIsSigned)
+    if (!Importer.getToContext().getLangOpts().CharIsSigned)
       return Importer.getToContext().SignedCharTy;
    =20
     return Importer.getToContext().CharTy;
=20
-  case BuiltinType::SChar: return Importer.getToContext().SignedCharTy;
   case BuiltinType::WChar_S:
   case BuiltinType::WChar_U:
     // FIXME: If not in C++, shall we translate to the C equivalent of
     // wchar_t?
     return Importer.getToContext().WCharTy;
-   =20
-  case BuiltinType::Short : return Importer.getToContext().ShortTy;
-  case BuiltinType::Int : return Importer.getToContext().IntTy;
-  case BuiltinType::Long : return Importer.getToContext().LongTy;
-  case BuiltinType::LongLong : return Importer.getToContext().LongLongTy;
-  case BuiltinType::Int128 : return Importer.getToContext().Int128Ty;
-  case BuiltinType::Half: return Importer.getToContext().HalfTy;
-  case BuiltinType::Float: return Importer.getToContext().FloatTy;
-  case BuiltinType::Double: return Importer.getToContext().DoubleTy;
-  case BuiltinType::LongDouble: return Importer.getToContext().LongDoubleT=
y;
-
-  case BuiltinType::NullPtr:
-    // FIXME: Make sure that the "to" context supports C++0x!
-    return Importer.getToContext().NullPtrTy;
-   =20
-  case BuiltinType::Overload: return Importer.getToContext().OverloadTy;
-  case BuiltinType::Dependent: return Importer.getToContext().DependentTy;
-  case BuiltinType::UnknownAny: return Importer.getToContext().UnknownAnyT=
y;
-  case BuiltinType::BoundMember: return Importer.getToContext().BoundMembe=
rTy;
-
-  case BuiltinType::ObjCId:
-    // FIXME: Make sure that the "to" context supports Objective-C!
-    return Importer.getToContext().ObjCBuiltinIdTy;
-   =20
-  case BuiltinType::ObjCClass:
-    return Importer.getToContext().ObjCBuiltinClassTy;
-
-  case BuiltinType::ObjCSel:
-    return Importer.getToContext().ObjCBuiltinSelTy;
   }
- =20
-  return QualType();
+
+  llvm_unreachable("Invalid BuiltinType Kind!");
 }
=20
 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
@@ -1600,7 +1583,11 @@
   if (!ToExpr)
     return QualType();
  =20
-  return Importer.getToContext().getDecltypeType(ToExpr);
+  QualType UnderlyingType =3D Importer.Import(T->getUnderlyingType());
+  if (UnderlyingType.isNull())
+    return QualType();
+
+  return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
 }
=20
 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType=
 *T) {
@@ -1813,11 +1800,11 @@
     To.setNamedTypeInfo(Importer.Import(FromTInfo));
     return;
   }
-    llvm_unreachable("Unknown name kind.");
   }
+  llvm_unreachable("Unknown name kind.");
 }
=20
-void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImp=
ort) {
+void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImp=
ort) { =20
   if (Importer.isMinimalImport() && !ForceImport) {
     Importer.ImportContext(FromDC);
     return;
@@ -1831,16 +1818,75 @@
 }
=20
 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,=20
-                                       bool ForceImport) {
-  if (To->getDefinition() || To->isBeingDefined())
+                                       ImportDefinitionKind Kind) {
+  if (To->getDefinition() || To->isBeingDefined()) {
+    if (Kind =3D=3D IDK_Everything)
+      ImportDeclContext(From, /*ForceImport=3D*/true);
+   =20
     return false;
+  }
  =20
   To->startDefinition();
  =20
   // Add base classes.
   if (CXXRecordDecl *ToCXX =3D dyn_cast<CXXRecordDecl>(To)) {
     CXXRecordDecl *FromCXX =3D cast<CXXRecordDecl>(From);
-   =20
+
+    struct CXXRecordDecl::DefinitionData &ToData =3D ToCXX->data();
+    struct CXXRecordDecl::DefinitionData &FromData =3D FromCXX->data();
+    ToData.UserDeclaredConstructor =3D FromData.UserDeclaredConstructor;
+    ToData.UserDeclaredCopyConstructor =3D FromData.UserDeclaredCopyConstr=
uctor;
+    ToData.UserDeclaredMoveConstructor =3D FromData.UserDeclaredMoveConstr=
uctor;
+    ToData.UserDeclaredCopyAssignment =3D FromData.UserDeclaredCopyAssignm=
ent;
+    ToData.UserDeclaredMoveAssignment =3D FromData.UserDeclaredMoveAssignm=
ent;
+    ToData.UserDeclaredDestructor =3D FromData.UserDeclaredDestructor;
+    ToData.Aggregate =3D FromData.Aggregate;
+    ToData.PlainOldData =3D FromData.PlainOldData;
+    ToData.Empty =3D FromData.Empty;
+    ToData.Polymorphic =3D FromData.Polymorphic;
+    ToData.Abstract =3D FromData.Abstract;
+    ToData.IsStandardLayout =3D FromData.IsStandardLayout;
+    ToData.HasNoNonEmptyBases =3D FromData.HasNoNonEmptyBases;
+    ToData.HasPrivateFields =3D FromData.HasPrivateFields;
+    ToData.HasProtectedFields =3D FromData.HasProtectedFields;
+    ToData.HasPublicFields =3D FromData.HasPublicFields;
+    ToData.HasMutableFields =3D FromData.HasMutableFields;
+    ToData.HasOnlyCMembers =3D FromData.HasOnlyCMembers;
+    ToData.HasTrivialDefaultConstructor =3D FromData.HasTrivialDefaultCons=
tructor;
+    ToData.HasConstexprNonCopyMoveConstructor
+      =3D FromData.HasConstexprNonCopyMoveConstructor;
+    ToData.DefaultedDefaultConstructorIsConstexpr
+      =3D FromData.DefaultedDefaultConstructorIsConstexpr;
+    ToData.DefaultedCopyConstructorIsConstexpr
+      =3D FromData.DefaultedCopyConstructorIsConstexpr;
+    ToData.DefaultedMoveConstructorIsConstexpr
+      =3D FromData.DefaultedMoveConstructorIsConstexpr;
+    ToData.HasConstexprDefaultConstructor
+      =3D FromData.HasConstexprDefaultConstructor;
+    ToData.HasConstexprCopyConstructor =3D FromData.HasConstexprCopyConstr=
uctor;
+    ToData.HasConstexprMoveConstructor =3D FromData.HasConstexprMoveConstr=
uctor;
+    ToData.HasTrivialCopyConstructor =3D FromData.HasTrivialCopyConstructo=
r;
+    ToData.HasTrivialMoveConstructor =3D FromData.HasTrivialMoveConstructo=
r;
+    ToData.HasTrivialCopyAssignment =3D FromData.HasTrivialCopyAssignment;
+    ToData.HasTrivialMoveAssignment =3D FromData.HasTrivialMoveAssignment;
+    ToData.HasTrivialDestructor =3D FromData.HasTrivialDestructor;
+    ToData.HasIrrelevantDestructor =3D FromData.HasIrrelevantDestructor;
+    ToData.HasNonLiteralTypeFieldsOrBases
+      =3D FromData.HasNonLiteralTypeFieldsOrBases;
+    // ComputedVisibleConversions not imported.
+    ToData.UserProvidedDefaultConstructor
+      =3D FromData.UserProvidedDefaultConstructor;
+    ToData.DeclaredDefaultConstructor =3D FromData.DeclaredDefaultConstruc=
tor;
+    ToData.DeclaredCopyConstructor =3D FromData.DeclaredCopyConstructor;
+    ToData.DeclaredMoveConstructor =3D FromData.DeclaredMoveConstructor;
+    ToData.DeclaredCopyAssignment =3D FromData.DeclaredCopyAssignment;
+    ToData.DeclaredMoveAssignment =3D FromData.DeclaredMoveAssignment;
+    ToData.DeclaredDestructor =3D FromData.DeclaredDestructor;
+    ToData.FailedImplicitMoveConstructor
+      =3D FromData.FailedImplicitMoveConstructor;
+    ToData.FailedImplicitMoveAssignment =3D FromData.FailedImplicitMoveAss=
ignment;
+    ToData.IsLambda =3D FromData.IsLambda;
+
     SmallVector<CXXBaseSpecifier *, 4> Bases;
     for (CXXRecordDecl::base_class_iterator=20
                   Base1 =3D FromCXX->bases_begin(),
@@ -1871,15 +1917,20 @@
       ToCXX->setBases(Bases.data(), Bases.size());
   }
  =20
-  ImportDeclContext(From, ForceImport);
+  if (shouldForceImportDeclContext(Kind))
+    ImportDeclContext(From, /*ForceImport=3D*/true);
+ =20
   To->completeDefinition();
   return false;
 }
=20
 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,=20
-                                       bool ForceImport) {
-  if (To->getDefinition() || To->isBeingDefined())
+                                       ImportDefinitionKind Kind) {
+  if (To->getDefinition() || To->isBeingDefined()) {
+    if (Kind =3D=3D IDK_Everything)
+      ImportDeclContext(From, /*ForceImport=3D*/true);
     return false;
+  }
  =20
   To->startDefinition();
=20
@@ -1890,8 +1941,9 @@
   QualType ToPromotionType =3D Importer.Import(From->getPromotionType());
   if (ToPromotionType.isNull())
     return true;
- =20
-  ImportDeclContext(From, ForceImport);
+
+  if (shouldForceImportDeclContext(Kind))
+    ImportDeclContext(From, /*ForceImport=3D*/true);
  =20
   // FIXME: we might need to merge the number of positive or negative bits
   // if the enumerator lists don't match.
@@ -1983,7 +2035,6 @@
   }
  =20
   llvm_unreachable("Invalid template argument kind");
-  return TemplateArgument();
 }
=20
 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *From=
Args,
@@ -2029,6 +2080,15 @@
   return 0;
 }
=20
+Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
+  TranslationUnitDecl *ToD =3D=20
+    Importer.getToContext().getTranslationUnitDecl();
+   =20
+  Importer.Imported(D, ToD);
+   =20
+  return ToD;
+}
+
 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
   // Import the major distinguishing characteristics of this namespace.
   DeclContext *DC, *LexicalDC;
@@ -2074,10 +2134,12 @@
   NamespaceDecl *ToNamespace =3D MergeWithNamespace;
   if (!ToNamespace) {
     ToNamespace =3D NamespaceDecl::Create(Importer.getToContext(), DC,
+                                        D->isInline(),
                                         Importer.Import(D->getLocStart()),
-                                        Loc, Name.getAsIdentifierInfo());
+                                        Loc, Name.getAsIdentifierInfo(),
+                                        /*PrevDecl=3D*/0);
     ToNamespace->setLexicalDeclContext(LexicalDC);
-    LexicalDC->addDecl(ToNamespace);
+    LexicalDC->addDeclInternal(ToNamespace);
    =20
     // If this is an anonymous namespace, register it as the anonymous
     // namespace within its context.
@@ -2156,7 +2218,7 @@
   ToTypedef->setAccess(D->getAccess());
   ToTypedef->setLexicalDeclContext(LexicalDC);
   Importer.Imported(D, ToTypedef);
-  LexicalDC->addDecl(ToTypedef);
+  LexicalDC->addDeclInternal(ToTypedef);
  =20
   return ToTypedef;
 }
@@ -2183,7 +2245,7 @@
   if (!SearchName && D->getTypedefNameForAnonDecl()) {
     SearchName =3D Importer.Import(D->getTypedefNameForAnonDecl()->getDecl=
Name());
     IDNS =3D Decl::IDNS_Ordinary;
-  } else if (Importer.getToContext().getLangOptions().CPlusPlus)
+  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
     IDNS |=3D Decl::IDNS_Ordinary;
  =20
   // We may already have an enum of the same name; try to find and match i=
t.
@@ -2227,7 +2289,7 @@
   D2->setAccess(D->getAccess());
   D2->setLexicalDeclContext(LexicalDC);
   Importer.Imported(D, D2);
-  LexicalDC->addDecl(D2);
+  LexicalDC->addDeclInternal(D2);
=20
   // Import the integer type.
   QualType ToIntegerType =3D Importer.Import(D->getIntegerType());
@@ -2268,7 +2330,7 @@
   if (!SearchName && D->getTypedefNameForAnonDecl()) {
     SearchName =3D Importer.Import(D->getTypedefNameForAnonDecl()->getDecl=
Name());
     IDNS =3D Decl::IDNS_Ordinary;
-  } else if (Importer.getToContext().getLangOptions().CPlusPlus)
+  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
     IDNS |=3D Decl::IDNS_Ordinary;
=20
   // We may already have a record of the same name; try to find and match =
it.
@@ -2332,12 +2394,12 @@
    =20
     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
     D2->setLexicalDeclContext(LexicalDC);
-    LexicalDC->addDecl(D2);
+    LexicalDC->addDeclInternal(D2);
   }
  =20
   Importer.Imported(D, D2);
=20
-  if (D->isCompleteDefinition() && ImportDefinition(D, D2))
+  if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
     return 0;
  =20
   return D2;
@@ -2389,7 +2451,7 @@
   ToEnumerator->setAccess(D->getAccess());
   ToEnumerator->setLexicalDeclContext(LexicalDC);
   Importer.Imported(D, ToEnumerator);
-  LexicalDC->addDecl(ToEnumerator);
+  LexicalDC->addDeclInternal(ToEnumerator);
   return ToEnumerator;
 }
=20
@@ -2425,7 +2487,7 @@
           // Sema::IsOverload out to the AST library.
          =20
           // Function overloading is okay in C++.
-          if (Importer.getToContext().getLangOptions().CPlusPlus)
+          if (Importer.getToContext().getLangOpts().CPlusPlus)
             continue;
          =20
           // Complain about inconsistent function types.
@@ -2530,14 +2592,14 @@
   // Set the parameters.
   for (unsigned I =3D 0, N =3D Parameters.size(); I !=3D N; ++I) {
     Parameters[I]->setOwningFunction(ToFunction);
-    ToFunction->addDecl(Parameters[I]);
+    ToFunction->addDeclInternal(Parameters[I]);
   }
   ToFunction->setParams(Parameters);
=20
   // FIXME: Other bits to merge?
=20
   // Add this function to the lexical context.
-  LexicalDC->addDecl(ToFunction);
+  LexicalDC->addDeclInternal(ToFunction);
=20
   return ToFunction;
 }
@@ -2605,7 +2667,7 @@
   if (ToField->hasInClassInitializer())
     ToField->setInClassInitializer(D->getInClassInitializer());
   Importer.Imported(D, ToField);
-  LexicalDC->addDecl(ToField);
+  LexicalDC->addDeclInternal(ToField);
   return ToField;
 }
=20
@@ -2661,7 +2723,7 @@
   ToIndirectField->setAccess(D->getAccess());
   ToIndirectField->setLexicalDeclContext(LexicalDC);
   Importer.Imported(D, ToIndirectField);
-  LexicalDC->addDecl(ToIndirectField);
+  LexicalDC->addDeclInternal(ToIndirectField);
   return ToIndirectField;
 }
=20
@@ -2710,7 +2772,7 @@
                                               BitWidth, D->getSynthesize()=
);
   ToIvar->setLexicalDeclContext(LexicalDC);
   Importer.Imported(D, ToIvar);
-  LexicalDC->addDecl(ToIvar);
+  LexicalDC->addDeclInternal(ToIvar);
   return ToIvar;
  =20
 }
@@ -2791,6 +2853,11 @@
         } else {
           Expr *Init =3D Importer.Import(DDef->getInit());
           MergeWithVar->setInit(Init);
+          if (DDef->isInitKnownICE()) {
+            EvaluatedStmt *Eval =3D MergeWithVar->ensureEvaluatedStmt();
+            Eval->CheckedICE =3D true;
+            Eval->IsICE =3D DDef->isInitICE();
+          }
         }
       }
      =20
@@ -2823,7 +2890,7 @@
   ToVar->setAccess(D->getAccess());
   ToVar->setLexicalDeclContext(LexicalDC);
   Importer.Imported(D, ToVar);
-  LexicalDC->addDecl(ToVar);
+  LexicalDC->addDeclInternal(ToVar);
=20
   // Merge the initializer.
   // FIXME: Can we really import any initializer? Alternatively, we could =
force
@@ -3002,7 +3069,7 @@
   // Set the parameters.
   for (unsigned I =3D 0, N =3D ToParams.size(); I !=3D N; ++I) {
     ToParams[I]->setOwningFunction(ToMethod);
-    ToMethod->addDecl(ToParams[I]);
+    ToMethod->addDeclInternal(ToParams[I]);
   }
   SmallVector<SourceLocation, 12> SelLocs;
   D->getSelectorLocs(SelLocs);
@@ -3010,7 +3077,7 @@
=20
   ToMethod->setLexicalDeclContext(LexicalDC);
   Importer.Imported(D, ToMethod);
-  LexicalDC->addDecl(ToMethod);
+  LexicalDC->addDeclInternal(ToMethod);
   return ToMethod;
 }
=20
@@ -3037,9 +3104,11 @@
                                           Loc,=20
                                        Importer.Import(D->getCategoryNameL=
oc()),=20
                                           Name.getAsIdentifierInfo(),
-                                          ToInterface);
+                                          ToInterface,
+                                       Importer.Import(D->getIvarLBraceLoc=
()),
+                                       Importer.Import(D->getIvarRBraceLoc=
()));
     ToCategory->setLexicalDeclContext(LexicalDC);
-    LexicalDC->addDecl(ToCategory);
+    LexicalDC->addDeclInternal(ToCategory);
     Importer.Imported(D, ToCategory);
    =20
     // Import protocols
@@ -3084,7 +3153,59 @@
   return ToCategory;
 }
=20
+bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,=20
+                                       ObjCProtocolDecl *To,
+                                       ImportDefinitionKind Kind) {
+  if (To->getDefinition()) {
+    if (shouldForceImportDeclContext(Kind))
+      ImportDeclContext(From);
+    return false;
+  }
+
+  // Start the protocol definition
+  To->startDefinition();
+ =20
+  // Import protocols
+  SmallVector<ObjCProtocolDecl *, 4> Protocols;
+  SmallVector<SourceLocation, 4> ProtocolLocs;
+  ObjCProtocolDecl::protocol_loc_iterator=20
+  FromProtoLoc =3D From->protocol_loc_begin();
+  for (ObjCProtocolDecl::protocol_iterator FromProto =3D From->protocol_be=
gin(),
+                                        FromProtoEnd =3D From->protocol_en=
d();
+       FromProto !=3D FromProtoEnd;
+       ++FromProto, ++FromProtoLoc) {
+    ObjCProtocolDecl *ToProto
+      =3D cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
+    if (!ToProto)
+      return true;
+    Protocols.push_back(ToProto);
+    ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
+  }
+ =20
+  // FIXME: If we're merging, make sure that the protocol list is the same.
+  To->setProtocolList(Protocols.data(), Protocols.size(),
+                      ProtocolLocs.data(), Importer.getToContext());
+
+  if (shouldForceImportDeclContext(Kind)) {
+    // Import all of the members of this protocol.
+    ImportDeclContext(From, /*ForceImport=3D*/true);
+  }
+  return false;
+}
+
 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
+  // If this protocol has a definition in the translation unit we're comin=
g=20
+  // from, but this particular declaration is not that definition, import =
the
+  // definition and map to that.
+  ObjCProtocolDecl *Definition =3D D->getDefinition();
+  if (Definition && Definition !=3D D) {
+    Decl *ImportedDef =3D Importer.Import(Definition);
+    if (!ImportedDef)
+      return 0;
+   =20
+    return Importer.Imported(D, ImportedDef);
+  }
+
   // Import the major distinguishing characteristics of a protocol.
   DeclContext *DC, *LexicalDC;
   DeclarationName Name;
@@ -3104,48 +3225,133 @@
   }
  =20
   ObjCProtocolDecl *ToProto =3D MergeWithProtocol;
-  if (!ToProto || ToProto->isForwardDecl()) {
-    if (!ToProto) {
-      ToProto =3D ObjCProtocolDecl::Create(Importer.getToContext(), DC,
-                                         Name.getAsIdentifierInfo(), Loc,
-                                         Importer.Import(D->getAtStartLoc(=
)));
-      ToProto->setForwardDecl(D->isForwardDecl());
-      ToProto->setLexicalDeclContext(LexicalDC);
-      LexicalDC->addDecl(ToProto);
+  if (!ToProto) {
+    ToProto =3D ObjCProtocolDecl::Create(Importer.getToContext(), DC,
+                                       Name.getAsIdentifierInfo(), Loc,
+                                       Importer.Import(D->getAtStartLoc()),
+                                       /*PrevDecl=3D*/0);
+    ToProto->setLexicalDeclContext(LexicalDC);
+    LexicalDC->addDeclInternal(ToProto);
+  }
+   =20
+  Importer.Imported(D, ToProto);
+
+  if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
+    return 0;
+ =20
+  return ToProto;
+}
+
+bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,=20
+                                       ObjCInterfaceDecl *To,
+                                       ImportDefinitionKind Kind) {
+  if (To->getDefinition()) {
+    // Check consistency of superclass.
+    ObjCInterfaceDecl *FromSuper =3D From->getSuperClass();
+    if (FromSuper) {
+      FromSuper =3D cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSu=
per));
+      if (!FromSuper)
+        return true;
     }
-    Importer.Imported(D, ToProto);
-
-    // Import protocols
-    SmallVector<ObjCProtocolDecl *, 4> Protocols;
-    SmallVector<SourceLocation, 4> ProtocolLocs;
-    ObjCProtocolDecl::protocol_loc_iterator=20
-      FromProtoLoc =3D D->protocol_loc_begin();
-    for (ObjCProtocolDecl::protocol_iterator FromProto =3D D->protocol_beg=
in(),
-                                          FromProtoEnd =3D D->protocol_end=
();
+   =20
+    ObjCInterfaceDecl *ToSuper =3D To->getSuperClass();   =20
+    if ((bool)FromSuper !=3D (bool)ToSuper ||
+        (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
+      Importer.ToDiag(To->getLocation(),=20
+                      diag::err_odr_objc_superclass_inconsistent)
+        << To->getDeclName();
+      if (ToSuper)
+        Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superc=
lass)
+          << To->getSuperClass()->getDeclName();
+      else
+        Importer.ToDiag(To->getLocation(),=20
+                        diag::note_odr_objc_missing_superclass);
+      if (From->getSuperClass())
+        Importer.FromDiag(From->getSuperClassLoc(),=20
+                          diag::note_odr_objc_superclass)
+        << From->getSuperClass()->getDeclName();
+      else
+        Importer.FromDiag(From->getLocation(),=20
+                          diag::note_odr_objc_missing_superclass);       =20
+    }
+   =20
+    if (shouldForceImportDeclContext(Kind))
+      ImportDeclContext(From);
+    return false;
+  }
+ =20
+  // Start the definition.
+  To->startDefinition();
+ =20
+  // If this class has a superclass, import it.
+  if (From->getSuperClass()) {
+    ObjCInterfaceDecl *Super =3D cast_or_null<ObjCInterfaceDecl>(
+                                 Importer.Import(From->getSuperClass()));
+    if (!Super)
+      return true;
+   =20
+    To->setSuperClass(Super);
+    To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc()));
+  }
+ =20
+  // Import protocols
+  SmallVector<ObjCProtocolDecl *, 4> Protocols;
+  SmallVector<SourceLocation, 4> ProtocolLocs;
+  ObjCInterfaceDecl::protocol_loc_iterator=20
+  FromProtoLoc =3D From->protocol_loc_begin();
+ =20
+  for (ObjCInterfaceDecl::protocol_iterator FromProto =3D From->protocol_b=
egin(),
+                                         FromProtoEnd =3D From->protocol_e=
nd();
        FromProto !=3D FromProtoEnd;
        ++FromProto, ++FromProtoLoc) {
-      ObjCProtocolDecl *ToProto
-        =3D cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
-      if (!ToProto)
-        return 0;
-      Protocols.push_back(ToProto);
-      ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
-    }
+    ObjCProtocolDecl *ToProto
+      =3D cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
+    if (!ToProto)
+      return true;
+    Protocols.push_back(ToProto);
+    ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
+  }
+ =20
+  // FIXME: If we're merging, make sure that the protocol list is the same.
+  To->setProtocolList(Protocols.data(), Protocols.size(),
+                      ProtocolLocs.data(), Importer.getToContext());
+ =20
+  // Import categories. When the categories themselves are imported, they'=
ll
+  // hook themselves into this interface.
+  for (ObjCCategoryDecl *FromCat =3D From->getCategoryList(); FromCat;
+       FromCat =3D FromCat->getNextClassCategory())
+    Importer.Import(FromCat);
+
+  // If we have an @implementation, import it as well.
+  if (From->getImplementation()) {
+    ObjCImplementationDecl *Impl =3D cast_or_null<ObjCImplementationDecl>(
+                                     Importer.Import(From->getImplementati=
on()));
+    if (!Impl)
+      return true;
    =20
-    // FIXME: If we're merging, make sure that the protocol list is the sa=
me.
-    ToProto->setProtocolList(Protocols.data(), Protocols.size(),
-                             ProtocolLocs.data(), Importer.getToContext());
-  } else {
-    Importer.Imported(D, ToProto);
+    To->setImplementation(Impl);
   }
=20
-  // Import all of the members of this protocol.
-  ImportDeclContext(D);
-
-  return ToProto;
+  if (shouldForceImportDeclContext(Kind)) {
+    // Import all of the members of this class.
+    ImportDeclContext(From, /*ForceImport=3D*/true);
+  }
+  return false;
 }
=20
 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
+  // If this class has a definition in the translation unit we're coming f=
rom,
+  // but this particular declaration is not that definition, import the
+  // definition and map to that.
+  ObjCInterfaceDecl *Definition =3D D->getDefinition();
+  if (Definition && Definition !=3D D) {
+    Decl *ImportedDef =3D Importer.Import(Definition);
+    if (!ImportedDef)
+      return 0;
+   =20
+    return Importer.Imported(D, ImportedDef);
+  }
+
   // Import the major distinguishing characteristics of an @interface.
   DeclContext *DC, *LexicalDC;
   DeclarationName Name;
@@ -3153,6 +3359,7 @@
   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
     return 0;
=20
+  // Look for an existing interface with the same name.
   ObjCInterfaceDecl *MergeWithIface =3D 0;
   llvm::SmallVector<NamedDecl *, 2> FoundDecls;
   DC->localUncachedLookup(Name, FoundDecls);
@@ -3164,105 +3371,22 @@
       break;
   }
  =20
+  // Create an interface declaration, if one does not already exist.
   ObjCInterfaceDecl *ToIface =3D MergeWithIface;
-  if (!ToIface || ToIface->isForwardDecl()) {
-    if (!ToIface) {
-      ToIface =3D ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
-                                          Importer.Import(D->getAtStartLoc=
()),
-                                          Name.getAsIdentifierInfo(), Loc,
-                                          D->isForwardDecl(),
-                                          D->isImplicitInterfaceDecl());
-      ToIface->setForwardDecl(D->isForwardDecl());
-      ToIface->setLexicalDeclContext(LexicalDC);
-      LexicalDC->addDecl(ToIface);
-    }
-    Importer.Imported(D, ToIface);
-
-    if (D->getSuperClass()) {
-      ObjCInterfaceDecl *Super
-        =3D cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getSuperCla=
ss()));
-      if (!Super)
-        return 0;
-     =20
-      ToIface->setSuperClass(Super);
-      ToIface->setSuperClassLoc(Importer.Import(D->getSuperClassLoc()));
-    }
+  if (!ToIface) {
+    ToIface =3D ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
+                                        Importer.Import(D->getAtStartLoc()=
),
+                                        Name.getAsIdentifierInfo(),=20
+                                        /*PrevDecl=3D*/0,Loc,
+                                        D->isImplicitInterfaceDecl());
+    ToIface->setLexicalDeclContext(LexicalDC);
+    LexicalDC->addDeclInternal(ToIface);
+  }
+  Importer.Imported(D, ToIface);
+ =20
+  if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
+    return 0;
    =20
-    // Import protocols
-    SmallVector<ObjCProtocolDecl *, 4> Protocols;
-    SmallVector<SourceLocation, 4> ProtocolLocs;
-    ObjCInterfaceDecl::protocol_loc_iterator=20
-      FromProtoLoc =3D D->protocol_loc_begin();
-   =20
-    // FIXME: Should we be usng all_referenced_protocol_begin() here?
-    for (ObjCInterfaceDecl::protocol_iterator FromProto =3D D->protocol_be=
gin(),
-                                           FromProtoEnd =3D D->protocol_en=
d();
-       FromProto !=3D FromProtoEnd;
-       ++FromProto, ++FromProtoLoc) {
-      ObjCProtocolDecl *ToProto
-        =3D cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
-      if (!ToProto)
-        return 0;
-      Protocols.push_back(ToProto);
-      ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
-    }
-   =20
-    // FIXME: If we're merging, make sure that the protocol list is the sa=
me.
-    ToIface->setProtocolList(Protocols.data(), Protocols.size(),
-                             ProtocolLocs.data(), Importer.getToContext());
-   =20
-    // Import @end range
-    ToIface->setAtEndRange(Importer.Import(D->getAtEndRange()));
-  } else {
-    Importer.Imported(D, ToIface);
-
-    // Check for consistency of superclasses.
-    DeclarationName FromSuperName, ToSuperName;
-    if (D->getSuperClass())
-      FromSuperName =3D Importer.Import(D->getSuperClass()->getDeclName());
-    if (ToIface->getSuperClass())
-      ToSuperName =3D ToIface->getSuperClass()->getDeclName();
-    if (FromSuperName !=3D ToSuperName) {
-      Importer.ToDiag(ToIface->getLocation(),=20
-                      diag::err_odr_objc_superclass_inconsistent)
-        << ToIface->getDeclName();
-      if (ToIface->getSuperClass())
-        Importer.ToDiag(ToIface->getSuperClassLoc(),=20
-                        diag::note_odr_objc_superclass)
-          << ToIface->getSuperClass()->getDeclName();
-      else
-        Importer.ToDiag(ToIface->getLocation(),=20
-                        diag::note_odr_objc_missing_superclass);
-      if (D->getSuperClass())
-        Importer.FromDiag(D->getSuperClassLoc(),=20
-                          diag::note_odr_objc_superclass)
-          << D->getSuperClass()->getDeclName();
-      else
-        Importer.FromDiag(D->getLocation(),=20
-                          diag::note_odr_objc_missing_superclass);
-      return 0;
-    }
-  }
- =20
-  // Import categories. When the categories themselves are imported, they'=
ll
-  // hook themselves into this interface.
-  for (ObjCCategoryDecl *FromCat =3D D->getCategoryList(); FromCat;
-       FromCat =3D FromCat->getNextClassCategory())
-    Importer.Import(FromCat);
- =20
-  // Import all of the members of this class.
-  ImportDeclContext(D);
- =20
-  // If we have an @implementation, import it as well.
-  if (D->getImplementation()) {
-    ObjCImplementationDecl *Impl =3D cast_or_null<ObjCImplementationDecl>(
-                                       Importer.Import(D->getImplementatio=
n()));
-    if (!Impl)
-      return 0;
-   =20
-    ToIface->setImplementation(Impl);
-  }
- =20
   return ToIface;
 }
=20
@@ -3278,11 +3402,13 @@
     if (!DC)
       return 0;
    =20
+    SourceLocation CategoryNameLoc =3D Importer.Import(D->getCategoryNameL=
oc());
     ToImpl =3D ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
                                           Importer.Import(D->getIdentifier=
()),
                                           Category->getClassInterface(),
                                           Importer.Import(D->getLocation()=
),
-                                          Importer.Import(D->getAtStartLoc=
()));
+                                          Importer.Import(D->getAtStartLoc=
()),
+                                          CategoryNameLoc);
    =20
     DeclContext *LexicalDC =3D DC;
     if (D->getDeclContext() !=3D D->getLexicalDeclContext()) {
@@ -3293,7 +3419,7 @@
       ToImpl->setLexicalDeclContext(LexicalDC);
     }
    =20
-    LexicalDC->addDecl(ToImpl);
+    LexicalDC->addDeclInternal(ToImpl);
     Category->setImplementation(ToImpl);
   }
  =20
@@ -3326,7 +3452,9 @@
                                   Importer.ImportContext(D->getDeclContext=
()),
                                           Iface, Super,
                                           Importer.Import(D->getLocation()=
),
-                                          Importer.Import(D->getAtStartLoc=
()));
+                                          Importer.Import(D->getAtStartLoc=
()),
+                                          Importer.Import(D->getIvarLBrace=
Loc()),
+                                          Importer.Import(D->getIvarRBrace=
Loc()));
    =20
     if (D->getDeclContext() !=3D D->getLexicalDeclContext()) {
       DeclContext *LexicalDC
@@ -3346,7 +3474,7 @@
     if ((Super && !Impl->getSuperClass()) ||
         (!Super && Impl->getSuperClass()) ||
         (Super && Impl->getSuperClass() &&=20
-         Super->getCanonicalDecl() !=3D Impl->getSuperClass())) {
+         !declaresSameEntity(Super->getCanonicalDecl(), Impl->getSuperClas=
s()))) {
         Importer.ToDiag(Impl->getLocation(),=20
                         diag::err_odr_objc_superclass_inconsistent)
           << Iface->getDeclName();
@@ -3418,11 +3546,12 @@
     =3D ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
                                Name.getAsIdentifierInfo(),=20
                                Importer.Import(D->getAtLoc()),
+                               Importer.Import(D->getLParenLoc()),
                                T,
                                D->getPropertyImplementation());
   Importer.Imported(D, ToProperty);
   ToProperty->setLexicalDeclContext(LexicalDC);
-  LexicalDC->addDecl(ToProperty);
+  LexicalDC->addDeclInternal(ToProperty);
=20
   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
   ToProperty->setPropertyAttributesAsWritten(
@@ -3481,7 +3610,7 @@
                                   Importer.Import(D->getPropertyIvarDeclLo=
c()));
     ToImpl->setLexicalDeclContext(LexicalDC);
     Importer.Imported(D, ToImpl);
-    LexicalDC->addDecl(ToImpl);
+    LexicalDC->addDeclInternal(ToImpl);
   } else {
     // Check that we have the same kind of property implementation (@synth=
esize
     // vs. @dynamic).
@@ -3519,79 +3648,6 @@
   return ToImpl;
 }
=20
-Decl *
-ASTNodeImporter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
-  // Import the context of this declaration.
-  DeclContext *DC =3D Importer.ImportContext(D->getDeclContext());
-  if (!DC)
-    return 0;
- =20
-  DeclContext *LexicalDC =3D DC;
-  if (D->getDeclContext() !=3D D->getLexicalDeclContext()) {
-    LexicalDC =3D Importer.ImportContext(D->getLexicalDeclContext());
-    if (!LexicalDC)
-      return 0;
-  }
- =20
-  // Import the location of this declaration.
-  SourceLocation Loc =3D Importer.Import(D->getLocation());
- =20
-  SmallVector<ObjCProtocolDecl *, 4> Protocols;
-  SmallVector<SourceLocation, 4> Locations;
-  ObjCForwardProtocolDecl::protocol_loc_iterator FromProtoLoc
-    =3D D->protocol_loc_begin();
-  for (ObjCForwardProtocolDecl::protocol_iterator FromProto
-         =3D D->protocol_begin(), FromProtoEnd =3D D->protocol_end();
-       FromProto !=3D FromProtoEnd;=20
-       ++FromProto, ++FromProtoLoc) {
-    ObjCProtocolDecl *ToProto
-      =3D cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
-    if (!ToProto)
-      continue;
-   =20
-    Protocols.push_back(ToProto);
-    Locations.push_back(Importer.Import(*FromProtoLoc));
-  }
- =20
-  ObjCForwardProtocolDecl *ToForward
-    =3D ObjCForwardProtocolDecl::Create(Importer.getToContext(), DC, Loc,=20
-                                      Protocols.data(), Protocols.size(),
-                                      Locations.data());
-  ToForward->setLexicalDeclContext(LexicalDC);
-  LexicalDC->addDecl(ToForward);
-  Importer.Imported(D, ToForward);
-  return ToForward;
-}
-
-Decl *ASTNodeImporter::VisitObjCClassDecl(ObjCClassDecl *D) {
-  // Import the context of this declaration.
-  DeclContext *DC =3D Importer.ImportContext(D->getDeclContext());
-  if (!DC)
-    return 0;
- =20
-  DeclContext *LexicalDC =3D DC;
-  if (D->getDeclContext() !=3D D->getLexicalDeclContext()) {
-    LexicalDC =3D Importer.ImportContext(D->getLexicalDeclContext());
-    if (!LexicalDC)
-      return 0;
-  }
- =20
-  // Import the location of this declaration.
-  SourceLocation Loc =3D Importer.Import(D->getLocation());
-  ObjCClassDecl::ObjCClassRef *From =3D D->getForwardDecl();
-  ObjCInterfaceDecl *ToIface
-    =3D cast_or_null<ObjCInterfaceDecl>(Importer.Import(From->getInterface=
()));
-  ObjCClassDecl *ToClass =3D ObjCClassDecl::Create(Importer.getToContext()=
, DC,
-                                        Loc,
-                                        ToIface,
-                                        Importer.Import(From->getLocation(=
)));
-   =20
-  ToClass->setLexicalDeclContext(LexicalDC);
-  LexicalDC->addDecl(ToClass);
-  Importer.Imported(D, ToClass);
-  return ToClass;
-}
-
 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
   // For template arguments, we adopt the translation unit as our declarat=
ion
   // context. This context will be fixed when the actual template declarat=
ion
@@ -3749,7 +3805,7 @@
  =20
   D2->setAccess(D->getAccess());
   D2->setLexicalDeclContext(LexicalDC);
-  LexicalDC->addDecl(D2);
+  LexicalDC->addDeclInternal(D2);
  =20
   // Note the relationship between the class templates.
   Importer.Imported(D, D2);
@@ -3844,7 +3900,7 @@
    =20
     // Add the specialization to this context.
     D2->setLexicalDeclContext(LexicalDC);
-    LexicalDC->addDecl(D2);
+    LexicalDC->addDeclInternal(D2);
   }
   Importer.Imported(D, D2);
  =20
@@ -3891,7 +3947,9 @@
=20
   DeclRefExpr *DRE =3D DeclRefExpr::Create(Importer.getToContext(),=20
                                          Importer.Import(E->getQualifierLo=
c()),
+                                   Importer.Import(E->getTemplateKeywordLo=
c()),
                                          ToD,
+                                         E->refersToEnclosingLocal(),
                                          Importer.Import(E->getLocation()),
                                          T, E->getValueKind(),
                                          FoundD,
@@ -4116,7 +4174,7 @@
     return 0;
=20
   return ToContext.getTrivialTypeSourceInfo(T,=20
-                        FromTSI->getTypeLoc().getSourceRange().getBegin());
+                        FromTSI->getTypeLoc().getLocStart());
 }
=20
 Decl *ASTImporter::Import(Decl *FromD) {
@@ -4170,7 +4228,55 @@
   if (!FromDC)
     return FromDC;
=20
-  return cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
+  DeclContext *ToDC =3D cast_or_null<DeclContext>(Import(cast<Decl>(FromDC=
)));
+  if (!ToDC)
+    return 0;
+ =20
+  // When we're using a record/enum/Objective-C class/protocol as a contex=
t, we=20
+  // need it to have a definition.
+  if (RecordDecl *ToRecord =3D dyn_cast<RecordDecl>(ToDC)) {
+    RecordDecl *FromRecord =3D cast<RecordDecl>(FromDC);
+    if (ToRecord->isCompleteDefinition()) {
+      // Do nothing.
+    } else if (FromRecord->isCompleteDefinition()) {
+      ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
+                                              ASTNodeImporter::IDK_Basic);
+    } else {
+      CompleteDecl(ToRecord);
+    }
+  } else if (EnumDecl *ToEnum =3D dyn_cast<EnumDecl>(ToDC)) {
+    EnumDecl *FromEnum =3D cast<EnumDecl>(FromDC);
+    if (ToEnum->isCompleteDefinition()) {
+      // Do nothing.
+    } else if (FromEnum->isCompleteDefinition()) {
+      ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
+                                              ASTNodeImporter::IDK_Basic);
+    } else {
+      CompleteDecl(ToEnum);
+    }   =20
+  } else if (ObjCInterfaceDecl *ToClass =3D dyn_cast<ObjCInterfaceDecl>(To=
DC)) {
+    ObjCInterfaceDecl *FromClass =3D cast<ObjCInterfaceDecl>(FromDC);
+    if (ToClass->getDefinition()) {
+      // Do nothing.
+    } else if (ObjCInterfaceDecl *FromDef =3D FromClass->getDefinition()) {
+      ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
+                                              ASTNodeImporter::IDK_Basic);
+    } else {
+      CompleteDecl(ToClass);
+    }
+  } else if (ObjCProtocolDecl *ToProto =3D dyn_cast<ObjCProtocolDecl>(ToDC=
)) {
+    ObjCProtocolDecl *FromProto =3D cast<ObjCProtocolDecl>(FromDC);
+    if (ToProto->getDefinition()) {
+      // Do nothing.
+    } else if (ObjCProtocolDecl *FromDef =3D FromProto->getDefinition()) {
+      ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
+                                              ASTNodeImporter::IDK_Basic);
+    } else {
+      CompleteDecl(ToProto);
+    }   =20
+  }
+ =20
+  return ToDC;
 }
=20
 Expr *ASTImporter::Import(Expr *FromE) {
@@ -4244,7 +4350,6 @@
   }
=20
   llvm_unreachable("Invalid nested name specifier kind");
-  return 0;
 }
=20
 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS)=
 {
@@ -4339,7 +4444,6 @@
   }
  =20
   llvm_unreachable("Invalid template name kind");
-  return TemplateName();
 }
=20
 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
@@ -4413,7 +4517,7 @@
     if (RecordDecl *ToRecord =3D dyn_cast<RecordDecl>(To)) {
       if (!ToRecord->getDefinition()) {
         Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,=20
-                                  /*ForceImport=3D*/true);
+                                  ASTNodeImporter::IDK_Everything);
         return;
       }     =20
     }
@@ -4421,11 +4525,27 @@
     if (EnumDecl *ToEnum =3D dyn_cast<EnumDecl>(To)) {
       if (!ToEnum->getDefinition()) {
         Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,=20
-                                  /*ForceImport=3D*/true);
+                                  ASTNodeImporter::IDK_Everything);
         return;
       }     =20
     }
-
+   =20
+    if (ObjCInterfaceDecl *ToIFace =3D dyn_cast<ObjCInterfaceDecl>(To)) {
+      if (!ToIFace->getDefinition()) {
+        Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
+                                  ASTNodeImporter::IDK_Everything);
+        return;
+      }
+    }
+
+    if (ObjCProtocolDecl *ToProto =3D dyn_cast<ObjCProtocolDecl>(To)) {
+      if (!ToProto->getDefinition()) {
+        Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
+                                  ASTNodeImporter::IDK_Everything);
+        return;
+      }
+    }
+   =20
     Importer.ImportDeclContext(FromDC, true);
   }
 }
@@ -4483,8 +4603,7 @@
     return DeclarationName::getUsingDirectiveName();
   }
=20
-  // Silence bogus GCC warning
-  return DeclarationName();
+  llvm_unreachable("Invalid DeclarationName Kind!");
 }
=20
 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
@@ -4521,6 +4640,26 @@
   return FromContext.getDiagnostics().Report(Loc, DiagID);
 }
=20
+void ASTImporter::CompleteDecl (Decl *D) {
+  if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(D)) {
+    if (!ID->getDefinition())
+      ID->startDefinition();
+  }
+  else if (ObjCProtocolDecl *PD =3D dyn_cast<ObjCProtocolDecl>(D)) {
+    if (!PD->getDefinition())
+      PD->startDefinition();
+  }
+  else if (TagDecl *TD =3D dyn_cast<TagDecl>(D)) {
+    if (!TD->getDefinition() && !TD->isBeingDefined()) {
+      TD->startDefinition();
+      TD->setCompleteDefinition(true);
+    }
+  }
+  else {
+    assert (0 && "CompleteDecl called on a Decl that can't be completed");
+  }
+}
+
 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
   ImportedDecls[From] =3D To;
   return To;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
AttrImpl.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/AttrImpl.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/AttrImpl.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -19,4 +19,8 @@
=20
 Attr::~Attr() { }
=20
+void InheritableAttr::anchor() { }
+
+void InheritableParamAttr::anchor() { }
+
 #include "clang/AST/AttrImpl.inc"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
CXXInheritance.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/CXXInheritance.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/CXXInheritance.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -23,12 +23,15 @@
 void CXXBasePaths::ComputeDeclsFound() {
   assert(NumDeclsFound =3D=3D 0 && !DeclsFound &&
          "Already computed the set of declarations");
- =20
-  std::set<NamedDecl *> Decls;
-  for (CXXBasePaths::paths_iterator Path =3D begin(), PathEnd =3D end();
-       Path !=3D PathEnd; ++Path)
-    Decls.insert(*Path->Decls.first);
- =20
+
+  SmallVector<NamedDecl *, 8> Decls;
+  for (paths_iterator Path =3D begin(), PathEnd =3D end(); Path !=3D PathE=
nd; ++Path)
+    Decls.push_back(*Path->Decls.first);
+
+  // Eliminate duplicated decls.
+  llvm::array_pod_sort(Decls.begin(), Decls.end());
+  Decls.erase(std::unique(Decls.begin(), Decls.end()), Decls.end());
+
   NumDeclsFound =3D Decls.size();
   DeclsFound =3D new NamedDecl * [NumDeclsFound];
   std::copy(Decls.begin(), Decls.end(), DeclsFound);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
Decl.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/Decl.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/Decl.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -24,6 +24,7 @@
 #include "clang/AST/ASTMutationListener.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "clang/Basic/Module.h"
 #include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TargetInfo.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -47,8 +48,6 @@
     case VisibilityAttr::Protected:
       return ProtectedVisibility;
     }
-
-    return DefaultVisibility;
   }
=20
   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
@@ -66,17 +65,6 @@
 }
=20
 typedef NamedDecl::LinkageInfo LinkageInfo;
-typedef std::pair<Linkage,Visibility> LVPair;
-
-static LVPair merge(LVPair L, LVPair R) {
-  return LVPair(minLinkage(L.first, R.first),
-                minVisibility(L.second, R.second));
-}
-
-static LVPair merge(LVPair L, LinkageInfo R) {
-  return LVPair(minLinkage(L.first, R.linkage()),
-                minVisibility(L.second, R.visibility()));
-}
=20
 namespace {
 /// Flags controlling the computation of linkage and visibility.
@@ -112,11 +100,16 @@
 };=20
 } // end anonymous namespace
=20
+static LinkageInfo getLVForType(QualType T) {
+  std::pair<Linkage,Visibility> P =3D T->getLinkageAndVisibility();
+  return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
+}
+
 /// \brief Get the most restrictive linkage for the types in the given
 /// template parameter list.
-static LVPair=20
+static LinkageInfo
 getLVForTemplateParameterList(const TemplateParameterList *Params) {
-  LVPair LV(ExternalLinkage, DefaultVisibility);
+  LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
   for (TemplateParameterList::const_iterator P =3D Params->begin(),
                                           PEnd =3D Params->end();
        P !=3D PEnd; ++P) {
@@ -125,20 +118,20 @@
         for (unsigned I =3D 0, N =3D NTTP->getNumExpansionTypes(); I !=3D =
N; ++I) {
           QualType T =3D NTTP->getExpansionType(I);
           if (!T->isDependentType())
-            LV =3D merge(LV, T->getLinkageAndVisibility());
+            LV.merge(getLVForType(T));
         }
         continue;
       }
-     =20
+
       if (!NTTP->getType()->isDependentType()) {
-        LV =3D merge(LV, NTTP->getType()->getLinkageAndVisibility());
+        LV.merge(getLVForType(NTTP->getType()));
         continue;
       }
     }
=20
     if (TemplateTemplateParmDecl *TTP
                                    =3D dyn_cast<TemplateTemplateParmDecl>(=
*P)) {
-      LV =3D merge(LV, getLVForTemplateParameterList(TTP->getTemplateParam=
eters()));
+      LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters())=
);
     }
   }
=20
@@ -150,10 +143,10 @@
=20
 /// \brief Get the most restrictive linkage for the types and
 /// declarations in the given template argument list.
-static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
-                                           unsigned NumArgs,
-                                           LVFlags &F) {
-  LVPair LV(ExternalLinkage, DefaultVisibility);
+static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Ar=
gs,
+                                                unsigned NumArgs,
+                                                LVFlags &F) {
+  LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
=20
   for (unsigned I =3D 0; I !=3D NumArgs; ++I) {
     switch (Args[I].getKind()) {
@@ -161,9 +154,9 @@
     case TemplateArgument::Integral:
     case TemplateArgument::Expression:
       break;
-     =20
+
     case TemplateArgument::Type:
-      LV =3D merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
+      LV.merge(getLVForType(Args[I].getAsType()));
       break;
=20
     case TemplateArgument::Declaration:
@@ -177,15 +170,15 @@
=20
     case TemplateArgument::Template:
     case TemplateArgument::TemplateExpansion:
-      if (TemplateDecl *Template=20
+      if (TemplateDecl *Template
                 =3D Args[I].getAsTemplateOrTemplatePattern().getAsTemplate=
Decl())
-        LV =3D merge(LV, getLVForDecl(Template, F));
+        LV.merge(getLVForDecl(Template, F));
       break;
=20
     case TemplateArgument::Pack:
-      LV =3D merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
-                                                  Args[I].pack_size(),
-                                                  F));
+      LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(),
+                                                   Args[I].pack_size(),
+                                                   F));
       break;
     }
   }
@@ -193,7 +186,7 @@
   return LV;
 }
=20
-static LVPair
+static LinkageInfo
 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
                              LVFlags &F) {
   return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
@@ -229,14 +222,14 @@
     //   and neither explicitly declared extern nor previously
     //   declared to have external linkage; or
     // (there is no equivalent in C99)
-    if (Context.getLangOptions().CPlusPlus &&
+    if (Context.getLangOpts().CPlusPlus &&
         Var->getType().isConstant(Context) &&=20
         Var->getStorageClass() !=3D SC_Extern &&
         Var->getStorageClass() !=3D SC_PrivateExtern) {
       bool FoundExtern =3D false;
-      for (const VarDecl *PrevVar =3D Var->getPreviousDeclaration();
+      for (const VarDecl *PrevVar =3D Var->getPreviousDecl();
            PrevVar && !FoundExtern;=20
-           PrevVar =3D PrevVar->getPreviousDeclaration())
+           PrevVar =3D PrevVar->getPreviousDecl())
         if (isExternalLinkage(PrevVar->getLinkage()))
           FoundExtern =3D true;
      =20
@@ -244,8 +237,8 @@
         return LinkageInfo::internal();
     }
     if (Var->getStorageClass() =3D=3D SC_None) {
-      const VarDecl *PrevVar =3D Var->getPreviousDeclaration();
-      for (; PrevVar; PrevVar =3D PrevVar->getPreviousDeclaration())
+      const VarDecl *PrevVar =3D Var->getPreviousDecl();
+      for (; PrevVar; PrevVar =3D PrevVar->getPreviousDecl())
         if (PrevVar->getStorageClass() =3D=3D SC_PrivateExtern)
           break;
         if (PrevVar)
@@ -274,7 +267,8 @@
   if (D->isInAnonymousNamespace()) {
     const VarDecl *Var =3D dyn_cast<VarDecl>(D);
     const FunctionDecl *Func =3D dyn_cast<FunctionDecl>(D);
-    if ((!Var || !Var->isExternC()) && (!Func || !Func->isExternC()))
+    if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
+        (!Func || !Func->getDeclContext()->isExternCContext()))
       return LinkageInfo::uniqueExternal();
   }
=20
@@ -285,6 +279,7 @@
   //   scope and no storage-class specifier, its linkage is
   //   external.
   LinkageInfo LV;
+  LV.mergeVisibility(Context.getLangOpts().getVisibilityMode());
=20
   if (F.ConsiderVisibilityAttributes) {
     if (llvm::Optional<Visibility> Vis =3D D->getExplicitVisibility()) {
@@ -296,10 +291,10 @@
       for (const DeclContext *DC =3D D->getDeclContext();
            !isa<TranslationUnitDecl>(DC);
            DC =3D DC->getParent()) {
-        if (!isa<NamespaceDecl>(DC)) continue;
-        if (llvm::Optional<Visibility> Vis
-                           =3D cast<NamespaceDecl>(DC)->getExplicitVisibil=
ity()) {
-          LV.setVisibility(*Vis, false);
+        const NamespaceDecl *ND =3D dyn_cast<NamespaceDecl>(DC);
+        if (!ND) continue;
+        if (llvm::Optional<Visibility> Vis =3D ND->getExplicitVisibility()=
) {
+          LV.setVisibility(*Vis, true);
           F.ConsiderGlobalVisibility =3D false;
           break;
         }
@@ -335,18 +330,19 @@
     //
     // Note that we don't want to make the variable non-external
     // because of this, but unique-external linkage suits us.
-    if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
-      LVPair TypeLV =3D Var->getType()->getLinkageAndVisibility();
-      if (TypeLV.first !=3D ExternalLinkage)
+    if (Context.getLangOpts().CPlusPlus &&
+        !Var->getDeclContext()->isExternCContext()) {
+      LinkageInfo TypeLV =3D getLVForType(Var->getType());
+      if (TypeLV.linkage() !=3D ExternalLinkage)
         return LinkageInfo::uniqueExternal();
-      if (!LV.visibilityExplicit())
-        LV.mergeVisibility(TypeLV.second);
+      LV.mergeVisibilityWithMin(TypeLV.visibility(),
+                                TypeLV.visibilityExplicit());
     }
=20
     if (Var->getStorageClass() =3D=3D SC_PrivateExtern)
       LV.setVisibility(HiddenVisibility, true);
=20
-    if (!Context.getLangOptions().CPlusPlus &&
+    if (!Context.getLangOpts().CPlusPlus &&
         (Var->getStorageClass() =3D=3D SC_Extern ||
          Var->getStorageClass() =3D=3D SC_PrivateExtern)) {
=20
@@ -359,7 +355,7 @@
       //   specified at the prior declaration. If no prior declaration
       //   is visible, or if the prior declaration specifies no
       //   linkage, then the identifier has external linkage.
-      if (const VarDecl *PrevVar =3D Var->getPreviousDeclaration()) {
+      if (const VarDecl *PrevVar =3D Var->getPreviousDecl()) {
         LinkageInfo PrevLV =3D getLVForDecl(PrevVar, F);
         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
         LV.mergeVisibility(PrevLV);
@@ -381,7 +377,7 @@
     //   storage-class specifier, its linkage is determined exactly
     //   as if it were declared with the storage-class specifier
     //   extern.
-    if (!Context.getLangOptions().CPlusPlus &&
+    if (!Context.getLangOpts().CPlusPlus &&
         (Function->getStorageClass() =3D=3D SC_Extern ||
          Function->getStorageClass() =3D=3D SC_PrivateExtern ||
          Function->getStorageClass() =3D=3D SC_None)) {
@@ -394,7 +390,7 @@
       //   specified at the prior declaration. If no prior declaration
       //   is visible, or if the prior declaration specifies no
       //   linkage, then the identifier has external linkage.
-      if (const FunctionDecl *PrevFunc =3D Function->getPreviousDeclaratio=
n()) {
+      if (const FunctionDecl *PrevFunc =3D Function->getPreviousDecl()) {
         LinkageInfo PrevLV =3D getLVForDecl(PrevFunc, F);
         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
         LV.mergeVisibility(PrevLV);
@@ -405,7 +401,8 @@
     // unique-external linkage, it's not legally usable from outside
     // this translation unit.  However, we should use the C linkage
     // rules instead for extern "C" declarations.
-    if (Context.getLangOptions().CPlusPlus && !Function->isExternC() &&
+    if (Context.getLangOpts().CPlusPlus &&
+        !Function->getDeclContext()->isExternCContext() &&
         Function->getType()->getLinkage() =3D=3D UniqueExternalLinkage)
       return LinkageInfo::uniqueExternal();
=20
@@ -417,7 +414,7 @@
         LV.merge(getLVForDecl(specInfo->getTemplate(),
                               F.onlyTemplateVisibility()));
         const TemplateArgumentList &templateArgs =3D *specInfo->TemplateAr=
guments;
-        LV.merge(getLVForTemplateArgumentList(templateArgs, F));
+        LV.mergeWithMin(getLVForTemplateArgumentList(templateArgs, F));
       }
     }
=20
@@ -443,14 +440,14 @@
=20
         // The arguments at which the template was instantiated.
         const TemplateArgumentList &TemplateArgs =3D spec->getTemplateArgs=
();
-        LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
+        LV.mergeWithMin(getLVForTemplateArgumentList(TemplateArgs, F));
       }
     }
=20
     // Consider -fvisibility unless the type has C linkage.
     if (F.ConsiderGlobalVisibility)
       F.ConsiderGlobalVisibility =3D
-        (Context.getLangOptions().CPlusPlus &&
+        (Context.getLangOpts().CPlusPlus &&
          !Tag->getDeclContext()->isExternCContext());
=20
   //     - an enumerator belonging to an enumeration with external linkage;
@@ -486,11 +483,6 @@
   if (LV.linkage() !=3D ExternalLinkage)
     return LinkageInfo(LV.linkage(), DefaultVisibility, false);
=20
-  // If we didn't end up with hidden visibility, consider attributes
-  // and -fvisibility.
-  if (F.ConsiderGlobalVisibility)
-    LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
-
   return LV;
 }
=20
@@ -507,6 +499,7 @@
     return LinkageInfo::none();
=20
   LinkageInfo LV;
+  LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode());
=20
   // The flags we're going to use to compute the class's visibility.
   LVFlags ClassF =3D F;
@@ -548,7 +541,8 @@
     if (FunctionTemplateSpecializationInfo *spec
            =3D MD->getTemplateSpecializationInfo()) {
       if (shouldConsiderTemplateLV(MD, spec)) {
-        LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F)=
);
+        LV.mergeWithMin(getLVForTemplateArgumentList(*spec->TemplateArgume=
nts,
+                                                     F));
         if (F.ConsiderTemplateParameterTypes)
           LV.merge(getLVForTemplateParameterList(
                               spec->getTemplate()->getTemplateParameters()=
));
@@ -567,8 +561,9 @@
     // about whether containing classes have visibility attributes,
     // and that's intentional.
     if (TSK !=3D TSK_ExplicitInstantiationDeclaration &&
+        TSK !=3D TSK_ExplicitInstantiationDefinition &&
         F.ConsiderGlobalVisibility &&
-        MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
+        MD->getASTContext().getLangOpts().InlineVisibilityHidden) {
       // InlineVisibilityHidden only applies to definitions, and
       // isInlined() only gives meaningful answers on definitions
       // anyway.
@@ -586,7 +581,8 @@
       if (shouldConsiderTemplateLV(spec)) {
         // Merge template argument/parameter information for member
         // class template specializations.
-        LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
+        LV.mergeWithMin(getLVForTemplateArgumentList(spec->getTemplateArgs=
(),
+                                                     F));
       if (F.ConsiderTemplateParameterTypes)
         LV.merge(getLVForTemplateParameterList(
                     spec->getSpecializedTemplate()->getTemplateParameters(=
)));
@@ -597,18 +593,11 @@
   } else if (const VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
     // Modify the variable's linkage by its type, but ignore the
     // type's visibility unless it's a definition.
-    LVPair TypeLV =3D VD->getType()->getLinkageAndVisibility();
-    if (TypeLV.first !=3D ExternalLinkage)
+    LinkageInfo TypeLV =3D getLVForType(VD->getType());
+    if (TypeLV.linkage() !=3D ExternalLinkage)
       LV.mergeLinkage(UniqueExternalLinkage);
     if (!LV.visibilityExplicit())
-      LV.mergeVisibility(TypeLV.second);
-  }
-
-  F.ConsiderGlobalVisibility &=3D !LV.visibilityExplicit();
-
-  // Apply -fvisibility if desired.
-  if (F.ConsiderGlobalVisibility && LV.visibility() !=3D HiddenVisibility)=
 {
-    LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMo=
de());
+      LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
   }
=20
   return LV;
@@ -623,6 +612,8 @@
   }
 }
=20
+void NamedDecl::anchor() { }
+
 void NamedDecl::ClearLinkageCache() {
   // Note that we can't skip clearing the linkage of children just
   // because the parent doesn't have cached linkage:  we don't cache
@@ -683,13 +674,13 @@
 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
   // Use the most recent declaration of a variable.
   if (const VarDecl *var =3D dyn_cast<VarDecl>(this))
-    return getVisibilityOf(var->getMostRecentDeclaration());
+    return getVisibilityOf(var->getMostRecentDecl());
=20
   // Use the most recent declaration of a function, and also handle
   // function template specializations.
   if (const FunctionDecl *fn =3D dyn_cast<FunctionDecl>(this)) {
     if (llvm::Optional<Visibility> V
-                            =3D getVisibilityOf(fn->getMostRecentDeclarati=
on()))=20
+                            =3D getVisibilityOf(fn->getMostRecentDecl()))=20
       return V;
=20
     // If the function is a specialization of a template with an
@@ -698,6 +689,12 @@
           =3D fn->getTemplateSpecializationInfo())
       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl=
());
=20
+    // If the function is a member of a specialization of a class template
+    // and the corresponding decl has explicit visibility, use that.
+    FunctionDecl *InstantiatedFrom =3D fn->getInstantiatedFromMemberFuncti=
on();
+    if (InstantiatedFrom)
+      return getVisibilityOf(InstantiatedFrom);
+
     return llvm::Optional<Visibility>();
   }
=20
@@ -712,6 +709,14 @@
         =3D dyn_cast<ClassTemplateSpecializationDecl>(this))
     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDec=
l());
=20
+  // If this is a member class of a specialization of a class template
+  // and the corresponding decl has explicit visibility, use that.
+  if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(this)) {
+    CXXRecordDecl *InstantiatedFrom =3D RD->getInstantiatedFromMemberClass=
();
+    if (InstantiatedFrom)
+      return getVisibilityOf(InstantiatedFrom);
+  }
+
   return llvm::Optional<Visibility>();
 }
=20
@@ -721,19 +726,46 @@
   switch (D->getKind()) {
     default:
       break;
+    case Decl::ParmVar:
+      return LinkageInfo::none();
     case Decl::TemplateTemplateParm: // count these as external
     case Decl::NonTypeTemplateParm:
     case Decl::ObjCAtDefsField:
     case Decl::ObjCCategory:
     case Decl::ObjCCategoryImpl:
     case Decl::ObjCCompatibleAlias:
-    case Decl::ObjCForwardProtocol:
     case Decl::ObjCImplementation:
     case Decl::ObjCMethod:
     case Decl::ObjCProperty:
     case Decl::ObjCPropertyImpl:
     case Decl::ObjCProtocol:
       return LinkageInfo::external();
+     =20
+    case Decl::CXXRecord: {
+      const CXXRecordDecl *Record =3D cast<CXXRecordDecl>(D);
+      if (Record->isLambda()) {
+        if (!Record->getLambdaManglingNumber()) {
+          // This lambda has no mangling number, so it's internal.
+          return LinkageInfo::internal();
+        }
+       =20
+        // This lambda has its linkage/visibility determined by its owner.
+        const DeclContext *DC =3D D->getDeclContext()->getRedeclContext();
+        if (Decl *ContextDecl =3D Record->getLambdaContextDecl()) {
+          if (isa<ParmVarDecl>(ContextDecl))
+            DC =3D ContextDecl->getDeclContext()->getRedeclContext();
+          else
+            return getLVForDecl(cast<NamedDecl>(ContextDecl), Flags);
+        }
+
+        if (const NamedDecl *ND =3D dyn_cast<NamedDecl>(DC))
+          return getLVForDecl(ND, Flags);
+       =20
+        return LinkageInfo::external();
+      }
+     =20
+      break;
+    }
   }
=20
   // Handle linkage for namespace-scope names.
@@ -763,7 +795,8 @@
   //   external linkage.
   if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
     if (const FunctionDecl *Function =3D dyn_cast<FunctionDecl>(D)) {
-      if (Function->isInAnonymousNamespace() && !Function->isExternC())
+      if (Function->isInAnonymousNamespace() &&
+          !Function->getDeclContext()->isExternCContext())
         return LinkageInfo::uniqueExternal();
=20
       LinkageInfo LV;
@@ -772,7 +805,7 @@
           LV.setVisibility(*Vis);
       }
      =20
-      if (const FunctionDecl *Prev =3D Function->getPreviousDeclaration())=
 {
+      if (const FunctionDecl *Prev =3D Function->getPreviousDecl()) {
         LinkageInfo PrevLV =3D getLVForDecl(Prev, Flags);
         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
         LV.mergeVisibility(PrevLV);
@@ -784,7 +817,8 @@
     if (const VarDecl *Var =3D dyn_cast<VarDecl>(D))
       if (Var->getStorageClass() =3D=3D SC_Extern ||
           Var->getStorageClass() =3D=3D SC_PrivateExtern) {
-        if (Var->isInAnonymousNamespace() && !Var->isExternC())
+        if (Var->isInAnonymousNamespace() &&
+            !Var->getDeclContext()->isExternCContext())
           return LinkageInfo::uniqueExternal();
=20
         LinkageInfo LV;
@@ -795,7 +829,7 @@
             LV.setVisibility(*Vis);
         }
        =20
-        if (const VarDecl *Prev =3D Var->getPreviousDeclaration()) {
+        if (const VarDecl *Prev =3D Var->getPreviousDecl()) {
           LinkageInfo PrevLV =3D getLVForDecl(Prev, Flags);
           if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
           LV.mergeVisibility(PrevLV);
@@ -811,7 +845,7 @@
 }
=20
 std::string NamedDecl::getQualifiedNameAsString() const {
-  return getQualifiedNameAsString(getASTContext().getLangOptions());
+  return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
 }
=20
 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) c=
onst {
@@ -904,7 +938,7 @@
=20
   if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(this))
     // For function declarations, we keep track of redeclarations.
-    return FD->getPreviousDeclaration() =3D=3D OldD;
+    return FD->getPreviousDecl() =3D=3D OldD;
=20
   // For function templates, the underlying function declarations are link=
ed.
   if (const FunctionTemplateDecl *FunctionTemplate
@@ -933,6 +967,12 @@
                                         cast<UsingDecl>(OldD)->getQualifie=
r());
   }
=20
+  // A typedef of an Objective-C class type can replace an Objective-C cla=
ss
+  // declaration or definition, and vice versa.
+  if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
+      (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
+    return true;
+ =20
   // For non-function declarations, if the declarations are of the
   // same kind then this must be a redeclaration, or semantic analysis
   // would not have given us the new declaration.
@@ -943,23 +983,21 @@
   return getLinkage() !=3D NoLinkage;
 }
=20
-NamedDecl *NamedDecl::getUnderlyingDecl() {
+NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
   NamedDecl *ND =3D this;
-  while (true) {
-    if (UsingShadowDecl *UD =3D dyn_cast<UsingShadowDecl>(ND))
-      ND =3D UD->getTargetDecl();
-    else if (ObjCCompatibleAliasDecl *AD
-              =3D dyn_cast<ObjCCompatibleAliasDecl>(ND))
-      return AD->getClassInterface();
-    else
-      return ND;
-  }
+  while (UsingShadowDecl *UD =3D dyn_cast<UsingShadowDecl>(ND))
+    ND =3D UD->getTargetDecl();
+
+  if (ObjCCompatibleAliasDecl *AD =3D dyn_cast<ObjCCompatibleAliasDecl>(ND=
))
+    return AD->getClassInterface();
+
+  return ND;
 }
=20
 bool NamedDecl::isCXXInstanceMember() const {
-  assert(isCXXClassMember() &&
-         "checking whether non-member is instance member");
-
+  if (!isCXXClassMember())
+    return false;
+ =20
   const NamedDecl *D =3D this;
   if (isa<UsingShadowDecl>(D))
     D =3D cast<UsingShadowDecl>(D)->getTargetDecl();
@@ -1131,7 +1169,6 @@
   }
=20
   llvm_unreachable("Invalid storage class");
-  return 0;
 }
=20
 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
@@ -1141,6 +1178,12 @@
   return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritte=
n);
 }
=20
+VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
+  return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,=20
+                           QualType(), 0, SC_None, SC_None);
+}
+
 void VarDecl::setStorageClass(StorageClass SC) {
   assert(isLegalForVariable(SC));
   if (getStorageClass() !=3D SC)
@@ -1156,34 +1199,26 @@
 }
=20
 bool VarDecl::isExternC() const {
+  if (getLinkage() !=3D ExternalLinkage)
+    return false;
+
+  const DeclContext *DC =3D getDeclContext();
+  if (DC->isRecord())
+    return false;
+
   ASTContext &Context =3D getASTContext();
-  if (!Context.getLangOptions().CPlusPlus)
-    return (getDeclContext()->isTranslationUnit() &&
-            getStorageClass() !=3D SC_Static) ||
-      (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
-
-  const DeclContext *DC =3D getDeclContext();
-  if (DC->isFunctionOrMethod())
-    return false;
-
-  for (; !DC->isTranslationUnit(); DC =3D DC->getParent()) {
-    if (const LinkageSpecDecl *Linkage =3D dyn_cast<LinkageSpecDecl>(DC)) =
 {
-      if (Linkage->getLanguage() =3D=3D LinkageSpecDecl::lang_c)
-        return getStorageClass() !=3D SC_Static;
-
-      break;
-    }
-
-  }
-
-  return false;
+  if (!Context.getLangOpts().CPlusPlus)
+    return true;
+  return DC->isExternCContext();
 }
=20
 VarDecl *VarDecl::getCanonicalDecl() {
   return getFirstDeclaration();
 }
=20
-VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
+VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
+  ASTContext &C) const
+{
   // C++ [basic.def]p2:
   //   A declaration is a definition unless [...] it contains the 'extern'
   //   specifier or a linkage-specification and neither an initializer [..=
.],
@@ -1214,8 +1249,8 @@
  =20
   if (getStorageClassAsWritten() =3D=3D SC_Extern ||
        getStorageClassAsWritten() =3D=3D SC_PrivateExtern) {
-    for (const VarDecl *PrevVar =3D getPreviousDeclaration();
-         PrevVar; PrevVar =3D PrevVar->getPreviousDeclaration()) {
+    for (const VarDecl *PrevVar =3D getPreviousDecl();
+         PrevVar; PrevVar =3D PrevVar->getPreviousDecl()) {
       if (PrevVar->getLinkage() =3D=3D InternalLinkage && PrevVar->hasInit=
())
         return DeclarationOnly;
     }
@@ -1225,7 +1260,7 @@
   //   and without a storage class specifier or the scs 'static', constitu=
tes
   //   a tentative definition.
   // No such thing in C++.
-  if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
+  if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
     return TentativeDefinition;
=20
   // What's left is (in C, block-scope) declarations without initializers =
or
@@ -1263,23 +1298,26 @@
   return true;
 }
=20
-VarDecl *VarDecl::getDefinition() {
+VarDecl *VarDecl::getDefinition(ASTContext &C) {
   VarDecl *First =3D getFirstDeclaration();
   for (redecl_iterator I =3D First->redecls_begin(), E =3D First->redecls_=
end();
        I !=3D E; ++I) {
-    if ((*I)->isThisDeclarationADefinition() =3D=3D Definition)
+    if ((*I)->isThisDeclarationADefinition(C) =3D=3D Definition)
       return *I;
   }
   return 0;
 }
=20
-VarDecl::DefinitionKind VarDecl::hasDefinition() const {
+VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
   DefinitionKind Kind =3D DeclarationOnly;
  =20
   const VarDecl *First =3D getFirstDeclaration();
   for (redecl_iterator I =3D First->redecls_begin(), E =3D First->redecls_=
end();
-       I !=3D E; ++I)
-    Kind =3D std::max(Kind, (*I)->isThisDeclarationADefinition());
+       I !=3D E; ++I) {
+    Kind =3D std::max(Kind, (*I)->isThisDeclarationADefinition(C));
+    if (Kind =3D=3D Definition)
+      break;
+  }
=20
   return Kind;
 }
@@ -1334,6 +1372,130 @@
   Init =3D I;
 }
=20
+bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
+  const LangOptions &Lang =3D C.getLangOpts();
+
+  if (!Lang.CPlusPlus)
+    return false;
+
+  // In C++11, any variable of reference type can be used in a constant
+  // expression if it is initialized by a constant expression.
+  if (Lang.CPlusPlus0x && getType()->isReferenceType())
+    return true;
+
+  // Only const objects can be used in constant expressions in C++. C++98 =
does
+  // not require the variable to be non-volatile, but we consider this to =
be a
+  // defect.
+  if (!getType().isConstQualified() || getType().isVolatileQualified())
+    return false;
+
+  // In C++, const, non-volatile variables of integral or enumeration types
+  // can be used in constant expressions.
+  if (getType()->isIntegralOrEnumerationType())
+    return true;
+
+  // Additionally, in C++11, non-volatile constexpr variables can be used =
in
+  // constant expressions.
+  return Lang.CPlusPlus0x && isConstexpr();
+}
+
+/// Convert the initializer for this declaration to the elaborated Evaluat=
edStmt
+/// form, which contains extra information on the evaluated value of the
+/// initializer.
+EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
+  EvaluatedStmt *Eval =3D Init.dyn_cast<EvaluatedStmt *>();
+  if (!Eval) {
+    Stmt *S =3D Init.get<Stmt *>();
+    Eval =3D new (getASTContext()) EvaluatedStmt;
+    Eval->Value =3D S;
+    Init =3D Eval;
+  }
+  return Eval;
+}
+
+APValue *VarDecl::evaluateValue() const {
+  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
+  return evaluateValue(Notes);
+}
+
+APValue *VarDecl::evaluateValue(
+    llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
+  EvaluatedStmt *Eval =3D ensureEvaluatedStmt();
+
+  // We only produce notes indicating why an initializer is non-constant t=
he
+  // first time it is evaluated. FIXME: The notes won't always be emitted =
the
+  // first time we try evaluation, so might not be produced at all.
+  if (Eval->WasEvaluated)
+    return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
+
+  const Expr *Init =3D cast<Expr>(Eval->Value);
+  assert(!Init->isValueDependent());
+
+  if (Eval->IsEvaluating) {
+    // FIXME: Produce a diagnostic for self-initialization.
+    Eval->CheckedICE =3D true;
+    Eval->IsICE =3D false;
+    return 0;
+  }
+
+  Eval->IsEvaluating =3D true;
+
+  bool Result =3D Init->EvaluateAsInitializer(Eval->Evaluated, getASTConte=
xt(),
+                                            this, Notes);
+
+  // Ensure the result is an uninitialized APValue if evaluation fails.
+  if (!Result)
+    Eval->Evaluated =3D APValue();
+
+  Eval->IsEvaluating =3D false;
+  Eval->WasEvaluated =3D true;
+
+  // In C++11, we have determined whether the initializer was a constant
+  // expression as a side-effect.
+  if (getASTContext().getLangOpts().CPlusPlus0x && !Eval->CheckedICE) {
+    Eval->CheckedICE =3D true;
+    Eval->IsICE =3D Result && Notes.empty();
+  }
+
+  return Result ? &Eval->Evaluated : 0;
+}
+
+bool VarDecl::checkInitIsICE() const {
+  // Initializers of weak variables are never ICEs.
+  if (isWeak())
+    return false;
+
+  EvaluatedStmt *Eval =3D ensureEvaluatedStmt();
+  if (Eval->CheckedICE)
+    // We have already checked whether this subexpression is an
+    // integral constant expression.
+    return Eval->IsICE;
+
+  const Expr *Init =3D cast<Expr>(Eval->Value);
+  assert(!Init->isValueDependent());
+
+  // In C++11, evaluate the initializer to check whether it's a constant
+  // expression.
+  if (getASTContext().getLangOpts().CPlusPlus0x) {
+    llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
+    evaluateValue(Notes);
+    return Eval->IsICE;
+  }
+
+  // It's an ICE whether or not the definition we found is
+  // out-of-line.  See DR 721 and the discussion in Clang PR
+  // 6206 for details.
+
+  if (Eval->CheckingICE)
+    return false;
+  Eval->CheckingICE =3D true;
+
+  Eval->IsICE =3D Init->isIntegerConstantExpr(getASTContext());
+  Eval->CheckingICE =3D false;
+  Eval->CheckedICE =3D true;
+  return Eval->IsICE;
+}
+
 bool VarDecl::extendsLifetimeOfTemporary() const {
   assert(getType()->isReferenceType() &&"Non-references never extend lifet=
ime");
  =20
@@ -1390,6 +1552,12 @@
                              S, SCAsWritten, DefArg);
 }
=20
+ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
+  return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocatio=
n(),
+                               0, QualType(), 0, SC_None, SC_None, 0);
+}
+
 SourceRange ParmVarDecl::getSourceRange() const {
   if (!hasInheritedDefaultArg()) {
     SourceRange ArgRange =3D getDefaultArgRange();
@@ -1412,21 +1580,6 @@
   return Arg;
 }
=20
-unsigned ParmVarDecl::getNumDefaultArgTemporaries() const {
-  if (const ExprWithCleanups *E =3D dyn_cast<ExprWithCleanups>(getInit()))
-    return E->getNumTemporaries();
-
-  return 0;
-}
-
-CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) {
-  assert(getNumDefaultArgTemporaries() &&=20
-         "Default arguments does not have any temporaries!");
-
-  ExprWithCleanups *E =3D cast<ExprWithCleanups>(getInit());
-  return E->getTemporary(i);
-}
-
 SourceRange ParmVarDecl::getDefaultArgRange() const {
   if (const Expr *E =3D getInit())
     return E->getSourceRange();
@@ -1540,7 +1693,7 @@
   const TranslationUnitDecl *tunit =3D
     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
   return tunit &&
-         !tunit->getASTContext().getLangOptions().Freestanding &&
+         !tunit->getASTContext().getLangOpts().Freestanding &&
          getIdentifier() &&
          getIdentifier()->isStr("main");
 }
@@ -1568,27 +1721,21 @@
 }
=20
 bool FunctionDecl::isExternC() const {
-  ASTContext &Context =3D getASTContext();
-  // In C, any non-static, non-overloadable function has external
-  // linkage.
-  if (!Context.getLangOptions().CPlusPlus)
-    return getStorageClass() !=3D SC_Static && !getAttr<OverloadableAttr>(=
);
+  if (getLinkage() !=3D ExternalLinkage)
+    return false;
+
+  if (getAttr<OverloadableAttr>())
+    return false;
=20
   const DeclContext *DC =3D getDeclContext();
   if (DC->isRecord())
     return false;
=20
-  for (; !DC->isTranslationUnit(); DC =3D DC->getParent()) {
-    if (const LinkageSpecDecl *Linkage =3D dyn_cast<LinkageSpecDecl>(DC)) =
 {
-      if (Linkage->getLanguage() =3D=3D LinkageSpecDecl::lang_c)
-        return getStorageClass() !=3D SC_Static &&
-               !getAttr<OverloadableAttr>();
-
-      break;
-    }
-  }
-
-  return isMain();
+  ASTContext &Context =3D getASTContext();
+  if (!Context.getLangOpts().CPlusPlus)
+    return true;
+
+  return isMain() || DC->isExternCContext();
 }
=20
 bool FunctionDecl::isGlobal() const {
@@ -1622,7 +1769,7 @@
     FunTmpl->setPreviousDeclaration(PrevFunTmpl);
   }
  =20
-  if (PrevDecl->IsInline)
+  if (PrevDecl && PrevDecl->IsInline)
     IsInline =3D true;
 }
=20
@@ -1652,11 +1799,14 @@
 /// value of type \c Builtin::ID if in the target-independent range
 /// \c [1,Builtin::First), or a target-specific builtin value.
 unsigned FunctionDecl::getBuiltinID() const {
+  if (!getIdentifier())
+    return 0;
+
+  unsigned BuiltinID =3D getIdentifier()->getBuiltinID();
+  if (!BuiltinID)
+    return 0;
+
   ASTContext &Context =3D getASTContext();
-  if (!getIdentifier() || !getIdentifier()->getBuiltinID())
-    return 0;
-
-  unsigned BuiltinID =3D getIdentifier()->getBuiltinID();
   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
     return BuiltinID;
=20
@@ -1670,7 +1820,7 @@
=20
   // If this function is at translation-unit scope and we're not in
   // C++, it refers to the C library function.
-  if (!Context.getLangOptions().CPlusPlus &&
+  if (!Context.getLangOpts().CPlusPlus &&
       getDeclContext()->isTranslationUnit())
     return BuiltinID;
=20
@@ -1710,12 +1860,22 @@
   }
 }
=20
+void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> Ne=
wDecls) {
+  assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
+
+  if (!NewDecls.empty()) {
+    NamedDecl **A =3D new (getASTContext()) NamedDecl*[NewDecls.size()];
+    std::copy(NewDecls.begin(), NewDecls.end(), A);
+    DeclsInPrototypeScope =3D llvm::ArrayRef<NamedDecl*>(A, NewDecls.size(=
));
+  }
+}
+
 /// getMinRequiredArguments - Returns the minimum number of arguments
 /// needed to call this function. This may be fewer than the number of
 /// function parameters, if some of the parameters have default
 /// arguments (in C++) or the last parameter is a parameter pack.
 unsigned FunctionDecl::getMinRequiredArguments() const {
-  if (!getASTContext().getLangOptions().CPlusPlus)
+  if (!getASTContext().getLangOpts().CPlusPlus)
     return getNumParams();
  =20
   unsigned NumRequiredArgs =3D getNumParams(); =20
@@ -1777,31 +1937,79 @@
   return false;
 }
=20
+static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
+  // Only consider file-scope declarations in this test.
+  if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
+    return false;
+
+  // Only consider explicit declarations; the presence of a builtin for a
+  // libcall shouldn't affect whether a definition is externally visible.
+  if (Redecl->isImplicit())
+    return false;
+
+  if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() =3D=3D SC_=
Extern)=20
+    return true; // Not an inline definition
+
+  return false;
+}
+
 /// \brief For a function declaration in C or C++, determine whether this
 /// declaration causes the definition to be externally visible.
 ///
-/// Determines whether this is the first non-inline redeclaration of an in=
line
-/// function in a language where "inline" does not normally require an
-/// externally visible definition.
+/// Specifically, this determines if adding the current declaration to the=
 set
+/// of redeclarations of the given functions causes
+/// isInlineDefinitionExternallyVisible to change from false to true.
 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const=
 {
   assert(!doesThisDeclarationHaveABody() &&
          "Must have a declaration without a body.");
=20
   ASTContext &Context =3D getASTContext();
=20
-  // In C99 mode, a function may have an inline definition (causing it to
-  // be deferred) then redeclared later.  As a special case, "extern inlin=
e"
-  // is not required to produce an external symbol.
-  if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 =
||
-      Context.getLangOptions().CPlusPlus)
+  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
+    // With GNU inlining, a declaration with 'inline' but not 'extern', fo=
rces
+    // an externally visible definition.
+    //
+    // FIXME: What happens if gnu_inline gets added on after the first
+    // declaration?
+    if (!isInlineSpecified() || getStorageClassAsWritten() =3D=3D SC_Exter=
n)
+      return false;
+
+    const FunctionDecl *Prev =3D this;
+    bool FoundBody =3D false;
+    while ((Prev =3D Prev->getPreviousDecl())) {
+      FoundBody |=3D Prev->Body;
+
+      if (Prev->Body) {
+        // If it's not the case that both 'inline' and 'extern' are
+        // specified on the definition, then it is always externally visib=
le.
+        if (!Prev->isInlineSpecified() ||
+            Prev->getStorageClassAsWritten() !=3D SC_Extern)
+          return false;
+      } else if (Prev->isInlineSpecified() &&=20
+                 Prev->getStorageClassAsWritten() !=3D SC_Extern) {
+        return false;
+      }
+    }
+    return FoundBody;
+  }
+
+  if (Context.getLangOpts().CPlusPlus)
     return false;
-  if (getLinkage() !=3D ExternalLinkage || isInlineSpecified())
+
+  // C99 6.7.4p6:
+  //   [...] If all of the file scope declarations for a function in a=20
+  //   translation unit include the inline function specifier without exte=
rn,=20
+  //   then the definition in that translation unit is an inline definitio=
n.
+  if (isInlineSpecified() && getStorageClass() !=3D SC_Extern)
     return false;
-  const FunctionDecl *Definition =3D 0;
-  if (hasBody(Definition))
-    return Definition->isInlined() &&
-           Definition->isInlineDefinitionExternallyVisible();
-  return false;
+  const FunctionDecl *Prev =3D this;
+  bool FoundBody =3D false;
+  while ((Prev =3D Prev->getPreviousDecl())) {
+    FoundBody |=3D Prev->Body;
+    if (RedeclForcesDefC99(Prev))
+      return false;
+  }
+  return FoundBody;
 }
=20
 /// \brief For an inline function definition in C or C++, determine whethe=
r the=20
@@ -1826,7 +2034,10 @@
   assert(isInlined() && "Function must be inline");
   ASTContext &Context =3D getASTContext();
  =20
-  if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
+  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
+    // Note: If you change the logic here, please change
+    // doesDeclarationForceExternallyVisibleDefinition as well.
+    //
     // If it's not the case that both 'inline' and 'extern' are
     // specified on the definition, then this inline definition is
     // externally visible.
@@ -1845,7 +2056,7 @@
    =20
     return false;
   }
- =20
+
   // C99 6.7.4p6:
   //   [...] If all of the file scope declarations for a function in a=20
   //   translation unit include the inline function specifier without exte=
rn,=20
@@ -1853,17 +2064,8 @@
   for (redecl_iterator Redecl =3D redecls_begin(), RedeclEnd =3D redecls_e=
nd();
        Redecl !=3D RedeclEnd;
        ++Redecl) {
-    // Only consider file-scope declarations in this test.
-    if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
-      continue;
-
-    // Only consider explicit declarations; the presence of a builtin for a
-    // libcall shouldn't affect whether a definition is externally visible.
-    if (Redecl->isImplicit())
-      continue;
-
-    if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() =3D=3D S=
C_Extern)=20
-      return true; // Not an inline definition
+    if (RedeclForcesDefC99(*Redecl))
+      return true;
   }
  =20
   // C99 6.7.4p6:
@@ -1966,7 +2168,20 @@
     return true;
=20
   return PatternDecl->isInlined();
-}                     =20
+}
+
+bool FunctionDecl::isTemplateInstantiation() const {
+  switch (getTemplateSpecializationKind()) {
+    case TSK_Undeclared:
+    case TSK_ExplicitSpecialization:
+      return false;     =20
+    case TSK_ImplicitInstantiation:
+    case TSK_ExplicitInstantiationDeclaration:
+    case TSK_ExplicitInstantiationDefinition:
+      return true;
+  }
+  llvm_unreachable("All TSK values handled.");
+}
   =20
 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
   // Handle class scope explicit specialization special case.
@@ -2040,22 +2255,7 @@
                                                       TemplateArgsAsWritte=
n,
                                                       PointOfInstantiation=
);
   TemplateOrSpecialization =3D Info;
-
-  // Insert this function template specialization into the set of known
-  // function template specializations.
-  if (InsertPos)
-    Template->addSpecialization(Info, InsertPos);
-  else {
-    // Try to insert the new node. If there is an existing node, leave it,=
 the
-    // set will contain the canonical decls while
-    // FunctionTemplateDecl::findSpecialization will return
-    // the most recent redeclarations.
-    FunctionTemplateSpecializationInfo *Existing
-      =3D Template->getSpecializations().GetOrInsertNode(Info);
-    (void)Existing;
-    assert((!Existing || Existing->Function->isCanonicalDecl()) &&
-           "Set is supposed to only contain canonical decls");
-  }
+  Template->addSpecialization(Info, InsertPos);
 }
=20
 void
@@ -2169,6 +2369,92 @@
   return SourceRange(getOuterLocStart(), EndRangeLoc);
 }
=20
+unsigned FunctionDecl::getMemoryFunctionKind() const {
+  IdentifierInfo *FnInfo =3D getIdentifier();
+
+  if (!FnInfo)
+    return 0;
+   =20
+  // Builtin handling.
+  switch (getBuiltinID()) {
+  case Builtin::BI__builtin_memset:
+  case Builtin::BI__builtin___memset_chk:
+  case Builtin::BImemset:
+    return Builtin::BImemset;
+
+  case Builtin::BI__builtin_memcpy:
+  case Builtin::BI__builtin___memcpy_chk:
+  case Builtin::BImemcpy:
+    return Builtin::BImemcpy;
+
+  case Builtin::BI__builtin_memmove:
+  case Builtin::BI__builtin___memmove_chk:
+  case Builtin::BImemmove:
+    return Builtin::BImemmove;
+
+  case Builtin::BIstrlcpy:
+    return Builtin::BIstrlcpy;
+  case Builtin::BIstrlcat:
+    return Builtin::BIstrlcat;
+
+  case Builtin::BI__builtin_memcmp:
+  case Builtin::BImemcmp:
+    return Builtin::BImemcmp;
+
+  case Builtin::BI__builtin_strncpy:
+  case Builtin::BI__builtin___strncpy_chk:
+  case Builtin::BIstrncpy:
+    return Builtin::BIstrncpy;
+
+  case Builtin::BI__builtin_strncmp:
+  case Builtin::BIstrncmp:
+    return Builtin::BIstrncmp;
+
+  case Builtin::BI__builtin_strncasecmp:
+  case Builtin::BIstrncasecmp:
+    return Builtin::BIstrncasecmp;
+
+  case Builtin::BI__builtin_strncat:
+  case Builtin::BI__builtin___strncat_chk:
+  case Builtin::BIstrncat:
+    return Builtin::BIstrncat;
+
+  case Builtin::BI__builtin_strndup:
+  case Builtin::BIstrndup:
+    return Builtin::BIstrndup;
+
+  case Builtin::BI__builtin_strlen:
+  case Builtin::BIstrlen:
+    return Builtin::BIstrlen;
+
+  default:
+    if (isExternC()) {
+      if (FnInfo->isStr("memset"))
+        return Builtin::BImemset;
+      else if (FnInfo->isStr("memcpy"))
+        return Builtin::BImemcpy;
+      else if (FnInfo->isStr("memmove"))
+        return Builtin::BImemmove;
+      else if (FnInfo->isStr("memcmp"))
+        return Builtin::BImemcmp;
+      else if (FnInfo->isStr("strncpy"))
+        return Builtin::BIstrncpy;
+      else if (FnInfo->isStr("strncmp"))
+        return Builtin::BIstrncmp;
+      else if (FnInfo->isStr("strncasecmp"))
+        return Builtin::BIstrncasecmp;
+      else if (FnInfo->isStr("strncat"))
+        return Builtin::BIstrncat;
+      else if (FnInfo->isStr("strndup"))
+        return Builtin::BIstrndup;
+      else if (FnInfo->isStr("strlen"))
+        return Builtin::BIstrlen;
+    }
+    break;
+  }
+  return 0;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // FieldDecl Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2182,6 +2468,12 @@
                            BW, Mutable, HasInit);
 }
=20
+FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
+  return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
+                             0, QualType(), 0, 0, false, false);
+}
+
 bool FieldDecl::isAnonymousStructOrUnion() const {
   if (!isImplicit() || getDeclName())
     return false;
@@ -2201,31 +2493,27 @@
 unsigned FieldDecl::getFieldIndex() const {
   if (CachedFieldIndex) return CachedFieldIndex - 1;
=20
-  unsigned index =3D 0;
+  unsigned Index =3D 0;
   const RecordDecl *RD =3D getParent();
   const FieldDecl *LastFD =3D 0;
   bool IsMsStruct =3D RD->hasAttr<MsStructAttr>();
- =20
-  RecordDecl::field_iterator i =3D RD->field_begin(), e =3D RD->field_end(=
);
-  while (true) {
-    assert(i !=3D e && "failed to find field in parent!");
-    if (*i =3D=3D this)
-      break;
+
+  for (RecordDecl::field_iterator I =3D RD->field_begin(), E =3D RD->field=
_end();
+       I !=3D E; ++I, ++Index) {
+    (*I)->CachedFieldIndex =3D Index + 1;
=20
     if (IsMsStruct) {
       // Zero-length bitfields following non-bitfield members are ignored.
-      if (getASTContext().ZeroBitfieldFollowsNonBitfield((*i), LastFD)) {
-        ++i;
+      if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
+        --Index;
         continue;
       }
-      LastFD =3D (*i);
+      LastFD =3D (*I);
     }
-    ++i;
-    ++index;
   }
=20
-  CachedFieldIndex =3D index + 1;
-  return index;
+  assert(CachedFieldIndex && "failed to find field in parent");
+  return CachedFieldIndex - 1;
 }
=20
 SourceRange FieldDecl::getSourceRange() const {
@@ -2339,6 +2627,8 @@
 // EnumDecl Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void EnumDecl::anchor() { }
+
 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
                            SourceLocation StartLoc, SourceLocation IdLoc,
                            IdentifierInfo *Id,
@@ -2350,9 +2640,10 @@
   return Enum;
 }
=20
-EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
-  return new (C) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
-                          false, false, false);
+EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
+  return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
+                            false, false, false);
 }
=20
 void EnumDecl::completeDefinition(QualType NewType,
@@ -2368,6 +2659,37 @@
   TagDecl::completeDefinition();
 }
=20
+TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const=
 {
+  if (MemberSpecializationInfo *MSI =3D getMemberSpecializationInfo())
+    return MSI->getTemplateSpecializationKind();
+
+  return TSK_Undeclared;
+}
+
+void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TS=
K,
+                                         SourceLocation PointOfInstantiati=
on) {
+  MemberSpecializationInfo *MSI =3D getMemberSpecializationInfo();
+  assert(MSI && "Not an instantiated member enumeration?");
+  MSI->setTemplateSpecializationKind(TSK);
+  if (TSK !=3D TSK_ExplicitSpecialization &&
+      PointOfInstantiation.isValid() &&
+      MSI->getPointOfInstantiation().isInvalid())
+    MSI->setPointOfInstantiation(PointOfInstantiation);
+}
+
+EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
+  if (SpecializationInfo)
+    return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
+
+  return 0;
+}
+
+void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
+                                            TemplateSpecializationKind TSK=
) {
+  assert(!SpecializationInfo && "Member enum is already a specialization");
+  SpecializationInfo =3D new (C) MemberSpecializationInfo(ED, TSK);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // RecordDecl Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2392,9 +2714,10 @@
   return R;
 }
=20
-RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
-  return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
-                            SourceLocation(), 0, 0);
+RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned I=
D) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
+  return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
+                              SourceLocation(), 0, 0);
 }
=20
 bool RecordDecl::isInjectedClassName() const {
@@ -2502,10 +2825,14 @@
 // Other Decl Allocation/Deallocation Method Implementations
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void TranslationUnitDecl::anchor() { }
+
 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
   return new (C) TranslationUnitDecl(C);
 }
=20
+void LabelDecl::anchor() { }
+
 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
                              SourceLocation IdentL, IdentifierInfo *II) {
   return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
@@ -2518,17 +2845,14 @@
   return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
 }
=20
-
-NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
-                                     SourceLocation StartLoc,
-                                     SourceLocation IdLoc, IdentifierInfo =
*Id) {
-  return new (C) NamespaceDecl(DC, StartLoc, IdLoc, Id);
+LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
+  return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
 }
=20
-NamespaceDecl *NamespaceDecl::getNextNamespace() {
-  return dyn_cast_or_null<NamespaceDecl>(
-                       NextNamespace.get(getASTContext().getExternalSource=
()));
-}
+void ValueDecl::anchor() { }
+
+void ImplicitParamDecl::anchor() { }
=20
 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *D=
C,
                                              SourceLocation IdLoc,
@@ -2537,6 +2861,12 @@
   return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
 }
=20
+ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,=20
+                                                         unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
+  return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
+}
+
 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
                                    SourceLocation StartLoc,
                                    const DeclarationNameInfo &NameInfo,
@@ -2553,10 +2883,22 @@
   return New;
 }
=20
+FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID)=
 {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
+  return new (Mem) FunctionDecl(Function, 0, SourceLocation(),=20
+                                DeclarationNameInfo(), QualType(), 0,
+                                SC_None, SC_None, false, false);
+}
+
 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocatio=
n L) {
   return new (C) BlockDecl(DC, L);
 }
=20
+BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
+  return new (Mem) BlockDecl(0, SourceLocation());
+}
+
 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
                                            SourceLocation L,
                                            IdentifierInfo *Id, QualType T,
@@ -2564,6 +2906,15 @@
   return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
 }
=20
+EnumConstantDecl *
+EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
+  return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,=20
+                                    llvm::APSInt());
+}
+
+void IndirectFieldDecl::anchor() { }
+
 IndirectFieldDecl *
 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
@@ -2571,6 +2922,13 @@
   return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
 }
=20
+IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
+                                                         unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
+  return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(=
),
+                                     QualType(), 0, 0);
+}
+
 SourceRange EnumConstantDecl::getSourceRange() const {
   SourceLocation End =3D getLocation();
   if (Init)
@@ -2578,12 +2936,21 @@
   return SourceRange(getLocation(), End);
 }
=20
+void TypeDecl::anchor() { }
+
 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
                                  SourceLocation StartLoc, SourceLocation I=
dLoc,
                                  IdentifierInfo *Id, TypeSourceInfo *TInfo=
) {
   return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
 }
=20
+void TypedefNameDecl::anchor() { }
+
+TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
+  return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0=
);
+}
+
 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
                                      SourceLocation StartLoc,
                                      SourceLocation IdLoc, IdentifierInfo =
*Id,
@@ -2591,6 +2958,11 @@
   return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
 }
=20
+TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned I=
D) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
+  return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0,=
 0);
+}
+
 SourceRange TypedefDecl::getSourceRange() const {
   SourceLocation RangeEnd =3D getLocation();
   if (TypeSourceInfo *TInfo =3D getTypeSourceInfo()) {
@@ -2607,9 +2979,96 @@
   return SourceRange(getLocStart(), RangeEnd);
 }
=20
+void FileScopeAsmDecl::anchor() { }
+
 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
                                            StringLiteral *Str,
                                            SourceLocation AsmLoc,
                                            SourceLocation RParenLoc) {
   return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
 }
+
+FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,=20
+                                                       unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
+  return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation=
());
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// ImportDecl Implementation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+/// \brief Retrieve the number of module identifiers needed to name the gi=
ven
+/// module.
+static unsigned getNumModuleIdentifiers(Module *Mod) {
+  unsigned Result =3D 1;
+  while (Mod->Parent) {
+    Mod =3D Mod->Parent;
+    ++Result;
+  }
+  return Result;
+}
+
+ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,=20
+                       Module *Imported,
+                       ArrayRef<SourceLocation> IdentifierLocs)
+  : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
+    NextLocalImport()
+{
+  assert(getNumModuleIdentifiers(Imported) =3D=3D IdentifierLocs.size());
+  SourceLocation *StoredLocs =3D reinterpret_cast<SourceLocation *>(this +=
 1);
+  memcpy(StoredLocs, IdentifierLocs.data(),=20
+         IdentifierLocs.size() * sizeof(SourceLocation));
+}
+
+ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,=20
+                       Module *Imported, SourceLocation EndLoc)
+  : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
+    NextLocalImport()
+{
+  *reinterpret_cast<SourceLocation *>(this + 1) =3D EndLoc;
+}
+
+ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,=20
+                               SourceLocation StartLoc, Module *Imported,
+                               ArrayRef<SourceLocation> IdentifierLocs) {
+  void *Mem =3D C.Allocate(sizeof(ImportDecl) +=20
+                         IdentifierLocs.size() * sizeof(SourceLocation));
+  return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
+}
+
+ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,=20
+                                       SourceLocation StartLoc,
+                                       Module *Imported,=20
+                                       SourceLocation EndLoc) {
+  void *Mem =3D C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
+  ImportDecl *Import =3D new (Mem) ImportDecl(DC, StartLoc, Imported, EndL=
oc);
+  Import->setImplicit();
+  return Import;
+}
+
+ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
+                                           unsigned NumLocations) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID,=20
+                                       (sizeof(ImportDecl) +=20
+                                        NumLocations * sizeof(SourceLocati=
on)));
+  return new (Mem) ImportDecl(EmptyShell()); =20
+}
+
+ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
+  if (!ImportedAndComplete.getInt())
+    return ArrayRef<SourceLocation>();
+
+  const SourceLocation *StoredLocs
+    =3D reinterpret_cast<const SourceLocation *>(this + 1);
+  return ArrayRef<SourceLocation>(StoredLocs,=20
+                                  getNumModuleIdentifiers(getImportedModul=
e()));
+}
+
+SourceRange ImportDecl::getSourceRange() const {
+  if (!ImportedAndComplete.getInt())
+    return SourceRange(getLocation(),=20
+                       *reinterpret_cast<const SourceLocation *>(this + 1)=
);
+ =20
+  return SourceRange(getLocation(), getIdentifierLocs().back());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DeclBase.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DeclBase.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DeclBase.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -39,7 +39,24 @@
 #define ABSTRACT_DECL(DECL)
 #include "clang/AST/DeclNodes.inc"
=20
-static bool StatSwitch =3D false;
+void *Decl::AllocateDeserializedDecl(const ASTContext &Context,=20
+                                     unsigned ID,
+                                     unsigned Size) {
+  // Allocate an extra 8 bytes worth of storage, which ensures that the
+  // resulting pointer will still be 8-byte aligned.=20
+  void *Start =3D Context.Allocate(Size + 8);
+  void *Result =3D (char*)Start + 8;
+ =20
+  unsigned *PrefixPtr =3D (unsigned *)Result - 2;
+ =20
+  // Zero out the first 4 bytes; this is used to store the owning module I=
D.
+  PrefixPtr[0] =3D 0;
+ =20
+  // Store the global declaration ID in the second 4 bytes.
+  PrefixPtr[1] =3D ID;
+ =20
+  return Result;
+}
=20
 const char *Decl::getDeclKindName() const {
   switch (DeclKind) {
@@ -52,7 +69,7 @@
=20
 void Decl::setInvalidDecl(bool Invalid) {
   InvalidDecl =3D Invalid;
-  if (Invalid) {
+  if (Invalid && !isa<ParmVarDecl>(this)) {
     // Defensive maneuver for ill-formed code: we're likely not to make it=
 to
     // a point where we set the access specifier, so default it to "public"
     // to avoid triggering asserts elsewhere in the front end.=20
@@ -69,9 +86,9 @@
   }
 }
=20
-bool Decl::CollectingStats(bool Enable) {
-  if (Enable) StatSwitch =3D true;
-  return StatSwitch;
+bool Decl::StatisticsEnabled =3D false;
+void Decl::EnableStatistics() {
+  StatisticsEnabled =3D true;
 }
=20
 void Decl::PrintStats() {
@@ -100,7 +117,6 @@
=20
 void Decl::add(Kind k) {
   switch (k) {
-  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
 #define ABSTRACT_DECL(DECL)
 #include "clang/AST/DeclNodes.inc"
@@ -185,15 +201,24 @@
     return;
=20
   if (isInSemaDC()) {
-    MultipleDC *MDC =3D new (getASTContext()) MultipleDC();
-    MDC->SemanticDC =3D getDeclContext();
-    MDC->LexicalDC =3D DC;
-    DeclCtx =3D MDC;
+    setDeclContextsImpl(getDeclContext(), DC, getASTContext());
   } else {
     getMultipleDC()->LexicalDC =3D DC;
   }
 }
=20
+void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
+                               ASTContext &Ctx) {
+  if (SemaDC =3D=3D LexicalDC) {
+    DeclCtx =3D SemaDC;
+  } else {
+    Decl::MultipleDC *MDC =3D new (Ctx) Decl::MultipleDC();
+    MDC->SemanticDC =3D SemaDC;
+    MDC->LexicalDC =3D LexicalDC;
+    DeclCtx =3D MDC;
+  }
+}
+
 bool Decl::isInAnonymousNamespace() const {
   const DeclContext *DC =3D getDeclContext();
   do {
@@ -282,13 +307,20 @@
   // Match the platform name.
   if (A->getPlatform()->getName() !=3D TargetPlatform)
     return AR_Available;
-
+ =20
+  std::string HintMessage;
+  if (!A->getMessage().empty()) {
+    HintMessage =3D " - ";
+    HintMessage +=3D A->getMessage();
+  }
+ =20
   // Make sure that this declaration has not been marked 'unavailable'.
   if (A->getUnavailable()) {
     if (Message) {
       Message->clear();
       llvm::raw_string_ostream Out(*Message);
-      Out << "not available on " << PrettyPlatformName;
+      Out << "not available on " << PrettyPlatformName=20
+          << HintMessage;
     }
=20
     return AR_Unavailable;
@@ -301,7 +333,7 @@
       Message->clear();
       llvm::raw_string_ostream Out(*Message);
       Out << "introduced in " << PrettyPlatformName << ' '=20
-          << A->getIntroduced();
+          << A->getIntroduced() << HintMessage;
     }
=20
     return AR_NotYetIntroduced;
@@ -313,7 +345,7 @@
       Message->clear();
       llvm::raw_string_ostream Out(*Message);
       Out << "obsoleted in " << PrettyPlatformName << ' '=20
-          << A->getObsoleted();
+          << A->getObsoleted() << HintMessage;
     }
    =20
     return AR_Unavailable;
@@ -325,7 +357,7 @@
       Message->clear();
       llvm::raw_string_ostream Out(*Message);
       Out << "first deprecated in " << PrettyPlatformName << ' '
-          << A->getDeprecated();
+          << A->getDeprecated() << HintMessage;
     }
    =20
     return AR_Deprecated;
@@ -391,7 +423,7 @@
     }
   } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this))
     return false;
-  else if (!(getASTContext().getLangOptions().ObjCNonFragileABI &&
+  else if (!(getASTContext().getLangOpts().ObjCNonFragileABI &&
              isa<ObjCInterfaceDecl>(this)))
     return false;
=20
@@ -488,9 +520,7 @@
     case LinkageSpec:
     case FileScopeAsm:
     case StaticAssert:
-    case ObjCClass:
     case ObjCPropertyImpl:
-    case ObjCForwardProtocol:
     case Block:
     case TranslationUnit:
=20
@@ -501,17 +531,18 @@
     case ObjCImplementation:
     case ObjCCategory:
     case ObjCCategoryImpl:
+    case Import:
       // Never looked up by name.
       return 0;
   }
=20
-  return 0;
+  llvm_unreachable("Invalid DeclKind!");
 }
=20
-void Decl::setAttrs(const AttrVec &attrs) {
+void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
   assert(!HasAttrs && "Decl already contains attrs.");
=20
-  AttrVec &AttrBlank =3D getASTContext().getDeclAttrs(this);
+  AttrVec &AttrBlank =3D Ctx.getDeclAttrs(this);
   assert(AttrBlank.empty() && "HasAttrs was wrong?");
=20
   AttrBlank =3D attrs;
@@ -640,7 +671,11 @@
 }
=20
 DeclContext *Decl::getNonClosureContext() {
-  DeclContext *DC =3D getDeclContext();
+  return getDeclContext()->getNonClosureAncestor();
+}
+
+DeclContext *DeclContext::getNonClosureAncestor() {
+  DeclContext *DC =3D this;
=20
   // This is basically "while (DC->isClosure()) DC =3D DC->getParent();"
   // except that it's significantly more efficient to cast to a known
@@ -704,10 +739,14 @@
   if (isa<ClassTemplatePartialSpecializationDecl>(this))
     return true;
=20
-  if (const CXXRecordDecl *Record =3D dyn_cast<CXXRecordDecl>(this))
+  if (const CXXRecordDecl *Record =3D dyn_cast<CXXRecordDecl>(this)) {
     if (Record->getDescribedClassTemplate())
       return true;
-
+   =20
+    if (Record->isDependentLambda())
+      return true;
+  }
+ =20
   if (const FunctionDecl *Function =3D dyn_cast<FunctionDecl>(this)) {
     if (Function->getDescribedFunctionTemplate())
       return true;
@@ -767,9 +806,18 @@
     return this;
=20
   case Decl::ObjCInterface:
+    if (ObjCInterfaceDecl *Def =3D cast<ObjCInterfaceDecl>(this)->getDefin=
ition())
+      return Def;
+     =20
+    return this;
+     =20
   case Decl::ObjCProtocol:
+    if (ObjCProtocolDecl *Def =3D cast<ObjCProtocolDecl>(this)->getDefinit=
ion())
+      return Def;
+   =20
+    return this;
+     =20
   case Decl::ObjCCategory:
-    // FIXME: Can Objective-C interfaces be forward-declared?
     return this;
=20
   case Decl::ObjCImplementation:
@@ -804,21 +852,27 @@
   }
 }
=20
-DeclContext *DeclContext::getNextContext() {
-  switch (DeclKind) {
-  case Decl::Namespace:
-    // Return the next namespace
-    return static_cast<NamespaceDecl*>(this)->getNextNamespace();
-
-  default:
-    return 0;
+void=20
+DeclContext::collectAllContexts(llvm::SmallVectorImpl<DeclContext *> &Cont=
exts){
+  Contexts.clear();
+ =20
+  if (DeclKind !=3D Decl::Namespace) {
+    Contexts.push_back(this);
+    return;
   }
+ =20
+  NamespaceDecl *Self =3D static_cast<NamespaceDecl *>(this);
+  for (NamespaceDecl *N =3D Self->getMostRecentDecl(); N;
+       N =3D N->getPreviousDecl())
+    Contexts.push_back(N);
+ =20
+  std::reverse(Contexts.begin(), Contexts.end());
 }
=20
 std::pair<Decl *, Decl *>
-DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls,
+DeclContext::BuildDeclChain(ArrayRef<Decl*> Decls,
                             bool FieldsAlreadyLoaded) {
-  // Build up a chain of declarations via the Decl::NextDeclInContext fiel=
d.
+  // Build up a chain of declarations via the Decl::NextInContextAndBits f=
ield.
   Decl *FirstNewDecl =3D 0;
   Decl *PrevDecl =3D 0;
   for (unsigned I =3D 0, N =3D Decls.size(); I !=3D N; ++I) {
@@ -827,7 +881,7 @@
=20
     Decl *D =3D Decls[I];
     if (PrevDecl)
-      PrevDecl->NextDeclInContext =3D D;
+      PrevDecl->NextInContextAndBits.setPointer(D);
     else
       FirstNewDecl =3D D;
=20
@@ -873,7 +927,7 @@
   Decl *ExternalFirst, *ExternalLast;
   llvm::tie(ExternalFirst, ExternalLast) =3D BuildDeclChain(Decls,
                                                           FieldsAlreadyLoa=
ded);
-  ExternalLast->NextDeclInContext =3D FirstDecl;
+  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
   FirstDecl =3D ExternalFirst;
   if (!LastDecl)
     LastDecl =3D ExternalLast;
@@ -884,7 +938,7 @@
                                                     DeclarationName Name) {
   ASTContext &Context =3D DC->getParentASTContext();
   StoredDeclsMap *Map;
-  if (!(Map =3D DC->LookupPtr))
+  if (!(Map =3D DC->LookupPtr.getPointer()))
     Map =3D DC->CreateStoredDeclsMap(Context);
=20
   StoredDeclsList &List =3D (*Map)[Name];
@@ -901,7 +955,7 @@
   ASTContext &Context =3D DC->getParentASTContext();;
=20
   StoredDeclsMap *Map;
-  if (!(Map =3D DC->LookupPtr))
+  if (!(Map =3D DC->LookupPtr.getPointer()))
     Map =3D DC->CreateStoredDeclsMap(Context);
=20
   StoredDeclsList &List =3D (*Map)[Name];
@@ -948,7 +1002,7 @@
 void DeclContext::removeDecl(Decl *D) {
   assert(D->getLexicalDeclContext() =3D=3D this &&
          "decl being removed from non-lexical context");
-  assert((D->NextDeclInContext || D =3D=3D LastDecl) &&
+  assert((D->NextInContextAndBits.getPointer() || D =3D=3D LastDecl) &&
          "decl is not in decls list");
=20
   // Remove D from the decl chain.  This is O(n) but hopefully rare.
@@ -956,12 +1010,12 @@
     if (D =3D=3D LastDecl)
       FirstDecl =3D LastDecl =3D 0;
     else
-      FirstDecl =3D D->NextDeclInContext;
+      FirstDecl =3D D->NextInContextAndBits.getPointer();
   } else {
-    for (Decl *I =3D FirstDecl; true; I =3D I->NextDeclInContext) {
+    for (Decl *I =3D FirstDecl; true; I =3D I->NextInContextAndBits.getPoi=
nter()) {
       assert(I && "decl not found in linked list");
-      if (I->NextDeclInContext =3D=3D D) {
-        I->NextDeclInContext =3D D->NextDeclInContext;
+      if (I->NextInContextAndBits.getPointer() =3D=3D D) {
+        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPoin=
ter());
         if (D =3D=3D LastDecl) LastDecl =3D I;
         break;
       }
@@ -969,7 +1023,7 @@
   }
  =20
   // Mark that D is no longer in the decl chain.
-  D->NextDeclInContext =3D 0;
+  D->NextInContextAndBits.setPointer(0);
=20
   // Remove D from the lookup table if necessary.
   if (isa<NamedDecl>(D)) {
@@ -978,12 +1032,13 @@
     // Remove only decls that have a name
     if (!ND->getDeclName()) return;
=20
-    StoredDeclsMap *Map =3D getPrimaryContext()->LookupPtr;
+    StoredDeclsMap *Map =3D getPrimaryContext()->LookupPtr.getPointer();
     if (!Map) return;
=20
     StoredDeclsMap::iterator Pos =3D Map->find(ND->getDeclName());
     assert(Pos !=3D Map->end() && "no lookup entry for decl");
-    Pos->second.remove(ND);
+    if (Pos->second.getAsVector() || Pos->second.getAsDecl() =3D=3D ND)
+      Pos->second.remove(ND);
   }
 }
=20
@@ -994,7 +1049,7 @@
          "Decl already inserted into a DeclContext");
=20
   if (FirstDecl) {
-    LastDecl->NextDeclInContext =3D D;
+    LastDecl->NextInContextAndBits.setPointer(D);
     LastDecl =3D D;
   } else {
     FirstDecl =3D LastDecl =3D D;
@@ -1004,55 +1059,118 @@
   // update it's class-specific state.
   if (CXXRecordDecl *Record =3D dyn_cast<CXXRecordDecl>(this))
     Record->addedMember(D);
+
+  // If this is a newly-created (not de-serialized) import declaration, wi=
re
+  // it in to the list of local import declarations.
+  if (!D->isFromASTFile()) {
+    if (ImportDecl *Import =3D dyn_cast<ImportDecl>(D))
+      D->getASTContext().addedLocalImportDecl(Import);
+  }
 }
=20
 void DeclContext::addDecl(Decl *D) {
   addHiddenDecl(D);
=20
   if (NamedDecl *ND =3D dyn_cast<NamedDecl>(D))
-    ND->getDeclContext()->makeDeclVisibleInContext(ND);
+    ND->getDeclContext()->getPrimaryContext()->
+        makeDeclVisibleInContextWithFlags(ND, false, true);
+}
+
+void DeclContext::addDeclInternal(Decl *D) {
+  addHiddenDecl(D);
+
+  if (NamedDecl *ND =3D dyn_cast<NamedDecl>(D))
+    ND->getDeclContext()->getPrimaryContext()->
+        makeDeclVisibleInContextWithFlags(ND, true, true);
+}
+
+/// shouldBeHidden - Determine whether a declaration which was declared
+/// within its semantic context should be invisible to qualified name look=
up.
+static bool shouldBeHidden(NamedDecl *D) {
+  // Skip unnamed declarations.
+  if (!D->getDeclName())
+    return true;
+
+  // Skip entities that can't be found by name lookup into a particular
+  // context.
+  if ((D->getIdentifierNamespace() =3D=3D 0 && !isa<UsingDirectiveDecl>(D)=
) ||
+      D->isTemplateParameter())
+    return true;
+
+  // Skip template specializations.
+  // FIXME: This feels like a hack. Should DeclarationName support
+  // template-ids, or is there a better way to keep specializations
+  // from being visible?
+  if (isa<ClassTemplateSpecializationDecl>(D))
+    return true;
+  if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D))
+    if (FD->isFunctionTemplateSpecialization())
+      return true;
+
+  return false;
 }
=20
 /// buildLookup - Build the lookup data structure with all of the
-/// declarations in DCtx (and any other contexts linked to it or
-/// transparent contexts nested within it).
-void DeclContext::buildLookup(DeclContext *DCtx) {
-  for (; DCtx; DCtx =3D DCtx->getNextContext()) {
-    for (decl_iterator D =3D DCtx->decls_begin(),
-                    DEnd =3D DCtx->decls_end();
-         D !=3D DEnd; ++D) {
-      // Insert this declaration into the lookup structure, but only
-      // if it's semantically in its decl context.  During non-lazy
-      // lookup building, this is implicitly enforced by addDecl.
-      if (NamedDecl *ND =3D dyn_cast<NamedDecl>(*D))
-        if (D->getDeclContext() =3D=3D DCtx)
-          makeDeclVisibleInContextImpl(ND);
+/// declarations in this DeclContext (and any other contexts linked
+/// to it or transparent contexts nested within it) and return it.
+StoredDeclsMap *DeclContext::buildLookup() {
+  assert(this =3D=3D getPrimaryContext() && "buildLookup called on non-pri=
mary DC");
=20
-      // Insert any forward-declared Objective-C interface into the lookup
-      // data structure.
-      if (ObjCClassDecl *Class =3D dyn_cast<ObjCClassDecl>(*D))
-        makeDeclVisibleInContextImpl(Class->getForwardInterfaceDecl());
-     =20
-      // If this declaration is itself a transparent declaration context or
-      // inline namespace, add its members (recursively).
-      if (DeclContext *InnerCtx =3D dyn_cast<DeclContext>(*D))
-        if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespac=
e())
-          buildLookup(InnerCtx->getPrimaryContext());
-    }
+  if (!LookupPtr.getInt())
+    return LookupPtr.getPointer();
+
+  llvm::SmallVector<DeclContext *, 2> Contexts;
+  collectAllContexts(Contexts);
+  for (unsigned I =3D 0, N =3D Contexts.size(); I !=3D N; ++I)
+    buildLookupImpl(Contexts[I]);
+
+  // We no longer have any lazy decls.
+  LookupPtr.setInt(false);
+  return LookupPtr.getPointer();
+}
+
+/// buildLookupImpl - Build part of the lookup data structure for the
+/// declarations contained within DCtx, which will either be this
+/// DeclContext, a DeclContext linked to it, or a transparent context
+/// nested within it.
+void DeclContext::buildLookupImpl(DeclContext *DCtx) {
+  for (decl_iterator I =3D DCtx->decls_begin(), E =3D DCtx->decls_end();
+       I !=3D E; ++I) {
+    Decl *D =3D *I;
+
+    // Insert this declaration into the lookup structure, but only if
+    // it's semantically within its decl context. Any other decls which
+    // should be found in this context are added eagerly.
+    if (NamedDecl *ND =3D dyn_cast<NamedDecl>(D))
+      if (ND->getDeclContext() =3D=3D DCtx && !shouldBeHidden(ND))
+        makeDeclVisibleInContextImpl(ND, false);
+
+    // If this declaration is itself a transparent declaration context
+    // or inline namespace, add the members of this declaration of that
+    // context (recursively).
+    if (DeclContext *InnerCtx =3D dyn_cast<DeclContext>(D))
+      if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace(=
))
+        buildLookupImpl(InnerCtx);
   }
 }
=20
 DeclContext::lookup_result
 DeclContext::lookup(DeclarationName Name) {
+  assert(DeclKind !=3D Decl::LinkageSpec &&
+         "Should not perform lookups into linkage specs!");
+
   DeclContext *PrimaryContext =3D getPrimaryContext();
   if (PrimaryContext !=3D this)
     return PrimaryContext->lookup(Name);
=20
   if (hasExternalVisibleStorage()) {
-    // Check to see if we've already cached the lookup results.
-    if (LookupPtr) {
-      StoredDeclsMap::iterator I =3D LookupPtr->find(Name);
-      if (I !=3D LookupPtr->end())
+    // If a PCH has a result for this name, and we have a local declaratio=
n, we
+    // will have imported the PCH result when adding the local declaration.
+    // FIXME: For modules, we could have had more declarations added by mo=
dule
+    // imoprts since we saw the declaration of the local name.
+    if (StoredDeclsMap *Map =3D LookupPtr.getPointer()) {
+      StoredDeclsMap::iterator I =3D Map->find(Name);
+      if (I !=3D Map->end())
         return I->second.getLookupResult();
     }
=20
@@ -1060,20 +1178,18 @@
     return Source->FindExternalVisibleDeclsByName(this, Name);
   }
=20
-  /// If there is no lookup data structure, build one now by walking
-  /// all of the linked DeclContexts (in declaration order!) and
-  /// inserting their values.
-  if (!LookupPtr) {
-    buildLookup(this);
+  StoredDeclsMap *Map =3D LookupPtr.getPointer();
+  if (LookupPtr.getInt())
+    Map =3D buildLookup();
=20
-    if (!LookupPtr)
-      return lookup_result(lookup_iterator(0), lookup_iterator(0));
-  }
+  if (!Map)
+    return lookup_result(lookup_iterator(0), lookup_iterator(0));
=20
-  StoredDeclsMap::iterator Pos =3D LookupPtr->find(Name);
-  if (Pos =3D=3D LookupPtr->end())
+  StoredDeclsMap::iterator I =3D Map->find(Name);
+  if (I =3D=3D Map->end())
     return lookup_result(lookup_iterator(0), lookup_iterator(0));
-  return Pos->second.getLookupResult();
+
+  return I->second.getLookupResult();
 }
=20
 DeclContext::lookup_const_result
@@ -1094,10 +1210,10 @@
   }
=20
   // If we have a lookup table, check there first. Maybe we'll get lucky.
-  if (LookupPtr) {
-    StoredDeclsMap::iterator Pos =3D LookupPtr->find(Name);
-    if (Pos !=3D LookupPtr->end()) {
-      Results.insert(Results.end(),=20
+  if (StoredDeclsMap *Map =3D LookupPtr.getPointer()) {
+    StoredDeclsMap::iterator Pos =3D Map->find(Name);
+    if (Pos !=3D Map->end()) {
+      Results.insert(Results.end(),
                      Pos->second.getLookupResult().first,
                      Pos->second.getLookupResult().second);
       return;
@@ -1147,79 +1263,97 @@
   return false;
 }
=20
-void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable)=
 {
-  // FIXME: This feels like a hack. Should DeclarationName support
-  // template-ids, or is there a better way to keep specializations
-  // from being visible?
-  if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter())
+void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
+  DeclContext *PrimaryDC =3D this->getPrimaryContext();
+  DeclContext *DeclDC =3D D->getDeclContext()->getPrimaryContext();
+  // If the decl is being added outside of its semantic decl context, we
+  // need to ensure that we eagerly build the lookup information for it.
+  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC =3D=3D =
DeclDC);
+}
+
+void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Int=
ernal,
+                                                    bool Recoverable) {
+  assert(this =3D=3D getPrimaryContext() && "expected a primary DC");
+
+  // Skip declarations within functions.
+  // FIXME: We shouldn't need to build lookup tables for function declarat=
ions
+  // ever, and we can't do so correctly because we can't model the nesting=
 of
+  // scopes which occurs within functions. We use "qualified" lookup into
+  // function declarations when handling friend declarations inside nested
+  // classes, and consequently accept the following invalid code:
+  //
+  //   void f() { void g(); { int g; struct S { friend void g(); }; } }
+  if (isFunctionOrMethod() && !isa<FunctionDecl>(D))
     return;
-  if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D))
-    if (FD->isFunctionTemplateSpecialization())
-      return;
=20
-  DeclContext *PrimaryContext =3D getPrimaryContext();
-  if (PrimaryContext !=3D this) {
-    PrimaryContext->makeDeclVisibleInContext(D, Recoverable);
+  // Skip declarations which should be invisible to name lookup.
+  if (shouldBeHidden(D))
     return;
+
+  // If we already have a lookup data structure, perform the insertion into
+  // it. If we might have externally-stored decls with this name, look them
+  // up and perform the insertion. If this decl was declared outside its
+  // semantic context, buildLookup won't add it, so add it now.
+  //
+  // FIXME: As a performance hack, don't add such decls into the translati=
on
+  // unit unless we're in C++, since qualified lookup into the TU is never
+  // performed.
+  if (LookupPtr.getPointer() || hasExternalVisibleStorage() ||
+      ((!Recoverable || D->getDeclContext() !=3D D->getLexicalDeclContext(=
)) &&
+       (getParentASTContext().getLangOpts().CPlusPlus ||
+        !isTranslationUnit()))) {
+    // If we have lazily omitted any decls, they might have the same name =
as
+    // the decl which we are adding, so build a full lookup table before a=
dding
+    // this decl.
+    buildLookup();
+    makeDeclVisibleInContextImpl(D, Internal);
+  } else {
+    LookupPtr.setInt(true);
   }
=20
-  // If we already have a lookup data structure, perform the insertion
-  // into it. If we haven't deserialized externally stored decls, deserial=
ize
-  // them so we can add the decl. Otherwise, be lazy and don't build that
-  // structure until someone asks for it.
-  if (LookupPtr || !Recoverable || hasExternalVisibleStorage())
-    makeDeclVisibleInContextImpl(D);
-
   // If we are a transparent context or inline namespace, insert into our
   // parent context, too. This operation is recursive.
   if (isTransparentContext() || isInlineNamespace())
-    getParent()->makeDeclVisibleInContext(D, Recoverable);
+    getParent()->getPrimaryContext()->
+        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
=20
   Decl *DCAsDecl =3D cast<Decl>(this);
-  // Notify that a decl was made visible unless it's a Tag being defined.=20
+  // Notify that a decl was made visible unless we are a Tag being defined.
   if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined(=
)))
     if (ASTMutationListener *L =3D DCAsDecl->getASTMutationListener())
       L->AddedVisibleDecl(this, D);
 }
=20
-void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
-  // Skip unnamed declarations.
-  if (!D->getDeclName())
-    return;
-
-  // Skip entities that can't be found by name lookup into a particular
-  // context.
-  if ((D->getIdentifierNamespace() =3D=3D 0 && !isa<UsingDirectiveDecl>(D)=
) ||
-      D->isTemplateParameter())
-    return;
-
-  ASTContext *C =3D 0;
-  if (!LookupPtr) {
-    C =3D &getParentASTContext();
-    CreateStoredDeclsMap(*C);
+void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal=
) {
+  // Find or create the stored declaration map.
+  StoredDeclsMap *Map =3D LookupPtr.getPointer();
+  if (!Map) {
+    ASTContext *C =3D &getParentASTContext();
+    Map =3D CreateStoredDeclsMap(*C);
   }
=20
   // If there is an external AST source, load any declarations it knows ab=
out
   // with this declaration's name.
   // If the lookup table contains an entry about this name it means that we
   // have already checked the external source.
-  if (ExternalASTSource *Source =3D getParentASTContext().getExternalSourc=
e())
-    if (hasExternalVisibleStorage() &&
-        LookupPtr->find(D->getDeclName()) =3D=3D LookupPtr->end())
-      Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
+  if (!Internal)
+    if (ExternalASTSource *Source =3D getParentASTContext().getExternalSou=
rce())
+      if (hasExternalVisibleStorage() &&
+          Map->find(D->getDeclName()) =3D=3D Map->end())
+        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
=20
   // Insert this declaration into the map.
-  StoredDeclsList &DeclNameEntries =3D (*LookupPtr)[D->getDeclName()];
+  StoredDeclsList &DeclNameEntries =3D (*Map)[D->getDeclName()];
   if (DeclNameEntries.isNull()) {
     DeclNameEntries.setOnlyValue(D);
     return;
   }
=20
-  // If it is possible that this is a redeclaration, check to see if there=
 is
-  // already a decl for which declarationReplaces returns true.  If there =
is
-  // one, just replace it and return.
-  if (DeclNameEntries.HandleRedeclaration(D))
+  if (DeclNameEntries.HandleRedeclaration(D)) {
+    // This declaration has replaced an existing one for which
+    // declarationReplaces returns true.
     return;
+  }
=20
   // Put this declaration into the appropriate slot.
   DeclNameEntries.AddSubsequentDecl(D);
@@ -1229,6 +1363,8 @@
 /// this context.
 DeclContext::udir_iterator_range
 DeclContext::getUsingDirectives() const {
+  // FIXME: Use something more efficient than normal lookup for using
+  // directives. In C++, using directives are looked up more than anything=
 else.
   lookup_const_result Result =3D lookup(UsingDirectiveDecl::getName());
   return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
                              reinterpret_cast<udir_iterator>(Result.second=
));
@@ -1239,7 +1375,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
-  assert(!LookupPtr && "context already has a decls map");
+  assert(!LookupPtr.getPointer() && "context already has a decls map");
   assert(getPrimaryContext() =3D=3D this &&
          "creating decls map on non-primary context");
=20
@@ -1251,7 +1387,7 @@
     M =3D new StoredDeclsMap();
   M->Previous =3D C.LastSDM;
   C.LastSDM =3D llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
-  LookupPtr =3D M;
+  LookupPtr.setPointer(M);
   return M;
 }
=20
@@ -1283,11 +1419,11 @@
   assert(Parent->isDependentContext()
          && "cannot iterate dependent diagnostics of non-dependent context=
");
   Parent =3D Parent->getPrimaryContext();
-  if (!Parent->LookupPtr)
+  if (!Parent->LookupPtr.getPointer())
     Parent->CreateStoredDeclsMap(C);
=20
   DependentStoredDeclsMap *Map
-    =3D static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr);
+    =3D static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr.getPointer=
());
=20
   // Allocate the copy of the PartialDiagnostic via the ASTContext's
   // BumpPtrAllocator, rather than the ASTContext itself.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DeclCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -17,6 +17,7 @@
 #include "clang/AST/ASTMutationListener.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "llvm/ADT/STLExtras.h"
@@ -27,6 +28,13 @@
 // Decl Allocation/Deallocation Method Implementations
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void AccessSpecDecl::anchor() { }
+
+AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned=
 ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(AccessSpecDecl));
+  return new (Mem) AccessSpecDecl(EmptyShell());
+}
+
 CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
   : UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false),
     UserDeclaredMoveConstructor(false), UserDeclaredCopyAssignment(false),
@@ -34,17 +42,24 @@
     Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
     Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true),
     HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(fa=
lse),
-    HasMutableFields(false), HasTrivialDefaultConstructor(true),
-    HasConstexprNonCopyMoveConstructor(false), HasTrivialCopyConstructor(t=
rue),
+    HasMutableFields(false), HasOnlyCMembers(true),
+    HasTrivialDefaultConstructor(true),
+    HasConstexprNonCopyMoveConstructor(false),
+    DefaultedDefaultConstructorIsConstexpr(true),
+    DefaultedCopyConstructorIsConstexpr(true),
+    DefaultedMoveConstructorIsConstexpr(true),
+    HasConstexprDefaultConstructor(false), HasConstexprCopyConstructor(fal=
se),
+    HasConstexprMoveConstructor(false), HasTrivialCopyConstructor(true),
     HasTrivialMoveConstructor(true), HasTrivialCopyAssignment(true),
     HasTrivialMoveAssignment(true), HasTrivialDestructor(true),
+    HasIrrelevantDestructor(true),
     HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(fals=
e),
     UserProvidedDefaultConstructor(false), DeclaredDefaultConstructor(fals=
e),
     DeclaredCopyConstructor(false), DeclaredMoveConstructor(false),
     DeclaredCopyAssignment(false), DeclaredMoveAssignment(false),
     DeclaredDestructor(false), FailedImplicitMoveConstructor(false),
-    FailedImplicitMoveAssignment(false), NumBases(0), NumVBases(0), Bases(=
),
-    VBases(), Definition(D), FirstFriend(0) {
+    FailedImplicitMoveAssignment(false), IsLambda(false), NumBases(0),
+    NumVBases(0), Bases(), VBases(), Definition(D), FirstFriend(0) {
 }
=20
 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
@@ -68,24 +83,41 @@
   return R;
 }
=20
-CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, EmptyShell Empty=
) {
-  return new (C) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(),
-                               SourceLocation(), 0, 0);
+CXXRecordDecl *CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContex=
t *DC,
+                                           SourceLocation Loc, bool Depend=
ent) {
+  CXXRecordDecl* R =3D new (C) CXXRecordDecl(CXXRecord, TTK_Class, DC, Loc=
, Loc,
+                                           0, 0);
+  R->IsBeingDefined =3D true;
+  R->DefinitionData =3D new (C) struct LambdaDefinitionData(R, Dependent);
+  C.getTypeDeclType(R, /*PrevDecl=3D*/0);
+  return R;
+}
+
+CXXRecordDecl *
+CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(CXXRecordDecl));
+  return new (Mem) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(=
),
+                                 SourceLocation(), 0, 0);
 }
=20
 void
 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
                         unsigned NumBases) {
   ASTContext &C =3D getASTContext();
- =20
-  // C++ [dcl.init.aggr]p1:
-  //   An aggregate is an array or a class (clause 9) with [...]
-  //   no base classes [...].
-  data().Aggregate =3D false;
=20
   if (!data().Bases.isOffset() && data().NumBases > 0)
     C.Deallocate(data().getBases());
=20
+  if (NumBases) {
+    // C++ [dcl.init.aggr]p1:
+    //   An aggregate is [...] a class with [...] no base classes [...].
+    data().Aggregate =3D false;
+
+    // C++ [class]p4:
+    //   A POD-struct is an aggregate class...
+    data().PlainOldData =3D false;
+  }
+
   // The set of seen virtual base types.
   llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
  =20
@@ -105,14 +137,6 @@
     CXXRecordDecl *BaseClassDecl
       =3D cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
=20
-    // C++ [dcl.init.aggr]p1:
-    //   An aggregate is [...] a class with [...] no base classes [...].
-    data().Aggregate =3D false;   =20
-   =20
-    // C++ [class]p4:
-    //   A POD-struct is an aggregate class...
-    data().PlainOldData =3D false;
-   =20
     // A class with a non-empty base class is not empty.
     // FIXME: Standard ref?
     if (!BaseClassDecl->isEmpty()) {
@@ -190,6 +214,13 @@
       //   A standard-layout class is a class that: [...]
       //    -- has [...] no virtual base classes
       data().IsStandardLayout =3D false;
+
+      // C++11 [dcl.constexpr]p4:
+      //   In the definition of a constexpr constructor [...]
+      //    -- the class shall not have any virtual base classes
+      data().DefaultedDefaultConstructorIsConstexpr =3D false;
+      data().DefaultedCopyConstructorIsConstexpr =3D false;
+      data().DefaultedMoveConstructorIsConstexpr =3D false;
     } else {
       // C++ [class.ctor]p5:
       //   A default constructor is trivial [...] if:
@@ -221,6 +252,32 @@
         data().HasTrivialCopyAssignment =3D false;
       if (!BaseClassDecl->hasTrivialMoveAssignment())
         data().HasTrivialMoveAssignment =3D false;
+
+      // C++11 [class.ctor]p6:
+      //   If that user-written default constructor would satisfy the
+      //   requirements of a constexpr constructor, the implicitly-defined
+      //   default constructor is constexpr.
+      if (!BaseClassDecl->hasConstexprDefaultConstructor())
+        data().DefaultedDefaultConstructorIsConstexpr =3D false;
+
+      // C++11 [class.copy]p13:
+      //   If the implicitly-defined constructor would satisfy the require=
ments
+      //   of a constexpr constructor, the implicitly-defined constructor =
is
+      //   constexpr.
+      // C++11 [dcl.constexpr]p4:
+      //    -- every constructor involved in initializing [...] base class
+      //       sub-objects shall be a constexpr constructor
+      if (!BaseClassDecl->hasConstexprCopyConstructor())
+        data().DefaultedCopyConstructorIsConstexpr =3D false;
+      if (BaseClassDecl->hasDeclaredMoveConstructor() ||
+          BaseClassDecl->needsImplicitMoveConstructor())
+        // FIXME: If the implicit move constructor generated for the base =
class
+        // would be ill-formed, the implicit move constructor generated fo=
r the
+        // derived class calls the base class' copy constructor.
+        data().DefaultedMoveConstructorIsConstexpr &=3D
+          BaseClassDecl->hasConstexprMoveConstructor();
+      else if (!BaseClassDecl->hasConstexprCopyConstructor())
+        data().DefaultedMoveConstructorIsConstexpr =3D false;
     }
    =20
     // C++ [class.ctor]p3:
@@ -228,7 +285,10 @@
     //   have trivial destructors.
     if (!BaseClassDecl->hasTrivialDestructor())
       data().HasTrivialDestructor =3D false;
-   =20
+
+    if (!BaseClassDecl->hasIrrelevantDestructor())
+      data().HasIrrelevantDestructor =3D false;
+
     // A class has an Objective-C object member if... or any of its bases
     // has an Objective-C object member.
     if (BaseClassDecl->hasObjectMember())
@@ -410,6 +470,12 @@
 }
=20
 void CXXRecordDecl::addedMember(Decl *D) {
+  if (!D->isImplicit() &&
+      !isa<FieldDecl>(D) &&
+      !isa<IndirectFieldDecl>(D) &&
+      (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() =3D=3D TTK_Class=
))
+    data().HasOnlyCMembers =3D false;
+
   // Ignore friends and invalid declarations.
   if (D->getFriendObjectKind() || D->isInvalidDecl())
     return;
@@ -453,8 +519,7 @@
       //    -- class X has no virtual functions [...]
       data().HasTrivialCopyAssignment =3D false;
       data().HasTrivialMoveAssignment =3D false;
-      // FIXME: Destructor?
-
+           =20
       // C++0x [class]p7:
       //   A standard-layout class is a class that: [...]
       //    -- has no virtual functions
@@ -472,13 +537,21 @@
     // If this is a special member function, note that it was added and th=
en
     // return early.
     if (CXXConstructorDecl *Constructor =3D dyn_cast<CXXConstructorDecl>(D=
)) {
-      if (Constructor->isDefaultConstructor())
+      if (Constructor->isDefaultConstructor()) {
         data().DeclaredDefaultConstructor =3D true;
-      else if (Constructor->isCopyConstructor())
+        if (Constructor->isConstexpr()) {
+          data().HasConstexprDefaultConstructor =3D true;
+          data().HasConstexprNonCopyMoveConstructor =3D true;
+        }
+      } else if (Constructor->isCopyConstructor()) {
         data().DeclaredCopyConstructor =3D true;
-      else if (Constructor->isMoveConstructor())
+        if (Constructor->isConstexpr())
+          data().HasConstexprCopyConstructor =3D true;
+      } else if (Constructor->isMoveConstructor()) {
         data().DeclaredMoveConstructor =3D true;
-      else
+        if (Constructor->isConstexpr())
+          data().HasConstexprMoveConstructor =3D true;
+      } else
         goto NotASpecialMember;
       return;
     } else if (isa<CXXDestructorDecl>(D)) {
@@ -508,14 +581,18 @@
     // to all functions.
     bool UserProvided =3D Constructor->isUserProvided();
=20
-    // C++0x [class.ctor]p5:
-    //   A default constructor is trivial if it is not user-provided [...]
     if (Constructor->isDefaultConstructor()) {
       data().DeclaredDefaultConstructor =3D true;
       if (UserProvided) {
+        // C++0x [class.ctor]p5:
+        //   A default constructor is trivial if it is not user-provided [=
...]
         data().HasTrivialDefaultConstructor =3D false;
         data().UserProvidedDefaultConstructor =3D true;
       }
+      if (Constructor->isConstexpr()) {
+        data().HasConstexprDefaultConstructor =3D true;
+        data().HasConstexprNonCopyMoveConstructor =3D true;
+      }
     }
=20
     // Note when we have a user-declared copy or move constructor, which w=
ill
@@ -530,6 +607,9 @@
         //   user-provided [...]
         if (UserProvided)
           data().HasTrivialCopyConstructor =3D false;
+
+        if (Constructor->isConstexpr())
+          data().HasConstexprCopyConstructor =3D true;
       } else if (Constructor->isMoveConstructor()) {
         data().UserDeclaredMoveConstructor =3D true;
         data().DeclaredMoveConstructor =3D true;
@@ -539,6 +619,9 @@
         //   user-provided [...]
         if (UserProvided)
           data().HasTrivialMoveConstructor =3D false;
+
+        if (Constructor->isConstexpr())
+          data().HasConstexprMoveConstructor =3D true;
       }
     }
     if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructo=
r()) {
@@ -553,7 +636,7 @@
     // C++0x [dcl.init.aggr]p1:
     //   An aggregate is an array or a class with no user-provided
     //   constructors [...].
-    if (!getASTContext().getLangOptions().CPlusPlus0x || UserProvided)
+    if (!getASTContext().getLangOpts().CPlusPlus0x || UserProvided)
       data().Aggregate =3D false;
=20
     // C++ [class]p4:
@@ -569,17 +652,29 @@
   if (CXXDestructorDecl *DD =3D dyn_cast<CXXDestructorDecl>(D)) {
     data().DeclaredDestructor =3D true;
     data().UserDeclaredDestructor =3D true;
-   =20
+    data().HasIrrelevantDestructor =3D false;
+
     // C++ [class]p4:=20
     //   A POD-struct is an aggregate class that has [...] no user-defined=20
     //   destructor.
     // This bit is the C++03 POD bit, not the 0x one.
     data().PlainOldData =3D false;
    =20
-    // C++0x [class.dtor]p5:=20
-    //   A destructor is trivial if it is not user-provided and [...]
-    if (DD->isUserProvided())
+    // C++11 [class.dtor]p5:=20
+    //   A destructor is trivial if it is not user-provided and if
+    //    -- the destructor is not virtual.
+    if (DD->isUserProvided() || DD->isVirtual()) {
       data().HasTrivialDestructor =3D false;
+      // C++11 [dcl.constexpr]p1:
+      //   The constexpr specifier shall be applied only to [...] the
+      //   declaration of a static data member of a literal type.
+      // C++11 [basic.types]p10:
+      //   A type is a literal type if it is [...] a class type that [...]=
 has
+      //   a trivial destructor.
+      data().DefaultedDefaultConstructorIsConstexpr =3D false;
+      data().DefaultedCopyConstructorIsConstexpr =3D false;
+      data().DefaultedMoveConstructorIsConstexpr =3D false;
+    }
    =20
     return;
   }
@@ -634,14 +729,14 @@
       // hasn't been set yet.  That's really just a misdesign in Sema.
=20
       if (FunTmpl) {
-        if (FunTmpl->getPreviousDeclaration())
-          data().Conversions.replace(FunTmpl->getPreviousDeclaration(),
+        if (FunTmpl->getPreviousDecl())
+          data().Conversions.replace(FunTmpl->getPreviousDecl(),
                                      FunTmpl);
         else
           data().Conversions.addDecl(FunTmpl);
       } else {
-        if (Conversion->getPreviousDeclaration())
-          data().Conversions.replace(Conversion->getPreviousDeclaration(),
+        if (Conversion->getPreviousDecl())
+          data().Conversions.replace(Conversion->getPreviousDecl(),
                                      Conversion);
         else
           data().Conversions.addDecl(Conversion);       =20
@@ -703,7 +798,7 @@
     ASTContext &Context =3D getASTContext();
     QualType T =3D Context.getBaseElementType(Field->getType());
     if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
-      if (!Context.getLangOptions().ObjCAutoRefCount ||
+      if (!Context.getLangOpts().ObjCAutoRefCount ||
           T.getObjCLifetime() !=3D Qualifiers::OCL_ExplicitNone)
         setHasObjectMember(true);
     } else if (!T.isPODType(Context))
@@ -718,12 +813,8 @@
       data().IsStandardLayout =3D false;
     }
=20
-    // Record if this field is the first non-literal field or base.
-    // As a slight variation on the standard, we regard mutable members as=
 being
-    // non-literal, since mutating a constexpr variable would break C++11
-    // constant expression semantics.
-    if ((!hasNonLiteralTypeFieldsOrBases() && !T->isLiteralType()) ||
-        Field->isMutable())
+    // Record if this field is the first non-literal or volatile field or =
base.
+    if (!T->isLiteralType() || T.isVolatileQualified())
       data().HasNonLiteralTypeFieldsOrBases =3D true;
=20
     if (Field->hasInClassInitializer()) {
@@ -746,7 +837,7 @@
       CXXRecordDecl* FieldRec =3D cast<CXXRecordDecl>(RecordTy->getDecl());
       if (FieldRec->getDefinition()) {
         // C++0x [class.ctor]p5:
-        //   A defulat constructor is trivial [...] if:
+        //   A default constructor is trivial [...] if:
         //    -- for all the non-static data members of its class that are=
 of
         //       class type (or array thereof), each such class has a triv=
ial
         //       default constructor.
@@ -779,6 +870,8 @@
=20
         if (!FieldRec->hasTrivialDestructor())
           data().HasTrivialDestructor =3D false;
+        if (!FieldRec->hasIrrelevantDestructor())
+          data().HasIrrelevantDestructor =3D false;
         if (FieldRec->hasObjectMember())
           setHasObjectMember(true);
=20
@@ -818,7 +911,41 @@
         // Keep track of the presence of mutable fields.
         if (FieldRec->hasMutableFields())
           data().HasMutableFields =3D true;
+
+        // C++11 [class.copy]p13:
+        //   If the implicitly-defined constructor would satisfy the
+        //   requirements of a constexpr constructor, the implicitly-defin=
ed
+        //   constructor is constexpr.
+        // C++11 [dcl.constexpr]p4:
+        //    -- every constructor involved in initializing non-static data
+        //       members [...] shall be a constexpr constructor
+        if (!Field->hasInClassInitializer() &&
+            !FieldRec->hasConstexprDefaultConstructor())
+          // The standard requires any in-class initializer to be a consta=
nt
+          // expression. We consider this to be a defect.
+          data().DefaultedDefaultConstructorIsConstexpr =3D false;
+
+        if (!FieldRec->hasConstexprCopyConstructor())
+          data().DefaultedCopyConstructorIsConstexpr =3D false;
+
+        if (FieldRec->hasDeclaredMoveConstructor() ||
+            FieldRec->needsImplicitMoveConstructor())
+          // FIXME: If the implicit move constructor generated for the mem=
ber's
+          // class would be ill-formed, the implicit move constructor gene=
rated
+          // for this class calls the member's copy constructor.
+          data().DefaultedMoveConstructorIsConstexpr &=3D
+            FieldRec->hasConstexprMoveConstructor();
+        else if (!FieldRec->hasConstexprCopyConstructor())
+          data().DefaultedMoveConstructorIsConstexpr =3D false;
       }
+    } else {
+      // Base element type of field is a non-class type.
+      if (!T->isLiteralType()) {
+        data().DefaultedDefaultConstructorIsConstexpr =3D false;
+        data().DefaultedCopyConstructorIsConstexpr =3D false;
+        data().DefaultedMoveConstructorIsConstexpr =3D false;
+      } else if (!Field->hasInClassInitializer())
+        data().DefaultedDefaultConstructorIsConstexpr =3D false;
     }
=20
     // C++0x [class]p7:
@@ -849,6 +976,35 @@
       data().Conversions.addDecl(Shadow, Shadow->getAccess());
 }
=20
+bool CXXRecordDecl::isCLike() const {
+  if (getTagKind() =3D=3D TTK_Class || !TemplateOrInstantiation.isNull())
+    return false;
+  if (!hasDefinition())
+    return true;
+
+  return isPOD() && data().HasOnlyCMembers;
+}
+
+void CXXRecordDecl::getCaptureFields(
+       llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
+       FieldDecl *&ThisCapture) const {
+  Captures.clear();
+  ThisCapture =3D 0;
+
+  LambdaDefinitionData &Lambda =3D getLambdaData();
+  RecordDecl::field_iterator Field =3D field_begin();
+  for (LambdaExpr::Capture *C =3D Lambda.Captures, *CEnd =3D C + Lambda.Nu=
mCaptures;
+       C !=3D CEnd; ++C, ++Field) {
+    if (C->capturesThis()) {
+      ThisCapture =3D *Field;
+      continue;
+    }
+
+    Captures[C->getCapturedVar()] =3D *Field;
+  }
+}
+
+
 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv)=
 {
   QualType T;
   if (isa<UsingShadowDecl>(Conv))
@@ -1087,7 +1243,7 @@
 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverride=
rs) {
   RecordDecl::completeDefinition();
  =20
-  if (hasObjectMember() && getASTContext().getLangOptions().ObjCAutoRefCou=
nt) {
+  if (hasObjectMember() && getASTContext().getLangOpts().ObjCAutoRefCount)=
 {
     // Objective-C Automatic Reference Counting:
     //   If a class has a non-static data member of Objective-C pointer
     //   type (or array thereof), it is a non-POD type and its
@@ -1099,6 +1255,7 @@
     Data.HasTrivialCopyConstructor =3D false;
     Data.HasTrivialCopyAssignment =3D false;
     Data.HasTrivialDestructor =3D false;
+    Data.HasIrrelevantDestructor =3D false;
   }
  =20
   // If the class may be abstract (but hasn't been marked as such), check =
for
@@ -1157,6 +1314,8 @@
   return false;
 }
=20
+void CXXMethodDecl::anchor() { }
+
 CXXMethodDecl *
 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
                       SourceLocation StartLoc,
@@ -1169,6 +1328,14 @@
                                EndLocation);
 }
=20
+CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned I=
D) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(CXXMethodDecl));
+  return new (Mem) CXXMethodDecl(CXXMethod, 0, SourceLocation(),=20
+                                 DeclarationNameInfo(), QualType(),
+                                 0, false, SC_None, false, false,
+                                 SourceLocation());
+}
+
 bool CXXMethodDecl::isUsualDeallocationFunction() const {
   if (getOverloadedOperator() !=3D OO_Delete &&
       getOverloadedOperator() !=3D OO_Array_Delete)
@@ -1254,19 +1421,23 @@
   assert(MD->isCanonicalDecl() && "Method is not canonical!");
   assert(!MD->getParent()->isDependentContext() &&
          "Can't add an overridden method to a class template!");
+  assert(MD->isVirtual() && "Method is not virtual!");
=20
   getASTContext().addOverriddenMethod(this, MD);
 }
=20
 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() c=
onst {
+  if (isa<CXXConstructorDecl>(this)) return 0;
   return getASTContext().overridden_methods_begin(this);
 }
=20
 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() con=
st {
+  if (isa<CXXConstructorDecl>(this)) return 0;
   return getASTContext().overridden_methods_end(this);
 }
=20
 unsigned CXXMethodDecl::size_overridden_methods() const {
+  if (isa<CXXConstructorDecl>(this)) return 0;
   return getASTContext().overridden_methods_size(this);
 }
=20
@@ -1296,14 +1467,20 @@
   return CheckFn->hasBody(fn) && !fn->isOutOfLine();
 }
=20
+bool CXXMethodDecl::isLambdaStaticInvoker() const {
+  return getParent()->isLambda() &&=20
+         getIdentifier() && getIdentifier()->getName() =3D=3D "__invoke";
+}
+
+
 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
                                        TypeSourceInfo *TInfo, bool IsVirtu=
al,
                                        SourceLocation L, Expr *Init,
                                        SourceLocation R,
                                        SourceLocation EllipsisLoc)
   : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),=20
-    LParenLoc(L), RParenLoc(R), IsVirtual(IsVirtual), IsWritten(false),
-    SourceOrderOrNumArrayIndices(0)
+    LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),=20
+    IsWritten(false), SourceOrderOrNumArrayIndices(0)
 {
 }
=20
@@ -1313,7 +1490,7 @@
                                        SourceLocation L, Expr *Init,
                                        SourceLocation R)
   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
-    LParenLoc(L), RParenLoc(R), IsVirtual(false),
+    LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
     IsWritten(false), SourceOrderOrNumArrayIndices(0)
 {
 }
@@ -1324,17 +1501,17 @@
                                        SourceLocation L, Expr *Init,
                                        SourceLocation R)
   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
-    LParenLoc(L), RParenLoc(R), IsVirtual(false),
+    LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
     IsWritten(false), SourceOrderOrNumArrayIndices(0)
 {
 }
=20
 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
-                                       SourceLocation D, SourceLocation L,
-                                       CXXConstructorDecl *Target, Expr *I=
nit,
+                                       TypeSourceInfo *TInfo,
+                                       SourceLocation L, Expr *Init,=20
                                        SourceLocation R)
-  : Initializee(Target), MemberOrEllipsisLocation(D), Init(Init),
-    LParenLoc(L), RParenLoc(R), IsVirtual(false),
+  : Initializee(TInfo), MemberOrEllipsisLocation(), Init(Init),
+    LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false),
     IsWritten(false), SourceOrderOrNumArrayIndices(0)
 {
 }
@@ -1383,13 +1560,16 @@
 }
=20
 SourceLocation CXXCtorInitializer::getSourceLocation() const {
-  if (isAnyMemberInitializer() || isDelegatingInitializer())
+  if (isAnyMemberInitializer())
     return getMemberLocation();
=20
   if (isInClassMemberInitializer())
     return getAnyMember()->getLocation();
  =20
-  return getBaseClassLoc().getLocalSourceRange().getBegin();
+  if (TypeSourceInfo *TSInfo =3D Initializee.get<TypeSourceInfo*>())
+    return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
+ =20
+  return SourceLocation();
 }
=20
 SourceRange CXXCtorInitializer::getSourceRange() const {
@@ -1403,10 +1583,13 @@
   return SourceRange(getSourceLocation(), getRParenLoc());
 }
=20
+void CXXConstructorDecl::anchor() { }
+
 CXXConstructorDecl *
-CXXConstructorDecl::Create(ASTContext &C, EmptyShell Empty) {
-  return new (C) CXXConstructorDecl(0, SourceLocation(), DeclarationNameIn=
fo(),
-                                    QualType(), 0, false, false, false, fa=
lse);
+CXXConstructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(CXXConstructorDecl)=
);
+  return new (Mem) CXXConstructorDecl(0, SourceLocation(),DeclarationNameI=
nfo(),
+                                      QualType(), 0, false, false, false,f=
alse);
 }
=20
 CXXConstructorDecl *
@@ -1424,6 +1607,15 @@
                                     isConstexpr);
 }
=20
+CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
+  assert(isDelegatingConstructor() && "Not a delegating constructor!");
+  Expr *E =3D (*init_begin())->getInit()->IgnoreImplicit();
+  if (CXXConstructExpr *Construct =3D dyn_cast<CXXConstructExpr>(E))
+    return Construct->getConstructor();
+ =20
+  return 0;
+}
+
 bool CXXConstructorDecl::isDefaultConstructor() const {
   // C++ [class.ctor]p5:
   //   A default constructor for a class X is a constructor of class
@@ -1524,8 +1716,8 @@
=20
 const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() co=
nst {
   // Hack: we store the inherited constructor in the overridden method tab=
le
-  method_iterator It =3D begin_overridden_methods();
-  if (It =3D=3D end_overridden_methods())
+  method_iterator It =3D getASTContext().overridden_methods_begin(this);
+  if (It =3D=3D getASTContext().overridden_methods_end(this))
     return 0;
=20
   return cast<CXXConstructorDecl>(*It);
@@ -1534,13 +1726,17 @@
 void
 CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *Base=
Ctor){
   // Hack: we store the inherited constructor in the overridden method tab=
le
-  assert(size_overridden_methods() =3D=3D 0 && "Base ctor already set.");
-  addOverriddenMethod(BaseCtor);
+  assert(getASTContext().overridden_methods_size(this) =3D=3D 0 &&
+         "Base ctor already set.");
+  getASTContext().addOverriddenMethod(this, BaseCtor);
 }
=20
+void CXXDestructorDecl::anchor() { }
+
 CXXDestructorDecl *
-CXXDestructorDecl::Create(ASTContext &C, EmptyShell Empty) {
-  return new (C) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInf=
o(),
+CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(CXXDestructorDecl));
+  return new (Mem) CXXDestructorDecl(0, SourceLocation(), DeclarationNameI=
nfo(),
                                    QualType(), 0, false, false);
 }
=20
@@ -1557,11 +1753,14 @@
                                    isImplicitlyDeclared);
 }
=20
+void CXXConversionDecl::anchor() { }
+
 CXXConversionDecl *
-CXXConversionDecl::Create(ASTContext &C, EmptyShell Empty) {
-  return new (C) CXXConversionDecl(0, SourceLocation(), DeclarationNameInf=
o(),
-                                   QualType(), 0, false, false, false,
-                                   SourceLocation());
+CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(CXXConversionDecl));
+  return new (Mem) CXXConversionDecl(0, SourceLocation(), DeclarationNameI=
nfo(),
+                                     QualType(), 0, false, false, false,
+                                     SourceLocation());
 }
=20
 CXXConversionDecl *
@@ -1579,6 +1778,13 @@
                                    EndLocation);
 }
=20
+bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
+  return isImplicit() && getParent()->isLambda() &&
+         getConversionType()->isBlockPointerType();
+}
+
+void LinkageSpecDecl::anchor() { }
+
 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
                                          DeclContext *DC,
                                          SourceLocation ExternLoc,
@@ -1588,6 +1794,14 @@
   return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, RBraceLoc);
 }
=20
+LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsign=
ed ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(LinkageSpecDecl));
+  return new (Mem) LinkageSpecDecl(0, SourceLocation(), SourceLocation(),
+                                   lang_c, SourceLocation());
+}
+
+void UsingDirectiveDecl::anchor() { }
+
 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext =
*DC,
                                                SourceLocation L,
                                                SourceLocation NamespaceLoc,
@@ -1601,6 +1815,14 @@
                                     IdentLoc, Used, CommonAncestor);
 }
=20
+UsingDirectiveDecl *
+UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(UsingDirectiveDecl)=
);
+  return new (Mem) UsingDirectiveDecl(0, SourceLocation(), SourceLocation(=
),
+                                      NestedNameSpecifierLoc(),
+                                      SourceLocation(), 0, 0);
+}
+
 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
   if (NamespaceAliasDecl *NA =3D
         dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
@@ -1608,6 +1830,36 @@
   return cast_or_null<NamespaceDecl>(NominatedNamespace);
 }
=20
+void NamespaceDecl::anchor() { }
+
+NamespaceDecl::NamespaceDecl(DeclContext *DC, bool Inline,=20
+                             SourceLocation StartLoc,
+                             SourceLocation IdLoc, IdentifierInfo *Id,
+                             NamespaceDecl *PrevDecl)
+  : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
+    LocStart(StartLoc), RBraceLoc(), AnonOrFirstNamespaceAndInline(0, Inli=
ne)=20
+{
+  setPreviousDeclaration(PrevDecl);
+ =20
+  if (PrevDecl)
+    AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespac=
e());
+}
+
+NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
+                                     bool Inline, SourceLocation StartLoc,
+                                     SourceLocation IdLoc, IdentifierInfo =
*Id,
+                                     NamespaceDecl *PrevDecl) {
+  return new (C) NamespaceDecl(DC, Inline, StartLoc, IdLoc, Id, PrevDecl);
+}
+
+NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned I=
D) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(NamespaceDecl));
+  return new (Mem) NamespaceDecl(0, false, SourceLocation(), SourceLocatio=
n(),=20
+                                 0, 0);
+}
+
+void NamespaceAliasDecl::anchor() { }
+
 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext =
*DC,
                                                SourceLocation UsingLoc,
                                                SourceLocation AliasLoc,
@@ -1621,6 +1873,22 @@
                                     QualifierLoc, IdentLoc, Namespace);
 }
=20
+NamespaceAliasDecl *
+NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(NamespaceAliasDecl)=
);
+  return new (Mem) NamespaceAliasDecl(0, SourceLocation(), SourceLocation(=
), 0,
+                                      NestedNameSpecifierLoc(),=20
+                                      SourceLocation(), 0);
+}
+
+void UsingShadowDecl::anchor() { }
+
+UsingShadowDecl *
+UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(UsingShadowDecl));
+  return new (Mem) UsingShadowDecl(0, SourceLocation(), 0, 0);
+}
+
 UsingDecl *UsingShadowDecl::getUsingDecl() const {
   const UsingShadowDecl *Shadow =3D this;
   while (const UsingShadowDecl *NextShadow =3D
@@ -1629,14 +1897,16 @@
   return cast<UsingDecl>(Shadow->UsingOrNextShadow);
 }
=20
+void UsingDecl::anchor() { }
+
 void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
   assert(std::find(shadow_begin(), shadow_end(), S) =3D=3D shadow_end() &&
          "declaration already in set");
   assert(S->getUsingDecl() =3D=3D this);
=20
-  if (FirstUsingShadow)
-    S->UsingOrNextShadow =3D FirstUsingShadow;
-  FirstUsingShadow =3D S;
+  if (FirstUsingShadow.getPointer())
+    S->UsingOrNextShadow =3D FirstUsingShadow.getPointer();
+  FirstUsingShadow.setPointer(S);
 }
=20
 void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
@@ -1646,13 +1916,14 @@
=20
   // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
=20
-  if (FirstUsingShadow =3D=3D S) {
-    FirstUsingShadow =3D dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow);
+  if (FirstUsingShadow.getPointer() =3D=3D S) {
+    FirstUsingShadow.setPointer(
+      dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
     S->UsingOrNextShadow =3D this;
     return;
   }
=20
-  UsingShadowDecl *Prev =3D FirstUsingShadow;
+  UsingShadowDecl *Prev =3D FirstUsingShadow.getPointer();
   while (Prev->UsingOrNextShadow !=3D S)
     Prev =3D cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
   Prev->UsingOrNextShadow =3D S->UsingOrNextShadow;
@@ -1666,6 +1937,14 @@
   return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, IsTypeNameArg);
 }
=20
+UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(UsingDecl));
+  return new (Mem) UsingDecl(0, SourceLocation(), NestedNameSpecifierLoc(),
+                             DeclarationNameInfo(), false);
+}
+
+void UnresolvedUsingValueDecl::anchor() { }
+
 UnresolvedUsingValueDecl *
 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
                                  SourceLocation UsingLoc,
@@ -1675,6 +1954,16 @@
                                           QualifierLoc, NameInfo);
 }
=20
+UnresolvedUsingValueDecl *
+UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(UnresolvedUsingValu=
eDecl));
+  return new (Mem) UnresolvedUsingValueDecl(0, QualType(), SourceLocation(=
),
+                                            NestedNameSpecifierLoc(),
+                                            DeclarationNameInfo());
+}
+
+void UnresolvedUsingTypenameDecl::anchor() { }
+
 UnresolvedUsingTypenameDecl *
 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
                                     SourceLocation UsingLoc,
@@ -1687,6 +1976,19 @@
                                              TargetName.getAsIdentifierInf=
o());
 }
=20
+UnresolvedUsingTypenameDecl *
+UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID=
) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID,=20
+                                       sizeof(UnresolvedUsingTypenameDecl)=
);
+  return new (Mem) UnresolvedUsingTypenameDecl(0, SourceLocation(),
+                                               SourceLocation(),
+                                               NestedNameSpecifierLoc(),
+                                               SourceLocation(),
+                                               0);
+}
+
+void StaticAssertDecl::anchor() { }
+
 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
                                            SourceLocation StaticAssertLoc,
                                            Expr *AssertExpr,
@@ -1696,9 +1998,14 @@
                                   RParenLoc);
 }
=20
+StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,=20
+                                                       unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(StaticAssertDecl));
+  return new (Mem) StaticAssertDecl(0, SourceLocation(), 0, 0,SourceLocati=
on());
+}
+
 static const char *getAccessName(AccessSpecifier AS) {
   switch (AS) {
-    default:
     case AS_none:
       llvm_unreachable("Invalid access specifier!");
     case AS_public:
@@ -1708,9 +2015,15 @@
     case AS_protected:
       return "protected";
   }
+  llvm_unreachable("Invalid access specifier!");
 }
=20
 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
                                            AccessSpecifier AS) {
   return DB << getAccessName(AS);
 }
+
+const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB,
+                                           AccessSpecifier AS) {
+  return DB << getAccessName(AS);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DeclFriend.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DeclFriend.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DeclFriend.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -16,6 +16,8 @@
 #include "clang/AST/DeclTemplate.h"
 using namespace clang;
=20
+void FriendDecl::anchor() { }
+
 FriendDecl *FriendDecl::Create(ASTContext &C, DeclContext *DC,
                                SourceLocation L,
                                FriendUnion Friend,
@@ -40,6 +42,7 @@
   return FD;
 }
=20
-FriendDecl *FriendDecl::Create(ASTContext &C, EmptyShell Empty) {
-  return new (C) FriendDecl(Empty);
+FriendDecl *FriendDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(FriendDecl));
+  return new (Mem) FriendDecl(EmptyShell());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DeclObjC.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DeclObjC.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DeclObjC.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -46,6 +46,8 @@
 // ObjCInterfaceDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCContainerDecl::anchor() { }
+
 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
 ///
 ObjCIvarDecl *
@@ -147,6 +149,8 @@
   return 0;
 }
=20
+void ObjCInterfaceDecl::anchor() { }
+
 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
 /// with name 'PropertyId' in the primary class; including those in protoc=
ols
 /// (direct or indirect) used by the primary class.
@@ -154,7 +158,11 @@
 ObjCPropertyDecl *
 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
                                             IdentifierInfo *PropertyId) co=
nst {
-  if (ExternallyCompleted)
+  // FIXME: Should make sure no callers ever do this.
+  if (!hasDefinition())
+    return 0;
+ =20
+  if (data().ExternallyCompleted)
     LoadExternalDefinition();
=20
   if (ObjCPropertyDecl *PD =3D
@@ -175,11 +183,12 @@
                               ObjCProtocolDecl *const* ExtList, unsigned E=
xtNum,
                               ASTContext &C)
 {
-  if (ExternallyCompleted)
+  if (data().ExternallyCompleted)
     LoadExternalDefinition();
=20
-  if (AllReferencedProtocols.empty() && ReferencedProtocols.empty()) {
-    AllReferencedProtocols.set(ExtList, ExtNum, C);
+  if (data().AllReferencedProtocols.empty() &&=20
+      data().ReferencedProtocols.empty()) {
+    data().AllReferencedProtocols.set(ExtList, ExtNum, C);
     return;
   }
  =20
@@ -214,7 +223,28 @@
     ProtocolRefs.push_back(*p);
   }
=20
-  AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(), C);
+  data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size=
(),C);
+}
+
+void ObjCInterfaceDecl::allocateDefinitionData() {
+  assert(!hasDefinition() && "ObjC class already has a definition");
+  Data =3D new (getASTContext()) DefinitionData();
+  Data->Definition =3D this;
+
+  // Make the type point at the definition, now that we have one.
+  if (TypeForDecl)
+    cast<ObjCInterfaceType>(TypeForDecl)->Decl =3D this;
+}
+
+void ObjCInterfaceDecl::startDefinition() {
+  allocateDefinitionData();
+
+  // Update all of the declarations with a pointer to the definition.
+  for (redecl_iterator RD =3D redecls_begin(), RDEnd =3D redecls_end();
+       RD !=3D RDEnd; ++RD) {
+    if (*RD !=3D this)
+      RD->Data =3D Data;
+  }
 }
=20
 /// getFirstClassExtension - Find first class extension of the given class.
@@ -237,6 +267,13 @@
=20
 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
                                               ObjCInterfaceDecl *&clsDecla=
red) {
+  // FIXME: Should make sure no callers ever do this.
+  if (!hasDefinition())
+    return 0; =20
+
+  if (data().ExternallyCompleted)
+    LoadExternalDefinition();
+
   ObjCInterfaceDecl* ClassDecl =3D this;
   while (ClassDecl !=3D NULL) {
     if (ObjCIvarDecl *I =3D ClassDecl->getIvarDecl(ID)) {
@@ -261,6 +298,13 @@
 /// the it returns NULL.
 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
                                         const IdentifierInfo*ICName) {
+  // FIXME: Should make sure no callers ever do this.
+  if (!hasDefinition())
+    return 0;
+
+  if (data().ExternallyCompleted)
+    LoadExternalDefinition();
+
   ObjCInterfaceDecl* ClassDecl =3D this;
   while (ClassDecl !=3D NULL) {
     if (ClassDecl->getIdentifier() =3D=3D ICName)
@@ -272,12 +316,17 @@
=20
 /// lookupMethod - This method returns an instance/class method by looking=
 in
 /// the class, its categories, and its super classes (using a linear searc=
h).
-ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
-                                                bool isInstance) const {
+ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,=20
+                                     bool isInstance,
+                                     bool shallowCategoryLookup) const {
+  // FIXME: Should make sure no callers ever do this.
+  if (!hasDefinition())
+    return 0;
+
   const ObjCInterfaceDecl* ClassDecl =3D this;
   ObjCMethodDecl *MethodDecl =3D 0;
=20
-  if (ExternallyCompleted)
+  if (data().ExternallyCompleted)
     LoadExternalDefinition();
=20
   while (ClassDecl !=3D NULL) {
@@ -285,28 +334,30 @@
       return MethodDecl;
=20
     // Didn't find one yet - look through protocols.
-    const ObjCList<ObjCProtocolDecl> &Protocols =3D
-      ClassDecl->getReferencedProtocols();
-    for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
-         E =3D Protocols.end(); I !=3D E; ++I)
+    for (ObjCInterfaceDecl::protocol_iterator I =3D ClassDecl->protocol_be=
gin(),
+                                              E =3D ClassDecl->protocol_en=
d();
+           I !=3D E; ++I)
       if ((MethodDecl =3D (*I)->lookupMethod(Sel, isInstance)))
         return MethodDecl;
-
+   =20
     // Didn't find one yet - now look through categories.
     ObjCCategoryDecl *CatDecl =3D ClassDecl->getCategoryList();
     while (CatDecl) {
       if ((MethodDecl =3D CatDecl->getMethod(Sel, isInstance)))
         return MethodDecl;
=20
-      // Didn't find one yet - look through protocols.
-      const ObjCList<ObjCProtocolDecl> &Protocols =3D
-        CatDecl->getReferencedProtocols();
-      for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
-           E =3D Protocols.end(); I !=3D E; ++I)
-        if ((MethodDecl =3D (*I)->lookupMethod(Sel, isInstance)))
-          return MethodDecl;
+      if (!shallowCategoryLookup) {
+        // Didn't find one yet - look through protocols.
+        const ObjCList<ObjCProtocolDecl> &Protocols =3D
+          CatDecl->getReferencedProtocols();
+        for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
+             E =3D Protocols.end(); I !=3D E; ++I)
+          if ((MethodDecl =3D (*I)->lookupMethod(Sel, isInstance)))
+            return MethodDecl;
+      }
       CatDecl =3D CatDecl->getNextClassCategory();
     }
+ =20
     ClassDecl =3D ClassDecl->getSuperClass();
   }
   return NULL;
@@ -315,6 +366,13 @@
 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
                                    const Selector &Sel,
                                    bool Instance) {
+  // FIXME: Should make sure no callers ever do this.
+  if (!hasDefinition())
+    return 0;
+
+  if (data().ExternallyCompleted)
+    LoadExternalDefinition();
+
   ObjCMethodDecl *Method =3D 0;
   if (ObjCImplementationDecl *ImpDecl =3D getImplementation())
     Method =3D Instance ? ImpDecl->getInstanceMethod(Sel)=20
@@ -351,6 +409,12 @@
                                 HasRelatedResultType);
 }
=20
+ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned=
 ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCMethodDecl));
+  return new (Mem) ObjCMethodDecl(SourceLocation(), SourceLocation(),=20
+                                  Selector(), QualType(), 0, 0);
+}
+
 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) {
   assert(PrevMethod);
   getASTContext().setObjCMethodRedeclaration(PrevMethod, this);
@@ -452,6 +516,10 @@
         return MD;
   }
=20
+  if (isRedeclaration())
+    return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
+                                                    isInstanceMethod());
+
   return this;
 }
=20
@@ -560,17 +628,26 @@
=20
   bool selfIsPseudoStrong =3D false;
   bool selfIsConsumed =3D false;
-  if (isInstanceMethod() && Context.getLangOptions().ObjCAutoRefCount) {
-    selfIsConsumed =3D hasAttr<NSConsumesSelfAttr>();
+ =20
+  if (Context.getLangOpts().ObjCAutoRefCount) {
+    if (isInstanceMethod()) {
+      selfIsConsumed =3D hasAttr<NSConsumesSelfAttr>();
=20
-    // 'self' is always __strong.  It's actually pseudo-strong except
-    // in init methods, though.
-    Qualifiers qs;
-    qs.setObjCLifetime(Qualifiers::OCL_Strong);
-    selfTy =3D Context.getQualifiedType(selfTy, qs);
+      // 'self' is always __strong.  It's actually pseudo-strong except
+      // in init methods (or methods labeled ns_consumes_self), though.
+      Qualifiers qs;
+      qs.setObjCLifetime(Qualifiers::OCL_Strong);
+      selfTy =3D Context.getQualifiedType(selfTy, qs);
=20
-    // In addition, 'self' is const unless this is an init method.
-    if (getMethodFamily() !=3D OMF_init) {
+      // In addition, 'self' is const unless this is an init method.
+      if (getMethodFamily() !=3D OMF_init && !selfIsConsumed) {
+        selfTy =3D selfTy.withConst();
+        selfIsPseudoStrong =3D true;
+      }
+    }
+    else {
+      assert(isClassMethod());
+      // 'self' is always const in class methods.
       selfTy =3D selfTy.withConst();
       selfIsPseudoStrong =3D true;
     }
@@ -608,28 +685,45 @@
 // ObjCInterfaceDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-ObjCInterfaceDecl *ObjCInterfaceDecl::Create(ASTContext &C,
+ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
                                              DeclContext *DC,
                                              SourceLocation atLoc,
                                              IdentifierInfo *Id,
+                                             ObjCInterfaceDecl *PrevDecl,
                                              SourceLocation ClassLoc,
-                                             bool ForwardDecl, bool isInte=
rnal){
-  return new (C) ObjCInterfaceDecl(DC, atLoc, Id, ClassLoc, ForwardDecl,
-                                     isInternal);
+                                             bool isInternal){
+  ObjCInterfaceDecl *Result =3D new (C) ObjCInterfaceDecl(DC, atLoc, Id, C=
lassLoc,=20
+                                                        PrevDecl, isIntern=
al);
+  C.getObjCInterfaceType(Result, PrevDecl);
+  return Result;
+}
+
+ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(ASTContext &C,=20
+                                                         unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCInterfaceDecl));
+  return new (Mem) ObjCInterfaceDecl(0, SourceLocation(), 0, SourceLocatio=
n(),
+                                     0, false);
 }
=20
 ObjCInterfaceDecl::
 ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *I=
d,
-                  SourceLocation CLoc, bool FD, bool isInternal)
+                  SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
+                  bool isInternal)
   : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, atLoc),
-    TypeForDecl(0), SuperClass(0),
-    CategoryList(0), IvarList(0),=20
-    ForwardDecl(FD), InternalInterface(isInternal), ExternallyCompleted(fa=
lse) {
+    TypeForDecl(0), Data()
+{
+  setPreviousDeclaration(PrevDecl);
+ =20
+  // Copy the 'data' pointer over.
+  if (PrevDecl)
+    Data =3D PrevDecl->Data;
+ =20
+  setImplicit(isInternal);
 }
=20
 void ObjCInterfaceDecl::LoadExternalDefinition() const {
-  assert(ExternallyCompleted && "Class is not externally completed");
-  ExternallyCompleted =3D false;
+  assert(data().ExternallyCompleted && "Class is not externally completed"=
);
+  data().ExternallyCompleted =3D false;
   getASTContext().getExternalSource()->CompleteType(
                                         const_cast<ObjCInterfaceDecl *>(th=
is));
 }
@@ -637,35 +731,44 @@
 void ObjCInterfaceDecl::setExternallyCompleted() {
   assert(getASTContext().getExternalSource() &&=20
          "Class can't be externally completed without an external source");
-  assert(!ForwardDecl &&=20
+  assert(hasDefinition() &&=20
          "Forward declarations can't be externally completed");
-  ExternallyCompleted =3D true;
+  data().ExternallyCompleted =3D true;
 }
=20
 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
-  if (ExternallyCompleted)
-    LoadExternalDefinition();
-
-  return getASTContext().getObjCImplementation(
-                                          const_cast<ObjCInterfaceDecl*>(t=
his));
+  if (const ObjCInterfaceDecl *Def =3D getDefinition()) {
+    if (data().ExternallyCompleted)
+      LoadExternalDefinition();
+   =20
+    return getASTContext().getObjCImplementation(
+             const_cast<ObjCInterfaceDecl*>(Def));
+  }
+ =20
+  // FIXME: Should make sure no callers ever do this.
+  return 0;
 }
=20
 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
-  getASTContext().setObjCImplementation(this, ImplD);
+  getASTContext().setObjCImplementation(getDefinition(), ImplD);
 }
=20
 /// all_declared_ivar_begin - return first ivar declared in this class,
 /// its extensions and its implementation. Lazily build the list on first
 /// access.
 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
-  if (IvarList)
-    return IvarList;
+  // FIXME: Should make sure no callers ever do this.
+  if (!hasDefinition())
+    return 0;
+ =20
+  if (data().IvarList)
+    return data().IvarList;
  =20
   ObjCIvarDecl *curIvar =3D 0;
   if (!ivar_empty()) {
     ObjCInterfaceDecl::ivar_iterator I =3D ivar_begin(), E =3D ivar_end();
-    IvarList =3D (*I); ++I;
-    for (curIvar =3D IvarList; I !=3D E; curIvar =3D *I, ++I)
+    data().IvarList =3D (*I); ++I;
+    for (curIvar =3D data().IvarList; I !=3D E; curIvar =3D *I, ++I)
       curIvar->setNextIvar(*I);
   }
  =20
@@ -674,9 +777,9 @@
     if (!CDecl->ivar_empty()) {
       ObjCCategoryDecl::ivar_iterator I =3D CDecl->ivar_begin(),
                                           E =3D CDecl->ivar_end();
-      if (!IvarList) {
-        IvarList =3D (*I); ++I;
-        curIvar =3D IvarList;
+      if (!data().IvarList) {
+        data().IvarList =3D (*I); ++I;
+        curIvar =3D data().IvarList;
       }
       for ( ;I !=3D E; curIvar =3D *I, ++I)
         curIvar->setNextIvar(*I);
@@ -687,15 +790,15 @@
     if (!ImplDecl->ivar_empty()) {
       ObjCImplementationDecl::ivar_iterator I =3D ImplDecl->ivar_begin(),
                                             E =3D ImplDecl->ivar_end();
-      if (!IvarList) {
-        IvarList =3D (*I); ++I;
-        curIvar =3D IvarList;
+      if (!data().IvarList) {
+        data().IvarList =3D (*I); ++I;
+        curIvar =3D data().IvarList;
       }
       for ( ;I !=3D E; curIvar =3D *I, ++I)
         curIvar->setNextIvar(*I);
     }
   }
-  return IvarList;
+  return data().IvarList;
 }
=20
 /// FindCategoryDeclaration - Finds category declaration in the list of
@@ -704,7 +807,11 @@
 ///
 ObjCCategoryDecl *
 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) con=
st {
-  if (ExternallyCompleted)
+  // FIXME: Should make sure no callers ever do this.
+  if (!hasDefinition())
+    return 0;
+
+  if (data().ExternallyCompleted)
     LoadExternalDefinition();
=20
   for (ObjCCategoryDecl *Category =3D getCategoryList();
@@ -739,13 +846,13 @@
 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
                                     bool lookupCategory,
                                     bool RHSIsQualifiedID) {
+  if (!hasDefinition())
+    return false;
+ =20
   ObjCInterfaceDecl *IDecl =3D this;
   // 1st, look up the class.
-  const ObjCList<ObjCProtocolDecl> &Protocols =3D
-  IDecl->getReferencedProtocols();
-
-  for (ObjCList<ObjCProtocolDecl>::iterator PI =3D Protocols.begin(),
-       E =3D Protocols.end(); PI !=3D E; ++PI) {
+  for (ObjCInterfaceDecl::protocol_iterator
+        PI =3D IDecl->protocol_begin(), E =3D IDecl->protocol_end(); PI !=
=3D E; ++PI){
     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
       return true;
     // This is dubious and is added to be compatible with gcc.  In gcc, it=
 is
@@ -782,6 +889,8 @@
 // ObjCIvarDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCIvarDecl::anchor() { }
+
 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
                                    SourceLocation StartLoc,
                                    SourceLocation IdLoc, IdentifierInfo *I=
d,
@@ -824,6 +933,12 @@
                               ac, BW, synthesized);
 }
=20
+ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID)=
 {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCIvarDecl));
+  return new (Mem) ObjCIvarDecl(0, SourceLocation(), SourceLocation(), 0,
+                                QualType(), 0, ObjCIvarDecl::None, 0, fals=
e);
+}
+
 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
   const ObjCContainerDecl *DC =3D cast<ObjCContainerDecl>(getDeclContext()=
);
=20
@@ -852,6 +967,8 @@
 // ObjCAtDefsFieldDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCAtDefsFieldDecl::anchor() { }
+
 ObjCAtDefsFieldDecl
 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
                              SourceLocation StartLoc,  SourceLocation IdLo=
c,
@@ -859,15 +976,46 @@
   return new (C) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
 }
=20
+ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C=
,=20
+                                                             unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCAtDefsFieldDecl=
));
+  return new (Mem) ObjCAtDefsFieldDecl(0, SourceLocation(), SourceLocation=
(),
+                                       0, QualType(), 0);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ObjCProtocolDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCProtocolDecl::anchor() { }
+
+ObjCProtocolDecl::ObjCProtocolDecl(DeclContext *DC, IdentifierInfo *Id,
+                                   SourceLocation nameLoc,=20
+                                   SourceLocation atStartLoc,
+                                   ObjCProtocolDecl *PrevDecl)
+  : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc), Data()
+{
+  setPreviousDeclaration(PrevDecl);
+  if (PrevDecl)
+    Data =3D PrevDecl->Data;
+}
+
 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
                                            IdentifierInfo *Id,
                                            SourceLocation nameLoc,
-                                           SourceLocation atStartLoc) {
-  return new (C) ObjCProtocolDecl(DC, Id, nameLoc, atStartLoc);
+                                           SourceLocation atStartLoc,
+                                           ObjCProtocolDecl *PrevDecl) {
+  ObjCProtocolDecl *Result=20
+    =3D new (C) ObjCProtocolDecl(DC, Id, nameLoc, atStartLoc, PrevDecl);
+ =20
+  return Result;
+}
+
+ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,=20
+                                                       unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCProtocolDecl));
+  return new (Mem) ObjCProtocolDecl(0, 0, SourceLocation(), SourceLocation=
(),
+                                    0);
 }
=20
 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Na=
me) {
@@ -898,87 +1046,57 @@
   return NULL;
 }
=20
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// ObjCClassDecl
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-ObjCClassDecl::ObjCClassDecl(DeclContext *DC, SourceLocation L,
-                             ObjCInterfaceDecl *const Elt,
-                             const SourceLocation Loc,
-                             ASTContext &C)
-  : Decl(ObjCClass, DC, L) {
-  setClass(C, Elt, Loc);
+void ObjCProtocolDecl::allocateDefinitionData() {
+  assert(!Data && "Protocol already has a definition!");
+  Data =3D new (getASTContext()) DefinitionData;
+  Data->Definition =3D this;
 }
=20
-ObjCClassDecl *ObjCClassDecl::Create(ASTContext &C, DeclContext *DC,
-                                     SourceLocation L,
-                                     ObjCInterfaceDecl *const Elt,
-                                     const SourceLocation Loc) {
-  return new (C) ObjCClassDecl(DC, L, Elt, Loc, C);
-}
-
-void ObjCClassDecl::setClass(ASTContext &C, ObjCInterfaceDecl*const Cls,
-                             const SourceLocation Loc) {
-   =20
-  ForwardDecl =3D (ObjCClassRef*) C.Allocate(sizeof(ObjCClassRef),
-                                           llvm::alignOf<ObjCClassRef>());
-  new (ForwardDecl) ObjCClassRef(Cls, Loc);
-}
-   =20
-SourceRange ObjCClassDecl::getSourceRange() const {
-  // FIXME: We should include the semicolon
-  return SourceRange(getLocation(), ForwardDecl->getLocation());
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// ObjCForwardProtocolDecl
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-ObjCForwardProtocolDecl::
-ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L,
-                        ObjCProtocolDecl *const *Elts, unsigned nElts,
-                        const SourceLocation *Locs, ASTContext &C)
-: Decl(ObjCForwardProtocol, DC, L) {
-  ReferencedProtocols.set(Elts, nElts, Locs, C);
-}
-
-
-ObjCForwardProtocolDecl *
-ObjCForwardProtocolDecl::Create(ASTContext &C, DeclContext *DC,
-                                SourceLocation L,
-                                ObjCProtocolDecl *const *Elts,
-                                unsigned NumElts,
-                                const SourceLocation *Locs) {
-  return new (C) ObjCForwardProtocolDecl(DC, L, Elts, NumElts, Locs, C);
+void ObjCProtocolDecl::startDefinition() {
+  allocateDefinitionData();
+ =20
+  // Update all of the declarations with a pointer to the definition.
+  for (redecl_iterator RD =3D redecls_begin(), RDEnd =3D redecls_end();
+       RD !=3D RDEnd; ++RD)
+    RD->Data =3D this->Data;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ObjCCategoryDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCCategoryDecl::anchor() { }
+
 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
                                            SourceLocation AtLoc,=20
                                            SourceLocation ClassNameLoc,
                                            SourceLocation CategoryNameLoc,
                                            IdentifierInfo *Id,
-                                           ObjCInterfaceDecl *IDecl) {
+                                           ObjCInterfaceDecl *IDecl,
+                                           SourceLocation IvarLBraceLoc,
+                                           SourceLocation IvarRBraceLoc) {
   ObjCCategoryDecl *CatDecl =3D new (C) ObjCCategoryDecl(DC, AtLoc, ClassN=
ameLoc,
                                                        CategoryNameLoc, Id,
-                                                       IDecl);
+                                                       IDecl,
+                                                       IvarLBraceLoc, Ivar=
RBraceLoc);
   if (IDecl) {
     // Link this category into its class's category list.
     CatDecl->NextClassCategory =3D IDecl->getCategoryList();
-    IDecl->setCategoryList(CatDecl);
-    if (ASTMutationListener *L =3D C.getASTMutationListener())
-      L->AddedObjCCategoryToInterface(CatDecl, IDecl);
+    if (IDecl->hasDefinition()) {
+      IDecl->setCategoryList(CatDecl);
+      if (ASTMutationListener *L =3D C.getASTMutationListener())
+        L->AddedObjCCategoryToInterface(CatDecl, IDecl);
+    }
   }
=20
   return CatDecl;
 }
=20
-ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, EmptyShell Empty=
) {
-  return new (C) ObjCCategoryDecl(0, SourceLocation(), SourceLocation(),
-                                  SourceLocation(), 0, 0);
+ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,=20
+                                                       unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCCategoryDecl));
+  return new (Mem) ObjCCategoryDecl(0, SourceLocation(), SourceLocation(),
+                                    SourceLocation(), 0, 0);
 }
=20
 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
@@ -995,14 +1113,26 @@
 // ObjCCategoryImplDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCCategoryImplDecl::anchor() { }
+
 ObjCCategoryImplDecl *
 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
                              IdentifierInfo *Id,
                              ObjCInterfaceDecl *ClassInterface,
                              SourceLocation nameLoc,
-                             SourceLocation atStartLoc) {
+                             SourceLocation atStartLoc,
+                             SourceLocation CategoryNameLoc) {
+  if (ClassInterface && ClassInterface->hasDefinition())
+    ClassInterface =3D ClassInterface->getDefinition();
   return new (C) ObjCCategoryImplDecl(DC, Id, ClassInterface,
-                                      nameLoc, atStartLoc);
+                                      nameLoc, atStartLoc, CategoryNameLoc=
);
+}
+
+ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext =
&C,=20
+                                                               unsigned ID=
) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCCategoryImplDec=
l));
+  return new (Mem) ObjCCategoryImplDecl(0, 0, 0, SourceLocation(),=20
+                                        SourceLocation(), SourceLocation()=
);
 }
=20
 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
@@ -1013,6 +1143,8 @@
 }
=20
=20
+void ObjCImplDecl::anchor() { }
+
 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *propert=
y) {
   // FIXME: The context should be correct before we get here.
   property->setLexicalDeclContext(this);
@@ -1066,8 +1198,8 @@
 }
=20
 raw_ostream &clang::operator<<(raw_ostream &OS,
-                                     const ObjCCategoryImplDecl *CID) {
-  OS << CID->getName();
+                               const ObjCCategoryImplDecl &CID) {
+  OS << CID.getName();
   return OS;
 }
=20
@@ -1075,14 +1207,28 @@
 // ObjCImplementationDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCImplementationDecl::anchor() { }
+
 ObjCImplementationDecl *
 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
                                ObjCInterfaceDecl *ClassInterface,
                                ObjCInterfaceDecl *SuperDecl,
                                SourceLocation nameLoc,
-                               SourceLocation atStartLoc) {
+                               SourceLocation atStartLoc,
+                               SourceLocation IvarLBraceLoc,
+                               SourceLocation IvarRBraceLoc) {
+  if (ClassInterface && ClassInterface->hasDefinition())
+    ClassInterface =3D ClassInterface->getDefinition();
   return new (C) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
-                                        nameLoc, atStartLoc);
+                                        nameLoc, atStartLoc,
+                                        IvarLBraceLoc, IvarRBraceLoc);
+}
+
+ObjCImplementationDecl *
+ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCImplementationD=
ecl));
+  return new (Mem) ObjCImplementationDecl(0, 0, 0, SourceLocation(),=20
+                                          SourceLocation());
 }
=20
 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
@@ -1099,8 +1245,8 @@
 }
=20
 raw_ostream &clang::operator<<(raw_ostream &OS,
-                                     const ObjCImplementationDecl *ID) {
-  OS << ID->getName();
+                               const ObjCImplementationDecl &ID) {
+  OS << ID.getName();
   return OS;
 }
=20
@@ -1108,6 +1254,8 @@
 // ObjCCompatibleAliasDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCCompatibleAliasDecl::anchor() { }
+
 ObjCCompatibleAliasDecl *
 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
                                 SourceLocation L,
@@ -1116,17 +1264,34 @@
   return new (C) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
 }
=20
+ObjCCompatibleAliasDecl *
+ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCCompatibleAlias=
Decl));
+  return new (Mem) ObjCCompatibleAliasDecl(0, SourceLocation(), 0, 0);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ObjCPropertyDecl
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void ObjCPropertyDecl::anchor() { }
+
 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
                                            SourceLocation L,
                                            IdentifierInfo *Id,
                                            SourceLocation AtLoc,
+                                           SourceLocation LParenLoc,
                                            TypeSourceInfo *T,
                                            PropertyControl propControl) {
-  return new (C) ObjCPropertyDecl(DC, L, Id, AtLoc, T);
+  return new (C) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T);
+}
+
+ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,=20
+                                                       unsigned ID) {
+  void * Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCPropertyDecl));
+  return new (Mem) ObjCPropertyDecl(0, SourceLocation(), 0, SourceLocation=
(),
+                                    SourceLocation(),
+                                    0);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1145,6 +1310,13 @@
                                       ivarLoc);
 }
=20
+ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext =
&C,=20
+                                                               unsigned ID=
) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ObjCPropertyImplDec=
l));
+  return new (Mem) ObjCPropertyImplDecl(0, SourceLocation(), SourceLocatio=
n(),
+                                        0, Dynamic, 0, SourceLocation());
+}
+
 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
   SourceLocation EndLoc =3D getLocation();
   if (IvarLoc.isValid())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DeclPrinter.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DeclPrinter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DeclPrinter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/PrettyPrinter.h"
+#include "clang/Basic/Module.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace clang;
=20
@@ -58,6 +59,7 @@
     void VisitLabelDecl(LabelDecl *D);
     void VisitParmVarDecl(ParmVarDecl *D);
     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
+    void VisitImportDecl(ImportDecl *D);
     void VisitStaticAssertDecl(StaticAssertDecl *D);
     void VisitNamespaceDecl(NamespaceDecl *D);
     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
@@ -68,10 +70,8 @@
     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
     void VisitClassTemplateDecl(ClassTemplateDecl *D);
     void VisitObjCMethodDecl(ObjCMethodDecl *D);
-    void VisitObjCClassDecl(ObjCClassDecl *D);
     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
-    void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
@@ -85,6 +85,7 @@
=20
     void PrintTemplateParameters(const TemplateParameterList *Params,
                                  const TemplateArgumentList *Args);
+    void prettyPrintAttributes(Decl *D);
   };
 }
=20
@@ -182,6 +183,16 @@
   return Out;
 }
=20
+void DeclPrinter::prettyPrintAttributes(Decl *D) {
+  if (D->hasAttrs()) {
+    AttrVec &Attrs =3D D->getAttrs();
+    for (AttrVec::const_iterator i=3DAttrs.begin(), e=3DAttrs.end(); i!=3D=
e; ++i) {
+        Attr *A =3D *i;
+        A->printPretty(Out, Context);
+    }
+  }
+}
+
 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
   this->Indent();
   Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
@@ -320,11 +331,11 @@
       Out << "__module_private__ ";
   }
   Out << S;
+  prettyPrintAttributes(D);
 }
=20
 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
-  Out << "using " << D->getNameAsString() << " =3D "
-      << D->getUnderlyingType().getAsString(Policy);
+  Out << "using " << *D << " =3D " << D->getUnderlyingType().getAsString(P=
olicy);
 }
=20
 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
@@ -350,6 +361,7 @@
     VisitDeclContext(D);
     Indent() << "}";
   }
+  prettyPrintAttributes(D);
 }
=20
 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
@@ -376,7 +388,7 @@
=20
 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
   if (!Policy.SuppressSpecifiers) {
-    switch (D->getStorageClass()) {
+    switch (D->getStorageClassAsWritten()) {
     case SC_None: break;
     case SC_Extern: Out << "extern "; break;
     case SC_Static: Out << "static "; break;
@@ -466,12 +478,6 @@
       }
     }
=20
-    if (D->hasAttr<NoReturnAttr>())
-      Proto +=3D " __attribute((noreturn))";
-
-    if (D->hasAttr<ReturnsTwiceAttr>())
-      Proto +=3D " __attribute((returns_twice))";
-
     if (CXXConstructorDecl *CDecl =3D dyn_cast<CXXConstructorDecl>(D)) {
       bool HasInitializerList =3D false;
       for (CXXConstructorDecl::init_const_iterator B =3D CDecl->init_begin=
(),
@@ -542,6 +548,7 @@
   }
=20
   Out << Proto;
+  prettyPrintAttributes(D);
=20
   if (D->isPure())
     Out << " =3D 0";
@@ -588,16 +595,18 @@
     Out << " =3D ";
     Init->printPretty(Out, Context, 0, Policy, Indentation);
   }
+  prettyPrintAttributes(D);
 }
=20
 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
-  Out << D->getNameAsString() << ":";
+  Out << *D << ":";
 }
=20
=20
 void DeclPrinter::VisitVarDecl(VarDecl *D) {
-  if (!Policy.SuppressSpecifiers && D->getStorageClass() !=3D SC_None)
-    Out << VarDecl::getStorageClassSpecifierString(D->getStorageClass()) <=
< " ";
+  StorageClass SCAsWritten =3D D->getStorageClassAsWritten();
+  if (!Policy.SuppressSpecifiers && SCAsWritten !=3D SC_None)
+    Out << VarDecl::getStorageClassSpecifierString(SCAsWritten) << " ";
=20
   if (!Policy.SuppressSpecifiers && D->isThreadSpecified())
     Out << "__thread ";
@@ -612,17 +621,22 @@
   Out << Name;
   Expr *Init =3D D->getInit();
   if (!Policy.SuppressInitializers && Init) {
-    if (D->hasCXXDirectInitializer())
-      Out << "(";
-    else {
-        CXXConstructExpr *CCE =3D dyn_cast<CXXConstructExpr>(Init);
-        if (!CCE || CCE->getConstructor()->isCopyConstructor())
-          Out << " =3D ";
+    bool ImplicitInit =3D false;
+    if (CXXConstructExpr *Construct =3D dyn_cast<CXXConstructExpr>(Init))
+      ImplicitInit =3D D->getInitStyle() =3D=3D VarDecl::CallInit &&
+          Construct->getNumArgs() =3D=3D 0 && !Construct->isListInitializa=
tion();
+    if (!ImplicitInit) {
+      if (D->getInitStyle() =3D=3D VarDecl::CallInit)
+        Out << "(";
+      else if (D->getInitStyle() =3D=3D VarDecl::CInit) {
+        Out << " =3D ";
+      }
+      Init->printPretty(Out, Context, 0, Policy, Indentation);
+      if (D->getInitStyle() =3D=3D VarDecl::CallInit)
+        Out << ")";
     }
-    Init->printPretty(Out, Context, 0, Policy, Indentation);
-    if (D->hasCXXDirectInitializer())
-      Out << ")";
   }
+  prettyPrintAttributes(D);
 }
=20
 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
@@ -635,6 +649,11 @@
   Out << ")";
 }
=20
+void DeclPrinter::VisitImportDecl(ImportDecl *D) {
+  Out << "@__experimental_modules_import " << D->getImportedModule()->getF=
ullModuleName()
+      << ";\n";
+}
+
 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
   Out << "static_assert(";
   D->getAssertExpr()->printPretty(Out, Context, 0, Policy, Indentation);
@@ -745,7 +764,7 @@
       if (TTP->isParameterPack())
         Out << "... ";
=20
-      Out << TTP->getNameAsString();
+      Out << *TTP;
=20
       if (Args) {
         Out << " =3D ";
@@ -829,10 +848,6 @@
 // Objective-C declarations
 //------------------------------------------------------------------------=
----
=20
-void DeclPrinter::VisitObjCClassDecl(ObjCClassDecl *D) {
-  Out << "@class " << *D->getForwardInterfaceDecl();
-}
-
 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
   if (OMD->isInstanceMethod())
     Out << "- ";
@@ -882,6 +897,11 @@
   std::string I =3D OID->getNameAsString();
   ObjCInterfaceDecl *SID =3D OID->getSuperClass();
=20
+  if (!OID->isThisDeclarationADefinition()) {
+    Out << "@class " << I << ";";
+    return;
+  }
+ =20
   if (SID)
     Out << "@interface " << I << " : " << *SID;
   else
@@ -914,17 +934,12 @@
   // FIXME: implement the rest...
 }
=20
-void DeclPrinter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D)=
 {
-  Out << "@protocol ";
-  for (ObjCForwardProtocolDecl::protocol_iterator I =3D D->protocol_begin(=
),
-         E =3D D->protocol_end();
-       I !=3D E; ++I) {
-    if (I !=3D D->protocol_begin()) Out << ", ";
-    Out << **I;
+void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
+  if (!PID->isThisDeclarationADefinition()) {
+    Out << "@protocol " << PID->getIdentifier() << ";\n";
+    return;
   }
-}
-
-void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
+ =20
   Out << "@protocol " << *PID << '\n';
   VisitDeclContext(PID, false);
   Out << "@end";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DeclTemplate.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DeclTemplate.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DeclTemplate.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -112,42 +112,34 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 RedeclarableTemplateDecl::CommonBase *RedeclarableTemplateDecl::getCommonP=
tr() {
-  // Find the first declaration of this function template.
-  RedeclarableTemplateDecl *First =3D getCanonicalDecl();
+  if (!Common) {
+    // Walk the previous-declaration chain until we either find a declarat=
ion
+    // with a common pointer or we run out of previous declarations.
+    llvm::SmallVector<RedeclarableTemplateDecl *, 2> PrevDecls;
+    for (RedeclarableTemplateDecl *Prev =3D getPreviousDecl(); Prev;
+         Prev =3D Prev->getPreviousDecl()) {
+      if (Prev->Common) {
+        Common =3D Prev->Common;
+        break;
+      }
+     =20
+      PrevDecls.push_back(Prev);
+    }
=20
-  if (First->CommonOrPrev.isNull()) {
-    CommonBase *CommonPtr =3D First->newCommon(getASTContext());
-    First->CommonOrPrev =3D CommonPtr;
-    CommonPtr->Latest =3D First;
+    // If we never found a common pointer, allocate one now.
+    if (!Common) {
+      // FIXME: If any of the declarations is from an AST file, we probably
+      // need an update record to add the common data.
+     =20
+      Common =3D newCommon(getASTContext());
+    }
+   =20
+    // Update any previous declarations we saw with the common pointer.
+    for (unsigned I =3D 0, N =3D PrevDecls.size(); I !=3D N; ++I)
+      PrevDecls[I]->Common =3D Common;
   }
-  return First->CommonOrPrev.get<CommonBase*>();
-}
=20
-
-RedeclarableTemplateDecl *RedeclarableTemplateDecl::getCanonicalDeclImpl()=
 {
-  RedeclarableTemplateDecl *Tmpl =3D this;
-  while (Tmpl->getPreviousDeclaration())
-    Tmpl =3D Tmpl->getPreviousDeclaration();
-  return Tmpl;
-}
-
-void RedeclarableTemplateDecl::setPreviousDeclarationImpl(
-                                               RedeclarableTemplateDecl *P=
rev) {
-  if (Prev) {
-    CommonBase *Common =3D Prev->getCommonPtr();
-    Prev =3D Common->Latest;
-    Common->Latest =3D this;
-    CommonOrPrev =3D Prev;
-  } else {
-    assert(CommonOrPrev.is<CommonBase*>() && "Cannot reset TemplateDecl Pr=
ev");
-  }
-}
-
-RedeclarableTemplateDecl *RedeclarableTemplateDecl::getNextRedeclaration()=
 {
-  if (CommonOrPrev.is<RedeclarableTemplateDecl*>())
-    return CommonOrPrev.get<RedeclarableTemplateDecl*>();
-  CommonBase *Common =3D CommonOrPrev.get<CommonBase*>();
-  return Common ? Common->Latest : this;
+  return Common;
 }
=20
 template <class EntryType>
@@ -160,7 +152,7 @@
   llvm::FoldingSetNodeID ID;
   EntryType::Profile(ID,Args,NumArgs, getASTContext());
   EntryType *Entry =3D Specs.FindNodeOrInsertPos(ID, InsertPos);
-  return Entry ? SETraits::getMostRecentDeclaration(Entry) : 0;
+  return Entry ? SETraits::getMostRecentDecl(Entry) : 0;
 }
=20
 /// \brief Generate the injected template arguments for the given template
@@ -181,7 +173,7 @@
       Arg =3D TemplateArgument(ArgType);
     } else if (NonTypeTemplateParmDecl *NTTP =3D
                dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
-      Expr *E =3D new (Context) DeclRefExpr(NTTP,
+      Expr *E =3D new (Context) DeclRefExpr(NTTP, /*enclosing*/ false,
                                   NTTP->getType().getNonLValueExprType(Con=
text),
                                   Expr::getValueKindForType(NTTP->getType(=
)),
                                           NTTP->getLocation());
@@ -224,9 +216,11 @@
   return new (C) FunctionTemplateDecl(DC, L, Name, Params, Decl);
 }
=20
-FunctionTemplateDecl *FunctionTemplateDecl::Create(ASTContext &C, EmptyShe=
ll) {
-  return new (C) FunctionTemplateDecl(0, SourceLocation(), DeclarationName=
(),
-                                      0, 0);
+FunctionTemplateDecl *FunctionTemplateDecl::CreateDeserialized(ASTContext =
&C,
+                                                               unsigned ID=
) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(FunctionTemplateDec=
l));
+  return new (Mem) FunctionTemplateDecl(0, SourceLocation(), DeclarationNa=
me(),
+                                        0, 0);
 }
=20
 RedeclarableTemplateDecl::CommonBase *
@@ -244,7 +238,10 @@
=20
 void FunctionTemplateDecl::addSpecialization(
       FunctionTemplateSpecializationInfo *Info, void *InsertPos) {
-  getSpecializations().InsertNode(Info, InsertPos);
+  if (InsertPos)
+    getSpecializations().InsertNode(Info, InsertPos);
+  else
+    getSpecializations().GetOrInsertNode(Info);
   if (ASTMutationListener *L =3D getASTMutationListener())
     L->AddedCXXTemplateSpecialization(this, Info->Function);
 }
@@ -284,8 +281,10 @@
   return New;
 }
=20
-ClassTemplateDecl *ClassTemplateDecl::Create(ASTContext &C, EmptyShell Emp=
ty) {
-  return new (C) ClassTemplateDecl(Empty);
+ClassTemplateDecl *ClassTemplateDecl::CreateDeserialized(ASTContext &C,=20
+                                                         unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(ClassTemplateDecl));
+  return new (Mem) ClassTemplateDecl(EmptyShell());
 }
=20
 void ClassTemplateDecl::LoadLazySpecializations() {
@@ -326,7 +325,14 @@
=20
 void ClassTemplateDecl::AddSpecialization(ClassTemplateSpecializationDecl =
*D,
                                           void *InsertPos) {
-  getSpecializations().InsertNode(D, InsertPos);
+  if (InsertPos)
+    getSpecializations().InsertNode(D, InsertPos);
+  else {
+    ClassTemplateSpecializationDecl *Existing=20
+      =3D getSpecializations().GetOrInsertNode(D);
+    (void)Existing;
+    assert(Existing->isCanonicalDecl() && "Non-canonical specialization?");
+  }
   if (ASTMutationListener *L =3D getASTMutationListener())
     L->AddedCXXTemplateSpecialization(this, D);
 }
@@ -342,7 +348,15 @@
 void ClassTemplateDecl::AddPartialSpecialization(
                                       ClassTemplatePartialSpecializationDe=
cl *D,
                                       void *InsertPos) {
-  getPartialSpecializations().InsertNode(D, InsertPos);
+  if (InsertPos)
+    getPartialSpecializations().InsertNode(D, InsertPos);
+  else {
+    ClassTemplatePartialSpecializationDecl *Existing
+      =3D getPartialSpecializations().GetOrInsertNode(D);
+    (void)Existing;
+    assert(Existing->isCanonicalDecl() && "Non-canonical specialization?");
+  }
+
   if (ASTMutationListener *L =3D getASTMutationListener())
     L->AddedCXXTemplateSpecialization(this, D);
 }
@@ -357,7 +371,7 @@
        P =3D PartialSpecs.begin(), PEnd =3D PartialSpecs.end();
        P !=3D PEnd; ++P) {
     assert(!PS[P->getSequenceNumber()]);
-    PS[P->getSequenceNumber()] =3D P->getMostRecentDeclaration();
+    PS[P->getSequenceNumber()] =3D P->getMostRecentDecl();
   }
 }
=20
@@ -370,7 +384,7 @@
                           PEnd =3D getPartialSpecializations().end();
        P !=3D PEnd; ++P) {
     if (Context.hasSameType(P->getInjectedSpecializationType(), T))
-      return P->getMostRecentDeclaration();
+      return P->getMostRecentDecl();
   }
=20
   return 0;
@@ -385,7 +399,7 @@
          PEnd =3D getPartialSpecializations().end();
        P !=3D PEnd; ++P) {
     if (P->getInstantiatedFromMember()->getCanonicalDecl() =3D=3D DCanon)
-      return P->getMostRecentDeclaration();
+      return P->getMostRecentDecl();
   }
=20
   return 0;
@@ -433,9 +447,10 @@
 }
=20
 TemplateTypeParmDecl *
-TemplateTypeParmDecl::Create(const ASTContext &C, EmptyShell Empty) {
-  return new (C) TemplateTypeParmDecl(0, SourceLocation(), SourceLocation(=
),
-                                      0, false);
+TemplateTypeParmDecl::CreateDeserialized(const ASTContext &C, unsigned ID)=
 {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(TemplateTypeParmDec=
l));
+  return new (Mem) TemplateTypeParmDecl(0, SourceLocation(), SourceLocatio=
n(),
+                                        0, false);
 }
=20
 SourceLocation TemplateTypeParmDecl::getDefaultArgumentLoc() const {
@@ -520,6 +535,27 @@
                                            ExpandedTInfos);
 }
=20
+NonTypeTemplateParmDecl *
+NonTypeTemplateParmDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(NonTypeTemplateParm=
Decl));
+  return new (Mem) NonTypeTemplateParmDecl(0, SourceLocation(),=20
+                                           SourceLocation(), 0, 0, 0,=20
+                                           QualType(), false, 0);
+}
+
+NonTypeTemplateParmDecl *
+NonTypeTemplateParmDecl::CreateDeserialized(ASTContext &C, unsigned ID,
+                                            unsigned NumExpandedTypes) {
+  unsigned Size =3D sizeof(NonTypeTemplateParmDecl)=20
+                + NumExpandedTypes * 2 * sizeof(void*);
+ =20
+  void *Mem =3D AllocateDeserializedDecl(C, ID, Size);
+  return new (Mem) NonTypeTemplateParmDecl(0, SourceLocation(),=20
+                                           SourceLocation(), 0, 0, 0,
+                                           QualType(), 0, 0, NumExpandedTy=
pes,
+                                           0);
+}
+
 SourceRange NonTypeTemplateParmDecl::getSourceRange() const {
   if (hasDefaultArgument() && !defaultArgumentWasInherited())
     return SourceRange(getOuterLocStart(),
@@ -537,6 +573,8 @@
 // TemplateTemplateParmDecl Method Implementations
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void TemplateTemplateParmDecl::anchor() { }
+
 TemplateTemplateParmDecl *
 TemplateTemplateParmDecl::Create(const ASTContext &C, DeclContext *DC,
                                  SourceLocation L, unsigned D, unsigned P,
@@ -546,6 +584,13 @@
                                           Params);
 }
=20
+TemplateTemplateParmDecl *
+TemplateTemplateParmDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(TemplateTemplatePar=
mDecl));
+  return new (Mem) TemplateTemplateParmDecl(0, SourceLocation(), 0, 0, fal=
se,
+                                            0, 0);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // TemplateArgumentList Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -582,6 +627,12 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// TemplateDecl Implementation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+void TemplateDecl::anchor() { }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ClassTemplateSpecializationDecl Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 ClassTemplateSpecializationDecl::
@@ -628,9 +679,11 @@
 }
=20
 ClassTemplateSpecializationDecl *
-ClassTemplateSpecializationDecl::Create(ASTContext &Context, EmptyShell Em=
pty) {
-  return
-    new (Context)ClassTemplateSpecializationDecl(ClassTemplateSpecializati=
on);
+ClassTemplateSpecializationDecl::CreateDeserialized(ASTContext &C,=20
+                                                    unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID,=20
+                                       sizeof(ClassTemplateSpecializationD=
ecl));
+  return new (Mem) ClassTemplateSpecializationDecl(ClassTemplateSpecializa=
tion);
 }
=20
 void
@@ -682,6 +735,8 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // ClassTemplatePartialSpecializationDecl Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+void ClassTemplatePartialSpecializationDecl::anchor() { }
+
 ClassTemplatePartialSpecializationDecl::
 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
                                        DeclContext *DC,
@@ -740,15 +795,19 @@
 }
=20
 ClassTemplatePartialSpecializationDecl *
-ClassTemplatePartialSpecializationDecl::Create(ASTContext &Context,
-                                               EmptyShell Empty) {
-  return new (Context)ClassTemplatePartialSpecializationDecl();
+ClassTemplatePartialSpecializationDecl::CreateDeserialized(ASTContext &C,
+                                                           unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID,=20
+                sizeof(ClassTemplatePartialSpecializationDecl));
+  return new (Mem) ClassTemplatePartialSpecializationDecl();
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // FriendTemplateDecl Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void FriendTemplateDecl::anchor() { }
+
 FriendTemplateDecl *FriendTemplateDecl::Create(ASTContext &Context,
                                                DeclContext *DC,
                                                SourceLocation L,
@@ -761,9 +820,10 @@
   return Result;
 }
=20
-FriendTemplateDecl *FriendTemplateDecl::Create(ASTContext &Context,
-                                               EmptyShell Empty) {
-  return new (Context) FriendTemplateDecl(Empty);
+FriendTemplateDecl *FriendTemplateDecl::CreateDeserialized(ASTContext &C,
+                                                           unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(FriendTemplateDecl)=
);
+  return new (Mem) FriendTemplateDecl(EmptyShell());
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -780,10 +840,11 @@
   return new (C) TypeAliasTemplateDecl(DC, L, Name, Params, Decl);
 }
=20
-TypeAliasTemplateDecl *TypeAliasTemplateDecl::Create(ASTContext &C,
-                                                     EmptyShell) {
-  return new (C) TypeAliasTemplateDecl(0, SourceLocation(), DeclarationNam=
e(),
-                                       0, 0);
+TypeAliasTemplateDecl *TypeAliasTemplateDecl::CreateDeserialized(ASTContex=
t &C,
+                                                                 unsigned =
ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID, sizeof(TypeAliasTemplateDe=
cl));
+  return new (Mem) TypeAliasTemplateDecl(0, SourceLocation(), DeclarationN=
ame(),
+                                         0, 0);
 }
=20
 void TypeAliasTemplateDecl::DeallocateCommon(void *Ptr) {
@@ -796,3 +857,16 @@
   return CommonPtr;
 }
=20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// ClassScopeFunctionSpecializationDecl Implementation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+void ClassScopeFunctionSpecializationDecl::anchor() { }
+
+ClassScopeFunctionSpecializationDecl *
+ClassScopeFunctionSpecializationDecl::CreateDeserialized(ASTContext &C,
+                                                         unsigned ID) {
+  void *Mem =3D AllocateDeserializedDecl(C, ID,=20
+                sizeof(ClassScopeFunctionSpecializationDecl));
+  return new (Mem) ClassScopeFunctionSpecializationDecl(0, SourceLocation(=
), 0);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DeclarationName.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DeclarationName.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DeclarationName.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -53,7 +53,7 @@
   void *FETokenInfo;
 };
=20
-/// CXXLiberalOperatorName - Contains the actual identifier that makes up =
the
+/// CXXLiteralOperatorName - Contains the actual identifier that makes up =
the
 /// name.
 ///
 /// This identifier is stored here rather than directly in DeclarationName=
 so as
@@ -64,6 +64,10 @@
 public:
   IdentifierInfo *ID;
=20
+  /// FETokenInfo - Extra information associated with this operator
+  /// name that can be used by the front end.
+  void *FETokenInfo;
+
   void Profile(llvm::FoldingSetNodeID &FSID) {
     FSID.AddPointer(ID);
   }
@@ -125,8 +129,8 @@
   case DeclarationName::CXXUsingDirective:
     return 0;
   }
-             =20
-  return 0;
+
+  llvm_unreachable("Invalid DeclarationName Kind!");
 }
=20
 } // end namespace clang
@@ -189,7 +193,6 @@
=20
       return ObjCMultiArgSelector;
     }
-    break;
   }
=20
   // Can't actually get here.
@@ -334,7 +337,7 @@
     return getAsCXXOperatorIdName()->FETokenInfo;
=20
   case CXXLiteralOperatorName:
-    return getCXXLiteralIdentifier()->getFETokenInfo<void>();
+    return getAsCXXLiteralOperatorIdName()->FETokenInfo;
=20
   default:
     llvm_unreachable("Declaration name has no FETokenInfo");
@@ -358,7 +361,7 @@
     break;
=20
   case CXXLiteralOperatorName:
-    getCXXLiteralIdentifier()->setFETokenInfo(T);
+    getAsCXXLiteralOperatorIdName()->FETokenInfo =3D T;
     break;
=20
   default:
@@ -472,6 +475,7 @@
   CXXLiteralOperatorIdName *LiteralName =3D new (Ctx) CXXLiteralOperatorId=
Name;
   LiteralName->ExtraKindOrNumArgs =3D DeclarationNameExtra::CXXLiteralOper=
ator;
   LiteralName->ID =3D II;
+  LiteralName->FETokenInfo =3D 0;
=20
   LiteralNames->InsertNode(LiteralName, InsertPos);
   return DeclarationName(LiteralName);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
DumpXML.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/DumpXML.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/DumpXML.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -39,8 +39,7 @@
 #include "clang/AST/TypeVisitor.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
=20
@@ -66,7 +65,6 @@
=20
   void dispatch(Decl *D) {
     switch (D->getKind()) {
-      default: llvm_unreachable("Decl that isn't part of DeclNodes.inc!");
 #define DECL(DERIVED, BASE) \
       case Decl::DERIVED: \
         DISPATCH(dispatch##DERIVED##DeclAttrs, DERIVED##Decl); \
@@ -121,7 +119,6 @@
=20
   void dispatch(Type *T) {
     switch (T->getTypeClass()) {
-      default: llvm_unreachable("Type that isn't part of TypeNodes.inc!");
 #define TYPE(DERIVED, BASE) \
       case Type::DERIVED: \
         DISPATCH(dispatch##DERIVED##TypeAttrs, DERIVED##Type); \
@@ -167,7 +164,6 @@
   }
=20
   llvm_unreachable("unknown type kind!");
-  return "unknown_type";
 }
=20
 struct XMLDumper : public XMLDeclVisitor<XMLDumper>,
@@ -227,7 +223,7 @@
   //---- General utilities -------------------------------------------//
=20
   void setPointer(StringRef prop, const void *p) {
-    llvm::SmallString<10> buffer;
+    SmallString<10> buffer;
     llvm::raw_svector_ostream os(buffer);
     os << p;
     os.flush();
@@ -243,7 +239,7 @@
   }
=20
   void setInteger(StringRef prop, unsigned n) {
-    llvm::SmallString<10> buffer;
+    SmallString<10> buffer;
     llvm::raw_svector_ostream os(buffer);
     os << n;
     os.flush();
@@ -324,7 +320,8 @@
       break;
        =20
     case TemplateArgument::Declaration: {
-      visitDeclRef(A.getAsDecl());
+      if (Decl *D =3D A.getAsDecl())
+        visitDeclRef(D);
       break;
     }
     case TemplateArgument::Integral: {
@@ -411,7 +408,7 @@
   }
=20
   template <class T> void visitRedeclarableAttrs(T *D) {
-    if (T *Prev =3D D->getPreviousDeclaration())
+    if (T *Prev =3D D->getPreviousDecl())
       setPointer("previous", Prev);
   }
=20
@@ -465,7 +462,13 @@
     if (D->getStorageClass() !=3D SC_None)
       set("storage",
           VarDecl::getStorageClassSpecifierString(D->getStorageClass()));
-    setFlag("directinit", D->hasCXXDirectInitializer());
+    StringRef initStyle =3D "";
+    switch (D->getInitStyle()) {
+    case VarDecl::CInit: initStyle =3D "c"; break;
+    case VarDecl::CallInit: initStyle =3D "call"; break;
+    case VarDecl::ListInit: initStyle =3D "list"; break;
+    }
+    set("initstyle", initStyle);
     setFlag("nrvo", D->isNRVOVariable());
     // TODO: instantiation, etc.
   }
@@ -495,6 +498,10 @@
     for (FunctionDecl::param_iterator
            I =3D D->param_begin(), E =3D D->param_end(); I !=3D E; ++I)
       dispatch(*I);
+    for (llvm::ArrayRef<NamedDecl*>::iterator
+           I =3D D->getDeclsInPrototypeScope().begin(), E =3D D->getDeclsI=
nPrototypeScope().end();
+         I !=3D E; ++I)
+      dispatch(*I);
     if (D->doesThisDeclarationHaveABody())
       dispatch(D->getBody());
   }
@@ -740,11 +747,6 @@
     visitDeclContext(D);
   }
=20
-  // ObjCClassDecl
-  void visitObjCClassDeclChildren(ObjCClassDecl *D) {
-    visitDeclRef(D->getForwardInterfaceDecl());
-  }
-
   // ObjCInterfaceDecl
   void visitCategoryList(ObjCCategoryDecl *D) {
     if (!D) return;
@@ -755,7 +757,7 @@
   }
   void visitObjCInterfaceDeclAttrs(ObjCInterfaceDecl *D) {
     setPointer("typeptr", D->getTypeForDecl());
-    setFlag("forward_decl", D->isForwardDecl());
+    setFlag("forward_decl", !D->isThisDeclarationADefinition());
     setFlag("implicit_interface", D->isImplicitInterfaceDecl());
   }
   void visitObjCInterfaceDeclChildren(ObjCInterfaceDecl *D) {
@@ -815,18 +817,11 @@
     }
   }
=20
-  // ObjCForwardProtocolDecl
-  void visitObjCForwardProtocolDeclChildren(ObjCForwardProtocolDecl *D) {
-    for (ObjCForwardProtocolDecl::protocol_iterator
-           I =3D D->protocol_begin(), E =3D D->protocol_end(); I !=3D E; +=
+I)
-      visitDeclRef(*I);
-  }
-
   // ObjCProtocolDecl
-  void visitObjCProtocolDeclAttrs(ObjCProtocolDecl *D) {
-    setFlag("forward_decl", D->isForwardDecl());
-  }
   void visitObjCProtocolDeclChildren(ObjCProtocolDecl *D) {
+    if (!D->isThisDeclarationADefinition())
+      return;
+   =20
     if (D->protocol_begin() !=3D D->protocol_end()) {
       TemporaryContainer C(*this, "protocols");
       for (ObjCInterfaceDecl::protocol_iterator
@@ -835,6 +830,9 @@
     }
   }
   void visitObjCProtocolDeclAsContext(ObjCProtocolDecl *D) {
+    if (!D->isThisDeclarationADefinition())
+      return;
+   =20
     visitDeclContext(D);
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
Expr.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/Expr.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/Expr.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -18,6 +18,7 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/EvaluatedExprVisitor.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/StmtVisitor.h"
 #include "clang/Lex/LiteralSupport.h"
@@ -29,6 +30,7 @@
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 #include <algorithm>
+#include <cstring>
 using namespace clang;
=20
 /// isKnownToHaveBooleanValue - Return true if this is an integer expressi=
on
@@ -92,6 +94,8 @@
=20
 // Amusing macro metaprogramming hack: check whether a class provides
 // a more specific implementation of getExprLoc().
+//
+// See also Stmt.cpp:{getLocStart(),getLocEnd()}.
 namespace {
   /// This implementation is used when a class provides a custom
   /// implementation of getExprLoc.
@@ -108,7 +112,7 @@
   template <class E>
   SourceLocation getExprLocImpl(const Expr *expr,
                                 SourceLocation (Expr::*v)() const) {
-    return static_cast<const E*>(expr)->getSourceRange().getBegin();
+    return static_cast<const E*>(expr)->getLocStart();
   }
 }
=20
@@ -123,7 +127,6 @@
 #include "clang/AST/StmtNodes.inc"
   }
   llvm_unreachable("unknown statement kind");
-  return SourceLocation();
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -133,7 +136,7 @@
 /// \brief Compute the type-, value-, and instantiation-dependence of a=20
 /// declaration reference
 /// based on the declaration being referenced.
-static void computeDeclRefDependence(NamedDecl *D, QualType T,
+static void computeDeclRefDependence(ASTContext &Ctx, NamedDecl *D, QualTy=
pe T,
                                      bool &TypeDependent,
                                      bool &ValueDependent,
                                      bool &InstantiationDependent) {
@@ -184,21 +187,29 @@
  =20
   //  (VD) - a constant with integral or enumeration type and is
   //         initialized with an expression that is value-dependent.
+  //  (VD) - a constant with literal type and is initialized with an
+  //         expression that is value-dependent [C++11].
+  //  (VD) - FIXME: Missing from the standard:
+  //       -  an entity with reference type and is initialized with an
+  //          expression that is value-dependent [C++11]
   if (VarDecl *Var =3D dyn_cast<VarDecl>(D)) {
-    if (Var->getType()->isIntegralOrEnumerationType() &&
-        Var->getType().getCVRQualifiers() =3D=3D Qualifiers::Const) {
+    if ((Ctx.getLangOpts().CPlusPlus0x ?
+           Var->getType()->isLiteralType() :
+           Var->getType()->isIntegralOrEnumerationType()) &&
+        (Var->getType().getCVRQualifiers() =3D=3D Qualifiers::Const ||
+         Var->getType()->isReferenceType())) {
       if (const Expr *Init =3D Var->getAnyInitializer())
         if (Init->isValueDependent()) {
           ValueDependent =3D true;
           InstantiationDependent =3D true;
         }
-    }=20
-   =20
+    }
+
     // (VD) - FIXME: Missing from the standard:=20
     //      -  a member function or a static data member of the current=20
     //         instantiation
-    else if (Var->isStaticDataMember() &&=20
-             Var->getDeclContext()->isDependentContext()) {
+    if (Var->isStaticDataMember() &&=20
+        Var->getDeclContext()->isDependentContext()) {
       ValueDependent =3D true;
       InstantiationDependent =3D true;
     }
@@ -212,16 +223,15 @@
   if (isa<CXXMethodDecl>(D) && D->getDeclContext()->isDependentContext()) {
     ValueDependent =3D true;
     InstantiationDependent =3D true;
-    return;
-  } =20
+  }
 }
=20
-void DeclRefExpr::computeDependence() {
+void DeclRefExpr::computeDependence(ASTContext &Ctx) {
   bool TypeDependent =3D false;
   bool ValueDependent =3D false;
   bool InstantiationDependent =3D false;
-  computeDeclRefDependence(getDecl(), getType(), TypeDependent, ValueDepen=
dent,
-                           InstantiationDependent);
+  computeDeclRefDependence(Ctx, getDecl(), getType(), TypeDependent,
+                           ValueDependent, InstantiationDependent);
  =20
   // (TD) C++ [temp.dep.expr]p3:
   //   An id-expression is type-dependent if it contains:
@@ -250,8 +260,11 @@
     ExprBits.ContainsUnexpandedParameterPack =3D true;
 }
=20
-DeclRefExpr::DeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
-                         ValueDecl *D, const DeclarationNameInfo &NameInfo,
+DeclRefExpr::DeclRefExpr(ASTContext &Ctx,
+                         NestedNameSpecifierLoc QualifierLoc,
+                         SourceLocation TemplateKWLoc,
+                         ValueDecl *D, bool RefersToEnclosingLocal,
+                         const DeclarationNameInfo &NameInfo,
                          NamedDecl *FoundD,
                          const TemplateArgumentListInfo *TemplateArgs,
                          QualType T, ExprValueKind VK)
@@ -263,38 +276,48 @@
   DeclRefExprBits.HasFoundDecl =3D FoundD ? 1 : 0;
   if (FoundD)
     getInternalFoundDecl() =3D FoundD;
-  DeclRefExprBits.HasExplicitTemplateArgs =3D TemplateArgs ? 1 : 0;
+  DeclRefExprBits.HasTemplateKWAndArgsInfo
+    =3D (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
+  DeclRefExprBits.RefersToEnclosingLocal =3D RefersToEnclosingLocal;
   if (TemplateArgs) {
     bool Dependent =3D false;
     bool InstantiationDependent =3D false;
     bool ContainsUnexpandedParameterPack =3D false;
-    getExplicitTemplateArgs().initializeFrom(*TemplateArgs, Dependent,
-                                             InstantiationDependent,
-                                             ContainsUnexpandedParameterPa=
ck);
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArg=
s,
+                                               Dependent,
+                                               InstantiationDependent,
+                                               ContainsUnexpandedParameter=
Pack);
     if (InstantiationDependent)
       setInstantiationDependent(true);
+  } else if (TemplateKWLoc.isValid()) {
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
   }
   DeclRefExprBits.HadMultipleCandidates =3D 0;
=20
-  computeDependence();
+  computeDependence(Ctx);
 }
=20
 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
                                  NestedNameSpecifierLoc QualifierLoc,
+                                 SourceLocation TemplateKWLoc,
                                  ValueDecl *D,
+                                 bool RefersToEnclosingLocal,
                                  SourceLocation NameLoc,
                                  QualType T,
                                  ExprValueKind VK,
                                  NamedDecl *FoundD,
                                  const TemplateArgumentListInfo *TemplateA=
rgs) {
-  return Create(Context, QualifierLoc, D,
+  return Create(Context, QualifierLoc, TemplateKWLoc, D,
+                RefersToEnclosingLocal,
                 DeclarationNameInfo(D->getDeclName(), NameLoc),
                 T, VK, FoundD, TemplateArgs);
 }
=20
 DeclRefExpr *DeclRefExpr::Create(ASTContext &Context,
                                  NestedNameSpecifierLoc QualifierLoc,
+                                 SourceLocation TemplateKWLoc,
                                  ValueDecl *D,
+                                 bool RefersToEnclosingLocal,
                                  const DeclarationNameInfo &NameInfo,
                                  QualType T,
                                  ExprValueKind VK,
@@ -310,25 +333,28 @@
   if (FoundD)
     Size +=3D sizeof(NamedDecl *);
   if (TemplateArgs)
-    Size +=3D ASTTemplateArgumentListInfo::sizeFor(*TemplateArgs);
+    Size +=3D ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
+  else if (TemplateKWLoc.isValid())
+    Size +=3D ASTTemplateKWAndArgsInfo::sizeFor(0);
=20
   void *Mem =3D Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
-  return new (Mem) DeclRefExpr(QualifierLoc, D, NameInfo, FoundD, Template=
Args,
-                               T, VK);
+  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
+                               RefersToEnclosingLocal,
+                               NameInfo, FoundD, TemplateArgs, T, VK);
 }
=20
 DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext &Context,
                                       bool HasQualifier,
                                       bool HasFoundDecl,
-                                      bool HasExplicitTemplateArgs,
+                                      bool HasTemplateKWAndArgsInfo,
                                       unsigned NumTemplateArgs) {
   std::size_t Size =3D sizeof(DeclRefExpr);
   if (HasQualifier)
     Size +=3D sizeof(NestedNameSpecifierLoc);
   if (HasFoundDecl)
     Size +=3D sizeof(NamedDecl *);
-  if (HasExplicitTemplateArgs)
-    Size +=3D ASTTemplateArgumentListInfo::sizeFor(NumTemplateArgs);
+  if (HasTemplateKWAndArgsInfo)
+    Size +=3D ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
=20
   void *Mem =3D Context.Allocate(Size, llvm::alignOf<DeclRefExpr>());
   return new (Mem) DeclRefExpr(EmptyShell());
@@ -342,6 +368,16 @@
     R.setEnd(getRAngleLoc());
   return R;
 }
+SourceLocation DeclRefExpr::getLocStart() const {
+  if (hasQualifier())
+    return getQualifierLoc().getBeginLoc();
+  return getNameInfo().getLocStart();
+}
+SourceLocation DeclRefExpr::getLocEnd() const {
+  if (hasExplicitTemplateArgs())
+    return getRAngleLoc();
+  return getNameInfo().getLocEnd();
+}
=20
 // FIXME: Maybe this should use DeclPrinter with a special "print predefin=
ed
 // expr" policy instead.
@@ -352,7 +388,7 @@
     if (IT !=3D PrettyFunction && IT !=3D PrettyFunctionNoVirtual)
       return FD->getNameAsString();
=20
-    llvm::SmallString<256> Name;
+    SmallString<256> Name;
     llvm::raw_svector_ostream Out(Name);
=20
     if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(FD)) {
@@ -362,22 +398,24 @@
         Out << "static ";
     }
=20
-    PrintingPolicy Policy(Context.getLangOptions());
-
+    PrintingPolicy Policy(Context.getLangOpts());
     std::string Proto =3D FD->getQualifiedNameAsString(Policy);
-
-    const FunctionType *AFT =3D FD->getType()->getAs<FunctionType>();
+    llvm::raw_string_ostream POut(Proto);
+
+    const FunctionDecl *Decl =3D FD;
+    if (const FunctionDecl* Pattern =3D FD->getTemplateInstantiationPatter=
n())
+      Decl =3D Pattern;
+    const FunctionType *AFT =3D Decl->getType()->getAs<FunctionType>();
     const FunctionProtoType *FT =3D 0;
     if (FD->hasWrittenPrototype())
       FT =3D dyn_cast<FunctionProtoType>(AFT);
=20
-    Proto +=3D "(";
+    POut << "(";
     if (FT) {
-      llvm::raw_string_ostream POut(Proto);
-      for (unsigned i =3D 0, e =3D FD->getNumParams(); i !=3D e; ++i) {
+      for (unsigned i =3D 0, e =3D Decl->getNumParams(); i !=3D e; ++i) {
         if (i) POut << ", ";
         std::string Param;
-        FD->getParamDecl(i)->getType().getAsStringInternal(Param, Policy);
+        Decl->getParamDecl(i)->getType().getAsStringInternal(Param, Policy=
);
         POut << Param;
       }
=20
@@ -386,16 +424,74 @@
         POut << "...";
       }
     }
-    Proto +=3D ")";
+    POut << ")";
=20
     if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(FD)) {
       Qualifiers ThisQuals =3D Qualifiers::fromCVRMask(MD->getTypeQualifie=
rs());
       if (ThisQuals.hasConst())
-        Proto +=3D " const";
+        POut << " const";
       if (ThisQuals.hasVolatile())
-        Proto +=3D " volatile";
+        POut << " volatile";
+      RefQualifierKind Ref =3D MD->getRefQualifier();
+      if (Ref =3D=3D RQ_LValue)
+        POut << " &";
+      else if (Ref =3D=3D RQ_RValue)
+        POut << " &&";
     }
=20
+    typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsT=
y;
+    SpecsTy Specs;
+    const DeclContext *Ctx =3D FD->getDeclContext();
+    while (Ctx && isa<NamedDecl>(Ctx)) {
+      const ClassTemplateSpecializationDecl *Spec
+                               =3D dyn_cast<ClassTemplateSpecializationDec=
l>(Ctx);
+      if (Spec && !Spec->isExplicitSpecialization())
+        Specs.push_back(Spec);
+      Ctx =3D Ctx->getParent();
+    }
+
+    std::string TemplateParams;
+    llvm::raw_string_ostream TOut(TemplateParams);
+    for (SpecsTy::reverse_iterator I =3D Specs.rbegin(), E =3D Specs.rend(=
);
+         I !=3D E; ++I) {
+      const TemplateParameterList *Params=20
+                  =3D (*I)->getSpecializedTemplate()->getTemplateParameter=
s();
+      const TemplateArgumentList &Args =3D (*I)->getTemplateArgs();
+      assert(Params->size() =3D=3D Args.size());
+      for (unsigned i =3D 0, numParams =3D Params->size(); i !=3D numParam=
s; ++i) {
+        StringRef Param =3D Params->getParam(i)->getName();
+        if (Param.empty()) continue;
+        TOut << Param << " =3D ";
+        Args.get(i).print(Policy, TOut);
+        TOut << ", ";
+      }
+    }
+
+    FunctionTemplateSpecializationInfo *FSI=20
+                                          =3D FD->getTemplateSpecializatio=
nInfo();
+    if (FSI && !FSI->isExplicitSpecialization()) {
+      const TemplateParameterList* Params=20
+                                  =3D FSI->getTemplate()->getTemplateParam=
eters();
+      const TemplateArgumentList* Args =3D FSI->TemplateArguments;
+      assert(Params->size() =3D=3D Args->size());
+      for (unsigned i =3D 0, e =3D Params->size(); i !=3D e; ++i) {
+        StringRef Param =3D Params->getParam(i)->getName();
+        if (Param.empty()) continue;
+        TOut << Param << " =3D ";
+        Args->get(i).print(Policy, TOut);
+        TOut << ", ";
+      }
+    }
+
+    TOut.flush();
+    if (!TemplateParams.empty()) {
+      // remove the trailing comma and space
+      TemplateParams.resize(TemplateParams.size() - 2);
+      POut << " [" << TemplateParams << "]";
+    }
+
+    POut.flush();
+
     if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
       AFT->getResultType().getAsStringInternal(Proto, Policy);
=20
@@ -405,7 +501,7 @@
     return Name.str().str();
   }
   if (const ObjCMethodDecl *MD =3D dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
-    llvm::SmallString<256> Name;
+    SmallString<256> Name;
     llvm::raw_svector_ostream Out(Name);
     Out << (MD->isInstanceMethod() ? '-' : '+');
     Out << '[';
@@ -417,7 +513,7 @@
=20
     if (const ObjCCategoryImplDecl *CID =3D
         dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
-      Out << '(' << CID << ')';
+      Out << '(' << *CID << ')';
=20
     Out <<  ' ';
     Out << MD->getSelector().getAsString();
@@ -468,7 +564,7 @@
=20
 FloatingLiteral *
 FloatingLiteral::Create(ASTContext &C, EmptyShell Empty) {
-  return new (C) FloatingLiteral(Empty);
+  return new (C) FloatingLiteral(C, Empty);
 }
=20
 /// getValueAsApproximateDouble - This returns the value as an inaccurate
@@ -482,6 +578,30 @@
   return V.convertToDouble();
 }
=20
+int StringLiteral::mapCharByteWidth(TargetInfo const &target,StringKind k)=
 {
+  int CharByteWidth =3D 0;
+  switch(k) {
+    case Ascii:
+    case UTF8:
+      CharByteWidth =3D target.getCharWidth();
+      break;
+    case Wide:
+      CharByteWidth =3D target.getWCharWidth();
+      break;
+    case UTF16:
+      CharByteWidth =3D target.getChar16Width();
+      break;
+    case UTF32:
+      CharByteWidth =3D target.getChar32Width();
+      break;
+  }
+  assert((CharByteWidth & 7) =3D=3D 0 && "Assumes character size is byte m=
ultiple");
+  CharByteWidth /=3D 8;
+  assert((CharByteWidth=3D=3D1 || CharByteWidth=3D=3D2 || CharByteWidth=3D=
=3D4)
+         && "character byte widths supported are 1, 2, and 4 only");
+  return CharByteWidth;
+}
+
 StringLiteral *StringLiteral::Create(ASTContext &C, StringRef Str,
                                      StringKind Kind, bool Pascal, QualTyp=
e Ty,
                                      const SourceLocation *Loc,
@@ -494,12 +614,8 @@
   StringLiteral *SL =3D new (Mem) StringLiteral(Ty);
=20
   // OPTIMIZE: could allocate this appended to the StringLiteral.
-  char *AStrData =3D new (C, 1) char[Str.size()];
-  memcpy(AStrData, Str.data(), Str.size());
-  SL->StrData =3D AStrData;
-  SL->ByteLength =3D Str.size();
-  SL->Kind =3D Kind;
-  SL->IsPascal =3D Pascal;
+  SL->setString(C,Str,Kind,Pascal);
+
   SL->TokLocs[0] =3D Loc[0];
   SL->NumConcatenated =3D NumStrs;
=20
@@ -513,17 +629,46 @@
                          sizeof(SourceLocation)*(NumStrs-1),
                          llvm::alignOf<StringLiteral>());
   StringLiteral *SL =3D new (Mem) StringLiteral(QualType());
-  SL->StrData =3D 0;
-  SL->ByteLength =3D 0;
+  SL->CharByteWidth =3D 0;
+  SL->Length =3D 0;
   SL->NumConcatenated =3D NumStrs;
   return SL;
 }
=20
-void StringLiteral::setString(ASTContext &C, StringRef Str) {
-  char *AStrData =3D new (C, 1) char[Str.size()];
-  memcpy(AStrData, Str.data(), Str.size());
-  StrData =3D AStrData;
-  ByteLength =3D Str.size();
+void StringLiteral::setString(ASTContext &C, StringRef Str,
+                              StringKind Kind, bool IsPascal) {
+  //FIXME: we assume that the string data comes from a target that uses th=
e same
+  // code unit size and endianess for the type of string.
+  this->Kind =3D Kind;
+  this->IsPascal =3D IsPascal;
+ =20
+  CharByteWidth =3D mapCharByteWidth(C.getTargetInfo(),Kind);
+  assert((Str.size()%CharByteWidth =3D=3D 0)
+         && "size of data must be multiple of CharByteWidth");
+  Length =3D Str.size()/CharByteWidth;
+
+  switch(CharByteWidth) {
+    case 1: {
+      char *AStrData =3D new (C) char[Length];
+      std::memcpy(AStrData,Str.data(),Str.size());
+      StrData.asChar =3D AStrData;
+      break;
+    }
+    case 2: {
+      uint16_t *AStrData =3D new (C) uint16_t[Length];
+      std::memcpy(AStrData,Str.data(),Str.size());
+      StrData.asUInt16 =3D AStrData;
+      break;
+    }
+    case 4: {
+      uint32_t *AStrData =3D new (C) uint32_t[Length];
+      std::memcpy(AStrData,Str.data(),Str.size());
+      StrData.asUInt32 =3D AStrData;
+      break;
+    }
+    default:
+      assert(false && "unsupported CharByteWidth");
+  }
 }
=20
 /// getLocationOfByte - Return a source location that points to the specif=
ied
@@ -596,7 +741,6 @@
 /// corresponds to, e.g. "sizeof" or "[pre]++".
 const char *UnaryOperator::getOpcodeStr(Opcode Op) {
   switch (Op) {
-  default: llvm_unreachable("Unknown unary operator");
   case UO_PostInc: return "++";
   case UO_PostDec: return "--";
   case UO_PreInc:  return "++";
@@ -611,6 +755,7 @@
   case UO_Imag:    return "__imag";
   case UO_Extension: return "__extension__";
   }
+  llvm_unreachable("Unknown unary operator");
 }
=20
 UnaryOperatorKind
@@ -778,7 +923,7 @@
=20
 /// isBuiltinCall - If this is a call to a builtin, return the builtin ID.=
  If
 /// not, return 0.
-unsigned CallExpr::isBuiltinCall(const ASTContext &Context) const {
+unsigned CallExpr::isBuiltinCall() const {
   // All simple function calls (e.g. func()) are implicitly cast to pointe=
r to
   // function. As a result, we try and obtain the DeclRefExpr from the
   // ImplicitCastExpr.
@@ -826,6 +971,24 @@
     end =3D getArg(getNumArgs() - 1)->getLocEnd();
   return SourceRange(begin, end);
 }
+SourceLocation CallExpr::getLocStart() const {
+  if (isa<CXXOperatorCallExpr>(this))
+    return cast<CXXOperatorCallExpr>(this)->getSourceRange().getBegin();
+
+  SourceLocation begin =3D getCallee()->getLocStart();
+  if (begin.isInvalid() && getNumArgs() > 0)
+    begin =3D getArg(0)->getLocStart();
+  return begin;
+}
+SourceLocation CallExpr::getLocEnd() const {
+  if (isa<CXXOperatorCallExpr>(this))
+    return cast<CXXOperatorCallExpr>(this)->getSourceRange().getEnd();
+
+  SourceLocation end =3D getRParenLoc();
+  if (end.isInvalid() && getNumArgs() > 0)
+    end =3D getArg(getNumArgs() - 1)->getLocEnd();
+  return end;
+}
=20
 OffsetOfExpr *OffsetOfExpr::Create(ASTContext &C, QualType type,=20
                                    SourceLocation OperatorLoc,
@@ -886,6 +1049,7 @@
=20
 MemberExpr *MemberExpr::Create(ASTContext &C, Expr *base, bool isarrow,
                                NestedNameSpecifierLoc QualifierLoc,
+                               SourceLocation TemplateKWLoc,
                                ValueDecl *memberdecl,
                                DeclAccessPair founddecl,
                                DeclarationNameInfo nameinfo,
@@ -902,7 +1066,9 @@
     Size +=3D sizeof(MemberNameQualifier);
=20
   if (targs)
-    Size +=3D ASTTemplateArgumentListInfo::sizeFor(*targs);
+    Size +=3D ASTTemplateKWAndArgsInfo::sizeFor(targs->size());
+  else if (TemplateKWLoc.isValid())
+    Size +=3D ASTTemplateKWAndArgsInfo::sizeFor(0);
=20
   void *Mem =3D C.Allocate(Size, llvm::alignOf<MemberExpr>());
   MemberExpr *E =3D new (Mem) MemberExpr(base, isarrow, memberdecl, namein=
fo,
@@ -926,41 +1092,46 @@
     NQ->FoundDecl =3D founddecl;
   }
=20
+  E->HasTemplateKWAndArgsInfo =3D (targs || TemplateKWLoc.isValid());
+
   if (targs) {
     bool Dependent =3D false;
     bool InstantiationDependent =3D false;
     bool ContainsUnexpandedParameterPack =3D false;
-    E->HasExplicitTemplateArgumentList =3D true;
-    E->getExplicitTemplateArgs().initializeFrom(*targs, Dependent,
-                                                InstantiationDependent,
-                                              ContainsUnexpandedParameterP=
ack);
+    E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *targs,
+                                                  Dependent,
+                                                  InstantiationDependent,
+                                             ContainsUnexpandedParameterPa=
ck);
     if (InstantiationDependent)
       E->setInstantiationDependent(true);
+  } else if (TemplateKWLoc.isValid()) {
+    E->getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
   }
=20
   return E;
 }
=20
 SourceRange MemberExpr::getSourceRange() const {
-  SourceLocation StartLoc;
+  return SourceRange(getLocStart(), getLocEnd());
+}
+SourceLocation MemberExpr::getLocStart() const {
   if (isImplicitAccess()) {
     if (hasQualifier())
-      StartLoc =3D getQualifierLoc().getBeginLoc();
-    else
-      StartLoc =3D MemberLoc;
-  } else {
-    // FIXME: We don't want this to happen. Rather, we should be able to
-    // detect all kinds of implicit accesses more cleanly.
-    StartLoc =3D getBase()->getLocStart();
-    if (StartLoc.isInvalid())
-      StartLoc =3D MemberLoc;
+      return getQualifierLoc().getBeginLoc();
+    return MemberLoc;
   }
- =20
-  SourceLocation EndLoc =3D=20
-    HasExplicitTemplateArgumentList? getRAngleLoc()=20
-                                   : getMemberNameInfo().getEndLoc();
- =20
-  return SourceRange(StartLoc, EndLoc);
+
+  // FIXME: We don't want this to happen. Rather, we should be able to
+  // detect all kinds of implicit accesses more cleanly.
+  SourceLocation BaseStartLoc =3D getBase()->getLocStart();
+  if (BaseStartLoc.isValid())
+    return BaseStartLoc;
+  return MemberLoc;
+}
+SourceLocation MemberExpr::getLocEnd() const {
+  if (hasExplicitTemplateArgs())
+    return getRAngleLoc();
+  return getMemberNameInfo().getEndLoc();
 }
=20
 void CastExpr::CheckCastConsistency() const {
@@ -983,6 +1154,11 @@
     assert(getSubExpr()->getType()->isBlockPointerType());
     goto CheckNoBasePath;
=20
+  case CK_ReinterpretMemberPointer:
+    assert(getType()->isMemberPointerType());
+    assert(getSubExpr()->getType()->isMemberPointerType());
+    goto CheckNoBasePath;
+
   case CK_BitCast:
     // Arbitrary casts to C pointer types count as bitcasts.
     // Otherwise, we should only have block and ObjC pointer casts
@@ -1001,6 +1177,11 @@
            !getSubExpr()->getType()->isBlockPointerType());
     goto CheckNoBasePath;
=20
+  case CK_CopyAndAutoreleaseBlockObject:
+    assert(getType()->isBlockPointerType());
+    assert(getSubExpr()->getType()->isBlockPointerType());
+    goto CheckNoBasePath;
+     =20
   // These should not have an inheritance path.
   case CK_Dynamic:
   case CK_ToUnion:
@@ -1035,8 +1216,9 @@
=20
   case CK_Dependent:
   case CK_LValueToRValue:
-  case CK_GetObjCProperty:
   case CK_NoOp:
+  case CK_AtomicToNonAtomic:
+  case CK_NonAtomicToAtomic:
   case CK_PointerToBoolean:
   case CK_IntegralToBoolean:
   case CK_FloatingToBoolean:
@@ -1061,8 +1243,6 @@
     return "LValueBitCast";
   case CK_LValueToRValue:
     return "LValueToRValue";
-  case CK_GetObjCProperty:
-    return "GetObjCProperty";
   case CK_NoOp:
     return "NoOp";
   case CK_BaseToDerived:
@@ -1087,6 +1267,8 @@
     return "BaseToDerivedMemberPointer";
   case CK_DerivedToBaseMemberPointer:
     return "DerivedToBaseMemberPointer";
+  case CK_ReinterpretMemberPointer:
+    return "ReinterpretMemberPointer";
   case CK_UserDefinedConversion:
     return "UserDefinedConversion";
   case CK_ConstructorConversion:
@@ -1151,10 +1333,15 @@
     return "ARCReclaimReturnedObject";
   case CK_ARCExtendBlockObject:
     return "ARCCExtendBlockObject";
+  case CK_AtomicToNonAtomic:
+    return "AtomicToNonAtomic";
+  case CK_NonAtomicToAtomic:
+    return "NonAtomicToAtomic";
+  case CK_CopyAndAutoreleaseBlockObject:
+    return "CopyAndAutoreleaseBlockObject";
   }
=20
   llvm_unreachable("Unhandled cast kind!");
-  return 0;
 }
=20
 Expr *CastExpr::getSubExprAsWritten() {
@@ -1196,7 +1383,6 @@
 #include "clang/AST/StmtNodes.inc"
   default:
     llvm_unreachable("non-cast expressions not possible here");
-    return 0;
   }
 }
=20
@@ -1284,7 +1470,7 @@
   case BO_Comma:     return ",";
   }
=20
-  return "";
+  llvm_unreachable("Invalid OpCode!");
 }
=20
 BinaryOperatorKind
@@ -1355,9 +1541,10 @@
   : Expr(InitListExprClass, QualType(), VK_RValue, OK_Ordinary, false, fal=
se,
          false, false),
     InitExprs(C, numInits),
-    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0),
-    HadArrayRangeDesignator(false)=20
-{     =20
+    LBraceLoc(lbraceloc), RBraceLoc(rbraceloc), SyntacticForm(0)
+{
+  sawArrayRangeDesignator(false);
+  setInitializesStdInitializerList(false);
   for (unsigned I =3D 0; I !=3D numInits; ++I) {
     if (initExprs[I]->isTypeDependent())
       ExprBits.TypeDependent =3D true;
@@ -1394,6 +1581,7 @@
 }
=20
 void InitListExpr::setArrayFiller(Expr *filler) {
+  assert(!hasArrayFiller() && "Filler already set!");
   ArrayFillerOrUnionFieldInit =3D filler;
   // Fill out any "holes" in the array due to designated initializers.
   Expr **inits =3D getInits();
@@ -1433,9 +1621,10 @@
=20
 /// getFunctionType - Return the underlying function type for this block.
 ///
-const FunctionType *BlockExpr::getFunctionType() const {
-  return getType()->getAs<BlockPointerType>()->
-                    getPointeeType()->getAs<FunctionType>();
+const FunctionProtoType *BlockExpr::getFunctionType() const {
+  // The block pointer is never sugared, but the function type might be.
+  return cast<BlockPointerType>(getType())
+           ->getPointeeType()->castAs<FunctionProtoType>();
 }
=20
 SourceLocation BlockExpr::getCaretLocation() const {
@@ -1591,7 +1780,8 @@
     // Fallthrough for generic call handling.
   }
   case CallExprClass:
-  case CXXMemberCallExprClass: {
+  case CXXMemberCallExprClass:
+  case UserDefinedLiteralClass: {
     // If this is a direct call, get the callee.
     const CallExpr *CE =3D cast<CallExpr>(this);
     if (const Decl *FD =3D CE->getCalleeDecl()) {
@@ -1620,7 +1810,7 @@
=20
   case ObjCMessageExprClass: {
     const ObjCMessageExpr *ME =3D cast<ObjCMessageExpr>(this);
-    if (Ctx.getLangOptions().ObjCAutoRefCount &&
+    if (Ctx.getLangOpts().ObjCAutoRefCount &&
         ME->isInstanceMessage() &&
         !ME->getType()->isVoidType() &&
         ME->getSelector().getIdentifierInfoForSlot(0) &&
@@ -1644,6 +1834,19 @@
     R1 =3D getSourceRange();
     return true;
=20
+  case PseudoObjectExprClass: {
+    const PseudoObjectExpr *PO =3D cast<PseudoObjectExpr>(this);
+
+    // Only complain about things that have the form of a getter.
+    if (isa<UnaryOperator>(PO->getSyntacticForm()) ||
+        isa<BinaryOperator>(PO->getSyntacticForm()))
+      return false;
+
+    Loc =3D getExprLoc();
+    R1 =3D getSourceRange();
+    return true;
+  }
+
   case StmtExprClass: {
     // Statement exprs don't logically have side effects themselves, but a=
re
     // sometimes used in macros in ways that give them a type that is unus=
ed.
@@ -1730,14 +1933,8 @@
                                                       ->isOBJCGCCandidate(=
Ctx);
   case CStyleCastExprClass:
     return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
-  case BlockDeclRefExprClass:
   case DeclRefExprClass: {
-   =20
-    const Decl *D;
-    if (const BlockDeclRefExpr *BDRE =3D dyn_cast<BlockDeclRefExpr>(E))
-        D =3D BDRE->getDecl();
-    else=20
-        D =3D cast<DeclRefExpr>(E)->getDecl();
+    const Decl *D =3D cast<DeclRefExpr>(E)->getDecl();
        =20
     if (const VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
       if (VD->hasGlobalStorage())
@@ -1766,7 +1963,7 @@
 }
=20
 QualType Expr::findBoundMemberType(const Expr *expr) {
-  assert(expr->getType()->isSpecificPlaceholderType(BuiltinType::BoundMemb=
er));
+  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
=20
   // Bound member expressions are always one of these possibilities:
   //   x->m      x.m      x->*y      x.*y
@@ -1910,8 +2107,9 @@
     //     pointer, or member function pointer that does not have a non-th=
rowing
     //     exception-specification
   case CallExprClass:
+  case CXXMemberCallExprClass:
   case CXXOperatorCallExprClass:
-  case CXXMemberCallExprClass: {
+  case UserDefinedLiteralClass: {
     const CallExpr *CE =3D cast<CallExpr>(this);
     CanThrowResult CT;
     if (isTypeDependent())
@@ -1934,15 +2132,22 @@
     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
   }
=20
+  case LambdaExprClass: {
+    const LambdaExpr *Lambda =3D cast<LambdaExpr>(this);
+    CanThrowResult CT =3D Expr::CT_Cannot;
+    for (LambdaExpr::capture_init_iterator Cap =3D Lambda->capture_init_be=
gin(),
+                                        CapEnd =3D Lambda->capture_init_en=
d();
+         Cap !=3D CapEnd; ++Cap)
+      CT =3D MergeCanThrow(CT, (*Cap)->CanThrow(C));
+    return CT;
+  }
+
   case CXXNewExprClass: {
     CanThrowResult CT;
     if (isTypeDependent())
       CT =3D CT_Dependent;
     else
-      CT =3D MergeCanThrow(
-        CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNew()),
-        CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getConstructor(),
-                       /*NullThrows*/false));
+      CT =3D CanCalleeThrow(C, this, cast<CXXNewExpr>(this)->getOperatorNe=
w());
     if (CT =3D=3D CT_Can)
       return CT;
     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
@@ -1979,38 +2184,47 @@
     // specs.
   case ObjCMessageExprClass:
   case ObjCPropertyRefExprClass:
+  case ObjCSubscriptRefExprClass:
+    return CT_Can;
+
+    // All the ObjC literals that are implemented as calls are
+    // potentially throwing unless we decide to close off that
+    // possibility.
+  case ObjCArrayLiteralClass:
+  case ObjCDictionaryLiteralClass:
+  case ObjCNumericLiteralClass:
     return CT_Can;
=20
     // Many other things have subexpressions, so we have to test those.
     // Some are simple:
-  case ParenExprClass:
-  case MemberExprClass:
-  case CXXReinterpretCastExprClass:
-  case CXXConstCastExprClass:
   case ConditionalOperatorClass:
   case CompoundLiteralExprClass:
+  case CXXConstCastExprClass:
+  case CXXDefaultArgExprClass:
+  case CXXReinterpretCastExprClass:
+  case DesignatedInitExprClass:
+  case ExprWithCleanupsClass:
   case ExtVectorElementExprClass:
   case InitListExprClass:
-  case DesignatedInitExprClass:
+  case MemberExprClass:
+  case ObjCIsaExprClass:
+  case ObjCIvarRefExprClass:
+  case ParenExprClass:
   case ParenListExprClass:
+  case ShuffleVectorExprClass:
   case VAArgExprClass:
-  case CXXDefaultArgExprClass:
-  case ExprWithCleanupsClass:
-  case ObjCIvarRefExprClass:
-  case ObjCIsaExprClass:
-  case ShuffleVectorExprClass:
     return CanSubExprsThrow(C, this);
=20
     // Some might be dependent for other reasons.
-  case UnaryOperatorClass:
   case ArraySubscriptExprClass:
-  case ImplicitCastExprClass:
+  case BinaryOperatorClass:
+  case CompoundAssignOperatorClass:
   case CStyleCastExprClass:
   case CXXStaticCastExprClass:
   case CXXFunctionalCastExprClass:
-  case BinaryOperatorClass:
-  case CompoundAssignOperatorClass:
-  case MaterializeTemporaryExprClass: {
+  case ImplicitCastExprClass:
+  case MaterializeTemporaryExprClass:
+  case UnaryOperatorClass: {
     CanThrowResult CT =3D isTypeDependent() ? CT_Dependent : CT_Cannot;
     return MergeCanThrow(CT, CanSubExprsThrow(C, this));
   }
@@ -2030,16 +2244,71 @@
     return cast<GenericSelectionExpr>(this)->getResultExpr()->CanThrow(C);
=20
     // Some expressions are always dependent.
+  case CXXDependentScopeMemberExprClass:
+  case CXXUnresolvedConstructExprClass:
   case DependentScopeDeclRefExprClass:
-  case CXXUnresolvedConstructExprClass:
-  case CXXDependentScopeMemberExprClass:
     return CT_Dependent;
=20
-  default:
-    // All other expressions don't have subexpressions, or else they are
-    // unevaluated.
+  case AtomicExprClass:
+  case AsTypeExprClass:
+  case BinaryConditionalOperatorClass:
+  case BlockExprClass:
+  case CUDAKernelCallExprClass:
+  case DeclRefExprClass:
+  case ObjCBridgedCastExprClass:
+  case ObjCIndirectCopyRestoreExprClass:
+  case ObjCProtocolExprClass:
+  case ObjCSelectorExprClass:
+  case OffsetOfExprClass:
+  case PackExpansionExprClass:
+  case PseudoObjectExprClass:
+  case SubstNonTypeTemplateParmExprClass:
+  case SubstNonTypeTemplateParmPackExprClass:
+  case UnaryExprOrTypeTraitExprClass:
+  case UnresolvedLookupExprClass:
+  case UnresolvedMemberExprClass:
+    // FIXME: Can any of the above throw?  If so, when?
     return CT_Cannot;
+
+  case AddrLabelExprClass:
+  case ArrayTypeTraitExprClass:
+  case BinaryTypeTraitExprClass:
+  case TypeTraitExprClass:
+  case CXXBoolLiteralExprClass:
+  case CXXNoexceptExprClass:
+  case CXXNullPtrLiteralExprClass:
+  case CXXPseudoDestructorExprClass:
+  case CXXScalarValueInitExprClass:
+  case CXXThisExprClass:
+  case CXXUuidofExprClass:
+  case CharacterLiteralClass:
+  case ExpressionTraitExprClass:
+  case FloatingLiteralClass:
+  case GNUNullExprClass:
+  case ImaginaryLiteralClass:
+  case ImplicitValueInitExprClass:
+  case IntegerLiteralClass:
+  case ObjCEncodeExprClass:
+  case ObjCStringLiteralClass:
+  case ObjCBoolLiteralExprClass:
+  case OpaqueValueExprClass:
+  case PredefinedExprClass:
+  case SizeOfPackExprClass:
+  case StringLiteralClass:
+  case UnaryTypeTraitExprClass:
+    // These expressions can never throw.
+    return CT_Cannot;
+
+#define STMT(CLASS, PARENT) case CLASS##Class:
+#define STMT_RANGE(Base, First, Last)
+#define LAST_STMT_RANGE(BASE, FIRST, LAST)
+#define EXPR(CLASS, PARENT)
+#define ABSTRACT_STMT(STMT)
+#include "clang/AST/StmtNodes.inc"
+  case NoStmtClass:
+    llvm_unreachable("Invalid class for expression");
   }
+  llvm_unreachable("Bogus StmtClass");
 }
=20
 Expr* Expr::IgnoreParens() {
@@ -2364,24 +2633,14 @@
=20
 /// hasAnyTypeDependentArguments - Determines if any of the expressions
 /// in Exprs is type-dependent.
-bool Expr::hasAnyTypeDependentArguments(Expr** Exprs, unsigned NumExprs) {
-  for (unsigned I =3D 0; I < NumExprs; ++I)
+bool Expr::hasAnyTypeDependentArguments(llvm::ArrayRef<Expr *> Exprs) {
+  for (unsigned I =3D 0; I < Exprs.size(); ++I)
     if (Exprs[I]->isTypeDependent())
       return true;
=20
   return false;
 }
=20
-/// hasAnyValueDependentArguments - Determines if any of the expressions
-/// in Exprs is value-dependent.
-bool Expr::hasAnyValueDependentArguments(Expr** Exprs, unsigned NumExprs) {
-  for (unsigned I =3D 0; I < NumExprs; ++I)
-    if (Exprs[I]->isValueDependent())
-      return true;
-
-  return false;
-}
-
 bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef) const {
   // This function is attempting whether an expression is an initializer
   // which can be evaluated at compile-time.  isEvaluatable handles most
@@ -2399,6 +2658,8 @@
=20
   switch (getStmtClass()) {
   default: break;
+  case IntegerLiteralClass:
+  case FloatingLiteralClass:
   case StringLiteralClass:
   case ObjCStringLiteralClass:
   case ObjCEncodeExprClass:
@@ -2408,15 +2669,20 @@
     const CXXConstructExpr *CE =3D cast<CXXConstructExpr>(this);
=20
     // Only if it's
-    // 1) an application of the trivial default constructor or
-    if (!CE->getConstructor()->isTrivial()) return false;
-    if (!CE->getNumArgs()) return true;
-
-    // 2) an elidable trivial copy construction of an operand which is
-    //    itself a constant initializer.  Note that we consider the
-    //    operand on its own, *not* as a reference binding.
-    return CE->isElidable() &&
-           CE->getArg(0)->isConstantInitializer(Ctx, false);
+    if (CE->getConstructor()->isTrivial()) {
+      // 1) an application of the trivial default constructor or
+      if (!CE->getNumArgs()) return true;
+
+      // 2) an elidable trivial copy construction of an operand which is
+      //    itself a constant initializer.  Note that we consider the
+      //    operand on its own, *not* as a reference binding.
+      if (CE->isElidable() &&
+          CE->getArg(0)->isConstantInitializer(Ctx, false))
+        return true;
+    }
+
+    // 3) a foldable constexpr constructor.
+    break;
   }
   case CompoundLiteralExprClass: {
     // This handles gcc's extension that allows global initializers like
@@ -2456,36 +2722,38 @@
       return Exp->getSubExpr()->isConstantInitializer(Ctx, false);
     break;
   }
-  case BinaryOperatorClass: {
-    // Special case &&foo - &&bar.  It would be nice to generalize this so=
mehow
-    // but this handles the common case.
-    const BinaryOperator *Exp =3D cast<BinaryOperator>(this);
-    if (Exp->getOpcode() =3D=3D BO_Sub &&
-        isa<AddrLabelExpr>(Exp->getLHS()->IgnoreParenNoopCasts(Ctx)) &&
-        isa<AddrLabelExpr>(Exp->getRHS()->IgnoreParenNoopCasts(Ctx)))
-      return true;
-    break;
-  }
   case CXXFunctionalCastExprClass:
   case CXXStaticCastExprClass:
   case ImplicitCastExprClass:
-  case CStyleCastExprClass:
-    // Handle casts with a destination that's a struct or union; this
-    // deals with both the gcc no-op struct cast extension and the
-    // cast-to-union extension.
-    if (getType()->isRecordType())
-      return cast<CastExpr>(this)->getSubExpr()
-        ->isConstantInitializer(Ctx, false);
-     =20
-    // Integer->integer casts can be handled here, which is important for
-    // things like (int)(&&x-&&y).  Scary but true.
-    if (getType()->isIntegerType() &&
-        cast<CastExpr>(this)->getSubExpr()->getType()->isIntegerType())
-      return cast<CastExpr>(this)->getSubExpr()
-        ->isConstantInitializer(Ctx, false);
-     =20
+  case CStyleCastExprClass: {
+    const CastExpr *CE =3D cast<CastExpr>(this);
+
+    // If we're promoting an integer to an _Atomic type then this is const=
ant
+    // if the integer is constant.  We also need to check the converse in =
case
+    // someone does something like:
+    //
+    // int a =3D (_Atomic(int))42;
+    //
+    // I doubt anyone would write code like this directly, but it's quite
+    // possible as the result of macro expansions.
+    if (CE->getCastKind() =3D=3D CK_NonAtomicToAtomic ||
+        CE->getCastKind() =3D=3D CK_AtomicToNonAtomic)
+      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
+
+    // Handle bitcasts of vector constants.
+    if (getType()->isVectorType() && CE->getCastKind() =3D=3D CK_BitCast)
+      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
+
+    // Handle misc casts we want to ignore.
+    // FIXME: Is it really safe to ignore all these?
+    if (CE->getCastKind() =3D=3D CK_NoOp ||
+        CE->getCastKind() =3D=3D CK_LValueToRValue ||
+        CE->getCastKind() =3D=3D CK_ToUnion ||
+        CE->getCastKind() =3D=3D CK_ConstructorConversion)
+      return CE->getSubExpr()->isConstantInitializer(Ctx, false);
+
     break;
-     =20
+  }
   case MaterializeTemporaryExprClass:
     return cast<MaterializeTemporaryExpr>(this)->GetTemporaryExpr()
                                             ->isConstantInitializer(Ctx, f=
alse);
@@ -2493,6 +2761,60 @@
   return isEvaluatable(Ctx);
 }
=20
+namespace {
+  /// \brief Look for a call to a non-trivial function within an expressio=
n.
+  class NonTrivialCallFinder : public EvaluatedExprVisitor<NonTrivialCallF=
inder>
+  {
+    typedef EvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
+   =20
+    bool NonTrivial;
+   =20
+  public:
+    explicit NonTrivialCallFinder(ASTContext &Context)=20
+      : Inherited(Context), NonTrivial(false) { }
+   =20
+    bool hasNonTrivialCall() const { return NonTrivial; }
+   =20
+    void VisitCallExpr(CallExpr *E) {
+      if (CXXMethodDecl *Method
+          =3D dyn_cast_or_null<CXXMethodDecl>(E->getCalleeDecl())) {
+        if (Method->isTrivial()) {
+          // Recurse to children of the call.
+          Inherited::VisitStmt(E);
+          return;
+        }
+      }
+     =20
+      NonTrivial =3D true;
+    }
+   =20
+    void VisitCXXConstructExpr(CXXConstructExpr *E) {
+      if (E->getConstructor()->isTrivial()) {
+        // Recurse to children of the call.
+        Inherited::VisitStmt(E);
+        return;
+      }
+     =20
+      NonTrivial =3D true;
+    }
+   =20
+    void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
+      if (E->getTemporary()->getDestructor()->isTrivial()) {
+        Inherited::VisitStmt(E);
+        return;
+      }
+     =20
+      NonTrivial =3D true;
+    }
+  };
+}
+
+bool Expr::hasNonTrivialCall(ASTContext &Ctx) {
+  NonTrivialCallFinder Finder(Ctx);
+  Finder.Visit(this);
+  return Finder.hasNonTrivialCall(); =20
+}
+
 /// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null=20
 /// pointer constant or not, as well as the specific kind of constant dete=
cted.
 /// Null pointer constants can be integer constant expressions with the
@@ -2518,7 +2840,7 @@
=20
   // Strip off a cast to void*, if it exists. Except in C++.
   if (const ExplicitCastExpr *CE =3D dyn_cast<ExplicitCastExpr>(this)) {
-    if (!Ctx.getLangOptions().CPlusPlus) {
+    if (!Ctx.getLangOpts().CPlusPlus) {
       // Check that it is a cast to void*.
       if (const PointerType *PT =3D CE->getType()->getAs<PointerType>()) {
         QualType Pointee =3D PT->getPointeeType();
@@ -2548,6 +2870,9 @@
   } else if (const MaterializeTemporaryExpr *M=20
                                    =3D dyn_cast<MaterializeTemporaryExpr>(=
this)) {
     return M->GetTemporaryExpr()->isNullPointerConstant(Ctx, NPC);
+  } else if (const OpaqueValueExpr *OVE =3D dyn_cast<OpaqueValueExpr>(this=
)) {
+    if (const Expr *Source =3D OVE->getSourceExpr())
+      return Source->isNullPointerConstant(Ctx, NPC);
   }
=20
   // C++0x nullptr_t is always a null pointer constant.
@@ -2563,15 +2888,22 @@
       }
   // This expression must be an integer type.
   if (!getType()->isIntegerType() ||=20
-      (Ctx.getLangOptions().CPlusPlus && getType()->isEnumeralType()))
+      (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
     return NPCK_NotNull;
=20
   // If we have an integer constant expression, we need to *evaluate* it a=
nd
-  // test for the value 0.
-  llvm::APSInt Result;
-  bool IsNull =3D isIntegerConstantExpr(Result, Ctx) && Result =3D=3D 0;
-
-  return (IsNull ? NPCK_ZeroInteger : NPCK_NotNull);
+  // test for the value 0. Don't use the C++11 constant expression semanti=
cs
+  // for this, for now; once the dust settles on core issue 903, we might =
only
+  // allow a literal 0 here in C++11 mode.
+  if (Ctx.getLangOpts().CPlusPlus0x) {
+    if (!isCXX98IntegralConstantExpr(Ctx))
+      return NPCK_NotNull;
+  } else {
+    if (!isIntegerConstantExpr(Ctx))
+      return NPCK_NotNull;
+  }
+
+  return (EvaluateKnownConstInt(Ctx) =3D=3D 0) ? NPCK_ZeroInteger : NPCK_N=
otNull;
 }
=20
 /// \brief If this expression is an l-value for an Objective C
@@ -2722,7 +3054,8 @@
                                  SelectorLocationsKind SelLocsK,
                                  ObjCMethodDecl *Method,
                                  ArrayRef<Expr *> Args,
-                                 SourceLocation RBracLoc)
+                                 SourceLocation RBracLoc,
+                                 bool isImplicit)
   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary,
          /*TypeDependent=3D*/false, /*ValueDependent=3D*/false,
          /*InstantiationDependent=3D*/false,
@@ -2730,8 +3063,8 @@
     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
                                                        : Sel.getAsOpaquePt=
r())),
     Kind(IsInstanceSuper? SuperInstance : SuperClass),
-    HasMethod(Method !=3D 0), IsDelegateInitCall(false), SuperLoc(SuperLoc=
),
-    LBracLoc(LBracLoc), RBracLoc(RBracLoc)=20
+    HasMethod(Method !=3D 0), IsDelegateInitCall(false), IsImplicit(isImpl=
icit),
+    SuperLoc(SuperLoc), LBracLoc(LBracLoc), RBracLoc(RBracLoc)=20
 {
   initArgsAndSelLocs(Args, SelLocs, SelLocsK);
   setReceiverPointer(SuperType.getAsOpaquePtr());
@@ -2746,14 +3079,15 @@
                                  SelectorLocationsKind SelLocsK,
                                  ObjCMethodDecl *Method,
                                  ArrayRef<Expr *> Args,
-                                 SourceLocation RBracLoc)
+                                 SourceLocation RBracLoc,
+                                 bool isImplicit)
   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, T->isDependentType(),
          T->isDependentType(), T->isInstantiationDependentType(),
          T->containsUnexpandedParameterPack()),
     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
                                                        : Sel.getAsOpaquePt=
r())),
     Kind(Class),
-    HasMethod(Method !=3D 0), IsDelegateInitCall(false),
+    HasMethod(Method !=3D 0), IsDelegateInitCall(false), IsImplicit(isImpl=
icit),
     LBracLoc(LBracLoc), RBracLoc(RBracLoc)=20
 {
   initArgsAndSelLocs(Args, SelLocs, SelLocsK);
@@ -2769,7 +3103,8 @@
                                  SelectorLocationsKind SelLocsK,
                                  ObjCMethodDecl *Method,
                                  ArrayRef<Expr *> Args,
-                                 SourceLocation RBracLoc)
+                                 SourceLocation RBracLoc,
+                                 bool isImplicit)
   : Expr(ObjCMessageExprClass, T, VK, OK_Ordinary, Receiver->isTypeDepende=
nt(),
          Receiver->isTypeDependent(),
          Receiver->isInstantiationDependent(),
@@ -2777,7 +3112,7 @@
     SelectorOrMethod(reinterpret_cast<uintptr_t>(Method? Method
                                                        : Sel.getAsOpaquePt=
r())),
     Kind(Instance),
-    HasMethod(Method !=3D 0), IsDelegateInitCall(false),
+    HasMethod(Method !=3D 0), IsDelegateInitCall(false), IsImplicit(isImpl=
icit),
     LBracLoc(LBracLoc), RBracLoc(RBracLoc)=20
 {
   initArgsAndSelLocs(Args, SelLocs, SelLocsK);
@@ -2803,8 +3138,10 @@
   }
=20
   SelLocsKind =3D SelLocsK;
-  if (SelLocsK =3D=3D SelLoc_NonStandard)
-    std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
+  if (!isImplicit()) {
+    if (SelLocsK =3D=3D SelLoc_NonStandard)
+      std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
+  }
 }
=20
 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
@@ -2817,12 +3154,19 @@
                                          ArrayRef<SourceLocation> SelLocs,
                                          ObjCMethodDecl *Method,
                                          ArrayRef<Expr *> Args,
-                                         SourceLocation RBracLoc) {
-  SelectorLocationsKind SelLocsK;
-  ObjCMessageExpr *Mem =3D alloc(Context, Args, RBracLoc, SelLocs, Sel, Se=
lLocsK);
+                                         SourceLocation RBracLoc,
+                                         bool isImplicit) {
+  assert((!SelLocs.empty() || isImplicit) &&
+         "No selector locs for non-implicit message");
+  ObjCMessageExpr *Mem;
+  SelectorLocationsKind SelLocsK =3D SelectorLocationsKind();
+  if (isImplicit)
+    Mem =3D alloc(Context, Args.size(), 0);
+  else
+    Mem =3D alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, SuperLoc, IsInstanceSu=
per,
                                    SuperType, Sel, SelLocs, SelLocsK,
-                                   Method, Args, RBracLoc);
+                                   Method, Args, RBracLoc, isImplicit);
 }
=20
 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
@@ -2833,11 +3177,19 @@
                                          ArrayRef<SourceLocation> SelLocs,
                                          ObjCMethodDecl *Method,
                                          ArrayRef<Expr *> Args,
-                                         SourceLocation RBracLoc) {
-  SelectorLocationsKind SelLocsK;
-  ObjCMessageExpr *Mem =3D alloc(Context, Args, RBracLoc, SelLocs, Sel, Se=
lLocsK);
+                                         SourceLocation RBracLoc,
+                                         bool isImplicit) {
+  assert((!SelLocs.empty() || isImplicit) &&
+         "No selector locs for non-implicit message");
+  ObjCMessageExpr *Mem;
+  SelectorLocationsKind SelLocsK =3D SelectorLocationsKind();
+  if (isImplicit)
+    Mem =3D alloc(Context, Args.size(), 0);
+  else
+    Mem =3D alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
-                                   SelLocs, SelLocsK, Method, Args, RBracL=
oc);
+                                   SelLocs, SelLocsK, Method, Args, RBracL=
oc,
+                                   isImplicit);
 }
=20
 ObjCMessageExpr *ObjCMessageExpr::Create(ASTContext &Context, QualType T,
@@ -2848,11 +3200,19 @@
                                          ArrayRef<SourceLocation> SelLocs,
                                          ObjCMethodDecl *Method,
                                          ArrayRef<Expr *> Args,
-                                         SourceLocation RBracLoc) {
-  SelectorLocationsKind SelLocsK;
-  ObjCMessageExpr *Mem =3D alloc(Context, Args, RBracLoc, SelLocs, Sel, Se=
lLocsK);
+                                         SourceLocation RBracLoc,
+                                         bool isImplicit) {
+  assert((!SelLocs.empty() || isImplicit) &&
+         "No selector locs for non-implicit message");
+  ObjCMessageExpr *Mem;
+  SelectorLocationsKind SelLocsK =3D SelectorLocationsKind();
+  if (isImplicit)
+    Mem =3D alloc(Context, Args.size(), 0);
+  else
+    Mem =3D alloc(Context, Args, RBracLoc, SelLocs, Sel, SelLocsK);
   return new (Mem) ObjCMessageExpr(T, VK, LBracLoc, Receiver, Sel,
-                                   SelLocs, SelLocsK, Method, Args, RBracL=
oc);
+                                   SelLocs, SelLocsK, Method, Args, RBracL=
oc,
+                                   isImplicit);
 }
=20
 ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext &Context,=20
@@ -2902,7 +3262,7 @@
     return getSuperLoc();
   }
=20
-  return SourceLocation();
+  llvm_unreachable("Invalid ReceiverKind!");
 }
=20
 Selector ObjCMessageExpr::getSelector() const {
@@ -2951,8 +3311,8 @@
   case OBC_BridgeRetained:
     return "__bridge_retained";
   }
- =20
-  return "__bridge";
+
+  llvm_unreachable("Invalid BridgeKind!");
 }
=20
 bool ChooseExpr::isConditionTrue(const ASTContext &C) const {
@@ -3225,11 +3585,10 @@
=20
 ParenListExpr::ParenListExpr(ASTContext& C, SourceLocation lparenloc,
                              Expr **exprs, unsigned nexprs,
-                             SourceLocation rparenloc, QualType T)
-  : Expr(ParenListExprClass, T, VK_RValue, OK_Ordinary,
+                             SourceLocation rparenloc)
+  : Expr(ParenListExprClass, QualType(), VK_RValue, OK_Ordinary,
          false, false, false, false),
     NumExprs(nexprs), LParenLoc(lparenloc), RParenLoc(rparenloc) {
-  assert(!T.isNull() && "ParenListExpr must have a valid type");
   Exprs =3D new (C) Stmt*[nexprs];
   for (unsigned i =3D 0; i !=3D nexprs; ++i) {
     if (exprs[i]->isTypeDependent())
@@ -3256,6 +3615,72 @@
   return cast<OpaqueValueExpr>(e);
 }
=20
+PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &Context, EmptyShell=
 sh,
+                                           unsigned numSemanticExprs) {
+  void *buffer =3D Context.Allocate(sizeof(PseudoObjectExpr) +
+                                    (1 + numSemanticExprs) * sizeof(Expr*),
+                                  llvm::alignOf<PseudoObjectExpr>());
+  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
+}
+
+PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticE=
xprs)
+  : Expr(PseudoObjectExprClass, shell) {
+  PseudoObjectExprBits.NumSubExprs =3D numSemanticExprs + 1;
+}
+
+PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext &C, Expr *syntax,
+                                           ArrayRef<Expr*> semantics,
+                                           unsigned resultIndex) {
+  assert(syntax && "no syntactic expression!");
+  assert(semantics.size() && "no semantic expressions!");
+
+  QualType type;
+  ExprValueKind VK;
+  if (resultIndex =3D=3D NoResult) {
+    type =3D C.VoidTy;
+    VK =3D VK_RValue;
+  } else {
+    assert(resultIndex < semantics.size());
+    type =3D semantics[resultIndex]->getType();
+    VK =3D semantics[resultIndex]->getValueKind();
+    assert(semantics[resultIndex]->getObjectKind() =3D=3D OK_Ordinary);
+  }
+
+  void *buffer =3D C.Allocate(sizeof(PseudoObjectExpr) +
+                              (1 + semantics.size()) * sizeof(Expr*),
+                            llvm::alignOf<PseudoObjectExpr>());
+  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
+                                      resultIndex);
+}
+
+PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
+                                   Expr *syntax, ArrayRef<Expr*> semantics,
+                                   unsigned resultIndex)
+  : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary,
+         /*filled in at end of ctor*/ false, false, false, false) {
+  PseudoObjectExprBits.NumSubExprs =3D semantics.size() + 1;
+  PseudoObjectExprBits.ResultIndex =3D resultIndex + 1;
+
+  for (unsigned i =3D 0, e =3D semantics.size() + 1; i !=3D e; ++i) {
+    Expr *E =3D (i =3D=3D 0 ? syntax : semantics[i-1]);
+    getSubExprsBuffer()[i] =3D E;
+
+    if (E->isTypeDependent())
+      ExprBits.TypeDependent =3D true;
+    if (E->isValueDependent())
+      ExprBits.ValueDependent =3D true;
+    if (E->isInstantiationDependent())
+      ExprBits.InstantiationDependent =3D true;
+    if (E->containsUnexpandedParameterPack())
+      ExprBits.ContainsUnexpandedParameterPack =3D true;
+
+    if (isa<OpaqueValueExpr>(E))
+      assert(cast<OpaqueValueExpr>(E)->getSourceExpr() !=3D 0 &&
+             "opaque-value semantic expressions for pseudo-object "
+             "operations must have sources");
+  }
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //  ExprIterator.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -3298,24 +3723,117 @@
                      reinterpret_cast<Stmt **>(getArgs() + getNumArgs()));
 }
=20
-// Blocks
-BlockDeclRefExpr::BlockDeclRefExpr(VarDecl *d, QualType t, ExprValueKind V=
K,
-                                   SourceLocation l, bool ByRef,=20
-                                   bool constAdded)
-  : Expr(BlockDeclRefExprClass, t, VK, OK_Ordinary, false, false, false,
-         d->isParameterPack()),
-    D(d), Loc(l), IsByRef(ByRef), ConstQualAdded(constAdded)
+ObjCArrayLiteral::ObjCArrayLiteral(llvm::ArrayRef<Expr *> Elements,=20
+                                   QualType T, ObjCMethodDecl *Method,
+                                   SourceRange SR)
+  : Expr(ObjCArrayLiteralClass, T, VK_RValue, OK_Ordinary,=20
+         false, false, false, false),=20
+    NumElements(Elements.size()), Range(SR), ArrayWithObjectsMethod(Method)
 {
-  bool TypeDependent =3D false;
-  bool ValueDependent =3D false;
-  bool InstantiationDependent =3D false;
-  computeDeclRefDependence(D, getType(), TypeDependent, ValueDependent,
-                           InstantiationDependent);
-  ExprBits.TypeDependent =3D TypeDependent;
-  ExprBits.ValueDependent =3D ValueDependent;
-  ExprBits.InstantiationDependent =3D InstantiationDependent;
+  Expr **SaveElements =3D getElements();
+  for (unsigned I =3D 0, N =3D Elements.size(); I !=3D N; ++I) {
+    if (Elements[I]->isTypeDependent() || Elements[I]->isValueDependent())
+      ExprBits.ValueDependent =3D true;
+    if (Elements[I]->isInstantiationDependent())
+      ExprBits.InstantiationDependent =3D true;
+    if (Elements[I]->containsUnexpandedParameterPack())
+      ExprBits.ContainsUnexpandedParameterPack =3D true;
+   =20
+    SaveElements[I] =3D Elements[I];
+  }
 }
=20
+ObjCArrayLiteral *ObjCArrayLiteral::Create(ASTContext &C,=20
+                                           llvm::ArrayRef<Expr *> Elements,
+                                           QualType T, ObjCMethodDecl * Me=
thod,
+                                           SourceRange SR) {
+  void *Mem =3D C.Allocate(sizeof(ObjCArrayLiteral)=20
+                         + Elements.size() * sizeof(Expr *));
+  return new (Mem) ObjCArrayLiteral(Elements, T, Method, SR);
+}
+
+ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(ASTContext &C,=20
+                                                unsigned NumElements) {
+ =20
+  void *Mem =3D C.Allocate(sizeof(ObjCArrayLiteral)=20
+                         + NumElements * sizeof(Expr *));
+  return new (Mem) ObjCArrayLiteral(EmptyShell(), NumElements);
+}
+
+ObjCDictionaryLiteral::ObjCDictionaryLiteral(
+                                             ArrayRef<ObjCDictionaryElemen=
t> VK,=20
+                                             bool HasPackExpansions,
+                                             QualType T, ObjCMethodDecl *m=
ethod,
+                                             SourceRange SR)
+  : Expr(ObjCDictionaryLiteralClass, T, VK_RValue, OK_Ordinary, false, fal=
se,
+         false, false),
+    NumElements(VK.size()), HasPackExpansions(HasPackExpansions), Range(SR=
),=20
+    DictWithObjectsMethod(method)
+{
+  KeyValuePair *KeyValues =3D getKeyValues();
+  ExpansionData *Expansions =3D getExpansionData();
+  for (unsigned I =3D 0; I < NumElements; I++) {
+    if (VK[I].Key->isTypeDependent() || VK[I].Key->isValueDependent() ||
+        VK[I].Value->isTypeDependent() || VK[I].Value->isValueDependent())
+      ExprBits.ValueDependent =3D true;
+    if (VK[I].Key->isInstantiationDependent() ||
+        VK[I].Value->isInstantiationDependent())
+      ExprBits.InstantiationDependent =3D true;
+    if (VK[I].EllipsisLoc.isInvalid() &&
+        (VK[I].Key->containsUnexpandedParameterPack() ||
+         VK[I].Value->containsUnexpandedParameterPack()))
+      ExprBits.ContainsUnexpandedParameterPack =3D true;
+
+    KeyValues[I].Key =3D VK[I].Key;
+    KeyValues[I].Value =3D VK[I].Value;=20
+    if (Expansions) {
+      Expansions[I].EllipsisLoc =3D VK[I].EllipsisLoc;
+      if (VK[I].NumExpansions)
+        Expansions[I].NumExpansionsPlusOne =3D *VK[I].NumExpansions + 1;
+      else
+        Expansions[I].NumExpansionsPlusOne =3D 0;
+    }
+  }
+}
+
+ObjCDictionaryLiteral *
+ObjCDictionaryLiteral::Create(ASTContext &C,
+                              ArrayRef<ObjCDictionaryElement> VK,=20
+                              bool HasPackExpansions,
+                              QualType T, ObjCMethodDecl *method,
+                              SourceRange SR) {
+  unsigned ExpansionsSize =3D 0;
+  if (HasPackExpansions)
+    ExpansionsSize =3D sizeof(ExpansionData) * VK.size();
+   =20
+  void *Mem =3D C.Allocate(sizeof(ObjCDictionaryLiteral) +=20
+                         sizeof(KeyValuePair) * VK.size() + ExpansionsSize=
);
+  return new (Mem) ObjCDictionaryLiteral(VK, HasPackExpansions, T, method,=
 SR);
+}
+
+ObjCDictionaryLiteral *
+ObjCDictionaryLiteral::CreateEmpty(ASTContext &C, unsigned NumElements,
+                                   bool HasPackExpansions) {
+  unsigned ExpansionsSize =3D 0;
+  if (HasPackExpansions)
+    ExpansionsSize =3D sizeof(ExpansionData) * NumElements;
+  void *Mem =3D C.Allocate(sizeof(ObjCDictionaryLiteral) +=20
+                         sizeof(KeyValuePair) * NumElements + ExpansionsSi=
ze);
+  return new (Mem) ObjCDictionaryLiteral(EmptyShell(), NumElements,=20
+                                         HasPackExpansions);
+}
+
+ObjCSubscriptRefExpr *ObjCSubscriptRefExpr::Create(ASTContext &C,
+                                                   Expr *base,
+                                                   Expr *key, QualType T,=20
+                                                   ObjCMethodDecl *getMeth=
od,
+                                                   ObjCMethodDecl *setMeth=
od,=20
+                                                   SourceLocation RB) {
+  void *Mem =3D C.Allocate(sizeof(ObjCSubscriptRefExpr));
+  return new (Mem) ObjCSubscriptRefExpr(base, key, T, VK_LValue,=20
+                                        OK_ObjCSubscript,
+                                        getMethod, setMethod, RB);
+}
=20
 AtomicExpr::AtomicExpr(SourceLocation BLoc, Expr **args, unsigned nexpr,
                        QualType t, AtomicOp op, SourceLocation RP)
@@ -3323,6 +3841,7 @@
          false, false, false, false),
     NumSubExprs(nexpr), BuiltinLoc(BLoc), RParenLoc(RP), Op(op)
 {
+  assert(nexpr =3D=3D getNumSubExprs(op) && "wrong number of subexpression=
s");
   for (unsigned i =3D 0; i < nexpr; i++) {
     if (args[i]->isTypeDependent())
       ExprBits.TypeDependent =3D true;
@@ -3336,3 +3855,49 @@
     SubExprs[i] =3D args[i];
   }
 }
+
+unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
+  switch (Op) {
+  case AO__c11_atomic_init:
+  case AO__c11_atomic_load:
+  case AO__atomic_load_n:
+    return 2;
+
+  case AO__c11_atomic_store:
+  case AO__c11_atomic_exchange:
+  case AO__atomic_load:
+  case AO__atomic_store:
+  case AO__atomic_store_n:
+  case AO__atomic_exchange_n:
+  case AO__c11_atomic_fetch_add:
+  case AO__c11_atomic_fetch_sub:
+  case AO__c11_atomic_fetch_and:
+  case AO__c11_atomic_fetch_or:
+  case AO__c11_atomic_fetch_xor:
+  case AO__atomic_fetch_add:
+  case AO__atomic_fetch_sub:
+  case AO__atomic_fetch_and:
+  case AO__atomic_fetch_or:
+  case AO__atomic_fetch_xor:
+  case AO__atomic_fetch_nand:
+  case AO__atomic_add_fetch:
+  case AO__atomic_sub_fetch:
+  case AO__atomic_and_fetch:
+  case AO__atomic_or_fetch:
+  case AO__atomic_xor_fetch:
+  case AO__atomic_nand_fetch:
+    return 3;
+
+  case AO__atomic_exchange:
+    return 4;
+
+  case AO__c11_atomic_compare_exchange_strong:
+  case AO__c11_atomic_compare_exchange_weak:
+    return 5;
+
+  case AO__atomic_compare_exchange:
+  case AO__atomic_compare_exchange_n:
+    return 6;
+  }
+  llvm_unreachable("unknown atomic op");
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ExprCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ExprCXX.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ExprCXX.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -45,30 +45,26 @@
=20
 // CXXNewExpr
 CXXNewExpr::CXXNewExpr(ASTContext &C, bool globalNew, FunctionDecl *operat=
orNew,
+                       FunctionDecl *operatorDelete,
+                       bool usualArrayDeleteWantsSize,
                        Expr **placementArgs, unsigned numPlaceArgs,
-                       SourceRange TypeIdParens, Expr *arraySize,
-                       CXXConstructorDecl *constructor, bool initializer,
-                       Expr **constructorArgs, unsigned numConsArgs,
-                       bool HadMultipleCandidates,
-                       FunctionDecl *operatorDelete,
-                       bool usualArrayDeleteWantsSize, QualType ty,
-                       TypeSourceInfo *AllocatedTypeInfo,
-                       SourceLocation startLoc, SourceLocation endLoc,
-                       SourceLocation constructorLParen,
-                       SourceLocation constructorRParen)
+                       SourceRange typeIdParens, Expr *arraySize,
+                       InitializationStyle initializationStyle,
+                       Expr *initializer, QualType ty,
+                       TypeSourceInfo *allocatedTypeInfo,
+                       SourceLocation startLoc, SourceRange directInitRang=
e)
   : Expr(CXXNewExprClass, ty, VK_RValue, OK_Ordinary,
          ty->isDependentType(), ty->isDependentType(),
          ty->isInstantiationDependentType(),
          ty->containsUnexpandedParameterPack()),
-    GlobalNew(globalNew), Initializer(initializer),
-    UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize),
-    HadMultipleCandidates(HadMultipleCandidates),
-    SubExprs(0), OperatorNew(operatorNew),
-    OperatorDelete(operatorDelete), Constructor(constructor),
-    AllocatedTypeInfo(AllocatedTypeInfo), TypeIdParens(TypeIdParens),
-    StartLoc(startLoc), EndLoc(endLoc), ConstructorLParen(constructorLPare=
n),
-    ConstructorRParen(constructorRParen) {
-  AllocateArgsArray(C, arraySize !=3D 0, numPlaceArgs, numConsArgs);
+    SubExprs(0), OperatorNew(operatorNew), OperatorDelete(operatorDelete),
+    AllocatedTypeInfo(allocatedTypeInfo), TypeIdParens(typeIdParens),
+    StartLoc(startLoc), DirectInitRange(directInitRange),
+    GlobalNew(globalNew), UsualArrayDeleteWantsSize(usualArrayDeleteWantsS=
ize) {
+  assert((initializer !=3D 0 || initializationStyle =3D=3D NoInit) &&
+         "Only NoInit can have no initializer.");
+  StoredInitializationStyle =3D initializer ? initializationStyle + 1 : 0;
+  AllocateArgsArray(C, arraySize !=3D 0, numPlaceArgs, initializer !=3D 0);
   unsigned i =3D 0;
   if (Array) {
     if (arraySize->isInstantiationDependent())
@@ -80,6 +76,16 @@
     SubExprs[i++] =3D arraySize;
   }
=20
+  if (initializer) {
+    if (initializer->isInstantiationDependent())
+      ExprBits.InstantiationDependent =3D true;
+
+    if (initializer->containsUnexpandedParameterPack())
+      ExprBits.ContainsUnexpandedParameterPack =3D true;
+
+    SubExprs[i++] =3D initializer;
+  }
+
   for (unsigned j =3D 0; j < NumPlacementArgs; ++j) {
     if (placementArgs[j]->isInstantiationDependent())
       ExprBits.InstantiationDependent =3D true;
@@ -88,25 +94,15 @@
=20
     SubExprs[i++] =3D placementArgs[j];
   }
-
-  for (unsigned j =3D 0; j < NumConstructorArgs; ++j) {
-    if (constructorArgs[j]->isInstantiationDependent())
-      ExprBits.InstantiationDependent =3D true;
-    if (constructorArgs[j]->containsUnexpandedParameterPack())
-      ExprBits.ContainsUnexpandedParameterPack =3D true;
-
-    SubExprs[i++] =3D constructorArgs[j];
-  }
 }
=20
 void CXXNewExpr::AllocateArgsArray(ASTContext &C, bool isArray,
-                                   unsigned numPlaceArgs, unsigned numCons=
Args){
+                                   unsigned numPlaceArgs, bool hasInitiali=
zer){
   assert(SubExprs =3D=3D 0 && "SubExprs already allocated");
   Array =3D isArray;
   NumPlacementArgs =3D numPlaceArgs;
-  NumConstructorArgs =3D numConsArgs;=20
- =20
-  unsigned TotalSize =3D Array + NumPlacementArgs + NumConstructorArgs;
+
+  unsigned TotalSize =3D Array + hasInitializer + NumPlacementArgs;
   SubExprs =3D new (C) Stmt*[TotalSize];
 }
=20
@@ -115,6 +111,18 @@
     castAs<FunctionProtoType>()->isNothrow(Ctx);
 }
=20
+SourceLocation CXXNewExpr::getEndLoc() const {
+  switch (getInitializationStyle()) {
+  case NoInit:
+    return AllocatedTypeInfo->getTypeLoc().getEndLoc();
+  case CallInit:
+    return DirectInitRange.getEnd();
+  case ListInit:
+    return getInitializer()->getSourceRange().getEnd();
+  }
+  llvm_unreachable("bogus initialization style");
+}
+
 // CXXDeleteExpr
 QualType CXXDeleteExpr::getDestroyedType() const {
   const Expr *Arg =3D getArgument();
@@ -191,40 +199,45 @@
   return SourceRange(Base->getLocStart(), End);
 }
=20
-
 // UnresolvedLookupExpr
 UnresolvedLookupExpr *
 UnresolvedLookupExpr::Create(ASTContext &C,=20
                              CXXRecordDecl *NamingClass,
                              NestedNameSpecifierLoc QualifierLoc,
+                             SourceLocation TemplateKWLoc,
                              const DeclarationNameInfo &NameInfo,
                              bool ADL,
-                             const TemplateArgumentListInfo &Args,
-                             UnresolvedSetIterator Begin,=20
-                             UnresolvedSetIterator End)=20
+                             const TemplateArgumentListInfo *Args,
+                             UnresolvedSetIterator Begin,
+                             UnresolvedSetIterator End)
 {
-  void *Mem =3D C.Allocate(sizeof(UnresolvedLookupExpr) +=20
-                         ASTTemplateArgumentListInfo::sizeFor(Args));
-  return new (Mem) UnresolvedLookupExpr(C, NamingClass, QualifierLoc, Name=
Info,
-                                        ADL, /*Overload*/ true, &Args,
+  assert(Args || TemplateKWLoc.isValid());
+  unsigned num_args =3D Args ? Args->size() : 0;
+  void *Mem =3D C.Allocate(sizeof(UnresolvedLookupExpr) +
+                         ASTTemplateKWAndArgsInfo::sizeFor(num_args));
+  return new (Mem) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
+                                        TemplateKWLoc, NameInfo,
+                                        ADL, /*Overload*/ true, Args,
                                         Begin, End, /*StdIsAssociated=3D*/=
false);
 }
=20
 UnresolvedLookupExpr *
-UnresolvedLookupExpr::CreateEmpty(ASTContext &C, bool HasExplicitTemplateA=
rgs,=20
+UnresolvedLookupExpr::CreateEmpty(ASTContext &C,
+                                  bool HasTemplateKWAndArgsInfo,
                                   unsigned NumTemplateArgs) {
   std::size_t size =3D sizeof(UnresolvedLookupExpr);
-  if (HasExplicitTemplateArgs)
-    size +=3D ASTTemplateArgumentListInfo::sizeFor(NumTemplateArgs);
+  if (HasTemplateKWAndArgsInfo)
+    size +=3D ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
=20
   void *Mem =3D C.Allocate(size, llvm::alignOf<UnresolvedLookupExpr>());
   UnresolvedLookupExpr *E =3D new (Mem) UnresolvedLookupExpr(EmptyShell());
-  E->HasExplicitTemplateArgs =3D HasExplicitTemplateArgs;
+  E->HasTemplateKWAndArgsInfo =3D HasTemplateKWAndArgsInfo;
   return E;
 }
=20
 OverloadExpr::OverloadExpr(StmtClass K, ASTContext &C,=20
                            NestedNameSpecifierLoc QualifierLoc,
+                           SourceLocation TemplateKWLoc,
                            const DeclarationNameInfo &NameInfo,
                            const TemplateArgumentListInfo *TemplateArgs,
                            UnresolvedSetIterator Begin,=20
@@ -243,8 +256,9 @@
           (QualifierLoc &&=20
            QualifierLoc.getNestedNameSpecifier()
                                       ->containsUnexpandedParameterPack())=
)),
-    Results(0), NumResults(End - Begin), NameInfo(NameInfo),=20
-    QualifierLoc(QualifierLoc), HasExplicitTemplateArgs(TemplateArgs !=3D =
0)
+    NameInfo(NameInfo), QualifierLoc(QualifierLoc),
+    Results(0), NumResults(End - Begin),
+    HasTemplateKWAndArgsInfo(TemplateArgs !=3D 0 || TemplateKWLoc.isValid(=
))
 {
   NumResults =3D End - Begin;
   if (NumResults) {
@@ -271,9 +285,10 @@
     bool Dependent =3D false;
     bool InstantiationDependent =3D false;
     bool ContainsUnexpandedParameterPack =3D false;
-    getExplicitTemplateArgs().initializeFrom(*TemplateArgs, Dependent,
-                                             InstantiationDependent,
-                                             ContainsUnexpandedParameterPa=
ck);
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArg=
s,
+                                               Dependent,
+                                               InstantiationDependent,
+                                               ContainsUnexpandedParameter=
Pack);
=20
     if (Dependent) {
       ExprBits.TypeDependent =3D true;
@@ -283,6 +298,8 @@
       ExprBits.InstantiationDependent =3D true;
     if (ContainsUnexpandedParameterPack)
       ExprBits.ContainsUnexpandedParameterPack =3D true;
+  } else if (TemplateKWLoc.isValid()) {
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
   }
=20
   if (isTypeDependent())
@@ -314,6 +331,7 @@
 // DependentScopeDeclRefExpr
 DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(QualType T,
                             NestedNameSpecifierLoc QualifierLoc,
+                            SourceLocation TemplateKWLoc,
                             const DeclarationNameInfo &NameInfo,
                             const TemplateArgumentListInfo *Args)
   : Expr(DependentScopeDeclRefExprClass, T, VK_LValue, OK_Ordinary,
@@ -326,47 +344,52 @@
            QualifierLoc.getNestedNameSpecifier()
                             ->containsUnexpandedParameterPack()))),
     QualifierLoc(QualifierLoc), NameInfo(NameInfo),=20
-    HasExplicitTemplateArgs(Args !=3D 0)
+    HasTemplateKWAndArgsInfo(Args !=3D 0 || TemplateKWLoc.isValid())
 {
   if (Args) {
     bool Dependent =3D true;
     bool InstantiationDependent =3D true;
     bool ContainsUnexpandedParameterPack
       =3D ExprBits.ContainsUnexpandedParameterPack;
-
-    reinterpret_cast<ASTTemplateArgumentListInfo*>(this+1)
-      ->initializeFrom(*Args, Dependent, InstantiationDependent,
-                       ContainsUnexpandedParameterPack);
-   =20
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *Args,
+                                               Dependent,
+                                               InstantiationDependent,
+                                               ContainsUnexpandedParameter=
Pack);
     ExprBits.ContainsUnexpandedParameterPack =3D ContainsUnexpandedParamet=
erPack;
+  } else if (TemplateKWLoc.isValid()) {
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
   }
 }
=20
 DependentScopeDeclRefExpr *
 DependentScopeDeclRefExpr::Create(ASTContext &C,
                                   NestedNameSpecifierLoc QualifierLoc,
+                                  SourceLocation TemplateKWLoc,
                                   const DeclarationNameInfo &NameInfo,
                                   const TemplateArgumentListInfo *Args) {
   std::size_t size =3D sizeof(DependentScopeDeclRefExpr);
   if (Args)
-    size +=3D ASTTemplateArgumentListInfo::sizeFor(*Args);
+    size +=3D ASTTemplateKWAndArgsInfo::sizeFor(Args->size());
+  else if (TemplateKWLoc.isValid())
+    size +=3D ASTTemplateKWAndArgsInfo::sizeFor(0);
   void *Mem =3D C.Allocate(size);
-  return new (Mem) DependentScopeDeclRefExpr(C.DependentTy, QualifierLoc,=20
-                                             NameInfo, Args);
+  return new (Mem) DependentScopeDeclRefExpr(C.DependentTy, QualifierLoc,
+                                             TemplateKWLoc, NameInfo, Args=
);
 }
=20
 DependentScopeDeclRefExpr *
 DependentScopeDeclRefExpr::CreateEmpty(ASTContext &C,
-                                       bool HasExplicitTemplateArgs,
+                                       bool HasTemplateKWAndArgsInfo,
                                        unsigned NumTemplateArgs) {
   std::size_t size =3D sizeof(DependentScopeDeclRefExpr);
-  if (HasExplicitTemplateArgs)
-    size +=3D ASTTemplateArgumentListInfo::sizeFor(NumTemplateArgs);
+  if (HasTemplateKWAndArgsInfo)
+    size +=3D ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
   void *Mem =3D C.Allocate(size);
-  DependentScopeDeclRefExpr *E=20
+  DependentScopeDeclRefExpr *E
     =3D new (Mem) DependentScopeDeclRefExpr(QualType(), NestedNameSpecifie=
rLoc(),
+                                          SourceLocation(),
                                           DeclarationNameInfo(), 0);
-  E->HasExplicitTemplateArgs =3D HasExplicitTemplateArgs;
+  E->HasTemplateKWAndArgsInfo =3D HasTemplateKWAndArgsInfo;
   return E;
 }
=20
@@ -601,6 +624,39 @@
   return new (Buffer) CXXFunctionalCastExpr(EmptyShell(), PathSize);
 }
=20
+UserDefinedLiteral::LiteralOperatorKind
+UserDefinedLiteral::getLiteralOperatorKind() const {
+  if (getNumArgs() =3D=3D 0)
+    return LOK_Template;
+  if (getNumArgs() =3D=3D 2)
+    return LOK_String;
+
+  assert(getNumArgs() =3D=3D 1 && "unexpected #args in literal operator ca=
ll");
+  QualType ParamTy =3D
+    cast<FunctionDecl>(getCalleeDecl())->getParamDecl(0)->getType();
+  if (ParamTy->isPointerType())
+    return LOK_Raw;
+  if (ParamTy->isAnyCharacterType())
+    return LOK_Character;
+  if (ParamTy->isIntegerType())
+    return LOK_Integer;
+  if (ParamTy->isFloatingType())
+    return LOK_Floating;
+
+  llvm_unreachable("unknown kind of literal operator");
+}
+
+Expr *UserDefinedLiteral::getCookedLiteral() {
+#ifndef NDEBUG
+  LiteralOperatorKind LOK =3D getLiteralOperatorKind();
+  assert(LOK !=3D LOK_Template && LOK !=3D LOK_Raw && "not a cooked litera=
l");
+#endif
+  return getArg(0);
+}
+
+const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {
+  return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();
+}
=20
 CXXDefaultArgExpr *
 CXXDefaultArgExpr::Create(ASTContext &C, SourceLocation Loc,=20
@@ -618,8 +674,9 @@
 CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(ASTContext &C,
                                                    CXXTemporary *Temp,
                                                    Expr* SubExpr) {
-  assert(SubExpr->getType()->isRecordType() &&
-         "Expression bound to a temporary must have record type!");
+  assert((SubExpr->getType()->isRecordType() ||
+          SubExpr->getType()->isArrayType()) &&
+         "Expression bound to a temporary must have record or array type!"=
);
=20
   return new (C) CXXBindTemporaryExpr(Temp, SubExpr);
 }
@@ -636,7 +693,7 @@
                      Type->getType().getNonReferenceType(),=20
                      Type->getTypeLoc().getBeginLoc(),
                      Cons, false, Args, NumArgs,
-                     HadMultipleCandidates, ZeroInitialization,
+                     HadMultipleCandidates, /*FIXME*/false, ZeroInitializa=
tion,
                      CXXConstructExpr::CK_Complete, parenRange),
     Type(Type) {
 }
@@ -651,13 +708,15 @@
                                            CXXConstructorDecl *D, bool Eli=
dable,
                                            Expr **Args, unsigned NumArgs,
                                            bool HadMultipleCandidates,
+                                           bool ListInitialization,
                                            bool ZeroInitialization,
                                            ConstructionKind ConstructKind,
                                            SourceRange ParenRange) {
   return new (C) CXXConstructExpr(C, CXXConstructExprClass, T, Loc, D,=20
                                   Elidable, Args, NumArgs,
-                                  HadMultipleCandidates, ZeroInitializatio=
n,
-                                  ConstructKind, ParenRange);
+                                  HadMultipleCandidates, ListInitializatio=
n,
+                                  ZeroInitialization, ConstructKind,
+                                  ParenRange);
 }
=20
 CXXConstructExpr::CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T,
@@ -665,6 +724,7 @@
                                    CXXConstructorDecl *D, bool elidable,
                                    Expr **args, unsigned numargs,
                                    bool HadMultipleCandidates,
+                                   bool ListInitialization,
                                    bool ZeroInitialization,
                                    ConstructionKind ConstructKind,
                                    SourceRange ParenRange)
@@ -674,6 +734,7 @@
          T->containsUnexpandedParameterPack()),
     Constructor(D), Loc(Loc), ParenRange(ParenRange),  NumArgs(numargs),
     Elidable(elidable), HadMultipleCandidates(HadMultipleCandidates),
+    ListInitialization(ListInitialization),
     ZeroInitialization(ZeroInitialization),
     ConstructKind(ConstructKind), Args(0)
 {
@@ -695,35 +756,228 @@
   }
 }
=20
-ExprWithCleanups::ExprWithCleanups(ASTContext &C,
-                                   Expr *subexpr,
-                                   CXXTemporary **temps,
-                                   unsigned numtemps)
+LambdaExpr::Capture::Capture(SourceLocation Loc, bool Implicit,
+                             LambdaCaptureKind Kind, VarDecl *Var,
+                             SourceLocation EllipsisLoc)
+  : VarAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc)
+{
+  unsigned Bits =3D 0;
+  if (Implicit)
+    Bits |=3D Capture_Implicit;
+ =20
+  switch (Kind) {
+  case LCK_This:=20
+    assert(Var =3D=3D 0 && "'this' capture cannot have a variable!");
+    break;
+
+  case LCK_ByCopy:
+    Bits |=3D Capture_ByCopy;
+    // Fall through=20
+  case LCK_ByRef:
+    assert(Var && "capture must have a variable!");
+    break;
+  }
+  VarAndBits.setInt(Bits);
+}
+
+LambdaCaptureKind LambdaExpr::Capture::getCaptureKind() const {
+  if (capturesThis())
+    return LCK_This;
+
+  return (VarAndBits.getInt() & Capture_ByCopy)? LCK_ByCopy : LCK_ByRef;
+}
+
+LambdaExpr::LambdaExpr(QualType T,=20
+                       SourceRange IntroducerRange,
+                       LambdaCaptureDefault CaptureDefault,
+                       ArrayRef<Capture> Captures,=20
+                       bool ExplicitParams,
+                       bool ExplicitResultType,
+                       ArrayRef<Expr *> CaptureInits,
+                       ArrayRef<VarDecl *> ArrayIndexVars,
+                       ArrayRef<unsigned> ArrayIndexStarts,
+                       SourceLocation ClosingBrace)
+  : Expr(LambdaExprClass, T, VK_RValue, OK_Ordinary,
+         T->isDependentType(), T->isDependentType(), T->isDependentType(),
+         /*ContainsUnexpandedParameterPack=3D*/false),
+    IntroducerRange(IntroducerRange),
+    NumCaptures(Captures.size()),
+    CaptureDefault(CaptureDefault),
+    ExplicitParams(ExplicitParams),
+    ExplicitResultType(ExplicitResultType),
+    ClosingBrace(ClosingBrace)
+{
+  assert(CaptureInits.size() =3D=3D Captures.size() && "Wrong number of ar=
guments");
+  CXXRecordDecl *Class =3D getLambdaClass();
+  CXXRecordDecl::LambdaDefinitionData &Data =3D Class->getLambdaData();
+ =20
+  // FIXME: Propagate "has unexpanded parameter pack" bit.
+ =20
+  // Copy captures.
+  ASTContext &Context =3D Class->getASTContext();
+  Data.NumCaptures =3D NumCaptures;
+  Data.NumExplicitCaptures =3D 0;
+  Data.Captures =3D (Capture *)Context.Allocate(sizeof(Capture) * NumCaptu=
res);
+  Capture *ToCapture =3D Data.Captures;
+  for (unsigned I =3D 0, N =3D Captures.size(); I !=3D N; ++I) {
+    if (Captures[I].isExplicit())
+      ++Data.NumExplicitCaptures;
+   =20
+    *ToCapture++ =3D Captures[I];
+  }
+=20
+  // Copy initialization expressions for the non-static data members.
+  Stmt **Stored =3D getStoredStmts();
+  for (unsigned I =3D 0, N =3D CaptureInits.size(); I !=3D N; ++I)
+    *Stored++ =3D CaptureInits[I];
+ =20
+  // Copy the body of the lambda.
+  *Stored++ =3D getCallOperator()->getBody();
+
+  // Copy the array index variables, if any.
+  HasArrayIndexVars =3D !ArrayIndexVars.empty();
+  if (HasArrayIndexVars) {
+    assert(ArrayIndexStarts.size() =3D=3D NumCaptures);
+    memcpy(getArrayIndexVars(), ArrayIndexVars.data(),
+           sizeof(VarDecl *) * ArrayIndexVars.size());
+    memcpy(getArrayIndexStarts(), ArrayIndexStarts.data(),=20
+           sizeof(unsigned) * Captures.size());
+    getArrayIndexStarts()[Captures.size()] =3D ArrayIndexVars.size();
+  }
+}
+
+LambdaExpr *LambdaExpr::Create(ASTContext &Context,=20
+                               CXXRecordDecl *Class,
+                               SourceRange IntroducerRange,
+                               LambdaCaptureDefault CaptureDefault,
+                               ArrayRef<Capture> Captures,=20
+                               bool ExplicitParams,
+                               bool ExplicitResultType,
+                               ArrayRef<Expr *> CaptureInits,
+                               ArrayRef<VarDecl *> ArrayIndexVars,
+                               ArrayRef<unsigned> ArrayIndexStarts,
+                               SourceLocation ClosingBrace) {
+  // Determine the type of the expression (i.e., the type of the
+  // function object we're creating).
+  QualType T =3D Context.getTypeDeclType(Class);
+
+  unsigned Size =3D sizeof(LambdaExpr) + sizeof(Stmt *) * (Captures.size()=
 + 1);
+  if (!ArrayIndexVars.empty())
+    Size +=3D sizeof(VarDecl *) * ArrayIndexVars.size()
+          + sizeof(unsigned) * (Captures.size() + 1);
+  void *Mem =3D Context.Allocate(Size);
+  return new (Mem) LambdaExpr(T, IntroducerRange, CaptureDefault,=20
+                              Captures, ExplicitParams, ExplicitResultType,
+                              CaptureInits, ArrayIndexVars, ArrayIndexStar=
ts,
+                              ClosingBrace);
+}
+
+LambdaExpr *LambdaExpr::CreateDeserialized(ASTContext &C, unsigned NumCapt=
ures,
+                                           unsigned NumArrayIndexVars) {
+  unsigned Size =3D sizeof(LambdaExpr) + sizeof(Stmt *) * (NumCaptures + 1=
);
+  if (NumArrayIndexVars)
+    Size +=3D sizeof(VarDecl) * NumArrayIndexVars
+          + sizeof(unsigned) * (NumCaptures + 1);
+  void *Mem =3D C.Allocate(Size);
+  return new (Mem) LambdaExpr(EmptyShell(), NumCaptures, NumArrayIndexVars=
 > 0);
+}
+
+LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
+  return getLambdaClass()->getLambdaData().Captures;
+}
+
+LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
+  return capture_begin() + NumCaptures;
+}
+
+LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
+  return capture_begin();
+}
+
+LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
+  struct CXXRecordDecl::LambdaDefinitionData &Data
+    =3D getLambdaClass()->getLambdaData();
+  return Data.Captures + Data.NumExplicitCaptures;
+}
+
+LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
+  return explicit_capture_end();
+}
+
+LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
+  return capture_end();
+}
+
+ArrayRef<VarDecl *>=20
+LambdaExpr::getCaptureInitIndexVars(capture_init_iterator Iter) const {
+  assert(HasArrayIndexVars && "No array index-var data?");
+ =20
+  unsigned Index =3D Iter - capture_init_begin();
+  assert(Index < getLambdaClass()->getLambdaData().NumCaptures &&
+         "Capture index out-of-range");
+  VarDecl **IndexVars =3D getArrayIndexVars();
+  unsigned *IndexStarts =3D getArrayIndexStarts();
+  return ArrayRef<VarDecl *>(IndexVars + IndexStarts[Index],
+                             IndexVars + IndexStarts[Index + 1]);
+}
+
+CXXRecordDecl *LambdaExpr::getLambdaClass() const {
+  return getType()->getAsCXXRecordDecl();
+}
+
+CXXMethodDecl *LambdaExpr::getCallOperator() const {
+  CXXRecordDecl *Record =3D getLambdaClass();
+  DeclarationName Name
+    =3D Record->getASTContext().DeclarationNames.getCXXOperatorName(OO_Cal=
l);
+  DeclContext::lookup_result Calls =3D Record->lookup(Name);
+  assert(Calls.first !=3D Calls.second && "Missing lambda call operator!");
+  CXXMethodDecl *Result =3D cast<CXXMethodDecl>(*Calls.first++);
+  assert(Calls.first =3D=3D Calls.second && "More than lambda one call ope=
rator?");
+  return Result;
+}
+
+CompoundStmt *LambdaExpr::getBody() const {
+  if (!getStoredStmts()[NumCaptures])
+    getStoredStmts()[NumCaptures] =3D getCallOperator()->getBody();
+   =20
+  return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
+}
+
+bool LambdaExpr::isMutable() const {
+  return (getCallOperator()->getTypeQualifiers() & Qualifiers::Const) =3D=
=3D 0;
+}
+
+ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
+                                   ArrayRef<CleanupObject> objects)
   : Expr(ExprWithCleanupsClass, subexpr->getType(),
          subexpr->getValueKind(), subexpr->getObjectKind(),
          subexpr->isTypeDependent(), subexpr->isValueDependent(),
          subexpr->isInstantiationDependent(),
          subexpr->containsUnexpandedParameterPack()),
-    SubExpr(subexpr), Temps(0), NumTemps(0) {
-  if (numtemps) {
-    setNumTemporaries(C, numtemps);
-    for (unsigned i =3D 0; i !=3D numtemps; ++i)
-      Temps[i] =3D temps[i];
-  }
+    SubExpr(subexpr) {
+  ExprWithCleanupsBits.NumObjects =3D objects.size();
+  for (unsigned i =3D 0, e =3D objects.size(); i !=3D e; ++i)
+    getObjectsBuffer()[i] =3D objects[i];
 }
=20
-void ExprWithCleanups::setNumTemporaries(ASTContext &C, unsigned N) {
-  assert(Temps =3D=3D 0 && "Cannot resize with this");
-  NumTemps =3D N;
-  Temps =3D new (C) CXXTemporary*[NumTemps];
+ExprWithCleanups *ExprWithCleanups::Create(ASTContext &C, Expr *subexpr,
+                                           ArrayRef<CleanupObject> objects=
) {
+  size_t size =3D sizeof(ExprWithCleanups)
+              + objects.size() * sizeof(CleanupObject);
+  void *buffer =3D C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
+  return new (buffer) ExprWithCleanups(subexpr, objects);
 }
=20
+ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
+  : Expr(ExprWithCleanupsClass, empty) {
+  ExprWithCleanupsBits.NumObjects =3D numObjects;
+}
=20
-ExprWithCleanups *ExprWithCleanups::Create(ASTContext &C,
-                                           Expr *SubExpr,
-                                           CXXTemporary **Temps,
-                                           unsigned NumTemps) {
-  return new (C) ExprWithCleanups(C, SubExpr, Temps, NumTemps);
+ExprWithCleanups *ExprWithCleanups::Create(ASTContext &C, EmptyShell empty,
+                                           unsigned numObjects) {
+  size_t size =3D sizeof(ExprWithCleanups) + numObjects * sizeof(CleanupOb=
ject);
+  void *buffer =3D C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
+  return new (buffer) ExprWithCleanups(empty, numObjects);
 }
=20
 CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(TypeSourceInfo *Typ=
e,
@@ -781,7 +1035,8 @@
                                                  Expr *Base, QualType Base=
Type,
                                                  bool IsArrow,
                                                  SourceLocation OperatorLo=
c,
-                                           NestedNameSpecifierLoc Qualifie=
rLoc,
+                                          NestedNameSpecifierLoc Qualifier=
Loc,
+                                          SourceLocation TemplateKWLoc,
                                           NamedDecl *FirstQualifierFoundIn=
Scope,
                                           DeclarationNameInfo MemberNameIn=
fo,
                                    const TemplateArgumentListInfo *Templat=
eArgs)
@@ -793,7 +1048,7 @@
                                        ->containsUnexpandedParameterPack()=
) ||
           MemberNameInfo.containsUnexpandedParameterPack())),
     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
-    HasExplicitTemplateArgs(TemplateArgs !=3D 0),
+    HasTemplateKWAndArgsInfo(TemplateArgs !=3D 0 || TemplateKWLoc.isValid(=
)),
     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),=20
     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
     MemberNameInfo(MemberNameInfo) {
@@ -801,11 +1056,14 @@
     bool Dependent =3D true;
     bool InstantiationDependent =3D true;
     bool ContainsUnexpandedParameterPack =3D false;
-    getExplicitTemplateArgs().initializeFrom(*TemplateArgs, Dependent,
-                                             InstantiationDependent,
-                                             ContainsUnexpandedParameterPa=
ck);
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArg=
s,
+                                               Dependent,
+                                               InstantiationDependent,
+                                               ContainsUnexpandedParameter=
Pack);
     if (ContainsUnexpandedParameterPack)
       ExprBits.ContainsUnexpandedParameterPack =3D true;
+  } else if (TemplateKWLoc.isValid()) {
+    getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
   }
 }
=20
@@ -824,8 +1082,8 @@
                                          containsUnexpandedParameterPack()=
) ||
           MemberNameInfo.containsUnexpandedParameterPack())),
     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
-    HasExplicitTemplateArgs(false), OperatorLoc(OperatorLoc),
-    QualifierLoc(QualifierLoc),=20
+    HasTemplateKWAndArgsInfo(false),
+    OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
     MemberNameInfo(MemberNameInfo) { }
=20
@@ -834,47 +1092,50 @@
                                 Expr *Base, QualType BaseType, bool IsArro=
w,
                                 SourceLocation OperatorLoc,
                                 NestedNameSpecifierLoc QualifierLoc,
+                                SourceLocation TemplateKWLoc,
                                 NamedDecl *FirstQualifierFoundInScope,
                                 DeclarationNameInfo MemberNameInfo,
                                 const TemplateArgumentListInfo *TemplateAr=
gs) {
-  if (!TemplateArgs)
+  if (!TemplateArgs && !TemplateKWLoc.isValid())
     return new (C) CXXDependentScopeMemberExpr(C, Base, BaseType,
                                                IsArrow, OperatorLoc,
                                                QualifierLoc,
                                                FirstQualifierFoundInScope,
                                                MemberNameInfo);
=20
-  std::size_t size =3D sizeof(CXXDependentScopeMemberExpr);
-  if (TemplateArgs)
-    size +=3D ASTTemplateArgumentListInfo::sizeFor(*TemplateArgs);
+  unsigned NumTemplateArgs =3D TemplateArgs ? TemplateArgs->size() : 0;
+  std::size_t size =3D sizeof(CXXDependentScopeMemberExpr)
+    + ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
=20
   void *Mem =3D C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr=
>());
   return new (Mem) CXXDependentScopeMemberExpr(C, Base, BaseType,
                                                IsArrow, OperatorLoc,
                                                QualifierLoc,
+                                               TemplateKWLoc,
                                                FirstQualifierFoundInScope,
                                                MemberNameInfo, TemplateArg=
s);
 }
=20
 CXXDependentScopeMemberExpr *
 CXXDependentScopeMemberExpr::CreateEmpty(ASTContext &C,
-                                         bool HasExplicitTemplateArgs,
+                                         bool HasTemplateKWAndArgsInfo,
                                          unsigned NumTemplateArgs) {
-  if (!HasExplicitTemplateArgs)
+  if (!HasTemplateKWAndArgsInfo)
     return new (C) CXXDependentScopeMemberExpr(C, 0, QualType(),
-                                               0, SourceLocation(),=20
+                                               0, SourceLocation(),
                                                NestedNameSpecifierLoc(), 0,
                                                DeclarationNameInfo());
=20
   std::size_t size =3D sizeof(CXXDependentScopeMemberExpr) +
-                     ASTTemplateArgumentListInfo::sizeFor(NumTemplateArgs);
+                     ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
   void *Mem =3D C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr=
>());
   CXXDependentScopeMemberExpr *E
     =3D  new (Mem) CXXDependentScopeMemberExpr(C, 0, QualType(),
-                                             0, SourceLocation(),=20
-                                             NestedNameSpecifierLoc(), 0,
+                                             0, SourceLocation(),
+                                             NestedNameSpecifierLoc(),
+                                             SourceLocation(), 0,
                                              DeclarationNameInfo(), 0);
-  E->HasExplicitTemplateArgs =3D true;
+  E->HasTemplateKWAndArgsInfo =3D true;
   return E;
 }
=20
@@ -913,12 +1174,13 @@
                                            bool IsArrow,
                                            SourceLocation OperatorLoc,
                                            NestedNameSpecifierLoc Qualifie=
rLoc,
+                                           SourceLocation TemplateKWLoc,
                                    const DeclarationNameInfo &MemberNameIn=
fo,
                                    const TemplateArgumentListInfo *Templat=
eArgs,
                                            UnresolvedSetIterator Begin,=20
                                            UnresolvedSetIterator End)
-  : OverloadExpr(UnresolvedMemberExprClass, C, QualifierLoc, MemberNameInf=
o,
-                 TemplateArgs, Begin, End,
+  : OverloadExpr(UnresolvedMemberExprClass, C, QualifierLoc, TemplateKWLoc,
+                 MemberNameInfo, TemplateArgs, Begin, End,
                  // Dependent
                  ((Base && Base->isTypeDependent()) ||
                   BaseType->isDependentType()),
@@ -949,31 +1211,34 @@
                              Expr *Base, QualType BaseType, bool IsArrow,
                              SourceLocation OperatorLoc,
                              NestedNameSpecifierLoc QualifierLoc,
+                             SourceLocation TemplateKWLoc,
                              const DeclarationNameInfo &MemberNameInfo,
                              const TemplateArgumentListInfo *TemplateArgs,
                              UnresolvedSetIterator Begin,=20
                              UnresolvedSetIterator End) {
   std::size_t size =3D sizeof(UnresolvedMemberExpr);
   if (TemplateArgs)
-    size +=3D ASTTemplateArgumentListInfo::sizeFor(*TemplateArgs);
+    size +=3D ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
+  else if (TemplateKWLoc.isValid())
+    size +=3D ASTTemplateKWAndArgsInfo::sizeFor(0);
=20
   void *Mem =3D C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
   return new (Mem) UnresolvedMemberExpr(C,=20
                              HasUnresolvedUsing, Base, BaseType,
-                             IsArrow, OperatorLoc, QualifierLoc,
+                             IsArrow, OperatorLoc, QualifierLoc, TemplateK=
WLoc,
                              MemberNameInfo, TemplateArgs, Begin, End);
 }
=20
 UnresolvedMemberExpr *
-UnresolvedMemberExpr::CreateEmpty(ASTContext &C, bool HasExplicitTemplateA=
rgs,
+UnresolvedMemberExpr::CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgs=
Info,
                                   unsigned NumTemplateArgs) {
   std::size_t size =3D sizeof(UnresolvedMemberExpr);
-  if (HasExplicitTemplateArgs)
-    size +=3D ASTTemplateArgumentListInfo::sizeFor(NumTemplateArgs);
+  if (HasTemplateKWAndArgsInfo)
+    size +=3D ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
=20
   void *Mem =3D C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
   UnresolvedMemberExpr *E =3D new (Mem) UnresolvedMemberExpr(EmptyShell());
-  E->HasExplicitTemplateArgs =3D HasExplicitTemplateArgs;
+  E->HasTemplateKWAndArgsInfo =3D HasTemplateKWAndArgsInfo;
   return E;
 }
=20
@@ -1020,4 +1285,51 @@
   return TemplateArgument(Arguments, NumArguments);
 }
=20
+TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kin=
d,
+                             ArrayRef<TypeSourceInfo *> Args,
+                             SourceLocation RParenLoc,
+                             bool Value)
+  : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary,
+         /*TypeDependent=3D*/false,
+         /*ValueDependent=3D*/false,
+         /*InstantiationDependent=3D*/false,
+         /*ContainsUnexpandedParameterPack=3D*/false),
+    Loc(Loc), RParenLoc(RParenLoc)
+{
+  TypeTraitExprBits.Kind =3D Kind;
+  TypeTraitExprBits.Value =3D Value;
+  TypeTraitExprBits.NumArgs =3D Args.size();
=20
+  TypeSourceInfo **ToArgs =3D getTypeSourceInfos();
+ =20
+  for (unsigned I =3D 0, N =3D Args.size(); I !=3D N; ++I) {
+    if (Args[I]->getType()->isDependentType())
+      setValueDependent(true);
+    if (Args[I]->getType()->isInstantiationDependentType())
+      setInstantiationDependent(true);
+    if (Args[I]->getType()->containsUnexpandedParameterPack())
+      setContainsUnexpandedParameterPack(true);
+   =20
+    ToArgs[I] =3D Args[I];
+  }
+}
+
+TypeTraitExpr *TypeTraitExpr::Create(ASTContext &C, QualType T,=20
+                                     SourceLocation Loc,=20
+                                     TypeTrait Kind,
+                                     ArrayRef<TypeSourceInfo *> Args,
+                                     SourceLocation RParenLoc,
+                                     bool Value) {
+  unsigned Size =3D sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * Args=
.size();
+  void *Mem =3D C.Allocate(Size);
+  return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
+}
+
+TypeTraitExpr *TypeTraitExpr::CreateDeserialized(ASTContext &C,
+                                                 unsigned NumArgs) {
+  unsigned Size =3D sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * NumA=
rgs;
+  void *Mem =3D C.Allocate(Size);
+  return new (Mem) TypeTraitExpr(EmptyShell());
+}
+
+void ArrayTypeTraitExpr::anchor() { }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ExprClassification.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ExprClassification.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ExprClassification.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -47,7 +47,6 @@
     return Cl::CL_XValue;
   }
   llvm_unreachable("Invalid value category of implicit cast.");
-  return Cl::CL_PRValue;
 }
=20
 Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const {
@@ -56,7 +55,7 @@
   Cl::Kinds kind =3D ClassifyInternal(Ctx, this);
   // C99 6.3.2.1: An lvalue is an expression with an object type or an
   //   incomplete type other than void.
-  if (!Ctx.getLangOptions().CPlusPlus) {
+  if (!Ctx.getLangOpts().CPlusPlus) {
     // Thus, no functions.
     if (TR->isFunctionType() || TR =3D=3D Ctx.OverloadTy)
       kind =3D Cl::CL_Function;
@@ -90,17 +89,17 @@
=20
 static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
   // This function takes the first stab at classifying expressions.
-  const LangOptions &Lang =3D Ctx.getLangOptions();
+  const LangOptions &Lang =3D Ctx.getLangOpts();
=20
   switch (E->getStmtClass()) {
-    // First come the expressions that are always lvalues, unconditionally.
   case Stmt::NoStmtClass:
 #define ABSTRACT_STMT(Kind)
 #define STMT(Kind, Base) case Expr::Kind##Class:
 #define EXPR(Kind, Base)
 #include "clang/AST/StmtNodes.inc"
     llvm_unreachable("cannot classify a statement");
-    break;
+
+    // First come the expressions that are always lvalues, unconditionally.
   case Expr::ObjCIsaExprClass:
     // C++ [expr.prim.general]p1: A string literal is an lvalue.
   case Expr::StringLiteralClass:
@@ -109,6 +108,7 @@
     // __func__ and friends are too.
   case Expr::PredefinedExprClass:
     // Property references are lvalues
+  case Expr::ObjCSubscriptRefExprClass:
   case Expr::ObjCPropertyRefExprClass:
     // C++ [expr.typeid]p1: The result of a typeid expression is an lvalue=
 of...
   case Expr::CXXTypeidExprClass:
@@ -122,10 +122,11 @@
     // FIXME: ObjC++0x might have different rules
   case Expr::ObjCIvarRefExprClass:
     return Cl::CL_LValue;
+
     // C99 6.5.2.5p5 says that compound literals are lvalues.
     // In C++, they're class temporaries.
   case Expr::CompoundLiteralExprClass:
-    return Ctx.getLangOptions().CPlusPlus? Cl::CL_ClassTemporary=20
+    return Ctx.getLangOpts().CPlusPlus? Cl::CL_ClassTemporary=20
                                          : Cl::CL_LValue;
=20
     // Expressions that are prvalues.
@@ -151,13 +152,17 @@
   case Expr::CXXScalarValueInitExprClass:
   case Expr::UnaryTypeTraitExprClass:
   case Expr::BinaryTypeTraitExprClass:
+  case Expr::TypeTraitExprClass:
   case Expr::ArrayTypeTraitExprClass:
   case Expr::ExpressionTraitExprClass:
   case Expr::ObjCSelectorExprClass:
   case Expr::ObjCProtocolExprClass:
   case Expr::ObjCStringLiteralClass:
+  case Expr::ObjCNumericLiteralClass:
+  case Expr::ObjCArrayLiteralClass:
+  case Expr::ObjCDictionaryLiteralClass:
+  case Expr::ObjCBoolLiteralExprClass:
   case Expr::ParenListExprClass:
-  case Expr::InitListExprClass:
   case Expr::SizeOfPackExprClass:
   case Expr::SubstNonTypeTemplateParmPackExprClass:
   case Expr::AsTypeExprClass:
@@ -184,9 +189,6 @@
       return isa<FunctionDecl>(cast<DeclRefExpr>(E)->getDecl())
                ? Cl::CL_PRValue : Cl::CL_LValue;
     return ClassifyDecl(Ctx, cast<DeclRefExpr>(E)->getDecl());
-    // We deal with names referenced from blocks the same way.
-  case Expr::BlockDeclRefExprClass:
-    return ClassifyDecl(Ctx, cast<BlockDeclRefExpr>(E)->getDecl());
=20
     // Member access is complex.
   case Expr::MemberExprClass:
@@ -229,21 +231,24 @@
     }
=20
   case Expr::OpaqueValueExprClass:
+    return ClassifyExprValueKind(Lang, E, E->getValueKind());
+
+    // Pseudo-object expressions can produce l-values with reference magic.
+  case Expr::PseudoObjectExprClass:
     return ClassifyExprValueKind(Lang, E,
-                                 cast<OpaqueValueExpr>(E)->getValueKind());
+                                 cast<PseudoObjectExpr>(E)->getValueKind()=
);
=20
     // Implicit casts are lvalues if they're lvalue casts. Other than that=
, we
     // only specifically record class temporaries.
   case Expr::ImplicitCastExprClass:
-    return ClassifyExprValueKind(Lang, E,
-                                 cast<ImplicitCastExpr>(E)->getValueKind()=
);
+    return ClassifyExprValueKind(Lang, E, E->getValueKind());
=20
     // C++ [expr.prim.general]p4: The presence of parentheses does not aff=
ect
     //   whether the expression is an lvalue.
   case Expr::ParenExprClass:
     return ClassifyInternal(Ctx, cast<ParenExpr>(E)->getSubExpr());
=20
-    // C1X 6.5.1.1p4: [A generic selection] is an lvalue, a function desig=
nator,
+    // C11 6.5.1.1p4: [A generic selection] is an lvalue, a function desig=
nator,
     // or a void expression if its result expression is, respectively, an
     // lvalue, a function designator, or a void expression.
   case Expr::GenericSelectionExprClass:
@@ -261,6 +266,7 @@
   case Expr::CallExprClass:
   case Expr::CXXOperatorCallExprClass:
   case Expr::CXXMemberCallExprClass:
+  case Expr::UserDefinedLiteralClass:
   case Expr::CUDAKernelCallExprClass:
     return ClassifyUnnamed(Ctx, cast<CallExpr>(E)->getCallReturnType());
=20
@@ -328,35 +334,46 @@
     // Some C++ expressions are always class temporaries.
   case Expr::CXXConstructExprClass:
   case Expr::CXXTemporaryObjectExprClass:
+  case Expr::LambdaExprClass:
     return Cl::CL_ClassTemporary;
=20
   case Expr::VAArgExprClass:
     return ClassifyUnnamed(Ctx, E->getType());
-     =20
+
   case Expr::DesignatedInitExprClass:
     return ClassifyInternal(Ctx, cast<DesignatedInitExpr>(E)->getInit());
-     =20
+
   case Expr::StmtExprClass: {
     const CompoundStmt *S =3D cast<StmtExpr>(E)->getSubStmt();
     if (const Expr *LastExpr =3D dyn_cast_or_null<Expr>(S->body_back()))
       return ClassifyUnnamed(Ctx, LastExpr->getType());
     return Cl::CL_PRValue;
   }
-     =20
+
   case Expr::CXXUuidofExprClass:
     return Cl::CL_LValue;
-     =20
+
   case Expr::PackExpansionExprClass:
     return ClassifyInternal(Ctx, cast<PackExpansionExpr>(E)->getPattern());
-     =20
+
   case Expr::MaterializeTemporaryExprClass:
     return cast<MaterializeTemporaryExpr>(E)->isBoundToLvalueReference()
               ? Cl::CL_LValue=20
               : Cl::CL_XValue;
+
+  case Expr::InitListExprClass:
+    // An init list can be an lvalue if it is bound to a reference and
+    // contains only one element. In that case, we look at that element
+    // for an exact classification. Init list creation takes care of the
+    // value kind for us, so we only need to fine-tune.
+    if (E->isRValue())
+      return ClassifyExprValueKind(Lang, E, E->getValueKind());
+    assert(cast<InitListExpr>(E)->getNumInits() =3D=3D 1 &&
+           "Only 1-element init lists can be glvalues.");
+    return ClassifyInternal(Ctx, cast<InitListExpr>(E)->getInit(0));
   }
- =20
+
   llvm_unreachable("unhandled expression kind in classification");
-  return Cl::CL_LValue;
 }
=20
 /// ClassifyDecl - Return the classification of an expression referencing =
the
@@ -379,7 +396,7 @@
   else
     islvalue =3D isa<VarDecl>(D) || isa<FieldDecl>(D) ||
 	  isa<IndirectFieldDecl>(D) ||
-      (Ctx.getLangOptions().CPlusPlus &&
+      (Ctx.getLangOpts().CPlusPlus &&
         (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)));
=20
   return islvalue ? Cl::CL_LValue : Cl::CL_PRValue;
@@ -390,7 +407,7 @@
 /// calls and casts.
 static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) {
   // In C, function calls are always rvalues.
-  if (!Ctx.getLangOptions().CPlusPlus) return Cl::CL_PRValue;
+  if (!Ctx.getLangOpts().CPlusPlus) return Cl::CL_PRValue;
=20
   // C++ [expr.call]p10: A function call is an lvalue if the result type i=
s an
   //   lvalue reference type or an rvalue reference to function type, an x=
value
@@ -411,7 +428,7 @@
               ? Cl::CL_PRValue : Cl::CL_LValue);
=20
   // Handle C first, it's easier.
-  if (!Ctx.getLangOptions().CPlusPlus) {
+  if (!Ctx.getLangOpts().CPlusPlus) {
     // C99 6.5.2.3p3
     // For dot access, the expression is an lvalue if the first part is. F=
or
     // arrow access, it always is an lvalue.
@@ -463,7 +480,7 @@
 }
=20
 static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E=
) {
-  assert(Ctx.getLangOptions().CPlusPlus &&
+  assert(Ctx.getLangOpts().CPlusPlus &&
          "This is only relevant for C++.");
   // C++ [expr.ass]p1: All [...] return an lvalue referring to the left op=
erand.
   // Except we override this for writes to ObjC properties.
@@ -480,14 +497,16 @@
   //   is a pointer to a data member is of the same value category as its =
first
   //   operand.
   if (E->getOpcode() =3D=3D BO_PtrMemD)
-    return (E->getType()->isFunctionType() || E->getType() =3D=3D Ctx.Boun=
dMemberTy)
+    return (E->getType()->isFunctionType() ||
+            E->hasPlaceholderType(BuiltinType::BoundMember))
              ? Cl::CL_MemberFunction=20
              : ClassifyInternal(Ctx, E->getLHS());
=20
   // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue =
if its
   //   second operand is a pointer to data member and a prvalue otherwise.
   if (E->getOpcode() =3D=3D BO_PtrMemI)
-    return (E->getType()->isFunctionType() || E->getType() =3D=3D Ctx.Boun=
dMemberTy)
+    return (E->getType()->isFunctionType() ||
+            E->hasPlaceholderType(BuiltinType::BoundMember))
              ? Cl::CL_MemberFunction=20
              : Cl::CL_LValue;
=20
@@ -497,7 +516,7 @@
=20
 static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True,
                                      const Expr *False) {
-  assert(Ctx.getLangOptions().CPlusPlus &&
+  assert(Ctx.getLangOpts().CPlusPlus &&
          "This is only relevant for C++.");
=20
   // C++ [expr.cond]p2
@@ -536,18 +555,9 @@
=20
   // This is the lvalue case.
   // Functions are lvalues in C++, but not modifiable. (C++ [basic.lval]p6)
-  if (Ctx.getLangOptions().CPlusPlus && E->getType()->isFunctionType())
+  if (Ctx.getLangOpts().CPlusPlus && E->getType()->isFunctionType())
     return Cl::CM_Function;
=20
-  // You cannot assign to a variable outside a block from within the block=
 if
-  // it is not marked __block, e.g.
-  //   void takeclosure(void (^C)(void));
-  //   void func() { int x =3D 1; takeclosure(^{ x =3D 7; }); }
-  if (const BlockDeclRefExpr *BDR =3D dyn_cast<BlockDeclRefExpr>(E)) {
-    if (!BDR->isByRef() && isa<VarDecl>(BDR->getDecl()))
-      return Cl::CM_NotBlockQualified;
-  }
-
   // Assignment to a property in ObjC is an implicit setter access. But a
   // setter might not exist.
   if (const ObjCPropertyRefExpr *Expr =3D dyn_cast<ObjCPropertyRefExpr>(E)=
) {
@@ -559,6 +569,7 @@
   // Const stuff is obviously not modifiable.
   if (CT.isConstQualified())
     return Cl::CM_ConstQualified;
+
   // Arrays are not modifiable, only their elements are.
   if (CT->isArrayType())
     return Cl::CM_ArrayType;
@@ -569,7 +580,7 @@
   // Records with any const fields (recursively) are not modifiable.
   if (const RecordType *R =3D CT->getAs<RecordType>()) {
     assert((E->getObjectKind() =3D=3D OK_ObjCProperty ||
-            !Ctx.getLangOptions().CPlusPlus) &&
+            !Ctx.getLangOpts().CPlusPlus) &&
            "C++ struct assignment should be resolved by the "
            "copy assignment operator.");
     if (R->hasConstFields())
@@ -624,7 +635,6 @@
   case Cl::CM_Function: return MLV_NotObjectType;
   case Cl::CM_LValueCast:
     llvm_unreachable("CM_LValueCast and CL_LValue don't match");
-  case Cl::CM_NotBlockQualified: return MLV_NotBlockQualified;
   case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty;
   case Cl::CM_ConstQualified: return MLV_ConstQualified;
   case Cl::CM_ArrayType: return MLV_ArrayType;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ExprConstant.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ExprConstant.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -9,6 +9,28 @@
 //
 // This file implements the Expr constant evaluator.
 //
+// Constant expression evaluation produces four main results:
+//
+//  * A success/failure flag indicating whether constant folding was succe=
ssful.
+//    This is the 'bool' return value used by most of the code in this fil=
e. A
+//    'false' return value indicates that constant folding has failed, and=
 any
+//    appropriate diagnostic has already been produced.
+//
+//  * An evaluated result, valid only if constant folding has not failed.
+//
+//  * A flag indicating if evaluation encountered (unevaluated) side-effec=
ts.
+//    These arise in cases such as (sideEffect(), 0) and (sideEffect() || =
1),
+//    where it is possible to determine the evaluated result regardless.
+//
+//  * A set of notes indicating why the evaluation was not a constant expr=
ession
+//    (under the C++11 rules only, at the moment), or, if folding failed t=
oo,
+//    why the expression could not be folded.
+//
+// If we are checking for a potential constant expression, failure to cons=
tant
+// fold a potential constant sub-expression will be indicated by a 'false'
+// return value (the expression could not be folded) and no diagnostic (the
+// expression is not necessarily non-constant).
+//
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/AST/APValue.h"
@@ -23,46 +45,612 @@
 #include "clang/Basic/TargetInfo.h"
 #include "llvm/ADT/SmallString.h"
 #include <cstring>
+#include <functional>
=20
 using namespace clang;
 using llvm::APSInt;
 using llvm::APFloat;
=20
-/// EvalInfo - This is a private struct used by the evaluator to capture
-/// information about a subexpression as it is folded.  It retains informa=
tion
-/// about the AST context, but also maintains information about the folded
-/// expression.
-///
-/// If an expression could be evaluated, it is still possible it is not a C
-/// "integer constant expression" or constant expression.  If not, this st=
ruct
-/// captures information about how and why not.
-///
-/// One bit of information passed *into* the request for constant folding
-/// indicates whether the subexpression is "evaluated" or not according to=
 C
-/// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
-/// evaluate the expression regardless of what the RHS is, but C only allo=
ws
-/// certain things in certain situations.
+static bool IsGlobalLValue(APValue::LValueBase B);
+
 namespace {
+  struct LValue;
+  struct CallStackFrame;
+  struct EvalInfo;
+
+  static QualType getType(APValue::LValueBase B) {
+    if (!B) return QualType();
+    if (const ValueDecl *D =3D B.dyn_cast<const ValueDecl*>())
+      return D->getType();
+    return B.get<const Expr*>()->getType();
+  }
+
+  /// Get an LValue path entry, which is known to not be an array index, a=
s a
+  /// field or base class.
+  static
+  APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
+    APValue::BaseOrMemberType Value;
+    Value.setFromOpaqueValue(E.BaseOrMember);
+    return Value;
+  }
+
+  /// Get an LValue path entry, which is known to not be an array index, a=
s a
+  /// field declaration.
+  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
+    return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
+  }
+  /// Get an LValue path entry, which is known to not be an array index, a=
s a
+  /// base class declaration.
+  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
+    return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
+  }
+  /// Determine whether this LValue path entry for a base class names a vi=
rtual
+  /// base class.
+  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
+    return getAsBaseOrMember(E).getInt();
+  }
+
+  /// Find the path length and type of the most-derived subobject in the g=
iven
+  /// path, and find the size of the containing array, if any.
+  static
+  unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
+                                    ArrayRef<APValue::LValuePathEntry> Pat=
h,
+                                    uint64_t &ArraySize, QualType &Type) {
+    unsigned MostDerivedLength =3D 0;
+    Type =3D Base;
+    for (unsigned I =3D 0, N =3D Path.size(); I !=3D N; ++I) {
+      if (Type->isArrayType()) {
+        const ConstantArrayType *CAT =3D
+          cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
+        Type =3D CAT->getElementType();
+        ArraySize =3D CAT->getSize().getZExtValue();
+        MostDerivedLength =3D I + 1;
+      } else if (Type->isAnyComplexType()) {
+        const ComplexType *CT =3D Type->castAs<ComplexType>();
+        Type =3D CT->getElementType();
+        ArraySize =3D 2;
+        MostDerivedLength =3D I + 1;
+      } else if (const FieldDecl *FD =3D getAsField(Path[I])) {
+        Type =3D FD->getType();
+        ArraySize =3D 0;
+        MostDerivedLength =3D I + 1;
+      } else {
+        // Path[I] describes a base class.
+        ArraySize =3D 0;
+      }
+    }
+    return MostDerivedLength;
+  }
+
+  // The order of this enum is important for diagnostics.
+  enum CheckSubobjectKind {
+    CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
+    CSK_This, CSK_Real, CSK_Imag
+  };
+
+  /// A path from a glvalue to a subobject of that glvalue.
+  struct SubobjectDesignator {
+    /// True if the subobject was named in a manner not supported by C++11=
. Such
+    /// lvalues can still be folded, but they are not core constant expres=
sions
+    /// and we cannot perform lvalue-to-rvalue conversions on them.
+    bool Invalid : 1;
+
+    /// Is this a pointer one past the end of an object?
+    bool IsOnePastTheEnd : 1;
+
+    /// The length of the path to the most-derived object of which this is=
 a
+    /// subobject.
+    unsigned MostDerivedPathLength : 30;
+
+    /// The size of the array of which the most-derived object is an eleme=
nt, or
+    /// 0 if the most-derived object is not an array element.
+    uint64_t MostDerivedArraySize;
+
+    /// The type of the most derived object referred to by this address.
+    QualType MostDerivedType;
+
+    typedef APValue::LValuePathEntry PathEntry;
+
+    /// The entries on the path from the glvalue to the designated subobje=
ct.
+    SmallVector<PathEntry, 8> Entries;
+
+    SubobjectDesignator() : Invalid(true) {}
+
+    explicit SubobjectDesignator(QualType T)
+      : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
+        MostDerivedArraySize(0), MostDerivedType(T) {}
+
+    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
+      : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(fals=
e),
+        MostDerivedPathLength(0), MostDerivedArraySize(0) {
+      if (!Invalid) {
+        IsOnePastTheEnd =3D V.isLValueOnePastTheEnd();
+        ArrayRef<PathEntry> VEntries =3D V.getLValuePath();
+        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
+        if (V.getLValueBase())
+          MostDerivedPathLength =3D
+              findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
+                                       V.getLValuePath(), MostDerivedArray=
Size,
+                                       MostDerivedType);
+      }
+    }
+
+    void setInvalid() {
+      Invalid =3D true;
+      Entries.clear();
+    }
+
+    /// Determine whether this is a one-past-the-end pointer.
+    bool isOnePastTheEnd() const {
+      if (IsOnePastTheEnd)
+        return true;
+      if (MostDerivedArraySize &&
+          Entries[MostDerivedPathLength - 1].ArrayIndex =3D=3D MostDerived=
ArraySize)
+        return true;
+      return false;
+    }
+
+    /// Check that this refers to a valid subobject.
+    bool isValidSubobject() const {
+      if (Invalid)
+        return false;
+      return !isOnePastTheEnd();
+    }
+    /// Check that this refers to a valid subobject, and if not, produce a
+    /// relevant diagnostic and set the designator as invalid.
+    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind =
CSK);
+
+    /// Update this designator to refer to the first element within this a=
rray.
+    void addArrayUnchecked(const ConstantArrayType *CAT) {
+      PathEntry Entry;
+      Entry.ArrayIndex =3D 0;
+      Entries.push_back(Entry);
+
+      // This is a most-derived object.
+      MostDerivedType =3D CAT->getElementType();
+      MostDerivedArraySize =3D CAT->getSize().getZExtValue();
+      MostDerivedPathLength =3D Entries.size();
+    }
+    /// Update this designator to refer to the given base or member of this
+    /// object.
+    void addDeclUnchecked(const Decl *D, bool Virtual =3D false) {
+      PathEntry Entry;
+      APValue::BaseOrMemberType Value(D, Virtual);
+      Entry.BaseOrMember =3D Value.getOpaqueValue();
+      Entries.push_back(Entry);
+
+      // If this isn't a base class, it's a new most-derived object.
+      if (const FieldDecl *FD =3D dyn_cast<FieldDecl>(D)) {
+        MostDerivedType =3D FD->getType();
+        MostDerivedArraySize =3D 0;
+        MostDerivedPathLength =3D Entries.size();
+      }
+    }
+    /// Update this designator to refer to the given complex component.
+    void addComplexUnchecked(QualType EltTy, bool Imag) {
+      PathEntry Entry;
+      Entry.ArrayIndex =3D Imag;
+      Entries.push_back(Entry);
+
+      // This is technically a most-derived object, though in practice this
+      // is unlikely to matter.
+      MostDerivedType =3D EltTy;
+      MostDerivedArraySize =3D 2;
+      MostDerivedPathLength =3D Entries.size();
+    }
+    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t=
 N);
+    /// Add N to the address of this subobject.
+    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
+      if (Invalid) return;
+      if (MostDerivedPathLength =3D=3D Entries.size() && MostDerivedArrayS=
ize) {
+        Entries.back().ArrayIndex +=3D N;
+        if (Entries.back().ArrayIndex > MostDerivedArraySize) {
+          diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
+          setInvalid();
+        }
+        return;
+      }
+      // [expr.add]p4: For the purposes of these operators, a pointer to a
+      // nonarray object behaves the same as a pointer to the first elemen=
t of
+      // an array of length one with the type of the object as its element=
 type.
+      if (IsOnePastTheEnd && N =3D=3D (uint64_t)-1)
+        IsOnePastTheEnd =3D false;
+      else if (!IsOnePastTheEnd && N =3D=3D 1)
+        IsOnePastTheEnd =3D true;
+      else if (N !=3D 0) {
+        diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
+        setInvalid();
+      }
+    }
+  };
+
+  /// A stack frame in the constexpr call stack.
+  struct CallStackFrame {
+    EvalInfo &Info;
+
+    /// Parent - The caller of this stack frame.
+    CallStackFrame *Caller;
+
+    /// CallLoc - The location of the call expression for this call.
+    SourceLocation CallLoc;
+
+    /// Callee - The function which was called.
+    const FunctionDecl *Callee;
+
+    /// Index - The call index of this call.
+    unsigned Index;
+
+    /// This - The binding for the this pointer in this call, if any.
+    const LValue *This;
+
+    /// ParmBindings - Parameter bindings for this function call, indexed =
by
+    /// parameters' function scope indices.
+    const APValue *Arguments;
+
+    typedef llvm::DenseMap<const Expr*, APValue> MapTy;
+    typedef MapTy::const_iterator temp_iterator;
+    /// Temporaries - Temporary lvalues materialized within this stack fra=
me.
+    MapTy Temporaries;
+
+    CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
+                   const FunctionDecl *Callee, const LValue *This,
+                   const APValue *Arguments);
+    ~CallStackFrame();
+  };
+
+  /// A partial diagnostic which we might know in advance that we are not =
going
+  /// to emit.
+  class OptionalDiagnostic {
+    PartialDiagnostic *Diag;
+
+  public:
+    explicit OptionalDiagnostic(PartialDiagnostic *Diag =3D 0) : Diag(Diag=
) {}
+
+    template<typename T>
+    OptionalDiagnostic &operator<<(const T &v) {
+      if (Diag)
+        *Diag << v;
+      return *this;
+    }
+
+    OptionalDiagnostic &operator<<(const APSInt &I) {
+      if (Diag) {
+        llvm::SmallVector<char, 32> Buffer;
+        I.toString(Buffer);
+        *Diag << StringRef(Buffer.data(), Buffer.size());
+      }
+      return *this;
+    }
+
+    OptionalDiagnostic &operator<<(const APFloat &F) {
+      if (Diag) {
+        llvm::SmallVector<char, 32> Buffer;
+        F.toString(Buffer);
+        *Diag << StringRef(Buffer.data(), Buffer.size());
+      }
+      return *this;
+    }
+  };
+
+  /// EvalInfo - This is a private struct used by the evaluator to capture
+  /// information about a subexpression as it is folded.  It retains infor=
mation
+  /// about the AST context, but also maintains information about the fold=
ed
+  /// expression.
+  ///
+  /// If an expression could be evaluated, it is still possible it is not =
a C
+  /// "integer constant expression" or constant expression.  If not, this =
struct
+  /// captures information about how and why not.
+  ///
+  /// One bit of information passed *into* the request for constant folding
+  /// indicates whether the subexpression is "evaluated" or not according =
to C
+  /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We c=
an
+  /// evaluate the expression regardless of what the RHS is, but C only al=
lows
+  /// certain things in certain situations.
   struct EvalInfo {
-    const ASTContext &Ctx;
-
-    /// EvalResult - Contains information about the evaluation.
-    Expr::EvalResult &EvalResult;
+    ASTContext &Ctx;
+
+    /// EvalStatus - Contains information about the evaluation.
+    Expr::EvalStatus &EvalStatus;
+
+    /// CurrentCall - The top of the constexpr call stack.
+    CallStackFrame *CurrentCall;
+
+    /// CallStackDepth - The number of calls in the call stack right now.
+    unsigned CallStackDepth;
+
+    /// NextCallIndex - The next call index to assign.
+    unsigned NextCallIndex;
=20
     typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
+    /// OpaqueValues - Values used as the common expression in a
+    /// BinaryConditionalOperator.
     MapTy OpaqueValues;
+
+    /// BottomFrame - The frame in which evaluation started. This must be
+    /// initialized after CurrentCall and CallStackDepth.
+    CallStackFrame BottomFrame;
+
+    /// EvaluatingDecl - This is the declaration whose initializer is being
+    /// evaluated, if any.
+    const VarDecl *EvaluatingDecl;
+
+    /// EvaluatingDeclValue - This is the value being constructed for the
+    /// declaration whose initializer is being evaluated, if any.
+    APValue *EvaluatingDeclValue;
+
+    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, f=
urther
+    /// notes attached to it will also be stored, otherwise they will not =
be.
+    bool HasActiveDiagnostic;
+
+    /// CheckingPotentialConstantExpression - Are we checking whether the
+    /// expression is a potential constant expression? If so, some diagnos=
tics
+    /// are suppressed.
+    bool CheckingPotentialConstantExpression;
+
+    EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
+      : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
+        CallStackDepth(0), NextCallIndex(1),
+        BottomFrame(*this, SourceLocation(), 0, 0, 0),
+        EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(fal=
se),
+        CheckingPotentialConstantExpression(false) {}
+
     const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
       MapTy::const_iterator i =3D OpaqueValues.find(e);
       if (i =3D=3D OpaqueValues.end()) return 0;
       return &i->second;
     }
=20
-    EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
-      : Ctx(ctx), EvalResult(evalresult) {}
-
-    const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
+    void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
+      EvaluatingDecl =3D VD;
+      EvaluatingDeclValue =3D &Value;
+    }
+
+    const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
+
+    bool CheckCallLimit(SourceLocation Loc) {
+      // Don't perform any constexpr calls (other than the call we're chec=
king)
+      // when checking a potential constant expression.
+      if (CheckingPotentialConstantExpression && CallStackDepth > 1)
+        return false;
+      if (NextCallIndex =3D=3D 0) {
+        // NextCallIndex has wrapped around.
+        Diag(Loc, diag::note_constexpr_call_limit_exceeded);
+        return false;
+      }
+      if (CallStackDepth <=3D getLangOpts().ConstexprCallDepth)
+        return true;
+      Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
+        << getLangOpts().ConstexprCallDepth;
+      return false;
+    }
+
+    CallStackFrame *getCallFrame(unsigned CallIndex) {
+      assert(CallIndex && "no call index in getCallFrame");
+      // We will eventually hit BottomFrame, which has Index 1, so Frame c=
an't
+      // be null in this loop.
+      CallStackFrame *Frame =3D CurrentCall;
+      while (Frame->Index > CallIndex)
+        Frame =3D Frame->Caller;
+      return (Frame->Index =3D=3D CallIndex) ? Frame : 0;
+    }
+
+  private:
+    /// Add a diagnostic to the diagnostics list.
+    PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
+      PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
+      EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
+      return EvalStatus.Diag->back().second;
+    }
+
+    /// Add notes containing a call stack to the current point of evaluati=
on.
+    void addCallStack(unsigned Limit);
+
+  public:
+    /// Diagnose that the evaluation cannot be folded.
+    OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
+                              =3D diag::note_invalid_subexpr_in_const_expr,
+                            unsigned ExtraNotes =3D 0) {
+      // If we have a prior diagnostic, it will be noting that the express=
ion
+      // isn't a constant expression. This diagnostic is more important.
+      // FIXME: We might want to show both diagnostics to the user.
+      if (EvalStatus.Diag) {
+        unsigned CallStackNotes =3D CallStackDepth - 1;
+        unsigned Limit =3D Ctx.getDiagnostics().getConstexprBacktraceLimit=
();
+        if (Limit)
+          CallStackNotes =3D std::min(CallStackNotes, Limit + 1);
+        if (CheckingPotentialConstantExpression)
+          CallStackNotes =3D 0;
+
+        HasActiveDiagnostic =3D true;
+        EvalStatus.Diag->clear();
+        EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
+        addDiag(Loc, DiagId);
+        if (!CheckingPotentialConstantExpression)
+          addCallStack(Limit);
+        return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
+      }
+      HasActiveDiagnostic =3D false;
+      return OptionalDiagnostic();
+    }
+
+    OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
+                              =3D diag::note_invalid_subexpr_in_const_expr,
+                            unsigned ExtraNotes =3D 0) {
+      if (EvalStatus.Diag)
+        return Diag(E->getExprLoc(), DiagId, ExtraNotes);
+      HasActiveDiagnostic =3D false;
+      return OptionalDiagnostic();
+    }
+
+    /// Diagnose that the evaluation does not produce a C++11 core constant
+    /// expression.
+    template<typename LocArg>
+    OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
+                                 =3D diag::note_invalid_subexpr_in_const_e=
xpr,
+                               unsigned ExtraNotes =3D 0) {
+      // Don't override a previous diagnostic.
+      if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
+        HasActiveDiagnostic =3D false;
+        return OptionalDiagnostic();
+      }
+      return Diag(Loc, DiagId, ExtraNotes);
+    }
+
+    /// Add a note to a prior diagnostic.
+    OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
+      if (!HasActiveDiagnostic)
+        return OptionalDiagnostic();
+      return OptionalDiagnostic(&addDiag(Loc, DiagId));
+    }
+
+    /// Add a stack of notes to a prior diagnostic.
+    void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
+      if (HasActiveDiagnostic) {
+        EvalStatus.Diag->insert(EvalStatus.Diag->end(),
+                                Diags.begin(), Diags.end());
+      }
+    }
+
+    /// Should we continue evaluation as much as possible after encounteri=
ng a
+    /// construct which can't be folded?
+    bool keepEvaluatingAfterFailure() {
+      return CheckingPotentialConstantExpression &&
+             EvalStatus.Diag && EvalStatus.Diag->empty();
+    }
   };
=20
+  /// Object used to treat all foldable expressions as constant expression=
s.
+  struct FoldConstant {
+    bool Enabled;
+
+    explicit FoldConstant(EvalInfo &Info)
+      : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
+                !Info.EvalStatus.HasSideEffects) {
+    }
+    // Treat the value we've computed since this object was created as con=
stant.
+    void Fold(EvalInfo &Info) {
+      if (Enabled && !Info.EvalStatus.Diag->empty() &&
+          !Info.EvalStatus.HasSideEffects)
+        Info.EvalStatus.Diag->clear();
+    }
+  };
+
+  /// RAII object used to suppress diagnostics and side-effects from a
+  /// speculative evaluation.
+  class SpeculativeEvaluationRAII {
+    EvalInfo &Info;
+    Expr::EvalStatus Old;
+
+  public:
+    SpeculativeEvaluationRAII(EvalInfo &Info,
+                              llvm::SmallVectorImpl<PartialDiagnosticAt>
+                                *NewDiag =3D 0)
+      : Info(Info), Old(Info.EvalStatus) {
+      Info.EvalStatus.Diag =3D NewDiag;
+    }
+    ~SpeculativeEvaluationRAII() {
+      Info.EvalStatus =3D Old;
+    }
+  };
+}
+
+bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
+                                         CheckSubobjectKind CSK) {
+  if (Invalid)
+    return false;
+  if (isOnePastTheEnd()) {
+    Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
+      << CSK;
+    setInvalid();
+    return false;
+  }
+  return true;
+}
+
+void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
+                                                    const Expr *E, uint64_=
t N) {
+  if (MostDerivedPathLength =3D=3D Entries.size() && MostDerivedArraySize)
+    Info.CCEDiag(E, diag::note_constexpr_array_index)
+      << static_cast<int>(N) << /*array*/ 0
+      << static_cast<unsigned>(MostDerivedArraySize);
+  else
+    Info.CCEDiag(E, diag::note_constexpr_array_index)
+      << static_cast<int>(N) << /*non-array*/ 1;
+  setInvalid();
+}
+
+CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
+                               const FunctionDecl *Callee, const LValue *T=
his,
+                               const APValue *Arguments)
+    : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Calle=
e),
+      Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
+  Info.CurrentCall =3D this;
+  ++Info.CallStackDepth;
+}
+
+CallStackFrame::~CallStackFrame() {
+  assert(Info.CurrentCall =3D=3D this && "calls retired out of order");
+  --Info.CallStackDepth;
+  Info.CurrentCall =3D Caller;
+}
+
+/// Produce a string describing the given constexpr call.
+static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
+  unsigned ArgIndex =3D 0;
+  bool IsMemberCall =3D isa<CXXMethodDecl>(Frame->Callee) &&
+                      !isa<CXXConstructorDecl>(Frame->Callee) &&
+                      cast<CXXMethodDecl>(Frame->Callee)->isInstance();
+
+  if (!IsMemberCall)
+    Out << *Frame->Callee << '(';
+
+  for (FunctionDecl::param_const_iterator I =3D Frame->Callee->param_begin=
(),
+       E =3D Frame->Callee->param_end(); I !=3D E; ++I, ++ArgIndex) {
+    if (ArgIndex > (unsigned)IsMemberCall)
+      Out << ", ";
+
+    const ParmVarDecl *Param =3D *I;
+    const APValue &Arg =3D Frame->Arguments[ArgIndex];
+    Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
+
+    if (ArgIndex =3D=3D 0 && IsMemberCall)
+      Out << "->" << *Frame->Callee << '(';
+  }
+
+  Out << ')';
+}
+
+void EvalInfo::addCallStack(unsigned Limit) {
+  // Determine which calls to skip, if any.
+  unsigned ActiveCalls =3D CallStackDepth - 1;
+  unsigned SkipStart =3D ActiveCalls, SkipEnd =3D SkipStart;
+  if (Limit && Limit < ActiveCalls) {
+    SkipStart =3D Limit / 2 + Limit % 2;
+    SkipEnd =3D ActiveCalls - Limit / 2;
+  }
+
+  // Walk the call stack and add the diagnostics.
+  unsigned CallIdx =3D 0;
+  for (CallStackFrame *Frame =3D CurrentCall; Frame !=3D &BottomFrame;
+       Frame =3D Frame->Caller, ++CallIdx) {
+    // Skip this call?
+    if (CallIdx >=3D SkipStart && CallIdx < SkipEnd) {
+      if (CallIdx =3D=3D SkipStart) {
+        // Note that we're skipping calls.
+        addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
+          << unsigned(ActiveCalls - Limit);
+      }
+      continue;
+    }
+
+    llvm::SmallVector<char, 128> Buffer;
+    llvm::raw_svector_ostream Out(Buffer);
+    describeCall(Frame, Out);
+    addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
+  }
+}
+
+namespace {
   struct ComplexValue {
   private:
     bool IsInt;
@@ -104,28 +692,203 @@
   };
=20
   struct LValue {
-    const Expr *Base;
+    APValue::LValueBase Base;
     CharUnits Offset;
-
-    const Expr *getLValueBase() { return Base; }
-    CharUnits getLValueOffset() { return Offset; }
-
-    void moveInto(APValue &v) const {
-      v =3D APValue(Base, Offset);
-    }
-    void setFrom(const APValue &v) {
-      assert(v.isLValue());
-      Base =3D v.getLValueBase();
-      Offset =3D v.getLValueOffset();
+    unsigned CallIndex;
+    SubobjectDesignator Designator;
+
+    const APValue::LValueBase getLValueBase() const { return Base; }
+    CharUnits &getLValueOffset() { return Offset; }
+    const CharUnits &getLValueOffset() const { return Offset; }
+    unsigned getLValueCallIndex() const { return CallIndex; }
+    SubobjectDesignator &getLValueDesignator() { return Designator; }
+    const SubobjectDesignator &getLValueDesignator() const { return Design=
ator;}
+
+    void moveInto(APValue &V) const {
+      if (Designator.Invalid)
+        V =3D APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
+      else
+        V =3D APValue(Base, Offset, Designator.Entries,
+                    Designator.IsOnePastTheEnd, CallIndex);
+    }
+    void setFrom(ASTContext &Ctx, const APValue &V) {
+      assert(V.isLValue());
+      Base =3D V.getLValueBase();
+      Offset =3D V.getLValueOffset();
+      CallIndex =3D V.getLValueCallIndex();
+      Designator =3D SubobjectDesignator(Ctx, V);
+    }
+
+    void set(APValue::LValueBase B, unsigned I =3D 0) {
+      Base =3D B;
+      Offset =3D CharUnits::Zero();
+      CallIndex =3D I;
+      Designator =3D SubobjectDesignator(getType(B));
+    }
+
+    // Check that this LValue is not based on a null pointer. If it is, pr=
oduce
+    // a diagnostic and mark the designator as invalid.
+    bool checkNullPointer(EvalInfo &Info, const Expr *E,
+                          CheckSubobjectKind CSK) {
+      if (Designator.Invalid)
+        return false;
+      if (!Base) {
+        Info.CCEDiag(E, diag::note_constexpr_null_subobject)
+          << CSK;
+        Designator.setInvalid();
+        return false;
+      }
+      return true;
+    }
+
+    // Check this LValue refers to an object. If not, set the designator t=
o be
+    // invalid and emit a diagnostic.
+    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind =
CSK) {
+      // Outside C++11, do not build a designator referring to a subobject=
 of
+      // any object: we won't use such a designator for anything.
+      if (!Info.getLangOpts().CPlusPlus0x)
+        Designator.setInvalid();
+      return checkNullPointer(Info, E, CSK) &&
+             Designator.checkSubobject(Info, E, CSK);
+    }
+
+    void addDecl(EvalInfo &Info, const Expr *E,
+                 const Decl *D, bool Virtual =3D false) {
+      if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base=
))
+        Designator.addDeclUnchecked(D, Virtual);
+    }
+    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *=
CAT) {
+      if (checkSubobject(Info, E, CSK_ArrayToPointer))
+        Designator.addArrayUnchecked(CAT);
+    }
+    void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Im=
ag) {
+      if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
+        Designator.addComplexUnchecked(EltTy, Imag);
+    }
+    void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
+      if (checkNullPointer(Info, E, CSK_ArrayIndex))
+        Designator.adjustIndex(Info, E, N);
     }
   };
-}
-
-static bool Evaluate(EvalInfo &info, const Expr *E);
+
+  struct MemberPtr {
+    MemberPtr() {}
+    explicit MemberPtr(const ValueDecl *Decl) :
+      DeclAndIsDerivedMember(Decl, false), Path() {}
+
+    /// The member or (direct or indirect) field referred to by this member
+    /// pointer, or 0 if this is a null member pointer.
+    const ValueDecl *getDecl() const {
+      return DeclAndIsDerivedMember.getPointer();
+    }
+    /// Is this actually a member of some type derived from the relevant c=
lass?
+    bool isDerivedMember() const {
+      return DeclAndIsDerivedMember.getInt();
+    }
+    /// Get the class which the declaration actually lives in.
+    const CXXRecordDecl *getContainingRecord() const {
+      return cast<CXXRecordDecl>(
+          DeclAndIsDerivedMember.getPointer()->getDeclContext());
+    }
+
+    void moveInto(APValue &V) const {
+      V =3D APValue(getDecl(), isDerivedMember(), Path);
+    }
+    void setFrom(const APValue &V) {
+      assert(V.isMemberPointer());
+      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
+      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
+      Path.clear();
+      ArrayRef<const CXXRecordDecl*> P =3D V.getMemberPointerPath();
+      Path.insert(Path.end(), P.begin(), P.end());
+    }
+
+    /// DeclAndIsDerivedMember - The member declaration, and a flag indica=
ting
+    /// whether the member is a member of some class derived from the clas=
s type
+    /// of the member pointer.
+    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
+    /// Path - The path of base/derived classes from the member declaratio=
n's
+    /// class (exclusive) to the class type of the member pointer (inclusi=
ve).
+    SmallVector<const CXXRecordDecl*, 4> Path;
+
+    /// Perform a cast towards the class of the Decl (either up or down the
+    /// hierarchy).
+    bool castBack(const CXXRecordDecl *Class) {
+      assert(!Path.empty());
+      const CXXRecordDecl *Expected;
+      if (Path.size() >=3D 2)
+        Expected =3D Path[Path.size() - 2];
+      else
+        Expected =3D getContainingRecord();
+      if (Expected->getCanonicalDecl() !=3D Class->getCanonicalDecl()) {
+        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B:=
:*),
+        // if B does not contain the original member and is not a base or
+        // derived class of the class containing the original member, the =
result
+        // of the cast is undefined.
+        // C++11 [conv.mem]p2 does not cover this case for a cast from (B:=
:*) to
+        // (D::*). We consider that to be a language defect.
+        return false;
+      }
+      Path.pop_back();
+      return true;
+    }
+    /// Perform a base-to-derived member pointer cast.
+    bool castToDerived(const CXXRecordDecl *Derived) {
+      if (!getDecl())
+        return true;
+      if (!isDerivedMember()) {
+        Path.push_back(Derived);
+        return true;
+      }
+      if (!castBack(Derived))
+        return false;
+      if (Path.empty())
+        DeclAndIsDerivedMember.setInt(false);
+      return true;
+    }
+    /// Perform a derived-to-base member pointer cast.
+    bool castToBase(const CXXRecordDecl *Base) {
+      if (!getDecl())
+        return true;
+      if (Path.empty())
+        DeclAndIsDerivedMember.setInt(true);
+      if (isDerivedMember()) {
+        Path.push_back(Base);
+        return true;
+      }
+      return castBack(Base);
+    }
+  };
+
+  /// Compare two member pointers, which are assumed to be of the same typ=
e.
+  static bool operator=3D=3D(const MemberPtr &LHS, const MemberPtr &RHS) {
+    if (!LHS.getDecl() || !RHS.getDecl())
+      return !LHS.getDecl() && !RHS.getDecl();
+    if (LHS.getDecl()->getCanonicalDecl() !=3D RHS.getDecl()->getCanonical=
Decl())
+      return false;
+    return LHS.Path =3D=3D RHS.Path;
+  }
+
+  /// Kinds of constant expression checking, for diagnostics.
+  enum CheckConstantExpressionKind {
+    CCEK_Constant,    ///< A normal constant.
+    CCEK_ReturnValue, ///< A constexpr function return value.
+    CCEK_MemberInit   ///< A constexpr constructor mem-initializer.
+  };
+}
+
+static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
+static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
+                            const LValue &This, const Expr *E,
+                            CheckConstantExpressionKind CCEK =3D CCEK_Cons=
tant,
+                            bool AllowNonLiteralTypes =3D false);
 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
+static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
+                                  EvalInfo &Info);
+static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Inf=
o);
 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info=
);
-static bool EvaluateIntegerOrLValue(const Expr *E, APValue  &Result,
+static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
                                     EvalInfo &Info);
 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &In=
fo);
@@ -134,116 +897,306 @@
 // Misc utilities
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-static bool IsGlobalLValue(const Expr* E) {
-  if (!E) return true;
-
-  if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E)) {
-    if (isa<FunctionDecl>(DRE->getDecl()))
+/// Should this call expression be treated as a string literal?
+static bool IsStringLiteralCall(const CallExpr *E) {
+  unsigned Builtin =3D E->isBuiltinCall();
+  return (Builtin =3D=3D Builtin::BI__builtin___CFStringMakeConstantString=
 ||
+          Builtin =3D=3D Builtin::BI__builtin___NSStringMakeConstantString=
);
+}
+
+static bool IsGlobalLValue(APValue::LValueBase B) {
+  // C++11 [expr.const]p3 An address constant expression is a prvalue core
+  // constant expression of pointer type that evaluates to...
+
+  // ... a null pointer value, or a prvalue core constant expression of ty=
pe
+  // std::nullptr_t.
+  if (!B) return true;
+
+  if (const ValueDecl *D =3D B.dyn_cast<const ValueDecl*>()) {
+    // ... the address of an object with static storage duration,
+    if (const VarDecl *VD =3D dyn_cast<VarDecl>(D))
+      return VD->hasGlobalStorage();
+    // ... the address of a function,
+    return isa<FunctionDecl>(D);
+  }
+
+  const Expr *E =3D B.get<const Expr*>();
+  switch (E->getStmtClass()) {
+  default:
+    return false;
+  case Expr::CompoundLiteralExprClass: {
+    const CompoundLiteralExpr *CLE =3D cast<CompoundLiteralExpr>(E);
+    return CLE->isFileScope() && CLE->isLValue();
+  }
+  // A string literal has static storage duration.
+  case Expr::StringLiteralClass:
+  case Expr::PredefinedExprClass:
+  case Expr::ObjCStringLiteralClass:
+  case Expr::ObjCEncodeExprClass:
+  case Expr::CXXTypeidExprClass:
+    return true;
+  case Expr::CallExprClass:
+    return IsStringLiteralCall(cast<CallExpr>(E));
+  // For GCC compatibility, &&label has static storage duration.
+  case Expr::AddrLabelExprClass:
+    return true;
+  // A Block literal expression may be used as the initialization value for
+  // Block variables at global or local static scope.
+  case Expr::BlockExprClass:
+    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
+  case Expr::ImplicitValueInitExprClass:
+    // FIXME:
+    // We can never form an lvalue with an implicit value initialization a=
s its
+    // base through expression evaluation, so these only appear in one cas=
e: the
+    // implicit variable declaration we invent when checking whether a con=
stexpr
+    // constructor can produce a constant expression. We must assume that =
such
+    // an expression might be a global lvalue.
+    return true;
+  }
+}
+
+static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
+  assert(Base && "no location for a null lvalue");
+  const ValueDecl *VD =3D Base.dyn_cast<const ValueDecl*>();
+  if (VD)
+    Info.Note(VD->getLocation(), diag::note_declared_at);
+  else
+    Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
+              diag::note_constexpr_temporary_here);
+}
+
+/// Check that this reference or pointer core constant expression is a val=
id
+/// value for an address or reference constant expression. Return true if =
we
+/// can fold this expression, whether or not it's a constant expression.
+static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation L=
oc,
+                                          QualType Type, const LValue &LVa=
l) {
+  bool IsReferenceType =3D Type->isReferenceType();
+
+  APValue::LValueBase Base =3D LVal.getLValueBase();
+  const SubobjectDesignator &Designator =3D LVal.getLValueDesignator();
+
+  // Check that the object is a global. Note that the fake 'this' object we
+  // manufacture when checking potential constant expressions is conservat=
ively
+  // assumed to be global here.
+  if (!IsGlobalLValue(Base)) {
+    if (Info.getLangOpts().CPlusPlus0x) {
+      const ValueDecl *VD =3D Base.dyn_cast<const ValueDecl*>();
+      Info.Diag(Loc, diag::note_constexpr_non_global, 1)
+        << IsReferenceType << !Designator.Entries.empty()
+        << !!VD << VD;
+      NoteLValueLocation(Info, Base);
+    } else {
+      Info.Diag(Loc);
+    }
+    // Don't allow references to temporaries to escape.
+    return false;
+  }
+  assert((Info.CheckingPotentialConstantExpression ||
+          LVal.getLValueCallIndex() =3D=3D 0) &&
+         "have call index for global lvalue");
+
+  // Allow address constant expressions to be past-the-end pointers. This =
is
+  // an extension: the standard requires them to point to an object.
+  if (!IsReferenceType)
+    return true;
+
+  // A reference constant expression must refer to an object.
+  if (!Base) {
+    // FIXME: diagnostic
+    Info.CCEDiag(Loc);
+    return true;
+  }
+
+  // Does this refer one past the end of some object?
+  if (Designator.isOnePastTheEnd()) {
+    const ValueDecl *VD =3D Base.dyn_cast<const ValueDecl*>();
+    Info.Diag(Loc, diag::note_constexpr_past_end, 1)
+      << !Designator.Entries.empty() << !!VD << VD;
+    NoteLValueLocation(Info, Base);
+  }
+
+  return true;
+}
+
+/// Check that this core constant expression is of literal type, and if no=
t,
+/// produce an appropriate diagnostic.
+static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
+  if (!E->isRValue() || E->getType()->isLiteralType())
+    return true;
+
+  // Prvalue constant expressions must be of literal types.
+  if (Info.getLangOpts().CPlusPlus0x)
+    Info.Diag(E, diag::note_constexpr_nonliteral)
+      << E->getType();
+  else
+    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+  return false;
+}
+
+/// Check that this core constant expression value is a valid value for a
+/// constant expression. If not, report an appropriate diagnostic. Does not
+/// check that the expression is of literal type.
+static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
+                                    QualType Type, const APValue &Value) {
+  // Core issue 1454: For a literal constant expression of array or class =
type,
+  // each subobject of its value shall have been initialized by a constant
+  // expression.
+  if (Value.isArray()) {
+    QualType EltTy =3D Type->castAsArrayTypeUnsafe()->getElementType();
+    for (unsigned I =3D 0, N =3D Value.getArrayInitializedElts(); I !=3D N=
; ++I) {
+      if (!CheckConstantExpression(Info, DiagLoc, EltTy,
+                                   Value.getArrayInitializedElt(I)))
+        return false;
+    }
+    if (!Value.hasArrayFiller())
       return true;
-    if (const VarDecl *VD =3D dyn_cast<VarDecl>(DRE->getDecl()))
-      return VD->hasGlobalStorage();
-    return false;
-  }
-
-  if (const CompoundLiteralExpr *CLE =3D dyn_cast<CompoundLiteralExpr>(E))
-    return CLE->isFileScope();
-
+    return CheckConstantExpression(Info, DiagLoc, EltTy,
+                                   Value.getArrayFiller());
+  }
+  if (Value.isUnion() && Value.getUnionField()) {
+    return CheckConstantExpression(Info, DiagLoc,
+                                   Value.getUnionField()->getType(),
+                                   Value.getUnionValue());
+  }
+  if (Value.isStruct()) {
+    RecordDecl *RD =3D Type->castAs<RecordType>()->getDecl();
+    if (const CXXRecordDecl *CD =3D dyn_cast<CXXRecordDecl>(RD)) {
+      unsigned BaseIndex =3D 0;
+      for (CXXRecordDecl::base_class_const_iterator I =3D CD->bases_begin(=
),
+             End =3D CD->bases_end(); I !=3D End; ++I, ++BaseIndex) {
+        if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
+                                     Value.getStructBase(BaseIndex)))
+          return false;
+      }
+    }
+    for (RecordDecl::field_iterator I =3D RD->field_begin(), E =3D RD->fie=
ld_end();
+         I !=3D E; ++I) {
+      if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
+                                   Value.getStructField((*I)->getFieldInde=
x())))
+        return false;
+    }
+  }
+
+  if (Value.isLValue()) {
+    LValue LVal;
+    LVal.setFrom(Info.Ctx, Value);
+    return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
+  }
+
+  // Everything else is fine.
   return true;
 }
=20
-static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
-  const Expr* Base =3D Value.Base;
-
+const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
+  return LVal.Base.dyn_cast<const ValueDecl*>();
+}
+
+static bool IsLiteralLValue(const LValue &Value) {
+  return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
+}
+
+static bool IsWeakLValue(const LValue &Value) {
+  const ValueDecl *Decl =3D GetLValueBaseDecl(Value);
+  return Decl && Decl->isWeak();
+}
+
+static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
   // A null base expression indicates a null pointer.  These are always
   // evaluatable, and they are false unless the offset is zero.
-  if (!Base) {
-    Result =3D !Value.Offset.isZero();
+  if (!Value.getLValueBase()) {
+    Result =3D !Value.getLValueOffset().isZero();
     return true;
   }
=20
-  // Require the base expression to be a global l-value.
-  if (!IsGlobalLValue(Base)) return false;
-
-  // We have a non-null base expression.  These are generally known to
-  // be true, but if it'a decl-ref to a weak symbol it can be null at
-  // runtime.
+  // We have a non-null base.  These are generally known to be true, but i=
f it's
+  // a weak declaration it can be null at runtime.
   Result =3D true;
-
-  const DeclRefExpr* DeclRef =3D dyn_cast<DeclRefExpr>(Base);
-  if (!DeclRef)
+  const ValueDecl *Decl =3D Value.getLValueBase().dyn_cast<const ValueDecl=
*>();
+  return !Decl || !Decl->isWeak();
+}
+
+static bool HandleConversionToBool(const APValue &Val, bool &Result) {
+  switch (Val.getKind()) {
+  case APValue::Uninitialized:
+    return false;
+  case APValue::Int:
+    Result =3D Val.getInt().getBoolValue();
     return true;
-
-  // If it's a weak symbol, it isn't constant-evaluable.
-  const ValueDecl* Decl =3D DeclRef->getDecl();
-  if (Decl->hasAttr<WeakAttr>() ||
-      Decl->hasAttr<WeakRefAttr>() ||
-      Decl->isWeakImported())
+  case APValue::Float:
+    Result =3D !Val.getFloat().isZero();
+    return true;
+  case APValue::ComplexInt:
+    Result =3D Val.getComplexIntReal().getBoolValue() ||
+             Val.getComplexIntImag().getBoolValue();
+    return true;
+  case APValue::ComplexFloat:
+    Result =3D !Val.getComplexFloatReal().isZero() ||
+             !Val.getComplexFloatImag().isZero();
+    return true;
+  case APValue::LValue:
+    return EvalPointerValueAsBool(Val, Result);
+  case APValue::MemberPointer:
+    Result =3D Val.getMemberPointerDecl();
+    return true;
+  case APValue::Vector:
+  case APValue::Array:
+  case APValue::Struct:
+  case APValue::Union:
+  case APValue::AddrLabelDiff:
     return false;
-
-  return true;
-}
-
-static bool HandleConversionToBool(const Expr* E, bool& Result,
-                                   EvalInfo &Info) {
-  if (E->getType()->isIntegralOrEnumerationType()) {
-    APSInt IntResult;
-    if (!EvaluateInteger(E, IntResult, Info))
-      return false;
-    Result =3D IntResult !=3D 0;
-    return true;
-  } else if (E->getType()->isRealFloatingType()) {
-    APFloat FloatResult(0.0);
-    if (!EvaluateFloat(E, FloatResult, Info))
-      return false;
-    Result =3D !FloatResult.isZero();
-    return true;
-  } else if (E->getType()->hasPointerRepresentation()) {
-    LValue PointerResult;
-    if (!EvaluatePointer(E, PointerResult, Info))
-      return false;
-    return EvalPointerValueAsBool(PointerResult, Result);
-  } else if (E->getType()->isAnyComplexType()) {
-    ComplexValue ComplexResult;
-    if (!EvaluateComplex(E, ComplexResult, Info))
-      return false;
-    if (ComplexResult.isComplexFloat()) {
-      Result =3D !ComplexResult.getComplexFloatReal().isZero() ||
-               !ComplexResult.getComplexFloatImag().isZero();
-    } else {
-      Result =3D ComplexResult.getComplexIntReal().getBoolValue() ||
-               ComplexResult.getComplexIntImag().getBoolValue();
-    }
-    return true;
-  }
-
+  }
+
+  llvm_unreachable("unknown APValue kind");
+}
+
+static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
+                                       EvalInfo &Info) {
+  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition=
");
+  APValue Val;
+  if (!Evaluate(Val, Info, E))
+    return false;
+  return HandleConversionToBool(Val, Result);
+}
+
+template<typename T>
+static bool HandleOverflow(EvalInfo &Info, const Expr *E,
+                           const T &SrcValue, QualType DestType) {
+  Info.Diag(E, diag::note_constexpr_overflow)
+    << SrcValue << DestType;
   return false;
 }
=20
-static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
-                                   APFloat &Value, const ASTContext &Ctx) {
-  unsigned DestWidth =3D Ctx.getIntWidth(DestType);
+static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
+                                 QualType SrcType, const APFloat &Value,
+                                 QualType DestType, APSInt &Result) {
+  unsigned DestWidth =3D Info.Ctx.getIntWidth(DestType);
   // Determine whether we are converting to unsigned or signed.
   bool DestSigned =3D DestType->isSignedIntegerOrEnumerationType();
=20
-  // FIXME: Warning for overflow.
-  APSInt Result(DestWidth, !DestSigned);
+  Result =3D APSInt(DestWidth, !DestSigned);
   bool ignored;
-  (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignor=
ed);
-  return Result;
-}
-
-static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
-                                      APFloat &Value, const ASTContext &Ct=
x) {
+  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
+      & APFloat::opInvalidOp)
+    return HandleOverflow(Info, E, Value, DestType);
+  return true;
+}
+
+static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
+                                   QualType SrcType, QualType DestType,
+                                   APFloat &Result) {
+  APFloat Value =3D Result;
   bool ignored;
-  APFloat Result =3D Value;
-  Result.convert(Ctx.getFloatTypeSemantics(DestType),
-                 APFloat::rmNearestTiesToEven, &ignored);
-  return Result;
-}
-
-static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
-                                 APSInt &Value, const ASTContext &Ctx) {
-  unsigned DestWidth =3D Ctx.getIntWidth(DestType);
+  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
+                     APFloat::rmNearestTiesToEven, &ignored)
+      & APFloat::opOverflow)
+    return HandleOverflow(Info, E, Value, DestType);
+  return true;
+}
+
+static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
+                                 QualType DestType, QualType SrcType,
+                                 APSInt &Value) {
+  unsigned DestWidth =3D Info.Ctx.getIntWidth(DestType);
   APSInt Result =3D Value;
   // Figure out if this is a truncate, extend or noop cast.
   // If the input is signed, do a sign extend, noop, or truncate.
@@ -252,22 +1205,1071 @@
   return Result;
 }
=20
-static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
-                                    APSInt &Value, const ASTContext &Ctx) {
-
-  APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
-  Result.convertFromAPInt(Value, Value.isSigned(),
-                          APFloat::rmNearestTiesToEven);
-  return Result;
+static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
+                                 QualType SrcType, const APSInt &Value,
+                                 QualType DestType, APFloat &Result) {
+  Result =3D APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
+  if (Result.convertFromAPInt(Value, Value.isSigned(),
+                              APFloat::rmNearestTiesToEven)
+      & APFloat::opOverflow)
+    return HandleOverflow(Info, E, Value, DestType);
+  return true;
+}
+
+static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
+                                  llvm::APInt &Res) {
+  APValue SVal;
+  if (!Evaluate(SVal, Info, E))
+    return false;
+  if (SVal.isInt()) {
+    Res =3D SVal.getInt();
+    return true;
+  }
+  if (SVal.isFloat()) {
+    Res =3D SVal.getFloat().bitcastToAPInt();
+    return true;
+  }
+  if (SVal.isVector()) {
+    QualType VecTy =3D E->getType();
+    unsigned VecSize =3D Info.Ctx.getTypeSize(VecTy);
+    QualType EltTy =3D VecTy->castAs<VectorType>()->getElementType();
+    unsigned EltSize =3D Info.Ctx.getTypeSize(EltTy);
+    bool BigEndian =3D Info.Ctx.getTargetInfo().isBigEndian();
+    Res =3D llvm::APInt::getNullValue(VecSize);
+    for (unsigned i =3D 0; i < SVal.getVectorLength(); i++) {
+      APValue &Elt =3D SVal.getVectorElt(i);
+      llvm::APInt EltAsInt;
+      if (Elt.isInt()) {
+        EltAsInt =3D Elt.getInt();
+      } else if (Elt.isFloat()) {
+        EltAsInt =3D Elt.getFloat().bitcastToAPInt();
+      } else {
+        // Don't try to handle vectors of anything other than int or float
+        // (not sure if it's possible to hit this case).
+        Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+        return false;
+      }
+      unsigned BaseEltSize =3D EltAsInt.getBitWidth();
+      if (BigEndian)
+        Res |=3D EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
+      else
+        Res |=3D EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
+    }
+    return true;
+  }
+  // Give up if the input isn't an int, float, or vector.  For example, we
+  // reject "(v4i16)(intptr_t)&a".
+  Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+  return false;
+}
+
+/// Cast an lvalue referring to a base subobject to a derived class, by
+/// truncating the lvalue's path to the given length.
+static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Resu=
lt,
+                               const RecordDecl *TruncatedType,
+                               unsigned TruncatedElements) {
+  SubobjectDesignator &D =3D Result.Designator;
+
+  // Check we actually point to a derived class object.
+  if (TruncatedElements =3D=3D D.Entries.size())
+    return true;
+  assert(TruncatedElements >=3D D.MostDerivedPathLength &&
+         "not casting to a derived class");
+  if (!Result.checkSubobject(Info, E, CSK_Derived))
+    return false;
+
+  // Truncate the path to the subobject, and remove any derived-to-base of=
fsets.
+  const RecordDecl *RD =3D TruncatedType;
+  for (unsigned I =3D TruncatedElements, N =3D D.Entries.size(); I !=3D N;=
 ++I) {
+    const ASTRecordLayout &Layout =3D Info.Ctx.getASTRecordLayout(RD);
+    const CXXRecordDecl *Base =3D getAsBaseClass(D.Entries[I]);
+    if (isVirtualBaseClass(D.Entries[I]))
+      Result.Offset -=3D Layout.getVBaseClassOffset(Base);
+    else
+      Result.Offset -=3D Layout.getBaseClassOffset(Base);
+    RD =3D Base;
+  }
+  D.Entries.resize(TruncatedElements);
+  return true;
+}
+
+static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &=
Obj,
+                                   const CXXRecordDecl *Derived,
+                                   const CXXRecordDecl *Base,
+                                   const ASTRecordLayout *RL =3D 0) {
+  if (!RL) RL =3D &Info.Ctx.getASTRecordLayout(Derived);
+  Obj.getLValueOffset() +=3D RL->getBaseClassOffset(Base);
+  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
+}
+
+static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
+                             const CXXRecordDecl *DerivedDecl,
+                             const CXXBaseSpecifier *Base) {
+  const CXXRecordDecl *BaseDecl =3D Base->getType()->getAsCXXRecordDecl();
+
+  if (!Base->isVirtual()) {
+    HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
+    return true;
+  }
+
+  SubobjectDesignator &D =3D Obj.Designator;
+  if (D.Invalid)
+    return false;
+
+  // Extract most-derived object and corresponding type.
+  DerivedDecl =3D D.MostDerivedType->getAsCXXRecordDecl();
+  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLeng=
th))
+    return false;
+
+  // Find the virtual base class.
+  const ASTRecordLayout &Layout =3D Info.Ctx.getASTRecordLayout(DerivedDec=
l);
+  Obj.getLValueOffset() +=3D Layout.getVBaseClassOffset(BaseDecl);
+  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
+  return true;
+}
+
+/// Update LVal to refer to the given field, which must be a member of the=
 type
+/// currently described by LVal.
+static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
+                               const FieldDecl *FD,
+                               const ASTRecordLayout *RL =3D 0) {
+  if (!RL)
+    RL =3D &Info.Ctx.getASTRecordLayout(FD->getParent());
+
+  unsigned I =3D FD->getFieldIndex();
+  LVal.Offset +=3D Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
+  LVal.addDecl(Info, E, FD);
+}
+
+/// Update LVal to refer to the given indirect field.
+static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
+                                       LValue &LVal,
+                                       const IndirectFieldDecl *IFD) {
+  for (IndirectFieldDecl::chain_iterator C =3D IFD->chain_begin(),
+                                         CE =3D IFD->chain_end(); C !=3D C=
E; ++C)
+    HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
+}
+
+/// Get the size of the given type in char units.
+static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
+                         QualType Type, CharUnits &Size) {
+  // sizeof(void), __alignof__(void), sizeof(function) =3D 1 as a gcc
+  // extension.
+  if (Type->isVoidType() || Type->isFunctionType()) {
+    Size =3D CharUnits::One();
+    return true;
+  }
+
+  if (!Type->isConstantSizeType()) {
+    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
+    // FIXME: Better diagnostic.
+    Info.Diag(Loc);
+    return false;
+  }
+
+  Size =3D Info.Ctx.getTypeSizeInChars(Type);
+  return true;
+}
+
+/// Update a pointer value to model pointer arithmetic.
+/// \param Info - Information about the ongoing evaluation.
+/// \param E - The expression being evaluated, for diagnostic purposes.
+/// \param LVal - The pointer value to be updated.
+/// \param EltTy - The pointee type represented by LVal.
+/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
+static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
+                                        LValue &LVal, QualType EltTy,
+                                        int64_t Adjustment) {
+  CharUnits SizeOfPointee;
+  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
+    return false;
+
+  // Compute the new offset in the appropriate width.
+  LVal.Offset +=3D Adjustment * SizeOfPointee;
+  LVal.adjustIndex(Info, E, Adjustment);
+  return true;
+}
+
+/// Update an lvalue to refer to a component of a complex number.
+/// \param Info - Information about the ongoing evaluation.
+/// \param LVal - The lvalue to be updated.
+/// \param EltTy - The complex number's component type.
+/// \param Imag - False for the real component, true for the imaginary.
+static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
+                                       LValue &LVal, QualType EltTy,
+                                       bool Imag) {
+  if (Imag) {
+    CharUnits SizeOfComponent;
+    if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
+      return false;
+    LVal.Offset +=3D SizeOfComponent;
+  }
+  LVal.addComplex(Info, E, EltTy, Imag);
+  return true;
+}
+
+/// Try to evaluate the initializer for a variable declaration.
+static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
+                                const VarDecl *VD,
+                                CallStackFrame *Frame, APValue &Result) {
+  // If this is a parameter to an active constexpr function call, perform
+  // argument substitution.
+  if (const ParmVarDecl *PVD =3D dyn_cast<ParmVarDecl>(VD)) {
+    // Assume arguments of a potential constant expression are unknown
+    // constant expressions.
+    if (Info.CheckingPotentialConstantExpression)
+      return false;
+    if (!Frame || !Frame->Arguments) {
+      Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+      return false;
+    }
+    Result =3D Frame->Arguments[PVD->getFunctionScopeIndex()];
+    return true;
+  }
+
+  // Dig out the initializer, and use the declaration which it's attached =
to.
+  const Expr *Init =3D VD->getAnyInitializer(VD);
+  if (!Init || Init->isValueDependent()) {
+    // If we're checking a potential constant expression, the variable cou=
ld be
+    // initialized later.
+    if (!Info.CheckingPotentialConstantExpression)
+      Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+    return false;
+  }
+
+  // If we're currently evaluating the initializer of this declaration, us=
e that
+  // in-flight value.
+  if (Info.EvaluatingDecl =3D=3D VD) {
+    Result =3D *Info.EvaluatingDeclValue;
+    return !Result.isUninit();
+  }
+
+  // Never evaluate the initializer of a weak variable. We can't be sure t=
hat
+  // this is the definition which will be used.
+  if (VD->isWeak()) {
+    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+    return false;
+  }
+
+  // Check that we can fold the initializer. In C++, we will have already =
done
+  // this in the cases where it matters for conformance.
+  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
+  if (!VD->evaluateValue(Notes)) {
+    Info.Diag(E, diag::note_constexpr_var_init_non_constant,
+              Notes.size() + 1) << VD;
+    Info.Note(VD->getLocation(), diag::note_declared_at);
+    Info.addNotes(Notes);
+    return false;
+  } else if (!VD->checkInitIsICE()) {
+    Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
+                 Notes.size() + 1) << VD;
+    Info.Note(VD->getLocation(), diag::note_declared_at);
+    Info.addNotes(Notes);
+  }
+
+  Result =3D *VD->getEvaluatedValue();
+  return true;
+}
+
+static bool IsConstNonVolatile(QualType T) {
+  Qualifiers Quals =3D T.getQualifiers();
+  return Quals.hasConst() && !Quals.hasVolatile();
+}
+
+/// Get the base index of the given base class within an APValue represent=
ing
+/// the given derived class.
+static unsigned getBaseIndex(const CXXRecordDecl *Derived,
+                             const CXXRecordDecl *Base) {
+  Base =3D Base->getCanonicalDecl();
+  unsigned Index =3D 0;
+  for (CXXRecordDecl::base_class_const_iterator I =3D Derived->bases_begin=
(),
+         E =3D Derived->bases_end(); I !=3D E; ++I, ++Index) {
+    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() =3D=3D Base)
+      return Index;
+  }
+
+  llvm_unreachable("base class missing from derived class's bases list");
+}
+
+/// Extract the value of a character from a string literal.
+static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Li=
t,
+                                            uint64_t Index) {
+  // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
+  const StringLiteral *S =3D dyn_cast<StringLiteral>(Lit);
+  assert(S && "unexpected string literal expression kind");
+
+  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
+    Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType=
());
+  if (Index < S->getLength())
+    Value =3D S->getCodeUnit(Index);
+  return Value;
+}
+
+/// Extract the designated sub-object of an rvalue.
+static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
+                             APValue &Obj, QualType ObjType,
+                             const SubobjectDesignator &Sub, QualType SubT=
ype) {
+  if (Sub.Invalid)
+    // A diagnostic will have already been produced.
+    return false;
+  if (Sub.isOnePastTheEnd()) {
+    Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
+                (unsigned)diag::note_constexpr_read_past_end :
+                (unsigned)diag::note_invalid_subexpr_in_const_expr);
+    return false;
+  }
+  if (Sub.Entries.empty())
+    return true;
+  if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
+    // This object might be initialized later.
+    return false;
+
+  APValue *O =3D &Obj;
+  // Walk the designator's path to find the subobject.
+  for (unsigned I =3D 0, N =3D Sub.Entries.size(); I !=3D N; ++I) {
+    if (ObjType->isArrayType()) {
+      // Next subobject is an array element.
+      const ConstantArrayType *CAT =3D Info.Ctx.getAsConstantArrayType(Obj=
Type);
+      assert(CAT && "vla in literal type?");
+      uint64_t Index =3D Sub.Entries[I].ArrayIndex;
+      if (CAT->getSize().ule(Index)) {
+        // Note, it should not be possible to form a pointer with a valid
+        // designator which points more than one past the end of the array.
+        Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
+                    (unsigned)diag::note_constexpr_read_past_end :
+                    (unsigned)diag::note_invalid_subexpr_in_const_expr);
+        return false;
+      }
+      // An array object is represented as either an Array APValue or as an
+      // LValue which refers to a string literal.
+      if (O->isLValue()) {
+        assert(I =3D=3D N - 1 && "extracting subobject of character?");
+        assert(!O->hasLValuePath() || O->getLValuePath().empty());
+        Obj =3D APValue(ExtractStringLiteralCharacter(
+          Info, O->getLValueBase().get<const Expr*>(), Index));
+        return true;
+      } else if (O->getArrayInitializedElts() > Index)
+        O =3D &O->getArrayInitializedElt(Index);
+      else
+        O =3D &O->getArrayFiller();
+      ObjType =3D CAT->getElementType();
+    } else if (ObjType->isAnyComplexType()) {
+      // Next subobject is a complex number.
+      uint64_t Index =3D Sub.Entries[I].ArrayIndex;
+      if (Index > 1) {
+        Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
+                    (unsigned)diag::note_constexpr_read_past_end :
+                    (unsigned)diag::note_invalid_subexpr_in_const_expr);
+        return false;
+      }
+      assert(I =3D=3D N - 1 && "extracting subobject of scalar?");
+      if (O->isComplexInt()) {
+        Obj =3D APValue(Index ? O->getComplexIntImag()
+                            : O->getComplexIntReal());
+      } else {
+        assert(O->isComplexFloat());
+        Obj =3D APValue(Index ? O->getComplexFloatImag()
+                            : O->getComplexFloatReal());
+      }
+      return true;
+    } else if (const FieldDecl *Field =3D getAsField(Sub.Entries[I])) {
+      if (Field->isMutable()) {
+        Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
+          << Field;
+        Info.Note(Field->getLocation(), diag::note_declared_at);
+        return false;
+      }
+
+      // Next subobject is a class, struct or union field.
+      RecordDecl *RD =3D ObjType->castAs<RecordType>()->getDecl();
+      if (RD->isUnion()) {
+        const FieldDecl *UnionField =3D O->getUnionField();
+        if (!UnionField ||
+            UnionField->getCanonicalDecl() !=3D Field->getCanonicalDecl())=
 {
+          Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
+            << Field << !UnionField << UnionField;
+          return false;
+        }
+        O =3D &O->getUnionValue();
+      } else
+        O =3D &O->getStructField(Field->getFieldIndex());
+      ObjType =3D Field->getType();
+
+      if (ObjType.isVolatileQualified()) {
+        if (Info.getLangOpts().CPlusPlus) {
+          // FIXME: Include a description of the path to the volatile subo=
bject.
+          Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
+            << 2 << Field;
+          Info.Note(Field->getLocation(), diag::note_declared_at);
+        } else {
+          Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+        }
+        return false;
+      }
+    } else {
+      // Next subobject is a base class.
+      const CXXRecordDecl *Derived =3D ObjType->getAsCXXRecordDecl();
+      const CXXRecordDecl *Base =3D getAsBaseClass(Sub.Entries[I]);
+      O =3D &O->getStructBase(getBaseIndex(Derived, Base));
+      ObjType =3D Info.Ctx.getRecordType(Base);
+    }
+
+    if (O->isUninit()) {
+      if (!Info.CheckingPotentialConstantExpression)
+        Info.Diag(E, diag::note_constexpr_read_uninit);
+      return false;
+    }
+  }
+
+  // This may look super-stupid, but it serves an important purpose: if we=
 just
+  // swapped Obj and *O, we'd create an object which had itself as a subob=
ject.
+  // To avoid the leak, we ensure that Tmp ends up owning the original com=
plete
+  // object, which is destroyed by Tmp's destructor.
+  APValue Tmp;
+  O->swap(Tmp);
+  Obj.swap(Tmp);
+  return true;
+}
+
+/// Find the position where two subobject designators diverge, or equivale=
ntly
+/// the length of the common initial subsequence.
+static unsigned FindDesignatorMismatch(QualType ObjType,
+                                       const SubobjectDesignator &A,
+                                       const SubobjectDesignator &B,
+                                       bool &WasArrayIndex) {
+  unsigned I =3D 0, N =3D std::min(A.Entries.size(), B.Entries.size());
+  for (/**/; I !=3D N; ++I) {
+    if (!ObjType.isNull() &&
+        (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
+      // Next subobject is an array element.
+      if (A.Entries[I].ArrayIndex !=3D B.Entries[I].ArrayIndex) {
+        WasArrayIndex =3D true;
+        return I;
+      }
+      if (ObjType->isAnyComplexType())
+        ObjType =3D ObjType->castAs<ComplexType>()->getElementType();
+      else
+        ObjType =3D ObjType->castAsArrayTypeUnsafe()->getElementType();
+    } else {
+      if (A.Entries[I].BaseOrMember !=3D B.Entries[I].BaseOrMember) {
+        WasArrayIndex =3D false;
+        return I;
+      }
+      if (const FieldDecl *FD =3D getAsField(A.Entries[I]))
+        // Next subobject is a field.
+        ObjType =3D FD->getType();
+      else
+        // Next subobject is a base class.
+        ObjType =3D QualType();
+    }
+  }
+  WasArrayIndex =3D false;
+  return I;
+}
+
+/// Determine whether the given subobject designators refer to elements of=
 the
+/// same array object.
+static bool AreElementsOfSameArray(QualType ObjType,
+                                   const SubobjectDesignator &A,
+                                   const SubobjectDesignator &B) {
+  if (A.Entries.size() !=3D B.Entries.size())
+    return false;
+
+  bool IsArray =3D A.MostDerivedArraySize !=3D 0;
+  if (IsArray && A.MostDerivedPathLength !=3D A.Entries.size())
+    // A is a subobject of the array element.
+    return false;
+
+  // If A (and B) designates an array element, the last entry will be the =
array
+  // index. That doesn't have to match. Otherwise, we're in the 'implicit =
array
+  // of length 1' case, and the entire path must match.
+  bool WasArrayIndex;
+  unsigned CommonLength =3D FindDesignatorMismatch(ObjType, A, B, WasArray=
Index);
+  return CommonLength >=3D A.Entries.size() - IsArray;
+}
+
+/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversio=
n on
+/// the given lvalue. This can also be used for 'lvalue-to-lvalue' convers=
ions
+/// for looking up the glvalue referred to by an entity of reference type.
+///
+/// \param Info - Information about the ongoing evaluation.
+/// \param Conv - The expression for which we are performing the conversio=
n.
+///               Used for diagnostics.
+/// \param Type - The type we expect this conversion to produce, before
+///               stripping cv-qualifiers in the case of a non-clas type.
+/// \param LVal - The glvalue on which we are attempting to perform this a=
ction.
+/// \param RVal - The produced value will be placed here.
+static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Con=
v,
+                                           QualType Type,
+                                           const LValue &LVal, APValue &RV=
al) {
+  if (LVal.Designator.Invalid)
+    // A diagnostic will have already been produced.
+    return false;
+
+  const Expr *Base =3D LVal.Base.dyn_cast<const Expr*>();
+
+  if (!LVal.Base) {
+    // FIXME: Indirection through a null pointer deserves a specific diagn=
ostic.
+    Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
+    return false;
+  }
+
+  CallStackFrame *Frame =3D 0;
+  if (LVal.CallIndex) {
+    Frame =3D Info.getCallFrame(LVal.CallIndex);
+    if (!Frame) {
+      Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
+      NoteLValueLocation(Info, LVal.Base);
+      return false;
+    }
+  }
+
+  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified =
type
+  // is not a constant expression (even if the object is non-volatile). We=
 also
+  // apply this rule to C++98, in order to conform to the expected 'volati=
le'
+  // semantics.
+  if (Type.isVolatileQualified()) {
+    if (Info.getLangOpts().CPlusPlus)
+      Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
+    else
+      Info.Diag(Conv);
+    return false;
+  }
+
+  if (const ValueDecl *D =3D LVal.Base.dyn_cast<const ValueDecl*>()) {
+    // In C++98, const, non-volatile integers initialized with ICEs are IC=
Es.
+    // In C++11, constexpr, non-volatile variables initialized with consta=
nt
+    // expressions are constant expressions too. Inside constexpr function=
s,
+    // parameters are constant expressions even if they're non-const.
+    // In C, such things can also be folded, although they are not ICEs.
+    const VarDecl *VD =3D dyn_cast<VarDecl>(D);
+    if (VD) {
+      if (const VarDecl *VDef =3D VD->getDefinition(Info.Ctx))
+        VD =3D VDef;
+    }
+    if (!VD || VD->isInvalidDecl()) {
+      Info.Diag(Conv);
+      return false;
+    }
+
+    // DR1313: If the object is volatile-qualified but the glvalue was not,
+    // behavior is undefined so the result is not a constant expression.
+    QualType VT =3D VD->getType();
+    if (VT.isVolatileQualified()) {
+      if (Info.getLangOpts().CPlusPlus) {
+        Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 <<=
 VD;
+        Info.Note(VD->getLocation(), diag::note_declared_at);
+      } else {
+        Info.Diag(Conv);
+      }
+      return false;
+    }
+
+    if (!isa<ParmVarDecl>(VD)) {
+      if (VD->isConstexpr()) {
+        // OK, we can read this variable.
+      } else if (VT->isIntegralOrEnumerationType()) {
+        if (!VT.isConstQualified()) {
+          if (Info.getLangOpts().CPlusPlus) {
+            Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) <<=
 VD;
+            Info.Note(VD->getLocation(), diag::note_declared_at);
+          } else {
+            Info.Diag(Conv);
+          }
+          return false;
+        }
+      } else if (VT->isFloatingType() && VT.isConstQualified()) {
+        // We support folding of const floating-point types, in order to m=
ake
+        // static const data members of such types (supported as an extens=
ion)
+        // more useful.
+        if (Info.getLangOpts().CPlusPlus0x) {
+          Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) <=
< VD;
+          Info.Note(VD->getLocation(), diag::note_declared_at);
+        } else {
+          Info.CCEDiag(Conv);
+        }
+      } else {
+        // FIXME: Allow folding of values of any literal type in all langu=
ages.
+        if (Info.getLangOpts().CPlusPlus0x) {
+          Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << V=
D;
+          Info.Note(VD->getLocation(), diag::note_declared_at);
+        } else {
+          Info.Diag(Conv);
+        }
+        return false;
+      }
+    }
+
+    if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
+      return false;
+
+    if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
+      return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
+
+    // The declaration was initialized by an lvalue, with no lvalue-to-rva=
lue
+    // conversion. This happens when the declaration and the lvalue should=
 be
+    // considered synonymous, for instance when initializing an array of c=
har
+    // from a string literal. Continue as if the initializer lvalue was the
+    // value we were originally given.
+    assert(RVal.getLValueOffset().isZero() &&
+           "offset for lvalue init of non-reference");
+    Base =3D RVal.getLValueBase().get<const Expr*>();
+
+    if (unsigned CallIndex =3D RVal.getLValueCallIndex()) {
+      Frame =3D Info.getCallFrame(CallIndex);
+      if (!Frame) {
+        Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
+        NoteLValueLocation(Info, RVal.getLValueBase());
+        return false;
+      }
+    } else {
+      Frame =3D 0;
+    }
+  }
+
+  // Volatile temporary objects cannot be read in constant expressions.
+  if (Base->getType().isVolatileQualified()) {
+    if (Info.getLangOpts().CPlusPlus) {
+      Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
+      Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
+    } else {
+      Info.Diag(Conv);
+    }
+    return false;
+  }
+
+  if (Frame) {
+    // If this is a temporary expression with a nontrivial initializer, gr=
ab the
+    // value from the relevant stack frame.
+    RVal =3D Frame->Temporaries[Base];
+  } else if (const CompoundLiteralExpr *CLE
+             =3D dyn_cast<CompoundLiteralExpr>(Base)) {
+    // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating=
 the
+    // initializer until now for such expressions. Such an expression can'=
t be
+    // an ICE in C, so this only matters for fold.
+    assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c+=
+?");
+    if (!Evaluate(RVal, Info, CLE->getInitializer()))
+      return false;
+  } else if (isa<StringLiteral>(Base)) {
+    // We represent a string literal array as an lvalue pointing at the
+    // corresponding expression, rather than building an array of chars.
+    // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
+    RVal =3D APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
+  } else {
+    Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
+    return false;
+  }
+
+  return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designat=
or,
+                          Type);
+}
+
+/// Build an lvalue for the object argument of a member function call.
+static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
+                                   LValue &This) {
+  if (Object->getType()->isPointerType())
+    return EvaluatePointer(Object, This, Info);
+
+  if (Object->isGLValue())
+    return EvaluateLValue(Object, This, Info);
+
+  if (Object->getType()->isLiteralType())
+    return EvaluateTemporary(Object, This, Info);
+
+  return false;
+}
+
+/// HandleMemberPointerAccess - Evaluate a member access operation and bui=
ld an
+/// lvalue referring to the result.
+///
+/// \param Info - Information about the ongoing evaluation.
+/// \param BO - The member pointer access operation.
+/// \param LV - Filled in with a reference to the resulting object.
+/// \param IncludeMember - Specifies whether the member itself is included=
 in
+///        the resulting LValue subobject designator. This is not possible=
 when
+///        creating a bound member function.
+/// \return The field or method declaration to which the member pointer re=
fers,
+///         or 0 if evaluation fails.
+static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
+                                                  const BinaryOperator *BO,
+                                                  LValue &LV,
+                                                  bool IncludeMember =3D t=
rue) {
+  assert(BO->getOpcode() =3D=3D BO_PtrMemD || BO->getOpcode() =3D=3D BO_Pt=
rMemI);
+
+  bool EvalObjOK =3D EvaluateObjectArgument(Info, BO->getLHS(), LV);
+  if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
+    return 0;
+
+  MemberPtr MemPtr;
+  if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
+    return 0;
+
+  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
+  // member value, the behavior is undefined.
+  if (!MemPtr.getDecl())
+    return 0;
+
+  if (!EvalObjOK)
+    return 0;
+
+  if (MemPtr.isDerivedMember()) {
+    // This is a member of some derived class. Truncate LV appropriately.
+    // The end of the derived-to-base path for the base object must match =
the
+    // derived-to-base path for the member pointer.
+    if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
+        LV.Designator.Entries.size())
+      return 0;
+    unsigned PathLengthToMember =3D
+        LV.Designator.Entries.size() - MemPtr.Path.size();
+    for (unsigned I =3D 0, N =3D MemPtr.Path.size(); I !=3D N; ++I) {
+      const CXXRecordDecl *LVDecl =3D getAsBaseClass(
+          LV.Designator.Entries[PathLengthToMember + I]);
+      const CXXRecordDecl *MPDecl =3D MemPtr.Path[I];
+      if (LVDecl->getCanonicalDecl() !=3D MPDecl->getCanonicalDecl())
+        return 0;
+    }
+
+    // Truncate the lvalue to the appropriate derived class.
+    if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
+                            PathLengthToMember))
+      return 0;
+  } else if (!MemPtr.Path.empty()) {
+    // Extend the LValue path with the member pointer's path.
+    LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
+                                  MemPtr.Path.size() + IncludeMember);
+
+    // Walk down to the appropriate base class.
+    QualType LVType =3D BO->getLHS()->getType();
+    if (const PointerType *PT =3D LVType->getAs<PointerType>())
+      LVType =3D PT->getPointeeType();
+    const CXXRecordDecl *RD =3D LVType->getAsCXXRecordDecl();
+    assert(RD && "member pointer access on non-class-type expression");
+    // The first class in the path is that of the lvalue.
+    for (unsigned I =3D 1, N =3D MemPtr.Path.size(); I !=3D N; ++I) {
+      const CXXRecordDecl *Base =3D MemPtr.Path[N - I - 1];
+      HandleLValueDirectBase(Info, BO, LV, RD, Base);
+      RD =3D Base;
+    }
+    // Finally cast to the class containing the member.
+    HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
+  }
+
+  // Add the member. Note that we cannot build bound member functions here.
+  if (IncludeMember) {
+    if (const FieldDecl *FD =3D dyn_cast<FieldDecl>(MemPtr.getDecl()))
+      HandleLValueMember(Info, BO, LV, FD);
+    else if (const IndirectFieldDecl *IFD =3D
+               dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
+      HandleLValueIndirectMember(Info, BO, LV, IFD);
+    else
+      llvm_unreachable("can't construct reference to bound member function=
");
+  }
+
+  return MemPtr.getDecl();
+}
+
+/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operati=
on on
+/// the provided lvalue, which currently refers to the base object.
+static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
+                                    LValue &Result) {
+  SubobjectDesignator &D =3D Result.Designator;
+  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
+    return false;
+
+  QualType TargetQT =3D E->getType();
+  if (const PointerType *PT =3D TargetQT->getAs<PointerType>())
+    TargetQT =3D PT->getPointeeType();
+
+  // Check this cast lands within the final derived-to-base subobject path.
+  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
+    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
+      << D.MostDerivedType << TargetQT;
+    return false;
+  }
+
+  // Check the type of the final cast. We don't need to check the path,
+  // since a cast can only be formed if the path is unique.
+  unsigned NewEntriesSize =3D D.Entries.size() - E->path_size();
+  const CXXRecordDecl *TargetType =3D TargetQT->getAsCXXRecordDecl();
+  const CXXRecordDecl *FinalType;
+  if (NewEntriesSize =3D=3D D.MostDerivedPathLength)
+    FinalType =3D D.MostDerivedType->getAsCXXRecordDecl();
+  else
+    FinalType =3D getAsBaseClass(D.Entries[NewEntriesSize - 1]);
+  if (FinalType->getCanonicalDecl() !=3D TargetType->getCanonicalDecl()) {
+    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
+      << D.MostDerivedType << TargetQT;
+    return false;
+  }
+
+  // Truncate the lvalue to the appropriate derived class.
+  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
+}
+
+namespace {
+enum EvalStmtResult {
+  /// Evaluation failed.
+  ESR_Failed,
+  /// Hit a 'return' statement.
+  ESR_Returned,
+  /// Evaluation succeeded.
+  ESR_Succeeded
+};
+}
+
+// Evaluate a statement.
+static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
+                                   const Stmt *S) {
+  switch (S->getStmtClass()) {
+  default:
+    return ESR_Failed;
+
+  case Stmt::NullStmtClass:
+  case Stmt::DeclStmtClass:
+    return ESR_Succeeded;
+
+  case Stmt::ReturnStmtClass: {
+    const Expr *RetExpr =3D cast<ReturnStmt>(S)->getRetValue();
+    if (!Evaluate(Result, Info, RetExpr))
+      return ESR_Failed;
+    return ESR_Returned;
+  }
+
+  case Stmt::CompoundStmtClass: {
+    const CompoundStmt *CS =3D cast<CompoundStmt>(S);
+    for (CompoundStmt::const_body_iterator BI =3D CS->body_begin(),
+           BE =3D CS->body_end(); BI !=3D BE; ++BI) {
+      EvalStmtResult ESR =3D EvaluateStmt(Result, Info, *BI);
+      if (ESR !=3D ESR_Succeeded)
+        return ESR;
+    }
+    return ESR_Succeeded;
+  }
+  }
+}
+
+/// CheckTrivialDefaultConstructor - Check whether a constructor is a triv=
ial
+/// default constructor. If so, we'll fold it whether or not it's marked as
+/// constexpr. If it is marked as constexpr, we will never implicitly defi=
ne it,
+/// so we need special handling.
+static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation =
Loc,
+                                           const CXXConstructorDecl *CD,
+                                           bool IsValueInitialization) {
+  if (!CD->isTrivial() || !CD->isDefaultConstructor())
+    return false;
+
+  // Value-initialization does not call a trivial default constructor, so =
such a
+  // call is a core constant expression whether or not the constructor is
+  // constexpr.
+  if (!CD->isConstexpr() && !IsValueInitialization) {
+    if (Info.getLangOpts().CPlusPlus0x) {
+      // FIXME: If DiagDecl is an implicitly-declared special member funct=
ion,
+      // we should be much more explicit about why it's not constexpr.
+      Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
+        << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
+      Info.Note(CD->getLocation(), diag::note_declared_at);
+    } else {
+      Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
+    }
+  }
+  return true;
+}
+
+/// CheckConstexprFunction - Check that a function can be called in a cons=
tant
+/// expression.
+static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
+                                   const FunctionDecl *Declaration,
+                                   const FunctionDecl *Definition) {
+  // Potential constant expressions can contain calls to declared, but not=
 yet
+  // defined, constexpr functions.
+  if (Info.CheckingPotentialConstantExpression && !Definition &&
+      Declaration->isConstexpr())
+    return false;
+
+  // Can we evaluate this function call?
+  if (Definition && Definition->isConstexpr() && !Definition->isInvalidDec=
l())
+    return true;
+
+  if (Info.getLangOpts().CPlusPlus0x) {
+    const FunctionDecl *DiagDecl =3D Definition ? Definition : Declaration;
+    // FIXME: If DiagDecl is an implicitly-declared special member functio=
n, we
+    // should be much more explicit about why it's not constexpr.
+    Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
+      << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
+      << DiagDecl;
+    Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
+  } else {
+    Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
+  }
+  return false;
+}
+
+namespace {
+typedef SmallVector<APValue, 8> ArgVector;
+}
+
+/// EvaluateArgs - Evaluate the arguments to a function call.
+static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
+                         EvalInfo &Info) {
+  bool Success =3D true;
+  for (ArrayRef<const Expr*>::iterator I =3D Args.begin(), E =3D Args.end(=
);
+       I !=3D E; ++I) {
+    if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
+      // If we're checking for a potential constant expression, evaluate a=
ll
+      // initializers even if some of them fail.
+      if (!Info.keepEvaluatingAfterFailure())
+        return false;
+      Success =3D false;
+    }
+  }
+  return Success;
+}
+
+/// Evaluate a function call.
+static bool HandleFunctionCall(SourceLocation CallLoc,
+                               const FunctionDecl *Callee, const LValue *T=
his,
+                               ArrayRef<const Expr*> Args, const Stmt *Bod=
y,
+                               EvalInfo &Info, APValue &Result) {
+  ArgVector ArgValues(Args.size());
+  if (!EvaluateArgs(Args, ArgValues, Info))
+    return false;
+
+  if (!Info.CheckCallLimit(CallLoc))
+    return false;
+
+  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
+  return EvaluateStmt(Result, Info, Body) =3D=3D ESR_Returned;
+}
+
+/// Evaluate a constructor call.
+static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &Th=
is,
+                                  ArrayRef<const Expr*> Args,
+                                  const CXXConstructorDecl *Definition,
+                                  EvalInfo &Info, APValue &Result) {
+  ArgVector ArgValues(Args.size());
+  if (!EvaluateArgs(Args, ArgValues, Info))
+    return false;
+
+  if (!Info.CheckCallLimit(CallLoc))
+    return false;
+
+  const CXXRecordDecl *RD =3D Definition->getParent();
+  if (RD->getNumVBases()) {
+    Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
+    return false;
+  }
+
+  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
+
+  // If it's a delegating constructor, just delegate.
+  if (Definition->isDelegatingConstructor()) {
+    CXXConstructorDecl::init_const_iterator I =3D Definition->init_begin();
+    return EvaluateInPlace(Result, Info, This, (*I)->getInit());
+  }
+
+  // For a trivial copy or move constructor, perform an APValue copy. This=
 is
+  // essential for unions, where the operations performed by the construct=
or
+  // cannot be represented by ctor-initializers.
+  if (Definition->isDefaulted() &&
+      ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
+       (Definition->isMoveConstructor() && Definition->isTrivial()))) {
+    LValue RHS;
+    RHS.setFrom(Info.Ctx, ArgValues[0]);
+    return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(=
),
+                                          RHS, Result);
+  }
+
+  // Reserve space for the struct members.
+  if (!RD->isUnion() && Result.isUninit())
+    Result =3D APValue(APValue::UninitStruct(), RD->getNumBases(),
+                     std::distance(RD->field_begin(), RD->field_end()));
+
+  const ASTRecordLayout &Layout =3D Info.Ctx.getASTRecordLayout(RD);
+
+  bool Success =3D true;
+  unsigned BasesSeen =3D 0;
+#ifndef NDEBUG
+  CXXRecordDecl::base_class_const_iterator BaseIt =3D RD->bases_begin();
+#endif
+  for (CXXConstructorDecl::init_const_iterator I =3D Definition->init_begi=
n(),
+       E =3D Definition->init_end(); I !=3D E; ++I) {
+    LValue Subobject =3D This;
+    APValue *Value =3D &Result;
+
+    // Determine the subobject to initialize.
+    if ((*I)->isBaseInitializer()) {
+      QualType BaseType((*I)->getBaseClass(), 0);
+#ifndef NDEBUG
+      // Non-virtual base classes are initialized in the order in the class
+      // definition. We have already checked for virtual base classes.
+      assert(!BaseIt->isVirtual() && "virtual base for literal type");
+      assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
+             "base class initializers not in expected order");
+      ++BaseIt;
+#endif
+      HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
+                             BaseType->getAsCXXRecordDecl(), &Layout);
+      Value =3D &Result.getStructBase(BasesSeen++);
+    } else if (FieldDecl *FD =3D (*I)->getMember()) {
+      HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
+      if (RD->isUnion()) {
+        Result =3D APValue(FD);
+        Value =3D &Result.getUnionValue();
+      } else {
+        Value =3D &Result.getStructField(FD->getFieldIndex());
+      }
+    } else if (IndirectFieldDecl *IFD =3D (*I)->getIndirectMember()) {
+      // Walk the indirect field decl's chain to find the object to initia=
lize,
+      // and make sure we've initialized every step along it.
+      for (IndirectFieldDecl::chain_iterator C =3D IFD->chain_begin(),
+                                             CE =3D IFD->chain_end();
+           C !=3D CE; ++C) {
+        FieldDecl *FD =3D cast<FieldDecl>(*C);
+        CXXRecordDecl *CD =3D cast<CXXRecordDecl>(FD->getParent());
+        // Switch the union field if it differs. This happens if we had
+        // preceding zero-initialization, and we're now initializing a uni=
on
+        // subobject other than the first.
+        // FIXME: In this case, the values of the other subobjects are
+        // specified, since zero-initialization sets all padding bits to z=
ero.
+        if (Value->isUninit() ||
+            (Value->isUnion() && Value->getUnionField() !=3D FD)) {
+          if (CD->isUnion())
+            *Value =3D APValue(FD);
+          else
+            *Value =3D APValue(APValue::UninitStruct(), CD->getNumBases(),
+                             std::distance(CD->field_begin(), CD->field_en=
d()));
+        }
+        HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
+        if (CD->isUnion())
+          Value =3D &Value->getUnionValue();
+        else
+          Value =3D &Value->getStructField(FD->getFieldIndex());
+      }
+    } else {
+      llvm_unreachable("unknown base initializer kind");
+    }
+
+    if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
+                         (*I)->isBaseInitializer()
+                                      ? CCEK_Constant : CCEK_MemberInit)) {
+      // If we're checking for a potential constant expression, evaluate a=
ll
+      // initializers even if some of them fail.
+      if (!Info.keepEvaluatingAfterFailure())
+        return false;
+      Success =3D false;
+    }
+  }
+
+  return Success;
 }
=20
 namespace {
 class HasSideEffect
   : public ConstStmtVisitor<HasSideEffect, bool> {
-  EvalInfo &Info;
+  const ASTContext &Ctx;
 public:
=20
-  HasSideEffect(EvalInfo &info) : Info(info) {}
+  HasSideEffect(const ASTContext &C) : Ctx(C) {}
=20
   // Unhandled nodes conservatively default to having side effects.
   bool VisitStmt(const Stmt *S) {
@@ -279,17 +2281,12 @@
     return Visit(E->getResultExpr());
   }
   bool VisitDeclRefExpr(const DeclRefExpr *E) {
-    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
+    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
       return true;
     return false;
   }
   bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
-    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
-      return true;
-    return false;
-  }
-  bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
-    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
+    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
       return true;
     return false;
   }
@@ -310,7 +2307,7 @@
   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
     { return Visit(E->getLHS()) || Visit(E->getRHS()); }
   bool VisitChooseExpr(const ChooseExpr *E)
-    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
+    { return Visit(E->getChosenSubExpr(Ctx)); }
   bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
   bool VisitBinAssign(const BinaryOperator *E) { return true; }
   bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true;=
 }
@@ -321,7 +2318,7 @@
   bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
   bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
   bool VisitUnaryDeref(const UnaryOperator *E) {
-    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
+    if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
       return true;
     return Visit(E->getSubExpr());
   }
@@ -349,16 +2346,18 @@
     : info(info), opaqueValue(opaqueValue) {
=20
     // If evaluation fails, fail immediately.
-    if (!Evaluate(info, value)) {
+    if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
       this->opaqueValue =3D 0;
       return;
     }
-    info.OpaqueValues[opaqueValue] =3D info.EvalResult.Val;
   }
=20
   bool hasError() const { return opaqueValue =3D=3D 0; }
=20
   ~OpaqueValueEvaluation() {
+    // FIXME: For a recursive constexpr call, an outer stack frame might h=
ave
+    // been using this opaque value too, and will now have to re-evaluate =
the
+    // source expression.
     if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
   }
 };
@@ -370,18 +2369,55 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 namespace {
=20
-template <class Derived, typename RetTy=3Dvoid>
+// FIXME: RetTy is always bool. Remove it.
+template <class Derived, typename RetTy=3Dbool>
 class ExprEvaluatorBase
   : public ConstStmtVisitor<Derived, RetTy> {
 private:
   RetTy DerivedSuccess(const APValue &V, const Expr *E) {
     return static_cast<Derived*>(this)->Success(V, E);
   }
-  RetTy DerivedError(const Expr *E) {
-    return static_cast<Derived*>(this)->Error(E);
-  }
-  RetTy DerivedValueInitialization(const Expr *E) {
-    return static_cast<Derived*>(this)->ValueInitialization(E);
+  RetTy DerivedZeroInitialization(const Expr *E) {
+    return static_cast<Derived*>(this)->ZeroInitialization(E);
+  }
+
+  // Check whether a conditional operator with a non-constant condition is=
 a
+  // potential constant expression. If neither arm is a potential constant
+  // expression, then the conditional operator is not either.
+  template<typename ConditionalOperator>
+  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
+    assert(Info.CheckingPotentialConstantExpression);
+
+    // Speculatively evaluate both arms.
+    {
+      llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
+      SpeculativeEvaluationRAII Speculate(Info, &Diag);
+
+      StmtVisitorTy::Visit(E->getFalseExpr());
+      if (Diag.empty())
+        return;
+
+      Diag.clear();
+      StmtVisitorTy::Visit(E->getTrueExpr());
+      if (Diag.empty())
+        return;
+    }
+
+    Error(E, diag::note_constexpr_conditional_never_const);
+  }
+
+
+  template<typename ConditionalOperator>
+  bool HandleConditionalOperator(const ConditionalOperator *E) {
+    bool BoolResult;
+    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
+      if (Info.CheckingPotentialConstantExpression)
+        CheckPotentialConstantConditional(E);
+      return false;
+    }
+
+    Expr *EvalExpr =3D BoolResult ? E->getTrueExpr() : E->getFalseExpr();
+    return StmtVisitorTy::Visit(EvalExpr);
   }
=20
 protected:
@@ -389,16 +2425,32 @@
   typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
=20
-  RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
+  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
+    return Info.CCEDiag(E, D);
+  }
+
+  RetTy ZeroInitialization(const Expr *E) { return Error(E); }
=20
 public:
   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
=20
+  EvalInfo &getEvalInfo() { return Info; }
+
+  /// Report an evaluation error. This should only be called when an error=
 is
+  /// first discovered. When propagating an error, just return false.
+  bool Error(const Expr *E, diag::kind D) {
+    Info.Diag(E, D);
+    return false;
+  }
+  bool Error(const Expr *E) {
+    return Error(E, diag::note_invalid_subexpr_in_const_expr);
+  }
+
   RetTy VisitStmt(const Stmt *) {
     llvm_unreachable("Expression evaluator should not be called on stmts");
   }
   RetTy VisitExpr(const Expr *E) {
-    return DerivedError(E);
+    return Error(E);
   }
=20
   RetTy VisitParenExpr(const ParenExpr *E)
@@ -413,186 +2465,573 @@
     { return StmtVisitorTy::Visit(E->getResultExpr()); }
   RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmEx=
pr *E)
     { return StmtVisitorTy::Visit(E->getReplacement()); }
+  RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
+    { return StmtVisitorTy::Visit(E->getExpr()); }
+  // We cannot create any objects for which cleanups are required, so ther=
e is
+  // nothing to do here; all cleanups must come from unevaluated subexpres=
sions.
+  RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
+    { return StmtVisitorTy::Visit(E->getSubExpr()); }
+
+  RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
+    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
+    return static_cast<Derived*>(this)->VisitCastExpr(E);
+  }
+  RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
+    CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
+    return static_cast<Derived*>(this)->VisitCastExpr(E);
+  }
+
+  RetTy VisitBinaryOperator(const BinaryOperator *E) {
+    switch (E->getOpcode()) {
+    default:
+      return Error(E);
+
+    case BO_Comma:
+      VisitIgnoredValue(E->getLHS());
+      return StmtVisitorTy::Visit(E->getRHS());
+
+    case BO_PtrMemD:
+    case BO_PtrMemI: {
+      LValue Obj;
+      if (!HandleMemberPointerAccess(Info, E, Obj))
+        return false;
+      APValue Result;
+      if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Resu=
lt))
+        return false;
+      return DerivedSuccess(Result, E);
+    }
+    }
+  }
=20
   RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E)=
 {
+    // Cache the value of the common expression.
     OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon()=
);
     if (opaque.hasError())
-      return DerivedError(E);
-
-    bool cond;
-    if (!HandleConversionToBool(E->getCond(), cond, Info))
-      return DerivedError(E);
-
-    return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr(=
));
+      return false;
+
+    return HandleConditionalOperator(E);
   }
=20
   RetTy VisitConditionalOperator(const ConditionalOperator *E) {
-    bool BoolResult;
-    if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
-      return DerivedError(E);
-
-    Expr* EvalExpr =3D BoolResult ? E->getTrueExpr() : E->getFalseExpr();
-    return StmtVisitorTy::Visit(EvalExpr);
+    bool IsBcpCall =3D false;
+    // If the condition (ignoring parens) is a __builtin_constant_p call,
+    // the result is a constant expression if it can be folded without
+    // side-effects. This is an important GNU extension. See GCC PR38377
+    // for discussion.
+    if (const CallExpr *CallCE =3D
+          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
+      if (CallCE->isBuiltinCall() =3D=3D Builtin::BI__builtin_constant_p)
+        IsBcpCall =3D true;
+
+    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
+    // constant expression; we can't check whether it's potentially foldab=
le.
+    if (Info.CheckingPotentialConstantExpression && IsBcpCall)
+      return false;
+
+    FoldConstant Fold(Info);
+
+    if (!HandleConditionalOperator(E))
+      return false;
+
+    if (IsBcpCall)
+      Fold.Fold(Info);
+
+    return true;
   }
=20
   RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
-    const APValue *value =3D Info.getOpaqueValue(E);
-    if (!value)
-      return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
-                                 : DerivedError(E));
-    return DerivedSuccess(*value, E);
-  }
-
+    const APValue *Value =3D Info.getOpaqueValue(E);
+    if (!Value) {
+      const Expr *Source =3D E->getSourceExpr();
+      if (!Source)
+        return Error(E);
+      if (Source =3D=3D E) { // sanity checking.
+        assert(0 && "OpaqueValueExpr recursively refers to itself");
+        return Error(E);
+      }
+      return StmtVisitorTy::Visit(Source);
+    }
+    return DerivedSuccess(*Value, E);
+  }
+
+  RetTy VisitCallExpr(const CallExpr *E) {
+    const Expr *Callee =3D E->getCallee()->IgnoreParens();
+    QualType CalleeType =3D Callee->getType();
+
+    const FunctionDecl *FD =3D 0;
+    LValue *This =3D 0, ThisVal;
+    llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
+    bool HasQualifier =3D false;
+
+    // Extract function decl and 'this' pointer from the callee.
+    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
+      const ValueDecl *Member =3D 0;
+      if (const MemberExpr *ME =3D dyn_cast<MemberExpr>(Callee)) {
+        // Explicit bound member calls, such as x.f() or p->g();
+        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
+          return false;
+        Member =3D ME->getMemberDecl();
+        This =3D &ThisVal;
+        HasQualifier =3D ME->hasQualifier();
+      } else if (const BinaryOperator *BE =3D dyn_cast<BinaryOperator>(Cal=
lee)) {
+        // Indirect bound member calls ('.*' or '->*').
+        Member =3D HandleMemberPointerAccess(Info, BE, ThisVal, false);
+        if (!Member) return false;
+        This =3D &ThisVal;
+      } else
+        return Error(Callee);
+
+      FD =3D dyn_cast<FunctionDecl>(Member);
+      if (!FD)
+        return Error(Callee);
+    } else if (CalleeType->isFunctionPointerType()) {
+      LValue Call;
+      if (!EvaluatePointer(Callee, Call, Info))
+        return false;
+
+      if (!Call.getLValueOffset().isZero())
+        return Error(Callee);
+      FD =3D dyn_cast_or_null<FunctionDecl>(
+                             Call.getLValueBase().dyn_cast<const ValueDecl=
*>());
+      if (!FD)
+        return Error(Callee);
+
+      // Overloaded operator calls to member functions are represented as =
normal
+      // calls with '*this' as the first argument.
+      const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(FD);
+      if (MD && !MD->isStatic()) {
+        // FIXME: When selecting an implicit conversion for an overloaded
+        // operator delete, we sometimes try to evaluate calls to conversi=
on
+        // operators without a 'this' parameter!
+        if (Args.empty())
+          return Error(E);
+
+        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
+          return false;
+        This =3D &ThisVal;
+        Args =3D Args.slice(1);
+      }
+
+      // Don't call function pointers which have been cast to some other t=
ype.
+      if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType(=
)))
+        return Error(E);
+    } else
+      return Error(E);
+
+    if (This && !This->checkSubobject(Info, E, CSK_This))
+      return false;
+
+    // DR1358 allows virtual constexpr functions in some cases. Don't allow
+    // calls to such functions in constant expressions.
+    if (This && !HasQualifier &&
+        isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
+      return Error(E, diag::note_constexpr_virtual_call);
+
+    const FunctionDecl *Definition =3D 0;
+    Stmt *Body =3D FD->getBody(Definition);
+    APValue Result;
+
+    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
+        !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
+                            Info, Result))
+      return false;
+
+    return DerivedSuccess(Result, E);
+  }
+
+  RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
+    return StmtVisitorTy::Visit(E->getInitializer());
+  }
   RetTy VisitInitListExpr(const InitListExpr *E) {
-    if (Info.getLangOpts().CPlusPlus0x) {
-      if (E->getNumInits() =3D=3D 0)
-        return DerivedValueInitialization(E);
-      if (E->getNumInits() =3D=3D 1)
-        return StmtVisitorTy::Visit(E->getInit(0));
-    }
-    return DerivedError(E);
+    if (E->getNumInits() =3D=3D 0)
+      return DerivedZeroInitialization(E);
+    if (E->getNumInits() =3D=3D 1)
+      return StmtVisitorTy::Visit(E->getInit(0));
+    return Error(E);
   }
   RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
-    return DerivedValueInitialization(E);
+    return DerivedZeroInitialization(E);
   }
   RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
-    return DerivedValueInitialization(E);
-  }
-
+    return DerivedZeroInitialization(E);
+  }
+  RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
+    return DerivedZeroInitialization(E);
+  }
+
+  /// A member expression where the object is a prvalue is itself a prvalu=
e.
+  RetTy VisitMemberExpr(const MemberExpr *E) {
+    assert(!E->isArrow() && "missing call to bound member function?");
+
+    APValue Val;
+    if (!Evaluate(Val, Info, E->getBase()))
+      return false;
+
+    QualType BaseTy =3D E->getBase()->getType();
+
+    const FieldDecl *FD =3D dyn_cast<FieldDecl>(E->getMemberDecl());
+    if (!FD) return Error(E);
+    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
+    assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() =3D=
=3D
+           FD->getParent()->getCanonicalDecl() && "record / field mismatch=
");
+
+    SubobjectDesignator Designator(BaseTy);
+    Designator.addDeclUnchecked(FD);
+
+    return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()=
) &&
+           DerivedSuccess(Val, E);
+  }
+
+  RetTy VisitCastExpr(const CastExpr *E) {
+    switch (E->getCastKind()) {
+    default:
+      break;
+
+    case CK_AtomicToNonAtomic:
+    case CK_NonAtomicToAtomic:
+    case CK_NoOp:
+    case CK_UserDefinedConversion:
+      return StmtVisitorTy::Visit(E->getSubExpr());
+
+    case CK_LValueToRValue: {
+      LValue LVal;
+      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
+        return false;
+      APValue RVal;
+      // Note, we use the subexpression's type in order to retain cv-quali=
fiers.
+      if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getTyp=
e(),
+                                          LVal, RVal))
+        return false;
+      return DerivedSuccess(RVal, E);
+    }
+    }
+
+    return Error(E);
+  }
+
+  /// Visit a value which is evaluated, but whose value is ignored.
+  void VisitIgnoredValue(const Expr *E) {
+    APValue Scratch;
+    if (!Evaluate(Scratch, Info, E))
+      Info.EvalStatus.HasSideEffects =3D true;
+  }
 };
=20
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Common base class for lvalue and temporary evaluation.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+namespace {
+template<class Derived>
+class LValueExprEvaluatorBase
+  : public ExprEvaluatorBase<Derived, bool> {
+protected:
+  LValue &Result;
+  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
+  typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
+
+  bool Success(APValue::LValueBase B) {
+    Result.set(B);
+    return true;
+  }
+
+public:
+  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
+    ExprEvaluatorBaseTy(Info), Result(Result) {}
+
+  bool Success(const APValue &V, const Expr *E) {
+    Result.setFrom(this->Info.Ctx, V);
+    return true;
+  }
+
+  bool VisitMemberExpr(const MemberExpr *E) {
+    // Handle non-static data members.
+    QualType BaseTy;
+    if (E->isArrow()) {
+      if (!EvaluatePointer(E->getBase(), Result, this->Info))
+        return false;
+      BaseTy =3D E->getBase()->getType()->getAs<PointerType>()->getPointee=
Type();
+    } else if (E->getBase()->isRValue()) {
+      assert(E->getBase()->getType()->isRecordType());
+      if (!EvaluateTemporary(E->getBase(), Result, this->Info))
+        return false;
+      BaseTy =3D E->getBase()->getType();
+    } else {
+      if (!this->Visit(E->getBase()))
+        return false;
+      BaseTy =3D E->getBase()->getType();
+    }
+
+    const ValueDecl *MD =3D E->getMemberDecl();
+    if (const FieldDecl *FD =3D dyn_cast<FieldDecl>(E->getMemberDecl())) {
+      assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() =
=3D=3D
+             FD->getParent()->getCanonicalDecl() && "record / field mismat=
ch");
+      (void)BaseTy;
+      HandleLValueMember(this->Info, E, Result, FD);
+    } else if (const IndirectFieldDecl *IFD =3D dyn_cast<IndirectFieldDecl=
>(MD)) {
+      HandleLValueIndirectMember(this->Info, E, Result, IFD);
+    } else
+      return this->Error(E);
+
+    if (MD->getType()->isReferenceType()) {
+      APValue RefValue;
+      if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Re=
sult,
+                                          RefValue))
+        return false;
+      return Success(RefValue, E);
+    }
+    return true;
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *E) {
+    switch (E->getOpcode()) {
+    default:
+      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
+
+    case BO_PtrMemD:
+    case BO_PtrMemI:
+      return HandleMemberPointerAccess(this->Info, E, Result);
+    }
+  }
+
+  bool VisitCastExpr(const CastExpr *E) {
+    switch (E->getCastKind()) {
+    default:
+      return ExprEvaluatorBaseTy::VisitCastExpr(E);
+
+    case CK_DerivedToBase:
+    case CK_UncheckedDerivedToBase: {
+      if (!this->Visit(E->getSubExpr()))
+        return false;
+
+      // Now figure out the necessary offset to add to the base LV to get =
from
+      // the derived class to the base class.
+      QualType Type =3D E->getSubExpr()->getType();
+
+      for (CastExpr::path_const_iterator PathI =3D E->path_begin(),
+           PathE =3D E->path_end(); PathI !=3D PathE; ++PathI) {
+        if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordD=
ecl(),
+                              *PathI))
+          return false;
+        Type =3D (*PathI)->getType();
+      }
+
+      return true;
+    }
+    }
+  }
+};
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // LValue Evaluation
+//
+// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
+// function designators (in C), decl references to void objects (in C), and
+// temporaries (if building with -Wno-address-of-temporary).
+//
+// LValue evaluation produces values comprising a base expression of one o=
f the
+// following types:
+// - Declarations
+//  * VarDecl
+//  * FunctionDecl
+// - Literals
+//  * CompoundLiteralExpr in C
+//  * StringLiteral
+//  * CXXTypeidExpr
+//  * PredefinedExpr
+//  * ObjCStringLiteralExpr
+//  * ObjCEncodeExpr
+//  * AddrLabelExpr
+//  * BlockExpr
+//  * CallExpr for a MakeStringConstant builtin
+// - Locals and temporaries
+//  * Any Expr, with a CallIndex indicating the function in which the temp=
orary
+//    was evaluated.
+// plus an offset in bytes.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 namespace {
 class LValueExprEvaluator
-  : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
-  LValue &Result;
-  const Decl *PrevDecl;
-
-  bool Success(const Expr *E) {
-    Result.Base =3D E;
-    Result.Offset =3D CharUnits::Zero();
-    return true;
-  }
+  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
 public:
-
-  LValueExprEvaluator(EvalInfo &info, LValue &Result) :
-    ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
-
-  bool Success(const APValue &V, const Expr *E) {
-    Result.setFrom(V);
-    return true;
-  }
-  bool Error(const Expr *E) {
-    return false;
-  }
- =20
+  LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
+    LValueExprEvaluatorBaseTy(Info, Result) {}
+
+  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
+
   bool VisitDeclRefExpr(const DeclRefExpr *E);
   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
+  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
   bool VisitMemberExpr(const MemberExpr *E);
   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
+  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
   bool VisitUnaryDeref(const UnaryOperator *E);
+  bool VisitUnaryReal(const UnaryOperator *E);
+  bool VisitUnaryImag(const UnaryOperator *E);
=20
   bool VisitCastExpr(const CastExpr *E) {
     switch (E->getCastKind()) {
     default:
-      return false;
-
-    case CK_NoOp:
+      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
+
     case CK_LValueBitCast:
-      return Visit(E->getSubExpr());
-
-    // FIXME: Support CK_DerivedToBase and friends.
-    }
-  }
-
-  // FIXME: Missing: __real__, __imag__
-
+      this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
+      if (!Visit(E->getSubExpr()))
+        return false;
+      Result.Designator.setInvalid();
+      return true;
+
+    case CK_BaseToDerived:
+      if (!Visit(E->getSubExpr()))
+        return false;
+      return HandleBaseToDerivedCast(Info, E, Result);
+    }
+  }
 };
 } // end anonymous namespace
=20
+/// Evaluate an expression as an lvalue. This can be legitimately called on
+/// expressions which are not glvalues, in a few cases:
+///  * function designators in C,
+///  * "extern void" objects,
+///  * temporaries, if building with -Wno-address-of-temporary.
 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
+  assert((E->isGLValue() || E->getType()->isFunctionType() ||
+          E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
+         "can't evaluate expression as an lvalue");
   return LValueExprEvaluator(Info, Result).Visit(E);
 }
=20
 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
-  if (isa<FunctionDecl>(E->getDecl())) {
-    return Success(E);
-  } else if (const VarDecl* VD =3D dyn_cast<VarDecl>(E->getDecl())) {
-    if (!VD->getType()->isReferenceType())
-      return Success(E);
-    // Reference parameters can refer to anything even if they have an
-    // "initializer" in the form of a default argument.
-    if (!isa<ParmVarDecl>(VD)) {
-      // FIXME: Check whether VD might be overridden!
-
-      // Check for recursive initializers of references.
-      if (PrevDecl =3D=3D VD)
-        return Error(E);
-      PrevDecl =3D VD;
-      if (const Expr *Init =3D VD->getAnyInitializer())
-        return Visit(Init);
-    }
-  }
-
-  return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
+  if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(E->getDecl()))
+    return Success(FD);
+  if (const VarDecl *VD =3D dyn_cast<VarDecl>(E->getDecl()))
+    return VisitVarDecl(E, VD);
+  return Error(E);
+}
+
+bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
+  if (!VD->getType()->isReferenceType()) {
+    if (isa<ParmVarDecl>(VD)) {
+      Result.set(VD, Info.CurrentCall->Index);
+      return true;
+    }
+    return Success(VD);
+  }
+
+  APValue V;
+  if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
+    return false;
+  return Success(V, E);
+}
+
+bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
+    const MaterializeTemporaryExpr *E) {
+  if (E->GetTemporaryExpr()->isRValue()) {
+    if (E->getType()->isRecordType())
+      return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
+
+    Result.set(E, Info.CurrentCall->Index);
+    return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
+                           Result, E->GetTemporaryExpr());
+  }
+
+  // Materialization of an lvalue temporary occurs when we need to force a=
 copy
+  // (for instance, if it's a bitfield).
+  // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
+  if (!Visit(E->GetTemporaryExpr()))
+    return false;
+  if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
+                                      Info.CurrentCall->Temporaries[E]))
+    return false;
+  Result.set(E, Info.CurrentCall->Index);
+  return true;
 }
=20
 bool
 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E=
) {
+  assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?=
");
+  // Defer visiting the literal until the lvalue-to-rvalue conversion. We =
can
+  // only see this when folding in C, so there's no standard to follow her=
e.
   return Success(E);
 }
=20
+bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
+  if (E->isTypeOperand())
+    return Success(E);
+  CXXRecordDecl *RD =3D E->getExprOperand()->getType()->getAsCXXRecordDecl=
();
+  if (RD && RD->isPolymorphic()) {
+    Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
+      << E->getExprOperand()->getType()
+      << E->getExprOperand()->getSourceRange();
+    return false;
+  }
+  return Success(E);
+}
+
 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
-  QualType Ty;
-  if (E->isArrow()) {
-    if (!EvaluatePointer(E->getBase(), Result, Info))
-      return false;
-    Ty =3D E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
-  } else {
-    if (!Visit(E->getBase()))
-      return false;
-    Ty =3D E->getBase()->getType();
-  }
-
-  const RecordDecl *RD =3D Ty->getAs<RecordType>()->getDecl();
-  const ASTRecordLayout &RL =3D Info.Ctx.getASTRecordLayout(RD);
-
-  const FieldDecl *FD =3D dyn_cast<FieldDecl>(E->getMemberDecl());
-  if (!FD) // FIXME: deal with other kinds of member expressions
-    return false;
-
-  if (FD->getType()->isReferenceType())
-    return false;
-
-  unsigned i =3D FD->getFieldIndex();
-  Result.Offset +=3D Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
-  return true;
+  // Handle static data members.
+  if (const VarDecl *VD =3D dyn_cast<VarDecl>(E->getMemberDecl())) {
+    VisitIgnoredValue(E->getBase());
+    return VisitVarDecl(E, VD);
+  }
+
+  // Handle static member functions.
+  if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(E->getMemberDecl=
())) {
+    if (MD->isStatic()) {
+      VisitIgnoredValue(E->getBase());
+      return Success(MD);
+    }
+  }
+
+  // Handle non-static data members.
+  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
 }
=20
 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr=
 *E) {
+  // FIXME: Deal with vectors as array subscript bases.
+  if (E->getBase()->getType()->isVectorType())
+    return Error(E);
+
   if (!EvaluatePointer(E->getBase(), Result, Info))
     return false;
=20
   APSInt Index;
   if (!EvaluateInteger(E->getIdx(), Index, Info))
     return false;
-
-  CharUnits ElementSize =3D Info.Ctx.getTypeSizeInChars(E->getType());
-  Result.Offset +=3D Index.getSExtValue() * ElementSize;
-  return true;
+  int64_t IndexValue
+    =3D Index.isSigned() ? Index.getSExtValue()
+                       : static_cast<int64_t>(Index.getZExtValue());
+
+  return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexV=
alue);
 }
=20
 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
   return EvaluatePointer(E->getSubExpr(), Result, Info);
 }
=20
+bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
+  if (!Visit(E->getSubExpr()))
+    return false;
+  // __real is a no-op on scalar lvalues.
+  if (E->getSubExpr()->getType()->isAnyComplexType())
+    HandleLValueComplexElement(Info, E, Result, E->getType(), false);
+  return true;
+}
+
+bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
+  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
+         "lvalue __imag__ on scalar?");
+  if (!Visit(E->getSubExpr()))
+    return false;
+  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
+  return true;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Pointer Evaluation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -603,8 +3042,7 @@
   LValue &Result;
=20
   bool Success(const Expr *E) {
-    Result.Base =3D E;
-    Result.Offset =3D CharUnits::Zero();
+    Result.set(E);
     return true;
   }
 public:
@@ -613,13 +3051,10 @@
     : ExprEvaluatorBaseTy(info), Result(Result) {}
=20
   bool Success(const APValue &V, const Expr *E) {
-    Result.setFrom(V);
+    Result.setFrom(Info.Ctx, V);
     return true;
   }
-  bool Error(const Stmt *S) {
-    return false;
-  }
-  bool ValueInitialization(const Expr *E) {
+  bool ZeroInitialization(const Expr *E) {
     return Success((Expr*)0);
   }
=20
@@ -628,71 +3063,64 @@
   bool VisitUnaryAddrOf(const UnaryOperator *E);
   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
       { return Success(E); }
+  bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
+      { return Success(E); }   =20
   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
       { return Success(E); }
   bool VisitCallExpr(const CallExpr *E);
   bool VisitBlockExpr(const BlockExpr *E) {
     if (!E->getBlockDecl()->hasCaptures())
       return Success(E);
-    return false;
-  }
-  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
-      { return ValueInitialization(E); }
+    return Error(E);
+  }
+  bool VisitCXXThisExpr(const CXXThisExpr *E) {
+    if (!Info.CurrentCall->This)
+      return Error(E);
+    Result =3D *Info.CurrentCall->This;
+    return true;
+  }
=20
   // FIXME: Missing: @protocol, @selector
 };
 } // end anonymous namespace
=20
 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info)=
 {
-  assert(E->getType()->hasPointerRepresentation());
+  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
   return PointerExprEvaluator(Info, Result).Visit(E);
 }
=20
 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
   if (E->getOpcode() !=3D BO_Add &&
       E->getOpcode() !=3D BO_Sub)
-    return false;
+    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
=20
   const Expr *PExp =3D E->getLHS();
   const Expr *IExp =3D E->getRHS();
   if (IExp->getType()->isPointerType())
     std::swap(PExp, IExp);
=20
-  if (!EvaluatePointer(PExp, Result, Info))
+  bool EvalPtrOK =3D EvaluatePointer(PExp, Result, Info);
+  if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
     return false;
=20
   llvm::APSInt Offset;
-  if (!EvaluateInteger(IExp, Offset, Info))
+  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
     return false;
   int64_t AdditionalOffset
     =3D Offset.isSigned() ? Offset.getSExtValue()
                         : static_cast<int64_t>(Offset.getZExtValue());
-
-  // Compute the new offset in the appropriate width.
-
-  QualType PointeeType =3D
-    PExp->getType()->getAs<PointerType>()->getPointeeType();
-  CharUnits SizeOfPointee;
-
-  // Explicitly handle GNU void* and function pointer arithmetic extension=
s.
-  if (PointeeType->isVoidType() || PointeeType->isFunctionType())
-    SizeOfPointee =3D CharUnits::One();
-  else
-    SizeOfPointee =3D Info.Ctx.getTypeSizeInChars(PointeeType);
-
-  if (E->getOpcode() =3D=3D BO_Add)
-    Result.Offset +=3D AdditionalOffset * SizeOfPointee;
-  else
-    Result.Offset -=3D AdditionalOffset * SizeOfPointee;
-
-  return true;
+  if (E->getOpcode() =3D=3D BO_Sub)
+    AdditionalOffset =3D -AdditionalOffset;
+
+  QualType Pointee =3D PExp->getType()->getAs<PointerType>()->getPointeeTy=
pe();
+  return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
+                                     AdditionalOffset);
 }
=20
 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
   return EvaluateLValue(E->getSubExpr(), Result, Info);
 }
=20
-
 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
   const Expr* SubExpr =3D E->getSubExpr();
=20
@@ -700,260 +3128,654 @@
   default:
     break;
=20
-  case CK_NoOp:
   case CK_BitCast:
   case CK_CPointerToObjCPointerCast:
   case CK_BlockPointerToObjCPointerCast:
   case CK_AnyPointerToBlockPointerCast:
-    return Visit(SubExpr);
+    if (!Visit(SubExpr))
+      return false;
+    // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
+    // permitted in constant expressions in C++11. Bitcasts from cv void* =
are
+    // also static_casts, but we disallow them as a resolution to DR1312.
+    if (!E->getType()->isVoidPointerType()) {
+      Result.Designator.setInvalid();
+      if (SubExpr->getType()->isVoidPointerType())
+        CCEDiag(E, diag::note_constexpr_invalid_cast)
+          << 3 << SubExpr->getType();
+      else
+        CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
+    }
+    return true;
=20
   case CK_DerivedToBase:
   case CK_UncheckedDerivedToBase: {
-    LValue BaseLV;
-    if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
+    if (!EvaluatePointer(E->getSubExpr(), Result, Info))
       return false;
-
-    // Now figure out the necessary offset to add to the baseLV to get from
+    if (!Result.Base && Result.Offset.isZero())
+      return true;
+
+    // Now figure out the necessary offset to add to the base LV to get fr=
om
     // the derived class to the base class.
-    CharUnits Offset =3D CharUnits::Zero();
-
-    QualType Ty =3D E->getSubExpr()->getType();
-    const CXXRecordDecl *DerivedDecl =3D=20
-      Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
-
-    for (CastExpr::path_const_iterator PathI =3D E->path_begin(),=20
+    QualType Type =3D
+        E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(=
);
+
+    for (CastExpr::path_const_iterator PathI =3D E->path_begin(),
          PathE =3D E->path_end(); PathI !=3D PathE; ++PathI) {
-      const CXXBaseSpecifier *Base =3D *PathI;
-
-      // FIXME: If the base is virtual, we'd need to determine the type of=
 the
-      // most derived class and we don't support that right now.
-      if (Base->isVirtual())
+      if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
+                            *PathI))
         return false;
-
-      const CXXRecordDecl *BaseDecl =3D Base->getType()->getAsCXXRecordDec=
l();
-      const ASTRecordLayout &Layout =3D Info.Ctx.getASTRecordLayout(Derive=
dDecl);
-
-      Offset +=3D Layout.getBaseClassOffset(BaseDecl);
-      DerivedDecl =3D BaseDecl;
-    }
-
-    Result.Base =3D BaseLV.getLValueBase();
-    Result.Offset =3D BaseLV.getLValueOffset() + Offset;
+      Type =3D (*PathI)->getType();
+    }
+
     return true;
   }
=20
-  case CK_NullToPointer: {
-    Result.Base =3D 0;
-    Result.Offset =3D CharUnits::Zero();
-    return true;
-  }
+  case CK_BaseToDerived:
+    if (!Visit(E->getSubExpr()))
+      return false;
+    if (!Result.Base && Result.Offset.isZero())
+      return true;
+    return HandleBaseToDerivedCast(Info, E, Result);
+
+  case CK_NullToPointer:
+    VisitIgnoredValue(E->getSubExpr());
+    return ZeroInitialization(E);
=20
   case CK_IntegralToPointer: {
+    CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
+
     APValue Value;
     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
       break;
=20
     if (Value.isInt()) {
-      Value.getInt() =3D Value.getInt().extOrTrunc((unsigned)Info.Ctx.getT=
ypeSize(E->getType()));
-      Result.Base =3D 0;
-      Result.Offset =3D CharUnits::fromQuantity(Value.getInt().getZExtValu=
e());
+      unsigned Size =3D Info.Ctx.getTypeSize(E->getType());
+      uint64_t N =3D Value.getInt().extOrTrunc(Size).getZExtValue();
+      Result.Base =3D (Expr*)0;
+      Result.Offset =3D CharUnits::fromQuantity(N);
+      Result.CallIndex =3D 0;
+      Result.Designator.setInvalid();
       return true;
     } else {
       // Cast is of an lvalue, no need to change value.
-      Result.Base =3D Value.getLValueBase();
-      Result.Offset =3D Value.getLValueOffset();
+      Result.setFrom(Info.Ctx, Value);
       return true;
     }
   }
   case CK_ArrayToPointerDecay:
+    if (SubExpr->isGLValue()) {
+      if (!EvaluateLValue(SubExpr, Result, Info))
+        return false;
+    } else {
+      Result.set(SubExpr, Info.CurrentCall->Index);
+      if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
+                           Info, Result, SubExpr))
+        return false;
+    }
+    // The result is a pointer to the first element of the array.
+    if (const ConstantArrayType *CAT
+          =3D Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
+      Result.addArray(Info, E, CAT);
+    else
+      Result.Designator.setInvalid();
+    return true;
+
   case CK_FunctionToPointerDecay:
     return EvaluateLValue(SubExpr, Result, Info);
   }
=20
-  return false;
+  return ExprEvaluatorBaseTy::VisitCastExpr(E);
 }
=20
 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
-  if (E->isBuiltinCall(Info.Ctx) =3D=3D
-        Builtin::BI__builtin___CFStringMakeConstantString ||
-      E->isBuiltinCall(Info.Ctx) =3D=3D
-        Builtin::BI__builtin___NSStringMakeConstantString)
+  if (IsStringLiteralCall(E))
     return Success(E);
=20
   return ExprEvaluatorBaseTy::VisitCallExpr(E);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Member Pointer Evaluation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+class MemberPointerExprEvaluator
+  : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
+  MemberPtr &Result;
+
+  bool Success(const ValueDecl *D) {
+    Result =3D MemberPtr(D);
+    return true;
+  }
+public:
+
+  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
+    : ExprEvaluatorBaseTy(Info), Result(Result) {}
+
+  bool Success(const APValue &V, const Expr *E) {
+    Result.setFrom(V);
+    return true;
+  }
+  bool ZeroInitialization(const Expr *E) {
+    return Success((const ValueDecl*)0);
+  }
+
+  bool VisitCastExpr(const CastExpr *E);
+  bool VisitUnaryAddrOf(const UnaryOperator *E);
+};
+} // end anonymous namespace
+
+static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
+                                  EvalInfo &Info) {
+  assert(E->isRValue() && E->getType()->isMemberPointerType());
+  return MemberPointerExprEvaluator(Info, Result).Visit(E);
+}
+
+bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
+  switch (E->getCastKind()) {
+  default:
+    return ExprEvaluatorBaseTy::VisitCastExpr(E);
+
+  case CK_NullToMemberPointer:
+    VisitIgnoredValue(E->getSubExpr());
+    return ZeroInitialization(E);
+
+  case CK_BaseToDerivedMemberPointer: {
+    if (!Visit(E->getSubExpr()))
+      return false;
+    if (E->path_empty())
+      return true;
+    // Base-to-derived member pointer casts store the path in derived-to-b=
ase
+    // order, so iterate backwards. The CXXBaseSpecifier also provides us =
with
+    // the wrong end of the derived->base arc, so stagger the path by one =
class.
+    typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIt=
er;
+    for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
+         PathI !=3D PathE; ++PathI) {
+      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
+      const CXXRecordDecl *Derived =3D (*PathI)->getType()->getAsCXXRecord=
Decl();
+      if (!Result.castToDerived(Derived))
+        return Error(E);
+    }
+    const Type *FinalTy =3D E->getType()->castAs<MemberPointerType>()->get=
Class();
+    if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
+      return Error(E);
+    return true;
+  }
+
+  case CK_DerivedToBaseMemberPointer:
+    if (!Visit(E->getSubExpr()))
+      return false;
+    for (CastExpr::path_const_iterator PathI =3D E->path_begin(),
+         PathE =3D E->path_end(); PathI !=3D PathE; ++PathI) {
+      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
+      const CXXRecordDecl *Base =3D (*PathI)->getType()->getAsCXXRecordDec=
l();
+      if (!Result.castToBase(Base))
+        return Error(E);
+    }
+    return true;
+  }
+}
+
+bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
+  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
+  // member can be formed.
+  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Record Evaluation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+  class RecordExprEvaluator
+  : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
+    const LValue &This;
+    APValue &Result;
+  public:
+
+    RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Resul=
t)
+      : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
+
+    bool Success(const APValue &V, const Expr *E) {
+      Result =3D V;
+      return true;
+    }
+    bool ZeroInitialization(const Expr *E);
+
+    bool VisitCastExpr(const CastExpr *E);
+    bool VisitInitListExpr(const InitListExpr *E);
+    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
+  };
+}
+
+/// Perform zero-initialization on an object of non-union class type.
+/// C++11 [dcl.init]p5:
+///  To zero-initialize an object or reference of type T means:
+///    [...]
+///    -- if T is a (possibly cv-qualified) non-union class type,
+///       each non-static data member and each base-class subobject is
+///       zero-initialized
+static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
+                                          const RecordDecl *RD,
+                                          const LValue &This, APValue &Res=
ult) {
+  assert(!RD->isUnion() && "Expected non-union class type");
+  const CXXRecordDecl *CD =3D dyn_cast<CXXRecordDecl>(RD);
+  Result =3D APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
+                   std::distance(RD->field_begin(), RD->field_end()));
+
+  const ASTRecordLayout &Layout =3D Info.Ctx.getASTRecordLayout(RD);
+
+  if (CD) {
+    unsigned Index =3D 0;
+    for (CXXRecordDecl::base_class_const_iterator I =3D CD->bases_begin(),
+           End =3D CD->bases_end(); I !=3D End; ++I, ++Index) {
+      const CXXRecordDecl *Base =3D I->getType()->getAsCXXRecordDecl();
+      LValue Subobject =3D This;
+      HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
+      if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
+                                         Result.getStructBase(Index)))
+        return false;
+    }
+  }
+
+  for (RecordDecl::field_iterator I =3D RD->field_begin(), End =3D RD->fie=
ld_end();
+       I !=3D End; ++I) {
+    // -- if T is a reference type, no initialization is performed.
+    if ((*I)->getType()->isReferenceType())
+      continue;
+
+    LValue Subobject =3D This;
+    HandleLValueMember(Info, E, Subobject, *I, &Layout);
+
+    ImplicitValueInitExpr VIE((*I)->getType());
+    if (!EvaluateInPlace(
+          Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &=
VIE))
+      return false;
+  }
+
+  return true;
+}
+
+bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
+  const RecordDecl *RD =3D E->getType()->castAs<RecordType>()->getDecl();
+  if (RD->isUnion()) {
+    // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, t=
he
+    // object's first non-static named data member is zero-initialized
+    RecordDecl::field_iterator I =3D RD->field_begin();
+    if (I =3D=3D RD->field_end()) {
+      Result =3D APValue((const FieldDecl*)0);
+      return true;
+    }
+
+    LValue Subobject =3D This;
+    HandleLValueMember(Info, E, Subobject, *I);
+    Result =3D APValue(*I);
+    ImplicitValueInitExpr VIE((*I)->getType());
+    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
+  }
+
+  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
+    Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
+    return false;
+  }
+
+  return HandleClassZeroInitialization(Info, E, RD, This, Result);
+}
+
+bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
+  switch (E->getCastKind()) {
+  default:
+    return ExprEvaluatorBaseTy::VisitCastExpr(E);
+
+  case CK_ConstructorConversion:
+    return Visit(E->getSubExpr());
+
+  case CK_DerivedToBase:
+  case CK_UncheckedDerivedToBase: {
+    APValue DerivedObject;
+    if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
+      return false;
+    if (!DerivedObject.isStruct())
+      return Error(E->getSubExpr());
+
+    // Derived-to-base rvalue conversion: just slice off the derived part.
+    APValue *Value =3D &DerivedObject;
+    const CXXRecordDecl *RD =3D E->getSubExpr()->getType()->getAsCXXRecord=
Decl();
+    for (CastExpr::path_const_iterator PathI =3D E->path_begin(),
+         PathE =3D E->path_end(); PathI !=3D PathE; ++PathI) {
+      assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
+      const CXXRecordDecl *Base =3D (*PathI)->getType()->getAsCXXRecordDec=
l();
+      Value =3D &Value->getStructBase(getBaseIndex(RD, Base));
+      RD =3D Base;
+    }
+    Result =3D *Value;
+    return true;
+  }
+  }
+}
+
+bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
+  // Cannot constant-evaluate std::initializer_list inits.
+  if (E->initializesStdInitializerList())
+    return false;
+
+  const RecordDecl *RD =3D E->getType()->castAs<RecordType>()->getDecl();
+  const ASTRecordLayout &Layout =3D Info.Ctx.getASTRecordLayout(RD);
+
+  if (RD->isUnion()) {
+    const FieldDecl *Field =3D E->getInitializedFieldInUnion();
+    Result =3D APValue(Field);
+    if (!Field)
+      return true;
+
+    // If the initializer list for a union does not contain any elements, =
the
+    // first element of the union is value-initialized.
+    ImplicitValueInitExpr VIE(Field->getType());
+    const Expr *InitExpr =3D E->getNumInits() ? E->getInit(0) : &VIE;
+
+    LValue Subobject =3D This;
+    HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
+    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitEx=
pr);
+  }
+
+  assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases=
()) &&
+         "initializer list for class with base classes");
+  Result =3D APValue(APValue::UninitStruct(), 0,
+                   std::distance(RD->field_begin(), RD->field_end()));
+  unsigned ElementNo =3D 0;
+  bool Success =3D true;
+  for (RecordDecl::field_iterator Field =3D RD->field_begin(),
+       FieldEnd =3D RD->field_end(); Field !=3D FieldEnd; ++Field) {
+    // Anonymous bit-fields are not considered members of the class for
+    // purposes of aggregate initialization.
+    if (Field->isUnnamedBitfield())
+      continue;
+
+    LValue Subobject =3D This;
+
+    bool HaveInit =3D ElementNo < E->getNumInits();
+
+    // FIXME: Diagnostics here should point to the end of the initializer
+    // list, not the start.
+    HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobje=
ct,
+                       *Field, &Layout);
+
+    // Perform an implicit value-initialization for members beyond the end=
 of
+    // the initializer list.
+    ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()=
);
+
+    if (!EvaluateInPlace(
+          Result.getStructField((*Field)->getFieldIndex()),
+          Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
+      if (!Info.keepEvaluatingAfterFailure())
+        return false;
+      Success =3D false;
+    }
+  }
+
+  return Success;
+}
+
+bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E)=
 {
+  const CXXConstructorDecl *FD =3D E->getConstructor();
+  bool ZeroInit =3D E->requiresZeroInitialization();
+  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit))=
 {
+    // If we've already performed zero-initialization, we're already done.
+    if (!Result.isUninit())
+      return true;
+
+    if (ZeroInit)
+      return ZeroInitialization(E);
+
+    const CXXRecordDecl *RD =3D FD->getParent();
+    if (RD->isUnion())
+      Result =3D APValue((FieldDecl*)0);
+    else
+      Result =3D APValue(APValue::UninitStruct(), RD->getNumBases(),
+                       std::distance(RD->field_begin(), RD->field_end()));
+    return true;
+  }
+
+  const FunctionDecl *Definition =3D 0;
+  FD->getBody(Definition);
+
+  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
+    return false;
+
+  // Avoid materializing a temporary for an elidable copy/move constructor.
+  if (E->isElidable() && !ZeroInit)
+    if (const MaterializeTemporaryExpr *ME
+          =3D dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
+      return Visit(ME->GetTemporaryExpr());
+
+  if (ZeroInit && !ZeroInitialization(E))
+    return false;
+
+  llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
+  return HandleConstructorCall(E->getExprLoc(), This, Args,
+                               cast<CXXConstructorDecl>(Definition), Info,
+                               Result);
+}
+
+static bool EvaluateRecord(const Expr *E, const LValue &This,
+                           APValue &Result, EvalInfo &Info) {
+  assert(E->isRValue() && E->getType()->isRecordType() &&
+         "can't evaluate expression as a record rvalue");
+  return RecordExprEvaluator(Info, This, Result).Visit(E);
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Temporary Evaluation
+//
+// Temporaries are represented in the AST as rvalues, but generally behave=
 like
+// lvalues. The full-object of which the temporary is a subobject is impli=
citly
+// materialized so that a reference can bind to it.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+namespace {
+class TemporaryExprEvaluator
+  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
+public:
+  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
+    LValueExprEvaluatorBaseTy(Info, Result) {}
+
+  /// Visit an expression which constructs the value of this temporary.
+  bool VisitConstructExpr(const Expr *E) {
+    Result.set(E, Info.CurrentCall->Index);
+    return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result,=
 E);
+  }
+
+  bool VisitCastExpr(const CastExpr *E) {
+    switch (E->getCastKind()) {
+    default:
+      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
+
+    case CK_ConstructorConversion:
+      return VisitConstructExpr(E->getSubExpr());
+    }
+  }
+  bool VisitInitListExpr(const InitListExpr *E) {
+    return VisitConstructExpr(E);
+  }
+  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
+    return VisitConstructExpr(E);
+  }
+  bool VisitCallExpr(const CallExpr *E) {
+    return VisitConstructExpr(E);
+  }
+};
+} // end anonymous namespace
+
+/// Evaluate an expression of record type as a temporary.
+static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Inf=
o) {
+  assert(E->isRValue() && E->getType()->isRecordType());
+  return TemporaryExprEvaluator(Info, Result).Visit(E);
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Vector Evaluation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 namespace {
   class VectorExprEvaluator
-  : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
-    APValue GetZeroVector(QualType VecType);
+  : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
+    APValue &Result;
   public:
=20
-    VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
-
-    APValue Success(const APValue &V, const Expr *E) { return V; }
-    APValue Error(const Expr *E) { return APValue(); }
-    APValue ValueInitialization(const Expr *E)
-      { return GetZeroVector(E->getType()); }
-
-    APValue VisitUnaryReal(const UnaryOperator *E)
+    VectorExprEvaluator(EvalInfo &info, APValue &Result)
+      : ExprEvaluatorBaseTy(info), Result(Result) {}
+
+    bool Success(const ArrayRef<APValue> &V, const Expr *E) {
+      assert(V.size() =3D=3D E->getType()->castAs<VectorType>()->getNumEle=
ments());
+      // FIXME: remove this APValue copy.
+      Result =3D APValue(V.data(), V.size());
+      return true;
+    }
+    bool Success(const APValue &V, const Expr *E) {
+      assert(V.isVector());
+      Result =3D V;
+      return true;
+    }
+    bool ZeroInitialization(const Expr *E);
+
+    bool VisitUnaryReal(const UnaryOperator *E)
       { return Visit(E->getSubExpr()); }
-    APValue VisitCastExpr(const CastExpr* E);
-    APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
-    APValue VisitInitListExpr(const InitListExpr *E);
-    APValue VisitUnaryImag(const UnaryOperator *E);
+    bool VisitCastExpr(const CastExpr* E);
+    bool VisitInitListExpr(const InitListExpr *E);
+    bool VisitUnaryImag(const UnaryOperator *E);
     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
     //                 binary comparisons, binary and/or/xor,
     //                 shufflevector, ExtVectorElementExpr
-    //        (Note that these require implementing conversions
-    //         between vector types.)
   };
 } // end anonymous namespace
=20
 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info)=
 {
-  if (!E->getType()->isVectorType())
-    return false;
-  Result =3D VectorExprEvaluator(Info).Visit(E);
-  return !Result.isUninit();
-}
-
-APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
-  const VectorType *VTy =3D E->getType()->getAs<VectorType>();
-  QualType EltTy =3D VTy->getElementType();
+  assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rva=
lue");
+  return VectorExprEvaluator(Info, Result).Visit(E);
+}
+
+bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
+  const VectorType *VTy =3D E->getType()->castAs<VectorType>();
   unsigned NElts =3D VTy->getNumElements();
-  unsigned EltWidth =3D Info.Ctx.getTypeSize(EltTy);
-
-  const Expr* SE =3D E->getSubExpr();
+
+  const Expr *SE =3D E->getSubExpr();
   QualType SETy =3D SE->getType();
=20
   switch (E->getCastKind()) {
   case CK_VectorSplat: {
-    APValue Result =3D APValue();
+    APValue Val =3D APValue();
     if (SETy->isIntegerType()) {
       APSInt IntResult;
       if (!EvaluateInteger(SE, IntResult, Info))
-         return APValue();
-      Result =3D APValue(IntResult);
+         return false;
+      Val =3D APValue(IntResult);
     } else if (SETy->isRealFloatingType()) {
        APFloat F(0.0);
        if (!EvaluateFloat(SE, F, Info))
-         return APValue();
-       Result =3D APValue(F);
+         return false;
+       Val =3D APValue(F);
     } else {
-      return APValue();
+      return Error(E);
     }
=20
     // Splat and create vector APValue.
-    SmallVector<APValue, 4> Elts(NElts, Result);
-    return APValue(&Elts[0], Elts.size());
+    SmallVector<APValue, 4> Elts(NElts, Val);
+    return Success(Elts, E);
   }
   case CK_BitCast: {
-    if (SETy->isVectorType())
-      return Visit(SE);
-
-    if (!SETy->isIntegerType())
-      return APValue();
-
-    APSInt Init;
-    if (!EvaluateInteger(SE, Init, Info))
-      return APValue();
-
-    assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
-           "Vectors must be composed of ints or floats");
-
+    // Evaluate the operand into an APInt we can extract from.
+    llvm::APInt SValInt;
+    if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
+      return false;
+    // Extract the elements
+    QualType EltTy =3D VTy->getElementType();
+    unsigned EltSize =3D Info.Ctx.getTypeSize(EltTy);
+    bool BigEndian =3D Info.Ctx.getTargetInfo().isBigEndian();
     SmallVector<APValue, 4> Elts;
-    for (unsigned i =3D 0; i !=3D NElts; ++i) {
-      APSInt Tmp =3D Init.extOrTrunc(EltWidth);
-
-      if (EltTy->isIntegerType())
-        Elts.push_back(APValue(Tmp));
-      else
-        Elts.push_back(APValue(APFloat(Tmp)));
-
-      Init >>=3D EltWidth;
-    }
-    return APValue(&Elts[0], Elts.size());
-  }
-  case CK_LValueToRValue:
-  case CK_NoOp:
-    return Visit(SE);
+    if (EltTy->isRealFloatingType()) {
+      const llvm::fltSemantics &Sem =3D Info.Ctx.getFloatTypeSemantics(Elt=
Ty);
+      bool isIEESem =3D &Sem !=3D &APFloat::PPCDoubleDouble;
+      unsigned FloatEltSize =3D EltSize;
+      if (&Sem =3D=3D &APFloat::x87DoubleExtended)
+        FloatEltSize =3D 80;
+      for (unsigned i =3D 0; i < NElts; i++) {
+        llvm::APInt Elt;
+        if (BigEndian)
+          Elt =3D SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
+        else
+          Elt =3D SValInt.rotr(i*EltSize).trunc(FloatEltSize);
+        Elts.push_back(APValue(APFloat(Elt, isIEESem)));
+      }
+    } else if (EltTy->isIntegerType()) {
+      for (unsigned i =3D 0; i < NElts; i++) {
+        llvm::APInt Elt;
+        if (BigEndian)
+          Elt =3D SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
+        else
+          Elt =3D SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
+        Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
+      }
+    } else {
+      return Error(E);
+    }
+    return Success(Elts, E);
+  }
   default:
-    return APValue();
-  }
-}
-
-APValue
-VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E=
) {
-  return this->Visit(E->getInitializer());
-}
-
-APValue
+    return ExprEvaluatorBaseTy::VisitCastExpr(E);
+  }
+}
+
+bool
 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
-  const VectorType *VT =3D E->getType()->getAs<VectorType>();
+  const VectorType *VT =3D E->getType()->castAs<VectorType>();
   unsigned NumInits =3D E->getNumInits();
   unsigned NumElements =3D VT->getNumElements();
=20
   QualType EltTy =3D VT->getElementType();
   SmallVector<APValue, 4> Elements;
=20
-  // If a vector is initialized with a single element, that value
-  // becomes every element of the vector, not just the first.
-  // This is the behavior described in the IBM AltiVec documentation.
-  if (NumInits =3D=3D 1) {
-   =20
-    // Handle the case where the vector is initialized by a another=20
-    // vector (OpenCL 6.1.6).
-    if (E->getInit(0)->getType()->isVectorType())
-      return this->Visit(const_cast<Expr*>(E->getInit(0)));
-   =20
-    APValue InitValue;
-    if (EltTy->isIntegerType()) {
+  // The number of initializers can be less than the number of
+  // vector elements. For OpenCL, this can be due to nested vector
+  // initialization. For GCC compatibility, missing trailing elements=20
+  // should be initialized with zeroes.
+  unsigned CountInits =3D 0, CountElts =3D 0;
+  while (CountElts < NumElements) {
+    // Handle nested vector initialization.
+    if (CountInits < NumInits=20
+        && E->getInit(CountInits)->getType()->isExtVectorType()) {
+      APValue v;
+      if (!EvaluateVector(E->getInit(CountInits), v, Info))
+        return Error(E);
+      unsigned vlen =3D v.getVectorLength();
+      for (unsigned j =3D 0; j < vlen; j++)=20
+        Elements.push_back(v.getVectorElt(j));
+      CountElts +=3D vlen;
+    } else if (EltTy->isIntegerType()) {
       llvm::APSInt sInt(32);
-      if (!EvaluateInteger(E->getInit(0), sInt, Info))
-        return APValue();
-      InitValue =3D APValue(sInt);
+      if (CountInits < NumInits) {
+        if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
+          return false;
+      } else // trailing integer zero.
+        sInt =3D Info.Ctx.MakeIntValue(0, EltTy);
+      Elements.push_back(APValue(sInt));
+      CountElts++;
     } else {
       llvm::APFloat f(0.0);
-      if (!EvaluateFloat(E->getInit(0), f, Info))
-        return APValue();
-      InitValue =3D APValue(f);
-    }
-    for (unsigned i =3D 0; i < NumElements; i++) {
-      Elements.push_back(InitValue);
-    }
-  } else {
-    for (unsigned i =3D 0; i < NumElements; i++) {
-      if (EltTy->isIntegerType()) {
-        llvm::APSInt sInt(32);
-        if (i < NumInits) {
-          if (!EvaluateInteger(E->getInit(i), sInt, Info))
-            return APValue();
-        } else {
-          sInt =3D Info.Ctx.MakeIntValue(0, EltTy);
-        }
-        Elements.push_back(APValue(sInt));
-      } else {
-        llvm::APFloat f(0.0);
-        if (i < NumInits) {
-          if (!EvaluateFloat(E->getInit(i), f, Info))
-            return APValue();
-        } else {
-          f =3D APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
-        }
-        Elements.push_back(APValue(f));
-      }
-    }
-  }
-  return APValue(&Elements[0], Elements.size());
-}
-
-APValue
-VectorExprEvaluator::GetZeroVector(QualType T) {
-  const VectorType *VT =3D T->getAs<VectorType>();
+      if (CountInits < NumInits) {
+        if (!EvaluateFloat(E->getInit(CountInits), f, Info))
+          return false;
+      } else // trailing float zero.
+        f =3D APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
+      Elements.push_back(APValue(f));
+      CountElts++;
+    }
+    CountInits++;
+  }
+  return Success(Elements, E);
+}
+
+bool
+VectorExprEvaluator::ZeroInitialization(const Expr *E) {
+  const VectorType *VT =3D E->getType()->getAs<VectorType>();
   QualType EltTy =3D VT->getElementType();
   APValue ZeroElement;
   if (EltTy->isIntegerType())
@@ -963,17 +3785,175 @@
         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
=20
   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
-  return APValue(&Elements[0], Elements.size());
-}
-
-APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
-  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
-    Info.EvalResult.HasSideEffects =3D true;
-  return GetZeroVector(E->getType());
+  return Success(Elements, E);
+}
+
+bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
+  VisitIgnoredValue(E->getSubExpr());
+  return ZeroInitialization(E);
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Array Evaluation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+  class ArrayExprEvaluator
+  : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
+    const LValue &This;
+    APValue &Result;
+  public:
+
+    ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
+      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
+
+    bool Success(const APValue &V, const Expr *E) {
+      assert((V.isArray() || V.isLValue()) &&
+             "expected array or string literal");
+      Result =3D V;
+      return true;
+    }
+
+    bool ZeroInitialization(const Expr *E) {
+      const ConstantArrayType *CAT =3D
+          Info.Ctx.getAsConstantArrayType(E->getType());
+      if (!CAT)
+        return Error(E);
+
+      Result =3D APValue(APValue::UninitArray(), 0,
+                       CAT->getSize().getZExtValue());
+      if (!Result.hasArrayFiller()) return true;
+
+      // Zero-initialize all elements.
+      LValue Subobject =3D This;
+      Subobject.addArray(Info, E, CAT);
+      ImplicitValueInitExpr VIE(CAT->getElementType());
+      return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VI=
E);
+    }
+
+    bool VisitInitListExpr(const InitListExpr *E);
+    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
+  };
+} // end anonymous namespace
+
+static bool EvaluateArray(const Expr *E, const LValue &This,
+                          APValue &Result, EvalInfo &Info) {
+  assert(E->isRValue() && E->getType()->isArrayType() && "not an array rva=
lue");
+  return ArrayExprEvaluator(Info, This, Result).Visit(E);
+}
+
+bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
+  const ConstantArrayType *CAT =3D Info.Ctx.getAsConstantArrayType(E->getT=
ype());
+  if (!CAT)
+    return Error(E);
+
+  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [=
...]
+  // an appropriately-typed string literal enclosed in braces.
+  if (E->getNumInits() =3D=3D 1 && E->getInit(0)->isGLValue() &&
+      Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType=
())) {
+    LValue LV;
+    if (!EvaluateLValue(E->getInit(0), LV, Info))
+      return false;
+    APValue Val;
+    LV.moveInto(Val);
+    return Success(Val, E);
+  }
+
+  bool Success =3D true;
+
+  Result =3D APValue(APValue::UninitArray(), E->getNumInits(),
+                   CAT->getSize().getZExtValue());
+  LValue Subobject =3D This;
+  Subobject.addArray(Info, E, CAT);
+  unsigned Index =3D 0;
+  for (InitListExpr::const_iterator I =3D E->begin(), End =3D E->end();
+       I !=3D End; ++I, ++Index) {
+    if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
+                         Info, Subobject, cast<Expr>(*I)) ||
+        !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
+                                     CAT->getElementType(), 1)) {
+      if (!Info.keepEvaluatingAfterFailure())
+        return false;
+      Success =3D false;
+    }
+  }
+
+  if (!Result.hasArrayFiller()) return Success;
+  assert(E->hasArrayFiller() && "no array filler for incomplete init list"=
);
+  // FIXME: The Subobject here isn't necessarily right. This rarely matter=
s,
+  // but sometimes does:
+  //   struct S { constexpr S() : p(&p) {} void *p; };
+  //   S s[10] =3D {};
+  return EvaluateInPlace(Result.getArrayFiller(), Info,
+                         Subobject, E->getArrayFiller()) && Success;
+}
+
+bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
+  const ConstantArrayType *CAT =3D Info.Ctx.getAsConstantArrayType(E->getT=
ype());
+  if (!CAT)
+    return Error(E);
+
+  bool HadZeroInit =3D !Result.isUninit();
+  if (!HadZeroInit)
+    Result =3D APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtVa=
lue());
+  if (!Result.hasArrayFiller())
+    return true;
+
+  const CXXConstructorDecl *FD =3D E->getConstructor();
+
+  bool ZeroInit =3D E->requiresZeroInitialization();
+  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit))=
 {
+    if (HadZeroInit)
+      return true;
+
+    if (ZeroInit) {
+      LValue Subobject =3D This;
+      Subobject.addArray(Info, E, CAT);
+      ImplicitValueInitExpr VIE(CAT->getElementType());
+      return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VI=
E);
+    }
+
+    const CXXRecordDecl *RD =3D FD->getParent();
+    if (RD->isUnion())
+      Result.getArrayFiller() =3D APValue((FieldDecl*)0);
+    else
+      Result.getArrayFiller() =3D
+          APValue(APValue::UninitStruct(), RD->getNumBases(),
+                  std::distance(RD->field_begin(), RD->field_end()));
+    return true;
+  }
+
+  const FunctionDecl *Definition =3D 0;
+  FD->getBody(Definition);
+
+  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
+    return false;
+
+  // FIXME: The Subobject here isn't necessarily right. This rarely matter=
s,
+  // but sometimes does:
+  //   struct S { constexpr S() : p(&p) {} void *p; };
+  //   S s[10];
+  LValue Subobject =3D This;
+  Subobject.addArray(Info, E, CAT);
+
+  if (ZeroInit && !HadZeroInit) {
+    ImplicitValueInitExpr VIE(CAT->getElementType());
+    if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
+      return false;
+  }
+
+  llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
+  return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
+                               cast<CXXConstructorDecl>(Definition),
+                               Info, Result.getArrayFiller());
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Integer Evaluation
+//
+// As a GNU extension, we support casting pointers to sufficiently-wide in=
teger
+// types and back in constant folding. Integer values are thus represented
+// either as an integer-valued APValue, or as an lvalue-valued APValue.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 namespace {
@@ -984,7 +3964,7 @@
   IntExprEvaluator(EvalInfo &info, APValue &result)
     : ExprEvaluatorBaseTy(info), Result(result) {}
=20
-  bool Success(const llvm::APSInt &SI, const Expr *E) {
+  bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
     assert(E->getType()->isIntegralOrEnumerationType() &&
            "Invalid evaluation result.");
     assert(SI.isSigned() =3D=3D E->getType()->isSignedIntegerOrEnumeration=
Type() &&
@@ -994,8 +3974,11 @@
     Result =3D APValue(SI);
     return true;
   }
-
-  bool Success(const llvm::APInt &I, const Expr *E) {
+  bool Success(const llvm::APSInt &SI, const Expr *E) {
+    return Success(SI, E, Result);
+  }
+
+  bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
     assert(E->getType()->isIntegralOrEnumerationType() &&=20
            "Invalid evaluation result.");
     assert(I.getBitWidth() =3D=3D Info.Ctx.getIntWidth(E->getType()) &&
@@ -1005,37 +3988,33 @@
                             E->getType()->isUnsignedIntegerOrEnumerationTy=
pe());
     return true;
   }
-
-  bool Success(uint64_t Value, const Expr *E) {
+  bool Success(const llvm::APInt &I, const Expr *E) {
+    return Success(I, E, Result);
+  }
+
+  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
     assert(E->getType()->isIntegralOrEnumerationType() &&=20
            "Invalid evaluation result.");
     Result =3D APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
     return true;
   }
+  bool Success(uint64_t Value, const Expr *E) {
+    return Success(Value, E, Result);
+  }
=20
   bool Success(CharUnits Size, const Expr *E) {
     return Success(Size.getQuantity(), E);
   }
=20
-
-  bool Error(SourceLocation L, diag::kind D, const Expr *E) {
-    // Take the first error.
-    if (Info.EvalResult.Diag =3D=3D 0) {
-      Info.EvalResult.DiagLoc =3D L;
-      Info.EvalResult.Diag =3D D;
-      Info.EvalResult.DiagExpr =3D E;
-    }
-    return false;
-  }
-
   bool Success(const APValue &V, const Expr *E) {
+    if (V.isLValue() || V.isAddrLabelDiff()) {
+      Result =3D V;
+      return true;
+    }
     return Success(V.getInt(), E);
   }
-  bool Error(const Expr *E) {
-    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
-  }
-
-  bool ValueInitialization(const Expr *E) { return Success(0, E); }
+
+  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   //                            Visitor Methods
@@ -1057,8 +4036,7 @@
   }
   bool VisitMemberExpr(const MemberExpr *E) {
     if (CheckReferencedDecl(E, E->getMemberDecl())) {
-      // Conservatively assume a MemberExpr will have side-effects
-      Info.EvalResult.HasSideEffects =3D true;
+      VisitIgnoredValue(E->getBase());
       return true;
     }
=20
@@ -1077,9 +4055,13 @@
     return Success(E->getValue(), E);
   }
=20
+  bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
+    return Success(E->getValue(), E);
+  }
+   =20
   // Note, GNU defines __null as an integer, not a pointer.
   bool VisitGNUNullExpr(const GNUNullExpr *E) {
-    return ValueInitialization(E);
+    return ZeroInitialization(E);
   }
=20
   bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
@@ -1090,6 +4072,10 @@
     return Success(E->getValue(), E);
   }
=20
+  bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
+    return Success(E->getValue(), E);
+  }
+
   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
     return Success(E->getValue(), E);
   }
@@ -1107,27 +4093,43 @@
 private:
   CharUnits GetAlignOfExpr(const Expr *E);
   CharUnits GetAlignOfType(QualType T);
-  static QualType GetObjectType(const Expr *E);
+  static QualType GetObjectType(APValue::LValueBase B);
   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
   // FIXME: Missing: array subscript of vector, member of vector
 };
 } // end anonymous namespace
=20
-static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalIn=
fo &Info) {
-  assert(E->getType()->isIntegralOrEnumerationType());
+/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression=
, and
+/// produce either the integer value or a pointer.
+///
+/// GCC has a heinous extension which folds casts between pointer types and
+/// pointer-sized integral types. We support this by allowing the evaluati=
on of
+/// an integer rvalue to produce a pointer (represented as an lvalue) inst=
ead.
+/// Some simple arithmetic on such values is supported (they are treated m=
uch
+/// like char*).
+static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
+                                    EvalInfo &Info) {
+  assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
   return IntExprEvaluator(Info, Result).Visit(E);
 }
=20
-static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info)=
 {
-  assert(E->getType()->isIntegralOrEnumerationType());
-
+static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)=
 {
   APValue Val;
-  if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
+  if (!EvaluateIntegerOrLValue(E, Val, Info))
     return false;
+  if (!Val.isInt()) {
+    // FIXME: It would be better to produce the diagnostic for casting
+    //        a pointer to an integer.
+    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+    return false;
+  }
   Result =3D Val.getInt();
   return true;
 }
=20
+/// Check whether the given declaration can be directly converted to an in=
tegral
+/// rvalue. If not, no diagnostic is produced; there are other things we c=
an
+/// try.
 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
   // Enums are integer constant exprs.
   if (const EnumConstantDecl *ECD =3D dyn_cast<EnumConstantDecl>(D)) {
@@ -1149,43 +4151,6 @@
       return Success(Val, E);
     }
   }
-
-  // In C++, const, non-volatile integers initialized with ICEs are ICEs.
-  // In C, they can also be folded, although they are not ICEs.
-  if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()=20
-                                                        =3D=3D Qualifiers:=
:Const) {
-
-    if (isa<ParmVarDecl>(D))
-      return false;
-
-    if (const VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
-      if (const Expr *Init =3D VD->getAnyInitializer()) {
-        if (APValue *V =3D VD->getEvaluatedValue()) {
-          if (V->isInt())
-            return Success(V->getInt(), E);
-          return false;
-        }
-
-        if (VD->isEvaluatingValue())
-          return false;
-
-        VD->setEvaluatingValue();
-
-        Expr::EvalResult EResult;
-        if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
-            EResult.Val.isInt()) {
-          // Cache the evaluated value in the variable declaration.
-          Result =3D EResult.Val;
-          VD->setEvaluatedValue(Result);
-          return true;
-        }
-
-        VD->setEvaluatedValue(APValue());
-      }
-    }
-  }
-
-  // Otherwise, random variable references are not constants.
   return false;
 }
=20
@@ -1242,17 +4207,72 @@
     return union_type_class;
   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented typ=
e");
-  return -1;
+}
+
+/// EvaluateBuiltinConstantPForLValue - Determine the result of
+/// __builtin_constant_p when applied to the given lvalue.
+///
+/// An lvalue is only "constant" if it is a pointer or reference to the fi=
rst
+/// character of a string literal.
+template<typename LValue>
+static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
+  const Expr *E =3D LV.getLValueBase().template dyn_cast<const Expr*>();
+  return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
+}
+
+/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly =
to
+/// GCC as we can manage.
+static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
+  QualType ArgType =3D Arg->getType();
+
+  // __builtin_constant_p always has one operand. The rules which gcc foll=
ows
+  // are not precisely documented, but are as follows:
+  //
+  //  - If the operand is of integral, floating, complex or enumeration ty=
pe,
+  //    and can be folded to a known value of that type, it returns 1.
+  //  - If the operand and can be folded to a pointer to the first charact=
er
+  //    of a string literal (or such a pointer cast to an integral type), =
it
+  //    returns 1.
+  //
+  // Otherwise, it returns 0.
+  //
+  // FIXME: GCC also intends to return 1 for literals of aggregate types, =
but
+  // its support for this does not currently work.
+  if (ArgType->isIntegralOrEnumerationType()) {
+    Expr::EvalResult Result;
+    if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
+      return false;
+
+    APValue &V =3D Result.Val;
+    if (V.getKind() =3D=3D APValue::Int)
+      return true;
+
+    return EvaluateBuiltinConstantPForLValue(V);
+  } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
+    return Arg->isEvaluatable(Ctx);
+  } else if (ArgType->isPointerType() || Arg->isGLValue()) {
+    LValue LV;
+    Expr::EvalStatus Status;
+    EvalInfo Info(Ctx, Status);
+    if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
+                          : EvaluatePointer(Arg, LV, Info)) &&
+        !Status.HasSideEffects)
+      return EvaluateBuiltinConstantPForLValue(LV);
+  }
+
+  // Anything else isn't considered to be sufficiently constant.
+  return false;
 }
=20
 /// Retrieves the "underlying object type" of the given expression,
 /// as used by __builtin_object_size.
-QualType IntExprEvaluator::GetObjectType(const Expr *E) {
-  if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E)) {
-    if (const VarDecl *VD =3D dyn_cast<VarDecl>(DRE->getDecl()))
+QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
+  if (const ValueDecl *D =3D B.dyn_cast<const ValueDecl*>()) {
+    if (const VarDecl *VD =3D dyn_cast<VarDecl>(D))
       return VD->getType();
-  } else if (isa<CompoundLiteralExpr>(E)) {
-    return E->getType();
+  } else if (const Expr *E =3D B.get<const Expr*>()) {
+    if (isa<CompoundLiteralExpr>(E))
+      return E->getType();
   }
=20
   return QualType();
@@ -1265,16 +4285,15 @@
     return false;
=20
   // If we can prove the base is null, lower to zero now.
-  const Expr *LVBase =3D Base.getLValueBase();
-  if (!LVBase) return Success(0, E);
-
-  QualType T =3D GetObjectType(LVBase);
+  if (!Base.getLValueBase()) return Success(0, E);
+
+  QualType T =3D GetObjectType(Base.getLValueBase());
   if (T.isNull() ||
       T->isIncompleteType() ||
       T->isFunctionType() ||
       T->isVariablyModifiedType() ||
       T->isDependentType())
-    return false;
+    return Error(E);
=20
   CharUnits Size =3D Info.Ctx.getTypeSizeInChars(T);
   CharUnits Offset =3D Base.getLValueOffset();
@@ -1287,7 +4306,7 @@
 }
=20
 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
-  switch (E->isBuiltinCall(Info.Ctx)) {
+  switch (unsigned BuiltinOp =3D E->isBuiltinCall()) {
   default:
     return ExprEvaluatorBaseTy::VisitCallExpr(E);
=20
@@ -1303,17 +4322,15 @@
       return Success(0, E);
     }
=20
-    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
+    return Error(E);
   }
=20
   case Builtin::BI__builtin_classify_type:
     return Success(EvaluateBuiltinClassifyType(E), E);
=20
   case Builtin::BI__builtin_constant_p:
-    // __builtin_constant_p always has one operand: it returns true if that
-    // operand can be folded, false otherwise.
-    return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
-     =20
+    return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
+
   case Builtin::BI__builtin_eh_return_data_regno: {
     int Operand =3D E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtV=
alue();
     Operand =3D Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
@@ -1322,8 +4339,15 @@
=20
   case Builtin::BI__builtin_expect:
     return Visit(E->getArg(0));
-     =20
+
   case Builtin::BIstrlen:
+    // A call to strlen is not a constant expression.
+    if (Info.getLangOpts().CPlusPlus0x)
+      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
+        << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
+    else
+      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
+    // Fall through.
   case Builtin::BI__builtin_strlen:
     // As an extension, we support strlen() and __builtin_strlen() as cons=
tant
     // expressions when the argument is a string literal.
@@ -1339,57 +4363,482 @@
       return Success(Str.size(), E);
     }
      =20
-    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
-  }
-}
-
-bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
+    return Error(E);
+
+  case Builtin::BI__atomic_always_lock_free:
+  case Builtin::BI__atomic_is_lock_free:
+  case Builtin::BI__c11_atomic_is_lock_free: {
+    APSInt SizeVal;
+    if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
+      return false;
+
+    // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a pow=
er
+    // of two less than the maximum inline atomic width, we know it is
+    // lock-free.  If the size isn't a power of two, or greater than the
+    // maximum alignment where we promote atomics, we know it is not lock-=
free
+    // (at least not in the sense of atomic_is_lock_free).  Otherwise,
+    // the answer can only be determined at runtime; for example, 16-byte
+    // atomics have lock-free implementations on some, but not all,
+    // x86-64 processors.
+
+    // Check power-of-two.
+    CharUnits Size =3D CharUnits::fromQuantity(SizeVal.getZExtValue());
+    if (Size.isPowerOfTwo()) {
+      // Check against inlining width.
+      unsigned InlineWidthBits =3D
+          Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
+      if (Size <=3D Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
+        if (BuiltinOp =3D=3D Builtin::BI__c11_atomic_is_lock_free ||
+            Size =3D=3D CharUnits::One() ||
+            E->getArg(1)->isNullPointerConstant(Info.Ctx,
+                                                Expr::NPC_NeverValueDepend=
ent))
+          // OK, we will inline appropriately-aligned operations of this s=
ize,
+          // and _Atomic(T) is appropriately-aligned.
+          return Success(1, E);
+
+        QualType PointeeType =3D E->getArg(1)->IgnoreImpCasts()->getType()=
->
+          castAs<PointerType>()->getPointeeType();
+        if (!PointeeType->isIncompleteType() &&
+            Info.Ctx.getTypeAlignInChars(PointeeType) >=3D Size) {
+          // OK, we will inline operations on this object.
+          return Success(1, E);
+        }
+      }
+    }
+
+    return BuiltinOp =3D=3D Builtin::BI__atomic_always_lock_free ?
+        Success(0, E) : Error(E);
+  }
+  }
+}
+
+static bool HasSameBase(const LValue &A, const LValue &B) {
+  if (!A.getLValueBase())
+    return !B.getLValueBase();
+  if (!B.getLValueBase())
+    return false;
+
+  if (A.getLValueBase().getOpaqueValue() !=3D
+      B.getLValueBase().getOpaqueValue()) {
+    const Decl *ADecl =3D GetLValueBaseDecl(A);
+    if (!ADecl)
+      return false;
+    const Decl *BDecl =3D GetLValueBaseDecl(B);
+    if (!BDecl || ADecl->getCanonicalDecl() !=3D BDecl->getCanonicalDecl())
+      return false;
+  }
+
+  return IsGlobalLValue(A.getLValueBase()) ||
+         A.getLValueCallIndex() =3D=3D B.getLValueCallIndex();
+}
+
+/// Perform the given integer operation, which is known to need at most Bi=
tWidth
+/// bits, and check for overflow in the original type (if that type was no=
t an
+/// unsigned type).
+template<typename Operation>
+static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
+                                   const APSInt &LHS, const APSInt &RHS,
+                                   unsigned BitWidth, Operation Op) {
+  if (LHS.isUnsigned())
+    return Op(LHS, RHS);
+
+  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
+  APSInt Result =3D Value.trunc(LHS.getBitWidth());
+  if (Result.extend(BitWidth) !=3D Value)
+    HandleOverflow(Info, E, Value, E->getType());
+  return Result;
+}
+
+namespace {
+
+/// \brief Data recursive integer evaluator of certain binary operators.
+///
+/// We use a data recursive algorithm for binary operators so that we are =
able
+/// to handle extreme cases of chained binary operators without causing st=
ack
+/// overflow.
+class DataRecursiveIntBinOpEvaluator {
+  struct EvalResult {
+    APValue Val;
+    bool Failed;
+
+    EvalResult() : Failed(false) { }
+
+    void swap(EvalResult &RHS) {
+      Val.swap(RHS.Val);
+      Failed =3D RHS.Failed;
+      RHS.Failed =3D false;
+    }
+  };
+
+  struct Job {
+    const Expr *E;
+    EvalResult LHSResult; // meaningful only for binary operator expressio=
n.
+    enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
+   =20
+    Job() : StoredInfo(0) { }
+    void startSpeculativeEval(EvalInfo &Info) {
+      OldEvalStatus =3D Info.EvalStatus;
+      Info.EvalStatus.Diag =3D 0;
+      StoredInfo =3D &Info;
+    }
+    ~Job() {
+      if (StoredInfo) {
+        StoredInfo->EvalStatus =3D OldEvalStatus;
+      }
+    }
+  private:
+    EvalInfo *StoredInfo; // non-null if status changed.
+    Expr::EvalStatus OldEvalStatus;
+  };
+
+  SmallVector<Job, 16> Queue;
+
+  IntExprEvaluator &IntEval;
+  EvalInfo &Info;
+  APValue &FinalResult;
+
+public:
+  DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Resul=
t)
+    : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) {=
 }
+
+  /// \brief True if \param E is a binary operator that we are going to ha=
ndle
+  /// data recursively.
+  /// We handle binary operators that are comma, logical, or that have ope=
rands
+  /// with integral or enumeration type.
+  static bool shouldEnqueue(const BinaryOperator *E) {
+    return E->getOpcode() =3D=3D BO_Comma ||
+           E->isLogicalOp() ||
+           (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
+            E->getRHS()->getType()->isIntegralOrEnumerationType());
+  }
+
+  bool Traverse(const BinaryOperator *E) {
+    enqueue(E);
+    EvalResult PrevResult;
+    while (!Queue.empty())
+      process(PrevResult);
+
+    if (PrevResult.Failed) return false;
+
+    FinalResult.swap(PrevResult.Val);
+    return true;
+  }
+
+private:
+  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
+    return IntEval.Success(Value, E, Result);
+  }
+  bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
+    return IntEval.Success(Value, E, Result);
+  }
+  bool Error(const Expr *E) {
+    return IntEval.Error(E);
+  }
+  bool Error(const Expr *E, diag::kind D) {
+    return IntEval.Error(E, D);
+  }
+
+  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
+    return Info.CCEDiag(E, D);
+  }
+
+  // \brief Returns true if visiting the RHS is necessary, false otherwise.
+  bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
+                         bool &SuppressRHSDiags);
+
+  bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
+                  const BinaryOperator *E, APValue &Result);
+
+  void EvaluateExpr(const Expr *E, EvalResult &Result) {
+    Result.Failed =3D !Evaluate(Result.Val, Info, E);
+    if (Result.Failed)
+      Result.Val =3D APValue();
+  }
+
+  void process(EvalResult &Result);
+
+  void enqueue(const Expr *E) {
+    E =3D E->IgnoreParens();
+    Queue.resize(Queue.size()+1);
+    Queue.back().E =3D E;
+    Queue.back().Kind =3D Job::AnyExprKind;
+  }
+};
+
+}
+
+bool DataRecursiveIntBinOpEvaluator::
+       VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
+                         bool &SuppressRHSDiags) {
   if (E->getOpcode() =3D=3D BO_Comma) {
-    if (!Visit(E->getRHS()))
-      return false;
-
-    // If we can't evaluate the LHS, it might have side effects;
-    // conservatively mark it.
-    if (!E->getLHS()->isEvaluatable(Info.Ctx))
-      Info.EvalResult.HasSideEffects =3D true;
-
+    // Ignore LHS but note if we could not evaluate it.
+    if (LHSResult.Failed)
+      Info.EvalStatus.HasSideEffects =3D true;
     return true;
   }
-
+ =20
   if (E->isLogicalOp()) {
-    // These need to be handled specially because the operands aren't
-    // necessarily integral
-    bool lhsResult, rhsResult;
-
-    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
+    bool lhsResult;
+    if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
       // We were able to evaluate the LHS, see if we can get away with not
       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
-      if (lhsResult =3D=3D (E->getOpcode() =3D=3D BO_LOr))
-        return Success(lhsResult, E);
-
-      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
-        if (E->getOpcode() =3D=3D BO_LOr)
-          return Success(lhsResult || rhsResult, E);
-        else
-          return Success(lhsResult && rhsResult, E);
+      if (lhsResult =3D=3D (E->getOpcode() =3D=3D BO_LOr)) {
+        Success(lhsResult, E, LHSResult.Val);
+        return false; // Ignore RHS
       }
     } else {
-      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
+      // Since we weren't able to evaluate the left hand side, it
+      // must have had side effects.
+      Info.EvalStatus.HasSideEffects =3D true;
+     =20
+      // We can't evaluate the LHS; however, sometimes the result
+      // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
+      // Don't ignore RHS and suppress diagnostics from this arm.
+      SuppressRHSDiags =3D true;
+    }
+   =20
+    return true;
+  }
+ =20
+  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
+         E->getRHS()->getType()->isIntegralOrEnumerationType());
+ =20
+  if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
+    return false; // Ignore RHS;
+
+  return true;
+}
+
+bool DataRecursiveIntBinOpEvaluator::
+       VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
+                  const BinaryOperator *E, APValue &Result) {
+  if (E->getOpcode() =3D=3D BO_Comma) {
+    if (RHSResult.Failed)
+      return false;
+    Result =3D RHSResult.Val;
+    return true;
+  }
+ =20
+  if (E->isLogicalOp()) {
+    bool lhsResult, rhsResult;
+    bool LHSIsOK =3D HandleConversionToBool(LHSResult.Val, lhsResult);
+    bool RHSIsOK =3D HandleConversionToBool(RHSResult.Val, rhsResult);
+   =20
+    if (LHSIsOK) {
+      if (RHSIsOK) {
+        if (E->getOpcode() =3D=3D BO_LOr)
+          return Success(lhsResult || rhsResult, E, Result);
+        else
+          return Success(lhsResult && rhsResult, E, Result);
+      }
+    } else {
+      if (RHSIsOK) {
         // We can't evaluate the LHS; however, sometimes the result
         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
-        if (rhsResult =3D=3D (E->getOpcode() =3D=3D BO_LOr) ||
-            !rhsResult =3D=3D (E->getOpcode() =3D=3D BO_LAnd)) {
-          // Since we weren't able to evaluate the left hand side, it
-          // must have had side effects.
-          Info.EvalResult.HasSideEffects =3D true;
-
-          return Success(rhsResult, E);
+        if (rhsResult =3D=3D (E->getOpcode() =3D=3D BO_LOr))
+          return Success(rhsResult, E, Result);
+      }
+    }
+   =20
+    return false;
+  }
+ =20
+  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
+         E->getRHS()->getType()->isIntegralOrEnumerationType());
+ =20
+  if (LHSResult.Failed || RHSResult.Failed)
+    return false;
+ =20
+  const APValue &LHSVal =3D LHSResult.Val;
+  const APValue &RHSVal =3D RHSResult.Val;
+ =20
+  // Handle cases like (unsigned long)&a + 4.
+  if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
+    Result =3D LHSVal;
+    CharUnits AdditionalOffset =3D CharUnits::fromQuantity(
+                                                         RHSVal.getInt().g=
etZExtValue());
+    if (E->getOpcode() =3D=3D BO_Add)
+      Result.getLValueOffset() +=3D AdditionalOffset;
+    else
+      Result.getLValueOffset() -=3D AdditionalOffset;
+    return true;
+  }
+ =20
+  // Handle cases like 4 + (unsigned long)&a
+  if (E->getOpcode() =3D=3D BO_Add &&
+      RHSVal.isLValue() && LHSVal.isInt()) {
+    Result =3D RHSVal;
+    Result.getLValueOffset() +=3D CharUnits::fromQuantity(
+                                                        LHSVal.getInt().ge=
tZExtValue());
+    return true;
+  }
+ =20
+  if (E->getOpcode() =3D=3D BO_Sub && LHSVal.isLValue() && RHSVal.isLValue=
()) {
+    // Handle (intptr_t)&&A - (intptr_t)&&B.
+    if (!LHSVal.getLValueOffset().isZero() ||
+        !RHSVal.getLValueOffset().isZero())
+      return false;
+    const Expr *LHSExpr =3D LHSVal.getLValueBase().dyn_cast<const Expr*>();
+    const Expr *RHSExpr =3D RHSVal.getLValueBase().dyn_cast<const Expr*>();
+    if (!LHSExpr || !RHSExpr)
+      return false;
+    const AddrLabelExpr *LHSAddrExpr =3D dyn_cast<AddrLabelExpr>(LHSExpr);
+    const AddrLabelExpr *RHSAddrExpr =3D dyn_cast<AddrLabelExpr>(RHSExpr);
+    if (!LHSAddrExpr || !RHSAddrExpr)
+      return false;
+    // Make sure both labels come from the same function.
+    if (LHSAddrExpr->getLabel()->getDeclContext() !=3D
+        RHSAddrExpr->getLabel()->getDeclContext())
+      return false;
+    Result =3D APValue(LHSAddrExpr, RHSAddrExpr);
+    return true;
+  }
+ =20
+  // All the following cases expect both operands to be an integer
+  if (!LHSVal.isInt() || !RHSVal.isInt())
+    return Error(E);
+ =20
+  const APSInt &LHS =3D LHSVal.getInt();
+  APSInt RHS =3D RHSVal.getInt();
+ =20
+  switch (E->getOpcode()) {
+    default:
+      return Error(E);
+    case BO_Mul:
+      return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
+                                          LHS.getBitWidth() * 2,
+                                          std::multiplies<APSInt>()), E,
+                     Result);
+    case BO_Add:
+      return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
+                                          LHS.getBitWidth() + 1,
+                                          std::plus<APSInt>()), E, Result);
+    case BO_Sub:
+      return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
+                                          LHS.getBitWidth() + 1,
+                                          std::minus<APSInt>()), E, Result=
);
+    case BO_And: return Success(LHS & RHS, E, Result);
+    case BO_Xor: return Success(LHS ^ RHS, E, Result);
+    case BO_Or:  return Success(LHS | RHS, E, Result);
+    case BO_Div:
+    case BO_Rem:
+      if (RHS =3D=3D 0)
+        return Error(E, diag::note_expr_divide_by_zero);
+      // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter=
 is
+      // not actually undefined behavior in C++11 due to a language defect.
+      if (RHS.isNegative() && RHS.isAllOnesValue() &&
+          LHS.isSigned() && LHS.isMinSignedValue())
+        HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->get=
Type());
+      return Success(E->getOpcode() =3D=3D BO_Rem ? LHS % RHS : LHS / RHS,=
 E,
+                     Result);
+    case BO_Shl: {
+      // During constant-folding, a negative shift is an opposite shift. S=
uch
+      // a shift is not a constant expression.
+      if (RHS.isSigned() && RHS.isNegative()) {
+        CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
+        RHS =3D -RHS;
+        goto shift_right;
+      }
+     =20
+    shift_left:
+      // C++11 [expr.shift]p1: Shift width must be less than the bit width=
 of
+      // the shifted type.
+      unsigned SA =3D (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
+      if (SA !=3D RHS) {
+        CCEDiag(E, diag::note_constexpr_large_shift)
+        << RHS << E->getType() << LHS.getBitWidth();
+      } else if (LHS.isSigned()) {
+        // C++11 [expr.shift]p2: A signed left shift must have a non-negat=
ive
+        // operand, and must not overflow the corresponding unsigned type.
+        if (LHS.isNegative())
+          CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
+        else if (LHS.countLeadingZeros() < SA)
+          CCEDiag(E, diag::note_constexpr_lshift_discards);
+      }
+     =20
+      return Success(LHS << SA, E, Result);
+    }
+    case BO_Shr: {
+      // During constant-folding, a negative shift is an opposite shift. S=
uch a
+      // shift is not a constant expression.
+      if (RHS.isSigned() && RHS.isNegative()) {
+        CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
+        RHS =3D -RHS;
+        goto shift_left;
+      }
+     =20
+    shift_right:
+      // C++11 [expr.shift]p1: Shift width must be less than the bit width=
 of the
+      // shifted type.
+      unsigned SA =3D (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
+      if (SA !=3D RHS)
+        CCEDiag(E, diag::note_constexpr_large_shift)
+        << RHS << E->getType() << LHS.getBitWidth();
+     =20
+      return Success(LHS >> SA, E, Result);
+    }
+     =20
+    case BO_LT: return Success(LHS < RHS, E, Result);
+    case BO_GT: return Success(LHS > RHS, E, Result);
+    case BO_LE: return Success(LHS <=3D RHS, E, Result);
+    case BO_GE: return Success(LHS >=3D RHS, E, Result);
+    case BO_EQ: return Success(LHS =3D=3D RHS, E, Result);
+    case BO_NE: return Success(LHS !=3D RHS, E, Result);
+  }
+}
+
+void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
+  Job &job =3D Queue.back();
+ =20
+  switch (job.Kind) {
+    case Job::AnyExprKind: {
+      if (const BinaryOperator *Bop =3D dyn_cast<BinaryOperator>(job.E)) {
+        if (shouldEnqueue(Bop)) {
+          job.Kind =3D Job::BinOpKind;
+          enqueue(Bop->getLHS());
+          return;
         }
       }
-    }
-
-    return false;
-  }
+     =20
+      EvaluateExpr(job.E, Result);
+      Queue.pop_back();
+      return;
+    }
+     =20
+    case Job::BinOpKind: {
+      const BinaryOperator *Bop =3D cast<BinaryOperator>(job.E);
+      bool SuppressRHSDiags =3D false;
+      if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
+        Queue.pop_back();
+        return;
+      }
+      if (SuppressRHSDiags)
+        job.startSpeculativeEval(Info);
+      job.LHSResult.swap(Result);
+      job.Kind =3D Job::BinOpVisitedLHSKind;
+      enqueue(Bop->getRHS());
+      return;
+    }
+     =20
+    case Job::BinOpVisitedLHSKind: {
+      const BinaryOperator *Bop =3D cast<BinaryOperator>(job.E);
+      EvalResult RHS;
+      RHS.swap(Result);
+      Result.Failed =3D !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
+      Queue.pop_back();
+      return;
+    }
+  }
+ =20
+  llvm_unreachable("Invalid Job::Kind!");
+}
+
+bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
+  if (E->isAssignmentOp())
+    return Error(E);
+
+  if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
+    return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
=20
   QualType LHSTy =3D E->getLHS()->getType();
   QualType RHSTy =3D E->getRHS()->getType();
@@ -1398,10 +4847,11 @@
     assert(RHSTy->isAnyComplexType() && "Invalid comparison");
     ComplexValue LHS, RHS;
=20
-    if (!EvaluateComplex(E->getLHS(), LHS, Info))
+    bool LHSOK =3D EvaluateComplex(E->getLHS(), LHS, Info);
+    if (!LHSOK && !Info.keepEvaluatingAfterFailure())
       return false;
=20
-    if (!EvaluateComplex(E->getRHS(), RHS, Info))
+    if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
       return false;
=20
     if (LHS.isComplexFloat()) {
@@ -1440,10 +4890,11 @@
       RHSTy->isRealFloatingType()) {
     APFloat RHS(0.0), LHS(0.0);
=20
-    if (!EvaluateFloat(E->getRHS(), RHS, Info))
+    bool LHSOK =3D EvaluateFloat(E->getRHS(), RHS, Info);
+    if (!LHSOK && !Info.keepEvaluatingAfterFailure())
       return false;
=20
-    if (!EvaluateFloat(E->getLHS(), LHS, Info))
+    if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
       return false;
=20
     APFloat::cmpResult CR =3D LHS.compare(RHS);
@@ -1470,155 +4921,232 @@
   }
=20
   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
-    if (E->getOpcode() =3D=3D BO_Sub || E->isEqualityOp()) {
-      LValue LHSValue;
-      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
+    if (E->getOpcode() =3D=3D BO_Sub || E->isComparisonOp()) {
+      LValue LHSValue, RHSValue;
+
+      bool LHSOK =3D EvaluatePointer(E->getLHS(), LHSValue, Info);
+      if (!LHSOK && Info.keepEvaluatingAfterFailure())
         return false;
=20
-      LValue RHSValue;
-      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
+      if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
         return false;
=20
-      // Reject any bases from the normal codepath; we special-case compar=
isons
-      // to null.
-      if (LHSValue.getLValueBase()) {
+      // Reject differing bases from the normal codepath; we special-case
+      // comparisons to null.
+      if (!HasSameBase(LHSValue, RHSValue)) {
+        if (E->getOpcode() =3D=3D BO_Sub) {
+          // Handle &&A - &&B.
+          if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
+            return false;
+          const Expr *LHSExpr =3D LHSValue.Base.dyn_cast<const Expr*>();
+          const Expr *RHSExpr =3D LHSValue.Base.dyn_cast<const Expr*>();
+          if (!LHSExpr || !RHSExpr)
+            return false;
+          const AddrLabelExpr *LHSAddrExpr =3D dyn_cast<AddrLabelExpr>(LHS=
Expr);
+          const AddrLabelExpr *RHSAddrExpr =3D dyn_cast<AddrLabelExpr>(RHS=
Expr);
+          if (!LHSAddrExpr || !RHSAddrExpr)
+            return false;
+          // Make sure both labels come from the same function.
+          if (LHSAddrExpr->getLabel()->getDeclContext() !=3D
+              RHSAddrExpr->getLabel()->getDeclContext())
+            return false;
+          Result =3D APValue(LHSAddrExpr, RHSAddrExpr);
+          return true;
+        }
+        // Inequalities and subtractions between unrelated pointers have
+        // unspecified or undefined behavior.
         if (!E->isEqualityOp())
-          return false;
-        if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero=
())
-          return false;
-        bool bres;
-        if (!EvalPointerValueAsBool(LHSValue, bres))
-          return false;
-        return Success(bres ^ (E->getOpcode() =3D=3D BO_EQ), E);
-      } else if (RHSValue.getLValueBase()) {
-        if (!E->isEqualityOp())
-          return false;
-        if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero=
())
-          return false;
-        bool bres;
-        if (!EvalPointerValueAsBool(RHSValue, bres))
-          return false;
-        return Success(bres ^ (E->getOpcode() =3D=3D BO_EQ), E);
+          return Error(E);
+        // A constant address may compare equal to the address of a symbol.
+        // The one exception is that address of an object cannot compare e=
qual
+        // to a null pointer constant.
+        if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
+            (!RHSValue.Base && !RHSValue.Offset.isZero()))
+          return Error(E);
+        // It's implementation-defined whether distinct literals will have
+        // distinct addresses. In clang, the result of such a comparison is
+        // unspecified, so it is not a constant expression. However, we do=
 know
+        // that the address of a literal will be non-null.
+        if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
+            LHSValue.Base && RHSValue.Base)
+          return Error(E);
+        // We can't tell whether weak symbols will end up pointing to the =
same
+        // object.
+        if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
+          return Error(E);
+        // Pointers with different bases cannot represent the same object.
+        // (Note that clang defaults to -fmerge-all-constants, which can
+        // lead to inconsistent results for comparisons involving the addr=
ess
+        // of a constant; this generally doesn't matter in practice.)
+        return Success(E->getOpcode() =3D=3D BO_NE, E);
       }
=20
+      const CharUnits &LHSOffset =3D LHSValue.getLValueOffset();
+      const CharUnits &RHSOffset =3D RHSValue.getLValueOffset();
+
+      SubobjectDesignator &LHSDesignator =3D LHSValue.getLValueDesignator(=
);
+      SubobjectDesignator &RHSDesignator =3D RHSValue.getLValueDesignator(=
);
+
       if (E->getOpcode() =3D=3D BO_Sub) {
+        // C++11 [expr.add]p6:
+        //   Unless both pointers point to elements of the same array obje=
ct, or
+        //   one past the last element of the array object, the behavior is
+        //   undefined.
+        if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
+            !AreElementsOfSameArray(getType(LHSValue.Base),
+                                    LHSDesignator, RHSDesignator))
+          CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_arr=
ay);
+
         QualType Type =3D E->getLHS()->getType();
         QualType ElementType =3D Type->getAs<PointerType>()->getPointeeTyp=
e();
=20
-        CharUnits ElementSize =3D CharUnits::One();
-        if (!ElementType->isVoidType() && !ElementType->isFunctionType())
-          ElementSize =3D Info.Ctx.getTypeSizeInChars(ElementType);
-
-        CharUnits Diff =3D LHSValue.getLValueOffset() -=20
-                             RHSValue.getLValueOffset();
-        return Success(Diff / ElementSize, E);
+        CharUnits ElementSize;
+        if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
+          return false;
+
+        // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runti=
me,
+        // and produce incorrect results when it overflows. Such behavior
+        // appears to be non-conforming, but is common, so perhaps we shou=
ld
+        // assume the standard intended for such cases to be undefined beh=
avior
+        // and check for them.
+
+        // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
+        // overflow in the final conversion to ptrdiff_t.
+        APSInt LHS(
+          llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
+        APSInt RHS(
+          llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
+        APSInt ElemSize(
+          llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false=
);
+        APSInt TrueResult =3D (LHS - RHS) / ElemSize;
+        APSInt Result =3D TrueResult.trunc(Info.Ctx.getIntWidth(E->getType=
()));
+
+        if (Result.extend(65) !=3D TrueResult)
+          HandleOverflow(Info, E, TrueResult, E->getType());
+        return Success(Result, E);
       }
-      bool Result;
-      if (E->getOpcode() =3D=3D BO_EQ) {
-        Result =3D LHSValue.getLValueOffset() =3D=3D RHSValue.getLValueOff=
set();
-      } else {
-        Result =3D LHSValue.getLValueOffset() !=3D RHSValue.getLValueOffse=
t();
+
+      // C++11 [expr.rel]p3:
+      //   Pointers to void (after pointer conversions) can be compared, w=
ith a
+      //   result defined as follows: If both pointers represent the same
+      //   address or are both the null pointer value, the result is true =
if the
+      //   operator is <=3D or >=3D and false otherwise; otherwise the res=
ult is
+      //   unspecified.
+      // We interpret this as applying to pointers to *cv* void.
+      if (LHSTy->isVoidPointerType() && LHSOffset !=3D RHSOffset &&
+          E->isRelationalOp())
+        CCEDiag(E, diag::note_constexpr_void_comparison);
+
+      // C++11 [expr.rel]p2:
+      // - If two pointers point to non-static data members of the same ob=
ject,
+      //   or to subobjects or array elements fo such members, recursively=
, the
+      //   pointer to the later declared member compares greater provided =
the
+      //   two members have the same access control and provided their cla=
ss is
+      //   not a union.
+      //   [...]
+      // - Otherwise pointer comparisons are unspecified.
+      if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
+          E->isRelationalOp()) {
+        bool WasArrayIndex;
+        unsigned Mismatch =3D
+          FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
+                                 RHSDesignator, WasArrayIndex);
+        // At the point where the designators diverge, the comparison has a
+        // specified value if:
+        //  - we are comparing array indices
+        //  - we are comparing fields of a union, or fields with the same =
access
+        // Otherwise, the result is unspecified and thus the comparison is=
 not a
+        // constant expression.
+        if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
+            Mismatch < RHSDesignator.Entries.size()) {
+          const FieldDecl *LF =3D getAsField(LHSDesignator.Entries[Mismatc=
h]);
+          const FieldDecl *RF =3D getAsField(RHSDesignator.Entries[Mismatc=
h]);
+          if (!LF && !RF)
+            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classe=
s);
+          else if (!LF)
+            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
+              << getAsBaseClass(LHSDesignator.Entries[Mismatch])
+              << RF->getParent() << RF;
+          else if (!RF)
+            CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
+              << getAsBaseClass(RHSDesignator.Entries[Mismatch])
+              << LF->getParent() << LF;
+          else if (!LF->getParent()->isUnion() &&
+                   LF->getAccess() !=3D RF->getAccess())
+            CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_a=
ccess)
+              << LF << LF->getAccess() << RF << RF->getAccess()
+              << LF->getParent();
+        }
       }
-      return Success(Result, E);
-    }
-  }
-  if (!LHSTy->isIntegralOrEnumerationType() ||
-      !RHSTy->isIntegralOrEnumerationType()) {
-    // We can't continue from here for non-integral types, and they
-    // could potentially confuse the following operations.
-    return false;
-  }
-
-  // The LHS of a constant expr is always evaluated and needed.
-  if (!Visit(E->getLHS()))
-    return false; // error in subexpression.
-
-  APValue RHSVal;
-  if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
-    return false;
-
-  // Handle cases like (unsigned long)&a + 4.
-  if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
-    CharUnits Offset =3D Result.getLValueOffset();
-    CharUnits AdditionalOffset =3D CharUnits::fromQuantity(
-                                     RHSVal.getInt().getZExtValue());
-    if (E->getOpcode() =3D=3D BO_Add)
-      Offset +=3D AdditionalOffset;
-    else
-      Offset -=3D AdditionalOffset;
-    Result =3D APValue(Result.getLValueBase(), Offset);
-    return true;
-  }
-
-  // Handle cases like 4 + (unsigned long)&a
-  if (E->getOpcode() =3D=3D BO_Add &&
-        RHSVal.isLValue() && Result.isInt()) {
-    CharUnits Offset =3D RHSVal.getLValueOffset();
-    Offset +=3D CharUnits::fromQuantity(Result.getInt().getZExtValue());
-    Result =3D APValue(RHSVal.getLValueBase(), Offset);
-    return true;
-  }
-
-  // All the following cases expect both operands to be an integer
-  if (!Result.isInt() || !RHSVal.isInt())
-    return false;
-
-  APSInt& RHS =3D RHSVal.getInt();
-
-  switch (E->getOpcode()) {
-  default:
-    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E=
);
-  case BO_Mul: return Success(Result.getInt() * RHS, E);
-  case BO_Add: return Success(Result.getInt() + RHS, E);
-  case BO_Sub: return Success(Result.getInt() - RHS, E);
-  case BO_And: return Success(Result.getInt() & RHS, E);
-  case BO_Xor: return Success(Result.getInt() ^ RHS, E);
-  case BO_Or:  return Success(Result.getInt() | RHS, E);
-  case BO_Div:
-    if (RHS =3D=3D 0)
-      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
-    return Success(Result.getInt() / RHS, E);
-  case BO_Rem:
-    if (RHS =3D=3D 0)
-      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
-    return Success(Result.getInt() % RHS, E);
-  case BO_Shl: {
-    // During constant-folding, a negative shift is an opposite shift.
-    if (RHS.isSigned() && RHS.isNegative()) {
-      RHS =3D -RHS;
-      goto shift_right;
-    }
-
-  shift_left:
-    unsigned SA
-      =3D (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
-    return Success(Result.getInt() << SA, E);
-  }
-  case BO_Shr: {
-    // During constant-folding, a negative shift is an opposite shift.
-    if (RHS.isSigned() && RHS.isNegative()) {
-      RHS =3D -RHS;
-      goto shift_left;
-    }
-
-  shift_right:
-    unsigned SA =3D
-      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
-    return Success(Result.getInt() >> SA, E);
-  }
-
-  case BO_LT: return Success(Result.getInt() < RHS, E);
-  case BO_GT: return Success(Result.getInt() > RHS, E);
-  case BO_LE: return Success(Result.getInt() <=3D RHS, E);
-  case BO_GE: return Success(Result.getInt() >=3D RHS, E);
-  case BO_EQ: return Success(Result.getInt() =3D=3D RHS, E);
-  case BO_NE: return Success(Result.getInt() !=3D RHS, E);
-  }
+
+      switch (E->getOpcode()) {
+      default: llvm_unreachable("missing comparison operator");
+      case BO_LT: return Success(LHSOffset < RHSOffset, E);
+      case BO_GT: return Success(LHSOffset > RHSOffset, E);
+      case BO_LE: return Success(LHSOffset <=3D RHSOffset, E);
+      case BO_GE: return Success(LHSOffset >=3D RHSOffset, E);
+      case BO_EQ: return Success(LHSOffset =3D=3D RHSOffset, E);
+      case BO_NE: return Success(LHSOffset !=3D RHSOffset, E);
+      }
+    }
+  }
+
+  if (LHSTy->isMemberPointerType()) {
+    assert(E->isEqualityOp() && "unexpected member pointer operation");
+    assert(RHSTy->isMemberPointerType() && "invalid comparison");
+
+    MemberPtr LHSValue, RHSValue;
+
+    bool LHSOK =3D EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
+    if (!LHSOK && Info.keepEvaluatingAfterFailure())
+      return false;
+
+    if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
+      return false;
+
+    // C++11 [expr.eq]p2:
+    //   If both operands are null, they compare equal. Otherwise if only =
one is
+    //   null, they compare unequal.
+    if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
+      bool Equal =3D !LHSValue.getDecl() && !RHSValue.getDecl();
+      return Success(E->getOpcode() =3D=3D BO_EQ ? Equal : !Equal, E);
+    }
+
+    //   Otherwise if either is a pointer to a virtual member function, the
+    //   result is unspecified.
+    if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(LHSValue.getDe=
cl()))
+      if (MD->isVirtual())
+        CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
+    if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(RHSValue.getDe=
cl()))
+      if (MD->isVirtual())
+        CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
+
+    //   Otherwise they compare equal if and only if they would refer to t=
he
+    //   same member of the same most derived object or the same subobject=
 if
+    //   they were dereferenced with a hypothetical object of the associat=
ed
+    //   class type.
+    bool Equal =3D LHSValue =3D=3D RHSValue;
+    return Success(E->getOpcode() =3D=3D BO_EQ ? Equal : !Equal, E);
+  }
+
+  if (LHSTy->isNullPtrType()) {
+    assert(E->isComparisonOp() && "unexpected nullptr operation");
+    assert(RHSTy->isNullPtrType() && "missing pointer conversion");
+    // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullp=
tr_t
+    // are compared, the result is true of the operator is <=3D, >=3D or =
=3D=3D, and
+    // false otherwise.
+    BinaryOperator::Opcode Opcode =3D E->getOpcode();
+    return Success(Opcode =3D=3D BO_EQ || Opcode =3D=3D BO_LE || Opcode =
=3D=3D BO_GE, E);
+  }
+
+  assert((!LHSTy->isIntegralOrEnumerationType() ||
+          !RHSTy->isIntegralOrEnumerationType()) &&
+         "DataRecursiveIntBinOpEvaluator should have handled integral type=
s");
+  // We can't continue from here for non-integral types.
+  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
 }
=20
 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
-  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
-  //   the result is the size of the referenced type."
   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, t=
he
   //   result shall be the alignment of the referenced type."
   if (const ReferenceType *Ref =3D T->getAs<ReferenceType>())
@@ -1678,34 +5206,24 @@
     QualType SrcTy =3D E->getTypeOfArgument();
     // C++ [expr.sizeof]p2: "When applied to a reference or a reference ty=
pe,
     //   the result is the size of the referenced type."
-    // C++ [expr.alignof]p3: "When alignof is applied to a reference type,=
 the
-    //   result shall be the alignment of the referenced type."
     if (const ReferenceType *Ref =3D SrcTy->getAs<ReferenceType>())
       SrcTy =3D Ref->getPointeeType();
=20
-    // sizeof(void), __alignof__(void), sizeof(function) =3D 1 as a gcc
-    // extension.
-    if (SrcTy->isVoidType() || SrcTy->isFunctionType())
-      return Success(1, E);
-
-    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
-    if (!SrcTy->isConstantSizeType())
+    CharUnits Sizeof;
+    if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
       return false;
-
-    // Get information about the size.
-    return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
+    return Success(Sizeof, E);
   }
   }
=20
   llvm_unreachable("unknown expr/type trait");
-  return false;
 }
=20
 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
   CharUnits Result;
   unsigned n =3D OOE->getNumComponents();
   if (n =3D=3D 0)
-    return false;
+    return Error(OOE);
   QualType CurrentType =3D OOE->getTypeSourceInfo()->getType();
   for (unsigned i =3D 0; i !=3D n; ++i) {
     OffsetOfExpr::OffsetOfNode ON =3D OOE->getComponent(i);
@@ -1717,18 +5235,18 @@
         return false;
       const ArrayType *AT =3D Info.Ctx.getAsArrayType(CurrentType);
       if (!AT)
-        return false;
+        return Error(OOE);
       CurrentType =3D AT->getElementType();
       CharUnits ElementSize =3D Info.Ctx.getTypeSizeInChars(CurrentType);
       Result +=3D IdxResult.getSExtValue() * ElementSize;
         break;
     }
-       =20
+
     case OffsetOfExpr::OffsetOfNode::Field: {
       FieldDecl *MemberDecl =3D ON.getField();
       const RecordType *RT =3D CurrentType->getAs<RecordType>();
-      if (!RT)=20
-        return false;
+      if (!RT)
+        return Error(OOE);
       RecordDecl *RD =3D RT->getDecl();
       const ASTRecordLayout &RL =3D Info.Ctx.getASTRecordLayout(RD);
       unsigned i =3D MemberDecl->getFieldIndex();
@@ -1737,20 +5255,19 @@
       CurrentType =3D MemberDecl->getType().getNonReferenceType();
       break;
     }
-       =20
+
     case OffsetOfExpr::OffsetOfNode::Identifier:
       llvm_unreachable("dependent __builtin_offsetof");
-      return false;
-       =20
+
     case OffsetOfExpr::OffsetOfNode::Base: {
       CXXBaseSpecifier *BaseSpec =3D ON.getBase();
       if (BaseSpec->isVirtual())
-        return false;
+        return Error(OOE);
=20
       // Find the layout of the class whose base we are looking into.
       const RecordType *RT =3D CurrentType->getAs<RecordType>();
-      if (!RT)=20
-        return false;
+      if (!RT)
+        return Error(OOE);
       RecordDecl *RD =3D RT->getDecl();
       const ASTRecordLayout &RL =3D Info.Ctx.getASTRecordLayout(RD);
=20
@@ -1758,7 +5275,7 @@
       CurrentType =3D BaseSpec->getType();
       const RecordType *BaseRT =3D CurrentType->getAs<RecordType>();
       if (!BaseRT)
-        return false;
+        return Error(OOE);
      =20
       // Add the offset to the base.
       Result +=3D RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDec=
l()));
@@ -1770,41 +5287,41 @@
 }
=20
 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
-  if (E->getOpcode() =3D=3D UO_LNot) {
-    // LNot's operand isn't necessarily an integer, so we handle it specia=
lly.
-    bool bres;
-    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
-      return false;
-    return Success(!bres, E);
-  }
-
-  // Only handle integral operations...
-  if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
-    return false;
-
-  // Get the operand value into 'Result'.
-  if (!Visit(E->getSubExpr()))
-    return false;
-
   switch (E->getOpcode()) {
   default:
     // Address, indirect, pre/post inc/dec, etc are not valid constant exp=
rs.
     // See C99 6.6p3.
-    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E=
);
+    return Error(E);
   case UO_Extension:
     // FIXME: Should extension allow i-c-e extension expressions in its sc=
ope?
     // If so, we could clear the diagnostic ID.
-    return true;
+    return Visit(E->getSubExpr());
   case UO_Plus:
-    // The result is always just the subexpr.
-    return true;
-  case UO_Minus:
-    if (!Result.isInt()) return false;
-    return Success(-Result.getInt(), E);
-  case UO_Not:
-    if (!Result.isInt()) return false;
+    // The result is just the value.
+    return Visit(E->getSubExpr());
+  case UO_Minus: {
+    if (!Visit(E->getSubExpr()))
+      return false;
+    if (!Result.isInt()) return Error(E);
+    const APSInt &Value =3D Result.getInt();
+    if (Value.isSigned() && Value.isMinSignedValue())
+      HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
+                     E->getType());
+    return Success(-Value, E);
+  }
+  case UO_Not: {
+    if (!Visit(E->getSubExpr()))
+      return false;
+    if (!Result.isInt()) return Error(E);
     return Success(~Result.getInt(), E);
   }
+  case UO_LNot: {
+    bool bres;
+    if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
+      return false;
+    return Success(!bres, E);
+  }
+  }
 }
=20
 /// HandleCast - This is used to evaluate implicit or explicit casts where=
 the
@@ -1826,6 +5343,7 @@
   case CK_NullToMemberPointer:
   case CK_BaseToDerivedMemberPointer:
   case CK_DerivedToBaseMemberPointer:
+  case CK_ReinterpretMemberPointer:
   case CK_ConstructorConversion:
   case CK_IntegralToPointer:
   case CK_ToVoid:
@@ -1847,18 +5365,20 @@
=20
   case CK_BitCast:
   case CK_Dependent:
-  case CK_GetObjCProperty:
   case CK_LValueBitCast:
-  case CK_UserDefinedConversion:
   case CK_ARCProduceObject:
   case CK_ARCConsumeObject:
   case CK_ARCReclaimReturnedObject:
   case CK_ARCExtendBlockObject:
-    return false;
-
+  case CK_CopyAndAutoreleaseBlockObject:
+    return Error(E);
+
+  case CK_UserDefinedConversion:
   case CK_LValueToRValue:
+  case CK_AtomicToNonAtomic:
+  case CK_NonAtomicToAtomic:
   case CK_NoOp:
-    return Visit(E->getSubExpr());
+    return ExprEvaluatorBaseTy::VisitCastExpr(E);
=20
   case CK_MemberPointerToBoolean:
   case CK_PointerToBoolean:
@@ -1867,7 +5387,7 @@
   case CK_FloatingComplexToBoolean:
   case CK_IntegralComplexToBoolean: {
     bool BoolResult;
-    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
+    if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
       return false;
     return Success(BoolResult, E);
   }
@@ -1877,31 +5397,44 @@
       return false;
=20
     if (!Result.isInt()) {
+      // Allow casts of address-of-label differences if they are no-ops
+      // or narrowing.  (The narrowing case isn't actually guaranteed to
+      // be constant-evaluatable except in some narrow cases which are hard
+      // to detect here.  We let it through on the assumption the user kno=
ws
+      // what they are doing.)
+      if (Result.isAddrLabelDiff())
+        return Info.Ctx.getTypeSize(DestType) <=3D Info.Ctx.getTypeSize(Sr=
cType);
       // Only allow casts of lvalues if they are lossless.
       return Info.Ctx.getTypeSize(DestType) =3D=3D Info.Ctx.getTypeSize(Sr=
cType);
     }
=20
-    return Success(HandleIntToIntCast(DestType, SrcType,
-                                      Result.getInt(), Info.Ctx), E);
+    return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
+                                      Result.getInt()), E);
   }
=20
   case CK_PointerToIntegral: {
+    CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
+
     LValue LV;
     if (!EvaluatePointer(SubExpr, LV, Info))
       return false;
=20
     if (LV.getLValueBase()) {
       // Only allow based lvalue casts if they are lossless.
+      // FIXME: Allow a larger integer size than the pointer size, and all=
ow
+      // narrowing back down to pointer width in subsequent integral casts.
+      // FIXME: Check integer type's active bits, not its type size.
       if (Info.Ctx.getTypeSize(DestType) !=3D Info.Ctx.getTypeSize(SrcType=
))
-        return false;
-
+        return Error(E);
+
+      LV.Designator.setInvalid();
       LV.moveInto(Result);
       return true;
     }
=20
     APSInt AsInt =3D Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantit=
y(),=20
                                          SrcType);
-    return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx),=
 E);
+    return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), =
E);
   }
=20
   case CK_IntegralComplexToReal: {
@@ -1916,19 +5449,23 @@
     if (!EvaluateFloat(SubExpr, F, Info))
       return false;
=20
-    return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E=
);
+    APSInt Value;
+    if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
+      return false;
+    return Success(Value, E);
   }
   }
=20
   llvm_unreachable("unknown cast resulting in integral value");
-  return false;
 }
=20
 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   if (E->getSubExpr()->getType()->isAnyComplexType()) {
     ComplexValue LV;
-    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
-      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
+    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
+      return false;
+    if (!LV.isComplexInt())
+      return Error(E);
     return Success(LV.getComplexIntReal(), E);
   }
=20
@@ -1938,13 +5475,14 @@
 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
     ComplexValue LV;
-    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
-      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
+    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
+      return false;
+    if (!LV.isComplexInt())
+      return Error(E);
     return Success(LV.getComplexIntImag(), E);
   }
=20
-  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
-    Info.EvalResult.HasSideEffects =3D true;
+  VisitIgnoredValue(E->getSubExpr());
   return Success(0, E);
 }
=20
@@ -1972,11 +5510,8 @@
     Result =3D V.getFloat();
     return true;
   }
-  bool Error(const Stmt *S) {
-    return false;
-  }
-
-  bool ValueInitialization(const Expr *E) {
+
+  bool ZeroInitialization(const Expr *E) {
     Result =3D APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType(=
)));
     return true;
   }
@@ -1991,15 +5526,12 @@
   bool VisitUnaryReal(const UnaryOperator *E);
   bool VisitUnaryImag(const UnaryOperator *E);
=20
-  bool VisitDeclRefExpr(const DeclRefExpr *E);
-
-  // FIXME: Missing: array subscript of vector, member of vector,
-  //                 ImplicitValueInitExpr
+  // FIXME: Missing: array subscript of vector, member of vector
 };
 } // end anonymous namespace
=20
 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
-  assert(E->getType()->isRealFloatingType());
+  assert(E->isRValue() && E->getType()->isRealFloatingType());
   return FloatExprEvaluator(Info, Result).Visit(E);
 }
=20
@@ -2029,7 +5561,7 @@
 }
=20
 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
-  switch (E->isBuiltinCall(Info.Ctx)) {
+  switch (E->isBuiltinCall()) {
   default:
     return ExprEvaluatorBaseTy::VisitCallExpr(E);
=20
@@ -2048,16 +5580,20 @@
   case Builtin::BI__builtin_nans:
   case Builtin::BI__builtin_nansf:
   case Builtin::BI__builtin_nansl:
-    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
-                                 true, Result);
+    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
+                               true, Result))
+      return Error(E);
+    return true;
=20
   case Builtin::BI__builtin_nan:
   case Builtin::BI__builtin_nanf:
   case Builtin::BI__builtin_nanl:
     // If this is __builtin_nan() turn this into a nan, otherwise we
     // can't constant fold it.
-    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
-                                 false, Result);
+    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
+                               false, Result))
+      return Error(E);
+    return true;
=20
   case Builtin::BI__builtin_fabs:
   case Builtin::BI__builtin_fabsf:
@@ -2082,48 +5618,6 @@
   }
 }
=20
-bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
-  if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
-    return true;
-
-  const Decl *D =3D E->getDecl();
-  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
-  const VarDecl *VD =3D cast<VarDecl>(D);
-
-  // Require the qualifiers to be const and not volatile.
-  CanQualType T =3D Info.Ctx.getCanonicalType(E->getType());
-  if (!T.isConstQualified() || T.isVolatileQualified())
-    return false;
-
-  const Expr *Init =3D VD->getAnyInitializer();
-  if (!Init) return false;
-
-  if (APValue *V =3D VD->getEvaluatedValue()) {
-    if (V->isFloat()) {
-      Result =3D V->getFloat();
-      return true;
-    }
-    return false;
-  }
-
-  if (VD->isEvaluatingValue())
-    return false;
-
-  VD->setEvaluatingValue();
-
-  Expr::EvalResult InitResult;
-  if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
-      InitResult.Val.isFloat()) {
-    // Cache the evaluated value in the variable declaration.
-    Result =3D InitResult.Val.getFloat();
-    VD->setEvaluatedValue(InitResult.Val);
-    return true;
-  }
-
-  VD->setEvaluatedValue(APValue());
-  return false;
-}
-
 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
   if (E->getSubExpr()->getType()->isAnyComplexType()) {
     ComplexValue CV;
@@ -2145,70 +5639,55 @@
     return true;
   }
=20
-  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
-    Info.EvalResult.HasSideEffects =3D true;
+  VisitIgnoredValue(E->getSubExpr());
   const llvm::fltSemantics &Sem =3D Info.Ctx.getFloatTypeSemantics(E->getT=
ype());
   Result =3D llvm::APFloat::getZero(Sem);
   return true;
 }
=20
 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
-  if (E->getOpcode() =3D=3D UO_Deref)
-    return false;
-
-  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
-    return false;
-
   switch (E->getOpcode()) {
-  default: return false;
+  default: return Error(E);
   case UO_Plus:
-    return true;
+    return EvaluateFloat(E->getSubExpr(), Result, Info);
   case UO_Minus:
+    if (!EvaluateFloat(E->getSubExpr(), Result, Info))
+      return false;
     Result.changeSign();
     return true;
   }
 }
=20
 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
-  if (E->getOpcode() =3D=3D BO_Comma) {
-    if (!EvaluateFloat(E->getRHS(), Result, Info))
-      return false;
-
-    // If we can't evaluate the LHS, it might have side effects;
-    // conservatively mark it.
-    if (!E->getLHS()->isEvaluatable(Info.Ctx))
-      Info.EvalResult.HasSideEffects =3D true;
-
-    return true;
-  }
-
-  // We can't evaluate pointer-to-member operations.
-  if (E->isPtrMemOp())
+  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() =3D=3D BO_C=
omma)
+    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
+
+  APFloat RHS(0.0);
+  bool LHSOK =3D EvaluateFloat(E->getLHS(), Result, Info);
+  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
     return false;
-
-  // FIXME: Diagnostics?  I really don't understand how the warnings
-  // and errors are supposed to work.
-  APFloat RHS(0.0);
-  if (!EvaluateFloat(E->getLHS(), Result, Info))
+  if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
     return false;
-  if (!EvaluateFloat(E->getRHS(), RHS, Info))
-    return false;
=20
   switch (E->getOpcode()) {
-  default: return false;
+  default: return Error(E);
   case BO_Mul:
     Result.multiply(RHS, APFloat::rmNearestTiesToEven);
-    return true;
+    break;
   case BO_Add:
     Result.add(RHS, APFloat::rmNearestTiesToEven);
-    return true;
+    break;
   case BO_Sub:
     Result.subtract(RHS, APFloat::rmNearestTiesToEven);
-    return true;
+    break;
   case BO_Div:
     Result.divide(RHS, APFloat::rmNearestTiesToEven);
-    return true;
-  }
+    break;
+  }
+
+  if (Result.isInfinity() || Result.isNaN())
+    CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
+  return true;
 }
=20
 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
@@ -2221,27 +5700,20 @@
=20
   switch (E->getCastKind()) {
   default:
-    return false;
-
-  case CK_LValueToRValue:
-  case CK_NoOp:
-    return Visit(SubExpr);
+    return ExprEvaluatorBaseTy::VisitCastExpr(E);
=20
   case CK_IntegralToFloating: {
     APSInt IntResult;
-    if (!EvaluateInteger(SubExpr, IntResult, Info))
-      return false;
-    Result =3D HandleIntToFloatCast(E->getType(), SubExpr->getType(),
-                                  IntResult, Info.Ctx);
-    return true;
+    return EvaluateInteger(SubExpr, IntResult, Info) &&
+           HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
+                                E->getType(), Result);
   }
=20
   case CK_FloatingCast: {
     if (!Visit(SubExpr))
       return false;
-    Result =3D HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
-                                    Result, Info.Ctx);
-    return true;
+    return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(=
),
+                                  Result);
   }
=20
   case CK_FloatingComplexToReal: {
@@ -2252,8 +5724,6 @@
     return true;
   }
   }
-
-  return false;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2273,30 +5743,43 @@
     Result.setFrom(V);
     return true;
   }
-  bool Error(const Expr *E) {
-    return false;
-  }
+
+  bool ZeroInitialization(const Expr *E);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
   //                            Visitor Methods
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
=20
   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
-
   bool VisitCastExpr(const CastExpr *E);
-
   bool VisitBinaryOperator(const BinaryOperator *E);
   bool VisitUnaryOperator(const UnaryOperator *E);
-  // FIXME Missing: ImplicitValueInitExpr, InitListExpr
+  bool VisitInitListExpr(const InitListExpr *E);
 };
 } // end anonymous namespace
=20
 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
                             EvalInfo &Info) {
-  assert(E->getType()->isAnyComplexType());
+  assert(E->isRValue() && E->getType()->isAnyComplexType());
   return ComplexExprEvaluator(Info, Result).Visit(E);
 }
=20
+bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
+  QualType ElemTy =3D E->getType()->getAs<ComplexType>()->getElementType();
+  if (ElemTy->isRealFloatingType()) {
+    Result.makeComplexFloat();
+    APFloat Zero =3D APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemT=
y));
+    Result.FloatReal =3D Zero;
+    Result.FloatImag =3D Zero;
+  } else {
+    Result.makeComplexInt();
+    APSInt Zero =3D Info.Ctx.MakeIntValue(0, ElemTy);
+    Result.IntReal =3D Zero;
+    Result.IntImag =3D Zero;
+  }
+  return true;
+}
+
 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E=
) {
   const Expr* SubExpr =3D E->getSubExpr();
=20
@@ -2338,6 +5821,7 @@
   case CK_BaseToDerivedMemberPointer:
   case CK_DerivedToBaseMemberPointer:
   case CK_MemberPointerToBoolean:
+  case CK_ReinterpretMemberPointer:
   case CK_ConstructorConversion:
   case CK_IntegralToPointer:
   case CK_PointerToIntegral:
@@ -2362,17 +5846,19 @@
   case CK_ARCConsumeObject:
   case CK_ARCReclaimReturnedObject:
   case CK_ARCExtendBlockObject:
+  case CK_CopyAndAutoreleaseBlockObject:
     llvm_unreachable("invalid cast kind for complex value");
=20
   case CK_LValueToRValue:
+  case CK_AtomicToNonAtomic:
+  case CK_NonAtomicToAtomic:
   case CK_NoOp:
-    return Visit(E->getSubExpr());
+    return ExprEvaluatorBaseTy::VisitCastExpr(E);
=20
   case CK_Dependent:
-  case CK_GetObjCProperty:
   case CK_LValueBitCast:
   case CK_UserDefinedConversion:
-    return false;
+    return Error(E);
=20
   case CK_FloatingRealToComplex: {
     APFloat &Real =3D Result.FloatReal;
@@ -2392,11 +5878,8 @@
     QualType From
       =3D E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType=
();
=20
-    Result.FloatReal
-      =3D HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
-    Result.FloatImag
-      =3D HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
-    return true;
+    return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
+           HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
   }
=20
   case CK_FloatingComplexToIntegralComplex: {
@@ -2407,9 +5890,10 @@
     QualType From
       =3D E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType=
();
     Result.makeComplexInt();
-    Result.IntReal =3D HandleFloatToIntCast(To, From, Result.FloatReal, In=
fo.Ctx);
-    Result.IntImag =3D HandleFloatToIntCast(To, From, Result.FloatImag, In=
fo.Ctx);
-    return true;
+    return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
+                                To, Result.IntReal) &&
+           HandleFloatToIntCast(Info, E, From, Result.FloatImag,
+                                To, Result.IntImag);
   }
=20
   case CK_IntegralRealToComplex: {
@@ -2430,8 +5914,8 @@
     QualType From
       =3D E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType=
();
=20
-    Result.IntReal =3D HandleIntToIntCast(To, From, Result.IntReal, Info.C=
tx);
-    Result.IntImag =3D HandleIntToIntCast(To, From, Result.IntImag, Info.C=
tx);
+    Result.IntReal =3D HandleIntToIntCast(Info, E, To, From, Result.IntRea=
l);
+    Result.IntImag =3D HandleIntToIntCast(Info, E, To, From, Result.IntIma=
g);
     return true;
   }
=20
@@ -2443,39 +5927,32 @@
     QualType From
       =3D E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType=
();
     Result.makeComplexFloat();
-    Result.FloatReal =3D HandleIntToFloatCast(To, From, Result.IntReal, In=
fo.Ctx);
-    Result.FloatImag =3D HandleIntToFloatCast(To, From, Result.IntImag, In=
fo.Ctx);
-    return true;
+    return HandleIntToFloatCast(Info, E, From, Result.IntReal,
+                                To, Result.FloatReal) &&
+           HandleIntToFloatCast(Info, E, From, Result.IntImag,
+                                To, Result.FloatImag);
   }
   }
=20
   llvm_unreachable("unknown cast resulting in complex value");
-  return false;
 }
=20
 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
-  if (E->getOpcode() =3D=3D BO_Comma) {
-    if (!Visit(E->getRHS()))
-      return false;
-
-    // If we can't evaluate the LHS, it might have side effects;
-    // conservatively mark it.
-    if (!E->getLHS()->isEvaluatable(Info.Ctx))
-      Info.EvalResult.HasSideEffects =3D true;
-
-    return true;
-  }
-  if (!Visit(E->getLHS()))
+  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() =3D=3D BO_C=
omma)
+    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
+
+  bool LHSOK =3D Visit(E->getLHS());
+  if (!LHSOK && !Info.keepEvaluatingAfterFailure())
     return false;
=20
   ComplexValue RHS;
-  if (!EvaluateComplex(E->getRHS(), RHS, Info))
+  if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
     return false;
=20
   assert(Result.isComplexFloat() =3D=3D RHS.isComplexFloat() &&
          "Invalid operands to binary operator.");
   switch (E->getOpcode()) {
-  default: return false;
+  default: return Error(E);
   case BO_Add:
     if (Result.isComplexFloat()) {
       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
@@ -2559,10 +6036,9 @@
       Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
       Res_i.divide(Den, APFloat::rmNearestTiesToEven);
     } else {
-      if (RHS.getComplexIntReal() =3D=3D 0 && RHS.getComplexIntImag() =3D=
=3D 0) {
-        // FIXME: what about diagnostics?
-        return false;
-      }
+      if (RHS.getComplexIntReal() =3D=3D 0 && RHS.getComplexIntImag() =3D=
=3D 0)
+        return Error(E, diag::note_expr_divide_by_zero);
+
       ComplexValue LHS =3D Result;
       APSInt Den =3D RHS.getComplexIntReal() * RHS.getComplexIntReal() +
         RHS.getComplexIntImag() * RHS.getComplexIntImag();
@@ -2586,8 +6062,7 @@
=20
   switch (E->getOpcode()) {
   default:
-    // FIXME: what about diagnostics?
-    return false;
+    return Error(E);
   case UO_Extension:
     return true;
   case UO_Plus:
@@ -2612,109 +6087,279 @@
   }
 }
=20
+bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
+  if (E->getNumInits() =3D=3D 2) {
+    if (E->getType()->isComplexType()) {
+      Result.makeComplexFloat();
+      if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
+        return false;
+      if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
+        return false;
+    } else {
+      Result.makeComplexInt();
+      if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
+        return false;
+      if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
+        return false;
+    }
+    return true;
+  }
+  return ExprEvaluatorBaseTy::VisitInitListExpr(E);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// Top level Expr::Evaluate method.
+// Void expression evaluation, primarily for a cast to void on the LHS of a
+// comma operator
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-static bool Evaluate(EvalInfo &Info, const Expr *E) {
-  if (E->getType()->isVectorType()) {
-    if (!EvaluateVector(E, Info.EvalResult.Val, Info))
+namespace {
+class VoidExprEvaluator
+  : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
+public:
+  VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
+
+  bool Success(const APValue &V, const Expr *e) { return true; }
+
+  bool VisitCastExpr(const CastExpr *E) {
+    switch (E->getCastKind()) {
+    default:
+      return ExprEvaluatorBaseTy::VisitCastExpr(E);
+    case CK_ToVoid:
+      VisitIgnoredValue(E->getSubExpr());
+      return true;
+    }
+  }
+};
+} // end anonymous namespace
+
+static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
+  assert(E->isRValue() && E->getType()->isVoidType());
+  return VoidExprEvaluator(Info).Visit(E);
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Top level Expr::EvaluateAsRValue method.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
+  // In C, function designators are not lvalues, but we evaluate them as i=
f they
+  // are.
+  if (E->isGLValue() || E->getType()->isFunctionType()) {
+    LValue LV;
+    if (!EvaluateLValue(E, LV, Info))
+      return false;
+    LV.moveInto(Result);
+  } else if (E->getType()->isVectorType()) {
+    if (!EvaluateVector(E, Result, Info))
       return false;
   } else if (E->getType()->isIntegralOrEnumerationType()) {
-    if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
-      return false;
-    if (Info.EvalResult.Val.isLValue() &&
-        !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
+    if (!IntExprEvaluator(Info, Result).Visit(E))
       return false;
   } else if (E->getType()->hasPointerRepresentation()) {
     LValue LV;
     if (!EvaluatePointer(E, LV, Info))
       return false;
-    if (!IsGlobalLValue(LV.Base))
-      return false;
-    LV.moveInto(Info.EvalResult.Val);
+    LV.moveInto(Result);
   } else if (E->getType()->isRealFloatingType()) {
     llvm::APFloat F(0.0);
     if (!EvaluateFloat(E, F, Info))
       return false;
-
-    Info.EvalResult.Val =3D APValue(F);
+    Result =3D APValue(F);
   } else if (E->getType()->isAnyComplexType()) {
     ComplexValue C;
     if (!EvaluateComplex(E, C, Info))
       return false;
-    C.moveInto(Info.EvalResult.Val);
-  } else
+    C.moveInto(Result);
+  } else if (E->getType()->isMemberPointerType()) {
+    MemberPtr P;
+    if (!EvaluateMemberPointer(E, P, Info))
+      return false;
+    P.moveInto(Result);
+    return true;
+  } else if (E->getType()->isArrayType()) {
+    LValue LV;
+    LV.set(E, Info.CurrentCall->Index);
+    if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
+      return false;
+    Result =3D Info.CurrentCall->Temporaries[E];
+  } else if (E->getType()->isRecordType()) {
+    LValue LV;
+    LV.set(E, Info.CurrentCall->Index);
+    if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
+      return false;
+    Result =3D Info.CurrentCall->Temporaries[E];
+  } else if (E->getType()->isVoidType()) {
+    if (Info.getLangOpts().CPlusPlus0x)
+      Info.CCEDiag(E, diag::note_constexpr_nonliteral)
+        << E->getType();
+    else
+      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
+    if (!EvaluateVoid(E, Info))
+      return false;
+  } else if (Info.getLangOpts().CPlusPlus0x) {
+    Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
     return false;
+  } else {
+    Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
+    return false;
+  }
=20
   return true;
 }
=20
-/// Evaluate - Return true if this is a constant which we can fold using
+/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In so=
me
+/// cases, the in-place evaluation is essential, since later initializers =
for
+/// an object can indirectly refer to subobjects which were initialized ea=
rlier.
+static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue =
&This,
+                            const Expr *E, CheckConstantExpressionKind CCE=
K,
+                            bool AllowNonLiteralTypes) {
+  if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
+    return false;
+
+  if (E->isRValue()) {
+    // Evaluate arrays and record types in-place, so that later initialize=
rs can
+    // refer to earlier-initialized members of the object.
+    if (E->getType()->isArrayType())
+      return EvaluateArray(E, This, Result, Info);
+    else if (E->getType()->isRecordType())
+      return EvaluateRecord(E, This, Result, Info);
+  }
+
+  // For any other type, in-place evaluation is unimportant.
+  return Evaluate(Result, Info, E);
+}
+
+/// EvaluateAsRValue - Try to evaluate this expression, performing an impl=
icit
+/// lvalue-to-rvalue cast if it is an lvalue.
+static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Resul=
t) {
+  if (!CheckLiteralType(Info, E))
+    return false;
+
+  if (!::Evaluate(Result, Info, E))
+    return false;
+
+  if (E->isGLValue()) {
+    LValue LV;
+    LV.setFrom(Info.Ctx, Result);
+    if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
+      return false;
+  }
+
+  // Check this core constant expression is a constant expression.
+  return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Resu=
lt);
+}
+
+/// EvaluateAsRValue - Return true if this is a constant which we can fold=
 using
 /// any crazy technique (that has nothing to do with language standards) t=
hat
 /// we want to.  If this function returns true, it returns the folded cons=
tant
-/// in Result.
-bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
+/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conver=
sion
+/// will be applied to the result.
+bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) con=
st {
+  // Fast-path evaluations of integer literals, since we sometimes see fil=
es
+  // containing vast quantities of these.
+  if (const IntegerLiteral *L =3D dyn_cast<IntegerLiteral>(this)) {
+    Result.Val =3D APValue(APSInt(L->getValue(),
+                                L->getType()->isUnsignedIntegerType()));
+    return true;
+  }
+
+  // FIXME: Evaluating values of large array and record types can cause
+  // performance problems. Only do so in C++11 for now.
+  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()=
) &&
+      !Ctx.getLangOpts().CPlusPlus0x)
+    return false;
+
   EvalInfo Info(Ctx, Result);
-  return ::Evaluate(Info, this);
+  return ::EvaluateAsRValue(Info, this, Result.Val);
 }
=20
 bool Expr::EvaluateAsBooleanCondition(bool &Result,
                                       const ASTContext &Ctx) const {
   EvalResult Scratch;
-  EvalInfo Info(Ctx, Scratch);
-
-  return HandleConversionToBool(this, Result, Info);
-}
-
-bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
-  EvalResult Scratch;
-  EvalInfo Info(Ctx, Scratch);
-
-  return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
+  return EvaluateAsRValue(Scratch, Ctx) &&
+         HandleConversionToBool(Scratch.Val, Result);
+}
+
+bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
+                         SideEffectsKind AllowSideEffects) const {
+  if (!getType()->isIntegralOrEnumerationType())
+    return false;
+
+  EvalResult ExprResult;
+  if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
+      (!AllowSideEffects && ExprResult.HasSideEffects))
+    return false;
+
+  Result =3D ExprResult.Val.getInt();
+  return true;
 }
=20
 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) con=
st {
   EvalInfo Info(Ctx, Result);
=20
   LValue LV;
-  if (EvaluateLValue(this, LV, Info) &&
-      !Result.HasSideEffects &&
-      IsGlobalLValue(LV.Base)) {
-    LV.moveInto(Result.Val);
-    return true;
-  }
-  return false;
-}
-
-bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
-                               const ASTContext &Ctx) const {
-  EvalInfo Info(Ctx, Result);
-
-  LValue LV;
-  if (EvaluateLValue(this, LV, Info)) {
-    LV.moveInto(Result.Val);
-    return true;
-  }
-  return false;
-}
-
-/// isEvaluatable - Call Evaluate to see if this expression can be constant
-/// folded, but discard the result.
+  if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
+      !CheckLValueConstantExpression(Info, getExprLoc(),
+                                     Ctx.getLValueReferenceType(getType())=
, LV))
+    return false;
+
+  LV.moveInto(Result.Val);
+  return true;
+}
+
+bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
+                                 const VarDecl *VD,
+                      llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) c=
onst {
+  // FIXME: Evaluating initializers for large array and record types can c=
ause
+  // performance problems. Only do so in C++11 for now.
+  if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()=
) &&
+      !Ctx.getLangOpts().CPlusPlus0x)
+    return false;
+
+  Expr::EvalStatus EStatus;
+  EStatus.Diag =3D &Notes;
+
+  EvalInfo InitInfo(Ctx, EStatus);
+  InitInfo.setEvaluatingDecl(VD, Value);
+
+  LValue LVal;
+  LVal.set(VD);
+
+  // C++11 [basic.start.init]p2:
+  //  Variables with static storage duration or thread storage duration sh=
all be
+  //  zero-initialized before any other initialization takes place.
+  // This behavior is not present in C.
+  if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
+      !VD->getType()->isReferenceType()) {
+    ImplicitValueInitExpr VIE(VD->getType());
+    if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
+                         /*AllowNonLiteralTypes=3D*/true))
+      return false;
+  }
+
+  if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
+                         /*AllowNonLiteralTypes=3D*/true) ||
+      EStatus.HasSideEffects)
+    return false;
+
+  return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(=
),
+                                 Value);
+}
+
+/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
+/// constant folded, but discard the result.
 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
   EvalResult Result;
-  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
+  return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
 }
=20
 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
-  Expr::EvalResult Result;
-  EvalInfo Info(Ctx, Result);
-  return HasSideEffect(Info).Visit(this);
+  return HasSideEffect(Ctx).Visit(this);
 }
=20
 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
   EvalResult EvalResult;
-  bool Result =3D Evaluate(EvalResult, Ctx);
+  bool Result =3D EvaluateAsRValue(EvalResult, Ctx);
   (void)Result;
   assert(Result && "Could not evaluate expression");
   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer=
");
@@ -2746,7 +6391,7 @@
 // value, it calls into Evalute.
 //
 // Meanings of Val:
-// 0: This expression is an ICE if it can be evaluated by Evaluate.
+// 0: This expression is an ICE.
 // 1: This expression is not an ICE, but if it isn't evaluated, it's
 //    a legal subexpression for an ICE. This return value is used to handle
 //    the comma operator in C99 mode.
@@ -2769,7 +6414,7 @@
=20
 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
   Expr::EvalResult EVResult;
-  if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
+  if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
       !EVResult.Val.isInt()) {
     return ICEDiag(2, E->getLocStart());
   }
@@ -2808,6 +6453,7 @@
   case Expr::CXXTypeidExprClass:
   case Expr::CXXUuidofExprClass:
   case Expr::CXXNullPtrLiteralExprClass:
+  case Expr::UserDefinedLiteralClass:
   case Expr::CXXThisExprClass:
   case Expr::CXXThrowExprClass:
   case Expr::CXXNewExprClass:
@@ -2823,16 +6469,19 @@
   case Expr::CXXDependentScopeMemberExprClass:
   case Expr::UnresolvedMemberExprClass:
   case Expr::ObjCStringLiteralClass:
+  case Expr::ObjCNumericLiteralClass:
+  case Expr::ObjCArrayLiteralClass:
+  case Expr::ObjCDictionaryLiteralClass:
   case Expr::ObjCEncodeExprClass:
   case Expr::ObjCMessageExprClass:
   case Expr::ObjCSelectorExprClass:
   case Expr::ObjCProtocolExprClass:
   case Expr::ObjCIvarRefExprClass:
   case Expr::ObjCPropertyRefExprClass:
+  case Expr::ObjCSubscriptRefExprClass:
   case Expr::ObjCIsaExprClass:
   case Expr::ShuffleVectorExprClass:
   case Expr::BlockExprClass:
-  case Expr::BlockDeclRefExprClass:
   case Expr::NoStmtClass:
   case Expr::OpaqueValueExprClass:
   case Expr::PackExpansionExprClass:
@@ -2840,18 +6489,10 @@
   case Expr::AsTypeExprClass:
   case Expr::ObjCIndirectCopyRestoreExprClass:
   case Expr::MaterializeTemporaryExprClass:
+  case Expr::PseudoObjectExprClass:
   case Expr::AtomicExprClass:
-    return ICEDiag(2, E->getLocStart());
-
   case Expr::InitListExprClass:
-    if (Ctx.getLangOptions().CPlusPlus0x) {
-      const InitListExpr *ILE =3D cast<InitListExpr>(E);
-      if (ILE->getNumInits() =3D=3D 0)
-        return NoDiag();
-      if (ILE->getNumInits() =3D=3D 1)
-        return CheckICE(ILE->getInit(0), Ctx);
-      // Fall through for more than 1 expression.
-    }
+  case Expr::LambdaExprClass:
     return ICEDiag(2, E->getLocStart());
=20
   case Expr::SizeOfPackExprClass:
@@ -2869,28 +6510,32 @@
     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
   case Expr::IntegerLiteralClass:
   case Expr::CharacterLiteralClass:
+  case Expr::ObjCBoolLiteralExprClass:
   case Expr::CXXBoolLiteralExprClass:
   case Expr::CXXScalarValueInitExprClass:
   case Expr::UnaryTypeTraitExprClass:
   case Expr::BinaryTypeTraitExprClass:
+  case Expr::TypeTraitExprClass:
   case Expr::ArrayTypeTraitExprClass:
   case Expr::ExpressionTraitExprClass:
   case Expr::CXXNoexceptExprClass:
     return NoDiag();
   case Expr::CallExprClass:
   case Expr::CXXOperatorCallExprClass: {
+    // C99 6.6/3 allows function calls within unevaluated subexpressions of
+    // constant expressions, but they can never be ICEs because an ICE can=
not
+    // contain an operand of (pointer to) function type.
     const CallExpr *CE =3D cast<CallExpr>(E);
-    if (CE->isBuiltinCall(Ctx))
+    if (CE->isBuiltinCall())
       return CheckEvalInICE(E, Ctx);
     return ICEDiag(2, E->getLocStart());
   }
-  case Expr::DeclRefExprClass:
+  case Expr::DeclRefExprClass: {
     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
       return NoDiag();
-    if (Ctx.getLangOptions().CPlusPlus &&
-        E->getType().getCVRQualifiers() =3D=3D Qualifiers::Const) {
-      const NamedDecl *D =3D cast<DeclRefExpr>(E)->getDecl();
-
+    const ValueDecl *D =3D dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDe=
cl());
+    if (Ctx.getLangOpts().CPlusPlus &&
+        D && IsConstNonVolatile(D->getType())) {
       // Parameter variables are never constants.  Without this check,
       // getAnyInitializer() can find a default argument, which leads
       // to chaos.
@@ -2901,40 +6546,20 @@
       //   A variable of non-volatile const-qualified integral or enumerat=
ion
       //   type initialized by an ICE can be used in ICEs.
       if (const VarDecl *Dcl =3D dyn_cast<VarDecl>(D)) {
-        Qualifiers Quals =3D Ctx.getCanonicalType(Dcl->getType()).getQuali=
fiers();
-        if (Quals.hasVolatile() || !Quals.hasConst())
+        if (!Dcl->getType()->isIntegralOrEnumerationType())
           return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
-       =20
-        // Look for a declaration of this variable that has an initializer.
-        const VarDecl *ID =3D 0;
-        const Expr *Init =3D Dcl->getAnyInitializer(ID);
-        if (Init) {
-          if (ID->isInitKnownICE()) {
-            // We have already checked whether this subexpression is an
-            // integral constant expression.
-            if (ID->isInitICE())
-              return NoDiag();
-            else
-              return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
-          }
-
-          // It's an ICE whether or not the definition we found is
-          // out-of-line.  See DR 721 and the discussion in Clang PR
-          // 6206 for details.
-
-          if (Dcl->isCheckingICE()) {
-            return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
-          }
-
-          Dcl->setCheckingICE();
-          ICEDiag Result =3D CheckICE(Init, Ctx);
-          // Cache the result of the ICE test.
-          Dcl->setInitKnownICE(Result.Val =3D=3D 0);
-          return Result;
-        }
+
+        const VarDecl *VD;
+        // Look for a declaration of this variable that has an initializer=
, and
+        // check whether it is an ICE.
+        if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
+          return NoDiag();
+        else
+          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
       }
     }
     return ICEDiag(2, E->getLocStart());
+  }
   case Expr::UnaryOperatorClass: {
     const UnaryOperator *Exp =3D cast<UnaryOperator>(E);
     switch (Exp->getOpcode()) {
@@ -2944,6 +6569,9 @@
     case UO_PreDec:
     case UO_AddrOf:
     case UO_Deref:
+      // C99 6.6/3 allows increment and decrement within unevaluated
+      // subexpressions of constant expressions, but they can never be ICEs
+      // because an ICE cannot contain an lvalue operand.
       return ICEDiag(2, E->getLocStart());
     case UO_Extension:
     case UO_LNot:
@@ -2959,8 +6587,8 @@
   }
   case Expr::OffsetOfExprClass: {
       // Note that per C99, offsetof must be an ICE. And AFAIK, using
-      // Evaluate matches the proposed gcc behavior for cases like
-      // "offsetof(struct s{int x[4];}, x[!.0])".  This doesn't affect
+      // EvaluateAsRValue matches the proposed gcc behavior for cases like
+      // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
       // compliance: we should warn earlier for offsetof expressions with
       // array subscripts that aren't ICEs, and if the array subscripts
       // are ICEs, the value of the offsetof must be an integer constant.
@@ -2989,6 +6617,9 @@
     case BO_AndAssign:
     case BO_XorAssign:
     case BO_OrAssign:
+      // C99 6.6/3 allows assignments within unevaluated subexpressions of
+      // constant expressions, but they can never be ICEs because an ICE c=
annot
+      // contain an lvalue operand.
       return ICEDiag(2, E->getLocStart());
=20
     case BO_Mul:
@@ -3012,7 +6643,7 @@
       ICEDiag RHSResult =3D CheckICE(Exp->getRHS(), Ctx);
       if (Exp->getOpcode() =3D=3D BO_Div ||
           Exp->getOpcode() =3D=3D BO_Rem) {
-        // Evaluate gives an error for undefined Div/Rem, so make sure
+        // EvaluateAsRValue gives an error for undefined Div/Rem, so make =
sure
         // we don't evaluate one.
         if (LHSResult.Val =3D=3D 0 && RHSResult.Val =3D=3D 0) {
           llvm::APSInt REval =3D Exp->getRHS()->EvaluateKnownConstInt(Ctx);
@@ -3026,7 +6657,7 @@
         }
       }
       if (Exp->getOpcode() =3D=3D BO_Comma) {
-        if (Ctx.getLangOptions().C99) {
+        if (Ctx.getLangOpts().C99) {
           // C99 6.6p3 introduces a strange edge case: comma can be in an =
ICE
           // if it isn't evaluated.
           if (LHSResult.Val =3D=3D 0 && RHSResult.Val =3D=3D 0)
@@ -3043,21 +6674,6 @@
     case BO_LAnd:
     case BO_LOr: {
       ICEDiag LHSResult =3D CheckICE(Exp->getLHS(), Ctx);
-
-      // C++0x [expr.const]p2:
-      //   [...] subexpressions of logical AND (5.14), logical OR
-      //   (5.15), and condi- tional (5.16) operations that are not
-      //   evaluated are not considered.
-      if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val =3D=3D 0) {
-        if (Exp->getOpcode() =3D=3D BO_LAnd &&=20
-            Exp->getLHS()->EvaluateKnownConstInt(Ctx) =3D=3D 0)
-          return LHSResult;
-
-        if (Exp->getOpcode() =3D=3D BO_LOr &&
-            Exp->getLHS()->EvaluateKnownConstInt(Ctx) !=3D 0)
-          return LHSResult;
-      }
-
       ICEDiag RHSResult =3D CheckICE(Exp->getRHS(), Ctx);
       if (LHSResult.Val =3D=3D 0 && RHSResult.Val =3D=3D 1) {
         // Rare case where the RHS has a comma "side-effect"; we need
@@ -3080,18 +6696,35 @@
   case Expr::CXXFunctionalCastExprClass:
   case Expr::CXXStaticCastExprClass:
   case Expr::CXXReinterpretCastExprClass:
-  case Expr::CXXConstCastExprClass:=20
+  case Expr::CXXConstCastExprClass:
   case Expr::ObjCBridgedCastExprClass: {
     const Expr *SubExpr =3D cast<CastExpr>(E)->getSubExpr();
+    if (isa<ExplicitCastExpr>(E)) {
+      if (const FloatingLiteral *FL
+            =3D dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))=
 {
+        unsigned DestWidth =3D Ctx.getIntWidth(E->getType());
+        bool DestSigned =3D E->getType()->isSignedIntegerOrEnumerationType=
();
+        APSInt IgnoredVal(DestWidth, !DestSigned);
+        bool Ignored;
+        // If the value does not fit in the destination type, the behavior=
 is
+        // undefined, so we are not required to treat it as a constant
+        // expression.
+        if (FL->getValue().convertToInteger(IgnoredVal,
+                                            llvm::APFloat::rmTowardZero,
+                                            &Ignored) & APFloat::opInvalid=
Op)
+          return ICEDiag(2, E->getLocStart());
+        return NoDiag();
+      }
+    }
     switch (cast<CastExpr>(E)->getCastKind()) {
     case CK_LValueToRValue:
+    case CK_AtomicToNonAtomic:
+    case CK_NonAtomicToAtomic:
     case CK_NoOp:
     case CK_IntegralToBoolean:
     case CK_IntegralCast:
       return CheckICE(SubExpr, Ctx);
     default:
-      if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
-        return NoDiag();
       return ICEDiag(2, E->getLocStart());
     }
   }
@@ -3114,30 +6747,14 @@
     // extension.  See GCC PR38377 for discussion.
     if (const CallExpr *CallCE
         =3D dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
-      if (CallCE->isBuiltinCall(Ctx) =3D=3D Builtin::BI__builtin_constant_=
p) {
-        Expr::EvalResult EVResult;
-        if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
-            !EVResult.Val.isInt()) {
-          return ICEDiag(2, E->getLocStart());
-        }
-        return NoDiag();
-      }
+      if (CallCE->isBuiltinCall() =3D=3D Builtin::BI__builtin_constant_p)
+        return CheckEvalInICE(E, Ctx);
     ICEDiag CondResult =3D CheckICE(Exp->getCond(), Ctx);
     if (CondResult.Val =3D=3D 2)
       return CondResult;
=20
-    // C++0x [expr.const]p2:
-    //   subexpressions of [...] conditional (5.16) operations that
-    //   are not evaluated are not considered
-    bool TrueBranch =3D Ctx.getLangOptions().CPlusPlus0x
-      ? Exp->getCond()->EvaluateKnownConstInt(Ctx) !=3D 0
-      : false;
-    ICEDiag TrueResult =3D NoDiag();
-    if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
-      TrueResult =3D CheckICE(Exp->getTrueExpr(), Ctx);
-    ICEDiag FalseResult =3D NoDiag();
-    if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
-      FalseResult =3D CheckICE(Exp->getFalseExpr(), Ctx);
+    ICEDiag TrueResult =3D CheckICE(Exp->getTrueExpr(), Ctx);
+    ICEDiag FalseResult =3D CheckICE(Exp->getFalseExpr(), Ctx);
=20
     if (TrueResult.Val =3D=3D 2)
       return TrueResult;
@@ -3162,22 +6779,116 @@
   }
   }
=20
-  // Silence a GCC warning
-  return ICEDiag(2, E->getLocStart());
-}
-
-bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
-                                 SourceLocation *Loc, bool isEvaluated) co=
nst {
+  llvm_unreachable("Invalid StmtClass!");
+}
+
+/// Evaluate an expression as a C++11 integral constant expression.
+static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
+                                                    const Expr *E,
+                                                    llvm::APSInt *Value,
+                                                    SourceLocation *Loc) {
+  if (!E->getType()->isIntegralOrEnumerationType()) {
+    if (Loc) *Loc =3D E->getExprLoc();
+    return false;
+  }
+
+  APValue Result;
+  if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
+    return false;
+
+  assert(Result.isInt() && "pointer cast to int is not an ICE");
+  if (Value) *Value =3D Result.getInt();
+  return true;
+}
+
+bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) con=
st {
+  if (Ctx.getLangOpts().CPlusPlus0x)
+    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
+
   ICEDiag d =3D CheckICE(this, Ctx);
   if (d.Val !=3D 0) {
     if (Loc) *Loc =3D d.Loc;
     return false;
   }
-  EvalResult EvalResult;
-  if (!Evaluate(EvalResult, Ctx))
+  return true;
+}
+
+bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
+                                 SourceLocation *Loc, bool isEvaluated) co=
nst {
+  if (Ctx.getLangOpts().CPlusPlus0x)
+    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
+
+  if (!isIntegerConstantExpr(Ctx, Loc))
+    return false;
+  if (!EvaluateAsInt(Value, Ctx))
     llvm_unreachable("ICE cannot be evaluated!");
-  assert(!EvalResult.HasSideEffects && "ICE with side effects!");
-  assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
-  Result =3D EvalResult.Val.getInt();
   return true;
 }
+
+bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
+  return CheckICE(this, Ctx).Val =3D=3D 0;
+}
+
+bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
+                               SourceLocation *Loc) const {
+  // We support this checking in C++98 mode in order to diagnose compatibi=
lity
+  // issues.
+  assert(Ctx.getLangOpts().CPlusPlus);
+
+  // Build evaluation settings.
+  Expr::EvalStatus Status;
+  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
+  Status.Diag =3D &Diags;
+  EvalInfo Info(Ctx, Status);
+
+  APValue Scratch;
+  bool IsConstExpr =3D ::EvaluateAsRValue(Info, this, Result ? *Result : S=
cratch);
+
+  if (!Diags.empty()) {
+    IsConstExpr =3D false;
+    if (Loc) *Loc =3D Diags[0].first;
+  } else if (!IsConstExpr) {
+    // FIXME: This shouldn't happen.
+    if (Loc) *Loc =3D getExprLoc();
+  }
+
+  return IsConstExpr;
+}
+
+bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
+                                   llvm::SmallVectorImpl<
+                                     PartialDiagnosticAt> &Diags) {
+  // FIXME: It would be useful to check constexpr function templates, but =
at the
+  // moment the constant expression evaluator cannot cope with the non-rig=
orous
+  // ASTs which we build for dependent expressions.
+  if (FD->isDependentContext())
+    return true;
+
+  Expr::EvalStatus Status;
+  Status.Diag =3D &Diags;
+
+  EvalInfo Info(FD->getASTContext(), Status);
+  Info.CheckingPotentialConstantExpression =3D true;
+
+  const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(FD);
+  const CXXRecordDecl *RD =3D MD ? MD->getParent()->getCanonicalDecl() : 0;
+
+  // FIXME: Fabricate an arbitrary expression on the stack and pretend tha=
t it
+  // is a temporary being used as the 'this' pointer.
+  LValue This;
+  ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.Int=
Ty);
+  This.set(&VIE, Info.CurrentCall->Index);
+
+  ArrayRef<const Expr*> Args;
+
+  SourceLocation Loc =3D FD->getLocation();
+
+  APValue Scratch;
+  if (const CXXConstructorDecl *CD =3D dyn_cast<CXXConstructorDecl>(FD))
+    HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
+  else
+    HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
+                       Args, FD->getBody(), Info, Scratch);
+
+  return Diags.empty();
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ItaniumMangle.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ItaniumMangle.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ItaniumMangle.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -40,14 +40,38 @@
=20
 namespace {
=20
+/// \brief Retrieve the declaration context that should be used when mangl=
ing=20
+/// the given declaration.
+static const DeclContext *getEffectiveDeclContext(const Decl *D) {
+  // The ABI assumes that lambda closure types that occur within=20
+  // default arguments live in the context of the function. However, due to
+  // the way in which Clang parses and creates function declarations, this=
 is
+  // not the case: the lambda closure type ends up living in the context=20
+  // where the function itself resides, because the function declaration i=
tself
+  // had not yet been created. Fix the context here.
+  if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(D)) {
+    if (RD->isLambda())
+      if (ParmVarDecl *ContextParam
+            =3D dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
+        return ContextParam->getDeclContext();
+  }
+ =20
+  return D->getDeclContext();
+}
+
+static const DeclContext *getEffectiveParentContext(const DeclContext *DC)=
 {
+  return getEffectiveDeclContext(cast<Decl>(DC));
+}
+ =20
 static const CXXRecordDecl *GetLocalClassDecl(const NamedDecl *ND) {
   const DeclContext *DC =3D dyn_cast<DeclContext>(ND);
   if (!DC)
-    DC =3D ND->getDeclContext();
+    DC =3D getEffectiveDeclContext(ND);
   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
-    if (isa<FunctionDecl>(DC->getParent()))
+    const DeclContext *Parent =3D getEffectiveDeclContext(cast<Decl>(DC));
+    if (isa<FunctionDecl>(Parent))
       return dyn_cast<CXXRecordDecl>(DC);
-    DC =3D DC->getParent();
+    DC =3D Parent;
   }
   return 0;
 }
@@ -63,7 +87,7 @@
   const FunctionDecl *fn =3D dyn_cast_or_null<FunctionDecl>(decl);
   return (fn ? getStructor(fn) : decl);
 }
-
+                                                   =20
 static const unsigned UnknownArity =3D ~0U;
=20
 class ItaniumMangleContext : public MangleContext {
@@ -122,6 +146,13 @@
   }
=20
   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
+    // Lambda closure types with external linkage (indicated by a=20
+    // non-zero lambda mangling number) have their own numbering scheme, so
+    // they do not need a discriminator.
+    if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(ND))
+      if (RD->isLambda() && RD->getLambdaManglingNumber() > 0)
+        return false;
+       =20
     unsigned &discriminator =3D Uniquifier[ND];
     if (!discriminator)
       discriminator =3D ++Discriminator;
@@ -272,6 +303,7 @@
   void mangleUnscopedTemplateName(TemplateName);
   void mangleSourceName(const IdentifierInfo *II);
   void mangleLocalName(const NamedDecl *ND);
+  void mangleLambda(const CXXRecordDecl *Lambda);
   void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
                         bool NoFunction=3Dfalse);
   void mangleNestedName(const TemplateDecl *TD,
@@ -332,8 +364,8 @@
=20
 static bool isInCLinkageSpecification(const Decl *D) {
   D =3D D->getCanonicalDecl();
-  for (const DeclContext *DC =3D D->getDeclContext();
-       !DC->isTranslationUnit(); DC =3D DC->getParent()) {
+  for (const DeclContext *DC =3D getEffectiveDeclContext(D);
+       !DC->isTranslationUnit(); DC =3D getEffectiveParentContext(DC)) {
     if (const LinkageSpecDecl *Linkage =3D dyn_cast<LinkageSpecDecl>(DC))
       return Linkage->getLanguage() =3D=3D LinkageSpecDecl::lang_c;
   }
@@ -343,7 +375,7 @@
=20
 bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) {
   // In C, functions with no attributes never need to be mangled. Fastpath=
 them.
-  if (!getASTContext().getLangOptions().CPlusPlus && !D->hasAttrs())
+  if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
     return false;
=20
   // Any decl can be declared with __asm("foo") on it, and this takes prec=
edence
@@ -360,22 +392,22 @@
     return true;
=20
   // Otherwise, no mangling is done outside C++ mode.
-  if (!getASTContext().getLangOptions().CPlusPlus)
+  if (!getASTContext().getLangOpts().CPlusPlus)
     return false;
=20
   // Variables at global scope with non-internal linkage are not mangled
   if (!FD) {
-    const DeclContext *DC =3D D->getDeclContext();
+    const DeclContext *DC =3D getEffectiveDeclContext(D);
     // Check for extern variable declared locally.
     if (DC->isFunctionOrMethod() && D->hasLinkage())
       while (!DC->isNamespace() && !DC->isTranslationUnit())
-        DC =3D DC->getParent();
+        DC =3D getEffectiveParentContext(DC);
     if (DC->isTranslationUnit() && D->getLinkage() !=3D InternalLinkage)
       return false;
   }
=20
   // Class members are always mangled.
-  if (D->getDeclContext()->isRecord())
+  if (getEffectiveDeclContext(D)->isRecord())
     return true;
=20
   // C functions and "main" are not mangled.
@@ -458,7 +490,7 @@
=20
 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
   while (isa<LinkageSpecDecl>(DC)) {
-    DC =3D DC->getParent();
+    DC =3D getEffectiveParentContext(DC);
   }
=20
   return DC;
@@ -466,7 +498,8 @@
=20
 /// isStd - Return whether a given namespace is the 'std' namespace.
 static bool isStd(const NamespaceDecl *NS) {
-  if (!IgnoreLinkageSpecDecls(NS->getParent())->isTranslationUnit())
+  if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
+                                ->isTranslationUnit())
     return false;
  =20
   const IdentifierInfo *II =3D NS->getOriginalNamespace()->getIdentifier();
@@ -502,26 +535,35 @@
   return 0;
 }
=20
+static bool isLambda(const NamedDecl *ND) {
+  const CXXRecordDecl *Record =3D dyn_cast<CXXRecordDecl>(ND);
+  if (!Record)
+    return false;
+ =20
+  return Record->isLambda();
+}
+
 void CXXNameMangler::mangleName(const NamedDecl *ND) {
   //  <name> ::=3D <nested-name>
   //         ::=3D <unscoped-name>
   //         ::=3D <unscoped-template-name> <template-args>
   //         ::=3D <local-name>
   //
-  const DeclContext *DC =3D ND->getDeclContext();
+  const DeclContext *DC =3D getEffectiveDeclContext(ND);
=20
   // If this is an extern variable declared locally, the relevant DeclCont=
ext
   // is that of the containing namespace, or the translation unit.
-  if (isa<FunctionDecl>(DC) && ND->hasLinkage())
+  // FIXME: This is a hack; extern variables declared locally should have
+  // a proper semantic declaration context!
+  if (isa<FunctionDecl>(DC) && ND->hasLinkage() && !isLambda(ND))
     while (!DC->isNamespace() && !DC->isTranslationUnit())
-      DC =3D DC->getParent();
+      DC =3D getEffectiveParentContext(DC);
   else if (GetLocalClassDecl(ND)) {
     mangleLocalName(ND);
     return;
   }
=20
-  while (isa<LinkageSpecDecl>(DC))
-    DC =3D DC->getParent();
+  DC =3D IgnoreLinkageSpecDecls(DC);
=20
   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
     // Check if we have a template.
@@ -547,7 +589,7 @@
 void CXXNameMangler::mangleName(const TemplateDecl *TD,
                                 const TemplateArgument *TemplateArgs,
                                 unsigned NumTemplateArgs) {
-  const DeclContext *DC =3D IgnoreLinkageSpecDecls(TD->getDeclContext());
+  const DeclContext *DC =3D IgnoreLinkageSpecDecls(getEffectiveDeclContext=
(TD));
=20
   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
     mangleUnscopedTemplateName(TD);
@@ -561,7 +603,8 @@
 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
   //  <unscoped-name> ::=3D <unqualified-name>
   //                  ::=3D St <unqualified-name>   # ::std::
-  if (isStdNamespace(ND->getDeclContext()))
+
+  if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
     Out << "St";
=20
   mangleUnqualifiedName(ND);
@@ -610,17 +653,41 @@
   //   representation (IEEE on Itanium), high-order bytes first,
   //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
   //   on Itanium.
-  // APInt::toString uses uppercase hexadecimal, and it's not really
-  // worth embellishing that interface for this use case, so we just
-  // do a second pass to lowercase things.
-  typedef llvm::SmallString<20> buffer_t;
-  buffer_t buffer;
-  f.bitcastToAPInt().toString(buffer, 16, false);
-
-  for (buffer_t::iterator i =3D buffer.begin(), e =3D buffer.end(); i !=3D=
 e; ++i)
-    if (isupper(*i)) *i =3D tolower(*i);
-
-  Out.write(buffer.data(), buffer.size());
+  // The 'without leading zeroes' thing seems to be an editorial
+  // mistake; see the discussion on cxx-abi-dev beginning on
+  // 2012-01-16.
+
+  // Our requirements here are just barely wierd enough to justify
+  // using a custom algorithm instead of post-processing APInt::toString().
+
+  llvm::APInt valueBits =3D f.bitcastToAPInt();
+  unsigned numCharacters =3D (valueBits.getBitWidth() + 3) / 4;
+  assert(numCharacters !=3D 0);
+
+  // Allocate a buffer of the right number of characters.
+  llvm::SmallVector<char, 20> buffer;
+  buffer.set_size(numCharacters);
+
+  // Fill the buffer left-to-right.
+  for (unsigned stringIndex =3D 0; stringIndex !=3D numCharacters; ++strin=
gIndex) {
+    // The bit-index of the next hex digit.
+    unsigned digitBitIndex =3D 4 * (numCharacters - stringIndex - 1);
+
+    // Project out 4 bits starting at 'digitIndex'.
+    llvm::integerPart hexDigit
+      =3D valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
+    hexDigit >>=3D (digitBitIndex % llvm::integerPartWidth);
+    hexDigit &=3D 0xF;
+
+    // Map that over to a lowercase hex digit.
+    static const char charForHex[16] =3D {
+      '0', '1', '2', '3', '4', '5', '6', '7',
+      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
+    };
+    buffer[stringIndex] =3D charForHex[hexDigit];
+  }
+
+  Out.write(buffer.data(), numCharacters);
 }
=20
 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
@@ -997,7 +1064,7 @@
       // This naming convention is the same as that followed by GCC,
       // though it shouldn't actually matter.
       if (ND && ND->getLinkage() =3D=3D InternalLinkage &&
-          ND->getDeclContext()->isFileContext())
+          getEffectiveDeclContext(ND)->isFileContext())
         Out << 'L';
=20
       mangleSourceName(II);
@@ -1052,13 +1119,24 @@
       break;
     }
=20
+    // <unnamed-type-name> ::=3D <closure-type-name>
+    //=20
+    // <closure-type-name> ::=3D Ul <lambda-sig> E [ <nonnegative number> =
] _
+    // <lambda-sig> ::=3D <parameter-type>+   # Parameter types or 'v' for=
 'void'.
+    if (const CXXRecordDecl *Record =3D dyn_cast<CXXRecordDecl>(TD)) {
+      if (Record->isLambda() && Record->getLambdaManglingNumber()) {
+        mangleLambda(Record);
+        break;
+      }
+    }
+       =20
     // Get a unique id for the anonymous struct.
     uint64_t AnonStructId =3D Context.getAnonymousStructId(TD);
=20
     // Mangle it as a source name in the form
     // [n] $_<id>
     // where n is the length of the string.
-    llvm::SmallString<8> Str;
+    SmallString<8> Str;
     Str +=3D "$_";
     Str +=3D llvm::utostr(AnonStructId);
=20
@@ -1180,8 +1258,10 @@
 void CXXNameMangler::mangleLocalName(const NamedDecl *ND) {
   // <local-name> :=3D Z <function encoding> E <entity name> [<discriminat=
or>]
   //              :=3D Z <function encoding> E s [<discriminator>]
+  // <local-name> :=3D Z <function encoding> E d [ <parameter number> ]=20
+  //                 _ <entity name>
   // <discriminator> :=3D _ <non-negative number>
-  const DeclContext *DC =3D ND->getDeclContext();
+  const DeclContext *DC =3D getEffectiveDeclContext(ND);
   if (isa<ObjCMethodDecl>(DC) && isa<FunctionDecl>(ND)) {
     // Don't add objc method name mangling to locally declared function
     mangleUnqualifiedName(ND);
@@ -1193,23 +1273,46 @@
   if (const ObjCMethodDecl *MD =3D dyn_cast<ObjCMethodDecl>(DC)) {
    mangleObjCMethodName(MD);
   } else if (const CXXRecordDecl *RD =3D GetLocalClassDecl(ND)) {
-    mangleFunctionEncoding(cast<FunctionDecl>(RD->getDeclContext()));
+    mangleFunctionEncoding(cast<FunctionDecl>(getEffectiveDeclContext(RD))=
);
     Out << 'E';
=20
+    // The parameter number is omitted for the last parameter, 0 for the=20
+    // second-to-last parameter, 1 for the third-to-last parameter, etc. T=
he=20
+    // <entity name> will of course contain a <closure-type-name>: Its=20
+    // numbering will be local to the particular argument in which it appe=
ars
+    // -- other default arguments do not affect its encoding.
+    bool SkipDiscriminator =3D false;
+    if (RD->isLambda()) {
+      if (const ParmVarDecl *Parm
+                 =3D dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDec=
l())) {
+        if (const FunctionDecl *Func
+              =3D dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
+          Out << 'd';
+          unsigned Num =3D Func->getNumParams() - Parm->getFunctionScopeIn=
dex();
+          if (Num > 1)
+            mangleNumber(Num - 2);
+          Out << '_';
+          SkipDiscriminator =3D true;
+        }
+      }
+    }
+   =20
     // Mangle the name relative to the closest enclosing function.
     if (ND =3D=3D RD) // equality ok because RD derived from ND above
       mangleUnqualifiedName(ND);
     else
       mangleNestedName(ND, DC, true /*NoFunction*/);
=20
-    unsigned disc;
-    if (Context.getNextDiscriminator(RD, disc)) {
-      if (disc < 10)
-        Out << '_' << disc;
-      else
-        Out << "__" << disc << '_';
+    if (!SkipDiscriminator) {
+      unsigned disc;
+      if (Context.getNextDiscriminator(RD, disc)) {
+        if (disc < 10)
+          Out << '_' << disc;
+        else
+          Out << "__" << disc << '_';
+      }
     }
-
+   =20
     return;
   }
   else
@@ -1219,6 +1322,48 @@
   mangleUnqualifiedName(ND);
 }
=20
+void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
+  // If the context of a closure type is an initializer for a class member=20
+  // (static or nonstatic), it is encoded in a qualified name with a final=20
+  // <prefix> of the form:
+  //
+  //   <data-member-prefix> :=3D <member source-name> M
+  //
+  // Technically, the data-member-prefix is part of the <prefix>. However,
+  // since a closure type will always be mangled with a prefix, it's easier
+  // to emit that last part of the prefix here.
+  if (Decl *Context =3D Lambda->getLambdaContextDecl()) {
+    if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
+        Context->getDeclContext()->isRecord()) {
+      if (const IdentifierInfo *Name
+            =3D cast<NamedDecl>(Context)->getIdentifier()) {
+        mangleSourceName(Name);
+        Out << 'M';           =20
+      }
+    }
+  }
+
+  Out << "Ul";
+  DeclarationName Name
+    =3D getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
+  const FunctionProtoType *Proto
+    =3D cast<CXXMethodDecl>(*Lambda->lookup(Name).first)->getType()->
+        getAs<FunctionProtoType>();
+  mangleBareFunctionType(Proto, /*MangleReturnType=3D*/false);       =20
+  Out << "E";
+ =20
+  // The number is omitted for the first closure type with a given=20
+  // <lambda-sig> in a given context; it is n-2 for the nth closure type=20
+  // (in lexical order) with that same <lambda-sig> and context.
+  //
+  // The AST keeps track of the number for us.
+  unsigned Number =3D Lambda->getLambdaManglingNumber();
+  assert(Number > 0 && "Lambda should be mangled as an unnamed class");
+  if (Number > 1)
+    mangleNumber(Number - 2);
+  Out << '_'; =20
+}
+
 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
   switch (qualifier->getKind()) {
   case NestedNameSpecifier::Global:
@@ -1258,15 +1403,14 @@
   //           ::=3D # empty
   //           ::=3D <substitution>
=20
-  while (isa<LinkageSpecDecl>(DC))
-    DC =3D DC->getParent();
+  DC =3D IgnoreLinkageSpecDecls(DC);
=20
   if (DC->isTranslationUnit())
     return;
=20
   if (const BlockDecl *Block =3D dyn_cast<BlockDecl>(DC)) {
-    manglePrefix(DC->getParent(), NoFunction);   =20
-    llvm::SmallString<64> Name;
+    manglePrefix(getEffectiveParentContext(DC), NoFunction);   =20
+    SmallString<64> Name;
     llvm::raw_svector_ostream NameStream(Name);
     Context.mangleBlock(Block, NameStream);
     NameStream.flush();
@@ -1274,26 +1418,27 @@
     return;
   }
  =20
-  if (mangleSubstitution(cast<NamedDecl>(DC)))
+  const NamedDecl *ND =3D cast<NamedDecl>(DC); =20
+  if (mangleSubstitution(ND))
     return;
-
+ =20
   // Check if we have a template.
   const TemplateArgumentList *TemplateArgs =3D 0;
-  if (const TemplateDecl *TD =3D isTemplate(cast<NamedDecl>(DC), TemplateA=
rgs)) {
+  if (const TemplateDecl *TD =3D isTemplate(ND, TemplateArgs)) {
     mangleTemplatePrefix(TD);
     TemplateParameterList *TemplateParameters =3D TD->getTemplateParameter=
s();
     mangleTemplateArgs(*TemplateParameters, *TemplateArgs);
   }
-  else if(NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
+  else if(NoFunction && (isa<FunctionDecl>(ND) || isa<ObjCMethodDecl>(ND)))
     return;
-  else if (const ObjCMethodDecl *Method =3D dyn_cast<ObjCMethodDecl>(DC))
+  else if (const ObjCMethodDecl *Method =3D dyn_cast<ObjCMethodDecl>(ND))
     mangleObjCMethodName(Method);
   else {
-    manglePrefix(DC->getParent(), NoFunction);
-    mangleUnqualifiedName(cast<NamedDecl>(DC));
+    manglePrefix(getEffectiveDeclContext(ND), NoFunction);
+    mangleUnqualifiedName(ND);
   }
=20
-  addSubstitution(cast<NamedDecl>(DC));
+  addSubstitution(ND);
 }
=20
 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
@@ -1336,7 +1481,7 @@
     return;
   }
=20
-  manglePrefix(ND->getDeclContext());
+  manglePrefix(getEffectiveDeclContext(ND));
   mangleUnqualifiedName(ND->getTemplatedDecl());
   addSubstitution(ND);
 }
@@ -1370,7 +1515,6 @@
=20
   case TemplateName::OverloadedTemplate:
     llvm_unreachable("can't mangle an overloaded template name as a <type>=
");
-    break;
=20
   case TemplateName::DependentTemplate: {
     const DependentTemplateName *Dependent =3D TN.getAsDependentTemplateNa=
me();
@@ -1531,7 +1675,7 @@
     //=20
     // where <address-space-number> is a source name consisting of 'AS'=20
     // followed by the address space <number>.
-    llvm::SmallString<64> ASString;
+    SmallString<64> ASString;
     ASString =3D "AS" + llvm::utostr_32(Quals.getAddressSpace());
     Out << 'U' << ASString.size() << ASString;
   }
@@ -1632,8 +1776,8 @@
     } while (true);
   }
   SplitQualType split =3D T.split();
-  Qualifiers quals =3D split.second;
-  const Type *ty =3D split.first;
+  Qualifiers quals =3D split.Quals;
+  const Type *ty =3D split.Ty;
=20
   bool isSubstitutable =3D quals || !isa<BuiltinType>(T);
   if (isSubstitutable && mangleSubstitution(T))
@@ -1735,12 +1879,12 @@
   case BuiltinType::LongDouble: Out << 'e'; break;
   case BuiltinType::NullPtr: Out << "Dn"; break;
=20
-  case BuiltinType::Overload:
+#define BUILTIN_TYPE(Id, SingletonId)
+#define PLACEHOLDER_TYPE(Id, SingletonId) \
+  case BuiltinType::Id:
+#include "clang/AST/BuiltinTypes.def"
   case BuiltinType::Dependent:
-  case BuiltinType::BoundMember:
-  case BuiltinType::UnknownAny:
     llvm_unreachable("mangling a placeholder type");
-    break;
   case BuiltinType::ObjCId: Out << "11objc_object"; break;
   case BuiltinType::ObjCClass: Out << "10objc_class"; break;
   case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
@@ -2217,15 +2361,12 @@
   // These all can only appear in local or variable-initialization
   // contexts and so should never appear in a mangling.
   case Expr::AddrLabelExprClass:
-  case Expr::BlockDeclRefExprClass:
   case Expr::CXXThisExprClass:
   case Expr::DesignatedInitExprClass:
   case Expr::ImplicitValueInitExprClass:
-  case Expr::InitListExprClass:
   case Expr::ParenListExprClass:
-  case Expr::CXXScalarValueInitExprClass:
+  case Expr::LambdaExprClass:
     llvm_unreachable("unexpected statement kind");
-    break;
=20
   // FIXME: invent manglings for all these.
   case Expr::BlockExprClass:
@@ -2242,6 +2383,10 @@
   case Expr::ObjCProtocolExprClass:
   case Expr::ObjCSelectorExprClass:
   case Expr::ObjCStringLiteralClass:
+  case Expr::ObjCNumericLiteralClass:
+  case Expr::ObjCArrayLiteralClass:
+  case Expr::ObjCDictionaryLiteralClass:
+  case Expr::ObjCSubscriptRefExprClass:
   case Expr::ObjCIndirectCopyRestoreExprClass:
   case Expr::OffsetOfExprClass:
   case Expr::PredefinedExprClass:
@@ -2249,6 +2394,7 @@
   case Expr::StmtExprClass:
   case Expr::UnaryTypeTraitExprClass:
   case Expr::BinaryTypeTraitExprClass:
+  case Expr::TypeTraitExprClass:
   case Expr::ArrayTypeTraitExprClass:
   case Expr::ExpressionTraitExprClass:
   case Expr::VAArgExprClass:
@@ -2256,6 +2402,7 @@
   case Expr::CXXNoexceptExprClass:
   case Expr::CUDAKernelCallExprClass:
   case Expr::AsTypeExprClass:
+  case Expr::PseudoObjectExprClass:
   case Expr::AtomicExprClass:
   {
     // As bad as this diagnostic is, it's better than crashing.
@@ -2282,6 +2429,16 @@
   case Expr::OpaqueValueExprClass:
     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
=20
+  case Expr::InitListExprClass: {
+    // Proposal by Jason Merrill, 2012-01-03
+    Out << "il";
+    const InitListExpr *InitList =3D cast<InitListExpr>(E);
+    for (unsigned i =3D 0, e =3D InitList->getNumInits(); i !=3D e; ++i)
+      mangleExpression(InitList->getInit(i));
+    Out << "E";
+    break;
+  }
+
   case Expr::CXXDefaultArgExprClass:
     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
     break;
@@ -2291,6 +2448,9 @@
                      Arity);
     break;
=20
+  case Expr::UserDefinedLiteralClass:
+    // We follow g++'s approach of mangling a UDL as a call to the literal
+    // operator.
   case Expr::CXXMemberCallExprClass: // fallthrough
   case Expr::CallExprClass: {
     const CallExpr *CE =3D cast<CallExpr>(E);
@@ -2318,7 +2478,6 @@
   }
=20
   case Expr::CXXNewExprClass: {
-    // Proposal from David Vandervoorde, 2010.06.30
     const CXXNewExpr *New =3D cast<CXXNewExpr>(E);
     if (New->isGlobalNew()) Out << "gs";
     Out << (New->isArray() ? "na" : "nw");
@@ -2328,10 +2487,29 @@
     Out << '_';
     mangleType(New->getAllocatedType());
     if (New->hasInitializer()) {
-      Out << "pi";
-      for (CXXNewExpr::const_arg_iterator I =3D New->constructor_arg_begin=
(),
-             E =3D New->constructor_arg_end(); I !=3D E; ++I)
-        mangleExpression(*I);
+      // Proposal by Jason Merrill, 2012-01-03
+      if (New->getInitializationStyle() =3D=3D CXXNewExpr::ListInit)
+        Out << "il";
+      else
+        Out << "pi";
+      const Expr *Init =3D New->getInitializer();
+      if (const CXXConstructExpr *CCE =3D dyn_cast<CXXConstructExpr>(Init)=
) {
+        // Directly inline the initializers.
+        for (CXXConstructExpr::const_arg_iterator I =3D CCE->arg_begin(),
+                                                  E =3D CCE->arg_end();
+             I !=3D E; ++I)
+          mangleExpression(*I);
+      } else if (const ParenListExpr *PLE =3D dyn_cast<ParenListExpr>(Init=
)) {
+        for (unsigned i =3D 0, e =3D PLE->getNumExprs(); i !=3D e; ++i)
+          mangleExpression(PLE->getExpr(i));
+      } else if (New->getInitializationStyle() =3D=3D CXXNewExpr::ListInit=
 &&
+                 isa<InitListExpr>(Init)) {
+        // Only take InitListExprs apart for list-initialization.
+        const InitListExpr *InitList =3D cast<InitListExpr>(Init);
+        for (unsigned i =3D 0, e =3D InitList->getNumInits(); i !=3D e; ++=
i)
+          mangleExpression(InitList->getInit(i));
+      } else
+        mangleExpression(Init);
     }
     Out << 'E';
     break;
@@ -2395,7 +2573,11 @@
     const CXXConstructExpr *CE =3D cast<CXXConstructExpr>(E);
     unsigned N =3D CE->getNumArgs();
=20
-    Out << "cv";
+    // Proposal by Jason Merrill, 2012-01-03
+    if (CE->isListInitialization())
+      Out << "tl";
+    else
+      Out << "cv";
     mangleType(CE->getType());
     if (N !=3D 1) Out << '_';
     for (unsigned I =3D 0; I !=3D N; ++I) mangleExpression(CE->getArg(I));
@@ -2403,6 +2585,12 @@
     break;
   }
=20
+  case Expr::CXXScalarValueInitExprClass:
+    Out <<"cv";
+    mangleType(E->getType());
+    Out <<"_E";
+    break;
+
   case Expr::UnaryExprOrTypeTraitExprClass: {
     const UnaryExprOrTypeTraitExpr *SAE =3D cast<UnaryExprOrTypeTraitExpr>=
(E);
    =20
@@ -2642,6 +2830,13 @@
     Out << 'E';
     break;
=20
+  // FIXME. __objc_yes/__objc_no are mangled same as true/false
+  case Expr::ObjCBoolLiteralExprClass:
+    Out << "Lb";
+    Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
+    Out << 'E';
+    break;
+ =20
   case Expr::CXXBoolLiteralExprClass:
     Out << "Lb";
     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
@@ -2897,23 +3092,48 @@
     Out << "Dp";
     mangleType(A.getAsTemplateOrTemplatePattern());
     break;
-  case TemplateArgument::Expression:
+  case TemplateArgument::Expression: {
+    // It's possible to end up with a DeclRefExpr here in certain
+    // dependent cases, in which case we should mangle as a
+    // declaration.
+    const Expr *E =3D A.getAsExpr()->IgnoreParens();
+    if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E)) {
+      const ValueDecl *D =3D DRE->getDecl();
+      if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
+        Out << "L";
+        mangle(D, "_Z");
+        Out << 'E';
+        break;
+      }
+    }
+   =20
     Out << 'X';
-    mangleExpression(A.getAsExpr());
+    mangleExpression(E);
     Out << 'E';
     break;
+  }
   case TemplateArgument::Integral:
     mangleIntegerLiteral(A.getIntegralType(), *A.getAsIntegral());
     break;
   case TemplateArgument::Declaration: {
     assert(P && "Missing template parameter for declaration argument");
     //  <expr-primary> ::=3D L <mangled-name> E # external name
-
+    //  <expr-primary> ::=3D L <type> 0 E
     // Clang produces AST's where pointer-to-member-function expressions
     // and pointer-to-function expressions are represented as a declaratio=
n not
     // an expression. We compensate for it here to produce the correct man=
gling.
+    const NonTypeTemplateParmDecl *Parameter =3D cast<NonTypeTemplateParmD=
ecl>(P);
+
+    // Handle NULL pointer arguments.
+    if (!A.getAsDecl()) {
+      Out << "L";
+      mangleType(Parameter->getType());
+      Out << "0E";
+      break;
+    }
+   =20
+
     NamedDecl *D =3D cast<NamedDecl>(A.getAsDecl());
-    const NonTypeTemplateParmDecl *Parameter =3D cast<NonTypeTemplateParmD=
ecl>(P);
     bool compensateMangling =3D !Parameter->getType()->isReferenceType();
     if (compensateMangling) {
       Out << 'X';
@@ -2982,8 +3202,15 @@
   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
 }
=20
+/// \brief Determine whether the given type has any qualifiers that are
+/// relevant for substitutions.
+static bool hasMangledSubstitutionQualifiers(QualType T) {
+  Qualifiers Qs =3D T.getQualifiers();
+  return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
+}
+
 bool CXXNameMangler::mangleSubstitution(QualType T) {
-  if (!T.getCVRQualifiers()) {
+  if (!hasMangledSubstitutionQualifiers(T)) {
     if (const RecordType *RT =3D T->getAs<RecordType>())
       return mangleSubstitution(RT->getDecl());
   }
@@ -3059,7 +3286,7 @@
   if (!SD)
     return false;
=20
-  if (!isStdNamespace(SD->getDeclContext()))
+  if (!isStdNamespace(getEffectiveDeclContext(SD)))
     return false;
=20
   const TemplateArgumentList &TemplateArgs =3D SD->getTemplateArgs();
@@ -3101,7 +3328,7 @@
   }
=20
   if (const ClassTemplateDecl *TD =3D dyn_cast<ClassTemplateDecl>(ND)) {
-    if (!isStdNamespace(TD->getDeclContext()))
+    if (!isStdNamespace(getEffectiveDeclContext(TD)))
       return false;
=20
     // <substitution> ::=3D Sa # ::std::allocator
@@ -3119,7 +3346,7 @@
=20
   if (const ClassTemplateSpecializationDecl *SD =3D
         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
-    if (!isStdNamespace(SD->getDeclContext()))
+    if (!isStdNamespace(getEffectiveDeclContext(SD)))
       return false;
=20
     //    <substitution> ::=3D Ss # ::std::basic_string<char,
@@ -3169,7 +3396,7 @@
 }
=20
 void CXXNameMangler::addSubstitution(QualType T) {
-  if (!T.getCVRQualifiers()) {
+  if (!hasMangledSubstitutionQualifiers(T)) {
     if (const RecordType *RT =3D T->getAs<RecordType>()) {
       addSubstitution(RT->getDecl());
       return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
Mangle.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/Mangle.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/Mangle.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -59,6 +59,8 @@
=20
 }
=20
+void MangleContext::anchor() { }
+
 void MangleContext::mangleGlobalBlock(const BlockDecl *BD,
                                       raw_ostream &Out) {
   Out << "__block_global_" << getBlockId(BD, false);
@@ -68,7 +70,7 @@
                                     CXXCtorType CT, const BlockDecl *BD,
                                     raw_ostream &ResStream) {
   checkMangleDC(CD, BD);
-  llvm::SmallString<64> Buffer;
+  SmallString<64> Buffer;
   llvm::raw_svector_ostream Out(Buffer);
   mangleCXXCtor(CD, CT, Out);
   Out.flush();
@@ -79,7 +81,7 @@
                                     CXXDtorType DT, const BlockDecl *BD,
                                     raw_ostream &ResStream) {
   checkMangleDC(DD, BD);
-  llvm::SmallString<64> Buffer;
+  SmallString<64> Buffer;
   llvm::raw_svector_ostream Out(Buffer);
   mangleCXXDtor(DD, DT, Out);
   Out.flush();
@@ -91,7 +93,7 @@
   assert(!isa<CXXConstructorDecl>(DC) && !isa<CXXDestructorDecl>(DC));
   checkMangleDC(DC, BD);
=20
-  llvm::SmallString<64> Buffer;
+  SmallString<64> Buffer;
   llvm::raw_svector_ostream Stream(Buffer);
   if (const ObjCMethodDecl *Method =3D dyn_cast<ObjCMethodDecl>(DC)) {
     mangleObjCMethodName(Method, Stream);
@@ -114,7 +116,7 @@
=20
 void MangleContext::mangleObjCMethodName(const ObjCMethodDecl *MD,
                                          raw_ostream &Out) {
-  llvm::SmallString<64> Name;
+  SmallString<64> Name;
   llvm::raw_svector_ostream OS(Name);
  =20
   const ObjCContainerDecl *CD =3D
@@ -122,7 +124,7 @@
   assert (CD && "Missing container decl in GetNameForMethod");
   OS << (MD->isInstanceMethod() ? '-' : '+') << '[' << CD->getName();
   if (const ObjCCategoryImplDecl *CID =3D dyn_cast<ObjCCategoryImplDecl>(C=
D))
-    OS << '(' << CID << ')';
+    OS << '(' << *CID << ')';
   OS << ' ' << MD->getSelector().getAsString() << ']';
  =20
   Out << OS.str().size() << OS.str();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
MicrosoftMangle.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -119,7 +119,7 @@
=20
 bool MicrosoftMangleContext::shouldMangleDeclName(const NamedDecl *D) {
   // In C, functions with no attributes never need to be mangled. Fastpath=
 them.
-  if (!getASTContext().getLangOptions().CPlusPlus && !D->hasAttrs())
+  if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
     return false;
=20
   // Any decl can be declared with __asm("foo") on it, and this takes prec=
edence
@@ -136,7 +136,7 @@
     return true;
=20
   // Otherwise, no mangling is done outside C++ mode.
-  if (!getASTContext().getLangOptions().CPlusPlus)
+  if (!getASTContext().getLangOpts().CPlusPlus)
     return false;
=20
   // Variables at global scope with internal linkage are not mangled.
@@ -335,10 +335,12 @@
       llvm_unreachable("Can't mangle Objective-C selector names here!");
      =20
     case DeclarationName::CXXConstructorName:
-      llvm_unreachable("Can't mangle constructors yet!");
+      Out << "?0";
+      break;
      =20
     case DeclarationName::CXXDestructorName:
-      llvm_unreachable("Can't mangle destructors yet!");
+      Out << "?1";
+      break;
      =20
     case DeclarationName::CXXConversionFunctionName:
       // <operator-name> ::=3D ?B # (cast)
@@ -701,12 +703,13 @@
   case BuiltinType::WChar_S:
   case BuiltinType::WChar_U: Out << "_W"; break;
=20
-  case BuiltinType::Overload:
+#define BUILTIN_TYPE(Id, SingletonId)
+#define PLACEHOLDER_TYPE(Id, SingletonId) \
+  case BuiltinType::Id:
+#include "clang/AST/BuiltinTypes.def"
   case BuiltinType::Dependent:
-  case BuiltinType::UnknownAny:
-  case BuiltinType::BoundMember:
-    llvm_unreachable(
-           "Overloaded and dependent types shouldn't get to name mangling"=
);
+    llvm_unreachable("placeholder types shouldn't get to name mangling");
+
   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
@@ -715,7 +718,7 @@
   case BuiltinType::Char32:
   case BuiltinType::Half:
   case BuiltinType::NullPtr:
-    llvm_unreachable("Don't know how to mangle this type");
+    assert(0 && "Don't know how to mangle this type yet");
   }
 }
=20
@@ -1167,13 +1170,15 @@
 }
 void MicrosoftMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
                                            CXXCtorType Type,
-                                           raw_ostream &) {
-  llvm_unreachable("Can't yet mangle constructors!");
+                                           raw_ostream & Out) {
+  MicrosoftCXXNameMangler mangler(*this, Out);
+  mangler.mangle(D);
 }
 void MicrosoftMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
                                            CXXDtorType Type,
-                                           raw_ostream &) {
-  llvm_unreachable("Can't yet mangle destructors!");
+                                           raw_ostream & Out) {
+  MicrosoftCXXNameMangler mangler(*this, Out);
+  mangler.mangle(D);
 }
 void MicrosoftMangleContext::mangleReferenceTemporary(const clang::VarDecl=
 *,
                                                       raw_ostream &) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
NestedNameSpecifier.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/NestedNameSpecifier.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/NestedNameSpecifier.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -130,7 +130,7 @@
     return TypeSpecWithTemplate;
   }
=20
-  return Global;
+  llvm_unreachable("Invalid NNS Kind!");
 }
=20
 /// \brief Retrieve the namespace stored in this nested name
@@ -170,8 +170,7 @@
     return getAsType()->isDependentType();
   }
=20
-  // Necessary to suppress a GCC warning.
-  return false;
+  llvm_unreachable("Invalid NNS Kind!");
 }
=20
 /// \brief Whether this nested name specifier refers to a dependent
@@ -191,9 +190,8 @@
   case TypeSpecWithTemplate:
     return getAsType()->isInstantiationDependentType();
   }
- =20
-  // Necessary to suppress a GCC warning.
-  return false;
+
+  llvm_unreachable("Invalid NNS Kind!");
 }
=20
 bool NestedNameSpecifier::containsUnexpandedParameterPack() const {
@@ -211,8 +209,7 @@
     return getAsType()->containsUnexpandedParameterPack();
   }
=20
-  // Necessary to suppress a GCC warning.
-  return false; =20
+  llvm_unreachable("Invalid NNS Kind!");
 }
=20
 /// \brief Print this nested name specifier to the given output
@@ -229,6 +226,9 @@
     break;
=20
   case Namespace:
+    if (getAsNamespace()->isAnonymousNamespace())
+      return;
+     =20
     OS << getAsNamespace()->getName();
     break;
=20
@@ -379,8 +379,8 @@
                        LoadSourceLocation(Data, Offset + sizeof(void*)));
   }
   }
- =20
-  return SourceRange();
+
+  llvm_unreachable("Invalid NNS Kind!");
 }
=20
 TypeLoc NestedNameSpecifierLoc::getTypeLoc() const {
@@ -434,9 +434,6 @@
   }
 }
=20
-NestedNameSpecifierLocBuilder::NestedNameSpecifierLocBuilder()
-  : Representation(0), Buffer(0), BufferSize(0), BufferCapacity(0) { }
-
 NestedNameSpecifierLocBuilder::
 NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other)=20
   : Representation(Other.Representation), Buffer(0),
@@ -499,11 +496,6 @@
   return *this;
 }
=20
-NestedNameSpecifierLocBuilder::~NestedNameSpecifierLocBuilder() {
-  if (BufferCapacity)
-    free(Buffer);
-}
-
 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,=20
                                            SourceLocation TemplateKWLoc,=20
                                            TypeLoc TL,=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
ParentMap.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/ParentMap.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/ParentMap.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -26,6 +26,10 @@
       M[*I] =3D S;
       BuildParentMap(M, *I);
     }
+ =20
+  // Also include the source expr tree of an OpaqueValueExpr in the map.
+  if (const OpaqueValueExpr *OVE =3D dyn_cast<OpaqueValueExpr>(S))
+    BuildParentMap(M, OVE->getSourceExpr());
 }
=20
 ParentMap::ParentMap(Stmt* S) : Impl(0) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
RecordLayout.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/RecordLayout.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/RecordLayout.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -43,7 +43,8 @@
 // Constructor for C++ records.
 ASTRecordLayout::ASTRecordLayout(const ASTContext &Ctx,
                                  CharUnits size, CharUnits alignment,
-                                 CharUnits vbptroffset, CharUnits datasize,
+                                 CharUnits vfptroffset, CharUnits vbptroff=
set,
+                                 CharUnits datasize,
                                  const uint64_t *fieldoffsets,
                                  unsigned fieldcount,
                                  CharUnits nonvirtualsize,
@@ -68,6 +69,7 @@
   CXXInfo->SizeOfLargestEmptySubobject =3D SizeOfLargestEmptySubobject;
   CXXInfo->BaseOffsets =3D BaseOffsets;
   CXXInfo->VBaseOffsets =3D VBaseOffsets;
+  CXXInfo->VFPtrOffset =3D vfptroffset;
   CXXInfo->VBPtrOffset =3D vbptroffset;
=20
 #ifndef NDEBUG
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
RecordLayoutBuilder.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -558,6 +558,14 @@
=20
   SmallVector<uint64_t, 16> FieldOffsets;
=20
+  /// \brief Whether the external AST source has provided a layout for this
+  /// record.
+  unsigned ExternalLayout : 1;
+
+  /// \brief Whether we need to infer alignment, even when we have an=20
+  /// externally-provided layout.
+  unsigned InferAlignment : 1;
+ =20
   /// Packed - Whether the record is packed or not.
   unsigned Packed : 1;
=20
@@ -592,6 +600,9 @@
   /// out is virtual.
   bool PrimaryBaseIsVirtual;
=20
+  /// VFPtrOffset - Virtual function table offset. Only for MS layout.
+  CharUnits VFPtrOffset;
+
   /// VBPtrOffset - Virtual base table offset. Only for MS layout.
   CharUnits VBPtrOffset;
=20
@@ -615,19 +626,47 @@
   /// avoid visiting virtual bases more than once.
   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
=20
-  RecordLayoutBuilder(const ASTContext &Context, EmptySubobjectMap
-                      *EmptySubobjects, CharUnits Alignment)
+  /// \brief Externally-provided size.
+  uint64_t ExternalSize;
+ =20
+  /// \brief Externally-provided alignment.
+  uint64_t ExternalAlign;
+ =20
+  /// \brief Externally-provided field offsets.
+  llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
+
+  /// \brief Externally-provided direct, non-virtual base offsets.
+  llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
+
+  /// \brief Externally-provided virtual base offsets.
+  llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffs=
ets;
+
+  RecordLayoutBuilder(const ASTContext &Context,
+                      EmptySubobjectMap *EmptySubobjects)
     : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),=20
-      Alignment(Alignment), UnpackedAlignment(Alignment),
-      Packed(false), IsUnion(false),=20
-      IsMac68kAlign(false), IsMsStruct(false),
+      Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
+      ExternalLayout(false), InferAlignment(false),=20
+      Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(fals=
e),
       UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()),=20
       DataSize(0), NonVirtualSize(CharUnits::Zero()),=20
       NonVirtualAlignment(CharUnits::One()),=20
       ZeroLengthBitfield(0), PrimaryBase(0),=20
-      PrimaryBaseIsVirtual(false), VBPtrOffset(CharUnits::fromQuantity(-1)=
),
+      PrimaryBaseIsVirtual(false),
+      VFPtrOffset(CharUnits::fromQuantity(-1)),
+      VBPtrOffset(CharUnits::fromQuantity(-1)),
       FirstNearlyEmptyVBase(0) { }
=20
+  /// Reset this RecordLayoutBuilder to a fresh state, using the given
+  /// alignment as the initial alignment.  This is used for the
+  /// correct layout of vb-table pointers in MSVC.
+  void resetWithTargetAlignment(CharUnits TargetAlignment) {
+    const ASTContext &Context =3D this->Context;
+    EmptySubobjectMap *EmptySubobjects =3D this->EmptySubobjects;
+    this->~RecordLayoutBuilder();
+    new (this) RecordLayoutBuilder(Context, EmptySubobjects);
+    Alignment =3D UnpackedAlignment =3D TargetAlignment;
+  }
+
   void Layout(const RecordDecl *D);
   void Layout(const CXXRecordDecl *D);
   void Layout(const ObjCInterfaceDecl *D);
@@ -637,8 +676,12 @@
   void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
                           bool FieldPacked, const FieldDecl *D);
   void LayoutBitField(const FieldDecl *D);
+
+  bool isMicrosoftCXXABI() const {
+    return Context.getTargetInfo().getCXXABI() =3D=3D CXXABI_Microsoft;
+  }
+
   void MSLayoutVirtualBases(const CXXRecordDecl *RD);
-  void MSLayout(const CXXRecordDecl *RD);
=20
   /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
   llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAlloc=
ator;
@@ -669,7 +712,7 @@
=20
   void SelectPrimaryVBase(const CXXRecordDecl *RD);
=20
-  CharUnits GetVirtualPointersSize(const CXXRecordDecl *RD) const;
+  void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
=20
   /// LayoutNonVirtualBases - Determines the primary base class (if any) a=
nd
   /// lays it out. Will then proceed to lay out all non-virtual base clase=
ss.
@@ -681,6 +724,10 @@
   void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
                                     CharUnits Offset);
=20
+  bool needsVFTable(const CXXRecordDecl *RD) const;
+  bool hasNewVirtualFunction(const CXXRecordDecl *RD) const;
+  bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
+
   /// LayoutVirtualBases - Lays out all the virtual bases.
   void LayoutVirtualBases(const CXXRecordDecl *RD,
                           const CXXRecordDecl *MostDerivedClass);
@@ -704,6 +751,14 @@
     UpdateAlignment(NewAlignment, NewAlignment);
   }
=20
+  /// \brief Retrieve the externally-supplied field offset for the given
+  /// field.
+  ///
+  /// \param Field The field whose offset is being queried.
+  /// \param ComputedOffset The offset that we've computed for this field.
+  uint64_t updateExternalFieldOffset(const FieldDecl *Field,=20
+                                     uint64_t ComputedOffset);
+ =20
   void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
                           uint64_t UnpackedOffset, unsigned UnpackedAlign,
                           bool isPacked, const FieldDecl *D);
@@ -730,20 +785,10 @@
   void setDataSize(CharUnits NewSize) { DataSize =3D Context.toBits(NewSiz=
e); }
   void setDataSize(uint64_t NewSize) { DataSize =3D NewSize; }
=20
-  bool HasVBPtr(const CXXRecordDecl *RD) const;
-  bool HasNewVirtualFunction(const CXXRecordDecl *RD) const;
-
-  /// Add vbptr or vfptr to layout.
-  void AddVPointer();
-
   RecordLayoutBuilder(const RecordLayoutBuilder&);   // DO NOT IMPLEMENT
   void operator=3D(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
 public:
   static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD);
-
-  virtual ~RecordLayoutBuilder() { }
-
-  CharUnits GetVBPtrOffset() const { return VBPtrOffset; }
 };
 } // end anonymous namespace
=20
@@ -778,11 +823,6 @@
   }
 }
=20
-CharUnits
-RecordLayoutBuilder::GetVirtualPointersSize(const CXXRecordDecl *RD) const=
 {
-  return Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWid=
th(0));
-}
-
 /// DeterminePrimaryBase - Determine the primary base of the given class.
 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
   // If the class isn't dynamic, it won't have a primary base.
@@ -805,7 +845,7 @@
     const CXXRecordDecl *Base =3D
       cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
=20
-    if (Base->isDynamicClass()) {
+    if (isPossiblePrimaryBase(Base)) {
       // We found it.
       PrimaryBase =3D Base;
       PrimaryBaseIsVirtual =3D false;
@@ -813,44 +853,30 @@
     }
   }
=20
-  // Otherwise, it is the first nearly empty virtual base that is not an
-  // indirect primary virtual base class, if one exists.
+  // The Microsoft ABI doesn't have primary virtual bases.
+  if (isMicrosoftCXXABI()) {
+    assert(!PrimaryBase && "Should not get here with a primary base!");
+    return;
+  }
+
+  // Under the Itanium ABI, if there is no non-virtual primary base class,
+  // try to compute the primary virtual base.  The primary virtual base is
+  // the first nearly empty virtual base that is not an indirect primary
+  // virtual base class, if one exists.
   if (RD->getNumVBases() !=3D 0) {
     SelectPrimaryVBase(RD);
     if (PrimaryBase)
       return;
   }
=20
-  // Otherwise, it is the first nearly empty virtual base that is not an
-  // indirect primary virtual base class, if one exists.
+  // Otherwise, it is the first indirect primary base class, if one exists.
   if (FirstNearlyEmptyVBase) {
     PrimaryBase =3D FirstNearlyEmptyVBase;
     PrimaryBaseIsVirtual =3D true;
     return;
   }
=20
-  // Otherwise there is no primary base class.
   assert(!PrimaryBase && "Should not get here with a primary base!");
-
-  // Allocate the virtual table pointer at offset zero.
-  assert(DataSize =3D=3D 0 && "Vtable pointer must be at offset zero!");
-
-  // Update the size.
-  setSize(getSize() + GetVirtualPointersSize(RD));
-  setDataSize(getSize());
-
-  CharUnits UnpackedBaseAlign =3D=20
-    Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0)=
);
-  CharUnits BaseAlign =3D (Packed) ? CharUnits::One() : UnpackedBaseAlign;
-
-  // The maximum field alignment overrides base align.
-  if (!MaxFieldAlignment.isZero()) {
-    BaseAlign =3D std::min(BaseAlign, MaxFieldAlignment);
-    UnpackedBaseAlign =3D std::min(UnpackedBaseAlign, MaxFieldAlignment);
-  }
-
-  // Update the alignment.
-  UpdateAlignment(BaseAlign, UnpackedBaseAlign);
 }
=20
 BaseSubobjectInfo *
@@ -959,6 +985,24 @@
 }
=20
 void
+RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAl=
ign) {
+  CharUnits BaseAlign =3D (Packed) ? CharUnits::One() : UnpackedBaseAlign;
+
+  // The maximum field alignment overrides base align.
+  if (!MaxFieldAlignment.isZero()) {
+    BaseAlign =3D std::min(BaseAlign, MaxFieldAlignment);
+    UnpackedBaseAlign =3D std::min(UnpackedBaseAlign, MaxFieldAlignment);
+  }
+
+  // Round up the current record size to pointer alignment.
+  setSize(getSize().RoundUpToAlignment(BaseAlign));
+  setDataSize(getSize());
+
+  // Update the alignment.
+  UpdateAlignment(BaseAlign, UnpackedBaseAlign);
+}
+
+void
 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
   // Then, determine the primary base class.
   DeterminePrimaryBase(RD);
@@ -990,20 +1034,45 @@
=20
       LayoutNonVirtualBase(PrimaryBaseInfo);
     }
+
+  // If this class needs a vtable/vf-table and didn't get one from a
+  // primary base, add it in now.
+  } else if (needsVFTable(RD)) {
+    assert(DataSize =3D=3D 0 && "Vtable pointer must be at offset zero!");
+    CharUnits PtrWidth =3D=20
+      Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(=
0));
+    CharUnits PtrAlign =3D=20
+      Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(=
0));
+    EnsureVTablePointerAlignment(PtrAlign);
+    if (isMicrosoftCXXABI())
+      VFPtrOffset =3D getSize();
+    setSize(getSize() + PtrWidth);
+    setDataSize(getSize());
   }
=20
+  bool HasDirectVirtualBases =3D false;
+  bool HasNonVirtualBaseWithVBTable =3D false;
+
   // Now lay out the non-virtual bases.
   for (CXXRecordDecl::base_class_const_iterator I =3D RD->bases_begin(),
          E =3D RD->bases_end(); I !=3D E; ++I) {
=20
-    // Ignore virtual bases.
-    if (I->isVirtual())
+    // Ignore virtual bases, but remember that we saw one.
+    if (I->isVirtual()) {
+      HasDirectVirtualBases =3D true;
       continue;
+    }
=20
     const CXXRecordDecl *BaseDecl =3D
-      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
+      cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
=20
-    // Skip the primary base.
+    // Remember if this base has virtual bases itself.
+    if (BaseDecl->getNumVBases())
+      HasNonVirtualBaseWithVBTable =3D true;
+
+    // Skip the primary base, because we've already laid it out.  The
+    // !PrimaryBaseIsVirtual check is required because we might have a
+    // non-virtual base of the same type as a primary virtual base.
     if (BaseDecl =3D=3D PrimaryBase && !PrimaryBaseIsVirtual)
       continue;
=20
@@ -1013,6 +1082,37 @@
=20
     LayoutNonVirtualBase(BaseInfo);
   }
+
+  // In the MS ABI, add the vb-table pointer if we need one, which is
+  // whenever we have a virtual base and we can't re-use a vb-table
+  // pointer from a non-virtual base.
+  if (isMicrosoftCXXABI() &&
+      HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
+    CharUnits PtrWidth =3D=20
+      Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(=
0));
+    CharUnits PtrAlign =3D=20
+      Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(=
0));
+
+    // MSVC potentially over-aligns the vb-table pointer by giving it
+    // the max alignment of all the non-virtual objects in the class.
+    // This is completely unnecessary, but we're not here to pass
+    // judgment.
+    //
+    // Note that we've only laid out the non-virtual bases, so on the
+    // first pass Alignment won't be set correctly here, but if the
+    // vb-table doesn't end up aligned correctly we'll come through
+    // and redo the layout from scratch with the right alignment.
+    //
+    // TODO: Instead of doing this, just lay out the fields as if the
+    // vb-table were at offset zero, then retroactively bump the field
+    // offsets up.
+    PtrAlign =3D std::max(PtrAlign, Alignment);
+
+    EnsureVTablePointerAlignment(PtrAlign);
+    VBPtrOffset =3D getSize();
+    setSize(getSize() + PtrWidth);
+    setDataSize(getSize());
+  }
 }
=20
 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Ba=
se) {
@@ -1061,43 +1161,81 @@
   }
 }
=20
-void RecordLayoutBuilder::AddVPointer() {
-  CharUnits PtrWidth =3D=20
-    Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)=
);
-  setSize(getSize() + PtrWidth);
-  setDataSize(getSize());
+/// needsVFTable - Return true if this class needs a vtable or vf-table
+/// when laid out as a base class.  These are treated the same because
+/// they're both always laid out at offset zero.
+///
+/// This function assumes that the class has no primary base.
+bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
+  assert(!PrimaryBase);
=20
-  if (Alignment > PtrWidth) {
-    setSize(getSize() + (Alignment - PtrWidth));
-    setDataSize(getSize());
-  }
+  // In the Itanium ABI, every dynamic class needs a vtable: even if
+  // this class has no virtual functions as a base class (i.e. it's
+  // non-polymorphic or only has virtual functions from virtual
+  // bases),x it still needs a vtable to locate its virtual bases.
+  if (!isMicrosoftCXXABI())
+    return RD->isDynamicClass();
+
+  // In the MS ABI, we need a vfptr if the class has virtual functions
+  // other than those declared by its virtual bases.  The AST doesn't
+  // tell us that directly, and checking manually for virtual
+  // functions that aren't overrides is expensive, but there are
+  // some important shortcuts:
+
+  //  - Non-polymorphic classes have no virtual functions at all.
+  if (!RD->isPolymorphic()) return false;
+
+  //  - Polymorphic classes with no virtual bases must either declare
+  //    virtual functions directly or inherit them, but in the latter
+  //    case we would have a primary base.
+  if (RD->getNumVBases() =3D=3D 0) return true;
+
+  return hasNewVirtualFunction(RD);
 }
=20
+/// hasNewVirtualFunction - Does the given polymorphic class declare a
+/// virtual function that does not override a method from any of its
+/// base classes?
 bool=20
-RecordLayoutBuilder::HasNewVirtualFunction(const CXXRecordDecl *RD) const {
+RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD) const {
+  assert(RD->isPolymorphic());
+  if (!RD->getNumBases())=20
+    return true;
+
   for (CXXRecordDecl::method_iterator method =3D RD->method_begin();
        method !=3D RD->method_end();
        ++method) {
-    if (method->isVirtual() &&
-      !method->size_overridden_methods()) {
+    if (method->isVirtual() && !method->size_overridden_methods()) {
       return true;
     }
   }
   return false;
 }
=20
-bool
-RecordLayoutBuilder::HasVBPtr(const CXXRecordDecl *RD) const {
-  if (!RD->getNumBases())
-    return false;
+/// isPossiblePrimaryBase - Is the given base class an acceptable
+/// primary base class?
+bool=20
+RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *Base) cons=
t {
+  // In the Itanium ABI, a class can be a primary base class if it has
+  // a vtable for any reason.
+  if (!isMicrosoftCXXABI())
+    return Base->isDynamicClass();
=20
-  for (CXXRecordDecl::base_class_const_iterator I =3D RD->bases_begin(),
-       E =3D RD->bases_end(); I !=3D E; ++I) {
-    if (!I->isVirtual()) {
-      return false;
-    }
-  }
-  return true;
+  // In the MS ABI, a class can only be a primary base class if it
+  // provides a vf-table at a static offset.  That means it has to be
+  // non-virtual base.  The existence of a separate vb-table means
+  // that it's possible to get virtual functions only from a virtual
+  // base, which we have to guard against.
+
+  // First off, it has to have virtual functions.
+  if (!Base->isPolymorphic()) return false;
+
+  // If it has no virtual bases, then everything is at a static offset.
+  if (!Base->getNumVBases()) return true;
+
+  // Okay, just ask the base class's layout.
+  return (Context.getASTRecordLayout(Base).getVFPtrOffset()
+            !=3D CharUnits::fromQuantity(-1));
 }
=20
 void
@@ -1121,7 +1259,7 @@
            "Cannot layout class with dependent bases.");
=20
     const CXXRecordDecl *BaseDecl =3D
-      cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
+      cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
=20
     if (I->isVirtual()) {
       if (PrimaryBase !=3D BaseDecl || !PrimaryBaseIsVirtual) {
@@ -1149,6 +1287,23 @@
   }
 }
=20
+void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
+
+  if (!RD->getNumVBases())
+    return;
+
+  // This is substantially simplified because there are no virtual
+  // primary bases.
+  for (CXXRecordDecl::base_class_const_iterator I =3D RD->vbases_begin(),
+       E =3D RD->vbases_end(); I !=3D E; ++I) {
+    const CXXRecordDecl *BaseDecl =3D I->getType()->getAsCXXRecordDecl();
+    const BaseSubobjectInfo *BaseInfo =3D VirtualBaseInfo.lookup(BaseDecl);
+    assert(BaseInfo && "Did not find virtual base info!");
+   =20
+    LayoutVirtualBase(BaseInfo);
+  }
+}
+
 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base)=
 {
   assert(!Base->Derived && "Trying to lay out a primary virtual base!");
  =20
@@ -1165,8 +1320,31 @@
 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
   const ASTRecordLayout &Layout =3D Context.getASTRecordLayout(Base->Class=
);
=20
+ =20
+  CharUnits Offset;
+ =20
+  // Query the external layout to see if it provides an offset.
+  bool HasExternalLayout =3D false;
+  if (ExternalLayout) {
+    llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
+    if (Base->IsVirtual) {
+      Known =3D ExternalVirtualBaseOffsets.find(Base->Class);
+      if (Known !=3D ExternalVirtualBaseOffsets.end()) {
+        Offset =3D Known->second;
+        HasExternalLayout =3D true;
+      }
+    } else {
+      Known =3D ExternalBaseOffsets.find(Base->Class);
+      if (Known !=3D ExternalBaseOffsets.end()) {
+        Offset =3D Known->second;
+        HasExternalLayout =3D true;
+      }
+    }
+  }
+ =20
   // If we have an empty base class, try to place it at offset 0.
   if (Base->Class->isEmpty() &&
+      (!HasExternalLayout || Offset =3D=3D CharUnits::Zero()) &&
       EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
     setSize(std::max(getSize(), Layout.getSize()));
=20
@@ -1182,13 +1360,19 @@
     UnpackedBaseAlign =3D std::min(UnpackedBaseAlign, MaxFieldAlignment);
   }
=20
-  // Round up the current record size to the base's alignment boundary.
-  CharUnits Offset =3D getDataSize().RoundUpToAlignment(BaseAlign);
+  if (!HasExternalLayout) {
+    // Round up the current record size to the base's alignment boundary.
+    Offset =3D getDataSize().RoundUpToAlignment(BaseAlign);
=20
-  // Try to place the base.
-  while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
-    Offset +=3D BaseAlign;
-
+    // Try to place the base.
+    while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
+      Offset +=3D BaseAlign;
+  } else {
+    bool Allowed =3D EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
+    (void)Allowed;
+    assert(Allowed && "Base subobject externally placed at overlapping off=
set");
+  }
+ =20
   if (!Base->Class->isEmpty()) {
     // Update the data size.
     setDataSize(Offset + Layout.getNonVirtualSize());
@@ -1212,7 +1396,7 @@
   IsMsStruct =3D D->hasAttr<MsStructAttr>();
=20
   // Honor the default struct packing maximum alignment flag.
-  if (unsigned DefaultMaxFieldAlignment =3D Context.getLangOptions().PackS=
truct) {
+  if (unsigned DefaultMaxFieldAlignment =3D Context.getLangOpts().PackStru=
ct) {
     MaxFieldAlignment =3D CharUnits::fromQuantity(DefaultMaxFieldAlignment=
);
   }
=20
@@ -1231,6 +1415,28 @@
     if (unsigned MaxAlign =3D D->getMaxAlignment())
       UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
   }
+ =20
+  // If there is an external AST source, ask it for the various offsets.
+  if (const RecordDecl *RD =3D dyn_cast<RecordDecl>(D))
+    if (ExternalASTSource *External =3D Context.getExternalSource()) {
+      ExternalLayout =3D External->layoutRecordType(RD,=20
+                                                  ExternalSize,
+                                                  ExternalAlign,
+                                                  ExternalFieldOffsets,
+                                                  ExternalBaseOffsets,
+                                                  ExternalVirtualBaseOffse=
ts);
+     =20
+      // Update based on external alignment.
+      if (ExternalLayout) {
+        if (ExternalAlign > 0) {
+          Alignment =3D Context.toCharUnitsFromBits(ExternalAlign);
+          UnpackedAlignment =3D Alignment;
+        } else {
+          // The external source didn't have alignment information; infer =
it.
+          InferAlignment =3D true;
+        }
+      }
+    }
 }
=20
 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
@@ -1243,11 +1449,6 @@
 }
=20
 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
-  if (Context.getTargetInfo().getCXXABI() =3D=3D CXXABI_Microsoft) {
-    MSLayout(RD);
-    return ;
-  }
-
   InitializeLayout(RD);
=20
   // Lay out the vtable and the non-virtual bases.
@@ -1260,13 +1461,27 @@
                                  Context.getTargetInfo().getCharAlign()));
   NonVirtualAlignment =3D Alignment;
=20
-  // Lay out the virtual bases and add the primary virtual base offsets.
-  LayoutVirtualBases(RD, RD);
+  if (isMicrosoftCXXABI() &&
+      NonVirtualSize !=3D NonVirtualSize.RoundUpToAlignment(Alignment)) {
+    CharUnits AlignMember =3D=20
+      NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
=20
-  VisitedVirtualBases.clear();
+    setSize(getSize() + AlignMember);
+    setDataSize(getSize());
=20
-  // Finally, round the size of the total struct up to the alignment of the
-  // struct itself.
+    NonVirtualSize =3D Context.toCharUnitsFromBits(
+                             llvm::RoundUpToAlignment(getSizeInBits(),
+                             Context.getTargetInfo().getCharAlign()));
+
+    MSLayoutVirtualBases(RD);
+
+  } else {
+    // Lay out the virtual bases and add the primary virtual base offsets.
+    LayoutVirtualBases(RD, RD);
+  }
+
+  // Finally, round the size of the total struct up to the alignment
+  // of the struct itself.
   FinishLayout(RD);
=20
 #ifndef NDEBUG
@@ -1350,13 +1565,21 @@
         uint64_t TypeSize =3D FieldInfo.first;
         unsigned FieldAlign =3D FieldInfo.second;
         // This check is needed for 'long long' in -m32 mode.
-        if (TypeSize > FieldAlign)
+        if (TypeSize > FieldAlign &&
+            (Context.hasSameType(FD->getType(),=20
+                                Context.UnsignedLongLongTy)=20
+             ||Context.hasSameType(FD->getType(),=20
+                                   Context.LongLongTy)))
           FieldAlign =3D TypeSize;
         FieldInfo =3D Context.getTypeInfo(LastFD->getType());
         uint64_t TypeSizeLastFD =3D FieldInfo.first;
         unsigned FieldAlignLastFD =3D FieldInfo.second;
         // This check is needed for 'long long' in -m32 mode.
-        if (TypeSizeLastFD > FieldAlignLastFD)
+        if (TypeSizeLastFD > FieldAlignLastFD &&
+            (Context.hasSameType(LastFD->getType(),=20
+                                Context.UnsignedLongLongTy)
+             || Context.hasSameType(LastFD->getType(),=20
+                                    Context.LongLongTy)))
           FieldAlignLastFD =3D TypeSizeLastFD;
        =20
         if (TypeSizeLastFD !=3D TypeSize) {
@@ -1435,7 +1658,7 @@
                                              uint64_t TypeSize,
                                              bool FieldPacked,
                                              const FieldDecl *D) {
-  assert(Context.getLangOptions().CPlusPlus &&
+  assert(Context.getLangOpts().CPlusPlus &&
          "Can only have wide bit-fields in C++!");
=20
   // Itanium C++ ABI 2.4:
@@ -1507,7 +1730,10 @@
   unsigned FieldAlign =3D FieldInfo.second;
  =20
   // This check is needed for 'long long' in -m32 mode.
-  if (IsMsStruct && (TypeSize > FieldAlign))
+  if (IsMsStruct && (TypeSize > FieldAlign) &&=20
+      (Context.hasSameType(D->getType(),=20
+                           Context.UnsignedLongLongTy)=20
+       || Context.hasSameType(D->getType(), Context.LongLongTy)))
     FieldAlign =3D TypeSize;
=20
   if (ZeroLengthBitfield) {
@@ -1557,18 +1783,21 @@
   UnpackedFieldAlign =3D std::max(UnpackedFieldAlign, D->getMaxAlignment()=
);
=20
   // The maximum field alignment overrides the aligned attribute.
-  if (!MaxFieldAlignment.isZero()) {
+  if (!MaxFieldAlignment.isZero() && FieldSize !=3D 0) {
     unsigned MaxFieldAlignmentInBits =3D Context.toBits(MaxFieldAlignment);
     FieldAlign =3D std::min(FieldAlign, MaxFieldAlignmentInBits);
     UnpackedFieldAlign =3D std::min(UnpackedFieldAlign, MaxFieldAlignmentI=
nBits);
   }
=20
   // Check if we need to add padding to give the field the correct alignme=
nt.
-  if (FieldSize =3D=3D 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > T=
ypeSize)
+  if (FieldSize =3D=3D 0 ||=20
+      (MaxFieldAlignment.isZero() &&
+       (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
     FieldOffset =3D llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
=20
   if (FieldSize =3D=3D 0 ||
-      (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSiz=
e)
+      (MaxFieldAlignment.isZero() &&
+       (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSi=
ze))
     UnpackedFieldOffset =3D llvm::RoundUpToAlignment(UnpackedFieldOffset,
                                                    UnpackedFieldAlign);
=20
@@ -1580,11 +1809,15 @@
   if (!IsMsStruct)
     ZeroLengthBitfield =3D 0;
=20
+  if (ExternalLayout)
+    FieldOffset =3D updateExternalFieldOffset(D, FieldOffset);
+
   // Place this field at the current location.
   FieldOffsets.push_back(FieldOffset);
=20
-  CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
-                    UnpackedFieldAlign, FieldPacked, D);
+  if (!ExternalLayout)
+    CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffse=
t,
+                      UnpackedFieldAlign, FieldPacked, D);
=20
   // Update DataSize to include the last byte containing (part of) the bit=
field.
   if (IsUnion) {
@@ -1606,7 +1839,7 @@
                   Context.toCharUnitsFromBits(UnpackedFieldAlign));
 }
=20
-void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
+void RecordLayoutBuilder::LayoutField(const FieldDecl *D) { =20
   if (D->isBitField()) {
     LayoutBitField(D);
     return;
@@ -1667,7 +1900,7 @@
       ZeroLengthBitfield =3D 0;
     }
=20
-    if (Context.getLangOptions().MSBitfields || IsMsStruct) {
+    if (Context.getLangOpts().MSBitfields || IsMsStruct) {
       // If MS bitfield layout is required, figure out what type is being
       // laid out and align the field to the width of that type.
      =20
@@ -1705,136 +1938,56 @@
   UnpackedFieldOffset =3D=20
     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
=20
-  if (!IsUnion && EmptySubobjects) {
-    // Check if we can place the field at this offset.
-    while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
-      // We couldn't place the field at the offset. Try again at a new off=
set.
-      FieldOffset +=3D FieldAlign;
+  if (ExternalLayout) {
+    FieldOffset =3D Context.toCharUnitsFromBits(
+                    updateExternalFieldOffset(D, Context.toBits(FieldOffse=
t)));
+   =20
+    if (!IsUnion && EmptySubobjects) {
+      // Record the fact that we're placing a field at this offset.
+      bool Allowed =3D EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffs=
et);
+      (void)Allowed;
+      assert(Allowed && "Externally-placed field cannot be placed here"); =
    =20
+    }
+  } else {
+    if (!IsUnion && EmptySubobjects) {
+      // Check if we can place the field at this offset.
+      while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
+        // We couldn't place the field at the offset. Try again at a new o=
ffset.
+        FieldOffset +=3D FieldAlign;
+      }
     }
   }
-
+ =20
   // Place this field at the current location.
   FieldOffsets.push_back(Context.toBits(FieldOffset));
=20
-  CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,=20
-                    Context.toBits(UnpackedFieldOffset),
-                    Context.toBits(UnpackedFieldAlign), FieldPacked, D);
+  if (!ExternalLayout)
+    CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,=20
+                      Context.toBits(UnpackedFieldOffset),
+                      Context.toBits(UnpackedFieldAlign), FieldPacked, D);
=20
   // Reserve space for this field.
   uint64_t FieldSizeInBits =3D Context.toBits(FieldSize);
   if (IsUnion)
-    setSize(std::max(getSizeInBits(), FieldSizeInBits));
+    setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
   else
-    setSize(FieldOffset + FieldSize);
+    setDataSize(FieldOffset + FieldSize);
=20
-  // Update the data size.
-  setDataSize(getSizeInBits());
+  // Update the size.
+  setSize(std::max(getSizeInBits(), getDataSizeInBits()));
=20
   // Remember max struct/class alignment.
   UpdateAlignment(FieldAlign, UnpackedFieldAlign);
 }
=20
-void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
-
-  if (!RD->getNumVBases())
+void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
+  if (ExternalLayout) {
+    setSize(ExternalSize);
     return;
-
-  for (CXXRecordDecl::base_class_const_iterator I =3D RD->vbases_begin(),
-       E =3D RD->vbases_end(); I !=3D E; ++I) {
-
-    const CXXRecordDecl* BaseDecl =3D I->getType()->getAsCXXRecordDecl();
-    const BaseSubobjectInfo* BaseInfo =3D VirtualBaseInfo.lookup(BaseDecl);
-
-    assert(BaseInfo && "Did not find virtual base info!");
-   =20
-    LayoutVirtualBase(BaseInfo);
   }
-}
-
-void RecordLayoutBuilder::MSLayout(const CXXRecordDecl *RD) {
-
-  bool IsVBPtrAddedToLayout =3D false;
-
-  InitializeLayout(RD);
-
-  if (HasVBPtr(RD)) {
-    // If all bases are virtual and the class declares a new virtual funct=
ion,
-    // MSVC builds a vfptr.
-    if (HasNewVirtualFunction(RD)) {
-      AddVPointer();
-    }
-
-    VBPtrOffset =3D getSize();
-    AddVPointer();
-    IsVBPtrAddedToLayout =3D true;
-
-    ComputeBaseSubobjectInfo(RD);
-  } else {
-    LayoutNonVirtualBases(RD);
-  }
-
-  if (RD->getNumVBases() &&
-      !IsVBPtrAddedToLayout) {
-    // Add vbptr.
-    VBPtrOffset =3D getSize();
-    AddVPointer();
-  }
-
-  LayoutFields(RD);
-
-  NonVirtualSize =3D Context.toCharUnitsFromBits(
-                           llvm::RoundUpToAlignment(getSizeInBits(),
-                           Context.getTargetInfo().getCharAlign()));
-  NonVirtualAlignment =3D Alignment;
-
-  if (NonVirtualSize !=3D NonVirtualSize.RoundUpToAlignment(Alignment)) {
-    CharUnits AlignMember =3D=20
-      NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
-
-    setSize(getSize() + AlignMember);
-    setDataSize(getSize());
-
-    NonVirtualSize =3D Context.toCharUnitsFromBits(
-                             llvm::RoundUpToAlignment(getSizeInBits(),
-                             Context.getTargetInfo().getCharAlign()));
-  }
-
-  MSLayoutVirtualBases(RD);
-
-  VisitedVirtualBases.clear();
-
-  // Finally, round the size of the total struct up to the alignment of the
-  // struct itself.
-  if (!RD->getNumVBases())
-    FinishLayout(RD);
-
-#ifndef NDEBUG
-  // Check that we have base offsets for all bases.
-  for (CXXRecordDecl::base_class_const_iterator I =3D RD->bases_begin(),
-    E =3D RD->bases_end(); I !=3D E; ++I) {
-      if (I->isVirtual())
-        continue;
-
-      const CXXRecordDecl *BaseDecl =3D
-        cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
-
-      assert(Bases.count(BaseDecl) && "Did not find base offset!");
-  }
-
-  // And all virtual bases.
-  for (CXXRecordDecl::base_class_const_iterator I =3D RD->vbases_begin(),
-    E =3D RD->vbases_end(); I !=3D E; ++I) {
-      const CXXRecordDecl *BaseDecl =3D
-        cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
-
-      assert(VBases.count(BaseDecl) && "Did not find base offset!");
-  }
-#endif
-}
-
-void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
+ =20
   // In C++, records cannot be of size 0.
-  if (Context.getLangOptions().CPlusPlus && getSizeInBits() =3D=3D 0) {
+  if (Context.getLangOpts().CPlusPlus && getSizeInBits() =3D=3D 0) {
     if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(D)) {
       // Compatibility with gcc requires a class (pod or non-pod)
       // which is not empty but of size 0; such as having fields of
@@ -1845,6 +1998,13 @@
     else
       setSize(CharUnits::One());
   }
+
+  // MSVC doesn't round up to the alignment of the record with virtual bas=
es.
+  if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(D)) {
+    if (isMicrosoftCXXABI() && RD->getNumVBases())
+      return;
+  }
+
   // Finally, round the size of the record up to the alignment of the
   // record itself.
   uint64_t UnpaddedSize =3D getSizeInBits() - UnfilledBitsInLastByte;
@@ -1881,8 +2041,9 @@
=20
 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
                                           CharUnits UnpackedNewAlignment) {
-  // The alignment is not modified when using 'mac68k' alignment.
-  if (IsMac68kAlign)
+  // The alignment is not modified when using 'mac68k' alignment or when
+  // we have an externally-supplied layout that also provides overall alig=
nment.
+  if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
     return;
=20
   if (NewAlignment > Alignment) {
@@ -1898,6 +2059,25 @@
   }
 }
=20
+uint64_t
+RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,=20
+                                               uint64_t ComputedOffset) {
+  assert(ExternalFieldOffsets.find(Field) !=3D ExternalFieldOffsets.end() =
&&
+         "Field does not have an external offset");
+ =20
+  uint64_t ExternalFieldOffset =3D ExternalFieldOffsets[Field];
+ =20
+  if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
+    // The externally-supplied field offset is before the field offset we
+    // computed. Assume that the structure is packed.
+    Alignment =3D CharUnits::fromQuantity(1);
+    InferAlignment =3D false;
+  }
+ =20
+  // Use the externally-supplied field offset.
+  return ExternalFieldOffset;
+}
+
 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
                                             uint64_t UnpaddedOffset,
                                             uint64_t UnpackedOffset,
@@ -2007,6 +2187,10 @@
   // as soon as we begin to parse the definition.  That definition is
   // not a complete definition (which is what isDefinition() tests)
   // until we *finish* parsing the definition.
+
+  if (D->hasExternalLexicalStorage() && !D->getDefinition())
+    getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
+   =20
   D =3D D->getDefinition();
   assert(D && "Cannot get layout of forward declarations!");
   assert(D->isCompleteDefinition() && "Cannot layout type before complete!=
");
@@ -2021,36 +2205,21 @@
=20
   if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(D)) {
     EmptySubobjectMap EmptySubobjects(*this, RD);
+    RecordLayoutBuilder Builder(*this, &EmptySubobjects);
+    Builder.Layout(RD);
=20
-    llvm::OwningPtr<RecordLayoutBuilder> Builder;
-    CharUnits TargetAlign =3D CharUnits::One();
-
-    Builder.reset(new RecordLayoutBuilder(*this,
-                                          &EmptySubobjects,
-                                          TargetAlign));
-
-    // Recover resources if we crash before exiting this method.
-    llvm::CrashRecoveryContextCleanupRegistrar<RecordLayoutBuilder>
-      RecordBuilderCleanup(Builder.get());
-   =20
-    Builder->Layout(RD);
-
-    TargetAlign =3D Builder->getAligment();
-   =20
-    if (getTargetInfo().getCXXABI() =3D=3D CXXABI_Microsoft &&
-        TargetAlign.getQuantity() > 4) {
-      // MSVC rounds the vtable pointer to the struct alignment in what mu=
st
-      // be a multi-pass operation. For now, let the builder figure out the
-      // alignment and recalculate the layout once its known.
-      Builder.reset(new RecordLayoutBuilder(*this,
-                                            &EmptySubobjects,
-                                            TargetAlign));
-
-      Builder->Layout(RD);
-
-      // Recover resources if we crash before exiting this method.
-      llvm::CrashRecoveryContextCleanupRegistrar<RecordLayoutBuilder>
-        RecordBuilderCleanup(Builder.get());
+    // MSVC gives the vb-table pointer an alignment equal to that of
+    // the non-virtual part of the structure.  That's an inherently
+    // multi-pass operation.  If our first pass doesn't give us
+    // adequate alignment, try again with the specified minimum
+    // alignment.  This is *much* more maintainable than computing the
+    // alignment in advance in a separately-coded pass; it's also
+    // significantly more efficient in the common case where the
+    // vb-table doesn't need extra padding.
+    if (Builder.VBPtrOffset !=3D CharUnits::fromQuantity(-1) &&
+        (Builder.VBPtrOffset % Builder.NonVirtualAlignment) !=3D 0) {
+      Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
+      Builder.Layout(RD);
     }
=20
     // FIXME: This is not always correct. See the part about bitfields at
@@ -2058,30 +2227,30 @@
     // FIXME: IsPODForThePurposeOfLayout should be stored in the record la=
yout.
     // This does not affect the calculations of MSVC layouts
     bool IsPODForThePurposeOfLayout =3D=20
-      (getTargetInfo().getCXXABI() =3D=3D CXXABI_Microsoft) ||
-      cast<CXXRecordDecl>(D)->isPOD();
+      (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
=20
     // FIXME: This should be done in FinalizeLayout.
     CharUnits DataSize =3D
-      IsPODForThePurposeOfLayout ? Builder->getSize() : Builder->getDataSi=
ze();
+      IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize=
();
     CharUnits NonVirtualSize =3D=20
-      IsPODForThePurposeOfLayout ? DataSize : Builder->NonVirtualSize;
+      IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
=20
     NewEntry =3D
-      new (*this) ASTRecordLayout(*this, Builder->getSize(),=20
-                                  Builder->Alignment,
-                                  Builder->GetVBPtrOffset(),
+      new (*this) ASTRecordLayout(*this, Builder.getSize(),=20
+                                  Builder.Alignment,
+                                  Builder.VFPtrOffset,
+                                  Builder.VBPtrOffset,
                                   DataSize,=20
-                                  Builder->FieldOffsets.data(),
-                                  Builder->FieldOffsets.size(),
+                                  Builder.FieldOffsets.data(),
+                                  Builder.FieldOffsets.size(),
                                   NonVirtualSize,
-                                  Builder->NonVirtualAlignment,
+                                  Builder.NonVirtualAlignment,
                                   EmptySubobjects.SizeOfLargestEmptySubobj=
ect,
-                                  Builder->PrimaryBase,
-                                  Builder->PrimaryBaseIsVirtual,
-                                  Builder->Bases, Builder->VBases);
+                                  Builder.PrimaryBase,
+                                  Builder.PrimaryBaseIsVirtual,
+                                  Builder.Bases, Builder.VBases);
   } else {
-    RecordLayoutBuilder Builder(*this, /*EmptySubobjects=3D*/0, CharUnits:=
:One());
+    RecordLayoutBuilder Builder(*this, /*EmptySubobjects=3D*/0);
     Builder.Layout(D);
=20
     NewEntry =3D
@@ -2094,9 +2263,9 @@
=20
   ASTRecordLayouts[D] =3D NewEntry;
=20
-  if (getLangOptions().DumpRecordLayouts) {
+  if (getLangOpts().DumpRecordLayouts) {
     llvm::errs() << "\n*** Dumping AST Record Layout\n";
-    DumpRecordLayout(D, llvm::errs());
+    DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimpl=
e);
   }
=20
   return *NewEntry;
@@ -2113,6 +2282,28 @@
   return Entry;
 }
=20
+static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
+  const ASTRecordLayout &Layout =3D C.getASTRecordLayout(FD->getParent());
+  return Layout.getFieldOffset(FD->getFieldIndex());
+}
+
+uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
+  uint64_t OffsetInBits;
+  if (const FieldDecl *FD =3D dyn_cast<FieldDecl>(VD)) {
+    OffsetInBits =3D ::getFieldOffset(*this, FD);
+  } else {
+    const IndirectFieldDecl *IFD =3D cast<IndirectFieldDecl>(VD);
+
+    OffsetInBits =3D 0;
+    for (IndirectFieldDecl::chain_iterator CI =3D IFD->chain_begin(),
+                                           CE =3D IFD->chain_end();
+         CI !=3D CE; ++CI)
+      OffsetInBits +=3D ::getFieldOffset(*this, cast<FieldDecl>(*CI));
+  }
+
+  return OffsetInBits;
+}
+
 /// getObjCLayout - Get or compute information about the layout of the
 /// given interface.
 ///
@@ -2121,7 +2312,11 @@
 const ASTRecordLayout &
 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
                           const ObjCImplementationDecl *Impl) const {
-  assert(!D->isForwardDecl() && "Invalid interface decl!");
+  // Retrieve the definition
+  if (D->hasExternalLexicalStorage() && !D->getDefinition())
+    getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
+  D =3D D->getDefinition();
+  assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl=
!");
=20
   // Look up this layout, if already laid out, return what we have.
   ObjCContainerDecl *Key =3D
@@ -2140,7 +2335,7 @@
       return getObjCLayout(D, 0);
   }
=20
-  RecordLayoutBuilder Builder(*this, /*EmptySubobjects=3D*/0, CharUnits::O=
ne());
+  RecordLayoutBuilder Builder(*this, /*EmptySubobjects=3D*/0);
   Builder.Layout(D);
=20
   const ASTRecordLayout *NewEntry =3D
@@ -2157,7 +2352,7 @@
=20
 static void PrintOffset(raw_ostream &OS,
                         CharUnits Offset, unsigned IndentLevel) {
-  OS << llvm::format("%4d | ", Offset.getQuantity());
+  OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
   OS.indent(IndentLevel * 2);
 }
=20
@@ -2180,22 +2375,16 @@
   IndentLevel++;
=20
   const CXXRecordDecl *PrimaryBase =3D Layout.getPrimaryBase();
+  bool HasVfptr =3D Layout.getVFPtrOffset() !=3D CharUnits::fromQuantity(-=
1);
   bool HasVbptr =3D Layout.getVBPtrOffset() !=3D CharUnits::fromQuantity(-=
1);
=20
   // Vtable pointer.
-  if (RD->isDynamicClass() && !PrimaryBase) {
+  if (RD->isDynamicClass() && !PrimaryBase &&
+      C.getTargetInfo().getCXXABI() !=3D CXXABI_Microsoft) {
     PrintOffset(OS, Offset, IndentLevel);
     OS << '(' << *RD << " vtable pointer)\n";
   }
  =20
-  if (HasVbptr && !PrimaryBase) {
-    PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
-    OS << '(' << *RD << " vbtable pointer)\n";
-
-    // one vbtable per class
-    HasVbptr =3D false;
-  }
-
   // Dump (non-virtual) bases
   for (CXXRecordDecl::base_class_const_iterator I =3D RD->bases_begin(),
          E =3D RD->bases_end(); I !=3D E; ++I) {
@@ -2213,7 +2402,12 @@
                         Base =3D=3D PrimaryBase ? "(primary base)" : "(bas=
e)",
                         /*IncludeVirtualBases=3D*/false);
   }
-  // vbptr
+
+  // vfptr and vbptr (for Microsoft C++ ABI)
+  if (HasVfptr) {
+    PrintOffset(OS, Offset + Layout.getVFPtrOffset(), IndentLevel);
+    OS << '(' << *RD << " vftable pointer)\n";
+  }
   if (HasVbptr) {
     PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
     OS << '(' << *RD << " vbtable pointer)\n";
@@ -2266,16 +2460,20 @@
 }
=20
 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
-                                  raw_ostream &OS) const {
+                                  raw_ostream &OS,
+                                  bool Simple) const {
   const ASTRecordLayout &Info =3D getASTRecordLayout(RD);
=20
   if (const CXXRecordDecl *CXXRD =3D dyn_cast<CXXRecordDecl>(RD))
-    return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
-                               /*IncludeVirtualBases=3D*/true);
+    if (!Simple)
+      return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
+                                 /*IncludeVirtualBases=3D*/true);
=20
   OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
-  OS << "Record: ";
-  RD->dump();
+  if (!Simple) {
+    OS << "Record: ";
+    RD->dump();
+  }
   OS << "\nLayout: ";
   OS << "<ASTRecordLayout\n";
   OS << "  Size:" << toBits(Info.getSize()) << "\n";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
Stmt.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/Stmt.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/Stmt.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -78,11 +78,9 @@
   ++getStmtInfoTableEntry(s).Counter;
 }
=20
-static bool StatSwitch =3D false;
-
-bool Stmt::CollectingStats(bool Enable) {
-  if (Enable) StatSwitch =3D true;
-  return StatSwitch;
+bool Stmt::StatisticsEnabled =3D false;
+void Stmt::EnableStatistics() {
+  StatisticsEnabled =3D true;
 }
=20
 Stmt *Stmt::IgnoreImplicit() {
@@ -164,7 +162,6 @@
 #include "clang/AST/StmtNodes.inc"
   }
   llvm_unreachable("unknown statement kind!");
-  return child_range();
 }
=20
 SourceRange Stmt::getSourceRange() const {
@@ -177,7 +174,72 @@
 #include "clang/AST/StmtNodes.inc"
   }
   llvm_unreachable("unknown statement kind!");
-  return SourceRange();
+}
+
+// Amusing macro metaprogramming hack: check whether a class provides
+// a more specific implementation of getLocStart() and getLocEnd().
+//
+// See also Expr.cpp:getExprLoc().
+namespace {
+  /// This implementation is used when a class provides a custom
+  /// implementation of getLocStart.
+  template <class S, class T>
+  SourceLocation getLocStartImpl(const Stmt *stmt,
+                                 SourceLocation (T::*v)() const) {
+    return static_cast<const S*>(stmt)->getLocStart();
+  }
+
+  /// This implementation is used when a class doesn't provide a custom
+  /// implementation of getLocStart.  Overload resolution should pick it o=
ver
+  /// the implementation above because it's more specialized according to
+  /// function template partial ordering.
+  template <class S>
+  SourceLocation getLocStartImpl(const Stmt *stmt,
+                                SourceLocation (Stmt::*v)() const) {
+    return static_cast<const S*>(stmt)->getSourceRange().getBegin();
+  }
+
+  /// This implementation is used when a class provides a custom
+  /// implementation of getLocEnd.
+  template <class S, class T>
+  SourceLocation getLocEndImpl(const Stmt *stmt,
+                               SourceLocation (T::*v)() const) {
+    return static_cast<const S*>(stmt)->getLocEnd();
+  }
+
+  /// This implementation is used when a class doesn't provide a custom
+  /// implementation of getLocEnd.  Overload resolution should pick it over
+  /// the implementation above because it's more specialized according to
+  /// function template partial ordering.
+  template <class S>
+  SourceLocation getLocEndImpl(const Stmt *stmt,
+                               SourceLocation (Stmt::*v)() const) {
+    return static_cast<const S*>(stmt)->getSourceRange().getEnd();
+  }
+}
+
+SourceLocation Stmt::getLocStart() const {
+  switch (getStmtClass()) {
+  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
+#define ABSTRACT_STMT(type)
+#define STMT(type, base) \
+  case Stmt::type##Class: \
+    return getLocStartImpl<type>(this, &type::getLocStart);
+#include "clang/AST/StmtNodes.inc"
+  }
+  llvm_unreachable("unknown statement kind");
+}
+
+SourceLocation Stmt::getLocEnd() const {
+  switch (getStmtClass()) {
+  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
+#define ABSTRACT_STMT(type)
+#define STMT(type, base) \
+  case Stmt::type##Class: \
+    return getLocEndImpl<type>(this, &type::getLocEnd);
+#include "clang/AST/StmtNodes.inc"
+  }
+  llvm_unreachable("unknown statement kind");
 }
=20
 void CompoundStmt::setStmts(ASTContext &C, Stmt **Stmts, unsigned NumStmts=
) {
@@ -631,9 +693,9 @@
     return;
   }
  =20
-  SubExprs[VAR] =3D new (C) DeclStmt(DeclGroupRef(V),=20
-                                   V->getSourceRange().getBegin(),
-                                   V->getSourceRange().getEnd());
+  SourceRange VarRange =3D V->getSourceRange();
+  SubExprs[VAR] =3D new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
+                                   VarRange.getEnd());
 }
=20
 ForStmt::ForStmt(ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,=20
@@ -662,9 +724,9 @@
     return;
   }
  =20
-  SubExprs[CONDVAR] =3D new (C) DeclStmt(DeclGroupRef(V),=20
-                                       V->getSourceRange().getBegin(),
-                                       V->getSourceRange().getEnd());
+  SourceRange VarRange =3D V->getSourceRange();
+  SubExprs[CONDVAR] =3D new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegi=
n(),
+                                       VarRange.getEnd());
 }
=20
 SwitchStmt::SwitchStmt(ASTContext &C, VarDecl *Var, Expr *cond)=20
@@ -689,9 +751,9 @@
     return;
   }
  =20
-  SubExprs[VAR] =3D new (C) DeclStmt(DeclGroupRef(V),=20
-                                   V->getSourceRange().getBegin(),
-                                   V->getSourceRange().getEnd());
+  SourceRange VarRange =3D V->getSourceRange();
+  SubExprs[VAR] =3D new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
+                                   VarRange.getEnd());
 }
=20
 Stmt *SwitchCase::getSubStmt() {
@@ -722,10 +784,10 @@
     SubExprs[VAR] =3D 0;
     return;
   }
- =20
-  SubExprs[VAR] =3D new (C) DeclStmt(DeclGroupRef(V),=20
-                                   V->getSourceRange().getBegin(),
-                                   V->getSourceRange().getEnd());
+
+  SourceRange VarRange =3D V->getSourceRange();
+  SubExprs[VAR] =3D new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
+                                   VarRange.getEnd());
 }
=20
 // IndirectGotoStmt
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
StmtDumper.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/StmtDumper.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/StmtDumper.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -112,6 +112,7 @@
       case OK_Ordinary: break;
       case OK_BitField: OS << " bitfield"; break;
       case OK_ObjCProperty: OS << " objcproperty"; break;
+      case OK_ObjCSubscript: OS << " objcsubscript"; break;
       case OK_VectorComponent: OS << " vectorcomponent"; break;
       }
     }
@@ -148,6 +149,7 @@
     void VisitCompoundAssignOperator(CompoundAssignOperator *Node);
     void VisitAddrLabelExpr(AddrLabelExpr *Node);
     void VisitBlockExpr(BlockExpr *Node);
+    void VisitOpaqueValueExpr(OpaqueValueExpr *Node);
=20
     // C++
     void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node);
@@ -167,7 +169,9 @@
     void VisitObjCSelectorExpr(ObjCSelectorExpr *Node);
     void VisitObjCProtocolExpr(ObjCProtocolExpr *Node);
     void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node);
+    void VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node);
     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node);
+    void VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node);
   };
 }
=20
@@ -250,7 +254,7 @@
=20
     std::string Name =3D VD->getNameAsString();
     VD->getType().getAsStringInternal(Name,
-                          PrintingPolicy(VD->getASTContext().getLangOption=
s()));
+                          PrintingPolicy(VD->getASTContext().getLangOpts()=
));
     OS << Name;
=20
     // If this is a vardecl with an initializer, emit it.
@@ -283,10 +287,10 @@
     const char *tn =3D UD->isTypeName() ? "typename " : "";
     OS << '"' << UD->getDeclKindName() << tn;
     UD->getQualifier()->print(OS,
-                        PrintingPolicy(UD->getASTContext().getLangOptions(=
)));
+                        PrintingPolicy(UD->getASTContext().getLangOpts()));
     OS << ";\"";
   } else if (LabelDecl *LD =3D dyn_cast<LabelDecl>(D)) {
-    OS << "label " << LD->getNameAsString();
+    OS << "label " << *LD;
   } else if (StaticAssertDecl *SAD =3D dyn_cast<StaticAssertDecl>(D)) {
     OS << "\"static_assert(\n";
     DumpSubTree(SAD->getAssertExpr());
@@ -425,7 +429,7 @@
=20
 void StmtDumper::VisitCharacterLiteral(CharacterLiteral *Node) {
   DumpExpr(Node);
-  OS << Node->getValue();
+  OS << " " << Node->getValue();
 }
=20
 void StmtDumper::VisitIntegerLiteral(IntegerLiteral *Node) {
@@ -503,8 +507,10 @@
 void StmtDumper::VisitBlockExpr(BlockExpr *Node) {
   DumpExpr(Node);
=20
+  BlockDecl *block =3D Node->getBlockDecl();
+  OS << " decl=3D" << block;
+
   IndentLevel++;
-  BlockDecl *block =3D Node->getBlockDecl();
   if (block->capturesCXXThis()) {
     OS << '\n'; Indent(); OS << "(capture this)";
   }
@@ -515,15 +521,26 @@
     OS << "(capture ";
     if (i->isByRef()) OS << "byref ";
     if (i->isNested()) OS << "nested ";
-    DumpDeclRef(i->getVariable());
+    if (i->getVariable())
+      DumpDeclRef(i->getVariable());
     if (i->hasCopyExpr()) DumpSubTree(i->getCopyExpr());
     OS << ")";
   }
   IndentLevel--;
=20
+  OS << '\n';
   DumpSubTree(block->getBody());
 }
=20
+void StmtDumper::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
+  DumpExpr(Node);
+
+  if (Expr *Source =3D Node->getSourceExpr()) {
+    OS << '\n';
+    DumpSubTree(Source);
+  }
+}
+
 // GNU extensions.
=20
 void StmtDumper::VisitAddrLabelExpr(AddrLabelExpr *Node) {
@@ -580,10 +597,12 @@
 void StmtDumper::VisitExprWithCleanups(ExprWithCleanups *Node) {
   DumpExpr(Node);
   ++IndentLevel;
-  for (unsigned i =3D 0, e =3D Node->getNumTemporaries(); i !=3D e; ++i) {
+  for (unsigned i =3D 0, e =3D Node->getNumObjects(); i !=3D e; ++i) {
     OS << "\n";
     Indent();
-    DumpCXXTemporary(Node->getTemporary(i));
+    OS << "(cleanup ";
+    DumpDeclRef(Node->getObject(i));
+    OS << ")";
   }
   --IndentLevel;
 }
@@ -667,6 +686,40 @@
=20
   if (Node->isSuperReceiver())
     OS << " super";
+
+  OS << " Messaging=3D";
+  if (Node->isMessagingGetter() && Node->isMessagingSetter())
+    OS << "Getter&Setter";
+  else if (Node->isMessagingGetter())
+    OS << "Getter";
+  else if (Node->isMessagingSetter())
+    OS << "Setter";
+}
+
+void StmtDumper::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
+  DumpExpr(Node);
+  if (Node->isArraySubscriptRefExpr())
+    OS << " Kind=3DArraySubscript GetterForArray=3D\"";
+  else
+    OS << " Kind=3DDictionarySubscript GetterForDictionary=3D\"";
+  if (Node->getAtIndexMethodDecl())
+    OS << Node->getAtIndexMethodDecl()->getSelector().getAsString();
+  else
+    OS << "(null)";
+ =20
+  if (Node->isArraySubscriptRefExpr())
+    OS << "\" SetterForArray=3D\"";
+  else
+    OS << "\" SetterForDictionary=3D\"";
+  if (Node->setAtIndexMethodDecl())
+    OS << Node->setAtIndexMethodDecl()->getSelector().getAsString();
+  else
+    OS << "(null)";
+}
+
+void StmtDumper::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
+  DumpExpr(Node);
+  OS << " " << (Node->getValue() ? "__objc_yes" : "__objc_no");
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
StmtPrinter.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/StmtPrinter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/StmtPrinter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -17,9 +17,9 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/PrettyPrinter.h"
-#include "llvm/Support/Format.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
+#include "llvm/ADT/SmallString.h"
 using namespace clang;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -305,6 +305,22 @@
   Indent() << "}\n";
 }
=20
+void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) {
+  Indent();
+  if (Node->isIfExists())
+    OS << "__if_exists (";
+  else
+    OS << "__if_not_exists (";
+ =20
+  if (NestedNameSpecifier *Qualifier
+        =3D Node->getQualifierLoc().getNestedNameSpecifier())
+    Qualifier->print(OS, Policy);
+ =20
+  OS << Node->getNameInfo() << ") ";
+ =20
+  PrintRawCompoundStmt(Node->getSubStmt());
+}
+
 void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
   Indent() << "goto " << Node->getLabel()->getName() << ";\n";
 }
@@ -528,6 +544,8 @@
 void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
   if (NestedNameSpecifier *Qualifier =3D Node->getQualifier())
     Qualifier->print(OS, Policy);
+  if (Node->hasTemplateKeyword())
+    OS << "template ";
   OS << Node->getNameInfo();
   if (Node->hasExplicitTemplateArgs())
     OS << TemplateSpecializationType::PrintTemplateArgumentList(
@@ -540,6 +558,8 @@
                                            DependentScopeDeclRefExpr *Node=
) {
   if (NestedNameSpecifier *Qualifier =3D Node->getQualifier())
     Qualifier->print(OS, Policy);
+  if (Node->hasTemplateKeyword())
+    OS << "template ";
   OS << Node->getNameInfo();
   if (Node->hasExplicitTemplateArgs())
     OS << TemplateSpecializationType::PrintTemplateArgumentList(
@@ -551,6 +571,8 @@
 void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
   if (Node->getQualifier())
     Node->getQualifier()->print(OS, Policy);
+  if (Node->hasTemplateKeyword())
+    OS << "template ";
   OS << Node->getNameInfo();
   if (Node->hasExplicitTemplateArgs())
     OS << TemplateSpecializationType::PrintTemplateArgumentList(
@@ -581,6 +603,14 @@
     OS << Node->getExplicitProperty()->getName();
 }
=20
+void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
+ =20
+  PrintExpr(Node->getBaseExpr());
+  OS << "[";
+  PrintExpr(Node->getKeyExpr());
+  OS << "]";
+}
+
 void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
   switch (Node->getIdentType()) {
     default:
@@ -644,7 +674,8 @@
     if (value < 256 && isprint(value)) {
       OS << "'" << (char)value << "'";
     } else if (value < 256) {
-      OS << "'\\x" << llvm::format("%x", value) << "'";
+      OS << "'\\x";
+      OS.write_hex(value) << "'";
     } else {
       // FIXME what to really do here?
       OS << value;
@@ -659,16 +690,23 @@
   // Emit suffixes.  Integer literals are always a builtin integer type.
   switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
   default: llvm_unreachable("Unexpected type for integer literal!");
+  // FIXME: The Short and UShort cases are to handle cases where a short
+  // integeral literal is formed during template instantiation.  They shou=
ld
+  // be removed when template instantiation no longer needs integer litera=
ls.
+  case BuiltinType::Short:
+  case BuiltinType::UShort:
   case BuiltinType::Int:       break; // no suffix.
   case BuiltinType::UInt:      OS << 'U'; break;
   case BuiltinType::Long:      OS << 'L'; break;
   case BuiltinType::ULong:     OS << "UL"; break;
   case BuiltinType::LongLong:  OS << "LL"; break;
   case BuiltinType::ULongLong: OS << "ULL"; break;
+  case BuiltinType::Int128:    OS << "i128"; break;
+  case BuiltinType::UInt128:   OS << "Ui128"; break;
   }
 }
 void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
-  llvm::SmallString<16> Str;
+  SmallString<16> Str;
   Node->getValue().toString(Str);
   OS << Str;
 }
@@ -687,22 +725,74 @@
   case StringLiteral::UTF32: OS << 'U'; break;
   }
   OS << '"';
+  static char Hex[] =3D "0123456789ABCDEF";
=20
-  // FIXME: this doesn't print wstrings right.
-  StringRef StrData =3D Str->getString();
-  for (StringRef::iterator I =3D StrData.begin(), E =3D StrData.end();=20
-                                                             I !=3D E; ++I=
) {
-    unsigned char Char =3D *I;
+  unsigned LastSlashX =3D Str->getLength();
+  for (unsigned I =3D 0, N =3D Str->getLength(); I !=3D N; ++I) {
+    switch (uint32_t Char =3D Str->getCodeUnit(I)) {
+    default:
+      // FIXME: Convert UTF-8 back to codepoints before rendering.
=20
-    switch (Char) {
-    default:
-      if (isprint(Char))
+      // Convert UTF-16 surrogate pairs back to codepoints before renderin=
g.
+      // Leave invalid surrogates alone; we'll use \x for those.
+      if (Str->getKind() =3D=3D StringLiteral::UTF16 && I !=3D N - 1 &&
+          Char >=3D 0xd800 && Char <=3D 0xdbff) {
+        uint32_t Trail =3D Str->getCodeUnit(I + 1);
+        if (Trail >=3D 0xdc00 && Trail <=3D 0xdfff) {
+          Char =3D 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
+          ++I;
+        }
+      }
+
+      if (Char > 0xff) {
+        // If this is a wide string, output characters over 0xff using \x
+        // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char=
 is a
+        // codepoint: use \x escapes for invalid codepoints.
+        if (Str->getKind() =3D=3D StringLiteral::Wide ||
+            (Char >=3D 0xd800 && Char <=3D 0xdfff) || Char >=3D 0x110000) {
+          // FIXME: Is this the best way to print wchar_t?
+          OS << "\\x";
+          int Shift =3D 28;
+          while ((Char >> Shift) =3D=3D 0)
+            Shift -=3D 4;
+          for (/**/; Shift >=3D 0; Shift -=3D 4)
+            OS << Hex[(Char >> Shift) & 15];
+          LastSlashX =3D I;
+          break;
+        }
+
+        if (Char > 0xffff)
+          OS << "\\U00"
+             << Hex[(Char >> 20) & 15]
+             << Hex[(Char >> 16) & 15];
+        else
+          OS << "\\u";
+        OS << Hex[(Char >> 12) & 15]
+           << Hex[(Char >>  8) & 15]
+           << Hex[(Char >>  4) & 15]
+           << Hex[(Char >>  0) & 15];
+        break;
+      }
+
+      // If we used \x... for the previous character, and this character i=
s a
+      // hexadecimal digit, prevent it being slurped as part of the \x.
+      if (LastSlashX + 1 =3D=3D I) {
+        switch (Char) {
+          case '0': case '1': case '2': case '3': case '4':
+          case '5': case '6': case '7': case '8': case '9':
+          case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
+          case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
+            OS << "\"\"";
+        }
+      }
+
+      if (Char <=3D 0xff && isprint(Char))
         OS << (char)Char;
       else  // Output anything hard as an octal escape.
         OS << '\\'
-        << (char)('0'+ ((Char >> 6) & 7))
-        << (char)('0'+ ((Char >> 3) & 7))
-        << (char)('0'+ ((Char >> 0) & 7));
+           << (char)('0' + ((Char >> 6) & 7))
+           << (char)('0' + ((Char >> 3) & 7))
+           << (char)('0' + ((Char >> 0) & 7));
       break;
     // Handle some common non-printable cases to make dumps prettier.
     case '\\': OS << "\\\\"; break;
@@ -849,9 +939,9 @@
   OS << (Node->isArrow() ? "->" : ".");
   if (NestedNameSpecifier *Qualifier =3D Node->getQualifier())
     Qualifier->print(OS, Policy);
-
+  if (Node->hasTemplateKeyword())
+    OS << "template ";
   OS << Node->getMemberNameInfo();
-
   if (Node->hasExplicitTemplateArgs())
     OS << TemplateSpecializationType::PrintTemplateArgumentList(
                                                     Node->getTemplateArgs(=
),
@@ -1011,52 +1101,42 @@
   OS << ")";
 }
=20
+void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
+  PrintExpr(Node->getSyntacticForm());
+}
+
 void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
   const char *Name =3D 0;
   switch (Node->getOp()) {
-    case AtomicExpr::Load:
-      Name =3D "__atomic_load(";
-      break;
-    case AtomicExpr::Store:
-      Name =3D "__atomic_store(";
-      break;
-    case AtomicExpr::CmpXchgStrong:
-      Name =3D "__atomic_compare_exchange_strong(";
-      break;
-    case AtomicExpr::CmpXchgWeak:
-      Name =3D "__atomic_compare_exchange_weak(";
-      break;
-    case AtomicExpr::Xchg:
-      Name =3D "__atomic_exchange(";
-      break;
-    case AtomicExpr::Add:
-      Name =3D "__atomic_fetch_add(";
-      break;
-    case AtomicExpr::Sub:
-      Name =3D "__atomic_fetch_sub(";
-      break;
-    case AtomicExpr::And:
-      Name =3D "__atomic_fetch_and(";
-      break;
-    case AtomicExpr::Or:
-      Name =3D "__atomic_fetch_or(";
-      break;
-    case AtomicExpr::Xor:
-      Name =3D "__atomic_fetch_xor(";
-      break;
+#define BUILTIN(ID, TYPE, ATTRS)
+#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
+  case AtomicExpr::AO ## ID: \
+    Name =3D #ID "("; \
+    break;
+#include "clang/Basic/Builtins.def"
   }
   OS << Name;
+
+  // AtomicExpr stores its subexpressions in a permuted order.
   PrintExpr(Node->getPtr());
   OS << ", ";
-  if (Node->getOp() !=3D AtomicExpr::Load) {
+  if (Node->getOp() !=3D AtomicExpr::AO__c11_atomic_load &&
+      Node->getOp() !=3D AtomicExpr::AO__atomic_load_n) {
     PrintExpr(Node->getVal1());
     OS << ", ";
   }
-  if (Node->isCmpXChg()) {
+  if (Node->getOp() =3D=3D AtomicExpr::AO__atomic_exchange ||
+      Node->isCmpXChg()) {
     PrintExpr(Node->getVal2());
     OS << ", ";
   }
-  PrintExpr(Node->getOrder());
+  if (Node->getOp() =3D=3D AtomicExpr::AO__atomic_compare_exchange ||
+      Node->getOp() =3D=3D AtomicExpr::AO__atomic_compare_exchange_n) {
+    PrintExpr(Node->getWeak());
+    OS << ", ";
+  }
+  if (Node->getOp() !=3D AtomicExpr::AO__c11_atomic_init)
+    PrintExpr(Node->getOrder());
   if (Node->isCmpXChg()) {
     OS << ", ";
     PrintExpr(Node->getOrderFail());
@@ -1165,6 +1245,39 @@
   OS << ")";
 }
=20
+void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
+  switch (Node->getLiteralOperatorKind()) {
+  case UserDefinedLiteral::LOK_Raw:
+    OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getStrin=
g();
+    break;
+  case UserDefinedLiteral::LOK_Template: {
+    DeclRefExpr *DRE =3D cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCas=
ts());
+    const TemplateArgumentList *Args =3D
+      cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
+    assert(Args);
+    const TemplateArgument &Pack =3D Args->get(0);
+    for (TemplateArgument::pack_iterator I =3D Pack.pack_begin(),
+                                         E =3D Pack.pack_end(); I !=3D E; =
++I) {
+      char C =3D (char)I->getAsIntegral()->getZExtValue();
+      OS << C;
+    }
+    break;
+  }
+  case UserDefinedLiteral::LOK_Integer: {
+    // Print integer literal without suffix.
+    IntegerLiteral *Int =3D cast<IntegerLiteral>(Node->getCookedLiteral());
+    OS << Int->getValue().toString(10, /*isSigned*/false);
+    break;
+  }
+  case UserDefinedLiteral::LOK_Floating:
+  case UserDefinedLiteral::LOK_String:
+  case UserDefinedLiteral::LOK_Character:
+    PrintExpr(Node->getCookedLiteral());
+    break;
+  }
+  OS << Node->getUDSuffix()->getName();
+}
+
 void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
   OS << (Node->getValue() ? "true" : "false");
 }
@@ -1214,6 +1327,98 @@
   OS << ")";
 }
=20
+void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
+  OS << '[';
+  bool NeedComma =3D false;
+  switch (Node->getCaptureDefault()) {
+  case LCD_None:
+    break;
+
+  case LCD_ByCopy:
+    OS << '=3D';
+    NeedComma =3D true;
+    break;
+
+  case LCD_ByRef:
+    OS << '&';
+    NeedComma =3D true;
+    break;
+  }
+  for (LambdaExpr::capture_iterator C =3D Node->explicit_capture_begin(),
+                                 CEnd =3D Node->explicit_capture_end();
+       C !=3D CEnd;
+       ++C) {
+    if (NeedComma)
+      OS << ", ";
+    NeedComma =3D true;
+
+    switch (C->getCaptureKind()) {
+    case LCK_This:
+      OS << "this";
+      break;
+
+    case LCK_ByRef:
+      if (Node->getCaptureDefault() !=3D LCD_ByRef)
+        OS << '&';
+      OS << C->getCapturedVar()->getName();
+      break;
+
+    case LCK_ByCopy:
+      if (Node->getCaptureDefault() !=3D LCD_ByCopy)
+        OS << '=3D';
+      OS << C->getCapturedVar()->getName();
+      break;
+    }
+  }
+  OS << ']';
+
+  if (Node->hasExplicitParameters()) {
+    OS << " (";
+    CXXMethodDecl *Method =3D Node->getCallOperator();
+    NeedComma =3D false;
+    for (CXXMethodDecl::param_iterator P =3D Method->param_begin(),
+                                    PEnd =3D Method->param_end();
+         P !=3D PEnd; ++P) {
+      if (NeedComma) {
+        OS << ", ";
+      } else {
+        NeedComma =3D true;
+      }
+      std::string ParamStr =3D (*P)->getNameAsString();
+      (*P)->getOriginalType().getAsStringInternal(ParamStr, Policy);
+      OS << ParamStr;
+    }
+    if (Method->isVariadic()) {
+      if (NeedComma)
+        OS << ", ";
+      OS << "...";
+    }
+    OS << ')';
+
+    if (Node->isMutable())
+      OS << " mutable";
+
+    const FunctionProtoType *Proto
+      =3D Method->getType()->getAs<FunctionProtoType>();
+    {
+      std::string ExceptionSpec;
+      Proto->printExceptionSpecification(ExceptionSpec, Policy);
+      OS << ExceptionSpec;
+    }
+
+    // FIXME: Attributes
+
+    // Print the trailing return type if it was specified in the source.
+    if (Node->hasExplicitResultType())
+      OS << " -> " << Proto->getResultType().getAsString(Policy);
+  }
+
+  // Print the body.
+  CompoundStmt *Body =3D Node->getBody();
+  OS << ' ';
+  PrintStmt(Body);
+}
+
 void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node=
) {
   if (TypeSourceInfo *TSInfo =3D Node->getTypeSourceInfo())
     OS << TSInfo->getType().getAsString(Policy) << "()";
@@ -1249,17 +1454,13 @@
   if (E->isParenTypeId())
     OS << ")";
=20
-  if (E->hasInitializer()) {
-    OS << "(";
-    unsigned NumCons =3D E->getNumConstructorArgs();
-    if (NumCons > 0) {
-      PrintExpr(E->getConstructorArg(0));
-      for (unsigned i =3D 1; i < NumCons; ++i) {
-        OS << ", ";
-        PrintExpr(E->getConstructorArg(i));
-      }
-    }
-    OS << ")";
+  CXXNewExpr::InitializationStyle InitStyle =3D E->getInitializationStyle(=
);
+  if (InitStyle) {
+    if (InitStyle =3D=3D CXXNewExpr::CallInit)
+      OS << "(";
+    PrintExpr(E->getInitializer());
+    if (InitStyle =3D=3D CXXNewExpr::CallInit)
+      OS << ")";
   }
 }
=20
@@ -1329,12 +1530,9 @@
   }
   if (NestedNameSpecifier *Qualifier =3D Node->getQualifier())
     Qualifier->print(OS, Policy);
-  else if (Node->hasExplicitTemplateArgs())
-    // FIXME: Track use of "template" keyword explicitly?
+  if (Node->hasTemplateKeyword())
     OS << "template ";
-
   OS << Node->getMemberNameInfo();
-
   if (Node->hasExplicitTemplateArgs()) {
     OS << TemplateSpecializationType::PrintTemplateArgumentList(
                                                     Node->getTemplateArgs(=
),
@@ -1350,11 +1548,9 @@
   }
   if (NestedNameSpecifier *Qualifier =3D Node->getQualifier())
     Qualifier->print(OS, Policy);
-
-  // FIXME: this might originally have been written with 'template'
-
+  if (Node->hasTemplateKeyword())
+    OS << "template ";
   OS << Node->getMemberNameInfo();
-
   if (Node->hasExplicitTemplateArgs()) {
     OS << TemplateSpecializationType::PrintTemplateArgumentList(
                                                     Node->getTemplateArgs(=
),
@@ -1382,6 +1578,7 @@
   case UTT_IsConst:                 return "__is_const";
   case UTT_IsEmpty:               return "__is_empty";
   case UTT_IsEnum:                return "__is_enum";
+  case UTT_IsFinal:                 return "__is_final";
   case UTT_IsFloatingPoint:         return "__is_floating_point";
   case UTT_IsFunction:              return "__is_function";
   case UTT_IsFundamental:           return "__is_fundamental";
@@ -1412,15 +1609,23 @@
=20
 static const char *getTypeTraitName(BinaryTypeTrait BTT) {
   switch (BTT) {
-  case BTT_IsBaseOf:         return "__is_base_of";
-  case BTT_IsConvertible:    return "__is_convertible";
-  case BTT_IsSame:           return "__is_same";
-  case BTT_TypeCompatible:   return "__builtin_types_compatible_p";
-  case BTT_IsConvertibleTo:  return "__is_convertible_to";
+  case BTT_IsBaseOf:              return "__is_base_of";
+  case BTT_IsConvertible:         return "__is_convertible";
+  case BTT_IsSame:                return "__is_same";
+  case BTT_TypeCompatible:        return "__builtin_types_compatible_p";
+  case BTT_IsConvertibleTo:       return "__is_convertible_to";
+  case BTT_IsTriviallyAssignable: return "__is_trivially_assignable";
   }
   llvm_unreachable("Binary type trait not covered by switch");
 }
=20
+static const char *getTypeTraitName(TypeTrait TT) {
+  switch (TT) {
+  case clang::TT_IsTriviallyConstructible:return "__is_trivially_construct=
ible";
+  }
+  llvm_unreachable("Type trait not covered by switch");
+}
+
 static const char *getTypeTraitName(ArrayTypeTrait ATT) {
   switch (ATT) {
   case ATT_ArrayRank:        return "__array_rank";
@@ -1448,6 +1653,16 @@
      << E->getRhsType().getAsString(Policy) << ")";
 }
=20
+void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
+  OS << getTypeTraitName(E->getTrait()) << "(";
+  for (unsigned I =3D 0, N =3D E->getNumArgs(); I !=3D N; ++I) {
+    if (I > 0)
+      OS << ", ";
+    OS << E->getArg(I)->getType().getAsString(Policy);
+  }
+  OS << ")";
+}
+
 void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
   OS << getTypeTraitName(E->getTrait()) << "("
      << E->getQueriedType().getAsString(Policy) << ")";
@@ -1471,12 +1686,12 @@
 }
=20
 void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
-  OS << "sizeof...(" << E->getPack()->getNameAsString() << ")";
+  OS << "sizeof...(" << *E->getPack() << ")";
 }
=20
 void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
                                        SubstNonTypeTemplateParmPackExpr *N=
ode) {
-  OS << Node->getParameterPack()->getNameAsString();
+  OS << *Node->getParameterPack();
 }
=20
 void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
@@ -1495,6 +1710,41 @@
   VisitStringLiteral(Node->getString());
 }
=20
+void StmtPrinter::VisitObjCNumericLiteral(ObjCNumericLiteral *E) {
+  OS << "@";
+  Visit(E->getNumber());
+}
+
+void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
+  OS << "@[ ";
+  StmtRange ch =3D E->children();
+  if (ch.first !=3D ch.second) {
+    while (1) {
+      Visit(*ch.first);
+      ++ch.first;
+      if (ch.first =3D=3D ch.second) break;
+      OS << ", ";
+    }
+  }
+  OS << " ]";
+}
+
+void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
+  OS << "@{ ";
+  for (unsigned I =3D 0, N =3D E->getNumElements(); I !=3D N; ++I) {
+    if (I > 0)
+      OS << ", ";
+   =20
+    ObjCDictionaryElement Element =3D E->getKeyValueElement(I);
+    Visit(Element.Key);
+    OS << " : ";
+    Visit(Element.Value);
+    if (Element.isPackExpansion())
+      OS << "...";
+  }
+  OS << " }";
+}
+
 void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
   OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
 }
@@ -1545,6 +1795,10 @@
   OS << "]";
 }
=20
+void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
+  OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
+}
+
 void
 StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr =
*E) {
   PrintExpr(E->getSubExpr());
@@ -1585,12 +1839,10 @@
   }
 }
=20
-void StmtPrinter::VisitBlockDeclRefExpr(BlockDeclRefExpr *Node) {
-  OS << *Node->getDecl();
+void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {=20
+  PrintExpr(Node->getSourceExpr());
 }
=20
-void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {}
-
 void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
   OS << "__builtin_astype(";
   PrintExpr(Node->getSrcExpr());
@@ -1604,7 +1856,7 @@
=20
 void Stmt::dumpPretty(ASTContext& Context) const {
   printPretty(llvm::errs(), Context, 0,
-              PrintingPolicy(Context.getLangOptions()));
+              PrintingPolicy(Context.getLangOpts()));
 }
=20
 void Stmt::printPretty(raw_ostream &OS, ASTContext& Context,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
StmtProfile.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/StmtProfile.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/StmtProfile.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -69,8 +69,12 @@
=20
 void StmtProfiler::VisitStmt(const Stmt *S) {
   ID.AddInteger(S->getStmtClass());
-  for (Stmt::const_child_range C =3D S->children(); C; ++C)
-    Visit(*C);
+  for (Stmt::const_child_range C =3D S->children(); C; ++C) {
+    if (*C)
+      Visit(*C);
+    else
+      ID.AddInteger(0);
+  }
 }
=20
 void StmtProfiler::VisitDeclStmt(const DeclStmt *S) {
@@ -182,6 +186,13 @@
   VisitStmt(S);
 }
=20
+void StmtProfiler::VisitMSDependentExistsStmt(const MSDependentExistsStmt =
*S) {
+  VisitStmt(S);
+  ID.AddBoolean(S->isIfExists());
+  VisitNestedNameSpecifier(S->getQualifierLoc().getNestedNameSpecifier());
+  VisitName(S->getNameInfo().getName());
+}
+
 void StmtProfiler::VisitSEHTryStmt(const SEHTryStmt *S) {
   VisitStmt(S);
 }
@@ -268,7 +279,7 @@
=20
 void StmtProfiler::VisitStringLiteral(const StringLiteral *S) {
   VisitExpr(S);
-  ID.AddString(S->getString());
+  ID.AddString(S->getBytes());
   ID.AddInteger(S->getKind());
 }
=20
@@ -449,13 +460,6 @@
   VisitDecl(S->getBlockDecl());
 }
=20
-void StmtProfiler::VisitBlockDeclRefExpr(const BlockDeclRefExpr *S) {
-  VisitExpr(S);
-  VisitDecl(S->getDecl());
-  ID.AddBoolean(S->isByRef());
-  ID.AddBoolean(S->isConstQualAdded());
-}
-
 void StmtProfiler::VisitGenericSelectionExpr(const GenericSelectionExpr *S=
) {
   VisitExpr(S);
   for (unsigned i =3D 0; i !=3D S->getNumAssocs(); ++i) {
@@ -468,6 +472,15 @@
   }
 }
=20
+void StmtProfiler::VisitPseudoObjectExpr(const PseudoObjectExpr *S) {
+  VisitExpr(S);
+  for (PseudoObjectExpr::const_semantics_iterator
+         i =3D S->semantics_begin(), e =3D S->semantics_end(); i !=3D e; +=
+i)
+    // Normally, we would not profile the source expressions of OVEs.
+    if (const OpaqueValueExpr *OVE =3D dyn_cast<OpaqueValueExpr>(*i))
+      Visit(OVE->getSourceExpr());
+}
+
 void StmtProfiler::VisitAtomicExpr(const AtomicExpr *S) {
   VisitExpr(S);
   ID.AddInteger(S->getOp());
@@ -487,7 +500,6 @@
   case OO_Conditional:
   case NUM_OVERLOADED_OPERATORS:
     llvm_unreachable("Invalid operator call kind");
-    return Stmt::ArraySubscriptExprClass;
      =20
   case OO_Plus:
     if (S->getNumArgs() =3D=3D 1) {
@@ -719,6 +731,10 @@
   VisitCXXNamedCastExpr(S);
 }
=20
+void StmtProfiler::VisitUserDefinedLiteral(const UserDefinedLiteral *S) {
+  VisitCallExpr(S);
+}
+
 void StmtProfiler::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *S) {
   VisitExpr(S);
   ID.AddBoolean(S->getValue());
@@ -775,6 +791,24 @@
 }
=20
 void
+StmtProfiler::VisitLambdaExpr(const LambdaExpr *S) {
+  VisitExpr(S);
+  for (LambdaExpr::capture_iterator C =3D S->explicit_capture_begin(),
+                                 CEnd =3D S->explicit_capture_end();
+       C !=3D CEnd; ++C) {
+    ID.AddInteger(C->getCaptureKind());
+    if (C->capturesVariable()) {
+      VisitDecl(C->getCapturedVar());
+      ID.AddBoolean(C->isPackExpansion());
+    }
+  }
+  // Note: If we actually needed to be able to match lambda
+  // expressions, we would have to consider parameters and return type
+  // here, among other things.
+  VisitStmt(S->getBody());
+}
+
+void
 StmtProfiler::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *S)=
 {
   VisitExpr(S);
 }
@@ -792,13 +826,11 @@
   VisitType(S->getAllocatedType());
   VisitDecl(S->getOperatorNew());
   VisitDecl(S->getOperatorDelete());
-  VisitDecl(S->getConstructor());
   ID.AddBoolean(S->isArray());
   ID.AddInteger(S->getNumPlacementArgs());
   ID.AddBoolean(S->isGlobalNew());
   ID.AddBoolean(S->isParenTypeId());
-  ID.AddBoolean(S->hasInitializer());
-  ID.AddInteger(S->getNumConstructorArgs());
+  ID.AddInteger(S->getInitializationStyle());
 }
=20
 void
@@ -837,6 +869,14 @@
   VisitType(S->getRhsType());
 }
=20
+void StmtProfiler::VisitTypeTraitExpr(const TypeTraitExpr *S) {
+  VisitExpr(S);
+  ID.AddInteger(S->getTrait());
+  ID.AddInteger(S->getNumArgs());
+  for (unsigned I =3D 0, N =3D S->getNumArgs(); I !=3D N; ++I)
+    VisitType(S->getArg(I)->getType());
+}
+
 void StmtProfiler::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *S) {
   VisitExpr(S);
   ID.AddInteger(S->getTrait());
@@ -935,6 +975,18 @@
   VisitExpr(S);
 }
=20
+void StmtProfiler::VisitObjCNumericLiteral(const ObjCNumericLiteral *E) {
+  VisitExpr(E);
+}
+
+void StmtProfiler::VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
+  VisitExpr(E);
+}
+
+void StmtProfiler::VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral =
*E) {
+  VisitExpr(E);
+}
+
 void StmtProfiler::VisitObjCEncodeExpr(const ObjCEncodeExpr *S) {
   VisitExpr(S);
   VisitType(S->getEncodedType());
@@ -971,6 +1023,12 @@
   }
 }
=20
+void StmtProfiler::VisitObjCSubscriptRefExpr(const ObjCSubscriptRefExpr *S=
) {
+  VisitExpr(S);
+  VisitDecl(S->getAtIndexMethodDecl());
+  VisitDecl(S->setAtIndexMethodDecl());
+}
+
 void StmtProfiler::VisitObjCMessageExpr(const ObjCMessageExpr *S) {
   VisitExpr(S);
   VisitName(S->getSelector());
@@ -982,6 +1040,11 @@
   ID.AddBoolean(S->isArrow());
 }
=20
+void StmtProfiler::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *S) {
+  VisitExpr(S);
+  ID.AddBoolean(S->getValue());
+}
+
 void StmtProfiler::VisitObjCIndirectCopyRestoreExpr(
     const ObjCIndirectCopyRestoreExpr *S) {
   VisitExpr(S);
@@ -1020,6 +1083,14 @@
       return;
     }
=20
+    if (const TemplateTypeParmDecl *TTP =3D
+          dyn_cast<TemplateTypeParmDecl>(D)) {
+      ID.AddInteger(TTP->getDepth());
+      ID.AddInteger(TTP->getIndex());
+      ID.AddBoolean(TTP->isParameterPack());
+      return;
+    }
+
     if (const TemplateTemplateParmDecl *TTP =3D
           dyn_cast<TemplateTemplateParmDecl>(D)) {
       ID.AddInteger(TTP->getDepth());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
TemplateBase.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/TemplateBase.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/TemplateBase.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -22,6 +22,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/Diagnostic.h"
 #include "llvm/ADT/FoldingSet.h"
+#include "llvm/ADT/SmallString.h"
 #include <algorithm>
 #include <cctype>
=20
@@ -40,10 +41,9 @@
   if (T->isBooleanType()) {
     Out << (Val->getBoolValue() ? "true" : "false");
   } else if (T->isCharType()) {
-    const unsigned char Ch =3D Val->getZExtValue();
-    const std::string Str(1, Ch);
+    const char Ch =3D Val->getZExtValue();
     Out << ((Ch =3D=3D '\'') ? "'\\" : "'");
-    Out.write_escaped(Str, /*UseHexEscapes=3D*/ true);
+    Out.write_escaped(StringRef(&Ch, 1), /*UseHexEscapes=3D*/ true);
     Out << "'";
   } else {
     Out << Val->toString(10);
@@ -80,9 +80,13 @@
     return true;
=20
   case Declaration:
-    if (DeclContext *DC =3D dyn_cast<DeclContext>(getAsDecl()))
-      return DC->isDependentContext();
-    return getAsDecl()->getDeclContext()->isDependentContext();
+    if (Decl *D =3D getAsDecl()) {
+      if (DeclContext *DC =3D dyn_cast<DeclContext>(D))
+        return DC->isDependentContext();
+      return D->getDeclContext()->isDependentContext();
+    }
+     =20
+    return false;
=20
   case Integral:
     // Never dependent
@@ -100,7 +104,7 @@
     return false;
   }
=20
-  return false;
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 bool TemplateArgument::isInstantiationDependent() const {
@@ -118,10 +122,13 @@
     return true;
    =20
   case Declaration:
-    if (DeclContext *DC =3D dyn_cast<DeclContext>(getAsDecl()))
-      return DC->isDependentContext();
-    return getAsDecl()->getDeclContext()->isDependentContext();
-   =20
+    if (Decl *D =3D getAsDecl()) {
+      if (DeclContext *DC =3D dyn_cast<DeclContext>(D))
+        return DC->isDependentContext();
+      return D->getDeclContext()->isDependentContext();
+    }
+    return false;
+     =20
   case Integral:
     // Never dependent
     return false;
@@ -137,8 +144,8 @@
    =20
     return false;
   }
- =20
-  return false;
+
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 bool TemplateArgument::isPackExpansion() const {
@@ -159,8 +166,8 @@
   case Expression:
     return isa<PackExpansionExpr>(getAsExpr());
   }
- =20
-  return false;
+
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 bool TemplateArgument::containsUnexpandedParameterPack() const {
@@ -278,8 +285,7 @@
     return true;
   }
=20
-  // Suppress warnings.
-  return false;
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 TemplateArgument TemplateArgument::getPackExpansionPattern() const {
@@ -302,8 +308,8 @@
   case Template:
     return TemplateArgument();
   }
- =20
-  return TemplateArgument();
+
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 void TemplateArgument::print(const PrintingPolicy &Policy,=20
@@ -323,16 +329,14 @@
   }
    =20
   case Declaration: {
-    bool Unnamed =3D true;
     if (NamedDecl *ND =3D dyn_cast_or_null<NamedDecl>(getAsDecl())) {
       if (ND->getDeclName()) {
-        Unnamed =3D false;
-        Out << ND->getNameAsString();
+        Out << *ND;
+      } else {
+        Out << "<anonymous>";
       }
-    }
-   =20
-    if (Unnamed) {
-      Out << "<anonymous>";
+    } else {
+      Out << "nullptr";
     }
     break;
   }
@@ -412,8 +416,7 @@
     return SourceRange();
   }
=20
-  // Silence bonus gcc warning.
-  return SourceRange();
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 TemplateArgumentLoc=20
@@ -474,8 +477,8 @@
   case TemplateArgument::Null:
     return TemplateArgumentLoc();
   }
- =20
-  return TemplateArgumentLoc();
+
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
@@ -490,7 +493,9 @@
     return DB << Arg.getAsType();
      =20
   case TemplateArgument::Declaration:
-    return DB << Arg.getAsDecl();
+    if (Decl *D =3D Arg.getAsDecl())
+      return DB << D;
+    return DB << "nullptr";
      =20
   case TemplateArgument::Integral:
     return DB << Arg.getAsIntegral()->toString(10);
@@ -505,7 +510,7 @@
     // This shouldn't actually ever happen, so it's okay that we're
     // regurgitating an expression here.
     // FIXME: We're guessing at LangOptions!
-    llvm::SmallString<32> Str;
+    SmallString<32> Str;
     llvm::raw_svector_ostream OS(Str);
     LangOptions LangOpts;
     LangOpts.CPlusPlus =3D true;
@@ -516,7 +521,7 @@
      =20
   case TemplateArgument::Pack: {
     // FIXME: We're guessing at LangOptions!
-    llvm::SmallString<32> Str;
+    SmallString<32> Str;
     llvm::raw_svector_ostream OS(Str);
     LangOptions LangOpts;
     LangOpts.CPlusPlus =3D true;
@@ -525,15 +530,15 @@
     return DB << OS.str();
   }
   }
- =20
-  return DB;
+
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 const ASTTemplateArgumentListInfo *
 ASTTemplateArgumentListInfo::Create(ASTContext &C,
                                     const TemplateArgumentListInfo &List) {
   std::size_t size =3D sizeof(CXXDependentScopeMemberExpr) +
-                     ASTTemplateArgumentListInfo::sizeFor(List);
+                     ASTTemplateArgumentListInfo::sizeFor(List.size());
   void *Mem =3D C.Allocate(size, llvm::alignOf<ASTTemplateArgumentListInfo=
>());
   ASTTemplateArgumentListInfo *TAI =3D new (Mem) ASTTemplateArgumentListIn=
fo();
   TAI->initializeFrom(List);
@@ -586,7 +591,38 @@
          sizeof(TemplateArgumentLoc) * NumTemplateArgs;
 }
=20
-std::size_t ASTTemplateArgumentListInfo::sizeFor(
-                                      const TemplateArgumentListInfo &Info=
) {
-  return sizeFor(Info.size());
+void
+ASTTemplateKWAndArgsInfo::initializeFrom(SourceLocation TemplateKWLoc,
+                                         const TemplateArgumentListInfo &I=
nfo) {
+  Base::initializeFrom(Info);
+  setTemplateKeywordLoc(TemplateKWLoc);
 }
+
+void
+ASTTemplateKWAndArgsInfo
+::initializeFrom(SourceLocation TemplateKWLoc,
+                 const TemplateArgumentListInfo &Info,
+                 bool &Dependent,
+                 bool &InstantiationDependent,
+                 bool &ContainsUnexpandedParameterPack) {
+  Base::initializeFrom(Info, Dependent, InstantiationDependent,
+                       ContainsUnexpandedParameterPack);
+  setTemplateKeywordLoc(TemplateKWLoc);
+}
+
+void
+ASTTemplateKWAndArgsInfo::initializeFrom(SourceLocation TemplateKWLoc) {
+  // No explicit template arguments, but template keyword loc is valid.
+  assert(TemplateKWLoc.isValid());
+  LAngleLoc =3D SourceLocation();
+  RAngleLoc =3D SourceLocation();
+  NumTemplateArgs =3D 0;
+  setTemplateKeywordLoc(TemplateKWLoc);
+}
+
+std::size_t
+ASTTemplateKWAndArgsInfo::sizeFor(unsigned NumTemplateArgs) {
+  // Add space for the template keyword location.
+  return Base::sizeFor(NumTemplateArgs) + sizeof(SourceLocation);
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
TemplateName.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/TemplateName.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/TemplateName.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -149,7 +149,7 @@
     subst->getReplacement().print(OS, Policy, SuppressNNS);
   } else if (SubstTemplateTemplateParmPackStorage *SubstPack
                                         =3D getAsSubstTemplateTemplateParm=
Pack())
-    OS << SubstPack->getParameterPack()->getNameAsString();
+    OS << *SubstPack->getParameterPack();
   else {
     OverloadedTemplateStorage *OTS =3D getAsOverloadedTemplate();
     (*OTS->begin())->printName(OS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
Type.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/Type.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/Type.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -197,27 +197,28 @@
 /// concrete.
 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context)=
 {
   SplitQualType split =3D getSplitDesugaredType(T);
-  return Context.getQualifiedType(split.first, split.second);
+  return Context.getQualifiedType(split.Ty, split.Quals);
 }
=20
-QualType QualType::getSingleStepDesugaredType(const ASTContext &Context) c=
onst {
-  QualifierCollector Qs;
- =20
-  const Type *CurTy =3D Qs.strip(*this);
-  switch (CurTy->getTypeClass()) {
+QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
+                                                  const ASTContext &Contex=
t) {
+  SplitQualType split =3D type.split();
+  QualType desugar =3D split.Ty->getLocallyUnqualifiedSingleStepDesugaredT=
ype();
+  return Context.getQualifiedType(desugar, split.Quals);
+}
+
+QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
+  switch (getTypeClass()) {
 #define ABSTRACT_TYPE(Class, Parent)
 #define TYPE(Class, Parent) \
   case Type::Class: { \
-    const Class##Type *Ty =3D cast<Class##Type>(CurTy); \
-    if (!Ty->isSugared()) \
-      return *this; \
-    return Context.getQualifiedType(Ty->desugar(), Qs); \
-    break; \
+    const Class##Type *ty =3D cast<Class##Type>(this); \
+    if (!ty->isSugared()) return QualType(ty, 0); \
+    return ty->desugar(); \
   }
 #include "clang/AST/TypeNodes.def"
   }
-
-  return *this;
+  llvm_unreachable("bad type kind!");
 }
=20
 SplitQualType QualType::getSplitDesugaredType(QualType T) {
@@ -245,21 +246,21 @@
   SplitQualType split =3D type.split();
=20
   // All the qualifiers we've seen so far.
-  Qualifiers quals =3D split.second;
+  Qualifiers quals =3D split.Quals;
=20
   // The last type node we saw with any nodes inside it.
-  const Type *lastTypeWithQuals =3D split.first;
+  const Type *lastTypeWithQuals =3D split.Ty;
=20
   while (true) {
     QualType next;
=20
     // Do a single-step desugar, aborting the loop if the type isn't
     // sugared.
-    switch (split.first->getTypeClass()) {
+    switch (split.Ty->getTypeClass()) {
 #define ABSTRACT_TYPE(Class, Parent)
 #define TYPE(Class, Parent) \
     case Type::Class: { \
-      const Class##Type *ty =3D cast<Class##Type>(split.first); \
+      const Class##Type *ty =3D cast<Class##Type>(split.Ty); \
       if (!ty->isSugared()) goto done; \
       next =3D ty->desugar(); \
       break; \
@@ -270,9 +271,9 @@
     // Otherwise, split the underlying type.  If that yields qualifiers,
     // update the information.
     split =3D next.split();
-    if (!split.second.empty()) {
-      lastTypeWithQuals =3D split.first;
-      quals.addConsistentQualifiers(split.second);
+    if (!split.Quals.empty()) {
+      lastTypeWithQuals =3D split.Ty;
+      quals.addConsistentQualifiers(split.Quals);
     }
   }
=20
@@ -308,13 +309,6 @@
   }
 }
=20
-/// isVoidType - Helper method to determine if this is the 'void' type.
-bool Type::isVoidType() const {
-  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
-    return BT->getKind() =3D=3D BuiltinType::Void;
-  return false;
-}
-
 bool Type::isDerivedType() const {
   switch (CanonicalType->getTypeClass()) {
   case Pointer:
@@ -555,17 +549,6 @@
   return GetContainedAutoVisitor().Visit(this);
 }
=20
-bool Type::isIntegerType() const {
-  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
-    return BT->getKind() >=3D BuiltinType::Bool &&
-           BT->getKind() <=3D BuiltinType::Int128;
-  if (const EnumType *ET =3D dyn_cast<EnumType>(CanonicalType))
-    // Incomplete enum types are not treated as integer types.
-    // FIXME: In C++, enum types are never integer types.
-    return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
-  return false;
-}
-
 bool Type::hasIntegerRepresentation() const {
   if (const VectorType *VT =3D dyn_cast<VectorType>(CanonicalType))
     return VT->getElementType()->isIntegerType();
@@ -597,25 +580,13 @@
     return BT->getKind() >=3D BuiltinType::Bool &&
     BT->getKind() <=3D BuiltinType::Int128;
  =20
-  if (!Ctx.getLangOptions().CPlusPlus)
+  if (!Ctx.getLangOpts().CPlusPlus)
     if (const EnumType *ET =3D dyn_cast<EnumType>(CanonicalType))
       return ET->getDecl()->isComplete(); // Complete enum types are integ=
ral in C.
  =20
   return false;
 }
=20
-bool Type::isIntegralOrEnumerationType() const {
-  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
-    return BT->getKind() >=3D BuiltinType::Bool &&
-           BT->getKind() <=3D BuiltinType::Int128;
-
-  // Check for a complete enum type; incomplete enum types are not properl=
y an
-  // enumeration type in the sense required here.
-  if (const EnumType *ET =3D dyn_cast<EnumType>(CanonicalType))
-    return ET->getDecl()->isComplete();
-
-  return false; =20
-}
=20
 bool Type::isIntegralOrUnscopedEnumerationType() const {
   if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
@@ -633,11 +604,6 @@
 }
=20
=20
-bool Type::isBooleanType() const {
-  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
-    return BT->getKind() =3D=3D BuiltinType::Bool;
-  return false;
-}
=20
 bool Type::isCharType() const {
   if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
@@ -766,13 +732,6 @@
     return isUnsignedIntegerType();
 }
=20
-bool Type::isHalfType() const {
-  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
-    return BT->getKind() =3D=3D BuiltinType::Half;
-  // FIXME: Should we allow complex __fp16? Probably not.
-  return false;
-}
-
 bool Type::isFloatingType() const {
   if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
     return BT->getKind() >=3D BuiltinType::Half &&
@@ -819,21 +778,6 @@
   return isa<ComplexType>(CanonicalType);
 }
=20
-bool Type::isScalarType() const {
-  if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(CanonicalType))
-    return BT->getKind() > BuiltinType::Void &&
-           BT->getKind() <=3D BuiltinType::NullPtr;
-  if (const EnumType *ET =3D dyn_cast<EnumType>(CanonicalType))
-    // Enums are scalar types, but only if they are defined.  Incomplete e=
nums
-    // are not treated as scalar types.
-    return ET->getDecl()->isComplete();
-  return isa<PointerType>(CanonicalType) ||
-         isa<BlockPointerType>(CanonicalType) ||
-         isa<MemberPointerType>(CanonicalType) ||
-         isa<ComplexType>(CanonicalType) ||
-         isa<ObjCObjectPointerType>(CanonicalType);
-}
-
 Type::ScalarTypeKind Type::getScalarTypeKind() const {
   assert(isScalarType());
=20
@@ -897,37 +841,56 @@
 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.=
5p1)
 /// - a type that can describe objects, but which lacks information needed=
 to
 /// determine its size.
-bool Type::isIncompleteType() const {
+bool Type::isIncompleteType(NamedDecl **Def) const {
+  if (Def)
+    *Def =3D 0;
+ =20
   switch (CanonicalType->getTypeClass()) {
   default: return false;
   case Builtin:
     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can=
 never
     // be completed.
     return isVoidType();
-  case Enum:
+  case Enum: {
+    EnumDecl *EnumD =3D cast<EnumType>(CanonicalType)->getDecl();
+    if (Def)
+      *Def =3D EnumD;
+   =20
     // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
-    if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
-        return false;
-    // Fall through.
-  case Record:
+    if (EnumD->isFixed())
+      return false;
+   =20
+    return !EnumD->isCompleteDefinition();
+  }
+  case Record: {
     // A tagged type (struct/union/enum/class) is incomplete if the decl i=
s a
     // forward declaration, but not a full definition (C99 6.2.5p22).
-    return !cast<TagType>(CanonicalType)->getDecl()->isCompleteDefinition(=
);
+    RecordDecl *Rec =3D cast<RecordType>(CanonicalType)->getDecl();
+    if (Def)
+      *Def =3D Rec;
+    return !Rec->isCompleteDefinition();
+  }
   case ConstantArray:
     // An array is incomplete if its element type is incomplete
     // (C++ [dcl.array]p1).
     // We don't handle variable arrays (they're not allowed in C++) or
     // dependent-sized arrays (dependent types are never treated as incomp=
lete).
-    return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteT=
ype();
+    return cast<ArrayType>(CanonicalType)->getElementType()
+             ->isIncompleteType(Def);
   case IncompleteArray:
     // An array of unknown size is an incomplete type (C99 6.2.5p22).
     return true;
   case ObjCObject:
     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
-                                                         ->isIncompleteTyp=
e();
-  case ObjCInterface:
+             ->isIncompleteType(Def);
+  case ObjCInterface: {
     // ObjC interfaces are incomplete if they are @class, not @interface.
-    return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDec=
l();
+    ObjCInterfaceDecl *Interface
+      =3D cast<ObjCInterfaceType>(CanonicalType)->getDecl();
+    if (Def)
+      *Def =3D Interface;
+    return !Interface->hasDefinition();
+  }
   }
 }
=20
@@ -944,7 +907,7 @@
   if ((*this)->isIncompleteType())
     return false;
=20
-  if (Context.getLangOptions().ObjCAutoRefCount) {
+  if (Context.getLangOpts().ObjCAutoRefCount) {
     switch (getObjCLifetime()) {
     case Qualifiers::OCL_ExplicitNone:
       return true;
@@ -1006,7 +969,7 @@
   if ((*this)->isIncompleteType())
     return false;
  =20
-  if (Context.getLangOptions().ObjCAutoRefCount) {
+  if (Context.getLangOpts().ObjCAutoRefCount) {
     switch (getObjCLifetime()) {
     case Qualifiers::OCL_ExplicitNone:
       return true;
@@ -1056,7 +1019,7 @@
   if ((*this)->isArrayType())
     return Context.getBaseElementType(*this).isTrivialType(Context);
=20
-  if (Context.getLangOptions().ObjCAutoRefCount) {
+  if (Context.getLangOpts().ObjCAutoRefCount) {
     switch (getObjCLifetime()) {
     case Qualifiers::OCL_ExplicitNone:
       return true;
@@ -1126,15 +1089,13 @@
   if (BaseTy->isIncompleteType())
     return false;
=20
-  // Objective-C lifetime types are not literal types.
-  if (BaseTy->isObjCRetainableType())
-    return false;
- =20
   // C++0x [basic.types]p10:
   //   A type is a literal type if it is:
   //    -- a scalar type; or
-  // As an extension, Clang treats vector types as literal types.
-  if (BaseTy->isScalarType() || BaseTy->isVectorType())
+  // As an extension, Clang treats vector types and complex types as
+  // literal types.
+  if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
+      BaseTy->isAnyComplexType())
     return true;
   //    -- a reference type; or
   if (BaseTy->isReferenceType())
@@ -1203,7 +1164,7 @@
   if (ty->isDependentType())
     return false;
=20
-  if (Context.getLangOptions().ObjCAutoRefCount) {
+  if (Context.getLangOpts().ObjCAutoRefCount) {
     switch (getObjCLifetime()) {
     case Qualifiers::OCL_ExplicitNone:
       return true;
@@ -1272,6 +1233,10 @@
     case BuiltinType::UChar:
     case BuiltinType::Short:
     case BuiltinType::UShort:
+    case BuiltinType::WChar_S:
+    case BuiltinType::WChar_U:
+    case BuiltinType::Char16:
+    case BuiltinType::Char32:
       return true;
     default:
       return false;
@@ -1284,21 +1249,12 @@
         || ET->getDecl()->isScoped())
       return false;
    =20
-    const BuiltinType *BT
-      =3D ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
-    return BT->getKind() =3D=3D BuiltinType::Int
-           || BT->getKind() =3D=3D BuiltinType::UInt;
+    return true;
   }
  =20
   return false;
 }
=20
-bool Type::isNullPtrType() const {
-  if (const BuiltinType *BT =3D getAs<BuiltinType>())
-    return BT->getKind() =3D=3D BuiltinType::NullPtr;
-  return false;
-}
-
 bool Type::isSpecifierType() const {
   // Note that this intentionally does not use the canonical type.
   switch (getTypeClass()) {
@@ -1346,7 +1302,6 @@
   }
  =20
   llvm_unreachable("Type specifier is not a tag type kind.");
-  return TTK_Union;
 }
=20
 ElaboratedTypeKeyword
@@ -1401,7 +1356,6 @@
   }
=20
   llvm_unreachable("Unknown elaborated type keyword.");
-  return "";
 }
=20
 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
@@ -1461,7 +1415,6 @@
   }
  =20
   llvm_unreachable("Invalid type class.");
-  return 0;
 }
=20
 const char *BuiltinType::getName(const PrintingPolicy &Policy) const {
@@ -1475,13 +1428,13 @@
   case Int:               return "int";
   case Long:              return "long";
   case LongLong:          return "long long";
-  case Int128:            return "__int128_t";
+  case Int128:            return "__int128";
   case UChar:             return "unsigned char";
   case UShort:            return "unsigned short";
   case UInt:              return "unsigned int";
   case ULong:             return "unsigned long";
   case ULongLong:         return "unsigned long long";
-  case UInt128:           return "__uint128_t";
+  case UInt128:           return "unsigned __int128";
   case Half:              return "half";
   case Float:             return "float";
   case Double:            return "double";
@@ -1493,15 +1446,16 @@
   case NullPtr:           return "nullptr_t";
   case Overload:          return "<overloaded function type>";
   case BoundMember:       return "<bound member function type>";
+  case PseudoObject:      return "<pseudo-object type>";
   case Dependent:         return "<dependent type>";
   case UnknownAny:        return "<unknown type>";
+  case ARCUnbridgedCast:  return "<ARC unbridged cast type>";
   case ObjCId:            return "id";
   case ObjCClass:         return "Class";
   case ObjCSel:           return "SEL";
   }
  =20
   llvm_unreachable("Invalid builtin type.");
-  return 0;
 }
=20
 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
@@ -1513,7 +1467,7 @@
   //   have cv-unqualified types.
   //
   // See also C99 6.3.2.1p2.
-  if (!Context.getLangOptions().CPlusPlus ||
+  if (!Context.getLangOpts().CPlusPlus ||
       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
     return getUnqualifiedType();
  =20
@@ -1524,7 +1478,6 @@
   switch (CC) {
   case CC_Default:=20
     llvm_unreachable("no name for default cc");
-    return "";
=20
   case CC_C: return "cdecl";
   case CC_X86StdCall: return "stdcall";
@@ -1536,14 +1489,13 @@
   }
=20
   llvm_unreachable("Invalid calling convention.");
-  return "";
 }
=20
 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
                                      unsigned numArgs, QualType canonical,
                                      const ExtProtoInfo &epi)
-  : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals,=20
-                 epi.RefQualifier, canonical,
+  : FunctionType(FunctionProto, result, epi.TypeQuals, epi.RefQualifier,
+                 canonical,
                  result->isDependentType(),
                  result->isInstantiationDependentType(),
                  result->isVariablyModifiedType(),
@@ -1551,7 +1503,8 @@
                  epi.ExtInfo),
     NumArgs(numArgs), NumExceptions(epi.NumExceptions),
     ExceptionSpecType(epi.ExceptionSpecType),
-    HasAnyConsumedArgs(epi.ConsumedArguments !=3D 0)
+    HasAnyConsumedArgs(epi.ConsumedArguments !=3D 0),
+    Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn)
 {
   // Fill in the trailing argument array.
   QualType *argSlot =3D reinterpret_cast<QualType*>(this+1);
@@ -1649,8 +1602,8 @@
   // This is followed by an optional "consumed argument" section of the
   // same length as the first type sequence:
   //      bool*
-  // Finally, we have the ext info:
-  //      int
+  // Finally, we have the ext info and trailing return type flag:
+  //      int bool
   //=20
   // There is no ambiguity between the consumed arguments and an empty EH
   // spec because of the leading 'bool' which unambiguously indicates
@@ -1682,6 +1635,7 @@
       ID.AddBoolean(epi.ConsumedArguments[i]);
   }
   epi.ExtInfo.Profile(ID);
+  ID.AddBoolean(epi.HasTrailingReturn);
 }
=20
 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
@@ -1719,7 +1673,10 @@
 }
=20
 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
-  : Type(Decltype, can, E->isTypeDependent(),=20
+  // C++11 [temp.type]p2: "If an expression e involves a template paramete=
r,
+  // decltype(e) denotes a unique dependent type." Hence a decltype type is
+  // type-dependent even if its expression is only instantiation-dependent.
+  : Type(Decltype, can, E->isInstantiationDependent(),
          E->isInstantiationDependent(),
          E->getType()->isVariablyModifiedType(),=20
          E->containsUnexpandedParameterPack()),=20
@@ -1785,14 +1742,6 @@
   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
 }
=20
-bool RecordType::classof(const TagType *TT) {
-  return isa<RecordDecl>(TT->getDecl());
-}
-
-bool EnumType::classof(const TagType *TT) {
-  return isa<EnumDecl>(TT->getDecl());
-}
-
 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
   return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
 }
@@ -1872,8 +1821,10 @@
          Canon.isNull()? T.isDependent() : Canon->isDependentType(),
          Canon.isNull()? T.isDependent()=20
                        : Canon->isInstantiationDependentType(),
-         false, T.containsUnexpandedParameterPack()),
-    Template(T), NumArgs(NumArgs) {
+         false,
+         Canon.isNull()? T.containsUnexpandedParameterPack()
+                       : Canon->containsUnexpandedParameterPack()),
+    Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
   assert(!T.getAsDependentTemplateName() &&=20
          "Use DependentTemplateSpecializationType for dependent template-n=
ame");
   assert((T.getKind() =3D=3D TemplateName::Template ||
@@ -1905,17 +1856,14 @@
     if (Args[Arg].getKind() =3D=3D TemplateArgument::Type &&
         Args[Arg].getAsType()->isVariablyModifiedType())
       setVariablyModified();
-    if (Args[Arg].containsUnexpandedParameterPack())
+    if (Canon.isNull() && Args[Arg].containsUnexpandedParameterPack())
       setContainsUnexpandedParameterPack();
=20
     new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
   }
=20
   // Store the aliased type if this is a type alias template specializatio=
n.
-  bool IsTypeAlias =3D !AliasedType.isNull();
-  assert(IsTypeAlias =3D=3D isTypeAlias() &&
-         "allocated wrong size for type alias");
-  if (IsTypeAlias) {
+  if (TypeAlias) {
     TemplateArgument *Begin =3D reinterpret_cast<TemplateArgument *>(this =
+ 1);
     *reinterpret_cast<QualType*>(Begin + getNumArgs()) =3D AliasedType;
   }
@@ -1932,11 +1880,6 @@
     Args[Idx].Profile(ID, Context);
 }
=20
-bool TemplateSpecializationType::isTypeAlias() const {
-  TemplateDecl *D =3D Template.getAsTemplateDecl();
-  return D && isa<TypeAliasTemplateDecl>(D);
-}
-
 QualType
 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
   if (!hasNonFastQualifiers())
@@ -1970,21 +1913,22 @@
=20
 /// \brief The cached properties of a type.
 class CachedProperties {
-  char linkage;
-  char visibility;
+  NamedDecl::LinkageInfo LV;
   bool local;
  =20
 public:
-  CachedProperties(Linkage linkage, Visibility visibility, bool local)
-    : linkage(linkage), visibility(visibility), local(local) {}
+  CachedProperties(NamedDecl::LinkageInfo LV, bool local)
+    : LV(LV), local(local) {}
  =20
-  Linkage getLinkage() const { return (Linkage) linkage; }
-  Visibility getVisibility() const { return (Visibility) visibility; }
+  Linkage getLinkage() const { return LV.linkage(); }
+  Visibility getVisibility() const { return LV.visibility(); }
+  bool isVisibilityExplicit() const { return LV.visibilityExplicit(); }
   bool hasLocalOrUnnamedType() const { return local; }
  =20
   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
-    return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
-                            minVisibility(L.getVisibility(), R.getVisibili=
ty()),
+    NamedDecl::LinkageInfo MergedLV =3D L.LV;
+    MergedLV.merge(R.LV);
+    return CachedProperties(MergedLV,
                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedTy=
pe());
   }
 };
@@ -2004,9 +1948,10 @@
=20
   static CachedProperties get(const Type *T) {
     ensure(T);
-    return CachedProperties(T->TypeBits.getLinkage(),
-                            T->TypeBits.getVisibility(),
-                            T->TypeBits.hasLocalOrUnnamedType());
+    NamedDecl::LinkageInfo LV(T->TypeBits.getLinkage(),
+                              T->TypeBits.getVisibility(),
+                              T->TypeBits.isVisibilityExplicit());
+    return CachedProperties(LV, T->TypeBits.hasLocalOrUnnamedType());
   }
=20
   static void ensure(const Type *T) {
@@ -2020,6 +1965,8 @@
       ensure(CT);
       T->TypeBits.CacheValidAndVisibility =3D
         CT->TypeBits.CacheValidAndVisibility;
+      T->TypeBits.CachedExplicitVisibility =3D
+        CT->TypeBits.CachedExplicitVisibility;
       T->TypeBits.CachedLinkage =3D CT->TypeBits.CachedLinkage;
       T->TypeBits.CachedLocalOrUnnamed =3D CT->TypeBits.CachedLocalOrUnnam=
ed;
       return;
@@ -2028,6 +1975,7 @@
     // Compute the cached properties and then set the cache.
     CachedProperties Result =3D computeCachedProperties(T);
     T->TypeBits.CacheValidAndVisibility =3D Result.getVisibility() + 1U;
+    T->TypeBits.CachedExplicitVisibility =3D Result.isVisibilityExplicit();
     assert(T->TypeBits.isCacheValid() &&
            T->TypeBits.getVisibility() =3D=3D Result.getVisibility());
     T->TypeBits.CachedLinkage =3D Result.getLinkage();
@@ -2055,13 +2003,13 @@
 #include "clang/AST/TypeNodes.def"
     // Treat instantiation-dependent types as external.
     assert(T->isInstantiationDependentType());
-    return CachedProperties(ExternalLinkage, DefaultVisibility, false);
+    return CachedProperties(NamedDecl::LinkageInfo(), false);
=20
   case Type::Builtin:
     // C++ [basic.link]p8:
     //   A type is said to have linkage if and only if:
     //     - it is a fundamental type (3.9.1); or
-    return CachedProperties(ExternalLinkage, DefaultVisibility, false);
+    return CachedProperties(NamedDecl::LinkageInfo(), false);
=20
   case Type::Record:
   case Type::Enum: {
@@ -2075,7 +2023,7 @@
     bool IsLocalOrUnnamed =3D
       Tag->getDeclContext()->isFunctionOrMethod() ||
       (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
-    return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnname=
d);
+    return CachedProperties(LV, IsLocalOrUnnamed);
   }
=20
     // C++ [basic.link]p8:
@@ -2115,7 +2063,7 @@
   case Type::ObjCInterface: {
     NamedDecl::LinkageInfo LV =3D
       cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
-    return CachedProperties(LV.linkage(), LV.visibility(), false);
+    return CachedProperties(LV, false);
   }
   case Type::ObjCObject:
     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
@@ -2126,10 +2074,6 @@
   }
=20
   llvm_unreachable("unhandled type class");
-
-  // C++ [basic.link]p8:
-  //   Names not covered by these rules have no linkage.
-  return CachedProperties(NoLinkage, DefaultVisibility, false);
 }
=20
 /// \brief Determine the linkage of this type.
@@ -2144,6 +2088,11 @@
   return TypeBits.getVisibility();
 }
=20
+bool Type::isVisibilityExplicit() const {
+  Cache::ensure(this);
+  return TypeBits.isVisibilityExplicit();
+}
+
 bool Type::hasUnnamedOrLocalType() const {
   Cache::ensure(this);
   return TypeBits.hasLocalOrUnnamedType();
@@ -2285,7 +2234,7 @@
   case Qualifiers::OCL_Autoreleasing:
   case Qualifiers::OCL_Strong:
   case Qualifiers::OCL_Weak:
-    return !Context.getLangOptions().ObjCAutoRefCount;
+    return !Context.getLangOpts().ObjCAutoRefCount;
   }
  =20
   if (const CXXRecordDecl *Record=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
TypeLoc.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/TypeLoc.cpp	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/TypeLoc.cpp	Tue Apr 17 11:51:51=
 2012 +0300
@@ -196,55 +196,54 @@
 TypeSpecifierType BuiltinTypeLoc::getWrittenTypeSpec() const {
   if (needsExtraLocalData())
     return static_cast<TypeSpecifierType>(getWrittenBuiltinSpecs().Type);
-  else {
-    switch (getTypePtr()->getKind()) {
-    case BuiltinType::Void:
-      return TST_void;
-    case BuiltinType::Bool:
-      return TST_bool;
-    case BuiltinType::Char_U:
-    case BuiltinType::Char_S:
-      return TST_char;
-    case BuiltinType::Char16:
-      return TST_char16;
-    case BuiltinType::Char32:
-      return TST_char32;
-    case BuiltinType::WChar_S:
-    case BuiltinType::WChar_U:
-      return TST_wchar;
+  switch (getTypePtr()->getKind()) {
+  case BuiltinType::Void:
+    return TST_void;
+  case BuiltinType::Bool:
+    return TST_bool;
+  case BuiltinType::Char_U:
+  case BuiltinType::Char_S:
+    return TST_char;
+  case BuiltinType::Char16:
+    return TST_char16;
+  case BuiltinType::Char32:
+    return TST_char32;
+  case BuiltinType::WChar_S:
+  case BuiltinType::WChar_U:
+    return TST_wchar;
+  case BuiltinType::UChar:
+  case BuiltinType::UShort:
+  case BuiltinType::UInt:
+  case BuiltinType::ULong:
+  case BuiltinType::ULongLong:
+  case BuiltinType::UInt128:
+  case BuiltinType::SChar:
+  case BuiltinType::Short:
+  case BuiltinType::Int:
+  case BuiltinType::Long:
+  case BuiltinType::LongLong:
+  case BuiltinType::Int128:
+  case BuiltinType::Half:
+  case BuiltinType::Float:
+  case BuiltinType::Double:
+  case BuiltinType::LongDouble:
+    llvm_unreachable("Builtin type needs extra local data!");
+    // Fall through, if the impossible happens.
+     =20
+  case BuiltinType::NullPtr:
+  case BuiltinType::Overload:
+  case BuiltinType::Dependent:
+  case BuiltinType::BoundMember:
+  case BuiltinType::UnknownAny:
+  case BuiltinType::ARCUnbridgedCast:
+  case BuiltinType::PseudoObject:
+  case BuiltinType::ObjCId:
+  case BuiltinType::ObjCClass:
+  case BuiltinType::ObjCSel:
+    return TST_unspecified;
+  }
=20
-    case BuiltinType::UChar:
-    case BuiltinType::UShort:
-    case BuiltinType::UInt:
-    case BuiltinType::ULong:
-    case BuiltinType::ULongLong:
-    case BuiltinType::UInt128:
-    case BuiltinType::SChar:
-    case BuiltinType::Short:
-    case BuiltinType::Int:
-    case BuiltinType::Long:
-    case BuiltinType::LongLong:
-    case BuiltinType::Int128:
-    case BuiltinType::Half:
-    case BuiltinType::Float:
-    case BuiltinType::Double:
-    case BuiltinType::LongDouble:
-      llvm_unreachable("Builtin type needs extra local data!");
-      // Fall through, if the impossible happens.
-       =20
-    case BuiltinType::NullPtr:
-    case BuiltinType::Overload:
-    case BuiltinType::Dependent:
-    case BuiltinType::BoundMember:
-    case BuiltinType::UnknownAny:
-    case BuiltinType::ObjCId:
-    case BuiltinType::ObjCClass:
-    case BuiltinType::ObjCSel:
-      return TST_unspecified;
-    }
-  }
- =20
-  return TST_unspecified;
+  llvm_unreachable("Invalid BuiltinType Kind!");
 }
=20
 TypeLoc TypeLoc::IgnoreParensImpl(TypeLoc TL) {
@@ -255,7 +254,7 @@
=20
 void ElaboratedTypeLoc::initializeLocal(ASTContext &Context,=20
                                         SourceLocation Loc) {
-  setKeywordLoc(Loc);
+  setElaboratedKeywordLoc(Loc);
   NestedNameSpecifierLocBuilder Builder;
   Builder.MakeTrivial(Context, getTypePtr()->getQualifier(), Loc);
   setQualifierLoc(Builder.getWithLocInContext(Context));
@@ -263,17 +262,17 @@
=20
 void DependentNameTypeLoc::initializeLocal(ASTContext &Context,=20
                                            SourceLocation Loc) {
-  setKeywordLoc(Loc);
+  setElaboratedKeywordLoc(Loc);
   NestedNameSpecifierLocBuilder Builder;
   Builder.MakeTrivial(Context, getTypePtr()->getQualifier(), Loc);
   setQualifierLoc(Builder.getWithLocInContext(Context));
   setNameLoc(Loc);
 }
=20
-void=20
-DependentTemplateSpecializationTypeLoc::initializeLocal(ASTContext &Contex=
t,=20
+void
+DependentTemplateSpecializationTypeLoc::initializeLocal(ASTContext &Contex=
t,
                                                         SourceLocation Loc=
) {
-  setKeywordLoc(Loc);
+  setElaboratedKeywordLoc(Loc);
   if (getTypePtr()->getQualifier()) {
     NestedNameSpecifierLocBuilder Builder;
     Builder.MakeTrivial(Context, getTypePtr()->getQualifier(), Loc);
@@ -281,8 +280,8 @@
   } else {
     setQualifierLoc(NestedNameSpecifierLoc());
   }
- =20
-  setNameLoc(Loc);
+  setTemplateKeywordLoc(Loc);
+  setTemplateNameLoc(Loc);
   setLAngleLoc(Loc);
   setRAngleLoc(Loc);
   TemplateSpecializationTypeLoc::initializeArgLocs(Context, getNumArgs(),
@@ -302,8 +301,7 @@
     case TemplateArgument::Integral:
     case TemplateArgument::Pack:
     case TemplateArgument::Expression:
-      // FIXME: Can we do better for declarations and integral values?
-      ArgInfos[i] =3D TemplateArgumentLocInfo();
+      ArgInfos[i] =3D TemplateArgumentLocInfo(Args[i].getAsExpr());
       break;
      =20
     case TemplateArgument::Type:
@@ -332,4 +330,3 @@
     }
   }
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
TypePrinter.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/TypePrinter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/TypePrinter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -75,7 +75,7 @@
=20
 void TypePrinter::print(QualType t, std::string &buffer) {
   SplitQualType split =3D t.split();
-  print(split.first, split.second, buffer);
+  print(split.Ty, split.Quals, buffer);
 }
=20
 void TypePrinter::print(const Type *T, Qualifiers Quals, std::string &buff=
er) {
@@ -264,8 +264,9 @@
=20
 void TypePrinter::printMemberPointer(const MemberPointerType *T,=20
                                      std::string &S) {=20
-  std::string C;
-  print(QualType(T->getClass(), 0), C);
+  PrintingPolicy InnerPolicy(Policy);
+  Policy.SuppressTag =3D true;
+  std::string C =3D QualType(T->getClass(), 0).getAsString(InnerPolicy);
   C +=3D "::*";
   S =3D C + S;
  =20
@@ -397,6 +398,35 @@
   print(T->getElementType(), S);
 }
=20
+void=20
+FunctionProtoType::printExceptionSpecification(std::string &S,=20
+                                               PrintingPolicy Policy) cons=
t {
+ =20
+  if (hasDynamicExceptionSpec()) {
+    S +=3D " throw(";
+    if (getExceptionSpecType() =3D=3D EST_MSAny)
+      S +=3D "...";
+    else
+      for (unsigned I =3D 0, N =3D getNumExceptions(); I !=3D N; ++I) {
+        if (I)
+          S +=3D ", ";
+       =20
+        S +=3D getExceptionType(I).getAsString(Policy);
+      }
+    S +=3D ")";
+  } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
+    S +=3D " noexcept";
+    if (getExceptionSpecType() =3D=3D EST_ComputedNoexcept) {
+      S +=3D "(";
+      llvm::raw_string_ostream EOut(S);
+      getNoexceptExpr()->printPretty(EOut, 0, Policy);
+      EOut.flush();
+      S +=3D EOut.str();
+      S +=3D ")";
+    }
+  }
+}
+
 void TypePrinter::printFunctionProto(const FunctionProtoType *T,=20
                                      std::string &S) {=20
   // If needed for precedence reasons, wrap the inner part in grouping par=
ens.
@@ -427,8 +457,7 @@
=20
   FunctionType::ExtInfo Info =3D T->getExtInfo();
   switch(Info.getCC()) {
-  case CC_Default:
-  default: break;
+  case CC_Default: break;
   case CC_C:
     S +=3D " __attribute__((cdecl))";
     break;
@@ -471,34 +500,13 @@
     S +=3D " &&";
     break;
   }
-
-  if (T->hasDynamicExceptionSpec()) {
-    S +=3D " throw(";
-    if (T->getExceptionSpecType() =3D=3D EST_MSAny)
-      S +=3D "...";
-    else
-      for (unsigned I =3D 0, N =3D T->getNumExceptions(); I !=3D N; ++I) {
-        if (I)
-          S +=3D ", ";
-
-        std::string ExceptionType;
-        print(T->getExceptionType(I), ExceptionType);
-        S +=3D ExceptionType;
-      }
-    S +=3D ")";
-  } else if (isNoexceptExceptionSpec(T->getExceptionSpecType())) {
-    S +=3D " noexcept";
-    if (T->getExceptionSpecType() =3D=3D EST_ComputedNoexcept) {
-      S +=3D "(";
-      llvm::raw_string_ostream EOut(S);
-      T->getNoexceptExpr()->printPretty(EOut, 0, Policy);
-      EOut.flush();
-      S +=3D EOut.str();
-      S +=3D ")";
-    }
-  }
-
-  print(T->getResultType(), S);
+  T->printExceptionSpecification(S, Policy);
+  if (T->hasTrailingReturn()) {
+    std::string ResultS;
+    print(T->getResultType(), ResultS);
+    S =3D "auto " + S + " -> " + ResultS;
+  } else
+    print(T->getResultType(), S);
 }
=20
 void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,=20
@@ -600,6 +608,9 @@
   unsigned OldSize =3D Buffer.size();
=20
   if (NamespaceDecl *NS =3D dyn_cast<NamespaceDecl>(DC)) {
+    if (Policy.SuppressUnwrittenScope &&=20
+        (NS->isAnonymousNamespace() || NS->isInline()))
+      return;
     if (NS->getIdentifier())
       Buffer +=3D NS->getNameAsString();
     else
@@ -620,6 +631,8 @@
       Buffer +=3D Typedef->getIdentifier()->getName();
     else if (Tag->getIdentifier())
       Buffer +=3D Tag->getIdentifier()->getName();
+    else
+      return;
   }
=20
   if (Buffer.size() !=3D OldSize)
@@ -660,8 +673,14 @@
     // Make an unambiguous representation for anonymous types, e.g.
     //   <anonymous enum at /usr/include/string.h:120:9>
     llvm::raw_string_ostream OS(Buffer);
-    OS << "<anonymous";
-
+   =20
+    if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
+      OS << "<lambda";
+      HasKindDecoration =3D true;
+    } else {
+      OS << "<anonymous";
+    }
+   =20
     if (Policy.AnonymousTagLocations) {
       // Suppress the redundant tag keyword if we just printed one.
       // We don't have to worry about ElaboratedTypes here because you can=
't
@@ -930,7 +949,7 @@
   case AttributedType::attr_objc_ownership:
     S +=3D "objc_ownership(";
     switch (T->getEquivalentType().getObjCLifetime()) {
-    case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
+    case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
     case Qualifiers::OCL_ExplicitNone: S +=3D "none"; break;
     case Qualifiers::OCL_Strong: S +=3D "strong"; break;
     case Qualifiers::OCL_Weak: S +=3D "weak"; break;
@@ -1157,9 +1176,21 @@
   AppendTypeQualList(S, getCVRQualifiers());
   if (unsigned addrspace =3D getAddressSpace()) {
     if (!S.empty()) S +=3D ' ';
-    S +=3D "__attribute__((address_space(";
-    S +=3D llvm::utostr_32(addrspace);
-    S +=3D ")))";
+    switch (addrspace) {
+      case LangAS::opencl_global:
+        S +=3D "__global";
+        break;
+      case LangAS::opencl_local:
+        S +=3D "__local";
+        break;
+      case LangAS::opencl_constant:
+        S +=3D "__constant";
+        break;
+      default:
+        S +=3D "__attribute__((address_space(";
+        S +=3D llvm::utostr_32(addrspace);
+        S +=3D ")))";
+    }
   }
   if (Qualifiers::GC gc =3D getObjCGCAttr()) {
     if (!S.empty()) S +=3D ' ';
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/AST/=
VTableBuilder.cpp
--- a/head/contrib/llvm/tools/clang/lib/AST/VTableBuilder.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/AST/VTableBuilder.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -466,10 +466,10 @@
=20
 static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
                                     const CXXMethodDecl *RHS) {
-  ASTContext &C =3D LHS->getASTContext(); // TODO: thread this down
-  CanQual<FunctionProtoType>
-    LT =3D C.getCanonicalType(LHS->getType()).getAs<FunctionProtoType>(),
-    RT =3D C.getCanonicalType(RHS->getType()).getAs<FunctionProtoType>();
+  const FunctionProtoType *LT =3D
+    cast<FunctionProtoType>(LHS->getType().getCanonicalType());
+  const FunctionProtoType *RT =3D
+    cast<FunctionProtoType>(RHS->getType().getCanonicalType());
=20
   // Fast-path matches in the canonical types.
   if (LT =3D=3D RT) return true;
@@ -477,7 +477,7 @@
   // Force the signatures to match.  We can't rely on the overrides
   // list here because there isn't necessarily an inheritance
   // relationship between the two methods.
-  if (LT.getQualifiers() !=3D RT.getQualifiers() ||
+  if (LT->getTypeQuals() !=3D RT->getTypeQuals() ||
       LT->getNumArgs() !=3D RT->getNumArgs())
     return false;
   for (unsigned I =3D 0, E =3D LT->getNumArgs(); I !=3D E; ++I)
@@ -996,7 +996,7 @@
=20
     LayoutVTable();
=20
-    if (Context.getLangOptions().DumpVTableLayouts)
+    if (Context.getLangOpts().DumpVTableLayouts)
       dumpLayout(llvm::errs());
   }
=20
@@ -1580,7 +1580,7 @@
   LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
=20
   // -fapple-kext adds an extra entry at end of vtbl.
-  bool IsAppleKext =3D Context.getLangOptions().AppleKext;
+  bool IsAppleKext =3D Context.getLangOpts().AppleKext;
   if (IsAppleKext)
     Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero(=
)));
 }
@@ -2136,7 +2136,8 @@
       uint64_t VTableIndex =3D I->first;
       const std::string &MethodName =3D I->second;
=20
-      Out << llvm::format(" %4u | ", VTableIndex) << MethodName << '\n';
+      Out << llvm::format(" %4" PRIu64 " | ", VTableIndex) << MethodName
+          << '\n';
     }
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/CFG.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/CFG.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/CFG.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -12,7 +12,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "clang/Analysis/Support/SaveAndRestore.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/StmtVisitor.h"
@@ -250,7 +250,7 @@
   typedef BlockScopePosPair JumpSource;
=20
   ASTContext *Context;
-  llvm::OwningPtr<CFG> cfg;
+  OwningPtr<CFG> cfg;
=20
   CFGBlock *Block;
   CFGBlock *Succ;
@@ -286,6 +286,11 @@
   CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
   const Stmt *lastLookup;
=20
+  // Caches boolean evaluations of expressions to avoid multiple re-evalua=
tions
+  // during construction of branches for chained logical operators.
+  typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
+  CachedBoolEvalsTy CachedBoolEvals;
+
 public:
   explicit CFGBuilder(ASTContext *astContext,
                       const CFG::BuildOptions &buildOpts)=20
@@ -305,7 +310,6 @@
   // Visitors to walk an AST and construct the CFG.
   CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
   CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
-  CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
   CFGBlock *VisitBreakStmt(BreakStmt *B);
   CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
   CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
@@ -331,19 +335,23 @@
   CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
   CFGBlock *VisitDefaultStmt(DefaultStmt *D);
   CFGBlock *VisitDoStmt(DoStmt *D);
+  CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
   CFGBlock *VisitForStmt(ForStmt *F);
   CFGBlock *VisitGotoStmt(GotoStmt *G);
   CFGBlock *VisitIfStmt(IfStmt *I);
   CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
   CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
   CFGBlock *VisitLabelStmt(LabelStmt *L);
+  CFGBlock *VisitLambdaExpr(LambdaExpr *L);
   CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
   CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
+  CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
   CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
   CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
   CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
   CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
   CFGBlock *VisitReturnStmt(ReturnStmt *R);
+  CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
   CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
                                           AddStmtChoice asc);
   CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
@@ -354,6 +362,7 @@
   CFGBlock *Visit(Stmt *S, AddStmtChoice asc =3D AddStmtChoice::NotAlwaysA=
dd);
   CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
   CFGBlock *VisitChildren(Stmt *S);
+  CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
=20
   // Visitors to walk an AST and generate destructors of temporaries in
   // full expression.
@@ -431,18 +440,70 @@
       return false;
     return !S->isTypeDependent() &&=20
            !S->isValueDependent() &&
-           S->Evaluate(outResult, *Context);
+           S->EvaluateAsRValue(outResult, *Context);
   }
=20
   /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
   /// if we can evaluate to a known value, otherwise return -1.
   TryResult tryEvaluateBool(Expr *S) {
+    if (!BuildOpts.PruneTriviallyFalseEdges ||
+        S->isTypeDependent() || S->isValueDependent())
+      return TryResult();
+
+    if (BinaryOperator *Bop =3D dyn_cast<BinaryOperator>(S)) {
+      if (Bop->isLogicalOp()) {
+        // Check the cache first.
+        CachedBoolEvalsTy::iterator I =3D CachedBoolEvals.find(S);
+        if (I !=3D CachedBoolEvals.end())
+          return I->second; // already in map;
+
+        // Retrieve result at first, or the map might be updated.
+        TryResult Result =3D evaluateAsBooleanConditionNoCache(S);
+        CachedBoolEvals[S] =3D Result; // update or insert
+        return Result;
+      }
+    }
+
+    return evaluateAsBooleanConditionNoCache(S);
+  }
+
+  /// \brief Evaluate as boolean \param E without using the cache.
+  TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
+    if (BinaryOperator *Bop =3D dyn_cast<BinaryOperator>(E)) {
+      if (Bop->isLogicalOp()) {
+        TryResult LHS =3D tryEvaluateBool(Bop->getLHS());
+        if (LHS.isKnown()) {
+          // We were able to evaluate the LHS, see if we can get away with=
 not
+          // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
+          if (LHS.isTrue() =3D=3D (Bop->getOpcode() =3D=3D BO_LOr))
+            return LHS.isTrue();
+
+          TryResult RHS =3D tryEvaluateBool(Bop->getRHS());
+          if (RHS.isKnown()) {
+            if (Bop->getOpcode() =3D=3D BO_LOr)
+              return LHS.isTrue() || RHS.isTrue();
+            else
+              return LHS.isTrue() && RHS.isTrue();
+          }
+        } else {
+          TryResult RHS =3D tryEvaluateBool(Bop->getRHS());
+          if (RHS.isKnown()) {
+            // We can't evaluate the LHS; however, sometimes the result
+            // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
+            if (RHS.isTrue() =3D=3D (Bop->getOpcode() =3D=3D BO_LOr))
+              return RHS.isTrue();
+          }
+        }
+
+        return TryResult();
+      }
+    }
+
     bool Result;
-    if (!BuildOpts.PruneTriviallyFalseEdges ||
-        S->isTypeDependent() || S->isValueDependent() ||
-        !S->EvaluateAsBooleanCondition(Result, *Context))
-      return TryResult();
-    return Result;
+    if (E->EvaluateAsBooleanCondition(Result, *Context))
+      return Result;
+
+    return TryResult();
   }
  =20
 };
@@ -638,6 +699,52 @@
   return Block;
 }
=20
+/// \brief Retrieve the type of the temporary object whose lifetime was=20
+/// extended by a local reference with the given initializer.
+static QualType getReferenceInitTemporaryType(ASTContext &Context,
+                                              const Expr *Init) {
+  while (true) {
+    // Skip parentheses.
+    Init =3D Init->IgnoreParens();
+   =20
+    // Skip through cleanups.
+    if (const ExprWithCleanups *EWC =3D dyn_cast<ExprWithCleanups>(Init)) {
+      Init =3D EWC->getSubExpr();
+      continue;
+    }
+   =20
+    // Skip through the temporary-materialization expression.
+    if (const MaterializeTemporaryExpr *MTE
+          =3D dyn_cast<MaterializeTemporaryExpr>(Init)) {
+      Init =3D MTE->GetTemporaryExpr();
+      continue;
+    }
+   =20
+    // Skip derived-to-base and no-op casts.
+    if (const CastExpr *CE =3D dyn_cast<CastExpr>(Init)) {
+      if ((CE->getCastKind() =3D=3D CK_DerivedToBase ||
+           CE->getCastKind() =3D=3D CK_UncheckedDerivedToBase ||
+           CE->getCastKind() =3D=3D CK_NoOp) &&
+          Init->getType()->isRecordType()) {
+        Init =3D CE->getSubExpr();
+        continue;
+      }
+    }
+   =20
+    // Skip member accesses into rvalues.
+    if (const MemberExpr *ME =3D dyn_cast<MemberExpr>(Init)) {
+      if (!ME->isArrow() && ME->getBase()->isRValue()) {
+        Init =3D ME->getBase();
+        continue;
+      }
+    }
+   =20
+    break;
+  }
+
+  return Init->getType();
+}
+ =20
 /// addAutomaticObjDtors - Add to current block automatic objects destruct=
ors
 /// for objects in range of local scope positions. Use S as trigger statem=
ent
 /// for destructors.
@@ -649,8 +756,6 @@
   if (B =3D=3D E)
     return;
=20
-  CFGBlock::iterator InsertPos;
-
   // We need to append the destructors in reverse order, but any one of th=
em
   // may be a no-return destructor which changes the CFG. As a result, buf=
fer
   // this sequence up and replay them in reverse order when appending onto=
 the
@@ -666,9 +771,13 @@
     // If this destructor is marked as a no-return destructor, we need to
     // create a new block for the destructor which does not have as a succ=
essor
     // anything built thus far: control won't flow out of this block.
-    QualType Ty =3D (*I)->getType().getNonReferenceType();
-    if (const ArrayType *AT =3D Context->getAsArrayType(Ty))
-      Ty =3D AT->getElementType();
+    QualType Ty;
+    if ((*I)->getType()->isReferenceType()) {
+      Ty =3D getReferenceInitTemporaryType(*Context, (*I)->getInit());
+    } else {
+      Ty =3D Context->getBaseElementType((*I)->getType());
+    }
+   =20
     const CXXDestructorDecl *Dtor =3D Ty->getAsCXXRecordDecl()->getDestruc=
tor();
     if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr())
       Block =3D createNoReturnBlock();
@@ -798,16 +907,15 @@
=20
   // Check for const references bound to temporary. Set type to pointee.
   QualType QT =3D VD->getType();
-  if (const ReferenceType* RT =3D QT.getTypePtr()->getAs<ReferenceType>())=
 {
-    QT =3D RT->getPointeeType();
-    if (!QT.isConstQualified())
-      return Scope;
+  if (QT.getTypePtr()->isReferenceType()) {
     if (!VD->extendsLifetimeOfTemporary())
       return Scope;
+
+    QT =3D getReferenceInitTemporaryType(*Context, VD->getInit());
   }
=20
   // Check for constant size array. Set type to array element type.
-  if (const ConstantArrayType *AT =3D Context->getAsConstantArrayType(QT))=
 {
+  while (const ConstantArrayType *AT =3D Context->getAsConstantArrayType(Q=
T)) {
     if (AT->getSize() =3D=3D 0)
       return Scope;
     QT =3D AT->getElementType();
@@ -878,7 +986,7 @@
       return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
=20
     case Stmt::BlockExprClass:
-      return VisitBlockExpr(cast<BlockExpr>(S), asc);
+      return VisitNoRecurse(cast<Expr>(S), asc);
=20
     case Stmt::BreakStmtClass:
       return VisitBreakStmt(cast<BreakStmt>(S));
@@ -886,6 +994,7 @@
     case Stmt::CallExprClass:
     case Stmt::CXXOperatorCallExprClass:
     case Stmt::CXXMemberCallExprClass:
+    case Stmt::UserDefinedLiteralClass:
       return VisitCallExpr(cast<CallExpr>(S), asc);
=20
     case Stmt::CaseStmtClass:
@@ -957,12 +1066,21 @@
     case Stmt::LabelStmtClass:
       return VisitLabelStmt(cast<LabelStmt>(S));
=20
+    case Stmt::LambdaExprClass:
+      return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
+
     case Stmt::MemberExprClass:
       return VisitMemberExpr(cast<MemberExpr>(S), asc);
=20
+    case Stmt::NullStmtClass:
+      return Block;
+
     case Stmt::ObjCAtCatchStmtClass:
       return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
=20
+    case Stmt::ObjCAutoreleasePoolStmtClass:
+    return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
+
     case Stmt::ObjCAtSynchronizedStmtClass:
       return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
=20
@@ -975,9 +1093,12 @@
     case Stmt::ObjCForCollectionStmtClass:
       return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
=20
-    case Stmt::NullStmtClass:
+    case Stmt::OpaqueValueExprClass:
       return Block;
=20
+    case Stmt::PseudoObjectExprClass:
+      return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
+
     case Stmt::ReturnStmtClass:
       return VisitReturnStmt(cast<ReturnStmt>(S));
=20
@@ -1068,6 +1189,10 @@
       RHSBlock =3D createBlock();
     }
=20
+    // Generate the blocks for evaluating the LHS.
+    Block =3D LHSBlock;
+    CFGBlock *EntryLHSBlock =3D addStmt(B->getLHS());
+
     // See if this is a known constant.
     TryResult KnownVal =3D tryEvaluateBool(B->getLHS());
     if (KnownVal.isKnown() && (B->getOpcode() =3D=3D BO_LOr))
@@ -1083,9 +1208,7 @@
       addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
     }
=20
-    // Generate the blocks for evaluating the LHS.
-    Block =3D LHSBlock;
-    return addStmt(B->getLHS());
+    return EntryLHSBlock;
   }
=20
   if (B->getOpcode() =3D=3D BO_Comma) { // ,
@@ -1117,7 +1240,7 @@
   return (LBlock ? LBlock : RBlock);
 }
=20
-CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
+CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
   if (asc.alwaysAdd(*this, E)) {
     autoCreateBlock();
     appendStmt(Block, E);
@@ -1180,7 +1303,7 @@
   bool AddEHEdge =3D false;
=20
   // Languages without exceptions are assumed to not throw.
-  if (Context->getLangOptions().Exceptions) {
+  if (Context->getLangOpts().Exceptions) {
     if (BuildOpts.AddEHEdges)
       AddEHEdge =3D true;
   }
@@ -1405,14 +1528,24 @@
=20
   autoCreateBlock();
   appendStmt(Block, DS);
+ =20
+  // Keep track of the last non-null block, as 'Block' can be nulled out
+  // if the initializer expression is something like a 'while' in a
+  // statement-expression.
+  CFGBlock *LastBlock =3D Block;
=20
   if (Init) {
-    if (HasTemporaries)
+    if (HasTemporaries) {
       // For expression with temporaries go directly to subexpression to o=
mit
       // generating destructors for the second time.
-      Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
-    else
-      Visit(Init);
+      ExprWithCleanups *EC =3D cast<ExprWithCleanups>(Init);
+      if (CFGBlock *newBlock =3D Visit(EC->getSubExpr()))
+        LastBlock =3D newBlock;
+    }
+    else {
+      if (CFGBlock *newBlock =3D Visit(Init))
+        LastBlock =3D newBlock;
+    }
   }
=20
   // If the type of VD is a VLA, then we must process its size expressions.
@@ -1424,7 +1557,7 @@
   if (ScopePos && VD =3D=3D *ScopePos)
     ++ScopePos;
=20
-  return Block;
+  return Block ? Block : LastBlock;
 }
=20
 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
@@ -1588,6 +1721,19 @@
   return LabelBlock;
 }
=20
+CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
+  CFGBlock *LastBlock =3D VisitNoRecurse(E, asc);
+  for (LambdaExpr::capture_init_iterator it =3D E->capture_init_begin(),
+       et =3D E->capture_init_end(); it !=3D et; ++it) {
+    if (Expr *Init =3D *it) {
+      CFGBlock *Tmp =3D Visit(Init);
+      if (Tmp !=3D 0)
+        LastBlock =3D Tmp;
+    }
+  }
+  return LastBlock;
+}
+ =20
 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
   // Goto is a control-flow statement.  Thus we stop processing the current
   // block and create a new one.
@@ -1875,6 +2021,12 @@
   return addStmt(S->getCollection());
 }
=20
+CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt=
 *S) {
+  // Inline the body.
+  return addStmt(S->getSubStmt());
+  // TODO: consider adding cleanups for the end of @autoreleasepool scope.
+}
+
 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *=
S) {
   // FIXME: Add locking 'primitives' to CFG for @synchronized.
=20
@@ -1904,6 +2056,31 @@
   return NYS();
 }
=20
+CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
+  autoCreateBlock();
+
+  // Add the PseudoObject as the last thing.
+  appendStmt(Block, E);
+
+  CFGBlock *lastBlock =3D Block; =20
+
+  // Before that, evaluate all of the semantics in order.  In
+  // CFG-land, that means appending them in reverse order.
+  for (unsigned i =3D E->getNumSemanticExprs(); i !=3D 0; ) {
+    Expr *Semantic =3D E->getSemanticExpr(--i);
+
+    // If the semantic is an opaque value, we're being asked to bind
+    // it to its source expression.
+    if (OpaqueValueExpr *OVE =3D dyn_cast<OpaqueValueExpr>(Semantic))
+      Semantic =3D OVE->getSourceExpr();
+
+    if (CFGBlock *B =3D Visit(Semantic))
+      lastBlock =3D B;
+  }
+
+  return lastBlock;
+}
+
 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
   CFGBlock *LoopSuccessor =3D NULL;
=20
@@ -2530,9 +2707,18 @@
   CFGBlock *CatchBlock =3D Block;
   if (!CatchBlock)
     CatchBlock =3D createBlock();
-
+ =20
+  // CXXCatchStmt is more than just a label.  They have semantic meaning
+  // as well, as they implicitly "initialize" the catch variable.  Add
+  // it to the CFG as a CFGElement so that the control-flow of these
+  // semantics gets captured.
+  appendStmt(CatchBlock, CS);
+
+  // Also add the CXXCatchStmt as a label, to mirror handling of regular
+  // labels.
   CatchBlock->setLabel(CS);
=20
+  // Bail out if the CFG is bad.
   if (badCFG)
     return 0;
=20
@@ -2687,8 +2873,7 @@
 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
                                             AddStmtChoice asc) {
   autoCreateBlock();
-  if (!C->isElidable())
-    appendStmt(Block, C);
+  appendStmt(Block, C);
=20
   return VisitChildren(C);
 }
@@ -2958,7 +3143,7 @@
=20
   // Create the block.
   CFGBlock *Mem =3D getAllocator().Allocate<CFGBlock>();
-  new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
+  new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
   Blocks.push_back(Mem, BlkBVC);
=20
   // If this is the first block, set it as the Entry and Exit.
@@ -2989,7 +3174,7 @@
       const VarDecl *var =3D cast<CFGAutomaticObjDtor>(this)->getVarDecl();
       QualType ty =3D var->getType();
       ty =3D ty.getNonReferenceType();
-      if (const ArrayType *arrayType =3D astContext.getAsArrayType(ty)) {
+      while (const ArrayType *arrayType =3D astContext.getAsArrayType(ty))=
 {
         ty =3D arrayType->getElementType();
       }
       const RecordType *recordType =3D ty->getAs<RecordType>();
@@ -3010,7 +3195,6 @@
       return 0;
   }
   llvm_unreachable("getKind() returned bogus value");
-  return 0;
 }
=20
 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
@@ -3402,9 +3586,19 @@
=20
     if (isa<CXXOperatorCallExpr>(S)) {
       OS << " (OperatorCall)";
-    } else if (isa<CXXBindTemporaryExpr>(S)) {
+    }
+    else if (isa<CXXBindTemporaryExpr>(S)) {
       OS << " (BindTemporary)";
     }
+    else if (const CXXConstructExpr *CCE =3D dyn_cast<CXXConstructExpr>(S)=
) {
+      OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
+    }
+    else if (const CastExpr *CE =3D dyn_cast<CastExpr>(S)) {
+      OS << " (" << CE->getStmtClassName() << ", "
+         << CE->getCastKindName()
+         << ", " << CE->getType().getAsString()
+         << ")";
+    }
=20
     // Expressions need a newline.
     if (isa<Expr>(S))
@@ -3463,27 +3657,35 @@
=20
 static void print_block(raw_ostream &OS, const CFG* cfg,
                         const CFGBlock &B,
-                        StmtPrinterHelper* Helper, bool print_edges) {
-
-  if (Helper) Helper->setBlockID(B.getBlockID());
+                        StmtPrinterHelper* Helper, bool print_edges,
+                        bool ShowColors) {
+
+  if (Helper)
+    Helper->setBlockID(B.getBlockID());
=20
   // Print the header.
-  OS << "\n [ B" << B.getBlockID();
+  if (ShowColors)
+    OS.changeColor(raw_ostream::YELLOW, true);
+ =20
+  OS << "\n [B" << B.getBlockID();
=20
   if (&B =3D=3D &cfg->getEntry())
-    OS << " (ENTRY) ]\n";
+    OS << " (ENTRY)]\n";
   else if (&B =3D=3D &cfg->getExit())
-    OS << " (EXIT) ]\n";
+    OS << " (EXIT)]\n";
   else if (&B =3D=3D cfg->getIndirectGotoBlock())
-    OS << " (INDIRECT GOTO DISPATCH) ]\n";
+    OS << " (INDIRECT GOTO DISPATCH)]\n";
   else
-    OS << " ]\n";
+    OS << "]\n";
+ =20
+  if (ShowColors)
+    OS.resetColor();
=20
   // Print the label of this block.
   if (Stmt *Label =3D const_cast<Stmt*>(B.getLabel())) {
=20
     if (print_edges)
-      OS << "    ";
+      OS << "  ";
=20
     if (LabelStmt *L =3D dyn_cast<LabelStmt>(Label))
       OS << L->getName();
@@ -3521,22 +3723,22 @@
=20
     // Print the statement # in the basic block and the statement itself.
     if (print_edges)
-      OS << "    ";
+      OS << " ";
=20
     OS << llvm::format("%3d", j) << ": ";
=20
     if (Helper)
       Helper->setStmtID(j);
=20
-    print_elem(OS,Helper,*I);
+    print_elem(OS, Helper, *I);
   }
=20
   // Print the terminator of this block.
   if (B.getTerminator()) {
-    if (print_edges)
-      OS << "    ";
-
-    OS << "  T: ";
+    if (ShowColors)
+      OS.changeColor(raw_ostream::GREEN);
+
+    OS << "   T: ";
=20
     if (Helper) Helper->setBlockID(-1);
=20
@@ -3544,54 +3746,86 @@
                                      PrintingPolicy(Helper->getLangOpts())=
);
     TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt()));
     OS << '\n';
+   =20
+    if (ShowColors)
+      OS.resetColor();
   }
=20
   if (print_edges) {
     // Print the predecessors of this block.
-    OS << "    Predecessors (" << B.pred_size() << "):";
-    unsigned i =3D 0;
-
-    for (CFGBlock::const_pred_iterator I =3D B.pred_begin(), E =3D B.pred_=
end();
-         I !=3D E; ++I, ++i) {
-
-      if (i =3D=3D 8 || (i-8) =3D=3D 0)
-        OS << "\n     ";
-
-      OS << " B" << (*I)->getBlockID();
+    if (!B.pred_empty()) {
+      const raw_ostream::Colors Color =3D raw_ostream::BLUE;
+      if (ShowColors)
+        OS.changeColor(Color);
+      OS << "   Preds " ;
+      if (ShowColors)
+        OS.resetColor();
+      OS << '(' << B.pred_size() << "):";
+      unsigned i =3D 0;
+
+      if (ShowColors)
+        OS.changeColor(Color);
+     =20
+      for (CFGBlock::const_pred_iterator I =3D B.pred_begin(), E =3D B.pre=
d_end();
+           I !=3D E; ++I, ++i) {
+
+        if (i =3D=3D 8 || (i-8) =3D=3D 0)
+          OS << "\n     ";
+
+        OS << " B" << (*I)->getBlockID();
+      }
+     =20
+      if (ShowColors)
+        OS.resetColor();
+
+      OS << '\n';
     }
=20
-    OS << '\n';
-
     // Print the successors of this block.
-    OS << "    Successors (" << B.succ_size() << "):";
-    i =3D 0;
-
-    for (CFGBlock::const_succ_iterator I =3D B.succ_begin(), E =3D B.succ_=
end();
-         I !=3D E; ++I, ++i) {
-
-      if (i =3D=3D 8 || (i-8) % 10 =3D=3D 0)
-        OS << "\n    ";
-
-      if (*I)
-        OS << " B" << (*I)->getBlockID();
-      else
-        OS  << " NULL";
+    if (!B.succ_empty()) {
+      const raw_ostream::Colors Color =3D raw_ostream::MAGENTA;
+      if (ShowColors)
+        OS.changeColor(Color);
+      OS << "   Succs ";
+      if (ShowColors)
+        OS.resetColor();
+      OS << '(' << B.succ_size() << "):";
+      unsigned i =3D 0;
+
+      if (ShowColors)
+        OS.changeColor(Color);
+
+      for (CFGBlock::const_succ_iterator I =3D B.succ_begin(), E =3D B.suc=
c_end();
+           I !=3D E; ++I, ++i) {
+
+        if (i =3D=3D 8 || (i-8) % 10 =3D=3D 0)
+          OS << "\n    ";
+
+        if (*I)
+          OS << " B" << (*I)->getBlockID();
+        else
+          OS  << " NULL";
+      }
+     =20
+      if (ShowColors)
+        OS.resetColor();
+      OS << '\n';
     }
-
-    OS << '\n';
   }
 }
=20
=20
 /// dump - A simple pretty printer of a CFG that outputs to stderr.
-void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
+void CFG::dump(const LangOptions &LO, bool ShowColors) const {
+  print(llvm::errs(), LO, ShowColors);
+}
=20
 /// print - A simple pretty printer of a CFG that outputs to an ostream.
-void CFG::print(raw_ostream &OS, const LangOptions &LO) const {
+void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) c=
onst {
   StmtPrinterHelper Helper(this, LO);
=20
   // Print the entry block.
-  print_block(OS, this, getEntry(), &Helper, true);
+  print_block(OS, this, getEntry(), &Helper, true, ShowColors);
=20
   // Iterate through the CFGBlocks and print them one by one.
   for (const_iterator I =3D Blocks.begin(), E =3D Blocks.end() ; I !=3D E =
; ++I) {
@@ -3599,25 +3833,28 @@
     if (&(**I) =3D=3D &getEntry() || &(**I) =3D=3D &getExit())
       continue;
=20
-    print_block(OS, this, **I, &Helper, true);
+    print_block(OS, this, **I, &Helper, true, ShowColors);
   }
=20
   // Print the exit block.
-  print_block(OS, this, getExit(), &Helper, true);
+  print_block(OS, this, getExit(), &Helper, true, ShowColors);
+  OS << '\n';
   OS.flush();
 }
=20
 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
-void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
-  print(llvm::errs(), cfg, LO);
+void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
+                    bool ShowColors) const {
+  print(llvm::errs(), cfg, LO, ShowColors);
 }
=20
 /// print - A simple pretty printer of a CFGBlock that outputs to an ostre=
am.
 ///   Generally this will only be called from CFG::print.
 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
-                     const LangOptions &LO) const {
+                     const LangOptions &LO, bool ShowColors) const {
   StmtPrinterHelper Helper(cfg, LO);
-  print_block(OS, cfg, *this, &Helper, true);
+  print_block(OS, cfg, *this, &Helper, true, ShowColors);
+  OS << '\n';
 }
=20
 /// printTerminator - A simple pretty printer of the terminator of a CFGBl=
ock.
@@ -3714,7 +3951,7 @@
 #ifndef NDEBUG
     std::string OutSStr;
     llvm::raw_string_ostream Out(OutSStr);
-    print_block(Out,Graph, *Node, GraphHelper, false);
+    print_block(Out,Graph, *Node, GraphHelper, false, false);
     std::string& OutStr =3D Out.str();
=20
     if (OutStr[0] =3D=3D '\n') OutStr.erase(OutStr.begin());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/CocoaConventions.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/CocoaConventions.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/CocoaConventions.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -20,47 +20,6 @@
 using namespace clang;
 using namespace ento;
=20
-// The "fundamental rule" for naming conventions of methods:
-//  (url broken into two lines)
-//  http://developer.apple.com/documentation/Cocoa/Conceptual/
-//     MemoryMgmt/Tasks/MemoryManagementRules.html
-//
-// "You take ownership of an object if you create it using a method whose =
name
-//  begins with "alloc" or "new" or contains "copy" (for example, alloc,
-//  newObject, or mutableCopy), or if you send it a retain message. You are
-//  responsible for relinquishing ownership of objects you own using relea=
se
-//  or autorelease. Any other time you receive an object, you must
-//  not release it."
-//
-
-cocoa::NamingConvention cocoa::deriveNamingConvention(Selector S,=20
-                                                    const ObjCMethodDecl *=
MD) {
-  switch (MD && MD->hasAttr<ObjCMethodFamilyAttr>()? MD->getMethodFamily()=20
-                                                   : S.getMethodFamily()) {
-  case OMF_None:
-  case OMF_autorelease:
-  case OMF_dealloc:
-  case OMF_finalize:
-  case OMF_release:
-  case OMF_retain:
-  case OMF_retainCount:
-  case OMF_self:
-  case OMF_performSelector:
-    return NoConvention;
-
-  case OMF_init:
-    return InitRule;
-
-  case OMF_alloc:
-  case OMF_copy:
-  case OMF_mutableCopy:
-  case OMF_new:
-    return CreateRule;
-  }
-  llvm_unreachable("unexpected naming convention");
-  return NoConvention;
-}
-
 bool cocoa::isRefType(QualType RetTy, StringRef Prefix,
                       StringRef Name) {
   // Recursively walk the typedef stack, allowing typedefs of reference ty=
pes.
@@ -68,7 +27,9 @@
     StringRef TDName =3D TD->getDecl()->getIdentifier()->getName();
     if (TDName.startswith(Prefix) && TDName.endswith("Ref"))
       return true;
-   =20
+    // XPC unfortunately uses CF-style function names, but aren't CF types.
+    if (TDName.startswith("xpc_"))
+      return false;
     RetTy =3D TD->getDecl()->getUnderlyingType();
   }
  =20
@@ -115,7 +76,7 @@
  =20
   // Assume that anything declared with a forward declaration and no
   // @interface subclasses NSObject.
-  if (ID->isForwardDecl())
+  if (!ID->hasDefinition())
     return true;
  =20
   for ( ; ID ; ID =3D ID->getSuperClass())
@@ -174,6 +135,4 @@
     // If we matched a lowercase character, it isn't the end of the
     // word.  Keep scanning.
   }
- =20
-  return false;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/FormatString.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/FormatString.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/FormatString.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -13,6 +13,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "FormatStringParsing.h"
+#include "clang/Basic/LangOptions.h"
=20
 using clang::analyze_format_string::ArgTypeResult;
 using clang::analyze_format_string::FormatStringHandler;
@@ -155,6 +156,9 @@
   }
=20
   if (Amt.getHowSpecified() =3D=3D OptionalAmount::Constant && *(I++) =3D=
=3D '$') {
+    // Warn that positional arguments are non-standard.
+    H.HandlePosition(Start, I - Start);
+
     // Special case: '%0$', since this is an easy mistake.
     if (Amt.getConstantAmount() =3D=3D 0) {
       H.HandleZeroPosition(Start, I - Start);
@@ -175,7 +179,9 @@
 bool
 clang::analyze_format_string::ParseLengthModifier(FormatSpecifier &FS,
                                                   const char *&I,
-                                                  const char *E) {
+                                                  const char *E,
+                                                  const LangOptions &LO,
+                                                  bool IsScanf) {
   LengthModifier::Kind lmKind =3D LengthModifier::None;
   const char *lmPosition =3D I;
   switch (*I) {
@@ -183,19 +189,39 @@
       return false;
     case 'h':
       ++I;
-      lmKind =3D (I !=3D E && *I =3D=3D 'h') ?
-      ++I, LengthModifier::AsChar : LengthModifier::AsShort;
+      lmKind =3D (I !=3D E && *I =3D=3D 'h') ? (++I, LengthModifier::AsCha=
r)
+                                     : LengthModifier::AsShort;
       break;
     case 'l':
       ++I;
-      lmKind =3D (I !=3D E && *I =3D=3D 'l') ?
-      ++I, LengthModifier::AsLongLong : LengthModifier::AsLong;
+      lmKind =3D (I !=3D E && *I =3D=3D 'l') ? (++I, LengthModifier::AsLon=
gLong)
+                                     : LengthModifier::AsLong;
       break;
     case 'j': lmKind =3D LengthModifier::AsIntMax;     ++I; break;
     case 'z': lmKind =3D LengthModifier::AsSizeT;      ++I; break;
     case 't': lmKind =3D LengthModifier::AsPtrDiff;    ++I; break;
     case 'L': lmKind =3D LengthModifier::AsLongDouble; ++I; break;
-    case 'q': lmKind =3D LengthModifier::AsLongLong;   ++I; break;
+    case 'q': lmKind =3D LengthModifier::AsQuad;       ++I; break;
+    case 'a':
+      if (IsScanf && !LO.C99 && !LO.CPlusPlus0x) {
+        // For scanf in C90, look at the next character to see if this sho=
uld
+        // be parsed as the GNU extension 'a' length modifier. If not, this
+        // will be parsed as a conversion specifier.
+        ++I;
+        if (I !=3D E && (*I =3D=3D 's' || *I =3D=3D 'S' || *I =3D=3D '['))=
 {
+          lmKind =3D LengthModifier::AsAllocate;
+          break;
+        }
+        --I;
+      }
+      return false;
+    case 'm':
+      if (IsScanf) {
+        lmKind =3D LengthModifier::AsMAllocate;
+        ++I;
+        break;
+      }
+      return false;
   }
   LengthModifier lm(lmPosition, lmKind);
   FS.setLengthModifier(lm);
@@ -213,7 +239,21 @@
=20
     case UnknownTy:
       return true;
-
+     =20
+    case AnyCharTy: {
+      if (const BuiltinType *BT =3D argTy->getAs<BuiltinType>())
+        switch (BT->getKind()) {
+          default:
+            break;
+          case BuiltinType::Char_S:
+          case BuiltinType::SChar:
+          case BuiltinType::UChar:
+          case BuiltinType::Char_U:
+            return true;           =20
+        }
+      return false;
+    }
+     =20
     case SpecificTy: {
       argTy =3D C.getCanonicalType(argTy).getUnqualifiedType();
       if (T =3D=3D argTy)
@@ -297,15 +337,28 @@
=20
     case CPointerTy:
       return argTy->isPointerType() || argTy->isObjCObjectPointerType() ||
-        argTy->isNullPtrType();
+             argTy->isBlockPointerType() || argTy->isNullPtrType();
=20
-    case ObjCPointerTy:
-      return argTy->getAs<ObjCObjectPointerType>() !=3D NULL;
+    case ObjCPointerTy: {
+      if (argTy->getAs<ObjCObjectPointerType>() ||
+          argTy->getAs<BlockPointerType>())
+        return true;
+     =20
+      // Handle implicit toll-free bridging.
+      if (const PointerType *PT =3D argTy->getAs<PointerType>()) {
+        // Things such as CFTypeRef are really just opaque pointers
+        // to C structs representing CF types that can often be bridged
+        // to Objective-C objects.  Since the compiler doesn't know which
+        // structs can be toll-free bridged, we just accept them all.
+        QualType pointee =3D PT->getPointeeType();
+        if (pointee->getAsStructureType() || pointee->isVoidType())
+          return true;
+      }
+      return false;     =20
+    }
   }
=20
-  // FIXME: Should be unreachable, but Clang is currently emitting
-  // a warning.
-  return false;
+  llvm_unreachable("Invalid ArgTypeResult Kind!");
 }
=20
 QualType ArgTypeResult::getRepresentativeType(ASTContext &C) const {
@@ -314,6 +367,8 @@
       llvm_unreachable("No representative type for Invalid ArgTypeResult");
     case UnknownTy:
       return QualType();
+    case AnyCharTy:
+      return C.CharTy;
     case SpecificTy:
       return T;
     case CStrTy:
@@ -330,11 +385,17 @@
     }
   }
=20
-  // FIXME: Should be unreachable, but Clang is currently emitting
-  // a warning.
-  return QualType();
+  llvm_unreachable("Invalid ArgTypeResult Kind!");
 }
=20
+std::string ArgTypeResult::getRepresentativeTypeName(ASTContext &C) const {
+  std::string S =3D getRepresentativeType(C).getAsString();
+  if (Name && S !=3D Name)
+    return std::string("'") + Name + "' (aka '" + S + "')";
+  return std::string("'") + S + "'";
+}
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Methods on OptionalAmount.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -359,6 +420,8 @@
     return "l";
   case AsLongLong:
     return "ll";
+  case AsQuad:
+    return "q";
   case AsIntMax:
     return "j";
   case AsSizeT:
@@ -367,6 +430,10 @@
     return "t";
   case AsLongDouble:
     return "L";
+  case AsAllocate:
+    return "a";
+  case AsMAllocate:
+    return "m";
   case None:
     return "";
   }
@@ -374,6 +441,52 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Methods on ConversionSpecifier.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+const char *ConversionSpecifier::toString() const {
+  switch (kind) {
+  case dArg: return "d";
+  case iArg: return "i";
+  case oArg: return "o";
+  case uArg: return "u";
+  case xArg: return "x";
+  case XArg: return "X";
+  case fArg: return "f";
+  case FArg: return "F";
+  case eArg: return "e";
+  case EArg: return "E";
+  case gArg: return "g";
+  case GArg: return "G";
+  case aArg: return "a";
+  case AArg: return "A";
+  case cArg: return "c";
+  case sArg: return "s";
+  case pArg: return "p";
+  case nArg: return "n";
+  case PercentArg:  return "%";
+  case ScanListArg: return "[";
+  case InvalidSpecifier: return NULL;
+
+  // MacOS X unicode extensions.
+  case CArg: return "C";
+  case SArg: return "S";
+
+  // Objective-C specific specifiers.
+  case ObjCObjArg: return "@";
+
+  // FreeBSD specific specifiers.
+  case bArg: return "b";
+  case DArg: return "D";
+  case rArg: return "r";
+
+  // GlibC specific specifiers.
+  case PrintErrno: return "m";
+  }
+  return NULL;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Methods on OptionalAmount.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -398,19 +511,16 @@
   }
 }
=20
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// Methods on ConversionSpecifier.
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
 bool FormatSpecifier::hasValidLengthModifier() const {
   switch (LM.getKind()) {
     case LengthModifier::None:
       return true;
      =20
-        // Handle most integer flags
+    // Handle most integer flags
     case LengthModifier::AsChar:
     case LengthModifier::AsShort:
     case LengthModifier::AsLongLong:
+    case LengthModifier::AsQuad:
     case LengthModifier::AsIntMax:
     case LengthModifier::AsSizeT:
     case LengthModifier::AsPtrDiff:
@@ -428,7 +538,7 @@
           return false;
       }
      =20
-        // Handle 'l' flag
+    // Handle 'l' flag
     case LengthModifier::AsLong:
       switch (CS.getKind()) {
         case ConversionSpecifier::dArg:
@@ -449,6 +559,7 @@
         case ConversionSpecifier::cArg:
         case ConversionSpecifier::sArg:
         case ConversionSpecifier::rArg:
+        case ConversionSpecifier::ScanListArg:
           return true;
         default:
           return false;
@@ -465,11 +576,113 @@
         case ConversionSpecifier::gArg:
         case ConversionSpecifier::GArg:
           return true;
+        // GNU extension.
+        case ConversionSpecifier::dArg:
+        case ConversionSpecifier::iArg:
+        case ConversionSpecifier::oArg:
+        case ConversionSpecifier::uArg:
+        case ConversionSpecifier::xArg:
+        case ConversionSpecifier::XArg:
+          return true;
+        default:
+          return false;
+      }
+
+    case LengthModifier::AsAllocate:
+      switch (CS.getKind()) {
+        case ConversionSpecifier::sArg:
+        case ConversionSpecifier::SArg:
+        case ConversionSpecifier::ScanListArg:
+          return true;
+        default:
+          return false;
+      }
+
+    case LengthModifier::AsMAllocate:
+      switch (CS.getKind()) {
+        case ConversionSpecifier::cArg:
+        case ConversionSpecifier::CArg:
+        case ConversionSpecifier::sArg:
+        case ConversionSpecifier::SArg:
+        case ConversionSpecifier::ScanListArg:
+          return true;
         default:
           return false;
       }
   }
-  return false;
+  llvm_unreachable("Invalid LengthModifier Kind!");
 }
=20
+bool FormatSpecifier::hasStandardLengthModifier() const {
+  switch (LM.getKind()) {
+    case LengthModifier::None:
+    case LengthModifier::AsChar:
+    case LengthModifier::AsShort:
+    case LengthModifier::AsLong:
+    case LengthModifier::AsLongLong:
+    case LengthModifier::AsIntMax:
+    case LengthModifier::AsSizeT:
+    case LengthModifier::AsPtrDiff:
+    case LengthModifier::AsLongDouble:
+      return true;
+    case LengthModifier::AsAllocate:
+    case LengthModifier::AsMAllocate:
+    case LengthModifier::AsQuad:
+      return false;
+  }
+  llvm_unreachable("Invalid LengthModifier Kind!");
+}
=20
+bool FormatSpecifier::hasStandardConversionSpecifier(const LangOptions &La=
ngOpt) const {
+  switch (CS.getKind()) {
+    case ConversionSpecifier::cArg:
+    case ConversionSpecifier::dArg:
+    case ConversionSpecifier::iArg:
+    case ConversionSpecifier::oArg:
+    case ConversionSpecifier::uArg:
+    case ConversionSpecifier::xArg:
+    case ConversionSpecifier::XArg:
+    case ConversionSpecifier::fArg:
+    case ConversionSpecifier::FArg:
+    case ConversionSpecifier::eArg:
+    case ConversionSpecifier::EArg:
+    case ConversionSpecifier::gArg:
+    case ConversionSpecifier::GArg:
+    case ConversionSpecifier::aArg:
+    case ConversionSpecifier::AArg:
+    case ConversionSpecifier::sArg:
+    case ConversionSpecifier::pArg:
+    case ConversionSpecifier::nArg:
+    case ConversionSpecifier::ObjCObjArg:
+    case ConversionSpecifier::ScanListArg:
+    case ConversionSpecifier::PercentArg:
+      return true;
+    case ConversionSpecifier::CArg:
+    case ConversionSpecifier::SArg:
+      return LangOpt.ObjC1 || LangOpt.ObjC2;
+    case ConversionSpecifier::InvalidSpecifier:
+    case ConversionSpecifier::bArg:
+    case ConversionSpecifier::DArg:
+    case ConversionSpecifier::rArg:
+    case ConversionSpecifier::PrintErrno:
+      return false;
+  }
+  llvm_unreachable("Invalid ConversionSpecifier Kind!");
+}
+
+bool FormatSpecifier::hasStandardLengthConversionCombination() const {
+  if (LM.getKind() =3D=3D LengthModifier::AsLongDouble) {
+    switch(CS.getKind()) {
+        case ConversionSpecifier::dArg:
+        case ConversionSpecifier::iArg:
+        case ConversionSpecifier::oArg:
+        case ConversionSpecifier::uArg:
+        case ConversionSpecifier::xArg:
+        case ConversionSpecifier::XArg:
+          return false;
+        default:
+          return true;
+    }
+  }
+  return true;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/FormatStringParsing.h
--- a/head/contrib/llvm/tools/clang/lib/Analysis/FormatStringParsing.h	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/FormatStringParsing.h	Tue =
Apr 17 11:51:51 2012 +0300
@@ -8,6 +8,8 @@
=20
 namespace clang {
=20
+class LangOptions;
+
 template <typename T>
 class UpdateOnReturn {
   T &ValueToUpdate;
@@ -42,7 +44,8 @@
=20
 /// Returns true if a LengthModifier was parsed and installed in the
 /// FormatSpecifier& argument, and false otherwise.
-bool ParseLengthModifier(FormatSpecifier &FS, const char *&Beg, const char=
 *E);
+bool ParseLengthModifier(FormatSpecifier &FS, const char *&Beg, const char=
 *E,
+                         const LangOptions &LO, bool IsScanf =3D false);
  =20
 template <typename T> class SpecifierResult {
   T FS;
@@ -69,4 +72,3 @@
 } // end clang namespace
=20
 #endif
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/LiveVariables.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/LiveVariables.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/LiveVariables.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,4 +1,6 @@
 #include "clang/Analysis/Analyses/LiveVariables.h"
+#include "clang/Analysis/Analyses/PostOrderCFGView.h"
+
 #include "clang/AST/Stmt.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/AnalysisContext.h"
@@ -15,113 +17,14 @@
=20
 namespace {
=20
-// FIXME: This is copy-pasted from ThreadSafety.c.  I wanted a patch that
-// contained working code before refactoring the implementation of both
-// files.
-class CFGBlockSet {
-  llvm::BitVector VisitedBlockIDs;
- =20
-public:
-  // po_iterator requires this iterator, but the only interface needed is =
the
-  // value_type typedef.
-  struct iterator {
-    typedef const CFGBlock *value_type;
-  };
- =20
-  CFGBlockSet() {}
-  CFGBlockSet(const CFG *G) : VisitedBlockIDs(G->getNumBlockIDs(), false) =
{}
- =20
-  /// \brief Set the bit associated with a particular CFGBlock.
-  /// This is the important method for the SetType template parameter.
-  bool insert(const CFGBlock *Block) {
-    // Note that insert() is called by po_iterator, which doesn't check to=
 make
-    // sure that Block is non-null.  Moreover, the CFGBlock iterator will
-    // occasionally hand out null pointers for pruned edges, so we catch t=
hose
-    // here.
-    if (Block =3D=3D 0)
-      return false;  // if an edge is trivially false.
-    if (VisitedBlockIDs.test(Block->getBlockID()))
-      return false;
-    VisitedBlockIDs.set(Block->getBlockID());
-    return true;
-  }
- =20
-  /// \brief Check if the bit for a CFGBlock has been already set.
-  /// This method is for tracking visited blocks in the main threadsafety =
loop.
-  /// Block must not be null.
-  bool alreadySet(const CFGBlock *Block) {
-    return VisitedBlockIDs.test(Block->getBlockID());
-  }
-};
-
-/// \brief We create a helper class which we use to iterate through CFGBlo=
cks in
-/// the topological order.
-class TopologicallySortedCFG {
-  typedef llvm::po_iterator<const CFG*, CFGBlockSet, true>  po_iterator;
- =20
-  std::vector<const CFGBlock*> Blocks;
- =20
-  typedef llvm::DenseMap<const CFGBlock *, unsigned> BlockOrderTy;
-  BlockOrderTy BlockOrder;
- =20
- =20
-public:
-  typedef std::vector<const CFGBlock*>::reverse_iterator iterator;
- =20
-  TopologicallySortedCFG(const CFG *CFGraph) {
-    Blocks.reserve(CFGraph->getNumBlockIDs());
-    CFGBlockSet BSet(CFGraph);
-   =20
-    for (po_iterator I =3D po_iterator::begin(CFGraph, BSet),
-         E =3D po_iterator::end(CFGraph, BSet); I !=3D E; ++I) {
-      BlockOrder[*I] =3D Blocks.size() + 1;
-      Blocks.push_back(*I);     =20
-    }
-  }
- =20
-  iterator begin() {
-    return Blocks.rbegin();
-  }
- =20
-  iterator end() {
-    return Blocks.rend();
-  }
- =20
-  bool empty() {
-    return begin() =3D=3D end();
-  }
- =20
-  struct BlockOrderCompare;
-  friend struct BlockOrderCompare;
-
-  struct BlockOrderCompare {
-    const TopologicallySortedCFG &TSC;
-  public:
-    BlockOrderCompare(const TopologicallySortedCFG &tsc) : TSC(tsc) {}
-   =20
-    bool operator()(const CFGBlock *b1, const CFGBlock *b2) const {
-      TopologicallySortedCFG::BlockOrderTy::const_iterator b1It =3D TSC.Bl=
ockOrder.find(b1);
-      TopologicallySortedCFG::BlockOrderTy::const_iterator b2It =3D TSC.Bl=
ockOrder.find(b2);
-     =20
-      unsigned b1V =3D (b1It =3D=3D TSC.BlockOrder.end()) ? 0 : b1It->seco=
nd;
-      unsigned b2V =3D (b2It =3D=3D TSC.BlockOrder.end()) ? 0 : b2It->seco=
nd;
-      return b1V > b2V;
-    } =20
-  };
- =20
-  BlockOrderCompare getComparator() const {
-    return BlockOrderCompare(*this);
-  }
-};
-
 class DataflowWorklist {
   SmallVector<const CFGBlock *, 20> worklist;
   llvm::BitVector enqueuedBlocks;
-  TopologicallySortedCFG TSC;
+  PostOrderCFGView *POV;
 public:
-  DataflowWorklist(const CFG &cfg)
+  DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
     : enqueuedBlocks(cfg.getNumBlockIDs()),
-      TSC(&cfg) {}
+      POV(Ctx.getAnalysis<PostOrderCFGView>()) {}
  =20
   void enqueueBlock(const CFGBlock *block);
   void enqueueSuccessors(const CFGBlock *block);
@@ -168,10 +71,9 @@
 }
=20
 void DataflowWorklist::sortWorklist() {
-  std::sort(worklist.begin(), worklist.end(), TSC.getComparator());
+  std::sort(worklist.begin(), worklist.end(), POV->getComparator());
 }
=20
-
 const CFGBlock *DataflowWorklist::dequeue() {
   if (worklist.empty())
     return 0;
@@ -184,7 +86,7 @@
 namespace {
 class LiveVariablesImpl {
 public: =20
-  AnalysisContext &analysisContext;
+  AnalysisDeclContext &analysisContext;
   std::vector<LiveVariables::LivenessValues> cfgBlockValues;
   llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
   llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
@@ -204,7 +106,7 @@
=20
   void dumpBlockLiveness(const SourceManager& M);
=20
-  LiveVariablesImpl(AnalysisContext &ac, bool KillAtAssign)
+  LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
     : analysisContext(ac),
       SSetFact(false), // Do not canonicalize ImmutableSets by default.
       DSetFact(false), // This is a *major* performance win.
@@ -241,6 +143,8 @@
   }
 }
=20
+void LiveVariables::Observer::anchor() { }
+
 LiveVariables::LivenessValues
 LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
                          LiveVariables::LivenessValues valsB) { =20
@@ -329,6 +233,29 @@
   return 0;
 }
=20
+static const Stmt *LookThroughStmt(const Stmt *S) {
+  while (S) {
+    if (const Expr *Ex =3D dyn_cast<Expr>(S))
+      S =3D Ex->IgnoreParens();   =20
+    if (const ExprWithCleanups *EWC =3D dyn_cast<ExprWithCleanups>(S)) {
+      S =3D EWC->getSubExpr();
+      continue;
+    }
+    if (const OpaqueValueExpr *OVE =3D dyn_cast<OpaqueValueExpr>(S)) {
+      S =3D OVE->getSourceExpr();
+      continue;
+    }
+    break;
+  }
+  return S;
+}
+
+static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
+                        llvm::ImmutableSet<const Stmt *>::Factory &F,
+                        const Stmt *S) {
+  Set =3D F.add(Set, LookThroughStmt(S));
+}
+
 void TransferFunctions::Visit(Stmt *S) {
   if (observer)
     observer->observeStmt(S, currentBlock, val);
@@ -353,8 +280,7 @@
       // Include the implicit "this" pointer as being live.
       CXXMemberCallExpr *CE =3D cast<CXXMemberCallExpr>(S);
       if (Expr *ImplicitObj =3D CE->getImplicitObjectArgument()) {
-        ImplicitObj =3D ImplicitObj->IgnoreParens();       =20
-        val.liveStmts =3D LV.SSetFact.add(val.liveStmts, ImplicitObj);
+        AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
       }
       break;
     }
@@ -363,12 +289,23 @@
       if (const VarDecl *VD =3D dyn_cast<VarDecl>(DS->getSingleDecl())) {
         for (const VariableArrayType* VA =3D FindVA(VD->getType());
              VA !=3D 0; VA =3D FindVA(VA->getElementType())) {
-          val.liveStmts =3D LV.SSetFact.add(val.liveStmts,
-                                          VA->getSizeExpr()->IgnoreParens(=
));
+          AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
         }
       }
       break;
     }
+    case Stmt::PseudoObjectExprClass: {
+      // A pseudo-object operation only directly consumes its result
+      // expression.
+      Expr *child =3D cast<PseudoObjectExpr>(S)->getResultExpr();
+      if (!child) return;
+      if (OpaqueValueExpr *OV =3D dyn_cast<OpaqueValueExpr>(child))
+        child =3D OV->getSourceExpr();
+      child =3D child->IgnoreParens();
+      val.liveStmts =3D LV.SSetFact.add(val.liveStmts, child);
+      return;
+    }
+
     // FIXME: These cases eventually shouldn't be needed.
     case Stmt::ExprWithCleanupsClass: {
       S =3D cast<ExprWithCleanups>(S)->getSubExpr();
@@ -386,12 +323,8 @@
  =20
   for (Stmt::child_iterator it =3D S->child_begin(), ei =3D S->child_end();
        it !=3D ei; ++it) {
-    if (Stmt *child =3D *it) {
-      if (Expr *Ex =3D dyn_cast<Expr>(child))
-        child =3D Ex->IgnoreParens();
-              =20
-      val.liveStmts =3D LV.SSetFact.add(val.liveStmts, child);
-    }
+    if (Stmt *child =3D *it)
+      AddLiveStmt(val.liveStmts, LV.SSetFact, child);
   }
 }
=20
@@ -421,7 +354,7 @@
 }
=20
 void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
-  AnalysisContext::referenced_decls_iterator I, E;
+  AnalysisDeclContext::referenced_decls_iterator I, E;
   llvm::tie(I, E) =3D
     LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
   for ( ; I !=3D E ; ++I) {
@@ -545,7 +478,7 @@
 }
=20
 LiveVariables *
-LiveVariables::computeLiveness(AnalysisContext &AC,
+LiveVariables::computeLiveness(AnalysisDeclContext &AC,
                                  bool killAtAssign) {
=20
   // No CFG?  Bail out.
@@ -557,7 +490,7 @@
=20
   // Construct the dataflow worklist.  Enqueue the exit block as the
   // start of the analysis.
-  DataflowWorklist worklist(*cfg);
+  DataflowWorklist worklist(*cfg, AC);
   llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
=20
   // FIXME: we should enqueue using post order.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/PrintfFormatString.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/PrintfFormatString.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/PrintfFormatString.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -52,7 +52,7 @@
                                                   const char *&Beg,
                                                   const char *E,
                                                   unsigned &argIndex,
-                                                  bool FormatExtensions) {
+                                                  const LangOptions &LO) {
=20
   using namespace clang::analyze_format_string;
   using namespace clang::analyze_printf;
@@ -151,7 +151,7 @@
   }
=20
   // Look for the length modifier.
-  if (ParseLengthModifier(FS, I, E) && I =3D=3D E) {
+  if (ParseLengthModifier(FS, I, E, LO) && I =3D=3D E) {
     // No more characters left?
     H.HandleIncompleteSpecifier(Start, E - Start);
     return true;
@@ -197,10 +197,10 @@
     // Glibc specific.
     case 'm': k =3D ConversionSpecifier::PrintErrno; break;
     // FreeBSD format extensions
-    case 'b': if (FormatExtensions) k =3D ConversionSpecifier::bArg; break=
; /* check for int and then char * */
-    case 'r': if (FormatExtensions) k =3D ConversionSpecifier::rArg; break;
-    case 'y': if (FormatExtensions) k =3D ConversionSpecifier::iArg; break;
-    case 'D': if (FormatExtensions) k =3D ConversionSpecifier::DArg; break=
; /* check for u_char * pointer and a char * string */
+    case 'b': if (LO.FormatExtensions) k =3D ConversionSpecifier::bArg; br=
eak; /* check for int and then char * */
+    case 'r': if (LO.FormatExtensions) k =3D ConversionSpecifier::rArg; br=
eak;
+    case 'y': if (LO.FormatExtensions) k =3D ConversionSpecifier::iArg; br=
eak;
+    case 'D': if (LO.FormatExtensions) k =3D ConversionSpecifier::DArg; br=
eak; /* check for u_char * pointer and a char * string */
   }
   PrintfConversionSpecifier CS(conversionPosition, k);
   FS.setConversionSpecifier(CS);
@@ -220,14 +220,14 @@
 bool clang::analyze_format_string::ParsePrintfString(FormatStringHandler &=
H,
                                                      const char *I,
                                                      const char *E,
-                                                     bool FormatExtensions=
) {
+                                                     const LangOptions &LO=
) {
=20
   unsigned argIndex =3D 0;
=20
   // Keep looking for a format specifier until we have exhausted the strin=
g.
   while (I !=3D E) {
     const PrintfSpecifierResult &FSR =3D ParsePrintfSpecifier(H, I, E, arg=
Index,
-                                                            FormatExtensio=
ns);
+                                                            LO);
     // Did a fail-stop error of any kind occur when parsing the specifier?
     // If so, don't do any more processing.
     if (FSR.shouldStop())
@@ -246,55 +246,11 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// Methods on ConversionSpecifier.
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-const char *ConversionSpecifier::toString() const {
-  switch (kind) {
-  case dArg: return "d";
-  case iArg: return "i";
-  case oArg: return "o";
-  case uArg: return "u";
-  case xArg: return "x";
-  case XArg: return "X";
-  case fArg: return "f";
-  case FArg: return "F";
-  case eArg: return "e";
-  case EArg: return "E";
-  case gArg: return "g";
-  case GArg: return "G";
-  case aArg: return "a";
-  case AArg: return "A";
-  case cArg: return "c";
-  case sArg: return "s";
-  case pArg: return "p";
-  case nArg: return "n";
-  case PercentArg:  return "%";
-  case ScanListArg: return "[";
-  case InvalidSpecifier: return NULL;
-
-  // MacOS X unicode extensions.
-  case CArg: return "C";
-  case SArg: return "S";
-
-  // Objective-C specific specifiers.
-  case ObjCObjArg: return "@";
-
-  // FreeBSD specific specifiers.
-  case bArg: return "b";
-  case DArg: return "D";
-  case rArg: return "r";
-
-  // GlibC specific specifiers.
-  case PrintErrno: return "m";
-  }
-  return NULL;
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Methods on PrintfSpecifier.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-ArgTypeResult PrintfSpecifier::getArgType(ASTContext &Ctx) const {
+ArgTypeResult PrintfSpecifier::getArgType(ASTContext &Ctx,
+                                          bool IsObjCLiteral) const {
   const PrintfConversionSpecifier &CS =3D getConversionSpecifier();
=20
   if (!CS.consumesDataArgument())
@@ -303,7 +259,8 @@
   if (CS.getKind() =3D=3D ConversionSpecifier::cArg)
     switch (LM.getKind()) {
       case LengthModifier::None: return Ctx.IntTy;
-      case LengthModifier::AsLong: return ArgTypeResult::WIntTy;
+      case LengthModifier::AsLong:
+        return ArgTypeResult(ArgTypeResult::WIntTy, "wint_t");
       default:
         return ArgTypeResult::Invalid();
     }
@@ -311,39 +268,50 @@
   if (CS.isIntArg())
     switch (LM.getKind()) {
       case LengthModifier::AsLongDouble:
-        return ArgTypeResult::Invalid();
+        // GNU extension.
+        return Ctx.LongLongTy;
       case LengthModifier::None: return Ctx.IntTy;
-      case LengthModifier::AsChar: return Ctx.SignedCharTy;
+      case LengthModifier::AsChar: return ArgTypeResult::AnyCharTy;
       case LengthModifier::AsShort: return Ctx.ShortTy;
       case LengthModifier::AsLong: return Ctx.LongTy;
-      case LengthModifier::AsLongLong: return Ctx.LongLongTy;
+      case LengthModifier::AsLongLong:
+      case LengthModifier::AsQuad:
+        return Ctx.LongLongTy;
       case LengthModifier::AsIntMax:
-        // FIXME: Return unknown for now.
+        return ArgTypeResult(Ctx.getIntMaxType(), "intmax_t");
+      case LengthModifier::AsSizeT:
+        // FIXME: How to get the corresponding signed version of size_t?
         return ArgTypeResult();
-      case LengthModifier::AsSizeT: return Ctx.getSizeType();
-      case LengthModifier::AsPtrDiff: return Ctx.getPointerDiffType();
+      case LengthModifier::AsPtrDiff:
+        return ArgTypeResult(Ctx.getPointerDiffType(), "ptrdiff_t");
+      case LengthModifier::AsAllocate:
+      case LengthModifier::AsMAllocate:
+        return ArgTypeResult::Invalid();
     }
=20
   if (CS.isUIntArg())
     switch (LM.getKind()) {
       case LengthModifier::AsLongDouble:
-        return ArgTypeResult::Invalid();
+        // GNU extension.
+        return Ctx.UnsignedLongLongTy;
       case LengthModifier::None: return Ctx.UnsignedIntTy;
       case LengthModifier::AsChar: return Ctx.UnsignedCharTy;
       case LengthModifier::AsShort: return Ctx.UnsignedShortTy;
       case LengthModifier::AsLong: return Ctx.UnsignedLongTy;
-      case LengthModifier::AsLongLong: return Ctx.UnsignedLongLongTy;
+      case LengthModifier::AsLongLong:
+      case LengthModifier::AsQuad:
+        return Ctx.UnsignedLongLongTy;
       case LengthModifier::AsIntMax:
-        // FIXME: Return unknown for now.
-        return ArgTypeResult();
+        return ArgTypeResult(Ctx.getUIntMaxType(), "uintmax_t");
       case LengthModifier::AsSizeT:
-        // FIXME: How to get the corresponding unsigned
-        // version of size_t?
-        return ArgTypeResult();
+        return ArgTypeResult(Ctx.getSizeType(), "size_t");
       case LengthModifier::AsPtrDiff:
         // FIXME: How to get the corresponding unsigned
         // version of ptrdiff_t?
         return ArgTypeResult();
+      case LengthModifier::AsAllocate:
+      case LengthModifier::AsMAllocate:
+        return ArgTypeResult::Invalid();
     }
=20
   if (CS.isDoubleArg()) {
@@ -354,15 +322,24 @@
=20
   switch (CS.getKind()) {
     case ConversionSpecifier::sArg:
-      return ArgTypeResult(LM.getKind() =3D=3D LengthModifier::AsWideChar ?
-          ArgTypeResult::WCStrTy : ArgTypeResult::CStrTy);
+      if (LM.getKind() =3D=3D LengthModifier::AsWideChar) {
+        if (IsObjCLiteral)
+          return Ctx.getPointerType(Ctx.UnsignedShortTy.withConst());
+        return ArgTypeResult(ArgTypeResult::WCStrTy, "wchar_t *");
+      }
+      return ArgTypeResult::CStrTy;
     case ConversionSpecifier::SArg:
-      // FIXME: This appears to be Mac OS X specific.
-      return ArgTypeResult::WCStrTy;
+      if (IsObjCLiteral)
+        return Ctx.getPointerType(Ctx.UnsignedShortTy.withConst());
+      return ArgTypeResult(ArgTypeResult::WCStrTy, "wchar_t *");
     case ConversionSpecifier::CArg:
-      return Ctx.WCharTy;
+      if (IsObjCLiteral)
+        return Ctx.UnsignedShortTy;
+      return ArgTypeResult(Ctx.WCharTy, "wchar_t");
     case ConversionSpecifier::pArg:
       return ArgTypeResult::CPointerTy;
+    case ConversionSpecifier::ObjCObjArg:
+      return ArgTypeResult::ObjCPointerTy;
     default:
       break;
   }
@@ -371,7 +348,8 @@
   return ArgTypeResult();
 }
=20
-bool PrintfSpecifier::fixType(QualType QT) {
+bool PrintfSpecifier::fixType(QualType QT, const LangOptions &LangOpt,
+                              ASTContext &Ctx, bool IsObjCLiteral) {
   // Handle strings first (char *, wchar_t *)
   if (QT->isPointerType() && (QT->getPointeeType()->isAnyCharacterType()))=
 {
     CS.setKind(ConversionSpecifier::sArg);
@@ -383,17 +361,17 @@
     // Set the long length modifier for wide characters
     if (QT->getPointeeType()->isWideCharType())
       LM.setKind(LengthModifier::AsWideChar);
+    else
+      LM.setKind(LengthModifier::None);
=20
     return true;
   }
=20
   // We can only work with builtin types.
-  if (!QT->isBuiltinType())
+  const BuiltinType *BT =3D QT->getAs<BuiltinType>();
+  if (!BT)
     return false;
=20
-  // Everything else should be a base type
-  const BuiltinType *BT =3D QT->getAs<BuiltinType>();
-
   // Set length modifier
   switch (BT->getKind()) {
   case BuiltinType::Bool:
@@ -404,18 +382,15 @@
   case BuiltinType::UInt128:
   case BuiltinType::Int128:
   case BuiltinType::Half:
-    // Integral types which are non-trivial to correct.
+    // Various types which are non-trivial to correct.
     return false;
=20
-  case BuiltinType::Void:
-  case BuiltinType::NullPtr:
-  case BuiltinType::ObjCId:
-  case BuiltinType::ObjCClass:
-  case BuiltinType::ObjCSel:
-  case BuiltinType::Dependent:
-  case BuiltinType::Overload:
-  case BuiltinType::BoundMember:
-  case BuiltinType::UnknownAny:
+#define SIGNED_TYPE(Id, SingletonId)
+#define UNSIGNED_TYPE(Id, SingletonId)
+#define FLOATING_TYPE(Id, SingletonId)
+#define BUILTIN_TYPE(Id, SingletonId) \
+  case BuiltinType::Id:
+#include "clang/AST/BuiltinTypes.def"
     // Misc other stuff which doesn't make sense here.
     return false;
=20
@@ -453,6 +428,28 @@
     break;
   }
=20
+  // Handle size_t, ptrdiff_t, etc. that have dedicated length modifiers i=
n C99.
+  if (isa<TypedefType>(QT) && (LangOpt.C99 || LangOpt.CPlusPlus0x)) {
+    const IdentifierInfo *Identifier =3D QT.getBaseTypeIdentifier();
+    if (Identifier->getName() =3D=3D "size_t") {
+      LM.setKind(LengthModifier::AsSizeT);
+    } else if (Identifier->getName() =3D=3D "ssize_t") {
+      // Not C99, but common in Unix.
+      LM.setKind(LengthModifier::AsSizeT);
+    } else if (Identifier->getName() =3D=3D "intmax_t") {
+      LM.setKind(LengthModifier::AsIntMax);
+    } else if (Identifier->getName() =3D=3D "uintmax_t") {
+      LM.setKind(LengthModifier::AsIntMax);
+    } else if (Identifier->getName() =3D=3D "ptrdiff_t") {
+      LM.setKind(LengthModifier::AsPtrDiff);
+    }
+  }
+
+  // If fixing the length modifier was enough, we are done.
+  const analyze_printf::ArgTypeResult &ATR =3D getArgType(Ctx, IsObjCLiter=
al);
+  if (hasValidLengthModifier() && ATR.isValid() && ATR.matchesType(Ctx, QT=
))
+    return true;
+
   // Set conversion specifier and disable any flags which do not apply to =
it.
   // Let typedefs to char fall through to int, as %c is silly for uint8_t.
   if (isa<TypedefType>(QT) && QT->isAnyCharacterType()) {
@@ -472,9 +469,7 @@
     HasAlternativeForm =3D 0;
   }
   else if (QT->isUnsignedIntegerType()) {
-    // Preserve the original formatting, e.g. 'X', 'o'.
-    if (!cast<PrintfConversionSpecifier>(CS).isUIntArg())
-      CS.setKind(ConversionSpecifier::uArg);
+    CS.setKind(ConversionSpecifier::uArg);
     HasAlternativeForm =3D 0;
     HasPlusPrefix =3D 0;
   } else {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/ProgramPoint.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/ProgramPoint.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/ProgramPoint.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -34,8 +34,6 @@
       return PostLoad(S, LC, tag);
     case ProgramPoint::PreStoreKind:
       return PreStore(S, LC, tag);
-    case ProgramPoint::PostStoreKind:
-      return PostStore(S, LC, tag);
     case ProgramPoint::PostLValueKind:
       return PostLValue(S, LC, tag);
     case ProgramPoint::PostPurgeDeadSymbolsKind:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/PseudoConstantAnalysis.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/PseudoConstantAnalysis.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/PseudoConstantAnalysis.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -68,8 +68,6 @@
 const Decl *PseudoConstantAnalysis::getDecl(const Expr *E) {
   if (const DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(E))
     return DR->getDecl();
-  else if (const BlockDeclRefExpr *BDR =3D dyn_cast<BlockDeclRefExpr>(E))
-    return BDR->getDecl();
   else
     return 0;
 }
@@ -198,18 +196,7 @@
       break;
     }
=20
-    // Case 4: Block variable references
-    case Stmt::BlockDeclRefExprClass: {
-      const BlockDeclRefExpr *BDR =3D cast<BlockDeclRefExpr>(Head);
-      if (const VarDecl *VD =3D dyn_cast<VarDecl>(BDR->getDecl())) {
-        // Add the Decl to the used list
-        UsedVars->insert(VD);
-        continue;
-      }
-      break;
-    }
-
-    // Case 5: Variable references
+    // Case 4: Variable references
     case Stmt::DeclRefExprClass: {
       const DeclRefExpr *DR =3D cast<DeclRefExpr>(Head);
       if (const VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl())) {
@@ -220,7 +207,7 @@
       break;
     }
=20
-    // Case 6: Block expressions
+    // Case 5: Block expressions
     case Stmt::BlockExprClass: {
       const BlockExpr *B =3D cast<BlockExpr>(Head);
       // Add the body of the block to the list
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/ReachableCode.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/ReachableCode.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/ReachableCode.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -251,7 +251,9 @@
 }
=20
 namespace clang { namespace reachable_code {
- =20
+
+void Callback::anchor() { } =20
+
 unsigned ScanReachableFromBlock(const CFGBlock *Start,
                                 llvm::BitVector &Reachable) {
   unsigned count =3D 0;
@@ -287,7 +289,7 @@
   return count;
 }
  =20
-void FindUnreachableCode(AnalysisContext &AC, Callback &CB) {
+void FindUnreachableCode(AnalysisDeclContext &AC, Callback &CB) {
   CFG *cfg =3D AC.getCFG();
   if (!cfg)
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/ScanfFormatString.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/ScanfFormatString.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/ScanfFormatString.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -20,9 +20,11 @@
 using clang::analyze_format_string::LengthModifier;
 using clang::analyze_format_string::OptionalAmount;
 using clang::analyze_format_string::ConversionSpecifier;
+using clang::analyze_scanf::ScanfArgTypeResult;
 using clang::analyze_scanf::ScanfConversionSpecifier;
 using clang::analyze_scanf::ScanfSpecifier;
 using clang::UpdateOnReturn;
+using namespace clang;
=20
 typedef clang::analyze_format_string::SpecifierResult<ScanfSpecifier>
         ScanfSpecifierResult;
@@ -65,7 +67,8 @@
 static ScanfSpecifierResult ParseScanfSpecifier(FormatStringHandler &H,
                                                 const char *&Beg,
                                                 const char *E,
-                                                unsigned &argIndex) {
+                                                unsigned &argIndex,
+                                                const LangOptions &LO) {
  =20
   using namespace clang::analyze_scanf;
   const char *I =3D Beg;
@@ -130,7 +133,7 @@
   }
  =20
   // Look for the length modifier.
-  if (ParseLengthModifier(FS, I, E) && I =3D=3D E) {
+  if (ParseLengthModifier(FS, I, E, LO, /*scanf=3D*/true) && I =3D=3D E) {
       // No more characters left?
     H.HandleIncompleteSpecifier(Start, E - Start);
     return true;
@@ -173,7 +176,7 @@
   }
   ScanfConversionSpecifier CS(conversionPosition, k);
   if (k =3D=3D ScanfConversionSpecifier::ScanListArg) {
-    if (!ParseScanList(H, CS, I, E))
+    if (ParseScanList(H, CS, I, E))
       return true;
   }
   FS.setConversionSpecifier(CS);
@@ -190,16 +193,248 @@
   }
   return ScanfSpecifierResult(Start, FS);
 }
- =20
+
+ScanfArgTypeResult ScanfSpecifier::getArgType(ASTContext &Ctx) const {
+  const ScanfConversionSpecifier &CS =3D getConversionSpecifier();
+
+  if (!CS.consumesDataArgument())
+    return ScanfArgTypeResult::Invalid();
+
+  switch(CS.getKind()) {
+    // Signed int.
+    case ConversionSpecifier::dArg:
+    case ConversionSpecifier::iArg:
+      switch (LM.getKind()) {
+        case LengthModifier::None: return ArgTypeResult(Ctx.IntTy);
+        case LengthModifier::AsChar:
+          return ArgTypeResult(ArgTypeResult::AnyCharTy);
+        case LengthModifier::AsShort: return ArgTypeResult(Ctx.ShortTy);
+        case LengthModifier::AsLong: return ArgTypeResult(Ctx.LongTy);
+        case LengthModifier::AsLongLong:
+        case LengthModifier::AsQuad:
+          return ArgTypeResult(Ctx.LongLongTy);
+        case LengthModifier::AsIntMax:
+          return ScanfArgTypeResult(Ctx.getIntMaxType(), "intmax_t *");
+        case LengthModifier::AsSizeT:
+          // FIXME: ssize_t.
+          return ScanfArgTypeResult();
+        case LengthModifier::AsPtrDiff:
+          return ScanfArgTypeResult(Ctx.getPointerDiffType(), "ptrdiff_t *=
");
+        case LengthModifier::AsLongDouble:
+          // GNU extension.
+          return ArgTypeResult(Ctx.LongLongTy);
+        case LengthModifier::AsAllocate: return ScanfArgTypeResult::Invali=
d();
+        case LengthModifier::AsMAllocate: return ScanfArgTypeResult::Inval=
id();
+      }
+
+    // Unsigned int.
+    case ConversionSpecifier::oArg:
+    case ConversionSpecifier::uArg:
+    case ConversionSpecifier::xArg:
+    case ConversionSpecifier::XArg:
+      switch (LM.getKind()) {
+        case LengthModifier::None: return ArgTypeResult(Ctx.UnsignedIntTy);
+        case LengthModifier::AsChar: return ArgTypeResult(Ctx.UnsignedChar=
Ty);
+        case LengthModifier::AsShort: return ArgTypeResult(Ctx.UnsignedSho=
rtTy);
+        case LengthModifier::AsLong: return ArgTypeResult(Ctx.UnsignedLong=
Ty);
+        case LengthModifier::AsLongLong:
+        case LengthModifier::AsQuad:
+          return ArgTypeResult(Ctx.UnsignedLongLongTy);
+        case LengthModifier::AsIntMax:
+          return ScanfArgTypeResult(Ctx.getUIntMaxType(), "uintmax_t *");
+        case LengthModifier::AsSizeT:
+          return ScanfArgTypeResult(Ctx.getSizeType(), "size_t *");
+        case LengthModifier::AsPtrDiff:
+          // FIXME: Unsigned version of ptrdiff_t?
+          return ScanfArgTypeResult();
+        case LengthModifier::AsLongDouble:
+          // GNU extension.
+          return ArgTypeResult(Ctx.UnsignedLongLongTy);
+        case LengthModifier::AsAllocate: return ScanfArgTypeResult::Invali=
d();
+        case LengthModifier::AsMAllocate: return ScanfArgTypeResult::Inval=
id();
+      }
+
+    // Float.
+    case ConversionSpecifier::aArg:
+    case ConversionSpecifier::AArg:
+    case ConversionSpecifier::eArg:
+    case ConversionSpecifier::EArg:
+    case ConversionSpecifier::fArg:
+    case ConversionSpecifier::FArg:
+    case ConversionSpecifier::gArg:
+    case ConversionSpecifier::GArg:
+      switch (LM.getKind()) {
+        case LengthModifier::None: return ArgTypeResult(Ctx.FloatTy);
+        case LengthModifier::AsLong: return ArgTypeResult(Ctx.DoubleTy);
+        case LengthModifier::AsLongDouble:
+          return ArgTypeResult(Ctx.LongDoubleTy);
+        default:
+          return ScanfArgTypeResult::Invalid();
+      }
+
+    // Char, string and scanlist.
+    case ConversionSpecifier::cArg:
+    case ConversionSpecifier::sArg:
+    case ConversionSpecifier::ScanListArg:
+      switch (LM.getKind()) {
+        case LengthModifier::None: return ScanfArgTypeResult::CStrTy;
+        case LengthModifier::AsLong:
+          return ScanfArgTypeResult(ScanfArgTypeResult::WCStrTy, "wchar_t =
*");
+        case LengthModifier::AsAllocate:
+        case LengthModifier::AsMAllocate:
+          return ScanfArgTypeResult(ArgTypeResult::CStrTy);
+        default:
+          return ScanfArgTypeResult::Invalid();
+      }
+    case ConversionSpecifier::CArg:
+    case ConversionSpecifier::SArg:
+      // FIXME: Mac OS X specific?
+      switch (LM.getKind()) {
+        case LengthModifier::None:
+          return ScanfArgTypeResult(ScanfArgTypeResult::WCStrTy, "wchar_t =
*");
+        case LengthModifier::AsAllocate:
+        case LengthModifier::AsMAllocate:
+          return ScanfArgTypeResult(ArgTypeResult::WCStrTy, "wchar_t **");
+        default:
+          return ScanfArgTypeResult::Invalid();
+      }
+
+    // Pointer.
+    case ConversionSpecifier::pArg:
+      return ScanfArgTypeResult(ArgTypeResult(ArgTypeResult::CPointerTy));
+
+    default:
+      break;
+  }
+
+  return ScanfArgTypeResult();
+}
+
+bool ScanfSpecifier::fixType(QualType QT, const LangOptions &LangOpt,
+                             ASTContext &Ctx) {
+  if (!QT->isPointerType())
+    return false;
+
+  QualType PT =3D QT->getPointeeType();
+  const BuiltinType *BT =3D PT->getAs<BuiltinType>();
+  if (!BT)
+    return false;
+
+  // Pointer to a character.
+  if (PT->isAnyCharacterType()) {
+    CS.setKind(ConversionSpecifier::sArg);
+    if (PT->isWideCharType())
+      LM.setKind(LengthModifier::AsWideChar);
+    else
+      LM.setKind(LengthModifier::None);
+    return true;
+  }
+
+  // Figure out the length modifier.
+  switch (BT->getKind()) {
+    // no modifier
+    case BuiltinType::UInt:
+    case BuiltinType::Int:
+    case BuiltinType::Float:
+      LM.setKind(LengthModifier::None);
+      break;
+
+    // hh
+    case BuiltinType::Char_U:
+    case BuiltinType::UChar:
+    case BuiltinType::Char_S:
+    case BuiltinType::SChar:
+      LM.setKind(LengthModifier::AsChar);
+      break;
+
+    // h
+    case BuiltinType::Short:
+    case BuiltinType::UShort:
+      LM.setKind(LengthModifier::AsShort);
+      break;
+
+    // l
+    case BuiltinType::Long:
+    case BuiltinType::ULong:
+    case BuiltinType::Double:
+      LM.setKind(LengthModifier::AsLong);
+      break;
+
+    // ll
+    case BuiltinType::LongLong:
+    case BuiltinType::ULongLong:
+      LM.setKind(LengthModifier::AsLongLong);
+      break;
+
+    // L
+    case BuiltinType::LongDouble:
+      LM.setKind(LengthModifier::AsLongDouble);
+      break;
+
+    // Don't know.
+    default:
+      return false;
+  }
+
+  // Handle size_t, ptrdiff_t, etc. that have dedicated length modifiers i=
n C99.
+  if (isa<TypedefType>(PT) && (LangOpt.C99 || LangOpt.CPlusPlus0x)) {
+    const IdentifierInfo *Identifier =3D QT.getBaseTypeIdentifier();
+    if (Identifier->getName() =3D=3D "size_t") {
+      LM.setKind(LengthModifier::AsSizeT);
+    } else if (Identifier->getName() =3D=3D "ssize_t") {
+      // Not C99, but common in Unix.
+      LM.setKind(LengthModifier::AsSizeT);
+    } else if (Identifier->getName() =3D=3D "intmax_t") {
+      LM.setKind(LengthModifier::AsIntMax);
+    } else if (Identifier->getName() =3D=3D "uintmax_t") {
+      LM.setKind(LengthModifier::AsIntMax);
+    } else if (Identifier->getName() =3D=3D "ptrdiff_t") {
+      LM.setKind(LengthModifier::AsPtrDiff);
+    }
+  }
+
+  // If fixing the length modifier was enough, we are done.
+  const analyze_scanf::ScanfArgTypeResult &ATR =3D getArgType(Ctx);
+  if (hasValidLengthModifier() && ATR.isValid() && ATR.matchesType(Ctx, QT=
))
+    return true;
+
+  // Figure out the conversion specifier.
+  if (PT->isRealFloatingType())
+    CS.setKind(ConversionSpecifier::fArg);
+  else if (PT->isSignedIntegerType())
+    CS.setKind(ConversionSpecifier::dArg);
+  else if (PT->isUnsignedIntegerType())
+    CS.setKind(ConversionSpecifier::uArg);
+  else
+    llvm_unreachable("Unexpected type");
+
+  return true;
+}
+
+void ScanfSpecifier::toString(raw_ostream &os) const {
+  os << "%";
+
+  if (usesPositionalArg())
+    os << getPositionalArgIndex() << "$";
+  if (SuppressAssignment)
+    os << "*";
+
+  FieldWidth.toString(os);
+  os << LM.toString();
+  os << CS.toString();
+}
+
 bool clang::analyze_format_string::ParseScanfString(FormatStringHandler &H,
                                                     const char *I,
-                                                    const char *E) {
+                                                    const char *E,
+                                                    const LangOptions &LO)=
 {
  =20
   unsigned argIndex =3D 0;
  =20
   // Keep looking for a format specifier until we have exhausted the strin=
g.
   while (I !=3D E) {
-    const ScanfSpecifierResult &FSR =3D ParseScanfSpecifier(H, I, E, argIn=
dex);
+    const ScanfSpecifierResult &FSR =3D ParseScanfSpecifier(H, I, E, argIn=
dex,
+                                                          LO);
     // Did a fail-stop error of any kind occur when parsing the specifier?
     // If so, don't do any more processing.
     if (FSR.shouldStop())
@@ -218,4 +453,47 @@
   return false;
 }
=20
+bool ScanfArgTypeResult::matchesType(ASTContext& C, QualType argTy) const {
+  switch (K) {
+    case InvalidTy:
+      llvm_unreachable("ArgTypeResult must be valid");
+    case UnknownTy:
+      return true;
+    case CStrTy:
+      return ArgTypeResult(ArgTypeResult::CStrTy).matchesType(C, argTy);
+    case WCStrTy:
+      return ArgTypeResult(ArgTypeResult::WCStrTy).matchesType(C, argTy);
+    case PtrToArgTypeResultTy: {
+      const PointerType *PT =3D argTy->getAs<PointerType>();
+      if (!PT)
+        return false;
+      return A.matchesType(C, PT->getPointeeType());
+    }
+  }
=20
+  llvm_unreachable("Invalid ScanfArgTypeResult Kind!");
+}
+
+QualType ScanfArgTypeResult::getRepresentativeType(ASTContext &C) const {
+  switch (K) {
+    case InvalidTy:
+      llvm_unreachable("No representative type for Invalid ArgTypeResult");
+    case UnknownTy:
+      return QualType();
+    case CStrTy:
+      return C.getPointerType(C.CharTy);
+    case WCStrTy:
+      return C.getPointerType(C.getWCharType());
+    case PtrToArgTypeResultTy:
+      return C.getPointerType(A.getRepresentativeType(C));
+  }
+
+  llvm_unreachable("Invalid ScanfArgTypeResult Kind!");
+}
+
+std::string ScanfArgTypeResult::getRepresentativeTypeName(ASTContext& C) c=
onst {
+  std::string S =3D getRepresentativeType(C).getAsString();
+  if (!Name)
+    return std::string("'") + S + "'";
+  return std::string("'") + Name + "' (aka '" + S + "')";
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/ThreadSafety.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/ThreadSafety.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/ThreadSafety.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/Analysis/Analyses/ThreadSafety.h"
+#include "clang/Analysis/Analyses/PostOrderCFGView.h"
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Analysis/CFG.h"
 #include "clang/Analysis/CFGStmtMap.h"
@@ -31,7 +32,9 @@
 #include "llvm/ADT/PostOrderIterator.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/raw_ostream.h"
 #include <algorithm>
+#include <utility>
 #include <vector>
=20
 using namespace clang;
@@ -40,90 +43,7 @@
 // Key method definition
 ThreadSafetyHandler::~ThreadSafetyHandler() {}
=20
-// Helper function
-static Expr *getParent(Expr *Exp) {
-  if (MemberExpr *ME =3D dyn_cast<MemberExpr>(Exp))
-    return ME->getBase();
-  if (CXXMemberCallExpr *CE =3D dyn_cast<CXXMemberCallExpr>(Exp))
-    return CE->getImplicitObjectArgument();
-  return 0;
-}
-
 namespace {
-/// \brief Implements a set of CFGBlocks using a BitVector.
-///
-/// This class contains a minimal interface, primarily dictated by the Set=
Type
-/// template parameter of the llvm::po_iterator template, as used with ext=
ernal
-/// storage. We also use this set to keep track of which CFGBlocks we visit
-/// during the analysis.
-class CFGBlockSet {
-  llvm::BitVector VisitedBlockIDs;
-
-public:
-  // po_iterator requires this iterator, but the only interface needed is =
the
-  // value_type typedef.
-  struct iterator {
-    typedef const CFGBlock *value_type;
-  };
-
-  CFGBlockSet() {}
-  CFGBlockSet(const CFG *G) : VisitedBlockIDs(G->getNumBlockIDs(), false) =
{}
-
-  /// \brief Set the bit associated with a particular CFGBlock.
-  /// This is the important method for the SetType template parameter.
-  bool insert(const CFGBlock *Block) {
-    // Note that insert() is called by po_iterator, which doesn't check to=
 make
-    // sure that Block is non-null.  Moreover, the CFGBlock iterator will
-    // occasionally hand out null pointers for pruned edges, so we catch t=
hose
-    // here.
-    if (Block =3D=3D 0)
-      return false;  // if an edge is trivially false.
-    if (VisitedBlockIDs.test(Block->getBlockID()))
-      return false;
-    VisitedBlockIDs.set(Block->getBlockID());
-    return true;
-  }
-
-  /// \brief Check if the bit for a CFGBlock has been already set.
-  /// This method is for tracking visited blocks in the main threadsafety =
loop.
-  /// Block must not be null.
-  bool alreadySet(const CFGBlock *Block) {
-    return VisitedBlockIDs.test(Block->getBlockID());
-  }
-};
-
-/// \brief We create a helper class which we use to iterate through CFGBlo=
cks in
-/// the topological order.
-class TopologicallySortedCFG {
-  typedef llvm::po_iterator<const CFG*, CFGBlockSet, true>  po_iterator;
-
-  std::vector<const CFGBlock*> Blocks;
-
-public:
-  typedef std::vector<const CFGBlock*>::reverse_iterator iterator;
-
-  TopologicallySortedCFG(const CFG *CFGraph) {
-    Blocks.reserve(CFGraph->getNumBlockIDs());
-    CFGBlockSet BSet(CFGraph);
-
-    for (po_iterator I =3D po_iterator::begin(CFGraph, BSet),
-         E =3D po_iterator::end(CFGraph, BSet); I !=3D E; ++I) {
-      Blocks.push_back(*I);
-    }
-  }
-
-  iterator begin() {
-    return Blocks.rbegin();
-  }
-
-  iterator end() {
-    return Blocks.rend();
-  }
-
-  bool empty() {
-    return begin() =3D=3D end();
-  }
-};
=20
 /// \brief A MutexID object uniquely identifies a particular mutex, and
 /// is built from an Expr* (i.e. calling a lock function).
@@ -136,16 +56,17 @@
 /// (1) Local variables in the expression, such as "x" have not changed.
 /// (2) Values on the heap that affect the expression have not changed.
 /// (3) The expression involves only pure function calls.
+///
 /// The current implementation assumes, but does not verify, that multiple=
 uses
 /// of the same lock expression satisfies these criteria.
 ///
 /// Clang introduces an additional wrinkle, which is that it is difficult =
to
 /// derive canonical expressions, or compare expressions directly for equa=
lity.
-/// Thus, we identify a mutex not by an Expr, but by the set of named
+/// Thus, we identify a mutex not by an Expr, but by the list of named
 /// declarations that are referenced by the Expr.  In other words,
 /// x->foo->bar.mu will be a four element vector with the Decls for
 /// mu, bar, and foo, and x.  The vector will uniquely identify the expres=
sion
-/// for all practical purposes.
+/// for all practical purposes.  Null is used to denote 'this'.
 ///
 /// Note we will need to perform substitution on "this" and function param=
eter
 /// names when constructing a lock expression.
@@ -164,38 +85,176 @@
   SmallVector<NamedDecl*, 2> DeclSeq;
=20
   /// Build a Decl sequence representing the lock from the given expressio=
n.
-  /// Recursive function that bottoms out when the final DeclRefExpr is re=
ached.
-  // FIXME: Lock expressions that involve array indices or function calls.
-  // FIXME: Deal with LockReturned attribute.
-  void buildMutexID(Expr *Exp, Expr *Parent) {
+  /// Recursive function that terminates on DeclRefExpr.
+  /// Note: this function merely creates a MutexID; it does not check to
+  /// ensure that the original expression is a valid mutex expression.
+  void buildMutexID(Expr *Exp, const NamedDecl *D, Expr *Parent,
+                    unsigned NumArgs, Expr **FunArgs) {
+    if (!Exp) {
+      DeclSeq.clear();
+      return;
+    }
+
     if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(Exp)) {
       NamedDecl *ND =3D cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()=
);
+      ParmVarDecl *PV =3D dyn_cast_or_null<ParmVarDecl>(ND);
+      if (PV) {
+        FunctionDecl *FD =3D
+          cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
+        unsigned i =3D PV->getFunctionScopeIndex();
+
+        if (FunArgs && FD =3D=3D D->getCanonicalDecl()) {
+          // Substitute call arguments for references to function paramete=
rs
+          assert(i < NumArgs);
+          buildMutexID(FunArgs[i], D, 0, 0, 0);
+          return;
+        }
+        // Map the param back to the param of the original function declar=
ation.
+        DeclSeq.push_back(FD->getParamDecl(i));
+        return;
+      }
+      // Not a function parameter -- just store the reference.
       DeclSeq.push_back(ND);
     } else if (MemberExpr *ME =3D dyn_cast<MemberExpr>(Exp)) {
       NamedDecl *ND =3D ME->getMemberDecl();
       DeclSeq.push_back(ND);
-      buildMutexID(ME->getBase(), Parent);
+      buildMutexID(ME->getBase(), D, Parent, NumArgs, FunArgs);
     } else if (isa<CXXThisExpr>(Exp)) {
       if (Parent)
-        buildMutexID(Parent, 0);
-      else
-        return; // mutexID is still valid in this case
-    } else if (CastExpr *CE =3D dyn_cast<CastExpr>(Exp))
-      buildMutexID(CE->getSubExpr(), Parent);
-    else
-      DeclSeq.clear(); // invalid lock expression
+        buildMutexID(Parent, D, 0, 0, 0);
+      else {
+        DeclSeq.push_back(0);  // Use 0 to represent 'this'.
+        return;  // mutexID is still valid in this case
+      }
+    } else if (CXXMemberCallExpr *CMCE =3D dyn_cast<CXXMemberCallExpr>(Exp=
)) {
+      DeclSeq.push_back(CMCE->getMethodDecl()->getCanonicalDecl());
+      buildMutexID(CMCE->getImplicitObjectArgument(),
+                   D, Parent, NumArgs, FunArgs);
+      unsigned NumCallArgs =3D CMCE->getNumArgs();
+      Expr** CallArgs =3D CMCE->getArgs();
+      for (unsigned i =3D 0; i < NumCallArgs; ++i) {
+        buildMutexID(CallArgs[i], D, Parent, NumArgs, FunArgs);
+      }
+    } else if (CallExpr *CE =3D dyn_cast<CallExpr>(Exp)) {
+      buildMutexID(CE->getCallee(), D, Parent, NumArgs, FunArgs);
+      unsigned NumCallArgs =3D CE->getNumArgs();
+      Expr** CallArgs =3D CE->getArgs();
+      for (unsigned i =3D 0; i < NumCallArgs; ++i) {
+        buildMutexID(CallArgs[i], D, Parent, NumArgs, FunArgs);
+      }
+    } else if (BinaryOperator *BOE =3D dyn_cast<BinaryOperator>(Exp)) {
+      buildMutexID(BOE->getLHS(), D, Parent, NumArgs, FunArgs);
+      buildMutexID(BOE->getRHS(), D, Parent, NumArgs, FunArgs);
+    } else if (UnaryOperator *UOE =3D dyn_cast<UnaryOperator>(Exp)) {
+      buildMutexID(UOE->getSubExpr(), D, Parent, NumArgs, FunArgs);
+    } else if (ArraySubscriptExpr *ASE =3D dyn_cast<ArraySubscriptExpr>(Ex=
p)) {
+      buildMutexID(ASE->getBase(), D, Parent, NumArgs, FunArgs);
+      buildMutexID(ASE->getIdx(), D, Parent, NumArgs, FunArgs);
+    } else if (AbstractConditionalOperator *CE =3D
+                 dyn_cast<AbstractConditionalOperator>(Exp)) {
+      buildMutexID(CE->getCond(), D, Parent, NumArgs, FunArgs);
+      buildMutexID(CE->getTrueExpr(), D, Parent, NumArgs, FunArgs);
+      buildMutexID(CE->getFalseExpr(), D, Parent, NumArgs, FunArgs);
+    } else if (ChooseExpr *CE =3D dyn_cast<ChooseExpr>(Exp)) {
+      buildMutexID(CE->getCond(), D, Parent, NumArgs, FunArgs);
+      buildMutexID(CE->getLHS(), D, Parent, NumArgs, FunArgs);
+      buildMutexID(CE->getRHS(), D, Parent, NumArgs, FunArgs);
+    } else if (CastExpr *CE =3D dyn_cast<CastExpr>(Exp)) {
+      buildMutexID(CE->getSubExpr(), D, Parent, NumArgs, FunArgs);
+    } else if (ParenExpr *PE =3D dyn_cast<ParenExpr>(Exp)) {
+      buildMutexID(PE->getSubExpr(), D, Parent, NumArgs, FunArgs);
+    } else if (isa<CharacterLiteral>(Exp) ||
+             isa<CXXNullPtrLiteralExpr>(Exp) ||
+             isa<GNUNullExpr>(Exp) ||
+             isa<CXXBoolLiteralExpr>(Exp) ||
+             isa<FloatingLiteral>(Exp) ||
+             isa<ImaginaryLiteral>(Exp) ||
+             isa<IntegerLiteral>(Exp) ||
+             isa<StringLiteral>(Exp) ||
+             isa<ObjCStringLiteral>(Exp)) {
+      return;  // FIXME: Ignore literals for now
+    } else {
+      // Ignore.  FIXME: mark as invalid expression?
+    }
+  }
+
+  /// \brief Construct a MutexID from an expression.
+  /// \param MutexExp The original mutex expression within an attribute
+  /// \param DeclExp An expression involving the Decl on which the attribu=
te
+  ///        occurs.
+  /// \param D  The declaration to which the lock/unlock attribute is atta=
ched.
+  void buildMutexIDFromExp(Expr *MutexExp, Expr *DeclExp, const NamedDecl =
*D) {
+    Expr *Parent =3D 0;
+    unsigned NumArgs =3D 0;
+    Expr **FunArgs =3D 0;
+
+    // If we are processing a raw attribute expression, with no substituti=
ons.
+    if (DeclExp =3D=3D 0) {
+      buildMutexID(MutexExp, D, 0, 0, 0);
+      return;
+    }
+
+    // Examine DeclExp to find Parent and FunArgs, which are used to subst=
itute
+    // for formal parameters when we call buildMutexID later.
+    if (MemberExpr *ME =3D dyn_cast<MemberExpr>(DeclExp)) {
+      Parent =3D ME->getBase();
+    } else if (CXXMemberCallExpr *CE =3D dyn_cast<CXXMemberCallExpr>(DeclE=
xp)) {
+      Parent =3D CE->getImplicitObjectArgument();
+      NumArgs =3D CE->getNumArgs();
+      FunArgs =3D CE->getArgs();
+    } else if (CallExpr *CE =3D dyn_cast<CallExpr>(DeclExp)) {
+      NumArgs =3D CE->getNumArgs();
+      FunArgs =3D CE->getArgs();
+    } else if (CXXConstructExpr *CE =3D dyn_cast<CXXConstructExpr>(DeclExp=
)) {
+      Parent =3D 0;  // FIXME -- get the parent from DeclStmt
+      NumArgs =3D CE->getNumArgs();
+      FunArgs =3D CE->getArgs();
+    } else if (D && isa<CXXDestructorDecl>(D)) {
+      // There's no such thing as a "destructor call" in the AST.
+      Parent =3D DeclExp;
+    }
+
+    // If the attribute has no arguments, then assume the argument is "thi=
s".
+    if (MutexExp =3D=3D 0) {
+      buildMutexID(Parent, D, 0, 0, 0);
+      return;
+    }
+
+    buildMutexID(MutexExp, D, Parent, NumArgs, FunArgs);
   }
=20
 public:
-  MutexID(Expr *LExpr, Expr *ParentExpr) {
-    buildMutexID(LExpr, ParentExpr);
+  explicit MutexID(clang::Decl::EmptyShell e) {
+    DeclSeq.clear();
   }
=20
-  /// If we encounter part of a lock expression we cannot parse
+  /// \param MutexExp The original mutex expression within an attribute
+  /// \param DeclExp An expression involving the Decl on which the attribu=
te
+  ///        occurs.
+  /// \param D  The declaration to which the lock/unlock attribute is atta=
ched.
+  /// Caller must check isValid() after construction.
+  MutexID(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
+    buildMutexIDFromExp(MutexExp, DeclExp, D);
+  }
+
+  /// Return true if this is a valid decl sequence.
+  /// Caller must call this by hand after construction to handle errors.
   bool isValid() const {
     return !DeclSeq.empty();
   }
=20
+  /// Issue a warning about an invalid lock expression
+  static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
+                              Expr *DeclExp, const NamedDecl* D) {
+    SourceLocation Loc;
+    if (DeclExp)
+      Loc =3D DeclExp->getExprLoc();
+
+    // FIXME: add a note about the attribute location in MutexExp or D
+    if (Loc.isValid())
+      Handler.handleInvalidLockExp(Loc);
+  }
+
   bool operator=3D=3D(const MutexID &other) const {
     return DeclSeq =3D=3D other.DeclSeq;
   }
@@ -218,9 +277,11 @@
   /// The caret will point unambiguously to the lock expression, so using =
this
   /// name in diagnostics is a way to get simple, and consistent, mutex na=
mes.
   /// We do not want to output the entire expression text for security rea=
sons.
-  StringRef getName() const {
+  std::string getName() const {
     assert(isValid());
-    return DeclSeq.front()->getName();
+    if (!DeclSeq.front())
+      return "this";  // Use 0 to represent 'this'.
+    return DeclSeq.front()->getNameAsString();
   }
=20
   void Profile(llvm::FoldingSetNodeID &ID) const {
@@ -231,6 +292,7 @@
   }
 };
=20
+
 /// \brief This is a helper class that stores info about the most recent
 /// accquire of a Lock.
 ///
@@ -245,9 +307,14 @@
   ///
   /// FIXME: add support for re-entrant locking and lock up/downgrading
   LockKind LKind;
+  MutexID UnderlyingMutex;  // for ScopedLockable objects
=20
   LockData(SourceLocation AcquireLoc, LockKind LKind)
-    : AcquireLoc(AcquireLoc), LKind(LKind) {}
+    : AcquireLoc(AcquireLoc), LKind(LKind), UnderlyingMutex(Decl::EmptyShe=
ll())
+  {}
+
+  LockData(SourceLocation AcquireLoc, LockKind LKind, const MutexID &Mu)
+    : AcquireLoc(AcquireLoc), LKind(LKind), UnderlyingMutex(Mu) {}
=20
   bool operator=3D=3D(const LockData &other) const {
     return AcquireLoc =3D=3D other.AcquireLoc && LKind =3D=3D other.LKind;
@@ -258,14 +325,567 @@
   }
=20
   void Profile(llvm::FoldingSetNodeID &ID) const {
-      ID.AddInteger(AcquireLoc.getRawEncoding());
-      ID.AddInteger(LKind);
-    }
+    ID.AddInteger(AcquireLoc.getRawEncoding());
+    ID.AddInteger(LKind);
+  }
 };
=20
+
 /// A Lockset maps each MutexID (defined above) to information about how i=
t has
 /// been locked.
 typedef llvm::ImmutableMap<MutexID, LockData> Lockset;
+typedef llvm::ImmutableMap<NamedDecl*, unsigned> LocalVarContext;
+
+class LocalVariableMap;
+
+/// A side (entry or exit) of a CFG node.
+enum CFGBlockSide { CBS_Entry, CBS_Exit };
+
+/// CFGBlockInfo is a struct which contains all the information that is
+/// maintained for each block in the CFG.  See LocalVariableMap for more
+/// information about the contexts.
+struct CFGBlockInfo {
+  Lockset EntrySet;             // Lockset held at entry to block
+  Lockset ExitSet;              // Lockset held at exit from block
+  LocalVarContext EntryContext; // Context held at entry to block
+  LocalVarContext ExitContext;  // Context held at exit from block
+  SourceLocation EntryLoc;      // Location of first statement in block
+  SourceLocation ExitLoc;       // Location of last statement in block.
+  unsigned EntryIndex;          // Used to replay contexts later
+
+  const Lockset &getSet(CFGBlockSide Side) const {
+    return Side =3D=3D CBS_Entry ? EntrySet : ExitSet;
+  }
+  SourceLocation getLocation(CFGBlockSide Side) const {
+    return Side =3D=3D CBS_Entry ? EntryLoc : ExitLoc;
+  }
+
+private:
+  CFGBlockInfo(Lockset EmptySet, LocalVarContext EmptyCtx)
+    : EntrySet(EmptySet), ExitSet(EmptySet),
+      EntryContext(EmptyCtx), ExitContext(EmptyCtx)
+  { }
+
+public:
+  static CFGBlockInfo getEmptyBlockInfo(Lockset::Factory &F,
+                                        LocalVariableMap &M);
+};
+
+
+
+// A LocalVariableMap maintains a map from local variables to their curren=
tly
+// valid definitions.  It provides SSA-like functionality when traversing =
the
+// CFG.  Like SSA, each definition or assignment to a variable is assigned=
 a
+// unique name (an integer), which acts as the SSA name for that definitio=
n.
+// The total set of names is shared among all CFG basic blocks.
+// Unlike SSA, we do not rewrite expressions to replace local variables de=
clrefs
+// with their SSA-names.  Instead, we compute a Context for each point in =
the
+// code, which maps local variables to the appropriate SSA-name.  This map
+// changes with each assignment.
+//
+// The map is computed in a single pass over the CFG.  Subsequent analyses=
 can
+// then query the map to find the appropriate Context for a statement, and=
 use
+// that Context to look up the definitions of variables.
+class LocalVariableMap {
+public:
+  typedef LocalVarContext Context;
+
+  /// A VarDefinition consists of an expression, representing the value of=
 the
+  /// variable, along with the context in which that expression should be
+  /// interpreted.  A reference VarDefinition does not itself contain this
+  /// information, but instead contains a pointer to a previous VarDefinit=
ion.
+  struct VarDefinition {
+  public:
+    friend class LocalVariableMap;
+
+    NamedDecl *Dec;       // The original declaration for this variable.
+    Expr *Exp;            // The expression for this variable, OR
+    unsigned Ref;         // Reference to another VarDefinition
+    Context Ctx;          // The map with which Exp should be interpreted.
+
+    bool isReference() { return !Exp; }
+
+  private:
+    // Create ordinary variable definition
+    VarDefinition(NamedDecl *D, Expr *E, Context C)
+      : Dec(D), Exp(E), Ref(0), Ctx(C)
+    { }
+
+    // Create reference to previous definition
+    VarDefinition(NamedDecl *D, unsigned R, Context C)
+      : Dec(D), Exp(0), Ref(R), Ctx(C)
+    { }
+  };
+
+private:
+  Context::Factory ContextFactory;
+  std::vector<VarDefinition> VarDefinitions;
+  std::vector<unsigned> CtxIndices;
+  std::vector<std::pair<Stmt*, Context> > SavedContexts;
+
+public:
+  LocalVariableMap() {
+    // index 0 is a placeholder for undefined variables (aka phi-nodes).
+    VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
+  }
+
+  /// Look up a definition, within the given context.
+  const VarDefinition* lookup(NamedDecl *D, Context Ctx) {
+    const unsigned *i =3D Ctx.lookup(D);
+    if (!i)
+      return 0;
+    assert(*i < VarDefinitions.size());
+    return &VarDefinitions[*i];
+  }
+
+  /// Look up the definition for D within the given context.  Returns
+  /// NULL if the expression is not statically known.  If successful, also
+  /// modifies Ctx to hold the context of the return Expr.
+  Expr* lookupExpr(NamedDecl *D, Context &Ctx) {
+    const unsigned *P =3D Ctx.lookup(D);
+    if (!P)
+      return 0;
+
+    unsigned i =3D *P;
+    while (i > 0) {
+      if (VarDefinitions[i].Exp) {
+        Ctx =3D VarDefinitions[i].Ctx;
+        return VarDefinitions[i].Exp;
+      }
+      i =3D VarDefinitions[i].Ref;
+    }
+    return 0;
+  }
+
+  Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
+
+  /// Return the next context after processing S.  This function is used by
+  /// clients of the class to get the appropriate context when traversing =
the
+  /// CFG.  It must be called for every assignment or DeclStmt.
+  Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
+    if (SavedContexts[CtxIndex+1].first =3D=3D S) {
+      CtxIndex++;
+      Context Result =3D SavedContexts[CtxIndex].second;
+      return Result;
+    }
+    return C;
+  }
+
+  void dumpVarDefinitionName(unsigned i) {
+    if (i =3D=3D 0) {
+      llvm::errs() << "Undefined";
+      return;
+    }
+    NamedDecl *Dec =3D VarDefinitions[i].Dec;
+    if (!Dec) {
+      llvm::errs() << "<<NULL>>";
+      return;
+    }
+    Dec->printName(llvm::errs());
+    llvm::errs() << "." << i << " " << ((void*) Dec);
+  }
+
+  /// Dumps an ASCII representation of the variable map to llvm::errs()
+  void dump() {
+    for (unsigned i =3D 1, e =3D VarDefinitions.size(); i < e; ++i) {
+      Expr *Exp =3D VarDefinitions[i].Exp;
+      unsigned Ref =3D VarDefinitions[i].Ref;
+
+      dumpVarDefinitionName(i);
+      llvm::errs() << " =3D ";
+      if (Exp) Exp->dump();
+      else {
+        dumpVarDefinitionName(Ref);
+        llvm::errs() << "\n";
+      }
+    }
+  }
+
+  /// Dumps an ASCII representation of a Context to llvm::errs()
+  void dumpContext(Context C) {
+    for (Context::iterator I =3D C.begin(), E =3D C.end(); I !=3D E; ++I) {
+      NamedDecl *D =3D I.getKey();
+      D->printName(llvm::errs());
+      const unsigned *i =3D C.lookup(D);
+      llvm::errs() << " -> ";
+      dumpVarDefinitionName(*i);
+      llvm::errs() << "\n";
+    }
+  }
+
+  /// Builds the variable map.
+  void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
+                     std::vector<CFGBlockInfo> &BlockInfo);
+
+protected:
+  // Get the current context index
+  unsigned getContextIndex() { return SavedContexts.size()-1; }
+
+  // Save the current context for later replay
+  void saveContext(Stmt *S, Context C) {
+    SavedContexts.push_back(std::make_pair(S,C));
+  }
+
+  // Adds a new definition to the given context, and returns a new context.
+  // This method should be called when declaring a new variable.
+  Context addDefinition(NamedDecl *D, Expr *Exp, Context Ctx) {
+    assert(!Ctx.contains(D));
+    unsigned newID =3D VarDefinitions.size();
+    Context NewCtx =3D ContextFactory.add(Ctx, D, newID);
+    VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
+    return NewCtx;
+  }
+
+  // Add a new reference to an existing definition.
+  Context addReference(NamedDecl *D, unsigned i, Context Ctx) {
+    unsigned newID =3D VarDefinitions.size();
+    Context NewCtx =3D ContextFactory.add(Ctx, D, newID);
+    VarDefinitions.push_back(VarDefinition(D, i, Ctx));
+    return NewCtx;
+  }
+
+  // Updates a definition only if that definition is already in the map.
+  // This method should be called when assigning to an existing variable.
+  Context updateDefinition(NamedDecl *D, Expr *Exp, Context Ctx) {
+    if (Ctx.contains(D)) {
+      unsigned newID =3D VarDefinitions.size();
+      Context NewCtx =3D ContextFactory.remove(Ctx, D);
+      NewCtx =3D ContextFactory.add(NewCtx, D, newID);
+      VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
+      return NewCtx;
+    }
+    return Ctx;
+  }
+
+  // Removes a definition from the context, but keeps the variable name
+  // as a valid variable.  The index 0 is a placeholder for cleared defini=
tions.
+  Context clearDefinition(NamedDecl *D, Context Ctx) {
+    Context NewCtx =3D Ctx;
+    if (NewCtx.contains(D)) {
+      NewCtx =3D ContextFactory.remove(NewCtx, D);
+      NewCtx =3D ContextFactory.add(NewCtx, D, 0);
+    }
+    return NewCtx;
+  }
+
+  // Remove a definition entirely frmo the context.
+  Context removeDefinition(NamedDecl *D, Context Ctx) {
+    Context NewCtx =3D Ctx;
+    if (NewCtx.contains(D)) {
+      NewCtx =3D ContextFactory.remove(NewCtx, D);
+    }
+    return NewCtx;
+  }
+
+  Context intersectContexts(Context C1, Context C2);
+  Context createReferenceContext(Context C);
+  void intersectBackEdge(Context C1, Context C2);
+
+  friend class VarMapBuilder;
+};
+
+
+// This has to be defined after LocalVariableMap.
+CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(Lockset::Factory &F,
+                                             LocalVariableMap &M) {
+  return CFGBlockInfo(F.getEmptyMap(), M.getEmptyContext());
+}
+
+
+/// Visitor which builds a LocalVariableMap
+class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
+public:
+  LocalVariableMap* VMap;
+  LocalVariableMap::Context Ctx;
+
+  VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
+    : VMap(VM), Ctx(C) {}
+
+  void VisitDeclStmt(DeclStmt *S);
+  void VisitBinaryOperator(BinaryOperator *BO);
+};
+
+
+// Add new local variables to the variable map
+void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
+  bool modifiedCtx =3D false;
+  DeclGroupRef DGrp =3D S->getDeclGroup();
+  for (DeclGroupRef::iterator I =3D DGrp.begin(), E =3D DGrp.end(); I !=3D=
 E; ++I) {
+    if (VarDecl *VD =3D dyn_cast_or_null<VarDecl>(*I)) {
+      Expr *E =3D VD->getInit();
+
+      // Add local variables with trivial type to the variable map
+      QualType T =3D VD->getType();
+      if (T.isTrivialType(VD->getASTContext())) {
+        Ctx =3D VMap->addDefinition(VD, E, Ctx);
+        modifiedCtx =3D true;
+      }
+    }
+  }
+  if (modifiedCtx)
+    VMap->saveContext(S, Ctx);
+}
+
+// Update local variable definitions in variable map
+void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
+  if (!BO->isAssignmentOp())
+    return;
+
+  Expr *LHSExp =3D BO->getLHS()->IgnoreParenCasts();
+
+  // Update the variable map and current context.
+  if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(LHSExp)) {
+    ValueDecl *VDec =3D DRE->getDecl();
+    if (Ctx.lookup(VDec)) {
+      if (BO->getOpcode() =3D=3D BO_Assign)
+        Ctx =3D VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
+      else
+        // FIXME -- handle compound assignment operators
+        Ctx =3D VMap->clearDefinition(VDec, Ctx);
+      VMap->saveContext(BO, Ctx);
+    }
+  }
+}
+
+
+// Computes the intersection of two contexts.  The intersection is the
+// set of variables which have the same definition in both contexts;
+// variables with different definitions are discarded.
+LocalVariableMap::Context
+LocalVariableMap::intersectContexts(Context C1, Context C2) {
+  Context Result =3D C1;
+  for (Context::iterator I =3D C1.begin(), E =3D C1.end(); I !=3D E; ++I) {
+    NamedDecl *Dec =3D I.getKey();
+    unsigned i1 =3D I.getData();
+    const unsigned *i2 =3D C2.lookup(Dec);
+    if (!i2)             // variable doesn't exist on second path
+      Result =3D removeDefinition(Dec, Result);
+    else if (*i2 !=3D i1)  // variable exists, but has different definition
+      Result =3D clearDefinition(Dec, Result);
+  }
+  return Result;
+}
+
+// For every variable in C, create a new variable that refers to the
+// definition in C.  Return a new context that contains these new variable=
s.
+// (We use this for a naive implementation of SSA on loop back-edges.)
+LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context=
 C) {
+  Context Result =3D getEmptyContext();
+  for (Context::iterator I =3D C.begin(), E =3D C.end(); I !=3D E; ++I) {
+    NamedDecl *Dec =3D I.getKey();
+    unsigned i =3D I.getData();
+    Result =3D addReference(Dec, i, Result);
+  }
+  return Result;
+}
+
+// This routine also takes the intersection of C1 and C2, but it does so by
+// altering the VarDefinitions.  C1 must be the result of an earlier call =
to
+// createReferenceContext.
+void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
+  for (Context::iterator I =3D C1.begin(), E =3D C1.end(); I !=3D E; ++I) {
+    NamedDecl *Dec =3D I.getKey();
+    unsigned i1 =3D I.getData();
+    VarDefinition *VDef =3D &VarDefinitions[i1];
+    assert(VDef->isReference());
+
+    const unsigned *i2 =3D C2.lookup(Dec);
+    if (!i2 || (*i2 !=3D i1))
+      VDef->Ref =3D 0;    // Mark this variable as undefined
+  }
+}
+
+
+// Traverse the CFG in topological order, so all predecessors of a block
+// (excluding back-edges) are visited before the block itself.  At
+// each point in the code, we calculate a Context, which holds the set of
+// variable definitions which are visible at that point in execution.
+// Visible variables are mapped to their definitions using an array that
+// contains all definitions.
+//
+// At join points in the CFG, the set is computed as the intersection of
+// the incoming sets along each edge, E.g.
+//
+//                       { Context                 | VarDefinitions }
+//   int x =3D 0;          { x -> x1                 | x1 =3D 0 }
+//   int y =3D 0;          { x -> x1, y -> y1        | y1 =3D 0, x1 =3D 0 }
+//   if (b) x =3D 1;       { x -> x2, y -> y1        | x2 =3D 1, y1 =3D 0,=
 ... }
+//   else   x =3D 2;       { x -> x3, y -> y1        | x3 =3D 2, x2 =3D 1,=
 ... }
+//   ...                 { y -> y1  (x is unknown) | x3 =3D 2, x2 =3D 1, .=
.. }
+//
+// This is essentially a simpler and more naive version of the standard SSA
+// algorithm.  Those definitions that remain in the intersection are from =
blocks
+// that strictly dominate the current block.  We do not bother to insert p=
roper
+// phi nodes, because they are not used in our analysis; instead, wherever
+// a phi node would be required, we simply remove that definition from the
+// context (E.g. x above).
+//
+// The initial traversal does not capture back-edges, so those need to be
+// handled on a separate pass.  Whenever the first pass encounters an
+// incoming back edge, it duplicates the context, creating new definitions
+// that refer back to the originals.  (These correspond to places where SSA
+// might have to insert a phi node.)  On the second pass, these definition=
s are
+// set to NULL if the the variable has changed on the back-edge (i.e. a phi
+// node was actually required.)  E.g.
+//
+//                       { Context           | VarDefinitions }
+//   int x =3D 0, y =3D 0;   { x -> x1, y -> y1  | y1 =3D 0, x1 =3D 0 }
+//   while (b)           { x -> x2, y -> y1  | [1st:] x2=3Dx1; [2nd:] x2=
=3DNULL; }
+//     x =3D x+1;          { x -> x3, y -> y1  | x3 =3D x2 + 1, ... }
+//   ...                 { y -> y1           | x3 =3D 2, x2 =3D 1, ... }
+//
+void LocalVariableMap::traverseCFG(CFG *CFGraph,
+                                   PostOrderCFGView *SortedGraph,
+                                   std::vector<CFGBlockInfo> &BlockInfo) {
+  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
+
+  CtxIndices.resize(CFGraph->getNumBlockIDs());
+
+  for (PostOrderCFGView::iterator I =3D SortedGraph->begin(),
+       E =3D SortedGraph->end(); I!=3D E; ++I) {
+    const CFGBlock *CurrBlock =3D *I;
+    int CurrBlockID =3D CurrBlock->getBlockID();
+    CFGBlockInfo *CurrBlockInfo =3D &BlockInfo[CurrBlockID];
+
+    VisitedBlocks.insert(CurrBlock);
+
+    // Calculate the entry context for the current block
+    bool HasBackEdges =3D false;
+    bool CtxInit =3D true;
+    for (CFGBlock::const_pred_iterator PI =3D CurrBlock->pred_begin(),
+         PE  =3D CurrBlock->pred_end(); PI !=3D PE; ++PI) {
+      // if *PI -> CurrBlock is a back edge, so skip it
+      if (*PI =3D=3D 0 || !VisitedBlocks.alreadySet(*PI)) {
+        HasBackEdges =3D true;
+        continue;
+      }
+
+      int PrevBlockID =3D (*PI)->getBlockID();
+      CFGBlockInfo *PrevBlockInfo =3D &BlockInfo[PrevBlockID];
+
+      if (CtxInit) {
+        CurrBlockInfo->EntryContext =3D PrevBlockInfo->ExitContext;
+        CtxInit =3D false;
+      }
+      else {
+        CurrBlockInfo->EntryContext =3D
+          intersectContexts(CurrBlockInfo->EntryContext,
+                            PrevBlockInfo->ExitContext);
+      }
+    }
+
+    // Duplicate the context if we have back-edges, so we can call
+    // intersectBackEdges later.
+    if (HasBackEdges)
+      CurrBlockInfo->EntryContext =3D
+        createReferenceContext(CurrBlockInfo->EntryContext);
+
+    // Create a starting context index for the current block
+    saveContext(0, CurrBlockInfo->EntryContext);
+    CurrBlockInfo->EntryIndex =3D getContextIndex();
+
+    // Visit all the statements in the basic block.
+    VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
+    for (CFGBlock::const_iterator BI =3D CurrBlock->begin(),
+         BE =3D CurrBlock->end(); BI !=3D BE; ++BI) {
+      switch (BI->getKind()) {
+        case CFGElement::Statement: {
+          const CFGStmt *CS =3D cast<CFGStmt>(&*BI);
+          VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
+          break;
+        }
+        default:
+          break;
+      }
+    }
+    CurrBlockInfo->ExitContext =3D VMapBuilder.Ctx;
+
+    // Mark variables on back edges as "unknown" if they've been changed.
+    for (CFGBlock::const_succ_iterator SI =3D CurrBlock->succ_begin(),
+         SE  =3D CurrBlock->succ_end(); SI !=3D SE; ++SI) {
+      // if CurrBlock -> *SI is *not* a back edge
+      if (*SI =3D=3D 0 || !VisitedBlocks.alreadySet(*SI))
+        continue;
+
+      CFGBlock *FirstLoopBlock =3D *SI;
+      Context LoopBegin =3D BlockInfo[FirstLoopBlock->getBlockID()].EntryC=
ontext;
+      Context LoopEnd   =3D CurrBlockInfo->ExitContext;
+      intersectBackEdge(LoopBegin, LoopEnd);
+    }
+  }
+
+  // Put an extra entry at the end of the indexed context array
+  unsigned exitID =3D CFGraph->getExit().getBlockID();
+  saveContext(0, BlockInfo[exitID].ExitContext);
+}
+
+/// Find the appropriate source locations to use when producing diagnostic=
s for
+/// each block in the CFG.
+static void findBlockLocations(CFG *CFGraph,
+                               PostOrderCFGView *SortedGraph,
+                               std::vector<CFGBlockInfo> &BlockInfo) {
+  for (PostOrderCFGView::iterator I =3D SortedGraph->begin(),
+       E =3D SortedGraph->end(); I!=3D E; ++I) {
+    const CFGBlock *CurrBlock =3D *I;
+    CFGBlockInfo *CurrBlockInfo =3D &BlockInfo[CurrBlock->getBlockID()];
+
+    // Find the source location of the last statement in the block, if the
+    // block is not empty.
+    if (const Stmt *S =3D CurrBlock->getTerminator()) {
+      CurrBlockInfo->EntryLoc =3D CurrBlockInfo->ExitLoc =3D S->getLocStar=
t();
+    } else {
+      for (CFGBlock::const_reverse_iterator BI =3D CurrBlock->rbegin(),
+           BE =3D CurrBlock->rend(); BI !=3D BE; ++BI) {
+        // FIXME: Handle other CFGElement kinds.
+        if (const CFGStmt *CS =3D dyn_cast<CFGStmt>(&*BI)) {
+          CurrBlockInfo->ExitLoc =3D CS->getStmt()->getLocStart();
+          break;
+        }
+      }
+    }
+
+    if (!CurrBlockInfo->ExitLoc.isInvalid()) {
+      // This block contains at least one statement. Find the source locat=
ion
+      // of the first statement in the block.
+      for (CFGBlock::const_iterator BI =3D CurrBlock->begin(),
+           BE =3D CurrBlock->end(); BI !=3D BE; ++BI) {
+        // FIXME: Handle other CFGElement kinds.
+        if (const CFGStmt *CS =3D dyn_cast<CFGStmt>(&*BI)) {
+          CurrBlockInfo->EntryLoc =3D CS->getStmt()->getLocStart();
+          break;
+        }
+      }
+    } else if (CurrBlock->pred_size() =3D=3D 1 && *CurrBlock->pred_begin()=
 &&
+               CurrBlock !=3D &CFGraph->getExit()) {
+      // The block is empty, and has a single predecessor. Use its exit
+      // location.
+      CurrBlockInfo->EntryLoc =3D CurrBlockInfo->ExitLoc =3D
+          BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
+    }
+  }
+}
+
+/// \brief Class which implements the core thread safety analysis routines.
+class ThreadSafetyAnalyzer {
+  friend class BuildLockset;
+
+  ThreadSafetyHandler &Handler;
+  Lockset::Factory    LocksetFactory;
+  LocalVariableMap    LocalVarMap;
+
+public:
+  ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
+
+  Lockset intersectAndWarn(const CFGBlockInfo &Block1, CFGBlockSide Side1,
+                           const CFGBlockInfo &Block2, CFGBlockSide Side2,
+                           LockErrorKind LEK);
+
+  Lockset addLock(Lockset &LSet, Expr *MutexExp, const NamedDecl *D,
+                  LockKind LK, SourceLocation Loc);
+
+  void runAnalysis(AnalysisDeclContext &AC);
+};
+
=20
 /// \brief We use this class to visit different types of expressions in
 /// CFGBlocks, and build up the lockset.
@@ -273,32 +893,51 @@
 /// output error messages related to missing locks.
 /// FIXME: In future, we may be able to not inherit from a visitor.
 class BuildLockset : public StmtVisitor<BuildLockset> {
+  friend class ThreadSafetyAnalyzer;
+
   ThreadSafetyHandler &Handler;
+  Lockset::Factory &LocksetFactory;
+  LocalVariableMap &LocalVarMap;
+
   Lockset LSet;
-  Lockset::Factory &LocksetFactory;
+  LocalVariableMap::Context LVarCtx;
+  unsigned CtxIndex;
=20
   // Helper functions
-  void removeLock(SourceLocation UnlockLoc, Expr *LockExp, Expr *Parent);
-  void addLock(SourceLocation LockLoc, Expr *LockExp, Expr *Parent,
-               LockKind LK);
+  void addLock(const MutexID &Mutex, const LockData &LDat);
+  void removeLock(const MutexID &Mutex, SourceLocation UnlockLoc);
+
+  template <class AttrType>
+  void addLocksToSet(LockKind LK, AttrType *Attr,
+                     Expr *Exp, NamedDecl *D, VarDecl *VD =3D 0);
+  void removeLocksFromSet(UnlockFunctionAttr *Attr,
+                          Expr *Exp, NamedDecl* FunDecl);
+
   const ValueDecl *getValueDecl(Expr *Exp);
   void warnIfMutexNotHeld (const NamedDecl *D, Expr *Exp, AccessKind AK,
                            Expr *MutexExp, ProtectedOperationKind POK);
   void checkAccess(Expr *Exp, AccessKind AK);
   void checkDereference(Expr *Exp, AccessKind AK);
+  void handleCall(Expr *Exp, NamedDecl *D, VarDecl *VD =3D 0);
=20
   template <class AttrType>
-  void addLocksToSet(LockKind LK, Attr *Attr, CXXMemberCallExpr *Exp);
+  void addTrylock(LockKind LK, AttrType *Attr, Expr *Exp, NamedDecl *FunDe=
cl,
+                  const CFGBlock* PredBlock, const CFGBlock *CurrBlock,
+                  Expr *BrE, bool Neg);
+  CallExpr* getTrylockCallExpr(Stmt *Cond, LocalVariableMap::Context C,
+                               bool &Negate);
+  void handleTrylock(Stmt *Cond, const CFGBlock* PredBlock,
+                     const CFGBlock *CurrBlock);
=20
   /// \brief Returns true if the lockset contains a lock, regardless of wh=
ether
   /// the lock is held exclusively or shared.
-  bool locksetContains(MutexID Lock) const {
+  bool locksetContains(const MutexID &Lock) const {
     return LSet.lookup(Lock);
   }
=20
   /// \brief Returns true if the lockset contains a lock with the passed in
   /// locktype.
-  bool locksetContains(MutexID Lock, LockKind KindRequested) const {
+  bool locksetContains(const MutexID &Lock, LockKind KindRequested) const {
     const LockData *LockHeld =3D LSet.lookup(Lock);
     return (LockHeld && KindRequested =3D=3D LockHeld->LKind);
   }
@@ -307,7 +946,8 @@
   /// passed in locktype. So for example, if we pass in LK_Shared, this fu=
nction
   /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pa=
ss in
   /// LK_Exclusive, this function returns true if the lock is held LK_Excl=
usive.
-  bool locksetContainsAtLeast(MutexID Lock, LockKind KindRequested) const {
+  bool locksetContainsAtLeast(const MutexID &Lock,
+                              LockKind KindRequested) const {
     switch (KindRequested) {
       case LK_Shared:
         return locksetContains(Lock);
@@ -318,57 +958,121 @@
   }
=20
 public:
-  BuildLockset(ThreadSafetyHandler &Handler, Lockset LS, Lockset::Factory =
&F)
-    : StmtVisitor<BuildLockset>(), Handler(Handler), LSet(LS),
-      LocksetFactory(F) {}
-
-  Lockset getLockset() {
-    return LSet;
-  }
+  BuildLockset(ThreadSafetyAnalyzer *analyzer, CFGBlockInfo &Info)
+    : StmtVisitor<BuildLockset>(),
+      Handler(analyzer->Handler),
+      LocksetFactory(analyzer->LocksetFactory),
+      LocalVarMap(analyzer->LocalVarMap),
+      LSet(Info.EntrySet),
+      LVarCtx(Info.EntryContext),
+      CtxIndex(Info.EntryIndex)
+  {}
=20
   void VisitUnaryOperator(UnaryOperator *UO);
   void VisitBinaryOperator(BinaryOperator *BO);
   void VisitCastExpr(CastExpr *CE);
-  void VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp);
+  void VisitCallExpr(CallExpr *Exp);
+  void VisitCXXConstructExpr(CXXConstructExpr *Exp);
+  void VisitDeclStmt(DeclStmt *S);
 };
=20
 /// \brief Add a new lock to the lockset, warning if the lock is already t=
here.
-/// \param LockLoc The source location of the acquire
-/// \param LockExp The lock expression corresponding to the lock to be add=
ed
-void BuildLockset::addLock(SourceLocation LockLoc, Expr *LockExp, Expr *Pa=
rent,
-                           LockKind LK) {
-  // FIXME: deal with acquired before/after annotations. We can write a fi=
rst
-  // pass that does the transitive lookup lazily, and refine afterwards.
-  MutexID Mutex(LockExp, Parent);
-  if (!Mutex.isValid()) {
-    Handler.handleInvalidLockExp(LockExp->getExprLoc());
-    return;
-  }
-
-  LockData NewLock(LockLoc, LK);
-
+/// \param Mutex -- the Mutex expression for the lock
+/// \param LDat  -- the LockData for the lock
+void BuildLockset::addLock(const MutexID &Mutex, const LockData& LDat) {
+  // FIXME: deal with acquired before/after annotations.
   // FIXME: Don't always warn when we have support for reentrant locks.
   if (locksetContains(Mutex))
-    Handler.handleDoubleLock(Mutex.getName(), LockLoc);
-  LSet =3D LocksetFactory.add(LSet, Mutex, NewLock);
+    Handler.handleDoubleLock(Mutex.getName(), LDat.AcquireLoc);
+  else
+    LSet =3D LocksetFactory.add(LSet, Mutex, LDat);
 }
=20
 /// \brief Remove a lock from the lockset, warning if the lock is not ther=
e.
 /// \param LockExp The lock expression corresponding to the lock to be rem=
oved
 /// \param UnlockLoc The source location of the unlock (only used in error=
 msg)
-void BuildLockset::removeLock(SourceLocation UnlockLoc, Expr *LockExp,
-                              Expr *Parent) {
-  MutexID Mutex(LockExp, Parent);
-  if (!Mutex.isValid()) {
-    Handler.handleInvalidLockExp(LockExp->getExprLoc());
+void BuildLockset::removeLock(const MutexID &Mutex, SourceLocation UnlockL=
oc) {
+  const LockData *LDat =3D LSet.lookup(Mutex);
+  if (!LDat)
+    Handler.handleUnmatchedUnlock(Mutex.getName(), UnlockLoc);
+  else {
+    // For scoped-lockable vars, remove the mutex associated with this var.
+    if (LDat->UnderlyingMutex.isValid())
+      removeLock(LDat->UnderlyingMutex, UnlockLoc);
+    LSet =3D LocksetFactory.remove(LSet, Mutex);
+  }
+}
+
+/// \brief This function, parameterized by an attribute type, is used to a=
dd a
+/// set of locks specified as attribute arguments to the lockset.
+template <typename AttrType>
+void BuildLockset::addLocksToSet(LockKind LK, AttrType *Attr,
+                                 Expr *Exp, NamedDecl* FunDecl, VarDecl *V=
D) {
+  typedef typename AttrType::args_iterator iterator_type;
+
+  SourceLocation ExpLocation =3D Exp->getExprLoc();
+
+  // Figure out if we're calling the constructor of scoped lockable class
+  bool isScopedVar =3D false;
+  if (VD) {
+    if (CXXConstructorDecl *CD =3D dyn_cast<CXXConstructorDecl>(FunDecl)) {
+      CXXRecordDecl* PD =3D CD->getParent();
+      if (PD && PD->getAttr<ScopedLockableAttr>())
+        isScopedVar =3D true;
+    }
+  }
+
+  if (Attr->args_size() =3D=3D 0) {
+    // The mutex held is the "this" object.
+    MutexID Mutex(0, Exp, FunDecl);
+    if (!Mutex.isValid())
+      MutexID::warnInvalidLock(Handler, 0, Exp, FunDecl);
+    else
+      addLock(Mutex, LockData(ExpLocation, LK));
     return;
   }
=20
-  Lockset NewLSet =3D LocksetFactory.remove(LSet, Mutex);
-  if(NewLSet =3D=3D LSet)
-    Handler.handleUnmatchedUnlock(Mutex.getName(), UnlockLoc);
+  for (iterator_type I=3DAttr->args_begin(), E=3DAttr->args_end(); I !=3D =
E; ++I) {
+    MutexID Mutex(*I, Exp, FunDecl);
+    if (!Mutex.isValid())
+      MutexID::warnInvalidLock(Handler, *I, Exp, FunDecl);
+    else {
+      addLock(Mutex, LockData(ExpLocation, LK));
+      if (isScopedVar) {
+        // For scoped lockable vars, map this var to its underlying mutex.
+        DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocati=
on());
+        MutexID SMutex(&DRE, 0, 0);
+        addLock(SMutex, LockData(VD->getLocation(), LK, Mutex));
+      }
+    }
+  }
+}
=20
-  LSet =3D NewLSet;
+/// \brief This function removes a set of locks specified as attribute
+/// arguments from the lockset.
+void BuildLockset::removeLocksFromSet(UnlockFunctionAttr *Attr,
+                                      Expr *Exp, NamedDecl* FunDecl) {
+  SourceLocation ExpLocation;
+  if (Exp) ExpLocation =3D Exp->getExprLoc();
+
+  if (Attr->args_size() =3D=3D 0) {
+    // The mutex held is the "this" object.
+    MutexID Mu(0, Exp, FunDecl);
+    if (!Mu.isValid())
+      MutexID::warnInvalidLock(Handler, 0, Exp, FunDecl);
+    else
+      removeLock(Mu, ExpLocation);
+    return;
+  }
+
+  for (UnlockFunctionAttr::args_iterator I =3D Attr->args_begin(),
+       E =3D Attr->args_end(); I !=3D E; ++I) {
+    MutexID Mutex(*I, Exp, FunDecl);
+    if (!Mutex.isValid())
+      MutexID::warnInvalidLock(Handler, *I, Exp, FunDecl);
+    else
+      removeLock(Mutex, ExpLocation);
+  }
 }
=20
 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
@@ -383,20 +1087,19 @@
 }
=20
 /// \brief Warn if the LSet does not contain a lock sufficient to protect =
access
-/// of at least the passed in AccessType.
+/// of at least the passed in AccessKind.
 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
                                       AccessKind AK, Expr *MutexExp,
                                       ProtectedOperationKind POK) {
   LockKind LK =3D getLockKindFromAccessKind(AK);
-  Expr *Parent =3D getParent(Exp);
-  MutexID Mutex(MutexExp, Parent);
+
+  MutexID Mutex(MutexExp, Exp, D);
   if (!Mutex.isValid())
-    Handler.handleInvalidLockExp(MutexExp->getExprLoc());
+    MutexID::warnInvalidLock(Handler, MutexExp, Exp, D);
   else if (!locksetContainsAtLeast(Mutex, LK))
     Handler.handleMutexNotHeld(D, POK, Mutex.getName(), LK, Exp->getExprLo=
c());
 }
=20
-
 /// \brief This method identifies variable dereferences and checks pt_guar=
ded_by
 /// and pt_guarded_var annotations. Note that we only check these annotati=
ons
 /// at the time a pointer is dereferenced.
@@ -440,71 +1143,10 @@
       warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
 }
=20
-/// \brief For unary operations which read and write a variable, we need to
-/// check whether we hold any required mutexes. Reads are checked in
-/// VisitCastExpr.
-void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
-  switch (UO->getOpcode()) {
-    case clang::UO_PostDec:
-    case clang::UO_PostInc:
-    case clang::UO_PreDec:
-    case clang::UO_PreInc: {
-      Expr *SubExp =3D UO->getSubExpr()->IgnoreParenCasts();
-      checkAccess(SubExp, AK_Written);
-      checkDereference(SubExp, AK_Written);
-      break;
-    }
-    default:
-      break;
-  }
-}
-
-/// For binary operations which assign to a variable (writes), we need to =
check
-/// whether we hold any required mutexes.
-/// FIXME: Deal with non-primitive types.
-void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
-  if (!BO->isAssignmentOp())
-    return;
-  Expr *LHSExp =3D BO->getLHS()->IgnoreParenCasts();
-  checkAccess(LHSExp, AK_Written);
-  checkDereference(LHSExp, AK_Written);
-}
-
-/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
-/// need to ensure we hold any required mutexes.
-/// FIXME: Deal with non-primitive types.
-void BuildLockset::VisitCastExpr(CastExpr *CE) {
-  if (CE->getCastKind() !=3D CK_LValueToRValue)
-    return;
-  Expr *SubExp =3D CE->getSubExpr()->IgnoreParenCasts();
-  checkAccess(SubExp, AK_Read);
-  checkDereference(SubExp, AK_Read);
-}
-
-/// \brief This function, parameterized by an attribute type, is used to a=
dd a
-/// set of locks specified as attribute arguments to the lockset.
-template <typename AttrType>
-void BuildLockset::addLocksToSet(LockKind LK, Attr *Attr,
-                                 CXXMemberCallExpr *Exp) {
-  typedef typename AttrType::args_iterator iterator_type;
-  SourceLocation ExpLocation =3D Exp->getExprLoc();
-  Expr *Parent =3D Exp->getImplicitObjectArgument();
-  AttrType *SpecificAttr =3D cast<AttrType>(Attr);
-
-  if (SpecificAttr->args_size() =3D=3D 0) {
-    // The mutex held is the "this" object.
-    addLock(ExpLocation, Parent, 0, LK);
-    return;
-  }
-
-  for (iterator_type I =3D SpecificAttr->args_begin(),
-       E =3D SpecificAttr->args_end(); I !=3D E; ++I)
-    addLock(ExpLocation, *I, Parent, LK);
-}
-
-/// \brief When visiting CXXMemberCallExprs we need to examine the attribu=
tes on
-/// the method that is being called and add, remove or check locks in the
-/// lockset accordingly.
+/// \brief Process a function call, method call, constructor call,
+/// or destructor call.  This involves looking at the attributes on the
+/// corresponding function/method/constructor/destructor, issuing warnings,
+/// and updating the locksets accordingly.
 ///
 /// FIXME: For classes annotated with one of the guarded annotations, we n=
eed
 /// to treat const method calls as reads and non-const method calls as wri=
tes,
@@ -515,44 +1157,32 @@
 ///
 /// FIXME: Do not flag an error for member variables accessed in construct=
ors/
 /// destructors
-void BuildLockset::VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp) {
-  NamedDecl *D =3D dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
-
-  SourceLocation ExpLocation =3D Exp->getExprLoc();
-  Expr *Parent =3D Exp->getImplicitObjectArgument();
-
-  if(!D || !D->hasAttrs())
-    return;
-
+void BuildLockset::handleCall(Expr *Exp, NamedDecl *D, VarDecl *VD) {
   AttrVec &ArgAttrs =3D D->getAttrs();
   for(unsigned i =3D 0; i < ArgAttrs.size(); ++i) {
     Attr *Attr =3D ArgAttrs[i];
     switch (Attr->getKind()) {
       // When we encounter an exclusive lock function, we need to add the =
lock
       // to our lockset with kind exclusive.
-      case attr::ExclusiveLockFunction:
-        addLocksToSet<ExclusiveLockFunctionAttr>(LK_Exclusive, Attr, Exp);
+      case attr::ExclusiveLockFunction: {
+        ExclusiveLockFunctionAttr *A =3D cast<ExclusiveLockFunctionAttr>(A=
ttr);
+        addLocksToSet(LK_Exclusive, A, Exp, D, VD);
         break;
+      }
=20
       // When we encounter a shared lock function, we need to add the lock
       // to our lockset with kind shared.
-      case attr::SharedLockFunction:
-        addLocksToSet<SharedLockFunctionAttr>(LK_Shared, Attr, Exp);
+      case attr::SharedLockFunction: {
+        SharedLockFunctionAttr *A =3D cast<SharedLockFunctionAttr>(Attr);
+        addLocksToSet(LK_Shared, A, Exp, D, VD);
         break;
+      }
=20
       // When we encounter an unlock function, we need to remove unlocked
       // mutexes from the lockset, and flag a warning if they are not ther=
e.
       case attr::UnlockFunction: {
         UnlockFunctionAttr *UFAttr =3D cast<UnlockFunctionAttr>(Attr);
-
-        if (UFAttr->args_size() =3D=3D 0) { // The lock held is the "this"=
 object.
-          removeLock(ExpLocation, Parent, 0);
-          break;
-        }
-
-        for (UnlockFunctionAttr::args_iterator I =3D UFAttr->args_begin(),
-             E =3D UFAttr->args_end(); I !=3D E; ++I)
-          removeLock(ExpLocation, *I, Parent);
+        removeLocksFromSet(UFAttr, Exp, D);
         break;
       }
=20
@@ -579,12 +1209,12 @@
         LocksExcludedAttr *LEAttr =3D cast<LocksExcludedAttr>(Attr);
         for (LocksExcludedAttr::args_iterator I =3D LEAttr->args_begin(),
             E =3D LEAttr->args_end(); I !=3D E; ++I) {
-          MutexID Mutex(*I, Parent);
+          MutexID Mutex(*I, Exp, D);
           if (!Mutex.isValid())
-            Handler.handleInvalidLockExp((*I)->getExprLoc());
+            MutexID::warnInvalidLock(Handler, *I, Exp, D);
           else if (locksetContains(Mutex))
             Handler.handleFunExcludesLock(D->getName(), Mutex.getName(),
-                                          ExpLocation);
+                                          Exp->getExprLoc());
         }
         break;
       }
@@ -596,7 +1226,180 @@
   }
 }
=20
-} // end anonymous namespace
+
+/// \brief Add lock to set, if the current block is in the taken branch of=
 a
+/// trylock.
+template <class AttrType>
+void BuildLockset::addTrylock(LockKind LK, AttrType *Attr, Expr *Exp,
+                              NamedDecl *FunDecl, const CFGBlock *PredBloc=
k,
+                              const CFGBlock *CurrBlock, Expr *BrE, bool N=
eg) {
+  // Find out which branch has the lock
+  bool branch =3D 0;
+  if (CXXBoolLiteralExpr *BLE =3D dyn_cast_or_null<CXXBoolLiteralExpr>(BrE=
)) {
+    branch =3D BLE->getValue();
+  }
+  else if (IntegerLiteral *ILE =3D dyn_cast_or_null<IntegerLiteral>(BrE)) {
+    branch =3D ILE->getValue().getBoolValue();
+  }
+  int branchnum =3D branch ? 0 : 1;
+  if (Neg) branchnum =3D !branchnum;
+
+  // If we've taken the trylock branch, then add the lock
+  int i =3D 0;
+  for (CFGBlock::const_succ_iterator SI =3D PredBlock->succ_begin(),
+       SE =3D PredBlock->succ_end(); SI !=3D SE && i < 2; ++SI, ++i) {
+    if (*SI =3D=3D CurrBlock && i =3D=3D branchnum) {
+      addLocksToSet(LK, Attr, Exp, FunDecl, 0);
+    }
+  }
+}
+
+
+// If Cond can be traced back to a function call, return the call expressi=
on.
+// The negate variable should be called with false, and will be set to true
+// if the function call is negated, e.g. if (!mu.tryLock(...))
+CallExpr* BuildLockset::getTrylockCallExpr(Stmt *Cond,
+                               LocalVariableMap::Context C,
+                               bool &Negate) {
+  if (!Cond)
+    return 0;
+
+  if (CallExpr *CallExp =3D dyn_cast<CallExpr>(Cond)) {
+    return CallExp;
+  }
+  else if (ImplicitCastExpr *CE =3D dyn_cast<ImplicitCastExpr>(Cond)) {
+    return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
+  }
+  else if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(Cond)) {
+    Expr *E =3D LocalVarMap.lookupExpr(DRE->getDecl(), C);
+    return getTrylockCallExpr(E, C, Negate);
+  }
+  else if (UnaryOperator *UOP =3D dyn_cast<UnaryOperator>(Cond)) {
+    if (UOP->getOpcode() =3D=3D UO_LNot) {
+      Negate =3D !Negate;
+      return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
+    }
+  }
+  // FIXME -- handle && and || as well.
+  return NULL;
+}
+
+
+/// \brief Process a conditional branch from a previous block to the curre=
nt
+/// block, looking for trylock calls.
+void BuildLockset::handleTrylock(Stmt *Cond, const CFGBlock *PredBlock,
+                                 const CFGBlock *CurrBlock) {
+  bool Negate =3D false;
+  CallExpr *Exp =3D getTrylockCallExpr(Cond, LVarCtx, Negate);
+  if (!Exp)
+    return;
+
+  NamedDecl *FunDecl =3D dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
+  if(!FunDecl || !FunDecl->hasAttrs())
+    return;
+
+  // If the condition is a call to a Trylock function, then grab the attri=
butes
+  AttrVec &ArgAttrs =3D FunDecl->getAttrs();
+  for (unsigned i =3D 0; i < ArgAttrs.size(); ++i) {
+    Attr *Attr =3D ArgAttrs[i];
+    switch (Attr->getKind()) {
+      case attr::ExclusiveTrylockFunction: {
+        ExclusiveTrylockFunctionAttr *A =3D
+          cast<ExclusiveTrylockFunctionAttr>(Attr);
+        addTrylock(LK_Exclusive, A, Exp, FunDecl, PredBlock, CurrBlock,
+                   A->getSuccessValue(), Negate);
+        break;
+      }
+      case attr::SharedTrylockFunction: {
+        SharedTrylockFunctionAttr *A =3D
+          cast<SharedTrylockFunctionAttr>(Attr);
+        addTrylock(LK_Shared, A, Exp, FunDecl, PredBlock, CurrBlock,
+                   A->getSuccessValue(), Negate);
+        break;
+      }
+      default:
+        break;
+    }
+  }
+}
+
+
+/// \brief For unary operations which read and write a variable, we need to
+/// check whether we hold any required mutexes. Reads are checked in
+/// VisitCastExpr.
+void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
+  switch (UO->getOpcode()) {
+    case clang::UO_PostDec:
+    case clang::UO_PostInc:
+    case clang::UO_PreDec:
+    case clang::UO_PreInc: {
+      Expr *SubExp =3D UO->getSubExpr()->IgnoreParenCasts();
+      checkAccess(SubExp, AK_Written);
+      checkDereference(SubExp, AK_Written);
+      break;
+    }
+    default:
+      break;
+  }
+}
+
+/// For binary operations which assign to a variable (writes), we need to =
check
+/// whether we hold any required mutexes.
+/// FIXME: Deal with non-primitive types.
+void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
+  if (!BO->isAssignmentOp())
+    return;
+
+  // adjust the context
+  LVarCtx =3D LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
+
+  Expr *LHSExp =3D BO->getLHS()->IgnoreParenCasts();
+  checkAccess(LHSExp, AK_Written);
+  checkDereference(LHSExp, AK_Written);
+}
+
+/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
+/// need to ensure we hold any required mutexes.
+/// FIXME: Deal with non-primitive types.
+void BuildLockset::VisitCastExpr(CastExpr *CE) {
+  if (CE->getCastKind() !=3D CK_LValueToRValue)
+    return;
+  Expr *SubExp =3D CE->getSubExpr()->IgnoreParenCasts();
+  checkAccess(SubExp, AK_Read);
+  checkDereference(SubExp, AK_Read);
+}
+
+
+void BuildLockset::VisitCallExpr(CallExpr *Exp) {
+  NamedDecl *D =3D dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
+  if(!D || !D->hasAttrs())
+    return;
+  handleCall(Exp, D);
+}
+
+void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
+  // FIXME -- only handles constructors in DeclStmt below.
+}
+
+void BuildLockset::VisitDeclStmt(DeclStmt *S) {
+  // adjust the context
+  LVarCtx =3D LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
+
+  DeclGroupRef DGrp =3D S->getDeclGroup();
+  for (DeclGroupRef::iterator I =3D DGrp.begin(), E =3D DGrp.end(); I !=3D=
 E; ++I) {
+    Decl *D =3D *I;
+    if (VarDecl *VD =3D dyn_cast_or_null<VarDecl>(D)) {
+      Expr *E =3D VD->getInit();
+      if (CXXConstructExpr *CE =3D dyn_cast_or_null<CXXConstructExpr>(E)) {
+        NamedDecl *CtorD =3D dyn_cast_or_null<NamedDecl>(CE->getConstructo=
r());
+        if (!CtorD || !CtorD->hasAttrs())
+          return;
+        handleCall(CE, CtorD, VD);
+      }
+    }
+  }
+}
+
=20
 /// \brief Compute the intersection of two locksets and issue warnings for=
 any
 /// locks in the symmetric difference.
@@ -606,9 +1409,14 @@
 /// A; if () then B; else C; D; we need to check that the lockset after B =
and C
 /// are the same. In the event of a difference, we use the intersection of=
 these
 /// two locksets at the start of D.
-static Lockset intersectAndWarn(ThreadSafetyHandler &Handler,
-                                const Lockset LSet1, const Lockset LSet2,
-                                Lockset::Factory &Fact, LockErrorKind LEK)=
 {
+Lockset ThreadSafetyAnalyzer::intersectAndWarn(const CFGBlockInfo &Block1,
+                                               CFGBlockSide Side1,
+                                               const CFGBlockInfo &Block2,
+                                               CFGBlockSide Side2,
+                                               LockErrorKind LEK) {
+  Lockset LSet1 =3D Block1.getSet(Side1);
+  Lockset LSet2 =3D Block2.getSet(Side2);
+
   Lockset Intersection =3D LSet1;
   for (Lockset::iterator I =3D LSet2.begin(), E =3D LSet2.end(); I !=3D E;=
 ++I) {
     const MutexID &LSet2Mutex =3D I.getKey();
@@ -619,11 +1427,13 @@
                                          LSet2LockData.AcquireLoc,
                                          LD->AcquireLoc);
         if (LD->LKind !=3D LK_Exclusive)
-          Intersection =3D Fact.add(Intersection, LSet2Mutex, LSet2LockDat=
a);
+          Intersection =3D LocksetFactory.add(Intersection, LSet2Mutex,
+                                            LSet2LockData);
       }
     } else {
       Handler.handleMutexHeldEndOfScope(LSet2Mutex.getName(),
-                                        LSet2LockData.AcquireLoc, LEK);
+                                        LSet2LockData.AcquireLoc,
+                                        Block1.getLocation(Side1), LEK);
     }
   }
=20
@@ -632,91 +1442,111 @@
       const MutexID &Mutex =3D I.getKey();
       const LockData &MissingLock =3D I.getData();
       Handler.handleMutexHeldEndOfScope(Mutex.getName(),
-                                        MissingLock.AcquireLoc, LEK);
-      Intersection =3D Fact.remove(Intersection, Mutex);
+                                        MissingLock.AcquireLoc,
+                                        Block2.getLocation(Side2), LEK);
+      Intersection =3D LocksetFactory.remove(Intersection, Mutex);
     }
   }
   return Intersection;
 }
=20
-static Lockset addLock(ThreadSafetyHandler &Handler,
-                       Lockset::Factory &LocksetFactory,
-                       Lockset &LSet, Expr *LockExp, LockKind LK,
-                       SourceLocation Loc) {
-  MutexID Mutex(LockExp, 0);
+Lockset ThreadSafetyAnalyzer::addLock(Lockset &LSet, Expr *MutexExp,
+                                      const NamedDecl *D,
+                                      LockKind LK, SourceLocation Loc) {
+  MutexID Mutex(MutexExp, 0, D);
   if (!Mutex.isValid()) {
-    Handler.handleInvalidLockExp(LockExp->getExprLoc());
+    MutexID::warnInvalidLock(Handler, MutexExp, 0, D);
     return LSet;
   }
   LockData NewLock(Loc, LK);
   return LocksetFactory.add(LSet, Mutex, NewLock);
 }
=20
-namespace clang {
-namespace thread_safety {
 /// \brief Check a function's CFG for thread-safety violations.
 ///
 /// We traverse the blocks in the CFG, compute the set of mutexes that are=
 held
 /// at the end of each block, and issue warnings for thread safety violati=
ons.
 /// Each block in the CFG is traversed exactly once.
-void runThreadSafetyAnalysis(AnalysisContext &AC,
-                             ThreadSafetyHandler &Handler) {
+void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
   CFG *CFGraph =3D AC.getCFG();
   if (!CFGraph) return;
-  const Decl *D =3D AC.getDecl();
-  if (D && D->getAttr<NoThreadSafetyAnalysisAttr>()) return;
+  const NamedDecl *D =3D dyn_cast_or_null<NamedDecl>(AC.getDecl());
=20
-  Lockset::Factory LocksetFactory;
+  if (!D)
+    return;  // Ignore anonymous functions for now.
+  if (D->getAttr<NoThreadSafetyAnalysisAttr>())
+    return;
+  // FIXME: Do something a bit more intelligent inside constructor and
+  // destructor code.  Constructors and destructors must assume unique acc=
ess
+  // to 'this', so checks on member variable access is disabled, but we sh=
ould
+  // still enable checks on other objects.
+  if (isa<CXXConstructorDecl>(D))
+    return;  // Don't check inside constructors.
+  if (isa<CXXDestructorDecl>(D))
+    return;  // Don't check inside destructors.
=20
-  // FIXME: Swith to SmallVector? Otherwise improve performance impact?
-  std::vector<Lockset> EntryLocksets(CFGraph->getNumBlockIDs(),
-                                     LocksetFactory.getEmptyMap());
-  std::vector<Lockset> ExitLocksets(CFGraph->getNumBlockIDs(),
-                                    LocksetFactory.getEmptyMap());
+  std::vector<CFGBlockInfo> BlockInfo(CFGraph->getNumBlockIDs(),
+    CFGBlockInfo::getEmptyBlockInfo(LocksetFactory, LocalVarMap));
=20
   // We need to explore the CFG via a "topological" ordering.
   // That way, we will be guaranteed to have information about required
   // predecessor locksets when exploring a new block.
-  TopologicallySortedCFG SortedGraph(CFGraph);
-  CFGBlockSet VisitedBlocks(CFGraph);
+  PostOrderCFGView *SortedGraph =3D AC.getAnalysis<PostOrderCFGView>();
+  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
=20
-  if (!SortedGraph.empty() && D->hasAttrs()) {
-    const CFGBlock *FirstBlock =3D *SortedGraph.begin();
-    Lockset &InitialLockset =3D EntryLocksets[FirstBlock->getBlockID()];
+  // Compute SSA names for local variables
+  LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
+
+  // Fill in source locations for all CFGBlocks.
+  findBlockLocations(CFGraph, SortedGraph, BlockInfo);
+
+  // Add locks from exclusive_locks_required and shared_locks_required
+  // to initial lockset. Also turn off checking for lock and unlock functi=
ons.
+  // FIXME: is there a more intelligent way to check lock/unlock functions?
+  if (!SortedGraph->empty() && D->hasAttrs()) {
+    const CFGBlock *FirstBlock =3D *SortedGraph->begin();
+    Lockset &InitialLockset =3D BlockInfo[FirstBlock->getBlockID()].EntryS=
et;
     const AttrVec &ArgAttrs =3D D->getAttrs();
-    for(unsigned i =3D 0; i < ArgAttrs.size(); ++i) {
+    for (unsigned i =3D 0; i < ArgAttrs.size(); ++i) {
       Attr *Attr =3D ArgAttrs[i];
       SourceLocation AttrLoc =3D Attr->getLocation();
       if (SharedLocksRequiredAttr *SLRAttr
             =3D dyn_cast<SharedLocksRequiredAttr>(Attr)) {
         for (SharedLocksRequiredAttr::args_iterator
-            SLRIter =3D SLRAttr->args_begin(),
-            SLREnd =3D SLRAttr->args_end(); SLRIter !=3D SLREnd; ++SLRIter)
-          InitialLockset =3D addLock(Handler, LocksetFactory, InitialLocks=
et,
-                                   *SLRIter, LK_Shared,
+             SLRIter =3D SLRAttr->args_begin(),
+             SLREnd =3D SLRAttr->args_end(); SLRIter !=3D SLREnd; ++SLRIte=
r)
+          InitialLockset =3D addLock(InitialLockset,
+                                   *SLRIter, D, LK_Shared,
                                    AttrLoc);
       } else if (ExclusiveLocksRequiredAttr *ELRAttr
                    =3D dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
         for (ExclusiveLocksRequiredAttr::args_iterator
-            ELRIter =3D ELRAttr->args_begin(),
-            ELREnd =3D ELRAttr->args_end(); ELRIter !=3D ELREnd; ++ELRIter)
-          InitialLockset =3D addLock(Handler, LocksetFactory, InitialLocks=
et,
-                                   *ELRIter, LK_Exclusive,
+             ELRIter =3D ELRAttr->args_begin(),
+             ELREnd =3D ELRAttr->args_end(); ELRIter !=3D ELREnd; ++ELRIte=
r)
+          InitialLockset =3D addLock(InitialLockset,
+                                   *ELRIter, D, LK_Exclusive,
                                    AttrLoc);
+      } else if (isa<UnlockFunctionAttr>(Attr)) {
+        // Don't try to check unlock functions for now
+        return;
+      } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
+        // Don't try to check lock functions for now
+        return;
+      } else if (isa<SharedLockFunctionAttr>(Attr)) {
+        // Don't try to check lock functions for now
+        return;
       }
     }
   }
=20
-  for (TopologicallySortedCFG::iterator I =3D SortedGraph.begin(),
-       E =3D SortedGraph.end(); I!=3D E; ++I) {
+  for (PostOrderCFGView::iterator I =3D SortedGraph->begin(),
+       E =3D SortedGraph->end(); I!=3D E; ++I) {
     const CFGBlock *CurrBlock =3D *I;
     int CurrBlockID =3D CurrBlock->getBlockID();
-
-    VisitedBlocks.insert(CurrBlock);
+    CFGBlockInfo *CurrBlockInfo =3D &BlockInfo[CurrBlockID];
=20
     // Use the default initial lockset in case there are no predecessors.
-    Lockset &Entryset =3D EntryLocksets[CurrBlockID];
-    Lockset &Exitset =3D ExitLocksets[CurrBlockID];
+    VisitedBlocks.insert(CurrBlock);
=20
     // Iterate through the predecessor blocks and warn if the lockset for =
all
     // predecessors is not the same. We take the entry lockset of the curr=
ent
@@ -732,6 +1562,7 @@
     // union because the real error is probably that we forgot to unlock M=
 on
     // all code paths.
     bool LocksetInitialized =3D false;
+    llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
     for (CFGBlock::const_pred_iterator PI =3D CurrBlock->pred_begin(),
          PE  =3D CurrBlock->pred_end(); PI !=3D PE; ++PI) {
=20
@@ -739,24 +1570,102 @@
       if (*PI =3D=3D 0 || !VisitedBlocks.alreadySet(*PI))
         continue;
=20
+      // Ignore edges from blocks that can't return.
+      if ((*PI)->hasNoReturnElement())
+        continue;
+
+      // If the previous block ended in a 'continue' or 'break' statement,=
 then
+      // a difference in locksets is probably due to a bug in that block, =
rather
+      // than in some other predecessor. In that case, keep the other
+      // predecessor's lockset.
+      if (const Stmt *Terminator =3D (*PI)->getTerminator()) {
+        if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
+          SpecialBlocks.push_back(*PI);
+          continue;
+        }
+      }
+
       int PrevBlockID =3D (*PI)->getBlockID();
+      CFGBlockInfo *PrevBlockInfo =3D &BlockInfo[PrevBlockID];
+
       if (!LocksetInitialized) {
-        Entryset =3D ExitLocksets[PrevBlockID];
+        CurrBlockInfo->EntrySet =3D PrevBlockInfo->ExitSet;
         LocksetInitialized =3D true;
       } else {
-        Entryset =3D intersectAndWarn(Handler, Entryset,
-                                    ExitLocksets[PrevBlockID], LocksetFact=
ory,
-                                    LEK_LockedSomePredecessors);
+        CurrBlockInfo->EntrySet =3D
+          intersectAndWarn(*CurrBlockInfo, CBS_Entry,
+                           *PrevBlockInfo, CBS_Exit,
+                           LEK_LockedSomePredecessors);
       }
     }
=20
-    BuildLockset LocksetBuilder(Handler, Entryset, LocksetFactory);
+    // Process continue and break blocks. Assume that the lockset for the
+    // resulting block is unaffected by any discrepancies in them.
+    for (unsigned SpecialI =3D 0, SpecialN =3D SpecialBlocks.size();
+         SpecialI < SpecialN; ++SpecialI) {
+      CFGBlock *PrevBlock =3D SpecialBlocks[SpecialI];
+      int PrevBlockID =3D PrevBlock->getBlockID();
+      CFGBlockInfo *PrevBlockInfo =3D &BlockInfo[PrevBlockID];
+
+      if (!LocksetInitialized) {
+        CurrBlockInfo->EntrySet =3D PrevBlockInfo->ExitSet;
+        LocksetInitialized =3D true;
+      } else {
+        // Determine whether this edge is a loop terminator for diagnostic
+        // purposes. FIXME: A 'break' statement might be a loop terminator=
, but
+        // it might also be part of a switch. Also, a subsequent destructor
+        // might add to the lockset, in which case the real issue might be=
 a
+        // double lock on the other path.
+        const Stmt *Terminator =3D PrevBlock->getTerminator();
+        bool IsLoop =3D Terminator && isa<ContinueStmt>(Terminator);
+
+        // Do not update EntrySet.
+        intersectAndWarn(*CurrBlockInfo, CBS_Entry, *PrevBlockInfo, CBS_Ex=
it,
+                         IsLoop ? LEK_LockedSomeLoopIterations
+                                : LEK_LockedSomePredecessors);
+      }
+    }
+
+    BuildLockset LocksetBuilder(this, *CurrBlockInfo);
+    CFGBlock::const_pred_iterator PI =3D CurrBlock->pred_begin(),
+                                  PE =3D CurrBlock->pred_end();
+    if (PI !=3D PE) {
+      // If the predecessor ended in a branch, then process any trylocks.
+      // FIXME -- check to make sure there's only one predecessor.
+      if (Stmt *TCE =3D (*PI)->getTerminatorCondition()) {
+        LocksetBuilder.handleTrylock(TCE, *PI, CurrBlock);
+      }
+    }
+
+    // Visit all the statements in the basic block.
     for (CFGBlock::const_iterator BI =3D CurrBlock->begin(),
          BE =3D CurrBlock->end(); BI !=3D BE; ++BI) {
-      if (const CFGStmt *CfgStmt =3D dyn_cast<CFGStmt>(&*BI))
-        LocksetBuilder.Visit(const_cast<Stmt*>(CfgStmt->getStmt()));
+      switch (BI->getKind()) {
+        case CFGElement::Statement: {
+          const CFGStmt *CS =3D cast<CFGStmt>(&*BI);
+          LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
+          break;
+        }
+        // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
+        case CFGElement::AutomaticObjectDtor: {
+          const CFGAutomaticObjDtor *AD =3D cast<CFGAutomaticObjDtor>(&*BI=
);
+          CXXDestructorDecl *DD =3D const_cast<CXXDestructorDecl*>(
+            AD->getDestructorDecl(AC.getASTContext()));
+          if (!DD->hasAttrs())
+            break;
+
+          // Create a dummy expression,
+          VarDecl *VD =3D const_cast<VarDecl*>(AD->getVarDecl());
+          DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
+                          AD->getTriggerStmt()->getLocEnd());
+          LocksetBuilder.handleCall(&DRE, DD);
+          break;
+        }
+        default:
+          break;
+      }
     }
-    Exitset =3D LocksetBuilder.getLockset();
+    CurrBlockInfo->ExitSet =3D LocksetBuilder.LSet;
=20
     // For every back edge from CurrBlock (the end of the loop) to another=
 block
     // (FirstLoopBlock) we need to check that the Lockset of Block is equa=
l to
@@ -770,21 +1679,38 @@
         continue;
=20
       CFGBlock *FirstLoopBlock =3D *SI;
-      Lockset PreLoop =3D EntryLocksets[FirstLoopBlock->getBlockID()];
-      Lockset LoopEnd =3D ExitLocksets[CurrBlockID];
-      intersectAndWarn(Handler, LoopEnd, PreLoop, LocksetFactory,
+      CFGBlockInfo &PreLoop =3D BlockInfo[FirstLoopBlock->getBlockID()];
+      CFGBlockInfo &LoopEnd =3D BlockInfo[CurrBlockID];
+      intersectAndWarn(LoopEnd, CBS_Exit, PreLoop, CBS_Entry,
                        LEK_LockedSomeLoopIterations);
     }
   }
=20
-  Lockset InitialLockset =3D EntryLocksets[CFGraph->getEntry().getBlockID(=
)];
-  Lockset FinalLockset =3D ExitLocksets[CFGraph->getExit().getBlockID()];
+  CFGBlockInfo &Initial =3D BlockInfo[CFGraph->getEntry().getBlockID()];
+  CFGBlockInfo &Final =3D BlockInfo[CFGraph->getExit().getBlockID()];
=20
   // FIXME: Should we call this function for all blocks which exit the fun=
ction?
-  intersectAndWarn(Handler, InitialLockset, FinalLockset, LocksetFactory,
+  intersectAndWarn(Initial, CBS_Entry, Final, CBS_Exit,
                    LEK_LockedAtEndOfFunction);
 }
=20
+} // end anonymous namespace
+
+
+namespace clang {
+namespace thread_safety {
+
+/// \brief Check a function's CFG for thread-safety violations.
+///
+/// We traverse the blocks in the CFG, compute the set of mutexes that are=
 held
+/// at the end of each block, and issue warnings for thread safety violati=
ons.
+/// Each block in the CFG is traversed exactly once.
+void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
+                             ThreadSafetyHandler &Handler) {
+  ThreadSafetyAnalyzer Analyzer(Handler);
+  Analyzer.runAnalysis(AC);
+}
+
 /// \brief Helper function that returns a LockKind required for the given =
level
 /// of access.
 LockKind getLockKindFromAccessKind(AccessKind AK) {
@@ -796,4 +1722,5 @@
   }
   llvm_unreachable("Unknown AccessKind");
 }
+
 }} // end namespace clang::thread_safety
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Anal=
ysis/UninitializedValues.cpp
--- a/head/contrib/llvm/tools/clang/lib/Analysis/UninitializedValues.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Analysis/UninitializedValues.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
 #include "clang/Analysis/Analyses/UninitializedValues.h"
-#include "clang/Analysis/Support/SaveAndRestore.h"
+#include "llvm/Support/SaveAndRestore.h"
=20
 using namespace clang;
=20
@@ -337,7 +337,7 @@
 class TransferFunctions : public StmtVisitor<TransferFunctions> {
   CFGBlockValues &vals;
   const CFG &cfg;
-  AnalysisContext ∾
+  AnalysisDeclContext ∾
   UninitVariablesHandler *handler;
  =20
   /// The last DeclRefExpr seen when analyzing a block.  Used to
@@ -356,7 +356,7 @@
  =20
 public:
   TransferFunctions(CFGBlockValues &vals, const CFG &cfg,
-                    AnalysisContext &ac,
+                    AnalysisDeclContext &ac,
                     UninitVariablesHandler *handler)
     : vals(vals), cfg(cfg), ac(ac), handler(handler),
       lastDR(0), lastLoad(0),
@@ -615,7 +615,7 @@
 //=3D=3D=3D=3D------------------------------------------------------------=
------------//
=20
 static bool runOnBlock(const CFGBlock *block, const CFG &cfg,
-                       AnalysisContext &ac, CFGBlockValues &vals,
+                       AnalysisDeclContext &ac, CFGBlockValues &vals,
                        llvm::BitVector &wasAnalyzed,
                        UninitVariablesHandler *handler =3D 0) {
  =20
@@ -672,7 +672,7 @@
 void clang::runUninitializedVariablesAnalysis(
     const DeclContext &dc,
     const CFG &cfg,
-    AnalysisContext &ac,
+    AnalysisDeclContext &ac,
     UninitVariablesHandler &handler,
     UninitVariablesAnalysisStats &stats) {
   CFGBlockValues vals(cfg);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/Builtins.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/Builtins.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/Builtins.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -15,6 +15,7 @@
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/SmallVector.h"
 using namespace clang;
=20
 static const Builtin::Info BuiltinInfo[] =3D {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/ConvertUTF.c
--- a/head/contrib/llvm/tools/clang/lib/Basic/ConvertUTF.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/ConvertUTF.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -339,67 +339,6 @@
     return result;
 }
=20
-/* --------------------------------------------------------------------- */
-
-ConversionResult ConvertUTF8toUTF32 (
-        const UTF8** sourceStart, const UTF8* sourceEnd,=20
-        UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
-    ConversionResult result =3D conversionOK;
-    const UTF8* source =3D *sourceStart;
-    UTF32* target =3D *targetStart;
-    while (source < sourceEnd) {
-        UTF32 ch =3D 0;
-        unsigned short extraBytesToRead =3D trailingBytesForUTF8[*source];
-        if (source + extraBytesToRead >=3D sourceEnd) {
-            result =3D sourceExhausted; break;
-        }
-        /* Do this check whether lenient or strict */
-        if (!isLegalUTF8(source, extraBytesToRead+1)) {
-            result =3D sourceIllegal;
-            break;
-        }
-        /*
-         * The cases all fall through. See "Note A" below.
-         */
-        switch (extraBytesToRead) {
-            case 5: ch +=3D *source++; ch <<=3D 6;
-            case 4: ch +=3D *source++; ch <<=3D 6;
-            case 3: ch +=3D *source++; ch <<=3D 6;
-            case 2: ch +=3D *source++; ch <<=3D 6;
-            case 1: ch +=3D *source++; ch <<=3D 6;
-            case 0: ch +=3D *source++;
-        }
-        ch -=3D offsetsFromUTF8[extraBytesToRead];
-
-        if (target >=3D targetEnd) {
-            source -=3D (extraBytesToRead+1); /* Back up the source pointe=
r! */
-            result =3D targetExhausted; break;
-        }
-        if (ch <=3D UNI_MAX_LEGAL_UTF32) {
-            /*
-             * UTF-16 surrogate values are illegal in UTF-32, and anything
-             * over Plane 17 (> 0x10FFFF) is illegal.
-             */
-            if (ch >=3D UNI_SUR_HIGH_START && ch <=3D UNI_SUR_LOW_END) {
-                if (flags =3D=3D strictConversion) {
-                    source -=3D (extraBytesToRead+1); /* return to the ill=
egal value itself */
-                    result =3D sourceIllegal;
-                    break;
-                } else {
-                    *target++ =3D UNI_REPLACEMENT_CHAR;
-                }
-            } else {
-                *target++ =3D ch;
-            }
-        } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */
-            result =3D sourceIllegal;
-            *target++ =3D UNI_REPLACEMENT_CHAR;
-        }
-    }
-    *sourceStart =3D source;
-    *targetStart =3D target;
-    return result;
-}
 #endif
=20
 /* --------------------------------------------------------------------- */
@@ -448,7 +387,7 @@
  */
 Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd) {
     int length =3D trailingBytesForUTF8[*source]+1;
-    if (source+length > sourceEnd) {
+    if (length > sourceEnd - source) {
         return false;
     }
     return isLegalUTF8(source, length);
@@ -456,6 +395,22 @@
=20
 /* --------------------------------------------------------------------- */
=20
+/*
+ * Exported function to return whether a UTF-8 string is legal or not.
+ * This is not used here; it's just exported.
+ */
+Boolean isLegalUTF8String(const UTF8 *source, const UTF8 *sourceEnd) {
+    while (source !=3D sourceEnd) {
+        int length =3D trailingBytesForUTF8[*source] + 1;
+        if (length > sourceEnd - source || !isLegalUTF8(source, length))
+            return false;
+        source +=3D length;
+    }
+    return true;
+}
+
+/* --------------------------------------------------------------------- */
+
 ConversionResult ConvertUTF8toUTF16 (
         const UTF8** sourceStart, const UTF8* sourceEnd,=20
         UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags) {
@@ -465,7 +420,7 @@
     while (source < sourceEnd) {
         UTF32 ch =3D 0;
         unsigned short extraBytesToRead =3D trailingBytesForUTF8[*source];
-        if (source + extraBytesToRead >=3D sourceEnd) {
+        if (extraBytesToRead >=3D sourceEnd - source) {
             result =3D sourceExhausted; break;
         }
         /* Do this check whether lenient or strict */
@@ -527,6 +482,68 @@
     return result;
 }
=20
+/* --------------------------------------------------------------------- */
+
+ConversionResult ConvertUTF8toUTF32 (
+        const UTF8** sourceStart, const UTF8* sourceEnd,=20
+        UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags) {
+    ConversionResult result =3D conversionOK;
+    const UTF8* source =3D *sourceStart;
+    UTF32* target =3D *targetStart;
+    while (source < sourceEnd) {
+        UTF32 ch =3D 0;
+        unsigned short extraBytesToRead =3D trailingBytesForUTF8[*source];
+        if (extraBytesToRead >=3D sourceEnd - source) {
+            result =3D sourceExhausted; break;
+        }
+        /* Do this check whether lenient or strict */
+        if (!isLegalUTF8(source, extraBytesToRead+1)) {
+            result =3D sourceIllegal;
+            break;
+        }
+        /*
+         * The cases all fall through. See "Note A" below.
+         */
+        switch (extraBytesToRead) {
+            case 5: ch +=3D *source++; ch <<=3D 6;
+            case 4: ch +=3D *source++; ch <<=3D 6;
+            case 3: ch +=3D *source++; ch <<=3D 6;
+            case 2: ch +=3D *source++; ch <<=3D 6;
+            case 1: ch +=3D *source++; ch <<=3D 6;
+            case 0: ch +=3D *source++;
+        }
+        ch -=3D offsetsFromUTF8[extraBytesToRead];
+
+        if (target >=3D targetEnd) {
+            source -=3D (extraBytesToRead+1); /* Back up the source pointe=
r! */
+            result =3D targetExhausted; break;
+        }
+        if (ch <=3D UNI_MAX_LEGAL_UTF32) {
+            /*
+             * UTF-16 surrogate values are illegal in UTF-32, and anything
+             * over Plane 17 (> 0x10FFFF) is illegal.
+             */
+            if (ch >=3D UNI_SUR_HIGH_START && ch <=3D UNI_SUR_LOW_END) {
+                if (flags =3D=3D strictConversion) {
+                    source -=3D (extraBytesToRead+1); /* return to the ill=
egal value itself */
+                    result =3D sourceIllegal;
+                    break;
+                } else {
+                    *target++ =3D UNI_REPLACEMENT_CHAR;
+                }
+            } else {
+                *target++ =3D ch;
+            }
+        } else { /* i.e., ch > UNI_MAX_LEGAL_UTF32 */
+            result =3D sourceIllegal;
+            *target++ =3D UNI_REPLACEMENT_CHAR;
+        }
+    }
+    *sourceStart =3D source;
+    *targetStart =3D target;
+    return result;
+}
+
 /* ---------------------------------------------------------------------
=20
     Note A.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/Diagnostic.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/Diagnostic.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/Diagnostic.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,7 +14,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/PartialDiagnostic.h"
-#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/CrashRecoveryContext.h"
=20
@@ -27,14 +27,14 @@
                                unsigned NumPrevArgs,
                                SmallVectorImpl<char> &Output,
                                void *Cookie,
-                               SmallVectorImpl<intptr_t> &QualTypeVals) {
+                               ArrayRef<intptr_t> QualTypeVals) {
   const char *Str =3D "<can't format argument>";
   Output.append(Str, Str+strlen(Str));
 }
=20
=20
 DiagnosticsEngine::DiagnosticsEngine(
-                       const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diag=
s,
+                       const IntrusiveRefCntPtr<DiagnosticIDs> &diags,
                        DiagnosticConsumer *client, bool ShouldOwnClient)
   : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
     SourceMgr(0) {
@@ -53,6 +53,7 @@
=20
   ErrorLimit =3D 0;
   TemplateBacktraceLimit =3D 0;
+  ConstexprBacktraceLimit =3D 0;
=20
   Reset();
 }
@@ -118,7 +119,7 @@
 }
=20
 void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Ar=
g1,
-                                      StringRef Arg2) {
+                                             StringRef Arg2) {
   if (DelayedDiagID)
     return;
=20
@@ -161,7 +162,7 @@
 /// \param The source location that this change of diagnostic state should
 /// take affect. It can be null if we are setting the latest state.
 void DiagnosticsEngine::setDiagnosticMapping(diag::kind Diag, diag::Mappin=
g Map,
-                                      SourceLocation L) {
+                                             SourceLocation L) {
   assert(Diag < diag::DIAG_UPPER_LIMIT &&
          "Can only map builtin diagnostics");
   assert((Diags->isBuiltinWarningOrExtension(Diag) ||
@@ -169,18 +170,16 @@
          "Cannot map errors into warnings!");
   assert(!DiagStatePoints.empty());
=20
-  bool isPragma =3D L.isValid();
   FullSourceLoc Loc(L, *SourceMgr);
   FullSourceLoc LastStateChangePos =3D DiagStatePoints.back().Loc;
-  DiagnosticMappingInfo MappingInfo =3D DiagnosticMappingInfo::Make(
-    Map, /*IsUser=3D*/true, isPragma);
-
-  // If this is a pragma mapping, then set the diagnostic mapping flags so=
 that
-  // we override command line options.
-  if (isPragma) {
-    MappingInfo.setNoWarningAsError(true);
-    MappingInfo.setNoErrorAsFatal(true);
+  // Don't allow a mapping to a warning override an error/fatal mapping.
+  if (Map =3D=3D diag::MAP_WARNING) {
+    DiagnosticMappingInfo &Info =3D GetCurDiagState()->getOrAddMappingInfo=
(Diag);
+    if (Info.getMapping() =3D=3D diag::MAP_ERROR ||
+        Info.getMapping() =3D=3D diag::MAP_FATAL)
+      Map =3D Info.getMapping();
   }
+  DiagnosticMappingInfo MappingInfo =3D makeMappingInfo(Map, L);
=20
   // Common case; setting all the diagnostics of a group in one place.
   if (Loc.isInvalid() || Loc =3D=3D LastStateChangePos) {
@@ -244,6 +243,24 @@
   return false;
 }
=20
+void DiagnosticsEngine::setDiagnosticWarningAsError(diag::kind Diag,
+                                                    bool Enabled) {
+  // If we are enabling this feature, just set the diagnostic mappings to =
map to
+  // errors.
+  if (Enabled)=20
+    setDiagnosticMapping(Diag, diag::MAP_ERROR, SourceLocation());
+
+  // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, a=
nd
+  // potentially downgrade anything already mapped to be a warning.
+  DiagnosticMappingInfo &Info =3D GetCurDiagState()->getOrAddMappingInfo(D=
iag);
+
+  if (Info.getMapping() =3D=3D diag::MAP_ERROR ||
+      Info.getMapping() =3D=3D diag::MAP_FATAL)
+    Info.setMapping(diag::MAP_WARNING);
+
+  Info.setNoWarningAsError(true);
+}
+
 bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
                                                          bool Enabled) {
   // If we are enabling this feature, just set the diagnostic mappings to =
map to
@@ -274,6 +291,23 @@
   return false;
 }
=20
+void DiagnosticsEngine::setDiagnosticErrorAsFatal(diag::kind Diag,
+                                                  bool Enabled) {
+  // If we are enabling this feature, just set the diagnostic mappings to =
map to
+  // errors.
+  if (Enabled)
+    setDiagnosticMapping(Diag, diag::MAP_FATAL, SourceLocation());
+ =20
+  // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, a=
nd
+  // potentially downgrade anything already mapped to be a warning.
+  DiagnosticMappingInfo &Info =3D GetCurDiagState()->getOrAddMappingInfo(D=
iag);
+ =20
+  if (Info.getMapping() =3D=3D diag::MAP_FATAL)
+    Info.setMapping(diag::MAP_ERROR);
+ =20
+  Info.setNoErrorAsFatal(true);
+}
+
 bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
                                                        bool Enabled) {
   // If we are enabling this feature, just set the diagnostic mappings to =
map to
@@ -303,6 +337,18 @@
   return false;
 }
=20
+void DiagnosticsEngine::setMappingToAllDiagnostics(diag::Mapping Map,
+                                                   SourceLocation Loc) {
+  // Get all the diagnostics.
+  llvm::SmallVector<diag::kind, 64> AllDiags;
+  Diags->getAllDiagnostics(AllDiags);
+
+  // Set the mapping.
+  for (unsigned i =3D 0, e =3D AllDiags.size(); i !=3D e; ++i)
+    if (Diags->isBuiltinWarningOrExtension(AllDiags[i]))
+      setDiagnosticMapping(AllDiags[i], Map, Loc);
+}
+
 void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
   assert(CurDiagID =3D=3D ~0U && "Multiple diagnostics in flight at once!"=
);
=20
@@ -311,7 +357,7 @@
   NumDiagArgs =3D 0;
=20
   NumDiagRanges =3D storedDiag.range_size();
-  assert(NumDiagRanges < sizeof(DiagRanges)/sizeof(DiagRanges[0]) &&
+  assert(NumDiagRanges < DiagnosticsEngine::MaxRanges &&
          "Too many arguments to diagnostic!");
   unsigned i =3D 0;
   for (StoredDiagnostic::range_iterator
@@ -319,14 +365,13 @@
          RE =3D storedDiag.range_end(); RI !=3D RE; ++RI)
     DiagRanges[i++] =3D *RI;
=20
-  NumFixItHints =3D storedDiag.fixit_size();
-  assert(NumFixItHints < DiagnosticsEngine::MaxFixItHints &&
-      "Too many fix-it hints!");
-  i =3D 0;
+  assert(NumDiagRanges < DiagnosticsEngine::MaxFixItHints &&
+         "Too many arguments to diagnostic!");
+  NumDiagFixItHints =3D 0;
   for (StoredDiagnostic::fixit_iterator
          FI =3D storedDiag.fixit_begin(),
          FE =3D storedDiag.fixit_end(); FI !=3D FE; ++FI)
-    FixItHints[i++] =3D *FI;
+    DiagFixItHints[NumDiagFixItHints++] =3D *FI;
=20
   assert(Client && "DiagnosticConsumer not set!");
   Level DiagLevel =3D storedDiag.getLevel();
@@ -340,35 +385,18 @@
   CurDiagID =3D ~0U;
 }
=20
-void DiagnosticBuilder::FlushCounts() {
-  DiagObj->NumDiagArgs =3D NumArgs;
-  DiagObj->NumDiagRanges =3D NumRanges;
-  DiagObj->NumFixItHints =3D NumFixItHints;
-}
-
-bool DiagnosticBuilder::Emit() {
-  // If DiagObj is null, then its soul was stolen by the copy ctor
-  // or the user called Emit().
-  if (DiagObj =3D=3D 0) return false;
-
-  // When emitting diagnostics, we set the final argument count into
-  // the DiagnosticsEngine object.
-  FlushCounts();
-
+bool DiagnosticsEngine::EmitCurrentDiagnostic() {
   // Process the diagnostic, sending the accumulated information to the
   // DiagnosticConsumer.
-  bool Emitted =3D DiagObj->ProcessDiag();
+  bool Emitted =3D ProcessDiag();
=20
   // Clear out the current diagnostic object.
-  unsigned DiagID =3D DiagObj->CurDiagID;
-  DiagObj->Clear();
+  unsigned DiagID =3D CurDiagID;
+  Clear();
=20
   // If there was a delayed diagnostic, emit it now.
-  if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID !=3D DiagID)
-    DiagObj->ReportDelayed();
-
-  // This diagnostic is dead.
-  DiagObj =3D 0;
+  if (DelayedDiagID && DelayedDiagID !=3D DiagID)
+    ReportDelayed();
=20
   return Emitted;
 }
@@ -802,7 +830,7 @@
        "Valid source location without setting a source manager for diagnos=
tic");
   if (Info.getLocation().isValid())
     Loc =3D FullSourceLoc(Info.getLocation(), Info.getSourceManager());
-  llvm::SmallString<64> Message;
+  SmallString<64> Message;
   Info.FormatDiagnostic(Message);
   this->Message.assign(Message.begin(), Message.end());
=20
@@ -833,6 +861,8 @@
 ///  reported by DiagnosticsEngine.
 bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
=20
+void IgnoringDiagConsumer::anchor() { }
+
 PartialDiagnostic::StorageAllocator::StorageAllocator() {
   for (unsigned I =3D 0; I !=3D NumCached; ++I)
     FreeList[I] =3D Cached + I;
@@ -840,7 +870,9 @@
 }
=20
 PartialDiagnostic::StorageAllocator::~StorageAllocator() {
-  // Don't assert if we are in a CrashRecovery context, as this
-  // invariant may be invalidated during a crash.
-  assert((NumFreeListEntries =3D=3D NumCached || llvm::CrashRecoveryContex=
t::isRecoveringFromCrash()) && "A partial is on the lamb");
+  // Don't assert if we are in a CrashRecovery context, as this invariant =
may
+  // be invalidated during a crash.
+  assert((NumFreeListEntries =3D=3D NumCached ||=20
+          llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&=20
+         "A partial is on the lamb");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/DiagnosticIDs.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/DiagnosticIDs.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/DiagnosticIDs.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -11,16 +11,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "clang/AST/ASTDiagnostic.h"
-#include "clang/Analysis/AnalysisDiagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/AllDiagnostics.h"
 #include "clang/Basic/DiagnosticCategories.h"
 #include "clang/Basic/SourceManager.h"
-#include "clang/Driver/DriverDiagnostic.h"
-#include "clang/Frontend/FrontendDiagnostic.h"
-#include "clang/Lex/LexDiagnostic.h"
-#include "clang/Parse/ParseDiagnostic.h"
-#include "clang/Sema/SemaDiagnostic.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/ErrorHandling.h"
=20
@@ -51,107 +45,49 @@
   unsigned WarnShowInSystemHeader : 1;
   unsigned Category : 5;
=20
-  uint8_t  NameLen;
-  uint8_t  OptionGroupLen;
+  uint16_t OptionGroupIndex;
=20
   uint16_t DescriptionLen;
-  uint16_t BriefExplanationLen;
-  uint16_t FullExplanationLen;
+  const char *DescriptionStr;
=20
-  const char *NameStr;
-  const char *OptionGroupStr;
-
-  const char *DescriptionStr;
-  const char *BriefExplanationStr;
-  const char *FullExplanationStr;
-
-  StringRef getName() const {
-    return StringRef(NameStr, NameLen);
-  }
-  StringRef getOptionGroup() const {
-    return StringRef(OptionGroupStr, OptionGroupLen);
+  unsigned getOptionGroupIndex() const {
+    return OptionGroupIndex;
   }
=20
   StringRef getDescription() const {
     return StringRef(DescriptionStr, DescriptionLen);
   }
-  StringRef getBriefExplanation() const {
-    return StringRef(BriefExplanationStr, BriefExplanationLen);
-  }
-  StringRef getFullExplanation() const {
-    return StringRef(FullExplanationStr, FullExplanationLen);
-  }
=20
   bool operator<(const StaticDiagInfoRec &RHS) const {
     return DiagID < RHS.DiagID;
   }
 };
=20
-struct StaticDiagNameIndexRec {
-  const char *NameStr;
-  unsigned short DiagID;
-  uint8_t NameLen;
-
-  StringRef getName() const {
-    return StringRef(NameStr, NameLen);
-  }
-
-  bool operator<(const StaticDiagNameIndexRec &RHS) const {
-    return getName() < RHS.getName();
-  }
- =20
-  bool operator=3D=3D(const StaticDiagNameIndexRec &RHS) const {
-    return getName() =3D=3D RHS.getName();
-  }
-};
-
-template <size_t SizeOfStr, typename FieldType>
-class StringSizerHelper {
-  char FIELD_TOO_SMALL[SizeOfStr <=3D FieldType(~0U) ? 1 : -1];
-public:
-  enum { Size =3D SizeOfStr };
-};
-
 } // namespace anonymous
=20
-#define STR_SIZE(str, fieldTy) StringSizerHelper<sizeof(str)-1, fieldTy>::=
Size=20
-
 static const StaticDiagInfoRec StaticDiagInfo[] =3D {
 #define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,               \
              SFINAE,ACCESS,NOWERROR,SHOWINSYSHEADER,              \
-             CATEGORY,BRIEF,FULL)                                 \
+             CATEGORY)                                            \
   { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, ACCESS,           \
-    NOWERROR, SHOWINSYSHEADER, CATEGORY,                          \
-    STR_SIZE(#ENUM, uint8_t), STR_SIZE(GROUP, uint8_t),           \
-    STR_SIZE(DESC, uint16_t), STR_SIZE(BRIEF, uint16_t),          \
-    STR_SIZE(FULL, uint16_t),                                     \
-    #ENUM, GROUP, DESC, BRIEF, FULL },
+    NOWERROR, SHOWINSYSHEADER, CATEGORY, GROUP,                   \
+    STR_SIZE(DESC, uint16_t), DESC },
 #include "clang/Basic/DiagnosticCommonKinds.inc"
 #include "clang/Basic/DiagnosticDriverKinds.inc"
 #include "clang/Basic/DiagnosticFrontendKinds.inc"
+#include "clang/Basic/DiagnosticSerializationKinds.inc"
 #include "clang/Basic/DiagnosticLexKinds.inc"
 #include "clang/Basic/DiagnosticParseKinds.inc"
 #include "clang/Basic/DiagnosticASTKinds.inc"
 #include "clang/Basic/DiagnosticSemaKinds.inc"
 #include "clang/Basic/DiagnosticAnalysisKinds.inc"
 #undef DIAG
-  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
 };
=20
 static const unsigned StaticDiagInfoSize =3D
   sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
=20
-/// To be sorted before first use (since it's splitted among multiple file=
s)
-static const StaticDiagNameIndexRec StaticDiagNameIndex[] =3D {
-#define DIAG_NAME_INDEX(ENUM) { #ENUM, diag::ENUM, STR_SIZE(#ENUM, uint8_t=
) },
-#include "clang/Basic/DiagnosticIndexName.inc"
-#undef DIAG_NAME_INDEX
-  { 0, 0, 0 }
-};
-
-static const unsigned StaticDiagNameIndexSize =3D
-  sizeof(StaticDiagNameIndex)/sizeof(StaticDiagNameIndex[0])-1;
-
 /// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified Dia=
gID,
 /// or null if the ID is invalid.
 static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
@@ -173,7 +109,7 @@
=20
   // Search the diagnostic table with a binary search.
   StaticDiagInfoRec Find =3D { static_cast<unsigned short>(DiagID),
-                             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, =
0, 0};
+                             0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
=20
   const StaticDiagInfoRec *Found =3D
     std::lower_bound(StaticDiagInfo, StaticDiagInfo + StaticDiagInfoSize, =
Find);
@@ -207,15 +143,6 @@
   return Info;
 }
=20
-/// getWarningOptionForDiag - Return the lowest-level warning option that
-/// enables the specified diagnostic.  If there is no -Wfoo flag that cont=
rols
-/// the diagnostic, this returns null.
-StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
-  if (const StaticDiagInfoRec *Info =3D GetDiagInfo(DiagID))
-    return Info->getOptionGroup();
-  return StringRef();
-}
-
 /// getCategoryNumberForDiag - Return the category number that a specified
 /// DiagID belongs to, or 0 if no category.
 unsigned DiagnosticIDs::getCategoryNumberForDiag(unsigned DiagID) {
@@ -295,50 +222,6 @@
   return SFINAE_Report;
 }
=20
-/// getName - Given a diagnostic ID, return its name
-StringRef DiagnosticIDs::getName(unsigned DiagID) {
-  if (const StaticDiagInfoRec *Info =3D GetDiagInfo(DiagID))
-    return Info->getName();
-  return StringRef();
-}
-
-/// getIdFromName - Given a diagnostic name, return its ID, or 0
-unsigned DiagnosticIDs::getIdFromName(StringRef Name) {
-  const StaticDiagNameIndexRec *StaticDiagNameIndexEnd =3D
-    StaticDiagNameIndex + StaticDiagNameIndexSize;
- =20
-  if (Name.empty()) { return diag::DIAG_UPPER_LIMIT; }
- =20
-  assert(Name.size() =3D=3D static_cast<uint8_t>(Name.size()) &&
-         "Name is too long");
-  StaticDiagNameIndexRec Find =3D { Name.data(), 0,
-                                  static_cast<uint8_t>(Name.size()) };
- =20
-  const StaticDiagNameIndexRec *Found =3D
-    std::lower_bound( StaticDiagNameIndex, StaticDiagNameIndexEnd, Find);
-  if (Found =3D=3D StaticDiagNameIndexEnd ||
-      Found->getName() !=3D Name)
-    return diag::DIAG_UPPER_LIMIT;
- =20
-  return Found->DiagID;
-}
-
-/// getBriefExplanation - Given a diagnostic ID, return a brief explanation
-/// of the issue
-StringRef DiagnosticIDs::getBriefExplanation(unsigned DiagID) {
-  if (const StaticDiagInfoRec *Info =3D GetDiagInfo(DiagID))
-    return Info->getBriefExplanation();
-  return StringRef();
-}
-
-/// getFullExplanation - Given a diagnostic ID, return a full explanation
-/// of the issue
-StringRef DiagnosticIDs::getFullExplanation(unsigned DiagID) {
-  if (const StaticDiagInfoRec *Info =3D GetDiagInfo(DiagID))
-    return Info->getFullExplanation();
-  return StringRef();
-}
-
 /// getBuiltinDiagClass - Return the class field of the diagnostic.
 ///
 static unsigned getBuiltinDiagClass(unsigned DiagID) {
@@ -348,35 +231,6 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// diag_iterator
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-llvm::StringRef DiagnosticIDs::diag_iterator::getDiagName() const {
-  return static_cast<const StaticDiagNameIndexRec*>(impl)->getName();
-}
-
-unsigned DiagnosticIDs::diag_iterator::getDiagID() const {
-  return static_cast<const StaticDiagNameIndexRec*>(impl)->DiagID;
-}
-
-DiagnosticIDs::diag_iterator &DiagnosticIDs::diag_iterator::operator++() {
-  const StaticDiagNameIndexRec* ptr =3D
-    static_cast<const StaticDiagNameIndexRec*>(impl);;
-  ++ptr;
-  impl =3D ptr;
-  return *this;
-}
-
-DiagnosticIDs::diag_iterator DiagnosticIDs::diags_begin() {
-  return DiagnosticIDs::diag_iterator(StaticDiagNameIndex);
-}
-
-DiagnosticIDs::diag_iterator DiagnosticIDs::diags_end() {
-  return DiagnosticIDs::diag_iterator(StaticDiagNameIndex +
-                                      StaticDiagNameIndexSize);
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Custom Diagnostic information
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -530,7 +384,6 @@
     (diag::kind)DiagID);
=20
   switch (MappingInfo.getMapping()) {
-  default: llvm_unreachable("Unknown mapping!");
   case diag::MAP_IGNORE:
     Result =3D DiagnosticIDs::Ignored;
     break;
@@ -553,7 +406,7 @@
   // Ignore -pedantic diagnostics inside __extension__ blocks.
   // (The diagnostics controlled by -pedantic are the extension diagnostics
   // that are not enabled by default.)
-  bool EnabledByDefault;
+  bool EnabledByDefault =3D false;
   bool IsExtensionDiag =3D isBuiltinExtensionDiag(DiagID, EnabledByDefault=
);
   if (Diag.AllExtensionsSilenced && IsExtensionDiag && !EnabledByDefault)
     return DiagnosticIDs::Ignored;
@@ -648,6 +501,15 @@
   return LHS.getName() < RHS.getName();
 }
=20
+/// getWarningOptionForDiag - Return the lowest-level warning option that
+/// enables the specified diagnostic.  If there is no -Wfoo flag that cont=
rols
+/// the diagnostic, this returns null.
+StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) {
+  if (const StaticDiagInfoRec *Info =3D GetDiagInfo(DiagID))
+    return OptionTable[Info->getOptionGroupIndex()].getName();
+  return StringRef();
+}
+
 void DiagnosticIDs::getDiagnosticsInGroup(
   const WarningOption *Group,
   llvm::SmallVectorImpl<diag::kind> &Diags) const
@@ -681,6 +543,35 @@
   return false;
 }
=20
+void DiagnosticIDs::getAllDiagnostics(
+                               llvm::SmallVectorImpl<diag::kind> &Diags) c=
onst {
+  for (unsigned i =3D 0; i !=3D StaticDiagInfoSize; ++i)
+    Diags.push_back(StaticDiagInfo[i].DiagID);
+}
+
+StringRef DiagnosticIDs::getNearestWarningOption(StringRef Group) {
+  StringRef Best;
+  unsigned BestDistance =3D Group.size() + 1; // Sanity threshold.
+  for (const WarningOption *i =3D OptionTable, *e =3D OptionTable + Option=
TableSize;
+       i !=3D e; ++i) {
+    // Don't suggest ignored warning flags.
+    if (!i->Members && !i->SubGroups)
+      continue;
+
+    unsigned Distance =3D i->getName().edit_distance(Group, true, BestDist=
ance);
+    if (Distance =3D=3D BestDistance) {
+      // Two matches with the same distance, don't prefer one over the oth=
er.
+      Best =3D "";
+    } else if (Distance < BestDistance) {
+      // This is a better match.
+      Best =3D i->getName();
+      BestDistance =3D Distance;
+    }
+  }
+
+  return Best;
+}
+
 /// ProcessDiag - This is the method used to report a diagnostic that is
 /// finally fully formed.
 bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const {
@@ -766,19 +657,6 @@
     }
   }
=20
-  // If we have any Fix-Its, make sure that all of the Fix-Its point into
-  // source locations that aren't macro expansions. If any point into macro
-  // expansions, remove all of the Fix-Its.
-  for (unsigned I =3D 0, N =3D Diag.NumFixItHints; I !=3D N; ++I) {
-    const FixItHint &FixIt =3D Diag.FixItHints[I];
-    if (FixIt.RemoveRange.isInvalid() ||
-        FixIt.RemoveRange.getBegin().isMacroID() ||
-        FixIt.RemoveRange.getEnd().isMacroID()) {
-      Diag.NumFixItHints =3D 0;
-      break;
-    }   =20
-  }
- =20
   // Finally, report it.
   Diag.Client->HandleDiagnostic((DiagnosticsEngine::Level)DiagLevel, Info);
   if (Diag.Client->IncludeInDiagnosticCounts()) {
@@ -806,9 +684,14 @@
     return false;
=20
   // Currently we consider all ARC errors as recoverable.
-  if (getCategoryNumberForDiag(DiagID) =3D=3D
-        diag::DiagCat_Automatic_Reference_Counting_Issue)
+  if (isARCDiagnostic(DiagID))
     return false;
=20
   return true;
 }
+
+bool DiagnosticIDs::isARCDiagnostic(unsigned DiagID) {
+  unsigned cat =3D getCategoryNumberForDiag(DiagID);
+  return DiagnosticIDs::getCategoryNameFromID(cat).startswith("ARC ");
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/FileManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/FileManager.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/FileManager.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -20,13 +20,12 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/FileSystemStatCache.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/system_error.h"
-#include "llvm/Config/config.h"
+#include "llvm/Config/llvm-config.h"
 #include <map>
 #include <set>
 #include <string>
@@ -106,8 +105,8 @@
   FileEntry &getFile(const char *Name, const struct stat & /*StatBuf*/) {
     std::string FullPath(GetFullPath(Name));
=20
-    // LowercaseString because Windows filesystem is case insensitive.
-    FullPath =3D llvm::LowercaseString(FullPath);
+    // Lowercase string because Windows filesystem is case insensitive.
+    FullPath =3D StringRef(FullPath).lower();
     return UniqueFiles.GetOrCreateValue(FullPath).getValue();
   }
=20
@@ -266,6 +265,12 @@
 ///
 const DirectoryEntry *FileManager::getDirectory(StringRef DirName,
                                                 bool CacheFailure) {
+  // stat doesn't like trailing separators.
+  // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'.
+  // (though it can strip '\\')
+  if (DirName.size() > 1 && llvm::sys::path::is_separator(DirName.back()))
+    DirName =3D DirName.substr(0, DirName.size()-1);
+
   ++NumDirLookups;
   llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =3D
     SeenDirEntries.GetOrCreateValue(DirName);
@@ -472,14 +477,14 @@
       || llvm::sys::path::is_absolute(pathRef))
     return;
=20
-  llvm::SmallString<128> NewPath(FileSystemOpts.WorkingDir);
+  SmallString<128> NewPath(FileSystemOpts.WorkingDir);
   llvm::sys::path::append(NewPath, pathRef);
   path =3D NewPath;
 }
=20
 llvm::MemoryBuffer *FileManager::
 getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
-  llvm::OwningPtr<llvm::MemoryBuffer> Result;
+  OwningPtr<llvm::MemoryBuffer> Result;
   llvm::error_code ec;
=20
   const char *Filename =3D Entry->getName();
@@ -504,7 +509,7 @@
     return Result.take();
   }
=20
-  llvm::SmallString<128> FilePath(Entry->getName());
+  SmallString<128> FilePath(Entry->getName());
   FixupRelativePath(FilePath);
   ec =3D llvm::MemoryBuffer::getFile(FilePath.str(), Result, Entry->getSiz=
e());
   if (ec && ErrorStr)
@@ -514,7 +519,7 @@
=20
 llvm::MemoryBuffer *FileManager::
 getBufferForFile(StringRef Filename, std::string *ErrorStr) {
-  llvm::OwningPtr<llvm::MemoryBuffer> Result;
+  OwningPtr<llvm::MemoryBuffer> Result;
   llvm::error_code ec;
   if (FileSystemOpts.WorkingDir.empty()) {
     ec =3D llvm::MemoryBuffer::getFile(Filename, Result);
@@ -523,7 +528,7 @@
     return Result.take();
   }
=20
-  llvm::SmallString<128> FilePath(Filename);
+  SmallString<128> FilePath(Filename);
   FixupRelativePath(FilePath);
   ec =3D llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
   if (ec && ErrorStr)
@@ -544,7 +549,7 @@
     return FileSystemStatCache::get(Path, StatBuf, FileDescriptor,
                                     StatCache.get());
=20
-  llvm::SmallString<128> FilePath(Path);
+  SmallString<128> FilePath(Path);
   FixupRelativePath(FilePath);
=20
   return FileSystemStatCache::get(FilePath.c_str(), StatBuf, FileDescripto=
r,
@@ -553,7 +558,7 @@
=20
 bool FileManager::getNoncachedStatValue(StringRef Path,=20
                                         struct stat &StatBuf) {
-  llvm::SmallString<128> FilePath(Path);
+  SmallString<128> FilePath(Path);
   FixupRelativePath(FilePath);
=20
   return ::stat(FilePath.c_str(), &StatBuf) !=3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/FileSystemStatCache.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/FileSystemStatCache.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/FileSystemStatCache.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -28,6 +28,8 @@
 #define S_ISDIR(s) ((_S_IFDIR & s) !=3D0)
 #endif
=20
+void FileSystemStatCache::anchor() { }
+
 /// FileSystemStatCache::get - Get the 'stat' information for the specified
 /// path, using the cache to accelerate it if possible.  This returns true=
 if
 /// the path does not exist or false if it exists.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/IdentifierTable.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/IdentifierTable.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/IdentifierTable.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -16,9 +16,10 @@
 #include "clang/Basic/LangOptions.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/DenseMap.h"
-#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cstdio>
=20
 using namespace clang;
@@ -37,7 +38,10 @@
   IsCPPOperatorKeyword =3D false;
   NeedsHandleIdentifier =3D false;
   IsFromAST =3D false;
+  ChangedAfterLoad =3D false;
   RevertedTokenID =3D false;
+  OutOfDate =3D false;
+  IsModulesImport =3D false;
   FETokenInfo =3D 0;
   Entry =3D 0;
 }
@@ -74,6 +78,10 @@
   // Populate the identifier table with info about keywords for the current
   // language.
   AddKeywords(LangOpts);
+     =20
+
+  // Add the '_experimental_modules_import' contextual keyword.
+  get("__experimental_modules_import").setModulesImport(true);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -93,7 +101,7 @@
     KEYNOCXX =3D 0x80,
     KEYBORLAND =3D 0x100,
     KEYOPENCL =3D 0x200,
-    KEYC1X =3D 0x400,
+    KEYC11 =3D 0x400,
     KEYARC =3D 0x800,
     KEYALL =3D 0x0fff
   };
@@ -105,7 +113,7 @@
 ///
 /// The C90/C99/CPP/CPP0x flags are set to 3 if the token is a keyword in a
 /// future language standard, set to 2 if the token should be enabled in t=
he
-/// specified langauge, set to 1 if it is an extension in the specified
+/// specified language, set to 1 if it is an extension in the specified
 /// language, and set to 0 if disabled in the specified language.
 static void AddKeyword(StringRef Keyword,
                        tok::TokenKind TokenCode, unsigned Flags,
@@ -122,8 +130,10 @@
   else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult =3D 2;
   else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult =3D 2;
   else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult =3D 2;
-  else if (LangOpts.C1X && (Flags & KEYC1X)) AddResult =3D 2;
-  else if (LangOpts.ObjCAutoRefCount && (Flags & KEYARC)) AddResult =3D 2;
+  else if (LangOpts.C11 && (Flags & KEYC11)) AddResult =3D 2;
+  // We treat bridge casts as objective-C keywords so we can warn on them
+  // in non-arc mode.
+  else if (LangOpts.ObjC2 && (Flags & KEYARC)) AddResult =3D 2;
   else if (LangOpts.CPlusPlus && (Flags & KEYCXX0X)) AddResult =3D 3;
=20
   // Don't add this keyword if disabled in this language.
@@ -212,7 +222,7 @@
   CASE( 6, 'i', 'n', ifndef);
   CASE( 6, 'i', 'p', import);
   CASE( 6, 'p', 'a', pragma);
-
+     =20
   CASE( 7, 'd', 'f', defined);
   CASE( 7, 'i', 'c', include);
   CASE( 7, 'w', 'r', warning);
@@ -220,8 +230,11 @@
   CASE( 8, 'u', 'a', unassert);
   CASE(12, 'i', 'c', include_next);
=20
+  CASE(14, '_', 'p', __public_macro);
+     =20
+  CASE(15, '_', 'p', __private_macro);
+
   CASE(16, '_', 'i', __include_macros);
-  CASE(16, '_', 'e', __export_macro__);
 #undef CASE
 #undef HASH
   }
@@ -347,7 +360,7 @@
 }
=20
 std::string MultiKeywordSelector::getName() const {
-  llvm::SmallString<256> Str;
+  SmallString<256> Str;
   llvm::raw_svector_ostream OS(Str);
   for (keyword_iterator I =3D keyword_begin(), E =3D keyword_end(); I !=3D=
 E; ++I) {
     if (*I)
@@ -445,6 +458,18 @@
   return *static_cast<SelectorTableImpl*>(P);
 }
=20
+/*static*/ Selector
+SelectorTable::constructSetterName(IdentifierTable &Idents,
+                                   SelectorTable &SelTable,
+                                   const IdentifierInfo *Name) {
+  SmallString<100> SelectorName;
+  SelectorName =3D "set";
+  SelectorName +=3D Name->getName();
+  SelectorName[3] =3D toupper(SelectorName[3]);
+  IdentifierInfo *SetterName =3D &Idents.get(SelectorName);
+  return SelTable.getUnarySelector(SetterName);
+}
+
 size_t SelectorTable::getTotalMemory() const {
   SelectorTableImpl &SelTabImpl =3D getSelectorTableImpl(Impl);
   return SelTabImpl.Allocator.getTotalMemory();
@@ -495,5 +520,5 @@
 #include "clang/Basic/OperatorKinds.def"
   }
=20
-  return 0;
+  llvm_unreachable("Invalid OverloadedOperatorKind!");
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/LangOptions.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/LangOptions.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/LangOptions.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -26,5 +26,7 @@
 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
   Name =3D Default;
 #include "clang/Basic/LangOptions.def"
+ =20
+  CurrentModule.clear();
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/SourceLocation.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/SourceLocation.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/SourceLocation.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -115,6 +115,10 @@
   return SrcMgr->isBeforeInTranslationUnit(*this, Loc);
 }
=20
+void FullSourceLoc::dump() const {
+  SourceLocation::dump(*SrcMgr);
+}
+
 const char *FullSourceLoc::getCharacterData(bool *Invalid) const {
   assert(isValid());
   return SrcMgr->getCharacterData(*this, Invalid);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/SourceManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/SourceManager.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/SourceManager.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -71,7 +71,11 @@
=20
 void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B,
                                  bool DoNotFree) {
-  assert(B !=3D Buffer.getPointer());
+  if (B =3D=3D Buffer.getPointer()) {
+    assert(0 && "Replacing with the same buffer");
+    Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
+    return;
+  }
  =20
   if (shouldFreeBuffer())
     delete Buffer.getPointer();
@@ -366,7 +370,8 @@
 SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr)
   : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true),
     ExternalSLocEntries(0), LineTable(0), NumLinearScans(0),
-    NumBinaryProbes(0), FakeBufferForRecovery(0) {
+    NumBinaryProbes(0), FakeBufferForRecovery(0),
+    FakeContentCacheForRecovery(0) {
   clearIDTables();
   Diag.setSourceManager(this);
 }
@@ -378,16 +383,21 @@
   // content cache objects are bump pointer allocated, we just have to run=
 the
   // dtors, but we call the deallocate method for completeness.
   for (unsigned i =3D 0, e =3D MemBufferInfos.size(); i !=3D e; ++i) {
-    MemBufferInfos[i]->~ContentCache();
-    ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
+    if (MemBufferInfos[i]) {
+      MemBufferInfos[i]->~ContentCache();
+      ContentCacheAlloc.Deallocate(MemBufferInfos[i]);
+    }
   }
   for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator
        I =3D FileInfos.begin(), E =3D FileInfos.end(); I !=3D E; ++I) {
-    I->second->~ContentCache();
-    ContentCacheAlloc.Deallocate(I->second);
+    if (I->second) {
+      I->second->~ContentCache();
+      ContentCacheAlloc.Deallocate(I->second);
+    }
   }
  =20
   delete FakeBufferForRecovery;
+  delete FakeContentCacheForRecovery;
=20
   for (llvm::DenseMap<FileID, MacroArgsMap *>::iterator
          I =3D MacroArgsCacheMap.begin(),E =3D MacroArgsCacheMap.end(); I!=
=3DE; ++I) {
@@ -461,6 +471,25 @@
   return Entry;
 }
=20
+const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index,
+                                                      bool *Invalid) const=
 {
+  assert(!SLocEntryLoaded[Index]);
+  if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) {
+    if (Invalid)
+      *Invalid =3D true;
+    // If the file of the SLocEntry changed we could still have loaded it.
+    if (!SLocEntryLoaded[Index]) {
+      // Try to recover; create a SLocEntry so the rest of clang can handl=
e it.
+      LoadedSLocEntryTable[Index] =3D SLocEntry::get(0,
+                                 FileInfo::get(SourceLocation(),
+                                               getFakeContentCacheForRecov=
ery(),
+                                               SrcMgr::C_User));
+    }
+  }
+
+  return LoadedSLocEntryTable[Index];
+}
+
 std::pair<int, unsigned>
 SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries,
                                          unsigned TotalSize) {
@@ -483,6 +512,18 @@
   return FakeBufferForRecovery;
 }
=20
+/// \brief As part of recovering from missing or changed content, produce a
+/// fake content cache.
+const SrcMgr::ContentCache *
+SourceManager::getFakeContentCacheForRecovery() const {
+  if (!FakeContentCacheForRecovery) {
+    FakeContentCacheForRecovery =3D new ContentCache();
+    FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(),
+                                               /*DoNotFree=3D*/true);
+  }
+  return FakeContentCacheForRecovery;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Methods to create new FileID's and macro expansions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -580,6 +621,7 @@
   assert(IR && "getOrCreateContentCache() cannot return NULL");
=20
   const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree);
+  const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden =3D true;
 }
=20
 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
@@ -730,11 +772,11 @@
 /// This function knows that the SourceLocation is in a loaded buffer, not=
 a
 /// local one.
 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
-  assert(SLocOffset >=3D CurrentLoadedOffset && "Bad function choice");
-
   // Sanity checking, otherwise a bug may lead to hanging in release build.
-  if (SLocOffset < CurrentLoadedOffset)
+  if (SLocOffset < CurrentLoadedOffset) {
+    assert(0 && "Invalid SLocOffset or bad function choice");
     return FileID();
+  }
=20
   // Essentially the same as the local case, but the loaded array is sorted
   // in the other direction.
@@ -946,13 +988,20 @@
 unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos,
                                         bool *Invalid) const {
   bool MyInvalid =3D false;
-  const char *Buf =3D getBuffer(FID, &MyInvalid)->getBufferStart();
+  const llvm::MemoryBuffer *MemBuf =3D getBuffer(FID, &MyInvalid);
   if (Invalid)
     *Invalid =3D MyInvalid;
=20
   if (MyInvalid)
     return 1;
=20
+  if (FilePos >=3D MemBuf->getBufferSize()) {
+    if (Invalid)
+      *Invalid =3D MyInvalid;
+    return 1;
+  }
+
+  const char *Buf =3D MemBuf->getBufferStart();
   unsigned LineStart =3D FilePos;
   while (LineStart && Buf[LineStart-1] !=3D '\n' && Buf[LineStart-1] !=3D =
'\r')
     --LineStart;
@@ -988,6 +1037,10 @@
   return getPresumedLoc(Loc).getColumn();
 }
=20
+#ifdef __SSE2__
+#include <emmintrin.h>
+#endif
+
 static LLVM_ATTRIBUTE_NOINLINE void
 ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI,
                    llvm::BumpPtrAllocator &Alloc,
@@ -1013,11 +1066,44 @@
   unsigned Offs =3D 0;
   while (1) {
     // Skip over the contents of the line.
-    // TODO: Vectorize this?  This is very performance sensitive for progr=
ams
-    // with lots of diagnostics and in -E mode.
     const unsigned char *NextBuf =3D (const unsigned char *)Buf;
+
+#ifdef __SSE2__
+    // Try to skip to the next newline using SSE instructions. This is very
+    // performance sensitive for programs with lots of diagnostics and in =
-E
+    // mode.
+    __m128i CRs =3D _mm_set1_epi8('\r');
+    __m128i LFs =3D _mm_set1_epi8('\n');
+
+    // First fix up the alignment to 16 bytes.
+    while (((uintptr_t)NextBuf & 0xF) !=3D 0) {
+      if (*NextBuf =3D=3D '\n' || *NextBuf =3D=3D '\r' || *NextBuf =3D=3D =
'\0')
+        goto FoundSpecialChar;
+      ++NextBuf;
+    }
+
+    // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'.
+    while (NextBuf+16 <=3D End) {
+      __m128i Chunk =3D *(__m128i*)NextBuf;
+      __m128i Cmp =3D _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs),
+                                 _mm_cmpeq_epi8(Chunk, LFs));
+      unsigned Mask =3D _mm_movemask_epi8(Cmp);
+
+      // If we found a newline, adjust the pointer and jump to the handlin=
g code.
+      if (Mask !=3D 0) {
+        NextBuf +=3D llvm::CountTrailingZeros_32(Mask);
+        goto FoundSpecialChar;
+      }
+      NextBuf +=3D 16;
+    }
+#endif
+
     while (*NextBuf !=3D '\n' && *NextBuf !=3D '\r' && *NextBuf !=3D '\0')
       ++NextBuf;
+
+#ifdef __SSE2__
+FoundSpecialChar:
+#endif
     Offs +=3D NextBuf-Buf;
     Buf =3D NextBuf;
=20
@@ -1508,9 +1594,10 @@
     return FileLoc.getLocWithOffset(Size);
   }
=20
+  const llvm::MemoryBuffer *Buffer =3D Content->getBuffer(Diag, *this);
   unsigned FilePos =3D Content->SourceLineCache[Line - 1];
-  const char *Buf =3D Content->getBuffer(Diag, *this)->getBufferStart() + =
FilePos;
-  unsigned BufLength =3D Content->getBuffer(Diag, *this)->getBufferEnd() -=
 Buf;
+  const char *Buf =3D Buffer->getBufferStart() + FilePos;
+  unsigned BufLength =3D Buffer->getBufferSize() - FilePos;
   if (BufLength =3D=3D 0)
     return FileLoc.getLocWithOffset(FilePos);
=20
@@ -1568,14 +1655,31 @@
       continue;
     }
=20
-    if (!Entry.getExpansion().isMacroArgExpansion())
+    const ExpansionInfo &ExpInfo =3D Entry.getExpansion();
+
+    if (ExpInfo.getExpansionLocStart().isFileID()) {
+      if (!isInFileID(ExpInfo.getExpansionLocStart(), FID))
+        return; // No more files/macros that may be "contained" in this fi=
le.
+    }
+
+    if (!ExpInfo.isMacroArgExpansion())
       continue;
-=20
-    SourceLocation SpellLoc =3D
-        getSpellingLoc(Entry.getExpansion().getSpellingLoc());
+
+    SourceLocation SpellLoc =3D ExpInfo.getSpellingLoc();
+    while (!SpellLoc.isFileID()) {
+      std::pair<FileID, unsigned> LocInfo =3D getDecomposedLoc(SpellLoc);
+      const ExpansionInfo &Info =3D getSLocEntry(LocInfo.first).getExpansi=
on();
+      if (!Info.isMacroArgExpansion())
+        break;
+      SpellLoc =3D Info.getSpellingLoc().getLocWithOffset(LocInfo.second);
+    }
+    if (!SpellLoc.isFileID())
+      continue;
+   =20
     unsigned BeginOffs;
     if (!isInFileID(SpellLoc, FID, &BeginOffs))
-      return; // No more files/macros that may be "contained" in this file.
+      continue;
+
     unsigned EndOffs =3D BeginOffs + getFileIDSize(FileID::get(ID));
=20
     // Add a new chunk for this macro argument. A previous macro argument =
chunk
@@ -1648,7 +1752,7 @@
   SourceLocation UpperLoc;
   const SrcMgr::SLocEntry &Entry =3D SM.getSLocEntry(Loc.first);
   if (Entry.isExpansion())
-    UpperLoc =3D Entry.getExpansion().getExpansionLocEnd();
+    UpperLoc =3D Entry.getExpansion().getExpansionLocStart();
   else
     UpperLoc =3D Entry.getFile().getIncludeLoc();
  =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/TargetInfo.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/TargetInfo.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/TargetInfo.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -27,6 +27,7 @@
 TargetInfo::TargetInfo(const std::string &T) : Triple(T) {
   // Set defaults.  Defaults are set for a 32-bit RISC platform, like PPC =
or
   // SPARC.  These should be overridden by concrete targets as needed.
+  BigEndian =3D true;
   TLSSupported =3D true;
   NoAsmVariants =3D false;
   PointerWidth =3D PointerAlign =3D 32;
@@ -34,6 +35,7 @@
   IntWidth =3D IntAlign =3D 32;
   LongWidth =3D LongAlign =3D 32;
   LongLongWidth =3D LongLongAlign =3D 64;
+  SuitableAlign =3D 64;
   HalfWidth =3D 16;
   HalfAlign =3D 16;
   FloatWidth =3D 32;
@@ -74,6 +76,9 @@
   // Default to no types using fpret.
   RealTypeUsesObjCFPRet =3D 0;
=20
+  // Default to not using fp2ret for __Complex long double
+  ComplexLongDoubleUsesFP2Ret =3D false;
+
   // Default to using the Itanium ABI.
   CXXABI =3D CXXABI_Itanium;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/Targets.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/Targets.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/Targets.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -54,6 +54,14 @@
   Builder.defineMacro("__" + MacroName + "__");
 }
=20
+static void defineCPUMacros(MacroBuilder &Builder, StringRef CPUName,
+                            bool Tuning =3D true) {
+  Builder.defineMacro("__" + CPUName);
+  Builder.defineMacro("__" + CPUName + "__");
+  if (Tuning)
+    Builder.defineMacro("__tune_" + CPUName + "__");
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Defines specific to certain operating systems.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -99,13 +107,6 @@
     // allow this in C, since one might have block pointers in structs that
     // are used in pure C code and in Objective-C ARC.
     Builder.defineMacro("__unsafe_unretained", "");
-
-    // The Objective-C bridged cast keywords are defined to nothing in non=
-ARC
-    // mode; then they become normal, C-style casts.
-    Builder.defineMacro("__bridge", "");
-    Builder.defineMacro("__bridge_transfer", "");
-    Builder.defineMacro("__bridge_retained", "");
-    Builder.defineMacro("__bridge_retain", "");
   }
=20
   if (Opts.Static)
@@ -118,36 +119,15 @@
=20
   // Get the platform type and version number from the triple.
   unsigned Maj, Min, Rev;
-
-  // If no version was given, default to to 10.4.0, for simplifying tests.
-  if (Triple.getOSName() =3D=3D "darwin" || Triple.getOSName() =3D=3D "osx=
") {
+  if (Triple.isMacOSX()) {
+    Triple.getMacOSXVersion(Maj, Min, Rev);
     PlatformName =3D "macosx";
-    Min =3D Rev =3D 0;
-    Maj =3D 8;
   } else {
-    // Otherwise, honor all three triple forms ("-darwinNNN[-iphoneos]",
-    // "-osxNNN", and "-iosNNN").
-
-    if (Triple.getOS() =3D=3D llvm::Triple::Darwin) {
-      // For historical reasons that make little sense, the version passed=
 here
-      // is the "darwin" version, which drops the 10 and offsets by 4.
-      Triple.getOSVersion(Maj, Min, Rev);
-
-      if (Triple.getEnvironmentName() =3D=3D "iphoneos") {
-        PlatformName =3D "ios";
-      } else {
-        PlatformName =3D "macosx";
-        Rev =3D Min;
-        Min =3D Maj - 4;
-        Maj =3D 10;
-      }
-    } else {
-      Triple.getOSVersion(Maj, Min, Rev);
-      PlatformName =3D llvm::Triple::getOSTypeName(Triple.getOS());
-    }
+    Triple.getOSVersion(Maj, Min, Rev);
+    PlatformName =3D llvm::Triple::getOSTypeName(Triple.getOS());
   }
=20
-  // If -ccc-host-triple arch-pc-win32-macho option specified, we're
+  // If -target arch-pc-win32-macho option specified, we're
   // generating code for Win32 ABI. No need to emit
   // __ENVIRONMENT_XX_OS_VERSION_MIN_REQUIRED__.
   if (PlatformName =3D=3D "win32") {
@@ -156,7 +136,7 @@
   }
=20
   // Set the appropriate OS version define.
-  if (PlatformName =3D=3D "ios") {
+  if (Triple.getOS() =3D=3D llvm::Triple::IOS) {
     assert(Maj < 10 && Min < 100 && Rev < 100 && "Invalid version!");
     char Str[6];
     Str[0] =3D '0' + Maj;
@@ -217,6 +197,12 @@
     return "__TEXT,__StaticInit,regular,pure_instructions";
   }
=20
+  /// Darwin does not support protected visibility.  Darwin's "default"
+  /// is very similar to ELF's "protected";  Darwin requires a "weak"
+  /// attribute on declarations that can be dynamically replaced.
+  virtual bool hasProtectedVisibility() const {
+    return false;
+  }
 };
=20
=20
@@ -236,7 +222,18 @@
   }
 public:
   DragonFlyBSDTargetInfo(const std::string &triple)
-    : OSTargetInfo<Target>(triple) {}
+    : OSTargetInfo<Target>(triple) {
+      this->UserLabelPrefix =3D "";
+
+      llvm::Triple Triple(triple);
+      switch (Triple.getArch()) {
+        default:
+        case llvm::Triple::x86:
+        case llvm::Triple::x86_64:
+          this->MCountName =3D ".mcount";
+          break;
+      }
+  }
 };
=20
 // FreeBSD Target
@@ -249,7 +246,7 @@
=20
     unsigned Release =3D Triple.getOSMajorVersion();
     if (Release =3D=3D 0U)
-      Release =3D 8U;
+      Release =3D 8;
=20
     Builder.defineMacro("__FreeBSD__", Twine(Release));
     Builder.defineMacro("__FreeBSD_cc_version", Twine(Release * 100000U + =
1U));
@@ -298,6 +295,7 @@
     Builder.defineMacro("_EM_LSIZE", "4");
     Builder.defineMacro("_EM_FSIZE", "4");
     Builder.defineMacro("_EM_DSIZE", "8");
+    Builder.defineMacro("__ELF__");
     DefineStd(Builder, "unix", Opts);
   }
 public:
@@ -329,6 +327,10 @@
     this->UserLabelPrefix =3D "";
     this->WIntType =3D TargetInfo::UnsignedInt;
   }
+
+  virtual const char *getStaticInitSectionSpecifier() const {
+    return ".text.startup";
+  }
 };
=20
 // NetBSD Target
@@ -367,7 +369,26 @@
   }
 public:
   OpenBSDTargetInfo(const std::string &triple)
-    : OSTargetInfo<Target>(triple) {}
+    : OSTargetInfo<Target>(triple) {
+      this->UserLabelPrefix =3D "";
+
+      llvm::Triple Triple(triple);
+      switch (Triple.getArch()) {
+        default:
+        case llvm::Triple::x86:
+        case llvm::Triple::x86_64:
+        case llvm::Triple::arm:
+	case llvm::Triple::sparc:
+          this->MCountName =3D "__mcount";
+          break;
+        case llvm::Triple::mips64:
+        case llvm::Triple::mips64el:
+        case llvm::Triple::ppc:
+	case llvm::Triple::sparcv9:
+          this->MCountName =3D "_mcount";
+          break;
+      }
+  }
 };
=20
 // PSP Target
@@ -408,13 +429,14 @@
   PS3PPUTargetInfo(const std::string& triple)
     : OSTargetInfo<Target>(triple) {
     this->UserLabelPrefix =3D "";
-    this->LongWidth =3D this->LongAlign =3D this->PointerWidth =3D this->P=
ointerAlign =3D 32;
+    this->LongWidth =3D this->LongAlign =3D 32;
+    this->PointerWidth =3D this->PointerAlign =3D 32;
     this->IntMaxType =3D TargetInfo::SignedLongLong;
     this->UIntMaxType =3D TargetInfo::UnsignedLongLong;
     this->Int64Type =3D TargetInfo::SignedLongLong;
     this->SizeType =3D TargetInfo::UnsignedInt;
     this->DescriptionString =3D "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:=
32:32-"
-                        "i64:64:64-f32:32:32-f64:64:64-v128:128:128-n32";
+                              "i64:64:64-f32:32:32-f64:64:64-v128:128:128-=
n32";
   }
 };
=20
@@ -468,12 +490,26 @@
     Builder.defineMacro("__ELF__");
     Builder.defineMacro("__svr4__");
     Builder.defineMacro("__SVR4");
+    // Solaris headers require _XOPEN_SOURCE to be set to 600 for C99 and
+    // newer, but to 500 for everything else.  feature_test.h has a check =
to
+    // ensure that you are not using C99 with an old version of X/Open or =
C89
+    // with a new version. =20
+    if (Opts.C99 || Opts.C11)
+      Builder.defineMacro("_XOPEN_SOURCE", "600");
+    else
+      Builder.defineMacro("_XOPEN_SOURCE", "500");
+    if (Opts.CPlusPlus)
+      Builder.defineMacro("__C99FEATURES__");
+    Builder.defineMacro("_LARGEFILE_SOURCE");
+    Builder.defineMacro("_LARGEFILE64_SOURCE");
+    Builder.defineMacro("__EXTENSIONS__");
+    Builder.defineMacro("_REENTRANT");
   }
 public:
   SolarisTargetInfo(const std::string& triple)
     : OSTargetInfo<Target>(triple) {
     this->UserLabelPrefix =3D "";
-    this->WCharType =3D this->SignedLong;
+    this->WCharType =3D this->SignedInt;
     // FIXME: WIntType should be SignedLong
   }
 };
@@ -538,7 +574,10 @@
   static const char * const GCCRegNames[];
   static const TargetInfo::GCCRegAlias GCCRegAliases[];
 public:
-  PPCTargetInfo(const std::string& triple) : TargetInfo(triple) {}
+  PPCTargetInfo(const std::string& triple) : TargetInfo(triple) {
+    LongDoubleWidth =3D LongDoubleAlign =3D 128;
+    LongDoubleFormat =3D &llvm::APFloat::PPCDoubleDouble;
+  }
=20
   virtual void getTargetBuiltins(const Builtin::Info *&Records,
                                  unsigned &NumRecords) const {
@@ -546,9 +585,13 @@
     NumRecords =3D clang::PPC::LastTSBuiltin-Builtin::FirstTSBuiltin;
   }
=20
+  virtual bool isCLZForZeroUndef() const { return false; }
+
   virtual void getTargetDefines(const LangOptions &Opts,
                                 MacroBuilder &Builder) const;
=20
+  virtual bool hasFeature(StringRef Feature) const;
+ =20
   virtual void getGCCRegNames(const char * const *&Names,
                               unsigned &NumNames) const;
   virtual void getGCCRegAliases(const GCCRegAlias *&Aliases,
@@ -701,7 +744,11 @@
   }
 }
=20
-
+bool PPCTargetInfo::hasFeature(StringRef Feature) const {
+  return Feature =3D=3D "powerpc";
+}
+
+ =20
 const char * const PPCTargetInfo::GCCRegNames[] =3D {
   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
@@ -814,13 +861,21 @@
                         "i64:64:64-f32:32:32-f64:64:64-v128:128:128-n32";
=20
     switch (getTriple().getOS()) {
+    case llvm::Triple::Linux:
     case llvm::Triple::FreeBSD:
     case llvm::Triple::NetBSD:
       SizeType =3D UnsignedInt;
+      PtrDiffType =3D SignedInt;
+      IntPtrType =3D SignedInt;
       break;
     default:
       break;
     }
+
+    if (getTriple().getOS() =3D=3D llvm::Triple::FreeBSD) {
+      LongDoubleWidth =3D LongDoubleAlign =3D 64;
+      LongDoubleFormat =3D &llvm::APFloat::IEEEdouble;
+    }
   }
=20
   virtual const char *getVAListDeclaration() const {
@@ -846,6 +901,11 @@
     Int64Type =3D SignedLong;
     DescriptionString =3D "E-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
                         "i64:64:64-f32:32:32-f64:64:64-v128:128:128-n32:64=
";
+
+    if (getTriple().getOS() =3D=3D llvm::Triple::FreeBSD) {
+      LongDoubleWidth =3D LongDoubleAlign =3D 64;
+      LongDoubleFormat =3D &llvm::APFloat::IEEEdouble;
+    }
   }
   virtual const char *getVAListDeclaration() const {
     return "typedef char* __builtin_va_list;";
@@ -862,6 +922,10 @@
     : DarwinTargetInfo<PPC32TargetInfo>(triple) {
     HasAlignMac68kSupport =3D true;
     BoolWidth =3D BoolAlign =3D 32; //XXX support -mone-byte-bool?
+    LongLongAlign =3D 32;
+    SuitableAlign =3D 128;
+    DescriptionString =3D "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
+                        "i64:32:64-f32:32:32-f64:64:64-v128:128:128-n32";
   }
   virtual const char *getVAListDeclaration() const {
     return "typedef char* __builtin_va_list;";
@@ -874,6 +938,7 @@
   DarwinPPC64TargetInfo(const std::string& triple)
     : DarwinTargetInfo<PPC64TargetInfo>(triple) {
     HasAlignMac68kSupport =3D true;
+    SuitableAlign =3D 128;
   }
 };
 } // end anonymous namespace.
@@ -890,6 +955,7 @@
     std::vector<llvm::StringRef> AvailableFeatures;
   public:
     PTXTargetInfo(const std::string& triple) : TargetInfo(triple) {
+      BigEndian =3D false;
       TLSSupported =3D false;
       LongWidth =3D LongAlign =3D 64;
       AddrSpaceMap =3D &PTXAddrSpaceMap;
@@ -924,7 +990,10 @@
       Records =3D BuiltinInfo;
       NumRecords =3D clang::PTX::LastTSBuiltin-Builtin::FirstTSBuiltin;
     }
-
+    virtual bool hasFeature(StringRef Feature) const {
+      return Feature =3D=3D "ptx";
+    }
+   =20
     virtual void getGCCRegNames(const char * const *&Names,
                                 unsigned &NumNames) const;
     virtual void getGCCRegAliases(const GCCRegAlias *&Aliases,
@@ -948,7 +1017,7 @@
     }
=20
     virtual bool setFeatureEnabled(llvm::StringMap<bool> &Features,
-                                   const std::string &Name,
+                                   StringRef Name,
                                    bool Enabled) const;
   };
=20
@@ -970,7 +1039,7 @@
   }
=20
   bool PTXTargetInfo::setFeatureEnabled(llvm::StringMap<bool> &Features,
-                                        const std::string &Name,
+                                        StringRef Name,
                                         bool Enabled) const {
     if(std::binary_search(AvailableFeatures.begin(), AvailableFeatures.end=
(),
                           Name)) {
@@ -1023,6 +1092,10 @@
   virtual void getTargetDefines(const LangOptions &Opts,
                                 MacroBuilder &Builder) const;
=20
+  virtual bool hasFeature(StringRef Feature) const {
+    return Feature =3D=3D "mblaze";
+  }
+ =20
   virtual const char *getVAListDeclaration() const {
     return "typedef char* __builtin_va_list;";
   }
@@ -1146,6 +1219,8 @@
   "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
   "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
+  "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7",
+  "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15",
 };
=20
 const TargetInfo::AddlRegName AddlRegNames[] =3D {
@@ -1163,14 +1238,18 @@
 // most of the implementation can be shared.
 class X86TargetInfo : public TargetInfo {
   enum X86SSEEnum {
-    NoSSE, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42
+    NoSSE, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42, AVX, AVX2
   } SSELevel;
   enum MMX3DNowEnum {
     NoMMX3DNow, MMX, AMD3DNow, AMD3DNowAthlon
   } MMX3DNowLevel;
=20
   bool HasAES;
-  bool HasAVX;
+  bool HasLZCNT;
+  bool HasBMI;
+  bool HasBMI2;
+  bool HasPOPCNT;
+  bool HasFMA4;
=20
   /// \brief Enumeration of all of the X86 CPUs supported by Clang.
   ///
@@ -1252,6 +1331,7 @@
     CK_Corei7,
     CK_Corei7AVX,
     CK_CoreAVXi,
+    CK_CoreAVX2,
     //@}
=20
     /// \name K6
@@ -1283,6 +1363,20 @@
     CK_Opteron,
     CK_OpteronSSE3,
     CK_AMDFAM10,
+    //@}
+
+    /// \name Bobcat
+    /// Bobcat architecture processors.
+    //@{
+    CK_BTVER1,
+    //@}
+
+    /// \name Bulldozer
+    /// Bulldozer architecture processors.
+    //@{
+    CK_BDVER1,
+    CK_BDVER2,
+    //@}
=20
     /// This specification is deprecated and will be removed in the future.
     /// Users should prefer \see CK_K8.
@@ -1300,9 +1394,15 @@
 public:
   X86TargetInfo(const std::string& triple)
     : TargetInfo(triple), SSELevel(NoSSE), MMX3DNowLevel(NoMMX3DNow),
-      HasAES(false), HasAVX(false), CPU(CK_Generic) {
+      HasAES(false), HasLZCNT(false), HasBMI(false), HasBMI2(false),
+      HasPOPCNT(false), HasFMA4(false), CPU(CK_Generic) {
+    BigEndian =3D false;
     LongDoubleFormat =3D &llvm::APFloat::x87DoubleExtended;
   }
+  virtual unsigned getFloatEvalMethod() const {
+    // X87 evaluates with 80 bits "long double" precision.
+    return SSELevel =3D=3D NoSSE ? 2 : 0;
+  }
   virtual void getTargetBuiltins(const Builtin::Info *&Records,
                                  unsigned &NumRecords) const {
     Records =3D BuiltinInfo;
@@ -1332,12 +1432,17 @@
   virtual void getTargetDefines(const LangOptions &Opts,
                                 MacroBuilder &Builder) const;
   virtual bool setFeatureEnabled(llvm::StringMap<bool> &Features,
-                                 const std::string &Name,
+                                 StringRef Name,
                                  bool Enabled) const;
   virtual void getDefaultFeatures(llvm::StringMap<bool> &Features) const;
+  virtual bool hasFeature(StringRef Feature) const;
   virtual void HandleTargetFeatures(std::vector<std::string> &Features);
   virtual const char* getABI() const {
-    return MMX3DNowLevel =3D=3D NoMMX3DNow ? "no-mmx" : "";
+    if (PointerWidth =3D=3D 64 && SSELevel >=3D AVX)
+      return "avx";
+    else if (PointerWidth =3D=3D 32 && MMX3DNowLevel =3D=3D NoMMX3DNow)
+      return "no-mmx";
+    return "";
   }
   virtual bool setCPU(const std::string &Name) {
     CPU =3D llvm::StringSwitch<CPUKind>(Name)
@@ -1367,6 +1472,7 @@
       .Case("corei7", CK_Corei7)
       .Case("corei7-avx", CK_Corei7AVX)
       .Case("core-avx-i", CK_CoreAVXi)
+      .Case("core-avx2", CK_CoreAVX2)
       .Case("k6", CK_K6)
       .Case("k6-2", CK_K6_2)
       .Case("k6-3", CK_K6_3)
@@ -1383,6 +1489,9 @@
       .Case("opteron", CK_Opteron)
       .Case("opteron-sse3", CK_OpteronSSE3)
       .Case("amdfam10", CK_AMDFAM10)
+      .Case("btver1", CK_BTVER1)
+      .Case("bdver1", CK_BDVER1)
+      .Case("bdver2", CK_BDVER2)
       .Case("x86-64", CK_x86_64)
       .Case("geode", CK_Geode)
       .Default(CK_Generic);
@@ -1436,6 +1545,7 @@
     case CK_Corei7:
     case CK_Corei7AVX:
     case CK_CoreAVXi:
+    case CK_CoreAVX2:
     case CK_Athlon64:
     case CK_Athlon64SSE3:
     case CK_AthlonFX:
@@ -1444,6 +1554,9 @@
     case CK_Opteron:
     case CK_OpteronSSE3:
     case CK_AMDFAM10:
+    case CK_BTVER1:
+    case CK_BDVER1:
+    case CK_BDVER2:
     case CK_x86_64:
       return true;
     }
@@ -1465,6 +1578,12 @@
   Features["sse4a"] =3D false;
   Features["aes"] =3D false;
   Features["avx"] =3D false;
+  Features["avx2"] =3D false;
+  Features["lzcnt"] =3D false;
+  Features["bmi"] =3D false;
+  Features["bmi2"] =3D false;
+  Features["popcnt"] =3D false;
+  Features["fma4"] =3D false;
=20
   // FIXME: This *really* should not be here.
=20
@@ -1509,8 +1628,7 @@
     break;
   case CK_Penryn:
     setFeatureEnabled(Features, "mmx", true);
-    setFeatureEnabled(Features, "sse4", true);
-    Features["sse42"] =3D false;
+    setFeatureEnabled(Features, "sse4.1", true);
     break;
   case CK_Atom:
     setFeatureEnabled(Features, "mmx", true);
@@ -1528,6 +1646,15 @@
     setFeatureEnabled(Features, "aes", true);
     //setFeatureEnabled(Features, "avx", true);
     break;
+  case CK_CoreAVX2:
+    setFeatureEnabled(Features, "mmx", true);
+    setFeatureEnabled(Features, "sse4", true);
+    setFeatureEnabled(Features, "aes", true);
+    setFeatureEnabled(Features, "lzcnt", true);
+    setFeatureEnabled(Features, "bmi", true);
+    setFeatureEnabled(Features, "bmi2", true);
+    //setFeatureEnabled(Features, "avx2", true);
+    break;
   case CK_K6:
   case CK_WinChipC6:
     setFeatureEnabled(Features, "mmx", true);
@@ -1567,6 +1694,15 @@
     setFeatureEnabled(Features, "sse4a", true);
     setFeatureEnabled(Features, "3dnowa", true);
     break;
+  case CK_BTVER1:
+    setFeatureEnabled(Features, "ssse3", true);
+    setFeatureEnabled(Features, "sse4a", true);
+  case CK_BDVER1:
+  case CK_BDVER2:
+    setFeatureEnabled(Features, "sse4", true);
+    setFeatureEnabled(Features, "sse4a", true);
+    setFeatureEnabled(Features, "aes", true);
+    break;
   case CK_C3_2:
     setFeatureEnabled(Features, "mmx", true);
     setFeatureEnabled(Features, "sse", true);
@@ -1575,7 +1711,7 @@
 }
=20
 bool X86TargetInfo::setFeatureEnabled(llvm::StringMap<bool> &Features,
-                                      const std::string &Name,
+                                      StringRef Name,
                                       bool Enabled) const {
   // FIXME: This *really* should not be here.  We need some way of transla=
ting
   // options into llvm subtarget features.
@@ -1600,7 +1736,8 @@
         Features["ssse3"] =3D true;
     else if (Name =3D=3D "sse4" || Name =3D=3D "sse4.2")
       Features["mmx"] =3D Features["sse"] =3D Features["sse2"] =3D Feature=
s["sse3"] =3D
-        Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D =
true;
+        Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D
+        Features["popcnt"] =3D true;
     else if (Name =3D=3D "sse4.1")
       Features["mmx"] =3D Features["sse"] =3D Features["sse2"] =3D Feature=
s["sse3"] =3D
         Features["ssse3"] =3D Features["sse41"] =3D true;
@@ -1613,21 +1750,39 @@
     else if (Name =3D=3D "avx")
       Features["mmx"] =3D Features["sse"] =3D Features["sse2"] =3D Feature=
s["sse3"] =3D
         Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D
-        Features["avx"] =3D true;
+        Features["popcnt"] =3D Features["avx"] =3D true;
+    else if (Name =3D=3D "avx2")
+      Features["mmx"] =3D Features["sse"] =3D Features["sse2"] =3D Feature=
s["sse3"] =3D
+        Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D
+        Features["popcnt"] =3D Features["avx"] =3D Features["avx2"] =3D tr=
ue;
+    else if (Name =3D=3D "fma4")
+        Features["mmx"] =3D Features["sse"] =3D Features["sse2"] =3D Featu=
res["sse3"] =3D
+        Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D
+        Features["popcnt"] =3D Features["avx"] =3D Features["fma4"] =3D tr=
ue;
     else if (Name =3D=3D "sse4a")
-      Features["mmx"] =3D Features["sse4a"] =3D true;
+      Features["mmx"] =3D Features["sse"] =3D Features["sse2"] =3D Feature=
s["sse3"] =3D
+        Features["lzcnt"] =3D Features["popcnt"] =3D Features["sse4a"] =3D=
 true;
+    else if (Name =3D=3D "lzcnt")
+      Features["lzcnt"] =3D true;
+    else if (Name =3D=3D "bmi")
+      Features["bmi"] =3D true;
+    else if (Name =3D=3D "bmi2")
+      Features["bmi2"] =3D true;
+    else if (Name =3D=3D "popcnt")
+      Features["popcnt"] =3D true;
   } else {
     if (Name =3D=3D "mmx")
       Features["mmx"] =3D Features["3dnow"] =3D Features["3dnowa"] =3D fal=
se;
     else if (Name =3D=3D "sse")
       Features["sse"] =3D Features["sse2"] =3D Features["sse3"] =3D
-        Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D =
false;
+        Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D
+        Features["sse4a"] =3D false;
     else if (Name =3D=3D "sse2")
       Features["sse2"] =3D Features["sse3"] =3D Features["ssse3"] =3D
-        Features["sse41"] =3D Features["sse42"] =3D false;
+        Features["sse41"] =3D Features["sse42"] =3D Features["sse4a"] =3D =
false;
     else if (Name =3D=3D "sse3")
       Features["sse3"] =3D Features["ssse3"] =3D Features["sse41"] =3D
-        Features["sse42"] =3D false;
+        Features["sse42"] =3D Features["sse4a"] =3D false;
     else if (Name =3D=3D "ssse3")
       Features["ssse3"] =3D Features["sse41"] =3D Features["sse42"] =3D fa=
lse;
     else if (Name =3D=3D "sse4" || Name =3D=3D "sse4.1")
@@ -1641,9 +1796,21 @@
     else if (Name =3D=3D "aes")
       Features["aes"] =3D false;
     else if (Name =3D=3D "avx")
-      Features["avx"] =3D false;
+      Features["avx"] =3D Features["avx2"] =3D Features["fma4"] =3D false;
+    else if (Name =3D=3D "avx2")
+      Features["avx2"] =3D false;
     else if (Name =3D=3D "sse4a")
       Features["sse4a"] =3D false;
+    else if (Name =3D=3D "lzcnt")
+      Features["lzcnt"] =3D false;
+    else if (Name =3D=3D "bmi")
+      Features["bmi"] =3D false;
+    else if (Name =3D=3D "bmi2")
+      Features["bmi2"] =3D false;
+    else if (Name =3D=3D "popcnt")
+      Features["popcnt"] =3D false;
+    else if (Name =3D=3D "fma4")
+      Features["fma4"] =3D false;
   }
=20
   return true;
@@ -1658,20 +1825,42 @@
     if (Features[i][0] =3D=3D '-')
       continue;
=20
-    if (Features[i].substr(1) =3D=3D "aes") {
+    StringRef Feature =3D StringRef(Features[i]).substr(1);
+
+    if (Feature =3D=3D "aes") {
       HasAES =3D true;
       continue;
     }
=20
-    // FIXME: Not sure yet how to treat AVX in regard to SSE levels.
-    // For now let it be enabled together with other SSE levels.
-    if (Features[i].substr(1) =3D=3D "avx") {
-      HasAVX =3D true;
+    if (Feature =3D=3D "lzcnt") {
+      HasLZCNT =3D true;
       continue;
     }
=20
+    if (Feature =3D=3D "bmi") {
+      HasBMI =3D true;
+      continue;
+    }
+
+    if (Feature =3D=3D "bmi2") {
+      HasBMI2 =3D true;
+      continue;
+    }
+
+    if (Feature =3D=3D "popcnt") {
+      HasPOPCNT =3D true;
+      continue;
+    }
+
+    if (Feature =3D=3D "fma4") {
+      HasFMA4 =3D true;
+      continue;
+    }
+
     assert(Features[i][0] =3D=3D '+' && "Invalid target feature!");
-    X86SSEEnum Level =3D llvm::StringSwitch<X86SSEEnum>(Features[i].substr=
(1))
+    X86SSEEnum Level =3D llvm::StringSwitch<X86SSEEnum>(Feature)
+      .Case("avx2", AVX2)
+      .Case("avx", AVX)
       .Case("sse42", SSE42)
       .Case("sse41", SSE41)
       .Case("ssse3", SSSE3)
@@ -1682,7 +1871,7 @@
     SSELevel =3D std::max(SSELevel, Level);
=20
     MMX3DNowEnum ThreeDNowLevel =3D
-      llvm::StringSwitch<MMX3DNowEnum>(Features[i].substr(1))
+      llvm::StringSwitch<MMX3DNowEnum>(Feature)
         .Case("3dnowa", AMD3DNowAthlon)
         .Case("3dnow", AMD3DNow)
         .Case("mmx", MMX)
@@ -1705,8 +1894,10 @@
                                      MacroBuilder &Builder) const {
   // Target identification.
   if (PointerWidth =3D=3D 64) {
-    Builder.defineMacro("_LP64");
-    Builder.defineMacro("__LP64__");
+    if (getLongWidth() =3D=3D 64) {
+      Builder.defineMacro("_LP64");
+      Builder.defineMacro("__LP64__");
+    }
     Builder.defineMacro("__amd64__");
     Builder.defineMacro("__amd64");
     Builder.defineMacro("__x86_64");
@@ -1729,9 +1920,7 @@
   case CK_WinChipC6:
   case CK_WinChip2:
   case CK_C3:
-    Builder.defineMacro("__i486");
-    Builder.defineMacro("__i486__");
-    Builder.defineMacro("__tune_i486__");
+    defineCPUMacros(Builder, "i486");
     break;
   case CK_PentiumMMX:
     Builder.defineMacro("__pentium_mmx__");
@@ -1739,12 +1928,8 @@
     // Fallthrough
   case CK_i586:
   case CK_Pentium:
-    Builder.defineMacro("__i586");
-    Builder.defineMacro("__i586__");
-    Builder.defineMacro("__tune_i586__");
-    Builder.defineMacro("__pentium");
-    Builder.defineMacro("__pentium__");
-    Builder.defineMacro("__tune_pentium__");
+    defineCPUMacros(Builder, "i586");
+    defineCPUMacros(Builder, "pentium");
     break;
   case CK_Pentium3:
   case CK_Pentium3M:
@@ -1768,34 +1953,25 @@
     break;
   case CK_Pentium4:
   case CK_Pentium4M:
-    Builder.defineMacro("__pentium4");
-    Builder.defineMacro("__pentium4__");
-    Builder.defineMacro("__tune_pentium4__");
+    defineCPUMacros(Builder, "pentium4");
     break;
   case CK_Yonah:
   case CK_Prescott:
   case CK_Nocona:
-    Builder.defineMacro("__nocona");
-    Builder.defineMacro("__nocona__");
-    Builder.defineMacro("__tune_nocona__");
+    defineCPUMacros(Builder, "nocona");
     break;
   case CK_Core2:
   case CK_Penryn:
-    Builder.defineMacro("__core2");
-    Builder.defineMacro("__core2__");
-    Builder.defineMacro("__tune_core2__");
+    defineCPUMacros(Builder, "core2");
     break;
   case CK_Atom:
-    Builder.defineMacro("__atom");
-    Builder.defineMacro("__atom__");
-    Builder.defineMacro("__tune_atom__");
+    defineCPUMacros(Builder, "atom");
     break;
   case CK_Corei7:
   case CK_Corei7AVX:
   case CK_CoreAVXi:
-    Builder.defineMacro("__corei7");
-    Builder.defineMacro("__corei7__");
-    Builder.defineMacro("__tune_corei7__");
+  case CK_CoreAVX2:
+    defineCPUMacros(Builder, "corei7");
     break;
   case CK_K6_2:
     Builder.defineMacro("__k6_2__");
@@ -1811,18 +1987,14 @@
     }
     // Fallthrough
   case CK_K6:
-    Builder.defineMacro("__k6");
-    Builder.defineMacro("__k6__");
-    Builder.defineMacro("__tune_k6__");
+    defineCPUMacros(Builder, "k6");
     break;
   case CK_Athlon:
   case CK_AthlonThunderbird:
   case CK_Athlon4:
   case CK_AthlonXP:
   case CK_AthlonMP:
-    Builder.defineMacro("__athlon");
-    Builder.defineMacro("__athlon__");
-    Builder.defineMacro("__tune_athlon__");
+    defineCPUMacros(Builder, "athlon");
     if (SSELevel !=3D NoSSE) {
       Builder.defineMacro("__athlon_sse__");
       Builder.defineMacro("__tune_athlon_sse__");
@@ -1836,19 +2008,22 @@
   case CK_Athlon64:
   case CK_Athlon64SSE3:
   case CK_AthlonFX:
-    Builder.defineMacro("__k8");
-    Builder.defineMacro("__k8__");
-    Builder.defineMacro("__tune_k8__");
+    defineCPUMacros(Builder, "k8");
     break;
   case CK_AMDFAM10:
-    Builder.defineMacro("__amdfam10");
-    Builder.defineMacro("__amdfam10__");
-    Builder.defineMacro("__tune_amdfam10__");
+    defineCPUMacros(Builder, "amdfam10");
+    break;
+  case CK_BTVER1:
+    defineCPUMacros(Builder, "btver1");
+    break;
+  case CK_BDVER1:
+    defineCPUMacros(Builder, "bdver1");
+    break;
+  case CK_BDVER2:
+    defineCPUMacros(Builder, "bdver2");
     break;
   case CK_Geode:
-    Builder.defineMacro("__geode");
-    Builder.defineMacro("__geode__");
-    Builder.defineMacro("__tune_geode__");
+    defineCPUMacros(Builder, "geode");
     break;
   }
=20
@@ -1864,11 +2039,27 @@
   if (HasAES)
     Builder.defineMacro("__AES__");
=20
-  if (HasAVX)
-    Builder.defineMacro("__AVX__");
+  if (HasLZCNT)
+    Builder.defineMacro("__LZCNT__");
+
+  if (HasBMI)
+    Builder.defineMacro("__BMI__");
+
+  if (HasBMI2)
+    Builder.defineMacro("__BMI2__");
+
+  if (HasPOPCNT)
+    Builder.defineMacro("__POPCNT__");
+
+  if (HasFMA4)
+    Builder.defineMacro("__FMA4__");
=20
   // Each case falls through to the previous one here.
   switch (SSELevel) {
+  case AVX2:
+    Builder.defineMacro("__AVX2__");
+  case AVX:
+    Builder.defineMacro("__AVX__");
   case SSE42:
     Builder.defineMacro("__SSE4_2__");
   case SSE41:
@@ -1889,6 +2080,8 @@
=20
   if (Opts.MicrosoftExt && PointerWidth =3D=3D 32) {
     switch (SSELevel) {
+    case AVX2:
+    case AVX:
     case SSE42:
     case SSE41:
     case SSSE3:
@@ -1917,6 +2110,30 @@
   }
 }
=20
+bool X86TargetInfo::hasFeature(StringRef Feature) const {
+  return llvm::StringSwitch<bool>(Feature)
+      .Case("aes", HasAES)
+      .Case("avx", SSELevel >=3D AVX)
+      .Case("avx2", SSELevel >=3D AVX2)
+      .Case("bmi", HasBMI)
+      .Case("bmi2", HasBMI2)
+      .Case("fma4", HasFMA4)
+      .Case("lzcnt", HasLZCNT)
+      .Case("mm3dnow", MMX3DNowLevel >=3D AMD3DNow)
+      .Case("mm3dnowa", MMX3DNowLevel >=3D AMD3DNowAthlon)
+      .Case("mmx", MMX3DNowLevel >=3D MMX)
+      .Case("popcnt", HasPOPCNT)
+      .Case("sse", SSELevel >=3D SSE1)
+      .Case("sse2", SSELevel >=3D SSE2)
+      .Case("sse3", SSELevel >=3D SSE3)
+      .Case("ssse3", SSELevel >=3D SSSE3)
+      .Case("sse41", SSELevel >=3D SSE41)
+      .Case("sse42", SSELevel >=3D SSE42)
+      .Case("x86", true)
+      .Case("x86_32", PointerWidth =3D=3D 32)
+      .Case("x86_64", PointerWidth =3D=3D 64)
+      .Default(false);
+}
=20
 bool
 X86TargetInfo::validateAsmConstraint(const char *&Name,
@@ -1959,7 +2176,6 @@
             // x86_64 instructions.
     return true;
   }
-  return false;
 }
=20
=20
@@ -1992,6 +2208,7 @@
     DoubleAlign =3D LongLongAlign =3D 32;
     LongDoubleWidth =3D 96;
     LongDoubleAlign =3D 32;
+    SuitableAlign =3D 128;
     DescriptionString =3D "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
                         "i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:=
128-"
                         "a0:0:64-f80:32:32-n8:16:32-S128";
@@ -2023,6 +2240,20 @@
 } // end anonymous namespace
=20
 namespace {
+class NetBSDI386TargetInfo : public NetBSDTargetInfo<X86_32TargetInfo> {
+public:
+  NetBSDI386TargetInfo(const std::string &triple) :
+    NetBSDTargetInfo<X86_32TargetInfo>(triple) {
+  }
+
+  virtual unsigned getFloatEvalMethod() const {
+    // NetBSD defaults to "double" rounding
+    return 1;
+  }
+};
+} // end anonymous namespace
+
+namespace {
 class OpenBSDI386TargetInfo : public OpenBSDTargetInfo<X86_32TargetInfo> {
 public:
   OpenBSDI386TargetInfo(const std::string& triple) :
@@ -2041,6 +2272,7 @@
     DarwinTargetInfo<X86_32TargetInfo>(triple) {
     LongDoubleWidth =3D 128;
     LongDoubleAlign =3D 128;
+    SuitableAlign =3D 128;
     SizeType =3D UnsignedLong;
     IntPtrType =3D SignedLong;
     DescriptionString =3D "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
@@ -2233,6 +2465,7 @@
     LongDoubleAlign =3D 128;
     LargeArrayMinWidth =3D 128;
     LargeArrayAlign =3D 128;
+    SuitableAlign =3D 128;
     IntMaxType =3D SignedLong;
     UIntMaxType =3D UnsignedLong;
     Int64Type =3D SignedLong;
@@ -2245,6 +2478,9 @@
     // Use fpret only for long double.
     RealTypeUsesObjCFPRet =3D (1 << TargetInfo::LongDouble);
=20
+    // Use fp2ret for _Complex long double.
+    ComplexLongDoubleUsesFP2Ret =3D true;
+
     // x86-64 has atomics up to 16 bytes.
     // FIXME: Once the backend is fixed, increase MaxAtomicInlineWidth to =
128
     // on CPUs with cmpxchg16b
@@ -2399,8 +2635,11 @@
   ARMTargetInfo(const std::string &TripleStr)
     : TargetInfo(TripleStr), ABI("aapcs-linux"), CPU("arm1136j-s")
   {
+    BigEndian =3D false;
     SizeType =3D UnsignedInt;
     PtrDiffType =3D SignedInt;
+    // AAPCS 7.1.1, ARM-Linux ABI 2.4: type of wchar_t is unsigned int.
+    WCharType =3D UnsignedInt;
=20
     // {} in inline assembly are neon specifiers, not assembly variant
     // specifiers.
@@ -2426,6 +2665,12 @@
     // ARM has atomics up to 8 bytes
     // FIXME: Set MaxAtomicInlineWidth if we have the feature v6e
     MaxAtomicPromoteWidth =3D 64;
+
+    // Do force alignment of members that follow zero length bitfields.  If
+    // the alignment of the zero-length bitfield is greater than the membe=
r=20
+    // that follows it, `bar', `bar' will be aligned as the  type of the=20
+    // zero length bitfield.
+    UseZeroLengthBitfieldAlignment =3D true;
   }
   virtual const char *getABI() const { return ABI.c_str(); }
   virtual bool setABI(const std::string &Name) {
@@ -2436,19 +2681,16 @@
     // FIXME: We need support for -meabi... we could just mangle it into t=
he
     // name.
     if (Name =3D=3D "apcs-gnu") {
-      DoubleAlign =3D LongLongAlign =3D LongDoubleAlign =3D 32;
+      DoubleAlign =3D LongLongAlign =3D LongDoubleAlign =3D SuitableAlign =
=3D 32;
       SizeType =3D UnsignedLong;
=20
+      // Revert to using SignedInt on apcs-gnu to comply with existing beh=
aviour.
+      WCharType =3D SignedInt;
+
       // Do not respect the alignment of bit-field types when laying out
       // structures. This corresponds to PCC_BITFIELD_TYPE_MATTERS in gcc.
       UseBitFieldTypeAlignment =3D false;
=20
-      /// Do force alignment of members that follow zero length bitfields.=
  If
-      /// the alignment of the zero-length bitfield is greater than the me=
mber=20
-      /// that follows it, `bar', `bar' will be aligned as the  type of th=
e=20
-      /// zero length bitfield.
-      UseZeroLengthBitfieldAlignment =3D true;
-
       /// gcc forces the alignment to 4 bytes, regardless of the type of t=
he
       /// zero length bitfield.  This corresponds to EMPTY_FIELD_BOUNDARY =
in
       /// gcc.
@@ -2485,10 +2727,11 @@
   }
=20
   virtual bool setFeatureEnabled(llvm::StringMap<bool> &Features,
-                                 const std::string &Name,
+                                 StringRef Name,
                                  bool Enabled) const {
     if (Name =3D=3D "soft-float" || Name =3D=3D "soft-float-abi" ||
-        Name =3D=3D "vfp2" || Name =3D=3D "vfp3" || Name =3D=3D "neon") {
+        Name =3D=3D "vfp2" || Name =3D=3D "vfp3" || Name =3D=3D "neon" || =
Name =3D=3D "d16" ||
+        Name =3D=3D "neonfp") {
       Features[Name] =3D Enabled;
     } else
       return false;
@@ -2522,6 +2765,15 @@
       Features.erase(it);
   }
=20
+  virtual bool hasFeature(StringRef Feature) const {
+    return llvm::StringSwitch<bool>(Feature)
+        .Case("arm", true)
+        .Case("softfloat", SoftFloat)
+        .Case("thumb", IsThumb)
+        .Case("neon", FPU =3D=3D NeonFPU && !SoftFloat &&=20
+              StringRef(getCPUDefineSuffix(CPU)).startswith("7"))   =20
+        .Default(false);
+  }
   static const char *getCPUDefineSuffix(StringRef Name) {
     return llvm::StringSwitch<const char*>(Name)
       .Cases("arm8", "arm810", "4")
@@ -2540,6 +2792,7 @@
       .Cases("arm1156t2-s", "arm1156t2f-s", "6T2")
       .Cases("cortex-a8", "cortex-a9", "7A")
       .Case("cortex-m3", "7M")
+      .Case("cortex-m4", "7M")
       .Case("cortex-m0", "6M")
       .Default(0);
   }
@@ -2606,6 +2859,7 @@
     Records =3D BuiltinInfo;
     NumRecords =3D clang::ARM::LastTSBuiltin-Builtin::FirstTSBuiltin;
   }
+  virtual bool isCLZForZeroUndef() const { return false; }
   virtual const char *getVAListDeclaration() const {
     return "typedef void* __builtin_va_list;";
   }
@@ -2729,7 +2983,6 @@
 };
 } // end anonymous namespace.
=20
-
 namespace {
 class DarwinARMTargetInfo :
   public DarwinTargetInfo<ARMTargetInfo> {
@@ -2750,6 +3003,154 @@
 };
 } // end anonymous namespace.
=20
+
+namespace {
+// Hexagon abstract base class
+class HexagonTargetInfo : public TargetInfo {
+  static const Builtin::Info BuiltinInfo[];
+  static const char * const GCCRegNames[];
+  static const TargetInfo::GCCRegAlias GCCRegAliases[];
+  std::string CPU;
+public:
+  HexagonTargetInfo(const std::string& triple) : TargetInfo(triple)  {
+    BigEndian =3D false;
+    DescriptionString =3D ("e-p:32:32:32-"
+                         "i64:64:64-i32:32:32-"
+                         "i16:16:16-i1:32:32-a:0:0");
+
+    // {} in inline assembly are packet specifiers, not assembly variant
+    // specifiers.
+    NoAsmVariants =3D true;
+  }
+
+  virtual void getTargetBuiltins(const Builtin::Info *&Records,
+                                 unsigned &NumRecords) const {
+    Records =3D BuiltinInfo;
+    NumRecords =3D clang::Hexagon::LastTSBuiltin-Builtin::FirstTSBuiltin;
+  }
+
+  virtual bool validateAsmConstraint(const char *&Name,
+                                     TargetInfo::ConstraintInfo &Info) con=
st {
+    return true;
+  }
+
+  virtual void getTargetDefines(const LangOptions &Opts,
+                                MacroBuilder &Builder) const;
+
+  virtual bool hasFeature(StringRef Feature) const {
+    return Feature =3D=3D "hexagon";
+  }
+ =20
+  virtual const char *getVAListDeclaration() const {
+    return "typedef char* __builtin_va_list;";
+  }
+  virtual void getGCCRegNames(const char * const *&Names,
+                              unsigned &NumNames) const;
+  virtual void getGCCRegAliases(const GCCRegAlias *&Aliases,
+                                unsigned &NumAliases) const;
+  virtual const char *getClobbers() const {
+    return "";
+  }
+
+  static const char *getHexagonCPUSuffix(StringRef Name) {
+    return llvm::StringSwitch<const char*>(Name)
+      .Case("hexagonv2", "2")
+      .Case("hexagonv3", "3")
+      .Case("hexagonv4", "4")
+      .Default(0);
+  }
+
+  virtual bool setCPU(const std::string &Name) {
+    if (!getHexagonCPUSuffix(Name))
+      return false;
+
+    CPU =3D Name;
+    return true;
+  }
+};
+
+void HexagonTargetInfo::getTargetDefines(const LangOptions &Opts,
+                                MacroBuilder &Builder) const {
+  Builder.defineMacro("qdsp6");
+  Builder.defineMacro("__qdsp6", "1");
+  Builder.defineMacro("__qdsp6__", "1");
+
+  Builder.defineMacro("hexagon");
+  Builder.defineMacro("__hexagon", "1");
+  Builder.defineMacro("__hexagon__", "1");
+
+  if(CPU =3D=3D "hexagonv1") {
+    Builder.defineMacro("__HEXAGON_V1__");
+    Builder.defineMacro("__HEXAGON_ARCH__", "1");
+    if(Opts.HexagonQdsp6Compat) {
+      Builder.defineMacro("__QDSP6_V1__");
+      Builder.defineMacro("__QDSP6_ARCH__", "1");
+    }
+  }
+  else if(CPU =3D=3D "hexagonv2") {
+    Builder.defineMacro("__HEXAGON_V2__");
+    Builder.defineMacro("__HEXAGON_ARCH__", "2");
+    if(Opts.HexagonQdsp6Compat) {
+      Builder.defineMacro("__QDSP6_V2__");
+      Builder.defineMacro("__QDSP6_ARCH__", "2");
+    }
+  }
+  else if(CPU =3D=3D "hexagonv3") {
+    Builder.defineMacro("__HEXAGON_V3__");
+    Builder.defineMacro("__HEXAGON_ARCH__", "3");
+    if(Opts.HexagonQdsp6Compat) {
+      Builder.defineMacro("__QDSP6_V3__");
+      Builder.defineMacro("__QDSP6_ARCH__", "3");
+    }
+  }
+  else if(CPU =3D=3D "hexagonv4") {
+    Builder.defineMacro("__HEXAGON_V4__");
+    Builder.defineMacro("__HEXAGON_ARCH__", "4");
+    if(Opts.HexagonQdsp6Compat) {
+      Builder.defineMacro("__QDSP6_V4__");
+      Builder.defineMacro("__QDSP6_ARCH__", "4");
+    }
+  }
+}
+
+const char * const HexagonTargetInfo::GCCRegNames[] =3D {
+  "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
+  "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
+  "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
+  "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
+  "p0", "p1", "p2", "p3",
+  "sa0", "lc0", "sa1", "lc1", "m0", "m1", "usr", "ugp"
+};
+
+void HexagonTargetInfo::getGCCRegNames(const char * const *&Names,
+                                   unsigned &NumNames) const {
+  Names =3D GCCRegNames;
+  NumNames =3D llvm::array_lengthof(GCCRegNames);
+}
+
+
+const TargetInfo::GCCRegAlias HexagonTargetInfo::GCCRegAliases[] =3D {
+  { { "sp" }, "r29" },
+  { { "fp" }, "r30" },
+  { { "lr" }, "r31" },
+ };
+
+void HexagonTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases,
+                                     unsigned &NumAliases) const {
+  Aliases =3D GCCRegAliases;
+  NumAliases =3D llvm::array_lengthof(GCCRegAliases);
+}
+
+
+const Builtin::Info HexagonTargetInfo::BuiltinInfo[] =3D {
+#define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES },
+#define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\
+                                              ALL_LANGUAGES },
+#include "clang/Basic/BuiltinsHexagon.def"
+};
+}
+
+
 namespace {
 class SparcV8TargetInfo : public TargetInfo {
   static const TargetInfo::GCCRegAlias GCCRegAliases[];
@@ -2758,11 +3159,12 @@
 public:
   SparcV8TargetInfo(const std::string& triple) : TargetInfo(triple) {
     // FIXME: Support Sparc quad-precision long double?
+    BigEndian =3D false;
     DescriptionString =3D "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
                         "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32";
   }
   virtual bool setFeatureEnabled(llvm::StringMap<bool> &Features,
-                                 const std::string &Name,
+                                 StringRef Name,
                                  bool Enabled) const {
     if (Name =3D=3D "soft-float")
       Features[Name] =3D Enabled;
@@ -2786,6 +3188,14 @@
     if (SoftFloat)
       Builder.defineMacro("SOFT_FLOAT", "1");
   }
+ =20
+  virtual bool hasFeature(StringRef Feature) const {
+    return llvm::StringSwitch<bool>(Feature)
+             .Case("softfloat", SoftFloat)
+             .Case("sparc", true)
+             .Default(false);
+  }
+ =20
   virtual void getTargetBuiltins(const Builtin::Info *&Records,
                                  unsigned &NumRecords) const {
     // FIXME: Implement!
@@ -2887,11 +3297,13 @@
     static const char * const GCCRegNames[];
   public:
     MSP430TargetInfo(const std::string& triple) : TargetInfo(triple) {
+      BigEndian =3D false;
       TLSSupported =3D false;
       IntWidth =3D 16; IntAlign =3D 16;
       LongWidth =3D 32; LongLongWidth =3D 64;
       LongAlign =3D LongLongAlign =3D 16;
       PointerWidth =3D 16; PointerAlign =3D 16;
+      SuitableAlign =3D 16;
       SizeType =3D UnsignedInt;
       IntMaxType =3D SignedLong;
       UIntMaxType =3D UnsignedLong;
@@ -2912,6 +3324,9 @@
       Records =3D 0;
       NumRecords =3D 0;
     }
+    virtual bool hasFeature(StringRef Feature) const {
+      return Feature =3D=3D "msp430";
+    }
     virtual void getGCCRegNames(const char * const *&Names,
                                 unsigned &NumNames) const;
     virtual void getGCCRegAliases(const GCCRegAlias *&Aliases,
@@ -2947,140 +3362,6 @@
   }
 }
=20
-
-namespace {
-  class SystemZTargetInfo : public TargetInfo {
-    static const char * const GCCRegNames[];
-  public:
-    SystemZTargetInfo(const std::string& triple) : TargetInfo(triple) {
-      TLSSupported =3D false;
-      IntWidth =3D IntAlign =3D 32;
-      LongWidth =3D LongLongWidth =3D LongAlign =3D LongLongAlign =3D 64;
-      PointerWidth =3D PointerAlign =3D 64;
-      DescriptionString =3D "E-p:64:64:64-i8:8:16-i16:16:16-i32:32:32-"
-      "i64:64:64-f32:32:32-f64:64:64-f128:128:128-a0:16:16-n32:64";
-   }
-    virtual void getTargetDefines(const LangOptions &Opts,
-                                  MacroBuilder &Builder) const {
-      Builder.defineMacro("__s390__");
-      Builder.defineMacro("__s390x__");
-    }
-    virtual void getTargetBuiltins(const Builtin::Info *&Records,
-                                   unsigned &NumRecords) const {
-      // FIXME: Implement.
-      Records =3D 0;
-      NumRecords =3D 0;
-    }
-
-    virtual void getGCCRegNames(const char * const *&Names,
-                                unsigned &NumNames) const;
-    virtual void getGCCRegAliases(const GCCRegAlias *&Aliases,
-                                  unsigned &NumAliases) const {
-      // No aliases.
-      Aliases =3D 0;
-      NumAliases =3D 0;
-    }
-    virtual bool validateAsmConstraint(const char *&Name,
-                                       TargetInfo::ConstraintInfo &info) c=
onst {
-      // FIXME: implement
-      return true;
-    }
-    virtual const char *getClobbers() const {
-      // FIXME: Is this really right?
-      return "";
-    }
-    virtual const char *getVAListDeclaration() const {
-      // FIXME: implement
-      return "typedef char* __builtin_va_list;";
-   }
-  };
-
-  const char * const SystemZTargetInfo::GCCRegNames[] =3D {
-    "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
-    "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
-  };
-
-  void SystemZTargetInfo::getGCCRegNames(const char * const *&Names,
-                                         unsigned &NumNames) const {
-    Names =3D GCCRegNames;
-    NumNames =3D llvm::array_lengthof(GCCRegNames);
-  }
-}
-
-namespace {
-  class BlackfinTargetInfo : public TargetInfo {
-    static const char * const GCCRegNames[];
-  public:
-    BlackfinTargetInfo(const std::string& triple) : TargetInfo(triple) {
-      TLSSupported =3D false;
-      DoubleAlign =3D 32;
-      LongLongAlign =3D 32;
-      LongDoubleAlign =3D 32;
-      DescriptionString =3D "e-p:32:32-i64:32-f64:32-n32";
-    }
-
-    virtual void getTargetDefines(const LangOptions &Opts,
-                                  MacroBuilder &Builder) const {
-      DefineStd(Builder, "bfin", Opts);
-      DefineStd(Builder, "BFIN", Opts);
-      Builder.defineMacro("__ADSPBLACKFIN__");
-      // FIXME: This one is really dependent on -mcpu
-      Builder.defineMacro("__ADSPLPBLACKFIN__");
-      // FIXME: Add cpu-dependent defines and __SILICON_REVISION__
-    }
-
-    virtual void getTargetBuiltins(const Builtin::Info *&Records,
-                                   unsigned &NumRecords) const {
-      // FIXME: Implement.
-      Records =3D 0;
-      NumRecords =3D 0;
-    }
-
-    virtual void getGCCRegNames(const char * const *&Names,
-                                unsigned &NumNames) const;
-
-    virtual void getGCCRegAliases(const GCCRegAlias *&Aliases,
-                                  unsigned &NumAliases) const {
-      // No aliases.
-      Aliases =3D 0;
-      NumAliases =3D 0;
-    }
-
-    virtual bool validateAsmConstraint(const char *&Name,
-                                       TargetInfo::ConstraintInfo &Info) c=
onst {
-      if (strchr("adzDWeABbvfcCtukxywZY", Name[0])) {
-        Info.setAllowsRegister();
-        return true;
-      }
-      return false;
-    }
-
-    virtual const char *getClobbers() const {
-      return "";
-    }
-
-    virtual const char *getVAListDeclaration() const {
-      return "typedef char* __builtin_va_list;";
-    }
-  };
-
-  const char * const BlackfinTargetInfo::GCCRegNames[] =3D {
-    "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
-    "p0", "p1", "p2", "p3", "p4", "p5", "sp", "fp",
-    "i0", "i1", "i2", "i3", "b0", "b1", "b2", "b3",
-    "l0", "l1", "l2", "l3", "m0", "m1", "m2", "m3",
-    "a0", "a1", "cc",
-    "rets", "reti", "retx", "retn", "rete", "astat", "seqstat", "usp",
-    "argp", "lt0", "lt1", "lc0", "lc1", "lb0", "lb1"
-  };
-
-  void BlackfinTargetInfo::getGCCRegNames(const char * const *&Names,
-                                          unsigned &NumNames) const {
-    Names =3D GCCRegNames;
-    NumNames =3D llvm::array_lengthof(GCCRegNames);
-  }
-}
-
 namespace {
=20
   // LLVM and Clang cannot be used directly to output native binaries for
@@ -3107,6 +3388,7 @@
       IntAlign =3D 32;
       LongAlign =3D LongLongAlign =3D 32;
       PointerAlign =3D 32;
+      SuitableAlign =3D 32;
       SizeType =3D UnsignedInt;
       IntMaxType =3D SignedLong;
       UIntMaxType =3D UnsignedLong;
@@ -3134,6 +3416,10 @@
       Builder.defineMacro("__TCE__");
       Builder.defineMacro("__TCE_V1__");
     }
+    virtual bool hasFeature(StringRef Feature) const {
+      return Feature =3D=3D "tce";
+    }
+   =20
     virtual void getTargetBuiltins(const Builtin::Info *&Records,
                                    unsigned &NumRecords) const {}
     virtual const char *getClobbers() const {
@@ -3156,14 +3442,22 @@
 namespace {
 class MipsTargetInfoBase : public TargetInfo {
   std::string CPU;
+  bool SoftFloat;
+  bool SingleFloat;
+
 protected:
   std::string ABI;
+
 public:
-  MipsTargetInfoBase(const std::string& triple, const std::string& ABIStr)
-    : TargetInfo(triple), ABI(ABIStr) {
-    SizeType =3D UnsignedInt;
-    PtrDiffType =3D SignedInt;
-  }
+  MipsTargetInfoBase(const std::string& triple,
+                     const std::string& ABIStr,
+                     const std::string& CPUStr)
+    : TargetInfo(triple),
+      CPU(CPUStr),
+      SoftFloat(false), SingleFloat(false),
+      ABI(ABIStr)
+  {}
+
   virtual const char *getABI() const { return ABI.c_str(); }
   virtual bool setABI(const std::string &Name) =3D 0;
   virtual bool setCPU(const std::string &Name) {
@@ -3174,28 +3468,50 @@
     Features[ABI] =3D true;
     Features[CPU] =3D true;
   }
+
   virtual void getArchDefines(const LangOptions &Opts,
-                              MacroBuilder &Builder) const =3D 0;
+                              MacroBuilder &Builder) const {
+    if (SoftFloat)
+      Builder.defineMacro("__mips_soft_float", Twine(1));
+    else if (SingleFloat)
+      Builder.defineMacro("__mips_single_float", Twine(1));
+    else if (!SoftFloat && !SingleFloat)
+      Builder.defineMacro("__mips_hard_float", Twine(1));
+    else
+      llvm_unreachable("Invalid float ABI for Mips.");
+
+    Builder.defineMacro("_MIPS_SZPTR", Twine(getPointerWidth(0)));
+    Builder.defineMacro("_MIPS_SZINT", Twine(getIntWidth()));
+    Builder.defineMacro("_MIPS_SZLONG", Twine(getLongWidth()));
+  }
+
   virtual void getTargetDefines(const LangOptions &Opts,
                                 MacroBuilder &Builder) const =3D 0;
   virtual void getTargetBuiltins(const Builtin::Info *&Records,
                                  unsigned &NumRecords) const {
     // FIXME: Implement!
   }
+  virtual bool hasFeature(StringRef Feature) const {
+    return Feature =3D=3D "mips";
+  }
   virtual const char *getVAListDeclaration() const {
     return "typedef void* __builtin_va_list;";
   }
   virtual void getGCCRegNames(const char * const *&Names,
                               unsigned &NumNames) const {
     static const char * const GCCRegNames[] =3D {
+      // CPU register names
+      // Must match second column of GCCRegAliases
       "$0",   "$1",   "$2",   "$3",   "$4",   "$5",   "$6",   "$7",
       "$8",   "$9",   "$10",  "$11",  "$12",  "$13",  "$14",  "$15",
       "$16",  "$17",  "$18",  "$19",  "$20",  "$21",  "$22",  "$23",
-      "$24",  "$25",  "$26",  "$27",  "$28",  "$sp",  "$fp",  "$31",
+      "$24",  "$25",  "$26",  "$27",  "$28",  "$29",  "$30",  "$31",
+      // Floating point register names
       "$f0",  "$f1",  "$f2",  "$f3",  "$f4",  "$f5",  "$f6",  "$f7",
       "$f8",  "$f9",  "$f10", "$f11", "$f12", "$f13", "$f14", "$f15",
       "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23",
       "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31",
+      // Hi/lo and condition register names
       "hi",   "lo",   "",     "$fcc0","$fcc1","$fcc2","$fcc3","$fcc4",
       "$fcc5","$fcc6","$fcc7"
     };
@@ -3208,26 +3524,64 @@
                                      TargetInfo::ConstraintInfo &Info) con=
st {
     switch (*Name) {
     default:
+      return false;
+       =20
     case 'r': // CPU registers.
     case 'd': // Equivalent to "r" unless generating MIPS16 code.
     case 'y': // Equivalent to "r", backwards compatibility only.
     case 'f': // floating-point registers.
+    case 'c': // $25 for indirect jumps
+    case 'l': // lo register
+    case 'x': // hilo register pair
       Info.setAllowsRegister();
       return true;
     }
+  }
+
+  virtual const char *getClobbers() const {
+    // FIXME: Implement!
+    return "";
+  }
+
+  virtual bool setFeatureEnabled(llvm::StringMap<bool> &Features,
+                                 StringRef Name,
+                                 bool Enabled) const {
+    if (Name =3D=3D "soft-float" || Name =3D=3D "single-float") {
+      Features[Name] =3D Enabled;
+      return true;
+    }
     return false;
   }
=20
-  virtual const char *getClobbers() const {
-    // FIXME: Implement!
-    return "";
+  virtual void HandleTargetFeatures(std::vector<std::string> &Features) {
+    SoftFloat =3D false;
+    SingleFloat =3D false;
+
+    for (std::vector<std::string>::iterator it =3D Features.begin(),
+         ie =3D Features.end(); it !=3D ie; ++it) {
+      if (*it =3D=3D "+single-float") {
+        SingleFloat =3D true;
+        break;
+      }
+
+      if (*it =3D=3D "+soft-float") {
+        SoftFloat =3D true;
+        // This option is front-end specific.
+        // Do not need to pass it to the backend.
+        Features.erase(it);
+        break;
+      }
+    }
   }
 };
=20
 class Mips32TargetInfoBase : public MipsTargetInfoBase {
 public:
   Mips32TargetInfoBase(const std::string& triple) :
-    MipsTargetInfoBase(triple, "o32") {}
+    MipsTargetInfoBase(triple, "o32", "mips32") {
+    SizeType =3D UnsignedInt;
+    PtrDiffType =3D SignedInt;
+  }
   virtual bool setABI(const std::string &Name) {
     if ((Name =3D=3D "o32") || (Name =3D=3D "eabi")) {
       ABI =3D Name;
@@ -3237,6 +3591,8 @@
   }
   virtual void getArchDefines(const LangOptions &Opts,
                               MacroBuilder &Builder) const {
+    MipsTargetInfoBase::getArchDefines(Opts, Builder);
+
     if (ABI =3D=3D "o32") {
       Builder.defineMacro("__mips_o32");
       Builder.defineMacro("_ABIO32", "1");
@@ -3278,8 +3634,8 @@
       { { "k0" }, "$26" },
       { { "k1" }, "$27" },
       { { "gp" }, "$28" },
-      { { "sp" }, "$29" },
-      { { "fp" }, "$30" },
+      { { "sp","$sp" }, "$29" },
+      { { "fp","$fp" }, "$30" },
       { { "ra" }, "$31" }
     };
     Aliases =3D GCCRegAliases;
@@ -3307,6 +3663,7 @@
 class Mips32ELTargetInfo : public Mips32TargetInfoBase {
 public:
   Mips32ELTargetInfo(const std::string& triple) : Mips32TargetInfoBase(tri=
ple) {
+    BigEndian =3D false;
     DescriptionString =3D "e-p:32:32:32-i1:8:8-i8:8:32-i16:16:32-i32:32:32=
-"
                         "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32";
   }
@@ -3325,17 +3682,32 @@
   virtual void SetDescriptionString(const std::string &Name) =3D 0;
 public:
   Mips64TargetInfoBase(const std::string& triple) :
-    MipsTargetInfoBase(triple, "n64") {}
+    MipsTargetInfoBase(triple, "n64", "mips64") {
+    LongWidth =3D LongAlign =3D 64;
+    PointerWidth =3D PointerAlign =3D 64;
+    LongDoubleWidth =3D LongDoubleAlign =3D 128;
+    LongDoubleFormat =3D &llvm::APFloat::IEEEquad;
+    SuitableAlign =3D 128;
+  }
   virtual bool setABI(const std::string &Name) {
     SetDescriptionString(Name);
-    if ((Name =3D=3D "n32") || (Name =3D=3D "n64")) {
-      ABI =3D Name;
-      return true;
-    } else
+
+    if (Name !=3D "n32" && Name !=3D "n64")
       return false;
+
+    ABI =3D Name;
+
+    if (Name =3D=3D "n32") {
+      LongWidth =3D LongAlign =3D 32;
+      PointerWidth =3D PointerAlign =3D 32;
+    }
+
+    return true;
   }
   virtual void getArchDefines(const LangOptions &Opts,
                               MacroBuilder &Builder) const {
+    MipsTargetInfoBase::getArchDefines(Opts, Builder);
+
     if (ABI =3D=3D "n32") {
       Builder.defineMacro("__mips_n32");
       Builder.defineMacro("_ABIN32", "2");
@@ -3380,8 +3752,8 @@
       { { "k0" }, "$26" },
       { { "k1" }, "$27" },
       { { "gp" }, "$28" },
-      { { "sp" }, "$29" },
-      { { "fp" }, "$30" },
+      { { "sp","$sp" }, "$29" },
+      { { "fp","$fp" }, "$30" },
       { { "ra" }, "$31" }
     };
     Aliases =3D GCCRegAliases;
@@ -3394,13 +3766,15 @@
     // Change DescriptionString only if ABI is n32. =20
     if (Name =3D=3D "n32")
       DescriptionString =3D "E-p:32:32:32-i1:8:8-i8:8:32-i16:16:32-i32:32:=
32-"
-                          "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32";  =
   =20
+                          "i64:64:64-f32:32:32-f64:64:64-f128:128:128-"
+                          "v64:64:64-n32";     =20
   }
 public:
   Mips64EBTargetInfo(const std::string& triple) : Mips64TargetInfoBase(tri=
ple) {
     // Default ABI is n64. =20
     DescriptionString =3D "E-p:64:64:64-i1:8:8-i8:8:32-i16:16:32-i32:32:32=
-"
-                        "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32";
+                        "i64:64:64-f32:32:32-f64:64:64-f128:128:128-"
+                        "v64:64:64-n32";
   }
   virtual void getTargetDefines(const LangOptions &Opts,
                                 MacroBuilder &Builder) const {
@@ -3418,13 +3792,16 @@
     // Change DescriptionString only if ABI is n32. =20
     if (Name =3D=3D "n32")
       DescriptionString =3D "e-p:32:32:32-i1:8:8-i8:8:32-i16:16:32-i32:32:=
32-"
-                          "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32";  =
   =20
+                          "i64:64:64-f32:32:32-f64:64:64-f128:128:128"
+                          "-v64:64:64-n32";     =20
   }
 public:
   Mips64ELTargetInfo(const std::string& triple) : Mips64TargetInfoBase(tri=
ple) {
-    // Default ABI is n64. =20
+    // Default ABI is n64.
+    BigEndian =3D false;
     DescriptionString =3D "e-p:64:64:64-i1:8:8-i8:8:32-i16:16:32-i32:32:32=
-"
-                        "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32";
+                        "i64:64:64-f32:32:32-f64:64:64-f128:128:128-"
+                        "v64:64:64-n32";
   }
   virtual void getTargetDefines(const LangOptions &Opts,
                                 MacroBuilder &Builder) const {
@@ -3442,6 +3819,7 @@
 class PNaClTargetInfo : public TargetInfo {
 public:
   PNaClTargetInfo(const std::string& triple) : TargetInfo(triple) {
+    BigEndian =3D false;
     this->UserLabelPrefix =3D "";
     this->LongAlign =3D 32;
     this->LongWidth =3D 32;
@@ -3477,9 +3855,13 @@
     if (Opts.CPlusPlus)
       Builder.defineMacro("_GNU_SOURCE");
=20
+    Builder.defineMacro("__LITTLE_ENDIAN__");
     Builder.defineMacro("__native_client__");
     getArchDefines(Opts, Builder);
   }
+  virtual bool hasFeature(StringRef Feature) const {
+    return Feature =3D=3D "pnacl";
+  }
   virtual void getTargetBuiltins(const Builtin::Info *&Records,
                                  unsigned &NumRecords) const {
   }
@@ -3526,6 +3908,9 @@
   default:
     return NULL;
=20
+  case llvm::Triple::hexagon:
+    return new HexagonTargetInfo(T);
+
   case llvm::Triple::arm:
   case llvm::Triple::thumb:
     if (Triple.isOSDarwin())
@@ -3544,11 +3929,6 @@
       return new ARMTargetInfo(T);
     }
=20
-  case llvm::Triple::bfin:
-    if ( os =3D=3D llvm::Triple::RTEMS )
-      return new RTEMSTargetInfo<BlackfinTargetInfo>(T);
-    return new BlackfinTargetInfo(T);
-
   case llvm::Triple::msp430:
     return new MSP430TargetInfo(T);
=20
@@ -3676,9 +4056,6 @@
   case llvm::Triple::cellspu:
     return new PS3SPUTargetInfo<PPC64TargetInfo>(T);
=20
-  case llvm::Triple::systemz:
-    return new SystemZTargetInfo(T);
-
   case llvm::Triple::tce:
     return new TCETargetInfo(T);
=20
@@ -3694,7 +4071,7 @@
     case llvm::Triple::DragonFly:
       return new DragonFlyBSDTargetInfo<X86_32TargetInfo>(T);
     case llvm::Triple::NetBSD:
-      return new NetBSDTargetInfo<X86_32TargetInfo>(T);
+      return new NetBSDI386TargetInfo(T);
     case llvm::Triple::OpenBSD:
       return new OpenBSDI386TargetInfo(T);
     case llvm::Triple::FreeBSD:
@@ -3753,7 +4130,7 @@
   llvm::Triple Triple(Opts.Triple);
=20
   // Construct the target
-  llvm::OwningPtr<TargetInfo> Target(AllocateTarget(Triple.str()));
+  OwningPtr<TargetInfo> Target(AllocateTarget(Triple.str()));
   if (!Target) {
     Diags.Report(diag::err_target_unknown_triple) << Triple.str();
     return 0;
@@ -3821,8 +4198,7 @@
   Opts.Features.clear();
   for (llvm::StringMap<bool>::const_iterator it =3D Features.begin(),
          ie =3D Features.end(); it !=3D ie; ++it)
-    Opts.Features.push_back(std::string(it->second ? "+" : "-") +
-                            it->first().str());
+    Opts.Features.push_back((it->second ? "+" : "-") + it->first().str());
   Target->HandleTargetFeatures(Opts.Features);
=20
   return Target.take();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Basi=
c/Version.cpp
--- a/head/contrib/llvm/tools/clang/lib/Basic/Version.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Basic/Version.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -19,7 +19,7 @@
 #include <cstdlib>
=20
 namespace clang {
- =20
+
 std::string getClangRepositoryPath() {
 #if defined(CLANG_REPOSITORY_STRING)
   return CLANG_REPOSITORY_STRING;
@@ -32,7 +32,7 @@
=20
   // If the SVN_REPOSITORY is empty, try to use the SVN keyword. This help=
s us
   // pick up a tag in an SVN export, for example.
-  static StringRef SVNRepository("$URL: http://llvm.org/svn/llvm-project/c=
fe/tags/RELEASE_30/final/lib/Basic/Version.cpp $");
+  static StringRef SVNRepository("$URL: http://llvm.org/svn/llvm-project/c=
fe/trunk/lib/Basic/Version.cpp $");
   if (URL.empty()) {
     URL =3D SVNRepository.slice(SVNRepository.find(':'),
                               SVNRepository.find("/lib/Basic"));
@@ -50,6 +50,23 @@
 #endif
 }
=20
+std::string getLLVMRepositoryPath() {
+#ifdef LLVM_REPOSITORY
+  StringRef URL(LLVM_REPOSITORY);
+#else
+  StringRef URL("");
+#endif
+
+  // Trim path prefix off, assuming path came from standard llvm path.
+  // Leave "llvm/" prefix to distinguish the following llvm revision from =
the
+  // clang revision.
+  size_t Start =3D URL.find("llvm/");
+  if (Start !=3D StringRef::npos)
+    URL =3D URL.substr(Start);
+
+  return URL;
+}
+
 std::string getClangRevision() {
 #ifdef SVN_REVISION
   return SVN_REVISION;
@@ -58,29 +75,50 @@
 #endif
 }
=20
+std::string getLLVMRevision() {
+#ifdef LLVM_REVISION
+  return LLVM_REVISION;
+#else
+  return "";
+#endif
+}
+
 std::string getClangFullRepositoryVersion() {
   std::string buf;
   llvm::raw_string_ostream OS(buf);
   std::string Path =3D getClangRepositoryPath();
   std::string Revision =3D getClangRevision();
-  if (!Path.empty())
-    OS << Path;
-  if (!Revision.empty()) {
+  if (!Path.empty() || !Revision.empty()) {
+    OS << '(';
     if (!Path.empty())
-      OS << ' ';
-    OS << Revision;
+      OS << Path;
+    if (!Revision.empty()) {
+      if (!Path.empty())
+        OS << ' ';
+      OS << Revision;
+    }
+    OS << ')';
+  } =20
+  // Support LLVM in a separate repository.
+  std::string LLVMRev =3D getLLVMRevision();
+  if (!LLVMRev.empty() && LLVMRev !=3D Revision) {
+    OS << " (";   =20
+    std::string LLVMRepo =3D getLLVMRepositoryPath();
+    if (!LLVMRepo.empty())
+      OS << LLVMRepo << ' ';
+    OS << LLVMRev << ')';
   }
   return OS.str();
 }
- =20
+
 std::string getClangFullVersion() {
   std::string buf;
   llvm::raw_string_ostream OS(buf);
 #ifdef CLANG_VENDOR
   OS << CLANG_VENDOR;
 #endif
-  OS << "clang version " CLANG_VERSION_STRING " ("
-     << getClangFullRepositoryVersion() << ')';
+  OS << "clang version " CLANG_VERSION_STRING " "
+     << getClangFullRepositoryVersion();
=20
 #ifdef CLANG_VENDOR_SUFFIX
   OS << CLANG_VENDOR_SUFFIX;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/ABIInfo.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/ABIInfo.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/ABIInfo.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -42,7 +42,8 @@
       /// type, or by coercing to another specified type stored in
       /// 'CoerceToType').  If an offset is specified (in UIntData), then =
the
       /// argument passed is offset by some number of bytes in the memory
-      /// representation.
+      /// representation. A dummy argument is emitted before the real argu=
ment
+      /// if the specified type stored in "PaddingType" is not zero.
       Direct,
=20
       /// Extend - Valid only for integer argument types. Same as 'direct'
@@ -69,19 +70,22 @@
   private:
     Kind TheKind;
     llvm::Type *TypeData;
+    llvm::Type *PaddingType; // Currently allowed only for Direct.
     unsigned UIntData;
     bool BoolData0;
     bool BoolData1;
=20
-    ABIArgInfo(Kind K, llvm::Type *TD=3D0,
-               unsigned UI=3D0, bool B0 =3D false, bool B1 =3D false)
-      : TheKind(K), TypeData(TD), UIntData(UI), BoolData0(B0), BoolData1(B=
1) {}
+    ABIArgInfo(Kind K, llvm::Type *TD=3D0, unsigned UI=3D0,
+               bool B0 =3D false, bool B1 =3D false, llvm::Type* P =3D 0)
+      : TheKind(K), TypeData(TD), PaddingType(P), UIntData(UI), BoolData0(=
B0),
+        BoolData1(B1) {}
=20
   public:
     ABIArgInfo() : TheKind(Direct), TypeData(0), UIntData(0) {}
=20
-    static ABIArgInfo getDirect(llvm::Type *T =3D 0, unsigned Offset =3D 0=
) {
-      return ABIArgInfo(Direct, T, Offset);
+    static ABIArgInfo getDirect(llvm::Type *T =3D 0, unsigned Offset =3D 0,
+                                llvm::Type *Padding =3D 0) {
+      return ABIArgInfo(Direct, T, Offset, false, false, Padding);
     }
     static ABIArgInfo getExtend(llvm::Type *T =3D 0) {
       return ABIArgInfo(Extend, T, 0);
@@ -113,6 +117,11 @@
       assert((isDirect() || isExtend()) && "Not a direct or extend kind");
       return UIntData;
     }
+
+    llvm::Type *getPaddingType() const {
+      return PaddingType;
+    }
+
     llvm::Type *getCoerceToType() const {
       assert(canHaveCoerceToType() && "Invalid kind!");
       return TypeData;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/BackendUtil.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/BackendUtil.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -43,7 +43,7 @@
 class EmitAssemblyHelper {
   DiagnosticsEngine &Diags;
   const CodeGenOptions &CodeGenOpts;
-  const TargetOptions &TargetOpts;
+  const clang::TargetOptions &TargetOpts;
   const LangOptions &LangOpts;
   Module *TheModule;
=20
@@ -87,7 +87,8 @@
=20
 public:
   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
-                     const CodeGenOptions &CGOpts, const TargetOptions &TO=
pts,
+                     const CodeGenOptions &CGOpts,
+                     const clang::TargetOptions &TOpts,
                      const LangOptions &LOpts,
                      Module *M)
     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpt=
s),
@@ -105,6 +106,11 @@
=20
 }
=20
+static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassMa=
nagerBase &PM) {
+  if (Builder.OptLevel > 0)
+    PM.add(createObjCARCAPElimPass());
+}
+
 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassMa=
nagerBase &PM) {
   if (Builder.OptLevel > 0)
     PM.add(createObjCARCExpandPass());
@@ -115,6 +121,16 @@
     PM.add(createObjCARCOptPass());
 }
=20
+static void addAddressSanitizerPass(const PassManagerBuilder &Builder,
+                                    PassManagerBase &PM) {
+  PM.add(createAddressSanitizerPass());
+}
+
+static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
+                                   PassManagerBase &PM) {
+  PM.add(createThreadSanitizerPass());
+}
+
 void EmitAssemblyHelper::CreatePasses() {
   unsigned OptLevel =3D CodeGenOpts.OptimizationLevel;
   CodeGenOptions::InliningMethod Inlining =3D CodeGenOpts.Inlining;
@@ -138,10 +154,26 @@
   if (LangOpts.ObjCAutoRefCount) {
     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
                            addObjCARCExpandPass);
+    PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
+                           addObjCARCAPElimPass);
     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
                            addObjCARCOptPass);
   }
- =20
+
+  if (LangOpts.AddressSanitizer) {
+    PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
+                           addAddressSanitizerPass);
+    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
+                           addAddressSanitizerPass);
+  }
+
+  if (LangOpts.ThreadSanitizer) {
+    PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
+                           addThreadSanitizerPass);
+    PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
+                           addThreadSanitizerPass);
+  }
+
   // Figure out TargetLibraryInfo.
   Triple TargetTriple(TheModule->getTargetTriple());
   PMBuilder.LibraryInfo =3D new TargetLibraryInfo(TargetTriple);
@@ -164,7 +196,11 @@
   }
   case CodeGenOptions::OnlyAlwaysInlining:
     // Respect always_inline.
-    PMBuilder.Inliner =3D createAlwaysInlinerPass();
+    if (OptLevel =3D=3D 0)
+      // Do not insert lifetime intrinsics at -O0.
+      PMBuilder.Inliner =3D createAlwaysInlinerPass(false);
+    else
+      PMBuilder.Inliner =3D createAlwaysInlinerPass();
     break;
   }
=20
@@ -206,35 +242,6 @@
   // being gross, this is also totally broken if we ever care about
   // concurrency.
=20
-  // Set frame pointer elimination mode.
-  if (!CodeGenOpts.DisableFPElim) {
-    llvm::NoFramePointerElim =3D false;
-    llvm::NoFramePointerElimNonLeaf =3D false;
-  } else if (CodeGenOpts.OmitLeafFramePointer) {
-    llvm::NoFramePointerElim =3D false;
-    llvm::NoFramePointerElimNonLeaf =3D true;
-  } else {
-    llvm::NoFramePointerElim =3D true;
-    llvm::NoFramePointerElimNonLeaf =3D true;
-  }
-
-  // Set float ABI type.
-  if (CodeGenOpts.FloatABI =3D=3D "soft" || CodeGenOpts.FloatABI =3D=3D "s=
oftfp")
-    llvm::FloatABIType =3D llvm::FloatABI::Soft;
-  else if (CodeGenOpts.FloatABI =3D=3D "hard")
-    llvm::FloatABIType =3D llvm::FloatABI::Hard;
-  else {
-    assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
-    llvm::FloatABIType =3D llvm::FloatABI::Default;
-  }
-
-  llvm::LessPreciseFPMADOption =3D CodeGenOpts.LessPreciseFPMAD;
-  llvm::NoInfsFPMath =3D CodeGenOpts.NoInfsFPMath;
-  llvm::NoNaNsFPMath =3D CodeGenOpts.NoNaNsFPMath;
-  NoZerosInBSS =3D CodeGenOpts.NoZeroInitializedInBSS;
-  llvm::UnsafeFPMath =3D CodeGenOpts.UnsafeFPMath;
-  llvm::UseSoftFloat =3D CodeGenOpts.SoftFloat;
-
   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
=20
   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
@@ -255,7 +262,7 @@
     CM =3D llvm::CodeModel::Default;
   }
=20
-  std::vector<const char *> BackendArgs;
+  SmallVector<const char *, 16> BackendArgs;
   BackendArgs.push_back("clang"); // Fake program name.
   if (!CodeGenOpts.DebugPass.empty()) {
     BackendArgs.push_back("-debug-pass");
@@ -273,7 +280,7 @@
     BackendArgs.push_back("-global-merge=3Dfalse");
   BackendArgs.push_back(0);
   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
-                                    const_cast<char **>(&BackendArgs[0]));
+                                    BackendArgs.data());
=20
   std::string FeaturesStr;
   if (TargetOpts.Features.size()) {
@@ -296,8 +303,52 @@
     RM =3D llvm::Reloc::DynamicNoPIC;
   }
=20
+  CodeGenOpt::Level OptLevel =3D CodeGenOpt::Default;
+  switch (CodeGenOpts.OptimizationLevel) {
+  default: break;
+  case 0: OptLevel =3D CodeGenOpt::None; break;
+  case 3: OptLevel =3D CodeGenOpt::Aggressive; break;
+  }
+
+  llvm::TargetOptions Options;
+
+  // Set frame pointer elimination mode.
+  if (!CodeGenOpts.DisableFPElim) {
+    Options.NoFramePointerElim =3D false;
+    Options.NoFramePointerElimNonLeaf =3D false;
+  } else if (CodeGenOpts.OmitLeafFramePointer) {
+    Options.NoFramePointerElim =3D false;
+    Options.NoFramePointerElimNonLeaf =3D true;
+  } else {
+    Options.NoFramePointerElim =3D true;
+    Options.NoFramePointerElimNonLeaf =3D true;
+  }
+
+  // Set float ABI type.
+  if (CodeGenOpts.FloatABI =3D=3D "soft" || CodeGenOpts.FloatABI =3D=3D "s=
oftfp")
+    Options.FloatABIType =3D llvm::FloatABI::Soft;
+  else if (CodeGenOpts.FloatABI =3D=3D "hard")
+    Options.FloatABIType =3D llvm::FloatABI::Hard;
+  else {
+    assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
+    Options.FloatABIType =3D llvm::FloatABI::Default;
+  }
+
+  Options.LessPreciseFPMADOption =3D CodeGenOpts.LessPreciseFPMAD;
+  Options.NoInfsFPMath =3D CodeGenOpts.NoInfsFPMath;
+  Options.NoNaNsFPMath =3D CodeGenOpts.NoNaNsFPMath;
+  Options.NoZerosInBSS =3D CodeGenOpts.NoZeroInitializedInBSS;
+  Options.UnsafeFPMath =3D CodeGenOpts.UnsafeFPMath;
+  Options.UseSoftFloat =3D CodeGenOpts.SoftFloat;
+  Options.StackAlignmentOverride =3D CodeGenOpts.StackAlignment;
+  Options.RealignStack =3D CodeGenOpts.StackRealignment;
+  Options.DisableTailCalls =3D CodeGenOpts.DisableTailCalls;
+  Options.TrapFuncName =3D CodeGenOpts.TrapFuncName;
+  Options.PositionIndependentExecutable =3D LangOpts.PIELevel !=3D 0;
+
   TargetMachine *TM =3D TheTarget->createTargetMachine(Triple, TargetOpts.=
CPU,
-                                                     FeaturesStr, RM, CM);
+                                                     FeaturesStr, Options,
+                                                     RM, CM, OptLevel);
=20
   if (CodeGenOpts.RelaxAll)
     TM->setMCRelaxAll(true);
@@ -305,18 +356,19 @@
     TM->setMCSaveTempLabels(true);
   if (CodeGenOpts.NoDwarf2CFIAsm)
     TM->setMCUseCFI(false);
+  if (!CodeGenOpts.NoDwarfDirectoryAsm)
+    TM->setMCUseDwarfDirectory(true);
   if (CodeGenOpts.NoExecStack)
     TM->setMCNoExecStack(true);
=20
   // Create the code generator passes.
   PassManager *PM =3D getCodeGenPasses();
-  CodeGenOpt::Level OptLevel =3D CodeGenOpt::Default;
=20
-  switch (CodeGenOpts.OptimizationLevel) {
-  default: break;
-  case 0: OptLevel =3D CodeGenOpt::None; break;
-  case 3: OptLevel =3D CodeGenOpt::Aggressive; break;
-  }
+  // Add LibraryInfo.
+  TargetLibraryInfo *TLI =3D new TargetLibraryInfo();
+  if (!CodeGenOpts.SimplifyLibCalls)
+    TLI->disableAllFunctions();
+  PM->add(TLI);
=20
   // Normal mode, emit a .s or .o file by running the code generator. Note,
   // this also adds codegenerator level optimization passes.
@@ -331,10 +383,11 @@
   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
   // "codegen" passes so that it isn't run multiple times when there is
   // inlining happening.
-  if (LangOpts.ObjCAutoRefCount)
+  if (LangOpts.ObjCAutoRefCount &&
+      CodeGenOpts.OptimizationLevel > 0)
     PM->add(createObjCARCContractPass());
=20
-  if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
+  if (TM->addPassesToEmitFile(*PM, OS, CGFT,
                               /*DisableVerify=3D*/!CodeGenOpts.VerifyModul=
e)) {
     Diags.Report(diag::err_fe_unable_to_interface_with_target);
     return false;
@@ -397,7 +450,7 @@
=20
 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
                               const CodeGenOptions &CGOpts,
-                              const TargetOptions &TOpts,
+                              const clang::TargetOptions &TOpts,
                               const LangOptions &LOpts,
                               Module *M,
                               BackendAction Action, raw_ostream *OS) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGBlocks.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -25,13 +25,15 @@
 using namespace clang;
 using namespace CodeGen;
=20
-CGBlockInfo::CGBlockInfo(const BlockExpr *blockExpr, const char *N)
-  : Name(N), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(false),
-    HasCXXObject(false), UsesStret(false), StructureType(0), Block(blockEx=
pr) {
+CGBlockInfo::CGBlockInfo(const BlockDecl *block, StringRef name)
+  : Name(name), CXXThisIndex(0), CanBeGlobal(false), NeedsCopyDispose(fals=
e),
+    HasCXXObject(false), UsesStret(false), StructureType(0), Block(block),
+    DominatingIP(0) {
    =20
-  // Skip asm prefix, if any.
-  if (Name && Name[0] =3D=3D '\01')
-    ++Name;
+  // Skip asm prefix, if any.  'name' is usually taken directly from
+  // the mangled name of the enclosing function.
+  if (!name.empty() && name[0] =3D=3D '\01')
+    name =3D name.substr(1);
 }
=20
 // Anchor the vtable to this translation unit.
@@ -90,7 +92,7 @@
                           CGM.GetAddrOfConstantCString(typeAtEncoding), i8=
p));
  =20
   // GC layout.
-  if (C.getLangOptions().ObjC1)
+  if (C.getLangOpts().ObjC1)
     elements.push_back(CGM.getObjCRuntime().BuildGCBlockLayout(CGM, blockI=
nfo));
   else
     elements.push_back(llvm::Constant::getNullValue(i8p));
@@ -213,6 +215,7 @@
 /// acceptable because we make no promises about address stability of
 /// captured variables.
 static llvm::Constant *tryCaptureAsConstant(CodeGenModule &CGM,
+                                            CodeGenFunction *CGF,
                                             const VarDecl *var) {
   QualType type =3D var->getType();
=20
@@ -224,7 +227,7 @@
   //   Except that any class member declared mutable can be
   //   modified, any attempt to modify a const object during its
   //   lifetime results in undefined behavior.
-  if (CGM.getLangOptions().CPlusPlus && !isSafeForCXXConstantCapture(type))
+  if (CGM.getLangOpts().CPlusPlus && !isSafeForCXXConstantCapture(type))
     return 0;
=20
   // If the variable doesn't have any initializer (shouldn't this be
@@ -233,7 +236,7 @@
   const Expr *init =3D var->getInit();
   if (!init) return 0;
=20
-  return CGM.EmitConstantExpr(init, var->getType());
+  return CGM.EmitConstantInit(*var, CGF);
 }
=20
 /// Get the low bit of a nonzero character count.  This is the
@@ -276,7 +279,8 @@
=20
 /// Compute the layout of the given block.  Attempts to lay the block
 /// out with minimal space requirements.
-static void computeBlockInfo(CodeGenModule &CGM, CGBlockInfo &info) {
+static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
+                             CGBlockInfo &info) {
   ASTContext &C =3D CGM.getContext();
   const BlockDecl *block =3D info.getBlockDecl();
=20
@@ -340,7 +344,7 @@
=20
     // Otherwise, build a layout chunk with the size and alignment of
     // the declaration.
-    if (llvm::Constant *constant =3D tryCaptureAsConstant(CGM, variable)) {
+    if (llvm::Constant *constant =3D tryCaptureAsConstant(CGM, CGF, variab=
le)) {
       info.Captures[variable] =3D CGBlockInfo::Capture::makeConstant(const=
ant);
       continue;
     }
@@ -370,7 +374,7 @@
       info.HasCXXObject =3D true;
=20
     // And so do types with destructors.
-    } else if (CGM.getLangOptions().CPlusPlus) {
+    } else if (CGM.getLangOpts().CPlusPlus) {
       if (const CXXRecordDecl *record =3D
             variable->getType()->getAsCXXRecordDecl()) {
         if (!record->hasTrivialDestructor()) {
@@ -380,13 +384,15 @@
       }
     }
=20
-    CharUnits size =3D C.getTypeSizeInChars(variable->getType());
+    QualType VT =3D variable->getType();
+    CharUnits size =3D C.getTypeSizeInChars(VT);
     CharUnits align =3D C.getDeclAlign(variable);
+   =20
     maxFieldAlign =3D std::max(maxFieldAlign, align);
=20
     llvm::Type *llvmType =3D
-      CGM.getTypes().ConvertTypeForMem(variable->getType());
-
+      CGM.getTypes().ConvertTypeForMem(VT);
+   =20
     layout.push_back(BlockLayoutChunk(align, size, &*ci, llvmType));
   }
=20
@@ -481,18 +487,146 @@
     llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
 }
=20
+/// Enter the scope of a block.  This should be run at the entrance to
+/// a full-expression so that the block's cleanups are pushed at the
+/// right place in the stack.
+static void enterBlockScope(CodeGenFunction &CGF, BlockDecl *block) {
+  // Allocate the block info and place it at the head of the list.
+  CGBlockInfo &blockInfo =3D
+    *new CGBlockInfo(block, CGF.CurFn->getName());
+  blockInfo.NextBlockInfo =3D CGF.FirstBlockInfo;
+  CGF.FirstBlockInfo =3D &blockInfo;
+
+  // Compute information about the layout, etc., of this block,
+  // pushing cleanups as necessary.
+  computeBlockInfo(CGF.CGM, &CGF, blockInfo);
+
+  // Nothing else to do if it can be global.
+  if (blockInfo.CanBeGlobal) return;
+
+  // Make the allocation for the block.
+  blockInfo.Address =3D
+    CGF.CreateTempAlloca(blockInfo.StructureType, "block");
+  blockInfo.Address->setAlignment(blockInfo.BlockAlign.getQuantity());
+
+  // If there are cleanups to emit, enter them (but inactive).
+  if (!blockInfo.NeedsCopyDispose) return;
+
+  // Walk through the captures (in order) and find the ones not
+  // captured by constant.
+  for (BlockDecl::capture_const_iterator ci =3D block->capture_begin(),
+         ce =3D block->capture_end(); ci !=3D ce; ++ci) {
+    // Ignore __block captures; there's nothing special in the
+    // on-stack block that we need to do for them.
+    if (ci->isByRef()) continue;
+
+    // Ignore variables that are constant-captured.
+    const VarDecl *variable =3D ci->getVariable();
+    CGBlockInfo::Capture &capture =3D blockInfo.getCapture(variable);
+    if (capture.isConstant()) continue;
+
+    // Ignore objects that aren't destructed.
+    QualType::DestructionKind dtorKind =3D
+      variable->getType().isDestructedType();
+    if (dtorKind =3D=3D QualType::DK_none) continue;
+
+    CodeGenFunction::Destroyer *destroyer;
+
+    // Block captures count as local values and have imprecise semantics.
+    // They also can't be arrays, so need to worry about that.
+    if (dtorKind =3D=3D QualType::DK_objc_strong_lifetime) {
+      destroyer =3D CodeGenFunction::destroyARCStrongImprecise;
+    } else {
+      destroyer =3D CGF.getDestroyer(dtorKind);
+    }
+
+    // GEP down to the address.
+    llvm::Value *addr =3D CGF.Builder.CreateStructGEP(blockInfo.Address,
+                                                    capture.getIndex());
+
+    // We can use that GEP as the dominating IP.
+    if (!blockInfo.DominatingIP)
+      blockInfo.DominatingIP =3D cast<llvm::Instruction>(addr);
+
+    CleanupKind cleanupKind =3D InactiveNormalCleanup;
+    bool useArrayEHCleanup =3D CGF.needsEHCleanup(dtorKind);
+    if (useArrayEHCleanup)=20
+      cleanupKind =3D InactiveNormalAndEHCleanup;
+
+    CGF.pushDestroy(cleanupKind, addr, variable->getType(),
+                    destroyer, useArrayEHCleanup);
+
+    // Remember where that cleanup was.
+    capture.setCleanup(CGF.EHStack.stable_begin());
+  }
+}
+
+/// Enter a full-expression with a non-trivial number of objects to
+/// clean up.  This is in this file because, at the moment, the only
+/// kind of cleanup object is a BlockDecl*.
+void CodeGenFunction::enterNonTrivialFullExpression(const ExprWithCleanups=
 *E) {
+  assert(E->getNumObjects() !=3D 0);
+  ArrayRef<ExprWithCleanups::CleanupObject> cleanups =3D E->getObjects();
+  for (ArrayRef<ExprWithCleanups::CleanupObject>::iterator
+         i =3D cleanups.begin(), e =3D cleanups.end(); i !=3D e; ++i) {
+    enterBlockScope(*this, *i);
+  }
+}
+
+/// Find the layout for the given block in a linked list and remove it.
+static CGBlockInfo *findAndRemoveBlockInfo(CGBlockInfo **head,
+                                           const BlockDecl *block) {
+  while (true) {
+    assert(head && *head);
+    CGBlockInfo *cur =3D *head;
+
+    // If this is the block we're looking for, splice it out of the list.
+    if (cur->getBlockDecl() =3D=3D block) {
+      *head =3D cur->NextBlockInfo;
+      return cur;
+    }
+
+    head =3D &cur->NextBlockInfo;
+  }
+}
+
+/// Destroy a chain of block layouts.
+void CodeGenFunction::destroyBlockInfos(CGBlockInfo *head) {
+  assert(head && "destroying an empty chain");
+  do {
+    CGBlockInfo *cur =3D head;
+    head =3D cur->NextBlockInfo;
+    delete cur;
+  } while (head !=3D 0);
+}
+
 /// Emit a block literal expression in the current function.
 llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr)=
 {
-  std::string Name =3D CurFn->getName();
-  CGBlockInfo blockInfo(blockExpr, Name.c_str());
+  // If the block has no captures, we won't have a pre-computed
+  // layout for it.
+  if (!blockExpr->getBlockDecl()->hasCaptures()) {
+    CGBlockInfo blockInfo(blockExpr->getBlockDecl(), CurFn->getName());
+    computeBlockInfo(CGM, this, blockInfo);
+    blockInfo.BlockExpression =3D blockExpr;
+    return EmitBlockLiteral(blockInfo);
+  }
=20
-  // Compute information about the layout, etc., of this block.
-  computeBlockInfo(CGM, blockInfo);
+  // Find the block info for this block and take ownership of it.
+  OwningPtr<CGBlockInfo> blockInfo;
+  blockInfo.reset(findAndRemoveBlockInfo(&FirstBlockInfo,
+                                         blockExpr->getBlockDecl()));
=20
-  // Using that metadata, generate the actual block function.
+  blockInfo->BlockExpression =3D blockExpr;
+  return EmitBlockLiteral(*blockInfo);
+}
+
+llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInf=
o) {
+  // Using the computed layout, generate the actual block function.
+  bool isLambdaConv =3D blockInfo.getBlockDecl()->isConversionFromLambda();
   llvm::Constant *blockFn
     =3D CodeGenFunction(CGM).GenerateBlockFunction(CurGD, blockInfo,
-                                                 CurFuncDecl, LocalDeclMap=
);
+                                                 CurFuncDecl, LocalDeclMap,
+                                                 isLambdaConv);
   blockFn =3D llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
=20
   // If there is nothing to capture, we can emit this as a global block.
@@ -507,11 +641,8 @@
   // Build the block descriptor.
   llvm::Constant *descriptor =3D buildBlockDescriptor(CGM, blockInfo);
=20
-  llvm::Type *intTy =3D ConvertType(getContext().IntTy);
-
-  llvm::AllocaInst *blockAddr =3D
-    CreateTempAlloca(blockInfo.StructureType, "block");
-  blockAddr->setAlignment(blockInfo.BlockAlign.getQuantity());
+  llvm::AllocaInst *blockAddr =3D blockInfo.Address;
+  assert(blockAddr && "block has no address!");
=20
   // Compute the initial on-stack block flags.
   BlockFlags flags =3D BLOCK_HAS_SIGNATURE;
@@ -521,9 +652,9 @@
=20
   // Initialize the block literal.
   Builder.CreateStore(isa, Builder.CreateStructGEP(blockAddr, 0, "block.is=
a"));
-  Builder.CreateStore(llvm::ConstantInt::get(intTy, flags.getBitMask()),
+  Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
                       Builder.CreateStructGEP(blockAddr, 1, "block.flags")=
);
-  Builder.CreateStore(llvm::ConstantInt::get(intTy, 0),
+  Builder.CreateStore(llvm::ConstantInt::get(IntTy, 0),
                       Builder.CreateStructGEP(blockAddr, 2, "block.reserve=
d"));
   Builder.CreateStore(blockFn, Builder.CreateStructGEP(blockAddr, 3,
                                                        "block.invoke"));
@@ -570,6 +701,10 @@
       src =3D Builder.CreateStructGEP(LoadBlockStruct(),
                                     enclosingCapture.getIndex(),
                                     "block.capture.addr");
+    } else if (blockDecl->isConversionFromLambda()) {
+      // The lambda capture in a lambda's conversion-to-block-pointer is
+      // special; we'll simply emit it directly.
+      src =3D 0;
     } else {
       // This is a [[type]]*.
       src =3D LocalDeclMap[variable];
@@ -591,7 +726,19 @@
=20
     // If we have a copy constructor, evaluate that into the block field.
     } else if (const Expr *copyExpr =3D ci->getCopyExpr()) {
-      EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
+      if (blockDecl->isConversionFromLambda()) {
+        // If we have a lambda conversion, emit the expression
+        // directly into the block instead.
+        CharUnits Align =3D getContext().getTypeAlignInChars(type);
+        AggValueSlot Slot =3D
+            AggValueSlot::forAddr(blockField, Align, Qualifiers(),
+                                  AggValueSlot::IsDestructed,
+                                  AggValueSlot::DoesNotNeedGCBarriers,
+                                  AggValueSlot::IsNotAliased);
+        EmitAggExpr(copyExpr, Slot);
+      } else {
+        EmitSynthesizedCXXCopyCtor(blockField, src, copyExpr);
+      }
=20
     // If it's a reference variable, copy the reference into the block fie=
ld.
     } else if (type->isReferenceType()) {
@@ -606,45 +753,23 @@
=20
       // We use one of these or the other depending on whether the
       // reference is nested.
-      DeclRefExpr notNested(const_cast<VarDecl*>(variable), type, VK_LValu=
e,
-                            SourceLocation());
-      BlockDeclRefExpr nested(const_cast<VarDecl*>(variable), type,
-                              VK_LValue, SourceLocation(), /*byref*/ false=
);
-
-      Expr *declRef =3D=20
-        (ci->isNested() ? static_cast<Expr*>(&nested) : &notNested);
+      DeclRefExpr declRef(const_cast<VarDecl*>(variable),
+                          /*refersToEnclosing*/ ci->isNested(), type,
+                          VK_LValue, SourceLocation());
=20
       ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRVa=
lue,
-                           declRef, VK_RValue);
+                           &declRef, VK_RValue);
       EmitExprAsInit(&l2r, &blockFieldPseudoVar,
                      MakeAddrLValue(blockField, type,
-                                    getContext().getDeclAlign(variable)
-                                                .getQuantity()),
+                                    getContext().getDeclAlign(variable)),
                      /*captured by init*/ false);
     }
=20
-    // Push a destructor if necessary.  The semantics for when this
-    // actually gets run are really obscure.
+    // Activate the cleanup if layout pushed one.
     if (!ci->isByRef()) {
-      switch (QualType::DestructionKind dtorKind =3D type.isDestructedType=
()) {
-      case QualType::DK_none:
-        break;
-
-      // Block captures count as local values and have imprecise semantics.
-      // They also can't be arrays, so need to worry about that.
-      case QualType::DK_objc_strong_lifetime: {
-        // This local is a GCC and MSVC compiler workaround.
-        Destroyer *destroyer =3D &destroyARCStrongImprecise;
-        pushDestroy(getCleanupKind(dtorKind), blockField, type,
-                    *destroyer, /*useEHCleanupForArray*/ false);
-        break;
-      }
-
-      case QualType::DK_objc_weak_lifetime:
-      case QualType::DK_cxx_destructor:
-        pushDestroy(dtorKind, blockField, type);
-        break;
-      }
+      EHScopeStack::stable_iterator cleanup =3D capture.getCleanup();
+      if (cleanup.isValid())
+        ActivateCleanupBlock(cleanup, blockInfo.DominatingIP);
     }
   }
=20
@@ -744,11 +869,11 @@
   llvm::Value *Func =3D Builder.CreateLoad(FuncPtr);
=20
   const FunctionType *FuncTy =3D FnType->castAs<FunctionType>();
-  const CGFunctionInfo &FnInfo =3D CGM.getTypes().getFunctionInfo(Args, Fu=
ncTy);
+  const CGFunctionInfo &FnInfo =3D
+    CGM.getTypes().arrangeFunctionCall(Args, FuncTy);
=20
   // Cast the function pointer to the right type.
-  llvm::Type *BlockFTy =3D
-    CGM.getTypes().GetFunctionType(FnInfo, false);
+  llvm::Type *BlockFTy =3D CGM.getTypes().GetFunctionType(FnInfo);
=20
   llvm::Type *BlockFTyPtr =3D llvm::PointerType::getUnqual(BlockFTy);
   Func =3D Builder.CreateBitCast(Func, BlockFTyPtr);
@@ -798,10 +923,11 @@
 llvm::Constant *
 CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
                                     const char *name) {
-  CGBlockInfo blockInfo(blockExpr, name);
+  CGBlockInfo blockInfo(blockExpr->getBlockDecl(), name);
+  blockInfo.BlockExpression =3D blockExpr;
=20
   // Compute information about the layout, etc., of this block.
-  computeBlockInfo(*this, blockInfo);
+  computeBlockInfo(*this, 0, blockInfo);
=20
   // Using that metadata, generate the actual block function.
   llvm::Constant *blockFn;
@@ -809,7 +935,8 @@
     llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
     blockFn =3D CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
                                                            blockInfo,
-                                                           0, LocalDeclMap=
);
+                                                           0, LocalDeclMap,
+                                                           false);
   }
   blockFn =3D llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
=20
@@ -863,7 +990,8 @@
 CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
                                        const CGBlockInfo &blockInfo,
                                        const Decl *outerFnDecl,
-                                       const DeclMapTy &ldm) {
+                                       const DeclMapTy &ldm,
+                                       bool IsLambdaConversionToBlock) {
   const BlockDecl *blockDecl =3D blockInfo.getBlockDecl();
=20
   // Check if we should generate debug info for this block function.
@@ -901,16 +1029,15 @@
     args.push_back(*i);
=20
   // Create the function declaration.
-  const FunctionProtoType *fnType =3D
-    cast<FunctionProtoType>(blockInfo.getBlockExpr()->getFunctionType());
+  const FunctionProtoType *fnType =3D blockInfo.getBlockExpr()->getFunctio=
nType();
   const CGFunctionInfo &fnInfo =3D
-    CGM.getTypes().getFunctionInfo(fnType->getResultType(), args,
-                                   fnType->getExtInfo());
+    CGM.getTypes().arrangeFunctionDeclaration(fnType->getResultType(), arg=
s,
+                                              fnType->getExtInfo(),
+                                              fnType->isVariadic());
   if (CGM.ReturnTypeUsesSRet(fnInfo))
     blockInfo.UsesStret =3D true;
=20
-  llvm::FunctionType *fnLLVMType =3D
-    CGM.getTypes().GetFunctionType(fnInfo, fnType->isVariadic());
+  llvm::FunctionType *fnLLVMType =3D CGM.getTypes().GetFunctionType(fnInfo=
);
=20
   MangleBuffer name;
   CGM.getBlockMangledName(GD, name, blockDecl);
@@ -976,12 +1103,15 @@
     LocalDeclMap[variable] =3D alloca;
   }
=20
-  // Save a spot to insert the debug information for all the BlockDeclRefD=
ecls.
+  // Save a spot to insert the debug information for all the DeclRefExprs.
   llvm::BasicBlock *entry =3D Builder.GetInsertBlock();
   llvm::BasicBlock::iterator entry_ptr =3D Builder.GetInsertPoint();
   --entry_ptr;
=20
-  EmitStmt(blockDecl->getBody());
+  if (IsLambdaConversionToBlock)
+    EmitLambdaBlockInvokeBody();
+  else
+    EmitStmt(blockDecl->getBody());
=20
   // Remember where we were...
   llvm::BasicBlock *resume =3D Builder.GetInsertBlock();
@@ -990,7 +1120,7 @@
   ++entry_ptr;
   Builder.SetInsertPoint(entry, entry_ptr);
=20
-  // Emit debug information for all the BlockDeclRefDecls.
+  // Emit debug information for all the DeclRefExprs.
   // FIXME: also for 'this'
   if (CGDebugInfo *DI =3D getDebugInfo()) {
     for (BlockDecl::capture_const_iterator ci =3D blockDecl->capture_begin=
(),
@@ -1052,11 +1182,13 @@
   args.push_back(&srcDecl);
=20
   const CGFunctionInfo &FI =3D
-      CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo=
());
+    CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
+                                              FunctionType::ExtInfo(),
+                                              /*variadic*/ false);
=20
   // FIXME: it would be nice if these were mergeable with things with
   // identical semantics.
-  llvm::FunctionType *LTy =3D CGM.getTypes().GetFunctionType(FI, false);
+  llvm::FunctionType *LTy =3D CGM.getTypes().GetFunctionType(FI);
=20
   llvm::Function *Fn =3D
     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
@@ -1076,7 +1208,7 @@
                                           SC_Static,
                                           SC_None,
                                           false,
-                                          true);
+                                          false);
   StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
=20
   llvm::Type *structPtrTy =3D blockInfo.StructureType->getPointerTo();
@@ -1119,7 +1251,7 @@
         flags =3D BLOCK_FIELD_IS_BLOCK;
=20
       // Special rules for ARC captures:
-      if (getLangOptions().ObjCAutoRefCount) {
+      if (getLangOpts().ObjCAutoRefCount) {
         Qualifiers qs =3D type.getQualifiers();
=20
         // Don't generate special copy logic for a captured object
@@ -1167,11 +1299,13 @@
   args.push_back(&srcDecl);
=20
   const CGFunctionInfo &FI =3D
-      CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo=
());
+    CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
+                                              FunctionType::ExtInfo(),
+                                              /*variadic*/ false);
=20
   // FIXME: We'd like to put these into a mergable by content, with
   // internal linkage.
-  llvm::FunctionType *LTy =3D CGM.getTypes().GetFunctionType(FI, false);
+  llvm::FunctionType *LTy =3D CGM.getTypes().GetFunctionType(FI);
=20
   llvm::Function *Fn =3D
     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
@@ -1189,7 +1323,7 @@
                                           SourceLocation(), II, C.VoidTy, =
0,
                                           SC_Static,
                                           SC_None,
-                                          false, true);
+                                          false, false);
   StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
=20
   llvm::Type *structPtrTy =3D blockInfo.StructureType->getPointerTo();
@@ -1229,7 +1363,7 @@
         flags =3D BLOCK_FIELD_IS_BLOCK;
=20
       // Special rules for ARC captures.
-      if (getLangOptions().ObjCAutoRefCount) {
+      if (getLangOpts().ObjCAutoRefCount) {
         Qualifiers qs =3D type.getQualifiers();
=20
         // Don't generate special dispose logic for a captured object
@@ -1340,15 +1474,23 @@
     // Do a "move" by copying the value and then zeroing out the old
     // variable.
=20
-    llvm::Value *value =3D CGF.Builder.CreateLoad(srcField);
+    llvm::LoadInst *value =3D CGF.Builder.CreateLoad(srcField);
+    value->setAlignment(Alignment.getQuantity());
+   =20
     llvm::Value *null =3D
       llvm::ConstantPointerNull::get(cast<llvm::PointerType>(value->getTyp=
e()));
-    CGF.Builder.CreateStore(value, destField);
-    CGF.Builder.CreateStore(null, srcField);
+
+    llvm::StoreInst *store =3D CGF.Builder.CreateStore(value, destField);
+    store->setAlignment(Alignment.getQuantity());
+
+    store =3D CGF.Builder.CreateStore(null, srcField);
+    store->setAlignment(Alignment.getQuantity());
   }
=20
   void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
-    llvm::Value *value =3D CGF.Builder.CreateLoad(field);
+    llvm::LoadInst *value =3D CGF.Builder.CreateLoad(field);
+    value->setAlignment(Alignment.getQuantity());
+
     CGF.EmitARCRelease(value, /*precise*/ false);
   }
=20
@@ -1358,6 +1500,39 @@
   }
 };
=20
+/// Emits the copy/dispose helpers for an ARC __block __strong
+/// variable that's of block-pointer type.
+class ARCStrongBlockByrefHelpers : public CodeGenModule::ByrefHelpers {
+public:
+  ARCStrongBlockByrefHelpers(CharUnits alignment) : ByrefHelpers(alignment=
) {}
+
+  void emitCopy(CodeGenFunction &CGF, llvm::Value *destField,
+                llvm::Value *srcField) {
+    // Do the copy with objc_retainBlock; that's all that
+    // _Block_object_assign would do anyway, and we'd have to pass the
+    // right arguments to make sure it doesn't get no-op'ed.
+    llvm::LoadInst *oldValue =3D CGF.Builder.CreateLoad(srcField);
+    oldValue->setAlignment(Alignment.getQuantity());
+
+    llvm::Value *copy =3D CGF.EmitARCRetainBlock(oldValue, /*mandatory*/ t=
rue);
+
+    llvm::StoreInst *store =3D CGF.Builder.CreateStore(copy, destField);
+    store->setAlignment(Alignment.getQuantity());
+  }
+
+  void emitDispose(CodeGenFunction &CGF, llvm::Value *field) {
+    llvm::LoadInst *value =3D CGF.Builder.CreateLoad(field);
+    value->setAlignment(Alignment.getQuantity());
+
+    CGF.EmitARCRelease(value, /*precise*/ false);
+  }
+
+  void profileImpl(llvm::FoldingSetNodeID &id) const {
+    // 2 is distinguishable from all pointers and byref flags
+    id.AddInteger(2);
+  }
+};
+
 /// Emits the copy/dispose helpers for a __block variable with a
 /// nontrivial copy constructor or destructor.
 class CXXByrefHelpers : public CodeGenModule::ByrefHelpers {
@@ -1404,10 +1579,12 @@
   args.push_back(&src);
=20
   const CGFunctionInfo &FI =3D
-    CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
+    CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
+                                                  FunctionType::ExtInfo(),
+                                                  /*variadic*/ false);
=20
   CodeGenTypes &Types =3D CGF.CGM.getTypes();
-  llvm::FunctionType *LTy =3D Types.GetFunctionType(FI, false);
+  llvm::FunctionType *LTy =3D Types.GetFunctionType(FI);
=20
   // FIXME: We'd like to put these into a mergable by content, with
   // internal linkage.
@@ -1424,7 +1601,7 @@
                                           SourceLocation(), II, R, 0,
                                           SC_Static,
                                           SC_None,
-                                          false, true);
+                                          false, false);
=20
   CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
=20
@@ -1472,10 +1649,12 @@
   args.push_back(&src);
=20
   const CGFunctionInfo &FI =3D
-    CGF.CGM.getTypes().getFunctionInfo(R, args, FunctionType::ExtInfo());
+    CGF.CGM.getTypes().arrangeFunctionDeclaration(R, args,
+                                                  FunctionType::ExtInfo(),
+                                                  /*variadic*/ false);
=20
   CodeGenTypes &Types =3D CGF.CGM.getTypes();
-  llvm::FunctionType *LTy =3D Types.GetFunctionType(FI, false);
+  llvm::FunctionType *LTy =3D Types.GetFunctionType(FI);
=20
   // FIXME: We'd like to put these into a mergable by content, with
   // internal linkage.
@@ -1493,7 +1672,7 @@
                                           SourceLocation(), II, R, 0,
                                           SC_Static,
                                           SC_None,
-                                          false, true);
+                                          false, false);
   CGF.StartFunction(FD, R, Fn, FI, args, SourceLocation());
=20
   if (byrefInfo.needsDispose()) {
@@ -1565,7 +1744,7 @@
=20
   // If we have lifetime, that dominates.
   if (Qualifiers::ObjCLifetime lifetime =3D qs.getObjCLifetime()) {
-    assert(getLangOptions().ObjCAutoRefCount);
+    assert(getLangOpts().ObjCAutoRefCount);
=20
     switch (lifetime) {
     case Qualifiers::OCL_None: llvm_unreachable("impossible");
@@ -1584,13 +1763,10 @@
=20
     // ARC __strong __block variables need to be retained.
     case Qualifiers::OCL_Strong:
-      // Block-pointers need to be _Block_copy'ed, so we let the
-      // runtime be in charge.  But we can't use the code below
-      // because we don't want to set BYREF_CALLER, which will
-      // just make the runtime ignore us.
+      // Block pointers need to be copied, and there's no direct
+      // transfer possible.
       if (type->isBlockPointerType()) {
-        BlockFieldFlags flags =3D BLOCK_FIELD_IS_BLOCK;
-        ObjectByrefHelpers byrefInfo(emission.Alignment, flags);
+        ARCStrongBlockByrefHelpers byrefInfo(emission.Alignment);
         return ::buildByrefHelpers(CGM, byrefType, byrefInfo);
=20
       // Otherwise, we transfer ownership of the retain from the stack
@@ -1674,7 +1850,8 @@
   // int32_t __size;
   types.push_back(Int32Ty);
=20
-  bool HasCopyAndDispose =3D getContext().BlockRequiresCopying(Ty);
+  bool HasCopyAndDispose =3D
+       (Ty->isObjCRetainableType()) || getContext().getBlockVarCopyInits(D=
);
   if (HasCopyAndDispose) {
     /// void *__copy_helper;
     types.push_back(Int8PtrTy);
@@ -1701,7 +1878,7 @@
    =20
     unsigned NumPaddingBytes =3D AlignedOffsetInBytes - CurrentOffsetInByt=
es;
     if (NumPaddingBytes > 0) {
-      llvm::Type *Ty =3D llvm::Type::getInt8Ty(getLLVMContext());
+      llvm::Type *Ty =3D Int8Ty;
       // FIXME: We need a sema error for alignment larger than the minimum=
 of
       // the maximal stack alignment and the alignment of malloc on the sy=
stem.
       if (NumPaddingBytes > 1)
@@ -1803,7 +1980,7 @@
 /// to be done externally.
 void CodeGenFunction::enterByrefCleanup(const AutoVarEmission &emission) {
   // We don't enter this cleanup if we're in pure-GC mode.
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::GCOnly)
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::GCOnly)
     return;
=20
   EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Addre=
ss);
@@ -1812,7 +1989,7 @@
 /// Adjust the declaration of something from the blocks API.
 static void configureBlocksRuntimeObject(CodeGenModule &CGM,
                                          llvm::Constant *C) {
-  if (!CGM.getLangOptions().BlocksRuntimeOptional) return;
+  if (!CGM.getLangOpts().BlocksRuntimeOptional) return;
=20
   llvm::GlobalValue *GV =3D cast<llvm::GlobalValue>(C->stripPointerCasts()=
);
   if (GV->isDeclaration() &&
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGBlocks.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGBlocks.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -23,6 +23,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
=20
+#include "CodeGenFunction.h"
 #include "CGBuilder.h"
 #include "CGCall.h"
 #include "CGValue.h"
@@ -128,13 +129,14 @@
 class CGBlockInfo {
 public:
   /// Name - The name of the block, kindof.
-  const char *Name;
+  llvm::StringRef Name;
=20
   /// The field index of 'this' within the block, if there is one.
   unsigned CXXThisIndex;
=20
   class Capture {
     uintptr_t Data;
+    EHScopeStack::stable_iterator Cleanup;
=20
   public:
     bool isIndex() const { return (Data & 1) !=3D 0; }
@@ -144,6 +146,14 @@
       assert(isConstant());
       return reinterpret_cast<llvm::Value*>(Data);
     }
+    EHScopeStack::stable_iterator getCleanup() const {
+      assert(isIndex());
+      return Cleanup;
+    }
+    void setCleanup(EHScopeStack::stable_iterator cleanup) {
+      assert(isIndex());
+      Cleanup =3D cleanup;
+    }
=20
     static Capture makeIndex(unsigned index) {
       Capture v;
@@ -158,9 +168,6 @@
     }   =20
   };
=20
-  /// The mapping of allocated indexes within the block.
-  llvm::DenseMap<const VarDecl*, Capture> Captures; =20
-
   /// CanBeGlobal - True if the block can be global, i.e. it has
   /// no non-constant captures.
   bool CanBeGlobal : 1;
@@ -176,22 +183,44 @@
   /// because it gets set later in the block-creation process.
   mutable bool UsesStret : 1;
=20
+  /// The mapping of allocated indexes within the block.
+  llvm::DenseMap<const VarDecl*, Capture> Captures; =20
+
+  llvm::AllocaInst *Address;
   llvm::StructType *StructureType;
-  const BlockExpr *Block;
+  const BlockDecl *Block;
+  const BlockExpr *BlockExpression;
   CharUnits BlockSize;
   CharUnits BlockAlign;
=20
+  /// An instruction which dominates the full-expression that the
+  /// block is inside.
+  llvm::Instruction *DominatingIP;
+
+  /// The next block in the block-info chain.  Invalid if this block
+  /// info is not part of the CGF's block-info chain, which is true
+  /// if it corresponds to a global block or a block whose expression
+  /// has been encountered.
+  CGBlockInfo *NextBlockInfo;
+
   const Capture &getCapture(const VarDecl *var) const {
-    llvm::DenseMap<const VarDecl*, Capture>::const_iterator
+    return const_cast<CGBlockInfo*>(this)->getCapture(var);
+  }
+  Capture &getCapture(const VarDecl *var) {
+    llvm::DenseMap<const VarDecl*, Capture>::iterator
       it =3D Captures.find(var);
     assert(it !=3D Captures.end() && "no entry for variable!");
     return it->second;
   }
=20
-  const BlockDecl *getBlockDecl() const { return Block->getBlockDecl(); }
-  const BlockExpr *getBlockExpr() const { return Block; }
+  const BlockDecl *getBlockDecl() const { return Block; }
+  const BlockExpr *getBlockExpr() const {
+    assert(BlockExpression);
+    assert(BlockExpression->getBlockDecl() =3D=3D Block);
+    return BlockExpression;
+  }
=20
-  CGBlockInfo(const BlockExpr *blockExpr, const char *Name);
+  CGBlockInfo(const BlockDecl *blockDecl, llvm::StringRef Name);
 };
=20
 }  // end namespace CodeGen
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGBuiltin.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGBuiltin.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -16,7 +16,6 @@
 #include "CodeGenModule.h"
 #include "CGObjCRuntime.h"
 #include "clang/Basic/TargetInfo.h"
-#include "clang/AST/APValue.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/Basic/TargetBuiltins.h"
@@ -176,7 +175,7 @@
                                         unsigned BuiltinID, const CallExpr=
 *E) {
   // See if we can constant fold this builtin.  If so, don't emit it at al=
l.
   Expr::EvalResult Result;
-  if (E->Evaluate(Result, CGM.getContext()) &&
+  if (E->EvaluateAsRValue(Result, CGM.getContext()) &&
       !Result.hasSideEffects()) {
     if (Result.Val.isInt())
       return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
@@ -215,7 +214,9 @@
     return RValue::get(Builder.CreateCall2(CGM.getIntrinsic(Intrinsic::vac=
opy),
                                            DstPtr, SrcPtr));
   }
-  case Builtin::BI__builtin_abs: {
+  case Builtin::BI__builtin_abs:=20
+  case Builtin::BI__builtin_labs:
+  case Builtin::BI__builtin_llabs: {
     Value *ArgValue =3D EmitScalarExpr(E->getArg(0));
=20
     Value *NegOp =3D Builder.CreateNeg(ArgValue, "neg");
@@ -228,6 +229,7 @@
=20
     return RValue::get(Result);
   }
+  case Builtin::BI__builtin_ctzs:
   case Builtin::BI__builtin_ctz:
   case Builtin::BI__builtin_ctzl:
   case Builtin::BI__builtin_ctzll: {
@@ -237,12 +239,14 @@
     Value *F =3D CGM.getIntrinsic(Intrinsic::cttz, ArgType);
=20
     llvm::Type *ResultType =3D ConvertType(E->getType());
-    Value *Result =3D Builder.CreateCall(F, ArgValue);
+    Value *ZeroUndef =3D Builder.getInt1(Target.isCLZForZeroUndef());
+    Value *Result =3D Builder.CreateCall2(F, ArgValue, ZeroUndef);
     if (Result->getType() !=3D ResultType)
       Result =3D Builder.CreateIntCast(Result, ResultType, /*isSigned*/tru=
e,
                                      "cast");
     return RValue::get(Result);
   }
+  case Builtin::BI__builtin_clzs:
   case Builtin::BI__builtin_clz:
   case Builtin::BI__builtin_clzl:
   case Builtin::BI__builtin_clzll: {
@@ -252,7 +256,8 @@
     Value *F =3D CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
=20
     llvm::Type *ResultType =3D ConvertType(E->getType());
-    Value *Result =3D Builder.CreateCall(F, ArgValue);
+    Value *ZeroUndef =3D Builder.getInt1(Target.isCLZForZeroUndef());
+    Value *Result =3D Builder.CreateCall2(F, ArgValue, ZeroUndef);
     if (Result->getType() !=3D ResultType)
       Result =3D Builder.CreateIntCast(Result, ResultType, /*isSigned*/tru=
e,
                                      "cast");
@@ -268,7 +273,8 @@
     Value *F =3D CGM.getIntrinsic(Intrinsic::cttz, ArgType);
=20
     llvm::Type *ResultType =3D ConvertType(E->getType());
-    Value *Tmp =3D Builder.CreateAdd(Builder.CreateCall(F, ArgValue),
+    Value *Tmp =3D Builder.CreateAdd(Builder.CreateCall2(F, ArgValue,
+                                                       Builder.getTrue()),
                                    llvm::ConstantInt::get(ArgType, 1));
     Value *Zero =3D llvm::Constant::getNullValue(ArgType);
     Value *IsZero =3D Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
@@ -534,7 +540,8 @@
   case Builtin::BI__builtin_bzero: {
     Value *Address =3D EmitScalarExpr(E->getArg(0));
     Value *SizeVal =3D EmitScalarExpr(E->getArg(1));
-    Builder.CreateMemSet(Address, Builder.getInt8(0), SizeVal, 1, false);
+    unsigned Align =3D GetPointeeAlignment(E->getArg(0));
+    Builder.CreateMemSet(Address, Builder.getInt8(0), SizeVal, Align, fals=
e);
     return RValue::get(Address);
   }
   case Builtin::BImemcpy:
@@ -542,7 +549,9 @@
     Value *Address =3D EmitScalarExpr(E->getArg(0));
     Value *SrcAddr =3D EmitScalarExpr(E->getArg(1));
     Value *SizeVal =3D EmitScalarExpr(E->getArg(2));
-    Builder.CreateMemCpy(Address, SrcAddr, SizeVal, 1, false);
+    unsigned Align =3D std::min(GetPointeeAlignment(E->getArg(0)),
+                              GetPointeeAlignment(E->getArg(1)));
+    Builder.CreateMemCpy(Address, SrcAddr, SizeVal, Align, false);
     return RValue::get(Address);
   }
      =20
@@ -557,7 +566,9 @@
     Value *Dest =3D EmitScalarExpr(E->getArg(0));
     Value *Src =3D EmitScalarExpr(E->getArg(1));
     Value *SizeVal =3D llvm::ConstantInt::get(Builder.getContext(), Size);
-    Builder.CreateMemCpy(Dest, Src, SizeVal, 1, false);
+    unsigned Align =3D std::min(GetPointeeAlignment(E->getArg(0)),
+                              GetPointeeAlignment(E->getArg(1)));
+    Builder.CreateMemCpy(Dest, Src, SizeVal, Align, false);
     return RValue::get(Dest);
   }
      =20
@@ -581,7 +592,9 @@
     Value *Dest =3D EmitScalarExpr(E->getArg(0));
     Value *Src =3D EmitScalarExpr(E->getArg(1));
     Value *SizeVal =3D llvm::ConstantInt::get(Builder.getContext(), Size);
-    Builder.CreateMemMove(Dest, Src, SizeVal, 1, false);
+    unsigned Align =3D std::min(GetPointeeAlignment(E->getArg(0)),
+                              GetPointeeAlignment(E->getArg(1)));
+    Builder.CreateMemMove(Dest, Src, SizeVal, Align, false);
     return RValue::get(Dest);
   }
=20
@@ -590,7 +603,9 @@
     Value *Address =3D EmitScalarExpr(E->getArg(0));
     Value *SrcAddr =3D EmitScalarExpr(E->getArg(1));
     Value *SizeVal =3D EmitScalarExpr(E->getArg(2));
-    Builder.CreateMemMove(Address, SrcAddr, SizeVal, 1, false);
+    unsigned Align =3D std::min(GetPointeeAlignment(E->getArg(0)),
+                              GetPointeeAlignment(E->getArg(1)));
+    Builder.CreateMemMove(Address, SrcAddr, SizeVal, Align, false);
     return RValue::get(Address);
   }
   case Builtin::BImemset:
@@ -599,7 +614,8 @@
     Value *ByteVal =3D Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
                                          Builder.getInt8Ty());
     Value *SizeVal =3D EmitScalarExpr(E->getArg(2));
-    Builder.CreateMemSet(Address, ByteVal, SizeVal, 1, false);
+    unsigned Align =3D GetPointeeAlignment(E->getArg(0));
+    Builder.CreateMemSet(Address, ByteVal, SizeVal, Align, false);
     return RValue::get(Address);
   }
   case Builtin::BI__builtin___memset_chk: {
@@ -614,7 +630,8 @@
     Value *ByteVal =3D Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
                                          Builder.getInt8Ty());
     Value *SizeVal =3D llvm::ConstantInt::get(Builder.getContext(), Size);
-    Builder.CreateMemSet(Address, ByteVal, SizeVal, 1, false);
+    unsigned Align =3D GetPointeeAlignment(E->getArg(0));
+    Builder.CreateMemSet(Address, ByteVal, SizeVal, Align, false);
    =20
     return RValue::get(Address);
   }
@@ -925,12 +942,13 @@
   case Builtin::BI__sync_lock_release_8:
   case Builtin::BI__sync_lock_release_16: {
     Value *Ptr =3D EmitScalarExpr(E->getArg(0));
-    llvm::Type *ElLLVMTy =3D
-      cast<llvm::PointerType>(Ptr->getType())->getElementType();
-    llvm::StoreInst *Store =3D=20
-      Builder.CreateStore(llvm::Constant::getNullValue(ElLLVMTy), Ptr);
     QualType ElTy =3D E->getArg(0)->getType()->getPointeeType();
     CharUnits StoreSize =3D getContext().getTypeSizeInChars(ElTy);
+    llvm::Type *ITy =3D llvm::IntegerType::get(getLLVMContext(),
+                                             StoreSize.getQuantity() * 8);
+    Ptr =3D Builder.CreateBitCast(Ptr, ITy->getPointerTo());
+    llvm::StoreInst *Store =3D=20
+      Builder.CreateStore(llvm::Constant::getNullValue(ITy), Ptr);
     Store->setAlignment(StoreSize.getQuantity());
     Store->setAtomic(llvm::Release);
     return RValue::get(0);
@@ -948,10 +966,186 @@
     return RValue::get(0);
   }
=20
+  case Builtin::BI__c11_atomic_is_lock_free:
+  case Builtin::BI__atomic_is_lock_free: {
+    // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
+    // __c11 builtin, ptr is 0 (indicating a properly-aligned object), sin=
ce
+    // _Atomic(T) is always properly-aligned.
+    const char *LibCallName =3D "__atomic_is_lock_free";
+    CallArgList Args;
+    Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
+             getContext().getSizeType());
+    if (BuiltinID =3D=3D Builtin::BI__atomic_is_lock_free)
+      Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
+               getContext().VoidPtrTy);
+    else
+      Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
+               getContext().VoidPtrTy);
+    const CGFunctionInfo &FuncInfo =3D
+        CGM.getTypes().arrangeFunctionCall(E->getType(), Args,
+                                           FunctionType::ExtInfo(),
+                                           RequiredArgs::All);
+    llvm::FunctionType *FTy =3D CGM.getTypes().GetFunctionType(FuncInfo);
+    llvm::Constant *Func =3D CGM.CreateRuntimeFunction(FTy, LibCallName);
+    return EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
+  }
+
+  case Builtin::BI__atomic_test_and_set: {
+    // Look at the argument type to determine whether this is a volatile
+    // operation. The parameter type is always volatile.
+    QualType PtrTy =3D E->getArg(0)->IgnoreImpCasts()->getType();
+    bool Volatile =3D
+        PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified=
();
+
+    Value *Ptr =3D EmitScalarExpr(E->getArg(0));
+    unsigned AddrSpace =3D
+        cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
+    Ptr =3D Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
+    Value *NewVal =3D Builder.getInt8(1);
+    Value *Order =3D EmitScalarExpr(E->getArg(1));
+    if (isa<llvm::ConstantInt>(Order)) {
+      int ord =3D cast<llvm::ConstantInt>(Order)->getZExtValue();
+      AtomicRMWInst *Result =3D 0;
+      switch (ord) {
+      case 0:  // memory_order_relaxed
+      default: // invalid order
+        Result =3D Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
+                                         Ptr, NewVal,
+                                         llvm::Monotonic);
+        break;
+      case 1:  // memory_order_consume
+      case 2:  // memory_order_acquire
+        Result =3D Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
+                                         Ptr, NewVal,
+                                         llvm::Acquire);
+        break;
+      case 3:  // memory_order_release
+        Result =3D Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
+                                         Ptr, NewVal,
+                                         llvm::Release);
+        break;
+      case 4:  // memory_order_acq_rel
+        Result =3D Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
+                                         Ptr, NewVal,
+                                         llvm::AcquireRelease);
+        break;
+      case 5:  // memory_order_seq_cst
+        Result =3D Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
+                                         Ptr, NewVal,
+                                         llvm::SequentiallyConsistent);
+        break;
+      }
+      Result->setVolatile(Volatile);
+      return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
+    }
+
+    llvm::BasicBlock *ContBB =3D createBasicBlock("atomic.continue", CurFn=
);
+
+    llvm::BasicBlock *BBs[5] =3D {
+      createBasicBlock("monotonic", CurFn),
+      createBasicBlock("acquire", CurFn),
+      createBasicBlock("release", CurFn),
+      createBasicBlock("acqrel", CurFn),
+      createBasicBlock("seqcst", CurFn)
+    };
+    llvm::AtomicOrdering Orders[5] =3D {
+      llvm::Monotonic, llvm::Acquire, llvm::Release,
+      llvm::AcquireRelease, llvm::SequentiallyConsistent
+    };
+
+    Order =3D Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
+    llvm::SwitchInst *SI =3D Builder.CreateSwitch(Order, BBs[0]);
+
+    Builder.SetInsertPoint(ContBB);
+    PHINode *Result =3D Builder.CreatePHI(Int8Ty, 5, "was_set");
+
+    for (unsigned i =3D 0; i < 5; ++i) {
+      Builder.SetInsertPoint(BBs[i]);
+      AtomicRMWInst *RMW =3D Builder.CreateAtomicRMW(llvm::AtomicRMWInst::=
Xchg,
+                                                   Ptr, NewVal, Orders[i]);
+      RMW->setVolatile(Volatile);
+      Result->addIncoming(RMW, BBs[i]);
+      Builder.CreateBr(ContBB);
+    }
+
+    SI->addCase(Builder.getInt32(0), BBs[0]);
+    SI->addCase(Builder.getInt32(1), BBs[1]);
+    SI->addCase(Builder.getInt32(2), BBs[1]);
+    SI->addCase(Builder.getInt32(3), BBs[2]);
+    SI->addCase(Builder.getInt32(4), BBs[3]);
+    SI->addCase(Builder.getInt32(5), BBs[4]);
+
+    Builder.SetInsertPoint(ContBB);
+    return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
+  }
+
+  case Builtin::BI__atomic_clear: {
+    QualType PtrTy =3D E->getArg(0)->IgnoreImpCasts()->getType();
+    bool Volatile =3D
+        PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified=
();
+
+    Value *Ptr =3D EmitScalarExpr(E->getArg(0));
+    unsigned AddrSpace =3D
+        cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
+    Ptr =3D Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
+    Value *NewVal =3D Builder.getInt8(0);
+    Value *Order =3D EmitScalarExpr(E->getArg(1));
+    if (isa<llvm::ConstantInt>(Order)) {
+      int ord =3D cast<llvm::ConstantInt>(Order)->getZExtValue();
+      StoreInst *Store =3D Builder.CreateStore(NewVal, Ptr, Volatile);
+      Store->setAlignment(1);
+      switch (ord) {
+      case 0:  // memory_order_relaxed
+      default: // invalid order
+        Store->setOrdering(llvm::Monotonic);
+        break;
+      case 3:  // memory_order_release
+        Store->setOrdering(llvm::Release);
+        break;
+      case 5:  // memory_order_seq_cst
+        Store->setOrdering(llvm::SequentiallyConsistent);
+        break;
+      }
+      return RValue::get(0);
+    }
+
+    llvm::BasicBlock *ContBB =3D createBasicBlock("atomic.continue", CurFn=
);
+
+    llvm::BasicBlock *BBs[3] =3D {
+      createBasicBlock("monotonic", CurFn),
+      createBasicBlock("release", CurFn),
+      createBasicBlock("seqcst", CurFn)
+    };
+    llvm::AtomicOrdering Orders[3] =3D {
+      llvm::Monotonic, llvm::Release, llvm::SequentiallyConsistent
+    };
+
+    Order =3D Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
+    llvm::SwitchInst *SI =3D Builder.CreateSwitch(Order, BBs[0]);
+
+    for (unsigned i =3D 0; i < 3; ++i) {
+      Builder.SetInsertPoint(BBs[i]);
+      StoreInst *Store =3D Builder.CreateStore(NewVal, Ptr, Volatile);
+      Store->setAlignment(1);
+      Store->setOrdering(Orders[i]);
+      Builder.CreateBr(ContBB);
+    }
+
+    SI->addCase(Builder.getInt32(0), BBs[0]);
+    SI->addCase(Builder.getInt32(3), BBs[1]);
+    SI->addCase(Builder.getInt32(5), BBs[2]);
+
+    Builder.SetInsertPoint(ContBB);
+    return RValue::get(0);
+  }
+
   case Builtin::BI__atomic_thread_fence:
-  case Builtin::BI__atomic_signal_fence: {
+  case Builtin::BI__atomic_signal_fence:
+  case Builtin::BI__c11_atomic_thread_fence:
+  case Builtin::BI__c11_atomic_signal_fence: {
     llvm::SynchronizationScope Scope;
-    if (BuiltinID =3D=3D Builtin::BI__atomic_signal_fence)
+    if (BuiltinID =3D=3D Builtin::BI__atomic_signal_fence ||
+        BuiltinID =3D=3D Builtin::BI__c11_atomic_signal_fence)
       Scope =3D llvm::SingleThread;
     else
       Scope =3D llvm::CrossThread;
@@ -1145,8 +1339,9 @@
     Value *V =3D Builder.CreateCall(F, Args);
     QualType BuiltinRetType =3D E->getType();
=20
-    llvm::Type *RetTy =3D llvm::Type::getVoidTy(getLLVMContext());
-    if (!BuiltinRetType->isVoidType()) RetTy =3D ConvertType(BuiltinRetTyp=
e);
+    llvm::Type *RetTy =3D VoidTy;
+    if (!BuiltinRetType->isVoidType())=20
+      RetTy =3D ConvertType(BuiltinRetType);
=20
     if (RetTy !=3D V->getType()) {
       assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&
@@ -1181,30 +1376,37 @@
   case llvm::Triple::ppc:
   case llvm::Triple::ppc64:
     return EmitPPCBuiltinExpr(BuiltinID, E);
+  case llvm::Triple::hexagon:
+    return EmitHexagonBuiltinExpr(BuiltinID, E);
   default:
     return 0;
   }
 }
=20
-static llvm::VectorType *GetNeonType(LLVMContext &C, unsigned type, bool q=
) {
-  switch (type) {
-    default: break;
-    case 0:=20
-    case 5: return llvm::VectorType::get(llvm::Type::getInt8Ty(C), 8 << (i=
nt)q);
-    case 6:
-    case 7:
-    case 1: return llvm::VectorType::get(llvm::Type::getInt16Ty(C),4 << (i=
nt)q);
-    case 2: return llvm::VectorType::get(llvm::Type::getInt32Ty(C),2 << (i=
nt)q);
-    case 3: return llvm::VectorType::get(llvm::Type::getInt64Ty(C),1 << (i=
nt)q);
-    case 4: return llvm::VectorType::get(llvm::Type::getFloatTy(C),2 << (i=
nt)q);
-  };
-  return 0;
+static llvm::VectorType *GetNeonType(CodeGenFunction *CGF,
+                                     NeonTypeFlags TypeFlags) {
+  int IsQuad =3D TypeFlags.isQuad();
+  switch (TypeFlags.getEltType()) {
+  case NeonTypeFlags::Int8:
+  case NeonTypeFlags::Poly8:
+    return llvm::VectorType::get(CGF->Int8Ty, 8 << IsQuad);
+  case NeonTypeFlags::Int16:
+  case NeonTypeFlags::Poly16:
+  case NeonTypeFlags::Float16:
+    return llvm::VectorType::get(CGF->Int16Ty, 4 << IsQuad);
+  case NeonTypeFlags::Int32:
+    return llvm::VectorType::get(CGF->Int32Ty, 2 << IsQuad);
+  case NeonTypeFlags::Int64:
+    return llvm::VectorType::get(CGF->Int64Ty, 1 << IsQuad);
+  case NeonTypeFlags::Float32:
+    return llvm::VectorType::get(CGF->FloatTy, 2 << IsQuad);
+  }
+  llvm_unreachable("Invalid NeonTypeFlags element type!");
 }
=20
 Value *CodeGenFunction::EmitNeonSplat(Value *V, Constant *C) {
   unsigned nElts =3D cast<llvm::VectorType>(V->getType())->getNumElements(=
);
-  SmallVector<Constant*, 16> Indices(nElts, C);
-  Value* SV =3D llvm::ConstantVector::get(Indices);
+  Value* SV =3D llvm::ConstantVector::getSplat(nElts, C);
   return Builder.CreateShuffleVector(V, V, SV, "lane");
 }
=20
@@ -1224,26 +1426,28 @@
=20
 Value *CodeGenFunction::EmitNeonShiftVector(Value *V, llvm::Type *Ty,=20
                                             bool neg) {
-  ConstantInt *CI =3D cast<ConstantInt>(V);
-  int SV =3D CI->getSExtValue();
+  int SV =3D cast<ConstantInt>(V)->getSExtValue();
  =20
   llvm::VectorType *VTy =3D cast<llvm::VectorType>(Ty);
   llvm::Constant *C =3D ConstantInt::get(VTy->getElementType(), neg ? -SV =
: SV);
-  SmallVector<llvm::Constant*, 16> CV(VTy->getNumElements(), C);
-  return llvm::ConstantVector::get(CV);
+  return llvm::ConstantVector::getSplat(VTy->getNumElements(), C);
 }
=20
 /// GetPointeeAlignment - Given an expression with a pointer type, find the
 /// alignment of the type referenced by the pointer.  Skip over implicit
 /// casts.
-static Value *GetPointeeAlignment(CodeGenFunction &CGF, const Expr *Addr) {
+unsigned CodeGenFunction::GetPointeeAlignment(const Expr *Addr) {
   unsigned Align =3D 1;
   // Check if the type is a pointer.  The implicit cast operand might not =
be.
   while (Addr->getType()->isPointerType()) {
     QualType PtTy =3D Addr->getType()->getPointeeType();
-    unsigned NewA =3D CGF.getContext().getTypeAlignInChars(PtTy).getQuanti=
ty();
-    if (NewA > Align)
-      Align =3D NewA;
+   =20
+    // Can't get alignment of incomplete types.
+    if (!PtTy->isIncompleteType()) {
+      unsigned NewA =3D getContext().getTypeAlignInChars(PtTy).getQuantity=
();
+      if (NewA > Align)
+        Align =3D NewA;
+    }
=20
     // If the address is an implicit cast, repeat with the cast operand.
     if (const ImplicitCastExpr *CastAddr =3D dyn_cast<ImplicitCastExpr>(Ad=
dr)) {
@@ -1252,7 +1456,14 @@
     }
     break;
   }
-  return llvm::ConstantInt::get(CGF.Int32Ty, Align);
+  return Align;
+}
+
+/// GetPointeeAlignmentValue - Given an expression with a pointer type, fi=
nd
+/// the alignment of the type referenced by the pointer.  Skip over implic=
it
+/// casts.  Return the alignment as an llvm::Value.
+Value *CodeGenFunction::GetPointeeAlignmentValue(const Expr *Addr) {
+  return llvm::ConstantInt::get(Int32Ty, GetPointeeAlignment(Addr));
 }
=20
 Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
@@ -1349,9 +1560,9 @@
     // Determine the overloaded type of this builtin.
     llvm::Type *Ty;
     if (BuiltinID =3D=3D ARM::BI__builtin_arm_vcvtr_f)
-      Ty =3D llvm::Type::getFloatTy(getLLVMContext());
+      Ty =3D FloatTy;
     else
-      Ty =3D llvm::Type::getDoubleTy(getLLVMContext());
+      Ty =3D DoubleTy;
    =20
     // Determine whether this is an unsigned conversion or not.
     bool usgn =3D Result.getZExtValue() =3D=3D 1;
@@ -1363,14 +1574,12 @@
   }
  =20
   // Determine the type of this overloaded NEON intrinsic.
-  unsigned type =3D Result.getZExtValue();
-  bool usgn =3D type & 0x08;
-  bool quad =3D type & 0x10;
-  bool poly =3D (type & 0x7) =3D=3D 5 || (type & 0x7) =3D=3D 6;
-  (void)poly;  // Only used in assert()s.
+  NeonTypeFlags Type(Result.getZExtValue());
+  bool usgn =3D Type.isUnsigned();
+  bool quad =3D Type.isQuad();
   bool rightShift =3D false;
=20
-  llvm::VectorType *VTy =3D GetNeonType(getLLVMContext(), type & 0x7, quad=
);
+  llvm::VectorType *VTy =3D GetNeonType(this, Type);
   llvm::Type *Ty =3D VTy;
   if (!Ty)
     return 0;
@@ -1429,34 +1638,40 @@
     return EmitNeonCall(F, Ops, "vcnt");
   }
   case ARM::BI__builtin_neon_vcvt_f16_v: {
-    assert((type & 0x7) =3D=3D 7 && !quad && "unexpected vcvt_f16_v builti=
n");
+    assert(Type.getEltType() =3D=3D NeonTypeFlags::Float16 && !quad &&
+           "unexpected vcvt_f16_v builtin");
     Function *F =3D CGM.getIntrinsic(Intrinsic::arm_neon_vcvtfp2hf);
     return EmitNeonCall(F, Ops, "vcvt");
   }
   case ARM::BI__builtin_neon_vcvt_f32_f16: {
-    assert((type & 0x7) =3D=3D 7 && !quad && "unexpected vcvt_f32_f16 buil=
tin");
+    assert(Type.getEltType() =3D=3D NeonTypeFlags::Float16 && !quad &&
+           "unexpected vcvt_f32_f16 builtin");
     Function *F =3D CGM.getIntrinsic(Intrinsic::arm_neon_vcvthf2fp);
     return EmitNeonCall(F, Ops, "vcvt");
   }
   case ARM::BI__builtin_neon_vcvt_f32_v:
-  case ARM::BI__builtin_neon_vcvtq_f32_v: {
+  case ARM::BI__builtin_neon_vcvtq_f32_v:
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
-    Ty =3D GetNeonType(getLLVMContext(), 4, quad);
+    Ty =3D GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float32, false, =
quad));
     return usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")=20
                 : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
-  }
   case ARM::BI__builtin_neon_vcvt_s32_v:
   case ARM::BI__builtin_neon_vcvt_u32_v:
   case ARM::BI__builtin_neon_vcvtq_s32_v:
   case ARM::BI__builtin_neon_vcvtq_u32_v: {
-    Ops[0] =3D Builder.CreateBitCast(Ops[0], GetNeonType(getLLVMContext(),=
 4, quad));
+    llvm::Type *FloatTy =3D
+      GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float32, false, quad)=
);
+    Ops[0] =3D Builder.CreateBitCast(Ops[0], FloatTy);
     return usgn ? Builder.CreateFPToUI(Ops[0], Ty, "vcvt")=20
                 : Builder.CreateFPToSI(Ops[0], Ty, "vcvt");
   }
   case ARM::BI__builtin_neon_vcvt_n_f32_v:
   case ARM::BI__builtin_neon_vcvtq_n_f32_v: {
-    llvm::Type *Tys[2] =3D { GetNeonType(getLLVMContext(), 4, quad), Ty };
-    Int =3D usgn ? Intrinsic::arm_neon_vcvtfxu2fp : Intrinsic::arm_neon_vc=
vtfxs2fp;
+    llvm::Type *FloatTy =3D
+      GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float32, false, quad)=
);
+    llvm::Type *Tys[2] =3D { FloatTy, Ty };
+    Int =3D usgn ? Intrinsic::arm_neon_vcvtfxu2fp
+               : Intrinsic::arm_neon_vcvtfxs2fp;
     Function *F =3D CGM.getIntrinsic(Int, Tys);
     return EmitNeonCall(F, Ops, "vcvt_n");
   }
@@ -1464,8 +1679,11 @@
   case ARM::BI__builtin_neon_vcvt_n_u32_v:
   case ARM::BI__builtin_neon_vcvtq_n_s32_v:
   case ARM::BI__builtin_neon_vcvtq_n_u32_v: {
-    llvm::Type *Tys[2] =3D { Ty, GetNeonType(getLLVMContext(), 4, quad) };
-    Int =3D usgn ? Intrinsic::arm_neon_vcvtfp2fxu : Intrinsic::arm_neon_vc=
vtfp2fxs;
+    llvm::Type *FloatTy =3D
+      GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float32, false, quad)=
);
+    llvm::Type *Tys[2] =3D { Ty, FloatTy };
+    Int =3D usgn ? Intrinsic::arm_neon_vcvtfp2fxu
+               : Intrinsic::arm_neon_vcvtfp2fxs;
     Function *F =3D CGM.getIntrinsic(Int, Tys);
     return EmitNeonCall(F, Ops, "vcvt_n");
   }
@@ -1491,30 +1709,35 @@
     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vhsub");
   case ARM::BI__builtin_neon_vld1_v:
   case ARM::BI__builtin_neon_vld1q_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vld1, Ty),
                         Ops, "vld1");
   case ARM::BI__builtin_neon_vld1_lane_v:
-  case ARM::BI__builtin_neon_vld1q_lane_v:
+  case ARM::BI__builtin_neon_vld1q_lane_v: {
     Ops[1] =3D Builder.CreateBitCast(Ops[1], Ty);
     Ty =3D llvm::PointerType::getUnqual(VTy->getElementType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
-    Ops[0] =3D Builder.CreateLoad(Ops[0]);
-    return Builder.CreateInsertElement(Ops[1], Ops[0], Ops[2], "vld1_lane"=
);
+    LoadInst *Ld =3D Builder.CreateLoad(Ops[0]);
+    Value *Align =3D GetPointeeAlignmentValue(E->getArg(0));
+    Ld->setAlignment(cast<ConstantInt>(Align)->getZExtValue());
+    return Builder.CreateInsertElement(Ops[1], Ld, Ops[2], "vld1_lane");
+  }
   case ARM::BI__builtin_neon_vld1_dup_v:
   case ARM::BI__builtin_neon_vld1q_dup_v: {
     Value *V =3D UndefValue::get(Ty);
     Ty =3D llvm::PointerType::getUnqual(VTy->getElementType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
-    Ops[0] =3D Builder.CreateLoad(Ops[0]);
+    LoadInst *Ld =3D Builder.CreateLoad(Ops[0]);
+    Value *Align =3D GetPointeeAlignmentValue(E->getArg(0));
+    Ld->setAlignment(cast<ConstantInt>(Align)->getZExtValue());
     llvm::Constant *CI =3D ConstantInt::get(Int32Ty, 0);
-    Ops[0] =3D Builder.CreateInsertElement(V, Ops[0], CI);
+    Ops[0] =3D Builder.CreateInsertElement(V, Ld, CI);
     return EmitNeonSplat(Ops[0], CI);
   }
   case ARM::BI__builtin_neon_vld2_v:
   case ARM::BI__builtin_neon_vld2q_v: {
     Function *F =3D CGM.getIntrinsic(Intrinsic::arm_neon_vld2, Ty);
-    Value *Align =3D GetPointeeAlignment(*this, E->getArg(1));
+    Value *Align =3D GetPointeeAlignmentValue(E->getArg(1));
     Ops[1] =3D Builder.CreateCall2(F, Ops[1], Align, "vld2");
     Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
@@ -1523,7 +1746,7 @@
   case ARM::BI__builtin_neon_vld3_v:
   case ARM::BI__builtin_neon_vld3q_v: {
     Function *F =3D CGM.getIntrinsic(Intrinsic::arm_neon_vld3, Ty);
-    Value *Align =3D GetPointeeAlignment(*this, E->getArg(1));
+    Value *Align =3D GetPointeeAlignmentValue(E->getArg(1));
     Ops[1] =3D Builder.CreateCall2(F, Ops[1], Align, "vld3");
     Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
@@ -1532,7 +1755,7 @@
   case ARM::BI__builtin_neon_vld4_v:
   case ARM::BI__builtin_neon_vld4q_v: {
     Function *F =3D CGM.getIntrinsic(Intrinsic::arm_neon_vld4, Ty);
-    Value *Align =3D GetPointeeAlignment(*this, E->getArg(1));
+    Value *Align =3D GetPointeeAlignmentValue(E->getArg(1));
     Ops[1] =3D Builder.CreateCall2(F, Ops[1], Align, "vld4");
     Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
@@ -1543,7 +1766,7 @@
     Function *F =3D CGM.getIntrinsic(Intrinsic::arm_neon_vld2lane, Ty);
     Ops[2] =3D Builder.CreateBitCast(Ops[2], Ty);
     Ops[3] =3D Builder.CreateBitCast(Ops[3], Ty);
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(1)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(1)));
     Ops[1] =3D Builder.CreateCall(F, makeArrayRef(Ops).slice(1), "vld2_lan=
e");
     Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
@@ -1555,7 +1778,7 @@
     Ops[2] =3D Builder.CreateBitCast(Ops[2], Ty);
     Ops[3] =3D Builder.CreateBitCast(Ops[3], Ty);
     Ops[4] =3D Builder.CreateBitCast(Ops[4], Ty);
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(1)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(1)));
     Ops[1] =3D Builder.CreateCall(F, makeArrayRef(Ops).slice(1), "vld3_lan=
e");
     Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
@@ -1568,7 +1791,7 @@
     Ops[3] =3D Builder.CreateBitCast(Ops[3], Ty);
     Ops[4] =3D Builder.CreateBitCast(Ops[4], Ty);
     Ops[5] =3D Builder.CreateBitCast(Ops[5], Ty);
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(1)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(1)));
     Ops[1] =3D Builder.CreateCall(F, makeArrayRef(Ops).slice(1), "vld3_lan=
e");
     Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
     Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
@@ -1584,15 +1807,15 @@
         Int =3D Intrinsic::arm_neon_vld2;=20
         break;
       case ARM::BI__builtin_neon_vld3_dup_v:
-        Int =3D Intrinsic::arm_neon_vld2;=20
+        Int =3D Intrinsic::arm_neon_vld3;=20
         break;
       case ARM::BI__builtin_neon_vld4_dup_v:
-        Int =3D Intrinsic::arm_neon_vld2;=20
+        Int =3D Intrinsic::arm_neon_vld4;=20
         break;
       default: llvm_unreachable("unknown vld_dup intrinsic?");
       }
       Function *F =3D CGM.getIntrinsic(Int, Ty);
-      Value *Align =3D GetPointeeAlignment(*this, E->getArg(1));
+      Value *Align =3D GetPointeeAlignmentValue(E->getArg(1));
       Ops[1] =3D Builder.CreateCall2(F, Ops[1], Align, "vld_dup");
       Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
       Ops[0] =3D Builder.CreateBitCast(Ops[0], Ty);
@@ -1603,10 +1826,10 @@
       Int =3D Intrinsic::arm_neon_vld2lane;=20
       break;
     case ARM::BI__builtin_neon_vld3_dup_v:
-      Int =3D Intrinsic::arm_neon_vld2lane;=20
+      Int =3D Intrinsic::arm_neon_vld3lane;=20
       break;
     case ARM::BI__builtin_neon_vld4_dup_v:
-      Int =3D Intrinsic::arm_neon_vld2lane;=20
+      Int =3D Intrinsic::arm_neon_vld4lane;=20
       break;
     default: llvm_unreachable("unknown vld_dup intrinsic?");
     }
@@ -1619,7 +1842,7 @@
=20
     llvm::Constant *CI =3D ConstantInt::get(Int32Ty, 0);
     Args.push_back(CI);
-    Args.push_back(GetPointeeAlignment(*this, E->getArg(1)));
+    Args.push_back(GetPointeeAlignmentValue(E->getArg(1)));
    =20
     Ops[1] =3D Builder.CreateCall(F, Args, "vld_dup");
     // splat lane 0 to all elts in each vector of the result.
@@ -1656,12 +1879,12 @@
   }
   case ARM::BI__builtin_neon_vmul_v:
   case ARM::BI__builtin_neon_vmulq_v:
-    assert(poly && "vmul builtin only supported for polynomial types");
+    assert(Type.isPoly() && "vmul builtin only supported for polynomial ty=
pes");
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vmulp, Ty),
                         Ops, "vmul");
   case ARM::BI__builtin_neon_vmull_v:
     Int =3D usgn ? Intrinsic::arm_neon_vmullu : Intrinsic::arm_neon_vmulls;
-    Int =3D poly ? (unsigned)Intrinsic::arm_neon_vmullp : Int;
+    Int =3D Type.isPoly() ? (unsigned)Intrinsic::arm_neon_vmullp : Int;
     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmull");
   case ARM::BI__builtin_neon_vpadal_v:
   case ARM::BI__builtin_neon_vpadalq_v: {
@@ -1852,43 +2075,48 @@
     return Builder.CreateAdd(Ops[0], Ops[1]);
   case ARM::BI__builtin_neon_vst1_v:
   case ARM::BI__builtin_neon_vst1q_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst1, Ty),
                         Ops, "");
   case ARM::BI__builtin_neon_vst1_lane_v:
-  case ARM::BI__builtin_neon_vst1q_lane_v:
+  case ARM::BI__builtin_neon_vst1q_lane_v: {
     Ops[1] =3D Builder.CreateBitCast(Ops[1], Ty);
     Ops[1] =3D Builder.CreateExtractElement(Ops[1], Ops[2]);
     Ty =3D llvm::PointerType::getUnqual(Ops[1]->getType());
-    return Builder.CreateStore(Ops[1], Builder.CreateBitCast(Ops[0], Ty));
+    StoreInst *St =3D Builder.CreateStore(Ops[1],
+                                        Builder.CreateBitCast(Ops[0], Ty));
+    Value *Align =3D GetPointeeAlignmentValue(E->getArg(0));
+    St->setAlignment(cast<ConstantInt>(Align)->getZExtValue());
+    return St;
+  }
   case ARM::BI__builtin_neon_vst2_v:
   case ARM::BI__builtin_neon_vst2q_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst2, Ty),
                         Ops, "");
   case ARM::BI__builtin_neon_vst2_lane_v:
   case ARM::BI__builtin_neon_vst2q_lane_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst2lane, Ty),
                         Ops, "");
   case ARM::BI__builtin_neon_vst3_v:
   case ARM::BI__builtin_neon_vst3q_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst3, Ty),
                         Ops, "");
   case ARM::BI__builtin_neon_vst3_lane_v:
   case ARM::BI__builtin_neon_vst3q_lane_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst3lane, Ty),
                         Ops, "");
   case ARM::BI__builtin_neon_vst4_v:
   case ARM::BI__builtin_neon_vst4q_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst4, Ty),
                         Ops, "");
   case ARM::BI__builtin_neon_vst4_lane_v:
   case ARM::BI__builtin_neon_vst4q_lane_v:
-    Ops.push_back(GetPointeeAlignment(*this, E->getArg(0)));
+    Ops.push_back(GetPointeeAlignmentValue(E->getArg(0)));
     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst4lane, Ty),
                         Ops, "");
   case ARM::BI__builtin_neon_vsubhn_v:
@@ -1937,8 +2165,8 @@
     for (unsigned vi =3D 0; vi !=3D 2; ++vi) {
       SmallVector<Constant*, 16> Indices;
       for (unsigned i =3D 0, e =3D VTy->getNumElements(); i !=3D e; i +=3D=
 2) {
-        Indices.push_back(ConstantInt::get(Int32Ty, i+vi));
-        Indices.push_back(ConstantInt::get(Int32Ty, i+e+vi));
+        Indices.push_back(Builder.getInt32(i+vi));
+        Indices.push_back(Builder.getInt32(i+e+vi));
       }
       Value *Addr =3D Builder.CreateConstInBoundsGEP1_32(Ops[0], vi);
       SV =3D llvm::ConstantVector::get(Indices);
@@ -1990,7 +2218,7 @@
 }
=20
 llvm::Value *CodeGenFunction::
-BuildVector(const SmallVectorImpl<llvm::Value*> &Ops) {
+BuildVector(ArrayRef<llvm::Value*> Ops) {
   assert((Ops.size() & (Ops.size() - 1)) =3D=3D 0 &&
          "Not a power-of-two sized vector!");
   bool AllConstants =3D true;
@@ -1999,7 +2227,7 @@
=20
   // If this is a constant vector, create a ConstantVector.
   if (AllConstants) {
-    std::vector<llvm::Constant*> CstOps;
+    SmallVector<llvm::Constant*, 16> CstOps;
     for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i)
       CstOps.push_back(cast<Constant>(Ops[i]));
     return llvm::ConstantVector::get(CstOps);
@@ -2010,8 +2238,7 @@
     llvm::UndefValue::get(llvm::VectorType::get(Ops[0]->getType(), Ops.siz=
e()));
=20
   for (unsigned i =3D 0, e =3D Ops.size(); i !=3D e; ++i)
-    Result =3D Builder.CreateInsertElement(Result, Ops[i],
-               llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContex=
t()), i));
+    Result =3D Builder.CreateInsertElement(Result, Ops[i], Builder.getInt3=
2(i));
=20
   return Result;
 }
@@ -2043,61 +2270,6 @@
=20
   switch (BuiltinID) {
   default: return 0;
-  case X86::BI__builtin_ia32_pslldi128:
-  case X86::BI__builtin_ia32_psllqi128:
-  case X86::BI__builtin_ia32_psllwi128:
-  case X86::BI__builtin_ia32_psradi128:
-  case X86::BI__builtin_ia32_psrawi128:
-  case X86::BI__builtin_ia32_psrldi128:
-  case X86::BI__builtin_ia32_psrlqi128:
-  case X86::BI__builtin_ia32_psrlwi128: {
-    Ops[1] =3D Builder.CreateZExt(Ops[1], Int64Ty, "zext");
-    llvm::Type *Ty =3D llvm::VectorType::get(Int64Ty, 2);
-    llvm::Value *Zero =3D llvm::ConstantInt::get(Int32Ty, 0);
-    Ops[1] =3D Builder.CreateInsertElement(llvm::UndefValue::get(Ty),
-                                         Ops[1], Zero, "insert");
-    Ops[1] =3D Builder.CreateBitCast(Ops[1], Ops[0]->getType(), "bitcast");
-    const char *name =3D 0;
-    Intrinsic::ID ID =3D Intrinsic::not_intrinsic;
-
-    switch (BuiltinID) {
-    default: llvm_unreachable("Unsupported shift intrinsic!");
-    case X86::BI__builtin_ia32_pslldi128:
-      name =3D "pslldi";
-      ID =3D Intrinsic::x86_sse2_psll_d;
-      break;
-    case X86::BI__builtin_ia32_psllqi128:
-      name =3D "psllqi";
-      ID =3D Intrinsic::x86_sse2_psll_q;
-      break;
-    case X86::BI__builtin_ia32_psllwi128:
-      name =3D "psllwi";
-      ID =3D Intrinsic::x86_sse2_psll_w;
-      break;
-    case X86::BI__builtin_ia32_psradi128:
-      name =3D "psradi";
-      ID =3D Intrinsic::x86_sse2_psra_d;
-      break;
-    case X86::BI__builtin_ia32_psrawi128:
-      name =3D "psrawi";
-      ID =3D Intrinsic::x86_sse2_psra_w;
-      break;
-    case X86::BI__builtin_ia32_psrldi128:
-      name =3D "psrldi";
-      ID =3D Intrinsic::x86_sse2_psrl_d;
-      break;
-    case X86::BI__builtin_ia32_psrlqi128:
-      name =3D "psrlqi";
-      ID =3D Intrinsic::x86_sse2_psrl_q;
-      break;
-    case X86::BI__builtin_ia32_psrlwi128:
-      name =3D "psrlwi";
-      ID =3D Intrinsic::x86_sse2_psrl_w;
-      break;
-    }
-    llvm::Function *F =3D CGM.getIntrinsic(ID);
-    return Builder.CreateCall(F, Ops, name);
-  }
   case X86::BI__builtin_ia32_vec_init_v8qi:
   case X86::BI__builtin_ia32_vec_init_v4hi:
   case X86::BI__builtin_ia32_vec_init_v2si:
@@ -2106,66 +2278,6 @@
   case X86::BI__builtin_ia32_vec_ext_v2si:
     return Builder.CreateExtractElement(Ops[0],
                                   llvm::ConstantInt::get(Ops[1]->getType()=
, 0));
-  case X86::BI__builtin_ia32_pslldi:
-  case X86::BI__builtin_ia32_psllqi:
-  case X86::BI__builtin_ia32_psllwi:
-  case X86::BI__builtin_ia32_psradi:
-  case X86::BI__builtin_ia32_psrawi:
-  case X86::BI__builtin_ia32_psrldi:
-  case X86::BI__builtin_ia32_psrlqi:
-  case X86::BI__builtin_ia32_psrlwi: {
-    Ops[1] =3D Builder.CreateZExt(Ops[1], Int64Ty, "zext");
-    llvm::Type *Ty =3D llvm::VectorType::get(Int64Ty, 1);
-    Ops[1] =3D Builder.CreateBitCast(Ops[1], Ty, "bitcast");
-    const char *name =3D 0;
-    Intrinsic::ID ID =3D Intrinsic::not_intrinsic;
-
-    switch (BuiltinID) {
-    default: llvm_unreachable("Unsupported shift intrinsic!");
-    case X86::BI__builtin_ia32_pslldi:
-      name =3D "pslldi";
-      ID =3D Intrinsic::x86_mmx_psll_d;
-      break;
-    case X86::BI__builtin_ia32_psllqi:
-      name =3D "psllqi";
-      ID =3D Intrinsic::x86_mmx_psll_q;
-      break;
-    case X86::BI__builtin_ia32_psllwi:
-      name =3D "psllwi";
-      ID =3D Intrinsic::x86_mmx_psll_w;
-      break;
-    case X86::BI__builtin_ia32_psradi:
-      name =3D "psradi";
-      ID =3D Intrinsic::x86_mmx_psra_d;
-      break;
-    case X86::BI__builtin_ia32_psrawi:
-      name =3D "psrawi";
-      ID =3D Intrinsic::x86_mmx_psra_w;
-      break;
-    case X86::BI__builtin_ia32_psrldi:
-      name =3D "psrldi";
-      ID =3D Intrinsic::x86_mmx_psrl_d;
-      break;
-    case X86::BI__builtin_ia32_psrlqi:
-      name =3D "psrlqi";
-      ID =3D Intrinsic::x86_mmx_psrl_q;
-      break;
-    case X86::BI__builtin_ia32_psrlwi:
-      name =3D "psrlwi";
-      ID =3D Intrinsic::x86_mmx_psrl_w;
-      break;
-    }
-    llvm::Function *F =3D CGM.getIntrinsic(ID);
-    return Builder.CreateCall(F, Ops, name);
-  }
-  case X86::BI__builtin_ia32_cmpps: {
-    llvm::Function *F =3D CGM.getIntrinsic(Intrinsic::x86_sse_cmp_ps);
-    return Builder.CreateCall(F, Ops, "cmpps");
-  }
-  case X86::BI__builtin_ia32_cmpss: {
-    llvm::Function *F =3D CGM.getIntrinsic(Intrinsic::x86_sse_cmp_ss);
-    return Builder.CreateCall(F, Ops, "cmpss");
-  }
   case X86::BI__builtin_ia32_ldmxcsr: {
     llvm::Type *PtrTy =3D Int8PtrTy;
     Value *One =3D llvm::ConstantInt::get(Int32Ty, 1);
@@ -2182,14 +2294,6 @@
                        Builder.CreateBitCast(Tmp, PtrTy));
     return Builder.CreateLoad(Tmp, "stmxcsr");
   }
-  case X86::BI__builtin_ia32_cmppd: {
-    llvm::Function *F =3D CGM.getIntrinsic(Intrinsic::x86_sse2_cmp_pd);
-    return Builder.CreateCall(F, Ops, "cmppd");
-  }
-  case X86::BI__builtin_ia32_cmpsd: {
-    llvm::Function *F =3D CGM.getIntrinsic(Intrinsic::x86_sse2_cmp_sd);
-    return Builder.CreateCall(F, Ops, "cmpsd");
-  }
   case X86::BI__builtin_ia32_storehps:
   case X86::BI__builtin_ia32_storelps: {
     llvm::Type *PtrTy =3D llvm::PointerType::getUnqual(Int64Ty);
@@ -2268,6 +2372,44 @@
     // If palignr is shifting the pair of vectors more than 32 bytes, emit=
 zero.
     return llvm::Constant::getNullValue(ConvertType(E->getType()));
   }
+  case X86::BI__builtin_ia32_palignr256: {
+    unsigned shiftVal =3D cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
+
+    // If palignr is shifting the pair of input vectors less than 17 bytes,
+    // emit a shuffle instruction.
+    if (shiftVal <=3D 16) {
+      SmallVector<llvm::Constant*, 32> Indices;
+      // 256-bit palignr operates on 128-bit lanes so we need to handle th=
at
+      for (unsigned l =3D 0; l !=3D 2; ++l) {
+        unsigned LaneStart =3D l * 16;
+        unsigned LaneEnd =3D (l+1) * 16;
+        for (unsigned i =3D 0; i !=3D 16; ++i) {
+          unsigned Idx =3D shiftVal + i + LaneStart;
+          if (Idx >=3D LaneEnd) Idx +=3D 16; // end of lane, switch operand
+          Indices.push_back(llvm::ConstantInt::get(Int32Ty, Idx));
+        }
+      }
+
+      Value* SV =3D llvm::ConstantVector::get(Indices);
+      return Builder.CreateShuffleVector(Ops[1], Ops[0], SV, "palignr");
+    }
+
+    // If palignr is shifting the pair of input vectors more than 16 but l=
ess
+    // than 32 bytes, emit a logical right shift of the destination.
+    if (shiftVal < 32) {
+      llvm::Type *VecTy =3D llvm::VectorType::get(Int64Ty, 4);
+
+      Ops[0] =3D Builder.CreateBitCast(Ops[0], VecTy, "cast");
+      Ops[1] =3D llvm::ConstantInt::get(Int32Ty, (shiftVal-16) * 8);
+
+      // create i32 constant
+      llvm::Function *F =3D CGM.getIntrinsic(Intrinsic::x86_avx2_psrl_dq);
+      return Builder.CreateCall(F, makeArrayRef(&Ops[0], 2), "palignr");
+    }
+
+    // If palignr is shifting the pair of vectors more than 32 bytes, emit=
 zero.
+    return llvm::Constant::getNullValue(ConvertType(E->getType()));
+  }
   case X86::BI__builtin_ia32_movntps:
   case X86::BI__builtin_ia32_movntpd:
   case X86::BI__builtin_ia32_movntdq:
@@ -2285,140 +2427,2013 @@
     return SI;
   }
   // 3DNow!
-  case X86::BI__builtin_ia32_pavgusb:
-  case X86::BI__builtin_ia32_pf2id:
-  case X86::BI__builtin_ia32_pfacc:
-  case X86::BI__builtin_ia32_pfadd:
-  case X86::BI__builtin_ia32_pfcmpeq:
-  case X86::BI__builtin_ia32_pfcmpge:
-  case X86::BI__builtin_ia32_pfcmpgt:
-  case X86::BI__builtin_ia32_pfmax:
-  case X86::BI__builtin_ia32_pfmin:
-  case X86::BI__builtin_ia32_pfmul:
-  case X86::BI__builtin_ia32_pfrcp:
-  case X86::BI__builtin_ia32_pfrcpit1:
-  case X86::BI__builtin_ia32_pfrcpit2:
-  case X86::BI__builtin_ia32_pfrsqrt:
-  case X86::BI__builtin_ia32_pfrsqit1:
-  case X86::BI__builtin_ia32_pfrsqrtit1:
-  case X86::BI__builtin_ia32_pfsub:
-  case X86::BI__builtin_ia32_pfsubr:
-  case X86::BI__builtin_ia32_pi2fd:
-  case X86::BI__builtin_ia32_pmulhrw:
-  case X86::BI__builtin_ia32_pf2iw:
-  case X86::BI__builtin_ia32_pfnacc:
-  case X86::BI__builtin_ia32_pfpnacc:
-  case X86::BI__builtin_ia32_pi2fw:
   case X86::BI__builtin_ia32_pswapdsf:
   case X86::BI__builtin_ia32_pswapdsi: {
     const char *name =3D 0;
     Intrinsic::ID ID =3D Intrinsic::not_intrinsic;
     switch(BuiltinID) {
-    case X86::BI__builtin_ia32_pavgusb:
-      name =3D "pavgusb";
-      ID =3D Intrinsic::x86_3dnow_pavgusb;
-      break;
-    case X86::BI__builtin_ia32_pf2id:
-      name =3D "pf2id";
-      ID =3D Intrinsic::x86_3dnow_pf2id;
-      break;
-    case X86::BI__builtin_ia32_pfacc:
-      name =3D "pfacc";
-      ID =3D Intrinsic::x86_3dnow_pfacc;
-      break;
-    case X86::BI__builtin_ia32_pfadd:
-      name =3D "pfadd";
-      ID =3D Intrinsic::x86_3dnow_pfadd;
-      break;
-    case X86::BI__builtin_ia32_pfcmpeq:
-      name =3D "pfcmpeq";
-      ID =3D Intrinsic::x86_3dnow_pfcmpeq;
-      break;
-    case X86::BI__builtin_ia32_pfcmpge:
-      name =3D "pfcmpge";
-      ID =3D Intrinsic::x86_3dnow_pfcmpge;
-      break;
-    case X86::BI__builtin_ia32_pfcmpgt:
-      name =3D "pfcmpgt";
-      ID =3D Intrinsic::x86_3dnow_pfcmpgt;
-      break;
-    case X86::BI__builtin_ia32_pfmax:
-      name =3D "pfmax";
-      ID =3D Intrinsic::x86_3dnow_pfmax;
-      break;
-    case X86::BI__builtin_ia32_pfmin:
-      name =3D "pfmin";
-      ID =3D Intrinsic::x86_3dnow_pfmin;
-      break;
-    case X86::BI__builtin_ia32_pfmul:
-      name =3D "pfmul";
-      ID =3D Intrinsic::x86_3dnow_pfmul;
-      break;
-    case X86::BI__builtin_ia32_pfrcp:
-      name =3D "pfrcp";
-      ID =3D Intrinsic::x86_3dnow_pfrcp;
-      break;
-    case X86::BI__builtin_ia32_pfrcpit1:
-      name =3D "pfrcpit1";
-      ID =3D Intrinsic::x86_3dnow_pfrcpit1;
-      break;
-    case X86::BI__builtin_ia32_pfrcpit2:
-      name =3D "pfrcpit2";
-      ID =3D Intrinsic::x86_3dnow_pfrcpit2;
-      break;
-    case X86::BI__builtin_ia32_pfrsqrt:
-      name =3D "pfrsqrt";
-      ID =3D Intrinsic::x86_3dnow_pfrsqrt;
-      break;
-    case X86::BI__builtin_ia32_pfrsqit1:
-    case X86::BI__builtin_ia32_pfrsqrtit1:
-      name =3D "pfrsqit1";
-      ID =3D Intrinsic::x86_3dnow_pfrsqit1;
-      break;
-    case X86::BI__builtin_ia32_pfsub:
-      name =3D "pfsub";
-      ID =3D Intrinsic::x86_3dnow_pfsub;
-      break;
-    case X86::BI__builtin_ia32_pfsubr:
-      name =3D "pfsubr";
-      ID =3D Intrinsic::x86_3dnow_pfsubr;
-      break;
-    case X86::BI__builtin_ia32_pi2fd:
-      name =3D "pi2fd";
-      ID =3D Intrinsic::x86_3dnow_pi2fd;
-      break;
-    case X86::BI__builtin_ia32_pmulhrw:
-      name =3D "pmulhrw";
-      ID =3D Intrinsic::x86_3dnow_pmulhrw;
-      break;
-    case X86::BI__builtin_ia32_pf2iw:
-      name =3D "pf2iw";
-      ID =3D Intrinsic::x86_3dnowa_pf2iw;
-      break;
-    case X86::BI__builtin_ia32_pfnacc:
-      name =3D "pfnacc";
-      ID =3D Intrinsic::x86_3dnowa_pfnacc;
-      break;
-    case X86::BI__builtin_ia32_pfpnacc:
-      name =3D "pfpnacc";
-      ID =3D Intrinsic::x86_3dnowa_pfpnacc;
-      break;
-    case X86::BI__builtin_ia32_pi2fw:
-      name =3D "pi2fw";
-      ID =3D Intrinsic::x86_3dnowa_pi2fw;
-      break;
+    default: llvm_unreachable("Unsupported intrinsic!");
     case X86::BI__builtin_ia32_pswapdsf:
     case X86::BI__builtin_ia32_pswapdsi:
       name =3D "pswapd";
       ID =3D Intrinsic::x86_3dnowa_pswapd;
       break;
     }
+    llvm::Type *MMXTy =3D llvm::Type::getX86_MMXTy(getLLVMContext());
+    Ops[0] =3D Builder.CreateBitCast(Ops[0], MMXTy, "cast");
     llvm::Function *F =3D CGM.getIntrinsic(ID);
     return Builder.CreateCall(F, Ops, name);
   }
   }
 }
=20
+
+Value *CodeGenFunction::EmitHexagonBuiltinExpr(unsigned BuiltinID,
+                                             const CallExpr *E) {
+  llvm::SmallVector<Value*, 4> Ops;
+
+  for (unsigned i =3D 0, e =3D E->getNumArgs(); i !=3D e; i++)
+    Ops.push_back(EmitScalarExpr(E->getArg(i)));
+
+  Intrinsic::ID ID =3D Intrinsic::not_intrinsic;
+
+  switch (BuiltinID) {
+  default: return 0;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpeq:
+    ID =3D Intrinsic::hexagon_C2_cmpeq; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgt:
+    ID =3D Intrinsic::hexagon_C2_cmpgt; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgtu:
+    ID =3D Intrinsic::hexagon_C2_cmpgtu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpeqp:
+    ID =3D Intrinsic::hexagon_C2_cmpeqp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgtp:
+    ID =3D Intrinsic::hexagon_C2_cmpgtp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgtup:
+    ID =3D Intrinsic::hexagon_C2_cmpgtup; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_bitsset:
+    ID =3D Intrinsic::hexagon_C2_bitsset; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_bitsclr:
+    ID =3D Intrinsic::hexagon_C2_bitsclr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpeqi:
+    ID =3D Intrinsic::hexagon_C2_cmpeqi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgti:
+    ID =3D Intrinsic::hexagon_C2_cmpgti; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgtui:
+    ID =3D Intrinsic::hexagon_C2_cmpgtui; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgei:
+    ID =3D Intrinsic::hexagon_C2_cmpgei; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpgeui:
+    ID =3D Intrinsic::hexagon_C2_cmpgeui; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmplt:
+    ID =3D Intrinsic::hexagon_C2_cmplt; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_cmpltu:
+    ID =3D Intrinsic::hexagon_C2_cmpltu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_bitsclri:
+    ID =3D Intrinsic::hexagon_C2_bitsclri; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_and:
+    ID =3D Intrinsic::hexagon_C2_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_or:
+    ID =3D Intrinsic::hexagon_C2_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_xor:
+    ID =3D Intrinsic::hexagon_C2_xor; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_andn:
+    ID =3D Intrinsic::hexagon_C2_andn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_not:
+    ID =3D Intrinsic::hexagon_C2_not; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_orn:
+    ID =3D Intrinsic::hexagon_C2_orn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_pxfer_map:
+    ID =3D Intrinsic::hexagon_C2_pxfer_map; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_any8:
+    ID =3D Intrinsic::hexagon_C2_any8; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_all8:
+    ID =3D Intrinsic::hexagon_C2_all8; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_vitpack:
+    ID =3D Intrinsic::hexagon_C2_vitpack; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_mux:
+    ID =3D Intrinsic::hexagon_C2_mux; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_muxii:
+    ID =3D Intrinsic::hexagon_C2_muxii; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_muxir:
+    ID =3D Intrinsic::hexagon_C2_muxir; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_muxri:
+    ID =3D Intrinsic::hexagon_C2_muxri; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_vmux:
+    ID =3D Intrinsic::hexagon_C2_vmux; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_mask:
+    ID =3D Intrinsic::hexagon_C2_mask; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmpbeq:
+    ID =3D Intrinsic::hexagon_A2_vcmpbeq; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmpbgtu:
+    ID =3D Intrinsic::hexagon_A2_vcmpbgtu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmpheq:
+    ID =3D Intrinsic::hexagon_A2_vcmpheq; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmphgt:
+    ID =3D Intrinsic::hexagon_A2_vcmphgt; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmphgtu:
+    ID =3D Intrinsic::hexagon_A2_vcmphgtu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmpweq:
+    ID =3D Intrinsic::hexagon_A2_vcmpweq; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmpwgt:
+    ID =3D Intrinsic::hexagon_A2_vcmpwgt; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vcmpwgtu:
+    ID =3D Intrinsic::hexagon_A2_vcmpwgtu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_tfrpr:
+    ID =3D Intrinsic::hexagon_C2_tfrpr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C2_tfrrp:
+    ID =3D Intrinsic::hexagon_C2_tfrrp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_acc_sat_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_acc_sat_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_nac_sat_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_nac_sat_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_rnd_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_rnd_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_sat_rnd_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpy_sat_rnd_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_acc_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_acc_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_nac_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_nac_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyd_rnd_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyd_rnd_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_acc_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_acc_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_nac_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_nac_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyu_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyu_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_acc_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_acc_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_nac_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_nac_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_hh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_hh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_hh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_hh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_hl_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_hl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_hl_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_hl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_lh_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_lh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_lh_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_lh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_ll_s0:
+    ID =3D Intrinsic::hexagon_M2_mpyud_ll_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyud_ll_s1:
+    ID =3D Intrinsic::hexagon_M2_mpyud_ll_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpysmi:
+    ID =3D Intrinsic::hexagon_M2_mpysmi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_macsip:
+    ID =3D Intrinsic::hexagon_M2_macsip; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_macsin:
+    ID =3D Intrinsic::hexagon_M2_macsin; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_dpmpyss_s0:
+    ID =3D Intrinsic::hexagon_M2_dpmpyss_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_dpmpyss_acc_s0:
+    ID =3D Intrinsic::hexagon_M2_dpmpyss_acc_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_dpmpyss_nac_s0:
+    ID =3D Intrinsic::hexagon_M2_dpmpyss_nac_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_dpmpyuu_s0:
+    ID =3D Intrinsic::hexagon_M2_dpmpyuu_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_dpmpyuu_acc_s0:
+    ID =3D Intrinsic::hexagon_M2_dpmpyuu_acc_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_dpmpyuu_nac_s0:
+    ID =3D Intrinsic::hexagon_M2_dpmpyuu_nac_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpy_up:
+    ID =3D Intrinsic::hexagon_M2_mpy_up; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyu_up:
+    ID =3D Intrinsic::hexagon_M2_mpyu_up; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_dpmpyss_rnd_s0:
+    ID =3D Intrinsic::hexagon_M2_dpmpyss_rnd_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyi:
+    ID =3D Intrinsic::hexagon_M2_mpyi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mpyui:
+    ID =3D Intrinsic::hexagon_M2_mpyui; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_maci:
+    ID =3D Intrinsic::hexagon_M2_maci; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_acci:
+    ID =3D Intrinsic::hexagon_M2_acci; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_accii:
+    ID =3D Intrinsic::hexagon_M2_accii; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_nacci:
+    ID =3D Intrinsic::hexagon_M2_nacci; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_naccii:
+    ID =3D Intrinsic::hexagon_M2_naccii; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_subacc:
+    ID =3D Intrinsic::hexagon_M2_subacc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmpy2s_s0:
+    ID =3D Intrinsic::hexagon_M2_vmpy2s_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmpy2s_s1:
+    ID =3D Intrinsic::hexagon_M2_vmpy2s_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmac2s_s0:
+    ID =3D Intrinsic::hexagon_M2_vmac2s_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmac2s_s1:
+    ID =3D Intrinsic::hexagon_M2_vmac2s_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmpy2s_s0pack:
+    ID =3D Intrinsic::hexagon_M2_vmpy2s_s0pack; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmpy2s_s1pack:
+    ID =3D Intrinsic::hexagon_M2_vmpy2s_s1pack; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmac2:
+    ID =3D Intrinsic::hexagon_M2_vmac2; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmpy2es_s0:
+    ID =3D Intrinsic::hexagon_M2_vmpy2es_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmpy2es_s1:
+    ID =3D Intrinsic::hexagon_M2_vmpy2es_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmac2es_s0:
+    ID =3D Intrinsic::hexagon_M2_vmac2es_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmac2es_s1:
+    ID =3D Intrinsic::hexagon_M2_vmac2es_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vmac2es:
+    ID =3D Intrinsic::hexagon_M2_vmac2es; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrmac_s0:
+    ID =3D Intrinsic::hexagon_M2_vrmac_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrmpy_s0:
+    ID =3D Intrinsic::hexagon_M2_vrmpy_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vdmpyrs_s0:
+    ID =3D Intrinsic::hexagon_M2_vdmpyrs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vdmpyrs_s1:
+    ID =3D Intrinsic::hexagon_M2_vdmpyrs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vdmacs_s0:
+    ID =3D Intrinsic::hexagon_M2_vdmacs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vdmacs_s1:
+    ID =3D Intrinsic::hexagon_M2_vdmacs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vdmpys_s0:
+    ID =3D Intrinsic::hexagon_M2_vdmpys_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vdmpys_s1:
+    ID =3D Intrinsic::hexagon_M2_vdmpys_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpyrs_s0:
+    ID =3D Intrinsic::hexagon_M2_cmpyrs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpyrs_s1:
+    ID =3D Intrinsic::hexagon_M2_cmpyrs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpyrsc_s0:
+    ID =3D Intrinsic::hexagon_M2_cmpyrsc_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpyrsc_s1:
+    ID =3D Intrinsic::hexagon_M2_cmpyrsc_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmacs_s0:
+    ID =3D Intrinsic::hexagon_M2_cmacs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmacs_s1:
+    ID =3D Intrinsic::hexagon_M2_cmacs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmacsc_s0:
+    ID =3D Intrinsic::hexagon_M2_cmacsc_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmacsc_s1:
+    ID =3D Intrinsic::hexagon_M2_cmacsc_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpys_s0:
+    ID =3D Intrinsic::hexagon_M2_cmpys_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpys_s1:
+    ID =3D Intrinsic::hexagon_M2_cmpys_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpysc_s0:
+    ID =3D Intrinsic::hexagon_M2_cmpysc_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpysc_s1:
+    ID =3D Intrinsic::hexagon_M2_cmpysc_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cnacs_s0:
+    ID =3D Intrinsic::hexagon_M2_cnacs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cnacs_s1:
+    ID =3D Intrinsic::hexagon_M2_cnacs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cnacsc_s0:
+    ID =3D Intrinsic::hexagon_M2_cnacsc_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cnacsc_s1:
+    ID =3D Intrinsic::hexagon_M2_cnacsc_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmpys_s1:
+    ID =3D Intrinsic::hexagon_M2_vrcmpys_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmpys_acc_s1:
+    ID =3D Intrinsic::hexagon_M2_vrcmpys_acc_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmpys_s1rp:
+    ID =3D Intrinsic::hexagon_M2_vrcmpys_s1rp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacls_s0:
+    ID =3D Intrinsic::hexagon_M2_mmacls_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacls_s1:
+    ID =3D Intrinsic::hexagon_M2_mmacls_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmachs_s0:
+    ID =3D Intrinsic::hexagon_M2_mmachs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmachs_s1:
+    ID =3D Intrinsic::hexagon_M2_mmachs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyl_s0:
+    ID =3D Intrinsic::hexagon_M2_mmpyl_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyl_s1:
+    ID =3D Intrinsic::hexagon_M2_mmpyl_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyh_s0:
+    ID =3D Intrinsic::hexagon_M2_mmpyh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyh_s1:
+    ID =3D Intrinsic::hexagon_M2_mmpyh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacls_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmacls_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacls_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmacls_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmachs_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmachs_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmachs_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmachs_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyl_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmpyl_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyl_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmpyl_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyh_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmpyh_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyh_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmpyh_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_hmmpyl_rs1:
+    ID =3D Intrinsic::hexagon_M2_hmmpyl_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_hmmpyh_rs1:
+    ID =3D Intrinsic::hexagon_M2_hmmpyh_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmaculs_s0:
+    ID =3D Intrinsic::hexagon_M2_mmaculs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmaculs_s1:
+    ID =3D Intrinsic::hexagon_M2_mmaculs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacuhs_s0:
+    ID =3D Intrinsic::hexagon_M2_mmacuhs_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacuhs_s1:
+    ID =3D Intrinsic::hexagon_M2_mmacuhs_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyul_s0:
+    ID =3D Intrinsic::hexagon_M2_mmpyul_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyul_s1:
+    ID =3D Intrinsic::hexagon_M2_mmpyul_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyuh_s0:
+    ID =3D Intrinsic::hexagon_M2_mmpyuh_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyuh_s1:
+    ID =3D Intrinsic::hexagon_M2_mmpyuh_s1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmaculs_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmaculs_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmaculs_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmaculs_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacuhs_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmacuhs_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmacuhs_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmacuhs_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyul_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmpyul_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyul_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmpyul_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyuh_rs0:
+    ID =3D Intrinsic::hexagon_M2_mmpyuh_rs0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_mmpyuh_rs1:
+    ID =3D Intrinsic::hexagon_M2_mmpyuh_rs1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmaci_s0:
+    ID =3D Intrinsic::hexagon_M2_vrcmaci_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmacr_s0:
+    ID =3D Intrinsic::hexagon_M2_vrcmacr_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmaci_s0c:
+    ID =3D Intrinsic::hexagon_M2_vrcmaci_s0c; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmacr_s0c:
+    ID =3D Intrinsic::hexagon_M2_vrcmacr_s0c; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmaci_s0:
+    ID =3D Intrinsic::hexagon_M2_cmaci_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmacr_s0:
+    ID =3D Intrinsic::hexagon_M2_cmacr_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmpyi_s0:
+    ID =3D Intrinsic::hexagon_M2_vrcmpyi_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmpyr_s0:
+    ID =3D Intrinsic::hexagon_M2_vrcmpyr_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmpyi_s0c:
+    ID =3D Intrinsic::hexagon_M2_vrcmpyi_s0c; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vrcmpyr_s0c:
+    ID =3D Intrinsic::hexagon_M2_vrcmpyr_s0c; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpyi_s0:
+    ID =3D Intrinsic::hexagon_M2_cmpyi_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_cmpyr_s0:
+    ID =3D Intrinsic::hexagon_M2_cmpyr_s0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vcmpy_s0_sat_i:
+    ID =3D Intrinsic::hexagon_M2_vcmpy_s0_sat_i; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vcmpy_s0_sat_r:
+    ID =3D Intrinsic::hexagon_M2_vcmpy_s0_sat_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vcmpy_s1_sat_i:
+    ID =3D Intrinsic::hexagon_M2_vcmpy_s1_sat_i; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vcmpy_s1_sat_r:
+    ID =3D Intrinsic::hexagon_M2_vcmpy_s1_sat_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vcmac_s0_sat_i:
+    ID =3D Intrinsic::hexagon_M2_vcmac_s0_sat_i; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vcmac_s0_sat_r:
+    ID =3D Intrinsic::hexagon_M2_vcmac_s0_sat_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vcrotate:
+    ID =3D Intrinsic::hexagon_S2_vcrotate; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_add:
+    ID =3D Intrinsic::hexagon_A2_add; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_sub:
+    ID =3D Intrinsic::hexagon_A2_sub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addsat:
+    ID =3D Intrinsic::hexagon_A2_addsat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subsat:
+    ID =3D Intrinsic::hexagon_A2_subsat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addi:
+    ID =3D Intrinsic::hexagon_A2_addi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_l16_ll:
+    ID =3D Intrinsic::hexagon_A2_addh_l16_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_l16_hl:
+    ID =3D Intrinsic::hexagon_A2_addh_l16_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_l16_sat_ll:
+    ID =3D Intrinsic::hexagon_A2_addh_l16_sat_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_l16_sat_hl:
+    ID =3D Intrinsic::hexagon_A2_addh_l16_sat_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_l16_ll:
+    ID =3D Intrinsic::hexagon_A2_subh_l16_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_l16_hl:
+    ID =3D Intrinsic::hexagon_A2_subh_l16_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_l16_sat_ll:
+    ID =3D Intrinsic::hexagon_A2_subh_l16_sat_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_l16_sat_hl:
+    ID =3D Intrinsic::hexagon_A2_subh_l16_sat_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_ll:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_lh:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_lh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_hl:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_hh:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_hh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_sat_ll:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_sat_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_sat_lh:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_sat_lh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_sat_hl:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_sat_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addh_h16_sat_hh:
+    ID =3D Intrinsic::hexagon_A2_addh_h16_sat_hh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_ll:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_lh:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_lh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_hl:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_hh:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_hh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_sat_ll:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_sat_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_sat_lh:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_sat_lh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_sat_hl:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_sat_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subh_h16_sat_hh:
+    ID =3D Intrinsic::hexagon_A2_subh_h16_sat_hh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_aslh:
+    ID =3D Intrinsic::hexagon_A2_aslh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_asrh:
+    ID =3D Intrinsic::hexagon_A2_asrh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addp:
+    ID =3D Intrinsic::hexagon_A2_addp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addpsat:
+    ID =3D Intrinsic::hexagon_A2_addpsat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_addsp:
+    ID =3D Intrinsic::hexagon_A2_addsp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subp:
+    ID =3D Intrinsic::hexagon_A2_subp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_neg:
+    ID =3D Intrinsic::hexagon_A2_neg; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_negsat:
+    ID =3D Intrinsic::hexagon_A2_negsat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_abs:
+    ID =3D Intrinsic::hexagon_A2_abs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_abssat:
+    ID =3D Intrinsic::hexagon_A2_abssat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vconj:
+    ID =3D Intrinsic::hexagon_A2_vconj; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_negp:
+    ID =3D Intrinsic::hexagon_A2_negp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_absp:
+    ID =3D Intrinsic::hexagon_A2_absp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_max:
+    ID =3D Intrinsic::hexagon_A2_max; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_maxu:
+    ID =3D Intrinsic::hexagon_A2_maxu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_min:
+    ID =3D Intrinsic::hexagon_A2_min; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_minu:
+    ID =3D Intrinsic::hexagon_A2_minu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_maxp:
+    ID =3D Intrinsic::hexagon_A2_maxp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_maxup:
+    ID =3D Intrinsic::hexagon_A2_maxup; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_minp:
+    ID =3D Intrinsic::hexagon_A2_minp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_minup:
+    ID =3D Intrinsic::hexagon_A2_minup; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_tfr:
+    ID =3D Intrinsic::hexagon_A2_tfr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_tfrsi:
+    ID =3D Intrinsic::hexagon_A2_tfrsi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_tfrp:
+    ID =3D Intrinsic::hexagon_A2_tfrp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_tfrpi:
+    ID =3D Intrinsic::hexagon_A2_tfrpi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_zxtb:
+    ID =3D Intrinsic::hexagon_A2_zxtb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_sxtb:
+    ID =3D Intrinsic::hexagon_A2_sxtb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_zxth:
+    ID =3D Intrinsic::hexagon_A2_zxth; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_sxth:
+    ID =3D Intrinsic::hexagon_A2_sxth; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_combinew:
+    ID =3D Intrinsic::hexagon_A2_combinew; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_combineii:
+    ID =3D Intrinsic::hexagon_A2_combineii; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_combine_hh:
+    ID =3D Intrinsic::hexagon_A2_combine_hh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_combine_hl:
+    ID =3D Intrinsic::hexagon_A2_combine_hl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_combine_lh:
+    ID =3D Intrinsic::hexagon_A2_combine_lh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_combine_ll:
+    ID =3D Intrinsic::hexagon_A2_combine_ll; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_tfril:
+    ID =3D Intrinsic::hexagon_A2_tfril; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_tfrih:
+    ID =3D Intrinsic::hexagon_A2_tfrih; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_and:
+    ID =3D Intrinsic::hexagon_A2_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_or:
+    ID =3D Intrinsic::hexagon_A2_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_xor:
+    ID =3D Intrinsic::hexagon_A2_xor; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_not:
+    ID =3D Intrinsic::hexagon_A2_not; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_xor_xacc:
+    ID =3D Intrinsic::hexagon_M2_xor_xacc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_subri:
+    ID =3D Intrinsic::hexagon_A2_subri; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_andir:
+    ID =3D Intrinsic::hexagon_A2_andir; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_orir:
+    ID =3D Intrinsic::hexagon_A2_orir; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_andp:
+    ID =3D Intrinsic::hexagon_A2_andp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_orp:
+    ID =3D Intrinsic::hexagon_A2_orp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_xorp:
+    ID =3D Intrinsic::hexagon_A2_xorp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_notp:
+    ID =3D Intrinsic::hexagon_A2_notp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_sxtw:
+    ID =3D Intrinsic::hexagon_A2_sxtw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_sat:
+    ID =3D Intrinsic::hexagon_A2_sat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_sath:
+    ID =3D Intrinsic::hexagon_A2_sath; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_satuh:
+    ID =3D Intrinsic::hexagon_A2_satuh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_satub:
+    ID =3D Intrinsic::hexagon_A2_satub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_satb:
+    ID =3D Intrinsic::hexagon_A2_satb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vaddub:
+    ID =3D Intrinsic::hexagon_A2_vaddub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vaddubs:
+    ID =3D Intrinsic::hexagon_A2_vaddubs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vaddh:
+    ID =3D Intrinsic::hexagon_A2_vaddh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vaddhs:
+    ID =3D Intrinsic::hexagon_A2_vaddhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vadduhs:
+    ID =3D Intrinsic::hexagon_A2_vadduhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vaddw:
+    ID =3D Intrinsic::hexagon_A2_vaddw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vaddws:
+    ID =3D Intrinsic::hexagon_A2_vaddws; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svavgh:
+    ID =3D Intrinsic::hexagon_A2_svavgh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svavghs:
+    ID =3D Intrinsic::hexagon_A2_svavghs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svnavgh:
+    ID =3D Intrinsic::hexagon_A2_svnavgh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svaddh:
+    ID =3D Intrinsic::hexagon_A2_svaddh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svaddhs:
+    ID =3D Intrinsic::hexagon_A2_svaddhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svadduhs:
+    ID =3D Intrinsic::hexagon_A2_svadduhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svsubh:
+    ID =3D Intrinsic::hexagon_A2_svsubh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svsubhs:
+    ID =3D Intrinsic::hexagon_A2_svsubhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_svsubuhs:
+    ID =3D Intrinsic::hexagon_A2_svsubuhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vraddub:
+    ID =3D Intrinsic::hexagon_A2_vraddub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vraddub_acc:
+    ID =3D Intrinsic::hexagon_A2_vraddub_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vradduh:
+    ID =3D Intrinsic::hexagon_M2_vradduh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vsubub:
+    ID =3D Intrinsic::hexagon_A2_vsubub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vsububs:
+    ID =3D Intrinsic::hexagon_A2_vsububs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vsubh:
+    ID =3D Intrinsic::hexagon_A2_vsubh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vsubhs:
+    ID =3D Intrinsic::hexagon_A2_vsubhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vsubuhs:
+    ID =3D Intrinsic::hexagon_A2_vsubuhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vsubw:
+    ID =3D Intrinsic::hexagon_A2_vsubw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vsubws:
+    ID =3D Intrinsic::hexagon_A2_vsubws; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vabsh:
+    ID =3D Intrinsic::hexagon_A2_vabsh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vabshsat:
+    ID =3D Intrinsic::hexagon_A2_vabshsat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vabsw:
+    ID =3D Intrinsic::hexagon_A2_vabsw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vabswsat:
+    ID =3D Intrinsic::hexagon_A2_vabswsat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vabsdiffw:
+    ID =3D Intrinsic::hexagon_M2_vabsdiffw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M2_vabsdiffh:
+    ID =3D Intrinsic::hexagon_M2_vabsdiffh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vrsadub:
+    ID =3D Intrinsic::hexagon_A2_vrsadub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vrsadub_acc:
+    ID =3D Intrinsic::hexagon_A2_vrsadub_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavgub:
+    ID =3D Intrinsic::hexagon_A2_vavgub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavguh:
+    ID =3D Intrinsic::hexagon_A2_vavguh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavgh:
+    ID =3D Intrinsic::hexagon_A2_vavgh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vnavgh:
+    ID =3D Intrinsic::hexagon_A2_vnavgh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavgw:
+    ID =3D Intrinsic::hexagon_A2_vavgw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vnavgw:
+    ID =3D Intrinsic::hexagon_A2_vnavgw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavgwr:
+    ID =3D Intrinsic::hexagon_A2_vavgwr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vnavgwr:
+    ID =3D Intrinsic::hexagon_A2_vnavgwr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavgwcr:
+    ID =3D Intrinsic::hexagon_A2_vavgwcr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vnavgwcr:
+    ID =3D Intrinsic::hexagon_A2_vnavgwcr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavghcr:
+    ID =3D Intrinsic::hexagon_A2_vavghcr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vnavghcr:
+    ID =3D Intrinsic::hexagon_A2_vnavghcr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavguw:
+    ID =3D Intrinsic::hexagon_A2_vavguw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavguwr:
+    ID =3D Intrinsic::hexagon_A2_vavguwr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavgubr:
+    ID =3D Intrinsic::hexagon_A2_vavgubr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavguhr:
+    ID =3D Intrinsic::hexagon_A2_vavguhr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vavghr:
+    ID =3D Intrinsic::hexagon_A2_vavghr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vnavghr:
+    ID =3D Intrinsic::hexagon_A2_vnavghr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vminh:
+    ID =3D Intrinsic::hexagon_A2_vminh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vmaxh:
+    ID =3D Intrinsic::hexagon_A2_vmaxh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vminub:
+    ID =3D Intrinsic::hexagon_A2_vminub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vmaxub:
+    ID =3D Intrinsic::hexagon_A2_vmaxub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vminuh:
+    ID =3D Intrinsic::hexagon_A2_vminuh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vmaxuh:
+    ID =3D Intrinsic::hexagon_A2_vmaxuh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vminw:
+    ID =3D Intrinsic::hexagon_A2_vminw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vmaxw:
+    ID =3D Intrinsic::hexagon_A2_vmaxw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vminuw:
+    ID =3D Intrinsic::hexagon_A2_vminuw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_vmaxuw:
+    ID =3D Intrinsic::hexagon_A2_vmaxuw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_r:
+    ID =3D Intrinsic::hexagon_S2_asr_r_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_r:
+    ID =3D Intrinsic::hexagon_S2_asl_r_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_r:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_r:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_p:
+    ID =3D Intrinsic::hexagon_S2_asr_r_p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_p:
+    ID =3D Intrinsic::hexagon_S2_asl_r_p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_p:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_p:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_r_acc:
+    ID =3D Intrinsic::hexagon_S2_asr_r_r_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_r_acc:
+    ID =3D Intrinsic::hexagon_S2_asl_r_r_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_r_acc:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_r_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_r_acc:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_r_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_p_acc:
+    ID =3D Intrinsic::hexagon_S2_asr_r_p_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_p_acc:
+    ID =3D Intrinsic::hexagon_S2_asl_r_p_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_p_acc:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_p_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_p_acc:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_p_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_r_nac:
+    ID =3D Intrinsic::hexagon_S2_asr_r_r_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_r_nac:
+    ID =3D Intrinsic::hexagon_S2_asl_r_r_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_r_nac:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_r_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_r_nac:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_r_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_p_nac:
+    ID =3D Intrinsic::hexagon_S2_asr_r_p_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_p_nac:
+    ID =3D Intrinsic::hexagon_S2_asl_r_p_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_p_nac:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_p_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_p_nac:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_p_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_r_and:
+    ID =3D Intrinsic::hexagon_S2_asr_r_r_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_r_and:
+    ID =3D Intrinsic::hexagon_S2_asl_r_r_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_r_and:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_r_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_r_and:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_r_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_r_or:
+    ID =3D Intrinsic::hexagon_S2_asr_r_r_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_r_or:
+    ID =3D Intrinsic::hexagon_S2_asl_r_r_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_r_or:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_r_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_r_or:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_r_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_p_and:
+    ID =3D Intrinsic::hexagon_S2_asr_r_p_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_p_and:
+    ID =3D Intrinsic::hexagon_S2_asl_r_p_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_p_and:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_p_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_p_and:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_p_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_p_or:
+    ID =3D Intrinsic::hexagon_S2_asr_r_p_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_p_or:
+    ID =3D Intrinsic::hexagon_S2_asl_r_p_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_p_or:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_p_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_p_or:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_p_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_r_sat:
+    ID =3D Intrinsic::hexagon_S2_asr_r_r_sat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_r_sat:
+    ID =3D Intrinsic::hexagon_S2_asl_r_r_sat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_r:
+    ID =3D Intrinsic::hexagon_S2_asr_i_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_r:
+    ID =3D Intrinsic::hexagon_S2_asl_i_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_p:
+    ID =3D Intrinsic::hexagon_S2_asr_i_p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_p:
+    ID =3D Intrinsic::hexagon_S2_asl_i_p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc:
+    ID =3D Intrinsic::hexagon_S2_asr_i_r_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_r_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc:
+    ID =3D Intrinsic::hexagon_S2_asl_i_r_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc:
+    ID =3D Intrinsic::hexagon_S2_asr_i_p_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_p_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc:
+    ID =3D Intrinsic::hexagon_S2_asl_i_p_acc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac:
+    ID =3D Intrinsic::hexagon_S2_asr_i_r_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_r_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac:
+    ID =3D Intrinsic::hexagon_S2_asl_i_r_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac:
+    ID =3D Intrinsic::hexagon_S2_asr_i_p_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_p_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac:
+    ID =3D Intrinsic::hexagon_S2_asl_i_p_nac; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_r_xacc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc:
+    ID =3D Intrinsic::hexagon_S2_asl_i_r_xacc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_p_xacc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc:
+    ID =3D Intrinsic::hexagon_S2_asl_i_p_xacc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and:
+    ID =3D Intrinsic::hexagon_S2_asr_i_r_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_r_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and:
+    ID =3D Intrinsic::hexagon_S2_asl_i_r_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or:
+    ID =3D Intrinsic::hexagon_S2_asr_i_r_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_r_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or:
+    ID =3D Intrinsic::hexagon_S2_asl_i_r_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and:
+    ID =3D Intrinsic::hexagon_S2_asr_i_p_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_p_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and:
+    ID =3D Intrinsic::hexagon_S2_asl_i_p_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or:
+    ID =3D Intrinsic::hexagon_S2_asr_i_p_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_p_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or:
+    ID =3D Intrinsic::hexagon_S2_asl_i_p_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat:
+    ID =3D Intrinsic::hexagon_S2_asl_i_r_sat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd:
+    ID =3D Intrinsic::hexagon_S2_asr_i_r_rnd; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax:
+    ID =3D Intrinsic::hexagon_S2_asr_i_r_rnd_goodsyntax; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri:
+    ID =3D Intrinsic::hexagon_S2_addasl_rrri; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_valignib:
+    ID =3D Intrinsic::hexagon_S2_valignib; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_valignrb:
+    ID =3D Intrinsic::hexagon_S2_valignrb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vspliceib:
+    ID =3D Intrinsic::hexagon_S2_vspliceib; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsplicerb:
+    ID =3D Intrinsic::hexagon_S2_vsplicerb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsplatrh:
+    ID =3D Intrinsic::hexagon_S2_vsplatrh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsplatrb:
+    ID =3D Intrinsic::hexagon_S2_vsplatrb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_insert:
+    ID =3D Intrinsic::hexagon_S2_insert; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax:
+    ID =3D Intrinsic::hexagon_S2_tableidxb_goodsyntax; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax:
+    ID =3D Intrinsic::hexagon_S2_tableidxh_goodsyntax; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax:
+    ID =3D Intrinsic::hexagon_S2_tableidxw_goodsyntax; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax:
+    ID =3D Intrinsic::hexagon_S2_tableidxd_goodsyntax; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_extractu:
+    ID =3D Intrinsic::hexagon_S2_extractu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_insertp:
+    ID =3D Intrinsic::hexagon_S2_insertp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_extractup:
+    ID =3D Intrinsic::hexagon_S2_extractup; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_insert_rp:
+    ID =3D Intrinsic::hexagon_S2_insert_rp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_extractu_rp:
+    ID =3D Intrinsic::hexagon_S2_extractu_rp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_insertp_rp:
+    ID =3D Intrinsic::hexagon_S2_insertp_rp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_extractup_rp:
+    ID =3D Intrinsic::hexagon_S2_extractup_rp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_tstbit_i:
+    ID =3D Intrinsic::hexagon_S2_tstbit_i; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_setbit_i:
+    ID =3D Intrinsic::hexagon_S2_setbit_i; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_togglebit_i:
+    ID =3D Intrinsic::hexagon_S2_togglebit_i; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_clrbit_i:
+    ID =3D Intrinsic::hexagon_S2_clrbit_i; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_tstbit_r:
+    ID =3D Intrinsic::hexagon_S2_tstbit_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_setbit_r:
+    ID =3D Intrinsic::hexagon_S2_setbit_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_togglebit_r:
+    ID =3D Intrinsic::hexagon_S2_togglebit_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_clrbit_r:
+    ID =3D Intrinsic::hexagon_S2_clrbit_r; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh:
+    ID =3D Intrinsic::hexagon_S2_asr_i_vh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_vh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh:
+    ID =3D Intrinsic::hexagon_S2_asl_i_vh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_vh:
+    ID =3D Intrinsic::hexagon_S2_asr_r_vh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_vh:
+    ID =3D Intrinsic::hexagon_S2_asl_r_vh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_vh:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_vh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_vh:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_vh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw:
+    ID =3D Intrinsic::hexagon_S2_asr_i_vw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun:
+    ID =3D Intrinsic::hexagon_S2_asr_i_svw_trun; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_svw_trun:
+    ID =3D Intrinsic::hexagon_S2_asr_r_svw_trun; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw:
+    ID =3D Intrinsic::hexagon_S2_lsr_i_vw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw:
+    ID =3D Intrinsic::hexagon_S2_asl_i_vw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asr_r_vw:
+    ID =3D Intrinsic::hexagon_S2_asr_r_vw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_asl_r_vw:
+    ID =3D Intrinsic::hexagon_S2_asl_r_vw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsr_r_vw:
+    ID =3D Intrinsic::hexagon_S2_lsr_r_vw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lsl_r_vw:
+    ID =3D Intrinsic::hexagon_S2_lsl_r_vw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vrndpackwh:
+    ID =3D Intrinsic::hexagon_S2_vrndpackwh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vrndpackwhs:
+    ID =3D Intrinsic::hexagon_S2_vrndpackwhs; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsxtbh:
+    ID =3D Intrinsic::hexagon_S2_vsxtbh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vzxtbh:
+    ID =3D Intrinsic::hexagon_S2_vzxtbh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsathub:
+    ID =3D Intrinsic::hexagon_S2_vsathub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_svsathub:
+    ID =3D Intrinsic::hexagon_S2_svsathub; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_svsathb:
+    ID =3D Intrinsic::hexagon_S2_svsathb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsathb:
+    ID =3D Intrinsic::hexagon_S2_vsathb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vtrunohb:
+    ID =3D Intrinsic::hexagon_S2_vtrunohb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vtrunewh:
+    ID =3D Intrinsic::hexagon_S2_vtrunewh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vtrunowh:
+    ID =3D Intrinsic::hexagon_S2_vtrunowh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vtrunehb:
+    ID =3D Intrinsic::hexagon_S2_vtrunehb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsxthw:
+    ID =3D Intrinsic::hexagon_S2_vsxthw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vzxthw:
+    ID =3D Intrinsic::hexagon_S2_vzxthw; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsatwh:
+    ID =3D Intrinsic::hexagon_S2_vsatwh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsatwuh:
+    ID =3D Intrinsic::hexagon_S2_vsatwuh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_packhl:
+    ID =3D Intrinsic::hexagon_S2_packhl; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A2_swiz:
+    ID =3D Intrinsic::hexagon_A2_swiz; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsathub_nopack:
+    ID =3D Intrinsic::hexagon_S2_vsathub_nopack; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsathb_nopack:
+    ID =3D Intrinsic::hexagon_S2_vsathb_nopack; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsatwh_nopack:
+    ID =3D Intrinsic::hexagon_S2_vsatwh_nopack; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_vsatwuh_nopack:
+    ID =3D Intrinsic::hexagon_S2_vsatwuh_nopack; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_shuffob:
+    ID =3D Intrinsic::hexagon_S2_shuffob; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_shuffeb:
+    ID =3D Intrinsic::hexagon_S2_shuffeb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_shuffoh:
+    ID =3D Intrinsic::hexagon_S2_shuffoh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_shuffeh:
+    ID =3D Intrinsic::hexagon_S2_shuffeh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_parityp:
+    ID =3D Intrinsic::hexagon_S2_parityp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_lfsp:
+    ID =3D Intrinsic::hexagon_S2_lfsp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_clbnorm:
+    ID =3D Intrinsic::hexagon_S2_clbnorm; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_clb:
+    ID =3D Intrinsic::hexagon_S2_clb; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_cl0:
+    ID =3D Intrinsic::hexagon_S2_cl0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_cl1:
+    ID =3D Intrinsic::hexagon_S2_cl1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_clbp:
+    ID =3D Intrinsic::hexagon_S2_clbp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_cl0p:
+    ID =3D Intrinsic::hexagon_S2_cl0p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_cl1p:
+    ID =3D Intrinsic::hexagon_S2_cl1p; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_brev:
+    ID =3D Intrinsic::hexagon_S2_brev; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_ct0:
+    ID =3D Intrinsic::hexagon_S2_ct0; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_ct1:
+    ID =3D Intrinsic::hexagon_S2_ct1; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_interleave:
+    ID =3D Intrinsic::hexagon_S2_interleave; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S2_deinterleave:
+    ID =3D Intrinsic::hexagon_S2_deinterleave; break;
+
+  case Hexagon::BI__builtin_SI_to_SXTHI_asrh:
+    ID =3D Intrinsic::hexagon_SI_to_SXTHI_asrh; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_orn:
+    ID =3D Intrinsic::hexagon_A4_orn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_andn:
+    ID =3D Intrinsic::hexagon_A4_andn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_ornp:
+    ID =3D Intrinsic::hexagon_A4_ornp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_andnp:
+    ID =3D Intrinsic::hexagon_A4_andnp; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_combineir:
+    ID =3D Intrinsic::hexagon_A4_combineir; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_combineri:
+    ID =3D Intrinsic::hexagon_A4_combineri; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_cmpneqi:
+    ID =3D Intrinsic::hexagon_C4_cmpneqi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_cmpneq:
+    ID =3D Intrinsic::hexagon_C4_cmpneq; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_cmpltei:
+    ID =3D Intrinsic::hexagon_C4_cmpltei; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_cmplte:
+    ID =3D Intrinsic::hexagon_C4_cmplte; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_cmplteui:
+    ID =3D Intrinsic::hexagon_C4_cmplteui; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_cmplteu:
+    ID =3D Intrinsic::hexagon_C4_cmplteu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_rcmpneq:
+    ID =3D Intrinsic::hexagon_A4_rcmpneq; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_rcmpneqi:
+    ID =3D Intrinsic::hexagon_A4_rcmpneqi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_rcmpeq:
+    ID =3D Intrinsic::hexagon_A4_rcmpeq; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_rcmpeqi:
+    ID =3D Intrinsic::hexagon_A4_rcmpeqi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_fastcorner9:
+    ID =3D Intrinsic::hexagon_C4_fastcorner9; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_fastcorner9_not:
+    ID =3D Intrinsic::hexagon_C4_fastcorner9_not; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_and_andn:
+    ID =3D Intrinsic::hexagon_C4_and_andn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_and_and:
+    ID =3D Intrinsic::hexagon_C4_and_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_and_orn:
+    ID =3D Intrinsic::hexagon_C4_and_orn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_and_or:
+    ID =3D Intrinsic::hexagon_C4_and_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_or_andn:
+    ID =3D Intrinsic::hexagon_C4_or_andn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_or_and:
+    ID =3D Intrinsic::hexagon_C4_or_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_or_orn:
+    ID =3D Intrinsic::hexagon_C4_or_orn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_C4_or_or:
+    ID =3D Intrinsic::hexagon_C4_or_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S4_addaddi:
+    ID =3D Intrinsic::hexagon_S4_addaddi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S4_subaddi:
+    ID =3D Intrinsic::hexagon_S4_subaddi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_xor_xacc:
+    ID =3D Intrinsic::hexagon_M4_xor_xacc; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_and_and:
+    ID =3D Intrinsic::hexagon_M4_and_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_and_or:
+    ID =3D Intrinsic::hexagon_M4_and_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_and_xor:
+    ID =3D Intrinsic::hexagon_M4_and_xor; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_and_andn:
+    ID =3D Intrinsic::hexagon_M4_and_andn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_xor_and:
+    ID =3D Intrinsic::hexagon_M4_xor_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_xor_or:
+    ID =3D Intrinsic::hexagon_M4_xor_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_xor_andn:
+    ID =3D Intrinsic::hexagon_M4_xor_andn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_or_and:
+    ID =3D Intrinsic::hexagon_M4_or_and; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_or_or:
+    ID =3D Intrinsic::hexagon_M4_or_or; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_or_xor:
+    ID =3D Intrinsic::hexagon_M4_or_xor; break;
+
+  case Hexagon::BI__builtin_HEXAGON_M4_or_andn:
+    ID =3D Intrinsic::hexagon_M4_or_andn; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S4_or_andix:
+    ID =3D Intrinsic::hexagon_S4_or_andix; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S4_or_andi:
+    ID =3D Intrinsic::hexagon_S4_or_andi; break;
+
+  case Hexagon::BI__builtin_HEXAGON_S4_or_ori:
+    ID =3D Intrinsic::hexagon_S4_or_ori; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_modwrapu:
+    ID =3D Intrinsic::hexagon_A4_modwrapu; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_cround_rr:
+    ID =3D Intrinsic::hexagon_A4_cround_rr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_round_ri:
+    ID =3D Intrinsic::hexagon_A4_round_ri; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_round_rr:
+    ID =3D Intrinsic::hexagon_A4_round_rr; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat:
+    ID =3D Intrinsic::hexagon_A4_round_ri_sat; break;
+
+  case Hexagon::BI__builtin_HEXAGON_A4_round_rr_sat:
+    ID =3D Intrinsic::hexagon_A4_round_rr_sat; break;
+
+  }
+
+  llvm::Function *F =3D CGM.getIntrinsic(ID);
+  return Builder.CreateCall(F, Ops, "");
+}
+
 Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned BuiltinID,
                                            const CallExpr *E) {
   SmallVector<Value*, 4> Ops;
@@ -2506,5 +4521,4 @@
     return Builder.CreateCall(F, Ops, "");
   }
   }
-  return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGCXX.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGCXX.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -196,7 +196,8 @@
                                 GlobalDecl(ctor, Ctor_Base)))
     return;
=20
-  const CGFunctionInfo &fnInfo =3D getTypes().getFunctionInfo(ctor, ctorTy=
pe);
+  const CGFunctionInfo &fnInfo =3D
+    getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
=20
   llvm::Function *fn =3D
     cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo));
@@ -218,11 +219,10 @@
   if (llvm::GlobalValue *existing =3D GetGlobalValue(name))
     return existing;
=20
-  if (!fnInfo) fnInfo =3D &getTypes().getFunctionInfo(ctor, ctorType);
+  if (!fnInfo)
+    fnInfo =3D &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType=
);
=20
-  const FunctionProtoType *proto =3D ctor->getType()->castAs<FunctionProto=
Type>();
-  llvm::FunctionType *fnType =3D
-    getTypes().GetFunctionType(*fnInfo, proto->isVariadic());
+  llvm::FunctionType *fnType =3D getTypes().GetFunctionType(*fnInfo);
   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
                                                       /*ForVTable=3D*/fals=
e));
 }
@@ -260,7 +260,8 @@
   if (dtorType =3D=3D Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
     return;
=20
-  const CGFunctionInfo &fnInfo =3D getTypes().getFunctionInfo(dtor, dtorTy=
pe);
+  const CGFunctionInfo &fnInfo =3D
+    getTypes().arrangeCXXDestructor(dtor, dtorType);
=20
   llvm::Function *fn =3D
     cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo));
@@ -282,11 +283,9 @@
   if (llvm::GlobalValue *existing =3D GetGlobalValue(name))
     return existing;
=20
-  if (!fnInfo) fnInfo =3D &getTypes().getFunctionInfo(dtor, dtorType);
+  if (!fnInfo) fnInfo =3D &getTypes().arrangeCXXDestructor(dtor, dtorType);
=20
-  llvm::FunctionType *fnType =3D
-    getTypes().GetFunctionType(*fnInfo, false);
-
+  llvm::FunctionType *fnType =3D getTypes().GetFunctionType(*fnInfo);
   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
                                                       /*ForVTable=3D*/fals=
e));
 }
@@ -359,12 +358,10 @@
   // -O does that. But need to support -O0 as well.
   if (MD->isVirtual() && Type !=3D Dtor_Base) {
     // Compute the function type we're calling.
-    const CGFunctionInfo *FInfo =3D=20
-    &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
-                                    Dtor_Complete);
-    const FunctionProtoType *FPT =3D MD->getType()->getAs<FunctionProtoTyp=
e>();
-    llvm::Type *Ty
-      =3D CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
+    const CGFunctionInfo &FInfo =3D=20
+      CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
+                                          Dtor_Complete);
+    llvm::Type *Ty =3D CGM.getTypes().GetFunctionType(FInfo);
=20
     llvm::Value *VTable =3D CGM.getVTables().GetAddrOfVTable(RD);
     Ty =3D Ty->getPointerTo()->getPointerTo();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGCXXABI.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGCXXABI.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGCXXABI.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -49,9 +49,8 @@
     MPT->getPointeeType()->getAs<FunctionProtoType>();
   const CXXRecordDecl *RD =3D=20
     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
-  llvm::FunctionType *FTy =3D=20
-    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
-                                   FPT->isVariadic());
+  llvm::FunctionType *FTy =3D CGM.getTypes().GetFunctionType(
+                              CGM.getTypes().arrangeCXXMethodType(RD, FPT)=
);
   return llvm::Constant::getNullValue(FTy->getPointerTo());
 }
=20
@@ -71,6 +70,11 @@
   return GetBogusMemberPointer(CGM, E->getType());
 }
=20
+llvm::Constant *CGCXXABI::EmitMemberPointerConversion(const CastExpr *E,
+                                                      llvm::Constant *Src)=
 {
+  return GetBogusMemberPointer(CGM, E->getType());
+}
+
 llvm::Value *
 CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
                                       llvm::Value *L,
@@ -90,11 +94,6 @@
 }
=20
 llvm::Constant *
-CGCXXABI::EmitMemberPointerConversion(llvm::Constant *C, const CastExpr *E=
) {
-  return GetBogusMemberPointer(CGM, E->getType());
-}
-
-llvm::Constant *
 CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
   return GetBogusMemberPointer(CGM, QualType(MPT, 0));
 }
@@ -110,6 +109,10 @@
   return GetBogusMemberPointer(CGM, QualType(MPT, 0));
 }
=20
+llvm::Constant *CGCXXABI::EmitMemberPointer(const APValue &MP, QualType MP=
T) {
+  return GetBogusMemberPointer(CGM, MPT);
+}
+
 bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
   // Fake answer.
   return true;
@@ -169,6 +172,28 @@
=20
 void CGCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
                                const VarDecl &D,
-                               llvm::GlobalVariable *GV) {
+                               llvm::GlobalVariable *GV,
+                               bool PerformInit) {
   ErrorUnsupportedABI(CGF, "static local variable initialization");
 }
+
+/// Returns the adjustment, in bytes, required for the given
+/// member-pointer operation.  Returns null if no adjustment is
+/// required.
+llvm::Constant *CGCXXABI::getMemberPointerAdjustment(const CastExpr *E) {
+  assert(E->getCastKind() =3D=3D CK_DerivedToBaseMemberPointer ||
+         E->getCastKind() =3D=3D CK_BaseToDerivedMemberPointer);
+
+  QualType derivedType;
+  if (E->getCastKind() =3D=3D CK_DerivedToBaseMemberPointer)
+    derivedType =3D E->getSubExpr()->getType();
+  else
+    derivedType =3D E->getType();
+
+  const CXXRecordDecl *derivedClass =3D
+    derivedType->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDe=
cl();
+
+  return CGM.GetNonVirtualBaseClassOffset(derivedClass,
+                                          E->path_begin(),
+                                          E->path_end());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGCXXABI.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGCXXABI.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGCXXABI.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -42,17 +42,17 @@
 class CGCXXABI {
 protected:
   CodeGenModule &CGM;
-  llvm::OwningPtr<MangleContext> MangleCtx;
+  OwningPtr<MangleContext> MangleCtx;
=20
   CGCXXABI(CodeGenModule &CGM)
     : CGM(CGM), MangleCtx(CGM.getContext().createMangleContext()) {}
=20
 protected:
   ImplicitParamDecl *&getThisDecl(CodeGenFunction &CGF) {
-    return CGF.CXXThisDecl;
+    return CGF.CXXABIThisDecl;
   }
   llvm::Value *&getThisValue(CodeGenFunction &CGF) {
-    return CGF.CXXThisValue;
+    return CGF.CXXABIThisValue;
   }
=20
   ImplicitParamDecl *&getVTTDecl(CodeGenFunction &CGF) {
@@ -100,16 +100,16 @@
                                                     llvm::Value *MemPtr,
                                             const MemberPointerType *MPT);
=20
-  /// Perform a derived-to-base or base-to-derived member pointer
-  /// conversion.
+  /// Perform a derived-to-base, base-to-derived, or bitcast member
+  /// pointer conversion.
   virtual llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
                                                    const CastExpr *E,
                                                    llvm::Value *Src);
=20
-  /// Perform a derived-to-base or base-to-derived member pointer
-  /// conversion on a constant member pointer.
-  virtual llvm::Constant *EmitMemberPointerConversion(llvm::Constant *C,
-                                                      const CastExpr *E);
+  /// Perform a derived-to-base, base-to-derived, or bitcast member
+  /// pointer conversion on a constant value.
+  virtual llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
+                                                      llvm::Constant *Src);
=20
   /// Return true if the given member pointer can be zero-initialized
   /// (in the C++ sense) with an LLVM zeroinitializer.
@@ -125,6 +125,9 @@
   virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *M=
PT,
                                                 CharUnits offset);
=20
+  /// Create a member pointer for the given member pointer constant.
+  virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MP=
T);
+
   /// Emit a comparison between two member pointers.  Returns an i1.
   virtual llvm::Value *
   EmitMemberPointerComparison(CodeGenFunction &CGF,
@@ -139,6 +142,15 @@
                              llvm::Value *MemPtr,
                              const MemberPointerType *MPT);
=20
+protected:
+  /// A utility method for computing the offset required for the given
+  /// base-to-derived or derived-to-base member-pointer conversion.
+  /// Does not handle virtual conversions (in case we ever fully
+  /// support an ABI that allows this).  Returns null if no adjustment
+  /// is required.
+  llvm::Constant *getMemberPointerAdjustment(const CastExpr *E);
+
+public:
   /// Build the signature of the given constructor variant by adding
   /// any required parameters.  For convenience, ResTy has been
   /// initialized to 'void', and ArgTys has been initialized with the
@@ -228,12 +240,14 @@
=20
   /// Emits the guarded initializer and destructor setup for the given
   /// variable, given that it couldn't be emitted as a constant.
+  /// If \p PerformInit is false, the initialization has been folded to a
+  /// constant and should not be performed.
   ///
   /// The variable may be:
   ///   - a static local variable
   ///   - a static data member of a class template instantiation
   virtual void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
-                               llvm::GlobalVariable *DeclPtr);
+                               llvm::GlobalVariable *DeclPtr, bool Perform=
Init);
=20
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGCall.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGCall.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGCall.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "ABIInfo.h"
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
+#include "TargetInfo.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
@@ -66,29 +67,39 @@
   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
 }
=20
+/// Arrange the argument and result information for a value of the
+/// given unprototyped function type.
 const CGFunctionInfo &
-CodeGenTypes::getFunctionInfo(CanQual<FunctionNoProtoType> FTNP) {
-  return getFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
-                         SmallVector<CanQualType, 16>(),
-                         FTNP->getExtInfo());
+CodeGenTypes::arrangeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
+  // When translating an unprototyped function type, always use a
+  // variadic type.
+  return arrangeFunctionType(FTNP->getResultType().getUnqualifiedType(),
+                             ArrayRef<CanQualType>(),
+                             FTNP->getExtInfo(),
+                             RequiredArgs(0));
 }
=20
-/// \param Args - contains any initial parameters besides those
-///   in the formal type
-static const CGFunctionInfo &getFunctionInfo(CodeGenTypes &CGT,
-                                  SmallVectorImpl<CanQualType> &ArgTys,
+/// Arrange the argument and result information for a value of the
+/// given function type, on top of any implicit parameters already
+/// stored.
+static const CGFunctionInfo &arrangeFunctionType(CodeGenTypes &CGT,
+                                  SmallVectorImpl<CanQualType> &argTypes,
                                              CanQual<FunctionProtoType> FT=
P) {
+  RequiredArgs required =3D RequiredArgs::forPrototypePlus(FTP, argTypes.s=
ize());
   // FIXME: Kill copy.
   for (unsigned i =3D 0, e =3D FTP->getNumArgs(); i !=3D e; ++i)
-    ArgTys.push_back(FTP->getArgType(i));
-  CanQualType ResTy =3D FTP->getResultType().getUnqualifiedType();
-  return CGT.getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
+    argTypes.push_back(FTP->getArgType(i));
+  CanQualType resultType =3D FTP->getResultType().getUnqualifiedType();
+  return CGT.arrangeFunctionType(resultType, argTypes,
+                                 FTP->getExtInfo(), required);
 }
=20
+/// Arrange the argument and result information for a value of the
+/// given function type.
 const CGFunctionInfo &
-CodeGenTypes::getFunctionInfo(CanQual<FunctionProtoType> FTP) {
-  SmallVector<CanQualType, 16> ArgTys;
-  return ::getFunctionInfo(*this, ArgTys, FTP);
+CodeGenTypes::arrangeFunctionType(CanQual<FunctionProtoType> FTP) {
+  SmallVector<CanQualType, 16> argTypes;
+  return ::arrangeFunctionType(*this, argTypes, FTP);
 }
=20
 static CallingConv getCallingConventionForDecl(const Decl *D) {
@@ -111,162 +122,250 @@
   return CC_C;
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXRecordDecl *R=
D,
-                                                 const FunctionProtoType *=
FTP) {
-  SmallVector<CanQualType, 16> ArgTys;
+/// Arrange the argument and result information for a call to an
+/// unknown C++ non-static member function of the given abstract type.
+/// The member function must be an ordinary function, i.e. not a
+/// constructor or destructor.
+const CGFunctionInfo &
+CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
+                                   const FunctionProtoType *FTP) {
+  SmallVector<CanQualType, 16> argTypes;
=20
   // Add the 'this' pointer.
-  ArgTys.push_back(GetThisType(Context, RD));
+  argTypes.push_back(GetThisType(Context, RD));
=20
-  return ::getFunctionInfo(*this, ArgTys,
+  return ::arrangeFunctionType(*this, argTypes,
               FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(=
));
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *M=
D) {
-  SmallVector<CanQualType, 16> ArgTys;
-
+/// Arrange the argument and result information for a declaration or
+/// definition of the given C++ non-static member function.  The
+/// member function must be an ordinary function, i.e. not a
+/// constructor or destructor.
+const CGFunctionInfo &
+CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
   assert(!isa<CXXConstructorDecl>(MD) && "wrong method for contructors!");
   assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
=20
-  // Add the 'this' pointer unless this is a static method.
-  if (MD->isInstance())
-    ArgTys.push_back(GetThisType(Context, MD->getParent()));
+  CanQual<FunctionProtoType> prototype =3D GetFormalType(MD);
=20
-  return ::getFunctionInfo(*this, ArgTys, GetFormalType(MD));
+  if (MD->isInstance()) {
+    // The abstract case is perfectly fine.
+    return arrangeCXXMethodType(MD->getParent(), prototype.getTypePtr());
+  }
+
+  return arrangeFunctionType(prototype);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXConstructorDe=
cl *D,
-                                                    CXXCtorType Type) {
-  SmallVector<CanQualType, 16> ArgTys;
-  ArgTys.push_back(GetThisType(Context, D->getParent()));
-  CanQualType ResTy =3D Context.VoidTy;
+/// Arrange the argument and result information for a declaration
+/// or definition to the given constructor variant.
+const CGFunctionInfo &
+CodeGenTypes::arrangeCXXConstructorDeclaration(const CXXConstructorDecl *D,
+                                               CXXCtorType ctorKind) {
+  SmallVector<CanQualType, 16> argTypes;
+  argTypes.push_back(GetThisType(Context, D->getParent()));
+  CanQualType resultType =3D Context.VoidTy;
=20
-  TheCXXABI.BuildConstructorSignature(D, Type, ResTy, ArgTys);
+  TheCXXABI.BuildConstructorSignature(D, ctorKind, resultType, argTypes);
=20
   CanQual<FunctionProtoType> FTP =3D GetFormalType(D);
=20
+  RequiredArgs required =3D RequiredArgs::forPrototypePlus(FTP, argTypes.s=
ize());
+
   // Add the formal parameters.
   for (unsigned i =3D 0, e =3D FTP->getNumArgs(); i !=3D e; ++i)
-    ArgTys.push_back(FTP->getArgType(i));
+    argTypes.push_back(FTP->getArgType(i));
=20
-  return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
+  return arrangeFunctionType(resultType, argTypes, FTP->getExtInfo(), requ=
ired);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXDestructorDec=
l *D,
-                                                    CXXDtorType Type) {
-  SmallVector<CanQualType, 2> ArgTys;
-  ArgTys.push_back(GetThisType(Context, D->getParent()));
-  CanQualType ResTy =3D Context.VoidTy;
+/// Arrange the argument and result information for a declaration,
+/// definition, or call to the given destructor variant.  It so
+/// happens that all three cases produce the same information.
+const CGFunctionInfo &
+CodeGenTypes::arrangeCXXDestructor(const CXXDestructorDecl *D,
+                                   CXXDtorType dtorKind) {
+  SmallVector<CanQualType, 2> argTypes;
+  argTypes.push_back(GetThisType(Context, D->getParent()));
+  CanQualType resultType =3D Context.VoidTy;
=20
-  TheCXXABI.BuildDestructorSignature(D, Type, ResTy, ArgTys);
+  TheCXXABI.BuildDestructorSignature(D, dtorKind, resultType, argTypes);
=20
   CanQual<FunctionProtoType> FTP =3D GetFormalType(D);
   assert(FTP->getNumArgs() =3D=3D 0 && "dtor with formal parameters");
=20
-  return getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo());
+  return arrangeFunctionType(resultType, argTypes, FTP->getExtInfo(),
+                             RequiredArgs::All);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD=
) {
+/// Arrange the argument and result information for the declaration or
+/// definition of the given function.
+const CGFunctionInfo &
+CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
   if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(FD))
     if (MD->isInstance())
-      return getFunctionInfo(MD);
+      return arrangeCXXMethodDeclaration(MD);
=20
   CanQualType FTy =3D FD->getType()->getCanonicalTypeUnqualified();
+
   assert(isa<FunctionType>(FTy));
-  if (isa<FunctionNoProtoType>(FTy))
-    return getFunctionInfo(FTy.getAs<FunctionNoProtoType>());
+
+  // When declaring a function without a prototype, always use a
+  // non-variadic type.
+  if (isa<FunctionNoProtoType>(FTy)) {
+    CanQual<FunctionNoProtoType> noProto =3D FTy.getAs<FunctionNoProtoType=
>();
+    return arrangeFunctionType(noProto->getResultType(),
+                               ArrayRef<CanQualType>(),
+                               noProto->getExtInfo(),
+                               RequiredArgs::All);
+  }
+
   assert(isa<FunctionProtoType>(FTy));
-  return getFunctionInfo(FTy.getAs<FunctionProtoType>());
+  return arrangeFunctionType(FTy.getAs<FunctionProtoType>());
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *=
MD) {
-  SmallVector<CanQualType, 16> ArgTys;
-  ArgTys.push_back(Context.getCanonicalParamType(MD->getSelfDecl()->getTyp=
e()));
-  ArgTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())=
);
+/// Arrange the argument and result information for the declaration or
+/// definition of an Objective-C method.
+const CGFunctionInfo &
+CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
+  // It happens that this is the same as a call with no optional
+  // arguments, except also using the formal 'self' type.
+  return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
+}
+
+/// Arrange the argument and result information for the function type
+/// through which to perform a send to the given Objective-C method,
+/// using the given receiver type.  The receiver type is not always
+/// the 'self' type of the method or even an Objective-C pointer type.
+/// This is *not* the right method for actually performing such a
+/// message send, due to the possibility of optional arguments.
+const CGFunctionInfo &
+CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
+                                              QualType receiverType) {
+  SmallVector<CanQualType, 16> argTys;
+  argTys.push_back(Context.getCanonicalParamType(receiverType));
+  argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())=
);
   // FIXME: Kill copy?
   for (ObjCMethodDecl::param_const_iterator i =3D MD->param_begin(),
          e =3D MD->param_end(); i !=3D e; ++i) {
-    ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
+    argTys.push_back(Context.getCanonicalParamType((*i)->getType()));
   }
=20
   FunctionType::ExtInfo einfo;
   einfo =3D einfo.withCallingConv(getCallingConventionForDecl(MD));
=20
-  if (getContext().getLangOptions().ObjCAutoRefCount &&
+  if (getContext().getLangOpts().ObjCAutoRefCount &&
       MD->hasAttr<NSReturnsRetainedAttr>())
     einfo =3D einfo.withProducesResult(true);
=20
-  return getFunctionInfo(GetReturnType(MD->getResultType()), ArgTys, einfo=
);
+  RequiredArgs required =3D
+    (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
+
+  return arrangeFunctionType(GetReturnType(MD->getResultType()), argTys,
+                             einfo, required);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(GlobalDecl GD) {
+const CGFunctionInfo &
+CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
   // FIXME: Do we need to handle ObjCMethodDecl?
   const FunctionDecl *FD =3D cast<FunctionDecl>(GD.getDecl());
=20
   if (const CXXConstructorDecl *CD =3D dyn_cast<CXXConstructorDecl>(FD))
-    return getFunctionInfo(CD, GD.getCtorType());
+    return arrangeCXXConstructorDeclaration(CD, GD.getCtorType());
=20
   if (const CXXDestructorDecl *DD =3D dyn_cast<CXXDestructorDecl>(FD))
-    return getFunctionInfo(DD, GD.getDtorType());
+    return arrangeCXXDestructor(DD, GD.getDtorType());
=20
-  return getFunctionInfo(FD);
+  return arrangeFunctionDeclaration(FD);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
-                                                    const CallArgList &Arg=
s,
-                                            const FunctionType::ExtInfo &I=
nfo) {
-  // FIXME: Kill copy.
-  SmallVector<CanQualType, 16> ArgTys;
-  for (CallArgList::const_iterator i =3D Args.begin(), e =3D Args.end();
-       i !=3D e; ++i)
-    ArgTys.push_back(Context.getCanonicalParamType(i->Ty));
-  return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
+/// Figure out the rules for calling a function with the given formal
+/// type using the given arguments.  The arguments are necessary
+/// because the function might be unprototyped, in which case it's
+/// target-dependent in crazy ways.
+const CGFunctionInfo &
+CodeGenTypes::arrangeFunctionCall(const CallArgList &args,
+                                  const FunctionType *fnType) {
+  RequiredArgs required =3D RequiredArgs::All;
+  if (const FunctionProtoType *proto =3D dyn_cast<FunctionProtoType>(fnTyp=
e)) {
+    if (proto->isVariadic())
+      required =3D RequiredArgs(proto->getNumArgs());
+  } else if (CGM.getTargetCodeGenInfo()
+               .isNoProtoCallVariadic(args, cast<FunctionNoProtoType>(fnTy=
pe))) {
+    required =3D RequiredArgs(0);
+  }
+
+  return arrangeFunctionCall(fnType->getResultType(), args,
+                             fnType->getExtInfo(), required);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
-                                                    const FunctionArgList =
&Args,
-                                            const FunctionType::ExtInfo &I=
nfo) {
+const CGFunctionInfo &
+CodeGenTypes::arrangeFunctionCall(QualType resultType,
+                                  const CallArgList &args,
+                                  const FunctionType::ExtInfo &info,
+                                  RequiredArgs required) {
   // FIXME: Kill copy.
-  SmallVector<CanQualType, 16> ArgTys;
-  for (FunctionArgList::const_iterator i =3D Args.begin(), e =3D Args.end(=
);
+  SmallVector<CanQualType, 16> argTypes;
+  for (CallArgList::const_iterator i =3D args.begin(), e =3D args.end();
        i !=3D e; ++i)
-    ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
-  return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
+    argTypes.push_back(Context.getCanonicalParamType(i->Ty));
+  return arrangeFunctionType(GetReturnType(resultType), argTypes, info,
+                             required);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getNullaryFunctionInfo() {
-  SmallVector<CanQualType, 1> args;
-  return getFunctionInfo(getContext().VoidTy, args, FunctionType::ExtInfo(=
));
+const CGFunctionInfo &
+CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
+                                         const FunctionArgList &args,
+                                         const FunctionType::ExtInfo &info,
+                                         bool isVariadic) {
+  // FIXME: Kill copy.
+  SmallVector<CanQualType, 16> argTypes;
+  for (FunctionArgList::const_iterator i =3D args.begin(), e =3D args.end(=
);
+       i !=3D e; ++i)
+    argTypes.push_back(Context.getCanonicalParamType((*i)->getType()));
+
+  RequiredArgs required =3D
+    (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
+  return arrangeFunctionType(GetReturnType(resultType), argTypes, info,
+                             required);
 }
=20
-const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy,
-                           const SmallVectorImpl<CanQualType> &ArgTys,
-                                            const FunctionType::ExtInfo &I=
nfo) {
+const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
+  return arrangeFunctionType(getContext().VoidTy, ArrayRef<CanQualType>(),
+                             FunctionType::ExtInfo(), RequiredArgs::All);
+}
+
+/// Arrange the argument and result information for an abstract value
+/// of a given function type.  This is the method which all of the
+/// above functions ultimately defer to.
+const CGFunctionInfo &
+CodeGenTypes::arrangeFunctionType(CanQualType resultType,
+                                  ArrayRef<CanQualType> argTypes,
+                                  const FunctionType::ExtInfo &info,
+                                  RequiredArgs required) {
 #ifndef NDEBUG
-  for (SmallVectorImpl<CanQualType>::const_iterator
-         I =3D ArgTys.begin(), E =3D ArgTys.end(); I !=3D E; ++I)
+  for (ArrayRef<CanQualType>::const_iterator
+         I =3D argTypes.begin(), E =3D argTypes.end(); I !=3D E; ++I)
     assert(I->isCanonicalAsParam());
 #endif
=20
-  unsigned CC =3D ClangCallConvToLLVMCallConv(Info.getCC());
+  unsigned CC =3D ClangCallConvToLLVMCallConv(info.getCC());
=20
   // Lookup or create unique function info.
   llvm::FoldingSetNodeID ID;
-  CGFunctionInfo::Profile(ID, Info, ResTy, ArgTys.begin(), ArgTys.end());
+  CGFunctionInfo::Profile(ID, info, required, resultType, argTypes);
=20
-  void *InsertPos =3D 0;
-  CGFunctionInfo *FI =3D FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
+  void *insertPos =3D 0;
+  CGFunctionInfo *FI =3D FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
   if (FI)
     return *FI;
=20
-  // Construct the function info.
-  FI =3D new CGFunctionInfo(CC, Info.getNoReturn(), Info.getProducesResult=
(),
-                          Info.getHasRegParm(), Info.getRegParm(), ResTy,
-                          ArgTys.data(), ArgTys.size());
-  FunctionInfos.InsertNode(FI, InsertPos);
+  // Construct the function info.  We co-allocate the ArgInfos.
+  FI =3D CGFunctionInfo::create(CC, info, resultType, argTypes, required);
+  FunctionInfos.InsertNode(FI, insertPos);
=20
-  bool Inserted =3D FunctionsBeingProcessed.insert(FI); (void)Inserted;
-  assert(Inserted && "Recursively being processed?");
+  bool inserted =3D FunctionsBeingProcessed.insert(FI); (void)inserted;
+  assert(inserted && "Recursively being processed?");
  =20
   // Compute ABI information.
   getABIInfo().computeInfo(*FI);
@@ -274,39 +373,42 @@
   // Loop over all of the computed argument and return value info.  If any=
 of
   // them are direct or extend without a specified coerce type, specify the
   // default now.
-  ABIArgInfo &RetInfo =3D FI->getReturnInfo();
-  if (RetInfo.canHaveCoerceToType() && RetInfo.getCoerceToType() =3D=3D 0)
-    RetInfo.setCoerceToType(ConvertType(FI->getReturnType()));
+  ABIArgInfo &retInfo =3D FI->getReturnInfo();
+  if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() =3D=3D 0)
+    retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
=20
   for (CGFunctionInfo::arg_iterator I =3D FI->arg_begin(), E =3D FI->arg_e=
nd();
        I !=3D E; ++I)
     if (I->info.canHaveCoerceToType() && I->info.getCoerceToType() =3D=3D =
0)
       I->info.setCoerceToType(ConvertType(I->type));
=20
-  bool Erased =3D FunctionsBeingProcessed.erase(FI); (void)Erased;
-  assert(Erased && "Not in set?");
+  bool erased =3D FunctionsBeingProcessed.erase(FI); (void)erased;
+  assert(erased && "Not in set?");
  =20
   return *FI;
 }
=20
-CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
-                               bool _NoReturn, bool returnsRetained,
-                               bool _HasRegParm, unsigned _RegParm,
-                               CanQualType ResTy,
-                               const CanQualType *ArgTys,
-                               unsigned NumArgTys)
-  : CallingConvention(_CallingConvention),
-    EffectiveCallingConvention(_CallingConvention),
-    NoReturn(_NoReturn), ReturnsRetained(returnsRetained),
-    HasRegParm(_HasRegParm), RegParm(_RegParm)
-{
-  NumArgs =3D NumArgTys;
-
-  // FIXME: Coallocate with the CGFunctionInfo object.
-  Args =3D new ArgInfo[1 + NumArgTys];
-  Args[0].type =3D ResTy;
-  for (unsigned i =3D 0; i !=3D NumArgTys; ++i)
-    Args[1 + i].type =3D ArgTys[i];
+CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
+                                       const FunctionType::ExtInfo &info,
+                                       CanQualType resultType,
+                                       ArrayRef<CanQualType> argTypes,
+                                       RequiredArgs required) {
+  void *buffer =3D operator new(sizeof(CGFunctionInfo) +
+                              sizeof(ArgInfo) * (argTypes.size() + 1));
+  CGFunctionInfo *FI =3D new(buffer) CGFunctionInfo();
+  FI->CallingConvention =3D llvmCC;
+  FI->EffectiveCallingConvention =3D llvmCC;
+  FI->ASTCallingConvention =3D info.getCC();
+  FI->NoReturn =3D info.getNoReturn();
+  FI->ReturnsRetained =3D info.getProducesResult();
+  FI->Required =3D required;
+  FI->HasRegParm =3D info.getHasRegParm();
+  FI->RegParm =3D info.getRegParm();
+  FI->NumArgs =3D argTypes.size();
+  FI->getArgsBuffer()[0].type =3D resultType;
+  for (unsigned i =3D 0, e =3D argTypes.size(); i !=3D e; ++i)
+    FI->getArgsBuffer()[i + 1].type =3D argTypes[i];
+  return FI;
 }
=20
 /***/
@@ -366,7 +468,7 @@
     QualType EltTy =3D CT->getElementType();
     llvm::Value *RealAddr =3D Builder.CreateStructGEP(Addr, 0, "real");
     EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(RealAddr, Elt=
Ty));
-    llvm::Value *ImagAddr =3D Builder.CreateStructGEP(Addr, 0, "imag");
+    llvm::Value *ImagAddr =3D Builder.CreateStructGEP(Addr, 1, "imag");
     EmitStoreThroughLValue(RValue::get(AI++), MakeAddrLValue(ImagAddr, Elt=
Ty));
   } else {
     EmitStoreThroughLValue(RValue::get(AI), LV);
@@ -521,7 +623,9 @@
         SI->setAlignment(1);
     }
   } else {
-    CGF.Builder.CreateStore(Val, DestPtr, DestIsVolatile);
+    llvm::StoreInst *SI =3D CGF.Builder.CreateStore(Val, DestPtr, DestIsVo=
latile);
+    if (LowAlignment)
+      SI->setAlignment(1);
   }
 }
=20
@@ -611,20 +715,24 @@
   return false;
 }
=20
+bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
+  if (const ComplexType *CT =3D ResultType->getAs<ComplexType>()) {
+    if (const BuiltinType *BT =3D CT->getElementType()->getAs<BuiltinType>=
()) {
+      if (BT->getKind() =3D=3D BuiltinType::LongDouble)
+        return getContext().getTargetInfo().useObjCFP2RetForComplexLongDou=
ble();
+    }
+  }
+
+  return false;
+}
+
 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
-  const CGFunctionInfo &FI =3D getFunctionInfo(GD);
-
-  // For definition purposes, don't consider a K&R function variadic.
-  bool Variadic =3D false;
-  if (const FunctionProtoType *FPT =3D
-        cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoTy=
pe>())
-    Variadic =3D FPT->isVariadic();
-
-  return GetFunctionType(FI, Variadic);
+  const CGFunctionInfo &FI =3D arrangeGlobalDeclaration(GD);
+  return GetFunctionType(FI);
 }
=20
 llvm::FunctionType *
-CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool isVariadic) {
+CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
  =20
   bool Inserted =3D FunctionsBeingProcessed.insert(&FI); (void)Inserted;
   assert(Inserted && "Recursively being processed?");
@@ -675,6 +783,9 @@
=20
     case ABIArgInfo::Extend:
     case ABIArgInfo::Direct: {
+      // Insert a padding type to ensure proper alignment.
+      if (llvm::Type *PaddingType =3D argAI.getPaddingType())
+        argTypes.push_back(PaddingType);
       // If the coerce-to type is a first class aggregate, flatten it.  Ei=
ther
       // way is semantically identical, but fast-isel and the optimizer
       // generally likes scalar values better than FCAs.
@@ -697,7 +808,7 @@
   bool Erased =3D FunctionsBeingProcessed.erase(&FI); (void)Erased;
   assert(Erased && "Not in set?");
  =20
-  return llvm::FunctionType::get(resultType, argTypes, isVariadic);
+  return llvm::FunctionType::get(resultType, argTypes, FI.isVariadic());
 }
=20
 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
@@ -709,18 +820,18 @@
    =20
   const CGFunctionInfo *Info;
   if (isa<CXXDestructorDecl>(MD))
-    Info =3D &getFunctionInfo(cast<CXXDestructorDecl>(MD), GD.getDtorType(=
));
+    Info =3D &arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), GD.getDtor=
Type());
   else
-    Info =3D &getFunctionInfo(MD);
-  return GetFunctionType(*Info, FPT->isVariadic());
+    Info =3D &arrangeCXXMethodDeclaration(MD);
+  return GetFunctionType(*Info);
 }
=20
 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
                                            const Decl *TargetDecl,
                                            AttributeListType &PAL,
                                            unsigned &CallingConv) {
-  unsigned FuncAttrs =3D 0;
-  unsigned RetAttrs =3D 0;
+  llvm::Attributes FuncAttrs;
+  llvm::Attributes RetAttrs;
=20
   CallingConv =3D FI.getEffectiveCallingConvention();
=20
@@ -806,7 +917,7 @@
          ie =3D FI.arg_end(); it !=3D ie; ++it) {
     QualType ParamType =3D it->type;
     const ABIArgInfo &AI =3D it->info;
-    unsigned Attributes =3D 0;
+    llvm::Attributes Attrs;
=20
     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
     // have the corresponding parameter variable.  It doesn't make
@@ -814,20 +925,24 @@
     switch (AI.getKind()) {
     case ABIArgInfo::Extend:
       if (ParamType->isSignedIntegerOrEnumerationType())
-        Attributes |=3D llvm::Attribute::SExt;
+        Attrs |=3D llvm::Attribute::SExt;
       else if (ParamType->isUnsignedIntegerOrEnumerationType())
-        Attributes |=3D llvm::Attribute::ZExt;
+        Attrs |=3D llvm::Attribute::ZExt;
       // FALL THROUGH
     case ABIArgInfo::Direct:
       if (RegParm > 0 &&
-          (ParamType->isIntegerType() || ParamType->isPointerType())) {
+          (ParamType->isIntegerType() || ParamType->isPointerType() ||
+           ParamType->isReferenceType())) {
         RegParm -=3D
         (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
         if (RegParm >=3D 0)
-          Attributes |=3D llvm::Attribute::InReg;
+          Attrs |=3D llvm::Attribute::InReg;
       }
       // FIXME: handle sseregparm someday...
=20
+      // Increment Index if there is padding.
+      Index +=3D (AI.getPaddingType() !=3D 0);
+
       if (llvm::StructType *STy =3D
             dyn_cast<llvm::StructType>(AI.getCoerceToType()))
         Index +=3D STy->getNumElements()-1;  // 1 will be added below.
@@ -835,9 +950,9 @@
=20
     case ABIArgInfo::Indirect:
       if (AI.getIndirectByVal())
-        Attributes |=3D llvm::Attribute::ByVal;
+        Attrs |=3D llvm::Attribute::ByVal;
=20
-      Attributes |=3D
+      Attrs |=3D
         llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
       // byval disables readnone and readonly.
       FuncAttrs &=3D ~(llvm::Attribute::ReadOnly |
@@ -859,8 +974,8 @@
     }
     }
=20
-    if (Attributes)
-      PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
+    if (Attrs)
+      PAL.push_back(llvm::AttributeWithIndex::get(Index, Attrs));
     ++Index;
   }
   if (FuncAttrs)
@@ -970,6 +1085,10 @@
=20
     case ABIArgInfo::Extend:
     case ABIArgInfo::Direct: {
+      // Skip the dummy padding argument.
+      if (ArgI.getPaddingType())
+        ++AI;
+
       // If we have the trivial case, handle it with no muss and fuss.
       if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
           ArgI.getCoerceToType() =3D=3D ConvertType(Ty) &&
@@ -991,7 +1110,7 @@
         break;
       }
=20
-      llvm::AllocaInst *Alloca =3D CreateMemTemp(Ty, "coerce");
+      llvm::AllocaInst *Alloca =3D CreateMemTemp(Ty, Arg->getName());
=20
       // The alignment we need to use is the max of the requested alignmen=
t for
       // the argument plus the alignment required by our access code below.
@@ -1015,15 +1134,36 @@
       // If the coerce-to type is a first class aggregate, we flatten it a=
nd
       // pass the elements. Either way is semantically identical, but fast=
-isel
       // and the optimizer generally likes scalar values better than FCAs.
-      if (llvm::StructType *STy =3D
-            dyn_cast<llvm::StructType>(ArgI.getCoerceToType())) {
-        Ptr =3D Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(ST=
y));
+      llvm::StructType *STy =3D dyn_cast<llvm::StructType>(ArgI.getCoerceT=
oType());
+      if (STy && STy->getNumElements() > 1) {
+        uint64_t SrcSize =3D CGM.getTargetData().getTypeAllocSize(STy);
+        llvm::Type *DstTy =3D
+          cast<llvm::PointerType>(Ptr->getType())->getElementType();
+        uint64_t DstSize =3D CGM.getTargetData().getTypeAllocSize(DstTy);
=20
-        for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++i)=
 {
-          assert(AI !=3D Fn->arg_end() && "Argument mismatch!");
-          AI->setName(Arg->getName() + ".coerce" + Twine(i));
-          llvm::Value *EltPtr =3D Builder.CreateConstGEP2_32(Ptr, 0, i);
-          Builder.CreateStore(AI++, EltPtr);
+        if (SrcSize <=3D DstSize) {
+          Ptr =3D Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(=
STy));
+
+          for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++=
i) {
+            assert(AI !=3D Fn->arg_end() && "Argument mismatch!");
+            AI->setName(Arg->getName() + ".coerce" + Twine(i));
+            llvm::Value *EltPtr =3D Builder.CreateConstGEP2_32(Ptr, 0, i);
+            Builder.CreateStore(AI++, EltPtr);
+          }
+        } else {
+          llvm::AllocaInst *TempAlloca =3D
+            CreateTempAlloca(ArgI.getCoerceToType(), "coerce");
+          TempAlloca->setAlignment(AlignmentToUse);
+          llvm::Value *TempV =3D TempAlloca;
+
+          for (unsigned i =3D 0, e =3D STy->getNumElements(); i !=3D e; ++=
i) {
+            assert(AI !=3D Fn->arg_end() && "Argument mismatch!");
+            AI->setName(Arg->getName() + ".coerce" + Twine(i));
+            llvm::Value *EltPtr =3D Builder.CreateConstGEP2_32(TempV, 0, i=
);
+            Builder.CreateStore(AI++, EltPtr);
+          }
+
+          Builder.CreateMemCpy(Ptr, TempV, DstSize, AlignmentToUse);
         }
       } else {
         // Simple case, just do a coerced store of the argument into the a=
lloca.
@@ -1047,10 +1187,12 @@
       // If this structure was expanded into multiple arguments then
       // we need to create a temporary and reconstruct it from the
       // arguments.
-      llvm::Value *Temp =3D CreateMemTemp(Ty, Arg->getName() + ".addr");
-      llvm::Function::arg_iterator End =3D
-        ExpandTypeFromArgs(Ty, MakeAddrLValue(Temp, Ty), AI);
-      EmitParmDecl(*Arg, Temp, ArgNo);
+      llvm::AllocaInst *Alloca =3D CreateMemTemp(Ty);
+      CharUnits Align =3D getContext().getDeclAlign(Arg);
+      Alloca->setAlignment(Align.getQuantity());
+      LValue LV =3D MakeAddrLValue(Alloca, Ty, Align);
+      llvm::Function::arg_iterator End =3D ExpandTypeFromArgs(Ty, LV, AI);
+      EmitParmDecl(*Arg, Alloca, ArgNo);
=20
       // Name the arguments used in expansion and increment AI.
       unsigned Index =3D 0;
@@ -1076,6 +1218,17 @@
   assert(AI =3D=3D Fn->arg_end() && "Argument mismatch!");
 }
=20
+static void eraseUnusedBitCasts(llvm::Instruction *insn) {
+  while (insn->use_empty()) {
+    llvm::BitCastInst *bitcast =3D dyn_cast<llvm::BitCastInst>(insn);
+    if (!bitcast) return;
+
+    // This is "safe" because we would have used a ConstantExpr otherwise.
+    insn =3D cast<llvm::Instruction>(bitcast->getOperand(0));
+    bitcast->eraseFromParent();
+  }
+}
+
 /// Try to emit a fused autorelease of a return result.
 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
                                                     llvm::Value *result) {
@@ -1154,9 +1307,54 @@
   return CGF.Builder.CreateBitCast(result, resultType);
 }
=20
+/// If this is a +1 of the value of an immutable 'self', remove it.
+static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
+                                          llvm::Value *result) {
+  // This is only applicable to a method with an immutable 'self'.
+  const ObjCMethodDecl *method =3D dyn_cast<ObjCMethodDecl>(CGF.CurCodeDec=
l);
+  if (!method) return 0;
+  const VarDecl *self =3D method->getSelfDecl();
+  if (!self->getType().isConstQualified()) return 0;
+
+  // Look for a retain call.
+  llvm::CallInst *retainCall =3D
+    dyn_cast<llvm::CallInst>(result->stripPointerCasts());
+  if (!retainCall ||
+      retainCall->getCalledValue() !=3D CGF.CGM.getARCEntrypoints().objc_r=
etain)
+    return 0;
+
+  // Look for an ordinary load of 'self'.
+  llvm::Value *retainedValue =3D retainCall->getArgOperand(0);
+  llvm::LoadInst *load =3D
+    dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
+  if (!load || load->isAtomic() || load->isVolatile() ||=20
+      load->getPointerOperand() !=3D CGF.GetAddrOfLocalVar(self))
+    return 0;
+
+  // Okay!  Burn it all down.  This relies for correctness on the
+  // assumption that the retain is emitted as part of the return and
+  // that thereafter everything is used "linearly".
+  llvm::Type *resultType =3D result->getType();
+  eraseUnusedBitCasts(cast<llvm::Instruction>(result));
+  assert(retainCall->use_empty());
+  retainCall->eraseFromParent();
+  eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
+
+  return CGF.Builder.CreateBitCast(load, resultType);
+}
+
 /// Emit an ARC autorelease of the result of a function.
+///
+/// \return the value to actually return from the function
 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
                                             llvm::Value *result) {
+  // If we're returning 'self', kill the initial retain.  This is a
+  // heuristic attempt to "encourage correctness" in the really unfortunate
+  // case where we have a return of self during a dealloc and we desperate=
ly
+  // need to avoid the possible autorelease.
+  if (llvm::Value *self =3D tryRemoveRetainOfSelf(CGF, result))
+    return self;
+
   // At -O0, try to emit a fused retain/autorelease.
   if (CGF.shouldUseFusedARCCalls())
     if (llvm::Value *fused =3D tryEmitFusedAutoreleaseOfResult(CGF, result=
))
@@ -1165,6 +1363,44 @@
   return CGF.EmitARCAutoreleaseReturnValue(result);
 }
=20
+/// Heuristically search for a dominating store to the return-value slot.
+static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &=
CGF) {
+  // If there are multiple uses of the return-value slot, just check
+  // for something immediately preceding the IP.  Sometimes this can
+  // happen with how we generate implicit-returns; it can also happen
+  // with noreturn cleanups.
+  if (!CGF.ReturnValue->hasOneUse()) {
+    llvm::BasicBlock *IP =3D CGF.Builder.GetInsertBlock();
+    if (IP->empty()) return 0;
+    llvm::StoreInst *store =3D dyn_cast<llvm::StoreInst>(&IP->back());
+    if (!store) return 0;
+    if (store->getPointerOperand() !=3D CGF.ReturnValue) return 0;
+    assert(!store->isAtomic() && !store->isVolatile()); // see below
+    return store;
+  }
+
+  llvm::StoreInst *store =3D
+    dyn_cast<llvm::StoreInst>(CGF.ReturnValue->use_back());
+  if (!store) return 0;
+
+  // These aren't actually possible for non-coerced returns, and we
+  // only care about non-coerced returns on this code path.
+  assert(!store->isAtomic() && !store->isVolatile());
+
+  // Now do a first-and-dirty dominance check: just walk up the
+  // single-predecessors chain from the current insertion point.
+  llvm::BasicBlock *StoreBB =3D store->getParent();
+  llvm::BasicBlock *IP =3D CGF.Builder.GetInsertBlock();
+  while (IP !=3D StoreBB) {
+    if (!(IP =3D IP->getSinglePredecessor()))
+      return 0;
+  }
+
+  // Okay, the store's basic block dominates the insertion point; we
+  // can do our thing.
+  return store;
+}
+
 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
   // Functions with no result always return void.
   if (ReturnValue =3D=3D 0) {
@@ -1199,16 +1435,9 @@
       // The internal return value temp always will have pointer-to-return=
-type
       // type, just do a load.
=20
-      // If the instruction right before the insertion point is a store to=
 the
-      // return value, we can elide the load, zap the store, and usually z=
ap the
-      // alloca.
-      llvm::BasicBlock *InsertBB =3D Builder.GetInsertBlock();
-      llvm::StoreInst *SI =3D 0;
-      if (InsertBB->empty() ||
-          !(SI =3D dyn_cast<llvm::StoreInst>(&InsertBB->back())) ||
-          SI->getPointerOperand() !=3D ReturnValue || SI->isVolatile()) {
-        RV =3D Builder.CreateLoad(ReturnValue);
-      } else {
+      // If there is a dominating store to ReturnValue, we can elide
+      // the load, zap the store, and usually zap the alloca.
+      if (llvm::StoreInst *SI =3D findDominatingStoreToReturnValue(*this))=
 {
         // Get the stored value and nuke the now-dead store.
         RetDbgLoc =3D SI->getDebugLoc();
         RV =3D SI->getValueOperand();
@@ -1219,6 +1448,10 @@
           cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
           ReturnValue =3D 0;
         }
+
+      // Otherwise, we have to do a simple load.
+      } else {
+        RV =3D Builder.CreateLoad(ReturnValue);
       }
     } else {
       llvm::Value *V =3D ReturnValue;
@@ -1236,7 +1469,7 @@
     // In ARC, end functions that return a retainable type with a call
     // to objc_autoreleaseReturnValue.
     if (AutoreleaseResult) {
-      assert(getLangOptions().ObjCAutoRefCount &&
+      assert(getLangOpts().ObjCAutoRefCount &&
              !FI.isReturnsRetained() &&
              RetTy->isObjCRetainableType());
       RV =3D emitAutoreleaseOfResult(*this, RV);
@@ -1431,7 +1664,7 @@
                                   QualType type) {
   if (const ObjCIndirectCopyRestoreExpr *CRE
         =3D dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
-    assert(getContext().getLangOptions().ObjCAutoRefCount);
+    assert(getContext().getLangOpts().ObjCAutoRefCount);
     assert(getContext().hasSameType(E->getType(), type));
     return emitWritebackArg(*this, args, CRE);
   }
@@ -1450,14 +1683,23 @@
       cast<CastExpr>(E)->getCastKind() =3D=3D CK_LValueToRValue) {
     LValue L =3D EmitLValue(cast<CastExpr>(E)->getSubExpr());
     assert(L.isSimple());
-    args.add(RValue::getAggregate(L.getAddress(), L.isVolatileQualified()),
-             type, /*NeedsCopy*/true);
+    args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
     return;
   }
=20
   args.add(EmitAnyExprToTemp(E), type);
 }
=20
+// In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
+// optimizer it can aggressively ignore unwind edges.
+void
+CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
+  if (CGM.getCodeGenOpts().OptimizationLevel !=3D 0 &&
+      !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
+    Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
+                      CGM.getNoObjCARCExceptionsMetadata());
+}
+
 /// Emits a call or invoke instruction to the given function, depending
 /// on the current state of the EH stack.
 llvm::CallSite
@@ -1465,14 +1707,22 @@
                                   ArrayRef<llvm::Value *> Args,
                                   const Twine &Name) {
   llvm::BasicBlock *InvokeDest =3D getInvokeDest();
+
+  llvm::Instruction *Inst;
   if (!InvokeDest)
-    return Builder.CreateCall(Callee, Args, Name);
+    Inst =3D Builder.CreateCall(Callee, Args, Name);
+  else {
+    llvm::BasicBlock *ContBB =3D createBasicBlock("invoke.cont");
+    Inst =3D Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
+    EmitBlock(ContBB);
+  }
=20
-  llvm::BasicBlock *ContBB =3D createBasicBlock("invoke.cont");
-  llvm::InvokeInst *Invoke =3D Builder.CreateInvoke(Callee, ContBB, Invoke=
Dest,
-                                                  Args, Name);
-  EmitBlock(ContBB);
-  return Invoke;
+  // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
+  // optimizer it can aggressively ignore unwind edges.
+  if (CGM.getLangOpts().ObjCAutoRefCount)
+    AddObjCARCExceptionMetadata(Inst);
+
+  return Inst;
 }
=20
 llvm::CallSite
@@ -1501,8 +1751,11 @@
       llvm::Value *EltAddr =3D Builder.CreateConstGEP2_32(Addr, 0, Elt);
       LValue LV =3D MakeAddrLValue(EltAddr, EltTy);
       RValue EltRV;
-      if (CodeGenFunction::hasAggregateLLVMType(EltTy))
-        EltRV =3D RValue::getAggregate(LV.getAddress());
+      if (EltTy->isAnyComplexType())
+        // FIXME: Volatile?
+        EltRV =3D RValue::getComplex(LoadComplexFromAddr(LV.getAddress(), =
false));
+      else if (CodeGenFunction::hasAggregateLLVMType(EltTy))
+        EltRV =3D LV.asAggregateRValue();
       else
         EltRV =3D EmitLoadOfLValue(LV);
       ExpandTypeToArgs(EltTy, EltRV, Args, IRFuncTy);
@@ -1519,13 +1772,16 @@
       // FIXME: What are the right qualifiers here?
       LValue LV =3D EmitLValueForField(Addr, FD, 0);
       RValue FldRV;
-      if (CodeGenFunction::hasAggregateLLVMType(FT))
-        FldRV =3D RValue::getAggregate(LV.getAddress());
+      if (FT->isAnyComplexType())
+        // FIXME: Volatile?
+        FldRV =3D RValue::getComplex(LoadComplexFromAddr(LV.getAddress(), =
false));
+      else if (CodeGenFunction::hasAggregateLLVMType(FT))
+        FldRV =3D LV.asAggregateRValue();
       else
         FldRV =3D EmitLoadOfLValue(LV);
       ExpandTypeToArgs(FT, FldRV, Args, IRFuncTy);
     }
-  } else if (isa<ComplexType>(Ty)) {
+  } else if (Ty->isAnyComplexType()) {
     ComplexPairTy CV =3D RV.getComplexVal();
     Args.push_back(CV.first);
     Args.push_back(CV.second);
@@ -1639,6 +1895,12 @@
=20
     case ABIArgInfo::Extend:
     case ABIArgInfo::Direct: {
+      // Insert a padding argument to ensure proper alignment.
+      if (llvm::Type *PaddingType =3D ArgInfo.getPaddingType()) {
+        Args.push_back(llvm::UndefValue::get(PaddingType));
+        ++IRArgNo;
+      }
+
       if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
           ArgInfo.getCoerceToType() =3D=3D ConvertType(info_it->type) &&
           ArgInfo.getDirectOffset() =3D=3D 0) {
@@ -1769,6 +2031,11 @@
   CS.setAttributes(Attrs);
   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
=20
+  // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
+  // optimizer it can aggressively ignore unwind edges.
+  if (CGM.getLangOpts().ObjCAutoRefCount)
+    AddObjCARCExceptionMetadata(CS.getInstruction());
+
   // If the call doesn't return, finish the basic block and clear the
   // insertion point; this allows the rest of IRgen to discard
   // unreachable code.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGCall.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGCall.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGCall.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -98,6 +98,55 @@
     SmallVector<Writeback, 1> Writebacks;
   };
=20
+  /// A class for recording the number of arguments that a function
+  /// signature requires.
+  class RequiredArgs {
+    /// The number of required arguments, or ~0 if the signature does
+    /// not permit optional arguments.
+    unsigned NumRequired;
+  public:
+    enum All_t { All };
+
+    RequiredArgs(All_t _) : NumRequired(~0U) {}
+    explicit RequiredArgs(unsigned n) : NumRequired(n) {
+      assert(n !=3D ~0U);
+    }
+
+    /// Compute the arguments required by the given formal prototype,
+    /// given that there may be some additional, non-formal arguments
+    /// in play.
+    static RequiredArgs forPrototypePlus(const FunctionProtoType *prototyp=
e,
+                                         unsigned additional) {
+      if (!prototype->isVariadic()) return All;
+      return RequiredArgs(prototype->getNumArgs() + additional);
+    }
+
+    static RequiredArgs forPrototype(const FunctionProtoType *prototype) {
+      return forPrototypePlus(prototype, 0);
+    }
+
+    static RequiredArgs forPrototype(CanQual<FunctionProtoType> prototype)=
 {
+      return forPrototype(prototype.getTypePtr());
+    }
+
+    static RequiredArgs forPrototypePlus(CanQual<FunctionProtoType> protot=
ype,
+                                         unsigned additional) {
+      return forPrototypePlus(prototype.getTypePtr(), additional);
+    }
+
+    bool allowsOptionalArgs() const { return NumRequired !=3D ~0U; }
+    bool getNumRequiredArgs() const {
+      assert(allowsOptionalArgs());
+      return NumRequired;
+    }
+
+    unsigned getOpaqueData() const { return NumRequired; }
+    static RequiredArgs getFromOpaqueData(unsigned value) {
+      if (value =3D=3D ~0U) return All;
+      return RequiredArgs(value);
+    }
+  };
+
   /// FunctionArgList - Type for representing both the decl and type
   /// of parameters to a function. The decl must be either a
   /// ParmVarDecl or ImplicitParamDecl.
@@ -114,50 +163,71 @@
=20
     /// The LLVM::CallingConv to use for this function (as specified by the
     /// user).
-    unsigned CallingConvention;
+    unsigned CallingConvention : 8;
=20
     /// The LLVM::CallingConv to actually use for this function, which may
     /// depend on the ABI.
-    unsigned EffectiveCallingConvention;
+    unsigned EffectiveCallingConvention : 8;
+
+    /// The clang::CallingConv that this was originally created with.
+    unsigned ASTCallingConvention : 8;
=20
     /// Whether this function is noreturn.
-    bool NoReturn;
+    unsigned NoReturn : 1;
=20
     /// Whether this function is returns-retained.
-    bool ReturnsRetained;
+    unsigned ReturnsRetained : 1;
+
+    /// How many arguments to pass inreg.
+    unsigned HasRegParm : 1;
+    unsigned RegParm : 4;
+
+    RequiredArgs Required;
=20
     unsigned NumArgs;
-    ArgInfo *Args;
+    ArgInfo *getArgsBuffer() {
+      return reinterpret_cast<ArgInfo*>(this+1);
+    }
+    const ArgInfo *getArgsBuffer() const {
+      return reinterpret_cast<const ArgInfo*>(this + 1);
+    }
=20
-    /// How many arguments to pass inreg.
-    bool HasRegParm;
-    unsigned RegParm;
+    CGFunctionInfo() : Required(RequiredArgs::All) {}
=20
   public:
+    static CGFunctionInfo *create(unsigned llvmCC,
+                                  const FunctionType::ExtInfo &extInfo,
+                                  CanQualType resultType,
+                                  ArrayRef<CanQualType> argTypes,
+                                  RequiredArgs required);
+
     typedef const ArgInfo *const_arg_iterator;
     typedef ArgInfo *arg_iterator;
=20
-    CGFunctionInfo(unsigned CallingConvention, bool NoReturn,
-                   bool ReturnsRetained, bool HasRegParm, unsigned RegParm,
-                   CanQualType ResTy,
-                   const CanQualType *ArgTys, unsigned NumArgTys);
-    ~CGFunctionInfo() { delete[] Args; }
-
-    const_arg_iterator arg_begin() const { return Args + 1; }
-    const_arg_iterator arg_end() const { return Args + 1 + NumArgs; }
-    arg_iterator arg_begin() { return Args + 1; }
-    arg_iterator arg_end() { return Args + 1 + NumArgs; }
+    const_arg_iterator arg_begin() const { return getArgsBuffer() + 1; }
+    const_arg_iterator arg_end() const { return getArgsBuffer() + 1 + NumA=
rgs; }
+    arg_iterator arg_begin() { return getArgsBuffer() + 1; }
+    arg_iterator arg_end() { return getArgsBuffer() + 1 + NumArgs; }
=20
     unsigned  arg_size() const { return NumArgs; }
=20
+    bool isVariadic() const { return Required.allowsOptionalArgs(); }
+    RequiredArgs getRequiredArgs() const { return Required; }
+
     bool isNoReturn() const { return NoReturn; }
=20
-    /// In ARR, whether this function retains its return value.  This
+    /// In ARC, whether this function retains its return value.  This
     /// is not always reliable for call sites.
     bool isReturnsRetained() const { return ReturnsRetained; }
=20
+    /// getASTCallingConvention() - Return the AST-specified calling
+    /// convention.
+    CallingConv getASTCallingConvention() const {
+      return CallingConv(ASTCallingConvention);
+    }
+
     /// getCallingConvention - Return the user specified calling
-    /// convention.
+    /// convention, which has been translated into an LLVM CC.
     unsigned getCallingConvention() const { return CallingConvention; }
=20
     /// getEffectiveCallingConvention - Return the actual calling conventi=
on to
@@ -172,36 +242,44 @@
     bool getHasRegParm() const { return HasRegParm; }
     unsigned getRegParm() const { return RegParm; }
=20
-    CanQualType getReturnType() const { return Args[0].type; }
+    FunctionType::ExtInfo getExtInfo() const {
+      return FunctionType::ExtInfo(isNoReturn(),
+                                   getHasRegParm(), getRegParm(),
+                                   getASTCallingConvention(),
+                                   isReturnsRetained());
+    }
=20
-    ABIArgInfo &getReturnInfo() { return Args[0].info; }
-    const ABIArgInfo &getReturnInfo() const { return Args[0].info; }
+    CanQualType getReturnType() const { return getArgsBuffer()[0].type; }
+
+    ABIArgInfo &getReturnInfo() { return getArgsBuffer()[0].info; }
+    const ABIArgInfo &getReturnInfo() const { return getArgsBuffer()[0].in=
fo; }
=20
     void Profile(llvm::FoldingSetNodeID &ID) {
-      ID.AddInteger(getCallingConvention());
+      ID.AddInteger(getASTCallingConvention());
       ID.AddBoolean(NoReturn);
       ID.AddBoolean(ReturnsRetained);
       ID.AddBoolean(HasRegParm);
       ID.AddInteger(RegParm);
+      ID.AddInteger(Required.getOpaqueData());
       getReturnType().Profile(ID);
       for (arg_iterator it =3D arg_begin(), ie =3D arg_end(); it !=3D ie; =
++it)
         it->type.Profile(ID);
     }
-    template<class Iterator>
     static void Profile(llvm::FoldingSetNodeID &ID,
-                        const FunctionType::ExtInfo &Info,
-                        CanQualType ResTy,
-                        Iterator begin,
-                        Iterator end) {
-      ID.AddInteger(Info.getCC());
-      ID.AddBoolean(Info.getNoReturn());
-      ID.AddBoolean(Info.getProducesResult());
-      ID.AddBoolean(Info.getHasRegParm());
-      ID.AddInteger(Info.getRegParm());
-      ResTy.Profile(ID);
-      for (; begin !=3D end; ++begin) {
-        CanQualType T =3D *begin; // force iterator to be over canonical t=
ypes
-        T.Profile(ID);
+                        const FunctionType::ExtInfo &info,
+                        RequiredArgs required,
+                        CanQualType resultType,
+                        ArrayRef<CanQualType> argTypes) {
+      ID.AddInteger(info.getCC());
+      ID.AddBoolean(info.getNoReturn());
+      ID.AddBoolean(info.getProducesResult());
+      ID.AddBoolean(info.getHasRegParm());
+      ID.AddInteger(info.getRegParm());
+      ID.AddInteger(required.getOpaqueData());
+      resultType.Profile(ID);
+      for (ArrayRef<CanQualType>::iterator
+             i =3D argTypes.begin(), e =3D argTypes.end(); i !=3D e; ++i) {
+        i->Profile(ID);
       }
     }
   };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGClass.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGClass.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGClass.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -11,6 +11,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "CGBlocks.h"
 #include "CGDebugInfo.h"
 #include "CodeGenFunction.h"
 #include "clang/AST/CXXInheritance.h"
@@ -95,7 +96,6 @@
   // TODO: for complete types, this should be possible with a GEP.
   llvm::Value *V =3D This;
   if (Offset.isPositive()) {
-    llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(getLLVMContext());
     V =3D Builder.CreateBitCast(V, Int8PtrTy);
     V =3D Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
   }
@@ -125,8 +125,7 @@
     BaseOffset =3D NonVirtualOffset;
  =20
   // Apply the base offset.
-  llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
-  ThisPtr =3D CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
+  ThisPtr =3D CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy);
   ThisPtr =3D CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
=20
   return ThisPtr;
@@ -250,9 +249,9 @@
   }
  =20
   // Apply the offset.
-  Value =3D Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
-  Value =3D Builder.CreateSub(Value, NonVirtualOffset);
-  Value =3D Builder.CreateIntToPtr(Value, DerivedPtrTy);
+  Value =3D Builder.CreateBitCast(Value, Int8PtrTy);
+  Value =3D Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
+                            "sub.ptr");
=20
   // Just cast.
   Value =3D Builder.CreateBitCast(Value, DerivedPtrTy);
@@ -397,16 +396,16 @@
     CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
                                               BaseClassDecl,
                                               isBaseVirtual);
-
+  CharUnits Alignment =3D CGF.getContext().getTypeAlignInChars(BaseType);
   AggValueSlot AggSlot =3D
-    AggValueSlot::forAddr(V, Qualifiers(),
+    AggValueSlot::forAddr(V, Alignment, Qualifiers(),
                           AggValueSlot::IsDestructed,
                           AggValueSlot::DoesNotNeedGCBarriers,
                           AggValueSlot::IsNotAliased);
=20
   CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  =20
-  if (CGF.CGM.getLangOptions().Exceptions &&=20
+  if (CGF.CGM.getLangOpts().Exceptions &&=20
       !BaseClassDecl->hasTrivialDestructor())
     CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
                                           isBaseVirtual);
@@ -414,47 +413,59 @@
=20
 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
                                      LValue LHS,
+                                     Expr *Init,
                                      llvm::Value *ArrayIndexVar,
-                                     CXXCtorInitializer *MemberInit,
                                      QualType T,
+                                     ArrayRef<VarDecl *> ArrayIndexes,
                                      unsigned Index) {
-  if (Index =3D=3D MemberInit->getNumArrayIndices()) {
-    CodeGenFunction::RunCleanupsScope Cleanups(CGF);
-   =20
-    llvm::Value *Dest =3D LHS.getAddress();
-    if (ArrayIndexVar) {
-      // If we have an array index variable, load it and use it as an offs=
et.
-      // Then, increment the value.
-      llvm::Value *ArrayIndex =3D CGF.Builder.CreateLoad(ArrayIndexVar);
-      Dest =3D CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddres=
s");
-      llvm::Value *Next =3D llvm::ConstantInt::get(ArrayIndex->getType(), =
1);
-      Next =3D CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
-      CGF.Builder.CreateStore(Next, ArrayIndexVar);     =20
+  if (Index =3D=3D ArrayIndexes.size()) {
+    LValue LV =3D LHS;
+    { // Scope for Cleanups.
+      CodeGenFunction::RunCleanupsScope Cleanups(CGF);
+
+      if (ArrayIndexVar) {
+        // If we have an array index variable, load it and use it as an of=
fset.
+        // Then, increment the value.
+        llvm::Value *Dest =3D LHS.getAddress();
+        llvm::Value *ArrayIndex =3D CGF.Builder.CreateLoad(ArrayIndexVar);
+        Dest =3D CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddr=
ess");
+        llvm::Value *Next =3D llvm::ConstantInt::get(ArrayIndex->getType()=
, 1);
+        Next =3D CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
+        CGF.Builder.CreateStore(Next, ArrayIndexVar);   =20
+
+        // Update the LValue.
+        LV.setAddress(Dest);
+        CharUnits Align =3D CGF.getContext().getTypeAlignInChars(T);
+        LV.setAlignment(std::min(Align, LV.getAlignment()));
+      }
+
+      if (!CGF.hasAggregateLLVMType(T)) {
+        CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
+      } else if (T->isAnyComplexType()) {
+        CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
+                                    LV.isVolatileQualified());
+      } else {
+        AggValueSlot Slot =3D
+          AggValueSlot::forLValue(LV,
+                                  AggValueSlot::IsDestructed,
+                                  AggValueSlot::DoesNotNeedGCBarriers,
+                                  AggValueSlot::IsNotAliased);
+
+        CGF.EmitAggExpr(Init, Slot);
+      }
     }
=20
-    if (!CGF.hasAggregateLLVMType(T)) {
-      LValue lvalue =3D CGF.MakeAddrLValue(Dest, T);
-      CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, lvalue, false);
-    } else if (T->isAnyComplexType()) {
-      CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest,=20
-                                  LHS.isVolatileQualified());
-    } else {   =20
-      AggValueSlot Slot =3D
-        AggValueSlot::forAddr(Dest, LHS.getQuals(),
-                              AggValueSlot::IsDestructed,
-                              AggValueSlot::DoesNotNeedGCBarriers,
-                              AggValueSlot::IsNotAliased);
-     =20
-      CGF.EmitAggExpr(MemberInit->getInit(), Slot);
-    }
-   =20
+    // Now, outside of the initializer cleanup scope, destroy the backing =
array
+    // for a std::initializer_list member.
+    CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
+
     return;
   }
  =20
   const ConstantArrayType *Array =3D CGF.getContext().getAsConstantArrayTy=
pe(T);
   assert(Array && "Array initialization without the array type?");
   llvm::Value *IndexVar
-    =3D CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
+    =3D CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
   assert(IndexVar && "Array index variable not loaded");
  =20
   // Initialize this index variable to zero.
@@ -490,8 +501,8 @@
    =20
     // Inside the loop body recurse to emit the inner loop or, eventually,=
 the
     // constructor call.
-    EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,=20
-                             Array->getElementType(), Index + 1);
+    EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
+                             Array->getElementType(), ArrayIndexes, Index =
+ 1);
   }
  =20
   CGF.EmitBlock(ContinueBlock);
@@ -511,19 +522,15 @@
=20
 namespace {
   struct CallMemberDtor : EHScopeStack::Cleanup {
-    FieldDecl *Field;
+    llvm::Value *V;
     CXXDestructorDecl *Dtor;
=20
-    CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
-      : Field(Field), Dtor(Dtor) {}
+    CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
+      : V(V), Dtor(Dtor) {}
=20
     void Emit(CodeGenFunction &CGF, Flags flags) {
-      // FIXME: Is this OK for C++0x delegating constructors?
-      llvm::Value *ThisPtr =3D CGF.LoadCXXThis();
-      LValue LHS =3D CGF.EmitLValueForField(ThisPtr, Field, 0);
-
       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=3D*/=
false,
-                                LHS.getAddress());
+                                V);
     }
   };
 }
@@ -533,7 +540,7 @@
   return Moving ? Record->hasTrivialMoveConstructor() :
                   Record->hasTrivialCopyConstructor();
 }
- =20
+
 static void EmitMemberInitializer(CodeGenFunction &CGF,
                                   const CXXRecordDecl *ClassDecl,
                                   CXXCtorInitializer *MemberInit,
@@ -545,7 +552,7 @@
  =20
   // non-static data member initializers.
   FieldDecl *Field =3D MemberInit->getAnyMember();
-  QualType FieldType =3D CGF.getContext().getCanonicalType(Field->getType(=
));
+  QualType FieldType =3D Field->getType();
=20
   llvm::Value *ThisPtr =3D CGF.LoadCXXThis();
   LValue LHS;
@@ -559,67 +566,83 @@
     LHS =3D CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
   }
=20
-  if (!CGF.hasAggregateLLVMType(Field->getType())) {
+  // Special case: if we are in a copy or move constructor, and we are cop=
ying
+  // an array of PODs or classes with trivial copy constructors, ignore the
+  // AST and perform the copy we know is equivalent.
+  // FIXME: This is hacky at best... if we had a bit more explicit informa=
tion
+  // in the AST, we could generalize it more easily.
+  const ConstantArrayType *Array
+    =3D CGF.getContext().getAsConstantArrayType(FieldType);
+  if (Array && Constructor->isImplicitlyDefined() &&
+      Constructor->isCopyOrMoveConstructor()) {
+    QualType BaseElementTy =3D CGF.getContext().getBaseElementType(Array);
+    const CXXRecordDecl *Record =3D BaseElementTy->getAsCXXRecordDecl();
+    if (BaseElementTy.isPODType(CGF.getContext()) ||
+        (Record && hasTrivialCopyOrMoveConstructor(Record,
+                       Constructor->isMoveConstructor()))) {
+      // Find the source pointer. We knows it's the last argument because
+      // we know we're in a copy constructor.
+      unsigned SrcArgIndex =3D Args.size() - 1;
+      llvm::Value *SrcPtr
+        =3D CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]=
));
+      LValue Src =3D CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0=
);
+     =20
+      // Copy the aggregate.
+      CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
+                            LHS.isVolatileQualified());
+      return;
+    }
+  }
+
+  ArrayRef<VarDecl *> ArrayIndexes;
+  if (MemberInit->getNumArrayIndices())
+    ArrayIndexes =3D MemberInit->getArrayIndexes();
+  CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayInde=
xes);
+}
+
+void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
+                                              LValue LHS, Expr *Init,
+                                             ArrayRef<VarDecl *> ArrayInde=
xes) {
+  QualType FieldType =3D Field->getType();
+  if (!hasAggregateLLVMType(FieldType)) {
     if (LHS.isSimple()) {
-      CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false);
+      EmitExprAsInit(Init, Field, LHS, false);
     } else {
-      RValue RHS =3D RValue::get(CGF.EmitScalarExpr(MemberInit->getInit())=
);
-      CGF.EmitStoreThroughLValue(RHS, LHS);
+      RValue RHS =3D RValue::get(EmitScalarExpr(Init));
+      EmitStoreThroughLValue(RHS, LHS);
     }
-  } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
-    CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
-                                LHS.isVolatileQualified());
+  } else if (FieldType->isAnyComplexType()) {
+    EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualifie=
d());
   } else {
     llvm::Value *ArrayIndexVar =3D 0;
-    const ConstantArrayType *Array
-      =3D CGF.getContext().getAsConstantArrayType(FieldType);
-    if (Array && Constructor->isImplicitlyDefined() &&
-        Constructor->isCopyOrMoveConstructor()) {
-      llvm::Type *SizeTy
-        =3D CGF.ConvertType(CGF.getContext().getSizeType());
+    if (ArrayIndexes.size()) {
+      llvm::Type *SizeTy =3D ConvertType(getContext().getSizeType());
      =20
       // The LHS is a pointer to the first object we'll be constructing, as
       // a flat array.
-      QualType BaseElementTy =3D CGF.getContext().getBaseElementType(Array=
);
-      llvm::Type *BasePtr =3D CGF.ConvertType(BaseElementTy);
+      QualType BaseElementTy =3D getContext().getBaseElementType(FieldType=
);
+      llvm::Type *BasePtr =3D ConvertType(BaseElementTy);
       BasePtr =3D llvm::PointerType::getUnqual(BasePtr);
-      llvm::Value *BaseAddrPtr =3D CGF.Builder.CreateBitCast(LHS.getAddres=
s(),=20
-                                                           BasePtr);
-      LHS =3D CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
+      llvm::Value *BaseAddrPtr =3D Builder.CreateBitCast(LHS.getAddress(),=20
+                                                       BasePtr);
+      LHS =3D MakeAddrLValue(BaseAddrPtr, BaseElementTy);
      =20
       // Create an array index that will be used to walk over all of the
       // objects we're constructing.
-      ArrayIndexVar =3D CGF.CreateTempAlloca(SizeTy, "object.index");
+      ArrayIndexVar =3D CreateTempAlloca(SizeTy, "object.index");
       llvm::Value *Zero =3D llvm::Constant::getNullValue(SizeTy);
-      CGF.Builder.CreateStore(Zero, ArrayIndexVar);
+      Builder.CreateStore(Zero, ArrayIndexVar);
      =20
-      // If we are copying an array of PODs or classes with trivial copy=20
-      // constructors, perform a single aggregate copy.
-      const CXXRecordDecl *Record =3D BaseElementTy->getAsCXXRecordDecl();
-      if (BaseElementTy.isPODType(CGF.getContext()) ||
-          (Record && hasTrivialCopyOrMoveConstructor(Record,
-                         Constructor->isMoveConstructor()))) {
-        // Find the source pointer. We knows it's the last argument because
-        // we know we're in a copy constructor.
-        unsigned SrcArgIndex =3D Args.size() - 1;
-        llvm::Value *SrcPtr
-          =3D CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgInde=
x]));
-        LValue Src =3D CGF.EmitLValueForFieldInitialization(SrcPtr, Field,=
 0);
-       =20
-        // Copy the aggregate.
-        CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldTyp=
e,
-                              LHS.isVolatileQualified());
-        return;
-      }
      =20
       // Emit the block variables for the array indices, if any.
-      for (unsigned I =3D 0, N =3D MemberInit->getNumArrayIndices(); I !=
=3D N; ++I)
-        CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
+      for (unsigned I =3D 0, N =3D ArrayIndexes.size(); I !=3D N; ++I)
+        EmitAutoVarDecl(*ArrayIndexes[I]);
     }
    =20
-    EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldTyp=
e, 0);
+    EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
+                             ArrayIndexes, 0);
    =20
-    if (!CGF.CGM.getLangOptions().Exceptions)
+    if (!CGM.getLangOpts().Exceptions)
       return;
=20
     // FIXME: If we have an array of classes w/ non-trivial destructors,=20
@@ -631,8 +654,8 @@
    =20
     CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RT->getDecl());
     if (!RD->hasTrivialDestructor())
-      CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
-                                              RD->getDestructor());
+      EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
+                                          RD->getDestructor());
   }
 }
=20
@@ -708,6 +731,9 @@
=20
   EHScopeStack::stable_iterator CleanupDepth =3D EHStack.stable_begin();
=20
+  // TODO: in restricted cases, we can emit the vbase initializers of
+  // a complete ctor and then delegate to the base ctor.
+
   // Emit the constructor prologue, i.e. the base and member
   // initializers.
   EmitCtorPrologue(Ctor, CtorType, Args);
@@ -912,7 +938,7 @@
     }
     // -fapple-kext must inline any call to this dtor into
     // the caller's body.
-    if (getContext().getLangOptions().AppleKext)
+    if (getContext().getLangOpts().AppleKext)
       CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
     break;
   }
@@ -940,13 +966,13 @@
=20
   class DestroyField  : public EHScopeStack::Cleanup {
     const FieldDecl *field;
-    CodeGenFunction::Destroyer &destroyer;
+    CodeGenFunction::Destroyer *destroyer;
     bool useEHCleanupForArray;
=20
   public:
     DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destr=
oyer,
                  bool useEHCleanupForArray)
-      : field(field), destroyer(*destroyer),
+      : field(field), destroyer(destroyer),
         useEHCleanupForArray(useEHCleanupForArray) {}
=20
     void Emit(CodeGenFunction &CGF, Flags flags) {
@@ -1039,6 +1065,10 @@
     QualType::DestructionKind dtorKind =3D type.isDestructedType();
     if (!dtorKind) continue;
=20
+    // Anonymous union members do not have their destructors called.
+    const RecordType *RT =3D type->getAsUnionType();
+    if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
+
     CleanupKind cleanupKind =3D getCleanupKind(dtorKind);
     EHStack.pushCleanup<DestroyField>(cleanupKind, field,
                                       getDestroyer(dtorKind),
@@ -1145,7 +1175,7 @@
=20
     // Evaluate the constructor and its arguments in a regular
     // partial-destroy cleanup.
-    if (getLangOptions().Exceptions &&
+    if (getLangOpts().Exceptions &&
         !ctor->getParent()->hasTrivialDestructor()) {
       Destroyer *destroyer =3D destroyCXXObject;
       pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
@@ -1192,8 +1222,8 @@
=20
   CGDebugInfo *DI =3D getDebugInfo();
   if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
-    // If debug info for this class has been emitted then this is the righ=
t time
-    // to do so.
+    // If debug info for this class has not been emitted then this is the
+    // right time to do so.
     const CXXRecordDecl *Parent =3D D->getParent();
     DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
                               Parent->getLocation());
@@ -1273,7 +1303,7 @@
     EmitCallArg(Args, *Arg, ArgType);
   }
  =20
-  EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
+  EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
            ReturnValueSlot(), Args, D);
 }
=20
@@ -1309,7 +1339,7 @@
     EmitDelegateCallArg(DelegateArgs, param);
   }
=20
-  EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
+  EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
            CGM.GetAddrOfCXXConstructor(Ctor, CtorType),=20
            ReturnValueSlot(), DelegateArgs, Ctor);
 }
@@ -1338,8 +1368,10 @@
=20
   llvm::Value *ThisPtr =3D LoadCXXThis();
=20
+  QualType Ty =3D getContext().getTagDeclType(Ctor->getParent());
+  CharUnits Alignment =3D getContext().getTypeAlignInChars(Ty);
   AggValueSlot AggSlot =3D
-    AggValueSlot::forAddr(ThisPtr, Qualifiers(),
+    AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
                           AggValueSlot::IsDestructed,
                           AggValueSlot::DoesNotNeedGCBarriers,
                           AggValueSlot::IsNotAliased);
@@ -1347,7 +1379,7 @@
   EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
=20
   const CXXRecordDecl *ClassDecl =3D Ctor->getParent();
-  if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor(=
)) {
+  if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
     CXXDtorType Type =3D
       CurGD.getCtorType() =3D=3D Ctor_Complete ? Dtor_Complete : Dtor_Base;
=20
@@ -1364,7 +1396,7 @@
   llvm::Value *VTT =3D GetVTTParameter(*this, GlobalDecl(DD, Type),=20
                                      ForVirtualBase);
   llvm::Value *Callee =3D 0;
-  if (getContext().getLangOptions().AppleKext)
+  if (getContext().getLangOpts().AppleKext)
     Callee =3D BuildAppleKextVirtualDestructorCall(DD, Type,=20
                                                  DD->getParent());
    =20
@@ -1485,7 +1517,8 @@
   llvm::Type *AddressPointPtrTy =3D
     VTableAddressPoint->getType()->getPointerTo();
   VTableField =3D Builder.CreateBitCast(VTableField, AddressPointPtrTy);
-  Builder.CreateStore(VTableAddressPoint, VTableField);
+  llvm::StoreInst *Store =3D Builder.CreateStore(VTableAddressPoint, VTabl=
eField);
+  CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
 }
=20
 void
@@ -1568,7 +1601,9 @@
 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
                                            llvm::Type *Ty) {
   llvm::Value *VTablePtrSrc =3D Builder.CreateBitCast(This, Ty->getPointer=
To());
-  return Builder.CreateLoad(VTablePtrSrc, "vtable");
+  llvm::Instruction *VTable =3D Builder.CreateLoad(VTablePtrSrc, "vtable");
+  CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
+  return VTable;
 }
=20
 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
@@ -1682,7 +1717,7 @@
  =20
   // When building with -fapple-kext, all calls must go through the vtable=
 since
   // the kernel linker can do runtime patching of vtables.
-  if (Context.getLangOptions().AppleKext)
+  if (Context.getLangOpts().AppleKext)
     return true;
=20
   return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
@@ -1692,13 +1727,110 @@
 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
                                              const CXXMethodDecl *MD,
                                              llvm::Value *This) {
-  const FunctionProtoType *FPT =3D MD->getType()->castAs<FunctionProtoType=
>();
-  llvm::Type *Ty =3D
-    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
-                                   FPT->isVariadic());
+  llvm::FunctionType *fnType =3D
+    CGM.getTypes().GetFunctionType(
+                             CGM.getTypes().arrangeCXXMethodDeclaration(MD=
));
=20
   if (UseVirtualCall(getContext(), E, MD))
-    return BuildVirtualCall(MD, This, Ty);
+    return BuildVirtualCall(MD, This, fnType);
=20
-  return CGM.GetAddrOfFunction(MD, Ty);
+  return CGM.GetAddrOfFunction(MD, fnType);
 }
+
+void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *Lamb=
da,
+                                                 CallArgList &CallArgs) {
+  // Lookup the call operator
+  DeclarationName Name
+    =3D getContext().DeclarationNames.getCXXOperatorName(OO_Call);
+  DeclContext::lookup_const_result Calls =3D Lambda->lookup(Name);
+  CXXMethodDecl *CallOperator =3D cast<CXXMethodDecl>(*Calls.first++);
+  const FunctionProtoType *FPT =3D
+      CallOperator->getType()->getAs<FunctionProtoType>();
+  QualType ResultType =3D FPT->getResultType();
+
+  // Get the address of the call operator.
+  GlobalDecl GD(CallOperator);
+  const CGFunctionInfo &CalleeFnInfo =3D
+    CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtIn=
fo(),
+                                       RequiredArgs::forPrototypePlus(FPT,=
 1));
+  llvm::Type *Ty =3D CGM.getTypes().GetFunctionType(CalleeFnInfo);
+  llvm::Value *Callee =3D CGM.GetAddrOfFunction(GD, Ty);
+
+  // Determine whether we have a return value slot to use.
+  ReturnValueSlot Slot;
+  if (!ResultType->isVoidType() &&
+      CurFnInfo->getReturnInfo().getKind() =3D=3D ABIArgInfo::Indirect &&
+      hasAggregateLLVMType(CurFnInfo->getReturnType()))
+    Slot =3D ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified()=
);
+ =20
+  // Now emit our call.
+  RValue RV =3D EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperato=
r);
+
+  // Forward the returned value
+  if (!ResultType->isVoidType() && Slot.isNull())
+    EmitReturnOfRValue(RV, ResultType);
+}
+
+void CodeGenFunction::EmitLambdaBlockInvokeBody() {
+  const BlockDecl *BD =3D BlockInfo->getBlockDecl();
+  const VarDecl *variable =3D BD->capture_begin()->getVariable();
+  const CXXRecordDecl *Lambda =3D variable->getType()->getAsCXXRecordDecl(=
);
+
+  // Start building arguments for forwarding call
+  CallArgList CallArgs;
+
+  QualType ThisType =3D getContext().getPointerType(getContext().getRecord=
Type(Lambda));
+  llvm::Value *ThisPtr =3D GetAddrOfBlockDecl(variable, false);
+  CallArgs.add(RValue::get(ThisPtr), ThisType);
+
+  // Add the rest of the parameters.
+  for (BlockDecl::param_const_iterator I =3D BD->param_begin(),
+       E =3D BD->param_end(); I !=3D E; ++I) {
+    ParmVarDecl *param =3D *I;
+    EmitDelegateCallArg(CallArgs, param);
+  }
+
+  EmitForwardingCallToLambda(Lambda, CallArgs);
+}
+
+void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
+  if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
+    // FIXME: Making this work correctly is nasty because it requires eith=
er
+    // cloning the body of the call operator or making the call operator f=
orward.
+    CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic funct=
ion");
+    return;
+  }
+
+  EmitFunctionBody(Args);
+}
+
+void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *=
MD) {
+  const CXXRecordDecl *Lambda =3D MD->getParent();
+
+  // Start building arguments for forwarding call
+  CallArgList CallArgs;
+
+  QualType ThisType =3D getContext().getPointerType(getContext().getRecord=
Type(Lambda));
+  llvm::Value *ThisPtr =3D llvm::UndefValue::get(getTypes().ConvertType(Th=
isType));
+  CallArgs.add(RValue::get(ThisPtr), ThisType);
+
+  // Add the rest of the parameters.
+  for (FunctionDecl::param_const_iterator I =3D MD->param_begin(),
+       E =3D MD->param_end(); I !=3D E; ++I) {
+    ParmVarDecl *param =3D *I;
+    EmitDelegateCallArg(CallArgs, param);
+  }
+
+  EmitForwardingCallToLambda(Lambda, CallArgs);
+}
+
+void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *=
MD) {
+  if (MD->isVariadic()) {
+    // FIXME: Making this work correctly is nasty because it requires eith=
er
+    // cloning the body of the call operator or making the call operator f=
orward.
+    CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
+    return;
+  }
+
+  EmitLambdaDelegatingInvokeBody(MD);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGCleanup.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGCleanup.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGCleanup.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -84,7 +84,6 @@
   }
=20
   llvm_unreachable("bad saved r-value kind");
-  return RValue();
 }
=20
 /// Push an entry of the given size onto this protected-scope stack.
@@ -251,8 +250,7 @@
=20
   // Initialize it to false at a site that's guaranteed to be run
   // before each evaluation.
-  llvm::BasicBlock *block =3D OutermostConditional->getStartingBlock();
-  new llvm::StoreInst(Builder.getFalse(), active, &block->back());
+  setBeforeOutermostConditional(Builder.getFalse(), active);
=20
   // Initialize it to true at the current location.
   Builder.CreateStore(Builder.getTrue(), active);
@@ -504,9 +502,9 @@
    =20
     // The only uses should be fixup switches.
     llvm::SwitchInst *si =3D cast<llvm::SwitchInst>(use.getUser());
-    if (si->getNumCases() =3D=3D 2 && si->getDefaultDest() =3D=3D unreacha=
bleBB) {
+    if (si->getNumCases() =3D=3D 1 && si->getDefaultDest() =3D=3D unreacha=
bleBB) {
       // Replace the switch with a branch.
-      llvm::BranchInst::Create(si->getSuccessor(1), si);
+      llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
=20
       // The switch operand is a load from the cleanup-dest alloca.
       llvm::LoadInst *condition =3D cast<llvm::LoadInst>(si->getCondition(=
));
@@ -1000,57 +998,75 @@
 /// extra uses *after* the change-over point.
 static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
                                         EHScopeStack::stable_iterator C,
-                                        ForActivation_t Kind) {
+                                        ForActivation_t kind,
+                                        llvm::Instruction *dominatingIP) {
   EHCleanupScope &Scope =3D cast<EHCleanupScope>(*CGF.EHStack.find(C));
=20
-  // We always need the flag if we're activating the cleanup, because
-  // we have to assume that the current location doesn't necessarily
-  // dominate all future uses of the cleanup.
-  bool NeedFlag =3D (Kind =3D=3D ForActivation);
+  // We always need the flag if we're activating the cleanup in a
+  // conditional context, because we have to assume that the current
+  // location doesn't necessarily dominate the cleanup's code.
+  bool isActivatedInConditional =3D
+    (kind =3D=3D ForActivation && CGF.isInConditionalBranch());
+
+  bool needFlag =3D false;
=20
   // Calculate whether the cleanup was used:
=20
   //   - as a normal cleanup
-  if (Scope.isNormalCleanup() && IsUsedAsNormalCleanup(CGF.EHStack, C)) {
+  if (Scope.isNormalCleanup() &&
+      (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C)))=
 {
     Scope.setTestFlagInNormalCleanup();
-    NeedFlag =3D true;
+    needFlag =3D true;
   }
=20
   //  - as an EH cleanup
-  if (Scope.isEHCleanup() && IsUsedAsEHCleanup(CGF.EHStack, C)) {
+  if (Scope.isEHCleanup() &&
+      (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
     Scope.setTestFlagInEHCleanup();
-    NeedFlag =3D true;
+    needFlag =3D true;
   }
=20
   // If it hasn't yet been used as either, we're done.
-  if (!NeedFlag) return;
+  if (!needFlag) return;
=20
-  llvm::AllocaInst *Var =3D Scope.getActiveFlag();
-  if (!Var) {
-    Var =3D CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactiv=
e");
-    Scope.setActiveFlag(Var);
+  llvm::AllocaInst *var =3D Scope.getActiveFlag();
+  if (!var) {
+    var =3D CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactiv=
e");
+    Scope.setActiveFlag(var);
+
+    assert(dominatingIP && "no existing variable and no dominating IP!");
=20
     // Initialize to true or false depending on whether it was
     // active up to this point.
-    CGF.InitTempAlloca(Var, CGF.Builder.getInt1(Kind =3D=3D ForDeactivatio=
n));
+    llvm::Value *value =3D CGF.Builder.getInt1(kind =3D=3D ForDeactivation=
);
+
+    // If we're in a conditional block, ignore the dominating IP and
+    // use the outermost conditional branch.
+    if (CGF.isInConditionalBranch()) {
+      CGF.setBeforeOutermostConditional(value, var);
+    } else {
+      new llvm::StoreInst(value, var, dominatingIP);
+    }
   }
=20
-  CGF.Builder.CreateStore(CGF.Builder.getInt1(Kind =3D=3D ForActivation), =
Var);
+  CGF.Builder.CreateStore(CGF.Builder.getInt1(kind =3D=3D ForActivation), =
var);
 }
=20
 /// Activate a cleanup that was created in an inactivated state.
-void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C=
) {
+void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
+                                           llvm::Instruction *dominatingIP=
) {
   assert(C !=3D EHStack.stable_end() && "activating bottom of stack?");
   EHCleanupScope &Scope =3D cast<EHCleanupScope>(*EHStack.find(C));
   assert(!Scope.isActive() && "double activation");
=20
-  SetupCleanupBlockActivation(*this, C, ForActivation);
+  SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
=20
   Scope.setActive(true);
 }
=20
 /// Deactive a cleanup that was created in an active state.
-void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator=
 C) {
+void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator=
 C,
+                                             llvm::Instruction *dominating=
IP) {
   assert(C !=3D EHStack.stable_end() && "deactivating bottom of stack?");
   EHCleanupScope &Scope =3D cast<EHCleanupScope>(*EHStack.find(C));
   assert(Scope.isActive() && "double deactivation");
@@ -1066,7 +1082,7 @@
   }
=20
   // Otherwise, follow the general case.
-  SetupCleanupBlockActivation(*this, C, ForDeactivation);
+  SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
=20
   Scope.setActive(false);
 }
@@ -1077,3 +1093,11 @@
       CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
   return NormalCleanupDest;
 }
+
+/// Emits all the code to cause the given temporary to be cleaned up.
+void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
+                                       QualType TempType,
+                                       llvm::Value *Ptr) {
+  pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
+              /*useEHCleanup*/ true);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGDebugInfo.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -35,7 +35,6 @@
 #include "llvm/Support/Dwarf.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Target/TargetData.h"
-#include "llvm/Target/TargetMachine.h"
 using namespace clang;
 using namespace clang::CodeGen;
=20
@@ -75,7 +74,7 @@
     llvm::DILexicalBlockFile LBF =3D llvm::DILexicalBlockFile(LB);
     llvm::DIDescriptor D
       =3D DBuilder.createLexicalBlockFile(LBF.getScope(),
-					getOrCreateFile(CurLoc));
+                                        getOrCreateFile(CurLoc));
     llvm::MDNode *N =3D D;
     LexicalBlockStack.pop_back();
     LexicalBlockStack.push_back(N);
@@ -118,12 +117,25 @@
 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
   assert (FD && "Invalid FunctionDecl!");
   IdentifierInfo *FII =3D FD->getIdentifier();
-  if (FII)
+  FunctionTemplateSpecializationInfo *Info
+    =3D FD->getTemplateSpecializationInfo();
+  if (!Info && FII)
     return FII->getName();
=20
   // Otherwise construct human readable name for debug info.
   std::string NS =3D FD->getNameAsString();
=20
+  // Add any template specialization args.
+  if (Info) {
+    const TemplateArgumentList *TArgs =3D Info->TemplateArguments;
+    const TemplateArgument *Args =3D TArgs->data();
+    unsigned NumArgs =3D TArgs->size();
+    PrintingPolicy Policy(CGM.getLangOpts());
+    NS +=3D TemplateSpecializationType::PrintTemplateArgumentList(Args,
+                                                                NumArgs,
+                                                                Policy);
+  }
+
   // Copy this name on the side and use its reference.
   char *StrPtr =3D DebugInfoNames.Allocate<char>(NS.length());
   memcpy(StrPtr, NS.data(), NS.length());
@@ -131,7 +143,7 @@
 }
=20
 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
-  llvm::SmallString<256> MethodName;
+  SmallString<256> MethodName;
   llvm::raw_svector_ostream OS(MethodName);
   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
   const DeclContext *DC =3D OMD->getDeclContext();
@@ -164,8 +176,8 @@
=20
 /// getClassName - Get class name including template argument list.
 StringRef=20
-CGDebugInfo::getClassName(RecordDecl *RD) {
-  ClassTemplateSpecializationDecl *Spec
+CGDebugInfo::getClassName(const RecordDecl *RD) {
+  const ClassTemplateSpecializationDecl *Spec
     =3D dyn_cast<ClassTemplateSpecializationDecl>(RD);
   if (!Spec)
     return RD->getName();
@@ -184,7 +196,7 @@
     NumArgs =3D TemplateArgs.size();
   }
   Buffer =3D RD->getIdentifier()->getNameStart();
-  PrintingPolicy Policy(CGM.getLangOptions());
+  PrintingPolicy Policy(CGM.getLangOpts());
   Buffer +=3D TemplateSpecializationType::PrintTemplateArgumentList(Args,
                                                                   NumArgs,
                                                                   Policy);
@@ -223,7 +235,6 @@
=20
   DIFileCache[fname] =3D F;
   return F;
-
 }
=20
 /// getOrCreateMainFile - Get the file info for main compile unit.
@@ -234,7 +245,8 @@
 /// getLineNumber - Get line number for the location. If location is inval=
id
 /// then use current location.
 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
-  assert((Loc.isValid() || CurLoc.isValid()) && "Invalid current location!=
");
+  if (Loc.isInvalid() && CurLoc.isInvalid())
+    return 0;
   SourceManager &SM =3D CGM.getContext().getSourceManager();
   PresumedLoc PLoc =3D SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
   return PLoc.isValid()? PLoc.getLine() : 0;
@@ -243,16 +255,20 @@
 /// getColumnNumber - Get column number for the location. If location is=20
 /// invalid then use current location.
 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
-  assert((Loc.isValid() || CurLoc.isValid()) && "Invalid current location!=
");
+  if (Loc.isInvalid() && CurLoc.isInvalid())
+    return 0;
   SourceManager &SM =3D CGM.getContext().getSourceManager();
   PresumedLoc PLoc =3D SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
   return PLoc.isValid()? PLoc.getColumn() : 0;
 }
=20
 StringRef CGDebugInfo::getCurrentDirname() {
+  if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
+    return CGM.getCodeGenOpts().DebugCompilationDir;
+
   if (!CWDName.empty())
     return CWDName;
-  llvm::SmallString<256> CWD;
+  SmallString<256> CWD;
   llvm::sys::fs::current_path(CWD);
   char *CompDirnamePtr =3D DebugInfoNames.Allocate<char>(CWD.size());
   memcpy(CompDirnamePtr, CWD.data(), CWD.size());
@@ -285,7 +301,7 @@
   StringRef Filename(FilenamePtr, MainFileName.length());
  =20
   unsigned LangTag;
-  const LangOptions &LO =3D CGM.getLangOptions();
+  const LangOptions &LO =3D CGM.getLangOpts();
   if (LO.CPlusPlus) {
     if (LO.ObjC1)
       LangTag =3D llvm::dwarf::DW_LANG_ObjC_plus_plus;
@@ -321,35 +337,32 @@
   unsigned Encoding =3D 0;
   const char *BTName =3D NULL;
   switch (BT->getKind()) {
+#define BUILTIN_TYPE(Id, SingletonId)
+#define PLACEHOLDER_TYPE(Id, SingletonId) \
+  case BuiltinType::Id:
+#include "clang/AST/BuiltinTypes.def"
   case BuiltinType::Dependent:
-    llvm_unreachable("Unexpected builtin type Dependent");
-  case BuiltinType::Overload:
-    llvm_unreachable("Unexpected builtin type Overload");
-  case BuiltinType::BoundMember:
-    llvm_unreachable("Unexpected builtin type BoundMember");
-  case BuiltinType::UnknownAny:
-    llvm_unreachable("Unexpected builtin type UnknownAny");
+    llvm_unreachable("Unexpected builtin type");
   case BuiltinType::NullPtr:
     return DBuilder.
-      createNullPtrType(BT->getName(CGM.getContext().getLangOptions()));
+      createNullPtrType(BT->getName(CGM.getContext().getLangOpts()));
   case BuiltinType::Void:
     return llvm::DIType();
   case BuiltinType::ObjCClass:
-    return DBuilder.createStructType(TheCU, "objc_class",=20
-                                     getOrCreateMainFile(), 0, 0, 0,
-                                     llvm::DIDescriptor::FlagFwdDecl,=20
-                                     llvm::DIArray());
+    return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
+                                      "objc_class", getOrCreateMainFile(),
+                                      0);
   case BuiltinType::ObjCId: {
     // typedef struct objc_class *Class;
     // typedef struct objc_object {
     //  Class isa;
     // } *id;
=20
-    llvm::DIType OCTy =3D=20
-      DBuilder.createStructType(TheCU, "objc_class",=20
-                                getOrCreateMainFile(), 0, 0, 0,
-                                llvm::DIDescriptor::FlagFwdDecl,=20
-                                llvm::DIArray());
+    // TODO: Cache these two types to avoid duplicates.
+    llvm::DIType OCTy =3D
+      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
+                                 "objc_class", getOrCreateMainFile(),
+                                 0);
     unsigned Size =3D CGM.getContext().getTypeSize(CGM.getContext().VoidPt=
rTy);
    =20
     llvm::DIType ISATy =3D DBuilder.createPointerType(OCTy, Size);
@@ -367,10 +380,10 @@
                                      0, 0, 0, 0, Elements);
   }
   case BuiltinType::ObjCSel: {
-    return  DBuilder.createStructType(TheCU, "objc_selector",=20
-                                      getOrCreateMainFile(), 0, 0, 0,
-                                      llvm::DIDescriptor::FlagFwdDecl,=20
-                                      llvm::DIArray());
+    return
+      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
+                                 "objc_selector", getOrCreateMainFile(),
+                                 0);
   }
   case BuiltinType::UChar:
   case BuiltinType::Char_U: Encoding =3D llvm::dwarf::DW_ATE_unsigned_char=
; break;
@@ -403,7 +416,7 @@
   case BuiltinType::ULong:     BTName =3D "long unsigned int"; break;
   case BuiltinType::ULongLong: BTName =3D "long long unsigned int"; break;
   default:
-    BTName =3D BT->getName(CGM.getContext().getLangOptions());
+    BTName =3D BT->getName(CGM.getContext().getLangOpts());
     break;
   }
   // Bit size, align and offset of the type.
@@ -479,34 +492,82 @@
                                Ty->getPointeeType(), Unit);
 }
=20
+// Creates a forward declaration for a RecordDecl in the given context.
+llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
+                                              llvm::DIDescriptor Ctx) {
+  llvm::DIFile DefUnit =3D getOrCreateFile(RD->getLocation());
+  unsigned Line =3D getLineNumber(RD->getLocation());
+  StringRef RDName =3D RD->getName();
+
+  // Get the tag.
+  const CXXRecordDecl *CXXDecl =3D dyn_cast<CXXRecordDecl>(RD);
+  unsigned Tag =3D 0;
+  if (CXXDecl) {
+    RDName =3D getClassName(RD);
+    Tag =3D llvm::dwarf::DW_TAG_class_type;
+  }
+  else if (RD->isStruct())
+    Tag =3D llvm::dwarf::DW_TAG_structure_type;
+  else if (RD->isUnion())
+    Tag =3D llvm::dwarf::DW_TAG_union_type;
+  else
+    llvm_unreachable("Unknown RecordDecl type!");
+
+  // Create the type.
+  return DBuilder.createForwardDecl(Tag, RDName, DefUnit, Line);
+}
+
+// Walk up the context chain and create forward decls for record decls,
+// and normal descriptors for namespaces.
+llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
+  if (!Context)
+    return TheCU;
+
+  // See if we already have the parent.
+  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
+    I =3D RegionMap.find(Context);
+  if (I !=3D RegionMap.end())
+    return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
+ =20
+  // Check namespace.
+  if (const NamespaceDecl *NSDecl =3D dyn_cast<NamespaceDecl>(Context))
+    return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
+
+  if (const RecordDecl *RD =3D dyn_cast<RecordDecl>(Context)) {
+    if (!RD->isDependentType()) {
+      llvm::DIType Ty =3D getOrCreateLimitedType(CGM.getContext().getTypeD=
eclType(RD),
+					       getOrCreateMainFile());
+      return llvm::DIDescriptor(Ty);
+    }
+  }
+  return TheCU;
+}
+
 /// CreatePointeeType - Create Pointee type. If Pointee is a record
 /// then emit record's fwd if debug info size reduction is enabled.
 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
                                             llvm::DIFile Unit) {
   if (!CGM.getCodeGenOpts().LimitDebugInfo)
     return getOrCreateType(PointeeTy, Unit);
- =20
+
+  // Limit debug info for the pointee type.
+
+  // If we have an existing type, use that, it's still smaller than creati=
ng
+  // a new type.
+  llvm::DIType Ty =3D getTypeOrNull(PointeeTy);
+  if (Ty.Verify()) return Ty;
+
+  // Handle qualifiers.
+  if (PointeeTy.hasLocalQualifiers())
+    return CreateQualifiedType(PointeeTy, Unit);
+
   if (const RecordType *RTy =3D dyn_cast<RecordType>(PointeeTy)) {
     RecordDecl *RD =3D RTy->getDecl();
-    llvm::DIFile DefUnit =3D getOrCreateFile(RD->getLocation());
-    unsigned Line =3D getLineNumber(RD->getLocation());
     llvm::DIDescriptor FDContext =3D
       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
-
-    if (RD->isStruct())
-      return DBuilder.createStructType(FDContext, RD->getName(), DefUnit,
-                                       Line, 0, 0, llvm::DIType::FlagFwdDe=
cl,
-                                       llvm::DIArray());
-    else if (RD->isUnion())
-      return DBuilder.createUnionType(FDContext, RD->getName(), DefUnit,
-                                      Line, 0, 0, llvm::DIType::FlagFwdDec=
l,
-                                      llvm::DIArray());
-    else {
-      assert(RD->isClass() && "Unknown RecordType!");
-      return DBuilder.createClassType(FDContext, RD->getName(), DefUnit,
-                                      Line, 0, 0, 0, llvm::DIType::FlagFwd=
Decl,
-                                      llvm::DIType(), llvm::DIArray());
-    }
+    llvm::DIType RetTy =3D createRecordFwdDecl(RD, FDContext);
+    TypeCache[QualType(RTy, 0).getAsOpaquePtr()] =3D RetTy;
+    return RetTy;
   }
   return getOrCreateType(PointeeTy, Unit);
=20
@@ -516,7 +577,6 @@
                                                 const Type *Ty,=20
                                                 QualType PointeeTy,
                                                 llvm::DIFile Unit) {
-
   if (Tag =3D=3D llvm::dwarf::DW_TAG_reference_type)
     return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit)=
);
                                    =20
@@ -527,8 +587,8 @@
   uint64_t Size =3D CGM.getContext().getTargetInfo().getPointerWidth(AS);
   uint64_t Align =3D CGM.getContext().getTypeAlign(Ty);
=20
-  return=20
-    DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), Size, A=
lign);
+  return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
+                                    Size, Align);
 }
=20
 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
@@ -594,8 +654,7 @@
   return BlockLiteralGeneric;
 }
=20
-llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
-                                     llvm::DIFile Unit) {
+llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile U=
nit) {
   // Typedefs are derived from some other type.  If we have a typedef of a
   // typedef, make sure to emit the whole chain.
   llvm::DIType Src =3D getOrCreateType(Ty->getDecl()->getUnderlyingType(),=
 Unit);
@@ -605,11 +664,12 @@
   // declared.
   unsigned Line =3D getLineNumber(Ty->getDecl()->getLocation());
   const TypedefNameDecl *TyDecl =3D Ty->getDecl();
-  llvm::DIDescriptor TydefContext =3D
+ =20
+  llvm::DIDescriptor TypedefContext =3D
     getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
-
-  return =20
-    DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TydefContex=
t);
+ =20
+  return
+    DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefCont=
ext);
 }
=20
 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
@@ -634,6 +694,34 @@
   return DbgTy;
 }
=20
+
+void CGDebugInfo::
+CollectRecordStaticVars(const RecordDecl *RD, llvm::DIType FwdDecl) {
+ =20
+  for (RecordDecl::decl_iterator I =3D RD->decls_begin(), E =3D RD->decls_=
end();
+       I !=3D E; ++I)
+    if (const VarDecl *V =3D dyn_cast<VarDecl>(*I)) {
+      if (V->getInit()) {
+        const APValue *Value =3D V->evaluateValue();
+        if (Value && Value->isInt()) {
+          llvm::ConstantInt *CI
+            =3D llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt=
());
+         =20
+          // Create the descriptor for static variable.
+          llvm::DIFile VUnit =3D getOrCreateFile(V->getLocation());
+          StringRef VName =3D V->getName();
+          llvm::DIType VTy =3D getOrCreateType(V->getType(), VUnit);
+          // Do not use DIGlobalVariable for enums.
+          if (VTy.getTag() !=3D llvm::dwarf::DW_TAG_enumeration_type) {
+            DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
+                                          getLineNumber(V->getLocation()),
+                                          VTy, true, CI);
+          }
+        }
+      }
+    }
+}
+
 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
                                           QualType type,
                                           uint64_t sizeInBitsOverride,
@@ -674,44 +762,75 @@
                     SmallVectorImpl<llvm::Value *> &elements,
                     llvm::DIType RecordTy) {
   unsigned fieldNo =3D 0;
-  const FieldDecl *LastFD =3D 0;
-  bool IsMsStruct =3D record->hasAttr<MsStructAttr>();
- =20
   const ASTRecordLayout &layout =3D CGM.getContext().getASTRecordLayout(re=
cord);
-  for (RecordDecl::field_iterator I =3D record->field_begin(),
-                                  E =3D record->field_end();
-       I !=3D E; ++I, ++fieldNo) {
-    FieldDecl *field =3D *I;
-    if (IsMsStruct) {
-      // Zero-length bitfields following non-bitfield members are ignored
-      if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)=
) {
-        --fieldNo;
+  const CXXRecordDecl *CXXDecl =3D dyn_cast<CXXRecordDecl>(record);
+
+  // For C++11 Lambdas a Fields will be the same as a Capture, but the Cap=
ture
+  // has the name and the location of the variable so we should iterate ov=
er
+  // both concurrently.
+  if (CXXDecl && CXXDecl->isLambda()) {
+    RecordDecl::field_iterator Field =3D CXXDecl->field_begin();
+    unsigned fieldno =3D 0;
+    for (CXXRecordDecl::capture_const_iterator I =3D CXXDecl->captures_beg=
in(),
+           E =3D CXXDecl->captures_end(); I !=3D E; ++I, ++Field, ++fieldn=
o) {
+      const LambdaExpr::Capture C =3D *I;
+      // TODO: Need to handle 'this' in some way by probably renaming the
+      // this of the lambda class and having a field member of 'this'.
+      if (C.capturesVariable()) {
+        VarDecl *V =3D C.getCapturedVar();
+        llvm::DIFile VUnit =3D getOrCreateFile(C.getLocation());
+        StringRef VName =3D V->getName();
+        uint64_t SizeInBitsOverride =3D 0;
+        if (Field->isBitField()) {
+          SizeInBitsOverride =3D Field->getBitWidthValue(CGM.getContext());
+          assert(SizeInBitsOverride && "found named 0-width bitfield");
+        }
+        llvm::DIType fieldType
+          =3D createFieldType(VName, Field->getType(), SizeInBitsOverride,=
 C.getLocation(),
+                            Field->getAccess(), layout.getFieldOffset(fiel=
dno),
+                            VUnit, RecordTy);
+        elements.push_back(fieldType);
+      }
+    }
+  } else {
+    bool IsMsStruct =3D record->hasAttr<MsStructAttr>();
+    const FieldDecl *LastFD =3D 0;
+    for (RecordDecl::field_iterator I =3D record->field_begin(),
+           E =3D record->field_end();
+         I !=3D E; ++I, ++fieldNo) {
+      FieldDecl *field =3D *I;
+
+      if (IsMsStruct) {
+        // Zero-length bitfields following non-bitfield members are ignored
+        if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastF=
D)) {
+          --fieldNo;
+          continue;
+        }
+        LastFD =3D field;
+      }
+
+      StringRef name =3D field->getName();
+      QualType type =3D field->getType();
+
+      // Ignore unnamed fields unless they're anonymous structs/unions.
+      if (name.empty() && !type->isRecordType()) {
+        LastFD =3D field;
         continue;
       }
-      LastFD =3D field;
+
+      uint64_t SizeInBitsOverride =3D 0;
+      if (field->isBitField()) {
+        SizeInBitsOverride =3D field->getBitWidthValue(CGM.getContext());
+        assert(SizeInBitsOverride && "found named 0-width bitfield");
+      }
+
+      llvm::DIType fieldType
+        =3D createFieldType(name, type, SizeInBitsOverride,
+                          field->getLocation(), field->getAccess(),
+                          layout.getFieldOffset(fieldNo), tunit, RecordTy);
+
+      elements.push_back(fieldType);
     }
-
-    StringRef name =3D field->getName();
-    QualType type =3D field->getType();
-
-    // Ignore unnamed fields unless they're anonymous structs/unions.
-    if (name.empty() && !type->isRecordType()) {
-      LastFD =3D field;
-      continue;
-    }
-
-    uint64_t SizeInBitsOverride =3D 0;
-    if (field->isBitField()) {
-      SizeInBitsOverride =3D field->getBitWidthValue(CGM.getContext());
-      assert(SizeInBitsOverride && "found named 0-width bitfield");
-    }
-
-    llvm::DIType fieldType
-      =3D createFieldType(name, type, SizeInBitsOverride,
-                        field->getLocation(), field->getAccess(),
-                        layout.getFieldOffset(fieldNo), tunit, RecordTy);
-
-    elements.push_back(fieldType);
   }
 }
=20
@@ -725,7 +844,7 @@
     =3D getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoTyp=
e>(),
                                0),
                       Unit);
- =20
+
   // Add "this" pointer.
   llvm::DIArray Args =3D llvm::DICompositeType(FnTy).getTypeArray();
   assert (Args.getNumElements() && "Invalid number of arguments!");
@@ -738,11 +857,29 @@
   if (!Method->isStatic()) {
     // "this" pointer is always first argument.
     QualType ThisPtr =3D Method->getThisType(CGM.getContext());
-    llvm::DIType ThisPtrType =3D
-      DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit));
-   =20
-    TypeCache[ThisPtr.getAsOpaquePtr()] =3D ThisPtrType;
-    Elts.push_back(ThisPtrType);
+
+    const CXXRecordDecl *RD =3D Method->getParent();
+    if (isa<ClassTemplateSpecializationDecl>(RD)) {
+      // Create pointer type directly in this case.
+      const PointerType *ThisPtrTy =3D cast<PointerType>(ThisPtr);
+      QualType PointeeTy =3D ThisPtrTy->getPointeeType();
+      unsigned AS =3D CGM.getContext().getTargetAddressSpace(PointeeTy);
+      uint64_t Size =3D CGM.getContext().getTargetInfo().getPointerWidth(A=
S);
+      uint64_t Align =3D CGM.getContext().getTypeAlign(ThisPtrTy);
+      llvm::DIType PointeeType =3D getOrCreateType(PointeeTy, Unit);
+      llvm::DIType ThisPtrType =3D DBuilder.createPointerType(PointeeType,=
 Size, Align);
+      TypeCache[ThisPtr.getAsOpaquePtr()] =3D ThisPtrType;
+      // TODO: This and the artificial type below are misleading, the
+      // types aren't artificial the argument is, but the current
+      // metadata doesn't represent that.
+      ThisPtrType =3D DBuilder.createArtificialType(ThisPtrType);
+      Elts.push_back(ThisPtrType);
+    } else {
+      llvm::DIType ThisPtrType =3D getOrCreateType(ThisPtr, Unit);
+      TypeCache[ThisPtr.getAsOpaquePtr()] =3D ThisPtrType;
+      ThisPtrType =3D DBuilder.createArtificialType(ThisPtrType);
+      Elts.push_back(ThisPtrType);
+    }
   }
=20
   // Copy rest of the arguments.
@@ -757,14 +894,13 @@
 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined=20
 /// inside a function.
 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
-  if (const CXXRecordDecl *NRD =3D=20
-      dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
+  if (const CXXRecordDecl *NRD =3D dyn_cast<CXXRecordDecl>(RD->getDeclCont=
ext()))
     return isFunctionLocalClass(NRD);
-  else if (isa<FunctionDecl>(RD->getDeclContext()))
+  if (isa<FunctionDecl>(RD->getDeclContext()))
     return true;
   return false;
- =20
 }
+
 /// CreateCXXMemberFunction - A helper function to create a DISubprogram f=
or
 /// a single member function GlobalDecl.
 llvm::DISubprogram
@@ -823,35 +959,48 @@
   }
   if (Method->hasPrototype())
     Flags |=3D llvm::DIDescriptor::FlagPrototyped;
-   =20
+
+  llvm::DIArray TParamsArray =3D CollectFunctionTemplateParams(Method, Uni=
t);
   llvm::DISubprogram SP =3D
     DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,=20
                           MethodDefUnit, MethodLine,
                           MethodTy, /*isLocalToUnit=3D*/false,=20
                           /* isDefinition=3D*/ false,
                           Virtuality, VIndex, ContainingType,
-                          Flags, CGM.getLangOptions().Optimize);
+                          Flags, CGM.getLangOpts().Optimize, NULL,
+                          TParamsArray);
  =20
-  SPCache[Method] =3D llvm::WeakVH(SP);
+  SPCache[Method->getCanonicalDecl()] =3D llvm::WeakVH(SP);
=20
   return SP;
 }
=20
 /// CollectCXXMemberFunctions - A helper function to collect debug info for
-/// C++ member functions.This is used while creating debug info entry for=20
+/// C++ member functions. This is used while creating debug info entry for=20
 /// a Record.
 void CGDebugInfo::
 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
                           SmallVectorImpl<llvm::Value *> &EltTys,
                           llvm::DIType RecordTy) {
-  for(CXXRecordDecl::method_iterator I =3D RD->method_begin(),
-        E =3D RD->method_end(); I !=3D E; ++I) {
-    const CXXMethodDecl *Method =3D *I;
-   =20
-    if (Method->isImplicit() && !Method->isUsed())
+
+  // Since we want more than just the individual member decls if we
+  // have templated functions iterate over every declaration to gather
+  // the functions.
+  for(DeclContext::decl_iterator I =3D RD->decls_begin(),
+        E =3D RD->decls_end(); I !=3D E; ++I) {
+    Decl *D =3D *I;
+    if (D->isImplicit() && !D->isUsed())
       continue;
=20
-    EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
+    if (const CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(D))
+      EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
+    else if (FunctionTemplateDecl *FTD =3D dyn_cast<FunctionTemplateDecl>(=
D))
+      for (FunctionTemplateDecl::spec_iterator SI =3D FTD->spec_begin(),
+            SE =3D FTD->spec_end(); SI !=3D SE; ++SI) {
+        FunctionDecl *FD =3D *SI;
+        if (CXXMethodDecl *M =3D dyn_cast<CXXMethodDecl>(FD))
+          EltTys.push_back(CreateCXXMemberFunction(M, Unit, RecordTy));
+      }
   }
 }                                =20
=20
@@ -862,7 +1011,7 @@
 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
                 SmallVectorImpl<llvm::Value *> &EltTys,
                 llvm::DIType RecordTy) {
-  for (CXXRecordDecl::friend_iterator BI =3D  RD->friend_begin(),
+  for (CXXRecordDecl::friend_iterator BI =3D RD->friend_begin(),
          BE =3D RD->friend_end(); BI !=3D BE; ++BI) {
     if ((*BI)->isUnsupportedFriend())
       continue;
@@ -992,7 +1141,7 @@
=20
 /// getVTableName - Get vtable name for the given Class.
 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
-  // Otherwise construct gdb compatible name name.
+  // Construct gdb compatible name name.
   std::string Name =3D "_vptr$" + RD->getNameAsString();
=20
   // Copy this name on the side and use its reference.
@@ -1028,7 +1177,15 @@
 /// getOrCreateRecordType - Emit record type's standalone debug info.=20
 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,=20
                                                 SourceLocation Loc) {
-  llvm::DIType T =3D  getOrCreateType(RTy, getOrCreateFile(Loc));
+  llvm::DIType T =3D getOrCreateType(RTy, getOrCreateFile(Loc));
+  return T;
+}
+
+/// getOrCreateInterfaceType - Emit an objective c interface type standalo=
ne
+/// debug info.
+llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
+						   SourceLocation Loc) {
+  llvm::DIType T =3D getOrCreateType(D, getOrCreateFile(Loc));
   DBuilder.retainType(T);
   return T;
 }
@@ -1036,11 +1193,9 @@
 /// CreateType - get structure or union type.
 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
   RecordDecl *RD =3D Ty->getDecl();
-  llvm::DIFile Unit =3D getOrCreateFile(RD->getLocation());
=20
   // Get overall information about the record type for the debug info.
   llvm::DIFile DefUnit =3D getOrCreateFile(RD->getLocation());
-  unsigned Line =3D getLineNumber(RD->getLocation());
=20
   // Records and classes and unions can all be recursive.  To handle them,=
 we
   // first generate a debug descriptor for the struct as a forward declara=
tion.
@@ -1048,126 +1203,63 @@
   // its members.  Finally, we create a descriptor for the complete type (=
which
   // may refer to the forward decl if the struct is recursive) and replace=
 all
   // uses of the forward declaration with the final definition.
-  llvm::DIDescriptor FDContext =3D
-    getContextDescriptor(cast<Decl>(RD->getDeclContext()));
=20
-  // If this is just a forward declaration, construct an appropriately
-  // marked node and just return it.
-  if (!RD->getDefinition()) {
-    llvm::DIType FwdDecl =3D
-      DBuilder.createStructType(FDContext, RD->getName(),
-                                DefUnit, Line, 0, 0,
-                                llvm::DIDescriptor::FlagFwdDecl,
-                                llvm::DIArray());
+  llvm::DIType FwdDecl =3D getOrCreateLimitedType(QualType(Ty, 0), DefUnit=
);
=20
-      return FwdDecl;
-  }
+  if (FwdDecl.isForwardDecl())
+    return FwdDecl;
=20
-  llvm::DIType FwdDecl =3D DBuilder.createTemporaryType(DefUnit);
+  llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
=20
-  llvm::MDNode *MN =3D FwdDecl;
-  llvm::TrackingVH<llvm::MDNode> FwdDeclNode =3D MN;
-  // Otherwise, insert it into the TypeCache so that recursive uses will f=
ind
-  // it.
-  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] =3D FwdDecl;
   // Push the struct on region stack.
   LexicalBlockStack.push_back(FwdDeclNode);
   RegionMap[Ty->getDecl()] =3D llvm::WeakVH(FwdDecl);
=20
+  // Add this to the completed types cache since we're completing it.
+  CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] =3D FwdDecl;
+
   // Convert all the elements.
   SmallVector<llvm::Value *, 16> EltTys;
=20
+  // Note: The split of CXXDecl information here is intentional, the
+  // gdb tests will depend on a certain ordering at printout. The debug
+  // information offsets are still correct if we merge them all together
+  // though.
   const CXXRecordDecl *CXXDecl =3D dyn_cast<CXXRecordDecl>(RD);
   if (CXXDecl) {
-    CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
-    CollectVTableInfo(CXXDecl, Unit, EltTys);
+    CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
+    CollectVTableInfo(CXXDecl, DefUnit, EltTys);
   }
- =20
-  // Collect static variables with initializers.
-  for (RecordDecl::decl_iterator I =3D RD->decls_begin(), E =3D RD->decls_=
end();
-       I !=3D E; ++I)
-    if (const VarDecl *V =3D dyn_cast<VarDecl>(*I)) {
-      if (const Expr *Init =3D V->getInit()) {
-        Expr::EvalResult Result;
-        if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()=
) {
-          llvm::ConstantInt *CI=20
-            =3D llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.ge=
tInt());
-         =20
-          // Create the descriptor for static variable.
-          llvm::DIFile VUnit =3D getOrCreateFile(V->getLocation());
-          StringRef VName =3D V->getName();
-          llvm::DIType VTy =3D getOrCreateType(V->getType(), VUnit);
-          // Do not use DIGlobalVariable for enums.
-          if (VTy.getTag() !=3D llvm::dwarf::DW_TAG_enumeration_type) {
-            DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
-                                          getLineNumber(V->getLocation()),
-                                          VTy, true, CI);
-          }
-        }
-      }
-    }
=20
-  CollectRecordFields(RD, Unit, EltTys, FwdDecl);
+  // Collect static variables with initializers and other fields.
+  CollectRecordStaticVars(RD, FwdDecl);
+  CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
   llvm::DIArray TParamsArray;
   if (CXXDecl) {
-    CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
-    CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
+    CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
+    CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
     if (const ClassTemplateSpecializationDecl *TSpecial
         =3D dyn_cast<ClassTemplateSpecializationDecl>(RD))
-      TParamsArray =3D CollectCXXTemplateParams(TSpecial, Unit);
+      TParamsArray =3D CollectCXXTemplateParams(TSpecial, DefUnit);
   }
=20
   LexicalBlockStack.pop_back();
-  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =3D=20
-    RegionMap.find(Ty->getDecl());
-  if (RI !=3D RegionMap.end())
-    RegionMap.erase(RI);
+  RegionMap.erase(Ty->getDecl());
=20
-  llvm::DIDescriptor RDContext =3D =20
-    getContextDescriptor(cast<Decl>(RD->getDeclContext()));
-  StringRef RDName =3D RD->getName();
-  uint64_t Size =3D CGM.getContext().getTypeSize(Ty);
-  uint64_t Align =3D CGM.getContext().getTypeAlign(Ty);
   llvm::DIArray Elements =3D DBuilder.getOrCreateArray(EltTys);
-  llvm::MDNode *RealDecl =3D NULL;
+  // FIXME: Magic numbers ahoy! These should be changed when we
+  // get some enums in llvm/Analysis/DebugInfo.h to refer to
+  // them.
+  if (RD->isUnion())
+    FwdDeclNode->replaceOperandWith(10, Elements);
+  else if (CXXDecl) {
+    FwdDeclNode->replaceOperandWith(10, Elements);
+    FwdDeclNode->replaceOperandWith(13, TParamsArray);
+  } else
+    FwdDeclNode->replaceOperandWith(10, Elements);
=20
-  if (RD->isUnion())
-    RealDecl =3D DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
-                                        Size, Align, 0, Elements);
-  else if (CXXDecl) {
-    RDName =3D getClassName(RD);
-     // A class's primary base or the class itself contains the vtable.
-    llvm::MDNode *ContainingType =3D NULL;
-    const ASTRecordLayout &RL =3D CGM.getContext().getASTRecordLayout(RD);
-    if (const CXXRecordDecl *PBase =3D RL.getPrimaryBase()) {
-      // Seek non virtual primary base root.
-      while (1) {
-        const ASTRecordLayout &BRL =3D CGM.getContext().getASTRecordLayout=
(PBase);
-        const CXXRecordDecl *PBT =3D BRL.getPrimaryBase();
-        if (PBT && !BRL.isPrimaryBaseVirtual())
-          PBase =3D PBT;
-        else=20
-          break;
-      }
-      ContainingType =3D=20
-        getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
-    }
-    else if (CXXDecl->isDynamicClass())=20
-      ContainingType =3D FwdDecl;
-
-   RealDecl =3D DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
-                                       Size, Align, 0, 0, llvm::DIType(),
-                                       Elements, ContainingType,
-                                       TParamsArray);
-  } else=20
-    RealDecl =3D DBuilder.createStructType(RDContext, RDName, DefUnit, Lin=
e,
-                                         Size, Align, 0, Elements);
-
-  // Now that we have a real decl for the struct, replace anything using t=
he
-  // old decl with the new one.  This will recursively update the debug in=
fo.
-  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
-  RegionMap[RD] =3D llvm::WeakVH(RealDecl);
-  return llvm::DIType(RealDecl);
+  RegionMap[Ty->getDecl()] =3D llvm::WeakVH(FwdDeclNode);
+  return llvm::DIType(FwdDeclNode);
 }
=20
 /// CreateType - get objective-c object type.
@@ -1191,30 +1283,38 @@
=20
   // If this is just a forward declaration return a special forward-declar=
ation
   // debug type since we won't be able to lay out the entire type.
-  if (ID->isForwardDecl()) {
+  ObjCInterfaceDecl *Def =3D ID->getDefinition();
+  if (!Def) {
     llvm::DIType FwdDecl =3D
-      DBuilder.createStructType(Unit, ID->getName(),
-                                DefUnit, Line, 0, 0, 0,
-                                llvm::DIArray(), RuntimeLang);
+      DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
+				 ID->getName(), DefUnit, Line,
+				 RuntimeLang);
     return FwdDecl;
   }
=20
-  // To handle a recursive interface, we first generate a debug descriptor
-  // for the struct as a forward declaration. Then (if it is a definition)
-  // we go through and get debug info for all of its members.  Finally, we
-  // create a descriptor for the complete type (which may refer to the
-  // forward decl if the struct is recursive) and replace all uses of the
-  // forward declaration with the final definition.
-  llvm::DIType FwdDecl =3D DBuilder.createTemporaryType(DefUnit);
+  ID =3D Def;
=20
-  llvm::MDNode *MN =3D FwdDecl;
-  llvm::TrackingVH<llvm::MDNode> FwdDeclNode =3D MN;
-  // Otherwise, insert it into the TypeCache so that recursive uses will f=
ind
-  // it.
-  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] =3D FwdDecl;
+  // Bit size, align and offset of the type.
+  uint64_t Size =3D CGM.getContext().getTypeSize(Ty);
+  uint64_t Align =3D CGM.getContext().getTypeAlign(Ty);
+
+  unsigned Flags =3D 0;
+  if (ID->getImplementation())
+    Flags |=3D llvm::DIDescriptor::FlagObjcClassComplete;
+
+  llvm::DIType RealDecl =3D
+    DBuilder.createStructType(Unit, ID->getName(), DefUnit,
+                              Line, Size, Align, Flags,
+                              llvm::DIArray(), RuntimeLang);
+
+  // Otherwise, insert it into the CompletedTypeCache so that recursive us=
es
+  // will find it and we're emitting the complete type.
+  CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] =3D RealDecl;
   // Push the struct on region stack.
+  llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
+
   LexicalBlockStack.push_back(FwdDeclNode);
-  RegionMap[Ty->getDecl()] =3D llvm::WeakVH(FwdDecl);
+  RegionMap[Ty->getDecl()] =3D llvm::WeakVH(RealDecl);
=20
   // Convert all the elements.
   SmallVector<llvm::Value *, 16> EltTys;
@@ -1227,12 +1327,31 @@
       return llvm::DIType();
    =20
     llvm::DIType InhTag =3D
-      DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0);
+      DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
     EltTys.push_back(InhTag);
   }
=20
+  for (ObjCContainerDecl::prop_iterator I =3D ID->prop_begin(),
+         E =3D ID->prop_end(); I !=3D E; ++I) {
+    const ObjCPropertyDecl *PD =3D *I;
+    SourceLocation Loc =3D PD->getLocation();
+    llvm::DIFile PUnit =3D getOrCreateFile(Loc);
+    unsigned PLine =3D getLineNumber(Loc);
+    ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl();
+    ObjCMethodDecl *Setter =3D PD->getSetterMethodDecl();
+    llvm::MDNode *PropertyNode =3D
+      DBuilder.createObjCProperty(PD->getName(),
+				  PUnit, PLine,
+                                  (Getter && Getter->isImplicit()) ? "" :
+                                  getSelectorName(PD->getGetterName()),
+                                  (Setter && Setter->isImplicit()) ? "" :
+                                  getSelectorName(PD->getSetterName()),
+                                  PD->getPropertyAttributes(),
+				  getOrCreateType(PD->getType(), PUnit));
+    EltTys.push_back(PropertyNode);
+  }
+
   const ASTRecordLayout &RL =3D CGM.getContext().getASTObjCInterfaceLayout=
(ID);
-  ObjCImplementationDecl *ImpD =3D ID->getImplementation();
   unsigned FieldNo =3D 0;
   for (ObjCIvarDecl *Field =3D ID->all_declared_ivar_begin(); Field;
        Field =3D Field->getNextIvar(), ++FieldNo) {
@@ -1266,7 +1385,7 @@
     // the non-fragile abi and the debugger should ignore the value anyway=
s.
     // Call it the FieldNo+1 due to how debuggers use the information,
     // e.g. negating the value when it needs a lookup in the dynamic table.
-    uint64_t FieldOffset =3D CGM.getLangOptions().ObjCNonFragileABI ? Fiel=
dNo+1
+    uint64_t FieldOffset =3D CGM.getLangOpts().ObjCNonFragileABI ? FieldNo=
+1
       : RL.getFieldOffset(FieldNo);
=20
     unsigned Flags =3D 0;
@@ -1275,69 +1394,43 @@
     else if (Field->getAccessControl() =3D=3D ObjCIvarDecl::Private)
       Flags =3D llvm::DIDescriptor::FlagPrivate;
=20
-    StringRef PropertyName;
-    StringRef PropertyGetter;
-    StringRef PropertySetter;
-    unsigned PropertyAttributes =3D 0;
-    ObjCPropertyDecl *PD =3D NULL;
-    if (ImpD)
+    llvm::MDNode *PropertyNode =3D NULL;
+    if (ObjCImplementationDecl *ImpD =3D ID->getImplementation()) {
       if (ObjCPropertyImplDecl *PImpD =3D=20
-          ImpD->FindPropertyImplIvarDecl(Field->getIdentifier()))
-        PD =3D PImpD->getPropertyDecl();
-    if (PD) {
-      PropertyName =3D PD->getName();
-      PropertyGetter =3D getSelectorName(PD->getGetterName());
-      PropertySetter =3D getSelectorName(PD->getSetterName());
-      PropertyAttributes =3D PD->getPropertyAttributes();
-    }=20
+          ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
+        if (ObjCPropertyDecl *PD =3D PImpD->getPropertyDecl()) {
+	  SourceLocation Loc =3D PD->getLocation();
+	  llvm::DIFile PUnit =3D getOrCreateFile(Loc);
+	  unsigned PLine =3D getLineNumber(Loc);
+          ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl();
+          ObjCMethodDecl *Setter =3D PD->getSetterMethodDecl();
+          PropertyNode =3D
+            DBuilder.createObjCProperty(PD->getName(),
+                                        PUnit, PLine,
+                                        (Getter && Getter->isImplicit()) ?=
 "" :
+                                        getSelectorName(PD->getGetterName(=
)),
+                                        (Setter && Setter->isImplicit()) ?=
 "" :
+                                        getSelectorName(PD->getSetterName(=
)),
+                                        PD->getPropertyAttributes(),
+                                        getOrCreateType(PD->getType(), PUn=
it));
+        }
+      }
+    }
     FieldTy =3D DBuilder.createObjCIVar(FieldName, FieldDefUnit,
                                       FieldLine, FieldSize, FieldAlign,
                                       FieldOffset, Flags, FieldTy,
-                                      PropertyName, PropertyGetter,
-                                      PropertySetter, PropertyAttributes);
+                                      PropertyNode);
     EltTys.push_back(FieldTy);
   }
=20
   llvm::DIArray Elements =3D DBuilder.getOrCreateArray(EltTys);
-
+  FwdDeclNode->replaceOperandWith(10, Elements);
+ =20
   LexicalBlockStack.pop_back();
-  llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =3D=20
-    RegionMap.find(Ty->getDecl());
-  if (RI !=3D RegionMap.end())
-    RegionMap.erase(RI);
-
-  // Bit size, align and offset of the type.
-  uint64_t Size =3D CGM.getContext().getTypeSize(Ty);
-  uint64_t Align =3D CGM.getContext().getTypeAlign(Ty);
-
-  unsigned Flags =3D 0;
-  if (ID->getImplementation())
-    Flags |=3D llvm::DIDescriptor::FlagObjcClassComplete;
-
-  llvm::DIType RealDecl =3D
-    DBuilder.createStructType(Unit, ID->getName(), DefUnit,
-                                  Line, Size, Align, Flags,
-                                  Elements, RuntimeLang);
-
-  // Now that we have a real decl for the struct, replace anything using t=
he
-  // old decl with the new one.  This will recursively update the debug in=
fo.
-  llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
-  RegionMap[ID] =3D llvm::WeakVH(RealDecl);
-
-  return RealDecl;
+  return llvm::DIType(FwdDeclNode);
 }
=20
-llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
-  if (const RecordType *RT =3D dyn_cast<RecordType>(Ty))
-    return CreateType(RT);
-  else if (const EnumType *ET =3D dyn_cast<EnumType>(Ty))
-    return CreateEnumType(ET->getDecl());
-
-  return llvm::DIType();
-}
-
-llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
-                                     llvm::DIFile Unit) {
+llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Un=
it) {
   llvm::DIType ElementTy =3D getOrCreateType(Ty->getElementType(), Unit);
   int64_t NumElems =3D Ty->getNumElements();
   int64_t LowerBound =3D 0;
@@ -1545,20 +1638,14 @@
     if (T =3D=3D LastT)
       return T;
   } while (true);
- =20
-  return T;
 }
=20
-/// getOrCreateType - Get the type from the cache or create a new
-/// one if necessary.
-llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
-                                          llvm::DIFile Unit) {
-  if (Ty.isNull())
-    return llvm::DIType();
+/// getType - Get the type from the cache or return null type if it doesn'=
t exist.
+llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
=20
   // Unwrap the type as needed for debug information.
   Ty =3D UnwrapTypeForDebugInfo(Ty);
-
+ =20
   // Check for existing entry.
   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =3D
     TypeCache.find(Ty.getAsOpaquePtr());
@@ -1568,17 +1655,59 @@
       return llvm::DIType(cast<llvm::MDNode>(it->second));
   }
=20
+  return llvm::DIType();
+}
+
+/// getCompletedTypeOrNull - Get the type from the cache or return null if=
 it
+/// doesn't exist.
+llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
+
+  // Unwrap the type as needed for debug information.
+  Ty =3D UnwrapTypeForDebugInfo(Ty);
+
+  // Check for existing entry.
+  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =3D
+    CompletedTypeCache.find(Ty.getAsOpaquePtr());
+  if (it !=3D CompletedTypeCache.end()) {
+    // Verify that the debug info still exists.
+    if (&*it->second)
+      return llvm::DIType(cast<llvm::MDNode>(it->second));
+  }
+
+  return llvm::DIType();
+}
+
+
+/// getOrCreateType - Get the type from the cache or create a new
+/// one if necessary.
+llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
+  if (Ty.isNull())
+    return llvm::DIType();
+
+  // Unwrap the type as needed for debug information.
+  Ty =3D UnwrapTypeForDebugInfo(Ty);
+ =20
+  llvm::DIType T =3D getCompletedTypeOrNull(Ty);
+
+  if (T.Verify()) return T;
+
   // Otherwise create the type.
   llvm::DIType Res =3D CreateTypeNode(Ty, Unit);
=20
+  llvm::DIType TC =3D getTypeOrNull(Ty);
+  if (TC.Verify() && TC.isForwardDecl())
+    ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), TC));
+ =20
   // And update the type cache.
-  TypeCache[Ty.getAsOpaquePtr()] =3D Res; =20
+  TypeCache[Ty.getAsOpaquePtr()] =3D Res;
+
+  if (!Res.isForwardDecl())
+    CompletedTypeCache[Ty.getAsOpaquePtr()] =3D Res;
   return Res;
 }
=20
 /// CreateTypeNode - Create a new debug type node.
-llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
-                                         llvm::DIFile Unit) {
+llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
   // Handle qualifiers, which recursively handles what they refer to.
   if (Ty.hasLocalQualifiers())
     return CreateQualifiedType(Ty, Unit);
@@ -1603,15 +1732,20 @@
     return CreateType(cast<ObjCObjectType>(Ty), Unit);
   case Type::ObjCInterface:
     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
-  case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
-  case Type::Complex: return CreateType(cast<ComplexType>(Ty));
-  case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
+  case Type::Builtin:
+    return CreateType(cast<BuiltinType>(Ty));
+  case Type::Complex:
+    return CreateType(cast<ComplexType>(Ty));
+  case Type::Pointer:
+    return CreateType(cast<PointerType>(Ty), Unit);
   case Type::BlockPointer:
     return CreateType(cast<BlockPointerType>(Ty), Unit);
-  case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
+  case Type::Typedef:
+    return CreateType(cast<TypedefType>(Ty), Unit);
   case Type::Record:
+    return CreateType(cast<RecordType>(Ty));
   case Type::Enum:
-    return CreateType(cast<TagType>(Ty));
+    return CreateEnumType(cast<EnumType>(Ty)->getDecl());
   case Type::FunctionProto:
   case Type::FunctionNoProto:
     return CreateType(cast<FunctionType>(Ty), Unit);
@@ -1642,7 +1776,6 @@
   case Type::UnaryTransform:
   case Type::Auto:
     llvm_unreachable("type should have been unwrapped!");
-    return llvm::DIType();     =20
   }
  =20
   assert(Diag && "Fall through without a diagnostic?");
@@ -1653,6 +1786,123 @@
   return llvm::DIType();
 }
=20
+/// getOrCreateLimitedType - Get the type from the cache or create a new
+/// limited type if necessary.
+llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
+						 llvm::DIFile Unit) {
+  if (Ty.isNull())
+    return llvm::DIType();
+
+  // Unwrap the type as needed for debug information.
+  Ty =3D UnwrapTypeForDebugInfo(Ty);
+
+  llvm::DIType T =3D getTypeOrNull(Ty);
+
+  // We may have cached a forward decl when we could have created
+  // a non-forward decl. Go ahead and create a non-forward decl
+  // now.
+  if (T.Verify() && !T.isForwardDecl()) return T;
+
+  // Otherwise create the type.
+  llvm::DIType Res =3D CreateLimitedTypeNode(Ty, Unit);
+
+  if (T.Verify() && T.isForwardDecl())
+    ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), T));
+
+  // And update the type cache.
+  TypeCache[Ty.getAsOpaquePtr()] =3D Res;
+  return Res;
+}
+
+// TODO: Currently used for context chains when limiting debug info.
+llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
+  RecordDecl *RD =3D Ty->getDecl();
+ =20
+  // Get overall information about the record type for the debug info.
+  llvm::DIFile DefUnit =3D getOrCreateFile(RD->getLocation());
+  unsigned Line =3D getLineNumber(RD->getLocation());
+  StringRef RDName =3D RD->getName();
+
+  llvm::DIDescriptor RDContext;
+  if (CGM.getCodeGenOpts().LimitDebugInfo)
+    RDContext =3D createContextChain(cast<Decl>(RD->getDeclContext()));
+  else
+    RDContext =3D getContextDescriptor(cast<Decl>(RD->getDeclContext()));
+
+  // If this is just a forward declaration, construct an appropriately
+  // marked node and just return it.
+  if (!RD->getDefinition())
+    return createRecordFwdDecl(RD, RDContext);
+
+  uint64_t Size =3D CGM.getContext().getTypeSize(Ty);
+  uint64_t Align =3D CGM.getContext().getTypeAlign(Ty);
+  const CXXRecordDecl *CXXDecl =3D dyn_cast<CXXRecordDecl>(RD);
+  llvm::TrackingVH<llvm::MDNode> RealDecl;
+ =20
+  if (RD->isUnion())
+    RealDecl =3D DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
+					Size, Align, 0, llvm::DIArray());
+  else if (CXXDecl) {
+    RDName =3D getClassName(RD);
+   =20
+    // FIXME: This could be a struct type giving a default visibility diff=
erent
+    // than C++ class type, but needs llvm metadata changes first.
+    RealDecl =3D DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
+					Size, Align, 0, 0, llvm::DIType(),
+					llvm::DIArray(), llvm::DIType(),
+					llvm::DIArray());
+  } else
+    RealDecl =3D DBuilder.createStructType(RDContext, RDName, DefUnit, Lin=
e,
+					 Size, Align, 0, llvm::DIArray());
+
+  RegionMap[Ty->getDecl()] =3D llvm::WeakVH(RealDecl);
+  TypeCache[QualType(Ty, 0).getAsOpaquePtr()] =3D llvm::DIType(RealDecl);
+
+  if (CXXDecl) {
+    // A class's primary base or the class itself contains the vtable.
+    llvm::MDNode *ContainingType =3D NULL;
+    const ASTRecordLayout &RL =3D CGM.getContext().getASTRecordLayout(RD);
+    if (const CXXRecordDecl *PBase =3D RL.getPrimaryBase()) {
+      // Seek non virtual primary base root.
+      while (1) {
+	const ASTRecordLayout &BRL =3D CGM.getContext().getASTRecordLayout(PBase);
+	const CXXRecordDecl *PBT =3D BRL.getPrimaryBase();
+	if (PBT && !BRL.isPrimaryBaseVirtual())
+	  PBase =3D PBT;
+	else
+	  break;
+      }
+      ContainingType =3D
+	getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
+    }
+    else if (CXXDecl->isDynamicClass())
+      ContainingType =3D RealDecl;
+
+    RealDecl->replaceOperandWith(12, ContainingType);
+  }
+  return llvm::DIType(RealDecl);
+}
+
+/// CreateLimitedTypeNode - Create a new debug type node, but only forward
+/// declare composite types that haven't been processed yet.
+llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile U=
nit) {
+
+  // Work out details of type.
+  switch (Ty->getTypeClass()) {
+#define TYPE(Class, Base)
+#define ABSTRACT_TYPE(Class, Base)
+#define NON_CANONICAL_TYPE(Class, Base)
+#define DEPENDENT_TYPE(Class, Base) case Type::Class:
+        #include "clang/AST/TypeNodes.def"
+    llvm_unreachable("Dependent types cannot show up in debug information"=
);
+
+  case Type::Record:
+    return CreateLimitedType(cast<RecordType>(Ty));
+  default:
+    return CreateTypeNode(Ty, Unit);
+  }
+}
+
 /// CreateMemberType - Create new member and increase Offset by FType's si=
ze.
 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FTy=
pe,
                                            StringRef Name,
@@ -1677,7 +1927,7 @@
   getContextDescriptor(cast<Decl>(D->getDeclContext()));
=20
   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
-    MI =3D SPCache.find(FD);
+    MI =3D SPCache.find(FD->getCanonicalDecl());
   if (MI !=3D SPCache.end()) {
     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
@@ -1688,7 +1938,7 @@
          E =3D FD->redecls_end(); I !=3D E; ++I) {
     const FunctionDecl *NextFD =3D *I;
     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
-      MI =3D SPCache.find(NextFD);
+      MI =3D SPCache.find(NextFD->getCanonicalDecl());
     if (MI !=3D SPCache.end()) {
       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
@@ -1705,7 +1955,7 @@
                                                   llvm::DIFile F) {
   if (const CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(D))
     return getOrCreateMethodType(Method, F);
-  else if (const ObjCMethodDecl *OMethod =3D dyn_cast<ObjCMethodDecl>(D)) {
+  if (const ObjCMethodDecl *OMethod =3D dyn_cast<ObjCMethodDecl>(D)) {
     // Add "self" and "_cmd"
     SmallVector<llvm::Value *, 16> Elts;
=20
@@ -1726,8 +1976,7 @@
   return getOrCreateType(FnType, F);
 }
=20
-/// EmitFunctionStart - Constructs the debug code for entering a function -
-/// "llvm.dbg.func.start.".
+/// EmitFunctionStart - Constructs the debug code for entering a function.
 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
                                     llvm::Function *Fn,
                                     CGBuilderTy &Builder) {
@@ -1738,15 +1987,17 @@
   FnBeginRegionCount.push_back(LexicalBlockStack.size());
=20
   const Decl *D =3D GD.getDecl();
+  // Use the location of the declaration.
+  SourceLocation Loc =3D D->getLocation();
  =20
   unsigned Flags =3D 0;
-  llvm::DIFile Unit =3D getOrCreateFile(CurLoc);
+  llvm::DIFile Unit =3D getOrCreateFile(Loc);
   llvm::DIDescriptor FDContext(Unit);
   llvm::DIArray TParamsArray;
   if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
-    // If there is a DISubprogram for  this function available then use it.
+    // If there is a DISubprogram for this function available then use it.
     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
-      FI =3D SPCache.find(FD);
+      FI =3D SPCache.find(FD->getCanonicalDecl());
     if (FI !=3D SPCache.end()) {
       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
@@ -1758,12 +2009,13 @@
     }
     Name =3D getFunctionName(FD);
     // Use mangled name as linkage name for c/c++ functions.
-    if (!Fn->hasInternalLinkage())
+    if (FD->hasPrototype()) {
       LinkageName =3D CGM.getMangledName(GD);
+      Flags |=3D llvm::DIDescriptor::FlagPrototyped;
+    }
     if (LinkageName =3D=3D Name)
       LinkageName =3D StringRef();
-    if (FD->hasPrototype())
-      Flags |=3D llvm::DIDescriptor::FlagPrototyped;
+
     if (const NamespaceDecl *NSDecl =3D
         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
       FDContext =3D getOrCreateNameSpace(NSDecl);
@@ -1784,18 +2036,17 @@
   if (!Name.empty() && Name[0] =3D=3D '\01')
     Name =3D Name.substr(1);
=20
-  // It is expected that CurLoc is set before using EmitFunctionStart.
-  // Usually, CurLoc points to the left bracket location of compound
-  // statement representing function body.
-  unsigned LineNo =3D getLineNumber(CurLoc);
+  unsigned LineNo =3D getLineNumber(Loc);
   if (D->isImplicit())
     Flags |=3D llvm::DIDescriptor::FlagArtificial;
+
   llvm::DISubprogram SPDecl =3D getFunctionDeclaration(D);
   llvm::DISubprogram SP =3D
     DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
                             LineNo, getOrCreateFunctionType(D, FnType, Uni=
t),
                             Fn->hasInternalLinkage(), true/*definition*/,
-                            Flags, CGM.getLangOptions().Optimize, Fn,
+                            getLineNumber(CurLoc),
+                            Flags, CGM.getLangOpts().Optimize, Fn,
                             TParamsArray, SPDecl);
=20
   // Push function on region stack.
@@ -1835,11 +2086,11 @@
 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
   llvm::DIDescriptor D =3D
     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
-				llvm::DIDescriptor() :
-				llvm::DIDescriptor(LexicalBlockStack.back()),
-				getOrCreateFile(CurLoc),
-				getLineNumber(CurLoc),
-				getColumnNumber(CurLoc));
+                                llvm::DIDescriptor() :
+                                llvm::DIDescriptor(LexicalBlockStack.back(=
)),
+                                getOrCreateFile(CurLoc),
+                                getLineNumber(CurLoc),
+                                getColumnNumber(CurLoc));
   llvm::MDNode *DN =3D D;
   LexicalBlockStack.push_back(DN);
 }
@@ -1855,8 +2106,8 @@
=20
   // Emit a line table change for the current location inside the new scop=
e.
   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
-  					      getColumnNumber(Loc),
-  					      LexicalBlockStack.back()));
+                                  getColumnNumber(Loc),
+                                  LexicalBlockStack.back()));
 }
=20
 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarat=
ive
@@ -1997,7 +2248,7 @@
     if (VD->hasAttr<BlocksAttr>()) {
       CharUnits offset =3D CharUnits::fromQuantity(32);
       SmallVector<llvm::Value *, 9> addr;
-      llvm::Type *Int64Ty =3D llvm::Type::getInt64Ty(CGM.getLLVMContext());
+      llvm::Type *Int64Ty =3D CGM.Int64Ty;
       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPl=
us));
       // offset of __forwarding field
       offset =3D CGM.getContext().toCharUnitsFromBits(
@@ -2017,7 +2268,6 @@
                                        addr, ArgNo);
      =20
       // Insert an llvm.dbg.declare into the current block.
-      // Insert an llvm.dbg.declare into the current block.
       llvm::Instruction *Call =3D
         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
@@ -2027,7 +2277,7 @@
     llvm::DIVariable D =3D
       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),=20
                                    Name, Unit, Line, Ty,=20
-                                   CGM.getLangOptions().Optimize, Flags, A=
rgNo);
+                                   CGM.getLangOpts().Optimize, Flags, ArgN=
o);
    =20
     // Insert an llvm.dbg.declare into the current block.
     llvm::Instruction *Call =3D
@@ -2056,7 +2306,7 @@
         llvm::DIVariable D =3D
           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
                                        FieldName, Unit, Line, FieldTy,=20
-                                       CGM.getLangOptions().Optimize, Flag=
s,
+                                       CGM.getLangOpts().Optimize, Flags,
                                        ArgNo);
          =20
         // Insert an llvm.dbg.declare into the current block.
@@ -2103,7 +2353,7 @@
           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
=20
   SmallVector<llvm::Value *, 9> addr;
-  llvm::Type *Int64Ty =3D llvm::Type::getInt64Ty(CGM.getLLVMContext());
+  llvm::Type *Int64Ty =3D CGM.Int64Ty;
   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
   if (isByRef) {
@@ -2261,7 +2511,7 @@
     fields.push_back(fieldType);
   }
=20
-  llvm::SmallString<36> typeName;
+  SmallString<36> typeName;
   llvm::raw_svector_ostream(typeName)
     << "__block_literal_" << CGM.getUniqueBlockCount();
=20
@@ -2284,7 +2534,7 @@
     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
                                  llvm::DIDescriptor(scope),=20
                                  name, tunit, line, type,=20
-                                 CGM.getLangOptions().Optimize, flags,
+                                 CGM.getLangOpts().Optimize, flags,
                                  cast<llvm::Argument>(addr)->getArgNo() + =
1);
    =20
   // Insert an llvm.dbg.value into the current block.
@@ -2297,7 +2547,6 @@
 /// EmitGlobalVariable - Emit information about a global variable.
 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
                                      const VarDecl *D) {
- =20
   // Create global variable debug descriptor.
   llvm::DIFile Unit =3D getOrCreateFile(D->getLocation());
   unsigned LineNo =3D getLineNumber(D->getLocation());
@@ -2314,7 +2563,7 @@
     QualType ET =3D CGM.getContext().getAsArrayType(T)->getElementType();
=20
     T =3D CGM.getContext().getConstantArrayType(ET, ConstVal,
-                                           ArrayType::Normal, 0);
+                                              ArrayType::Normal, 0);
   }
   StringRef DeclName =3D D->getName();
   StringRef LinkageName;
@@ -2395,16 +2644,25 @@
   return NS;
 }
=20
-/// UpdateCompletedType - Update type cache because the type is now
-/// translated.
-void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
-  QualType Ty =3D CGM.getContext().getTagDeclType(TD);
-
-  // If the type exist in type cache then remove it from the cache.
-  // There is no need to prepare debug info for the completed type
-  // right now. It will be generated on demand lazily.
-  llvm::DenseMap<void *, llvm::WeakVH>::iterator it =3D
-    TypeCache.find(Ty.getAsOpaquePtr());
-  if (it !=3D TypeCache.end())=20
-    TypeCache.erase(it);
+void CGDebugInfo::finalize(void) {
+  for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
+         =3D ReplaceMap.begin(), VE =3D ReplaceMap.end(); VI !=3D VE; ++VI=
) {
+    llvm::DIType Ty, RepTy;
+    // Verify that the debug info still exists.
+    if (&*VI->second)
+      Ty =3D llvm::DIType(cast<llvm::MDNode>(VI->second));
+   =20
+    llvm::DenseMap<void *, llvm::WeakVH>::iterator it =3D
+      TypeCache.find(VI->first);
+    if (it !=3D TypeCache.end()) {
+      // Verify that the debug info still exists.
+      if (&*it->second)
+        RepTy =3D llvm::DIType(cast<llvm::MDNode>(it->second));
+    }
+   =20
+    if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
+      Ty.replaceAllUsesWith(RepTy);
+    }
+  }
+  DBuilder.finalize();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGDebugInfo.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -53,6 +53,13 @@
   /// TypeCache - Cache of previously constructed Types.
   llvm::DenseMap<void *, llvm::WeakVH> TypeCache;
=20
+  /// CompleteTypeCache - Cache of previously constructed complete RecordT=
ypes.
+  llvm::DenseMap<void *, llvm::WeakVH> CompletedTypeCache;
+
+  /// ReplaceMap - Cache of forward declared types to RAUW at the end of
+  /// compilation.
+  std::vector<std::pair<void *, llvm::WeakVH> >ReplaceMap;
+
   bool BlockLiteralGenericSet;
   llvm::DIType BlockLiteralGeneric;
=20
@@ -83,8 +90,8 @@
   llvm::DIType CreateType(const PointerType *Ty, llvm::DIFile F);
   llvm::DIType CreateType(const BlockPointerType *Ty, llvm::DIFile F);
   llvm::DIType CreateType(const FunctionType *Ty, llvm::DIFile F);
-  llvm::DIType CreateType(const TagType *Ty);
   llvm::DIType CreateType(const RecordType *Ty);
+  llvm::DIType CreateLimitedType(const RecordType *Ty);
   llvm::DIType CreateType(const ObjCInterfaceType *Ty, llvm::DIFile F);
   llvm::DIType CreateType(const ObjCObjectType *Ty, llvm::DIFile F);
   llvm::DIType CreateType(const VectorType *Ty, llvm::DIFile F);
@@ -94,6 +101,8 @@
   llvm::DIType CreateType(const MemberPointerType *Ty, llvm::DIFile F);
   llvm::DIType CreateType(const AtomicType *Ty, llvm::DIFile F);
   llvm::DIType CreateEnumType(const EnumDecl *ED);
+  llvm::DIType getTypeOrNull(const QualType);
+  llvm::DIType getCompletedTypeOrNull(const QualType);
   llvm::DIType getOrCreateMethodType(const CXXMethodDecl *Method,
                                      llvm::DIFile F);
   llvm::DIType getOrCreateFunctionType(const Decl *D, QualType FnType,
@@ -139,6 +148,7 @@
                                AccessSpecifier AS, uint64_t offsetInBits,
                                llvm::DIFile tunit,
                                llvm::DIDescriptor scope);
+  void CollectRecordStaticVars(const RecordDecl *, llvm::DIType);
   void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile F,
                            SmallVectorImpl<llvm::Value *> &E,
                            llvm::DIType RecordTy);
@@ -154,7 +164,8 @@
 public:
   CGDebugInfo(CodeGenModule &CGM);
   ~CGDebugInfo();
-  void finalize() { DBuilder.finalize(); }
+
+  void finalize(void);
=20
   /// setLocation - Update the current source location. If \arg loc is
   /// invalid it is ignored.
@@ -172,10 +183,6 @@
   /// EmitFunctionEnd - Constructs the debug code for exiting a function.
   void EmitFunctionEnd(CGBuilderTy &Builder);
=20
-  /// UpdateCompletedType - Update type cache because the type is now
-  /// translated.
-  void UpdateCompletedType(const TagDecl *TD);
-
   /// EmitLexicalBlockStart - Emit metadata to indicate the beginning of a
   /// new lexical block and push the block onto the stack.
   void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
@@ -219,6 +226,12 @@
=20
   /// getOrCreateRecordType - Emit record type's standalone debug info.=20
   llvm::DIType getOrCreateRecordType(QualType Ty, SourceLocation L);
+
+  /// getOrCreateInterfaceType - Emit an objective c interface type standa=
lone
+  /// debug info.
+  llvm::DIType getOrCreateInterfaceType(QualType Ty,
+					SourceLocation Loc);
+
 private:
   /// EmitDeclare - Emit call to llvm.dbg.declare for a variable declarati=
on.
   void EmitDeclare(const VarDecl *decl, unsigned Tag, llvm::Value *AI,
@@ -232,6 +245,13 @@
   /// getContextDescriptor - Get context info for the decl.
   llvm::DIDescriptor getContextDescriptor(const Decl *Decl);
=20
+  /// createRecordFwdDecl - Create a forward decl for a RecordType in a gi=
ven
+  /// context.
+  llvm::DIType createRecordFwdDecl(const RecordDecl *, llvm::DIDescriptor);
+ =20
+  /// createContextChain - Create a set of decls for the context chain.
+  llvm::DIDescriptor createContextChain(const Decl *Decl);
+
   /// getCurrentDirname - Return current directory name.
   StringRef getCurrentDirname();
=20
@@ -249,9 +269,17 @@
   /// necessary.
   llvm::DIType getOrCreateType(QualType Ty, llvm::DIFile F);
=20
+  /// getOrCreateLimitedType - Get the type from the cache or create a new
+  /// partial type if necessary.
+  llvm::DIType getOrCreateLimitedType(QualType Ty, llvm::DIFile F);
+
   /// CreateTypeNode - Create type metadata for a source language type.
   llvm::DIType CreateTypeNode(QualType Ty, llvm::DIFile F);
=20
+  /// CreateLimitedTypeNode - Create type metadata for a source language
+  /// type, but only partial types for records.
+  llvm::DIType CreateLimitedTypeNode(QualType Ty, llvm::DIFile F);
+
   /// CreateMemberType - Create new member and increase Offset by FType's =
size.
   llvm::DIType CreateMemberType(llvm::DIFile Unit, QualType FType,
                                 StringRef Name, uint64_t *Offset);
@@ -274,7 +302,7 @@
   StringRef getSelectorName(Selector S);
=20
   /// getClassName - Get class name including template argument list.
-  StringRef getClassName(RecordDecl *RD);
+  StringRef getClassName(const RecordDecl *RD);
=20
   /// getVTableName - Get vtable name for the given Class.
   StringRef getVTableName(const CXXRecordDecl *Decl);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGDecl.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGDecl.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -65,8 +65,6 @@
   case Decl::AccessSpec:
   case Decl::LinkageSpec:
   case Decl::ObjCPropertyImpl:
-  case Decl::ObjCClass:
-  case Decl::ObjCForwardProtocol:
   case Decl::FileScopeAsm:
   case Decl::Friend:
   case Decl::FriendTemplate:
@@ -84,6 +82,7 @@
   case Decl::NamespaceAlias:
   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
   case Decl::Label:        // __label__ x;
+  case Decl::Import:
     // None of these decls require codegen support.
     return;
=20
@@ -122,7 +121,7 @@
     // uniqued.  We can't do this in C, though, because there's no
     // standard way to agree on which variables are the same (i.e.
     // there's no mangling).
-    if (getContext().getLangOptions().CPlusPlus)
+    if (getContext().getLangOpts().CPlusPlus)
       if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
         Linkage =3D CurFn->getLinkage();
=20
@@ -142,7 +141,7 @@
 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &=
D,
                                      const char *Separator) {
   CodeGenModule &CGM =3D CGF.CGM;
-  if (CGF.getContext().getLangOptions().CPlusPlus) {
+  if (CGF.getContext().getLangOpts().CPlusPlus) {
     StringRef Name =3D CGM.getMangledName(&D);
     return Name.str();
   }
@@ -177,7 +176,12 @@
   QualType Ty =3D D.getType();
   assert(Ty->isConstantSizeType() && "VLAs can't be static");
=20
-  std::string Name =3D GetStaticDeclName(*this, D, Separator);
+  // Use the label if the variable is renamed with the asm-label extension.
+  std::string Name;
+  if (D.hasAttr<AsmLabelAttr>())
+    Name =3D CGM.getMangledName(&D);
+  else
+    Name =3D GetStaticDeclName(*this, D, Separator);
=20
   llvm::Type *LTy =3D CGM.getTypes().ConvertTypeForMem(Ty);
   llvm::GlobalVariable *GV =3D
@@ -192,6 +196,14 @@
   return GV;
 }
=20
+/// hasNontrivialDestruction - Determine whether a type's destruction is
+/// non-trivial. If so, and the variable uses static initialization, we mu=
st
+/// register its destructor to run on exit.
+static bool hasNontrivialDestruction(QualType T) {
+  CXXRecordDecl *RD =3D T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(=
);
+  return RD && !RD->hasTrivialDestructor();
+}
+
 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
 /// global variable that has already been created for it.  If the initiali=
zer
 /// has a different type than GV does, this may free GV and return a diffe=
rent
@@ -199,19 +211,19 @@
 llvm::GlobalVariable *
 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
                                                llvm::GlobalVariable *GV) {
-  llvm::Constant *Init =3D CGM.EmitConstantExpr(D.getInit(), D.getType(), =
this);
+  llvm::Constant *Init =3D CGM.EmitConstantInit(D, this);
=20
   // If constant emission failed, then this should be a C++ static
   // initializer.
   if (!Init) {
-    if (!getContext().getLangOptions().CPlusPlus)
+    if (!getContext().getLangOpts().CPlusPlus)
       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
     else if (Builder.GetInsertBlock()) {
       // Since we have a static initializer, this global variable can't
       // be constant.
       GV->setConstant(false);
=20
-      EmitCXXGuardedInit(D, GV);
+      EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
     }
     return GV;
   }
@@ -243,7 +255,16 @@
     OldGV->eraseFromParent();
   }
=20
+  GV->setConstant(CGM.isTypeConstant(D.getType(), true));
   GV->setInitializer(Init);
+
+  if (hasNontrivialDestruction(D.getType())) {
+    // We have a constant initializer, but a nontrivial destructor. We sti=
ll
+    // need to perform a guarded "initialization" in order to register the
+    // destructor.
+    EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
+  }
+
   return GV;
 }
=20
@@ -252,11 +273,23 @@
   llvm::Value *&DMEntry =3D LocalDeclMap[&D];
   assert(DMEntry =3D=3D 0 && "Decl already exists in localdeclmap!");
=20
-  llvm::GlobalVariable *GV =3D CreateStaticVarDecl(D, ".", Linkage);
+  // Check to see if we already have a global variable for this
+  // declaration.  This can happen when double-emitting function
+  // bodies, e.g. with complete and base constructors.
+  llvm::Constant *addr =3D
+    CGM.getStaticLocalDeclAddress(&D);
+
+  llvm::GlobalVariable *var;
+  if (addr) {
+    var =3D cast<llvm::GlobalVariable>(addr->stripPointerCasts());
+  } else {
+    addr =3D var =3D CreateStaticVarDecl(D, ".", Linkage);
+  }
=20
   // Store into LocalDeclMap before generating initializer to handle
   // circular references.
-  DMEntry =3D GV;
+  DMEntry =3D addr;
+  CGM.setStaticLocalDeclAddress(&D, addr);
=20
   // We can't have a VLA here, but we can have a pointer to a VLA,
   // even though that doesn't really make any sense.
@@ -264,40 +297,38 @@
   if (D.getType()->isVariablyModifiedType())
     EmitVariablyModifiedType(D.getType());
=20
-  // Local static block variables must be treated as globals as they may be
-  // referenced in their RHS initializer block-literal expresion.
-  CGM.setStaticLocalDeclAddress(&D, GV);
+  // Save the type in case adding the initializer forces a type change.
+  llvm::Type *expectedType =3D addr->getType();
=20
   // If this value has an initializer, emit it.
   if (D.getInit())
-    GV =3D AddInitializerToStaticVarDecl(D, GV);
+    var =3D AddInitializerToStaticVarDecl(D, var);
=20
-  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
+  var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
=20
   if (D.hasAttr<AnnotateAttr>())
-    CGM.AddGlobalAnnotations(&D, GV);
+    CGM.AddGlobalAnnotations(&D, var);
=20
   if (const SectionAttr *SA =3D D.getAttr<SectionAttr>())
-    GV->setSection(SA->getName());
+    var->setSection(SA->getName());
=20
   if (D.hasAttr<UsedAttr>())
-    CGM.AddUsedGlobal(GV);
+    CGM.AddUsedGlobal(var);
=20
   // We may have to cast the constant because of the initializer
   // mismatch above.
   //
   // FIXME: It is really dangerous to store this in the map; if anyone
   // RAUW's the GV uses of this constant will be invalid.
-  llvm::Type *LTy =3D CGM.getTypes().ConvertTypeForMem(D.getType());
-  llvm::Type *LPtrTy =3D
-    LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
-  DMEntry =3D llvm::ConstantExpr::getBitCast(GV, LPtrTy);
+  llvm::Constant *castedAddr =3D llvm::ConstantExpr::getBitCast(var, expec=
tedType);
+  DMEntry =3D castedAddr;
+  CGM.setStaticLocalDeclAddress(&D, castedAddr);
=20
   // Emit global variable debug descriptor for static vars.
   CGDebugInfo *DI =3D getDebugInfo();
   if (DI) {
     DI->setLocation(D.getLocation());
-    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
+    DI->EmitGlobalVariable(var, &D);
   }
 }
=20
@@ -306,12 +337,12 @@
     DestroyObject(llvm::Value *addr, QualType type,
                   CodeGenFunction::Destroyer *destroyer,
                   bool useEHCleanupForArray)
-      : addr(addr), type(type), destroyer(*destroyer),
+      : addr(addr), type(type), destroyer(destroyer),
         useEHCleanupForArray(useEHCleanupForArray) {}
=20
     llvm::Value *addr;
     QualType type;
-    CodeGenFunction::Destroyer &destroyer;
+    CodeGenFunction::Destroyer *destroyer;
     bool useEHCleanupForArray;
=20
     void Emit(CodeGenFunction &CGF, Flags flags) {
@@ -371,8 +402,8 @@
     void Emit(CodeGenFunction &CGF, Flags flags) {
       // Compute the address of the local variable, in case it's a
       // byref or something.
-      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
-                      SourceLocation());
+      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
+                      Var.getType(), VK_LValue, SourceLocation());
       llvm::Value *value =3D CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&D=
RE));
       CGF.EmitExtendGCLifetime(value);
     }
@@ -388,8 +419,8 @@
       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
=20
     void Emit(CodeGenFunction &CGF, Flags flags) {
-      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
-                      SourceLocation());
+      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
+                      Var.getType(), VK_LValue, SourceLocation());
       // Compute the address of the local variable, in case it's a byref
       // or something.
       llvm::Value *Addr =3D CGF.EmitDeclRefLValue(&DRE).getAddress();
@@ -426,7 +457,7 @@
     break;
=20
   case Qualifiers::OCL_Strong: {
-    CodeGenFunction::Destroyer &destroyer =3D
+    CodeGenFunction::Destroyer *destroyer =3D
       (var.hasAttr<ObjCPreciseLifetimeAttr>()
        ? CodeGenFunction::destroyARCStrongPrecise
        : CodeGenFunction::destroyARCStrongImprecise);
@@ -490,15 +521,17 @@
     llvm::Value *value =3D EmitScalarExpr(init);
     if (capturedByInit)
       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
-    EmitStoreThroughLValue(RValue::get(value), lvalue);
+    EmitStoreThroughLValue(RValue::get(value), lvalue, true);
     return;
   }
=20
   // If we're emitting a value with lifetime, we have to do the
   // initialization *before* we leave the cleanup scopes.
+  if (const ExprWithCleanups *ewc =3D dyn_cast<ExprWithCleanups>(init)) {
+    enterFullExpression(ewc);
+    init =3D ewc->getSubExpr();
+  }
   CodeGenFunction::RunCleanupsScope Scope(*this);
-  if (const ExprWithCleanups *ewc =3D dyn_cast<ExprWithCleanups>(init))
-    init =3D ewc->getSubExpr();
=20
   // We have to maintain the illusion that the variable is
   // zero-initialized.  If the variable might be accessed in its
@@ -529,7 +562,7 @@
=20
     // Otherwise just do a simple store.
     else
-      EmitStoreOfScalar(zero, tempLV);
+      EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
   }
=20
   // Emit the initializer.
@@ -575,19 +608,19 @@
   // both __weak and __strong, but __weak got filtered out above.
   if (accessedByInit && lifetime =3D=3D Qualifiers::OCL_Strong) {
     llvm::Value *oldValue =3D EmitLoadOfScalar(lvalue);
-    EmitStoreOfScalar(value, lvalue);
+    EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
     EmitARCRelease(oldValue, /*precise*/ false);
     return;
   }
=20
-  EmitStoreOfScalar(value, lvalue);
+  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
 }
=20
 /// EmitScalarInit - Initialize the given lvalue with the given object.
 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
   Qualifiers::ObjCLifetime lifetime =3D lvalue.getObjCLifetime();
   if (!lifetime)
-    return EmitStoreThroughLValue(RValue::get(init), lvalue);
+    return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
=20
   switch (lifetime) {
   case Qualifiers::OCL_None:
@@ -611,7 +644,7 @@
     break;
   }
=20
-  EmitStoreOfScalar(init, lvalue);
+  EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
 }
=20
 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
@@ -638,6 +671,16 @@
     }
     return true;
   }
+ =20
+  if (llvm::ConstantDataSequential *CDS =3D
+        dyn_cast<llvm::ConstantDataSequential>(Init)) {
+    for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i) {
+      llvm::Constant *Elt =3D CDS->getElementAsConstant(i);
+      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
+        return false;
+    }
+    return true;
+  }
=20
   // Anything else is hard and scary.
   return false;
@@ -648,17 +691,26 @@
 /// stores that would be required.
 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value=
 *Loc,
                                          bool isVolatile, CGBuilderTy &Bui=
lder) {
-  // Zero doesn't require any stores.
-  if (isa<llvm::ConstantAggregateZero>(Init) ||
-      isa<llvm::ConstantPointerNull>(Init) ||
-      isa<llvm::UndefValue>(Init))
+  // Zero doesn't require a store.
+  if (Init->isNullValue() || isa<llvm::UndefValue>(Init))
     return;
=20
   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
       isa<llvm::ConstantExpr>(Init)) {
-    if (!Init->isNullValue())
-      Builder.CreateStore(Init, Loc, isVolatile);
+    Builder.CreateStore(Init, Loc, isVolatile);
+    return;
+  }
+ =20
+  if (llvm::ConstantDataSequential *CDS =3D=20
+        dyn_cast<llvm::ConstantDataSequential>(Init)) {
+    for (unsigned i =3D 0, e =3D CDS->getNumElements(); i !=3D e; ++i) {
+      llvm::Constant *Elt =3D CDS->getElementAsConstant(i);
+     =20
+      // Get a pointer to the element and emit it.
+      emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0,=
 i),
+                                   isVolatile, Builder);
+    }
     return;
   }
=20
@@ -667,9 +719,7 @@
=20
   for (unsigned i =3D 0, e =3D Init->getNumOperands(); i !=3D e; ++i) {
     llvm::Constant *Elt =3D cast<llvm::Constant>(Init->getOperand(i));
-    if (Elt->isNullValue()) continue;
-
-    // Otherwise, get a pointer to the element and emit it.
+    // Get a pointer to the element and emit it.
     emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i=
),
                                  isVolatile, Builder);
   }
@@ -728,15 +778,17 @@
   llvm::Value *DeclPtr;
   if (Ty->isConstantSizeType()) {
     if (!Target.useGlobalsForAutomaticVariables()) {
-      bool NRVO =3D getContext().getLangOptions().ElideConstructors &&
+      bool NRVO =3D getContext().getLangOpts().ElideConstructors &&
                   D.isNRVOVariable();
=20
       // If this value is a POD array or struct with a statically
-      // determinable constant initializer, there are optimizations we
-      // can do.
-      // TODO: we can potentially constant-evaluate non-POD structs and
-      // arrays as long as the initialization is trivial (e.g. if they
-      // have a non-trivial destructor, but not a non-trivial constructor).
+      // determinable constant initializer, there are optimizations we can=
 do.
+      //
+      // TODO: We should constant-evaluate the initializer of any variable,
+      // as long as it is initialized by a constant expression. Currently,
+      // isConstantInitializer produces wrong answers for structs with
+      // reference or bitfield members, and a few other cases, and checking
+      // for POD-ness protects us from some of these.
       if (D.getInit() &&
           (Ty->isArrayType() || Ty->isRecordType()) &&
           (Ty.isPODType(getContext()) ||
@@ -744,9 +796,10 @@
           D.getInit()->isConstantInitializer(getContext(), false)) {
=20
         // If the variable's a const type, and it's neither an NRVO
-        // candidate nor a __block variable, emit it as a global instead.
-        if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified(=
) &&
-            !NRVO && !isByRef) {
+        // candidate nor a __block variable and has no mutable members,
+        // emit it as a global instead.
+        if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
+            CGM.isTypeConstant(Ty, true)) {
           EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
=20
           emission.Address =3D 0; // signal this condition to later callba=
cks
@@ -788,7 +841,7 @@
           LTy =3D BuildByRefType(&D);
=20
         llvm::AllocaInst *Alloc =3D CreateTempAlloca(LTy);
-        Alloc->setName(D.getNameAsString());
+        Alloc->setName(D.getName());
=20
         CharUnits allocaAlignment =3D alignment;
         if (isByRef)
@@ -960,21 +1013,22 @@
   llvm::Value *Loc =3D
     capturedByInit ? emission.Address : emission.getObjectAddress(*this);
=20
-  if (!emission.IsConstantAggregate) {
-    LValue lv =3D MakeAddrLValue(Loc, type, alignment.getQuantity());
+  llvm::Constant *constant =3D 0;
+  if (emission.IsConstantAggregate) {
+    assert(!capturedByInit && "constant init contains a capturing block?");
+    constant =3D CGM.EmitConstantInit(D, this);
+  }
+
+  if (!constant) {
+    LValue lv =3D MakeAddrLValue(Loc, type, alignment);
     lv.setNonGC(true);
     return EmitExprAsInit(Init, &D, lv, capturedByInit);
   }
=20
   // If this is a simple aggregate initialization, we can optimize it
   // in various ways.
-  assert(!capturedByInit && "constant init contains a capturing block?");
-
   bool isVolatile =3D type.isVolatileQualified();
=20
-  llvm::Constant *constant =3D CGM.EmitConstantExpr(D.getInit(), type, thi=
s);
-  assert(constant !=3D 0 && "Wasn't a simple constant init?");
-
   llvm::Value *SizeVal =3D
     llvm::ConstantInt::get(IntPtrTy,
                            getContext().getTypeSizeInChars(type).getQuanti=
ty());
@@ -1035,7 +1089,7 @@
     RValue rvalue =3D EmitReferenceBindingToExpr(init, D);
     if (capturedByInit)
       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
-    EmitStoreThroughLValue(rvalue, lvalue);
+    EmitStoreThroughLValue(rvalue, lvalue, true);
   } else if (!hasAggregateLLVMType(type)) {
     EmitScalarInit(init, D, lvalue, capturedByInit);
   } else if (type->isAnyComplexType()) {
@@ -1049,6 +1103,7 @@
                                               AggValueSlot::IsDestructed,
                                          AggValueSlot::DoesNotNeedGCBarrie=
rs,
                                               AggValueSlot::IsNotAliased));
+    MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
   }
 }
=20
@@ -1101,7 +1156,7 @@
   }
=20
   // If we haven't chosen a more specific destroyer, use the default.
-  if (!destroyer) destroyer =3D &getDestroyer(dtorKind);
+  if (!destroyer) destroyer =3D getDestroyer(dtorKind);
=20
   // Use an EH cleanup in array destructors iff the destructor itself
   // is being pushed as an EH cleanup.
@@ -1123,7 +1178,7 @@
     emitAutoVarTypeCleanup(emission, dtorKind);
=20
   // In GC mode, honor objc_precise_lifetime.
-  if (getLangOptions().getGC() !=3D LangOptions::NonGC &&
+  if (getLangOpts().getGC() !=3D LangOptions::NonGC &&
       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
   }
@@ -1135,7 +1190,7 @@
     llvm::Constant *F =3D CGM.GetAddrOfFunction(FD);
     assert(F && "Could not find function!");
=20
-    const CGFunctionInfo &Info =3D CGM.getTypes().getFunctionInfo(FD);
+    const CGFunctionInfo &Info =3D CGM.getTypes().arrangeFunctionDeclarati=
on(FD);
     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info,=
 &D);
   }
=20
@@ -1145,25 +1200,18 @@
     enterByrefCleanup(emission);
 }
=20
-CodeGenFunction::Destroyer &
+CodeGenFunction::Destroyer *
 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
-  // This is surprisingly compiler-dependent.  GCC 4.2 can't bind
-  // references to functions directly in returns, and using '*&foo'
-  // confuses MSVC.  Luckily, the following code pattern works in both.
-  Destroyer *destroyer =3D 0;
   switch (kind) {
   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"=
);
   case QualType::DK_cxx_destructor:
-    destroyer =3D &destroyCXXObject;
-    break;
+    return destroyCXXObject;
   case QualType::DK_objc_strong_lifetime:
-    destroyer =3D &destroyARCStrongPrecise;
-    break;
+    return destroyARCStrongPrecise;
   case QualType::DK_objc_weak_lifetime:
-    destroyer =3D &destroyARCWeak;
-    break;
+    return destroyARCWeak;
   }
-  return *destroyer;
+  llvm_unreachable("Unknown DestructionKind");
 }
=20
 /// pushDestroy - Push the standard destructor for the given type.
@@ -1177,7 +1225,7 @@
 }
=20
 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *ad=
dr,
-                                  QualType type, Destroyer &destroyer,
+                                  QualType type, Destroyer *destroyer,
                                   bool useEHCleanupForArray) {
   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
                                      destroyer, useEHCleanupForArray);
@@ -1195,7 +1243,7 @@
 ///   used when destroying array elements, in case one of the
 ///   destructions throws an exception
 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
-                                  Destroyer &destroyer,
+                                  Destroyer *destroyer,
                                   bool useEHCleanupForArray) {
   const ArrayType *arrayType =3D getContext().getAsArrayType(type);
   if (!arrayType)
@@ -1232,7 +1280,7 @@
 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
                                        llvm::Value *end,
                                        QualType type,
-                                       Destroyer &destroyer,
+                                       Destroyer *destroyer,
                                        bool checkZeroLength,
                                        bool useEHCleanup) {
   assert(!type->isArrayType());
@@ -1283,7 +1331,7 @@
 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
                                     llvm::Value *begin, llvm::Value *end,
                                     QualType type,
-                                    CodeGenFunction::Destroyer &destroyer)=
 {
+                                    CodeGenFunction::Destroyer *destroyer)=
 {
   // If the element type is itself an array, drill down.
   unsigned arrayDepth =3D 0;
   while (const ArrayType *arrayType =3D CGF.getContext().getAsArrayType(ty=
pe)) {
@@ -1316,13 +1364,13 @@
     llvm::Value *ArrayBegin;
     llvm::Value *ArrayEnd;
     QualType ElementType;
-    CodeGenFunction::Destroyer &Destroyer;
+    CodeGenFunction::Destroyer *Destroyer;
   public:
     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *array=
End,
                                QualType elementType,
                                CodeGenFunction::Destroyer *destroyer)
       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
-        ElementType(elementType), Destroyer(*destroyer) {}
+        ElementType(elementType), Destroyer(destroyer) {}
=20
     void Emit(CodeGenFunction &CGF, Flags flags) {
       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
@@ -1337,14 +1385,14 @@
     llvm::Value *ArrayBegin;
     llvm::Value *ArrayEndPointer;
     QualType ElementType;
-    CodeGenFunction::Destroyer &Destroyer;
+    CodeGenFunction::Destroyer *Destroyer;
   public:
     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
                                  llvm::Value *arrayEndPointer,
                                  QualType elementType,
                                  CodeGenFunction::Destroyer *destroyer)
       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
-        ElementType(elementType), Destroyer(*destroyer) {}
+        ElementType(elementType), Destroyer(destroyer) {}
=20
     void Emit(CodeGenFunction &CGF, Flags flags) {
       llvm::Value *arrayEnd =3D CGF.Builder.CreateLoad(ArrayEndPointer);
@@ -1367,10 +1415,10 @@
 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayB=
egin,
                                                  llvm::Value *arrayEndPoin=
ter,
                                                        QualType elementTyp=
e,
-                                                       Destroyer &destroye=
r) {
+                                                       Destroyer *destroye=
r) {
   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
                                                     arrayBegin, arrayEndPo=
inter,
-                                                    elementType, &destroye=
r);
+                                                    elementType, destroyer=
);
 }
=20
 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
@@ -1386,10 +1434,10 @@
 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBeg=
in,
                                                      llvm::Value *arrayEnd,
                                                      QualType elementType,
-                                                     Destroyer &destroyer)=
 {
+                                                     Destroyer *destroyer)=
 {
   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
                                                   arrayBegin, arrayEnd,
-                                                  elementType, &destroyer);
+                                                  elementType, destroyer);
 }
=20
 namespace {
@@ -1442,7 +1490,10 @@
     DeclPtr =3D Arg;
   } else {
     // Otherwise, create a temporary to hold the value.
-    DeclPtr =3D CreateMemTemp(Ty, D.getName() + ".addr");
+    llvm::AllocaInst *Alloc =3D CreateTempAlloca(ConvertTypeForMem(Ty),
+                                               D.getName() + ".addr");
+    Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
+    DeclPtr =3D Alloc;
=20
     bool doStore =3D true;
=20
@@ -1480,7 +1531,7 @@
=20
         if (lt =3D=3D Qualifiers::OCL_Weak) {
           EmitARCInitWeak(DeclPtr, Arg);
-          doStore =3D false; // The weak init is a store, no need to do two
+          doStore =3D false; // The weak init is a store, no need to do tw=
o.
         }
       }
=20
@@ -1491,8 +1542,8 @@
     // Store the initial value into the alloca.
     if (doStore) {
       LValue lv =3D MakeAddrLValue(DeclPtr, Ty,
-                                 getContext().getDeclAlign(&D).getQuantity=
());
-      EmitStoreOfScalar(Arg, lv);
+                                 getContext().getDeclAlign(&D));
+      EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
     }
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGDeclCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGDeclCXX.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGDeclCXX.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -28,7 +28,7 @@
  =20
   ASTContext &Context =3D CGF.getContext();
=20
-  unsigned alignment =3D Context.getDeclAlign(&D).getQuantity();
+  CharUnits alignment =3D Context.getDeclAlign(&D);
   QualType type =3D D.getType();
   LValue lv =3D CGF.MakeAddrLValue(DeclPtr, type, alignment);
=20
@@ -101,60 +101,159 @@
   CGF.EmitCXXGlobalDtorRegistration(function, argument);
 }
=20
+/// Emit code to cause the variable at the given address to be considered =
as
+/// constant from this point onwards.
+static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
+                              llvm::Constant *Addr) {
+  // Don't emit the intrinsic if we're not optimizing.
+  if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
+    return;
+
+  // Grab the llvm.invariant.start intrinsic.
+  llvm::Intrinsic::ID InvStartID =3D llvm::Intrinsic::invariant_start;
+  llvm::Constant *InvariantStart =3D CGF.CGM.getIntrinsic(InvStartID);
+
+  // Emit a call with the size in bytes of the object.
+  CharUnits WidthChars =3D CGF.getContext().getTypeSizeInChars(D.getType()=
);
+  uint64_t Width =3D WidthChars.getQuantity();
+  llvm::Value *Args[2] =3D { llvm::ConstantInt::getSigned(CGF.Int64Ty, Wid=
th),
+                           llvm::ConstantExpr::getBitCast(Addr, CGF.Int8Pt=
rTy)};
+  CGF.Builder.CreateCall(InvariantStart, Args);
+}
+
 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
-                                               llvm::Constant *DeclPtr) {
+                                               llvm::Constant *DeclPtr,
+                                               bool PerformInit) {
=20
   const Expr *Init =3D D.getInit();
   QualType T =3D D.getType();
=20
   if (!T->isReferenceType()) {
-    EmitDeclInit(*this, D, DeclPtr);
-    EmitDeclDestroy(*this, D, DeclPtr);
+    if (PerformInit)
+      EmitDeclInit(*this, D, DeclPtr);
+    if (CGM.isTypeConstant(D.getType(), true))
+      EmitDeclInvariant(*this, D, DeclPtr);
+    else
+      EmitDeclDestroy(*this, D, DeclPtr);
     return;
   }
=20
+  assert(PerformInit && "cannot have constant initializer which needs "
+         "destruction for reference");
   unsigned Alignment =3D getContext().getDeclAlign(&D).getQuantity();
   RValue RV =3D EmitReferenceBindingToExpr(Init, &D);
   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
 }
=20
-void
-CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
-                                               llvm::Constant *DeclPtr) {
-  // Generate a global destructor entry if not using __cxa_atexit.
-  if (!CGM.getCodeGenOpts().CXAAtExit) {
-    CGM.AddCXXDtorEntry(DtorFn, DeclPtr);
+/// Register a global destructor using __cxa_atexit.
+static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
+                                        llvm::Constant *dtor,
+                                        llvm::Constant *addr) {
+  // We're assuming that the destructor function is something we can
+  // reasonably call with the default CC.  Go ahead and cast it to the
+  // right prototype.
+  llvm::Type *dtorTy =3D
+    llvm::FunctionType::get(CGF.VoidTy, CGF.Int8PtrTy, false)->getPointerT=
o();
+
+  // extern "C" int __cxa_atexit(void (*f)(void *), void *p, void *d);
+  llvm::Type *paramTys[] =3D { dtorTy, CGF.Int8PtrTy, CGF.Int8PtrTy };
+  llvm::FunctionType *atexitTy =3D
+    llvm::FunctionType::get(CGF.IntTy, paramTys, false);
+
+  // Fetch the actual function.
+  llvm::Constant *atexit =3D
+    CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
+  if (llvm::Function *fn =3D dyn_cast<llvm::Function>(atexit))
+    fn->setDoesNotThrow();
+
+  // Create a variable that binds the atexit to this shared object.
+  llvm::Constant *handle =3D
+    CGF.CGM.CreateRuntimeVariable(CGF.Int8Ty, "__dso_handle");
+
+  llvm::Value *args[] =3D {
+    llvm::ConstantExpr::getBitCast(dtor, dtorTy),
+    llvm::ConstantExpr::getBitCast(addr, CGF.Int8PtrTy),
+    handle
+  };
+  CGF.Builder.CreateCall(atexit, args);
+}
+
+static llvm::Function *
+CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
+                                   llvm::FunctionType *ty,
+                                   const Twine &name);
+
+/// Create a stub function, suitable for being passed to atexit,
+/// which passes the given address to the given destructor function.
+static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
+                                        llvm::Constant *dtor,
+                                        llvm::Constant *addr) {
+  // Get the destructor function type, void(*)(void).
+  llvm::FunctionType *ty =3D llvm::FunctionType::get(CGM.VoidTy, false);
+  llvm::Function *fn =3D
+    CreateGlobalInitOrDestructFunction(CGM, ty,
+                                       Twine("__dtor_", addr->getName()));
+
+  CodeGenFunction CGF(CGM);
+
+  CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
+                    CGM.getTypes().arrangeNullaryFunction(),
+                    FunctionArgList(), SourceLocation());
+
+  llvm::CallInst *call =3D CGF.Builder.CreateCall(dtor, addr);
+=20
+ // Make sure the call and the callee agree on calling convention.
+  if (llvm::Function *dtorFn =3D
+        dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
+    call->setCallingConv(dtorFn->getCallingConv());
+
+  CGF.FinishFunction();
+
+  return fn;
+}
+
+/// Register a global destructor using atexit.
+static void emitGlobalDtorWithAtExit(CodeGenFunction &CGF,
+                                     llvm::Constant *dtor,
+                                     llvm::Constant *addr) {
+  // Create a function which calls the destructor.
+  llvm::Constant *dtorStub =3D createAtExitStub(CGF.CGM, dtor, addr);
+
+  // extern "C" int atexit(void (*f)(void));
+  llvm::FunctionType *atexitTy =3D
+    llvm::FunctionType::get(CGF.IntTy, dtorStub->getType(), false);
+
+  llvm::Constant *atexit =3D
+    CGF.CGM.CreateRuntimeFunction(atexitTy, "atexit");
+  if (llvm::Function *atexitFn =3D dyn_cast<llvm::Function>(atexit))
+    atexitFn->setDoesNotThrow();
+
+  CGF.Builder.CreateCall(atexit, dtorStub);
+}
+
+void CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *dtor,
+                                                    llvm::Constant *addr) {
+  // Use __cxa_atexit if available.
+  if (CGM.getCodeGenOpts().CXAAtExit) {
+    emitGlobalDtorWithCXAAtExit(*this, dtor, addr);
     return;
   }
=20
-  // Get the destructor function type
-  llvm::Type *DtorFnTy =3D
-    llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
-                            Int8PtrTy, false);
-  DtorFnTy =3D llvm::PointerType::getUnqual(DtorFnTy);
+  // In Apple kexts, we want to add a global destructor entry.
+  // FIXME: shouldn't this be guarded by some variable?
+  if (CGM.getContext().getLangOpts().AppleKext) {
+    // Generate a global destructor entry.
+    CGM.AddCXXDtorEntry(dtor, addr);
+    return;
+  }
=20
-  llvm::Type *Params[] =3D { DtorFnTy, Int8PtrTy, Int8PtrTy };
-
-  // Get the __cxa_atexit function type
-  // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
-  llvm::FunctionType *AtExitFnTy =3D
-    llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false=
);
-
-  llvm::Constant *AtExitFn =3D CGM.CreateRuntimeFunction(AtExitFnTy,
-                                                       "__cxa_atexit");
-  if (llvm::Function *Fn =3D dyn_cast<llvm::Function>(AtExitFn))
-    Fn->setDoesNotThrow();
-
-  llvm::Constant *Handle =3D CGM.CreateRuntimeVariable(Int8PtrTy,
-                                                     "__dso_handle");
-  llvm::Value *Args[3] =3D { llvm::ConstantExpr::getBitCast(DtorFn, DtorFn=
Ty),
-                           llvm::ConstantExpr::getBitCast(DeclPtr, Int8Ptr=
Ty),
-                           llvm::ConstantExpr::getBitCast(Handle, Int8PtrT=
y) };
-  Builder.CreateCall(AtExitFn, Args);
+  // Otherwise, we just use atexit.
+  emitGlobalDtorWithAtExit(*this, dtor, addr);
 }
=20
 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
-                                         llvm::GlobalVariable *DeclPtr) {
+                                         llvm::GlobalVariable *DeclPtr,
+                                         bool PerformInit) {
   // If we've been asked to forbid guard variables, emit an error now.
   // This diagnostic is hard-coded for Darwin's use case;  we can find
   // better phrasing if someone else needs it.
@@ -163,24 +262,24 @@
               "this initialization requires a guard variable, which "
               "the kernel does not support");
=20
-  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr);
+  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
 }
=20
 static llvm::Function *
 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
                                    llvm::FunctionType *FTy,
-                                   StringRef Name) {
+                                   const Twine &Name) {
   llvm::Function *Fn =3D
     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
                            Name, &CGM.getModule());
-  if (!CGM.getContext().getLangOptions().AppleKext) {
+  if (!CGM.getContext().getLangOpts().AppleKext) {
     // Set the section if needed.
     if (const char *Section =3D=20
           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
       Fn->setSection(Section);
   }
=20
-  if (!CGM.getLangOptions().Exceptions)
+  if (!CGM.getLangOpts().Exceptions)
     Fn->setDoesNotThrow();
=20
   return Fn;
@@ -188,16 +287,16 @@
=20
 void
 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
-                                            llvm::GlobalVariable *Addr) {
-  llvm::FunctionType *FTy
-    =3D llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
-                              false);
+                                            llvm::GlobalVariable *Addr,
+                                            bool PerformInit) {
+  llvm::FunctionType *FTy =3D llvm::FunctionType::get(VoidTy, false);
=20
   // Create a variable initialization function.
   llvm::Function *Fn =3D
     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init"=
);
=20
-  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr);
+  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
+                                                          PerformInit);
=20
   if (D->hasAttr<InitPriorityAttr>()) {
     unsigned int order =3D D->getAttr<InitPriorityAttr>()->getPriority();
@@ -226,9 +325,7 @@
   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
     return;
=20
-  llvm::FunctionType *FTy
-    =3D llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
-                              false);
+  llvm::FunctionType *FTy =3D llvm::FunctionType::get(VoidTy, false);
=20
   // Create our global initialization function.
   llvm::Function *Fn =3D=20
@@ -260,24 +357,23 @@
   if (CXXGlobalDtors.empty())
     return;
=20
-  llvm::FunctionType *FTy
-    =3D llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
-                              false);
+  llvm::FunctionType *FTy =3D llvm::FunctionType::get(VoidTy, false);
=20
   // Create our global destructor function.
   llvm::Function *Fn =3D
     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
=20
-  CodeGenFunction(*this).GenerateCXXGlobalDtorFunc(Fn, CXXGlobalDtors);
+  CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
   AddGlobalDtor(Fn);
 }
=20
 /// Emit the code necessary to initialize the given global variable.
 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
                                                        const VarDecl *D,
-                                                 llvm::GlobalVariable *Add=
r) {
+                                                 llvm::GlobalVariable *Add=
r,
+                                                       bool PerformInit) {
   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
-                getTypes().getNullaryFunctionInfo(),
+                getTypes().arrangeNullaryFunction(),
                 FunctionArgList(), SourceLocation());
=20
   // Use guarded initialization if the global variable is weak. This
@@ -285,9 +381,9 @@
   // definitions explicitly marked weak.
   if (Addr->getLinkage() =3D=3D llvm::GlobalValue::WeakODRLinkage ||
       Addr->getLinkage() =3D=3D llvm::GlobalValue::WeakAnyLinkage) {
-    EmitCXXGuardedInit(*D, Addr);
+    EmitCXXGuardedInit(*D, Addr, PerformInit);
   } else {
-    EmitCXXGlobalVarDeclInit(*D, Addr);
+    EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
   }
=20
   FinishFunction();
@@ -297,14 +393,14 @@
                                                 llvm::Constant **Decls,
                                                 unsigned NumDecls) {
   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
-                getTypes().getNullaryFunctionInfo(),
+                getTypes().arrangeNullaryFunction(),
                 FunctionArgList(), SourceLocation());
=20
   RunCleanupsScope Scope(*this);
=20
   // When building in Objective-C++ ARC mode, create an autorelease pool
   // around the global initializers.
-  if (getLangOptions().ObjCAutoRefCount && getLangOptions().CPlusPlus) {  =
 =20
+  if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {   =20
     llvm::Value *token =3D EmitObjCAutoreleasePoolPush();
     EmitObjCAutoreleasePoolCleanup(token);
   }
@@ -318,11 +414,11 @@
   FinishFunction();
 }
=20
-void CodeGenFunction::GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
+void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant=
*> >
                                                 &DtorsAndObjects) {
   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
-                getTypes().getNullaryFunctionInfo(),
+                getTypes().arrangeNullaryFunction(),
                 FunctionArgList(), SourceLocation());
=20
   // Emit the dtors, in reverse order from construction.
@@ -343,16 +439,17 @@
 llvm::Function *=20
 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
                                        QualType type,
-                                       Destroyer &destroyer,
+                                       Destroyer *destroyer,
                                        bool useEHCleanupForArray) {
   FunctionArgList args;
   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
   args.push_back(&dst);
  =20
   const CGFunctionInfo &FI =3D=20
-    CGM.getTypes().getFunctionInfo(getContext().VoidTy, args,=20
-                                   FunctionType::ExtInfo());
-  llvm::FunctionType *FTy =3D CGM.getTypes().GetFunctionType(FI, false);
+    CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
+                                              FunctionType::ExtInfo(),
+                                              /*variadic*/ false);
+  llvm::FunctionType *FTy =3D CGM.getTypes().GetFunctionType(FI);
   llvm::Function *fn =3D=20
     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor"=
);
=20
@@ -365,4 +462,3 @@
  =20
   return fn;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGException.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGException.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGException.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -11,18 +11,14 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "CodeGenFunction.h"
+#include "CGCleanup.h"
+#include "CGObjCRuntime.h"
+#include "TargetInfo.h"
 #include "clang/AST/StmtCXX.h"
-
 #include "llvm/Intrinsics.h"
-#include "llvm/IntrinsicInst.h"
 #include "llvm/Support/CallSite.h"
=20
-#include "CGObjCRuntime.h"
-#include "CodeGenFunction.h"
-#include "CGException.h"
-#include "CGCleanup.h"
-#include "TargetInfo.h"
-
 using namespace clang;
 using namespace CodeGen;
=20
@@ -104,7 +100,7 @@
   llvm::FunctionType *FTy =3D
     llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=3D*/false);
=20
-  if (CGM.getLangOptions().SjLjExceptions)
+  if (CGM.getLangOpts().SjLjExceptions)
     return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume");
   return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume");
 }
@@ -113,7 +109,7 @@
   llvm::FunctionType *FTy =3D
     llvm::FunctionType::get(VoidTy, Int8PtrTy, /*IsVarArgs=3D*/false);
=20
-  if (CGM.getLangOptions().SjLjExceptions)
+  if (CGM.getLangOpts().SjLjExceptions)
     return CGM.CreateRuntimeFunction(FTy, "_Unwind_SjLj_Resume_or_Rethrow"=
);
   return CGM.CreateRuntimeFunction(FTy, "_Unwind_Resume_or_Rethrow");
 }
@@ -127,9 +123,9 @@
   StringRef name;
=20
   // In C++, use std::terminate().
-  if (CGF.getLangOptions().CPlusPlus)
+  if (CGF.getLangOpts().CPlusPlus)
     name =3D "_ZSt9terminatev"; // FIXME: mangling!
-  else if (CGF.getLangOptions().ObjC1 &&
+  else if (CGF.getLangOpts().ObjC1 &&
            CGF.CGM.getCodeGenOpts().ObjCRuntimeHasTerminate)
     name =3D "objc_terminate";
   else
@@ -145,14 +141,37 @@
   return CGF.CGM.CreateRuntimeFunction(FTy, Name);
 }
=20
-const EHPersonality EHPersonality::GNU_C("__gcc_personality_v0");
-const EHPersonality EHPersonality::GNU_C_SJLJ("__gcc_personality_sj0");
-const EHPersonality EHPersonality::NeXT_ObjC("__objc_personality_v0");
-const EHPersonality EHPersonality::GNU_CPlusPlus("__gxx_personality_v0");
-const EHPersonality EHPersonality::GNU_CPlusPlus_SJLJ("__gxx_personality_s=
j0");
-const EHPersonality EHPersonality::GNU_ObjC("__gnu_objc_personality_v0",
-                                            "objc_exception_throw");
-const EHPersonality EHPersonality::GNU_ObjCXX("__gnustep_objcxx_personalit=
y_v0");
+namespace {
+  /// The exceptions personality for a function.
+  struct EHPersonality {
+    const char *PersonalityFn;
+
+    // If this is non-null, this personality requires a non-standard
+    // function for rethrowing an exception after a catchall cleanup.
+    // This function must have prototype void(void*).
+    const char *CatchallRethrowFn;
+
+    static const EHPersonality &get(const LangOptions &Lang);
+    static const EHPersonality GNU_C;
+    static const EHPersonality GNU_C_SJLJ;
+    static const EHPersonality GNU_ObjC;
+    static const EHPersonality GNU_ObjCXX;
+    static const EHPersonality NeXT_ObjC;
+    static const EHPersonality GNU_CPlusPlus;
+    static const EHPersonality GNU_CPlusPlus_SJLJ;
+  };
+}
+
+const EHPersonality EHPersonality::GNU_C =3D { "__gcc_personality_v0", 0 };
+const EHPersonality EHPersonality::GNU_C_SJLJ =3D { "__gcc_personality_sj0=
", 0 };
+const EHPersonality EHPersonality::NeXT_ObjC =3D { "__objc_personality_v0"=
, 0 };
+const EHPersonality EHPersonality::GNU_CPlusPlus =3D { "__gxx_personality_=
v0", 0};
+const EHPersonality
+EHPersonality::GNU_CPlusPlus_SJLJ =3D { "__gxx_personality_sj0", 0 };
+const EHPersonality
+EHPersonality::GNU_ObjC =3D {"__gnu_objc_personality_v0", "objc_exception_=
throw"};
+const EHPersonality
+EHPersonality::GNU_ObjCXX =3D { "__gnustep_objcxx_personality_v0", 0 };
=20
 static const EHPersonality &getCPersonality(const LangOptions &L) {
   if (L.SjLjExceptions)
@@ -211,10 +230,8 @@
 static llvm::Constant *getPersonalityFn(CodeGenModule &CGM,
                                         const EHPersonality &Personality) {
   llvm::Constant *Fn =3D
-    CGM.CreateRuntimeFunction(llvm::FunctionType::get(
-                                llvm::Type::getInt32Ty(CGM.getLLVMContext(=
)),
-                                true),
-                              Personality.getPersonalityFnName());
+    CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty, true),
+                              Personality.PersonalityFn);
   return Fn;
 }
=20
@@ -283,17 +300,18 @@
     return;
=20
   // If we're not in ObjC++ -fexceptions, there's nothing to do.
-  if (!Features.CPlusPlus || !Features.ObjC1 || !Features.Exceptions)
+  if (!LangOpts.CPlusPlus || !LangOpts.ObjC1 || !LangOpts.Exceptions)
     return;
=20
-  const EHPersonality &ObjCXX =3D EHPersonality::get(Features);
-  const EHPersonality &CXX =3D getCXXPersonality(Features);
-  if (&ObjCXX =3D=3D &CXX ||
-      ObjCXX.getPersonalityFnName() =3D=3D CXX.getPersonalityFnName())
+  const EHPersonality &ObjCXX =3D EHPersonality::get(LangOpts);
+  const EHPersonality &CXX =3D getCXXPersonality(LangOpts);
+  if (&ObjCXX =3D=3D &CXX)
     return;
=20
-  llvm::Function *Fn =3D
-    getModule().getFunction(ObjCXX.getPersonalityFnName());
+  assert(std::strcmp(ObjCXX.PersonalityFn, CXX.PersonalityFn) !=3D 0 &&
+         "Different EHPersonalities using the same personality function.");
+
+  llvm::Function *Fn =3D getModule().getFunction(ObjCXX.PersonalityFn);
=20
   // Nothing to do if it's unused.
   if (!Fn || Fn->use_empty()) return;
@@ -359,7 +377,7 @@
                        /*IsInit*/ true);
=20
   // Deactivate the cleanup block.
-  CGF.DeactivateCleanupBlock(cleanup);
+  CGF.DeactivateCleanupBlock(cleanup, cast<llvm::Instruction>(typedAddr));
 }
=20
 llvm::Value *CodeGenFunction::getExceptionSlot() {
@@ -452,7 +470,7 @@
 }
=20
 void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
-  if (!CGM.getLangOptions().CXXExceptions)
+  if (!CGM.getLangOpts().CXXExceptions)
     return;
  =20
   const FunctionDecl* FD =3D dyn_cast_or_null<FunctionDecl>(D);
@@ -520,7 +538,7 @@
 }
=20
 void CodeGenFunction::EmitEndEHSpec(const Decl *D) {
-  if (!CGM.getLangOptions().CXXExceptions)
+  if (!CGM.getLangOpts().CXXExceptions)
     return;
  =20
   const FunctionDecl* FD =3D dyn_cast_or_null<FunctionDecl>(D);
@@ -636,15 +654,14 @@
     return false;
   }
=20
-  // Suppress warning.
-  return false;
+  llvm_unreachable("Invalid EHScope Kind!");
 }
=20
 llvm::BasicBlock *CodeGenFunction::getInvokeDestImpl() {
   assert(EHStack.requiresLandingPad());
   assert(!EHStack.empty());
=20
-  if (!CGM.getLangOptions().Exceptions)
+  if (!CGM.getLangOpts().Exceptions)
     return 0;
=20
   // Check the innermost scope for a cached landing pad.  If this is
@@ -734,7 +751,7 @@
   // Save the current IR generation state.
   CGBuilderTy::InsertPoint savedIP =3D Builder.saveAndClearIP();
=20
-  const EHPersonality &personality =3D EHPersonality::get(getLangOptions()=
);
+  const EHPersonality &personality =3D EHPersonality::get(getLangOpts());
=20
   // Create and configure the landing pad.
   llvm::BasicBlock *lpad =3D createBasicBlock("lpad");
@@ -984,8 +1001,23 @@
     if (CatchType->hasPointerRepresentation()) {
       llvm::Value *CastExn =3D
         CGF.Builder.CreateBitCast(AdjustedExn, LLVMCatchTy, "exn.casted");
-      CGF.Builder.CreateStore(CastExn, ParamAddr);
-      return;
+
+      switch (CatchType.getQualifiers().getObjCLifetime()) {
+      case Qualifiers::OCL_Strong:
+        CastExn =3D CGF.EmitARCRetainNonBlock(CastExn);
+        // fallthrough
+
+      case Qualifiers::OCL_None:
+      case Qualifiers::OCL_ExplicitNone:
+      case Qualifiers::OCL_Autoreleasing:
+        CGF.Builder.CreateStore(CastExn, ParamAddr);
+        return;
+
+      case Qualifiers::OCL_Weak:
+        CGF.EmitARCInitWeak(ParamAddr, CastExn);
+        return;
+      }
+      llvm_unreachable("bad ownership qualifier!");
     }
=20
     // Otherwise, it returns a pointer into the exception object.
@@ -1039,10 +1071,12 @@
   CGF.EHStack.pushTerminate();
=20
   // Perform the copy construction.
-  CGF.EmitAggExpr(copyExpr, AggValueSlot::forAddr(ParamAddr, Qualifiers(),
-                                                  AggValueSlot::IsNotDestr=
ucted,
-                                          AggValueSlot::DoesNotNeedGCBarri=
ers,
-                                                  AggValueSlot::IsNotAlias=
ed));
+  CharUnits Alignment =3D CGF.getContext().getDeclAlign(&CatchParam);
+  CGF.EmitAggExpr(copyExpr,
+                  AggValueSlot::forAddr(ParamAddr, Alignment, Qualifiers(),
+                                        AggValueSlot::IsNotDestructed,
+                                        AggValueSlot::DoesNotNeedGCBarrier=
s,
+                                        AggValueSlot::IsNotAliased));
=20
   // Leave the terminate scope.
   CGF.EHStack.popTerminate();
@@ -1170,14 +1204,10 @@
     if (nextIsEnd) {
       CGF.Builder.restoreIP(savedIP);
       return;
-
+    }
     // Otherwise we need to emit and continue at that block.
-    } else {
-      CGF.EmitBlock(nextBlock);
-    }
+    CGF.EmitBlock(nextBlock);
   }
-
-  llvm_unreachable("fell out of loop!");
 }
=20
 void CodeGenFunction::popCatchScope() {
@@ -1464,7 +1494,7 @@
   Builder.SetInsertPoint(TerminateLandingPad);
=20
   // Tell the backend that this is a landing pad.
-  const EHPersonality &Personality =3D EHPersonality::get(CGM.getLangOptio=
ns());
+  const EHPersonality &Personality =3D EHPersonality::get(CGM.getLangOpts(=
));
   llvm::LandingPadInst *LPadInst =3D
     Builder.CreateLandingPad(llvm::StructType::get(Int8PtrTy, Int32Ty, NUL=
L),
                              getOpaquePersonalityFn(CGM, Personality), 0);
@@ -1511,24 +1541,23 @@
   EHResumeBlock =3D createBasicBlock("eh.resume");
   Builder.SetInsertPoint(EHResumeBlock);
=20
-  const EHPersonality &Personality =3D EHPersonality::get(CGM.getLangOptio=
ns());
+  const EHPersonality &Personality =3D EHPersonality::get(CGM.getLangOpts(=
));
=20
   // This can always be a call because we necessarily didn't find
   // anything on the EH stack which needs our help.
-  StringRef RethrowName =3D Personality.getCatchallRethrowFnName();
-  if (!RethrowName.empty()) {
+  const char *RethrowName =3D Personality.CatchallRethrowFn;
+  if (RethrowName !=3D 0) {
     Builder.CreateCall(getCatchallRethrowFn(*this, RethrowName),
                        getExceptionFromSlot())
       ->setDoesNotReturn();
   } else {
-    llvm::Value *Exn =3D getExceptionFromSlot();
-
     switch (CleanupHackLevel) {
     case CHL_MandatoryCatchall:
       // In mandatory-catchall mode, we need to use
       // _Unwind_Resume_or_Rethrow, or whatever the personality's
       // equivalent is.
-      Builder.CreateCall(getUnwindResumeOrRethrowFn(), Exn)
+      Builder.CreateCall(getUnwindResumeOrRethrowFn(),
+                         getExceptionFromSlot())
         ->setDoesNotReturn();
       break;
     case CHL_MandatoryCleanup: {
@@ -1552,7 +1581,7 @@
       // In an idealized mode where we don't have to worry about the
       // optimizer combining landing pads, we should just use
       // _Unwind_Resume (or the personality's equivalent).
-      Builder.CreateCall(getUnwindResumeFn(), Exn)
+      Builder.CreateCall(getUnwindResumeFn(), getExceptionFromSlot())
         ->setDoesNotReturn();
       break;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGExpr.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGExpr.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGExpr.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -23,6 +23,7 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/Frontend/CodeGenOptions.h"
 #include "llvm/Intrinsics.h"
+#include "llvm/LLVMContext.h"
 #include "llvm/Target/TargetData.h"
 using namespace clang;
 using namespace CodeGen;
@@ -134,14 +135,16 @@
                                        llvm::Value *Location,
                                        Qualifiers Quals,
                                        bool IsInit) {
-  if (E->getType()->isAnyComplexType())
+  // FIXME: This function should take an LValue as an argument.
+  if (E->getType()->isAnyComplexType()) {
     EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
-  else if (hasAggregateLLVMType(E->getType()))
-    EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
+  } else if (hasAggregateLLVMType(E->getType())) {
+    CharUnits Alignment =3D getContext().getTypeAlignInChars(E->getType());
+    EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
                                          AggValueSlot::IsDestructed_t(IsIn=
it),
                                          AggValueSlot::DoesNotNeedGCBarrie=
rs,
                                          AggValueSlot::IsAliased_t(!IsInit=
)));
-  else {
+  } else {
     RValue RV =3D RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
     LValue LV =3D MakeAddrLValue(Location, E->getType());
     EmitStoreThroughLValue(RV, LV);
@@ -182,7 +185,7 @@
                          const NamedDecl *InitializedDecl) {
   if (const VarDecl *VD =3D dyn_cast_or_null<VarDecl>(InitializedDecl)) {
     if (VD->hasGlobalStorage()) {
-      llvm::SmallString<256> Name;
+      SmallString<256> Name;
       llvm::raw_svector_ostream Out(Name);
       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, =
Out);
       Out.flush();
@@ -209,13 +212,20 @@
                             const CXXDestructorDecl *&ReferenceTemporaryDt=
or,
                             QualType &ObjCARCReferenceLifetimeType,
                             const NamedDecl *InitializedDecl) {
+  // Look through single-element init lists that claim to be lvalues. They=
're
+  // just syntactic wrappers in this case.
+  if (const InitListExpr *ILE =3D dyn_cast<InitListExpr>(E)) {
+    if (ILE->getNumInits() =3D=3D 1 && ILE->isGLValue())
+      E =3D ILE->getInit(0);
+  }
+
   // Look through expressions for materialized temporaries (for now).
   if (const MaterializeTemporaryExpr *M=20
                                       =3D dyn_cast<MaterializeTemporaryExp=
r>(E)) {
     // Objective-C++ ARC:
     //   If we are binding a reference to a temporary that has ownership, =
we=20
     //   need to perform retain/release operations on the temporary.
-    if (CGF.getContext().getLangOptions().ObjCAutoRefCount &&       =20
+    if (CGF.getContext().getLangOpts().ObjCAutoRefCount &&       =20
         E->getType()->isObjCLifetimeType() &&
         (E->getType().getObjCLifetime() =3D=3D Qualifiers::OCL_Strong ||
          E->getType().getObjCLifetime() =3D=3D Qualifiers::OCL_Weak ||
@@ -228,29 +238,21 @@
   if (const CXXDefaultArgExpr *DAE =3D dyn_cast<CXXDefaultArgExpr>(E))
     E =3D DAE->getExpr();
  =20
-  if (const ExprWithCleanups *TE =3D dyn_cast<ExprWithCleanups>(E)) {
+  if (const ExprWithCleanups *EWC =3D dyn_cast<ExprWithCleanups>(E)) {
+    CGF.enterFullExpression(EWC);
     CodeGenFunction::RunCleanupsScope Scope(CGF);
=20
-    return EmitExprForReferenceBinding(CGF, TE->getSubExpr(),=20
+    return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),=20
                                        ReferenceTemporary,=20
                                        ReferenceTemporaryDtor,
                                        ObjCARCReferenceLifetimeType,
                                        InitializedDecl);
   }
=20
-  if (const ObjCPropertyRefExpr *PRE =3D=20
-      dyn_cast<ObjCPropertyRefExpr>(E->IgnoreParenImpCasts()))
-    if (PRE->getGetterResultType()->isReferenceType())
-      E =3D PRE;
-   =20
   RValue RV;
   if (E->isGLValue()) {
     // Emit the expression as an lvalue.
     LValue LV =3D CGF.EmitLValue(E);
-    if (LV.isPropertyRef()) {
-      RV =3D CGF.EmitLoadOfPropertyRefLValue(LV);
-      return RV.getScalarVal();
-    }
    =20
     if (LV.isSimple())
       return LV.getAddress();
@@ -358,10 +360,11 @@
         !E->getType()->isAnyComplexType()) {
       ReferenceTemporary =3D CreateReferenceTemporary(CGF, E->getType(),=20
                                                     InitializedDecl);
+      CharUnits Alignment =3D CGF.getContext().getTypeAlignInChars(E->getT=
ype());
       AggValueSlot::IsDestructed_t isDestructed
         =3D AggValueSlot::IsDestructed_t(InitializedDecl !=3D 0);
-      AggSlot =3D AggValueSlot::forAddr(ReferenceTemporary, Qualifiers(),
-                                      isDestructed,
+      AggSlot =3D AggValueSlot::forAddr(ReferenceTemporary, Alignment,
+                                      Qualifiers(), isDestructed,
                                       AggValueSlot::DoesNotNeedGCBarriers,
                                       AggValueSlot::IsNotAliased);
     }
@@ -484,21 +487,17 @@
     case Qualifiers::OCL_Strong: {
       bool precise =3D VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
       CleanupKind cleanupKind =3D getARCCleanupKind();
-      // This local is a GCC and MSVC compiler workaround.
-      Destroyer *destroyer =3D precise ? &destroyARCStrongPrecise :
-                                       &destroyARCStrongImprecise;
       pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetim=
eType,
-                  *destroyer, cleanupKind & EHCleanup);
+                  precise ? destroyARCStrongPrecise : destroyARCStrongImpr=
ecise,
+                  cleanupKind & EHCleanup);
       break;
     }
        =20
     case Qualifiers::OCL_Weak: {
-      // This local is a GCC and MSVC compiler workaround.
-      Destroyer *destroyer =3D &destroyARCWeak;
       // __weak objects always get EH cleanups; otherwise, exceptions
       // could cause really nasty crashes instead of mere leaks.
       pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
-                  ObjCARCReferenceLifetimeType, *destroyer, true);
+                  ObjCARCReferenceLifetimeType, destroyARCWeak, true);
       break;       =20
     }
     }
@@ -512,10 +511,8 @@
 /// input field number being accessed.
 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
                                              const llvm::Constant *Elts) {
-  if (isa<llvm::ConstantAggregateZero>(Elts))
-    return 0;
-
-  return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
+  return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
+      ->getZExtValue();
 }
=20
 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
@@ -643,6 +640,9 @@
   switch (E->getStmtClass()) {
   default: return EmitUnsupportedLValue(E, "l-value expression");
=20
+  case Expr::ObjCPropertyRefExprClass:
+    llvm_unreachable("cannot emit a property reference directly");
+
   case Expr::ObjCSelectorExprClass:
   return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
   case Expr::ObjCIsaExprClass:
@@ -656,6 +656,7 @@
   case Expr::CallExprClass:
   case Expr::CXXMemberCallExprClass:
   case Expr::CXXOperatorCallExprClass:
+  case Expr::UserDefinedLiteralClass:
     return EmitCallExprLValue(cast<CallExpr>(E));
   case Expr::VAArgExprClass:
     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
@@ -671,17 +672,28 @@
     return EmitStringLiteralLValue(cast<StringLiteral>(E));
   case Expr::ObjCEncodeExprClass:
     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
-
-  case Expr::BlockDeclRefExprClass:
-    return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
+  case Expr::PseudoObjectExprClass:
+    return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
+  case Expr::InitListExprClass:
+    assert(cast<InitListExpr>(E)->getNumInits() =3D=3D 1 &&
+           "Only single-element init list can be lvalue.");
+    return EmitLValue(cast<InitListExpr>(E)->getInit(0));
=20
   case Expr::CXXTemporaryObjectExprClass:
   case Expr::CXXConstructExprClass:
     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
   case Expr::CXXBindTemporaryExprClass:
     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
-  case Expr::ExprWithCleanupsClass:
-    return EmitExprWithCleanupsLValue(cast<ExprWithCleanups>(E));
+  case Expr::LambdaExprClass:
+    return EmitLambdaLValue(cast<LambdaExpr>(E));
+
+  case Expr::ExprWithCleanupsClass: {
+    const ExprWithCleanups *cleanups =3D cast<ExprWithCleanups>(E);
+    enterFullExpression(cleanups);
+    RunCleanupsScope Scope(*this);
+    return EmitLValue(cleanups->getSubExpr());
+  }
+
   case Expr::CXXScalarValueInitExprClass:
     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
   case Expr::CXXDefaultArgExprClass:
@@ -693,8 +705,6 @@
     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
   case Expr::ObjCIvarRefExprClass:
     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
-  case Expr::ObjCPropertyRefExprClass:
-    return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
   case Expr::StmtExprClass:
     return EmitStmtExprLValue(cast<StmtExpr>(E));
   case Expr::UnaryOperatorClass:
@@ -726,16 +736,188 @@
   case Expr::CXXConstCastExprClass:
   case Expr::ObjCBridgedCastExprClass:
     return EmitCastLValue(cast<CastExpr>(E));
-     =20
+
   case Expr::MaterializeTemporaryExprClass:
     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
   }
 }
=20
+/// Given an object of the given canonical type, can we safely copy a
+/// value out of it based on its initializer?
+static bool isConstantEmittableObjectType(QualType type) {
+  assert(type.isCanonical());
+  assert(!type->isReferenceType());
+
+  // Must be const-qualified but non-volatile.
+  Qualifiers qs =3D type.getLocalQualifiers();
+  if (!qs.hasConst() || qs.hasVolatile()) return false;
+
+  // Otherwise, all object types satisfy this except C++ classes with
+  // mutable subobjects or non-trivial copy/destroy behavior.
+  if (const RecordType *RT =3D dyn_cast<RecordType>(type))
+    if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(RT->getDecl()))
+      if (RD->hasMutableFields() || !RD->isTrivial())
+        return false;
+
+  return true;
+}
+
+/// Can we constant-emit a load of a reference to a variable of the
+/// given type?  This is different from predicates like
+/// Decl::isUsableInConstantExpressions because we do want it to apply
+/// in situations that don't necessarily satisfy the language's rules
+/// for this (e.g. C++'s ODR-use rules).  For example, we want to able
+/// to do this with const float variables even if those variables
+/// aren't marked 'constexpr'.
+enum ConstantEmissionKind {
+  CEK_None,
+  CEK_AsReferenceOnly,
+  CEK_AsValueOrReference,
+  CEK_AsValueOnly
+};
+static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type)=
 {
+  type =3D type.getCanonicalType();
+  if (const ReferenceType *ref =3D dyn_cast<ReferenceType>(type)) {
+    if (isConstantEmittableObjectType(ref->getPointeeType()))
+      return CEK_AsValueOrReference;
+    return CEK_AsReferenceOnly;
+  }
+  if (isConstantEmittableObjectType(type))
+    return CEK_AsValueOnly;
+  return CEK_None;
+}
+
+/// Try to emit a reference to the given value without producing it as
+/// an l-value.  This is actually more than an optimization: we can't
+/// produce an l-value for variables that we never actually captured
+/// in a block or lambda, which means const int variables or constexpr
+/// literals or similar.
+CodeGenFunction::ConstantEmission
+CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
+  ValueDecl *value =3D refExpr->getDecl();
+
+  // The value needs to be an enum constant or a constant variable.
+  ConstantEmissionKind CEK;
+  if (isa<ParmVarDecl>(value)) {
+    CEK =3D CEK_None;
+  } else if (VarDecl *var =3D dyn_cast<VarDecl>(value)) {
+    CEK =3D checkVarTypeForConstantEmission(var->getType());
+  } else if (isa<EnumConstantDecl>(value)) {
+    CEK =3D CEK_AsValueOnly;
+  } else {
+    CEK =3D CEK_None;
+  }
+  if (CEK =3D=3D CEK_None) return ConstantEmission();
+
+  Expr::EvalResult result;
+  bool resultIsReference;
+  QualType resultType;
+
+  // It's best to evaluate all the way as an r-value if that's permitted.
+  if (CEK !=3D CEK_AsReferenceOnly &&
+      refExpr->EvaluateAsRValue(result, getContext())) {
+    resultIsReference =3D false;
+    resultType =3D refExpr->getType();
+
+  // Otherwise, try to evaluate as an l-value.
+  } else if (CEK !=3D CEK_AsValueOnly &&
+             refExpr->EvaluateAsLValue(result, getContext())) {
+    resultIsReference =3D true;
+    resultType =3D value->getType();
+
+  // Failure.
+  } else {
+    return ConstantEmission();
+  }
+
+  // In any case, if the initializer has side-effects, abandon ship.
+  if (result.HasSideEffects)
+    return ConstantEmission();
+
+  // Emit as a constant.
+  llvm::Constant *C =3D CGM.EmitConstantValue(result.Val, resultType, this=
);
+
+  // Make sure we emit a debug reference to the global variable.
+  // This should probably fire even for=20
+  if (isa<VarDecl>(value)) {
+    if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
+      EmitDeclRefExprDbgValue(refExpr, C);
+  } else {
+    assert(isa<EnumConstantDecl>(value));
+    EmitDeclRefExprDbgValue(refExpr, C);
+  }
+
+  // If we emitted a reference constant, we need to dereference that.
+  if (resultIsReference)
+    return ConstantEmission::forReference(C);
+
+  return ConstantEmission::forValue(C);
+}
+
 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
-                          lvalue.getAlignment(), lvalue.getType(),
-                          lvalue.getTBAAInfo());
+                          lvalue.getAlignment().getQuantity(),
+                          lvalue.getType(), lvalue.getTBAAInfo());
+}
+
+static bool hasBooleanRepresentation(QualType Ty) {
+  if (Ty->isBooleanType())
+    return true;
+
+  if (const EnumType *ET =3D Ty->getAs<EnumType>())
+    return ET->getDecl()->getIntegerType()->isBooleanType();
+
+  if (const AtomicType *AT =3D Ty->getAs<AtomicType>())
+    return hasBooleanRepresentation(AT->getValueType());
+
+  return false;
+}
+
+llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
+  const EnumType *ET =3D Ty->getAs<EnumType>();
+  bool IsRegularCPlusPlusEnum =3D (getLangOpts().CPlusPlus && ET &&
+                                 CGM.getCodeGenOpts().StrictEnums &&
+                                 !ET->getDecl()->isFixed());
+  bool IsBool =3D hasBooleanRepresentation(Ty);
+  llvm::Type *LTy;
+  if (!IsBool && !IsRegularCPlusPlusEnum)
+    return NULL;
+
+  llvm::APInt Min;
+  llvm::APInt End;
+  if (IsBool) {
+    Min =3D llvm::APInt(8, 0);
+    End =3D llvm::APInt(8, 2);
+    LTy =3D Int8Ty;
+  } else {
+    const EnumDecl *ED =3D ET->getDecl();
+    LTy =3D ConvertTypeForMem(ED->getIntegerType());
+    unsigned Bitwidth =3D LTy->getScalarSizeInBits();
+    unsigned NumNegativeBits =3D ED->getNumNegativeBits();
+    unsigned NumPositiveBits =3D ED->getNumPositiveBits();
+
+    if (NumNegativeBits) {
+      unsigned NumBits =3D std::max(NumNegativeBits, NumPositiveBits + 1);
+      assert(NumBits <=3D Bitwidth);
+      End =3D llvm::APInt(Bitwidth, 1) << (NumBits - 1);
+      Min =3D -End;
+    } else {
+      assert(NumPositiveBits <=3D Bitwidth);
+      End =3D llvm::APInt(Bitwidth, 1) << NumPositiveBits;
+      Min =3D llvm::APInt(Bitwidth, 0);
+    }
+  }
+
+  if (End =3D=3D Min)
+    return NULL;
+
+  llvm::Value *LowAndHigh[2];
+  LowAndHigh[0] =3D llvm::ConstantInt::get(LTy, Min);
+  LowAndHigh[1] =3D llvm::ConstantInt::get(LTy, End);
+
+  llvm::LLVMContext &C =3D getLLVMContext();
+  llvm::MDNode *Range =3D llvm::MDNode::get(C, LowAndHigh);
+  return Range;
 }
=20
 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Vol=
atile,
@@ -748,19 +930,20 @@
     Load->setAlignment(Alignment);
   if (TBAAInfo)
     CGM.DecorateInstruction(Load, TBAAInfo);
+  // If this is an atomic type, all normal reads must be atomic
+  if (Ty->isAtomicType())
+    Load->setAtomic(llvm::SequentiallyConsistent);
+
+  if (CGM.getCodeGenOpts().OptimizationLevel > 0)
+    if (llvm::MDNode *RangeInfo =3D getRangeForLoadFromType(Ty))
+      Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
=20
   return EmitFromMemory(Load, Ty);
 }
=20
-static bool isBooleanUnderlyingType(QualType Ty) {
-  if (const EnumType *ET =3D dyn_cast<EnumType>(Ty))
-    return ET->getDecl()->getIntegerType()->isBooleanType();
-  return false;
-}
-
 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty=
) {
   // Bool has a different representation in memory than in registers.
-  if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
+  if (hasBooleanRepresentation(Ty)) {
     // This should really always be an i1, but sometimes it's already
     // an i8, and it's awkward to track those cases down.
     if (Value->getType()->isIntegerTy(1))
@@ -773,7 +956,7 @@
=20
 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType =
Ty) {
   // Bool has a different representation in memory than in registers.
-  if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
+  if (hasBooleanRepresentation(Ty)) {
     assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8"=
);
     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
   }
@@ -784,7 +967,8 @@
 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *A=
ddr,
                                         bool Volatile, unsigned Alignment,
                                         QualType Ty,
-                                        llvm::MDNode *TBAAInfo) {
+                                        llvm::MDNode *TBAAInfo,
+                                        bool isInit) {
   Value =3D EmitToMemory(Value, Ty);
  =20
   llvm::StoreInst *Store =3D Builder.CreateStore(Value, Addr, Volatile);
@@ -792,12 +976,15 @@
     Store->setAlignment(Alignment);
   if (TBAAInfo)
     CGM.DecorateInstruction(Store, TBAAInfo);
+  if (!isInit && Ty->isAtomicType())
+    Store->setAtomic(llvm::SequentiallyConsistent);
 }
=20
-void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue)=
 {
+void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
+    bool isInit) {
   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
-                    lvalue.getAlignment(), lvalue.getType(),
-                    lvalue.getTBAAInfo());
+                    lvalue.getAlignment().getQuantity(), lvalue.getType(),
+                    lvalue.getTBAAInfo(), isInit);
 }
=20
 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,=
 this
@@ -821,9 +1008,10 @@
   }
=20
   if (LV.isVectorElt()) {
-    llvm::Value *Vec =3D Builder.CreateLoad(LV.getVectorAddr(),
-                                          LV.isVolatileQualified());
-    return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
+    llvm::LoadInst *Load =3D Builder.CreateLoad(LV.getVectorAddr(),
+                                              LV.isVolatileQualified());
+    Load->setAlignment(LV.getAlignment().getQuantity());
+    return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(=
),
                                                     "vecext"));
   }
=20
@@ -832,11 +1020,8 @@
   if (LV.isExtVectorElt())
     return EmitLoadOfExtVectorElementLValue(LV);
=20
-  if (LV.isBitField())
-    return EmitLoadOfBitfieldLValue(LV);
-
-  assert(LV.isPropertyRef() && "Unknown LValue type!");
-  return EmitLoadOfPropertyRefLValue(LV);
+  assert(LV.isBitField() && "Unknown LValue type!");
+  return EmitLoadOfBitfieldLValue(LV);
 }
=20
 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
@@ -867,8 +1052,7 @@
     }
=20
     // Cast to the access type.
-    llvm::Type *PTy =3D llvm::Type::getIntNPtrTy(getLLVMContext(),
-                                                     AI.AccessWidth,
+    llvm::Type *PTy =3D llvm::Type::getIntNPtrTy(getLLVMContext(), AI.Acce=
ssWidth,
                        CGM.getContext().getTargetAddressSpace(LV.getType()=
));
     Ptr =3D Builder.CreateBitCast(Ptr, PTy);
=20
@@ -914,8 +1098,10 @@
 // If this is a reference to a subset of the elements of a vector, create =
an
 // appropriate shufflevector.
 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
-  llvm::Value *Vec =3D Builder.CreateLoad(LV.getExtVectorAddr(),
-                                        LV.isVolatileQualified());
+  llvm::LoadInst *Load =3D Builder.CreateLoad(LV.getExtVectorAddr(),
+                                            LV.isVolatileQualified());
+  Load->setAlignment(LV.getAlignment().getQuantity());
+  llvm::Value *Vec =3D Load;
=20
   const llvm::Constant *Elts =3D LV.getExtVectorElts();
=20
@@ -932,10 +1118,8 @@
   unsigned NumResultElts =3D ExprVT->getNumElements();
=20
   SmallVector<llvm::Constant*, 4> Mask;
-  for (unsigned i =3D 0; i !=3D NumResultElts; ++i) {
-    unsigned InIdx =3D getAccessedFieldNo(i, Elts);
-    Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
-  }
+  for (unsigned i =3D 0; i !=3D NumResultElts; ++i)
+    Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
=20
   llvm::Value *MaskV =3D llvm::ConstantVector::get(Mask);
   Vec =3D Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getT=
ype()),
@@ -948,15 +1132,19 @@
 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
 /// lvalue, where both are guaranteed to the have the same type, and that =
type
 /// is 'Ty'.
-void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst) {
+void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool =
isInit) {
   if (!Dst.isSimple()) {
     if (Dst.isVectorElt()) {
       // Read/modify/write the vector, inserting the new element.
-      llvm::Value *Vec =3D Builder.CreateLoad(Dst.getVectorAddr(),
-                                            Dst.isVolatileQualified());
+      llvm::LoadInst *Load =3D Builder.CreateLoad(Dst.getVectorAddr(),
+                                                Dst.isVolatileQualified());
+      Load->setAlignment(Dst.getAlignment().getQuantity());
+      llvm::Value *Vec =3D Load;
       Vec =3D Builder.CreateInsertElement(Vec, Src.getScalarVal(),
                                         Dst.getVectorIdx(), "vecins");
-      Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified=
());
+      llvm::StoreInst *Store =3D Builder.CreateStore(Vec, Dst.getVectorAdd=
r(),
+                                                   Dst.isVolatileQualified=
());
+      Store->setAlignment(Dst.getAlignment().getQuantity());
       return;
     }
=20
@@ -965,11 +1153,8 @@
     if (Dst.isExtVectorElt())
       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
=20
-    if (Dst.isBitField())
-      return EmitStoreThroughBitfieldLValue(Src, Dst);
-
-    assert(Dst.isPropertyRef() && "Unknown LValue type");
-    return EmitStoreThroughPropertyRefLValue(Src, Dst);
+    assert(Dst.isBitField() && "Unknown LValue type");
+    return EmitStoreThroughBitfieldLValue(Src, Dst);
   }
=20
   // There's special magic for assigning into an ARC-qualified l-value.
@@ -1031,7 +1216,7 @@
   }
=20
   assert(Src.isScalar() && "Can't emit an agg store with this method");
-  EmitStoreOfScalar(Src.getScalarVal(), Dst);
+  EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
 }
=20
 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Ds=
t,
@@ -1045,7 +1230,7 @@
   // Get the source value, truncated to the width of the bit-field.
   llvm::Value *SrcVal =3D Src.getScalarVal();
=20
-  if (Dst.getType()->isBooleanType())
+  if (hasBooleanRepresentation(Dst.getType()))
     SrcVal =3D Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=3D*/false);
=20
   SrcVal =3D Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeI=
nBits,
@@ -1143,8 +1328,10 @@
                                                                LValue Dst)=
 {
   // This access turns into a read/modify/write of the vector.  Load the i=
nput
   // value now.
-  llvm::Value *Vec =3D Builder.CreateLoad(Dst.getExtVectorAddr(),
-                                        Dst.isVolatileQualified());
+  llvm::LoadInst *Load =3D Builder.CreateLoad(Dst.getExtVectorAddr(),
+                                            Dst.isVolatileQualified());
+  Load->setAlignment(Dst.getAlignment().getQuantity());
+  llvm::Value *Vec =3D Load;
   const llvm::Constant *Elts =3D Dst.getExtVectorElts();
=20
   llvm::Value *SrcVal =3D Src.getScalarVal();
@@ -1158,10 +1345,8 @@
       // elements and restore the vector mask since it is on the side it w=
ill be
       // stored.
       SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
-      for (unsigned i =3D 0; i !=3D NumSrcElts; ++i) {
-        unsigned InIdx =3D getAccessedFieldNo(i, Elts);
-        Mask[InIdx] =3D llvm::ConstantInt::get(Int32Ty, i);
-      }
+      for (unsigned i =3D 0; i !=3D NumSrcElts; ++i)
+        Mask[getAccessedFieldNo(i, Elts)] =3D Builder.getInt32(i);
=20
       llvm::Value *MaskV =3D llvm::ConstantVector::get(Mask);
       Vec =3D Builder.CreateShuffleVector(SrcVal,
@@ -1173,11 +1358,9 @@
       // FIXME: since we're shuffling with undef, can we just use the indi=
ces
       //        into that?  This could be simpler.
       SmallVector<llvm::Constant*, 4> ExtMask;
-      unsigned i;
-      for (i =3D 0; i !=3D NumSrcElts; ++i)
-        ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
-      for (; i !=3D NumDstElts; ++i)
-        ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
+      for (unsigned i =3D 0; i !=3D NumSrcElts; ++i)
+        ExtMask.push_back(Builder.getInt32(i));
+      ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
       llvm::Value *ExtMaskV =3D llvm::ConstantVector::get(ExtMask);
       llvm::Value *ExtSrcVal =3D
         Builder.CreateShuffleVector(SrcVal,
@@ -1186,13 +1369,11 @@
       // build identity
       SmallVector<llvm::Constant*, 4> Mask;
       for (unsigned i =3D 0; i !=3D NumDstElts; ++i)
-        Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
+        Mask.push_back(Builder.getInt32(i));
=20
       // modify when what gets shuffled in
-      for (unsigned i =3D 0; i !=3D NumSrcElts; ++i) {
-        unsigned Idx =3D getAccessedFieldNo(i, Elts);
-        Mask[Idx] =3D llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
-      }
+      for (unsigned i =3D 0; i !=3D NumSrcElts; ++i)
+        Mask[getAccessedFieldNo(i, Elts)] =3D Builder.getInt32(i+NumDstElt=
s);
       llvm::Value *MaskV =3D llvm::ConstantVector::get(Mask);
       Vec =3D Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
     } else {
@@ -1206,7 +1387,9 @@
     Vec =3D Builder.CreateInsertElement(Vec, SrcVal, Elt);
   }
=20
-  Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified=
());
+  llvm::StoreInst *Store =3D Builder.CreateStore(Vec, Dst.getExtVectorAddr=
(),
+                                               Dst.isVolatileQualified());
+  Store->setAlignment(Dst.getAlignment().getQuantity());
 }
=20
 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
@@ -1215,7 +1398,7 @@
 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
                                  LValue &LV,
                                  bool IsMemberAccess=3Dfalse) {
-  if (Ctx.getLangOptions().getGC() =3D=3D LangOptions::NonGC)
+  if (Ctx.getLangOpts().getGC() =3D=3D LangOptions::NonGC)
     return;
  =20
   if (isa<ObjCIvarRefExpr>(E)) {
@@ -1323,14 +1506,19 @@
          "Var decl must have external storage or be a file var decl!");
=20
   llvm::Value *V =3D CGF.CGM.GetAddrOfGlobalVar(VD);
-  if (VD->getType()->isReferenceType())
-    V =3D CGF.Builder.CreateLoad(V);
- =20
-  V =3D EmitBitCastOfLValueToProperType(CGF, V,
-                                CGF.getTypes().ConvertTypeForMem(E->getTyp=
e()));
-
-  unsigned Alignment =3D CGF.getContext().getDeclAlign(VD).getQuantity();
-  LValue LV =3D CGF.MakeAddrLValue(V, E->getType(), Alignment);
+  llvm::Type *RealVarTy =3D CGF.getTypes().ConvertTypeForMem(VD->getType()=
);
+  V =3D EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
+  CharUnits Alignment =3D CGF.getContext().getDeclAlign(VD);
+  QualType T =3D E->getType();
+  LValue LV;
+  if (VD->getType()->isReferenceType()) {
+    llvm::LoadInst *LI =3D CGF.Builder.CreateLoad(V);
+    LI->setAlignment(Alignment.getQuantity());
+    V =3D LI;
+    LV =3D CGF.MakeNaturalAlignAddrLValue(V, T);
+  } else {
+    LV =3D CGF.MakeAddrLValue(V, E->getType(), Alignment);
+  }
   setObjCGCLValueClass(CGF.getContext(), E, LV);
   return LV;
 }
@@ -1350,13 +1538,21 @@
       V =3D CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
     }
   }
-  unsigned Alignment =3D CGF.getContext().getDeclAlign(FD).getQuantity();
+  CharUnits Alignment =3D CGF.getContext().getDeclAlign(FD);
   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
 }
=20
 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
   const NamedDecl *ND =3D E->getDecl();
-  unsigned Alignment =3D getContext().getDeclAlign(ND).getQuantity();
+  CharUnits Alignment =3D getContext().getDeclAlign(ND);
+  QualType T =3D E->getType();
+
+  // FIXME: We should be able to assert this for FunctionDecls as well!
+  // FIXME: We should be able to assert this for all DeclRefExprs, not just
+  // those with a valid source location.
+  assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
+          !E->getLocation().isValid()) &&
+         "Should not use decl without marking it used!");
=20
   if (ND->hasAttr<WeakRefAttr>()) {
     const ValueDecl *VD =3D cast<ValueDecl>(ND);
@@ -1365,30 +1561,46 @@
   }
=20
   if (const VarDecl *VD =3D dyn_cast<VarDecl>(ND)) {
-   =20
     // Check if this is a global variable.
     if (VD->hasExternalStorage() || VD->isFileVarDecl())=20
       return EmitGlobalVarDeclLValue(*this, E, VD);
=20
+    bool isBlockVariable =3D VD->hasAttr<BlocksAttr>();
+
     bool NonGCable =3D VD->hasLocalStorage() &&
                      !VD->getType()->isReferenceType() &&
-                     !VD->hasAttr<BlocksAttr>();
+                     !isBlockVariable;
=20
     llvm::Value *V =3D LocalDeclMap[VD];
     if (!V && VD->isStaticLocal())=20
       V =3D CGM.getStaticLocalDeclAddress(VD);
+
+    // Use special handling for lambdas.
+    if (!V) {
+      if (FieldDecl *FD =3D LambdaCaptureFields.lookup(VD))
+        return EmitLValueForField(CXXABIThisValue, FD, 0);
+
+      assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
+      CharUnits alignment =3D getContext().getDeclAlign(VD);
+      return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
+                            E->getType(), alignment);
+    }
+
     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
=20
-    if (VD->hasAttr<BlocksAttr>())
+    if (isBlockVariable)
       V =3D BuildBlockByrefAddress(V, VD);
-   =20
-    if (VD->getType()->isReferenceType())
-      V =3D Builder.CreateLoad(V);
-
-    V =3D EmitBitCastOfLValueToProperType(*this, V,
-                                    getTypes().ConvertTypeForMem(E->getTyp=
e()));
-
-    LValue LV =3D MakeAddrLValue(V, E->getType(), Alignment);
+
+    LValue LV;
+    if (VD->getType()->isReferenceType()) {
+      llvm::LoadInst *LI =3D Builder.CreateLoad(V);
+      LI->setAlignment(Alignment.getQuantity());
+      V =3D LI;
+      LV =3D MakeNaturalAlignAddrLValue(V, T);
+    } else {
+      LV =3D MakeAddrLValue(V, T, Alignment);
+    }
+
     if (NonGCable) {
       LV.getQuals().removeObjCGCAttr();
       LV.setNonGC(true);
@@ -1401,16 +1613,6 @@
     return EmitFunctionDeclLValue(*this, E, fn);
=20
   llvm_unreachable("Unhandled DeclRefExpr");
- =20
-  // an invalid LValue, but the assert will
-  // ensure that this point is never reached.
-  return LValue();
-}
-
-LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
-  unsigned Alignment =3D
-    getContext().getDeclAlign(E->getDecl()).getQuantity();
-  return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment);
 }
=20
 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
@@ -1425,15 +1627,15 @@
     QualType T =3D E->getSubExpr()->getType()->getPointeeType();
     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal typ=
e");
=20
-    LValue LV =3D MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
+    LValue LV =3D MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr(=
)), T);
     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
=20
     // We should not generate __weak write barrier on indirect reference
     // of a pointer to object; as in void foo (__weak id *param); *param =
=3D 0;
     // But, we continue to generate __strong write barrier on indirect wri=
te
     // into a pointer to object.
-    if (getContext().getLangOptions().ObjC1 &&
-        getContext().getLangOptions().getGC() !=3D LangOptions::NonGC &&
+    if (getContext().getLangOpts().ObjC1 &&
+        getContext().getLangOpts().getGC() !=3D LangOptions::NonGC &&
         LV.isObjCWeak())
       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
     return LV;
@@ -1444,9 +1646,10 @@
     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
     llvm::Value *Addr =3D LV.getAddress();
=20
-    // real and imag are valid on scalars.  This is a faster way of
-    // testing that.
-    if (!cast<llvm::PointerType>(Addr->getType())
+    // __real is valid on scalars.  This is a faster way of testing that.
+    // __imag can only produce an rvalue on scalars.
+    if (E->getOpcode() =3D=3D UO_Real &&
+        !cast<llvm::PointerType>(Addr->getType())
            ->getElementType()->isStructTy()) {
       assert(E->getSubExpr()->getType()->isArithmeticType());
       return LV;
@@ -1588,7 +1791,7 @@
     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
     Idx =3D Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
-                                 E->getBase()->getType());
+                                 E->getBase()->getType(), LHS.getAlignment=
());
   }
=20
   // Extend or truncate the index type to 32 or 64-bits.
@@ -1617,7 +1820,7 @@
   // We know that the pointer points to a type of the correct size, unless=
 the
   // size is a VLA or Objective-C interface.
   llvm::Value *Address =3D 0;
-  unsigned ArrayAlignment =3D 0;
+  CharUnits ArrayAlignment;
   if (const VariableArrayType *vla =3D
         getContext().getAsVariableArrayType(E->getType())) {
     // The base must be a pointer, which is not an aggregate.  Emit
@@ -1632,7 +1835,7 @@
     // GEP indexes are signed, and scaling an index isn't permitted to
     // signed-overflow, so we use the same semantics for our explicit
     // multiply.  We suppress this if overflow is not undefined behavior.
-    if (getLangOptions().isSignedOverflowDefined()) {
+    if (getLangOpts().isSignedOverflowDefined()) {
       Idx =3D Builder.CreateMul(Idx, numElements);
       Address =3D Builder.CreateGEP(Address, Idx, "arrayidx");
     } else {
@@ -1667,14 +1870,14 @@
     // Propagate the alignment from the array itself to the result.
     ArrayAlignment =3D ArrayLV.getAlignment();
=20
-    if (getContext().getLangOptions().isSignedOverflowDefined())
+    if (getContext().getLangOpts().isSignedOverflowDefined())
       Address =3D Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
     else
       Address =3D Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
   } else {
     // The base must be a pointer, which is not an aggregate.  Emit it.
     llvm::Value *Base =3D EmitScalarExpr(E->getBase());
-    if (getContext().getLangOptions().isSignedOverflowDefined())
+    if (getContext().getLangOpts().isSignedOverflowDefined())
       Address =3D Builder.CreateGEP(Base, Idx, "arrayidx");
     else
       Address =3D Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
@@ -1684,17 +1887,21 @@
   assert(!T.isNull() &&
          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
=20
+ =20
   // Limit the alignment to that of the result type.
-  if (ArrayAlignment) {
-    unsigned Align =3D getContext().getTypeAlignInChars(T).getQuantity();
+  LValue LV;
+  if (!ArrayAlignment.isZero()) {
+    CharUnits Align =3D getContext().getTypeAlignInChars(T);
     ArrayAlignment =3D std::min(Align, ArrayAlignment);
+    LV =3D MakeAddrLValue(Address, T, ArrayAlignment);
+  } else {
+    LV =3D MakeNaturalAlignAddrLValue(Address, T);
   }
=20
-  LValue LV =3D MakeAddrLValue(Address, T, ArrayAlignment);
   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
=20
-  if (getContext().getLangOptions().ObjC1 &&
-      getContext().getLangOptions().getGC() !=3D LangOptions::NonGC) {
+  if (getContext().getLangOpts().ObjC1 &&
+      getContext().getLangOpts().getGC() !=3D LangOptions::NonGC) {
     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
     setObjCGCLValueClass(getContext(), E, LV);
   }
@@ -1702,13 +1909,11 @@
 }
=20
 static
-llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
+llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
                                        SmallVector<unsigned, 4> &Elts) {
   SmallVector<llvm::Constant*, 4> CElts;
-
-  llvm::Type *Int32Ty =3D llvm::Type::getInt32Ty(VMContext);
   for (unsigned i =3D 0, e =3D Elts.size(); i !=3D e; ++i)
-    CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
+    CElts.push_back(Builder.getInt32(Elts[i]));
=20
   return llvm::ConstantVector::get(CElts);
 }
@@ -1751,22 +1956,20 @@
   E->getEncodedElementAccess(Indices);
=20
   if (Base.isSimple()) {
-    llvm::Constant *CV =3D GenerateConstantVector(getLLVMContext(), Indice=
s);
-    return LValue::MakeExtVectorElt(Base.getAddress(), CV, type);
+    llvm::Constant *CV =3D GenerateConstantVector(Builder, Indices);
+    return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
+                                    Base.getAlignment());
   }
   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here=
!");
=20
   llvm::Constant *BaseElts =3D Base.getExtVectorElts();
   SmallVector<llvm::Constant *, 4> CElts;
=20
-  for (unsigned i =3D 0, e =3D Indices.size(); i !=3D e; ++i) {
-    if (isa<llvm::ConstantAggregateZero>(BaseElts))
-      CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
-    else
-      CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i]=
)));
-  }
+  for (unsigned i =3D 0, e =3D Indices.size(); i !=3D e; ++i)
+    CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
   llvm::Constant *CV =3D llvm::ConstantVector::get(CElts);
-  return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type);
+  return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
+                                  Base.getAlignment());
 }
=20
 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
@@ -1847,6 +2050,7 @@
=20
   const RecordDecl *rec =3D field->getParent();
   QualType type =3D field->getType();
+  CharUnits alignment =3D getContext().getDeclAlign(field);
=20
   bool mayAlias =3D rec->hasAttr<MayAliasAttr>();
=20
@@ -1863,6 +2067,7 @@
     if (const ReferenceType *refType =3D type->getAs<ReferenceType>()) {
       llvm::LoadInst *load =3D Builder.CreateLoad(addr, "ref");
       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
+      load->setAlignment(alignment.getQuantity());
=20
       if (CGM.shouldUseTBAA()) {
         llvm::MDNode *tbaa;
@@ -1876,6 +2081,10 @@
       addr =3D load;
       mayAlias =3D false;
       type =3D refType->getPointeeType();
+      if (type->isIncompleteType())
+        alignment =3D CharUnits();
+      else
+        alignment =3D getContext().getTypeAlignInChars(type);
       cvr =3D 0; // qualifiers don't recursively apply to referencee
     }
   }
@@ -1891,7 +2100,6 @@
   if (field->hasAttr<AnnotateAttr>())
     addr =3D EmitFieldAnnotations(field, addr);
=20
-  unsigned alignment =3D getContext().getDeclAlign(field).getQuantity();
   LValue LV =3D MakeAddrLValue(addr, type, alignment);
   LV.getQuals().addCVRQualifiers(cvr);
=20
@@ -1932,11 +2140,16 @@
   unsigned AS =3D cast<llvm::PointerType>(V->getType())->getAddressSpace();
   V =3D Builder.CreateBitCast(V, llvmType->getPointerTo(AS));
  =20
-  unsigned Alignment =3D getContext().getDeclAlign(Field).getQuantity();
+  CharUnits Alignment =3D getContext().getDeclAlign(Field);
   return MakeAddrLValue(V, FieldType, Alignment);
 }
=20
 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExp=
r *E){
+  if (E->isFileScope()) {
+    llvm::Value *GlobalPtr =3D CGM.GetAddrOfConstantCompoundLiteral(E);
+    return MakeAddrLValue(GlobalPtr, E->getType());
+  }
+
   llvm::Value *DeclPtr =3D CreateMemTemp(E->getType(), ".compoundliteral");
   const Expr *InitExpr =3D E->getInitializer();
   LValue Result =3D MakeAddrLValue(DeclPtr, E->getType());
@@ -1957,6 +2170,8 @@
     return EmitAggExprToLValue(expr);
   }
=20
+  OpaqueValueMapping binding(*this, expr);
+
   const Expr *condExpr =3D expr->getCond();
   bool CondExprBool;
   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
@@ -1967,8 +2182,6 @@
       return EmitLValue(live);
   }
=20
-  OpaqueValueMapping binding(*this, expr);
-
   llvm::BasicBlock *lhsBlock =3D createBasicBlock("cond.true");
   llvm::BasicBlock *rhsBlock =3D createBasicBlock("cond.false");
   llvm::BasicBlock *contBlock =3D createBasicBlock("cond.end");
@@ -2020,21 +2233,11 @@
=20
   case CK_Dependent:
     llvm_unreachable("dependent cast kind in IR gen!");
-
-  case CK_GetObjCProperty: {
-    LValue LV =3D EmitLValue(E->getSubExpr());
-    assert(LV.isPropertyRef());
-    RValue RV =3D EmitLoadOfPropertyRefLValue(LV);
-
-    // Property is an aggregate r-value.
-    if (RV.isAggregate()) {
-      return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
-    }
-
-    // Implicit property returns an l-value.
-    assert(RV.isScalar());
-    return MakeAddrLValue(RV.getScalarVal(), E->getSubExpr()->getType());
-  }
+=20
+  // These two casts are currently treated as no-ops, although they could
+  // potentially be real operations depending on the target's ABI.
+  case CK_NonAtomicToAtomic:
+  case CK_AtomicToNonAtomic:
=20
   case CK_NoOp:
   case CK_LValueToRValue:
@@ -2071,11 +2274,13 @@
   case CK_DerivedToBaseMemberPointer:
   case CK_BaseToDerivedMemberPointer:
   case CK_MemberPointerToBoolean:
+  case CK_ReinterpretMemberPointer:
   case CK_AnyPointerToBlockPointerCast:
   case CK_ARCProduceObject:
   case CK_ARCConsumeObject:
   case CK_ARCReclaimReturnedObject:
-  case CK_ARCExtendBlockObject: {
+  case CK_ARCExtendBlockObject:=20
+  case CK_CopyAndAutoreleaseBlockObject: {
     // These casts only produce lvalues when we're binding a reference to =
a=20
     // temporary realized from a (converted) pure rvalue. Emit the express=
ion
     // as a value, copy it into a temporary, and return an lvalue referrin=
g to
@@ -2163,7 +2368,7 @@
 }
=20
 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
-  assert(e->isGLValue() || e->getType()->isRecordType());
+  assert(OpaqueValueMappingData::shouldBindAsLValue(e));
   return getOpaqueLValueMapping(e);
 }
=20
@@ -2206,7 +2411,7 @@
   if (const CXXPseudoDestructorExpr *PseudoDtor=20
           =3D dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnorePare=
ns())) {
     QualType DestroyedType =3D PseudoDtor->getDestroyedType();
-    if (getContext().getLangOptions().ObjCAutoRefCount &&
+    if (getContext().getLangOpts().ObjCAutoRefCount &&
         DestroyedType->isObjCLifetimeType() &&
         (DestroyedType.getObjCLifetime() =3D=3D Qualifiers::OCL_Strong ||
          DestroyedType.getObjCLifetime() =3D=3D Qualifiers::OCL_Weak)) {
@@ -2342,7 +2547,14 @@
   AggValueSlot Slot =3D CreateAggTemp(E->getType(), "temp.lvalue");
   Slot.setExternallyDestructed();
   EmitAggExpr(E->getSubExpr(), Slot);
-  EmitCXXTemporary(E->getTemporary(), Slot.getAddr());
+  EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
+  return MakeAddrLValue(Slot.getAddr(), E->getType());
+}
+
+LValue
+CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
+  AggValueSlot Slot =3D CreateAggTemp(E->getType(), "temp.lvalue");
+  EmitLambdaExpr(E, Slot);
   return MakeAddrLValue(Slot.getAddr(), E->getType());
 }
=20
@@ -2427,7 +2639,8 @@
   CallArgList Args;
   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
=20
-  const CGFunctionInfo &FnInfo =3D CGM.getTypes().getFunctionInfo(Args, Fn=
Type);
+  const CGFunctionInfo &FnInfo =3D
+    CGM.getTypes().arrangeFunctionCall(Args, FnType);
=20
   // C99 6.5.2.2p6:
   //   If the expression that denotes the called function has a type
@@ -2446,11 +2659,8 @@
   // through an unprototyped function type works like a *non-variadic*
   // call.  The way we make this work is to cast to the exact type
   // of the promoted arguments.
-  if (isa<FunctionNoProtoType>(FnType) &&
-      !getTargetHooks().isNoProtoCallVariadic(FnType->getCallConv())) {
-    assert(cast<llvm::FunctionType>(Callee->getType()->getContainedType(0))
-             ->isVarArg());
-    llvm::Type *CalleeTy =3D getTypes().GetFunctionType(FnInfo, false);
+  if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) {
+    llvm::Type *CalleeTy =3D getTypes().GetFunctionType(FnInfo);
     CalleeTy =3D CalleeTy->getPointerTo();
     Callee =3D Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
   }
@@ -2481,7 +2691,17 @@
 EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
              llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
              uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
-  if (E->isCmpXChg()) {
+  llvm::AtomicRMWInst::BinOp Op =3D llvm::AtomicRMWInst::Add;
+  llvm::Instruction::BinaryOps PostOp =3D (llvm::Instruction::BinaryOps)0;
+
+  switch (E->getOp()) {
+  case AtomicExpr::AO__c11_atomic_init:
+    llvm_unreachable("Already handled!");
+
+  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
+  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
+  case AtomicExpr::AO__atomic_compare_exchange:
+  case AtomicExpr::AO__atomic_compare_exchange_n: {
     // Note that cmpxchg only supports specifying one ordering and
     // doesn't support weak cmpxchg, at least at the moment.
     llvm::LoadInst *LoadVal1 =3D CGF.Builder.CreateLoad(Val1);
@@ -2498,7 +2718,9 @@
     return;
   }
=20
-  if (E->getOp() =3D=3D AtomicExpr::Load) {
+  case AtomicExpr::AO__c11_atomic_load:
+  case AtomicExpr::AO__atomic_load_n:
+  case AtomicExpr::AO__atomic_load: {
     llvm::LoadInst *Load =3D CGF.Builder.CreateLoad(Ptr);
     Load->setAtomic(Order);
     Load->setAlignment(Size);
@@ -2508,7 +2730,9 @@
     return;
   }
=20
-  if (E->getOp() =3D=3D AtomicExpr::Store) {
+  case AtomicExpr::AO__c11_atomic_store:
+  case AtomicExpr::AO__atomic_store:
+  case AtomicExpr::AO__atomic_store_n: {
     assert(!Dest && "Store does not return a value");
     llvm::LoadInst *LoadVal1 =3D CGF.Builder.CreateLoad(Val1);
     LoadVal1->setAlignment(Align);
@@ -2519,25 +2743,74 @@
     return;
   }
=20
-  llvm::AtomicRMWInst::BinOp Op =3D llvm::AtomicRMWInst::Add;
-  switch (E->getOp()) {
-    case AtomicExpr::CmpXchgWeak:
-    case AtomicExpr::CmpXchgStrong:
-    case AtomicExpr::Store:
-    case AtomicExpr::Load:  assert(0 && "Already handled!");
-    case AtomicExpr::Add:   Op =3D llvm::AtomicRMWInst::Add;  break;
-    case AtomicExpr::Sub:   Op =3D llvm::AtomicRMWInst::Sub;  break;
-    case AtomicExpr::And:   Op =3D llvm::AtomicRMWInst::And;  break;
-    case AtomicExpr::Or:    Op =3D llvm::AtomicRMWInst::Or;   break;
-    case AtomicExpr::Xor:   Op =3D llvm::AtomicRMWInst::Xor;  break;
-    case AtomicExpr::Xchg:  Op =3D llvm::AtomicRMWInst::Xchg; break;
+  case AtomicExpr::AO__c11_atomic_exchange:
+  case AtomicExpr::AO__atomic_exchange_n:
+  case AtomicExpr::AO__atomic_exchange:
+    Op =3D llvm::AtomicRMWInst::Xchg;
+    break;
+
+  case AtomicExpr::AO__atomic_add_fetch:
+    PostOp =3D llvm::Instruction::Add;
+    // Fall through.
+  case AtomicExpr::AO__c11_atomic_fetch_add:
+  case AtomicExpr::AO__atomic_fetch_add:
+    Op =3D llvm::AtomicRMWInst::Add;
+    break;
+
+  case AtomicExpr::AO__atomic_sub_fetch:
+    PostOp =3D llvm::Instruction::Sub;
+    // Fall through.
+  case AtomicExpr::AO__c11_atomic_fetch_sub:
+  case AtomicExpr::AO__atomic_fetch_sub:
+    Op =3D llvm::AtomicRMWInst::Sub;
+    break;
+
+  case AtomicExpr::AO__atomic_and_fetch:
+    PostOp =3D llvm::Instruction::And;
+    // Fall through.
+  case AtomicExpr::AO__c11_atomic_fetch_and:
+  case AtomicExpr::AO__atomic_fetch_and:
+    Op =3D llvm::AtomicRMWInst::And;
+    break;
+
+  case AtomicExpr::AO__atomic_or_fetch:
+    PostOp =3D llvm::Instruction::Or;
+    // Fall through.
+  case AtomicExpr::AO__c11_atomic_fetch_or:
+  case AtomicExpr::AO__atomic_fetch_or:
+    Op =3D llvm::AtomicRMWInst::Or;
+    break;
+
+  case AtomicExpr::AO__atomic_xor_fetch:
+    PostOp =3D llvm::Instruction::Xor;
+    // Fall through.
+  case AtomicExpr::AO__c11_atomic_fetch_xor:
+  case AtomicExpr::AO__atomic_fetch_xor:
+    Op =3D llvm::AtomicRMWInst::Xor;
+    break;
+
+  case AtomicExpr::AO__atomic_nand_fetch:
+    PostOp =3D llvm::Instruction::And;
+    // Fall through.
+  case AtomicExpr::AO__atomic_fetch_nand:
+    Op =3D llvm::AtomicRMWInst::Nand;
+    break;
   }
+
   llvm::LoadInst *LoadVal1 =3D CGF.Builder.CreateLoad(Val1);
   LoadVal1->setAlignment(Align);
   llvm::AtomicRMWInst *RMWI =3D
       CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
   RMWI->setVolatile(E->isVolatile());
-  llvm::StoreInst *StoreDest =3D CGF.Builder.CreateStore(RMWI, Dest);
+
+  // For __atomic_*_fetch operations, perform the operation again to
+  // determine the value which was written.
+  llvm::Value *Result =3D RMWI;
+  if (PostOp)
+    Result =3D CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
+  if (E->getOp() =3D=3D AtomicExpr::AO__atomic_nand_fetch)
+    Result =3D CGF.Builder.CreateNot(Result);
+  llvm::StoreInst *StoreDest =3D CGF.Builder.CreateStore(Result, Dest);
   StoreDest->setAlignment(Align);
 }
=20
@@ -2562,7 +2835,9 @@
=20
 RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
   QualType AtomicTy =3D E->getPtr()->getType()->getPointeeType();
-  QualType MemTy =3D AtomicTy->getAs<AtomicType>()->getValueType();
+  QualType MemTy =3D AtomicTy;
+  if (const AtomicType *AT =3D AtomicTy->getAs<AtomicType>())
+    MemTy =3D AT->getValueType();
   CharUnits sizeChars =3D getContext().getTypeSizeInChars(AtomicTy);
   uint64_t Size =3D sizeChars.getQuantity();
   CharUnits alignChars =3D getContext().getTypeAlignInChars(AtomicTy);
@@ -2571,84 +2846,202 @@
       getContext().getTargetInfo().getMaxAtomicInlineWidth();
   bool UseLibcall =3D (Size !=3D Align || Size > MaxInlineWidth);
=20
+
+
   llvm::Value *Ptr, *Order, *OrderFail =3D 0, *Val1 =3D 0, *Val2 =3D 0;
   Ptr =3D EmitScalarExpr(E->getPtr());
+
+  if (E->getOp() =3D=3D AtomicExpr::AO__c11_atomic_init) {
+    assert(!Dest && "Init does not return a value");
+    if (!hasAggregateLLVMType(E->getVal1()->getType())) {
+      QualType PointeeType
+        =3D E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
+      EmitScalarInit(EmitScalarExpr(E->getVal1()),
+                     LValue::MakeAddr(Ptr, PointeeType, alignChars,
+                                      getContext()));
+    } else if (E->getType()->isAnyComplexType()) {
+      EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
+    } else {
+      AggValueSlot Slot =3D AggValueSlot::forAddr(Ptr, alignChars,
+                                        AtomicTy.getQualifiers(),
+                                        AggValueSlot::IsNotDestructed,
+                                        AggValueSlot::DoesNotNeedGCBarrier=
s,
+                                        AggValueSlot::IsNotAliased);
+      EmitAggExpr(E->getVal1(), Slot);
+    }
+    return RValue::get(0);
+  }
+
   Order =3D EmitScalarExpr(E->getOrder());
-  if (E->isCmpXChg()) {
+
+  switch (E->getOp()) {
+  case AtomicExpr::AO__c11_atomic_init:
+    llvm_unreachable("Already handled!");
+
+  case AtomicExpr::AO__c11_atomic_load:
+  case AtomicExpr::AO__atomic_load_n:
+    break;
+
+  case AtomicExpr::AO__atomic_load:
+    Dest =3D EmitScalarExpr(E->getVal1());
+    break;
+
+  case AtomicExpr::AO__atomic_store:
     Val1 =3D EmitScalarExpr(E->getVal1());
-    Val2 =3D EmitValToTemp(*this, E->getVal2());
+    break;
+
+  case AtomicExpr::AO__atomic_exchange:
+    Val1 =3D EmitScalarExpr(E->getVal1());
+    Dest =3D EmitScalarExpr(E->getVal2());
+    break;
+
+  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
+  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
+  case AtomicExpr::AO__atomic_compare_exchange_n:
+  case AtomicExpr::AO__atomic_compare_exchange:
+    Val1 =3D EmitScalarExpr(E->getVal1());
+    if (E->getOp() =3D=3D AtomicExpr::AO__atomic_compare_exchange)
+      Val2 =3D EmitScalarExpr(E->getVal2());
+    else
+      Val2 =3D EmitValToTemp(*this, E->getVal2());
     OrderFail =3D EmitScalarExpr(E->getOrderFail());
-    (void)OrderFail; // OrderFail is unused at the moment
-  } else if ((E->getOp() =3D=3D AtomicExpr::Add || E->getOp() =3D=3D Atomi=
cExpr::Sub) &&
-             MemTy->isPointerType()) {
-    // For pointers, we're required to do a bit of math: adding 1 to an in=
t*
-    // is not the same as adding 1 to a uintptr_t.
-    QualType Val1Ty =3D E->getVal1()->getType();
-    llvm::Value *Val1Scalar =3D EmitScalarExpr(E->getVal1());
-    CharUnits PointeeIncAmt =3D
-        getContext().getTypeSizeInChars(MemTy->getPointeeType());
-    Val1Scalar =3D Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt=
));
-    Val1 =3D CreateMemTemp(Val1Ty, ".atomictmp");
-    EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
-  } else if (E->getOp() !=3D AtomicExpr::Load) {
+    // Evaluate and discard the 'weak' argument.
+    if (E->getNumSubExprs() =3D=3D 6)
+      EmitScalarExpr(E->getWeak());
+    break;
+
+  case AtomicExpr::AO__c11_atomic_fetch_add:
+  case AtomicExpr::AO__c11_atomic_fetch_sub:
+    if (MemTy->isPointerType()) {
+      // For pointer arithmetic, we're required to do a bit of math:
+      // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
+      // ... but only for the C11 builtins. The GNU builtins expect the
+      // user to multiply by sizeof(T).
+      QualType Val1Ty =3D E->getVal1()->getType();
+      llvm::Value *Val1Scalar =3D EmitScalarExpr(E->getVal1());
+      CharUnits PointeeIncAmt =3D
+          getContext().getTypeSizeInChars(MemTy->getPointeeType());
+      Val1Scalar =3D Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncA=
mt));
+      Val1 =3D CreateMemTemp(Val1Ty, ".atomictmp");
+      EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
+      break;
+    }
+    // Fall through.
+  case AtomicExpr::AO__atomic_fetch_add:
+  case AtomicExpr::AO__atomic_fetch_sub:
+  case AtomicExpr::AO__atomic_add_fetch:
+  case AtomicExpr::AO__atomic_sub_fetch:
+  case AtomicExpr::AO__c11_atomic_store:
+  case AtomicExpr::AO__c11_atomic_exchange:
+  case AtomicExpr::AO__atomic_store_n:
+  case AtomicExpr::AO__atomic_exchange_n:
+  case AtomicExpr::AO__c11_atomic_fetch_and:
+  case AtomicExpr::AO__c11_atomic_fetch_or:
+  case AtomicExpr::AO__c11_atomic_fetch_xor:
+  case AtomicExpr::AO__atomic_fetch_and:
+  case AtomicExpr::AO__atomic_fetch_or:
+  case AtomicExpr::AO__atomic_fetch_xor:
+  case AtomicExpr::AO__atomic_fetch_nand:
+  case AtomicExpr::AO__atomic_and_fetch:
+  case AtomicExpr::AO__atomic_or_fetch:
+  case AtomicExpr::AO__atomic_xor_fetch:
+  case AtomicExpr::AO__atomic_nand_fetch:
     Val1 =3D EmitValToTemp(*this, E->getVal1());
+    break;
   }
=20
-  if (E->getOp() !=3D AtomicExpr::Store && !Dest)
+  if (!E->getType()->isVoidType() && !Dest)
     Dest =3D CreateMemTemp(E->getType(), ".atomicdst");
=20
+  // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrar=
y .
   if (UseLibcall) {
-    // FIXME: Finalize what the libcalls are actually supposed to look lik=
e.
-    // See also http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
-    return EmitUnsupportedRValue(E, "atomic library call");
-  }
+
+    llvm::SmallVector<QualType, 5> Params;
+    CallArgList Args;
+    // Size is always the first parameter
+    Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
+             getContext().getSizeType());
+    // Atomic address is always the second parameter
+    Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
+             getContext().VoidPtrTy);
+
+    const char* LibCallName;
+    QualType RetTy =3D getContext().VoidTy;
+    switch (E->getOp()) {
+    // There is only one libcall for compare an exchange, because there is=
 no
+    // optimisation benefit possible from a libcall version of a weak comp=
are
+    // and exchange.
+    // bool __atomic_compare_exchange(size_t size, void *obj, void *expect=
ed,
+    //                                void *desired, int success, int fail=
ure)
+    case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
+    case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
+    case AtomicExpr::AO__atomic_compare_exchange:
+    case AtomicExpr::AO__atomic_compare_exchange_n:
+      LibCallName =3D "__atomic_compare_exchange";
+      RetTy =3D getContext().BoolTy;
+      Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
+               getContext().VoidPtrTy);
+      Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
+               getContext().VoidPtrTy);
+      Args.add(RValue::get(Order),
+               getContext().IntTy);
+      Order =3D OrderFail;
+      break;
+    // void __atomic_exchange(size_t size, void *mem, void *val, void *ret=
urn,
+    //                        int order)
+    case AtomicExpr::AO__c11_atomic_exchange:
+    case AtomicExpr::AO__atomic_exchange_n:
+    case AtomicExpr::AO__atomic_exchange:
+      LibCallName =3D "__atomic_exchange";
+      Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
+               getContext().VoidPtrTy);
+      Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
+               getContext().VoidPtrTy);
+      break;
+    // void __atomic_store(size_t size, void *mem, void *val, int order)
+    case AtomicExpr::AO__c11_atomic_store:
+    case AtomicExpr::AO__atomic_store:
+    case AtomicExpr::AO__atomic_store_n:
+      LibCallName =3D "__atomic_store";
+      Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
+               getContext().VoidPtrTy);
+      break;
+    // void __atomic_load(size_t size, void *mem, void *return, int order)
+    case AtomicExpr::AO__c11_atomic_load:
+    case AtomicExpr::AO__atomic_load:
+    case AtomicExpr::AO__atomic_load_n:
+      LibCallName =3D "__atomic_load";
+      Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
+               getContext().VoidPtrTy);
+      break;
 #if 0
-  if (UseLibcall) {
-    const char* LibCallName;
-    switch (E->getOp()) {
-    case AtomicExpr::CmpXchgWeak:
-      LibCallName =3D "__atomic_compare_exchange_generic"; break;
-    case AtomicExpr::CmpXchgStrong:
-      LibCallName =3D "__atomic_compare_exchange_generic"; break;
+    // These are only defined for 1-16 byte integers.  It is not clear what
+    // their semantics would be on anything else...
     case AtomicExpr::Add:   LibCallName =3D "__atomic_fetch_add_generic"; =
break;
     case AtomicExpr::Sub:   LibCallName =3D "__atomic_fetch_sub_generic"; =
break;
     case AtomicExpr::And:   LibCallName =3D "__atomic_fetch_and_generic"; =
break;
     case AtomicExpr::Or:    LibCallName =3D "__atomic_fetch_or_generic"; b=
reak;
     case AtomicExpr::Xor:   LibCallName =3D "__atomic_fetch_xor_generic"; =
break;
-    case AtomicExpr::Xchg:  LibCallName =3D "__atomic_exchange_generic"; b=
reak;
-    case AtomicExpr::Store: LibCallName =3D "__atomic_store_generic"; brea=
k;
-    case AtomicExpr::Load:  LibCallName =3D "__atomic_load_generic"; break;
+#endif
+    default: return EmitUnsupportedRValue(E, "atomic library call");
     }
-    llvm::SmallVector<QualType, 4> Params;
-    CallArgList Args;
-    QualType RetTy =3D getContext().VoidTy;
-    if (E->getOp() !=3D AtomicExpr::Store && !E->isCmpXChg())
-      Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
-               getContext().VoidPtrTy);
-    Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
-             getContext().VoidPtrTy);
-    if (E->getOp() !=3D AtomicExpr::Load)
-      Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
-               getContext().VoidPtrTy);
-    if (E->isCmpXChg()) {
-      Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
-               getContext().VoidPtrTy);
-      RetTy =3D getContext().IntTy;
-    }
-    Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
-             getContext().getSizeType());
+    // order is always the last parameter
+    Args.add(RValue::get(Order),
+             getContext().IntTy);
+
     const CGFunctionInfo &FuncInfo =3D
-        CGM.getTypes().getFunctionInfo(RetTy, Args, FunctionType::ExtInfo(=
));
-    llvm::FunctionType *FTy =3D CGM.getTypes().GetFunctionType(FuncInfo, f=
alse);
+        CGM.getTypes().arrangeFunctionCall(RetTy, Args,
+            FunctionType::ExtInfo(), RequiredArgs::All);
+    llvm::FunctionType *FTy =3D CGM.getTypes().GetFunctionType(FuncInfo);
     llvm::Constant *Func =3D CGM.CreateRuntimeFunction(FTy, LibCallName);
     RValue Res =3D EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
     if (E->isCmpXChg())
       return Res;
-    if (E->getOp() =3D=3D AtomicExpr::Store)
+    if (E->getType()->isVoidType())
       return RValue::get(0);
     return ConvertTempToRValue(*this, E->getType(), Dest);
   }
-#endif
+
   llvm::Type *IPtrTy =3D
       llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
   llvm::Value *OrigDest =3D Dest;
@@ -2684,24 +3077,31 @@
     default: // invalid order
       // We should not ever get here normally, but it's hard to
       // enforce that in general.
-      break;=20
+      break;
     }
-    if (E->getOp() =3D=3D AtomicExpr::Store)
+    if (E->getType()->isVoidType())
       return RValue::get(0);
     return ConvertTempToRValue(*this, E->getType(), OrigDest);
   }
=20
   // Long case, when Order isn't obviously constant.
=20
+  bool IsStore =3D E->getOp() =3D=3D AtomicExpr::AO__c11_atomic_store ||
+                 E->getOp() =3D=3D AtomicExpr::AO__atomic_store ||
+                 E->getOp() =3D=3D AtomicExpr::AO__atomic_store_n;
+  bool IsLoad =3D E->getOp() =3D=3D AtomicExpr::AO__c11_atomic_load ||
+                E->getOp() =3D=3D AtomicExpr::AO__atomic_load ||
+                E->getOp() =3D=3D AtomicExpr::AO__atomic_load_n;
+
   // Create all the relevant BB's
   llvm::BasicBlock *MonotonicBB =3D 0, *AcquireBB =3D 0, *ReleaseBB =3D 0,
                    *AcqRelBB =3D 0, *SeqCstBB =3D 0;
   MonotonicBB =3D createBasicBlock("monotonic", CurFn);
-  if (E->getOp() !=3D AtomicExpr::Store)
+  if (!IsStore)
     AcquireBB =3D createBasicBlock("acquire", CurFn);
-  if (E->getOp() !=3D AtomicExpr::Load)
+  if (!IsLoad)
     ReleaseBB =3D createBasicBlock("release", CurFn);
-  if (E->getOp() !=3D AtomicExpr::Load && E->getOp() !=3D AtomicExpr::Stor=
e)
+  if (!IsLoad && !IsStore)
     AcqRelBB =3D createBasicBlock("acqrel", CurFn);
   SeqCstBB =3D createBasicBlock("seqcst", CurFn);
   llvm::BasicBlock *ContBB =3D createBasicBlock("atomic.continue", CurFn);
@@ -2718,7 +3118,7 @@
   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
                llvm::Monotonic);
   Builder.CreateBr(ContBB);
-  if (E->getOp() !=3D AtomicExpr::Store) {
+  if (!IsStore) {
     Builder.SetInsertPoint(AcquireBB);
     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
                  llvm::Acquire);
@@ -2726,14 +3126,14 @@
     SI->addCase(Builder.getInt32(1), AcquireBB);
     SI->addCase(Builder.getInt32(2), AcquireBB);
   }
-  if (E->getOp() !=3D AtomicExpr::Load) {
+  if (!IsLoad) {
     Builder.SetInsertPoint(ReleaseBB);
     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
                  llvm::Release);
     Builder.CreateBr(ContBB);
     SI->addCase(Builder.getInt32(3), ReleaseBB);
   }
-  if (E->getOp() !=3D AtomicExpr::Load && E->getOp() !=3D AtomicExpr::Stor=
e) {
+  if (!IsLoad && !IsStore) {
     Builder.SetInsertPoint(AcqRelBB);
     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
                  llvm::AcquireRelease);
@@ -2748,7 +3148,102 @@
=20
   // Cleanup and return
   Builder.SetInsertPoint(ContBB);
-  if (E->getOp() =3D=3D AtomicExpr::Store)
+  if (E->getType()->isVoidType())
     return RValue::get(0);
   return ConvertTempToRValue(*this, E->getType(), OrigDest);
 }
+
+void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
+  assert(Val->getType()->isFPOrFPVectorTy());
+  if (Accuracy =3D=3D 0.0 || !isa<llvm::Instruction>(Val))
+    return;
+
+  llvm::Value *ULPs =3D llvm::ConstantFP::get(Builder.getFloatTy(), Accura=
cy);
+  llvm::MDNode *Node =3D llvm::MDNode::get(getLLVMContext(), ULPs);
+
+  cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpaccura=
cy,
+                                            Node);
+}
+
+namespace {
+  struct LValueOrRValue {
+    LValue LV;
+    RValue RV;
+  };
+}
+
+static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
+                                           const PseudoObjectExpr *E,
+                                           bool forLValue,
+                                           AggValueSlot slot) {
+  llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
+
+  // Find the result expression, if any.
+  const Expr *resultExpr =3D E->getResultExpr();
+  LValueOrRValue result;
+
+  for (PseudoObjectExpr::const_semantics_iterator
+         i =3D E->semantics_begin(), e =3D E->semantics_end(); i !=3D e; +=
+i) {
+    const Expr *semantic =3D *i;
+
+    // If this semantic expression is an opaque value, bind it
+    // to the result of its source expression.
+    if (const OpaqueValueExpr *ov =3D dyn_cast<OpaqueValueExpr>(semantic))=
 {
+
+      // If this is the result expression, we may need to evaluate
+      // directly into the slot.
+      typedef CodeGenFunction::OpaqueValueMappingData OVMA;
+      OVMA opaqueData;
+      if (ov =3D=3D resultExpr && ov->isRValue() && !forLValue &&
+          CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
+          !ov->getType()->isAnyComplexType()) {
+        CGF.EmitAggExpr(ov->getSourceExpr(), slot);
+
+        LValue LV =3D CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
+        opaqueData =3D OVMA::bind(CGF, ov, LV);
+        result.RV =3D slot.asRValue();
+
+      // Otherwise, emit as normal.
+      } else {
+        opaqueData =3D OVMA::bind(CGF, ov, ov->getSourceExpr());
+
+        // If this is the result, also evaluate the result now.
+        if (ov =3D=3D resultExpr) {
+          if (forLValue)
+            result.LV =3D CGF.EmitLValue(ov);
+          else
+            result.RV =3D CGF.EmitAnyExpr(ov, slot);
+        }
+      }
+
+      opaques.push_back(opaqueData);
+
+    // Otherwise, if the expression is the result, evaluate it
+    // and remember the result.
+    } else if (semantic =3D=3D resultExpr) {
+      if (forLValue)
+        result.LV =3D CGF.EmitLValue(semantic);
+      else
+        result.RV =3D CGF.EmitAnyExpr(semantic, slot);
+
+    // Otherwise, evaluate the expression in an ignored context.
+    } else {
+      CGF.EmitIgnoredExpr(semantic);
+    }
+  }
+
+  // Unbind all the opaques now.
+  for (unsigned i =3D 0, e =3D opaques.size(); i !=3D e; ++i)
+    opaques[i].unbind(CGF);
+
+  return result;
+}
+
+RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
+                                               AggValueSlot slot) {
+  return emitPseudoObjectExpr(*this, E, false, slot).RV;
+}
+
+LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
+  return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGExprAgg.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "CGObjCRuntime.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
 #include "clang/AST/StmtVisitor.h"
 #include "llvm/Constants.h"
 #include "llvm/Function.h"
@@ -74,12 +75,17 @@
=20
   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore =3D false);
-  void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore =3D false);
+  void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore =3D false,
+                         unsigned Alignment =3D 0);
=20
   void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
=20
+  void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList=
);
+  void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
+                     QualType elementType, InitListExpr *E);
+
   AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
-    if (CGF.getLangOptions().getGC() && TypeRequiresGCollection(T))
+    if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
       return AggValueSlot::NeedsGCBarriers;
     return AggValueSlot::DoesNotNeedGCBarriers;
   }
@@ -103,7 +109,24 @@
   }
=20
   // l-values.
-  void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
+  void VisitDeclRefExpr(DeclRefExpr *E) {
+    // For aggregates, we should always be able to emit the variable
+    // as an l-value unless it's a reference.  This is due to the fact
+    // that we can't actually ever see a normal l2r conversion on an
+    // aggregate in C++, and in C there's no language standard
+    // actively preventing us from listing variables in the captures
+    // list of a block.
+    if (E->getDecl()->getType()->isReferenceType()) {
+      if (CodeGenFunction::ConstantEmission result
+            =3D CGF.tryEmitAsConstant(E)) {
+        EmitFinalDestCopy(E, result.getReferenceLValue(CGF, E));
+        return;
+      }
+    }
+
+    EmitAggLoadOfLValue(E);
+  }
+
   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
@@ -111,9 +134,6 @@
   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
     EmitAggLoadOfLValue(E);
   }
-  void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
-    EmitAggLoadOfLValue(E);
-  }
   void VisitPredefinedExpr(const PredefinedExpr *E) {
     EmitAggLoadOfLValue(E);
   }
@@ -131,7 +151,6 @@
   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
     EmitAggLoadOfLValue(E);
   }
-  void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
=20
   void VisitAbstractConditionalOperator(const AbstractConditionalOperator =
*CO);
   void VisitChooseExpr(const ChooseExpr *CE);
@@ -142,12 +161,22 @@
   }
   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
   void VisitCXXConstructExpr(const CXXConstructExpr *E);
+  void VisitLambdaExpr(LambdaExpr *E);
   void VisitExprWithCleanups(ExprWithCleanups *E);
   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
=20
+  void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
+    if (E->isGLValue()) {
+      LValue LV =3D CGF.EmitPseudoObjectLValue(E);
+      return EmitFinalDestCopy(E, LV);
+    }
+
+    CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
+  }
+
   void VisitVAArgExpr(VAArgExpr *E);
=20
   void EmitInitializationToLValue(Expr *E, LValue Address);
@@ -213,7 +242,8 @@
 }
=20
 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
-void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ign=
ore) {
+void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ign=
ore,
+                                       unsigned Alignment) {
   assert(Src.isAggregate() && "value must be aggregate value!");
=20
   // If Dest is ignored, then we're evaluating an aggregate expression
@@ -224,7 +254,7 @@
   // volatile.
   if (Dest.isIgnored()) {
     if (!Src.isVolatileQualified() ||
-        CGF.CGM.getLangOptions().CPlusPlus ||
+        CGF.CGM.getLangOpts().CPlusPlus ||
         (IgnoreResult && Ignore))
       return;
=20
@@ -248,16 +278,239 @@
   // from the source as well, as we can't eliminate it if either operand
   // is volatile, unless copy has volatile for both source and destination=
..
   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType=
(),
-                        Dest.isVolatile()|Src.isVolatileQualified());
+                        Dest.isVolatile()|Src.isVolatileQualified(),
+                        Alignment);
 }
=20
 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ign=
ore) {
   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
=20
-  EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
-                                            Src.isVolatileQualified()),
-                    Ignore);
+  CharUnits Alignment =3D std::min(Src.getAlignment(), Dest.getAlignment()=
);
+  EmitFinalDestCopy(E, Src.asAggregateRValue(), Ignore, Alignment.getQuant=
ity());
+}
+
+static QualType GetStdInitializerListElementType(QualType T) {
+  // Just assume that this is really std::initializer_list.
+  ClassTemplateSpecializationDecl *specialization =3D
+      cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDe=
cl());
+  return specialization->getTemplateArgs()[0].getAsType();
+}
+
+/// \brief Prepare cleanup for the temporary array.
+static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
+                                          QualType arrayType,
+                                          llvm::Value *addr,
+                                          const InitListExpr *initList) {
+  QualType::DestructionKind dtorKind =3D arrayType.isDestructedType();
+  if (!dtorKind)
+    return; // Type doesn't need destroying.
+  if (dtorKind !=3D QualType::DK_cxx_destructor) {
+    CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
+    return;
+  }
+
+  CodeGenFunction::Destroyer *destroyer =3D CGF.getDestroyer(dtorKind);
+  CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
+                  /*EHCleanup=3D*/true);
+}
+
+/// \brief Emit the initializer for a std::initializer_list initialized wi=
th a
+/// real initializer list.
+void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
+                                            InitListExpr *initList) {
+  // We emit an array containing the elements, then have the init list poi=
nt
+  // at the array.
+  ASTContext &ctx =3D CGF.getContext();
+  unsigned numInits =3D initList->getNumInits();
+  QualType element =3D GetStdInitializerListElementType(initList->getType(=
));
+  llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
+  QualType array =3D ctx.getConstantArrayType(element, size, ArrayType::No=
rmal,0);
+  llvm::Type *LTy =3D CGF.ConvertTypeForMem(array);
+  llvm::AllocaInst *alloc =3D CGF.CreateTempAlloca(LTy);
+  alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
+  alloc->setName(".initlist.");
+
+  EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
+
+  // FIXME: The diagnostics are somewhat out of place here.
+  RecordDecl *record =3D initList->getType()->castAs<RecordType>()->getDec=
l();
+  RecordDecl::field_iterator field =3D record->field_begin();
+  if (field =3D=3D record->field_end()) {
+    CGF.ErrorUnsupported(initList, "weird std::initializer_list");
+    return;
+  }
+
+  QualType elementPtr =3D ctx.getPointerType(element.withConst());
+
+  // Start pointer.
+  if (!ctx.hasSameType(field->getType(), elementPtr)) {
+    CGF.ErrorUnsupported(initList, "weird std::initializer_list");
+    return;
+  }
+  LValue start =3D CGF.EmitLValueForFieldInitialization(destPtr, *field, 0=
);
+  llvm::Value *arrayStart =3D Builder.CreateStructGEP(alloc, 0, "arraystar=
t");
+  CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
+  ++field;
+
+  if (field =3D=3D record->field_end()) {
+    CGF.ErrorUnsupported(initList, "weird std::initializer_list");
+    return;
+  }
+  LValue endOrLength =3D CGF.EmitLValueForFieldInitialization(destPtr, *fi=
eld, 0);
+  if (ctx.hasSameType(field->getType(), elementPtr)) {
+    // End pointer.
+    llvm::Value *arrayEnd =3D Builder.CreateStructGEP(alloc,numInits, "arr=
ayend");
+    CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
+  } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
+    // Length.
+    CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLen=
gth);
+  } else {
+    CGF.ErrorUnsupported(initList, "weird std::initializer_list");
+    return;
+  }
+
+  if (!Dest.isExternallyDestructed())
+    EmitStdInitializerListCleanup(CGF, array, alloc, initList);
+}
+
+/// \brief Emit initialization of an array from an initializer list.
+void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *=
AType,
+                                   QualType elementType, InitListExpr *E) {
+  uint64_t NumInitElements =3D E->getNumInits();
+
+  uint64_t NumArrayElements =3D AType->getNumElements();
+  assert(NumInitElements <=3D NumArrayElements);
+
+  // DestPtr is an array*.  Construct an elementType* by drilling
+  // down a level.
+  llvm::Value *zero =3D llvm::ConstantInt::get(CGF.SizeTy, 0);
+  llvm::Value *indices[] =3D { zero, zero };
+  llvm::Value *begin =3D
+    Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
+
+  // Exception safety requires us to destroy all the
+  // already-constructed members if an initializer throws.
+  // For that, we'll need an EH cleanup.
+  QualType::DestructionKind dtorKind =3D elementType.isDestructedType();
+  llvm::AllocaInst *endOfInit =3D 0;
+  EHScopeStack::stable_iterator cleanup;
+  llvm::Instruction *cleanupDominator =3D 0;
+  if (CGF.needsEHCleanup(dtorKind)) {
+    // In principle we could tell the cleanup where we are more
+    // directly, but the control flow can get so varied here that it
+    // would actually be quite complex.  Therefore we go through an
+    // alloca.
+    endOfInit =3D CGF.CreateTempAlloca(begin->getType(),
+                                     "arrayinit.endOfInit");
+    cleanupDominator =3D Builder.CreateStore(begin, endOfInit);
+    CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
+                                         CGF.getDestroyer(dtorKind));
+    cleanup =3D CGF.EHStack.stable_begin();
+
+  // Otherwise, remember that we didn't need a cleanup.
+  } else {
+    dtorKind =3D QualType::DK_none;
+  }
+
+  llvm::Value *one =3D llvm::ConstantInt::get(CGF.SizeTy, 1);
+
+  // The 'current element to initialize'.  The invariants on this
+  // variable are complicated.  Essentially, after each iteration of
+  // the loop, it points to the last initialized element, except
+  // that it points to the beginning of the array before any
+  // elements have been initialized.
+  llvm::Value *element =3D begin;
+
+  // Emit the explicit initializers.
+  for (uint64_t i =3D 0; i !=3D NumInitElements; ++i) {
+    // Advance to the next element.
+    if (i > 0) {
+      element =3D Builder.CreateInBoundsGEP(element, one, "arrayinit.eleme=
nt");
+
+      // Tell the cleanup that it needs to destroy up to this
+      // element.  TODO: some of these stores can be trivially
+      // observed to be unnecessary.
+      if (endOfInit) Builder.CreateStore(element, endOfInit);
+    }
+
+    // If these are nested std::initializer_list inits, do them directly,
+    // because they are conceptually the same "location".
+    InitListExpr *initList =3D dyn_cast<InitListExpr>(E->getInit(i));
+    if (initList && initList->initializesStdInitializerList()) {
+      EmitStdInitializerList(element, initList);
+    } else {
+      LValue elementLV =3D CGF.MakeAddrLValue(element, elementType);
+      EmitInitializationToLValue(E->getInit(i), elementLV);
+    }
+  }
+
+  // Check whether there's a non-trivial array-fill expression.
+  // Note that this will be a CXXConstructExpr even if the element
+  // type is an array (or array of array, etc.) of class type.
+  Expr *filler =3D E->getArrayFiller();
+  bool hasTrivialFiller =3D true;
+  if (CXXConstructExpr *cons =3D dyn_cast_or_null<CXXConstructExpr>(filler=
)) {
+    assert(cons->getConstructor()->isDefaultConstructor());
+    hasTrivialFiller =3D cons->getConstructor()->isTrivial();
+  }
+
+  // Any remaining elements need to be zero-initialized, possibly
+  // using the filler expression.  We can skip this if the we're
+  // emitting to zeroed memory.
+  if (NumInitElements !=3D NumArrayElements &&
+      !(Dest.isZeroed() && hasTrivialFiller &&
+        CGF.getTypes().isZeroInitializable(elementType))) {
+
+    // Use an actual loop.  This is basically
+    //   do { *array++ =3D filler; } while (array !=3D end);
+
+    // Advance to the start of the rest of the array.
+    if (NumInitElements) {
+      element =3D Builder.CreateInBoundsGEP(element, one, "arrayinit.start=
");
+      if (endOfInit) Builder.CreateStore(element, endOfInit);
+    }
+
+    // Compute the end of the array.
+    llvm::Value *end =3D Builder.CreateInBoundsGEP(begin,
+                      llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
+                                                 "arrayinit.end");
+
+    llvm::BasicBlock *entryBB =3D Builder.GetInsertBlock();
+    llvm::BasicBlock *bodyBB =3D CGF.createBasicBlock("arrayinit.body");
+
+    // Jump into the body.
+    CGF.EmitBlock(bodyBB);
+    llvm::PHINode *currentElement =3D
+      Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
+    currentElement->addIncoming(element, entryBB);
+
+    // Emit the actual filler expression.
+    LValue elementLV =3D CGF.MakeAddrLValue(currentElement, elementType);
+    if (filler)
+      EmitInitializationToLValue(filler, elementLV);
+    else
+      EmitNullInitializationToLValue(elementLV);
+
+    // Move on to the next element.
+    llvm::Value *nextElement =3D
+      Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
+
+    // Tell the EH cleanup that we finished with the last element.
+    if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
+
+    // Leave the loop if we're done.
+    llvm::Value *done =3D Builder.CreateICmpEQ(nextElement, end,
+                                             "arrayinit.done");
+    llvm::BasicBlock *endBB =3D CGF.createBasicBlock("arrayinit.end");
+    Builder.CreateCondBr(done, endBB, bodyBB);
+    currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
+
+    CGF.EmitBlock(endBB);
+  }
+
+  // Leave the partial-array cleanup if we entered one.
+  if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -325,16 +578,10 @@
                 "should have been unpacked before we got here");
   }
=20
-  case CK_GetObjCProperty: {
-    LValue LV =3D CGF.EmitLValue(E->getSubExpr());
-    assert(LV.isPropertyRef());
-    RValue RV =3D CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot()=
);
-    EmitMoveFromReturnSlot(E, RV);
-    break;
-  }
-
   case CK_LValueToRValue: // hope for downstream optimization
   case CK_NoOp:
+  case CK_AtomicToNonAtomic:
+  case CK_NonAtomicToAtomic:
   case CK_UserDefinedConversion:
   case CK_ConstructorConversion:
     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getTyp=
e(),
@@ -345,7 +592,6 @@
      =20
   case CK_LValueBitCast:
     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
-    break;
=20
   case CK_Dependent:
   case CK_BitCast:
@@ -356,6 +602,7 @@
   case CK_BaseToDerivedMemberPointer:
   case CK_DerivedToBaseMemberPointer:
   case CK_MemberPointerToBoolean:
+  case CK_ReinterpretMemberPointer:
   case CK_IntegralToPointer:
   case CK_PointerToIntegral:
   case CK_PointerToBoolean:
@@ -385,6 +632,7 @@
   case CK_ARCConsumeObject:
   case CK_ARCReclaimReturnedObject:
   case CK_ARCExtendBlockObject:
+  case CK_CopyAndAutoreleaseBlockObject:
     llvm_unreachable("cast kind invalid for aggregate types");
   }
 }
@@ -404,11 +652,6 @@
   EmitMoveFromReturnSlot(E, RV);
 }
=20
-void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
-  llvm_unreachable("direct property access not surrounded by "
-                   "lvalue-to-rvalue cast");
-}
-
 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
   CGF.EmitIgnoredExpr(E->getLHS());
   Visit(E->getRHS());
@@ -456,29 +699,13 @@
  =20
   LValue LHS =3D CGF.EmitLValue(E->getLHS());
=20
-  // We have to special case property setters, otherwise we must have
-  // a simple lvalue (no aggregates inside vectors, bitfields).
-  if (LHS.isPropertyRef()) {
-    const ObjCPropertyRefExpr *RE =3D LHS.getPropertyRefExpr();
-    QualType ArgType =3D RE->getSetterArgType();
-    RValue Src;
-    if (ArgType->isReferenceType())
-      Src =3D CGF.EmitReferenceBindingToExpr(E->getRHS(), 0);
-    else {
-      AggValueSlot Slot =3D EnsureSlot(E->getRHS()->getType());
-      CGF.EmitAggExpr(E->getRHS(), Slot);
-      Src =3D Slot.asRValue();
-    }
-    CGF.EmitStoreThroughPropertyRefLValue(Src, LHS);
-  } else {
-    // Codegen the RHS so that it stores directly into the LHS.
-    AggValueSlot LHSSlot =3D
-      AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,=20
-                              needsGC(E->getLHS()->getType()),
-                              AggValueSlot::IsAliased);
-    CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
-    EmitFinalDestCopy(E, LHS, true);
-  }
+  // Codegen the RHS so that it stores directly into the LHS.
+  AggValueSlot LHSSlot =3D
+    AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,=20
+                            needsGC(E->getLHS()->getType()),
+                            AggValueSlot::IsAliased);
+  CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
+  EmitFinalDestCopy(E, LHS, true);
 }
=20
 void AggExprEmitter::
@@ -547,7 +774,7 @@
=20
   // Push that destructor we promised.
   if (!wasExternallyDestructed)
-    CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
+    CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
 }
=20
 void
@@ -556,8 +783,16 @@
   CGF.EmitCXXConstructExpr(E, Slot);
 }
=20
+void
+AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
+  AggValueSlot Slot =3D EnsureSlot(E->getType());
+  CGF.EmitLambdaExpr(E, Slot);
+}
+
 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
-  CGF.EmitExprWithCleanups(E, Dest);
+  CGF.enterFullExpression(E);
+  CodeGenFunction::RunCleanupsScope cleanups(CGF);
+  Visit(E->getSubExpr());
 }
=20
 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E=
) {
@@ -636,9 +871,16 @@
     return;
  =20
   if (!CGF.hasAggregateLLVMType(type)) {
-    // For non-aggregates, we can store zero
+    // For non-aggregates, we can store zero.
     llvm::Value *null =3D llvm::Constant::getNullValue(CGF.ConvertType(typ=
e));
-    CGF.EmitStoreThroughLValue(RValue::get(null), lv);
+    // Note that the following is not equivalent to
+    // EmitStoreThroughBitfieldLValue for ARC types.
+    if (lv.isBitField()) {
+      CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
+    } else {
+      assert(lv.isSimple());
+      CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
+    }
   } else {
     // There's a potential optimization opportunity in combining
     // memsets; that would be easy for arrays, but relatively
@@ -665,17 +907,15 @@
   if (E->hadArrayRangeDesignator())
     CGF.ErrorUnsupported(E, "GNU array range designator extension");
=20
-  llvm::Value *DestPtr =3D Dest.getAddr();
+  if (E->initializesStdInitializerList()) {
+    EmitStdInitializerList(Dest.getAddr(), E);
+    return;
+  }
+
+  llvm::Value *DestPtr =3D EnsureSlot(E->getType()).getAddr();
=20
   // Handle initialization of an array.
   if (E->getType()->isArrayType()) {
-    llvm::PointerType *APType =3D
-      cast<llvm::PointerType>(DestPtr->getType());
-    llvm::ArrayType *AType =3D
-      cast<llvm::ArrayType>(APType->getElementType());
-
-    uint64_t NumInitElements =3D E->getNumInits();
-
     if (E->getNumInits() > 0) {
       QualType T1 =3D E->getType();
       QualType T2 =3D E->getInit(0)->getType();
@@ -685,136 +925,15 @@
       }
     }
=20
-    uint64_t NumArrayElements =3D AType->getNumElements();
-    assert(NumInitElements <=3D NumArrayElements);
+    QualType elementType =3D
+        CGF.getContext().getAsArrayType(E->getType())->getElementType();
=20
-    QualType elementType =3D E->getType().getCanonicalType();
-    elementType =3D CGF.getContext().getQualifiedType(
-                    cast<ArrayType>(elementType)->getElementType(),
-                    elementType.getQualifiers() + Dest.getQualifiers());
+    llvm::PointerType *APType =3D
+      cast<llvm::PointerType>(DestPtr->getType());
+    llvm::ArrayType *AType =3D
+      cast<llvm::ArrayType>(APType->getElementType());
=20
-    // DestPtr is an array*.  Construct an elementType* by drilling
-    // down a level.
-    llvm::Value *zero =3D llvm::ConstantInt::get(CGF.SizeTy, 0);
-    llvm::Value *indices[] =3D { zero, zero };
-    llvm::Value *begin =3D
-      Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
-
-    // Exception safety requires us to destroy all the
-    // already-constructed members if an initializer throws.
-    // For that, we'll need an EH cleanup.
-    QualType::DestructionKind dtorKind =3D elementType.isDestructedType();
-    llvm::AllocaInst *endOfInit =3D 0;
-    EHScopeStack::stable_iterator cleanup;
-    if (CGF.needsEHCleanup(dtorKind)) {
-      // In principle we could tell the cleanup where we are more
-      // directly, but the control flow can get so varied here that it
-      // would actually be quite complex.  Therefore we go through an
-      // alloca.
-      endOfInit =3D CGF.CreateTempAlloca(begin->getType(),
-                                       "arrayinit.endOfInit");
-      Builder.CreateStore(begin, endOfInit);
-      CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
-                                           CGF.getDestroyer(dtorKind));
-      cleanup =3D CGF.EHStack.stable_begin();
-
-    // Otherwise, remember that we didn't need a cleanup.
-    } else {
-      dtorKind =3D QualType::DK_none;
-    }
-
-    llvm::Value *one =3D llvm::ConstantInt::get(CGF.SizeTy, 1);
-
-    // The 'current element to initialize'.  The invariants on this
-    // variable are complicated.  Essentially, after each iteration of
-    // the loop, it points to the last initialized element, except
-    // that it points to the beginning of the array before any
-    // elements have been initialized.
-    llvm::Value *element =3D begin;
-
-    // Emit the explicit initializers.
-    for (uint64_t i =3D 0; i !=3D NumInitElements; ++i) {
-      // Advance to the next element.
-      if (i > 0) {
-        element =3D Builder.CreateInBoundsGEP(element, one, "arrayinit.ele=
ment");
-
-        // Tell the cleanup that it needs to destroy up to this
-        // element.  TODO: some of these stores can be trivially
-        // observed to be unnecessary.
-        if (endOfInit) Builder.CreateStore(element, endOfInit);
-      }
-
-      LValue elementLV =3D CGF.MakeAddrLValue(element, elementType);
-      EmitInitializationToLValue(E->getInit(i), elementLV);
-    }
-
-    // Check whether there's a non-trivial array-fill expression.
-    // Note that this will be a CXXConstructExpr even if the element
-    // type is an array (or array of array, etc.) of class type.
-    Expr *filler =3D E->getArrayFiller();
-    bool hasTrivialFiller =3D true;
-    if (CXXConstructExpr *cons =3D dyn_cast_or_null<CXXConstructExpr>(fill=
er)) {
-      assert(cons->getConstructor()->isDefaultConstructor());
-      hasTrivialFiller =3D cons->getConstructor()->isTrivial();
-    }
-
-    // Any remaining elements need to be zero-initialized, possibly
-    // using the filler expression.  We can skip this if the we're
-    // emitting to zeroed memory.
-    if (NumInitElements !=3D NumArrayElements &&
-        !(Dest.isZeroed() && hasTrivialFiller &&
-          CGF.getTypes().isZeroInitializable(elementType))) {
-
-      // Use an actual loop.  This is basically
-      //   do { *array++ =3D filler; } while (array !=3D end);
-
-      // Advance to the start of the rest of the array.
-      if (NumInitElements) {
-        element =3D Builder.CreateInBoundsGEP(element, one, "arrayinit.sta=
rt");
-        if (endOfInit) Builder.CreateStore(element, endOfInit);
-      }
-
-      // Compute the end of the array.
-      llvm::Value *end =3D Builder.CreateInBoundsGEP(begin,
-                        llvm::ConstantInt::get(CGF.SizeTy, NumArrayElement=
s),
-                                                   "arrayinit.end");
-
-      llvm::BasicBlock *entryBB =3D Builder.GetInsertBlock();
-      llvm::BasicBlock *bodyBB =3D CGF.createBasicBlock("arrayinit.body");
-
-      // Jump into the body.
-      CGF.EmitBlock(bodyBB);
-      llvm::PHINode *currentElement =3D
-        Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
-      currentElement->addIncoming(element, entryBB);
-
-      // Emit the actual filler expression.
-      LValue elementLV =3D CGF.MakeAddrLValue(currentElement, elementType);
-      if (filler)
-        EmitInitializationToLValue(filler, elementLV);
-      else
-        EmitNullInitializationToLValue(elementLV);
-
-      // Move on to the next element.
-      llvm::Value *nextElement =3D
-        Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
-
-      // Tell the EH cleanup that we finished with the last element.
-      if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
-
-      // Leave the loop if we're done.
-      llvm::Value *done =3D Builder.CreateICmpEQ(nextElement, end,
-                                               "arrayinit.done");
-      llvm::BasicBlock *endBB =3D CGF.createBasicBlock("arrayinit.end");
-      Builder.CreateCondBr(done, endBB, bodyBB);
-      currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
-
-      CGF.EmitBlock(endBB);
-    }
-
-    // Leave the partial-array cleanup if we entered one.
-    if (dtorKind) CGF.DeactivateCleanupBlock(cleanup);
-
+    EmitArrayInit(DestPtr, AType, elementType, E);
     return;
   }
=20
@@ -862,6 +981,7 @@
   // We'll need to enter cleanup scopes in case any of the member
   // initializers throw an exception.
   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
+  llvm::Instruction *cleanupDominator =3D 0;
=20
   // Here we iterate over the fields; this makes it simpler to both
   // default-initialize fields and skip over unnamed fields.
@@ -905,6 +1025,9 @@
           =3D field->getType().isDestructedType()) {
       assert(LV.isSimple());
       if (CGF.needsEHCleanup(dtorKind)) {
+        if (!cleanupDominator)
+          cleanupDominator =3D CGF.Builder.CreateUnreachable(); // placeho=
lder
+
         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
                         CGF.getDestroyer(dtorKind), false);
         cleanups.push_back(CGF.EHStack.stable_begin());
@@ -924,7 +1047,11 @@
   // Deactivate all the partial cleanups in reverse order, which
   // generally means popping them.
   for (unsigned i =3D cleanups.size(); i !=3D 0; --i)
-    CGF.DeactivateCleanupBlock(cleanups[i-1]);
+    CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
+
+  // Destroy the placeholder if we made one.
+  if (cleanupDominator)
+    cleanupDominator->eraseFromParent();
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -996,7 +1123,7 @@
   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() =3D=3D 0) ret=
urn;
=20
   // C++ objects with a user-declared constructor don't need zero'ing.
-  if (CGF.getContext().getLangOptions().CPlusPlus)
+  if (CGF.getContext().getLangOpts().CPlusPlus)
     if (const RecordType *RT =3D CGF.getContext()
                        .getBaseElementType(E->getType())->getAs<RecordType=
>()) {
       const CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RT->getDecl());
@@ -1021,9 +1148,8 @@
   CharUnits Align =3D TypeInfo.second;
=20
   llvm::Value *Loc =3D Slot.getAddr();
-  llvm::Type *BP =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
  =20
-  Loc =3D CGF.Builder.CreateBitCast(Loc, BP);
+  Loc =3D CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,=20
                            Align.getQuantity(), false);
  =20
@@ -1066,10 +1192,10 @@
=20
 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
                                         llvm::Value *SrcPtr, QualType Ty,
-                                        bool isVolatile) {
+                                        bool isVolatile, unsigned Alignmen=
t) {
   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
=20
-  if (getContext().getLangOptions().CPlusPlus) {
+  if (getContext().getLangOpts().CPlusPlus) {
     if (const RecordType *RT =3D Ty->getAs<RecordType>()) {
       CXXRecordDecl *Record =3D cast<CXXRecordDecl>(RT->getDecl());
       assert((Record->hasTrivialCopyConstructor() ||=20
@@ -1099,6 +1225,9 @@
   std::pair<CharUnits, CharUnits> TypeInfo =3D=20
     getContext().getTypeInfoInChars(Ty);
=20
+  if (!Alignment)
+    Alignment =3D TypeInfo.second.getQuantity();
+
   // FIXME: Handle variable sized types.
=20
   // FIXME: If we have a volatile struct, the optimizer can remove what mi=
ght
@@ -1125,7 +1254,7 @@
   SrcPtr =3D Builder.CreateBitCast(SrcPtr, SBP);
=20
   // Don't do any of the memmove_collectable tests if GC isn't set.
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::NonGC) {
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::NonGC) {
     // fall through
   } else if (const RecordType *RecordTy =3D Ty->getAs<RecordType>()) {
     RecordDecl *Record =3D RecordTy->getDecl();
@@ -1155,5 +1284,60 @@
   Builder.CreateMemCpy(DestPtr, SrcPtr,
                        llvm::ConstantInt::get(IntPtrTy,=20
                                               TypeInfo.first.getQuantity()=
),
-                       TypeInfo.second.getQuantity(), isVolatile);
+                       Alignment, isVolatile);
 }
+
+void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
+                                                         const Expr *init)=
 {
+  const ExprWithCleanups *cleanups =3D dyn_cast<ExprWithCleanups>(init);
+  if (cleanups)
+    init =3D cleanups->getSubExpr();
+
+  if (isa<InitListExpr>(init) &&
+      cast<InitListExpr>(init)->initializesStdInitializerList()) {
+    // We initialized this std::initializer_list with an initializer list.
+    // A backing array was created. Push a cleanup for it.
+    EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
+  }
+}
+
+static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
+                                                   llvm::Value *arrayStart,
+                                                   const InitListExpr *ini=
t) {
+  // Check if there are any recursive cleanups to do, i.e. if we have
+  //   std::initializer_list<std::initializer_list<obj>> list =3D {{obj()}=
};
+  // then we need to destroy the inner array as well.
+  for (unsigned i =3D 0, e =3D init->getNumInits(); i !=3D e; ++i) {
+    const InitListExpr *subInit =3D dyn_cast<InitListExpr>(init->getInit(i=
));
+    if (!subInit || !subInit->initializesStdInitializerList())
+      continue;
+
+    // This one needs to be destroyed. Get the address of the std::init_li=
st.
+    llvm::Value *offset =3D llvm::ConstantInt::get(CGF.SizeTy, i);
+    llvm::Value *loc =3D CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
+                                                 "std.initlist");
+    CGF.EmitStdInitializerListCleanup(loc, subInit);
+  }
+}
+
+void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
+                                                    const InitListExpr *in=
it) {
+  ASTContext &ctx =3D getContext();
+  QualType element =3D GetStdInitializerListElementType(init->getType());
+  unsigned numInits =3D init->getNumInits();
+  llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
+  QualType array =3Dctx.getConstantArrayType(element, size, ArrayType::Nor=
mal, 0);
+  QualType arrayPtr =3D ctx.getPointerType(array);
+  llvm::Type *arrayPtrType =3D ConvertType(arrayPtr);
+
+  // lvalue is the location of a std::initializer_list, which as its first
+  // element has a pointer to the array we want to destroy.
+  llvm::Value *startPointer =3D Builder.CreateStructGEP(loc, 0, "startPoin=
ter");
+  llvm::Value *startAddress =3D Builder.CreateLoad(startPointer, "startAdd=
ress");
+
+  ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
+
+  llvm::Value *arrayAddress =3D
+      Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
+  ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGExprCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprCXX.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprCXX.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -33,8 +33,6 @@
   assert(MD->isInstance() &&
          "Trying to emit a member call expr on a static method!");
=20
-  const FunctionProtoType *FPT =3D MD->getType()->getAs<FunctionProtoType>=
();
-
   CallArgList Args;
=20
   // Push the this ptr.
@@ -45,13 +43,16 @@
     QualType T =3D getContext().getPointerType(getContext().VoidPtrTy);
     Args.add(RValue::get(VTT), T);
   }
+
+  const FunctionProtoType *FPT =3D MD->getType()->castAs<FunctionProtoType=
>();
+  RequiredArgs required =3D RequiredArgs::forPrototypePlus(FPT, Args.size(=
));
  =20
-  // And the rest of the call args
+  // And the rest of the call args.
   EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
=20
-  QualType ResultType =3D FPT->getResultType();
-  return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
-                                                 FPT->getExtInfo()),
+  return EmitCall(CGM.getTypes().arrangeFunctionCall(FPT->getResultType(),=
 Args,
+                                                     FPT->getExtInfo(),
+                                                     required),
                   Callee, ReturnValue, Args, MD);
 }
=20
@@ -112,7 +113,7 @@
  =20
   // When building with -fapple-kext, all calls must go through the vtable=
 since
   // the kernel linker can do runtime patching of vtables.
-  if (Context.getLangOptions().AppleKext)
+  if (Context.getLangOpts().AppleKext)
     return false;
=20
   // If the most derived class is marked final, we know that no subclass c=
an
@@ -229,17 +230,16 @@
   // Compute the function type we're calling.
   const CGFunctionInfo *FInfo =3D 0;
   if (isa<CXXDestructorDecl>(MD))
-    FInfo =3D &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
-                                           Dtor_Complete);
+    FInfo =3D &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>=
(MD),
+                                                 Dtor_Complete);
   else if (isa<CXXConstructorDecl>(MD))
-    FInfo =3D &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
-                                            Ctor_Complete);
+    FInfo =3D &CGM.getTypes().arrangeCXXConstructorDeclaration(
+                                                 cast<CXXConstructorDecl>(=
MD),
+                                                 Ctor_Complete);
   else
-    FInfo =3D &CGM.getTypes().getFunctionInfo(MD);
+    FInfo =3D &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
=20
-  const FunctionProtoType *FPT =3D MD->getType()->getAs<FunctionProtoType>=
();
-  llvm::Type *Ty
-    =3D CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
+  llvm::Type *Ty =3D CGM.getTypes().GetFunctionType(*FInfo);
=20
   // C++ [class.virtual]p12:
   //   Explicit qualification with the scope operator (5.1) suppresses the
@@ -256,7 +256,7 @@
     if (UseVirtualCall) {
       Callee =3D BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
     } else {
-      if (getContext().getLangOptions().AppleKext &&
+      if (getContext().getLangOpts().AppleKext &&
           MD->isVirtual() &&
           ME->hasQualifier())
         Callee =3D BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
@@ -269,7 +269,7 @@
   } else if (UseVirtualCall) {
       Callee =3D BuildVirtualCall(MD, This, Ty);=20
   } else {
-    if (getContext().getLangOptions().AppleKext &&
+    if (getContext().getLangOpts().AppleKext &&
         MD->isVirtual() &&
         ME->hasQualifier())
       Callee =3D BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
@@ -322,7 +322,7 @@
  =20
   // And the rest of the call args
   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
-  return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,=20
+  return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,=20
                   ReturnValue, Args);
 }
=20
@@ -427,7 +427,7 @@
   // Elide the constructor if we're constructing from a temporary.
   // The temporary check is required because Sema sets this on NRVO
   // returns.
-  if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
+  if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
     assert(getContext().hasSameUnqualifiedType(E->getType(),
                                                E->getArg(0)->getType()));
     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
@@ -508,6 +508,7 @@
=20
 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
                                         const CXXNewExpr *e,
+                                        unsigned minElements,
                                         llvm::Value *&numElements,
                                         llvm::Value *&sizeWithoutCookie) {
   QualType type =3D e->getAllocatedType();
@@ -581,6 +582,11 @@
     // Okay, compute a count at the right width.
     llvm::APInt adjustedCount =3D count.zextOrTrunc(sizeWidth);
=20
+    // If there is a brace-initializer, we cannot allocate fewer elements =
than
+    // there are initializers. If we do, that's treated like an overflow.
+    if (adjustedCount.ult(minElements))
+      hasAnyOverflow =3D true;
+
     // Scale numElements by that.  This might overflow, but we don't
     // care because it only overflows if allocationSize does, too, and
     // if that overflows then we shouldn't use this.
@@ -612,14 +618,16 @@
=20
   // Otherwise, we might need to use the overflow intrinsics.
   } else {
-    // There are up to four conditions we need to test for:
+    // There are up to five conditions we need to test for:
     // 1) if isSigned, we need to check whether numElements is negative;
     // 2) if numElementsWidth > sizeWidth, we need to check whether
     //   numElements is larger than something representable in size_t;
-    // 3) we need to compute
+    // 3) if minElements > 0, we need to check whether numElements is smal=
ler
+    //    than that.
+    // 4) we need to compute
     //      sizeWithoutCookie :=3D numElements * typeSizeMultiplier
     //    and check whether it overflows; and
-    // 4) if we need a cookie, we need to compute
+    // 5) if we need a cookie, we need to compute
     //      size :=3D sizeWithoutCookie + cookieSize
     //    and check whether it overflows.
=20
@@ -646,10 +654,11 @@
       // If there's a non-1 type size multiplier, then we can do the
       // signedness check at the same time as we do the multiply
       // because a negative number times anything will cause an
-      // unsigned overflow.  Otherwise, we have to do it here.
+      // unsigned overflow.  Otherwise, we have to do it here. But at least
+      // in this case, we can subsume the >=3D minElements check.
       if (typeSizeMultiplier =3D=3D 1)
         hasOverflow =3D CGF.Builder.CreateICmpSLT(numElements,
-                                      llvm::ConstantInt::get(CGF.SizeTy, 0=
));
+                              llvm::ConstantInt::get(CGF.SizeTy, minElemen=
ts));
=20
     // Otherwise, zext up to size_t if necessary.
     } else if (numElementsWidth < sizeWidth) {
@@ -658,6 +667,21 @@
=20
     assert(numElements->getType() =3D=3D CGF.SizeTy);
=20
+    if (minElements) {
+      // Don't allow allocation of fewer elements than we have initializer=
s.
+      if (!hasOverflow) {
+        hasOverflow =3D CGF.Builder.CreateICmpULT(numElements,
+                              llvm::ConstantInt::get(CGF.SizeTy, minElemen=
ts));
+      } else if (numElementsWidth > sizeWidth) {
+        // The other existing overflow subsumes this check.
+        // We do an unsigned comparison, since any signed value < -1 is
+        // taken care of either above or below.
+        hasOverflow =3D CGF.Builder.CreateOr(hasOverflow,
+                          CGF.Builder.CreateICmpULT(numElements,
+                              llvm::ConstantInt::get(CGF.SizeTy, minElemen=
ts)));
+      }
+    }
+
     size =3D numElements;
=20
     // Multiply by the type size if necessary.  This multiplier
@@ -741,30 +765,26 @@
   return size;
 }
=20
-static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr=
 *E,
-                                    llvm::Value *NewPtr) {
- =20
-  assert(E->getNumConstructorArgs() =3D=3D 1 &&
-         "Can only have one argument to initializer of POD type.");
- =20
-  const Expr *Init =3D E->getConstructorArg(0);
-  QualType AllocType =3D E->getAllocatedType();
+static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
+                                    QualType AllocType, llvm::Value *NewPt=
r) {
=20
-  unsigned Alignment =3D
-    CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
+  CharUnits Alignment =3D CGF.getContext().getTypeAlignInChars(AllocType);
   if (!CGF.hasAggregateLLVMType(AllocType))
-    CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType, Alig=
nment),
+    CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
+                                                   Alignment),
                        false);
   else if (AllocType->isAnyComplexType())
     CGF.EmitComplexExprIntoAddr(Init, NewPtr,=20
                                 AllocType.isVolatileQualified());
   else {
     AggValueSlot Slot
-      =3D AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
+      =3D AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers=
(),
                               AggValueSlot::IsDestructed,
                               AggValueSlot::DoesNotNeedGCBarriers,
                               AggValueSlot::IsNotAliased);
     CGF.EmitAggExpr(Init, Slot);
+
+    CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
   }
 }
=20
@@ -773,30 +793,67 @@
                                          QualType elementType,
                                          llvm::Value *beginPtr,
                                          llvm::Value *numElements) {
-  // We have a POD type.
-  if (E->getNumConstructorArgs() =3D=3D 0)
-    return;
+  if (!E->hasInitializer())
+    return; // We have a POD type.
=20
-  // Check if the number of elements is constant.
-  bool checkZero =3D true;
-  if (llvm::ConstantInt *constNum =3D dyn_cast<llvm::ConstantInt>(numEleme=
nts)) {
-    // If it's constant zero, skip the whole loop.
-    if (constNum->isZero()) return;
-
-    checkZero =3D false;
-  }
-
+  llvm::Value *explicitPtr =3D beginPtr;
   // Find the end of the array, hoisted out of the loop.
   llvm::Value *endPtr =3D
     Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
=20
+  unsigned initializerElements =3D 0;
+
+  const Expr *Init =3D E->getInitializer();
+  llvm::AllocaInst *endOfInit =3D 0;
+  QualType::DestructionKind dtorKind =3D elementType.isDestructedType();
+  EHScopeStack::stable_iterator cleanup;
+  llvm::Instruction *cleanupDominator =3D 0;
+  // If the initializer is an initializer list, first do the explicit elem=
ents.
+  if (const InitListExpr *ILE =3D dyn_cast<InitListExpr>(Init)) {
+    initializerElements =3D ILE->getNumInits();
+
+    // Enter a partial-destruction cleanup if necessary.
+    if (needsEHCleanup(dtorKind)) {
+      // In principle we could tell the cleanup where we are more
+      // directly, but the control flow can get so varied here that it
+      // would actually be quite complex.  Therefore we go through an
+      // alloca.
+      endOfInit =3D CreateTempAlloca(beginPtr->getType(), "array.endOfInit=
");
+      cleanupDominator =3D Builder.CreateStore(beginPtr, endOfInit);
+      pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
+                                       getDestroyer(dtorKind));
+      cleanup =3D EHStack.stable_begin();
+    }
+
+    for (unsigned i =3D 0, e =3D ILE->getNumInits(); i !=3D e; ++i) {
+      // Tell the cleanup that it needs to destroy up to this
+      // element.  TODO: some of these stores can be trivially
+      // observed to be unnecessary.
+      if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
+      StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explici=
tPtr);
+      explicitPtr =3DBuilder.CreateConstGEP1_32(explicitPtr, 1, "array.exp=
.next");
+    }
+
+    // The remaining elements are filled with the array filler expression.
+    Init =3D ILE->getArrayFiller();
+  }
+
   // Create the continuation block.
   llvm::BasicBlock *contBB =3D createBasicBlock("new.loop.end");
=20
-  // If we need to check for zero, do so now.
-  if (checkZero) {
+  // If the number of elements isn't constant, we have to now check if the=
re is
+  // anything left to initialize.
+  if (llvm::ConstantInt *constNum =3D dyn_cast<llvm::ConstantInt>(numEleme=
nts)) {
+    // If all elements have already been initialized, skip the whole loop.
+    if (constNum->getZExtValue() <=3D initializerElements) {
+      // If there was a cleanup, deactivate it.
+      if (cleanupDominator)
+        DeactivateCleanupBlock(cleanup, cleanupDominator);;
+      return;
+    }
+  } else {
     llvm::BasicBlock *nonEmptyBB =3D createBasicBlock("new.loop.nonempty");
-    llvm::Value *isEmpty =3D Builder.CreateICmpEQ(beginPtr, endPtr,
+    llvm::Value *isEmpty =3D Builder.CreateICmpEQ(explicitPtr, endPtr,
                                                 "array.isempty");
     Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
     EmitBlock(nonEmptyBB);
@@ -810,24 +867,28 @@
=20
   // Set up the current-element phi.
   llvm::PHINode *curPtr =3D
-    Builder.CreatePHI(beginPtr->getType(), 2, "array.cur");
-  curPtr->addIncoming(beginPtr, entryBB);
+    Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
+  curPtr->addIncoming(explicitPtr, entryBB);
+
+  // Store the new cleanup position for irregular cleanups.
+  if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
=20
   // Enter a partial-destruction cleanup if necessary.
-  QualType::DestructionKind dtorKind =3D elementType.isDestructedType();
-  EHScopeStack::stable_iterator cleanup;
-  if (needsEHCleanup(dtorKind)) {
+  if (!cleanupDominator && needsEHCleanup(dtorKind)) {
     pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
                                    getDestroyer(dtorKind));
     cleanup =3D EHStack.stable_begin();
+    cleanupDominator =3D Builder.CreateUnreachable();
   }
=20
   // Emit the initializer into this element.
-  StoreAnyExprIntoOneUnit(*this, E, curPtr);
+  StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
=20
   // Leave the cleanup if we entered one.
-  if (cleanup !=3D EHStack.stable_end())
-    DeactivateCleanupBlock(cleanup);
+  if (cleanupDominator) {
+    DeactivateCleanupBlock(cleanup, cleanupDominator);
+    cleanupDominator->eraseFromParent();
+  }
=20
   // Advance to the next element.
   llvm::Value *nextPtr =3D Builder.CreateConstGEP1_32(curPtr, 1, "array.ne=
xt");
@@ -854,13 +915,15 @@
                                llvm::Value *NewPtr,
                                llvm::Value *NumElements,
                                llvm::Value *AllocSizeWithoutCookie) {
+  const Expr *Init =3D E->getInitializer();
   if (E->isArray()) {
-    if (CXXConstructorDecl *Ctor =3D E->getConstructor()) {
+    if (const CXXConstructExpr *CCE =3D dyn_cast_or_null<CXXConstructExpr>=
(Init)){
+      CXXConstructorDecl *Ctor =3D CCE->getConstructor();
       bool RequiresZeroInitialization =3D false;
-      if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
+      if (Ctor->isTrivial()) {
         // If new expression did not specify value-initialization, then th=
ere
         // is no initialization.
-        if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
+        if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmp=
ty())
           return;
      =20
         if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
@@ -873,43 +936,25 @@
         RequiresZeroInitialization =3D true;
       }
=20
-      CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,=20
-                                     E->constructor_arg_begin(),=20
-                                     E->constructor_arg_end(),
+      CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
+                                     CCE->arg_begin(),  CCE->arg_end(),
                                      RequiresZeroInitialization);
       return;
-    } else if (E->getNumConstructorArgs() =3D=3D 1 &&
-               isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
+    } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
+               CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
       // Optimization: since zero initialization will just set the memory
       // to all zeroes, generate a single memset to do it in one shot.
       EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
       return;
-    } else {
-      CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
-      return;
     }
+    CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
+    return;
   }
=20
-  if (CXXConstructorDecl *Ctor =3D E->getConstructor()) {
-    // Per C++ [expr.new]p15, if we have an initializer, then we're perfor=
ming
-    // direct initialization. C++ [dcl.init]p5 requires that we=20
-    // zero-initialize storage if there are no user-declared constructors.
-    if (E->hasInitializer() &&=20
-        !Ctor->getParent()->hasUserDeclaredConstructor() &&
-        !Ctor->getParent()->isEmpty())
-      CGF.EmitNullInitialization(NewPtr, ElementType);
-     =20
-    CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=3D*/f=
alse,=20
-                               NewPtr, E->constructor_arg_begin(),
-                               E->constructor_arg_end());
+  if (!Init)
+    return;
=20
-    return;
-  }
-  // We have a POD type.
-  if (E->getNumConstructorArgs() =3D=3D 0)
-    return;
- =20
-  StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
+  StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
 }
=20
 namespace {
@@ -961,7 +1006,7 @@
         DeleteArgs.add(getPlacementArgs()[I], *AI++);
=20
       // Call 'operator delete'.
-      CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
+      CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
     }
@@ -1022,7 +1067,7 @@
       }
=20
       // Call 'operator delete'.
-      CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
+      CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
                    ReturnValueSlot(), DeleteArgs, OperatorDelete);
     }
@@ -1057,7 +1102,7 @@
     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
=20
   CallDeleteDuringConditionalNew *Cleanup =3D CGF.EHStack
-    .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanu=
p,
+    .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
                                                  E->getNumPlacementArgs(),
                                                  E->getOperatorDelete(),
                                                  SavedNewPtr,
@@ -1066,7 +1111,7 @@
     Cleanup->setPlacementArg(I,
                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
=20
-  CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
+  CGF.initFullExprCleanup();
 }
=20
 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
@@ -1083,10 +1128,18 @@
   // The allocation size is the first argument.
   QualType sizeType =3D getContext().getSizeType();
=20
+  // If there is a brace-initializer, cannot allocate fewer elements than =
inits.
+  unsigned minElements =3D 0;
+  if (E->isArray() && E->hasInitializer()) {
+    if (const InitListExpr *ILE =3D dyn_cast<InitListExpr>(E->getInitializ=
er()))
+      minElements =3D ILE->getNumInits();
+  }
+
   llvm::Value *numElements =3D 0;
   llvm::Value *allocSizeWithoutCookie =3D 0;
   llvm::Value *allocSize =3D
-    EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
+    EmitCXXNewAllocSize(*this, E, minElements, numElements,
+                        allocSizeWithoutCookie);
  =20
   allocatorArgs.add(RValue::get(allocSize), sizeType);
=20
@@ -1129,7 +1182,8 @@
     // TODO: kill any unnecessary computations done for the size
     // argument.
   } else {
-    RV =3D EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocato=
rType),
+    RV =3D EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
+                                                     allocatorType),
                   CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
                   allocatorArgs, allocator);
   }
@@ -1140,7 +1194,7 @@
   // CXXNewExpr::shouldNullCheckAllocation()) and we have an
   // interesting initializer.
   bool nullCheck =3D allocatorType->isNothrow(getContext()) &&
-    !(allocType.isPODType(getContext()) && !E->hasInitializer());
+    (!allocType.isPODType(getContext()) || E->hasInitializer());
=20
   llvm::BasicBlock *nullCheckBB =3D 0;
   llvm::BasicBlock *contBB =3D 0;
@@ -1168,10 +1222,12 @@
   // If there's an operator delete, enter a cleanup to call it if an
   // exception is thrown.
   EHScopeStack::stable_iterator operatorDeleteCleanup;
+  llvm::Instruction *cleanupDominator =3D 0;
   if (E->getOperatorDelete() &&
       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
     operatorDeleteCleanup =3D EHStack.stable_begin();
+    cleanupDominator =3D Builder.CreateUnreachable();
   }
=20
   assert((allocSize =3D=3D allocSizeWithoutCookie) =3D=3D
@@ -1200,9 +1256,11 @@
=20
   // Deactivate the 'operator delete' cleanup if we finished
   // initialization.
-  if (operatorDeleteCleanup.isValid())
-    DeactivateCleanupBlock(operatorDeleteCleanup);
- =20
+  if (operatorDeleteCleanup.isValid()) {
+    DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
+    cleanupDominator->eraseFromParent();
+  }
+
   if (nullCheck) {
     conditional.end(*this);
=20
@@ -1248,7 +1306,7 @@
     DeleteArgs.add(RValue::get(Size), SizeTy);
=20
   // Emit the call to delete.
-  EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
+  EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
            CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),=20
            DeleteArgs, DeleteFD);
 }
@@ -1295,9 +1353,8 @@
         }
        =20
         llvm::Type *Ty =3D
-          CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dt=
or,
-                                                               Dtor_Comple=
te),
-                                         /*isVariadic=3D*/false);
+          CGF.getTypes().GetFunctionType(
+                         CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Co=
mplete));
          =20
         llvm::Value *Callee
           =3D CGF.BuildVirtualCall(Dtor,=20
@@ -1324,7 +1381,7 @@
   if (Dtor)
     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
                               /*ForVirtualBase=3D*/false, Ptr);
-  else if (CGF.getLangOptions().ObjCAutoRefCount &&
+  else if (CGF.getLangOpts().ObjCAutoRefCount &&
            ElementType->isObjCLifetimeType()) {
     switch (ElementType.getObjCLifetime()) {
     case Qualifiers::OCL_None:
@@ -1405,7 +1462,7 @@
       }
=20
       // Emit the call to delete.
-      CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
+      CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
                    CGF.CGM.GetAddrOfFunction(OperatorDelete),
                    ReturnValueSlot(), Args, OperatorDelete);
     }
@@ -1514,10 +1571,7 @@
=20
 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
   // void __cxa_bad_typeid();
- =20
-  llvm::Type *VoidTy =3D llvm::Type::getVoidTy(CGF.getLLVMContext());
-  llvm::FunctionType *FTy =3D
-  llvm::FunctionType::get(VoidTy, false);
+  llvm::FunctionType *FTy =3D llvm::FunctionType::get(CGF.VoidTy, false);
  =20
   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
 }
@@ -1598,7 +1652,7 @@
   //                      const abi::__class_type_info *dst,
   //                      std::ptrdiff_t src2dst_offset);
  =20
-  llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
+  llvm::Type *Int8PtrTy =3D CGF.Int8PtrTy;
   llvm::Type *PtrDiffTy =3D=20
     CGF.ConvertType(CGF.getContext().getPointerDiffType());
=20
@@ -1612,11 +1666,7 @@
=20
 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
   // void __cxa_bad_cast();
- =20
-  llvm::Type *VoidTy =3D llvm::Type::getVoidTy(CGF.getLLVMContext());
-  llvm::FunctionType *FTy =3D
-    llvm::FunctionType::get(VoidTy, false);
- =20
+  llvm::FunctionType *FTy =3D llvm::FunctionType::get(CGF.VoidTy, false);
   return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
 }
=20
@@ -1762,3 +1812,19 @@
=20
   return Value;
 }
+
+void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slo=
t) {
+  RunCleanupsScope Scope(*this);
+
+  CXXRecordDecl::field_iterator CurField =3D E->getLambdaClass()->field_be=
gin();
+  for (LambdaExpr::capture_init_iterator i =3D E->capture_init_begin(),
+                                         e =3D E->capture_init_end();
+       i !=3D e; ++i, ++CurField) {
+    // Emit initialization
+    LValue LV =3D EmitLValueForFieldInitialization(Slot.getAddr(), *CurFie=
ld, 0);
+    ArrayRef<VarDecl *> ArrayIndexes;
+    if (CurField->getType()->isArrayType())
+      ArrayIndexes =3D E->getCaptureInitIndexVars(i);
+    EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
+  }
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGExprComplex.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprComplex.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprComplex.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -64,11 +64,8 @@
   }
=20
   ComplexPairTy EmitLoadOfLValue(LValue LV) {
-    if (LV.isSimple())
-      return EmitLoadOfComplex(LV.getAddress(), LV.isVolatileQualified());
-
-    assert(LV.isPropertyRef() && "Unknown LValue type!");
-    return CGF.EmitLoadOfPropertyRefLValue(LV).getComplexVal();
+    assert(LV.isSimple() && "complex l-value must be simple");
+    return EmitLoadOfComplex(LV.getAddress(), LV.isVolatileQualified());
   }
=20
   /// EmitLoadOfComplex - Given a pointer to a complex value, emit code to=
 load
@@ -78,11 +75,8 @@
   /// EmitStoreThroughLValue - Given an l-value of complex type, store
   /// a complex number into it.
   void EmitStoreThroughLValue(ComplexPairTy Val, LValue LV) {
-    if (LV.isSimple())
-      return EmitStoreOfComplex(Val, LV.getAddress(), LV.isVolatileQualifi=
ed());
-
-    assert(LV.isPropertyRef() && "Unknown LValue type!");
-    CGF.EmitStoreThroughPropertyRefLValue(RValue::getComplex(Val), LV);
+    assert(LV.isSimple() && "complex l-value must be simple");
+    return EmitStoreOfComplex(Val, LV.getAddress(), LV.isVolatileQualified=
());
   }
=20
   /// EmitStoreOfComplex - Store the specified real/imag parts into the
@@ -117,13 +111,18 @@
   }
=20
   // l-values.
-  ComplexPairTy VisitDeclRefExpr(const Expr *E) { return EmitLoadOfLValue(=
E); }
-  ComplexPairTy VisitBlockDeclRefExpr(const Expr *E) { return EmitLoadOfLV=
alue(E); }
-  ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
+  ComplexPairTy VisitDeclRefExpr(DeclRefExpr *E) {
+    if (CodeGenFunction::ConstantEmission result =3D CGF.tryEmitAsConstant=
(E)) {
+      if (result.isReference())
+        return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
+
+      llvm::ConstantStruct *pair =3D
+        cast<llvm::ConstantStruct>(result.getValue());
+      return ComplexPairTy(pair->getOperand(0), pair->getOperand(1));
+    }
     return EmitLoadOfLValue(E);
   }
-  ComplexPairTy VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
-    assert(E->getObjectKind() =3D=3D OK_Ordinary);
+  ComplexPairTy VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
     return EmitLoadOfLValue(E);
   }
   ComplexPairTy VisitObjCMessageExpr(ObjCMessageExpr *E) {
@@ -137,6 +136,10 @@
     return CGF.getOpaqueRValueMapping(E).getComplexVal();
   }
=20
+  ComplexPairTy VisitPseudoObjectExpr(PseudoObjectExpr *E) {
+    return CGF.EmitPseudoObjectRValue(E).getComplexVal();
+  }
+
   // FIXME: CompoundLiteralExpr
=20
   ComplexPairTy EmitCast(CastExpr::CastKind CK, Expr *Op, QualType DestTy);
@@ -185,7 +188,9 @@
     return Visit(DAE->getExpr());
   }
   ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
-    return CGF.EmitExprWithCleanups(E).getComplexVal();
+    CGF.enterFullExpression(E);
+    CodeGenFunction::RunCleanupsScope Scope(CGF);
+    return Visit(E->getSubExpr());
   }
   ComplexPairTy VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
     assert(E->getType()->isAnyComplexType() && "Expected complex type!");
@@ -265,6 +270,10 @@
=20
   ComplexPairTy VisitInitListExpr(InitListExpr *E);
=20
+  ComplexPairTy VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
+    return EmitLoadOfLValue(E);
+  }
+
   ComplexPairTy VisitVAArgExpr(VAArgExpr *E);
=20
   ComplexPairTy VisitAtomicExpr(AtomicExpr *E) {
@@ -362,12 +371,10 @@
   switch (CK) {
   case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
=20
-  case CK_GetObjCProperty: {
-    LValue LV =3D CGF.EmitLValue(Op);
-    assert(LV.isPropertyRef() && "Unknown LValue type!");
-    return CGF.EmitLoadOfPropertyRefLValue(LV).getComplexVal();
-  }
-
+  // Atomic to non-atomic casts may be more than a no-op for some platform=
s and
+  // for some types.
+  case CK_AtomicToNonAtomic:
+  case CK_NonAtomicToAtomic:
   case CK_NoOp:
   case CK_LValueToRValue:
   case CK_UserDefinedConversion:
@@ -394,6 +401,7 @@
   case CK_BaseToDerivedMemberPointer:
   case CK_DerivedToBaseMemberPointer:
   case CK_MemberPointerToBoolean:
+  case CK_ReinterpretMemberPointer:
   case CK_ConstructorConversion:
   case CK_IntegralToPointer:
   case CK_PointerToIntegral:
@@ -418,6 +426,7 @@
   case CK_ARCConsumeObject:
   case CK_ARCReclaimReturnedObject:
   case CK_ARCExtendBlockObject:
+  case CK_CopyAndAutoreleaseBlockObject:
     llvm_unreachable("invalid cast kind for complex value");
=20
   case CK_FloatingRealToComplex:
@@ -631,11 +640,7 @@
   LValue LV =3D EmitCompoundAssignLValue(E, Func, Val);
=20
   // The result of an assignment in C is the assigned r-value.
-  if (!CGF.getContext().getLangOptions().CPlusPlus)
-    return Val;
-
-  // Objective-C property assignment never reloads the value following a s=
tore.
-  if (LV.isPropertyRef())
+  if (!CGF.getContext().getLangOpts().CPlusPlus)
     return Val;
=20
   // If the lvalue is non-volatile, return the computed value of the assig=
nment.
@@ -670,11 +675,7 @@
   LValue LV =3D EmitBinAssignLValue(E, Val);
=20
   // The result of an assignment in C is the assigned r-value.
-  if (!CGF.getContext().getLangOptions().CPlusPlus)
-    return Val;
-
-  // Objective-C property assignment never reloads the value following a s=
tore.
-  if (LV.isPropertyRef())
+  if (!CGF.getContext().getLangOpts().CPlusPlus)
     return Val;
=20
   // If the lvalue is non-volatile, return the computed value of the assig=
nment.
@@ -831,7 +832,6 @@
=20
   default:
     llvm_unreachable("unexpected complex compound assignment");
-    Op =3D 0;
   }
=20
   ComplexPairTy Val; // ignored
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGExprConstant.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprConstant.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprConstant.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -40,20 +40,27 @@
   bool Packed;
   CharUnits NextFieldOffsetInChars;
   CharUnits LLVMStructAlignment;
-  std::vector<llvm::Constant *> Elements;
+  SmallVector<llvm::Constant *, 32> Elements;
 public:
   static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *=
CGF,
                                      InitListExpr *ILE);
- =20
-private: =20
+  static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *=
CGF,
+                                     const APValue &Value, QualType ValTy);
+
+private:
   ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
     : CGM(CGM), CGF(CGF), Packed(false),=20
     NextFieldOffsetInChars(CharUnits::Zero()),
     LLVMStructAlignment(CharUnits::One()) { }
=20
-  bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
+  void AppendVTablePointer(BaseSubobject Base, llvm::Constant *VTable,
+                           const CXXRecordDecl *VTableClass);
+
+  void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
                    llvm::Constant *InitExpr);
=20
+  void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
+
   void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
                       llvm::ConstantInt *InitExpr);
=20
@@ -62,8 +69,12 @@
   void AppendTailPadding(CharUnits RecordSize);
=20
   void ConvertStructToPacked();
-                             =20
+
   bool Build(InitListExpr *ILE);
+  void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
+             llvm::Constant *VTable, const CXXRecordDecl *VTableClass,
+             CharUnits BaseOffset);
+  llvm::Constant *Finalize(QualType Ty);
=20
   CharUnits getAlignment(const llvm::Constant *C) const {
     if (Packed)  return CharUnits::One();
@@ -77,14 +88,36 @@
   }
 };
=20
-bool ConstStructBuilder::
+void ConstStructBuilder::AppendVTablePointer(BaseSubobject Base,
+                                             llvm::Constant *VTable,
+                                             const CXXRecordDecl *VTableCl=
ass) {
+  // Find the appropriate vtable within the vtable group.
+  uint64_t AddressPoint =3D
+    CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Ba=
se);
+  llvm::Value *Indices[] =3D {
+    llvm::ConstantInt::get(CGM.Int64Ty, 0),
+    llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
+  };
+  llvm::Constant *VTableAddressPoint =3D
+    llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
+
+  // Add the vtable at the start of the object.
+  AppendBytes(Base.getBaseOffset(), VTableAddressPoint);
+}
+
+void ConstStructBuilder::
 AppendField(const FieldDecl *Field, uint64_t FieldOffset,
             llvm::Constant *InitCst) {
-
   const ASTContext &Context =3D CGM.getContext();
=20
   CharUnits FieldOffsetInChars =3D Context.toCharUnitsFromBits(FieldOffset=
);
=20
+  AppendBytes(FieldOffsetInChars, InitCst);
+}
+
+void ConstStructBuilder::
+AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
+
   assert(NextFieldOffsetInChars <=3D FieldOffsetInChars
          && "Field offset mismatch!");
=20
@@ -99,14 +132,13 @@
=20
     // Convert the struct to a packed struct.
     ConvertStructToPacked();
-   =20
+
     AlignedNextFieldOffsetInChars =3D NextFieldOffsetInChars;
   }
=20
   if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
     // We need to append padding.
-    AppendPadding(
-        FieldOffsetInChars - NextFieldOffsetInChars);
+    AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
=20
     assert(NextFieldOffsetInChars =3D=3D FieldOffsetInChars &&
            "Did not add enough padding!");
@@ -118,14 +150,12 @@
   Elements.push_back(InitCst);
   NextFieldOffsetInChars =3D AlignedNextFieldOffsetInChars +
                            getSizeInChars(InitCst);
- =20
+
   if (Packed)
-    assert(LLVMStructAlignment =3D=3D CharUnits::One() &&=20
+    assert(LLVMStructAlignment =3D=3D CharUnits::One() &&
            "Packed struct not byte-aligned!");
   else
     LLVMStructAlignment =3D std::max(LLVMStructAlignment, FieldAlignment);
-
-  return true;
 }
=20
 void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
@@ -280,7 +310,7 @@
   if (PadSize.isZero())
     return;
=20
-  llvm::Type *Ty =3D llvm::Type::getInt8Ty(CGM.getLLVMContext());
+  llvm::Type *Ty =3D CGM.Int8Ty;
   if (PadSize > CharUnits::One())
     Ty =3D llvm::ArrayType::get(Ty, PadSize.getQuantity());
=20
@@ -300,7 +330,7 @@
 }
=20
 void ConstStructBuilder::ConvertStructToPacked() {
-  std::vector<llvm::Constant *> PackedElements;
+  SmallVector<llvm::Constant *, 16> PackedElements;
   CharUnits ElementOffsetInChars =3D CharUnits::Zero();
=20
   for (unsigned i =3D 0, e =3D Elements.size(); i !=3D e; ++i) {
@@ -316,7 +346,7 @@
       CharUnits NumChars =3D
         AlignedElementOffsetInChars - ElementOffsetInChars;
=20
-      llvm::Type *Ty =3D llvm::Type::getInt8Ty(CGM.getLLVMContext());
+      llvm::Type *Ty =3D CGM.Int8Ty;
       if (NumChars > CharUnits::One())
         Ty =3D llvm::ArrayType::get(Ty, NumChars.getQuantity());
=20
@@ -332,12 +362,17 @@
   assert(ElementOffsetInChars =3D=3D NextFieldOffsetInChars &&
          "Packing the struct changed its size!");
=20
-  Elements =3D PackedElements;
+  Elements.swap(PackedElements);
   LLVMStructAlignment =3D CharUnits::One();
   Packed =3D true;
 }
                            =20
 bool ConstStructBuilder::Build(InitListExpr *ILE) {
+  if (ILE->initializesStdInitializerList()) {
+    //CGM.ErrorUnsupported(ILE, "global std::initializer_list");
+    return false;
+  }
+
   RecordDecl *RD =3D ILE->getType()->getAs<RecordType>()->getDecl();
   const ASTRecordLayout &Layout =3D CGM.getContext().getASTRecordLayout(RD=
);
=20
@@ -382,8 +417,7 @@
    =20
     if (!Field->isBitField()) {
       // Handle non-bitfield members.
-      if (!AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit))
-        return false;
+      AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
     } else {
       // Otherwise we have a bitfield.
       AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
@@ -391,6 +425,106 @@
     }
   }
=20
+  return true;
+}
+
+namespace {
+struct BaseInfo {
+  BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
+    : Decl(Decl), Offset(Offset), Index(Index) {
+  }
+
+  const CXXRecordDecl *Decl;
+  CharUnits Offset;
+  unsigned Index;
+
+  bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
+};
+}
+
+void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
+                               bool IsPrimaryBase, llvm::Constant *VTable,
+                               const CXXRecordDecl *VTableClass,
+                               CharUnits Offset) {
+  const ASTRecordLayout &Layout =3D CGM.getContext().getASTRecordLayout(RD=
);
+
+  if (const CXXRecordDecl *CD =3D dyn_cast<CXXRecordDecl>(RD)) {
+    // Add a vtable pointer, if we need one and it hasn't already been add=
ed.
+    if (CD->isDynamicClass() && !IsPrimaryBase)
+      AppendVTablePointer(BaseSubobject(CD, Offset), VTable, VTableClass);
+
+    // Accumulate and sort bases, in order to visit them in address order,=
 which
+    // may not be the same as declaration order.
+    llvm::SmallVector<BaseInfo, 8> Bases;
+    Bases.reserve(CD->getNumBases());
+    unsigned BaseNo =3D 0;
+    for (CXXRecordDecl::base_class_const_iterator Base =3D CD->bases_begin=
(),
+         BaseEnd =3D CD->bases_end(); Base !=3D BaseEnd; ++Base, ++BaseNo)=
 {
+      assert(!Base->isVirtual() && "should not have virtual bases here");
+      const CXXRecordDecl *BD =3D Base->getType()->getAsCXXRecordDecl();
+      CharUnits BaseOffset =3D Layout.getBaseClassOffset(BD);
+      Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
+    }
+    std::stable_sort(Bases.begin(), Bases.end());
+
+    for (unsigned I =3D 0, N =3D Bases.size(); I !=3D N; ++I) {
+      BaseInfo &Base =3D Bases[I];
+
+      bool IsPrimaryBase =3D Layout.getPrimaryBase() =3D=3D Base.Decl;
+      Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
+            VTable, VTableClass, Offset + Base.Offset);
+    }
+  }
+
+  unsigned FieldNo =3D 0;
+  const FieldDecl *LastFD =3D 0;
+  bool IsMsStruct =3D RD->hasAttr<MsStructAttr>();
+  uint64_t OffsetBits =3D CGM.getContext().toBits(Offset);
+
+  for (RecordDecl::field_iterator Field =3D RD->field_begin(),
+       FieldEnd =3D RD->field_end(); Field !=3D FieldEnd; ++Field, ++Field=
No) {
+    if (IsMsStruct) {
+      // Zero-length bitfields following non-bitfield members are
+      // ignored:
+      if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((*Field), LastFD=
)) {
+        --FieldNo;
+        continue;
+      }
+      LastFD =3D (*Field);
+    }
+
+    // If this is a union, skip all the fields that aren't being initializ=
ed.
+    if (RD->isUnion() && Val.getUnionField() !=3D *Field)
+      continue;
+
+    // Don't emit anonymous bitfields, they just affect layout.
+    if (Field->isUnnamedBitfield()) {
+      LastFD =3D (*Field);
+      continue;
+    }
+
+    // Emit the value of the initializer.
+    const APValue &FieldValue =3D
+      RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
+    llvm::Constant *EltInit =3D
+      CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
+    assert(EltInit && "EmitConstantValue can't fail");
+
+    if (!Field->isBitField()) {
+      // Handle non-bitfield members.
+      AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, Elt=
Init);
+    } else {
+      // Otherwise we have a bitfield.
+      AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
+                     cast<llvm::ConstantInt>(EltInit));
+    }
+  }
+}
+
+llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
+  RecordDecl *RD =3D Ty->getAs<RecordType>()->getDecl();
+  const ASTRecordLayout &Layout =3D CGM.getContext().getASTRecordLayout(RD=
);
+
   CharUnits LayoutSizeInChars =3D Layout.getSize();
=20
   if (NextFieldOffsetInChars > LayoutSizeInChars) {
@@ -398,66 +532,85 @@
     // we must have a flexible array member at the end.
     assert(RD->hasFlexibleArrayMember() &&
            "Must have flexible array member if struct is bigger than type!=
");
-   =20
+
     // No tail padding is necessary.
-    return true;
+  } else {
+    // Append tail padding if necessary.
+    AppendTailPadding(LayoutSizeInChars);
+
+    CharUnits LLVMSizeInChars =3D
+      NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
+
+    // Check if we need to convert the struct to a packed struct.
+    if (NextFieldOffsetInChars <=3D LayoutSizeInChars &&
+        LLVMSizeInChars > LayoutSizeInChars) {
+      assert(!Packed && "Size mismatch!");
+
+      ConvertStructToPacked();
+      assert(NextFieldOffsetInChars <=3D LayoutSizeInChars &&
+             "Converting to packed did not help!");
+    }
+
+    assert(LayoutSizeInChars =3D=3D NextFieldOffsetInChars &&
+           "Tail padding mismatch!");
   }
=20
-  CharUnits LLVMSizeInChars =3D=20
-    NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
-
-  // Check if we need to convert the struct to a packed struct.
-  if (NextFieldOffsetInChars <=3D LayoutSizeInChars &&=20
-      LLVMSizeInChars > LayoutSizeInChars) {
-    assert(!Packed && "Size mismatch!");
-   =20
-    ConvertStructToPacked();
-    assert(NextFieldOffsetInChars <=3D LayoutSizeInChars &&
-           "Converting to packed did not help!");
-  }
-
-  // Append tail padding if necessary.
-  AppendTailPadding(LayoutSizeInChars);
-
-  assert(LayoutSizeInChars =3D=3D NextFieldOffsetInChars &&
-         "Tail padding mismatch!");
-
-  return true;
-}
- =20
-llvm::Constant *ConstStructBuilder::
-  BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, InitListExpr *ILE)=
 {
-  ConstStructBuilder Builder(CGM, CGF);
- =20
-  if (!Builder.Build(ILE))
-    return 0;
- =20
   // Pick the type to use.  If the type is layout identical to the Convert=
Type
   // type then use it, otherwise use whatever the builder produced for us.
   llvm::StructType *STy =3D
       llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
-                                               Builder.Elements,Builder.Pa=
cked);
-  llvm::Type *ILETy =3D CGM.getTypes().ConvertType(ILE->getType());
-  if (llvm::StructType *ILESTy =3D dyn_cast<llvm::StructType>(ILETy)) {
-    if (ILESTy->isLayoutIdentical(STy))
-      STy =3D ILESTy;
+                                               Elements, Packed);
+  llvm::Type *ValTy =3D CGM.getTypes().ConvertType(Ty);
+  if (llvm::StructType *ValSTy =3D dyn_cast<llvm::StructType>(ValTy)) {
+    if (ValSTy->isLayoutIdentical(STy))
+      STy =3D ValSTy;
   }
-   =20
-  llvm::Constant *Result =3D
-    llvm::ConstantStruct::get(STy, Builder.Elements);
- =20
-  assert(Builder.NextFieldOffsetInChars.RoundUpToAlignment(
-           Builder.getAlignment(Result)) =3D=3D
-         Builder.getSizeInChars(Result) && "Size mismatch!");
- =20
+
+  llvm::Constant *Result =3D llvm::ConstantStruct::get(STy, Elements);
+
+  assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) =
=3D=3D
+         getSizeInChars(Result) && "Size mismatch!");
+
   return Result;
 }
=20
- =20
+llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
+                                                CodeGenFunction *CGF,
+                                                InitListExpr *ILE) {
+  ConstStructBuilder Builder(CGM, CGF);
+
+  if (!Builder.Build(ILE))
+    return 0;
+
+  return Builder.Finalize(ILE->getType());
+}
+
+llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
+                                                CodeGenFunction *CGF,
+                                                const APValue &Val,
+                                                QualType ValTy) {
+  ConstStructBuilder Builder(CGM, CGF);
+
+  const RecordDecl *RD =3D ValTy->castAs<RecordType>()->getDecl();
+  const CXXRecordDecl *CD =3D dyn_cast<CXXRecordDecl>(RD);
+  llvm::Constant *VTable =3D 0;
+  if (CD && CD->isDynamicClass())
+    VTable =3D CGM.getVTables().GetAddrOfVTable(CD);
+
+  Builder.Build(Val, RD, false, VTable, CD, CharUnits::Zero());
+
+  return Builder.Finalize(ValTy);
+}
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                             ConstExprEmitter
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
- =20
+
+/// This class only needs to handle two cases:
+/// 1) Literals (this is used by APValue emission to emit literals).
+/// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
+///    constant fold these types).
 class ConstExprEmitter :
   public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
   CodeGenModule &CGM;
@@ -493,34 +646,6 @@
     return Visit(E->getInitializer());
   }
=20
-  llvm::Constant *VisitUnaryAddrOf(UnaryOperator *E) {
-    if (E->getType()->isMemberPointerType())
-      return CGM.getMemberPointerConstant(E);
-
-    return 0;
-  }
-   =20
-  llvm::Constant *VisitBinSub(BinaryOperator *E) {
-    // This must be a pointer/pointer subtraction.  This only happens for
-    // address of label.
-    if (!isa<AddrLabelExpr>(E->getLHS()->IgnoreParenNoopCasts(CGM.getConte=
xt())) ||
-       !isa<AddrLabelExpr>(E->getRHS()->IgnoreParenNoopCasts(CGM.getContex=
t())))
-      return 0;
-   =20
-    llvm::Constant *LHS =3D CGM.EmitConstantExpr(E->getLHS(),
-                                               E->getLHS()->getType(), CGF=
);
-    llvm::Constant *RHS =3D CGM.EmitConstantExpr(E->getRHS(),
-                                               E->getRHS()->getType(), CGF=
);
-
-    llvm::Type *ResultType =3D ConvertType(E->getType());
-    LHS =3D llvm::ConstantExpr::getPtrToInt(LHS, ResultType);
-    RHS =3D llvm::ConstantExpr::getPtrToInt(RHS, ResultType);
-       =20
-    // No need to divide by element size, since addr of label is always vo=
id*,
-    // which has size 1 in GNUish.
-    return llvm::ConstantExpr::getSub(LHS, RHS);
-  }
-   =20
   llvm::Constant *VisitCastExpr(CastExpr* E) {
     Expr *subExpr =3D E->getSubExpr();
     llvm::Constant *C =3D CGM.EmitConstantExpr(subExpr, subExpr->getType()=
, CGF);
@@ -536,8 +661,8 @@
=20
       // Build a struct with the union sub-element as the first member,
       // and padded to the appropriate size
-      std::vector<llvm::Constant*> Elts;
-      std::vector<llvm::Type*> Types;
+      SmallVector<llvm::Constant*, 2> Elts;
+      SmallVector<llvm::Type*, 2> Types;
       Elts.push_back(C);
       Types.push_back(C->getType());
       unsigned CurSize =3D CGM.getTargetData().getTypeAllocSize(C->getType=
());
@@ -545,7 +670,7 @@
=20
       assert(CurSize <=3D TotalSize && "Union size mismatch!");
       if (unsigned NumPadBytes =3D TotalSize - CurSize) {
-        llvm::Type *Ty =3D llvm::Type::getInt8Ty(VMContext);
+        llvm::Type *Ty =3D CGM.Int8Ty;
         if (NumPadBytes > 1)
           Ty =3D llvm::ArrayType::get(Ty, NumPadBytes);
=20
@@ -557,46 +682,41 @@
         llvm::StructType::get(C->getType()->getContext(), Types, false);
       return llvm::ConstantStruct::get(STy, Elts);
     }
-    case CK_NullToMemberPointer: {
-      const MemberPointerType *MPT =3D E->getType()->getAs<MemberPointerTy=
pe>();
-      return CGM.getCXXABI().EmitNullMemberPointer(MPT);
-    }
-
-    case CK_DerivedToBaseMemberPointer:
-    case CK_BaseToDerivedMemberPointer:
-      return CGM.getCXXABI().EmitMemberPointerConversion(C, E);
=20
     case CK_LValueToRValue:
+    case CK_AtomicToNonAtomic:
+    case CK_NonAtomicToAtomic:
     case CK_NoOp:
       return C;
=20
-    case CK_CPointerToObjCPointerCast:
-    case CK_BlockPointerToObjCPointerCast:
-    case CK_AnyPointerToBlockPointerCast:
-    case CK_LValueBitCast:
-    case CK_BitCast:
-      if (C->getType() =3D=3D destType) return C;
-      return llvm::ConstantExpr::getBitCast(C, destType);
+    case CK_Dependent: llvm_unreachable("saw dependent cast!");
=20
-    case CK_Dependent: llvm_unreachable("saw dependent cast!");
+    case CK_ReinterpretMemberPointer:
+    case CK_DerivedToBaseMemberPointer:
+    case CK_BaseToDerivedMemberPointer:
+      return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
=20
     // These will never be supported.
     case CK_ObjCObjectLValueCast:
-    case CK_GetObjCProperty:
-    case CK_ToVoid:
-    case CK_Dynamic:
     case CK_ARCProduceObject:
     case CK_ARCConsumeObject:
     case CK_ARCReclaimReturnedObject:
     case CK_ARCExtendBlockObject:
+    case CK_CopyAndAutoreleaseBlockObject:
       return 0;
=20
-    // These might need to be supported for constexpr.
+    // These don't need to be handled here because Evaluate knows how to
+    // evaluate them in the cases where they can be folded.
+    case CK_BitCast:
+    case CK_ToVoid:
+    case CK_Dynamic:
+    case CK_LValueBitCast:
+    case CK_NullToMemberPointer:
     case CK_UserDefinedConversion:
     case CK_ConstructorConversion:
-      return 0;
-
-    // These should eventually be supported.
+    case CK_CPointerToObjCPointerCast:
+    case CK_BlockPointerToObjCPointerCast:
+    case CK_AnyPointerToBlockPointerCast:
     case CK_ArrayToPointerDecay:
     case CK_FunctionToPointerDecay:
     case CK_BaseToDerived:
@@ -614,53 +734,17 @@
     case CK_IntegralComplexToBoolean:
     case CK_IntegralComplexCast:
     case CK_IntegralComplexToFloatingComplex:
+    case CK_PointerToIntegral:
+    case CK_PointerToBoolean:
+    case CK_NullToPointer:
+    case CK_IntegralCast:
+    case CK_IntegralToPointer:
+    case CK_IntegralToBoolean:
+    case CK_IntegralToFloating:
+    case CK_FloatingToIntegral:
+    case CK_FloatingToBoolean:
+    case CK_FloatingCast:
       return 0;
-
-    case CK_PointerToIntegral:
-      if (!E->getType()->isBooleanType())
-        return llvm::ConstantExpr::getPtrToInt(C, destType);
-      // fallthrough
-
-    case CK_PointerToBoolean:
-      return llvm::ConstantExpr::getICmp(llvm::CmpInst::ICMP_EQ, C,
-        llvm::ConstantPointerNull::get(cast<llvm::PointerType>(C->getType(=
))));
-
-    case CK_NullToPointer:
-      return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destTy=
pe));
-
-    case CK_IntegralCast: {
-      bool isSigned =3D subExpr->getType()->isSignedIntegerOrEnumerationTy=
pe();
-      return llvm::ConstantExpr::getIntegerCast(C, destType, isSigned);
-    }
-
-    case CK_IntegralToPointer: {
-      bool isSigned =3D subExpr->getType()->isSignedIntegerOrEnumerationTy=
pe();
-      C =3D llvm::ConstantExpr::getIntegerCast(C, CGM.IntPtrTy, isSigned);
-      return llvm::ConstantExpr::getIntToPtr(C, destType);
-    }
-
-    case CK_IntegralToBoolean:
-      return llvm::ConstantExpr::getICmp(llvm::CmpInst::ICMP_EQ, C,
-                             llvm::Constant::getNullValue(C->getType()));
-
-    case CK_IntegralToFloating:
-      if (subExpr->getType()->isSignedIntegerOrEnumerationType())
-        return llvm::ConstantExpr::getSIToFP(C, destType);
-      else
-        return llvm::ConstantExpr::getUIToFP(C, destType);
-
-    case CK_FloatingToIntegral:
-      if (E->getType()->isSignedIntegerOrEnumerationType())
-        return llvm::ConstantExpr::getFPToSI(C, destType);
-      else
-        return llvm::ConstantExpr::getFPToUI(C, destType);
-
-    case CK_FloatingToBoolean:
-      return llvm::ConstantExpr::getFCmp(llvm::CmpInst::FCMP_UNE, C,
-                             llvm::Constant::getNullValue(C->getType()));
-
-    case CK_FloatingCast:
-      return llvm::ConstantExpr::getFPCast(C, destType);
     }
     llvm_unreachable("Invalid CastKind");
   }
@@ -675,12 +759,13 @@
=20
   llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
     unsigned NumInitElements =3D ILE->getNumInits();
-    if (NumInitElements =3D=3D 1 && ILE->getType() =3D=3D ILE->getInit(0)-=
>getType() &&
+    if (NumInitElements =3D=3D 1 &&
+        CGM.getContext().hasSameUnqualifiedType(ILE->getType(),
+                                                ILE->getInit(0)->getType()=
) &&
         (isa<StringLiteral>(ILE->getInit(0)) ||
          isa<ObjCEncodeExpr>(ILE->getInit(0))))
       return Visit(ILE->getInit(0));
=20
-    std::vector<llvm::Constant*> Elts;
     llvm::ArrayType *AType =3D
         cast<llvm::ArrayType>(ConvertType(ILE->getType()));
     llvm::Type *ElemTy =3D AType->getElementType();
@@ -691,9 +776,11 @@
     unsigned NumInitableElts =3D std::min(NumInitElements, NumElements);
=20
     // Copy initializer elements.
-    unsigned i =3D 0;
+    std::vector<llvm::Constant*> Elts;
+    Elts.reserve(NumInitableElts + NumElements);
+
     bool RewriteType =3D false;
-    for (; i < NumInitableElts; ++i) {
+    for (unsigned i =3D 0; i < NumInitableElts; ++i) {
       Expr *Init =3D ILE->getInit(i);
       llvm::Constant *C =3D CGM.EmitConstantExpr(Init, Init->getType(), CG=
F);
       if (!C)
@@ -712,13 +799,13 @@
     if (!fillC)
       return 0;
     RewriteType |=3D (fillC->getType() !=3D ElemTy);
-    for (; i < NumElements; ++i)
-      Elts.push_back(fillC);
+    Elts.resize(NumElements, fillC);
=20
     if (RewriteType) {
       // FIXME: Try to avoid packing the array
       std::vector<llvm::Type*> Types;
-      for (unsigned i =3D 0; i < Elts.size(); ++i)
+      Types.reserve(NumInitableElts + NumElements);
+      for (unsigned i =3D 0, e =3D Elts.size(); i < e; ++i)
         Types.push_back(Elts[i]->getType());
       llvm::StructType *SType =3D llvm::StructType::get(AType->getContext(=
),
                                                             Types, true);
@@ -741,31 +828,6 @@
   }
=20
   llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
-    if (ILE->getType()->isAnyComplexType() && ILE->getNumInits() =3D=3D 2)=
 {
-      // Complex type with element initializers
-      Expr *Real =3D ILE->getInit(0);
-      Expr *Imag =3D ILE->getInit(1);
-      llvm::Constant *Complex[2];
-      Complex[0] =3D CGM.EmitConstantExpr(Real, Real->getType(), CGF);
-      if (!Complex[0])
-        return 0;
-      Complex[1] =3D CGM.EmitConstantExpr(Imag, Imag->getType(), CGF);
-      if (!Complex[1])
-        return 0;
-      llvm::StructType *STy =3D
-          cast<llvm::StructType>(ConvertType(ILE->getType()));
-      return llvm::ConstantStruct::get(STy, Complex);
-    }
-
-    if (ILE->getType()->isScalarType()) {
-      // We have a scalar in braces. Just use the first element.
-      if (ILE->getNumInits() > 0) {
-        Expr *Init =3D ILE->getInit(0);
-        return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
-      }
-      return CGM.EmitNullConstant(ILE->getType());
-    }
-
     if (ILE->getType()->isArrayType())
       return EmitArrayInitialization(ILE);
=20
@@ -775,11 +837,7 @@
     if (ILE->getType()->isUnionType())
       return EmitUnionInitialization(ILE);
=20
-    // If ILE was a constant vector, we would have handled it already.
-    if (ILE->getType()->isVectorType())
-      return 0;
-
-    llvm_unreachable("Unable to handle InitListExpr");
+    return 0;
   }
=20
   llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
@@ -817,13 +875,7 @@
   }
=20
   llvm::Constant *VisitStringLiteral(StringLiteral *E) {
-    assert(!E->getType()->isPointerType() && "Strings are always arrays");
-
-    // This must be a string initializing an array in a static initializer.
-    // Don't emit it as the address of the string, emit the string data it=
self
-    // as an inline array.
-    return llvm::ConstantArray::get(VMContext,
-                                    CGM.GetStringForStringLiteral(E), fals=
e);
+    return CGM.GetConstantArrayFromStringLiteral(E);
   }
=20
   llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
@@ -837,7 +889,7 @@
     // Resize the string to the right size, adding zeros at the end, or
     // truncating as needed.
     Str.resize(CAT->getSize().getZExtValue(), '\0');
-    return llvm::ConstantArray::get(VMContext, Str, false);
+    return llvm::ConstantDataArray::getString(VMContext, Str, false);
   }
=20
   llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
@@ -850,25 +902,8 @@
   }
=20
 public:
-  llvm::Constant *EmitLValue(Expr *E) {
-    switch (E->getStmtClass()) {
-    default: break;
-    case Expr::CompoundLiteralExprClass: {
-      // Note that due to the nature of compound literals, this is guarant=
eed
-      // to be the only use of the variable, so we just generate it here.
-      CompoundLiteralExpr *CLE =3D cast<CompoundLiteralExpr>(E);
-      llvm::Constant* C =3D Visit(CLE->getInitializer());
-      // FIXME: "Leaked" on failure.
-      if (C)
-        C =3D new llvm::GlobalVariable(CGM.getModule(), C->getType(),
-                                     E->getType().isConstant(CGM.getContex=
t()),
-                                     llvm::GlobalValue::InternalLinkage,
-                                     C, ".compoundliteral", 0, false,
-                          CGM.getContext().getTargetAddressSpace(E->getTyp=
e()));
-      return C;
-    }
-    case Expr::DeclRefExprClass: {
-      ValueDecl *Decl =3D cast<DeclRefExpr>(E)->getDecl();
+  llvm::Constant *EmitLValue(APValue::LValueBase LVBase) {
+    if (const ValueDecl *Decl =3D LVBase.dyn_cast<const ValueDecl*>()) {
       if (Decl->hasAttr<WeakRefAttr>())
         return CGM.GetWeakRefReference(Decl);
       if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(Decl))
@@ -884,7 +919,26 @@
           }
         }
       }
-      break;
+      return 0;
+    }
+
+    Expr *E =3D const_cast<Expr*>(LVBase.get<const Expr*>());
+    switch (E->getStmtClass()) {
+    default: break;
+    case Expr::CompoundLiteralExprClass: {
+      // Note that due to the nature of compound literals, this is guarant=
eed
+      // to be the only use of the variable, so we just generate it here.
+      CompoundLiteralExpr *CLE =3D cast<CompoundLiteralExpr>(E);
+      llvm::Constant* C =3D CGM.EmitConstantExpr(CLE->getInitializer(),
+                                               CLE->getType(), CGF);
+      // FIXME: "Leaked" on failure.
+      if (C)
+        C =3D new llvm::GlobalVariable(CGM.getModule(), C->getType(),
+                                     E->getType().isConstant(CGM.getContex=
t()),
+                                     llvm::GlobalValue::InternalLinkage,
+                                     C, ".compoundliteral", 0, false,
+                          CGM.getContext().getTargetAddressSpace(E->getTyp=
e()));
+      return C;
     }
     case Expr::StringLiteralClass:
       return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E)=
);
@@ -915,7 +969,7 @@
     }
     case Expr::CallExprClass: {
       CallExpr* CE =3D cast<CallExpr>(E);
-      unsigned builtin =3D CE->isBuiltinCall(CGM.getContext());
+      unsigned builtin =3D CE->isBuiltinCall();
       if (builtin !=3D
             Builtin::BI__builtin___CFStringMakeConstantString &&
           builtin !=3D
@@ -939,6 +993,15 @@
=20
       return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_s=
tr());
     }
+    case Expr::CXXTypeidExprClass: {
+      CXXTypeidExpr *Typeid =3D cast<CXXTypeidExpr>(E);
+      QualType T;
+      if (Typeid->isTypeOperand())
+        T =3D Typeid->getTypeOperand();
+      else
+        T =3D Typeid->getExprOperand()->getType();
+      return CGM.GetAddrOfRTTIDescriptor(T);
+    }
     }
=20
     return 0;
@@ -947,6 +1010,31 @@
=20
 }  // end anonymous namespace.
=20
+llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
+                                                CodeGenFunction *CGF) {
+  if (const APValue *Value =3D D.evaluateValue())
+    return EmitConstantValueForMemory(*Value, D.getType(), CGF);
+
+  // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
+  // reference is a constant expression, and the reference binds to a temp=
orary,
+  // then constant initialization is performed. ConstExprEmitter will
+  // incorrectly emit a prvalue constant in this case, and the calling code
+  // interprets that as the (pointer) value of the reference, rather than =
the
+  // desired value of the referee.
+  if (D.getType()->isReferenceType())
+    return 0;
+
+  const Expr *E =3D D.getInit();
+  assert(E && "No initializer to emit");
+
+  llvm::Constant* C =3D ConstExprEmitter(*this, CGF).Visit(const_cast<Expr=
*>(E));
+  if (C && C->getType()->isIntegerTy(1)) {
+    llvm::Type *BoolTy =3D getTypes().ConvertTypeForMem(E->getType());
+    C =3D llvm::ConstantExpr::getZExt(C, BoolTy);
+  }
+  return C;
+}
+
 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
                                                 QualType DestType,
                                                 CodeGenFunction *CGF) {
@@ -957,130 +1045,14 @@
   if (DestType->isReferenceType())
     Success =3D E->EvaluateAsLValue(Result, Context);
   else
-    Success =3D E->Evaluate(Result, Context);
+    Success =3D E->EvaluateAsRValue(Result, Context);
=20
-  if (Success && !Result.HasSideEffects) {
-    switch (Result.Val.getKind()) {
-    case APValue::Uninitialized:
-      llvm_unreachable("Constant expressions should be initialized.");
-    case APValue::LValue: {
-      llvm::Type *DestTy =3D getTypes().ConvertTypeForMem(DestType);
-      llvm::Constant *Offset =3D
-        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
-                               Result.Val.getLValueOffset().getQuantity());
+  llvm::Constant *C =3D 0;
+  if (Success && !Result.HasSideEffects)
+    C =3D EmitConstantValue(Result.Val, DestType, CGF);
+  else
+    C =3D ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
=20
-      llvm::Constant *C;
-      if (const Expr *LVBase =3D Result.Val.getLValueBase()) {
-        C =3D ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LV=
Base));
-
-        // Apply offset if necessary.
-        if (!Offset->isNullValue()) {
-          llvm::Type *Type =3D llvm::Type::getInt8PtrTy(VMContext);
-          llvm::Constant *Casted =3D llvm::ConstantExpr::getBitCast(C, Typ=
e);
-          Casted =3D llvm::ConstantExpr::getGetElementPtr(Casted, Offset);
-          C =3D llvm::ConstantExpr::getBitCast(Casted, C->getType());
-        }
-
-        // Convert to the appropriate type; this could be an lvalue for
-        // an integer.
-        if (isa<llvm::PointerType>(DestTy))
-          return llvm::ConstantExpr::getBitCast(C, DestTy);
-
-        return llvm::ConstantExpr::getPtrToInt(C, DestTy);
-      } else {
-        C =3D Offset;
-
-        // Convert to the appropriate type; this could be an lvalue for
-        // an integer.
-        if (isa<llvm::PointerType>(DestTy))
-          return llvm::ConstantExpr::getIntToPtr(C, DestTy);
-
-        // If the types don't match this should only be a truncate.
-        if (C->getType() !=3D DestTy)
-          return llvm::ConstantExpr::getTrunc(C, DestTy);
-
-        return C;
-      }
-    }
-    case APValue::Int: {
-      llvm::Constant *C =3D llvm::ConstantInt::get(VMContext,
-                                                 Result.Val.getInt());
-
-      if (C->getType()->isIntegerTy(1)) {
-        llvm::Type *BoolTy =3D getTypes().ConvertTypeForMem(E->getType());
-        C =3D llvm::ConstantExpr::getZExt(C, BoolTy);
-      }
-      return C;
-    }
-    case APValue::ComplexInt: {
-      llvm::Constant *Complex[2];
-
-      Complex[0] =3D llvm::ConstantInt::get(VMContext,
-                                          Result.Val.getComplexIntReal());
-      Complex[1] =3D llvm::ConstantInt::get(VMContext,
-                                          Result.Val.getComplexIntImag());
-
-      // FIXME: the target may want to specify that this is packed.
-      llvm::StructType *STy =3D llvm::StructType::get(Complex[0]->getType(=
),
-                                                    Complex[1]->getType(),
-                                                    NULL);
-      return llvm::ConstantStruct::get(STy, Complex);
-    }
-    case APValue::Float: {
-      const llvm::APFloat &Init =3D Result.Val.getFloat();
-      if (&Init.getSemantics() =3D=3D &llvm::APFloat::IEEEhalf)
-        return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
-      else
-        return llvm::ConstantFP::get(VMContext, Init);
-    }
-    case APValue::ComplexFloat: {
-      llvm::Constant *Complex[2];
-
-      Complex[0] =3D llvm::ConstantFP::get(VMContext,
-                                         Result.Val.getComplexFloatReal());
-      Complex[1] =3D llvm::ConstantFP::get(VMContext,
-                                         Result.Val.getComplexFloatImag());
-
-      // FIXME: the target may want to specify that this is packed.
-      llvm::StructType *STy =3D llvm::StructType::get(Complex[0]->getType(=
),
-                                                    Complex[1]->getType(),
-                                                    NULL);
-      return llvm::ConstantStruct::get(STy, Complex);
-    }
-    case APValue::Vector: {
-      SmallVector<llvm::Constant *, 4> Inits;
-      unsigned NumElts =3D Result.Val.getVectorLength();
-
-      if (Context.getLangOptions().AltiVec &&
-          isa<CastExpr>(E) &&
-          cast<CastExpr>(E)->getCastKind() =3D=3D CK_VectorSplat) {
-        // AltiVec vector initialization with a single literal
-        APValue &Elt =3D Result.Val.getVectorElt(0);
-
-        llvm::Constant* InitValue =3D Elt.isInt()
-          ? cast<llvm::Constant>
-              (llvm::ConstantInt::get(VMContext, Elt.getInt()))
-          : cast<llvm::Constant>
-              (llvm::ConstantFP::get(VMContext, Elt.getFloat()));
-
-        for (unsigned i =3D 0; i !=3D NumElts; ++i)
-          Inits.push_back(InitValue);
-
-      } else {
-        for (unsigned i =3D 0; i !=3D NumElts; ++i) {
-          APValue &Elt =3D Result.Val.getVectorElt(i);
-          if (Elt.isInt())
-            Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()=
));
-          else
-            Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat(=
)));
-        }
-      }
-      return llvm::ConstantVector::get(Inits);
-    }
-    }
-  }
-
-  llvm::Constant* C =3D ConstExprEmitter(*this, CGF).Visit(const_cast<Expr=
*>(E));
   if (C && C->getType()->isIntegerTy(1)) {
     llvm::Type *BoolTy =3D getTypes().ConvertTypeForMem(E->getType());
     C =3D llvm::ConstantExpr::getZExt(C, BoolTy);
@@ -1088,11 +1060,192 @@
   return C;
 }
=20
-static uint64_t getFieldOffset(ASTContext &C, const FieldDecl *field) {
-  const ASTRecordLayout &layout =3D C.getASTRecordLayout(field->getParent(=
));
-  return layout.getFieldOffset(field->getFieldIndex());
+llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value,
+                                                 QualType DestType,
+                                                 CodeGenFunction *CGF) {
+  switch (Value.getKind()) {
+  case APValue::Uninitialized:
+    llvm_unreachable("Constant expressions should be initialized.");
+  case APValue::LValue: {
+    llvm::Type *DestTy =3D getTypes().ConvertTypeForMem(DestType);
+    llvm::Constant *Offset =3D
+      llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity(=
));
+
+    llvm::Constant *C;
+    if (APValue::LValueBase LVBase =3D Value.getLValueBase()) {
+      // An array can be represented as an lvalue referring to the base.
+      if (isa<llvm::ArrayType>(DestTy)) {
+        assert(Offset->isNullValue() && "offset on array initializer");
+        return ConstExprEmitter(*this, CGF).Visit(
+          const_cast<Expr*>(LVBase.get<const Expr*>()));
+      }
+
+      C =3D ConstExprEmitter(*this, CGF).EmitLValue(LVBase);
+
+      // Apply offset if necessary.
+      if (!Offset->isNullValue()) {
+        llvm::Constant *Casted =3D llvm::ConstantExpr::getBitCast(C, Int8P=
trTy);
+        Casted =3D llvm::ConstantExpr::getGetElementPtr(Casted, Offset);
+        C =3D llvm::ConstantExpr::getBitCast(Casted, C->getType());
+      }
+
+      // Convert to the appropriate type; this could be an lvalue for
+      // an integer.
+      if (isa<llvm::PointerType>(DestTy))
+        return llvm::ConstantExpr::getBitCast(C, DestTy);
+
+      return llvm::ConstantExpr::getPtrToInt(C, DestTy);
+    } else {
+      C =3D Offset;
+
+      // Convert to the appropriate type; this could be an lvalue for
+      // an integer.
+      if (isa<llvm::PointerType>(DestTy))
+        return llvm::ConstantExpr::getIntToPtr(C, DestTy);
+
+      // If the types don't match this should only be a truncate.
+      if (C->getType() !=3D DestTy)
+        return llvm::ConstantExpr::getTrunc(C, DestTy);
+
+      return C;
+    }
+  }
+  case APValue::Int:
+    return llvm::ConstantInt::get(VMContext, Value.getInt());
+  case APValue::ComplexInt: {
+    llvm::Constant *Complex[2];
+
+    Complex[0] =3D llvm::ConstantInt::get(VMContext,
+                                        Value.getComplexIntReal());
+    Complex[1] =3D llvm::ConstantInt::get(VMContext,
+                                        Value.getComplexIntImag());
+
+    // FIXME: the target may want to specify that this is packed.
+    llvm::StructType *STy =3D llvm::StructType::get(Complex[0]->getType(),
+                                                  Complex[1]->getType(),
+                                                  NULL);
+    return llvm::ConstantStruct::get(STy, Complex);
+  }
+  case APValue::Float: {
+    const llvm::APFloat &Init =3D Value.getFloat();
+    if (&Init.getSemantics() =3D=3D &llvm::APFloat::IEEEhalf)
+      return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
+    else
+      return llvm::ConstantFP::get(VMContext, Init);
+  }
+  case APValue::ComplexFloat: {
+    llvm::Constant *Complex[2];
+
+    Complex[0] =3D llvm::ConstantFP::get(VMContext,
+                                       Value.getComplexFloatReal());
+    Complex[1] =3D llvm::ConstantFP::get(VMContext,
+                                       Value.getComplexFloatImag());
+
+    // FIXME: the target may want to specify that this is packed.
+    llvm::StructType *STy =3D llvm::StructType::get(Complex[0]->getType(),
+                                                  Complex[1]->getType(),
+                                                  NULL);
+    return llvm::ConstantStruct::get(STy, Complex);
+  }
+  case APValue::Vector: {
+    SmallVector<llvm::Constant *, 4> Inits;
+    unsigned NumElts =3D Value.getVectorLength();
+
+    for (unsigned i =3D 0; i !=3D NumElts; ++i) {
+      const APValue &Elt =3D Value.getVectorElt(i);
+      if (Elt.isInt())
+        Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
+      else
+        Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
+    }
+    return llvm::ConstantVector::get(Inits);
+  }
+  case APValue::AddrLabelDiff: {
+    const AddrLabelExpr *LHSExpr =3D Value.getAddrLabelDiffLHS();
+    const AddrLabelExpr *RHSExpr =3D Value.getAddrLabelDiffRHS();
+    llvm::Constant *LHS =3D EmitConstantExpr(LHSExpr, LHSExpr->getType(), =
CGF);
+    llvm::Constant *RHS =3D EmitConstantExpr(RHSExpr, RHSExpr->getType(), =
CGF);
+
+    // Compute difference
+    llvm::Type *ResultType =3D getTypes().ConvertType(DestType);
+    LHS =3D llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
+    RHS =3D llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
+    llvm::Constant *AddrLabelDiff =3D llvm::ConstantExpr::getSub(LHS, RHS);
+
+    // LLVM is a bit sensitive about the exact format of the
+    // address-of-label difference; make sure to truncate after
+    // the subtraction.
+    return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType=
);
+  }
+  case APValue::Struct:
+  case APValue::Union:
+    return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
+  case APValue::Array: {
+    const ArrayType *CAT =3D Context.getAsArrayType(DestType);
+    unsigned NumElements =3D Value.getArraySize();
+    unsigned NumInitElts =3D Value.getArrayInitializedElts();
+
+    std::vector<llvm::Constant*> Elts;
+    Elts.reserve(NumElements);
+
+    // Emit array filler, if there is one.
+    llvm::Constant *Filler =3D 0;
+    if (Value.hasArrayFiller())
+      Filler =3D EmitConstantValueForMemory(Value.getArrayFiller(),
+                                          CAT->getElementType(), CGF);
+
+    // Emit initializer elements.
+    llvm::Type *CommonElementType =3D 0;
+    for (unsigned I =3D 0; I < NumElements; ++I) {
+      llvm::Constant *C =3D Filler;
+      if (I < NumInitElts)
+        C =3D EmitConstantValueForMemory(Value.getArrayInitializedElt(I),
+                                       CAT->getElementType(), CGF);
+      if (I =3D=3D 0)
+        CommonElementType =3D C->getType();
+      else if (C->getType() !=3D CommonElementType)
+        CommonElementType =3D 0;
+      Elts.push_back(C);
+    }
+
+    if (!CommonElementType) {
+      // FIXME: Try to avoid packing the array
+      std::vector<llvm::Type*> Types;
+      Types.reserve(NumElements);
+      for (unsigned i =3D 0, e =3D Elts.size(); i < e; ++i)
+        Types.push_back(Elts[i]->getType());
+      llvm::StructType *SType =3D llvm::StructType::get(VMContext, Types, =
true);
+      return llvm::ConstantStruct::get(SType, Elts);
+    }
+
+    llvm::ArrayType *AType =3D
+      llvm::ArrayType::get(CommonElementType, NumElements);
+    return llvm::ConstantArray::get(AType, Elts);
+  }
+  case APValue::MemberPointer:
+    return getCXXABI().EmitMemberPointer(Value, DestType);
+  }
+  llvm_unreachable("Unknown APValue kind");
 }
-   =20
+
+llvm::Constant *
+CodeGenModule::EmitConstantValueForMemory(const APValue &Value,
+                                          QualType DestType,
+                                          CodeGenFunction *CGF) {
+  llvm::Constant *C =3D EmitConstantValue(Value, DestType, CGF);
+  if (C->getType()->isIntegerTy(1)) {
+    llvm::Type *BoolTy =3D getTypes().ConvertTypeForMem(DestType);
+    C =3D llvm::ConstantExpr::getZExt(C, BoolTy);
+  }
+  return C;
+}
+
+llvm::Constant *
+CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr =
*E) {
+  assert(E->isFileScope() && "not a file-scope compound literal expr");
+  return ConstExprEmitter(*this, 0).EmitLValue(E);
+}
+
 llvm::Constant *
 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
   // Member pointer constants always have a very particular form.
@@ -1104,25 +1257,14 @@
     return getCXXABI().EmitMemberPointer(method);
=20
   // Otherwise, a member data pointer.
-  uint64_t fieldOffset;
-  if (const FieldDecl *field =3D dyn_cast<FieldDecl>(decl))
-    fieldOffset =3D getFieldOffset(getContext(), field);
-  else {
-    const IndirectFieldDecl *ifield =3D cast<IndirectFieldDecl>(decl);
-
-    fieldOffset =3D 0;
-    for (IndirectFieldDecl::chain_iterator ci =3D ifield->chain_begin(),
-           ce =3D ifield->chain_end(); ci !=3D ce; ++ci)
-      fieldOffset +=3D getFieldOffset(getContext(), cast<FieldDecl>(*ci));
-  }
-
+  uint64_t fieldOffset =3D getContext().getFieldOffset(decl);
   CharUnits chars =3D getContext().toCharUnitsFromBits((int64_t) fieldOffs=
et);
   return getCXXABI().EmitMemberDataPointer(type, chars);
 }
=20
 static void
 FillInNullDataMemberPointers(CodeGenModule &CGM, QualType T,
-                             std::vector<llvm::Constant *> &Elements,
+                             SmallVectorImpl<llvm::Constant *> &Elements,
                              uint64_t StartOffset) {
   assert(StartOffset % CGM.getContext().getCharWidth() =3D=3D 0 &&=20
          "StartOffset not byte aligned!");
@@ -1189,8 +1331,7 @@
=20
     // FIXME: hardcodes Itanium member pointer representation!
     llvm::Constant *NegativeOne =3D
-      llvm::ConstantInt::get(llvm::Type::getInt8Ty(CGM.getLLVMContext()),
-                             -1ULL, /*isSigned*/true);
+      llvm::ConstantInt::get(CGM.Int8Ty, -1ULL, /*isSigned*/true);
=20
     // Fill in the null data member pointer.
     for (CharUnits I =3D StartIndex; I !=3D EndIndex; ++I)
@@ -1238,13 +1379,17 @@
   for (RecordDecl::field_iterator I =3D record->field_begin(),
          E =3D record->field_end(); I !=3D E; ++I) {
     const FieldDecl *field =3D *I;
-   =20
-    // Ignore bit fields.
-    if (field->isBitField())
-      continue;
-   =20
-    unsigned fieldIndex =3D layout.getLLVMFieldNo(field);
-    elements[fieldIndex] =3D CGM.EmitNullConstant(field->getType());
+
+    // Fill in non-bitfields. (Bitfields always use a zero pattern, which =
we
+    // will fill in later.)
+    if (!field->isBitField()) {
+      unsigned fieldIndex =3D layout.getLLVMFieldNo(field);
+      elements[fieldIndex] =3D CGM.EmitNullConstant(field->getType());
+    }
+
+    // For unions, stop after the first named field.
+    if (record->isUnion() && field->getDeclName())
+      break;
   }
=20
   // Fill in the virtual bases, if we're working with the complete object.
@@ -1299,14 +1444,13 @@
   unsigned numBaseElements =3D baseArrayType->getNumElements();
=20
   // Fill in null data member pointers.
-  std::vector<llvm::Constant *> baseElements(numBaseElements);
+  SmallVector<llvm::Constant *, 16> baseElements(numBaseElements);
   FillInNullDataMemberPointers(CGM, CGM.getContext().getTypeDeclType(base),
                                baseElements, 0);
=20
   // Now go through all other elements and zero them out.
   if (numBaseElements) {
-    llvm::Type *i8 =3D llvm::Type::getInt8Ty(CGM.getLLVMContext());
-    llvm::Constant *i8_zero =3D llvm::Constant::getNullValue(i8);
+    llvm::Constant *i8_zero =3D llvm::Constant::getNullValue(CGM.Int8Ty);
     for (unsigned i =3D 0; i !=3D numBaseElements; ++i) {
       if (!baseElements[i])
         baseElements[i] =3D i8_zero;
@@ -1321,17 +1465,18 @@
     return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
    =20
   if (const ConstantArrayType *CAT =3D Context.getAsConstantArrayType(T)) {
+    llvm::ArrayType *ATy =3D
+      cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
=20
     QualType ElementTy =3D CAT->getElementType();
=20
     llvm::Constant *Element =3D EmitNullConstant(ElementTy);
     unsigned NumElements =3D CAT->getSize().getZExtValue();
-    std::vector<llvm::Constant *> Array(NumElements);
-    for (unsigned i =3D 0; i !=3D NumElements; ++i)
-      Array[i] =3D Element;
-
-    llvm::ArrayType *ATy =3D
-      cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
+   =20
+    if (Element->isNullValue())
+      return llvm::ConstantAggregateZero::get(ATy);
+   =20
+    SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
     return llvm::ConstantArray::get(ATy, Array);
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGExprScalar.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGExprScalar.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -177,6 +177,9 @@
   Value *VisitCharacterLiteral(const CharacterLiteral *E) {
     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()=
);
   }
+  Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
+    return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()=
);
+  }
   Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
     return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue()=
);
   }
@@ -197,6 +200,10 @@
     return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLeng=
th());
   }
=20
+  Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
+    return CGF.EmitPseudoObjectRValue(E).getScalarVal();
+  }
+
   Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
     if (E->isGLValue())
       return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
@@ -204,33 +211,17 @@
     // Otherwise, assume the mapping is the scalar directly.
     return CGF.getOpaqueRValueMapping(E).getScalarVal();
   }
-   =20
+
   // l-values.
   Value *VisitDeclRefExpr(DeclRefExpr *E) {
-    Expr::EvalResult Result;
-    if (!E->Evaluate(Result, CGF.getContext()))
-      return EmitLoadOfLValue(E);
-
-    assert(!Result.HasSideEffects && "Constant declref with side-effect?!"=
);
-
-    llvm::Constant *C;
-    if (Result.Val.isInt())
-      C =3D Builder.getInt(Result.Val.getInt());
-    else if (Result.Val.isFloat())
-      C =3D llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
-    else
-      return EmitLoadOfLValue(E);
-
-    // Make sure we emit a debug reference to the global variable.
-    if (VarDecl *VD =3D dyn_cast<VarDecl>(E->getDecl())) {
-      if (!CGF.getContext().DeclMustBeEmitted(VD))
-        CGF.EmitDeclRefExprDbgValue(E, C);
-    } else if (isa<EnumConstantDecl>(E->getDecl())) {
-      CGF.EmitDeclRefExprDbgValue(E, C);
+    if (CodeGenFunction::ConstantEmission result =3D CGF.tryEmitAsConstant=
(E)) {
+      if (result.isReference())
+        return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
+      return result.getValue();
     }
-
-    return C;
+    return EmitLoadOfLValue(E);
   }
+
   Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
     return CGF.EmitObjCSelectorExpr(E);
   }
@@ -240,11 +231,6 @@
   Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
     return EmitLoadOfLValue(E);
   }
-  Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
-    assert(E->getObjectKind() =3D=3D OK_Ordinary &&
-           "reached property reference without lvalue-to-rvalue");
-    return EmitLoadOfLValue(E);
-  }
   Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
     if (E->getMethodDecl() &&=20
         E->getMethodDecl()->getResultType()->isReferenceType())
@@ -287,8 +273,6 @@
=20
   Value *VisitStmtExpr(const StmtExpr *E);
=20
-  Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
-
   // Unary Operators.
   Value *VisitUnaryPostDec(const UnaryOperator *E) {
     LValue LV =3D EmitLValue(E->getSubExpr());
@@ -354,7 +338,9 @@
   }
=20
   Value *VisitExprWithCleanups(ExprWithCleanups *E) {
-    return CGF.EmitExprWithCleanups(E).getScalarVal();
+    CGF.enterFullExpression(E);
+    CodeGenFunction::RunCleanupsScope Scope(CGF);
+    return Visit(E->getSubExpr());
   }
   Value *VisitCXXNewExpr(const CXXNewExpr *E) {
     return CGF.EmitCXXNewExpr(E);
@@ -405,7 +391,7 @@
   // Binary Operators.
   Value *EmitMul(const BinOpInfo &Ops) {
     if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
-      switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior(=
)) {
+      switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
       case LangOptions::SOB_Undefined:
         return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
       case LangOptions::SOB_Defined:
@@ -420,7 +406,7 @@
     return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
   }
   bool isTrapvOverflowBehavior() {
-    return CGF.getContext().getLangOptions().getSignedOverflowBehavior()=20
+    return CGF.getContext().getLangOpts().getSignedOverflowBehavior()=20
                =3D=3D LangOptions::SOB_Trapping;=20
   }
   /// Create a binary op that checks for overflow.
@@ -512,6 +498,15 @@
   Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
     return CGF.EmitObjCStringLiteral(E);
   }
+  Value *VisitObjCNumericLiteral(ObjCNumericLiteral *E) {
+    return CGF.EmitObjCNumericLiteral(E);
+  }
+  Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
+    return CGF.EmitObjCArrayLiteral(E);
+  }
+  Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
+    return CGF.EmitObjCDictionaryLiteral(E);
+  }
   Value *VisitAsTypeExpr(AsTypeExpr *CE);
   Value *VisitAtomicExpr(AtomicExpr *AE);
 };
@@ -559,7 +554,7 @@
   if (SrcType->isHalfType()) {
     Src =3D Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::conve=
rt_from_fp16), Src);
     SrcType =3D CGF.getContext().FloatTy;
-    SrcTy =3D llvm::Type::getFloatTy(VMContext);
+    SrcTy =3D CGF.FloatTy;
   }
=20
   // Handle conversions to bool first, they are special: comparisons again=
st 0.
@@ -609,12 +604,9 @@
     UnV =3D Builder.CreateInsertElement(UnV, Elt, Idx);
=20
     // Splat the element across to all elements
-    SmallVector<llvm::Constant*, 16> Args;
     unsigned NumElements =3D cast<llvm::VectorType>(DstTy)->getNumElements=
();
-    for (unsigned i =3D 0; i !=3D NumElements; ++i)
-      Args.push_back(Builder.getInt32(0));
-
-    llvm::Constant *Mask =3D llvm::ConstantVector::get(Args);
+    llvm::Constant *Mask =3D llvm::ConstantVector::getSplat(NumElements,
+                                                          Builder.getInt32=
(0));
     llvm::Value *Yay =3D Builder.CreateShuffleVector(UnV, UnV, Mask, "spla=
t");
     return Yay;
   }
@@ -630,7 +622,7 @@
=20
   // Cast to half via float
   if (DstType->isHalfType())
-    DstTy =3D llvm::Type::getFloatTy(VMContext);
+    DstTy =3D CGF.FloatTy;
=20
   if (isa<llvm::IntegerType>(SrcTy)) {
     bool InputSigned =3D SrcType->isSignedIntegerOrEnumerationType();
@@ -748,11 +740,8 @@
                                        (1 << llvm::Log2_32(LHSElts))-1);
             =20
     // Mask off the high bits of each shuffle index.
-    SmallVector<llvm::Constant *, 32> MaskV;
-    for (unsigned i =3D 0, e =3D MTy->getNumElements(); i !=3D e; ++i)
-      MaskV.push_back(EltMask);
-   =20
-    Value* MaskBits =3D llvm::ConstantVector::get(MaskV);
+    Value *MaskBits =3D llvm::ConstantVector::getSplat(MTy->getNumElements=
(),
+                                                     EltMask);
     Mask =3D Builder.CreateAnd(Mask, MaskBits, "mask");
    =20
     // newv =3D undef
@@ -765,8 +754,8 @@
                                                         MTy->getNumElement=
s());
     Value* NewV =3D llvm::UndefValue::get(RTy);
     for (unsigned i =3D 0, e =3D MTy->getNumElements(); i !=3D e; ++i) {
-      Value *Indx =3D Builder.getInt32(i);
-      Indx =3D Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
+      Value *IIndx =3D Builder.getInt32(i);
+      Value *Indx =3D Builder.CreateExtractElement(Mask, IIndx, "shuf_idx"=
);
       Indx =3D Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
      =20
       // Handle vec3 special since the index will be off by one for the RH=
S.
@@ -778,7 +767,7 @@
         Indx =3D Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_id=
x");
       }
       Value *VExt =3D Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
-      NewV =3D Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
+      NewV =3D Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
     }
     return NewV;
   }
@@ -800,13 +789,13 @@
   return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
 }
 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
-  Expr::EvalResult Result;
-  if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
+  llvm::APSInt Value;
+  if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)=
) {
     if (E->isArrow())
       CGF.EmitScalarExpr(E->getBase());
     else
       EmitLValue(E->getBase());
-    return Builder.getInt(Result.Val.getInt());
+    return Builder.getInt(Value);
   }
=20
   // Emit debug info for aggregate now, if it was delayed to reduce=20
@@ -900,8 +889,7 @@
           if (CurIdx =3D=3D 0) {
             // insert into undef -> shuffle (src, undef)
             Args.push_back(C);
-            for (unsigned j =3D 1; j !=3D ResElts; ++j)
-              Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
+            Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
=20
             LHS =3D EI->getVectorOperand();
             RHS =3D V;
@@ -912,9 +900,8 @@
             for (unsigned j =3D 0; j !=3D CurIdx; ++j)
               Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
             Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
-            for (unsigned j =3D CurIdx + 1; j !=3D ResElts; ++j)
-              Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
-           =20
+            Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
+
             LHS =3D cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
             RHS =3D EI->getVectorOperand();
             VIsUndefShuffle =3D false;
@@ -958,8 +945,7 @@
         }
         for (unsigned j =3D 0, je =3D InitElts; j !=3D je; ++j)
           Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
-        for (unsigned j =3D CurIdx + InitElts; j !=3D ResElts; ++j)
-          Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
+        Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
=20
         if (VIsUndefShuffle)
           V =3D cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
@@ -973,8 +959,7 @@
     if (Args.empty()) {
       for (unsigned j =3D 0; j !=3D InitElts; ++j)
         Args.push_back(Builder.getInt32(j));
-      for (unsigned j =3D InitElts; j !=3D ResElts; ++j)
-        Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
+      Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
       llvm::Constant *Mask =3D llvm::ConstantVector::get(Args);
       Init =3D Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT=
),
                                          Mask, "vext");
@@ -984,8 +969,7 @@
         Args.push_back(Builder.getInt32(j));
       for (unsigned j =3D 0; j !=3D InitElts; ++j)
         Args.push_back(Builder.getInt32(j+Offset));
-      for (unsigned j =3D CurIdx + InitElts; j !=3D ResElts; ++j)
-        Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
+      Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
     }
=20
     // If V is undef, make sure it ends up on the RHS of the shuffle to aid
@@ -1053,7 +1037,7 @@
     Value *V =3D EmitLValue(E).getAddress();
     V =3D Builder.CreateBitCast(V,=20
                           ConvertType(CGF.getContext().getPointerType(Dest=
Ty)));
-    return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy));
+    return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
   }
=20
   case CK_CPointerToObjCPointerCast:
@@ -1063,6 +1047,8 @@
     Value *Src =3D Visit(const_cast<Expr*>(E));
     return Builder.CreateBitCast(Src, ConvertType(DestTy));
   }
+  case CK_AtomicToNonAtomic:
+  case CK_NonAtomicToAtomic:
   case CK_NoOp:
   case CK_UserDefinedConversion:
     return Visit(const_cast<Expr*>(E));
@@ -1130,6 +1116,7 @@
     return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
   }
=20
+  case CK_ReinterpretMemberPointer:
   case CK_BaseToDerivedMemberPointer:
   case CK_DerivedToBaseMemberPointer: {
     Value *Src =3D Visit(E);
@@ -1155,6 +1142,9 @@
   case CK_ARCExtendBlockObject:
     return CGF.EmitARCExtendBlockObject(E);
=20
+  case CK_CopyAndAutoreleaseBlockObject:
+    return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
+     =20
   case CK_FloatingRealToComplex:
   case CK_FloatingComplexCast:
   case CK_IntegralRealToComplex:
@@ -1164,15 +1154,6 @@
   case CK_ConstructorConversion:
   case CK_ToUnion:
     llvm_unreachable("scalar cast to non-scalar value");
-    break;
-
-  case CK_GetObjCProperty: {
-    assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
-    assert(E->isGLValue() && E->getObjectKind() =3D=3D OK_ObjCProperty &&
-           "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
-    RValue RV =3D CGF.EmitLoadOfLValue(CGF.EmitLValue(E));
-    return RV.getScalarVal();
-  }
=20
   case CK_LValueToRValue:
     assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
@@ -1202,6 +1183,8 @@
   case CK_VectorSplat: {
     llvm::Type *DstTy =3D ConvertType(DestTy);
     Value *Elt =3D Visit(const_cast<Expr*>(E));
+    Elt =3D EmitScalarConversion(Elt, E->getType(),
+                               DestTy->getAs<VectorType>()->getElementType=
());
=20
     // Insert the element in element zero of an undef vector
     llvm::Value *UnV =3D llvm::UndefValue::get(DstTy);
@@ -1209,13 +1192,9 @@
     UnV =3D Builder.CreateInsertElement(UnV, Elt, Idx);
=20
     // Splat the element across to all elements
-    SmallVector<llvm::Constant*, 16> Args;
     unsigned NumElements =3D cast<llvm::VectorType>(DstTy)->getNumElements=
();
     llvm::Constant *Zero =3D Builder.getInt32(0);
-    for (unsigned i =3D 0; i < NumElements; i++)
-      Args.push_back(Zero);
-
-    llvm::Constant *Mask =3D llvm::ConstantVector::get(Args);
+    llvm::Constant *Mask =3D llvm::ConstantVector::getSplat(NumElements, Z=
ero);
     llvm::Value *Yay =3D Builder.CreateShuffleVector(UnV, UnV, Mask, "spla=
t");
     return Yay;
   }
@@ -1252,7 +1231,6 @@
   }
=20
   llvm_unreachable("unknown scalar cast");
-  return 0;
 }
=20
 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
@@ -1261,11 +1239,6 @@
     .getScalarVal();
 }
=20
-Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E)=
 {
-  LValue LV =3D CGF.EmitBlockDeclRefLValue(E);
-  return CGF.EmitLoadOfLValue(LV).getScalarVal();
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                             Unary Operators
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1274,13 +1247,11 @@
 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
                                 llvm::Value *InVal,
                                 llvm::Value *NextVal, bool IsInc) {
-  switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
+  switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
   case LangOptions::SOB_Undefined:
     return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
-    break;
   case LangOptions::SOB_Defined:
     return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
-    break;
   case LangOptions::SOB_Trapping:
     BinOpInfo BinOp;
     BinOp.LHS =3D InVal;
@@ -1300,9 +1271,21 @@
   QualType type =3D E->getSubExpr()->getType();
   llvm::Value *value =3D EmitLoadOfLValue(LV);
   llvm::Value *input =3D value;
+  llvm::PHINode *atomicPHI =3D 0;
=20
   int amount =3D (isInc ? 1 : -1);
=20
+  if (const AtomicType *atomicTy =3D type->getAs<AtomicType>()) {
+    llvm::BasicBlock *startBB =3D Builder.GetInsertBlock();
+    llvm::BasicBlock *opBB =3D CGF.createBasicBlock("atomic_op", CGF.CurFn=
);
+    Builder.CreateBr(opBB);
+    Builder.SetInsertPoint(opBB);
+    atomicPHI =3D Builder.CreatePHI(value->getType(), 2);
+    atomicPHI->addIncoming(value, startBB);
+    type =3D atomicTy->getValueType();
+    value =3D atomicPHI;
+  }
+
   // Special case of integer increment that we have to check first: bool++.
   // Due to promotion rules, we get:
   //   bool++ -> bool =3D bool + 1
@@ -1336,7 +1319,7 @@
           =3D CGF.getContext().getAsVariableArrayType(type)) {
       llvm::Value *numElts =3D CGF.getVLASize(vla).first;
       if (!isInc) numElts =3D Builder.CreateNSWNeg(numElts, "vla.negsize");
-      if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
+      if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
         value =3D Builder.CreateGEP(value, numElts, "vla.inc");
       else
         value =3D Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
@@ -1346,7 +1329,7 @@
       llvm::Value *amt =3D Builder.getInt32(amount);
=20
       value =3D CGF.EmitCastToVoidPtr(value);
-      if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
+      if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
         value =3D Builder.CreateGEP(value, amt, "incdec.funcptr");
       else
         value =3D Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
@@ -1355,7 +1338,7 @@
     // For everything else, we can just do a simple increment.
     } else {
       llvm::Value *amt =3D Builder.getInt32(amount);
-      if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
+      if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
         value =3D Builder.CreateGEP(value, amt, "incdec.ptr");
       else
         value =3D Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
@@ -1416,12 +1399,24 @@
     llvm::Value *sizeValue =3D
       llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
=20
-    if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
+    if (CGF.getContext().getLangOpts().isSignedOverflowDefined())
       value =3D Builder.CreateGEP(value, sizeValue, "incdec.objptr");
     else
       value =3D Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr=
");
     value =3D Builder.CreateBitCast(value, input->getType());
   }
+ =20
+  if (atomicPHI) {
+    llvm::BasicBlock *opBB =3D Builder.GetInsertBlock();
+    llvm::BasicBlock *contBB =3D CGF.createBasicBlock("atomic_cont", CGF.C=
urFn);
+    llvm::Value *old =3D Builder.CreateAtomicCmpXchg(LV.getAddress(), atom=
icPHI,
+        value, llvm::SequentiallyConsistent);
+    atomicPHI->addIncoming(old, opBB);
+    llvm::Value *success =3D Builder.CreateICmpEQ(old, atomicPHI);
+    Builder.CreateCondBr(success, contBB, opBB);
+    Builder.SetInsertPoint(contBB);
+    return isPre ? value : input;
+  }
=20
   // Store the updated result through the lvalue.
   if (LV.isBitField())
@@ -1459,6 +1454,15 @@
 }
=20
 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
+ =20
+  // Perform vector logical not on comparison with zero vector.
+  if (E->getType()->isExtVectorType()) {
+    Value *Oper =3D Visit(E->getSubExpr());
+    Value *Zero =3D llvm::Constant::getNullValue(Oper->getType());
+    Value *Result =3D Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zer=
o, "cmp");
+    return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
+  }
+ =20
   // Compare operand to zero.
   Value *BoolVal =3D CGF.EvaluateExprAsBool(E->getSubExpr());
=20
@@ -1473,9 +1477,9 @@
=20
 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
   // Try folding the offsetof to a constant.
-  Expr::EvalResult EvalResult;
-  if (E->Evaluate(EvalResult, CGF.getContext()))
-    return Builder.getInt(EvalResult.Val.getInt());
+  llvm::APSInt Value;
+  if (E->EvaluateAsInt(Value, CGF.getContext()))
+    return Builder.getInt(Value);
=20
   // Loop over the components of the offsetof to compute the value.
   unsigned n =3D E->getNumComponents();
@@ -1596,9 +1600,7 @@
=20
   // If this isn't sizeof(vla), the result must be constant; use the const=
ant
   // folding logic so we don't have to duplicate it here.
-  Expr::EvalResult Result;
-  E->Evaluate(Result, CGF.getContext());
-  return Builder.getInt(Result.Val.getInt());
+  return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
 }
=20
 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
@@ -1632,7 +1634,10 @@
=20
   // __imag on a scalar returns zero.  Emit the subexpr to ensure side
   // effects are evaluated, but not the actual value.
-  CGF.EmitScalarExpr(Op, true);
+  if (Op->isGLValue())
+    CGF.EmitLValue(Op);
+  else
+    CGF.EmitScalarExpr(Op, true);
   return llvm::Constant::getNullValue(ConvertType(E->getType()));
 }
=20
@@ -1679,12 +1684,38 @@
   OpInfo.LHS =3D EmitLoadOfLValue(LHSLV);
   OpInfo.LHS =3D EmitScalarConversion(OpInfo.LHS, LHSTy,
                                     E->getComputationLHSType());
+
+  llvm::PHINode *atomicPHI =3D 0;
+  if (const AtomicType *atomicTy =3D OpInfo.Ty->getAs<AtomicType>()) {
+    // FIXME: For floating point types, we should be saving and restoring =
the
+    // floating point environment in the loop.
+    llvm::BasicBlock *startBB =3D Builder.GetInsertBlock();
+    llvm::BasicBlock *opBB =3D CGF.createBasicBlock("atomic_op", CGF.CurFn=
);
+    Builder.CreateBr(opBB);
+    Builder.SetInsertPoint(opBB);
+    atomicPHI =3D Builder.CreatePHI(OpInfo.LHS->getType(), 2);
+    atomicPHI->addIncoming(OpInfo.LHS, startBB);
+    OpInfo.Ty =3D atomicTy->getValueType();
+    OpInfo.LHS =3D atomicPHI;
+  }
  =20
   // Expand the binary operator.
   Result =3D (this->*Func)(OpInfo);
  =20
   // Convert the result back to the LHS type.
   Result =3D EmitScalarConversion(Result, E->getComputationResultType(), L=
HSTy);
+
+  if (atomicPHI) {
+    llvm::BasicBlock *opBB =3D Builder.GetInsertBlock();
+    llvm::BasicBlock *contBB =3D CGF.createBasicBlock("atomic_cont", CGF.C=
urFn);
+    llvm::Value *old =3D Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), a=
tomicPHI,
+        Result, llvm::SequentiallyConsistent);
+    atomicPHI->addIncoming(old, opBB);
+    llvm::Value *success =3D Builder.CreateICmpEQ(old, atomicPHI);
+    Builder.CreateCondBr(success, contBB, opBB);
+    Builder.SetInsertPoint(contBB);
+    return LHSLV;
+  }
  =20
   // Store the result value into the LHS lvalue. Bit-fields are handled
   // specially because the result is altered by the store, i.e., [C99 6.5.=
16p1]
@@ -1709,11 +1740,7 @@
     return 0;
=20
   // The result of an assignment in C is the assigned r-value.
-  if (!CGF.getContext().getLangOptions().CPlusPlus)
-    return RHS;
-
-  // Objective-C property assignment never reloads the value following a s=
tore.
-  if (LHS.isPropertyRef())
+  if (!CGF.getContext().getLangOpts().CPlusPlus)
     return RHS;
=20
   // If the lvalue is non-volatile, return the computed value of the assig=
nment.
@@ -1772,8 +1799,18 @@
       Builder.SetInsertPoint(DivCont);
     }
   }
-  if (Ops.LHS->getType()->isFPOrFPVectorTy())
-    return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
+  if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
+    llvm::Value *Val =3D Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
+    if (CGF.getContext().getLangOpts().OpenCL) {
+      // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
+      llvm::Type *ValTy =3D Val->getType();
+      if (ValTy->isFloatTy() ||
+          (isa<llvm::VectorType>(ValTy) &&
+           cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
+        CGF.SetFPAccuracy(Val, 2.5);
+    }
+    return Val;
+  }
   else if (Ops.Ty->hasUnsignedIntegerRepresentation())
     return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
   else
@@ -1817,7 +1854,6 @@
     break;
   default:
     llvm_unreachable("Unsupported operation for overflow detection");
-    IID =3D 0;
   }
   OpID <<=3D 1;
   OpID |=3D 1;
@@ -1841,7 +1877,7 @@
=20
   // Handle overflow with llvm.trap.
   const std::string *handlerName =3D=20
-    &CGF.getContext().getLangOptions().OverflowHandler;
+    &CGF.getContext().getLangOpts().OverflowHandler;
   if (handlerName->empty()) {
     EmitOverflowBB(overflowBB);
     Builder.SetInsertPoint(continueBB);
@@ -1853,7 +1889,7 @@
   Builder.SetInsertPoint(overflowBB);
=20
   // Get the overflow handler.
-  llvm::Type *Int8Ty =3D llvm::Type::getInt8Ty(VMContext);
+  llvm::Type *Int8Ty =3D CGF.Int8Ty;
   llvm::Type *argTypes[] =3D { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
   llvm::FunctionType *handlerTy =3D
       llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
@@ -1940,7 +1976,7 @@
     // GEP indexes are signed, and scaling an index isn't permitted to
     // signed-overflow, so we use the same semantics for our explicit
     // multiply.  We suppress this if overflow is not undefined behavior.
-    if (CGF.getLangOptions().isSignedOverflowDefined()) {
+    if (CGF.getLangOpts().isSignedOverflowDefined()) {
       index =3D CGF.Builder.CreateMul(index, numElements, "vla.index");
       pointer =3D CGF.Builder.CreateGEP(pointer, index, "add.ptr");
     } else {
@@ -1959,7 +1995,7 @@
     return CGF.Builder.CreateBitCast(result, pointer->getType());
   }
=20
-  if (CGF.getLangOptions().isSignedOverflowDefined())
+  if (CGF.getLangOpts().isSignedOverflowDefined())
     return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
=20
   return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
@@ -1971,7 +2007,7 @@
     return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
=20
   if (op.Ty->isSignedIntegerOrEnumerationType()) {
-    switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior())=
 {
+    switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
     case LangOptions::SOB_Undefined:
       return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
     case LangOptions::SOB_Defined:
@@ -1991,7 +2027,7 @@
   // The LHS is always a pointer if either side is.
   if (!op.LHS->getType()->isPointerTy()) {
     if (op.Ty->isSignedIntegerOrEnumerationType()) {
-      switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior(=
)) {
+      switch (CGF.getContext().getLangOpts().getSignedOverflowBehavior()) {
       case LangOptions::SOB_Undefined:
         return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
       case LangOptions::SOB_Defined:
@@ -2117,36 +2153,28 @@
   case BuiltinType::UChar:
     return (IT =3D=3D VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
                             llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
-    break;
   case BuiltinType::Char_S:
   case BuiltinType::SChar:
     return (IT =3D=3D VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
                             llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
-    break;
   case BuiltinType::UShort:
     return (IT =3D=3D VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
                             llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
-    break;
   case BuiltinType::Short:
     return (IT =3D=3D VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
                             llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
-    break;
   case BuiltinType::UInt:
   case BuiltinType::ULong:
     return (IT =3D=3D VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
                             llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
-    break;
   case BuiltinType::Int:
   case BuiltinType::Long:
     return (IT =3D=3D VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
                             llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
-    break;
   case BuiltinType::Float:
     return (IT =3D=3D VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
                             llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
-    break;
   }
-  return llvm::Intrinsic::not_intrinsic;
 }
=20
 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UIC=
mpOpc,
@@ -2325,11 +2353,7 @@
     return 0;
=20
   // The result of an assignment in C is the assigned r-value.
-  if (!CGF.getContext().getLangOptions().CPlusPlus)
-    return RHS;
-
-  // Objective-C property assignment never reloads the value following a s=
tore.
-  if (LHS.isPropertyRef())
+  if (!CGF.getContext().getLangOpts().CPlusPlus)
     return RHS;
=20
   // If the lvalue is non-volatile, return the computed value of the assig=
nment.
@@ -2341,6 +2365,18 @@
 }
=20
 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
+ =20
+  // Perform vector logical and on comparisons with zero vectors.
+  if (E->getType()->isVectorType()) {
+    Value *LHS =3D Visit(E->getLHS());
+    Value *RHS =3D Visit(E->getRHS());
+    Value *Zero =3D llvm::ConstantAggregateZero::get(LHS->getType());
+    LHS =3D Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
+    RHS =3D Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
+    Value *And =3D Builder.CreateAnd(LHS, RHS);
+    return Builder.CreateSExt(And, Zero->getType(), "sext");
+  }
+ =20
   llvm::Type *ResTy =3D ConvertType(E->getType());
  =20
   // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
@@ -2396,6 +2432,18 @@
 }
=20
 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
+ =20
+  // Perform vector logical or on comparisons with zero vectors.
+  if (E->getType()->isVectorType()) {
+    Value *LHS =3D Visit(E->getLHS());
+    Value *RHS =3D Visit(E->getRHS());
+    Value *Zero =3D llvm::ConstantAggregateZero::get(LHS->getType());
+    LHS =3D Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
+    RHS =3D Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
+    Value *Or =3D Builder.CreateOr(LHS, RHS);
+    return Builder.CreateSExt(Or, Zero->getType(), "sext");
+  }
+ =20
   llvm::Type *ResTy =3D ConvertType(E->getType());
  =20
   // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
@@ -2503,16 +2551,23 @@
     Expr *live =3D lhsExpr, *dead =3D rhsExpr;
     if (!CondExprBool) std::swap(live, dead);
=20
-    // If the dead side doesn't have labels we need, and if the Live side =
isn't
-    // the gnu missing ?: extension (which we could handle, but don't both=
er
-    // to), just emit the Live part.
-    if (!CGF.ContainsLabel(dead))
-      return Visit(live);
+    // If the dead side doesn't have labels we need, just emit the Live pa=
rt.
+    if (!CGF.ContainsLabel(dead)) {
+      Value *Result =3D Visit(live);
+
+      // If the live part is a throw expression, it acts like it has a void
+      // type, so evaluating it returns a null Value*.  However, a conditi=
onal
+      // with non-void type must return a non-null Value*.
+      if (!Result && !E->getType()->isVoidType())
+        Result =3D llvm::UndefValue::get(CGF.ConvertType(E->getType()));
+
+      return Result;
+    }
   }
=20
   // OpenCL: If the condition is a vector, we can treat this condition like
   // the select function.
-  if (CGF.getContext().getLangOptions().OpenCL=20
+  if (CGF.getContext().getLangOpts().OpenCL=20
       && condExpr->getType()->isVectorType()) {
     llvm::Value *CondV =3D CGF.EmitScalarExpr(condExpr);
     llvm::Value *LHS =3D Visit(lhsExpr);
@@ -2524,11 +2579,7 @@
     unsigned numElem =3D vecTy->getNumElements();     =20
     llvm::Type *elemType =3D vecTy->getElementType();
    =20
-    std::vector<llvm::Constant*> Zvals;
-    for (unsigned i =3D 0; i < numElem; ++i)
-      Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
-
-    llvm::Value *zeroVec =3D llvm::ConstantVector::get(Zvals);   =20
+    llvm::Value *zeroVec =3D llvm::Constant::getNullValue(vecTy);
     llvm::Value *TestMSB =3D Builder.CreateICmpSLT(CondV, zeroVec);
     llvm::Value *tmp =3D Builder.CreateSExt(TestMSB,=20
                                           llvm::VectorType::get(elemType,
@@ -2564,6 +2615,11 @@
     llvm::Value *CondV =3D CGF.EvaluateExprAsBool(condExpr);
     llvm::Value *LHS =3D Visit(lhsExpr);
     llvm::Value *RHS =3D Visit(rhsExpr);
+    if (!LHS) {
+      // If the conditional has void type, make sure we return a null Valu=
e*.
+      assert(!RHS && "LHS and RHS types must match");
+      return 0;
+    }
     return Builder.CreateSelect(CondV, LHS, RHS, "cond");
   }
=20
@@ -2661,8 +2717,7 @@
       Args.push_back(Builder.getInt32(2));
 =20
       if (numElementsDst =3D=3D 4)
-        Args.push_back(llvm::UndefValue::get(
-                                             llvm::Type::getInt32Ty(CGF.ge=
tLLVMContext())));
+        Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
      =20
       llvm::Constant *Mask =3D llvm::ConstantVector::get(Args);
      =20
@@ -2733,11 +2788,11 @@
=20
   Expr *BaseExpr =3D E->getBase();
   if (BaseExpr->isRValue()) {
-    V =3D CreateTempAlloca(ClassPtrTy, "resval");
+    V =3D CreateMemTemp(E->getType(), "resval");
     llvm::Value *Src =3D EmitScalarExpr(BaseExpr);
     Builder.CreateStore(Src, V);
     V =3D ScalarExprEmitter(*this).EmitLoadOfLValue(
-      MakeAddrLValue(V, E->getType()));
+      MakeNaturalAlignAddrLValue(V, E->getType()));
   } else {
     if (E->isArrow())
       V =3D ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
@@ -2748,7 +2803,7 @@
   // build Class* type
   ClassPtrTy =3D ClassPtrTy->getPointerTo();
   V =3D Builder.CreateBitCast(V, ClassPtrTy);
-  return MakeAddrLValue(V, E->getType());
+  return MakeNaturalAlignAddrLValue(V, E->getType());
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGObjC.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjC.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjC.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -29,6 +29,10 @@
 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
 static TryEmitResult
 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
+static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
+                                      const Expr *E,
+                                      const ObjCMethodDecl *Method,
+                                      RValue Result);
=20
 /// Given the address of a variable of pointer type, find the correct
 /// null to store into it.
@@ -47,6 +51,140 @@
   return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
 }
=20
+/// EmitObjCNumericLiteral - This routine generates code for
+/// the appropriate +[NSNumber numberWith<Type>:] method.
+///
+llvm::Value *
+CodeGenFunction::EmitObjCNumericLiteral(const ObjCNumericLiteral *E) {
+  // Generate the correct selector for this literal's concrete type.
+  const Expr *NL =3D E->getNumber();
+  // Get the method.
+  const ObjCMethodDecl *Method =3D E->getObjCNumericLiteralMethod();
+  assert(Method && "NSNumber method is null");
+  Selector Sel =3D Method->getSelector();
+ =20
+  // Generate a reference to the class pointer, which will be the receiver.
+  QualType ResultType =3D E->getType(); // should be NSNumber *
+  const ObjCObjectPointerType *InterfacePointerType =3D=20
+    ResultType->getAsObjCInterfacePointerType();
+  ObjCInterfaceDecl *NSNumberDecl =3D=20
+    InterfacePointerType->getObjectType()->getInterface();
+  CGObjCRuntime &Runtime =3D CGM.getObjCRuntime();
+  llvm::Value *Receiver =3D Runtime.GetClass(Builder, NSNumberDecl);
+
+  const ParmVarDecl *argDecl =3D *Method->param_begin();
+  QualType ArgQT =3D argDecl->getType().getUnqualifiedType();
+  RValue RV =3D EmitAnyExpr(NL);
+  CallArgList Args;
+  Args.add(RV, ArgQT);
+
+  RValue result =3D Runtime.GenerateMessageSend(*this, ReturnValueSlot(),=20
+                                              ResultType, Sel, Receiver, A=
rgs,=20
+                                              NSNumberDecl, Method);
+  return Builder.CreateBitCast(result.getScalarVal(),=20
+                               ConvertType(E->getType()));
+}
+
+llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
+                                    const ObjCMethodDecl *MethodWithObject=
s) {
+  ASTContext &Context =3D CGM.getContext();
+  const ObjCDictionaryLiteral *DLE =3D 0;
+  const ObjCArrayLiteral *ALE =3D dyn_cast<ObjCArrayLiteral>(E);
+  if (!ALE)
+    DLE =3D cast<ObjCDictionaryLiteral>(E);
+ =20
+  // Compute the type of the array we're initializing.
+  uint64_t NumElements =3D=20
+    ALE ? ALE->getNumElements() : DLE->getNumElements();
+  llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
+                            NumElements);
+  QualType ElementType =3D Context.getObjCIdType().withConst();
+  QualType ElementArrayType=20
+    =3D Context.getConstantArrayType(ElementType, APNumElements,=20
+                                   ArrayType::Normal, /*IndexTypeQuals=3D*=
/0);
+
+  // Allocate the temporary array(s).
+  llvm::Value *Objects =3D CreateMemTemp(ElementArrayType, "objects"); =20
+  llvm::Value *Keys =3D 0;
+  if (DLE)
+    Keys =3D CreateMemTemp(ElementArrayType, "keys");
+ =20
+  // Perform the actual initialialization of the array(s).
+  for (uint64_t i =3D 0; i < NumElements; i++) {
+    if (ALE) {
+      // Emit the initializer.
+      const Expr *Rhs =3D ALE->getElement(i);
+      LValue LV =3D LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
+                                   ElementType,
+                                   Context.getTypeAlignInChars(Rhs->getTyp=
e()),
+                                   Context);
+      EmitScalarInit(Rhs, /*D=3D*/0, LV, /*capturedByInit=3D*/false);
+    } else {     =20
+      // Emit the key initializer.
+      const Expr *Key =3D DLE->getKeyValueElement(i).Key;
+      LValue KeyLV =3D LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
+                                      ElementType,
+                                    Context.getTypeAlignInChars(Key->getTy=
pe()),
+                                      Context);
+      EmitScalarInit(Key, /*D=3D*/0, KeyLV, /*capturedByInit=3D*/false);
+
+      // Emit the value initializer.
+      const Expr *Value =3D DLE->getKeyValueElement(i).Value; =20
+      LValue ValueLV =3D LValue::MakeAddr(Builder.CreateStructGEP(Objects,=
 i),=20
+                                        ElementType,
+                                  Context.getTypeAlignInChars(Value->getTy=
pe()),
+                                        Context);
+      EmitScalarInit(Value, /*D=3D*/0, ValueLV, /*capturedByInit=3D*/false=
);
+    }
+  }
+ =20
+  // Generate the argument list.
+  CallArgList Args; =20
+  ObjCMethodDecl::param_const_iterator PI =3D MethodWithObjects->param_beg=
in();
+  const ParmVarDecl *argDecl =3D *PI++;
+  QualType ArgQT =3D argDecl->getType().getUnqualifiedType();
+  Args.add(RValue::get(Objects), ArgQT);
+  if (DLE) {
+    argDecl =3D *PI++;
+    ArgQT =3D argDecl->getType().getUnqualifiedType();
+    Args.add(RValue::get(Keys), ArgQT);
+  }
+  argDecl =3D *PI;
+  ArgQT =3D argDecl->getType().getUnqualifiedType();
+  llvm::Value *Count =3D=20
+    llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
+  Args.add(RValue::get(Count), ArgQT);
+
+  // Generate a reference to the class pointer, which will be the receiver.
+  Selector Sel =3D MethodWithObjects->getSelector();
+  QualType ResultType =3D E->getType();
+  const ObjCObjectPointerType *InterfacePointerType
+    =3D ResultType->getAsObjCInterfacePointerType();
+  ObjCInterfaceDecl *Class=20
+    =3D InterfacePointerType->getObjectType()->getInterface();
+  CGObjCRuntime &Runtime =3D CGM.getObjCRuntime();
+  llvm::Value *Receiver =3D Runtime.GetClass(Builder, Class);
+
+  // Generate the message send.
+  RValue result
+    =3D Runtime.GenerateMessageSend(*this, ReturnValueSlot(),=20
+                                  MethodWithObjects->getResultType(),
+                                  Sel,
+                                  Receiver, Args, Class,
+                                  MethodWithObjects);
+  return Builder.CreateBitCast(result.getScalarVal(),=20
+                               ConvertType(E->getType()));
+}
+
+llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral =
*E) {
+  return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
+}
+
+llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
+                                            const ObjCDictionaryLiteral *E=
) {
+  return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
+}
+
 /// Emit a selector.
 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr =
*E) {
   // Untyped selector.
@@ -143,7 +281,7 @@
   // though.
   bool retainSelf =3D
     (!isDelegateInit &&
-     CGM.getLangOptions().ObjCAutoRefCount &&
+     CGM.getLangOpts().ObjCAutoRefCount &&
      method &&
      method->hasAttr<NSConsumesSelfAttr>());
=20
@@ -197,7 +335,7 @@
   // In ARC, we sometimes want to "extend the lifetime"
   // (i.e. retain+autorelease) of receivers of returns-inner-pointer
   // messages.
-  if (getLangOptions().ObjCAutoRefCount && method &&
+  if (getLangOpts().ObjCAutoRefCount && method &&
       method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
       shouldExtendReceiverForInnerPointerMessage(E))
     Receiver =3D EmitARCRetainAutorelease(ReceiverType, Receiver);
@@ -216,7 +354,7 @@
   // be an undefined read and write of an object in unordered
   // expressions.
   if (isDelegateInit) {
-    assert(getLangOptions().ObjCAutoRefCount &&
+    assert(getLangOpts().ObjCAutoRefCount &&
            "delegate init calls should only be marked in ARC");
=20
     // Do an unsafe store of null into self.
@@ -307,14 +445,14 @@
=20
   llvm::Function *Fn =3D CGM.getObjCRuntime().GenerateMethod(OMD, CD);
=20
-  const CGFunctionInfo &FI =3D CGM.getTypes().getFunctionInfo(OMD);
+  const CGFunctionInfo &FI =3D CGM.getTypes().arrangeObjCMethodDeclaration=
(OMD);
   CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
=20
   args.push_back(OMD->getSelfDecl());
   args.push_back(OMD->getCmdDecl());
=20
   for (ObjCMethodDecl::param_const_iterator PI =3D OMD->param_begin(),
-       E =3D OMD->param_end(); PI !=3D E; ++PI)
+         E =3D OMD->param_end(); PI !=3D E; ++PI)
     args.push_back(*PI);
=20
   CurGD =3D OMD;
@@ -322,7 +460,7 @@
   StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
=20
   // In ARC, certain methods get an extra cleanup.
-  if (CGM.getLangOptions().ObjCAutoRefCount &&
+  if (CGM.getLangOpts().ObjCAutoRefCount &&
       OMD->isInstanceMethod() &&
       OMD->getSelector().isUnarySelector()) {
     const IdentifierInfo *ident =3D=20
@@ -369,8 +507,9 @@
   args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
=20
   llvm::Value *fn =3D CGF.CGM.getObjCRuntime().GetGetStructFunction();
-  CGF.EmitCall(CGF.getTypes().getFunctionInfo(Context.VoidTy, args,
-                                              FunctionType::ExtInfo()),
+  CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Context.VoidTy, args,
+                                                  FunctionType::ExtInfo(),
+                                                  RequiredArgs::All),
                fn, ReturnValueSlot(), args);
 }
=20
@@ -467,13 +606,13 @@
   // Handle retain.
   if (setterKind =3D=3D ObjCPropertyDecl::Retain) {
     // In GC-only, there's nothing special that needs to be done.
-    if (CGM.getLangOptions().getGC() =3D=3D LangOptions::GCOnly) {
+    if (CGM.getLangOpts().getGC() =3D=3D LangOptions::GCOnly) {
       // fallthrough
=20
     // In ARC, if the property is non-atomic, use expression emission,
     // which translates to objc_storeStrong.  This isn't required, but
     // it's slightly nicer.
-    } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
+    } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
       Kind =3D Expression;
       return;
=20
@@ -508,14 +647,14 @@
   // expressions.  This actually works out to being atomic anyway,
   // except for ARC __strong, but that should trigger the above code.
   if (ivarType.hasNonTrivialObjCLifetime() ||
-      (CGM.getLangOptions().getGC() &&
+      (CGM.getLangOpts().getGC() &&
        CGM.getContext().getObjCGCAttrKind(ivarType))) {
     Kind =3D Expression;
     return;
   }
=20
   // Compute whether the ivar has strong members.
-  if (CGM.getLangOptions().getGC())
+  if (CGM.getLangOpts().getGC())
     if (const RecordType *recordType =3D ivarType->getAs<RecordType>())
       HasStrong =3D recordType->getDecl()->hasObjectMember();
=20
@@ -564,12 +703,14 @@
 /// is illegal within a category.
 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
                                          const ObjCPropertyImplDecl *PID) {
+  llvm::Constant *AtomicHelperFn =3D=20
+    GenerateObjCAtomicGetterCopyHelperFunction(PID);
   const ObjCPropertyDecl *PD =3D PID->getPropertyDecl();
   ObjCMethodDecl *OMD =3D PD->getGetterMethodDecl();
   assert(OMD && "Invalid call to generate getter (empty method)");
-  StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
-
-  generateObjCGetterBody(IMP, PID);
+  StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
+
+  generateObjCGetterBody(IMP, PID, AtomicHelperFn);
=20
   FinishFunction();
 }
@@ -597,14 +738,53 @@
   return false;
 }
=20
+/// emitCPPObjectAtomicGetterCall - Call the runtime function to=20
+/// copy the ivar into the resturn slot.
+static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,=20
+                                          llvm::Value *returnAddr,
+                                          ObjCIvarDecl *ivar,
+                                          llvm::Constant *AtomicHelperFn) {
+  // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
+  //                           AtomicHelperFn);
+  CallArgList args;
+ =20
+  // The 1st argument is the return Slot.
+  args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
+ =20
+  // The 2nd argument is the address of the ivar.
+  llvm::Value *ivarAddr =3D=20
+  CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),=20
+                        CGF.LoadObjCSelf(), ivar, 0).getAddress();
+  ivarAddr =3D CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
+  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
+ =20
+  // Third argument is the helper function.
+  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
+ =20
+  llvm::Value *copyCppAtomicObjectFn =3D=20
+  CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
+  CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy,=
 args,
+                                                  FunctionType::ExtInfo(),
+                                                  RequiredArgs::All),
+               copyCppAtomicObjectFn, ReturnValueSlot(), args);
+}
+
 void
 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *clas=
sImpl,
-                                        const ObjCPropertyImplDecl *propIm=
pl) {
+                                        const ObjCPropertyImplDecl *propIm=
pl,
+                                        llvm::Constant *AtomicHelperFn) {
   // If there's a non-trivial 'get' expression, we just have to emit that.
   if (!hasTrivialGetExpr(propImpl)) {
-    ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
-                   /*nrvo*/ 0);
-    EmitReturnStmt(ret);
+    if (!AtomicHelperFn) {
+      ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
+                     /*nrvo*/ 0);
+      EmitReturnStmt(ret);
+    }
+    else {
+      ObjCIvarDecl *ivar =3D propImpl->getPropertyIvarDecl();
+      emitCPPObjectAtomicGetterCall(*this, ReturnValue,=20
+                                    ivar, AtomicHelperFn);
+    }
     return;
   }
=20
@@ -670,8 +850,9 @@
=20
     // FIXME: We shouldn't need to get the function info here, the
     // runtime already should have computed it to build the function.
-    RValue RV =3D EmitCall(getTypes().getFunctionInfo(propType, args,
-                                                    FunctionType::ExtInfo(=
)),
+    RValue RV =3D EmitCall(getTypes().arrangeFunctionCall(propType, args,
+                                                        FunctionType::ExtI=
nfo(),
+                                                        RequiredArgs::All),
                          getPropertyFn, ReturnValueSlot(), args);
=20
     // We need to fix the type here. Ivars with copy & retain are
@@ -752,7 +933,8 @@
=20
   // The second argument is the address of the parameter variable.
   ParmVarDecl *argVar =3D *OMD->param_begin();
-  DeclRefExpr argRef(argVar, argVar->getType(), VK_LValue, SourceLocation(=
));
+  DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(=
),=20
+                     VK_LValue, SourceLocation());
   llvm::Value *argAddr =3D CGF.EmitLValue(&argRef).getAddress();
   argAddr =3D CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
   args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
@@ -770,11 +952,52 @@
   args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
=20
   llvm::Value *copyStructFn =3D CGF.CGM.getObjCRuntime().GetSetStructFunct=
ion();
-  CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, arg=
s,
-                                              FunctionType::ExtInfo()),
+  CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy,=
 args,
+                                                  FunctionType::ExtInfo(),
+                                                  RequiredArgs::All),
                copyStructFn, ReturnValueSlot(), args);
 }
=20
+/// emitCPPObjectAtomicSetterCall - Call the runtime function to store=20
+/// the value from the first formal parameter into the given ivar, using=20
+/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
+static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,=20
+                                          ObjCMethodDecl *OMD,
+                                          ObjCIvarDecl *ivar,
+                                          llvm::Constant *AtomicHelperFn) {
+  // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,=20
+  //                           AtomicHelperFn);
+  CallArgList args;
+ =20
+  // The first argument is the address of the ivar.
+  llvm::Value *ivarAddr =3D=20
+    CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),=20
+                          CGF.LoadObjCSelf(), ivar, 0).getAddress();
+  ivarAddr =3D CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
+  args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
+ =20
+  // The second argument is the address of the parameter variable.
+  ParmVarDecl *argVar =3D *OMD->param_begin();
+  DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(=
),=20
+                     VK_LValue, SourceLocation());
+  llvm::Value *argAddr =3D CGF.EmitLValue(&argRef).getAddress();
+  argAddr =3D CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
+  args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
+ =20
+  // Third argument is the helper function.
+  args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
+ =20
+  llvm::Value *copyCppAtomicObjectFn =3D=20
+    CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
+  CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy,=
 args,
+                                                  FunctionType::ExtInfo(),
+                                                  RequiredArgs::All),
+               copyCppAtomicObjectFn, ReturnValueSlot(), args);
+ =20
+
+}
+
+
 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
   Expr *setter =3D PID->getSetterCXXAssignment();
   if (!setter) return true;
@@ -799,20 +1022,38 @@
   return false;
 }
=20
+static bool UseOptimizedSetter(CodeGenModule &CGM) {
+  if (CGM.getLangOpts().getGC() !=3D LangOptions::NonGC)
+    return false;
+  const TargetInfo &Target =3D CGM.getContext().getTargetInfo();
+
+  if (Target.getPlatformName() !=3D "macosx")
+    return false;
+
+  return Target.getPlatformMinVersion() >=3D VersionTuple(10, 8);
+}
+
 void
 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *clas=
sImpl,
-                                        const ObjCPropertyImplDecl *propIm=
pl) {
+                                        const ObjCPropertyImplDecl *propIm=
pl,
+                                        llvm::Constant *AtomicHelperFn) {
+  const ObjCPropertyDecl *prop =3D propImpl->getPropertyDecl();
+  ObjCIvarDecl *ivar =3D propImpl->getPropertyIvarDecl();
+  ObjCMethodDecl *setterMethod =3D prop->getSetterMethodDecl();
+ =20
   // Just use the setter expression if Sema gave us one and it's
-  // non-trivial.  There's no way to do this atomically.
+  // non-trivial.
   if (!hasTrivialSetExpr(propImpl)) {
-    EmitStmt(propImpl->getSetterCXXAssignment());
+    if (!AtomicHelperFn)
+      // If non-atomic, assignment is called directly.
+      EmitStmt(propImpl->getSetterCXXAssignment());
+    else
+      // If atomic, assignment is called via a locking api.
+      emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
+                                    AtomicHelperFn);
     return;
   }
=20
-  const ObjCPropertyDecl *prop =3D propImpl->getPropertyDecl();
-  ObjCIvarDecl *ivar =3D propImpl->getPropertyIvarDecl(); =20
-  ObjCMethodDecl *setterMethod =3D prop->getSetterMethodDecl();
-
   PropertyImplStrategy strategy(CGM, propImpl);
   switch (strategy.getKind()) {
   case PropertyImplStrategy::Native: {
@@ -845,13 +1086,28 @@
=20
   case PropertyImplStrategy::GetSetProperty:
   case PropertyImplStrategy::SetPropertyAndExpressionGet: {
-    llvm::Value *setPropertyFn =3D
-      CGM.getObjCRuntime().GetPropertySetFunction();
-    if (!setPropertyFn) {
-      CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
-      return;
+ =20
+    llvm::Value *setOptimizedPropertyFn =3D 0;
+    llvm::Value *setPropertyFn =3D 0;
+    if (UseOptimizedSetter(CGM)) {
+      // 10.8 code and GC is off
+      setOptimizedPropertyFn =3D=20
+        CGM.getObjCRuntime()
+           .GetOptimizedPropertySetFunction(strategy.isAtomic(),
+                                            strategy.isCopy());
+      if (!setOptimizedPropertyFn) {
+        CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
+        return;
+      }
     }
-
+    else {
+      setPropertyFn =3D CGM.getObjCRuntime().GetPropertySetFunction();
+      if (!setPropertyFn) {
+        CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy=
");
+        return;
+      }
+    }
+  =20
     // Emit objc_setProperty((id) self, _cmd, offset, arg,
     //                       <is-atomic>, <is-copy>).
     llvm::Value *cmd =3D
@@ -866,17 +1122,28 @@
     CallArgList args;
     args.add(RValue::get(self), getContext().getObjCIdType());
     args.add(RValue::get(cmd), getContext().getObjCSelType());
-    args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
-    args.add(RValue::get(arg), getContext().getObjCIdType());
-    args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
-             getContext().BoolTy);
-    args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
-             getContext().BoolTy);
-    // FIXME: We shouldn't need to get the function info here, the runtime
-    // already should have computed it to build the function.
-    EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
-                                        FunctionType::ExtInfo()),
-             setPropertyFn, ReturnValueSlot(), args);
+    if (setOptimizedPropertyFn) {
+      args.add(RValue::get(arg), getContext().getObjCIdType());
+      args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
+      EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
+                                              FunctionType::ExtInfo(),
+                                              RequiredArgs::All),
+               setOptimizedPropertyFn, ReturnValueSlot(), args);
+    } else {
+      args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
+      args.add(RValue::get(arg), getContext().getObjCIdType());
+      args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
+               getContext().BoolTy);
+      args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
+               getContext().BoolTy);
+      // FIXME: We shouldn't need to get the function info here, the runti=
me
+      // already should have computed it to build the function.
+      EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
+                                              FunctionType::ExtInfo(),
+                                              RequiredArgs::All),
+               setPropertyFn, ReturnValueSlot(), args);
+    }
+   =20
     return;
   }
=20
@@ -890,7 +1157,8 @@
=20
   // Otherwise, fake up some ASTs and emit a normal assignment.
   ValueDecl *selfDecl =3D setterMethod->getSelfDecl();
-  DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocatio=
n());
+  DeclRefExpr self(selfDecl, false, selfDecl->getType(),
+                   VK_LValue, SourceLocation());
   ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
                             selfDecl->getType(), CK_LValueToRValue, &self,
                             VK_RValue);
@@ -899,7 +1167,7 @@
=20
   ParmVarDecl *argDecl =3D *setterMethod->param_begin();
   QualType argType =3D argDecl->getType().getNonReferenceType();
-  DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
+  DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
   ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
                            argType.getUnqualifiedType(), CK_LValueToRValue,
                            &arg, VK_RValue);
@@ -943,12 +1211,14 @@
 /// is illegal within a category.
 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
                                          const ObjCPropertyImplDecl *PID) {
+  llvm::Constant *AtomicHelperFn =3D=20
+    GenerateObjCAtomicSetterCopyHelperFunction(PID);
   const ObjCPropertyDecl *PD =3D PID->getPropertyDecl();
   ObjCMethodDecl *OMD =3D PD->getSetterMethodDecl();
   assert(OMD && "Invalid call to generate setter (empty method)");
-  StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
-
-  generateObjCSetterBody(IMP, PID);
+  StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
+
+  generateObjCSetterBody(IMP, PID, AtomicHelperFn);
=20
   FinishFunction();
 }
@@ -958,13 +1228,13 @@
   private:
     llvm::Value *addr;
     const ObjCIvarDecl *ivar;
-    CodeGenFunction::Destroyer &destroyer;
+    CodeGenFunction::Destroyer *destroyer;
     bool useEHCleanupForArray;
   public:
     DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
                 CodeGenFunction::Destroyer *destroyer,
                 bool useEHCleanupForArray)
-      : addr(addr), ivar(ivar), destroyer(*destroyer),
+      : addr(addr), ivar(ivar), destroyer(destroyer),
         useEHCleanupForArray(useEHCleanupForArray) {}
=20
     void Emit(CodeGenFunction &CGF, Flags flags) {
@@ -1004,11 +1274,11 @@
     // Use a call to objc_storeStrong to destroy strong ivars, for the
     // general benefit of the tools.
     if (dtorKind =3D=3D QualType::DK_objc_strong_lifetime) {
-      destroyer =3D &destroyARCStrongWithStore;
+      destroyer =3D destroyARCStrongWithStore;
=20
     // Otherwise use the default for the destruction kind.
     } else {
-      destroyer =3D &CGF.getDestroyer(dtorKind);
+      destroyer =3D CGF.getDestroyer(dtorKind);
     }
=20
     CleanupKind cleanupKind =3D CGF.getCleanupKind(dtorKind);
@@ -1067,7 +1337,7 @@
 }
=20
 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::NonGC)
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::NonGC)
     return false;
   if (const RecordType *FDTTy =3D Ty.getTypePtr()->getAs<RecordType>())
     return FDTTy->getDecl()->hasObjectMember();
@@ -1087,117 +1357,6 @@
   return PTy->getPointeeType();
 }
=20
-LValue
-CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
-  // This is a special l-value that just issues sends when we load or
-  // store through it.
-
-  // For certain base kinds, we need to emit the base immediately.
-  llvm::Value *Base;
-  if (E->isSuperReceiver())
-    Base =3D LoadObjCSelf();
-  else if (E->isClassReceiver())
-    Base =3D CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
-  else
-    Base =3D EmitScalarExpr(E->getBase());
-  return LValue::MakePropertyRef(E, Base);
-}
-
-static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
-                                       ReturnValueSlot Return,
-                                       QualType ResultType,
-                                       Selector S,
-                                       llvm::Value *Receiver,
-                                       const CallArgList &CallArgs) {
-  const ObjCMethodDecl *OMD =3D cast<ObjCMethodDecl>(CGF.CurFuncDecl);
-  bool isClassMessage =3D OMD->isClassMethod();
-  bool isCategoryImpl =3D isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
-  return CGF.CGM.getObjCRuntime()
-                .GenerateMessageSendSuper(CGF, Return, ResultType,
-                                          S, OMD->getClassInterface(),
-                                          isCategoryImpl, Receiver,
-                                          isClassMessage, CallArgs);
-}
-
-RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
-                                                    ReturnValueSlot Return=
) {
-  const ObjCPropertyRefExpr *E =3D LV.getPropertyRefExpr();
-  QualType ResultType =3D E->getGetterResultType();
-  Selector S;
-  const ObjCMethodDecl *method;
-  if (E->isExplicitProperty()) {
-    const ObjCPropertyDecl *Property =3D E->getExplicitProperty();
-    S =3D Property->getGetterName();
-    method =3D Property->getGetterMethodDecl();
-  } else {
-    method =3D E->getImplicitPropertyGetter();
-    S =3D method->getSelector();
-  }
-
-  llvm::Value *Receiver =3D LV.getPropertyRefBaseAddr();
-
-  if (CGM.getLangOptions().ObjCAutoRefCount) {
-    QualType receiverType;
-    if (E->isSuperReceiver())
-      receiverType =3D E->getSuperReceiverType();
-    else if (E->isClassReceiver())
-      receiverType =3D getContext().getObjCClassType();
-    else
-      receiverType =3D E->getBase()->getType();
-  }
-
-  // Accesses to 'super' follow a different code path.
-  if (E->isSuperReceiver())
-    return AdjustRelatedResultType(*this, E, method,
-                                   GenerateMessageSendSuper(*this, Return,=20
-                                                            ResultType,
-                                                            S, Receiver,=20
-                                                            CallArgList())=
);
-  const ObjCInterfaceDecl *ReceiverClass
-    =3D (E->isClassReceiver() ? E->getClassReceiver() : 0);
-  return AdjustRelatedResultType(*this, E, method,
-          CGM.getObjCRuntime().
-             GenerateMessageSend(*this, Return, ResultType, S,
-                                 Receiver, CallArgList(), ReceiverClass));
-}
-
-void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
-                                                        LValue Dst) {
-  const ObjCPropertyRefExpr *E =3D Dst.getPropertyRefExpr();
-  Selector S =3D E->getSetterSelector();
-  QualType ArgType =3D E->getSetterArgType();
- =20
-  // FIXME. Other than scalars, AST is not adequate for setter and
-  // getter type mismatches which require conversion.
-  if (Src.isScalar()) {
-    llvm::Value *SrcVal =3D Src.getScalarVal();
-    QualType DstType =3D getContext().getCanonicalType(ArgType);
-    llvm::Type *DstTy =3D ConvertType(DstType);
-    if (SrcVal->getType() !=3D DstTy)
-      Src =3D=20
-        RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
-  }
- =20
-  CallArgList Args;
-  Args.add(Src, ArgType);
-
-  llvm::Value *Receiver =3D Dst.getPropertyRefBaseAddr();
-  QualType ResultType =3D getContext().VoidTy;
-
-  if (E->isSuperReceiver()) {
-    GenerateMessageSendSuper(*this, ReturnValueSlot(),
-                             ResultType, S, Receiver, Args);
-    return;
-  }
-
-  const ObjCInterfaceDecl *ReceiverClass
-    =3D (E->isClassReceiver() ? E->getClassReceiver() : 0);
-
-  CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
-                                           ResultType, S, Receiver, Args,
-                                           ReceiverClass);
-}
-
 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStm=
t &S){
   llvm::Constant *EnumerationMutationFn =3D
     CGM.getObjCRuntime().EnumerationMutationFunction();
@@ -1243,7 +1402,7 @@
=20
   // Emit the collection pointer.  In ARC, we do a retain.
   llvm::Value *Collection;
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     Collection =3D EmitARCRetainScalarExpr(S.getCollection());
=20
     // Enter a cleanup to do the release.
@@ -1343,8 +1502,9 @@
   Args2.add(RValue::get(V), getContext().getObjCIdType());
   // FIXME: We shouldn't need to get the function info here, the runtime a=
lready
   // should have computed it to build the function.
-  EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
-                                          FunctionType::ExtInfo()),
+  EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
+                                              FunctionType::ExtInfo(),
+                                              RequiredArgs::All),
            EnumerationMutationFn, ReturnValueSlot(), Args2);
=20
   // Otherwise, or if the mutation function returns, just continue.
@@ -1360,7 +1520,7 @@
     EmitAutoVarInit(variable);
=20
     const VarDecl* D =3D cast<VarDecl>(SD->getSingleDecl());
-    DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
+    DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
                         VK_LValue, SourceLocation());
     elementLValue =3D EmitLValue(&tempDRE);
     elementType =3D D->getType();
@@ -1467,7 +1627,7 @@
     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
=20
   // Leave the cleanup we entered in ARC.
-  if (getLangOptions().ObjCAutoRefCount)
+  if (getLangOpts().ObjCAutoRefCount)
     PopCleanupBlock();
=20
   EmitBlock(LoopEnd.getBlock());
@@ -1604,9 +1764,7 @@
            =3D=3D value->getType());
=20
   if (!fn) {
-    std::vector<llvm::Type*> argTypes(2);
-    argTypes[0] =3D CGF.Int8PtrPtrTy;
-    argTypes[1] =3D CGF.Int8PtrTy;
+    llvm::Type *argTypes[] =3D { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
=20
     llvm::FunctionType *fnType
       =3D llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
@@ -1720,8 +1878,7 @@
     // in a moment.
     } else if (CGM.getCodeGenOpts().OptimizationLevel =3D=3D 0) {
       llvm::FunctionType *type =3D
-        llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
-                                /*variadic*/ false);
+        llvm::FunctionType::get(VoidTy, /*variadic*/false);
      =20
       marker =3D llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ =
true);
=20
@@ -1813,7 +1970,8 @@
   // lvalue is inadequately aligned.
   if (shouldUseFusedARCCalls() &&
       !isBlock &&
-      !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
+      (dst.getAlignment().isZero() ||
+       dst.getAlignment() >=3D CharUnits::fromQuantity(PointerAlignInBytes=
))) {
     return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
   }
=20
@@ -2086,7 +2244,7 @@
 }
=20
 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
-  if (CGM.getLangOptions().ObjCAutoRefCount)
+  if (CGM.getLangOpts().ObjCAutoRefCount)
     EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
   else
     EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, P=
tr);
@@ -2109,7 +2267,6 @@
   }
=20
   llvm_unreachable("impossible lifetime!");
-  return TryEmitResult();
 }
=20
 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
@@ -2138,7 +2295,7 @@
   // As a very special optimization, in ARC++, if the l-value is the
   // result of a non-volatile assignment, do a simple retain of the
   // result of the call to objc_storeWeak instead of reloading.
-  if (CGF.getLangOptions().CPlusPlus &&
+  if (CGF.getLangOpts().CPlusPlus &&
       !type.isVolatileQualified() &&
       type.getObjCLifetime() =3D=3D Qualifiers::OCL_Weak &&
       isa<BinaryOperator>(e) &&
@@ -2233,10 +2390,64 @@
   return true;
 }
=20
+/// Try to emit a PseudoObjectExpr at +1.
+///
+/// This massively duplicates emitPseudoObjectRValue.
+static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
+                                                  const PseudoObjectExpr *=
E) {
+  llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
+
+  // Find the result expression.
+  const Expr *resultExpr =3D E->getResultExpr();
+  assert(resultExpr);
+  TryEmitResult result;
+
+  for (PseudoObjectExpr::const_semantics_iterator
+         i =3D E->semantics_begin(), e =3D E->semantics_end(); i !=3D e; +=
+i) {
+    const Expr *semantic =3D *i;
+
+    // If this semantic expression is an opaque value, bind it
+    // to the result of its source expression.
+    if (const OpaqueValueExpr *ov =3D dyn_cast<OpaqueValueExpr>(semantic))=
 {
+      typedef CodeGenFunction::OpaqueValueMappingData OVMA;
+      OVMA opaqueData;
+
+      // If this semantic is the result of the pseudo-object
+      // expression, try to evaluate the source as +1.
+      if (ov =3D=3D resultExpr) {
+        assert(!OVMA::shouldBindAsLValue(ov));
+        result =3D tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
+        opaqueData =3D OVMA::bind(CGF, ov, RValue::get(result.getPointer()=
));
+
+      // Otherwise, just bind it.
+      } else {
+        opaqueData =3D OVMA::bind(CGF, ov, ov->getSourceExpr());
+      }
+      opaques.push_back(opaqueData);
+
+    // Otherwise, if the expression is the result, evaluate it
+    // and remember the result.
+    } else if (semantic =3D=3D resultExpr) {
+      result =3D tryEmitARCRetainScalarExpr(CGF, semantic);
+
+    // Otherwise, evaluate the expression in an ignored context.
+    } else {
+      CGF.EmitIgnoredExpr(semantic);
+    }
+  }
+
+  // Unbind all the opaques now.
+  for (unsigned i =3D 0, e =3D opaques.size(); i !=3D e; ++i)
+    opaques[i].unbind(CGF);
+
+  return result;
+}
+
 static TryEmitResult
 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
   // Look through cleanups.
   if (const ExprWithCleanups *cleanups =3D dyn_cast<ExprWithCleanups>(e)) {
+    CGF.enterFullExpression(cleanups);
     CodeGenFunction::RunCleanupsScope scope(CGF);
     return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
   }
@@ -2331,12 +2542,6 @@
         return TryEmitResult(result, true);
       }
=20
-      case CK_GetObjCProperty: {
-        llvm::Value *result =3D emitARCRetainCall(CGF, ce);
-        if (resultType) result =3D CGF.Builder.CreateBitCast(result, resul=
tType);
-        return TryEmitResult(result, true);
-      }
-
       default:
         break;
       }
@@ -2358,6 +2563,17 @@
       llvm::Value *result =3D emitARCRetainCall(CGF, e);
       if (resultType) result =3D CGF.Builder.CreateBitCast(result, resultT=
ype);
       return TryEmitResult(result, true);
+
+    // Look through pseudo-object expressions.
+    } else if (const PseudoObjectExpr *pseudo =3D dyn_cast<PseudoObjectExp=
r>(e)) {
+      TryEmitResult result
+        =3D tryEmitARCRetainPseudoObject(CGF, pseudo);
+      if (resultType) {
+        llvm::Value *value =3D result.getPointer();
+        value =3D CGF.Builder.CreateBitCast(value, resultType);
+        result.setPointer(value);
+      }
+      return result;
     }
=20
     // Conservatively halt the search at any other expression kind.
@@ -2424,17 +2640,19 @@
=20
 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
   // In ARC, retain and autorelease the expression.
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     // Do so before running any cleanups for the full-expression.
     // tryEmitARCRetainScalarExpr does make an effort to do things
     // inside cleanups, but there are crazy cases like
     //   @throw A().foo;
     // where a full retain+autorelease is required and would
     // otherwise happen after the destructor for the temporary.
+    if (const ExprWithCleanups *ewc =3D dyn_cast<ExprWithCleanups>(expr)) {
+      enterFullExpression(ewc);
+      expr =3D ewc->getSubExpr();
+    }
+
     CodeGenFunction::RunCleanupsScope cleanups(*this);
-    if (const ExprWithCleanups *ewc =3D dyn_cast<ExprWithCleanups>(expr))
-      expr =3D ewc->getSubExpr();
-
     return EmitARCRetainAutoreleaseScalarExpr(expr);
   }
=20
@@ -2468,12 +2686,8 @@
   // If the RHS was emitted retained, expand this.
   if (hasImmediateRetain) {
     llvm::Value *oldValue =3D
-      EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
-                       lvalue.getAlignment(), e->getType(),
-                       lvalue.getTBAAInfo());
-    EmitStoreOfScalar(value, lvalue.getAddress(),
-                      lvalue.isVolatileQualified(), lvalue.getAlignment(),
-                      e->getType(), lvalue.getTBAAInfo());
+      EmitLoadOfScalar(lvalue);
+    EmitStoreOfScalar(value, lvalue);
     EmitARCRelease(oldValue, /*precise*/ false);
   } else {
     value =3D EmitARCStoreStrong(lvalue, value, ignored);
@@ -2487,15 +2701,13 @@
   llvm::Value *value =3D EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
   LValue lvalue =3D EmitLValue(e->getLHS());
=20
-  EmitStoreOfScalar(value, lvalue.getAddress(),
-                    lvalue.isVolatileQualified(), lvalue.getAlignment(),
-                    e->getType(), lvalue.getTBAAInfo());
+  EmitStoreOfScalar(value, lvalue);
=20
   return std::pair<LValue,llvm::Value*>(lvalue, value);
 }
=20
 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
-                                             const ObjCAutoreleasePoolStmt=
 &ARPS) {
+                                          const ObjCAutoreleasePoolStmt &A=
RPS) {
   const Stmt *subStmt =3D ARPS.getSubStmt();
   const CompoundStmt &S =3D cast<CompoundStmt>(*subStmt);
=20
@@ -2526,7 +2738,7 @@
 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
   // We just use an inline assembly.
   llvm::FunctionType *extenderType
-    =3D llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
+    =3D llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
   llvm::Value *extender
     =3D llvm::InlineAsm::get(extenderType,
                            /* assembly */ "",
@@ -2537,4 +2749,226 @@
   Builder.CreateCall(extender, object)->setDoesNotThrow();
 }
=20
+/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type w=
ith
+/// non-trivial copy assignment function, produce following helper functio=
n.
+/// static void copyHelper(Ty *dest, const Ty *source) { *dest =3D *source=
; }
+///
+llvm::Constant *
+CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
+                                        const ObjCPropertyImplDecl *PID) {
+  // FIXME. This api is for NeXt runtime only for now.
+  if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
+    return 0;
+  QualType Ty =3D PID->getPropertyIvarDecl()->getType();
+  if (!Ty->isRecordType())
+    return 0;
+  const ObjCPropertyDecl *PD =3D PID->getPropertyDecl();
+  if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
+    return 0;
+  llvm::Constant * HelperFn =3D 0;
+  if (hasTrivialSetExpr(PID))
+    return 0;
+  assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
+  if ((HelperFn =3D CGM.getAtomicSetterHelperFnMap(Ty)))
+    return HelperFn;
+ =20
+  ASTContext &C =3D getContext();
+  IdentifierInfo *II
+    =3D &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
+  FunctionDecl *FD =3D FunctionDecl::Create(C,
+                                          C.getTranslationUnitDecl(),
+                                          SourceLocation(),
+                                          SourceLocation(), II, C.VoidTy, =
0,
+                                          SC_Static,
+                                          SC_None,
+                                          false,
+                                          false);
+ =20
+  QualType DestTy =3D C.getPointerType(Ty);
+  QualType SrcTy =3D Ty;
+  SrcTy.addConst();
+  SrcTy =3D C.getPointerType(SrcTy);
+ =20
+  FunctionArgList args;
+  ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
+  args.push_back(&dstDecl);
+  ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
+  args.push_back(&srcDecl);
+ =20
+  const CGFunctionInfo &FI =3D
+    CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
+                                              FunctionType::ExtInfo(),
+                                              RequiredArgs::All);
+ =20
+  llvm::FunctionType *LTy =3D CGM.getTypes().GetFunctionType(FI);
+ =20
+  llvm::Function *Fn =3D
+    llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
+                           "__assign_helper_atomic_property_",
+                           &CGM.getModule());
+ =20
+  if (CGM.getModuleDebugInfo())
+    DebugInfo =3D CGM.getModuleDebugInfo();
+ =20
+ =20
+  StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
+ =20
+  DeclRefExpr DstExpr(&dstDecl, false, DestTy,
+                      VK_RValue, SourceLocation());
+  UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
+                    VK_LValue, OK_Ordinary, SourceLocation());
+ =20
+  DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
+                      VK_RValue, SourceLocation());
+  UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
+                    VK_LValue, OK_Ordinary, SourceLocation());
+ =20
+  Expr *Args[2] =3D { &DST, &SRC };
+  CallExpr *CalleeExp =3D cast<CallExpr>(PID->getSetterCXXAssignment());
+  CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
+                              Args, 2, DestTy->getPointeeType(),=20
+                              VK_LValue, SourceLocation());
+ =20
+  EmitStmt(&TheCall);
+
+  FinishFunction();
+  HelperFn =3D llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
+  CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
+  return HelperFn;
+}
+
+llvm::Constant *
+CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
+                                            const ObjCPropertyImplDecl *PI=
D) {
+  // FIXME. This api is for NeXt runtime only for now.
+  if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
+    return 0;
+  const ObjCPropertyDecl *PD =3D PID->getPropertyDecl();
+  QualType Ty =3D PD->getType();
+  if (!Ty->isRecordType())
+    return 0;
+  if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
+    return 0;
+  llvm::Constant * HelperFn =3D 0;
+ =20
+  if (hasTrivialGetExpr(PID))
+    return 0;
+  assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null=
");
+  if ((HelperFn =3D CGM.getAtomicGetterHelperFnMap(Ty)))
+    return HelperFn;
+ =20
+ =20
+  ASTContext &C =3D getContext();
+  IdentifierInfo *II
+  =3D &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
+  FunctionDecl *FD =3D FunctionDecl::Create(C,
+                                          C.getTranslationUnitDecl(),
+                                          SourceLocation(),
+                                          SourceLocation(), II, C.VoidTy, =
0,
+                                          SC_Static,
+                                          SC_None,
+                                          false,
+                                          false);
+ =20
+  QualType DestTy =3D C.getPointerType(Ty);
+  QualType SrcTy =3D Ty;
+  SrcTy.addConst();
+  SrcTy =3D C.getPointerType(SrcTy);
+ =20
+  FunctionArgList args;
+  ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
+  args.push_back(&dstDecl);
+  ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
+  args.push_back(&srcDecl);
+ =20
+  const CGFunctionInfo &FI =3D
+  CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
+                                            FunctionType::ExtInfo(),
+                                            RequiredArgs::All);
+ =20
+  llvm::FunctionType *LTy =3D CGM.getTypes().GetFunctionType(FI);
+ =20
+  llvm::Function *Fn =3D
+  llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
+                         "__copy_helper_atomic_property_", &CGM.getModule(=
));
+ =20
+  if (CGM.getModuleDebugInfo())
+    DebugInfo =3D CGM.getModuleDebugInfo();
+ =20
+ =20
+  StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
+ =20
+  DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
+                      VK_RValue, SourceLocation());
+ =20
+  UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
+                    VK_LValue, OK_Ordinary, SourceLocation());
+ =20
+  CXXConstructExpr *CXXConstExpr =3D=20
+    cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
+ =20
+  SmallVector<Expr*, 4> ConstructorArgs;
+  ConstructorArgs.push_back(&SRC);
+  CXXConstructExpr::arg_iterator A =3D CXXConstExpr->arg_begin();
+  ++A;
+ =20
+  for (CXXConstructExpr::arg_iterator AEnd =3D CXXConstExpr->arg_end();
+       A !=3D AEnd; ++A)
+    ConstructorArgs.push_back(*A);
+ =20
+  CXXConstructExpr *TheCXXConstructExpr =3D
+    CXXConstructExpr::Create(C, Ty, SourceLocation(),
+                             CXXConstExpr->getConstructor(),
+                             CXXConstExpr->isElidable(),
+                             &ConstructorArgs[0], ConstructorArgs.size(),
+                             CXXConstExpr->hadMultipleCandidates(),
+                             CXXConstExpr->isListInitialization(),
+                             CXXConstExpr->requiresZeroInitialization(),
+                             CXXConstExpr->getConstructionKind(),
+                             SourceRange());
+ =20
+  DeclRefExpr DstExpr(&dstDecl, false, DestTy,
+                      VK_RValue, SourceLocation());
+ =20
+  RValue DV =3D EmitAnyExpr(&DstExpr);
+  CharUnits Alignment
+    =3D getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
+  EmitAggExpr(TheCXXConstructExpr,=20
+              AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifie=
rs(),
+                                    AggValueSlot::IsDestructed,
+                                    AggValueSlot::DoesNotNeedGCBarriers,
+                                    AggValueSlot::IsNotAliased));
+ =20
+  FinishFunction();
+  HelperFn =3D llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
+  CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
+  return HelperFn;
+}
+
+llvm::Value *
+CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType =
Ty) {
+  // Get selectors for retain/autorelease.
+  IdentifierInfo *CopyID =3D &getContext().Idents.get("copy");
+  Selector CopySelector =3D
+      getContext().Selectors.getNullarySelector(CopyID);
+  IdentifierInfo *AutoreleaseID =3D &getContext().Idents.get("autorelease"=
);
+  Selector AutoreleaseSelector =3D
+      getContext().Selectors.getNullarySelector(AutoreleaseID);
+
+  // Emit calls to retain/autorelease.
+  CGObjCRuntime &Runtime =3D CGM.getObjCRuntime();
+  llvm::Value *Val =3D Block;
+  RValue Result;
+  Result =3D Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
+                                       Ty, CopySelector,
+                                       Val, CallArgList(), 0, 0);
+  Val =3D Result.getScalarVal();
+  Result =3D Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
+                                       Ty, AutoreleaseSelector,
+                                       Val, CallArgList(), 0, 0);
+  Val =3D Result.getScalarVal();
+  return Val;
+}
+
+
 CGObjCRuntime::~CGObjCRuntime() {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGObjCGNU.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCGNU.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCGNU.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -18,7 +18,6 @@
 #include "CodeGenModule.h"
 #include "CodeGenFunction.h"
 #include "CGCleanup.h"
-
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
@@ -104,8 +103,6 @@
 /// GNUstep).
 class CGObjCGNU : public CGObjCRuntime {
 protected:
-  /// The module that is using this class
-  CodeGenModule &CGM;
   /// The LLVM module into which output is inserted
   llvm::Module &TheModule;
   /// strut objc_super.  Used for sending messages to super.  This structu=
re
@@ -187,7 +184,7 @@
     std::string name =3D prefix + Str;
     llvm::Constant *ConstStr =3D TheModule.getGlobalVariable(name);
     if (!ConstStr) {
-      llvm::Constant *value =3D llvm::ConstantArray::get(VMContext, Str, t=
rue);
+      llvm::Constant *value =3D llvm::ConstantDataArray::getString(VMConte=
xt,Str);
       ConstStr =3D new llvm::GlobalVariable(TheModule, value->getType(), t=
rue,
               llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
     }
@@ -288,6 +285,10 @@
   LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakRea=
dFn,=20
     WeakAssignFn, GlobalAssignFn;
=20
+  typedef std::pair<std::string, std::string> ClassAliasPair;
+  /// All classes that have aliases set for them.
+  std::vector<ClassAliasPair> ClassAliases;
+
 protected:
   /// Function used for throwing Objective-C exceptions.
   LazyRuntimeFunction ExceptionThrowFn;
@@ -336,10 +337,9 @@
   /// containing a size and an array of structures containing instance var=
iable
   /// metadata.  This is used purely for introspection in the fragile ABI.=
  In
   /// the non-fragile ABI, it's used for instance variable fixup.
-  llvm::Constant *GenerateIvarList(
-      const SmallVectorImpl<llvm::Constant *>  &IvarNames,
-      const SmallVectorImpl<llvm::Constant *>  &IvarTypes,
-      const SmallVectorImpl<llvm::Constant *>  &IvarOffsets);
+  llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
+                                   ArrayRef<llvm::Constant *> IvarTypes,
+                                   ArrayRef<llvm::Constant *> IvarOffsets);
   /// Generates a method list structure.  This is a structure containing a=
 size
   /// and an array of structures containing method metadata.
   ///
@@ -347,8 +347,8 @@
   /// pointer allowing them to be chained together in a linked list.
   llvm::Constant *GenerateMethodList(const StringRef &ClassName,
       const StringRef &CategoryName,
-      const SmallVectorImpl<Selector>  &MethodSels,
-      const SmallVectorImpl<llvm::Constant *>  &MethodTypes,
+      ArrayRef<Selector> MethodSels,
+      ArrayRef<llvm::Constant *> MethodTypes,
       bool isClassMethodList);
   /// Emits an empty protocol.  This is used for @protocol() where no prot=
ocol
   /// is found.  The runtime will (hopefully) fix up the pointer to refer =
to the
@@ -361,8 +361,7 @@
         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
   /// Generates a list of referenced protocols.  Classes, categories, and
   /// protocols all use this structure.
-  llvm::Constant *GenerateProtocolList(
-      const SmallVectorImpl<std::string> &Protocols);
+  llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
   /// To ensure that all protocols are seen by the runtime, we add a categ=
ory on
   /// a class defined in the runtime, declaring no methods, but adopting t=
he
   /// protocols.  This is a horribly ugly hack, but it allows us to collec=
t all
@@ -387,8 +386,8 @@
   /// Generates a method list.  This is used by protocols to define the re=
quired
   /// and optional methods.
   llvm::Constant *GenerateProtocolMethodList(
-      const SmallVectorImpl<llvm::Constant *>  &MethodNames,
-      const SmallVectorImpl<llvm::Constant *>  &MethodTypes);
+      ArrayRef<llvm::Constant *> MethodNames,
+      ArrayRef<llvm::Constant *> MethodTypes);
   /// Returns a selector with the specified type encoding.  An empty strin=
g is
   /// used to return an untyped selector (with the types field set to NULL=
).
   llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel,
@@ -427,7 +426,7 @@
   /// significant bit being assumed to come first in the bitfield.  Theref=
ore,
   /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
   /// while a bitfield / with the 63rd bit set will be 1<<64.
-  llvm::Constant *MakeBitField(llvm::SmallVectorImpl<bool> &bits);
+  llvm::Constant *MakeBitField(ArrayRef<bool> bits);
 public:
   CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
       unsigned protocolClassVersion);
@@ -466,13 +465,17 @@
                                          const ObjCContainerDecl *CD);
   virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
+  virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
   virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
                                            const ObjCProtocolDecl *PD);
   virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
   virtual llvm::Function *ModuleInitFunction();
   virtual llvm::Constant *GetPropertyGetFunction();
   virtual llvm::Constant *GetPropertySetFunction();
+  virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,=20
+                                                          bool copy);
   virtual llvm::Constant *GetSetStructFunction();
+  virtual llvm::Constant *GetCppAtomicObjectFunction();
   virtual llvm::Constant *GetGetStructFunction();
   virtual llvm::Constant *EnumerationMutationFunction();
=20
@@ -539,8 +542,8 @@
                                  llvm::MDNode *node) {
     CGBuilderTy &Builder =3D CGF.Builder;
     llvm::Value *args[] =3D {
-      EnforceType(Builder, Receiver, IdTy),
-      EnforceType(Builder, cmd, SelectorTy) };
+            EnforceType(Builder, Receiver, IdTy),
+            EnforceType(Builder, cmd, SelectorTy) };
     llvm::CallSite imp =3D CGF.EmitCallOrInvoke(MsgLookupFn, args);
     imp->setMetadata(msgSendMDKind, node);
     return imp.getInstruction();
@@ -599,9 +602,9 @@
       LookupFn->setDoesNotCapture(1);
=20
       llvm::Value *args[] =3D {
-        EnforceType(Builder, ReceiverPtr, PtrToIdTy),
-        EnforceType(Builder, cmd, SelectorTy),
-        EnforceType(Builder, self, IdTy) };
+              EnforceType(Builder, ReceiverPtr, PtrToIdTy),
+              EnforceType(Builder, cmd, SelectorTy),
+              EnforceType(Builder, self, IdTy) };
       llvm::CallSite slot =3D CGF.EmitCallOrInvoke(LookupFn, args);
       slot.setOnlyReadsMemory();
       slot->setMetadata(msgSendMDKind, node);
@@ -638,7 +641,7 @@
       SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
               PtrToObjCSuperTy, SelectorTy, NULL);
       // If we're in ObjC++ mode, then we want to make=20
-      if (CGM.getLangOptions().CPlusPlus) {
+      if (CGM.getLangOpts().CPlusPlus) {
         llvm::Type *VoidTy =3D llvm::Type::getVoidTy(VMContext);
         // void *__cxa_begin_catch(void *e)
         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
@@ -683,9 +686,9 @@
=20
 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
     unsigned protocolClassVersion)
-  : CGM(cgm), TheModule(CGM.getModule()), VMContext(cgm.getLLVMContext()),
-  ClassPtrAlias(0), MetaClassPtrAlias(0), RuntimeVersion(runtimeABIVersion=
),
-  ProtocolVersion(protocolClassVersion) {
+  : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
+    VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0=
),
+    RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersio=
n) {
=20
   msgSendMDKind =3D VMContext.getMDKindID("GNUObjCMessageSend");
=20
@@ -770,7 +773,7 @@
   IMPTy =3D llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMP=
Args,
               true));
=20
-  const LangOptions &Opts =3D CGM.getLangOptions();
+  const LangOptions &Opts =3D CGM.getLangOpts();
   if ((Opts.getGC() !=3D LangOptions::NonGC) || Opts.ObjCAutoRefCount)
     RuntimeVersion =3D 10;
=20
@@ -879,14 +882,14 @@
 }
=20
 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
-  if (!CGM.getLangOptions().CPlusPlus) {
+  if (!CGM.getLangOpts().CPlusPlus) {
       if (T->isObjCIdType()
           || T->isObjCQualifiedIdType()) {
         // With the old ABI, there was only one kind of catchall, which br=
oke
         // foreign exceptions.  With the new ABI, we use __objc_id_typeinf=
o as
         // a pointer indicating object catchalls, and NULL to indicate real
         // catchalls
-        if (CGM.getLangOptions().ObjCNonFragileABI) {
+        if (CGM.getLangOpts().ObjCNonFragileABI) {
           return MakeConstantString("@id");
         } else {
           return 0;
@@ -930,7 +933,8 @@
=20
   // Return the existing typeinfo if it exists
   llvm::Constant *typeinfo =3D TheModule.getGlobalVariable(typeinfoName);
-  if (typeinfo) return typeinfo;
+  if (typeinfo)
+    return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
=20
   // Otherwise create it.
=20
@@ -970,12 +974,27 @@
   if (old !=3D ObjCStrings.end())
     return old->getValue();
=20
+  StringRef StringClass =3D CGM.getLangOpts().ObjCConstantStringClass;
+
+  if (StringClass.empty()) StringClass =3D "NXConstantString";
+
+  std::string Sym =3D "_OBJC_CLASS_";
+  Sym +=3D StringClass;
+
+  llvm::Constant *isa =3D TheModule.getNamedGlobal(Sym);
+
+  if (!isa)
+    isa =3D new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */fals=
e,
+            llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
+  else if (isa->getType() !=3D PtrToIdTy)
+    isa =3D llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
+
   std::vector<llvm::Constant*> Ivars;
-  Ivars.push_back(NULLPtr);
+  Ivars.push_back(isa);
   Ivars.push_back(MakeConstantString(Str));
   Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
   llvm::Constant *ObjCStr =3D MakeGlobal(
-    llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
+    llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
     Ivars, ".objc_str");
   ObjCStr =3D llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
   ObjCStrings[Str] =3D ObjCStr;
@@ -998,7 +1017,7 @@
                                     const CallArgList &CallArgs,
                                     const ObjCMethodDecl *Method) {
   CGBuilderTy &Builder =3D CGF.Builder;
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::GCOnly) {
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::GCOnly) {
     if (Sel =3D=3D RetainSel || Sel =3D=3D AutoreleaseSel) {
       return RValue::get(EnforceType(Builder, Receiver,
                   CGM.getTypes().ConvertType(ResultType)));
@@ -1017,9 +1036,7 @@
   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
   ActualArgs.addFrom(CallArgs);
=20
-  CodeGenTypes &Types =3D CGM.getTypes();
-  const CGFunctionInfo &FnInfo =3D Types.getFunctionInfo(ResultType, Actua=
lArgs,
-                                                       FunctionType::ExtIn=
fo());
+  MessageSendInfo MSI =3D getMessageSendInfo(Method, ResultType, ActualArg=
s);
=20
   llvm::Value *ReceiverClass =3D 0;
   if (isCategoryImpl) {
@@ -1072,12 +1089,10 @@
   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1)=
);
=20
   ObjCSuper =3D EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
-  llvm::FunctionType *impType =3D
-    Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
=20
   // Get the IMP
   llvm::Value *imp =3D LookupIMPSuper(CGF, ObjCSuper, cmd);
-  imp =3D EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
+  imp =3D EnforceType(Builder, imp, MSI.MessengerType);
=20
   llvm::Value *impMD[] =3D {
       llvm::MDString::get(VMContext, Sel.getAsString()),
@@ -1087,8 +1102,7 @@
   llvm::MDNode *node =3D llvm::MDNode::get(VMContext, impMD);
=20
   llvm::Instruction *call;
-  RValue msgRet =3D CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
-      0, &call);
+  RValue msgRet =3D CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0,=
 &call);
   call->setMetadata(msgSendMDKind, node);
   return msgRet;
 }
@@ -1106,7 +1120,7 @@
   CGBuilderTy &Builder =3D CGF.Builder;
=20
   // Strip out message sends to retain / release in GC mode
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::GCOnly) {
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::GCOnly) {
     if (Sel =3D=3D RetainSel || Sel =3D=3D AutoreleaseSel) {
       return RValue::get(EnforceType(Builder, Receiver,
                   CGM.getTypes().ConvertType(ResultType)));
@@ -1161,27 +1175,46 @@
    };
   llvm::MDNode *node =3D llvm::MDNode::get(VMContext, impMD);
=20
-  // Get the IMP to call
-  llvm::Value *imp =3D LookupIMP(CGF, Receiver, cmd, node);
-
   CallArgList ActualArgs;
   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
   ActualArgs.addFrom(CallArgs);
=20
-  CodeGenTypes &Types =3D CGM.getTypes();
-  const CGFunctionInfo &FnInfo =3D Types.getFunctionInfo(ResultType, Actua=
lArgs,
-                                                       FunctionType::ExtIn=
fo());
-  llvm::FunctionType *impType =3D
-    Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
-  imp =3D EnforceType(Builder, imp, llvm::PointerType::getUnqual(impType));
+  MessageSendInfo MSI =3D getMessageSendInfo(Method, ResultType, ActualArg=
s);
=20
+  // Get the IMP to call
+  llvm::Value *imp;
=20
-  // For sender-aware dispatch, we pass the sender as the third argument t=
o a
-  // lookup function.  When sending messages from C code, the sender is ni=
l.
-  // objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
+  // If we have non-legacy dispatch specified, we try using the objc_msgSe=
nd()
+  // functions.  These are not supported on all platforms (or all runtimes=
 on a
+  // given platform), so we=20
+  switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
+    case CodeGenOptions::Legacy:
+      imp =3D LookupIMP(CGF, Receiver, cmd, node);
+      break;
+    case CodeGenOptions::Mixed:
+    case CodeGenOptions::NonLegacy:
+      if (CGM.ReturnTypeUsesFPRet(ResultType)) {
+        imp =3D CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, Id=
Ty, true),
+                                  "objc_msgSend_fpret");
+      } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
+        // The actual types here don't matter - we're going to bitcast the
+        // function anyway
+        imp =3D CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, Id=
Ty, true),
+                                  "objc_msgSend_stret");
+      } else {
+        imp =3D CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, Id=
Ty, true),
+                                  "objc_msgSend");
+      }
+  }
+
+  // Reset the receiver in case the lookup modified it
+  ActualArgs[0] =3D CallArg(RValue::get(Receiver), ASTIdTy, false);
+
+  imp =3D EnforceType(Builder, imp, MSI.MessengerType);
+
   llvm::Instruction *call;
-  RValue msgRet =3D CGF.EmitCall(FnInfo, imp, Return, ActualArgs,
+  RValue msgRet =3D CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
       0, &call);
   call->setMetadata(msgSendMDKind, node);
=20
@@ -1225,11 +1258,12 @@
=20
 /// Generates a MethodList.  Used in construction of a objc_class and
 /// objc_category structures.
-llvm::Constant *CGObjCGNU::GenerateMethodList(const StringRef &ClassName,
-                                              const StringRef &CategoryNam=
e,
-    const SmallVectorImpl<Selector> &MethodSels,
-    const SmallVectorImpl<llvm::Constant *> &MethodTypes,
-    bool isClassMethodList) {
+llvm::Constant *CGObjCGNU::
+GenerateMethodList(const StringRef &ClassName,
+                   const StringRef &CategoryName,
+                   ArrayRef<Selector> MethodSels,
+                   ArrayRef<llvm::Constant *> MethodTypes,
+                   bool isClassMethodList) {
   if (MethodSels.empty())
     return NULLPtr;
   // Get the method structure type.
@@ -1282,10 +1316,10 @@
 }
=20
 /// Generates an IvarList.  Used in construction of a objc_class.
-llvm::Constant *CGObjCGNU::GenerateIvarList(
-    const SmallVectorImpl<llvm::Constant *>  &IvarNames,
-    const SmallVectorImpl<llvm::Constant *>  &IvarTypes,
-    const SmallVectorImpl<llvm::Constant *>  &IvarOffsets) {
+llvm::Constant *CGObjCGNU::
+GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
+                 ArrayRef<llvm::Constant *> IvarTypes,
+                 ArrayRef<llvm::Constant *> IvarOffsets) {
   if (IvarNames.size() =3D=3D 0)
     return NULLPtr;
   // Get the method structure type.
@@ -1345,7 +1379,7 @@
   // anyway; the classes will still work with the GNU runtime, they will j=
ust
   // be ignored.
   llvm::StructType *ClassTy =3D llvm::StructType::get(
-      PtrToInt8Ty,        // class_pointer
+      PtrToInt8Ty,        // isa=20
       PtrToInt8Ty,        // super_class
       PtrToInt8Ty,        // name
       LongTy,             // version
@@ -1396,14 +1430,25 @@
   Elements.push_back(WeakIvarBitmap);
   // Create an instance of the structure
   // This is now an externally visible symbol, so that we can speed up cla=
ss
-  // messages in the next ABI.
-  return MakeGlobal(ClassTy, Elements, (isMeta ? "_OBJC_METACLASS_":
-      "_OBJC_CLASS_") + std::string(Name), llvm::GlobalValue::ExternalLink=
age);
+  // messages in the next ABI.  We may already have some weak references to
+  // this, so check and fix them properly.
+  std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
+          std::string(Name));
+  llvm::GlobalVariable *ClassRef =3D TheModule.getNamedGlobal(ClassSym);
+  llvm::Constant *Class =3D MakeGlobal(ClassTy, Elements, ClassSym,
+          llvm::GlobalValue::ExternalLinkage);
+  if (ClassRef) {
+      ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
+                  ClassRef->getType()));
+      ClassRef->removeFromParent();
+      Class->setName(ClassSym);
+  }
+  return Class;
 }
=20
-llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
-    const SmallVectorImpl<llvm::Constant *>  &MethodNames,
-    const SmallVectorImpl<llvm::Constant *>  &MethodTypes) {
+llvm::Constant *CGObjCGNU::
+GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
+                           ArrayRef<llvm::Constant *> MethodTypes) {
   // Get the method structure type.
   llvm::StructType *ObjCMethodDescTy =3D llvm::StructType::get(
     PtrToInt8Ty, // Really a selector, but the runtime does the casting fo=
r us.
@@ -1430,8 +1475,7 @@
 }
=20
 // Create the protocol list structure used in classes, categories and so on
-llvm::Constant *CGObjCGNU::GenerateProtocolList(
-    const SmallVectorImpl<std::string> &Protocols) {
+llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Proto=
cols){
   llvm::ArrayType *ProtocolArrayTy =3D llvm::ArrayType::get(PtrToInt8Ty,
       Protocols.size());
   llvm::StructType *ProtocolListTy =3D llvm::StructType::get(
@@ -1506,6 +1550,11 @@
 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
   ASTContext &Context =3D CGM.getContext();
   std::string ProtocolName =3D PD->getNameAsString();
+ =20
+  // Use the protocol definition, if there is one.
+  if (const ObjCProtocolDecl *Def =3D PD->getDefinition())
+    PD =3D Def;
+
   SmallVector<std::string, 16> Protocols;
   for (ObjCProtocolDecl::protocol_iterator PI =3D PD->protocol_begin(),
        E =3D PD->protocol_end(); PI !=3D E; ++PI)
@@ -1723,7 +1772,7 @@
 /// significant bit being assumed to come first in the bitfield.  Therefor=
e, a
 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, wh=
ile a
 /// bitfield / with the 63rd bit set will be 1<<64.
-llvm::Constant *CGObjCGNU::MakeBitField(llvm::SmallVectorImpl<bool> &bits)=
 {
+llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
   int bitCount =3D bits.size();
   int ptrBits =3D
         (TheModule.getPointerSize() =3D=3D llvm::Module::Pointer32) ? 32 :=
 64;
@@ -1881,6 +1930,15 @@
           ".objc_property_list");
 }
=20
+void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
+  // Get the class declaration for which the alias is specified.
+  ObjCInterfaceDecl *ClassDecl =3D
+    const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
+  std::string ClassName =3D ClassDecl->getNameAsString();
+  std::string AliasName =3D OAD->getNameAsString();
+  ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
+}
+
 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
   ASTContext &Context =3D CGM.getContext();
=20
@@ -1926,7 +1984,7 @@
     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantit=
y();
   // For non-fragile ivars, set the instance size to 0 - {the size of just=
 this
   // class}.  The runtime will then set this to the correct value on load.
-  if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
+  if (CGM.getContext().getLangOpts().ObjCNonFragileABI) {
     instanceSize =3D 0 - (instanceSize - superInstanceSize);
   }
=20
@@ -1941,7 +1999,7 @@
       // Get the offset
       uint64_t BaseOffset =3D ComputeIvarBaseOffset(CGM, OID, IVD);
       uint64_t Offset =3D BaseOffset;
-      if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
+      if (CGM.getContext().getLangOpts().ObjCNonFragileABI) {
         Offset =3D BaseOffset - superInstanceSize;
       }
       llvm::Constant *OffsetValue =3D llvm::ConstantInt::get(IntTy, Offset=
);
@@ -2013,9 +2071,9 @@
   }
   // Collect the names of referenced protocols
   SmallVector<std::string, 16> Protocols;
-  const ObjCList<ObjCProtocolDecl> &Protos =3DClassDecl->getReferencedProt=
ocols();
-  for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protos.begin(),
-       E =3D Protos.end(); I !=3D E; ++I)
+  for (ObjCInterfaceDecl::protocol_iterator
+         I =3D ClassDecl->protocol_begin(),
+         E =3D ClassDecl->protocol_end(); I !=3D E; ++I)
     Protocols.push_back((*I)->getNameAsString());
=20
=20
@@ -2063,15 +2121,16 @@
       // Get the existing variable, if one exists.
       llvm::GlobalVariable *offset =3D TheModule.getNamedGlobal(Name);
       if (offset) {
-          offset->setInitializer(offsetValue);
-          // If this is the real definition, change its linkage type so th=
at
-          // different modules will use this one, rather than their private
-          // copy.
-          offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
+        offset->setInitializer(offsetValue);
+        // If this is the real definition, change its linkage type so that
+        // different modules will use this one, rather than their private
+        // copy.
+        offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
       } else {
-          // Add a new alias if there isn't one already.
-          offset =3D new llvm::GlobalVariable(TheModule, offsetValue->getT=
ype(),
-                  false, llvm::GlobalValue::ExternalLinkage, offsetValue, =
Name);
+        // Add a new alias if there isn't one already.
+        offset =3D new llvm::GlobalVariable(TheModule, offsetValue->getTyp=
e(),
+                false, llvm::GlobalValue::ExternalLinkage, offsetValue, Na=
me);
+        (void) offset; // Silence dead store warning.
       }
       ++ivarIndex;
   }
@@ -2135,7 +2194,7 @@
         ConstantStrings.size() + 1);
     ConstantStrings.push_back(NULLPtr);
=20
-    StringRef StringClass =3D CGM.getLangOptions().ObjCConstantStringClass;
+    StringRef StringClass =3D CGM.getLangOpts().ObjCConstantStringClass;
=20
     if (StringClass.empty()) StringClass =3D "NXConstantString";
=20
@@ -2263,12 +2322,12 @@
   Elements.push_back(SymTab);
=20
   if (RuntimeVersion >=3D 10)
-    switch (CGM.getLangOptions().getGC()) {
+    switch (CGM.getLangOpts().getGC()) {
       case LangOptions::GCOnly:
         Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
         break;
       case LangOptions::NonGC:
-        if (CGM.getLangOptions().ObjCAutoRefCount)
+        if (CGM.getLangOpts().ObjCAutoRefCount)
           Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
         else
           Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
@@ -2296,6 +2355,46 @@
                             llvm::PointerType::getUnqual(ModuleTy), true);
   llvm::Value *Register =3D CGM.CreateRuntimeFunction(FT, "__objc_exec_cla=
ss");
   Builder.CreateCall(Register, Module);
+
+  if (!ClassAliases.empty()) {
+    llvm::Type *ArgTypes[2] =3D {PtrTy, PtrToInt8Ty};
+    llvm::FunctionType *RegisterAliasTy =3D
+      llvm::FunctionType::get(Builder.getVoidTy(),
+                              ArgTypes, false);
+    llvm::Function *RegisterAlias =3D llvm::Function::Create(
+      RegisterAliasTy,
+      llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
+      &TheModule);
+    llvm::BasicBlock *AliasBB =3D
+      llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
+    llvm::BasicBlock *NoAliasBB =3D
+      llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
+
+    // Branch based on whether the runtime provided class_registerAlias_np=
()
+    llvm::Value *HasRegisterAlias =3D Builder.CreateICmpNE(RegisterAlias,
+            llvm::Constant::getNullValue(RegisterAlias->getType()));
+    Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
+
+    // The true branch (has alias registration fucntion):
+    Builder.SetInsertPoint(AliasBB);
+    // Emit alias registration calls:
+    for (std::vector<ClassAliasPair>::iterator iter =3D ClassAliases.begin=
();
+       iter !=3D ClassAliases.end(); ++iter) {
+       llvm::Constant *TheClass =3D
+         TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(=
),
+            true);
+       if (0 !=3D TheClass) {
+         TheClass =3D llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
+         Builder.CreateCall2(RegisterAlias, TheClass,
+            MakeConstantString(iter->second));
+       }
+    }
+    // Jump to end:
+    Builder.CreateBr(NoAliasBB);
+
+    // Missing alias registration function, just return from the function:
+    Builder.SetInsertPoint(NoAliasBB);
+  }
   Builder.CreateRetVoid();
=20
   return LoadFunction;
@@ -2312,7 +2411,7 @@
=20
   CodeGenTypes &Types =3D CGM.getTypes();
   llvm::FunctionType *MethodTy =3D
-    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
+    Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
   std::string FunctionName =3D SymbolNameForMethod(ClassName, CategoryName,
       MethodName, isClassMethod);
=20
@@ -2332,12 +2431,20 @@
   return SetPropertyFn;
 }
=20
+llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
+                                                           bool copy) {
+  return 0;
+}
+
 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
   return GetStructPropertyFn;
 }
 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
   return SetStructPropertyFn;
 }
+llvm::Constant *CGObjCGNU::GetCppAtomicObjectFunction() {
+  return 0;
+}
=20
 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
   return EnumerationMutationFn;
@@ -2487,7 +2594,7 @@
     // to replace it with the real version for a library.  In non-PIC code=
 you
     // must compile with the fragile ABI if you want to use ivars from a
     // GCC-compiled class.
-    if (CGM.getLangOptions().PICLevel) {
+    if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
       llvm::GlobalVariable *IvarOffsetGV =3D new llvm::GlobalVariable(TheM=
odule,
             Int32Ty, false,
             llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
@@ -2533,7 +2640,7 @@
 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
                          const ObjCInterfaceDecl *Interface,
                          const ObjCIvarDecl *Ivar) {
-  if (CGM.getLangOptions().ObjCNonFragileABI) {
+  if (CGM.getLangOpts().ObjCNonFragileABI) {
     Interface =3D FindIvarInterface(CGM.getContext(), Interface, Ivar);
     if (RuntimeVersion < 10)
       return CGF.Builder.CreateZExtOrBitCast(
@@ -2547,7 +2654,10 @@
       Offset =3D new llvm::GlobalVariable(TheModule, IntTy,
           false, llvm::GlobalValue::LinkOnceAnyLinkage,
           llvm::Constant::getNullValue(IntTy), name);
-    return CGF.Builder.CreateLoad(Offset);
+    Offset =3D CGF.Builder.CreateLoad(Offset);
+    if (Offset->getType() !=3D PtrDiffTy)
+      Offset =3D CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
+    return Offset;
   }
   uint64_t Offset =3D ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
@@ -2555,7 +2665,7 @@
=20
 CGObjCRuntime *
 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
-  if (CGM.getLangOptions().ObjCNonFragileABI)
+  if (CGM.getLangOpts().ObjCNonFragileABI)
     return new CGObjCGNUstep(CGM);
   return new CGObjCGCC(CGM);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGObjCMac.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCMac.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -42,11 +42,8 @@
 using namespace clang;
 using namespace CodeGen;
=20
-
 namespace {
=20
-typedef std::vector<llvm::Constant*> ConstantVector;
-
 // FIXME: We should find a nicer way to make the labels for metadata, stri=
ng
 // concatenation is lame.
=20
@@ -92,13 +89,28 @@
   /// would be unbalanced.
   llvm::Constant *getMessageSendFpretFn() const {
     llvm::Type *params[] =3D { ObjectPtrTy, SelectorPtrTy };
-    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(
-                                             llvm::Type::getDoubleTy(VMCon=
text),
-                                                        params, true),
+    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
+                                                             params, true),
                                      "objc_msgSend_fpret");
=20
   }
=20
+  /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
+  ///
+  /// The messenger used when the return value is returned in two values o=
n the
+  /// x87 floating point stack; without a special entrypoint, the nil case
+  /// would be unbalanced. Only used on 64-bit X86.
+  llvm::Constant *getMessageSendFp2retFn() const {
+    llvm::Type *params[] =3D { ObjectPtrTy, SelectorPtrTy };
+    llvm::Type *longDoubleType =3D llvm::Type::getX86_FP80Ty(VMContext);
+    llvm::Type *resultType =3D=20
+      llvm::StructType::get(longDoubleType, longDoubleType, NULL);
+
+    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
+                                                             params, true),
+                                     "objc_msgSend_fp2ret");
+  }
+
   /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
   ///
   /// The messenger used for super calls, which have different dispatch
@@ -159,7 +171,7 @@
=20
 public:
   llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
-  llvm::Type *Int8PtrTy;
+  llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
=20
   /// ObjectPtrTy - LLVM type for object handles (typeof(id))
   llvm::Type *ObjectPtrTy;
@@ -169,10 +181,26 @@
=20
   /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
   llvm::Type *SelectorPtrTy;
+ =20
+private:
   /// ProtocolPtrTy - LLVM type for external protocol handles
   /// (typeof(Protocol))
   llvm::Type *ExternalProtocolPtrTy;
-
+ =20
+public:
+  llvm::Type *getExternalProtocolPtrTy() {
+    if (!ExternalProtocolPtrTy) {
+      // FIXME: It would be nice to unify this with the opaque type, so th=
at the
+      // IR comes out a bit cleaner.
+      CodeGen::CodeGenTypes &Types =3D CGM.getTypes();
+      ASTContext &Ctx =3D CGM.getContext();
+      llvm::Type *T =3D Types.ConvertType(Ctx.getObjCProtoType());
+      ExternalProtocolPtrTy =3D llvm::PointerType::getUnqual(T);
+    }
+   =20
+    return ExternalProtocolPtrTy;
+  }
+ =20
   // SuperCTy - clang type for struct objc_super.
   QualType SuperCTy;
   // SuperPtrCTy - clang type for struct objc_super *.
@@ -213,9 +241,9 @@
     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified=
());
     Params.push_back(Ctx.BoolTy);
     llvm::FunctionType *FTy =3D
-      Types.GetFunctionType(Types.getFunctionInfo(IdType, Params,
-                                                  FunctionType::ExtInfo()),
-                            false);
+      Types.GetFunctionType(Types.arrangeFunctionType(IdType, Params,
+                                                      FunctionType::ExtInf=
o(),
+                                                      RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
   }
=20
@@ -233,12 +261,47 @@
     Params.push_back(Ctx.BoolTy);
     Params.push_back(Ctx.BoolTy);
     llvm::FunctionType *FTy =3D
-      Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
-                                                  FunctionType::ExtInfo()),
-                            false);
+      Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
+                                                      FunctionType::ExtInf=
o(),
+                                                      RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
   }
=20
+  llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
+    CodeGen::CodeGenTypes &Types =3D CGM.getTypes();
+    ASTContext &Ctx =3D CGM.getContext();
+    // void objc_setProperty_atomic(id self, SEL _cmd,=20
+    //                              id newValue, ptrdiff_t offset);
+    // void objc_setProperty_nonatomic(id self, SEL _cmd,=20
+    //                                 id newValue, ptrdiff_t offset);
+    // void objc_setProperty_atomic_copy(id self, SEL _cmd,=20
+    //                                   id newValue, ptrdiff_t offset);
+    // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,=20
+    //                                      id newValue, ptrdiff_t offset);
+   =20
+    SmallVector<CanQualType,4> Params;
+    CanQualType IdType =3D Ctx.getCanonicalParamType(Ctx.getObjCIdType());
+    CanQualType SelType =3D Ctx.getCanonicalParamType(Ctx.getObjCSelType()=
);
+    Params.push_back(IdType);
+    Params.push_back(SelType);
+    Params.push_back(IdType);
+    Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified=
());
+    llvm::FunctionType *FTy =3D
+    Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
+                                                    FunctionType::ExtInfo(=
),
+                                                    RequiredArgs::All));
+    const char *name;
+    if (atomic && copy)
+      name =3D "objc_setProperty_atomic_copy";
+    else if (atomic && !copy)
+      name =3D "objc_setProperty_atomic";
+    else if (!atomic && copy)
+      name =3D "objc_setProperty_nonatomic_copy";
+    else
+      name =3D "objc_setProperty_nonatomic";
+     =20
+    return CGM.CreateRuntimeFunction(FTy, name);
+  }
  =20
   llvm::Constant *getCopyStructFn() {
     CodeGen::CodeGenTypes &Types =3D CGM.getTypes();
@@ -251,12 +314,31 @@
     Params.push_back(Ctx.BoolTy);
     Params.push_back(Ctx.BoolTy);
     llvm::FunctionType *FTy =3D
-      Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
-                                                  FunctionType::ExtInfo()),
-                            false);
+      Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
+                                                      FunctionType::ExtInf=
o(),
+                                                      RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
   }
  =20
+  /// This routine declares and returns address of:
+  /// void objc_copyCppObjectAtomic(
+  ///         void *dest, const void *src,=20
+  ///         void (*copyHelper) (void *dest, const void *source));
+  llvm::Constant *getCppAtomicObjectFunction() {
+    CodeGen::CodeGenTypes &Types =3D CGM.getTypes();
+    ASTContext &Ctx =3D CGM.getContext();
+    /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *h=
elper);
+    SmallVector<CanQualType,3> Params;
+    Params.push_back(Ctx.VoidPtrTy);
+    Params.push_back(Ctx.VoidPtrTy);
+    Params.push_back(Ctx.VoidPtrTy);
+    llvm::FunctionType *FTy =3D
+      Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
+                                                      FunctionType::ExtInf=
o(),
+                                                      RequiredArgs::All));
+    return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
+  }
+ =20
   llvm::Constant *getEnumerationMutationFn() {
     CodeGen::CodeGenTypes &Types =3D CGM.getTypes();
     ASTContext &Ctx =3D CGM.getContext();
@@ -264,9 +346,9 @@
     SmallVector<CanQualType,1> Params;
     Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
     llvm::FunctionType *FTy =3D
-      Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params,
-                                                  FunctionType::ExtInfo()),
-                            false);
+      Types.GetFunctionType(Types.arrangeFunctionType(Ctx.VoidTy, Params,
+                                                      FunctionType::ExtInf=
o(),
+                                                      RequiredArgs::All));
     return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
   }
=20
@@ -391,6 +473,14 @@
     return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn=
();
   }
=20
+  llvm::Constant *getSendFp2retFn(bool IsSuper) const {
+    return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
+  }
+
+  llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
+    return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
+  }
+
   ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
   ~ObjCCommonTypesHelper(){}
 };
@@ -492,7 +582,8 @@
     llvm::Type *params[] =3D { CGM.Int32Ty->getPointerTo() };
     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
                                                              params, false=
),
-                                     "_setjmp");
+                                     "_setjmp",
+                                     llvm::Attribute::ReturnsTwice);
   }
=20
 public:
@@ -663,7 +754,6 @@
   };
=20
 protected:
-  CodeGen::CodeGenModule &CGM;
   llvm::LLVMContext &VMContext;
   // FIXME! May not be needing this after all.
   unsigned ObjCABI;
@@ -718,16 +808,16 @@
   llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
=20
   /// DefinedClasses - List of defined classes.
-  std::vector<llvm::GlobalValue*> DefinedClasses;
+  llvm::SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
=20
   /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
-  std::vector<llvm::GlobalValue*> DefinedNonLazyClasses;
+  llvm::SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
=20
   /// DefinedCategories - List of defined categories.
-  std::vector<llvm::GlobalValue*> DefinedCategories;
+  llvm::SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
=20
   /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
-  std::vector<llvm::GlobalValue*> DefinedNonLazyCategories;
+  llvm::SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
=20
   /// GetNameForMethod - Return a name for the given method.
   /// \param[out] NameOut - The return value.
@@ -741,10 +831,11 @@
   llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
=20
   /// GetMethodVarType - Return a unique constant for the given
-  /// selector's name. The return value has type char *.
+  /// method's type encoding string. The return value has type char *.
=20
   // FIXME: This is a horrible name.
-  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
+  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
+                                   bool Extended =3D false);
   llvm::Constant *GetMethodVarType(const FieldDecl *D);
=20
   /// GetPropertyName - Return a unique constant for the given
@@ -775,7 +866,7 @@
   void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
                            const llvm::StructLayout *Layout,
                            const RecordDecl *RD,
-                           const SmallVectorImpl<const FieldDecl*> &RecFie=
lds,
+                           ArrayRef<const FieldDecl*> RecFields,
                            unsigned int BytePos, bool ForStrongLayout,
                            bool &HasUnion);
=20
@@ -791,12 +882,19 @@
                                    const ObjCContainerDecl *OCD,
                                    const ObjCCommonTypesHelper &ObjCTypes);
=20
+  /// EmitProtocolMethodTypes - Generate the array of extended method type=20
+  /// strings. The return value has type Int8PtrPtrTy.
+  llvm::Constant *EmitProtocolMethodTypes(Twine Name,=20
+                                          ArrayRef<llvm::Constant*> Method=
Types,
+                                       const ObjCCommonTypesHelper &ObjCTy=
pes);
+
   /// PushProtocolProperties - Push protocol's property on the input stack.
-  void PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*, 16>=
 &PropertySet,
-                              std::vector<llvm::Constant*> &Properties,
-                                   const Decl *Container,
-                                   const ObjCProtocolDecl *PROTO,
-                                   const ObjCCommonTypesHelper &ObjCTypes);
+  void PushProtocolProperties(
+    llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
+    llvm::SmallVectorImpl<llvm::Constant*> &Properties,
+    const Decl *Container,
+    const ObjCProtocolDecl *PROTO,
+    const ObjCCommonTypesHelper &ObjCTypes);
=20
   /// GetProtocolRef - Return a reference to the internal protocol
   /// description, creating an empty one if it has not been
@@ -840,10 +938,10 @@
=20
 public:
   CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
-    CGM(cgm), VMContext(cgm.getLLVMContext()) { }
+    CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
=20
   virtual llvm::Constant *GenerateConstantString(const StringLiteral *SL);
-
+ =20
   virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
                                          const ObjCContainerDecl *CD=3D0);
=20
@@ -915,7 +1013,7 @@
   /// given implementation. The return value has type ClassPtrTy.
   llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
                                 llvm::Constant *Protocols,
-                                const ConstantVector &Methods);
+                                ArrayRef<llvm::Constant*> Methods);
=20
   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
=20
@@ -925,7 +1023,7 @@
   /// implementation. The return value has type MethodListPtrTy.
   llvm::Constant *EmitMethodList(Twine Name,
                                  const char *Section,
-                                 const ConstantVector &Methods);
+                                 ArrayRef<llvm::Constant*> Methods);
=20
   /// EmitMethodDescList - Emit a method description list for a list of
   /// method declarations.
@@ -940,7 +1038,7 @@
   /// The return value has type MethodDescriptionListPtrTy.
   llvm::Constant *EmitMethodDescList(Twine Name,
                                      const char *Section,
-                                     const ConstantVector &Methods);
+                                     ArrayRef<llvm::Constant*> Methods);
=20
   /// GetOrEmitProtocol - Get the protocol object for the given
   /// declaration, emitting it if necessary. The return value has type
@@ -959,8 +1057,9 @@
   /// ProtocolExtensionPtrTy.
   llvm::Constant *
   EmitProtocolExtension(const ObjCProtocolDecl *PD,
-                        const ConstantVector &OptInstanceMethods,
-                        const ConstantVector &OptClassMethods);
+                        ArrayRef<llvm::Constant*> OptInstanceMethods,
+                        ArrayRef<llvm::Constant*> OptClassMethods,
+                        ArrayRef<llvm::Constant*> MethodTypesExt);
=20
   /// EmitProtocolList - Generate the list of referenced
   /// protocols. The return value has type ProtocolListPtrTy.
@@ -1016,13 +1115,18 @@
=20
   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
=20
+  virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {}
+
   virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
                                            const ObjCProtocolDecl *PD);
=20
   virtual llvm::Constant *GetPropertyGetFunction();
   virtual llvm::Constant *GetPropertySetFunction();
+  virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,=20
+                                                          bool copy);
   virtual llvm::Constant *GetGetStructFunction();
   virtual llvm::Constant *GetSetStructFunction();
+  virtual llvm::Constant *GetCppAtomicObjectFunction();
   virtual llvm::Constant *EnumerationMutationFunction();
=20
   virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
@@ -1096,7 +1200,7 @@
=20
   /// AddModuleClassList - Add the given list of class pointers to the
   /// module with the provided symbol and section names.
-  void AddModuleClassList(const std::vector<llvm::GlobalValue*> &Container,
+  void AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
                           const char *SymbolName,
                           const char *SectionName);
=20
@@ -1118,7 +1222,7 @@
   /// implementation. The return value has type MethodListnfABITy.
   llvm::Constant *EmitMethodList(Twine Name,
                                  const char *Section,
-                                 const ConstantVector &Methods);
+                                 ArrayRef<llvm::Constant*> Methods);
   /// EmitIvarList - Emit the ivar list for the given
   /// implementation. If ForClass is true the list of class ivars
   /// (i.e. metaclass ivars) is emitted, otherwise the list of
@@ -1267,6 +1371,9 @@
   virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
=20
   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
+
+  virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {}
+
   virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
                                            const ObjCProtocolDecl *PD);
=20
@@ -1279,12 +1386,20 @@
     return ObjCTypes.getSetPropertyFn();
   }
  =20
+  virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,=20
+                                                          bool copy) {
+    return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
+  }
+ =20
   virtual llvm::Constant *GetSetStructFunction() {
     return ObjCTypes.getCopyStructFn();
   }
   virtual llvm::Constant *GetGetStructFunction() {
     return ObjCTypes.getCopyStructFn();
   }
+  virtual llvm::Constant *GetCppAtomicObjectFunction() {
+    return ObjCTypes.getCppAtomicObjectFunction();
+  }
  =20
   virtual llvm::Constant *EnumerationMutationFunction() {
     return ObjCTypes.getEnumerationMutationFn();
@@ -1325,13 +1440,13 @@
 /// value.
 struct NullReturnState {
   llvm::BasicBlock *NullBB;
-
-  NullReturnState() : NullBB(0) {}
+  llvm::BasicBlock *callBB;
+  NullReturnState() : NullBB(0), callBB(0) {}
=20
   void init(CodeGenFunction &CGF, llvm::Value *receiver) {
     // Make blocks for the null-init and call edges.
     NullBB =3D CGF.createBasicBlock("msgSend.nullinit");
-    llvm::BasicBlock *callBB =3D CGF.createBasicBlock("msgSend.call");
+    callBB =3D CGF.createBasicBlock("msgSend.call");
=20
     // Check for a null receiver and, if there is one, jump to the
     // null-init test.
@@ -1342,8 +1457,16 @@
     CGF.EmitBlock(callBB);
   }
=20
-  RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType=
) {
+  RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
+                  const CallArgList &CallArgs,
+                  const ObjCMethodDecl *Method) {
     if (!NullBB) return result;
+   =20
+    llvm::Value *NullInitPtr =3D 0;
+    if (result.isScalar() && !resultType->isVoidType()) {
+      NullInitPtr =3D CGF.CreateTempAlloca(result.getScalarVal()->getType(=
));
+      CGF.Builder.CreateStore(result.getScalarVal(), NullInitPtr);
+    }
=20
     // Finish the call path.
     llvm::BasicBlock *contBB =3D CGF.createBasicBlock("msgSend.cont");
@@ -1351,13 +1474,54 @@
=20
     // Emit the null-init block and perform the null-initialization there.
     CGF.EmitBlock(NullBB);
-    assert(result.isAggregate() && "null init of non-aggregate result?");
-    CGF.EmitNullInitialization(result.getAggregateAddr(), resultType);
-
-    // Jump to the continuation block.
+   =20
+    // Release consumed arguments along the null-receiver path.
+    if (Method) {
+      CallArgList::const_iterator I =3D CallArgs.begin();
+      for (ObjCMethodDecl::param_const_iterator i =3D Method->param_begin(=
),
+           e =3D Method->param_end(); i !=3D e; ++i, ++I) {
+        const ParmVarDecl *ParamDecl =3D (*i);
+        if (ParamDecl->hasAttr<NSConsumedAttr>()) {
+          RValue RV =3D I->RV;
+          assert(RV.isScalar() &&=20
+                 "NullReturnState::complete - arg not on object");
+          CGF.EmitARCRelease(RV.getScalarVal(), true);
+        }
+      }
+    }
+   =20
+    if (result.isScalar()) {
+      if (NullInitPtr)
+        CGF.EmitNullInitialization(NullInitPtr, resultType);
+      // Jump to the continuation block.
+      CGF.EmitBlock(contBB);
+      return NullInitPtr ? RValue::get(CGF.Builder.CreateLoad(NullInitPtr)=
)=20
+      : result;
+    }
+   =20
+    if (!resultType->isAnyComplexType()) {
+      assert(result.isAggregate() && "null init of non-aggregate result?");
+      CGF.EmitNullInitialization(result.getAggregateAddr(), resultType);
+      // Jump to the continuation block.
+      CGF.EmitBlock(contBB);
+      return result;
+    }
+
+    // _Complex type
+    // FIXME. Now easy to handle any other scalar type whose result is ret=
urned
+    // in memory due to ABI limitations.
     CGF.EmitBlock(contBB);
-
-    return result;
+    CodeGenFunction::ComplexPairTy CallCV =3D result.getComplexVal();
+    llvm::Type *MemberType =3D CallCV.first->getType();
+    llvm::Constant *ZeroCV =3D llvm::Constant::getNullValue(MemberType);
+    // Create phi instruction for scalar complex value.
+    llvm::PHINode *PHIReal =3D CGF.Builder.CreatePHI(MemberType, 2);
+    PHIReal->addIncoming(ZeroCV, NullBB);
+    PHIReal->addIncoming(CallCV.first, callBB);
+    llvm::PHINode *PHIImag =3D CGF.Builder.CreatePHI(MemberType, 2);
+    PHIImag->addIncoming(ZeroCV, NullBB);
+    PHIImag->addIncoming(CallCV.second, callBB);
+    return RValue::getComplex(PHIReal, PHIImag);
   }
 };
=20
@@ -1428,7 +1592,6 @@
     return CGM.GetAddrOfRTTIDescriptor(T,  /*ForEH=3D*/true);
  =20
   llvm_unreachable("asking for catch type for ObjC type in fragile runtime=
");
-  return 0;
 }
=20
 /// Generate a constant CFString object.
@@ -1452,11 +1615,15 @@
=20
 llvm::Constant *CGObjCCommonMac::GenerateConstantString(
   const StringLiteral *SL) {
-  return (CGM.getLangOptions().NoConstantCFStrings =3D=3D 0 ?=20
+  return (CGM.getLangOpts().NoConstantCFStrings =3D=3D 0 ?=20
           CGM.GetAddrOfConstantCFString(SL) :
           CGM.GetAddrOfConstantString(SL));
 }
=20
+enum {
+  kCFTaggedObjectID_Integer =3D (1 << 1) + 1
+};
+
 /// Generates a message send where the super is the receiver.  This is
 /// a message send to self with special delivery semantics indicating
 /// which class's method should be called.
@@ -1553,11 +1720,8 @@
   ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
   ActualArgs.addFrom(CallArgs);
=20
-  CodeGenTypes &Types =3D CGM.getTypes();
-  const CGFunctionInfo &FnInfo =3D Types.getFunctionInfo(ResultType, Actua=
lArgs,
-                                                       FunctionType::ExtIn=
fo());
-  llvm::FunctionType *FTy =3D
-    Types.GetFunctionType(FnInfo, Method ? Method->isVariadic() : false);
+  // If we're calling a method, use the formal signature.
+  MessageSendInfo MSI =3D getMessageSendInfo(Method, ResultType, ActualArg=
s);
=20
   if (Method)
     assert(CGM.getContext().getCanonicalType(Method->getResultType()) =3D=
=3D
@@ -1567,20 +1731,38 @@
   NullReturnState nullReturn;
=20
   llvm::Constant *Fn =3D NULL;
-  if (CGM.ReturnTypeUsesSRet(FnInfo)) {
+  if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
     if (!IsSuper) nullReturn.init(CGF, Arg0);
     Fn =3D (ObjCABI =3D=3D 2) ?  ObjCTypes.getSendStretFn2(IsSuper)
       : ObjCTypes.getSendStretFn(IsSuper);
   } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
     Fn =3D (ObjCABI =3D=3D 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
       : ObjCTypes.getSendFpretFn(IsSuper);
+  } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
+    Fn =3D (ObjCABI =3D=3D 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
+      : ObjCTypes.getSendFp2retFn(IsSuper);
   } else {
     Fn =3D (ObjCABI =3D=3D 2) ? ObjCTypes.getSendFn2(IsSuper)
       : ObjCTypes.getSendFn(IsSuper);
   }
-  Fn =3D llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(F=
Ty));
-  RValue rvalue =3D CGF.EmitCall(FnInfo, Fn, Return, ActualArgs);
-  return nullReturn.complete(CGF, rvalue, ResultType);
+ =20
+  bool requiresnullCheck =3D false;
+  if (CGM.getLangOpts().ObjCAutoRefCount && Method)
+    for (ObjCMethodDecl::param_const_iterator i =3D Method->param_begin(),
+         e =3D Method->param_end(); i !=3D e; ++i) {
+      const ParmVarDecl *ParamDecl =3D (*i);
+      if (ParamDecl->hasAttr<NSConsumedAttr>()) {
+        if (!nullReturn.NullBB)
+          nullReturn.init(CGF, Arg0);
+        requiresnullCheck =3D true;
+        break;
+      }
+    }
+ =20
+  Fn =3D llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
+  RValue rvalue =3D CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs);
+  return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
+                             requiresnullCheck ? Method : 0);
 }
=20
 static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT) {
@@ -1590,6 +1772,10 @@
   if (FQT.isObjCGCWeak() || FQT.getObjCLifetime() =3D=3D Qualifiers::OCL_W=
eak)
     return Qualifiers::Weak;
  =20
+  // check for __unsafe_unretained
+  if (FQT.getObjCLifetime() =3D=3D Qualifiers::OCL_ExplicitNone)
+    return Qualifiers::GCNone;
+ =20
   if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
     return Qualifiers::Strong;
  =20
@@ -1601,11 +1787,10 @@
=20
 llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
                                                 const CGBlockInfo &blockIn=
fo) {
-  llvm::Constant *nullPtr =3D=20
-    llvm::Constant::getNullValue(llvm::Type::getInt8PtrTy(VMContext));
-
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::NonGC &&
-      !CGM.getLangOptions().ObjCAutoRefCount)
+  llvm::Constant *nullPtr =3D llvm::Constant::getNullValue(CGM.Int8PtrTy);
+
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::NonGC &&
+      !CGM.getLangOpts().ObjCAutoRefCount)
     return nullPtr;
=20
   bool hasUnion =3D false;
@@ -1673,10 +1858,10 @@
  =20
   std::string BitMap;
   llvm::Constant *C =3D BuildIvarLayoutBitmap(BitMap);
-  if (CGM.getLangOptions().ObjCGCBitmapPrint) {
+  if (CGM.getLangOpts().ObjCGCBitmapPrint) {
     printf("\n block variable layout for block: ");
     const unsigned char *s =3D (unsigned char*)BitMap.c_str();
-    for (unsigned i =3D 0; i < BitMap.size(); i++)
+    for (unsigned i =3D 0, e =3D BitMap.size(); i < e; i++)
       if (!(s[i] & 0xf0))
         printf("0x0%x%s", s[i], s[i] !=3D 0 ? ", " : "");
       else
@@ -1694,7 +1879,7 @@
   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
=20
   return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
-                                        ObjCTypes.ExternalProtocolPtrTy);
+                                        ObjCTypes.getExternalProtocolPtrTy=
());
 }
=20
 void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
@@ -1729,12 +1914,16 @@
 See EmitProtocolExtension().
 */
 llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
-  llvm::GlobalVariable *&Entry =3D Protocols[PD->getIdentifier()];
+  llvm::GlobalVariable *Entry =3D Protocols[PD->getIdentifier()];
=20
   // Early exit if a defining object has already been generated.
   if (Entry && Entry->hasInitializer())
     return Entry;
=20
+  // Use the protocol definition, if there is one.
+  if (const ObjCProtocolDecl *Def =3D PD->getDefinition())
+    PD =3D Def;
+
   // FIXME: I don't understand why gcc generates this, or where it is
   // resolved. Investigate. Its also wasteful to look this up over and ove=
r.
   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
@@ -1742,6 +1931,7 @@
   // Construct method lists.
   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
+  std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
   for (ObjCProtocolDecl::instmeth_iterator
          i =3D PD->instmeth_begin(), e =3D PD->instmeth_end(); i !=3D e; +=
+i) {
     ObjCMethodDecl *MD =3D *i;
@@ -1751,8 +1941,10 @@
    =20
     if (MD->getImplementationControl() =3D=3D ObjCMethodDecl::Optional) {
       OptInstanceMethods.push_back(C);
+      OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
     } else {
       InstanceMethods.push_back(C);
+      MethodTypesExt.push_back(GetMethodVarType(MD, true));
     }
   }
=20
@@ -1765,26 +1957,30 @@
=20
     if (MD->getImplementationControl() =3D=3D ObjCMethodDecl::Optional) {
       OptClassMethods.push_back(C);
+      OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
     } else {
       ClassMethods.push_back(C);
+      MethodTypesExt.push_back(GetMethodVarType(MD, true));
     }
   }
=20
-  std::vector<llvm::Constant*> Values(5);
-  Values[0] =3D EmitProtocolExtension(PD, OptInstanceMethods, OptClassMeth=
ods);
-  Values[1] =3D GetClassName(PD->getIdentifier());
-  Values[2] =3D
+  MethodTypesExt.insert(MethodTypesExt.end(),
+                        OptMethodTypesExt.begin(), OptMethodTypesExt.end()=
);
+
+  llvm::Constant *Values[] =3D {
+    EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,=20
+                          MethodTypesExt),
+    GetClassName(PD->getIdentifier()),
     EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getName(),
                      PD->protocol_begin(),
-                     PD->protocol_end());
-  Values[3] =3D
+                     PD->protocol_end()),
     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getNam=
e(),
                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
-                       InstanceMethods);
-  Values[4] =3D
+                       InstanceMethods),
     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
-                       ClassMethods);
+                       ClassMethods)
+  };
   llvm::Constant *Init =3D llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
                                                    Values);
=20
@@ -1801,6 +1997,8 @@
     Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
     // FIXME: Is this necessary? Why only for protocol?
     Entry->setAlignment(4);
+
+    Protocols[PD->getIdentifier()] =3D Entry;
   }
   CGM.AddUsedGlobal(Entry);
=20
@@ -1833,31 +2031,34 @@
   struct objc_method_description_list *optional_instance_methods;
   struct objc_method_description_list *optional_class_methods;
   struct objc_property_list *instance_properties;
+  const char ** extendedMethodTypes;
   };
 */
 llvm::Constant *
 CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
-                                 const ConstantVector &OptInstanceMethods,
-                                 const ConstantVector &OptClassMethods) {
+                                 ArrayRef<llvm::Constant*> OptInstanceMeth=
ods,
+                                 ArrayRef<llvm::Constant*> OptClassMethods,
+                                 ArrayRef<llvm::Constant*> MethodTypesExt)=
 {
   uint64_t Size =3D
     CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
-  std::vector<llvm::Constant*> Values(4);
-  Values[0] =3D llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
-  Values[1] =3D
+  llvm::Constant *Values[] =3D {
+    llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
                        + PD->getName(),
                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
-                       OptInstanceMethods);
-  Values[2] =3D
+                       OptInstanceMethods),
     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getNa=
me(),
                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
-                       OptClassMethods);
-  Values[3] =3D EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getN=
ame(),
-                               0, PD, ObjCTypes);
+                       OptClassMethods),
+    EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getName(), 0, PD,
+                     ObjCTypes),
+    EmitProtocolMethodTypes("\01L_OBJC_PROTOCOL_METHOD_TYPES_" + PD->getNa=
me(),
+                            MethodTypesExt, ObjCTypes)
+  };
=20
   // Return null if no extension bits are used.
   if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
-      Values[3]->isNullValue())
+      Values[3]->isNullValue() && Values[4]->isNullValue())
     return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
=20
   llvm::Constant *Init =3D
@@ -1871,16 +2072,16 @@
=20
 /*
   struct objc_protocol_list {
-  struct objc_protocol_list *next;
-  long count;
-  Protocol *list[];
+    struct objc_protocol_list *next;
+    long count;
+    Protocol *list[];
   };
 */
 llvm::Constant *
 CGObjCMac::EmitProtocolList(Twine Name,
                             ObjCProtocolDecl::protocol_iterator begin,
                             ObjCProtocolDecl::protocol_iterator end) {
-  std::vector<llvm::Constant*> ProtocolRefs;
+  llvm::SmallVector<llvm::Constant*, 16> ProtocolRefs;
=20
   for (; begin !=3D end; ++begin)
     ProtocolRefs.push_back(GetProtocolRef(*begin));
@@ -1909,12 +2110,12 @@
   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
 }
=20
-void CGObjCCommonMac::PushProtocolProperties(llvm::SmallPtrSet<const Ident=
ifierInfo*, 16> &PropertySet,
-                                   std::vector<llvm::Constant*> &Propertie=
s,
-                                   const Decl *Container,
-                                   const ObjCProtocolDecl *PROTO,
-                                   const ObjCCommonTypesHelper &ObjCTypes)=
 {
-  std::vector<llvm::Constant*> Prop(2);
+void CGObjCCommonMac::
+PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &Proper=
tySet,
+                       llvm::SmallVectorImpl<llvm::Constant*> &Properties,
+                       const Decl *Container,
+                       const ObjCProtocolDecl *PROTO,
+                       const ObjCCommonTypesHelper &ObjCTypes) {
   for (ObjCProtocolDecl::protocol_iterator P =3D PROTO->protocol_begin(),
          E =3D PROTO->protocol_end(); P !=3D E; ++P)=20
     PushProtocolProperties(PropertySet, Properties, Container, (*P), ObjCT=
ypes);
@@ -1923,36 +2124,40 @@
     const ObjCPropertyDecl *PD =3D *I;
     if (!PropertySet.insert(PD->getIdentifier()))
       continue;
-    Prop[0] =3D GetPropertyName(PD->getIdentifier());
-    Prop[1] =3D GetPropertyTypeString(PD, Container);
+    llvm::Constant *Prop[] =3D {
+      GetPropertyName(PD->getIdentifier()),
+      GetPropertyTypeString(PD, Container)
+    };
     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, P=
rop));
   }
 }
=20
 /*
   struct _objc_property {
-  const char * const name;
-  const char * const attributes;
+    const char * const name;
+    const char * const attributes;
   };
=20
   struct _objc_property_list {
-  uint32_t entsize; // sizeof (struct _objc_property)
-  uint32_t prop_count;
-  struct _objc_property[prop_count];
+    uint32_t entsize; // sizeof (struct _objc_property)
+    uint32_t prop_count;
+    struct _objc_property[prop_count];
   };
 */
 llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
                                        const Decl *Container,
                                        const ObjCContainerDecl *OCD,
                                        const ObjCCommonTypesHelper &ObjCTy=
pes) {
-  std::vector<llvm::Constant*> Properties, Prop(2);
+  llvm::SmallVector<llvm::Constant*, 16> Properties;
   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
   for (ObjCContainerDecl::prop_iterator I =3D OCD->prop_begin(),
          E =3D OCD->prop_end(); I !=3D E; ++I) {
     const ObjCPropertyDecl *PD =3D *I;
     PropertySet.insert(PD->getIdentifier());
-    Prop[0] =3D GetPropertyName(PD->getIdentifier());
-    Prop[1] =3D GetPropertyTypeString(PD, Container);
+    llvm::Constant *Prop[] =3D {
+      GetPropertyName(PD->getIdentifier()),
+      GetPropertyTypeString(PD, Container)
+    };
     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
                                                    Prop));
   }
@@ -1993,6 +2198,26 @@
   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
 }
=20
+llvm::Constant *
+CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
+                                         ArrayRef<llvm::Constant*> MethodT=
ypes,
+                                         const ObjCCommonTypesHelper &ObjC=
Types) {
+  // Return null for empty list.
+  if (MethodTypes.empty())
+    return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
+
+  llvm::ArrayType *AT =3D llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
+                                             MethodTypes.size());
+  llvm::Constant *Init =3D llvm::ConstantArray::get(AT, MethodTypes);
+
+  llvm::GlobalVariable *GV =3D=20
+    CreateMetadataVar(Name, Init,
+                      (ObjCABI =3D=3D 2) ? "__DATA, __objc_const" : 0,
+                      (ObjCABI =3D=3D 2) ? 8 : 4,
+                      true);
+  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
+}
+
 /*
   struct objc_method_description_list {
   int count;
@@ -2001,11 +2226,11 @@
 */
 llvm::Constant *
 CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
-  std::vector<llvm::Constant*> Desc(2);
-  Desc[0] =3D
+  llvm::Constant *Desc[] =3D {
     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
-                                   ObjCTypes.SelectorPtrTy);
-  Desc[1] =3D GetMethodVarType(MD);
+                                   ObjCTypes.SelectorPtrTy),
+    GetMethodVarType(MD)
+  };
   if (!Desc[1])
     return 0;
  =20
@@ -2013,9 +2238,9 @@
                                    Desc);
 }
=20
-llvm::Constant *CGObjCMac::EmitMethodDescList(Twine Name,
-                                              const char *Section,
-                                              const ConstantVector &Method=
s) {
+llvm::Constant *
+CGObjCMac::EmitMethodDescList(Twine Name, const char *Section,
+                              ArrayRef<llvm::Constant*> Methods) {
   // Return null for empty list.
   if (Methods.empty())
     return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtr=
Ty);
@@ -2054,11 +2279,11 @@
   const ObjCCategoryDecl *Category =3D
     Interface->FindCategoryDeclaration(OCD->getIdentifier());
=20
-  llvm::SmallString<256> ExtName;
+  SmallString<256> ExtName;
   llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
                                      << OCD->getName();
=20
-  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
+  llvm::SmallVector<llvm::Constant*, 16> InstanceMethods, ClassMethods;
   for (ObjCCategoryImplDecl::instmeth_iterator
          i =3D OCD->instmeth_begin(), e =3D OCD->instmeth_end(); i !=3D e;=
 ++i) {
     // Instance methods should always be defined.
@@ -2164,7 +2389,7 @@
   if (ID->getClassInterface()->getVisibility() =3D=3D HiddenVisibility)
     Flags |=3D eClassFlags_Hidden;
=20
-  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
+  llvm::SmallVector<llvm::Constant*, 16> InstanceMethods, ClassMethods;
   for (ObjCImplementationDecl::instmeth_iterator
          i =3D ID->instmeth_begin(), e =3D ID->instmeth_end(); i !=3D e; +=
+i) {
     // Instance methods should always be defined.
@@ -2244,7 +2469,7 @@
=20
 llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
                                          llvm::Constant *Protocols,
-                                         const ConstantVector &Methods) {
+                                         ArrayRef<llvm::Constant*> Methods=
) {
   unsigned Flags =3D eClassFlags_Meta;
   unsigned Size =3D CGM.getTargetData().getTypeAllocSize(ObjCTypes.ClassTy=
);
=20
@@ -2384,19 +2609,19 @@
=20
 /*
   struct objc_ivar {
-  char *ivar_name;
-  char *ivar_type;
-  int ivar_offset;
+    char *ivar_name;
+    char *ivar_type;
+    int ivar_offset;
   };
=20
   struct objc_ivar_list {
-  int ivar_count;
-  struct objc_ivar list[count];
+    int ivar_count;
+    struct objc_ivar list[count];
   };
 */
 llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
                                         bool ForClass) {
-  std::vector<llvm::Constant*> Ivars, Ivar(3);
+  std::vector<llvm::Constant*> Ivars;
=20
   // When emitting the root class GCC emits ivar entries for the
   // actual class structure. It is not clear if we need to follow this
@@ -2413,10 +2638,12 @@
     // Ignore unnamed bit-fields.
     if (!IVD->getDeclName())
       continue;
-    Ivar[0] =3D GetMethodVarName(IVD->getIdentifier());
-    Ivar[1] =3D GetMethodVarType(IVD);
-    Ivar[2] =3D llvm::ConstantInt::get(ObjCTypes.IntTy,
-                                     ComputeIvarBaseOffset(CGM, OID, IVD));
+    llvm::Constant *Ivar[] =3D {
+      GetMethodVarName(IVD->getIdentifier()),
+      GetMethodVarType(IVD),
+      llvm::ConstantInt::get(ObjCTypes.IntTy,
+                             ComputeIvarBaseOffset(CGM, OID, IVD))
+    };
     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
   }
=20
@@ -2465,18 +2692,18 @@
   if (!Fn)
     return 0;
=20
-  std::vector<llvm::Constant*> Method(3);
-  Method[0] =3D
+  llvm::Constant *Method[] =3D {
     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
-                                   ObjCTypes.SelectorPtrTy);
-  Method[1] =3D GetMethodVarType(MD);
-  Method[2] =3D llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
+                                   ObjCTypes.SelectorPtrTy),
+    GetMethodVarType(MD),
+    llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
+  };
   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
 }
=20
 llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
                                           const char *Section,
-                                          const ConstantVector &Methods) {
+                                          ArrayRef<llvm::Constant*> Method=
s) {
   // Return null for empty list.
   if (Methods.empty())
     return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
@@ -2495,12 +2722,12 @@
=20
 llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
                                                 const ObjCContainerDecl *C=
D) {
-  llvm::SmallString<256> Name;
+  SmallString<256> Name;
   GetNameForMethod(OMD, CD, Name);
=20
   CodeGenTypes &Types =3D CGM.getTypes();
   llvm::FunctionType *MethodTy =3D
-    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
+    Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
   llvm::Function *Method =3D
     llvm::Function::Create(MethodTy,
                            llvm::GlobalValue::InternalLinkage,
@@ -2544,6 +2771,11 @@
   return ObjCTypes.getSetPropertyFn();
 }
=20
+llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,=20
+                                                           bool copy) {
+  return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
+}
+
 llvm::Constant *CGObjCMac::GetGetStructFunction() {
   return ObjCTypes.getCopyStructFn();
 }
@@ -2551,6 +2783,10 @@
   return ObjCTypes.getCopyStructFn();
 }
=20
+llvm::Constant *CGObjCMac::GetCppAtomicObjectFunction() {
+  return ObjCTypes.getCppAtomicObjectFunction();
+}
+
 llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
   return ObjCTypes.getEnumerationMutationFn();
 }
@@ -2959,6 +3195,7 @@
   llvm::CallInst *SetJmpResult =3D
     CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_=
result");
   SetJmpResult->setDoesNotThrow();
+  SetJmpResult->setCanReturnTwice();
=20
   // If setjmp returned 0, enter the protected block; otherwise,
   // branch to the handler.
@@ -3024,6 +3261,7 @@
         CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer,
                                "setjmp.result");
       SetJmpResult->setDoesNotThrow();
+      SetJmpResult->setCanReturnTwice();
=20
       llvm::Value *Threw =3D
         CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
@@ -3379,41 +3617,48 @@
=20
 void CGObjCCommonMac::EmitImageInfo() {
   unsigned version =3D 0; // Version is unused?
-  unsigned flags =3D 0;
-
-  // FIXME: Fix and continue?
-  if (CGM.getLangOptions().getGC() !=3D LangOptions::NonGC)
-    flags |=3D eImageInfo_GarbageCollected;
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::GCOnly)
-    flags |=3D eImageInfo_GCOnly;
-
-  // We never allow @synthesize of a superclass property.
-  flags |=3D eImageInfo_CorrectedSynthesize;
-
-  llvm::Type *Int32Ty =3D llvm::Type::getInt32Ty(VMContext);
- =20
-  // Emitted as int[2];
-  llvm::Constant *values[2] =3D {
-    llvm::ConstantInt::get(Int32Ty, version),
-    llvm::ConstantInt::get(Int32Ty, flags)
-  };
-  llvm::ArrayType *AT =3D llvm::ArrayType::get(Int32Ty, 2);
-
-  const char *Section;
-  if (ObjCABI =3D=3D 1)
-    Section =3D "__OBJC, __image_info,regular";
-  else
-    Section =3D "__DATA, __objc_imageinfo, regular, no_dead_strip";
-  llvm::GlobalVariable *GV =3D
-    CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
-                      llvm::ConstantArray::get(AT, values),
-                      Section,
-                      0,
-                      true);
-  GV->setConstant(true);
+  const char *Section =3D (ObjCABI =3D=3D 1) ?
+    "__OBJC, __image_info,regular" :
+    "__DATA, __objc_imageinfo, regular, no_dead_strip";
+
+  // Generate module-level named metadata to convey this information to the
+  // linker and code-gen.
+  llvm::Module &Mod =3D CGM.getModule();
+
+  // Add the ObjC ABI version to the module flags.
+  Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
+  Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
+                    version);
+  Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
+                    llvm::MDString::get(VMContext,Section));
+
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::NonGC) {
+    // Non-GC overrides those files which specify GC.
+    Mod.addModuleFlag(llvm::Module::Override,
+                      "Objective-C Garbage Collection", (uint32_t)0);
+  } else {
+    // Add the ObjC garbage collection value.
+    Mod.addModuleFlag(llvm::Module::Error,
+                      "Objective-C Garbage Collection",
+                      eImageInfo_GarbageCollected);
+
+    if (CGM.getLangOpts().getGC() =3D=3D LangOptions::GCOnly) {
+      // Add the ObjC GC Only value.
+      Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
+                        eImageInfo_GCOnly);
+
+      // Require that GC be specified and set to eImageInfo_GarbageCollect=
ed.
+      llvm::Value *Ops[2] =3D {
+        llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
+        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
+                               eImageInfo_GarbageCollected)
+      };
+      Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
+                        llvm::MDNode::get(VMContext, Ops));
+    }
+  }
 }
=20
-
 // struct objc_module {
 //   unsigned long version;
 //   unsigned long size;
@@ -3427,12 +3672,13 @@
 void CGObjCMac::EmitModuleInfo() {
   uint64_t Size =3D CGM.getTargetData().getTypeAllocSize(ObjCTypes.ModuleT=
y);
=20
-  std::vector<llvm::Constant*> Values(4);
-  Values[0] =3D llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
-  Values[1] =3D llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
-  // This used to be the filename, now it is unused. <rdr://4327263>
-  Values[2] =3D GetClassName(&CGM.getContext().Idents.get(""));
-  Values[3] =3D EmitModuleSymbols();
+  llvm::Constant *Values[] =3D {
+    llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
+    llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
+    // This used to be the filename, now it is unused. <rdr://4327263>
+    GetClassName(&CGM.getContext().Idents.get("")),
+    EmitModuleSymbols()
+  };
   CreateMetadataVar("\01L_OBJC_MODULES",
                     llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
                     "__OBJC,__module_info,regular,no_dead_strip",
@@ -3455,7 +3701,7 @@
=20
   // The runtime expects exactly the list of defined classes followed
   // by the list of defined categories, in a single array.
-  std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
+  SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
   for (unsigned i=3D0; i<NumClasses; i++)
     Symbols[i] =3D llvm::ConstantExpr::getBitCast(DefinedClasses[i],
                                                 ObjCTypes.Int8PtrTy);
@@ -3466,7 +3712,7 @@
=20
   Values[4] =3D
     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
-                                                  NumClasses + NumCategori=
es),
+                                                  Symbols.size()),
                              Symbols);
=20
   llvm::Constant *Init =3D llvm::ConstantStruct::getAnon(Values);
@@ -3531,8 +3777,8 @@
=20
   if (!Entry)
     Entry =3D CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
-                          llvm::ConstantArray::get(VMContext,
-                                                   Ident->getNameStart()),
+                              llvm::ConstantDataArray::getString(VMContext,
+                                                         Ident->getNameSta=
rt()),
                               ((ObjCABI =3D=3D 2) ?
                                "__TEXT,__objc_classname,cstring_literals" :
                                "__TEXT,__cstring,cstring_literals"),
@@ -3575,7 +3821,7 @@
 void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
                              const llvm::StructLayout *Layout,
                              const RecordDecl *RD,
-                             const SmallVectorImpl<const FieldDecl*> &RecF=
ields,
+                             ArrayRef<const FieldDecl*> RecFields,
                              unsigned int BytePos, bool ForStrongLayout,
                              bool &HasUnion) {
   bool IsUnion =3D (RD && RD->isUnion());
@@ -3593,7 +3839,7 @@
     return;
   unsigned WordSizeInBits =3D CGM.getContext().getTargetInfo().getPointerW=
idth(0);
   unsigned ByteSizeInBits =3D CGM.getContext().getTargetInfo().getCharWidt=
h();
-  if (!RD && CGM.getLangOptions().ObjCAutoRefCount) {
+  if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
     const FieldDecl *FirstField =3D RecFields[0];
     FirstFieldDelta =3D=20
       ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
@@ -3740,9 +3986,9 @@
 /// the given argument BitMap string container. Routine reads
 /// two containers, IvarsInfo and SkipIvars which are assumed to be
 /// filled already by the caller.
-llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string& BitMap=
) {
+llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap=
) {
   unsigned int WordsToScan, WordsToSkip;
-  llvm::Type *PtrTy =3D llvm::Type::getInt8PtrTy(VMContext);
+  llvm::Type *PtrTy =3D CGM.Int8PtrTy;
  =20
   // Build the string of skip/scan nibbles
   SmallVector<SKIP_SCAN, 32> SkipScanIvars;
@@ -3857,7 +4103,7 @@
  =20
   llvm::GlobalVariable * Entry =3D
   CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
-                    llvm::ConstantArray::get(VMContext, BitMap.c_str()),
+                    llvm::ConstantDataArray::getString(VMContext, BitMap,f=
alse),
                     ((ObjCABI =3D=3D 2) ?
                      "__TEXT,__objc_classname,cstring_literals" :
                      "__TEXT,__cstring,cstring_literals"),
@@ -3886,14 +4132,14 @@
   bool ForStrongLayout) {
   bool hasUnion =3D false;
=20
-  llvm::Type *PtrTy =3D llvm::Type::getInt8PtrTy(VMContext);
-  if (CGM.getLangOptions().getGC() =3D=3D LangOptions::NonGC &&
-      !CGM.getLangOptions().ObjCAutoRefCount)
+  llvm::Type *PtrTy =3D CGM.Int8PtrTy;
+  if (CGM.getLangOpts().getGC() =3D=3D LangOptions::NonGC &&
+      !CGM.getLangOpts().ObjCAutoRefCount)
     return llvm::Constant::getNullValue(PtrTy);
=20
   const ObjCInterfaceDecl *OI =3D OMD->getClassInterface();
   SmallVector<const FieldDecl*, 32> RecFields;
-  if (CGM.getLangOptions().ObjCAutoRefCount) {
+  if (CGM.getLangOpts().ObjCAutoRefCount) {
     for (const ObjCIvarDecl *IVD =3D OI->all_declared_ivar_begin();=20
          IVD; IVD =3D IVD->getNextIvar())
       RecFields.push_back(cast<FieldDecl>(IVD));
@@ -3925,12 +4171,12 @@
   std::string BitMap;
   llvm::Constant *C =3D BuildIvarLayoutBitmap(BitMap);
  =20
-   if (CGM.getLangOptions().ObjCGCBitmapPrint) {
+   if (CGM.getLangOpts().ObjCGCBitmapPrint) {
     printf("\n%s ivar layout for class '%s': ",
            ForStrongLayout ? "strong" : "weak",
            OMD->getClassInterface()->getName().data());
     const unsigned char *s =3D (unsigned char*)BitMap.c_str();
-    for (unsigned i =3D 0; i < BitMap.size(); i++)
+    for (unsigned i =3D 0, e =3D BitMap.size(); i < e; i++)
       if (!(s[i] & 0xf0))
         printf("0x0%x%s", s[i], s[i] !=3D 0 ? ", " : "");
       else
@@ -3943,10 +4189,10 @@
 llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
   llvm::GlobalVariable *&Entry =3D MethodVarNames[Sel];
=20
-  // FIXME: Avoid std::string copying.
+  // FIXME: Avoid std::string in "Sel.getAsString()"
   if (!Entry)
     Entry =3D CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
-                        llvm::ConstantArray::get(VMContext, Sel.getAsStrin=
g()),
+               llvm::ConstantDataArray::getString(VMContext, Sel.getAsStri=
ng()),
                               ((ObjCABI =3D=3D 2) ?
                                "__TEXT,__objc_methname,cstring_literals" :
                                "__TEXT,__cstring,cstring_literals"),
@@ -3968,7 +4214,7 @@
=20
   if (!Entry)
     Entry =3D CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
-                              llvm::ConstantArray::get(VMContext, TypeStr),
+                         llvm::ConstantDataArray::getString(VMContext, Typ=
eStr),
                               ((ObjCABI =3D=3D 2) ?
                                "__TEXT,__objc_methtype,cstring_literals" :
                                "__TEXT,__cstring,cstring_literals"),
@@ -3977,18 +4223,17 @@
   return getConstantGEP(VMContext, Entry, 0, 0);
 }
=20
-llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D)=
 {
+llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
+                                                  bool Extended) {
   std::string TypeStr;
-  if (CGM.getContext().getObjCEncodingForMethodDecl(
-                                                const_cast<ObjCMethodDecl*=
>(D),
-                                                    TypeStr))
+  if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
     return 0;
=20
   llvm::GlobalVariable *&Entry =3D MethodVarTypes[TypeStr];
=20
   if (!Entry)
     Entry =3D CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
-                              llvm::ConstantArray::get(VMContext, TypeStr),
+                         llvm::ConstantDataArray::getString(VMContext, Typ=
eStr),
                               ((ObjCABI =3D=3D 2) ?
                                "__TEXT,__objc_methtype,cstring_literals" :
                                "__TEXT,__cstring,cstring_literals"),
@@ -4003,8 +4248,8 @@
=20
   if (!Entry)
     Entry =3D CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
-                          llvm::ConstantArray::get(VMContext,
-                                                   Ident->getNameStart()),
+                        llvm::ConstantDataArray::getString(VMContext,
+                                                       Ident->getNameStart=
()),
                               "__TEXT,__cstring,cstring_literals",
                               1, true);
=20
@@ -4030,7 +4275,7 @@
      << '[' << CD->getName();
   if (const ObjCCategoryImplDecl *CID =3D
       dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
-    OS << '(' << CID << ')';
+    OS << '(' << *CID << ')';
   OS << ' ' << D->getSelector().getAsString() << ']';
 }
=20
@@ -4044,7 +4289,7 @@
     if (I->second->hasInitializer())
       continue;
=20
-    std::vector<llvm::Constant*> Values(5);
+    llvm::Constant *Values[5];
     Values[0] =3D llvm::Constant::getNullValue(ObjCTypes.ProtocolExtension=
PtrTy);
     Values[1] =3D GetClassName(I->first);
     Values[2] =3D llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy=
);
@@ -4062,7 +4307,7 @@
   //
   // FIXME: It would be nice if we had an LLVM construct for this.
   if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
-    llvm::SmallString<256> Asm;
+    SmallString<256> Asm;
     Asm +=3D CGM.getModule().getModuleInlineAsm();
     if (!Asm.empty() && Asm.back() !=3D '\n')
       Asm +=3D '\n';
@@ -4077,7 +4322,7 @@
       OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\=
n";
     }
=20
-    for (size_t i =3D 0; i < DefinedCategoryNames.size(); ++i) {
+    for (size_t i =3D 0, e =3D DefinedCategoryNames.size(); i < e; ++i) {
       OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=3D0\n"
          << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << =
"\n";
     }
@@ -4096,7 +4341,8 @@
 /* *** */
=20
 ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
-  : VMContext(cgm.getLLVMContext()), CGM(cgm) {
+  : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(0)=20
+{
   CodeGen::CodeGenTypes &Types =3D CGM.getTypes();
   ASTContext &Ctx =3D CGM.getContext();
=20
@@ -4104,17 +4350,13 @@
   IntTy =3D Types.ConvertType(Ctx.IntTy);
   LongTy =3D Types.ConvertType(Ctx.LongTy);
   LongLongTy =3D Types.ConvertType(Ctx.LongLongTy);
-  Int8PtrTy =3D llvm::Type::getInt8PtrTy(VMContext);
+  Int8PtrTy =3D CGM.Int8PtrTy;
+  Int8PtrPtrTy =3D CGM.Int8PtrPtrTy;
=20
   ObjectPtrTy =3D Types.ConvertType(Ctx.getObjCIdType());
   PtrObjectPtrTy =3D llvm::PointerType::getUnqual(ObjectPtrTy);
   SelectorPtrTy =3D Types.ConvertType(Ctx.getObjCSelType());
=20
-  // FIXME: It would be nice to unify this with the opaque type, so that t=
he IR
-  // comes out a bit cleaner.
-  llvm::Type *T =3D Types.ConvertType(Ctx.getObjCProtoType());
-  ExternalProtocolPtrTy =3D llvm::PointerType::getUnqual(T);
-
   // I'm not sure I like this. The implicit coordination is a bit
   // gross. We should solve this in a reasonable fashion because this
   // is a pretty common task (match some runtime data structure with
@@ -4206,12 +4448,13 @@
   //   struct _objc_method_description_list *optional_instance_methods;
   //   struct _objc_method_description_list *optional_class_methods;
   //   struct _objc_property_list *instance_properties;
+  //   const char ** extendedMethodTypes;
   // }
   ProtocolExtensionTy =3D
     llvm::StructType::create("struct._objc_protocol_extension",
                              IntTy, MethodDescriptionListPtrTy,
                              MethodDescriptionListPtrTy, PropertyListPtrTy,
-                             NULL);
+                             Int8PtrPtrTy, NULL);
=20
   // struct _objc_protocol_extension *
   ProtocolExtensionPtrTy =3D llvm::PointerType::getUnqual(ProtocolExtensio=
nTy);
@@ -4349,14 +4592,12 @@
   uint64_t SetJmpBufferSize =3D 18;
=20
   // Exceptions
-  llvm::Type *StackPtrTy =3D llvm::ArrayType::get(
-    llvm::Type::getInt8PtrTy(VMContext), 4);
+  llvm::Type *StackPtrTy =3D llvm::ArrayType::get(CGM.Int8PtrTy, 4);
=20
   ExceptionDataTy =3D
     llvm::StructType::create("struct._objc_exception_data",
-                         llvm::ArrayType::get(llvm::Type::getInt32Ty(VMCon=
text),
-                                              SetJmpBufferSize),
-                         StackPtrTy, NULL);
+                             llvm::ArrayType::get(CGM.Int32Ty,SetJmpBuffer=
Size),
+                             StackPtrTy, NULL);
=20
 }
=20
@@ -4384,6 +4625,7 @@
   //   const struct _prop_list_t * properties;
   //   const uint32_t size;  // sizeof(struct _protocol_t)
   //   const uint32_t flags;  // =3D 0
+  //   const char ** extendedMethodTypes;
   // }
=20
   // Holder for struct _protocol_list_t *
@@ -4395,7 +4637,8 @@
                              llvm::PointerType::getUnqual(ProtocolListnfAB=
ITy),
                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
-                             PropertyListPtrTy, IntTy, IntTy, NULL);
+                             PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
+                             NULL);
=20
   // struct _protocol_t*
   ProtocolnfABIPtrTy =3D llvm::PointerType::getUnqual(ProtocolnfABITy);
@@ -4555,23 +4798,22 @@
   return NULL;
 }
=20
-void CGObjCNonFragileABIMac::AddModuleClassList(const
-                                                std::vector<llvm::GlobalVa=
lue*>
-                                                &Container,
-                                                const char *SymbolName,
-                                                const char *SectionName) {
+void CGObjCNonFragileABIMac::
+AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
+                   const char *SymbolName,
+                   const char *SectionName) {
   unsigned NumClasses =3D Container.size();
=20
   if (!NumClasses)
     return;
=20
-  std::vector<llvm::Constant*> Symbols(NumClasses);
+  SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
   for (unsigned i=3D0; i<NumClasses; i++)
     Symbols[i] =3D llvm::ConstantExpr::getBitCast(Container[i],
                                                 ObjCTypes.Int8PtrTy);
-  llvm::Constant* Init =3D
+  llvm::Constant *Init =3D
     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
-                                                  NumClasses),
+                                                  Symbols.size()),
                              Symbols);
=20
   llvm::GlobalVariable *GV =3D
@@ -4593,14 +4835,14 @@
                      "\01L_OBJC_LABEL_CLASS_$",
                      "__DATA, __objc_classlist, regular, no_dead_strip");
  =20
-  for (unsigned i =3D 0; i < DefinedClasses.size(); i++) {
+  for (unsigned i =3D 0, e =3D DefinedClasses.size(); i < e; i++) {
     llvm::GlobalValue *IMPLGV =3D DefinedClasses[i];
     if (IMPLGV->getLinkage() !=3D llvm::GlobalValue::ExternalWeakLinkage)
       continue;
     IMPLGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
   }
  =20
-  for (unsigned i =3D 0; i < DefinedMetaClasses.size(); i++) {
+  for (unsigned i =3D 0, e =3D DefinedMetaClasses.size(); i < e; i++) {
     llvm::GlobalValue *IMPLGV =3D DefinedMetaClasses[i];
     if (IMPLGV->getLinkage() !=3D llvm::GlobalValue::ExternalWeakLinkage)
       continue;
@@ -4631,8 +4873,6 @@
   // At various points we've experimented with using vtable-based
   // dispatch for all methods.
   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
-  default:
-    llvm_unreachable("Invalid dispatch method!");
   case CodeGenOptions::Legacy:
     return false;
   case CodeGenOptions::NonLegacy:
@@ -4653,7 +4893,7 @@
=20
     // These are vtable-based if GC is disabled.
     // Optimistically use vtable dispatch for hybrid compiles.
-    if (CGM.getLangOptions().getGC() !=3D LangOptions::GCOnly) {
+    if (CGM.getLangOpts().getGC() !=3D LangOptions::GCOnly) {
       VTableDispatchMethods.insert(GetNullarySelector("retain"));
       VTableDispatchMethods.insert(GetNullarySelector("release"));
       VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
@@ -4669,7 +4909,7 @@
=20
     // These are vtable-based if GC is enabled.
     // Optimistically use vtable dispatch for hybrid compiles.
-    if (CGM.getLangOptions().getGC() !=3D LangOptions::NonGC) {
+    if (CGM.getLangOpts().getGC() !=3D LangOptions::NonGC) {
       VTableDispatchMethods.insert(GetNullarySelector("hash"));
       VTableDispatchMethods.insert(GetUnarySelector("addObject"));
    =20
@@ -4721,9 +4961,9 @@
   unsigned InstanceSize,
   const ObjCImplementationDecl *ID) {
   std::string ClassName =3D ID->getNameAsString();
-  std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
-
-  if (CGM.getLangOptions().ObjCAutoRefCount)
+  llvm::Constant *Values[10]; // 11 for 64bit targets!
+
+  if (CGM.getLangOpts().ObjCAutoRefCount)
     flags |=3D CLS_COMPILED_BY_ARC;
=20
   Values[ 0] =3D llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
@@ -4819,14 +5059,15 @@
   llvm::Constant *SuperClassGV,
   llvm::Constant *ClassRoGV,
   bool HiddenVisibility) {
-  std::vector<llvm::Constant*> Values(5);
-  Values[0] =3D IsAGV;
-  Values[1] =3D SuperClassGV;
+  llvm::Constant *Values[] =3D {
+    IsAGV,
+    SuperClassGV,
+    ObjCEmptyCacheVar,  // &ObjCEmptyCacheVar
+    ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
+    ClassRoGV           // &CLASS_RO_GV
+  };
   if (!Values[1])
     Values[1] =3D llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
-  Values[2] =3D ObjCEmptyCacheVar;  // &ObjCEmptyCacheVar
-  Values[3] =3D ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
-  Values[4] =3D ClassRoGV;                 // &CLASS_RO_GV
   llvm::Constant *Init =3D llvm::ConstantStruct::get(ObjCTypes.ClassnfABIT=
y,
                                                    Values);
   llvm::GlobalVariable *GV =3D GetClassGlobal(ClassName);
@@ -4987,7 +5228,7 @@
   //
   llvm::Constant *Init =3D
     llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
-                                   ObjCTypes.ExternalProtocolPtrTy);
+                                   ObjCTypes.getExternalProtocolPtrTy());
=20
   std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
   ProtocolName +=3D PD->getName();
@@ -5025,7 +5266,7 @@
   std::string ExtClassName(getClassSymbolPrefix() +
                            Interface->getNameAsString());
=20
-  std::vector<llvm::Constant*> Values(6);
+  llvm::Constant *Values[6];
   Values[0] =3D GetClassName(OCD->getIdentifier());
   // meta-class entry symbol
   llvm::GlobalVariable *ClassGV =3D GetClassGlobal(ExtClassName);
@@ -5064,7 +5305,7 @@
   const ObjCCategoryDecl *Category =3D
     Interface->FindCategoryDeclaration(OCD->getIdentifier());
   if (Category) {
-    llvm::SmallString<256> ExtName;
+    SmallString<256> ExtName;
     llvm::raw_svector_ostream(ExtName) << Interface->getName() << "_$_"
                                        << OCD->getName();
     Values[4] =3D EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
@@ -5110,12 +5351,12 @@
   if (!Fn)
     return 0;
=20
-  std::vector<llvm::Constant*> Method(3);
-  Method[0] =3D
+  llvm::Constant *Method[] =3D {
     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
-                                   ObjCTypes.SelectorPtrTy);
-  Method[1] =3D GetMethodVarType(MD);
-  Method[2] =3D llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
+                                   ObjCTypes.SelectorPtrTy),
+    GetMethodVarType(MD),
+    llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
+  };
   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
 }
=20
@@ -5126,9 +5367,10 @@
 ///   struct _objc_method method_list[method_count];
 /// }
 ///
-llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
-                                                       const char *Section,
-                                                const ConstantVector &Meth=
ods) {
+llvm::Constant *
+CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
+                                       const char *Section,
+                                       ArrayRef<llvm::Constant*> Methods) {
   // Return null for empty list.
   if (Methods.empty())
     return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
@@ -5215,7 +5457,7 @@
 llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
   const ObjCImplementationDecl *ID) {
=20
-  std::vector<llvm::Constant*> Ivars, Ivar(5);
+  std::vector<llvm::Constant*> Ivars;
=20
   const ObjCInterfaceDecl *OID =3D ID->getClassInterface();
   assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
@@ -5227,6 +5469,7 @@
     // Ignore unnamed bit-fields.
     if (!IVD->getDeclName())
       continue;
+    llvm::Constant *Ivar[5];
     Ivar[0] =3D EmitIvarOffsetVar(ID->getClassInterface(), IVD,
                                 ComputeIvarBaseOffset(CGM, ID, IVD));
     Ivar[1] =3D GetMethodVarName(IVD->getIdentifier());
@@ -5304,21 +5547,27 @@
 ///   const struct _prop_list_t * properties;
 ///   const uint32_t size;  // sizeof(struct _protocol_t)
 ///   const uint32_t flags;  // =3D 0
+///   const char ** extendedMethodTypes;
 /// }
 /// @endcode
 ///
=20
 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
   const ObjCProtocolDecl *PD) {
-  llvm::GlobalVariable *&Entry =3D Protocols[PD->getIdentifier()];
+  llvm::GlobalVariable *Entry =3D Protocols[PD->getIdentifier()];
=20
   // Early exit if a defining object has already been generated.
   if (Entry && Entry->hasInitializer())
     return Entry;
=20
+  // Use the protocol definition, if there is one.
+  if (const ObjCProtocolDecl *Def =3D PD->getDefinition())
+    PD =3D Def;
+ =20
   // Construct method lists.
   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
+  std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
   for (ObjCProtocolDecl::instmeth_iterator
          i =3D PD->instmeth_begin(), e =3D PD->instmeth_end(); i !=3D e; +=
+i) {
     ObjCMethodDecl *MD =3D *i;
@@ -5328,8 +5577,10 @@
    =20
     if (MD->getImplementationControl() =3D=3D ObjCMethodDecl::Optional) {
       OptInstanceMethods.push_back(C);
+      OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
     } else {
       InstanceMethods.push_back(C);
+      MethodTypesExt.push_back(GetMethodVarType(MD, true));
     }
   }
=20
@@ -5342,12 +5593,17 @@
=20
     if (MD->getImplementationControl() =3D=3D ObjCMethodDecl::Optional) {
       OptClassMethods.push_back(C);
+      OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
     } else {
       ClassMethods.push_back(C);
+      MethodTypesExt.push_back(GetMethodVarType(MD, true));
     }
   }
=20
-  std::vector<llvm::Constant*> Values(10);
+  MethodTypesExt.insert(MethodTypesExt.end(),
+                        OptMethodTypesExt.begin(), OptMethodTypesExt.end()=
);
+
+  llvm::Constant *Values[11];
   // isa is NULL
   Values[0] =3D llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
   Values[1] =3D GetClassName(PD->getIdentifier());
@@ -5377,6 +5633,9 @@
     CGM.getTargetData().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
   Values[8] =3D llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
   Values[9] =3D llvm::Constant::getNullValue(ObjCTypes.IntTy);
+  Values[10] =3D EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPE=
S_"
+                                       + PD->getName(),
+                                       MethodTypesExt, ObjCTypes);
   llvm::Constant *Init =3D llvm::ConstantStruct::get(ObjCTypes.ProtocolnfA=
BITy,
                                                    Values);
=20
@@ -5392,6 +5651,8 @@
     Entry->setAlignment(
       CGM.getTargetData().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
     Entry->setSection("__DATA,__datacoal_nt,coalesced");
+
+    Protocols[PD->getIdentifier()] =3D Entry;
   }
   Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
   CGM.AddUsedGlobal(Entry);
@@ -5422,14 +5683,14 @@
 CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
                                       ObjCProtocolDecl::protocol_iterator =
begin,
                                       ObjCProtocolDecl::protocol_iterator =
end) {
-  std::vector<llvm::Constant*> ProtocolRefs;
+  llvm::SmallVector<llvm::Constant*, 16> ProtocolRefs;
=20
   // Just return null for empty protocol lists
   if (begin =3D=3D end)
     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
=20
   // FIXME: We shouldn't need to do this lookup here, should we?
-  llvm::SmallString<256> TmpName;
+  SmallString<256> TmpName;
   Name.toVector(TmpName);
   llvm::GlobalVariable *GV =3D
     CGM.getModule().getGlobalVariable(TmpName.str(), true);
@@ -5447,10 +5708,9 @@
   Values[0] =3D
     llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
   Values[1] =3D
-    llvm::ConstantArray::get(
-      llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
-                           ProtocolRefs.size()),
-      ProtocolRefs);
+    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIP=
trTy,
+                                                  ProtocolRefs.size()),
+                             ProtocolRefs);
=20
   llvm::Constant *Init =3D llvm::ConstantStruct::getAnon(Values);
   GV =3D new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
@@ -5473,7 +5733,7 @@
=20
 llvm::Constant *
 CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl =
*MD) {
-  std::vector<llvm::Constant*> Desc(3);
+  llvm::Constant *Desc[3];
   Desc[0] =3D
     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
                                    ObjCTypes.SelectorPtrTy);
@@ -5499,8 +5759,13 @@
                                                const ObjCIvarDecl *Ivar,
                                                unsigned CVRQualifiers) {
   ObjCInterfaceDecl *ID =3D ObjectTy->getAs<ObjCObjectType>()->getInterfac=
e();
+  llvm::Value *Offset =3D EmitIvarOffset(CGF, ID, Ivar);
+  if (llvm::LoadInst *LI =3D dyn_cast<llvm::LoadInst>(Offset))
+    LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),=20
+                   llvm::MDNode::get(VMContext,
+                   ArrayRef<llvm::Value*>()));
   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
-                                  EmitIvarOffset(CGF, ID, Ivar));
+                                  Offset);
 }
=20
 llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
@@ -5557,9 +5822,7 @@
=20
   args.insert(args.end(), formalArgs.begin(), formalArgs.end());
=20
-  const CGFunctionInfo &fnInfo =3D
-    CGM.getTypes().getFunctionInfo(resultType, args,
-                                   FunctionType::ExtInfo());
+  MessageSendInfo MSI =3D getMessageSendInfo(method, resultType, args);
=20
   NullReturnState nullReturn;
=20
@@ -5572,7 +5835,7 @@
   // FIXME: don't use this for that.
   llvm::Constant *fn =3D 0;
   std::string messageRefName("\01l_");
-  if (CGM.ReturnTypeUsesSRet(fnInfo)) {
+  if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
     if (isSuper) {
       fn =3D ObjCTypes.getMessageSendSuper2StretFixupFn();
       messageRefName +=3D "objc_msgSendSuper2_stret_fixup";
@@ -5616,6 +5879,20 @@
     messageRef->setAlignment(16);
     messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
   }
+ =20
+  bool requiresnullCheck =3D false;
+  if (CGM.getLangOpts().ObjCAutoRefCount && method)
+    for (ObjCMethodDecl::param_const_iterator i =3D method->param_begin(),
+         e =3D method->param_end(); i !=3D e; ++i) {
+      const ParmVarDecl *ParamDecl =3D (*i);
+      if (ParamDecl->hasAttr<NSConsumedAttr>()) {
+        if (!nullReturn.NullBB)
+          nullReturn.init(CGF, arg0);
+        requiresnullCheck =3D true;
+        break;
+      }
+    }
+ =20
   llvm::Value *mref =3D
     CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
=20
@@ -5626,14 +5903,11 @@
   llvm::Value *callee =3D CGF.Builder.CreateStructGEP(mref, 0);
   callee =3D CGF.Builder.CreateLoad(callee, "msgSend_fn");
=20
-  bool variadic =3D method ? method->isVariadic() : false;
-  llvm::FunctionType *fnType =3D=20
-    CGF.getTypes().GetFunctionType(fnInfo, variadic);
-  callee =3D CGF.Builder.CreateBitCast(callee,
-                                     llvm::PointerType::getUnqual(fnType));
-
-  RValue result =3D CGF.EmitCall(fnInfo, callee, returnSlot, args);
-  return nullReturn.complete(CGF, result, resultType);
+  callee =3D CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
+
+  RValue result =3D CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
+  return nullReturn.complete(CGF, result, resultType, formalArgs,=20
+                             requiresnullCheck ? method : 0);
 }
=20
 /// Generate code for a message send expression in the nonfragile abi.
@@ -5839,7 +6113,12 @@
=20
   if (lval)
     return Entry;
-  return Builder.CreateLoad(Entry);
+  llvm::LoadInst* LI =3D Builder.CreateLoad(Entry);
+ =20
+  LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),=20
+                  llvm::MDNode::get(VMContext,
+                                    ArrayRef<llvm::Value*>()));
+  return LI;
 }
 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
 /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
@@ -6049,13 +6328,13 @@
                                         llvm::GlobalValue::ExternalLinkage,
                                         0, VTableName);
=20
-  llvm::Value *VTableIdx =3D
-    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 2);
-
-  std::vector<llvm::Constant*> Values(3);
-  Values[0] =3D llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx);
-  Values[1] =3D GetClassName(ID->getIdentifier());
-  Values[2] =3D GetClassGlobal(ClassName);
+  llvm::Value *VTableIdx =3D llvm::ConstantInt::get(CGM.Int32Ty, 2);
+
+  llvm::Constant *Values[] =3D {
+    llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx),
+    GetClassName(ID->getIdentifier()),
+    GetClassGlobal(ClassName)
+  };
   llvm::Constant *Init =3D
     llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
=20
@@ -6069,7 +6348,7 @@
                                       ID->getIdentifier()->getName()));
   }
=20
-  if (CGM.getLangOptions().getVisibilityMode() =3D=3D HiddenVisibility)
+  if (CGM.getLangOpts().getVisibilityMode() =3D=3D HiddenVisibility)
     Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
   Entry->setAlignment(CGM.getTargetData().getABITypeAlignment(
       ObjCTypes.EHTypeTy));
@@ -6088,7 +6367,7 @@
=20
 CodeGen::CGObjCRuntime *
 CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
-  if (CGM.getLangOptions().ObjCNonFragileABI)
+  if (CGM.getLangOpts().ObjCNonFragileABI)
     return new CGObjCNonFragileABIMac(CGM);
   return new CGObjCMac(CGM);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGObjCRuntime.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
   // If we know have an implementation (and the ivar is in it) then
   // look up in the implementation layout.
   const ASTRecordLayout *RL;
-  if (ID && ID->getClassInterface() =3D=3D Container)
+  if (ID && declaresSameEntity(ID->getClassInterface(), Container))
     RL =3D &CGM.getContext().getASTObjCImplementationLayout(ID);
   else
     RL =3D &CGM.getContext().getASTObjCInterfaceLayout(Container);
@@ -85,7 +85,7 @@
                                                unsigned CVRQualifiers,
                                                llvm::Value *Offset) {
   // Compute (type*) ( (char *) BaseValue + Offset)
-  llvm::Type *I8Ptr =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
+  llvm::Type *I8Ptr =3D CGF.Int8PtrTy;
   QualType IvarTy =3D Ivar->getType();
   llvm::Type *LTy =3D CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
   llvm::Value *V =3D CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
@@ -93,7 +93,7 @@
   V =3D CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
=20
   if (!Ivar->isBitField()) {
-    LValue LV =3D CGF.MakeAddrLValue(V, IvarTy);
+    LValue LV =3D CGF.MakeNaturalAlignAddrLValue(V, IvarTy);
     LV.getQuals().addCVRQualifiers(CVRQualifiers);
     return LV;
   }
@@ -229,7 +229,7 @@
       cast<llvm::CallInst>(Exn)->setDoesNotThrow();
     }
=20
-    CodeGenFunction::RunCleanupsScope cleanups(CGF);
+    CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRan=
ge());
=20
     if (endCatchFn) {
       // Add a cleanup to leave the catch.
@@ -246,7 +246,24 @@
       llvm::Value *CastExn =3D CGF.Builder.CreateBitCast(Exn, CatchType);
=20
       CGF.EmitAutoVarDecl(*CatchParam);
-      CGF.Builder.CreateStore(CastExn, CGF.GetAddrOfLocalVar(CatchParam));
+
+      llvm::Value *CatchParamAddr =3D CGF.GetAddrOfLocalVar(CatchParam);
+
+      switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {
+      case Qualifiers::OCL_Strong:
+        CastExn =3D CGF.EmitARCRetainNonBlock(CastExn);
+        // fallthrough
+
+      case Qualifiers::OCL_None:
+      case Qualifiers::OCL_ExplicitNone:
+      case Qualifiers::OCL_Autoreleasing:
+        CGF.Builder.CreateStore(CastExn, CatchParamAddr);
+        break;
+
+      case Qualifiers::OCL_Weak:
+        CGF.EmitARCInitWeak(CatchParamAddr, CastExn);
+        break;
+      }
     }
=20
     CGF.ObjCEHValueStack.push_back(Exn);
@@ -293,7 +310,7 @@
   // ARC release and lock-release cleanups.
   const Expr *lockExpr =3D S.getSynchExpr();
   llvm::Value *lock;
-  if (CGF.getLangOptions().ObjCAutoRefCount) {
+  if (CGF.getLangOpts().ObjCAutoRefCount) {
     lock =3D CGF.EmitARCRetainScalarExpr(lockExpr);
     lock =3D CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);
   } else {
@@ -310,3 +327,48 @@
   // Emit the body of the statement.
   CGF.EmitStmt(S.getSynchBody());
 }
+
+/// Compute the pointer-to-function type to which a message send
+/// should be casted in order to correctly call the given method
+/// with the given arguments.
+///
+/// \param method - may be null
+/// \param resultType - the result type to use if there's no method
+/// \param argInfo - the actual arguments, including implicit ones
+CGObjCRuntime::MessageSendInfo
+CGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,
+                                  QualType resultType,
+                                  CallArgList &callArgs) {
+  // If there's a method, use information from that.
+  if (method) {
+    const CGFunctionInfo &signature =3D
+      CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].T=
y);
+
+    llvm::PointerType *signatureType =3D
+      CGM.getTypes().GetFunctionType(signature)->getPointerTo();
+
+    // If that's not variadic, there's no need to recompute the ABI
+    // arrangement.
+    if (!signature.isVariadic())
+      return MessageSendInfo(signature, signatureType);
+
+    // Otherwise, there is.
+    FunctionType::ExtInfo einfo =3D signature.getExtInfo();
+    const CGFunctionInfo &argsInfo =3D
+      CGM.getTypes().arrangeFunctionCall(resultType, callArgs, einfo,
+                                         signature.getRequiredArgs());
+
+    return MessageSendInfo(argsInfo, signatureType);
+  }
+
+  // There's no method;  just use a default CC.
+  const CGFunctionInfo &argsInfo =3D
+    CGM.getTypes().arrangeFunctionCall(resultType, callArgs,=20
+                                       FunctionType::ExtInfo(),
+                                       RequiredArgs::All);
+
+  // Derive the signature to call from that.
+  llvm::PointerType *signatureType =3D
+    CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();
+  return MessageSendInfo(argsInfo, signatureType);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGObjCRuntime.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGObjCRuntime.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -63,6 +63,9 @@
 /// Implements runtime-specific code generation functions.
 class CGObjCRuntime {
 protected:
+  CodeGen::CodeGenModule &CGM;
+  CGObjCRuntime(CodeGen::CodeGenModule &CGM) : CGM(CGM) {}
+
   // Utility functions for unified ivar access. These need to
   // eventually be folded into other places (the structure layout
   // code).
@@ -132,7 +135,7 @@
=20
   /// Generate a constant string object.
   virtual llvm::Constant *GenerateConstantString(const StringLiteral *) =
=3D 0;
-
+ =20
   /// Generate a category.  A category contains a list of methods (and
   /// accompanying metadata) and a list of protocols.
   virtual void GenerateCategory(const ObjCCategoryImplDecl *OCD) =3D 0;
@@ -140,6 +143,9 @@
   /// Generate a class structure for this class.
   virtual void GenerateClass(const ObjCImplementationDecl *OID) =3D 0;
=20
+  /// Register an class alias.
+  virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) =3D 0;
+
   /// Generate an Objective-C message send operation.
   ///
   /// \param Method - The method being called, this may be null if synthes=
izing
@@ -196,10 +202,17 @@
   /// Return the runtime function for setting properties.
   virtual llvm::Constant *GetPropertySetFunction() =3D 0;
=20
+  /// Return the runtime function for optimized setting properties.
+  virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,=20
+                                                          bool copy) =3D 0;
+
   // API for atomic copying of qualified aggregates in getter.
   virtual llvm::Constant *GetGetStructFunction() =3D 0;
   // API for atomic copying of qualified aggregates in setter.
   virtual llvm::Constant *GetSetStructFunction() =3D 0;
+  // API for atomic copying of qualified aggregates with non-trivial copy
+  // assignment (c++) in setter/getter.
+  virtual llvm::Constant *GetCppAtomicObjectFunction() =3D 0;
  =20
   /// GetClass - Return a reference to the class for the given
   /// interface decl.
@@ -249,6 +262,19 @@
   virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
                                   const CodeGen::CGBlockInfo &blockInfo) =
=3D 0;
   virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) =
=3D 0;
+
+  struct MessageSendInfo {
+    const CGFunctionInfo &CallInfo;
+    llvm::PointerType *MessengerType;
+
+    MessageSendInfo(const CGFunctionInfo &callInfo,
+                    llvm::PointerType *messengerType)
+      : CallInfo(callInfo), MessengerType(messengerType) {}
+  };
+
+  MessageSendInfo getMessageSendInfo(const ObjCMethodDecl *method,
+                                     QualType resultType,
+                                     CallArgList &callArgs);
 };
=20
 /// Creates an instance of an Objective-C runtime class.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGRTTI.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGRTTI.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGRTTI.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -26,8 +26,6 @@
   CodeGenModule &CGM;  // Per-module state.
   llvm::LLVMContext &VMContext;
  =20
-  llvm::Type *Int8PtrTy;
- =20
   /// Fields - The fields of the RTTI descriptor currently being built.
   SmallVector<llvm::Constant *, 16> Fields;
=20
@@ -65,8 +63,7 @@
  =20
 public:
   RTTIBuilder(CodeGenModule &CGM) : CGM(CGM),=20
-    VMContext(CGM.getModule().getContext()),
-    Int8PtrTy(llvm::Type::getInt8PtrTy(VMContext)) { }
+    VMContext(CGM.getModule().getContext()) { }
=20
   // Pointer type info flags.
   enum {
@@ -116,7 +113,7 @@
 llvm::GlobalVariable *
 RTTIBuilder::GetAddrOfTypeName(QualType Ty,=20
                                llvm::GlobalVariable::LinkageTypes Linkage)=
 {
-  llvm::SmallString<256> OutName;
+  SmallString<256> OutName;
   llvm::raw_svector_ostream Out(OutName);
   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
   Out.flush();
@@ -125,7 +122,8 @@
   // We know that the mangled name of the type starts at index 4 of the
   // mangled name of the typename, so we can just index into it in order to
   // get the mangled name of the type.
-  llvm::Constant *Init =3D llvm::ConstantArray::get(VMContext, Name.substr=
(4));
+  llvm::Constant *Init =3D llvm::ConstantDataArray::getString(VMContext,
+                                                            Name.substr(4)=
);
=20
   llvm::GlobalVariable *GV =3D=20
     CGM.CreateOrReplaceCXXRuntimeVariable(Name, Init->getType(), Linkage);
@@ -137,7 +135,7 @@
=20
 llvm::Constant *RTTIBuilder::GetAddrOfExternalRTTIDescriptor(QualType Ty) {
   // Mangle the RTTI name.
-  llvm::SmallString<256> OutName;
+  SmallString<256> OutName;
   llvm::raw_svector_ostream Out(OutName);
   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
   Out.flush();
@@ -148,11 +146,12 @@
  =20
   if (!GV) {
     // Create a new global variable.
-    GV =3D new llvm::GlobalVariable(CGM.getModule(), Int8PtrTy, /*Constant=
=3D*/true,
+    GV =3D new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
+                                  /*Constant=3D*/true,
                                   llvm::GlobalValue::ExternalLinkage, 0, N=
ame);
   }
  =20
-  return llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
+  return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
 }
=20
 /// TypeInfoIsInStandardLibrary - Given a builtin type, returns whether th=
e type
@@ -195,10 +194,11 @@
     case BuiltinType::UInt128:
       return true;
      =20
-    case BuiltinType::Overload:
     case BuiltinType::Dependent:
-    case BuiltinType::BoundMember:
-    case BuiltinType::UnknownAny:
+#define BUILTIN_TYPE(Id, SingletonId)
+#define PLACEHOLDER_TYPE(Id, SingletonId) \
+    case BuiltinType::Id:
+#include "clang/AST/BuiltinTypes.def"
       llvm_unreachable("asking for RRTI for a placeholder type!");
      =20
     case BuiltinType::ObjCId:
@@ -206,9 +206,8 @@
     case BuiltinType::ObjCSel:
       llvm_unreachable("FIXME: Objective-C types are unsupported!");
   }
- =20
-  // Silent gcc.
-  return false;
+
+  llvm_unreachable("Invalid BuiltinType Kind!");
 }
=20
 static bool TypeInfoIsInStandardLibrary(const PointerType *PointerTy) {
@@ -250,7 +249,7 @@
   ASTContext &Context =3D CGM.getContext();
=20
   // If RTTI is disabled, don't consider key functions.
-  if (!Context.getLangOptions().RTTI) return false;
+  if (!Context.getLangOpts().RTTI) return false;
=20
   if (const RecordType *RecordTy =3D dyn_cast<RecordType>(Ty)) {
     const CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RecordTy->getDecl());
@@ -327,7 +326,7 @@
     return llvm::GlobalValue::InternalLinkage;
=20
   case ExternalLinkage:
-    if (!CGM.getLangOptions().RTTI) {
+    if (!CGM.getLangOpts().RTTI) {
       // RTTI is not enabled, which means that this type info struct is go=
ing
       // to be used for exception handling. Give it linkonce_odr linkage.
       return llvm::GlobalValue::LinkOnceODRLinkage;
@@ -335,6 +334,8 @@
=20
     if (const RecordType *Record =3D dyn_cast<RecordType>(Ty)) {
       const CXXRecordDecl *RD =3D cast<CXXRecordDecl>(Record->getDecl());
+      if (RD->hasAttr<WeakAttr>())
+        return llvm::GlobalValue::WeakODRLinkage;
       if (RD->isDynamicClass())
         return CGM.getVTableLinkage(RD);
     }
@@ -342,7 +343,7 @@
     return llvm::GlobalValue::LinkOnceODRLinkage;
   }
=20
-  return llvm::GlobalValue::LinkOnceODRLinkage;
+  llvm_unreachable("Invalid linkage!");
 }
=20
 // CanUseSingleInheritance - Return whether the given record decl has a "s=
ingle,=20
@@ -479,7 +480,7 @@
   }
=20
   llvm::Constant *VTable =3D=20
-    CGM.getModule().getOrInsertGlobal(VTableName, Int8PtrTy);
+    CGM.getModule().getOrInsertGlobal(VTableName, CGM.Int8PtrTy);
    =20
   llvm::Type *PtrDiffTy =3D=20
     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
@@ -487,7 +488,7 @@
   // The vtable address point is 2.
   llvm::Constant *Two =3D llvm::ConstantInt::get(PtrDiffTy, 2);
   VTable =3D llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Two);
-  VTable =3D llvm::ConstantExpr::getBitCast(VTable, Int8PtrTy);
+  VTable =3D llvm::ConstantExpr::getBitCast(VTable, CGM.Int8PtrTy);
=20
   Fields.push_back(VTable);
 }
@@ -531,7 +532,7 @@
   GV->setLinkage(Linkage);
=20
   // Get the typename global.
-  llvm::SmallString<256> OutName;
+  SmallString<256> OutName;
   llvm::raw_svector_ostream Out(OutName);
   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(Ty, Out);
   Out.flush();
@@ -551,7 +552,7 @@
   Ty =3D CGM.getContext().getCanonicalType(Ty);
=20
   // Check if we've already emitted an RTTI descriptor for this type.
-  llvm::SmallString<256> OutName;
+  SmallString<256> OutName;
   llvm::raw_svector_ostream Out(OutName);
   CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty, Out);
   Out.flush();
@@ -561,7 +562,7 @@
   if (OldGV && !OldGV->isDeclaration()) {
     maybeUpdateRTTILinkage(CGM, OldGV, Ty);
=20
-    return llvm::ConstantExpr::getBitCast(OldGV, Int8PtrTy);
+    return llvm::ConstantExpr::getBitCast(OldGV, CGM.Int8PtrTy);
   }
=20
   // Check if there is already an external RTTI descriptor for this type.
@@ -582,8 +583,7 @@
   // And the name.
   llvm::GlobalVariable *TypeName =3D GetAddrOfTypeName(Ty, Linkage);
=20
-  llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(VMContext);
-  Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, Int8PtrTy));
+  Fields.push_back(llvm::ConstantExpr::getBitCast(TypeName, CGM.Int8PtrTy)=
);
=20
   switch (Ty->getTypeClass()) {
 #define TYPE(Class, Base)
@@ -705,7 +705,7 @@
=20
   GV->setUnnamedAddr(true);
=20
-  return llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
+  return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
 }
=20
 /// ComputeQualifierFlags - Compute the pointer type info flags from the
@@ -982,14 +982,11 @@
   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
   // FIXME: should we even be calling this method if RTTI is disabled
   // and it's not for EH?
-  if (!ForEH && !getContext().getLangOptions().RTTI) {
-    llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(VMContext);
+  if (!ForEH && !getContext().getLangOpts().RTTI)
     return llvm::Constant::getNullValue(Int8PtrTy);
-  }
  =20
-  if (ForEH && Ty->isObjCObjectPointerType() && !Features.NeXTRuntime) {
+  if (ForEH && Ty->isObjCObjectPointerType() && !LangOpts.NeXTRuntime)
     return ObjCRuntime->GetEHType(Ty);
-  }
=20
   return RTTIBuilder(*this).BuildTypeInfo(Ty);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGRecordLayoutBuilder.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -120,24 +120,29 @@
   bool LayoutFields(const RecordDecl *D);
=20
   /// Layout a single base, virtual or non-virtual
-  void LayoutBase(const CXXRecordDecl *base,
+  bool LayoutBase(const CXXRecordDecl *base,
                   const CGRecordLayout &baseLayout,
                   CharUnits baseOffset);
=20
   /// LayoutVirtualBase - layout a single virtual base.
-  void LayoutVirtualBase(const CXXRecordDecl *base,
+  bool LayoutVirtualBase(const CXXRecordDecl *base,
                          CharUnits baseOffset);
=20
   /// LayoutVirtualBases - layout the virtual bases of a record decl.
-  void LayoutVirtualBases(const CXXRecordDecl *RD,
+  bool LayoutVirtualBases(const CXXRecordDecl *RD,
                           const ASTRecordLayout &Layout);
+
+  /// MSLayoutVirtualBases - layout the virtual bases of a record decl,
+  /// like MSVC.
+  bool MSLayoutVirtualBases(const CXXRecordDecl *RD,
+                            const ASTRecordLayout &Layout);
  =20
   /// LayoutNonVirtualBase - layout a single non-virtual base.
-  void LayoutNonVirtualBase(const CXXRecordDecl *base,
+  bool LayoutNonVirtualBase(const CXXRecordDecl *base,
                             CharUnits baseOffset);
  =20
   /// LayoutNonVirtualBases - layout the virtual bases of a record decl.
-  void LayoutNonVirtualBases(const CXXRecordDecl *RD,=20
+  bool LayoutNonVirtualBases(const CXXRecordDecl *RD,=20
                              const ASTRecordLayout &Layout);
=20
   /// ComputeNonVirtualBaseType - Compute the non-virtual base field types.
@@ -526,6 +531,7 @@
   CharUnits unionAlign =3D CharUnits::Zero();
=20
   bool hasOnlyZeroSizedBitFields =3D true;
+  bool checkedFirstFieldZeroInit =3D false;
=20
   unsigned fieldNo =3D 0;
   for (RecordDecl::field_iterator field =3D D->field_begin(),
@@ -537,6 +543,11 @@
     if (!fieldType)
       continue;
=20
+    if (field->getDeclName() && !checkedFirstFieldZeroInit) {
+      CheckZeroInitializable(field->getType());
+      checkedFirstFieldZeroInit =3D true;
+    }
+
     hasOnlyZeroSizedBitFields =3D false;
=20
     CharUnits fieldAlign =3D CharUnits::fromQuantity(
@@ -565,6 +576,7 @@
     }
   }
   if (unionAlign.isZero()) {
+    (void)hasOnlyZeroSizedBitFields;
     assert(hasOnlyZeroSizedBitFields &&
            "0-align record did not have all zero-sized bit-fields!");
     unionAlign =3D CharUnits::One();
@@ -576,7 +588,7 @@
     AppendPadding(recordSize, unionAlign);
 }
=20
-void CGRecordLayoutBuilder::LayoutBase(const CXXRecordDecl *base,
+bool CGRecordLayoutBuilder::LayoutBase(const CXXRecordDecl *base,
                                        const CGRecordLayout &baseLayout,
                                        CharUnits baseOffset) {
   ResizeLastBaseFieldIfNecessary(baseOffset);
@@ -589,22 +601,18 @@
   LastLaidOutBase.Offset =3D NextFieldOffset;
   LastLaidOutBase.NonVirtualSize =3D baseASTLayout.getNonVirtualSize();
=20
-  // Fields and bases can be laid out in the tail padding of previous
-  // bases.  If this happens, we need to allocate the base as an i8
-  // array; otherwise, we can use the subobject type.  However,
-  // actually doing that would require knowledge of what immediately
-  // follows this base in the layout, so instead we do a conservative
-  // approximation, which is to use the base subobject type if it
-  // has the same LLVM storage size as the nvsize.
+  llvm::StructType *subobjectType =3D baseLayout.getBaseSubobjectLLVMType(=
);
+  if (getTypeAlignment(subobjectType) > Alignment)
+    return false;
=20
-  llvm::StructType *subobjectType =3D baseLayout.getBaseSubobjectLLVMType(=
);
   AppendField(baseOffset, subobjectType);
+  return true;
 }
=20
-void CGRecordLayoutBuilder::LayoutNonVirtualBase(const CXXRecordDecl *base,
+bool CGRecordLayoutBuilder::LayoutNonVirtualBase(const CXXRecordDecl *base,
                                                  CharUnits baseOffset) {
   // Ignore empty bases.
-  if (base->isEmpty()) return;
+  if (base->isEmpty()) return true;
=20
   const CGRecordLayout &baseLayout =3D Types.getCGRecordLayout(base);
   if (IsZeroInitializableAsBase) {
@@ -615,26 +623,51 @@
       baseLayout.isZeroInitializableAsBase();
   }
=20
-  LayoutBase(base, baseLayout, baseOffset);
+  if (!LayoutBase(base, baseLayout, baseOffset))
+    return false;
   NonVirtualBases[base] =3D (FieldTypes.size() - 1);
+  return true;
 }
=20
-void
+bool
 CGRecordLayoutBuilder::LayoutVirtualBase(const CXXRecordDecl *base,
                                          CharUnits baseOffset) {
   // Ignore empty bases.
-  if (base->isEmpty()) return;
+  if (base->isEmpty()) return true;
=20
   const CGRecordLayout &baseLayout =3D Types.getCGRecordLayout(base);
   if (IsZeroInitializable)
     IsZeroInitializable =3D baseLayout.isZeroInitializableAsBase();
=20
-  LayoutBase(base, baseLayout, baseOffset);
+  if (!LayoutBase(base, baseLayout, baseOffset))
+    return false;
   VirtualBases[base] =3D (FieldTypes.size() - 1);
+  return true;
+}
+
+bool
+CGRecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD,
+                                          const ASTRecordLayout &Layout) {
+  if (!RD->getNumVBases())
+    return true;
+
+  // The vbases list is uniqued and ordered by a depth-first
+  // traversal, which is what we need here.
+  for (CXXRecordDecl::base_class_const_iterator I =3D RD->vbases_begin(),
+        E =3D RD->vbases_end(); I !=3D E; ++I) {
+
+    const CXXRecordDecl *BaseDecl =3D=20
+      cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
+
+    CharUnits vbaseOffset =3D Layout.getVBaseClassOffset(BaseDecl);
+    if (!LayoutVirtualBase(BaseDecl, vbaseOffset))
+      return false;
+  }
+  return true;
 }
=20
 /// LayoutVirtualBases - layout the non-virtual bases of a record decl.
-void
+bool
 CGRecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
                                           const ASTRecordLayout &Layout) {
   for (CXXRecordDecl::base_class_const_iterator I =3D RD->bases_begin(),
@@ -650,7 +683,8 @@
         continue;
=20
       CharUnits vbaseOffset =3D Layout.getVBaseClassOffset(BaseDecl);
-      LayoutVirtualBase(BaseDecl, vbaseOffset);
+      if (!LayoutVirtualBase(BaseDecl, vbaseOffset))
+        return false;
     }
=20
     if (!BaseDecl->getNumVBases()) {
@@ -658,32 +692,39 @@
       continue;
     }
    =20
-    LayoutVirtualBases(BaseDecl, Layout);
+    if (!LayoutVirtualBases(BaseDecl, Layout))
+      return false;
   }
+  return true;
 }
=20
-void
+bool
 CGRecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD,
                                              const ASTRecordLayout &Layout=
) {
   const CXXRecordDecl *PrimaryBase =3D Layout.getPrimaryBase();
=20
-  // Check if we need to add a vtable pointer.
-  if (RD->isDynamicClass()) {
-    if (!PrimaryBase) {
-      llvm::Type *FunctionType =3D
-        llvm::FunctionType::get(llvm::Type::getInt32Ty(Types.getLLVMContex=
t()),
-                                /*isVarArg=3D*/true);
-      llvm::Type *VTableTy =3D FunctionType->getPointerTo();
+  // If we have a primary base, lay it out first.
+  if (PrimaryBase) {
+    if (!Layout.isPrimaryBaseVirtual()) {
+      if (!LayoutNonVirtualBase(PrimaryBase, CharUnits::Zero()))
+        return false;
+    } else {
+      if (!LayoutVirtualBase(PrimaryBase, CharUnits::Zero()))
+        return false;
+    }
=20
-      assert(NextFieldOffset.isZero() &&
-             "VTable pointer must come first!");
-      AppendField(CharUnits::Zero(), VTableTy->getPointerTo());
-    } else {
-      if (!Layout.isPrimaryBaseVirtual())
-        LayoutNonVirtualBase(PrimaryBase, CharUnits::Zero());
-      else
-        LayoutVirtualBase(PrimaryBase, CharUnits::Zero());
-    }
+  // Otherwise, add a vtable / vf-table if the layout says to do so.
+  } else if (Types.getContext().getTargetInfo().getCXXABI() =3D=3D CXXABI_=
Microsoft
+               ? Layout.getVFPtrOffset() !=3D CharUnits::fromQuantity(-1)
+               : RD->isDynamicClass()) {
+    llvm::Type *FunctionType =3D
+      llvm::FunctionType::get(llvm::Type::getInt32Ty(Types.getLLVMContext(=
)),
+                              /*isVarArg=3D*/true);
+    llvm::Type *VTableTy =3D FunctionType->getPointerTo();
+   =20
+    assert(NextFieldOffset.isZero() &&
+           "VTable pointer must come first!");
+    AppendField(CharUnits::Zero(), VTableTy->getPointerTo());
   }
=20
   // Layout the non-virtual bases.
@@ -699,8 +740,19 @@
     if (BaseDecl =3D=3D PrimaryBase && !Layout.isPrimaryBaseVirtual())
       continue;
=20
-    LayoutNonVirtualBase(BaseDecl, Layout.getBaseClassOffset(BaseDecl));
+    if (!LayoutNonVirtualBase(BaseDecl, Layout.getBaseClassOffset(BaseDecl=
)))
+      return false;
   }
+
+  // Add a vb-table pointer if the layout insists.
+  if (Layout.getVBPtrOffset() !=3D CharUnits::fromQuantity(-1)) {
+    CharUnits VBPtrOffset =3D Layout.getVBPtrOffset();
+    llvm::Type *Vbptr =3D llvm::Type::getInt32PtrTy(Types.getLLVMContext()=
);
+    AppendPadding(VBPtrOffset, getTypeAlignment(Vbptr));
+    AppendField(VBPtrOffset, Vbptr);
+  }
+
+  return true;
 }
=20
 bool
@@ -731,7 +783,6 @@
     CharUnits NumBytes =3D AlignedNonVirtualTypeSize - AlignedNextFieldOff=
set;
     FieldTypes.push_back(getByteArrayType(NumBytes));
   }
-
  =20
   BaseSubobjectType =3D llvm::StructType::create(Types.getLLVMContext(),
                                                FieldTypes, "", Packed);
@@ -752,7 +803,8 @@
=20
   const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(D);
   if (RD)
-    LayoutNonVirtualBases(RD, Layout);
+    if (!LayoutNonVirtualBases(RD, Layout))
+      return false;
=20
   unsigned FieldNo =3D 0;
   const FieldDecl *LastFD =3D 0;
@@ -785,11 +837,19 @@
       return false;
     }
=20
-    // And lay out the virtual bases.
-    RD->getIndirectPrimaryBases(IndirectPrimaryBases);
-    if (Layout.isPrimaryBaseVirtual())
-      IndirectPrimaryBases.insert(Layout.getPrimaryBase());
-    LayoutVirtualBases(RD, Layout);
+    // Lay out the virtual bases.  The MS ABI uses a different
+    // algorithm here due to the lack of primary virtual bases.
+    if (Types.getContext().getTargetInfo().getCXXABI() !=3D CXXABI_Microso=
ft) {
+      RD->getIndirectPrimaryBases(IndirectPrimaryBases);
+      if (Layout.isPrimaryBaseVirtual())
+        IndirectPrimaryBases.insert(Layout.getPrimaryBase());
+
+      if (!LayoutVirtualBases(RD, Layout))
+        return false;
+    } else {
+      if (!MSLayoutVirtualBases(RD, Layout))
+        return false;
+    }
   }
  =20
   // Append tail padding if necessary.
@@ -831,17 +891,24 @@
   assert(NextFieldOffset <=3D fieldOffset &&
          "Incorrect field layout!");
=20
-  // Round up the field offset to the alignment of the field type.
-  CharUnits alignedNextFieldOffset =3D
-    NextFieldOffset.RoundUpToAlignment(fieldAlignment);
+  // Do nothing if we're already at the right offset.
+  if (fieldOffset =3D=3D NextFieldOffset) return;
=20
-  if (alignedNextFieldOffset < fieldOffset) {
-    // Even with alignment, the field offset is not at the right place,
-    // insert padding.
-    CharUnits padding =3D fieldOffset - NextFieldOffset;
+  // If we're not emitting a packed LLVM type, try to avoid adding
+  // unnecessary padding fields.
+  if (!Packed) {
+    // Round up the field offset to the alignment of the field type.
+    CharUnits alignedNextFieldOffset =3D
+      NextFieldOffset.RoundUpToAlignment(fieldAlignment);
+    assert(alignedNextFieldOffset <=3D fieldOffset);
=20
-    AppendBytes(padding);
+    // If that's the right offset, we're done.
+    if (alignedNextFieldOffset =3D=3D fieldOffset) return;
   }
+
+  // Otherwise we need explicit padding.
+  CharUnits padding =3D fieldOffset - NextFieldOffset;
+  AppendBytes(padding);
 }
=20
 bool CGRecordLayoutBuilder::ResizeLastBaseFieldIfNecessary(CharUnits offse=
t) {
@@ -905,7 +972,7 @@
     return;
=20
   // Can only have member pointers if we're compiling C++.
-  if (!Types.getContext().getLangOptions().CPlusPlus)
+  if (!Types.getContext().getLangOpts().CPlusPlus)
     return;
=20
   const Type *elementType =3D T->getBaseElementTypeUnsafe();
@@ -931,7 +998,7 @@
=20
   // If we're in C++, compute the base subobject type.
   llvm::StructType *BaseTy =3D 0;
-  if (isa<CXXRecordDecl>(D)) {
+  if (isa<CXXRecordDecl>(D) && !D->isUnion()) {
     BaseTy =3D Builder.BaseSubobjectType;
     if (!BaseTy) BaseTy =3D Ty;
   }
@@ -950,7 +1017,7 @@
   RL->BitFields.swap(Builder.BitFields);
=20
   // Dump the layout, if requested.
-  if (getContext().getLangOptions().DumpRecordLayouts) {
+  if (getContext().getLangOpts().DumpRecordLayouts) {
     llvm::errs() << "\n*** Dumping IRgen Record Layout\n";
     llvm::errs() << "Record: ";
     D->dump();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGStmt.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGStmt.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGStmt.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -73,6 +73,7 @@
   case Stmt::CXXCatchStmtClass:
   case Stmt::SEHExceptStmtClass:
   case Stmt::SEHFinallyStmtClass:
+  case Stmt::MSDependentExistsStmtClass:
     llvm_unreachable("invalid statement class to emit generically");
   case Stmt::NullStmtClass:
   case Stmt::CompoundStmtClass:
@@ -190,20 +191,13 @@
   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBrac=
Loc(),
                              "LLVM IR generation of compound statement ('{=
}')");
=20
-  CGDebugInfo *DI =3D getDebugInfo();
-  if (DI)
-    DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
-
-  // Keep track of the current cleanup stack depth.
-  RunCleanupsScope Scope(*this);
+  // Keep track of the current cleanup stack depth, including debug scopes.
+  LexicalScope Scope(*this, S.getSourceRange());
=20
   for (CompoundStmt::const_body_iterator I =3D S.body_begin(),
        E =3D S.body_end()-GetLast; I !=3D E; ++I)
     EmitStmt(*I);
=20
-  if (DI)
-    DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
-
   RValue RV;
   if (!GetLast)
     RV =3D RValue::get(0);
@@ -771,7 +765,8 @@
   } else if (RV->getType()->isAnyComplexType()) {
     EmitComplexExprIntoAddr(RV, ReturnValue, false);
   } else {
-    EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Qualifiers(),
+    CharUnits Alignment =3D getContext().getTypeAlignInChars(RV->getType()=
);
+    EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment, Qualifie=
rs(),
                                           AggValueSlot::IsDestructed,
                                           AggValueSlot::DoesNotNeedGCBarri=
ers,
                                           AggValueSlot::IsNotAliased));
@@ -783,7 +778,7 @@
 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
   // As long as debug info is modeled with instructions, we have to ensure=
 we
   // have a place to insert here and write the stop point here.
-  if (getDebugInfo() && HaveInsertPoint())
+  if (HaveInsertPoint())
     EmitStopPoint(&S);
=20
   for (DeclStmt::const_decl_iterator I =3D S.decl_begin(), E =3D S.decl_en=
d();
@@ -876,6 +871,16 @@
 }
=20
 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
+  // If there is no enclosing switch instance that we're aware of, then th=
is
+  // case statement and its block can be elided.  This situation only happ=
ens
+  // when we've constant-folded the switch, are emitting the constant case,
+  // and part of the constant case includes another case statement.  For=20
+  // instance: switch (4) { case 4: do { case 5: } while (1); }
+  if (!SwitchInsn) {
+    EmitStmt(S.getSubStmt());
+    return;
+  }
+
   // Handle case ranges.
   if (S.getRHS()) {
     EmitCaseStmtRange(S);
@@ -887,7 +892,7 @@
=20
   // If the body of the case is just a 'break', and if there was no fallth=
rough,
   // try to not emit an empty block.
-  if (isa<BreakStmt>(S.getSubStmt())) {
+  if ((CGM.getCodeGenOpts().OptimizationLevel > 0) && isa<BreakStmt>(S.get=
SubStmt())) {
     JumpDest Block =3D BreakContinueStack.back().BreakBlock;
    =20
     // Only do this optimization if there are no cleanups that need emitti=
ng.
@@ -1150,6 +1155,10 @@
   if (S.getConditionVariable())
     EmitAutoVarDecl(*S.getConditionVariable());
=20
+  // Handle nested switch statements.
+  llvm::SwitchInst *SavedSwitchInsn =3D SwitchInsn;
+  llvm::BasicBlock *SavedCRBlock =3D CaseRangeBlock;
+
   // See if we can constant fold the condition of the switch and therefore=
 only
   // emit the live case statement (if any) of the switch.
   llvm::APInt ConstantCondValue;
@@ -1159,20 +1168,26 @@
                                    getContext())) {
       RunCleanupsScope ExecutedScope(*this);
=20
+      // At this point, we are no longer "within" a switch instance, so
+      // we can temporarily enforce this to ensure that any embedded case
+      // statements are not emitted.
+      SwitchInsn =3D 0;
+
       // Okay, we can dead code eliminate everything except this case.  Em=
it the
       // specified series of statements and we're good.
       for (unsigned i =3D 0, e =3D CaseStmts.size(); i !=3D e; ++i)
         EmitStmt(CaseStmts[i]);
+
+      // Now we want to restore the saved switch instance so that nested
+      // switches continue to function properly
+      SwitchInsn =3D SavedSwitchInsn;
+
       return;
     }
   }
    =20
   llvm::Value *CondV =3D EmitScalarExpr(S.getCond());
=20
-  // Handle nested switch statements.
-  llvm::SwitchInst *SavedSwitchInsn =3D SwitchInsn;
-  llvm::BasicBlock *SavedCRBlock =3D CaseRangeBlock;
-
   // Create basic block to hold stuff that comes after switch
   // statement. We also need to create a default block now so that
   // explicit case ranges tests can have a place to jump to on
@@ -1199,7 +1214,7 @@
=20
   // Update the default block in case explicit case range tests have
   // been chained on top.
-  SwitchInsn->setSuccessor(0, CaseRangeBlock);
+  SwitchInsn->setDefaultDest(CaseRangeBlock);
=20
   // If a default was never emitted:
   if (!DefaultBlock->getParent()) {
@@ -1280,6 +1295,8 @@
   const VarDecl *Variable =3D dyn_cast<VarDecl>(&Value);
   if (!Variable)
     return Constraint;
+  if (Variable->getStorageClass() !=3D SC_Register)
+    return Constraint;
   AsmLabelAttr *Attr =3D Variable->getAttr<AsmLabelAttr>();
   if (!Attr)
     return Constraint;
@@ -1355,7 +1372,7 @@
   StringRef StrVal =3D Str->getString();
   if (!StrVal.empty()) {
     const SourceManager &SM =3D CGF.CGM.getContext().getSourceManager();
-    const LangOptions &LangOpts =3D CGF.CGM.getLangOptions();
+    const LangOptions &LangOpts =3D CGF.CGM.getLangOpts();
    =20
     // Add the location of the start of each subsequent line of the asm to=
 the
     // MDNode.
@@ -1490,6 +1507,11 @@
       llvm::Value *Arg =3D EmitAsmInputLValue(S, Info, Dest, InputExpr->ge=
tType(),
                                             InOutConstraints);
=20
+      if (llvm::Type* AdjTy =3D
+            getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
+                                                 Arg->getType()))
+        Arg =3D Builder.CreateBitCast(Arg, AdjTy);
+
       if (Info.allowsRegister())
         InOutConstraints +=3D llvm::utostr(i);
       else
@@ -1548,7 +1570,7 @@
         }
       }
     }
-    if (llvm::Type* AdjTy =3D=20
+    if (llvm::Type* AdjTy =3D
               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
                                                    Arg->getType()))
       Arg =3D Builder.CreateBitCast(Arg, AdjTy);
@@ -1590,7 +1612,7 @@
=20
   llvm::Type *ResultType;
   if (ResultRegTypes.empty())
-    ResultType =3D llvm::Type::getVoidTy(getLLVMContext());
+    ResultType =3D VoidTy;
   else if (ResultRegTypes.size() =3D=3D 1)
     ResultType =3D ResultRegTypes[0];
   else
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGVTT.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGVTT.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGVTT.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,13 +18,11 @@
 using namespace clang;
 using namespace CodeGen;
=20
-#define D1(x)
-
-llvm::Constant *GetAddrOfVTTVTable(CodeGenVTables &CGVT,
-                                   const CXXRecordDecl *MostDerivedClass,
-                                   const VTTVTable &VTable,
-                                   llvm::GlobalVariable::LinkageTypes Link=
age,
-                       llvm::DenseMap<BaseSubobject, uint64_t> &AddressPoi=
nts) {
+static llvm::Constant *
+GetAddrOfVTTVTable(CodeGenVTables &CGVT, const CXXRecordDecl *MostDerivedC=
lass,
+                   const VTTVTable &VTable,
+                   llvm::GlobalVariable::LinkageTypes Linkage,
+                   llvm::DenseMap<BaseSubobject, uint64_t> &AddressPoints)=
 {
   if (VTable.getBase() =3D=3D MostDerivedClass) {
     assert(VTable.getBaseOffset().isZero() &&
            "Most derived class vtable must have a zero offset!");
@@ -45,8 +43,7 @@
                                   const CXXRecordDecl *RD) {
   VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=3D*/true);
=20
-  llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(CGM.getLLVMContext()),
-             *Int64Ty =3D llvm::Type::getInt64Ty(CGM.getLLVMContext());
+  llvm::Type *Int8PtrTy =3D CGM.Int8PtrTy, *Int64Ty =3D CGM.Int64Ty;
   llvm::ArrayType *ArrayType =3D=20
     llvm::ArrayType::get(Int8PtrTy, Builder.getVTTComponents().size());
  =20
@@ -102,7 +99,7 @@
 llvm::GlobalVariable *CodeGenVTables::GetAddrOfVTT(const CXXRecordDecl *RD=
) {
   assert(RD->getNumVBases() && "Only classes with virtual bases need a VTT=
");
=20
-  llvm::SmallString<256> OutName;
+  SmallString<256> OutName;
   llvm::raw_svector_ostream Out(OutName);
   CGM.getCXXABI().getMangleContext().mangleCXXVTT(RD, Out);
   Out.flush();
@@ -113,10 +110,8 @@
=20
   VTTBuilder Builder(CGM.getContext(), RD, /*GenerateDefinition=3D*/false);
=20
-  llvm::Type *Int8PtrTy =3D=20
-    llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
   llvm::ArrayType *ArrayType =3D=20
-    llvm::ArrayType::get(Int8PtrTy, Builder.getVTTComponents().size());
+    llvm::ArrayType::get(CGM.Int8PtrTy, Builder.getVTTComponents().size());
=20
   llvm::GlobalVariable *GV =3D
     CGM.CreateOrReplaceCXXRuntimeVariable(Name, ArrayType,=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGVTables.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGVTables.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGVTables.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -52,7 +52,7 @@
   // If we're building with optimization, we always emit VTables since that
   // allows for virtual function calls to be devirtualized.
   // (We don't want to do this in -fapple-kext mode however).
-  if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOptions().Appl=
eKext)
+  if (CGM.getCodeGenOpts().OptimizationLevel && !CGM.getLangOpts().AppleKe=
xt)
     return true;
=20
   return KeyFunction->hasBody();
@@ -63,7 +63,7 @@
   const CXXMethodDecl *MD =3D cast<CXXMethodDecl>(GD.getDecl());
=20
   // Compute the mangled name.
-  llvm::SmallString<256> Name;
+  SmallString<256> Name;
   llvm::raw_svector_ostream Out(Name);
   if (const CXXDestructorDecl* DD =3D dyn_cast<CXXDestructorDecl>(MD))
     getCXXABI().getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(),
@@ -83,9 +83,7 @@
   if (!NonVirtualAdjustment && !VirtualAdjustment)
     return Ptr;
=20
-  llvm::Type *Int8PtrTy =3D=20
-    llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
- =20
+  llvm::Type *Int8PtrTy =3D CGF.Int8PtrTy;
   llvm::Value *V =3D CGF.Builder.CreateBitCast(Ptr, Int8PtrTy);
=20
   if (NonVirtualAdjustment) {
@@ -244,8 +242,8 @@
   QualType ResultType =3D FPT->getResultType();
=20
   // Get the original function
-  llvm::Type *Ty =3D
-    CGM.getTypes().GetFunctionType(FnInfo, /*IsVariadic*/true);
+  assert(FnInfo.isVariadic());
+  llvm::Type *Ty =3D CGM.getTypes().GetFunctionType(FnInfo);
   llvm::Value *Callee =3D CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=3D*/tr=
ue);
   llvm::Function *BaseFn =3D cast<llvm::Function>(Callee);
=20
@@ -331,6 +329,7 @@
                 SourceLocation());
=20
   CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
+  CXXThisValue =3D CXXABIThisValue;
=20
   // Adjust the 'this' pointer if necessary.
   llvm::Value *AdjustedThisPtr =3D=20
@@ -352,13 +351,13 @@
=20
   // Get our callee.
   llvm::Type *Ty =3D
-    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(GD),
-                                   FPT->isVariadic());
+    CGM.getTypes().GetFunctionType(CGM.getTypes().arrangeGlobalDeclaration=
(GD));
   llvm::Value *Callee =3D CGM.GetAddrOfFunction(GD, Ty, /*ForVTable=3D*/tr=
ue);
=20
 #ifndef NDEBUG
   const CGFunctionInfo &CallFnInfo =3D=20
-    CGM.getTypes().getFunctionInfo(ResultType, CallArgs, FPT->getExtInfo()=
);
+    CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtIn=
fo(),
+                                       RequiredArgs::forPrototypePlus(FPT,=
 1));
   assert(CallFnInfo.getRegParm() =3D=3D FnInfo.getRegParm() &&
          CallFnInfo.isNoReturn() =3D=3D FnInfo.isNoReturn() &&
          CallFnInfo.getCallingConvention() =3D=3D FnInfo.getCallingConvent=
ion());
@@ -399,7 +398,7 @@
 void CodeGenVTables::EmitThunk(GlobalDecl GD, const ThunkInfo &Thunk,=20
                                bool UseAvailableExternallyLinkage)
 {
-  const CGFunctionInfo &FnInfo =3D CGM.getTypes().getFunctionInfo(GD);
+  const CGFunctionInfo &FnInfo =3D CGM.getTypes().arrangeGlobalDeclaration=
(GD);
=20
   // FIXME: re-use FnInfo in this computation.
   llvm::Constant *Entry =3D CGM.GetAddrOfThunk(GD, Thunk);
@@ -511,7 +510,7 @@
                                         unsigned NumVTableThunks) {
   SmallVector<llvm::Constant *, 64> Inits;
=20
-  llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
+  llvm::Type *Int8PtrTy =3D CGM.Int8PtrTy;
  =20
   llvm::Type *PtrDiffTy =3D=20
     CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType());
@@ -571,8 +570,7 @@
         // We have a pure virtual member function.
         if (!PureVirtualFn) {
           llvm::FunctionType *Ty =3D=20
-            llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMConte=
xt()),=20
-                                    /*isVarArg=3D*/false);
+            llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=3D*/false);
           PureVirtualFn =3D=20
             CGM.CreateRuntimeFunction(Ty, "__cxa_pure_virtual");
           PureVirtualFn =3D llvm::ConstantExpr::getBitCast(PureVirtualFn,=20
@@ -586,8 +584,8 @@
             VTableThunks[NextVTableThunkIndex].first =3D=3D I) {
           const ThunkInfo &Thunk =3D VTableThunks[NextVTableThunkIndex].se=
cond;
        =20
+          MaybeEmitThunkAvailableExternally(GD, Thunk);
           Init =3D CGM.GetAddrOfThunk(GD, Thunk);
-          MaybeEmitThunkAvailableExternally(GD, Thunk);
=20
           NextVTableThunkIndex++;
         } else {
@@ -622,15 +620,14 @@
   if (ShouldEmitVTableInThisTU(RD))
     CGM.DeferredVTables.push_back(RD);
=20
-  llvm::SmallString<256> OutName;
+  SmallString<256> OutName;
   llvm::raw_svector_ostream Out(OutName);
   CGM.getCXXABI().getMangleContext().mangleCXXVTable(RD, Out);
   Out.flush();
   StringRef Name =3D OutName.str();
=20
-  llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
   llvm::ArrayType *ArrayType =3D=20
-    llvm::ArrayType::get(Int8PtrTy,
+    llvm::ArrayType::get(CGM.Int8PtrTy,
                         VTContext.getVTableLayout(RD).getNumVTableComponen=
ts());
=20
   VTable =3D
@@ -668,7 +665,7 @@
                                       bool BaseIsVirtual,=20
                                    llvm::GlobalVariable::LinkageTypes Link=
age,
                                       VTableAddressPointsMapTy& AddressPoi=
nts) {
-  llvm::OwningPtr<VTableLayout> VTLayout(
+  OwningPtr<VTableLayout> VTLayout(
     VTContext.createConstructionVTableLayout(Base.getBase(),
                                              Base.getBaseOffset(),
                                              BaseIsVirtual, RD));
@@ -677,7 +674,7 @@
   AddressPoints =3D VTLayout->getAddressPoints();
=20
   // Get the mangled construction vtable name.
-  llvm::SmallString<256> OutName;
+  SmallString<256> OutName;
   llvm::raw_svector_ostream Out(OutName);
   CGM.getCXXABI().getMangleContext().
     mangleCXXCtorVTable(RD, Base.getBaseOffset().getQuantity(), Base.getBa=
se(),=20
@@ -685,9 +682,8 @@
   Out.flush();
   StringRef Name =3D OutName.str();
=20
-  llvm::Type *Int8PtrTy =3D llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
   llvm::ArrayType *ArrayType =3D=20
-    llvm::ArrayType::get(Int8PtrTy, VTLayout->getNumVTableComponents());
+    llvm::ArrayType::get(CGM.Int8PtrTy, VTLayout->getNumVTableComponents()=
);
=20
   // Create the variable that will hold the construction vtable.
   llvm::GlobalVariable *VTable =3D=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CGValue.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CGValue.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CGValue.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -16,6 +16,7 @@
 #define CLANG_CODEGEN_CGVALUE_H
=20
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/CharUnits.h"
 #include "clang/AST/Type.h"
=20
 namespace llvm {
@@ -24,9 +25,8 @@
 }
=20
 namespace clang {
-  class ObjCPropertyRefExpr;
-
 namespace CodeGen {
+  class AggValueSlot;
   class CGBitFieldInfo;
=20
 /// RValue - This trivial value class is used to represent the result of an
@@ -105,9 +105,7 @@
     Simple,       // This is a normal l-value, use getAddress().
     VectorElt,    // This is a vector element l-value (V[i]), use getVecto=
r*
     BitField,     // This is a bitfield l-value, use getBitfield*.
-    ExtVectorElt, // This is an extended vector subset, use getExtVectorCo=
mp
-    PropertyRef   // This is an Objective-C property reference, use
-                  // getPropertyRefExpr
+    ExtVectorElt  // This is an extended vector subset, use getExtVectorCo=
mp
   } LVType;
=20
   llvm::Value *V;
@@ -121,9 +119,6 @@
=20
     // BitField start bit and size
     const CGBitFieldInfo *BitFieldInfo;
-
-    // Obj-C property reference expression
-    const ObjCPropertyRefExpr *PropertyRefExpr;
   };
=20
   QualType Type;
@@ -131,7 +126,8 @@
   // 'const' is unused here
   Qualifiers Quals;
=20
-  /// The alignment to use when accessing this lvalue.
+  // The alignment to use when accessing this lvalue.  (For vector element=
s,
+  // this is the alignment of the whole vector.)
   unsigned short Alignment;
=20
   // objective-c's ivar
@@ -156,12 +152,14 @@
   llvm::MDNode *TBAAInfo;
=20
 private:
-  void Initialize(QualType Type, Qualifiers Quals, unsigned Alignment =3D =
0,
+  void Initialize(QualType Type, Qualifiers Quals,
+                  CharUnits Alignment =3D CharUnits(),
                   llvm::MDNode *TBAAInfo =3D 0) {
     this->Type =3D Type;
     this->Quals =3D Quals;
-    this->Alignment =3D Alignment;
-    assert(this->Alignment =3D=3D Alignment && "Alignment exceeds allowed =
max!");
+    this->Alignment =3D Alignment.getQuantity();
+    assert(this->Alignment =3D=3D Alignment.getQuantity() &&
+           "Alignment exceeds allowed max!");
=20
     // Initialize Objective-C flags.
     this->Ivar =3D this->ObjIsArray =3D this->NonGC =3D this->GlobalObjCRe=
f =3D false;
@@ -175,7 +173,6 @@
   bool isVectorElt() const { return LVType =3D=3D VectorElt; }
   bool isBitField() const { return LVType =3D=3D BitField; }
   bool isExtVectorElt() const { return LVType =3D=3D ExtVectorElt; }
-  bool isPropertyRef() const { return LVType =3D=3D PropertyRef; }
=20
   bool isVolatileQualified() const { return Quals.hasVolatile(); }
   bool isRestrictQualified() const { return Quals.hasRestrict(); }
@@ -226,7 +223,8 @@
=20
   unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
=20
-  unsigned getAlignment() const { return Alignment; }
+  CharUnits getAlignment() const { return CharUnits::fromQuantity(Alignmen=
t); }
+  void setAlignment(CharUnits A) { Alignment =3D A.getQuantity(); }
=20
   // simple lvalue
   llvm::Value *getAddress() const { assert(isSimple()); return V; }
@@ -256,18 +254,8 @@
     return *BitFieldInfo;
   }
=20
-  // property ref lvalue
-  llvm::Value *getPropertyRefBaseAddr() const {
-    assert(isPropertyRef());
-    return V;
-  }
-  const ObjCPropertyRefExpr *getPropertyRefExpr() const {
-    assert(isPropertyRef());
-    return PropertyRefExpr;
-  }
-
   static LValue MakeAddr(llvm::Value *address, QualType type,
-                         unsigned alignment, ASTContext &Context,
+                         CharUnits alignment, ASTContext &Context,
                          llvm::MDNode *TBAAInfo =3D 0) {
     Qualifiers qs =3D type.getQualifiers();
     qs.setObjCGCAttr(Context.getObjCGCAttrKind(type));
@@ -280,22 +268,22 @@
   }
=20
   static LValue MakeVectorElt(llvm::Value *Vec, llvm::Value *Idx,
-                              QualType type) {
+                              QualType type, CharUnits Alignment) {
     LValue R;
     R.LVType =3D VectorElt;
     R.V =3D Vec;
     R.VectorIdx =3D Idx;
-    R.Initialize(type, type.getQualifiers());
+    R.Initialize(type, type.getQualifiers(), Alignment);
     return R;
   }
=20
   static LValue MakeExtVectorElt(llvm::Value *Vec, llvm::Constant *Elts,
-                                 QualType type) {
+                                 QualType type, CharUnits Alignment) {
     LValue R;
     R.LVType =3D ExtVectorElt;
     R.V =3D Vec;
     R.VectorElts =3D Elts;
-    R.Initialize(type, type.getQualifiers());
+    R.Initialize(type, type.getQualifiers(), Alignment);
     return R;
   }
=20
@@ -316,17 +304,9 @@
     return R;
   }
=20
-  // FIXME: It is probably bad that we aren't emitting the target when we =
build
-  // the lvalue. However, this complicates the code a bit, and I haven't f=
igured
-  // out how to make it go wrong yet.
-  static LValue MakePropertyRef(const ObjCPropertyRefExpr *E,
-                                llvm::Value *Base) {
-    LValue R;
-    R.LVType =3D PropertyRef;
-    R.V =3D Base;
-    R.PropertyRefExpr =3D E;
-    R.Initialize(QualType(), Qualifiers());
-    return R;
+  RValue asAggregateRValue() const {
+    // FIMXE: Alignment
+    return RValue::getAggregate(getAddress(), isVolatileQualified());
   }
 };
=20
@@ -338,6 +318,8 @@
   // Qualifiers
   Qualifiers Quals;
=20
+  unsigned short Alignment;
+
   /// DestructedFlag - This is set to true if some external code is
   /// responsible for setting up a destructor for the slot.  Otherwise
   /// the code which constructs it should push the appropriate cleanup.
@@ -376,11 +358,8 @@
   /// ignored - Returns an aggregate value slot indicating that the
   /// aggregate value is being ignored.
   static AggValueSlot ignored() {
-    AggValueSlot AV;
-    AV.Addr =3D 0;
-    AV.Quals =3D Qualifiers();
-    AV.DestructedFlag =3D AV.ObjCGCFlag =3D AV.ZeroedFlag =3D AV.AliasedFl=
ag =3D false;
-    return AV;
+    return forAddr(0, CharUnits(), Qualifiers(), IsNotDestructed,
+                   DoesNotNeedGCBarriers, IsNotAliased);
   }
=20
   /// forAddr - Make a slot for an aggregate value.
@@ -393,13 +372,15 @@
   ///   for calling destructors on this object
   /// \param needsGC - true if the slot is potentially located
   ///   somewhere that ObjC GC calls should be emitted for
-  static AggValueSlot forAddr(llvm::Value *addr, Qualifiers quals,
+  static AggValueSlot forAddr(llvm::Value *addr, CharUnits align,
+                              Qualifiers quals,
                               IsDestructed_t isDestructed,
                               NeedsGCBarriers_t needsGC,
                               IsAliased_t isAliased,
                               IsZeroed_t isZeroed =3D IsNotZeroed) {
     AggValueSlot AV;
     AV.Addr =3D addr;
+    AV.Alignment =3D align.getQuantity();
     AV.Quals =3D quals;
     AV.DestructedFlag =3D isDestructed;
     AV.ObjCGCFlag =3D needsGC;
@@ -412,8 +393,8 @@
                                 NeedsGCBarriers_t needsGC,
                                 IsAliased_t isAliased,
                                 IsZeroed_t isZeroed =3D IsNotZeroed) {
-    return forAddr(LV.getAddress(), LV.getQuals(),
-                   isDestructed, needsGC, isAliased, isZeroed);
+    return forAddr(LV.getAddress(), LV.getAlignment(),
+                   LV.getQuals(), isDestructed, needsGC, isAliased, isZero=
ed);
   }
=20
   IsDestructed_t isExternallyDestructed() const {
@@ -445,14 +426,19 @@
     return Addr =3D=3D 0;
   }
=20
+  CharUnits getAlignment() const {
+    return CharUnits::fromQuantity(Alignment);
+  }
+
   IsAliased_t isPotentiallyAliased() const {
     return IsAliased_t(AliasedFlag);
   }
=20
+  // FIXME: Alignment?
   RValue asRValue() const {
     return RValue::getAggregate(getAddr(), isVolatile());
   }
- =20
+
   void setZeroed(bool V =3D true) { ZeroedFlag =3D V; }
   IsZeroed_t isZeroed() const {
     return IsZeroed_t(ZeroedFlag);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenAction.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenAction.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -8,6 +8,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/CodeGen/CodeGenAction.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/AST/ASTConsumer.h"
@@ -18,9 +19,12 @@
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "llvm/LLVMContext.h"
+#include "llvm/Linker.h"
 #include "llvm/Module.h"
 #include "llvm/Pass.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Bitcode/ReaderWriter.h"
 #include "llvm/Support/IRReader.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/SourceMgr.h"
@@ -30,6 +34,7 @@
=20
 namespace clang {
   class BackendConsumer : public ASTConsumer {
+    virtual void anchor();
     DiagnosticsEngine &Diags;
     BackendAction Action;
     const CodeGenOptions &CodeGenOpts;
@@ -40,9 +45,9 @@
=20
     Timer LLVMIRGeneration;
=20
-    llvm::OwningPtr<CodeGenerator> Gen;
+    OwningPtr<CodeGenerator> Gen;
=20
-    llvm::OwningPtr<llvm::Module> TheModule;
+    OwningPtr<llvm::Module> TheModule, LinkModule;
=20
   public:
     BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
@@ -50,7 +55,9 @@
                     const TargetOptions &targetopts,
                     const LangOptions &langopts,
                     bool TimePasses,
-                    const std::string &infile, raw_ostream *OS,
+                    const std::string &infile,
+                    llvm::Module *LinkModule,
+                    raw_ostream *OS,
                     LLVMContext &C) :
       Diags(_Diags),
       Action(action),
@@ -59,11 +66,17 @@
       LangOpts(langopts),
       AsmOutStream(OS),
       LLVMIRGeneration("LLVM IR Generation Time"),
-      Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)) {
+      Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
+      LinkModule(LinkModule) {
       llvm::TimePassesIsEnabled =3D TimePasses;
     }
=20
     llvm::Module *takeModule() { return TheModule.take(); }
+    llvm::Module *takeLinkModule() { return LinkModule.take(); }
+
+    virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
+      Gen->HandleCXXStaticMemberVarInstantiation(VD);
+    }
=20
     virtual void Initialize(ASTContext &Ctx) {
       Context =3D &Ctx;
@@ -79,7 +92,7 @@
         LLVMIRGeneration.stopTimer();
     }
=20
-    virtual void HandleTopLevelDecl(DeclGroupRef D) {
+    virtual bool HandleTopLevelDecl(DeclGroupRef D) {
       PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
                                      Context->getSourceManager(),
                                      "LLVM IR generation of declaration");
@@ -91,6 +104,8 @@
=20
       if (llvm::TimePassesIsEnabled)
         LLVMIRGeneration.stopTimer();
+
+      return true;
     }
=20
     virtual void HandleTranslationUnit(ASTContext &C) {
@@ -111,7 +126,7 @@
=20
       // Make sure IR generation is happy with the module. This is release=
d by
       // the module provider.
-      Module *M =3D Gen->ReleaseModule();
+      llvm::Module *M =3D Gen->ReleaseModule();
       if (!M) {
         // The module has been released by IR gen on failures, do not doub=
le
         // free.
@@ -122,6 +137,17 @@
       assert(TheModule.get() =3D=3D M &&
              "Unexpected module change during IR generation");
=20
+      // Link LinkModule into this module if present, preserving its valid=
ity.
+      if (LinkModule) {
+        std::string ErrorMsg;
+        if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSourc=
e,
+                                &ErrorMsg)) {
+          Diags.Report(diag::err_fe_cannot_link_module)
+            << LinkModule->getModuleIdentifier() << ErrorMsg;
+          return;
+        }
+      }
+
       // Install an inline asm handler so that diagnostics get printed thr=
ough
       // our diagnostics hooks.
       LLVMContext &Ctx =3D TheModule->getContext();
@@ -160,6 +186,8 @@
     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
                                SourceLocation LocCookie);
   };
+ =20
+  void BackendConsumer::anchor() {}
 }
=20
 /// ConvertBackendLocation - Convert a location in a temporary llvm::Sourc=
eMgr
@@ -215,8 +243,17 @@
   if (LocCookie.isValid()) {
     Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
    =20
-    if (D.getLoc().isValid())
-      Diags.Report(Loc, diag::note_fe_inline_asm_here);
+    if (D.getLoc().isValid()) {
+      DiagnosticBuilder B =3D Diags.Report(Loc, diag::note_fe_inline_asm_h=
ere);
+      // Convert the SMDiagnostic ranges into SourceRange and attach them
+      // to the diagnostic.
+      for (unsigned i =3D 0, e =3D D.getRanges().size(); i !=3D e; ++i) {
+        std::pair<unsigned, unsigned> Range =3D D.getRanges()[i];
+        unsigned Column =3D D.getColumnNo();
+        B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
+                         Loc.getLocWithOffset(Range.second - Column));
+      }
+    }
     return;
   }
  =20
@@ -229,7 +266,8 @@
 //
=20
 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
-  : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
+  : Act(_Act), LinkModule(0),
+    VMContext(_VMContext ? _VMContext : new LLVMContext),
     OwnsVMContext(!_VMContext) {}
=20
 CodeGenAction::~CodeGenAction() {
@@ -245,6 +283,10 @@
   if (!getCompilerInstance().hasASTConsumer())
     return;
=20
+  // If we were given a link module, release consumer's ownership of it.
+  if (LinkModule)
+    BEConsumer->takeLinkModule();
+
   // Steal the module from the consumer.
   TheModule.reset(BEConsumer->takeModule());
 }
@@ -281,16 +323,40 @@
 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
                                               StringRef InFile) {
   BackendAction BA =3D static_cast<BackendAction>(Act);
-  llvm::OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
+  OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
   if (BA !=3D Backend_EmitNothing && !OS)
     return 0;
=20
+  llvm::Module *LinkModuleToUse =3D LinkModule;
+
+  // If we were not given a link module, and the user requested that one be
+  // loaded from bitcode, do so now.
+  const std::string &LinkBCFile =3D CI.getCodeGenOpts().LinkBitcodeFile;
+  if (!LinkModuleToUse && !LinkBCFile.empty()) {
+    std::string ErrorStr;
+
+    llvm::MemoryBuffer *BCBuf =3D
+      CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
+    if (!BCBuf) {
+      CI.getDiagnostics().Report(diag::err_cannot_open_file)
+        << LinkBCFile << ErrorStr;
+      return 0;
+    }
+
+    LinkModuleToUse =3D getLazyBitcodeModule(BCBuf, *VMContext, &ErrorStr);
+    if (!LinkModuleToUse) {
+      CI.getDiagnostics().Report(diag::err_cannot_open_file)
+        << LinkBCFile << ErrorStr;
+      return 0;
+    }
+  }
+
   BEConsumer =3D=20
       new BackendConsumer(BA, CI.getDiagnostics(),
                           CI.getCodeGenOpts(), CI.getTargetOpts(),
                           CI.getLangOpts(),
-                          CI.getFrontendOpts().ShowTimers, InFile, OS.take=
(),
-                          *VMContext);
+                          CI.getFrontendOpts().ShowTimers, InFile,
+                          LinkModuleToUse, OS.take(), *VMContext);
   return BEConsumer;
 }
=20
@@ -328,8 +394,17 @@
       StringRef Msg =3D Err.getMessage();
       if (Msg.startswith("error: "))
         Msg =3D Msg.substr(7);
+
+      // Escape '%', which is interpreted as a format character.
+      llvm::SmallString<128> EscapedMessage;
+      for (unsigned i =3D 0, e =3D Msg.size(); i !=3D e; ++i) {
+        if (Msg[i] =3D=3D '%')
+          EscapedMessage +=3D '%';
+        EscapedMessage +=3D Msg[i];
+      }
+
       unsigned DiagID =3D CI.getDiagnostics().getCustomDiagID(
-          DiagnosticsEngine::Error, Msg);
+          DiagnosticsEngine::Error, EscapedMessage);
=20
       CI.getDiagnostics().Report(Loc, DiagID);
       return;
@@ -348,20 +423,26 @@
=20
 //
=20
+void EmitAssemblyAction::anchor() { }
 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
=20
+void EmitBCAction::anchor() { }
 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
   : CodeGenAction(Backend_EmitBC, _VMContext) {}
=20
+void EmitLLVMAction::anchor() { }
 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
   : CodeGenAction(Backend_EmitLL, _VMContext) {}
=20
+void EmitLLVMOnlyAction::anchor() { }
 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
=20
+void EmitCodeGenOnlyAction::anchor() { }
 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
=20
+void EmitObjAction::anchor() { }
 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
   : CodeGenAction(Backend_EmitObj, _VMContext) {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenFunction.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -16,9 +16,7 @@
 #include "CGCUDARuntime.h"
 #include "CGCXXABI.h"
 #include "CGDebugInfo.h"
-#include "CGException.h"
 #include "clang/Basic/TargetInfo.h"
-#include "clang/AST/APValue.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
@@ -31,20 +29,29 @@
=20
 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
   : CodeGenTypeCache(cgm), CGM(cgm),
-    Target(CGM.getContext().getTargetInfo()), Builder(cgm.getModule().getC=
ontext()),
+    Target(CGM.getContext().getTargetInfo()),
+    Builder(cgm.getModule().getContext()),
     AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
-    NormalCleanupDest(0), NextCleanupDestIndex(1),
-    EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(0),
+    LambdaThisCaptureField(0), NormalCleanupDest(0), NextCleanupDestIndex(=
1),
+    FirstBlockInfo(0), EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(=
0),
     DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false),
     IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(=
0),
-    CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
-    OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
-    TrapBB(0) {
+    CXXABIThisDecl(0), CXXABIThisValue(0), CXXThisValue(0), CXXVTTDecl(0),
+    CXXVTTValue(0), OutermostConditional(0), TerminateLandingPad(0),
+    TerminateHandler(0), TrapBB(0) {
=20
-  CatchUndefined =3D getContext().getLangOptions().CatchUndefined;
+  CatchUndefined =3D getContext().getLangOpts().CatchUndefined;
   CGM.getCXXABI().getMangleContext().startNewFunction();
 }
=20
+CodeGenFunction::~CodeGenFunction() {
+  // If there are any unclaimed block infos, go ahead and destroy them
+  // now.  This can happen if IR-gen gets clever and skips evaluating
+  // something.
+  if (FirstBlockInfo)
+    destroyBlockInfos(FirstBlockInfo);
+}
+
=20
 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
   return CGM.getTypes().ConvertTypeForMem(T);
@@ -222,8 +229,7 @@
   llvm::PointerType *PointerTy =3D Int8PtrTy;
   llvm::Type *ProfileFuncArgs[] =3D { PointerTy, PointerTy };
   llvm::FunctionType *FunctionTy =3D
-    llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
-                            ProfileFuncArgs, false);
+    llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
=20
   llvm::Constant *F =3D CGM.CreateRuntimeFunction(FunctionTy, Fn);
   llvm::CallInst *CallSite =3D Builder.CreateCall(
@@ -237,8 +243,7 @@
 }
=20
 void CodeGenFunction::EmitMCountInstrumentation() {
-  llvm::FunctionType *FTy =3D
-    llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false=
);
+  llvm::FunctionType *FTy =3D llvm::FunctionType::get(VoidTy, false);
=20
   llvm::Constant *MCountFn =3D CGM.CreateRuntimeFunction(FTy,
                                                        Target.getMCountNam=
e());
@@ -261,15 +266,16 @@
=20
   // Pass inline keyword to optimizer if it appears explicitly on any
   // declaration.
-  if (const FunctionDecl *FD =3D dyn_cast_or_null<FunctionDecl>(D))
-    for (FunctionDecl::redecl_iterator RI =3D FD->redecls_begin(),
-           RE =3D FD->redecls_end(); RI !=3D RE; ++RI)
-      if (RI->isInlineSpecified()) {
-        Fn->addFnAttr(llvm::Attribute::InlineHint);
-        break;
-      }
+  if (!CGM.getCodeGenOpts().NoInline)=20
+    if (const FunctionDecl *FD =3D dyn_cast_or_null<FunctionDecl>(D))
+      for (FunctionDecl::redecl_iterator RI =3D FD->redecls_begin(),
+             RE =3D FD->redecls_end(); RI !=3D RE; ++RI)
+        if (RI->isInlineSpecified()) {
+          Fn->addFnAttr(llvm::Attribute::InlineHint);
+          break;
+        }
=20
-  if (getContext().getLangOptions().OpenCL) {
+  if (getContext().getLangOpts().OpenCL) {
     // Add metadata for a kernel function.
     if (const FunctionDecl *FD =3D dyn_cast_or_null<FunctionDecl>(D))
       if (FD->hasAttr<OpenCLKernelAttr>()) {
@@ -298,12 +304,19 @@
=20
   // Emit subprogram debug descriptor.
   if (CGDebugInfo *DI =3D getDebugInfo()) {
-    // FIXME: what is going on here and why does it ignore all these
-    // interesting type properties?
+    unsigned NumArgs =3D 0;
+    QualType *ArgsArray =3D new QualType[Args.size()];
+    for (FunctionArgList::const_iterator i =3D Args.begin(), e =3D Args.en=
d();
+	 i !=3D e; ++i) {
+      ArgsArray[NumArgs++] =3D (*i)->getType();
+    }
+
     QualType FnType =3D
-      getContext().getFunctionType(RetTy, 0, 0,
+      getContext().getFunctionType(RetTy, ArgsArray, NumArgs,
                                    FunctionProtoType::ExtProtoInfo());
=20
+    delete[] ArgsArray;
+
     DI->setLocation(StartLoc);
     DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
   }
@@ -328,7 +341,7 @@
     // Tell the epilog emitter to autorelease the result.  We do this
     // now so that various specialized functions can suppress it
     // during their IR-generation.
-    if (getLangOptions().ObjCAutoRefCount &&
+    if (getLangOpts().ObjCAutoRefCount &&
         !CurFnInfo->isReturnsRetained() &&
         RetTy->isObjCRetainableType())
       AutoreleaseResult =3D true;
@@ -339,8 +352,27 @@
   PrologueCleanupDepth =3D EHStack.stable_begin();
   EmitFunctionProlog(*CurFnInfo, CurFn, Args);
=20
-  if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
+  if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
     CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
+    const CXXMethodDecl *MD =3D cast<CXXMethodDecl>(D);
+    if (MD->getParent()->isLambda() &&
+        MD->getOverloadedOperator() =3D=3D OO_Call) {
+      // We're in a lambda; figure out the captures.
+      MD->getParent()->getCaptureFields(LambdaCaptureFields,
+                                        LambdaThisCaptureField);
+      if (LambdaThisCaptureField) {
+        // If this lambda captures this, load it.
+        LValue ThisLValue =3D EmitLValueForField(CXXABIThisValue,
+                                               LambdaThisCaptureField, 0);
+        CXXThisValue =3D EmitLoadOfLValue(ThisLValue).getScalarVal();
+      }
+    } else {
+      // Not in a lambda; just use 'this' from the method.
+      // FIXME: Should we generate a new load for each use of 'this'?  The
+      // fast register allocator would be happier...
+      CXXThisValue =3D CXXABIThisValue;
+    }
+  }
=20
   // If any of the arguments have a variably modified type, make sure to
   // emit the type size.
@@ -397,9 +429,8 @@
   if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
     CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
=20
-  if (FD->getNumParams())
-    for (unsigned i =3D 0, e =3D FD->getNumParams(); i !=3D e; ++i)
-      Args.push_back(FD->getParamDecl(i));
+  for (unsigned i =3D 0, e =3D FD->getNumParams(); i !=3D e; ++i)
+    Args.push_back(FD->getParamDecl(i));
=20
   SourceRange BodyRange;
   if (Stmt *Body =3D FD->getBody()) BodyRange =3D Body->getSourceRange();
@@ -412,10 +443,21 @@
     EmitDestructorBody(Args);
   else if (isa<CXXConstructorDecl>(FD))
     EmitConstructorBody(Args);
-  else if (getContext().getLangOptions().CUDA &&
+  else if (getContext().getLangOpts().CUDA &&
            !CGM.getCodeGenOpts().CUDAIsDevice &&
            FD->hasAttr<CUDAGlobalAttr>())
     CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
+  else if (isa<CXXConversionDecl>(FD) &&
+           cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()=
) {
+    // The lambda conversion to block pointer is special; the semantics ca=
n't be
+    // expressed in the AST, so IRGen needs to special-case it.
+    EmitLambdaToBlockPointerBody(Args);
+  } else if (isa<CXXMethodDecl>(FD) &&
+             cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
+    // The lambda "__invoke" function is special, because it forwards or
+    // clones the body of the function call operator (but is actually stat=
ic).
+    EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
+  }
   else
     EmitFunctionBody(Args);
=20
@@ -505,15 +547,14 @@
 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
   // FIXME: Rename and handle conversion of other evaluatable things
   // to bool.
-  Expr::EvalResult Result;
-  if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
-      Result.HasSideEffects)
+  llvm::APSInt Int;
+  if (!Cond->EvaluateAsInt(Int, getContext()))
     return false;  // Not foldable, not integer or not fully evaluatable.
- =20
+
   if (CodeGenFunction::ContainsLabel(Cond))
     return false;  // Contains a label.
- =20
-  ResultInt =3D Result.Val.getInt();
+
+  ResultInt =3D Int;
   return true;
 }
=20
@@ -606,29 +647,24 @@
   }
=20
   if (const ConditionalOperator *CondOp =3D dyn_cast<ConditionalOperator>(=
Cond)) {
-    // Handle ?: operator.
+    // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
+    llvm::BasicBlock *LHSBlock =3D createBasicBlock("cond.true");
+    llvm::BasicBlock *RHSBlock =3D createBasicBlock("cond.false");
=20
-    // Just ignore GNU ?: extension.
-    if (CondOp->getLHS()) {
-      // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
-      llvm::BasicBlock *LHSBlock =3D createBasicBlock("cond.true");
-      llvm::BasicBlock *RHSBlock =3D createBasicBlock("cond.false");
+    ConditionalEvaluation cond(*this);
+    EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
=20
-      ConditionalEvaluation cond(*this);
-      EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
+    cond.begin(*this);
+    EmitBlock(LHSBlock);
+    EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
+    cond.end(*this);
=20
-      cond.begin(*this);
-      EmitBlock(LHSBlock);
-      EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
-      cond.end(*this);
+    cond.begin(*this);
+    EmitBlock(RHSBlock);
+    EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
+    cond.end(*this);
=20
-      cond.begin(*this);
-      EmitBlock(RHSBlock);
-      EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
-      cond.end(*this);
-
-      return;
-    }
+    return;
   }
=20
   // Emit the code with the fully general case.
@@ -696,7 +732,7 @@
 void
 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty)=
 {
   // Ignore empty classes in C++.
-  if (getContext().getLangOptions().CPlusPlus) {
+  if (getContext().getLangOpts().CPlusPlus) {
     if (const RecordType *RT =3D Ty->getAs<RecordType>()) {
       if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
         return;
@@ -916,19 +952,19 @@
=20
   // We're going to walk down into the type and look for VLA
   // expressions.
-  type =3D type.getCanonicalType();
   do {
     assert(type->isVariablyModifiedType());
=20
     const Type *ty =3D type.getTypePtr();
     switch (ty->getTypeClass()) {
+
 #define TYPE(Class, Base)
 #define ABSTRACT_TYPE(Class, Base)
-#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
+#define NON_CANONICAL_TYPE(Class, Base)
 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
-#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
+#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
 #include "clang/AST/TypeNodes.def"
-      llvm_unreachable("unexpected dependent or non-canonical type!");
+      llvm_unreachable("unexpected dependent type!");
=20
     // These types are never variably-modified.
     case Type::Builtin:
@@ -937,6 +973,8 @@
     case Type::ExtVector:
     case Type::Record:
     case Type::Enum:
+    case Type::Elaborated:
+    case Type::TemplateSpecialization:
     case Type::ObjCObject:
     case Type::ObjCInterface:
     case Type::ObjCObjectPointer:
@@ -986,11 +1024,31 @@
       break;
     }
=20
-    case Type::FunctionProto:=20
+    case Type::FunctionProto:
     case Type::FunctionNoProto:
       type =3D cast<FunctionType>(ty)->getResultType();
       break;
=20
+    case Type::Paren:
+    case Type::TypeOf:
+    case Type::UnaryTransform:
+    case Type::Attributed:
+    case Type::SubstTemplateTypeParm:
+      // Keep walking after single level desugaring.
+      type =3D type.getSingleStepDesugaredType(getContext());
+      break;
+
+    case Type::Typedef:
+    case Type::Decltype:
+    case Type::Auto:
+      // Stop walking: nothing to do.
+      return;
+
+    case Type::TypeOfExpr:
+      // Stop walking: emit typeof expression.
+      EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
+      return;
+
     case Type::Atomic:
       type =3D cast<AtomicType>(ty)->getValueType();
       break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenFunction.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenFunction.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -25,8 +25,10 @@
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/ValueHandle.h"
+#include "llvm/Support/Debug.h"
 #include "CodeGenModule.h"
 #include "CGBuilder.h"
+#include "CGDebugInfo.h"
 #include "CGValue.h"
=20
 namespace llvm {
@@ -41,8 +43,8 @@
 }
=20
 namespace clang {
-  class APValue;
   class ASTContext;
+  class BlockDecl;
   class CXXDestructorDecl;
   class CXXForRangeStmt;
   class CXXTryStmt;
@@ -69,7 +71,6 @@
=20
 namespace CodeGen {
   class CodeGenTypes;
-  class CGDebugInfo;
   class CGFunctionInfo;
   class CGRecordLayout;
   class CGBlockInfo;
@@ -598,6 +599,9 @@
   const CodeGen::CGBlockInfo *BlockInfo;
   llvm::Value *BlockPointer;
=20
+  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
+  FieldDecl *LambdaThisCaptureField;
+
   /// \brief A mapping from NRVO variables to the flags used to indicate
   /// when the NRVO has been applied to this variable.
   llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
@@ -609,6 +613,9 @@
=20
   unsigned NextCleanupDestIndex;
=20
+  /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
+  CGBlockInfo *FirstBlockInfo;
+
   /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
   llvm::BasicBlock *EHResumeBlock;
=20
@@ -625,10 +632,6 @@
=20
   llvm::BasicBlock *getInvokeDestImpl();
=20
-  /// Set up the last cleaup that was pushed as a conditional
-  /// full-expression cleanup.
-  void initFullExprCleanup();
-
   template <class T>
   typename DominatingValue<T>::saved_type saveValueInCond(T value) {
     return DominatingValue<T>::save(*this, value);
@@ -739,6 +742,10 @@
     initFullExprCleanup();
   }
=20
+  /// Set up the last cleaup that was pushed as a conditional
+  /// full-expression cleanup.
+  void initFullExprCleanup();
+
   /// PushDestructorCleanup - Push a cleanup to call the
   /// complete-object destructor of an object of the given type at the
   /// given address.  Does nothing if T is not a C++ class type with a
@@ -758,16 +765,27 @@
   /// DeactivateCleanupBlock - Deactivates the given cleanup block.
   /// The block cannot be reactivated.  Pops it if it's the top of the
   /// stack.
-  void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
+  ///
+  /// \param DominatingIP - An instruction which is known to
+  ///   dominate the current IP (if set) and which lies along
+  ///   all paths of execution between the current IP and the
+  ///   the point at which the cleanup comes into scope.
+  void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
+                              llvm::Instruction *DominatingIP);
=20
   /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
   /// Cannot be used to resurrect a deactivated cleanup.
-  void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
+  ///
+  /// \param DominatingIP - An instruction which is known to
+  ///   dominate the current IP (if set) and which lies along
+  ///   all paths of execution between the current IP and the
+  ///   the point at which the cleanup comes into scope.
+  void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
+                            llvm::Instruction *DominatingIP);
=20
   /// \brief Enters a new scope for capturing cleanups, all of which
   /// will be executed once the scope is exited.
   class RunCleanupsScope {
-    CodeGenFunction& CGF;
     EHScopeStack::stable_iterator CleanupStackDepth;
     bool OldDidCallStackSave;
     bool PerformCleanup;
@@ -775,10 +793,13 @@
     RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
     RunCleanupsScope &operator=3D(const RunCleanupsScope &); // DO NOT IMP=
LEMENT
=20
+  protected:
+    CodeGenFunction& CGF;
+   =20
   public:
     /// \brief Enter a new cleanup scope.
     explicit RunCleanupsScope(CodeGenFunction &CGF)
-      : CGF(CGF), PerformCleanup(true)
+      : PerformCleanup(true), CGF(CGF)
     {
       CleanupStackDepth =3D CGF.EHStack.stable_begin();
       OldDidCallStackSave =3D CGF.DidCallStackSave;
@@ -809,6 +830,41 @@
     }
   };
=20
+  class LexicalScope: protected RunCleanupsScope {
+    SourceRange Range;
+    bool PopDebugStack;
+
+    LexicalScope(const LexicalScope &); // DO NOT IMPLEMENT THESE
+    LexicalScope &operator=3D(const LexicalScope &);
+
+  public:
+    /// \brief Enter a new cleanup scope.
+    explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
+      : RunCleanupsScope(CGF), Range(Range), PopDebugStack(true) {
+      if (CGDebugInfo *DI =3D CGF.getDebugInfo())
+        DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
+    }
+
+    /// \brief Exit this cleanup scope, emitting any accumulated
+    /// cleanups.
+    ~LexicalScope() {
+      if (PopDebugStack) {
+        CGDebugInfo *DI =3D CGF.getDebugInfo();
+        if (DI) DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
+      }
+    }
+
+    /// \brief Force the emission of cleanups now, instead of waiting
+    /// until this object is destroyed.
+    void ForceCleanup() {
+      RunCleanupsScope::ForceCleanup();
+      if (CGDebugInfo *DI =3D CGF.getDebugInfo()) {
+        DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
+        PopDebugStack =3D false;
+      }
+    }
+  };
+
=20
   /// PopCleanupBlocks - Takes the old cleanup stack size and emits
   /// the cleanup blocks that have been added.
@@ -881,6 +937,12 @@
   /// one branch or the other of a conditional expression.
   bool isInConditionalBranch() const { return OutermostConditional !=3D 0;=
 }
=20
+  void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr=
) {
+    assert(isInConditionalBranch());
+    llvm::BasicBlock *block =3D OutermostConditional->getStartingBlock();
+    new llvm::StoreInst(value, addr, &block->back());   =20
+  }
+
   /// An RAII object to record that we're evaluating a statement
   /// expression.
   class StmtExprEvaluation {
@@ -912,18 +974,91 @@
=20
   public:
     PeepholeProtection() : Inst(0) {}
-  }; =20
+  };
+
+  /// A non-RAII class containing all the information about a bound
+  /// opaque value.  OpaqueValueMapping, below, is a RAII wrapper for
+  /// this which makes individual mappings very simple; using this
+  /// class directly is useful when you have a variable number of
+  /// opaque values or don't want the RAII functionality for some
+  /// reason.
+  class OpaqueValueMappingData {
+    const OpaqueValueExpr *OpaqueValue;
+    bool BoundLValue;
+    CodeGenFunction::PeepholeProtection Protection;
+
+    OpaqueValueMappingData(const OpaqueValueExpr *ov,
+                           bool boundLValue)
+      : OpaqueValue(ov), BoundLValue(boundLValue) {}
+  public:
+    OpaqueValueMappingData() : OpaqueValue(0) {}
+
+    static bool shouldBindAsLValue(const Expr *expr) {
+      // gl-values should be bound as l-values for obvious reasons.
+      // Records should be bound as l-values because IR generation
+      // always keeps them in memory.  Expressions of function type
+      // act exactly like l-values but are formally required to be
+      // r-values in C.
+      return expr->isGLValue() ||
+             expr->getType()->isRecordType() ||
+             expr->getType()->isFunctionType();
+    }
+
+    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
+                                       const OpaqueValueExpr *ov,
+                                       const Expr *e) {
+      if (shouldBindAsLValue(ov))
+        return bind(CGF, ov, CGF.EmitLValue(e));
+      return bind(CGF, ov, CGF.EmitAnyExpr(e));
+    }
+
+    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
+                                       const OpaqueValueExpr *ov,
+                                       const LValue &lv) {
+      assert(shouldBindAsLValue(ov));
+      CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
+      return OpaqueValueMappingData(ov, true);
+    }
+
+    static OpaqueValueMappingData bind(CodeGenFunction &CGF,
+                                       const OpaqueValueExpr *ov,
+                                       const RValue &rv) {
+      assert(!shouldBindAsLValue(ov));
+      CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
+
+      OpaqueValueMappingData data(ov, false);
+
+      // Work around an extremely aggressive peephole optimization in
+      // EmitScalarConversion which assumes that all other uses of a
+      // value are extant.
+      data.Protection =3D CGF.protectFromPeepholes(rv);
+
+      return data;
+    }
+
+    bool isValid() const { return OpaqueValue !=3D 0; }
+    void clear() { OpaqueValue =3D 0; }
+
+    void unbind(CodeGenFunction &CGF) {
+      assert(OpaqueValue && "no data to unbind!");
+
+      if (BoundLValue) {
+        CGF.OpaqueLValues.erase(OpaqueValue);
+      } else {
+        CGF.OpaqueRValues.erase(OpaqueValue);
+        CGF.unprotectFromPeepholes(Protection);
+      }
+    }
+  };
=20
   /// An RAII object to set (and then clear) a mapping for an OpaqueValueE=
xpr.
   class OpaqueValueMapping {
     CodeGenFunction &CGF;
-    const OpaqueValueExpr *OpaqueValue;
-    bool BoundLValue;
-    CodeGenFunction::PeepholeProtection Protection;
+    OpaqueValueMappingData Data;
=20
   public:
     static bool shouldBindAsLValue(const Expr *expr) {
-      return expr->isGLValue() || expr->getType()->isRecordType();
+      return OpaqueValueMappingData::shouldBindAsLValue(expr);
     }
=20
     /// Build the opaque value mapping for the given conditional
@@ -933,75 +1068,34 @@
     ///
     OpaqueValueMapping(CodeGenFunction &CGF,
                        const AbstractConditionalOperator *op) : CGF(CGF) {
-      if (isa<ConditionalOperator>(op)) {
-        OpaqueValue =3D 0;
-        BoundLValue =3D false;
+      if (isa<ConditionalOperator>(op))
+        // Leave Data empty.
         return;
-      }
=20
       const BinaryConditionalOperator *e =3D cast<BinaryConditionalOperato=
r>(op);
-      init(e->getOpaqueValue(), e->getCommon());
+      Data =3D OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
+                                          e->getCommon());
     }
=20
     OpaqueValueMapping(CodeGenFunction &CGF,
                        const OpaqueValueExpr *opaqueValue,
                        LValue lvalue)
-      : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(true) {
-      assert(opaqueValue && "no opaque value expression!");
-      assert(shouldBindAsLValue(opaqueValue));
-      initLValue(lvalue);
+      : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lval=
ue)) {
     }
=20
     OpaqueValueMapping(CodeGenFunction &CGF,
                        const OpaqueValueExpr *opaqueValue,
                        RValue rvalue)
-      : CGF(CGF), OpaqueValue(opaqueValue), BoundLValue(false) {
-      assert(opaqueValue && "no opaque value expression!");
-      assert(!shouldBindAsLValue(opaqueValue));
-      initRValue(rvalue);
+      : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rval=
ue)) {
     }
=20
     void pop() {
-      assert(OpaqueValue && "mapping already popped!");
-      popImpl();
-      OpaqueValue =3D 0;
+      Data.unbind(CGF);
+      Data.clear();
     }
=20
     ~OpaqueValueMapping() {
-      if (OpaqueValue) popImpl();
-    }
-
-  private:
-    void popImpl() {
-      if (BoundLValue)
-        CGF.OpaqueLValues.erase(OpaqueValue);
-      else {
-        CGF.OpaqueRValues.erase(OpaqueValue);
-        CGF.unprotectFromPeepholes(Protection);
-      }
-    }
-
-    void init(const OpaqueValueExpr *ov, const Expr *e) {
-      OpaqueValue =3D ov;
-      BoundLValue =3D shouldBindAsLValue(ov);
-      assert(BoundLValue =3D=3D shouldBindAsLValue(e)
-             && "inconsistent expression value kinds!");
-      if (BoundLValue)
-        initLValue(CGF.EmitLValue(e));
-      else
-        initRValue(CGF.EmitAnyExpr(e));
-    }
-
-    void initLValue(const LValue &lv) {
-      CGF.OpaqueLValues.insert(std::make_pair(OpaqueValue, lv));
-    }
-
-    void initRValue(const RValue &rv) {
-      // Work around an extremely aggressive peephole optimization in
-      // EmitScalarConversion which assumes that all other uses of a
-      // value are extant.
-      Protection =3D CGF.protectFromPeepholes(rv);
-      CGF.OpaqueRValues.insert(std::make_pair(OpaqueValue, rv));
+      if (Data.isValid()) Data.unbind(CGF);
     }
   };
  =20
@@ -1046,7 +1140,7 @@
   };
   SmallVector<BreakContinue, 8> BreakContinueStack;
=20
-  /// SwitchInsn - This is nearest current switch instruction. It is null =
if if
+  /// SwitchInsn - This is nearest current switch instruction. It is null =
if
   /// current context is not in a switch.
   llvm::SwitchInst *SwitchInsn;
=20
@@ -1073,7 +1167,8 @@
=20
   /// CXXThisDecl - When generating code for a C++ member function,
   /// this will hold the implicit 'this' declaration.
-  ImplicitParamDecl *CXXThisDecl;
+  ImplicitParamDecl *CXXABIThisDecl;
+  llvm::Value *CXXABIThisValue;
   llvm::Value *CXXThisValue;
=20
   /// CXXVTTDecl - When generating code for a base object constructor or
@@ -1099,6 +1194,7 @@
=20
 public:
   CodeGenFunction(CodeGenModule &cgm);
+  ~CodeGenFunction();
=20
   CodeGenTypes &getTypes() const { return CGM.getTypes(); }
   ASTContext &getContext() const { return CGM.getContext(); }
@@ -1114,7 +1210,7 @@
     return CGM.getCodeGenOpts().OptimizationLevel =3D=3D 0;
   }
=20
-  const LangOptions &getLangOptions() const { return CGM.getLangOptions();=
 }
+  const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
=20
   /// Returns a pointer to the function's exception object and selector sl=
ot,
   /// which is assigned in every landing pad.
@@ -1152,27 +1248,27 @@
   void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
                                         llvm::Value *arrayEndPointer,
                                         QualType elementType,
-                                        Destroyer &destroyer);
+                                        Destroyer *destroyer);
   void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
                                       llvm::Value *arrayEnd,
                                       QualType elementType,
-                                      Destroyer &destroyer);
+                                      Destroyer *destroyer);
=20
   void pushDestroy(QualType::DestructionKind dtorKind,
                    llvm::Value *addr, QualType type);
   void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
-                   Destroyer &destroyer, bool useEHCleanupForArray);
-  void emitDestroy(llvm::Value *addr, QualType type, Destroyer &destroyer,
+                   Destroyer *destroyer, bool useEHCleanupForArray);
+  void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
                    bool useEHCleanupForArray);
   llvm::Function *generateDestroyHelper(llvm::Constant *addr,
                                         QualType type,
-                                        Destroyer &destroyer,
+                                        Destroyer *destroyer,
                                         bool useEHCleanupForArray);
   void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
-                        QualType type, Destroyer &destroyer,
+                        QualType type, Destroyer *destroyer,
                         bool checkZeroLength, bool useEHCleanup);
=20
-  Destroyer &getDestroyer(QualType::DestructionKind destructionKind);
+  Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
=20
   /// Determines whether an EH cleanup is required to destroy a type
   /// with the given destruction kind.
@@ -1182,9 +1278,9 @@
       return false;
     case QualType::DK_cxx_destructor:
     case QualType::DK_objc_weak_lifetime:
-      return getLangOptions().Exceptions;
+      return getLangOpts().Exceptions;
     case QualType::DK_objc_strong_lifetime:
-      return getLangOptions().Exceptions &&
+      return getLangOpts().Exceptions &&
              CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
     }
     llvm_unreachable("bad destruction kind");
@@ -1208,7 +1304,8 @@
   void GenerateObjCGetter(ObjCImplementationDecl *IMP,
                           const ObjCPropertyImplDecl *PID);
   void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
-                              const ObjCPropertyImplDecl *propImpl);
+                              const ObjCPropertyImplDecl *propImpl,
+                              llvm::Constant *AtomicHelperFn);
=20
   void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
                                   ObjCMethodDecl *MD, bool ctor);
@@ -1218,7 +1315,8 @@
   void GenerateObjCSetter(ObjCImplementationDecl *IMP,
                           const ObjCPropertyImplDecl *PID);
   void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
-                              const ObjCPropertyImplDecl *propImpl);
+                              const ObjCPropertyImplDecl *propImpl,
+                              llvm::Constant *AtomicHelperFn);
   bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
   bool IvarTypeWithAggrGCObjects(QualType Ty);
=20
@@ -1227,6 +1325,8 @@
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
=20
   llvm::Value *EmitBlockLiteral(const BlockExpr *);
+  llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
+  static void destroyBlockInfos(CGBlockInfo *info);
   llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
                                            const CGBlockInfo &Info,
                                            llvm::StructType *,
@@ -1235,10 +1335,16 @@
   llvm::Function *GenerateBlockFunction(GlobalDecl GD,
                                         const CGBlockInfo &Info,
                                         const Decl *OuterFuncDecl,
-                                        const DeclMapTy &ldm);
+                                        const DeclMapTy &ldm,
+                                        bool IsLambdaConversionToBlock);
=20
   llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
   llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockIn=
fo);
+  llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
+                                             const ObjCPropertyImplDecl *P=
ID);
+  llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
+                                             const ObjCPropertyImplDecl *P=
ID);
+  llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty=
);
=20
   void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
=20
@@ -1253,10 +1359,7 @@
   }
=20
   void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
-  void AllocateBlockDecl(const BlockDeclRefExpr *E);
-  llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
-    return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
-  }
+  void AllocateBlockDecl(const DeclRefExpr *E);
   llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
   llvm::Type *BuildByRefType(const VarDecl *var);
=20
@@ -1272,6 +1375,13 @@
   void EmitDestructorBody(FunctionArgList &Args);
   void EmitFunctionBody(FunctionArgList &Args);
=20
+  void EmitForwardingCallToLambda(const CXXRecordDecl *Lambda,
+                                  CallArgList &CallArgs);
+  void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
+  void EmitLambdaBlockInvokeBody();
+  void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
+  void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
+
   /// EmitReturnBlock - Emit the unified return block, trying to avoid its
   /// emission when possible.
   void EmitReturnBlock();
@@ -1290,6 +1400,9 @@
   void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
                         FunctionArgList &Args);
=20
+  void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
+                               ArrayRef<VarDecl *> ArrayIndexes);
+
   /// InitializeVTablePointer - Initialize the vtable pointer of the given
   /// subobject.
   ///
@@ -1442,7 +1555,15 @@
   //                                  Helpers
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
=20
-  LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment =3D=
 0) {
+  LValue MakeAddrLValue(llvm::Value *V, QualType T,
+                        CharUnits Alignment =3D CharUnits()) {
+    return LValue::MakeAddr(V, T, Alignment, getContext(),
+                            CGM.getTBAAInfo(T));
+  }
+  LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
+    CharUnits Alignment;
+    if (!T->isIncompleteType())
+      Alignment =3D getContext().getTypeAlignInChars(T);
     return LValue::MakeAddr(V, T, Alignment, getContext(),
                             CGM.getTBAAInfo(T));
   }
@@ -1470,7 +1591,9 @@
   /// CreateAggTemp - Create a temporary memory object for the given
   /// aggregate type.
   AggValueSlot CreateAggTemp(QualType T, const Twine &Name =3D "tmp") {
-    return AggValueSlot::forAddr(CreateMemTemp(T, Name), T.getQualifiers(),
+    CharUnits Alignment =3D getContext().getTypeAlignInChars(T);
+    return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
+                                 T.getQualifiers(),
                                  AggValueSlot::IsNotDestructed,
                                  AggValueSlot::DoesNotNeedGCBarriers,
                                  AggValueSlot::IsNotAliased);
@@ -1519,7 +1642,8 @@
   /// \param isVolatile - True iff either the source or the destination is
   /// volatile.
   void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
-                         QualType EltTy, bool isVolatile=3Dfalse);
+                         QualType EltTy, bool isVolatile=3Dfalse,
+                         unsigned Alignment =3D 0);
=20
   /// StartBlock - Start new block named N. If insert block is a dummy blo=
ck
   /// then reuse it.
@@ -1677,7 +1801,8 @@
   void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
                                llvm::Value *NewPtr, llvm::Value *NumElemen=
ts);
=20
-  void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
+  void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
+                        llvm::Value *Ptr);
=20
   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
@@ -1688,6 +1813,10 @@
   llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
   llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *D=
CE);
=20
+  void MaybeEmitStdInitializerListCleanup(llvm::Value *loc, const Expr *in=
it);
+  void EmitStdInitializerListCleanup(llvm::Value *loc,
+                                     const InitListExpr *init);
+
   void EmitCheck(llvm::Value *, unsigned Size);
=20
   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
@@ -1917,13 +2046,14 @@
   /// the LLVM value representation.
   void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
                          bool Volatile, unsigned Alignment, QualType Ty,
-                         llvm::MDNode *TBAAInfo =3D 0);
+                         llvm::MDNode *TBAAInfo =3D 0, bool isInit=3Dfalse=
);
=20
   /// EmitStoreOfScalar - Store a scalar value to an address, taking
   /// care to appropriately convert from the memory representation to
   /// the LLVM value representation.  The l-value must be a simple
-  /// l-value.
-  void EmitStoreOfScalar(llvm::Value *value, LValue lvalue);
+  /// l-value.  The isInit flag indicates whether this is an initializatio=
n.
+  /// If so, atomic qualifiers are ignored and the store is always non-ato=
mic.
+  void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=3D=
false);
=20
   /// EmitLoadOfLValue - Given an expression that represents a value lvalu=
e,
   /// this method emits the address of the lvalue, then loads the result a=
s an
@@ -1931,15 +2061,12 @@
   RValue EmitLoadOfLValue(LValue V);
   RValue EmitLoadOfExtVectorElementLValue(LValue V);
   RValue EmitLoadOfBitfieldLValue(LValue LV);
-  RValue EmitLoadOfPropertyRefLValue(LValue LV,
-                                 ReturnValueSlot Return =3D ReturnValueSlo=
t());
=20
   /// EmitStoreThroughLValue - Store the specified rvalue into the specifi=
ed
   /// lvalue, where both are guaranteed to the have the same type, and tha=
t type
   /// is 'Ty'.
-  void EmitStoreThroughLValue(RValue Src, LValue Dst);
+  void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=3Dfalse);
   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
-  void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst);
=20
   /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
   /// EmitStoreThroughLValue.
@@ -1977,6 +2104,40 @@
   LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
   LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
=20
+  class ConstantEmission {
+    llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
+    ConstantEmission(llvm::Constant *C, bool isReference)
+      : ValueAndIsReference(C, isReference) {}
+  public:
+    ConstantEmission() {}
+    static ConstantEmission forReference(llvm::Constant *C) {
+      return ConstantEmission(C, true);
+    }
+    static ConstantEmission forValue(llvm::Constant *C) {
+      return ConstantEmission(C, false);
+    }
+
+    operator bool() const { return ValueAndIsReference.getOpaqueValue() !=
=3D 0; }
+
+    bool isReference() const { return ValueAndIsReference.getInt(); }
+    LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
+      assert(isReference());
+      return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer=
(),
+                                            refExpr->getType());
+    }
+
+    llvm::Constant *getValue() const {
+      assert(!isReference());
+      return ValueAndIsReference.getPointer();
+    }
+  };
+
+  ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
+
+  RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
+                                AggValueSlot slot =3D AggValueSlot::ignore=
d());
+  LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
+
   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
                               const ObjCIvarDecl *Ivar);
   LValue EmitLValueForAnonRecordField(llvm::Value* Base,
@@ -1999,16 +2160,13 @@
   LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
                                 unsigned CVRQualifiers);
=20
-  LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
-
   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
-  LValue EmitExprWithCleanupsLValue(const ExprWithCleanups *E);
+  LValue EmitLambdaLValue(const LambdaExpr *E);
   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
=20
   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
-  LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
   LValue EmitStmtExprLValue(const StmtExpr *E);
   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
   LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
@@ -2098,12 +2256,18 @@
   llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
                                    bool negateForRightShift);
=20
-  llvm::Value *BuildVector(const SmallVectorImpl<llvm::Value*> &Ops);
+  llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
+  llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *=
E);
   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
=20
   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
+  llvm::Value *EmitObjCNumericLiteral(const ObjCNumericLiteral *E);
+  llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
+  llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
+  llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
+                                const ObjCMethodDecl *MethodWithObjects);
   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
                              ReturnValueSlot Return =3D ReturnValueSlot());
@@ -2243,7 +2407,8 @@
=20
   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
   /// variable with global storage.
-  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
+  void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
+                                bool PerformInit);
=20
   /// EmitCXXGlobalDtorRegistration - Emits a call to register the global =
ptr
   /// with the C++ runtime so that its destructor will be called at exit.
@@ -2255,7 +2420,8 @@
   /// possible to prove that an initialization will be done exactly
   /// once, e.g. with a static local variable or a static data member
   /// of a class template.
-  void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr);
+  void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
+                          bool PerformInit);
=20
   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
   /// variables.
@@ -2263,26 +2429,32 @@
                                  llvm::Constant **Decls,
                                  unsigned NumDecls);
=20
-  /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
+  /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
   /// variables.
-  void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
-                                 const std::vector<std::pair<llvm::WeakVH,
-                                   llvm::Constant*> > &DtorsAndObjects);
+  void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
+                                  const std::vector<std::pair<llvm::WeakVH,
+                                  llvm::Constant*> > &DtorsAndObjects);
=20
   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
                                         const VarDecl *D,
-                                        llvm::GlobalVariable *Addr);
+                                        llvm::GlobalVariable *Addr,
+                                        bool PerformInit);
=20
   void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  =20
   void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
                                   const Expr *Exp);
=20
-  RValue EmitExprWithCleanups(const ExprWithCleanups *E,
-                              AggValueSlot Slot =3DAggValueSlot::ignored()=
);
+  void enterFullExpression(const ExprWithCleanups *E) {
+    if (E->getNumObjects() =3D=3D 0) return;
+    enterNonTrivialFullExpression(E);
+  }
+  void enterNonTrivialFullExpression(const ExprWithCleanups *E);
=20
   void EmitCXXThrowExpr(const CXXThrowExpr *E);
=20
+  void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
+
   RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest =3D 0);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2344,7 +2516,12 @@
   /// a r-value suitable for passing the given parameter.
   void EmitDelegateCallArg(CallArgList &args, const VarDecl *param);
=20
+  /// SetFPAccuracy - Set the minimum required accuracy of the given float=
ing
+  /// point operation, expressed as the maximum relative error in ulp.
+  void SetFPAccuracy(llvm::Value *Val, float Accuracy);
+
 private:
+  llvm::MDNode *getRangeForLoadFromType(QualType Ty);
   void EmitReturnOfRValue(RValue RV, QualType Ty);
=20
   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
@@ -2432,6 +2609,18 @@
   CodeGenModule::ByrefHelpers *
   buildByrefHelpers(llvm::StructType &byrefType,
                     const AutoVarEmission &emission);
+
+  void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
+
+  /// GetPointeeAlignment - Given an expression with a pointer type, find =
the
+  /// alignment of the type referenced by the pointer.  Skip over implicit
+  /// casts.
+  unsigned GetPointeeAlignment(const Expr *Addr);
+
+  /// GetPointeeAlignmentValue - Given an expression with a pointer type, =
find
+  /// the alignment of the type referenced by the pointer.  Skip over impl=
icit
+  /// casts.  Return the alignment as an llvm::Value.
+  llvm::Value *GetPointeeAlignmentValue(const Expr *Addr);
 };
=20
 /// Helper class with most of the code for saving a value for a
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenModule.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -30,6 +30,7 @@
 #include "clang/AST/Mangle.h"
 #include "clang/AST/RecordLayout.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TargetInfo.h"
@@ -38,6 +39,7 @@
 #include "llvm/Module.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/LLVMContext.h"
+#include "llvm/ADT/APSInt.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/Target/Mangler.h"
 #include "llvm/Target/TargetData.h"
@@ -56,35 +58,53 @@
   }
=20
   llvm_unreachable("invalid C++ ABI kind");
-  return *CreateItaniumCXXABI(CGM);
 }
=20
=20
 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
                              llvm::Module &M, const llvm::TargetData &TD,
                              DiagnosticsEngine &diags)
-  : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(=
M),
+  : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
     ABI(createCXXABI(*this)),=20
-    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
+    Types(*this),
     TBAA(0),
     VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
-    DebugInfo(0), ARCData(0), RRData(0), CFConstantStringClassRef(0),
+    DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
+    RRData(0), CFConstantStringClassRef(0),
     ConstantStringClassRef(0), NSConstantStringType(0),
     VMContext(M.getContext()),
     NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
     BlockObjectAssign(0), BlockObjectDispose(0),
     BlockDescriptorType(0), GenericBlockLiteralType(0) {
-  if (Features.ObjC1)
+     =20
+  // Initialize the type cache.
+  llvm::LLVMContext &LLVMContext =3D M.getContext();
+  VoidTy =3D llvm::Type::getVoidTy(LLVMContext);
+  Int8Ty =3D llvm::Type::getInt8Ty(LLVMContext);
+  Int16Ty =3D llvm::Type::getInt16Ty(LLVMContext);
+  Int32Ty =3D llvm::Type::getInt32Ty(LLVMContext);
+  Int64Ty =3D llvm::Type::getInt64Ty(LLVMContext);
+  FloatTy =3D llvm::Type::getFloatTy(LLVMContext);
+  DoubleTy =3D llvm::Type::getDoubleTy(LLVMContext);
+  PointerWidthInBits =3D C.getTargetInfo().getPointerWidth(0);
+  PointerAlignInBytes =3D
+  C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(=
);
+  IntTy =3D llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWi=
dth());
+  IntPtrTy =3D llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
+  Int8PtrTy =3D Int8Ty->getPointerTo(0);
+  Int8PtrPtrTy =3D Int8PtrTy->getPointerTo(0);
+
+  if (LangOpts.ObjC1)
     createObjCRuntime();
-  if (Features.OpenCL)
+  if (LangOpts.OpenCL)
     createOpenCLRuntime();
-  if (Features.CUDA)
+  if (LangOpts.CUDA)
     createCUDARuntime();
=20
   // Enable TBAA unless it's suppressed.
   if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
-    TBAA =3D new CodeGenTBAA(Context, VMContext, getLangOptions(),
+    TBAA =3D new CodeGenTBAA(Context, VMContext, getLangOpts(),
                            ABI.getMangleContext());
=20
   // If debug info or coverage generation is enabled, create the CGDebugIn=
fo
@@ -95,23 +115,9 @@
=20
   Block.GlobalUniqueCount =3D 0;
=20
-  if (C.getLangOptions().ObjCAutoRefCount)
+  if (C.getLangOpts().ObjCAutoRefCount)
     ARCData =3D new ARCEntrypoints();
   RRData =3D new RREntrypoints();
-
-  // Initialize the type cache.
-  llvm::LLVMContext &LLVMContext =3D M.getContext();
-  VoidTy =3D llvm::Type::getVoidTy(LLVMContext);
-  Int8Ty =3D llvm::Type::getInt8Ty(LLVMContext);
-  Int32Ty =3D llvm::Type::getInt32Ty(LLVMContext);
-  Int64Ty =3D llvm::Type::getInt64Ty(LLVMContext);
-  PointerWidthInBits =3D C.getTargetInfo().getPointerWidth(0);
-  PointerAlignInBytes =3D
-    C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantit=
y();
-  IntTy =3D llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWi=
dth());
-  IntPtrTy =3D llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
-  Int8PtrTy =3D Int8Ty->getPointerTo(0);
-  Int8PtrPtrTy =3D Int8PtrTy->getPointerTo(0);
 }
=20
 CodeGenModule::~CodeGenModule() {
@@ -127,7 +133,7 @@
 }
=20
 void CodeGenModule::createObjCRuntime() {
-  if (!Features.NeXTRuntime)
+  if (!LangOpts.NeXTRuntime)
     ObjCRuntime =3D CreateGNUObjCRuntime(*this);
   else
     ObjCRuntime =3D CreateMacObjCRuntime(*this);
@@ -168,8 +174,6 @@
 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
   // Make sure that this type is translated.
   Types.UpdateCompletedType(TD);
-  if (DebugInfo)
-    DebugInfo->UpdateCompletedType(TD);
 }
=20
 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
@@ -178,6 +182,12 @@
   return TBAA->getTBAAInfo(QTy);
 }
=20
+llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
+  if (!TBAA)
+    return 0;
+  return TBAA->getTBAAInfoForVTablePtr();
+}
+
 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
                                         llvm::MDNode *TBAAInfo) {
   Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
@@ -292,7 +302,7 @@
   // If there's a key function, there may be translation units
   // that don't have the key function's definition.  But ignore
   // this if we're emitting RTTI under -fno-rtti.
-  if (!(TVK !=3D TVK_ForRTTI) || Features.RTTI) {
+  if (!(TVK !=3D TVK_ForRTTI) || LangOpts.RTTI) {
     if (Context.getKeyFunction(RD))
       return;
   }
@@ -317,7 +327,7 @@
     return Str;
   }
  =20
-  llvm::SmallString<256> Buffer;
+  SmallString<256> Buffer;
   llvm::raw_svector_ostream Out(Buffer);
   if (const CXXConstructorDecl *D =3D dyn_cast<CXXConstructorDecl>(ND))
     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
@@ -379,16 +389,15 @@
=20
   // Get the type of a ctor entry, { i32, void ()* }.
   llvm::StructType *CtorStructTy =3D
-    llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
-                          llvm::PointerType::getUnqual(CtorFTy), NULL);
+    llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), =
NULL);
=20
   // Construct the constructor and destructor arrays.
-  std::vector<llvm::Constant*> Ctors;
+  SmallVector<llvm::Constant*, 8> Ctors;
   for (CtorList::const_iterator I =3D Fns.begin(), E =3D Fns.end(); I !=3D=
 E; ++I) {
-    std::vector<llvm::Constant*> S;
-    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
-                I->second, false));
-    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
+    llvm::Constant *S[] =3D {
+      llvm::ConstantInt::get(Int32Ty, I->second, false),
+      llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
+    };
     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
   }
=20
@@ -431,7 +440,7 @@
   // merged with other definitions. c) C++ has the ODR, so we know the
   // definition is dependable.
   if (Linkage =3D=3D GVA_CXXInline || Linkage =3D=3D GVA_TemplateInstantia=
tion)
-    return !Context.getLangOptions().AppleKext=20
+    return !Context.getLangOpts().AppleKext=20
              ? llvm::Function::LinkOnceODRLinkage=20
              : llvm::Function::InternalLinkage;
  =20
@@ -440,7 +449,7 @@
   // and must all be equivalent. However, we are not allowed to
   // throw away these explicit instantiations.
   if (Linkage =3D=3D GVA_ExplicitTemplateInstantiation)
-    return !Context.getLangOptions().AppleKext
+    return !Context.getLangOpts().AppleKext
              ? llvm::Function::WeakODRLinkage
              : llvm::Function::ExternalLinkage;
  =20
@@ -475,16 +484,16 @@
 /// except under the fragile ObjC ABI with only ObjC exceptions
 /// enabled.  This means, for example, that C with -fexceptions
 /// enables this.
-static bool hasUnwindExceptions(const LangOptions &Features) {
+static bool hasUnwindExceptions(const LangOptions &LangOpts) {
   // If exceptions are completely disabled, obviously this is false.
-  if (!Features.Exceptions) return false;
+  if (!LangOpts.Exceptions) return false;
=20
   // If C++ exceptions are enabled, this is true.
-  if (Features.CXXExceptions) return true;
+  if (LangOpts.CXXExceptions) return true;
=20
   // If ObjC exceptions are enabled, this depends on the ABI.
-  if (Features.ObjCExceptions) {
-    if (!Features.ObjCNonFragileABI) return false;
+  if (LangOpts.ObjCExceptions) {
+    if (!LangOpts.ObjCNonFragileABI) return false;
   }
=20
   return true;
@@ -495,7 +504,7 @@
   if (CodeGenOpts.UnwindTables)
     F->setHasUWTable();
=20
-  if (!hasUnwindExceptions(Features))
+  if (!hasUnwindExceptions(LangOpts))
     F->addFnAttr(llvm::Attribute::NoUnwind);
=20
   if (D->hasAttr<NakedAttr>()) {
@@ -515,11 +524,18 @@
   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
     F->setUnnamedAddr(true);
=20
-  if (Features.getStackProtector() =3D=3D LangOptions::SSPOn)
+  if (LangOpts.getStackProtector() =3D=3D LangOptions::SSPOn)
     F->addFnAttr(llvm::Attribute::StackProtect);
-  else if (Features.getStackProtector() =3D=3D LangOptions::SSPReq)
+  else if (LangOpts.getStackProtector() =3D=3D LangOptions::SSPReq)
     F->addFnAttr(llvm::Attribute::StackProtectReq);
  =20
+  if (LangOpts.AddressSanitizer) {
+    // When AddressSanitizer is enabled, set AddressSafety attribute
+    // unless __attribute__((no_address_safety_analysis)) is used.
+    if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
+      F->addFnAttr(llvm::Attribute::AddressSafety);
+  }
+
   unsigned alignment =3D D->getMaxAlignment() / Context.getCharWidth();
   if (alignment)
     F->setAlignment(alignment);
@@ -569,7 +585,7 @@
   const FunctionDecl *FD =3D cast<FunctionDecl>(GD.getDecl());
=20
   if (!IsIncompleteFunction)
-    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
+    SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD),=
 F);
=20
   // Only a few attributes are set on declarations; these may later be
   // overridden by a definition.
@@ -605,20 +621,18 @@
   if (LLVMUsed.empty())
     return;
=20
-  llvm::Type *i8PTy =3D llvm::Type::getInt8PtrTy(VMContext);
-
   // Convert LLVMUsed to what ConstantArray needs.
-  std::vector<llvm::Constant*> UsedArray;
+  SmallVector<llvm::Constant*, 8> UsedArray;
   UsedArray.resize(LLVMUsed.size());
   for (unsigned i =3D 0, e =3D LLVMUsed.size(); i !=3D e; ++i) {
     UsedArray[i] =3D
      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
-                                      i8PTy);
+                                    Int8PtrTy);
   }
=20
   if (UsedArray.empty())
     return;
-  llvm::ArrayType *ATy =3D llvm::ArrayType::get(i8PTy, UsedArray.size());
+  llvm::ArrayType *ATy =3D llvm::ArrayType::get(Int8PtrTy, UsedArray.size(=
));
=20
   llvm::GlobalVariable *GV =3D
     new llvm::GlobalVariable(getModule(), ATy, false,
@@ -689,7 +703,7 @@
     return i->second;
=20
   // Not found yet, create a new global.
-  llvm::Constant *s =3D llvm::ConstantArray::get(getLLVMContext(), Str, tr=
ue);
+  llvm::Constant *s =3D llvm::ConstantDataArray::getString(getLLVMContext(=
), Str);
   llvm::GlobalValue *gv =3D new llvm::GlobalVariable(getModule(), s->getTy=
pe(),
     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
   gv->setSection(AnnotationSection);
@@ -744,7 +758,7 @@
=20
 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
   // Never defer when EmitAllDecls is specified.
-  if (Features.EmitAllDecls)
+  if (LangOpts.EmitAllDecls)
     return false;
=20
   return !getContext().DeclMustBeEmitted(Global);
@@ -788,7 +802,7 @@
     return EmitAliasDefinition(GD);
=20
   // If this is CUDA, be selective about which declarations we emit.
-  if (Features.CUDA) {
+  if (LangOpts.CUDA) {
     if (CodeGenOpts.CUDAIsDevice) {
       if (!Global->hasAttr<CUDADeviceAttr>() &&
           !Global->hasAttr<CUDAGlobalAttr>() &&
@@ -815,10 +829,7 @@
       FD->getBody(InlineDefinition);
=20
       StringRef MangledName =3D getMangledName(GD);
-      llvm::StringMap<GlobalDecl>::iterator DDI =3D
-          DeferredDecls.find(MangledName);
-      if (DDI !=3D DeferredDecls.end())
-        DeferredDecls.erase(DDI);
+      DeferredDecls.erase(MangledName);
       EmitGlobalDefinition(InlineDefinition);
       return;
     }
@@ -840,7 +851,7 @@
=20
   // If we're deferring emission of a C++ variable with an
   // initializer, remember the order in which it appeared in the file.
-  if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
+  if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
       cast<VarDecl>(Global)->hasInit()) {
     DelayedCXXInitPosition[Global] =3D CXXGlobalInits.size();
     CXXGlobalInits.push_back(0);
@@ -863,20 +874,28 @@
   struct FunctionIsDirectlyRecursive :
     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
     const StringRef Name;
+    const Builtin::Context &BI;
     bool Result;
-    FunctionIsDirectlyRecursive(const FunctionDecl *F) :
-      Name(F->getName()), Result(false) {
+    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
+      Name(N), BI(C), Result(false) {
     }
     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
=20
     bool TraverseCallExpr(CallExpr *E) {
-      const Decl *D =3D E->getCalleeDecl();
-      if (!D)
+      const FunctionDecl *FD =3D E->getDirectCallee();
+      if (!FD)
         return true;
-      AsmLabelAttr *Attr =3D D->getAttr<AsmLabelAttr>();
-      if (!Attr)
+      AsmLabelAttr *Attr =3D FD->getAttr<AsmLabelAttr>();
+      if (Attr && Name =3D=3D Attr->getLabel()) {
+        Result =3D true;
+        return false;
+      }
+      unsigned BuiltinID =3D FD->getBuiltinID();
+      if (!BuiltinID)
         return true;
-      if (Name =3D=3D Attr->getLabel()) {
+      StringRef BuiltinName =3D BI.GetName(BuiltinID);
+      if (BuiltinName.startswith("__builtin_") &&
+          Name =3D=3D BuiltinName.slice(strlen("__builtin_"), StringRef::n=
pos)) {
         Result =3D true;
         return false;
       }
@@ -885,15 +904,24 @@
   };
 }
=20
-// isTriviallyRecursiveViaAsm - Check if this function calls another
-// decl that, because of the asm attribute, ends up pointing to itself.
+// isTriviallyRecursive - Check if this function calls another
+// decl that, because of the asm attribute or the other decl being a built=
in,
+// ends up pointing to itself.
 bool
-CodeGenModule::isTriviallyRecursiveViaAsm(const FunctionDecl *F) {
-  if (getCXXABI().getMangleContext().shouldMangleDeclName(F))
-    return false;
+CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
+  StringRef Name;
+  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
+    // asm labels are a special kind of mangling we have to support.
+    AsmLabelAttr *Attr =3D FD->getAttr<AsmLabelAttr>();
+    if (!Attr)
+      return false;
+    Name =3D Attr->getLabel();
+  } else {
+    Name =3D FD->getName();
+  }
=20
-  FunctionIsDirectlyRecursive Walker(F);
-  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
+  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
+  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
   return Walker.Result;
 }
=20
@@ -909,7 +937,7 @@
   // but a function that calls itself is clearly not equivalent to the real
   // implementation.
   // This happens in glibc's btowc and in some configure checks.
-  return !isTriviallyRecursiveViaAsm(F);
+  return !isTriviallyRecursive(F);
 }
=20
 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
@@ -1023,7 +1051,7 @@
   //
   // We also don't emit a definition for a function if it's going to be an=
 entry
   // in a vtable, unless it's already marked as used.
-  } else if (getLangOptions().CPlusPlus && D.getDecl()) {
+  } else if (getLangOpts().CPlusPlus && D.getDecl()) {
     // Look for a declaration that's lexically in a record.
     const FunctionDecl *FD =3D cast<FunctionDecl>(D.getDecl());
     do {
@@ -1037,7 +1065,7 @@
           break;
         }
       }
-      FD =3D FD->getPreviousDeclaration();
+      FD =3D FD->getPreviousDecl();
     } while (FD);
   }
=20
@@ -1075,19 +1103,23 @@
                                  ExtraAttrs);
 }
=20
-static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
-                                 bool ConstantInit) {
-  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType(=
))
+/// isTypeConstant - Determine whether an object of this type can be emitt=
ed
+/// as a constant.
+///
+/// If ExcludeCtor is true, the duration when the object's constructor runs
+/// will not be considered. The caller will need to verify that the object=
 is
+/// not written to during its construction.
+bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
+  if (!Ty.isConstant(Context) && !Ty->isReferenceType())
     return false;
- =20
-  if (Context.getLangOptions().CPlusPlus) {
-    if (const RecordType *Record=20
-          =3D Context.getBaseElementType(D->getType())->getAs<RecordType>(=
))
-      return ConstantInit &&=20
-             cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
-             !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
+
+  if (Context.getLangOpts().CPlusPlus) {
+    if (const CXXRecordDecl *Record
+          =3D Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
+      return ExcludeCtor && !Record->hasMutableFields() &&
+             Record->hasTrivialDestructor();
   }
- =20
+
   return true;
 }
=20
@@ -1144,7 +1176,7 @@
   if (D) {
     // FIXME: This code is overly simple and should be merged with other g=
lobal
     // handling.
-    GV->setConstant(DeclIsConstantGlobal(Context, D, false));
+    GV->setConstant(isTypeConstant(D->getType(), false));
=20
     // Set linkage and visibility in case we never see a definition.
     NamedDecl::LinkageInfo LV =3D D->getLinkageAndVisibility();
@@ -1280,19 +1312,19 @@
           return llvm::GlobalVariable::AvailableExternallyLinkage;
=20
         if (KeyFunction->isInlined())
-          return !Context.getLangOptions().AppleKext ?
+          return !Context.getLangOpts().AppleKext ?
                    llvm::GlobalVariable::LinkOnceODRLinkage :
                    llvm::Function::InternalLinkage;
        =20
         return llvm::GlobalVariable::ExternalLinkage;
        =20
       case TSK_ImplicitInstantiation:
-        return !Context.getLangOptions().AppleKext ?
+        return !Context.getLangOpts().AppleKext ?
                  llvm::GlobalVariable::LinkOnceODRLinkage :
                  llvm::Function::InternalLinkage;
=20
       case TSK_ExplicitInstantiationDefinition:
-        return !Context.getLangOptions().AppleKext ?
+        return !Context.getLangOpts().AppleKext ?
                  llvm::GlobalVariable::WeakODRLinkage :
                  llvm::Function::InternalLinkage;
  =20
@@ -1300,13 +1332,13 @@
         // FIXME: Use available_externally linkage. However, this currently
         // breaks LLVM's build due to undefined symbols.
         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
-        return !Context.getLangOptions().AppleKext ?
+        return !Context.getLangOpts().AppleKext ?
                  llvm::GlobalVariable::LinkOnceODRLinkage :
                  llvm::Function::InternalLinkage;
     }
   }
  =20
-  if (Context.getLangOptions().AppleKext)
+  if (Context.getLangOpts().AppleKext)
     return llvm::Function::InternalLinkage;
  =20
   switch (RD->getTemplateSpecializationKind()) {
@@ -1322,9 +1354,8 @@
   case TSK_ExplicitInstantiationDefinition:
       return llvm::GlobalVariable::WeakODRLinkage;
   }
- =20
-  // Silence GCC warning.
-  return llvm::GlobalVariable::LinkOnceODRLinkage;
+
+  llvm_unreachable("Invalid TemplateSpecializationKind!");
 }
=20
 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
@@ -1332,13 +1363,134 @@
       TheTargetData.getTypeStoreSizeInBits(Ty));
 }
=20
+llvm::Constant *
+CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl =
*D,
+                                                       const Expr *rawInit=
) {
+  ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
+  if (const ExprWithCleanups *withCleanups =3D
+          dyn_cast<ExprWithCleanups>(rawInit)) {
+    cleanups =3D withCleanups->getObjects();
+    rawInit =3D withCleanups->getSubExpr();
+  }
+
+  const InitListExpr *init =3D dyn_cast<InitListExpr>(rawInit);
+  if (!init || !init->initializesStdInitializerList() ||
+      init->getNumInits() =3D=3D 0)
+    return 0;
+
+  ASTContext &ctx =3D getContext();
+  unsigned numInits =3D init->getNumInits();
+  // FIXME: This check is here because we would otherwise silently miscomp=
ile
+  // nested global std::initializer_lists. Better would be to have a real
+  // implementation.
+  for (unsigned i =3D 0; i < numInits; ++i) {
+    const InitListExpr *inner =3D dyn_cast<InitListExpr>(init->getInit(i));
+    if (inner && inner->initializesStdInitializerList()) {
+      ErrorUnsupported(inner, "nested global std::initializer_list");
+      return 0;
+    }
+  }
+
+  // Synthesize a fake VarDecl for the array and initialize that.
+  QualType elementType =3D init->getInit(0)->getType();
+  llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
+  QualType arrayType =3D ctx.getConstantArrayType(elementType, numElements,
+                                                ArrayType::Normal, 0);
+
+  IdentifierInfo *name =3D &ctx.Idents.get(D->getNameAsString() + "__initl=
ist");
+  TypeSourceInfo *sourceInfo =3D ctx.getTrivialTypeSourceInfo(
+                                              arrayType, D->getLocation());
+  VarDecl *backingArray =3D VarDecl::Create(ctx, const_cast<DeclContext*>(
+                                                          D->getDeclContex=
t()),
+                                          D->getLocStart(), D->getLocation=
(),
+                                          name, arrayType, sourceInfo,
+                                          SC_Static, SC_Static);
+
+  // Now clone the InitListExpr to initialize the array instead.
+  // Incredible hack: we want to use the existing InitListExpr here, so we=
 need
+  // to tell it that it no longer initializes a std::initializer_list.
+  Expr *arrayInit =3D new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
+                                    const_cast<InitListExpr*>(init)->getIn=
its(),
+                                                   init->getNumInits(),
+                                                   init->getRBraceLoc());
+  arrayInit->setType(arrayType);
+
+  if (!cleanups.empty())
+    arrayInit =3D ExprWithCleanups::Create(ctx, arrayInit, cleanups);
+
+  backingArray->setInit(arrayInit);
+
+  // Emit the definition of the array.
+  EmitGlobalVarDefinition(backingArray);
+
+  // Inspect the initializer list to validate it and determine its type.
+  // FIXME: doing this every time is probably inefficient; caching would b=
e nice
+  RecordDecl *record =3D init->getType()->castAs<RecordType>()->getDecl();
+  RecordDecl::field_iterator field =3D record->field_begin();
+  if (field =3D=3D record->field_end()) {
+    ErrorUnsupported(D, "weird std::initializer_list");
+    return 0;
+  }
+  QualType elementPtr =3D ctx.getPointerType(elementType.withConst());
+  // Start pointer.
+  if (!ctx.hasSameType(field->getType(), elementPtr)) {
+    ErrorUnsupported(D, "weird std::initializer_list");
+    return 0;
+  }
+  ++field;
+  if (field =3D=3D record->field_end()) {
+    ErrorUnsupported(D, "weird std::initializer_list");
+    return 0;
+  }
+  bool isStartEnd =3D false;
+  if (ctx.hasSameType(field->getType(), elementPtr)) {
+    // End pointer.
+    isStartEnd =3D true;
+  } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
+    ErrorUnsupported(D, "weird std::initializer_list");
+    return 0;
+  }
+
+  // Now build an APValue representing the std::initializer_list.
+  APValue initListValue(APValue::UninitStruct(), 0, 2);
+  APValue &startField =3D initListValue.getStructField(0);
+  APValue::LValuePathEntry startOffsetPathEntry;
+  startOffsetPathEntry.ArrayIndex =3D 0;
+  startField =3D APValue(APValue::LValueBase(backingArray),
+                       CharUnits::fromQuantity(0),
+                       llvm::makeArrayRef(startOffsetPathEntry),
+                       /*IsOnePastTheEnd=3D*/false, 0);
+
+  if (isStartEnd) {
+    APValue &endField =3D initListValue.getStructField(1);
+    APValue::LValuePathEntry endOffsetPathEntry;
+    endOffsetPathEntry.ArrayIndex =3D numInits;
+    endField =3D APValue(APValue::LValueBase(backingArray),
+                       ctx.getTypeSizeInChars(elementType) * numInits,
+                       llvm::makeArrayRef(endOffsetPathEntry),
+                       /*IsOnePastTheEnd=3D*/true, 0);
+  } else {
+    APValue &sizeField =3D initListValue.getStructField(1);
+    sizeField =3D APValue(llvm::APSInt(numElements));
+  }
+
+  // Emit the constant for the initializer_list.
+  llvm::Constant *llvmInit =3D
+      EmitConstantValueForMemory(initListValue, D->getType());
+  assert(llvmInit && "failed to initialize as constant");
+  return llvmInit;
+}
+
 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
   llvm::Constant *Init =3D 0;
   QualType ASTTy =3D D->getType();
-  bool NonConstInit =3D false;
+  CXXRecordDecl *RD =3D ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordD=
ecl();
+  bool NeedsGlobalCtor =3D false;
+  bool NeedsGlobalDtor =3D RD && !RD->hasTrivialDestructor();
=20
-  const Expr *InitExpr =3D D->getAnyInitializer();
- =20
+  const VarDecl *InitDecl;
+  const Expr *InitExpr =3D D->getAnyInitializer(InitDecl);
+
   if (!InitExpr) {
     // This is a tentative definition; tentative definitions are
     // implicitly initialized with { 0 }.
@@ -1352,23 +1504,32 @@
     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
     Init =3D EmitNullConstant(D->getType());
   } else {
-    Init =3D EmitConstantExpr(InitExpr, D->getType());      =20
+    // If this is a std::initializer_list, emit the special initializer.
+    Init =3D MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
+    // An empty init list will perform zero-initialization, which happens
+    // to be exactly what we want.
+    // FIXME: It does so in a global constructor, which is *not* what we
+    // want.
+
+    if (!Init)
+      Init =3D EmitConstantInit(*InitDecl);
     if (!Init) {
       QualType T =3D InitExpr->getType();
       if (D->getType()->isReferenceType())
         T =3D D->getType();
-     =20
-      if (getLangOptions().CPlusPlus) {
+
+      if (getLangOpts().CPlusPlus) {
         Init =3D EmitNullConstant(T);
-        NonConstInit =3D true;
+        NeedsGlobalCtor =3D true;
       } else {
         ErrorUnsupported(D, "static initializer");
         Init =3D llvm::UndefValue::get(getTypes().ConvertType(T));
       }
     } else {
       // We don't need an initializer, so remove the entry for the delayed
-      // initializer position (just in case this entry was delayed).
-      if (getLangOptions().CPlusPlus)
+      // initializer position (just in case this entry was delayed) if we
+      // also don't need to register a destructor.
+      if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
         DelayedCXXInitPosition.erase(D);
     }
   }
@@ -1422,12 +1583,11 @@
   GV->setInitializer(Init);
=20
   // If it is safe to mark the global 'constant', do so now.
-  GV->setConstant(false);
-  if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
-    GV->setConstant(true);
+  GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
+                  isTypeConstant(D->getType(), true));
=20
   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
- =20
+
   // Set the llvm linkage type as appropriate.
   llvm::GlobalValue::LinkageTypes Linkage =3D=20
     GetLLVMLinkageVarDefinition(D, GV);
@@ -1439,8 +1599,8 @@
   SetCommonAttributes(D, GV);
=20
   // Emit the initializer function if necessary.
-  if (NonConstInit)
-    EmitCXXGlobalVarDeclInitFunc(D, GV);
+  if (NeedsGlobalCtor || NeedsGlobalDtor)
+    EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
=20
   // Emit global variable debug information.
   if (CGDebugInfo *DI =3D getModuleDebugInfo())
@@ -1465,7 +1625,7 @@
   } else if (Linkage =3D=3D GVA_TemplateInstantiation ||
              Linkage =3D=3D GVA_ExplicitTemplateInstantiation)
     return llvm::GlobalVariable::WeakODRLinkage;
-  else if (!getLangOptions().CPlusPlus &&=20
+  else if (!getLangOpts().CPlusPlus &&=20
            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
              D->getAttr<CommonAttr>()) &&
            !D->hasExternalStorage() && !D->getInit() &&
@@ -1565,16 +1725,20 @@
   }
 }
=20
+void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
+  TemplateSpecializationKind TSK =3D VD->getTemplateSpecializationKind();
+  // If we have a definition, this might be a deferred decl. If the
+  // instantiation is explicit, make sure we emit it at the end.
+  if (VD->getDefinition() && TSK =3D=3D TSK_ExplicitInstantiationDefinitio=
n)
+    GetAddrOfGlobalVar(VD);
+}
=20
 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
   const FunctionDecl *D =3D cast<FunctionDecl>(GD.getDecl());
=20
   // Compute the function info and LLVM type.
-  const CGFunctionInfo &FI =3D getTypes().getFunctionInfo(GD);
-  bool variadic =3D false;
-  if (const FunctionProtoType *fpt =3D D->getType()->getAs<FunctionProtoTy=
pe>())
-    variadic =3D fpt->isVariadic();
-  llvm::FunctionType *Ty =3D getTypes().GetFunctionType(FI, variadic);
+  const CGFunctionInfo &FI =3D getTypes().arrangeGlobalDeclaration(GD);
+  llvm::FunctionType *Ty =3D getTypes().GetFunctionType(FI);
=20
   // Get or create the prototype for the function.
   llvm::Constant *Entry =3D GetAddrOfFunction(GD, Ty);
@@ -1739,8 +1903,10 @@
     return Map.GetOrCreateValue(String);
   }
=20
-  // Otherwise, convert the UTF8 literals into a byte string.
-  SmallVector<UTF16, 128> ToBuf(NumBytes);
+  // Otherwise, convert the UTF8 literals into a string of shorts.
+  IsUTF16 =3D true;
+
+  SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
   const UTF8 *FromPtr =3D (UTF8 *)String.data();
   UTF16 *ToPtr =3D &ToBuf[0];
=20
@@ -1751,38 +1917,20 @@
   // ConvertUTF8toUTF16 returns the length in ToPtr.
   StringLength =3D ToPtr - &ToBuf[0];
=20
-  // Render the UTF-16 string into a byte array and convert to the target =
byte
-  // order.
-  //
-  // FIXME: This isn't something we should need to do here.
-  llvm::SmallString<128> AsBytes;
-  AsBytes.reserve(StringLength * 2);
-  for (unsigned i =3D 0; i !=3D StringLength; ++i) {
-    unsigned short Val =3D ToBuf[i];
-    if (TargetIsLSB) {
-      AsBytes.push_back(Val & 0xFF);
-      AsBytes.push_back(Val >> 8);
-    } else {
-      AsBytes.push_back(Val >> 8);
-      AsBytes.push_back(Val & 0xFF);
-    }
-  }
-  // Append one extra null character, the second is automatically added by=
 our
-  // caller.
-  AsBytes.push_back(0);
-
-  IsUTF16 =3D true;
-  return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
+  // Add an explicit null.
+  *ToPtr =3D 0;
+  return Map.
+    GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()=
),
+                               (StringLength + 1) * 2));
 }
=20
 static llvm::StringMapEntry<llvm::Constant*> &
 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
-		       const StringLiteral *Literal,
-		       unsigned &StringLength)
-{
-	StringRef String =3D Literal->getString();
-	StringLength =3D String.size();
-	return Map.GetOrCreateValue(String);
+                       const StringLiteral *Literal,
+                       unsigned &StringLength) {
+  StringRef String =3D Literal->getString();
+  StringLength =3D String.size();
+  return Map.GetOrCreateValue(String);
 }
=20
 llvm::Constant *
@@ -1797,8 +1945,7 @@
   if (llvm::Constant *C =3D Entry.getValue())
     return C;
=20
-  llvm::Constant *Zero =3D
-      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
+  llvm::Constant *Zero =3D llvm::Constant::getNullValue(Int32Ty);
   llvm::Constant *Zeros[] =3D { Zero, Zero };
=20
   // If we don't already have it, get __CFConstantStringClassReference.
@@ -1817,7 +1964,7 @@
   llvm::StructType *STy =3D
     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
=20
-  std::vector<llvm::Constant*> Fields(4);
+  llvm::Constant *Fields[4];
=20
   // Class pointer.
   Fields[0] =3D CFConstantStringClassRef;
@@ -1828,27 +1975,31 @@
     llvm::ConstantInt::get(Ty, 0x07C8);
=20
   // String pointer.
-  llvm::Constant *C =3D llvm::ConstantArray::get(VMContext, Entry.getKey()=
.str());
+  llvm::Constant *C =3D 0;
+  if (isUTF16) {
+    ArrayRef<uint16_t> Arr =3D
+      llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
+                                   Entry.getKey().size() / 2);
+    C =3D llvm::ConstantDataArray::get(VMContext, Arr);
+  } else {
+    C =3D llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
+  }
=20
   llvm::GlobalValue::LinkageTypes Linkage;
-  bool isConstant;
-  if (isUTF16) {
+  if (isUTF16)
     // FIXME: why do utf strings get "_" labels instead of "L" labels?
     Linkage =3D llvm::GlobalValue::InternalLinkage;
-    // Note: -fwritable-strings doesn't make unicode CFStrings writable, b=
ut
-    // does make plain ascii ones writable.
-    isConstant =3D true;
-  } else {
+  else
     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker e=
rror
     // when using private linkage. It is not clear if this is a bug in ld
     // or a reasonable new restriction.
     Linkage =3D llvm::GlobalValue::LinkerPrivateLinkage;
-    isConstant =3D !Features.WritableStrings;
-  }
  =20
+  // Note: -fwritable-strings doesn't make the backing store strings of
+  // CFStrings writable. (See <rdar://problem/10657500>)
   llvm::GlobalVariable *GV =3D
-    new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkag=
e, C,
-                             ".str");
+    new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=3D*/t=
rue,
+                             Linkage, C, ".str");
   GV->setUnnamedAddr(true);
   if (isUTF16) {
     CharUnits Align =3D getContext().getTypeAlignInChars(getContext().Shor=
tTy);
@@ -1857,8 +2008,14 @@
     CharUnits Align =3D getContext().getTypeAlignInChars(getContext().Char=
Ty);
     GV->setAlignment(Align.getQuantity());
   }
+
+  // String.
   Fields[2] =3D llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
=20
+  if (isUTF16)
+    // Cast the UTF16 string to the correct type.
+    Fields[2] =3D llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
+
   // String length.
   Ty =3D getTypes().ConvertType(getContext().LongTy);
   Fields[3] =3D llvm::ConstantInt::get(Ty, StringLength);
@@ -1879,7 +2036,7 @@
 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
                  DeclContext *DC, IdentifierInfo *Id) {
   SourceLocation Loc;
-  if (Ctx.getLangOptions().CPlusPlus)
+  if (Ctx.getLangOpts().CPlusPlus)
     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
   else
     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
@@ -1894,16 +2051,15 @@
   if (llvm::Constant *C =3D Entry.getValue())
     return C;
  =20
-  llvm::Constant *Zero =3D
-  llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
+  llvm::Constant *Zero =3D llvm::Constant::getNullValue(Int32Ty);
   llvm::Constant *Zeros[] =3D { Zero, Zero };
  =20
   // If we don't already have it, get _NSConstantStringClassReference.
   if (!ConstantStringClassRef) {
-    std::string StringClass(getLangOptions().ObjCConstantStringClass);
+    std::string StringClass(getLangOpts().ObjCConstantStringClass);
     llvm::Type *Ty =3D getTypes().ConvertType(getContext().IntTy);
     llvm::Constant *GV;
-    if (Features.ObjCNonFragileABI) {
+    if (LangOpts.ObjCNonFragileABI) {
       std::string str =3D=20
         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"=20
                             : "OBJC_CLASS_$_" + StringClass;
@@ -1958,18 +2114,19 @@
     NSConstantStringType =3D cast<llvm::StructType>(getTypes().ConvertType=
(NSTy));
   }
  =20
-  std::vector<llvm::Constant*> Fields(3);
+  llvm::Constant *Fields[3];
  =20
   // Class pointer.
   Fields[0] =3D ConstantStringClassRef;
  =20
   // String pointer.
-  llvm::Constant *C =3D llvm::ConstantArray::get(VMContext, Entry.getKey()=
.str());
+  llvm::Constant *C =3D
+    llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  =20
   llvm::GlobalValue::LinkageTypes Linkage;
   bool isConstant;
   Linkage =3D llvm::GlobalValue::PrivateLinkage;
-  isConstant =3D !Features.WritableStrings;
+  isConstant =3D !LangOpts.WritableStrings;
  =20
   llvm::GlobalVariable *GV =3D
   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage,=
 C,
@@ -1990,7 +2147,7 @@
                                 "_unnamed_nsstring_");
   // FIXME. Fix section.
   if (const char *Sect =3D=20
-        Features.ObjCNonFragileABI=20
+        LangOpts.ObjCNonFragileABI=20
           ? getContext().getTargetInfo().getNSStringNonFragileABISection()=20
           : getContext().getTargetInfo().getNSStringSection())
     GV->setSection(Sect);
@@ -2034,54 +2191,72 @@
   return ObjCFastEnumerationStateType;
 }
=20
-/// GetStringForStringLiteral - Return the appropriate bytes for a
-/// string literal, properly padded to match the literal type.
-std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *=
E) {
-  const ASTContext &Context =3D getContext();
-  const ConstantArrayType *CAT =3D
-    Context.getAsConstantArrayType(E->getType());
-  assert(CAT && "String isn't pointer or array!");
+llvm::Constant *
+CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
+  assert(!E->getType()->isPointerType() && "Strings are always arrays");
+ =20
+  // Don't emit it as the address of the string, emit the string data itse=
lf
+  // as an inline array.
+  if (E->getCharByteWidth() =3D=3D 1) {
+    SmallString<64> Str(E->getString());
=20
-  // Resize the string to the right size.
-  uint64_t RealLen =3D CAT->getSize().getZExtValue();
+    // Resize the string to the right size, which is indicated by its type.
+    const ConstantArrayType *CAT =3D Context.getAsConstantArrayType(E->get=
Type());
+    Str.resize(CAT->getSize().getZExtValue());
+    return llvm::ConstantDataArray::getString(VMContext, Str, false);
+  }
+ =20
+  llvm::ArrayType *AType =3D
+    cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
+  llvm::Type *ElemTy =3D AType->getElementType();
+  unsigned NumElements =3D AType->getNumElements();
=20
-  switch (E->getKind()) {
-  case StringLiteral::Ascii:
-  case StringLiteral::UTF8:
-    break;
-  case StringLiteral::Wide:
-    RealLen *=3D Context.getTargetInfo().getWCharWidth() / Context.getChar=
Width();
-    break;
-  case StringLiteral::UTF16:
-    RealLen *=3D Context.getTargetInfo().getChar16Width() / Context.getCha=
rWidth();
-    break;
-  case StringLiteral::UTF32:
-    RealLen *=3D Context.getTargetInfo().getChar32Width() / Context.getCha=
rWidth();
-    break;
+  // Wide strings have either 2-byte or 4-byte elements.
+  if (ElemTy->getPrimitiveSizeInBits() =3D=3D 16) {
+    SmallVector<uint16_t, 32> Elements;
+    Elements.reserve(NumElements);
+
+    for(unsigned i =3D 0, e =3D E->getLength(); i !=3D e; ++i)
+      Elements.push_back(E->getCodeUnit(i));
+    Elements.resize(NumElements);
+    return llvm::ConstantDataArray::get(VMContext, Elements);
   }
-
-  std::string Str =3D E->getString().str();
-  Str.resize(RealLen, '\0');
-
-  return Str;
+ =20
+  assert(ElemTy->getPrimitiveSizeInBits() =3D=3D 32);
+  SmallVector<uint32_t, 32> Elements;
+  Elements.reserve(NumElements);
+ =20
+  for(unsigned i =3D 0, e =3D E->getLength(); i !=3D e; ++i)
+    Elements.push_back(E->getCodeUnit(i));
+  Elements.resize(NumElements);
+  return llvm::ConstantDataArray::get(VMContext, Elements);
 }
=20
 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
 /// constant array for the given string literal.
 llvm::Constant *
 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
-  // FIXME: This can be more efficient.
-  // FIXME: We shouldn't need to bitcast the constant in the wide string c=
ase.
   CharUnits Align =3D getContext().getTypeAlignInChars(S->getType());
-  llvm::Constant *C =3D GetAddrOfConstantString(GetStringForStringLiteral(=
S),
-                                              /* GlobalName */ 0,
-                                              Align.getQuantity());
-  if (S->isWide() || S->isUTF16() || S->isUTF32()) {
-    llvm::Type *DestTy =3D
-        llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
-    C =3D llvm::ConstantExpr::getBitCast(C, DestTy);
+  if (S->isAscii() || S->isUTF8()) {
+    SmallString<64> Str(S->getString());
+   =20
+    // Resize the string to the right size, which is indicated by its type.
+    const ConstantArrayType *CAT =3D Context.getAsConstantArrayType(S->get=
Type());
+    Str.resize(CAT->getSize().getZExtValue());
+    return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantit=
y());
   }
-  return C;
+
+  // FIXME: the following does not memoize wide strings.
+  llvm::Constant *C =3D GetConstantArrayFromStringLiteral(S);
+  llvm::GlobalVariable *GV =3D
+    new llvm::GlobalVariable(getModule(),C->getType(),
+                             !LangOpts.WritableStrings,
+                             llvm::GlobalValue::PrivateLinkage,
+                             C,".str");
+
+  GV->setAlignment(Align.getQuantity());
+  GV->setUnnamedAddr(true);
+  return GV;
 }
=20
 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
@@ -2103,7 +2278,7 @@
                                              unsigned Alignment) {
   // Create Constant for this string literal. Don't add a '\0'.
   llvm::Constant *C =3D
-      llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
+      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
=20
   // Create a global variable for this string
   llvm::GlobalVariable *GV =3D
@@ -2126,14 +2301,12 @@
 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
                                                        const char *GlobalN=
ame,
                                                        unsigned Alignment)=
 {
-  bool IsConstant =3D !Features.WritableStrings;
-
   // Get the default prefix if a name wasn't specified.
   if (!GlobalName)
     GlobalName =3D ".str";
=20
   // Don't share any string literals if strings aren't constant.
-  if (!IsConstant)
+  if (LangOpts.WritableStrings)
     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
=20
   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =3D
@@ -2147,7 +2320,8 @@
   }
=20
   // Create a global variable for this.
-  llvm::GlobalVariable *GV =3D GenerateStringLiteral(Str, true, *this, Glo=
balName, Alignment);
+  llvm::GlobalVariable *GV =3D GenerateStringLiteral(Str, true, *this, Glo=
balName,
+                                                   Alignment);
   Entry.setValue(GV);
   return GV;
 }
@@ -2308,6 +2482,7 @@
   case Decl::TypeAliasTemplate:
   case Decl::NamespaceAlias:
   case Decl::Block:
+  case Decl::Import:
     break;
   case Decl::CXXConstructor:
     // Skip function templates
@@ -2330,8 +2505,6 @@
   // Objective-C Decls
=20
   // Forward declarations, no (immediate) code generation.
-  case Decl::ObjCClass:
-  case Decl::ObjCForwardProtocol:
   case Decl::ObjCInterface:
     break;
  =20
@@ -2342,10 +2515,13 @@
     break;
   }
=20
-  case Decl::ObjCProtocol:
-    ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
+  case Decl::ObjCProtocol: {
+    ObjCProtocolDecl *Proto =3D cast<ObjCProtocolDecl>(D);
+    if (Proto->isThisDeclarationADefinition())
+      ObjCRuntime->GenerateProtocol(Proto);
     break;
-
+  }
+     =20
   case Decl::ObjCCategoryImpl:
     // Categories have properties but don't support synthesize so we
     // can ignore them here.
@@ -2354,11 +2530,16 @@
=20
   case Decl::ObjCImplementation: {
     ObjCImplementationDecl *OMD =3D cast<ObjCImplementationDecl>(D);
-    if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
+    if (LangOpts.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
       Context.ResetObjCLayout(OMD->getClassInterface());
     EmitObjCPropertyImplementations(OMD);
     EmitObjCIvarInitializations(OMD);
     ObjCRuntime->GenerateClass(OMD);
+    // Emit global variable debug information.
+    if (CGDebugInfo *DI =3D getModuleDebugInfo())
+      DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->=
getClassInterface()),
+				   OMD->getLocation());
+   =20
     break;
   }
   case Decl::ObjCMethod: {
@@ -2369,7 +2550,7 @@
     break;
   }
   case Decl::ObjCCompatibleAlias:
-    // compatibility-alias is a directive and has no code gen.
+    ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
     break;
=20
   case Decl::LinkageSpec:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenModule.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenModule.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -26,7 +26,6 @@
 #include "llvm/Module.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/StringMap.h"
-#include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/ValueHandle.h"
=20
@@ -56,6 +55,7 @@
   class Decl;
   class Expr;
   class Stmt;
+  class InitListExpr;
   class StringLiteral;
   class NamedDecl;
   class ValueDecl;
@@ -103,8 +103,10 @@
     /// void
     llvm::Type *VoidTy;
=20
-    /// i8, i32, and i64
-    llvm::IntegerType *Int8Ty, *Int32Ty, *Int64Ty;
+    /// i8, i16, i32, and i64
+    llvm::IntegerType *Int8Ty, *Int16Ty, *Int32Ty, *Int64Ty;
+    /// float, double
+    llvm::Type *FloatTy, *DoubleTy;
=20
     /// int
     llvm::IntegerType *IntTy;
@@ -213,7 +215,7 @@
   typedef std::vector<std::pair<llvm::Constant*, int> > CtorList;
=20
   ASTContext &Context;
-  const LangOptions &Features;
+  const LangOptions &LangOpts;
   const CodeGenOptions &CodeGenOpts;
   llvm::Module &TheModule;
   const llvm::TargetData &TheTargetData;
@@ -232,6 +234,7 @@
   CGCUDARuntime* CUDARuntime;
   CGDebugInfo* DebugInfo;
   ARCEntrypoints *ARCData;
+  llvm::MDNode *NoObjCARCExceptionsMetadata;
   RREntrypoints *RRData;
=20
   // WeakRefReferences - A set of references that have only been seen via
@@ -276,7 +279,11 @@
=20
   llvm::StringMap<llvm::Constant*> CFConstantStringMap;
   llvm::StringMap<llvm::GlobalVariable*> ConstantStringMap;
-  llvm::DenseMap<const Decl*, llvm::Value*> StaticLocalDeclMap;
+  llvm::DenseMap<const Decl*, llvm::Constant *> StaticLocalDeclMap;
+  llvm::DenseMap<const Decl*, llvm::GlobalVariable*> StaticLocalDeclGuardM=
ap;
+ =20
+  llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
+  llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
=20
   /// CXXGlobalInits - Global variables with initializers that need to run
   /// before main.
@@ -324,7 +331,7 @@
   void createOpenCLRuntime();
   void createCUDARuntime();
=20
-  bool isTriviallyRecursiveViaAsm(const FunctionDecl *F);
+  bool isTriviallyRecursive(const FunctionDecl *F);
   bool shouldEmitFunction(const FunctionDecl *F);
   llvm::LLVMContext &VMContext;
=20
@@ -382,7 +389,7 @@
   CGCXXABI &getCXXABI() { return ABI; }
=20
   ARCEntrypoints &getARCEntrypoints() const {
-    assert(getLangOptions().ObjCAutoRefCount && ARCData !=3D 0);
+    assert(getLangOpts().ObjCAutoRefCount && ARCData !=3D 0);
     return *ARCData;
   }
=20
@@ -391,19 +398,51 @@
     return *RRData;
   }
=20
-  llvm::Value *getStaticLocalDeclAddress(const VarDecl *VD) {
-    return StaticLocalDeclMap[VD];
+  llvm::Constant *getStaticLocalDeclAddress(const VarDecl *D) {
+    return StaticLocalDeclMap[D];
   }
   void setStaticLocalDeclAddress(const VarDecl *D,=20
-                             llvm::GlobalVariable *GV) {
-    StaticLocalDeclMap[D] =3D GV;
+                                 llvm::Constant *C) {
+    StaticLocalDeclMap[D] =3D C;
+  }
+
+  llvm::GlobalVariable *getStaticLocalDeclGuardAddress(const VarDecl *D) {
+    return StaticLocalDeclGuardMap[D];
+  }
+  void setStaticLocalDeclGuardAddress(const VarDecl *D,=20
+                                      llvm::GlobalVariable *C) {
+    StaticLocalDeclGuardMap[D] =3D C;
+  }
+
+  llvm::Constant *getAtomicSetterHelperFnMap(QualType Ty) {
+    return AtomicSetterHelperFnMap[Ty];
+  }
+  void setAtomicSetterHelperFnMap(QualType Ty,
+                            llvm::Constant *Fn) {
+    AtomicSetterHelperFnMap[Ty] =3D Fn;
+  }
+
+  llvm::Constant *getAtomicGetterHelperFnMap(QualType Ty) {
+    return AtomicGetterHelperFnMap[Ty];
+  }
+  void setAtomicGetterHelperFnMap(QualType Ty,
+                            llvm::Constant *Fn) {
+    AtomicGetterHelperFnMap[Ty] =3D Fn;
   }
=20
   CGDebugInfo *getModuleDebugInfo() { return DebugInfo; }
=20
+  llvm::MDNode *getNoObjCARCExceptionsMetadata() {
+    if (!NoObjCARCExceptionsMetadata)
+      NoObjCARCExceptionsMetadata =3D
+        llvm::MDNode::get(getLLVMContext(),
+                          SmallVector<llvm::Value*,1>());
+    return NoObjCARCExceptionsMetadata;
+  }
+
   ASTContext &getContext() const { return Context; }
   const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
-  const LangOptions &getLangOptions() const { return Features; }
+  const LangOptions &getLangOpts() const { return LangOpts; }
   llvm::Module &getModule() const { return TheModule; }
   CodeGenTypes &getTypes() { return Types; }
   CodeGenVTables &getVTables() { return VTables; }
@@ -418,6 +457,9 @@
   bool shouldUseTBAA() const { return TBAA !=3D 0; }
=20
   llvm::MDNode *getTBAAInfo(QualType QTy);
+  llvm::MDNode *getTBAAInfoForVTablePtr();
+
+  bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor);
=20
   static void DecorateInstruction(llvm::Instruction *Inst,
                                   llvm::MDNode *TBAAInfo);
@@ -451,7 +493,6 @@
     case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibilit=
y;
     }
     llvm_unreachable("unknown visibility!");
-    return llvm::GlobalValue::DefaultVisibility;
   }
=20
   llvm::Constant *GetAddrOfGlobal(GlobalDecl GD) {
@@ -551,11 +592,6 @@
   /// requires no captures.
   llvm::Constant *GetAddrOfGlobalBlock(const BlockExpr *BE, const char *);
  =20
-  /// GetStringForStringLiteral - Return the appropriate bytes for a string
-  /// literal, properly padded to match the literal type. If only the addr=
ess of
-  /// a constant is needed consider using GetAddrOfConstantStringLiteral.
-  std::string GetStringForStringLiteral(const StringLiteral *E);
-
   /// GetAddrOfConstantCFString - Return a pointer to a constant CFString =
object
   /// for the given string.
   llvm::Constant *GetAddrOfConstantCFString(const StringLiteral *Literal);
@@ -565,6 +601,10 @@
   /// -fconstant-string-class=3Dclass_name option.
   llvm::Constant *GetAddrOfConstantString(const StringLiteral *Literal);
=20
+  /// GetConstantArrayFromStringLiteral - Return a constant array for the =
given
+  /// string.
+  llvm::Constant *GetConstantArrayFromStringLiteral(const StringLiteral *E=
);
+
   /// GetAddrOfConstantStringFromLiteral - Return a pointer to a constant =
array
   /// for the given string literal.
   llvm::Constant *GetAddrOfConstantStringFromLiteral(const StringLiteral *=
S);
@@ -596,6 +636,10 @@
   llvm::Constant *GetAddrOfConstantCString(const std::string &str,
                                            const char *GlobalName=3D0,
                                            unsigned Alignment=3D1);
+
+  /// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant g=
lobal
+  /// variable for the given file-scope compound literal expression.
+  llvm::Constant *GetAddrOfConstantCompoundLiteral(const CompoundLiteralEx=
pr*E);
  =20
   /// \brief Retrieve the record type that describes the state of an
   /// Objective-C fast enumeration loop (for..in).
@@ -624,6 +668,10 @@
   /// EmitTopLevelDecl - Emit code for a single top level declaration.
   void EmitTopLevelDecl(Decl *D);
=20
+  /// HandleCXXStaticMemberVarInstantiation - Tell the consumer that this
+  // variable has been instantiated.
+  void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
+
   /// AddUsedGlobal - Add a global which should be forced to be
   /// present in the object file; these are emitted to the llvm.used
   /// metadata global.
@@ -661,12 +709,28 @@
=20
   llvm::Constant *getMemberPointerConstant(const UnaryOperator *e);
=20
+  /// EmitConstantInit - Try to emit the initializer for the given declara=
tion
+  /// as a constant; returns 0 if the expression cannot be emitted as a
+  /// constant.
+  llvm::Constant *EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF =
=3D 0);
+
   /// EmitConstantExpr - Try to emit the given expression as a
   /// constant; returns 0 if the expression cannot be emitted as a
   /// constant.
   llvm::Constant *EmitConstantExpr(const Expr *E, QualType DestType,
                                    CodeGenFunction *CGF =3D 0);
=20
+  /// EmitConstantValue - Emit the given constant value as a constant, in =
the
+  /// type's scalar representation.
+  llvm::Constant *EmitConstantValue(const APValue &Value, QualType DestTyp=
e,
+                                    CodeGenFunction *CGF =3D 0);
+
+  /// EmitConstantValueForMemory - Emit the given constant value as a cons=
tant,
+  /// in the type's memory representation.
+  llvm::Constant *EmitConstantValueForMemory(const APValue &Value,
+                                             QualType DestType,
+                                             CodeGenFunction *CGF =3D 0);
+
   /// EmitNullConstant - Return the result of value-initializing the given
   /// type, i.e. a null expression of the given type.  This is usually,
   /// but not always, an LLVM null constant.
@@ -715,10 +779,14 @@
   /// as a return type.
   bool ReturnTypeUsesSRet(const CGFunctionInfo &FI);
=20
-  /// ReturnTypeUsesSret - Return true iff the given type uses 'fpret' whe=
n used
-  /// as a return type.
+  /// ReturnTypeUsesFPRet - Return true iff the given type uses 'fpret' wh=
en
+  /// used as a return type.
   bool ReturnTypeUsesFPRet(QualType ResultType);
=20
+  /// ReturnTypeUsesFP2Ret - Return true iff the given type uses 'fp2ret' =
when
+  /// used as a return type.
+  bool ReturnTypeUsesFP2Ret(QualType ResultType);
+
   /// ConstructAttributeList - Get the LLVM attributes and calling convent=
ion to
   /// use for a particular function type.
   ///
@@ -830,6 +898,8 @@
=20
   void EmitGlobalFunctionDefinition(GlobalDecl GD);
   void EmitGlobalVarDefinition(const VarDecl *D);
+  llvm::Constant *MaybeEmitGlobalStdInitializerListInitializer(const VarDe=
cl *D,
+                                                              const Expr *=
init);
   void EmitAliasDefinition(GlobalDecl GD);
   void EmitObjCPropertyImplementations(const ObjCImplementationDecl *D);
   void EmitObjCIvarInitializations(ObjCImplementationDecl *D);
@@ -864,8 +934,11 @@
   /// EmitCXXGlobalDtorFunc - Emit the function that destroys C++ globals.
   void EmitCXXGlobalDtorFunc();
=20
+  /// EmitCXXGlobalVarDeclInitFunc - Emit the function that initializes the
+  /// specified global (if PerformInit is true) and registers its destruct=
or.
   void EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
-                                    llvm::GlobalVariable *Addr);
+                                    llvm::GlobalVariable *Addr,
+                                    bool PerformInit);
=20
   // FIXME: Hardcoding priority here is gross.
   void AddGlobalCtor(llvm::Function *Ctor, int Priority=3D65535);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenTBAA.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTBAA.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTBAA.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -169,7 +169,7 @@
=20
     // TODO: This is using the RTTI name. Is there a better way to get
     // a unique string for a type?
-    llvm::SmallString<256> OutName;
+    SmallString<256> OutName;
     llvm::raw_svector_ostream Out(OutName);
     MContext.mangleCXXRTTIName(QualType(ETy, 0), Out);
     Out.flush();
@@ -179,3 +179,7 @@
   // For now, handle any other kind of type conservatively.
   return MetadataCache[Ty] =3D getChar();
 }
+
+llvm::MDNode *CodeGenTBAA::getTBAAInfoForVTablePtr() {
+  return getTBAAInfoForNamedType("vtable pointer", getRoot());
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenTBAA.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTBAA.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTBAA.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -68,6 +68,10 @@
   /// getTBAAInfo - Get the TBAA MDNode to be used for a dereference
   /// of the given type.
   llvm::MDNode *getTBAAInfo(QualType QTy);
+
+  /// getTBAAInfoForVTablePtr - Get the TBAA MDNode to be used for a
+  /// dereference of a vtable pointer.
+  llvm::MDNode *getTBAAInfoForVTablePtr();
 };
=20
 }  // end namespace CodeGen
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenTypes.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #include "CGCall.h"
 #include "CGCXXABI.h"
 #include "CGRecordLayout.h"
+#include "TargetInfo.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclCXX.h"
@@ -26,11 +27,12 @@
 using namespace clang;
 using namespace CodeGen;
=20
-CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M,
-                           const llvm::TargetData &TD, const ABIInfo &Info,
-                           CGCXXABI &CXXABI, const CodeGenOptions &CGO)
-  : Context(Ctx), Target(Ctx.getTargetInfo()), TheModule(M), TheTargetData=
(TD),
-    TheABIInfo(Info), TheCXXABI(CXXABI), CodeGenOpts(CGO) {
+CodeGenTypes::CodeGenTypes(CodeGenModule &CGM)
+  : Context(CGM.getContext()), Target(Context.getTargetInfo()),
+    TheModule(CGM.getModule()), TheTargetData(CGM.getTargetData()),
+    TheABIInfo(CGM.getTargetCodeGenInfo().getABIInfo()),
+    TheCXXABI(CGM.getCXXABI()),
+    CodeGenOpts(CGM.getCodeGenOpts()), CGM(CGM) {
   SkippedLayout =3D false;
 }
=20
@@ -48,7 +50,7 @@
 void CodeGenTypes::addRecordTypeName(const RecordDecl *RD,
                                      llvm::StructType *Ty,
                                      StringRef suffix) {
-  llvm::SmallString<256> TypeName;
+  SmallString<256> TypeName;
   llvm::raw_svector_ostream OS(TypeName);
   OS << RD->getKindName() << '.';
  =20
@@ -193,11 +195,9 @@
   // If this isn't a tagged type, we can convert it!
   const TagType *TT =3D Ty->getAs<TagType>();
   if (TT =3D=3D 0) return true;
- =20
- =20
-  // If it's a tagged type used by-value, but is just a forward decl, we c=
an't
-  // convert it.  Note that getDefinition()=3D=3D0 is not the same as !isD=
efinition.
-  if (TT->getDecl()->getDefinition() =3D=3D 0)
+   =20
+  // Incomplete types cannot be converted.
+  if (TT->isIncompleteType())
     return false;
  =20
   // If this is an enum, then it is always safe to convert.
@@ -305,7 +305,6 @@
 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
 #include "clang/AST/TypeNodes.def"
     llvm_unreachable("Non-canonical or dependent types aren't possible.");
-    break;
=20
   case Type::Builtin: {
     switch (cast<BuiltinType>(Ty)->getKind()) {
@@ -368,12 +367,12 @@
       ResultType =3D llvm::IntegerType::get(getLLVMContext(), 128);
       break;
    =20
-    case BuiltinType::Overload:
     case BuiltinType::Dependent:
-    case BuiltinType::BoundMember:
-    case BuiltinType::UnknownAny:
+#define BUILTIN_TYPE(Id, SingletonId)
+#define PLACEHOLDER_TYPE(Id, SingletonId) \
+    case BuiltinType::Id:
+#include "clang/AST/BuiltinTypes.def"
       llvm_unreachable("Unexpected placeholder builtin type!");
-      break;
     }
     break;
   }
@@ -474,16 +473,13 @@
     // The function type can be built; call the appropriate routines to
     // build it.
     const CGFunctionInfo *FI;
-    bool isVariadic;
     if (const FunctionProtoType *FPT =3D dyn_cast<FunctionProtoType>(FT)) {
-      FI =3D &getFunctionInfo(
+      FI =3D &arrangeFunctionType(
                    CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, =
0)));
-      isVariadic =3D FPT->isVariadic();
     } else {
       const FunctionNoProtoType *FNPT =3D cast<FunctionNoProtoType>(FT);
-      FI =3D &getFunctionInfo(
+      FI =3D &arrangeFunctionType(
                 CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, =
0)));
-      isVariadic =3D true;
     }
    =20
     // If there is something higher level prodding our CGFunctionInfo, then
@@ -495,7 +491,7 @@
     } else {
=20
       // Otherwise, we're good to go, go ahead and convert it.
-      ResultType =3D GetFunctionType(*FI, isVariadic);
+      ResultType =3D GetFunctionType(*FI);
     }
=20
     RecordsBeingLaidOut.erase(Ty);
@@ -560,7 +556,7 @@
   }
=20
   case Type::Atomic: {
-    ResultType =3D ConvertTypeForMem(cast<AtomicType>(Ty)->getValueType());
+    ResultType =3D ConvertType(cast<AtomicType>(Ty)->getValueType());
     break;
   }
   }
@@ -655,7 +651,7 @@
=20
 bool CodeGenTypes::isZeroInitializable(QualType T) {
   // No need to check for member pointers when not compiling C++.
-  if (!Context.getLangOptions().CPlusPlus)
+  if (!Context.getLangOpts().CPlusPlus)
     return true;
  =20
   T =3D Context.getBaseElementType(T);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/CodeGenTypes.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.h	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/CodeGenTypes.h	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -52,10 +52,13 @@
 namespace CodeGen {
   class CGCXXABI;
   class CGRecordLayout;
+  class CodeGenModule;
+  class RequiredArgs;
=20
 /// CodeGenTypes - This class organizes the cross-module state that is used
 /// while lowering AST types to LLVM types.
 class CodeGenTypes {
+  // Some of this stuff should probably be left on the CGM.
   ASTContext &Context;
   const TargetInfo &Target;
   llvm::Module &TheModule;
@@ -63,6 +66,7 @@
   const ABIInfo &TheABIInfo;
   CGCXXABI &TheCXXABI;
   const CodeGenOptions &CodeGenOpts;
+  CodeGenModule &CGM;
=20
   /// The opaque type map for Objective-C interfaces. All direct
   /// manipulation is done by the runtime interfaces, which are
@@ -101,9 +105,7 @@
   llvm::DenseMap<const Type *, llvm::Type *> TypeCache;
=20
 public:
-  CodeGenTypes(ASTContext &Ctx, llvm::Module &M, const llvm::TargetData &T=
D,
-               const ABIInfo &Info, CGCXXABI &CXXABI,
-               const CodeGenOptions &Opts);
+  CodeGenTypes(CodeGenModule &CGM);
   ~CodeGenTypes();
=20
   const llvm::TargetData &getTargetData() const { return TheTargetData; }
@@ -124,8 +126,7 @@
   llvm::Type *ConvertTypeForMem(QualType T);
=20
   /// GetFunctionType - Get the LLVM function type for \arg Info.
-  llvm::FunctionType *GetFunctionType(const CGFunctionInfo &Info,
-                                      bool IsVariadic);
+  llvm::FunctionType *GetFunctionType(const CGFunctionInfo &Info);
=20
   llvm::FunctionType *GetFunctionType(GlobalDecl GD);
=20
@@ -148,50 +149,66 @@
=20
   /// getNullaryFunctionInfo - Get the function info for a void()
   /// function with standard CC.
-  const CGFunctionInfo &getNullaryFunctionInfo();
+  const CGFunctionInfo &arrangeNullaryFunction();
=20
-  /// getFunctionInfo - Get the function info for the specified function d=
ecl.
-  const CGFunctionInfo &getFunctionInfo(GlobalDecl GD);
+  // The arrangement methods are split into three families:
+  //   - those meant to drive the signature and prologue/epilogue
+  //     of a function declaration or definition,
+  //   - those meant for the computation of the LLVM type for an abstract
+  //     appearance of a function, and
+  //   - those meant for performing the IR-generation of a call.
+  // They differ mainly in how they deal with optional (i.e. variadic)
+  // arguments, as well as unprototyped functions.
+  //
+  // Key points:
+  // - The CGFunctionInfo for emitting a specific call site must include
+  //   entries for the optional arguments.
+  // - The function type used at the call site must reflect the formal
+  //   signature of the declaration being called, or else the call will
+  //   go awry.
+  // - For the most part, unprototyped functions are called by casting to
+  //   a formal signature inferred from the specific argument types used
+  //   at the call-site.  However, some targets (e.g. x86-64) screw with
+  //   this for compatibility reasons.
=20
-  const CGFunctionInfo &getFunctionInfo(const FunctionDecl *FD);
-  const CGFunctionInfo &getFunctionInfo(const CXXMethodDecl *MD);
-  const CGFunctionInfo &getFunctionInfo(const ObjCMethodDecl *MD);
-  const CGFunctionInfo &getFunctionInfo(const CXXConstructorDecl *D,
-                                        CXXCtorType Type);
-  const CGFunctionInfo &getFunctionInfo(const CXXDestructorDecl *D,
-                                        CXXDtorType Type);
+  const CGFunctionInfo &arrangeGlobalDeclaration(GlobalDecl GD);
+  const CGFunctionInfo &arrangeFunctionDeclaration(const FunctionDecl *FD);
+  const CGFunctionInfo &arrangeFunctionDeclaration(QualType ResTy,
+                                                   const FunctionArgList &=
Args,
+                                             const FunctionType::ExtInfo &=
Info,
+                                                   bool isVariadic);
=20
-  const CGFunctionInfo &getFunctionInfo(const CallArgList &Args,
-                                        const FunctionType *Ty) {
-    return getFunctionInfo(Ty->getResultType(), Args,
-                           Ty->getExtInfo());
-  }
+  const CGFunctionInfo &arrangeObjCMethodDeclaration(const ObjCMethodDecl =
*MD);
+  const CGFunctionInfo &arrangeObjCMessageSendSignature(const ObjCMethodDe=
cl *MD,
+                                                        QualType receiverT=
ype);
=20
-  const CGFunctionInfo &getFunctionInfo(CanQual<FunctionProtoType> Ty);
-  const CGFunctionInfo &getFunctionInfo(CanQual<FunctionNoProtoType> Ty);
+  const CGFunctionInfo &arrangeCXXMethodDeclaration(const CXXMethodDecl *M=
D);
+  const CGFunctionInfo &arrangeCXXConstructorDeclaration(
+                                                    const CXXConstructorDe=
cl *D,
+                                                    CXXCtorType Type);
+  const CGFunctionInfo &arrangeCXXDestructor(const CXXDestructorDecl *D,
+                                             CXXDtorType Type);
=20
-  /// getFunctionInfo - Get the function info for a member function of
-  /// the given type.  This is used for calls through member function
-  /// pointers.
-  const CGFunctionInfo &getFunctionInfo(const CXXRecordDecl *RD,
-                                        const FunctionProtoType *FTP);
+  const CGFunctionInfo &arrangeFunctionCall(const CallArgList &Args,
+                                            const FunctionType *Ty);
+  const CGFunctionInfo &arrangeFunctionCall(QualType ResTy,
+                                            const CallArgList &args,
+                                            const FunctionType::ExtInfo &i=
nfo,
+                                            RequiredArgs required);
=20
-  /// getFunctionInfo - Get the function info for a function described by a
-  /// return type and argument types. If the calling convention is not
-  /// specified, the "C" calling convention will be used.
-  const CGFunctionInfo &getFunctionInfo(QualType ResTy,
-                                        const CallArgList &Args,
-                                        const FunctionType::ExtInfo &Info);
-  const CGFunctionInfo &getFunctionInfo(QualType ResTy,
-                                        const FunctionArgList &Args,
-                                        const FunctionType::ExtInfo &Info);
+  const CGFunctionInfo &arrangeFunctionType(CanQual<FunctionProtoType> Ty);
+  const CGFunctionInfo &arrangeFunctionType(CanQual<FunctionNoProtoType> T=
y);
+  const CGFunctionInfo &arrangeCXXMethodType(const CXXRecordDecl *RD,
+                                             const FunctionProtoType *FTP);
=20
   /// Retrieves the ABI information for the given function signature.
+  /// This is the "core" routine to which all the others defer.
   ///
-  /// \param ArgTys - must all actually be canonical as params
-  const CGFunctionInfo &getFunctionInfo(CanQualType RetTy,
-                               const SmallVectorImpl<CanQualType> &ArgTys,
-                                        const FunctionType::ExtInfo &Info);
+  /// \param argTypes - must all actually be canonical as params
+  const CGFunctionInfo &arrangeFunctionType(CanQualType returnType,
+                                            ArrayRef<CanQualType> argTypes,
+                                            const FunctionType::ExtInfo &i=
nfo,
+                                            RequiredArgs args);
=20
   /// \brief Compute a new LLVM record layout object for the given record.
   CGRecordLayout *ComputeRecordLayout(const RecordDecl *D,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/ItaniumCXXABI.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/ItaniumCXXABI.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -73,15 +73,17 @@
   llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
                                            const CastExpr *E,
                                            llvm::Value *Src);
-
-  llvm::Constant *EmitMemberPointerConversion(llvm::Constant *C,
-                                              const CastExpr *E);
+  llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
+                                              llvm::Constant *Src);
=20
   llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
=20
   llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
   llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
                                         CharUnits offset);
+  llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
+  llvm::Constant *BuildMemberPointer(const CXXMethodDecl *MD,
+                                     CharUnits ThisAdjustment);
=20
   llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
                                            llvm::Value *L,
@@ -121,7 +123,7 @@
                        llvm::Value *&AllocPtr, CharUnits &CookieSize);
=20
   void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
-                       llvm::GlobalVariable *DeclPtr);
+                       llvm::GlobalVariable *DeclPtr, bool PerformInit);
 };
=20
 class ARMCXXABI : public ItaniumCXXABI {
@@ -216,8 +218,8 @@
     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
=20
   llvm::FunctionType *FTy =3D=20
-    CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT),
-                                   FPT->isVariadic());
+    CGM.getTypes().GetFunctionType(
+      CGM.getTypes().arrangeCXXMethodType(RD, FPT));
=20
   llvm::IntegerType *ptrdiff =3D getPtrDiffTy();
   llvm::Constant *ptrdiff_1 =3D llvm::ConstantInt::get(ptrdiff, 1);
@@ -312,7 +314,10 @@
   return Builder.CreateBitCast(Addr, PType);
 }
=20
-/// Perform a derived-to-base or base-to-derived member pointer conversion.
+/// Perform a bitcast, derived-to-base, or base-to-derived member pointer
+/// conversion.
+///
+/// Bitcast conversions are always a no-op under Itanium.
 ///
 /// Obligatory offset/adjustment diagram:
 ///         <-- offset -->          <-- adjustment -->
@@ -335,146 +340,106 @@
 llvm::Value *
 ItaniumCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
                                            const CastExpr *E,
-                                           llvm::Value *Src) {
+                                           llvm::Value *src) {
   assert(E->getCastKind() =3D=3D CK_DerivedToBaseMemberPointer ||
-         E->getCastKind() =3D=3D CK_BaseToDerivedMemberPointer);
+         E->getCastKind() =3D=3D CK_BaseToDerivedMemberPointer ||
+         E->getCastKind() =3D=3D CK_ReinterpretMemberPointer);
=20
-  if (isa<llvm::Constant>(Src))
-    return EmitMemberPointerConversion(cast<llvm::Constant>(Src), E);
+  // Under Itanium, reinterprets don't require any additional processing.
+  if (E->getCastKind() =3D=3D CK_ReinterpretMemberPointer) return src;
+
+  // Use constant emission if we can.
+  if (isa<llvm::Constant>(src))
+    return EmitMemberPointerConversion(E, cast<llvm::Constant>(src));
+
+  llvm::Constant *adj =3D getMemberPointerAdjustment(E);
+  if (!adj) return src;
=20
   CGBuilderTy &Builder =3D CGF.Builder;
+  bool isDerivedToBase =3D (E->getCastKind() =3D=3D CK_DerivedToBaseMember=
Pointer);
=20
-  const MemberPointerType *SrcTy =3D
-    E->getSubExpr()->getType()->getAs<MemberPointerType>();
-  const MemberPointerType *DestTy =3D E->getType()->getAs<MemberPointerTyp=
e>();
-
-  const CXXRecordDecl *SrcDecl =3D SrcTy->getClass()->getAsCXXRecordDecl();
-  const CXXRecordDecl *DestDecl =3D DestTy->getClass()->getAsCXXRecordDecl=
();
-
-  bool DerivedToBase =3D
-    E->getCastKind() =3D=3D CK_DerivedToBaseMemberPointer;
-
-  const CXXRecordDecl *DerivedDecl;
-  if (DerivedToBase)
-    DerivedDecl =3D SrcDecl;
-  else
-    DerivedDecl =3D DestDecl;
-
-  llvm::Constant *Adj =3D=20
-    CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
-                                         E->path_begin(),
-                                         E->path_end());
-  if (!Adj) return Src;
+  const MemberPointerType *destTy =3D
+    E->getType()->castAs<MemberPointerType>();
=20
   // For member data pointers, this is just a matter of adding the
   // offset if the source is non-null.
-  if (SrcTy->isMemberDataPointer()) {
-    llvm::Value *Dst;
-    if (DerivedToBase)
-      Dst =3D Builder.CreateNSWSub(Src, Adj, "adj");
+  if (destTy->isMemberDataPointer()) {
+    llvm::Value *dst;
+    if (isDerivedToBase)
+      dst =3D Builder.CreateNSWSub(src, adj, "adj");
     else
-      Dst =3D Builder.CreateNSWAdd(Src, Adj, "adj");
+      dst =3D Builder.CreateNSWAdd(src, adj, "adj");
=20
     // Null check.
-    llvm::Value *Null =3D llvm::Constant::getAllOnesValue(Src->getType());
-    llvm::Value *IsNull =3D Builder.CreateICmpEQ(Src, Null, "memptr.isnull=
");
-    return Builder.CreateSelect(IsNull, Src, Dst);
+    llvm::Value *null =3D llvm::Constant::getAllOnesValue(src->getType());
+    llvm::Value *isNull =3D Builder.CreateICmpEQ(src, null, "memptr.isnull=
");
+    return Builder.CreateSelect(isNull, src, dst);
   }
=20
   // The this-adjustment is left-shifted by 1 on ARM.
   if (IsARM) {
-    uint64_t Offset =3D cast<llvm::ConstantInt>(Adj)->getZExtValue();
-    Offset <<=3D 1;
-    Adj =3D llvm::ConstantInt::get(Adj->getType(), Offset);
+    uint64_t offset =3D cast<llvm::ConstantInt>(adj)->getZExtValue();
+    offset <<=3D 1;
+    adj =3D llvm::ConstantInt::get(adj->getType(), offset);
   }
=20
-  llvm::Value *SrcAdj =3D Builder.CreateExtractValue(Src, 1, "src.adj");
-  llvm::Value *DstAdj;
-  if (DerivedToBase)
-    DstAdj =3D Builder.CreateNSWSub(SrcAdj, Adj, "adj");
+  llvm::Value *srcAdj =3D Builder.CreateExtractValue(src, 1, "src.adj");
+  llvm::Value *dstAdj;
+  if (isDerivedToBase)
+    dstAdj =3D Builder.CreateNSWSub(srcAdj, adj, "adj");
   else
-    DstAdj =3D Builder.CreateNSWAdd(SrcAdj, Adj, "adj");
+    dstAdj =3D Builder.CreateNSWAdd(srcAdj, adj, "adj");
=20
-  return Builder.CreateInsertValue(Src, DstAdj, 1);
+  return Builder.CreateInsertValue(src, dstAdj, 1);
 }
=20
 llvm::Constant *
-ItaniumCXXABI::EmitMemberPointerConversion(llvm::Constant *C,
-                                           const CastExpr *E) {
-  const MemberPointerType *SrcTy =3D=20
-    E->getSubExpr()->getType()->getAs<MemberPointerType>();
-  const MemberPointerType *DestTy =3D=20
-    E->getType()->getAs<MemberPointerType>();
+ItaniumCXXABI::EmitMemberPointerConversion(const CastExpr *E,
+                                           llvm::Constant *src) {
+  assert(E->getCastKind() =3D=3D CK_DerivedToBaseMemberPointer ||
+         E->getCastKind() =3D=3D CK_BaseToDerivedMemberPointer ||
+         E->getCastKind() =3D=3D CK_ReinterpretMemberPointer);
=20
-  bool DerivedToBase =3D
-    E->getCastKind() =3D=3D CK_DerivedToBaseMemberPointer;
+  // Under Itanium, reinterprets don't require any additional processing.
+  if (E->getCastKind() =3D=3D CK_ReinterpretMemberPointer) return src;
=20
-  const CXXRecordDecl *DerivedDecl;
-  if (DerivedToBase)
-    DerivedDecl =3D SrcTy->getClass()->getAsCXXRecordDecl();
-  else
-    DerivedDecl =3D DestTy->getClass()->getAsCXXRecordDecl();
+  // If the adjustment is trivial, we don't need to do anything.
+  llvm::Constant *adj =3D getMemberPointerAdjustment(E);
+  if (!adj) return src;
=20
-  // Calculate the offset to the base class.
-  llvm::Constant *Offset =3D=20
-    CGM.GetNonVirtualBaseClassOffset(DerivedDecl,
-                                     E->path_begin(),
-                                     E->path_end());
-  // If there's no offset, we're done.
-  if (!Offset) return C;
+  bool isDerivedToBase =3D (E->getCastKind() =3D=3D CK_DerivedToBaseMember=
Pointer);
=20
-  // If the source is a member data pointer, we have to do a null
-  // check and then add the offset.  In the common case, we can fold
-  // away the offset.
-  if (SrcTy->isMemberDataPointer()) {
-    assert(C->getType() =3D=3D getPtrDiffTy());
+  const MemberPointerType *destTy =3D
+    E->getType()->castAs<MemberPointerType>();
=20
-    // If it's a constant int, just create a new constant int.
-    if (llvm::ConstantInt *CI =3D dyn_cast<llvm::ConstantInt>(C)) {
-      int64_t Src =3D CI->getSExtValue();
+  // For member data pointers, this is just a matter of adding the
+  // offset if the source is non-null.
+  if (destTy->isMemberDataPointer()) {
+    // null maps to null.
+    if (src->isAllOnesValue()) return src;
=20
-      // Null converts to null.
-      if (Src =3D=3D -1) return CI;
-
-      // Otherwise, just add the offset.
-      int64_t OffsetV =3D cast<llvm::ConstantInt>(Offset)->getSExtValue();
-      int64_t Dst =3D (DerivedToBase ? Src - OffsetV : Src + OffsetV);
-      return llvm::ConstantInt::get(CI->getType(), Dst, /*signed*/ true);
-    }
-
-    // Otherwise, we have to form a constant select expression.
-    llvm::Constant *Null =3D llvm::Constant::getAllOnesValue(C->getType());
-
-    llvm::Constant *IsNull =3D
-      llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_EQ, C, Null);
-
-    llvm::Constant *Dst;
-    if (DerivedToBase)
-      Dst =3D llvm::ConstantExpr::getNSWSub(C, Offset);
+    if (isDerivedToBase)
+      return llvm::ConstantExpr::getNSWSub(src, adj);
     else
-      Dst =3D llvm::ConstantExpr::getNSWAdd(C, Offset);
-
-    return llvm::ConstantExpr::getSelect(IsNull, Null, Dst);
+      return llvm::ConstantExpr::getNSWAdd(src, adj);
   }
=20
   // The this-adjustment is left-shifted by 1 on ARM.
   if (IsARM) {
-    int64_t OffsetV =3D cast<llvm::ConstantInt>(Offset)->getSExtValue();
-    OffsetV <<=3D 1;
-    Offset =3D llvm::ConstantInt::get(Offset->getType(), OffsetV);
+    uint64_t offset =3D cast<llvm::ConstantInt>(adj)->getZExtValue();
+    offset <<=3D 1;
+    adj =3D llvm::ConstantInt::get(adj->getType(), offset);
   }
=20
-  llvm::ConstantStruct *CS =3D cast<llvm::ConstantStruct>(C);
+  llvm::Constant *srcAdj =3D llvm::ConstantExpr::getExtractValue(src, 1);
+  llvm::Constant *dstAdj;
+  if (isDerivedToBase)
+    dstAdj =3D llvm::ConstantExpr::getNSWSub(srcAdj, adj);
+  else
+    dstAdj =3D llvm::ConstantExpr::getNSWAdd(srcAdj, adj);
=20
-  llvm::Constant *Values[2] =3D { CS->getOperand(0), 0 };
-  if (DerivedToBase)
-    Values[1] =3D llvm::ConstantExpr::getSub(CS->getOperand(1), Offset);
-  else
-    Values[1] =3D llvm::ConstantExpr::getAdd(CS->getOperand(1), Offset);
-
-  return llvm::ConstantStruct::get(CS->getType(), Values);
-}       =20
-
+  return llvm::ConstantExpr::getInsertValue(src, dstAdj, 1);
+}
=20
 llvm::Constant *
 ItaniumCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
@@ -500,6 +465,11 @@
 }
=20
 llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
+  return BuildMemberPointer(MD, CharUnits::Zero());
+}
+
+llvm::Constant *ItaniumCXXABI::BuildMemberPointer(const CXXMethodDecl *MD,
+                                                  CharUnits ThisAdjustment=
) {
   assert(MD->isInstance() && "Member function must not be static!");
   MD =3D MD->getCanonicalDecl();
=20
@@ -524,14 +494,16 @@
       //   discrimination as the least significant bit of ptr does for
       //   Itanium.
       MemPtr[0] =3D llvm::ConstantInt::get(ptrdiff_t, VTableOffset);
-      MemPtr[1] =3D llvm::ConstantInt::get(ptrdiff_t, 1);
+      MemPtr[1] =3D llvm::ConstantInt::get(ptrdiff_t,
+                                         2 * ThisAdjustment.getQuantity() =
+ 1);
     } else {
       // Itanium C++ ABI 2.3:
       //   For a virtual function, [the pointer field] is 1 plus the
       //   virtual table offset (in bytes) of the function,
       //   represented as a ptrdiff_t.
       MemPtr[0] =3D llvm::ConstantInt::get(ptrdiff_t, VTableOffset + 1);
-      MemPtr[1] =3D llvm::ConstantInt::get(ptrdiff_t, 0);
+      MemPtr[1] =3D llvm::ConstantInt::get(ptrdiff_t,
+                                         ThisAdjustment.getQuantity());
     }
   } else {
     const FunctionProtoType *FPT =3D MD->getType()->castAs<FunctionProtoTy=
pe>();
@@ -539,8 +511,7 @@
     // Check whether the function has a computable LLVM signature.
     if (Types.isFuncTypeConvertible(FPT)) {
       // The function has a computable LLVM signature; use the correct typ=
e.
-      Ty =3D Types.GetFunctionType(Types.getFunctionInfo(MD),
-                                 FPT->isVariadic());
+      Ty =3D Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
     } else {
       // Use an arbitrary non-function type to tell GetAddrOfFunction that=
 the
       // function type is incomplete.
@@ -549,12 +520,45 @@
     llvm::Constant *addr =3D CGM.GetAddrOfFunction(MD, Ty);
=20
     MemPtr[0] =3D llvm::ConstantExpr::getPtrToInt(addr, ptrdiff_t);
-    MemPtr[1] =3D llvm::ConstantInt::get(ptrdiff_t, 0);
+    MemPtr[1] =3D llvm::ConstantInt::get(ptrdiff_t, (IsARM ? 2 : 1) *
+                                       ThisAdjustment.getQuantity());
   }
  =20
   return llvm::ConstantStruct::getAnon(MemPtr);
 }
=20
+llvm::Constant *ItaniumCXXABI::EmitMemberPointer(const APValue &MP,
+                                                 QualType MPType) {
+  const MemberPointerType *MPT =3D MPType->castAs<MemberPointerType>();
+  const ValueDecl *MPD =3D MP.getMemberPointerDecl();
+  if (!MPD)
+    return EmitNullMemberPointer(MPT);
+
+  // Compute the this-adjustment.
+  CharUnits ThisAdjustment =3D CharUnits::Zero();
+  ArrayRef<const CXXRecordDecl*> Path =3D MP.getMemberPointerPath();
+  bool DerivedMember =3D MP.isMemberPointerToDerivedMember();
+  const CXXRecordDecl *RD =3D cast<CXXRecordDecl>(MPD->getDeclContext());
+  for (unsigned I =3D 0, N =3D Path.size(); I !=3D N; ++I) {
+    const CXXRecordDecl *Base =3D RD;
+    const CXXRecordDecl *Derived =3D Path[I];
+    if (DerivedMember)
+      std::swap(Base, Derived);
+    ThisAdjustment +=3D
+      getContext().getASTRecordLayout(Derived).getBaseClassOffset(Base);
+    RD =3D Path[I];
+  }
+  if (DerivedMember)
+    ThisAdjustment =3D -ThisAdjustment;
+
+  if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(MPD))
+    return BuildMemberPointer(MD, ThisAdjustment);
+
+  CharUnits FieldOffset =3D
+    getContext().toCharUnitsFromBits(getContext().getFieldOffset(MPD));
+  return EmitMemberDataPointer(MPT, ThisAdjustment + FieldOffset);
+}
+
 /// The comparison algorithm is pretty easy: the member pointers are
 /// the same if they're either bitwise identical *or* both null.
 ///
@@ -775,7 +779,7 @@
   /// Initialize the return slot to 'this' at the start of the
   /// function.
   if (HasThisReturn(CGF.CurGD))
-    CGF.Builder.CreateStore(CGF.LoadCXXThis(), CGF.ReturnValue);
+    CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
 }
=20
 void ARMCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF,
@@ -801,7 +805,7 @@
   // Automatic Reference Counting:
   //   We need an array cookie for pointers with strong or weak lifetime.
   QualType AllocatedType =3D expr->getAllocatedType();
-  if (getContext().getLangOptions().ObjCAutoRefCount &&
+  if (getContext().getLangOpts().ObjCAutoRefCount &&
       AllocatedType->isObjCLifetimeType()) {
     switch (AllocatedType.getObjCLifetime()) {
     case Qualifiers::OCL_None:
@@ -1020,27 +1024,28 @@
     llvm::FunctionType::get(CGM.getTypes().ConvertType(CGM.getContext().In=
tTy),
                             GuardPtrTy, /*isVarArg=3D*/false);
  =20
-  return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire");
+  return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_acquire",
+                                   llvm::Attribute::NoUnwind);
 }
=20
 static llvm::Constant *getGuardReleaseFn(CodeGenModule &CGM,
                                          llvm::PointerType *GuardPtrTy) {
   // void __cxa_guard_release(__guard *guard_object);
   llvm::FunctionType *FTy =3D
-    llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
-                            GuardPtrTy, /*isVarArg=3D*/false);
+    llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=3D*/false);
  =20
-  return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release");
+  return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_release",
+                                   llvm::Attribute::NoUnwind);
 }
=20
 static llvm::Constant *getGuardAbortFn(CodeGenModule &CGM,
                                        llvm::PointerType *GuardPtrTy) {
   // void __cxa_guard_abort(__guard *guard_object);
   llvm::FunctionType *FTy =3D
-    llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
-                            GuardPtrTy, /*isVarArg=3D*/false);
+    llvm::FunctionType::get(CGM.VoidTy, GuardPtrTy, /*isVarArg=3D*/false);
  =20
-  return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort");
+  return CGM.CreateRuntimeFunction(FTy, "__cxa_guard_abort",
+                                   llvm::Attribute::NoUnwind);
 }
=20
 namespace {
@@ -1059,43 +1064,53 @@
 /// just special-case it at particular places.
 void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
                                     const VarDecl &D,
-                                    llvm::GlobalVariable *GV) {
+                                    llvm::GlobalVariable *var,
+                                    bool shouldPerformInit) {
   CGBuilderTy &Builder =3D CGF.Builder;
=20
   // We only need to use thread-safe statics for local variables;
   // global initialization is always single-threaded.
   bool threadsafe =3D
-    (getContext().getLangOptions().ThreadsafeStatics && D.isLocalVarDecl()=
);
-
-  llvm::IntegerType *GuardTy;
+    (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
=20
   // If we have a global variable with internal linkage and thread-safe st=
atics
   // are disabled, we can just let the guard variable be of type i8.
-  bool useInt8GuardVariable =3D !threadsafe && GV->hasInternalLinkage();
+  bool useInt8GuardVariable =3D !threadsafe && var->hasInternalLinkage();
+
+  llvm::IntegerType *guardTy;
   if (useInt8GuardVariable) {
-    GuardTy =3D CGF.Int8Ty;
+    guardTy =3D CGF.Int8Ty;
   } else {
     // Guard variables are 64 bits in the generic ABI and 32 bits on ARM.
-    GuardTy =3D (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
+    guardTy =3D (IsARM ? CGF.Int32Ty : CGF.Int64Ty);
   }
-  llvm::PointerType *GuardPtrTy =3D GuardTy->getPointerTo();
+  llvm::PointerType *guardPtrTy =3D guardTy->getPointerTo();
=20
-  // Create the guard variable.
-  llvm::SmallString<256> GuardVName;
-  llvm::raw_svector_ostream Out(GuardVName);
-  getMangleContext().mangleItaniumGuardVariable(&D, Out);
-  Out.flush();
+  // Create the guard variable if we don't already have it (as we
+  // might if we're double-emitting this function body).
+  llvm::GlobalVariable *guard =3D CGM.getStaticLocalDeclGuardAddress(&D);
+  if (!guard) {
+    // Mangle the name for the guard.
+    SmallString<256> guardName;
+    {
+      llvm::raw_svector_ostream out(guardName);
+      getMangleContext().mangleItaniumGuardVariable(&D, out);
+      out.flush();
+    }
=20
-  // Just absorb linkage and visibility from the variable.
-  llvm::GlobalVariable *GuardVariable =3D
-    new llvm::GlobalVariable(CGM.getModule(), GuardTy,
-                             false, GV->getLinkage(),
-                             llvm::ConstantInt::get(GuardTy, 0),
-                             GuardVName.str());
-  GuardVariable->setVisibility(GV->getVisibility());
+    // Create the guard variable with a zero-initializer.
+    // Just absorb linkage and visibility from the guarded variable.
+    guard =3D new llvm::GlobalVariable(CGM.getModule(), guardTy,
+                                     false, var->getLinkage(),
+                                     llvm::ConstantInt::get(guardTy, 0),
+                                     guardName.str());
+    guard->setVisibility(var->getVisibility());
+
+    CGM.setStaticLocalDeclGuardAddress(&D, guard);
+  }
=20
   // Test whether the variable has completed initialization.
-  llvm::Value *IsInitialized;
+  llvm::Value *isInitialized;
=20
   // ARM C++ ABI 3.2.3.1:
   //   To support the potential use of initialization guard variables
@@ -1109,9 +1124,9 @@
   //         ...
   //     }
   if (IsARM && !useInt8GuardVariable) {
-    llvm::Value *V =3D Builder.CreateLoad(GuardVariable);
+    llvm::Value *V =3D Builder.CreateLoad(guard);
     V =3D Builder.CreateAnd(V, Builder.getInt32(1));
-    IsInitialized =3D Builder.CreateIsNull(V, "guard.uninitialized");
+    isInitialized =3D Builder.CreateIsNull(V, "guard.uninitialized");
=20
   // Itanium C++ ABI 3.3.2:
   //   The following is pseudo-code showing how these functions can be use=
d:
@@ -1129,9 +1144,8 @@
   //     }
   } else {
     // Load the first byte of the guard variable.
-    llvm::Type *PtrTy =3D Builder.getInt8PtrTy();
     llvm::LoadInst *LI =3D=20
-      Builder.CreateLoad(Builder.CreateBitCast(GuardVariable, PtrTy));
+      Builder.CreateLoad(Builder.CreateBitCast(guard, CGM.Int8PtrTy));
     LI->setAlignment(1);
=20
     // Itanium ABI:
@@ -1143,14 +1157,14 @@
     if (threadsafe)
       LI->setAtomic(llvm::Acquire);
=20
-    IsInitialized =3D Builder.CreateIsNull(LI, "guard.uninitialized");
+    isInitialized =3D Builder.CreateIsNull(LI, "guard.uninitialized");
   }
=20
   llvm::BasicBlock *InitCheckBlock =3D CGF.createBasicBlock("init.check");
   llvm::BasicBlock *EndBlock =3D CGF.createBasicBlock("init.end");
=20
   // Check if the first byte of the guard variable is zero.
-  Builder.CreateCondBr(IsInitialized, InitCheckBlock, EndBlock);
+  Builder.CreateCondBr(isInitialized, InitCheckBlock, EndBlock);
=20
   CGF.EmitBlock(InitCheckBlock);
=20
@@ -1158,7 +1172,7 @@
   if (threadsafe) {   =20
     // Call __cxa_guard_acquire.
     llvm::Value *V
-      =3D Builder.CreateCall(getGuardAcquireFn(CGM, GuardPtrTy), GuardVari=
able);
+      =3D Builder.CreateCall(getGuardAcquireFn(CGM, guardPtrTy), guard);
               =20
     llvm::BasicBlock *InitBlock =3D CGF.createBasicBlock("init");
  =20
@@ -1166,22 +1180,22 @@
                          InitBlock, EndBlock);
  =20
     // Call __cxa_guard_abort along the exceptional edge.
-    CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, GuardVariable);
+    CGF.EHStack.pushCleanup<CallGuardAbort>(EHCleanup, guard);
    =20
     CGF.EmitBlock(InitBlock);
   }
=20
   // Emit the initializer and add a global destructor if appropriate.
-  CGF.EmitCXXGlobalVarDeclInit(D, GV);
+  CGF.EmitCXXGlobalVarDeclInit(D, var, shouldPerformInit);
=20
   if (threadsafe) {
     // Pop the guard-abort cleanup if we pushed one.
     CGF.PopCleanupBlock();
=20
     // Call __cxa_guard_release.  This cannot throw.
-    Builder.CreateCall(getGuardReleaseFn(CGM, GuardPtrTy), GuardVariable);
+    Builder.CreateCall(getGuardReleaseFn(CGM, guardPtrTy), guard);
   } else {
-    Builder.CreateStore(llvm::ConstantInt::get(GuardTy, 1), GuardVariable);
+    Builder.CreateStore(llvm::ConstantInt::get(guardTy, 1), guard);
   }
=20
   CGF.EmitBlock(EndBlock);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/MicrosoftCXXABI.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/MicrosoftCXXABI.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/MicrosoftCXXABI.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -78,6 +78,13 @@
   //     delete[] p;
   //   }
   // Whereas it prints "104" and "104" if you give A a destructor.
+  void ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr,
+                       const CXXDeleteExpr *expr,
+                       QualType ElementType, llvm::Value *&NumElements,
+                       llvm::Value *&AllocPtr, CharUnits &CookieSize) {
+    CGF.CGM.ErrorUnsupported(expr, "don't know how to handle array cookies=
 "
+                                   "in the Microsoft C++ ABI");
+  }
 };
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/ModuleBuilder.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/ModuleBuilder.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/ModuleBuilder.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -28,12 +28,12 @@
 namespace {
   class CodeGeneratorImpl : public CodeGenerator {
     DiagnosticsEngine &Diags;
-    llvm::OwningPtr<const llvm::TargetData> TD;
+    OwningPtr<const llvm::TargetData> TD;
     ASTContext *Ctx;
     const CodeGenOptions CodeGenOpts;  // Intentionally copied in.
   protected:
-    llvm::OwningPtr<llvm::Module> M;
-    llvm::OwningPtr<CodeGen::CodeGenModule> Builder;
+    OwningPtr<llvm::Module> M;
+    OwningPtr<CodeGen::CodeGenModule> Builder;
   public:
     CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleN=
ame,
                       const CodeGenOptions &CGO, llvm::LLVMContext& C)
@@ -59,10 +59,15 @@
                                                *M, *TD, Diags));
     }
=20
-    virtual void HandleTopLevelDecl(DeclGroupRef DG) {
+    virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
+      Builder->HandleCXXStaticMemberVarInstantiation(VD);
+    }
+
+    virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
       // Make sure to emit all elements of a Decl.
       for (DeclGroupRef::iterator I =3D DG.begin(), E =3D DG.end(); I !=3D=
 E; ++I)
         Builder->EmitTopLevelDecl(*I);
+      return true;
     }
=20
     /// HandleTagDeclDefinition - This callback is invoked each time a Tag=
Decl
@@ -74,7 +79,7 @@
      =20
       // In C++, we may have member functions that need to be emitted at t=
his=20
       // point.
-      if (Ctx->getLangOptions().CPlusPlus && !D->isDependentContext()) {
+      if (Ctx->getLangOpts().CPlusPlus && !D->isDependentContext()) {
         for (DeclContext::decl_iterator M =3D D->decls_begin(),=20
                                      MEnd =3D D->decls_end();
              M !=3D MEnd; ++M)
@@ -112,6 +117,8 @@
   };
 }
=20
+void CodeGenerator::anchor() { }
+
 CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
                                         const std::string& ModuleName,
                                         const CodeGenOptions &CGO,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/TargetInfo.cpp
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -98,7 +98,8 @@
   return 32;
 }
=20
-bool TargetCodeGenInfo::isNoProtoCallVariadic(CallingConv CC) const {
+bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
+                                     const FunctionNoProtoType *fnType) co=
nst {
   // The following conventions are known to require this to be false:
   //   x86_stdcall
   //   MIPS
@@ -117,10 +118,14 @@
=20
   QualType FT =3D FD->getType();
=20
-    // Constant arrays of empty records count as empty, strip them off.
+  // Constant arrays of empty records count as empty, strip them off.
+  // Constant arrays of zero length always count as empty.
   if (AllowArrays)
-    while (const ConstantArrayType *AT =3D Context.getAsConstantArrayType(=
FT))
+    while (const ConstantArrayType *AT =3D Context.getAsConstantArrayType(=
FT)) {
+      if (AT->getSize() =3D=3D 0)
+        return true;
       FT =3D AT->getElementType();
+    }
=20
   const RecordType *RT =3D FT->getAs<RecordType>();
   if (!RT)
@@ -252,6 +257,11 @@
     }
   }
=20
+  // We don't consider a struct a single-element struct if it has
+  // padding beyond the element type.
+  if (Found && Context.getTypeSize(Found) !=3D Context.getTypeSize(T))
+    return 0;
+
   return Found;
 }
=20
@@ -287,6 +297,8 @@
   if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
     return false;
=20
+  uint64_t Size =3D 0;
+
   for (RecordDecl::field_iterator i =3D RD->field_begin(), e =3D RD->field=
_end();
          i !=3D e; ++i) {
     const FieldDecl *FD =3D *i;
@@ -299,8 +311,14 @@
     // counts as "basic" is more complicated than what we were doing previ=
ously.
     if (FD->isBitField())
       return false;
+
+    Size +=3D Context.getTypeSize(FD->getType());
   }
=20
+  // Make sure there are not any holes in the struct.
+  if (Size !=3D Context.getTypeSize(Ty))
+    return false;
+
   return true;
 }
=20
@@ -339,8 +357,14 @@
 }
=20
 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
-  if (isAggregateTypeForABI(Ty))
+  if (isAggregateTypeForABI(Ty)) {
+    // Records with non trivial destructors/constructors should not be pas=
sed
+    // by value.
+    if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
+      return ABIArgInfo::getIndirect(0, /*ByVal=3D*/false);
+
     return ABIArgInfo::getIndirect(0);
+  }
=20
   // Treat an enum type as its underlying type.
   if (const EnumType *EnumTy =3D Ty->getAs<EnumType>())
@@ -365,8 +389,8 @@
           ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
 }
=20
-/// UseX86_MMXType - Return true if this is an MMX type that should use th=
e special
-/// x86_mmx type.
+/// UseX86_MMXType - Return true if this is an MMX type that should use the
+/// special x86_mmx type.
 bool UseX86_MMXType(llvm::Type *IRType) {
   // If the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>, use the
   // special x86_mmx type.
@@ -394,12 +418,14 @@
   bool IsDarwinVectorABI;
   bool IsSmallStructInRegABI;
   bool IsMMXDisabled;
+  bool IsWin32FloatStructABI;
=20
   static bool isRegisterSize(unsigned Size) {
     return (Size =3D=3D 8 || Size =3D=3D 16 || Size =3D=3D 32 || Size =3D=
=3D 64);
   }
=20
-  static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
+  static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,=20
+                                          unsigned callingConvention);
=20
   /// getIndirectResult - Give a source type \arg Ty, return a suitable re=
sult
   /// such that the argument will be passed in memory.
@@ -410,11 +436,13 @@
=20
 public:
=20
-  ABIArgInfo classifyReturnType(QualType RetTy) const;
+  ABIArgInfo classifyReturnType(QualType RetTy,=20
+                                unsigned callingConvention) const;
   ABIArgInfo classifyArgumentType(QualType RetTy) const;
=20
   virtual void computeInfo(CGFunctionInfo &FI) const {
-    FI.getReturnInfo() =3D classifyReturnType(FI.getReturnType());
+    FI.getReturnInfo() =3D classifyReturnType(FI.getReturnType(),=20
+                                            FI.getCallingConvention());
     for (CGFunctionInfo::arg_iterator it =3D FI.arg_begin(), ie =3D FI.arg=
_end();
          it !=3D ie; ++it)
       it->info =3D classifyArgumentType(it->type);
@@ -423,15 +451,16 @@
   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
                                  CodeGenFunction &CGF) const;
=20
-  X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m)
+  X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool m, bool w)
     : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
-      IsMMXDisabled(m) {}
+      IsMMXDisabled(m), IsWin32FloatStructABI(w) {}
 };
=20
 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
 public:
-  X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool=
 m)
-    :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, m)) {}
+  X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
+      bool d, bool p, bool m, bool w)
+    :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, m, w)) {}
=20
   void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
                            CodeGen::CodeGenModule &CGM) const;
@@ -459,7 +488,8 @@
 /// shouldReturnTypeInRegister - Determine if the given type should be
 /// passed in a register (for the Darwin ABI).
 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
-                                               ASTContext &Context) {
+                                               ASTContext &Context,
+                                               unsigned callingConvention)=
 {
   uint64_t Size =3D Context.getTypeSize(Ty);
=20
   // Type must be register sized.
@@ -484,7 +514,8 @@
=20
   // Arrays are treated like records.
   if (const ConstantArrayType *AT =3D Context.getAsConstantArrayType(Ty))
-    return shouldReturnTypeInRegister(AT->getElementType(), Context);
+    return shouldReturnTypeInRegister(AT->getElementType(), Context,
+                                      callingConvention);
=20
   // Otherwise, it must be a record type.
   const RecordType *RT =3D Ty->getAs<RecordType>();
@@ -492,6 +523,13 @@
=20
   // FIXME: Traverse bases here too.
=20
+  // For thiscall conventions, structures will never be returned in
+  // a register.  This is for compatibility with the MSVC ABI
+  if (callingConvention =3D=3D llvm::CallingConv::X86_ThisCall &&=20
+      RT->isStructureType()) {
+    return false;
+  }
+
   // Structure types are passed in register if all fields would be
   // passed in a register.
   for (RecordDecl::field_iterator i =3D RT->getDecl()->field_begin(),
@@ -503,14 +541,15 @@
       continue;
=20
     // Check fields recursively.
-    if (!shouldReturnTypeInRegister(FD->getType(), Context))
+    if (!shouldReturnTypeInRegister(FD->getType(), Context,=20
+                                    callingConvention))
       return false;
   }
-
   return true;
 }
=20
-ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy) const {
+ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,=20
+                                            unsigned callingConvention) co=
nst {
   if (RetTy->isVoidType())
     return ABIArgInfo::getIgnore();
=20
@@ -555,51 +594,24 @@
     if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
       return ABIArgInfo::getIndirect(0);
=20
-    // Classify "single element" structs as their element type.
-    if (const Type *SeltTy =3D isSingleElementStruct(RetTy, getContext()))=
 {
-      if (const BuiltinType *BT =3D SeltTy->getAs<BuiltinType>()) {
-        if (BT->isIntegerType()) {
-          // We need to use the size of the structure, padding
-          // bit-fields can adjust that to be larger than the single
-          // element type.
-          uint64_t Size =3D getContext().getTypeSize(RetTy);
-          return ABIArgInfo::getDirect(
-            llvm::IntegerType::get(getVMContext(), (unsigned)Size));
-        }
-
-        if (BT->getKind() =3D=3D BuiltinType::Float) {
-          assert(getContext().getTypeSize(RetTy) =3D=3D
-                 getContext().getTypeSize(SeltTy) &&
-                 "Unexpect single element structure size!");
-          return ABIArgInfo::getDirect(llvm::Type::getFloatTy(getVMContext=
()));
-        }
-
-        if (BT->getKind() =3D=3D BuiltinType::Double) {
-          assert(getContext().getTypeSize(RetTy) =3D=3D
-                 getContext().getTypeSize(SeltTy) &&
-                 "Unexpect single element structure size!");
-          return ABIArgInfo::getDirect(llvm::Type::getDoubleTy(getVMContex=
t()));
-        }
-      } else if (SeltTy->isPointerType()) {
-        // FIXME: It would be really nice if this could come out as the pr=
oper
-        // pointer type.
-        llvm::Type *PtrTy =3D llvm::Type::getInt8PtrTy(getVMContext());
-        return ABIArgInfo::getDirect(PtrTy);
-      } else if (SeltTy->isVectorType()) {
-        // 64- and 128-bit vectors are never returned in a
-        // register when inside a structure.
-        uint64_t Size =3D getContext().getTypeSize(RetTy);
-        if (Size =3D=3D 64 || Size =3D=3D 128)
-          return ABIArgInfo::getIndirect(0);
-
-        return classifyReturnType(QualType(SeltTy, 0));
-      }
-    }
-
     // Small structures which are register sized are generally returned
     // in a register.
-    if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext())) {
+    if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),=20
+                                                  callingConvention)) {
       uint64_t Size =3D getContext().getTypeSize(RetTy);
+
+      // As a special-case, if the struct is a "single-element" struct, and
+      // the field is of type "float" or "double", return it in a
+      // floating-point register. (MSVC does not apply this special case.)
+      // We apply a similar transformation for pointer types to improve the
+      // quality of the generated IR.
+      if (const Type *SeltTy =3D isSingleElementStruct(RetTy, getContext()=
))
+        if ((!IsWin32FloatStructABI && SeltTy->isRealFloatingType())
+            || SeltTy->hasPointerRepresentation())
+          return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)=
));
+
+      // FIXME: We should be able to narrow this integer in cases with dead
+      // padding.
       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),S=
ize));
     }
=20
@@ -631,7 +643,7 @@
        i !=3D e; ++i) {
     QualType FT =3D i->getType();
=20
-    if (FT->getAs<VectorType>() && Context.getTypeSize(Ty) =3D=3D 128)
+    if (FT->getAs<VectorType>() && Context.getTypeSize(FT) =3D=3D 128)
       return true;
=20
     if (isRecordWithSSEVectorType(Context, FT))
@@ -655,7 +667,7 @@
   }
=20
   // Otherwise, if the type contains an SSE vector type, the alignment is =
16.
-  if (isRecordWithSSEVectorType(getContext(), Ty))
+  if (Align >=3D 16 && isRecordWithSSEVectorType(getContext(), Ty))
     return 16;
=20
   return MinABIStackAlignInBytes;
@@ -694,8 +706,8 @@
         return getIndirectResult(Ty);
     }
=20
-    // Ignore empty structs.
-    if (Ty->isStructureType() && getContext().getTypeSize(Ty) =3D=3D 0)
+    // Ignore empty structs/unions.
+    if (isEmptyRecord(getContext(), Ty, true))
       return ABIArgInfo::getIgnore();
=20
     // Expand small (<=3D 128-bit) record types when we know that the stac=
k layout
@@ -743,19 +755,36 @@
=20
 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
                                       CodeGenFunction &CGF) const {
-  llvm::Type *BP =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
-  llvm::Type *BPP =3D llvm::PointerType::getUnqual(BP);
+  llvm::Type *BPP =3D CGF.Int8PtrPtrTy;
=20
   CGBuilderTy &Builder =3D CGF.Builder;
   llvm::Value *VAListAddrAsBPP =3D Builder.CreateBitCast(VAListAddr, BPP,
                                                        "ap");
   llvm::Value *Addr =3D Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
+
+  // Compute if the address needs to be aligned
+  unsigned Align =3D CGF.getContext().getTypeAlignInChars(Ty).getQuantity(=
);
+  Align =3D getTypeStackAlignInBytes(Ty, Align);
+  Align =3D std::max(Align, 4U);
+  if (Align > 4) {
+    // addr =3D (addr + align - 1) & -align;
+    llvm::Value *Offset =3D
+      llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
+    Addr =3D CGF.Builder.CreateGEP(Addr, Offset);
+    llvm::Value *AsInt =3D CGF.Builder.CreatePtrToInt(Addr,
+                                                    CGF.Int32Ty);
+    llvm::Value *Mask =3D llvm::ConstantInt::get(CGF.Int32Ty, -Align);
+    Addr =3D CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
+                                      Addr->getType(),
+                                      "ap.cur.aligned");
+  }
+
   llvm::Type *PTy =3D
     llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
   llvm::Value *AddrTyped =3D Builder.CreateBitCast(Addr, PTy);
=20
   uint64_t Offset =3D
-    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
+    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
   llvm::Value *NextAddr =3D
     Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
                       "ap.next");
@@ -782,10 +811,8 @@
                                                CodeGen::CodeGenFunction &C=
GF,
                                                llvm::Value *Address) const=
 {
   CodeGen::CGBuilderTy &Builder =3D CGF.Builder;
-  llvm::LLVMContext &Context =3D CGF.getLLVMContext();
-
-  llvm::IntegerType *i8 =3D llvm::Type::getInt8Ty(Context);
-  llvm::Value *Four8 =3D llvm::ConstantInt::get(i8, 4);
+
+  llvm::Value *Four8 =3D llvm::ConstantInt::get(CGF.Int8Ty, 4);
=20
   // 0-7 are the eight integer registers;  the order is different
   //   on Darwin (for EH), but the range is the same.
@@ -796,7 +823,7 @@
     // 12-16 are st(0..4).  Not sure why we stop at 4.
     // These have size 16, which is sizeof(long double) on
     // platforms with 8-byte alignment for that type.
-    llvm::Value *Sixteen8 =3D llvm::ConstantInt::get(i8, 16);
+    llvm::Value *Sixteen8 =3D llvm::ConstantInt::get(CGF.Int8Ty, 16);
     AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
=20
   } else {
@@ -807,7 +834,7 @@
     // 11-16 are st(0..5).  Not sure why we stop at 5.
     // These have size 12, which is sizeof(long double) on
     // platforms with 4-byte alignment for that type.
-    llvm::Value *Twelve8 =3D llvm::ConstantInt::get(i8, 12);
+    llvm::Value *Twelve8 =3D llvm::ConstantInt::get(CGF.Int8Ty, 12);
     AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
   }
=20
@@ -897,14 +924,20 @@
=20
   /// getIndirectResult - Give a source type \arg Ty, return a suitable re=
sult
   /// such that the argument will be passed in memory.
-  ABIArgInfo getIndirectResult(QualType Ty) const;
+  ///
+  /// \param freeIntRegs - The number of free integer registers remaining
+  /// available.
+  ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
=20
   ABIArgInfo classifyReturnType(QualType RetTy) const;
=20
   ABIArgInfo classifyArgumentType(QualType Ty,
+                                  unsigned freeIntRegs,
                                   unsigned &neededInt,
                                   unsigned &neededSSE) const;
=20
+  bool IsIllegalVectorType(QualType Ty) const;
+
   /// The 0.98 ABI revision clarified a lot of ambiguities,
   /// unfortunately in ways that were not always consistent with
   /// certain previous compilers.  In particular, platforms which
@@ -914,8 +947,23 @@
     return !getContext().getTargetInfo().getTriple().isOSDarwin();
   }
=20
+  bool HasAVX;
+
 public:
-  X86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
+  X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
+      ABIInfo(CGT), HasAVX(hasavx) {}
+
+  bool isPassedUsingAVXType(QualType type) const {
+    unsigned neededInt, neededSSE;
+    // The freeIntRegs argument doesn't matter here.
+    ABIArgInfo info =3D classifyArgumentType(type, 0, neededInt, neededSSE=
);
+    if (info.isDirect()) {
+      llvm::Type *ty =3D info.getCoerceToType();
+      if (llvm::VectorType *vectorTy =3D dyn_cast_or_null<llvm::VectorType=
>(ty))
+        return (vectorTy->getBitWidth() > 128);
+    }
+    return false;
+  }
=20
   virtual void computeInfo(CGFunctionInfo &FI) const;
=20
@@ -939,8 +987,12 @@
=20
 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
 public:
-  X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
-    : TargetCodeGenInfo(new X86_64ABIInfo(CGT)) {}
+  X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
+    : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
+
+  const X86_64ABIInfo &getABIInfo() const {
+    return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo=
());
+  }
=20
   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
     return 7;
@@ -948,16 +1000,11 @@
=20
   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
                                llvm::Value *Address) const {
-    CodeGen::CGBuilderTy &Builder =3D CGF.Builder;
-    llvm::LLVMContext &Context =3D CGF.getLLVMContext();
-
-    llvm::IntegerType *i8 =3D llvm::Type::getInt8Ty(Context);
-    llvm::Value *Eight8 =3D llvm::ConstantInt::get(i8, 8);
+    llvm::Value *Eight8 =3D llvm::ConstantInt::get(CGF.Int8Ty, 8);
=20
     // 0-15 are the 16 integer registers.
     // 16 is %rip.
-    AssignToArrayRange(Builder, Address, Eight8, 0, 16);
-
+    AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
     return false;
   }
=20
@@ -967,13 +1014,29 @@
     return X86AdjustInlineAsmType(CGF, Constraint, Ty);
   }
=20
-  bool isNoProtoCallVariadic(CallingConv CC) const {
+  bool isNoProtoCallVariadic(const CallArgList &args,
+                             const FunctionNoProtoType *fnType) const {
     // The default CC on x86-64 sets %al to the number of SSA
     // registers used, and GCC sets this when calling an unprototyped
-    // function, so we override the default behavior.
-    if (CC =3D=3D CC_Default || CC =3D=3D CC_C) return true;
-
-    return TargetCodeGenInfo::isNoProtoCallVariadic(CC);
+    // function, so we override the default behavior.  However, don't do
+    // that when AVX types are involved: the ABI explicitly states it is
+    // undefined, and it doesn't work in practice because of how the ABI
+    // defines varargs anyway.
+    if (fnType->getCallConv() =3D=3D CC_Default || fnType->getCallConv() =
=3D=3D CC_C) {
+      bool HasAVXType =3D false;
+      for (CallArgList::const_iterator
+             it =3D args.begin(), ie =3D args.end(); it !=3D ie; ++it) {
+        if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
+          HasAVXType =3D true;
+          break;
+        }
+      }
+
+      if (!HasAVXType)
+        return true;
+    }
+
+    return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
   }
=20
 };
@@ -989,16 +1052,11 @@
=20
   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
                                llvm::Value *Address) const {
-    CodeGen::CGBuilderTy &Builder =3D CGF.Builder;
-    llvm::LLVMContext &Context =3D CGF.getLLVMContext();
-
-    llvm::IntegerType *i8 =3D llvm::Type::getInt8Ty(Context);
-    llvm::Value *Eight8 =3D llvm::ConstantInt::get(i8, 8);
+    llvm::Value *Eight8 =3D llvm::ConstantInt::get(CGF.Int8Ty, 8);
=20
     // 0-15 are the 16 integer registers.
     // 16 is %rip.
-    AssignToArrayRange(Builder, Address, Eight8, 0, 16);
-
+    AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
     return false;
   }
 };
@@ -1164,7 +1222,7 @@
       // split.
       if (OffsetBase && OffsetBase !=3D 64)
         Hi =3D Lo;
-    } else if (Size =3D=3D 128 || Size =3D=3D 256) {
+    } else if (Size =3D=3D 128 || (HasAVX && Size =3D=3D 256)) {
       // Arguments of 256-bits are split into four eightbyte chunks. The
       // least significant one belongs to class SSE and all the others to =
class
       // SSEUP. The original Lo and Hi design considers that types can't be
@@ -1377,10 +1435,28 @@
   return ABIArgInfo::getIndirect(0);
 }
=20
-ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty) const {
+bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
+  if (const VectorType *VecTy =3D Ty->getAs<VectorType>()) {
+    uint64_t Size =3D getContext().getTypeSize(VecTy);
+    unsigned LargestVector =3D HasAVX ? 256 : 128;
+    if (Size <=3D 64 || Size > LargestVector)
+      return true;
+  }
+
+  return false;
+}
+
+ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
+                                            unsigned freeIntRegs) const {
   // If this is a scalar LLVM value then assume LLVM will pass it in the r=
ight
   // place naturally.
-  if (!isAggregateTypeForABI(Ty)) {
+  //
+  // This assumption is optimistic, as there could be free registers avail=
able
+  // when we need to pass this argument in memory, and LLVM could try to p=
ass
+  // the argument in the free register. This does not seem to happen curre=
ntly,
+  // but this code would be much safer if we could mark the argument with
+  // 'onstack'. See PR12193.
+  if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
     // Treat an enum type as its underlying type.
     if (const EnumType *EnumTy =3D Ty->getAs<EnumType>())
       Ty =3D EnumTy->getDecl()->getIntegerType();
@@ -1395,6 +1471,38 @@
   // Compute the byval alignment. We specify the alignment of the byval in=
 all
   // cases so that the mid-level optimizer knows the alignment of the byva=
l.
   unsigned Align =3D std::max(getContext().getTypeAlign(Ty) / 8, 8U);
+
+  // Attempt to avoid passing indirect results using byval when possible. =
This
+  // is important for good codegen.
+  //
+  // We do this by coercing the value into a scalar type which the backend=
 can
+  // handle naturally (i.e., without using byval).
+  //
+  // For simplicity, we currently only do this when we have exhausted all =
of the
+  // free integer registers. Doing this when there are free integer regist=
ers
+  // would require more care, as we would have to ensure that the coerced =
value
+  // did not claim the unused register. That would require either reording=
 the
+  // arguments to the function (so that any subsequent inreg values came f=
irst),
+  // or only doing this optimization when there were no following argument=
s that
+  // might be inreg.
+  //
+  // We currently expect it to be rare (particularly in well written code)=
 for
+  // arguments to be passed on the stack when there are still free integer
+  // registers available (this would typically imply large structs being p=
assed
+  // by value), so this seems like a fair tradeoff for now.
+  //
+  // We can revisit this if the backend grows support for 'onstack' parame=
ter
+  // attributes. See PR12193.
+  if (freeIntRegs =3D=3D 0) {
+    uint64_t Size =3D getContext().getTypeSize(Ty);
+
+    // If this type fits in an eightbyte, coerce it into the matching inte=
gral
+    // type, which will end up on the stack (with alignment 8).
+    if (Align =3D=3D 8 && Size <=3D 64)
+      return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
+                                                          Size));
+  }
+
   return ABIArgInfo::getIndirect(Align);
 }
=20
@@ -1416,7 +1524,7 @@
   if (llvm::VectorType *VT =3D dyn_cast<llvm::VectorType>(IRType)){
     llvm::Type *EltTy =3D VT->getElementType();
     unsigned BitWidth =3D VT->getBitWidth();
-    if ((BitWidth =3D=3D 128 || BitWidth =3D=3D 256) &&
+    if ((BitWidth >=3D 128 && BitWidth <=3D 256) &&
         (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
          EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
          EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
@@ -1810,8 +1918,10 @@
   return ABIArgInfo::getDirect(ResType);
 }
=20
-ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, unsigned &need=
edInt,
-                                               unsigned &neededSSE) const {
+ABIArgInfo X86_64ABIInfo::classifyArgumentType(
+  QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &needed=
SSE)
+  const
+{
   X86_64ABIInfo::Class Lo, Hi;
   classify(Ty, 0, Lo, Hi);
=20
@@ -1843,7 +1953,7 @@
   case ComplexX87:
     if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
       ++neededInt;
-    return getIndirectResult(Ty);
+    return getIndirectResult(Ty, freeIntRegs);
=20
   case SSEUp:
   case X87Up:
@@ -1951,7 +2061,8 @@
   for (CGFunctionInfo::arg_iterator it =3D FI.arg_begin(), ie =3D FI.arg_e=
nd();
        it !=3D ie; ++it) {
     unsigned neededInt, neededSSE;
-    it->info =3D classifyArgumentType(it->type, neededInt, neededSSE);
+    it->info =3D classifyArgumentType(it->type, freeIntRegs, neededInt,
+                                    neededSSE);
=20
     // AMD64-ABI 3.2.3p3: If there are no registers available for any
     // eightbyte of an argument, the whole argument is passed on the
@@ -1961,7 +2072,7 @@
       freeIntRegs -=3D neededInt;
       freeSSERegs -=3D neededSSE;
     } else {
-      it->info =3D getIndirectResult(it->type);
+      it->info =3D getIndirectResult(it->type, freeIntRegs);
     }
   }
 }
@@ -1976,19 +2087,17 @@
=20
   // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
   // byte boundary if alignment needed by type exceeds 8 byte boundary.
+  // It isn't stated explicitly in the standard, but in practice we use
+  // alignment greater than 16 where necessary.
   uint64_t Align =3D CGF.getContext().getTypeAlign(Ty) / 8;
   if (Align > 8) {
-    // Note that we follow the ABI & gcc here, even though the type
-    // could in theory have an alignment greater than 16. This case
-    // shouldn't ever matter in practice.
-
-    // overflow_arg_area =3D (overflow_arg_area + 15) & ~15;
+    // overflow_arg_area =3D (overflow_arg_area + align - 1) & -align;
     llvm::Value *Offset =3D
-      llvm::ConstantInt::get(CGF.Int32Ty, 15);
+      llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
     overflow_arg_area =3D CGF.Builder.CreateGEP(overflow_arg_area, Offset);
     llvm::Value *AsInt =3D CGF.Builder.CreatePtrToInt(overflow_arg_area,
                                                     CGF.Int64Ty);
-    llvm::Value *Mask =3D llvm::ConstantInt::get(CGF.Int64Ty, ~15LL);
+    llvm::Value *Mask =3D llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)A=
lign);
     overflow_arg_area =3D
       CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
                                  overflow_arg_area->getType(),
@@ -2019,8 +2128,6 @@
=20
 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
                                       CodeGenFunction &CGF) const {
-  llvm::LLVMContext &VMContext =3D CGF.getLLVMContext();
-
   // Assume that va_list type is correct; should be pointer to LLVM type:
   // struct {
   //   i32 gp_offset;
@@ -2031,7 +2138,7 @@
   unsigned neededInt, neededSSE;
=20
   Ty =3D CGF.getContext().getCanonicalType(Ty);
-  ABIArgInfo AI =3D classifyArgumentType(Ty, neededInt, neededSSE);
+  ABIArgInfo AI =3D classifyArgumentType(Ty, 0, neededInt, neededSSE);
=20
   // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
   // in the registers. If not go to step 7.
@@ -2129,7 +2236,7 @@
     // area, we need to collect the two eightbytes together.
     llvm::Value *RegAddrLo =3D CGF.Builder.CreateGEP(RegAddr, fp_offset);
     llvm::Value *RegAddrHi =3D CGF.Builder.CreateConstGEP1_32(RegAddrLo, 1=
6);
-    llvm::Type *DoubleTy =3D llvm::Type::getDoubleTy(VMContext);
+    llvm::Type *DoubleTy =3D CGF.DoubleTy;
     llvm::Type *DblPtrTy =3D
       llvm::PointerType::getUnqual(DoubleTy);
     llvm::StructType *ST =3D llvm::StructType::get(DoubleTy,
@@ -2192,7 +2299,8 @@
=20
     // FIXME: mingw-w64-gcc emits 128-bit struct as i128
     if (Size =3D=3D 128 &&
-        getContext().getTargetInfo().getTriple().getOS() =3D=3D llvm::Trip=
le::MinGW32)
+        getContext().getTargetInfo().getTriple().getOS()
+          =3D=3D llvm::Triple::MinGW32)
       return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
                                                           Size));
=20
@@ -2224,8 +2332,7 @@
=20
 llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType=
 Ty,
                                       CodeGenFunction &CGF) const {
-  llvm::Type *BP =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
-  llvm::Type *BPP =3D llvm::PointerType::getUnqual(BP);
+  llvm::Type *BPP =3D CGF.Int8PtrPtrTy;
=20
   CGBuilderTy &Builder =3D CGF.Builder;
   llvm::Value *VAListAddrAsBPP =3D Builder.CreateBitCast(VAListAddr, BPP,
@@ -2270,9 +2377,8 @@
   // against gcc output.  AFAIK all ABIs use the same encoding.
=20
   CodeGen::CGBuilderTy &Builder =3D CGF.Builder;
-  llvm::LLVMContext &Context =3D CGF.getLLVMContext();
-
-  llvm::IntegerType *i8 =3D llvm::Type::getInt8Ty(Context);
+
+  llvm::IntegerType *i8 =3D CGF.Int8Ty;
   llvm::Value *Four8 =3D llvm::ConstantInt::get(i8, 4);
   llvm::Value *Eight8 =3D llvm::ConstantInt::get(i8, 8);
   llvm::Value *Sixteen8 =3D llvm::ConstantInt::get(i8, 16);
@@ -2327,8 +2433,9 @@
   ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind)=
 {}
=20
   bool isEABI() const {
-    StringRef Env =3D getContext().getTargetInfo().getTriple().getEnvironm=
entName();
-    return (Env =3D=3D "gnueabi" || Env =3D=3D "eabi");
+    StringRef Env =3D
+      getContext().getTargetInfo().getTriple().getEnvironmentName();
+    return (Env =3D=3D "gnueabi" || Env =3D=3D "eabi" || Env =3D=3D "andro=
ideabi");
   }
=20
 private:
@@ -2362,15 +2469,10 @@
=20
   bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
                                llvm::Value *Address) const {
-    CodeGen::CGBuilderTy &Builder =3D CGF.Builder;
-    llvm::LLVMContext &Context =3D CGF.getLLVMContext();
-
-    llvm::IntegerType *i8 =3D llvm::Type::getInt8Ty(Context);
-    llvm::Value *Four8 =3D llvm::ConstantInt::get(i8, 4);
+    llvm::Value *Four8 =3D llvm::ConstantInt::get(CGF.Int8Ty, 4);
=20
     // 0-15 are the 16 integer registers.
-    AssignToArrayRange(Builder, Address, Four8, 0, 15);
-
+    AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
     return false;
   }
=20
@@ -2671,6 +2773,14 @@
   if (isEmptyRecord(getContext(), RetTy, true))
     return ABIArgInfo::getIgnore();
=20
+  // Check for homogeneous aggregates with AAPCS-VFP.
+  if (getABIKind() =3D=3D AAPCS_VFP) {
+    const Type *Base =3D 0;
+    if (isHomogeneousAggregate(RetTy, Base, getContext()))
+      // Homogeneous Aggregates are returned directly.
+      return ABIArgInfo::getDirect();
+  }
+
   // Aggregates <=3D 4 bytes are returned in r0; other aggregates
   // are returned indirectly.
   uint64_t Size =3D getContext().getTypeSize(RetTy);
@@ -2688,12 +2798,11 @@
=20
 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
                                    CodeGenFunction &CGF) const {
-  llvm::Type *BP =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
-  llvm::Type *BPP =3D llvm::PointerType::getUnqual(BP);
+  llvm::Type *BP =3D CGF.Int8PtrTy;
+  llvm::Type *BPP =3D CGF.Int8PtrPtrTy;
=20
   CGBuilderTy &Builder =3D CGF.Builder;
-  llvm::Value *VAListAddrAsBPP =3D Builder.CreateBitCast(VAListAddr, BPP,
-                                                       "ap");
+  llvm::Value *VAListAddrAsBPP =3D Builder.CreateBitCast(VAListAddr, BPP, =
"ap");
   llvm::Value *Addr =3D Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
   // Handle address alignment for type alignment > 32 bits
   uint64_t TyAlign =3D CGF.getContext().getTypeAlign(Ty) / 8;
@@ -2773,7 +2882,7 @@
=20
   // Calling convention as default by an ABI.
   llvm::CallingConv::ID DefaultCC;
-  const LangOptions &LangOpts =3D getContext().getLangOptions();
+  const LangOptions &LangOpts =3D getContext().getLangOpts();
   if (LangOpts.OpenCL || LangOpts.CUDA) {
     // If we are in OpenCL or CUDA mode, then default to device functions
     DefaultCC =3D llvm::CallingConv::PTX_Device;
@@ -2793,7 +2902,6 @@
 llvm::Value *PTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
                                    CodeGenFunction &CFG) const {
   llvm_unreachable("PTX does not support varargs");
-  return 0;
 }
=20
 void PTXTargetCodeGenInfo::SetTargetAttributes(const Decl *D,
@@ -2805,7 +2913,7 @@
   llvm::Function *F =3D cast<llvm::Function>(GV);
=20
   // Perform special handling in OpenCL mode
-  if (M.getLangOptions().OpenCL) {
+  if (M.getLangOpts().OpenCL) {
     // Use OpenCL function attributes to set proper calling conventions
     // By default, all functions are device functions
     if (FD->hasAttr<OpenCLKernelAttr>()) {
@@ -2817,7 +2925,7 @@
   }
=20
   // Perform special handling in CUDA mode.
-  if (M.getLangOptions().CUDA) {
+  if (M.getLangOpts().CUDA) {
     // CUDA __global__ functions get a kernel calling convention.  Since
     // __global__ functions cannot be called from the device, we do not
     // need to set the noinline attribute.
@@ -2829,85 +2937,6 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// SystemZ ABI Implementation
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-namespace {
-
-class SystemZABIInfo : public ABIInfo {
-public:
-  SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
-
-  bool isPromotableIntegerType(QualType Ty) const;
-
-  ABIArgInfo classifyReturnType(QualType RetTy) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy) const;
-
-  virtual void computeInfo(CGFunctionInfo &FI) const {
-    FI.getReturnInfo() =3D classifyReturnType(FI.getReturnType());
-    for (CGFunctionInfo::arg_iterator it =3D FI.arg_begin(), ie =3D FI.arg=
_end();
-         it !=3D ie; ++it)
-      it->info =3D classifyArgumentType(it->type);
-  }
-
-  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
-                                 CodeGenFunction &CGF) const;
-};
-
-class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
-public:
-  SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
-    : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
-};
-
-}
-
-bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
-  // SystemZ ABI requires all 8, 16 and 32 bit quantities to be extended.
-  if (const BuiltinType *BT =3D Ty->getAs<BuiltinType>())
-    switch (BT->getKind()) {
-    case BuiltinType::Bool:
-    case BuiltinType::Char_S:
-    case BuiltinType::Char_U:
-    case BuiltinType::SChar:
-    case BuiltinType::UChar:
-    case BuiltinType::Short:
-    case BuiltinType::UShort:
-    case BuiltinType::Int:
-    case BuiltinType::UInt:
-      return true;
-    default:
-      return false;
-    }
-  return false;
-}
-
-llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType T=
y,
-                                       CodeGenFunction &CGF) const {
-  // FIXME: Implement
-  return 0;
-}
-
-
-ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
-  if (RetTy->isVoidType())
-    return ABIArgInfo::getIgnore();
-  if (isAggregateTypeForABI(RetTy))
-    return ABIArgInfo::getIndirect(0);
-
-  return (isPromotableIntegerType(RetTy) ?
-          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
-}
-
-ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
-  if (isAggregateTypeForABI(Ty))
-    return ABIArgInfo::getIndirect(0);
-
-  return (isPromotableIntegerType(Ty) ?
-          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // MBlaze ABI Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -3063,24 +3092,28 @@
=20
 namespace {
 class MipsABIInfo : public ABIInfo {
-  static const unsigned MinABIStackAlignInBytes =3D 4;
+  bool IsO32;
+  unsigned MinABIStackAlignInBytes;
+  llvm::Type* HandleAggregates(QualType Ty) const;
+  llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
+  llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
 public:
-  MipsABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
+  MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
+    ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8) {}
=20
   ABIArgInfo classifyReturnType(QualType RetTy) const;
-  ABIArgInfo classifyArgumentType(QualType RetTy) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
   virtual void computeInfo(CGFunctionInfo &FI) const;
   virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
                                  CodeGenFunction &CGF) const;
 };
=20
-const unsigned MipsABIInfo::MinABIStackAlignInBytes;
-
 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
   unsigned SizeOfUnwindException;
 public:
-  MIPSTargetCodeGenInfo(CodeGenTypes &CGT, unsigned SZ)
-    : TargetCodeGenInfo(new MipsABIInfo(CGT)), SizeOfUnwindException(SZ) {}
+  MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
+    : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
+      SizeOfUnwindException(IsO32 ? 24 : 32) {}
=20
   int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
     return 29;
@@ -3095,35 +3128,184 @@
 };
 }
=20
-ABIArgInfo MipsABIInfo::classifyArgumentType(QualType Ty) const {
+// In N32/64, an aligned double precision floating point field is passed in
+// a register.
+llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty) const {
+  if (IsO32)
+    return 0;
+
+  if (Ty->isComplexType())
+    return CGT.ConvertType(Ty);
+
+  const RecordType *RT =3D Ty->getAs<RecordType>();
+
+  // Unions are passed in integer registers.
+  if (!RT || !RT->isStructureOrClassType())
+    return 0;
+
+  const RecordDecl *RD =3D RT->getDecl();
+  const ASTRecordLayout &Layout =3D getContext().getASTRecordLayout(RD);
+  uint64_t StructSize =3D getContext().getTypeSize(Ty);
+  assert(!(StructSize % 8) && "Size of structure must be multiple of 8.");
+ =20
+  uint64_t LastOffset =3D 0;
+  unsigned idx =3D 0;
+  llvm::IntegerType *I64 =3D llvm::IntegerType::get(getVMContext(), 64);
+  SmallVector<llvm::Type*, 8> ArgList;
+
+  // Iterate over fields in the struct/class and check if there are any al=
igned
+  // double fields.
+  for (RecordDecl::field_iterator i =3D RD->field_begin(), e =3D RD->field=
_end();
+       i !=3D e; ++i, ++idx) {
+    const QualType Ty =3D (*i)->getType();
+    const BuiltinType *BT =3D Ty->getAs<BuiltinType>();
+
+    if (!BT || BT->getKind() !=3D BuiltinType::Double)
+      continue;
+
+    uint64_t Offset =3D Layout.getFieldOffset(idx);
+    if (Offset % 64) // Ignore doubles that are not aligned.
+      continue;
+
+    // Add ((Offset - LastOffset) / 64) args of type i64.
+    for (unsigned j =3D (Offset - LastOffset) / 64; j > 0; --j)
+      ArgList.push_back(I64);
+
+    // Add double type.
+    ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
+    LastOffset =3D Offset + 64;
+  }
+
+  // This struct/class doesn't have an aligned double field.
+  if (!LastOffset)
+    return 0;
+
+  // Add ((StructSize - LastOffset) / 64) args of type i64.
+  for (unsigned N =3D (StructSize - LastOffset) / 64; N; --N)
+    ArgList.push_back(I64);
+
+  // If the size of the remainder is not zero, add one more integer type to
+  // ArgList.
+  unsigned R =3D (StructSize - LastOffset) % 64;
+  if (R)
+    ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
+
+  return llvm::StructType::get(getVMContext(), ArgList);
+}
+
+llvm::Type *MipsABIInfo::getPaddingType(uint64_t Align, uint64_t Offset) c=
onst {
+  // Padding is inserted only for N32/64.
+  if (IsO32)
+    return 0;
+
+  assert(Align <=3D 16 && "Alignment larger than 16 not handled.");
+  return (Align =3D=3D 16 && Offset & 0xf) ?
+    llvm::IntegerType::get(getVMContext(), 64) : 0;
+}
+
+ABIArgInfo
+MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
+  uint64_t OrigOffset =3D Offset;
+  uint64_t TySize =3D
+    llvm::RoundUpToAlignment(getContext().getTypeSize(Ty), 64) / 8;
+  uint64_t Align =3D getContext().getTypeAlign(Ty) / 8;
+  Offset =3D llvm::RoundUpToAlignment(Offset, std::max(Align, (uint64_t)8)=
);
+  Offset +=3D TySize;
+
   if (isAggregateTypeForABI(Ty)) {
     // Ignore empty aggregates.
-    if (getContext().getTypeSize(Ty) =3D=3D 0)
+    if (TySize =3D=3D 0)
       return ABIArgInfo::getIgnore();
=20
     // Records with non trivial destructors/constructors should not be pas=
sed
     // by value.
-    if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
+    if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) {
+      Offset =3D OrigOffset + 8;
       return ABIArgInfo::getIndirect(0, /*ByVal=3D*/false);
-
-    return ABIArgInfo::getIndirect(0);
+    }
+
+    // If we have reached here, aggregates are passed either indirectly vi=
a a
+    // byval pointer or directly by coercing to another structure type. In=
 the
+    // latter case, padding is inserted if the offset of the aggregate is
+    // unaligned.
+    llvm::Type *ResType =3D HandleAggregates(Ty);
+
+    if (!ResType)
+      return ABIArgInfo::getIndirect(0);
+
+    return ABIArgInfo::getDirect(ResType, 0, getPaddingType(Align, OrigOff=
set));
   }
=20
   // Treat an enum type as its underlying type.
   if (const EnumType *EnumTy =3D Ty->getAs<EnumType>())
     Ty =3D EnumTy->getDecl()->getIntegerType();
=20
-  return (Ty->isPromotableIntegerType() ?
-          ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
+  if (Ty->isPromotableIntegerType())
+    return ABIArgInfo::getExtend();
+
+  return ABIArgInfo::getDirect(0, 0, getPaddingType(Align, OrigOffset));
 }
=20
+llvm::Type*
+MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
+  const RecordType *RT =3D RetTy->getAs<RecordType>();
+  SmallVector<llvm::Type*, 2> RTList;
+
+  if (RT && RT->isStructureOrClassType()) {
+    const RecordDecl *RD =3D RT->getDecl();
+    const ASTRecordLayout &Layout =3D getContext().getASTRecordLayout(RD);
+    unsigned FieldCnt =3D Layout.getFieldCount();
+
+    // N32/64 returns struct/classes in floating point registers if the
+    // following conditions are met:
+    // 1. The size of the struct/class is no larger than 128-bit.
+    // 2. The struct/class has one or two fields all of which are floating
+    //    point types.
+    // 3. The offset of the first field is zero (this follows what gcc doe=
s).=20
+    //
+    // Any other composite results are returned in integer registers.
+    //
+    if (FieldCnt && (FieldCnt <=3D 2) && !Layout.getFieldOffset(0)) {
+      RecordDecl::field_iterator b =3D RD->field_begin(), e =3D RD->field_=
end();
+      for (; b !=3D e; ++b) {
+        const BuiltinType *BT =3D (*b)->getType()->getAs<BuiltinType>();
+
+        if (!BT || !BT->isFloatingPoint())
+          break;
+
+        RTList.push_back(CGT.ConvertType((*b)->getType()));
+      }
+
+      if (b =3D=3D e)
+        return llvm::StructType::get(getVMContext(), RTList,
+                                     RD->hasAttr<PackedAttr>());
+
+      RTList.clear();
+    }
+  }
+
+  RTList.push_back(llvm::IntegerType::get(getVMContext(),
+                                          std::min(Size, (uint64_t)64)));
+  if (Size > 64)
+    RTList.push_back(llvm::IntegerType::get(getVMContext(), Size - 64));
+
+  return llvm::StructType::get(getVMContext(), RTList);
+}
+
 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
-  if (RetTy->isVoidType())
+  uint64_t Size =3D getContext().getTypeSize(RetTy);
+
+  if (RetTy->isVoidType() || Size =3D=3D 0)
     return ABIArgInfo::getIgnore();
=20
   if (isAggregateTypeForABI(RetTy)) {
-    if (RetTy->isAnyComplexType())
-      return ABIArgInfo::getDirect();
+    if (Size <=3D 128) {
+      if (RetTy->isAnyComplexType())
+        return ABIArgInfo::getDirect();
+
+      if (!IsO32 && !isRecordWithNonTrivialDestructorOrCopyConstructor(Ret=
Ty))
+        return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
+    }
=20
     return ABIArgInfo::getIndirect(0);
   }
@@ -3137,148 +3319,284 @@
 }
=20
 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
+  ABIArgInfo &RetInfo =3D FI.getReturnInfo();
+  RetInfo =3D classifyReturnType(FI.getReturnType());
+
+  // Check if a pointer to an aggregate is passed as a hidden argument. =20
+  uint64_t Offset =3D RetInfo.isIndirect() ? 8 : 0;
+
+  for (CGFunctionInfo::arg_iterator it =3D FI.arg_begin(), ie =3D FI.arg_e=
nd();
+       it !=3D ie; ++it)
+    it->info =3D classifyArgumentType(it->type, Offset);
+}
+
+llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
+                                    CodeGenFunction &CGF) const {
+  llvm::Type *BP =3D CGF.Int8PtrTy;
+  llvm::Type *BPP =3D CGF.Int8PtrPtrTy;
+=20
+  CGBuilderTy &Builder =3D CGF.Builder;
+  llvm::Value *VAListAddrAsBPP =3D Builder.CreateBitCast(VAListAddr, BPP, =
"ap");
+  llvm::Value *Addr =3D Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
+  int64_t TypeAlign =3D getContext().getTypeAlign(Ty) / 8;
+  llvm::Type *PTy =3D llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
+  llvm::Value *AddrTyped;
+  unsigned PtrWidth =3D getContext().getTargetInfo().getPointerWidth(0);
+  llvm::IntegerType *IntTy =3D (PtrWidth =3D=3D 32) ? CGF.Int32Ty : CGF.In=
t64Ty;
+
+  if (TypeAlign > MinABIStackAlignInBytes) {
+    llvm::Value *AddrAsInt =3D CGF.Builder.CreatePtrToInt(Addr, IntTy);
+    llvm::Value *Inc =3D llvm::ConstantInt::get(IntTy, TypeAlign - 1);
+    llvm::Value *Mask =3D llvm::ConstantInt::get(IntTy, -TypeAlign);
+    llvm::Value *Add =3D CGF.Builder.CreateAdd(AddrAsInt, Inc);
+    llvm::Value *And =3D CGF.Builder.CreateAnd(Add, Mask);
+    AddrTyped =3D CGF.Builder.CreateIntToPtr(And, PTy);
+  }
+  else
+    AddrTyped =3D Builder.CreateBitCast(Addr, PTy); =20
+
+  llvm::Value *AlignedAddr =3D Builder.CreateBitCast(AddrTyped, BP);
+  TypeAlign =3D std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
+  uint64_t Offset =3D
+    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAli=
gn);
+  llvm::Value *NextAddr =3D
+    Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
+                      "ap.next");
+  Builder.CreateStore(NextAddr, VAListAddrAsBPP);
+ =20
+  return AddrTyped;
+}
+
+bool
+MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &C=
GF,
+                                               llvm::Value *Address) const=
 {
+  // This information comes from gcc's implementation, which seems to
+  // as canonical as it gets.
+
+  // Everything on MIPS is 4 bytes.  Double-precision FP registers
+  // are aliased to pairs of single-precision FP registers.
+  llvm::Value *Four8 =3D llvm::ConstantInt::get(CGF.Int8Ty, 4);
+
+  // 0-31 are the general purpose registers, $0 - $31.
+  // 32-63 are the floating-point registers, $f0 - $f31.
+  // 64 and 65 are the multiply/divide registers, $hi and $lo.
+  // 66 is the (notional, I think) register for signal-handler return.
+  AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
+
+  // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
+  // They are one bit wide and ignored here.
+
+  // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
+  // (coprocessor 1 is the FP unit)
+  // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
+  // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
+  // 176-181 are the DSP accumulator registers.
+  AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
+  return false;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defa=
ults.
+// Currently subclassed only to implement custom OpenCL C function attribu=
te=20
+// handling.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+
+class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
+public:
+  TCETargetCodeGenInfo(CodeGenTypes &CGT)
+    : DefaultTargetCodeGenInfo(CGT) {}
+
+  virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
+                                   CodeGen::CodeGenModule &M) const;
+};
+
+void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
+                                               llvm::GlobalValue *GV,
+                                               CodeGen::CodeGenModule &M) =
const {
+  const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D);
+  if (!FD) return;
+
+  llvm::Function *F =3D cast<llvm::Function>(GV);
+ =20
+  if (M.getLangOpts().OpenCL) {
+    if (FD->hasAttr<OpenCLKernelAttr>()) {
+      // OpenCL C Kernel functions are not subject to inlining
+      F->addFnAttr(llvm::Attribute::NoInline);
+         =20
+      if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
+
+        // Convert the reqd_work_group_size() attributes to metadata.
+        llvm::LLVMContext &Context =3D F->getContext();
+        llvm::NamedMDNode *OpenCLMetadata =3D=20
+            M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_=
info");
+
+        SmallVector<llvm::Value*, 5> Operands;
+        Operands.push_back(F);
+
+        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,=20
+                             llvm::APInt(32,=20
+                             FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim=
())));
+        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
+                             llvm::APInt(32,
+                               FD->getAttr<ReqdWorkGroupSizeAttr>()->getYD=
im())));
+        Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,=20
+                             llvm::APInt(32,=20
+                               FD->getAttr<ReqdWorkGroupSizeAttr>()->getZD=
im())));
+
+        // Add a boolean constant operand for "required" (true) or "hint" =
(false)
+        // for implementing the work_group_size_hint attr later. Currently=20
+        // always true as the hint is not yet implemented.
+        Operands.push_back(llvm::ConstantInt::getTrue(Context));
+        OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
+      }
+    }
+  }
+}
+
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Hexagon ABI Implementation
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+
+class HexagonABIInfo : public ABIInfo {
+
+
+public:
+  HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
+
+private:
+
+  ABIArgInfo classifyReturnType(QualType RetTy) const;
+  ABIArgInfo classifyArgumentType(QualType RetTy) const;
+
+  virtual void computeInfo(CGFunctionInfo &FI) const;
+
+  virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
+                                 CodeGenFunction &CGF) const;
+};
+
+class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
+public:
+  HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
+    :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
+
+  int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
+    return 29;
+  }
+};
+
+}
+
+void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
   FI.getReturnInfo() =3D classifyReturnType(FI.getReturnType());
   for (CGFunctionInfo::arg_iterator it =3D FI.arg_begin(), ie =3D FI.arg_e=
nd();
        it !=3D ie; ++it)
     it->info =3D classifyArgumentType(it->type);
 }
=20
-llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
-                                    CodeGenFunction &CGF) const {
-  llvm::Type *BP =3D llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
-  llvm::Type *BPP =3D llvm::PointerType::getUnqual(BP);
-=20
+ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
+  if (!isAggregateTypeForABI(Ty)) {
+    // Treat an enum type as its underlying type.
+    if (const EnumType *EnumTy =3D Ty->getAs<EnumType>())
+      Ty =3D EnumTy->getDecl()->getIntegerType();
+
+    return (Ty->isPromotableIntegerType() ?
+            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
+  }
+
+  // Ignore empty records.
+  if (isEmptyRecord(getContext(), Ty, true))
+    return ABIArgInfo::getIgnore();
+
+  // Structures with either a non-trivial destructor or a non-trivial
+  // copy constructor are always indirect.
+  if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
+    return ABIArgInfo::getIndirect(0, /*ByVal=3D*/false);
+
+  uint64_t Size =3D getContext().getTypeSize(Ty);
+  if (Size > 64)
+    return ABIArgInfo::getIndirect(0, /*ByVal=3D*/true);
+    // Pass in the smallest viable integer type.
+  else if (Size > 32)
+      return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
+  else if (Size > 16)
+      return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
+  else if (Size > 8)
+      return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
+  else
+      return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
+}
+
+ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
+  if (RetTy->isVoidType())
+    return ABIArgInfo::getIgnore();
+
+  // Large vector types should be returned via memory.
+  if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
+    return ABIArgInfo::getIndirect(0);
+
+  if (!isAggregateTypeForABI(RetTy)) {
+    // Treat an enum type as its underlying type.
+    if (const EnumType *EnumTy =3D RetTy->getAs<EnumType>())
+      RetTy =3D EnumTy->getDecl()->getIntegerType();
+
+    return (RetTy->isPromotableIntegerType() ?
+            ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
+  }
+
+  // Structures with either a non-trivial destructor or a non-trivial
+  // copy constructor are always indirect.
+  if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
+    return ABIArgInfo::getIndirect(0, /*ByVal=3D*/false);
+
+  if (isEmptyRecord(getContext(), RetTy, true))
+    return ABIArgInfo::getIgnore();
+
+  // Aggregates <=3D 8 bytes are returned in r0; other aggregates
+  // are returned indirectly.
+  uint64_t Size =3D getContext().getTypeSize(RetTy);
+  if (Size <=3D 64) {
+    // Return in the smallest viable integer type.
+    if (Size <=3D 8)
+      return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
+    if (Size <=3D 16)
+      return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
+    if (Size <=3D 32)
+      return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
+    return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
+  }
+
+  return ABIArgInfo::getIndirect(0, /*ByVal=3D*/true);
+}
+
+llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType T=
y,
+                                       CodeGenFunction &CGF) const {
+  // FIXME: Need to handle alignment
+  llvm::Type *BPP =3D CGF.Int8PtrPtrTy;
+
   CGBuilderTy &Builder =3D CGF.Builder;
-  llvm::Value *VAListAddrAsBPP =3D Builder.CreateBitCast(VAListAddr, BPP, =
"ap");
+  llvm::Value *VAListAddrAsBPP =3D Builder.CreateBitCast(VAListAddr, BPP,
+                                                       "ap");
   llvm::Value *Addr =3D Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
-  unsigned TypeAlign =3D getContext().getTypeAlign(Ty) / 8;
-  llvm::Type *PTy =3D llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
-  llvm::Value *AddrTyped;
-
-  if (TypeAlign > MinABIStackAlignInBytes) {
-    llvm::Value *AddrAsInt32 =3D CGF.Builder.CreatePtrToInt(Addr, CGF.Int3=
2Ty);
-    llvm::Value *Inc =3D llvm::ConstantInt::get(CGF.Int32Ty, TypeAlign - 1=
);
-    llvm::Value *Mask =3D llvm::ConstantInt::get(CGF.Int32Ty, -TypeAlign);
-    llvm::Value *Add =3D CGF.Builder.CreateAdd(AddrAsInt32, Inc);
-    llvm::Value *And =3D CGF.Builder.CreateAnd(Add, Mask);
-    AddrTyped =3D CGF.Builder.CreateIntToPtr(And, PTy);
-  }
-  else
-    AddrTyped =3D Builder.CreateBitCast(Addr, PTy); =20
-
-  llvm::Value *AlignedAddr =3D Builder.CreateBitCast(AddrTyped, BP);
-  TypeAlign =3D std::max(TypeAlign, MinABIStackAlignInBytes);
+  llvm::Type *PTy =3D
+    llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
+  llvm::Value *AddrTyped =3D Builder.CreateBitCast(Addr, PTy);
+
   uint64_t Offset =3D
-    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAli=
gn);
+    llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
   llvm::Value *NextAddr =3D
-    Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(CGF.Int32Ty, Off=
set),
+    Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
                       "ap.next");
   Builder.CreateStore(NextAddr, VAListAddrAsBPP);
- =20
+
   return AddrTyped;
 }
=20
-bool
-MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &C=
GF,
-                                               llvm::Value *Address) const=
 {
-  // This information comes from gcc's implementation, which seems to
-  // as canonical as it gets.
-
-  CodeGen::CGBuilderTy &Builder =3D CGF.Builder;
-  llvm::LLVMContext &Context =3D CGF.getLLVMContext();
-
-  // Everything on MIPS is 4 bytes.  Double-precision FP registers
-  // are aliased to pairs of single-precision FP registers.
-  llvm::IntegerType *i8 =3D llvm::Type::getInt8Ty(Context);
-  llvm::Value *Four8 =3D llvm::ConstantInt::get(i8, 4);
-
-  // 0-31 are the general purpose registers, $0 - $31.
-  // 32-63 are the floating-point registers, $f0 - $f31.
-  // 64 and 65 are the multiply/divide registers, $hi and $lo.
-  // 66 is the (notional, I think) register for signal-handler return.
-  AssignToArrayRange(Builder, Address, Four8, 0, 65);
-
-  // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
-  // They are one bit wide and ignored here.
-
-  // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
-  // (coprocessor 1 is the FP unit)
-  // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
-  // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
-  // 176-181 are the DSP accumulator registers.
-  AssignToArrayRange(Builder, Address, Four8, 80, 181);
-
-  return false;
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defa=
ults.
-// Currently subclassed only to implement custom OpenCL C function attribu=
te=20
-// handling.
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-namespace {
-
-class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
-public:
-  TCETargetCodeGenInfo(CodeGenTypes &CGT)
-    : DefaultTargetCodeGenInfo(CGT) {}
-
-  virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
-                                   CodeGen::CodeGenModule &M) const;
-};
-
-void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
-                                               llvm::GlobalValue *GV,
-                                               CodeGen::CodeGenModule &M) =
const {
-  const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D);
-  if (!FD) return;
-
-  llvm::Function *F =3D cast<llvm::Function>(GV);
- =20
-  if (M.getLangOptions().OpenCL) {
-    if (FD->hasAttr<OpenCLKernelAttr>()) {
-      // OpenCL C Kernel functions are not subject to inlining
-      F->addFnAttr(llvm::Attribute::NoInline);
-         =20
-      if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
-
-        // Convert the reqd_work_group_size() attributes to metadata.
-        llvm::LLVMContext &Context =3D F->getContext();
-        llvm::NamedMDNode *OpenCLMetadata =3D=20
-            M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_=
info");
-
-        SmallVector<llvm::Value*, 5> Operands;
-        Operands.push_back(F);
-
-        Operands.push_back(llvm::Constant::getIntegerValue(
-                             llvm::Type::getInt32Ty(Context),=20
-                             llvm::APInt(
-                               32,=20
-                               FD->getAttr<ReqdWorkGroupSizeAttr>()->getXD=
im())));
-        Operands.push_back(llvm::Constant::getIntegerValue(
-                             llvm::Type::getInt32Ty(Context),=20
-                             llvm::APInt(
-                               32,
-                               FD->getAttr<ReqdWorkGroupSizeAttr>()->getYD=
im())));
-        Operands.push_back(llvm::Constant::getIntegerValue(
-                             llvm::Type::getInt32Ty(Context),=20
-                             llvm::APInt(
-                               32,=20
-                               FD->getAttr<ReqdWorkGroupSizeAttr>()->getZD=
im())));
-
-        // Add a boolean constant operand for "required" (true) or "hint" =
(false)
-        // for implementing the work_group_size_hint attr later. Currently=20
-        // always true as the hint is not yet implemented.
-        Operands.push_back(llvm::ConstantInt::getTrue(llvm::Type::getInt1T=
y(Context)));
-
-        OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
-      }
-    }
-  }
-}
-
-}
=20
 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
   if (TheTargetCodeGenInfo)
@@ -3291,11 +3609,11 @@
=20
   case llvm::Triple::mips:
   case llvm::Triple::mipsel:
-    return *(TheTargetCodeGenInfo =3D new MIPSTargetCodeGenInfo(Types, 24)=
);
+    return *(TheTargetCodeGenInfo =3D new MIPSTargetCodeGenInfo(Types, tru=
e));
=20
   case llvm::Triple::mips64:
   case llvm::Triple::mips64el:
-    return *(TheTargetCodeGenInfo =3D new MIPSTargetCodeGenInfo(Types, 32)=
);
+    return *(TheTargetCodeGenInfo =3D new MIPSTargetCodeGenInfo(Types, fal=
se));
=20
   case llvm::Triple::arm:
   case llvm::Triple::thumb:
@@ -3317,9 +3635,6 @@
   case llvm::Triple::ptx64:
     return *(TheTargetCodeGenInfo =3D new PTXTargetCodeGenInfo(Types));
=20
-  case llvm::Triple::systemz:
-    return *(TheTargetCodeGenInfo =3D new SystemZTargetCodeGenInfo(Types));
-
   case llvm::Triple::mblaze:
     return *(TheTargetCodeGenInfo =3D new MBlazeTargetCodeGenInfo(Types));
=20
@@ -3334,7 +3649,8 @@
=20
     if (Triple.isOSDarwin())
       return *(TheTargetCodeGenInfo =3D
-               new X86_32TargetCodeGenInfo(Types, true, true, DisableMMX));
+               new X86_32TargetCodeGenInfo(
+                 Types, true, true, DisableMMX, false));
=20
     switch (Triple.getOS()) {
     case llvm::Triple::Cygwin:
@@ -3343,24 +3659,36 @@
     case llvm::Triple::DragonFly:
     case llvm::Triple::FreeBSD:
     case llvm::Triple::OpenBSD:
-    case llvm::Triple::NetBSD:
       return *(TheTargetCodeGenInfo =3D
-               new X86_32TargetCodeGenInfo(Types, false, true, DisableMMX)=
);
+               new X86_32TargetCodeGenInfo(
+                 Types, false, true, DisableMMX, false));
+
+    case llvm::Triple::Win32:
+      return *(TheTargetCodeGenInfo =3D
+               new X86_32TargetCodeGenInfo(
+                 Types, false, true, DisableMMX, true));
=20
     default:
       return *(TheTargetCodeGenInfo =3D
-               new X86_32TargetCodeGenInfo(Types, false, false, DisableMMX=
));
+               new X86_32TargetCodeGenInfo(
+                 Types, false, false, DisableMMX, false));
     }
   }
=20
-  case llvm::Triple::x86_64:
+  case llvm::Triple::x86_64: {
+    bool HasAVX =3D strcmp(getContext().getTargetInfo().getABI(), "avx") =
=3D=3D 0;
+
     switch (Triple.getOS()) {
     case llvm::Triple::Win32:
     case llvm::Triple::MinGW32:
     case llvm::Triple::Cygwin:
       return *(TheTargetCodeGenInfo =3D new WinX86_64TargetCodeGenInfo(Typ=
es));
     default:
-      return *(TheTargetCodeGenInfo =3D new X86_64TargetCodeGenInfo(Types)=
);
+      return *(TheTargetCodeGenInfo =3D new X86_64TargetCodeGenInfo(Types,
+                                                                  HasAVX));
     }
   }
+  case llvm::Triple::hexagon:
+    return *(TheTargetCodeGenInfo =3D new HexagonTargetCodeGenInfo(Types));
+  }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Code=
Gen/TargetInfo.h
--- a/head/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/CodeGen/TargetInfo.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -30,8 +30,10 @@
   class Decl;
=20
   namespace CodeGen {
+    class CallArgList;
     class CodeGenModule;
     class CodeGenFunction;
+    class CGFunctionInfo;
   }
=20
   /// TargetCodeGenInfo - This class organizes various target-specific
@@ -160,7 +162,8 @@
     /// same way and some out-of-band information is passed for the
     /// benefit of variadic callees, as is the case for x86-64.
     /// In this case the ABI should be consulted.
-    virtual bool isNoProtoCallVariadic(CallingConv CC) const;
+    virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args,
+                                       const FunctionNoProtoType *fnType) =
const;
   };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Action.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Action.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Action.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -27,6 +27,7 @@
   case PreprocessJobClass: return "preprocessor";
   case PrecompileJobClass: return "precompiler";
   case AnalyzeJobClass: return "analyzer";
+  case MigrateJobClass: return "migrator";
   case CompileJobClass: return "compiler";
   case AssembleJobClass: return "assembler";
   case LinkJobClass: return "linker";
@@ -38,14 +39,20 @@
   llvm_unreachable("invalid class");
 }
=20
+void InputAction::anchor() {}
+
 InputAction::InputAction(const Arg &_Input, types::ID _Type)
   : Action(InputClass, _Type), Input(_Input) {
 }
=20
+void BindArchAction::anchor() {}
+
 BindArchAction::BindArchAction(Action *Input, const char *_ArchName)
   : Action(BindArchClass, Input, Input->getType()), ArchName(_ArchName) {
 }
=20
+void JobAction::anchor() {}
+
 JobAction::JobAction(ActionClass Kind, Action *Input, types::ID Type)
   : Action(Kind, Input, Type) {
 }
@@ -54,38 +61,62 @@
   : Action(Kind, Inputs, Type) {
 }
=20
+void PreprocessJobAction::anchor() {}
+
 PreprocessJobAction::PreprocessJobAction(Action *Input, types::ID OutputTy=
pe)
   : JobAction(PreprocessJobClass, Input, OutputType) {
 }
=20
+void PrecompileJobAction::anchor() {}
+
 PrecompileJobAction::PrecompileJobAction(Action *Input, types::ID OutputTy=
pe)
   : JobAction(PrecompileJobClass, Input, OutputType) {
 }
=20
+void AnalyzeJobAction::anchor() {}
+
 AnalyzeJobAction::AnalyzeJobAction(Action *Input, types::ID OutputType)
   : JobAction(AnalyzeJobClass, Input, OutputType) {
 }
=20
+void MigrateJobAction::anchor() {}
+
+MigrateJobAction::MigrateJobAction(Action *Input, types::ID OutputType)
+  : JobAction(MigrateJobClass, Input, OutputType) {
+}
+
+void CompileJobAction::anchor() {}
+
 CompileJobAction::CompileJobAction(Action *Input, types::ID OutputType)
   : JobAction(CompileJobClass, Input, OutputType) {
 }
=20
+void AssembleJobAction::anchor() {}
+
 AssembleJobAction::AssembleJobAction(Action *Input, types::ID OutputType)
   : JobAction(AssembleJobClass, Input, OutputType) {
 }
=20
+void LinkJobAction::anchor() {}
+
 LinkJobAction::LinkJobAction(ActionList &Inputs, types::ID Type)
   : JobAction(LinkJobClass, Inputs, Type) {
 }
=20
+void LipoJobAction::anchor() {}
+
 LipoJobAction::LipoJobAction(ActionList &Inputs, types::ID Type)
   : JobAction(LipoJobClass, Inputs, Type) {
 }
=20
+void DsymutilJobAction::anchor() {}
+
 DsymutilJobAction::DsymutilJobAction(ActionList &Inputs, types::ID Type)
   : JobAction(DsymutilJobClass, Inputs, Type) {
 }
=20
+void VerifyJobAction::anchor() {}
+
 VerifyJobAction::VerifyJobAction(ActionList &Inputs, types::ID Type)
   : JobAction(VerifyJobClass, Inputs, Type) {
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Arg.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Arg.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Arg.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -61,7 +61,7 @@
 }
=20
 std::string Arg::getAsString(const ArgList &Args) const {
-  llvm::SmallString<256> Res;
+  SmallString<256> Res;
   llvm::raw_svector_ostream OS(Res);
=20
   ArgStringList ASL;
@@ -94,7 +94,7 @@
     break;
=20
   case Option::RenderCommaJoinedStyle: {
-    llvm::SmallString<256> Res;
+    SmallString<256> Res;
     llvm::raw_svector_ostream OS(Res);
     OS << getOption().getName();
     for (unsigned i =3D 0, e =3D getNumValues(); i !=3D e; ++i) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/ArgList.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/ArgList.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/ArgList.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -122,6 +122,24 @@
   return Res;
 }
=20
+Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1,
+                         OptSpecifier Id2, OptSpecifier Id3,
+                         OptSpecifier Id4) const {
+  Arg *Res =3D 0;
+  for (const_iterator it =3D begin(), ie =3D end(); it !=3D ie; ++it) {
+    if ((*it)->getOption().matches(Id0) ||
+        (*it)->getOption().matches(Id1) ||
+        (*it)->getOption().matches(Id2) ||
+        (*it)->getOption().matches(Id3) ||
+        (*it)->getOption().matches(Id4)) {
+      Res =3D *it;
+      Res->claim();
+    }
+  }
+
+  return Res;
+}
+
 bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) co=
nst {
   if (Arg *A =3D getLastArg(Pos, Neg))
     return A->getOption().matches(Pos);
@@ -136,13 +154,15 @@
 }
=20
 int ArgList::getLastArgIntValue(OptSpecifier Id, int Default,
-                                clang::DiagnosticsEngine &Diags) const {
+                                clang::DiagnosticsEngine *Diags) const {
   int Res =3D Default;
=20
   if (Arg *A =3D getLastArg(Id)) {
-    if (StringRef(A->getValue(*this)).getAsInteger(10, Res))
-      Diags.Report(diag::err_drv_invalid_int_value)
-        << A->getAsString(*this) << A->getValue(*this);
+    if (StringRef(A->getValue(*this)).getAsInteger(10, Res)) {
+      if (Diags)
+        Diags->Report(diag::err_drv_invalid_int_value)
+          << A->getAsString(*this) << A->getValue(*this);
+    }
   }
=20
   return Res;
@@ -210,7 +230,7 @@
 }
=20
 const char *ArgList::MakeArgString(const Twine &T) const {
-  llvm::SmallString<256> Str;
+  SmallString<256> Str;
   T.toVector(Str);
   return MakeArgString(Str.str());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/CC1AsOptions.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/CC1AsOptions.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/CC1AsOptions.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -18,7 +18,7 @@
 static const OptTable::Info CC1AsInfoTable[] =3D {
 #define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
                HELPTEXT, METAVAR)   \
-  { NAME, HELPTEXT, METAVAR, Option::KIND##Class, FLAGS, PARAM, \
+  { NAME, HELPTEXT, METAVAR, Option::KIND##Class, PARAM, FLAGS, \
     OPT_##GROUP, OPT_##ALIAS },
 #include "clang/Driver/CC1AsOptions.inc"
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/CC1Options.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/CC1Options.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/CC1Options.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -18,7 +18,7 @@
 static const OptTable::Info CC1InfoTable[] =3D {
 #define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
                HELPTEXT, METAVAR)   \
-  { NAME, HELPTEXT, METAVAR, Option::KIND##Class, FLAGS, PARAM, \
+  { NAME, HELPTEXT, METAVAR, Option::KIND##Class, PARAM, FLAGS, \
     OPT_##GROUP, OPT_##ALIAS },
 #include "clang/Driver/CC1Options.inc"
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Compilation.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -217,8 +217,12 @@
=20
   // Remove any user specified output.  Claim any unclaimed arguments, so =
as
   // to avoid emitting warnings about unused args.
-  if (TranslatedArgs->hasArg(options::OPT_o))
-    TranslatedArgs->eraseArg(options::OPT_o);
+  OptSpecifier OutputOpts[] =3D { options::OPT_o, options::OPT_MD,
+                                options::OPT_MMD };
+  for (unsigned i =3D 0; i !=3D sizeof(OutputOpts)/sizeof(OutputOpts[0]); =
++i) {
+    if (TranslatedArgs->hasArg(OutputOpts[i]))
+      TranslatedArgs->eraseArg(OutputOpts[i]);
+  }
   TranslatedArgs->ClaimAllArgs();
=20
   // Redirect stdout/stderr to /dev/null.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Driver.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Driver.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Driver.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -7,10 +7,6 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#ifdef HAVE_CLANG_CONFIG_H
-# include "clang/Config/config.h"
-#endif
-
 #include "clang/Driver/Driver.h"
=20
 #include "clang/Driver/Action.h"
@@ -18,7 +14,6 @@
 #include "clang/Driver/ArgList.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/DriverDiagnostic.h"
-#include "clang/Driver/HostInfo.h"
 #include "clang/Driver/Job.h"
 #include "clang/Driver/OptTable.h"
 #include "clang/Driver/Option.h"
@@ -28,7 +23,6 @@
=20
 #include "clang/Basic/Version.h"
=20
-#include "llvm/Config/config.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/ADT/OwningPtr.h"
@@ -40,22 +34,25 @@
 #include "llvm/Support/Program.h"
=20
 #include "InputInfo.h"
+#include "ToolChains.h"
=20
 #include <map>
=20
+#include "clang/Config/config.h"
+
 using namespace clang::driver;
 using namespace clang;
=20
 Driver::Driver(StringRef ClangExecutable,
-               StringRef DefaultHostTriple,
+               StringRef DefaultTargetTriple,
                StringRef DefaultImageName,
                bool IsProduction,
                DiagnosticsEngine &Diags)
   : Opts(createDriverOptTable()), Diags(Diags),
     ClangExecutable(ClangExecutable), UseStdLib(true),
-    DefaultHostTriple(DefaultHostTriple), DefaultImageName(DefaultImageNam=
e),
+    DefaultTargetTriple(DefaultTargetTriple),=20
+    DefaultImageName(DefaultImageName),
     DriverTitle("clang \"gcc-compatible\" driver"),
-    Host(0),
     CCPrintOptionsFilename(0), CCPrintHeadersFilename(0),
     CCLogDiagnosticsFilename(0), CCCIsCXX(false),
     CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false),
@@ -65,7 +62,7 @@
     CCCUsePCH(true), SuppressMissingInputWarning(false) {
   if (IsProduction) {
     // In a "production" build, only use clang on architectures we expect =
to
-    // work, and don't use clang C++.
+    // work.
     //
     // During development its more convenient to always have the driver use
     // clang, but we don't want users to be confused when things don't wor=
k, or
@@ -80,7 +77,7 @@
=20
   // Compute the path to the resource directory.
   StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
-  llvm::SmallString<128> P(Dir);
+  SmallString<128> P(Dir);
   if (ClangResourceDir !=3D "")
     llvm::sys::path::append(P, ClangResourceDir);
   else
@@ -90,7 +87,11 @@
=20
 Driver::~Driver() {
   delete Opts;
-  delete Host;
+
+  for (llvm::StringMap<ToolChain *>::iterator I =3D ToolChains.begin(),
+                                              E =3D ToolChains.end();
+       I !=3D E; ++I)
+    delete I->second;
 }
=20
 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) {
@@ -112,6 +113,12 @@
       Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
       continue;
     }
+
+    // Warn about -mcpu=3D without an argument.
+    if (A->getOption().matches(options::OPT_mcpu_EQ) &&=20
+        A->containsValue("")) {
+      Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(=
*Args);
+    }
   }
=20
   return Args;
@@ -134,8 +141,10 @@
     // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
   } else if ((PhaseArg =3D DAL.getLastArg(options::OPT_fsyntax_only)) ||
              (PhaseArg =3D DAL.getLastArg(options::OPT_rewrite_objc)) ||
+             (PhaseArg =3D DAL.getLastArg(options::OPT_rewrite_legacy_objc=
)) ||
+             (PhaseArg =3D DAL.getLastArg(options::OPT__migrate)) ||
              (PhaseArg =3D DAL.getLastArg(options::OPT__analyze,
-                                              options::OPT__analyze_auto))=
 ||
+                                        options::OPT__analyze_auto)) ||
              (PhaseArg =3D DAL.getLastArg(options::OPT_emit_ast)) ||
              (PhaseArg =3D DAL.getLastArg(options::OPT_S))) {
     FinalPhase =3D phases::Compile;
@@ -239,7 +248,7 @@
   llvm::PrettyStackTraceString CrashInfo("Compilation construction");
=20
   // FIXME: Handle environment options which affect driver behavior, somew=
here
-  // (client?). GCC_EXEC_PREFIX, LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS.
+  // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
=20
   if (char *env =3D ::getenv("COMPILER_PATH")) {
     StringRef CompilerPath =3D env;
@@ -303,10 +312,10 @@
       Cur =3D Split.second;
     }
   }
-  // FIXME: We shouldn't overwrite the default host triple here, but we ha=
ve
-  // nowhere else to put this currently.
-  if (const Arg *A =3D Args->getLastArg(options::OPT_ccc_host_triple))
-    DefaultHostTriple =3D A->getValue(*Args);
+  // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as=
/ld
+  // and getToolChain is const.
+  if (const Arg *A =3D Args->getLastArg(options::OPT_target))
+    DefaultTargetTriple =3D A->getValue(*Args);
   if (const Arg *A =3D Args->getLastArg(options::OPT_ccc_install_dir))
     Dir =3D InstalledDir =3D A->getValue(*Args);
   for (arg_iterator it =3D Args->filtered_begin(options::OPT_B),
@@ -320,14 +329,14 @@
   if (Args->hasArg(options::OPT_nostdlib))
     UseStdLib =3D false;
=20
-  Host =3D GetHostInfo(DefaultHostTriple.c_str());
-
   // Perform the default argument translations.
   DerivedArgList *TranslatedArgs =3D TranslateInputArgs(*Args);
=20
+  // Owned by the host.
+  const ToolChain &TC =3D getToolChain(*Args);
+
   // The compilation takes ownership of Args.
-  Compilation *C =3D new Compilation(*this, *Host->CreateToolChain(*Args),=
 Args,
-                                   TranslatedArgs);
+  Compilation *C =3D new Compilation(*this, TC, Args, TranslatedArgs);
=20
   // FIXME: This behavior shouldn't be here.
   if (CCCPrintOptions) {
@@ -342,8 +351,9 @@
   InputList Inputs;
   BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs);
=20
-  // Construct the list of abstract actions to perform for this compilatio=
n.
-  if (Host->useDriverDriver())
+  // Construct the list of abstract actions to perform for this compilatio=
n. On
+  // Darwin target OSes this uses the driver-driver and universal actions.
+  if (TC.getTriple().isOSDarwin())
     BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
                           Inputs, C->getActions());
   else
@@ -365,6 +375,13 @@
 // diagnostic information to a bug report.
 void Driver::generateCompilationDiagnostics(Compilation &C,
                                             const Command *FailingCommand)=
 {
+  if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
+    return; =20
+
+  // Don't try to generate diagnostics for link jobs.
+  if (FailingCommand->getCreator().isLinkJob())
+    return;
+
   Diag(clang::diag::note_drv_command_failed_diag_msg)
     << "Please submit a bug report to " BUG_REPORT_URL " and include comma=
nd"
     " line arguments and all diagnostic information.";
@@ -373,6 +390,12 @@
   CCCIsCPP =3D true;
   CCGenDiagnostics =3D true;
=20
+  // Save the original job command(s).
+  std::string Cmd;
+  llvm::raw_string_ostream OS(Cmd);
+  C.PrintJob(OS, C.getJobs(), "\n", false);
+  OS.flush();
+
   // Clear stale state and suppress tool output.
   C.initCompilationForDiagnostics();
   Diags.Reset();
@@ -403,21 +426,22 @@
   }
=20
   // Don't attempt to generate preprocessed files if multiple -arch option=
s are
-  // used.
-  int Archs =3D 0;
+  // used, unless they're all duplicates.
+  llvm::StringSet<> ArchNames;
   for (ArgList::const_iterator it =3D C.getArgs().begin(), ie =3D C.getArg=
s().end();
        it !=3D ie; ++it) {
     Arg *A =3D *it;
     if (A->getOption().matches(options::OPT_arch)) {
-      Archs++;
-      if (Archs > 1) {
-        Diag(clang::diag::note_drv_command_failed_diag_msg)
-          << "Error generating preprocessed source(s) - cannot generate "
-          "preprocessed source with multiple -arch options.";
-        return;
-      }
+      StringRef ArchName =3D A->getValue(C.getArgs());
+      ArchNames.insert(ArchName);
     }
   }
+  if (ArchNames.size() > 1) {
+    Diag(clang::diag::note_drv_command_failed_diag_msg)
+      << "Error generating preprocessed source(s) - cannot generate "
+      "preprocessed source with multiple -arch options.";
+    return;
+  }
=20
   if (Inputs.empty()) {
     Diag(clang::diag::note_drv_command_failed_diag_msg)
@@ -425,13 +449,13 @@
     return;
   }
=20
-  // Construct the list of abstract actions to perform for this compilatio=
n.
-  if (Host->useDriverDriver())
-    BuildUniversalActions(C.getDefaultToolChain(), C.getArgs(),
-                          Inputs, C.getActions());
+  // Construct the list of abstract actions to perform for this compilatio=
n. On
+  // Darwin OSes this uses the driver-driver and builds universal actions.
+  const ToolChain &TC =3D C.getDefaultToolChain();
+  if (TC.getTriple().isOSDarwin())
+    BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
   else
-    BuildActions(C.getDefaultToolChain(), C.getArgs(), Inputs,
-                 C.getActions());
+    BuildActions(TC, C.getArgs(), Inputs, C.getActions());
=20
   BuildJobs(C);
=20
@@ -449,11 +473,26 @@
   // If the command succeeded, we are done.
   if (Res =3D=3D 0) {
     Diag(clang::diag::note_drv_command_failed_diag_msg)
-      << "Preprocessed source(s) are located at:";
+      << "Preprocessed source(s) and associated run script(s) are located =
at:";
     ArgStringList Files =3D C.getTempFiles();
     for (ArgStringList::const_iterator it =3D Files.begin(), ie =3D Files.=
end();
-         it !=3D ie; ++it)
+         it !=3D ie; ++it) {
       Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
+
+      std::string Err;
+      std::string Script =3D StringRef(*it).rsplit('.').first;
+      Script +=3D ".sh";
+      llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err,
+                                    llvm::raw_fd_ostream::F_Excl |
+                                    llvm::raw_fd_ostream::F_Binary);
+      if (!Err.empty()) {
+        Diag(clang::diag::note_drv_command_failed_diag_msg)
+          << "Error generating run script: " + Script + " " + Err;
+      } else {
+        ScriptOS << Cmd;
+        Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
+      }
+    }
   } else {
     // Failure, remove preprocessed files.
     if (!C.getArgs().hasArg(options::OPT_save_temps))
@@ -486,9 +525,20 @@
     return Res;
=20
   // Otherwise, remove result files as well.
-  if (!C.getArgs().hasArg(options::OPT_save_temps))
+  if (!C.getArgs().hasArg(options::OPT_save_temps)) {
     C.CleanupFileList(C.getResultFiles(), true);
=20
+    // Failure result files are valid unless we crashed.
+    if (Res < 0) {
+      C.CleanupFileList(C.getFailureResultFiles(), true);
+#ifdef _WIN32
+      // Exit status should not be negative on Win32,
+      // unless abnormal termination.
+      Res =3D 1;
+#endif
+    }
+  }
+
   // Print extra information about abnormal failures, if possible.
   //
   // This is ad-hoc, but we don't want to be excessively noisy. If the res=
ult
@@ -502,7 +552,7 @@
     // FIXME: See FIXME above regarding result code interpretation.
     if (Res < 0)
       Diag(clang::diag::err_drv_command_signalled)
-        << FailingTool.getShortName() << -Res;
+        << FailingTool.getShortName();
     else
       Diag(clang::diag::err_drv_command_failed)
         << FailingTool.getShortName() << Res;
@@ -820,35 +870,32 @@
     else
       Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
=20
-    // Add a 'dsymutil' step if necessary, when debug info is enabled and =
we
-    // have a compile input. We need to run 'dsymutil' ourselves in such c=
ases
-    // because the debug info will refer to a temporary object file which =
is
-    // will be removed at the end of the compilation process.
-    if (Act->getType() =3D=3D types::TY_Image) {
-      Arg *A =3D Args.getLastArg(options::OPT_g_Group);
+    // Handle debug info queries.
+    Arg *A =3D Args.getLastArg(options::OPT_g_Group);
       if (A && !A->getOption().matches(options::OPT_g0) &&
           !A->getOption().matches(options::OPT_gstabs) &&
           ContainsCompileOrAssembleAction(Actions.back())) {
-        ActionList Inputs;
-        Inputs.push_back(Actions.back());
-        Actions.pop_back();
+  =20
+        // Add a 'dsymutil' step if necessary, when debug info is enabled =
and we
+        // have a compile input. We need to run 'dsymutil' ourselves in su=
ch cases
+        // because the debug info will refer to a temporary object file wh=
ich is
+        // will be removed at the end of the compilation process.
+        if (Act->getType() =3D=3D types::TY_Image) {
+          ActionList Inputs;
+          Inputs.push_back(Actions.back());
+          Actions.pop_back();
+          Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
+        }
=20
-        Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
-
-	// Verify the debug output if we're in assert mode.
-	// TODO: The verifier is noisy by default so put this under an
-	// option for now.
-	#ifndef NDEBUG
-	if (Args.hasArg(options::OPT_verify)) {
-	  ActionList VerifyInputs;
+        // Verify the output (debug information only) if we passed '-verif=
y'.
+        if (Args.hasArg(options::OPT_verify)) {
+          ActionList VerifyInputs;
 	  VerifyInputs.push_back(Actions.back());
 	  Actions.pop_back();
 	  Actions.push_back(new VerifyJobAction(VerifyInputs,
 						types::TY_Nothing));
 	}
-        #endif
       }
-    }
   }
 }
=20
@@ -931,15 +978,17 @@
=20
       // Check that the file exists, if enabled.
       if (CheckInputsExist && memcmp(Value, "-", 2) !=3D 0) {
-        llvm::SmallString<64> Path(Value);
-        if (Arg *WorkDir =3D Args.getLastArg(options::OPT_working_director=
y))
-          if (llvm::sys::path::is_absolute(Path.str())) {
-            Path =3D WorkDir->getValue(Args);
-            llvm::sys::path::append(Path, Value);
+        SmallString<64> Path(Value);
+        if (Arg *WorkDir =3D Args.getLastArg(options::OPT_working_director=
y)) {
+          SmallString<64> Directory(WorkDir->getValue(Args));
+          if (llvm::sys::path::is_absolute(Directory.str())) {
+            llvm::sys::path::append(Directory, Value);
+            Path.assign(Directory);
           }
+        }
=20
         bool exists =3D false;
-        if (/*error_code ec =3D*/llvm::sys::fs::exists(Value, exists) || !=
exists)
+        if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists)
           Diag(clang::diag::err_drv_no_such_file) << Path.str();
         else
           Inputs.push_back(std::make_pair(Ty, A));
@@ -954,6 +1003,7 @@
     } else if (A->getOption().matches(options::OPT_x)) {
       InputTypeArg =3D A;
       InputType =3D types::lookupTypeForTypeSpecifier(A->getValue(Args));
+      A->claim();
=20
       // Follow gcc behavior and treat as linker input for invalid -x
       // options. Its not clear why we shouldn't just revert to unknown; b=
ut
@@ -993,11 +1043,12 @@
=20
   // Construct the actions to perform.
   ActionList LinkerInputs;
+  unsigned NumSteps =3D 0;
   for (unsigned i =3D 0, e =3D Inputs.size(); i !=3D e; ++i) {
     types::ID InputType =3D Inputs[i].first;
     const Arg *InputArg =3D Inputs[i].second;
=20
-    unsigned NumSteps =3D types::getNumCompilationPhases(InputType);
+    NumSteps =3D types::getNumCompilationPhases(InputType);
     assert(NumSteps && "Invalid number of steps!");
=20
     // If the first step comes after the final phase we are doing as part =
of
@@ -1027,7 +1078,7 @@
     }
=20
     // Build the pipeline for this file.
-    llvm::OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
+    OwningPtr<Action> Current(new InputAction(*InputArg, InputType));
     for (unsigned i =3D 0; i !=3D NumSteps; ++i) {
       phases::ID Phase =3D types::getCompilationPhase(InputType, i);
=20
@@ -1065,7 +1116,7 @@
=20
   // If we are linking, claim any options which are obviously only used for
   // compilation.
-  if (FinalPhase =3D=3D phases::Link)
+  if (FinalPhase =3D=3D phases::Link && (NumSteps =3D=3D 1))
     Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
 }
=20
@@ -1094,8 +1145,12 @@
       return new CompileJobAction(Input, types::TY_Nothing);
     } else if (Args.hasArg(options::OPT_rewrite_objc)) {
       return new CompileJobAction(Input, types::TY_RewrittenObjC);
+    } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
+      return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
     } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_au=
to)) {
       return new AnalyzeJobAction(Input, types::TY_Plist);
+    } else if (Args.hasArg(options::OPT__migrate)) {
+      return new MigrateJobAction(Input, types::TY_Remap);
     } else if (Args.hasArg(options::OPT_emit_ast)) {
       return new CompileJobAction(Input, types::TY_AST);
     } else if (IsUsingLTO(Args)) {
@@ -1225,17 +1280,9 @@
   // bottom up, so what we are actually looking for is an assembler job wi=
th a
   // compiler input.
=20
-  // FIXME: This doesn't belong here, but ideally we will support static s=
oon
-  // anyway.
-  bool HasStatic =3D (C.getArgs().hasArg(options::OPT_mkernel) ||
-                    C.getArgs().hasArg(options::OPT_static) ||
-                    C.getArgs().hasArg(options::OPT_fapple_kext));
-  bool IsDarwin =3D TC->getTriple().isOSDarwin();
-  bool IsIADefault =3D TC->IsIntegratedAssemblerDefault() &&
-    !(HasStatic && IsDarwin);
   if (C.getArgs().hasFlag(options::OPT_integrated_as,
-                         options::OPT_no_integrated_as,
-                         IsIADefault) &&
+                          options::OPT_no_integrated_as,
+                          TC->IsIntegratedAssemblerDefault()) &&
       !C.getArgs().hasArg(options::OPT_save_temps) &&
       isa<AssembleJobAction>(JA) &&
       Inputs->size() =3D=3D 1 && isa<CompileJobAction>(*Inputs->begin())) {
@@ -1289,9 +1336,8 @@
   if (const BindArchAction *BAA =3D dyn_cast<BindArchAction>(A)) {
     const ToolChain *TC =3D &C.getDefaultToolChain();
=20
-    std::string Arch;
     if (BAA->getArchName())
-      TC =3D Host->CreateToolChain(C.getArgs(), BAA->getArchName());
+      TC =3D &getToolChain(C.getArgs(), BAA->getArchName());
=20
     BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
                        AtTopLevel, LinkingOutput, Result);
@@ -1383,7 +1429,7 @@
     return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
   }
=20
-  llvm::SmallString<128> BasePath(BaseInput);
+  SmallString<128> BasePath(BaseInput);
   StringRef BaseName;
=20
   // Dsymutil actions should use the full path.
@@ -1482,7 +1528,8 @@
=20
 std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC,
                                    bool WantFile) const {
-  std::string TargetSpecificExecutable(DefaultHostTriple + "-" + Name);
+  // FIXME: Needs a better variable than DefaultTargetTriple
+  std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
   // Respect a limited subset of the '-Bprefix' functionality in GCC by
   // attempting to use this prefix when lokup up program paths.
   for (Driver::prefix_list::const_iterator it =3D PrefixDirs.begin(),
@@ -1545,40 +1592,125 @@
   return P.str();
 }
=20
-const HostInfo *Driver::GetHostInfo(const char *TripleStr) const {
-  llvm::PrettyStackTraceString CrashInfo("Constructing host");
-  llvm::Triple Triple(llvm::Triple::normalize(TripleStr).c_str());
+/// \brief Compute target triple from args.
+///
+/// This routine provides the logic to compute a target triple from various
+/// args passed to the driver and the default triple string.
+static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
+                                        const ArgList &Args,
+                                        StringRef DarwinArchName) {
+  // FIXME: Already done in Compilation *Driver::BuildCompilation
+  if (const Arg *A =3D Args.getLastArg(options::OPT_target))
+    DefaultTargetTriple =3D A->getValue(Args);
=20
-  // TCE is an osless target
-  if (Triple.getArchName() =3D=3D "tce")
-    return createTCEHostInfo(*this, Triple);
+  llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
=20
-  switch (Triple.getOS()) {
-  case llvm::Triple::AuroraUX:
-    return createAuroraUXHostInfo(*this, Triple);
-  case llvm::Triple::Darwin:
-  case llvm::Triple::MacOSX:
-  case llvm::Triple::IOS:
-    return createDarwinHostInfo(*this, Triple);
-  case llvm::Triple::DragonFly:
-    return createDragonFlyHostInfo(*this, Triple);
-  case llvm::Triple::OpenBSD:
-    return createOpenBSDHostInfo(*this, Triple);
-  case llvm::Triple::NetBSD:
-    return createNetBSDHostInfo(*this, Triple);
-  case llvm::Triple::FreeBSD:
-    return createFreeBSDHostInfo(*this, Triple);
-  case llvm::Triple::Minix:
-    return createMinixHostInfo(*this, Triple);
-  case llvm::Triple::Linux:
-    return createLinuxHostInfo(*this, Triple);
-  case llvm::Triple::Win32:
-    return createWindowsHostInfo(*this, Triple);
-  case llvm::Triple::MinGW32:
-    return createMinGWHostInfo(*this, Triple);
-  default:
-    return createUnknownHostInfo(*this, Triple);
+  // Handle Darwin-specific options available here.
+  if (Target.isOSDarwin()) {
+    // If an explict Darwin arch name is given, that trumps all.
+    if (!DarwinArchName.empty()) {
+      Target.setArch(
+        llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName));
+      return Target;
+    }
+
+    // Handle the Darwin '-arch' flag.
+    if (Arg *A =3D Args.getLastArg(options::OPT_arch)) {
+      llvm::Triple::ArchType DarwinArch
+        =3D llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args));
+      if (DarwinArch !=3D llvm::Triple::UnknownArch)
+        Target.setArch(DarwinArch);
+    }
   }
+
+  // Skip further flag support on OSes which don't support '-m32' or '-m64=
'.
+  if (Target.getArchName() =3D=3D "tce" ||
+      Target.getOS() =3D=3D llvm::Triple::AuroraUX ||
+      Target.getOS() =3D=3D llvm::Triple::Minix)
+    return Target;
+
+  // Handle pseudo-target flags '-m32' and '-m64'.
+  // FIXME: Should this information be in llvm::Triple?
+  if (Arg *A =3D Args.getLastArg(options::OPT_m32, options::OPT_m64)) {
+    if (A->getOption().matches(options::OPT_m32)) {
+      if (Target.getArch() =3D=3D llvm::Triple::x86_64)
+        Target.setArch(llvm::Triple::x86);
+      if (Target.getArch() =3D=3D llvm::Triple::ppc64)
+        Target.setArch(llvm::Triple::ppc);
+    } else {
+      if (Target.getArch() =3D=3D llvm::Triple::x86)
+        Target.setArch(llvm::Triple::x86_64);
+      if (Target.getArch() =3D=3D llvm::Triple::ppc)
+        Target.setArch(llvm::Triple::ppc64);
+    }
+  }
+
+  return Target;
+}
+
+const ToolChain &Driver::getToolChain(const ArgList &Args,
+                                      StringRef DarwinArchName) const {
+  llvm::Triple Target =3D computeTargetTriple(DefaultTargetTriple, Args,
+                                            DarwinArchName);
+
+  ToolChain *&TC =3D ToolChains[Target.str()];
+  if (!TC) {
+    switch (Target.getOS()) {
+    case llvm::Triple::AuroraUX:
+      TC =3D new toolchains::AuroraUX(*this, Target, Args);
+      break;
+    case llvm::Triple::Darwin:
+    case llvm::Triple::MacOSX:
+    case llvm::Triple::IOS:
+      if (Target.getArch() =3D=3D llvm::Triple::x86 ||
+          Target.getArch() =3D=3D llvm::Triple::x86_64 ||
+          Target.getArch() =3D=3D llvm::Triple::arm ||
+          Target.getArch() =3D=3D llvm::Triple::thumb)
+        TC =3D new toolchains::DarwinClang(*this, Target);
+      else
+        TC =3D new toolchains::Darwin_Generic_GCC(*this, Target, Args);
+      break;
+    case llvm::Triple::DragonFly:
+      TC =3D new toolchains::DragonFly(*this, Target, Args);
+      break;
+    case llvm::Triple::OpenBSD:
+      TC =3D new toolchains::OpenBSD(*this, Target, Args);
+      break;
+    case llvm::Triple::NetBSD:
+      TC =3D new toolchains::NetBSD(*this, Target, Args);
+      break;
+    case llvm::Triple::FreeBSD:
+      TC =3D new toolchains::FreeBSD(*this, Target, Args);
+      break;
+    case llvm::Triple::Minix:
+      TC =3D new toolchains::Minix(*this, Target, Args);
+      break;
+    case llvm::Triple::Linux:
+      if (Target.getArch() =3D=3D llvm::Triple::hexagon)
+        TC =3D new toolchains::Hexagon_TC(*this, Target);
+      else
+        TC =3D new toolchains::Linux(*this, Target, Args);
+      break;
+    case llvm::Triple::Solaris:
+      TC =3D new toolchains::Solaris(*this, Target, Args);
+      break;
+    case llvm::Triple::Win32:
+      TC =3D new toolchains::Windows(*this, Target);
+      break;
+    case llvm::Triple::MinGW32:
+      // FIXME: We need a MinGW toolchain. Fallthrough for now.
+    default:
+      // TCE is an OSless target
+      if (Target.getArchName() =3D=3D "tce") {
+        TC =3D new toolchains::TCEToolChain(*this, Target);
+        break;
+      }
+
+      TC =3D new toolchains::Generic_GCC(*this, Target, Args);
+      break;
+    }
+  }
+  return *TC;
 }
=20
 bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction =
&JA,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/DriverOptions.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/DriverOptions.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/DriverOptions.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
 static const OptTable::Info InfoTable[] =3D {
 #define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \
                HELPTEXT, METAVAR)   \
-  { NAME, HELPTEXT, METAVAR, Option::KIND##Class, FLAGS, PARAM, \
+  { NAME, HELPTEXT, METAVAR, Option::KIND##Class, PARAM, FLAGS, \
     OPT_##GROUP, OPT_##ALIAS },
 #include "clang/Driver/Options.inc"
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Job.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Job.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Job.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -16,6 +16,8 @@
=20
 Job::~Job() {}
=20
+void Command::anchor() {}
+
 Command::Command(const Action &_Source, const Tool &_Creator,
                  const char *_Executable, const ArgStringList &_Arguments)
   : Job(CommandClass), Source(_Source), Creator(_Creator),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Option.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Option.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Option.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -61,8 +61,6 @@
 void Option::dump() const {
   llvm::errs() << "<";
   switch (Kind) {
-  default:
-    llvm_unreachable("Invalid kind");
 #define P(N) case N: llvm::errs() << #N; break
     P(GroupClass);
     P(InputClass);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/ToolChain.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/ToolChain.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/ToolChain.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -14,31 +14,31 @@
 #include "clang/Driver/ArgList.h"
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
-#include "clang/Driver/HostInfo.h"
 #include "clang/Driver/ObjCRuntime.h"
 #include "clang/Driver/Options.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/ErrorHandling.h"
 using namespace clang::driver;
 using namespace clang;
=20
-ToolChain::ToolChain(const HostInfo &H, const llvm::Triple &T)
-  : Host(H), Triple(T) {
+ToolChain::ToolChain(const Driver &D, const llvm::Triple &T)
+  : D(D), Triple(T) {
 }
=20
 ToolChain::~ToolChain() {
 }
=20
 const Driver &ToolChain::getDriver() const {
- return Host.getDriver();
+ return D;
 }
=20
 std::string ToolChain::GetFilePath(const char *Name) const {
-  return Host.getDriver().GetFilePath(Name, *this);
+  return D.GetFilePath(Name, *this);
=20
 }
=20
 std::string ToolChain::GetProgramPath(const char *Name, bool WantFile) con=
st {
-  return Host.getDriver().GetProgramPath(Name, *this, WantFile);
+  return D.GetProgramPath(Name, *this, WantFile);
 }
=20
 types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
@@ -55,6 +55,7 @@
     // Assume a minimal NeXT runtime.
     runtime.HasARC =3D false;
     runtime.HasWeak =3D false;
+    runtime.HasSubscripting =3D false;
     runtime.HasTerminate =3D false;
     return;
=20
@@ -62,6 +63,7 @@
     // Assume a maximal GNU runtime.
     runtime.HasARC =3D true;
     runtime.HasWeak =3D true;
+    runtime.HasSubscripting =3D false; // to be added
     runtime.HasTerminate =3D false; // to be added
     return;
   }
@@ -73,11 +75,15 @@
 // FIXME: tblgen this.
 static const char *getARMTargetCPU(const ArgList &Args,
                                    const llvm::Triple &Triple) {
-  // FIXME: Warn on inconsistent use of -mcpu and -march.
-
-  // If we have -mcpu=3D, use that.
-  if (Arg *A =3D Args.getLastArg(options::OPT_mcpu_EQ))
-    return A->getValue(Args);
+  // For Darwin targets, the -arch option (which is translated to a
+  // corresponding -march option) should determine the architecture
+  // (and the Mach-O slice) regardless of any -mcpu options.
+  if (!Triple.isOSDarwin()) {
+    // FIXME: Warn on inconsistent use of -mcpu and -march.
+    // If we have -mcpu=3D, use that.
+    if (Arg *A =3D Args.getLastArg(options::OPT_mcpu_EQ))
+      return A->getValue(Args);
+  }
=20
   StringRef MArch;
   if (Arg *A =3D Args.getLastArg(options::OPT_march_EQ)) {
@@ -88,45 +94,27 @@
     MArch =3D Triple.getArchName();
   }
=20
-  if (MArch =3D=3D "armv2" || MArch =3D=3D "armv2a")
-    return "arm2";
-  if (MArch =3D=3D "armv3")
-    return "arm6";
-  if (MArch =3D=3D "armv3m")
-    return "arm7m";
-  if (MArch =3D=3D "armv4" || MArch =3D=3D "armv4t")
-    return "arm7tdmi";
-  if (MArch =3D=3D "armv5" || MArch =3D=3D "armv5t")
-    return "arm10tdmi";
-  if (MArch =3D=3D "armv5e" || MArch =3D=3D "armv5te")
-    return "arm1026ejs";
-  if (MArch =3D=3D "armv5tej")
-    return "arm926ej-s";
-  if (MArch =3D=3D "armv6" || MArch =3D=3D "armv6k")
-    return "arm1136jf-s";
-  if (MArch =3D=3D "armv6j")
-    return "arm1136j-s";
-  if (MArch =3D=3D "armv6z" || MArch =3D=3D "armv6zk")
-    return "arm1176jzf-s";
-  if (MArch =3D=3D "armv6t2")
-    return "arm1156t2-s";
-  if (MArch =3D=3D "armv7" || MArch =3D=3D "armv7a" || MArch =3D=3D "armv7=
-a")
-    return "cortex-a8";
-  if (MArch =3D=3D "armv7r" || MArch =3D=3D "armv7-r")
-    return "cortex-r4";
-  if (MArch =3D=3D "armv7m" || MArch =3D=3D "armv7-m")
-    return "cortex-m3";
-  if (MArch =3D=3D "ep9312")
-    return "ep9312";
-  if (MArch =3D=3D "iwmmxt")
-    return "iwmmxt";
-  if (MArch =3D=3D "xscale")
-    return "xscale";
-  if (MArch =3D=3D "armv6m" || MArch =3D=3D "armv6-m")
-    return "cortex-m0";
-
-  // If all else failed, return the most base CPU LLVM supports.
-  return "arm7tdmi";
+  return llvm::StringSwitch<const char *>(MArch)
+    .Cases("armv2", "armv2a","arm2")
+    .Case("armv3", "arm6")
+    .Case("armv3m", "arm7m")
+    .Cases("armv4", "armv4t", "arm7tdmi")
+    .Cases("armv5", "armv5t", "arm10tdmi")
+    .Cases("armv5e", "armv5te", "arm1026ejs")
+    .Case("armv5tej", "arm926ej-s")
+    .Cases("armv6", "armv6k", "arm1136jf-s")
+    .Case("armv6j", "arm1136j-s")
+    .Cases("armv6z", "armv6zk", "arm1176jzf-s")
+    .Case("armv6t2", "arm1156t2-s")
+    .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
+    .Cases("armv7r", "armv7-r", "cortex-r4")
+    .Cases("armv7m", "armv7-m", "cortex-m3")
+    .Case("ep9312", "ep9312")
+    .Case("iwmmxt", "iwmmxt")
+    .Case("xscale", "xscale")
+    .Cases("armv6m", "armv6-m", "cortex-m0")
+    // If all else failed, return the most base CPU LLVM supports.
+    .Default("arm7tdmi");
 }
=20
 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particul=
ar
@@ -135,38 +123,23 @@
 // FIXME: This is redundant with -mcpu, why does LLVM use this.
 // FIXME: tblgen this, or kill it!
 static const char *getLLVMArchSuffixForARM(StringRef CPU) {
-  if (CPU =3D=3D "arm7tdmi" || CPU =3D=3D "arm7tdmi-s" || CPU =3D=3D "arm7=
10t" ||
-      CPU =3D=3D "arm720t" || CPU =3D=3D "arm9" || CPU =3D=3D "arm9tdmi" ||
-      CPU =3D=3D "arm920" || CPU =3D=3D "arm920t" || CPU =3D=3D "arm922t" =
||
-      CPU =3D=3D "arm940t" || CPU =3D=3D "ep9312")
-    return "v4t";
-
-  if (CPU =3D=3D "arm10tdmi" || CPU =3D=3D "arm1020t")
-    return "v5";
-
-  if (CPU =3D=3D "arm9e" || CPU =3D=3D "arm926ej-s" || CPU =3D=3D "arm946e=
-s" ||
-      CPU =3D=3D "arm966e-s" || CPU =3D=3D "arm968e-s" || CPU =3D=3D "arm1=
0e" ||
-      CPU =3D=3D "arm1020e" || CPU =3D=3D "arm1022e" || CPU =3D=3D "xscale=
" ||
-      CPU =3D=3D "iwmmxt")
-    return "v5e";
-
-  if (CPU =3D=3D "arm1136j-s" || CPU =3D=3D "arm1136jf-s" || CPU =3D=3D "a=
rm1176jz-s" ||
-      CPU =3D=3D "arm1176jzf-s" || CPU =3D=3D "mpcorenovfp" || CPU =3D=3D =
"mpcore")
-    return "v6";
-
-  if (CPU =3D=3D "arm1156t2-s" || CPU =3D=3D "arm1156t2f-s")
-    return "v6t2";
-
-  if (CPU =3D=3D "cortex-a8" || CPU =3D=3D "cortex-a9")
-    return "v7";
-
-  if (CPU =3D=3D "cortex-m3")
-    return "v7m";
-
-  if (CPU =3D=3D "cortex-m0")
-    return "v6m";
-
-  return "";
+  return llvm::StringSwitch<const char *>(CPU)
+    .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
+    .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
+    .Cases("arm920", "arm920t", "arm922t", "v4t")
+    .Cases("arm940t", "ep9312","v4t")
+    .Cases("arm10tdmi",  "arm1020t", "v5")
+    .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
+    .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
+    .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
+    .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
+    .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
+    .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
+    .Cases("cortex-a8", "cortex-a9", "v7")
+    .Case("cortex-m3", "v7m")
+    .Case("cortex-m4", "v7m")
+    .Case("cortex-m0", "v6m")
+    .Default("");
 }
=20
 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,=20
@@ -216,6 +189,22 @@
   // Each toolchain should provide the appropriate include flags.
 }
=20
+ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
+  const ArgList &Args) const
+{
+  if (Arg *A =3D Args.getLastArg(options::OPT_rtlib_EQ)) {
+    StringRef Value =3D A->getValue(Args);
+    if (Value =3D=3D "compiler-rt")
+      return ToolChain::RLT_CompilerRT;
+    if (Value =3D=3D "libgcc")
+      return ToolChain::RLT_Libgcc;
+    getDriver().Diag(diag::err_drv_invalid_rtlib_name)
+      << A->getAsString(Args);
+  }
+
+  return GetDefaultRuntimeLibType();
+}
+
 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) =
const{
   if (Arg *A =3D Args.getLastArg(options::OPT_stdlib_EQ)) {
     StringRef Value =3D A->getValue(Args);
@@ -230,6 +219,40 @@
   return ToolChain::CST_Libstdcxx;
 }
=20
+/// \brief Utility function to add a system include directory to CC1 argum=
ents.
+/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
+                                            ArgStringList &CC1Args,
+                                            const Twine &Path) {
+  CC1Args.push_back("-internal-isystem");
+  CC1Args.push_back(DriverArgs.MakeArgString(Path));
+}
+
+/// \brief Utility function to add a system include directory with extern =
"C"
+/// semantics to CC1 arguments.
+///
+/// Note that this should be used rarely, and only for directories that
+/// historically and for legacy reasons are treated as having implicit ext=
ern
+/// "C" semantics. These semantics are *ignored* by and large today, but i=
ts
+/// important to preserve the preprocessor changes resulting from the
+/// classification.
+/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverAr=
gs,
+                                                   ArgStringList &CC1Args,
+                                                   const Twine &Path) {
+  CC1Args.push_back("-internal-externc-isystem");
+  CC1Args.push_back(DriverArgs.MakeArgString(Path));
+}
+
+/// \brief Utility function to add a list of system include directories to=
 CC1.
+/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
+                                             ArgStringList &CC1Args,
+                                             ArrayRef<StringRef> Paths) {
+  for (ArrayRef<StringRef>::iterator I =3D Paths.begin(), E =3D Paths.end(=
);
+       I !=3D E; ++I) {
+    CC1Args.push_back("-internal-isystem");
+    CC1Args.push_back(DriverArgs.MakeArgString(*I));
+  }
+}
+
 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
                                              ArgStringList &CC1Args) const=
 {
   // Header search paths should be handled by each of the subclasses.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/ToolChains.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -9,16 +9,11 @@
=20
 #include "ToolChains.h"
=20
-#ifdef HAVE_CLANG_CONFIG_H
-# include "clang/Config/config.h"
-#endif
-
 #include "clang/Driver/Arg.h"
 #include "clang/Driver/ArgList.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
-#include "clang/Driver/HostInfo.h"
 #include "clang/Driver/ObjCRuntime.h"
 #include "clang/Driver/OptTable.h"
 #include "clang/Driver/Option.h"
@@ -38,16 +33,7 @@
=20
 #include <cstdlib> // ::getenv
=20
-#include "llvm/Config/config.h" // for CXX_INCLUDE_ROOT
-
-// Include the necessary headers to interface with the Windows registry and
-// environment.
-#ifdef _MSC_VER
-  #define WIN32_LEAN_AND_MEAN 1
-  #include <Windows.h>
-  #undef min
-  #undef max
-#endif
+#include "clang/Config/config.h" // for GCC_INSTALL_PREFIX
=20
 #ifndef CLANG_PREFIX
 #define CLANG_PREFIX
@@ -57,56 +43,26 @@
 using namespace clang::driver::toolchains;
 using namespace clang;
=20
-/// \brief Utility function to add a system include directory to CC1 argum=
ents.
-static void addSystemInclude(const ArgList &DriverArgs, ArgStringList &CC1=
Args,
-                             const Twine &Path) {
-  CC1Args.push_back("-internal-isystem");
-  CC1Args.push_back(DriverArgs.MakeArgString(Path));
-}
-
-/// \brief Utility function to add a system include directory with extern =
"C"
-/// semantics to CC1 arguments.
-///
-/// Note that this should be used rarely, and only for directories that
-/// historically and for legacy reasons are treated as having implicit ext=
ern
-/// "C" semantics. These semantics are *ignored* by and large today, but i=
ts
-/// important to preserve the preprocessor changes resulting from the
-/// classification.
-static void addExternCSystemInclude(const ArgList &DriverArgs,
-                                    ArgStringList &CC1Args, const Twine &P=
ath) {
-  CC1Args.push_back("-internal-externc-isystem");
-  CC1Args.push_back(DriverArgs.MakeArgString(Path));
-}
-
-/// \brief Utility function to add a list of system include directories to=
 CC1.
-static void addSystemIncludes(const ArgList &DriverArgs,
-                              ArgStringList &CC1Args,
-                              ArrayRef<StringRef> Paths) {
-  for (ArrayRef<StringRef>::iterator I =3D Paths.begin(), E =3D Paths.end(=
);
-       I !=3D E; ++I) {
-    CC1Args.push_back("-internal-isystem");
-    CC1Args.push_back(DriverArgs.MakeArgString(*I));
-  }
-}
-
 /// Darwin - Darwin tool chain for i386 and x86_64.
=20
-Darwin::Darwin(const HostInfo &Host, const llvm::Triple& Triple)
-  : ToolChain(Host, Triple), TargetInitialized(false),
+Darwin::Darwin(const Driver &D, const llvm::Triple& Triple)
+  : ToolChain(D, Triple), TargetInitialized(false),
     ARCRuntimeForSimulator(ARCSimulator_None),
     LibCXXForSimulator(LibCXXSimulator_None)
 {
-  // Compute the initial Darwin version based on the host.
-  bool HadExtra;
-  std::string OSName =3D Triple.getOSName();
-  if (!Driver::GetReleaseVersion(&OSName.c_str()[6],
-                                 DarwinVersion[0], DarwinVersion[1],
-                                 DarwinVersion[2], HadExtra))
-    getDriver().Diag(diag::err_drv_invalid_darwin_version) << OSName;
+  // Compute the initial Darwin version from the triple
+  unsigned Major, Minor, Micro;
+  if (!Triple.getMacOSXVersion(Major, Minor, Micro))
+    getDriver().Diag(diag::err_drv_invalid_darwin_version) <<
+      Triple.getOSName();
+  llvm::raw_string_ostream(MacosxVersionMin)
+    << Major << '.' << Minor << '.' << Micro;
=20
-  llvm::raw_string_ostream(MacosxVersionMin)
-    << "10." << std::max(0, (int)DarwinVersion[0] - 4) << '.'
-    << DarwinVersion[1];
+  // FIXME: DarwinVersion is only used to find GCC's libexec directory.
+  // It should be removed when we stop supporting that.
+  DarwinVersion[0] =3D Minor + 4;
+  DarwinVersion[1] =3D Micro;
+  DarwinVersion[2] =3D 0;
 }
=20
 types::ID Darwin::LookupTypeForExtension(const char *Ext) const {
@@ -141,12 +97,17 @@
     return !isMacosxVersionLT(10, 7);
 }
=20
+bool Darwin::hasSubscriptingRuntime() const {
+    return !isTargetIPhoneOS() && !isMacosxVersionLT(10, 8);
+}
+
 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
 void Darwin::configureObjCRuntime(ObjCRuntime &runtime) const {
   if (runtime.getKind() !=3D ObjCRuntime::NeXT)
     return ToolChain::configureObjCRuntime(runtime);
=20
   runtime.HasARC =3D runtime.HasWeak =3D hasARCRuntime();
+  runtime.HasSubscripting =3D hasSubscriptingRuntime();
=20
   // So far, objc_terminate is only available in iOS 5.
   // FIXME: do the simulator logic properly.
@@ -225,18 +186,16 @@
   if (!isTargetInitialized())
     return Triple.getTriple();
=20
-  unsigned Version[3];
-  getTargetVersion(Version);
-
-  llvm::SmallString<16> Str;
-  llvm::raw_svector_ostream(Str)
-    << (isTargetIPhoneOS() ? "ios" : "macosx")
-    << Version[0] << "." << Version[1] << "." << Version[2];
-  Triple.setOSName(Str.str());
+  SmallString<16> Str;
+  Str +=3D isTargetIPhoneOS() ? "ios" : "macosx";
+  Str +=3D getTargetVersion().getAsString();
+  Triple.setOSName(Str);
=20
   return Triple.getTriple();
 }
=20
+void Generic_ELF::anchor() {}
+
 Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA,
                          const ActionList &Inputs) const {
   Action::ActionClass Key;
@@ -255,15 +214,9 @@
   } else
     Key =3D JA.getKind();
=20
-  // FIXME: This doesn't belong here, but ideally we will support static s=
oon
-  // anyway.
-  bool HasStatic =3D (C.getArgs().hasArg(options::OPT_mkernel) ||
-                    C.getArgs().hasArg(options::OPT_static) ||
-                    C.getArgs().hasArg(options::OPT_fapple_kext));
-  bool IsIADefault =3D IsIntegratedAssemblerDefault() && !HasStatic;
   bool UseIntegratedAs =3D C.getArgs().hasFlag(options::OPT_integrated_as,
                                              options::OPT_no_integrated_as,
-                                             IsIADefault);
+                                             IsIntegratedAssemblerDefault(=
));
=20
   Tool *&T =3D Tools[Key];
   if (!T) {
@@ -274,6 +227,7 @@
     case Action::PreprocessJobClass:
       T =3D new tools::darwin::Preprocess(*this); break;
     case Action::AnalyzeJobClass:
+    case Action::MigrateJobClass:
       T =3D new tools::Clang(*this); break;
     case Action::PrecompileJobClass:
     case Action::CompileJobClass:
@@ -300,8 +254,8 @@
 }
=20
=20
-DarwinClang::DarwinClang(const HostInfo &Host, const llvm::Triple& Triple)
-  : Darwin(Host, Triple)
+DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple)
+  : Darwin(D, Triple)
 {
   getProgramPaths().push_back(getDriver().getInstalledDir());
   if (getDriver().getInstalledDir() !=3D getDriver().Dir)
@@ -344,8 +298,11 @@
   // Unfortunately, we still might depend on a few of the libraries that a=
re
   // only available in the gcc library directory (in particular
   // libstdc++.dylib). For now, hardcode the path to the known install loc=
ation.
+  // FIXME: This should get ripped out someday.  However, when building on
+  // 10.6 (darwin10), we're still relying on this to find libstdc++.dylib.
   llvm::sys::Path P(getDriver().Dir);
   P.eraseComponent(); // .../usr/bin -> ../usr
+  P.appendComponent("llvm-gcc-4.2");
   P.appendComponent("lib");
   P.appendComponent("gcc");
   switch (getTriple().getArch()) {
@@ -416,9 +373,11 @@
   P.appendComponent("libarclite_");
   std::string s =3D P.str();
   // Mash in the platform.
-  if (isTargetIPhoneOS())
+  if (isTargetIOSSimulator())
+    s +=3D "iphonesimulator";
+  else if (isTargetIPhoneOS())
     s +=3D "iphoneos";
-  // FIXME: isTargetIphoneOSSimulator() is not returning true.
+  // FIXME: Remove this once we depend fully on -mios-simulator-version-mi=
n.
   else if (ARCRuntimeForSimulator !=3D ARCSimulator_None)
     s +=3D "iphonesimulator";
   else
@@ -445,6 +404,16 @@
=20
 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
                                         ArgStringList &CmdArgs) const {
+  // Darwin only supports the compiler-rt based runtime libraries.
+  switch (GetRuntimeLibType(Args)) {
+  case ToolChain::RLT_CompilerRT:
+    break;
+  default:
+    getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
+      << Args.getLastArg(options::OPT_rtlib_EQ)->getValue(Args) << "darwin=
";
+    return;
+  }
+
   // Darwin doesn't support real static executables, don't link any runtime
   // libraries with -static.
   if (Args.hasArg(options::OPT_static))
@@ -459,6 +428,38 @@
     return;
   }
=20
+  // If we are building profile support, link that library in.
+  if (Args.hasArg(options::OPT_fprofile_arcs) ||
+      Args.hasArg(options::OPT_fprofile_generate) ||
+      Args.hasArg(options::OPT_fcreate_profile) ||
+      Args.hasArg(options::OPT_coverage)) {
+    // Select the appropriate runtime library for the target.
+    if (isTargetIPhoneOS()) {
+      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a");
+    } else {
+      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a");
+    }
+  }
+
+  // Add ASAN runtime library, if required. Dynamic libraries and bundles
+  // should not be linked with the runtime library.
+  if (Args.hasFlag(options::OPT_faddress_sanitizer,
+                   options::OPT_fno_address_sanitizer, false)) {
+    if (Args.hasArg(options::OPT_dynamiclib) ||
+        Args.hasArg(options::OPT_bundle)) return;
+    if (isTargetIPhoneOS()) {
+      getDriver().Diag(diag::err_drv_clang_unsupported_per_platform)
+        << "-faddress-sanitizer";
+    } else {
+      AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx.a");
+
+      // The ASAN runtime library requires C++ and CoreFoundation.
+      AddCXXStdlibLibArgs(Args, CmdArgs);
+      CmdArgs.push_back("-framework");
+      CmdArgs.push_back("CoreFoundation");
+    }
+  }
+
   // Otherwise link libSystem, then the dynamic runtime library, and final=
ly any
   // target specific static runtime library.
   CmdArgs.push_back("-lSystem");
@@ -540,7 +541,7 @@
   // '-miphoneos-version-min' to help us know whether there is an ARC runt=
ime
   // or not; try to parse a __IPHONE_OS_VERSION_MIN_REQUIRED
   // define passed in command-line.
-  if (!iOSVersion) {
+  if (!iOSVersion && !iOSSimVersion) {
     for (arg_iterator it =3D Args.filtered_begin(options::OPT_D),
            ie =3D Args.filtered_end(); it !=3D ie; ++it) {
       StringRef define =3D (*it)->getValue(Args);
@@ -717,6 +718,8 @@
     }
=20
     // Otherwise, look in the root.
+    // FIXME: This should be removed someday when we don't have to care ab=
out
+    // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
     if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exi=
sts)&&
       (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exi=
sts)){
       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
@@ -1022,6 +1025,10 @@
   return !isTargetIPhoneOS();
 }
=20
+bool Darwin::SupportsObjCARC() const {
+  return isTargetIPhoneOS() || !isMacosxVersionLT(10, 6);
+}
+
 std::string
 Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args,
                                                 types::ID InputType) const=
 {
@@ -1032,8 +1039,345 @@
 /// all subcommands; this relies on gcc translating the majority of
 /// command line options.
=20
-Generic_GCC::Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple)
-  : ToolChain(Host, Triple) {
+/// \brief Parse a GCCVersion object out of a string of text.
+///
+/// This is the primary means of forming GCCVersion objects.
+/*static*/
+Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) {
+  const GCCVersion BadVersion =3D { VersionText.str(), -1, -1, -1, "" };
+  std::pair<StringRef, StringRef> First =3D VersionText.split('.');
+  std::pair<StringRef, StringRef> Second =3D First.second.split('.');
+
+  GCCVersion GoodVersion =3D { VersionText.str(), -1, -1, -1, "" };
+  if (First.first.getAsInteger(10, GoodVersion.Major) ||
+      GoodVersion.Major < 0)
+    return BadVersion;
+  if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
+      GoodVersion.Minor < 0)
+    return BadVersion;
+
+  // First look for a number prefix and parse that if present. Otherwise j=
ust
+  // stash the entire patch string in the suffix, and leave the number
+  // unspecified. This covers versions strings such as:
+  //   4.4
+  //   4.4.0
+  //   4.4.x
+  //   4.4.2-rc4
+  //   4.4.x-patched
+  // And retains any patch number it finds.
+  StringRef PatchText =3D GoodVersion.PatchSuffix =3D Second.second.str();
+  if (!PatchText.empty()) {
+    if (unsigned EndNumber =3D PatchText.find_first_not_of("0123456789")) {
+      // Try to parse the number and any suffix.
+      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch=
) ||
+          GoodVersion.Patch < 0)
+        return BadVersion;
+      GoodVersion.PatchSuffix =3D PatchText.substr(EndNumber).str();
+    }
+  }
+
+  return GoodVersion;
+}
+
+/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
+bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const {
+  if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
+  if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
+
+  // Note that we rank versions with *no* patch specified is better than o=
nes
+  // hard-coding a patch version. Thus if the RHS has no patch, it always
+  // wins, and the LHS only wins if it has no patch and the RHS does have
+  // a patch.
+  if (RHS.Patch =3D=3D -1) return true;   if (Patch =3D=3D -1) return fals=
e;
+  if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
+
+  // Finally, between completely tied version numbers, the version with the
+  // suffix loses as we prefer full releases.
+  if (RHS.PatchSuffix.empty()) return true;
+  return false;
+}
+
+static StringRef getGCCToolchainDir(const ArgList &Args) {
+  const Arg *A =3D Args.getLastArg(options::OPT_gcc_toolchain);
+  if (A)
+    return A->getValue(Args);
+  return GCC_INSTALL_PREFIX;
+}
+
+/// \brief Construct a GCCInstallationDetector from the driver.
+///
+/// This performs all of the autodetection and sets up the various paths.
+/// Once constructed, a GCCInstallation is esentially immutable.
+///
+/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and
+/// should instead pull the target out of the driver. This is currently
+/// necessary because the driver doesn't store the final version of the ta=
rget
+/// triple.
+Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
+    const Driver &D,
+    const llvm::Triple &TargetTriple,
+    const ArgList &Args)
+    : IsValid(false) {
+  llvm::Triple MultiarchTriple
+    =3D TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant()
+                                 : TargetTriple.get32BitArchVariant();
+  llvm::Triple::ArchType TargetArch =3D TargetTriple.getArch();
+  // The library directories which may contain GCC installations.
+  SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs;
+  // The compatible GCC triples for this particular architecture.
+  SmallVector<StringRef, 10> CandidateTripleAliases;
+  SmallVector<StringRef, 10> CandidateMultiarchTripleAliases;
+  CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs,
+                           CandidateTripleAliases,
+                           CandidateMultiarchLibDirs,
+                           CandidateMultiarchTripleAliases);
+
+  // Compute the set of prefixes for our search.
+  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
+                                       D.PrefixDirs.end());
+
+  StringRef GCCToolchainDir =3D getGCCToolchainDir(Args);
+  if (GCCToolchainDir !=3D "") {
+    if (GCCToolchainDir.back() =3D=3D '/')
+      GCCToolchainDir =3D GCCToolchainDir.drop_back(); // remove the /
+
+    Prefixes.push_back(GCCToolchainDir);
+  } else {
+    Prefixes.push_back(D.SysRoot);
+    Prefixes.push_back(D.SysRoot + "/usr");
+    Prefixes.push_back(D.InstalledDir + "/..");
+  }
+
+  // Loop over the various components which exist and select the best GCC
+  // installation available. GCC installs are ranked by version number.
+  Version =3D GCCVersion::Parse("0.0.0");
+  for (unsigned i =3D 0, ie =3D Prefixes.size(); i < ie; ++i) {
+    if (!llvm::sys::fs::exists(Prefixes[i]))
+      continue;
+    for (unsigned j =3D 0, je =3D CandidateLibDirs.size(); j < je; ++j) {
+      const std::string LibDir =3D Prefixes[i] + CandidateLibDirs[j].str();
+      if (!llvm::sys::fs::exists(LibDir))
+        continue;
+      for (unsigned k =3D 0, ke =3D CandidateTripleAliases.size(); k < ke;=
 ++k)
+        ScanLibDirForGCCTriple(TargetArch, LibDir, CandidateTripleAliases[=
k]);
+    }
+    for (unsigned j =3D 0, je =3D CandidateMultiarchLibDirs.size(); j < je=
; ++j) {
+      const std::string LibDir
+        =3D Prefixes[i] + CandidateMultiarchLibDirs[j].str();
+      if (!llvm::sys::fs::exists(LibDir))
+        continue;
+      for (unsigned k =3D 0, ke =3D CandidateMultiarchTripleAliases.size()=
; k < ke;
+           ++k)
+        ScanLibDirForGCCTriple(TargetArch, LibDir,
+                               CandidateMultiarchTripleAliases[k],
+                               /*NeedsMultiarchSuffix=3D*/true);
+    }
+  }
+}
+
+/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTri=
ples(
+    const llvm::Triple &TargetTriple,
+    const llvm::Triple &MultiarchTriple,
+    SmallVectorImpl<StringRef> &LibDirs,
+    SmallVectorImpl<StringRef> &TripleAliases,
+    SmallVectorImpl<StringRef> &MultiarchLibDirs,
+    SmallVectorImpl<StringRef> &MultiarchTripleAliases) {
+  // Declare a bunch of static data sets that we'll select between below. =
These
+  // are specifically designed to always refer to string literals to avoid=
 any
+  // lifetime or initialization issues.
+  static const char *const ARMLibDirs[] =3D { "/lib" };
+  static const char *const ARMTriples[] =3D {
+    "arm-linux-gnueabi",
+    "arm-linux-androideabi"
+  };
+
+  static const char *const X86_64LibDirs[] =3D { "/lib64", "/lib" };
+  static const char *const X86_64Triples[] =3D {
+    "x86_64-linux-gnu",
+    "x86_64-unknown-linux-gnu",
+    "x86_64-pc-linux-gnu",
+    "x86_64-redhat-linux6E",
+    "x86_64-redhat-linux",
+    "x86_64-suse-linux",
+    "x86_64-manbo-linux-gnu",
+    "x86_64-linux-gnu",
+    "x86_64-slackware-linux"
+  };
+  static const char *const X86LibDirs[] =3D { "/lib32", "/lib" };
+  static const char *const X86Triples[] =3D {
+    "i686-linux-gnu",
+    "i686-pc-linux-gnu",
+    "i486-linux-gnu",
+    "i386-linux-gnu",
+    "i686-redhat-linux",
+    "i586-redhat-linux",
+    "i386-redhat-linux",
+    "i586-suse-linux",
+    "i486-slackware-linux"
+  };
+
+  static const char *const MIPSLibDirs[] =3D { "/lib" };
+  static const char *const MIPSTriples[] =3D { "mips-linux-gnu" };
+  static const char *const MIPSELLibDirs[] =3D { "/lib" };
+  static const char *const MIPSELTriples[] =3D { "mipsel-linux-gnu" };
+
+  static const char *const PPCLibDirs[] =3D { "/lib32", "/lib" };
+  static const char *const PPCTriples[] =3D {
+    "powerpc-linux-gnu",
+    "powerpc-unknown-linux-gnu",
+    "powerpc-suse-linux"
+  };
+  static const char *const PPC64LibDirs[] =3D { "/lib64", "/lib" };
+  static const char *const PPC64Triples[] =3D {
+    "powerpc64-linux-gnu",
+    "powerpc64-unknown-linux-gnu",
+    "powerpc64-suse-linux",
+    "ppc64-redhat-linux"
+  };
+
+  switch (TargetTriple.getArch()) {
+  case llvm::Triple::arm:
+  case llvm::Triple::thumb:
+    LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDir=
s));
+    TripleAliases.append(
+      ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples));
+    break;
+  case llvm::Triple::x86_64:
+    LibDirs.append(
+      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
+    TripleAliases.append(
+      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
+    MultiarchLibDirs.append(
+      X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs));
+    MultiarchTripleAliases.append(
+      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
+    break;
+  case llvm::Triple::x86:
+    LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDir=
s));
+    TripleAliases.append(
+      X86Triples, X86Triples + llvm::array_lengthof(X86Triples));
+    MultiarchLibDirs.append(
+      X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
+    MultiarchTripleAliases.append(
+      X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples));
+    break;
+  case llvm::Triple::mips:
+    LibDirs.append(
+      MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs));
+    TripleAliases.append(
+      MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples));
+    break;
+  case llvm::Triple::mipsel:
+    LibDirs.append(
+      MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs));
+    TripleAliases.append(
+      MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples));
+    break;
+  case llvm::Triple::ppc:
+    LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDir=
s));
+    TripleAliases.append(
+      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
+    MultiarchLibDirs.append(
+      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
+    MultiarchTripleAliases.append(
+      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
+    break;
+  case llvm::Triple::ppc64:
+    LibDirs.append(
+      PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
+    TripleAliases.append(
+      PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples));
+    MultiarchLibDirs.append(
+      PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs));
+    MultiarchTripleAliases.append(
+      PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
+    break;
+
+  default:
+    // By default, just rely on the standard lib directories and the origi=
nal
+    // triple.
+    break;
+  }
+
+  // Always append the drivers target triple to the end, in case it doesn't
+  // match any of our aliases.
+  TripleAliases.push_back(TargetTriple.str());
+
+  // Also include the multiarch variant if it's different.
+  if (TargetTriple.str() !=3D MultiarchTriple.str())
+    MultiarchTripleAliases.push_back(MultiarchTriple.str());
+}
+
+void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
+    llvm::Triple::ArchType TargetArch, const std::string &LibDir,
+    StringRef CandidateTriple, bool NeedsMultiarchSuffix) {
+  // There are various different suffixes involving the triple we
+  // check for. We also record what is necessary to walk from each back
+  // up to the lib directory.
+  const std::string LibSuffixes[] =3D {
+    "/gcc/" + CandidateTriple.str(),
+    "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
+
+    // Ubuntu has a strange mis-matched pair of triples that this happens =
to
+    // match.
+    // FIXME: It may be worthwhile to generalize this and look for a second
+    // triple.
+    "/i386-linux-gnu/gcc/" + CandidateTriple.str()
+  };
+  const std::string InstallSuffixes[] =3D {
+    "/../../..",
+    "/../../../..",
+    "/../../../.."
+  };
+  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
+  const unsigned NumLibSuffixes =3D (llvm::array_lengthof(LibSuffixes) -
+                                   (TargetArch !=3D llvm::Triple::x86));
+  for (unsigned i =3D 0; i < NumLibSuffixes; ++i) {
+    StringRef LibSuffix =3D LibSuffixes[i];
+    llvm::error_code EC;
+    for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE;
+         !EC && LI !=3D LE; LI =3D LI.increment(EC)) {
+      StringRef VersionText =3D llvm::sys::path::filename(LI->path());
+      GCCVersion CandidateVersion =3D GCCVersion::Parse(VersionText);
+      static const GCCVersion MinVersion =3D { "4.1.1", 4, 1, 1, "" };
+      if (CandidateVersion < MinVersion)
+        continue;
+      if (CandidateVersion <=3D Version)
+        continue;
+
+      // Some versions of SUSE and Fedora on ppc64 put 32-bit libs
+      // in what would normally be GCCInstallPath and put the 64-bit
+      // libs in a subdirectory named 64. The simple logic we follow is th=
at
+      // *if* there is a subdirectory of the right name with crtbegin.o in=
 it,
+      // we use that. If not, and if not a multiarch triple, we look for
+      // crtbegin.o without the subdirectory.
+      StringRef MultiarchSuffix
+        =3D (TargetArch =3D=3D llvm::Triple::x86_64 ||
+           TargetArch =3D=3D llvm::Triple::ppc64) ? "/64" : "/32";
+      if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.=
o")) {
+        GCCMultiarchSuffix =3D MultiarchSuffix.str();
+      } else {
+        if (NeedsMultiarchSuffix ||
+            !llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
+          continue;
+        GCCMultiarchSuffix.clear();
+      }
+
+      Version =3D CandidateVersion;
+      GCCTriple.setTriple(CandidateTriple);
+      // FIXME: We hack together the directory name here instead of
+      // using LI to ensure stable path separators across Windows and
+      // Linux.
+      GCCInstallPath =3D LibDir + LibSuffixes[i] + "/" + VersionText.str();
+      GCCParentLibPath =3D GCCInstallPath + InstallSuffixes[i];
+      IsValid =3D true;
+    }
+  }
+}
+
+Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple,
+                         const ArgList &Args)
+  : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) {
   getProgramPaths().push_back(getDriver().getInstalledDir());
   if (getDriver().getInstalledDir() !=3D getDriver().Dir)
     getProgramPaths().push_back(getDriver().Dir);
@@ -1066,6 +1410,7 @@
     case Action::PrecompileJobClass:
       T =3D new tools::gcc::Precompile(*this); break;
     case Action::AnalyzeJobClass:
+    case Action::MigrateJobClass:
       T =3D new tools::Clang(*this); break;
     case Action::CompileJobClass:
       T =3D new tools::gcc::Compile(*this); break;
@@ -1101,13 +1446,80 @@
 const char *Generic_GCC::GetForcedPicModel() const {
   return 0;
 }
+/// Hexagon Toolchain
+
+Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple& Triple)
+  : ToolChain(D, Triple) {
+  getProgramPaths().push_back(getDriver().getInstalledDir());
+  if (getDriver().getInstalledDir() !=3D getDriver().Dir.c_str())
+    getProgramPaths().push_back(getDriver().Dir);
+}
+
+Hexagon_TC::~Hexagon_TC() {
+  // Free tool implementations.
+  for (llvm::DenseMap<unsigned, Tool*>::iterator
+         it =3D Tools.begin(), ie =3D Tools.end(); it !=3D ie; ++it)
+    delete it->second;
+}
+
+Tool &Hexagon_TC::SelectTool(const Compilation &C,
+                             const JobAction &JA,
+                             const ActionList &Inputs) const {
+  Action::ActionClass Key;
+  //   if (JA.getKind () =3D=3D Action::CompileJobClass)
+  //     Key =3D JA.getKind ();
+  //     else
+
+  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
+    Key =3D Action::AnalyzeJobClass;
+  else
+    Key =3D JA.getKind();
+  //   if ((JA.getKind () =3D=3D Action::CompileJobClass)
+  //     && (JA.getType () !=3D types::TY_LTO_BC)) {
+  //     Key =3D JA.getKind ();
+  //   }
+
+  Tool *&T =3D Tools[Key];
+  if (!T) {
+    switch (Key) {
+    case Action::InputClass:
+    case Action::BindArchClass:
+      assert(0 && "Invalid tool kind.");
+    case Action::AnalyzeJobClass:
+      T =3D new tools::Clang(*this); break;
+    case Action::AssembleJobClass:
+      T =3D new tools::hexagon::Assemble(*this); break;
+    case Action::LinkJobClass:
+      T =3D new tools::hexagon::Link(*this); break;
+    default:
+      assert(false && "Unsupported action for Hexagon target.");
+    }
+  }
+
+  return *T;
+}
+
+bool Hexagon_TC::IsUnwindTablesDefault() const {
+  // FIXME: Gross; we should probably have some separate target
+  // definition, possibly even reusing the one in clang.
+  return getArchName() =3D=3D "x86_64";
+}
+
+const char *Hexagon_TC::GetDefaultRelocationModel() const {
+  return "static";
+}
+
+const char *Hexagon_TC::GetForcedPicModel() const {
+  return 0;
+} // End Hexagon
+
=20
 /// TCEToolChain - A tool chain using the llvm bitcode tools to perform
 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
 /// Currently does not support anything else but compilation.
=20
-TCEToolChain::TCEToolChain(const HostInfo &Host, const llvm::Triple& Tripl=
e)
-  : ToolChain(Host, Triple) {
+TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple)
+  : ToolChain(D, Triple) {
   // Path mangling to find libexec
   std::string Path(getDriver().Dir);
=20
@@ -1159,8 +1571,8 @@
=20
 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
=20
-OpenBSD::OpenBSD(const HostInfo &Host, const llvm::Triple& Triple)
-  : Generic_ELF(Host, Triple) {
+OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgLis=
t &Args)
+  : Generic_ELF(D, Triple, Args) {
   getFilePaths().push_back(getDriver().Dir + "/../lib");
   getFilePaths().push_back("/usr/lib");
 }
@@ -1199,26 +1611,17 @@
=20
 /// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly.
=20
-FreeBSD::FreeBSD(const HostInfo &Host, const llvm::Triple& Triple)
-  : Generic_ELF(Host, Triple) {
+FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgLis=
t &Args)
+  : Generic_ELF(D, Triple, Args) {
=20
-  // Determine if we are compiling 32-bit code on an x86_64 platform.
-  bool Lib32 =3D false;
-  if (Triple.getArch() =3D=3D llvm::Triple::x86 &&
-      llvm::Triple(getDriver().DefaultHostTriple).getArch() =3D=3D
-        llvm::Triple::x86_64)
-    Lib32 =3D true;
-
-  if (Triple.getArch() =3D=3D llvm::Triple::ppc &&
-      llvm::Triple(getDriver().DefaultHostTriple).getArch() =3D=3D
-        llvm::Triple::ppc64)
-    Lib32 =3D true;
-
-  if (Lib32) {
-    getFilePaths().push_back(CLANG_PREFIX "/usr/lib32");
-  } else {
-    getFilePaths().push_back(CLANG_PREFIX "/usr/lib");
-  }
+  // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall
+  // back to '/usr/lib' if it doesn't exist.
+  if ((Triple.getArch() =3D=3D llvm::Triple::x86 ||
+       Triple.getArch() =3D=3D llvm::Triple::ppc) &&
+      llvm::sys::fs::exists(getDriver().SysRoot + CLANG_PREFIX "/usr/lib32=
/crt1.o"))
+    getFilePaths().push_back(getDriver().SysRoot + CLANG_PREFIX "/usr/lib3=
2");
+  else
+    getFilePaths().push_back(getDriver().SysRoot + CLANG_PREFIX "/usr/lib"=
);
 }
=20
 Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA,
@@ -1254,21 +1657,19 @@
=20
 /// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly.
=20
-NetBSD::NetBSD(const HostInfo &Host, const llvm::Triple& Triple,
-               const llvm::Triple& ToolTriple)
-  : Generic_ELF(Host, Triple), ToolTriple(ToolTriple) {
-
-  // Determine if we are compiling 32-bit code on an x86_64 platform.
-  bool Lib32 =3D false;
-  if (ToolTriple.getArch() =3D=3D llvm::Triple::x86_64 &&
-      Triple.getArch() =3D=3D llvm::Triple::x86)
-    Lib32 =3D true;
+NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList =
&Args)
+  : Generic_ELF(D, Triple, Args) {
=20
   if (getDriver().UseStdLib) {
-    if (Lib32)
+    // When targeting a 32-bit platform, try the special directory used on
+    // 64-bit hosts, and only fall back to the main library directory if t=
hat
+    // doesn't work.
+    // FIXME: It'd be nicer to test if this directory exists, but I'm not =
sure
+    // what all logic is needed to emulate the '=3D' prefix here.
+    if (Triple.getArch() =3D=3D llvm::Triple::x86)
       getFilePaths().push_back("=3D/usr/lib/i386");
-    else
-      getFilePaths().push_back("=3D/usr/lib");
+
+    getFilePaths().push_back("=3D/usr/lib");
   }
 }
=20
@@ -1291,10 +1692,10 @@
       if (UseIntegratedAs)
         T =3D new tools::ClangAs(*this);
       else
-        T =3D new tools::netbsd::Assemble(*this, ToolTriple);
+        T =3D new tools::netbsd::Assemble(*this);
       break;
     case Action::LinkJobClass:
-      T =3D new tools::netbsd::Link(*this, ToolTriple);
+      T =3D new tools::netbsd::Link(*this);
       break;
     default:
       T =3D &Generic_GCC::SelectTool(C, JA, Inputs);
@@ -1306,12 +1707,10 @@
=20
 /// Minix - Minix tool chain which can call as(1) and ld(1) directly.
=20
-Minix::Minix(const HostInfo &Host, const llvm::Triple& Triple)
-  : Generic_GCC(Host, Triple) {
+Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &A=
rgs)
+  : Generic_ELF(D, Triple, Args) {
   getFilePaths().push_back(getDriver().Dir + "/../lib");
   getFilePaths().push_back("/usr/lib");
-  getFilePaths().push_back("/usr/gnu/lib");
-  getFilePaths().push_back("/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
 }
=20
 Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA,
@@ -1339,8 +1738,9 @@
=20
 /// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly.
=20
-AuroraUX::AuroraUX(const HostInfo &Host, const llvm::Triple& Triple)
-  : Generic_GCC(Host, Triple) {
+AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple,
+                   const ArgList &Args)
+  : Generic_GCC(D, Triple, Args) {
=20
   getProgramPaths().push_back(getDriver().getInstalledDir());
   if (getDriver().getInstalledDir() !=3D getDriver().Dir)
@@ -1377,6 +1777,42 @@
   return *T;
 }
=20
+/// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
+
+Solaris::Solaris(const Driver &D, const llvm::Triple& Triple,
+                 const ArgList &Args)
+  : Generic_GCC(D, Triple, Args) {
+
+  getProgramPaths().push_back(getDriver().getInstalledDir());
+  if (getDriver().getInstalledDir() !=3D getDriver().Dir)
+    getProgramPaths().push_back(getDriver().Dir);
+
+  getFilePaths().push_back(getDriver().Dir + "/../lib");
+  getFilePaths().push_back("/usr/lib");
+}
+
+Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA,
+                           const ActionList &Inputs) const {
+  Action::ActionClass Key;
+  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
+    Key =3D Action::AnalyzeJobClass;
+  else
+    Key =3D JA.getKind();
+
+  Tool *&T =3D Tools[Key];
+  if (!T) {
+    switch (Key) {
+    case Action::AssembleJobClass:
+      T =3D new tools::solaris::Assemble(*this); break;
+    case Action::LinkJobClass:
+      T =3D new tools::solaris::Link(*this); break;
+    default:
+      T =3D &Generic_GCC::SelectTool(C, JA, Inputs);
+    }
+  }
+
+  return *T;
+}
=20
 /// Linux toolchain (very bare-bones at the moment).
=20
@@ -1392,6 +1828,7 @@
   Fedora13,
   Fedora14,
   Fedora15,
+  Fedora16,
   FedoraRawhide,
   OpenSuse11_3,
   OpenSuse11_4,
@@ -1404,62 +1841,55 @@
   UbuntuMaverick,
   UbuntuNatty,
   UbuntuOneiric,
+  UbuntuPrecise,
   UnknownDistro
 };
=20
 static bool IsRedhat(enum LinuxDistro Distro) {
-  return Distro =3D=3D Fedora13 || Distro =3D=3D Fedora14 ||
-         Distro =3D=3D Fedora15 || Distro =3D=3D FedoraRawhide ||
-         Distro =3D=3D RHEL4 || Distro =3D=3D RHEL5 || Distro =3D=3D RHEL6;
+  return (Distro >=3D Fedora13 && Distro <=3D FedoraRawhide) ||
+         (Distro >=3D RHEL4    && Distro <=3D RHEL6);
 }
=20
 static bool IsOpenSuse(enum LinuxDistro Distro) {
-  return Distro =3D=3D OpenSuse11_3 || Distro =3D=3D OpenSuse11_4 ||
-         Distro =3D=3D OpenSuse12_1;
+  return Distro >=3D OpenSuse11_3 && Distro <=3D OpenSuse12_1;
 }
=20
 static bool IsDebian(enum LinuxDistro Distro) {
-  return Distro =3D=3D DebianLenny || Distro =3D=3D DebianSqueeze ||
-         Distro =3D=3D DebianWheezy;
+  return Distro >=3D DebianLenny && Distro <=3D DebianWheezy;
 }
=20
 static bool IsUbuntu(enum LinuxDistro Distro) {
-  return Distro =3D=3D UbuntuHardy  || Distro =3D=3D UbuntuIntrepid ||
-         Distro =3D=3D UbuntuLucid  || Distro =3D=3D UbuntuMaverick ||
-         Distro =3D=3D UbuntuJaunty || Distro =3D=3D UbuntuKarmic ||
-         Distro =3D=3D UbuntuNatty  || Distro =3D=3D UbuntuOneiric;
+  return Distro >=3D UbuntuHardy && Distro <=3D UbuntuPrecise;
 }
=20
 static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) {
-  llvm::OwningPtr<llvm::MemoryBuffer> File;
+  OwningPtr<llvm::MemoryBuffer> File;
   if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) {
     StringRef Data =3D File.get()->getBuffer();
     SmallVector<StringRef, 8> Lines;
     Data.split(Lines, "\n");
-    for (unsigned int i =3D 0, s =3D Lines.size(); i < s; ++ i) {
-      if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Dhardy")
-        return UbuntuHardy;
-      else if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Dintrepid")
-        return UbuntuIntrepid;
-      else if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Djaunty")
-        return UbuntuJaunty;
-      else if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Dkarmic")
-        return UbuntuKarmic;
-      else if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Dlucid")
-        return UbuntuLucid;
-      else if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Dmaverick")
-        return UbuntuMaverick;
-      else if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Dnatty")
-        return UbuntuNatty;
-      else if (Lines[i] =3D=3D "DISTRIB_CODENAME=3Doneiric")
-        return UbuntuOneiric;
-    }
-    return UnknownDistro;
+    LinuxDistro Version =3D UnknownDistro;
+    for (unsigned i =3D 0, s =3D Lines.size(); i !=3D s; ++i)
+      if (Version =3D=3D UnknownDistro && Lines[i].startswith("DISTRIB_COD=
ENAME=3D"))
+        Version =3D llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17))
+          .Case("hardy", UbuntuHardy)
+          .Case("intrepid", UbuntuIntrepid)
+          .Case("jaunty", UbuntuJaunty)
+          .Case("karmic", UbuntuKarmic)
+          .Case("lucid", UbuntuLucid)
+          .Case("maverick", UbuntuMaverick)
+          .Case("natty", UbuntuNatty)
+          .Case("oneiric", UbuntuOneiric)
+          .Case("precise", UbuntuPrecise)
+          .Default(UnknownDistro);
+    return Version;
   }
=20
   if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) {
     StringRef Data =3D File.get()->getBuffer();
-    if (Data.startswith("Fedora release 15"))
+    if (Data.startswith("Fedora release 16"))
+      return Fedora16;
+    else if (Data.startswith("Fedora release 15"))
       return Fedora15;
     else if (Data.startswith("Fedora release 14"))
       return Fedora14;
@@ -1486,23 +1916,19 @@
     StringRef Data =3D File.get()->getBuffer();
     if (Data[0] =3D=3D '5')
       return DebianLenny;
-    else if (Data.startswith("squeeze/sid"))
+    else if (Data.startswith("squeeze/sid") || Data[0] =3D=3D '6')
       return DebianSqueeze;
-    else if (Data.startswith("wheezy/sid"))
+    else if (Data.startswith("wheezy/sid")  || Data[0] =3D=3D '7')
       return DebianWheezy;
     return UnknownDistro;
   }
=20
-  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) {
-    StringRef Data =3D File.get()->getBuffer();
-    if (Data.startswith("openSUSE 11.3"))
-      return OpenSuse11_3;
-    else if (Data.startswith("openSUSE 11.4"))
-      return OpenSuse11_4;
-    else if (Data.startswith("openSUSE 12.1"))
-      return OpenSuse12_1;
-    return UnknownDistro;
-  }
+  if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File))
+    return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer())
+      .StartsWith("openSUSE 11.3", OpenSuse11_3)
+      .StartsWith("openSUSE 11.4", OpenSuse11_4)
+      .StartsWith("openSUSE 12.1", OpenSuse12_1)
+      .Default(UnknownDistro);
=20
   bool Exists;
   if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists)
@@ -1514,247 +1940,6 @@
   return UnknownDistro;
 }
=20
-/// \brief Parse a GCCVersion object out of a string of text.
-///
-/// This is the primary means of forming GCCVersion objects.
-/*static*/ Linux::GCCVersion Linux::GCCVersion::Parse(StringRef VersionTex=
t) {
-  const GCCVersion BadVersion =3D { VersionText.str(), -1, -1, -1, "" };
-  std::pair<StringRef, StringRef> First =3D VersionText.split('.');
-  std::pair<StringRef, StringRef> Second =3D First.second.split('.');
-
-  GCCVersion GoodVersion =3D { VersionText.str(), -1, -1, -1, "" };
-  if (First.first.getAsInteger(10, GoodVersion.Major) ||
-      GoodVersion.Major < 0)
-    return BadVersion;
-  if (Second.first.getAsInteger(10, GoodVersion.Minor) ||
-      GoodVersion.Minor < 0)
-    return BadVersion;
-
-  // First look for a number prefix and parse that if present. Otherwise j=
ust
-  // stash the entire patch string in the suffix, and leave the number
-  // unspecified. This covers versions strings such as:
-  //   4.4
-  //   4.4.0
-  //   4.4.x
-  //   4.4.2-rc4
-  //   4.4.x-patched
-  // And retains any patch number it finds.
-  StringRef PatchText =3D GoodVersion.PatchSuffix =3D Second.second.str();
-  if (!PatchText.empty()) {
-    if (unsigned EndNumber =3D PatchText.find_first_not_of("0123456789")) {
-      // Try to parse the number and any suffix.
-      if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch=
) ||
-          GoodVersion.Patch < 0)
-        return BadVersion;
-      GoodVersion.PatchSuffix =3D PatchText.substr(EndNumber).str();
-    }
-  }
-
-  return GoodVersion;
-}
-
-/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering.
-bool Linux::GCCVersion::operator<(const GCCVersion &RHS) const {
-  if (Major < RHS.Major) return true; if (Major > RHS.Major) return false;
-  if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false;
-
-  // Note that we rank versions with *no* patch specified is better than o=
nes
-  // hard-coding a patch version. Thus if the RHS has no patch, it always
-  // wins, and the LHS only wins if it has no patch and the RHS does have
-  // a patch.
-  if (RHS.Patch =3D=3D -1) return true;   if (Patch =3D=3D -1) return fals=
e;
-  if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false;
-
-  // Finally, between completely tied version numbers, the version with the
-  // suffix loses as we prefer full releases.
-  if (RHS.PatchSuffix.empty()) return true;
-  return false;
-}
-
-/// \brief Construct a GCCInstallationDetector from the driver.
-///
-/// This performs all of the autodetection and sets up the various paths.
-/// Once constructed, a GCCInstallation is esentially immutable.
-Linux::GCCInstallationDetector::GCCInstallationDetector(const Driver &D)
-  : IsValid(false),
-    GccTriple(D.DefaultHostTriple) {
-  // FIXME: Using CXX_INCLUDE_ROOT is here is a bit of a hack, but
-  // avoids adding yet another option to configure/cmake.
-  // It would probably be cleaner to break it in two variables
-  // CXX_GCC_ROOT with just /foo/bar
-  // CXX_GCC_VER with 4.5.2
-  // Then we would have
-  // CXX_INCLUDE_ROOT =3D CXX_GCC_ROOT/include/c++/CXX_GCC_VER
-  // and this function would return
-  // CXX_GCC_ROOT/lib/gcc/CXX_INCLUDE_ARCH/CXX_GCC_VER
-  llvm::SmallString<128> CxxIncludeRoot(CXX_INCLUDE_ROOT);
-  if (CxxIncludeRoot !=3D "") {
-    // This is of the form /foo/bar/include/c++/4.5.2/
-    if (CxxIncludeRoot.back() =3D=3D '/')
-      llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the /
-    StringRef Version =3D llvm::sys::path::filename(CxxIncludeRoot);
-    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the version
-    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the c++
-    llvm::sys::path::remove_filename(CxxIncludeRoot); // remove the include
-    GccInstallPath =3D CxxIncludeRoot.str();
-    GccInstallPath.append("/lib/gcc/");
-    GccInstallPath.append(CXX_INCLUDE_ARCH);
-    GccInstallPath.append("/");
-    GccInstallPath.append(Version);
-    GccParentLibPath =3D GccInstallPath + "/../../..";
-    IsValid =3D true;
-    return;
-  }
-
-  llvm::Triple::ArchType HostArch =3D llvm::Triple(GccTriple).getArch();
-  // The library directories which may contain GCC installations.
-  SmallVector<StringRef, 4> CandidateLibDirs;
-  // The compatible GCC triples for this particular architecture.
-  SmallVector<StringRef, 10> CandidateTriples;
-  CollectLibDirsAndTriples(HostArch, CandidateLibDirs, CandidateTriples);
-
-  // Always include the default host triple as the final fallback if no
-  // specific triple is detected.
-  CandidateTriples.push_back(D.DefaultHostTriple);
-
-  // Compute the set of prefixes for our search.
-  SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(),
-                                       D.PrefixDirs.end());
-  Prefixes.push_back(D.SysRoot);
-  Prefixes.push_back(D.SysRoot + "/usr");
-  Prefixes.push_back(D.InstalledDir + "/..");
-
-  // Loop over the various components which exist and select the best GCC
-  // installation available. GCC installs are ranked by version number.
-  Version =3D GCCVersion::Parse("0.0.0");
-  for (unsigned i =3D 0, ie =3D Prefixes.size(); i < ie; ++i) {
-    if (!llvm::sys::fs::exists(Prefixes[i]))
-      continue;
-    for (unsigned j =3D 0, je =3D CandidateLibDirs.size(); j < je; ++j) {
-      const std::string LibDir =3D Prefixes[i] + CandidateLibDirs[j].str();
-      if (!llvm::sys::fs::exists(LibDir))
-        continue;
-      for (unsigned k =3D 0, ke =3D CandidateTriples.size(); k < ke; ++k)
-        ScanLibDirForGCCTriple(HostArch, LibDir, CandidateTriples[k]);
-    }
-  }
-}
-
-/*static*/ void Linux::GCCInstallationDetector::CollectLibDirsAndTriples(
-    llvm::Triple::ArchType HostArch, SmallVectorImpl<StringRef> &LibDirs,
-    SmallVectorImpl<StringRef> &Triples) {
-  if (HostArch =3D=3D llvm::Triple::arm || HostArch =3D=3D llvm::Triple::t=
humb) {
-    static const char *const ARMLibDirs[] =3D { "/lib" };
-    static const char *const ARMTriples[] =3D { "arm-linux-gnueabi" };
-    LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDir=
s));
-    Triples.append(ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriple=
s));
-  } else if (HostArch =3D=3D llvm::Triple::x86_64) {
-    static const char *const X86_64LibDirs[] =3D { "/lib64", "/lib" };
-    static const char *const X86_64Triples[] =3D {
-      "x86_64-linux-gnu",
-      "x86_64-unknown-linux-gnu",
-      "x86_64-pc-linux-gnu",
-      "x86_64-redhat-linux6E",
-      "x86_64-redhat-linux",
-      "x86_64-suse-linux",
-      "x86_64-manbo-linux-gnu",
-      "x86_64-linux-gnu",
-      "x86_64-slackware-linux"
-    };
-    LibDirs.append(X86_64LibDirs,
-                   X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs));
-    Triples.append(X86_64Triples,
-                   X86_64Triples + llvm::array_lengthof(X86_64Triples));
-  } else if (HostArch =3D=3D llvm::Triple::x86) {
-    static const char *const X86LibDirs[] =3D { "/lib32", "/lib" };
-    static const char *const X86Triples[] =3D {
-      "i686-linux-gnu",
-      "i686-pc-linux-gnu",
-      "i486-linux-gnu",
-      "i386-linux-gnu",
-      "i686-redhat-linux",
-      "i586-redhat-linux",
-      "i386-redhat-linux",
-      "i586-suse-linux",
-      "i486-slackware-linux"
-    };
-    LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDir=
s));
-    Triples.append(X86Triples, X86Triples + llvm::array_lengthof(X86Triple=
s));
-  } else if (HostArch =3D=3D llvm::Triple::ppc) {
-    static const char *const PPCLibDirs[] =3D { "/lib32", "/lib" };
-    static const char *const PPCTriples[] =3D {
-      "powerpc-linux-gnu",
-      "powerpc-unknown-linux-gnu"
-    };
-    LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDir=
s));
-    Triples.append(PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriple=
s));
-  } else if (HostArch =3D=3D llvm::Triple::ppc64) {
-    static const char *const PPC64LibDirs[] =3D { "/lib64", "/lib" };
-    static const char *const PPC64Triples[] =3D {
-      "powerpc64-unknown-linux-gnu"
-    };
-    LibDirs.append(PPC64LibDirs,
-                   PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs));
-    Triples.append(PPC64Triples,
-                   PPC64Triples + llvm::array_lengthof(PPC64Triples));
-  }
-}
-
-void Linux::GCCInstallationDetector::ScanLibDirForGCCTriple(
-    llvm::Triple::ArchType HostArch, const std::string &LibDir,
-    StringRef CandidateTriple) {
-  // There are various different suffixes involving the triple we
-  // check for. We also record what is necessary to walk from each back
-  // up to the lib directory.
-  const std::string Suffixes[] =3D {
-    "/gcc/" + CandidateTriple.str(),
-    "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(),
-
-    // Ubuntu has a strange mis-matched pair of triples that this happens =
to
-    // match.
-    // FIXME: It may be worthwhile to generalize this and look for a second
-    // triple.
-    "/i386-linux-gnu/gcc/" + CandidateTriple.str()
-  };
-  const std::string InstallSuffixes[] =3D {
-    "/../../..",
-    "/../../../..",
-    "/../../../.."
-  };
-  // Only look at the final, weird Ubuntu suffix for i386-linux-gnu.
-  const unsigned NumSuffixes =3D (llvm::array_lengthof(Suffixes) -
-                                (HostArch !=3D llvm::Triple::x86));
-  for (unsigned i =3D 0; i < NumSuffixes; ++i) {
-    StringRef Suffix =3D Suffixes[i];
-    llvm::error_code EC;
-    for (llvm::sys::fs::directory_iterator LI(LibDir + Suffix, EC), LE;
-         !EC && LI !=3D LE; LI =3D LI.increment(EC)) {
-      StringRef VersionText =3D llvm::sys::path::filename(LI->path());
-      GCCVersion CandidateVersion =3D GCCVersion::Parse(VersionText);
-      static const GCCVersion MinVersion =3D { "4.1.1", 4, 1, 1, "" };
-      if (CandidateVersion < MinVersion)
-        continue;
-      if (CandidateVersion <=3D Version)
-        continue;
-      if (!llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
-        continue;
-
-      Version =3D CandidateVersion;
-      GccTriple =3D CandidateTriple.str();
-      // FIXME: We hack together the directory name here instead of
-      // using LI to ensure stable path separators across Windows and
-      // Linux.
-      GccInstallPath =3D LibDir + Suffixes[i] + "/" + VersionText.str();
-      GccParentLibPath =3D GccInstallPath + InstallSuffixes[i];
-      IsValid =3D true;
-    }
-  }
-}
-
-static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
-  if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
-}
-
 /// \brief Get our best guess at the multiarch triple for a target.
 ///
 /// Debian-based systems are starting to use a multiarch setup where they =
use
@@ -1771,36 +1956,49 @@
=20
     // We use the existence of '/lib/<triple>' as a directory to detect so=
me
     // common linux triples that don't quite match the Clang triple for bo=
th
-    // 32-bit and 64-bit targets. This works around annoying discrepancies=
 on
-    // Debian-based systems.
+    // 32-bit and 64-bit targets. Multiarch fixes its install triples to t=
hese
+    // regardless of what the actual target triple is.
   case llvm::Triple::x86:
-    if (llvm::sys::fs::exists(SysRoot + "/lib/i686-linux-gnu"))
-      return "i686-linux-gnu";
     if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu"))
       return "i386-linux-gnu";
     return TargetTriple.str();
   case llvm::Triple::x86_64:
     if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu"))
       return "x86_64-linux-gnu";
-    if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-pc-linux-gnu"))
-      return "x86_64-pc-linux-gnu";
-    if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-unknown-linux-gnu"))
-      return "x86_64-unknown-linux-gnu";
+    return TargetTriple.str();
+  case llvm::Triple::mips:
+    if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu"))
+      return "mips-linux-gnu";
+    return TargetTriple.str();
+  case llvm::Triple::mipsel:
+    if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu"))
+      return "mipsel-linux-gnu";
+    return TargetTriple.str();
+  case llvm::Triple::ppc:
+    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu"))
+      return "powerpc-linux-gnu";
+    return TargetTriple.str();
+  case llvm::Triple::ppc64:
+    if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu"))
+      return "powerpc64-linux-gnu";
     return TargetTriple.str();
   }
 }
=20
-Linux::Linux(const HostInfo &Host, const llvm::Triple &Triple)
-  : Generic_ELF(Host, Triple), GCCInstallation(getDriver()) {
-  llvm::Triple::ArchType Arch =3D
-    llvm::Triple(getDriver().DefaultHostTriple).getArch();
+static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
+  if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
+}
+
+Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &A=
rgs)
+  : Generic_ELF(D, Triple, Args) {
+  llvm::Triple::ArchType Arch =3D Triple.getArch();
   const std::string &SysRoot =3D getDriver().SysRoot;
=20
   // OpenSuse stores the linker with the compiler, add that to the search
   // path.
   ToolChain::path_list &PPaths =3D getProgramPaths();
   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
-                         GCCInstallation.getTriple() + "/bin").str());
+                         GCCInstallation.getTriple().str() + "/bin").str()=
);
=20
   Linker =3D GetProgramPath("ld");
=20
@@ -1814,13 +2012,27 @@
   if (Arch =3D=3D llvm::Triple::arm || Arch =3D=3D llvm::Triple::thumb)
     ExtraOpts.push_back("-X");
=20
-  if (IsRedhat(Distro) || IsOpenSuse(Distro) || Distro =3D=3D UbuntuMaveri=
ck ||
-      Distro =3D=3D UbuntuNatty || Distro =3D=3D UbuntuOneiric)
-    ExtraOpts.push_back("--hash-style=3Dgnu");
+  const bool IsMips =3D Arch =3D=3D llvm::Triple::mips ||
+                      Arch =3D=3D llvm::Triple::mipsel ||
+                      Arch =3D=3D llvm::Triple::mips64 ||
+                      Arch =3D=3D llvm::Triple::mips64el;
=20
-  if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro =3D=3D UbuntuLucid =
||
-      Distro =3D=3D UbuntuJaunty || Distro =3D=3D UbuntuKarmic)
-    ExtraOpts.push_back("--hash-style=3Dboth");
+  const bool IsAndroid =3D Triple.getEnvironment() =3D=3D llvm::Triple::AN=
DROIDEABI;
+
+  // Do not use 'gnu' hash style for Mips targets because .gnu.hash
+  // and the MIPS ABI require .dynsym to be sorted in different ways.
+  // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
+  // ABI requires a mapping between the GOT and the symbol table.
+  // Android loader does not support .gnu.hash.
+  if (!IsMips && !IsAndroid) {
+    if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
+        (IsUbuntu(Distro) && Distro >=3D UbuntuMaverick))
+      ExtraOpts.push_back("--hash-style=3Dgnu");
+
+    if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro =3D=3D UbuntuLuci=
d ||
+        Distro =3D=3D UbuntuJaunty || Distro =3D=3D UbuntuKarmic)
+      ExtraOpts.push_back("--hash-style=3Dboth");
+  }
=20
   if (IsRedhat(Distro))
     ExtraOpts.push_back("--no-add-needed");
@@ -1828,9 +2040,7 @@
   if (Distro =3D=3D DebianSqueeze || Distro =3D=3D DebianWheezy ||
       IsOpenSuse(Distro) ||
       (IsRedhat(Distro) && Distro !=3D RHEL4 && Distro !=3D RHEL5) ||
-      Distro =3D=3D UbuntuLucid ||
-      Distro =3D=3D UbuntuMaverick || Distro =3D=3D UbuntuKarmic ||
-      Distro =3D=3D UbuntuNatty || Distro =3D=3D UbuntuOneiric)
+      (IsUbuntu(Distro) && Distro >=3D UbuntuKarmic))
     ExtraOpts.push_back("--build-id");
=20
   if (IsOpenSuse(Distro))
@@ -1842,24 +2052,31 @@
   // possible permutations of these directories, and seeing which ones it =
added
   // to the link paths.
   path_list &Paths =3D getFilePaths();
-  const bool Is32Bits =3D (getArch() =3D=3D llvm::Triple::x86 ||
-                         getArch() =3D=3D llvm::Triple::ppc);
=20
-  const std::string Suffix32 =3D Arch =3D=3D llvm::Triple::x86_64 ? "/32" =
: "";
-  const std::string Suffix64 =3D Arch =3D=3D llvm::Triple::x86_64 ? "" : "=
/64";
-  const std::string Suffix =3D Is32Bits ? Suffix32 : Suffix64;
-  const std::string Multilib =3D Is32Bits ? "lib32" : "lib64";
+  const std::string Multilib =3D Triple.isArch32Bit() ? "lib32" : "lib64";
   const std::string MultiarchTriple =3D getMultiarchTriple(Triple, SysRoot=
);
=20
   // Add the multilib suffixed paths where they are available.
   if (GCCInstallation.isValid()) {
+    const llvm::Triple &GCCTriple =3D GCCInstallation.getTriple();
     const std::string &LibPath =3D GCCInstallation.getParentLibPath();
-    const std::string &GccTriple =3D GCCInstallation.getTriple();
-    addPathIfExists(GCCInstallation.getInstallPath() + Suffix, Paths);
-    addPathIfExists(LibPath + "/../" + GccTriple + "/lib/../" + Multilib,
+    addPathIfExists((GCCInstallation.getInstallPath() +
+                     GCCInstallation.getMultiarchSuffix()),
                     Paths);
-    addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
-    addPathIfExists(LibPath + "/../" + Multilib, Paths);
+
+    // If the GCC installation we found is inside of the sysroot, we want =
to
+    // prefer libraries installed in the parent prefix of the GCC installa=
tion.
+    // It is important to *not* use these paths when the GCC installation =
is
+    // outside of the system root as that can pick up un-intented librarie=
s.
+    // This usually happens when there is an external cross compiler on the
+    // host system, and a more minimal sysroot available that is the targe=
t of
+    // the cross.
+    if (StringRef(LibPath).startswith(SysRoot)) {
+      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Mu=
ltilib,
+                      Paths);
+      addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
+      addPathIfExists(LibPath + "/../" + Multilib, Paths);
+    }
   }
   addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
   addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
@@ -1869,22 +2086,22 @@
   // Try walking via the GCC triple path in case of multiarch GCC
   // installations with strange symlinks.
   if (GCCInstallation.isValid())
-    addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple() +
+    addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().st=
r() +
                     "/../../" + Multilib, Paths);
=20
   // Add the non-multilib suffixed paths (if potentially different).
   if (GCCInstallation.isValid()) {
     const std::string &LibPath =3D GCCInstallation.getParentLibPath();
-    const std::string &GccTriple =3D GCCInstallation.getTriple();
-    if (!Suffix.empty())
+    const llvm::Triple &GCCTriple =3D GCCInstallation.getTriple();
+    if (!GCCInstallation.getMultiarchSuffix().empty())
       addPathIfExists(GCCInstallation.getInstallPath(), Paths);
-    addPathIfExists(LibPath + "/../" + GccTriple + "/lib", Paths);
-    addPathIfExists(LibPath + "/" + MultiarchTriple, Paths);
-    addPathIfExists(LibPath, Paths);
+
+    if (StringRef(LibPath).startswith(SysRoot)) {
+      addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
+      addPathIfExists(LibPath, Paths);
+    }
   }
-  addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
   addPathIfExists(SysRoot + "/lib", Paths);
-  addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
   addPathIfExists(SysRoot + "/usr/lib", Paths);
 }
=20
@@ -1981,6 +2198,18 @@
   const StringRef ARMMultiarchIncludeDirs[] =3D {
     "/usr/include/arm-linux-gnueabi"
   };
+  const StringRef MIPSMultiarchIncludeDirs[] =3D {
+    "/usr/include/mips-linux-gnu"
+  };
+  const StringRef MIPSELMultiarchIncludeDirs[] =3D {
+    "/usr/include/mipsel-linux-gnu"
+  };
+  const StringRef PPCMultiarchIncludeDirs[] =3D {
+    "/usr/include/powerpc-linux-gnu"
+  };
+  const StringRef PPC64MultiarchIncludeDirs[] =3D {
+    "/usr/include/powerpc64-linux-gnu"
+  };
   ArrayRef<StringRef> MultiarchIncludeDirs;
   if (getTriple().getArch() =3D=3D llvm::Triple::x86_64) {
     MultiarchIncludeDirs =3D X86_64MultiarchIncludeDirs;
@@ -1988,11 +2217,19 @@
     MultiarchIncludeDirs =3D X86MultiarchIncludeDirs;
   } else if (getTriple().getArch() =3D=3D llvm::Triple::arm) {
     MultiarchIncludeDirs =3D ARMMultiarchIncludeDirs;
+  } else if (getTriple().getArch() =3D=3D llvm::Triple::mips) {
+    MultiarchIncludeDirs =3D MIPSMultiarchIncludeDirs;
+  } else if (getTriple().getArch() =3D=3D llvm::Triple::mipsel) {
+    MultiarchIncludeDirs =3D MIPSELMultiarchIncludeDirs;
+  } else if (getTriple().getArch() =3D=3D llvm::Triple::ppc) {
+    MultiarchIncludeDirs =3D PPCMultiarchIncludeDirs;
+  } else if (getTriple().getArch() =3D=3D llvm::Triple::ppc64) {
+    MultiarchIncludeDirs =3D PPC64MultiarchIncludeDirs;
   }
   for (ArrayRef<StringRef>::iterator I =3D MultiarchIncludeDirs.begin(),
                                      E =3D MultiarchIncludeDirs.end();
        I !=3D E; ++I) {
-    if (llvm::sys::fs::exists(*I)) {
+    if (llvm::sys::fs::exists(D.SysRoot + *I)) {
       addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
       break;
     }
@@ -2001,12 +2238,18 @@
   if (getTriple().getOS() =3D=3D llvm::Triple::RTEMS)
     return;
=20
+  // Add an include of '/include' directly. This isn't provided by default=
 by
+  // system GCCs, but is often used with cross-compiling GCCs, and harmles=
s to
+  // add even when Clang is acting as-if it were a system compiler.
+  addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
+
   addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
 }
=20
-static bool addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
-                                     const ArgList &DriverArgs,
-                                     ArgStringList &CC1Args) {
+/// \brief Helper to add the thre variant paths for a libstdc++ installati=
on.
+/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetAr=
chDir,
+                                                const ArgList &DriverArgs,
+                                                ArgStringList &CC1Args) {
   if (!llvm::sys::fs::exists(Base))
     return false;
   addSystemInclude(DriverArgs, CC1Args, Base);
@@ -2029,37 +2272,10 @@
     return;
   }
=20
-  const llvm::Triple &TargetTriple =3D getTriple();
-  const llvm::Triple::ArchType TargetArch =3D TargetTriple.getArch();
-  bool IsTarget64Bit =3D (TargetArch =3D=3D llvm::Triple::x86_64 ||
-                        TargetArch =3D=3D llvm::Triple::ppc64);
-
-  StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
-  if (!CxxIncludeRoot.empty()) {
-    StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
-    if (CxxIncludeArch.empty())
-      CxxIncludeArch =3D TargetTriple.str();
-
-    addLibStdCXXIncludePaths(
-      CxxIncludeRoot,
-      CxxIncludeArch + (IsTarget64Bit ? CXX_INCLUDE_64BIT_DIR
-                                      : CXX_INCLUDE_32BIT_DIR),
-      DriverArgs, CC1Args);
+  // We need a detected GCC installation on Linux to provide libstdc++'s
+  // headers. We handled the libc++ case above.
+  if (!GCCInstallation.isValid())
     return;
-  }
-
-  // Check if the target architecture specific dirs need a suffix. Note th=
at we
-  // only support the suffix-based bi-arch-like header scheme for host/tar=
get
-  // mismatches of just bit width.
-  llvm::Triple::ArchType HostArch =3D
-    llvm::Triple(getDriver().DefaultHostTriple).getArch();
-  StringRef Suffix;
-  if ((HostArch =3D=3D llvm::Triple::x86 && TargetArch =3D=3D llvm::Triple=
::x86_64) ||
-      (HostArch =3D=3D llvm::Triple::ppc && TargetArch =3D=3D llvm::Triple=
::ppc64))
-    Suffix =3D "/64";
-  if ((HostArch =3D=3D llvm::Triple::x86_64 && TargetArch =3D=3D llvm::Tri=
ple::x86) ||
-      (HostArch =3D=3D llvm::Triple::ppc64 && TargetArch =3D=3D llvm::Trip=
le::ppc))
-    Suffix =3D "/32";
=20
   // By default, look for the C++ headers in an include directory adjacent=
 to
   // the lib directory of the GCC installation. Note that this is expect t=
o be
@@ -2068,20 +2284,22 @@
   StringRef InstallDir =3D GCCInstallation.getInstallPath();
   StringRef Version =3D GCCInstallation.getVersion();
   if (!addLibStdCXXIncludePaths(LibDir + "/../include/c++/" + Version,
-                                GCCInstallation.getTriple() + Suffix,
+                                (GCCInstallation.getTriple().str() +
+                                 GCCInstallation.getMultiarchSuffix()),
                                 DriverArgs, CC1Args)) {
     // Gentoo is weird and places its headers inside the GCC install, so i=
f the
     // first attempt to find the headers fails, try this pattern.
     addLibStdCXXIncludePaths(InstallDir + "/include/g++-v4",
-                             GCCInstallation.getTriple() + Suffix,
+                             (GCCInstallation.getTriple().str() +
+                              GCCInstallation.getMultiarchSuffix()),
                              DriverArgs, CC1Args);
   }
 }
=20
 /// DragonFly - DragonFly tool chain which can call as(1) and ld(1) direct=
ly.
=20
-DragonFly::DragonFly(const HostInfo &Host, const llvm::Triple& Triple)
-  : Generic_ELF(Host, Triple) {
+DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const Ar=
gList &Args)
+  : Generic_ELF(D, Triple, Args) {
=20
   // Path mangling to find libexec
   getProgramPaths().push_back(getDriver().getInstalledDir());
@@ -2115,322 +2333,3 @@
=20
   return *T;
 }
-
-Windows::Windows(const HostInfo &Host, const llvm::Triple& Triple)
-  : ToolChain(Host, Triple) {
-}
-
-Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA,
-                          const ActionList &Inputs) const {
-  Action::ActionClass Key;
-  if (getDriver().ShouldUseClangCompiler(C, JA, getTriple()))
-    Key =3D Action::AnalyzeJobClass;
-  else
-    Key =3D JA.getKind();
-
-  bool UseIntegratedAs =3D C.getArgs().hasFlag(options::OPT_integrated_as,
-                                             options::OPT_no_integrated_as,
-                                             IsIntegratedAssemblerDefault(=
));
-
-  Tool *&T =3D Tools[Key];
-  if (!T) {
-    switch (Key) {
-    case Action::InputClass:
-    case Action::BindArchClass:
-    case Action::LipoJobClass:
-    case Action::DsymutilJobClass:
-    case Action::VerifyJobClass:
-      llvm_unreachable("Invalid tool kind.");
-    case Action::PreprocessJobClass:
-    case Action::PrecompileJobClass:
-    case Action::AnalyzeJobClass:
-    case Action::CompileJobClass:
-      T =3D new tools::Clang(*this); break;
-    case Action::AssembleJobClass:
-      if (!UseIntegratedAs && getTriple().getEnvironment() =3D=3D llvm::Tr=
iple::MachO)
-        T =3D new tools::darwin::Assemble(*this);
-      else
-        T =3D new tools::ClangAs(*this);
-      break;
-    case Action::LinkJobClass:
-      T =3D new tools::visualstudio::Link(*this); break;
-    }
-  }
-
-  return *T;
-}
-
-bool Windows::IsIntegratedAssemblerDefault() const {
-  return true;
-}
-
-bool Windows::IsUnwindTablesDefault() const {
-  // FIXME: Gross; we should probably have some separate target
-  // definition, possibly even reusing the one in clang.
-  return getArchName() =3D=3D "x86_64";
-}
-
-const char *Windows::GetDefaultRelocationModel() const {
-  return "static";
-}
-
-const char *Windows::GetForcedPicModel() const {
-  if (getArchName() =3D=3D "x86_64")
-    return "pic";
-  return 0;
-}
-
-// FIXME: This probably should goto to some platform utils place.
-#ifdef _MSC_VER
-
-/// \brief Read registry string.
-/// This also supports a means to look for high-versioned keys by use
-/// of a $VERSION placeholder in the key path.
-/// $VERSION in the key path is a placeholder for the version number,
-/// causing the highest value path to be searched for and used.
-/// I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION".
-/// There can be additional characters in the component.  Only the numberic
-/// characters are compared.
-static bool getSystemRegistryString(const char *keyPath, const char *value=
Name,
-                                    char *value, size_t maxLength) {
-  HKEY hRootKey =3D NULL;
-  HKEY hKey =3D NULL;
-  const char* subKey =3D NULL;
-  DWORD valueType;
-  DWORD valueSize =3D maxLength - 1;
-  long lResult;
-  bool returnValue =3D false;
-
-  if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) =3D=3D 0) {
-    hRootKey =3D HKEY_CLASSES_ROOT;
-    subKey =3D keyPath + 18;
-  } else if (strncmp(keyPath, "HKEY_USERS\\", 11) =3D=3D 0) {
-    hRootKey =3D HKEY_USERS;
-    subKey =3D keyPath + 11;
-  } else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) =3D=3D 0) {
-    hRootKey =3D HKEY_LOCAL_MACHINE;
-    subKey =3D keyPath + 19;
-  } else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) =3D=3D 0) {
-    hRootKey =3D HKEY_CURRENT_USER;
-    subKey =3D keyPath + 18;
-  } else {
-    return false;
-  }
-
-  const char *placeHolder =3D strstr(subKey, "$VERSION");
-  char bestName[256];
-  bestName[0] =3D '\0';
-  // If we have a $VERSION placeholder, do the highest-version search.
-  if (placeHolder) {
-    const char *keyEnd =3D placeHolder - 1;
-    const char *nextKey =3D placeHolder;
-    // Find end of previous key.
-    while ((keyEnd > subKey) && (*keyEnd !=3D '\\'))
-      keyEnd--;
-    // Find end of key containing $VERSION.
-    while (*nextKey && (*nextKey !=3D '\\'))
-      nextKey++;
-    size_t partialKeyLength =3D keyEnd - subKey;
-    char partialKey[256];
-    if (partialKeyLength > sizeof(partialKey))
-      partialKeyLength =3D sizeof(partialKey);
-    strncpy(partialKey, subKey, partialKeyLength);
-    partialKey[partialKeyLength] =3D '\0';
-    HKEY hTopKey =3D NULL;
-    lResult =3D RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey);
-    if (lResult =3D=3D ERROR_SUCCESS) {
-      char keyName[256];
-      int bestIndex =3D -1;
-      double bestValue =3D 0.0;
-      DWORD index, size =3D sizeof(keyName) - 1;
-      for (index =3D 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL,
-          NULL, NULL, NULL) =3D=3D ERROR_SUCCESS; index++) {
-        const char *sp =3D keyName;
-        while (*sp && !isdigit(*sp))
-          sp++;
-        if (!*sp)
-          continue;
-        const char *ep =3D sp + 1;
-        while (*ep && (isdigit(*ep) || (*ep =3D=3D '.')))
-          ep++;
-        char numBuf[32];
-        strncpy(numBuf, sp, sizeof(numBuf) - 1);
-        numBuf[sizeof(numBuf) - 1] =3D '\0';
-        double value =3D strtod(numBuf, NULL);
-        if (value > bestValue) {
-          bestIndex =3D (int)index;
-          bestValue =3D value;
-          strcpy(bestName, keyName);
-        }
-        size =3D sizeof(keyName) - 1;
-      }
-      // If we found the highest versioned key, open the key and get the v=
alue.
-      if (bestIndex !=3D -1) {
-        // Append rest of key.
-        strncat(bestName, nextKey, sizeof(bestName) - 1);
-        bestName[sizeof(bestName) - 1] =3D '\0';
-        // Open the chosen key path remainder.
-        lResult =3D RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey);
-        if (lResult =3D=3D ERROR_SUCCESS) {
-          lResult =3D RegQueryValueEx(hKey, valueName, NULL, &valueType,
-            (LPBYTE)value, &valueSize);
-          if (lResult =3D=3D ERROR_SUCCESS)
-            returnValue =3D true;
-          RegCloseKey(hKey);
-        }
-      }
-      RegCloseKey(hTopKey);
-    }
-  } else {
-    lResult =3D RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey);
-    if (lResult =3D=3D ERROR_SUCCESS) {
-      lResult =3D RegQueryValueEx(hKey, valueName, NULL, &valueType,
-        (LPBYTE)value, &valueSize);
-      if (lResult =3D=3D ERROR_SUCCESS)
-        returnValue =3D true;
-      RegCloseKey(hKey);
-    }
-  }
-  return returnValue;
-}
-
-/// \brief Get Windows SDK installation directory.
-static bool getWindowsSDKDir(std::string &path) {
-  char windowsSDKInstallDir[256];
-  // Try the Windows registry.
-  bool hasSDKDir =3D getSystemRegistryString(
-   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VER=
SION",
-                                           "InstallationFolder",
-                                           windowsSDKInstallDir,
-                                           sizeof(windowsSDKInstallDir) - =
1);
-    // If we have both vc80 and vc90, pick version we were compiled with.
-  if (hasSDKDir && windowsSDKInstallDir[0]) {
-    path =3D windowsSDKInstallDir;
-    return true;
-  }
-  return false;
-}
-
-  // Get Visual Studio installation directory.
-static bool getVisualStudioDir(std::string &path) {
-  // First check the environment variables that vsvars32.bat sets.
-  const char* vcinstalldir =3D getenv("VCINSTALLDIR");
-  if (vcinstalldir) {
-    char *p =3D const_cast<char *>(strstr(vcinstalldir, "\\VC"));
-    if (p)
-      *p =3D '\0';
-    path =3D vcinstalldir;
-    return true;
-  }
-
-  char vsIDEInstallDir[256];
-  char vsExpressIDEInstallDir[256];
-  // Then try the windows registry.
-  bool hasVCDir =3D getSystemRegistryString(
-    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION",
-    "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1);
-  bool hasVCExpressDir =3D getSystemRegistryString(
-    "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION",
-    "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) -=
 1);
-    // If we have both vc80 and vc90, pick version we were compiled with.
-  if (hasVCDir && vsIDEInstallDir[0]) {
-    char *p =3D (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE");
-    if (p)
-      *p =3D '\0';
-    path =3D vsIDEInstallDir;
-    return true;
-  }
-
-  if (hasVCExpressDir && vsExpressIDEInstallDir[0]) {
-    char *p =3D (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE");
-    if (p)
-      *p =3D '\0';
-    path =3D vsExpressIDEInstallDir;
-    return true;
-  }
-
-  // Try the environment.
-  const char *vs100comntools =3D getenv("VS100COMNTOOLS");
-  const char *vs90comntools =3D getenv("VS90COMNTOOLS");
-  const char *vs80comntools =3D getenv("VS80COMNTOOLS");
-  const char *vscomntools =3D NULL;
-
-  // Try to find the version that we were compiled with
-  if(false) {}
-  #if (_MSC_VER >=3D 1600)  // VC100
-  else if(vs100comntools) {
-    vscomntools =3D vs100comntools;
-  }
-  #elif (_MSC_VER =3D=3D 1500) // VC80
-  else if(vs90comntools) {
-    vscomntools =3D vs90comntools;
-  }
-  #elif (_MSC_VER =3D=3D 1400) // VC80
-  else if(vs80comntools) {
-    vscomntools =3D vs80comntools;
-  }
-  #endif
-  // Otherwise find any version we can
-  else if (vs100comntools)
-    vscomntools =3D vs100comntools;
-  else if (vs90comntools)
-    vscomntools =3D vs90comntools;
-  else if (vs80comntools)
-    vscomntools =3D vs80comntools;
-
-  if (vscomntools && *vscomntools) {
-    const char *p =3D strstr(vscomntools, "\\Common7\\Tools");
-    path =3D p ? std::string(vscomntools, p) : vscomntools;
-    return true;
-  }
-  return false;
-}
-
-#endif // _MSC_VER
-
-void Windows::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
-                                        ArgStringList &CC1Args) const {
-  if (DriverArgs.hasArg(options::OPT_nostdinc))
-    return;
-
-  if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
-    llvm::sys::Path P(getDriver().ResourceDir);
-    P.appendComponent("include");
-    addSystemInclude(DriverArgs, CC1Args, P.str());
-  }
-
-  if (DriverArgs.hasArg(options::OPT_nostdlibinc))
-    return;
-
-  std::string VSDir;
-  std::string WindowsSDKDir;
-
-#ifdef _MSC_VER
-  // When built with access to the proper Windows APIs, try to actually fi=
nd
-  // the correct include paths first.
-  if (getVisualStudioDir(VSDir)) {
-    addSystemInclude(DriverArgs, CC1Args, VSDir + "\\VC\\include");
-    if (getWindowsSDKDir(WindowsSDKDir))
-      addSystemInclude(DriverArgs, CC1Args, WindowsSDKDir + "\\include");
-    else
-      addSystemInclude(DriverArgs, CC1Args,
-                       VSDir + "\\VC\\PlatformSDK\\Include");
-    return;
-  }
-#endif // _MSC_VER
-
-  // As a fallback, select default install paths.
-  const StringRef Paths[] =3D {
-    "C:/Program Files/Microsoft Visual Studio 10.0/VC/include",
-    "C:/Program Files/Microsoft Visual Studio 9.0/VC/include",
-    "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include",
-    "C:/Program Files/Microsoft Visual Studio 8/VC/include",
-    "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include"
-  };
-  addSystemIncludes(DriverArgs, CC1Args, Paths);
-}
-
-void Windows::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
-                                           ArgStringList &CC1Args) const {
-  // FIXME: There should probably be logic here to find libc++ on Windows.
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/ToolChains.h
--- a/head/contrib/llvm/tools/clang/lib/Driver/ToolChains.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/ToolChains.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -13,6 +13,7 @@
 #include "clang/Driver/Action.h"
 #include "clang/Driver/ToolChain.h"
=20
+#include "clang/Basic/VersionTuple.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/Support/Compiler.h"
=20
@@ -27,10 +28,100 @@
 /// command line options.
 class LLVM_LIBRARY_VISIBILITY Generic_GCC : public ToolChain {
 protected:
+  /// \brief Struct to store and manipulate GCC versions.
+  ///
+  /// We rely on assumptions about the form and structure of GCC version
+  /// numbers: they consist of at most three '.'-separated components, and=
 each
+  /// component is a non-negative integer except for the last component. F=
or
+  /// the last component we are very flexible in order to tolerate release
+  /// candidates or 'x' wildcards.
+  ///
+  /// Note that the ordering established among GCCVersions is based on the
+  /// preferred version string to use. For example we prefer versions with=
out
+  /// a hard-coded patch number to those with a hard coded patch number.
+  ///
+  /// Currently this doesn't provide any logic for textual suffixes to pat=
ches
+  /// in the way that (for example) Debian's version format does. If that =
ever
+  /// becomes necessary, it can be added.
+  struct GCCVersion {
+    /// \brief The unparsed text of the version.
+    std::string Text;
+
+    /// \brief The parsed major, minor, and patch numbers.
+    int Major, Minor, Patch;
+
+    /// \brief Any textual suffix on the patch number.
+    std::string PatchSuffix;
+
+    static GCCVersion Parse(StringRef VersionText);
+    bool operator<(const GCCVersion &RHS) const;
+    bool operator>(const GCCVersion &RHS) const { return RHS < *this; }
+    bool operator<=3D(const GCCVersion &RHS) const { return !(*this > RHS)=
; }
+    bool operator>=3D(const GCCVersion &RHS) const { return !(*this < RHS)=
; }
+  };
+
+
+  /// \brief This is a class to find a viable GCC installation for Clang to
+  /// use.
+  ///
+  /// This class tries to find a GCC installation on the system, and report
+  /// information about it. It starts from the host information provided t=
o the
+  /// Driver, and has logic for fuzzing that where appropriate.
+  class GCCInstallationDetector {
+
+    bool IsValid;
+    llvm::Triple GCCTriple;
+
+    // FIXME: These might be better as path objects.
+    std::string GCCInstallPath;
+    std::string GCCMultiarchSuffix;
+    std::string GCCParentLibPath;
+
+    GCCVersion Version;
+
+  public:
+    GCCInstallationDetector(const Driver &D, const llvm::Triple &TargetTri=
ple,
+                            const ArgList &Args);
+
+    /// \brief Check whether we detected a valid GCC install.
+    bool isValid() const { return IsValid; }
+
+    /// \brief Get the GCC triple for the detected install.
+    const llvm::Triple &getTriple() const { return GCCTriple; }
+
+    /// \brief Get the detected GCC installation path.
+    StringRef getInstallPath() const { return GCCInstallPath; }
+
+    /// \brief Get the detected GCC installation path suffix for multiarch=
 GCCs.
+    StringRef getMultiarchSuffix() const { return GCCMultiarchSuffix; }
+
+    /// \brief Get the detected GCC parent lib path.
+    StringRef getParentLibPath() const { return GCCParentLibPath; }
+
+    /// \brief Get the detected GCC version string.
+    StringRef getVersion() const { return Version.Text; }
+
+  private:
+    static void CollectLibDirsAndTriples(
+      const llvm::Triple &TargetTriple,
+      const llvm::Triple &MultiarchTriple,
+      SmallVectorImpl<StringRef> &LibDirs,
+      SmallVectorImpl<StringRef> &TripleAliases,
+      SmallVectorImpl<StringRef> &MultiarchLibDirs,
+      SmallVectorImpl<StringRef> &MultiarchTripleAliases);
+
+    void ScanLibDirForGCCTriple(llvm::Triple::ArchType TargetArch,
+                                const std::string &LibDir,
+                                StringRef CandidateTriple,
+                                bool NeedsMultiarchSuffix =3D false);
+  };
+
+  GCCInstallationDetector GCCInstallation;
+
   mutable llvm::DenseMap<unsigned, Tool*> Tools;
=20
 public:
-  Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple);
+  Generic_GCC(const Driver &D, const llvm::Triple& Triple, const ArgList &=
Args);
   ~Generic_GCC();
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
@@ -39,9 +130,37 @@
   virtual bool IsUnwindTablesDefault() const;
   virtual const char *GetDefaultRelocationModel() const;
   virtual const char *GetForcedPicModel() const;
+
+protected:
+  /// \name ToolChain Implementation Helper Functions
+  /// @{
+
+  /// \brief Check whether the target triple's architecture is 64-bits.
+  bool isTarget64Bit() const { return getTriple().isArch64Bit(); }
+
+  /// \brief Check whether the target triple's architecture is 32-bits.
+  bool isTarget32Bit() const { return getTriple().isArch32Bit(); }
+
+  /// @}
+};
+
+class LLVM_LIBRARY_VISIBILITY Hexagon_TC : public ToolChain {
+protected:
+  mutable llvm::DenseMap<unsigned, Tool*> Tools;
+
+public:
+  Hexagon_TC(const Driver &D, const llvm::Triple& Triple);
+  ~Hexagon_TC();
+
+  virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
+                           const ActionList &Inputs) const;
+
+  virtual bool IsUnwindTablesDefault() const;
+  virtual const char *GetDefaultRelocationModel() const;
+  virtual const char *GetForcedPicModel() const;
 };
=20
-/// Darwin - The base Darwin tool chain.
+  /// Darwin - The base Darwin tool chain.
 class LLVM_LIBRARY_VISIBILITY Darwin : public ToolChain {
 public:
   /// The host version.
@@ -80,19 +199,20 @@
   mutable bool TargetIsIPhoneOSSimulator;
=20
   /// The OS version we are targeting.
-  mutable unsigned TargetVersion[3];
+  mutable VersionTuple TargetVersion;
=20
   /// The default macosx-version-min of this tool chain; empty until
   /// initialized.
   std::string MacosxVersionMin;
=20
   bool hasARCRuntime() const;
+  bool hasSubscriptingRuntime() const;
=20
 private:
   void AddDeploymentTarget(DerivedArgList &Args) const;
=20
 public:
-  Darwin(const HostInfo &Host, const llvm::Triple& Triple);
+  Darwin(const Driver &D, const llvm::Triple& Triple);
   ~Darwin();
=20
   std::string ComputeEffectiveClangTriple(const ArgList &Args,
@@ -111,17 +231,14 @@
     // change. This will go away when we move away from argument translati=
on.
     if (TargetInitialized && TargetIsIPhoneOS =3D=3D IsIPhoneOS &&
         TargetIsIPhoneOSSimulator =3D=3D IsIOSSim &&
-        TargetVersion[0] =3D=3D Major && TargetVersion[1] =3D=3D Minor &&
-        TargetVersion[2] =3D=3D Micro)
+        TargetVersion =3D=3D VersionTuple(Major, Minor, Micro))
       return;
=20
     assert(!TargetInitialized && "Target already initialized!");
     TargetInitialized =3D true;
     TargetIsIPhoneOS =3D IsIPhoneOS;
     TargetIsIPhoneOSSimulator =3D IsIOSSim;
-    TargetVersion[0] =3D Major;
-    TargetVersion[1] =3D Minor;
-    TargetVersion[2] =3D Micro;
+    TargetVersion =3D VersionTuple(Major, Minor, Micro);
   }
=20
   bool isTargetIPhoneOS() const {
@@ -134,13 +251,17 @@
     return TargetIsIPhoneOSSimulator;
   }
=20
+  bool isTargetMacOS() const {
+    return !isTargetIOSSimulator() &&
+           !isTargetIPhoneOS() &&
+           ARCRuntimeForSimulator =3D=3D ARCSimulator_None;
+  }
+
   bool isTargetInitialized() const { return TargetInitialized; }
=20
-  void getTargetVersion(unsigned (&Res)[3]) const {
+  VersionTuple getTargetVersion() const {
     assert(TargetInitialized && "Target not initialized!");
-    Res[0] =3D TargetVersion[0];
-    Res[1] =3D TargetVersion[1];
-    Res[2] =3D TargetVersion[2];
+    return TargetVersion;
   }
=20
   /// getDarwinArchName - Get the "Darwin" arch name for a particular comp=
iler
@@ -148,24 +269,14 @@
   /// distinct architectures.
   StringRef getDarwinArchName(const ArgList &Args) const;
=20
-  static bool isVersionLT(unsigned (&A)[3], unsigned (&B)[3]) {
-    for (unsigned i=3D0; i < 3; ++i) {
-      if (A[i] > B[i]) return false;
-      if (A[i] < B[i]) return true;
-    }
-    return false;
-  }
-
   bool isIPhoneOSVersionLT(unsigned V0, unsigned V1=3D0, unsigned V2=3D0) =
const {
     assert(isTargetIPhoneOS() && "Unexpected call for OS X target!");
-    unsigned B[3] =3D { V0, V1, V2 };
-    return isVersionLT(TargetVersion, B);
+    return TargetVersion < VersionTuple(V0, V1, V2);
   }
=20
   bool isMacosxVersionLT(unsigned V0, unsigned V1=3D0, unsigned V2=3D0) co=
nst {
     assert(!isTargetIPhoneOS() && "Unexpected call for iPhoneOS target!");
-    unsigned B[3] =3D { V0, V1, V2 };
-    return isVersionLT(TargetVersion, B);
+    return TargetVersion < VersionTuple(V0, V1, V2);
   }
=20
   /// AddLinkSearchPathArgs - Add the linker search paths to \arg CmdArgs.
@@ -211,9 +322,8 @@
 #ifdef DISABLE_DEFAULT_INTEGRATED_ASSEMBLER
     return false;
 #else
-    // Default integrated assembler to on for x86.
-    return (getTriple().getArch() =3D=3D llvm::Triple::x86 ||
-            getTriple().getArch() =3D=3D llvm::Triple::x86_64);
+    // Default integrated assembler to on for Darwin.
+    return true;
 #endif
   }
   virtual bool IsStrictAliasingDefault() const {
@@ -225,7 +335,7 @@
   }
  =20
   virtual bool IsObjCDefaultSynthPropertiesDefault() const {
-    return false;
+    return true;
   }
=20
   virtual bool IsObjCNonFragileABIDefault() const {
@@ -248,10 +358,13 @@
   virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const {
     // Stack protectors default to on for user code on 10.5,
     // and for everything in 10.6 and beyond
-    return !isTargetIPhoneOS() &&
+    return isTargetIPhoneOS() ||
       (!isMacosxVersionLT(10, 6) ||
          (!isMacosxVersionLT(10, 5) && !KernelOrKext));
   }
+  virtual RuntimeLibType GetDefaultRuntimeLibType() const {
+    return ToolChain::RLT_CompilerRT;
+  }
   virtual const char *GetDefaultRelocationModel() const;
   virtual const char *GetForcedPicModel() const;
=20
@@ -259,6 +372,8 @@
=20
   virtual bool SupportsObjCGC() const;
=20
+  virtual bool SupportsObjCARC() const;
+
   virtual bool UseDwarfDebugFlags() const;
=20
   virtual bool UseSjLjExceptions() const;
@@ -272,7 +387,7 @@
   void AddGCCLibexecPath(unsigned darwinVersion);
=20
 public:
-  DarwinClang(const HostInfo &Host, const llvm::Triple& Triple);
+  DarwinClang(const Driver &D, const llvm::Triple& Triple);
=20
   /// @name Darwin ToolChain Implementation
   /// {
@@ -299,8 +414,8 @@
 /// Darwin_Generic_GCC - Generic Darwin tool chain using gcc.
 class LLVM_LIBRARY_VISIBILITY Darwin_Generic_GCC : public Generic_GCC {
 public:
-  Darwin_Generic_GCC(const HostInfo &Host, const llvm::Triple& Triple)
-    : Generic_GCC(Host, Triple) {}
+  Darwin_Generic_GCC(const Driver &D, const llvm::Triple& Triple, const Ar=
gList &Args)
+    : Generic_GCC(D, Triple, Args) {}
=20
   std::string ComputeEffectiveClangTriple(const ArgList &Args,
                                           types::ID InputType) const;
@@ -309,9 +424,10 @@
 };
=20
 class LLVM_LIBRARY_VISIBILITY Generic_ELF : public Generic_GCC {
- public:
-  Generic_ELF(const HostInfo &Host, const llvm::Triple& Triple)
-    : Generic_GCC(Host, Triple) {}
+  virtual void anchor();
+public:
+  Generic_ELF(const Driver &D, const llvm::Triple& Triple, const ArgList &=
Args)
+    : Generic_GCC(D, Triple, Args) {}
=20
   virtual bool IsIntegratedAssemblerDefault() const {
     // Default integrated assembler to on for x86.
@@ -322,15 +438,36 @@
=20
 class LLVM_LIBRARY_VISIBILITY AuroraUX : public Generic_GCC {
 public:
-  AuroraUX(const HostInfo &Host, const llvm::Triple& Triple);
+  AuroraUX(const Driver &D, const llvm::Triple& Triple, const ArgList &Arg=
s);
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
                            const ActionList &Inputs) const;
 };
=20
+class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_GCC {
+public:
+  Solaris(const Driver &D, const llvm::Triple& Triple, const ArgList &Args=
);
+
+  virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
+                           const ActionList &Inputs) const;
+
+  virtual bool IsIntegratedAssemblerDefault() const { return true; }
+};
+
+
 class LLVM_LIBRARY_VISIBILITY OpenBSD : public Generic_ELF {
 public:
-  OpenBSD(const HostInfo &Host, const llvm::Triple& Triple);
+  OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args=
);
+
+  virtual bool IsObjCNonFragileABIDefault() const { return true; }
+  virtual bool IsObjCLegacyDispatchDefault() const {
+    llvm::Triple::ArchType Arch =3D getTriple().getArch();
+    if (Arch =3D=3D llvm::Triple::arm ||
+        Arch =3D=3D llvm::Triple::x86 ||
+        Arch =3D=3D llvm::Triple::x86_64)
+     return false;
+    return true;
+  }
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
                            const ActionList &Inputs) const;
@@ -338,26 +475,43 @@
=20
 class LLVM_LIBRARY_VISIBILITY FreeBSD : public Generic_ELF {
 public:
-  FreeBSD(const HostInfo &Host, const llvm::Triple& Triple);
+  FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args=
);
+
+  virtual bool IsObjCNonFragileABIDefault() const { return true; }
+  virtual bool IsObjCLegacyDispatchDefault() const {
+    llvm::Triple::ArchType Arch =3D getTriple().getArch();
+    if (Arch =3D=3D llvm::Triple::arm ||
+        Arch =3D=3D llvm::Triple::x86 ||
+        Arch =3D=3D llvm::Triple::x86_64)
+     return false;
+    return true;
+  }
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
                            const ActionList &Inputs) const;
 };
=20
 class LLVM_LIBRARY_VISIBILITY NetBSD : public Generic_ELF {
-  const llvm::Triple ToolTriple;
+public:
+  NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args);
=20
-public:
-  NetBSD(const HostInfo &Host, const llvm::Triple& Triple,
-         const llvm::Triple& ToolTriple);
+  virtual bool IsObjCNonFragileABIDefault() const { return true; }
+  virtual bool IsObjCLegacyDispatchDefault() const {
+    llvm::Triple::ArchType Arch =3D getTriple().getArch();
+    if (Arch =3D=3D llvm::Triple::arm ||
+        Arch =3D=3D llvm::Triple::x86 ||
+        Arch =3D=3D llvm::Triple::x86_64)
+     return false;
+    return true;
+  }
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
                            const ActionList &Inputs) const;
 };
=20
-class LLVM_LIBRARY_VISIBILITY Minix : public Generic_GCC {
+class LLVM_LIBRARY_VISIBILITY Minix : public Generic_ELF {
 public:
-  Minix(const HostInfo &Host, const llvm::Triple& Triple);
+  Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args);
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
                            const ActionList &Inputs) const;
@@ -365,95 +519,15 @@
=20
 class LLVM_LIBRARY_VISIBILITY DragonFly : public Generic_ELF {
 public:
-  DragonFly(const HostInfo &Host, const llvm::Triple& Triple);
+  DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Ar=
gs);
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
                            const ActionList &Inputs) const;
 };
=20
 class LLVM_LIBRARY_VISIBILITY Linux : public Generic_ELF {
-  /// \brief Struct to store and manipulate GCC versions.
-  ///
-  /// We rely on assumptions about the form and structure of GCC version
-  /// numbers: they consist of at most three '.'-separated components, and=
 each
-  /// component is a non-negative integer except for the last component. F=
or
-  /// the last component we are very flexible in order to tolerate release
-  /// candidates or 'x' wildcards.
-  ///
-  /// Note that the ordering established among GCCVersions is based on the
-  /// preferred version string to use. For example we prefer versions with=
out
-  /// a hard-coded patch number to those with a hard coded patch number.
-  ///
-  /// Currently this doesn't provide any logic for textual suffixes to pat=
ches
-  /// in the way that (for example) Debian's version format does. If that =
ever
-  /// becomes necessary, it can be added.
-  struct GCCVersion {
-    /// \brief The unparsed text of the version.
-    std::string Text;
-
-    /// \brief The parsed major, minor, and patch numbers.
-    int Major, Minor, Patch;
-
-    /// \brief Any textual suffix on the patch number.
-    std::string PatchSuffix;
-
-    static GCCVersion Parse(StringRef VersionText);
-    bool operator<(const GCCVersion &RHS) const;
-    bool operator>(const GCCVersion &RHS) const { return RHS < *this; }
-    bool operator<=3D(const GCCVersion &RHS) const { return !(*this > RHS)=
; }
-    bool operator>=3D(const GCCVersion &RHS) const { return !(*this < RHS)=
; }
-  };
-
-
-  /// \brief This is a class to find a viable GCC installation for Clang to
-  /// use.
-  ///
-  /// This class tries to find a GCC installation on the system, and report
-  /// information about it. It starts from the host information provided t=
o the
-  /// Driver, and has logic for fuzzing that where appropriate.
-  class GCCInstallationDetector {
-
-    bool IsValid;
-    std::string GccTriple;
-
-    // FIXME: These might be better as path objects.
-    std::string GccInstallPath;
-    std::string GccParentLibPath;
-
-    GCCVersion Version;
-
-  public:
-    GCCInstallationDetector(const Driver &D);
-
-    /// \brief Check whether we detected a valid GCC install.
-    bool isValid() const { return IsValid; }
-
-    /// \brief Get the GCC triple for the detected install.
-    StringRef getTriple() const { return GccTriple; }
-
-    /// \brief Get the detected GCC installation path.
-    StringRef getInstallPath() const { return GccInstallPath; }
-
-    /// \brief Get the detected GCC parent lib path.
-    StringRef getParentLibPath() const { return GccParentLibPath; }
-
-    /// \brief Get the detected GCC version string.
-    StringRef getVersion() const { return Version.Text; }
-
-  private:
-    static void CollectLibDirsAndTriples(llvm::Triple::ArchType HostArch,
-                                         SmallVectorImpl<StringRef> &LibDi=
rs,
-                                         SmallVectorImpl<StringRef> &Tripl=
es);
-
-    void ScanLibDirForGCCTriple(llvm::Triple::ArchType HostArch,
-                                const std::string &LibDir,
-                                StringRef CandidateTriple);
-  };
-
-  GCCInstallationDetector GCCInstallation;
-
 public:
-  Linux(const HostInfo &Host, const llvm::Triple& Triple);
+  Linux(const Driver &D, const llvm::Triple& Triple, const ArgList &Args);
=20
   virtual bool HasNativeLLVMSupport() const;
=20
@@ -467,6 +541,11 @@
=20
   std::string Linker;
   std::vector<std::string> ExtraOpts;
+
+private:
+  static bool addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
+                                       const ArgList &DriverArgs,
+                                       ArgStringList &CC1Args);
 };
=20
=20
@@ -474,7 +553,7 @@
 /// all subcommands. See http://tce.cs.tut.fi for our peculiar target.
 class LLVM_LIBRARY_VISIBILITY TCEToolChain : public ToolChain {
 public:
-  TCEToolChain(const HostInfo &Host, const llvm::Triple& Triple);
+  TCEToolChain(const Driver &D, const llvm::Triple& Triple);
   ~TCEToolChain();
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
@@ -493,7 +572,7 @@
   mutable llvm::DenseMap<unsigned, Tool*> Tools;
=20
 public:
-  Windows(const HostInfo &Host, const llvm::Triple& Triple);
+  Windows(const Driver &D, const llvm::Triple& Triple);
=20
   virtual Tool &SelectTool(const Compilation &C, const JobAction &JA,
                            const ActionList &Inputs) const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Tools.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Tools.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Tools.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -16,7 +16,6 @@
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Job.h"
-#include "clang/Driver/HostInfo.h"
 #include "clang/Driver/ObjCRuntime.h"
 #include "clang/Driver/Option.h"
 #include "clang/Driver/Options.h"
@@ -36,13 +35,6 @@
 #include "InputInfo.h"
 #include "ToolChains.h"
=20
-#ifdef __CYGWIN__
-#include <cygwin/version.h>
-#if defined(CYGWIN_VERSION_DLL_MAJOR) && CYGWIN_VERSION_DLL_MAJOR<1007
-#define IS_CYGWIN15 1
-#endif
-#endif
-
 using namespace clang::driver;
 using namespace clang::driver::tools;
 using namespace clang;
@@ -96,85 +88,11 @@
   }
 }
=20
-static void AddLinkerInputs(const ToolChain &TC,
-                            const InputInfoList &Inputs, const ArgList &Ar=
gs,
-                            ArgStringList &CmdArgs) {
-  const Driver &D =3D TC.getDriver();
-
-  // Add extra linker input arguments which are not treated as inputs
-  // (constructed via -Xarch_).
-  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
-
-  for (InputInfoList::const_iterator
-         it =3D Inputs.begin(), ie =3D Inputs.end(); it !=3D ie; ++it) {
-    const InputInfo &II =3D *it;
-
-    if (!TC.HasNativeLLVMSupport()) {
-      // Don't try to pass LLVM inputs unless we have native support.
-      if (II.getType() =3D=3D types::TY_LLVM_IR ||
-          II.getType() =3D=3D types::TY_LTO_IR ||
-          II.getType() =3D=3D types::TY_LLVM_BC ||
-          II.getType() =3D=3D types::TY_LTO_BC)
-        D.Diag(diag::err_drv_no_linker_llvm_support)
-          << TC.getTripleString();
-    }
-
-    // Add filenames immediately.
-    if (II.isFilename()) {
-      CmdArgs.push_back(II.getFilename());
-      continue;
-    }
-
-    // Otherwise, this is a linker input argument.
-    const Arg &A =3D II.getInputArg();
-
-    // Handle reserved library options.
-    if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
-      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
-    } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
-      TC.AddCCKextLibArgs(Args, CmdArgs);
-    } else
-      A.renderAsInput(Args, CmdArgs);
-  }
-}
-
-/// \brief Determine whether Objective-C automated reference counting is
-/// enabled.
-static bool isObjCAutoRefCount(const ArgList &Args) {
-  return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, f=
alse);
-}
-
-static void addProfileRT(const ToolChain &TC, const ArgList &Args,
-                         ArgStringList &CmdArgs,
-                         llvm::Triple Triple) {
-  if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
-        Args.hasArg(options::OPT_fprofile_generate) ||
-        Args.hasArg(options::OPT_fcreate_profile) ||
-        Args.hasArg(options::OPT_coverage)))
-    return;
-
-  // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lg=
cov to
-  // the link line. We cannot do the same thing because unlike gcov there =
is a
-  // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but t=
hat is
-  // not supported by old linkers.
-  Twine ProfileRT =3D
-    Twine(TC.getDriver().Dir) + "/../lib/" + "libprofile_rt.a";
-
-  if (Triple.isOSDarwin()) {
-    // On Darwin, if the static library doesn't exist try the dylib.
-    bool Exists;
-    if (llvm::sys::fs::exists(ProfileRT.str(), Exists) || !Exists)
-      ProfileRT =3D
-        Twine(TC.getDriver().Dir) + "/../lib/" + "libprofile_rt.dylib";
-  }
-
-  CmdArgs.push_back(Args.MakeArgString(ProfileRT));
-}
-
-static void AddIncludeDirectoryList(const ArgList &Args,
-                                    ArgStringList &CmdArgs,
-                                    const char *ArgName,
-                                    const char *DirList) {
+static void addDirectoryList(const ArgList &Args,
+                             ArgStringList &CmdArgs,
+                             const char *ArgName,
+                             const char *EnvVar) {
+  const char *DirList =3D ::getenv(EnvVar);
   if (!DirList)
     return; // Nothing to do.
=20
@@ -203,7 +121,85 @@
   }
 }
=20
-void Clang::AddPreprocessingOptions(const Driver &D,
+static void AddLinkerInputs(const ToolChain &TC,
+                            const InputInfoList &Inputs, const ArgList &Ar=
gs,
+                            ArgStringList &CmdArgs) {
+  const Driver &D =3D TC.getDriver();
+
+  // Add extra linker input arguments which are not treated as inputs
+  // (constructed via -Xarch_).
+  Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
+
+  for (InputInfoList::const_iterator
+         it =3D Inputs.begin(), ie =3D Inputs.end(); it !=3D ie; ++it) {
+    const InputInfo &II =3D *it;
+
+    if (!TC.HasNativeLLVMSupport()) {
+      // Don't try to pass LLVM inputs unless we have native support.
+      if (II.getType() =3D=3D types::TY_LLVM_IR ||
+          II.getType() =3D=3D types::TY_LTO_IR ||
+          II.getType() =3D=3D types::TY_LLVM_BC ||
+          II.getType() =3D=3D types::TY_LTO_BC)
+        D.Diag(diag::err_drv_no_linker_llvm_support)
+          << TC.getTripleString();
+    }
+
+    // Add filenames immediately.
+    if (II.isFilename()) {
+      CmdArgs.push_back(II.getFilename());
+      continue;
+    }
+
+    // Otherwise, this is a linker input argument.
+    const Arg &A =3D II.getInputArg();
+
+    // Handle reserved library options.
+    if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
+      TC.AddCXXStdlibLibArgs(Args, CmdArgs);
+    } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) {
+      TC.AddCCKextLibArgs(Args, CmdArgs);
+    } else
+      A.renderAsInput(Args, CmdArgs);
+  }
+
+  // LIBRARY_PATH - included following the user specified library paths.
+  addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
+}
+
+/// \brief Determine whether Objective-C automated reference counting is
+/// enabled.
+static bool isObjCAutoRefCount(const ArgList &Args) {
+  return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, f=
alse);
+}
+
+/// \brief Determine whether we are linking the ObjC runtime.
+static bool isObjCRuntimeLinked(const ArgList &Args) {
+  if (isObjCAutoRefCount(Args))
+    return true;
+  return Args.hasArg(options::OPT_fobjc_link_runtime);
+}
+
+static void addProfileRT(const ToolChain &TC, const ArgList &Args,
+                         ArgStringList &CmdArgs,
+                         llvm::Triple Triple) {
+  if (!(Args.hasArg(options::OPT_fprofile_arcs) ||
+        Args.hasArg(options::OPT_fprofile_generate) ||
+        Args.hasArg(options::OPT_fcreate_profile) ||
+        Args.hasArg(options::OPT_coverage)))
+    return;
+
+  // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lg=
cov to
+  // the link line. We cannot do the same thing because unlike gcov there =
is a
+  // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but t=
hat is
+  // not supported by old linkers.
+  std::string ProfileRT =3D
+    std::string(TC.getDriver().Dir) + "/../lib/libprofile_rt.a";
+
+  CmdArgs.push_back(Args.MakeArgString(ProfileRT));
+}
+
+void Clang::AddPreprocessingOptions(Compilation &C,
+                                    const Driver &D,
                                     const ArgList &Args,
                                     ArgStringList &CmdArgs,
                                     const InputInfo &Output,
@@ -225,11 +221,13 @@
       DepFile =3D Output.getFilename();
     } else if (Arg *MF =3D Args.getLastArg(options::OPT_MF)) {
       DepFile =3D MF->getValue(Args);
+      C.addFailureResultFile(DepFile);
     } else if (A->getOption().matches(options::OPT_M) ||
                A->getOption().matches(options::OPT_MM)) {
       DepFile =3D "-";
     } else {
       DepFile =3D darwin::CC1::getDependencyFileName(Args, Inputs);
+      C.addFailureResultFile(DepFile);
     }
     CmdArgs.push_back("-dependency-file");
     CmdArgs.push_back(DepFile);
@@ -247,13 +245,13 @@
         // Otherwise derive from the base input.
         //
         // FIXME: This should use the computed output file location.
-        llvm::SmallString<128> P(Inputs[0].getBaseInput());
+        SmallString<128> P(Inputs[0].getBaseInput());
         llvm::sys::path::replace_extension(P, "o");
         DepTarget =3D Args.MakeArgString(llvm::sys::path::filename(P));
       }
=20
       CmdArgs.push_back("-MT");
-      llvm::SmallString<128> Quoted;
+      SmallString<128> Quoted;
       QuoteTarget(DepTarget, Quoted);
       CmdArgs.push_back(Args.MakeArgString(Quoted));
     }
@@ -281,7 +279,7 @@
=20
     if (A->getOption().matches(options::OPT_MQ)) {
       CmdArgs.push_back("-MT");
-      llvm::SmallString<128> Quoted;
+      SmallString<128> Quoted;
       QuoteTarget(A->getValue(Args), Quoted);
       CmdArgs.push_back(Args.MakeArgString(Quoted));
=20
@@ -392,7 +390,7 @@
     A->claim();
     A->render(Args, CmdArgs);
   } else {
-    llvm::SmallString<128> DefaultModuleCache;
+    SmallString<128> DefaultModuleCache;
     llvm::sys::path::system_temp_directory(/*erasedOnReboot=3D*/false,=20
                                            DefaultModuleCache);
     llvm::sys::path::append(DefaultModuleCache, "clang-module-cache");
@@ -400,24 +398,20 @@
     CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache));
   }
  =20
-  Args.AddAllArgs(CmdArgs, options::OPT_fauto_module_import);
-
   // Parse additional include paths from environment variables.
+  // FIXME: We should probably sink the logic for handling these from the
+  // frontend into the driver. It will allow deleting 4 otherwise unused f=
lags.
   // CPATH - included following the user specified includes (but prior to
   // builtin and standard includes).
-  AddIncludeDirectoryList(Args, CmdArgs, "-I", ::getenv("CPATH"));
+  addDirectoryList(Args, CmdArgs, "-I", "CPATH");
   // C_INCLUDE_PATH - system includes enabled when compiling C.
-  AddIncludeDirectoryList(Args, CmdArgs, "-c-isystem",
-                          ::getenv("C_INCLUDE_PATH"));
+  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
   // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
-  AddIncludeDirectoryList(Args, CmdArgs, "-cxx-isystem",
-                          ::getenv("CPLUS_INCLUDE_PATH"));
+  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
   // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
-  AddIncludeDirectoryList(Args, CmdArgs, "-objc-isystem",
-                          ::getenv("OBJC_INCLUDE_PATH"));
+  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
   // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
-  AddIncludeDirectoryList(Args, CmdArgs, "-objcxx-isystem",
-                          ::getenv("OBJCPLUS_INCLUDE_PATH"));
+  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PAT=
H");
=20
   // Add C++ include arguments, if needed.
   if (types::isCXX(Inputs[0].getType()))
@@ -489,6 +483,9 @@
     .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
     .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
     .Cases("cortex-a8", "cortex-a9", "v7")
+    .Case("cortex-m3", "v7m")
+    .Case("cortex-m4", "v7m")
+    .Case("cortex-m0", "v6m")
     .Default("");
 }
=20
@@ -504,46 +501,78 @@
     if (Triple.isOSDarwin())
       return true;
     return false;
-
-  case llvm::Triple::systemz:
-    return false;
   }
 }
=20
-void Clang::AddARMTargetArgs(const ArgList &Args,
-                             ArgStringList &CmdArgs,
-                             bool KernelOrKext) const {
-  const Driver &D =3D getToolChain().getDriver();
-  llvm::Triple Triple =3D getToolChain().getTriple();
-
-  // Select the ABI to use.
-  //
-  // FIXME: Support -meabi.
-  const char *ABIName =3D 0;
-  if (Arg *A =3D Args.getLastArg(options::OPT_mabi_EQ)) {
-    ABIName =3D A->getValue(Args);
-  } else {
-    // Select the default based on the platform.
-    switch(Triple.getEnvironment()) {
-    case llvm::Triple::GNUEABI:
-      ABIName =3D "aapcs-linux";
-      break;
-    case llvm::Triple::EABI:
-      ABIName =3D "aapcs";
-      break;
-    default:
-      ABIName =3D "apcs-gnu";
-    }
-  }
-  CmdArgs.push_back("-target-abi");
-  CmdArgs.push_back(ABIName);
-
-  // Set the CPU based on -march=3D and -mcpu=3D.
-  CmdArgs.push_back("-target-cpu");
-  CmdArgs.push_back(getARMTargetCPU(Args, Triple));
-
-  // Select the float ABI as determined by -msoft-float, -mhard-float, and
-  // -mfloat-abi=3D.
+// Handle -mfpu=3D.
+//
+// FIXME: Centralize feature selection, defaulting shouldn't be also in the
+// frontend target.
+static void addFPUArgs(const Driver &D, const Arg *A, const ArgList &Args,
+                       ArgStringList &CmdArgs) {
+  StringRef FPU =3D A->getValue(Args);
+
+  // Set the target features based on the FPU.
+  if (FPU =3D=3D "fpa" || FPU =3D=3D "fpe2" || FPU =3D=3D "fpe3" || FPU =
=3D=3D "maverick") {
+    // Disable any default FPU support.
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("-vfp2");
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("-vfp3");
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("-neon");
+  } else if (FPU =3D=3D "vfp3-d16" || FPU =3D=3D "vfpv3-d16") {
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+vfp3");
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+d16");
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("-neon");
+  } else if (FPU =3D=3D "vfp") {
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+vfp2");
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("-neon");
+  } else if (FPU =3D=3D "vfp3" || FPU =3D=3D "vfpv3") {
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+vfp3");
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("-neon");
+  } else if (FPU =3D=3D "neon") {
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+neon");
+  } else
+    D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
+}
+
+// Handle -mfpmath=3D.
+static void addFPMathArgs(const Driver &D, const Arg *A, const ArgList &Ar=
gs,
+                          ArgStringList &CmdArgs, StringRef CPU) {
+  StringRef FPMath =3D A->getValue(Args);
+ =20
+  // Set the target features based on the FPMath.
+  if (FPMath =3D=3D "neon") {
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+neonfp");
+   =20
+    if (CPU !=3D "cortex-a8" && CPU !=3D "cortex-a9" && CPU !=3D "cortex-a=
9-mp")   =20
+      D.Diag(diag::err_drv_invalid_feature) << "-mfpmath=3Dneon" << CPU;
+   =20
+  } else if (FPMath =3D=3D "vfp" || FPMath =3D=3D "vfp2" || FPMath =3D=3D =
"vfp3" ||
+             FPMath =3D=3D "vfp4") {
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("-neonfp");
+
+    // FIXME: Add warnings when disabling a feature not present for a give=
n CPU.   =20
+  } else
+    D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
+}
+
+// Select the float ABI as determined by -msoft-float, -mhard-float, and
+// -mfloat-abi=3D.
+static StringRef getARMFloatABI(const Driver &D,
+                                const ArgList &Args,
+                                const llvm::Triple &Triple) {
   StringRef FloatABI;
   if (Arg *A =3D Args.getLastArg(options::OPT_msoft_float,
                                options::OPT_mhard_float,
@@ -564,7 +593,6 @@
=20
   // If unspecified, choose the default based on the platform.
   if (FloatABI.empty()) {
-    const llvm::Triple &Triple =3D getToolChain().getTriple();
     switch (Triple.getOS()) {
     case llvm::Triple::Darwin:
     case llvm::Triple::MacOSX:
@@ -582,7 +610,7 @@
     }
=20
     case llvm::Triple::Linux: {
-      if (getToolChain().getTriple().getEnvironment() =3D=3D llvm::Triple:=
:GNUEABI) {
+      if (Triple.getEnvironment() =3D=3D llvm::Triple::GNUEABI) {
         FloatABI =3D "softfp";
         break;
       }
@@ -598,6 +626,15 @@
         // EABI is always AAPCS, and if it was not marked 'hard', it's sof=
tfp
         FloatABI =3D "softfp";
         break;
+      case llvm::Triple::ANDROIDEABI: {
+        StringRef ArchName =3D
+          getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
+        if (ArchName.startswith("v7"))
+          FloatABI =3D "softfp";
+        else
+          FloatABI =3D "soft";
+        break;
+      }
       default:
         // Assume "soft", but warn the user we are guessing.
         FloatABI =3D "soft";
@@ -607,6 +644,45 @@
     }
   }
=20
+  return FloatABI;
+}
+
+
+void Clang::AddARMTargetArgs(const ArgList &Args,
+                             ArgStringList &CmdArgs,
+                             bool KernelOrKext) const {
+  const Driver &D =3D getToolChain().getDriver();
+  llvm::Triple Triple =3D getToolChain().getTriple();
+
+  // Select the ABI to use.
+  //
+  // FIXME: Support -meabi.
+  const char *ABIName =3D 0;
+  if (Arg *A =3D Args.getLastArg(options::OPT_mabi_EQ)) {
+    ABIName =3D A->getValue(Args);
+  } else {
+    // Select the default based on the platform.
+    switch(Triple.getEnvironment()) {
+    case llvm::Triple::ANDROIDEABI:
+    case llvm::Triple::GNUEABI:
+      ABIName =3D "aapcs-linux";
+      break;
+    case llvm::Triple::EABI:
+      ABIName =3D "aapcs";
+      break;
+    default:
+      ABIName =3D "apcs-gnu";
+    }
+  }
+  CmdArgs.push_back("-target-abi");
+  CmdArgs.push_back(ABIName);
+
+  // Set the CPU based on -march=3D and -mcpu=3D.
+  CmdArgs.push_back("-target-cpu");
+  CmdArgs.push_back(getARMTargetCPU(Args, Triple));
+
+  // Determine floating point ABI from the options & target defaults.
+  StringRef FloatABI =3D getARMFloatABI(D, Args, Triple);
   if (FloatABI =3D=3D "soft") {
     // Floating point operations and argument passing are soft.
     //
@@ -644,33 +720,12 @@
   }
=20
   // Honor -mfpu=3D.
-  //
-  // FIXME: Centralize feature selection, defaulting shouldn't be also in =
the
-  // frontend target.
-  if (const Arg *A =3D Args.getLastArg(options::OPT_mfpu_EQ)) {
-    StringRef FPU =3D A->getValue(Args);
-
-    // Set the target features based on the FPU.
-    if (FPU =3D=3D "fpa" || FPU =3D=3D "fpe2" || FPU =3D=3D "fpe3" || FPU =
=3D=3D "maverick") {
-      // Disable any default FPU support.
-      CmdArgs.push_back("-target-feature");
-      CmdArgs.push_back("-vfp2");
-      CmdArgs.push_back("-target-feature");
-      CmdArgs.push_back("-vfp3");
-      CmdArgs.push_back("-target-feature");
-      CmdArgs.push_back("-neon");
-    } else if (FPU =3D=3D "vfp") {
-      CmdArgs.push_back("-target-feature");
-      CmdArgs.push_back("+vfp2");
-    } else if (FPU =3D=3D "vfp3") {
-      CmdArgs.push_back("-target-feature");
-      CmdArgs.push_back("+vfp3");
-    } else if (FPU =3D=3D "neon") {
-      CmdArgs.push_back("-target-feature");
-      CmdArgs.push_back("+neon");
-    } else
-      D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
-  }
+  if (const Arg *A =3D Args.getLastArg(options::OPT_mfpu_EQ))
+    addFPUArgs(D, A, Args, CmdArgs);
+
+  // Honor -mfpmath=3D.
+  if (const Arg *A =3D Args.getLastArg(options::OPT_mfpmath_EQ))
+    addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
=20
   // Setting -msoft-float effectively disables NEON because of the GCC
   // implementation, although the same isn't true of VFP or VFP3.
@@ -703,25 +758,32 @@
=20
 // Get default architecture.
 static const char* getMipsArchFromCPU(StringRef CPUName) {
-  if (CPUName =3D=3D "mips32r1" || CPUName =3D=3D "4ke")
+  if (CPUName =3D=3D "mips32" || CPUName =3D=3D "mips32r2")
     return "mips";
=20
-  assert((CPUName =3D=3D "mips64r1" || CPUName =3D=3D "mips64r2") &&
+  assert((CPUName =3D=3D "mips64" || CPUName =3D=3D "mips64r2") &&
          "Unexpected cpu name.");
=20
   return "mips64";
 }
=20
+// Check that ArchName is a known Mips architecture name.
+static bool checkMipsArchName(StringRef ArchName) {
+  return ArchName =3D=3D "mips" ||
+         ArchName =3D=3D "mipsel" ||
+         ArchName =3D=3D "mips64" ||
+         ArchName =3D=3D "mips64el";
+}
+
 // Get default target cpu.
-static const char* getMipsCPUFromArch(StringRef ArchName, const Driver &D)=
 {
+static const char* getMipsCPUFromArch(StringRef ArchName) {
   if (ArchName =3D=3D "mips" || ArchName =3D=3D "mipsel")
-    return "mips32r1";
-  else if (ArchName =3D=3D "mips64" || ArchName =3D=3D "mips64el")
-    return "mips64r1";
-  else
-    D.Diag(diag::err_drv_invalid_arch_name) << ArchName;
-
-  return 0;
+    return "mips32";
+
+  assert((ArchName =3D=3D "mips64" || ArchName =3D=3D "mips64el") &&
+         "Unexpected arch name.");
+
+  return "mips64";
 }
=20
 // Get default ABI.
@@ -734,61 +796,98 @@
     return "n64";
 }
=20
-void Clang::AddMIPSTargetArgs(const ArgList &Args,
-                             ArgStringList &CmdArgs) const {
-  const Driver &D =3D getToolChain().getDriver();
-
+// Get CPU and ABI names. They are not independent
+// so we have to calculate them together.
+static void getMipsCPUAndABI(const ArgList &Args,
+                             const ToolChain &TC,
+                             StringRef &CPUName,
+                             StringRef &ABIName) {
   StringRef ArchName;
-  const char *CPUName;
-
-  // Set target cpu and architecture.
+
+  // Select target cpu and architecture.
   if (Arg *A =3D Args.getLastArg(options::OPT_mcpu_EQ)) {
     CPUName =3D A->getValue(Args);
     ArchName =3D getMipsArchFromCPU(CPUName);
   }
   else {
-    ArchName =3D Args.MakeArgString(getToolChain().getArchName());
-    CPUName =3D getMipsCPUFromArch(ArchName, D);
-  }
-
-  CmdArgs.push_back("-target-cpu");
-  CmdArgs.push_back(CPUName);
+    ArchName =3D Args.MakeArgString(TC.getArchName());
+    if (!checkMipsArchName(ArchName))
+      TC.getDriver().Diag(diag::err_drv_invalid_arch_name) << ArchName;
+    else
+      CPUName =3D getMipsCPUFromArch(ArchName);
+  }
 =20
   // Select the ABI to use.
-  const char *ABIName =3D 0;
   if (Arg *A =3D Args.getLastArg(options::OPT_mabi_EQ))
     ABIName =3D A->getValue(Args);
   else=20
     ABIName =3D getMipsABIFromArch(ArchName);
+}
+
+void Clang::AddMIPSTargetArgs(const ArgList &Args,
+                             ArgStringList &CmdArgs) const {
+  const Driver &D =3D getToolChain().getDriver();
+  StringRef CPUName;
+  StringRef ABIName;
+  getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
+
+  CmdArgs.push_back("-target-cpu");
+  CmdArgs.push_back(CPUName.data());
=20
   CmdArgs.push_back("-target-abi");
-  CmdArgs.push_back(ABIName);
-
-  // Select the float ABI as determined by -msoft-float, -mhard-float, and
+  CmdArgs.push_back(ABIName.data());
+
+  // Select the float ABI as determined by -msoft-float, -mhard-float,
+  // and -mfloat-abi=3D.
   StringRef FloatABI;
   if (Arg *A =3D Args.getLastArg(options::OPT_msoft_float,
-                               options::OPT_mhard_float)) {
+                               options::OPT_mhard_float,
+                               options::OPT_mfloat_abi_EQ)) {
     if (A->getOption().matches(options::OPT_msoft_float))
       FloatABI =3D "soft";
     else if (A->getOption().matches(options::OPT_mhard_float))
       FloatABI =3D "hard";
+    else {
+      FloatABI =3D A->getValue(Args);
+      if (FloatABI !=3D "soft" && FloatABI !=3D "single" && FloatABI !=3D =
"hard") {
+        D.Diag(diag::err_drv_invalid_mfloat_abi)
+          << A->getAsString(Args);
+        FloatABI =3D "hard";
+      }
+    }
   }
=20
   // If unspecified, choose the default based on the platform.
   if (FloatABI.empty()) {
-    // Assume "soft", but warn the user we are guessing.
-    FloatABI =3D "soft";
-    D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
+    // Assume "hard", because it's a default value used by gcc.
+    // When we start to recognize specific target MIPS processors,
+    // we will be able to select the default more correctly.
+    FloatABI =3D "hard";
   }
=20
   if (FloatABI =3D=3D "soft") {
     // Floating point operations and argument passing are soft.
-    //
-    // FIXME: This changes CPP defines, we need -target-soft-float.
     CmdArgs.push_back("-msoft-float");
-  } else {
+    CmdArgs.push_back("-mfloat-abi");
+    CmdArgs.push_back("soft");
+
+    // FIXME: Note, this is a hack. We need to pass the selected float
+    // mode to the MipsTargetInfoBase to define appropriate macros there.
+    // Now it is the only method.
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+soft-float");
+  }
+  else if (FloatABI =3D=3D "single") {
+    // Restrict the use of hardware floating-point
+    // instructions to 32-bit operations.
+    CmdArgs.push_back("-target-feature");
+    CmdArgs.push_back("+single-float");
+  }
+  else {
+    // Floating point operations and argument passing are hard.
     assert(FloatABI =3D=3D "hard" && "Invalid float abi!");
-    CmdArgs.push_back("-mhard-float");
+    CmdArgs.push_back("-mfloat-abi");
+    CmdArgs.push_back("hard");
   }
 }
=20
@@ -797,9 +896,8 @@
   const Driver &D =3D getToolChain().getDriver();
=20
   if (const Arg *A =3D Args.getLastArg(options::OPT_march_EQ)) {
-    StringRef MArch =3D A->getValue(Args);
     CmdArgs.push_back("-target-cpu");
-    CmdArgs.push_back(MArch.str().c_str());
+    CmdArgs.push_back(A->getValue(Args));
   }
=20
   // Select the float ABI as determined by -msoft-float, -mhard-float, and
@@ -941,6 +1039,70 @@
   }
 }
=20
+static Arg* getLastHexagonArchArg (const ArgList &Args)
+{
+  Arg * A =3D NULL;
+
+  for (ArgList::const_iterator it =3D Args.begin(), ie =3D Args.end();
+       it !=3D ie; ++it) {
+    if ((*it)->getOption().matches(options::OPT_march_EQ) ||
+        (*it)->getOption().matches(options::OPT_mcpu_EQ)) {
+      A =3D *it;
+      A->claim();
+    }
+    else if ((*it)->getOption().matches(options::OPT_m_Joined)){
+      StringRef Value =3D (*it)->getValue(Args,0);
+      if (Value.startswith("v")) {
+        A =3D *it;
+        A->claim();
+      }
+    }
+  }
+  return A;
+}
+
+static StringRef getHexagonTargetCPU(const ArgList &Args)
+{
+  Arg *A;
+  llvm::StringRef WhichHexagon;
+
+  // Select the default CPU (v4) if none was given or detection failed.
+  if ((A =3D getLastHexagonArchArg (Args))) {
+    WhichHexagon =3D A->getValue(Args);
+    if (WhichHexagon =3D=3D "")
+      return "v4";
+    else
+      return WhichHexagon;
+  }
+  else
+    return "v4";
+}
+
+void Clang::AddHexagonTargetArgs(const ArgList &Args,
+                                 ArgStringList &CmdArgs) const {
+  llvm::Triple Triple =3D getToolChain().getTriple();
+
+  CmdArgs.push_back("-target-cpu");
+  CmdArgs.push_back(Args.MakeArgString("hexagon" + getHexagonTargetCPU(Arg=
s)));
+  CmdArgs.push_back("-fno-signed-char");
+  CmdArgs.push_back("-nobuiltininc");
+
+  if (Args.hasArg(options::OPT_mqdsp6_compat)) =20
+    CmdArgs.push_back("-mqdsp6-compat");
+
+  if (Arg *A =3D Args.getLastArg(options::OPT_G,
+                               options::OPT_msmall_data_threshold_EQ)) {
+    std::string SmallDataThreshold=3D"-small-data-threshold=3D";
+    SmallDataThreshold +=3D A->getValue(Args);
+    CmdArgs.push_back ("-mllvm");
+    CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold));
+    A->claim();
+  }
+
+  CmdArgs.push_back ("-mllvm");
+  CmdArgs.push_back ("-machine-sink-split=3D0");
+}
+
 static bool
 shouldUseExceptionTablesForObjCExceptions(unsigned objcABIVersion,
                                           const llvm::Triple &Triple) {
@@ -966,11 +1128,20 @@
 /// Objective-C exceptions.
 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
                              const llvm::Triple &Triple,
-                             bool KernelOrKext, bool IsRewriter,
+                             bool KernelOrKext,
                              unsigned objcABIVersion,
                              ArgStringList &CmdArgs) {
-  if (KernelOrKext)
+  if (KernelOrKext) {
+    // -mkernel and -fapple-kext imply no exceptions, so claim exception r=
elated
+    // arguments now to avoid warnings about unused arguments.
+    Args.ClaimAllArgs(options::OPT_fexceptions);
+    Args.ClaimAllArgs(options::OPT_fno_exceptions);
+    Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
+    Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
+    Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
+    Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
     return;
+  }
=20
   // Exceptions are enabled by default.
   bool ExceptionsEnabled =3D true;
@@ -1033,28 +1204,29 @@
=20
 static bool ShouldDisableCFI(const ArgList &Args,
                              const ToolChain &TC) {
+  bool Default =3D true;
   if (TC.getTriple().isOSDarwin()) {
     // The native darwin assembler doesn't support cfi directives, so
     // we disable them if we think the .s file will be passed to it.
-
-    // FIXME: Duplicated code with ToolChains.cpp
-    // FIXME: This doesn't belong here, but ideally we will support static=
 soon
-    // anyway.
-    bool HasStatic =3D (Args.hasArg(options::OPT_mkernel) ||
-                      Args.hasArg(options::OPT_static) ||
-                      Args.hasArg(options::OPT_fapple_kext));
-    bool IsIADefault =3D TC.IsIntegratedAssemblerDefault() && !HasStatic;
-    bool UseIntegratedAs =3D Args.hasFlag(options::OPT_integrated_as,
-                                        options::OPT_no_integrated_as,
-                                        IsIADefault);
-    bool UseCFI =3D Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
-                               options::OPT_fno_dwarf2_cfi_asm,
-                               UseIntegratedAs);
-    return !UseCFI;
-  }
-
-  // For now we assume that every other assembler support CFI.
-  return false;
+    Default =3D Args.hasFlag(options::OPT_integrated_as,
+			   options::OPT_no_integrated_as,
+			   TC.IsIntegratedAssemblerDefault());
+  }
+  return !Args.hasFlag(options::OPT_fdwarf2_cfi_asm,
+		       options::OPT_fno_dwarf2_cfi_asm,
+		       Default);
+}
+
+static bool ShouldDisableDwarfDirectory(const ArgList &Args,
+                                        const ToolChain &TC) {
+  bool IsIADefault =3D TC.IsIntegratedAssemblerDefault();
+  bool UseIntegratedAs =3D Args.hasFlag(options::OPT_integrated_as,
+                                      options::OPT_no_integrated_as,
+                                      IsIADefault);
+  bool UseDwarfDirectory =3D Args.hasFlag(options::OPT_fdwarf_directory_as=
m,
+                                        options::OPT_fno_dwarf_directory_a=
sm,
+                                        UseIntegratedAs);
+  return !UseDwarfDirectory;
 }
=20
 /// \brief Check whether the given input tree contains any compilation act=
ions.
@@ -1092,6 +1264,46 @@
     RelaxDefault);
 }
=20
+/// If AddressSanitizer is enabled, add appropriate linker flags (Linux).
+/// This needs to be called before we add the C run-time (malloc, etc).
+static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
+                           ArgStringList &CmdArgs) {
+  // Add asan linker flags when linking an executable, but not a shared ob=
ject.
+  if (Args.hasArg(options::OPT_shared) ||
+      !Args.hasFlag(options::OPT_faddress_sanitizer,
+                    options::OPT_fno_address_sanitizer, false))
+    return;
+
+  // LibAsan is "libclang_rt.asan-<ArchName>.a" in the Linux library resou=
rce
+  // directory.
+  SmallString<128> LibAsan(TC.getDriver().ResourceDir);
+  llvm::sys::path::append(LibAsan, "lib", "linux",
+                          (Twine("libclang_rt.asan-") +
+                           TC.getArchName() + ".a"));
+  CmdArgs.push_back(Args.MakeArgString(LibAsan));
+  CmdArgs.push_back("-lpthread");
+  CmdArgs.push_back("-ldl");
+  CmdArgs.push_back("-export-dynamic");
+}
+
+static bool shouldUseFramePointer(const ArgList &Args,
+                                  const llvm::Triple &Triple) {
+  if (Arg *A =3D Args.getLastArg(options::OPT_fno_omit_frame_pointer,
+                               options::OPT_fomit_frame_pointer))
+    return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
+
+  // Don't use a frame pointer on linux x86 and x86_64 if optimizing.
+  if ((Triple.getArch() =3D=3D llvm::Triple::x86_64 ||
+       Triple.getArch() =3D=3D llvm::Triple::x86) &&
+      Triple.getOS() =3D=3D llvm::Triple::Linux) {
+    if (Arg *A =3D Args.getLastArg(options::OPT_O_Group))
+      if (!A->getOption().matches(options::OPT_O0))
+        return false;
+  }
+
+  return true;
+}
+
 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
                          const InputInfo &Output,
                          const InputInfoList &Inputs,
@@ -1116,9 +1328,13 @@
=20
   // Select the appropriate action.
   bool IsRewriter =3D false;
+  bool IsModernRewriter =3D false;
+ =20
   if (isa<AnalyzeJobAction>(JA)) {
     assert(JA.getType() =3D=3D types::TY_Plist && "Invalid output type.");
     CmdArgs.push_back("-analyze");
+  } else if (isa<MigrateJobAction>(JA)) {
+    CmdArgs.push_back("-migrate");
   } else if (isa<PreprocessJobAction>(JA)) {
     if (Output.getType() =3D=3D types::TY_Dependencies)
       CmdArgs.push_back("-Eonly");
@@ -1184,6 +1400,9 @@
       CmdArgs.push_back("-emit-pch");
     } else if (JA.getType() =3D=3D types::TY_RewrittenObjC) {
       CmdArgs.push_back("-rewrite-objc");
+      IsModernRewriter =3D true;
+    } else if (JA.getType() =3D=3D types::TY_RewrittenLegacyObjC) {
+      CmdArgs.push_back("-rewrite-objc");
       IsRewriter =3D true;
     } else {
       assert(JA.getType() =3D=3D types::TY_PP_Asm &&
@@ -1218,17 +1437,27 @@
=20
     CmdArgs.push_back("-analyzer-eagerly-assume");
=20
+    CmdArgs.push_back("-analyzer-ipa=3Dinlining");
+
     // Add default argument set.
     if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
       CmdArgs.push_back("-analyzer-checker=3Dcore");
-      CmdArgs.push_back("-analyzer-checker=3Ddeadcode");
-      CmdArgs.push_back("-analyzer-checker=3Dsecurity");
=20
       if (getToolChain().getTriple().getOS() !=3D llvm::Triple::Win32)
         CmdArgs.push_back("-analyzer-checker=3Dunix");
=20
       if (getToolChain().getTriple().getVendor() =3D=3D llvm::Triple::Appl=
e)
         CmdArgs.push_back("-analyzer-checker=3Dosx");
+     =20
+      CmdArgs.push_back("-analyzer-checker=3Ddeadcode");
+     =20
+      // Enable the following experimental checkers for testing.=20
+      CmdArgs.push_back("-analyzer-checker=3Dsecurity.insecureAPI.Unchecke=
dReturn");
+      CmdArgs.push_back("-analyzer-checker=3Dsecurity.insecureAPI.getpw");
+      CmdArgs.push_back("-analyzer-checker=3Dsecurity.insecureAPI.gets");
+      CmdArgs.push_back("-analyzer-checker=3Dsecurity.insecureAPI.mktemp")=
;     =20
+      CmdArgs.push_back("-analyzer-checker=3Dsecurity.insecureAPI.mkstemp"=
);
+      CmdArgs.push_back("-analyzer-checker=3Dsecurity.insecureAPI.vfork");
     }
=20
     // Set the output format. The default is plist, for (lame) historical
@@ -1260,15 +1489,43 @@
   // would do to enable flag_pic.
   //
   // FIXME: Centralize this code.
-  bool PICEnabled =3D (Args.hasArg(options::OPT_fPIC) ||
-                     Args.hasArg(options::OPT_fpic) ||
-                     Args.hasArg(options::OPT_fPIE) ||
-                     Args.hasArg(options::OPT_fpie));
-  bool PICDisabled =3D (Args.hasArg(options::OPT_mkernel) ||
-                      Args.hasArg(options::OPT_static));
+  Arg *LastPICArg =3D 0;
+  for (ArgList::const_iterator I =3D Args.begin(), E =3D Args.end(); I !=
=3D E; ++I) {
+    if ((*I)->getOption().matches(options::OPT_fPIC) ||
+        (*I)->getOption().matches(options::OPT_fno_PIC) ||
+        (*I)->getOption().matches(options::OPT_fpic) ||
+        (*I)->getOption().matches(options::OPT_fno_pic) ||
+        (*I)->getOption().matches(options::OPT_fPIE) ||
+        (*I)->getOption().matches(options::OPT_fno_PIE) ||
+        (*I)->getOption().matches(options::OPT_fpie) ||
+        (*I)->getOption().matches(options::OPT_fno_pie)) {
+      LastPICArg =3D *I;
+      (*I)->claim();
+    }
+  }
+  bool PICDisabled =3D false;
+  bool PICEnabled =3D false;
+  bool PICForPIE =3D false;
+  if (LastPICArg) {
+    PICForPIE =3D (LastPICArg->getOption().matches(options::OPT_fPIE) ||
+                 LastPICArg->getOption().matches(options::OPT_fpie));
+    PICEnabled =3D (PICForPIE ||
+                  LastPICArg->getOption().matches(options::OPT_fPIC) ||
+                  LastPICArg->getOption().matches(options::OPT_fpic));
+    PICDisabled =3D !PICEnabled;
+  }
+  // Note that these flags are trump-cards. Regardless of the order w.r.t.=
 the
+  // PIC or PIE options above, if these show up, PIC is disabled.
+  if (Args.hasArg(options::OPT_mkernel))
+    PICDisabled =3D true;
+  if (Args.hasArg(options::OPT_static))
+    PICDisabled =3D true;
+  bool DynamicNoPIC =3D Args.hasArg(options::OPT_mdynamic_no_pic);
+
+  // Select the relocation model.
   const char *Model =3D getToolChain().GetForcedPicModel();
   if (!Model) {
-    if (Args.hasArg(options::OPT_mdynamic_no_pic))
+    if (DynamicNoPIC)
       Model =3D "dynamic-no-pic";
     else if (PICDisabled)
       Model =3D "static";
@@ -1277,19 +1534,25 @@
     else
       Model =3D getToolChain().GetDefaultRelocationModel();
   }
-  if (StringRef(Model) !=3D "pic") {
+  StringRef ModelStr =3D Model ? Model : "";
+  if (Model && ModelStr !=3D "pic") {
     CmdArgs.push_back("-mrelocation-model");
     CmdArgs.push_back(Model);
   }
=20
-  // Infer the __PIC__ value.
-  //
-  // FIXME:  This isn't quite right on Darwin, which always sets
-  // __PIC__=3D2.
-  if (strcmp(Model, "pic") =3D=3D 0 || strcmp(Model, "dynamic-no-pic") =3D=
=3D 0) {
+  // Infer the __PIC__ and __PIE__ values.
+  if (ModelStr =3D=3D "pic" && PICForPIE) {
+    CmdArgs.push_back("-pie-level");
+    CmdArgs.push_back((LastPICArg &&
+                       LastPICArg->getOption().matches(options::OPT_fPIE))=
 ?
+                      "2" : "1");
+  } else if (ModelStr =3D=3D "pic" || ModelStr =3D=3D "dynamic-no-pic") {
     CmdArgs.push_back("-pic-level");
-    CmdArgs.push_back(Args.hasArg(options::OPT_fPIC) ? "2" : "1");
-  }
+    CmdArgs.push_back(((ModelStr !=3D "dynamic-no-pic" && LastPICArg &&
+                        LastPICArg->getOption().matches(options::OPT_fPIC)=
) ||
+                       getToolChain().getTriple().isOSDarwin()) ? "2" : "1=
");
+  }
+
   if (!Args.hasFlag(options::OPT_fmerge_all_constants,
                     options::OPT_fno_merge_all_constants))
     CmdArgs.push_back("-fno-merge-all-constants");
@@ -1304,9 +1567,7 @@
   if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
     CmdArgs.push_back("-mrtd");
=20
-  // FIXME: Set --enable-unsafe-fp-math.
-  if (Args.hasFlag(options::OPT_fno_omit_frame_pointer,
-                   options::OPT_fomit_frame_pointer))
+  if (shouldUseFramePointer(Args, getToolChain().getTriple()))
     CmdArgs.push_back("-mdisable-fp-elim");
   if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
                     options::OPT_fno_zero_initialized_in_bss))
@@ -1315,6 +1576,96 @@
                     options::OPT_fno_strict_aliasing,
                     getToolChain().IsStrictAliasingDefault()))
     CmdArgs.push_back("-relaxed-aliasing");
+  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enu=
ms,
+                   false))
+    CmdArgs.push_back("-fstrict-enums");
+  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
+                    options::OPT_fno_optimize_sibling_calls))
+    CmdArgs.push_back("-mdisable-tail-calls");
+
+  // Handle various floating point optimization flags, mapping them to the
+  // appropriate LLVM code generation flags. The pattern for all of these =
is to
+  // default off the codegen optimizations, and if any flag enables them a=
nd no
+  // flag disables them after the flag enabling them, enable the codegen
+  // optimization. This is complicated by several "umbrella" flags.
+  if (Arg *A =3D Args.getLastArg(options::OPT_ffast_math,
+                               options::OPT_ffinite_math_only,
+                               options::OPT_fno_finite_math_only,
+                               options::OPT_fhonor_infinities,
+                               options::OPT_fno_honor_infinities))
+    if (A->getOption().getID() !=3D options::OPT_fno_finite_math_only &&
+        A->getOption().getID() !=3D options::OPT_fhonor_infinities)
+      CmdArgs.push_back("-menable-no-infs");
+  if (Arg *A =3D Args.getLastArg(options::OPT_ffast_math,
+                               options::OPT_ffinite_math_only,
+                               options::OPT_fno_finite_math_only,
+                               options::OPT_fhonor_nans,
+                               options::OPT_fno_honor_nans))
+    if (A->getOption().getID() !=3D options::OPT_fno_finite_math_only &&
+        A->getOption().getID() !=3D options::OPT_fhonor_nans)
+      CmdArgs.push_back("-menable-no-nans");
+
+  // -fno-math-errno is default.
+  bool MathErrno =3D false;
+  if (Arg *A =3D Args.getLastArg(options::OPT_ffast_math,
+                               options::OPT_fmath_errno,
+                               options::OPT_fno_math_errno)) {
+    if (A->getOption().getID() =3D=3D options::OPT_fmath_errno) {
+      CmdArgs.push_back("-fmath-errno");
+      MathErrno =3D true;
+    }
+  }
+
+  // There are several flags which require disabling very specific
+  // optimizations. Any of these being disabled forces us to turn off the
+  // entire set of LLVM optimizations, so collect them through all the flag
+  // madness.
+  bool AssociativeMath =3D false;
+  if (Arg *A =3D Args.getLastArg(options::OPT_ffast_math,
+                               options::OPT_funsafe_math_optimizations,
+                               options::OPT_fno_unsafe_math_optimizations,
+                               options::OPT_fassociative_math,
+                               options::OPT_fno_associative_math))
+    if (A->getOption().getID() !=3D options::OPT_fno_unsafe_math_optimizat=
ions &&
+        A->getOption().getID() !=3D options::OPT_fno_associative_math)
+      AssociativeMath =3D true;
+  bool ReciprocalMath =3D false;
+  if (Arg *A =3D Args.getLastArg(options::OPT_ffast_math,
+                               options::OPT_funsafe_math_optimizations,
+                               options::OPT_fno_unsafe_math_optimizations,
+                               options::OPT_freciprocal_math,
+                               options::OPT_fno_reciprocal_math))
+    if (A->getOption().getID() !=3D options::OPT_fno_unsafe_math_optimizat=
ions &&
+        A->getOption().getID() !=3D options::OPT_fno_reciprocal_math)
+      ReciprocalMath =3D true;
+  bool SignedZeros =3D true;
+  if (Arg *A =3D Args.getLastArg(options::OPT_ffast_math,
+                               options::OPT_funsafe_math_optimizations,
+                               options::OPT_fno_unsafe_math_optimizations,
+                               options::OPT_fsigned_zeros,
+                               options::OPT_fno_signed_zeros))
+    if (A->getOption().getID() !=3D options::OPT_fno_unsafe_math_optimizat=
ions &&
+        A->getOption().getID() !=3D options::OPT_fsigned_zeros)
+      SignedZeros =3D false;
+  bool TrappingMath =3D true;
+  if (Arg *A =3D Args.getLastArg(options::OPT_ffast_math,
+                               options::OPT_funsafe_math_optimizations,
+                               options::OPT_fno_unsafe_math_optimizations,
+                               options::OPT_ftrapping_math,
+                               options::OPT_fno_trapping_math))
+    if (A->getOption().getID() !=3D options::OPT_fno_unsafe_math_optimizat=
ions &&
+        A->getOption().getID() !=3D options::OPT_ftrapping_math)
+      TrappingMath =3D false;
+  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
+      !TrappingMath)
+    CmdArgs.push_back("-menable-unsafe-fp-math");
+
+  // We separately look for the '-ffast-math' flag, and if we find it, tel=
l the
+  // frontend to provide the appropriate preprocessor macros. This is dist=
inct
+  // from enabling any optimizations as it induces a language change which=
 must
+  // survive serialization and deserialization, etc.
+  if (Args.hasArg(options::OPT_ffast_math))
+    CmdArgs.push_back("-ffast-math");
=20
   // Decide whether to use verbose asm. Verbose assembly is the default on
   // toolchains which have the integrated assembler on by default.
@@ -1397,7 +1748,13 @@
   case llvm::Triple::x86_64:
     AddX86TargetArgs(Args, CmdArgs);
     break;
-  }
+
+  case llvm::Triple::hexagon:
+    AddHexagonTargetArgs(Args, CmdArgs);
+    break;
+  }
+
+
=20
   // Pass the linker version in use.
   if (Arg *A =3D Args.getLastArg(options::OPT_mlinker_version_EQ)) {
@@ -1411,21 +1768,11 @@
                    !getToolChain().getTriple().isOSDarwin()))
     CmdArgs.push_back("-momit-leaf-frame-pointer");
=20
-  // -fno-math-errno is default.
-  if (Args.hasFlag(options::OPT_fmath_errno,
-                   options::OPT_fno_math_errno,
-                   false))
-    CmdArgs.push_back("-fmath-errno");
-
   // Explicitly error on some things we know we don't support and can't ju=
st
   // ignore.
   types::ID InputType =3D Inputs[0].getType();
   if (!Args.hasArg(options::OPT_fallow_unsupported)) {
     Arg *Unsupported;
-    if ((Unsupported =3D Args.getLastArg(options::OPT_iframework)))
-      D.Diag(diag::err_drv_clang_unsupported)
-        << Unsupported->getOption().getName();
-
     if (types::isCXX(InputType) &&
         getToolChain().getTriple().isOSDarwin() &&
         getToolChain().getTriple().getArch() =3D=3D llvm::Triple::x86) {
@@ -1456,8 +1803,9 @@
   // wrong.
   Args.ClaimAllArgs(options::OPT_g_Group);
   if (Arg *A =3D Args.getLastArg(options::OPT_g_Group))
-    if (!A->getOption().matches(options::OPT_g0))
+    if (!A->getOption().matches(options::OPT_g0)) {
       CmdArgs.push_back("-g");
+    }
=20
   Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections);
   Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections);
@@ -1496,10 +1844,12 @@
=20
   Args.AddLastArg(CmdArgs, options::OPT_working_directory);
=20
+  bool ARCMTEnabled =3D false;
   if (!Args.hasArg(options::OPT_fno_objc_arc)) {
     if (const Arg *A =3D Args.getLastArg(options::OPT_ccc_arcmt_check,
                                        options::OPT_ccc_arcmt_modify,
                                        options::OPT_ccc_arcmt_migrate)) {
+      ARCMTEnabled =3D true;
       switch (A->getOption().getID()) {
       default:
         llvm_unreachable("missed a case");
@@ -1511,7 +1861,7 @@
         break;
       case options::OPT_ccc_arcmt_migrate:
         CmdArgs.push_back("-arcmt-migrate");
-        CmdArgs.push_back("-arcmt-migrate-directory");
+        CmdArgs.push_back("-mt-migrate-directory");
         CmdArgs.push_back(A->getValue(Args));
=20
         Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
@@ -1521,12 +1871,31 @@
     }
   }
=20
+  if (const Arg *A =3D Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
+    if (ARCMTEnabled) {
+      D.Diag(diag::err_drv_argument_not_allowed_with)
+        << A->getAsString(Args) << "-ccc-arcmt-migrate";
+    }
+    CmdArgs.push_back("-mt-migrate-directory");
+    CmdArgs.push_back(A->getValue(Args));
+
+    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
+                     options::OPT_objcmt_migrate_subscripting)) {
+      // None specified, means enable them all.
+      CmdArgs.push_back("-objcmt-migrate-literals");
+      CmdArgs.push_back("-objcmt-migrate-subscripting");
+    } else {
+      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
+      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
+    }
+  }
+
   // Add preprocessing options like -I, -D, etc. if we are using the
   // preprocessor.
   //
   // FIXME: Support -fpreprocessed
   if (types::getPreprocessedType(InputType) !=3D types::TY_INVALID)
-    AddPreprocessingOptions(D, Args, CmdArgs, Output, Inputs);
+    AddPreprocessingOptions(C, D, Args, CmdArgs, Output, Inputs);
=20
   // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 ass=
umes
   // that "The compiler can only warn and ignore the option if not recogni=
zed".
@@ -1611,11 +1980,30 @@
   if (ShouldDisableCFI(Args, getToolChain()))
     CmdArgs.push_back("-fno-dwarf2-cfi-asm");
=20
-  if (Arg *A =3D Args.getLastArg(options::OPT_ftemplate_depth_)) {
+  if (ShouldDisableDwarfDirectory(Args, getToolChain()))
+    CmdArgs.push_back("-fno-dwarf-directory-asm");
+
+  if (const char *pwd =3D ::getenv("PWD")) {
+    // GCC also verifies that stat(pwd) and stat(".") have the same inode
+    // number. Not doing those because stats are slow, but we could.
+    if (llvm::sys::path::is_absolute(pwd)) {
+      std::string CompDir =3D pwd;
+      CmdArgs.push_back("-fdebug-compilation-dir");
+      CmdArgs.push_back(Args.MakeArgString(CompDir));
+    }
+  }
+
+  if (Arg *A =3D Args.getLastArg(options::OPT_ftemplate_depth_,
+                               options::OPT_ftemplate_depth_EQ)) {
     CmdArgs.push_back("-ftemplate-depth");
     CmdArgs.push_back(A->getValue(Args));
   }
=20
+  if (Arg *A =3D Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
+    CmdArgs.push_back("-fconstexpr-depth");
+    CmdArgs.push_back(A->getValue(Args));
+  }
+
   if (Arg *A =3D Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
                                options::OPT_Wlarge_by_value_copy_def)) {
     CmdArgs.push_back("-Wlarge-by-value-copy");
@@ -1654,6 +2042,11 @@
     CmdArgs.push_back(A->getValue(Args));
   }
=20
+  if (Arg *A =3D Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_E=
Q)) {
+    CmdArgs.push_back("-fconstexpr-backtrace-limit");
+    CmdArgs.push_back(A->getValue(Args));
+  }
+
   // Pass -fmessage-length=3D.
   CmdArgs.push_back("-fmessage-length");
   if (Arg *A =3D Args.getLastArg(options::OPT_fmessage_length_EQ)) {
@@ -1673,9 +2066,8 @@
   Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
=20
   // -fhosted is default.
-  if (KernelOrKext || Args.hasFlag(options::OPT_ffreestanding,
-                                   options::OPT_fhosted,
-                                   false))
+  if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false=
) ||
+      KernelOrKext)
     CmdArgs.push_back("-ffreestanding");
=20
   // Forward -f (flag) options which we can pass directly.
@@ -1684,9 +2076,28 @@
   Args.AddLastArg(CmdArgs, options::OPT_fformat_extensions);
   Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
   Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info);
+  Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info);
+  Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
+  Args.AddLastArg(CmdArgs, options::OPT_faltivec);
+
+  // Report and error for -faltivec on anything other then PowerPC.
+  if (const Arg *A =3D Args.getLastArg(options::OPT_faltivec))
+    if (!(getToolChain().getTriple().getArch() =3D=3D llvm::Triple::ppc ||
+          getToolChain().getTriple().getArch() =3D=3D llvm::Triple::ppc64))
+      D.Diag(diag::err_drv_argument_only_allowed_with)
+        << A->getAsString(Args) << "ppc/ppc64";
+
   if (getToolChain().SupportsProfiling())
     Args.AddLastArg(CmdArgs, options::OPT_pg);
=20
+  if (Args.hasFlag(options::OPT_faddress_sanitizer,
+                   options::OPT_fno_address_sanitizer, false))
+    CmdArgs.push_back("-faddress-sanitizer");
+
+  if (Args.hasFlag(options::OPT_fthread_sanitizer,
+                   options::OPT_fno_thread_sanitizer, false))
+    CmdArgs.push_back("-fthread-sanitizer");
+
   // -flax-vector-conversions is default.
   if (!Args.hasFlag(options::OPT_flax_vector_conversions,
                     options::OPT_fno_lax_vector_conversions))
@@ -1706,12 +2117,7 @@
     CmdArgs.push_back(A->getValue(Args));
   }
=20
-  // Forward -ftrap_function=3D options to the backend.
-  if (Arg *A =3D Args.getLastArg(options::OPT_ftrap_function_EQ)) {
-    StringRef FuncName =3D A->getValue(Args);
-    CmdArgs.push_back("-backend-option");
-    CmdArgs.push_back(Args.MakeArgString("-trap-func=3D" + FuncName));
-  }
+  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
=20
   // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
   // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
@@ -1748,10 +2154,20 @@
   }
=20
   // Translate -mstackrealign
-  if (Args.hasArg(options::OPT_mstackrealign)) {
+  if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackreali=
gn,
+                   false)) {
     CmdArgs.push_back("-backend-option");
     CmdArgs.push_back("-force-align-stack");
   }
+  if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackreal=
ign,
+                   false)) {
+    CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
+  }
+
+  if (Args.hasArg(options::OPT_mstack_alignment)) {
+    StringRef alignment =3D Args.getLastArgValue(options::OPT_mstack_align=
ment);
+    CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=3D" + alignmen=
t));
+  }
=20
   // Forward -f options with positive and negative forms; we translate
   // these by hand.
@@ -1761,6 +2177,7 @@
       CmdArgs.push_back("-fapple-kext");
     if (!Args.hasArg(options::OPT_fbuiltin))
       CmdArgs.push_back("-fno-builtin");
+    Args.ClaimAllArgs(options::OPT_fno_builtin);
   }
   // -fbuiltin is default.
   else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin))
@@ -1783,6 +2200,17 @@
       CmdArgs.push_back("-fblocks-runtime-optional");
   }
=20
+  // -fmodules enables modules (off by default). However, for C++/Objectiv=
e-C++,
+  // users must also pass -fcxx-modules. The latter flag will disappear on=
ce the
+  // modules implementation is solid for C++/Objective-C++ programs as wel=
l.
+  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)=
) {
+    bool AllowedInCXX =3D Args.hasFlag(options::OPT_fcxx_modules,=20
+                                     options::OPT_fno_cxx_modules,=20
+                                     false);
+    if (AllowedInCXX || !types::isCXX(InputType))
+      CmdArgs.push_back("-fmodules");
+  }
+
   // -faccess-control is default.
   if (Args.hasFlag(options::OPT_fno_access_control,
                    options::OPT_faccess_control,
@@ -1796,14 +2224,15 @@
     CmdArgs.push_back("-fno-elide-constructors");
=20
   // -frtti is default.
-  if (KernelOrKext ||
-      !Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti))
+  if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) ||
+      KernelOrKext)
     CmdArgs.push_back("-fno-rtti");
=20
-  // -fshort-enums=3D0 is default.
-  // FIXME: Are there targers where -fshort-enums is on by default ?
+  // -fshort-enums=3D0 is default for all architectures except Hexagon.
   if (Args.hasFlag(options::OPT_fshort_enums,
-                   options::OPT_fno_short_enums, false))
+                   options::OPT_fno_short_enums,
+                   getToolChain().getTriple().getArch() =3D=3D
+                   llvm::Triple::hexagon))
     CmdArgs.push_back("-fshort-enums");
=20
   // -fsigned-char is default.
@@ -1817,10 +2246,12 @@
     CmdArgs.push_back("-fno-threadsafe-statics");
=20
   // -fuse-cxa-atexit is default.
-  if (KernelOrKext ||
-    !Args.hasFlag(options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_a=
texit,
-                  getToolChain().getTriple().getOS() !=3D llvm::Triple::Cy=
gwin &&
-                  getToolChain().getTriple().getOS() !=3D llvm::Triple::Mi=
nGW32))
+  if (!Args.hasFlag(options::OPT_fuse_cxa_atexit,
+                    options::OPT_fno_use_cxa_atexit,
+                   getToolChain().getTriple().getOS() !=3D llvm::Triple::C=
ygwin &&
+                  getToolChain().getTriple().getOS() !=3D llvm::Triple::Mi=
nGW32 &&
+              getToolChain().getTriple().getArch() !=3D llvm::Triple::hexa=
gon) ||
+      KernelOrKext)
     CmdArgs.push_back("-fno-use-cxa-atexit");
=20
   // -fms-extensions=3D0 is default.
@@ -1829,8 +2260,12 @@
     CmdArgs.push_back("-fms-extensions");
=20
   // -fms-compatibility=3D0 is default.
-  if (Args.hasFlag(options::OPT_fms_compatibility, options::OPT_fno_ms_com=
patibility,
-                   getToolChain().getTriple().getOS() =3D=3D llvm::Triple:=
:Win32))
+  if (Args.hasFlag(options::OPT_fms_compatibility,=20
+                   options::OPT_fno_ms_compatibility,
+                   (getToolChain().getTriple().getOS() =3D=3D llvm::Triple=
::Win32 &&
+                    Args.hasFlag(options::OPT_fms_extensions,=20
+                                 options::OPT_fno_ms_extensions,
+                                 true))))
     CmdArgs.push_back("-fms-compatibility");
=20
   // -fmsc-version=3D1300 is default.
@@ -1868,11 +2303,18 @@
                    false))
     CmdArgs.push_back("-fgnu89-inline");
=20
+  if (Args.hasArg(options::OPT_fno_inline))
+    CmdArgs.push_back("-fno-inline");
+
+  if (Args.hasArg(options::OPT_fno_inline_functions))
+    CmdArgs.push_back("-fno-inline-functions");
+
   // -fobjc-nonfragile-abi=3D0 is default.
   ObjCRuntime objCRuntime;
   unsigned objcABIVersion =3D 0;
   bool NeXTRuntimeIsDefault
-    =3D (IsRewriter || getToolChain().getTriple().isOSDarwin());
+    =3D (IsRewriter || IsModernRewriter ||
+       getToolChain().getTriple().isOSDarwin());
   if (Args.hasFlag(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
                    NeXTRuntimeIsDefault)) {
     objCRuntime.setKind(ObjCRuntime::NeXT);
@@ -1906,8 +2348,9 @@
       D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
   } else {
     // Otherwise, determine if we are using the non-fragile ABI.
-    bool NonFragileABIIsDefault
-      =3D (!IsRewriter && getToolChain().IsObjCNonFragileABIDefault());
+    bool NonFragileABIIsDefault =3D=20
+      (IsModernRewriter ||=20
+       (!IsRewriter && getToolChain().IsObjCNonFragileABIDefault()));
     if (Args.hasFlag(options::OPT_fobjc_nonfragile_abi,
                      options::OPT_fno_objc_nonfragile_abi,
                      NonFragileABIIsDefault)) {
@@ -1950,10 +2393,9 @@
     }
   }
=20
-  // -fobjc-default-synthesize-properties=3D0 is default.
-  if (Args.hasFlag(options::OPT_fobjc_default_synthesize_properties,
-                   options::OPT_fno_objc_default_synthesize_properties,
-                   getToolChain().IsObjCDefaultSynthPropertiesDefault())) {
+  // -fobjc-default-synthesize-properties=3D1 is default. This only has an=
 effect
+  // if the nonfragile objc abi is used.
+  if (getToolChain().IsObjCDefaultSynthPropertiesDefault()) {
     CmdArgs.push_back("-fobjc-default-synthesize-properties");
   }
=20
@@ -1961,6 +2403,9 @@
   // NOTE: This logic is duplicated in ToolChains.cpp.
   bool ARC =3D isObjCAutoRefCount(Args);
   if (ARC) {
+    if (!getToolChain().SupportsObjCARC())
+      D.Diag(diag::err_arc_unsupported);
+
     CmdArgs.push_back("-fobjc-arc");
=20
     // FIXME: It seems like this entire block, and several around it shoul=
d be
@@ -1983,7 +2428,7 @@
=20
   // -fobjc-infer-related-result-type is the default, except in the Object=
ive-C
   // rewriter.
-  if (IsRewriter)
+  if (IsRewriter || IsModernRewriter)
     CmdArgs.push_back("-fno-objc-infer-related-result-type");
=20
   // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-g=
c-only
@@ -2006,7 +2451,7 @@
=20
   // Add exception args.
   addExceptionArgs(Args, InputType, getToolChain().getTriple(),
-                   KernelOrKext, IsRewriter, objcABIVersion, CmdArgs);
+                   KernelOrKext, objcABIVersion, CmdArgs);
=20
   if (getToolChain().UseSjLjExceptions())
     CmdArgs.push_back("-fsjlj-exceptions");
@@ -2057,6 +2502,7 @@
       Args.hasArg(options::OPT_fapple_kext)) {
     if (!Args.hasArg(options::OPT_fcommon))
       CmdArgs.push_back("-fno-common");
+    Args.ClaimAllArgs(options::OPT_fno_common);
   }
=20
   // -fcommon is default, only pass non-default.
@@ -2086,11 +2532,6 @@
                     options::OPT_fno_diagnostics_fixit_info))
     CmdArgs.push_back("-fno-diagnostics-fixit-info");
=20
-  // Enable -fdiagnostics-show-name by default.
-  if (Args.hasFlag(options::OPT_fdiagnostics_show_name,
-                   options::OPT_fno_diagnostics_show_name, false))
-    CmdArgs.push_back("-fdiagnostics-show-name");
-
   // Enable -fdiagnostics-show-option by default.
   if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
                    options::OPT_fno_diagnostics_show_option))
@@ -2164,6 +2605,10 @@
       D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
   }
=20
+  if (Args.hasFlag(options::OPT_fapple_pragma_pack,
+                   options::OPT_fno_apple_pragma_pack, false))
+    CmdArgs.push_back("-fapple-pragma-pack");
+
   // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
   //
   // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. P=
R4941.
@@ -2189,6 +2634,12 @@
=20
   Args.AddLastArg(CmdArgs, options::OPT_dM);
   Args.AddLastArg(CmdArgs, options::OPT_dD);
+ =20
+  // Handle serialized diagnostics.
+  if (Arg *A =3D Args.getLastArg(options::OPT__serialize_diags)) {
+    CmdArgs.push_back("-serialize-diagnostic-file");
+    CmdArgs.push_back(Args.MakeArgString(A->getValue(Args)));
+  }
=20
   // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM o=
ption
   // parser.
@@ -2237,7 +2688,7 @@
            ie =3D Args.end(); it !=3D ie; ++it)
       (*it)->render(Args, OriginalArgs);
=20
-    llvm::SmallString<256> Flags;
+    SmallString<256> Flags;
     Flags +=3D Exec;
     for (unsigned i =3D 0, e =3D OriginalArgs.size(); i !=3D e; ++i) {
       Flags +=3D " ";
@@ -2271,6 +2722,24 @@
   Args.ClaimAllArgs(options::OPT_emit_llvm);
 }
=20
+void ClangAs::AddARMTargetArgs(const ArgList &Args,
+                               ArgStringList &CmdArgs) const {
+  const Driver &D =3D getToolChain().getDriver();
+  llvm::Triple Triple =3D getToolChain().getTriple();
+
+  // Set the CPU based on -march=3D and -mcpu=3D.
+  CmdArgs.push_back("-target-cpu");
+  CmdArgs.push_back(getARMTargetCPU(Args, Triple));
+
+  // Honor -mfpu=3D.
+  if (const Arg *A =3D Args.getLastArg(options::OPT_mfpu_EQ))
+    addFPUArgs(D, A, Args, CmdArgs);
+
+  // Honor -mfpmath=3D.
+  if (const Arg *A =3D Args.getLastArg(options::OPT_mfpmath_EQ))
+    addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple));
+}
+
 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
                            const InputInfo &Output,
                            const InputInfoList &Inputs,
@@ -2307,10 +2776,54 @@
   if (UseRelaxAll(C, Args))
     CmdArgs.push_back("-relax-all");
=20
+  // Add target specific cpu and features flags.
+  switch(getToolChain().getTriple().getArch()) {
+  default:
+    break;
+
+  case llvm::Triple::arm:
+  case llvm::Triple::thumb:
+    AddARMTargetArgs(Args, CmdArgs);
+    break;
+  }
+
   // Ignore explicit -force_cpusubtype_ALL option.
   (void) Args.hasArg(options::OPT_force__cpusubtype__ALL);
=20
-  // FIXME: Add -g support, once we have it.
+  // Determine the original source input.
+  const Action *SourceAction =3D &JA;
+  while (SourceAction->getKind() !=3D Action::InputClass) {
+    assert(!SourceAction->getInputs().empty() && "unexpected root action!"=
);
+    SourceAction =3D SourceAction->getInputs()[0];
+  }
+
+  // Forward -g, assuming we are dealing with an actual assembly file.
+  if (SourceAction->getType() =3D=3D types::TY_Asm ||
+      SourceAction->getType() =3D=3D types::TY_PP_Asm) {
+    Args.ClaimAllArgs(options::OPT_g_Group);
+    if (Arg *A =3D Args.getLastArg(options::OPT_g_Group))
+      if (!A->getOption().matches(options::OPT_g0))
+        CmdArgs.push_back("-g");
+  }
+
+  // Optionally embed the -cc1as level arguments into the debug info, for =
build
+  // analysis.
+  if (getToolChain().UseDwarfDebugFlags()) {
+    ArgStringList OriginalArgs;
+    for (ArgList::const_iterator it =3D Args.begin(),
+           ie =3D Args.end(); it !=3D ie; ++it)
+      (*it)->render(Args, OriginalArgs);
+
+    SmallString<256> Flags;
+    const char *Exec =3D getToolChain().getDriver().getClangProgramPath();
+    Flags +=3D Exec;
+    for (unsigned i =3D 0, e =3D OriginalArgs.size(); i !=3D e; ++i) {
+      Flags +=3D " ";
+      Flags +=3D OriginalArgs[i];
+    }
+    CmdArgs.push_back("-dwarf-debug-flags");
+    CmdArgs.push_back(Args.MakeArgString(Flags.str()));
+  }
=20
   // FIXME: Add -static support, once we have it.
=20
@@ -2389,6 +2902,8 @@
     CmdArgs.push_back("-fsyntax-only");
   }
=20
+  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
+                       options::OPT_Xassembler);
=20
   // Only pass -x if gcc will understand it; otherwise hope gcc
   // understands the suffix correctly. The main use case this would go
@@ -2437,12 +2952,7 @@
   if (!customGCCName.empty())
     GCCName =3D customGCCName.c_str();
   else if (D.CCCIsCXX) {
-#ifdef IS_CYGWIN15
-    // FIXME: Detect the version of Cygwin at runtime?
-    GCCName =3D "g++-4";
-#else
     GCCName =3D "g++";
-#endif
   } else
     GCCName =3D "gcc";
=20
@@ -2488,6 +2998,155 @@
   // The types are (hopefully) good enough.
 }
=20
+// Hexagon tools start.
+void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA,
+                                        ArgStringList &CmdArgs) const {
+
+}
+void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
+                               const InputInfo &Output,
+                               const InputInfoList &Inputs,
+                               const ArgList &Args,
+                               const char *LinkingOutput) const {
+
+  const Driver &D =3D getToolChain().getDriver();
+  ArgStringList CmdArgs;
+
+  std::string MarchString =3D "-march=3D";
+  MarchString +=3D getHexagonTargetCPU(Args);
+  CmdArgs.push_back(Args.MakeArgString(MarchString));
+
+  RenderExtraToolArgs(JA, CmdArgs);
+
+  if (Output.isFilename()) {
+    CmdArgs.push_back("-o");
+    CmdArgs.push_back(Output.getFilename());
+  } else {
+    assert(Output.isNothing() && "Unexpected output");
+    CmdArgs.push_back("-fsyntax-only");
+  }
+
+
+  // Only pass -x if gcc will understand it; otherwise hope gcc
+  // understands the suffix correctly. The main use case this would go
+  // wrong in is for linker inputs if they happened to have an odd
+  // suffix; really the only way to get this to happen is a command
+  // like '-x foobar a.c' which will treat a.c like a linker input.
+  //
+  // FIXME: For the linker case specifically, can we safely convert
+  // inputs into '-Wl,' options?
+  for (InputInfoList::const_iterator
+         it =3D Inputs.begin(), ie =3D Inputs.end(); it !=3D ie; ++it) {
+    const InputInfo &II =3D *it;
+
+    // Don't try to pass LLVM or AST inputs to a generic gcc.
+    if (II.getType() =3D=3D types::TY_LLVM_IR || II.getType() =3D=3D types=
::TY_LTO_IR ||
+        II.getType() =3D=3D types::TY_LLVM_BC || II.getType() =3D=3D types=
::TY_LTO_BC)
+      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
+        << getToolChain().getTripleString();
+    else if (II.getType() =3D=3D types::TY_AST)
+      D.Diag(clang::diag::err_drv_no_ast_support)
+        << getToolChain().getTripleString();
+
+    if (II.isFilename())
+      CmdArgs.push_back(II.getFilename());
+    else
+      // Don't render as input, we need gcc to do the translations. FIXME:=
 Pranav: What is this ?
+      II.getInputArg().render(Args, CmdArgs);
+  }
+
+  const char *GCCName =3D "hexagon-as";
+  const char *Exec =3D
+    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
+  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
+
+}
+void hexagon::Link::RenderExtraToolArgs(const JobAction &JA,
+                                    ArgStringList &CmdArgs) const {
+  // The types are (hopefully) good enough.
+}
+
+void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA,
+                               const InputInfo &Output,
+                               const InputInfoList &Inputs,
+                               const ArgList &Args,
+                               const char *LinkingOutput) const {
+
+  const Driver &D =3D getToolChain().getDriver();
+  ArgStringList CmdArgs;
+
+  for (ArgList::const_iterator
+         it =3D Args.begin(), ie =3D Args.end(); it !=3D ie; ++it) {
+    Arg *A =3D *it;
+    if (A->getOption().hasForwardToGCC()) {
+      // Don't forward any -g arguments to assembly steps.
+      if (isa<AssembleJobAction>(JA) &&
+          A->getOption().matches(options::OPT_g_Group))
+        continue;
+
+      // It is unfortunate that we have to claim here, as this means
+      // we will basically never report anything interesting for
+      // platforms using a generic gcc, even if we are just using gcc
+      // to get to the assembler.
+      A->claim();
+      A->render(Args, CmdArgs);
+    }
+  }
+
+  RenderExtraToolArgs(JA, CmdArgs);
+
+  // Add Arch Information
+  Arg *A;
+  if ((A =3D getLastHexagonArchArg(Args))) {
+    if (A->getOption().matches(options::OPT_m_Joined))
+      A->render(Args, CmdArgs);
+    else
+      CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Arg=
s)));
+  }
+  else {
+    CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args)=
));
+  }
+
+  CmdArgs.push_back("-mqdsp6-compat");
+
+  const char *GCCName;
+  if (C.getDriver().CCCIsCXX)
+    GCCName =3D "hexagon-g++";
+  else
+    GCCName =3D "hexagon-gcc";
+  const char *Exec =3D
+    Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
+
+  if (Output.isFilename()) {
+    CmdArgs.push_back("-o");
+    CmdArgs.push_back(Output.getFilename());
+  }
+
+  for (InputInfoList::const_iterator
+         it =3D Inputs.begin(), ie =3D Inputs.end(); it !=3D ie; ++it) {
+    const InputInfo &II =3D *it;
+
+    // Don't try to pass LLVM or AST inputs to a generic gcc.
+    if (II.getType() =3D=3D types::TY_LLVM_IR || II.getType() =3D=3D types=
::TY_LTO_IR ||
+        II.getType() =3D=3D types::TY_LLVM_BC || II.getType() =3D=3D types=
::TY_LTO_BC)
+      D.Diag(clang::diag::err_drv_no_linker_llvm_support)
+        << getToolChain().getTripleString();
+    else if (II.getType() =3D=3D types::TY_AST)
+      D.Diag(clang::diag::err_drv_no_ast_support)
+        << getToolChain().getTripleString();
+
+    if (II.isFilename())
+      CmdArgs.push_back(II.getFilename());
+    else
+      // Don't render as input, we need gcc to do the translations. FIXME:=
 Pranav: What is this ?
+      II.getInputArg().render(Args, CmdArgs);
+  }
+  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
+
+}
+// Hexagon tools end.
+
+
 const char *darwin::CC1::getCC1Name(types::ID Type) const {
   switch (Type) {
   default:
@@ -2510,6 +3169,8 @@
   }
 }
=20
+void darwin::CC1::anchor() {}
+
 const char *darwin::CC1::getBaseInputName(const ArgList &Args,
                                           const InputInfoList &Inputs) {
   return Args.MakeArgString(
@@ -2548,13 +3209,27 @@
     StringRef Option =3D *it;
     bool RemoveOption =3D false;
=20
-    // Remove -faltivec
-    if (Option.equals("-faltivec")) {
-      it =3D CmdArgs.erase(it);
+    // Erase both -fmodule-cache-path and its argument.
+    if (Option.equals("-fmodule-cache-path") && it+2 !=3D ie) {
+      it =3D CmdArgs.erase(it, it+2);
       ie =3D CmdArgs.end();
       continue;
     }
=20
+    // Remove unsupported -f options.
+    if (Option.startswith("-f")) {
+      // Remove -f/-fno- to reduce the number of cases.
+      if (Option.startswith("-fno-"))
+        Option =3D Option.substr(5);
+      else
+        Option =3D Option.substr(2);
+      RemoveOption =3D llvm::StringSwitch<bool>(Option)
+        .Case("altivec", true)
+        .Case("modules", true)
+        .Case("diagnostics-show-note-include-stack", true)
+        .Default(false);
+    }
+
     // Handle machine specific options.
     if (Option.startswith("-m")) {
       RemoveOption =3D llvm::StringSwitch<bool>(Option)
@@ -2595,6 +3270,7 @@
         .Case("c++11-narrowing", true)
         .Case("conditional-uninitialized", true)
         .Case("constant-conversion", true)
+        .Case("conversion-null", true)
         .Case("CFString-literal", true)
         .Case("constant-logical-operand", true)
         .Case("custom-atomic-properties", true)
@@ -3000,9 +3676,11 @@
=20
   assert(Inputs.size() =3D=3D 1 && "Unexpected number of inputs!");
=20
+  // Silence warning about unused --serialize-diagnostics
+  Args.ClaimAllArgs(options::OPT__serialize_diags);
+
   types::ID InputType =3D Inputs[0].getType();
-  const Arg *A;
-  if ((A =3D Args.getLastArg(options::OPT_traditional)))
+  if (const Arg *A =3D Args.getLastArg(options::OPT_traditional))
     D.Diag(diag::err_drv_argument_only_allowed_with)
       << A->getAsString(Args) << "-E";
=20
@@ -3119,7 +3797,7 @@
     if (Args.hasArg(options::OPT_gstabs))
       CmdArgs.push_back("--gstabs");
     else if (Args.hasArg(options::OPT_g_Group))
-      CmdArgs.push_back("--gdwarf2");
+      CmdArgs.push_back("-g");
   }
=20
   // Derived from asm spec.
@@ -3154,6 +3832,8 @@
   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
 }
=20
+void darwin::DarwinTool::anchor() {}
+
 void darwin::DarwinTool::AddDarwinArch(const ArgList &Args,
                                        ArgStringList &CmdArgs) const {
   StringRef ArchName =3D getDarwinToolChain().getDarwinArchName(Args);
@@ -3185,13 +3865,7 @@
=20
   // Newer linkers support -demangle, pass it if supported and not disable=
d by
   // the user.
-  //
-  // FIXME: We temporarily avoid passing -demangle to any iOS linker, beca=
use
-  // unfortunately we can't be guaranteed that the linker version used the=
re
-  // will match the linker version detected at configure time. We need the
-  // universal driver.
-  if (Version[0] >=3D 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_deman=
gle) &&
-      !DarwinTC.isTargetIPhoneOS()) {
+  if (Version[0] >=3D 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_deman=
gle)) {
     // Don't pass -demangle to ld_classic.
     //
     // FIXME: This is a temporary workaround, ld should be handling this.
@@ -3291,8 +3965,7 @@
   Args.AddAllArgs(CmdArgs, options::OPT_init);
=20
   // Add the deployment target.
-  unsigned TargetVersion[3];
-  DarwinTC.getTargetVersion(TargetVersion);
+  VersionTuple TargetVersion =3D DarwinTC.getTargetVersion();
=20
   // If we had an explicit -mios-simulator-version-min argument, honor tha=
t,
   // otherwise use the traditional deployment targets. We can't just check=
 the
@@ -3307,9 +3980,7 @@
     CmdArgs.push_back("-iphoneos_version_min");
   else
     CmdArgs.push_back("-macosx_version_min");
-  CmdArgs.push_back(Args.MakeArgString(Twine(TargetVersion[0]) + "." +
-                                       Twine(TargetVersion[1]) + "." +
-                                       Twine(TargetVersion[2])));
+  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
=20
   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
@@ -3492,7 +4163,7 @@
                 CmdArgs.push_back("-lcrt1.o");
               else if (getDarwinToolChain().isMacosxVersionLT(10, 6))
                 CmdArgs.push_back("-lcrt1.10.5.o");
-              else
+              else if (getDarwinToolChain().isMacosxVersionLT(10, 8))
                 CmdArgs.push_back("-lcrt1.10.6.o");
=20
               // darwin_crt2 spec is empty.
@@ -3513,20 +4184,42 @@
=20
   Args.AddAllArgs(CmdArgs, options::OPT_L);
=20
+  // If we're building a dynamic lib with -faddress-sanitizer, unresolved
+  // symbols may appear. Mark all of them as dynamic_lookup.
+  // Linking executables is handled in lib/Driver/ToolChains.cpp.
+  if (Args.hasFlag(options::OPT_faddress_sanitizer,
+                   options::OPT_fno_address_sanitizer, false)) {
+    if (Args.hasArg(options::OPT_dynamiclib) ||
+        Args.hasArg(options::OPT_bundle)) {
+      CmdArgs.push_back("-undefined");
+      CmdArgs.push_back("dynamic_lookup");
+    }
+  }
+
   if (Args.hasArg(options::OPT_fopenmp))
     // This is more complicated in gcc...
     CmdArgs.push_back("-lgomp");
=20
   getDarwinToolChain().AddLinkSearchPathArgs(Args, CmdArgs);
=20
-  // In ARC, if we don't have runtime support, link in the runtime
-  // stubs.  We have to do this *before* adding any of the normal
-  // linker inputs so that its initializer gets run first.
-  if (isObjCAutoRefCount(Args)) {
-    ObjCRuntime runtime;
-    getDarwinToolChain().configureObjCRuntime(runtime);
-    if (!runtime.HasARC)
-      getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
+  if (isObjCRuntimeLinked(Args)) {
+    // Avoid linking compatibility stubs on i386 mac.
+    if (!getDarwinToolChain().isTargetMacOS() ||
+        getDarwinToolChain().getArchName() !=3D "i386") {
+      // If we don't have ARC or subscripting runtime support, link in the
+      // runtime stubs.  We have to do this *before* adding any of the nor=
mal
+      // linker inputs so that its initializer gets run first.
+      ObjCRuntime runtime;
+      getDarwinToolChain().configureObjCRuntime(runtime);
+      // We use arclite library for both ARC and subscripting support.
+      if ((!runtime.HasARC && isObjCAutoRefCount(Args)) ||
+          !runtime.HasSubscripting)
+        getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs);
+      CmdArgs.push_back("-framework");
+      CmdArgs.push_back("Foundation");
+    }
+    // Link libobj.
+    CmdArgs.push_back("-lobjc");
   }
=20
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
@@ -3557,8 +4250,6 @@
     // endfile_spec is empty.
   }
=20
-  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
-
   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
   Args.AddAllArgs(CmdArgs, options::OPT_F);
=20
@@ -3618,6 +4309,9 @@
 				       const char *LinkingOutput) const {
   ArgStringList CmdArgs;
   CmdArgs.push_back("--verify");
+  CmdArgs.push_back("--debug-info");
+  CmdArgs.push_back("--eh-frame");
+  CmdArgs.push_back("--quiet");
=20
   assert(Inputs.size() =3D=3D 1 && "Unable to handle multiple inputs.");
   const InputInfo &Input =3D Inputs[0];
@@ -3631,6 +4325,137 @@
   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
 }
=20
+void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
+                                      const InputInfo &Output,
+                                      const InputInfoList &Inputs,
+                                      const ArgList &Args,
+                                      const char *LinkingOutput) const {
+  ArgStringList CmdArgs;
+
+  Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
+                       options::OPT_Xassembler);
+
+  CmdArgs.push_back("-o");
+  CmdArgs.push_back(Output.getFilename());
+
+  for (InputInfoList::const_iterator
+         it =3D Inputs.begin(), ie =3D Inputs.end(); it !=3D ie; ++it) {
+    const InputInfo &II =3D *it;
+    CmdArgs.push_back(II.getFilename());
+  }
+
+  const char *Exec =3D
+    Args.MakeArgString(getToolChain().GetProgramPath("as"));
+  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
+}
+
+
+void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA,
+                                  const InputInfo &Output,
+                                  const InputInfoList &Inputs,
+                                  const ArgList &Args,
+                                  const char *LinkingOutput) const {
+  // FIXME: Find a real GCC, don't hard-code versions here
+  std::string GCCLibPath =3D "/usr/gcc/4.5/lib/gcc/";
+  const llvm::Triple &T =3D getToolChain().getTriple();
+  std::string LibPath =3D "/usr/lib/";
+  llvm::Triple::ArchType Arch =3D T.getArch();
+  switch (Arch) {
+        case llvm::Triple::x86:
+          GCCLibPath +=3D ("i386-" + T.getVendorName() + "-" +
+              T.getOSName()).str() + "/4.5.2/";
+          break;
+        case llvm::Triple::x86_64:
+          GCCLibPath +=3D ("i386-" + T.getVendorName() + "-" +
+              T.getOSName()).str();
+          GCCLibPath +=3D "/4.5.2/amd64/";
+          LibPath +=3D "amd64/";
+          break;
+        default:
+          assert(0 && "Unsupported architecture");
+  }
+
+  ArgStringList CmdArgs;
+
+  // Demangle C++ names in errors
+  CmdArgs.push_back("-C");
+
+  if ((!Args.hasArg(options::OPT_nostdlib)) &&
+      (!Args.hasArg(options::OPT_shared))) {
+    CmdArgs.push_back("-e");
+    CmdArgs.push_back("_start");
+  }
+
+  if (Args.hasArg(options::OPT_static)) {
+    CmdArgs.push_back("-Bstatic");
+    CmdArgs.push_back("-dn");
+  } else {
+    CmdArgs.push_back("-Bdynamic");
+    if (Args.hasArg(options::OPT_shared)) {
+      CmdArgs.push_back("-shared");
+    } else {
+      CmdArgs.push_back("--dynamic-linker");
+      CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1"));
+    }
+  }
+
+  if (Output.isFilename()) {
+    CmdArgs.push_back("-o");
+    CmdArgs.push_back(Output.getFilename());
+  } else {
+    assert(Output.isNothing() && "Invalid output.");
+  }
+
+  if (!Args.hasArg(options::OPT_nostdlib) &&
+      !Args.hasArg(options::OPT_nostartfiles)) {
+    if (!Args.hasArg(options::OPT_shared)) {
+      CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o"));
+      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
+      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
+      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
+    } else {
+      CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o"));
+      CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o"));
+      CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o"));
+    }
+    if (getToolChain().getDriver().CCCIsCXX)
+      CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o"));
+  }
+
+  CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath));
+
+  Args.AddAllArgs(CmdArgs, options::OPT_L);
+  Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
+  Args.AddAllArgs(CmdArgs, options::OPT_e);
+  Args.AddAllArgs(CmdArgs, options::OPT_r);
+
+  AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
+
+  if (!Args.hasArg(options::OPT_nostdlib) &&
+      !Args.hasArg(options::OPT_nodefaultlibs)) {
+    if (getToolChain().getDriver().CCCIsCXX)
+      getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
+    CmdArgs.push_back("-lgcc_s");
+    if (!Args.hasArg(options::OPT_shared)) {
+      CmdArgs.push_back("-lgcc");
+      CmdArgs.push_back("-lc");
+      CmdArgs.push_back("-lm");
+    }
+  }
+
+  if (!Args.hasArg(options::OPT_nostdlib) &&
+      !Args.hasArg(options::OPT_nostartfiles)) {
+    CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o"));
+  }
+  CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o"));
+
+  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
+
+  const char *Exec =3D
+    Args.MakeArgString(getToolChain().GetProgramPath("ld"));
+  C.addCommand(new Command(JA, *this, Exec, CmdArgs));
+}
+
 void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
                                       const InputInfo &Output,
                                       const InputInfoList &Inputs,
@@ -3806,8 +4631,12 @@
   if (!Args.hasArg(options::OPT_nostdlib) &&
       !Args.hasArg(options::OPT_nostartfiles)) {
     if (!Args.hasArg(options::OPT_shared)) {
-      CmdArgs.push_back(Args.MakeArgString(
-                              getToolChain().GetFilePath("crt0.o")));
+      if (Args.hasArg(options::OPT_pg)) =20
+        CmdArgs.push_back(Args.MakeArgString(
+                                getToolChain().GetFilePath("gcrt0.o")));
+      else
+        CmdArgs.push_back(Args.MakeArgString(
+                                getToolChain().GetFilePath("crt0.o")));
       CmdArgs.push_back(Args.MakeArgString(
                               getToolChain().GetFilePath("crtbegin.o")));
     } else {
@@ -3832,7 +4661,10 @@
       !Args.hasArg(options::OPT_nodefaultlibs)) {
     if (D.CCCIsCXX) {
       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
-      CmdArgs.push_back("-lm");
+      if (Args.hasArg(options::OPT_pg))=20
+        CmdArgs.push_back("-lm_p");
+      else
+        CmdArgs.push_back("-lm");
     }
=20
     // FIXME: For some reason GCC passes -lgcc before adding
@@ -3841,8 +4673,12 @@
=20
     if (Args.hasArg(options::OPT_pthread))
       CmdArgs.push_back("-lpthread");
-    if (!Args.hasArg(options::OPT_shared))
-      CmdArgs.push_back("-lc");
+    if (!Args.hasArg(options::OPT_shared)) {
+      if (Args.hasArg(options::OPT_pg))=20
+         CmdArgs.push_back("-lc_p");
+      else
+         CmdArgs.push_back("-lc");
+    }
     CmdArgs.push_back("-lgcc");
   }
=20
@@ -4062,11 +4898,9 @@
=20
   // When building 32-bit code on NetBSD/amd64, we have to explicitly
   // instruct as in the base system to assemble 32-bit code.
-  if (ToolTriple.getArch() =3D=3D llvm::Triple::x86_64 &&
-      getToolChain().getArch() =3D=3D llvm::Triple::x86)
+  if (getToolChain().getArch() =3D=3D llvm::Triple::x86)
     CmdArgs.push_back("--32");
=20
-
   // Set byte order explicitly
   if (getToolChain().getArchName() =3D=3D "mips")
     CmdArgs.push_back("-EB");
@@ -4116,8 +4950,7 @@
=20
   // When building 32-bit code on NetBSD/amd64, we have to explicitly
   // instruct ld in the base system to link 32-bit code.
-  if (ToolTriple.getArch() =3D=3D llvm::Triple::x86_64 &&
-      getToolChain().getArch() =3D=3D llvm::Triple::x86) {
+  if (getToolChain().getArch() =3D=3D llvm::Triple::x86) {
     CmdArgs.push_back("-m");
     CmdArgs.push_back("elf_i386");
   }
@@ -4218,11 +5051,48 @@
     CmdArgs.push_back("--32");
   } else if (getToolChain().getArch() =3D=3D llvm::Triple::x86_64) {
     CmdArgs.push_back("--64");
+  } else if (getToolChain().getArch() =3D=3D llvm::Triple::ppc) {
+    CmdArgs.push_back("-a32");
+    CmdArgs.push_back("-mppc");
+    CmdArgs.push_back("-many");
+  } else if (getToolChain().getArch() =3D=3D llvm::Triple::ppc64) {
+    CmdArgs.push_back("-a64");
+    CmdArgs.push_back("-mppc64");
+    CmdArgs.push_back("-many");
   } else if (getToolChain().getArch() =3D=3D llvm::Triple::arm) {
     StringRef MArch =3D getToolChain().getArchName();
     if (MArch =3D=3D "armv7" || MArch =3D=3D "armv7a" || MArch =3D=3D "arm=
v7-a")
       CmdArgs.push_back("-mfpu=3Dneon");
-  }
+  } else if (getToolChain().getArch() =3D=3D llvm::Triple::mips ||
+             getToolChain().getArch() =3D=3D llvm::Triple::mipsel ||
+             getToolChain().getArch() =3D=3D llvm::Triple::mips64 ||
+             getToolChain().getArch() =3D=3D llvm::Triple::mips64el) {
+    StringRef CPUName;
+    StringRef ABIName;
+    getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName);
+
+    CmdArgs.push_back("-march");
+    CmdArgs.push_back(CPUName.data());
+
+    // Convert ABI name to the GNU tools acceptable variant.
+    if (ABIName =3D=3D "o32")
+      ABIName =3D "32";
+    else if (ABIName =3D=3D "n64")
+      ABIName =3D "64";
+
+    CmdArgs.push_back("-mabi");
+    CmdArgs.push_back(ABIName.data());
+
+    if (getToolChain().getArch() =3D=3D llvm::Triple::mips ||
+        getToolChain().getArch() =3D=3D llvm::Triple::mips64)
+      CmdArgs.push_back("-EB");
+    else
+      CmdArgs.push_back("-EL");
+  }
+
+  Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
+  Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
=20
   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
                        options::OPT_Xassembler);
@@ -4241,6 +5111,30 @@
   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
 }
=20
+static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs,
+                      const ArgList &Args) {
+  bool StaticLibgcc =3D Args.hasArg(options::OPT_static) ||
+    Args.hasArg(options::OPT_static_libgcc);
+  if (!D.CCCIsCXX)
+    CmdArgs.push_back("-lgcc");
+
+  if (StaticLibgcc) {
+    if (D.CCCIsCXX)
+      CmdArgs.push_back("-lgcc");
+  } else {
+    if (!D.CCCIsCXX)
+      CmdArgs.push_back("--as-needed");
+    CmdArgs.push_back("-lgcc_s");
+    if (!D.CCCIsCXX)
+      CmdArgs.push_back("--no-as-needed");
+  }
+
+  if (StaticLibgcc)
+    CmdArgs.push_back("-lgcc_eh");
+  else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
+    CmdArgs.push_back("-lgcc");
+}
+
 void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA,
                                     const InputInfo &Output,
                                     const InputInfoList &Inputs,
@@ -4290,6 +5184,14 @@
     CmdArgs.push_back("elf32ppclinux");
   else if (ToolChain.getArch() =3D=3D llvm::Triple::ppc64)
     CmdArgs.push_back("elf64ppc");
+  else if (ToolChain.getArch() =3D=3D llvm::Triple::mips)
+    CmdArgs.push_back("elf32btsmip");
+  else if (ToolChain.getArch() =3D=3D llvm::Triple::mipsel)
+    CmdArgs.push_back("elf32ltsmip");
+  else if (ToolChain.getArch() =3D=3D llvm::Triple::mips64)
+    CmdArgs.push_back("elf64btsmip");
+  else if (ToolChain.getArch() =3D=3D llvm::Triple::mips64el)
+    CmdArgs.push_back("elf64ltsmip");
   else
     CmdArgs.push_back("elf_x86_64");
=20
@@ -4313,6 +5215,12 @@
     else if (ToolChain.getArch() =3D=3D llvm::Triple::arm ||
              ToolChain.getArch() =3D=3D llvm::Triple::thumb)
       CmdArgs.push_back("/lib/ld-linux.so.3");
+    else if (ToolChain.getArch() =3D=3D llvm::Triple::mips ||
+             ToolChain.getArch() =3D=3D llvm::Triple::mipsel)
+      CmdArgs.push_back("/lib/ld.so.1");
+    else if (ToolChain.getArch() =3D=3D llvm::Triple::mips64 ||
+             ToolChain.getArch() =3D=3D llvm::Triple::mips64el)
+      CmdArgs.push_back("/lib64/ld.so.1");
     else if (ToolChain.getArch() =3D=3D llvm::Triple::ppc)
       CmdArgs.push_back("/lib/ld.so.1");
     else if (ToolChain.getArch() =3D=3D llvm::Triple::ppc64)
@@ -4356,35 +5264,36 @@
        i !=3D e; ++i)
     CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i));
=20
+  // Tell the linker to load the plugin. This has to come before AddLinker=
Inputs
+  // as gold requires -plugin to come before any -plugin-opt that -Wl might
+  // forward.
+  if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) {
+    CmdArgs.push_back("-plugin");
+    std::string Plugin =3D ToolChain.getDriver().Dir + "/../lib/LLVMgold.s=
o";
+    CmdArgs.push_back(Args.MakeArgString(Plugin));
+  }
+
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
=20
   if (D.CCCIsCXX && !Args.hasArg(options::OPT_nostdlib)) {
+    bool OnlyLibstdcxxStatic =3D Args.hasArg(options::OPT_static_libstdcxx=
) &&
+      !Args.hasArg(options::OPT_static);
+    if (OnlyLibstdcxxStatic)
+      CmdArgs.push_back("-Bstatic");
     ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
+    if (OnlyLibstdcxxStatic)
+      CmdArgs.push_back("-Bdynamic");
     CmdArgs.push_back("-lm");
   }
=20
+  // Call this before we add the C run-time.
+  addAsanRTLinux(getToolChain(), Args, CmdArgs);
+
   if (!Args.hasArg(options::OPT_nostdlib)) {
     if (Args.hasArg(options::OPT_static))
       CmdArgs.push_back("--start-group");
=20
-    if (!D.CCCIsCXX)
-      CmdArgs.push_back("-lgcc");
-
-    if (Args.hasArg(options::OPT_static)) {
-      if (D.CCCIsCXX)
-        CmdArgs.push_back("-lgcc");
-    } else {
-      if (!D.CCCIsCXX)
-        CmdArgs.push_back("--as-needed");
-      CmdArgs.push_back("-lgcc_s");
-      if (!D.CCCIsCXX)
-        CmdArgs.push_back("--no-as-needed");
-    }
-
-    if (Args.hasArg(options::OPT_static))
-      CmdArgs.push_back("-lgcc_eh");
-    else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
-      CmdArgs.push_back("-lgcc");
+    AddLibgcc(D, CmdArgs, Args);
=20
     if (Args.hasArg(options::OPT_pthread) ||
         Args.hasArg(options::OPT_pthreads))
@@ -4394,19 +5303,8 @@
=20
     if (Args.hasArg(options::OPT_static))
       CmdArgs.push_back("--end-group");
-    else {
-      if (!D.CCCIsCXX)
-        CmdArgs.push_back("-lgcc");
-
-      if (!D.CCCIsCXX)
-        CmdArgs.push_back("--as-needed");
-      CmdArgs.push_back("-lgcc_s");
-      if (!D.CCCIsCXX)
-        CmdArgs.push_back("--no-as-needed");
-
-      if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX)
-        CmdArgs.push_back("-lgcc");
-    }
+    else
+      AddLibgcc(D, CmdArgs, Args);
=20
=20
     if (!Args.hasArg(options::OPT_nostartfiles)) {
@@ -4423,12 +5321,6 @@
=20
   addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
=20
-  if (Args.hasArg(options::OPT_use_gold_plugin)) {
-    CmdArgs.push_back("-plugin");
-    std::string Plugin =3D ToolChain.getDriver().Dir + "/../lib/LLVMgold.s=
o";
-    CmdArgs.push_back(Args.MakeArgString(Plugin));
-  }
-
   C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs));
 }
=20
@@ -4452,7 +5344,7 @@
   }
=20
   const char *Exec =3D
-    Args.MakeArgString(getToolChain().GetProgramPath("gas"));
+    Args.MakeArgString(getToolChain().GetProgramPath("as"));
   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
 }
=20
@@ -4472,9 +5364,12 @@
   }
=20
   if (!Args.hasArg(options::OPT_nostdlib) &&
-      !Args.hasArg(options::OPT_nostartfiles))
-    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
-                                                      "/usr/gnu/lib/crtso.=
o")));
+      !Args.hasArg(options::OPT_nostartfiles)) {
+      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt=
1.o")));
+      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt=
i.o")));
+      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt=
begin.o")));
+      CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt=
n.o")));
+  }
=20
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
@@ -4482,33 +5377,28 @@
=20
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
=20
+  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
+
   if (!Args.hasArg(options::OPT_nostdlib) &&
       !Args.hasArg(options::OPT_nodefaultlibs)) {
     if (D.CCCIsCXX) {
       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
       CmdArgs.push_back("-lm");
     }
-
+  }
+
+  if (!Args.hasArg(options::OPT_nostdlib) &&
+      !Args.hasArg(options::OPT_nostartfiles)) {
     if (Args.hasArg(options::OPT_pthread))
       CmdArgs.push_back("-lpthread");
     CmdArgs.push_back("-lc");
-    CmdArgs.push_back("-lgcc");
-    CmdArgs.push_back("-L/usr/gnu/lib");
-    // FIXME: fill in the correct search path for the final
-    // support libraries.
-    CmdArgs.push_back("-L/usr/gnu/lib/gcc/i686-pc-minix/4.4.3");
-  }
-
-  if (!Args.hasArg(options::OPT_nostdlib) &&
-      !Args.hasArg(options::OPT_nostartfiles)) {
-    CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath(
-                                              "/usr/gnu/lib/libend.a")));
-  }
-
-  addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
-
-  const char *Exec =3D
-    Args.MakeArgString(getToolChain().GetProgramPath("/usr/gnu/bin/gld"));
+    CmdArgs.push_back("-lCompilerRT-Generic");
+    CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
+    CmdArgs.push_back(
+	 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
+  }
+
+  const char *Exec =3D Args.MakeArgString(getToolChain().GetProgramPath("l=
d"));
   C.addCommand(new Command(JA, *this, Exec, CmdArgs));
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Tools.h
--- a/head/contrib/llvm/tools/clang/lib/Driver/Tools.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Tools.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -29,7 +29,8 @@
=20
   /// \brief Clang compiler tool.
   class LLVM_LIBRARY_VISIBILITY Clang : public Tool {
-    void AddPreprocessingOptions(const Driver &D,
+    void AddPreprocessingOptions(Compilation &C,
+                                 const Driver &D,
                                  const ArgList &Args,
                                  ArgStringList &CmdArgs,
                                  const InputInfo &Output,
@@ -40,6 +41,7 @@
     void AddMIPSTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) co=
nst;
     void AddSparcTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) c=
onst;
     void AddX86TargetArgs(const ArgList &Args, ArgStringList &CmdArgs) con=
st;
+    void AddHexagonTargetArgs (const ArgList &Args, ArgStringList &CmdArgs=
) const;
=20
   public:
     Clang(const ToolChain &TC) : Tool("clang", "clang frontend", TC) {}
@@ -57,6 +59,7 @@
=20
   /// \brief Clang integrated assembler tool.
   class LLVM_LIBRARY_VISIBILITY ClangAs : public Tool {
+    void AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) con=
st;
   public:
     ClangAs(const ToolChain &TC) : Tool("clang::as",
                                         "clang integrated assembler", TC) =
{}
@@ -145,14 +148,54 @@
                                        "linker (via gcc)", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void RenderExtraToolArgs(const JobAction &JA,
                                      ArgStringList &CmdArgs) const;
   };
 } // end namespace gcc
=20
+namespace hexagon {
+  // For Hexagon, we do not need to instantiate tools for PreProcess, PreC=
ompile and Compile.
+  // We simply use "clang -cc1" for those actions.
+  class LLVM_LIBRARY_VISIBILITY Assemble : public Tool {
+  public:
+    Assemble(const ToolChain &TC) : Tool("hexagon::Assemble",
+      "hexagon-as", TC) {}
+
+    virtual bool hasIntegratedCPP() const { return false; }
+
+    virtual void RenderExtraToolArgs(const JobAction &JA,
+                                     ArgStringList &CmdArgs) const;
+    virtual void ConstructJob(Compilation &C, const JobAction &JA,
+                              const InputInfo &Output,
+                              const InputInfoList &Inputs,
+                              const ArgList &TCArgs,
+                              const char *LinkingOutput) const;
+  };
+
+  class LLVM_LIBRARY_VISIBILITY Link : public Tool {
+  public:
+    Link(const ToolChain &TC) : Tool("hexagon::Link",
+      "hexagon-ld", TC) {}
+
+    virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
+
+    virtual void RenderExtraToolArgs(const JobAction &JA,
+                                     ArgStringList &CmdArgs) const;
+    virtual void ConstructJob(Compilation &C, const JobAction &JA,
+                              const InputInfo &Output,
+                              const InputInfoList &Inputs,
+                              const ArgList &TCArgs,
+                              const char *LinkingOutput) const;
+  };
+} // end namespace hexagon.
+
+
 namespace darwin {
   class LLVM_LIBRARY_VISIBILITY DarwinTool : public Tool {
+    virtual void anchor();
   protected:
     void AddDarwinArch(const ArgList &Args, ArgStringList &CmdArgs) const;
=20
@@ -166,6 +209,7 @@
   };
=20
   class LLVM_LIBRARY_VISIBILITY CC1 : public DarwinTool  {
+    virtual void anchor();
   public:
     static const char *getBaseInputName(const ArgList &Args,
                                  const InputInfoList &Input);
@@ -243,6 +287,7 @@
     Link(const ToolChain &TC) : DarwinTool("darwin::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -314,6 +359,7 @@
     Link(const ToolChain &TC) : Tool("openbsd::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -343,6 +389,7 @@
     Link(const ToolChain &TC) : Tool("freebsd::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -355,12 +402,10 @@
   /// netbsd -- Directly call GNU Binutils assembler and linker
 namespace netbsd {
   class LLVM_LIBRARY_VISIBILITY Assemble : public Tool  {
-  private:
-    const llvm::Triple ToolTriple;
=20
   public:
-    Assemble(const ToolChain &TC, const llvm::Triple &ToolTriple)
-      : Tool("netbsd::Assemble", "assembler", TC), ToolTriple(ToolTriple) =
{}
+    Assemble(const ToolChain &TC)
+      : Tool("netbsd::Assemble", "assembler", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
=20
@@ -371,14 +416,13 @@
                               const char *LinkingOutput) const;
   };
   class LLVM_LIBRARY_VISIBILITY Link : public Tool  {
-  private:
-    const llvm::Triple ToolTriple;
=20
   public:
-    Link(const ToolChain &TC, const llvm::Triple &ToolTriple)
-      : Tool("netbsd::Link", "linker", TC), ToolTriple(ToolTriple) {}
+    Link(const ToolChain &TC)
+      : Tool("netbsd::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -408,6 +452,7 @@
     Link(const ToolChain &TC) : Tool("linux::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -436,6 +481,7 @@
     Link(const ToolChain &TC) : Tool("minix::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -445,6 +491,36 @@
   };
 } // end namespace minix
=20
+  /// solaris -- Directly call Solaris assembler and linker
+namespace solaris {
+  class LLVM_LIBRARY_VISIBILITY Assemble : public Tool  {
+  public:
+    Assemble(const ToolChain &TC) : Tool("solaris::Assemble", "assembler",
+                                         TC) {}
+
+    virtual bool hasIntegratedCPP() const { return false; }
+
+    virtual void ConstructJob(Compilation &C, const JobAction &JA,
+                              const InputInfo &Output,
+                              const InputInfoList &Inputs,
+                              const ArgList &TCArgs,
+                              const char *LinkingOutput) const;
+  };
+  class LLVM_LIBRARY_VISIBILITY Link : public Tool  {
+  public:
+    Link(const ToolChain &TC) : Tool("solaris::Link", "linker", TC) {}
+
+    virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
+
+    virtual void ConstructJob(Compilation &C, const JobAction &JA,
+                              const InputInfo &Output,
+                              const InputInfoList &Inputs,
+                              const ArgList &TCArgs,
+                              const char *LinkingOutput) const;
+  };
+} // end namespace solaris
+
   /// auroraux -- Directly call GNU Binutils assembler and linker
 namespace auroraux {
   class LLVM_LIBRARY_VISIBILITY Assemble : public Tool  {
@@ -465,6 +541,7 @@
     Link(const ToolChain &TC) : Tool("auroraux::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -494,6 +571,7 @@
     Link(const ToolChain &TC) : Tool("dragonfly::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
@@ -510,6 +588,7 @@
     Link(const ToolChain &TC) : Tool("visualstudio::Link", "linker", TC) {}
=20
     virtual bool hasIntegratedCPP() const { return false; }
+    virtual bool isLinkJob() const { return true; }
=20
     virtual void ConstructJob(Compilation &C, const JobAction &JA,
                               const InputInfo &Output,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Driv=
er/Types.cpp
--- a/head/contrib/llvm/tools/clang/lib/Driver/Types.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Driver/Types.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -102,6 +102,7 @@
   case TY_LLVM_IR:
   case TY_LLVM_BC:
   case TY_RewrittenObjC:
+  case TY_RewrittenLegacyObjC:
     return true;
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/ASTConsumers.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/ASTConsumers.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/ASTConsumers.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -66,9 +66,10 @@
       this->Context =3D &Context;
     }
=20
-    virtual void HandleTopLevelDecl(DeclGroupRef D) {
+    virtual bool HandleTopLevelDecl(DeclGroupRef D) {
       for (DeclGroupRef::iterator I =3D D.begin(), E =3D D.end(); I !=3D E=
; ++I)
         HandleTopLevelSingleDecl(*I);
+      return true;
     }
=20
     void HandleTopLevelSingleDecl(Decl *D);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/ASTMerge.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/ASTMerge.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -26,8 +26,7 @@
   // FIXME: This is a hack. We need a better way to communicate the
   // AST file, compiler instance, and file name than member variables
   // of FrontendAction.
-  AdaptedAction->setCurrentFile(getCurrentFile(), getCurrentFileKind(),
-                                takeCurrentASTUnit());
+  AdaptedAction->setCurrentInput(getCurrentInput(), takeCurrentASTUnit());
   AdaptedAction->setCompilerInstance(&CI);
   return AdaptedAction->BeginSourceFileAction(CI, Filename);
 }
@@ -35,13 +34,13 @@
 void ASTMergeAction::ExecuteAction() {
   CompilerInstance &CI =3D getCompilerInstance();
   CI.getDiagnostics().getClient()->BeginSourceFile(
-                                         CI.getASTContext().getLangOptions=
());
+                                         CI.getASTContext().getLangOpts());
   CI.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
                                        &CI.getASTContext());
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs>
+  IntrusiveRefCntPtr<DiagnosticIDs>
       DiagIDs(CI.getDiagnostics().getDiagnosticIDs());
   for (unsigned I =3D 0, N =3D ASTFiles.size(); I !=3D N; ++I) {
-    llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
+    IntrusiveRefCntPtr<DiagnosticsEngine>
         Diags(new DiagnosticsEngine(DiagIDs, CI.getDiagnostics().getClient=
(),
                              /*ShouldOwnClient=3D*/false));
     ASTUnit *Unit =3D ASTUnit::LoadFromASTFile(ASTFiles[I], Diags,
@@ -80,8 +79,8 @@
 }
=20
 ASTMergeAction::ASTMergeAction(FrontendAction *AdaptedAction,
-                               std::string *ASTFiles, unsigned NumASTFiles)
-  : AdaptedAction(AdaptedAction), ASTFiles(ASTFiles, ASTFiles + NumASTFile=
s) {
+                               ArrayRef<std::string> ASTFiles)
+  : AdaptedAction(AdaptedAction), ASTFiles(ASTFiles.begin(), ASTFiles.end(=
)) {
   assert(AdaptedAction && "ASTMergeAction needs an action to adapt");
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/ASTUnit.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -27,6 +27,7 @@
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/FrontendOptions.h"
+#include "clang/Frontend/MultiplexConsumer.h"
 #include "clang/Frontend/Utils.h"
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/ASTWriter.h"
@@ -46,6 +47,7 @@
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Mutex.h"
+#include "llvm/Support/MutexGuard.h"
 #include "llvm/Support/CrashRecoveryContext.h"
 #include <cstdlib>
 #include <cstdio>
@@ -81,6 +83,121 @@
       }
     }
   };
+ =20
+  struct OnDiskData {
+    /// \brief The file in which the precompiled preamble is stored.
+    std::string PreambleFile;
+
+    /// \brief Temporary files that should be removed when the ASTUnit is=20
+    /// destroyed.
+    SmallVector<llvm::sys::Path, 4> TemporaryFiles;
+   =20
+    /// \brief Erase temporary files.
+    void CleanTemporaryFiles();
+
+    /// \brief Erase the preamble file.
+    void CleanPreambleFile();
+
+    /// \brief Erase temporary files and the preamble file.
+    void Cleanup();
+  };
+}
+
+static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
+  static llvm::sys::SmartMutex<false> M(/* recursive =3D */ true);
+  return M;
+}
+
+static void cleanupOnDiskMapAtExit(void);
+
+typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
+static OnDiskDataMap &getOnDiskDataMap() {
+  static OnDiskDataMap M;
+  static bool hasRegisteredAtExit =3D false;
+  if (!hasRegisteredAtExit) {
+    hasRegisteredAtExit =3D true;
+    atexit(cleanupOnDiskMapAtExit);
+  }
+  return M;
+}
+
+static void cleanupOnDiskMapAtExit(void) {
+  // No mutex required here since we are leaving the program.
+  OnDiskDataMap &M =3D getOnDiskDataMap();
+  for (OnDiskDataMap::iterator I =3D M.begin(), E =3D M.end(); I !=3D E; +=
+I) {
+    // We don't worry about freeing the memory associated with OnDiskDataM=
ap.
+    // All we care about is erasing stale files.
+    I->second->Cleanup();
+  }
+}
+
+static OnDiskData &getOnDiskData(const ASTUnit *AU) {
+  // We require the mutex since we are modifying the structure of the
+  // DenseMap.
+  llvm::MutexGuard Guard(getOnDiskMutex());
+  OnDiskDataMap &M =3D getOnDiskDataMap();
+  OnDiskData *&D =3D M[AU];
+  if (!D)
+    D =3D new OnDiskData();
+  return *D;
+}
+
+static void erasePreambleFile(const ASTUnit *AU) {
+  getOnDiskData(AU).CleanPreambleFile();
+}
+
+static void removeOnDiskEntry(const ASTUnit *AU) {
+  // We require the mutex since we are modifying the structure of the
+  // DenseMap.
+  llvm::MutexGuard Guard(getOnDiskMutex());
+  OnDiskDataMap &M =3D getOnDiskDataMap();
+  OnDiskDataMap::iterator I =3D M.find(AU);
+  if (I !=3D M.end()) {
+    I->second->Cleanup();
+    delete I->second;
+    M.erase(AU);
+  }
+}
+
+static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFil=
e) {
+  getOnDiskData(AU).PreambleFile =3D preambleFile;
+}
+
+static const std::string &getPreambleFile(const ASTUnit *AU) {
+  return getOnDiskData(AU).PreambleFile; =20
+}
+
+void OnDiskData::CleanTemporaryFiles() {
+  for (unsigned I =3D 0, N =3D TemporaryFiles.size(); I !=3D N; ++I)
+    TemporaryFiles[I].eraseFromDisk();
+  TemporaryFiles.clear();=20
+}
+
+void OnDiskData::CleanPreambleFile() {
+  if (!PreambleFile.empty()) {
+    llvm::sys::Path(PreambleFile).eraseFromDisk();
+    PreambleFile.clear();
+  }
+}
+
+void OnDiskData::Cleanup() {
+  CleanTemporaryFiles();
+  CleanPreambleFile();
+}
+
+void ASTUnit::clearFileLevelDecls() {
+  for (FileDeclsTy::iterator
+         I =3D FileDecls.begin(), E =3D FileDecls.end(); I !=3D E; ++I)
+    delete I->second;
+  FileDecls.clear();
+}
+
+void ASTUnit::CleanTemporaryFiles() {
+  getOnDiskData(this).CleanTemporaryFiles();
+}
+
+void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
+  getOnDiskData(this).TemporaryFiles.push_back(TempFile);
 }
=20
 /// \brief After failing to build a precompiled preamble (due to
@@ -95,14 +212,14 @@
 static llvm::sys::cas_flag ActiveASTUnitObjects;
=20
 ASTUnit::ASTUnit(bool _MainFileIsAST)
-  : OnlyLocalDecls(false), CaptureDiagnostics(false),
+  : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
     MainFileIsAST(_MainFileIsAST),=20
     TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
     OwnsRemappedFileBuffers(true),
     NumStoredDiagnosticsFromDriver(0),
     PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
+    NumWarningsInPreamble(0),
     ShouldCacheCodeCompletionResults(false),
-    NestedMacroExpansions(true),
     CompletionCacheTopLevelHashValue(0),
     PreambleTopLevelHashValue(0),
     CurrentTopLevelHashValue(0),
@@ -114,10 +231,11 @@
 }
=20
 ASTUnit::~ASTUnit() {
-  CleanTemporaryFiles();
-  if (!PreambleFile.empty())
-    llvm::sys::Path(PreambleFile).eraseFromDisk();
- =20
+  clearFileLevelDecls();
+
+  // Clean up the temporary files and the preamble file.
+  removeOnDiskEntry(this);
+
   // Free the buffers associated with remapped files. We are required to
   // perform this operation here because we explicitly request that the
   // compiler instance *not* free these buffers for each invocation of the
@@ -143,11 +261,7 @@
   }   =20
 }
=20
-void ASTUnit::CleanTemporaryFiles() {
-  for (unsigned I =3D 0, N =3D TemporaryFiles.size(); I !=3D N; ++I)
-    TemporaryFiles[I].eraseFromDisk();
-  TemporaryFiles.clear();
-}
+void ASTUnit::setPreprocessor(Preprocessor *pp) { PP =3D pp; }
=20
 /// \brief Determine the set of code-completion contexts in which this=20
 /// declaration should be shown.
@@ -237,7 +351,8 @@
   typedef CodeCompletionResult Result;
   SmallVector<Result, 8> Results;
   CachedCompletionAllocator =3D new GlobalCodeCompletionAllocator;
-  TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results=
);
+  TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
+                                       getCodeCompletionTUInfo(), Results);
  =20
   // Translate global code completions into cached completions.
   llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
@@ -248,9 +363,10 @@
       bool IsNestedNameSpecifier =3D false;
       CachedCodeCompletionResult CachedResult;
       CachedResult.Completion =3D Results[I].CreateCodeCompletionString(*T=
heSema,
-                                                    *CachedCompletionAlloc=
ator);
+                                                    *CachedCompletionAlloc=
ator,
+                                                    getCodeCompletionTUInf=
o());
       CachedResult.ShowInContexts =3D getDeclShowContexts(Results[I].Decla=
ration,
-                                                        Ctx->getLangOption=
s(),
+                                                        Ctx->getLangOpts(),
                                                         IsNestedNameSpecif=
ier);
       CachedResult.Priority =3D Results[I].Priority;
       CachedResult.Kind =3D Results[I].CursorKind;
@@ -283,7 +399,7 @@
       CachedCompletionResults.push_back(CachedResult);
      =20
       /// Handle nested-name-specifiers in C++.
-      if (TheSema->Context.getLangOptions().CPlusPlus &&=20
+      if (TheSema->Context.getLangOpts().CPlusPlus &&=20
           IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
         // The contexts in which a nested-name-specifier can appear in C++.
         unsigned NNSContexts
@@ -312,7 +428,8 @@
           Results[I].StartsNestedNameSpecifier =3D true;
           CachedResult.Completion=20
             =3D Results[I].CreateCodeCompletionString(*TheSema,
-                                                    *CachedCompletionAlloc=
ator);
+                                                    *CachedCompletionAlloc=
ator,
+                                                    getCodeCompletionTUInf=
o());
           CachedResult.ShowInContexts =3D RemainingContexts;
           CachedResult.Priority =3D CCP_NestedNameSpecifier;
           CachedResult.TypeClass =3D STC_Void;
@@ -333,7 +450,8 @@
       CachedCodeCompletionResult CachedResult;
       CachedResult.Completion=20
         =3D Results[I].CreateCodeCompletionString(*TheSema,
-                                                *CachedCompletionAllocator=
);
+                                                *CachedCompletionAllocator,
+                                                getCodeCompletionTUInfo());
       CachedResult.ShowInContexts
         =3D (1 << (CodeCompletionContext::CCC_TopLevel - 1))
         | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
@@ -378,7 +496,7 @@
   ASTContext &Context;
   LangOptions &LangOpt;
   HeaderSearch &HSI;
-  llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
+  IntrusiveRefCntPtr<TargetInfo> &Target;
   std::string &Predefines;
   unsigned &Counter;
=20
@@ -388,7 +506,7 @@
 public:
   ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &Lan=
gOpt,=20
                    HeaderSearch &HSI,
-                   llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
+                   IntrusiveRefCntPtr<TargetInfo> &Target,
                    std::string &Predefines,
                    unsigned &Counter)
     : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
@@ -461,6 +579,9 @@
   DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
     // Just drop any diagnostics that come from cloned consumers; they'll
     // have different source managers anyway.
+    // FIXME: We'd like to be able to capture these somehow, even if it's =
just
+    // file/line/column, because they could occur when parsing module maps=
 or
+    // building modules on-demand.
     return new IgnoringDiagConsumer();
   }
 };
@@ -512,7 +633,7 @@
 }
=20
 /// \brief Configure the diagnostics object for use with ASTUnit.
-void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &=
Diags,
+void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
                              const char **ArgBegin, const char **ArgEnd,
                              ASTUnit &AST, bool CaptureDiagnostics) {
   if (!Diags.getPtr()) {
@@ -530,13 +651,14 @@
 }
=20
 ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
-                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
+                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
                                   const FileSystemOptions &FileSystemOpts,
                                   bool OnlyLocalDecls,
                                   RemappedFile *RemappedFiles,
                                   unsigned NumRemappedFiles,
-                                  bool CaptureDiagnostics) {
-  llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
+                                  bool CaptureDiagnostics,
+                                  bool AllowPCHWithCompilerErrors) {
+  OwningPtr<ASTUnit> AST(new ASTUnit(true));
=20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
@@ -553,7 +675,10 @@
   AST->FileMgr =3D new FileManager(FileSystemOpts);
   AST->SourceMgr =3D new SourceManager(AST->getDiagnostics(),
                                      AST->getFileManager());
-  AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
+  AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
+                                         AST->getDiagnostics(),
+                                         AST->ASTFileLangOpts,
+                                         /*Target=3D*/0));
  =20
   for (unsigned I =3D 0; I !=3D NumRemappedFiles; ++I) {
     FilenameOrMemBuf fileOrBuf =3D RemappedFiles[I].second;
@@ -608,7 +733,7 @@
   std::string Predefines;
   unsigned Counter;
=20
-  llvm::OwningPtr<ASTReader> Reader;
+  OwningPtr<ASTReader> Reader;
=20
   AST->PP =3D new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts=
,=20
                              /*Target=3D*/0, AST->getSourceManager(), Head=
erInfo,=20
@@ -628,7 +753,11 @@
                             /*DelayInitialization=3D*/true);
   ASTContext &Context =3D *AST->Ctx;
=20
-  Reader.reset(new ASTReader(PP, Context));
+  Reader.reset(new ASTReader(PP, Context,
+                             /*isysroot=3D*/"",
+                             /*DisableValidation=3D*/false,
+                             /*DisableStatCache=3D*/false,
+                             AllowPCHWithCompilerErrors));
  =20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
@@ -657,7 +786,7 @@
   // source, so that declarations will be deserialized from the
   // AST file as needed.
   ASTReader *ReaderPtr =3D Reader.get();
-  llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
+  OwningPtr<ExternalASTSource> Source(Reader.take());
=20
   // Unregister the cleanup for ASTReader.  It will get cleaned up
   // by the ASTUnit cleanup.
@@ -672,6 +801,7 @@
   AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
   AST->TheSema->Initialize();
   ReaderPtr->InitializeSema(*AST->TheSema);
+  AST->Reader =3D ReaderPtr;
=20
   return AST.take();
 }
@@ -711,22 +841,7 @@
       Hash =3D llvm::HashString(NameStr, Hash);
     }
     return;
-  }
- =20
-  if (ObjCForwardProtocolDecl *Forward=20
-      =3D dyn_cast<ObjCForwardProtocolDecl>(D)) {
-    for (ObjCForwardProtocolDecl::protocol_iterator=20
-         P =3D Forward->protocol_begin(),
-         PEnd =3D Forward->protocol_end();
-         P !=3D PEnd; ++P)
-      AddTopLevelDeclarationToHash(*P, Hash);
-    return;
-  }
- =20
-  if (ObjCClassDecl *Class =3D dyn_cast<ObjCClassDecl>(D)) {
-    AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
-    return;
-  }
+  } =20
 }
=20
 class TopLevelDeclTrackerConsumer : public ASTConsumer {
@@ -738,24 +853,46 @@
     : Unit(_Unit), Hash(Hash) {
     Hash =3D 0;
   }
- =20
-  void HandleTopLevelDecl(DeclGroupRef D) {
-    for (DeclGroupRef::iterator it =3D D.begin(), ie =3D D.end(); it !=3D =
ie; ++it) {
-      Decl *D =3D *it;
-      // FIXME: Currently ObjC method declarations are incorrectly being
-      // reported as top-level declarations, even though their DeclContext
-      // is the containing ObjC @interface/@implementation.  This is a
-      // fundamental problem in the parser right now.
-      if (isa<ObjCMethodDecl>(D))
-        continue;
=20
-      AddTopLevelDeclarationToHash(D, Hash);
-      Unit.addTopLevelDecl(D);
+  void handleTopLevelDecl(Decl *D) {
+    if (!D)
+      return;
+
+    // FIXME: Currently ObjC method declarations are incorrectly being
+    // reported as top-level declarations, even though their DeclContext
+    // is the containing ObjC @interface/@implementation.  This is a
+    // fundamental problem in the parser right now.
+    if (isa<ObjCMethodDecl>(D))
+      return;
+
+    AddTopLevelDeclarationToHash(D, Hash);
+    Unit.addTopLevelDecl(D);
+
+    handleFileLevelDecl(D);
+  }
+
+  void handleFileLevelDecl(Decl *D) {
+    Unit.addFileLevelDecl(D);
+    if (NamespaceDecl *NSD =3D dyn_cast<NamespaceDecl>(D)) {
+      for (NamespaceDecl::decl_iterator
+             I =3D NSD->decls_begin(), E =3D NSD->decls_end(); I !=3D E; +=
+I)
+        handleFileLevelDecl(*I);
     }
   }
=20
+  bool HandleTopLevelDecl(DeclGroupRef D) {
+    for (DeclGroupRef::iterator it =3D D.begin(), ie =3D D.end(); it !=3D =
ie; ++it)
+      handleTopLevelDecl(*it);
+    return true;
+  }
+
   // We're not interested in "interesting" decls.
   void HandleInterestingDecl(DeclGroupRef) {}
+
+  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
+    for (DeclGroupRef::iterator it =3D D.begin(), ie =3D D.end(); it !=3D =
ie; ++it)
+      handleTopLevelDecl(*it);
+  }
 };
=20
 class TopLevelDeclTrackerAction : public ASTFrontendAction {
@@ -787,12 +924,12 @@
 public:
   PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,=20
                              StringRef isysroot, raw_ostream *Out)
-    : PCHGenerator(PP, "", /*IsModule=3D*/false, isysroot, Out), Unit(Unit=
),
+    : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
       Hash(Unit.getCurrentTopLevelHashValue()) {
     Hash =3D 0;
   }
=20
-  virtual void HandleTopLevelDecl(DeclGroupRef D) {
+  virtual bool HandleTopLevelDecl(DeclGroupRef D) {
     for (DeclGroupRef::iterator it =3D D.begin(), ie =3D D.end(); it !=3D =
ie; ++it) {
       Decl *D =3D *it;
       // FIXME: Currently ObjC method declarations are incorrectly being
@@ -804,6 +941,7 @@
       AddTopLevelDeclarationToHash(D, Hash);
       TopLevelDecls.push_back(D);
     }
+    return true;
   }
=20
   virtual void HandleTranslationUnit(ASTContext &Ctx) {
@@ -852,6 +990,34 @@
=20
 }
=20
+static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic>=
 &
+                                                            StoredDiagnost=
ics) {
+  // Get rid of stored diagnostics except the ones from the driver which d=
o not
+  // have a source location.
+  for (unsigned I =3D 0; I < StoredDiagnostics.size(); ++I) {
+    if (StoredDiagnostics[I].getLocation().isValid()) {
+      StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
+      --I;
+    }
+  }
+}
+
+static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
+                                                              StoredDiagno=
stics,
+                                  SourceManager &SM) {
+  // The stored diagnostic has the old source manager in it; update
+  // the locations to refer into the new source manager. Since we've
+  // been careful to make sure that the source manager's state
+  // before and after are identical, so that we can reuse the source
+  // location itself.
+  for (unsigned I =3D 0, N =3D StoredDiagnostics.size(); I < N; ++I) {
+    if (StoredDiagnostics[I].getLocation().isValid()) {
+      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
+      StoredDiagnostics[I].setLocation(Loc);
+    }
+  }
+}
+
 /// Parse the source file into a translation unit using the given compiler
 /// invocation, replacing the current translation unit.
 ///
@@ -867,17 +1033,17 @@
   }
  =20
   // Create the compiler instance to use for building the AST.
-  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
+  OwningPtr<CompilerInstance> Clang(new CompilerInstance());
=20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
     CICleanup(Clang.get());
=20
-  llvm::IntrusiveRefCntPtr<CompilerInvocation>
+  IntrusiveRefCntPtr<CompilerInvocation>
     CCInvocation(new CompilerInvocation(*Invocation));
=20
   Clang->setInvocation(CCInvocation.getPtr());
-  OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].second;
+  OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].File;
    =20
   // Set up diagnostics, capturing any diagnostics that would
   // otherwise be dropped.
@@ -900,28 +1066,29 @@
  =20
   assert(Clang->getFrontendOpts().Inputs.size() =3D=3D 1 &&
          "Invocation must have exactly one source file!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_AST &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_AST &&
          "FIXME: AST inputs not yet supported here!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_LLVM_IR &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_LLVM_IR &&
          "IR inputs not support here!");
=20
   // Configure the various subsystems.
   // FIXME: Should we retain the previous file manager?
+  LangOpts =3D &Clang->getLangOpts();
   FileSystemOpts =3D Clang->getFileSystemOpts();
   FileMgr =3D new FileManager(FileSystemOpts);
   SourceMgr =3D new SourceManager(getDiagnostics(), *FileMgr);
   TheSema.reset();
   Ctx =3D 0;
   PP =3D 0;
+  Reader =3D 0;
  =20
   // Clear out old caches and data.
   TopLevelDecls.clear();
+  clearFileLevelDecls();
   CleanTemporaryFiles();
=20
   if (!OverrideMainBuffer) {
-    StoredDiagnostics.erase(
-                    StoredDiagnostics.begin() + NumStoredDiagnosticsFromDr=
iver,
-                            StoredDiagnostics.end());
+    checkAndRemoveNonDriverDiags(StoredDiagnostics);
     TopLevelDeclsInPreamble.clear();
   }
=20
@@ -934,14 +1101,12 @@
   // If the main file has been overridden due to the use of a preamble,
   // make that override happen and introduce the preamble.
   PreprocessorOptions &PreprocessorOpts =3D Clang->getPreprocessorOpts();
-  PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
-    =3D NestedMacroExpansions;
   if (OverrideMainBuffer) {
     PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffe=
r);
     PreprocessorOpts.PrecompiledPreambleBytes.first =3D Preamble.size();
     PreprocessorOpts.PrecompiledPreambleBytes.second
                                                     =3D PreambleEndsAtStar=
tOfLine;
-    PreprocessorOpts.ImplicitPCHInclude =3D PreambleFile;
+    PreprocessorOpts.ImplicitPCHInclude =3D getPreambleFile(this);
     PreprocessorOpts.DisablePCHValidation =3D true;
    =20
     // The stored diagnostic has the old source manager in it; update
@@ -949,49 +1114,37 @@
     // been careful to make sure that the source manager's state
     // before and after are identical, so that we can reuse the source
     // location itself.
-    for (unsigned I =3D NumStoredDiagnosticsFromDriver,=20
-                  N =3D StoredDiagnostics.size();=20
-         I < N; ++I) {
-      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
-                        getSourceManager());
-      StoredDiagnostics[I].setLocation(Loc);
-    }
+    checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
=20
     // Keep track of the override buffer;
     SavedMainFileBuffer =3D OverrideMainBuffer;
   }
  =20
-  llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
+  OwningPtr<TopLevelDeclTrackerAction> Act(
     new TopLevelDeclTrackerAction(*this));
    =20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
     ActCleanup(Act.get());
=20
-  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[=
0].second,
-                            Clang->getFrontendOpts().Inputs[0].first))
+  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[=
0]))
     goto error;
=20
   if (OverrideMainBuffer) {
-    std::string ModName =3D PreambleFile;
+    std::string ModName =3D getPreambleFile(this);
     TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
                                getSourceManager(), PreambleDiagnostics,
                                StoredDiagnostics);
   }
=20
   Act->Execute();
- =20
-  // Steal the created target, context, and preprocessor.
-  TheSema.reset(Clang->takeSema());
-  Consumer.reset(Clang->takeASTConsumer());
-  Ctx =3D &Clang->getASTContext();
-  PP =3D &Clang->getPreprocessor();
-  Clang->setSourceManager(0);
-  Clang->setFileManager(0);
-  Target =3D &Clang->getTarget();
+
+  transferASTDataFromCompilerInstance(*Clang);
  =20
   Act->EndSourceFile();
=20
+  FailedParseDiagnostics.clear();
+
   return false;
=20
 error:
@@ -1000,8 +1153,13 @@
     delete OverrideMainBuffer;
     SavedMainFileBuffer =3D 0;
   }
- =20
+
+  // Keep the ownership of the data in the ASTUnit because the client may
+  // want to see the diagnostics.
+  transferASTDataFromCompilerInstance(*Clang);
+  FailedParseDiagnostics.swap(StoredDiagnostics);
   StoredDiagnostics.clear();
+  NumStoredDiagnosticsFromDriver =3D 0;
   return true;
 }
=20
@@ -1053,7 +1211,7 @@
   // command line (to another file) or directly through the compiler invoc=
ation
   // (to a memory buffer).
   llvm::MemoryBuffer *Buffer =3D 0;
-  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
+  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
   if (const llvm::sys::FileStatus *MainFileStatus =3D MainFilePath.getFile=
Status()) {
     // Check whether there is a file-file remapping of the main file
     for (PreprocessorOptions::remapped_file_iterator
@@ -1103,7 +1261,7 @@
  =20
   // If the main source file was not remapped, load it now.
   if (!Buffer) {
-    Buffer =3D getBufferForFile(FrontendOpts.Inputs[0].second);
+    Buffer =3D getBufferForFile(FrontendOpts.Inputs[0].File);
     if (!Buffer)
       return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true=
));   =20
    =20
@@ -1111,7 +1269,7 @@
   }
  =20
   return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
-                                                       Invocation.getLangO=
pts(),
+                                                       *Invocation.getLang=
Opts(),
                                                        MaxLines));
 }
=20
@@ -1154,7 +1312,7 @@
                                                            bool AllowRebui=
ld,
                                                            unsigned MaxLin=
es) {
  =20
-  llvm::IntrusiveRefCntPtr<CompilerInvocation>
+  IntrusiveRefCntPtr<CompilerInvocation>
     PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
   FrontendOptions &FrontendOpts =3D PreambleInvocation->getFrontendOpts();
   PreprocessorOptions &PreprocessorOpts
@@ -1165,7 +1323,7 @@
     =3D ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuff=
er);
=20
   // If ComputePreamble() Take ownership of the preamble buffer.
-  llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
+  OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
   if (CreatedPreambleBuffer)
     OwnedPreambleBuffer.reset(NewPreamble.first);
=20
@@ -1173,10 +1331,7 @@
     // We couldn't find a preamble in the main source. Clear out the curre=
nt
     // preamble, if we have one. It's obviously no good any more.
     Preamble.clear();
-    if (!PreambleFile.empty()) {
-      llvm::sys::Path(PreambleFile).eraseFromDisk();
-      PreambleFile.clear();
-    }
+    erasePreambleFile(this);
=20
     // The next time we actually see a preamble, precompile it.
     PreambleRebuildCounter =3D 1;
@@ -1259,8 +1414,6 @@
=20
         // Set the state of the diagnostic object to mimic its state
         // after parsing the preamble.
-        // FIXME: This won't catch any #pragma push warning changes that
-        // have occurred in the preamble.
         getDiagnostics().Reset();
         ProcessWarningOptions(getDiagnostics(),=20
                               PreambleInvocation->getDiagnosticOpts());
@@ -1270,7 +1423,7 @@
         // buffer size we reserved when creating the preamble.
         return CreatePaddedMainFileBuffer(NewPreamble.first,=20
                                           PreambleReservedSize,
-                                          FrontendOpts.Inputs[0].second);
+                                          FrontendOpts.Inputs[0].File);
       }
     }
=20
@@ -1282,7 +1435,7 @@
     // We can't reuse the previously-computed preamble. Build a new one.
     Preamble.clear();
     PreambleDiagnostics.clear();
-    llvm::sys::Path(PreambleFile).eraseFromDisk();
+    erasePreambleFile(this);
     PreambleRebuildCounter =3D 1;
   } else if (!AllowRebuild) {
     // We aren't allowed to rebuild the precompiled preamble; just
@@ -1323,7 +1476,7 @@
=20
   // Save the preamble text for later; we'll need to compare against it for
   // subsequent reparses.
-  StringRef MainFilename =3D PreambleInvocation->getFrontendOpts().Inputs[=
0].second;
+  StringRef MainFilename =3D PreambleInvocation->getFrontendOpts().Inputs[=
0].File;
   Preamble.assign(FileMgr->getFile(MainFilename),
                   NewPreamble.first->getBufferStart(),=20
                   NewPreamble.first->getBufferStart()=20
@@ -1333,7 +1486,7 @@
   delete PreambleBuffer;
   PreambleBuffer
     =3D llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
-                                                FrontendOpts.Inputs[0].sec=
ond);
+                                                FrontendOpts.Inputs[0].Fil=
e);
   memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),=20
          NewPreamble.first->getBufferStart(), Preamble.size());
   memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.si=
ze(),=20
@@ -1341,7 +1494,7 @@
   const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] =3D '\n'; =20
  =20
   // Remap the main source file to the preamble buffer.
-  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
+  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].File);
   PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
  =20
   // Tell the compiler invocation to generate a temporary precompiled head=
er.
@@ -1352,14 +1505,14 @@
   PreprocessorOpts.PrecompiledPreambleBytes.second =3D false;
  =20
   // Create the compiler instance to use for building the precompiled prea=
mble.
-  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
+  OwningPtr<CompilerInstance> Clang(new CompilerInstance());
=20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
     CICleanup(Clang.get());
=20
   Clang->setInvocation(&*PreambleInvocation);
-  OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].second;
+  OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].File;
  =20
   // Set up diagnostics, capturing all of the diagnostics produced.
   Clang->setDiagnostics(&getDiagnostics());
@@ -1385,17 +1538,15 @@
  =20
   assert(Clang->getFrontendOpts().Inputs.size() =3D=3D 1 &&
          "Invocation must have exactly one source file!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_AST &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_AST &&
          "FIXME: AST inputs not yet supported here!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_LLVM_IR &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_LLVM_IR &&
          "IR inputs not support here!");
  =20
   // Clear out old caches and data.
   getDiagnostics().Reset();
   ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
-  StoredDiagnostics.erase(
-                    StoredDiagnostics.begin() + NumStoredDiagnosticsFromDr=
iver,
-                          StoredDiagnostics.end());
+  checkAndRemoveNonDriverDiags(StoredDiagnostics);
   TopLevelDecls.clear();
   TopLevelDeclsInPreamble.clear();
  =20
@@ -1406,10 +1557,9 @@
   Clang->setSourceManager(new SourceManager(getDiagnostics(),
                                             Clang->getFileManager()));
  =20
-  llvm::OwningPtr<PrecompilePreambleAction> Act;
+  OwningPtr<PrecompilePreambleAction> Act;
   Act.reset(new PrecompilePreambleAction(*this));
-  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[=
0].second,
-                            Clang->getFrontendOpts().Inputs[0].first)) {
+  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[=
0])) {
     llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
     Preamble.clear();
     PreambleRebuildCounter =3D DefaultPreambleRebuildInterval;
@@ -1438,14 +1588,11 @@
   // of preamble diagnostics.
   PreambleDiagnostics.clear();
   PreambleDiagnostics.insert(PreambleDiagnostics.end(),=20
-                   StoredDiagnostics.begin() + NumStoredDiagnosticsFromDri=
ver,
-                             StoredDiagnostics.end());
-  StoredDiagnostics.erase(
-                    StoredDiagnostics.begin() + NumStoredDiagnosticsFromDr=
iver,
-                          StoredDiagnostics.end());
+                            stored_diag_afterDriver_begin(), stored_diag_e=
nd());
+  checkAndRemoveNonDriverDiags(StoredDiagnostics);
  =20
   // Keep track of the preamble we precompiled.
-  PreambleFile =3D FrontendOpts.OutputFile;
+  setPreambleFile(this, FrontendOpts.OutputFile);
   NumWarningsInPreamble =3D getDiagnostics().getNumWarnings();
  =20
   // Keep track of all of the files that the source manager knows about,
@@ -1480,7 +1627,7 @@
  =20
   return CreatePaddedMainFileBuffer(NewPreamble.first,=20
                                     PreambleReservedSize,
-                                    FrontendOpts.Inputs[0].second);
+                                    FrontendOpts.Inputs[0].File);
 }
=20
 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
@@ -1498,15 +1645,28 @@
   TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.e=
nd());
 }
=20
+void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
+  // Steal the created target, context, and preprocessor.
+  TheSema.reset(CI.takeSema());
+  Consumer.reset(CI.takeASTConsumer());
+  Ctx =3D &CI.getASTContext();
+  PP =3D &CI.getPreprocessor();
+  CI.setSourceManager(0);
+  CI.setFileManager(0);
+  Target =3D &CI.getTarget();
+  Reader =3D CI.getModuleManager();
+}
+
 StringRef ASTUnit::getMainFileName() const {
-  return Invocation->getFrontendOpts().Inputs[0].second;
+  return Invocation->getFrontendOpts().Inputs[0].File;
 }
=20
 ASTUnit *ASTUnit::create(CompilerInvocation *CI,
-                         llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags=
) {
-  llvm::OwningPtr<ASTUnit> AST;
+                         IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
+                         bool CaptureDiagnostics) {
+  OwningPtr<ASTUnit> AST;
   AST.reset(new ASTUnit(false));
-  ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=3D*/false);
+  ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
   AST->Diagnostics =3D Diags;
   AST->Invocation =3D CI;
   AST->FileSystemOpts =3D CI->getFileSystemOpts();
@@ -1517,23 +1677,36 @@
 }
=20
 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
-                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
+                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
                                              ASTFrontendAction *Action,
-                                             ASTUnit *Unit) {
+                                             ASTUnit *Unit,
+                                             bool Persistent,
+                                             StringRef ResourceFilesPath,
+                                             bool OnlyLocalDecls,
+                                             bool CaptureDiagnostics,
+                                             bool PrecompilePreamble,
+                                             bool CacheCodeCompletionResul=
ts,
+                                             OwningPtr<ASTUnit> *ErrAST) {
   assert(CI && "A CompilerInvocation is required");
=20
-  llvm::OwningPtr<ASTUnit> OwnAST;
+  OwningPtr<ASTUnit> OwnAST;
   ASTUnit *AST =3D Unit;
   if (!AST) {
     // Create the AST unit.
-    OwnAST.reset(create(CI, Diags));
+    OwnAST.reset(create(CI, Diags, CaptureDiagnostics));
     AST =3D OwnAST.get();
   }
  =20
-  AST->OnlyLocalDecls =3D false;
-  AST->CaptureDiagnostics =3D false;
+  if (!ResourceFilesPath.empty()) {
+    // Override the resources path.
+    CI->getHeaderSearchOpts().ResourceDir =3D ResourceFilesPath;
+  }
+  AST->OnlyLocalDecls =3D OnlyLocalDecls;
+  AST->CaptureDiagnostics =3D CaptureDiagnostics;
+  if (PrecompilePreamble)
+    AST->PreambleRebuildCounter =3D 2;
   AST->TUKind =3D Action ? Action->getTranslationUnitKind() : TU_Complete;
-  AST->ShouldCacheCodeCompletionResults =3D false;
+  AST->ShouldCacheCodeCompletionResults =3D CacheCodeCompletionResults;
=20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
@@ -1551,14 +1724,14 @@
   AST->TargetFeatures =3D CI->getTargetOpts().Features;
=20
   // Create the compiler instance to use for building the AST.
-  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
+  OwningPtr<CompilerInstance> Clang(new CompilerInstance());
=20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
     CICleanup(Clang.get());
=20
   Clang->setInvocation(CI);
-  AST->OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].second;
+  AST->OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].File;
    =20
   // Set up diagnostics, capturing any diagnostics that would
   // otherwise be dropped.
@@ -1579,15 +1752,16 @@
  =20
   assert(Clang->getFrontendOpts().Inputs.size() =3D=3D 1 &&
          "Invocation must have exactly one source file!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_AST &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_AST &&
          "FIXME: AST inputs not yet supported here!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_LLVM_IR &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_LLVM_IR &&
          "IR inputs not supported here!");
=20
   // Configure the various subsystems.
   AST->TheSema.reset();
   AST->Ctx =3D 0;
   AST->PP =3D 0;
+  AST->Reader =3D 0;
  =20
   // Create a file manager object to provide access to and cache the files=
ystem.
   Clang->setFileManager(&AST->getFileManager());
@@ -1597,7 +1771,7 @@
=20
   ASTFrontendAction *Act =3D Action;
=20
-  llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
+  OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
   if (!Act) {
     TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
     Act =3D TrackerAct.get();
@@ -1607,21 +1781,28 @@
   llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
     ActCleanup(TrackerAct.get());
=20
-  if (!Act->BeginSourceFile(*Clang.get(),
-                            Clang->getFrontendOpts().Inputs[0].second,
-                            Clang->getFrontendOpts().Inputs[0].first))
+  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[=
0])) {
+    AST->transferASTDataFromCompilerInstance(*Clang);
+    if (OwnAST && ErrAST)
+      ErrAST->swap(OwnAST);
+
     return 0;
- =20
+  }
+
+  if (Persistent && !TrackerAct) {
+    Clang->getPreprocessor().addPPCallbacks(
+     new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValu=
e()));
+    std::vector<ASTConsumer*> Consumers;
+    if (Clang->hasASTConsumer())
+      Consumers.push_back(Clang->takeASTConsumer());
+    Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
+                                           AST->getCurrentTopLevelHashValu=
e()));
+    Clang->setASTConsumer(new MultiplexConsumer(Consumers));
+  }
   Act->Execute();
- =20
+
   // Steal the created target, context, and preprocessor.
-  AST->TheSema.reset(Clang->takeSema());
-  AST->Consumer.reset(Clang->takeASTConsumer());
-  AST->Ctx =3D &Clang->getASTContext();
-  AST->PP =3D &Clang->getPreprocessor();
-  Clang->setSourceManager(0);
-  Clang->setFileManager(0);
-  AST->Target =3D &Clang->getTarget();
+  AST->transferASTDataFromCompilerInstance(*Clang);
  =20
   Act->EndSourceFile();
=20
@@ -1661,15 +1842,14 @@
 }
=20
 ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
-                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
+                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
                                              bool OnlyLocalDecls,
                                              bool CaptureDiagnostics,
                                              bool PrecompilePreamble,
                                              TranslationUnitKind TUKind,
-                                             bool CacheCodeCompletionResul=
ts,
-                                             bool NestedMacroExpansions) {=
 =20
+                                             bool CacheCodeCompletionResul=
ts) { =20
   // Create the AST unit.
-  llvm::OwningPtr<ASTUnit> AST;
+  OwningPtr<ASTUnit> AST;
   AST.reset(new ASTUnit(false));
   ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
   AST->Diagnostics =3D Diags;
@@ -1678,7 +1858,6 @@
   AST->TUKind =3D TUKind;
   AST->ShouldCacheCodeCompletionResults =3D CacheCodeCompletionResults;
   AST->Invocation =3D CI;
-  AST->NestedMacroExpansions =3D NestedMacroExpansions;
  =20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
@@ -1692,7 +1871,7 @@
=20
 ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
                                       const char **ArgEnd,
-                                    llvm::IntrusiveRefCntPtr<DiagnosticsEn=
gine> Diags,
+                                    IntrusiveRefCntPtr<DiagnosticsEngine> =
Diags,
                                       StringRef ResourceFilesPath,
                                       bool OnlyLocalDecls,
                                       bool CaptureDiagnostics,
@@ -1702,7 +1881,9 @@
                                       bool PrecompilePreamble,
                                       TranslationUnitKind TUKind,
                                       bool CacheCodeCompletionResults,
-                                      bool NestedMacroExpansions) {
+                                      bool AllowPCHWithCompilerErrors,
+                                      bool SkipFunctionBodies,
+                                      OwningPtr<ASTUnit> *ErrAST) {
   if (!Diags.getPtr()) {
     // No diagnostics engine was provided, so create our own diagnostics o=
bject
     // with the default options.
@@ -1713,7 +1894,7 @@
=20
   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
  =20
-  llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
+  IntrusiveRefCntPtr<CompilerInvocation> CI;
=20
   {
=20
@@ -1738,18 +1919,21 @@
       CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fn=
ame);
     }
   }
-  CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =3D
-                                                  RemappedFilesKeepOrigina=
lName;
+  PreprocessorOptions &PPOpts =3D CI->getPreprocessorOpts();
+  PPOpts.RemappedFilesKeepOriginalName =3D RemappedFilesKeepOriginalName;
+  PPOpts.AllowPCHWithCompilerErrors =3D AllowPCHWithCompilerErrors;
  =20
   // Override the resources path.
   CI->getHeaderSearchOpts().ResourceDir =3D ResourceFilesPath;
=20
+  CI->getFrontendOpts().SkipFunctionBodies =3D SkipFunctionBodies;
+
   // Create the AST unit.
-  llvm::OwningPtr<ASTUnit> AST;
+  OwningPtr<ASTUnit> AST;
   AST.reset(new ASTUnit(false));
   ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
   AST->Diagnostics =3D Diags;
-
+  Diags =3D 0; // Zero out now to ease cleanup during crash recovery.
   AST->FileSystemOpts =3D CI->getFileSystemOpts();
   AST->FileMgr =3D new FileManager(AST->FileSystemOpts);
   AST->OnlyLocalDecls =3D OnlyLocalDecls;
@@ -1759,24 +1943,30 @@
   AST->NumStoredDiagnosticsFromDriver =3D StoredDiagnostics.size();
   AST->StoredDiagnostics.swap(StoredDiagnostics);
   AST->Invocation =3D CI;
-  AST->NestedMacroExpansions =3D NestedMacroExpansions;
+  CI =3D 0; // Zero out now to ease cleanup during crash recovery.
  =20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
     ASTUnitCleanup(AST.get());
-  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
-    llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
-    CICleanup(CI.getPtr());
-  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
-    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
-    DiagCleanup(Diags.getPtr());
=20
-  return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.tak=
e();
+  if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
+    // Some error occurred, if caller wants to examine diagnostics, pass i=
t the
+    // ASTUnit.
+    if (ErrAST) {
+      AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
+      ErrAST->swap(AST);
+    }
+    return 0;
+  }
+
+  return AST.take();
 }
=20
 bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFil=
es) {
   if (!Invocation)
     return true;
+
+  clearFileLevelDecls();
  =20
   SimpleTimer ParsingTimer(WantTiming);
   ParsingTimer.setOutput("Reparsing " + getMainFileName());
@@ -1808,15 +1998,15 @@
   // If we have a preamble file lying around, or if we might try to
   // build a precompiled preamble, do so now.
   llvm::MemoryBuffer *OverrideMainBuffer =3D 0;
-  if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
+  if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
     OverrideMainBuffer =3D getMainBufferWithPrecompiledPreamble(*Invocatio=
n);
    =20
   // Clear out the diagnostics state.
-  if (!OverrideMainBuffer) {
-    getDiagnostics().Reset();
-    ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts(=
));
-  }
- =20
+  getDiagnostics().Reset();
+  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
+  if (OverrideMainBuffer)
+    getDiagnostics().setNumWarnings(NumWarningsInPreamble);
+
   // Parse the sources
   bool Result =3D Parse(OverrideMainBuffer);
  =20
@@ -1826,9 +2016,9 @@
       CurrentTopLevelHashValue !=3D CompletionCacheTopLevelHashValue)
     CacheCodeCompletionResults();
=20
-  // We now need to clear out the completion allocator for
-  // clang_getCursorCompletionString; it'll be recreated if necessary.
-  CursorCompletionAllocator =3D 0;
+  // We now need to clear out the completion info related to this translat=
ion
+  // unit; it'll be recreated if necessary.
+  CCTUInfo.reset();
  =20
   return Result;
 }
@@ -1870,7 +2060,7 @@
         | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
         | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
=20
-      if (AST.getASTContext().getLangOptions().CPlusPlus)
+      if (AST.getASTContext().getLangOpts().CPlusPlus)
         NormalContexts |=3D (1LL << (CodeCompletionContext::CCC_EnumTag - =
1))
                    | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
                    | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag =
- 1));
@@ -1890,6 +2080,10 @@
     virtual CodeCompletionAllocator &getAllocator() {
       return Next.getAllocator();
     }
+
+    virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
+      return Next.getCodeCompletionTUInfo();
+    }
   };
 }
=20
@@ -1961,7 +2155,7 @@
       unsigned HiddenIDNS =3D (Decl::IDNS_Type | Decl::IDNS_Member |=20
                              Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
                              Decl::IDNS_NonMemberOperator);
-      if (Ctx.getLangOptions().CPlusPlus)
+      if (Ctx.getLangOpts().CPlusPlus)
         HiddenIDNS |=3D Decl::IDNS_Tag;
       Hiding =3D (IDNS & HiddenIDNS);
     }
@@ -2021,7 +2215,7 @@
     if (!Context.getPreferredType().isNull()) {
       if (C->Kind =3D=3D CXCursor_MacroDefinition) {
         Priority =3D getMacroUsagePriority(C->Completion->getTypedText(),
-                                         S.getLangOptions(),
+                                         S.getLangOpts(),
                                Context.getPreferredType()->isAnyPointerTyp=
e());       =20
       } else if (C->Type) {
         CanQualType Expected
@@ -2047,8 +2241,8 @@
         Context.getKind() =3D=3D CodeCompletionContext::CCC_MacroNameUse) {
       // Create a new code-completion string that just contains the
       // macro name, without its arguments.
-      CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
-                                    C->Availability);
+      CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInf=
o(),
+                                    CCP_CodePattern, C->Availability);
       Builder.AddTypedTextChunk(C->Completion->getTypedText());
       CursorKind =3D CXCursor_NotImplemented;
       Priority =3D CCP_CodePattern;
@@ -2089,7 +2283,7 @@
   CompletionTimer.setOutput("Code completion @ " + File + ":" +
                             Twine(Line) + ":" + Twine(Column));
=20
-  llvm::IntrusiveRefCntPtr<CompilerInvocation>
+  IntrusiveRefCntPtr<CompilerInvocation>
     CCInvocation(new CompilerInvocation(*Invocation));
=20
   FrontendOptions &FrontendOpts =3D CCInvocation->getFrontendOpts();
@@ -2105,16 +2299,16 @@
   FrontendOpts.CodeCompletionAt.Column =3D Column;
=20
   // Set the language options appropriately.
-  LangOpts =3D CCInvocation->getLangOpts();
+  LangOpts =3D *CCInvocation->getLangOpts();
=20
-  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
+  OwningPtr<CompilerInstance> Clang(new CompilerInstance());
=20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
     CICleanup(Clang.get());
=20
   Clang->setInvocation(&*CCInvocation);
-  OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].second;
+  OriginalSourceFile =3D Clang->getFrontendOpts().Inputs[0].File;
    =20
   // Set up diagnostics, capturing any diagnostics produced.
   Clang->setDiagnostics(&Diag);
@@ -2140,9 +2334,9 @@
  =20
   assert(Clang->getFrontendOpts().Inputs.size() =3D=3D 1 &&
          "Invocation must have exactly one source file!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_AST &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_AST &&
          "FIXME: AST inputs not yet supported here!");
-  assert(Clang->getFrontendOpts().Inputs[0].first !=3D IK_LLVM_IR &&
+  assert(Clang->getFrontendOpts().Inputs[0].Kind !=3D IK_LLVM_IR &&
          "IR inputs not support here!");
=20
  =20
@@ -2174,12 +2368,14 @@
                                 FrontendOpts.ShowGlobalSymbolsInCodeComple=
tion);
   Clang->setCodeCompletionConsumer(AugmentedConsumer);
=20
+  Clang->getFrontendOpts().SkipFunctionBodies =3D true;
+
   // If we have a precompiled preamble, try to use it. We only allow
   // the use of the precompiled preamble if we're if the completion
   // point is within the main file, after the end of the precompiled
   // preamble.
   llvm::MemoryBuffer *OverrideMainBuffer =3D 0;
-  if (!PreambleFile.empty()) {
+  if (!getPreambleFile(this).empty()) {
     using llvm::sys::FileStatus;
     llvm::sys::PathWithStatus CompleteFilePath(File);
     llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
@@ -2196,14 +2392,14 @@
   // make that override happen and introduce the preamble.
   PreprocessorOpts.DisableStatCache =3D true;
   StoredDiagnostics.insert(StoredDiagnostics.end(),
-                           this->StoredDiagnostics.begin(),
-             this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDri=
ver);
+                           stored_diag_begin(),
+                           stored_diag_afterDriver_begin());
   if (OverrideMainBuffer) {
     PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffe=
r);
     PreprocessorOpts.PrecompiledPreambleBytes.first =3D Preamble.size();
     PreprocessorOpts.PrecompiledPreambleBytes.second
                                                     =3D PreambleEndsAtStar=
tOfLine;
-    PreprocessorOpts.ImplicitPCHInclude =3D PreambleFile;
+    PreprocessorOpts.ImplicitPCHInclude =3D getPreambleFile(this);
     PreprocessorOpts.DisablePCHValidation =3D true;
    =20
     OwnedBuffers.push_back(OverrideMainBuffer);
@@ -2215,12 +2411,11 @@
   // Disable the preprocessing record
   PreprocessorOpts.DetailedRecord =3D false;
  =20
-  llvm::OwningPtr<SyntaxOnlyAction> Act;
+  OwningPtr<SyntaxOnlyAction> Act;
   Act.reset(new SyntaxOnlyAction);
-  if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0=
].second,
-                           Clang->getFrontendOpts().Inputs[0].first)) {
+  if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0=
])) {
     if (OverrideMainBuffer) {
-      std::string ModName =3D PreambleFile;
+      std::string ModName =3D getPreambleFile(this);
       TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
                                  getSourceManager(), PreambleDiagnostics,
                                  StoredDiagnostics);
@@ -2228,15 +2423,14 @@
     Act->Execute();
     Act->EndSourceFile();
   }
+
+  checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
 }
=20
 CXSaveError ASTUnit::Save(StringRef File) {
-  if (getDiagnostics().hasUnrecoverableErrorOccurred())
-    return CXSaveError_TranslationErrors;
-
   // Write to a temporary file and later rename it to the actual file, to =
avoid
   // possible race conditions.
-  llvm::SmallString<128> TempPath;
+  SmallString<128> TempPath;
   TempPath =3D File;
   TempPath +=3D "-%%%%%%%%";
   int fd;
@@ -2250,10 +2444,12 @@
=20
   serialize(Out);
   Out.close();
-  if (Out.has_error())
+  if (Out.has_error()) {
+    Out.clear_error();
     return CXSaveError_Unknown;
+  }
=20
-  if (llvm::error_code ec =3D llvm::sys::fs::rename(TempPath.str(), File))=
 {
+  if (llvm::sys::fs::rename(TempPath.str(), File)) {
     bool exists;
     llvm::sys::fs::remove(TempPath.str(), exists);
     return CXSaveError_Unknown;
@@ -2263,14 +2459,13 @@
 }
=20
 bool ASTUnit::serialize(raw_ostream &OS) {
-  if (getDiagnostics().hasErrorOccurred())
-    return true;
+  bool hasErrors =3D getDiagnostics().hasErrorOccurred();
=20
-  std::vector<unsigned char> Buffer;
+  SmallString<128> Buffer;
   llvm::BitstreamWriter Stream(Buffer);
   ASTWriter Writer(Stream);
   // FIXME: Handle modules
-  Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=3D*/false, "");
+  Writer.WriteAST(getSema(), 0, std::string(), 0, "", hasErrors);
  =20
   // Write the generated bitstream to "Out".
   if (!Buffer.empty())
@@ -2303,7 +2498,7 @@
   SmallVector<StoredDiagnostic, 4> Result;
   Result.reserve(Diags.size());
   assert(MMan && "Don't have a module manager");
-  serialization::Module *Mod =3D MMan->ModuleMgr.lookup(ModName);
+  serialization::ModuleFile *Mod =3D MMan->ModuleMgr.lookup(ModName);
   assert(Mod && "Don't have preamble module");
   SLocRemap &Remap =3D Mod->SLocRemap;
   for (unsigned I =3D 0, N =3D Diags.size(); I !=3D N; ++I) {
@@ -2347,6 +2542,95 @@
   Result.swap(Out);
 }
=20
+static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
+                               std::pair<unsigned, Decl *> R) {
+  return L.first < R.first;
+}
+
+void ASTUnit::addFileLevelDecl(Decl *D) {
+  assert(D);
+ =20
+  // We only care about local declarations.
+  if (D->isFromASTFile())
+    return;
+
+  SourceManager &SM =3D *SourceMgr;
+  SourceLocation Loc =3D D->getLocation();
+  if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
+    return;
+
+  // We only keep track of the file-level declarations of each file.
+  if (!D->getLexicalDeclContext()->isFileContext())
+    return;
+
+  SourceLocation FileLoc =3D SM.getFileLoc(Loc);
+  assert(SM.isLocalSourceLocation(FileLoc));
+  FileID FID;
+  unsigned Offset;
+  llvm::tie(FID, Offset) =3D SM.getDecomposedLoc(FileLoc);
+  if (FID.isInvalid())
+    return;
+
+  LocDeclsTy *&Decls =3D FileDecls[FID];
+  if (!Decls)
+    Decls =3D new LocDeclsTy();
+
+  std::pair<unsigned, Decl *> LocDecl(Offset, D);
+
+  if (Decls->empty() || Decls->back().first <=3D Offset) {
+    Decls->push_back(LocDecl);
+    return;
+  }
+
+  LocDeclsTy::iterator
+    I =3D std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocD=
ecl);
+
+  Decls->insert(I, LocDecl);
+}
+
+void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned L=
ength,
+                                  SmallVectorImpl<Decl *> &Decls) {
+  if (File.isInvalid())
+    return;
+
+  if (SourceMgr->isLoadedFileID(File)) {
+    assert(Ctx->getExternalSource() && "No external source!");
+    return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Len=
gth,
+                                                         Decls);
+  }
+
+  FileDeclsTy::iterator I =3D FileDecls.find(File);
+  if (I =3D=3D FileDecls.end())
+    return;
+
+  LocDeclsTy &LocDecls =3D *I->second;
+  if (LocDecls.empty())
+    return;
+
+  LocDeclsTy::iterator
+    BeginIt =3D std::lower_bound(LocDecls.begin(), LocDecls.end(),
+                               std::make_pair(Offset, (Decl*)0), compLocDe=
cl);
+  if (BeginIt !=3D LocDecls.begin())
+    --BeginIt;
+
+  // If we are pointing at a top-level decl inside an objc container, we n=
eed
+  // to backtrack until we find it otherwise we will fail to report that t=
he
+  // region overlaps with an objc container.
+  while (BeginIt !=3D LocDecls.begin() &&
+         BeginIt->second->isTopLevelDeclInObjCContainer())
+    --BeginIt;
+
+  LocDeclsTy::iterator
+    EndIt =3D std::upper_bound(LocDecls.begin(), LocDecls.end(),
+                             std::make_pair(Offset+Length, (Decl*)0),
+                             compLocDecl);
+  if (EndIt !=3D LocDecls.end())
+    ++EndIt;
+ =20
+  for (LocDeclsTy::iterator DIt =3D BeginIt; DIt !=3D EndIt; ++DIt)
+    Decls.push_back(DIt->second);
+}
+
 SourceLocation ASTUnit::getLocation(const FileEntry *File,
                                     unsigned Line, unsigned Col) const {
   const SourceManager &SM =3D getSourceManager();
@@ -2403,6 +2687,50 @@
   return Loc;
 }
=20
+bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
+  FileID FID;
+  if (SourceMgr)
+    FID =3D SourceMgr->getPreambleFileID();
+ =20
+  if (Loc.isInvalid() || FID.isInvalid())
+    return false;
+ =20
+  return SourceMgr->isInFileID(Loc, FID);
+}
+
+bool ASTUnit::isInMainFileID(SourceLocation Loc) {
+  FileID FID;
+  if (SourceMgr)
+    FID =3D SourceMgr->getMainFileID();
+ =20
+  if (Loc.isInvalid() || FID.isInvalid())
+    return false;
+ =20
+  return SourceMgr->isInFileID(Loc, FID);
+}
+
+SourceLocation ASTUnit::getEndOfPreambleFileID() {
+  FileID FID;
+  if (SourceMgr)
+    FID =3D SourceMgr->getPreambleFileID();
+ =20
+  if (FID.isInvalid())
+    return SourceLocation();
+
+  return SourceMgr->getLocForEndOfFile(FID);
+}
+
+SourceLocation ASTUnit::getStartOfMainFileID() {
+  FileID FID;
+  if (SourceMgr)
+    FID =3D SourceMgr->getMainFileID();
+ =20
+  if (FID.isInvalid())
+    return SourceLocation();
+ =20
+  return SourceMgr->getLocForStartOfFile(FID);
+}
+
 void ASTUnit::PreambleData::countLines() const {
   NumLines =3D 0;
   if (empty())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/CacheTokens.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/CacheTokens.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/CacheTokens.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -467,7 +467,7 @@
   // Iterate over all the files in SourceManager.  Create a lexer
   // for each file and cache the tokens.
   SourceManager &SM =3D PP.getSourceManager();
-  const LangOptions &LOpts =3D PP.getLangOptions();
+  const LangOptions &LOpts =3D PP.getLangOpts();
=20
   for (SourceManager::fileinfo_iterator I =3D SM.fileinfo_begin(),
        E =3D SM.fileinfo_end(); I !=3D E; ++I) {
@@ -540,7 +540,7 @@
   // Get the name of the main file.
   const SourceManager &SrcMgr =3D PP.getSourceManager();
   const FileEntry *MainFile =3D SrcMgr.getFileEntryForID(SrcMgr.getMainFil=
eID());
-  llvm::SmallString<128> MainFilePath(MainFile->getName());
+  SmallString<128> MainFilePath(MainFile->getName());
=20
   llvm::sys::fs::make_absolute(MainFilePath);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/CompilerInstance.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/CompilerInstance.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -11,6 +11,7 @@
 #include "clang/Sema/Sema.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
@@ -24,6 +25,7 @@
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/LogDiagnosticPrinter.h"
+#include "clang/Frontend/SerializedDiagnosticPrinter.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
 #include "clang/Frontend/Utils.h"
@@ -35,6 +37,7 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/Host.h"
+#include "llvm/Support/LockFileManager.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
@@ -42,18 +45,6 @@
 #include "llvm/Support/CrashRecoveryContext.h"
 #include "llvm/Config/config.h"
=20
-// Support for FileLockManager
-#include <fstream>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#if LLVM_ON_WIN32
-#include <windows.h>
-#endif
-#if LLVM_ON_UNIX
-#include <unistd.h>
-#endif
-
 using namespace clang;
=20
 CompilerInstance::CompilerInstance()
@@ -97,6 +88,7 @@
=20
 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Val=
ue) {
   CompletionConsumer.reset(Value);
+  getFrontendOpts().SkipFunctionBodies =3D Value !=3D 0;
 }
=20
 // Diagnostics
@@ -104,7 +96,7 @@
                               unsigned argc, const char* const *argv,
                               DiagnosticsEngine &Diags) {
   std::string ErrorInfo;
-  llvm::OwningPtr<raw_ostream> OS(
+  OwningPtr<raw_ostream> OS(
     new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorI=
nfo));
   if (!ErrorInfo.empty()) {
     Diags.Report(diag::err_fe_unable_to_open_logfile)
@@ -153,6 +145,28 @@
   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger=
));
 }
=20
+static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
+                                       DiagnosticsEngine &Diags,
+                                       StringRef OutputFile) {
+  std::string ErrorInfo;
+  OwningPtr<llvm::raw_fd_ostream> OS;
+  OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
+                                    llvm::raw_fd_ostream::F_Binary));
+ =20
+  if (!ErrorInfo.empty()) {
+    Diags.Report(diag::warn_fe_serialized_diag_failure)
+      << OutputFile << ErrorInfo;
+    return;
+  }
+ =20
+  DiagnosticConsumer *SerializedConsumer =3D
+    clang::serialized_diags::create(OS.take(), DiagOpts);
+
+ =20
+  Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
+                                                SerializedConsumer));
+}
+
 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
                                          DiagnosticConsumer *Client,
                                          bool ShouldOwnClient,
@@ -162,15 +176,15 @@
                                   &getCodeGenOpts());
 }
=20
-llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
+IntrusiveRefCntPtr<DiagnosticsEngine>
 CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
                                     int Argc, const char* const *Argv,
                                     DiagnosticConsumer *Client,
                                     bool ShouldOwnClient,
                                     bool ShouldCloneClient,
                                     const CodeGenOptions *CodeGenOpts) {
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
-  llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticsEngine>
       Diags(new DiagnosticsEngine(DiagID));
=20
   // Create the diagnostic client for reporting errors or for
@@ -194,6 +208,10 @@
   if (!Opts.DumpBuildInformation.empty())
     SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
=20
+  if (!Opts.DiagnosticSerializationFile.empty())
+    SetupSerializedDiagnostics(Opts, *Diags,
+                               Opts.DiagnosticSerializationFile);
+ =20
   // Configure our handling of diagnostics.
   ProcessWarningOptions(*Diags, Opts);
=20
@@ -223,7 +241,10 @@
     PTHMgr =3D PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
=20
   // Create the Preprocessor.
-  HeaderSearch *HeaderInfo =3D new HeaderSearch(getFileManager());
+  HeaderSearch *HeaderInfo =3D new HeaderSearch(getFileManager(),=20
+                                              getDiagnostics(),
+                                              getLangOpts(),
+                                              &getTarget());
   PP =3D new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
                         getSourceManager(), *HeaderInfo, *this, PTHMgr,
                         /*OwnsHeaderSearch=3D*/true);
@@ -237,28 +258,28 @@
   }
=20
   if (PPOpts.DetailedRecord)
-    PP->createPreprocessingRecord(
-                                  PPOpts.DetailedRecordIncludesNestedMacro=
Expansions);
+    PP->createPreprocessingRecord(PPOpts.DetailedRecordConditionalDirectiv=
es);
=20
   InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOp=
ts());
=20
   // Set up the module path, including the hash for the
   // module-creation options.
-  llvm::SmallString<256> SpecificModuleCache(
+  SmallString<256> SpecificModuleCache(
                            getHeaderSearchOpts().ModuleCachePath);
   if (!getHeaderSearchOpts().DisableModuleHash)
     llvm::sys::path::append(SpecificModuleCache,
                             getInvocation().getModuleHash());
-  PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
-    getPreprocessorOpts().ModuleBuildPath.empty()
-      ? std::string()
-      : getPreprocessorOpts().ModuleBuildPath.back());
+  PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
=20
   // Handle generating dependencies, if requested.
   const DependencyOutputOptions &DepOpts =3D getDependencyOutputOpts();
   if (!DepOpts.OutputFile.empty())
     AttachDependencyFileGen(*PP, DepOpts);
+  if (!DepOpts.DOTOutputFile.empty())
+    AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
+                             getHeaderSearchOpts().Sysroot);
=20
+ =20
   // Handle generating header include information, if requested.
   if (DepOpts.ShowHeaderIncludes)
     AttachHeaderIncludeGen(*PP);
@@ -286,12 +307,14 @@
 void CompilerInstance::createPCHExternalASTSource(StringRef Path,
                                                   bool DisablePCHValidatio=
n,
                                                   bool DisableStatCache,
+                                                bool AllowPCHWithCompilerE=
rrors,
                                                  void *DeserializationList=
ener){
-  llvm::OwningPtr<ExternalASTSource> Source;
+  OwningPtr<ExternalASTSource> Source;
   bool Preamble =3D getPreprocessorOpts().PrecompiledPreambleBytes.first !=
=3D 0;
   Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysr=
oot,
                                           DisablePCHValidation,
                                           DisableStatCache,
+                                          AllowPCHWithCompilerErrors,
                                           getPreprocessor(), getASTContext=
(),
                                           DeserializationListener,
                                           Preamble));
@@ -304,14 +327,16 @@
                                              const std::string &Sysroot,
                                              bool DisablePCHValidation,
                                              bool DisableStatCache,
+                                             bool AllowPCHWithCompilerErro=
rs,
                                              Preprocessor &PP,
                                              ASTContext &Context,
                                              void *DeserializationListener,
                                              bool Preamble) {
-  llvm::OwningPtr<ASTReader> Reader;
+  OwningPtr<ASTReader> Reader;
   Reader.reset(new ASTReader(PP, Context,
                              Sysroot.empty() ? "" : Sysroot.c_str(),
-                             DisablePCHValidation, DisableStatCache));
+                             DisablePCHValidation, DisableStatCache,
+                             AllowPCHWithCompilerErrors));
=20
   Reader->setDeserializationListener(
             static_cast<ASTDeserializationListener *>(DeserializationListe=
ner));
@@ -359,7 +384,7 @@
 void CompilerInstance::createCodeCompletionConsumer() {
   const ParsedSourceLocation &Loc =3D getFrontendOpts().CodeCompletionAt;
   if (!CompletionConsumer) {
-    CompletionConsumer.reset(
+    setCodeCompletionConsumer(
       createCodeCompletionConsumer(getPreprocessor(),
                                    Loc.FileName, Loc.Line, Loc.Column,
                                    getFrontendOpts().ShowMacrosInCodeCompl=
etion,
@@ -370,14 +395,14 @@
       return;
   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
                                   Loc.Line, Loc.Column)) {
-    CompletionConsumer.reset();
+    setCodeCompletionConsumer(0);
     return;
   }
=20
   if (CompletionConsumer->isOutputBinary() &&
       llvm::sys::Program::ChangeStdoutToBinary()) {
     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
-    CompletionConsumer.reset();
+    setCodeCompletionConsumer(0);
   }
 }
=20
@@ -424,7 +449,7 @@
         bool existed;
         llvm::sys::fs::remove(it->TempFilename, existed);
       } else {
-        llvm::SmallString<128> NewOutFile(it->Filename);
+        SmallString<128> NewOutFile(it->Filename);
=20
         // If '-working-directory' was passed, the output filename should =
be
         // relative to that.
@@ -450,7 +475,8 @@
                                           StringRef InFile,
                                           StringRef Extension) {
   return createOutputFile(getFrontendOpts().OutputFile, Binary,
-                          /*RemoveFileOnSignal=3D*/true, InFile, Extension=
);
+                          /*RemoveFileOnSignal=3D*/true, InFile, Extension,
+                          /*UseTemporary=3D*/true);
 }
=20
 llvm::raw_fd_ostream *
@@ -458,12 +484,14 @@
                                    bool Binary, bool RemoveFileOnSignal,
                                    StringRef InFile,
                                    StringRef Extension,
-                                   bool UseTemporary) {
+                                   bool UseTemporary,
+                                   bool CreateMissingDirectories) {
   std::string Error, OutputPathName, TempPathName;
   llvm::raw_fd_ostream *OS =3D createOutputFile(OutputPath, Error, Binary,
                                               RemoveFileOnSignal,
                                               InFile, Extension,
                                               UseTemporary,
+                                              CreateMissingDirectories,
                                               &OutputPathName,
                                               &TempPathName);
   if (!OS) {
@@ -488,8 +516,12 @@
                                    StringRef InFile,
                                    StringRef Extension,
                                    bool UseTemporary,
+                                   bool CreateMissingDirectories,
                                    std::string *ResultPathName,
                                    std::string *TempPathName) {
+  assert((!CreateMissingDirectories || UseTemporary) &&
+         "CreateMissingDirectories is only allowed when using temporary fi=
les");
+
   std::string OutFile, TempFile;
   if (!OutputPath.empty()) {
     OutFile =3D OutputPath;
@@ -504,18 +536,26 @@
     OutFile =3D "-";
   }
=20
-  llvm::OwningPtr<llvm::raw_fd_ostream> OS;
+  OwningPtr<llvm::raw_fd_ostream> OS;
   std::string OSFile;
=20
   if (UseTemporary && OutFile !=3D "-") {
-    llvm::sys::Path OutPath(OutFile);
-    // Only create the temporary if we can actually write to OutPath, othe=
rwise
-    // we want to fail early.
+    // Only create the temporary if the parent directory exists (or create
+    // missing directories is true) and we can actually write to OutPath,
+    // otherwise we want to fail early.
+    SmallString<256> AbsPath(OutputPath);
+    llvm::sys::fs::make_absolute(AbsPath);
+    llvm::sys::Path OutPath(AbsPath);
+    bool ParentExists =3D false;
+    if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()),
+                              ParentExists))
+      ParentExists =3D false;
     bool Exists;
-    if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
-        (OutPath.isRegularFile() && OutPath.canWrite())) {
+    if ((CreateMissingDirectories || ParentExists) &&
+        ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) ||
+         (OutPath.isRegularFile() && OutPath.canWrite()))) {
       // Create a temporary file.
-      llvm::SmallString<128> TempPath;
+      SmallString<128> TempPath;
       TempPath =3D OutFile;
       TempPath +=3D "-%%%%%%%%";
       int fd;
@@ -550,12 +590,15 @@
=20
 // Initialization Utilities
=20
-bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
-  return InitializeSourceManager(InputFile, getDiagnostics(), getFileManag=
er(),
-                                 getSourceManager(), getFrontendOpts());
+bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
+                                               SrcMgr::CharacteristicKind =
Kind){
+  return InitializeSourceManager(InputFile, Kind, getDiagnostics(),=20
+                                 getFileManager(), getSourceManager(),=20
+                                 getFrontendOpts());
 }
=20
 bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
+                                               SrcMgr::CharacteristicKind =
Kind,
                                                DiagnosticsEngine &Diags,
                                                FileManager &FileMgr,
                                                SourceManager &SourceMgr,
@@ -567,9 +610,9 @@
       Diags.Report(diag::err_fe_error_reading) << InputFile;
       return false;
     }
-    SourceMgr.createMainFileID(File);
+    SourceMgr.createMainFileID(File, Kind);
   } else {
-    llvm::OwningPtr<llvm::MemoryBuffer> SB;
+    OwningPtr<llvm::MemoryBuffer> SB;
     if (llvm::MemoryBuffer::getSTDIN(SB)) {
       // FIXME: Give ec.message() in this diag.
       Diags.Report(diag::err_fe_error_reading_stdin);
@@ -577,7 +620,7 @@
     }
     const FileEntry *File =3D FileMgr.getVirtualFile(SB->getBufferIdentifi=
er(),
                                                    SB->getBufferSize(), 0);
-    SourceMgr.createMainFileID(File);
+    SourceMgr.createMainFileID(File, Kind);
     SourceMgr.overrideFileContents(File, SB.take());
   }
=20
@@ -612,7 +655,7 @@
   if (getHeaderSearchOpts().Verbose)
     OS << "clang -cc1 version " CLANG_VERSION_STRING
        << " based upon " << PACKAGE_STRING
-       << " hosted on " << llvm::sys::getHostTriple() << "\n";
+       << " default target " << llvm::sys::getDefaultTargetTriple() << "\n=
";
=20
   if (getFrontendOpts().ShowTimers)
     createFrontendTimer();
@@ -621,18 +664,19 @@
     llvm::EnableStatistics();
=20
   for (unsigned i =3D 0, e =3D getFrontendOpts().Inputs.size(); i !=3D e; =
++i) {
-    const std::string &InFile =3D getFrontendOpts().Inputs[i].second;
-
     // Reset the ID tables if we are reusing the SourceManager.
     if (hasSourceManager())
       getSourceManager().clearIDTables();
=20
-    if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].fir=
st)) {
+    if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
       Act.Execute();
       Act.EndSourceFile();
     }
   }
=20
+  // Notify the diagnostic client that all files were processed.
+  getDiagnostics().getClient()->finish();
+
   if (getDiagnosticOpts().ShowCarets) {
     // We can have multiple diagnostics sharing one diagnostic client.
     // Get the total number of warnings/errors from the client.
@@ -670,320 +714,105 @@
 }
=20
 namespace {
-  struct CompileModuleData {
+  struct CompileModuleMapData {
     CompilerInstance &Instance;
-    GeneratePCHAction &CreateModuleAction;
+    GenerateModuleAction &CreateModuleAction;
   };
 }
=20
 /// \brief Helper function that executes the module-generating action under
 /// a crash recovery context.
-static void doCompileModule(void *UserData) {
-  CompileModuleData &Data =3D *reinterpret_cast<CompileModuleData *>(UserD=
ata);
+static void doCompileMapModule(void *UserData) {
+  CompileModuleMapData &Data
+    =3D *reinterpret_cast<CompileModuleMapData *>(UserData);
   Data.Instance.ExecuteAction(Data.CreateModuleAction);
 }
=20
-namespace {
-  /// \brief Class that manages the creation of a lock file to aid
-  /// implicit coordination between different processes.
-  ///
-  /// The implicit coordination works by creating a ".lock" file alongside
-  /// the file that we're coordinating for, using the atomicity of the file
-  /// system to ensure that only a single process can create that ".lock" =
file.
-  /// When the lock file is removed, the owning process has finished the
-  /// operation.
-  class LockFileManager {
-  public:
-    /// \brief Describes the state of a lock file.
-    enum LockFileState {
-      /// \brief The lock file has been created and is owned by this insta=
nce
-      /// of the object.
-      LFS_Owned,
-      /// \brief The lock file already exists and is owned by some other
-      /// instance.
-      LFS_Shared,
-      /// \brief An error occurred while trying to create or find the lock
-      /// file.
-      LFS_Error
-    };
-
-  private:
-    llvm::SmallString<128> LockFileName;
-    llvm::SmallString<128> UniqueLockFileName;
-
-    llvm::Optional<std::pair<std::string, int> > Owner;
-    llvm::Optional<llvm::error_code> Error;
-
-    LockFileManager(const LockFileManager &);
-    LockFileManager &operator=3D(const LockFileManager &);
-
-    static llvm::Optional<std::pair<std::string, int> >
-    readLockFile(StringRef LockFileName);
-
-    static bool processStillExecuting(StringRef Hostname, int PID);
-
-  public:
-
-    LockFileManager(StringRef FileName);
-    ~LockFileManager();
-
-    /// \brief Determine the state of the lock file.
-    LockFileState getState() const;
-
-    operator LockFileState() const { return getState(); }
-
-    /// \brief For a shared lock, wait until the owner releases the lock.
-    void waitForUnlock();
-  };
-}
-
-/// \brief Attempt to read the lock file with the given name, if it exists.
-///
-/// \param LockFileName The name of the lock file to read.
-///
-/// \returns The process ID of the process that owns this lock file
-llvm::Optional<std::pair<std::string, int> >
-LockFileManager::readLockFile(StringRef LockFileName) {
-  // Check whether the lock file exists. If not, clearly there's nothing
-  // to read, so we just return.
-  bool Exists =3D false;
-  if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
-    return llvm::Optional<std::pair<std::string, int> >();
-
-  // Read the owning host and PID out of the lock file. If it appears that=
 the
-  // owning process is dead, the lock file is invalid.
-  int PID =3D 0;
-  std::string Hostname;
-  std::ifstream Input(LockFileName.str().c_str());
-  if (Input >> Hostname >> PID && PID > 0 &&
-      processStillExecuting(Hostname, PID))
-    return std::make_pair(Hostname, PID);
-
-  // Delete the lock file. It's invalid anyway.
-  bool Existed;
-  llvm::sys::fs::remove(LockFileName, Existed);
-  return llvm::Optional<std::pair<std::string, int> >();
-}
-
-bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
-#if LLVM_ON_UNIX
-  char MyHostname[256];
-  MyHostname[255] =3D 0;
-  MyHostname[0] =3D 0;
-  gethostname(MyHostname, 255);
-  // Check whether the process is dead. If so, we're done.
-  if (MyHostname =3D=3D Hostname && getsid(PID) =3D=3D -1 && errno =3D=3D =
ESRCH)
-    return false;
-#endif
-
-  return true;
-}
-
-LockFileManager::LockFileManager(StringRef FileName)
-{
-  LockFileName =3D FileName;
-  LockFileName +=3D ".lock";
-
-  // If the lock file already exists, don't bother to try to create our own
-  // lock file; it won't work anyway. Just figure out who owns this lock f=
ile.
-  if ((Owner =3D readLockFile(LockFileName)))
+/// \brief Compile a module file for the given module, using the options=20
+/// provided by the importing compiler instance.
+static void compileModule(CompilerInstance &ImportingInstance,
+                          Module *Module,
+                          StringRef ModuleFileName) {
+  llvm::LockFileManager Locked(ModuleFileName);
+  switch (Locked) {
+  case llvm::LockFileManager::LFS_Error:
     return;
=20
-  // Create a lock file that is unique to this instance.
-  UniqueLockFileName =3D LockFileName;
-  UniqueLockFileName +=3D "-%%%%%%%%";
-  int UniqueLockFileID;
-  if (llvm::error_code EC
-        =3D llvm::sys::fs::unique_file(UniqueLockFileName.str(),
-                                     UniqueLockFileID,
-                                     UniqueLockFileName,
-                                     /*makeAbsolute=3D*/false)) {
-    Error =3D EC;
-    return;
-  }
-
-  // Write our process ID to our unique lock file.
-  {
-    llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=3D*/true);
-
-#if LLVM_ON_UNIX
-    // FIXME: move getpid() call into LLVM
-    char hostname[256];
-    hostname[255] =3D 0;
-    hostname[0] =3D 0;
-    gethostname(hostname, 255);
-    Out << hostname << ' ' << getpid();
-#else
-    Out << "localhost 1";
-#endif
-    Out.close();
-
-    if (Out.has_error()) {
-      // We failed to write out PID, so make up an excuse, remove the
-      // unique lock file, and fail.
-      Error =3D llvm::make_error_code(llvm::errc::no_space_on_device);
-      bool Existed;
-      llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
-      return;
-    }
-  }
-
-  // Create a hard link from the lock file name. If this succeeds, we're d=
one.
-  llvm::error_code EC
-    =3D llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
-                                      LockFileName.str());
-  if (EC =3D=3D llvm::errc::success)
-    return;
-
-  // Creating the hard link failed.
-
-#ifdef LLVM_ON_UNIX
-  // The creation of the hard link may appear to fail, but if stat'ing the
-  // unique file returns a link count of 2, then we can still declare succ=
ess.
-  struct stat StatBuf;
-  if (stat(UniqueLockFileName.c_str(), &StatBuf) =3D=3D 0 &&
-      StatBuf.st_nlink =3D=3D 2)
-    return;
-#endif
-
-  // Someone else managed to create the lock file first. Wipe out our uniq=
ue
-  // lock file (it's useless now) and read the process ID from the lock fi=
le.
-  bool Existed;
-  llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
-  if ((Owner =3D readLockFile(LockFileName)))
-    return;
-
-  // There is a lock file that nobody owns; try to clean it up and report
-  // an error.
-  llvm::sys::fs::remove(LockFileName.str(), Existed);
-  Error =3D EC;
-}
-
-LockFileManager::LockFileState LockFileManager::getState() const {
-  if (Owner)
-    return LFS_Shared;
-
-  if (Error)
-    return LFS_Error;
-
-  return LFS_Owned;
-}
-
-LockFileManager::~LockFileManager() {
-  if (getState() !=3D LFS_Owned)
-    return;
-
-  // Since we own the lock, remove the lock file and our own unique lock f=
ile.
-  bool Existed;
-  llvm::sys::fs::remove(LockFileName.str(), Existed);
-  llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
-}
-
-void LockFileManager::waitForUnlock() {
-  if (getState() !=3D LFS_Shared)
-    return;
-
-#if LLVM_ON_WIN32
-  unsigned long Interval =3D 1;
-#else
-  struct timespec Interval;
-  Interval.tv_sec =3D 0;
-  Interval.tv_nsec =3D 1000000;
-#endif
-  // Don't wait more than an hour for the file to appear.
-  const unsigned MaxSeconds =3D 3600;
-  do {
-    // Sleep for the designated interval, to allow the owning process time=
 to
-    // finish up and
-    // FIXME: Should we hook in to system APIs to get a notification when =
the
-    // lock file is deleted?
-#if LLVM_ON_WIN32
-    Sleep(Interval);
-#else
-    nanosleep(&Interval, NULL);
-#endif
-    // If the file no longer exists, we're done.
-    bool Exists =3D false;
-    if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
-      return;
-
-    if (!processStillExecuting((*Owner).first, (*Owner).second))
-      return;
-
-    // Exponentially increase the time we wait for the lock to be removed.
-#if LLVM_ON_WIN32
-    Interval *=3D 2;
-#else
-    Interval.tv_sec *=3D 2;
-    Interval.tv_nsec *=3D 2;
-    if (Interval.tv_nsec >=3D 1000000000) {
-      ++Interval.tv_sec;
-      Interval.tv_nsec -=3D 1000000000;
-    }
-#endif
-  } while (
-#if LLVM_ON_WIN32
-           Interval < MaxSeconds * 1000
-#else
-           Interval.tv_sec < (time_t)MaxSeconds
-#endif
-           );
-
-  // Give up.
-}
-
-/// \brief Compile a module file for the given module name with the given
-/// umbrella header, using the options provided by the importing compiler
-/// instance.
-static void compileModule(CompilerInstance &ImportingInstance,
-                          StringRef ModuleName,
-                          StringRef ModuleFileName,
-                          StringRef UmbrellaHeader) {
-  LockFileManager Locked(ModuleFileName);
-  switch (Locked) {
-  case LockFileManager::LFS_Error:
-    return;
-
-  case LockFileManager::LFS_Owned:
+  case llvm::LockFileManager::LFS_Owned:
     // We're responsible for building the module ourselves. Do so below.
     break;
=20
-  case LockFileManager::LFS_Shared:
+  case llvm::LockFileManager::LFS_Shared:
     // Someone else is responsible for building the module. Wait for them =
to
     // finish.
     Locked.waitForUnlock();
     break;
   }
=20
+  ModuleMap &ModMap=20
+    =3D ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModul=
eMap();
+   =20
   // Construct a compiler invocation for creating this module.
-  llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
+  IntrusiveRefCntPtr<CompilerInvocation> Invocation
     (new CompilerInvocation(ImportingInstance.getInvocation()));
=20
+  PreprocessorOptions &PPOpts =3D Invocation->getPreprocessorOpts();
+ =20
   // For any options that aren't intended to affect how a module is built,
   // reset them to their default values.
-  Invocation->getLangOpts().resetNonModularOptions();
-  Invocation->getPreprocessorOpts().resetNonModularOptions();
+  Invocation->getLangOpts()->resetNonModularOptions();
+  PPOpts.resetNonModularOptions();
+
+  // Note the name of the module we're building.
+  Invocation->getLangOpts()->CurrentModule =3D Module->getTopLevelModuleNa=
me();
=20
   // Note that this module is part of the module build path, so that we
   // can detect cycles in the module graph.
-  Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
+  PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
=20
+  // If there is a module map file, build the module using the module map.
   // Set up the inputs/outputs so that we build the module from its umbrel=
la
   // header.
   FrontendOptions &FrontendOpts =3D Invocation->getFrontendOpts();
   FrontendOpts.OutputFile =3D ModuleFileName.str();
   FrontendOpts.DisableFree =3D false;
   FrontendOpts.Inputs.clear();
-  FrontendOpts.Inputs.push_back(
-    std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()=
),
-                                                 UmbrellaHeader));
+  InputKind IK =3D getSourceInputKindFromOptions(*Invocation->getLangOpts(=
));
=20
+  // Get or create the module map that we'll use to build this module.
+  SmallString<128> TempModuleMapFileName;
+  if (const FileEntry *ModuleMapFile
+                                  =3D ModMap.getContainingModuleMapFile(Mo=
dule)) {
+    // Use the module map where this module resides.
+    FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName=
(),=20
+                                                    IK));
+  } else {
+    // Create a temporary module map file.
+    TempModuleMapFileName =3D Module->Name;
+    TempModuleMapFileName +=3D "-%%%%%%%%.map";
+    int FD;
+    if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,=20
+                                   TempModuleMapFileName,
+                                   /*makeAbsolute=3D*/true)
+          !=3D llvm::errc::success) {
+      ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_=
file)
+        << TempModuleMapFileName;
+      return;
+    }
+    // Print the module map to this file.
+    llvm::raw_fd_ostream OS(FD, /*shouldClose=3D*/true);
+    Module->print(OS);
+    FrontendOpts.Inputs.push_back(
+      FrontendInputFile(TempModuleMapFileName.str().str(), IK));
+  }
+
+  // Don't free the remapped file buffers; they are owned by our caller.
+  PPOpts.RetainRemappedFileBuffers =3D true;
+   =20
   Invocation->getDiagnosticOpts().VerifyDiagnostics =3D 0;
-
-
   assert(ImportingInstance.getInvocation().getModuleHash() =3D=3D
-           Invocation->getModuleHash() && "Module hash mismatch!");
-
+         Invocation->getModuleHash() && "Module hash mismatch!");
+ =20
   // Construct a compiler instance that will be used to actually create the
   // module.
   CompilerInstance Instance;
@@ -992,21 +821,39 @@
                              &ImportingInstance.getDiagnosticClient(),
                              /*ShouldOwnClient=3D*/true,
                              /*ShouldCloneClient=3D*/true);
-
+ =20
   // Construct a module-generating action.
-  GeneratePCHAction CreateModuleAction(true);
-
+  GenerateModuleAction CreateModuleAction;
+ =20
   // Execute the action to actually build the module in-place. Use a separ=
ate
   // thread so that we get a stack large enough.
   const unsigned ThreadStackSize =3D 8 << 20;
   llvm::CrashRecoveryContext CRC;
-  CompileModuleData Data =3D { Instance, CreateModuleAction };
-  CRC.RunSafelyOnThread(&doCompileModule, &Data, ThreadStackSize);
+  CompileModuleMapData Data =3D { Instance, CreateModuleAction };
+  CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
+ =20
+  // Delete the temporary module map file.
+  // FIXME: Even though we're executing under crash protection, it would s=
till
+  // be nice to do this with RemoveFileOnSignal when we can. However, that
+  // doesn't make sense for all clients, so clean this up manually.
+  if (!TempModuleMapFileName.empty())
+    llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
 }
=20
-ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
-                                       IdentifierInfo &ModuleName,
-                                       SourceLocation ModuleNameLoc) {
+Module *CompilerInstance::loadModule(SourceLocation ImportLoc,=20
+                                     ModuleIdPath Path,
+                                     Module::NameVisibilityKind Visibility,
+                                     bool IsInclusionDirective) {
+  // If we've already handled this import, just return the cached result.
+  // This one-element cache is important to eliminate redundant diagnostics
+  // when both the preprocessor and parser see the same import declaration.
+  if (!ImportLoc.isInvalid() && LastModuleImportLoc =3D=3D ImportLoc) {
+    // Make the named module visible.
+    if (LastModuleImportResult)
+      ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
+    return LastModuleImportResult;
+  }
+ =20
   // Determine what file we're searching from.
   SourceManager &SourceMgr =3D getSourceManager();
   SourceLocation ExpandedImportLoc =3D SourceMgr.getExpansionLoc(ImportLoc=
);
@@ -1015,98 +862,236 @@
   if (!CurFile)
     CurFile =3D SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
=20
-  // Search for a module with the given name.
-  std::string UmbrellaHeader;
-  std::string ModuleFileName;
-  const FileEntry *ModuleFile
-    =3D PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
-                                             &ModuleFileName,
-                                             &UmbrellaHeader);
+  StringRef ModuleName =3D Path[0].first->getName();
+  SourceLocation ModuleNameLoc =3D Path[0].second;
=20
-  bool BuildingModule =3D false;
-  if (!ModuleFile && !UmbrellaHeader.empty()) {
-    // We didn't find the module, but there is an umbrella header that
-    // can be used to create the module file. Create a separate compilation
-    // module to do so.
+  clang::Module *Module =3D 0;
+ =20
+  // If we don't already have information on this module, load the module =
now.
+  llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
+    =3D KnownModules.find(Path[0].first);
+  if (Known !=3D KnownModules.end()) {
+    // Retrieve the cached top-level module.
+    Module =3D Known->second;   =20
+  } else if (ModuleName =3D=3D getLangOpts().CurrentModule) {
+    // This is the module we're building.=20
+    Module =3D PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleN=
ame);
+    Known =3D KnownModules.insert(std::make_pair(Path[0].first, Module)).f=
irst;
+  } else {
+    // Search for a module with the given name.
+    Module =3D PP->getHeaderSearchInfo().lookupModule(ModuleName);
+    std::string ModuleFileName;
+    if (Module)
+      ModuleFileName =3D PP->getHeaderSearchInfo().getModuleFileName(Modul=
e);
+    else
+      ModuleFileName =3D PP->getHeaderSearchInfo().getModuleFileName(Modul=
eName);
+   =20
+    if (ModuleFileName.empty()) {
+      getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
+        << ModuleName
+        << SourceRange(ImportLoc, ModuleNameLoc);
+      LastModuleImportLoc =3D ImportLoc;
+      LastModuleImportResult =3D 0;
+      return 0;
+    }
+   =20
+    const FileEntry *ModuleFile
+      =3D getFileManager().getFile(ModuleFileName, /*OpenFile=3D*/false,
+                                 /*CacheFailure=3D*/false);
+    bool BuildingModule =3D false;
+    if (!ModuleFile && Module) {
+      // The module is not cached, but we have a module map from which we =
can
+      // build the module.
=20
-    // Check whether there is a cycle in the module graph.
-    SmallVectorImpl<std::string> &ModuleBuildPath
-      =3D getPreprocessorOpts().ModuleBuildPath;
-    SmallVectorImpl<std::string>::iterator Pos
-      =3D std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
-                  ModuleName.getName());
-    if (Pos !=3D ModuleBuildPath.end()) {
-      llvm::SmallString<256> CyclePath;
-      for (; Pos !=3D ModuleBuildPath.end(); ++Pos) {
-        CyclePath +=3D *Pos;
-        CyclePath +=3D " -> ";
+      // Check whether there is a cycle in the module graph.
+      SmallVectorImpl<std::string> &ModuleBuildPath
+        =3D getPreprocessorOpts().ModuleBuildPath;
+      SmallVectorImpl<std::string>::iterator Pos
+        =3D std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), Modu=
leName);
+      if (Pos !=3D ModuleBuildPath.end()) {
+        SmallString<256> CyclePath;
+        for (; Pos !=3D ModuleBuildPath.end(); ++Pos) {
+          CyclePath +=3D *Pos;
+          CyclePath +=3D " -> ";
+        }
+        CyclePath +=3D ModuleName;
+
+        getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
+          << ModuleName << CyclePath;
+        return 0;
       }
-      CyclePath +=3D ModuleName.getName();
=20
-      getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
-        << ModuleName.getName() << CyclePath;
+      getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
+        << ModuleName;
+      BuildingModule =3D true;
+      compileModule(*this, Module, ModuleFileName);
+      ModuleFile =3D FileMgr->getFile(ModuleFileName);
+    }
+
+    if (!ModuleFile) {
+      getDiagnostics().Report(ModuleNameLoc,
+                              BuildingModule? diag::err_module_not_built
+                                            : diag::err_module_not_found)
+        << ModuleName
+        << SourceRange(ImportLoc, ModuleNameLoc);
       return 0;
     }
=20
-    getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
-      << ModuleName.getName();
-    BuildingModule =3D true;
-    compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHea=
der);
-    ModuleFile =3D PP->getHeaderSearchInfo().lookupModule(ModuleName.getNa=
me());
+    // If we don't already have an ASTReader, create one now.
+    if (!ModuleManager) {
+      if (!hasASTContext())
+        createASTContext();
+
+      std::string Sysroot =3D getHeaderSearchOpts().Sysroot;
+      const PreprocessorOptions &PPOpts =3D getPreprocessorOpts();
+      ModuleManager =3D new ASTReader(getPreprocessor(), *Context,
+                                    Sysroot.empty() ? "" : Sysroot.c_str(),
+                                    PPOpts.DisablePCHValidation,
+                                    PPOpts.DisableStatCache);
+      if (hasASTConsumer()) {
+        ModuleManager->setDeserializationListener(
+          getASTConsumer().GetASTDeserializationListener());
+        getASTContext().setASTMutationListener(
+          getASTConsumer().GetASTMutationListener());
+      }
+      OwningPtr<ExternalASTSource> Source;
+      Source.reset(ModuleManager);
+      getASTContext().setExternalSource(Source);
+      if (hasSema())
+        ModuleManager->InitializeSema(getSema());
+      if (hasASTConsumer())
+        ModuleManager->StartTranslationUnit(&getASTConsumer());
+    }
+
+    // Try to load the module we found.
+    switch (ModuleManager->ReadAST(ModuleFile->getName(),
+                                   serialization::MK_Module)) {
+    case ASTReader::Success:
+      break;
+
+    case ASTReader::IgnorePCH:
+      // FIXME: The ASTReader will already have complained, but can we sho=
whorn
+      // that diagnostic information into a more useful form?
+      KnownModules[Path[0].first] =3D 0;
+      return 0;
+
+    case ASTReader::Failure:
+      // Already complained, but note now that we failed.
+      KnownModules[Path[0].first] =3D 0;
+      return 0;
+    }
+   =20
+    if (!Module) {
+      // If we loaded the module directly, without finding a module map fi=
rst,
+      // we'll have loaded the module's information from the module itself.
+      Module =3D PP->getHeaderSearchInfo().getModuleMap()
+                 .findModule((Path[0].first->getName()));
+    }
+   =20
+    // Cache the result of this top-level module lookup for later.
+    Known =3D KnownModules.insert(std::make_pair(Path[0].first, Module)).f=
irst;
   }
+ =20
+  // If we never found the module, fail.
+  if (!Module)
+    return 0;
+ =20
+  // Verify that the rest of the module path actually corresponds to
+  // a submodule.
+  if (Path.size() > 1) {
+    for (unsigned I =3D 1, N =3D Path.size(); I !=3D N; ++I) {
+      StringRef Name =3D Path[I].first->getName();
+      clang::Module *Sub =3D Module->findSubmodule(Name);
+     =20
+      if (!Sub) {
+        // Attempt to perform typo correction to find a module name that w=
orks.
+        llvm::SmallVector<StringRef, 2> Best;
+        unsigned BestEditDistance =3D (std::numeric_limits<unsigned>::max)=
();
+       =20
+        for (clang::Module::submodule_iterator J =3D Module->submodule_beg=
in(),=20
+                                            JEnd =3D Module->submodule_end=
();
+             J !=3D JEnd; ++J) {
+          unsigned ED =3D Name.edit_distance((*J)->Name,
+                                           /*AllowReplacements=3D*/true,
+                                           BestEditDistance);
+          if (ED <=3D BestEditDistance) {
+            if (ED < BestEditDistance) {
+              Best.clear();
+              BestEditDistance =3D ED;
+            }
+           =20
+            Best.push_back((*J)->Name);
+          }
+        }
+       =20
+        // If there was a clear winner, user it.
+        if (Best.size() =3D=3D 1) {
+          getDiagnostics().Report(Path[I].second,=20
+                                  diag::err_no_submodule_suggest)
+            << Path[I].first << Module->getFullModuleName() << Best[0]
+            << SourceRange(Path[0].second, Path[I-1].second)
+            << FixItHint::CreateReplacement(SourceRange(Path[I].second),
+                                            Best[0]);
+         =20
+          Sub =3D Module->findSubmodule(Best[0]);
+        }
+      }
+     =20
+      if (!Sub) {
+        // No submodule by this name. Complain, and don't look for further
+        // submodules.
+        getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
+          << Path[I].first << Module->getFullModuleName()
+          << SourceRange(Path[0].second, Path[I-1].second);
+        break;
+      }
+     =20
+      Module =3D Sub;
+    }
+  }
+ =20
+  // Make the named module visible, if it's not already part of the module
+  // we are parsing.
+  if (ModuleName !=3D getLangOpts().CurrentModule) {
+    if (!Module->IsFromModuleFile) {
+      // We have an umbrella header or directory that doesn't actually inc=
lude
+      // all of the headers within the directory it covers. Complain about
+      // this missing submodule and recover by forgetting that we ever saw
+      // this submodule.
+      // FIXME: Should we detect this at module load time? It seems fairly
+      // expensive (and rare).
+      getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
+        << Module->getFullModuleName()
+        << SourceRange(Path.front().second, Path.back().second);
+     =20
+      return 0;
+    }
=20
-  if (!ModuleFile) {
-    getDiagnostics().Report(ModuleNameLoc,
-                            BuildingModule? diag::err_module_not_built
-                                          : diag::err_module_not_found)
-      << ModuleName.getName()
-      << SourceRange(ImportLoc, ModuleNameLoc);
-    return 0;
+    // Check whether this module is available.
+    StringRef Feature;
+    if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) {
+      getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
+        << Module->getFullModuleName()
+        << Feature
+        << SourceRange(Path.front().second, Path.back().second);
+      LastModuleImportLoc =3D ImportLoc;
+      LastModuleImportResult =3D 0;
+      return 0;
+    }
+
+    ModuleManager->makeModuleVisible(Module, Visibility);
   }
-
-  // If we don't already have an ASTReader, create one now.
-  if (!ModuleManager) {
-    if (!hasASTContext())
-      createASTContext();
-
-    std::string Sysroot =3D getHeaderSearchOpts().Sysroot;
-    const PreprocessorOptions &PPOpts =3D getPreprocessorOpts();
-    ModuleManager =3D new ASTReader(getPreprocessor(), *Context,
-                                  Sysroot.empty() ? "" : Sysroot.c_str(),
-                                  PPOpts.DisablePCHValidation,
-                                  PPOpts.DisableStatCache);
-    if (hasASTConsumer()) {
-      ModuleManager->setDeserializationListener(
-        getASTConsumer().GetASTDeserializationListener());
-      getASTContext().setASTMutationListener(
-        getASTConsumer().GetASTMutationListener());
-    }
-    llvm::OwningPtr<ExternalASTSource> Source;
-    Source.reset(ModuleManager);
-    getASTContext().setExternalSource(Source);
-    if (hasSema())
-      ModuleManager->InitializeSema(getSema());
-    if (hasASTConsumer())
-      ModuleManager->StartTranslationUnit(&getASTConsumer());
+ =20
+  // If this module import was due to an inclusion directive, create an=20
+  // implicit import declaration to capture it in the AST.
+  if (IsInclusionDirective && hasASTContext()) {
+    TranslationUnitDecl *TU =3D getASTContext().getTranslationUnitDecl();
+    TU->addDecl(ImportDecl::CreateImplicit(getASTContext(), TU,
+                                           ImportLoc, Module,=20
+                                           Path.back().second));
   }
-
-  // Try to load the module we found.
-  switch (ModuleManager->ReadAST(ModuleFile->getName(),
-                                 serialization::MK_Module)) {
-  case ASTReader::Success:
-    break;
-
-  case ASTReader::IgnorePCH:
-    // FIXME: The ASTReader will already have complained, but can we showh=
orn
-    // that diagnostic information into a more useful form?
-    return 0;
-
-  case ASTReader::Failure:
-    // Already complained.
-    return 0;
-  }
-
-  // FIXME: The module file's FileEntry makes a poor key indeed!
-  return (ModuleKey)ModuleFile;
+ =20
+  LastModuleImportLoc =3D ImportLoc;
+  LastModuleImportResult =3D Module;
+  return Module;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/CompilerInvocation.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/CompilerInvocation.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -30,6 +30,21 @@
 #include "llvm/Support/Path.h"
 using namespace clang;
=20
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Initialization.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+CompilerInvocationBase::CompilerInvocationBase()
+  : LangOpts(new LangOptions()) {}
+
+CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBas=
e &X)
+  : RefCountedBase<CompilerInvocation>(),
+    LangOpts(new LangOptions(*X.getLangOpts())) {}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Utility functions.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
 static const char *getAnalysisStoreName(AnalysisStores Kind) {
   switch (Kind) {
   default:
@@ -63,41 +78,81 @@
 static const char *getAnalysisPurgeModeName(AnalysisPurgeMode Kind) {
   switch (Kind) {
   default:
-    llvm_unreachable("Unknown analysis client!");
+    llvm_unreachable("Unknown analysis purge mode!");
 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
   case NAME: return CMDFLAG;
 #include "clang/Frontend/Analyses.def"
   }
 }
=20
+static const char *getAnalysisIPAModeName(AnalysisIPAMode Kind) {
+  switch (Kind) {
+  default:
+    llvm_unreachable("Unknown analysis ipa mode!");
+#define ANALYSIS_IPA(NAME, CMDFLAG, DESC) \
+  case NAME: return CMDFLAG;
+#include "clang/Frontend/Analyses.def"
+  }
+}
+
+static const char *
+  getAnalysisInliningModeName(AnalysisInliningMode Kind) {
+  switch (Kind) {
+  default:
+    llvm_unreachable("Unknown analysis inlining mode!");
+#define ANALYSIS_INLINE_SELECTION(NAME, CMDFLAG, DESC) \
+  case NAME: return CMDFLAG;
+#include "clang/Frontend/Analyses.def"
+  }
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Serialization (to args)
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-static void AnalyzerOptsToArgs(const AnalyzerOptions &Opts,
-                               std::vector<std::string> &Res) {
+namespace {
+  /// ToArgsList - Helper class to create a list of std::strings.
+  class ToArgsList {
+    std::vector<std::string> &Res;
+  public:
+    explicit ToArgsList(std::vector<std::string> &Res) : Res(Res) {}
+
+    void push_back(StringRef Str) {
+      // Avoid creating a temporary string.
+      Res.push_back(std::string());
+      Res.back().assign(Str.data(), Str.size());
+    }
+
+    void push_back(StringRef Str1, StringRef Str2) {
+      push_back(Str1);
+      push_back(Str2);
+    }
+  };
+}
+
+static void AnalyzerOptsToArgs(const AnalyzerOptions &Opts, ToArgsList &Re=
s) {
   if (Opts.ShowCheckerHelp)
     Res.push_back("-analyzer-checker-help");
-  if (Opts.AnalysisStoreOpt !=3D RegionStoreModel) {
-    Res.push_back("-analyzer-store");
-    Res.push_back(getAnalysisStoreName(Opts.AnalysisStoreOpt));
-  }
-  if (Opts.AnalysisConstraintsOpt !=3D RangeConstraintsModel) {
-    Res.push_back("-analyzer-constraints");
-    Res.push_back(getAnalysisConstraintName(Opts.AnalysisConstraintsOpt));
-  }
-  if (Opts.AnalysisDiagOpt !=3D PD_HTML) {
-    Res.push_back("-analyzer-output");
-    Res.push_back(getAnalysisDiagClientName(Opts.AnalysisDiagOpt));
-  }
-  if (Opts.AnalysisPurgeOpt !=3D PurgeStmt) {
-    Res.push_back("-analyzer-purge");
-    Res.push_back(getAnalysisPurgeModeName(Opts.AnalysisPurgeOpt));
-  }
-  if (!Opts.AnalyzeSpecificFunction.empty()) {
-    Res.push_back("-analyze-function");
-    Res.push_back(Opts.AnalyzeSpecificFunction);
-  }
+  if (Opts.AnalysisStoreOpt !=3D RegionStoreModel)
+    Res.push_back("-analyzer-store",
+                  getAnalysisStoreName(Opts.AnalysisStoreOpt));
+  if (Opts.AnalysisConstraintsOpt !=3D RangeConstraintsModel)
+    Res.push_back("-analyzer-constraints",
+                  getAnalysisConstraintName(Opts.AnalysisConstraintsOpt));
+  if (Opts.AnalysisDiagOpt !=3D PD_HTML)
+    Res.push_back("-analyzer-output",
+                  getAnalysisDiagClientName(Opts.AnalysisDiagOpt));
+  if (Opts.AnalysisPurgeOpt !=3D PurgeStmt)
+    Res.push_back("-analyzer-purge",
+                  getAnalysisPurgeModeName(Opts.AnalysisPurgeOpt));
+  if (!Opts.AnalyzeSpecificFunction.empty())
+    Res.push_back("-analyze-function", Opts.AnalyzeSpecificFunction);
+  if (Opts.IPAMode !=3D Inlining)
+    Res.push_back("-analyzer-ipa", getAnalysisIPAModeName(Opts.IPAMode));
+  if (Opts.InliningMode !=3D NoRedundancy)
+    Res.push_back("-analyzer-inlining-mode",
+                  getAnalysisInliningModeName(Opts.InliningMode));
+
   if (Opts.AnalyzeAll)
     Res.push_back("-analyzer-opt-analyze-headers");
   if (Opts.AnalyzerDisplayProgress)
@@ -112,6 +167,8 @@
     Res.push_back("-analyzer-viz-egraph-graphviz");
   if (Opts.VisualizeEGUbi)
     Res.push_back("-analyzer-viz-egraph-ubigraph");
+  if (Opts.NoRetryExhausted)
+    Res.push_back("-analyzer-disable-retry-exhausted");
=20
   for (unsigned i =3D 0, e =3D Opts.CheckersControlList.size(); i !=3D e; =
++i) {
     const std::pair<std::string, bool> &opt =3D Opts.CheckersControlList[i=
];
@@ -123,18 +180,19 @@
   }
 }
=20
-static void CodeGenOptsToArgs(const CodeGenOptions &Opts,
-                              std::vector<std::string> &Res) {
+static void CodeGenOptsToArgs(const CodeGenOptions &Opts, ToArgsList &Res)=
 {
   if (Opts.DebugInfo)
     Res.push_back("-g");
   if (Opts.DisableLLVMOpts)
     Res.push_back("-disable-llvm-optzns");
   if (Opts.DisableRedZone)
     Res.push_back("-disable-red-zone");
-  if (!Opts.DwarfDebugFlags.empty()) {
-    Res.push_back("-dwarf-debug-flags");
-    Res.push_back(Opts.DwarfDebugFlags);
-  }
+  if (Opts.DisableTailCalls)
+    Res.push_back("-mdisable-tail-calls");
+  if (!Opts.DebugCompilationDir.empty())
+    Res.push_back("-fdebug-compilation-dir", Opts.DebugCompilationDir);
+  if (!Opts.DwarfDebugFlags.empty())
+    Res.push_back("-dwarf-debug-flags", Opts.DwarfDebugFlags);
   if (Opts.ObjCRuntimeHasARC)
     Res.push_back("-fobjc-runtime-has-arc");
   if (Opts.ObjCRuntimeHasTerminate)
@@ -160,10 +218,12 @@
     Opts.OptimizeSize =3D=3D 1 ? Res.push_back("-Os") : Res.push_back("-Oz=
");
   } else if (Opts.OptimizationLevel !=3D 0)
     Res.push_back("-O" + llvm::utostr(Opts.OptimizationLevel));
-  if (!Opts.MainFileName.empty()) {
-    Res.push_back("-main-file-name");
-    Res.push_back(Opts.MainFileName);
-  }
+  if (!Opts.MainFileName.empty())
+    Res.push_back("-main-file-name", Opts.MainFileName);
+  if (Opts.NoInfsFPMath)
+    Res.push_back("-menable-no-infinities");
+  if (Opts.NoNaNsFPMath)
+    Res.push_back("-menable-no-nans");
   // SimplifyLibCalls is only derived.
   // TimePasses is only derived.
   // UnitAtATime is unused.
@@ -179,10 +239,8 @@
     Res.push_back("-ffunction-sections");
   if (Opts.AsmVerbose)
     Res.push_back("-masm-verbose");
-  if (!Opts.CodeModel.empty()) {
-    Res.push_back("-mcode-model");
-    Res.push_back(Opts.CodeModel);
-  }
+  if (!Opts.CodeModel.empty())
+    Res.push_back("-mcode-model", Opts.CodeModel);
   if (Opts.CUDAIsDevice)
     Res.push_back("-fcuda-is-device");
   if (!Opts.CXAAtExit)
@@ -192,19 +250,14 @@
   if (Opts.ObjCAutoRefCountExceptions)
     Res.push_back("-fobjc-arc-eh");
   if (!Opts.DebugPass.empty()) {
-    Res.push_back("-mdebug-pass");
-    Res.push_back(Opts.DebugPass);
+    Res.push_back("-mdebug-pass", Opts.DebugPass);
   }
   if (Opts.DisableFPElim)
     Res.push_back("-mdisable-fp-elim");
-  if (!Opts.FloatABI.empty()) {
-    Res.push_back("-mfloat-abi");
-    Res.push_back(Opts.FloatABI);
-  }
-  if (!Opts.LimitFloatPrecision.empty()) {
-    Res.push_back("-mlimit-float-precision");
-    Res.push_back(Opts.LimitFloatPrecision);
-  }
+  if (!Opts.FloatABI.empty())
+    Res.push_back("-mfloat-abi", Opts.FloatABI);
+  if (!Opts.LimitFloatPrecision.empty())
+    Res.push_back("-mlimit-float-precision", Opts.LimitFloatPrecision);
   if (Opts.NoZeroInitializedInBSS)
     Res.push_back("-mno-zero-initialized-bss");
   switch (Opts.getObjCDispatchMethod()) {
@@ -217,10 +270,8 @@
     Res.push_back("-fobjc-dispatch-method=3Dnon-legacy");
     break;
   }
-  if (Opts.NumRegisterParameters) {
-    Res.push_back("-mregparm");
-    Res.push_back(llvm::utostr(Opts.NumRegisterParameters));
-  }
+  if (Opts.NumRegisterParameters)
+    Res.push_back("-mregparm", llvm::utostr(Opts.NumRegisterParameters));
   if (Opts.NoGlobalMerge)
     Res.push_back("-mno-global-merge");
   if (Opts.NoExecStack)
@@ -231,46 +282,40 @@
     Res.push_back("-msave-temp-labels");
   if (Opts.NoDwarf2CFIAsm)
     Res.push_back("-fno-dwarf2-cfi-asm");
+  if (Opts.NoDwarfDirectoryAsm)
+    Res.push_back("-fno-dwarf-directory-asm");
   if (Opts.SoftFloat)
     Res.push_back("-msoft-float");
+  if (Opts.StrictEnums)
+    Res.push_back("-fstrict-enums");
   if (Opts.UnwindTables)
     Res.push_back("-munwind-tables");
-  if (Opts.RelocationModel !=3D "pic") {
-    Res.push_back("-mrelocation-model");
-    Res.push_back(Opts.RelocationModel);
-  }
+  if (Opts.RelocationModel !=3D "pic")
+    Res.push_back("-mrelocation-model", Opts.RelocationModel);
   if (!Opts.VerifyModule)
     Res.push_back("-disable-llvm-verifier");
-  for (unsigned i =3D 0, e =3D Opts.BackendOptions.size(); i !=3D e; ++i) {
-    Res.push_back("-backend-option");
-    Res.push_back(Opts.BackendOptions[i]);
-  }
+  for (unsigned i =3D 0, e =3D Opts.BackendOptions.size(); i !=3D e; ++i)
+    Res.push_back("-backend-option", Opts.BackendOptions[i]);
 }
=20
 static void DependencyOutputOptsToArgs(const DependencyOutputOptions &Opts,
-                                       std::vector<std::string> &Res) {
+                                       ToArgsList &Res) {
   if (Opts.IncludeSystemHeaders)
     Res.push_back("-sys-header-deps");
   if (Opts.ShowHeaderIncludes)
     Res.push_back("-H");
-  if (!Opts.HeaderIncludeOutputFile.empty()) {
-    Res.push_back("-header-include-file");
-    Res.push_back(Opts.HeaderIncludeOutputFile);
-  }
+  if (!Opts.HeaderIncludeOutputFile.empty())
+    Res.push_back("-header-include-file", Opts.HeaderIncludeOutputFile);
   if (Opts.UsePhonyTargets)
     Res.push_back("-MP");
-  if (!Opts.OutputFile.empty()) {
-    Res.push_back("-dependency-file");
-    Res.push_back(Opts.OutputFile);
-  }
-  for (unsigned i =3D 0, e =3D Opts.Targets.size(); i !=3D e; ++i) {
-    Res.push_back("-MT");
-    Res.push_back(Opts.Targets[i]);
-  }
+  if (!Opts.OutputFile.empty())
+    Res.push_back("-dependency-file", Opts.OutputFile);
+  for (unsigned i =3D 0, e =3D Opts.Targets.size(); i !=3D e; ++i)
+    Res.push_back("-MT", Opts.Targets[i]);
 }
=20
 static void DiagnosticOptsToArgs(const DiagnosticOptions &Opts,
-                                 std::vector<std::string> &Res) {
+                                 ToArgsList &Res) {
   if (Opts.IgnoreWarnings)
     Res.push_back("-w");
   if (Opts.NoRewriteMacros)
@@ -295,8 +340,6 @@
     Res.push_back("-fcolor-diagnostics");
   if (Opts.VerifyDiagnostics)
     Res.push_back("-verify");
-  if (Opts.ShowNames)
-    Res.push_back("-fdiagnostics-show-name");
   if (Opts.ShowOptionNames)
     Res.push_back("-fdiagnostics-show-option");
   if (Opts.ShowCategories =3D=3D 1)
@@ -311,37 +354,29 @@
   case DiagnosticOptions::Vi:   =20
     Res.push_back("-fdiagnostics-format=3Dvi");    break;
   }
-  if (Opts.ErrorLimit) {
-    Res.push_back("-ferror-limit");
-    Res.push_back(llvm::utostr(Opts.ErrorLimit));
-  }
-  if (!Opts.DiagnosticLogFile.empty()) {
-    Res.push_back("-diagnostic-log-file");
-    Res.push_back(Opts.DiagnosticLogFile);
-  }
+  if (Opts.ErrorLimit)
+    Res.push_back("-ferror-limit", llvm::utostr(Opts.ErrorLimit));
+  if (!Opts.DiagnosticLogFile.empty())
+    Res.push_back("-diagnostic-log-file", Opts.DiagnosticLogFile);
   if (Opts.MacroBacktraceLimit
-                        !=3D DiagnosticOptions::DefaultMacroBacktraceLimit=
) {
-    Res.push_back("-fmacro-backtrace-limit");
-    Res.push_back(llvm::utostr(Opts.MacroBacktraceLimit));
-  }
+                        !=3D DiagnosticOptions::DefaultMacroBacktraceLimit)
+    Res.push_back("-fmacro-backtrace-limit",
+                  llvm::utostr(Opts.MacroBacktraceLimit));
   if (Opts.TemplateBacktraceLimit
-                        !=3D DiagnosticOptions::DefaultTemplateBacktraceLi=
mit) {
-    Res.push_back("-ftemplate-backtrace-limit");
-    Res.push_back(llvm::utostr(Opts.TemplateBacktraceLimit));
-  }
+                        !=3D DiagnosticOptions::DefaultTemplateBacktraceLi=
mit)
+    Res.push_back("-ftemplate-backtrace-limit",
+                  llvm::utostr(Opts.TemplateBacktraceLimit));
+  if (Opts.ConstexprBacktraceLimit
+                        !=3D DiagnosticOptions::DefaultConstexprBacktraceL=
imit)
+    Res.push_back("-fconstexpr-backtrace-limit",
+                  llvm::utostr(Opts.ConstexprBacktraceLimit));
=20
-  if (Opts.TabStop !=3D DiagnosticOptions::DefaultTabStop) {
-    Res.push_back("-ftabstop");
-    Res.push_back(llvm::utostr(Opts.TabStop));
-  }
-  if (Opts.MessageLength) {
-    Res.push_back("-fmessage-length");
-    Res.push_back(llvm::utostr(Opts.MessageLength));
-  }
-  if (!Opts.DumpBuildInformation.empty()) {
-    Res.push_back("-dump-build-information");
-    Res.push_back(Opts.DumpBuildInformation);
-  }
+  if (Opts.TabStop !=3D DiagnosticOptions::DefaultTabStop)
+    Res.push_back("-ftabstop", llvm::utostr(Opts.TabStop));
+  if (Opts.MessageLength)
+    Res.push_back("-fmessage-length", llvm::utostr(Opts.MessageLength));
+  if (!Opts.DumpBuildInformation.empty())
+    Res.push_back("-dump-build-information", Opts.DumpBuildInformation);
   for (unsigned i =3D 0, e =3D Opts.Warnings.size(); i !=3D e; ++i)
     Res.push_back("-W" + Opts.Warnings[i]);
 }
@@ -365,7 +400,6 @@
   }
=20
   llvm_unreachable("Unexpected language kind!");
-  return 0;
 }
=20
 static const char *getActionName(frontend::ActionKind Kind) {
@@ -395,27 +429,24 @@
   case frontend::PrintDeclContext:       return "-print-decl-contexts";
   case frontend::PrintPreamble:          return "-print-preamble";
   case frontend::PrintPreprocessedInput: return "-E";
+  case frontend::PubnamesDump:           return "-pubnames-dump";
   case frontend::RewriteMacros:          return "-rewrite-macros";
   case frontend::RewriteObjC:            return "-rewrite-objc";
   case frontend::RewriteTest:            return "-rewrite-test";
   case frontend::RunAnalysis:            return "-analyze";
+  case frontend::MigrateSource:          return "-migrate";
   case frontend::RunPreprocessorOnly:    return "-Eonly";
   }
=20
   llvm_unreachable("Unexpected language kind!");
-  return 0;
 }
=20
-static void FileSystemOptsToArgs(const FileSystemOptions &Opts,
-                                 std::vector<std::string> &Res) {
-  if (!Opts.WorkingDir.empty()) {
-    Res.push_back("-working-directory");
-    Res.push_back(Opts.WorkingDir);
-  }
+static void FileSystemOptsToArgs(const FileSystemOptions &Opts, ToArgsList=
 &Res){
+  if (!Opts.WorkingDir.empty())
+    Res.push_back("-working-directory", Opts.WorkingDir);
 }
=20
-static void FrontendOptsToArgs(const FrontendOptions &Opts,
-                               std::vector<std::string> &Res) {
+static void FrontendOptsToArgs(const FrontendOptions &Opts, ToArgsList &Re=
s) {
   if (Opts.DisableFree)
     Res.push_back("-disable-free");
   if (Opts.RelocatablePCH)
@@ -436,6 +467,12 @@
     Res.push_back("-version");
   if (Opts.FixWhatYouCan)
     Res.push_back("-fix-what-you-can");
+  if (Opts.FixOnlyWarnings)
+    Res.push_back("-fix-only-warnings");
+  if (Opts.FixAndRecompile)
+    Res.push_back("-fixit-recompile");
+  if (Opts.FixToTemporaries)
+    Res.push_back("-fixit-to-temporary");
   switch (Opts.ARCMTAction) {
   case FrontendOptions::ARCMT_None:
     break;
@@ -449,76 +486,63 @@
     Res.push_back("-arcmt-migrate");
     break;
   }
-  if (!Opts.ARCMTMigrateDir.empty()) {
-    Res.push_back("-arcmt-migrate-directory");
-    Res.push_back(Opts.ARCMTMigrateDir);
-  }
-  if (!Opts.ARCMTMigrateReportOut.empty()) {
-    Res.push_back("-arcmt-migrate-report-output");
-    Res.push_back(Opts.ARCMTMigrateReportOut);
-  }
+  if (!Opts.MTMigrateDir.empty())
+    Res.push_back("-mt-migrate-directory", Opts.MTMigrateDir);
+  if (!Opts.ARCMTMigrateReportOut.empty())
+    Res.push_back("-arcmt-migrate-report-output", Opts.ARCMTMigrateReportO=
ut);
   if (Opts.ARCMTMigrateEmitARCErrors)
     Res.push_back("-arcmt-migrate-emit-errors");
=20
+  if (Opts.ObjCMTAction & ~FrontendOptions::ObjCMT_Literals)
+    Res.push_back("-objcmt-migrate-literals");
+  if (Opts.ObjCMTAction & ~FrontendOptions::ObjCMT_Subscripting)
+    Res.push_back("-objcmt-migrate-subscripting");
+
   bool NeedLang =3D false;
   for (unsigned i =3D 0, e =3D Opts.Inputs.size(); i !=3D e; ++i)
-    if (FrontendOptions::getInputKindForExtension(Opts.Inputs[i].second) !=
=3D
-        Opts.Inputs[i].first)
+    if (FrontendOptions::getInputKindForExtension(Opts.Inputs[i].File) !=
=3D
+        Opts.Inputs[i].Kind)
       NeedLang =3D true;
-  if (NeedLang) {
-    Res.push_back("-x");
-    Res.push_back(getInputKindName(Opts.Inputs[0].first));
-  }
+  if (NeedLang)
+    Res.push_back("-x", getInputKindName(Opts.Inputs[0].Kind));
   for (unsigned i =3D 0, e =3D Opts.Inputs.size(); i !=3D e; ++i) {
-    assert((!NeedLang || Opts.Inputs[i].first =3D=3D Opts.Inputs[0].first)=
 &&
+    assert((!NeedLang || Opts.Inputs[i].Kind =3D=3D Opts.Inputs[0].Kind) &&
            "Unable to represent this input vector!");
-    Res.push_back(Opts.Inputs[i].second);
+    Res.push_back(Opts.Inputs[i].File);
   }
=20
-  if (!Opts.OutputFile.empty()) {
-    Res.push_back("-o");
-    Res.push_back(Opts.OutputFile);
-  }
-  if (!Opts.CodeCompletionAt.FileName.empty()) {
-    Res.push_back("-code-completion-at");
-    Res.push_back(Opts.CodeCompletionAt.FileName + ":" +
+  if (!Opts.OutputFile.empty())
+    Res.push_back("-o", Opts.OutputFile);
+  if (!Opts.CodeCompletionAt.FileName.empty())
+    Res.push_back("-code-completion-at",
+                  Opts.CodeCompletionAt.FileName + ":" +
                   llvm::utostr(Opts.CodeCompletionAt.Line) + ":" +
                   llvm::utostr(Opts.CodeCompletionAt.Column));
-  }
   if (Opts.ProgramAction !=3D frontend::PluginAction)
     Res.push_back(getActionName(Opts.ProgramAction));
   if (!Opts.ActionName.empty()) {
-    Res.push_back("-plugin");
-    Res.push_back(Opts.ActionName);
-    for(unsigned i =3D 0, e =3D Opts.PluginArgs.size(); i !=3D e; ++i) {
-      Res.push_back("-plugin-arg-" + Opts.ActionName);
-      Res.push_back(Opts.PluginArgs[i]);
-    }
+    Res.push_back("-plugin", Opts.ActionName);
+    for(unsigned i =3D 0, e =3D Opts.PluginArgs.size(); i !=3D e; ++i)
+      Res.push_back("-plugin-arg-" + Opts.ActionName, Opts.PluginArgs[i]);
   }
-  for (unsigned i =3D 0, e =3D Opts.Plugins.size(); i !=3D e; ++i) {
-    Res.push_back("-load");
-    Res.push_back(Opts.Plugins[i]);
+  for (unsigned i =3D 0, e =3D Opts.Plugins.size(); i !=3D e; ++i)
+    Res.push_back("-load", Opts.Plugins[i]);
+  for (unsigned i =3D 0, e =3D Opts.AddPluginActions.size(); i !=3D e; ++i=
) {
+    Res.push_back("-add-plugin", Opts.AddPluginActions[i]);
+    for(unsigned ai =3D 0, ae =3D Opts.AddPluginArgs.size(); ai !=3D ae; +=
+ai)
+      Res.push_back("-plugin-arg-" + Opts.AddPluginActions[i],
+                    Opts.AddPluginArgs[i][ai]);
   }
-  for (unsigned i =3D 0, e =3D Opts.AddPluginActions.size(); i !=3D e; ++i=
) {
-    Res.push_back("-add-plugin");
-    Res.push_back(Opts.AddPluginActions[i]);
-    for(unsigned ai =3D 0, ae =3D Opts.AddPluginArgs.size(); ai !=3D ae; +=
+ai) {
-      Res.push_back("-plugin-arg-" + Opts.AddPluginActions[i]);
-      Res.push_back(Opts.AddPluginArgs[i][ai]);
-    }
-  }
-  for (unsigned i =3D 0, e =3D Opts.ASTMergeFiles.size(); i !=3D e; ++i) {
-    Res.push_back("-ast-merge");
-    Res.push_back(Opts.ASTMergeFiles[i]);
-  }
-  for (unsigned i =3D 0, e =3D Opts.LLVMArgs.size(); i !=3D e; ++i) {
-    Res.push_back("-mllvm");
-    Res.push_back(Opts.LLVMArgs[i]);
-  }
+  for (unsigned i =3D 0, e =3D Opts.ASTMergeFiles.size(); i !=3D e; ++i)
+    Res.push_back("-ast-merge", Opts.ASTMergeFiles[i]);
+  for (unsigned i =3D 0, e =3D Opts.LLVMArgs.size(); i !=3D e; ++i)
+    Res.push_back("-mllvm", Opts.LLVMArgs[i]);
+  if (!Opts.OverrideRecordLayoutsFile.empty())
+    Res.push_back("-foverride-record-layout=3D" + Opts.OverrideRecordLayou=
tsFile);
 }
=20
 static void HeaderSearchOptsToArgs(const HeaderSearchOptions &Opts,
-                                   std::vector<std::string> &Res) {
+                                   ToArgsList &Res) {
   if (Opts.Sysroot !=3D "/") {
     Res.push_back("-isysroot");
     Res.push_back(Opts.Sysroot);
@@ -585,14 +609,10 @@
     Res.push_back(E.Path);
   }
=20
-  if (!Opts.ResourceDir.empty()) {
-    Res.push_back("-resource-dir");
-    Res.push_back(Opts.ResourceDir);
-  }
-  if (!Opts.ModuleCachePath.empty()) {
-    Res.push_back("-fmodule-cache-path");
-    Res.push_back(Opts.ModuleCachePath);
-  }
+  if (!Opts.ResourceDir.empty())
+    Res.push_back("-resource-dir", Opts.ResourceDir);
+  if (!Opts.ModuleCachePath.empty())
+    Res.push_back("-fmodule-cache-path", Opts.ModuleCachePath);
   if (!Opts.UseStandardSystemIncludes)
     Res.push_back("-nostdsysteminc");
   if (!Opts.UseStandardCXXIncludes)
@@ -603,8 +623,7 @@
     Res.push_back("-v");
 }
=20
-static void LangOptsToArgs(const LangOptions &Opts,
-                           std::vector<std::string> &Res) {
+static void LangOptsToArgs(const LangOptions &Opts, ToArgsList &Res) {
   LangOptions DefaultLangOpts;
=20
   // FIXME: Need to set -std to get all the implicit options.
@@ -629,6 +648,8 @@
     Res.push_back("-fgnu-keywords");
   if (Opts.MicrosoftExt)
     Res.push_back("-fms-extensions");
+  if (Opts.MicrosoftMode)
+    Res.push_back("-fms-compatibility");
   if (Opts.MSCVersion !=3D 0)
     Res.push_back("-fmsc-version=3D" + llvm::utostr(Opts.MSCVersion));
   if (Opts.Borland)
@@ -644,6 +665,10 @@
     Res.push_back("-fpascal-strings");
   if (Opts.CatchUndefined)
     Res.push_back("-fcatch-undefined-behavior");
+  if (Opts.AddressSanitizer)
+    Res.push_back("-faddress-sanitizer");
+  if (Opts.ThreadSanitizer)
+    Res.push_back("-fthread-sanitizer");
   if (Opts.WritableStrings)
     Res.push_back("-fwritable-strings");
   if (Opts.ConstStrings)
@@ -684,6 +709,8 @@
     Res.push_back("-fblocks");
   if (Opts.BlocksRuntimeOptional)
     Res.push_back("-fblocks-runtime-optional");
+  if (Opts.Modules)
+    Res.push_back("-fmodules");
   if (Opts.EmitAllDecls)
     Res.push_back("-femit-all-decls");
   if (Opts.MathErrno)
@@ -692,28 +719,31 @@
   case LangOptions::SOB_Undefined: break;
   case LangOptions::SOB_Defined:   Res.push_back("-fwrapv"); break;
   case LangOptions::SOB_Trapping:
-    Res.push_back("-ftrapv"); break;
-    if (!Opts.OverflowHandler.empty()) {
-      Res.push_back("-ftrapv-handler");
-      Res.push_back(Opts.OverflowHandler);
-    }
+    Res.push_back("-ftrapv");
+    if (!Opts.OverflowHandler.empty())
+      Res.push_back("-ftrapv-handler", Opts.OverflowHandler);
+    break;
   }
   if (Opts.HeinousExtensions)
     Res.push_back("-fheinous-gnu-extensions");
   // Optimize is implicit.
   // OptimizeSize is implicit.
+  if (Opts.FastMath)
+    Res.push_back("-ffast-math");
   if (Opts.Static)
     Res.push_back("-static-define");
-  if (Opts.DumpRecordLayouts)
+  if (Opts.DumpRecordLayoutsSimple)
+    Res.push_back("-fdump-record-layouts-simple");
+  else if (Opts.DumpRecordLayouts)
     Res.push_back("-fdump-record-layouts");
   if (Opts.DumpVTableLayouts)
     Res.push_back("-fdump-vtable-layouts");
   if (Opts.NoBitFieldTypeAlign)
     Res.push_back("-fno-bitfield-type-alignment");
-  if (Opts.PICLevel) {
-    Res.push_back("-pic-level");
-    Res.push_back(llvm::utostr(Opts.PICLevel));
-  }
+  if (Opts.PICLevel)
+    Res.push_back("-pic-level", llvm::utostr(Opts.PICLevel));
+  if (Opts.PIELevel)
+    Res.push_back("-pie-level", llvm::utostr(Opts.PIELevel));
   if (Opts.ObjCGCBitmapPrint)
     Res.push_back("-print-ivar-layout");
   if (Opts.NoConstantCFStrings)
@@ -757,77 +787,70 @@
   if (Opts.InlineVisibilityHidden)
     Res.push_back("-fvisibility-inlines-hidden");
=20
-  if (Opts.getStackProtector() !=3D 0) {
-    Res.push_back("-stack-protector");
-    Res.push_back(llvm::utostr(Opts.getStackProtector()));
-  }
-  if (Opts.InstantiationDepth !=3D DefaultLangOpts.InstantiationDepth) {
-    Res.push_back("-ftemplate-depth");
-    Res.push_back(llvm::utostr(Opts.InstantiationDepth));
-  }
-  if (!Opts.ObjCConstantStringClass.empty()) {
-    Res.push_back("-fconstant-string-class");
-    Res.push_back(Opts.ObjCConstantStringClass);
-  }
+  if (Opts.getStackProtector() !=3D 0)
+    Res.push_back("-stack-protector", llvm::utostr(Opts.getStackProtector(=
)));
+  if (Opts.InstantiationDepth !=3D DefaultLangOpts.InstantiationDepth)
+    Res.push_back("-ftemplate-depth", llvm::utostr(Opts.InstantiationDepth=
));
+  if (Opts.ConstexprCallDepth !=3D DefaultLangOpts.ConstexprCallDepth)
+    Res.push_back("-fconstexpr-depth", llvm::utostr(Opts.ConstexprCallDept=
h));
+  if (!Opts.ObjCConstantStringClass.empty())
+    Res.push_back("-fconstant-string-class", Opts.ObjCConstantStringClass);
   if (Opts.FakeAddressSpaceMap)
     Res.push_back("-ffake-address-space-map");
   if (Opts.ParseUnknownAnytype)
     Res.push_back("-funknown-anytype");
   if (Opts.DebuggerSupport)
     Res.push_back("-fdebugger-support");
+  if (Opts.DebuggerCastResultToId)
+    Res.push_back("-fdebugger-cast-result-to-id");
+  if (Opts.DebuggerObjCLiteral)
+    Res.push_back("-fdebugger-objc-literal");
   if (Opts.DelayedTemplateParsing)
     Res.push_back("-fdelayed-template-parsing");
   if (Opts.Deprecated)
     Res.push_back("-fdeprecated-macro");
+  if (Opts.ApplePragmaPack)
+    Res.push_back("-fapple-pragma-pack");
+  if (!Opts.CurrentModule.empty())
+    Res.push_back("-fmodule-name=3D" + Opts.CurrentModule);
 }
=20
 static void PreprocessorOptsToArgs(const PreprocessorOptions &Opts,
-                                   std::vector<std::string> &Res) {
+                                   ToArgsList &Res) {
   for (unsigned i =3D 0, e =3D Opts.Macros.size(); i !=3D e; ++i)
     Res.push_back(std::string(Opts.Macros[i].second ? "-U" : "-D") +
                   Opts.Macros[i].first);
   for (unsigned i =3D 0, e =3D Opts.Includes.size(); i !=3D e; ++i) {
     // FIXME: We need to avoid reincluding the implicit PCH and PTH includ=
es.
-    Res.push_back("-include");
-    Res.push_back(Opts.Includes[i]);
+    Res.push_back("-include", Opts.Includes[i]);
   }
-  for (unsigned i =3D 0, e =3D Opts.MacroIncludes.size(); i !=3D e; ++i) {
-    Res.push_back("-imacros");
-    Res.push_back(Opts.MacroIncludes[i]);
-  }
+  for (unsigned i =3D 0, e =3D Opts.MacroIncludes.size(); i !=3D e; ++i)
+    Res.push_back("-imacros", Opts.MacroIncludes[i]);
   if (!Opts.UsePredefines)
     Res.push_back("-undef");
   if (Opts.DetailedRecord)
     Res.push_back("-detailed-preprocessing-record");
-  if (!Opts.ImplicitPCHInclude.empty()) {
-    Res.push_back("-include-pch");
-    Res.push_back(Opts.ImplicitPCHInclude);
-  }
-  if (!Opts.ImplicitPTHInclude.empty()) {
-    Res.push_back("-include-pth");
-    Res.push_back(Opts.ImplicitPTHInclude);
-  }
+  if (!Opts.ImplicitPCHInclude.empty())
+    Res.push_back("-include-pch", Opts.ImplicitPCHInclude);
+  if (!Opts.ImplicitPTHInclude.empty())
+    Res.push_back("-include-pth", Opts.ImplicitPTHInclude);
   if (!Opts.TokenCache.empty()) {
-    if (Opts.ImplicitPTHInclude.empty()) {
-      Res.push_back("-token-cache");
-      Res.push_back(Opts.TokenCache);
-    } else
+    if (Opts.ImplicitPTHInclude.empty())
+      Res.push_back("-token-cache", Opts.TokenCache);
+    else
       assert(Opts.ImplicitPTHInclude =3D=3D Opts.TokenCache &&
              "Unsupported option combination!");
   }
-  for (unsigned i =3D 0, e =3D Opts.ChainedIncludes.size(); i !=3D e; ++i)=
 {
-    Res.push_back("-chain-include");
-    Res.push_back(Opts.ChainedIncludes[i]);
-  }
+  for (unsigned i =3D 0, e =3D Opts.ChainedIncludes.size(); i !=3D e; ++i)
+    Res.push_back("-chain-include", Opts.ChainedIncludes[i]);
   for (unsigned i =3D 0, e =3D Opts.RemappedFiles.size(); i !=3D e; ++i) {
-    Res.push_back("-remap-file");
-    Res.push_back(Opts.RemappedFiles[i].first + ";" +
-                  Opts.RemappedFiles[i].second);
+    Res.push_back("-remap-file", Opts.RemappedFiles[i].first + ";" +
+                                 Opts.RemappedFiles[i].second);
   }
 }
=20
 static void PreprocessorOutputOptsToArgs(const PreprocessorOutputOptions &=
Opts,
-                                         std::vector<std::string> &Res) {
+                                         ToArgsList &Res) {
   if (!Opts.ShowCPP && !Opts.ShowMacros)
     llvm::report_fatal_error("Invalid option combination!");
=20
@@ -845,43 +868,34 @@
 }
=20
 static void TargetOptsToArgs(const TargetOptions &Opts,
-                             std::vector<std::string> &Res) {
+                             ToArgsList &Res) {
   Res.push_back("-triple");
   Res.push_back(Opts.Triple);
-  if (!Opts.CPU.empty()) {
-    Res.push_back("-target-cpu");
-    Res.push_back(Opts.CPU);
-  }
-  if (!Opts.ABI.empty()) {
-    Res.push_back("-target-abi");
-    Res.push_back(Opts.ABI);
-  }
-  if (!Opts.LinkerVersion.empty()) {
-    Res.push_back("-target-linker-version");
-    Res.push_back(Opts.LinkerVersion);
-  }
-  if (!Opts.CXXABI.empty()) {
-    Res.push_back("-cxx-abi");
-    Res.push_back(Opts.CXXABI);
-  }
-  for (unsigned i =3D 0, e =3D Opts.Features.size(); i !=3D e; ++i) {
-    Res.push_back("-target-feature");
-    Res.push_back(Opts.Features[i]);
-  }
+  if (!Opts.CPU.empty())
+    Res.push_back("-target-cpu", Opts.CPU);
+  if (!Opts.ABI.empty())
+    Res.push_back("-target-abi", Opts.ABI);
+  if (!Opts.LinkerVersion.empty())
+    Res.push_back("-target-linker-version", Opts.LinkerVersion);
+  if (!Opts.CXXABI.empty())
+    Res.push_back("-cxx-abi", Opts.CXXABI);
+  for (unsigned i =3D 0, e =3D Opts.Features.size(); i !=3D e; ++i)
+    Res.push_back("-target-feature", Opts.Features[i]);
 }
=20
 void CompilerInvocation::toArgs(std::vector<std::string> &Res) {
-  AnalyzerOptsToArgs(getAnalyzerOpts(), Res);
-  CodeGenOptsToArgs(getCodeGenOpts(), Res);
-  DependencyOutputOptsToArgs(getDependencyOutputOpts(), Res);
-  DiagnosticOptsToArgs(getDiagnosticOpts(), Res);
-  FileSystemOptsToArgs(getFileSystemOpts(), Res);
-  FrontendOptsToArgs(getFrontendOpts(), Res);
-  HeaderSearchOptsToArgs(getHeaderSearchOpts(), Res);
-  LangOptsToArgs(getLangOpts(), Res);
-  PreprocessorOptsToArgs(getPreprocessorOpts(), Res);
-  PreprocessorOutputOptsToArgs(getPreprocessorOutputOpts(), Res);
-  TargetOptsToArgs(getTargetOpts(), Res);
+  ToArgsList List(Res);
+  AnalyzerOptsToArgs(getAnalyzerOpts(), List);
+  CodeGenOptsToArgs(getCodeGenOpts(), List);
+  DependencyOutputOptsToArgs(getDependencyOutputOpts(), List);
+  DiagnosticOptsToArgs(getDiagnosticOpts(), List);
+  FileSystemOptsToArgs(getFileSystemOpts(), List);
+  FrontendOptsToArgs(getFrontendOpts(), List);
+  HeaderSearchOptsToArgs(getHeaderSearchOpts(), List);
+  LangOptsToArgs(*getLangOpts(), List);
+  PreprocessorOptsToArgs(getPreprocessorOpts(), List);
+  PreprocessorOutputOptsToArgs(getPreprocessorOutputOpts(), List);
+  TargetOptsToArgs(getTargetOpts(), List);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -903,10 +917,10 @@
     Args.getLastArgIntValue(OPT_O, DefaultOpt, Diags);
 }
=20
-static void ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
+static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
                               DiagnosticsEngine &Diags) {
   using namespace cc1options;
-
+  bool Success =3D true;
   if (Arg *A =3D Args.getLastArg(OPT_analyzer_store)) {
     StringRef Name =3D A->getValue(Args);
     AnalysisStores Value =3D llvm::StringSwitch<AnalysisStores>(Name)
@@ -914,12 +928,13 @@
       .Case(CMDFLAG, NAME##Model)
 #include "clang/Frontend/Analyses.def"
       .Default(NumStores);
-    // FIXME: Error handling.
-    if (Value =3D=3D NumStores)
+    if (Value =3D=3D NumStores) {
       Diags.Report(diag::err_drv_invalid_value)
         << A->getAsString(Args) << Name;
-    else
+      Success =3D false;
+    } else {
       Opts.AnalysisStoreOpt =3D Value;
+    }
   }
=20
   if (Arg *A =3D Args.getLastArg(OPT_analyzer_constraints)) {
@@ -929,12 +944,13 @@
       .Case(CMDFLAG, NAME##Model)
 #include "clang/Frontend/Analyses.def"
       .Default(NumConstraints);
-    // FIXME: Error handling.
-    if (Value =3D=3D NumConstraints)
+    if (Value =3D=3D NumConstraints) {
       Diags.Report(diag::err_drv_invalid_value)
         << A->getAsString(Args) << Name;
-    else
+      Success =3D false;
+    } else {
       Opts.AnalysisConstraintsOpt =3D Value;
+    }
   }
=20
   if (Arg *A =3D Args.getLastArg(OPT_analyzer_output)) {
@@ -944,12 +960,13 @@
       .Case(CMDFLAG, PD_##NAME)
 #include "clang/Frontend/Analyses.def"
       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
-    // FIXME: Error handling.
-    if (Value =3D=3D NUM_ANALYSIS_DIAG_CLIENTS)
+    if (Value =3D=3D NUM_ANALYSIS_DIAG_CLIENTS) {
       Diags.Report(diag::err_drv_invalid_value)
         << A->getAsString(Args) << Name;
-    else
+      Success =3D false;
+    } else {
       Opts.AnalysisDiagOpt =3D Value;
+    }
   }
=20
   if (Arg *A =3D Args.getLastArg(OPT_analyzer_purge)) {
@@ -959,17 +976,51 @@
       .Case(CMDFLAG, NAME)
 #include "clang/Frontend/Analyses.def"
       .Default(NumPurgeModes);
-    // FIXME: Error handling.
-    if (Value =3D=3D NumPurgeModes)
+    if (Value =3D=3D NumPurgeModes) {
       Diags.Report(diag::err_drv_invalid_value)
         << A->getAsString(Args) << Name;
-    else
+      Success =3D false;
+    } else {
       Opts.AnalysisPurgeOpt =3D Value;
+    }
+  }
+
+  if (Arg *A =3D Args.getLastArg(OPT_analyzer_ipa)) {
+    StringRef Name =3D A->getValue(Args);
+    AnalysisIPAMode Value =3D llvm::StringSwitch<AnalysisIPAMode>(Name)
+#define ANALYSIS_IPA(NAME, CMDFLAG, DESC) \
+      .Case(CMDFLAG, NAME)
+#include "clang/Frontend/Analyses.def"
+      .Default(NumIPAModes);
+    if (Value =3D=3D NumIPAModes) {
+      Diags.Report(diag::err_drv_invalid_value)
+        << A->getAsString(Args) << Name;
+      Success =3D false;
+    } else {
+      Opts.IPAMode =3D Value;
+    }
+  }
+
+  if (Arg *A =3D Args.getLastArg(OPT_analyzer_inlining_mode)) {
+    StringRef Name =3D A->getValue(Args);
+    AnalysisInliningMode Value =3D llvm::StringSwitch<AnalysisInliningMode=
>(Name)
+#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
+      .Case(CMDFLAG, NAME)
+#include "clang/Frontend/Analyses.def"
+      .Default(NumInliningModes);
+    if (Value =3D=3D NumInliningModes) {
+      Diags.Report(diag::err_drv_invalid_value)
+        << A->getAsString(Args) << Name;
+      Success =3D false;
+    } else {
+      Opts.InliningMode =3D Value;
+    }
   }
=20
   Opts.ShowCheckerHelp =3D Args.hasArg(OPT_analyzer_checker_help);
   Opts.VisualizeEGDot =3D Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
   Opts.VisualizeEGUbi =3D Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
+  Opts.NoRetryExhausted =3D Args.hasArg(OPT_analyzer_disable_retry_exhaust=
ed);
   Opts.AnalyzeAll =3D Args.hasArg(OPT_analyzer_opt_analyze_headers);
   Opts.AnalyzerDisplayProgress =3D Args.hasArg(OPT_analyzer_display_progre=
ss);
   Opts.AnalyzeNestedBlocks =3D
@@ -983,7 +1034,13 @@
   Opts.MaxNodes =3D Args.getLastArgIntValue(OPT_analyzer_max_nodes, 150000=
,Diags);
   Opts.MaxLoop =3D Args.getLastArgIntValue(OPT_analyzer_max_loop, 4, Diags=
);
   Opts.EagerlyTrimEGraph =3D !Args.hasArg(OPT_analyzer_no_eagerly_trim_egr=
aph);
-  Opts.InlineCall =3D Args.hasArg(OPT_analyzer_inline_call);
+  Opts.PrintStats =3D Args.hasArg(OPT_analyzer_stats);
+  Opts.InlineMaxStackDepth =3D
+    Args.getLastArgIntValue(OPT_analyzer_inline_max_stack_depth,
+                            Opts.InlineMaxStackDepth, Diags);
+  Opts.InlineMaxFunctionSize =3D
+    Args.getLastArgIntValue(OPT_analyzer_inline_max_function_size,
+                            Opts.InlineMaxFunctionSize, Diags);
=20
   Opts.CheckersControlList.clear();
   for (arg_iterator it =3D Args.filtered_begin(OPT_analyzer_checker,
@@ -1000,25 +1057,41 @@
     for (unsigned i =3D 0, e =3D checkers.size(); i !=3D e; ++i)
       Opts.CheckersControlList.push_back(std::make_pair(checkers[i], enabl=
e));
   }
+
+  return Success;
 }
=20
-static void ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKin=
d IK,
+static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
+  Opts.NoNSAllocReallocError =3D Args.hasArg(OPT_migrator_no_nsalloc_error=
);
+  Opts.NoFinalizeRemoval =3D Args.hasArg(OPT_migrator_no_finalize_removal);
+  return true;
+}
+
+static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKin=
d IK,
                              DiagnosticsEngine &Diags) {
   using namespace cc1options;
+  bool Success =3D true;
=20
-  Opts.OptimizationLevel =3D getOptimizationLevel(Args, IK, Diags);
-  if (Opts.OptimizationLevel > 3) {
+  unsigned OptLevel =3D getOptimizationLevel(Args, IK, Diags);
+  if (OptLevel > 3) {
     Diags.Report(diag::err_drv_invalid_value)
-      << Args.getLastArg(OPT_O)->getAsString(Args) << Opts.OptimizationLev=
el;
-    Opts.OptimizationLevel =3D 3;
+      << Args.getLastArg(OPT_O)->getAsString(Args) << OptLevel;
+    OptLevel =3D 3;
+    Success =3D false;
   }
+  Opts.OptimizationLevel =3D OptLevel;
=20
   // We must always run at least the always inlining pass.
   Opts.Inlining =3D (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalI=
nlining
     : CodeGenOptions::OnlyAlwaysInlining;
+  // -fno-inline-functions overrides OptimizationLevel > 1.
+  Opts.NoInline =3D Args.hasArg(OPT_fno_inline);
+  Opts.Inlining =3D Args.hasArg(OPT_fno_inline_functions) ?=20
+    CodeGenOptions::OnlyAlwaysInlining : Opts.Inlining;
=20
   Opts.DebugInfo =3D Args.hasArg(OPT_g);
-  Opts.LimitDebugInfo =3D Args.hasArg(OPT_flimit_debug_info);
+  Opts.LimitDebugInfo =3D !Args.hasArg(OPT_fno_limit_debug_info)
+    || Args.hasArg(OPT_flimit_debug_info);
   Opts.DisableLLVMOpts =3D Args.hasArg(OPT_disable_llvm_optzns);
   Opts.DisableRedZone =3D Args.hasArg(OPT_disable_red_zone);
   Opts.ForbidGuardVariables =3D Args.hasArg(OPT_fforbid_guard_variables);
@@ -1046,12 +1119,17 @@
   Opts.CodeModel =3D Args.getLastArgValue(OPT_mcode_model);
   Opts.DebugPass =3D Args.getLastArgValue(OPT_mdebug_pass);
   Opts.DisableFPElim =3D Args.hasArg(OPT_mdisable_fp_elim);
+  Opts.DisableTailCalls =3D Args.hasArg(OPT_mdisable_tail_calls);
   Opts.FloatABI =3D Args.getLastArgValue(OPT_mfloat_abi);
   Opts.HiddenWeakVTables =3D Args.hasArg(OPT_fhidden_weak_vtables);
   Opts.LessPreciseFPMAD =3D Args.hasArg(OPT_cl_mad_enable);
   Opts.LimitFloatPrecision =3D Args.getLastArgValue(OPT_mlimit_float_preci=
sion);
-  Opts.NoInfsFPMath =3D Opts.NoNaNsFPMath =3D Args.hasArg(OPT_cl_finite_ma=
th_only)||
-                                          Args.hasArg(OPT_cl_fast_relaxed_=
math);
+  Opts.NoInfsFPMath =3D (Args.hasArg(OPT_menable_no_infinities) ||
+                       Args.hasArg(OPT_cl_finite_math_only)||
+                       Args.hasArg(OPT_cl_fast_relaxed_math));
+  Opts.NoNaNsFPMath =3D (Args.hasArg(OPT_menable_no_nans) ||
+                       Args.hasArg(OPT_cl_finite_math_only)||
+                       Args.hasArg(OPT_cl_fast_relaxed_math));
   Opts.NoZeroInitializedInBSS =3D Args.hasArg(OPT_mno_zero_initialized_in_=
bss);
   Opts.BackendOptions =3D Args.getAllArgValues(OPT_backend_option);
   Opts.NumRegisterParameters =3D Args.getLastArgIntValue(OPT_mregparm, 0, =
Diags);
@@ -1061,11 +1139,15 @@
   Opts.OmitLeafFramePointer =3D Args.hasArg(OPT_momit_leaf_frame_pointer);
   Opts.SaveTempLabels =3D Args.hasArg(OPT_msave_temp_labels);
   Opts.NoDwarf2CFIAsm =3D Args.hasArg(OPT_fno_dwarf2_cfi_asm);
+  Opts.NoDwarfDirectoryAsm =3D Args.hasArg(OPT_fno_dwarf_directory_asm);
   Opts.SoftFloat =3D Args.hasArg(OPT_msoft_float);
-  Opts.UnsafeFPMath =3D Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
+  Opts.StrictEnums =3D Args.hasArg(OPT_fstrict_enums);
+  Opts.UnsafeFPMath =3D Args.hasArg(OPT_menable_unsafe_fp_math) ||
+                      Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
                       Args.hasArg(OPT_cl_fast_relaxed_math);
   Opts.UnwindTables =3D Args.hasArg(OPT_munwind_tables);
   Opts.RelocationModel =3D Args.getLastArgValue(OPT_mrelocation_model, "pi=
c");
+  Opts.TrapFuncName =3D Args.getLastArgValue(OPT_ftrap_function_EQ);
=20
   Opts.FunctionSections =3D Args.hasArg(OPT_ffunction_sections);
   Opts.DataSections =3D Args.hasArg(OPT_fdata_sections);
@@ -1078,6 +1160,13 @@
   Opts.EmitGcovArcs =3D Args.hasArg(OPT_femit_coverage_data);
   Opts.EmitGcovNotes =3D Args.hasArg(OPT_femit_coverage_notes);
   Opts.CoverageFile =3D Args.getLastArgValue(OPT_coverage_file);
+  Opts.DebugCompilationDir =3D Args.getLastArgValue(OPT_fdebug_compilation=
_dir);
+  Opts.LinkBitcodeFile =3D Args.getLastArgValue(OPT_mlink_bitcode_file);
+  Opts.StackRealignment =3D Args.hasArg(OPT_mstackrealign);
+  if (Arg *A =3D Args.getLastArg(OPT_mstack_alignment)) {
+    StringRef Val =3D A->getValue(Args);
+    Val.getAsInteger(10, Opts.StackAlignment);
+  }
=20
   if (Arg *A =3D Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
     StringRef Name =3D A->getValue(Args);
@@ -1086,11 +1175,15 @@
       .Case("non-legacy", CodeGenOptions::NonLegacy)
       .Case("mixed", CodeGenOptions::Mixed)
       .Default(~0U);
-    if (Method =3D=3D ~0U)
+    if (Method =3D=3D ~0U) {
       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) <<=
 Name;
-    else
+      Success =3D false;
+    } else {
       Opts.ObjCDispatchMethod =3D Method;
+    }
   }
+
+  return Success;
 }
=20
 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
@@ -1103,12 +1196,17 @@
   Opts.ShowHeaderIncludes =3D Args.hasArg(OPT_H);
   Opts.HeaderIncludeOutputFile =3D Args.getLastArgValue(OPT_header_include=
_file);
   Opts.AddMissingHeaderDeps =3D Args.hasArg(OPT_MG);
+  Opts.DOTOutputFile =3D Args.getLastArgValue(OPT_dependency_dot);
 }
=20
-static void ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
-                                DiagnosticsEngine &Diags) {
+bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
+                                DiagnosticsEngine *Diags) {
   using namespace cc1options;
+  bool Success =3D true;
+
   Opts.DiagnosticLogFile =3D Args.getLastArgValue(OPT_diagnostic_log_file);
+  Opts.DiagnosticSerializationFile =3D
+    Args.getLastArgValue(OPT_diagnostic_serialized_file);
   Opts.IgnoreWarnings =3D Args.hasArg(OPT_w);
   Opts.NoRewriteMacros =3D Args.hasArg(OPT_Wno_rewrite_macros);
   Opts.Pedantic =3D Args.hasArg(OPT_pedantic);
@@ -1120,7 +1218,6 @@
                                  /*Default=3D*/true);
   Opts.ShowFixits =3D !Args.hasArg(OPT_fno_diagnostics_fixit_info);
   Opts.ShowLocation =3D !Args.hasArg(OPT_fno_show_source_location);
-  Opts.ShowNames =3D Args.hasArg(OPT_fdiagnostics_show_name);
   Opts.ShowOptionNames =3D Args.hasArg(OPT_fdiagnostics_show_option);
=20
   // Default behavior is to not to show note include stacks.
@@ -1136,10 +1233,13 @@
     Opts.ShowOverloads =3D DiagnosticsEngine::Ovl_Best;
   else if (ShowOverloads =3D=3D "all")
     Opts.ShowOverloads =3D DiagnosticsEngine::Ovl_All;
-  else
-    Diags.Report(diag::err_drv_invalid_value)
+  else {
+    Success =3D false;
+    if (Diags)
+      Diags->Report(diag::err_drv_invalid_value)
       << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
       << ShowOverloads;
+  }
=20
   StringRef ShowCategory =3D
     Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
@@ -1149,23 +1249,29 @@
     Opts.ShowCategories =3D 1;
   else if (ShowCategory =3D=3D "name")
     Opts.ShowCategories =3D 2;
-  else
-    Diags.Report(diag::err_drv_invalid_value)
+  else {
+    Success =3D false;
+    if (Diags)
+      Diags->Report(diag::err_drv_invalid_value)
       << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
       << ShowCategory;
+  }
=20
   StringRef Format =3D
     Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
   if (Format =3D=3D "clang")
     Opts.Format =3D DiagnosticOptions::Clang;
-  else if (Format =3D=3D "msvc")=20
+  else if (Format =3D=3D "msvc")
     Opts.Format =3D DiagnosticOptions::Msvc;
-  else if (Format =3D=3D "vi")=20
+  else if (Format =3D=3D "vi")
     Opts.Format =3D DiagnosticOptions::Vi;
-  else=20
-    Diags.Report(diag::err_drv_invalid_value)
+  else {
+    Success =3D false;
+    if (Diags)
+      Diags->Report(diag::err_drv_invalid_value)
       << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
       << Format;
+  }
  =20
   Opts.ShowSourceRanges =3D Args.hasArg(OPT_fdiagnostics_print_source_rang=
e_info);
   Opts.ShowParseableFixits =3D Args.hasArg(OPT_fdiagnostics_parseable_fixi=
ts);
@@ -1178,16 +1284,32 @@
     =3D Args.getLastArgIntValue(OPT_ftemplate_backtrace_limit,
                          DiagnosticOptions::DefaultTemplateBacktraceLimit,
                          Diags);
+  Opts.ConstexprBacktraceLimit
+    =3D Args.getLastArgIntValue(OPT_fconstexpr_backtrace_limit,
+                         DiagnosticOptions::DefaultConstexprBacktraceLimit,
+                         Diags);
   Opts.TabStop =3D Args.getLastArgIntValue(OPT_ftabstop,
                                     DiagnosticOptions::DefaultTabStop, Dia=
gs);
   if (Opts.TabStop =3D=3D 0 || Opts.TabStop > DiagnosticOptions::MaxTabSto=
p) {
-    Diags.Report(diag::warn_ignoring_ftabstop_value)
+    Opts.TabStop =3D DiagnosticOptions::DefaultTabStop;
+    if (Diags)
+      Diags->Report(diag::warn_ignoring_ftabstop_value)
       << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
-    Opts.TabStop =3D DiagnosticOptions::DefaultTabStop;
   }
   Opts.MessageLength =3D Args.getLastArgIntValue(OPT_fmessage_length, 0, D=
iags);
   Opts.DumpBuildInformation =3D Args.getLastArgValue(OPT_dump_build_inform=
ation);
-  Opts.Warnings =3D Args.getAllArgValues(OPT_W);
+
+  for (arg_iterator it =3D Args.filtered_begin(OPT_W),
+         ie =3D Args.filtered_end(); it !=3D ie; ++it) {
+    StringRef V =3D (*it)->getValue(Args);
+    // "-Wl," and such are not warnings options.
+    if (V.startswith("l,") || V.startswith("a,") || V.startswith("p,"))
+      continue;
+
+    Opts.Warnings.push_back(V);
+  }
+
+  return Success;
 }
=20
 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
@@ -1249,6 +1371,8 @@
       Opts.ProgramAction =3D frontend::PrintPreamble; break;
     case OPT_E:
       Opts.ProgramAction =3D frontend::PrintPreprocessedInput; break;
+    case OPT_pubnames_dump:
+      Opts.ProgramAction =3D frontend::PubnamesDump; break;
     case OPT_rewrite_macros:
       Opts.ProgramAction =3D frontend::RewriteMacros; break;
     case OPT_rewrite_objc:
@@ -1257,6 +1381,8 @@
       Opts.ProgramAction =3D frontend::RewriteTest; break;
     case OPT_analyze:
       Opts.ProgramAction =3D frontend::RunAnalysis; break;
+    case OPT_migrate:
+      Opts.ProgramAction =3D frontend::MigrateSource; break;
     case OPT_Eonly:
       Opts.ProgramAction =3D frontend::RunPreprocessorOnly; break;
     }
@@ -1308,8 +1434,11 @@
   Opts.ASTMergeFiles =3D Args.getAllArgValues(OPT_ast_merge);
   Opts.LLVMArgs =3D Args.getAllArgValues(OPT_mllvm);
   Opts.FixWhatYouCan =3D Args.hasArg(OPT_fix_what_you_can);
-
-  Opts.ARCMTAction =3D FrontendOptions::ARCMT_None;
+  Opts.FixOnlyWarnings =3D Args.hasArg(OPT_fix_only_warnings);
+  Opts.FixAndRecompile =3D Args.hasArg(OPT_fixit_recompile);
+  Opts.FixToTemporaries =3D Args.hasArg(OPT_fixit_to_temp);
+  Opts.OverrideRecordLayoutsFile
+    =3D Args.getLastArgValue(OPT_foverride_record_layout_EQ);
   if (const Arg *A =3D Args.getLastArg(OPT_arcmt_check,
                                      OPT_arcmt_modify,
                                      OPT_arcmt_migrate)) {
@@ -1327,12 +1456,23 @@
       break;
     }
   }
-  Opts.ARCMTMigrateDir =3D Args.getLastArgValue(OPT_arcmt_migrate_director=
y);
+  Opts.MTMigrateDir =3D Args.getLastArgValue(OPT_mt_migrate_directory);
   Opts.ARCMTMigrateReportOut
     =3D Args.getLastArgValue(OPT_arcmt_migrate_report_output);
   Opts.ARCMTMigrateEmitARCErrors
     =3D Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
=20
+  if (Args.hasArg(OPT_objcmt_migrate_literals))
+    Opts.ObjCMTAction |=3D FrontendOptions::ObjCMT_Literals;
+  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
+    Opts.ObjCMTAction |=3D FrontendOptions::ObjCMT_Subscripting;
+
+  if (Opts.ARCMTAction !=3D FrontendOptions::ARCMT_None &&
+      Opts.ObjCMTAction !=3D FrontendOptions::ObjCMT_None) {
+    Diags.Report(diag::err_drv_argument_not_allowed_with)
+      << "ARC migration" << "ObjC migration";
+  }
+
   InputKind DashX =3D IK_None;
   if (const Arg *A =3D Args.getLastArg(OPT_x)) {
     DashX =3D llvm::StringSwitch<InputKind>(A->getValue(Args))
@@ -1376,7 +1516,7 @@
       if (i =3D=3D 0)
         DashX =3D IK;
     }
-    Opts.Inputs.push_back(std::make_pair(IK, Inputs[i]));
+    Opts.Inputs.push_back(FrontendInputFile(Inputs[i], IK));
   }
=20
   return DashX;
@@ -1457,6 +1597,10 @@
          OPT_iwithsysroot), ie =3D Args.filtered_end(); it !=3D ie; ++it)
     Opts.AddPath((*it)->getValue(Args), frontend::System, true, false,
                  !(*it)->getOption().matches(OPT_iwithsysroot));
+  for (arg_iterator it =3D Args.filtered_begin(OPT_iframework),
+         ie =3D Args.filtered_end(); it !=3D ie; ++it)
+    Opts.AddPath((*it)->getValue(Args), frontend::System, true, true,
+                 true);
=20
   // Add the paths for the various language specific isystem flags.
   for (arg_iterator it =3D Args.filtered_begin(OPT_c_isystem),
@@ -1529,7 +1673,7 @@
   const LangStandard &Std =3D LangStandard::getLangStandardForKind(LangStd=
);
   Opts.BCPLComment =3D Std.hasBCPLComments();
   Opts.C99 =3D Std.isC99();
-  Opts.C1X =3D Std.isC1X();
+  Opts.C11 =3D Std.isC11();
   Opts.CPlusPlus =3D Std.isCPlusPlus();
   Opts.CPlusPlus0x =3D Std.isCPlusPlus0x();
   Opts.Digraphs =3D Std.hasDigraphs();
@@ -1680,6 +1824,7 @@
   else if (Vis =3D=3D "hidden")
     Opts.setVisibilityMode(HiddenVisibility);
   else if (Vis =3D=3D "protected")
+    // FIXME: diagnose if target does not support protected visibility
     Opts.setVisibilityMode(ProtectedVisibility);
   else
     Diags.Report(diag::err_drv_invalid_value)
@@ -1704,7 +1849,8 @@
                                    OPT_fno_dollars_in_identifiers,
                                    Opts.DollarIdents);
   Opts.PascalStrings =3D Args.hasArg(OPT_fpascal_strings);
-  Opts.MicrosoftExt =3D Args.hasArg(OPT_fms_extensions);
+  Opts.MicrosoftExt
+    =3D Args.hasArg(OPT_fms_extensions) || Args.hasArg(OPT_fms_compatibili=
ty);
   Opts.MicrosoftMode =3D Args.hasArg(OPT_fms_compatibility);
   Opts.MSCVersion =3D Args.getLastArgIntValue(OPT_fmsc_version, 0, Diags);
   Opts.Borland =3D Args.hasArg(OPT_fborland_extensions);
@@ -1724,6 +1870,7 @@
   Opts.RTTI =3D !Args.hasArg(OPT_fno_rtti);
   Opts.Blocks =3D Args.hasArg(OPT_fblocks);
   Opts.BlocksRuntimeOptional =3D Args.hasArg(OPT_fblocks_runtime_optional);
+  Opts.Modules =3D Args.hasArg(OPT_fmodules);
   Opts.CharIsSigned =3D !Args.hasArg(OPT_fno_signed_char);
   Opts.ShortWChar =3D Args.hasArg(OPT_fshort_wchar);
   Opts.ShortEnums =3D Args.hasArg(OPT_fshort_enums);
@@ -1736,7 +1883,9 @@
   Opts.ElideConstructors =3D !Args.hasArg(OPT_fno_elide_constructors);
   Opts.MathErrno =3D Args.hasArg(OPT_fmath_errno);
   Opts.InstantiationDepth =3D Args.getLastArgIntValue(OPT_ftemplate_depth,=
 1024,
-                                               Diags);
+                                                    Diags);
+  Opts.ConstexprCallDepth =3D Args.getLastArgIntValue(OPT_fconstexpr_depth=
, 512,
+                                                    Diags);
   Opts.DelayedTemplateParsing =3D Args.hasArg(OPT_fdelayed_template_parsin=
g);
   Opts.NumLargeByValueCopy =3D Args.getLastArgIntValue(OPT_Wlarge_by_value=
_copy,
                                                     0, Diags);
@@ -1753,18 +1902,27 @@
   Opts.EmitAllDecls =3D Args.hasArg(OPT_femit_all_decls);
   Opts.PackStruct =3D Args.getLastArgIntValue(OPT_fpack_struct, 0, Diags);
   Opts.PICLevel =3D Args.getLastArgIntValue(OPT_pic_level, 0, Diags);
+  Opts.PIELevel =3D Args.getLastArgIntValue(OPT_pie_level, 0, Diags);
   Opts.Static =3D Args.hasArg(OPT_static_define);
-  Opts.DumpRecordLayouts =3D Args.hasArg(OPT_fdump_record_layouts);
+  Opts.DumpRecordLayoutsSimple =3D Args.hasArg(OPT_fdump_record_layouts_si=
mple);
+  Opts.DumpRecordLayouts =3D Opts.DumpRecordLayoutsSimple=20
+                        || Args.hasArg(OPT_fdump_record_layouts);
   Opts.DumpVTableLayouts =3D Args.hasArg(OPT_fdump_vtable_layouts);
   Opts.SpellChecking =3D !Args.hasArg(OPT_fno_spell_checking);
   Opts.NoBitFieldTypeAlign =3D Args.hasArg(OPT_fno_bitfield_type_align);
   Opts.SinglePrecisionConstants =3D Args.hasArg(OPT_cl_single_precision_co=
nstant);
   Opts.FastRelaxedMath =3D Args.hasArg(OPT_cl_fast_relaxed_math);
-  Opts.OptimizeSize =3D 0;
   Opts.MRTD =3D Args.hasArg(OPT_mrtd);
+  Opts.HexagonQdsp6Compat =3D Args.hasArg(OPT_mqdsp6_compat);
   Opts.FakeAddressSpaceMap =3D Args.hasArg(OPT_ffake_address_space_map);
   Opts.ParseUnknownAnytype =3D Args.hasArg(OPT_funknown_anytype);
   Opts.DebuggerSupport =3D Args.hasArg(OPT_fdebugger_support);
+  Opts.DebuggerCastResultToId =3D Args.hasArg(OPT_fdebugger_cast_result_to=
_id);
+  Opts.DebuggerObjCLiteral =3D Args.hasArg(OPT_fdebugger_objc_literal);
+  Opts.AddressSanitizer =3D Args.hasArg(OPT_faddress_sanitizer);
+  Opts.ThreadSanitizer =3D Args.hasArg(OPT_fthread_sanitizer);
+  Opts.ApplePragmaPack =3D Args.hasArg(OPT_fapple_pragma_pack);
+  Opts.CurrentModule =3D Args.getLastArgValue(OPT_fmodule_name);
=20
   // Record whether the __DEPRECATED define was requested.
   Opts.Deprecated =3D Args.hasFlag(OPT_fdeprecated_macro,
@@ -1774,13 +1932,14 @@
   // FIXME: Eliminate this dependency.
   unsigned Opt =3D getOptimizationLevel(Args, IK, Diags);
   Opts.Optimize =3D Opt !=3D 0;
+  Opts.OptimizeSize =3D Args.hasArg(OPT_Os) || Args.hasArg(OPT_Oz);
=20
   // This is the __NO_INLINE__ define, which just depends on things like t=
he
   // optimization level and -fno-inline, not actually whether the backend =
has
   // inlining enabled.
-  //
-  // FIXME: This is affected by other options (-fno-inline).
-  Opts.NoInline =3D !Opt;
+  Opts.NoInlineDefine =3D !Opt || Args.hasArg(OPT_fno_inline);
+
+  Opts.FastMath =3D Args.hasArg(OPT_ffast_math);
=20
   unsigned SSP =3D Args.getLastArgIntValue(OPT_stack_protector, 0, Diags);
   switch (SSP) {
@@ -1806,7 +1965,6 @@
     Opts.TokenCache =3D Opts.ImplicitPTHInclude;
   Opts.UsePredefines =3D !Args.hasArg(OPT_undef);
   Opts.DetailedRecord =3D Args.hasArg(OPT_detailed_preprocessing_record);
-  Opts.AutoModuleImport =3D Args.hasArg(OPT_fauto_module_import);
   Opts.DisablePCHValidation =3D Args.hasArg(OPT_fno_validate_pch);
=20
   Opts.DumpDeserializedPCHDecls =3D Args.hasArg(OPT_dump_deserialized_pch_=
decls);
@@ -1917,45 +2075,54 @@
   Opts.LinkerVersion =3D Args.getLastArgValue(OPT_target_linker_version);
   Opts.Triple =3D llvm::Triple::normalize(Args.getLastArgValue(OPT_triple)=
);
=20
-  // Use the host triple if unspecified.
+  // Use the default target triple if unspecified.
   if (Opts.Triple.empty())
-    Opts.Triple =3D llvm::sys::getHostTriple();
+    Opts.Triple =3D llvm::sys::getDefaultTargetTriple();
 }
=20
 //
=20
-void CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
+bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
                                         const char *const *ArgBegin,
                                         const char *const *ArgEnd,
                                         DiagnosticsEngine &Diags) {
+  bool Success =3D true;
+
   // Parse the arguments.
-  llvm::OwningPtr<OptTable> Opts(createCC1OptTable());
+  OwningPtr<OptTable> Opts(createCC1OptTable());
   unsigned MissingArgIndex, MissingArgCount;
-  llvm::OwningPtr<InputArgList> Args(
+  OwningPtr<InputArgList> Args(
     Opts->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
=20
   // Check for missing argument error.
-  if (MissingArgCount)
+  if (MissingArgCount) {
     Diags.Report(diag::err_drv_missing_argument)
       << Args->getArgString(MissingArgIndex) << MissingArgCount;
+    Success =3D false;
+  }
=20
   // Issue errors on unknown arguments.
   for (arg_iterator it =3D Args->filtered_begin(OPT_UNKNOWN),
-         ie =3D Args->filtered_end(); it !=3D ie; ++it)
+         ie =3D Args->filtered_end(); it !=3D ie; ++it) {
     Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Ar=
gs);
+    Success =3D false;
+  }
=20
-  ParseAnalyzerArgs(Res.getAnalyzerOpts(), *Args, Diags);
+  Success =3D ParseAnalyzerArgs(Res.getAnalyzerOpts(), *Args, Diags) && Su=
ccess;
+  Success =3D ParseMigratorArgs(Res.getMigratorOpts(), *Args) && Success;
   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), *Args);
-  ParseDiagnosticArgs(Res.getDiagnosticOpts(), *Args, Diags);
+  Success =3D ParseDiagnosticArgs(Res.getDiagnosticOpts(), *Args, &Diags)
+            && Success;
   ParseFileSystemArgs(Res.getFileSystemOpts(), *Args);
   // FIXME: We shouldn't have to pass the DashX option around here
   InputKind DashX =3D ParseFrontendArgs(Res.getFrontendOpts(), *Args, Diag=
s);
-  ParseCodeGenArgs(Res.getCodeGenOpts(), *Args, DashX, Diags);
+  Success =3D ParseCodeGenArgs(Res.getCodeGenOpts(), *Args, DashX, Diags)
+            && Success;
   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), *Args);
   if (DashX !=3D IK_AST && DashX !=3D IK_LLVM_IR) {
-    ParseLangArgs(Res.getLangOpts(), *Args, DashX, Diags);
+    ParseLangArgs(*Res.getLangOpts(), *Args, DashX, Diags);
     if (Res.getFrontendOpts().ProgramAction =3D=3D frontend::RewriteObjC)
-      Res.getLangOpts().ObjCExceptions =3D 1;
+      Res.getLangOpts()->ObjCExceptions =3D 1;
   }
   // FIXME: ParsePreprocessorArgs uses the FileManager to read the content=
s of
   // PCH file and find the original header name. Remove the need to do tha=
t in
@@ -1965,6 +2132,8 @@
   ParsePreprocessorArgs(Res.getPreprocessorOpts(), *Args, FileMgr, Diags);
   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), *Args);
   ParseTargetArgs(Res.getTargetOpts(), *Args);
+
+  return Success;
 }
=20
 namespace {
@@ -2024,13 +2193,16 @@
   ModuleSignature Signature;
  =20
   // Start the signature with the compiler version.
-  Signature.add(getClangFullRepositoryVersion());
+  // FIXME: The full version string can be quite long.  Omit it from the
+  // module hash for now to avoid failures where the path name becomes too
+  // long.  An MD5 or similar checksum would work well here.
+  // Signature.add(getClangFullRepositoryVersion());
  =20
   // Extend the signature with the language options
 #define LANGOPT(Name, Bits, Default, Description) \
-  Signature.add(LangOpts.Name, Bits);
+  Signature.add(LangOpts->Name, Bits);
 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
-  Signature.add(static_cast<unsigned>(LangOpts.get##Name()), Bits);
+  Signature.add(static_cast<unsigned>(LangOpts->get##Name()), Bits);
 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
 #include "clang/Basic/LangOptions.def"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/CreateInvocationFromCommandLine.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/CreateInvocationFromComman=
dLine.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/CreateInvocationFromComman=
dLine.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 /// argument vector.
 CompilerInvocation *
 clang::createInvocationFromCommandLine(ArrayRef<const char *> ArgList,
-                            llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Di=
ags) {
+                            IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
   if (!Diags.getPtr()) {
     // No diagnostics engine was provided, so create our own diagnostics o=
bject
     // with the default options.
@@ -48,13 +48,13 @@
   Args.push_back("-fsyntax-only");
=20
   // FIXME: We shouldn't have to pass in the path info.
-  driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
+  driver::Driver TheDriver("clang", llvm::sys::getDefaultTargetTriple(),
                            "a.out", false, *Diags);
=20
   // Don't check that inputs exist, they may have been remapped.
   TheDriver.setCheckInputsExist(false);
=20
-  llvm::OwningPtr<driver::Compilation> C(TheDriver.BuildCompilation(Args));
+  OwningPtr<driver::Compilation> C(TheDriver.BuildCompilation(Args));
=20
   // Just print the cc1 options if -### was present.
   if (C->getArgs().hasArg(driver::options::OPT__HASH_HASH_HASH)) {
@@ -66,7 +66,7 @@
   // failed.
   const driver::JobList &Jobs =3D C->getJobs();
   if (Jobs.size() !=3D 1 || !isa<driver::Command>(*Jobs.begin())) {
-    llvm::SmallString<256> Msg;
+    SmallString<256> Msg;
     llvm::raw_svector_ostream OS(Msg);
     C->PrintJob(OS, C->getJobs(), "; ", true);
     Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
@@ -80,11 +80,12 @@
   }
=20
   const driver::ArgStringList &CCArgs =3D Cmd->getArguments();
-  CompilerInvocation *CI =3D new CompilerInvocation();
-  CompilerInvocation::CreateFromArgs(*CI,
+  OwningPtr<CompilerInvocation> CI(new CompilerInvocation());
+  if (!CompilerInvocation::CreateFromArgs(*CI,
                                      const_cast<const char **>(CCArgs.data=
()),
                                      const_cast<const char **>(CCArgs.data=
()) +
                                      CCArgs.size(),
-                                     *Diags);
-  return CI;
+                                     *Diags))
+    return 0;
+  return CI.take();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/DependencyFile.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/DependencyFile.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -31,11 +31,12 @@
   std::vector<std::string> Files;
   llvm::StringSet<> FilesSet;
   const Preprocessor *PP;
+  std::string OutputFile;
   std::vector<std::string> Targets;
-  raw_ostream *OS;
   bool IncludeSystemHeaders;
   bool PhonyTarget;
   bool AddMissingHeaderDeps;
+  bool SeenMissingHeader;
 private:
   bool FileMatchesDepCriteria(const char *Filename,
                               SrcMgr::CharacteristicKind FileType);
@@ -44,12 +45,12 @@
=20
 public:
   DependencyFileCallback(const Preprocessor *_PP,
-                         raw_ostream *_OS,
                          const DependencyOutputOptions &Opts)
-    : PP(_PP), Targets(Opts.Targets), OS(_OS),
+    : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
       IncludeSystemHeaders(Opts.IncludeSystemHeaders),
       PhonyTarget(Opts.UsePhonyTargets),
-      AddMissingHeaderDeps(Opts.AddMissingHeaderDeps) {}
+      AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
+      SeenMissingHeader(false) {}
=20
   virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
                            SrcMgr::CharacteristicKind FileType,
@@ -65,8 +66,6 @@
=20
   virtual void EndOfMainFile() {
     OutputDependencyFile();
-    delete OS;
-    OS =3D 0;
   }
 };
 }
@@ -78,19 +77,11 @@
     return;
   }
=20
-  std::string Err;
-  raw_ostream *OS(new llvm::raw_fd_ostream(Opts.OutputFile.c_str(), Err));
-  if (!Err.empty()) {
-    PP.getDiagnostics().Report(diag::err_fe_error_opening)
-      << Opts.OutputFile << Err;
-    return;
-  }
-
   // Disable the "file not found" diagnostic if the -MG option was given.
   if (Opts.AddMissingHeaderDeps)
     PP.SetSuppressIncludeNotFoundError(true);
=20
-  PP.addPPCallbacks(new DependencyFileCallback(&PP, OS, Opts));
+  PP.addPPCallbacks(new DependencyFileCallback(&PP, Opts));
 }
=20
 /// FileMatchesDepCriteria - Determine whether the given Filename should be
@@ -145,8 +136,12 @@
                                                 SourceLocation EndLoc,
                                                 StringRef SearchPath,
                                                 StringRef RelativePath) {
-  if (AddMissingHeaderDeps && !File)
-    AddFilename(FileName);
+  if (!File) {
+    if (AddMissingHeaderDeps)
+      AddFilename(FileName);
+    else
+      SeenMissingHeader =3D true;
+  }
 }
=20
 void DependencyFileCallback::AddFilename(StringRef Filename) {
@@ -165,6 +160,19 @@
 }
=20
 void DependencyFileCallback::OutputDependencyFile() {
+  if (SeenMissingHeader) {
+    llvm::sys::Path(OutputFile).eraseFromDisk();
+    return;
+  }
+
+  std::string Err;
+  llvm::raw_fd_ostream OS(OutputFile.c_str(), Err);
+  if (!Err.empty()) {
+    PP->getDiagnostics().Report(diag::err_fe_error_opening)
+      << OutputFile << Err;
+    return;
+  }
+
   // Write out the dependency targets, trying to avoid overly long
   // lines when possible. We try our best to emit exactly the same
   // dependency file as GCC (4.2), assuming the included files are the
@@ -179,16 +187,16 @@
       Columns +=3D N;
     } else if (Columns + N + 2 > MaxColumns) {
       Columns =3D N + 2;
-      *OS << " \\\n  ";
+      OS << " \\\n  ";
     } else {
       Columns +=3D N + 1;
-      *OS << ' ';
+      OS << ' ';
     }
     // Targets already quoted as needed.
-    *OS << *I;
+    OS << *I;
   }
=20
-  *OS << ':';
+  OS << ':';
   Columns +=3D 1;
=20
   // Now add each dependency in the order it was seen, but avoiding
@@ -200,23 +208,23 @@
     // break the line on the next iteration.
     unsigned N =3D I->length();
     if (Columns + (N + 1) + 2 > MaxColumns) {
-      *OS << " \\\n ";
+      OS << " \\\n ";
       Columns =3D 2;
     }
-    *OS << ' ';
-    PrintFilename(*OS, *I);
+    OS << ' ';
+    PrintFilename(OS, *I);
     Columns +=3D N + 1;
   }
-  *OS << '\n';
+  OS << '\n';
=20
   // Create phony targets if requested.
   if (PhonyTarget && !Files.empty()) {
     // Skip the first entry, this is always the input file itself.
     for (std::vector<std::string>::iterator I =3D Files.begin() + 1,
            E =3D Files.end(); I !=3D E; ++I) {
-      *OS << '\n';
-      PrintFilename(*OS, *I);
-      *OS << ":\n";
+      OS << '\n';
+      PrintFilename(OS, *I);
+      OS << ":\n";
     }
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/FrontendAction.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/FrontendAction.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -14,14 +14,15 @@
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Frontend/ASTUnit.h"
+#include "clang/Frontend/ChainedIncludesSource.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/FrontendPluginRegistry.h"
+#include "clang/Frontend/LayoutOverrideSource.h"
 #include "clang/Frontend/MultiplexConsumer.h"
 #include "clang/Parse/ParseAST.h"
 #include "clang/Serialization/ASTDeserializationListener.h"
 #include "clang/Serialization/ASTReader.h"
-#include "clang/Serialization/ChainedIncludesSource.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -30,37 +31,70 @@
=20
 namespace {
=20
-/// \brief Dumps deserialized declarations.
-class DeserializedDeclsDumper : public ASTDeserializationListener {
+class DelegatingDeserializationListener : public ASTDeserializationListene=
r {
   ASTDeserializationListener *Previous;
=20
 public:
-  DeserializedDeclsDumper(ASTDeserializationListener *Previous)
+  explicit DelegatingDeserializationListener(
+                                           ASTDeserializationListener *Pre=
vious)
     : Previous(Previous) { }
=20
+  virtual void ReaderInitialized(ASTReader *Reader) {
+    if (Previous)
+      Previous->ReaderInitialized(Reader);
+  }
+  virtual void IdentifierRead(serialization::IdentID ID,
+                              IdentifierInfo *II) {
+    if (Previous)
+      Previous->IdentifierRead(ID, II);
+  }
+  virtual void TypeRead(serialization::TypeIdx Idx, QualType T) {
+    if (Previous)
+      Previous->TypeRead(Idx, T);
+  }
+  virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
+    if (Previous)
+      Previous->DeclRead(ID, D);
+  }
+  virtual void SelectorRead(serialization::SelectorID ID, Selector Sel) {
+    if (Previous)
+      Previous->SelectorRead(ID, Sel);
+  }
+  virtual void MacroDefinitionRead(serialization::PreprocessedEntityID PPI=
D,=20
+                                   MacroDefinition *MD) {
+    if (Previous)
+      Previous->MacroDefinitionRead(PPID, MD);
+  }
+};
+
+/// \brief Dumps deserialized declarations.
+class DeserializedDeclsDumper : public DelegatingDeserializationListener {
+public:
+  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous)
+    : DelegatingDeserializationListener(Previous) { }
+
   virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
     llvm::outs() << "PCH DECL: " << D->getDeclKindName();
     if (const NamedDecl *ND =3D dyn_cast<NamedDecl>(D))
-      llvm::outs() << " - " << ND->getNameAsString();
+      llvm::outs() << " - " << *ND;
     llvm::outs() << "\n";
=20
-    if (Previous)
-      Previous->DeclRead(ID, D);
+    DelegatingDeserializationListener::DeclRead(ID, D);
   }
 };
=20
   /// \brief Checks deserialized declarations and emits error if a name
   /// matches one given in command-line using -error-on-deserialized-decl.
-  class DeserializedDeclsChecker : public ASTDeserializationListener {
+  class DeserializedDeclsChecker : public DelegatingDeserializationListene=
r {
     ASTContext &Ctx;
     std::set<std::string> NamesToCheck;
-    ASTDeserializationListener *Previous;
=20
   public:
     DeserializedDeclsChecker(ASTContext &Ctx,
                              const std::set<std::string> &NamesToCheck,=20
                              ASTDeserializationListener *Previous)
-      : Ctx(Ctx), NamesToCheck(NamesToCheck), Previous(Previous) { }
+      : DelegatingDeserializationListener(Previous),
+        Ctx(Ctx), NamesToCheck(NamesToCheck) { }
=20
     virtual void DeclRead(serialization::DeclID ID, const Decl *D) {
       if (const NamedDecl *ND =3D dyn_cast<NamedDecl>(D))
@@ -72,8 +106,7 @@
               << ND->getNameAsString();
         }
=20
-      if (Previous)
-        Previous->DeclRead(ID, D);
+      DelegatingDeserializationListener::DeclRead(ID, D);
     }
 };
=20
@@ -83,10 +116,9 @@
=20
 FrontendAction::~FrontendAction() {}
=20
-void FrontendAction::setCurrentFile(StringRef Value, InputKind Kind,
-                                    ASTUnit *AST) {
-  CurrentFile =3D Value;
-  CurrentFileKind =3D Kind;
+void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
+                                     ASTUnit *AST) {
+  this->CurrentInput =3D CurrentInput;
   CurrentASTUnit.reset(AST);
 }
=20
@@ -112,7 +144,7 @@
         ie =3D FrontendPluginRegistry::end();
         it !=3D ie; ++it) {
       if (it->getName() =3D=3D CI.getFrontendOpts().AddPluginActions[i]) {
-        llvm::OwningPtr<PluginASTAction> P(it->instantiate());
+        OwningPtr<PluginASTAction> P(it->instantiate());
         FrontendAction* c =3D P.get();
         if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i]))
           Consumers.push_back(c->CreateASTConsumer(CI, InFile));
@@ -124,11 +156,10 @@
 }
=20
 bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
-                                     StringRef Filename,
-                                     InputKind InputKind) {
+                                     const FrontendInputFile &Input) {
   assert(!Instance && "Already processing a source file!");
-  assert(!Filename.empty() && "Unexpected empty filename!");
-  setCurrentFile(Filename, InputKind);
+  assert(!Input.File.empty() && "Unexpected empty filename!");
+  setCurrentInput(Input);
   setCompilerInstance(&CI);
=20
   if (!BeginInvocation(CI))
@@ -136,20 +167,20 @@
=20
   // AST files follow a very different path, since they share objects via =
the
   // AST unit.
-  if (InputKind =3D=3D IK_AST) {
+  if (Input.Kind =3D=3D IK_AST) {
     assert(!usesPreprocessorOnly() &&
            "Attempt to pass AST file to preprocessor only action!");
     assert(hasASTFileSupport() &&
            "This action does not have AST file support!");
=20
-    llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics()=
);
+    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
     std::string Error;
-    ASTUnit *AST =3D ASTUnit::LoadFromASTFile(Filename, Diags,
+    ASTUnit *AST =3D ASTUnit::LoadFromASTFile(Input.File, Diags,
                                             CI.getFileSystemOpts());
     if (!AST)
       goto failure;
=20
-    setCurrentFile(Filename, InputKind, AST);
+    setCurrentInput(Input, AST);
=20
     // Set the shared objects, these are reset when we finish processing t=
he
     // file, otherwise the CompilerInstance will happily destroy them.
@@ -159,11 +190,11 @@
     CI.setASTContext(&AST->getASTContext());
=20
     // Initialize the action.
-    if (!BeginSourceFileAction(CI, Filename))
+    if (!BeginSourceFileAction(CI, Input.File))
       goto failure;
=20
     /// Create the AST consumer.
-    CI.setASTConsumer(CreateWrappedASTConsumer(CI, Filename));
+    CI.setASTConsumer(CreateWrappedASTConsumer(CI, Input.File));
     if (!CI.hasASTConsumer())
       goto failure;
=20
@@ -177,7 +208,7 @@
     CI.createSourceManager(CI.getFileManager());
=20
   // IR files bypass the rest of initialization.
-  if (InputKind =3D=3D IK_LLVM_IR) {
+  if (Input.Kind =3D=3D IK_LLVM_IR) {
     assert(hasIRSupport() &&
            "This action does not have IR file support!");
=20
@@ -185,7 +216,7 @@
     CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
=20
     // Initialize the action.
-    if (!BeginSourceFileAction(CI, Filename))
+    if (!BeginSourceFileAction(CI, Input.File))
       goto failure;
=20
     return true;
@@ -199,7 +230,7 @@
                                            &CI.getPreprocessor());
=20
   // Initialize the action.
-  if (!BeginSourceFileAction(CI, Filename))
+  if (!BeginSourceFileAction(CI, Input.File))
     goto failure;
=20
   /// Create the AST context and consumer unless this is a preprocessor on=
ly
@@ -207,8 +238,8 @@
   if (!usesPreprocessorOnly()) {
     CI.createASTContext();
=20
-    llvm::OwningPtr<ASTConsumer> Consumer(
-        CreateWrappedASTConsumer(CI, Filename));
+    OwningPtr<ASTConsumer> Consumer(
+                                   CreateWrappedASTConsumer(CI, Input.File=
));
     if (!Consumer)
       goto failure;
=20
@@ -216,7 +247,7 @@
=20
     if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
       // Convert headers to PCH and chain them.
-      llvm::OwningPtr<ExternalASTSource> source;
+      OwningPtr<ExternalASTSource> source;
       source.reset(ChainedIncludesSource::create(CI));
       if (!source)
         goto failure;
@@ -237,6 +268,7 @@
                                 CI.getPreprocessorOpts().ImplicitPCHInclud=
e,
                                 CI.getPreprocessorOpts().DisablePCHValidat=
ion,
                                 CI.getPreprocessorOpts().DisableStatCache,
+                            CI.getPreprocessorOpts().AllowPCHWithCompilerE=
rrors,
                                 DeserialListener);
       if (!CI.getASTContext().getExternalSource())
         goto failure;
@@ -252,9 +284,19 @@
   if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) {
     Preprocessor &PP =3D CI.getPreprocessor();
     PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),
-                                           PP.getLangOptions());
+                                           PP.getLangOpts());
   }
=20
+  // If there is a layout overrides file, attach an external AST source th=
at
+  // provides the layouts from that file.
+  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&=20
+      CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
+    OwningPtr<ExternalASTSource>=20
+      Override(new LayoutOverrideSource(
+                     CI.getFrontendOpts().OverrideRecordLayoutsFile));
+    CI.getASTContext().setExternalSource(Override);
+  }
+ =20
   return true;
=20
   // If we failed, reset state since the client will not end up calling the
@@ -268,7 +310,7 @@
   }
=20
   CI.getDiagnosticClient().EndSourceFile();
-  setCurrentFile("", IK_None);
+  setCurrentInput(FrontendInputFile());
   setCompilerInstance(0);
   return false;
 }
@@ -278,17 +320,11 @@
=20
   // Initialize the main file entry. This needs to be delayed until after =
PCH
   // has loaded.
-  if (isCurrentFileAST()) {
-    // Set the main file ID to an empty file.
-    //
-    // FIXME: We probably shouldn't need this, but for now this is the
-    // simplest way to reuse the logic in ParseAST.
-    const char *EmptyStr =3D "";
-    llvm::MemoryBuffer *SB =3D
-      llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>");
-    CI.getSourceManager().createMainFileIDForMemBuffer(SB);
-  } else {
-    if (!CI.InitializeSourceManager(getCurrentFile()))
+  if (!isCurrentFileAST()) {
+    if (!CI.InitializeSourceManager(getCurrentFile(),
+                                    getCurrentInput().IsSystem
+                                      ? SrcMgr::C_System
+                                      : SrcMgr::C_User))
       return;
   }
=20
@@ -352,7 +388,7 @@
   }
=20
   setCompilerInstance(0);
-  setCurrentFile("", IK_None);
+  setCurrentInput(FrontendInputFile());
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -376,9 +412,12 @@
   if (!CI.hasSema())
     CI.createSema(getTranslationUnitKind(), CompletionConsumer);
=20
-  ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats);
+  ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
+           CI.getFrontendOpts().SkipFunctionBodies);
 }
=20
+void PluginASTAction::anchor() { }
+
 ASTConsumer *
 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
                                               StringRef InFile) {
@@ -394,7 +433,7 @@
 }
 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI,
                                                   StringRef Filename) {
-  WrappedAction->setCurrentFile(getCurrentFile(), getCurrentFileKind());
+  WrappedAction->setCurrentInput(getCurrentInput());
   WrappedAction->setCompilerInstance(&CI);
   return WrappedAction->BeginSourceFileAction(CI, Filename);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/FrontendActions.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp	Tue Ap=
r 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp	Tue Ap=
r 17 11:51:51 2012 +0300
@@ -9,6 +9,7 @@
=20
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/AST/ASTConsumer.h"
+#include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Pragma.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Parse/Parser.h"
@@ -20,9 +21,11 @@
 #include "clang/Frontend/Utils.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/system_error.h"
+#include <set>
=20
 using namespace clang;
=20
@@ -85,8 +88,7 @@
=20
   if (!CI.getFrontendOpts().RelocatablePCH)
     Sysroot.clear();
-  return new PCHGenerator(CI.getPreprocessor(), OutputFile, MakeModule,=20
-                          Sysroot, OS);
+  return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS=
);
 }
=20
 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
@@ -113,11 +115,317 @@
   return false;
 }
=20
+ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
+                                                     StringRef InFile) {
+  std::string Sysroot;
+  std::string OutputFile;
+  raw_ostream *OS =3D 0;
+  if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
+    return 0;
+ =20
+  return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,=20
+                          Sysroot, OS);
+}
+
+/// \brief Collect the set of header includes needed to construct the give=
n=20
+/// module.
+///
+/// \param Module The module we're collecting includes from.
+///
+/// \param Includes Will be augmented with the set of #includes or #imports
+/// needed to load all of the named headers.
+static void collectModuleHeaderIncludes(const LangOptions &LangOpts,
+                                        FileManager &FileMgr,
+                                        ModuleMap &ModMap,
+                                        clang::Module *Module,
+                                        SmallString<256> &Includes) {
+  // Don't collect any headers for unavailable modules.
+  if (!Module->isAvailable())
+    return;
+
+  // Add includes for each of these headers.
+  for (unsigned I =3D 0, N =3D Module->Headers.size(); I !=3D N; ++I) {
+    if (LangOpts.ObjC1)
+      Includes +=3D "#import \"";
+    else
+      Includes +=3D "#include \"";
+    Includes +=3D Module->Headers[I]->getName();
+    Includes +=3D "\"\n";
+  }
+
+  if (const FileEntry *UmbrellaHeader =3D Module->getUmbrellaHeader()) {
+    if (Module->Parent) {
+      // Include the umbrella header for submodules.
+      if (LangOpts.ObjC1)
+        Includes +=3D "#import \"";
+      else
+        Includes +=3D "#include \"";
+      Includes +=3D UmbrellaHeader->getName();
+      Includes +=3D "\"\n";
+    }
+  } else if (const DirectoryEntry *UmbrellaDir =3D Module->getUmbrellaDir(=
)) {
+    // Add all of the headers we find in this subdirectory.
+    llvm::error_code EC;
+    SmallString<128> DirNative;
+    llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
+    for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), =
EC),=20
+                                                     DirEnd;
+         Dir !=3D DirEnd && !EC; Dir.increment(EC)) {
+      // Check whether this entry has an extension typically associated wi=
th=20
+      // headers.
+      if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()=
))
+          .Cases(".h", ".H", ".hh", ".hpp", true)
+          .Default(false))
+        continue;
+     =20
+      // If this header is marked 'unavailable' in this module, don't incl=
ude=20
+      // it.
+      if (const FileEntry *Header =3D FileMgr.getFile(Dir->path()))
+        if (ModMap.isHeaderInUnavailableModule(Header))
+          continue;
+     =20
+      // Include this header umbrella header for submodules.
+      if (LangOpts.ObjC1)
+        Includes +=3D "#import \"";
+      else
+        Includes +=3D "#include \"";
+      Includes +=3D Dir->path();
+      Includes +=3D "\"\n";
+    }
+  }
+ =20
+  // Recurse into submodules.
+  for (clang::Module::submodule_iterator Sub =3D Module->submodule_begin(),
+                                      SubEnd =3D Module->submodule_end();
+       Sub !=3D SubEnd; ++Sub)
+    collectModuleHeaderIncludes(LangOpts, FileMgr, ModMap, *Sub, Includes);
+}
+
+bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,=20
+                                                 StringRef Filename) {
+  // Find the module map file. =20
+  const FileEntry *ModuleMap =3D CI.getFileManager().getFile(Filename);
+  if (!ModuleMap)  {
+    CI.getDiagnostics().Report(diag::err_module_map_not_found)
+      << Filename;
+    return false;
+  }
+ =20
+  // Parse the module map file.
+  HeaderSearch &HS =3D CI.getPreprocessor().getHeaderSearchInfo();
+  if (HS.loadModuleMapFile(ModuleMap))
+    return false;
+ =20
+  if (CI.getLangOpts().CurrentModule.empty()) {
+    CI.getDiagnostics().Report(diag::err_missing_module_name);
+   =20
+    // FIXME: Eventually, we could consider asking whether there was just
+    // a single module described in the module map, and use that as a=20
+    // default. Then it would be fairly trivial to just "compile" a module
+    // map with a single module (the common case).
+    return false;
+  }
+ =20
+  // Dig out the module definition.
+  Module =3D HS.lookupModule(CI.getLangOpts().CurrentModule,=20
+                           /*AllowSearch=3D*/false);
+  if (!Module) {
+    CI.getDiagnostics().Report(diag::err_missing_module)
+      << CI.getLangOpts().CurrentModule << Filename;
+   =20
+    return false;
+  }
+
+  // Check whether we can build this module at all.
+  StringRef Feature;
+  if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Feature)) {
+    CI.getDiagnostics().Report(diag::err_module_unavailable)
+      << Module->getFullModuleName()
+      << Feature;
+
+    return false;
+  }
+
+  // Do we have an umbrella header for this module?
+  const FileEntry *UmbrellaHeader =3D Module->getUmbrellaHeader();
+ =20
+  // Collect the set of #includes we need to build the module.
+  SmallString<256> HeaderContents;
+  collectModuleHeaderIncludes(CI.getLangOpts(), CI.getFileManager(),
+    CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(),
+    Module, HeaderContents);
+  if (UmbrellaHeader && HeaderContents.empty()) {
+    // Simple case: we have an umbrella header and there are no additional
+    // includes, we can just parse the umbrella header directly.
+    setCurrentInput(FrontendInputFile(UmbrellaHeader->getName(),
+                                      getCurrentFileKind(),
+                                      Module->IsSystem));
+    return true;
+  }
+ =20
+  FileManager &FileMgr =3D CI.getFileManager();
+  SmallString<128> HeaderName;
+  time_t ModTime;
+  if (UmbrellaHeader) {
+    // Read in the umbrella header.
+    // FIXME: Go through the source manager; the umbrella header may have
+    // been overridden.
+    std::string ErrorStr;
+    llvm::MemoryBuffer *UmbrellaContents
+      =3D FileMgr.getBufferForFile(UmbrellaHeader, &ErrorStr);
+    if (!UmbrellaContents) {
+      CI.getDiagnostics().Report(diag::err_missing_umbrella_header)
+        << UmbrellaHeader->getName() << ErrorStr;
+      return false;
+    }
+   =20
+    // Combine the contents of the umbrella header with the automatically-
+    // generated includes.
+    SmallString<256> OldContents =3D HeaderContents;
+    HeaderContents =3D UmbrellaContents->getBuffer();
+    HeaderContents +=3D "\n\n";
+    HeaderContents +=3D "/* Module includes */\n";
+    HeaderContents +=3D OldContents;
+
+    // Pretend that we're parsing the umbrella header.
+    HeaderName =3D UmbrellaHeader->getName();
+    ModTime =3D UmbrellaHeader->getModificationTime();
+   =20
+    delete UmbrellaContents;
+  } else {
+    // Pick an innocuous-sounding name for the umbrella header.
+    HeaderName =3D Module->Name + ".h";
+    if (FileMgr.getFile(HeaderName, /*OpenFile=3D*/false,=20
+                        /*CacheFailure=3D*/false)) {
+      // Try again!
+      HeaderName =3D Module->Name + "-module.h";     =20
+      if (FileMgr.getFile(HeaderName, /*OpenFile=3D*/false,=20
+                          /*CacheFailure=3D*/false)) {
+        // Pick something ridiculous and go with it.
+        HeaderName =3D Module->Name + "-module.hmod";
+      }
+    }
+    ModTime =3D time(0);
+  }
+ =20
+  // Remap the contents of the header name we're using to our synthesized
+  // buffer.
+  const FileEntry *HeaderFile =3D FileMgr.getVirtualFile(HeaderName,=20
+                                                       HeaderContents.size=
(),=20
+                                                       ModTime);
+  llvm::MemoryBuffer *HeaderContentsBuf
+    =3D llvm::MemoryBuffer::getMemBufferCopy(HeaderContents);
+  CI.getSourceManager().overrideFileContents(HeaderFile, HeaderContentsBuf=
); =20
+  setCurrentInput(FrontendInputFile(HeaderName, getCurrentFileKind(),
+                                    Module->IsSystem));
+  return true;
+}
+
+bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &C=
I,
+                                                       StringRef InFile,
+                                                       std::string &Sysroo=
t,
+                                                       std::string &Output=
File,
+                                                       raw_ostream *&OS) {
+  // If no output file was provided, figure out where this module would go
+  // in the module cache.
+  if (CI.getFrontendOpts().OutputFile.empty()) {
+    HeaderSearch &HS =3D CI.getPreprocessor().getHeaderSearchInfo();
+    SmallString<256> ModuleFileName(HS.getModuleCachePath());
+    llvm::sys::path::append(ModuleFileName,=20
+                            CI.getLangOpts().CurrentModule + ".pcm");
+    CI.getFrontendOpts().OutputFile =3D ModuleFileName.str();
+  }
+ =20
+  // We use createOutputFile here because this is exposed via libclang, an=
d we
+  // must disable the RemoveFileOnSignal behavior.
+  // We use a temporary to avoid race conditions.
+  OS =3D CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=3D*=
/true,
+                           /*RemoveFileOnSignal=3D*/false, InFile,
+                           /*Extension=3D*/"", /*useTemporary=3D*/true,
+                           /*CreateMissingDirectories=3D*/true);
+  if (!OS)
+    return true;
+ =20
+  OutputFile =3D CI.getFrontendOpts().OutputFile;
+  return false;
+}
+
 ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
                                                  StringRef InFile) {
   return new ASTConsumer();
 }
=20
+namespace {
+  class PubnamesDumpConsumer : public ASTConsumer {
+    Preprocessor &PP;
+   =20
+    /// \brief Determine whether the given identifier provides a 'public' =
name.
+    bool isPublicName(IdentifierInfo *II) {
+      // If there are any top-level declarations associated with this
+      // identifier, it is a public name.
+      if (II->getFETokenInfo<void>())
+        return true;
+
+      // If this identifier is the name of a non-builtin macro that isn't
+      // defined on the command line or implicitly by the front end, it is=
 a
+      // public name.
+      if (II->hasMacroDefinition()) {
+        if (MacroInfo *M =3D PP.getMacroInfo(II))
+          if (!M->isBuiltinMacro()) {
+            SourceLocation Loc =3D M->getDefinitionLoc();
+            FileID File =3D PP.getSourceManager().getFileID(Loc);
+            if (PP.getSourceManager().getFileEntryForID(File))
+              return true;
+          }
+      }
+     =20
+      return false;
+    }
+     =20
+  public:
+    PubnamesDumpConsumer(Preprocessor &PP) : PP(PP) { }
+       =20
+    virtual void HandleTranslationUnit(ASTContext &Ctx) {
+      std::set<StringRef> Pubnames;
+     =20
+      // Add the names of any non-builtin macros.
+      for (IdentifierTable::iterator I =3D Ctx.Idents.begin(),
+                                  IEnd =3D Ctx.Idents.end();
+           I !=3D IEnd; ++I) {
+        if (isPublicName(I->second))
+          Pubnames.insert(I->first());
+      }
+     =20
+      // If there is an external identifier lookup source, consider those
+      // identifiers as well.
+      if (IdentifierInfoLookup *External
+            =3D Ctx.Idents.getExternalIdentifierLookup()) {
+        OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
+        do {
+          StringRef Name =3D Iter->Next();
+          if (Name.empty())
+            break;
+         =20
+          if (isPublicName(PP.getIdentifierInfo(Name)))
+            Pubnames.insert(Name);
+        } while (true);
+      }
+
+      // Print the names, in lexicographical order.
+      for (std::set<StringRef>::iterator N =3D Pubnames.begin(),
+                                      NEnd =3D Pubnames.end();
+           N !=3D NEnd; ++N) {
+        llvm::outs() << *N << '\n';
+      }
+    }
+  };
+}
+
+ASTConsumer *PubnamesDumpAction::CreateASTConsumer(CompilerInstance &CI,
+                                                   StringRef InFile) {
+  return new PubnamesDumpConsumer(CI.getPreprocessor());
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Preprocessor Actions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -128,7 +436,7 @@
=20
   // Start lexing the specified input file.
   const llvm::MemoryBuffer *FromFile =3D SM.getBuffer(SM.getMainFileID());
-  Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions());
+  Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
   RawLex.SetKeepWhitespaceMode(true);
=20
   Token RawTok;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/HeaderIncludeGen.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/HeaderIncludeGen.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/HeaderIncludeGen.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -11,6 +11,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace clang;
=20
@@ -107,10 +108,10 @@
   // are showing all headers.
   if (ShowHeader && Reason =3D=3D PPCallbacks::EnterFile) {
     // Write to a temporary string to avoid unnecessary flushing on errs().
-    llvm::SmallString<512> Filename(UserLoc.getFilename());
+    SmallString<512> Filename(UserLoc.getFilename());
     Lexer::Stringify(Filename);
=20
-    llvm::SmallString<256> Msg;
+    SmallString<256> Msg;
     if (ShowDepth) {
       // The main source file is at depth 1, so skip one dot.
       for (unsigned i =3D 1; i !=3D CurrentIncludeDepth; ++i)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/InitHeaderSearch.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/InitHeaderSearch.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -11,10 +11,6 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#ifdef HAVE_CLANG_CONFIG_H
-# include "clang/Config/config.h"
-#endif
-
 #include "clang/Frontend/Utils.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/LangOptions.h"
@@ -30,7 +26,9 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/Path.h"
-#include "llvm/Config/config.h"
+
+#include "clang/Config/config.h" // C_INCLUDE_DIRS
+
 #ifndef CLANG_PREFIX
 #define CLANG_PREFIX
 #endif
@@ -112,7 +110,7 @@
   FileManager &FM =3D Headers.getFileMgr();
=20
   // Compute the actual path, taking into consideration -isysroot.
-  llvm::SmallString<256> MappedPathStorage;
+  SmallString<256> MappedPathStorage;
   StringRef MappedPathStr =3D Path.toStringRef(MappedPathStorage);
=20
   // Handle isysroot.
@@ -336,19 +334,6 @@
 void InitHeaderSearch::
 AddDefaultCPlusPlusIncludePaths(const llvm::Triple &triple, const HeaderSe=
archOptions &HSOpts) {
   llvm::Triple::OSType os =3D triple.getOS();
-  StringRef CxxIncludeRoot(CXX_INCLUDE_ROOT);
-  if (CxxIncludeRoot !=3D "") {
-    StringRef CxxIncludeArch(CXX_INCLUDE_ARCH);
-    if (CxxIncludeArch =3D=3D "")
-      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, triple.str().c_str(),
-                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT=
_DIR,
-                                  triple);
-    else
-      AddGnuCPlusPlusIncludePaths(CxxIncludeRoot, CXX_INCLUDE_ARCH,
-                                  CXX_INCLUDE_32BIT_DIR, CXX_INCLUDE_64BIT=
_DIR,
-                                  triple);
-    return;
-  }
   // FIXME: temporary hack: hard-coded paths.
=20
   if (triple.isOSDarwin()) {
@@ -391,11 +376,10 @@
=20
   case llvm::Triple::Cygwin:
     // Cygwin-1.7
+    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.5.3=
");
     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.4=
");
     // g++-4 / Cygwin-1.5
     AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "4.3.2=
");
-    // FIXME: Do we support g++-3.4.4?
-    AddMinGWCPlusPlusIncludePaths("/usr/lib/gcc", "i686-pc-cygwin", "3.4.4=
");
     break;
   case llvm::Triple::MinGW32:
     // mingw-w64 C++ include paths (i686-w64-mingw32 and x86_64-w64-mingw3=
2)
@@ -403,12 +387,17 @@
     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.1");
     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.2");
     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.3");
+    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.5.4");
     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.0");
     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.1");
     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.2");
+    AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.6.3");
     AddMinGW64CXXPaths(HSOpts.ResourceDir, "4.7.0");
     // mingw.org C++ include paths
     AddMinGWCPlusPlusIncludePaths("/mingw/lib/gcc", "mingw32", "4.5.2"); /=
/MSYS
+    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.6.2");
+    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.6.1");
+    AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.5.2");
     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.5.0");
     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.4.0");
     AddMinGWCPlusPlusIncludePaths("c:/MinGW/lib/gcc", "mingw32", "4.3.0");
@@ -440,6 +429,8 @@
                                 "", "", "", triple);
     break;
   case llvm::Triple::Solaris:
+    AddGnuCPlusPlusIncludePaths("/usr/gcc/4.5/include/c++/4.5.2/",
+                                "i386-pc-solaris2.11", "", "", triple);
     // Solaris - Fall though..
   case llvm::Triple::AuroraUX:
     // AuroraUX
@@ -484,6 +475,11 @@
           AddPath(P.str(), CXXSystem, true, false, false, true);
         }
       }
+      // On Solaris, include the support directory for things like xlocale=
 and
+      // fudged system headers.
+      if (triple.getOS() =3D=3D llvm::Triple::Solaris)=20
+        AddPath("/usr/include/c++/v1/support/solaris", CXXSystem, true, fa=
lse,
+            false);
      =20
       AddPath("/usr/include/c++/v1", CXXSystem, true, false, false);
     } else {
@@ -675,5 +671,13 @@
=20
   Init.AddDefaultIncludePaths(Lang, Triple, HSOpts);
=20
+  if (HSOpts.UseBuiltinIncludes) {
+    // Set up the builtin include directory in the module map.
+    llvm::sys::Path P(HSOpts.ResourceDir);
+    P.appendComponent("include");
+    if (const DirectoryEntry *Dir =3D HS.getFileMgr().getDirectory(P.str()=
))
+      HS.getModuleMap().setBuiltinIncludeDir(Dir);
+  }
+
   Init.Realize(Lang);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/InitPreprocessor.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/InitPreprocessor.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/FrontendOptions.h"
 #include "clang/Frontend/PreprocessorOptions.h"
+#include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
@@ -48,39 +49,19 @@
   }
 }
=20
-std::string clang::NormalizeDashIncludePath(StringRef File,
-                                            FileManager &FileMgr) {
-  // Implicit include paths should be resolved relative to the current
-  // working directory first, and then use the regular header search
-  // mechanism. The proper way to handle this is to have the
-  // predefines buffer located at the current working directory, but
-  // it has no file entry. For now, workaround this by using an
-  // absolute path if we find the file here, and otherwise letting
-  // header search handle it.
-  llvm::SmallString<128> Path(File);
-  llvm::sys::fs::make_absolute(Path);
-  bool exists;
-  if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
-    Path =3D File;
-  else if (exists)
-    FileMgr.getFile(File);
-
-  return Lexer::Stringify(Path.str());
-}
-
 /// AddImplicitInclude - Add an implicit #include of the specified file to=
 the
 /// predefines buffer.
 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File,
                                FileManager &FileMgr) {
-  Builder.append("#include \"" +
-                 Twine(NormalizeDashIncludePath(File, FileMgr)) + "\"");
+  Builder.append(Twine("#include \"") +
+                 HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "=
\"");
 }
=20
 static void AddImplicitIncludeMacros(MacroBuilder &Builder,
                                      StringRef File,
                                      FileManager &FileMgr) {
-  Builder.append("#__include_macros \"" +
-                 Twine(NormalizeDashIncludePath(File, FileMgr)) + "\"");
+  Builder.append(Twine("#__include_macros \"") +
+                 HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "=
\"");
   // Marker token to stop the __include_macros fetch loop.
   Builder.append("##"); // ##?
 }
@@ -146,7 +127,7 @@
                "1.79769313486231580793728971405301e+308L",
                "1.18973149535723176508575932662800702e+4932L");
=20
-  llvm::SmallString<32> DefPrefix;
+  SmallString<32> DefPrefix;
   DefPrefix =3D "__";
   DefPrefix +=3D Prefix;
   DefPrefix +=3D "_";
@@ -221,6 +202,20 @@
                         ConstSuffix);
 }
=20
+/// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with
+/// the specified properties.
+static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign,
+                                    unsigned InlineWidth) {
+  // Fully-aligned, power-of-2 sizes no larger than the inline
+  // width will be inlined as lock-free operations.
+  if (TypeWidth =3D=3D TypeAlign && (TypeWidth & (TypeWidth - 1)) =3D=3D 0=
 &&
+      TypeWidth <=3D InlineWidth)
+    return "2"; // "always lock free"
+  // We cannot be certain what operations the lib calls might be
+  // able to implement as lock-free on future processors.
+  return "1"; // "sometimes lock free"
+}
+
 /// \brief Add definitions required for a smooth interaction between
 /// Objective-C++ automated reference counting and libstdc++ (4.2).
 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,=20
@@ -278,7 +273,7 @@
                                                const LangOptions &LangOpts,
                                                const FrontendOptions &FEOp=
ts,
                                                MacroBuilder &Builder) {
-  if (!LangOpts.MicrosoftExt && !LangOpts.TraditionalCPP)
+  if (!LangOpts.MicrosoftMode && !LangOpts.TraditionalCPP)
     Builder.defineMacro("__STDC__");
   if (LangOpts.Freestanding)
     Builder.defineMacro("__STDC_HOSTED__", "0");
@@ -286,7 +281,9 @@
     Builder.defineMacro("__STDC_HOSTED__");
=20
   if (!LangOpts.CPlusPlus) {
-    if (LangOpts.C99)
+    if (LangOpts.C11)
+      Builder.defineMacro("__STDC_VERSION__", "201112L");
+    else if (LangOpts.C99)
       Builder.defineMacro("__STDC_VERSION__", "199901L");
     else if (!LangOpts.GNUMode && LangOpts.Digraphs)
       Builder.defineMacro("__STDC_VERSION__", "199409L");
@@ -336,11 +333,25 @@
                       + getClangFullRepositoryVersion() + ")\"");
 #undef TOSTR
 #undef TOSTR2
-  // Currently claim to be compatible with GCC 4.2.1-5621.
-  Builder.defineMacro("__GNUC_MINOR__", "2");
-  Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
-  Builder.defineMacro("__GNUC__", "4");
-  Builder.defineMacro("__GXX_ABI_VERSION", "1002");
+  if (!LangOpts.MicrosoftMode) {
+    // Currently claim to be compatible with GCC 4.2.1-5621, but only if w=
e're
+    // not compiling for MSVC compatibility
+    Builder.defineMacro("__GNUC_MINOR__", "2");
+    Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
+    Builder.defineMacro("__GNUC__", "4");
+    Builder.defineMacro("__GXX_ABI_VERSION", "1002");
+  }
+
+  // Define macros for the C11 / C++11 memory orderings
+  Builder.defineMacro("__ATOMIC_RELAXED", "0");
+  Builder.defineMacro("__ATOMIC_CONSUME", "1");
+  Builder.defineMacro("__ATOMIC_ACQUIRE", "2");
+  Builder.defineMacro("__ATOMIC_RELEASE", "3");
+  Builder.defineMacro("__ATOMIC_ACQ_REL", "4");
+  Builder.defineMacro("__ATOMIC_SEQ_CST", "5");
+
+  // Support for #pragma redefine_extname (Sun compatibility)
+  Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1");
=20
   // As sad as it is, enough software depends on the __VERSION__ for versi=
on
   // checks that it is necessary to report 4.2.1 (the base GCC version we =
claim
@@ -428,6 +439,9 @@
   if (LangOpts.OptimizeSize)
     Builder.defineMacro("__OPTIMIZE_SIZE__");
=20
+  if (LangOpts.FastMath)
+    Builder.defineMacro("__FAST_MATH__");
+
   // Initialize target-specific preprocessor defines.
=20
   // Define type sizing macros based on the target properties.
@@ -521,16 +535,46 @@
   else
     Builder.defineMacro("__GNUC_STDC_INLINE__");
=20
-  if (LangOpts.NoInline)
+  // The value written by __atomic_test_and_set.
+  // FIXME: This is target-dependent.
+  Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1");
+
+  // Used by libstdc++ to implement ATOMIC_<foo>_LOCK_FREE.
+  unsigned InlineWidthBits =3D TI.getMaxAtomicInlineWidth();
+#define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \
+  Builder.defineMacro("__GCC_ATOMIC_" #TYPE "_LOCK_FREE", \
+                      getLockFreeValue(TI.get##Type##Width(), \
+                                       TI.get##Type##Align(), \
+                                       InlineWidthBits));
+  DEFINE_LOCK_FREE_MACRO(BOOL, Bool);
+  DEFINE_LOCK_FREE_MACRO(CHAR, Char);
+  DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16);
+  DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32);
+  DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar);
+  DEFINE_LOCK_FREE_MACRO(SHORT, Short);
+  DEFINE_LOCK_FREE_MACRO(INT, Int);
+  DEFINE_LOCK_FREE_MACRO(LONG, Long);
+  DEFINE_LOCK_FREE_MACRO(LLONG, LongLong);
+  Builder.defineMacro("__GCC_ATOMIC_POINTER_LOCK_FREE",
+                      getLockFreeValue(TI.getPointerWidth(0),
+                                       TI.getPointerAlign(0),
+                                       InlineWidthBits));
+#undef DEFINE_LOCK_FREE_MACRO
+
+  if (LangOpts.NoInlineDefine)
     Builder.defineMacro("__NO_INLINE__");
=20
   if (unsigned PICLevel =3D LangOpts.PICLevel) {
     Builder.defineMacro("__PIC__", Twine(PICLevel));
     Builder.defineMacro("__pic__", Twine(PICLevel));
   }
+  if (unsigned PIELevel =3D LangOpts.PIELevel) {
+    Builder.defineMacro("__PIE__", Twine(PIELevel));
+    Builder.defineMacro("__pie__", Twine(PIELevel));
+  }
=20
   // Macros to control C99 numerics and <float.h>
-  Builder.defineMacro("__FLT_EVAL_METHOD__", "0");
+  Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()=
));
   Builder.defineMacro("__FLT_RADIX__", "2");
   int Dig =3D PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 3=
6);
   Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig));
@@ -632,7 +676,7 @@
                                    const PreprocessorOptions &InitOpts,
                                    const HeaderSearchOptions &HSOpts,
                                    const FrontendOptions &FEOpts) {
-  const LangOptions &LangOpts =3D PP.getLangOptions();
+  const LangOptions &LangOpts =3D PP.getLangOpts();
   std::string PredefineBuffer;
   PredefineBuffer.reserve(4080);
   llvm::raw_string_ostream Predefines(PredefineBuffer);
@@ -641,14 +685,10 @@
   InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
                           PP.getFileManager(), InitOpts);
=20
-  // Specify whether the preprocessor should replace #include/#import with
-  // module imports when plausible.
-  PP.setAutoModuleImport(InitOpts.AutoModuleImport);
-
   // Emit line markers for various builtin sections of the file.  We don't=
 do
   // this in asm preprocessor mode, because "# 4" is not a line marker dir=
ective
   // in this mode.
-  if (!PP.getLangOptions().AsmPreprocessor)
+  if (!PP.getLangOpts().AsmPreprocessor)
     Builder.append("# 1 \"<built-in>\" 3");
=20
   // Install things like __POWERPC__, __GNUC__, etc into the macro table.
@@ -673,12 +713,12 @@
   // Even with predefines off, some macros are still predefined.
   // These should all be defined in the preprocessor according to the
   // current language configuration.
-  InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOptions=
(),
+  InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(),
                                      FEOpts, Builder);
=20
   // Add on the predefines from the driver.  Wrap in a #line directive to =
report
   // that they come from the command line.
-  if (!PP.getLangOptions().AsmPreprocessor)
+  if (!PP.getLangOpts().AsmPreprocessor)
     Builder.append("# 1 \"<command line>\" 1");
=20
   // Process #define's and #undef's in the order they are given.
@@ -706,7 +746,7 @@
   }
=20
   // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
-  if (!PP.getLangOptions().AsmPreprocessor)
+  if (!PP.getLangOpts().AsmPreprocessor)
     Builder.append("# 1 \"<built-in>\" 2");
=20
   // Instruct the preprocessor to skip the preamble.
@@ -718,6 +758,6 @@
  =20
   // Initialize the header search object.
   ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
-                           PP.getLangOptions(),
+                           PP.getLangOpts(),
                            PP.getTargetInfo().getTriple());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/LangStandards.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/LangStandards.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/LangStandards.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -19,14 +19,13 @@
=20
 const LangStandard &LangStandard::getLangStandardForKind(Kind K) {
   switch (K) {
-  default:
-    llvm_unreachable("Invalid language kind!");
   case lang_unspecified:
     llvm::report_fatal_error("getLangStandardForKind() on unspecified kind=
");
 #define LANGSTANDARD(id, name, desc, features) \
     case lang_##id: return Lang_##id;
 #include "clang/Frontend/LangStandards.def"
   }
+  llvm_unreachable("Invalid language kind!");
 }
=20
 const LangStandard *LangStandard::getLangStandardForName(StringRef Name) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/LogDiagnosticPrinter.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/LogDiagnosticPrinter.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/LogDiagnosticPrinter.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -12,6 +12,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/Support/ErrorHandling.h"
 using namespace clang;
=20
 LogDiagnosticPrinter::LogDiagnosticPrinter(raw_ostream &os,
@@ -28,14 +29,13 @@
=20
 static StringRef getLevelName(DiagnosticsEngine::Level Level) {
   switch (Level) {
-  default:
-    return "<unknown>";
   case DiagnosticsEngine::Ignored: return "ignored";
   case DiagnosticsEngine::Note:    return "note";
   case DiagnosticsEngine::Warning: return "warning";
   case DiagnosticsEngine::Error:   return "error";
   case DiagnosticsEngine::Fatal:   return "fatal error";
   }
+  llvm_unreachable("Invalid DiagnosticsEngine level!");
 }
=20
 // Escape XML characters inside the raw string.
@@ -64,7 +64,7 @@
     return;
=20
   // Write to a temporary string to ensure atomic write of diagnostic obje=
ct.
-  llvm::SmallString<512> Msg;
+  SmallString<512> Msg;
   llvm::raw_svector_ostream OS(Msg);
=20
   OS << "<dict>\n";
@@ -140,7 +140,7 @@
   DE.DiagnosticLevel =3D Level;
=20
   // Format the message.
-  llvm::SmallString<100> MessageStr;
+  SmallString<100> MessageStr;
   Info.FormatDiagnostic(MessageStr);
   DE.Message =3D MessageStr.str();
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/MultiplexConsumer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/MultiplexConsumer.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/MultiplexConsumer.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -89,7 +89,7 @@
 class MultiplexASTMutationListener : public ASTMutationListener {
 public:
   // Does NOT take ownership of the elements in L.
-  MultiplexASTMutationListener(const std::vector<ASTMutationListener*>& L);
+  MultiplexASTMutationListener(ArrayRef<ASTMutationListener*> L);
   virtual void CompletedTagDefinition(const TagDecl *D);
   virtual void AddedVisibleDecl(const DeclContext *DC, const Decl *D);
   virtual void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl =
*D);
@@ -99,13 +99,18 @@
                                               const FunctionDecl *D);
   virtual void CompletedImplicitDefinition(const FunctionDecl *D);
   virtual void StaticDataMemberInstantiated(const VarDecl *D);
+  virtual void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
+                                            const ObjCInterfaceDecl *IFD);
+  virtual void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *P=
rop,
+                                            const ObjCPropertyDecl *OrigPr=
op,
+                                            const ObjCCategoryDecl *ClassE=
xt);
 private:
   std::vector<ASTMutationListener*> Listeners;
 };
=20
 MultiplexASTMutationListener::MultiplexASTMutationListener(
-    const std::vector<ASTMutationListener*>& L)
-    : Listeners(L) {
+    ArrayRef<ASTMutationListener*> L)
+    : Listeners(L.begin(), L.end()) {
 }
=20
 void MultiplexASTMutationListener::CompletedTagDefinition(const TagDecl *D=
) {
@@ -144,12 +149,26 @@
   for (size_t i =3D 0, e =3D Listeners.size(); i !=3D e; ++i)
     Listeners[i]->StaticDataMemberInstantiated(D);
 }
+void MultiplexASTMutationListener::AddedObjCCategoryToInterface(
+                                                 const ObjCCategoryDecl *C=
atD,
+                                                 const ObjCInterfaceDecl *=
IFD) {
+  for (size_t i =3D 0, e =3D Listeners.size(); i !=3D e; ++i)
+    Listeners[i]->AddedObjCCategoryToInterface(CatD, IFD);
+}
+void MultiplexASTMutationListener::AddedObjCPropertyInClassExtension(
+                                             const ObjCPropertyDecl *Prop,
+                                             const ObjCPropertyDecl *OrigP=
rop,
+                                             const ObjCCategoryDecl *Class=
Ext) {
+  for (size_t i =3D 0, e =3D Listeners.size(); i !=3D e; ++i)
+    Listeners[i]->AddedObjCPropertyInClassExtension(Prop, OrigProp, ClassE=
xt);
+}
=20
 }  // end namespace clang
=20
=20
-MultiplexConsumer::MultiplexConsumer(const std::vector<ASTConsumer*>& C)
-    : Consumers(C), MutationListener(0), DeserializationListener(0) {
+MultiplexConsumer::MultiplexConsumer(ArrayRef<ASTConsumer*> C)
+    : Consumers(C.begin(), C.end()),
+      MutationListener(0), DeserializationListener(0) {
   // Collect the mutation listeners and deserialization listeners of all
   // children, and create a multiplex listener each if so.
   std::vector<ASTMutationListener*> mutationListeners;
@@ -183,9 +202,16 @@
     Consumers[i]->Initialize(Context);
 }
=20
-void MultiplexConsumer::HandleTopLevelDecl(DeclGroupRef D) {
+bool MultiplexConsumer::HandleTopLevelDecl(DeclGroupRef D) {
+  bool Continue =3D true;
   for (size_t i =3D 0, e =3D Consumers.size(); i !=3D e; ++i)
-    Consumers[i]->HandleTopLevelDecl(D);
+    Continue =3D Continue && Consumers[i]->HandleTopLevelDecl(D);
+  return Continue;
+}
+
+void  MultiplexConsumer::HandleCXXStaticMemberVarInstantiation(VarDecl *VD=
) {
+  for (size_t i =3D 0, e =3D Consumers.size(); i !=3D e; ++i)
+    Consumers[i]->HandleCXXStaticMemberVarInstantiation(VD);
 }
=20
 void MultiplexConsumer::HandleInterestingDecl(DeclGroupRef D) {
@@ -203,6 +229,16 @@
     Consumers[i]->HandleTagDeclDefinition(D);
 }
=20
+void MultiplexConsumer::HandleCXXImplicitFunctionInstantiation(FunctionDec=
l *D){
+  for (size_t i =3D 0, e =3D Consumers.size(); i !=3D e; ++i)
+    Consumers[i]->HandleCXXImplicitFunctionInstantiation(D);
+}
+
+void MultiplexConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
+  for (size_t i =3D 0, e =3D Consumers.size(); i !=3D e; ++i)
+    Consumers[i]->HandleTopLevelDeclInObjCContainer(D);
+}
+
 void MultiplexConsumer::CompleteTentativeDefinition(VarDecl *D) {
   for (size_t i =3D 0, e =3D Consumers.size(); i !=3D e; ++i)
     Consumers[i]->CompleteTentativeDefinition(D);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/PrintPreprocessedOutput.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cp=
p	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/PrintPreprocessedOutput.cp=
p	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,6 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/Config/config.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <cstdio>
@@ -63,7 +62,7 @@
   if (MI.tokens_empty() || !MI.tokens_begin()->hasLeadingSpace())
     OS << ' ';
=20
-  llvm::SmallString<128> SpellingBuffer;
+  SmallString<128> SpellingBuffer;
   for (MacroInfo::tokens_iterator I =3D MI.tokens_begin(), E =3D MI.tokens=
_end();
        I !=3D E; ++I) {
     if (I->hasLeadingSpace())
@@ -90,7 +89,7 @@
   bool EmittedTokensOnThisLine;
   bool EmittedMacroOnThisLine;
   SrcMgr::CharacteristicKind FileType;
-  llvm::SmallString<512> CurFilename;
+  SmallString<512> CurFilename;
   bool Initialized;
   bool DisableLineMarkers;
   bool DumpDefines;
@@ -109,7 +108,7 @@
     Initialized =3D false;
=20
     // If we're in microsoft mode, use normal #line instead of line marker=
s.
-    UseLineDirective =3D PP.getLangOptions().MicrosoftExt;
+    UseLineDirective =3D PP.getLangOpts().MicrosoftExt;
   }
=20
   void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine =3D true; }
@@ -390,7 +389,6 @@
   MoveToLine(Loc);
   OS << "#pragma " << Namespace << " diagnostic ";
   switch (Map) {
-  default: llvm_unreachable("unexpected diagnostic kind");
   case diag::MAP_WARNING:
     OS << "warning";
     break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/TextDiagnosticBuffer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticBuffer.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticBuffer.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
   // Default implementation (Warnings/errors count).
   DiagnosticConsumer::HandleDiagnostic(Level, Info);
=20
-  llvm::SmallString<100> Buf;
+  SmallString<100> Buf;
   Info.FormatDiagnostic(Buf);
   switch (Level) {
   default: llvm_unreachable(
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/TextDiagnosticPrinter.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/TextDiagnosticPrinter.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/DiagnosticOptions.h"
+#include "clang/Frontend/TextDiagnostic.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
@@ -23,28 +24,10 @@
 #include <algorithm>
 using namespace clang;
=20
-static const enum raw_ostream::Colors noteColor =3D
-  raw_ostream::BLACK;
-static const enum raw_ostream::Colors fixitColor =3D
-  raw_ostream::GREEN;
-static const enum raw_ostream::Colors caretColor =3D
-  raw_ostream::GREEN;
-static const enum raw_ostream::Colors warningColor =3D
-  raw_ostream::MAGENTA;
-static const enum raw_ostream::Colors errorColor =3D raw_ostream::RED;
-static const enum raw_ostream::Colors fatalColor =3D raw_ostream::RED;
-// Used for changing only the bold attribute.
-static const enum raw_ostream::Colors savedColor =3D
-  raw_ostream::SAVEDCOLOR;
-
-/// \brief Number of spaces to indent when word-wrapping.
-const unsigned WordWrapIndentation =3D 6;
-
 TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
                                              const DiagnosticOptions &diag=
s,
                                              bool _OwnsOutputStream)
-  : OS(os), LangOpts(0), DiagOpts(&diags),
-    LastCaretDiagnosticWasNote(0),
+  : OS(os), LangOpts(0), DiagOpts(&diags), SM(0),
     OwnsOutputStream(_OwnsOutputStream) {
 }
=20
@@ -53,878 +36,14 @@
     delete &OS;
 }
=20
-/// \brief Helper to recursivly walk up the include stack and print each l=
ayer
-/// on the way back down.
-static void PrintIncludeStackRecursively(raw_ostream &OS,
-                                         const SourceManager &SM,
-                                         SourceLocation Loc,
-                                         bool ShowLocation) {
-  if (Loc.isInvalid())
-    return;
-
-  PresumedLoc PLoc =3D SM.getPresumedLoc(Loc);
-  if (PLoc.isInvalid())
-    return;
-
-  // Print out the other include frames first.
-  PrintIncludeStackRecursively(OS, SM, PLoc.getIncludeLoc(), ShowLocation);
-
-  if (ShowLocation)
-    OS << "In file included from " << PLoc.getFilename()
-       << ':' << PLoc.getLine() << ":\n";
-  else
-    OS << "In included file:\n";
+void TextDiagnosticPrinter::BeginSourceFile(const LangOptions &LO,
+                                            const Preprocessor *PP) {
+  LangOpts =3D &LO;
 }
=20
-/// \brief Prints an include stack when appropriate for a particular diagn=
ostic
-/// level and location.
-///
-/// This routine handles all the logic of suppressing particular include s=
tacks
-/// (such as those for notes) and duplicate include stacks when repeated
-/// warnings occur within the same file. It also handles the logic of
-/// customizing the formatting and display of the include stack.
-///
-/// \param Level The diagnostic level of the message this stack pertains t=
o.
-/// \param Loc   The include location of the current file (not the diagnos=
tic
-///              location).
-void TextDiagnosticPrinter::PrintIncludeStack(DiagnosticsEngine::Level Lev=
el,
-                                              SourceLocation Loc,
-                                              const SourceManager &SM) {
-  // Skip redundant include stacks altogether.
-  if (LastWarningLoc =3D=3D Loc)
-    return;
-  LastWarningLoc =3D Loc;
-
-  if (!DiagOpts->ShowNoteIncludeStack && Level =3D=3D DiagnosticsEngine::N=
ote)
-    return;
-
-  PrintIncludeStackRecursively(OS, SM, Loc, DiagOpts->ShowLocation);
-}
-
-/// \brief When the source code line we want to print is too long for
-/// the terminal, select the "interesting" region.
-static void SelectInterestingSourceRegion(std::string &SourceLine,
-                                          std::string &CaretLine,
-                                          std::string &FixItInsertionLine,
-                                          unsigned EndOfCaretToken,
-                                          unsigned Columns) {
-  unsigned MaxSize =3D std::max(SourceLine.size(),
-                              std::max(CaretLine.size(),=20
-                                       FixItInsertionLine.size()));
-  if (MaxSize > SourceLine.size())
-    SourceLine.resize(MaxSize, ' ');
-  if (MaxSize > CaretLine.size())
-    CaretLine.resize(MaxSize, ' ');
-  if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
-    FixItInsertionLine.resize(MaxSize, ' ');
-   =20
-  // Find the slice that we need to display the full caret line
-  // correctly.
-  unsigned CaretStart =3D 0, CaretEnd =3D CaretLine.size();
-  for (; CaretStart !=3D CaretEnd; ++CaretStart)
-    if (!isspace(CaretLine[CaretStart]))
-      break;
-
-  for (; CaretEnd !=3D CaretStart; --CaretEnd)
-    if (!isspace(CaretLine[CaretEnd - 1]))
-      break;
-
-  // Make sure we don't chop the string shorter than the caret token
-  // itself.
-  if (CaretEnd < EndOfCaretToken)
-    CaretEnd =3D EndOfCaretToken;
-
-  // If we have a fix-it line, make sure the slice includes all of the
-  // fix-it information.
-  if (!FixItInsertionLine.empty()) {
-    unsigned FixItStart =3D 0, FixItEnd =3D FixItInsertionLine.size();
-    for (; FixItStart !=3D FixItEnd; ++FixItStart)
-      if (!isspace(FixItInsertionLine[FixItStart]))
-        break;
-
-    for (; FixItEnd !=3D FixItStart; --FixItEnd)
-      if (!isspace(FixItInsertionLine[FixItEnd - 1]))
-        break;
-
-    if (FixItStart < CaretStart)
-      CaretStart =3D FixItStart;
-    if (FixItEnd > CaretEnd)
-      CaretEnd =3D FixItEnd;
-  }
-
-  // CaretLine[CaretStart, CaretEnd) contains all of the interesting
-  // parts of the caret line. While this slice is smaller than the
-  // number of columns we have, try to grow the slice to encompass
-  // more context.
-
-  // If the end of the interesting region comes before we run out of
-  // space in the terminal, start at the beginning of the line.
-  if (Columns > 3 && CaretEnd < Columns - 3)
-    CaretStart =3D 0;
-
-  unsigned TargetColumns =3D Columns;
-  if (TargetColumns > 8)
-    TargetColumns -=3D 8; // Give us extra room for the ellipses.
-  unsigned SourceLength =3D SourceLine.size();
-  while ((CaretEnd - CaretStart) < TargetColumns) {
-    bool ExpandedRegion =3D false;
-    // Move the start of the interesting region left until we've
-    // pulled in something else interesting.
-    if (CaretStart =3D=3D 1)
-      CaretStart =3D 0;
-    else if (CaretStart > 1) {
-      unsigned NewStart =3D CaretStart - 1;
-
-      // Skip over any whitespace we see here; we're looking for
-      // another bit of interesting text.
-      while (NewStart && isspace(SourceLine[NewStart]))
-        --NewStart;
-
-      // Skip over this bit of "interesting" text.
-      while (NewStart && !isspace(SourceLine[NewStart]))
-        --NewStart;
-
-      // Move up to the non-whitespace character we just saw.
-      if (NewStart)
-        ++NewStart;
-
-      // If we're still within our limit, update the starting
-      // position within the source/caret line.
-      if (CaretEnd - NewStart <=3D TargetColumns) {
-        CaretStart =3D NewStart;
-        ExpandedRegion =3D true;
-      }
-    }
-
-    // Move the end of the interesting region right until we've
-    // pulled in something else interesting.
-    if (CaretEnd !=3D SourceLength) {
-      assert(CaretEnd < SourceLength && "Unexpected caret position!");
-      unsigned NewEnd =3D CaretEnd;
-
-      // Skip over any whitespace we see here; we're looking for
-      // another bit of interesting text.
-      while (NewEnd !=3D SourceLength && isspace(SourceLine[NewEnd - 1]))
-        ++NewEnd;
-
-      // Skip over this bit of "interesting" text.
-      while (NewEnd !=3D SourceLength && !isspace(SourceLine[NewEnd - 1]))
-        ++NewEnd;
-
-      if (NewEnd - CaretStart <=3D TargetColumns) {
-        CaretEnd =3D NewEnd;
-        ExpandedRegion =3D true;
-      }
-    }
-
-    if (!ExpandedRegion)
-      break;
-  }
-
-  // [CaretStart, CaretEnd) is the slice we want. Update the various
-  // output lines to show only this slice, with two-space padding
-  // before the lines so that it looks nicer.
-  if (CaretEnd < SourceLine.size())
-    SourceLine.replace(CaretEnd, std::string::npos, "...");
-  if (CaretEnd < CaretLine.size())
-    CaretLine.erase(CaretEnd, std::string::npos);
-  if (FixItInsertionLine.size() > CaretEnd)
-    FixItInsertionLine.erase(CaretEnd, std::string::npos);
-
-  if (CaretStart > 2) {
-    SourceLine.replace(0, CaretStart, "  ...");
-    CaretLine.replace(0, CaretStart, "     ");
-    if (FixItInsertionLine.size() >=3D CaretStart)
-      FixItInsertionLine.replace(0, CaretStart, "     ");
-  }
-}
-
-/// Look through spelling locations for a macro argument expansion, and
-/// if found skip to it so that we can trace the argument rather than the =
macros
-/// in which that argument is used. If no macro argument expansion is foun=
d,
-/// don't skip anything and return the starting location.
-static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
-                                                  SourceLocation StartLoc)=
 {
-  for (SourceLocation L =3D StartLoc; L.isMacroID();
-       L =3D SM.getImmediateSpellingLoc(L)) {
-    if (SM.isMacroArgExpansion(L))
-      return L;
-  }
-
-  // Otherwise just return initial location, there's nothing to skip.
-  return StartLoc;
-}
-
-/// Gets the location of the immediate macro caller, one level up the stack
-/// toward the initial macro typed into the source.
-static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
-                                                 SourceLocation Loc) {
-  if (!Loc.isMacroID()) return Loc;
-
-  // When we have the location of (part of) an expanded parameter, its spe=
lling
-  // location points to the argument as typed into the macro call, and
-  // therefore is used to locate the macro caller.
-  if (SM.isMacroArgExpansion(Loc))
-    return SM.getImmediateSpellingLoc(Loc);
-
-  // Otherwise, the caller of the macro is located where this macro is
-  // expanded (while the spelling is part of the macro definition).
-  return SM.getImmediateExpansionRange(Loc).first;
-}
-
-/// Gets the location of the immediate macro callee, one level down the st=
ack
-/// toward the leaf macro.
-static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
-                                                 SourceLocation Loc) {
-  if (!Loc.isMacroID()) return Loc;
-
-  // When we have the location of (part of) an expanded parameter, its
-  // expansion location points to the unexpanded paramater reference within
-  // the macro definition (or callee).
-  if (SM.isMacroArgExpansion(Loc))
-    return SM.getImmediateExpansionRange(Loc).first;
-
-  // Otherwise, the callee of the macro is located where this location was
-  // spelled inside the macro definition.
-  return SM.getImmediateSpellingLoc(Loc);
-}
-
-namespace {
-
-/// \brief Class to encapsulate the logic for formatting and printing a te=
xtual
-/// diagnostic message.
-///
-/// This class provides an interface for building and emitting a textual
-/// diagnostic, including all of the macro backtraces, caret diagnostics, =
FixIt
-/// Hints, and code snippets. In the presence of macros this involves
-/// a recursive process, synthesizing notes for each macro expansion.
-///
-/// The purpose of this class is to isolate the implementation of printing
-/// beautiful text diagnostics from any particular interfaces. The Clang
-/// DiagnosticClient is implemented through this class as is diagnostic
-/// printing coming out of libclang.
-///
-/// A brief worklist:
-/// FIXME: Sink the printing of the diagnostic message itself into this cl=
ass.
-/// FIXME: Sink the printing of the include stack into this class.
-/// FIXME: Remove the TextDiagnosticPrinter as an input.
-/// FIXME: Sink the recursive printing of template instantiations into this
-/// class.
-class TextDiagnostic {
-  TextDiagnosticPrinter &Printer;
-  raw_ostream &OS;
-  const SourceManager &SM;
-  const LangOptions &LangOpts;
-  const DiagnosticOptions &DiagOpts;
-
-public:
-  TextDiagnostic(TextDiagnosticPrinter &Printer,
-                  raw_ostream &OS,
-                  const SourceManager &SM,
-                  const LangOptions &LangOpts,
-                  const DiagnosticOptions &DiagOpts)
-    : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagO=
pts) {
-  }
-
-  /// \brief Emit the caret and underlining text.
-  ///
-  /// Walks up the macro expansion stack printing the code snippet, caret,
-  /// underlines and FixItHint display as appropriate at each level. Walk =
is
-  /// accomplished by calling itself recursively.
-  ///
-  /// FIXME: Remove macro expansion from this routine, it shouldn't be tie=
d to
-  /// caret diagnostics.
-  /// FIXME: Break up massive function into logical units.
-  ///
-  /// \param Loc The location for this caret.
-  /// \param Ranges The underlined ranges for this code snippet.
-  /// \param Hints The FixIt hints active for this diagnostic.
-  /// \param MacroSkipEnd The depth to stop skipping macro expansions.
-  /// \param OnMacroInst The current depth of the macro expansion stack.
-  void EmitCaret(SourceLocation Loc,
-            SmallVectorImpl<CharSourceRange>& Ranges,
-            ArrayRef<FixItHint> Hints,
-            unsigned &MacroDepth,
-            unsigned OnMacroInst =3D 0) {
-    assert(!Loc.isInvalid() && "must have a valid source location here");
-
-    // If this is a file source location, directly emit the source snippet=
 and
-    // caret line. Also record the macro depth reached.
-    if (Loc.isFileID()) {
-      assert(MacroDepth =3D=3D 0 && "We shouldn't hit a leaf node twice!");
-      MacroDepth =3D OnMacroInst;
-      EmitSnippetAndCaret(Loc, Ranges, Hints);
-      return;
-    }
-    // Otherwise recurse through each macro expansion layer.
-
-    // When processing macros, skip over the expansions leading up to
-    // a macro argument, and trace the argument's expansion stack instead.
-    Loc =3D skipToMacroArgExpansion(SM, Loc);
-
-    SourceLocation OneLevelUp =3D getImmediateMacroCallerLoc(SM, Loc);
-
-    // FIXME: Map ranges?
-    EmitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
-
-    // Map the location.
-    Loc =3D getImmediateMacroCalleeLoc(SM, Loc);
-
-    unsigned MacroSkipStart =3D 0, MacroSkipEnd =3D 0;
-    if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
-      MacroSkipStart =3D DiagOpts.MacroBacktraceLimit / 2 +
-        DiagOpts.MacroBacktraceLimit % 2;
-      MacroSkipEnd =3D MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
-    }
-
-    // Whether to suppress printing this macro expansion.
-    bool Suppressed =3D (OnMacroInst >=3D MacroSkipStart &&
-                       OnMacroInst < MacroSkipEnd);
-
-    // Map the ranges.
-    for (SmallVectorImpl<CharSourceRange>::iterator I =3D Ranges.begin(),
-                                                    E =3D Ranges.end();
-         I !=3D E; ++I) {
-      SourceLocation Start =3D I->getBegin(), End =3D I->getEnd();
-      if (Start.isMacroID())
-        I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
-      if (End.isMacroID())
-        I->setEnd(getImmediateMacroCalleeLoc(SM, End));
-    }
-
-    if (!Suppressed) {
-      // Don't print recursive expansion notes from an expansion note.
-      Loc =3D SM.getSpellingLoc(Loc);
-
-      // Get the pretty name, according to #line directives etc.
-      PresumedLoc PLoc =3D SM.getPresumedLoc(Loc);
-      if (PLoc.isInvalid())
-        return;
-
-      // If this diagnostic is not in the main file, print out the
-      // "included from" lines.
-      Printer.PrintIncludeStack(DiagnosticsEngine::Note, PLoc.getIncludeLo=
c(),=20
-                                SM);
-
-      if (DiagOpts.ShowLocation) {
-        // Emit the file/line/column that this expansion came from.
-        OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
-        if (DiagOpts.ShowColumn)
-          OS << PLoc.getColumn() << ':';
-        OS << ' ';
-      }
-      OS << "note: expanded from:\n";
-
-      EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
-      return;
-    }
-
-    if (OnMacroInst =3D=3D MacroSkipStart) {
-      // Tell the user that we've skipped contexts.
-      OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)=20
-      << " expansions in backtrace; use -fmacro-backtrace-limit=3D0 to see=
 "
-      "all)\n";
-    }
-  }
-
-  /// \brief Emit a code snippet and caret line.
-  ///
-  /// This routine emits a single line's code snippet and caret line..
-  ///
-  /// \param Loc The location for the caret.
-  /// \param Ranges The underlined ranges for this code snippet.
-  /// \param Hints The FixIt hints active for this diagnostic.
-  void EmitSnippetAndCaret(SourceLocation Loc,
-                           SmallVectorImpl<CharSourceRange>& Ranges,
-                           ArrayRef<FixItHint> Hints) {
-    assert(!Loc.isInvalid() && "must have a valid source location here");
-    assert(Loc.isFileID() && "must have a file location here");
-
-    // Decompose the location into a FID/Offset pair.
-    std::pair<FileID, unsigned> LocInfo =3D SM.getDecomposedLoc(Loc);
-    FileID FID =3D LocInfo.first;
-    unsigned FileOffset =3D LocInfo.second;
-
-    // Get information about the buffer it points into.
-    bool Invalid =3D false;
-    const char *BufStart =3D SM.getBufferData(FID, &Invalid).data();
-    if (Invalid)
-      return;
-
-    unsigned LineNo =3D SM.getLineNumber(FID, FileOffset);
-    unsigned ColNo =3D SM.getColumnNumber(FID, FileOffset);
-    unsigned CaretEndColNo
-      =3D ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
-
-    // Rewind from the current position to the start of the line.
-    const char *TokPtr =3D BufStart+FileOffset;
-    const char *LineStart =3D TokPtr-ColNo+1; // Column # is 1-based.
-
-
-    // Compute the line end.  Scan forward from the error position to the =
end of
-    // the line.
-    const char *LineEnd =3D TokPtr;
-    while (*LineEnd !=3D '\n' && *LineEnd !=3D '\r' && *LineEnd !=3D '\0')
-      ++LineEnd;
-
-    // FIXME: This shouldn't be necessary, but the CaretEndColNo can exten=
d past
-    // the source line length as currently being computed. See
-    // test/Misc/message-length.c.
-    CaretEndColNo =3D std::min(CaretEndColNo, unsigned(LineEnd - LineStart=
));
-
-    // Copy the line of code into an std::string for ease of manipulation.
-    std::string SourceLine(LineStart, LineEnd);
-
-    // Create a line for the caret that is filled with spaces that is the =
same
-    // length as the line of source code.
-    std::string CaretLine(LineEnd-LineStart, ' ');
-
-    // Highlight all of the characters covered by Ranges with ~ characters.
-    for (SmallVectorImpl<CharSourceRange>::iterator I =3D Ranges.begin(),
-                                                    E =3D Ranges.end();
-         I !=3D E; ++I)
-      HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
-
-    // Next, insert the caret itself.
-    if (ColNo-1 < CaretLine.size())
-      CaretLine[ColNo-1] =3D '^';
-    else
-      CaretLine.push_back('^');
-
-    ExpandTabs(SourceLine, CaretLine);
-
-    // If we are in -fdiagnostics-print-source-range-info mode, we are try=
ing
-    // to produce easily machine parsable output.  Add a space before the
-    // source line and the caret to make it trivial to tell the main diagn=
ostic
-    // line from what the user is intended to see.
-    if (DiagOpts.ShowSourceRanges) {
-      SourceLine =3D ' ' + SourceLine;
-      CaretLine =3D ' ' + CaretLine;
-    }
-
-    std::string FixItInsertionLine =3D BuildFixItInsertionLine(LineNo,
-                                                             LineStart, Li=
neEnd,
-                                                             Hints);
-
-    // If the source line is too long for our terminal, select only the
-    // "interesting" source region within that line.
-    unsigned Columns =3D DiagOpts.MessageLength;
-    if (Columns && SourceLine.size() > Columns)
-      SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionL=
ine,
-                                    CaretEndColNo, Columns);
-
-    // Finally, remove any blank spaces from the end of CaretLine.
-    while (CaretLine[CaretLine.size()-1] =3D=3D ' ')
-      CaretLine.erase(CaretLine.end()-1);
-
-    // Emit what we have computed.
-    OS << SourceLine << '\n';
-
-    if (DiagOpts.ShowColors)
-      OS.changeColor(caretColor, true);
-    OS << CaretLine << '\n';
-    if (DiagOpts.ShowColors)
-      OS.resetColor();
-
-    if (!FixItInsertionLine.empty()) {
-      if (DiagOpts.ShowColors)
-        // Print fixit line in color
-        OS.changeColor(fixitColor, false);
-      if (DiagOpts.ShowSourceRanges)
-        OS << ' ';
-      OS << FixItInsertionLine << '\n';
-      if (DiagOpts.ShowColors)
-        OS.resetColor();
-    }
-
-    // Print out any parseable fixit information requested by the options.
-    EmitParseableFixits(Hints);
-  }
-
-private:
-  /// \brief Highlight a SourceRange (with ~'s) for any characters on Line=
No.
-  void HighlightRange(const CharSourceRange &R,
-                      unsigned LineNo, FileID FID,
-                      const std::string &SourceLine,
-                      std::string &CaretLine) {
-    assert(CaretLine.size() =3D=3D SourceLine.size() &&
-           "Expect a correspondence between source and caret line!");
-    if (!R.isValid()) return;
-
-    SourceLocation Begin =3D SM.getExpansionLoc(R.getBegin());
-    SourceLocation End =3D SM.getExpansionLoc(R.getEnd());
-
-    // If the End location and the start location are the same and are a m=
acro
-    // location, then the range was something that came from a macro expan=
sion
-    // or _Pragma.  If this is an object-like macro, the best we can do is=
 to
-    // highlight the range.  If this is a function-like macro, we'd also l=
ike to
-    // highlight the arguments.
-    if (Begin =3D=3D End && R.getEnd().isMacroID())
-      End =3D SM.getExpansionRange(R.getEnd()).second;
-
-    unsigned StartLineNo =3D SM.getExpansionLineNumber(Begin);
-    if (StartLineNo > LineNo || SM.getFileID(Begin) !=3D FID)
-      return;  // No intersection.
-
-    unsigned EndLineNo =3D SM.getExpansionLineNumber(End);
-    if (EndLineNo < LineNo || SM.getFileID(End) !=3D FID)
-      return;  // No intersection.
-
-    // Compute the column number of the start.
-    unsigned StartColNo =3D 0;
-    if (StartLineNo =3D=3D LineNo) {
-      StartColNo =3D SM.getExpansionColumnNumber(Begin);
-      if (StartColNo) --StartColNo;  // Zero base the col #.
-    }
-
-    // Compute the column number of the end.
-    unsigned EndColNo =3D CaretLine.size();
-    if (EndLineNo =3D=3D LineNo) {
-      EndColNo =3D SM.getExpansionColumnNumber(End);
-      if (EndColNo) {
-        --EndColNo;  // Zero base the col #.
-
-        // Add in the length of the token, so that we cover multi-char tok=
ens if
-        // this is a token range.
-        if (R.isTokenRange())
-          EndColNo +=3D Lexer::MeasureTokenLength(End, SM, LangOpts);
-      } else {
-        EndColNo =3D CaretLine.size();
-      }
-    }
-
-    assert(StartColNo <=3D EndColNo && "Invalid range!");
-
-    // Check that a token range does not highlight only whitespace.
-    if (R.isTokenRange()) {
-      // Pick the first non-whitespace column.
-      while (StartColNo < SourceLine.size() &&
-             (SourceLine[StartColNo] =3D=3D ' ' || SourceLine[StartColNo] =
=3D=3D '\t'))
-        ++StartColNo;
-
-      // Pick the last non-whitespace column.
-      if (EndColNo > SourceLine.size())
-        EndColNo =3D SourceLine.size();
-      while (EndColNo-1 &&
-             (SourceLine[EndColNo-1] =3D=3D ' ' || SourceLine[EndColNo-1] =
=3D=3D '\t'))
-        --EndColNo;
-
-      // If the start/end passed each other, then we are trying to highlig=
ht a
-      // range that just exists in whitespace, which must be some sort of =
other
-      // bug.
-      assert(StartColNo <=3D EndColNo && "Trying to highlight whitespace??=
");
-    }
-
-    // Fill the range with ~'s.
-    for (unsigned i =3D StartColNo; i < EndColNo; ++i)
-      CaretLine[i] =3D '~';
-  }
-
-  std::string BuildFixItInsertionLine(unsigned LineNo,
-                                      const char *LineStart,
-                                      const char *LineEnd,
-                                      ArrayRef<FixItHint> Hints) {
-    std::string FixItInsertionLine;
-    if (Hints.empty() || !DiagOpts.ShowFixits)
-      return FixItInsertionLine;
-
-    for (ArrayRef<FixItHint>::iterator I =3D Hints.begin(), E =3D Hints.en=
d();
-         I !=3D E; ++I) {
-      if (!I->CodeToInsert.empty()) {
-        // We have an insertion hint. Determine whether the inserted
-        // code is on the same line as the caret.
-        std::pair<FileID, unsigned> HintLocInfo
-          =3D SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
-        if (LineNo =3D=3D SM.getLineNumber(HintLocInfo.first, HintLocInfo.=
second)) {
-          // Insert the new code into the line just below the code
-          // that the user wrote.
-          unsigned HintColNo
-            =3D SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
-          unsigned LastColumnModified
-            =3D HintColNo - 1 + I->CodeToInsert.size();
-          if (LastColumnModified > FixItInsertionLine.size())
-            FixItInsertionLine.resize(LastColumnModified, ' ');
-          std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
-                    FixItInsertionLine.begin() + HintColNo - 1);
-        } else {
-          FixItInsertionLine.clear();
-          break;
-        }
-      }
-    }
-
-    if (FixItInsertionLine.empty())
-      return FixItInsertionLine;
-
-    // Now that we have the entire fixit line, expand the tabs in it.
-    // Since we don't want to insert spaces in the middle of a word,
-    // find each word and the column it should line up with and insert
-    // spaces until they match.
-    unsigned FixItPos =3D 0;
-    unsigned LinePos =3D 0;
-    unsigned TabExpandedCol =3D 0;
-    unsigned LineLength =3D LineEnd - LineStart;
-
-    while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
-      // Find the next word in the FixIt line.
-      while (FixItPos < FixItInsertionLine.size() &&
-             FixItInsertionLine[FixItPos] =3D=3D ' ')
-        ++FixItPos;
-      unsigned CharDistance =3D FixItPos - TabExpandedCol;
-
-      // Walk forward in the source line, keeping track of
-      // the tab-expanded column.
-      for (unsigned I =3D 0; I < CharDistance; ++I, ++LinePos)
-        if (LinePos >=3D LineLength || LineStart[LinePos] !=3D '\t')
-          ++TabExpandedCol;
-        else
-          TabExpandedCol =3D
-            (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
-
-      // Adjust the fixit line to match this column.
-      FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
-      FixItPos =3D TabExpandedCol;
-
-      // Walk to the end of the word.
-      while (FixItPos < FixItInsertionLine.size() &&
-             FixItInsertionLine[FixItPos] !=3D ' ')
-        ++FixItPos;
-    }
-
-    return FixItInsertionLine;
-  }
-
-  void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
-    // Scan the source line, looking for tabs.  If we find any, manually e=
xpand
-    // them to spaces and update the CaretLine to match.
-    for (unsigned i =3D 0; i !=3D SourceLine.size(); ++i) {
-      if (SourceLine[i] !=3D '\t') continue;
-
-      // Replace this tab with at least one space.
-      SourceLine[i] =3D ' ';
-
-      // Compute the number of spaces we need to insert.
-      unsigned TabStop =3D DiagOpts.TabStop;
-      assert(0 < TabStop && TabStop <=3D DiagnosticOptions::MaxTabStop &&
-             "Invalid -ftabstop value");
-      unsigned NumSpaces =3D ((i+TabStop)/TabStop * TabStop) - (i+1);
-      assert(NumSpaces < TabStop && "Invalid computation of space amt");
-
-      // Insert spaces into the SourceLine.
-      SourceLine.insert(i+1, NumSpaces, ' ');
-
-      // Insert spaces or ~'s into CaretLine.
-      CaretLine.insert(i+1, NumSpaces, CaretLine[i] =3D=3D '~' ? '~' : ' '=
);
-    }
-  }
-
-  void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
-    if (!DiagOpts.ShowParseableFixits)
-      return;
-
-    // We follow FixItRewriter's example in not (yet) handling
-    // fix-its in macros.
-    for (ArrayRef<FixItHint>::iterator I =3D Hints.begin(), E =3D Hints.en=
d();
-         I !=3D E; ++I) {
-      if (I->RemoveRange.isInvalid() ||
-          I->RemoveRange.getBegin().isMacroID() ||
-          I->RemoveRange.getEnd().isMacroID())
-        return;
-    }
-
-    for (ArrayRef<FixItHint>::iterator I =3D Hints.begin(), E =3D Hints.en=
d();
-         I !=3D E; ++I) {
-      SourceLocation BLoc =3D I->RemoveRange.getBegin();
-      SourceLocation ELoc =3D I->RemoveRange.getEnd();
-
-      std::pair<FileID, unsigned> BInfo =3D SM.getDecomposedLoc(BLoc);
-      std::pair<FileID, unsigned> EInfo =3D SM.getDecomposedLoc(ELoc);
-
-      // Adjust for token ranges.
-      if (I->RemoveRange.isTokenRange())
-        EInfo.second +=3D Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
-
-      // We specifically do not do word-wrapping or tab-expansion here,
-      // because this is supposed to be easy to parse.
-      PresumedLoc PLoc =3D SM.getPresumedLoc(BLoc);
-      if (PLoc.isInvalid())
-        break;
-
-      OS << "fix-it:\"";
-      OS.write_escaped(PLoc.getFilename());
-      OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
-        << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
-        << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
-        << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
-        << "}:\"";
-      OS.write_escaped(I->CodeToInsert);
-      OS << "\"\n";
-    }
-  }
-};
-
-} // end namespace
-
-/// Get the presumed location of a diagnostic message. This computes the
-/// presumed location for the top of any macro backtrace when present.
-static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
-                                            SourceLocation Loc) {
-  // This is a condensed form of the algorithm used by EmitCaretDiagnostic=
 to
-  // walk to the top of the macro call stack.
-  while (Loc.isMacroID()) {
-    Loc =3D skipToMacroArgExpansion(SM, Loc);
-    Loc =3D getImmediateMacroCallerLoc(SM, Loc);
-  }
-
-  return SM.getPresumedLoc(Loc);
-}
-
-/// \brief Print out the file/line/column information and include trace.
-///
-/// This method handlen the emission of the diagnostic location informatio=
n.
-/// This includes extracting as much location information as is present fo=
r the
-/// diagnostic and printing it, as well as any include stack or source ran=
ges
-/// necessary.
-void TextDiagnosticPrinter::EmitDiagnosticLoc(DiagnosticsEngine::Level Lev=
el,
-                                              const Diagnostic &Info,
-                                              const SourceManager &SM,
-                                              PresumedLoc PLoc) {
-  if (PLoc.isInvalid()) {
-    // At least print the file name if available:
-    FileID FID =3D SM.getFileID(Info.getLocation());
-    if (!FID.isInvalid()) {
-      const FileEntry* FE =3D SM.getFileEntryForID(FID);
-      if (FE && FE->getName()) {
-        OS << FE->getName();
-        if (FE->getDevice() =3D=3D 0 && FE->getInode() =3D=3D 0
-            && FE->getFileMode() =3D=3D 0) {
-          // in PCH is a guess, but a good one:
-          OS << " (in PCH)";
-        }
-        OS << ": ";
-      }
-    }
-    return;
-  }
-  unsigned LineNo =3D PLoc.getLine();
-
-  if (!DiagOpts->ShowLocation)
-    return;
-
-  if (DiagOpts->ShowColors)
-    OS.changeColor(savedColor, true);
-
-  OS << PLoc.getFilename();
-  switch (DiagOpts->Format) {
-  case DiagnosticOptions::Clang: OS << ':'  << LineNo; break;
-  case DiagnosticOptions::Msvc:  OS << '('  << LineNo; break;
-  case DiagnosticOptions::Vi:    OS << " +" << LineNo; break;
-  }
-
-  if (DiagOpts->ShowColumn)
-    // Compute the column number.
-    if (unsigned ColNo =3D PLoc.getColumn()) {
-      if (DiagOpts->Format =3D=3D DiagnosticOptions::Msvc) {
-        OS << ',';
-        ColNo--;
-      } else=20
-        OS << ':';
-      OS << ColNo;
-    }
-  switch (DiagOpts->Format) {
-  case DiagnosticOptions::Clang:=20
-  case DiagnosticOptions::Vi:    OS << ':';    break;
-  case DiagnosticOptions::Msvc:  OS << ") : "; break;
-  }
-
-  if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
-    FileID CaretFileID =3D
-      SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
-    bool PrintedRange =3D false;
-
-    for (unsigned i =3D 0, e =3D Info.getNumRanges(); i !=3D e; ++i) {
-      // Ignore invalid ranges.
-      if (!Info.getRange(i).isValid()) continue;
-
-      SourceLocation B =3D Info.getRange(i).getBegin();
-      SourceLocation E =3D Info.getRange(i).getEnd();
-      B =3D SM.getExpansionLoc(B);
-      E =3D SM.getExpansionLoc(E);
-
-      // If the End location and the start location are the same and are a
-      // macro location, then the range was something that came from a
-      // macro expansion or _Pragma.  If this is an object-like macro, the
-      // best we can do is to highlight the range.  If this is a
-      // function-like macro, we'd also like to highlight the arguments.
-      if (B =3D=3D E && Info.getRange(i).getEnd().isMacroID())
-        E =3D SM.getExpansionRange(Info.getRange(i).getEnd()).second;
-
-      std::pair<FileID, unsigned> BInfo =3D SM.getDecomposedLoc(B);
-      std::pair<FileID, unsigned> EInfo =3D SM.getDecomposedLoc(E);
-
-      // If the start or end of the range is in another file, just discard
-      // it.
-      if (BInfo.first !=3D CaretFileID || EInfo.first !=3D CaretFileID)
-        continue;
-
-      // Add in the length of the token, so that we cover multi-char
-      // tokens.
-      unsigned TokSize =3D 0;
-      if (Info.getRange(i).isTokenRange())
-        TokSize =3D Lexer::MeasureTokenLength(E, SM, *LangOpts);
-
-      OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
-        << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
-        << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
-        << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
-        << '}';
-      PrintedRange =3D true;
-    }
-
-    if (PrintedRange)
-      OS << ':';
-  }
-  OS << ' ';
-}
-
-/// \brief Print the diagonstic level to a raw_ostream.
-///
-/// Handles colorizing the level and formatting.
-static void printDiagnosticLevel(raw_ostream &OS,
-                                 DiagnosticsEngine::Level Level,
-                                 bool ShowColors) {
-  if (ShowColors) {
-    // Print diagnostic category in bold and color
-    switch (Level) {
-    case DiagnosticsEngine::Ignored:
-      llvm_unreachable("Invalid diagnostic type");
-    case DiagnosticsEngine::Note:    OS.changeColor(noteColor, true); brea=
k;
-    case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); b=
reak;
-    case DiagnosticsEngine::Error:   OS.changeColor(errorColor, true); bre=
ak;
-    case DiagnosticsEngine::Fatal:   OS.changeColor(fatalColor, true); bre=
ak;
-    }
-  }
-
-  switch (Level) {
-  case DiagnosticsEngine::Ignored: llvm_unreachable("Invalid diagnostic ty=
pe");
-  case DiagnosticsEngine::Note:    OS << "note: "; break;
-  case DiagnosticsEngine::Warning: OS << "warning: "; break;
-  case DiagnosticsEngine::Error:   OS << "error: "; break;
-  case DiagnosticsEngine::Fatal:   OS << "fatal error: "; break;
-  }
-
-  if (ShowColors)
-    OS.resetColor();
-}
-
-/// \brief Print the diagnostic name to a raw_ostream.
-///
-/// This prints the diagnostic name to a raw_ostream if it has one. It for=
mats
-/// the name according to the expected diagnostic message formatting:
-///   " [diagnostic_name_here]"
-static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
-  if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
-    OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
+void TextDiagnosticPrinter::EndSourceFile() {
+  LangOpts =3D 0;
+  TextDiag.reset(0);
 }
=20
 /// \brief Print any diagnostic option information to a raw_ostream.
@@ -996,182 +115,6 @@
     OS << ']';
 }
=20
-/// \brief Skip over whitespace in the string, starting at the given
-/// index.
-///
-/// \returns The index of the first non-whitespace character that is
-/// greater than or equal to Idx or, if no such character exists,
-/// returns the end of the string.
-static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Lengt=
h) {
-  while (Idx < Length && isspace(Str[Idx]))
-    ++Idx;
-  return Idx;
-}
-
-/// \brief If the given character is the start of some kind of
-/// balanced punctuation (e.g., quotes or parentheses), return the
-/// character that will terminate the punctuation.
-///
-/// \returns The ending punctuation character, if any, or the NULL
-/// character if the input character does not start any punctuation.
-static inline char findMatchingPunctuation(char c) {
-  switch (c) {
-  case '\'': return '\'';
-  case '`': return '\'';
-  case '"':  return '"';
-  case '(':  return ')';
-  case '[': return ']';
-  case '{': return '}';
-  default: break;
-  }
-
-  return 0;
-}
-
-/// \brief Find the end of the word starting at the given offset
-/// within a string.
-///
-/// \returns the index pointing one character past the end of the
-/// word.
-static unsigned findEndOfWord(unsigned Start, StringRef Str,
-                              unsigned Length, unsigned Column,
-                              unsigned Columns) {
-  assert(Start < Str.size() && "Invalid start position!");
-  unsigned End =3D Start + 1;
-
-  // If we are already at the end of the string, take that as the word.
-  if (End =3D=3D Str.size())
-    return End;
-
-  // Determine if the start of the string is actually opening
-  // punctuation, e.g., a quote or parentheses.
-  char EndPunct =3D findMatchingPunctuation(Str[Start]);
-  if (!EndPunct) {
-    // This is a normal word. Just find the first space character.
-    while (End < Length && !isspace(Str[End]))
-      ++End;
-    return End;
-  }
-
-  // We have the start of a balanced punctuation sequence (quotes,
-  // parentheses, etc.). Determine the full sequence is.
-  llvm::SmallString<16> PunctuationEndStack;
-  PunctuationEndStack.push_back(EndPunct);
-  while (End < Length && !PunctuationEndStack.empty()) {
-    if (Str[End] =3D=3D PunctuationEndStack.back())
-      PunctuationEndStack.pop_back();
-    else if (char SubEndPunct =3D findMatchingPunctuation(Str[End]))
-      PunctuationEndStack.push_back(SubEndPunct);
-
-    ++End;
-  }
-
-  // Find the first space character after the punctuation ended.
-  while (End < Length && !isspace(Str[End]))
-    ++End;
-
-  unsigned PunctWordLength =3D End - Start;
-  if (// If the word fits on this line
-      Column + PunctWordLength <=3D Columns ||
-      // ... or the word is "short enough" to take up the next line
-      // without too much ugly white space
-      PunctWordLength < Columns/3)
-    return End; // Take the whole thing as a single "word".
-
-  // The whole quoted/parenthesized string is too long to print as a
-  // single "word". Instead, find the "word" that starts just after
-  // the punctuation and use that end-point instead. This will recurse
-  // until it finds something small enough to consider a word.
-  return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
-}
-
-/// \brief Print the given string to a stream, word-wrapping it to
-/// some number of columns in the process.
-///
-/// \param OS the stream to which the word-wrapping string will be
-/// emitted.
-/// \param Str the string to word-wrap and output.
-/// \param Columns the number of columns to word-wrap to.
-/// \param Column the column number at which the first character of \p
-/// Str will be printed. This will be non-zero when part of the first
-/// line has already been printed.
-/// \param Indentation the number of spaces to indent any lines beyond
-/// the first line.
-/// \returns true if word-wrapping was required, or false if the
-/// string fit on the first line.
-static bool printWordWrapped(raw_ostream &OS, StringRef Str,
-                             unsigned Columns,
-                             unsigned Column =3D 0,
-                             unsigned Indentation =3D WordWrapIndentation)=
 {
-  const unsigned Length =3D std::min(Str.find('\n'), Str.size());
-
-  // The string used to indent each line.
-  llvm::SmallString<16> IndentStr;
-  IndentStr.assign(Indentation, ' ');
-  bool Wrapped =3D false;
-  for (unsigned WordStart =3D 0, WordEnd; WordStart < Length;
-       WordStart =3D WordEnd) {
-    // Find the beginning of the next word.
-    WordStart =3D skipWhitespace(WordStart, Str, Length);
-    if (WordStart =3D=3D Length)
-      break;
-
-    // Find the end of this word.
-    WordEnd =3D findEndOfWord(WordStart, Str, Length, Column, Columns);
-
-    // Does this word fit on the current line?
-    unsigned WordLength =3D WordEnd - WordStart;
-    if (Column + WordLength < Columns) {
-      // This word fits on the current line; print it there.
-      if (WordStart) {
-        OS << ' ';
-        Column +=3D 1;
-      }
-      OS << Str.substr(WordStart, WordLength);
-      Column +=3D WordLength;
-      continue;
-    }
-
-    // This word does not fit on the current line, so wrap to the next
-    // line.
-    OS << '\n';
-    OS.write(&IndentStr[0], Indentation);
-    OS << Str.substr(WordStart, WordLength);
-    Column =3D Indentation + WordLength;
-    Wrapped =3D true;
-  }
-
-  // Append any remaning text from the message with its existing formattin=
g.
-  OS << Str.substr(Length);
-
-  return Wrapped;
-}
-
-static void printDiagnosticMessage(raw_ostream &OS,
-                                   DiagnosticsEngine::Level Level,
-                                   StringRef Message,
-                                   unsigned CurrentColumn, unsigned Column=
s,
-                                   bool ShowColors) {
-  if (ShowColors) {
-    // Print warnings, errors and fatal errors in bold, no color
-    switch (Level) {
-    case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); bre=
ak;
-    case DiagnosticsEngine::Error:   OS.changeColor(savedColor, true); bre=
ak;
-    case DiagnosticsEngine::Fatal:   OS.changeColor(savedColor, true); bre=
ak;
-    default: break; //don't bold notes
-    }
-  }
-
-  if (Columns)
-    printWordWrapped(OS, Message, Columns, CurrentColumn);
-  else
-    OS << Message;
-
-  if (ShowColors)
-    OS.resetColor();
-  OS << '\n';
-}
-
 void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Leve=
l,
                                              const Diagnostic &Info) {
   // Default implementation (Warnings/errors count).
@@ -1179,15 +122,12 @@
=20
   // Render the diagnostic message into a temporary buffer eagerly. We'll =
use
   // this later as we print out the diagnostic to the terminal.
-  llvm::SmallString<100> OutStr;
+  SmallString<100> OutStr;
   Info.FormatDiagnostic(OutStr);
=20
   llvm::raw_svector_ostream DiagMessageStream(OutStr);
-  if (DiagOpts->ShowNames)
-    printDiagnosticName(DiagMessageStream, Info);
   printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
=20
-
   // Keeps track of the the starting position of the location
   // information (e.g., "foo.c:10:4:") that precedes the error
   // message. We use this information to determine how long the
@@ -1202,10 +142,11 @@
   // diagnostics in a context that lacks language options, a source manage=
r, or
   // other infrastructure necessary when emitting more rich diagnostics.
   if (!Info.getLocation().isValid()) {
-    printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
-    printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
-                           OS.tell() - StartOfLocationInfo,
-                           DiagOpts->MessageLength, DiagOpts->ShowColors);
+    TextDiagnostic::printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
+    TextDiagnostic::printDiagnosticMessage(OS, Level, DiagMessageStream.st=
r(),
+                                           OS.tell() - StartOfLocationInfo,
+                                           DiagOpts->MessageLength,
+                                           DiagOpts->ShowColors);
     OS.flush();
     return;
   }
@@ -1215,59 +156,18 @@
   assert(DiagOpts && "Unexpected diagnostic without options set");
   assert(Info.hasSourceManager() &&
          "Unexpected diagnostic with no source manager");
-  const SourceManager &SM =3D Info.getSourceManager();
-  TextDiagnostic TextDiag(*this, OS, SM, *LangOpts, *DiagOpts);
=20
-  PresumedLoc PLoc =3D getDiagnosticPresumedLoc(SM, Info.getLocation());
+  // Rebuild the TextDiagnostic utility if missing or the source manager h=
as
+  // changed.
+  if (!TextDiag || SM !=3D &Info.getSourceManager()) {
+    SM =3D &Info.getSourceManager();
+    TextDiag.reset(new TextDiagnostic(OS, *SM, *LangOpts, *DiagOpts));
+  }
=20
-  // First, if this diagnostic is not in the main file, print out the
-  // "included from" lines.
-  PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
-  StartOfLocationInfo =3D OS.tell();
-
-  // Next emit the location of this particular diagnostic.
-  EmitDiagnosticLoc(Level, Info, SM, PLoc);
-
-  if (DiagOpts->ShowColors)
-    OS.resetColor();
-
-  printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
-  printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
-                         OS.tell() - StartOfLocationInfo,
-                         DiagOpts->MessageLength, DiagOpts->ShowColors);
-
-  // If caret diagnostics are enabled and we have location, we want to
-  // emit the caret.  However, we only do this if the location moved
-  // from the last diagnostic, if the last diagnostic was a note that
-  // was part of a different warning or error diagnostic, or if the
-  // diagnostic has ranges.  We don't want to emit the same caret
-  // multiple times if one loc has multiple diagnostics.
-  if (DiagOpts->ShowCarets &&
-      ((LastLoc !=3D Info.getLocation()) || Info.getNumRanges() ||
-       (LastCaretDiagnosticWasNote && Level !=3D DiagnosticsEngine::Note) =
||
-       Info.getNumFixItHints())) {
-    // Cache the LastLoc, it allows us to omit duplicate source/caret spew=
age.
-    LastLoc =3D FullSourceLoc(Info.getLocation(), Info.getSourceManager());
-    LastCaretDiagnosticWasNote =3D (Level =3D=3D DiagnosticsEngine::Note);
-
-    // Get the ranges into a local array we can hack on.
-    SmallVector<CharSourceRange, 20> Ranges;
-    Ranges.reserve(Info.getNumRanges());
-    for (unsigned i =3D 0, e =3D Info.getNumRanges(); i !=3D e; ++i)
-      Ranges.push_back(Info.getRange(i));
-
-    for (unsigned i =3D 0, e =3D Info.getNumFixItHints(); i !=3D e; ++i) {
-      const FixItHint &Hint =3D Info.getFixItHint(i);
-      if (Hint.RemoveRange.isValid())
-        Ranges.push_back(Hint.RemoveRange);
-    }
-
-    unsigned MacroDepth =3D 0;
-    TextDiag.EmitCaret(LastLoc, Ranges,
-                       llvm::makeArrayRef(Info.getFixItHints(),
-                                          Info.getNumFixItHints()),
-                       MacroDepth);
-  }
+  TextDiag->emitDiagnostic(Info.getLocation(), Level, DiagMessageStream.st=
r(),
+                           Info.getRanges(),
+                           llvm::makeArrayRef(Info.getFixItHints(),
+                                              Info.getNumFixItHints()));
=20
   OS.flush();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/VerifyDiagnosticConsumer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/VerifyDiagnosticConsumer.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -18,6 +18,8 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/Regex.h"
 #include "llvm/Support/raw_ostream.h"
+#include <climits>
+
 using namespace clang;
=20
 VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Dia=
gs)
@@ -38,7 +40,7 @@
 // DiagnosticConsumer interface.
=20
 void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
-                                             const Preprocessor *PP) {
+                                               const Preprocessor *PP) {
   // FIXME: Const hack, we screw up the preprocessor but in practice its ok
   // because it doesn't get reused. It would be better if we could make a =
copy
   // though.
@@ -82,6 +84,9 @@
   static Directive* Create(bool RegexKind, const SourceLocation &Location,
                            const std::string &Text, unsigned Count);
 public:
+  /// Constant representing one or more matches aka regex "+".
+  static const unsigned OneOrMoreCount =3D  UINT_MAX;
+
   SourceLocation Location;
   const std::string Text;
   unsigned Count;
@@ -119,8 +124,7 @@
   }
=20
   virtual bool Match(const std::string &S) {
-    return S.find(Text) !=3D std::string::npos ||
-           Text.find(S) !=3D std::string::npos;
+    return S.find(Text) !=3D std::string::npos;
   }
 };
=20
@@ -277,10 +281,14 @@
     // skip optional whitespace
     PH.SkipWhitespace();
=20
-    // next optional token: positive integer
+    // next optional token: positive integer or a '+'.
     unsigned Count =3D 1;
     if (PH.Next(Count))
       PH.Advance();
+    else if (PH.Next("+")) {
+      Count =3D Directive::OneOrMoreCount;
+      PH.Advance();
+    }
=20
     // skip optional whitespace
     PH.SkipWhitespace();
@@ -340,7 +348,7 @@
   SourceManager& SM =3D PP.getSourceManager();
   // Create a lexer to lex all the tokens of the main file in raw mode.
   const llvm::MemoryBuffer *FromFile =3D SM.getBuffer(FID);
-  Lexer RawLex(FID, FromFile, SM, PP.getLangOptions());
+  Lexer RawLex(FID, FromFile, SM, PP.getLangOpts());
=20
   // Return comments as tokens, this is how we find expected diagnostics.
   RawLex.SetCommentRetentionState(true);
@@ -370,7 +378,7 @@
                              const char *Kind, bool Expected) {
   if (diag_begin =3D=3D diag_end) return 0;
=20
-  llvm::SmallString<256> Fmt;
+  SmallString<256> Fmt;
   llvm::raw_svector_ostream OS(Fmt);
   for (const_diag_iterator I =3D diag_begin, E =3D diag_end; I !=3D E; ++I=
) {
     if (I->first.isInvalid() || !SourceMgr)
@@ -391,7 +399,7 @@
   if (DL.empty())
     return 0;
=20
-  llvm::SmallString<256> Fmt;
+  SmallString<256> Fmt;
   llvm::raw_svector_ostream OS(Fmt);
   for (DirectiveList::iterator I =3D DL.begin(), E =3D DL.end(); I !=3D E;=
 ++I) {
     Directive& D =3D **I;
@@ -421,6 +429,7 @@
   for (DirectiveList::iterator I =3D Left.begin(), E =3D Left.end(); I !=
=3D E; ++I) {
     Directive& D =3D **I;
     unsigned LineNo1 =3D SourceMgr.getPresumedLineNumber(D.Location);
+    bool FoundOnce =3D false;
=20
     for (unsigned i =3D 0; i < D.Count; ++i) {
       DiagList::iterator II, IE;
@@ -434,19 +443,26 @@
           break;
       }
       if (II =3D=3D IE) {
+        if (D.Count =3D=3D D.OneOrMoreCount) {
+          if (!FoundOnce)
+            LeftOnly.push_back(*I);
+          // We are only interested in at least one match, so exit the loo=
p.
+          break;
+        }
         // Not found.
         LeftOnly.push_back(*I);
       } else {
         // Found. The same cannot be found twice.
         Right.erase(II);
+        FoundOnce =3D true;
       }
     }
   }
   // Now all that's left in Right are those that were not matched.
-
-  return (PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true) +
-          PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
-                       Label, false));
+  unsigned num =3D PrintProblem(Diags, &SourceMgr, LeftOnly, Label, true);
+  num +=3D PrintProblem(Diags, &SourceMgr, Right.begin(), Right.end(),
+                      Label, false);
+  return num;
 }
=20
 /// CheckResults - This compares the expected results to those that
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tend/Warnings.cpp
--- a/head/contrib/llvm/tools/clang/lib/Frontend/Warnings.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Frontend/Warnings.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -31,6 +31,22 @@
 #include <algorithm>
 using namespace clang;
=20
+// EmitUnknownDiagWarning - Emit a warning and typo hint for unknown warni=
ng
+// opts
+static void EmitUnknownDiagWarning(DiagnosticsEngine &Diags,
+                                  StringRef Prefix, StringRef Opt,
+                                  bool isPositive) {
+  StringRef Suggestion =3D DiagnosticIDs::getNearestWarningOption(Opt);
+  if (!Suggestion.empty())
+    Diags.Report(isPositive? diag::warn_unknown_warning_option_suggest :
+                             diag::warn_unknown_negative_warning_option_su=
ggest)
+      << (Prefix.str() +=3D Opt) << (Prefix.str() +=3D Suggestion);
+  else
+    Diags.Report(isPositive? diag::warn_unknown_warning_option :
+                             diag::warn_unknown_negative_warning_option)
+      << (Prefix.str() +=3D Opt);
+}
+
 void clang::ProcessWarningOptions(DiagnosticsEngine &Diags,
                                   const DiagnosticOptions &Opts) {
   Diags.setSuppressSystemWarnings(true);  // Default to -Wno-system-headers
@@ -43,6 +59,8 @@
     Diags.setErrorLimit(Opts.ErrorLimit);
   if (Opts.TemplateBacktraceLimit)
     Diags.setTemplateBacktraceLimit(Opts.TemplateBacktraceLimit);
+  if (Opts.ConstexprBacktraceLimit)
+    Diags.setConstexprBacktraceLimit(Opts.ConstexprBacktraceLimit);
=20
   // If -pedantic or -pedantic-errors was specified, then we want to map a=
ll
   // extension diagnostics onto WARNING or ERROR unless the user has futz'd
@@ -54,92 +72,120 @@
   else
     Diags.setExtensionHandlingBehavior(DiagnosticsEngine::Ext_Ignore);
=20
-  for (unsigned i =3D 0, e =3D Opts.Warnings.size(); i !=3D e; ++i) {
-    StringRef Opt =3D Opts.Warnings[i];
+  llvm::SmallVector<diag::kind, 10> _Diags;
+  const IntrusiveRefCntPtr< DiagnosticIDs > DiagIDs =3D
+    Diags.getDiagnosticIDs();
+  // We parse the warning options twice.  The first pass sets diagnostic s=
tate,
+  // while the second pass reports warnings/errors.  This has the effect t=
hat
+  // we follow the more canonical "last option wins" paradigm when there a=
re=20
+  // conflicting options.
+  for (unsigned Report =3D 0, ReportEnd =3D 2; Report !=3D ReportEnd; ++Re=
port) {
+    bool SetDiagnostic =3D (Report =3D=3D 0);
+    for (unsigned i =3D 0, e =3D Opts.Warnings.size(); i !=3D e; ++i) {
+      StringRef Opt =3D Opts.Warnings[i];
=20
-    // Check to see if this warning starts with "no-", if so, this is a ne=
gative
-    // form of the option.
-    bool isPositive =3D true;
-    if (Opt.startswith("no-")) {
-      isPositive =3D false;
-      Opt =3D Opt.substr(3);
-    }
+      // Treat -Wformat=3D0 as an alias for -Wno-format.
+      if (Opt =3D=3D "format=3D0")
+        Opt =3D "no-format";
=20
-    // Figure out how this option affects the warning.  If -Wfoo, map the
-    // diagnostic to a warning, if -Wno-foo, map it to ignore.
-    diag::Mapping Mapping =3D isPositive ? diag::MAP_WARNING : diag::MAP_I=
GNORE;
+      // Check to see if this warning starts with "no-", if so, this is a
+      // negative form of the option.
+      bool isPositive =3D true;
+      if (Opt.startswith("no-")) {
+        isPositive =3D false;
+        Opt =3D Opt.substr(3);
+      }
=20
-    // -Wsystem-headers is a special case, not driven by the option table.=
  It
-    // cannot be controlled with -Werror.
-    if (Opt =3D=3D "system-headers") {
-      Diags.setSuppressSystemWarnings(!isPositive);
-      continue;
-    }
-   =20
-    // -Weverything is a special case as well.  It implicitly enables all
-    // warnings, including ones not explicitly in a warning group.
-    if (Opt =3D=3D "everything") {
-      Diags.setEnableAllWarnings(true);
-      continue;
-    }
-
-    // -Werror/-Wno-error is a special case, not controlled by the option =
table.
-    // It also has the "specifier" form of -Werror=3Dfoo and -Werror-foo.
-    if (Opt.startswith("error")) {
-      StringRef Specifier;
-      if (Opt.size() > 5) {  // Specifier must be present.
-        if ((Opt[5] !=3D '=3D' && Opt[5] !=3D '-') || Opt.size() =3D=3D 6)=
 {
-          Diags.Report(diag::warn_unknown_warning_specifier)
-            << "-Werror" << ("-W" + Opt.str());
+      // Figure out how this option affects the warning.  If -Wfoo, map the
+      // diagnostic to a warning, if -Wno-foo, map it to ignore.
+      diag::Mapping Mapping =3D isPositive ? diag::MAP_WARNING : diag::MAP=
_IGNORE;
+     =20
+      // -Wsystem-headers is a special case, not driven by the option tabl=
e.  It
+      // cannot be controlled with -Werror.
+      if (Opt =3D=3D "system-headers") {
+        if (SetDiagnostic)
+          Diags.setSuppressSystemWarnings(!isPositive);
+        continue;
+      }
+     =20
+      // -Weverything is a special case as well.  It implicitly enables all
+      // warnings, including ones not explicitly in a warning group.
+      if (Opt =3D=3D "everything") {
+        if (SetDiagnostic) {
+          if (isPositive) {
+            Diags.setEnableAllWarnings(true);
+          } else {
+            Diags.setEnableAllWarnings(false);
+            Diags.setMappingToAllDiagnostics(diag::MAP_IGNORE);
+          }
+        }
+        continue;
+      }
+     =20
+      // -Werror/-Wno-error is a special case, not controlled by the optio=
n=20
+      // table. It also has the "specifier" form of -Werror=3Dfoo and -Wer=
ror-foo.
+      if (Opt.startswith("error")) {
+        StringRef Specifier;
+        if (Opt.size() > 5) {  // Specifier must be present.
+          if ((Opt[5] !=3D '=3D' && Opt[5] !=3D '-') || Opt.size() =3D=3D =
6) {
+            if (Report)
+              Diags.Report(diag::warn_unknown_warning_specifier)
+                << "-Werror" << ("-W" + Opt.str());
+            continue;
+          }
+          Specifier =3D Opt.substr(6);
+        }
+       =20
+        if (Specifier.empty()) {
+          if (SetDiagnostic)
+            Diags.setWarningsAsErrors(isPositive);
           continue;
         }
-        Specifier =3D Opt.substr(6);
-      }
-
-      if (Specifier.empty()) {
-        Diags.setWarningsAsErrors(isPositive);
+       =20
+        if (SetDiagnostic) {
+          // Set the warning as error flag for this specifier.
+          Diags.setDiagnosticGroupWarningAsError(Specifier, isPositive);
+        } else if (DiagIDs->getDiagnosticsInGroup(Specifier, _Diags)) {
+          EmitUnknownDiagWarning(Diags, "-Werror=3D", Specifier, isPositiv=
e);
+        }
         continue;
       }
+     =20
+      // -Wfatal-errors is yet another special case.
+      if (Opt.startswith("fatal-errors")) {
+        StringRef Specifier;
+        if (Opt.size() !=3D 12) {
+          if ((Opt[12] !=3D '=3D' && Opt[12] !=3D '-') || Opt.size() =3D=
=3D 13) {
+            if (Report)
+              Diags.Report(diag::warn_unknown_warning_specifier)
+                << "-Wfatal-errors" << ("-W" + Opt.str());
+            continue;
+          }
+          Specifier =3D Opt.substr(13);
+        }
=20
-      // Set the warning as error flag for this specifier.
-      if (Diags.setDiagnosticGroupWarningAsError(Specifier, isPositive)) {
-        Diags.Report(isPositive ? diag::warn_unknown_warning_option :
-                     diag::warn_unknown_negative_warning_option)
-          << ("-W" + Opt.str());
-      }
-      continue;
-    }
-
-    // -Wfatal-errors is yet another special case.
-    if (Opt.startswith("fatal-errors")) {
-      StringRef Specifier;
-      if (Opt.size() !=3D 12) {
-        if ((Opt[12] !=3D '=3D' && Opt[12] !=3D '-') || Opt.size() =3D=3D =
13) {
-          Diags.Report(diag::warn_unknown_warning_specifier)
-            << "-Wfatal-errors" << ("-W" + Opt.str());
+        if (Specifier.empty()) {
+          if (SetDiagnostic)
+            Diags.setErrorsAsFatal(isPositive);
           continue;
         }
-        Specifier =3D Opt.substr(13);
-      }
-
-      if (Specifier.empty()) {
-        Diags.setErrorsAsFatal(isPositive);
+       =20
+        if (SetDiagnostic) {
+          // Set the error as fatal flag for this specifier.
+          Diags.setDiagnosticGroupErrorAsFatal(Specifier, isPositive);
+        } else if (DiagIDs->getDiagnosticsInGroup(Specifier, _Diags)) {
+          EmitUnknownDiagWarning(Diags, "-Wfatal-errors=3D", Specifier,
+                                 isPositive);
+        }
         continue;
       }
-
-      // Set the error as fatal flag for this specifier.
-      if (Diags.setDiagnosticGroupErrorAsFatal(Specifier, isPositive)) {
-        Diags.Report(isPositive ? diag::warn_unknown_warning_option :
-                     diag::warn_unknown_negative_warning_option)
-          << ("-W" + Opt.str());
+     =20
+      if (Report) {
+        if (DiagIDs->getDiagnosticsInGroup(Opt, _Diags))
+          EmitUnknownDiagWarning(Diags, "-W", Opt, isPositive);
+      } else {
+        Diags.setDiagnosticGroupMapping(Opt, Mapping);
       }
-      continue;
-    }
-
-    if (Diags.setDiagnosticGroupMapping(Opt, Mapping)) {
-      Diags.Report(isPositive ? diag::warn_unknown_warning_option :
-                   diag::warn_unknown_negative_warning_option)
-          << ("-W" + Opt.str());
     }
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Fron=
tendTool/ExecuteCompilerInvocation.cpp
--- a/head/contrib/llvm/tools/clang/lib/FrontendTool/ExecuteCompilerInvocat=
ion.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/FrontendTool/ExecuteCompilerInvocat=
ion.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -32,9 +32,6 @@
   using namespace clang::frontend;
=20
   switch (CI.getFrontendOpts().ProgramAction) {
-  default:
-    llvm_unreachable("Invalid program action!");
-
   case ASTDump:                return new ASTDumpAction();
   case ASTDumpXML:             return new ASTDumpXMLAction();
   case ASTPrint:               return new ASTPrintAction();
@@ -49,8 +46,8 @@
   case EmitCodeGenOnly:        return new EmitCodeGenOnlyAction();
   case EmitObj:                return new EmitObjAction();
   case FixIt:                  return new FixItAction();
-  case GenerateModule:         return new GeneratePCHAction(true);
-  case GeneratePCH:            return new GeneratePCHAction(false);
+  case GenerateModule:         return new GenerateModuleAction;
+  case GeneratePCH:            return new GeneratePCHAction;
   case GeneratePTH:            return new GeneratePTHAction();
   case InitOnly:               return new InitOnlyAction();
   case ParseSyntaxOnly:        return new SyntaxOnlyAction();
@@ -60,7 +57,7 @@
            FrontendPluginRegistry::begin(), ie =3D FrontendPluginRegistry:=
:end();
          it !=3D ie; ++it) {
       if (it->getName() =3D=3D CI.getFrontendOpts().ActionName) {
-        llvm::OwningPtr<PluginASTAction> P(it->instantiate());
+        OwningPtr<PluginASTAction> P(it->instantiate());
         if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
           return 0;
         return P.take();
@@ -75,12 +72,15 @@
   case PrintDeclContext:       return new DeclContextPrintAction();
   case PrintPreamble:          return new PrintPreambleAction();
   case PrintPreprocessedInput: return new PrintPreprocessedAction();
+  case PubnamesDump:           return new PubnamesDumpAction();
   case RewriteMacros:          return new RewriteMacrosAction();
   case RewriteObjC:            return new RewriteObjCAction();
   case RewriteTest:            return new RewriteTestAction();
   case RunAnalysis:            return new ento::AnalysisAction();
+  case MigrateSource:          return new arcmt::MigrateSourceAction();
   case RunPreprocessorOnly:    return new PreprocessOnlyAction();
   }
+  llvm_unreachable("Invalid program action!");
 }
=20
 static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
@@ -89,8 +89,14 @@
   if (!Act)
     return 0;
=20
+  const FrontendOptions &FEOpts =3D CI.getFrontendOpts();
+
+  if (FEOpts.FixAndRecompile) {
+    Act =3D new FixItRecompile(Act);
+  }
+ =20
   // Potentially wrap the base FE action in an ARC Migrate Tool action.
-  switch (CI.getFrontendOpts().ARCMTAction) {
+  switch (FEOpts.ARCMTAction) {
   case FrontendOptions::ARCMT_None:
     break;
   case FrontendOptions::ARCMT_Check:
@@ -101,17 +107,22 @@
     break;
   case FrontendOptions::ARCMT_Migrate:
     Act =3D new arcmt::MigrateAction(Act,
-                                   CI.getFrontendOpts().ARCMTMigrateDir,
-                                   CI.getFrontendOpts().ARCMTMigrateReport=
Out,
-                                CI.getFrontendOpts().ARCMTMigrateEmitARCEr=
rors);
+                                   FEOpts.MTMigrateDir,
+                                   FEOpts.ARCMTMigrateReportOut,
+                                   FEOpts.ARCMTMigrateEmitARCErrors);
     break;
   }
=20
+  if (FEOpts.ObjCMTAction !=3D FrontendOptions::ObjCMT_None) {
+    Act =3D new arcmt::ObjCMigrateAction(Act, FEOpts.MTMigrateDir,
+                   FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Literals,
+                   FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Subscrip=
ting);
+  }
+
   // If there are any AST files to merge, create a frontend action
   // adaptor to perform the merge.
-  if (!CI.getFrontendOpts().ASTMergeFiles.empty())
-    Act =3D new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
-                             CI.getFrontendOpts().ASTMergeFiles.size());
+  if (!FEOpts.ASTMergeFiles.empty())
+    Act =3D new ASTMergeAction(Act, FEOpts.ASTMergeFiles);
=20
   return Act;
 }
@@ -119,7 +130,7 @@
 bool clang::ExecuteCompilerInvocation(CompilerInstance *Clang) {
   // Honor -help.
   if (Clang->getFrontendOpts().ShowHelp) {
-    llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1OptTable());
+    OwningPtr<driver::OptTable> Opts(driver::createCC1OptTable());
     Opts->PrintHelp(llvm::outs(), "clang -cc1",
                     "LLVM 'Clang' Compiler: http://clang.llvm.org");
     return 0;
@@ -154,7 +165,7 @@
     for (unsigned i =3D 0; i !=3D NumArgs; ++i)
       Args[i + 1] =3D Clang->getFrontendOpts().LLVMArgs[i].c_str();
     Args[NumArgs + 1] =3D 0;
-    llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Arg=
s));
+    llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
   }
=20
   // Honor -analyzer-checker-help.
@@ -168,7 +179,7 @@
   bool Success =3D false;
   if (!Clang->getDiagnostics().hasErrorOccurred()) {
     // Create and execute the frontend action.
-    llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
+    OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
     if (Act) {
       Success =3D Clang->ExecuteAction(*Act);
       if (Clang->getFrontendOpts().DisableFree)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/avxintrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/avxintrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/avxintrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -145,17 +145,13 @@
   return (__m256)__builtin_ia32_rcpps256((__v8sf)a);
 }
=20
-static __inline __m256d __attribute__((__always_inline__, __nodebug__))
-_mm256_round_pd(__m256d v, const int m)
-{
-  return (__m256d)__builtin_ia32_roundpd256((__v4df)v, m);
-}
+#define _mm256_round_pd(V, M) __extension__ ({ \
+    __m256d __V =3D (V); \
+    (__m256d)__builtin_ia32_roundpd256((__v4df)__V, (M)); })
=20
-static __inline __m256 __attribute__((__always_inline__, __nodebug__))
-_mm256_round_ps(__m256 v, const int m)
-{
-  return (__m256)__builtin_ia32_roundps256((__v8sf)v, m);
-}
+#define _mm256_round_ps(V, M) __extension__ ({ \
+  __m256 __V =3D (V); \
+  (__m256)__builtin_ia32_roundps256((__v8sf)__V, (M)); })
=20
 #define _mm256_ceil_pd(V)  _mm256_round_pd((V), _MM_FROUND_CEIL)
 #define _mm256_floor_pd(V) _mm256_round_pd((V), _MM_FROUND_FLOOR)
@@ -262,60 +258,79 @@
 						  (__v8si)c);
 }
=20
-static __inline __m128d __attribute__((__always_inline__, __nodebug__))
-_mm_permute_pd(__m128d a, const int c)
-{
-  return (__m128d)__builtin_ia32_vpermilpd((__v2df)a, c);
-}
+#define _mm_permute_pd(A, C) __extension__ ({ \
+  __m128d __A =3D (A); \
+  (__m128d)__builtin_shufflevector((__v2df)__A, (__v2df) _mm_setzero_pd(),=
 \
+                                   (C) & 0x1, ((C) & 0x2) >> 1); })
=20
-static __inline __m256d __attribute__((__always_inline__, __nodebug__))
-_mm256_permute_pd(__m256d a, const int c)
-{
-  return (__m256d)__builtin_ia32_vpermilpd256((__v4df)a, c);
-}
+#define _mm256_permute_pd(A, C) __extension__ ({ \
+  __m256d __A =3D (A); \
+  (__m256d)__builtin_shufflevector((__v4df)__A, (__v4df) _mm256_setzero_pd=
(), \
+                                   (C) & 0x1, ((C) & 0x2) >> 1, \
+                                   2 + (((C) & 0x4) >> 2), \
+                                   2 + (((C) & 0x8) >> 3)); })
=20
-static __inline __m128 __attribute__((__always_inline__, __nodebug__))
-_mm_permute_ps(__m128 a, const int c)
-{
-  return (__m128)__builtin_ia32_vpermilps((__v4sf)a, c);
-}
+#define _mm_permute_ps(A, C) __extension__ ({ \
+  __m128 __A =3D (A); \
+  (__m128)__builtin_shufflevector((__v4sf)__A, (__v4sf) _mm_setzero_ps(), \
+                                   (C) & 0x3, ((C) & 0xc) >> 2, \
+                                   ((C) & 0x30) >> 4, ((C) & 0xc0) >> 6); =
})
=20
-static __inline __m256 __attribute__((__always_inline__, __nodebug__))
-_mm256_permute_ps(__m256 a, const int c)
-{
-  return (__m256)__builtin_ia32_vpermilps256((__v8sf)a, c);
-}
+#define _mm256_permute_ps(A, C) __extension__ ({ \
+  __m256 __A =3D (A); \
+  (__m256)__builtin_shufflevector((__v8sf)__A, (__v8sf) _mm256_setzero_ps(=
), \
+                                  (C) & 0x3, ((C) & 0xc) >> 2, \
+                                  ((C) & 0x30) >> 4, ((C) & 0xc0) >> 6, \
+                                  4 + (((C) & 0x03) >> 0), \
+                                  4 + (((C) & 0x0c) >> 2), \
+                                  4 + (((C) & 0x30) >> 4), \
+                                  4 + (((C) & 0xc0) >> 6)); })
=20
-static __inline __m256d __attribute__((__always_inline__, __nodebug__))
-_mm256_permute2f128_pd(__m256d a, __m256d b, const int c)
-{
-  return (__m256d)__builtin_ia32_vperm2f128_pd256((__v4df)a, (__v4df)b, c);
-}
+#define _mm256_permute2f128_pd(V1, V2, M) __extension__ ({ \
+  __m256d __V1 =3D (V1); \
+  __m256d __V2 =3D (V2); \
+  (__m256d)__builtin_shufflevector((__v4df)__V1, (__v4df)__V2, \
+                                   ((M) & 0x3) * 2, \
+                                   ((M) & 0x3) * 2 + 1, \
+                                   (((M) & 0x30) >> 4) * 2, \
+                                   (((M) & 0x30) >> 4) * 2 + 1); })
=20
-static __inline __m256 __attribute__((__always_inline__, __nodebug__))
-_mm256_permute2f128_ps(__m256 a, __m256 b, const int c)
-{
-  return (__m256)__builtin_ia32_vperm2f128_ps256((__v8sf)a, (__v8sf)b, c);
-}
+#define _mm256_permute2f128_ps(V1, V2, M) __extension__ ({ \
+  __m256 __V1 =3D (V1); \
+  __m256 __V2 =3D (V2); \
+  (__m256)__builtin_shufflevector((__v8sf)__V1, (__v8sf)__V2, \
+                                  ((M) & 0x3) * 4, \
+                                  ((M) & 0x3) * 4 + 1, \
+                                  ((M) & 0x3) * 4 + 2, \
+                                  ((M) & 0x3) * 4 + 3, \
+                                  (((M) & 0x30) >> 4) * 4, \
+                                  (((M) & 0x30) >> 4) * 4 + 1, \
+                                  (((M) & 0x30) >> 4) * 4 + 2, \
+                                  (((M) & 0x30) >> 4) * 4 + 3); })
=20
-static __inline __m256i __attribute__((__always_inline__, __nodebug__))
-_mm256_permute2f128_si256(__m256i a, __m256i b, const int c)
-{
-  return (__m256i)__builtin_ia32_vperm2f128_si256((__v8si)a, (__v8si)b, c);
-}
+#define _mm256_permute2f128_si256(V1, V2, M) __extension__ ({ \
+  __m256i __V1 =3D (V1); \
+  __m256i __V2 =3D (V2); \
+  (__m256i)__builtin_shufflevector((__v8si)__V1, (__v8si)__V2, \
+                                   ((M) & 0x3) * 4, \
+                                   ((M) & 0x3) * 4 + 1, \
+                                   ((M) & 0x3) * 4 + 2, \
+                                   ((M) & 0x3) * 4 + 3, \
+                                   (((M) & 0x30) >> 4) * 4, \
+                                   (((M) & 0x30) >> 4) * 4 + 1, \
+                                   (((M) & 0x30) >> 4) * 4 + 2, \
+                                   (((M) & 0x30) >> 4) * 4 + 3); })
=20
 /* Vector Blend */
-static __inline __m256d __attribute__((__always_inline__, __nodebug__))
-_mm256_blend_pd(__m256d a, __m256d b, const int c)
-{
-  return (__m256d)__builtin_ia32_blendpd256((__v4df)a, (__v4df)b, c);
-}
+#define _mm256_blend_pd(V1, V2, M) __extension__ ({ \
+  __m256d __V1 =3D (V1); \
+  __m256d __V2 =3D (V2); \
+  (__m256d)__builtin_ia32_blendpd256((__v4df)__V1, (__v4df)__V2, (M)); })
=20
-static __inline __m256 __attribute__((__always_inline__, __nodebug__))
-_mm256_blend_ps(__m256 a, __m256 b, const int c)
-{
-  return (__m256)__builtin_ia32_blendps256((__v8sf)a, (__v8sf)b, c);
-}
+#define _mm256_blend_ps(V1, V2, M) __extension__ ({ \
+  __m256 __V1 =3D (V1); \
+  __m256 __V2 =3D (V2); \
+  (__m256)__builtin_ia32_blendps256((__v8sf)__V1, (__v8sf)__V2, (M)); })
=20
 static __inline __m256d __attribute__((__always_inline__, __nodebug__))
 _mm256_blendv_pd(__m256d a, __m256d b, __m256d c)
@@ -330,26 +345,29 @@
 }
=20
 /* Vector Dot Product */
-static __inline __m256 __attribute__((__always_inline__, __nodebug__))
-_mm256_dp_ps(__m256 a, __m256 b, const int c)
-{
-  return (__m256)__builtin_ia32_dpps256((__v8sf)a, (__v8sf)b, c);
-}
+#define _mm256_dp_ps(V1, V2, M) __extension__ ({ \
+  __m256 __V1 =3D (V1); \
+  __m256 __V2 =3D (V2); \
+  (__m256)__builtin_ia32_dpps256((__v8sf)__V1, (__v8sf)__V2, (M)); })
=20
 /* Vector shuffle */
-#define _mm256_shuffle_ps(a, b, mask) \
-        (__builtin_shufflevector((__v8sf)(a), (__v8sf)(b), \
+#define _mm256_shuffle_ps(a, b, mask) __extension__ ({ \
+        __m256 __a =3D (a); \
+        __m256 __b =3D (b); \
+        (__m256)__builtin_shufflevector((__v8sf)__a, (__v8sf)__b, \
         (mask) & 0x3,                ((mask) & 0xc) >> 2, \
         (((mask) & 0x30) >> 4) + 8,  (((mask) & 0xc0) >> 6) + 8, \
         ((mask) & 0x3) + 4,          (((mask) & 0xc) >> 2) + 4, \
-        (((mask) & 0x30) >> 4) + 12, (((mask) & 0xc0) >> 6) + 12))
+        (((mask) & 0x30) >> 4) + 12, (((mask) & 0xc0) >> 6) + 12); })
=20
-#define _mm256_shuffle_pd(a, b, mask) \
-        (__builtin_shufflevector((__v4df)(a), (__v4df)(b), \
+#define _mm256_shuffle_pd(a, b, mask) __extension__ ({ \
+        __m256d __a =3D (a); \
+        __m256d __b =3D (b); \
+        (__m256d)__builtin_shufflevector((__v4df)__a, (__v4df)__b, \
         (mask) & 0x1, \
         (((mask) & 0x2) >> 1) + 4, \
         (((mask) & 0x4) >> 2) + 2, \
-        (((mask) & 0x8) >> 3) + 6))
+        (((mask) & 0x8) >> 3) + 6); })
=20
 /* Compare */
 #define _CMP_EQ_OQ    0x00 /* Equal (ordered, non-signaling)  */
@@ -385,42 +403,48 @@
 #define _CMP_GT_OQ    0x1e /* Greater-than (ordered, non-signaling)  */
 #define _CMP_TRUE_US  0x1f /* True (unordered, signaling)  */
=20
-#define _mm_cmp_pd(a, b, c) \
-  (__m128d)__builtin_ia32_cmppd((__v2df)(a), (__v2df)(b), (c))
+#define _mm_cmp_pd(a, b, c) __extension__ ({ \
+  __m128d __a =3D (a); \
+  __m128d __b =3D (b); \
+  (__m128d)__builtin_ia32_cmppd((__v2df)__a, (__v2df)__b, (c)); })
=20
-#define _mm_cmp_ps(a, b, c) \
-  (__m128)__builtin_ia32_cmpps((__v4sf)(a), (__v4sf)(b), (c))
+#define _mm_cmp_ps(a, b, c) __extension__ ({ \
+  __m128 __a =3D (a); \
+  __m128 __b =3D (b); \
+  (__m128)__builtin_ia32_cmpps((__v4sf)__a, (__v4sf)__b, (c)); })
=20
-#define _mm256_cmp_pd(a, b, c) \
-  (__m256d)__builtin_ia32_cmppd256((__v4df)(a), (__v4df)(b), (c))
+#define _mm256_cmp_pd(a, b, c) __extension__ ({ \
+  __m256d __a =3D (a); \
+  __m256d __b =3D (b); \
+  (__m256d)__builtin_ia32_cmppd256((__v4df)__a, (__v4df)__b, (c)); })
=20
-#define _mm256_cmp_ps(a, b, c) \
-  (__m256)__builtin_ia32_cmpps256((__v8sf)(a), (__v8sf)(b), (c))
+#define _mm256_cmp_ps(a, b, c) __extension__ ({ \
+  __m256 __a =3D (a); \
+  __m256 __b =3D (b); \
+  (__m256)__builtin_ia32_cmpps256((__v8sf)__a, (__v8sf)__b, (c)); })
=20
-#define _mm_cmp_sd(a, b, c) \
-  (__m128d)__builtin_ia32_cmpsd((__v2df)(a), (__v2df)(b), (c))
+#define _mm_cmp_sd(a, b, c) __extension__ ({ \
+  __m128d __a =3D (a); \
+  __m128d __b =3D (b); \
+  (__m128d)__builtin_ia32_cmpsd((__v2df)__a, (__v2df)__b, (c)); })
=20
-#define _mm_cmp_ss(a, b, c) \
-  (__m128)__builtin_ia32_cmpss((__v4sf)(a), (__v4sf)(b), (c))
+#define _mm_cmp_ss(a, b, c) __extension__ ({ \
+  __m128 __a =3D (a); \
+  __m128 __b =3D (b); \
+  (__m128)__builtin_ia32_cmpss((__v4sf)__a, (__v4sf)__b, (c)); })
=20
 /* Vector extract */
-static __inline __m128d __attribute__((__always_inline__, __nodebug__))
-_mm256_extractf128_pd(__m256d a, const int o)
-{
-  return (__m128d)__builtin_ia32_vextractf128_pd256((__v4df)a, o);
-}
+#define _mm256_extractf128_pd(A, O) __extension__ ({ \
+  __m256d __A =3D (A); \
+  (__m128d)__builtin_ia32_vextractf128_pd256((__v4df)__A, (O)); })
=20
-static __inline __m128 __attribute__((__always_inline__, __nodebug__))
-_mm256_extractf128_ps(__m256 a, const int o)
-{
-  return (__m128)__builtin_ia32_vextractf128_ps256((__v8sf)a, o);
-}
+#define _mm256_extractf128_ps(A, O) __extension__ ({ \
+  __m256 __A =3D (A); \
+  (__m128)__builtin_ia32_vextractf128_ps256((__v8sf)__A, (O)); })
=20
-static __inline __m128i __attribute__((__always_inline__, __nodebug__))
-_mm256_extractf128_si256(__m256i a, const int o)
-{
-  return (__m128i)__builtin_ia32_vextractf128_si256((__v8si)a, o);
-}
+#define _mm256_extractf128_si256(A, O) __extension__ ({ \
+  __m256i __A =3D (A); \
+  (__m128i)__builtin_ia32_vextractf128_si256((__v8si)__A, (O)); })
=20
 static __inline int __attribute__((__always_inline__, __nodebug__))
 _mm256_extract_epi32(__m256i a, int const imm)
@@ -453,23 +477,20 @@
 #endif
=20
 /* Vector insert */
-static __inline __m256d __attribute__((__always_inline__, __nodebug__))
-_mm256_insertf128_pd(__m256d a, __m128d b, const int o)
-{
-  return (__m256d)__builtin_ia32_vinsertf128_pd256((__v4df)a, (__v2df)b, o=
);
-}
+#define _mm256_insertf128_pd(V1, V2, O) __extension__ ({ \
+  __m256d __V1 =3D (V1); \
+  __m128d __V2 =3D (V2); \
+  (__m256d)__builtin_ia32_vinsertf128_pd256((__v4df)__V1, (__v2df)__V2, (O=
)); })
=20
-static __inline __m256 __attribute__((__always_inline__, __nodebug__))
-_mm256_insertf128_ps(__m256 a, __m128 b, const int o)
-{
-  return (__m256)__builtin_ia32_vinsertf128_ps256((__v8sf)a, (__v4sf)b, o);
-}
+#define _mm256_insertf128_ps(V1, V2, O) __extension__ ({ \
+  __m256 __V1 =3D (V1); \
+  __m128 __V2 =3D (V2); \
+  (__m256)__builtin_ia32_vinsertf128_ps256((__v8sf)__V1, (__v4sf)__V2, (O)=
); })
=20
-static __inline __m256i __attribute__((__always_inline__, __nodebug__))
-_mm256_insertf128_si256(__m256i a, __m128i b, const int o)
-{
-  return (__m256i)__builtin_ia32_vinsertf128_si256((__v8si)a, (__v4si)b, o=
);
-}
+#define _mm256_insertf128_si256(V1, V2, O) __extension__ ({ \
+  __m256i __V1 =3D (V1); \
+  __m128i __V2 =3D (V2); \
+  (__m256i)__builtin_ia32_vinsertf128_si256((__v8si)__V1, (__v4si)__V2, (O=
)); })
=20
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_insert_epi32(__m256i a, int b, int const imm)
@@ -762,13 +783,19 @@
 static __inline __m256d __attribute__((__always_inline__, __nodebug__))
 _mm256_loadu_pd(double const *p)
 {
-  return (__m256d)__builtin_ia32_loadupd256(p);
+  struct __loadu_pd {
+    __m256d v;
+  } __attribute__((packed, may_alias));
+  return ((struct __loadu_pd*)p)->v;
 }
=20
 static __inline __m256 __attribute__((__always_inline__, __nodebug__))
 _mm256_loadu_ps(float const *p)
 {
-  return (__m256)__builtin_ia32_loadups256(p);
+  struct __loadu_ps {
+    __m256 v;
+  } __attribute__((packed, may_alias));
+  return ((struct __loadu_ps*)p)->v;
 }
=20
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
@@ -780,7 +807,10 @@
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
 _mm256_loadu_si256(__m256i const *p)
 {
-  return (__m256i)__builtin_ia32_loaddqu256((char const *)p);
+  struct __loadu_si256 {
+    __m256i v;
+  } __attribute__((packed, may_alias));
+  return ((struct __loadu_si256*)p)->v;
 }
=20
 static __inline __m256i __attribute__((__always_inline__, __nodebug__))
@@ -1136,3 +1166,70 @@
   __m128i zero =3D _mm_setzero_si128();
   return __builtin_shufflevector(in, zero, 0, 1, 2, 2);
 }
+
+/* SIMD load ops (unaligned) */
+static __inline __m256 __attribute__((__always_inline__, __nodebug__))
+_mm256_loadu2_m128(float const *addr_hi, float const *addr_lo)
+{
+  struct __loadu_ps {
+    __m128 v;
+  } __attribute__((__packed__, __may_alias__));
+
+  __m256 v256 =3D _mm256_castps128_ps256(((struct __loadu_ps*)addr_lo)->v);
+  return _mm256_insertf128_ps(v256, ((struct __loadu_ps*)addr_hi)->v, 1);
+}
+
+static __inline __m256d __attribute__((__always_inline__, __nodebug__))
+_mm256_loadu2_m128d(double const *addr_hi, double const *addr_lo)
+{
+  struct __loadu_pd {
+    __m128d v;
+  } __attribute__((__packed__, __may_alias__));
+ =20
+  __m256d v256 =3D _mm256_castpd128_pd256(((struct __loadu_pd*)addr_lo)->v=
);
+  return _mm256_insertf128_pd(v256, ((struct __loadu_pd*)addr_hi)->v, 1);
+}
+
+static __inline __m256i __attribute__((__always_inline__, __nodebug__))
+_mm256_loadu2_m128i(__m128i const *addr_hi, __m128i const *addr_lo)
+{
+  struct __loadu_si128 {
+    __m128i v;
+  } __attribute__((packed, may_alias));
+  __m256i v256 =3D _mm256_castsi128_si256(((struct __loadu_si128*)addr_lo)=
->v);
+  return _mm256_insertf128_si256(v256, ((struct __loadu_si128*)addr_hi)->v=
, 1);
+}
+
+/* SIMD store ops (unaligned) */
+static __inline void __attribute__((__always_inline__, __nodebug__))
+_mm256_storeu2_m128(float *addr_hi, float *addr_lo, __m256 a)
+{
+  __m128 v128;
+
+  v128 =3D _mm256_castps256_ps128(a);
+  __builtin_ia32_storeups(addr_lo, v128);
+  v128 =3D _mm256_extractf128_ps(a, 1);
+  __builtin_ia32_storeups(addr_hi, v128);
+}
+
+static __inline void __attribute__((__always_inline__, __nodebug__))
+_mm256_storeu2_m128d(double *addr_hi, double *addr_lo, __m256d a)
+{
+  __m128d v128;
+
+  v128 =3D _mm256_castpd256_pd128(a);
+  __builtin_ia32_storeupd(addr_lo, v128);
+  v128 =3D _mm256_extractf128_pd(a, 1);
+  __builtin_ia32_storeupd(addr_hi, v128);
+}
+
+static __inline void __attribute__((__always_inline__, __nodebug__))
+_mm256_storeu2_m128i(__m128i *addr_hi, __m128i *addr_lo, __m256i a)
+{
+  __m128i v128;
+
+  v128 =3D _mm256_castsi256_si128(a);
+  __builtin_ia32_storedqu((char *)addr_lo, (__v16qi)v128);
+  v128 =3D _mm256_extractf128_si256(a, 1);
+  __builtin_ia32_storedqu((char *)addr_hi, (__v16qi)v128);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/emmintrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/emmintrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/emmintrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -821,8 +821,9 @@
   return a ^ b;
 }
=20
-#define _mm_slli_si128(VEC, IMM) \
-  ((__m128i)__builtin_ia32_pslldqi128((__m128i)(VEC), (IMM)*8))
+#define _mm_slli_si128(a, count) __extension__ ({ \
+  __m128i __a =3D (a); \
+  (__m128i)__builtin_ia32_pslldqi128(__a, (count)*8); })
=20
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_slli_epi16(__m128i a, int count)
@@ -885,8 +886,9 @@
 }
=20
=20
-#define _mm_srli_si128(VEC, IMM) \
-  ((__m128i)__builtin_ia32_psrldqi128((__m128i)(VEC), (IMM)*8))
+#define _mm_srli_si128(a, count) __extension__ ({ \
+  __m128i __a =3D (a); \
+  (__m128i)__builtin_ia32_psrldqi128(__a, (count)*8); })
=20
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_srli_epi16(__m128i a, int count)
@@ -945,7 +947,10 @@
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_cmpgt_epi8(__m128i a, __m128i b)
 {
-  return (__m128i)((__v16qi)a > (__v16qi)b);
+  /* This function always performs a signed comparison, but __v16qi is a c=
har
+     which may be signed or unsigned. */
+  typedef signed char __v16qs __attribute__((__vector_size__(16)));
+  return (__m128i)((__v16qs)a > (__v16qs)b);
 }
=20
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
@@ -1259,23 +1264,27 @@
   return __builtin_ia32_pmovmskb128((__v16qi)a);
 }
=20
-#define _mm_shuffle_epi32(a, imm) \
-  ((__m128i)__builtin_shufflevector((__v4si)(a), (__v4si) _mm_set1_epi32(0=
), \
-                                    (imm) & 0x3, ((imm) & 0xc) >> 2, \
-                                    ((imm) & 0x30) >> 4, ((imm) & 0xc0) >>=
 6))
+#define _mm_shuffle_epi32(a, imm) __extension__ ({ \
+  __m128i __a =3D (a); \
+  (__m128i)__builtin_shufflevector((__v4si)__a, (__v4si) _mm_set1_epi32(0)=
, \
+                                   (imm) & 0x3, ((imm) & 0xc) >> 2, \
+                                   ((imm) & 0x30) >> 4, ((imm) & 0xc0) >> =
6); })
=20
+#define _mm_shufflelo_epi16(a, imm) __extension__ ({ \
+  __m128i __a =3D (a); \
+  (__m128i)__builtin_shufflevector((__v8hi)__a, (__v8hi) _mm_set1_epi16(0)=
, \
+                                   (imm) & 0x3, ((imm) & 0xc) >> 2, \
+                                   ((imm) & 0x30) >> 4, ((imm) & 0xc0) >> =
6, \
+                                   4, 5, 6, 7); })
=20
-#define _mm_shufflelo_epi16(a, imm) \
-  ((__m128i)__builtin_shufflevector((__v8hi)(a), (__v8hi) _mm_set1_epi16(0=
), \
-                                    (imm) & 0x3, ((imm) & 0xc) >> 2, \
-                                    ((imm) & 0x30) >> 4, ((imm) & 0xc0) >>=
 6, \
-                                    4, 5, 6, 7))
-#define _mm_shufflehi_epi16(a, imm) \
-  ((__m128i)__builtin_shufflevector((__v8hi)(a), (__v8hi) _mm_set1_epi16(0=
), 0, 1, 2, 3, \
-                                    4 + (((imm) & 0x03) >> 0), \
-                                    4 + (((imm) & 0x0c) >> 2), \
-                                    4 + (((imm) & 0x30) >> 4), \
-                                    4 + (((imm) & 0xc0) >> 6)))
+#define _mm_shufflehi_epi16(a, imm) __extension__ ({ \
+  __m128i __a =3D (a); \
+  (__m128i)__builtin_shufflevector((__v8hi)__a, (__v8hi) _mm_set1_epi16(0)=
, \
+                                   0, 1, 2, 3, \
+                                   4 + (((imm) & 0x03) >> 0), \
+                                   4 + (((imm) & 0x0c) >> 2), \
+                                   4 + (((imm) & 0x30) >> 4), \
+                                   4 + (((imm) & 0xc0) >> 6)); })
=20
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_unpackhi_epi8(__m128i a, __m128i b)
@@ -1361,9 +1370,10 @@
   return __builtin_ia32_movmskpd(a);
 }
=20
-#define _mm_shuffle_pd(a, b, i) \
-  (__builtin_shufflevector((__m128d)(a), (__m128d)(b), (i) & 1, \
-                                                       (((i) & 2) >> 1) + =
2))
+#define _mm_shuffle_pd(a, b, i) __extension__ ({ \
+  __m128d __a =3D (a); \
+  __m128d __b =3D (b); \
+  __builtin_shufflevector(__a, __b, (i) & 1, (((i) & 2) >> 1) + 2); })
=20
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_castpd_ps(__m128d in)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/float.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/float.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/float.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -64,6 +64,11 @@
 #  undef FLT_MIN
 #  undef DBL_MIN
 #  undef LDBL_MIN
+#  if __STDC_VERSION__ >=3D 201112L || !defined(__STRICT_ANSI__)
+#    undef FLT_TRUE_MIN
+#    undef DBL_TRUE_MIN
+#    undef LDBL_TRUE_MIN
+#  endif
 #endif
=20
 /* Characteristics of floating point types, C99 5.2.4.2.2 */
@@ -110,4 +115,10 @@
 #define DBL_MIN __DBL_MIN__
 #define LDBL_MIN __LDBL_MIN__
=20
+#if __STDC_VERSION__ >=3D 201112L || !defined(__STRICT_ANSI__)
+#  define FLT_TRUE_MIN __FLT_DENORM_MIN__
+#  define DBL_TRUE_MIN __DBL_DENORM_MIN__
+#  define LDBL_TRUE_MIN __LDBL_DENORM_MIN__
+#endif
+
 #endif /* __FLOAT_H */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/immintrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/immintrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/immintrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -48,7 +48,7 @@
 #include <smmintrin.h>
 #endif
=20
-#if defined (__AES__) || defined (__PCLMUL__)
+#if defined (__AES__)
 #include <wmmintrin.h>
 #endif
=20
@@ -56,4 +56,20 @@
 #include <avxintrin.h>
 #endif
=20
+#ifdef __AVX2__
+#include <avx2intrin.h>
+#endif
+
+#ifdef __BMI__
+#include <bmiintrin.h>
+#endif
+
+#ifdef __BMI2__
+#include <bmi2intrin.h>
+#endif
+
+#ifdef __LZCNT__
+#include <lzcntintrin.h>
+#endif
+
 #endif /* __IMMINTRIN_H */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/mm3dnow.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/mm3dnow.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/mm3dnow.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -105,7 +105,7 @@
=20
 static __inline__ __m64 __attribute__((__always_inline__, __nodebug__))
 _m_pfrsqrtit1(__m64 __m1, __m64 __m2) {
-  return (__m64)__builtin_ia32_pfrsqrtit1((__v2sf)__m1, (__v2sf)__m2);
+  return (__m64)__builtin_ia32_pfrsqit1((__v2sf)__m1, (__v2sf)__m2);
 }
=20
 static __inline__ __m64 __attribute__((__always_inline__, __nodebug__))
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/smmintrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/smmintrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/smmintrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -57,23 +57,34 @@
 #define _mm_floor_ss(X, Y)   _mm_round_ss((X), (Y), _MM_FROUND_FLOOR)
 #define _mm_floor_sd(X, Y)   _mm_round_sd((X), (Y), _MM_FROUND_FLOOR)
=20
-#define _mm_round_ps(X, Y)      __builtin_ia32_roundps((X), (Y))
-#define _mm_round_ss(X, Y, M)   __builtin_ia32_roundss((X), (Y), (M))
-#define _mm_round_pd(X, M)      __builtin_ia32_roundpd((X), (M))
-#define _mm_round_sd(X, Y, M)   __builtin_ia32_roundsd((X), (Y), (M))
+#define _mm_round_ps(X, M) __extension__ ({ \
+  __m128 __X =3D (X); \
+  (__m128) __builtin_ia32_roundps((__v4sf)__X, (M)); })
+
+#define _mm_round_ss(X, Y, M) __extension__ ({ \
+  __m128 __X =3D (X); \
+  __m128 __Y =3D (Y); \
+  (__m128) __builtin_ia32_roundss((__v4sf)__X, (__v4sf)__Y, (M)); })
+
+#define _mm_round_pd(X, M) __extension__ ({ \
+  __m128d __X =3D (X); \
+  (__m128d) __builtin_ia32_roundpd((__v2df)__X, (M)); })
+
+#define _mm_round_sd(X, Y, M) __extension__ ({ \
+  __m128d __X =3D (X); \
+  __m128d __Y =3D (Y); \
+  (__m128d) __builtin_ia32_roundsd((__v2df)__X, (__v2df)__Y, (M)); })
=20
 /* SSE4 Packed Blending Intrinsics.  */
-static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
-_mm_blend_pd (__m128d __V1, __m128d __V2, const int __M)
-{
-  return (__m128d) __builtin_ia32_blendpd ((__v2df)__V1, (__v2df)__V2, __M=
);
-}
+#define _mm_blend_pd(V1, V2, M) __extension__ ({ \
+  __m128d __V1 =3D (V1); \
+  __m128d __V2 =3D (V2); \
+  (__m128d) __builtin_ia32_blendpd ((__v2df)__V1, (__v2df)__V2, (M)); })
=20
-static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
-_mm_blend_ps (__m128 __V1, __m128 __V2, const int __M)
-{
-  return (__m128) __builtin_ia32_blendps ((__v4sf)__V1, (__v4sf)__V2, __M);
-}
+#define _mm_blend_ps(V1, V2, M) __extension__ ({ \
+  __m128 __V1 =3D (V1); \
+  __m128 __V2 =3D (V2); \
+  (__m128) __builtin_ia32_blendps ((__v4sf)__V1, (__v4sf)__V2, (M)); })
=20
 static __inline__ __m128d __attribute__((__always_inline__, __nodebug__))
 _mm_blendv_pd (__m128d __V1, __m128d __V2, __m128d __M)
@@ -96,11 +107,10 @@
                                                (__v16qi)__M);
 }
=20
-static __inline__  __m128i __attribute__((__always_inline__, __nodebug__))
-_mm_blend_epi16 (__m128i __V1, __m128i __V2, const int __M)
-{
-  return (__m128i) __builtin_ia32_pblendw128 ((__v8hi)__V1, (__v8hi)__V2, =
__M);
-}
+#define _mm_blend_epi16(V1, V2, M) __extension__ ({ \
+  __m128i __V1 =3D (V1); \
+  __m128i __V2 =3D (V2); \
+  (__m128i) __builtin_ia32_pblendw128 ((__v8hi)__V1, (__v8hi)__V2, (M)); })
=20
 /* SSE4 Dword Multiply Instructions.  */
 static __inline__  __m128i __attribute__((__always_inline__, __nodebug__))
@@ -116,8 +126,15 @@
 }
=20
 /* SSE4 Floating Point Dot Product Instructions.  */
-#define _mm_dp_ps(X, Y, M) __builtin_ia32_dpps ((X), (Y), (M))
-#define _mm_dp_pd(X, Y, M) __builtin_ia32_dppd ((X), (Y), (M))
+#define _mm_dp_ps(X, Y, M) __extension__ ({ \
+  __m128 __X =3D (X); \
+  __m128 __Y =3D (Y); \
+  (__m128) __builtin_ia32_dpps((__v4sf)__X, (__v4sf)__Y, (M)); })
+
+#define _mm_dp_pd(X, Y, M) __extension__ ({\
+  __m128d __X =3D (X); \
+  __m128d __Y =3D (Y); \
+  (__m128d) __builtin_ia32_dppd((__v2df)__X, (__v2df)__Y, (M)); })
=20
 /* SSE4 Streaming Load Hint Instruction.  */
 static __inline__  __m128i __attribute__((__always_inline__, __nodebug__))
@@ -198,14 +215,14 @@
                                             =20
 /* Insert int into packed integer array at index.  */
 #define _mm_insert_epi8(X, I, N) (__extension__ ({ __v16qi __a =3D (__v16q=
i)(X); \
-                                                   __a[N] =3D I;          =
     \
+                                                   __a[(N)] =3D (I);      =
       \
                                                    __a;}))
 #define _mm_insert_epi32(X, I, N) (__extension__ ({ __v4si __a =3D (__v4si=
)(X); \
-                                                    __a[N] =3D I;         =
    \
+                                                    __a[(N)] =3D (I);     =
      \
                                                     __a;}))
 #ifdef __x86_64__
 #define _mm_insert_epi64(X, I, N) (__extension__ ({ __v2di __a =3D (__v2di=
)(X); \
-                                                    __a[N] =3D I;         =
    \
+                                                    __a[(N)] =3D (I);     =
      \
                                                     __a;}))
 #endif /* __x86_64__ */
=20
@@ -213,12 +230,12 @@
  * as a zero extended value, so it is unsigned.
  */
 #define _mm_extract_epi8(X, N) (__extension__ ({ __v16qi __a =3D (__v16qi)=
(X); \
-                                                 (unsigned char)__a[N];}))
+                                                 (unsigned char)__a[(N)];}=
))
 #define _mm_extract_epi32(X, N) (__extension__ ({ __v4si __a =3D (__v4si)(=
X); \
-                                                  (unsigned)__a[N];}))
+                                                  (unsigned)__a[(N)];}))
 #ifdef __x86_64__
 #define _mm_extract_epi64(X, N) (__extension__ ({ __v2di __a =3D (__v2di)(=
X); \
-                                                  __a[N];}))
+                                                  __a[(N)];}))
 #endif /* __x86_64 */
=20
 /* SSE4 128-bit Packed Integer Comparisons.  */
@@ -242,13 +259,13 @@
=20
 #define _mm_test_all_ones(V) _mm_testc_si128((V), _mm_cmpeq_epi32((V), (V)=
))
 #define _mm_test_mix_ones_zeros(M, V) _mm_testnzc_si128((M), (V))
-#define _mm_test_all_zeros(M, V) _mm_testz_si128 ((V), (V))
+#define _mm_test_all_zeros(M, V) _mm_testz_si128 ((M), (V))
=20
 /* SSE4 64-bit Packed Integer Comparisons.  */
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_cmpeq_epi64(__m128i __V1, __m128i __V2)
 {
-  return (__m128i) __builtin_ia32_pcmpeqq((__v2di)__V1, (__v2di)__V2);
+  return (__m128i)((__v2di)__V1 =3D=3D (__v2di)__V2);
 }
=20
 /* SSE4 Packed Integer Sign-Extension.  */
@@ -333,7 +350,16 @@
 }
=20
 /* SSE4 Multiple Packed Sums of Absolute Difference.  */
-#define _mm_mpsadbw_epu8(X, Y, M) __builtin_ia32_mpsadbw128((X), (Y), (M))
+#define _mm_mpsadbw_epu8(X, Y, M) __extension__ ({ \
+  __m128i __X =3D (X); \
+  __m128i __Y =3D (Y); \
+  (__m128i) __builtin_ia32_mpsadbw128((__v16qi)__X, (__v16qi)__Y, (M)); })
+
+static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
+_mm_minpos_epu16(__m128i __V)
+{
+  return (__m128i) __builtin_ia32_phminposuw128((__v8hi)__V);
+}
=20
 /* These definitions are normally in nmmintrin.h, but gcc puts them in here
    so we'll do the same.  */
@@ -371,20 +397,20 @@
=20
 #define _mm_cmpestrm(A, LA, B, LB, M) \
      __builtin_ia32_pcmpestrm128((A), (LA), (B), (LB), (M))
-#define _mm_cmpestri(X, LX, Y, LY, M) \
+#define _mm_cmpestri(A, LA, B, LB, M) \
      __builtin_ia32_pcmpestri128((A), (LA), (B), (LB), (M))
     =20
 /* SSE4.2 Packed Comparison Intrinsics and EFlag Reading.  */
-#define _mm_cmpistra(A, LA, B, LB, M) \
-     __builtin_ia32_pcmpistria128((A), (LA), (B), (LB), (M))
-#define _mm_cmpistrc(A, LA, B, LB, M) \
-     __builtin_ia32_pcmpistric128((A), (LA), (B), (LB), (M))
-#define _mm_cmpistro(A, LA, B, LB, M) \
-     __builtin_ia32_pcmpistrio128((A), (LA), (B), (LB), (M))
-#define _mm_cmpistrs(A, LA, B, LB, M) \
-     __builtin_ia32_pcmpistris128((A), (LA), (B), (LB), (M))
-#define _mm_cmpistrz(A, LA, B, LB, M) \
-     __builtin_ia32_pcmpistriz128((A), (LA), (B), (LB), (M))
+#define _mm_cmpistra(A, B, M) \
+     __builtin_ia32_pcmpistria128((A), (B), (M))
+#define _mm_cmpistrc(A, B, M) \
+     __builtin_ia32_pcmpistric128((A), (B), (M))
+#define _mm_cmpistro(A, B, M) \
+     __builtin_ia32_pcmpistrio128((A), (B), (M))
+#define _mm_cmpistrs(A, B, M) \
+     __builtin_ia32_pcmpistris128((A), (B), (M))
+#define _mm_cmpistrz(A, B, M) \
+     __builtin_ia32_pcmpistriz128((A), (B), (M))
=20
 #define _mm_cmpestra(A, LA, B, LB, M) \
      __builtin_ia32_pcmpestria128((A), (LA), (B), (LB), (M))
@@ -401,7 +427,7 @@
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_cmpgt_epi64(__m128i __V1, __m128i __V2)
 {
-  return __builtin_ia32_pcmpgtq((__v2di)__V1, (__v2di)__V2);
+  return (__m128i)((__v2di)__V1 > (__v2di)__V2);
 }
=20
 /* SSE4.2 Accumulate CRC32.  */
@@ -431,20 +457,9 @@
 }
 #endif /* __x86_64__ */
=20
-/* SSE4.2 Population Count.  */
-static __inline__ int __attribute__((__always_inline__, __nodebug__))
-_mm_popcnt_u32(unsigned int __A)
-{
-  return __builtin_popcount(__A);
-}
-
-#ifdef __x86_64__
-static __inline__ long long __attribute__((__always_inline__, __nodebug__))
-_mm_popcnt_u64(unsigned long long __A)
-{
-  return __builtin_popcountll(__A);
-}
-#endif /* __x86_64__ */
+#ifdef __POPCNT__
+#include <popcntintrin.h>
+#endif
=20
 #endif /* __SSE4_2__ */
 #endif /* __SSE4_1__ */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/tgmath.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/tgmath.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/tgmath.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -540,15 +540,15 @@
     _TG_ATTRS
     __tg_fabs(long double __x) {return fabsl(__x);}
=20
-static float _Complex
+static float
     _TG_ATTRS
     __tg_fabs(float _Complex __x) {return cabsf(__x);}
=20
-static double _Complex
+static double
     _TG_ATTRS
     __tg_fabs(double _Complex __x) {return cabs(__x);}
=20
-static long double _Complex
+static long double
     _TG_ATTRS
     __tg_fabs(long double _Complex __x) {return cabsl(__x);}
=20
@@ -976,6 +976,23 @@
 #undef log2
 #define log2(__x) __tg_log2(__tg_promote1((__x))(__x))
=20
+// logb
+
+static float
+    _TG_ATTRS
+    __tg_logb(float __x) {return logbf(__x);}
+
+static double
+    _TG_ATTRS
+    __tg_logb(double __x) {return logb(__x);}
+
+static long double
+    _TG_ATTRS
+    __tg_logb(long double __x) {return logbl(__x);}
+
+#undef logb
+#define logb(__x) __tg_logb(__tg_promote1((__x))(__x))
+
 // lrint
=20
 static long
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/tmmintrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/tmmintrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/tmmintrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -66,8 +66,15 @@
     return (__m128i)__builtin_ia32_pabsd128((__v4si)a);
 }
=20
-#define _mm_alignr_epi8(a, b, n) (__builtin_ia32_palignr128((a), (b), (n)))
-#define _mm_alignr_pi8(a, b, n) (__builtin_ia32_palignr((a), (b), (n)))
+#define _mm_alignr_epi8(a, b, n) __extension__ ({ \
+  __m128i __a =3D (a); \
+  __m128i __b =3D (b); \
+  (__m128i)__builtin_ia32_palignr128((__v16qi)__a, (__v16qi)__b, (n)); })
+
+#define _mm_alignr_pi8(a, b, n) __extension__ ({ \
+  __m64 __a =3D (a); \
+  __m64 __b =3D (b); \
+  (__m64)__builtin_ia32_palignr((__v8qi)__a, (__v8qi)__b, (n)); })
=20
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_hadd_epi16(__m128i a, __m128i b)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/wmmintrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/wmmintrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/wmmintrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -28,7 +28,7 @@
 # error "AES instructions not enabled"
 #else
=20
-#include <smmintrin.h>
+#include <xmmintrin.h>
=20
 static __inline__ __m128i __attribute__((__always_inline__, __nodebug__))
 _mm_aesenc_si128(__m128i __V, __m128i __R)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/x86intrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/x86intrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/x86intrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -26,6 +26,30 @@
=20
 #include <immintrin.h>
=20
-// FIXME: SSE4A, 3dNOW, FMA4, XOP, LWP, ABM, POPCNT
+#ifdef __3dNOW__
+#include <mm3dnow.h>
+#endif
+
+#ifdef __BMI__
+#include <bmiintrin.h>
+#endif
+
+#ifdef __BMI2__
+#include <bmi2intrin.h>
+#endif
+
+#ifdef __LZCNT__
+#include <lzcntintrin.h>
+#endif
+
+#ifdef __POPCNT__
+#include <popcntintrin.h>
+#endif
+
+#ifdef __FMA4__
+#include <fma4intrin.h>
+#endif
+
+// FIXME: SSE4A, XOP, LWP, ABM
=20
 #endif /* __X86INTRIN_H */
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Head=
ers/xmmintrin.h
--- a/head/contrib/llvm/tools/clang/lib/Headers/xmmintrin.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Headers/xmmintrin.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -664,7 +664,7 @@
 /* FIXME: We have to #define this because "sel" must be a constant integer=
, and
    Sema doesn't do any form of constant propagation yet. */
=20
-#define _mm_prefetch(a, sel) (__builtin_prefetch((void *)(a), 0, sel))
+#define _mm_prefetch(a, sel) (__builtin_prefetch((void *)(a), 0, (sel)))
=20
 static __inline__ void __attribute__((__always_inline__, __nodebug__))
 _mm_stream_pi(__m64 *p, __m64 a)
@@ -735,8 +735,9 @@
   return (__m64)__builtin_ia32_pmulhuw((__v4hi)a, (__v4hi)b); =20
 }
=20
-#define _mm_shuffle_pi16(a, n) \
-  ((__m64)__builtin_ia32_pshufw(a, n))
+#define _mm_shuffle_pi16(a, n) __extension__ ({ \
+  __m64 __a =3D (a); \
+  (__m64)__builtin_ia32_pshufw((__v4hi)__a, (n)); })
=20
 static __inline__ void __attribute__((__always_inline__, __nodebug__))
 _mm_maskmove_si64(__m64 d, __m64 n, char *p)
@@ -774,11 +775,13 @@
   __builtin_ia32_ldmxcsr(i);
 }
=20
-#define _mm_shuffle_ps(a, b, mask) \
-        (__builtin_shufflevector((__v4sf)(a), (__v4sf)(b),                \
-                                 (mask) & 0x3, ((mask) & 0xc) >> 2, \
-                                 (((mask) & 0x30) >> 4) + 4, \
-                                 (((mask) & 0xc0) >> 6) + 4))
+#define _mm_shuffle_ps(a, b, mask) __extension__ ({ \
+  __m128 __a =3D (a); \
+  __m128 __b =3D (b); \
+  (__m128)__builtin_shufflevector((__v4sf)__a, (__v4sf)__b, \
+                                  (mask) & 0x3, ((mask) & 0xc) >> 2, \
+                                  (((mask) & 0x30) >> 4) + 4, \
+                                  (((mask) & 0xc0) >> 6) + 4); })
=20
 static __inline__ __m128 __attribute__((__always_inline__, __nodebug__))
 _mm_unpackhi_ps(__m128 a, __m128 b)
@@ -935,7 +938,7 @@
=20
 #define _MM_FLUSH_ZERO_MASK   (0x8000)
 #define _MM_FLUSH_ZERO_ON     (0x8000)
-#define _MM_FLUSH_ZERO_OFF    (0x8000)
+#define _MM_FLUSH_ZERO_OFF    (0x0000)
=20
 #define _MM_GET_EXCEPTION_MASK() (_mm_getcsr() & _MM_MASK_MASK)
 #define _MM_GET_EXCEPTION_STATE() (_mm_getcsr() & _MM_EXCEPT_MASK)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Inde=
x/ASTLocation.cpp
--- a/head/contrib/llvm/tools/clang/lib/Index/ASTLocation.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Index/ASTLocation.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -41,7 +41,6 @@
     return 0;
=20
   switch (getKind()) {
-  default: llvm_unreachable("Invalid Kind");
   case N_Type:
     return 0;
   case N_Decl:
@@ -51,8 +50,8 @@
   case N_Stmt:
     return getDeclFromExpr(Stm);
   }
- =20
-  return 0;
+
+  llvm_unreachable("Invalid ASTLocation Kind!");
 }
=20
 SourceRange ASTLocation::getSourceRange() const {
@@ -60,7 +59,6 @@
     return SourceRange();
=20
   switch (getKind()) {
-  default: llvm_unreachable("Invalid Kind");
   case N_Decl:
     return D->getSourceRange();
   case N_Stmt:
@@ -70,8 +68,8 @@
   case N_Type:
     return AsTypeLoc().getLocalSourceRange();
   }
- =20
-  return SourceRange();
+
+  llvm_unreachable("Invalid ASTLocation Kind!");
 }
=20
 void ASTLocation::print(raw_ostream &OS) const {
@@ -91,7 +89,7 @@
=20
   case N_Stmt:
     OS << "[Stmt: " << AsStmt()->getStmtClassName() << " ";
-    AsStmt()->printPretty(OS, Ctx, 0, PrintingPolicy(Ctx.getLangOptions())=
);
+    AsStmt()->printPretty(OS, Ctx, 0, PrintingPolicy(Ctx.getLangOpts()));
     break;
    =20
   case N_NamedRef:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Inde=
x/Analyzer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Index/Analyzer.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Index/Analyzer.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -205,7 +205,7 @@
     assert(MsgD);
=20
     // Same interface ? We have a winner!
-    if (MsgD =3D=3D IFace)
+    if (declaresSameEntity(MsgD, IFace))
       return true;
=20
     // If the message interface is a superclass of the original interface,
@@ -220,7 +220,7 @@
     if (IFace) {
       Selector Sel =3D Msg->getSelector();
       for (ObjCInterfaceDecl *Cls =3D MsgD; Cls; Cls =3D Cls->getSuperClas=
s()) {
-        if (Cls =3D=3D IFace)
+        if (declaresSameEntity(Cls, IFace))
           return true;
         if (Cls->getMethod(Sel, IsInstanceMethod))
           return false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
HeaderMap.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/HeaderMap.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/HeaderMap.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -81,7 +81,7 @@
   unsigned FileSize =3D FE->getSize();
   if (FileSize <=3D sizeof(HMapHeader)) return 0;
=20
-  llvm::OwningPtr<const llvm::MemoryBuffer> FileBuffer(FM.getBufferForFile=
(FE));
+  OwningPtr<const llvm::MemoryBuffer> FileBuffer(FM.getBufferForFile(FE));
   if (FileBuffer =3D=3D 0) return 0;  // Unreadable file?
   const char *FileStart =3D FileBuffer->getBufferStart();
=20
@@ -220,7 +220,7 @@
=20
     // If so, we have a match in the hash table.  Construct the destination
     // path.
-    llvm::SmallString<1024> DestPath;
+    SmallString<1024> DestPath;
     DestPath +=3D getString(B.Prefix);
     DestPath +=3D getString(B.Suffix);
     return FM.getFile(DestPath.str());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
HeaderSearch.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/HeaderSearch.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/HeaderSearch.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -13,6 +13,8 @@
=20
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderMap.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "llvm/Support/FileSystem.h"
@@ -36,8 +38,12 @@
=20
 ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {}
=20
-HeaderSearch::HeaderSearch(FileManager &FM)
-    : FileMgr(FM), FrameworkMap(64) {
+HeaderSearch::HeaderSearch(FileManager &FM, DiagnosticsEngine &Diags,
+                           const LangOptions &LangOpts,=20
+                           const TargetInfo *Target)
+  : FileMgr(FM), Diags(Diags), FrameworkMap(64),=20
+    ModMap(FileMgr, *Diags.getClient(), LangOpts, Target)
+{
   AngledDirIdx =3D 0;
   SystemDirIdx =3D 0;
   NoCurDirSearch =3D false;
@@ -98,58 +104,81 @@
   return 0;
 }
=20
-const FileEntry *HeaderSearch::lookupModule(StringRef ModuleName,
-                                            std::string *ModuleFileName,
-                                            std::string *UmbrellaHeader) {
+std::string HeaderSearch::getModuleFileName(Module *Module) {
   // If we don't have a module cache path, we can't do anything.
-  if (ModuleCachePath.empty()) {
-    if (ModuleFileName)
-      ModuleFileName->clear();
-    return 0;
-  }
+  if (ModuleCachePath.empty())=20
+    return std::string();
+
+
+  SmallString<256> Result(ModuleCachePath);
+  llvm::sys::path::append(Result, Module->getTopLevelModule()->Name + ".pc=
m");
+  return Result.str().str();
+}
+
+std::string HeaderSearch::getModuleFileName(StringRef ModuleName) {
+  // If we don't have a module cache path, we can't do anything.
+  if (ModuleCachePath.empty())=20
+    return std::string();
  =20
-  // Try to find the module path.
-  llvm::SmallString<256> FileName(ModuleCachePath);
-  llvm::sys::path::append(FileName, ModuleName + ".pcm");
-  if (ModuleFileName)
-    *ModuleFileName =3D FileName.str();
+ =20
+  SmallString<256> Result(ModuleCachePath);
+  llvm::sys::path::append(Result, ModuleName + ".pcm");
+  return Result.str().str();
+}
+
+Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch)=
 {
+  // Look in the module map to determine if there is a module by this name.
+  Module *Module =3D ModMap.findModule(ModuleName);
+  if (Module || !AllowSearch)
+    return Module;
+ =20
+  // Look through the various header search paths to load any avai;able mo=
dule=20
+  // maps, searching for a module map that describes this module.
+  for (unsigned Idx =3D 0, N =3D SearchDirs.size(); Idx !=3D N; ++Idx) {
+    if (SearchDirs[Idx].isFramework()) {
+      // Search for or infer a module map for a framework.
+      SmallString<128> FrameworkDirName;
+      FrameworkDirName +=3D SearchDirs[Idx].getFrameworkDir()->getName();
+      llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework");
+      if (const DirectoryEntry *FrameworkDir=20
+            =3D FileMgr.getDirectory(FrameworkDirName)) {
+        bool IsSystem
+          =3D SearchDirs[Idx].getDirCharacteristic() !=3D SrcMgr::C_User;
+        Module =3D loadFrameworkModule(ModuleName, FrameworkDir, IsSystem);
+        if (Module)
+          break;
+      }
+    }
    =20
-  if (const FileEntry *ModuleFile
-        =3D getFileMgr().getFile(FileName, /*OpenFile=3D*/false,
-                               /*CacheFailure=3D*/false))
-    return ModuleFile;
- =20
-  // We didn't find the module. If we're not supposed to look for an
-  // umbrella header, this is the end of the road.
-  if (!UmbrellaHeader)
-    return 0;
- =20
-  // Look in each of the framework directories for an umbrella header with
-  // the same name as the module.
-  // FIXME: We need a way for non-frameworks to provide umbrella headers.
-  llvm::SmallString<128> UmbrellaHeaderName;
-  UmbrellaHeaderName =3D ModuleName;
-  UmbrellaHeaderName +=3D '/';
-  UmbrellaHeaderName +=3D ModuleName;
-  UmbrellaHeaderName +=3D ".h";
-  for (unsigned Idx =3D 0, N =3D SearchDirs.size(); Idx !=3D N; ++Idx) {
-    // Skip non-framework include paths
-    if (!SearchDirs[Idx].isFramework())
+    // FIXME: Figure out how header maps and module maps will work togethe=
r.
+   =20
+    // Only deal with normal search directories.
+    if (!SearchDirs[Idx].isNormalDir())
       continue;
    =20
-    // Look for the umbrella header in this directory.
-    if (const FileEntry *HeaderFile
-          =3D SearchDirs[Idx].LookupFile(UmbrellaHeaderName, *this, 0, 0,=20
-                                       StringRef(), 0)) {
-      *UmbrellaHeader =3D HeaderFile->getName();
-      return 0;
+    // Search for a module map file in this directory.
+    if (loadModuleMapFile(SearchDirs[Idx].getDir()) =3D=3D LMM_NewlyLoaded=
) {
+      // We just loaded a module map file; check whether the module is
+      // available now.
+      Module =3D ModMap.findModule(ModuleName);
+      if (Module)
+        break;
+    }
+             =20
+    // Search for a module map in a subdirectory with the same name as the
+    // module.
+    SmallString<128> NestedModuleMapDirName;
+    NestedModuleMapDirName =3D SearchDirs[Idx].getDir()->getName();
+    llvm::sys::path::append(NestedModuleMapDirName, ModuleName);
+    if (loadModuleMapFile(NestedModuleMapDirName) =3D=3D LMM_NewlyLoaded) {
+      // If we just loaded a module map file, look for the module again.
+      Module =3D ModMap.findModule(ModuleName);
+      if (Module)
+        break;
     }
   }
  =20
-  // We did not find an umbrella header. Clear out the UmbrellaHeader poin=
tee
-  // so our caller knows that we failed.
-  UmbrellaHeader->clear();
-  return 0;
+  return Module;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -175,9 +204,11 @@
     HeaderSearch &HS,
     SmallVectorImpl<char> *SearchPath,
     SmallVectorImpl<char> *RelativePath,
-    StringRef BuildingModule,
-    StringRef *SuggestedModule) const {
-  llvm::SmallString<1024> TmpDir;
+    Module **SuggestedModule,
+    bool &InUserSpecifiedSystemFramework) const {
+  InUserSpecifiedSystemFramework =3D false;
+
+  SmallString<1024> TmpDir;
   if (isNormalDir()) {
     // Concatenate the requested file onto the directory.
     TmpDir =3D getDir()->getName();
@@ -191,12 +222,27 @@
       RelativePath->clear();
       RelativePath->append(Filename.begin(), Filename.end());
     }
+   =20
+    // If we have a module map that might map this header, load it and
+    // check whether we'll have a suggestion for a module.
+    if (SuggestedModule && HS.hasModuleMap(TmpDir, getDir())) {
+      const FileEntry *File =3D HS.getFileMgr().getFile(TmpDir.str(),=20
+                                                      /*openFile=3D*/false=
);
+      if (!File)
+        return File;
+     =20
+      // If there is a module that corresponds to this header,=20
+      // suggest it.
+      *SuggestedModule =3D HS.findModuleForHeader(File);
+      return File;
+    }
+   =20
     return HS.getFileMgr().getFile(TmpDir.str(), /*openFile=3D*/true);
   }
=20
   if (isFramework())
     return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath,
-                             BuildingModule, SuggestedModule);
+                             SuggestedModule, InUserSpecifiedSystemFramewo=
rk);
=20
   assert(isHeaderMap() && "Unknown directory lookup");
   const FileEntry * const Result =3D getHeaderMap()->LookupFile(
@@ -223,8 +269,8 @@
     HeaderSearch &HS,
     SmallVectorImpl<char> *SearchPath,
     SmallVectorImpl<char> *RelativePath,
-    StringRef BuildingModule,
-    StringRef *SuggestedModule) const=20
+    Module **SuggestedModule,
+    bool &InUserSpecifiedSystemFramework) const
 {
   FileManager &FileMgr =3D HS.getFileMgr();
=20
@@ -233,49 +279,71 @@
   if (SlashPos =3D=3D StringRef::npos) return 0;
=20
   // Find out if this is the home for the specified framework, by checking
-  // HeaderSearch.  Possible answer are yes/no and unknown.
-  const DirectoryEntry *&FrameworkDirCache =3D
+  // HeaderSearch.  Possible answers are yes/no and unknown.
+  HeaderSearch::FrameworkCacheEntry &CacheEntry =3D
     HS.LookupFrameworkCache(Filename.substr(0, SlashPos));
=20
   // If it is known and in some other directory, fail.
-  if (FrameworkDirCache && FrameworkDirCache !=3D getFrameworkDir())
+  if (CacheEntry.Directory && CacheEntry.Directory !=3D getFrameworkDir())
     return 0;
=20
   // Otherwise, construct the path to this framework dir.
=20
   // FrameworkName =3D "/System/Library/Frameworks/"
-  llvm::SmallString<1024> FrameworkName;
+  SmallString<1024> FrameworkName;
   FrameworkName +=3D getFrameworkDir()->getName();
   if (FrameworkName.empty() || FrameworkName.back() !=3D '/')
     FrameworkName.push_back('/');
=20
   // FrameworkName =3D "/System/Library/Frameworks/Cocoa"
-  FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
+  StringRef ModuleName(Filename.begin(), SlashPos);
+  FrameworkName +=3D ModuleName;
=20
   // FrameworkName =3D "/System/Library/Frameworks/Cocoa.framework/"
   FrameworkName +=3D ".framework/";
=20
-  // If the cache entry is still unresolved, query to see if the cache ent=
ry is
-  // still unresolved.  If so, check its existence now.
-  if (FrameworkDirCache =3D=3D 0) {
+  // If the cache entry was unresolved, populate it now.
+  if (CacheEntry.Directory =3D=3D 0) {
     HS.IncrementFrameworkLookupCount();
=20
     // If the framework dir doesn't exist, we fail.
-    // FIXME: It's probably more efficient to query this with FileMgr.getD=
ir.
-    bool Exists;
-    if (llvm::sys::fs::exists(FrameworkName.str(), Exists) || !Exists)
-      return 0;
+    const DirectoryEntry *Dir =3D FileMgr.getDirectory(FrameworkName.str()=
);
+    if (Dir =3D=3D 0) return 0;
=20
     // Otherwise, if it does, remember that this is the right direntry for=
 this
     // framework.
-    FrameworkDirCache =3D getFrameworkDir();
+    CacheEntry.Directory =3D getFrameworkDir();
+
+    // If this is a user search directory, check if the framework has been
+    // user-specified as a system framework.
+    if (getDirCharacteristic() =3D=3D SrcMgr::C_User) {
+      SmallString<1024> SystemFrameworkMarker(FrameworkName);
+      SystemFrameworkMarker +=3D ".system_framework";
+      if (llvm::sys::fs::exists(SystemFrameworkMarker.str())) {
+        CacheEntry.IsUserSpecifiedSystemFramework =3D true;
+      }
+    }
   }
=20
+  // Set the 'user-specified system framework' flag.
+  InUserSpecifiedSystemFramework =3D CacheEntry.IsUserSpecifiedSystemFrame=
work;
+
   if (RelativePath !=3D NULL) {
     RelativePath->clear();
     RelativePath->append(Filename.begin()+SlashPos+1, Filename.end());
   }
=20
+  // If we're allowed to look for modules, try to load or create the module
+  // corresponding to this framework.
+  Module *Module =3D 0;
+  if (SuggestedModule) {
+    if (const DirectoryEntry *FrameworkDir
+                                        =3D FileMgr.getDirectory(Framework=
Name)) {
+      bool IsSystem =3D getDirCharacteristic() !=3D SrcMgr::C_User;
+      Module =3D HS.loadFrameworkModule(ModuleName, FrameworkDir, IsSystem=
);
+    }
+  }
+ =20
   // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h"
   unsigned OrigSize =3D FrameworkName.size();
=20
@@ -287,16 +355,13 @@
     SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1);
   }
=20
-  /// Determine whether this is the module we're building or not.
-  bool AutomaticImport =3D SuggestedModule &&
-    (BuildingModule !=3D StringRef(Filename.begin(), SlashPos)) &&
-    !Filename.substr(SlashPos + 1).startswith("..");
- =20
+  // Determine whether this is the module we're building or not.
+  bool AutomaticImport =3D Module; =20
   FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end());
   if (const FileEntry *FE =3D FileMgr.getFile(FrameworkName.str(),
                                             /*openFile=3D*/!AutomaticImpor=
t)) {
     if (AutomaticImport)
-      *SuggestedModule =3D StringRef(Filename.begin(), SlashPos);
+      *SuggestedModule =3D HS.findModuleForHeader(FE);
     return FE;
   }
=20
@@ -311,10 +376,14 @@
   const FileEntry *FE =3D FileMgr.getFile(FrameworkName.str(),=20
                                         /*openFile=3D*/!AutomaticImport);
   if (FE && AutomaticImport)
-    *SuggestedModule =3D StringRef(Filename.begin(), SlashPos);
+    *SuggestedModule =3D HS.findModuleForHeader(FE);
   return FE;
 }
=20
+void HeaderSearch::setTarget(const TargetInfo &Target) {
+  ModMap.setTarget(Target);
+}
+
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Header File Location.
@@ -334,10 +403,11 @@
     const FileEntry *CurFileEnt,
     SmallVectorImpl<char> *SearchPath,
     SmallVectorImpl<char> *RelativePath,
-    StringRef *SuggestedModule)=20
+    Module **SuggestedModule,
+    bool SkipCache)
 {
   if (SuggestedModule)
-    *SuggestedModule =3D StringRef();
+    *SuggestedModule =3D 0;
    =20
   // If 'Filename' is absolute, check to see if it exists and no searching.
   if (llvm::sys::path::is_absolute(Filename)) {
@@ -362,7 +432,7 @@
   // a subsequent include of "baz.h" should resolve to "whatever/foo/baz.h=
".
   // This search is not done for <> headers.
   if (CurFileEnt && !isAngled && !NoCurDirSearch) {
-    llvm::SmallString<1024> TmpDir;
+    SmallString<1024> TmpDir;
     // Concatenate the requested file onto the directory.
     // FIXME: Portability.  Filename concatenation should be in sys::Path.
     TmpDir +=3D CurFileEnt->getDir()->getName();
@@ -410,7 +480,7 @@
   // If the entry has been previously looked up, the first value will be
   // non-zero.  If the value is equal to i (the start point of our search)=
, then
   // this is a matching hit.
-  if (CacheLookup.first =3D=3D i+1) {
+  if (!SkipCache && CacheLookup.first =3D=3D i+1) {
     // Skip querying potentially lots of directories for this lookup.
     i =3D CacheLookup.second;
   } else {
@@ -422,9 +492,10 @@
=20
   // Check each directory in sequence to see if it contains this file.
   for (; i !=3D SearchDirs.size(); ++i) {
+    bool InUserSpecifiedSystemFramework =3D false;
     const FileEntry *FE =3D
       SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath,
-                               BuildingModule, SuggestedModule);
+                               SuggestedModule, InUserSpecifiedSystemFrame=
work);
     if (!FE) continue;
=20
     CurDir =3D &SearchDirs[i];
@@ -433,6 +504,12 @@
     HeaderFileInfo &HFI =3D getFileInfo(FE);
     HFI.DirInfo =3D CurDir->getDirCharacteristic();
=20
+    // If the directory characteristic is User but this framework was
+    // user-specified to be treated as a system framework, promote the
+    // characteristic.
+    if (HFI.DirInfo =3D=3D SrcMgr::C_User && InUserSpecifiedSystemFramewor=
k)
+      HFI.DirInfo =3D SrcMgr::C_System;
+
     // If this file is found in a header map and uses the framework style =
of
     // includes, then this header is part of a framework we're building.
     if (CurDir->isIndexHeaderMap()) {
@@ -456,7 +533,7 @@
   if (CurFileEnt && !isAngled && Filename.find('/') =3D=3D StringRef::npos=
) {
     HeaderFileInfo &IncludingHFI =3D getFileInfo(CurFileEnt);
     if (IncludingHFI.IndexHeaderMapHeader) {
-      llvm::SmallString<128> ScratchFilename;
+      SmallString<128> ScratchFilename;
       ScratchFilename +=3D IncludingHFI.Framework;
       ScratchFilename +=3D '/';
       ScratchFilename +=3D Filename;
@@ -491,6 +568,7 @@
   assert(ContextFileEnt && "No context file?");
=20
   // Framework names must have a '/' in the filename.  Find it.
+  // FIXME: Should we permit '\' on Windows?
   size_t SlashPos =3D Filename.find('/');
   if (SlashPos =3D=3D StringRef::npos) return 0;
=20
@@ -498,30 +576,32 @@
   const char *ContextName =3D ContextFileEnt->getName();
=20
   // If the context info wasn't a framework, couldn't be a subframework.
-  const char *FrameworkPos =3D strstr(ContextName, ".framework/");
-  if (FrameworkPos =3D=3D 0)
+  const unsigned DotFrameworkLen =3D 10;
+  const char *FrameworkPos =3D strstr(ContextName, ".framework");
+  if (FrameworkPos =3D=3D 0 ||=20
+      (FrameworkPos[DotFrameworkLen] !=3D '/' &&=20
+       FrameworkPos[DotFrameworkLen] !=3D '\\'))
     return 0;
=20
-  llvm::SmallString<1024> FrameworkName(ContextName,
-                                        FrameworkPos+strlen(".framework/")=
);
+  SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLe=
n+1);
=20
   // Append Frameworks/HIToolbox.framework/
   FrameworkName +=3D "Frameworks/";
   FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos);
   FrameworkName +=3D ".framework/";
=20
-  llvm::StringMapEntry<const DirectoryEntry *> &CacheLookup =3D
+  llvm::StringMapEntry<FrameworkCacheEntry> &CacheLookup =3D
     FrameworkMap.GetOrCreateValue(Filename.substr(0, SlashPos));
=20
   // Some other location?
-  if (CacheLookup.getValue() &&
+  if (CacheLookup.getValue().Directory &&
       CacheLookup.getKeyLength() =3D=3D FrameworkName.size() &&
       memcmp(CacheLookup.getKeyData(), &FrameworkName[0],
              CacheLookup.getKeyLength()) !=3D 0)
     return 0;
=20
   // Cache subframework.
-  if (CacheLookup.getValue() =3D=3D 0) {
+  if (CacheLookup.getValue().Directory =3D=3D 0) {
     ++NumSubFrameworkLookups;
=20
     // If the framework dir doesn't exist, we fail.
@@ -530,7 +610,7 @@
=20
     // Otherwise, if it does, remember that this is the right direntry for=
 this
     // framework.
-    CacheLookup.setValue(Dir);
+    CacheLookup.getValue().Directory =3D Dir;
   }
=20
   const FileEntry *FE =3D 0;
@@ -541,7 +621,7 @@
   }
=20
   // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h"
-  llvm::SmallString<1024> HeadersFilename(FrameworkName);
+  SmallString<1024> HeadersFilename(FrameworkName);
   HeadersFilename +=3D "Headers/";
   if (SearchPath !=3D NULL) {
     SearchPath->clear();
@@ -576,6 +656,28 @@
   return FE;
 }
=20
+/// \brief Helper static function to normalize a path for injection into
+/// a synthetic header.
+/*static*/ std::string
+HeaderSearch::NormalizeDashIncludePath(StringRef File, FileManager &FileMg=
r) {
+  // Implicit include paths should be resolved relative to the current
+  // working directory first, and then use the regular header search
+  // mechanism. The proper way to handle this is to have the
+  // predefines buffer located at the current working directory, but
+  // it has no file entry. For now, workaround this by using an
+  // absolute path if we find the file here, and otherwise letting
+  // header search handle it.
+  SmallString<128> Path(File);
+  llvm::sys::fs::make_absolute(Path);
+  bool exists;
+  if (llvm::sys::fs::exists(Path.str(), exists) || !exists)
+    Path =3D File;
+  else if (exists)
+    FileMgr.getFile(File);
+
+  return Lexer::Stringify(Path.str());
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // File Info Management.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -687,3 +789,247 @@
 StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) {
   return FrameworkNames.GetOrCreateValue(Framework).getKey();
 }
+
+bool HeaderSearch::hasModuleMap(StringRef FileName,=20
+                                const DirectoryEntry *Root) {
+  llvm::SmallVector<const DirectoryEntry *, 2> FixUpDirectories;
+ =20
+  StringRef DirName =3D FileName;
+  do {
+    // Get the parent directory name.
+    DirName =3D llvm::sys::path::parent_path(DirName);
+    if (DirName.empty())
+      return false;
+   =20
+    // Determine whether this directory exists.
+    const DirectoryEntry *Dir =3D FileMgr.getDirectory(DirName);
+    if (!Dir)
+      return false;
+   =20
+    // Try to load the module map file in this directory.
+    switch (loadModuleMapFile(Dir)) {
+    case LMM_NewlyLoaded:
+    case LMM_AlreadyLoaded:
+      // Success. All of the directories we stepped through inherit this m=
odule
+      // map file.
+      for (unsigned I =3D 0, N =3D FixUpDirectories.size(); I !=3D N; ++I)
+        DirectoryHasModuleMap[FixUpDirectories[I]] =3D true;
+     =20
+      return true;
+
+    case LMM_NoDirectory:
+    case LMM_InvalidModuleMap:
+      break;
+    }
+
+    // If we hit the top of our search, we're done.
+    if (Dir =3D=3D Root)
+      return false;
+       =20
+    // Keep track of all of the directories we checked, so we can mark the=
m as
+    // having module maps if we eventually do find a module map.
+    FixUpDirectories.push_back(Dir);
+  } while (true);
+}
+
+Module *HeaderSearch::findModuleForHeader(const FileEntry *File) {
+  if (Module *Mod =3D ModMap.findModuleForHeader(File))
+    return Mod;
+ =20
+  return 0;
+}
+
+bool HeaderSearch::loadModuleMapFile(const FileEntry *File) {
+  const DirectoryEntry *Dir =3D File->getDir();
+ =20
+  llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
+    =3D DirectoryHasModuleMap.find(Dir);
+  if (KnownDir !=3D DirectoryHasModuleMap.end())
+    return !KnownDir->second;
+ =20
+  bool Result =3D ModMap.parseModuleMapFile(File);
+  if (!Result && llvm::sys::path::filename(File->getName()) =3D=3D "module=
.map") {
+    // If the file we loaded was a module.map, look for the corresponding
+    // module_private.map.
+    SmallString<128> PrivateFilename(Dir->getName());
+    llvm::sys::path::append(PrivateFilename, "module_private.map");
+    if (const FileEntry *PrivateFile =3D FileMgr.getFile(PrivateFilename))
+      Result =3D ModMap.parseModuleMapFile(PrivateFile);
+  }
+ =20
+  DirectoryHasModuleMap[Dir] =3D !Result; =20
+  return Result;
+}
+
+Module *HeaderSearch::loadFrameworkModule(StringRef Name,=20
+                                          const DirectoryEntry *Dir,
+                                          bool IsSystem) {
+  if (Module *Module =3D ModMap.findModule(Name))
+    return Module;
+ =20
+  // Try to load a module map file.
+  switch (loadModuleMapFile(Dir)) {
+  case LMM_InvalidModuleMap:
+    break;
+   =20
+  case LMM_AlreadyLoaded:
+  case LMM_NoDirectory:
+    return 0;
+   =20
+  case LMM_NewlyLoaded:
+    return ModMap.findModule(Name);
+  }
+
+  // The top-level framework directory, from which we'll infer a framework
+  // module.
+  const DirectoryEntry *TopFrameworkDir =3D Dir;
+ =20
+  // The path from the module we're actually looking for back to the top-l=
evel
+  // framework name.
+  llvm::SmallVector<StringRef, 2> SubmodulePath;
+  SubmodulePath.push_back(Name);
+ =20
+  // Walk the directory structure to find any enclosing frameworks.
+  StringRef DirName =3D Dir->getName();
+  do {
+    // Get the parent directory name.
+    DirName =3D llvm::sys::path::parent_path(DirName);
+    if (DirName.empty())
+      break;
+   =20
+    // Determine whether this directory exists.
+    Dir =3D FileMgr.getDirectory(DirName);
+    if (!Dir)
+      break;
+   =20
+    // If this is a framework directory, then we're a subframework of this
+    // framework.
+    if (llvm::sys::path::extension(DirName) =3D=3D ".framework") {
+      SubmodulePath.push_back(llvm::sys::path::stem(DirName));
+      TopFrameworkDir =3D Dir;
+    }
+  } while (true);
+ =20
+  // Try to infer a module map from the top-level framework directory.
+  Module *Result =3D ModMap.inferFrameworkModule(SubmodulePath.back(),=20
+                                               TopFrameworkDir,
+                                               IsSystem,
+                                               /*Parent=3D*/0);
+ =20
+  // Follow the submodule path to find the requested (sub)framework module
+  // within the top-level framework module.
+  SubmodulePath.pop_back();
+  while (!SubmodulePath.empty() && Result) {
+    Result =3D ModMap.lookupModuleQualified(SubmodulePath.back(), Result);
+    SubmodulePath.pop_back();
+  }
+  return Result;
+}
+
+
+HeaderSearch::LoadModuleMapResult=20
+HeaderSearch::loadModuleMapFile(StringRef DirName) {
+  if (const DirectoryEntry *Dir =3D FileMgr.getDirectory(DirName))
+    return loadModuleMapFile(Dir);
+ =20
+  return LMM_NoDirectory;
+}
+
+HeaderSearch::LoadModuleMapResult=20
+HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir) {
+  llvm::DenseMap<const DirectoryEntry *, bool>::iterator KnownDir
+    =3D DirectoryHasModuleMap.find(Dir);
+  if (KnownDir !=3D DirectoryHasModuleMap.end())
+    return KnownDir->second? LMM_AlreadyLoaded : LMM_InvalidModuleMap;
+ =20
+  SmallString<128> ModuleMapFileName;
+  ModuleMapFileName +=3D Dir->getName();
+  unsigned ModuleMapDirNameLen =3D ModuleMapFileName.size();
+  llvm::sys::path::append(ModuleMapFileName, "module.map");
+  if (const FileEntry *ModuleMapFile =3D FileMgr.getFile(ModuleMapFileName=
)) {
+    // We have found a module map file. Try to parse it.
+    if (ModMap.parseModuleMapFile(ModuleMapFile)) {
+      // No suitable module map.
+      DirectoryHasModuleMap[Dir] =3D false;
+      return LMM_InvalidModuleMap;
+    }
+
+    // This directory has a module map.
+    DirectoryHasModuleMap[Dir] =3D true;
+   =20
+    // Check whether there is a private module map that we need to load as=
 well.
+    ModuleMapFileName.erase(ModuleMapFileName.begin() + ModuleMapDirNameLe=
n,
+                            ModuleMapFileName.end());
+    llvm::sys::path::append(ModuleMapFileName, "module_private.map");
+    if (const FileEntry *PrivateModuleMapFile
+                                        =3D FileMgr.getFile(ModuleMapFileN=
ame)) {
+      if (ModMap.parseModuleMapFile(PrivateModuleMapFile)) {
+        // No suitable module map.
+        DirectoryHasModuleMap[Dir] =3D false;
+        return LMM_InvalidModuleMap;
+      }     =20
+    }
+   =20
+    return LMM_NewlyLoaded;
+  }
+ =20
+  // No suitable module map.
+  DirectoryHasModuleMap[Dir] =3D false;
+  return LMM_InvalidModuleMap;
+}
+
+void HeaderSearch::collectAllModules(llvm::SmallVectorImpl<Module *> &Modu=
les) {
+  Modules.clear();
+ =20
+  // Load module maps for each of the header search directories.
+  for (unsigned Idx =3D 0, N =3D SearchDirs.size(); Idx !=3D N; ++Idx) {
+    if (SearchDirs[Idx].isFramework()) {
+      llvm::error_code EC;
+      SmallString<128> DirNative;
+      llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(),
+                              DirNative);
+     =20
+      // Search each of the ".framework" directories to load them as modul=
es.
+      bool IsSystem =3D SearchDirs[Idx].getDirCharacteristic() !=3D SrcMgr=
::C_User;
+      for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), Dir=
End;
+           Dir !=3D DirEnd && !EC; Dir.increment(EC)) {
+        if (llvm::sys::path::extension(Dir->path()) !=3D ".framework")
+          continue;
+       =20
+        const DirectoryEntry *FrameworkDir =3D FileMgr.getDirectory(Dir->p=
ath());
+        if (!FrameworkDir)
+          continue;
+       =20
+        // Load this framework module.
+        loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkD=
ir,
+                            IsSystem);
+      }
+      continue;
+    }
+   =20
+    // FIXME: Deal with header maps.
+    if (SearchDirs[Idx].isHeaderMap())
+      continue;
+   =20
+    // Try to load a module map file for the search directory.
+    loadModuleMapFile(SearchDirs[Idx].getDir());
+   =20
+    // Try to load module map files for immediate subdirectories of this s=
earch
+    // directory.
+    llvm::error_code EC;
+    SmallString<128> DirNative;
+    llvm::sys::path::native(SearchDirs[Idx].getDir()->getName(), DirNative=
);
+    for (llvm::sys::fs::directory_iterator Dir(DirNative.str(), EC), DirEn=
d;
+         Dir !=3D DirEnd && !EC; Dir.increment(EC)) {
+      loadModuleMapFile(Dir->path());
+    }
+  }
+ =20
+  // Populate the list of modules.
+  for (ModuleMap::module_iterator M =3D ModMap.module_begin(),=20
+                               MEnd =3D ModMap.module_end();
+       M !=3D MEnd; ++M) {
+    Modules.push_back(M->getValue());
+  }
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
Lexer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/Lexer.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/Lexer.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -30,6 +30,7 @@
 #include "clang/Lex/CodeCompletionHandler.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/StringSwitch.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include <cstring>
@@ -59,6 +60,8 @@
 // Lexer Class Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void Lexer::anchor() { }
+
 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
                       const char *BufEnd) {
   InitCharacterInfo();
@@ -114,7 +117,7 @@
 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor=
 &PP)
   : PreprocessorLexer(&PP, FID),
     FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
-    Features(PP.getLangOptions()) {
+    LangOpts(PP.getLangOpts()) {
=20
   InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
             InputFile->getBufferEnd());
@@ -126,9 +129,9 @@
 /// Lexer constructor - Create a new raw lexer object.  This object is only
 /// suitable for calls to 'LexRawToken'.  This lexer assumes that the text
 /// range will outlive it, so it doesn't take ownership of it.
-Lexer::Lexer(SourceLocation fileloc, const LangOptions &features,
+Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
              const char *BufStart, const char *BufPtr, const char *BufEnd)
-  : FileLoc(fileloc), Features(features) {
+  : FileLoc(fileloc), LangOpts(langOpts) {
=20
   InitLexer(BufStart, BufPtr, BufEnd);
=20
@@ -140,8 +143,8 @@
 /// suitable for calls to 'LexRawToken'.  This lexer assumes that the text
 /// range will outlive it, so it doesn't take ownership of it.
 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
-             const SourceManager &SM, const LangOptions &features)
-  : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) {
+             const SourceManager &SM, const LangOptions &langOpts)
+  : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
=20
   InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
             FromFile->getBufferEnd());
@@ -284,7 +287,7 @@
 /// wants to get the true, uncanonicalized, spelling of things like digrap=
hs
 /// UCNs, etc.
 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &Sour=
ceMgr,
-                               const LangOptions &Features, bool *Invalid)=
 {
+                               const LangOptions &LangOpts, bool *Invalid)=
 {
   assert((int)Tok.getLength() >=3D 0 && "Token character range is bogus!");
  =20
   // If this token contains nothing interesting, return it directly.
@@ -306,7 +309,7 @@
   for (const char *Ptr =3D TokStart, *End =3D TokStart+Tok.getLength();
        Ptr !=3D End; ) {
     unsigned CharSize;
-    Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
+    Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, LangOpts));
     Ptr +=3D CharSize;
   }
   assert(Result.size() !=3D unsigned(Tok.getLength()) &&
@@ -326,7 +329,7 @@
 /// if an internal buffer is returned.
 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,=20
                             const SourceManager &SourceMgr,
-                            const LangOptions &Features, bool *Invalid) {
+                            const LangOptions &LangOpts, bool *Invalid) {
   assert((int)Tok.getLength() >=3D 0 && "Token character range is bogus!");
=20
   const char *TokStart =3D 0;
@@ -366,7 +369,7 @@
   for (const char *Ptr =3D TokStart, *End =3D TokStart+Tok.getLength();
        Ptr !=3D End; ) {
     unsigned CharSize;
-    *OutBuf++ =3D Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
+    *OutBuf++ =3D Lexer::getCharAndSizeNoWarn(Ptr, CharSize, LangOpts);
     Ptr +=3D CharSize;
   }
   assert(unsigned(OutBuf-Buffer) !=3D Tok.getLength() &&
@@ -487,11 +490,11 @@
  SourceLocation FileLoc =3D SM.getSpellingLoc(Loc);
  SourceLocation BeginFileLoc =3D getBeginningOfFileToken(FileLoc, SM, Lang=
Opts);
  std::pair<FileID, unsigned> FileLocInfo =3D SM.getDecomposedLoc(FileLoc);
- std::pair<FileID, unsigned> BeginFileLocInfo=3D SM.getDecomposedLoc(Begin=
FileLoc);
+ std::pair<FileID, unsigned> BeginFileLocInfo
+   =3D SM.getDecomposedLoc(BeginFileLoc);
  assert(FileLocInfo.first =3D=3D BeginFileLocInfo.first &&
         FileLocInfo.second >=3D BeginFileLocInfo.second);
- return Loc.getLocWithOffset(SM.getDecomposedLoc(BeginFileLoc).second -
-                                 SM.getDecomposedLoc(FileLoc).second);
+ return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
 }
=20
 namespace {
@@ -505,13 +508,13 @@
=20
 std::pair<unsigned, bool>
 Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
-                       const LangOptions &Features, unsigned MaxLines) {
+                       const LangOptions &LangOpts, unsigned MaxLines) {
   // Create a lexer starting at the beginning of the file. Note that we us=
e a
   // "fake" file source location at offset 1 so that the lexer will track =
our
   // position within the file.
   const unsigned StartOffset =3D 1;
   SourceLocation StartLoc =3D SourceLocation::getFromRawEncoding(StartOffs=
et);
-  Lexer TheLexer(StartLoc, Features, Buffer->getBufferStart(),
+  Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
                  Buffer->getBufferStart(), Buffer->getBufferEnd());
  =20
   bool InPreprocessorDirective =3D false;
@@ -655,7 +658,7 @@
 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
                                               unsigned CharNo,
                                               const SourceManager &SM,
-                                              const LangOptions &Features)=
 {
+                                              const LangOptions &LangOpts)=
 {
   // Figure out how many physical characters away the specified expansion
   // character is.  This needs to take into consideration newlines and
   // trigraphs.
@@ -681,7 +684,7 @@
   // lexer to parse it correctly.
   for (; CharNo; --CharNo) {
     unsigned Size;
-    Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
+    Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
     TokPtr +=3D Size;
     PhysOffset +=3D Size;
   }
@@ -713,19 +716,16 @@
 /// a source location pointing to the last character in the token, etc.
 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Off=
set,
                                           const SourceManager &SM,
-                                          const LangOptions &Features) {
+                                          const LangOptions &LangOpts) {
   if (Loc.isInvalid())
     return SourceLocation();
=20
   if (Loc.isMacroID()) {
-    if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features))
+    if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
       return SourceLocation(); // Points inside the macro expansion.
-
-    // Continue and find the location just after the macro expansion.
-    Loc =3D SM.getExpansionRange(Loc).second;
   }
=20
-  unsigned Len =3D Lexer::MeasureTokenLength(Loc, SM, Features);
+  unsigned Len =3D Lexer::MeasureTokenLength(Loc, SM, LangOpts);
   if (Len > Offset)
     Len =3D Len - Offset;
   else
@@ -738,7 +738,8 @@
 /// token of the macro expansion.
 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
                                       const SourceManager &SM,
-                                      const LangOptions &LangOpts) {
+                                      const LangOptions &LangOpts,
+                                      SourceLocation *MacroBegin) {
   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
=20
   std::pair<FileID, unsigned> infoLoc =3D SM.getDecomposedLoc(loc);
@@ -749,17 +750,22 @@
=20
   SourceLocation expansionLoc =3D
     SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
-  if (expansionLoc.isFileID())
-    return true; // No other macro expansions, this is the first.
-
-  return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts);
+  if (expansionLoc.isFileID()) {
+    // No other macro expansions, this is the first.
+    if (MacroBegin)
+      *MacroBegin =3D expansionLoc;
+    return true;
+  }
+
+  return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
 }
=20
 /// \brief Returns true if the given MacroID location points at the last
 /// token of the macro expansion.
 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
-                                        const SourceManager &SM,
-                                        const LangOptions &LangOpts) {
+                                    const SourceManager &SM,
+                                    const LangOptions &LangOpts,
+                                    SourceLocation *MacroEnd) {
   assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
=20
   SourceLocation spellLoc =3D SM.getSpellingLoc(loc);
@@ -777,10 +783,192 @@
=20
   SourceLocation expansionLoc =3D
     SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
-  if (expansionLoc.isFileID())
-    return true; // No other macro expansions.
-
-  return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts);
+  if (expansionLoc.isFileID()) {
+    // No other macro expansions.
+    if (MacroEnd)
+      *MacroEnd =3D expansionLoc;
+    return true;
+  }
+
+  return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
+}
+
+static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
+                                             const SourceManager &SM,
+                                             const LangOptions &LangOpts) {
+  SourceLocation Begin =3D Range.getBegin();
+  SourceLocation End =3D Range.getEnd();
+  assert(Begin.isFileID() && End.isFileID());
+  if (Range.isTokenRange()) {
+    End =3D Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
+    if (End.isInvalid())
+      return CharSourceRange();
+  }
+
+  // Break down the source locations.
+  FileID FID;
+  unsigned BeginOffs;
+  llvm::tie(FID, BeginOffs) =3D SM.getDecomposedLoc(Begin);
+  if (FID.isInvalid())
+    return CharSourceRange();
+
+  unsigned EndOffs;
+  if (!SM.isInFileID(End, FID, &EndOffs) ||
+      BeginOffs > EndOffs)
+    return CharSourceRange();
+
+  return CharSourceRange::getCharRange(Begin, End);
+}
+
+/// \brief Accepts a range and returns a character range with file locatio=
ns.
+///
+/// Returns a null range if a part of the range resides inside a macro
+/// expansion or the range does not reside on the same FileID.
+CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
+                                         const SourceManager &SM,
+                                         const LangOptions &LangOpts) {
+  SourceLocation Begin =3D Range.getBegin();
+  SourceLocation End =3D Range.getEnd();
+  if (Begin.isInvalid() || End.isInvalid())
+    return CharSourceRange();
+
+  if (Begin.isFileID() && End.isFileID())
+    return makeRangeFromFileLocs(Range, SM, LangOpts);
+
+  if (Begin.isMacroID() && End.isFileID()) {
+    if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
+      return CharSourceRange();
+    Range.setBegin(Begin);
+    return makeRangeFromFileLocs(Range, SM, LangOpts);
+  }
+
+  if (Begin.isFileID() && End.isMacroID()) {
+    if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpt=
s,
+                                                          &End)) ||
+        (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOp=
ts,
+                                                           &End)))
+      return CharSourceRange();
+    Range.setEnd(End);
+    return makeRangeFromFileLocs(Range, SM, LangOpts);
+  }
+
+  assert(Begin.isMacroID() && End.isMacroID());
+  SourceLocation MacroBegin, MacroEnd;
+  if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
+      ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
+                                                        &MacroEnd)) ||
+       (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
+                                                         &MacroEnd)))) {
+    Range.setBegin(MacroBegin);
+    Range.setEnd(MacroEnd);
+    return makeRangeFromFileLocs(Range, SM, LangOpts);
+  }
+
+  FileID FID;
+  unsigned BeginOffs;
+  llvm::tie(FID, BeginOffs) =3D SM.getDecomposedLoc(Begin);
+  if (FID.isInvalid())
+    return CharSourceRange();
+
+  unsigned EndOffs;
+  if (!SM.isInFileID(End, FID, &EndOffs) ||
+      BeginOffs > EndOffs)
+    return CharSourceRange();
+
+  const SrcMgr::SLocEntry *E =3D &SM.getSLocEntry(FID);
+  const SrcMgr::ExpansionInfo &Expansion =3D E->getExpansion();
+  if (Expansion.isMacroArgExpansion() &&
+      Expansion.getSpellingLoc().isFileID()) {
+    SourceLocation SpellLoc =3D Expansion.getSpellingLoc();
+    Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
+    Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
+    return makeRangeFromFileLocs(Range, SM, LangOpts);
+  }
+
+  return CharSourceRange();
+}
+
+StringRef Lexer::getSourceText(CharSourceRange Range,
+                               const SourceManager &SM,
+                               const LangOptions &LangOpts,
+                               bool *Invalid) {
+  Range =3D makeFileCharRange(Range, SM, LangOpts);
+  if (Range.isInvalid()) {
+    if (Invalid) *Invalid =3D true;
+    return StringRef();
+  }
+
+  // Break down the source location.
+  std::pair<FileID, unsigned> beginInfo =3D SM.getDecomposedLoc(Range.getB=
egin());
+  if (beginInfo.first.isInvalid()) {
+    if (Invalid) *Invalid =3D true;
+    return StringRef();
+  }
+
+  unsigned EndOffs;
+  if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
+      beginInfo.second > EndOffs) {
+    if (Invalid) *Invalid =3D true;
+    return StringRef();
+  }
+
+  // Try to the load the file buffer.
+  bool invalidTemp =3D false;
+  StringRef file =3D SM.getBufferData(beginInfo.first, &invalidTemp);
+  if (invalidTemp) {
+    if (Invalid) *Invalid =3D true;
+    return StringRef();
+  }
+
+  if (Invalid) *Invalid =3D false;
+  return file.substr(beginInfo.second, EndOffs - beginInfo.second);
+}
+
+StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
+                                       const SourceManager &SM,
+                                       const LangOptions &LangOpts) {
+  assert(Loc.isMacroID() && "Only reasonble to call this on macros");
+
+  // Find the location of the immediate macro expansion.
+  while (1) {
+    FileID FID =3D SM.getFileID(Loc);
+    const SrcMgr::SLocEntry *E =3D &SM.getSLocEntry(FID);
+    const SrcMgr::ExpansionInfo &Expansion =3D E->getExpansion();
+    Loc =3D Expansion.getExpansionLocStart();
+    if (!Expansion.isMacroArgExpansion())
+      break;
+
+    // For macro arguments we need to check that the argument did not come
+    // from an inner macro, e.g: "MAC1( MAC2(foo) )"
+   =20
+    // Loc points to the argument id of the macro definition, move to the
+    // macro expansion.
+    Loc =3D SM.getImmediateExpansionRange(Loc).first;
+    SourceLocation SpellLoc =3D Expansion.getSpellingLoc();
+    if (SpellLoc.isFileID())
+      break; // No inner macro.
+
+    // If spelling location resides in the same FileID as macro expansion
+    // location, it means there is no inner macro.
+    FileID MacroFID =3D SM.getFileID(Loc);
+    if (SM.isInFileID(SpellLoc, MacroFID))
+      break;
+
+    // Argument came from inner macro.
+    Loc =3D SpellLoc;
+  }
+
+  // Find the spelling location of the start of the non-argument expansion
+  // range. This is where the macro name was spelled in order to begin
+  // expanding this macro.
+  Loc =3D SM.getSpellingLoc(Loc);
+
+  // Dig out the buffer where the macro name was spelled and the extents o=
f the
+  // name so that we can render it into the expansion note.
+  std::pair<FileID, unsigned> ExpansionInfo =3D SM.getDecomposedLoc(Loc);
+  unsigned MacroTokenLength =3D Lexer::MeasureTokenLength(Loc, SM, LangOpt=
s);
+  StringRef ExpansionBuffer =3D SM.getBufferData(ExpansionInfo.first);
+  return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -890,6 +1078,12 @@
 }
=20
=20
+/// isIdentifierHead - Return true if this is the first character of an
+/// identifier, which is [a-zA-Z_].
+static inline bool isIdentifierHead(unsigned char c) {
+  return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
+}
+
 /// isIdentifierBody - Return true if this is the body character of an
 /// identifier, which is [a-zA-Z0-9_].
 static inline bool isIdentifierBody(unsigned char c) {
@@ -1018,7 +1212,7 @@
   char Res =3D GetTrigraphCharForLetter(*CP);
   if (!Res || !L) return Res;
=20
-  if (!L->getFeatures().Trigraphs) {
+  if (!L->getLangOpts().Trigraphs) {
     if (!L->isLexingRawMode())
       L->Diag(CP-2, diag::trigraph_ignored);
     return 0;
@@ -1085,9 +1279,8 @@
                                         const LangOptions &LangOpts,
                                         bool SkipTrailingWhitespaceAndNewL=
ine) {
   if (Loc.isMacroID()) {
-    if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts))
+    if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
       return SourceLocation();
-    Loc =3D SM.getExpansionRange(Loc).second;
   }
   Loc =3D Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
=20
@@ -1169,6 +1362,13 @@
       // Found backslash<whitespace><newline>.  Parse the char after it.
       Size +=3D EscapedNewLineSize;
       Ptr  +=3D EscapedNewLineSize;
+
+      // If the char that we finally got was a \n, then we must have had
+      // something like \<newline><newline>.  We don't want to consume the
+      // second newline.
+      if (*Ptr =3D=3D '\n' || *Ptr =3D=3D '\r' || *Ptr =3D=3D '\0')
+        return ' ';
+
       // Use slow version to accumulate a correct size field.
       return getCharAndSizeSlow(Ptr, Size, Tok);
     }
@@ -1205,7 +1405,7 @@
 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
 /// be updated to match.
 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
-                                     const LangOptions &Features) {
+                                     const LangOptions &LangOpts) {
   // If we have a slash, look for an escaped newline.
   if (Ptr[0] =3D=3D '\\') {
     ++Size;
@@ -1220,8 +1420,14 @@
       Size +=3D EscapedNewLineSize;
       Ptr  +=3D EscapedNewLineSize;
=20
+      // If the char that we finally got was a \n, then we must have had
+      // something like \<newline><newline>.  We don't want to consume the
+      // second newline.
+      if (*Ptr =3D=3D '\n' || *Ptr =3D=3D '\r' || *Ptr =3D=3D '\0')
+        return ' ';
+
       // Use slow version to accumulate a correct size field.
-      return getCharAndSizeSlowNoWarn(Ptr, Size, Features);
+      return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
     }
=20
     // Otherwise, this is not an escaped newline, just return the slash.
@@ -1229,7 +1435,7 @@
   }
=20
   // If this is a trigraph, process it.
-  if (Features.Trigraphs && Ptr[0] =3D=3D '?' && Ptr[1] =3D=3D '?') {
+  if (LangOpts.Trigraphs && Ptr[0] =3D=3D '?' && Ptr[1] =3D=3D '?') {
     // If this is actually a legal trigraph (not something like "??x"), re=
turn
     // it.
     if (char C =3D GetTrigraphCharForLetter(Ptr[2])) {
@@ -1272,7 +1478,7 @@
   //
   // TODO: Could merge these checks into a CharInfo flag to make the compa=
rison
   // cheaper
-  if (C !=3D '\\' && C !=3D '?' && (C !=3D '$' || !Features.DollarIdents))=
 {
+  if (C !=3D '\\' && C !=3D '?' && (C !=3D '$' || !LangOpts.DollarIdents))=
 {
 FinishIdentifier:
     const char *IdStart =3D BufferPtr;
     FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
@@ -1301,7 +1507,7 @@
   while (1) {
     if (C =3D=3D '$') {
       // If we hit a $ and they are not supported in identifiers, we are d=
one.
-      if (!Features.DollarIdents) goto FinishIdentifier;
+      if (!LangOpts.DollarIdents) goto FinishIdentifier;
=20
       // Otherwise, emit a diagnostic and continue.
       if (!isLexingRawMode())
@@ -1327,12 +1533,12 @@
=20
 /// isHexaLiteral - Return true if Start points to a hex constant.
 /// in microsoft mode (where this is supposed to be several different toke=
ns).
-static bool isHexaLiteral(const char *Start, const LangOptions &Features) {
+static bool isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
   unsigned Size;
-  char C1 =3D Lexer::getCharAndSizeNoWarn(Start, Size, Features);
+  char C1 =3D Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
   if (C1 !=3D '0')
     return false;
-  char C2 =3D Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features);
+  char C2 =3D Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
   return (C2 =3D=3D 'x' || C2 =3D=3D 'X');
 }
=20
@@ -1343,7 +1549,7 @@
   unsigned Size;
   char C =3D getCharAndSize(CurPtr, Size);
   char PrevCh =3D 0;
-  while (isNumberBody(C)) { // FIXME: UCNs?
+  while (isNumberBody(C)) { // FIXME: UCNs.
     CurPtr =3D ConsumeChar(CurPtr, Size, Result);
     PrevCh =3D C;
     C =3D getCharAndSize(CurPtr, Size);
@@ -1353,7 +1559,7 @@
   if ((C =3D=3D '-' || C =3D=3D '+') && (PrevCh =3D=3D 'E' || PrevCh =3D=
=3D 'e')) {
     // If we are in Microsoft mode, don't continue if the constant is hex.
     // For example, MSVC will accept the following as 3 tokens: 0x1234567e=
+1
-    if (!Features.MicrosoftExt || !isHexaLiteral(BufferPtr, Features))
+    if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
       return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
   }
=20
@@ -1367,6 +1573,46 @@
   Result.setLiteralData(TokStart);
 }
=20
+/// LexUDSuffix - Lex the ud-suffix production for user-defined literal su=
ffixes
+/// in C++11, or warn on a ud-suffix in C++98.
+const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
+  assert(getLangOpts().CPlusPlus);
+
+  // Maximally munch an identifier. FIXME: UCNs.
+  unsigned Size;
+  char C =3D getCharAndSize(CurPtr, Size);
+  if (isIdentifierHead(C)) {
+    if (!getLangOpts().CPlusPlus0x) {
+      if (!isLexingRawMode())
+        Diag(CurPtr,
+             C =3D=3D '_' ? diag::warn_cxx11_compat_user_defined_literal
+                      : diag::warn_cxx11_compat_reserved_user_defined_lite=
ral)
+          << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
+      return CurPtr;
+    }
+
+    // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-su=
ffix
+    // that does not start with an underscore is ill-formed. As a conformi=
ng
+    // extension, we treat all such suffixes as if they had whitespace bef=
ore
+    // them.
+    if (C !=3D '_') {
+      if (!isLexingRawMode())
+        Diag(CurPtr, getLangOpts().MicrosoftMode ?=20
+            diag::ext_ms_reserved_user_defined_literal :
+            diag::ext_reserved_user_defined_literal)
+          << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
+      return CurPtr;
+    }
+
+    Result.setFlag(Token::HasUDSuffix);
+    do {
+      CurPtr =3D ConsumeChar(CurPtr, Size, Result);
+      C =3D getCharAndSize(CurPtr, Size);
+    } while (isIdentifierBody(C));
+  }
+  return CurPtr;
+}
+
 /// LexStringLiteral - Lex the remainder of a string literal, after having=
 lexed
 /// either " or L" or u8" or u" or U".
 void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
@@ -1388,7 +1634,7 @@
    =20
     if (C =3D=3D '\n' || C =3D=3D '\r' ||             // Newline.
         (C =3D=3D 0 && CurPtr-1 =3D=3D BufferEnd)) {  // End of file.
-      if (!isLexingRawMode() && !Features.AsmPreprocessor)
+      if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
         Diag(BufferPtr, diag::warn_unterminated_string);
       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
       return;
@@ -1406,6 +1652,10 @@
     C =3D getAndAdvanceChar(CurPtr, Result);
   }
=20
+  // If we are in C++11, lex the optional ud-suffix.
+  if (getLangOpts().CPlusPlus)
+    CurPtr =3D LexUDSuffix(Result, CurPtr);
+
   // If a nul character existed in the string, warn about it.
   if (NulCharacter && !isLexingRawMode())
     Diag(NulCharacter, diag::null_in_string);
@@ -1485,6 +1735,10 @@
     }
   }
=20
+  // If we are in C++11, lex the optional ud-suffix.
+  if (getLangOpts().CPlusPlus)
+    CurPtr =3D LexUDSuffix(Result, CurPtr);
+
   // Update the location of token as well as BufferPtr.
   const char *TokStart =3D BufferPtr;
   FormTokenWithChars(Result, CurPtr, Kind);
@@ -1538,7 +1792,7 @@
=20
   char C =3D getAndAdvanceChar(CurPtr, Result);
   if (C =3D=3D '\'') {
-    if (!isLexingRawMode() && !Features.AsmPreprocessor)
+    if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
       Diag(BufferPtr, diag::err_empty_character);
     FormTokenWithChars(Result, CurPtr, tok::unknown);
     return;
@@ -1552,7 +1806,7 @@
       C =3D getAndAdvanceChar(CurPtr, Result);
     } else if (C =3D=3D '\n' || C =3D=3D '\r' ||             // Newline.
                (C =3D=3D 0 && CurPtr-1 =3D=3D BufferEnd)) {  // End of fil=
e.
-      if (!isLexingRawMode() && !Features.AsmPreprocessor)
+      if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
         Diag(BufferPtr, diag::warn_unterminated_char);
       FormTokenWithChars(Result, CurPtr-1, tok::unknown);
       return;
@@ -1568,6 +1822,10 @@
     C =3D getAndAdvanceChar(CurPtr, Result);
   }
=20
+  // If we are in C++11, lex the optional ud-suffix.
+  if (getLangOpts().CPlusPlus)
+    CurPtr =3D LexUDSuffix(Result, CurPtr);
+
   // If a nul character existed in the character, warn about it.
   if (NulCharacter && !isLexingRawMode())
     Diag(NulCharacter, diag::null_in_char);
@@ -1633,12 +1891,12 @@
 bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
   // If BCPL comments aren't explicitly enabled for this language, emit an
   // extension warning.
-  if (!Features.BCPLComment && !isLexingRawMode()) {
+  if (!LangOpts.BCPLComment && !isLexingRawMode()) {
     Diag(BufferPtr, diag::ext_bcpl_comment);
=20
     // Mark them enabled so we only emit one warning for this translation
     // unit.
-    Features.BCPLComment =3D true;
+    LangOpts.BCPLComment =3D true;
   }
=20
   // Scan over the body of the comment.  The common case, when scanning, i=
s that
@@ -1687,14 +1945,6 @@
       break;
     }
=20
-    // If the char that we finally got was a \n, then we must have had som=
ething
-    // like \<newline><newline>.  We don't want to have consumed the second
-    // newline, we want CurPtr, to end up pointing to it down below.
-    if (C =3D=3D '\n' || C =3D=3D '\r') {
-      --CurPtr;
-      C =3D 'x'; // doesn't matter what this is.
-    }
-
     // If we read multiple characters, and one of those characters was a \=
r or
     // \n, then we had an escaped newline within the comment.  Emit diagno=
stic
     // unless the next line is also a // comment.
@@ -1833,7 +2083,7 @@
=20
     // If no trigraphs are enabled, warn that we ignored this trigraph and
     // ignore this * character.
-    if (!L->getFeatures().Trigraphs) {
+    if (!L->getLangOpts().Trigraphs) {
       if (!L->isLexingRawMode())
         L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
       return false;
@@ -1916,11 +2166,18 @@
       if (C =3D=3D '/') goto FoundSlash;
=20
 #ifdef __SSE2__
-      __m128i Slashes =3D _mm_set_epi8('/', '/', '/', '/', '/', '/', '/', =
'/',
-                                     '/', '/', '/', '/', '/', '/', '/', '/=
');
-      while (CurPtr+16 <=3D BufferEnd &&
-             _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes))=
 =3D=3D 0)
+      __m128i Slashes =3D _mm_set1_epi8('/');
+      while (CurPtr+16 <=3D BufferEnd) {
+        int cmp =3D _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Sl=
ashes));
+        if (cmp !=3D 0) {
+          // Adjust the pointer to point directly after the first slash. I=
t's
+          // not necessary to set C here, it will be overwritten at the en=
d of
+          // the outer loop.
+          CurPtr +=3D llvm::CountTrailingZeros_32(cmp) + 1;
+          goto FoundSlash;
+        }
         CurPtr +=3D 16;
+      }
 #elif __ALTIVEC__
       __vector unsigned char Slashes =3D {
         '/', '/', '/', '/',  '/', '/', '/', '/',
@@ -1948,8 +2205,8 @@
     while (C !=3D '/' && C !=3D '\0')
       C =3D *CurPtr++;
=20
+    if (C =3D=3D '/') {
   FoundSlash:
-    if (C =3D=3D '/') {
       if (CurPtr[-2] =3D=3D '*')  // We found the final */.  We're done!
         break;
=20
@@ -2119,8 +2376,9 @@
   // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, =
issue
   // a pedwarn.
   if (CurPtr !=3D BufferStart && (CurPtr[-1] !=3D '\n' && CurPtr[-1] !=3D =
'\r'))
-    Diag(BufferEnd, diag::ext_no_newline_eof)
-      << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
+    Diag(BufferEnd, LangOpts.CPlusPlus0x ? // C++11 [lex.phases] 2.2 p2
+         diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
+    << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
=20
   BufferPtr =3D CurPtr;
=20
@@ -2345,7 +2603,7 @@
      =20
   case 26:  // DOS & CP/M EOF: "^Z".
     // If we're in Microsoft extensions mode, treat this as end of file.
-    if (Features.MicrosoftExt) {
+    if (LangOpts.MicrosoftExt) {
       // Read the PP instance variable into an automatic variable, because
       // LexEndOfFile will often delete 'this'.
       Preprocessor *PPCache =3D PP;
@@ -2398,7 +2656,7 @@
     // If the next token is obviously a // or /* */ comment, skip it effic=
iently
     // too (without going through the big switch stmt).
     if (CurPtr[0] =3D=3D '/' && CurPtr[1] =3D=3D '/' && !inKeepCommentMode=
() &&
-        Features.BCPLComment && !Features.TraditionalCPP) {
+        LangOpts.BCPLComment && !LangOpts.TraditionalCPP) {
       if (SkipBCPLComment(Result, CurPtr+2))
         return; // There is a token to return.
       goto SkipIgnoredUnits;
@@ -2423,7 +2681,7 @@
     // Notify MIOpt that we read a non-whitespace/non-comment token.
     MIOpt.ReadToken();
=20
-    if (Features.CPlusPlus0x) {
+    if (LangOpts.CPlusPlus0x) {
       Char =3D getCharAndSize(CurPtr, SizeTmp);
=20
       // UTF-16 string literal
@@ -2475,7 +2733,7 @@
     // Notify MIOpt that we read a non-whitespace/non-comment token.
     MIOpt.ReadToken();
=20
-    if (Features.CPlusPlus0x) {
+    if (LangOpts.CPlusPlus0x) {
       Char =3D getCharAndSize(CurPtr, SizeTmp);
=20
       // UTF-32 string literal
@@ -2503,7 +2761,7 @@
     // Notify MIOpt that we read a non-whitespace/non-comment token.
     MIOpt.ReadToken();
=20
-    if (Features.CPlusPlus0x) {
+    if (LangOpts.CPlusPlus0x) {
       Char =3D getCharAndSize(CurPtr, SizeTmp);
=20
       if (Char =3D=3D '"')
@@ -2526,7 +2784,7 @@
                               tok::wide_string_literal);
=20
     // Wide raw string literal.
-    if (Features.CPlusPlus0x && Char =3D=3D 'R' &&
+    if (LangOpts.CPlusPlus0x && Char =3D=3D 'R' &&
         getCharAndSize(CurPtr + SizeTmp, SizeTmp2) =3D=3D '"')
       return LexRawStringLiteral(Result,
                                ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Re=
sult),
@@ -2554,7 +2812,7 @@
     return LexIdentifier(Result, CurPtr);
=20
   case '$':   // $ in identifiers.
-    if (Features.DollarIdents) {
+    if (LangOpts.DollarIdents) {
       if (!isLexingRawMode())
         Diag(CurPtr-1, diag::ext_dollar_in_identifier);
       // Notify MIOpt that we read a non-whitespace/non-comment token.
@@ -2606,7 +2864,7 @@
       MIOpt.ReadToken();
=20
       return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Resul=
t));
-    } else if (Features.CPlusPlus && Char =3D=3D '*') {
+    } else if (LangOpts.CPlusPlus && Char =3D=3D '*') {
       Kind =3D tok::periodstar;
       CurPtr +=3D SizeTmp;
     } else if (Char =3D=3D '.' &&
@@ -2655,7 +2913,7 @@
     if (Char =3D=3D '-') {      // --
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
       Kind =3D tok::minusminus;
-    } else if (Char =3D=3D '>' && Features.CPlusPlus &&
+    } else if (Char =3D=3D '>' && LangOpts.CPlusPlus &&
                getCharAndSize(CurPtr+SizeTmp, SizeTmp2) =3D=3D '*') {  // =
C++ ->*
       CurPtr =3D ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
                            SizeTmp2, Result);
@@ -2693,9 +2951,9 @@
       // "foo".  Check to see if the character after the second slash is a=
 '*'.
       // If so, we will lex that as a "/" instead of the start of a commen=
t.
       // However, we never do this in -traditional-cpp mode.
-      if ((Features.BCPLComment ||
+      if ((LangOpts.BCPLComment ||
            getCharAndSize(CurPtr+SizeTmp, SizeTmp2) !=3D '*') &&
-          !Features.TraditionalCPP) {
+          !LangOpts.TraditionalCPP) {
         if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
           return; // There is a token to return.
=20
@@ -2724,20 +2982,20 @@
     if (Char =3D=3D '=3D') {
       Kind =3D tok::percentequal;
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
-    } else if (Features.Digraphs && Char =3D=3D '>') {
+    } else if (LangOpts.Digraphs && Char =3D=3D '>') {
       Kind =3D tok::r_brace;                             // '%>' -> '}'
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
-    } else if (Features.Digraphs && Char =3D=3D ':') {
+    } else if (LangOpts.Digraphs && Char =3D=3D ':') {
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
       Char =3D getCharAndSize(CurPtr, SizeTmp);
       if (Char =3D=3D '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) =3D=
=3D ':') {
         Kind =3D tok::hashhash;                          // '%:%:' -> '##'
         CurPtr =3D ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
                              SizeTmp2, Result);
-      } else if (Char =3D=3D '@' && Features.MicrosoftExt) {// %:@ -> #@ -=
> Charize
+      } else if (Char =3D=3D '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -=
> Charize
         CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
         if (!isLexingRawMode())
-          Diag(BufferPtr, diag::charize_microsoft_ext);
+          Diag(BufferPtr, diag::ext_charize_microsoft);
         Kind =3D tok::hashat;
       } else {                                         // '%:' -> '#'
         // We parsed a # character.  If this occurs at the start of the li=
ne,
@@ -2789,7 +3047,7 @@
         // If this is '<<<<' and we're in a Perforce-style conflict marker,
         // ignore it.
         goto LexNextToken;
-      } else if (Features.CUDA && After =3D=3D '<') {
+      } else if (LangOpts.CUDA && After =3D=3D '<') {
         Kind =3D tok::lesslessless;
         CurPtr =3D ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
                              SizeTmp2, Result);
@@ -2800,8 +3058,8 @@
     } else if (Char =3D=3D '=3D') {
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
       Kind =3D tok::lessequal;
-    } else if (Features.Digraphs && Char =3D=3D ':') {     // '<:' -> '['
-      if (Features.CPlusPlus0x &&
+    } else if (LangOpts.Digraphs && Char =3D=3D ':') {     // '<:' -> '['
+      if (LangOpts.CPlusPlus0x &&
           getCharAndSize(CurPtr + SizeTmp, SizeTmp2) =3D=3D ':') {
         // C++0x [lex.pptoken]p3:
         //  Otherwise, if the next three characters are <:: and the subseq=
uent
@@ -2820,7 +3078,7 @@
=20
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
       Kind =3D tok::l_square;
-    } else if (Features.Digraphs && Char =3D=3D '%') {     // '<%' -> '{'
+    } else if (LangOpts.Digraphs && Char =3D=3D '%') {     // '<%' -> '{'
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
       Kind =3D tok::l_brace;
     } else {
@@ -2845,7 +3103,7 @@
       } else if (After =3D=3D '>' && HandleEndOfConflictMarker(CurPtr-1)) {
         // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
         goto LexNextToken;
-      } else if (Features.CUDA && After =3D=3D '>') {
+      } else if (LangOpts.CUDA && After =3D=3D '>') {
         Kind =3D tok::greatergreatergreater;
         CurPtr =3D ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
                              SizeTmp2, Result);
@@ -2884,10 +3142,10 @@
     break;
   case ':':
     Char =3D getCharAndSize(CurPtr, SizeTmp);
-    if (Features.Digraphs && Char =3D=3D '>') {
+    if (LangOpts.Digraphs && Char =3D=3D '>') {
       Kind =3D tok::r_square; // ':>' -> ']'
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
-    } else if (Features.CPlusPlus && Char =3D=3D ':') {
+    } else if (LangOpts.CPlusPlus && Char =3D=3D ':') {
       Kind =3D tok::coloncolon;
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
     } else {
@@ -2918,10 +3176,10 @@
     if (Char =3D=3D '#') {
       Kind =3D tok::hashhash;
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
-    } else if (Char =3D=3D '@' && Features.MicrosoftExt) {  // #@ -> Chari=
ze
+    } else if (Char =3D=3D '@' && LangOpts.MicrosoftExt) {  // #@ -> Chari=
ze
       Kind =3D tok::hashat;
       if (!isLexingRawMode())
-        Diag(BufferPtr, diag::charize_microsoft_ext);
+        Diag(BufferPtr, diag::ext_charize_microsoft);
       CurPtr =3D ConsumeChar(CurPtr, SizeTmp, Result);
     } else {
       // We parsed a # character.  If this occurs at the start of the line,
@@ -2954,7 +3212,7 @@
=20
   case '@':
     // Objective C support.
-    if (CurPtr[-1] =3D=3D '@' && Features.ObjC1)
+    if (CurPtr[-1] =3D=3D '@' && LangOpts.ObjC1)
       Kind =3D tok::at;
     else
       Kind =3D tok::unknown;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
LiteralSupport.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/LiteralSupport.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/LiteralSupport.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/LexDiagnostic.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/Basic/ConvertUTF.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 using namespace clang;
@@ -178,15 +179,16 @@
=20
 /// ProcessUCNEscape - Read the Universal Character Name, check constraint=
s and
 /// return the UTF32.
-static bool ProcessUCNEscape(const char *&ThisTokBuf, const char *ThisTokE=
nd,
+static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTo=
kBuf,
+                             const char *ThisTokEnd,
                              uint32_t &UcnVal, unsigned short &UcnLen,
                              FullSourceLoc Loc, DiagnosticsEngine *Diags,=20
-                             const LangOptions &Features) {
+                             const LangOptions &Features,
+                             bool in_char_string_literal =3D false) {
   if (!Features.CPlusPlus && !Features.C99 && Diags)
     Diags->Report(Loc, diag::warn_ucn_not_valid_in_c89);
=20
-  // Save the beginning of the string (for error diagnostics).
-  const char *ThisTokBegin =3D ThisTokBuf;
+  const char *UcnBegin =3D ThisTokBuf;
=20
   // Skip the '\u' char's.
   ThisTokBuf +=3D 2;
@@ -208,22 +210,43 @@
   if (UcnLenSave) {
     if (Diags) {
       SourceLocation L =3D
-        Lexer::AdvanceToTokenCharacter(Loc, ThisTokBuf-ThisTokBegin,
+        Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
                                        Loc.getManager(), Features);
-      Diags->Report(FullSourceLoc(L, Loc.getManager()),
-                    diag::err_ucn_escape_incomplete);
+      Diags->Report(L, diag::err_ucn_escape_incomplete);
     }
     return false;
   }
-  // Check UCN constraints (C99 6.4.3p2).
-  if ((UcnVal < 0xa0 &&
-      (UcnVal !=3D 0x24 && UcnVal !=3D 0x40 && UcnVal !=3D 0x60 )) // $, @=
, `
-      || (UcnVal >=3D 0xD800 && UcnVal <=3D 0xDFFF)
-      || (UcnVal > 0x10FFFF)) /* the maximum legal UTF32 value */ {
+
+  // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
+  if ((0xD800 <=3D UcnVal && UcnVal <=3D 0xDFFF) || // surrogate codepoints
+      UcnVal > 0x10FFFF) {                      // maximum legal UTF32 val=
ue
     if (Diags)
       Diags->Report(Loc, diag::err_ucn_escape_invalid);
     return false;
   }
+
+  // C++11 allows UCNs that refer to control characters and basic source
+  // characters inside character and string literals
+  if (UcnVal < 0xa0 &&
+      (UcnVal !=3D 0x24 && UcnVal !=3D 0x40 && UcnVal !=3D 0x60)) {  // $,=
 @, `
+    bool IsError =3D (!Features.CPlusPlus0x || !in_char_string_literal);
+    if (Diags) {
+      SourceLocation UcnBeginLoc =3D
+        Lexer::AdvanceToTokenCharacter(Loc, UcnBegin - ThisTokBegin,
+                                       Loc.getManager(), Features);
+      char BasicSCSChar =3D UcnVal;
+      if (UcnVal >=3D 0x20 && UcnVal < 0x7f)
+        Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_escape_basic_sc=
s :
+                      diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
+          << StringRef(&BasicSCSChar, 1);
+      else
+        Diags->Report(UcnBeginLoc, IsError ? diag::err_ucn_control_charact=
er :
+                      diag::warn_cxx98_compat_literal_ucn_control_characte=
r);
+    }
+    if (IsError)
+      return false;
+  }
+
   return true;
 }
=20
@@ -231,7 +254,8 @@
 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
 /// we will likely rework our support for UCN's.
-static void EncodeUCNEscape(const char *&ThisTokBuf, const char *ThisTokEn=
d,
+static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTok=
Buf,
+                            const char *ThisTokEnd,
                             char *&ResultBuf, bool &HadError,
                             FullSourceLoc Loc, unsigned CharByteWidth,
                             DiagnosticsEngine *Diags,
@@ -239,8 +263,8 @@
   typedef uint32_t UTF32;
   UTF32 UcnVal =3D 0;
   unsigned short UcnLen =3D 0;
-  if (!ProcessUCNEscape(ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, Loc, Diags,
-                        Features)) {
+  if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnL=
en,
+                        Loc, Diags, Features, true)) {
     HadError =3D 1;
     return;
   }
@@ -252,31 +276,30 @@
   assert((UcnLen=3D=3D 4 || UcnLen=3D=3D 8) && "only ucn length of 4 or 8 =
supported");
=20
   if (CharByteWidth =3D=3D 4) {
-    // Note: our internal rep of wide char tokens is always little-endian.
-    *ResultBuf++ =3D (UcnVal & 0x000000FF);
-    *ResultBuf++ =3D (UcnVal & 0x0000FF00) >> 8;
-    *ResultBuf++ =3D (UcnVal & 0x00FF0000) >> 16;
-    *ResultBuf++ =3D (UcnVal & 0xFF000000) >> 24;
+    // FIXME: Make the type of the result buffer correct instead of
+    // using reinterpret_cast.
+    UTF32 *ResultPtr =3D reinterpret_cast<UTF32*>(ResultBuf);
+    *ResultPtr =3D UcnVal;
+    ResultBuf +=3D 4;
     return;
   }
=20
   if (CharByteWidth =3D=3D 2) {
-    // Convert to UTF16.
+    // FIXME: Make the type of the result buffer correct instead of
+    // using reinterpret_cast.
+    UTF16 *ResultPtr =3D reinterpret_cast<UTF16*>(ResultBuf);
+
     if (UcnVal < (UTF32)0xFFFF) {
-      *ResultBuf++ =3D (UcnVal & 0x000000FF);
-      *ResultBuf++ =3D (UcnVal & 0x0000FF00) >> 8;
+      *ResultPtr =3D UcnVal;
+      ResultBuf +=3D 2;
       return;
     }
-    if (Diags) Diags->Report(Loc, diag::warn_ucn_escape_too_large);
=20
-    typedef uint16_t UTF16;
+    // Convert to UTF16.
     UcnVal -=3D 0x10000;
-    UTF16 surrogate1 =3D 0xD800 + (UcnVal >> 10);
-    UTF16 surrogate2 =3D 0xDC00 + (UcnVal & 0x3FF);
-    *ResultBuf++ =3D (surrogate1 & 0x000000FF);
-    *ResultBuf++ =3D (surrogate1 & 0x0000FF00) >> 8;
-    *ResultBuf++ =3D (surrogate2 & 0x000000FF);
-    *ResultBuf++ =3D (surrogate2 & 0x0000FF00) >> 8;
+    *ResultPtr     =3D 0xD800 + (UcnVal >> 10);
+    *(ResultPtr+1) =3D 0xDC00 + (UcnVal & 0x3FF);
+    ResultBuf +=3D 4;
     return;
   }
=20
@@ -323,6 +346,10 @@
 ///         decimal-constant integer-suffix
 ///         octal-constant integer-suffix
 ///         hexadecimal-constant integer-suffix
+///       user-defined-integer-literal: [C++11 lex.ext]
+///         decimal-literal ud-suffix
+///         octal-literal ud-suffix
+///         hexadecimal-literal ud-suffix
 ///       decimal-constant:
 ///         nonzero-digit
 ///         decimal-constant digit
@@ -372,6 +399,7 @@
   s =3D DigitsBegin =3D begin;
   saw_exponent =3D false;
   saw_period =3D false;
+  saw_ud_suffix =3D false;
   isLong =3D false;
   isUnsigned =3D false;
   isLongLong =3D false;
@@ -454,7 +482,7 @@
       continue;  // Success.
     case 'i':
     case 'I':
-      if (PP.getLangOptions().MicrosoftExt) {
+      if (PP.getLangOpts().MicrosoftExt) {
         if (isFPConstant || isLong || isLongLong) break;
=20
         // Allow i8, i16, i32, i64, and i128.
@@ -509,13 +537,20 @@
       isImaginary =3D true;
       continue;  // Success.
     }
-    // If we reached here, there was an error.
+    // If we reached here, there was an error or a ud-suffix.
     break;
   }
=20
-  // Report an error if there are any.
   if (s !=3D ThisTokEnd) {
-    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-begin),
+    if (PP.getLangOpts().CPlusPlus0x && s =3D=3D SuffixBegin && *s =3D=3D =
'_') {
+      // We have a ud-suffix! By C++11 [lex.ext]p10, ud-suffixes not start=
ing
+      // with an '_' are ill-formed.
+      saw_ud_suffix =3D true;
+      return;
+    }
+
+    // Report an error if there are any.
+    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin-begin),
             isFPConstant ? diag::err_invalid_suffix_float_constant :
                            diag::err_invalid_suffix_integer_constant)
       << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin);
@@ -539,13 +574,24 @@
     radix =3D 16;
     DigitsBegin =3D s;
     s =3D SkipHexDigits(s);
+    bool noSignificand =3D (s =3D=3D DigitsBegin);
     if (s =3D=3D ThisTokEnd) {
       // Done.
     } else if (*s =3D=3D '.') {
       s++;
       saw_period =3D true;
+      const char *floatDigitsBegin =3D s;
       s =3D SkipHexDigits(s);
+      noSignificand &=3D (floatDigitsBegin =3D=3D s);
     }
+
+    if (noSignificand) {
+      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), \
+        diag::err_hexconstant_requires_digits);
+      hadError =3D true;
+      return;
+    }
+
     // A binary exponent can appear with or with a '.'. If dotted, the
     // binary exponent is required.
     if (*s =3D=3D 'p' || *s =3D=3D 'P') {
@@ -562,7 +608,7 @@
       }
       s =3D first_non_digit;
=20
-      if (!PP.getLangOptions().HexFloats)
+      if (!PP.getLangOpts().HexFloats)
         PP.Diag(TokLoc, diag::ext_hexconstant_invalid);
     } else if (saw_period) {
       PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
@@ -710,7 +756,11 @@
 }
=20
=20
-///       character-literal: [C++0x lex.ccon]
+///       user-defined-character-literal: [C++11 lex.ext]
+///         character-literal ud-suffix
+///       ud-suffix:
+///         identifier
+///       character-literal: [C++11 lex.ccon]
 ///         ' c-char-sequence '
 ///         u' c-char-sequence '
 ///         U' c-char-sequence '
@@ -723,7 +773,7 @@
 ///           backslash \, or new-line character
 ///         escape-sequence
 ///         universal-character-name
-///       escape-sequence: [C++0x lex.ccon]
+///       escape-sequence:
 ///         simple-escape-sequence
 ///         octal-escape-sequence
 ///         hexadecimal-escape-sequence
@@ -736,7 +786,7 @@
 ///       hexadecimal-escape-sequence:
 ///         \x hexadecimal-digit
 ///         hexadecimal-escape-sequence hexadecimal-digit
-///       universal-character-name:
+///       universal-character-name: [C++11 lex.charset]
 ///         \u hex-quad
 ///         \U hex-quad hex-quad
 ///       hex-quad:
@@ -745,14 +795,15 @@
 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
                                      SourceLocation Loc, Preprocessor &PP,
                                      tok::TokenKind kind) {
-  // At this point we know that the character matches the regex "L?'.*'".
+  // At this point we know that the character matches the regex "(L|u|U)?'=
.*'".
   HadError =3D false;
=20
   Kind =3D kind;
=20
-  // Determine if this is a wide or UTF character.
-  if (Kind =3D=3D tok::wide_char_constant || Kind =3D=3D tok::utf16_char_c=
onstant ||
-      Kind =3D=3D tok::utf32_char_constant) {
+  const char *TokBegin =3D begin;
+
+  // Skip over wide character determinant.
+  if (Kind !=3D tok::char_constant) {
     ++begin;
   }
=20
@@ -760,6 +811,20 @@
   assert(begin[0] =3D=3D '\'' && "Invalid token lexed");
   ++begin;
=20
+  // Remove an optional ud-suffix.
+  if (end[-1] !=3D '\'') {
+    const char *UDSuffixEnd =3D end;
+    do {
+      --end;
+    } while (end[-1] !=3D '\'');
+    UDSuffixBuf.assign(end, UDSuffixEnd);
+    UDSuffixOffset =3D end - TokBegin;
+  }
+
+  // Trim the ending quote.
+  assert(end !=3D begin && "Invalid token lexed");
+  --end;
+
   // FIXME: The "Value" is an uint64_t so we can handle char literals of
   // up to 64-bits.
   // FIXME: This extensively assumes that 'char' is 8-bits.
@@ -771,76 +836,129 @@
   assert(PP.getTargetInfo().getWCharWidth() <=3D 64 &&
          "Assumes sizeof(wchar) on target is <=3D 64");
=20
-  // This is what we will use for overflow detection
-  llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
+  SmallVector<uint32_t,4> codepoint_buffer;
+  codepoint_buffer.resize(end-begin);
+  uint32_t *buffer_begin =3D &codepoint_buffer.front();
+  uint32_t *buffer_end =3D buffer_begin + codepoint_buffer.size();
=20
-  unsigned NumCharsSoFar =3D 0;
-  bool Warned =3D false;
-  while (begin[0] !=3D '\'') {
-    uint64_t ResultChar;
+  // Unicode escapes representing characters that cannot be correctly
+  // represented in a single code unit are disallowed in character literals
+  // by this implementation.
+  uint32_t largest_character_for_kind;
+  if (tok::wide_char_constant =3D=3D Kind) {
+    largest_character_for_kind =3D 0xFFFFFFFFu >> (32-PP.getTargetInfo().g=
etWCharWidth());
+  } else if (tok::utf16_char_constant =3D=3D Kind) {
+    largest_character_for_kind =3D 0xFFFF;
+  } else if (tok::utf32_char_constant =3D=3D Kind) {
+    largest_character_for_kind =3D 0x10FFFF;
+  } else {
+    largest_character_for_kind =3D 0x7Fu;
+  }
=20
-      // Is this a Universal Character Name escape?
-    if (begin[0] !=3D '\\')     // If this is a normal character, consume =
it.
-      ResultChar =3D (unsigned char)*begin++;
-    else {                    // Otherwise, this is an escape character.
-      unsigned CharWidth =3D getCharWidth(Kind, PP.getTargetInfo());
-      // Check for UCN.
-      if (begin[1] =3D=3D 'u' || begin[1] =3D=3D 'U') {
-        uint32_t utf32 =3D 0;
-        unsigned short UcnLen =3D 0;
-        if (!ProcessUCNEscape(begin, end, utf32, UcnLen,
-                              FullSourceLoc(Loc, PP.getSourceManager()),
-                              &PP.getDiagnostics(), PP.getLangOptions())) {
-          HadError =3D 1;
-        }
-        ResultChar =3D utf32;
-        if (CharWidth !=3D 32 && (ResultChar >> CharWidth) !=3D 0) {
-          PP.Diag(Loc, diag::warn_ucn_escape_too_large);
-          ResultChar &=3D ~0U >> (32-CharWidth);
+  while (begin!=3Dend) {
+    // Is this a span of non-escape characters?
+    if (begin[0] !=3D '\\') {
+      char const *start =3D begin;
+      do {
+        ++begin;
+      } while (begin !=3D end && *begin !=3D '\\');
+
+      char const *tmp_in_start =3D start;
+      uint32_t *tmp_out_start =3D buffer_begin;
+      ConversionResult res =3D
+      ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start),
+                         reinterpret_cast<UTF8 const *>(begin),
+                         &buffer_begin,buffer_end,strictConversion);
+      if (res!=3DconversionOK) {
+        // If we see bad encoding for unprefixed character literals, warn =
and=20
+        // simply copy the byte values, for compatibility with gcc and=20
+        // older versions of clang.
+        bool NoErrorOnBadEncoding =3D isAscii();
+        unsigned Msg =3D diag::err_bad_character_encoding;
+        if (NoErrorOnBadEncoding)
+          Msg =3D diag::warn_bad_character_encoding;
+        PP.Diag(Loc, Msg);
+        if (NoErrorOnBadEncoding) {
+          start =3D tmp_in_start;
+          buffer_begin =3D tmp_out_start;
+          for ( ; start !=3D begin; ++start, ++buffer_begin)
+            *buffer_begin =3D static_cast<uint8_t>(*start);
+        } else {
+          HadError =3D true;
         }
       } else {
-        // Otherwise, this is a non-UCN escape character.  Process it.
-        ResultChar =3D ProcessCharEscape(begin, end, HadError,
-                                       FullSourceLoc(Loc,PP.getSourceManag=
er()),
-                                       CharWidth, &PP.getDiagnostics());
+        for (; tmp_out_start <buffer_begin; ++tmp_out_start) {
+          if (*tmp_out_start > largest_character_for_kind) {
+            HadError =3D true;
+            PP.Diag(Loc, diag::err_character_too_large);
+          }
+        }
       }
+
+      continue;
     }
+    // Is this a Universal Character Name excape?
+    if (begin[1] =3D=3D 'u' || begin[1] =3D=3D 'U') {
+      unsigned short UcnLen =3D 0;
+      if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
+                            FullSourceLoc(Loc, PP.getSourceManager()),
+                            &PP.getDiagnostics(), PP.getLangOpts(),
+                            true))
+      {
+        HadError =3D true;
+      } else if (*buffer_begin > largest_character_for_kind) {
+        HadError =3D true;
+        PP.Diag(Loc,diag::err_character_too_large);
+      }
=20
-    // If this is a multi-character constant (e.g. 'abc'), handle it.  The=
se are
-    // implementation defined (C99 6.4.4.4p10).
-    if (NumCharsSoFar) {
-      if (!isAscii()) {
-        // Emulate GCC's (unintentional?) behavior: L'ab' -> L'b'.
-        LitVal =3D 0;
-      } else {
-        // Narrow character literals act as though their value is concaten=
ated
-        // in this implementation, but warn on overflow.
-        if (LitVal.countLeadingZeros() < 8 && !Warned) {
-          PP.Diag(Loc, diag::warn_char_constant_too_large);
-          Warned =3D true;
-        }
-        LitVal <<=3D 8;
-      }
+      ++buffer_begin;
+      continue;
     }
-
-    LitVal =3D LitVal + ResultChar;
-    ++NumCharsSoFar;
+    unsigned CharWidth =3D getCharWidth(Kind, PP.getTargetInfo());
+    uint64_t result =3D
+    ProcessCharEscape(begin, end, HadError,
+                      FullSourceLoc(Loc,PP.getSourceManager()),
+                      CharWidth, &PP.getDiagnostics());
+    *buffer_begin++ =3D result;
   }
=20
-  // If this is the second character being processed, do special handling.
+  unsigned NumCharsSoFar =3D buffer_begin-&codepoint_buffer.front();
+
   if (NumCharsSoFar > 1) {
-    // Warn about discarding the top bits for multi-char wide-character
-    // constants (L'abcd').
-    if (!isAscii())
+    if (isWide())
       PP.Diag(Loc, diag::warn_extraneous_char_constant);
-    else if (NumCharsSoFar !=3D 4)
+    else if (isAscii() && NumCharsSoFar =3D=3D 4)
+      PP.Diag(Loc, diag::ext_four_char_character_literal);
+    else if (isAscii())
       PP.Diag(Loc, diag::ext_multichar_character_literal);
     else
-      PP.Diag(Loc, diag::ext_four_char_character_literal);
+      PP.Diag(Loc, diag::err_multichar_utf_character_literal);
     IsMultiChar =3D true;
   } else
     IsMultiChar =3D false;
=20
+  llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
+
+  // Narrow character literals act as though their value is concatenated
+  // in this implementation, but warn on overflow.
+  bool multi_char_too_long =3D false;
+  if (isAscii() && isMultiChar()) {
+    LitVal =3D 0;
+    for (size_t i=3D0;i<NumCharsSoFar;++i) {
+      // check for enough leading zeros to shift into
+      multi_char_too_long |=3D (LitVal.countLeadingZeros() < 8);
+      LitVal <<=3D 8;
+      LitVal =3D LitVal + (codepoint_buffer[i] & 0xFF);
+    }
+  } else if (NumCharsSoFar > 0) {
+    // otherwise just take the last character
+    LitVal =3D buffer_begin[-1];
+  }
+
+  if (!HadError && multi_char_too_long) {
+    PP.Diag(Loc,diag::warn_char_constant_too_large);
+  }
+
   // Transfer the value from APInt to uint64_t
   Value =3D LitVal.getZExtValue();
=20
@@ -849,7 +967,7 @@
   // character constants are not sign extended in the this implementation:
   // '\xFF\xFF' =3D 65536 and '\x0\xFF' =3D 255, which matches GCC.
   if (isAscii() && NumCharsSoFar =3D=3D 1 && (Value & 128) &&
-      PP.getLangOptions().CharIsSigned)
+      PP.getLangOpts().CharIsSigned)
     Value =3D (signed char)Value;
 }
=20
@@ -909,7 +1027,7 @@
 StringLiteralParser::
 StringLiteralParser(const Token *StringToks, unsigned NumStringToks,
                     Preprocessor &PP, bool Complain)
-  : SM(PP.getSourceManager()), Features(PP.getLangOptions()),
+  : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
     Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() : 0),
     MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
     ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
@@ -985,7 +1103,7 @@
   ResultBuf.resize(SizeBound);
=20
   // Likewise, but for each string piece.
-  llvm::SmallString<512> TokenBuf;
+  SmallString<512> TokenBuf;
   TokenBuf.resize(MaxTokenLength);
=20
   // Loop over all the strings, getting their spelling, and expanding them=
 to
@@ -994,6 +1112,8 @@
=20
   Pascal =3D false;
=20
+  SourceLocation UDSuffixTokLoc;
+
   for (unsigned i =3D 0, e =3D NumStringToks; i !=3D e; ++i) {
     const char *ThisTokBuf =3D &TokenBuf[0];
     // Get the spelling of the token, which eliminates trigraphs, etc.  We=
 know
@@ -1008,7 +1128,42 @@
       continue;
     }
=20
-    const char *ThisTokEnd =3D ThisTokBuf+ThisTokLen-1;  // Skip end quote.
+    const char *ThisTokBegin =3D ThisTokBuf;
+    const char *ThisTokEnd =3D ThisTokBuf+ThisTokLen;
+
+    // Remove an optional ud-suffix.
+    if (ThisTokEnd[-1] !=3D '"') {
+      const char *UDSuffixEnd =3D ThisTokEnd;
+      do {
+        --ThisTokEnd;
+      } while (ThisTokEnd[-1] !=3D '"');
+
+      StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
+
+      if (UDSuffixBuf.empty()) {
+        UDSuffixBuf.assign(UDSuffix);
+        UDSuffixToken =3D i;
+        UDSuffixOffset =3D ThisTokEnd - ThisTokBuf;
+        UDSuffixTokLoc =3D StringToks[i].getLocation();
+      } else if (!UDSuffixBuf.equals(UDSuffix)) {
+        // C++11 [lex.ext]p8: At the end of phase 6, if a string literal i=
s the
+        // result of a concatenation involving at least one user-defined-s=
tring-
+        // literal, all the participating user-defined-string-literals sha=
ll
+        // have the same ud-suffix.
+        if (Diags) {
+          SourceLocation TokLoc =3D StringToks[i].getLocation();
+          Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
+            << UDSuffixBuf << UDSuffix
+            << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
+            << SourceRange(TokLoc, TokLoc);
+        }
+        hadError =3D true;
+      }
+    }
+
+    // Strip the end quote.
+    --ThisTokEnd;
+
     // TODO: Input character set mapping support.
=20
     // Skip marker for wide or unicode strings.
@@ -1028,12 +1183,14 @@
         ++ThisTokBuf;
       ++ThisTokBuf; // skip '('
=20
-      // remove same number of characters from the end
-      if (ThisTokEnd >=3D ThisTokBuf + (ThisTokBuf - Prefix))
-        ThisTokEnd -=3D (ThisTokBuf - Prefix);
+      // Remove same number of characters from the end
+      ThisTokEnd -=3D ThisTokBuf - Prefix;
+      assert(ThisTokEnd >=3D ThisTokBuf && "malformed raw string literal");
=20
       // Copy the string over
-      CopyStringFragment(StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf));
+      if (CopyStringFragment(StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf=
)))
+        if (DiagnoseBadString(StringToks[i]))
+          hadError =3D true;
     } else {
       assert(ThisTokBuf[0] =3D=3D '"' && "Expected quote, lexer broken?");
       ++ThisTokBuf; // skip "
@@ -1060,13 +1217,16 @@
           } while (ThisTokBuf !=3D ThisTokEnd && ThisTokBuf[0] !=3D '\\');
=20
           // Copy the character span over.
-          CopyStringFragment(StringRef(InStart, ThisTokBuf - InStart));
+          if (CopyStringFragment(StringRef(InStart, ThisTokBuf - InStart)))
+            if (DiagnoseBadString(StringToks[i]))
+              hadError =3D true;
           continue;
         }
         // Is this a Universal Character Name escape?
         if (ThisTokBuf[1] =3D=3D 'u' || ThisTokBuf[1] =3D=3D 'U') {
-          EncodeUCNEscape(ThisTokBuf, ThisTokEnd, ResultPtr,
-                          hadError, FullSourceLoc(StringToks[i].getLocatio=
n(),SM),
+          EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
+                          ResultPtr, hadError,
+                          FullSourceLoc(StringToks[i].getLocation(), SM),
                           CharByteWidth, Diags, Features);
           continue;
         }
@@ -1076,18 +1236,41 @@
                             FullSourceLoc(StringToks[i].getLocation(), SM),
                             CharByteWidth*8, Diags);
=20
-        // Note: our internal rep of wide char tokens is always little-end=
ian.
-        *ResultPtr++ =3D ResultChar & 0xFF;
-
-        for (unsigned i =3D 1, e =3D CharByteWidth; i !=3D e; ++i)
-          *ResultPtr++ =3D ResultChar >> i*8;
+        if (CharByteWidth =3D=3D 4) {
+          // FIXME: Make the type of the result buffer correct instead of
+          // using reinterpret_cast.
+          UTF32 *ResultWidePtr =3D reinterpret_cast<UTF32*>(ResultPtr);
+          *ResultWidePtr =3D ResultChar;
+          ResultPtr +=3D 4;
+        } else if (CharByteWidth =3D=3D 2) {
+          // FIXME: Make the type of the result buffer correct instead of
+          // using reinterpret_cast.
+          UTF16 *ResultWidePtr =3D reinterpret_cast<UTF16*>(ResultPtr);
+          *ResultWidePtr =3D ResultChar & 0xFFFF;
+          ResultPtr +=3D 2;
+        } else {
+          assert(CharByteWidth =3D=3D 1 && "Unexpected char width");
+          *ResultPtr++ =3D ResultChar & 0xFF;
+        }
       }
     }
   }
=20
   if (Pascal) {
-    ResultBuf[0] =3D ResultPtr-&ResultBuf[0]-1;
-    ResultBuf[0] /=3D CharByteWidth;
+    if (CharByteWidth =3D=3D 4) {
+      // FIXME: Make the type of the result buffer correct instead of
+      // using reinterpret_cast.
+      UTF32 *ResultWidePtr =3D reinterpret_cast<UTF32*>(ResultBuf.data());
+      ResultWidePtr[0] =3D GetNumStringChars() - 1;
+    } else if (CharByteWidth =3D=3D 2) {
+      // FIXME: Make the type of the result buffer correct instead of
+      // using reinterpret_cast.
+      UTF16 *ResultWidePtr =3D reinterpret_cast<UTF16*>(ResultBuf.data());
+      ResultWidePtr[0] =3D GetNumStringChars() - 1;
+    } else {
+      assert(CharByteWidth =3D=3D 1 && "Unexpected char width");
+      ResultBuf[0] =3D GetNumStringChars() - 1;
+    }
=20
     // Verify that pascal strings aren't too large.
     if (GetStringLength() > 256) {
@@ -1116,22 +1299,55 @@
=20
 /// copyStringFragment - This function copies from Start to End into Resul=
tPtr.
 /// Performs widening for multi-byte characters.
-void StringLiteralParser::CopyStringFragment(StringRef Fragment) {
+bool StringLiteralParser::CopyStringFragment(StringRef Fragment) {
+  assert(CharByteWidth=3D=3D1 || CharByteWidth=3D=3D2 || CharByteWidth=3D=
=3D4);
+  ConversionResult result =3D conversionOK;
   // Copy the character span over.
   if (CharByteWidth =3D=3D 1) {
+    if (!isLegalUTF8String(reinterpret_cast<const UTF8*>(Fragment.begin()),
+                           reinterpret_cast<const UTF8*>(Fragment.end())))
+      result =3D sourceIllegal;
     memcpy(ResultPtr, Fragment.data(), Fragment.size());
     ResultPtr +=3D Fragment.size();
-  } else {
-    // Note: our internal rep of wide char tokens is always little-endian.
-    for (StringRef::iterator I=3DFragment.begin(), E=3DFragment.end(); I!=
=3DE; ++I) {
-      *ResultPtr++ =3D *I;
-      // Add zeros at the end.
-      for (unsigned i =3D 1, e =3D CharByteWidth; i !=3D e; ++i)
-        *ResultPtr++ =3D 0;
-    }
+  } else if (CharByteWidth =3D=3D 2) {
+    UTF8 const *sourceStart =3D (UTF8 const *)Fragment.data();
+    // FIXME: Make the type of the result buffer correct instead of
+    // using reinterpret_cast.
+    UTF16 *targetStart =3D reinterpret_cast<UTF16*>(ResultPtr);
+    ConversionFlags flags =3D strictConversion;
+    result =3D ConvertUTF8toUTF16(
+	    &sourceStart,sourceStart + Fragment.size(),
+        &targetStart,targetStart + 2*Fragment.size(),flags);
+    if (result=3D=3DconversionOK)
+      ResultPtr =3D reinterpret_cast<char*>(targetStart);
+  } else if (CharByteWidth =3D=3D 4) {
+    UTF8 const *sourceStart =3D (UTF8 const *)Fragment.data();
+    // FIXME: Make the type of the result buffer correct instead of
+    // using reinterpret_cast.
+    UTF32 *targetStart =3D reinterpret_cast<UTF32*>(ResultPtr);
+    ConversionFlags flags =3D strictConversion;
+    result =3D ConvertUTF8toUTF32(
+        &sourceStart,sourceStart + Fragment.size(),
+        &targetStart,targetStart + 4*Fragment.size(),flags);
+    if (result=3D=3DconversionOK)
+      ResultPtr =3D reinterpret_cast<char*>(targetStart);
   }
+  assert((result !=3D targetExhausted)
+         && "ConvertUTF8toUTFXX exhausted target buffer");
+  return result !=3D conversionOK;
 }
=20
+bool StringLiteralParser::DiagnoseBadString(const Token &Tok) {
+  // If we see bad encoding for unprefixed string literals, warn and
+  // simply copy the byte values, for compatibility with gcc and older
+  // versions of clang.
+  bool NoErrorOnBadEncoding =3D isAscii();
+  unsigned Msg =3D NoErrorOnBadEncoding ? diag::warn_bad_string_encoding :
+                                        diag::err_bad_string_encoding;
+  if (Diags)
+    Diags->Report(FullSourceLoc(Tok.getLocation(), SM), Msg);
+  return !NoErrorOnBadEncoding;
+}
=20
 /// getOffsetOfStringByte - This function returns the offset of the
 /// specified byte of the string data represented by Token.  This handles
@@ -1139,7 +1355,7 @@
 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
                                                     unsigned ByteNo) const=
 {
   // Get the spelling of the token.
-  llvm::SmallString<32> SpellingBuffer;
+  SmallString<32> SpellingBuffer;
   SpellingBuffer.resize(Tok.getLength());
=20
   bool StringInvalid =3D false;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
MacroArgs.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/MacroArgs.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/MacroArgs.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,7 +15,8 @@
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/LexDiagnostic.h"
-
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include <algorithm>
=20
 using namespace clang;
@@ -155,6 +156,8 @@
   std::vector<Token> &Result =3D PreExpArgTokens[Arg];
   if (!Result.empty()) return Result;
=20
+  SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, tr=
ue);
+
   const Token *AT =3D getUnexpArgument(Arg);
   unsigned NumToks =3D getArgLength(AT)+1;  // Include the EOF.
=20
@@ -177,6 +180,8 @@
   // will not otherwise be popped until the next token is lexed.  The prob=
lem is
   // that the token may be lexed sometime after the vector of tokens itsel=
f is
   // destroyed, which would be badness.
+  if (PP.InCachingLexMode())
+    PP.ExitCachingLexMode();
   PP.RemoveTopOfLexerStack();
   return Result;
 }
@@ -198,7 +203,7 @@
   const Token *ArgTokStart =3D ArgToks;
=20
   // Stringify all the tokens.
-  llvm::SmallString<128> Result;
+  SmallString<128> Result;
   Result +=3D "\"";
=20
   bool isFirst =3D true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
MacroInfo.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/MacroInfo.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -27,7 +27,8 @@
   IsAllowRedefinitionsWithoutWarning =3D false;
   IsWarnIfUnused =3D false;
   IsDefinitionLengthCached =3D false;
-
+  IsPublic =3D true;
+ =20
   ArgumentList =3D 0;
   NumArguments =3D 0;
 }
@@ -48,6 +49,8 @@
   IsWarnIfUnused =3D MI.IsWarnIfUnused;
   IsDefinitionLengthCached =3D MI.IsDefinitionLengthCached;
   DefinitionLength =3D MI.DefinitionLength;
+  IsPublic =3D MI.IsPublic;
+ =20
   ArgumentList =3D 0;
   NumArguments =3D 0;
   setArgumentList(MI.ArgumentList, MI.NumArguments, PPAllocator);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PPCaching.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PPCaching.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PPCaching.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -42,6 +42,7 @@
          && "EnableBacktrackAtThisPos was not called!");
   CachedLexPos =3D BacktrackPositions.back();
   BacktrackPositions.pop_back();
+  recomputeCurLexerKind();
 }
=20
 void Preprocessor::CachingLex(Token &Result) {
@@ -56,17 +57,21 @@
   ExitCachingLexMode();
   Lex(Result);
=20
-  if (!isBacktrackEnabled()) {
+  if (isBacktrackEnabled()) {
+    // Cache the lexed token.
+    EnterCachingLexMode();
+    CachedTokens.push_back(Result);
+    ++CachedLexPos;
+    return;
+  }
+
+  if (CachedLexPos < CachedTokens.size()) {
+    EnterCachingLexMode();
+  } else {
     // All cached tokens were consumed.
     CachedTokens.clear();
     CachedLexPos =3D 0;
-    return;
   }
-
-  // Cache the lexed token.
-  EnterCachingLexMode();
-  CachedTokens.push_back(Result);
-  ++CachedLexPos;
 }
=20
 void Preprocessor::EnterCachingLexMode() {
@@ -74,8 +79,7 @@
     return;
=20
   PushIncludeMacroStack();
-  if (CurLexerKind !=3D CLK_LexAfterModuleImport)
-    CurLexerKind =3D CLK_CachingLexer;
+  CurLexerKind =3D CLK_CachingLexer;
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PPDirectives.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PPDirectives.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -22,6 +22,7 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/APInt.h"
+#include "llvm/Support/ErrorHandling.h"
 using namespace clang;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -119,8 +120,15 @@
     std::string Spelling =3D getSpelling(MacroNameTok, &Invalid);
     if (Invalid)
       return;
-   =20
+
     const IdentifierInfo &Info =3D Identifiers.get(Spelling);
+
+    // Allow #defining |and| and friends in microsoft mode.
+    if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
+      MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
+      return;
+    }
+
     if (Info.isCPlusPlusOperatorKeyword())
       // C++ 2.5p2: Alternative tokens behave the same as its primary token
       // except for their spellings.
@@ -173,7 +181,7 @@
     // trouble than it is worth to insert /**/ and check that there is no =
/**/
     // in the range also.
     FixItHint Hint;
-    if ((Features.GNUMode || Features.C99 || Features.CPlusPlus) &&
+    if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
         !CurTokenLexer)
       Hint =3D FixItHint::CreateInsertion(Tmp.getLocation(),"//");
     Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
@@ -305,9 +313,6 @@
         CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*=
/true,
                                        /*foundnonskip*/false,
                                        /*foundelse*/false);
-
-        if (Callbacks)
-          Callbacks->Endif();
       }
     } else if (Directive[0] =3D=3D 'e') {
       StringRef Sub =3D Directive.substr(1);
@@ -320,8 +325,11 @@
         assert(!InCond && "Can't be skipping if not in a conditional!");
=20
         // If we popped the outermost skipping block, we're done skipping!
-        if (!CondInfo.WasSkipping)
+        if (!CondInfo.WasSkipping) {
+          if (Callbacks)
+            Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
           break;
+        }
       } else if (Sub =3D=3D "lse") { // "else".
         // #else directive in a skipping conditional.  If not in some other
         // skipping conditional, and if #else hasn't already been seen, en=
ter it
@@ -334,14 +342,13 @@
         // Note that we've seen a #else in this conditional.
         CondInfo.FoundElse =3D true;
=20
-        if (Callbacks)
-          Callbacks->Else();
-
         // If the conditional is at the top level, and the #if block wasn't
         // entered, enter the #else block now.
         if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
           CondInfo.FoundNonSkip =3D true;
           CheckEndOfDirective("else");
+          if (Callbacks)
+            Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
           break;
         } else {
           DiscardUntilEndOfDirective();  // C99 6.10p4.
@@ -370,12 +377,13 @@
         // If this is a #elif with a #else before it, report the error.
         if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
=20
-        if (Callbacks)
-          Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
-
         // If this condition is true, enter it!
         if (ShouldEnter) {
           CondInfo.FoundNonSkip =3D true;
+          if (Callbacks)
+            Callbacks->Elif(Tok.getLocation(),
+                            SourceRange(ConditionalBegin, ConditionalEnd),
+                            CondInfo.IfLoc);
           break;
         }
       }
@@ -486,7 +494,8 @@
     const DirectoryLookup *&CurDir,
     SmallVectorImpl<char> *SearchPath,
     SmallVectorImpl<char> *RelativePath,
-    StringRef *SuggestedModule) {
+    Module **SuggestedModule,
+    bool SkipCache) {
   // If the header lookup mechanism may be relative to the current file, p=
ass in
   // info about where the current file is.
   const FileEntry *CurFileEnt =3D 0;
@@ -510,7 +519,7 @@
   CurDir =3D CurDirLookup;
   const FileEntry *FE =3D HeaderInfo.LookupFile(
       Filename, isAngled, FromDir, CurDir, CurFileEnt,
-      SearchPath, RelativePath, SuggestedModule);
+      SearchPath, RelativePath, SuggestedModule, SkipCache);
   if (FE) return FE;
=20
   // Otherwise, see if this is a subframework header.  If so, this is rela=
tive
@@ -575,9 +584,25 @@
   //   A(abc
   //     #warning blah
   //   def)
-  // If so, the user is relying on non-portable behavior, emit a diagnosti=
c.
-  if (InMacroArgs)
+  // If so, the user is relying on undefined behavior, emit a diagnostic. =
Do
+  // not support this for #include-like directives, since that can result =
in
+  // terrible diagnostics, and does not work in GCC.
+  if (InMacroArgs) {
+    if (IdentifierInfo *II =3D Result.getIdentifierInfo()) {
+      switch (II->getPPKeywordID()) {
+      case tok::pp_include:
+      case tok::pp_import:
+      case tok::pp_include_next:
+      case tok::pp___include_macros:
+        Diag(Result, diag::err_embedded_include) << II->getName();
+        DiscardUntilEndOfDirective();
+        return;
+      default:
+        break;
+      }
+    }
     Diag(Result, diag::ext_embedded_directive);
+  }
=20
 TryAgain:
   switch (Result.getKind()) {
@@ -594,7 +619,7 @@
     setCodeCompletionReached();
     return;
   case tok::numeric_constant:  // # 7  GNU line marker directive.
-    if (getLangOptions().AsmPreprocessor)
+    if (getLangOpts().AsmPreprocessor)
       break;  // # 4 is not a preprocessor directive in .S files.
     return HandleDigitDirective(Result);
   default:
@@ -664,8 +689,15 @@
       //isExtension =3D true;  // FIXME: implement #unassert
       break;
        =20
-    case tok::pp___export_macro__:
-      return HandleMacroExportDirective(Result);
+    case tok::pp___public_macro:
+      if (getLangOpts().Modules)
+        return HandleMacroPublicDirective(Result);
+      break;
+       =20
+    case tok::pp___private_macro:
+      if (getLangOpts().Modules)
+        return HandleMacroPrivateDirective(Result);
+      break;
     }
     break;
   }
@@ -674,7 +706,7 @@
   // directives.  This is important because # may be a comment or introduce
   // various pseudo-ops.  Just return the # token and push back the follow=
ing
   // token to be lexed next time.
-  if (getLangOptions().AsmPreprocessor) {
+  if (getLangOpts().AsmPreprocessor) {
     Token *Toks =3D new Token[2];
     // Return the # and the token after it.
     Toks[0] =3D SavedHash;
@@ -713,7 +745,7 @@
     return true;
   }
=20
-  llvm::SmallString<64> IntegerBuffer;
+  SmallString<64> IntegerBuffer;
   IntegerBuffer.resize(DigitTok.getLength());
   const char *DigitTokBegin =3D &IntegerBuffer[0];
   bool Invalid =3D false;
@@ -773,11 +805,11 @@
   // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
   // number greater than 2147483647".  C90 requires that the line # be <=
=3D 32767.
   unsigned LineLimit =3D 32768U;
-  if (Features.C99 || Features.CPlusPlus0x)
+  if (LangOpts.C99 || LangOpts.CPlusPlus0x)
     LineLimit =3D 2147483648U;
   if (LineNo >=3D LineLimit)
     Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
-  else if (Features.CPlusPlus0x && LineNo >=3D 32768U)
+  else if (LangOpts.CPlusPlus0x && LineNo >=3D 32768U)
     Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
=20
   int FilenameID =3D -1;
@@ -790,8 +822,10 @@
     ; // ok
   else if (StrTok.isNot(tok::string_literal)) {
     Diag(StrTok, diag::err_pp_line_invalid_filename);
-    DiscardUntilEndOfDirective();
-    return;
+    return DiscardUntilEndOfDirective();
+  } else if (StrTok.hasUDSuffix()) {
+    Diag(StrTok, diag::err_invalid_string_udl);
+    return DiscardUntilEndOfDirective();
   } else {
     // Parse and validate the string, converting it into a unique ID.
     StringLiteralParser Literal(&StrTok, 1, *this);
@@ -925,6 +959,9 @@
   else if (StrTok.isNot(tok::string_literal)) {
     Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
     return DiscardUntilEndOfDirective();
+  } else if (StrTok.hasUDSuffix()) {
+    Diag(StrTok, diag::err_invalid_string_udl);
+    return DiscardUntilEndOfDirective();
   } else {
     // Parse and validate the string, converting it into a unique ID.
     StringLiteralParser Literal(&StrTok, 1, *this);
@@ -982,10 +1019,18 @@
   // collapse multiple consequtive white space between tokens, but this is=
n't
   // specified by the standard.
   std::string Message =3D CurLexer->ReadToEndOfLine();
+
+  // Find the first non-whitespace character, so that we can make the
+  // diagnostic more succinct.
+  StringRef Msg(Message);
+  size_t i =3D Msg.find_first_not_of(' ');
+  if (i < Msg.size())
+    Msg =3D Msg.substr(i);
+ =20
   if (isWarning)
-    Diag(Tok, diag::pp_hash_warning) << Message;
+    Diag(Tok, diag::pp_hash_warning) << Msg;
   else
-    Diag(Tok, diag::err_pp_hash_error) << Message;
+    Diag(Tok, diag::err_pp_hash_error) << Msg;
 }
=20
 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
@@ -1007,6 +1052,11 @@
     return;
   }
=20
+  if (StrTok.hasUDSuffix()) {
+    Diag(StrTok, diag::err_invalid_string_udl);
+    return DiscardUntilEndOfDirective();
+  }
+
   // Verify that there is nothing after the string, other than EOD.
   CheckEndOfDirective("ident");
=20
@@ -1018,8 +1068,8 @@
   }
 }
=20
-/// \brief Handle a #__export_macro__ directive.
-void Preprocessor::HandleMacroExportDirective(Token &Tok) {
+/// \brief Handle a #public directive.
+void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
   Token MacroNameTok;
   ReadMacroName(MacroNameTok, 2);
  =20
@@ -1027,21 +1077,52 @@
   if (MacroNameTok.is(tok::eod))
     return;
=20
-  // Check to see if this is the last token on the #__export_macro__ line.
-  CheckEndOfDirective("__export_macro__");
+  // Check to see if this is the last token on the #__public_macro line.
+  CheckEndOfDirective("__public_macro");
=20
   // Okay, we finally have a valid identifier to undef.
   MacroInfo *MI =3D getMacroInfo(MacroNameTok.getIdentifierInfo());
  =20
   // If the macro is not defined, this is an error.
   if (MI =3D=3D 0) {
-    Diag(MacroNameTok, diag::err_pp_export_non_macro)
+    Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
       << MacroNameTok.getIdentifierInfo();
     return;
   }
  =20
   // Note that this macro has now been exported.
-  MI->setExportLocation(MacroNameTok.getLocation());
+  MI->setVisibility(/*IsPublic=3D*/true, MacroNameTok.getLocation());
+ =20
+  // If this macro definition came from a PCH file, mark it
+  // as having changed since serialization.
+  if (MI->isFromAST())
+    MI->setChangedAfterLoad();
+}
+
+/// \brief Handle a #private directive.
+void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
+  Token MacroNameTok;
+  ReadMacroName(MacroNameTok, 2);
+ =20
+  // Error reading macro name?  If so, diagnostic already issued.
+  if (MacroNameTok.is(tok::eod))
+    return;
+ =20
+  // Check to see if this is the last token on the #__private_macro line.
+  CheckEndOfDirective("__private_macro");
+ =20
+  // Okay, we finally have a valid identifier to undef.
+  MacroInfo *MI =3D getMacroInfo(MacroNameTok.getIdentifierInfo());
+ =20
+  // If the macro is not defined, this is an error.
+  if (MI =3D=3D 0) {
+    Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
+      << MacroNameTok.getIdentifierInfo();
+    return;
+  }
+ =20
+  // Note that this macro has now been marked private.
+  MI->setVisibility(/*IsPublic=3D*/false, MacroNameTok.getLocation());
  =20
   // If this macro definition came from a PCH file, mark it
   // as having changed since serialization.
@@ -1109,7 +1190,7 @@
 /// false if the > was found, otherwise it returns true if it finds and co=
nsumes
 /// the EOD marker.
 bool Preprocessor::ConcatenateIncludeName(
-                                        llvm::SmallString<128> &FilenameBu=
ffer,
+                                        SmallString<128> &FilenameBuffer,
                                           SourceLocation &End) {
   Token CurTok;
=20
@@ -1171,9 +1252,10 @@
   CurPPLexer->LexIncludeFilename(FilenameTok);
=20
   // Reserve a buffer to get the spelling.
-  llvm::SmallString<128> FilenameBuffer;
+  SmallString<128> FilenameBuffer;
   StringRef Filename;
   SourceLocation End;
+  SourceLocation CharEnd; // the end of this directive, in characters
  =20
   switch (FilenameTok.getKind()) {
   case tok::eod:
@@ -1184,6 +1266,7 @@
   case tok::string_literal:
     Filename =3D getSpelling(FilenameTok, FilenameBuffer);
     End =3D FilenameTok.getLocation();
+    CharEnd =3D End.getLocWithOffset(Filename.size());
     break;
=20
   case tok::less:
@@ -1193,6 +1276,7 @@
     if (ConcatenateIncludeName(FilenameBuffer, End))
       return;   // Found <eod> but no ">"?  Diagnostic already emitted.
     Filename =3D FilenameBuffer.str();
+    CharEnd =3D getLocForEndOfToken(End);
     break;
   default:
     Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
@@ -1200,6 +1284,7 @@
     return;
   }
=20
+  StringRef OriginalFilename =3D Filename;
   bool isAngled =3D
     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
@@ -1230,38 +1315,128 @@
     PragmaARCCFCodeAuditedLoc =3D SourceLocation();
   }
=20
+  if (HeaderInfo.HasIncludeAliasMap()) {
+    // Map the filename with the brackets still attached.  If the name doe=
sn't=20
+    // map to anything, fall back on the filename we've already gotten the=20
+    // spelling for.
+    StringRef NewName =3D HeaderInfo.MapHeaderToIncludeAlias(OriginalFilen=
ame);
+    if (!NewName.empty())
+      Filename =3D NewName;
+  }
+
   // Search include directories.
   const DirectoryLookup *CurDir;
-  llvm::SmallString<1024> SearchPath;
-  llvm::SmallString<1024> RelativePath;
+  SmallString<1024> SearchPath;
+  SmallString<1024> RelativePath;
   // We get the raw path only if we have 'Callbacks' to which we later pass
   // the path.
-  StringRef SuggestedModule;
+  Module *SuggestedModule =3D 0;
   const FileEntry *File =3D LookupFile(
       Filename, isAngled, LookupFrom, CurDir,
       Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
-      AutoModuleImport? &SuggestedModule : 0);
+      getLangOpts().Modules? &SuggestedModule : 0);
=20
-  // If we are supposed to import a module rather than including the heade=
r,
-  // do so now.
-  if (!SuggestedModule.empty()) {
-    TheModuleLoader.loadModule(IncludeTok.getLocation(),
-                               Identifiers.get(SuggestedModule),
-                               FilenameTok.getLocation());
-    return;
+  if (Callbacks) {
+    if (!File) {
+      // Give the clients a chance to recover.
+      SmallString<128> RecoveryPath;
+      if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
+        if (const DirectoryEntry *DE =3D FileMgr.getDirectory(RecoveryPath=
)) {
+          // Add the recovery path to the list of search paths.
+          DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
+          HeaderInfo.AddSearchPath(DL, isAngled);
+         =20
+          // Try the lookup again, skipping the cache.
+          File =3D LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
+                            getLangOpts().Modules? &SuggestedModule : 0,
+                            /*SkipCache*/true);
+        }
+      }
+    }
+   =20
+    // Notify the callback object that we've seen an inclusion directive.
+    Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,=
 File,
+                                  End, SearchPath, RelativePath);
   }
  =20
-  // Notify the callback object that we've seen an inclusion directive.
-  if (Callbacks)
-    Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled,=
 File,
-                                  End, SearchPath, RelativePath);
-
   if (File =3D=3D 0) {
     if (!SuppressIncludeNotFoundError)
       Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
     return;
   }
=20
+  // If we are supposed to import a module rather than including the heade=
r,
+  // do so now.
+  if (SuggestedModule) {
+    // Compute the module access path corresponding to this module.
+    // FIXME: Should we have a second loadModule() overload to avoid this
+    // extra lookup step?
+    llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
+    for (Module *Mod =3D SuggestedModule; Mod; Mod =3D Mod->Parent)
+      Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
+                                    FilenameTok.getLocation()));
+    std::reverse(Path.begin(), Path.end());
+
+    // Warn that we're replacing the include/import with a module import.
+    SmallString<128> PathString;
+    for (unsigned I =3D 0, N =3D Path.size(); I !=3D N; ++I) {
+      if (I)
+        PathString +=3D '.';
+      PathString +=3D Path[I].first->getName();
+    }
+    int IncludeKind =3D 0;
+   =20
+    switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
+    case tok::pp_include:
+      IncludeKind =3D 0;
+      break;
+     =20
+    case tok::pp_import:
+      IncludeKind =3D 1;
+      break;       =20
+       =20
+    case tok::pp_include_next:
+      IncludeKind =3D 2;
+      break;
+       =20
+    case tok::pp___include_macros:
+      IncludeKind =3D 3;
+      break;
+       =20
+    default:
+      llvm_unreachable("unknown include directive kind");
+    }
+
+    // Determine whether we are actually building the module that this
+    // include directive maps to.
+    bool BuildingImportedModule
+      =3D Path[0].first->getName() =3D=3D getLangOpts().CurrentModule;
+   =20
+    if (!BuildingImportedModule && getLangOpts().ObjC2) {
+      // If we're not building the imported module, warn that we're going
+      // to automatically turn this inclusion directive into a module impo=
rt.
+      // We only do this in Objective-C, where we have a module-import syn=
tax.
+      CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),=20
+                                   /*IsTokenRange=3D*/false);
+      Diag(HashLoc, diag::warn_auto_module_import)
+        << IncludeKind << PathString=20
+        << FixItHint::CreateReplacement(ReplaceRange,
+             "@__experimental_modules_import " + PathString.str().str() + =
";");
+    }
+   =20
+    // Load the module.
+    // If this was an #__include_macros directive, only make macros visibl=
e.
+    Module::NameVisibilityKind Visibility=20
+      =3D (IncludeKind =3D=3D 3)? Module::MacrosVisible : Module::AllVisib=
le;
+    Module *Imported
+      =3D TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visib=
ility,
+                                   /*IsIncludeDirective=3D*/true);
+   =20
+    // If this header isn't part of the module we're building, we're done.
+    if (!BuildingImportedModule && Imported)
+      return;
+  }
+ =20
   // The #included file will be considered to be a system header if either=
 it is
   // in a system include directory, or if the #includer is a system include
   // header.
@@ -1278,8 +1453,12 @@
   }
=20
   // Look up the file, create a File ID for it.
-  FileID FID =3D SourceMgr.createFileID(File, FilenameTok.getLocation(),
-                                      FileCharacter);
+  SourceLocation IncludePos =3D End;
+  // If the filename string was the result of macro expansions, set the in=
clude
+  // position on the file where it will be included and after the expansio=
ns.
+  if (IncludePos.isMacroID())
+    IncludePos =3D SourceMgr.getExpansionRange(IncludePos).second;
+  FileID FID =3D SourceMgr.createFileID(File, IncludePos, FileCharacter);
   assert(!FID.isInvalid() && "Expected valid file ID");
=20
   // Finally, if all is good, enter the new file!
@@ -1309,13 +1488,29 @@
   return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
 }
=20
+/// HandleMicrosoftImportDirective - Implements #import for Microsoft Mode
+void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
+  // The Microsoft #import directive takes a type library and generates he=
ader
+  // files from it, and includes those.  This is beyond the scope of what =
clang
+  // does, so we ignore it and error out.  However, #import can optionally=
 have
+  // trailing attributes that span multiple lines.  We're going to eat tho=
se
+  // so we can continue processing from there.
+  Diag(Tok, diag::err_pp_import_directive_ms );
+
+  // Read tokens until we get to the end of the directive.  Note that the=20
+  // directive can be split over multiple lines using the backslash charac=
ter.
+  DiscardUntilEndOfDirective();
+}
+
 /// HandleImportDirective - Implements #import.
 ///
 void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
                                          Token &ImportTok) {
-  if (!Features.ObjC1)  // #import is standard for ObjC.
+  if (!LangOpts.ObjC1) {  // #import is standard for ObjC.
+    if (LangOpts.MicrosoftMode)
+      return HandleMicrosoftImportDirective(ImportTok);
     Diag(ImportTok, diag::ext_pp_import_directive);
-
+  }
   return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
 }
=20
@@ -1354,10 +1549,9 @@
 /// definition has just been read.  Lex the rest of the arguments and the
 /// closing ), updating MI with what we learn.  Return true if an error oc=
curs
 /// parsing the arg list.
-bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
+bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
   SmallVector<IdentifierInfo*, 32> Arguments;
=20
-  Token Tok;
   while (1) {
     LexUnexpandedToken(Tok);
     switch (Tok.getKind()) {
@@ -1369,8 +1563,8 @@
       Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
       return true;
     case tok::ellipsis:  // #define X(... -> C99 varargs
-      if (!Features.C99)
-        Diag(Tok, Features.CPlusPlus0x ?=20
+      if (!LangOpts.C99)
+        Diag(Tok, LangOpts.CPlusPlus0x ?=20
              diag::warn_cxx98_compat_variadic_macro :
              diag::ext_variadic_macro);
=20
@@ -1476,7 +1670,7 @@
   } else if (Tok.is(tok::l_paren)) {
     // This is a function-like macro definition.  Read the argument list.
     MI->setIsFunctionLike();
-    if (ReadMacroDefinitionArgList(MI)) {
+    if (ReadMacroDefinitionArgList(MI, LastTok)) {
       // Forget about MI.
       ReleaseMacroInfo(MI);
       // Throw away the rest of the line.
@@ -1496,7 +1690,7 @@
=20
     // Read the first token after the arg list for down below.
     LexUnexpandedToken(Tok);
-  } else if (Features.C99 || Features.CPlusPlus0x) {
+  } else if (LangOpts.C99 || LangOpts.CPlusPlus0x) {
     // C99 requires whitespace between the macro definition and the body. =
 Emit
     // a diagnostic for something like "#define X+".
     Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
@@ -1561,7 +1755,7 @@
         // the '#' because '#' is often a comment character.  However, cha=
nge
         // the kind of the token to tok::unknown so that the preprocessor =
isn't
         // confused.
-        if (getLangOptions().AsmPreprocessor && Tok.isNot(tok::eod)) {
+        if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
           LastTok.setKind(tok::unknown);
         } else {
           Diag(Tok, diag::err_pp_stringize_not_parameter);
@@ -1732,6 +1926,13 @@
   if (MI)  // Mark it used.
     markMacroAsUsed(MI);
=20
+  if (Callbacks) {
+    if (isIfndef)
+      Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok);
+    else
+      Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok);
+  }
+
   // Should we include the stuff contained by this directive?
   if (!MI =3D=3D isIfndef) {
     // Yes, remember that we are inside a conditional, then lex the next t=
oken.
@@ -1744,13 +1945,6 @@
                                  /*Foundnonskip*/false,
                                  /*FoundElse*/false);
   }
-
-  if (Callbacks) {
-    if (isIfndef)
-      Callbacks->Ifndef(MacroNameTok);
-    else
-      Callbacks->Ifdef(MacroNameTok);
-  }
 }
=20
 /// HandleIfDirective - Implements the #if directive.
@@ -1774,6 +1968,10 @@
       CurPPLexer->MIOpt.EnterTopLevelConditional();
   }
=20
+  if (Callbacks)
+    Callbacks->If(IfToken.getLocation(),
+                  SourceRange(ConditionalBegin, ConditionalEnd));
+
   // Should we include the stuff contained by this directive?
   if (ConditionalTrue) {
     // Yes, remember that we are inside a conditional, then lex the next t=
oken.
@@ -1784,9 +1982,6 @@
     SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/fa=
lse,
                                  /*FoundElse*/false);
   }
-
-  if (Callbacks)
-    Callbacks->If(SourceRange(ConditionalBegin, ConditionalEnd));
 }
=20
 /// HandleEndifDirective - Implements the #endif directive.
@@ -1812,7 +2007,7 @@
          "This code should only be reachable in the non-skipping case!");
=20
   if (Callbacks)
-    Callbacks->Endif();
+    Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
 }
=20
 /// HandleElseDirective - Implements the #else directive.
@@ -1836,12 +2031,12 @@
   // If this is a #else with a #else before it, report the error.
   if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
=20
+  if (Callbacks)
+    Callbacks->Else(Result.getLocation(), CI.IfLoc);
+
   // Finally, skip the rest of the contents of this block.
   SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
                                /*FoundElse*/true, Result.getLocation());
-
-  if (Callbacks)
-    Callbacks->Else();
 }
=20
 /// HandleElifDirective - Implements the #elif directive.
@@ -1868,12 +2063,13 @@
=20
   // If this is a #elif with a #else before it, report the error.
   if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
+ =20
+  if (Callbacks)
+    Callbacks->Elif(ElifToken.getLocation(),
+                    SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLo=
c);
=20
   // Finally, skip the rest of the contents of this block.
   SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
                                /*FoundElse*/CI.FoundElse,
                                ElifToken.getLocation());
-
-  if (Callbacks)
-    Callbacks->Elif(SourceRange(ConditionalBegin, ConditionalEnd));
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PPExpressions.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PPExpressions.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PPExpressions.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -197,7 +197,7 @@
     PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
     return true;
   case tok::numeric_constant: {
-    llvm::SmallString<64> IntegerBuffer;
+    SmallString<64> IntegerBuffer;
     bool NumberInvalid =3D false;
     StringRef Spelling =3D PP.getSpelling(PeekTok, IntegerBuffer,=20
                                               &NumberInvalid);
@@ -215,9 +215,13 @@
     }
     assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
=20
+    // Complain about, and drop, any ud-suffix.
+    if (Literal.hasUDSuffix())
+      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
+
     // long long is a C99 feature.
-    if (!PP.getLangOptions().C99 && Literal.isLongLong)
-      PP.Diag(PeekTok, PP.getLangOptions().CPlusPlus0x ?
+    if (!PP.getLangOpts().C99 && Literal.isLongLong)
+      PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus0x ?
               diag::warn_cxx98_compat_longlong : diag::ext_longlong);
=20
     // Parse the integer literal into Result.
@@ -251,7 +255,11 @@
   case tok::wide_char_constant: {   // L'x'
   case tok::utf16_char_constant:    // u'x'
   case tok::utf32_char_constant:    // U'x'
-    llvm::SmallString<32> CharBuffer;
+    // Complain about, and drop, any ud-suffix.
+    if (PeekTok.hasUDSuffix())
+      PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
+
+    SmallString<32> CharBuffer;
     bool CharInvalid =3D false;
     StringRef ThisTok =3D PP.getSpelling(PeekTok, CharBuffer, &CharInvalid=
);
     if (CharInvalid)
@@ -282,7 +290,7 @@
     Val =3D Literal.getValue();
     // Set the signedness. UTF-16 and UTF-32 are always unsigned
     if (!Literal.isUTF16() && !Literal.isUTF32())
-      Val.setIsUnsigned(!PP.getLangOptions().CharIsSigned);
+      Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
=20
     if (Result.Val.getBitWidth() > Val.getBitWidth()) {
       Result.Val =3D Val.extend(Result.Val.getBitWidth());
@@ -646,7 +654,7 @@
     case tok::comma:
       // Comma is invalid in pp expressions in c89/c++ mode, but is valid =
in C99
       // if not being evaluated.
-      if (!PP.getLangOptions().C99 || ValueLive)
+      if (!PP.getLangOpts().C99 || ValueLive)
         PP.Diag(OpLoc, diag::ext_pp_comma_expr)
           << LHS.getRange() << RHS.getRange();
       Res =3D RHS.Val; // LHS =3D LHS,RHS -> RHS.
@@ -703,8 +711,6 @@
     LHS.Val =3D Res;
     LHS.setEnd(RHS.getRange().getEnd());
   }
-
-  return false;
 }
=20
 /// EvaluateDirectiveExpression - Evaluate an integer constant expression =
that
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PPLexerChange.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PPLexerChange.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PPLexerChange.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -16,8 +16,12 @@
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/LexDiagnostic.h"
+#include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
+#include "llvm/Support/FileSystem.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/PathV2.h"
+#include "llvm/ADT/StringSwitch.h"
 using namespace clang;
=20
 PPCallbacks::~PPCallbacks() {}
@@ -198,6 +202,31 @@
     CurLexerKind =3D CLK_TokenLexer;
 }
=20
+/// \brief Compute the relative path that names the given file relative to
+/// the given directory.
+static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
+                                const FileEntry *File,
+                                SmallString<128> &Result) {
+  Result.clear();
+
+  StringRef FilePath =3D File->getDir()->getName();
+  StringRef Path =3D FilePath;
+  while (!Path.empty()) {
+    if (const DirectoryEntry *CurDir =3D FM.getDirectory(Path)) {
+      if (CurDir =3D=3D Dir) {
+        Result =3D FilePath.substr(Path.size());
+        llvm::sys::path::append(Result,=20
+                                llvm::sys::path::filename(File->getName())=
);
+        return;
+      }
+    }
+   =20
+    Path =3D llvm::sys::path::parent_path(Path);
+  }
+ =20
+  Result =3D File->getName();
+}
+
 /// HandleEndOfFile - This callback is invoked when the lexer hits the end=
 of
 /// the current file.  This either returns the EOF token or pops a level o=
ff
 /// the include stack and keeps going.
@@ -216,8 +245,11 @@
     }
   }
=20
-  // Complain about reaching an EOF within arc_cf_code_audited.
-  if (PragmaARCCFCodeAuditedLoc.isValid()) {
+  // Complain about reaching a true EOF within arc_cf_code_audited.
+  // We don't want to complain about reaching the end of a macro
+  // instantiation or a _Pragma.
+  if (PragmaARCCFCodeAuditedLoc.isValid() &&
+      !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
     Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audite=
d);
=20
     // Recover by leaving immediately.
@@ -296,15 +328,17 @@
     CurLexer->BufferPtr =3D EndPos;
     CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
=20
-    // We're done with the #included file.
-    CurLexer.reset();
+    if (!isIncrementalProcessingEnabled())
+      // We're done with lexing.
+      CurLexer.reset();
   } else {
     assert(CurPTHLexer && "Got EOF but no current lexer set!");
     CurPTHLexer->getEOF(Result);
     CurPTHLexer.reset();
   }
-
-  CurPPLexer =3D 0;
+ =20
+  if (!isIncrementalProcessingEnabled())
+    CurPPLexer =3D 0;
=20
   // This is the end of the top-level file. 'WarnUnusedMacroLocs' has coll=
ected
   // all macro locations that we need to warn because they are not used.
@@ -312,6 +346,48 @@
          I=3DWarnUnusedMacroLocs.begin(), E=3DWarnUnusedMacroLocs.end(); I=
!=3DE; ++I)
     Diag(*I, diag::pp_macro_not_used);
=20
+  // If we are building a module that has an umbrella header, make sure th=
at
+  // each of the headers within the directory covered by the umbrella head=
er
+  // was actually included by the umbrella header.
+  if (Module *Mod =3D getCurrentModule()) {
+    if (Mod->getUmbrellaHeader()) {
+      SourceLocation StartLoc
+        =3D SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
+
+      if (getDiagnostics().getDiagnosticLevel(
+            diag::warn_uncovered_module_header,=20
+            StartLoc) !=3D DiagnosticsEngine::Ignored) {
+        ModuleMap &ModMap =3D getHeaderSearchInfo().getModuleMap();
+        typedef llvm::sys::fs::recursive_directory_iterator
+          recursive_directory_iterator;
+        const DirectoryEntry *Dir =3D Mod->getUmbrellaDir();
+        llvm::error_code EC;
+        for (recursive_directory_iterator Entry(Dir->getName(), EC), End;
+             Entry !=3D End && !EC; Entry.increment(EC)) {
+          using llvm::StringSwitch;
+         =20
+          // Check whether this entry has an extension typically associate=
d with
+          // headers.
+          if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()=
))
+                 .Cases(".h", ".H", ".hh", ".hpp", true)
+                 .Default(false))
+            continue;
+
+          if (const FileEntry *Header =3D getFileManager().getFile(Entry->=
path()))
+            if (!getSourceManager().hasFileInfo(Header)) {
+              if (!ModMap.isHeaderInUnavailableModule(Header)) {
+                // Find the relative path that would access this header.
+                SmallString<128> RelativePath;
+                computeRelativePath(FileMgr, Dir, Header, RelativePath);  =
           =20
+                Diag(StartLoc, diag::warn_uncovered_module_header)
+                  << RelativePath;
+              }
+            }
+        }
+      }
+    }
+  }
+ =20
   return true;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PPMacroExpansion.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PPMacroExpansion.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 #include "clang/Lex/LiteralSupport.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/STLExtras.h"
-#include "llvm/Config/config.h"
+#include "llvm/Config/llvm-config.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <cstdio>
@@ -47,13 +47,18 @@
=20
 /// setMacroInfo - Specify a macro for this identifier.
 ///
-void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI) {
+void Preprocessor::setMacroInfo(IdentifierInfo *II, MacroInfo *MI,
+                                bool LoadedFromAST) {
   if (MI) {
     Macros[II] =3D MI;
     II->setHasMacroDefinition(true);
+    if (II->isFromAST() && !LoadedFromAST)
+      II->setChangedSinceDeserialization();
   } else if (II->hasMacroDefinition()) {
     Macros.erase(II);
     II->setHasMacroDefinition(false);
+    if (II->isFromAST() && !LoadedFromAST)
+      II->setChangedSinceDeserialization();
   }
 }
=20
@@ -96,7 +101,7 @@
   Ident__has_warning      =3D RegisterBuiltinMacro(*this, "__has_warning");
=20
   // Microsoft Extensions.
-  if (Features.MicrosoftExt)=20
+  if (LangOpts.MicrosoftExt)=20
     Ident__pragma =3D RegisterBuiltinMacro(*this, "__pragma");
   else
     Ident__pragma =3D 0;
@@ -112,6 +117,11 @@
   // If the token isn't an identifier, it's always literally expanded.
   if (II =3D=3D 0) return true;
=20
+  // If the information about this identifier is out of date, update it fr=
om
+  // the external source.
+  if (II->isOutOfDate())
+    PP.getExternalSource()->updateOutOfDateIdentifier(*II);
+
   // If the identifier is a macro, and if that macro is enabled, it may be
   // expanded so it's not a trivial expansion.
   if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() &&
@@ -296,8 +306,10 @@
     // unexpandable.
     if (IdentifierInfo *NewII =3D Identifier.getIdentifierInfo()) {
       if (MacroInfo *NewMI =3D getMacroInfo(NewII))
-        if (!NewMI->isEnabled() || NewMI =3D=3D MI)
+        if (!NewMI->isEnabled() || NewMI =3D=3D MI) {
           Identifier.setFlag(Token::DisableExpand);
+          Diag(Identifier, diag::pp_disabled_macro_expansion);
+        }
     }
=20
     // Since this is not an identifier token, it can't be macro expanded, =
so
@@ -421,8 +433,8 @@
=20
     // Empty arguments are standard in C99 and C++0x, and are supported as=
 an extension in
     // other modes.
-    if (ArgTokens.size() =3D=3D ArgTokenStart && !Features.C99)
-      Diag(Tok, Features.CPlusPlus0x ?
+    if (ArgTokens.size() =3D=3D ArgTokenStart && !LangOpts.C99)
+      Diag(Tok, LangOpts.CPlusPlus0x ?
            diag::warn_cxx98_compat_empty_fnmacro_arg :
            diag::ext_empty_fnmacro_arg);
=20
@@ -576,9 +588,15 @@
 /// HasFeature - Return true if we recognize and implement the feature
 /// specified by the identifier as a standard language feature.
 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
-  const LangOptions &LangOpts =3D PP.getLangOptions();
+  const LangOptions &LangOpts =3D PP.getLangOpts();
+  StringRef Feature =3D II->getName();
=20
-  return llvm::StringSwitch<bool>(II->getName())
+  // Normalize the feature name, __foo__ becomes foo.
+  if (Feature.startswith("__") && Feature.endswith("__") && Feature.size()=
 >=3D 4)
+    Feature =3D Feature.substr(2, Feature.size() - 4);
+
+  return llvm::StringSwitch<bool>(Feature)
+           .Case("address_sanitizer", LangOpts.AddressSanitizer)
            .Case("attribute_analyzer_noreturn", true)
            .Case("attribute_availability", true)
            .Case("attribute_cf_returns_not_retained", true)
@@ -603,48 +621,60 @@
            .Case("objc_arc", LangOpts.ObjCAutoRefCount)
            .Case("objc_arc_weak", LangOpts.ObjCAutoRefCount &&=20
                  LangOpts.ObjCRuntimeHasWeak)
+           .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
            .Case("objc_fixed_enum", LangOpts.ObjC2)
            .Case("objc_instancetype", LangOpts.ObjC2)
+           .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
            .Case("objc_nonfragile_abi", LangOpts.ObjCNonFragileABI)
            .Case("objc_weak_class", LangOpts.ObjCNonFragileABI)
            .Case("ownership_holds", true)
            .Case("ownership_returns", true)
            .Case("ownership_takes", true)
-           // C1X features
-           .Case("c_alignas", LangOpts.C1X)
-           .Case("c_generic_selections", LangOpts.C1X)
-           .Case("c_static_assert", LangOpts.C1X)
-           // C++0x features
+           .Case("objc_bool", true)
+           .Case("objc_subscripting", LangOpts.ObjCNonFragileABI)
+           .Case("objc_array_literals", LangOpts.ObjC2)
+           .Case("objc_dictionary_literals", LangOpts.ObjC2)
+           .Case("arc_cf_code_audited", true)
+           // C11 features
+           .Case("c_alignas", LangOpts.C11)
+           .Case("c_atomic", LangOpts.C11)
+           .Case("c_generic_selections", LangOpts.C11)
+           .Case("c_static_assert", LangOpts.C11)
+           // C++11 features
            .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus0x)
            .Case("cxx_alias_templates", LangOpts.CPlusPlus0x)
            .Case("cxx_alignas", LangOpts.CPlusPlus0x)
+           .Case("cxx_atomic", LangOpts.CPlusPlus0x)
            .Case("cxx_attributes", LangOpts.CPlusPlus0x)
            .Case("cxx_auto_type", LangOpts.CPlusPlus0x)
-         //.Case("cxx_constexpr", false);
+           .Case("cxx_constexpr", LangOpts.CPlusPlus0x)
            .Case("cxx_decltype", LangOpts.CPlusPlus0x)
+           .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlu=
s0x)
            .Case("cxx_default_function_template_args", LangOpts.CPlusPlus0=
x)
+           .Case("cxx_defaulted_functions", LangOpts.CPlusPlus0x)
            .Case("cxx_delegating_constructors", LangOpts.CPlusPlus0x)
            .Case("cxx_deleted_functions", LangOpts.CPlusPlus0x)
            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus0x)
-         //.Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
+           .Case("cxx_generalized_initializers", LangOpts.CPlusPlus0x)
            .Case("cxx_implicit_moves", LangOpts.CPlusPlus0x)
          //.Case("cxx_inheriting_constructors", false)
            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus0x)
-         //.Case("cxx_lambdas", false)
+           .Case("cxx_lambdas", LangOpts.CPlusPlus0x)
+           .Case("cxx_local_type_template_args", LangOpts.CPlusPlus0x)
            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus0x)
            .Case("cxx_noexcept", LangOpts.CPlusPlus0x)
            .Case("cxx_nullptr", LangOpts.CPlusPlus0x)
            .Case("cxx_override_control", LangOpts.CPlusPlus0x)
            .Case("cxx_range_for", LangOpts.CPlusPlus0x)
-         //.Case("cxx_raw_string_literals", false)
+           .Case("cxx_raw_string_literals", LangOpts.CPlusPlus0x)
            .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus0x)
            .Case("cxx_rvalue_references", LangOpts.CPlusPlus0x)
            .Case("cxx_strong_enums", LangOpts.CPlusPlus0x)
            .Case("cxx_static_assert", LangOpts.CPlusPlus0x)
            .Case("cxx_trailing_return", LangOpts.CPlusPlus0x)
-         //.Case("cxx_unicode_literals", false)
-         //.Case("cxx_unrestricted_unions", false)
-         //.Case("cxx_user_literals", false)
+           .Case("cxx_unicode_literals", LangOpts.CPlusPlus0x)
+           .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus0x)
+           .Case("cxx_user_literals", LangOpts.CPlusPlus0x)
            .Case("cxx_variadic_templates", LangOpts.CPlusPlus0x)
            // Type traits
            .Case("has_nothrow_assign", LangOpts.CPlusPlus)
@@ -668,6 +698,7 @@
                  PP.getIdentifierInfo("__is_empty")->getTokenID()
                                                             !=3D tok::iden=
tifier)
            .Case("is_enum", LangOpts.CPlusPlus)
+           .Case("is_final", LangOpts.CPlusPlus)
            .Case("is_literal", LangOpts.CPlusPlus)
            .Case("is_standard_layout", LangOpts.CPlusPlus)
            // __is_pod is available only if the horrible
@@ -680,8 +711,11 @@
                                                             !=3D tok::iden=
tifier)
            .Case("is_polymorphic", LangOpts.CPlusPlus)
            .Case("is_trivial", LangOpts.CPlusPlus)
+           .Case("is_trivially_assignable", LangOpts.CPlusPlus)
+           .Case("is_trivially_constructible", LangOpts.CPlusPlus)
            .Case("is_trivially_copyable", LangOpts.CPlusPlus)
            .Case("is_union", LangOpts.CPlusPlus)
+           .Case("modules", LangOpts.Modules)
            .Case("tls", PP.getTargetInfo().isTLSSupported())
            .Case("underlying_type", LangOpts.CPlusPlus)
            .Default(false);
@@ -700,19 +734,28 @@
       DiagnosticsEngine::Ext_Error)
     return false;
=20
-  const LangOptions &LangOpts =3D PP.getLangOptions();
+  const LangOptions &LangOpts =3D PP.getLangOpts();
+  StringRef Extension =3D II->getName();
+
+  // Normalize the extension name, __foo__ becomes foo.
+  if (Extension.startswith("__") && Extension.endswith("__") &&
+      Extension.size() >=3D 4)
+    Extension =3D Extension.substr(2, Extension.size() - 4);
=20
   // Because we inherit the feature list from HasFeature, this string swit=
ch
   // must be less restrictive than HasFeature's.
-  return llvm::StringSwitch<bool>(II->getName())
-           // C1X features supported by other languages as extensions.
+  return llvm::StringSwitch<bool>(Extension)
+           // C11 features supported by other languages as extensions.
            .Case("c_alignas", true)
+           .Case("c_atomic", true)
            .Case("c_generic_selections", true)
            .Case("c_static_assert", true)
            // C++0x features supported by other languages as extensions.
+           .Case("cxx_atomic", LangOpts.CPlusPlus)
            .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
            .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
            .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
+           .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
            .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
            .Case("cxx_override_control", LangOpts.CPlusPlus)
            .Case("cxx_range_for", LangOpts.CPlusPlus)
@@ -724,7 +767,12 @@
 /// HasAttribute -  Return true if we recognize and implement the attribute
 /// specified by the given identifier.
 static bool HasAttribute(const IdentifierInfo *II) {
-    return llvm::StringSwitch<bool>(II->getName())
+  StringRef Name =3D II->getName();
+  // Normalize the attribute name, __foo__ becomes foo.
+  if (Name.startswith("__") && Name.endswith("__") && Name.size() >=3D 4)
+    Name =3D Name.substr(2, Name.size() - 4);
+
+  return llvm::StringSwitch<bool>(Name)
 #include "clang/Lex/AttrSpellings.inc"
         .Default(false);
 }
@@ -753,7 +801,7 @@
   PP.getCurrentLexer()->LexIncludeFilename(Tok);
=20
   // Reserve a buffer to get the spelling.
-  llvm::SmallString<128> FilenameBuffer;
+  SmallString<128> FilenameBuffer;
   StringRef Filename;
   SourceLocation EndLoc;
  =20
@@ -784,6 +832,16 @@
     return false;
   }
=20
+  // Get ')'.
+  PP.LexNonComment(Tok);
+
+  // Ensure we have a trailing ).
+  if (Tok.isNot(tok::r_paren)) {
+    PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName=
();
+    PP.Diag(LParenLoc, diag::note_matching) << "(";
+    return false;
+  }
+
   bool isAngled =3D PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filen=
ame);
   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
   // error.
@@ -795,20 +853,8 @@
   const FileEntry *File =3D
       PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NU=
LL);
=20
-  // Get the result value.  Result =3D true means the file exists.
-  bool Result =3D File !=3D 0;
-
-  // Get ')'.
-  PP.LexNonComment(Tok);
-
-  // Ensure we have a trailing ).
-  if (Tok.isNot(tok::r_paren)) {
-    PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName=
();
-    PP.Diag(LParenLoc, diag::note_matching) << "(";
-    return false;
-  }
-
-  return Result;
+  // Get the result value.  A result of true means the file exists.
+  return File !=3D 0;
 }
=20
 /// EvaluateHasInclude - Process a '__has_include("path")' expression.
@@ -855,7 +901,7 @@
=20
   ++NumBuiltinMacroExpanded;
=20
-  llvm::SmallString<128> TmpBuffer;
+  SmallString<128> TmpBuffer;
   llvm::raw_svector_ostream OS(TmpBuffer);
=20
   // Set up the return result.
@@ -902,7 +948,7 @@
     }
=20
     // Escape this filename.  Turn '\' -> '\\' '"' -> '\"'
-    llvm::SmallString<128> FN;
+    SmallString<128> FN;
     if (PLoc.isValid()) {
       FN +=3D PLoc.getFilename();
       Lexer::Stringify(FN);
@@ -1010,7 +1056,8 @@
     }
=20
     OS << (int)Value;
-    Tok.setKind(tok::numeric_constant);
+    if (IsValid)
+      Tok.setKind(tok::numeric_constant);
   } else if (II =3D=3D Ident__has_include ||
              II =3D=3D Ident__has_include_next) {
     // The argument to these two builtins should be a parenthesized
@@ -1049,6 +1096,9 @@
         // from macro expansion.
         SmallVector<Token, 4> StrToks;
         while (Tok.is(tok::string_literal)) {
+          // Complain about, and drop, any ud-suffix.
+          if (Tok.hasUDSuffix())
+            Diag(Tok, diag::err_invalid_string_udl);
           StrToks.push_back(Tok);
           LexUnexpandedToken(Tok);
         }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PTHLexer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PTHLexer.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PTHLexer.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -438,7 +438,7 @@
 PTHManager *PTHManager::Create(const std::string &file,
                                DiagnosticsEngine &Diags) {
   // Memory map the PTH file.
-  llvm::OwningPtr<llvm::MemoryBuffer> File;
+  OwningPtr<llvm::MemoryBuffer> File;
=20
   if (llvm::MemoryBuffer::getFile(file, File)) {
     // FIXME: Add ec.message() to this diag.
@@ -488,7 +488,7 @@
     return 0; // FIXME: Proper error diagnostic?
   }
=20
-  llvm::OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBe=
g));
+  OwningPtr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg));
=20
   // Warn if the PTH file is empty.  We still want to create a PTHManager
   // as the PTH could be used with -include-pth.
@@ -514,7 +514,7 @@
     return 0;
   }
=20
-  llvm::OwningPtr<PTHStringIdLookup> SL(PTHStringIdLookup::Create(StringId=
Table,
+  OwningPtr<PTHStringIdLookup> SL(PTHStringIdLookup::Create(StringIdTable,
                                                                   BufBeg));
=20
   // Get the location of the spelling cache.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
Pragma.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/Pragma.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/Pragma.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -115,10 +115,61 @@
     DiscardUntilEndOfDirective();
 }
=20
+namespace {
+/// \brief Helper class for \see Preprocessor::Handle_Pragma.
+class LexingFor_PragmaRAII {
+  Preprocessor &PP;
+  bool InMacroArgPreExpansion;
+  bool Failed;
+  Token &OutTok;
+  Token PragmaTok;
+
+public:
+  LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
+                       Token &Tok)
+    : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
+      Failed(false), OutTok(Tok) {
+    if (InMacroArgPreExpansion) {
+      PragmaTok =3D OutTok;
+      PP.EnableBacktrackAtThisPos();
+    }
+  }
+
+  ~LexingFor_PragmaRAII() {
+    if (InMacroArgPreExpansion) {
+      if (Failed) {
+        PP.CommitBacktrackedTokens();
+      } else {
+        PP.Backtrack();
+        OutTok =3D PragmaTok;
+      }
+    }
+  }
+
+  void failed() {
+    Failed =3D true;
+  }
+};
+}
+
 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
 /// return the first token after the directive.  The _Pragma token has just
 /// been read into 'Tok'.
 void Preprocessor::Handle_Pragma(Token &Tok) {
+
+  // This works differently if we are pre-expanding a macro argument.
+  // In that case we don't actually "activate" the pragma now, we only lex=
 it
+  // until we are sure it is lexically correct and then we backtrack so th=
at
+  // we activate the pragma whenever we encounter the tokens again in the =
token
+  // stream. This ensures that we will activate it in the correct location
+  // or that we will ignore it if it never enters the token stream, e.g:
+  //
+  //     #define EMPTY(x)
+  //     #define INACTIVE(x) EMPTY(x)
+  //     INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
+
+  LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
+
   // Remember the pragma token location.
   SourceLocation PragmaLoc =3D Tok.getLocation();
=20
@@ -126,27 +177,45 @@
   Lex(Tok);
   if (Tok.isNot(tok::l_paren)) {
     Diag(PragmaLoc, diag::err__Pragma_malformed);
-    return;
+    return _PragmaLexing.failed();
   }
=20
   // Read the '"..."'.
   Lex(Tok);
   if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal=
)) {
     Diag(PragmaLoc, diag::err__Pragma_malformed);
-    return;
+    // Skip this token, and the ')', if present.
+    if (Tok.isNot(tok::r_paren))
+      Lex(Tok);
+    if (Tok.is(tok::r_paren))
+      Lex(Tok);
+    return _PragmaLexing.failed();
+  }
+
+  if (Tok.hasUDSuffix()) {
+    Diag(Tok, diag::err_invalid_string_udl);
+    // Skip this token, and the ')', if present.
+    Lex(Tok);
+    if (Tok.is(tok::r_paren))
+      Lex(Tok);
+    return _PragmaLexing.failed();
   }
=20
   // Remember the string.
-  std::string StrVal =3D getSpelling(Tok);
+  Token StrTok =3D Tok;
=20
   // Read the ')'.
   Lex(Tok);
   if (Tok.isNot(tok::r_paren)) {
     Diag(PragmaLoc, diag::err__Pragma_malformed);
-    return;
+    return _PragmaLexing.failed();
   }
=20
+  if (InMacroArgPreExpansion)
+    return;
+
   SourceLocation RParenLoc =3D Tok.getLocation();
+  std::string StrVal =3D getSpelling(StrTok);
=20
   // The _Pragma is lexically sound.  Destringize according to C99 6.10.9.=
1:
   // "The string literal is destringized by deleting the L prefix, if pres=
ent,
@@ -304,6 +373,8 @@
=20
     // Finally, poison it!
     II->setIsPoisoned();
+    if (II->isFromAST())
+      II->setChangedSinceDeserialization();
   }
 }
=20
@@ -351,7 +422,7 @@
     return;
=20
   // Reserve a buffer to get the spelling.
-  llvm::SmallString<128> FilenameBuffer;
+  SmallString<128> FilenameBuffer;
   bool Invalid =3D false;
   StringRef Filename =3D getSpelling(FilenameTok, FilenameBuffer, &Invalid=
);
   if (Invalid)
@@ -440,6 +511,8 @@
     // "foo " "bar" "Baz"
     SmallVector<Token, 4> StrToks;
     while (Tok.is(tok::string_literal)) {
+      if (Tok.hasUDSuffix())
+        Diag(Tok, diag::err_invalid_string_udl);
       StrToks.push_back(Tok);
       Lex(Tok);
     }
@@ -516,6 +589,8 @@
   // "foo " "bar" "Baz"
   SmallVector<Token, 4> StrToks;
   while (Tok.is(tok::string_literal)) {
+    if (Tok.hasUDSuffix())
+      Diag(Tok, diag::err_invalid_string_udl);
     StrToks.push_back(Tok);
     Lex(Tok);
   }
@@ -575,6 +650,11 @@
     return 0;
   }
=20
+  if (Tok.hasUDSuffix()) {
+    Diag(Tok, diag::err_invalid_string_udl);
+    return 0;
+  }
+
   // Remember the macro string.
   std::string StrVal =3D getSpelling(Tok);
=20
@@ -661,6 +741,111 @@
   }
 }
=20
+void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
+  // We will either get a quoted filename or a bracketed filename, and we=20
+  // have to track which we got.  The first filename is the source name,
+  // and the second name is the mapped filename.  If the first is quoted,
+  // the second must be as well (cannot mix and match quotes and brackets).
+
+  // Get the open paren
+  Lex(Tok);
+  if (Tok.isNot(tok::l_paren)) {
+    Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
+    return;
+  }
+
+  // We expect either a quoted string literal, or a bracketed name
+  Token SourceFilenameTok;
+  CurPPLexer->LexIncludeFilename(SourceFilenameTok);
+  if (SourceFilenameTok.is(tok::eod)) {
+    // The diagnostic has already been handled
+    return;
+  }
+
+  StringRef SourceFileName;
+  SmallString<128> FileNameBuffer;
+  if (SourceFilenameTok.is(tok::string_literal) ||=20
+      SourceFilenameTok.is(tok::angle_string_literal)) {
+    SourceFileName =3D getSpelling(SourceFilenameTok, FileNameBuffer);
+  } else if (SourceFilenameTok.is(tok::less)) {
+    // This could be a path instead of just a name
+    FileNameBuffer.push_back('<');
+    SourceLocation End;
+    if (ConcatenateIncludeName(FileNameBuffer, End))
+      return; // Diagnostic already emitted
+    SourceFileName =3D FileNameBuffer.str();
+  } else {
+    Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
+    return;
+  }
+  FileNameBuffer.clear();
+
+  // Now we expect a comma, followed by another include name
+  Lex(Tok);
+  if (Tok.isNot(tok::comma)) {
+    Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
+    return;
+  }
+
+  Token ReplaceFilenameTok;
+  CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
+  if (ReplaceFilenameTok.is(tok::eod)) {
+    // The diagnostic has already been handled
+    return;
+  }
+
+  StringRef ReplaceFileName;
+  if (ReplaceFilenameTok.is(tok::string_literal) ||=20
+      ReplaceFilenameTok.is(tok::angle_string_literal)) {
+    ReplaceFileName =3D getSpelling(ReplaceFilenameTok, FileNameBuffer);
+  } else if (ReplaceFilenameTok.is(tok::less)) {
+    // This could be a path instead of just a name
+    FileNameBuffer.push_back('<');
+    SourceLocation End;
+    if (ConcatenateIncludeName(FileNameBuffer, End))
+      return; // Diagnostic already emitted
+    ReplaceFileName =3D FileNameBuffer.str();
+  } else {
+    Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
+    return;
+  }
+
+  // Finally, we expect the closing paren
+  Lex(Tok);
+  if (Tok.isNot(tok::r_paren)) {
+    Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
+    return;
+  }
+
+  // Now that we have the source and target filenames, we need to make sure
+  // they're both of the same type (angled vs non-angled)
+  StringRef OriginalSource =3D SourceFileName;
+
+  bool SourceIsAngled =3D=20
+    GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),=20
+                                SourceFileName);
+  bool ReplaceIsAngled =3D
+    GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
+                                ReplaceFileName);
+  if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
+      (SourceIsAngled !=3D ReplaceIsAngled)) {
+    unsigned int DiagID;
+    if (SourceIsAngled)
+      DiagID =3D diag::warn_pragma_include_alias_mismatch_angle;
+    else
+      DiagID =3D diag::warn_pragma_include_alias_mismatch_quote;
+
+    Diag(SourceFilenameTok.getLocation(), DiagID)
+      << SourceFileName=20
+      << ReplaceFileName;
+
+    return;
+  }
+
+  // Now we can let the include handler know about this mapping
+  getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
+}
+
 /// AddPragmaHandler - Add the specified pragma handler to the preprocesso=
r.
 /// If 'Namespace' is non-null, then it is a token required to exist on the
 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
@@ -712,8 +897,10 @@
=20
   // If this is a non-default namespace and it is now empty, remove
   // it.
-  if (NS !=3D PragmaHandlers && NS->IsEmpty())
+  if (NS !=3D PragmaHandlers && NS->IsEmpty()) {
     PragmaHandlers->RemovePragmaHandler(NS);
+    delete NS;
+  }
 }
=20
 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
@@ -939,6 +1126,15 @@
   }
 };
=20
+/// PragmaIncludeAliasHandler - "#pragma include_alias("...")".
+struct PragmaIncludeAliasHandler : public PragmaHandler {
+  PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
+  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introdu=
cer,
+                            Token &IncludeAliasTok) {
+      PP.HandlePragmaIncludeAlias(IncludeAliasTok);
+  }
+};
+
 /// PragmaMessageHandler - "#pragma message("...")".
 struct PragmaMessageHandler : public PragmaHandler {
   PragmaMessageHandler() : PragmaHandler("message") {}
@@ -1089,7 +1285,8 @@
   AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
=20
   // MS extensions.
-  if (Features.MicrosoftExt) {
+  if (LangOpts.MicrosoftExt) {
     AddPragmaHandler(new PragmaCommentHandler());
+    AddPragmaHandler(new PragmaIncludeAliasHandler());
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PreprocessingRecord.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PreprocessingRecord.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PreprocessingRecord.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -38,10 +38,13 @@
 }
=20
 PreprocessingRecord::PreprocessingRecord(SourceManager &SM,
-                                         bool IncludeNestedMacroExpansions)
-  : SourceMgr(SM), IncludeNestedMacroExpansions(IncludeNestedMacroExpansio=
ns),
+                                         bool RecordConditionalDirectives)
+  : SourceMgr(SM),
+    RecordCondDirectives(RecordConditionalDirectives), CondDirectiveNextId=
x(0),
     ExternalSource(0)
 {
+  if (RecordCondDirectives)
+    CondDirectiveStack.push_back(CondDirectiveNextIdx++);
 }
=20
 /// \brief Returns a pair of [Begin, End) iterators of preprocessed entiti=
es
@@ -49,35 +52,108 @@
 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
 PreprocessingRecord::getPreprocessedEntitiesInRange(SourceRange Range) {
   if (Range.isInvalid())
-    return std::make_pair(iterator(this, 0), iterator(this, 0));
+    return std::make_pair(iterator(), iterator());
+
+  if (CachedRangeQuery.Range =3D=3D Range) {
+    return std::make_pair(iterator(this, CachedRangeQuery.Result.first),
+                          iterator(this, CachedRangeQuery.Result.second));
+  }
+
+  std::pair<PPEntityID, PPEntityID>
+    Res =3D getPreprocessedEntitiesInRangeSlow(Range);
+ =20
+  CachedRangeQuery.Range =3D Range;
+  CachedRangeQuery.Result =3D Res;
+ =20
+  return std::make_pair(iterator(this, Res.first), iterator(this, Res.seco=
nd));
+}
+
+static bool isPreprocessedEntityIfInFileID(PreprocessedEntity *PPE, FileID=
 FID,
+                                           SourceManager &SM) {
+  assert(!FID.isInvalid());
+  if (!PPE)
+    return false;
+
+  SourceLocation Loc =3D PPE->getSourceRange().getBegin();
+  if (Loc.isInvalid())
+    return false;
+ =20
+  if (SM.isInFileID(SM.getFileLoc(Loc), FID))
+    return true;
+  else
+    return false;
+}
+
+/// \brief Returns true if the preprocessed entity that \arg PPEI iterator
+/// points to is coming from the file \arg FID.
+///
+/// Can be used to avoid implicit deserializations of preallocated
+/// preprocessed entities if we only care about entities of a specific file
+/// and not from files #included in the range given at
+/// \see getPreprocessedEntitiesInRange.
+bool PreprocessingRecord::isEntityInFileID(iterator PPEI, FileID FID) {
+  if (FID.isInvalid())
+    return false;
+
+  PPEntityID PPID =3D PPEI.Position;
+  if (PPID < 0) {
+    assert(unsigned(-PPID-1) < LoadedPreprocessedEntities.size() &&
+           "Out-of bounds loaded preprocessed entity");
+    assert(ExternalSource && "No external source to load from");
+    unsigned LoadedIndex =3D LoadedPreprocessedEntities.size()+PPID;
+    if (PreprocessedEntity *PPE =3D LoadedPreprocessedEntities[LoadedIndex=
])
+      return isPreprocessedEntityIfInFileID(PPE, FID, SourceMgr);
+
+    // See if the external source can see if the entity is in the file wit=
hout
+    // deserializing it.
+    llvm::Optional<bool>
+      IsInFile =3D ExternalSource->isPreprocessedEntityInFileID(LoadedInde=
x, FID);
+    if (IsInFile.hasValue())
+      return IsInFile.getValue();
+
+    // The external source did not provide a definite answer, go and deser=
ialize
+    // the entity to check it.
+    return isPreprocessedEntityIfInFileID(
+                                       getLoadedPreprocessedEntity(LoadedI=
ndex),
+                                          FID, SourceMgr);
+  }
+
+  assert(unsigned(PPID) < PreprocessedEntities.size() &&
+         "Out-of bounds local preprocessed entity");
+  return isPreprocessedEntityIfInFileID(PreprocessedEntities[PPID],
+                                        FID, SourceMgr);
+}
+
+/// \brief Returns a pair of [Begin, End) iterators of preprocessed entiti=
es
+/// that source range \arg R encompasses.
+std::pair<PreprocessingRecord::PPEntityID, PreprocessingRecord::PPEntityID>
+PreprocessingRecord::getPreprocessedEntitiesInRangeSlow(SourceRange Range)=
 {
+  assert(Range.isValid());
   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegi=
n()));
-
+ =20
   std::pair<unsigned, unsigned>
     Local =3D findLocalPreprocessedEntitiesInRange(Range);
-
+ =20
   // Check if range spans local entities.
   if (!ExternalSource || SourceMgr.isLocalSourceLocation(Range.getBegin()))
-    return std::make_pair(iterator(this, Local.first),
-                          iterator(this, Local.second));
-
+    return std::make_pair(Local.first, Local.second);
+ =20
   std::pair<unsigned, unsigned>
     Loaded =3D ExternalSource->findPreprocessedEntitiesInRange(Range);
-
+ =20
   // Check if range spans local entities.
   if (Loaded.first =3D=3D Loaded.second)
-    return std::make_pair(iterator(this, Local.first),
-                          iterator(this, Local.second));
-
+    return std::make_pair(Local.first, Local.second);
+ =20
   unsigned TotalLoaded =3D LoadedPreprocessedEntities.size();
-
+ =20
   // Check if range spans loaded entities.
   if (Local.first =3D=3D Local.second)
-    return std::make_pair(iterator(this, int(Loaded.first)-TotalLoaded),
-                          iterator(this, int(Loaded.second)-TotalLoaded));
-
+    return std::make_pair(int(Loaded.first)-TotalLoaded,
+                          int(Loaded.second)-TotalLoaded);
+ =20
   // Range spands loaded and local entities.
-  return std::make_pair(iterator(this, int(Loaded.first)-TotalLoaded),
-                        iterator(this, Local.second));
+  return std::make_pair(int(Loaded.first)-TotalLoaded, Local.second);
 }
=20
 std::pair<unsigned, unsigned>
@@ -168,33 +244,58 @@
   return I - PreprocessedEntities.begin();
 }
=20
-void PreprocessingRecord::addPreprocessedEntity(PreprocessedEntity *Entity=
) {
+PreprocessingRecord::PPEntityID
+PreprocessingRecord::addPreprocessedEntity(PreprocessedEntity *Entity) {
   assert(Entity);
   SourceLocation BeginLoc =3D Entity->getSourceRange().getBegin();
- =20
+
+  if (!isa<class InclusionDirective>(Entity)) {
+    assert((PreprocessedEntities.empty() ||
+            !SourceMgr.isBeforeInTranslationUnit(BeginLoc,
+                   PreprocessedEntities.back()->getSourceRange().getBegin(=
))) &&
+           "a macro directive was encountered out-of-order");
+    PreprocessedEntities.push_back(Entity);
+    return getPPEntityID(PreprocessedEntities.size()-1, /*isLoaded=3D*/fal=
se);
+  }
+
   // Check normal case, this entity begin location is after the previous o=
ne.
   if (PreprocessedEntities.empty() ||
       !SourceMgr.isBeforeInTranslationUnit(BeginLoc,
                    PreprocessedEntities.back()->getSourceRange().getBegin(=
))) {
     PreprocessedEntities.push_back(Entity);
-    return;
+    return getPPEntityID(PreprocessedEntities.size()-1, /*isLoaded=3D*/fal=
se);
   }
=20
-  // The entity's location is not after the previous one; this can happen =
rarely
-  // e.g. with "#include MACRO".
-  // Iterate the entities vector in reverse until we find the right place =
to
-  // insert the new entity.
-  for (std::vector<PreprocessedEntity *>::iterator
-         RI =3D PreprocessedEntities.end(), Begin =3D PreprocessedEntities=
.begin();
-       RI !=3D Begin; --RI) {
-    std::vector<PreprocessedEntity *>::iterator I =3D RI;
+  // The entity's location is not after the previous one; this can happen =
with
+  // include directives that form the filename using macros, e.g:
+  // "#include MACRO(STUFF)".
+
+  typedef std::vector<PreprocessedEntity *>::iterator pp_iter;
+
+  // Usually there are few macro expansions when defining the filename, do=
 a
+  // linear search for a few entities.
+  unsigned count =3D 0;
+  for (pp_iter RI    =3D PreprocessedEntities.end(),
+               Begin =3D PreprocessedEntities.begin();
+       RI !=3D Begin && count < 4; --RI, ++count) {
+    pp_iter I =3D RI;
     --I;
     if (!SourceMgr.isBeforeInTranslationUnit(BeginLoc,
                                            (*I)->getSourceRange().getBegin=
())) {
-      PreprocessedEntities.insert(RI, Entity);
-      return;
+      pp_iter insertI =3D PreprocessedEntities.insert(RI, Entity);
+      return getPPEntityID(insertI - PreprocessedEntities.begin(),
+                           /*isLoaded=3D*/false);
     }
   }
+
+  // Linear search unsuccessful. Do a binary search.
+  pp_iter I =3D std::upper_bound(PreprocessedEntities.begin(),
+                               PreprocessedEntities.end(),
+                               BeginLoc,
+                               PPEntityComp<&SourceRange::getBegin>(Source=
Mgr));
+  pp_iter insertI =3D PreprocessedEntities.insert(I, Entity);
+  return getPPEntityID(insertI - PreprocessedEntities.begin(),
+                       /*isLoaded=3D*/false);
 }
=20
 void PreprocessingRecord::SetExternalSource(
@@ -258,7 +359,8 @@
=20
 void PreprocessingRecord::MacroExpands(const Token &Id, const MacroInfo* M=
I,
                                        SourceRange Range) {
-  if (!IncludeNestedMacroExpansions && Id.getLocation().isMacroID())
+  // We don't record nested macro expansions.
+  if (Id.getLocation().isMacroID())
     return;
=20
   if (MI->isBuiltinMacro())
@@ -274,17 +376,12 @@
   SourceRange R(MI->getDefinitionLoc(), MI->getDefinitionEndLoc());
   MacroDefinition *Def
       =3D new (*this) MacroDefinition(Id.getIdentifierInfo(), R);
-  addPreprocessedEntity(Def);
-  MacroDefinitions[MI] =3D getPPEntityID(PreprocessedEntities.size()-1,
-                                       /*isLoaded=3D*/false);
+  MacroDefinitions[MI] =3D addPreprocessedEntity(Def);
 }
=20
 void PreprocessingRecord::MacroUndefined(const Token &Id,
                                          const MacroInfo *MI) {
-  llvm::DenseMap<const MacroInfo *, PPEntityID>::iterator Pos
-    =3D MacroDefinitions.find(MI);
-  if (Pos !=3D MacroDefinitions.end())
-    MacroDefinitions.erase(Pos);
+  MacroDefinitions.erase(MI);
 }
=20
 void PreprocessingRecord::InclusionDirective(
@@ -317,7 +414,6 @@
    =20
   default:
     llvm_unreachable("Unknown include directive kind");
-    return;
   }
  =20
   clang::InclusionDirective *ID
@@ -326,6 +422,95 @@
   addPreprocessedEntity(ID);
 }
=20
+bool PreprocessingRecord::rangeIntersectsConditionalDirective(
+                                                      SourceRange Range) c=
onst {
+  if (Range.isInvalid())
+    return false;
+
+  CondDirectiveLocsTy::const_iterator
+    low =3D std::lower_bound(CondDirectiveLocs.begin(), CondDirectiveLocs.=
end(),
+                           Range.getBegin(), CondDirectiveLoc::Comp(Source=
Mgr));
+  if (low =3D=3D CondDirectiveLocs.end())
+    return false;
+
+  if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), low->getLoc()))
+    return false;
+
+  CondDirectiveLocsTy::const_iterator
+    upp =3D std::upper_bound(low, CondDirectiveLocs.end(),
+                           Range.getEnd(), CondDirectiveLoc::Comp(SourceMg=
r));
+  unsigned uppIdx;
+  if (upp !=3D CondDirectiveLocs.end())
+    uppIdx =3D upp->getIdx();
+  else
+    uppIdx =3D 0;
+
+  return low->getIdx() !=3D uppIdx;
+}
+
+unsigned PreprocessingRecord::findCondDirectiveIdx(SourceLocation Loc) con=
st {
+  if (Loc.isInvalid())
+    return 0;
+
+  CondDirectiveLocsTy::const_iterator
+    low =3D std::lower_bound(CondDirectiveLocs.begin(), CondDirectiveLocs.=
end(),
+                           Loc, CondDirectiveLoc::Comp(SourceMgr));
+  if (low =3D=3D CondDirectiveLocs.end())
+    return 0;
+  return low->getIdx();
+}
+
+void PreprocessingRecord::addCondDirectiveLoc(CondDirectiveLoc DirLoc) {
+  // Ignore directives in system headers.
+  if (SourceMgr.isInSystemHeader(DirLoc.getLoc()))
+    return;
+
+  assert(CondDirectiveLocs.empty() ||
+         SourceMgr.isBeforeInTranslationUnit(CondDirectiveLocs.back().getL=
oc(),
+                                             DirLoc.getLoc()));
+  CondDirectiveLocs.push_back(DirLoc);
+}
+
+void PreprocessingRecord::If(SourceLocation Loc, SourceRange ConditionRang=
e) {
+  if (RecordCondDirectives) {
+    addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back()));
+    CondDirectiveStack.push_back(CondDirectiveNextIdx++);
+  }
+}
+
+void PreprocessingRecord::Ifdef(SourceLocation Loc, const Token &MacroName=
Tok) {
+  if (RecordCondDirectives) {
+    addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back()));
+    CondDirectiveStack.push_back(CondDirectiveNextIdx++);
+  }
+}
+
+void PreprocessingRecord::Ifndef(SourceLocation Loc,const Token &MacroName=
Tok) {
+  if (RecordCondDirectives) {
+    addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back()));
+    CondDirectiveStack.push_back(CondDirectiveNextIdx++);
+  }
+}
+
+void PreprocessingRecord::Elif(SourceLocation Loc, SourceRange ConditionRa=
nge,
+                               SourceLocation IfLoc) {
+  if (RecordCondDirectives)
+    addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back()));
+}
+
+void PreprocessingRecord::Else(SourceLocation Loc, SourceLocation IfLoc) {
+  if (RecordCondDirectives)
+    addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back()));
+}
+
+void PreprocessingRecord::Endif(SourceLocation Loc, SourceLocation IfLoc) {
+  if (RecordCondDirectives) {
+    addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back()));
+    assert(!CondDirectiveStack.empty());
+    CondDirectiveStack.pop_back();
+  }
+}
+
 size_t PreprocessingRecord::getTotalMemory() const {
   return BumpAlloc.getTotalMemory()
     + llvm::capacity_in_bytes(MacroDefinitions)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
Preprocessor.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/Preprocessor.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/Preprocessor.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -40,7 +40,7 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/TargetInfo.h"
 #include "llvm/ADT/APFloat.h"
-#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Capacity.h"
@@ -54,18 +54,19 @@
                            HeaderSearch &Headers, ModuleLoader &TheModuleL=
oader,
                            IdentifierInfoLookup* IILookup,
                            bool OwnsHeaders,
-                           bool DelayInitialization)
-  : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileM=
gr()),
+                           bool DelayInitialization,
+                           bool IncrProcessing)
+  : Diags(&diags), LangOpts(opts), Target(target),FileMgr(Headers.getFileM=
gr()),
     SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
-    ExternalSource(0),=20
-    Identifiers(opts, IILookup), CodeComplete(0),
+    ExternalSource(0), Identifiers(opts, IILookup),=20
+    IncrementalProcessing(IncrProcessing), CodeComplete(0),=20
     CodeCompletionFile(0), CodeCompletionOffset(0), CodeCompletionReached(=
0),
     SkipMainFilePreamble(0, true), CurPPLexer(0),=20
     CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0), MacroArgCache(=
0),=20
     Record(0), MIChainHead(0), MICache(0)=20
 {
   OwnsHeaderSearch =3D OwnsHeaders;
- =20
+
   if (!DelayInitialization) {
     assert(Target && "Must provide target information for PP initializatio=
n");
     Initialize(*Target);
@@ -74,9 +75,6 @@
=20
 Preprocessor::~Preprocessor() {
   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalanc=
e!");
-  assert(((MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty(=
)) ||
-          isCodeCompletionReached()) &&
-         "Preprocessor::HandleEndOfTokenLexer should have cleared those");
=20
   while (!IncludeMacroStack.empty()) {
     delete IncludeMacroStack.back().TheLexer;
@@ -133,11 +131,11 @@
   KeepComments =3D false;
   KeepMacroComments =3D false;
   SuppressIncludeNotFoundError =3D false;
-  AutoModuleImport =3D false;
  =20
   // Macro expansion is enabled.
   DisableMacroExpansion =3D false;
   InMacroArgs =3D false;
+  InMacroArgPreExpansion =3D false;
   NumCachedTokenLexers =3D 0;
  =20
   CachedLexPos =3D 0;
@@ -157,7 +155,7 @@
   // Initialize builtin macros like __LINE__ and friends.
   RegisterBuiltinMacros();
  =20
-  if(Features.Borland) {
+  if(LangOpts.Borland) {
     Ident__exception_info        =3D getIdentifierInfo("_exception_info");
     Ident___exception_info       =3D getIdentifierInfo("__exception_info");
     Ident_GetExceptionInfo       =3D getIdentifierInfo("GetExceptionInform=
ation");
@@ -171,7 +169,9 @@
     Ident__exception_info =3D Ident__exception_code =3D Ident__abnormal_te=
rmination =3D 0;
     Ident___exception_info =3D Ident___exception_code =3D Ident___abnormal=
_termination =3D 0;
     Ident_GetExceptionInfo =3D Ident_GetExceptionCode =3D Ident_AbnormalTe=
rmination =3D 0;
-  }=20
+  }
+ =20
+  HeaderInfo.setTarget(Target);
 }
=20
 void Preprocessor::setPTHManager(PTHManager* pm) {
@@ -270,6 +270,17 @@
   return Macros.end();
 }
=20
+void Preprocessor::recomputeCurLexerKind() {
+  if (CurLexer)
+    CurLexerKind =3D CLK_Lexer;
+  else if (CurPTHLexer)
+    CurLexerKind =3D CLK_PTHLexer;
+  else if (CurTokenLexer)
+    CurLexerKind =3D CLK_TokenLexer;
+  else=20
+    CurLexerKind =3D CLK_CachingLexer;
+}
+
 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
                                           unsigned CompleteLine,
                                           unsigned CompleteColumn) {
@@ -372,7 +383,12 @@
     Tok.setLiteralData(DestPtr);
 }
=20
-
+Module *Preprocessor::getCurrentModule() {
+  if (getLangOpts().CurrentModule.empty())
+    return 0;
+ =20
+  return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Preprocessor Initialization Methods
@@ -388,19 +404,23 @@
   assert(NumEnteredSourceFiles =3D=3D 0 && "Cannot reenter the main file!"=
);
   FileID MainFileID =3D SourceMgr.getMainFileID();
=20
-  // Enter the main file source buffer.
-  EnterSourceFile(MainFileID, 0, SourceLocation());
-
-  // If we've been asked to skip bytes in the main file (e.g., as part of a
-  // precompiled preamble), do so now.
-  if (SkipMainFilePreamble.first > 0)
-    CurLexer->SkipBytes(SkipMainFilePreamble.first,=20
-                        SkipMainFilePreamble.second);
+  // If MainFileID is loaded it means we loaded an AST file, no need to en=
ter
+  // a main file.
+  if (!SourceMgr.isLoadedFileID(MainFileID)) {
+    // Enter the main file source buffer.
+    EnterSourceFile(MainFileID, 0, SourceLocation());
  =20
-  // Tell the header info that the main file was entered.  If the file is =
later
-  // #imported, it won't be re-entered.
-  if (const FileEntry *FE =3D SourceMgr.getFileEntryForID(MainFileID))
-    HeaderInfo.IncrementIncludeCount(FE);
+    // If we've been asked to skip bytes in the main file (e.g., as part o=
f a
+    // precompiled preamble), do so now.
+    if (SkipMainFilePreamble.first > 0)
+      CurLexer->SkipBytes(SkipMainFilePreamble.first,=20
+                          SkipMainFilePreamble.second);
+   =20
+    // Tell the header info that the main file was entered.  If the file i=
s later
+    // #imported, it won't be re-entered.
+    if (const FileEntry *FE =3D SourceMgr.getFileEntryForID(MainFileID))
+      HeaderInfo.IncrementIncludeCount(FE);
+  }
=20
   // Preprocess Predefines to populate the initial preprocessor state.
   llvm::MemoryBuffer *SB =3D
@@ -437,7 +457,7 @@
                                            Identifier.getLength()));
   } else {
     // Cleaning needed, alloca a buffer, clean into it, then use the buffe=
r.
-    llvm::SmallString<64> IdentifierBuffer;
+    SmallString<64> IdentifierBuffer;
     StringRef CleanedStr =3D getSpelling(Identifier, IdentifierBuffer);
     II =3D getIdentifierInfo(CleanedStr);
   }
@@ -492,6 +512,13 @@
=20
   IdentifierInfo &II =3D *Identifier.getIdentifierInfo();
=20
+  // If the information about this identifier is out of date, update it fr=
om
+  // the external source.
+  if (II.isOutOfDate()) {
+    ExternalSource->updateOutOfDateIdentifier(II);
+    Identifier.setKind(II.getTokenID());
+  }
+ =20
   // If this identifier was poisoned, and if it was not produced from a ma=
cro
   // expansion, emit an error.
   if (II.isPoisoned() && CurPPLexer) {
@@ -500,8 +527,10 @@
=20
   // If this is a macro to be expanded, do it.
   if (MacroInfo *MI =3D getMacroInfo(&II)) {
-    if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
-      if (MI->isEnabled()) {
+    if (!DisableMacroExpansion) {
+      if (Identifier.isExpandDisabled()) {
+        Diag(Identifier, diag::pp_disabled_macro_expansion);
+      } else if (MI->isEnabled()) {
         if (!HandleMacroExpandedIdentifier(Identifier, MI))
           return;
       } else {
@@ -509,6 +538,7 @@
         // expanded, even if it's in a context where it could be expanded =
in the
         // future.
         Identifier.setFlag(Token::DisableExpand);
+        Diag(Identifier, diag::pp_disabled_macro_expansion);
       }
     }
   }
@@ -537,43 +567,59 @@
   if (II.isExtensionToken() && !DisableMacroExpansion)
     Diag(Identifier, diag::ext_token_used);
  =20
-  // If this is the '__import_module__' keyword, note that the next token
-  // indicates a module name.
-  if (II.getTokenID() =3D=3D tok::kw___import_module__ &&
-      !InMacroArgs && !DisableMacroExpansion) {
+  // If this is the '__experimental_modules_import' contextual keyword, no=
te
+  // that the next token indicates a module name.
+  //
+  // Note that we do not treat '__experimental_modules_import' as a contex=
tual
+  // keyword when we're in a caching lexer, because caching lexers only get
+  // used in contexts where import declarations are disallowed.
+  if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion &&
+      getLangOpts().Modules && CurLexerKind !=3D CLK_CachingLexer) {
     ModuleImportLoc =3D Identifier.getLocation();
+    ModuleImportPath.clear();
+    ModuleImportExpectsIdentifier =3D true;
     CurLexerKind =3D CLK_LexAfterModuleImport;
   }
 }
=20
-/// \brief Lex a token following the __import_module__ keyword.
+/// \brief Lex a token following the 'import' contextual keyword.
+///
 void Preprocessor::LexAfterModuleImport(Token &Result) {
   // Figure out what kind of lexer we actually have.
-  if (CurLexer)
-    CurLexerKind =3D CLK_Lexer;
-  else if (CurPTHLexer)
-    CurLexerKind =3D CLK_PTHLexer;
-  else if (CurTokenLexer)
-    CurLexerKind =3D CLK_TokenLexer;
-  else=20
-    CurLexerKind =3D CLK_CachingLexer;
+  recomputeCurLexerKind();
  =20
   // Lex the next token.
   Lex(Result);
=20
   // The token sequence=20
   //
-  //   __import_module__ identifier
+  //   import identifier (. identifier)*
   //
-  // indicates a module import directive. We already saw the __import_modu=
le__
-  // keyword, so now we're looking for the identifier.
-  if (Result.getKind() !=3D tok::identifier)
+  // indicates a module import directive. We already saw the 'import'=20
+  // contextual keyword, so now we're looking for the identifiers.
+  if (ModuleImportExpectsIdentifier && Result.getKind() =3D=3D tok::identi=
fier) {
+    // We expected to see an identifier here, and we did; continue handling
+    // identifiers.
+    ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
+                                              Result.getLocation()));
+    ModuleImportExpectsIdentifier =3D false;
+    CurLexerKind =3D CLK_LexAfterModuleImport;
     return;
+  }
  =20
-  // Load the module.
-  (void)TheModuleLoader.loadModule(ModuleImportLoc,
-                                   *Result.getIdentifierInfo(),=20
-                                   Result.getLocation());
+  // If we're expecting a '.' or a ';', and we got a '.', then wait until =
we
+  // see the next identifier.
+  if (!ModuleImportExpectsIdentifier && Result.getKind() =3D=3D tok::perio=
d) {
+    ModuleImportExpectsIdentifier =3D true;
+    CurLexerKind =3D CLK_LexAfterModuleImport;
+    return;
+  }
+
+  // If we have a non-empty module path, load the named module.
+  if (!ModuleImportPath.empty())
+    (void)TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath,
+                                     Module::MacrosVisible,
+                                     /*IsIncludeDirective=3D*/false);
 }
=20
 void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
@@ -610,12 +656,11 @@
=20
 CodeCompletionHandler::~CodeCompletionHandler() { }
=20
-void Preprocessor::createPreprocessingRecord(
-                                      bool IncludeNestedMacroExpansions) {
+void Preprocessor::createPreprocessingRecord(bool RecordConditionalDirecti=
ves) {
   if (Record)
     return;
  =20
   Record =3D new PreprocessingRecord(getSourceManager(),
-                                   IncludeNestedMacroExpansions);
+                                   RecordConditionalDirectives);
   addPPCallbacks(Record);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
PreprocessorLexer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/PreprocessorLexer.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/PreprocessorLexer.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -17,6 +17,8 @@
 #include "clang/Basic/SourceManager.h"
 using namespace clang;
=20
+void PreprocessorLexer::anchor() { }
+
 PreprocessorLexer::PreprocessorLexer(Preprocessor *pp, FileID fid)
   : PP(pp), FID(fid), InitialNumSLocEntries(0),
     ParsingPreprocessorDirective(false),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
TokenConcatenation.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/TokenConcatenation.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/TokenConcatenation.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -45,7 +45,7 @@
 /// IsIdentifierStringPrefix - Return true if the spelling of the token
 /// is literally 'L', 'u', 'U', or 'u8'. Including raw versions.
 bool TokenConcatenation::IsIdentifierStringPrefix(const Token &Tok) const {
-  const LangOptions &LangOpts =3D PP.getLangOptions();
+  const LangOptions &LangOpts =3D PP.getLangOpts();
=20
   if (!Tok.needsCleaning()) {
     if (Tok.getLength() < 1 || Tok.getLength() > 3)
@@ -85,6 +85,19 @@
   TokenInfo[tok::hash            ] |=3D aci_custom_firstchar;
   TokenInfo[tok::arrow           ] |=3D aci_custom_firstchar;
=20
+  // These tokens have custom code in C++11 mode.
+  if (PP.getLangOpts().CPlusPlus0x) {
+    TokenInfo[tok::string_literal      ] |=3D aci_custom;
+    TokenInfo[tok::wide_string_literal ] |=3D aci_custom;
+    TokenInfo[tok::utf8_string_literal ] |=3D aci_custom;
+    TokenInfo[tok::utf16_string_literal] |=3D aci_custom;
+    TokenInfo[tok::utf32_string_literal] |=3D aci_custom;
+    TokenInfo[tok::char_constant       ] |=3D aci_custom;
+    TokenInfo[tok::wide_char_constant  ] |=3D aci_custom;
+    TokenInfo[tok::utf16_char_constant ] |=3D aci_custom;
+    TokenInfo[tok::utf32_char_constant ] |=3D aci_custom;
+  }
+
   // These tokens change behavior if followed by an '=3D'.
   TokenInfo[tok::amp         ] |=3D aci_avoid_equal;           // &=3D
   TokenInfo[tok::plus        ] |=3D aci_avoid_equal;           // +=3D
@@ -179,12 +192,32 @@
   switch (PrevKind) {
   default:
     llvm_unreachable("InitAvoidConcatTokenInfo built wrong");
-    return true;
=20
   case tok::raw_identifier:
     llvm_unreachable("tok::raw_identifier in non-raw lexing mode!");
-    return true;
=20
+  case tok::string_literal:
+  case tok::wide_string_literal:
+  case tok::utf8_string_literal:
+  case tok::utf16_string_literal:
+  case tok::utf32_string_literal:
+  case tok::char_constant:
+  case tok::wide_char_constant:
+  case tok::utf16_char_constant:
+  case tok::utf32_char_constant:
+    if (!PP.getLangOpts().CPlusPlus0x)
+      return false;
+
+    // In C++11, a string or character literal followed by an identifier i=
s a
+    // single token.
+    if (Tok.getIdentifierInfo())
+      return true;
+
+    // A ud-suffix is an identifier. If the previous token ends with one, =
treat
+    // it as an identifier.
+    if (!PrevTok.hasUDSuffix())
+      return false;
+    // FALL THROUGH.
   case tok::identifier:   // id+id or id+number or id+L"foo".
     // id+'.'... will not append.
     if (Tok.is(tok::numeric_constant))
@@ -203,13 +236,15 @@
     // Otherwise, this is a narrow character or string.  If the *identifie=
r*
     // is a literal 'L', 'u8', 'u' or 'U', avoid pasting L "foo" -> L"foo".
     return IsIdentifierStringPrefix(PrevTok);
+
   case tok::numeric_constant:
     return isalnum(FirstChar) || Tok.is(tok::numeric_constant) ||
-    FirstChar =3D=3D '+' || FirstChar =3D=3D '-' || FirstChar =3D=3D '.';
+           FirstChar =3D=3D '+' || FirstChar =3D=3D '-' || FirstChar =3D=
=3D '.' ||
+           (PP.getLangOpts().CPlusPlus0x && FirstChar =3D=3D '_');
   case tok::period:          // ..., .*, .1234
     return (FirstChar =3D=3D '.' && PrevPrevTok.is(tok::period)) ||
     isdigit(FirstChar) ||
-    (PP.getLangOptions().CPlusPlus && FirstChar =3D=3D '*');
+    (PP.getLangOpts().CPlusPlus && FirstChar =3D=3D '*');
   case tok::amp:             // &&
     return FirstChar =3D=3D '&';
   case tok::plus:            // ++
@@ -228,10 +263,10 @@
     return FirstChar =3D=3D '>' || FirstChar =3D=3D ':';
   case tok::colon:           // ::, :>
     return FirstChar =3D=3D '>' ||
-    (PP.getLangOptions().CPlusPlus && FirstChar =3D=3D ':');
+    (PP.getLangOpts().CPlusPlus && FirstChar =3D=3D ':');
   case tok::hash:            // ##, #@, %:%:
     return FirstChar =3D=3D '#' || FirstChar =3D=3D '@' || FirstChar =3D=
=3D '%';
   case tok::arrow:           // ->*
-    return PP.getLangOptions().CPlusPlus && FirstChar =3D=3D '*';
+    return PP.getLangOpts().CPlusPlus && FirstChar =3D=3D '*';
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Lex/=
TokenLexer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Lex/TokenLexer.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Lex/TokenLexer.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -17,7 +17,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/LexDiagnostic.h"
-#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/SmallString.h"
 using namespace clang;
=20
=20
@@ -450,7 +450,7 @@
 /// are more ## after it, chomp them iteratively.  Return the result as To=
k.
 /// If this returns true, the caller should immediately return the token.
 bool TokenLexer::PasteTokens(Token &Tok) {
-  llvm::SmallString<128> Buffer;
+  SmallString<128> Buffer;
   const char *ResultTokStrPtr =3D 0;
   SourceLocation StartLoc =3D Tok.getLocation();
   SourceLocation PasteOpLoc;
@@ -527,7 +527,7 @@
       // Make a lexer to lex this string from.  Lex just this one token.
       // Make a lexer object so that we lex and expand the paste result.
       Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
-               PP.getLangOptions(), ScratchBufStart,
+               PP.getLangOpts(), ScratchBufStart,
                ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
=20
       // Lex a token in raw mode.  This way it won't look up identifiers
@@ -546,14 +546,14 @@
       if (isInvalid) {
         // Test for the Microsoft extension of /##/ turning into // here o=
n the
         // error path.
-        if (PP.getLangOptions().MicrosoftExt && Tok.is(tok::slash) &&
+        if (PP.getLangOpts().MicrosoftExt && Tok.is(tok::slash) &&
             RHS.is(tok::slash)) {
           HandleMicrosoftCommentPaste(Tok);
           return true;
         }
=20
         // Do not emit the error when preprocessing assembler code.
-        if (!PP.getLangOptions().AsmPreprocessor) {
+        if (!PP.getLangOpts().AsmPreprocessor) {
           // Explicitly convert the token location to have proper expansion
           // information so that the user knows where it came from.
           SourceManager &SM =3D PP.getSourceManager();
@@ -563,7 +563,7 @@
           // error to a warning that defaults to an error.  This allows
           // disabling it.
           PP.Diag(Loc,
-                  PP.getLangOptions().MicrosoftExt ? diag::err_pp_bad_past=
e_ms=20
+                  PP.getLangOpts().MicrosoftExt ? diag::err_pp_bad_paste_m=
s=20
                                                    : diag::err_pp_bad_past=
e)
             << Buffer.str();
         }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseAST.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseAST.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseAST.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -38,23 +38,24 @@
 void clang::ParseAST(Preprocessor &PP, ASTConsumer *Consumer,
                      ASTContext &Ctx, bool PrintStats,
                      TranslationUnitKind TUKind,
-                     CodeCompleteConsumer *CompletionConsumer) {
+                     CodeCompleteConsumer *CompletionConsumer,
+                     bool SkipFunctionBodies) {
=20
-  llvm::OwningPtr<Sema> S(new Sema(PP, Ctx, *Consumer,
+  OwningPtr<Sema> S(new Sema(PP, Ctx, *Consumer,
                                    TUKind,
                                    CompletionConsumer));
=20
   // Recover resources if we crash before exiting this method.
-  llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleaupSema(S.get());
+  llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(S.get());
  =20
-  ParseAST(*S.get(), PrintStats);
+  ParseAST(*S.get(), PrintStats, SkipFunctionBodies);
 }
=20
-void clang::ParseAST(Sema &S, bool PrintStats) {
+void clang::ParseAST(Sema &S, bool PrintStats, bool SkipFunctionBodies) {
   // Collect global stats on Decls/Stmts (until we have a module streamer).
   if (PrintStats) {
-    Decl::CollectingStats(true);
-    Stmt::CollectingStats(true);
+    Decl::EnableStatistics();
+    Stmt::EnableStatistics();
   }
=20
   // Also turn on collection of stats inside of the Sema object.
@@ -63,14 +64,15 @@
=20
   ASTConsumer *Consumer =3D &S.getASTConsumer();
=20
-  llvm::OwningPtr<Parser> ParseOP(new Parser(S.getPreprocessor(), S));
+  OwningPtr<Parser> ParseOP(new Parser(S.getPreprocessor(), S,
+                                       SkipFunctionBodies));
   Parser &P =3D *ParseOP.get();
=20
   PrettyStackTraceParserEntry CrashInfo(P);
=20
   // Recover resources if we crash before exiting this method.
   llvm::CrashRecoveryContextCleanupRegistrar<Parser>
-    CleaupParser(ParseOP.get());
+    CleanupParser(ParseOP.get());
=20
   S.getPreprocessor().EnterMainSourceFile();
   P.Initialize();
@@ -79,18 +81,23 @@
   if (ExternalASTSource *External =3D S.getASTContext().getExternalSource(=
))
     External->StartTranslationUnit(Consumer);
  =20
+  bool Abort =3D false;
   Parser::DeclGroupPtrTy ADecl;
  =20
   while (!P.ParseTopLevelDecl(ADecl)) {  // Not end of file.
     // If we got a null return and something *was* parsed, ignore it.  This
     // is due to a top-level semicolon, an action override, or a parse err=
or
     // skipping something.
-    if (ADecl)
-      Consumer->HandleTopLevelDecl(ADecl.get());
+    if (ADecl) {
+      if (!Consumer->HandleTopLevelDecl(ADecl.get())) {
+        Abort =3D true;
+        break;
+      }
+    }
   };
-  // Check for any pending objective-c implementation decl.
-  while ((ADecl =3D P.FinishPendingObjCActions()))
-    Consumer->HandleTopLevelDecl(ADecl.get());
+
+  if (Abort)
+    return;
  =20
   // Process any TopLevelDecls generated by #pragma weak.
   for (SmallVector<Decl*,2>::iterator
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseCXXInlineMethods.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseCXXInlineMethods.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseCXXInlineMethods.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -24,8 +24,10 @@
 Decl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS,
                                       AttributeList *AccessAttrs,
                                       ParsingDeclarator &D,
-                                const ParsedTemplateInfo &TemplateInfo,
-                                const VirtSpecifiers& VS, ExprResult& Init=
) {
+                                      const ParsedTemplateInfo &TemplateIn=
fo,
+                                      const VirtSpecifiers& VS,=20
+                                      FunctionDefinitionKind DefinitionKin=
d,
+                                      ExprResult& Init) {
   assert(D.isFunctionDeclarator() && "This isn't a function declarator!");
   assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try=
) ||
           Tok.is(tok::equal)) &&
@@ -36,20 +38,20 @@
           TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size(=
) : 0);
=20
   Decl *FnD;
-  D.setFunctionDefinition(true);
+  D.setFunctionDefinitionKind(DefinitionKind);
   if (D.getDeclSpec().isFriendSpecified())
     FnD =3D Actions.ActOnFriendFunctionDecl(getCurScope(), D,
                                           move(TemplateParams));
   else {
     FnD =3D Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D,
                                            move(TemplateParams), 0,=20
-                                           VS, /*HasInit=3D*/false);
+                                           VS, /*HasDeferredInit=3D*/false=
);
     if (FnD) {
       Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs,
                                        false, true);
       bool TypeSpecContainsAuto
         =3D D.getDeclSpec().getTypeSpecType() =3D=3D DeclSpec::TST_auto;
-      if (Init.get())
+      if (Init.isUsable())
         Actions.AddInitializerToDecl(FnD, Init.get(), false,=20
                                      TypeSpecContainsAuto);
       else
@@ -64,18 +66,25 @@
   if (Tok.is(tok::equal)) {
     ConsumeToken();
=20
+    if (!FnD) {
+      SkipUntil(tok::semi);
+      return 0;
+    }
+
     bool Delete =3D false;
     SourceLocation KWLoc;
     if (Tok.is(tok::kw_delete)) {
-      if (!getLang().CPlusPlus0x)
-        Diag(Tok, diag::warn_deleted_function_accepted_as_extension);
+      Diag(Tok, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_deleted_function :
+           diag::ext_deleted_function);
=20
       KWLoc =3D ConsumeToken();
       Actions.SetDeclDeleted(FnD, KWLoc);
       Delete =3D true;
     } else if (Tok.is(tok::kw_default)) {
-      if (!getLang().CPlusPlus0x)
-        Diag(Tok, diag::warn_defaulted_function_accepted_as_extension);
+      Diag(Tok, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_defaulted_function :
+           diag::ext_defaulted_function);
=20
       KWLoc =3D ConsumeToken();
       Actions.SetDeclDefaulted(FnD, KWLoc);
@@ -98,15 +107,13 @@
   // In delayed template parsing mode, if we are within a class template
   // or if we are about to parse function member template then consume
   // the tokens and store them for parsing at the end of the translation u=
nit.
-  if (getLang().DelayedTemplateParsing &&=20
+  if (getLangOpts().DelayedTemplateParsing &&=20
       ((Actions.CurContext->isDependentContext() ||
         TemplateInfo.Kind !=3D ParsedTemplateInfo::NonTemplate) &&=20
-        !Actions.IsInsideALocalClassWithinATemplateFunction()) &&
-        !D.getDeclSpec().isFriendSpecified()) {
+        !Actions.IsInsideALocalClassWithinATemplateFunction())) {
=20
     if (FnD) {
-      LateParsedTemplatedFunction *LPT =3D
-        new LateParsedTemplatedFunction(this, FnD);
+      LateParsedTemplatedFunction *LPT =3D new LateParsedTemplatedFunction=
(FnD);
=20
       FunctionDecl *FD =3D 0;
       if (FunctionTemplateDecl *FunTmpl =3D dyn_cast<FunctionTemplateDecl>=
(FnD))
@@ -138,16 +145,14 @@
   // function body.
   if (ConsumeAndStoreFunctionPrologue(Toks)) {
     // We didn't find the left-brace we expected after the
-    // constructor initializer.
-    if (Tok.is(tok::semi)) {
-      // We found a semicolon; complain, consume the semicolon, and
-      // don't try to parse this method later.
-      Diag(Tok.getLocation(), diag::err_expected_lbrace);
-      ConsumeAnyToken();
-      delete getCurrentClass().LateParsedDeclarations.back();
-      getCurrentClass().LateParsedDeclarations.pop_back();
-      return FnD;
-    }
+    // constructor initializer; we already printed an error, and it's like=
ly
+    // impossible to recover, so don't try to parse this method later.
+    // If we stopped at a semicolon, consume it to avoid an extra warning.
+     if (Tok.is(tok::semi))
+      ConsumeToken();
+    delete getCurrentClass().LateParsedDeclarations.back();
+    getCurrentClass().LateParsedDeclarations.pop_back();
+    return FnD;
   } else {
     // Consume everything up to (and including) the matching right brace.
     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=3D*/false);
@@ -188,7 +193,7 @@
   tok::TokenKind kind =3D Tok.getKind();
   if (kind =3D=3D tok::equal) {
     Toks.push_back(Tok);
-    ConsumeAnyToken();
+    ConsumeToken();
   }
=20
   if (kind =3D=3D tok::l_brace) {
@@ -290,7 +295,8 @@
                             Scope::FunctionPrototypeScope|Scope::DeclScope=
);
   for (unsigned I =3D 0, N =3D LM.DefaultArgs.size(); I !=3D N; ++I) {
     // Introduce the parameter into scope.
-    Actions.ActOnDelayedCXXMethodParameter(getCurScope(), LM.DefaultArgs[I=
].Param);
+    Actions.ActOnDelayedCXXMethodParameter(getCurScope(),=20
+                                           LM.DefaultArgs[I].Param);
=20
     if (CachedTokens *Toks =3D LM.DefaultArgs[I].Toks) {
       // Save the current token position.
@@ -310,9 +316,15 @@
       // The argument isn't actually potentially evaluated unless it is
       // used.
       EnterExpressionEvaluationContext Eval(Actions,
-                                            Sema::PotentiallyEvaluatedIfUs=
ed);
+                                            Sema::PotentiallyEvaluatedIfUs=
ed,
+                                            LM.DefaultArgs[I].Param);
=20
-      ExprResult DefArgResult(ParseAssignmentExpression());
+      ExprResult DefArgResult;
+      if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
+        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
+        DefArgResult =3D ParseBraceInitializer();
+      } else
+        DefArgResult =3D ParseAssignmentExpression();
       if (DefArgResult.isInvalid())
         Actions.ActOnParamDefaultArgumentError(LM.DefaultArgs[I].Param);
       else {
@@ -469,7 +481,8 @@
   ConsumeAnyToken();
=20
   SourceLocation EqualLoc;
-  ExprResult Init =3D ParseCXXMemberInitializer(/*IsFunction=3D*/false, Eq=
ualLoc);
+  ExprResult Init =3D ParseCXXMemberInitializer(MI.Field, /*IsFunction=3D*=
/false,=20
+                                              EqualLoc);
=20
   Actions.ActOnCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.releas=
e());
=20
@@ -596,6 +609,7 @@
     Toks.push_back(Tok);
     ConsumeToken();
   }
+  bool ReadInitializer =3D false;
   if (Tok.is(tok::colon)) {
     // Initializers can contain braces too.
     Toks.push_back(Tok);
@@ -603,37 +617,52 @@
=20
     while (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) {
       if (Tok.is(tok::eof) || Tok.is(tok::semi))
-        return true;
+        return Diag(Tok.getLocation(), diag::err_expected_lbrace);
=20
       // Grab the identifier.
       if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks,
                                 /*StopAtSemi=3D*/true,
                                 /*ConsumeFinalToken=3D*/false))
-        return true;
+        return Diag(Tok.getLocation(), diag::err_expected_lparen);
=20
       tok::TokenKind kind =3D Tok.getKind();
       Toks.push_back(Tok);
-      if (kind =3D=3D tok::l_paren)
+      bool IsLParen =3D (kind =3D=3D tok::l_paren);
+      SourceLocation LOpen =3D Tok.getLocation();
+
+      if (IsLParen) {
         ConsumeParen();
-      else {
+      } else {
         assert(kind =3D=3D tok::l_brace && "Must be left paren or brace he=
re.");
         ConsumeBrace();
         // In C++03, this has to be the start of the function body, which
-        // means the initializer is malformed.
-        if (!getLang().CPlusPlus0x)
+        // means the initializer is malformed; we'll diagnose it later.
+        if (!getLangOpts().CPlusPlus0x)
           return false;
       }
=20
       // Grab the initializer
-      if (!ConsumeAndStoreUntil(kind =3D=3D tok::l_paren ? tok::r_paren :
-                                                       tok::r_brace,
-                                Toks, /*StopAtSemi=3D*/true))
+      if (!ConsumeAndStoreUntil(IsLParen ? tok::r_paren : tok::r_brace,
+                                Toks, /*StopAtSemi=3D*/true)) {
+        Diag(Tok, IsLParen ? diag::err_expected_rparen :
+                             diag::err_expected_rbrace);
+        Diag(LOpen, diag::note_matching) << (IsLParen ? "(" : "{");
         return true;
+      }
+
+      // Grab pack ellipsis, if present
+      if (Tok.is(tok::ellipsis)) {
+        Toks.push_back(Tok);
+        ConsumeToken();
+      }
=20
       // Grab the separating comma, if any.
       if (Tok.is(tok::comma)) {
         Toks.push_back(Tok);
         ConsumeToken();
+      } else if (Tok.isNot(tok::l_brace)) {
+        ReadInitializer =3D true;
+        break;
       }
     }
   }
@@ -641,11 +670,14 @@
   // Grab any remaining garbage to be diagnosed later. We stop when we rea=
ch a
   // brace: an opening one is the function body, while a closing one proba=
bly
   // means we've reached the end of the class.
-  if (!ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
-                            /*StopAtSemi=3D*/true, /*ConsumeFinalToken=3D*=
/false))
-    return true;
-  if(Tok.isNot(tok::l_brace))
-    return true;
+  ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks,
+                       /*StopAtSemi=3D*/true,
+                       /*ConsumeFinalToken=3D*/false);
+  if (Tok.isNot(tok::l_brace)) {
+    if (ReadInitializer)
+      return Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma);
+    return Diag(Tok.getLocation(), diag::err_expected_lbrace);
+  }
=20
   Toks.push_back(Tok);
   ConsumeBrace();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseDecl.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseDecl.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "clang/Sema/PrettyDeclStackTrace.h"
 #include "RAIIObjectsForParser.h"
 #include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringSwitch.h"
 using namespace clang;
=20
@@ -35,9 +36,11 @@
                                  Declarator::TheContext Context,
                                  AccessSpecifier AS,
                                  Decl **OwnedType) {
+  DeclSpecContext DSC =3D getDeclSpecContextFromDeclaratorContext(Context);
+
   // Parse the common declaration-specifiers piece.
   DeclSpec DS(AttrFactory);
-  ParseSpecifierQualifierList(DS, AS);
+  ParseSpecifierQualifierList(DS, AS, DSC);
   if (OwnedType)
     *OwnedType =3D DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
=20
@@ -94,6 +97,8 @@
 /// which is followed by a comma or close parenthesis, then the arguments
 /// start with that identifier; otherwise they are an expression list."
 ///
+/// GCC does not require the ',' between attribs in an attribute-list.
+///
 /// At the moment, I am not doing 2 token lookahead. I am also unaware of
 /// any attributes that don't work (based on my limited testing). Most
 /// attributes are very simple in practice. Until we find a bug, I don't s=
ee
@@ -129,14 +134,15 @@
=20
       if (Tok.is(tok::l_paren)) {
         // handle "parameterized" attributes
-        if (LateAttrs && !ClassStack.empty() &&
-            isAttributeLateParsed(*AttrName)) {
-          // Delayed parsing is only available for attributes that occur
-          // in certain locations within a class scope.
+        if (LateAttrs && isAttributeLateParsed(*AttrName)) {
           LateParsedAttribute *LA =3D
             new LateParsedAttribute(this, *AttrName, AttrNameLoc);
           LateAttrs->push_back(LA);
-          getCurrentClass().LateParsedDeclarations.push_back(LA);
+
+          // Attributes in a class are parsed at the end of the class, alo=
ng
+          // with other late-parsed declarations.
+          if (!ClassStack.empty())
+            getCurrentClass().LateParsedDeclarations.push_back(LA);
=20
           // consume everything up to and including the matching right par=
ens
           ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
@@ -187,106 +193,88 @@
=20
   ConsumeParen(); // ignore the left paren loc for now
=20
-  if (Tok.is(tok::identifier)) {
-    IdentifierInfo *ParmName =3D Tok.getIdentifierInfo();
-    SourceLocation ParmLoc =3D ConsumeToken();
-
-    if (Tok.is(tok::r_paren)) {
-      // __attribute__(( mode(byte) ))
-      SourceLocation RParen =3D ConsumeParen();
+  IdentifierInfo *ParmName =3D 0;
+  SourceLocation ParmLoc;
+  bool BuiltinType =3D false;
+
+  switch (Tok.getKind()) {
+  case tok::kw_char:
+  case tok::kw_wchar_t:
+  case tok::kw_char16_t:
+  case tok::kw_char32_t:
+  case tok::kw_bool:
+  case tok::kw_short:
+  case tok::kw_int:
+  case tok::kw_long:
+  case tok::kw___int64:
+  case tok::kw___int128:
+  case tok::kw_signed:
+  case tok::kw_unsigned:
+  case tok::kw_float:
+  case tok::kw_double:
+  case tok::kw_void:
+  case tok::kw_typeof:
+    // __attribute__(( vec_type_hint(char) ))
+    // FIXME: Don't just discard the builtin type token.
+    ConsumeToken();
+    BuiltinType =3D true;
+    break;
+
+  case tok::identifier:
+    ParmName =3D Tok.getIdentifierInfo();
+    ParmLoc =3D ConsumeToken();
+    break;
+
+  default:
+    break;
+  }
+
+  ExprVector ArgExprs(Actions);
+
+  if (!BuiltinType &&
+      (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
+    // Eat the comma.
+    if (ParmLoc.isValid())
+      ConsumeToken();
+
+    // Parse the non-empty comma-separated list of expressions.
+    while (1) {
+      ExprResult ArgExpr(ParseAssignmentExpression());
+      if (ArgExpr.isInvalid()) {
+        SkipUntil(tok::r_paren);
+        return;
+      }
+      ArgExprs.push_back(ArgExpr.release());
+      if (Tok.isNot(tok::comma))
+        break;
+      ConsumeToken(); // Eat the comma, move to the next argument
+    }
+  }
+  else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
+    if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
+                          tok::greater)) {
+      while (Tok.is(tok::identifier)) {
+        ConsumeToken();
+        if (Tok.is(tok::greater))
+          break;
+        if (Tok.is(tok::comma)) {
+          ConsumeToken();
+          continue;
+        }
+      }
+      if (Tok.isNot(tok::greater))
+        Diag(Tok, diag::err_iboutletcollection_with_protocol);
+      SkipUntil(tok::r_paren, false, true); // skip until ')'
+    }
+  }
+
+  SourceLocation RParen =3D Tok.getLocation();
+  if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
+    AttributeList *attr =3D
       Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrName=
Loc,
-                   ParmName, ParmLoc, 0, 0);
-    } else if (Tok.is(tok::comma)) {
-      ConsumeToken();
-      // __attribute__(( format(printf, 1, 2) ))
-      ExprVector ArgExprs(Actions);
-      bool ArgExprsOk =3D true;
-
-      // now parse the non-empty comma separated list of expressions
-      while (1) {
-        ExprResult ArgExpr(ParseAssignmentExpression());
-        if (ArgExpr.isInvalid()) {
-          ArgExprsOk =3D false;
-          SkipUntil(tok::r_paren);
-          break;
-        } else {
-          ArgExprs.push_back(ArgExpr.release());
-        }
-        if (Tok.isNot(tok::comma))
-          break;
-        ConsumeToken(); // Eat the comma, move to the next argument
-      }
-      if (ArgExprsOk && Tok.is(tok::r_paren)) {
-        SourceLocation RParen =3D ConsumeParen();
-        Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrNa=
meLoc,
-                     ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
-      }
-    }
-  } else { // not an identifier
-    switch (Tok.getKind()) {
-    case tok::r_paren: {
-    // parse a possibly empty comma separated list of expressions
-      // __attribute__(( nonnull() ))
-      SourceLocation RParen =3D ConsumeParen();
-      Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrName=
Loc,
-                   0, SourceLocation(), 0, 0);
-      break;
-    }
-    case tok::kw_char:
-    case tok::kw_wchar_t:
-    case tok::kw_char16_t:
-    case tok::kw_char32_t:
-    case tok::kw_bool:
-    case tok::kw_short:
-    case tok::kw_int:
-    case tok::kw_long:
-    case tok::kw___int64:
-    case tok::kw_signed:
-    case tok::kw_unsigned:
-    case tok::kw_float:
-    case tok::kw_double:
-    case tok::kw_void:
-    case tok::kw_typeof: {
-      // If it's a builtin type name, eat it and expect a rparen
-      // __attribute__(( vec_type_hint(char) ))
-      SourceLocation EndLoc =3D ConsumeToken();
-      if (Tok.is(tok::r_paren))
-        EndLoc =3D ConsumeParen();
-      AttributeList *attr
-        =3D Attrs.addNew(AttrName, SourceRange(AttrNameLoc, EndLoc), 0,
-                       AttrNameLoc, 0, SourceLocation(), 0, 0);
-      if (attr->getKind() =3D=3D AttributeList::AT_IBOutletCollection)
-        Diag(Tok, diag::err_iboutletcollection_builtintype);
-      break;
-    }
-    default:
-      // __attribute__(( aligned(16) ))
-      ExprVector ArgExprs(Actions);
-      bool ArgExprsOk =3D true;
-
-      // now parse the list of expressions
-      while (1) {
-        ExprResult ArgExpr(ParseAssignmentExpression());
-        if (ArgExpr.isInvalid()) {
-          ArgExprsOk =3D false;
-          SkipUntil(tok::r_paren);
-          break;
-        } else {
-          ArgExprs.push_back(ArgExpr.release());
-        }
-        if (Tok.isNot(tok::comma))
-          break;
-        ConsumeToken(); // Eat the comma, move to the next argument
-      }
-      // Match the ')'.
-      if (ArgExprsOk && Tok.is(tok::r_paren)) {
-        SourceLocation RParen =3D ConsumeParen();
-        Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0,
-                     AttrNameLoc, 0, SourceLocation(),
-                     ArgExprs.take(), ArgExprs.size());
-      }
-      break;
-    }
+                   ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size());
+    if (BuiltinType && attr->getKind() =3D=3D AttributeList::AT_iboutletco=
llection)
+      Diag(Tok, diag::err_iboutletcollection_builtintype);
   }
 }
=20
@@ -450,7 +438,7 @@
   // are stored in the numeric constant. We utilize a quirk of the
   // lexer, which is that it handles something like 1.2.3 as a single
   // numeric constant, rather than two separate tokens.
-  llvm::SmallString<512> Buffer;
+  SmallString<512> Buffer;
   Buffer.resize(Tok.getLength()+1);
   const char *ThisTokBegin =3D &Buffer[0];
=20
@@ -539,7 +527,7 @@
 /// \brief Parse the contents of the "availability" attribute.
 ///
 /// availability-attribute:
-///   'availability' '(' platform ',' version-arg-list ')'
+///   'availability' '(' platform ',' version-arg-list, opt-message')'
 ///
 /// platform:
 ///   identifier
@@ -551,8 +539,10 @@
 /// version-arg:
 ///   'introduced' '=3D' version
 ///   'deprecated' '=3D' version
-///   'removed' =3D version
+///   'obsoleted' =3D version
 ///   'unavailable'
+/// opt-message:
+///   'message' '=3D' <string>
 void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
                                         SourceLocation AvailabilityLoc,
                                         ParsedAttributes &attrs,
@@ -562,6 +552,7 @@
=20
   enum { Introduced, Deprecated, Obsoleted, Unknown };
   AvailabilityChange Changes[Unknown];
+  ExprResult MessageExpr;
=20
   // Opening '('.
   BalancedDelimiterTracker T(*this, tok::l_paren);
@@ -590,6 +581,7 @@
     Ident_deprecated =3D PP.getIdentifierInfo("deprecated");
     Ident_obsoleted =3D PP.getIdentifierInfo("obsoleted");
     Ident_unavailable =3D PP.getIdentifierInfo("unavailable");
+    Ident_message =3D PP.getIdentifierInfo("message");
   }
=20
   // Parse the set of introductions/deprecations/removals.
@@ -616,7 +608,7 @@
       ConsumeToken();
       continue;
     }=20
-
+   =20
     if (Tok.isNot(tok::equal)) {
       Diag(Tok, diag::err_expected_equal_after)
         << Keyword;
@@ -624,6 +616,15 @@
       return;
     }
     ConsumeToken();
+    if (Keyword =3D=3D Ident_message) {
+      if (!isTokenStringLiteral()) {
+        Diag(Tok, diag::err_expected_string_literal);
+        SkipUntil(tok::r_paren);
+        return;
+      }
+      MessageExpr =3D ParseStringLiteralExpression();
+      break;
+    }
    =20
     SourceRange VersionRange;
     VersionTuple Version =3D ParseVersionTuple(VersionRange);
@@ -694,12 +695,13 @@
   // Record this attribute
   attrs.addNew(&Availability,=20
                SourceRange(AvailabilityLoc, T.getCloseLocation()),=20
-               0, SourceLocation(),
+               0, AvailabilityLoc,
                Platform, PlatformLoc,
                Changes[Introduced],
                Changes[Deprecated],
                Changes[Obsoleted],=20
-               UnavailableLoc, false, false);
+               UnavailableLoc, MessageExpr.take(),
+               false, false);
 }
=20
=20
@@ -713,7 +715,7 @@
 }
=20
 void Parser::LateParsedAttribute::ParseLexedAttributes() {
-  Self->ParseLexedAttribute(*this);
+  Self->ParseLexedAttribute(*this, true, false);
 }
=20
 /// Wrapper class which calls ParseLexedAttribute, after setting up the
@@ -733,17 +735,39 @@
   ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
   ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
=20
+  // Enter the scope of nested classes
+  if (!AlreadyHasClassScope)
+    Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
+                                                Class.TagOrTemplate);
+
   for (unsigned i =3D 0, ni =3D Class.LateParsedDeclarations.size(); i < n=
i; ++i) {
     Class.LateParsedDeclarations[i]->ParseLexedAttributes();
   }
+
+  if (!AlreadyHasClassScope)
+    Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
+                                                 Class.TagOrTemplate);
 }
=20
+
+/// \brief Parse all attributes in LAs, and attach them to Decl D.
+void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
+                                     bool EnterScope, bool OnDefinition) {
+  for (unsigned i =3D 0, ni =3D LAs.size(); i < ni; ++i) {
+    LAs[i]->addDecl(D);
+    ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
+  }
+  LAs.clear();
+}
+
+
 /// \brief Finish parsing an attribute for which parsing was delayed.
 /// This will be called at the end of parsing a class declaration
 /// for each LateParsedAttribute. We consume the saved tokens and
 /// create an attribute with the arguments filled in. We add this=20
 /// to the Attribute list for the decl.
-void Parser::ParseLexedAttribute(LateParsedAttribute &LA) {
+void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
+                                 bool EnterScope, bool OnDefinition) {
   // Save the current token position.
   SourceLocation OrigLoc =3D Tok.getLocation();
=20
@@ -754,36 +778,50 @@
   // Consume the previously pushed token.
   ConsumeAnyToken();
=20
+  if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
+    Diag(Tok, diag::warn_attribute_on_function_definition)
+      << LA.AttrName.getName();
+  }
+
   ParsedAttributes Attrs(AttrFactory);
   SourceLocation endLoc;
=20
-  // If the Decl is templatized, add template parameters to scope.
-  bool HasTemplateScope =3D LA.D && LA.D->isTemplateDecl();
-  ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
-  if (HasTemplateScope)
-    Actions.ActOnReenterTemplateScope(Actions.CurScope, LA.D);
-
-  // If the Decl is on a function, add function parameters to the scope.
-  bool HasFunctionScope =3D LA.D && LA.D->isFunctionOrFunctionTemplate();
-  ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunctionSco=
pe);
-  if (HasFunctionScope)
-    Actions.ActOnReenterFunctionContext(Actions.CurScope, LA.D);
-
-  ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
-
-  if (HasFunctionScope) {
-    Actions.ActOnExitFunctionContext();
-    FnScope.Exit();  // Pop scope, and remove Decls from IdResolver
+  if (LA.Decls.size() =3D=3D 1) {
+    Decl *D =3D LA.Decls[0];
+
+    // If the Decl is templatized, add template parameters to scope.
+    bool HasTemplateScope =3D EnterScope && D->isTemplateDecl();
+    ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope=
);
+    if (HasTemplateScope)
+      Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
+
+    // If the Decl is on a function, add function parameters to the scope.
+    bool HasFunctionScope =3D EnterScope && D->isFunctionOrFunctionTemplat=
e();
+    ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunctionS=
cope);
+    if (HasFunctionScope)
+      Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
+
+    ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
+
+    if (HasFunctionScope) {
+      Actions.ActOnExitFunctionContext();
+      FnScope.Exit();  // Pop scope, and remove Decls from IdResolver
+    }
+    if (HasTemplateScope) {
+      TempScope.Exit();
+    }
+  } else if (LA.Decls.size() > 0) {
+    // If there are multiple decls, then the decl cannot be within the
+    // function scope.
+    ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
+  } else {
+    Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
   }
-  if (HasTemplateScope) {
-    TempScope.Exit();
+
+  for (unsigned i =3D 0, ni =3D LA.Decls.size(); i < ni; ++i) {
+    Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
   }
=20
-  // Late parsed attributes must be attached to Decls by hand.  If the
-  // LA.D is not set, then this was not done properly.
-  assert(LA.D && "No decl attached to late parsed attribute");
-  Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.D, Attrs);
-
   if (Tok.getLocation() !=3D OrigLoc) {
     // Due to a parsing error, we either went over the cached tokens or
     // there are still cached tokens left, so we skip the leftover tokens.
@@ -792,7 +830,7 @@
     if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
                                                         OrigLoc))
     while (Tok.getLocation() !=3D OrigLoc && Tok.isNot(tok::eof))
-        ConsumeAnyToken();
+      ConsumeAnyToken();
   }
 }
=20
@@ -846,7 +884,7 @@
   bool ArgExprsOk =3D true;
  =20
   // now parse the list of expressions
-  while (1) {
+  while (Tok.isNot(tok::r_paren)) {
     ExprResult ArgExpr(ParseAssignmentExpression());
     if (ArgExpr.isInvalid()) {
       ArgExprsOk =3D false;
@@ -868,6 +906,40 @@
     *EndLoc =3D T.getCloseLocation();
 }
=20
+/// DiagnoseProhibitedCXX11Attribute - We have found the opening square br=
ackets
+/// of a C++11 attribute-specifier in a location where an attribute is not
+/// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose=
 this
+/// situation.
+///
+/// \return \c true if we skipped an attribute-like chunk of tokens, \c fa=
lse if
+/// this doesn't appear to actually be an attribute-specifier, and the cal=
ler
+/// should try to parse it.
+bool Parser::DiagnoseProhibitedCXX11Attribute() {
+  assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
+
+  switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
+  case CAK_NotAttributeSpecifier:
+    // No diagnostic: we're in Obj-C++11 and this is not actually an attri=
bute.
+    return false;
+
+  case CAK_InvalidAttributeSpecifier:
+    Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
+    return false;
+
+  case CAK_AttributeSpecifier:
+    // Parse and discard the attributes.
+    SourceLocation BeginLoc =3D ConsumeBracket();
+    ConsumeBracket();
+    SkipUntil(tok::r_square, /*StopAtSemi*/ false);
+    assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
+    SourceLocation EndLoc =3D ConsumeBracket();
+    Diag(BeginLoc, diag::err_attributes_not_allowed)
+      << SourceRange(BeginLoc, EndLoc);
+    return true;
+  }
+  llvm_unreachable("All cases handled above.");
+}
+
 void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs=
) {
   Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
     << attrs.Range;
@@ -886,7 +958,7 @@
 /// [C++]   namespace-definition
 /// [C++]   using-directive
 /// [C++]   using-declaration
-/// [C++0x/C1X] static_assert-declaration
+/// [C++0x/C11] static_assert-declaration
 ///         others... [FIXME]
 ///
 Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
@@ -908,7 +980,7 @@
     break;
   case tok::kw_inline:
     // Could be the start of an inline namespace. Allowed as an ext in C++=
03.
-    if (getLang().CPlusPlus && NextToken().is(tok::kw_namespace)) {
+    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
       ProhibitAttributes(attrs);
       SourceLocation InlineLoc =3D ConsumeToken();
       SingleDecl =3D ParseNamespace(Context, DeclEnd, InlineLoc);
@@ -965,10 +1037,7 @@
=20
   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
                              getDeclSpecContextFromDeclaratorContext(Conte=
xt));
-  StmtResult R =3D Actions.ActOnVlaStmt(DS);
-  if (R.isUsable())
-    Stmts.push_back(R.release());
- =20
+
   // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
   // declaration-specifiers init-declarator-list[opt] ';'
   if (Tok.is(tok::semi)) {
@@ -982,6 +1051,133 @@
   return ParseDeclGroup(DS, Context, /*FunctionDefs=3D*/ false, &DeclEnd, =
FRI); =20
 }
=20
+/// Returns true if this might be the start of a declarator, or a common t=
ypo
+/// for a declarator.
+bool Parser::MightBeDeclarator(unsigned Context) {
+  switch (Tok.getKind()) {
+  case tok::annot_cxxscope:
+  case tok::annot_template_id:
+  case tok::caret:
+  case tok::code_completion:
+  case tok::coloncolon:
+  case tok::ellipsis:
+  case tok::kw___attribute:
+  case tok::kw_operator:
+  case tok::l_paren:
+  case tok::star:
+    return true;
+
+  case tok::amp:
+  case tok::ampamp:
+    return getLangOpts().CPlusPlus;
+
+  case tok::l_square: // Might be an attribute on an unnamed bit-field.
+    return Context =3D=3D Declarator::MemberContext && getLangOpts().CPlus=
Plus0x &&
+           NextToken().is(tok::l_square);
+
+  case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
+    return Context =3D=3D Declarator::MemberContext || getLangOpts().CPlus=
Plus;
+
+  case tok::identifier:
+    switch (NextToken().getKind()) {
+    case tok::code_completion:
+    case tok::coloncolon:
+    case tok::comma:
+    case tok::equal:
+    case tok::equalequal: // Might be a typo for '=3D'.
+    case tok::kw_alignas:
+    case tok::kw_asm:
+    case tok::kw___attribute:
+    case tok::l_brace:
+    case tok::l_paren:
+    case tok::l_square:
+    case tok::less:
+    case tok::r_brace:
+    case tok::r_paren:
+    case tok::r_square:
+    case tok::semi:
+      return true;
+
+    case tok::colon:
+      // At namespace scope, 'identifier:' is probably a typo for 'identif=
ier::'
+      // and in block scope it's probably a label. Inside a class definiti=
on,
+      // this is a bit-field.
+      return Context =3D=3D Declarator::MemberContext ||
+             (getLangOpts().CPlusPlus && Context =3D=3D Declarator::FileCo=
ntext);
+
+    case tok::identifier: // Possible virt-specifier.
+      return getLangOpts().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken()=
);
+
+    default:
+      return false;
+    }
+
+  default:
+    return false;
+  }
+}
+
+/// Skip until we reach something which seems like a sensible place to pick
+/// up parsing after a malformed declaration. This will sometimes stop soo=
ner
+/// than SkipUntil(tok::r_brace) would, but will never stop later.
+void Parser::SkipMalformedDecl() {
+  while (true) {
+    switch (Tok.getKind()) {
+    case tok::l_brace:
+      // Skip until matching }, then stop. We've probably skipped over
+      // a malformed class or function definition or similar.
+      ConsumeBrace();
+      SkipUntil(tok::r_brace, /*StopAtSemi*/false);
+      if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try=
)) {
+        // This declaration isn't over yet. Keep skipping.
+        continue;
+      }
+      if (Tok.is(tok::semi))
+        ConsumeToken();
+      return;
+
+    case tok::l_square:
+      ConsumeBracket();
+      SkipUntil(tok::r_square, /*StopAtSemi*/false);
+      continue;
+
+    case tok::l_paren:
+      ConsumeParen();
+      SkipUntil(tok::r_paren, /*StopAtSemi*/false);
+      continue;
+
+    case tok::r_brace:
+      return;
+
+    case tok::semi:
+      ConsumeToken();
+      return;
+
+    case tok::kw_inline:
+      // 'inline namespace' at the start of a line is almost certainly
+      // a good place to pick back up parsing.
+      if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace))
+        return;
+      break;
+
+    case tok::kw_namespace:
+      // 'namespace' at the start of a line is almost certainly a good
+      // place to pick back up parsing.
+      if (Tok.isAtStartOfLine())
+        return;
+      break;
+
+    case tok::eof:
+      return;
+
+    default:
+      break;
+    }
+
+    ConsumeAnyToken();
+  }
+}
+
 /// ParseDeclGroup - Having concluded that this is either a function
 /// definition or a group of object declarations, actually parse the
 /// result.
@@ -996,13 +1192,16 @@
=20
   // Bail out if the first declarator didn't seem well-formed.
   if (!D.hasName() && !D.mayOmitIdentifier()) {
-    // Skip until ; or }.
-    SkipUntil(tok::r_brace, true, true);
-    if (Tok.is(tok::semi))
-      ConsumeToken();
+    SkipMalformedDecl();
     return DeclGroupPtrTy();
   }
=20
+  // Save late-parsed attributes for now; they need to be parsed in the
+  // appropriate function scope after the function Decl has been construct=
ed.
+  LateParsedAttrList LateParsedAttrs;
+  if (D.isFunctionDeclarator())
+    MaybeParseGNUAttributes(D, &LateParsedAttrs);
+
   // Check to see if we have a function *definition* which must have a bod=
y.
   if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
       // Look at the next token to make sure that this isn't a function
@@ -1018,7 +1217,8 @@
         DS.ClearStorageClassSpecs();
       }
=20
-      Decl *TheDecl =3D ParseFunctionDefinition(D);
+      Decl *TheDecl =3D
+        ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
       return Actions.ConvertDeclToDeclGroup(TheDecl);
     }
    =20
@@ -1035,7 +1235,7 @@
     }
   }
=20
-  if (ParseAttributesAfterDeclarator(D))
+  if (ParseAsmAttributesAfterDeclarator(D))
     return DeclGroupPtrTy();
=20
   // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, =
we
@@ -1050,23 +1250,38 @@
     Decl *ThisDecl =3D Actions.ActOnDeclarator(getCurScope(), D);
     Actions.ActOnCXXForRangeDecl(ThisDecl);
     Actions.FinalizeDeclaration(ThisDecl);
+    D.complete(ThisDecl);
     return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1=
);
   }
=20
   SmallVector<Decl *, 8> DeclsInGroup;
   Decl *FirstDecl =3D ParseDeclarationAfterDeclaratorAndAttributes(D);
+  if (LateParsedAttrs.size() > 0)
+    ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
   D.complete(FirstDecl);
   if (FirstDecl)
     DeclsInGroup.push_back(FirstDecl);
=20
+  bool ExpectSemi =3D Context !=3D Declarator::ForContext;
+
   // If we don't have a comma, it is either the end of the list (a ';') or=
 an
   // error, bail out.
   while (Tok.is(tok::comma)) {
-    // Consume the comma.
-    ConsumeToken();
+    SourceLocation CommaLoc =3D ConsumeToken();
+
+    if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)=
) {
+      // This comma was followed by a line-break and something which can't=
 be
+      // the start of a declarator. The comma was probably a typo for a
+      // semicolon.
+      Diag(CommaLoc, diag::err_expected_semi_declaration)
+        << FixItHint::CreateReplacement(CommaLoc, ";");
+      ExpectSemi =3D false;
+      break;
+    }
=20
     // Parse the next declarator.
     D.clear();
+    D.setCommaLoc(CommaLoc);
=20
     // Accept attributes in an init-declarator.  In the first declarator i=
n a
     // declaration, these would be part of the declspec.  In subsequent
@@ -1078,17 +1293,18 @@
     MaybeParseGNUAttributes(D);
=20
     ParseDeclarator(D);
-
-    Decl *ThisDecl =3D ParseDeclarationAfterDeclarator(D);
-    D.complete(ThisDecl);
-    if (ThisDecl)
-      DeclsInGroup.push_back(ThisDecl);   =20
+    if (!D.isInvalidType()) {
+      Decl *ThisDecl =3D ParseDeclarationAfterDeclarator(D);
+      D.complete(ThisDecl);
+      if (ThisDecl)
+        DeclsInGroup.push_back(ThisDecl);  =20
+    }
   }
=20
   if (DeclEnd)
     *DeclEnd =3D Tok.getLocation();
=20
-  if (Context !=3D Declarator::ForContext &&
+  if (ExpectSemi &&
       ExpectAndConsume(tok::semi,
                        Context =3D=3D Declarator::FileContext
                          ? diag::err_invalid_token_after_toplevel_declarat=
or
@@ -1110,7 +1326,7 @@
=20
 /// Parse an optional simple-asm-expr and attributes, and attach them to a
 /// declarator. Returns true on an error.
-bool Parser::ParseAttributesAfterDeclarator(Declarator &D) {
+bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
   // If a simple-asm-expr is present, parse it.
   if (Tok.is(tok::kw_asm)) {
     SourceLocation Loc;
@@ -1152,7 +1368,7 @@
 ///
 Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
                                      const ParsedTemplateInfo &TemplateInf=
o) {
-  if (ParseAttributesAfterDeclarator(D))
+  if (ParseAsmAttributesAfterDeclarator(D))
     return 0;
=20
   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
@@ -1196,8 +1412,8 @@
     D.getDeclSpec().getTypeSpecType() =3D=3D DeclSpec::TST_auto;
=20
   // Parse declarator '=3D' initializer.
-  if (isTokenEqualOrMistypedEqualEqual(
-                               diag::err_invalid_equalequal_after_declarat=
or)) {
+  // If a '=3D=3D' or '+=3D' is found, suggest a fixit to '=3D'.
+  if (isTokenEqualOrEqualTypo()) {
     ConsumeToken();
     if (Tok.is(tok::kw_delete)) {
       if (D.isFunctionDeclarator())
@@ -1207,12 +1423,12 @@
         Diag(ConsumeToken(), diag::err_deleted_non_function);
     } else if (Tok.is(tok::kw_default)) {
       if (D.isFunctionDeclarator())
-        Diag(Tok, diag::err_default_delete_in_multiple_declaration)
-          << 1 /* delete */;
+        Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declarat=
ion)
+          << 0 /* default */;
       else
         Diag(ConsumeToken(), diag::err_default_special_members);
     } else {
-      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
+      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
         EnterScope(0);
         Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
       }
@@ -1225,7 +1441,7 @@
      =20
       ExprResult Init(ParseInitializer());
=20
-      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
+      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
         ExitScope();
       }
@@ -1245,7 +1461,7 @@
     ExprVector Exprs(Actions);
     CommaLocsTy CommaLocs;
=20
-    if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
+    if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
       EnterScope(0);
       Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
     }
@@ -1253,7 +1469,7 @@
     if (ParseExpressionList(Exprs, CommaLocs)) {
       SkipUntil(tok::r_paren);
=20
-      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
+      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
         ExitScope();
       }
@@ -1264,18 +1480,21 @@
       assert(!Exprs.empty() && Exprs.size()-1 =3D=3D CommaLocs.size() &&
              "Unexpected number of commas!");
=20
-      if (getLang().CPlusPlus && D.getCXXScopeSpec().isSet()) {
+      if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
         Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
         ExitScope();
       }
=20
-      Actions.AddCXXDirectInitializerToDecl(ThisDecl, T.getOpenLocation(),
-                                            move_arg(Exprs),
-                                            T.getCloseLocation(),
-                                            TypeContainsAuto);
+      ExprResult Initializer =3D Actions.ActOnParenListExpr(T.getOpenLocat=
ion(),
+                                                          T.getCloseLocati=
on(),
+                                                          move_arg(Exprs));
+      Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
+                                   /*DirectInit=3D*/true, TypeContainsAuto=
);
     }
-  } else if (getLang().CPlusPlus0x && Tok.is(tok::l_brace)) {
+  } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
     // Parse C++0x braced-init-list.
+    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
+
     if (D.getCXXScopeSpec().isSet()) {
       EnterScope(0);
       Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
@@ -1309,17 +1528,24 @@
 ///          type-qualifier specifier-qualifier-list[opt]
 /// [GNU]    attributes     specifier-qualifier-list[opt]
 ///
-void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS)=
 {
+void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
+                                         DeclSpecContext DSC) {
   /// specifier-qualifier-list is a subset of declaration-specifiers.  Just
   /// parse declaration-specifiers and complain about extra stuff.
   /// TODO: diagnose attribute-specifiers and alignment-specifiers.
-  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS);
+  ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
=20
   // Validate declspec for type-name.
   unsigned Specs =3D DS.getParsedSpecifiers();
-  if (Specs =3D=3D DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
-      !DS.hasAttributes())
+  if (DSC =3D=3D DSC_type_specifier && !DS.hasTypeSpecifier()) {
+    Diag(Tok, diag::err_expected_type);
+    DS.SetTypeSpecError();
+  } else if (Specs =3D=3D DeclSpec::PQ_None && !DS.getNumProtocolQualifier=
s() &&
+             !DS.hasAttributes()) {
     Diag(Tok, diag::err_typename_requires_specqual);
+    if (!DS.hasTypeSpecifier())
+      DS.SetTypeSpecError();
+  }
=20
   // Issue diagnostic and remove storage class if present.
   if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
@@ -1340,6 +1566,12 @@
       Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspe=
c);
     DS.ClearFunctionSpecs();
   }
+
+  // Issue diagnostic and remove constexpr specfier if present.
+  if (DS.isConstexprSpecified()) {
+    Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
+    DS.ClearConstexprSpec();
+  }
 }
=20
 /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
@@ -1378,7 +1610,7 @@
 ///
 bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
                               const ParsedTemplateInfo &TemplateInfo,
-                              AccessSpecifier AS) {
+                              AccessSpecifier AS, DeclSpecContext DSC) {
   assert(Tok.is(tok::identifier) && "should have identifier");
=20
   SourceLocation Loc =3D Tok.getLocation();
@@ -1397,8 +1629,13 @@
   assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
=20
   // Since we know that this either implicit int (which is rare) or an
-  // error, we'd do lookahead to try to do better recovery.
-  if (isValidAfterIdentifierInDeclarator(NextToken())) {
+  // error, do lookahead to try to do better recovery. This never applies =
within
+  // a type specifier.
+  // FIXME: Don't bail out here in languages with no implicit int (like
+  // C++ with no -fms-extensions). This is much more likely to be an undec=
lared
+  // type or typo than a use of implicit int.
+  if (DSC !=3D DSC_type_specifier &&
+      isValidAfterIdentifierInDeclarator(NextToken())) {
     // If this token is valid for implicit int, e.g. "static x =3D 4", then
     // we just avoid eating the identifier, so it will be parsed as the
     // identifier in the declarator.
@@ -1429,14 +1666,15 @@
=20
     if (TagName) {
       Diag(Loc, diag::err_use_of_tag_name_without_tag)
-        << Tok.getIdentifierInfo() << TagName << getLang().CPlusPlus
+        << Tok.getIdentifierInfo() << TagName << getLangOpts().CPlusPlus
         << FixItHint::CreateInsertion(Tok.getLocation(),FixitTagName);
=20
       // Parse this as a tag as if the missing tag were present.
       if (TagKind =3D=3D tok::kw_enum)
-        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
+        ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
       else
-        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS);
+        ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
+                            /*EnteringContext*/ false, DSC_normal);
       return true;
     }
   }
@@ -1470,9 +1708,7 @@
   }
=20
   // Mark this as an error.
-  const char *PrevSpec;
-  unsigned DiagID;
-  DS.SetTypeSpecType(DeclSpec::TST_error, Loc, PrevSpec, DiagID);
+  DS.SetTypeSpecError();
   DS.SetRangeEnd(Tok.getLocation());
   ConsumeToken();
=20
@@ -1493,6 +1729,8 @@
     return DSC_class;
   if (Context =3D=3D Declarator::FileContext)
     return DSC_top_level;
+  if (Context =3D=3D Declarator::TrailingReturnContext)
+    return DSC_trailing;
   return DSC_normal;
 }
=20
@@ -1501,29 +1739,36 @@
 /// FIXME: Simply returns an alignof() expression if the argument is a
 /// type. Ideally, the type should be propagated directly into Sema.
 ///
-/// [C1X/C++0x] type-id
-/// [C1X]       constant-expression
-/// [C++0x]     assignment-expression
-ExprResult Parser::ParseAlignArgument(SourceLocation Start) {
+/// [C11]   type-id
+/// [C11]   constant-expression
+/// [C++0x] type-id ...[opt]
+/// [C++0x] assignment-expression ...[opt]
+ExprResult Parser::ParseAlignArgument(SourceLocation Start,
+                                      SourceLocation &EllipsisLoc) {
+  ExprResult ER;
   if (isTypeIdInParens()) {
-    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluate=
d);
     SourceLocation TypeLoc =3D Tok.getLocation();
     ParsedType Ty =3D ParseTypeName().get();
     SourceRange TypeRange(Start, Tok.getLocation());
-    return Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, tr=
ue,
-                                                Ty.getAsOpaquePtr(), TypeR=
ange);
+    ER =3D Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, tr=
ue,
+                                               Ty.getAsOpaquePtr(), TypeRa=
nge);
   } else
-    return ParseConstantExpression();
+    ER =3D ParseConstantExpression();
+
+  if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis))
+    EllipsisLoc =3D ConsumeToken();
+
+  return ER;
 }
=20
 /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
 /// attribute to Attrs.
 ///
 /// alignment-specifier:
-/// [C1X]   '_Alignas' '(' type-id ')'
-/// [C1X]   '_Alignas' '(' constant-expression ')'
-/// [C++0x] 'alignas' '(' type-id ')'
-/// [C++0x] 'alignas' '(' assignment-expression ')'
+/// [C11]   '_Alignas' '(' type-id ')'
+/// [C11]   '_Alignas' '(' constant-expression ')'
+/// [C++0x] 'alignas' '(' type-id ...[opt] ')'
+/// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')'
 void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
                                      SourceLocation *endLoc) {
   assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
@@ -1536,7 +1781,8 @@
   if (T.expectAndConsume(diag::err_expected_lparen))
     return;
=20
-  ExprResult ArgExpr =3D ParseAlignArgument(T.getOpenLocation());
+  SourceLocation EllipsisLoc;
+  ExprResult ArgExpr =3D ParseAlignArgument(T.getOpenLocation(), EllipsisL=
oc);
   if (ArgExpr.isInvalid()) {
     SkipUntil(tok::r_paren);
     return;
@@ -1546,6 +1792,12 @@
   if (endLoc)
     *endLoc =3D T.getCloseLocation();
=20
+  // FIXME: Handle pack-expansions here.
+  if (EllipsisLoc.isValid()) {
+    Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported);
+    return;
+  }
+
   ExprVector ArgExprs(Actions);
   ArgExprs.push_back(ArgExpr.release());
   Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc,
@@ -1557,7 +1809,7 @@
 ///         storage-class-specifier declaration-specifiers[opt]
 ///         type-specifier declaration-specifiers[opt]
 /// [C99]   function-specifier declaration-specifiers[opt]
-/// [C1X]   alignment-specifier declaration-specifiers[opt]
+/// [C11]   alignment-specifier declaration-specifiers[opt]
 /// [GNU]   attributes declaration-specifiers[opt]
 /// [Clang] '__module_private__' declaration-specifiers[opt]
 ///
@@ -1581,12 +1833,14 @@
 void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
                                         const ParsedTemplateInfo &Template=
Info,
                                         AccessSpecifier AS,
-                                        DeclSpecContext DSContext) {=20
+                                        DeclSpecContext DSContext,
+                                        LateParsedAttrList *LateAttrs) {
   if (DS.getSourceRange().isInvalid()) {
     DS.SetRangeStart(Tok.getLocation());
     DS.SetRangeEnd(Tok.getLocation());
   }
  =20
+  bool EnteringContext =3D (DSContext =3D=3D DSC_class || DSContext =3D=3D=
 DSC_top_level);
   while (1) {
     bool isInvalid =3D false;
     const char *PrevSpec =3D 0;
@@ -1631,7 +1885,7 @@
                                     : Sema::PCC_Template;
       else if (DSContext =3D=3D DSC_class)
         CCC =3D Sema::PCC_Class;
-      else if (ObjCImpDecl)
+      else if (CurParsedObjCImpl)
         CCC =3D Sema::PCC_ObjCImplementation;
      =20
       Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
@@ -1755,6 +2009,7 @@
                                                Next.getLocation(),
                                                getCurScope(), &SS,
                                                false, false, ParsedType(),
+                                               /*IsCtorOrDtorName=3D*/fals=
e,
                                                /*NonTrivialSourceInfo=3D*/=
true);
=20
       // If the referenced identifier is not a type, then this declspec is
@@ -1763,7 +2018,7 @@
       // typename.
       if (TypeRep =3D=3D 0) {
         ConsumeToken();   // Eat the scope spec so the identifier is curre=
nt.
-        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS)) continue;
+        if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) contin=
ue;
         goto DoneWithDeclSpec;
       }
=20
@@ -1798,7 +2053,7 @@
       // Objective-C supports syntax of the form 'id<proto1,proto2>' where=
 'id'
       // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
       // Objective-C interface.=20
-      if (Tok.is(tok::less) && getLang().ObjC1)
+      if (Tok.is(tok::less) && getLangOpts().ObjC1)
         ParseObjCProtocolQualifiers(DS);
      =20
       continue;
@@ -1823,10 +2078,11 @@
       goto DoneWithDeclSpec;
        =20
       // typedef-name
+    case tok::kw_decltype:
     case tok::identifier: {
       // In C++, check to see if this is a scope specifier like foo::bar::=
, if
       // so handle it as such.  This is important for ctor parsing.
-      if (getLang().CPlusPlus) {
+      if (getLangOpts().CPlusPlus) {
         if (TryAnnotateCXXScopeToken(true)) {
           if (!DS.hasTypeSpecifier())
             DS.SetTypeSpecError();
@@ -1846,7 +2102,6 @@
       if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
         break;
=20
-      // It has to be available as a typedef too!
       ParsedType TypeRep =3D
         Actions.getTypeName(*Tok.getIdentifierInfo(),
                             Tok.getLocation(), getCurScope());
@@ -1854,13 +2109,13 @@
       // If this is not a typedef name, don't parse it as part of the decl=
spec,
       // it must be an implicit int or an error.
       if (!TypeRep) {
-        if (ParseImplicitInt(DS, 0, TemplateInfo, AS)) continue;
+        if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue;
         goto DoneWithDeclSpec;
       }
=20
       // If we're in a context where the identifier could be a class name,
       // check whether this is a constructor declaration.
-      if (getLang().CPlusPlus && DSContext =3D=3D DSC_class &&
+      if (getLangOpts().CPlusPlus && DSContext =3D=3D DSC_class &&
           Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope=
()) &&
           isConstructorDeclarator())
         goto DoneWithDeclSpec;
@@ -1876,7 +2131,7 @@
       // Objective-C supports syntax of the form 'id<proto1,proto2>' where=
 'id'
       // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
       // Objective-C interface.=20
-      if (Tok.is(tok::less) && getLang().ObjC1)
+      if (Tok.is(tok::less) && getLangOpts().ObjC1)
         ParseObjCProtocolQualifiers(DS);
      =20
       // Need to support trailing type qualifiers (e.g. "id<p> const").
@@ -1896,7 +2151,7 @@
       // If we're in a context where the template-id could be a
       // constructor name or specialization, check whether this is a
       // constructor declaration.
-      if (getLang().CPlusPlus && DSContext =3D=3D DSC_class &&
+      if (getLangOpts().CPlusPlus && DSContext =3D=3D DSC_class &&
           Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
           isConstructorDeclarator())
         goto DoneWithDeclSpec;
@@ -1909,7 +2164,7 @@
=20
     // GNU attributes support.
     case tok::kw___attribute:
-      ParseGNUAttributes(DS.getAttributes());
+      ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
       continue;
=20
     // Microsoft declspec support.
@@ -1965,7 +2220,7 @@
                                          PrevSpec, DiagID);
       break;
     case tok::kw_auto:
-      if (getLang().CPlusPlus0x) {
+      if (getLangOpts().CPlusPlus0x) {
         if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
           isInvalid =3D DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto=
, Loc,
                                              PrevSpec, DiagID);
@@ -2004,8 +2259,8 @@
=20
     // alignment-specifier
     case tok::kw__Alignas:
-      if (!getLang().C1X)
-        Diag(Tok, diag::ext_c1x_alignas);
+      if (!getLangOpts().C11)
+        Diag(Tok, diag::ext_c11_alignas);
       ParseAlignmentSpecifier(DS.getAttributes());
       continue;
=20
@@ -2075,10 +2330,14 @@
       isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
                                      DiagID);
       break;
-     case tok::kw_half:
-       isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
-                                      DiagID);
-       break;
+    case tok::kw___int128:
+      isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
+                                     DiagID);
+      break;
+    case tok::kw_half:
+      isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
+                                     DiagID);
+      break;
     case tok::kw_float:
       isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
                                      DiagID);
@@ -2143,28 +2402,29 @@
     case tok::kw_union: {
       tok::TokenKind Kind =3D Tok.getKind();
       ConsumeToken();
-      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS);
+      ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
+                          EnteringContext, DSContext);
       continue;
     }
=20
     // enum-specifier:
     case tok::kw_enum:
       ConsumeToken();
-      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS);
+      ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
       continue;
=20
     // cv-qualifier:
     case tok::kw_const:
       isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, Diag=
ID,
-                                 getLang());
+                                 getLangOpts());
       break;
     case tok::kw_volatile:
       isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, D=
iagID,
-                                 getLang());
+                                 getLangOpts());
       break;
     case tok::kw_restrict:
       isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, D=
iagID,
-                                 getLang());
+                                 getLangOpts());
       break;
=20
     // C++ typename-specifier:
@@ -2182,7 +2442,7 @@
       ParseTypeofSpecifier(DS);
       continue;
=20
-    case tok::kw_decltype:
+    case tok::annot_decltype:
       ParseDecltypeSpecifier(DS);
       continue;
=20
@@ -2196,7 +2456,7 @@
=20
     // OpenCL qualifiers:
     case tok::kw_private:=20
-      if (!getLang().OpenCL)
+      if (!getLangOpts().OpenCL)
         goto DoneWithDeclSpec;
     case tok::kw___private:
     case tok::kw___global:
@@ -2212,7 +2472,7 @@
       // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
       // "id<SomeProtocol>".  This is hopelessly old fashioned and dangero=
us,
       // but we support it.
-      if (DS.hasTypeSpecifier() || !getLang().ObjC1)
+      if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
         goto DoneWithDeclSpec;
=20
       if (!ParseObjCProtocolQualifiers(DS))
@@ -2242,299 +2502,6 @@
   }
 }
=20
-/// ParseOptionalTypeSpecifier - Try to parse a single type-specifier. We
-/// primarily follow the C++ grammar with additions for C99 and GNU,
-/// which together subsume the C grammar. Note that the C++
-/// type-specifier also includes the C type-qualifier (for const,
-/// volatile, and C99 restrict). Returns true if a type-specifier was
-/// found (and parsed), false otherwise.
-///
-///       type-specifier: [C++ 7.1.5]
-///         simple-type-specifier
-///         class-specifier
-///         enum-specifier
-///         elaborated-type-specifier  [TODO]
-///         cv-qualifier
-///
-///       cv-qualifier: [C++ 7.1.5.1]
-///         'const'
-///         'volatile'
-/// [C99]   'restrict'
-///
-///       simple-type-specifier: [ C++ 7.1.5.2]
-///         '::'[opt] nested-name-specifier[opt] type-name [TODO]
-///         '::'[opt] nested-name-specifier 'template' template-id [TODO]
-///         'char'
-///         'wchar_t'
-///         'bool'
-///         'short'
-///         'int'
-///         'long'
-///         'signed'
-///         'unsigned'
-///         'float'
-///         'double'
-///         'void'
-/// [C99]   '_Bool'
-/// [C99]   '_Complex'
-/// [C99]   '_Imaginary'  // Removed in TC2?
-/// [GNU]   '_Decimal32'
-/// [GNU]   '_Decimal64'
-/// [GNU]   '_Decimal128'
-/// [GNU]   typeof-specifier
-/// [OBJC]  class-name objc-protocol-refs[opt]    [TODO]
-/// [OBJC]  typedef-name objc-protocol-refs[opt]  [TODO]
-/// [C++0x] 'decltype' ( expression )
-/// [AltiVec] '__vector'
-bool Parser::ParseOptionalTypeSpecifier(DeclSpec &DS, bool& isInvalid,
-                                        const char *&PrevSpec,
-                                        unsigned &DiagID,
-                                        const ParsedTemplateInfo &Template=
Info,
-                                        bool SuppressDeclarations) {
-  SourceLocation Loc =3D Tok.getLocation();
-
-  switch (Tok.getKind()) {
-  case tok::identifier:   // foo::bar
-    // If we already have a type specifier, this identifier is not a type.
-    if (DS.getTypeSpecType() !=3D DeclSpec::TST_unspecified ||
-        DS.getTypeSpecWidth() !=3D DeclSpec::TSW_unspecified ||
-        DS.getTypeSpecSign() !=3D DeclSpec::TSS_unspecified)
-      return false;
-    // Check for need to substitute AltiVec keyword tokens.
-    if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
-      break;
-    // Fall through.
-  case tok::kw_typename:  // typename foo::bar
-    // Annotate typenames and C++ scope specifiers.  If we get one, just
-    // recurse to handle whatever we get.
-    if (TryAnnotateTypeOrScopeToken(/*EnteringContext=3D*/false,
-                                    /*NeedType=3D*/true))
-      return true;
-    if (Tok.is(tok::identifier))
-      return false;
-    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
-                                      TemplateInfo, SuppressDeclarations);
-  case tok::coloncolon:   // ::foo::bar
-    if (NextToken().is(tok::kw_new) ||    // ::new
-        NextToken().is(tok::kw_delete))   // ::delete
-      return false;
-
-    // Annotate typenames and C++ scope specifiers.  If we get one, just
-    // recurse to handle whatever we get.
-    if (TryAnnotateTypeOrScopeToken(/*EnteringContext=3D*/false,
-                                    /*NeedType=3D*/true))
-      return true;
-    return ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
-                                      TemplateInfo, SuppressDeclarations);
-
-  // simple-type-specifier:
-  case tok::annot_typename: {
-    if (ParsedType T =3D getTypeAnnotation(Tok)) {
-      isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_typename,
-                                     Tok.getAnnotationEndLoc(), PrevSpec,
-                                     DiagID, T);
-    } else
-      DS.SetTypeSpecError();
-    DS.SetRangeEnd(Tok.getAnnotationEndLoc());
-    ConsumeToken(); // The typename
-
-    // Objective-C supports syntax of the form 'id<proto1,proto2>' where '=
id'
-    // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
-    // Objective-C interface.  If we don't have Objective-C or a '<', this=
 is
-    // just a normal reference to a typedef name.
-    if (Tok.is(tok::less) && getLang().ObjC1)
-      ParseObjCProtocolQualifiers(DS);
-   =20
-    return true;
-  }
-
-  case tok::kw_short:
-    isInvalid =3D DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, =
DiagID);
-    break;
-  case tok::kw_long:
-    if (DS.getTypeSpecWidth() !=3D DeclSpec::TSW_long)
-      isInvalid =3D DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
-                                      DiagID);
-    else
-      isInvalid =3D DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevS=
pec,
-                                      DiagID);
-    break;
-  case tok::kw___int64:
-      isInvalid =3D DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevS=
pec,
-                                      DiagID);
-    break;
-  case tok::kw_signed:
-    isInvalid =3D DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, =
DiagID);
-    break;
-  case tok::kw_unsigned:
-    isInvalid =3D DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
-                                   DiagID);
-    break;
-  case tok::kw__Complex:
-    isInvalid =3D DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSp=
ec,
-                                      DiagID);
-    break;
-  case tok::kw__Imaginary:
-    isInvalid =3D DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, Prev=
Spec,
-                                      DiagID);
-    break;
-  case tok::kw_void:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, Di=
agID);
-    break;
-  case tok::kw_char:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, Di=
agID);
-    break;
-  case tok::kw_int:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, Dia=
gID);
-    break;
-  case tok::kw_half:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, Di=
agID);
-    break;
-  case tok::kw_float:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, D=
iagID);
-    break;
-  case tok::kw_double:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, =
DiagID);
-    break;
-  case tok::kw_wchar_t:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, D=
iagID);
-    break;
-  case tok::kw_char16_t:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, =
DiagID);
-    break;
-  case tok::kw_char32_t:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, =
DiagID);
-    break;
-  case tok::kw_bool:
-  case tok::kw__Bool:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, Di=
agID);
-    break;
-  case tok::kw__Decimal32:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpe=
c,
-                                   DiagID);
-    break;
-  case tok::kw__Decimal64:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpe=
c,
-                                   DiagID);
-    break;
-  case tok::kw__Decimal128:
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSp=
ec,
-                                   DiagID);
-    break;
-  case tok::kw___vector:
-    isInvalid =3D DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
-    break;
-  case tok::kw___pixel:
-    isInvalid =3D DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
-    break;
- =20
-  // class-specifier:
-  case tok::kw_class:
-  case tok::kw_struct:
-  case tok::kw_union: {
-    tok::TokenKind Kind =3D Tok.getKind();
-    ConsumeToken();
-    ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS_none,
-                        SuppressDeclarations);
-    return true;
-  }
-
-  // enum-specifier:
-  case tok::kw_enum:
-    ConsumeToken();
-    ParseEnumSpecifier(Loc, DS, TemplateInfo, AS_none);
-    return true;
-
-  // cv-qualifier:
-  case tok::kw_const:
-    isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec,
-                               DiagID, getLang());
-    break;
-  case tok::kw_volatile:
-    isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec,
-                               DiagID, getLang());
-    break;
-  case tok::kw_restrict:
-    isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec,
-                               DiagID, getLang());
-    break;
-
-  // GNU typeof support.
-  case tok::kw_typeof:
-    ParseTypeofSpecifier(DS);
-    return true;
-
-  // C++0x decltype support.
-  case tok::kw_decltype:
-    ParseDecltypeSpecifier(DS);
-    return true;
-
-  // C++0x type traits support.
-  case tok::kw___underlying_type:
-    ParseUnderlyingTypeSpecifier(DS);
-    return true;
-
-  case tok::kw__Atomic:
-    ParseAtomicSpecifier(DS);
-    return true;
-
-  // OpenCL qualifiers:
-  case tok::kw_private:=20
-    if (!getLang().OpenCL)
-      return false;
-  case tok::kw___private:
-  case tok::kw___global:
-  case tok::kw___local:
-  case tok::kw___constant:
-  case tok::kw___read_only:
-  case tok::kw___write_only:
-  case tok::kw___read_write:
-    ParseOpenCLQualifiers(DS);
-    break;
-
-  // C++0x auto support.
-  case tok::kw_auto:
-    // This is only called in situations where a storage-class specifier is
-    // illegal, so we can assume an auto type specifier was intended even =
in
-    // C++98. In C++98 mode, DeclSpec::Finish will produce an appropriate
-    // extension diagnostic.
-    if (!getLang().CPlusPlus)
-      return false;
-
-    isInvalid =3D DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, Di=
agID);
-    break;
-
-  case tok::kw___ptr64:
-  case tok::kw___ptr32:
-  case tok::kw___w64:
-  case tok::kw___cdecl:
-  case tok::kw___stdcall:
-  case tok::kw___fastcall:
-  case tok::kw___thiscall:
-  case tok::kw___unaligned:
-    ParseMicrosoftTypeAttributes(DS.getAttributes());
-    return true;
-
-  case tok::kw___pascal:
-    ParseBorlandTypeAttributes(DS.getAttributes());
-    return true;
-
-  default:
-    // Not a type-specifier; do nothing.
-    return false;
-  }
-
-  // If the specifier combination wasn't legal, issue a diagnostic.
-  if (isInvalid) {
-    assert(PrevSpec && "Method did not return previous specifier!");
-    // Pick between error or extwarn.
-    Diag(Tok, DiagID) << PrevSpec;
-  }
-  DS.SetRangeEnd(Tok.getLocation());
-  ConsumeToken(); // whatever we parsed above.
-  return true;
-}
-
 /// ParseStructDeclaration - Parse a struct declaration without the termin=
ating
 /// semicolon.
 ///
@@ -2574,9 +2541,11 @@
=20
   // Read struct-declarators until we find the semicolon.
   bool FirstDeclarator =3D true;
+  SourceLocation CommaLoc;
   while (1) {
     ParsingDeclRAIIObject PD(*this);
     FieldDeclarator DeclaratorInfo(DS);
+    DeclaratorInfo.D.setCommaLoc(CommaLoc);
=20
     // Attributes are only allowed here on successive declarators.
     if (!FirstDeclarator)
@@ -2612,7 +2581,7 @@
       return;
=20
     // Consume the comma.
-    ConsumeToken();
+    CommaLoc =3D ConsumeToken();
=20
     FirstDeclarator =3D false;
   }
@@ -2642,9 +2611,10 @@
=20
   // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed =
in
   // C++.
-  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
-    Diag(Tok, diag::ext_empty_struct_union)
-      << (TagType =3D=3D TST_union);
+  if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
+    Diag(Tok, diag::ext_empty_struct_union) << (TagType =3D=3D TST_union);
+    Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType =3D=3D TST=
_union);
+  }
=20
   SmallVector<Decl *, 32> FieldDecls;
=20
@@ -2742,22 +2712,25 @@
 ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
 /// [GNU]   'enum' attributes[opt] identifier[opt] '{' enumerator-list ','=
 [opt]
 ///                                                 '}' attributes[opt]
+/// [MS]    'enum' __declspec[opt] identifier[opt] '{' enumerator-list ','=
 [opt]
+///                                                 '}'
 ///         'enum' identifier
 /// [GNU]   'enum' attributes[opt] identifier
 ///
-/// [C++0x] enum-head '{' enumerator-list[opt] '}'
-/// [C++0x] enum-head '{' enumerator-list ','  '}'
+/// [C++11] enum-head '{' enumerator-list[opt] '}'
+/// [C++11] enum-head '{' enumerator-list ','  '}'
 ///
-///       enum-head: [C++0x]
-///         enum-key attributes[opt] identifier[opt] enum-base[opt]
-///         enum-key attributes[opt] nested-name-specifier identifier enum=
-base[opt]
+///       enum-head: [C++11]
+///         enum-key attribute-specifier-seq[opt] identifier[opt] enum-bas=
e[opt]
+///         enum-key attribute-specifier-seq[opt] nested-name-specifier
+///             identifier enum-base[opt]
 ///
-///       enum-key: [C++0x]
+///       enum-key: [C++11]
 ///         'enum'
 ///         'enum' 'class'
 ///         'enum' 'struct'
 ///
-///       enum-base: [C++0x]
+///       enum-base: [C++11]
 ///         ':' type-specifier-seq
 ///
 /// [C++] elaborated-type-specifier:
@@ -2765,7 +2738,7 @@
 ///
 void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
                                 const ParsedTemplateInfo &TemplateInfo,
-                                AccessSpecifier AS) {
+                                AccessSpecifier AS, DeclSpecContext DSC) {
   // Parse the tag portion of this.
   if (Tok.is(tok::code_completion)) {
     // Code completion for an enum name.
@@ -2773,30 +2746,46 @@
     return cutOffParsing();
   }
=20
-  bool IsScopedEnum =3D false;
+  SourceLocation ScopedEnumKWLoc;
   bool IsScopedUsingClassTag =3D false;
=20
-  if (getLang().CPlusPlus0x &&
+  if (getLangOpts().CPlusPlus0x &&
       (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
-    IsScopedEnum =3D true;
+    Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
     IsScopedUsingClassTag =3D Tok.is(tok::kw_class);
-    ConsumeToken();
+    ScopedEnumKWLoc =3D ConsumeToken();
   }
- =20
+
+  // C++11 [temp.explicit]p12: The usual access controls do not apply to n=
ames
+  // used to specify explicit instantiations. We extend this to also cover
+  // explicit specializations.
+  Sema::SuppressAccessChecksRAII SuppressAccess(Actions,
+    TemplateInfo.Kind =3D=3D ParsedTemplateInfo::ExplicitInstantiation ||
+    TemplateInfo.Kind =3D=3D ParsedTemplateInfo::ExplicitSpecialization);
+
   // If attributes exist after tag, parse them.
   ParsedAttributes attrs(AttrFactory);
   MaybeParseGNUAttributes(attrs);
=20
-  bool AllowFixedUnderlyingType=20
-    =3D getLang().CPlusPlus0x || getLang().MicrosoftExt || getLang().ObjC2;
+  // If declspecs exist after tag, parse them.
+  while (Tok.is(tok::kw___declspec))
+    ParseMicrosoftDeclSpec(attrs);
+
+  // Enum definitions should not be parsed in a trailing-return-type.
+  bool AllowDeclaration =3D DSC !=3D DSC_trailing;
+
+  bool AllowFixedUnderlyingType =3D AllowDeclaration &&
+    (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt ||
+     getLangOpts().ObjC2);
=20
   CXXScopeSpec &SS =3D DS.getTypeSpecScope();
-  if (getLang().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
     // if a fixed underlying type is allowed.
     ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
    =20
-    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false))
+    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),=20
+                                       /*EnteringContext=3D*/false))
       return;
=20
     if (SS.isSet() && Tok.isNot(tok::identifier)) {
@@ -2812,7 +2801,7 @@
=20
   // Must have either 'enum name' or 'enum {...}'.
   if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
-      (AllowFixedUnderlyingType && Tok.isNot(tok::colon))) {
+      !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
     Diag(Tok, diag::err_expected_ident_lbrace);
=20
     // Skip the rest of this declarator, up until the comma or semicolon.
@@ -2828,14 +2817,17 @@
     NameLoc =3D ConsumeToken();
   }
=20
-  if (!Name && IsScopedEnum) {
+  if (!Name && ScopedEnumKWLoc.isValid()) {
     // C++0x 7.2p2: The optional identifier shall not be omitted in the
     // declaration of a scoped enumeration.
     Diag(Tok, diag::err_scoped_enum_missing_identifier);
-    IsScopedEnum =3D false;
+    ScopedEnumKWLoc =3D SourceLocation();
     IsScopedUsingClassTag =3D false;
   }
=20
+  // Stop suppressing access control now we've parsed the enum name.
+  SuppressAccess.done();
+
   TypeResult BaseType;
=20
   // Parse the fixed underlying type.
@@ -2870,10 +2862,16 @@
=20
         // Consume the ':'.
         ConsumeToken();
-     =20
-        if ((getLang().CPlusPlus &&=20
-             isCXXDeclarationSpecifier() !=3D TPResult::True()) ||
-            (!getLang().CPlusPlus && !isDeclarationSpecifier(true))) {
+
+        // If we see a type specifier followed by an open-brace, we have an
+        // ambiguity between an underlying type and a C++11 braced
+        // function-style cast. Resolve this by always treating it as an
+        // underlying type.
+        // FIXME: The standard is not entirely clear on how to disambiguat=
e in
+        // this case.
+        if ((getLangOpts().CPlusPlus &&
+             isCXXDeclarationSpecifier(TPResult::True()) !=3D TPResult::Tr=
ue()) ||
+            (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
           // We'll parse this as a bitfield later.
           PossibleBitfield =3D true;
           TPA.Revert();
@@ -2891,56 +2889,74 @@
       SourceRange Range;
       BaseType =3D ParseTypeName(&Range);
      =20
-      if (!getLang().CPlusPlus0x && !getLang().ObjC2)
+      if (!getLangOpts().CPlusPlus0x && !getLangOpts().ObjC2)
         Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
           << Range;
+      if (getLangOpts().CPlusPlus0x)
+        Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
     }
   }
=20
-  // There are three options here.  If we have 'enum foo;', then this is a
-  // forward declaration.  If we have 'enum foo {...' then this is a
-  // definition. Otherwise we have something like 'enum foo xyz', a refere=
nce.
+  // There are four options here.  If we have 'friend enum foo;' then this=
 is a
+  // friend declaration, and cannot have an accompanying definition. If we=
 have
+  // 'enum foo;', then this is a forward declaration.  If we have
+  // 'enum foo {...' then this is a definition. Otherwise we have something
+  // like 'enum foo xyz', a reference.
   //
   // This is needed to handle stuff like this right (C99 6.7.2.3p11):
   // enum foo {..};  void bar() { enum foo; }    <- new foo in bar.
   // enum foo {..};  void bar() { enum foo x; }  <- use of old foo.
   //
   Sema::TagUseKind TUK;
-  if (Tok.is(tok::l_brace))
+  if (DS.isFriendSpecified())
+    TUK =3D Sema::TUK_Friend;
+  else if (!AllowDeclaration)
+    TUK =3D Sema::TUK_Reference;
+  else if (Tok.is(tok::l_brace))
     TUK =3D Sema::TUK_Definition;
-  else if (Tok.is(tok::semi))
+  else if (Tok.is(tok::semi) && DSC !=3D DSC_type_specifier)
     TUK =3D Sema::TUK_Declaration;
   else
     TUK =3D Sema::TUK_Reference;
- =20
-  // enums cannot be templates, although they can be referenced from a=20
-  // template.
+
+  MultiTemplateParamsArg TParams;
   if (TemplateInfo.Kind !=3D ParsedTemplateInfo::NonTemplate &&
       TUK !=3D Sema::TUK_Reference) {
-    Diag(Tok, diag::err_enum_template);
-   =20
-    // Skip the rest of this declarator, up until the comma or semicolon.
-    SkipUntil(tok::comma, true);
-    return;     =20
+    if (!getLangOpts().CPlusPlus0x || !SS.isSet()) {
+      // Skip the rest of this declarator, up until the comma or semicolon.
+      Diag(Tok, diag::err_enum_template);
+      SkipUntil(tok::comma, true);
+      return;
+    }
+
+    if (TemplateInfo.Kind =3D=3D ParsedTemplateInfo::ExplicitInstantiation=
) {
+      // Enumerations can't be explicitly instantiated.
+      DS.SetTypeSpecError();
+      Diag(StartLoc, diag::err_explicit_instantiation_enum);
+      return;
+    }
+
+    assert(TemplateInfo.TemplateParams && "no template parameters");
+    TParams =3D MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
+                                     TemplateInfo.TemplateParams->size());
   }
- =20
+
   if (!Name && TUK !=3D Sema::TUK_Definition) {
     Diag(Tok, diag::err_enumerator_unnamed_no_def);
-   =20
+
     // Skip the rest of this declarator, up until the comma or semicolon.
     SkipUntil(tok::comma, true);
     return;
   }
-     =20
+
   bool Owned =3D false;
   bool IsDependent =3D false;
   const char *PrevSpec =3D 0;
   unsigned DiagID;
   Decl *TagDecl =3D Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TU=
K,
                                    StartLoc, SS, Name, NameLoc, attrs.getL=
ist(),
-                                   AS, DS.getModulePrivateSpecLoc(),
-                                   MultiTemplateParamsArg(Actions),
-                                   Owned, IsDependent, IsScopedEnum,
+                                   AS, DS.getModulePrivateSpecLoc(), TPara=
ms,
+                                   Owned, IsDependent, ScopedEnumKWLoc,
                                    IsScopedUsingClassTag, BaseType);
=20
   if (IsDependent) {
@@ -2971,7 +2987,7 @@
   if (!TagDecl) {
     // The action failed to produce an enumeration tag. If this is a=20
     // definition, consume the entire definition.
-    if (Tok.is(tok::l_brace)) {
+    if (Tok.is(tok::l_brace) && TUK !=3D Sema::TUK_Reference) {
       ConsumeBrace();
       SkipUntil(tok::r_brace);
     }
@@ -2979,9 +2995,17 @@
     DS.SetTypeSpecError();
     return;
   }
- =20
-  if (Tok.is(tok::l_brace))
-    ParseEnumBody(StartLoc, TagDecl);
+
+  if (Tok.is(tok::l_brace) && TUK !=3D Sema::TUK_Reference) {
+    if (TUK =3D=3D Sema::TUK_Friend) {
+      Diag(Tok, diag::err_friend_decl_defines_type)
+        << SourceRange(DS.getFriendSpecLoc());
+      ConsumeBrace();
+      SkipUntil(tok::r_brace);
+    } else {
+      ParseEnumBody(StartLoc, TagDecl);
+    }
+  }
=20
   if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
                          NameLoc.isValid() ? NameLoc : StartLoc,
@@ -3008,7 +3032,7 @@
   T.consumeOpen();
=20
   // C does not allow an empty enumerator-list, C++ does [dcl.enum].
-  if (Tok.is(tok::r_brace) && !getLang().CPlusPlus)
+  if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
     Diag(Tok, diag::error_empty_enum);
=20
   SmallVector<Decl *, 32> EnumConstantDecls;
@@ -3026,6 +3050,8 @@
=20
     SourceLocation EqualLoc;
     ExprResult AssignedVal;
+    ParsingDeclRAIIObject PD(*this);
+   =20
     if (Tok.is(tok::equal)) {
       EqualLoc =3D ConsumeToken();
       AssignedVal =3D ParseConstantExpression();
@@ -3039,6 +3065,8 @@
                                                     IdentLoc, Ident,
                                                     attrs.getList(), Equal=
Loc,
                                                     AssignedVal.release());
+    PD.complete(EnumConstDecl);
+   =20
     EnumConstantDecls.push_back(EnumConstDecl);
     LastEnumConstDecl =3D EnumConstDecl;
=20
@@ -3054,11 +3082,15 @@
       break;
     SourceLocation CommaLoc =3D ConsumeToken();
=20
-    if (Tok.isNot(tok::identifier) &&
-        !(getLang().C99 || getLang().CPlusPlus0x))
-      Diag(CommaLoc, diag::ext_enumerator_list_comma)
-        << getLang().CPlusPlus
-        << FixItHint::CreateRemoval(CommaLoc);
+    if (Tok.isNot(tok::identifier)) {
+      if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x)
+        Diag(CommaLoc, diag::ext_enumerator_list_comma)
+          << getLangOpts().CPlusPlus
+          << FixItHint::CreateRemoval(CommaLoc);
+      else if (getLangOpts().CPlusPlus0x)
+        Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
+          << FixItHint::CreateRemoval(CommaLoc);
+    }
   }
=20
   // Eat the }.
@@ -3086,7 +3118,7 @@
=20
     // type-qualifier only in OpenCL
   case tok::kw_private:
-    return getLang().OpenCL;
+    return getLangOpts().OpenCL;
=20
     // type-qualifier
   case tok::kw_const:
@@ -3113,6 +3145,7 @@
   case tok::kw_short:
   case tok::kw_long:
   case tok::kw___int64:
+  case tok::kw___int128:
   case tok::kw_signed:
   case tok::kw_unsigned:
   case tok::kw__Complex:
@@ -3183,6 +3216,7 @@
   case tok::kw_short:
   case tok::kw_long:
   case tok::kw___int64:
+  case tok::kw___int128:
   case tok::kw_signed:
   case tok::kw_unsigned:
   case tok::kw__Complex:
@@ -3221,7 +3255,7 @@
=20
     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit =
'id'.
   case tok::less:
-    return getLang().ObjC1;
+    return getLangOpts().ObjC1;
=20
   case tok::kw___cdecl:
   case tok::kw___stdcall:
@@ -3244,9 +3278,9 @@
     return true;
=20
   case tok::kw_private:
-    return getLang().OpenCL;
-
-  // C1x _Atomic()
+    return getLangOpts().OpenCL;
+
+  // C11 _Atomic()
   case tok::kw__Atomic:
     return true;
   }
@@ -3262,15 +3296,16 @@
   default: return false;
=20
   case tok::kw_private:
-    return getLang().OpenCL;
+    return getLangOpts().OpenCL;
=20
   case tok::identifier:   // foo::bar
     // Unfortunate hack to support "Class.factoryMethod" notation.
-    if (getLang().ObjC1 && NextToken().is(tok::period))
+    if (getLangOpts().ObjC1 && NextToken().is(tok::period))
       return false;
     if (TryAltiVecVectorToken())
       return true;
     // Fall through.
+  case tok::kw_decltype: // decltype(T())::type
   case tok::kw_typename: // typename T::type
     // Annotate typenames and C++ scope specifiers.  If we get one, just
     // recurse to handle whatever we get.
@@ -3317,6 +3352,7 @@
   case tok::kw_short:
   case tok::kw_long:
   case tok::kw___int64:
+  case tok::kw___int128:
   case tok::kw_signed:
   case tok::kw_unsigned:
   case tok::kw__Complex:
@@ -3366,16 +3402,16 @@
     return true;
=20
     // C++0x decltype.
-  case tok::kw_decltype:
+  case tok::annot_decltype:
     return true;
=20
-    // C1x _Atomic()
+    // C11 _Atomic()
   case tok::kw__Atomic:
     return true;
=20
     // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit =
'id'.
   case tok::less:
-    return getLang().ObjC1;
+    return getLangOpts().ObjC1;
=20
     // typedef-name
   case tok::annot_typename:
@@ -3411,7 +3447,8 @@
=20
   // Parse the C++ scope specifier.
   CXXScopeSpec SS;
-  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true)) {
+  if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),=20
+                                     /*EnteringContext=3D*/true)) {
     TPA.Revert();
     return false;
   }
@@ -3426,15 +3463,17 @@
     return false;
   }
=20
-  // Current class name must be followed by a left parentheses.
+  // Current class name must be followed by a left parenthesis.
   if (Tok.isNot(tok::l_paren)) {
     TPA.Revert();
     return false;
   }
   ConsumeParen();
=20
-  // A right parentheses or ellipsis signals that we have a constructor.
-  if (Tok.is(tok::r_paren) || Tok.is(tok::ellipsis)) {
+  // A right parenthesis, or ellipsis followed by a right parenthesis sign=
als
+  // that we have a constructor.
+  if (Tok.is(tok::r_paren) ||
+      (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
     TPA.Revert();
     return true;
   }
@@ -3451,7 +3490,43 @@
   // Check whether the next token(s) are part of a declaration
   // specifier, in which case we have the start of a parameter and,
   // therefore, we know that this is a constructor.
-  bool IsConstructor =3D isDeclarationSpecifier();
+  bool IsConstructor =3D false;
+  if (isDeclarationSpecifier())
+    IsConstructor =3D true;
+  else if (Tok.is(tok::identifier) ||
+           (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)=
)) {
+    // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
+    // This might be a parenthesized member name, but is more likely to
+    // be a constructor declaration with an invalid argument type. Keep
+    // looking.
+    if (Tok.is(tok::annot_cxxscope))
+      ConsumeToken();
+    ConsumeToken();
+
+    // If this is not a constructor, we must be parsing a declarator,
+    // which must have one of the following syntactic forms (see the
+    // grammar extract at the start of ParseDirectDeclarator):
+    switch (Tok.getKind()) {
+    case tok::l_paren:
+      // C(X   (   int));
+    case tok::l_square:
+      // C(X   [   5]);
+      // C(X   [   [attribute]]);
+    case tok::coloncolon:
+      // C(X   ::   Y);
+      // C(X   ::   *p);
+    case tok::r_paren:
+      // C(X   )
+      // Assume this isn't a constructor, rather than assuming it's a
+      // constructor with an unnamed parameter of an ill-formed type.
+      break;
+
+    default:
+      IsConstructor =3D true;
+      break;
+    }
+  }
+
   TPA.Revert();
   return IsConstructor;
 }
@@ -3470,15 +3545,12 @@
 ///
 void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
                                        bool VendorAttributesAllowed,
-                                       bool CXX0XAttributesAllowed) {
-  if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) {
-    SourceLocation Loc =3D Tok.getLocation();
+                                       bool CXX11AttributesAllowed) {
+  if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed &&
+      isCXX11AttributeSpecifier()) {
     ParsedAttributesWithRange attrs(AttrFactory);
-    ParseCXX0XAttributes(attrs);
-    if (CXX0XAttributesAllowed)
-      DS.takeAttributesFrom(attrs);
-    else
-      Diag(Loc, diag::err_attributes_not_allowed);
+    ParseCXX11Attributes(attrs);
+    DS.takeAttributesFrom(attrs);
   }
=20
   SourceLocation EndLoc;
@@ -3496,20 +3568,20 @@
        =20
     case tok::kw_const:
       isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_const   , Loc, PrevSpec, D=
iagID,
-                                 getLang());
+                                 getLangOpts());
       break;
     case tok::kw_volatile:
       isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, D=
iagID,
-                                 getLang());
+                                 getLangOpts());
       break;
     case tok::kw_restrict:
       isInvalid =3D DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, D=
iagID,
-                                 getLang());
+                                 getLangOpts());
       break;
=20
     // OpenCL qualifiers:
     case tok::kw_private:=20
-      if (!getLang().OpenCL)
+      if (!getLangOpts().OpenCL)
         goto DoneWithTypeQuals;
     case tok::kw___private:
     case tok::kw___global:
@@ -3574,11 +3646,26 @@
   ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
 }
=20
+static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lan=
g) {
+  if (Kind =3D=3D tok::star || Kind =3D=3D tok::caret)
+    return true;
+
+  // We parse rvalue refs in C++03, because otherwise the errors are scary.
+  if (!Lang.CPlusPlus)
+    return false;
+
+  return Kind =3D=3D tok::amp || Kind =3D=3D tok::ampamp;
+}
+
 /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-decl=
arator
 /// is parsed by the function passed to it. Pass null, and the direct-decl=
arator
 /// isn't parsed at all, making this function effectively parse the C++
 /// ptr-operator production.
 ///
+/// If the grammar of this construct is extended, matching changes must al=
so be
+/// made to TryParseDeclarator and MightBeDeclarator, and possibly to
+/// isConstructorDeclarator.
+///
 ///       declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
 /// [C]     pointer[opt] direct-declarator
 /// [C++]   direct-declarator
@@ -3603,11 +3690,13 @@
   // C++ member pointers start with a '::' or a nested-name.
   // Member pointers get special handling, since there's no place for the
   // scope spec in the generic path below.
-  if (getLang().CPlusPlus &&
+  if (getLangOpts().CPlusPlus &&
       (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
        Tok.is(tok::annot_cxxscope))) {
+    bool EnteringContext =3D D.getContext() =3D=3D Declarator::FileContext=
 ||
+                           D.getContext() =3D=3D Declarator::MemberContext;
     CXXScopeSpec SS;
-    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true); // ignore fail
+    ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
=20
     if (SS.isNotEmpty()) {
       if (Tok.isNot(tok::star)) {
@@ -3639,10 +3728,7 @@
=20
   tok::TokenKind Kind =3D Tok.getKind();
   // Not a pointer, C++ reference, or block.
-  if (Kind !=3D tok::star && Kind !=3D tok::caret &&
-      (Kind !=3D tok::amp || !getLang().CPlusPlus) &&
-      // We parse rvalue refs in C++03, because otherwise the errors are s=
cary.
-      (Kind !=3D tok::ampamp || !getLang().CPlusPlus)) {
+  if (!isPtrOperatorToken(Kind, getLangOpts())) {
     if (DirectDeclParser)
       (this->*DirectDeclParser)(D);
     return;
@@ -3657,6 +3743,7 @@
     // Is a pointer.
     DeclSpec DS(AttrFactory);
=20
+    // FIXME: GNU attributes are not allowed here in a new-type-id.
     ParseTypeQualifierListOpt(DS);
     D.ExtendWithDeclSpec(DS);
=20
@@ -3682,19 +3769,18 @@
=20
     // Complain about rvalue references in C++03, but then go on and build
     // the declarator.
-    if (Kind =3D=3D tok::ampamp && !getLang().CPlusPlus0x)
-      Diag(Loc, diag::ext_rvalue_reference);
+    if (Kind =3D=3D tok::ampamp)
+      Diag(Loc, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_rvalue_reference :
+           diag::ext_rvalue_reference);
+
+    // GNU-style and C++11 attributes are allowed here, as is restrict.
+    ParseTypeQualifierListOpt(DS);
+    D.ExtendWithDeclSpec(DS);
=20
     // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
     // cv-qualifiers are introduced through the use of a typedef or of a
     // template type argument, in which case the cv-qualifiers are ignored.
-    //
-    // [GNU] Retricted references are allowed.
-    // [GNU] Attributes on references are allowed.
-    // [C++0x] Attributes on references are not allowed.
-    ParseTypeQualifierListOpt(DS, true, false);
-    D.ExtendWithDeclSpec(DS);
-
     if (DS.getTypeQualifiers() !=3D DeclSpec::TQ_unspecified) {
       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
         Diag(DS.getConstSpecLoc(),
@@ -3732,6 +3818,19 @@
   }
 }
=20
+static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
+                                      SourceLocation EllipsisLoc) {
+  if (EllipsisLoc.isValid()) {
+    FixItHint Insertion;
+    if (!D.getEllipsisLoc().isValid()) {
+      Insertion =3D FixItHint::CreateInsertion(D.getIdentifierLoc(), "..."=
);
+      D.setEllipsisLoc(EllipsisLoc);
+    }
+    P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
+      << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName(=
);
+  }
+}
+
 /// ParseDirectDeclarator
 ///       direct-declarator: [C99 6.7.5]
 /// [C99]   identifier
@@ -3742,13 +3841,19 @@
 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr=
 ']'
 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr =
']'
 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
+/// [C++11] direct-declarator '[' constant-expression[opt] ']'
+///                    attribute-specifier-seq[opt]
 ///         direct-declarator '(' parameter-type-list ')'
 ///         direct-declarator '(' identifier-list[opt] ')'
 /// [GNU]   direct-declarator '(' parameter-forward-declarations
 ///                    parameter-type-list[opt] ')'
 /// [C++]   direct-declarator '(' parameter-declaration-clause ')'
 ///                    cv-qualifier-seq[opt] exception-specification[opt]
+/// [C++11] direct-declarator '(' parameter-declaration-clause ')'
+///                    attribute-specifier-seq[opt] cv-qualifier-seq[opt]
+///                    ref-qualifier[opt] exception-specification[opt]
 /// [C++]   declarator-id
+/// [C++11] declarator-id attribute-specifier-seq[opt]
 ///
 ///       declarator-id: [C++ 8]
 ///         '...'[opt] id-expression
@@ -3765,13 +3870,18 @@
 ///          '~' class-name
 ///         template-id
 ///
+/// Note, any additional constructs added here may need corresponding chan=
ges
+/// in isConstructorDeclarator.
 void Parser::ParseDirectDeclarator(Declarator &D) {
   DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
=20
-  if (getLang().CPlusPlus && D.mayHaveIdentifier()) {
+  if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
     // ParseDeclaratorInternal might already have parsed the scope.
     if (D.getCXXScopeSpec().isEmpty()) {
-      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), tr=
ue);
+      bool EnteringContext =3D D.getContext() =3D=3D Declarator::FileConte=
xt ||
+                             D.getContext() =3D=3D Declarator::MemberConte=
xt;
+      ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),=20
+                                     EnteringContext);
     }
=20
     if (D.getCXXScopeSpec().isValid()) {
@@ -3788,13 +3898,26 @@
     //   abstract-declarator if the type of the parameter names a template=20
     //   parameter pack that has not been expanded; otherwise, it is parsed
     //   as part of the parameter-declaration-clause.
-    if (Tok.is(tok::ellipsis) &&
+    if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
         !((D.getContext() =3D=3D Declarator::PrototypeContext ||
            D.getContext() =3D=3D Declarator::BlockLiteralContext) &&
           NextToken().is(tok::r_paren) &&
-          !Actions.containsUnexpandedParameterPacks(D)))
-      D.setEllipsisLoc(ConsumeToken());
-   =20
+          !Actions.containsUnexpandedParameterPacks(D))) {
+      SourceLocation EllipsisLoc =3D ConsumeToken();
+      if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
+        // The ellipsis was put in the wrong place. Recover, and explain to
+        // the user what they should have done.
+        ParseDeclarator(D);
+        diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
+        return;
+      } else
+        D.setEllipsisLoc(EllipsisLoc);
+
+      // The ellipsis can't be followed by a parenthesized declarator. We
+      // check for that in ParseParenDeclarator, after we have disambiguat=
ed
+      // the l_paren token.
+    }
+
     if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
         Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
       // We found something that indicates the start of an unqualified-id.
@@ -3810,11 +3933,13 @@
       else
         AllowConstructorName =3D (D.getContext() =3D=3D Declarator::Member=
Context);
=20
+      SourceLocation TemplateKWLoc;
       if (ParseUnqualifiedId(D.getCXXScopeSpec(),=20
                              /*EnteringContext=3D*/true,=20
                              /*AllowDestructorName=3D*/true,=20
                              AllowConstructorName,
                              ParsedType(),
+                             TemplateKWLoc,
                              D.getName()) ||
           // Once we're past the identifier, if the scope was bad, mark the
           // whole declarator bad.
@@ -3830,14 +3955,14 @@
       goto PastIdentifier;
     }
   } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
-    assert(!getLang().CPlusPlus &&
+    assert(!getLangOpts().CPlusPlus &&
            "There's a C++-specific check for tok::identifier above");
     assert(Tok.getIdentifierInfo() && "Not an identifier?");
     D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
     ConsumeToken();
     goto PastIdentifier;
   }
-   =20
+
   if (Tok.is(tok::l_paren)) {
     // direct-declarator: '(' declarator ')'
     // direct-declarator: '(' attributes declarator ')'
@@ -3849,7 +3974,7 @@
     // the scope already. Re-enter the scope, if we need to.
     if (D.getCXXScopeSpec().isSet()) {
       // If there was an error parsing parenthesized declarator, declarator
-      // scope may have been enterred before. Don't do it again.
+      // scope may have been entered before. Don't do it again.
       if (!D.isInvalidType() &&
           Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeS=
pec()))
         // Change the declaration context for name lookup, until this func=
tion
@@ -3864,8 +3989,8 @@
     if (D.getContext() =3D=3D Declarator::MemberContext)
       Diag(Tok, diag::err_expected_member_name_or_semi)
         << D.getDeclSpec().getSourceRange();
-    else if (getLang().CPlusPlus)
-      Diag(Tok, diag::err_expected_unqualified_id) << getLang().CPlusPlus;
+    else if (getLangOpts().CPlusPlus)
+      Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusP=
lus;
     else
       Diag(Tok, diag::err_expected_ident_lparen);
     D.SetIdentifier(0, Tok.getLocation());
@@ -3876,16 +4001,20 @@
   assert(D.isPastIdentifier() &&
          "Haven't past the location of the identifier yet?");
=20
-  // Don't parse attributes unless we have an identifier.
-  if (D.getIdentifier())
+  // Don't parse attributes unless we have parsed an unparenthesized name.
+  if (D.hasName() && !D.getNumTypeObjects())
     MaybeParseCXX0XAttributes(D);
=20
   while (1) {
     if (Tok.is(tok::l_paren)) {
+      // Enter function-declaration scope, limiting any declarators to the
+      // function prototype scope, including parameter declarators.
+      ParseScope PrototypeScope(this,
+                                Scope::FunctionPrototypeScope|Scope::DeclS=
cope);
       // The paren may be part of a C++ direct initializer, eg. "int x(1);=
".
       // In such a case, check if we actually have a function declarator; =
if it
       // is not, the declarator has been fully parsed.
-      if (getLang().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
+      if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
         // When not in file scope, warn for ambiguous function declarators=
, just
         // in case the author intended it as a variable definition.
         bool warnIfAmbiguous =3D D.getContext() !=3D Declarator::FileConte=
xt;
@@ -3896,13 +4025,14 @@
       BalancedDelimiterTracker T(*this, tok::l_paren);
       T.consumeOpen();
       ParseFunctionDeclarator(D, attrs, T);
+      PrototypeScope.Exit();
     } else if (Tok.is(tok::l_square)) {
       ParseBracketDeclarator(D);
     } else {
       break;
     }
   }
-}
+}=20
=20
 /// ParseParenDeclarator - We parsed the declarator D up to a paren.  This=
 is
 /// only called before the identifier, so these are most likely just group=
ing
@@ -3964,8 +4094,10 @@
     // paren, because we haven't seen the identifier yet.
     isGrouping =3D true;
   } else if (Tok.is(tok::r_paren) ||           // 'int()' is a function.
-             (getLang().CPlusPlus && Tok.is(tok::ellipsis)) || // C++ int(=
...)
-             isDeclarationSpecifier()) {       // 'int(int)' is a function.
+             (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
+              NextToken().is(tok::r_paren)) || // C++ int(...)
+             isDeclarationSpecifier() ||       // 'int(int)' is a function.
+             isCXX11AttributeSpecifier()) {    // 'int([[]]int)' is a func=
tion.
     // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
     // considered to be a type, not a K&R identifier-list.
     isGrouping =3D false;
@@ -3978,9 +4110,11 @@
   // direct-declarator: '(' declarator ')'
   // direct-declarator: '(' attributes declarator ')'
   if (isGrouping) {
+    SourceLocation EllipsisLoc =3D D.getEllipsisLoc();
+    D.setEllipsisLoc(SourceLocation());
+
     bool hadGroupingParens =3D D.hasGroupingParens();
     D.setGroupingParens(true);
-
     ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
     // Match the ')'.
     T.consumeClose();
@@ -3989,6 +4123,11 @@
                   attrs, T.getCloseLocation());
=20
     D.setGroupingParens(hadGroupingParens);
+
+    // An ellipsis cannot be placed outside parentheses.
+    if (EllipsisLoc.isValid())
+      diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
+
     return;
   }
=20
@@ -3998,31 +4137,39 @@
   // ParseFunctionDeclarator to handle of argument list.
   D.SetIdentifier(0, Tok.getLocation());
=20
+  // Enter function-declaration scope, limiting any declarators to the
+  // function prototype scope, including parameter declarators.
+  ParseScope PrototypeScope(this,
+                            Scope::FunctionPrototypeScope|Scope::DeclScope=
);
   ParseFunctionDeclarator(D, attrs, T, RequiresArg);
+  PrototypeScope.Exit();
 }
=20
 /// ParseFunctionDeclarator - We are after the identifier and have parsed =
the
 /// declarator D up to a paren, which indicates that we are parsing functi=
on
 /// arguments.
 ///
-/// If attrs is non-null, then the caller parsed those arguments immediate=
ly
-/// after the open paren - they should be considered to be the first argum=
ent of
-/// a parameter.  If RequiresArg is true, then the first argument of the
-/// function is required to be present and required to not be an identifier
-/// list.
+/// If FirstArgAttrs is non-null, then the caller parsed those arguments
+/// immediately after the open paren - they should be considered to be the
+/// first argument of a parameter.
 ///
-/// For C++, after the parameter-list, it also parses cv-qualifier-seq[opt=
],
-/// (C++0x) ref-qualifier[opt], exception-specification[opt], and
-/// (C++0x) trailing-return-type[opt].
+/// If RequiresArg is true, then the first argument of the function is req=
uired
+/// to be present and required to not be an identifier list.
 ///
-/// [C++0x] exception-specification:
+/// For C++, after the parameter-list, it also parses the cv-qualifier-seq=
[opt],
+/// (C++11) ref-qualifier[opt], exception-specification[opt],
+/// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type=
[opt].
+///
+/// [C++11] exception-specification:
 ///           dynamic-exception-specification
 ///           noexcept-specification
 ///
 void Parser::ParseFunctionDeclarator(Declarator &D,
-                                     ParsedAttributes &attrs,
+                                     ParsedAttributes &FirstArgAttrs,
                                      BalancedDelimiterTracker &Tracker,
                                      bool RequiresArg) {
+  assert(getCurScope()->isFunctionPrototypeScope() &&=20
+         "Should call from a Function scope");
   // lparen is already consumed!
   assert(D.isPastIdentifier() && "Should not call before identifier!");
=20
@@ -4037,13 +4184,18 @@
   DeclSpec DS(AttrFactory);
   bool RefQualifierIsLValueRef =3D true;
   SourceLocation RefQualifierLoc;
+  SourceLocation ConstQualifierLoc;
+  SourceLocation VolatileQualifierLoc;
   ExceptionSpecificationType ESpecType =3D EST_None;
   SourceRange ESpecRange;
   SmallVector<ParsedType, 2> DynamicExceptions;
   SmallVector<SourceRange, 2> DynamicExceptionRanges;
   ExprResult NoexceptExpr;
+  ParsedAttributes FnAttrs(AttrFactory);
   ParsedType TrailingReturnType;
- =20
+
+  Actions.ActOnStartFunctionDeclarator();
+
   SourceLocation EndLoc;
   if (isFunctionDeclaratorIdentifierList()) {
     if (RequiresArg)
@@ -4054,35 +4206,36 @@
     Tracker.consumeClose();
     EndLoc =3D Tracker.getCloseLocation();
   } else {
-    // Enter function-declaration scope, limiting any declarators to the
-    // function prototype scope, including parameter declarators.
-    ParseScope PrototypeScope(this,
-                              Scope::FunctionPrototypeScope|Scope::DeclSco=
pe);
-
     if (Tok.isNot(tok::r_paren))
-      ParseParameterDeclarationClause(D, attrs, ParamInfo, EllipsisLoc);
+      ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, Ellipsi=
sLoc);
     else if (RequiresArg)
       Diag(Tok, diag::err_argument_required_after_attribute);
=20
-    HasProto =3D ParamInfo.size() || getLang().CPlusPlus;
+    HasProto =3D ParamInfo.size() || getLangOpts().CPlusPlus;
=20
     // If we have the closing ')', eat it.
     Tracker.consumeClose();
     EndLoc =3D Tracker.getCloseLocation();
=20
-    if (getLang().CPlusPlus) {
-      MaybeParseCXX0XAttributes(attrs);
+    if (getLangOpts().CPlusPlus) {
+      // FIXME: Accept these components in any order, and produce fixits to
+      // correct the order if the user gets it wrong. Ideally we should de=
al
+      // with the virt-specifier-seq and pure-specifier in the same way.
=20
       // Parse cv-qualifier-seq[opt].
-      ParseTypeQualifierListOpt(DS, false /*no attributes*/);
-        if (!DS.getSourceRange().getEnd().isInvalid())
-          EndLoc =3D DS.getSourceRange().getEnd();
+      ParseTypeQualifierListOpt(DS, false /*no attributes*/, false);
+      if (!DS.getSourceRange().getEnd().isInvalid()) {
+        EndLoc =3D DS.getSourceRange().getEnd();
+        ConstQualifierLoc =3D DS.getConstSpecLoc();
+        VolatileQualifierLoc =3D DS.getVolatileSpecLoc();
+      }
=20
       // Parse ref-qualifier[opt].
       if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
-        if (!getLang().CPlusPlus0x)
-          Diag(Tok, diag::ext_ref_qualifier);
-       =20
+        Diag(Tok, getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_ref_qualifier :
+             diag::ext_ref_qualifier);
+
         RefQualifierIsLValueRef =3D Tok.is(tok::amp);
         RefQualifierLoc =3D ConsumeToken();
         EndLoc =3D RefQualifierLoc;
@@ -4096,17 +4249,19 @@
       if (ESpecType !=3D EST_None)
         EndLoc =3D ESpecRange.getEnd();
=20
+      // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this =
goes
+      // after the exception-specification.
+      MaybeParseCXX0XAttributes(FnAttrs);
+
       // Parse trailing-return-type[opt].
-      if (getLang().CPlusPlus0x && Tok.is(tok::arrow)) {
+      if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) {
+        Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
         SourceRange Range;
         TrailingReturnType =3D ParseTrailingReturnType(Range).get();
         if (Range.getEnd().isValid())
           EndLoc =3D Range.getEnd();
       }
     }
-
-    // Leave prototype scope.
-    PrototypeScope.Exit();
   }
=20
   // Remember that we parsed a function type, and remember the attributes.
@@ -4116,7 +4271,8 @@
                                              ParamInfo.data(), ParamInfo.s=
ize(),
                                              DS.getTypeQualifiers(),
                                              RefQualifierIsLValueRef,
-                                             RefQualifierLoc,
+                                             RefQualifierLoc, ConstQualifi=
erLoc,
+                                             VolatileQualifierLoc,
                                              /*MutableLoc=3D*/SourceLocati=
on(),
                                              ESpecType, ESpecRange.getBegi=
n(),
                                              DynamicExceptions.data(),
@@ -4127,7 +4283,9 @@
                                              Tracker.getOpenLocation(),=20
                                              EndLoc, D,
                                              TrailingReturnType),
-                attrs, EndLoc);
+                FnAttrs, EndLoc);
+
+  Actions.ActOnEndFunctionDeclarator();
 }
=20
 /// isFunctionDeclaratorIdentifierList - This parameter list may have an
@@ -4136,7 +4294,7 @@
 /// Note that identifier-lists are only allowed for normal declarators, no=
t for
 /// abstract-declarators.
 bool Parser::isFunctionDeclaratorIdentifierList() {
-  return !getLang().CPlusPlus
+  return !getLangOpts().CPlusPlus
          && Tok.is(tok::identifier)
          && !TryAltiVecVectorToken()
          // K&R identifier lists can't have typedefs as identifiers, per C=
99
@@ -4219,9 +4377,9 @@
 /// after the opening parenthesis. This function will not parse a K&R-style
 /// identifier list.
 ///
-/// D is the declarator being parsed.  If attrs is non-null, then the call=
er
-/// parsed those arguments immediately after the open paren - they should =
be
-/// considered to be the first argument of a parameter.
+/// D is the declarator being parsed.  If FirstArgAttrs is non-null, then =
the
+/// caller parsed those arguments immediately after the open paren - they =
should
+/// be considered to be part of the first parameter.
 ///
 /// After returning, ParamInfo will hold the parsed parameters. EllipsisLo=
c will
 /// be the location of the ellipsis, if any was parsed.
@@ -4238,20 +4396,24 @@
 ///       parameter-declaration: [C99 6.7.5]
 ///         declaration-specifiers declarator
 /// [C++]   declaration-specifiers declarator '=3D' assignment-expression
+/// [C++11]                                       initializer-clause
 /// [GNU]   declaration-specifiers declarator attributes
 ///         declaration-specifiers abstract-declarator[opt]
 /// [C++]   declaration-specifiers abstract-declarator[opt]
 ///           '=3D' assignment-expression
 /// [GNU]   declaration-specifiers abstract-declarator[opt] attributes
+/// [C++11] attribute-specifier-seq parameter-declaration
 ///
 void Parser::ParseParameterDeclarationClause(
        Declarator &D,
-       ParsedAttributes &attrs,
+       ParsedAttributes &FirstArgAttrs,
        SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
        SourceLocation &EllipsisLoc) {
=20
   while (1) {
     if (Tok.is(tok::ellipsis)) {
+      // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
+      // before deciding this was a parameter-declaration-clause.
       EllipsisLoc =3D ConsumeToken();     // Consume the ellipsis.
       break;
     }
@@ -4260,20 +4422,21 @@
     // Just use the ParsingDeclaration "scope" of the declarator.
     DeclSpec DS(AttrFactory);
=20
+    // Parse any C++11 attributes.
+    MaybeParseCXX0XAttributes(DS.getAttributes());
+
     // Skip any Microsoft attributes before a param.
-    if (getLang().MicrosoftExt && Tok.is(tok::l_square))
+    if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
       ParseMicrosoftAttributes(DS.getAttributes());
=20
     SourceLocation DSStart =3D Tok.getLocation();
=20
     // If the caller parsed attributes for the first argument, add them no=
w.
     // Take them so that we only apply the attributes to the first paramet=
er.
-    // FIXME: If we saw an ellipsis first, this code is not reached. Are t=
he
-    // attributes lost? Should they even be allowed?
     // FIXME: If we can leave the attributes in the token stream somehow, =
we can
-    // get rid of a parameter (attrs) and this statement. It might be too =
much
-    // hassle.
-    DS.takeAttributesFrom(attrs);
+    // get rid of a parameter (FirstArgAttrs) and this statement. It might=
 be
+    // too much hassle.
+    DS.takeAttributesFrom(FirstArgAttrs);
=20
     ParseDeclarationSpecifiers(DS);
=20
@@ -4346,9 +4509,15 @@
           // The argument isn't actually potentially evaluated unless it i=
s=20
           // used.
           EnterExpressionEvaluationContext Eval(Actions,
-                                              Sema::PotentiallyEvaluatedIf=
Used);
-
-          ExprResult DefArgResult(ParseAssignmentExpression());
+                                              Sema::PotentiallyEvaluatedIf=
Used,
+                                                Param);
+
+          ExprResult DefArgResult;
+          if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
+            Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_list=
s);
+            DefArgResult =3D ParseBraceInitializer();
+          } else
+            DefArgResult =3D ParseAssignmentExpression();
           if (DefArgResult.isInvalid()) {
             Actions.ActOnParamDefaultArgumentError(Param);
             SkipUntil(tok::comma, tok::r_paren, true, true);
@@ -4370,7 +4539,7 @@
       if (Tok.is(tok::ellipsis)) {
         EllipsisLoc =3D ConsumeToken();     // Consume the ellipsis.
        =20
-        if (!getLang().CPlusPlus) {
+        if (!getLangOpts().CPlusPlus) {
           // We have ellipsis without a preceding ',', which is ill-formed
           // in C. Complain and provide the fix.
           Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
@@ -4392,7 +4561,12 @@
 /// [C99]   direct-declarator '[' 'static' type-qual-list[opt] assign-expr=
 ']'
 /// [C99]   direct-declarator '[' type-qual-list 'static' assignment-expr =
']'
 /// [C99]   direct-declarator '[' type-qual-list[opt] '*' ']'
+/// [C++11] direct-declarator '[' constant-expression[opt] ']'
+///                           attribute-specifier-seq[opt]
 void Parser::ParseBracketDeclarator(Declarator &D) {
+  if (CheckProhibitedCXX11Attribute())
+    return;
+
   BalancedDelimiterTracker T(*this, tok::l_square);
   T.consumeOpen();
=20
@@ -4413,7 +4587,7 @@
   } else if (Tok.getKind() =3D=3D tok::numeric_constant &&
              GetLookAheadToken(1).is(tok::r_square)) {
     // [4] is very common.  Parse the numeric constant expression.
-    ExprResult ExprRes(Actions.ActOnNumericConstant(Tok));
+    ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
     ConsumeToken();
=20
     T.consumeClose();
@@ -4468,10 +4642,13 @@
=20
     // Parse the constant-expression or assignment-expression now (dependi=
ng
     // on dialect).
-    if (getLang().CPlusPlus)
+    if (getLangOpts().CPlusPlus) {
       NumElements =3D ParseConstantExpression();
-    else
+    } else {
+      EnterExpressionEvaluationContext Unevaluated(Actions,
+                                                   Sema::ConstantEvaluated=
);
       NumElements =3D ParseAssignmentExpression();
+    }
   }
=20
   // If there was an error parsing the assignment-expression, recover.
@@ -4508,6 +4685,8 @@
=20
   const bool hasParens =3D Tok.is(tok::l_paren);
=20
+  EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
+
   bool isCastExpr;
   ParsedType CastTy;
   SourceRange CastRange;
@@ -4543,6 +4722,13 @@
     return;
   }
=20
+  // We might need to transform the operand if it is potentially evaluated.
+  Operand =3D Actions.HandleExprEvaluationContextForTypeof(Operand.get());
+  if (Operand.isInvalid()) {
+    DS.SetTypeSpecError();
+    return;
+  }
+
   const char *PrevSpec =3D 0;
   unsigned DiagID;
   // Check for duplicate type specifiers (e.g. "int typeof(int)").
@@ -4551,7 +4737,7 @@
     Diag(StartLoc, DiagID) << PrevSpec;
 }
=20
-/// [C1X]   atomic-specifier:
+/// [C11]   atomic-specifier:
 ///           _Atomic ( type-name )
 ///
 void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseDeclCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseDeclCXX.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/PrettyDeclStackTrace.h"
+#include "llvm/ADT/SmallString.h"
 #include "RAIIObjectsForParser.h"
 using namespace clang;
=20
@@ -148,8 +149,9 @@
   }
=20
   // If we're still good, complain about inline namespaces in non-C++0x no=
w.
-  if (!getLang().CPlusPlus0x && InlineLoc.isValid())
-    Diag(InlineLoc, diag::ext_inline_namespace);
+  if (InlineLoc.isValid())
+    Diag(InlineLoc, getLangOpts().CPlusPlus0x ?
+         diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_names=
pace);
=20
   // Enter a scope for the namespace.
   ParseScope NamespaceScope(this, Scope::DeclScope);
@@ -233,7 +235,7 @@
=20
   CXXScopeSpec SS;
   // Parse (optional) nested-name-specifier.
-  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
+  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=3D*/f=
alse);
=20
   if (SS.isInvalid() || Tok.isNot(tok::identifier)) {
     Diag(Tok, diag::err_expected_namespace_name);
@@ -264,12 +266,17 @@
 ///
 Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) {
   assert(Tok.is(tok::string_literal) && "Not a string literal!");
-  llvm::SmallString<8> LangBuffer;
+  SmallString<8> LangBuffer;
   bool Invalid =3D false;
   StringRef Lang =3D PP.getSpelling(Tok, LangBuffer, &Invalid);
   if (Invalid)
     return 0;
=20
+  // FIXME: This is incorrect: linkage-specifiers are parsed in translation
+  // phase 7, so string-literal concatenation is supposed to occur.
+  //   extern "" "C" "" "+" "+" { } is legal.
+  if (Tok.hasUDSuffix())
+    Diag(Tok, diag::err_invalid_string_udl);
   SourceLocation Loc =3D ConsumeStringToken();
=20
   ParseScope LinkageScope(this, Scope::DeclScope);
@@ -381,7 +388,7 @@
=20
   CXXScopeSpec SS;
   // Parse (optional) nested-name-specifier.
-  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
+  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=3D*/f=
alse);
=20
   IdentifierInfo *NamespcName =3D 0;
   SourceLocation IdentLoc =3D SourceLocation();
@@ -449,7 +456,7 @@
     IsTypeName =3D false;
=20
   // Parse nested-name-specifier.
-  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
+  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=3D*/f=
alse);
=20
   // Check nested-name specifier.
   if (SS.isInvalid()) {
@@ -460,12 +467,14 @@
   // Parse the unqualified-id. We allow parsing of both constructor and
   // destructor names and allow the action module to diagnose any semantic
   // errors.
+  SourceLocation TemplateKWLoc;
   UnqualifiedId Name;
   if (ParseUnqualifiedId(SS,
                          /*EnteringContext=3D*/false,
                          /*AllowDestructorName=3D*/true,
                          /*AllowConstructorName=3D*/true,
                          ParsedType(),
+                         TemplateKWLoc,
                          Name)) {
     SkipUntil(tok::semi);
     return 0;
@@ -481,8 +490,9 @@
     // Where can GNU attributes appear?
     ConsumeToken();
=20
-    if (!getLang().CPlusPlus0x)
-      Diag(Tok.getLocation(), diag::ext_alias_declaration);
+    Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
+         diag::warn_cxx98_compat_alias_declaration :
+         diag::ext_alias_declaration);
=20
     // Type alias templates cannot be specialized.
     int SpecKind =3D -1;
@@ -571,20 +581,22 @@
                                        IsTypeName, TypenameLoc);
 }
=20
-/// ParseStaticAssertDeclaration - Parse C++0x or C1X static_assert-declar=
ation.
+/// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declar=
ation.
 ///
 /// [C++0x] static_assert-declaration:
 ///           static_assert ( constant-expression  ,  string-literal  ) ;
 ///
-/// [C1X]   static_assert-declaration:
+/// [C11]   static_assert-declaration:
 ///           _Static_assert ( constant-expression  ,  string-literal  ) ;
 ///
 Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
   assert((Tok.is(tok::kw_static_assert) || Tok.is(tok::kw__Static_assert))=
 &&
          "Not a static_assert declaration");
=20
-  if (Tok.is(tok::kw__Static_assert) && !getLang().C1X)
-    Diag(Tok, diag::ext_c1x_static_assert);
+  if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
+    Diag(Tok, diag::ext_c11_static_assert);
+  if (Tok.is(tok::kw_static_assert))
+    Diag(Tok, diag::warn_cxx98_compat_static_assert);
=20
   SourceLocation StaticAssertLoc =3D ConsumeToken();
=20
@@ -603,15 +615,17 @@
   if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi=
))
     return 0;
=20
-  if (Tok.isNot(tok::string_literal)) {
+  if (!isTokenStringLiteral()) {
     Diag(Tok, diag::err_expected_string_literal);
     SkipUntil(tok::semi);
     return 0;
   }
=20
   ExprResult AssertMessage(ParseStringLiteralExpression());
-  if (AssertMessage.isInvalid())
+  if (AssertMessage.isInvalid()) {
+    SkipUntil(tok::semi);
     return 0;
+  }
=20
   T.consumeClose();
=20
@@ -628,39 +642,94 @@
 ///
 /// 'decltype' ( expression )
 ///
-void Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
-  assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier");
-
-  SourceLocation StartLoc =3D ConsumeToken();
-  BalancedDelimiterTracker T(*this, tok::l_paren);
-  if (T.expectAndConsume(diag::err_expected_lparen_after,
-                       "decltype", tok::r_paren)) {
-    return;
+SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
+  assert((Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))
+           && "Not a decltype specifier");
+ =20
+
+  ExprResult Result;
+  SourceLocation StartLoc =3D Tok.getLocation();
+  SourceLocation EndLoc;
+
+  if (Tok.is(tok::annot_decltype)) {
+    Result =3D getExprAnnotation(Tok);
+    EndLoc =3D Tok.getAnnotationEndLoc();
+    ConsumeToken();
+    if (Result.isInvalid()) {
+      DS.SetTypeSpecError();
+      return EndLoc;
+    }
+  } else {
+    if (Tok.getIdentifierInfo()->isStr("decltype"))
+      Diag(Tok, diag::warn_cxx98_compat_decltype);
+
+    ConsumeToken();
+
+    BalancedDelimiterTracker T(*this, tok::l_paren);
+    if (T.expectAndConsume(diag::err_expected_lparen_after,
+                           "decltype", tok::r_paren)) {
+      DS.SetTypeSpecError();
+      return T.getOpenLocation() =3D=3D Tok.getLocation() ?
+             StartLoc : T.getOpenLocation();
+    }
+
+    // Parse the expression
+
+    // C++0x [dcl.type.simple]p4:
+    //   The operand of the decltype specifier is an unevaluated operand.
+    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluate=
d,
+                                                 0, /*IsDecltype=3D*/true);
+    Result =3D ParseExpression();
+    if (Result.isInvalid()) {
+      SkipUntil(tok::r_paren);
+      DS.SetTypeSpecError();
+      return StartLoc;
+    }
+
+    // Match the ')'
+    T.consumeClose();
+    if (T.getCloseLocation().isInvalid()) {
+      DS.SetTypeSpecError();
+      // FIXME: this should return the location of the last token
+      //        that was consumed (by "consumeClose()")
+      return T.getCloseLocation();
+    }
+
+    Result =3D Actions.ActOnDecltypeExpression(Result.take());
+    if (Result.isInvalid()) {
+      DS.SetTypeSpecError();
+      return T.getCloseLocation();
+    }
+
+    EndLoc =3D T.getCloseLocation();
   }
=20
-  // Parse the expression
-
-  // C++0x [dcl.type.simple]p4:
-  //   The operand of the decltype specifier is an unevaluated operand.
-  EnterExpressionEvaluationContext Unevaluated(Actions,
-                                               Sema::Unevaluated);
-  ExprResult Result =3D ParseExpression();
-  if (Result.isInvalid()) {
-    SkipUntil(tok::r_paren);
-    return;
-  }
-
-  // Match the ')'
-  T.consumeClose();
-  if (T.getCloseLocation().isInvalid())
-    return;
-
   const char *PrevSpec =3D 0;
   unsigned DiagID;
   // Check for duplicate type specifiers (e.g. "int decltype(a)").
   if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
-                         DiagID, Result.release()))
+                         DiagID, Result.release())) {
     Diag(StartLoc, DiagID) << PrevSpec;
+    DS.SetTypeSpecError();
+  }
+  return EndLoc;
+}
+
+void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,=20
+                                               SourceLocation StartLoc,
+                                               SourceLocation EndLoc) {
+  // make sure we have a token we can turn into an annotation token
+  if (PP.isBacktrackEnabled())
+    PP.RevertCachedTokens(1);
+  else
+    PP.EnterToken(Tok);
+
+  Tok.setKind(tok::annot_decltype);
+  setExprAnnotation(Tok, DS.getTypeSpecType() =3D=3D TST_decltype ?=20
+                         DS.getRepAsExpr() : ExprResult());
+  Tok.setAnnotationEndLoc(EndLoc);
+  Tok.setLocation(StartLoc);
+  PP.AnnotateCachedTokens(Tok);
 }
=20
 void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
@@ -692,18 +761,52 @@
     Diag(StartLoc, DiagID) << PrevSpec;
 }
=20
-/// ParseClassName - Parse a C++ class-name, which names a class. Note
-/// that we only check that the result names a type; semantic analysis
-/// will need to verify that the type names a class. The result is
-/// either a type or NULL, depending on whether a type name was
-/// found.
+/// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is eith=
er a
+/// class name or decltype-specifier. Note that we only check that the res=
ult=20
+/// names a type; semantic analysis will need to verify that the type name=
s a=20
+/// class. The result is either a type or null, depending on whether a typ=
e=20
+/// name was found.
 ///
+///       base-type-specifier: [C++ 10.1]
+///         class-or-decltype
+///       class-or-decltype: [C++ 10.1]
+///         nested-name-specifier[opt] class-name
+///         decltype-specifier
 ///       class-name: [C++ 9.1]
 ///         identifier
 ///         simple-template-id
 ///
-Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation,
-                                          CXXScopeSpec &SS) {
+Parser::TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
+                                                  SourceLocation &EndLocat=
ion) {
+  // Ignore attempts to use typename
+  if (Tok.is(tok::kw_typename)) {
+    Diag(Tok, diag::err_expected_class_name_not_template)
+      << FixItHint::CreateRemoval(Tok.getLocation());
+    ConsumeToken();
+  }
+
+  // Parse optional nested-name-specifier
+  CXXScopeSpec SS;
+  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=3D*/f=
alse);
+
+  BaseLoc =3D Tok.getLocation();
+
+  // Parse decltype-specifier
+  // tok =3D=3D kw_decltype is just error recovery, it can only happen whe=
n SS=20
+  // isn't empty
+  if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
+    if (SS.isNotEmpty())
+      Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
+        << FixItHint::CreateRemoval(SS.getRange());
+    // Fake up a Declarator to use with ActOnTypeName.
+    DeclSpec DS(AttrFactory);
+
+    EndLocation =3D ParseDecltypeSpecifier(DS);
+
+    Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
+    return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
+  }
+
   // Check whether we have a template-id that names a type.
   if (Tok.is(tok::annot_template_id)) {
     TemplateIdAnnotation *TemplateId =3D takeTemplateIdAnnotation(Tok);
@@ -751,8 +854,8 @@
     TemplateName.setIdentifier(Id, IdLoc);
=20
     // Parse the full template-id, then turn it into a type.
-    if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,
-                                SourceLocation(), true))
+    if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
+                                TemplateName, true))
       return true;
     if (TNK =3D=3D TNK_Dependent_template_name)
       AnnotateTemplateIdTokenAsType();
@@ -773,6 +876,7 @@
   // We have an identifier; check whether it is actually a type.
   ParsedType Type =3D Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, =
true,
                                         false, ParsedType(),
+                                        /*IsCtorOrDtorName=3D*/false,
                                         /*NonTrivialTypeSourceInfo=3D*/tru=
e);
   if (!Type) {
     Diag(IdLoc, diag::err_expected_class_name);
@@ -799,7 +903,7 @@
 /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
 /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
 /// until we reach the start of a definition or see a token that
-/// cannot start a definition. If SuppressDeclarations is true, we do know.
+/// cannot start a definition.
 ///
 ///       class-specifier: [C++ class]
 ///         class-head '{' member-specification[opt] '}'
@@ -839,7 +943,8 @@
 void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
                                  SourceLocation StartLoc, DeclSpec &DS,
                                  const ParsedTemplateInfo &TemplateInfo,
-                                 AccessSpecifier AS, bool SuppressDeclarat=
ions){
+                                 AccessSpecifier AS,=20
+                                 bool EnteringContext, DeclSpecContext DSC=
) {
   DeclSpec::TST TagType;
   if (TagTokKind =3D=3D tok::kw_struct)
     TagType =3D DeclSpec::TST_struct;
@@ -863,12 +968,9 @@
   // As an extension we do not perform access checking on the names used to
   // specify explicit specializations either. This is important to allow
   // specializing traits classes for private types.
-  bool SuppressingAccessChecks =3D false;
-  if (TemplateInfo.Kind =3D=3D ParsedTemplateInfo::ExplicitInstantiation ||
-      TemplateInfo.Kind =3D=3D ParsedTemplateInfo::ExplicitSpecialization)=
 {
-    Actions.ActOnStartSuppressingAccessChecks();
-    SuppressingAccessChecks =3D true;
-  }
+  Sema::SuppressAccessChecksRAII SuppressAccess(Actions,
+    TemplateInfo.Kind =3D=3D ParsedTemplateInfo::ExplicitInstantiation ||
+    TemplateInfo.Kind =3D=3D ParsedTemplateInfo::ExplicitSpecialization);
=20
   ParsedAttributes attrs(AttrFactory);
   // If attributes exist after tag, parse them.
@@ -914,11 +1016,11 @@
=20
   // Parse the (optional) nested-name-specifier.
   CXXScopeSpec &SS =3D DS.getTypeSpecScope();
-  if (getLang().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // "FOO : BAR" is not a potential typo for "FOO::BAR".
     ColonProtectionRAIIObject X(*this);
=20
-    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), true))
+    if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
       DS.SetTypeSpecError();
     if (SS.isSet())
       if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id))
@@ -935,7 +1037,7 @@
     Name =3D Tok.getIdentifierInfo();
     NameLoc =3D ConsumeToken();
=20
-    if (Tok.is(tok::less) && getLang().CPlusPlus) {
+    if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
       // The name was supposed to refer to a template, but didn't.
       // Eat the template argument list and try to continue parsing this as
       // a class (or template thereof).
@@ -997,39 +1099,41 @@
=20
       DS.SetTypeSpecError();
       SkipUntil(tok::semi, false, true);
-      if (SuppressingAccessChecks)
-        Actions.ActOnStopSuppressingAccessChecks();
-
       return;
     }
   }
=20
   // As soon as we're finished parsing the class's template-id, turn access
   // checking back on.
-  if (SuppressingAccessChecks)
-    Actions.ActOnStopSuppressingAccessChecks();
-
-  // There are four options here.  If we have 'struct foo;', then this
-  // is either a forward declaration or a friend declaration, which
-  // have to be treated differently.  If we have 'struct foo {...',
-  // 'struct foo :...' or 'struct foo final[opt]' then this is a
-  // definition. Otherwise we have something like 'struct foo xyz', a refe=
rence.
-  // However, in some contexts, things look like declarations but are just
-  // references, e.g.
-  // new struct s;
+  SuppressAccess.done();
+
+  // There are four options here.
+  //  - If we are in a trailing return type, this is always just a referen=
ce,
+  //    and we must not try to parse a definition. For instance,
+  //      [] () -> struct S { };
+  //    does not define a type.
+  //  - If we have 'struct foo {...', 'struct foo :...',
+  //    'struct foo final :' or 'struct foo final {', then this is a defin=
ition.
+  //  - If we have 'struct foo;', then this is either a forward declaration
+  //    or a friend declaration, which have to be treated differently.
+  //  - Otherwise we have something like 'struct foo xyz', a reference.
+  // However, in type-specifier-seq's, things look like declarations but a=
re
+  // just references, e.g.
+  //   new struct s;
   // or
-  // &T::operator struct s;
-  // For these, SuppressDeclarations is true.
+  //   &T::operator struct s;
+  // For these, DSC is DSC_type_specifier.
   Sema::TagUseKind TUK;
-  if (SuppressDeclarations)
+  if (DSC =3D=3D DSC_trailing)
     TUK =3D Sema::TUK_Reference;
-  else if (Tok.is(tok::l_brace) ||=20
-           (getLang().CPlusPlus && Tok.is(tok::colon)) ||
-           isCXX0XFinalKeyword()) {
+  else if (Tok.is(tok::l_brace) ||
+           (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
+           (isCXX0XFinalKeyword() &&
+            (NextToken().is(tok::l_brace) || NextToken().is(tok::colon))))=
 {
     if (DS.isFriendSpecified()) {
       // C++ [class.friend]p2:
       //   A class shall not be defined in a friend declaration.
-      Diag(Tok.getLocation(), diag::err_friend_decl_defines_class)
+      Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
         << SourceRange(DS.getFriendSpecLoc());
=20
       // Skip everything up to the semicolon, so that this looks like a pr=
oper
@@ -1040,7 +1144,7 @@
       // Okay, this is a class definition.
       TUK =3D Sema::TUK_Definition;
     }
-  } else if (Tok.is(tok::semi))
+  } else if (Tok.is(tok::semi) && DSC !=3D DSC_type_specifier)
     TUK =3D DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declarat=
ion;
   else
     TUK =3D Sema::TUK_Reference;
@@ -1092,14 +1196,14 @@
     } else if (TUK =3D=3D Sema::TUK_Reference ||
                (TUK =3D=3D Sema::TUK_Friend &&
                 TemplateInfo.Kind =3D=3D ParsedTemplateInfo::NonTemplate))=
 {
-      TypeResult =3D Actions.ActOnTagTemplateIdType(TUK, TagType,=20
-                                                  StartLoc,=20
+      TypeResult =3D Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
                                                   TemplateId->SS,
+                                                  TemplateId->TemplateKWLo=
c,
                                                   TemplateId->Template,
                                                   TemplateId->TemplateName=
Loc,
                                                   TemplateId->LAngleLoc,
                                                   TemplateArgsPtr,
-                                                  TemplateId->RAngleLoc); =
                                                =20
+                                                  TemplateId->RAngleLoc);
     } else {
       // This is an explicit specialization or a class template
       // partial specialization.
@@ -1191,8 +1295,9 @@
     TagOrTempResult =3D Actions.ActOnTag(getCurScope(), TagType, TUK, Star=
tLoc,
                                        SS, Name, NameLoc, attrs.getList(),=
 AS,
                                        DS.getModulePrivateSpecLoc(),
-                                       TParams, Owned, IsDependent, false,
-                                       false, clang::TypeResult());
+                                       TParams, Owned, IsDependent,
+                                       SourceLocation(), false,
+                                       clang::TypeResult());
=20
     // If ActOnTag said the type was dependent, try again with the
     // less common call.
@@ -1206,9 +1311,9 @@
   // If there is a body, parse it and inform the actions module.
   if (TUK =3D=3D Sema::TUK_Definition) {
     assert(Tok.is(tok::l_brace) ||
-           (getLang().CPlusPlus && Tok.is(tok::colon)) ||
+           (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
            isCXX0XFinalKeyword());
-    if (getLang().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()=
);
     else
       ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get());
@@ -1290,7 +1395,7 @@
=20
     case tok::r_brace:  // struct bar { struct foo {...} }
       // Missing ';' at end of struct is accepted as an extension in C mod=
e.
-      if (!getLang().CPlusPlus)
+      if (!getLangOpts().CPlusPlus)
         ExpectedSemi =3D false;
       break;
     }
@@ -1359,9 +1464,9 @@
 ///       base-specifier: [C++ class.derived]
 ///         ::[opt] nested-name-specifier[opt] class-name
 ///         'virtual' access-specifier[opt] ::[opt] nested-name-specifier[=
opt]
-///                        class-name
+///                        base-type-specifier
 ///         access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[=
opt]
-///                        class-name
+///                        base-type-specifier
 Parser::BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
   bool IsVirtual =3D false;
   SourceLocation StartLoc =3D Tok.getLocation();
@@ -1390,16 +1495,10 @@
     IsVirtual =3D true;
   }
=20
-  // Parse optional '::' and optional nested-name-specifier.
-  CXXScopeSpec SS;
-  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=3D*/f=
alse);
-
-  // The location of the base class itself.
-  SourceLocation BaseLoc =3D Tok.getLocation();
-
   // Parse the class-name.
   SourceLocation EndLocation;
-  TypeResult BaseType =3D ParseClassName(EndLocation, SS);
+  SourceLocation BaseLoc;
+  TypeResult BaseType =3D ParseBaseTypeSpecifier(BaseLoc, EndLocation);
   if (BaseType.isInvalid())
     return true;
=20
@@ -1468,14 +1567,14 @@
   }
 }
=20
-/// isCXX0XVirtSpecifier - Determine whether the next token is a C++0x
+/// isCXX0XVirtSpecifier - Determine whether the given token is a C++0x
 /// virt-specifier.
 ///
 ///       virt-specifier:
 ///         override
 ///         final
-VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier() const {
-  if (!getLang().CPlusPlus)
+VirtSpecifiers::Specifier Parser::isCXX0XVirtSpecifier(const Token &Tok) c=
onst {
+  if (!getLangOpts().CPlusPlus)
     return VirtSpecifiers::VS_None;
=20
   if (Tok.is(tok::identifier)) {
@@ -1516,9 +1615,10 @@
         << PrevSpec
         << FixItHint::CreateRemoval(Tok.getLocation());
=20
-    if (!getLang().CPlusPlus0x)
-      Diag(Tok.getLocation(), diag::ext_override_control_keyword)
-        << VirtSpecifiers::getSpecifierName(Specifier);
+    Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
+         diag::warn_cxx98_compat_override_control_keyword :
+         diag::ext_override_control_keyword)
+      << VirtSpecifiers::getSpecifierName(Specifier);
     ConsumeToken();
   }
 }
@@ -1526,7 +1626,7 @@
 /// isCXX0XFinalKeyword - Determine whether the next token is a C++0x
 /// contextual 'final' keyword.
 bool Parser::isCXX0XFinalKeyword() const {
-  if (!getLang().CPlusPlus)
+  if (!getLangOpts().CPlusPlus)
     return false;
=20
   if (!Tok.is(tok::identifier))
@@ -1581,7 +1681,7 @@
                                        const ParsedTemplateInfo &TemplateI=
nfo,
                                        ParsingDeclRAIIObject *TemplateDiag=
s) {
   if (Tok.is(tok::at)) {
-    if (getLang().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
+    if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs))
       Diag(Tok, diag::err_at_defs_cxx);
     else
       Diag(Tok, diag::err_at_in_class);
@@ -1605,11 +1705,14 @@
     if (isAccessDecl) {
       // Collect the scope specifier token we annotated earlier.
       CXXScopeSpec SS;
-      ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
+      ParseOptionalCXXScopeSpecifier(SS, ParsedType(),=20
+                                     /*EnteringContext=3D*/false);
=20
       // Try to parse an unqualified-id.
+      SourceLocation TemplateKWLoc;
       UnqualifiedId Name;
-      if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), Name)) {
+      if (ParseUnqualifiedId(SS, false, true, true, ParsedType(),
+                             TemplateKWLoc, Name)) {
         SkipUntil(tok::semi);
         return;
       }
@@ -1684,11 +1787,15 @@
     return;
   }
=20
+  // Hold late-parsed attributes so we can attach a Decl to them later.
+  LateParsedAttrList CommonLateParsedAttrs;
+
   // decl-specifier-seq:
   // Parse the common declaration-specifiers piece.
   ParsingDeclSpec DS(*this, TemplateDiags);
   DS.takeAttributesFrom(attrs);
-  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class);
+  ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class,
+                             &CommonLateParsedAttrs);
=20
   MultiTemplateParamsArg TemplateParams(Actions,
       TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0,
@@ -1708,6 +1815,9 @@
   // Hold late-parsed attributes so we can attach a Decl to them later.
   LateParsedAttrList LateParsedAttrs;
=20
+  SourceLocation EqualLoc;
+  bool HasInitializer =3D false;
+  ExprResult Init;
   if (Tok.isNot(tok::colon)) {
     // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
     ColonProtectionRAIIObject X(*this);
@@ -1730,39 +1840,42 @@
=20
     // MSVC permits pure specifier on inline functions declared at class s=
cope.
     // Hence check for =3D0 before checking for function definition.
-    ExprResult Init;
-    if (getLang().MicrosoftExt && Tok.is(tok::equal) &&
+    if (getLangOpts().MicrosoftExt && Tok.is(tok::equal) &&
         DeclaratorInfo.isFunctionDeclarator() &&=20
         NextToken().is(tok::numeric_constant)) {
-      ConsumeToken();
+      EqualLoc =3D ConsumeToken();
       Init =3D ParseInitializer();
       if (Init.isInvalid())
         SkipUntil(tok::comma, true, true);
+      else
+        HasInitializer =3D true;
     }
=20
-    bool IsDefinition =3D false;
+    FunctionDefinitionKind DefinitionKind =3D FDK_Declaration;
     // function-definition:
     //
     // In C++11, a non-function declarator followed by an open brace is a
     // braced-init-list for an in-class member initialization, not an
     // erroneous function definition.
-    if (Tok.is(tok::l_brace) && !getLang().CPlusPlus0x) {
-      IsDefinition =3D true;
+    if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus0x) {
+      DefinitionKind =3D FDK_Definition;
     } else if (DeclaratorInfo.isFunctionDeclarator()) {
       if (Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try=
)) {
-        IsDefinition =3D true;
+        DefinitionKind =3D FDK_Definition;
       } else if (Tok.is(tok::equal)) {
         const Token &KW =3D NextToken();
-        if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
-          IsDefinition =3D true;
+        if (KW.is(tok::kw_default))
+          DefinitionKind =3D FDK_Defaulted;
+        else if (KW.is(tok::kw_delete))
+          DefinitionKind =3D FDK_Deleted;
       }
     }
=20
-    if (IsDefinition) {
+    if (DefinitionKind) {
       if (!DeclaratorInfo.isFunctionDeclarator()) {
-        Diag(Tok, diag::err_func_def_no_params);
+        Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_para=
ms);
         ConsumeBrace();
-        SkipUntil(tok::r_brace, true);
+        SkipUntil(tok::r_brace, /*StopAtSemi*/false);
        =20
         // Consume the optional ';'
         if (Tok.is(tok::semi))
@@ -1771,12 +1884,13 @@
       }
=20
       if (DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_typedef) {
-        Diag(Tok, diag::err_function_declared_typedef);
+        Diag(DeclaratorInfo.getIdentifierLoc(),
+             diag::err_function_declared_typedef);
         // This recovery skips the entire function body. It would be nice
         // to simply call ParseCXXInlineMethodDef() below, however Sema
         // assumes the declarator represents a function, not a typedef.
         ConsumeBrace();
-        SkipUntil(tok::r_brace, true);
+        SkipUntil(tok::r_brace, /*StopAtSemi*/false);
=20
         // Consume the optional ';'
         if (Tok.is(tok::semi))
@@ -1786,10 +1900,13 @@
=20
       Decl *FunDecl =3D
         ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateI=
nfo,
-                                VS, Init);
-
+                                VS, DefinitionKind, Init);
+
+      for (unsigned i =3D 0, ni =3D CommonLateParsedAttrs.size(); i < ni; =
++i) {
+        CommonLateParsedAttrs[i]->addDecl(FunDecl);
+      }
       for (unsigned i =3D 0, ni =3D LateParsedAttrs.size(); i < ni; ++i) {
-        LateParsedAttrs[i]->setDecl(FunDecl);
+        LateParsedAttrs[i]->addDecl(FunDecl);
       }
       LateParsedAttrs.clear();
=20
@@ -1808,6 +1925,7 @@
=20
   SmallVector<Decl *, 8> DeclsInGroup;
   ExprResult BitfieldSize;
+  bool ExpectSemi =3D true;
=20
   while (1) {
     // member-declarator:
@@ -1839,9 +1957,8 @@
     // goes before or after the GNU attributes and __asm__.
     ParseOptionalCXX0XVirtSpecifierSeq(VS);
=20
-    bool HasInitializer =3D false;
     bool HasDeferredInitializer =3D false;
-    if (Tok.is(tok::equal) || Tok.is(tok::l_brace)) {
+    if ((Tok.is(tok::equal) || Tok.is(tok::l_brace)) && !HasInitializer) {
       if (BitfieldSize.get()) {
         Diag(Tok, diag::err_bitfield_member_init);
         SkipUntil(tok::comma, true, true);
@@ -1876,40 +1993,45 @@
     }
    =20
     // Set the Decl for any late parsed attributes
+    for (unsigned i =3D 0, ni =3D CommonLateParsedAttrs.size(); i < ni; ++=
i) {
+      CommonLateParsedAttrs[i]->addDecl(ThisDecl);
+    }
     for (unsigned i =3D 0, ni =3D LateParsedAttrs.size(); i < ni; ++i) {
-      LateParsedAttrs[i]->setDecl(ThisDecl);
+      LateParsedAttrs[i]->addDecl(ThisDecl);
     }
     LateParsedAttrs.clear();
=20
     // Handle the initializer.
     if (HasDeferredInitializer) {
       // The initializer was deferred; parse it and cache the tokens.
-      if (!getLang().CPlusPlus0x)
-        Diag(Tok, diag::warn_nonstatic_member_init_accepted_as_extension);
-     =20
+      Diag(Tok, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_nonstatic_member_init :
+           diag::ext_nonstatic_member_init);
+
       if (DeclaratorInfo.isArrayOfUnknownBound()) {
         // C++0x [dcl.array]p3: An array bound may also be omitted when the
         // declarator is followed by an initializer.=20
         //
         // A brace-or-equal-initializer for a member-declarator is not an
-        // initializer in the gramamr, so this is ill-formed.
+        // initializer in the grammar, so this is ill-formed.
         Diag(Tok, diag::err_incomplete_array_member_init);
         SkipUntil(tok::comma, true, true);
-        // Avoid later warnings about a class member of incomplete type.
-        ThisDecl->setInvalidDecl();
+        if (ThisDecl)
+          // Avoid later warnings about a class member of incomplete type.
+          ThisDecl->setInvalidDecl();
       } else
         ParseCXXNonStaticMemberInitializer(ThisDecl);
     } else if (HasInitializer) {
       // Normal initializer.
-      SourceLocation EqualLoc;
-      ExprResult Init
-        =3D ParseCXXMemberInitializer(DeclaratorInfo.isDeclarationOfFuncti=
on(),=20
-                                    EqualLoc);
+      if (!Init.isUsable())
+        Init =3D ParseCXXMemberInitializer(ThisDecl,
+                 DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
+     =20
       if (Init.isInvalid())
         SkipUntil(tok::comma, true, true);
       else if (ThisDecl)
-        Actions.AddInitializerToDecl(ThisDecl, Init.get(), false,
-                                   DS.getTypeSpecType() =3D=3D DeclSpec::T=
ST_auto);
+        Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInva=
lid(),
+                                   DS.getTypeSpecType() =3D=3D DeclSpec::T=
ST_auto);     =20
     } else if (ThisDecl && DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_s=
tatic) {
       // No initializer.
       Actions.ActOnUninitializedDecl(ThisDecl,=20
@@ -1935,12 +2057,26 @@
       break;
=20
     // Consume the comma.
-    ConsumeToken();
+    SourceLocation CommaLoc =3D ConsumeToken();
+
+    if (Tok.isAtStartOfLine() &&
+        !MightBeDeclarator(Declarator::MemberContext)) {
+      // This comma was followed by a line-break and something which can't=
 be
+      // the start of a declarator. The comma was probably a typo for a
+      // semicolon.
+      Diag(CommaLoc, diag::err_expected_semi_declaration)
+        << FixItHint::CreateReplacement(CommaLoc, ";");
+      ExpectSemi =3D false;
+      break;
+    }
=20
     // Parse the next declarator.
     DeclaratorInfo.clear();
     VS.clear();
     BitfieldSize =3D true;
+    Init =3D true;
+    HasInitializer =3D false;
+    DeclaratorInfo.setCommaLoc(CommaLoc);
=20
     // Attributes are only allowed on the second declarator.
     MaybeParseGNUAttributes(DeclaratorInfo);
@@ -1949,7 +2085,8 @@
       ParseDeclarator(DeclaratorInfo);
   }
=20
-  if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
+  if (ExpectSemi &&
+      ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
     // Skip to end of block or statement.
     SkipUntil(tok::r_brace, true, true);
     // If we stopped at a ';', eat it.
@@ -1968,26 +2105,29 @@
 ///
 ///   pure-specifier:
 ///     '=3D 0'
-/// =20
+///
 ///   brace-or-equal-initializer:
 ///     '=3D' initializer-expression
-///     braced-init-list                       [TODO]
-/// =20
+///     braced-init-list
+///
 ///   initializer-clause:
 ///     assignment-expression
-///     braced-init-list                       [TODO]
-/// =20
+///     braced-init-list
+///
 ///   defaulted/deleted function-definition:                              =
                                                                           =
                                                                           =
          =20
 ///     '=3D' 'default'
 ///     '=3D' 'delete'
 ///
 /// Prior to C++0x, the assignment-expression in an initializer-clause must
 /// be a constant-expression.
-ExprResult Parser::ParseCXXMemberInitializer(bool IsFunction,
+ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
                                              SourceLocation &EqualLoc) {
   assert((Tok.is(tok::equal) || Tok.is(tok::l_brace))
          && "Data member initializer not starting with '=3D' or '{'");
=20
+  EnterExpressionEvaluationContext Context(Actions,=20
+                                           Sema::PotentiallyEvaluated,
+                                           D);
   if (Tok.is(tok::equal)) {
     EqualLoc =3D ConsumeToken();
     if (Tok.is(tok::kw_delete)) {
@@ -2015,9 +2155,8 @@
       return ExprResult();
     }
=20
-    return ParseInitializer();
-  } else
-    return ExprError(Diag(Tok, diag::err_generalized_initializer_lists));
+  }
+  return ParseInitializer();
 }
=20
 /// ParseCXXMemberSpecification - Parse the class definition.
@@ -2071,20 +2210,13 @@
   SourceLocation FinalLoc;
=20
   // Parse the optional 'final' keyword.
-  if (getLang().CPlusPlus && Tok.is(tok::identifier)) {
-    IdentifierInfo *II =3D Tok.getIdentifierInfo();
-   =20
-    // Initialize the contextual keywords.
-    if (!Ident_final) {
-      Ident_final =3D &PP.getIdentifierTable().get("final");
-      Ident_override =3D &PP.getIdentifierTable().get("override");
-    }
-     =20
-    if (II =3D=3D Ident_final)
-      FinalLoc =3D ConsumeToken();
-
-    if (!getLang().CPlusPlus0x)=20
-      Diag(FinalLoc, diag::ext_override_control_keyword) << "final";
+  if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
+    assert(isCXX0XFinalKeyword() && "not a class definition");
+    FinalLoc =3D ConsumeToken();
+
+    Diag(FinalLoc, getLangOpts().CPlusPlus0x ?
+         diag::warn_cxx98_compat_override_control_keyword :
+         diag::ext_override_control_keyword) << "final";
   }
=20
   if (Tok.is(tok::colon)) {
@@ -2122,7 +2254,7 @@
     while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
       // Each iteration of this loop reads one member-declaration.
=20
-      if (getLang().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
+      if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
           Tok.is(tok::kw___if_not_exists))) {
         ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, Cur=
AS);
         continue;
@@ -2137,6 +2269,16 @@
         continue;
       }
=20
+      if (Tok.is(tok::annot_pragma_vis)) {
+        HandlePragmaVisibility();
+        continue;
+      }
+
+      if (Tok.is(tok::annot_pragma_pack)) {
+        HandlePragmaPack();
+        continue;
+      }
+
       AccessSpecifier AS =3D getAccessSpecifierIfPresent();
       if (AS !=3D AS_none) {
         // Current token is a C++ access specifier.
@@ -2150,11 +2292,6 @@
         SourceLocation EndLoc;
         if (Tok.is(tok::colon)) {
           EndLoc =3D Tok.getLocation();
-          if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
-                                           AccessAttrs.getList())) {
-            // found another attribute than only annotations
-            AccessAttrs.clear();
-          }
           ConsumeToken();
         } else if (Tok.is(tok::semi)) {
           EndLoc =3D Tok.getLocation();
@@ -2166,7 +2303,13 @@
           Diag(EndLoc, diag::err_expected_colon)=20
             << FixItHint::CreateInsertion(EndLoc, ":");
         }
-        Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc);
+
+        if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc,
+                                         AccessAttrs.getList())) {
+          // found another attribute than only annotations
+          AccessAttrs.clear();
+        }
+
         continue;
       }
=20
@@ -2303,7 +2446,7 @@
 Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
   // parse '::'[opt] nested-name-specifier[opt]
   CXXScopeSpec SS;
-  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
+  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=3D*/f=
alse);
   ParsedType TemplateTypeTy;
   if (Tok.is(tok::annot_template_id)) {
     TemplateIdAnnotation *TemplateId =3D takeTemplateIdAnnotation(Tok);
@@ -2314,18 +2457,33 @@
       TemplateTypeTy =3D getTypeAnnotation(Tok);
     }
   }
-  if (!TemplateTypeTy && Tok.isNot(tok::identifier)) {
+  // Uses of decltype will already have been converted to annot_decltype by
+  // ParseOptionalCXXScopeSpecifier at this point.
+  if (!TemplateTypeTy && Tok.isNot(tok::identifier)
+      && Tok.isNot(tok::annot_decltype)) {
     Diag(Tok, diag::err_expected_member_or_base_name);
     return true;
   }
=20
-  // Get the identifier. This may be a member name or a class name,
-  // but we'll let the semantic analysis determine which it is.
-  IdentifierInfo *II =3D Tok.is(tok::identifier) ? Tok.getIdentifierInfo()=
 : 0;
-  SourceLocation IdLoc =3D ConsumeToken();
+  IdentifierInfo *II =3D 0;
+  DeclSpec DS(AttrFactory);
+  SourceLocation IdLoc =3D Tok.getLocation();
+  if (Tok.is(tok::annot_decltype)) {
+    // Get the decltype expression, if there is one.
+    ParseDecltypeSpecifier(DS);
+  } else {
+    if (Tok.is(tok::identifier))
+      // Get the identifier. This may be a member name or a class name,
+      // but we'll let the semantic analysis determine which it is.
+      II =3D Tok.getIdentifierInfo();
+    ConsumeToken();
+  }
+
=20
   // Parse the '('.
-  if (getLang().CPlusPlus0x && Tok.is(tok::l_brace)) {
+  if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
+    Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
+
     ExprResult InitList =3D ParseBraceInitializer();
     if (InitList.isInvalid())
       return true;
@@ -2335,8 +2493,8 @@
       EllipsisLoc =3D ConsumeToken();
=20
     return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS,=
 II,
-                                       TemplateTypeTy, IdLoc, InitList.tak=
e(),
-                                       EllipsisLoc);
+                                       TemplateTypeTy, DS, IdLoc,=20
+                                       InitList.take(), EllipsisLoc);
   } else if(Tok.is(tok::l_paren)) {
     BalancedDelimiterTracker T(*this, tok::l_paren);
     T.consumeOpen();
@@ -2356,13 +2514,13 @@
       EllipsisLoc =3D ConsumeToken();
=20
     return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS,=
 II,
-                                       TemplateTypeTy, IdLoc,
+                                       TemplateTypeTy, DS, IdLoc,
                                        T.getOpenLocation(), ArgExprs.take(=
),
                                        ArgExprs.size(), T.getCloseLocation=
(),
                                        EllipsisLoc);
   }
=20
-  Diag(Tok, getLang().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace
+  Diag(Tok, getLangOpts().CPlusPlus0x ? diag::err_expected_lparen_or_lbrace
                                   : diag::err_expected_lparen);
   return true;
 }
@@ -2396,6 +2554,8 @@
   if (Tok.isNot(tok::kw_noexcept))
     return Result;
=20
+  Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
+
   // If we already had a dynamic specification, parse the noexcept for,
   // recovery, but emit a diagnostic and don't store the results.
   SourceRange NoexceptRange;
@@ -2468,7 +2628,7 @@
   // can throw anything".
   if (Tok.is(tok::ellipsis)) {
     SourceLocation EllipsisLoc =3D ConsumeToken();
-    if (!getLang().MicrosoftExt)
+    if (!getLangOpts().MicrosoftExt)
       Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
     T.consumeClose();
     SpecificationRange.setEnd(T.getCloseLocation());
@@ -2513,14 +2673,7 @@
=20
   ConsumeToken();
=20
-  // FIXME: Need to suppress declarations when parsing this typename.
-  // Otherwise in this function definition:
-  //
-  //   auto f() -> struct X {}
-  //
-  // struct X is parsed as class definition because of the trailing
-  // brace.
-  return ParseTypeName(&Range);
+  return ParseTypeName(&Range, Declarator::TrailingReturnContext);
 }
=20
 /// \brief We have just started parsing the definition of a new class,
@@ -2583,43 +2736,87 @@
   Victim->TemplateScope =3D getCurScope()->getParent()->isTemplateParamSco=
pe();
 }
=20
-/// ParseCXX0XAttributeSpecifier - Parse a C++0x attribute-specifier. Curr=
ently
+/// \brief Try to parse an 'identifier' which appears within an attribute-=
token.
+///
+/// \return the parsed identifier on success, and 0 if the next token is n=
ot an
+/// attribute-token.
+///
+/// C++11 [dcl.attr.grammar]p3:
+///   If a keyword or an alternative token that satisfies the syntactic
+///   requirements of an identifier is contained in an attribute-token,
+///   it is considered an identifier.
+IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &L=
oc) {
+  switch (Tok.getKind()) {
+  default:
+    // Identifiers and keywords have identifier info attached.
+    if (IdentifierInfo *II =3D Tok.getIdentifierInfo()) {
+      Loc =3D ConsumeToken();
+      return II;
+    }
+    return 0;
+
+  case tok::ampamp:       // 'and'
+  case tok::pipe:         // 'bitor'
+  case tok::pipepipe:     // 'or'
+  case tok::caret:        // 'xor'
+  case tok::tilde:        // 'compl'
+  case tok::amp:          // 'bitand'
+  case tok::ampequal:     // 'and_eq'
+  case tok::pipeequal:    // 'or_eq'
+  case tok::caretequal:   // 'xor_eq'
+  case tok::exclaim:      // 'not'
+  case tok::exclaimequal: // 'not_eq'
+    // Alternative tokens do not have identifier info, but their spelling
+    // starts with an alphabetical character.
+    llvm::SmallString<8> SpellingBuf;
+    StringRef Spelling =3D PP.getSpelling(Tok.getLocation(), SpellingBuf);
+    if (std::isalpha(Spelling[0])) {
+      Loc =3D ConsumeToken();
+      return &PP.getIdentifierTable().get(Spelling.data());
+    }
+    return 0;
+  }
+}
+
+/// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. Curr=
ently
 /// only parses standard attributes.
 ///
-/// [C++0x] attribute-specifier:
+/// [C++11] attribute-specifier:
 ///         '[' '[' attribute-list ']' ']'
 ///         alignment-specifier
 ///
-/// [C++0x] attribute-list:
+/// [C++11] attribute-list:
 ///         attribute[opt]
 ///         attribute-list ',' attribute[opt]
+///         attribute '...'
+///         attribute-list ',' attribute '...'
 ///
-/// [C++0x] attribute:
+/// [C++11] attribute:
 ///         attribute-token attribute-argument-clause[opt]
 ///
-/// [C++0x] attribute-token:
+/// [C++11] attribute-token:
 ///         identifier
 ///         attribute-scoped-token
 ///
-/// [C++0x] attribute-scoped-token:
+/// [C++11] attribute-scoped-token:
 ///         attribute-namespace '::' identifier
 ///
-/// [C++0x] attribute-namespace:
+/// [C++11] attribute-namespace:
 ///         identifier
 ///
-/// [C++0x] attribute-argument-clause:
+/// [C++11] attribute-argument-clause:
 ///         '(' balanced-token-seq ')'
 ///
-/// [C++0x] balanced-token-seq:
+/// [C++11] balanced-token-seq:
 ///         balanced-token
 ///         balanced-token-seq balanced-token
 ///
-/// [C++0x] balanced-token:
+/// [C++11] balanced-token:
 ///         '(' balanced-token-seq ')'
 ///         '[' balanced-token-seq ']'
 ///         '{' balanced-token-seq '}'
 ///         any token but '(', ')', '[', ']', '{', or '}'
-void Parser::ParseCXX0XAttributeSpecifier(ParsedAttributes &attrs,
+void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
                                           SourceLocation *endLoc) {
   if (Tok.is(tok::kw_alignas)) {
     Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
@@ -2628,56 +2825,53 @@
   }
=20
   assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)
-      && "Not a C++0x attribute list");
+      && "Not a C++11 attribute list");
=20
   Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
=20
   ConsumeBracket();
   ConsumeBracket();
=20
-  if (Tok.is(tok::comma)) {
-    Diag(Tok.getLocation(), diag::err_expected_ident);
-    ConsumeToken();
-  }
-
-  while (Tok.is(tok::identifier) || Tok.is(tok::comma)) {
+  while (Tok.isNot(tok::r_square)) {
     // attribute not present
     if (Tok.is(tok::comma)) {
       ConsumeToken();
       continue;
     }
=20
-    IdentifierInfo *ScopeName =3D 0, *AttrName =3D Tok.getIdentifierInfo();
-    SourceLocation ScopeLoc, AttrLoc =3D ConsumeToken();
+    SourceLocation ScopeLoc, AttrLoc;
+    IdentifierInfo *ScopeName =3D 0, *AttrName =3D 0;
+
+    AttrName =3D TryParseCXX11AttributeIdentifier(AttrLoc);
+    if (!AttrName)
+      // Break out to the "expected ']'" diagnostic.
+      break;
=20
     // scoped attribute
     if (Tok.is(tok::coloncolon)) {
       ConsumeToken();
=20
-      if (!Tok.is(tok::identifier)) {
+      ScopeName =3D AttrName;
+      ScopeLoc =3D AttrLoc;
+
+      AttrName =3D TryParseCXX11AttributeIdentifier(AttrLoc);
+      if (!AttrName) {
         Diag(Tok.getLocation(), diag::err_expected_ident);
         SkipUntil(tok::r_square, tok::comma, true, true);
         continue;
       }
-
-      ScopeName =3D AttrName;
-      ScopeLoc =3D AttrLoc;
-
-      AttrName =3D Tok.getIdentifierInfo();
-      AttrLoc =3D ConsumeToken();
     }
=20
     bool AttrParsed =3D false;
     // No scoped names are supported; ideally we could put all non-standard
     // attributes into namespaces.
     if (!ScopeName) {
-      switch(AttributeList::getKind(AttrName))
-      {
+      switch (AttributeList::getKind(AttrName)) {
       // No arguments
       case AttributeList::AT_carries_dependency:
       case AttributeList::AT_noreturn: {
         if (Tok.is(tok::l_paren)) {
-          Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_argume=
nts)
+          Diag(Tok.getLocation(), diag::err_cxx11_attribute_forbids_argume=
nts)
             << AttrName->getName();
           break;
         }
@@ -2699,6 +2893,13 @@
       // SkipUntil maintains the balancedness of tokens.
       SkipUntil(tok::r_paren, false);
     }
+
+    if (Tok.is(tok::ellipsis)) {
+      if (AttrParsed)
+        Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
+          << AttrName->getName();
+      ConsumeToken();
+    }
   }
=20
   if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare))
@@ -2709,19 +2910,19 @@
     SkipUntil(tok::r_square, false);
 }
=20
-/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier-seq.
+/// ParseCXX11Attributes - Parse a C++0x attribute-specifier-seq.
 ///
 /// attribute-specifier-seq:
 ///       attribute-specifier-seq[opt] attribute-specifier
-void Parser::ParseCXX0XAttributes(ParsedAttributesWithRange &attrs,
+void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
                                   SourceLocation *endLoc) {
   SourceLocation StartLoc =3D Tok.getLocation(), Loc;
   if (!endLoc)
     endLoc =3D &Loc;
=20
   do {
-    ParseCXX0XAttributeSpecifier(attrs, endLoc);
-  } while (isCXX0XAttributeSpecifier());
+    ParseCXX11AttributeSpecifier(attrs, endLoc);
+  } while (isCXX11AttributeSpecifier());
=20
   attrs.Range =3D SourceRange(StartLoc, *endLoc);
 }
@@ -2739,6 +2940,7 @@
   assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
=20
   while (Tok.is(tok::l_square)) {
+    // FIXME: If this is actually a C++11 attribute, parse it as one.
     ConsumeBracket();
     SkipUntil(tok::r_square, true, true);
     if (endLoc) *endLoc =3D Tok.getLocation();
@@ -2748,25 +2950,32 @@
=20
 void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
                                                     AccessSpecifier& CurAS=
) {
-  bool Result;
+  IfExistsCondition Result;
   if (ParseMicrosoftIfExistsCondition(Result))
     return;
  =20
-  if (Tok.isNot(tok::l_brace)) {
+  BalancedDelimiterTracker Braces(*this, tok::l_brace);
+  if (Braces.consumeOpen()) {
     Diag(Tok, diag::err_expected_lbrace);
     return;
   }
-  ConsumeBrace();
-
-  // Condition is false skip all inside the {}.
-  if (!Result) {
-    SkipUntil(tok::r_brace, false);
+
+  switch (Result.Behavior) {
+  case IEB_Parse:
+    // Parse the declarations below.
+    break;
+       =20
+  case IEB_Dependent:
+    Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
+      << Result.IsIfExists;
+    // Fall through to skip.
+     =20
+  case IEB_Skip:
+    Braces.skipToEnd();
     return;
   }
=20
-  // Condition is true, parse the declaration.
-  while (Tok.isNot(tok::r_brace)) {
-
+  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
     // __if_exists, __if_not_exists can nest.
     if ((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) {
       ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS=
);
@@ -2799,10 +3008,6 @@
     // Parse all the comma separated declarators.
     ParseCXXClassMemberDeclaration(CurAS, 0);
   }
-
-  if (Tok.isNot(tok::r_brace)) {
-    Diag(Tok, diag::err_expected_rbrace);
-    return;
-  }
-  ConsumeBrace();
+ =20
+  Braces.consumeClose();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseExpr.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseExpr.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseExpr.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -23,6 +23,7 @@
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ParsedTemplate.h"
+#include "clang/Sema/TypoCorrection.h"
 #include "clang/Basic/PrettyStackTrace.h"
 #include "RAIIObjectsForParser.h"
 #include "llvm/ADT/SmallVector.h"
@@ -174,8 +175,8 @@
 ///       expression: [C99 6.5.17]
 ///         assignment-expression ...[opt]
 ///         expression ',' assignment-expression ...[opt]
-ExprResult Parser::ParseExpression() {
-  ExprResult LHS(ParseAssignmentExpression());
+ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
+  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
   return ParseRHSOfBinaryExpression(move(LHS), prec::Comma);
 }
=20
@@ -211,7 +212,7 @@
 }
=20
 /// ParseAssignmentExpression - Parse an expr that doesn't include commas.
-ExprResult Parser::ParseAssignmentExpression() {
+ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
   if (Tok.is(tok::code_completion)) {
     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
     cutOffParsing();
@@ -221,7 +222,9 @@
   if (Tok.is(tok::kw_throw))
     return ParseThrowExpression();
=20
-  ExprResult LHS =3D ParseCastExpression(/*isUnaryExpression=3D*/false);
+  ExprResult LHS =3D ParseCastExpression(/*isUnaryExpression=3D*/false,
+                                       /*isAddressOfOperand=3D*/false,
+                                       isTypeCast);
   return ParseRHSOfBinaryExpression(move(LHS), prec::Assignment);
 }
=20
@@ -246,15 +249,17 @@
 }
=20
=20
-ExprResult Parser::ParseConstantExpression() {
-  // C++ [basic.def.odr]p2:
+ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
+  // C++03 [basic.def.odr]p2:
   //   An expression is potentially evaluated unless it appears where an
   //   integral constant expression is required (see 5.19) [...].
+  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
   EnterExpressionEvaluationContext Unevaluated(Actions,
-                                               Sema::Unevaluated);
+                                               Sema::ConstantEvaluated);
=20
-  ExprResult LHS(ParseCastExpression(false));
-  return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
+  ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
+  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
+  return Actions.ActOnConstantExpression(Res);
 }
=20
 /// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
@@ -263,7 +268,7 @@
 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
   prec::Level NextTokPrec =3D getBinOpPrecedence(Tok.getKind(),
                                                GreaterThanIsOperator,
-                                               getLang().CPlusPlus0x);
+                                               getLangOpts().CPlusPlus0x);
   SourceLocation ColonLoc;
=20
   while (1) {
@@ -311,8 +316,8 @@
         SourceLocation FILoc =3D Tok.getLocation();
         const char *FIText =3D ": ";
         const SourceManager &SM =3D PP.getSourceManager();
-        if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc)) {
-          FILoc =3D SM.getExpansionLoc(FILoc);
+        if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc=
)) {
+          assert(FILoc.isFileID());
           bool IsInvalid =3D false;
           const char *SourcePtr =3D
             SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
@@ -347,9 +352,16 @@
     // be a throw-expression, which is not a valid cast-expression.
     // Therefore we need some special-casing here.
     // Also note that the third operand of the conditional operator is
-    // an assignment-expression in C++.
+    // an assignment-expression in C++, and in C++11, we can have a
+    // braced-init-list on the RHS of an assignment. For better diagnostic=
s,
+    // parse as if we were allowed braced-init-lists everywhere, and check=
 that
+    // they only appear on the RHS of assignments later.
     ExprResult RHS;
-    if (getLang().CPlusPlus && NextTokPrec <=3D prec::Conditional)
+    bool RHSIsInitList =3D false;
+    if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
+      RHS =3D ParseBraceInitializer();
+      RHSIsInitList =3D true;
+    } else if (getLangOpts().CPlusPlus && NextTokPrec <=3D prec::Condition=
al)
       RHS =3D ParseAssignmentExpression();
     else
       RHS =3D ParseCastExpression(false);
@@ -361,7 +373,7 @@
     // operator immediately to the right of the RHS.
     prec::Level ThisPrec =3D NextTokPrec;
     NextTokPrec =3D getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperato=
r,
-                                     getLang().CPlusPlus0x);
+                                     getLangOpts().CPlusPlus0x);
=20
     // Assignment and conditional expressions are right-associative.
     bool isRightAssoc =3D ThisPrec =3D=3D prec::Conditional ||
@@ -371,6 +383,11 @@
     // more tightly with RHS than we do, evaluate it completely first.
     if (ThisPrec < NextTokPrec ||
         (ThisPrec =3D=3D NextTokPrec && isRightAssoc)) {
+      if (!RHS.isInvalid() && RHSIsInitList) {
+        Diag(Tok, diag::err_init_list_bin_op)
+          << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.g=
et());
+        RHS =3D ExprError();
+      }
       // If this is left-associative, only parse things on the RHS that bi=
nd
       // more tightly than the current operator.  If it is left-associativ=
e, it
       // is okay, to bind exactly as tightly.  For example, compile A=3DB=
=3DC=3DD as
@@ -378,15 +395,28 @@
       // The function takes ownership of the RHS.
       RHS =3D ParseRHSOfBinaryExpression(RHS,=20
                             static_cast<prec::Level>(ThisPrec + !isRightAs=
soc));
+      RHSIsInitList =3D false;
=20
       if (RHS.isInvalid())
         LHS =3D ExprError();
=20
       NextTokPrec =3D getBinOpPrecedence(Tok.getKind(), GreaterThanIsOpera=
tor,
-                                       getLang().CPlusPlus0x);
+                                       getLangOpts().CPlusPlus0x);
     }
     assert(NextTokPrec <=3D ThisPrec && "Recursion didn't work!");
=20
+    if (!RHS.isInvalid() && RHSIsInitList) {
+      if (ThisPrec =3D=3D prec::Assignment) {
+        Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_list=
s)
+          << Actions.getExprRange(RHS.get());
+      } else {
+        Diag(OpToken, diag::err_init_list_bin_op)
+          << /*RHS*/1 << PP.getSpelling(OpToken)
+          << Actions.getExprRange(RHS.get());
+        LHS =3D ExprError();
+      }
+    }
+
     if (!LHS.isInvalid()) {
       // Combine the LHS and RHS into the LHS (e.g. build AST).
       if (TernaryMiddle.isInvalid()) {
@@ -416,7 +446,7 @@
 ///
 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
                                        bool isAddressOfOperand,
-                                       bool isTypeCast) {
+                                       TypeCastState isTypeCast) {
   bool NotCastExpr;
   ExprResult Res =3D ParseCastExpression(isUnaryExpression,
                                        isAddressOfOperand,
@@ -427,6 +457,29 @@
   return move(Res);
 }
=20
+namespace {
+class CastExpressionIdValidator : public CorrectionCandidateCallback {
+ public:
+  CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes)
+      : AllowNonTypes(AllowNonTypes) {
+    WantTypeSpecifiers =3D AllowTypes;
+  }
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    NamedDecl *ND =3D candidate.getCorrectionDecl();
+    if (!ND)
+      return candidate.isKeyword();
+
+    if (isa<TypeDecl>(ND))
+      return WantTypeSpecifiers;
+    return AllowNonTypes;
+  }
+
+ private:
+  bool AllowNonTypes;
+};
+}
+
 /// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpressio=
n is
 /// true, parse a unary-expression. isAddressOfOperand exists because an
 /// id-expression that is the operand of address-of gets special treatment
@@ -444,14 +497,14 @@
 ///         unary-operator cast-expression
 ///         'sizeof' unary-expression
 ///         'sizeof' '(' type-name ')'
-/// [C++0x] 'sizeof' '...' '(' identifier ')'
+/// [C++11] 'sizeof' '...' '(' identifier ')'
 /// [GNU]   '__alignof' unary-expression
 /// [GNU]   '__alignof' '(' type-name ')'
-/// [C++0x] 'alignof' '(' type-id ')'
+/// [C++11] 'alignof' '(' type-id ')'
 /// [GNU]   '&&' identifier
+/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
 /// [C++]   new-expression
 /// [C++]   delete-expression
-/// [C++0x] 'noexcept' '(' expression ')'
 ///
 ///       unary-operator: one of
 ///         '&'  '*'  '+'  '-'  '~'  '!'
@@ -463,9 +516,10 @@
 ///         constant
 ///         string-literal
 /// [C++]   boolean-literal  [C++ 2.13.5]
-/// [C++0x] 'nullptr'        [C++0x 2.14.7]
+/// [C++11] 'nullptr'        [C++11 2.14.7]
+/// [C++11] user-defined-literal
 ///         '(' expression ')'
-/// [C1X]   generic-selection
+/// [C11]   generic-selection
 ///         '__func__'        [C99 6.4.2.2]
 /// [GNU]   '__FUNCTION__'
 /// [GNU]   '__PRETTY_FUNCTION__'
@@ -482,9 +536,9 @@
 /// [OBJC]  '@encode' '(' type-name ')'
 /// [OBJC]  objc-string-literal
 /// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5=
.2.3]
-/// [C++0x] simple-type-specifier braced-init-list                  [C++ 5=
.2.3]
+/// [C++11] simple-type-specifier braced-init-list                  [C++11=
 5.2.3]
 /// [C++]   typename-specifier '(' expression-list[opt] ')'         [C++ 5=
.2.3]
-/// [C++0x] typename-specifier braced-init-list                     [C++ 5=
.2.3]
+/// [C++11] typename-specifier braced-init-list                     [C++11=
 5.2.3]
 /// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5=
.2p1]
 /// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5=
.2p1]
 /// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5=
.2p1]
@@ -565,6 +619,7 @@
 ///                   '__is_class'
 ///                   '__is_empty'                            [TODO]
 ///                   '__is_enum'
+///                   '__is_final'
 ///                   '__is_pod'
 ///                   '__is_polymorphic'
 ///                   '__is_trivial'
@@ -590,7 +645,7 @@
 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
                                        bool isAddressOfOperand,
                                        bool &NotCastExpr,
-                                       bool isTypeCast) {
+                                       TypeCastState isTypeCast) {
   ExprResult Res;
   tok::TokenKind SavedKind =3D Tok.getKind();
   NotCastExpr =3D false;
@@ -611,7 +666,7 @@
     // If this expression is limited to being a unary-expression, the pare=
nt can
     // not start a cast expression.
     ParenParseOption ParenExprType =3D
-      (isUnaryExpression && !getLang().CPlusPlus)? CompoundLiteral : CastE=
xpr;
+      (isUnaryExpression && !getLangOpts().CPlusPlus)? CompoundLiteral : C=
astExpr;
     ParsedType CastTy;
     SourceLocation RParenLoc;
    =20
@@ -621,7 +676,7 @@
       ColonProtectionRAIIObject X(*this, false);
=20
       Res =3D ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
-                                 isTypeCast, CastTy, RParenLoc);
+                                 isTypeCast =3D=3D IsTypeCast, CastTy, RPa=
renLoc);
     }
=20
     switch (ParenExprType) {
@@ -645,15 +700,20 @@
     // constant: integer-constant
     // constant: floating-constant
=20
-    Res =3D Actions.ActOnNumericConstant(Tok);
+    Res =3D Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
     ConsumeToken();
     break;
=20
   case tok::kw_true:
   case tok::kw_false:
     return ParseCXXBoolLiteral();
+ =20
+  case tok::kw___objc_yes:
+  case tok::kw___objc_no:
+      return ParseObjCBoolLiteral();
=20
   case tok::kw_nullptr:
+    Diag(Tok, diag::warn_cxx98_compat_nullptr);
     return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
=20
   case tok::annot_primary_expr:
@@ -662,19 +722,21 @@
     ConsumeToken();
     break;
      =20
+  case tok::kw_decltype:
   case tok::identifier: {      // primary-expression: identifier
                                // unqualified-id: identifier
                                // constant: enumeration-constant
     // Turn a potentially qualified name into a annot_typename or
     // annot_cxxscope if it would be valid.  This handles things like x::y=
, etc.
-    if (getLang().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       // Avoid the unnecessary parse-time lookup in the common case
       // where the syntax forbids a type.
       const Token &Next =3D NextToken();
       if (Next.is(tok::coloncolon) ||
           (!ColonIsSacred && Next.is(tok::colon)) ||
           Next.is(tok::less) ||
-          Next.is(tok::l_paren)) {
+          Next.is(tok::l_paren) ||
+          Next.is(tok::l_brace)) {
         // If TryAnnotateTypeOrScopeToken annotates the token, tail recurs=
e.
         if (TryAnnotateTypeOrScopeToken())
           return ExprError();
@@ -689,13 +751,15 @@
     SourceLocation ILoc =3D ConsumeToken();
    =20
     // Support 'Class.property' and 'super.property' notation.
-    if (getLang().ObjC1 && Tok.is(tok::period) &&
+    if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
         (Actions.getTypeName(II, ILoc, getCurScope()) ||
          // Allow the base to be 'super' if in an objc-method.
          (&II =3D=3D Ident_super && getCurScope()->isInObjcMethodScope()))=
) {
       ConsumeToken();
      =20
-      if (Tok.isNot(tok::identifier)) {
+      // Allow either an identifier or the keyword 'class' (in C++).
+      if (Tok.isNot(tok::identifier) &&=20
+          !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
         Diag(Tok, diag::err_expected_property_name);
         return ExprError();
       }
@@ -711,7 +775,7 @@
     // the token sequence is ill-formed. However, if there's a ':' or ']' =
after
     // that identifier, this is probably a message send with a missing open
     // bracket. Treat it as such.=20
-    if (getLang().ObjC1 && &II =3D=3D Ident_super && !InMessageExpression =
&&
+    if (getLangOpts().ObjC1 && &II =3D=3D Ident_super && !InMessageExpress=
ion &&
         getCurScope()->isInObjcMethodScope() &&
         ((Tok.is(tok::identifier) &&
          (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
@@ -726,7 +790,7 @@
     // send that's missing the opening '['. Recovery
     // appropriately. Also take this path if we're performing code
     // completion after an Objective-C class name.
-    if (getLang().ObjC1 &&=20
+    if (getLangOpts().ObjC1 &&=20
         ((Tok.is(tok::identifier) && !InMessageExpression) ||=20
          Tok.is(tok::code_completion))) {
       const Token& Next =3D NextToken();
@@ -764,16 +828,20 @@
     // not.
     UnqualifiedId Name;
     CXXScopeSpec ScopeSpec;
+    SourceLocation TemplateKWLoc;
+    CastExpressionIdValidator Validator(isTypeCast !=3D NotTypeCast,
+                                        isTypeCast !=3D IsTypeCast);
     Name.setIdentifier(&II, ILoc);
-    Res =3D Actions.ActOnIdExpression(getCurScope(), ScopeSpec, Name,=20
-                                    Tok.is(tok::l_paren), isAddressOfOpera=
nd);
+    Res =3D Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKW=
Loc,
+                                    Name, Tok.is(tok::l_paren),
+                                    isAddressOfOperand, &Validator);
     break;
   }
   case tok::char_constant:     // constant: character-constant
   case tok::wide_char_constant:
   case tok::utf16_char_constant:
   case tok::utf32_char_constant:
-    Res =3D Actions.ActOnCharacterConstant(Tok);
+    Res =3D Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
     ConsumeToken();
     break;
   case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.=
2]
@@ -787,9 +855,9 @@
   case tok::utf8_string_literal:
   case tok::utf16_string_literal:
   case tok::utf32_string_literal:
-    Res =3D ParseStringLiteralExpression();
+    Res =3D ParseStringLiteralExpression(true);
     break;
-  case tok::kw__Generic:   // primary-expression: generic-selection [C1X 6=
.5.1]
+  case tok::kw__Generic:   // primary-expression: generic-selection [C11 6=
.5.1]
     Res =3D ParseGenericSelectionExpression();
     break;
   case tok::kw___builtin_va_arg:
@@ -807,7 +875,7 @@
     //     ++ cast-expression
     //     -- cast-expression
     SourceLocation SavedLoc =3D ConsumeToken();
-    Res =3D ParseCastExpression(!getLang().CPlusPlus);
+    Res =3D ParseCastExpression(!getLangOpts().CPlusPlus);
     if (!Res.isInvalid())
       Res =3D Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res=
.get());
     return move(Res);
@@ -909,6 +977,7 @@
     }
     // Fall through
      =20
+  case tok::annot_decltype:
   case tok::kw_char:
   case tok::kw_wchar_t:
   case tok::kw_char16_t:
@@ -918,6 +987,7 @@
   case tok::kw_int:
   case tok::kw_long:
   case tok::kw___int64:
+  case tok::kw___int128:
   case tok::kw_signed:
   case tok::kw_unsigned:
   case tok::kw_half:
@@ -927,7 +997,7 @@
   case tok::kw_typename:
   case tok::kw_typeof:
   case tok::kw___vector: {
-    if (!getLang().CPlusPlus) {
+    if (!getLangOpts().CPlusPlus) {
       Diag(Tok, diag::err_expected_expression);
       return ExprError();
     }
@@ -945,10 +1015,13 @@
     DeclSpec DS(AttrFactory);
     ParseCXXSimpleTypeSpecifier(DS);
     if (Tok.isNot(tok::l_paren) &&
-        (!getLang().CPlusPlus0x || Tok.isNot(tok::l_brace)))
+        (!getLangOpts().CPlusPlus0x || Tok.isNot(tok::l_brace)))
       return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
                          << DS.getSourceRange());
=20
+    if (Tok.is(tok::l_brace))
+      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
+
     Res =3D ParseCXXTypeConstructExpression(DS);
     break;
   }
@@ -970,7 +1043,8 @@
         // type, translate it into a type and continue parsing as a
         // cast expression.
         CXXScopeSpec SS;
-        ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
+        ParseOptionalCXXScopeSpecifier(SS, ParsedType(),=20
+                                       /*EnteringContext=3D*/false);
         AnnotateTemplateIdTokenAsType();
         return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
                                    NotCastExpr, isTypeCast);
@@ -1028,12 +1102,13 @@
     return ParseCXXDeleteExpression(false, Tok.getLocation());
=20
   case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
+    Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
     SourceLocation KeyLoc =3D ConsumeToken();
     BalancedDelimiterTracker T(*this, tok::l_paren);
=20
     if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
       return ExprError();
-    // C++ [expr.unary.noexcept]p1:
+    // C++11 [expr.unary.noexcept]p1:
     //   The noexcept operator determines whether the evaluation of its op=
erand,
     //   which is an unevaluated operand, can throw an exception.
     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluate=
d);
@@ -1081,6 +1156,7 @@
   case tok::kw___is_trivial:
   case tok::kw___is_trivially_copyable:
   case tok::kw___is_union:
+  case tok::kw___is_final:
   case tok::kw___has_trivial_constructor:
   case tok::kw___has_trivial_copy:
   case tok::kw___has_trivial_assign:
@@ -1096,8 +1172,12 @@
   case tok::kw___is_same:
   case tok::kw___is_convertible:
   case tok::kw___is_convertible_to:
+  case tok::kw___is_trivially_assignable:
     return ParseBinaryTypeTrait();
=20
+  case tok::kw___is_trivially_constructible:
+    return ParseTypeTrait();
+     =20
   case tok::kw___array_rank:
   case tok::kw___array_extent:
     return ParseArrayTypeTrait();
@@ -1119,17 +1199,22 @@
     return ExprError();
   }
   case tok::l_square:
-    if (getLang().CPlusPlus0x) {
-      if (getLang().ObjC1) {
+    if (getLangOpts().CPlusPlus0x) {
+      if (getLangOpts().ObjC1) {
+        // C++11 lambda expressions and Objective-C message sends both sta=
rt with a
+        // square bracket.  There are three possibilities here:
+        // we have a valid lambda expression, we have an invalid lambda
+        // expression, or we have something that doesn't appear to be a la=
mbda.
+        // If we're in the last case, we fall back to ParseObjCMessageExpr=
ession.
         Res =3D TryParseLambdaExpression();
-        if (Res.isInvalid())
+        if (!Res.isInvalid() && !Res.get())
           Res =3D ParseObjCMessageExpression();
         break;
       }
       Res =3D ParseLambdaExpression();
       break;
     }
-    if (getLang().ObjC1) {
+    if (getLangOpts().ObjC1) {
       Res =3D ParseObjCMessageExpression();
       break;
     }
@@ -1181,7 +1266,7 @@
       // If we see identifier: after an expression, and we're not already =
in a
       // message send, then this is probably a message send with a missing
       // opening bracket '['.
-      if (getLang().ObjC1 && !InMessageExpression &&=20
+      if (getLangOpts().ObjC1 && !InMessageExpression &&=20
           (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
         LHS =3D ParseObjCMessageExpressionBody(SourceLocation(), SourceLoc=
ation(),
                                              ParsedType(), LHS.get());
@@ -1199,17 +1284,23 @@
       // actually another message send.  In this case, do some look-ahead =
to see
       // if the contents of the square brackets are obviously not a valid
       // expression and recover by pretending there is no suffix.
-      if (getLang().ObjC1 && Tok.isAtStartOfLine() &&
+      if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
           isSimpleObjCMessageExpression())
         return move(LHS);
-      =20
+
+      // Reject array indices starting with a lambda-expression. '[[' is
+      // reserved for attributes.
+      if (CheckProhibitedCXX11Attribute())
+        return ExprError();
+
       BalancedDelimiterTracker T(*this, tok::l_square);
       T.consumeOpen();
       Loc =3D T.getOpenLocation();
       ExprResult Idx;
-      if (getLang().CPlusPlus0x && Tok.is(tok::l_brace))
+      if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
+        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
         Idx =3D ParseBraceInitializer();
-      else
+      } else
         Idx =3D ParseExpression();
=20
       SourceLocation RLoc =3D Tok.getLocation();
@@ -1233,22 +1324,27 @@
      =20
       Expr *ExecConfig =3D 0;
=20
-      BalancedDelimiterTracker LLLT(*this, tok::lesslessless);
       BalancedDelimiterTracker PT(*this, tok::l_paren);
=20
       if (OpKind =3D=3D tok::lesslessless) {
         ExprVector ExecConfigExprs(Actions);
         CommaLocsTy ExecConfigCommaLocs;
-        LLLT.consumeOpen();
+        SourceLocation OpenLoc =3D ConsumeToken();
=20
         if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
           LHS =3D ExprError();
         }
=20
-        if (LHS.isInvalid()) {
+        SourceLocation CloseLoc =3D Tok.getLocation();
+        if (Tok.is(tok::greatergreatergreater)) {
+          ConsumeToken();
+        } else if (LHS.isInvalid()) {
           SkipUntil(tok::greatergreatergreater);
-        } else if (LLLT.consumeClose()) {
+        } else {
           // There was an error closing the brackets
+          Diag(Tok, diag::err_expected_ggg);
+          Diag(OpenLoc, diag::note_matching) << "<<<";
+          SkipUntil(tok::greatergreatergreater);
           LHS =3D ExprError();
         }
=20
@@ -1261,9 +1357,9 @@
=20
         if (!LHS.isInvalid()) {
           ExprResult ECResult =3D Actions.ActOnCUDAExecConfigExpr(getCurSc=
ope(),
-                                    LLLT.getOpenLocation(),=20
+                                    OpenLoc,=20
                                     move_arg(ExecConfigExprs),=20
-                                    LLLT.getCloseLocation());
+                                    CloseLoc);
           if (ECResult.isInvalid())
             LHS =3D ExprError();
           else
@@ -1278,7 +1374,8 @@
       CommaLocsTy CommaLocs;
      =20
       if (Tok.is(tok::code_completion)) {
-        Actions.CodeCompleteCall(getCurScope(), LHS.get(), 0, 0);
+        Actions.CodeCompleteCall(getCurScope(), LHS.get(),
+                                 llvm::ArrayRef<Expr *>());
         cutOffParsing();
         return ExprError();
       }
@@ -1320,14 +1417,15 @@
       CXXScopeSpec SS;
       ParsedType ObjectType;
       bool MayBePseudoDestructor =3D false;
-      if (getLang().CPlusPlus && !LHS.isInvalid()) {
+      if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
         LHS =3D Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.ta=
ke(),
                                                    OpLoc, OpKind, ObjectTy=
pe,
                                                    MayBePseudoDestructor);
         if (LHS.isInvalid())
           break;
=20
-        ParseOptionalCXXScopeSpecifier(SS, ObjectType, false,
+        ParseOptionalCXXScopeSpecifier(SS, ObjectType,=20
+                                       /*EnteringContext=3D*/false,
                                        &MayBePseudoDestructor);
         if (SS.isNotEmpty())
           ObjectType =3D ParsedType();
@@ -1355,18 +1453,31 @@
       // names a real destructor.
       // Allow explicit constructor calls in Microsoft mode.
       // FIXME: Add support for explicit call of template constructor.
+      SourceLocation TemplateKWLoc;
       UnqualifiedId Name;
-      if (ParseUnqualifiedId(SS,=20
-                             /*EnteringContext=3D*/false,=20
-                             /*AllowDestructorName=3D*/true,
-                             /*AllowConstructorName=3D*/ getLang().Microso=
ftExt,=20
-                             ObjectType,
-                             Name))
+      if (getLangOpts().ObjC2 && OpKind =3D=3D tok::period && Tok.is(tok::=
kw_class)) {
+        // Objective-C++:
+        //   After a '.' in a member access expression, treat the keyword
+        //   'class' as if it were an identifier.
+        //
+        // This hack allows property access to the 'class' method because =
it is
+        // such a common method name. For other C++ keywords that are=20
+        // Objective-C method names, one must use the message send syntax.
+        IdentifierInfo *Id =3D Tok.getIdentifierInfo();
+        SourceLocation Loc =3D ConsumeToken();
+        Name.setIdentifier(Id, Loc);
+      } else if (ParseUnqualifiedId(SS,=20
+                                    /*EnteringContext=3D*/false,=20
+                                    /*AllowDestructorName=3D*/true,
+                                    /*AllowConstructorName=3D*/
+                                      getLangOpts().MicrosoftExt,=20
+                                    ObjectType, TemplateKWLoc, Name))
         LHS =3D ExprError();
      =20
       if (!LHS.isInvalid())
         LHS =3D Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), O=
pLoc,=20
-                                            OpKind, SS, Name, ObjCImpDecl,
+                                            OpKind, SS, TemplateKWLoc, Nam=
e,
+                                 CurParsedObjCImpl ? CurParsedObjCImpl->Dc=
l : 0,
                                             Tok.is(tok::l_paren));
       break;
     }
@@ -1419,19 +1530,11 @@
   // If the operand doesn't start with an '(', it must be an expression.
   if (Tok.isNot(tok::l_paren)) {
     isCastExpr =3D false;
-    if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) {
+    if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
       Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierI=
nfo();
       return ExprError();
     }
=20
-    // C++0x [expr.sizeof]p1:
-    //   [...] The operand is either an expression, which is an unevaluated
-    //   operand (Clause 5) [...]
-    //
-    // The GNU typeof and alignof extensions also behave as unevaluated
-    // operands.
-    EnterExpressionEvaluationContext Unevaluated(Actions,
-                                                 Sema::Unevaluated);
     Operand =3D ParseCastExpression(true/*isUnaryExpression*/);
   } else {
     // If it starts with a '(', we know that it is either a parenthesized
@@ -1441,14 +1544,6 @@
     ParenParseOption ExprType =3D CastExpr;
     SourceLocation LParenLoc =3D Tok.getLocation(), RParenLoc;
=20
-    // C++0x [expr.sizeof]p1:
-    //   [...] The operand is either an expression, which is an unevaluated
-    //   operand (Clause 5) [...]
-    //
-    // The GNU typeof and alignof extensions also behave as unevaluated
-    // operands.
-    EnterExpressionEvaluationContext Unevaluated(Actions,
-                                                 Sema::Unevaluated);
     Operand =3D ParseParenExpression(ExprType, true/*stopIfCastExpr*/,=20
                                    false, CastTy, RParenLoc);
     CastRange =3D SourceRange(LParenLoc, RParenLoc);
@@ -1460,7 +1555,7 @@
       return ExprEmpty();
     }
=20
-    if (getLang().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
+    if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
       // GNU typeof in C requires the expression to be parenthesized. Not =
so for
       // sizeof/alignof or in C++. Therefore, the parenthesized expression=
 is
       // the start of a unary-expression, but doesn't include any postfix=20
@@ -1533,7 +1628,12 @@
                                                 *Name, NameLoc,
                                                 RParenLoc);
   }
- =20
+
+  if (OpTok.is(tok::kw_alignof))
+    Diag(OpTok, diag::warn_cxx98_compat_alignof);
+
+  EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
+
   bool isCastExpr;
   ParsedType CastTy;
   SourceRange CastRange;
@@ -1573,7 +1673,7 @@
 /// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
 ///                                     assign-expr ')'
 /// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
-/// [OCL]   '__builtin_astype' '(' type-name expr ')'
+/// [OCL]   '__builtin_astype' '(' assignment-expression ',' type-name ')'
 ///
 /// [GNU] offsetof-member-designator:
 /// [GNU]   identifier
@@ -1661,6 +1761,9 @@
         Comps.back().LocEnd =3D ConsumeToken();
=20
       } else if (Tok.is(tok::l_square)) {
+        if (CheckProhibitedCXX11Attribute())
+          return ExprError();
+
         // offsetof-member-designator: offsetof-member-design '[' expressi=
on ']'
         Comps.push_back(Sema::OffsetOfComponent());
         Comps.back().isBrackets =3D true;
@@ -1803,23 +1906,40 @@
     return ExprError();
   }
=20
+  // Diagnose use of bridge casts in non-arc mode.
+  bool BridgeCast =3D (getLangOpts().ObjC2 &&
+                     (Tok.is(tok::kw___bridge) ||=20
+                      Tok.is(tok::kw___bridge_transfer) ||
+                      Tok.is(tok::kw___bridge_retained) ||
+                      Tok.is(tok::kw___bridge_retain)));
+  if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
+    StringRef BridgeCastName =3D Tok.getName();
+    SourceLocation BridgeKeywordLoc =3D ConsumeToken();
+    if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
+      Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
+        << BridgeCastName
+        << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
+    BridgeCast =3D false;
+  }
+ =20
   // None of these cases should fall through with an invalid Result
   // unless they've already reported an error.
- =20
   if (ExprType >=3D CompoundStmt && Tok.is(tok::l_brace)) {
     Diag(Tok, diag::ext_gnu_statement_expr);
+
+    Actions.ActOnStartStmtExpr();
+
     ParsedAttributes attrs(AttrFactory);
     StmtResult Stmt(ParseCompoundStatement(attrs, true));
     ExprType =3D CompoundStmt;
=20
     // If the substmt parsed correctly, build the AST node.
-    if (!Stmt.isInvalid())
+    if (!Stmt.isInvalid()) {
       Result =3D Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocati=
on());
-  } else if (ExprType >=3D CompoundLiteral &&=20
-             (Tok.is(tok::kw___bridge) ||=20
-              Tok.is(tok::kw___bridge_transfer) ||
-              Tok.is(tok::kw___bridge_retained) ||
-              Tok.is(tok::kw___bridge_retain))) {
+    } else {
+      Actions.ActOnStmtExprError();
+    }
+  } else if (ExprType >=3D CompoundLiteral && BridgeCast) {
     tok::TokenKind tokenKind =3D Tok.getKind();
     SourceLocation BridgeKeywordLoc =3D ConsumeToken();
=20
@@ -1879,7 +1999,7 @@
     // this is probably an Objective-C message send where the leading '[' =
is
     // missing. Recover as if that were the case.
     if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
-        !InMessageExpression && getLang().ObjC1 &&
+        !InMessageExpression && getLangOpts().ObjC1 &&
         (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
       TypeResult Ty;
       {
@@ -1922,7 +2042,7 @@
         }
        =20
         // Reject the cast of super idiom in ObjC.
-        if (Tok.is(tok::identifier) && getLang().ObjC1 &&
+        if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
             Tok.getIdentifierInfo() =3D=3D Ident_super &&=20
             getCurScope()->isInObjcMethodScope() &&
             GetLookAheadToken(1).isNot(tok::period)) {
@@ -1935,7 +2055,7 @@
         // TODO: For cast expression with CastTy.
         Result =3D ParseCastExpression(/*isUnaryExpression=3D*/false,
                                      /*isAddressOfOperand=3D*/false,
-                                     /*isTypeCast=3D*/true);
+                                     /*isTypeCast=3D*/IsTypeCast);
         if (!Result.isInvalid()) {
           Result =3D Actions.ActOnCastExpr(getCurScope(), OpenLoc,
                                          DeclaratorInfo, CastTy,=20
@@ -1956,13 +2076,13 @@
=20
     if (!ParseExpressionList(ArgExprs, CommaLocs)) {
       ExprType =3D SimpleExpr;
-      Result =3D Actions.ActOnParenOrParenListExpr(OpenLoc, Tok.getLocatio=
n(),
-                                                 move_arg(ArgExprs));
+      Result =3D Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
+                                          move_arg(ArgExprs));
     }
   } else {
     InMessageExpressionRAIIObject InMessage(*this, false);
    =20
-    Result =3D ParseExpression();
+    Result =3D ParseExpression(MaybeTypeCast);
     ExprType =3D SimpleExpr;
=20
     // Don't build a paren expression unless we actually match a ')'.
@@ -1993,7 +2113,7 @@
                                        SourceLocation LParenLoc,
                                        SourceLocation RParenLoc) {
   assert(Tok.is(tok::l_brace) && "Not a compound literal!");
-  if (!getLang().C99)   // Compound literals don't exist in C90.
+  if (!getLangOpts().C99)   // Compound literals don't exist in C90.
     Diag(LParenLoc, diag::ext_c99_compound_literal);
   ExprResult Result =3D ParseInitializer();
   if (!Result.isInvalid() && Ty)
@@ -2007,7 +2127,7 @@
 ///
 ///       primary-expression: [C99 6.5.1]
 ///         string-literal
-ExprResult Parser::ParseStringLiteralExpression() {
+ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiter=
al) {
   assert(isTokenStringLiteral() && "Not a string literal!");
=20
   // String concat.  Note that keywords like __func__ and __FUNCTION__ are=
 not
@@ -2020,11 +2140,12 @@
   } while (isTokenStringLiteral());
=20
   // Pass the set of string tokens, ready for concatenation, to the action=
s.
-  return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
+  return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size(),
+                                   AllowUserDefinedLiteral ? getCurScope()=
 : 0);
 }
=20
-/// ParseGenericSelectionExpression - Parse a C1X generic-selection
-/// [C1X 6.5.1.1].
+/// ParseGenericSelectionExpression - Parse a C11 generic-selection
+/// [C11 6.5.1.1].
 ///
 ///    generic-selection:
 ///           _Generic ( assignment-expression , generic-assoc-list )
@@ -2038,8 +2159,8 @@
   assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
   SourceLocation KeyLoc =3D ConsumeToken();
=20
-  if (!getLang().C1X)
-    Diag(KeyLoc, diag::ext_c1x_generic_selection);
+  if (!getLangOpts().C11)
+    Diag(KeyLoc, diag::ext_c11_generic_selection);
=20
   BalancedDelimiterTracker T(*this, tok::l_paren);
   if (T.expectAndConsume(diag::err_expected_lparen))
@@ -2047,7 +2168,7 @@
=20
   ExprResult ControllingExpr;
   {
-    // C1X 6.5.1.1p3 "The controlling expression of a generic selection is
+    // C11 6.5.1.1p3 "The controlling expression of a generic selection is
     // not evaluated."
     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluate=
d);
     ControllingExpr =3D ParseAssignmentExpression();
@@ -2068,7 +2189,7 @@
   while (1) {
     ParsedType Ty;
     if (Tok.is(tok::kw_default)) {
-      // C1X 6.5.1.1p2 "A generic selection shall have no more than one de=
fault
+      // C11 6.5.1.1p2 "A generic selection shall have no more than one de=
fault
       // generic association."
       if (!DefaultLoc.isInvalid()) {
         Diag(Tok, diag::err_duplicate_default_assoc);
@@ -2143,13 +2264,12 @@
                             SmallVectorImpl<SourceLocation> &CommaLocs,
                                  void (Sema::*Completer)(Scope *S,=20
                                                            Expr *Data,
-                                                           Expr **Args,
-                                                           unsigned NumArg=
s),
+                                                   llvm::ArrayRef<Expr *> =
Args),
                                  Expr *Data) {
   while (1) {
     if (Tok.is(tok::code_completion)) {
       if (Completer)
-        (Actions.*Completer)(getCurScope(), Data, Exprs.data(), Exprs.size=
());
+        (Actions.*Completer)(getCurScope(), Data, Exprs);
       else
         Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expressi=
on);
       cutOffParsing();
@@ -2157,9 +2277,10 @@
     }
=20
     ExprResult Expr;
-    if (getLang().CPlusPlus0x && Tok.is(tok::l_brace))
+    if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
+      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
       Expr =3D ParseBraceInitializer();
-    else
+    } else
       Expr =3D ParseAssignmentExpression();
=20
     if (Tok.is(tok::ellipsis))
@@ -2225,7 +2346,6 @@
   // allows determining whether a variable reference inside the block is
   // within or outside of the block.
   ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
-                              Scope::BreakScope | Scope::ContinueScope |
                               Scope::DeclScope);
=20
   // Inform sema that we are starting a block.
@@ -2270,6 +2390,8 @@
                                                        0, 0, 0,
                                                        true, SourceLocatio=
n(),
                                                        SourceLocation(),
+                                                       SourceLocation(),
+                                                       SourceLocation(),
                                                        EST_None,
                                                        SourceLocation(),
                                                        0, 0, 0, 0,
@@ -2300,3 +2422,12 @@
     Actions.ActOnBlockError(CaretLoc, getCurScope());
   return move(Result);
 }
+
+/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
+///
+///         '__objc_yes'
+///         '__objc_no'
+ExprResult Parser::ParseObjCBoolLiteral() {
+  tok::TokenKind Kind =3D Tok.getKind();
+  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseExprCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseExprCXX.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -14,6 +14,8 @@
 #include "clang/Parse/ParseDiagnostic.h"
 #include "clang/Parse/Parser.h"
 #include "RAIIObjectsForParser.h"
+#include "clang/Basic/PrettyStackTrace.h"
+#include "clang/Lex/LiteralSupport.h"
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ParsedTemplate.h"
@@ -136,7 +138,7 @@
                                             bool EnteringContext,
                                             bool *MayBePseudoDestructor,
                                             bool IsTypename) {
-  assert(getLang().CPlusPlus &&
+  assert(getLangOpts().CPlusPlus &&
          "Call sites of this function should be guarded by checking for C+=
+");
=20
   if (Tok.is(tok::annot_cxxscope)) {
@@ -168,6 +170,22 @@
     *MayBePseudoDestructor =3D false;
   }
=20
+  if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
+    DeclSpec DS(AttrFactory);
+    SourceLocation DeclLoc =3D Tok.getLocation();
+    SourceLocation EndLoc  =3D ParseDecltypeSpecifier(DS);
+    if (Tok.isNot(tok::coloncolon)) {
+      AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
+      return false;
+    }
+   =20
+    SourceLocation CCLoc =3D ConsumeToken();
+    if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
+      SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
+
+    HasScopeSpecifier =3D true;
+  }
+
   while (true) {
     if (HasScopeSpecifier) {
       // C++ [basic.lookup.classref]p5:
@@ -247,15 +265,13 @@
       // Commit to parsing the template-id.
       TPA.Commit();
       TemplateTy Template;
-      if (TemplateNameKind TNK =3D Actions.ActOnDependentTemplateName(getC=
urScope(),=20
-                                                                TemplateKW=
Loc,=20
-                                                                    SS,=20
-                                                                  Template=
Name,
-                                                                    Object=
Type,=20
-                                                                EnteringCo=
ntext,
-                                                                    Templa=
te)) {
-        if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,=20
-                                    TemplateKWLoc, false))
+      if (TemplateNameKind TNK
+          =3D Actions.ActOnDependentTemplateName(getCurScope(),
+                                               SS, TemplateKWLoc, Template=
Name,
+                                               ObjectType, EnteringContext,
+                                               Template)) {
+        if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
+                                    TemplateName, false))
           return true;
       } else
         return true;
@@ -283,16 +299,15 @@
       assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!=
");
       SourceLocation CCLoc =3D ConsumeToken();
=20
-      if (!HasScopeSpecifier)
-        HasScopeSpecifier =3D true;
+      HasScopeSpecifier =3D true;
      =20
       ASTTemplateArgsPtr TemplateArgsPtr(Actions,
                                          TemplateId->getTemplateArgs(),
                                          TemplateId->NumArgs);
      =20
       if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
-                                              /*FIXME:*/SourceLocation(),
-                                              SS,=20
+                                              SS,
+                                              TemplateId->TemplateKWLoc,
                                               TemplateId->Template,
                                               TemplateId->TemplateNameLoc,
                                               TemplateId->LAngleLoc,
@@ -381,15 +396,15 @@
                                                         EnteringContext,
                                                         Template,
                                               MemberOfUnknownSpecializatio=
n)) {
-        // We have found a template name, so annotate this this token
+        // We have found a template name, so annotate this token
         // with a template-id annotation. We do not permit the
         // template-id to be translated into a type annotation,
         // because some clients (e.g., the parsing of class template
         // specializations) still want to see the original template-id
         // token.
         ConsumeToken();
-        if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,=20
-                                    SourceLocation(), false))
+        if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
+                                    TemplateName, false))
           return true;
         continue;
       }=20
@@ -401,7 +416,7 @@
         // parse correctly as a template, so suggest the keyword 'template'
         // before 'getAs' and treat this as a dependent template name.
         unsigned DiagID =3D diag::err_missing_dependent_template_keyword;
-        if (getLang().MicrosoftExt)
+        if (getLangOpts().MicrosoftExt)
           DiagID =3D diag::warn_missing_dependent_template_keyword;
        =20
         Diag(Tok.getLocation(), DiagID)
@@ -410,14 +425,14 @@
        =20
         if (TemplateNameKind TNK=20
               =3D Actions.ActOnDependentTemplateName(getCurScope(),=20
-                                                   Tok.getLocation(), SS,=20
+                                                   SS, SourceLocation(),
                                                    TemplateName, ObjectTyp=
e,
                                                    EnteringContext, Templa=
te)) {
           // Consume the identifier.
           ConsumeToken();
-          if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName,=20
-                                      SourceLocation(), false))
-            return true;               =20
+          if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
+                                      TemplateName, false))
+            return true;
         }
         else
           return true;    =20
@@ -488,14 +503,16 @@
   //   '::' unqualified-id
   //
   CXXScopeSpec SS;
-  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
- =20
+  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=3D*/f=
alse);
+
+  SourceLocation TemplateKWLoc;
   UnqualifiedId Name;
-  if (ParseUnqualifiedId(SS,=20
-                         /*EnteringContext=3D*/false,=20
-                         /*AllowDestructorName=3D*/false,=20
-                         /*AllowConstructorName=3D*/false,=20
+  if (ParseUnqualifiedId(SS,
+                         /*EnteringContext=3D*/false,
+                         /*AllowDestructorName=3D*/false,
+                         /*AllowConstructorName=3D*/false,
                          /*ObjectType=3D*/ ParsedType(),
+                         TemplateKWLoc,
                          Name))
     return ExprError();
=20
@@ -503,10 +520,9 @@
   // followed by a postfix-expression suffix.
   if (isAddressOfOperand && isPostfixExpressionSuffixStart())
     isAddressOfOperand =3D false;
- =20
-  return Actions.ActOnIdExpression(getCurScope(), SS, Name, Tok.is(tok::l_=
paren),
-                                   isAddressOfOperand);
- =20
+
+  return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
+                                   Tok.is(tok::l_paren), isAddressOfOperan=
d);
 }
=20
 /// ParseLambdaExpression - Parse a C++0x lambda expression.
@@ -548,6 +564,9 @@
   if (DiagID) {
     Diag(Tok, DiagID.getValue());
     SkipUntil(tok::r_square);
+    SkipUntil(tok::l_brace);
+    SkipUntil(tok::r_brace);
+    return ExprError();
   }
=20
   return ParseLambdaExpressionAfterIntroducer(Intro);
@@ -559,7 +578,7 @@
 ///
 /// If we are not looking at a lambda expression, returns ExprError().
 ExprResult Parser::TryParseLambdaExpression() {
-  assert(getLang().CPlusPlus0x
+  assert(getLangOpts().CPlusPlus0x
          && Tok.is(tok::l_square)
          && "Not at the start of a possible lambda expression.");
=20
@@ -576,21 +595,28 @@
     return ParseLambdaExpression();
   }
=20
-  // If lookahead indicates this is an Objective-C message...
+  // If lookahead indicates an ObjC message send...
+  // [identifier identifier
   if (Next.is(tok::identifier) && After.is(tok::identifier)) {
-    return ExprError();
+    return ExprEmpty();
   }
=20
+  // Here, we're stuck: lambda introducers and Objective-C message sends a=
re
+  // unambiguous, but it requires arbitrary lookhead.  [a,b,c,d,e,f,g] is a
+  // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send.  Instead=
 of
+  // writing two routines to parse a lambda introducer, just try to parse
+  // a lambda introducer first, and fall back if that fails.
+  // (TryParseLambdaIntroducer never produces any diagnostic output.)
   LambdaIntroducer Intro;
   if (TryParseLambdaIntroducer(Intro))
-    return ExprError();
+    return ExprEmpty();
   return ParseLambdaExpressionAfterIntroducer(Intro);
 }
=20
 /// ParseLambdaExpression - Parse a lambda introducer.
 ///
 /// Returns a DiagnosticID if it hit something unexpected.
-llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &I=
ntro) {
+llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &I=
ntro){
   typedef llvm::Optional<unsigned> DiagResult;
=20
   assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
@@ -605,28 +631,49 @@
   if (Tok.is(tok::amp) &&
       (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
     Intro.Default =3D LCD_ByRef;
-    ConsumeToken();
+    Intro.DefaultLoc =3D ConsumeToken();
     first =3D false;
   } else if (Tok.is(tok::equal)) {
     Intro.Default =3D LCD_ByCopy;
-    ConsumeToken();
+    Intro.DefaultLoc =3D ConsumeToken();
     first =3D false;
   }
=20
   while (Tok.isNot(tok::r_square)) {
     if (!first) {
-      if (Tok.isNot(tok::comma))
+      if (Tok.isNot(tok::comma)) {
+        if (Tok.is(tok::code_completion)) {
+          Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,=20
+                                               /*AfterAmpersand=3D*/false);
+          ConsumeCodeCompletionToken();
+          break;
+        }
+
         return DiagResult(diag::err_expected_comma_or_rsquare);
+      }
       ConsumeToken();
     }
=20
+    if (Tok.is(tok::code_completion)) {
+      // If we're in Objective-C++ and we have a bare '[', then this is mo=
re
+      // likely to be a message receiver.
+      if (getLangOpts().ObjC1 && first)
+        Actions.CodeCompleteObjCMessageReceiver(getCurScope());
+      else
+        Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,=20
+                                             /*AfterAmpersand=3D*/false);
+      ConsumeCodeCompletionToken();
+      break;
+    }
+
     first =3D false;
-
+   =20
     // Parse capture.
     LambdaCaptureKind Kind =3D LCK_ByCopy;
     SourceLocation Loc;
     IdentifierInfo* Id =3D 0;
-
+    SourceLocation EllipsisLoc;
+   =20
     if (Tok.is(tok::kw_this)) {
       Kind =3D LCK_This;
       Loc =3D ConsumeToken();
@@ -634,11 +681,21 @@
       if (Tok.is(tok::amp)) {
         Kind =3D LCK_ByRef;
         ConsumeToken();
+
+        if (Tok.is(tok::code_completion)) {
+          Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,=20
+                                               /*AfterAmpersand=3D*/true);
+          ConsumeCodeCompletionToken();
+          break;
+        }
       }
=20
       if (Tok.is(tok::identifier)) {
         Id =3D Tok.getIdentifierInfo();
         Loc =3D ConsumeToken();
+       =20
+        if (Tok.is(tok::ellipsis))
+          EllipsisLoc =3D ConsumeToken();
       } else if (Tok.is(tok::kw_this)) {
         // FIXME: If we want to suggest a fixit here, will need to return =
more
         // than just DiagnosticID. Perhaps full DiagnosticBuilder that can=
 be
@@ -649,7 +706,7 @@
       }
     }
=20
-    Intro.addCapture(Kind, Loc, Id);
+    Intro.addCapture(Kind, Loc, Id, EllipsisLoc);
   }
=20
   T.consumeClose();
@@ -658,7 +715,7 @@
   return DiagResult();
 }
=20
-/// TryParseLambdaExpression - Tentatively parse a lambda introducer.
+/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
 ///
 /// Returns true if it hit something unexpected.
 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
@@ -679,9 +736,15 @@
 /// expression.
 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
                      LambdaIntroducer &Intro) {
+  SourceLocation LambdaBeginLoc =3D Intro.Range.getBegin();
+  Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
+
+  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
+                                "lambda expression parsing");
+
   // Parse lambda-declarator[opt].
   DeclSpec DS(AttrFactory);
-  Declarator D(DS, Declarator::PrototypeContext);
+  Declarator D(DS, Declarator::LambdaExprContext);
=20
   if (Tok.is(tok::l_paren)) {
     ParseScope PrototypeScope(this,
@@ -746,6 +809,8 @@
                                            DS.getTypeQualifiers(),
                                            /*RefQualifierIsLValueRef=3D*/t=
rue,
                                            /*RefQualifierLoc=3D*/SourceLoc=
ation(),
+                                         /*ConstQualifierLoc=3D*/SourceLoc=
ation(),
+                                      /*VolatileQualifierLoc=3D*/SourceLoc=
ation(),
                                            MutableLoc,
                                            ESpecType, ESpecRange.getBegin(=
),
                                            DynamicExceptions.data(),
@@ -756,24 +821,78 @@
                                            DeclLoc, DeclEndLoc, D,
                                            TrailingReturnType),
                   Attr, DeclEndLoc);
+  } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
+    // It's common to forget that one needs '()' before 'mutable' or the=20
+    // result type. Deal with this.
+    Diag(Tok, diag::err_lambda_missing_parens)
+      << Tok.is(tok::arrow)
+      << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
+    SourceLocation DeclLoc =3D Tok.getLocation();
+    SourceLocation DeclEndLoc =3D DeclLoc;
+   =20
+    // Parse 'mutable', if it's there.
+    SourceLocation MutableLoc;
+    if (Tok.is(tok::kw_mutable)) {
+      MutableLoc =3D ConsumeToken();
+      DeclEndLoc =3D MutableLoc;
+    }
+   =20
+    // Parse the return type, if there is one.
+    ParsedType TrailingReturnType;
+    if (Tok.is(tok::arrow)) {
+      SourceRange Range;
+      TrailingReturnType =3D ParseTrailingReturnType(Range).get();
+      if (Range.getEnd().isValid())
+        DeclEndLoc =3D Range.getEnd();     =20
+    }
+
+    ParsedAttributes Attr(AttrFactory);
+    D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=3D*/true,
+                     /*isVariadic=3D*/false,
+                     /*EllipsisLoc=3D*/SourceLocation(),
+                     /*Params=3D*/0, /*NumParams=3D*/0,
+                     /*TypeQuals=3D*/0,
+                     /*RefQualifierIsLValueRef=3D*/true,
+                     /*RefQualifierLoc=3D*/SourceLocation(),
+                     /*ConstQualifierLoc=3D*/SourceLocation(),
+                     /*VolatileQualifierLoc=3D*/SourceLocation(),
+                     MutableLoc,
+                     EST_None,=20
+                     /*ESpecLoc=3D*/SourceLocation(),
+                     /*Exceptions=3D*/0,
+                     /*ExceptionRanges=3D*/0,
+                     /*NumExceptions=3D*/0,
+                     /*NoexceptExpr=3D*/0,
+                     DeclLoc, DeclEndLoc, D,
+                     TrailingReturnType),
+                  Attr, DeclEndLoc);
+  }
+ =20
+
+  // FIXME: Rename BlockScope -> ClosureScope if we decide to continue usi=
ng
+  // it.
+  unsigned ScopeFlags =3D Scope::BlockScope | Scope::FnScope | Scope::Decl=
Scope;
+  if (getCurScope()->getFlags() & Scope::ThisScope)
+    ScopeFlags |=3D Scope::ThisScope;
+  ParseScope BodyScope(this, ScopeFlags);
+
+  Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
+
+  // Parse compound-statement.
+  if (!Tok.is(tok::l_brace)) {
+    Diag(Tok, diag::err_expected_lambda_body);
+    Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
+    return ExprError();
   }
=20
-  // Parse compound-statement.
-  if (Tok.is(tok::l_brace)) {
-    // FIXME: Rename BlockScope -> ClosureScope if we decide to continue u=
sing
-    // it.
-    ParseScope BodyScope(this, Scope::BlockScope | Scope::FnScope |
-                               Scope::BreakScope | Scope::ContinueScope |
-                               Scope::DeclScope);
+  StmtResult Stmt(ParseCompoundStatementBody());
+  BodyScope.Exit();
=20
-    StmtResult Stmt(ParseCompoundStatementBody());
-
-    BodyScope.Exit();
-  } else {
-    Diag(Tok, diag::err_expected_lambda_body);
-  }
-
-  return ExprEmpty();
+  if (!Stmt.isInvalid())
+    return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScop=
e());
+=20
+  Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
+  return ExprError();
 }
=20
 /// ParseCXXCasts - This handles the various ways to cast expressions to a=
nother
@@ -882,10 +1001,10 @@
     //   operand (Clause 5).
     //
     // Note that we can't tell whether the expression is an lvalue of a
-    // polymorphic class type until after we've parsed the expression, so
-    // we the expression is potentially potentially evaluated.
-    EnterExpressionEvaluationContext Unevaluated(Actions,
-                                       Sema::PotentiallyPotentiallyEvaluat=
ed);
+    // polymorphic class type until after we've parsed the expression; we
+    // speculatively assume the subexpression is unevaluated, and fix it up
+    // later.
+    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluate=
d);
     Result =3D ParseExpression();
=20
     // Match the ')'.
@@ -988,6 +1107,8 @@
     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"=
);
     CCLoc =3D ConsumeToken();
   } else if (Tok.is(tok::annot_template_id)) {
+    // FIXME: retrieve TemplateKWLoc from template-id annotation and
+    // store it in the pseudo-dtor node (to be used when instantiating it).
     FirstTypeName.setTemplateId(
                               (TemplateIdAnnotation *)Tok.getAnnotationVal=
ue());
     ConsumeToken();
@@ -1000,6 +1121,17 @@
   // Parse the tilde.
   assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
   SourceLocation TildeLoc =3D ConsumeToken();
+
+  if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()=
) {
+    DeclSpec DS(AttrFactory);
+    ParseDecltypeSpecifier(DS);
+    if (DS.getTypeSpecType() =3D=3D TST_error)
+      return ExprError();
+    return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,=20
+                                             OpKind, TildeLoc, DS,=20
+                                             Tok.is(tok::l_paren));
+  }
+
   if (!Tok.is(tok::identifier)) {
     Diag(Tok, diag::err_destructor_tilde_identifier);
     return ExprError();
@@ -1014,9 +1146,10 @@
   // If there is a '<', the second type name is a template-id. Parse
   // it as such.
   if (Tok.is(tok::less) &&
-      ParseUnqualifiedIdTemplateId(SS, Name, NameLoc, false, ObjectType,
-                                   SecondTypeName, /*AssumeTemplateName=3D=
*/true,
-                                   /*TemplateKWLoc*/SourceLocation()))
+      ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
+                                   Name, NameLoc,
+                                   false, ObjectType, SecondTypeName,
+                                   /*AssumeTemplateName=3D*/true))
     return ExprError();
=20
   return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
@@ -1092,14 +1225,17 @@
   ParsedType TypeRep =3D Actions.ActOnTypeName(getCurScope(), DeclaratorIn=
fo).get();
=20
   assert((Tok.is(tok::l_paren) ||
-          (getLang().CPlusPlus0x && Tok.is(tok::l_brace)))
+          (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)))
          && "Expected '(' or '{'!");
=20
   if (Tok.is(tok::l_brace)) {
-
-    // FIXME: Convert to a proper type construct expression.
-    return ParseBraceInitializer();
-
+    ExprResult Init =3D ParseBraceInitializer();
+    if (Init.isInvalid())
+      return Init;
+    Expr *InitList =3D Init.take();
+    return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
+                                             MultiExprArg(&InitList, 1),
+                                             SourceLocation());
   } else {
     GreaterThanIsOperatorScope G(GreaterThanIsOperator, true);
=20
@@ -1136,6 +1272,8 @@
 ///       condition:
 ///         expression
 ///         type-specifier-seq declarator '=3D' assignment-expression
+/// [C++11] type-specifier-seq declarator '=3D' initializer-clause
+/// [C++11] type-specifier-seq declarator braced-init-list
 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[=
opt]
 ///             '=3D' assignment-expression
 ///
@@ -1206,18 +1344,35 @@
   ExprOut =3D ExprError();
=20
   // '=3D' assignment-expression
-  if (isTokenEqualOrMistypedEqualEqual(
-                               diag::err_invalid_equalequal_after_declarat=
or)) {
+  // If a '=3D=3D' or '+=3D' is found, suggest a fixit to '=3D'.
+  bool CopyInitialization =3D isTokenEqualOrEqualTypo();
+  if (CopyInitialization)
     ConsumeToken();
-    ExprResult AssignExpr(ParseAssignmentExpression());
-    if (!AssignExpr.isInvalid())=20
-      Actions.AddInitializerToDecl(DeclOut, AssignExpr.take(), false,
-                                   DS.getTypeSpecType() =3D=3D DeclSpec::T=
ST_auto);
+
+  ExprResult InitExpr =3D ExprError();
+  if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
+    Diag(Tok.getLocation(),
+         diag::warn_cxx98_compat_generalized_initializer_lists);
+    InitExpr =3D ParseBraceInitializer();
+  } else if (CopyInitialization) {
+    InitExpr =3D ParseAssignmentExpression();
+  } else if (Tok.is(tok::l_paren)) {
+    // This was probably an attempt to initialize the variable.
+    SourceLocation LParen =3D ConsumeParen(), RParen =3D LParen;
+    if (SkipUntil(tok::r_paren, true, /*DontConsume=3D*/true))
+      RParen =3D ConsumeParen();
+    Diag(DeclOut ? DeclOut->getLocation() : LParen,
+         diag::err_expected_init_in_condition_lparen)
+      << SourceRange(LParen, RParen);
   } else {
-    // FIXME: C++0x allows a braced-init-list
-    Diag(Tok, diag::err_expected_equal_after_declarator);
+    Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
+         diag::err_expected_init_in_condition);
   }
- =20
+
+  if (!InitExpr.isInvalid())
+    Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitializa=
tion,
+                                 DS.getTypeSpecType() =3D=3D DeclSpec::TST=
_auto);
+
   // FIXME: Build a reference to this declaration? Convert it to bool?
   // (This is currently handled by Sema).
=20
@@ -1234,6 +1389,7 @@
   case tok::kw_short:
   case tok::kw_long:
   case tok::kw___int64:
+  case tok::kw___int128:
   case tok::kw_signed:
   case tok::kw_unsigned:
   case tok::kw_void:
@@ -1312,7 +1468,7 @@
     // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
     // Objective-C interface.  If we don't have Objective-C or a '<', this=
 is
     // just a normal reference to a typedef name.
-    if (Tok.is(tok::less) && getLang().ObjC1)
+    if (Tok.is(tok::less) && getLangOpts().ObjC1)
       ParseObjCProtocolQualifiers(DS);
    =20
     DS.Finish(Diags, PP);
@@ -1344,6 +1500,9 @@
   case tok::kw_int:
     DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
     break;
+  case tok::kw___int128:
+    DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
+    break;
   case tok::kw_half:
     DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
     break;
@@ -1365,8 +1524,11 @@
   case tok::kw_bool:
     DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
     break;
+  case tok::annot_decltype:
+  case tok::kw_decltype:
+    DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
+    return DS.Finish(Diags, PP);
=20
-    // FIXME: C++0x decltype support.
   // GNU typeof support.
   case tok::kw_typeof:
     ParseTypeofSpecifier(DS);
@@ -1393,22 +1555,7 @@
 ///     type-specifier type-specifier-seq[opt]
 ///
 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
-  DS.SetRangeStart(Tok.getLocation());
-  const char *PrevSpec =3D 0;
-  unsigned DiagID;
-  bool isInvalid =3D 0;
-
-  // Parse one or more of the type specifiers.
-  if (!ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
-      ParsedTemplateInfo(), /*SuppressDeclarations*/true)) {
-    Diag(Tok, diag::err_expected_type);
-    return true;
-  }
-
-  while (ParseOptionalTypeSpecifier(DS, isInvalid, PrevSpec, DiagID,
-         ParsedTemplateInfo(), /*SuppressDeclarations*/true))
-  {}
-
+  ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
   DS.Finish(Diags, PP);
   return false;
 }
@@ -1446,13 +1593,13 @@
 ///
 /// \returns true if a parse error occurred, false otherwise.
 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
+                                          SourceLocation TemplateKWLoc,
                                           IdentifierInfo *Name,
                                           SourceLocation NameLoc,
                                           bool EnteringContext,
                                           ParsedType ObjectType,
                                           UnqualifiedId &Id,
-                                          bool AssumeTemplateId,
-                                          SourceLocation TemplateKWLoc) {
+                                          bool AssumeTemplateId) {
   assert((AssumeTemplateId || Tok.is(tok::less)) &&
          "Expected '<' to finish parsing a template-id");
  =20
@@ -1463,7 +1610,7 @@
   case UnqualifiedId::IK_OperatorFunctionId:
   case UnqualifiedId::IK_LiteralOperatorId:
     if (AssumeTemplateId) {
-      TNK =3D Actions.ActOnDependentTemplateName(getCurScope(), TemplateKW=
Loc, SS,=20
+      TNK =3D Actions.ActOnDependentTemplateName(getCurScope(), SS, Templa=
teKWLoc,
                                                Id, ObjectType, EnteringCon=
text,
                                                Template);
       if (TNK =3D=3D TNK_Non_template)
@@ -1494,9 +1641,10 @@
         Diag(Id.StartLocation, diag::err_missing_dependent_template_keywor=
d)
           << Name
           << FixItHint::CreateInsertion(Id.StartLocation, "template ");
-        TNK =3D Actions.ActOnDependentTemplateName(getCurScope(), Template=
KWLoc,
-                                                 SS, Id, ObjectType,
-                                                 EnteringContext, Template=
);
+        TNK =3D Actions.ActOnDependentTemplateName(getCurScope(),
+                                                 SS, TemplateKWLoc, Id,
+                                                 ObjectType, EnteringConte=
xt,
+                                                 Template);
         if (TNK =3D=3D TNK_Non_template)
           return true;             =20
       }
@@ -1519,9 +1667,10 @@
     bool MemberOfUnknownSpecialization;
     TemplateName.setIdentifier(Name, NameLoc);
     if (ObjectType) {
-      TNK =3D Actions.ActOnDependentTemplateName(getCurScope(), TemplateKW=
Loc, SS,=20
-                                               TemplateName, ObjectType,
-                                               EnteringContext, Template);
+      TNK =3D Actions.ActOnDependentTemplateName(getCurScope(),
+                                               SS, TemplateKWLoc, Template=
Name,
+                                               ObjectType, EnteringContext,
+                                               Template);
       if (TNK =3D=3D TNK_Non_template)
         return true;
     } else {
@@ -1575,6 +1724,7 @@
     }
=20
     TemplateId->SS =3D SS;
+    TemplateId->TemplateKWLoc =3D TemplateKWLoc;
     TemplateId->Template =3D Template;
     TemplateId->Kind =3D TNK;
     TemplateId->LAngleLoc =3D LAngleLoc;
@@ -1591,12 +1741,13 @@
   // Bundle the template arguments together.
   ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
                                      TemplateArgs.size());
- =20
+
   // Constructor and destructor names.
   TypeResult Type
-    =3D Actions.ActOnTemplateIdType(SS, Template, NameLoc,
-                                  LAngleLoc, TemplateArgsPtr,
-                                  RAngleLoc);
+    =3D Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
+                                  Template, NameLoc,
+                                  LAngleLoc, TemplateArgsPtr, RAngleLoc,
+                                  /*IsCtorOrDtorName=3D*/true);
   if (Type.isInvalid())
     return true;
  =20
@@ -1666,7 +1817,9 @@
       bool isNew =3D Tok.getKind() =3D=3D tok::kw_new;
       // Consume the 'new' or 'delete'.
       SymbolLocations[SymbolIdx++] =3D ConsumeToken();
-      if (Tok.is(tok::l_square)) {
+      // Check for array new/delete.
+      if (Tok.is(tok::l_square) &&
+          (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))=
) {
         // Consume the '[' and ']'.
         BalancedDelimiterTracker T(*this, tok::l_square);
         T.consumeOpen();
@@ -1742,18 +1895,68 @@
   //   literal-operator-id: [C++0x 13.5.8]
   //     operator "" identifier
=20
-  if (getLang().CPlusPlus0x && Tok.is(tok::string_literal)) {
-    if (Tok.getLength() !=3D 2)
-      Diag(Tok.getLocation(), diag::err_operator_string_not_empty);
-    ConsumeStringToken();
+  if (getLangOpts().CPlusPlus0x && isTokenStringLiteral()) {
+    Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
=20
-    if (Tok.isNot(tok::identifier)) {
+    SourceLocation DiagLoc;
+    unsigned DiagId =3D 0;
+
+    // We're past translation phase 6, so perform string literal concatena=
tion
+    // before checking for "".
+    llvm::SmallVector<Token, 4> Toks;
+    llvm::SmallVector<SourceLocation, 4> TokLocs;
+    while (isTokenStringLiteral()) {
+      if (!Tok.is(tok::string_literal) && !DiagId) {
+        DiagLoc =3D Tok.getLocation();
+        DiagId =3D diag::err_literal_operator_string_prefix;
+      }
+      Toks.push_back(Tok);
+      TokLocs.push_back(ConsumeStringToken());
+    }
+
+    StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
+    if (Literal.hadError)
+      return true;
+
+    // Grab the literal operator's suffix, which will be either the next t=
oken
+    // or a ud-suffix from the string literal.
+    IdentifierInfo *II =3D 0;
+    SourceLocation SuffixLoc;
+    if (!Literal.getUDSuffix().empty()) {
+      II =3D &PP.getIdentifierTable().get(Literal.getUDSuffix());
+      SuffixLoc =3D
+        Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
+                                       Literal.getUDSuffixOffset(),
+                                       PP.getSourceManager(), getLangOpts(=
));
+      // This form is not permitted by the standard (yet).
+      DiagLoc =3D SuffixLoc;
+      DiagId =3D diag::err_literal_operator_missing_space;
+    } else if (Tok.is(tok::identifier)) {
+      II =3D Tok.getIdentifierInfo();
+      SuffixLoc =3D ConsumeToken();
+      TokLocs.push_back(SuffixLoc);
+    } else {
       Diag(Tok.getLocation(), diag::err_expected_ident);
       return true;
     }
=20
-    IdentifierInfo *II =3D Tok.getIdentifierInfo();
-    Result.setLiteralOperatorId(II, KeywordLoc, ConsumeToken());
+    // The string literal must be empty.
+    if (!Literal.GetString().empty() || Literal.Pascal) {
+      DiagLoc =3D TokLocs.front();
+      DiagId =3D diag::err_literal_operator_string_not_empty;
+    }
+
+    if (DiagId) {
+      // This isn't a valid literal-operator-id, but we think we know
+      // what the user meant. Tell them what they should have written.
+      llvm::SmallString<32> Str;
+      Str +=3D "\"\" ";
+      Str +=3D II->getName();
+      Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
+          SourceRange(TokLocs.front(), TokLocs.back()), Str);
+    }
+
+    Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
     return false;
   }
  =20
@@ -1823,13 +2026,13 @@
                                 bool AllowDestructorName,
                                 bool AllowConstructorName,
                                 ParsedType ObjectType,
+                                SourceLocation& TemplateKWLoc,
                                 UnqualifiedId &Result) {
=20
   // Handle 'A::template B'. This is for template-ids which have not
   // already been annotated by ParseOptionalCXXScopeSpecifier().
   bool TemplateSpecified =3D false;
-  SourceLocation TemplateKWLoc;
-  if (getLang().CPlusPlus && Tok.is(tok::kw_template) &&
+  if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
       (ObjectType || SS.isSet())) {
     TemplateSpecified =3D true;
     TemplateKWLoc =3D ConsumeToken();
@@ -1843,7 +2046,7 @@
     IdentifierInfo *Id =3D Tok.getIdentifierInfo();
     SourceLocation IdLoc =3D ConsumeToken();
=20
-    if (!getLang().CPlusPlus) {
+    if (!getLangOpts().CPlusPlus) {
       // If we're not in C++, only identifiers matter. Record the
       // identifier and return.
       Result.setIdentifier(Id, IdLoc);
@@ -1853,11 +2056,12 @@
     if (AllowConstructorName &&=20
         Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
       // We have parsed a constructor name.
-      Result.setConstructorName(Actions.getTypeName(*Id, IdLoc, getCurScop=
e(),
-                                                    &SS, false, false,
-                                                    ParsedType(),
-                                            /*NonTrivialTypeSourceInfo=3D*=
/true),
-                                IdLoc, IdLoc);
+      ParsedType Ty =3D Actions.getTypeName(*Id, IdLoc, getCurScope(),
+                                          &SS, false, false,
+                                          ParsedType(),
+                                          /*IsCtorOrDtorName=3D*/true,
+                                          /*NonTrivialTypeSourceInfo=3D*/t=
rue);
+      Result.setConstructorName(Ty, IdLoc, IdLoc);
     } else {
       // We have parsed an identifier.
       Result.setIdentifier(Id, IdLoc);     =20
@@ -1865,9 +2069,9 @@
=20
     // If the next token is a '<', we may have a template.
     if (TemplateSpecified || Tok.is(tok::less))
-      return ParseUnqualifiedIdTemplateId(SS, Id, IdLoc, EnteringContext,=20
-                                          ObjectType, Result,
-                                          TemplateSpecified, TemplateKWLoc=
);
+      return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
+                                          EnteringContext, ObjectType,
+                                          Result, TemplateSpecified);
    =20
     return false;
   }
@@ -1890,13 +2094,14 @@
           << TemplateId->Name
           << FixItHint::CreateRemoval(
                     SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleL=
oc));
-        Result.setConstructorName(Actions.getTypeName(*TemplateId->Name,
-                                                  TemplateId->TemplateName=
Loc,=20
-                                                      getCurScope(),
-                                                      &SS, false, false,
-                                                      ParsedType(),
-                                            /*NontrivialTypeSourceInfo=3D*=
/true),
-                                  TemplateId->TemplateNameLoc,=20
+        ParsedType Ty =3D Actions.getTypeName(*TemplateId->Name,
+                                            TemplateId->TemplateNameLoc,
+                                            getCurScope(),
+                                            &SS, false, false,
+                                            ParsedType(),
+                                            /*IsCtorOrDtorName=3D*/true,
+                                            /*NontrivialTypeSourceInfo=3D*=
/true);
+        Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
                                   TemplateId->RAngleLoc);
         ConsumeToken();
         return false;
@@ -1910,6 +2115,7 @@
     // We have already parsed a template-id; consume the annotation token =
as
     // our unqualified-id.
     Result.setTemplateId(TemplateId);
+    TemplateKWLoc =3D TemplateId->TemplateKWLoc;
     ConsumeToken();
     return false;
   }
@@ -1929,15 +2135,15 @@
     if ((Result.getKind() =3D=3D UnqualifiedId::IK_OperatorFunctionId ||
          Result.getKind() =3D=3D UnqualifiedId::IK_LiteralOperatorId) &&
         (TemplateSpecified || Tok.is(tok::less)))
-      return ParseUnqualifiedIdTemplateId(SS, 0, SourceLocation(),=20
-                                          EnteringContext, ObjectType,=20
-                                          Result,
-                                          TemplateSpecified, TemplateKWLoc=
);
+      return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
+                                          0, SourceLocation(),
+                                          EnteringContext, ObjectType,
+                                          Result, TemplateSpecified);
    =20
     return false;
   }
  =20
-  if (getLang().CPlusPlus &&=20
+  if (getLangOpts().CPlusPlus &&=20
       (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
     // C++ [expr.unary.op]p10:
     //   There is an ambiguity in the unary-expression ~X(), where X is a=20
@@ -1946,6 +2152,16 @@
    =20
     // Parse the '~'.
     SourceLocation TildeLoc =3D ConsumeToken();
+
+    if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
+      DeclSpec DS(AttrFactory);
+      SourceLocation EndLoc =3D ParseDecltypeSpecifier(DS);
+      if (ParsedType Type =3D Actions.getDestructorType(DS, ObjectType)) {
+        Result.setDestructorName(TildeLoc, Type, EndLoc);
+        return false;
+      }
+      return true;
+    }
    =20
     // Parse the class-name.
     if (Tok.isNot(tok::identifier)) {
@@ -1959,9 +2175,10 @@
    =20
     if (TemplateSpecified || Tok.is(tok::less)) {
       Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
-      return ParseUnqualifiedIdTemplateId(SS, ClassName, ClassNameLoc,
-                                          EnteringContext, ObjectType, Res=
ult,
-                                          TemplateSpecified, TemplateKWLoc=
);
+      return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
+                                          ClassName, ClassNameLoc,
+                                          EnteringContext, ObjectType,
+                                          Result, TemplateSpecified);
     }
    =20
     // Note that this is a destructor name.
@@ -1977,7 +2194,7 @@
   }
  =20
   Diag(Tok, diag::err_expected_unqualified_id)
-    << getLang().CPlusPlus;
+    << getLangOpts().CPlusPlus;
   return true;
 }
=20
@@ -2083,10 +2300,11 @@
     return ExprError();
   }
=20
-  ExprVector ConstructorArgs(Actions);
-  SourceLocation ConstructorLParen, ConstructorRParen;
+  ExprResult Initializer;
=20
   if (Tok.is(tok::l_paren)) {
+    SourceLocation ConstructorLParen, ConstructorRParen;
+    ExprVector ConstructorArgs(Actions);
     BalancedDelimiterTracker T(*this, tok::l_paren);
     T.consumeOpen();
     ConstructorLParen =3D T.getOpenLocation();
@@ -2103,15 +2321,20 @@
       SkipUntil(tok::semi, /*StopAtSemi=3D*/true, /*DontConsume=3D*/true);
       return ExprError();
     }
-  } else if (Tok.is(tok::l_brace)) {
-    // FIXME: Have to communicate the init-list to ActOnCXXNew.
-    ParseBraceInitializer();
+    Initializer =3D Actions.ActOnParenListExpr(ConstructorLParen,
+                                             ConstructorRParen,
+                                             move_arg(ConstructorArgs));
+  } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus0x) {
+    Diag(Tok.getLocation(),
+         diag::warn_cxx98_compat_generalized_initializer_lists);
+    Initializer =3D ParseBraceInitializer();
   }
+  if (Initializer.isInvalid())
+    return Initializer;
=20
   return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
                              move_arg(PlacementArgs), PlacementRParen,
-                             TypeIdParens, DeclaratorInfo, ConstructorLPar=
en,
-                             move_arg(ConstructorArgs), ConstructorRParen);
+                             TypeIdParens, DeclaratorInfo, Initializer.tak=
e());
 }
=20
 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to=
 be
@@ -2125,6 +2348,10 @@
   // Parse the array dimensions.
   bool first =3D true;
   while (Tok.is(tok::l_square)) {
+    // An array-size expression can't start with a lambda.
+    if (CheckProhibitedCXX11Attribute())
+      continue;
+
     BalancedDelimiterTracker T(*this, tok::l_square);
     T.consumeOpen();
=20
@@ -2139,13 +2366,16 @@
=20
     T.consumeClose();
=20
-    ParsedAttributes attrs(AttrFactory);
+    // Attributes here appertain to the array type. C++11 [expr.new]p5.
+    ParsedAttributes Attrs(AttrFactory);
+    MaybeParseCXX0XAttributes(Attrs);
+
     D.AddTypeInfo(DeclaratorChunk::getArray(0,
                                             /*static=3D*/false, /*star=3D*=
/false,
                                             Size.release(),
                                             T.getOpenLocation(),
                                             T.getCloseLocation()),
-                  attrs, T.getCloseLocation());
+                  Attrs, T.getCloseLocation());
=20
     if (T.getCloseLocation().isInvalid())
       return;
@@ -2197,7 +2427,11 @@
=20
   // Array delete?
   bool ArrayDelete =3D false;
-  if (Tok.is(tok::l_square)) {
+  if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
+    // FIXME: This could be the start of a lambda-expression. We should
+    // disambiguate this, but that will require arbitrary lookahead if
+    // the next token is '(':
+    //   delete [](int*){ /* ... */
     ArrayDelete =3D true;
     BalancedDelimiterTracker T(*this, tok::l_square);
=20
@@ -2235,6 +2469,7 @@
   case tok::kw___is_const:                   return UTT_IsConst;
   case tok::kw___is_empty:                return UTT_IsEmpty;
   case tok::kw___is_enum:                 return UTT_IsEnum;
+  case tok::kw___is_final:                 return UTT_IsFinal;
   case tok::kw___is_floating_point:          return UTT_IsFloatingPoint;
   case tok::kw___is_function:                return UTT_IsFunction;
   case tok::kw___is_fundamental:             return UTT_IsFundamental;
@@ -2271,6 +2506,15 @@
   case tok::kw___is_same:                    return BTT_IsSame;
   case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
   case tok::kw___is_convertible_to:          return BTT_IsConvertibleTo;
+  case tok::kw___is_trivially_assignable:    return BTT_IsTriviallyAssigna=
ble;
+  }
+}
+
+static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
+  switch (kind) {
+  default: llvm_unreachable("Not a known type trait");
+  case tok::kw___is_trivially_constructible:=20
+    return TT_IsTriviallyConstructible;
   }
 }
=20
@@ -2356,6 +2600,58 @@
                                       T.getCloseLocation());
 }
=20
+/// \brief Parse the built-in type-trait pseudo-functions that allow=20
+/// implementation of the TR1/C++11 type traits templates.
+///
+///       primary-expression:
+///          type-trait '(' type-id-seq ')'
+///
+///       type-id-seq:
+///          type-id ...[opt] type-id-seq[opt]
+///
+ExprResult Parser::ParseTypeTrait() {
+  TypeTrait Kind =3D TypeTraitFromTokKind(Tok.getKind());
+  SourceLocation Loc =3D ConsumeToken();
+ =20
+  BalancedDelimiterTracker Parens(*this, tok::l_paren);
+  if (Parens.expectAndConsume(diag::err_expected_lparen))
+    return ExprError();
+
+  llvm::SmallVector<ParsedType, 2> Args;
+  do {
+    // Parse the next type.
+    TypeResult Ty =3D ParseTypeName();
+    if (Ty.isInvalid()) {
+      Parens.skipToEnd();
+      return ExprError();
+    }
+
+    // Parse the ellipsis, if present.
+    if (Tok.is(tok::ellipsis)) {
+      Ty =3D Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
+      if (Ty.isInvalid()) {
+        Parens.skipToEnd();
+        return ExprError();
+      }
+    }
+   =20
+    // Add this type to the list of arguments.
+    Args.push_back(Ty.get());
+   =20
+    if (Tok.is(tok::comma)) {
+      ConsumeToken();
+      continue;
+    }
+   =20
+    break;
+  } while (true);
+ =20
+  if (Parens.consumeClose())
+    return ExprError();
+ =20
+  return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation()=
);
+}
+
 /// ParseArrayTypeTrait - Parse the built-in array type-trait
 /// pseudo-functions.
 ///
@@ -2396,10 +2692,8 @@
     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
                                        T.getCloseLocation());
   }
-  default:
-    break;
   }
-  return ExprError();
+  llvm_unreachable("Invalid ArrayTypeTrait!");
 }
=20
 /// ParseExpressionTrait - Parse built-in expression-trait
@@ -2432,7 +2726,7 @@
 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
                                          ParsedType &CastTy,
                                          BalancedDelimiterTracker &Tracker=
) {
-  assert(getLang().CPlusPlus && "Should only be called for C++!");
+  assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
   assert(ExprType =3D=3D CastExpr && "Compound literals are not ambiguous!=
");
   assert(isTypeIdInParens() && "Not a type-id!");
=20
@@ -2484,7 +2778,7 @@
                                    false/*isAddressofOperand*/,
                                    NotCastExpr,
                                    // type-id has priority.
-                                   true/*isTypeCast*/);
+                                   IsTypeCast);
     }
=20
     // If we parsed a cast-expression, it's really a type-id, otherwise it=
's
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseInit.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseInit.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseInit.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -21,18 +21,92 @@
 using namespace clang;
=20
=20
-/// MayBeDesignationStart - Return true if this token might be the start o=
f a
-/// designator.  If we can tell it is impossible that it is a designator, =
return
-/// false.
-static bool MayBeDesignationStart(tok::TokenKind K, Preprocessor &PP) {
-  switch (K) {
-  default: return false;
+/// MayBeDesignationStart - Return true if the current token might be the =
start=20
+/// of a designator.  If we can tell it is impossible that it is a designa=
tor,=20
+/// return false.
+bool Parser::MayBeDesignationStart() {
+  switch (Tok.getKind()) {
+  default:=20
+    return false;
+     =20
   case tok::period:      // designator: '.' identifier
-  case tok::l_square:    // designator: array-designator
+    return true;
+     =20
+  case tok::l_square: {  // designator: array-designator
+    if (!PP.getLangOpts().CPlusPlus0x)
       return true;
+   =20
+    // C++11 lambda expressions and C99 designators can be ambiguous all t=
he
+    // way through the closing ']' and to the next character. Handle the e=
asy
+    // cases here, and fall back to tentative parsing if those fail.
+    switch (PP.LookAhead(0).getKind()) {
+    case tok::equal:
+    case tok::r_square:
+      // Definitely starts a lambda expression.
+      return false;
+     =20
+    case tok::amp:
+    case tok::kw_this:
+    case tok::identifier:
+      // We have to do additional analysis, because these could be the
+      // start of a constant expression or a lambda capture list.
+      break;
+       =20
+    default:
+      // Anything not mentioned above cannot occur following a '[' in a=20
+      // lambda expression.
+      return true;       =20
+    }
+   =20
+    // Handle the complicated case below.
+    break;   =20
+  }
   case tok::identifier:  // designation: identifier ':'
     return PP.LookAhead(0).is(tok::colon);
   }
+ =20
+  // Parse up to (at most) the token after the closing ']' to determine=20
+  // whether this is a C99 designator or a lambda.=13
+  TentativeParsingAction Tentative(*this);
+  ConsumeBracket();
+  while (true) {
+    switch (Tok.getKind()) {
+    case tok::equal:
+    case tok::amp:
+    case tok::identifier:
+    case tok::kw_this:
+      // These tokens can occur in a capture list or a constant-expression.
+      // Keep looking.
+      ConsumeToken();
+      continue;
+     =20
+    case tok::comma:
+      // Since a comma cannot occur in a constant-expression, this must
+      // be a lambda.
+      Tentative.Revert();
+      return false;
+     =20
+    case tok::r_square: {
+      // Once we hit the closing square bracket, we look at the next
+      // token. If it's an '=3D', this is a designator. Otherwise, it's a
+      // lambda expression. This decision favors lambdas over the older
+      // GNU designator syntax, which allows one to omit the '=3D', but is
+      // consistent with GCC.
+      ConsumeBracket();
+      tok::TokenKind Kind =3D Tok.getKind();
+      Tentative.Revert();
+      return Kind =3D=3D tok::equal;
+    }
+     =20
+    default:
+      // Anything else cannot occur in a lambda capture list, so it
+      // must be a designator.
+      Tentative.Revert();
+      return true;
+    }
+  }
+ =20
+  return true;
 }
=20
 static void CheckArrayDesignatorSyntax(Parser &P, SourceLocation Loc,
@@ -81,7 +155,7 @@
   if (Tok.is(tok::identifier)) {
     const IdentifierInfo *FieldName =3D Tok.getIdentifierInfo();
=20
-    llvm::SmallString<256> NewSyntax;
+    SmallString<256> NewSyntax;
     llvm::raw_svector_ostream(NewSyntax) << '.' << FieldName->getName()
                                          << " =3D ";
=20
@@ -137,6 +211,11 @@
     //   [foo ... bar]     -> array designator
     //   [4][foo bar]      -> obsolete GNU designation with objc message s=
end.
     //
+    // We do not need to check for an expression starting with [[ here. If=
 it
+    // contains an Objective-C message send, then it is not an ill-formed
+    // attribute. If it is a lambda-expression within an array-designator,=
 then
+    // it will be rejected because a constant-expression cannot begin with=
 a
+    // lambda-expression.
     InMessageExpressionRAIIObject InMessage(*this, true);
    =20
     BalancedDelimiterTracker T(*this, tok::l_square);
@@ -149,7 +228,7 @@
     // send) or send to 'super', parse this as a message send
     // expression.  We handle C++ and C separately, since C++ requires
     // much more complicated parsing.
-    if  (getLang().ObjC1 && getLang().CPlusPlus) {
+    if  (getLangOpts().ObjC1 && getLangOpts().CPlusPlus) {
       // Send to 'super'.
       if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() =3D=3D Ident_=
super &&
           NextToken().isNot(tok::period) &&=20
@@ -184,7 +263,7 @@
       // adopt the expression for further analysis below.
       // FIXME: potentially-potentially evaluated expression above?
       Idx =3D ExprResult(static_cast<Expr*>(TypeOrExpr));
-    } else if (getLang().ObjC1 && Tok.is(tok::identifier)) {
+    } else if (getLangOpts().ObjC1 && Tok.is(tok::identifier)) {
       IdentifierInfo *II =3D Tok.getIdentifierInfo();
       SourceLocation IILoc =3D Tok.getLocation();
       ParsedType ReceiverType;
@@ -242,7 +321,7 @@
     // tokens are '...' or ']' or an objc message send.  If this is an objc
     // message send, handle it now.  An objc-message send is the start of
     // an assignment-expression production.
-    if (getLang().ObjC1 && Tok.isNot(tok::ellipsis) &&
+    if (getLangOpts().ObjC1 && Tok.isNot(tok::ellipsis) &&
         Tok.isNot(tok::r_square)) {
       CheckArrayDesignatorSyntax(*this, Tok.getLocation(), Desig);
       return ParseAssignmentExprWithObjCMessageExprStart(StartLoc,
@@ -330,7 +409,7 @@
=20
   if (Tok.is(tok::r_brace)) {
     // Empty initializers are a C++ feature and a GNU extension to C.
-    if (!getLang().CPlusPlus)
+    if (!getLangOpts().CPlusPlus)
       Diag(LBraceLoc, diag::ext_gnu_empty_initializer);
     // Match the '}'.
     return Actions.ActOnInitList(LBraceLoc, MultiExprArg(Actions),
@@ -340,12 +419,23 @@
   bool InitExprsOk =3D true;
=20
   while (1) {
+    // Handle Microsoft __if_exists/if_not_exists if necessary.
+    if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
+        Tok.is(tok::kw___if_not_exists))) {
+      if (ParseMicrosoftIfExistsBraceInitializer(InitExprs, InitExprsOk)) {
+        if (Tok.isNot(tok::comma)) break;
+        ConsumeToken();
+      }
+      if (Tok.is(tok::r_brace)) break;
+      continue;
+    }
+
     // Parse: designation[opt] initializer
=20
     // If we know that this cannot be a designation, just parse the nested
     // initializer directly.
     ExprResult SubElt;
-    if (MayBeDesignationStart(Tok.getKind(), PP))
+    if (MayBeDesignationStart())
       SubElt =3D ParseInitializerWithPotentialDesignator();
     else
       SubElt =3D ParseInitializer();
@@ -392,3 +482,66 @@
   return ExprError(); // an error occurred.
 }
=20
+
+// Return true if a comma (or closing brace) is necessary after the
+// __if_exists/if_not_exists statement.
+bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
+                                                    bool &InitExprsOk) {
+  bool trailingComma =3D false;
+  IfExistsCondition Result;
+  if (ParseMicrosoftIfExistsCondition(Result))
+    return false;
+ =20
+  BalancedDelimiterTracker Braces(*this, tok::l_brace);
+  if (Braces.consumeOpen()) {
+    Diag(Tok, diag::err_expected_lbrace);
+    return false;
+  }
+
+  switch (Result.Behavior) {
+  case IEB_Parse:
+    // Parse the declarations below.
+    break;
+       =20
+  case IEB_Dependent:
+    Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
+      << Result.IsIfExists;
+    // Fall through to skip.
+     =20
+  case IEB_Skip:
+    Braces.skipToEnd();
+    return false;
+  }
+
+  while (Tok.isNot(tok::eof)) {
+    trailingComma =3D false;
+    // If we know that this cannot be a designation, just parse the nested
+    // initializer directly.
+    ExprResult SubElt;
+    if (MayBeDesignationStart())
+      SubElt =3D ParseInitializerWithPotentialDesignator();
+    else
+      SubElt =3D ParseInitializer();
+
+    if (Tok.is(tok::ellipsis))
+      SubElt =3D Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken());
+   =20
+    // If we couldn't parse the subelement, bail out.
+    if (!SubElt.isInvalid())
+      InitExprs.push_back(SubElt.release());
+    else
+      InitExprsOk =3D false;
+
+    if (Tok.is(tok::comma)) {
+      ConsumeToken();
+      trailingComma =3D true;
+    }
+
+    if (Tok.is(tok::r_brace))
+      break;
+  }
+
+  Braces.consumeClose();
+
+  return !trailingComma;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseObjc.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseObjc.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseObjc.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -42,7 +42,6 @@
   switch (Tok.getObjCKeywordID()) {
   case tok::objc_class:
     return ParseObjCAtClassDeclaration(AtLoc);
-    break;
   case tok::objc_interface: {
     ParsedAttributes attrs(AttrFactory);
     SingleDecl =3D ParseObjCAtInterfaceDeclaration(AtLoc, attrs);
@@ -50,15 +49,12 @@
   }
   case tok::objc_protocol: {
     ParsedAttributes attrs(AttrFactory);
-    SingleDecl =3D ParseObjCAtProtocolDeclaration(AtLoc, attrs);
-    break;
+    return ParseObjCAtProtocolDeclaration(AtLoc, attrs);
   }
   case tok::objc_implementation:
-    SingleDecl =3D ParseObjCAtImplementationDeclaration(AtLoc);
-    break;
+    return ParseObjCAtImplementationDeclaration(AtLoc);
   case tok::objc_end:
     return ParseObjCAtEndDeclaration(AtLoc);
-    break;
   case tok::objc_compatibility_alias:
     SingleDecl =3D ParseObjCAtAliasDeclaration(AtLoc);
     break;
@@ -68,6 +64,12 @@
   case tok::objc_dynamic:
     SingleDecl =3D ParseObjCPropertyDynamic(AtLoc);
     break;
+  case tok::objc___experimental_modules_import:
+    if (getLangOpts().Modules)
+      return ParseModuleImport(AtLoc);
+     =20
+    // Fall through
+     =20
   default:
     Diag(AtLoc, diag::err_unexpected_at);
     SkipUntil(tok::semi);
@@ -113,6 +115,25 @@
                                               ClassNames.size());
 }
=20
+void Parser::CheckNestedObjCContexts(SourceLocation AtLoc)
+{
+  Sema::ObjCContainerKind ock =3D Actions.getObjCContainerKind();
+  if (ock =3D=3D Sema::OCK_None)
+    return;
+
+  Decl *Decl =3D Actions.getObjCDeclContext();
+  if (CurParsedObjCImpl) {
+    CurParsedObjCImpl->finish(AtLoc);
+  } else {
+    Actions.ActOnAtEnd(getCurScope(), AtLoc);
+  }
+  Diag(AtLoc, diag::err_objc_missing_end)
+      << FixItHint::CreateInsertion(AtLoc, "@end\n");
+  if (Decl)
+    Diag(Decl->getLocStart(), diag::note_objc_container_start)
+        << (int) ock;
+}
+
 ///
 ///   objc-interface:
 ///     objc-class-interface-attributes[opt] objc-class-interface
@@ -140,11 +161,13 @@
 ///     __attribute__((deprecated))
 ///     __attribute__((unavailable))
 ///     __attribute__((objc_exception)) - used by NSException on 64-bit
+///     __attribute__((objc_root_class))
 ///
-Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,
+Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
                                               ParsedAttributes &attrs) {
   assert(Tok.isObjCAtKeyword(tok::objc_interface) &&
          "ParseObjCAtInterfaceDeclaration(): Expected @interface");
+  CheckNestedObjCContexts(AtLoc);
   ConsumeToken(); // the "interface" identifier
=20
   // Code completion after '@interface'.
@@ -181,7 +204,7 @@
       categoryId =3D Tok.getIdentifierInfo();
       categoryLoc =3D ConsumeToken();
     }
-    else if (!getLang().ObjC2) {
+    else if (!getLangOpts().ObjC2) {
       Diag(Tok, diag::err_expected_ident); // missing category name.
       return 0;
     }
@@ -205,7 +228,7 @@
       return 0;
=20
     Decl *CategoryType =3D
-    Actions.ActOnStartCategoryInterface(atLoc,
+    Actions.ActOnStartCategoryInterface(AtLoc,
                                         nameId, nameLoc,
                                         categoryId, categoryLoc,
                                         ProtocolRefs.data(),
@@ -214,7 +237,7 @@
                                         EndProtoLoc);
    =20
     if (Tok.is(tok::l_brace))
-      ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, atL=
oc);
+      ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtL=
oc);
      =20
     ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType);
     return CategoryType;
@@ -250,14 +273,14 @@
     return 0;
=20
   Decl *ClsType =3D
-    Actions.ActOnStartClassInterface(atLoc, nameId, nameLoc,
+    Actions.ActOnStartClassInterface(AtLoc, nameId, nameLoc,
                                      superClassId, superClassLoc,
                                      ProtocolRefs.data(), ProtocolRefs.siz=
e(),
                                      ProtocolLocs.data(),
                                      EndProtoLoc, attrs.getList());
=20
   if (Tok.is(tok::l_brace))
-    ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, atLoc);
+    ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc);
=20
   ParseObjCInterfaceDeclList(tok::objc_interface, ClsType);
   return ClsType;
@@ -266,17 +289,22 @@
 /// The Objective-C property callback.  This should be defined where
 /// it's used, but instead it's been lifted to here to support VS2005.
 struct Parser::ObjCPropertyCallback : FieldCallback {
+private:
+  virtual void anchor();
+public:
   Parser &P;
   SmallVectorImpl<Decl *> &Props;
   ObjCDeclSpec &OCDS;
   SourceLocation AtLoc;
+  SourceLocation LParenLoc;
   tok::ObjCKeywordKind MethodImplKind;
        =20
   ObjCPropertyCallback(Parser &P,=20
                        SmallVectorImpl<Decl *> &Props,
                        ObjCDeclSpec &OCDS, SourceLocation AtLoc,
+                       SourceLocation LParenLoc,
                        tok::ObjCKeywordKind MethodImplKind) :
-    P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc),
+    P(P), Props(Props), OCDS(OCDS), AtLoc(AtLoc), LParenLoc(LParenLoc),
     MethodImplKind(MethodImplKind) {
   }
=20
@@ -308,7 +336,8 @@
                                                      FD.D.getIdentifier());
     bool isOverridingProperty =3D false;
     Decl *Property =3D
-      P.Actions.ActOnProperty(P.getCurScope(), AtLoc, FD, OCDS,
+      P.Actions.ActOnProperty(P.getCurScope(), AtLoc, LParenLoc,
+                              FD, OCDS,
                               GetterSel, SetterSel,=20
                               &isOverridingProperty,
                               MethodImplKind);
@@ -319,6 +348,9 @@
   }
 };
=20
+void Parser::ObjCPropertyCallback::anchor() {
+}
+
 ///   objc-interface-decl-list:
 ///     empty
 ///     objc-interface-decl-list objc-property-decl [OBJC2]
@@ -348,8 +380,12 @@
       allMethods.push_back(methodPrototype);
       // Consume the ';' here, since ParseObjCMethodPrototype() is re-used=
 for
       // method definitions.
-      ExpectAndConsume(tok::semi, diag::err_expected_semi_after_method_pro=
to,
-                       "", tok::semi);
+      if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)=
) {
+        // We didn't find a semi and we error'ed out. Skip until a ';' or =
'@'.
+        SkipUntil(tok::at, /*StopAtSemi=3D*/true, /*DontConsume=3D*/true);
+        if (Tok.is(tok::semi))
+          ConsumeToken();
+      }
       continue;
     }
     if (Tok.is(tok::l_paren)) {
@@ -372,7 +408,7 @@
     // Code completion within an Objective-C interface.
     if (Tok.is(tok::code_completion)) {
       Actions.CodeCompleteOrdinaryName(getCurScope(),=20
-                                  ObjCImpDecl? Sema::PCC_ObjCImplementation
+                            CurParsedObjCImpl? Sema::PCC_ObjCImplementation
                                              : Sema::PCC_ObjCInterface);
       return cutOffParsing();
     }
@@ -394,7 +430,6 @@
     if (Tok.is(tok::code_completion)) {
       Actions.CodeCompleteObjCAtDirective(getCurScope());
       return cutOffParsing();
-      break;
     }
=20
     tok::ObjCKeywordKind DirectiveKind =3D Tok.getObjCKeywordID();
@@ -425,7 +460,10 @@
        =20
     case tok::objc_implementation:
     case tok::objc_interface:
-      Diag(Tok, diag::err_objc_missing_end);
+      Diag(AtLoc, diag::err_objc_missing_end)
+          << FixItHint::CreateInsertion(AtLoc, "@end\n");
+      Diag(CDecl->getLocStart(), diag::note_objc_container_start)
+          << (int) Actions.getObjCContainerKind();
       ConsumeToken();
       break;
        =20
@@ -440,16 +478,19 @@
       break;
=20
     case tok::objc_property:
-      if (!getLang().ObjC2)
+      if (!getLangOpts().ObjC2)
         Diag(AtLoc, diag::err_objc_properties_require_objc2);
=20
       ObjCDeclSpec OCDS;
+      SourceLocation LParenLoc;
       // Parse property attribute list, if any.
-      if (Tok.is(tok::l_paren))
+      if (Tok.is(tok::l_paren)) {
+        LParenLoc =3D Tok.getLocation();
         ParseObjCPropertyAttribute(OCDS);
+      }
=20
       ObjCPropertyCallback Callback(*this, allProperties,
-                                    OCDS, AtLoc, MethodImplKind);
+                                    OCDS, AtLoc, LParenLoc, MethodImplKind=
);
=20
       // Parse all the comma separated declarators.
       DeclSpec DS(AttrFactory);
@@ -465,10 +506,16 @@
   if (Tok.is(tok::code_completion)) {
     Actions.CodeCompleteObjCAtDirective(getCurScope());
     return cutOffParsing();
-  } else if (Tok.isObjCAtKeyword(tok::objc_end))
+  } else if (Tok.isObjCAtKeyword(tok::objc_end)) {
     ConsumeToken(); // the "end" identifier
-  else
-    Diag(Tok, diag::err_objc_missing_end);
+  } else {
+    Diag(Tok, diag::err_objc_missing_end)
+        << FixItHint::CreateInsertion(Tok.getLocation(), "\n at end\n");
+    Diag(CDecl->getLocStart(), diag::note_objc_container_start)
+        << (int) Actions.getObjCContainerKind();
+    AtEnd.setBegin(Tok.getLocation());
+    AtEnd.setEnd(Tok.getLocation());
+  }
=20
   // Insert collected methods declarations into the @interface object.
   // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit.
@@ -732,7 +779,7 @@
   // FIXME: May have to do additional look-ahead to only allow for
   // valid tokens following an 'in'; such as an identifier, unary operator=
s,
   // '[' etc.
-  return (getLang().ObjC2 && Tok.is(tok::identifier) &&
+  return (getLangOpts().ObjC2 && Tok.is(tok::identifier) &&
           Tok.getIdentifierInfo() =3D=3D ObjCTypeQuals[objc_in]);
 }
=20
@@ -935,7 +982,7 @@
=20
   // If attributes exist before the method, parse them.
   ParsedAttributes methodAttrs(AttrFactory);
-  if (getLang().ObjC2)
+  if (getLangOpts().ObjC2)
     MaybeParseGNUAttributes(methodAttrs);
=20
   if (Tok.is(tok::code_completion)) {
@@ -961,7 +1008,7 @@
   SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo;
   if (Tok.isNot(tok::colon)) {
     // If attributes exist after the method, parse them.
-    if (getLang().ObjC2)
+    if (getLangOpts().ObjC2)
       MaybeParseGNUAttributes(methodAttrs);
=20
     Selector Sel =3D PP.getSelectorTable().getNullarySelector(SelIdent);
@@ -1004,7 +1051,7 @@
     // If attributes exist before the argument name, parse them.
     // Regardless, collect all the attributes we've parsed so far.
     ArgInfo.ArgAttrs =3D 0;
-    if (getLang().ObjC2) {
+    if (getLangOpts().ObjC2) {
       MaybeParseGNUAttributes(paramAttrs);
       ArgInfo.ArgAttrs =3D paramAttrs.getList();
     }
@@ -1083,7 +1130,7 @@
=20
   // FIXME: Add support for optional parameter list...
   // If attributes exist after the method, parse them.
-  if (getLang().ObjC2)
+  if (getLangOpts().ObjC2)
     MaybeParseGNUAttributes(methodAttrs);
  =20
   if (KeyIdents.size() =3D=3D 0)
@@ -1146,7 +1193,7 @@
     return true;
   }
=20
-  EndLoc =3D ConsumeAnyToken();
+  EndLoc =3D ConsumeToken();
=20
   // Convert the list of protocols identifiers into a list of protocol dec=
ls.
   Actions.FindProtocolDeclaration(WarnOnDeclarations,
@@ -1159,7 +1206,7 @@
 /// in a decl-specifier-seq, starting at the '<'.
 bool Parser::ParseObjCProtocolQualifiers(DeclSpec &DS) {
   assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'");
-  assert(getLang().ObjC1 && "Protocol qualifiers only exist in Objective-C=
");
+  assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objecti=
ve-C");
   SourceLocation LAngleLoc, EndProtoLoc;
   SmallVector<Decl *, 8> ProtocolDecl;
   SmallVector<SourceLocation, 8> ProtocolLocs;
@@ -1312,8 +1359,9 @@
 ///   "@protocol identifier ;" should be resolved as "@protocol
 ///   identifier-list ;": objc-interface-decl-list may not start with a
 ///   semicolon in the first alternative if objc-protocol-refs are omitted.
-Decl *Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
-                                             ParsedAttributes &attrs) {
+Parser::DeclGroupPtrTy=20
+Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc,
+                                       ParsedAttributes &attrs) {
   assert(Tok.isObjCAtKeyword(tok::objc_protocol) &&
          "ParseObjCAtProtocolDeclaration(): Expected @protocol");
   ConsumeToken(); // the "protocol" identifier
@@ -1321,12 +1369,12 @@
   if (Tok.is(tok::code_completion)) {
     Actions.CodeCompleteObjCProtocolDecl(getCurScope());
     cutOffParsing();
-    return 0;
+    return DeclGroupPtrTy();
   }
=20
   if (Tok.isNot(tok::identifier)) {
     Diag(Tok, diag::err_expected_ident); // missing protocol name.
-    return 0;
+    return DeclGroupPtrTy();
   }
   // Save the protocol name, then consume it.
   IdentifierInfo *protocolName =3D Tok.getIdentifierInfo();
@@ -1339,6 +1387,8 @@
                                                    attrs.getList());
   }
=20
+  CheckNestedObjCContexts(AtLoc);
+
   if (Tok.is(tok::comma)) { // list of forward declarations.
     SmallVector<IdentifierLocPair, 8> ProtocolRefs;
     ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc));
@@ -1349,7 +1399,7 @@
       if (Tok.isNot(tok::identifier)) {
         Diag(Tok, diag::err_expected_ident);
         SkipUntil(tok::semi);
-        return 0;
+        return DeclGroupPtrTy();
       }
       ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(),
                                                Tok.getLocation()));
@@ -1360,7 +1410,7 @@
     }
     // Consume the ';'.
     if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after, "@proto=
col"))
-      return 0;
+      return DeclGroupPtrTy();
=20
     return Actions.ActOnForwardProtocolDeclaration(AtLoc,
                                                    &ProtocolRefs[0],
@@ -1376,7 +1426,7 @@
   if (Tok.is(tok::less) &&
       ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false,
                                   LAngleLoc, EndProtoLoc))
-    return 0;
+    return DeclGroupPtrTy();
=20
   Decl *ProtoType =3D
     Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc,
@@ -1386,7 +1436,7 @@
                                         EndProtoLoc, attrs.getList());
=20
   ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType);
-  return ProtoType;
+  return Actions.ConvertDeclToDeclGroup(ProtoType);
 }
=20
 ///   objc-implementation:
@@ -1399,26 +1449,28 @@
 ///
 ///   objc-category-implementation-prologue:
 ///     @implementation identifier ( identifier )
-Decl *Parser::ParseObjCAtImplementationDeclaration(
-  SourceLocation atLoc) {
+Parser::DeclGroupPtrTy
+Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) {
   assert(Tok.isObjCAtKeyword(tok::objc_implementation) &&
          "ParseObjCAtImplementationDeclaration(): Expected @implementation=
");
+  CheckNestedObjCContexts(AtLoc);
   ConsumeToken(); // the "implementation" identifier
=20
   // Code completion after '@implementation'.
   if (Tok.is(tok::code_completion)) {
     Actions.CodeCompleteObjCImplementationDecl(getCurScope());
     cutOffParsing();
-    return 0;
+    return DeclGroupPtrTy();
   }
=20
   if (Tok.isNot(tok::identifier)) {
     Diag(Tok, diag::err_expected_ident); // missing class or category name.
-    return 0;
+    return DeclGroupPtrTy();
   }
   // We have a class or category name - consume it.
   IdentifierInfo *nameId =3D Tok.getIdentifierInfo();
   SourceLocation nameLoc =3D ConsumeToken(); // consume class or category =
name
+  Decl *ObjCImpDecl =3D 0;
=20
   if (Tok.is(tok::l_paren)) {
     // we have a category implementation.
@@ -1429,7 +1481,7 @@
     if (Tok.is(tok::code_completion)) {
       Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId=
, nameLoc);
       cutOffParsing();
-      return 0;
+      return DeclGroupPtrTy();
     }
    =20
     if (Tok.is(tok::identifier)) {
@@ -1437,45 +1489,57 @@
       categoryLoc =3D ConsumeToken();
     } else {
       Diag(Tok, diag::err_expected_ident); // missing category name.
-      return 0;
+      return DeclGroupPtrTy();
     }
     if (Tok.isNot(tok::r_paren)) {
       Diag(Tok, diag::err_expected_rparen);
       SkipUntil(tok::r_paren, false); // don't stop at ';'
-      return 0;
+      return DeclGroupPtrTy();
     }
     rparenLoc =3D ConsumeParen();
-    Decl *ImplCatType =3D Actions.ActOnStartCategoryImplementation(
-                                    atLoc, nameId, nameLoc, categoryId,
+    ObjCImpDecl =3D Actions.ActOnStartCategoryImplementation(
+                                    AtLoc, nameId, nameLoc, categoryId,
                                     categoryLoc);
=20
-    ObjCImpDecl =3D ImplCatType;
-    PendingObjCImpDecl.push_back(ObjCImpDecl);
-    return 0;
+  } else {
+    // We have a class implementation
+    SourceLocation superClassLoc;
+    IdentifierInfo *superClassId =3D 0;
+    if (Tok.is(tok::colon)) {
+      // We have a super class
+      ConsumeToken();
+      if (Tok.isNot(tok::identifier)) {
+        Diag(Tok, diag::err_expected_ident); // missing super class name.
+        return DeclGroupPtrTy();
+      }
+      superClassId =3D Tok.getIdentifierInfo();
+      superClassLoc =3D ConsumeToken(); // Consume super class name
+    }
+    ObjCImpDecl =3D Actions.ActOnStartClassImplementation(
+                                    AtLoc, nameId, nameLoc,
+                                    superClassId, superClassLoc);
+ =20
+    if (Tok.is(tok::l_brace)) // we have ivars
+      ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLo=
c);
   }
-  // We have a class implementation
-  SourceLocation superClassLoc;
-  IdentifierInfo *superClassId =3D 0;
-  if (Tok.is(tok::colon)) {
-    // We have a super class
-    ConsumeToken();
-    if (Tok.isNot(tok::identifier)) {
-      Diag(Tok, diag::err_expected_ident); // missing super class name.
-      return 0;
+  assert(ObjCImpDecl);
+
+  SmallVector<Decl *, 8> DeclsInGroup;
+
+  {
+    ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl);
+    while (!ObjCImplParsing.isFinished() && Tok.isNot(tok::eof)) {
+      ParsedAttributesWithRange attrs(AttrFactory);
+      MaybeParseCXX0XAttributes(attrs);
+      MaybeParseMicrosoftAttributes(attrs);
+      if (DeclGroupPtrTy DGP =3D ParseExternalDeclaration(attrs)) {
+        DeclGroupRef DG =3D DGP.get();
+        DeclsInGroup.append(DG.begin(), DG.end());
+      }
     }
-    superClassId =3D Tok.getIdentifierInfo();
-    superClassLoc =3D ConsumeToken(); // Consume super class name
   }
-  Decl *ImplClsType =3D Actions.ActOnStartClassImplementation(
-                                  atLoc, nameId, nameLoc,
-                                  superClassId, superClassLoc);
=20
-  if (Tok.is(tok::l_brace)) // we have ivars
-    ParseObjCClassInstanceVariables(ImplClsType, tok::objc_private, atLoc);
-
-  ObjCImpDecl =3D ImplClsType;
-  PendingObjCImpDecl.push_back(ObjCImpDecl);
-  return 0;
+  return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup);
 }
=20
 Parser::DeclGroupPtrTy
@@ -1483,35 +1547,44 @@
   assert(Tok.isObjCAtKeyword(tok::objc_end) &&
          "ParseObjCAtEndDeclaration(): Expected @end");
   ConsumeToken(); // the "end" identifier
-  SmallVector<Decl *, 8> DeclsInGroup;
-  Actions.DefaultSynthesizeProperties(getCurScope(), ObjCImpDecl);
-  for (size_t i =3D 0; i < LateParsedObjCMethods.size(); ++i) {
-    Decl *D =3D ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i]);
-    DeclsInGroup.push_back(D);
-  }
-  DeclsInGroup.push_back(ObjCImpDecl);
- =20
-  if (ObjCImpDecl) {
-    Actions.ActOnAtEnd(getCurScope(), atEnd);
-    PendingObjCImpDecl.pop_back();
-  }
+  if (CurParsedObjCImpl)
+    CurParsedObjCImpl->finish(atEnd);
   else
     // missing @implementation
-    Diag(atEnd.getBegin(), diag::err_expected_implementation);
-   =20
-  LateParsedObjCMethods.clear();
-  ObjCImpDecl =3D 0;
-  return Actions.BuildDeclaratorGroup(
-           DeclsInGroup.data(), DeclsInGroup.size(), false);
+    Diag(atEnd.getBegin(), diag::err_expected_objc_container);
+  return DeclGroupPtrTy();
 }
=20
-Parser::DeclGroupPtrTy Parser::FinishPendingObjCActions() {
-  Actions.DiagnoseUseOfUnimplementedSelectors();
-  if (PendingObjCImpDecl.empty())
-    return Actions.ConvertDeclToDeclGroup(0);
-  Decl *ImpDecl =3D PendingObjCImpDecl.pop_back_val();
-  Actions.ActOnAtEnd(getCurScope(), SourceRange());
-  return Actions.ConvertDeclToDeclGroup(ImpDecl);
+Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() {
+  if (!Finished) {
+    finish(P.Tok.getLocation());
+    if (P.Tok.is(tok::eof)) {
+      P.Diag(P.Tok, diag::err_objc_missing_end)
+          << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n at end\n");
+      P.Diag(Dcl->getLocStart(), diag::note_objc_container_start)
+          << Sema::OCK_Implementation;
+    }
+  }
+  P.CurParsedObjCImpl =3D 0;
+  assert(LateParsedObjCMethods.empty());
+}
+
+void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) {
+  assert(!Finished);
+  P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl);
+  for (size_t i =3D 0; i < LateParsedObjCMethods.size(); ++i)
+    P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i]);
+
+  P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd);
+
+  /// \brief Clear and free the cached objc methods.
+  for (LateParsedObjCMethodContainer::iterator
+         I =3D LateParsedObjCMethods.begin(),
+         E =3D LateParsedObjCMethods.end(); I !=3D E; ++I)
+    delete *I;
+  LateParsedObjCMethods.clear();
+
+  Finished =3D true;
 }
=20
 ///   compatibility-alias-decl:
@@ -1850,7 +1923,7 @@
=20
   // parse optional ';'
   if (Tok.is(tok::semi)) {
-    if (ObjCImpDecl) {
+    if (CurParsedObjCImpl) {
       Diag(Tok, diag::warn_semicolon_before_method_body)
         << FixItHint::CreateRemoval(Tok.getLocation());
     }
@@ -1868,19 +1941,32 @@
     if (Tok.isNot(tok::l_brace))
       return 0;
   }
+
+  if (!MDecl) {
+    ConsumeBrace();
+    SkipUntil(tok::r_brace, /*StopAtSemi=3D*/false);
+    return 0;
+  }
+
   // Allow the rest of sema to find private method decl implementations.
-  if (MDecl)
-    Actions.AddAnyMethodToGlobalPool(MDecl);
-   =20
-  // Consume the tokens and store them for later parsing.
-  LexedMethod* LM =3D new LexedMethod(this, MDecl);
-  LateParsedObjCMethods.push_back(LM);
-  CachedTokens &Toks =3D LM->Toks;
-  // Begin by storing the '{' token.
-  Toks.push_back(Tok);
-  ConsumeBrace();
-  // Consume everything up to (and including) the matching right brace.
-  ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=3D*/false);
+  Actions.AddAnyMethodToGlobalPool(MDecl);
+
+  if (CurParsedObjCImpl) {
+    // Consume the tokens and store them for later parsing.
+    LexedMethod* LM =3D new LexedMethod(this, MDecl);
+    CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM);
+    CachedTokens &Toks =3D LM->Toks;
+    // Begin by storing the '{' token.
+    Toks.push_back(Tok);
+    ConsumeBrace();
+    // Consume everything up to (and including) the matching right brace.
+    ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=3D*/false);
+
+  } else {
+    ConsumeBrace();
+    SkipUntil(tok::r_brace, /*StopAtSemi=3D*/false);
+  }
+
   return MDecl;
 }
=20
@@ -1924,9 +2010,62 @@
     cutOffParsing();
     return ExprError();
=20
+  case tok::minus:
+  case tok::plus: {
+    tok::TokenKind Kind =3D Tok.getKind();
+    SourceLocation OpLoc =3D ConsumeToken();
+
+    if (!Tok.is(tok::numeric_constant)) {
+      const char *Symbol =3D 0;
+      switch (Kind) {
+      case tok::minus: Symbol =3D "-"; break;
+      case tok::plus: Symbol =3D "+"; break;
+      default: llvm_unreachable("missing unary operator case");
+      }
+      Diag(Tok, diag::err_nsnumber_nonliteral_unary)
+        << Symbol;
+      return ExprError();
+    }
+
+    ExprResult Lit(Actions.ActOnNumericConstant(Tok));
+    if (Lit.isInvalid()) {
+      return move(Lit);
+    }
+    ConsumeToken(); // Consume the literal token.
+
+    Lit =3D Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.take());
+    if (Lit.isInvalid())
+      return move(Lit);
+
+    return ParsePostfixExpressionSuffix(
+             Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
+  }
+
   case tok::string_literal:    // primary-expression: string-literal
   case tok::wide_string_literal:
     return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc));
+
+  case tok::char_constant:
+    return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc));
+     =20
+  case tok::numeric_constant:
+    return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc));
+
+  case tok::kw_true:  // Objective-C++, etc.
+  case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes
+    return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, tru=
e));
+  case tok::kw_false: // Objective-C++, etc.
+  case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no
+    return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, fal=
se));
+   =20
+  case tok::l_square:
+    // Objective-C array literal
+    return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc));
+         =20
+  case tok::l_brace:
+    // Objective-C dictionary literal
+    return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc));
+         =20
   default:
     if (Tok.getIdentifierInfo() =3D=3D 0)
       return ExprError(Diag(AtLoc, diag::err_unexpected_at));
@@ -2037,14 +2176,14 @@
 /// This routine will only return true for a subset of valid message-send
 /// expressions.
 bool Parser::isSimpleObjCMessageExpression() {
-  assert(Tok.is(tok::l_square) && getLang().ObjC1 &&
+  assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 &&
          "Incorrect start for isSimpleObjCMessageExpression");
   return GetLookAheadToken(1).is(tok::identifier) &&
          GetLookAheadToken(2).is(tok::identifier);
 }
=20
 bool Parser::isStartOfObjCClassMessageMissingOpenBracket() {
-  if (!getLang().ObjC1 || !NextToken().is(tok::identifier) ||=20
+  if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) ||=20
       InMessageExpression)
     return false;
  =20
@@ -2093,7 +2232,7 @@
  =20
   InMessageExpressionRAIIObject InMessage(*this, true);
  =20
-  if (getLang().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // We completely separate the C and C++ cases because C++ requires
     // more complicated (read: slower) parsing.=20
    =20
@@ -2404,6 +2543,134 @@
                                               AtStrings.size()));
 }
=20
+/// ParseObjCBooleanLiteral -
+/// objc-scalar-literal : '@' boolean-keyword
+///                        ;
+/// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no'
+///                        ;
+ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc,=20
+                                           bool ArgValue) {
+  SourceLocation EndLoc =3D ConsumeToken();             // consume the key=
word.
+  return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue);
+}
+
+/// ParseObjCCharacterLiteral -
+/// objc-scalar-literal : '@' character-literal
+///                        ;
+ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) {
+  ExprResult Lit(Actions.ActOnCharacterConstant(Tok));
+  if (Lit.isInvalid()) {
+    return move(Lit);
+  }
+  ConsumeToken(); // Consume the literal token.
+  return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
+}
+
+/// ParseObjCNumericLiteral -
+/// objc-scalar-literal : '@' scalar-literal
+///                        ;
+/// scalar-literal : | numeric-constant			/* any numeric constant. */
+///                    ;
+ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) {
+  ExprResult Lit(Actions.ActOnNumericConstant(Tok));
+  if (Lit.isInvalid()) {
+    return move(Lit);
+  }
+  ConsumeToken(); // Consume the literal token.
+  return Owned(Actions.BuildObjCNumericLiteral(AtLoc, Lit.take()));
+}
+
+ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) {
+  ExprVector ElementExprs(Actions);                   // array elements.
+  ConsumeBracket(); // consume the l_square.
+
+  while (Tok.isNot(tok::r_square)) {
+    // Parse list of array element expressions (all must be id types).
+    ExprResult Res(ParseAssignmentExpression());
+    if (Res.isInvalid()) {
+      // We must manually skip to a ']', otherwise the expression skipper =
will
+      // stop at the ']' when it skips to the ';'.  We want it to skip bey=
ond
+      // the enclosing expression.
+      SkipUntil(tok::r_square);
+      return move(Res);
+    }   =20
+   =20
+    // Parse the ellipsis that indicates a pack expansion.
+    if (Tok.is(tok::ellipsis))
+      Res =3D Actions.ActOnPackExpansion(Res.get(), ConsumeToken());   =20
+    if (Res.isInvalid())
+      return true;
+
+    ElementExprs.push_back(Res.release());
+
+    if (Tok.is(tok::comma))
+      ConsumeToken(); // Eat the ','.
+    else if (Tok.isNot(tok::r_square))
+     return ExprError(Diag(Tok, diag::err_expected_rsquare_or_comma));
+  }
+  SourceLocation EndLoc =3D ConsumeBracket(); // location of ']'
+  MultiExprArg Args(Actions, ElementExprs.take(), ElementExprs.size());
+  return Owned(Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), A=
rgs));
+}
+
+ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) {
+  SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements.
+  ConsumeBrace(); // consume the l_square.
+  while (Tok.isNot(tok::r_brace)) {
+    // Parse the comma separated key : value expressions.
+    ExprResult KeyExpr;
+    {
+      ColonProtectionRAIIObject X(*this);
+      KeyExpr =3D ParseAssignmentExpression();
+      if (KeyExpr.isInvalid()) {
+        // We must manually skip to a '}', otherwise the expression skippe=
r will
+        // stop at the '}' when it skips to the ';'.  We want it to skip b=
eyond
+        // the enclosing expression.
+        SkipUntil(tok::r_brace);
+        return move(KeyExpr);
+      }
+    }
+
+    if (Tok.is(tok::colon)) {
+      ConsumeToken();
+    } else {
+      return ExprError(Diag(Tok, diag::err_expected_colon));
+    }
+   =20
+    ExprResult ValueExpr(ParseAssignmentExpression());
+    if (ValueExpr.isInvalid()) {
+      // We must manually skip to a '}', otherwise the expression skipper =
will
+      // stop at the '}' when it skips to the ';'.  We want it to skip bey=
ond
+      // the enclosing expression.
+      SkipUntil(tok::r_brace);
+      return move(ValueExpr);
+    }
+   =20
+    // Parse the ellipsis that designates this as a pack expansion.
+    SourceLocation EllipsisLoc;
+    if (Tok.is(tok::ellipsis) && getLangOpts().CPlusPlus)
+      EllipsisLoc =3D ConsumeToken();
+   =20
+    // We have a valid expression. Collect it in a vector so we can
+    // build the argument list.
+    ObjCDictionaryElement Element =3D {=20
+      KeyExpr.get(), ValueExpr.get(), EllipsisLoc, llvm::Optional<unsigned=
>()
+    };
+    Elements.push_back(Element);
+   =20
+    if (Tok.is(tok::comma))
+      ConsumeToken(); // Eat the ','.
+    else if (Tok.isNot(tok::r_brace))
+      return ExprError(Diag(Tok, diag::err_expected_rbrace_or_comma));
+  }
+  SourceLocation EndLoc =3D ConsumeBrace();
+ =20
+  // Create the ObjCDictionaryLiteral.
+  return Owned(Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLo=
c),
+                                                  Elements.data(),
+                                                  Elements.size()));
+}
+
 ///    objc-encode-expression:
 ///      @encode ( type-name )
 ExprResult
@@ -2519,7 +2786,10 @@
  }
=20
 Decl *Parser::ParseLexedObjCMethodDefs(LexedMethod &LM) {
-   =20
+
+  // Save the current token position.
+  SourceLocation OrigLoc =3D Tok.getLocation();
+
   assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!");
   // Append the current token at the end of the new token stream so that it
   // doesn't get lost.
@@ -2541,22 +2811,36 @@
   // specified Declarator for the method.
   Actions.ActOnStartOfObjCMethodDef(getCurScope(), MDecl);
    =20
-  if (PP.isCodeCompletionEnabled()) {
-      if (trySkippingFunctionBodyForCodeCompletion()) {
-          BodyScope.Exit();
-          return Actions.ActOnFinishFunctionBody(MDecl, 0);
-      }
+  if (SkipFunctionBodies && trySkippingFunctionBody()) {
+    BodyScope.Exit();
+    return Actions.ActOnFinishFunctionBody(MDecl, 0);
   }
    =20
   StmtResult FnBody(ParseCompoundStatementBody());
    =20
   // If the function body could not be parsed, make a bogus compoundstmt.
-  if (FnBody.isInvalid())
+  if (FnBody.isInvalid()) {
+    Sema::CompoundScopeRAII CompoundScope(Actions);
     FnBody =3D Actions.ActOnCompoundStmt(BraceLoc, BraceLoc,
                                        MultiStmtArg(Actions), false);
+  }
    =20
   // Leave the function body scope.
   BodyScope.Exit();
    =20
-  return Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
+  MDecl =3D Actions.ActOnFinishFunctionBody(MDecl, FnBody.take());
+
+  if (Tok.getLocation() !=3D OrigLoc) {
+    // Due to parsing error, we either went over the cached tokens or
+    // there are still cached tokens left. If it's the latter case skip the
+    // leftover tokens.
+    // Since this is an uncommon situation that should be avoided, use the
+    // expensive isBeforeInTranslationUnit call.
+    if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
+                                                     OrigLoc))
+      while (Tok.getLocation() !=3D OrigLoc && Tok.isNot(tok::eof))
+        ConsumeAnyToken();
+  }
+ =20
+  return MDecl;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParsePragma.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParsePragma.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParsePragma.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -29,6 +29,31 @@
   ConsumeToken(); // The argument token.
 }
=20
+void Parser::HandlePragmaVisibility() {
+  assert(Tok.is(tok::annot_pragma_vis));
+  const IdentifierInfo *VisType =3D
+    static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
+  SourceLocation VisLoc =3D ConsumeToken();
+  Actions.ActOnPragmaVisibility(VisType, VisLoc);
+}
+
+struct PragmaPackInfo {
+  Sema::PragmaPackKind Kind;
+  IdentifierInfo *Name;
+  Expr *Alignment;
+  SourceLocation LParenLoc;
+  SourceLocation RParenLoc;
+};
+
+void Parser::HandlePragmaPack() {
+  assert(Tok.is(tok::annot_pragma_pack));
+  PragmaPackInfo *Info =3D
+    static_cast<PragmaPackInfo *>(Tok.getAnnotationValue());
+  SourceLocation PragmaLoc =3D ConsumeToken();
+  Actions.ActOnPragmaPack(Info->Kind, Info->Name, Info->Alignment, PragmaL=
oc,
+                          Info->LParenLoc, Info->RParenLoc);
+}
+
 // #pragma GCC visibility comes in two variants:
 //   'push' '(' [visibility] ')'
 //   'pop'
@@ -42,13 +67,10 @@
=20
   const IdentifierInfo *PushPop =3D Tok.getIdentifierInfo();
=20
-  bool IsPush;
   const IdentifierInfo *VisType;
   if (PushPop && PushPop->isStr("pop")) {
-    IsPush =3D false;
     VisType =3D 0;
   } else if (PushPop && PushPop->isStr("push")) {
-    IsPush =3D true;
     PP.LexUnexpandedToken(Tok);
     if (Tok.isNot(tok::l_paren)) {
       PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
@@ -80,7 +102,14 @@
     return;
   }
=20
-  Actions.ActOnPragmaVisibility(IsPush, VisType, VisLoc);
+  Token *Toks =3D new Token[1];
+  Toks[0].startToken();
+  Toks[0].setKind(tok::annot_pragma_vis);
+  Toks[0].setLocation(VisLoc);
+  Toks[0].setAnnotationValue(
+                          const_cast<void*>(static_cast<const void*>(VisTy=
pe)));
+  PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=3D*/true,
+                      /*OwnsTokens=3D*/true);
 }
=20
 // #pragma pack(...) comes in the following delicious flavors:
@@ -110,6 +139,12 @@
       return;
=20
     PP.Lex(Tok);
+
+    // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
+    // the push/pop stack.
+    // In Apple gcc, #pragma pack(4) is equivalent to #pragma pack(push, 4)
+    if (PP.getLangOpts().ApplePragmaPack)
+      Kind =3D Sema::PPK_Push;
   } else if (Tok.is(tok::identifier)) {
     const IdentifierInfo *II =3D Tok.getIdentifierInfo();
     if (II->isStr("show")) {
@@ -159,6 +194,11 @@
         }
       }
     }
+  } else if (PP.getLangOpts().ApplePragmaPack) {
+    // In MSVC/gcc, #pragma pack() resets the alignment without affecting
+    // the push/pop stack.
+    // In Apple gcc #pragma pack() is equivalent to #pragma pack(pop).
+    Kind =3D Sema::PPK_Pop;
   }
=20
   if (Tok.isNot(tok::r_paren)) {
@@ -173,8 +213,26 @@
     return;
   }
=20
-  Actions.ActOnPragmaPack(Kind, Name, Alignment.release(), PackLoc,
-                          LParenLoc, RParenLoc);
+  PragmaPackInfo *Info =3D=20
+    (PragmaPackInfo*) PP.getPreprocessorAllocator().Allocate(
+      sizeof(PragmaPackInfo), llvm::alignOf<PragmaPackInfo>());
+  new (Info) PragmaPackInfo();
+  Info->Kind =3D Kind;
+  Info->Name =3D Name;
+  Info->Alignment =3D Alignment.release();
+  Info->LParenLoc =3D LParenLoc;
+  Info->RParenLoc =3D RParenLoc;
+
+  Token *Toks =3D=20
+    (Token*) PP.getPreprocessorAllocator().Allocate(
+      sizeof(Token) * 1, llvm::alignOf<Token>());
+  new (Toks) Token();
+  Toks[0].startToken();
+  Toks[0].setKind(tok::annot_pragma_pack);
+  Toks[0].setLocation(PackLoc);
+  Toks[0].setAnnotationValue(static_cast<void*>(Info));
+  PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=3D*/true,
+                      /*OwnsTokens=3D*/false);
 }
=20
 // #pragma ms_struct on
@@ -203,7 +261,8 @@
   }
  =20
   if (Tok.isNot(tok::eod)) {
-    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "=
ms_struct";
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
+      << "ms_struct";
     return;
   }
   Actions.ActOnPragmaMSStruct(Kind);
@@ -348,7 +407,9 @@
   // This allows us to cache a "#pragma unused" that occurs inside an inli=
ne
   // C++ member function.
=20
-  Token *Toks =3D new Token[2*Identifiers.size()];
+  Token *Toks =3D=20
+    (Token*) PP.getPreprocessorAllocator().Allocate(
+      sizeof(Token) * 2 * Identifiers.size(), llvm::alignOf<Token>());
   for (unsigned i=3D0; i !=3D Identifiers.size(); i++) {
     Token &pragmaUnusedTok =3D Toks[2*i], &idTok =3D Toks[2*i+1];
     pragmaUnusedTok.startToken();
@@ -356,7 +417,8 @@
     pragmaUnusedTok.setLocation(UnusedLoc);
     idTok =3D Identifiers[i];
   }
-  PP.EnterTokenStream(Toks, 2*Identifiers.size(), /*DisableMacroExpansion=
=3D*/true, /*OwnsTokens=3D*/true);
+  PP.EnterTokenStream(Toks, 2*Identifiers.size(),
+                      /*DisableMacroExpansion=3D*/true, /*OwnsTokens=3D*/f=
alse);
 }
=20
 // #pragma weak identifier
@@ -403,6 +465,44 @@
   }
 }
=20
+// #pragma redefine_extname identifier identifier
+void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP,=20
+                                               PragmaIntroducerKind Introd=
ucer,
+                                                Token &RedefToken) {
+  SourceLocation RedefLoc =3D RedefToken.getLocation();
+
+  Token Tok;
+  PP.Lex(Tok);
+  if (Tok.isNot(tok::identifier)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
+      "redefine_extname";
+    return;
+  }
+
+  IdentifierInfo *RedefName =3D Tok.getIdentifierInfo(), *AliasName =3D 0;
+  SourceLocation RedefNameLoc =3D Tok.getLocation(), AliasNameLoc;
+
+  PP.Lex(Tok);
+  if (Tok.isNot(tok::identifier)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
+        << "redefine_extname";
+    return;
+  }
+  AliasName =3D Tok.getIdentifierInfo();
+  AliasNameLoc =3D Tok.getLocation();
+  PP.Lex(Tok);
+
+  if (Tok.isNot(tok::eod)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
+      "redefine_extname";
+    return;
+  }
+
+  Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
+      RedefNameLoc, AliasNameLoc);
+}
+
+
 void
 PragmaFPContractHandler::HandlePragma(Preprocessor &PP,=20
                                       PragmaIntroducerKind Introducer,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParsePragma.h
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParsePragma.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParsePragma.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -90,6 +90,16 @@
                             Token &FirstToken);
 };
=20
+class PragmaRedefineExtnameHandler : public PragmaHandler {
+  Sema &Actions;
+public:
+  explicit PragmaRedefineExtnameHandler(Sema &A)
+    : PragmaHandler("redefine_extname"), Actions(A) {}
+
+  virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introdu=
cer,
+                            Token &FirstToken);
+};
+
 class PragmaOpenCLExtensionHandler : public PragmaHandler {
   Sema &Actions;
   Parser &parser;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseStmt.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseStmt.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseStmt.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -76,14 +76,15 @@
 /// [OBC]   '@' 'throw' ';'
 ///
 StmtResult
-Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement)=
 {
+Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement,
+                                    SourceLocation *TrailingElseLoc) {
   const char *SemiError =3D 0;
   StmtResult Res;
=20
   ParenBraceBracketBalancer BalancerRAIIObj(*this);
=20
   ParsedAttributesWithRange attrs(AttrFactory);
-  MaybeParseCXX0XAttributes(attrs);
+  MaybeParseCXX0XAttributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
=20
   // Cases in this switch statement should fall through if the parser expe=
cts
   // the token to end in a semicolon (in which case SemiError should be se=
t),
@@ -115,7 +116,7 @@
       IdentifierInfo *Name =3D Tok.getIdentifierInfo();
       SourceLocation NameLoc =3D Tok.getLocation();
=20
-      if (getLang().CPlusPlus)
+      if (getLangOpts().CPlusPlus)
         CheckForTemplateAndDigraph(Next, ParsedType(),
                                    /*EnteringContext=3D*/false, *Name, SS);
=20
@@ -170,7 +171,7 @@
         if (AnnotateTemplateIdToken(
                             TemplateTy::make(Classification.getTemplateNam=
e()),
                                     Classification.getTemplateNameKind(),
-                                    SS, Id, SourceLocation(),
+                                    SS, SourceLocation(), Id,
                                     /*AllowTypeAnnotation=3D*/false)) {
           // Handle errors here by skipping up to the next semicolon or '}=
', and
           // eat the semicolon if that's what stopped us.
@@ -206,7 +207,7 @@
   }
=20
   default: {
-    if ((getLang().CPlusPlus || !OnlyStatement) && isDeclarationStatement(=
)) {
+    if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatem=
ent()) {
       SourceLocation DeclStart =3D Tok.getLocation(), DeclEnd;
       DeclGroupPtrTy Decl =3D ParseDeclaration(Stmts, Declarator::BlockCon=
text,
                                              DeclEnd, attrs);
@@ -234,18 +235,18 @@
   }
=20
   case tok::kw_if:                  // C99 6.8.4.1: if-statement
-    return ParseIfStatement(attrs);
+    return ParseIfStatement(attrs, TrailingElseLoc);
   case tok::kw_switch:              // C99 6.8.4.2: switch-statement
-    return ParseSwitchStatement(attrs);
+    return ParseSwitchStatement(attrs, TrailingElseLoc);
=20
   case tok::kw_while:               // C99 6.8.5.1: while-statement
-    return ParseWhileStatement(attrs);
+    return ParseWhileStatement(attrs, TrailingElseLoc);
   case tok::kw_do:                  // C99 6.8.5.2: do-statement
     Res =3D ParseDoStatement(attrs);
     SemiError =3D "do/while";
     break;
   case tok::kw_for:                 // C99 6.8.5.3: for-statement
-    return ParseForStatement(attrs);
+    return ParseForStatement(attrs, TrailingElseLoc);
=20
   case tok::kw_goto:                // C99 6.8.6.1: goto-statement
     Res =3D ParseGotoStatement(attrs);
@@ -279,6 +280,14 @@
=20
   case tok::kw___try:
     return ParseSEHTryBlock(attrs);
+
+  case tok::annot_pragma_vis:
+    HandlePragmaVisibility();
+    return StmtEmpty();
+
+  case tok::annot_pragma_pack:
+    HandlePragmaPack();
+    return StmtEmpty();
   }
=20
   // If we reached this code, the statement must end in a semicolon.
@@ -355,7 +364,8 @@
     return move(TryBlock);
=20
   StmtResult Handler;
-  if(Tok.is(tok::kw___except)) {
+  if (Tok.is(tok::identifier) &&=20
+      Tok.getIdentifierInfo() =3D=3D getSEHExceptKeyword()) {
     SourceLocation Loc =3D ConsumeToken();
     Handler =3D ParseSEHExceptBlock(Loc);
   } else if (Tok.is(tok::kw___finally)) {
@@ -389,14 +399,14 @@
=20
   ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope);
=20
-  if (getLang().Borland) {
+  if (getLangOpts().Borland) {
     Ident__exception_info->setIsPoisoned(false);
     Ident___exception_info->setIsPoisoned(false);
     Ident_GetExceptionInfo->setIsPoisoned(false);
   }
   ExprResult FilterExpr(ParseExpression());
=20
-  if (getLang().Borland) {
+  if (getLangOpts().Borland) {
     Ident__exception_info->setIsPoisoned(true);
     Ident___exception_info->setIsPoisoned(true);
     Ident_GetExceptionInfo->setIsPoisoned(true);
@@ -594,7 +604,8 @@
     // Nicely diagnose the common error "switch (X) { case 4: }", which is
     // not valid.
     SourceLocation AfterColonLoc =3D PP.getLocForEndOfToken(ColonLoc);
-    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement);
+    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
+      << FixItHint::CreateInsertion(AfterColonLoc, " ;");
     SubStmt =3D true;
   }
=20
@@ -636,16 +647,22 @@
     ColonLoc =3D ExpectedLoc;
   }
=20
-  // Diagnose the common error "switch (X) {... default: }", which is not =
valid.
-  if (Tok.is(tok::r_brace)) {
+  StmtResult SubStmt;
+
+  if (Tok.isNot(tok::r_brace)) {
+    SubStmt =3D ParseStatement();
+  } else {
+    // Diagnose the common error "switch (X) {... default: }", which is
+    // not valid.
     SourceLocation AfterColonLoc =3D PP.getLocForEndOfToken(ColonLoc);
-    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement);
-    return StmtError();
+    Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
+      << FixItHint::CreateInsertion(AfterColonLoc, " ;");
+    SubStmt =3D true;
   }
=20
-  StmtResult SubStmt(ParseStatement());
+  // Broken sub-stmt shouldn't prevent forming the case statement properly.
   if (SubStmt.isInvalid())
-    return StmtError();
+    SubStmt =3D Actions.ActOnNullStmt(ColonLoc);
=20
   return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
                                   SubStmt.get(), getCurScope());
@@ -698,7 +715,6 @@
   return ParseCompoundStatementBody(isStmtExpr);
 }
=20
-
 /// ParseCompoundStatementBody - Parse a sequence of statements and invoke=
 the
 /// ActOnCompoundStmt action.  This expects the '{' to be the current toke=
n, and
 /// consume the '}' at the end of the block.  It does not manipulate the s=
cope
@@ -712,6 +728,8 @@
   if (T.consumeOpen())
     return StmtError();
=20
+  Sema::CompoundScopeRAII CompoundScope(Actions);
+
   StmtVector Stmts(Actions);
=20
   // "__label__ X, Y, Z;" is the GNU "Local Label" extension.  These are
@@ -752,7 +770,7 @@
       continue;
     }
=20
-    if (getLang().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
+    if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) ||
         Tok.is(tok::kw___if_not_exists))) {
       ParseMicrosoftIfExistsStatement(Stmts);
       continue;
@@ -771,7 +789,7 @@
         ConsumeToken();
=20
       ParsedAttributesWithRange attrs(AttrFactory);
-      MaybeParseCXX0XAttributes(attrs);
+      MaybeParseCXX0XAttributes(attrs, 0, /*MightBeObjCMessageSend*/ true);
=20
       // If this is the start of a declaration, parse it as such.
       if (isDeclarationStatement()) {
@@ -805,17 +823,20 @@
       Stmts.push_back(R.release());
   }
=20
+  SourceLocation CloseLoc =3D Tok.getLocation();
+
   // We broke out of the while loop because we found a '}' or EOF.
   if (Tok.isNot(tok::r_brace)) {
     Diag(Tok, diag::err_expected_rbrace);
     Diag(T.getOpenLocation(), diag::note_matching) << "{";
-    return StmtError();
+    // Recover by creating a compound statement with what we parsed so far,
+    // instead of dropping everything and returning StmtError();
+  } else {
+    if (!T.consumeClose())
+      CloseLoc =3D T.getCloseLocation();
   }
=20
-  if (T.consumeClose())
-    return StmtError();
-
-  return Actions.ActOnCompoundStmt(T.getOpenLocation(), T.getCloseLocation=
(),
+  return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
                                    move_arg(Stmts), isStmtExpr);
 }
=20
@@ -837,7 +858,7 @@
   BalancedDelimiterTracker T(*this, tok::l_paren);
   T.consumeOpen();
=20
-  if (getLang().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean);
   else {
     ExprResult =3D ParseExpression();
@@ -873,7 +894,8 @@
 /// [C++]   'if' '(' condition ')' statement
 /// [C++]   'if' '(' condition ')' statement 'else' statement
 ///
-StmtResult Parser::ParseIfStatement(ParsedAttributes &attrs) {
+StmtResult Parser::ParseIfStatement(ParsedAttributes &attrs,
+                                    SourceLocation *TrailingElseLoc) {
   // FIXME: Use attributes?
=20
   assert(Tok.is(tok::kw_if) && "Not an if stmt!");
@@ -885,7 +907,7 @@
     return StmtError();
   }
=20
-  bool C99orCXX =3D getLang().C99 || getLang().CPlusPlus;
+  bool C99orCXX =3D getLangOpts().C99 || getLangOpts().CPlusPlus;
=20
   // C99 6.8.4p3 - In C99, the if statement is a block.  This is not
   // the case for C90.
@@ -932,7 +954,9 @@
=20
   // Read the 'then' stmt.
   SourceLocation ThenStmtLoc =3D Tok.getLocation();
-  StmtResult ThenStmt(ParseStatement());
+
+  SourceLocation InnerStatementTrailingElseLoc;
+  StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc));
=20
   // Pop the 'if' scope if needed.
   InnerScope.Exit();
@@ -943,6 +967,9 @@
   StmtResult ElseStmt;
=20
   if (Tok.is(tok::kw_else)) {
+    if (TrailingElseLoc)
+      *TrailingElseLoc =3D Tok.getLocation();
+
     ElseLoc =3D ConsumeToken();
     ElseStmtLoc =3D Tok.getLocation();
=20
@@ -966,6 +993,8 @@
     Actions.CodeCompleteAfterIf(getCurScope());
     cutOffParsing();
     return StmtError();
+  } else if (InnerStatementTrailingElseLoc.isValid()) {
+    Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
   }
=20
   IfScope.Exit();
@@ -999,7 +1028,8 @@
 ///       switch-statement:
 ///         'switch' '(' expression ')' statement
 /// [C++]   'switch' '(' condition ')' statement
-StmtResult Parser::ParseSwitchStatement(ParsedAttributes &attrs) {
+StmtResult Parser::ParseSwitchStatement(ParsedAttributes &attrs,
+                                        SourceLocation *TrailingElseLoc) {
   // FIXME: Use attributes?
=20
   assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
@@ -1011,7 +1041,7 @@
     return StmtError();
   }
=20
-  bool C99orCXX =3D getLang().C99 || getLang().CPlusPlus;
+  bool C99orCXX =3D getLangOpts().C99 || getLangOpts().CPlusPlus;
=20
   // C99 6.8.4p3 - In C99, the switch statement is a block.  This is
   // not the case for C90.  Start the switch scope.
@@ -1067,15 +1097,20 @@
                         C99orCXX && Tok.isNot(tok::l_brace));
=20
   // Read the body statement.
-  StmtResult Body(ParseStatement());
+  StmtResult Body(ParseStatement(TrailingElseLoc));
=20
   // Pop the scopes.
   InnerScope.Exit();
   SwitchScope.Exit();
=20
-  if (Body.isInvalid())
+  if (Body.isInvalid()) {
     // FIXME: Remove the case statement list from the Switch statement.
-    Body =3D Actions.ActOnNullStmt(Tok.getLocation());
+
+    // Put the synthesized null statement on the same line as the end of s=
witch
+    // condition.
+    SourceLocation SynthesizedNullStmtLocation =3D Cond.get()->getLocEnd();
+    Body =3D Actions.ActOnNullStmt(SynthesizedNullStmtLocation);
+  }
=20
   return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get()=
);
 }
@@ -1084,7 +1119,8 @@
 ///       while-statement: [C99 6.8.5.1]
 ///         'while' '(' expression ')' statement
 /// [C++]   'while' '(' condition ')' statement
-StmtResult Parser::ParseWhileStatement(ParsedAttributes &attrs) {
+StmtResult Parser::ParseWhileStatement(ParsedAttributes &attrs,
+                                       SourceLocation *TrailingElseLoc) {
   // FIXME: Use attributes?
=20
   assert(Tok.is(tok::kw_while) && "Not a while stmt!");
@@ -1097,7 +1133,7 @@
     return StmtError();
   }
=20
-  bool C99orCXX =3D getLang().C99 || getLang().CPlusPlus;
+  bool C99orCXX =3D getLangOpts().C99 || getLangOpts().CPlusPlus;
=20
   // C99 6.8.5p5 - In C99, the while statement is a block.  This is not
   // the case for C90.  Start the loop scope.
@@ -1142,7 +1178,7 @@
                         C99orCXX && Tok.isNot(tok::l_brace));
=20
   // Read the body statement.
-  StmtResult Body(ParseStatement());
+  StmtResult Body(ParseStatement(TrailingElseLoc));
=20
   // Pop the body scope if needed.
   InnerScope.Exit();
@@ -1167,7 +1203,7 @@
   // C99 6.8.5p5 - In C99, the do statement is a block.  This is not
   // the case for C90.  Start the loop scope.
   unsigned ScopeFlags;
-  if (getLang().C99)
+  if (getLangOpts().C99)
     ScopeFlags =3D Scope::BreakScope | Scope::ContinueScope | Scope::DeclS=
cope;
   else
     ScopeFlags =3D Scope::BreakScope | Scope::ContinueScope;
@@ -1183,7 +1219,7 @@
   // which is entered and exited each time through the loop.
   //
   ParseScope InnerScope(this, Scope::DeclScope,
-                        (getLang().C99 || getLang().CPlusPlus) &&
+                        (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
                         Tok.isNot(tok::l_brace));
=20
   // Read the body statement.
@@ -1241,7 +1277,8 @@
 /// [C++0x] for-range-initializer:
 /// [C++0x]   expression
 /// [C++0x]   braced-init-list            [TODO]
-StmtResult Parser::ParseForStatement(ParsedAttributes &attrs) {
+StmtResult Parser::ParseForStatement(ParsedAttributes &attrs,
+                                     SourceLocation *TrailingElseLoc) {
   // FIXME: Use attributes?
=20
   assert(Tok.is(tok::kw_for) && "Not a for stmt!");
@@ -1253,7 +1290,7 @@
     return StmtError();
   }
=20
-  bool C99orCXXorObjC =3D getLang().C99 || getLang().CPlusPlus || getLang(=
).ObjC1;
+  bool C99orCXXorObjC =3D getLangOpts().C99 || getLangOpts().CPlusPlus || =
getLangOpts().ObjC1;
=20
   // C99 6.8.5p5 - In C99, the for statement is a block.  This is not
   // the case for C90.  Start the loop scope.
@@ -1305,7 +1342,7 @@
   if (Tok.is(tok::semi)) {  // for (;
     // no first part, eat the ';'.
     ConsumeToken();
-  } else if (isSimpleDeclaration()) {  // for (int X =3D 4;
+  } else if (isForInitDeclaration()) {  // for (int X =3D 4;
     // Parse declaration, which eats the ';'.
     if (!C99orCXXorObjC)   // Use of C99-style for loops in C90 mode?
       Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
@@ -1314,7 +1351,7 @@
     MaybeParseCXX0XAttributes(attrs);
=20
     // In C++0x, "for (T NS:a" might not be a typo for ::
-    bool MightBeForRangeStmt =3D getLang().CPlusPlus;
+    bool MightBeForRangeStmt =3D getLangOpts().CPlusPlus;
     ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
=20
     SourceLocation DeclStart =3D Tok.getLocation(), DeclEnd;
@@ -1326,8 +1363,8 @@
     FirstPart =3D Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
=20
     if (ForRangeInit.ParsedForRangeDecl()) {
-      if (!getLang().CPlusPlus0x)
-        Diag(ForRangeInit.ColonLoc, diag::ext_for_range);
+      Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_for_range : diag::ext_for_range);
=20
       ForRange =3D true;
     } else if (Tok.is(tok::semi)) {  // for (int x =3D 4;
@@ -1370,6 +1407,13 @@
         return StmtError();
       }
       Collection =3D ParseExpression();
+    } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::colon) && FirstPar=
t.get()) {
+      // User tried to write the reasonable, but ill-formed, for-range-sta=
tement
+      //   for (expr : expr) { ... }
+      Diag(Tok, diag::err_for_range_expected_decl)
+        << FirstPart.get()->getSourceRange();
+      SkipUntil(tok::r_paren, false, true);
+      SecondPartIsInvalid =3D true;
     } else {
       if (!Value.isInvalid()) {
         Diag(Tok, diag::err_expected_semi_for);
@@ -1390,7 +1434,7 @@
       // missing both semicolons.
     } else {
       ExprResult Second;
-      if (getLang().CPlusPlus)
+      if (getLangOpts().CPlusPlus)
         ParseCXXCondition(Second, SecondVar, ForLoc, true);
       else {
         Second =3D ParseExpression();
@@ -1458,7 +1502,7 @@
                         C99orCXXorObjC && Tok.isNot(tok::l_brace));
=20
   // Read the body statement.
-  StmtResult Body(ParseStatement());
+  StmtResult Body(ParseStatement(TrailingElseLoc));
=20
   // Pop the body scope if needed.
   InnerScope.Exit();
@@ -1564,13 +1608,12 @@
       return StmtError();
     }
=20
-    // FIXME: This is a hack to allow something like C++0x's generalized
-    // initializer lists, but only enough of this feature to allow Clang to
-    // parse libstdc++ 4.5's headers.
-    if (Tok.is(tok::l_brace) && getLang().CPlusPlus) {
+    if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
       R =3D ParseInitializer();
-      if (R.isUsable() && !getLang().CPlusPlus0x)
-        Diag(R.get()->getLocStart(), diag::ext_generalized_initializer_lis=
ts)
+      if (R.isUsable())
+        Diag(R.get()->getLocStart(), getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_generalized_initializer_lists :
+             diag::ext_generalized_initializer_lists)
           << R.get()->getSourceRange();
     } else
         R =3D ParseExpression();
@@ -1731,7 +1774,7 @@
   assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
   SourceLocation AsmLoc =3D ConsumeToken();
=20
-  if (getLang().MicrosoftExt && Tok.isNot(tok::l_paren) && !isTypeQualifie=
r()) {
+  if (getLangOpts().MicrosoftExt && Tok.isNot(tok::l_paren) && !isTypeQual=
ifier()) {
     msAsm =3D true;
     return ParseMicrosoftAsmStatement(AsmLoc);
   }
@@ -1756,8 +1799,11 @@
   T.consumeOpen();
=20
   ExprResult AsmString(ParseAsmStringLiteral());
-  if (AsmString.isInvalid())
+  if (AsmString.isInvalid()) {
+    // Consume up to and including the closing paren.
+    T.skipToEnd();
     return StmtError();
+  }
=20
   SmallVector<IdentifierInfo *, 4> Names;
   ExprVector Constraints(Actions);
@@ -1906,19 +1952,15 @@
     if (Tok.isNot(tok::comma)) return false;
     ConsumeToken();
   }
-
-  return true;
 }
=20
 Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope=
) {
   assert(Tok.is(tok::l_brace));
   SourceLocation LBraceLoc =3D Tok.getLocation();
=20
-  if (PP.isCodeCompletionEnabled()) {
-    if (trySkippingFunctionBodyForCodeCompletion()) {
-      BodyScope.Exit();
-      return Actions.ActOnFinishFunctionBody(Decl, 0);
-    }
+  if (SkipFunctionBodies && trySkippingFunctionBody()) {
+    BodyScope.Exit();
+    return Actions.ActOnFinishFunctionBody(Decl, 0);
   }
=20
   PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc,
@@ -1930,9 +1972,11 @@
   StmtResult FnBody(ParseCompoundStatementBody());
=20
   // If the function body could not be parsed, make a bogus compoundstmt.
-  if (FnBody.isInvalid())
+  if (FnBody.isInvalid()) {
+    Sema::CompoundScopeRAII CompoundScope(Actions);
     FnBody =3D Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
                                        MultiStmtArg(Actions), false);
+  }
=20
   BodyScope.Exit();
   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
@@ -1956,36 +2000,36 @@
   else
     Actions.ActOnDefaultCtorInitializers(Decl);
=20
-  if (PP.isCodeCompletionEnabled()) {
-    if (trySkippingFunctionBodyForCodeCompletion()) {
-      BodyScope.Exit();
-      return Actions.ActOnFinishFunctionBody(Decl, 0);
-    }
+  if (SkipFunctionBodies && trySkippingFunctionBody()) {
+    BodyScope.Exit();
+    return Actions.ActOnFinishFunctionBody(Decl, 0);
   }
=20
   SourceLocation LBraceLoc =3D Tok.getLocation();
   StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc));
   // If we failed to parse the try-catch, we just give the function an emp=
ty
   // compound statement as the body.
-  if (FnBody.isInvalid())
+  if (FnBody.isInvalid()) {
+    Sema::CompoundScopeRAII CompoundScope(Actions);
     FnBody =3D Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc,
                                        MultiStmtArg(Actions), false);
+  }
=20
   BodyScope.Exit();
   return Actions.ActOnFinishFunctionBody(Decl, FnBody.take());
 }
=20
-bool Parser::trySkippingFunctionBodyForCodeCompletion() {
+bool Parser::trySkippingFunctionBody() {
   assert(Tok.is(tok::l_brace));
-  assert(PP.isCodeCompletionEnabled() &&
-         "Should only be called when in code-completion mode");
+  assert(SkipFunctionBodies &&
+         "Should only be called when SkipFunctionBodies is enabled");
=20
   // We're in code-completion mode. Skip parsing for all function bodies u=
nless
   // the body contains the code-completion point.
   TentativeParsingAction PA(*this);
   ConsumeBrace();
   if (SkipUntil(tok::r_brace, /*StopAtSemi=3D*/false, /*DontConsume=3D*/fa=
lse,
-                /*StopAtCodeCompletion=3D*/true)) {
+                /*StopAtCodeCompletion=3D*/PP.isCodeCompletionEnabled())) {
     PA.Commit();
     return true;
   }
@@ -2035,10 +2079,13 @@
     return move(TryBlock);
=20
   // Borland allows SEH-handlers with 'try'
-  if(Tok.is(tok::kw___except) || Tok.is(tok::kw___finally)) {
+ =20
+  if((Tok.is(tok::identifier) &&=20
+      Tok.getIdentifierInfo() =3D=3D getSEHExceptKeyword()) ||=20
+     Tok.is(tok::kw___finally)) {
     // TODO: Factor into common return ParseSEHHandlerCommon(...)
     StmtResult Handler;
-    if(Tok.is(tok::kw___except)) {
+    if(Tok.getIdentifierInfo() =3D=3D getSEHExceptKeyword()) {
       SourceLocation Loc =3D ConsumeToken();
       Handler =3D ParseSEHExceptBlock(Loc);
     }
@@ -2130,19 +2177,51 @@
 }
=20
 void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
-  bool Result;
+  IfExistsCondition Result;
   if (ParseMicrosoftIfExistsCondition(Result))
     return;
=20
-  if (Tok.isNot(tok::l_brace)) {
+  // Handle dependent statements by parsing the braces as a compound state=
ment.
+  // This is not the same behavior as Visual C++, which don't treat this a=
s a
+  // compound statement, but for Clang's type checking we can't have anyth=
ing
+  // inside these braces escaping to the surrounding code.
+  if (Result.Behavior =3D=3D IEB_Dependent) {
+    if (!Tok.is(tok::l_brace)) {
+      Diag(Tok, diag::err_expected_lbrace);
+      return;     =20
+    }
+   =20
+    ParsedAttributes Attrs(AttrFactory);
+    StmtResult Compound =3D ParseCompoundStatement(Attrs);
+    if (Compound.isInvalid())
+      return;
+   =20
+    StmtResult DepResult =3D Actions.ActOnMSDependentExistsStmt(Result.Key=
wordLoc,
+                                                              Result.IsIfE=
xists,
+                                                              Result.SS,=20
+                                                              Result.Name,
+                                                              Compound.get=
());
+    if (DepResult.isUsable())
+      Stmts.push_back(DepResult.get());
+    return;
+  }
+ =20
+  BalancedDelimiterTracker Braces(*this, tok::l_brace);
+  if (Braces.consumeOpen()) {
     Diag(Tok, diag::err_expected_lbrace);
     return;
   }
-  ConsumeBrace();
=20
-  // Condition is false skip all inside the {}.
-  if (!Result) {
-    SkipUntil(tok::r_brace, false);
+  switch (Result.Behavior) {
+  case IEB_Parse:
+    // Parse the statements below.
+    break;
+     =20
+  case IEB_Dependent:
+    llvm_unreachable("Dependent case handled above");
+     =20
+  case IEB_Skip:
+    Braces.skipToEnd();
     return;
   }
=20
@@ -2152,10 +2231,5 @@
     if (R.isUsable())
       Stmts.push_back(R.release());
   }
-
-  if (Tok.isNot(tok::r_brace)) {
-    Diag(Tok, diag::err_expected_rbrace);
-    return;
-  }
-  ConsumeBrace();
+  Braces.consumeClose();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseTemplate.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseTemplate.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseTemplate.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -31,8 +31,9 @@
   ObjCDeclContextSwitch ObjCDC(*this);
  =20
   if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
-    return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
-                                           DeclEnd);
+    return ParseExplicitInstantiation(Context,
+                                      SourceLocation(), ConsumeToken(),
+                                      DeclEnd, AS);
   }
   return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
                                                   AccessAttrs);
@@ -240,6 +241,10 @@
     return 0;
   }
=20
+  LateParsedAttrList LateParsedAttrs;
+  if (DeclaratorInfo.isFunctionDeclarator())
+    MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
+
   // If we have a declaration or declarator list, handle it.
   if (isDeclarationAfterDeclarator()) {
     // Parse this declaration.
@@ -255,6 +260,8 @@
=20
     // Eat the semi colon after the declaration.
     ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
+    if (LateParsedAttrs.size() > 0)
+      ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
     DeclaratorInfo.complete(ThisDecl);
     return ThisDecl;
   }
@@ -262,20 +269,15 @@
   if (DeclaratorInfo.isFunctionDeclarator() &&
       isStartOfFunctionDefinition(DeclaratorInfo)) {
     if (DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_typedef) {
-      Diag(Tok, diag::err_function_declared_typedef);
-
-      if (Tok.is(tok::l_brace)) {
-        // This recovery skips the entire function body. It would be nice
-        // to simply call ParseFunctionDefinition() below, however Sema
-        // assumes the declarator represents a function, not a typedef.
-        ConsumeBrace();
-        SkipUntil(tok::r_brace, true);
-      } else {
-        SkipUntil(tok::semi);
-      }
-      return 0;
+      // Recover by ignoring the 'typedef'. This was probably supposed to =
be
+      // the 'typename' keyword, which we should have already suggested ad=
ding
+      // if it's appropriate.
+      Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typede=
f)
+        << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
+      DS.ClearStorageClassSpecs();
     }
-    return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
+    return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
+                                   &LateParsedAttrs);
   }
=20
   if (DeclaratorInfo.isFunctionDeclarator())
@@ -307,14 +309,19 @@
   LAngleLoc =3D ConsumeToken();
=20
   // Try to parse the template parameter list.
-  if (Tok.is(tok::greater))
+  bool Failed =3D false;
+  if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
+    Failed =3D ParseTemplateParameterList(Depth, TemplateParams);
+
+  if (Tok.is(tok::greatergreater)) {
+    Tok.setKind(tok::greater);
+    RAngleLoc =3D Tok.getLocation();
+    Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
+  } else if (Tok.is(tok::greater))
     RAngleLoc =3D ConsumeToken();
-  else if (ParseTemplateParameterList(Depth, TemplateParams)) {
-    if (!Tok.is(tok::greater)) {
-      Diag(Tok.getLocation(), diag::err_expected_greater);
-      return true;
-    }
-    RAngleLoc =3D ConsumeToken();
+  else if (Failed) {
+    Diag(Tok.getLocation(), diag::err_expected_greater);
+    return true;
   }
   return false;
 }
@@ -337,23 +344,21 @@
     } else {
       // If we failed to parse a template parameter, skip until we find
       // a comma or closing brace.
-      SkipUntil(tok::comma, tok::greater, true, true);
+      SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
     }
=20
     // Did we find a comma or the end of the template parmeter list?
     if (Tok.is(tok::comma)) {
       ConsumeToken();
-    } else if (Tok.is(tok::greater)) {
+    } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
       // Don't consume this... that's done by template parser.
       break;
     } else {
       // Somebody probably forgot to close the template. Skip ahead and
       // try to get out of the expression. This error is currently
       // subsumed by whatever goes on in ParseTemplateParameter.
-      // TODO: This could match >>, and it would be nice to avoid those
-      // silly errors with template <vec<T>>.
       Diag(Tok.getLocation(), diag::err_expected_comma_greater);
-      SkipUntil(tok::greater, true, true);
+      SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
       return false;
     }
   }
@@ -476,7 +481,7 @@
     EllipsisLoc =3D ConsumeToken();
=20
     Diag(EllipsisLoc,
-         getLang().CPlusPlus0x
+         getLangOpts().CPlusPlus0x
            ? diag::warn_cxx98_compat_variadic_templates
            : diag::ext_variadic_templates);
   }
@@ -488,7 +493,7 @@
     ParamName =3D Tok.getIdentifierInfo();
     NameLoc =3D ConsumeToken();
   } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
-            Tok.is(tok::greater)) {
+             Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
     // Unnamed template parameter. Don't have to do anything here, just
     // don't consume this token.
   } else {
@@ -503,9 +508,10 @@
   ParsedType DefaultArg;
   if (Tok.is(tok::equal)) {
     EqualLoc =3D ConsumeToken();
-    DefaultArg =3D ParseTypeName().get();
+    DefaultArg =3D ParseTypeName(/*Range=3D*/0,
+                               Declarator::TemplateTypeArgContext).get();
   }
- =20
+
   return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellips=
is,=20
                                     EllipsisLoc, KeyLoc, ParamName, NameLo=
c,
                                     Depth, Position, EqualLoc, DefaultArg);
@@ -536,13 +542,25 @@
   }
=20
   // Generate a meaningful error if the user forgot to put class before the
-  // identifier, comma, or greater.
+  // identifier, comma, or greater. Provide a fixit if the identifier, com=
ma,
+  // or greater appear immediately or after 'typename' or 'struct'. In the
+  // latter case, replace the keyword with 'class'.
   if (!Tok.is(tok::kw_class)) {
-    Diag(Tok.getLocation(), diag::err_expected_class_before)
-      << PP.getSpelling(Tok);
-    return 0;
-  }
-  ConsumeToken();
+    bool Replace =3D Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
+    const Token& Next =3D Replace ? NextToken() : Tok;
+    if (Next.is(tok::identifier) || Next.is(tok::comma) ||
+        Next.is(tok::greater) || Next.is(tok::greatergreater) ||
+        Next.is(tok::ellipsis))
+      Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
+        << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "cla=
ss")
+                    : FixItHint::CreateInsertion(Tok.getLocation(), "class=
 "));
+    else
+      Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
+
+    if (Replace)
+      ConsumeToken();
+  } else
+    ConsumeToken();
=20
   // Parse the ellipsis, if given.
   SourceLocation EllipsisLoc;
@@ -550,7 +568,7 @@
     EllipsisLoc =3D ConsumeToken();
    =20
     Diag(EllipsisLoc,
-         getLang().CPlusPlus0x
+         getLangOpts().CPlusPlus0x
            ? diag::warn_cxx98_compat_variadic_templates
            : diag::ext_variadic_templates);
   }
@@ -561,7 +579,8 @@
   if (Tok.is(tok::identifier)) {
     ParamName =3D Tok.getIdentifierInfo();
     NameLoc =3D ConsumeToken();
-  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::great=
er)) {
+  } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
+             Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
     // Unnamed template parameter. Don't have to do anything here, just
     // don't consume this token.
   } else {
@@ -587,10 +606,7 @@
     if (DefaultArg.isInvalid()) {
       Diag(Tok.getLocation(),=20
            diag::err_default_template_template_parameter_not_template);
-      static const tok::TokenKind EndToks[] =3D {=20
-        tok::comma, tok::greater, tok::greatergreater
-      };
-      SkipUntil(EndToks, 3, true, true);
+      SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
     }
   }
  =20
@@ -618,12 +634,7 @@
   Declarator ParamDecl(DS, Declarator::TemplateParamContext);
   ParseDeclarator(ParamDecl);
   if (DS.getTypeSpecType() =3D=3D DeclSpec::TST_unspecified) {
-    // This probably shouldn't happen - and it's more of a Sema thing, but
-    // basically we didn't parse the type name because we couldn't associa=
te
-    // it with an AST node. we should just skip to the comma or greater.
-    // TODO: This is currently a placeholder for some kind of Sema Error.
-    Diag(Tok.getLocation(), diag::err_parse_error);
-    SkipUntil(tok::comma, tok::greater, true, true);
+    Diag(Tok.getLocation(), diag::err_expected_template_parameter);
     return 0;
   }
=20
@@ -709,15 +720,15 @@
   RAngleLoc =3D Tok.getLocation();
=20
   if (Tok.is(tok::greatergreater)) {
-    if (!getLang().CPlusPlus0x) {
-      const char *ReplaceStr =3D "> >";
-      if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreat=
er))
-        ReplaceStr =3D "> > ";
+    const char *ReplaceStr =3D "> >";
+    if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater=
))
+      ReplaceStr =3D "> > ";
=20
-      Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_spac=
e)
-        << FixItHint::CreateReplacement(
-                                 SourceRange(Tok.getLocation()), ReplaceSt=
r);
-    }
+    Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
+         diag::warn_cxx98_compat_two_right_angle_brackets :
+         diag::err_two_right_angle_brackets_need_space)
+      << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
+                                      ReplaceStr);
=20
     Tok.setKind(tok::greater);
     if (!ConsumeLastToken) {
@@ -770,10 +781,10 @@
 ///
 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind=
 TNK,
                                      CXXScopeSpec &SS,
+                                     SourceLocation TemplateKWLoc,
                                      UnqualifiedId &TemplateName,
-                                     SourceLocation TemplateKWLoc,
                                      bool AllowTypeAnnotation) {
-  assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
+  assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++=
");
   assert(Template && Tok.is(tok::less) &&
          "Parser isn't at the beginning of a template-id");
=20
@@ -803,10 +814,9 @@
   // Build the annotation token.
   if (TNK =3D=3D TNK_Type_template && AllowTypeAnnotation) {
     TypeResult Type
-      =3D Actions.ActOnTemplateIdType(SS,=20
+      =3D Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
                                     Template, TemplateNameLoc,
-                                    LAngleLoc, TemplateArgsPtr,
-                                    RAngleLoc);
+                                    LAngleLoc, TemplateArgsPtr, RAngleLoc);
     if (Type.isInvalid()) {
       // If we failed to parse the template ID but skipped ahead to a >, w=
e're not
       // going to be able to form a token annotation.  Eat the '>' if pres=
ent.
@@ -838,6 +848,7 @@
       TemplateId->Operator =3D TemplateName.OperatorFunctionId.Operator;
     }
     TemplateId->SS =3D SS;
+    TemplateId->TemplateKWLoc =3D TemplateKWLoc;
     TemplateId->Template =3D Template;
     TemplateId->Kind =3D TNK;
     TemplateId->LAngleLoc =3D LAngleLoc;
@@ -883,6 +894,7 @@
=20
   TypeResult Type
     =3D Actions.ActOnTemplateIdType(TemplateId->SS,
+                                  TemplateId->TemplateKWLoc,
                                   TemplateId->Template,
                                   TemplateId->TemplateNameLoc,
                                   TemplateId->LAngleLoc,
@@ -932,7 +944,7 @@
   if (SS.isSet() && Tok.is(tok::kw_template)) {
     // Parse the optional 'template' keyword following the=20
     // nested-name-specifier.
-    SourceLocation TemplateLoc =3D ConsumeToken();
+    SourceLocation TemplateKWLoc =3D ConsumeToken();
    =20
     if (Tok.is(tok::identifier)) {
       // We appear to have a dependent template name.
@@ -949,8 +961,8 @@
       // template argument.
       TemplateTy Template;
       if (isEndOfTemplateArgument(Tok) &&
-          Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
-                                             SS, Name,=20
+          Actions.ActOnDependentTemplateName(getCurScope(),
+                                             SS, TemplateKWLoc, Name,
                                              /*ObjectType=3D*/ ParsedType(=
),
                                              /*EnteringContext=3D*/false,
                                              Template))
@@ -1033,7 +1045,7 @@
  =20
   // Parse a non-type template argument.=20
   SourceLocation Loc =3D Tok.getLocation();
-  ExprResult ExprArg =3D ParseConstantExpression();
+  ExprResult ExprArg =3D ParseConstantExpression(MaybeTypeCast);
   if (ExprArg.isInvalid() || !ExprArg.get())
     return ParsedTemplateArgument();
=20
@@ -1113,17 +1125,19 @@
 ///         'extern' [opt] 'template' declaration
 ///
 /// Note that the 'extern' is a GNU extension and C++0x feature.
-Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
+Decl *Parser::ParseExplicitInstantiation(unsigned Context,
+                                         SourceLocation ExternLoc,
                                          SourceLocation TemplateLoc,
-                                         SourceLocation &DeclEnd) {
+                                         SourceLocation &DeclEnd,
+                                         AccessSpecifier AS) {
   // This isn't really required here.
   ParsingDeclRAIIObject ParsingTemplateParams(*this);
=20
-  return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
+  return ParseSingleDeclarationAfterTemplate(Context,
                                              ParsedTemplateInfo(ExternLoc,
                                                                 TemplateLo=
c),
                                              ParsingTemplateParams,
-                                             DeclEnd, AS_none);
+                                             DeclEnd, AS);
 }
=20
 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
@@ -1157,29 +1171,27 @@
   if(!LMT.D)
      return;
=20
-  // If this is a member template, introduce the template parameter scope.
-  ParseScope TemplateScope(this, Scope::TemplateParamScope);
-
   // Get the FunctionDecl.
   FunctionDecl *FD =3D 0;
   if (FunctionTemplateDecl *FunTmpl =3D dyn_cast<FunctionTemplateDecl>(LMT=
.D))
     FD =3D FunTmpl->getTemplatedDecl();
   else
     FD =3D cast<FunctionDecl>(LMT.D);
- =20
-  // Reinject the template parameters.
+
+  // To restore the context after late parsing.
+  Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
+
   SmallVector<ParseScope*, 4> TemplateParamScopeStack;
   DeclaratorDecl* Declarator =3D dyn_cast<DeclaratorDecl>(FD);
   if (Declarator && Declarator->getNumTemplateParameterLists() !=3D 0) {
+    TemplateParamScopeStack.push_back(new ParseScope(this, Scope::Template=
ParamScope));
     Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
     Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
   } else {
-    Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
-
     // Get the list of DeclContext to reenter.
     SmallVector<DeclContext*, 4> DeclContextToReenter;
     DeclContext *DD =3D FD->getLexicalParent();
-    while (DD && DD->isRecord()) {
+    while (DD && !DD->isTranslationUnit()) {
       DeclContextToReenter.push_back(DD);
       DD =3D DD->getLexicalParent();
     }
@@ -1190,7 +1202,7 @@
     for (; II !=3D DeclContextToReenter.rend(); ++II) {
       if (ClassTemplatePartialSpecializationDecl* MD =3D
                 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*=
II)) {
-       TemplateParamScopeStack.push_back(new ParseScope(this,
+        TemplateParamScopeStack.push_back(new ParseScope(this,
                                                    Scope::TemplateParamSco=
pe));
         Actions.ActOnReenterTemplateScope(getCurScope(), MD);
       } else if (CXXRecordDecl* MD =3D dyn_cast_or_null<CXXRecordDecl>(*II=
)) {
@@ -1200,8 +1212,14 @@
         Actions.ActOnReenterTemplateScope(getCurScope(),
                                           MD->getDescribedClassTemplate());
       }
+      TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclSc=
ope));
+      Actions.PushDeclContext(Actions.getCurScope(), *II);
     }
+    TemplateParamScopeStack.push_back(new ParseScope(this,
+                                      Scope::TemplateParamScope));
+    Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
   }
+
   assert(!LMT.Toks.empty() && "Empty body!");
=20
   // Append the current token at the end of the new token stream so that it
@@ -1218,8 +1236,8 @@
   // to be re-used for method bodies as well.
   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
=20
-  // Recreate the DeclContext.
-  Sema::ContextRAII SavedContext(Actions, Actions.getContainingDC(FD));
+  // Recreate the containing function DeclContext.
+  Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(=
FD));
=20
   if (FunctionTemplateDecl *FunctionTemplate
         =3D dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
@@ -1227,7 +1245,7 @@
                                    FunctionTemplate->getTemplatedDecl());
   if (FunctionDecl *Function =3D dyn_cast_or_null<FunctionDecl>(LMT.D))
     Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
- =20
+
=20
   if (Tok.is(tok::kw_try)) {
     ParseFunctionTryBlock(LMT.D, FnScope);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/ParseTentative.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/ParseTentative.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/ParseTentative.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -62,7 +62,7 @@
     return true;
     // simple-declaration
   default:
-    return isCXXSimpleDeclaration();
+    return isCXXSimpleDeclaration(/*AllowForRangeDecl=3D*/false);
   }
 }
=20
@@ -75,7 +75,11 @@
 /// simple-declaration:
 ///   decl-specifier-seq init-declarator-list[opt] ';'
 ///
-bool Parser::isCXXSimpleDeclaration() {
+/// (if AllowForRangeDecl specified)
+/// for ( for-range-declaration : for-range-initializer ) statement
+/// for-range-declaration:=20
+///    attribute-specifier-seqopt type-specifier-seq declarator
+bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) {
   // C++ 6.8p1:
   // There is an ambiguity in the grammar involving expression-statements =
and
   // declarations: An expression-statement with a function-style explicit =
type
@@ -112,7 +116,7 @@
   // We need tentative parsing...
=20
   TentativeParsingAction PA(*this);
-  TPR =3D TryParseSimpleDeclaration();
+  TPR =3D TryParseSimpleDeclaration(AllowForRangeDecl);
   PA.Revert();
=20
   // In case of an error, let the declaration parsing code handle it.
@@ -130,7 +134,12 @@
 /// simple-declaration:
 ///   decl-specifier-seq init-declarator-list[opt] ';'
 ///
-Parser::TPResult Parser::TryParseSimpleDeclaration() {
+/// (if AllowForRangeDecl specified)
+/// for ( for-range-declaration : for-range-initializer ) statement
+/// for-range-declaration:=20
+///    attribute-specifier-seqopt type-specifier-seq declarator
+///
+Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl)=
 {
   // We know that we have a simple-type-specifier/typename-specifier follo=
wed
   // by a '('.
   assert(isCXXDeclarationSpecifier() =3D=3D TPResult::Ambiguous());
@@ -140,7 +149,7 @@
   else {
     ConsumeToken();
    =20
-    if (getLang().ObjC1 && Tok.is(tok::less))
+    if (getLangOpts().ObjC1 && Tok.is(tok::less))
       TryParseProtocolQualifiers();
   }
  =20
@@ -150,7 +159,7 @@
   if (TPR !=3D TPResult::Ambiguous())
     return TPR;
=20
-  if (Tok.isNot(tok::semi))
+  if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon)=
))
     return TPResult::False();
=20
   return TPResult::Ambiguous();
@@ -224,6 +233,8 @@
 ///       condition:
 ///         expression
 ///         type-specifier-seq declarator '=3D' assignment-expression
+/// [C++11] type-specifier-seq declarator '=3D' initializer-clause
+/// [C++11] type-specifier-seq declarator braced-init-list
 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[=
opt]
 ///             '=3D' assignment-expression
 ///
@@ -247,7 +258,7 @@
   else {
     ConsumeToken();
    =20
-    if (getLang().ObjC1 && Tok.is(tok::less))
+    if (getLangOpts().ObjC1 && Tok.is(tok::less))
       TryParseProtocolQualifiers();
   }
   assert(Tok.is(tok::l_paren) && "Expected '('");
@@ -265,6 +276,8 @@
     if (Tok.is(tok::equal)  ||
         Tok.is(tok::kw_asm) || Tok.is(tok::kw___attribute))
       TPR =3D TPResult::True();
+    else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace))
+      TPR =3D TPResult::True();
     else
       TPR =3D TPResult::False();
   }
@@ -322,7 +335,7 @@
   else {
     ConsumeToken();
    =20
-    if (getLang().ObjC1 && Tok.is(tok::less))
+    if (getLangOpts().ObjC1 && Tok.is(tok::less))
       TryParseProtocolQualifiers();
   }
  =20
@@ -347,7 +360,7 @@
     // ',', this is a type-id. Otherwise, it's an expression.
     } else if (Context =3D=3D TypeIdAsTemplateArgument &&
                (Tok.is(tok::greater) || Tok.is(tok::comma) ||
-                (getLang().CPlusPlus0x && Tok.is(tok::greatergreater)))) {
+                (getLangOpts().CPlusPlus0x && Tok.is(tok::greatergreater))=
)) {
       TPR =3D TPResult::True();
       isAmbiguous =3D true;
=20
@@ -361,91 +374,166 @@
   return TPR =3D=3D TPResult::True();
 }
=20
-/// isCXX0XAttributeSpecifier - returns true if this is a C++0x
-/// attribute-specifier. By default, unless in Obj-C++, only a cursory che=
ck is
-/// performed that will simply return true if a [[ is seen. Currently C++ =
has no
-/// syntactical ambiguities from this check, but it may inhibit error reco=
very.
-/// If CheckClosing is true, a check is made for closing ]] brackets.
+/// \brief Returns true if this is a C++11 attribute-specifier. Per
+/// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens
+/// always introduce an attribute. In Objective-C++11, this rule does not
+/// apply if either '[' begins a message-send.
 ///
-/// If given, After is set to the token after the attribute-specifier so t=
hat
-/// appropriate parsing decisions can be made; it is left untouched if fal=
se is
-/// returned.
+/// If Disambiguate is true, we try harder to determine whether a '[[' sta=
rts
+/// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if no=
t.
 ///
-/// FIXME: If an error is in the closing ]] brackets, the program assumes
-/// the absence of an attribute-specifier, which can cause very yucky erro=
rs
-/// to occur.
+/// If OuterMightBeMessageSend is true, we assume the outer '[' is either =
an
+/// Obj-C message send or the start of an attribute. Otherwise, we assume =
it
+/// is not an Obj-C message send.
 ///
-/// [C++0x] attribute-specifier:
+/// C++11 [dcl.attr.grammar]:
+///
+///     attribute-specifier:
 ///         '[' '[' attribute-list ']' ']'
 ///         alignment-specifier
 ///
-/// [C++0x] attribute-list:
+///     attribute-list:
 ///         attribute[opt]
 ///         attribute-list ',' attribute[opt]
+///         attribute '...'
+///         attribute-list ',' attribute '...'
 ///
-/// [C++0x] attribute:
+///     attribute:
 ///         attribute-token attribute-argument-clause[opt]
 ///
-/// [C++0x] attribute-token:
+///     attribute-token:
 ///         identifier
-///         attribute-scoped-token
+///         identifier '::' identifier
 ///
-/// [C++0x] attribute-scoped-token:
-///         attribute-namespace '::' identifier
-///
-/// [C++0x] attribute-namespace:
-///         identifier
-///
-/// [C++0x] attribute-argument-clause:
+///     attribute-argument-clause:
 ///         '(' balanced-token-seq ')'
-///
-/// [C++0x] balanced-token-seq:
-///         balanced-token
-///         balanced-token-seq balanced-token
-///
-/// [C++0x] balanced-token:
-///         '(' balanced-token-seq ')'
-///         '[' balanced-token-seq ']'
-///         '{' balanced-token-seq '}'
-///         any token but '(', ')', '[', ']', '{', or '}'
-bool Parser::isCXX0XAttributeSpecifier (bool CheckClosing,
-                                        tok::TokenKind *After) {
+Parser::CXX11AttributeKind
+Parser::isCXX11AttributeSpecifier(bool Disambiguate,
+                                  bool OuterMightBeMessageSend) {
   if (Tok.is(tok::kw_alignas))
-    return true;
+    return CAK_AttributeSpecifier;
=20
   if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square))
-    return false;
- =20
-  // No tentative parsing if we don't need to look for ]]
-  if (!CheckClosing && !getLang().ObjC1)
-    return true;
- =20
-  struct TentativeReverter {
-    TentativeParsingAction PA;
+    return CAK_NotAttributeSpecifier;
=20
-    TentativeReverter (Parser& P)
-      : PA(P)
-    {}
-    ~TentativeReverter () {
-      PA.Revert();
-    }
-  } R(*this);
+  // No tentative parsing if we don't need to look for ']]' or a lambda.
+  if (!Disambiguate && !getLangOpts().ObjC1)
+    return CAK_AttributeSpecifier;
+
+  TentativeParsingAction PA(*this);
=20
   // Opening brackets were checked for above.
   ConsumeBracket();
+
+  // Outside Obj-C++11, treat anything with a matching ']]' as an attribut=
e.
+  if (!getLangOpts().ObjC1) {
+    ConsumeBracket();
+
+    bool IsAttribute =3D SkipUntil(tok::r_square, false);
+    IsAttribute &=3D Tok.is(tok::r_square);
+
+    PA.Revert();
+
+    return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpec=
ifier;
+  }
+
+  // In Obj-C++11, we need to distinguish four situations:
+  //  1a) int x[[attr]];                     C++11 attribute.
+  //  1b) [[attr]];                          C++11 statement attribute.
+  //   2) int x[[obj](){ return 1; }()];     Lambda in array size/index.
+  //  3a) int x[[obj get]];                  Message send in array size/in=
dex.
+  //  3b) [[Class alloc] init];              Message send in message send.
+  //   4) [[obj]{ return self; }() doStuff]; Lambda in message send.
+  // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted.
+
+  // If we have a lambda-introducer, then this is definitely not a message=
 send.
+  // FIXME: If this disambiguation is too slow, fold the tentative lambda =
parse
+  // into the tentative attribute parse below.
+  LambdaIntroducer Intro;
+  if (!TryParseLambdaIntroducer(Intro)) {
+    // A lambda cannot end with ']]', and an attribute must.
+    bool IsAttribute =3D Tok.is(tok::r_square);
+
+    PA.Revert();
+
+    if (IsAttribute)
+      // Case 1: C++11 attribute.
+      return CAK_AttributeSpecifier;
+
+    if (OuterMightBeMessageSend)
+      // Case 4: Lambda in message send.
+      return CAK_NotAttributeSpecifier;
+
+    // Case 2: Lambda in array size / index.
+    return CAK_InvalidAttributeSpecifier;
+  }
+
   ConsumeBracket();
=20
-  // SkipUntil will handle balanced tokens, which are guaranteed in attrib=
utes.
-  SkipUntil(tok::r_square, false);
+  // If we don't have a lambda-introducer, then we have an attribute or a
+  // message-send.
+  bool IsAttribute =3D true;
+  while (Tok.isNot(tok::r_square)) {
+    if (Tok.is(tok::comma)) {
+      // Case 1: Stray commas can only occur in attributes.
+      PA.Revert();
+      return CAK_AttributeSpecifier;
+    }
=20
-  if (Tok.isNot(tok::r_square))
-    return false;
-  ConsumeBracket();
+    // Parse the attribute-token, if present.
+    // C++11 [dcl.attr.grammar]:
+    //   If a keyword or an alternative token that satisfies the syntactic
+    //   requirements of an identifier is contained in an attribute-token,
+    //   it is considered an identifier.
+    SourceLocation Loc;
+    if (!TryParseCXX11AttributeIdentifier(Loc)) {
+      IsAttribute =3D false;
+      break;
+    }
+    if (Tok.is(tok::coloncolon)) {
+      ConsumeToken();
+      if (!TryParseCXX11AttributeIdentifier(Loc)) {
+        IsAttribute =3D false;
+        break;
+      }
+    }
=20
-  if (After)
-    *After =3D Tok.getKind();
+    // Parse the attribute-argument-clause, if present.
+    if (Tok.is(tok::l_paren)) {
+      ConsumeParen();
+      if (!SkipUntil(tok::r_paren, false)) {
+        IsAttribute =3D false;
+        break;
+      }
+    }
=20
-  return true;
+    if (Tok.is(tok::ellipsis))
+      ConsumeToken();
+
+    if (Tok.isNot(tok::comma))
+      break;
+
+    ConsumeToken();
+  }
+
+  // An attribute must end ']]'.
+  if (IsAttribute) {
+    if (Tok.is(tok::r_square)) {
+      ConsumeBracket();
+      IsAttribute =3D Tok.is(tok::r_square);
+    } else {
+      IsAttribute =3D false;
+    }
+  }
+
+  PA.Revert();
+
+  if (IsAttribute)
+    // Case 1: C++11 statement attribute.
+    return CAK_AttributeSpecifier;
+
+  // Case 3: Message send.
+  return CAK_NotAttributeSpecifier;
 }
=20
 ///         declarator:
@@ -540,7 +628,8 @@
     ConsumeParen();
     if (mayBeAbstract &&
         (Tok.is(tok::r_paren) ||       // 'int()' is a function.
-         Tok.is(tok::ellipsis) ||      // 'int(...)' is a function.
+         // 'int(...)' is a function.
+         (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) ||
          isDeclarationSpecifier())) {   // 'int(int)' is a function.
       // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt]
       //        exception-specification[opt]
@@ -670,11 +759,14 @@
   case tok::kw___is_convertible_to:
   case tok::kw___is_empty:
   case tok::kw___is_enum:
+  case tok::kw___is_final:
   case tok::kw___is_literal:
   case tok::kw___is_literal_type:
   case tok::kw___is_pod:
   case tok::kw___is_polymorphic:
   case tok::kw___is_trivial:
+  case tok::kw___is_trivially_assignable:
+  case tok::kw___is_trivially_constructible:
   case tok::kw___is_trivially_copyable:
   case tok::kw___is_union:
   case tok::kw___uuidof:
@@ -690,6 +782,7 @@
   case tok::kw_int:
   case tok::kw_long:
   case tok::kw___int64:
+  case tok::kw___int128:
   case tok::kw_restrict:
   case tok::kw_short:
   case tok::kw_signed:
@@ -705,7 +798,6 @@
   case tok::kw_wchar_t:
   case tok::kw_char16_t:
   case tok::kw_char32_t:
-  case tok::kw_decltype:
   case tok::kw___underlying_type:
   case tok::kw_thread_local:
   case tok::kw__Decimal32:
@@ -825,7 +917,8 @@
 ///           'volatile'
 /// [GNU]     restrict
 ///
-Parser::TPResult Parser::isCXXDeclarationSpecifier() {
+Parser::TPResult
+Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult) {
   switch (Tok.getKind()) {
   case tok::identifier:   // foo::bar
     // Check for need to substitute AltiVec __vector keyword
@@ -840,21 +933,22 @@
       return TPResult::Error();
     if (Tok.is(tok::identifier))
       return TPResult::False();
-    return isCXXDeclarationSpecifier();
+    return isCXXDeclarationSpecifier(BracedCastResult);
=20
   case tok::coloncolon: {    // ::foo::bar
     const Token &Next =3D NextToken();
     if (Next.is(tok::kw_new) ||    // ::new
         Next.is(tok::kw_delete))   // ::delete
       return TPResult::False();
-
+  }
+    // Fall through.
+  case tok::kw_decltype:
     // Annotate typenames and C++ scope specifiers.  If we get one, just
     // recurse to handle whatever we get.
     if (TryAnnotateTypeOrScopeToken())
       return TPResult::Error();
-    return isCXXDeclarationSpecifier();
-  }
-     =20
+    return isCXXDeclarationSpecifier(BracedCastResult);
+
     // decl-specifier:
     //   storage-class-specifier
     //   type-specifier
@@ -940,8 +1034,31 @@
     // We've already annotated a scope; try to annotate a type.
     if (TryAnnotateTypeOrScopeToken())
       return TPResult::Error();
-    if (!Tok.is(tok::annot_typename))
+    if (!Tok.is(tok::annot_typename)) {
+      // If the next token is an identifier or a type qualifier, then this
+      // can't possibly be a valid expression either.
+      if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) {
+        CXXScopeSpec SS;
+        Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValu=
e(),
+                                                     Tok.getAnnotationRang=
e(),
+                                                     SS);
+        if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) {
+          TentativeParsingAction PA(*this);
+          ConsumeToken();
+          ConsumeToken();
+          bool isIdentifier =3D Tok.is(tok::identifier);
+          TPResult TPR =3D TPResult::False();
+          if (!isIdentifier)
+            TPR =3D isCXXDeclarationSpecifier(BracedCastResult);
+          PA.Revert();
+
+          if (isIdentifier ||
+              TPR =3D=3D TPResult::True() || TPR =3D=3D TPResult::Error())
+            return TPResult::Error();
+        }
+      }
       return TPResult::False();
+    }
     // If that succeeded, fallthrough into the generic simple-type-id case.
=20
     // The ambiguity resides in a simple-type-specifier/typename-specifier
@@ -965,13 +1082,14 @@
   case tok::annot_typename:
   case_typename:
     // In Objective-C, we might have a protocol-qualified type.
-    if (getLang().ObjC1 && NextToken().is(tok::less)) {
+    if (getLangOpts().ObjC1 && NextToken().is(tok::less)) {
       // Tentatively parse the=20
       TentativeParsingAction PA(*this);
       ConsumeToken(); // The type token
      =20
       TPResult TPR =3D TryParseProtocolQualifiers();
       bool isFollowedByParen =3D Tok.is(tok::l_paren);
+      bool isFollowedByBrace =3D Tok.is(tok::l_brace);
      =20
       PA.Revert();
      =20
@@ -980,6 +1098,9 @@
      =20
       if (isFollowedByParen)
         return TPResult::Ambiguous();
+
+      if (getLangOpts().CPlusPlus0x && isFollowedByBrace)
+        return BracedCastResult;
      =20
       return TPResult::True();
     }
@@ -993,15 +1114,26 @@
   case tok::kw_int:
   case tok::kw_long:
   case tok::kw___int64:
+  case tok::kw___int128:
   case tok::kw_signed:
   case tok::kw_unsigned:
   case tok::kw_half:
   case tok::kw_float:
   case tok::kw_double:
   case tok::kw_void:
+  case tok::annot_decltype:
     if (NextToken().is(tok::l_paren))
       return TPResult::Ambiguous();
=20
+    // This is a function-style cast in all cases we disambiguate other th=
an
+    // one:
+    //   struct S {
+    //     enum E : int { a =3D 4 }; // enum
+    //     enum E : int { 4 };     // bit-field
+    //   };
+    if (getLangOpts().CPlusPlus0x && NextToken().is(tok::l_brace))
+      return BracedCastResult;
+
     if (isStartOfObjCClassMessageMissingOpenBracket())
       return TPResult::False();
      =20
@@ -1016,6 +1148,7 @@
=20
     TPResult TPR =3D TryParseTypeofSpecifier();
     bool isFollowedByParen =3D Tok.is(tok::l_paren);
+    bool isFollowedByBrace =3D Tok.is(tok::l_brace);
=20
     PA.Revert();
=20
@@ -1025,18 +1158,17 @@
     if (isFollowedByParen)
       return TPResult::Ambiguous();
=20
+    if (getLangOpts().CPlusPlus0x && isFollowedByBrace)
+      return BracedCastResult;
+
     return TPResult::True();
   }
=20
-  // C++0x decltype support.
-  case tok::kw_decltype:
-    return TPResult::True();
-
   // C++0x type traits support
   case tok::kw___underlying_type:
     return TPResult::True();
=20
-  // C1x _Atomic
+  // C11 _Atomic
   case tok::kw__Atomic:
     return TPResult::True();
=20
@@ -1096,7 +1228,7 @@
   else {
     ConsumeToken();
    =20
-    if (getLang().ObjC1 && Tok.is(tok::less))
+    if (getLangOpts().ObjC1 && Tok.is(tok::less))
       TryParseProtocolQualifiers();
   }
=20
@@ -1160,11 +1292,13 @@
 ///   parameter-declaration-list ',' parameter-declaration
 ///
 /// parameter-declaration:
-///   decl-specifier-seq declarator attributes[opt]
-///   decl-specifier-seq declarator attributes[opt] '=3D' assignment-expre=
ssion
-///   decl-specifier-seq abstract-declarator[opt] attributes[opt]
-///   decl-specifier-seq abstract-declarator[opt] attributes[opt]
+///   attribute-specifier-seq[opt] decl-specifier-seq declarator attribute=
s[opt]
+///   attribute-specifier-seq[opt] decl-specifier-seq declarator attribute=
s[opt]
 ///     '=3D' assignment-expression
+///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[=
opt]
+///     attributes[opt]
+///   attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[=
opt]
+///     attributes[opt] '=3D' assignment-expression
 ///
 Parser::TPResult Parser::TryParseParameterDeclarationClause() {
=20
@@ -1182,13 +1316,23 @@
     // '...'[opt]
     if (Tok.is(tok::ellipsis)) {
       ConsumeToken();
-      return TPResult::True(); // '...' is a sign of a function declarator.
+      if (Tok.is(tok::r_paren))
+        return TPResult::True(); // '...)' is a sign of a function declara=
tor.
+      else
+        return TPResult::False();
     }
=20
+    // An attribute-specifier-seq here is a sign of a function declarator.
+    if (isCXX11AttributeSpecifier(/*Disambiguate*/false,
+                                  /*OuterMightBeMessageSend*/true))
+      return TPResult::True();
+
     ParsedAttributes attrs(AttrFactory);
     MaybeParseMicrosoftAttributes(attrs);
=20
     // decl-specifier-seq
+    // A parameter-declaration's initializer must be preceded by an '=3D',=
 so
+    // decl-specifier-seq '{' is not a parameter in C++11.
     TPResult TPR =3D TryParseDeclarationSpecifier();
     if (TPR !=3D TPResult::Ambiguous())
       return TPR;
@@ -1206,14 +1350,17 @@
     if (Tok.is(tok::equal)) {
       // '=3D' assignment-expression
       // Parse through assignment-expression.
-      tok::TokenKind StopToks[2] =3D{ tok::comma, tok::r_paren };
-      if (!SkipUntil(StopToks, 2, true/*StopAtSemi*/, true/*DontConsume*/))
+      if (!SkipUntil(tok::comma, tok::r_paren, true/*StopAtSemi*/,
+                     true/*DontConsume*/))
         return TPResult::Error();
     }
=20
     if (Tok.is(tok::ellipsis)) {
       ConsumeToken();
-      return TPResult::True(); // '...' is a sign of a function declarator.
+      if (Tok.is(tok::r_paren))
+        return TPResult::True(); // '...)' is a sign of a function declara=
tor.
+      else
+        return TPResult::False();
     }
=20
     if (Tok.isNot(tok::comma))
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Pars=
e/Parser.cpp
--- a/head/contrib/llvm/tools/clang/lib/Parse/Parser.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Parse/Parser.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -23,15 +23,24 @@
 #include "clang/AST/ASTConsumer.h"
 using namespace clang;
=20
-Parser::Parser(Preprocessor &pp, Sema &actions)
+IdentifierInfo *Parser::getSEHExceptKeyword() {
+  // __except is accepted as a (contextual) keyword=20
+  if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borla=
nd))
+    Ident__except =3D PP.getIdentifierInfo("__except");
+
+  return Ident__except;
+}
+
+Parser::Parser(Preprocessor &pp, Sema &actions, bool SkipFunctionBodies)
   : PP(pp), Actions(actions), Diags(PP.getDiagnostics()),
     GreaterThanIsOperator(true), ColonIsSacred(false),=20
-    InMessageExpression(false), TemplateParameterDepth(0) {
+    InMessageExpression(false), TemplateParameterDepth(0),
+    SkipFunctionBodies(SkipFunctionBodies) {
   Tok.setKind(tok::eof);
   Actions.CurScope =3D 0;
   NumCachedScopes =3D 0;
   ParenCount =3D BracketCount =3D BraceCount =3D 0;
-  ObjCImpDecl =3D 0;
+  CurParsedObjCImpl =3D 0;
=20
   // Add #pragma handlers. These are removed and destroyed in the
   // destructor.
@@ -56,10 +65,13 @@
   WeakHandler.reset(new PragmaWeakHandler(actions));
   PP.AddPragmaHandler(WeakHandler.get());
=20
+  RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler(actions));
+  PP.AddPragmaHandler(RedefineExtnameHandler.get());
+
   FPContractHandler.reset(new PragmaFPContractHandler(actions, *this));
   PP.AddPragmaHandler("STDC", FPContractHandler.get());
=20
-  if (getLang().OpenCL) {
+  if (getLangOpts().OpenCL) {
     OpenCLExtensionHandler.reset(
                   new PragmaOpenCLExtensionHandler(actions, *this));
     PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
@@ -202,15 +214,14 @@
 ///
 /// If SkipUntil finds the specified token, it returns true, otherwise it
 /// returns false.
-bool Parser::SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
-                       bool StopAtSemi, bool DontConsume,
-                       bool StopAtCodeCompletion) {
+bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi,
+                       bool DontConsume, bool StopAtCodeCompletion) {
   // We always want this function to skip at least one token if the first =
token
   // isn't T and if not at EOF.
   bool isFirstTokenSkipped =3D true;
   while (1) {
     // If we found one of the tokens, stop and return true.
-    for (unsigned i =3D 0; i !=3D NumToks; ++i) {
+    for (unsigned i =3D 0, NumToks =3D Toks.size(); i !=3D NumToks; ++i) {
       if (Tok.is(Toks[i])) {
         if (DontConsume) {
           // Noop, don't consume the token.
@@ -276,9 +287,6 @@
       ConsumeStringToken();
       break;
        =20
-    case tok::at:
-      return false;
-     =20
     case tok::semi:
       if (StopAtSemi)
         return false;
@@ -377,8 +385,10 @@
   UnusedHandler.reset();
   PP.RemovePragmaHandler(WeakHandler.get());
   WeakHandler.reset();
+  PP.RemovePragmaHandler(RedefineExtnameHandler.get());
+  RedefineExtnameHandler.reset();
=20
-  if (getLang().OpenCL) {
+  if (getLangOpts().OpenCL) {
     PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
     OpenCLExtensionHandler.reset();
     PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
@@ -401,12 +411,12 @@
   ConsumeToken();
=20
   if (Tok.is(tok::eof) &&
-      !getLang().CPlusPlus)  // Empty source file is an extension in C
+      !getLangOpts().CPlusPlus)  // Empty source file is an extension in C
     Diag(Tok, diag::ext_empty_source_file);
=20
   // Initialization for Objective-C context sensitive keywords recognition.
   // Referenced in Parser::ParseObjCTypeQualifierList.
-  if (getLang().ObjC1) {
+  if (getLangOpts().ObjC1) {
     ObjCTypeQuals[objc_in] =3D &PP.getIdentifierTable().get("in");
     ObjCTypeQuals[objc_out] =3D &PP.getIdentifierTable().get("out");
     ObjCTypeQuals[objc_inout] =3D &PP.getIdentifierTable().get("inout");
@@ -421,7 +431,7 @@
=20
   Ident_super =3D &PP.getIdentifierTable().get("super");
=20
-  if (getLang().AltiVec) {
+  if (getLangOpts().AltiVec) {
     Ident_vector =3D &PP.getIdentifierTable().get("vector");
     Ident_pixel =3D &PP.getIdentifierTable().get("pixel");
   }
@@ -431,11 +441,13 @@
   Ident_obsoleted =3D 0;
   Ident_unavailable =3D 0;
=20
+  Ident__except =3D 0;
+ =20
   Ident__exception_code =3D Ident__exception_info =3D Ident__abnormal_term=
ination =3D 0;
   Ident___exception_code =3D Ident___exception_info =3D Ident___abnormal_t=
ermination =3D 0;
   Ident_GetExceptionCode =3D Ident_GetExceptionInfo =3D Ident_AbnormalTerm=
ination =3D 0;
=20
-  if(getLang().Borland) {
+  if(getLangOpts().Borland) {
     Ident__exception_info        =3D PP.getIdentifierInfo("_exception_info=
");
     Ident___exception_info       =3D PP.getIdentifierInfo("__exception_inf=
o");
     Ident_GetExceptionInfo       =3D PP.getIdentifierInfo("GetExceptionInf=
ormation");
@@ -463,23 +475,30 @@
 bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) {
   DelayedCleanupPoint CleanupRAII(TopLevelDeclCleanupPool);
=20
+  // Skip over the EOF token, flagging end of previous input for increment=
al=20
+  // processing
+  if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof))
+    ConsumeToken();
+
   while (Tok.is(tok::annot_pragma_unused))
     HandlePragmaUnused();
=20
   Result =3D DeclGroupPtrTy();
   if (Tok.is(tok::eof)) {
     // Late template parsing can begin.
-    if (getLang().DelayedTemplateParsing)
+    if (getLangOpts().DelayedTemplateParsing)
       Actions.SetLateTemplateParser(LateTemplateParserCallback, this);
+    if (!PP.isIncrementalProcessingEnabled())
+      Actions.ActOnEndOfTranslationUnit();
+    //else don't tell Sema that we ended parsing: more input might come.
=20
-    Actions.ActOnEndOfTranslationUnit();
     return true;
   }
=20
   ParsedAttributesWithRange attrs(AttrFactory);
   MaybeParseCXX0XAttributes(attrs);
   MaybeParseMicrosoftAttributes(attrs);
- =20
+
   Result =3D ParseExternalDeclaration(attrs);
   return false;
 }
@@ -534,16 +553,22 @@
=20
   Decl *SingleDecl =3D 0;
   switch (Tok.getKind()) {
+  case tok::annot_pragma_vis:
+    HandlePragmaVisibility();
+    return DeclGroupPtrTy();
+  case tok::annot_pragma_pack:
+    HandlePragmaPack();
+    return DeclGroupPtrTy();
   case tok::semi:
-    if (!getLang().CPlusPlus0x)
-      Diag(Tok, diag::ext_top_level_semi)
-        << FixItHint::CreateRemoval(Tok.getLocation());
+    Diag(Tok, getLangOpts().CPlusPlus0x ?
+         diag::warn_cxx98_compat_top_level_semi : diag::ext_top_level_semi)
+      << FixItHint::CreateRemoval(Tok.getLocation());
=20
     ConsumeToken();
     // TODO: Invoke action for top-level semicolon.
     return DeclGroupPtrTy();
   case tok::r_brace:
-    Diag(Tok, diag::err_expected_external_declaration);
+    Diag(Tok, diag::err_extraneous_closing_brace);
     ConsumeBrace();
     return DeclGroupPtrTy();
   case tok::eof:
@@ -572,10 +597,9 @@
   }
   case tok::at:
     return ParseObjCAtDirectives();
-    break;
   case tok::minus:
   case tok::plus:
-    if (!getLang().ObjC1) {
+    if (!getLangOpts().ObjC1) {
       Diag(Tok, diag::err_expected_external_declaration);
       ConsumeToken();
       return DeclGroupPtrTy();
@@ -584,7 +608,7 @@
     break;
   case tok::code_completion:
       Actions.CodeCompleteOrdinaryName(getCurScope(),=20
-                                   ObjCImpDecl? Sema::PCC_ObjCImplementati=
on
+                             CurParsedObjCImpl? Sema::PCC_ObjCImplementati=
on
                                               : Sema::PCC_Namespace);
     cutOffParsing();
     return DeclGroupPtrTy();
@@ -605,7 +629,7 @@
   case tok::kw_static:
     // Parse (then ignore) 'static' prior to a template instantiation. Thi=
s is
     // a GCC extension that we intentionally do not support.
-    if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
+    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
       Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored)
         << 0;
       SourceLocation DeclEnd;
@@ -615,7 +639,7 @@
     goto dont_know;
      =20
   case tok::kw_inline:
-    if (getLang().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       tok::TokenKind NextKind =3D NextToken().getKind();
      =20
       // Inline namespaces. Allowed as an extension even in C++03.
@@ -638,13 +662,17 @@
     goto dont_know;
=20
   case tok::kw_extern:
-    if (getLang().CPlusPlus && NextToken().is(tok::kw_template)) {
+    if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) {
       // Extern templates
       SourceLocation ExternLoc =3D ConsumeToken();
       SourceLocation TemplateLoc =3D ConsumeToken();
+      Diag(ExternLoc, getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_extern_template :
+             diag::ext_extern_template) << SourceRange(ExternLoc, Template=
Loc);
       SourceLocation DeclEnd;
       return Actions.ConvertDeclToDeclGroup(
-                  ParseExplicitInstantiation(ExternLoc, TemplateLoc, DeclE=
nd));
+                  ParseExplicitInstantiation(Declarator::FileContext,
+                                             ExternLoc, TemplateLoc, DeclE=
nd));
     }
     // FIXME: Detect C++ linkage specifications here?
     goto dont_know;
@@ -653,9 +681,6 @@
   case tok::kw___if_not_exists:
     ParseMicrosoftIfExistsExternalDeclaration();
     return DeclGroupPtrTy();
-
-  case tok::kw___import_module__:
-    return ParseModuleImport();
      =20
   default:
   dont_know:
@@ -677,7 +702,7 @@
 /// declarator, continues a declaration or declaration list.
 bool Parser::isDeclarationAfterDeclarator() {
   // Check for '=3D delete' or '=3D default'
-  if (getLang().CPlusPlus && Tok.is(tok::equal)) {
+  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
     const Token &KW =3D NextToken();
     if (KW.is(tok::kw_default) || KW.is(tok::kw_delete))
       return false;
@@ -688,7 +713,7 @@
     Tok.is(tok::semi)  ||           // int X();  -> not a function def
     Tok.is(tok::kw_asm) ||          // int X() __asm__ -> not a function d=
ef
     Tok.is(tok::kw___attribute) ||  // int X() __attr__ -> not a function =
def
-    (getLang().CPlusPlus &&
+    (getLangOpts().CPlusPlus &&
      Tok.is(tok::l_paren));         // int X(0) -> not a function def [C++]
 }
=20
@@ -700,11 +725,11 @@
     return true;
  =20
   // Handle K&R C argument lists: int X(f) int f; {}
-  if (!getLang().CPlusPlus &&
+  if (!getLangOpts().CPlusPlus &&
       Declarator.getFunctionTypeInfo().isKNRPrototype())=20
     return isDeclarationSpecifier();
=20
-  if (getLang().CPlusPlus && Tok.is(tok::equal)) {
+  if (getLangOpts().CPlusPlus && Tok.is(tok::equal)) {
     const Token &KW =3D NextToken();
     return KW.is(tok::kw_default) || KW.is(tok::kw_delete);
   }
@@ -747,7 +772,7 @@
   // ObjC2 allows prefix attributes on class interfaces and protocols.
   // FIXME: This still needs better diagnostics. We should only accept
   // attributes here, no types, etc.
-  if (getLang().ObjC2 && Tok.is(tok::at)) {
+  if (getLangOpts().ObjC2 && Tok.is(tok::at)) {
     SourceLocation AtLoc =3D ConsumeToken(); // the "@"
     if (!Tok.isObjCAtKeyword(tok::objc_interface) &&
         !Tok.isObjCAtKeyword(tok::objc_protocol)) {
@@ -763,18 +788,17 @@
     if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, Dia=
gID))
       Diag(AtLoc, DiagID) << PrevSpec;
=20
-    Decl *TheDecl =3D 0;
     if (Tok.isObjCAtKeyword(tok::objc_protocol))
-      TheDecl =3D ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()=
);
-    else
-      TheDecl =3D ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes(=
));
-    return Actions.ConvertDeclToDeclGroup(TheDecl);
+      return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes());
+
+    return Actions.ConvertDeclToDeclGroup(
+            ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes()));
   }
=20
   // If the declspec consisted only of 'extern' and we have a string
   // literal following it, this must be a C++ linkage specifier like
   // 'extern "C"'.
-  if (Tok.is(tok::string_literal) && getLang().CPlusPlus &&
+  if (Tok.is(tok::string_literal) && getLangOpts().CPlusPlus &&
       DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_extern &&
       DS.getParsedSpecifiers() =3D=3D DeclSpec::PQ_StorageClassSpecifier) {
     Decl *TheDecl =3D ParseLinkage(DS, Declarator::FileContext);
@@ -812,7 +836,8 @@
 ///         decl-specifier-seq[opt] declarator function-try-block
 ///
 Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D,
-                                      const ParsedTemplateInfo &TemplateIn=
fo) {
+                                      const ParsedTemplateInfo &TemplateIn=
fo,
+                                      LateParsedAttrList *LateParsedAttrs)=
 {
   // Poison the SEH identifiers so they are flagged as illegal in function=
 bodies
   PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
   const DeclaratorChunk::FunctionTypeInfo &FTI =3D D.getFunctionTypeInfo();
@@ -820,7 +845,7 @@
   // If this is C90 and the declspecs were completely missing, fudge in an
   // implicit int.  We do this here because this is the only place where
   // declaration-specifiers are completely optional in the grammar.
-  if (getLang().ImplicitInt && D.getDeclSpec().isEmpty()) {
+  if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) {
     const char *PrevSpec;
     unsigned DiagID;
     D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int,
@@ -835,11 +860,10 @@
   if (FTI.isKNRPrototype())
     ParseKNRParamDeclarations(D);
=20
-
   // We should have either an opening brace or, in a C++ constructor,
   // we may have a colon.
   if (Tok.isNot(tok::l_brace) &&=20
-      (!getLang().CPlusPlus ||
+      (!getLangOpts().CPlusPlus ||
        (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) &&
         Tok.isNot(tok::equal)))) {
     Diag(Tok, diag::err_expected_fn_body);
@@ -852,9 +876,22 @@
       return 0;
   }
=20
+  // Check to make sure that any normal attributes are allowed to be on
+  // a definition.  Late parsed attributes are checked at the end.
+  if (Tok.isNot(tok::equal)) {
+    AttributeList *DtorAttrs =3D D.getAttributes();
+    while (DtorAttrs) {
+      if (!IsThreadSafetyAttribute(DtorAttrs->getName()->getName())) {
+        Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definit=
ion)
+          << DtorAttrs->getName()->getName();
+      }
+      DtorAttrs =3D DtorAttrs->getNext();
+    }
+  }
+
   // In delayed template parsing mode, for function template we consume the
   // tokens and store them for late parsing at the end of the translation =
unit.
-  if (getLang().DelayedTemplateParsing &&
+  if (getLangOpts().DelayedTemplateParsing &&
       TemplateInfo.Kind =3D=3D ParsedTemplateInfo::Template) {
     MultiTemplateParamsArg TemplateParameterLists(Actions,
                                          TemplateInfo.TemplateParams->data=
(),
@@ -863,14 +900,14 @@
     ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope);
     Scope *ParentScope =3D getCurScope()->getParent();
=20
-    D.setFunctionDefinition(true);
+    D.setFunctionDefinitionKind(FDK_Definition);
     Decl *DP =3D Actions.HandleDeclarator(ParentScope, D,
                                         move(TemplateParameterLists));
     D.complete(DP);
     D.getMutableDeclSpec().abort();
=20
     if (DP) {
-      LateParsedTemplatedFunction *LPT =3D new LateParsedTemplatedFunction=
(this, DP);
+      LateParsedTemplatedFunction *LPT =3D new LateParsedTemplatedFunction=
(DP);
=20
       FunctionDecl *FnD =3D 0;
       if (FunctionTemplateDecl *FunTmpl =3D dyn_cast<FunctionTemplateDecl>=
(DP))
@@ -910,7 +947,7 @@
   D.getMutableDeclSpec().abort();
=20
   if (Tok.is(tok::equal)) {
-    assert(getLang().CPlusPlus && "Only C++ function definitions have '=3D=
'");
+    assert(getLangOpts().CPlusPlus && "Only C++ function definitions have =
'=3D'");
     ConsumeToken();
=20
     Actions.ActOnFinishFunctionBody(Res, 0, false);
@@ -918,15 +955,17 @@
     bool Delete =3D false;
     SourceLocation KWLoc;
     if (Tok.is(tok::kw_delete)) {
-      if (!getLang().CPlusPlus0x)
-        Diag(Tok, diag::warn_deleted_function_accepted_as_extension);
+      Diag(Tok, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_deleted_function :
+           diag::ext_deleted_function);
=20
       KWLoc =3D ConsumeToken();
       Actions.SetDeclDeleted(Res, KWLoc);
       Delete =3D true;
     } else if (Tok.is(tok::kw_default)) {
-      if (!getLang().CPlusPlus0x)
-        Diag(Tok, diag::warn_defaulted_function_accepted_as_extension);
+      Diag(Tok, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_defaulted_function :
+           diag::ext_defaulted_function);
=20
       KWLoc =3D ConsumeToken();
       Actions.SetDeclDefaulted(Res, KWLoc);
@@ -963,6 +1002,10 @@
   } else
     Actions.ActOnDefaultCtorInitializers(Res);
=20
+  // Late attributes are parsed in the same scope as the function body.
+  if (LateParsedAttrs)
+    ParseLexedAttributeList(*LateParsedAttrs, Res, false, true);
+
   return ParseFunctionStatementBody(Res, BodyScope);
 }
=20
@@ -1056,18 +1099,19 @@
       if (Tok.isNot(tok::comma))
         break;
=20
+      ParmDeclarator.clear();
+
       // Consume the comma.
-      ConsumeToken();
+      ParmDeclarator.setCommaLoc(ConsumeToken());
=20
       // Parse the next declarator.
-      ParmDeclarator.clear();
       ParseDeclarator(ParmDeclarator);
     }
=20
     if (Tok.is(tok::semi)) {
       ConsumeToken();
     } else {
-      Diag(Tok, diag::err_parse_error);
+      Diag(Tok, diag::err_expected_semi_declaration);
       // Skip to end of block or statement
       SkipUntil(tok::semi, true);
       if (Tok.is(tok::semi))
@@ -1087,17 +1131,25 @@
 ///         string-literal
 ///
 Parser::ExprResult Parser::ParseAsmStringLiteral() {
-  if (!isTokenStringLiteral()) {
-    Diag(Tok, diag::err_expected_string_literal);
-    return ExprError();
+  switch (Tok.getKind()) {
+    case tok::string_literal:
+      break;
+    case tok::utf8_string_literal:
+    case tok::utf16_string_literal:
+    case tok::utf32_string_literal:
+    case tok::wide_string_literal: {
+      SourceLocation L =3D Tok.getLocation();
+      Diag(Tok, diag::err_asm_operand_wide_string_literal)
+        << (Tok.getKind() =3D=3D tok::wide_string_literal)
+        << SourceRange(L, L);
+      return ExprError();
+    }
+    default:
+      Diag(Tok, diag::err_expected_string_literal);
+      return ExprError();
   }
=20
-  ExprResult Res(ParseStringLiteralExpression());
-  if (Res.isInvalid()) return move(Res);
-
-  // TODO: Diagnose: wide string literal in 'asm'
-
-  return move(Res);
+  return ParseStringLiteralExpression();
 }
=20
 /// ParseSimpleAsm
@@ -1178,8 +1230,8 @@
 /// as the current tokens, so only call it in contexts where these are inv=
alid.
 bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedTy=
pe) {
   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon)
-          || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)) &&
-         "Cannot be a type or scope token!");
+          || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope)
+          || Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token=
!");
=20
   if (Tok.is(tok::kw_typename)) {
     // Parse a C++ typename-specifier, e.g., "typename T::type".
@@ -1190,11 +1242,12 @@
     //            simple-template-id
     SourceLocation TypenameLoc =3D ConsumeToken();
     CXXScopeSpec SS;
-    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=3D*/ParsedType(), =
false,
+    if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=3D*/ParsedType(),=20
+                                       /*EnteringContext=3D*/false,
                                        0, /*IsTypename*/true))
       return true;
     if (!SS.isSet()) {
-      if (getLang().MicrosoftExt)
+      if (getLangOpts().MicrosoftExt)
         Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typena=
me);
       else
         Diag(Tok.getLocation(), diag::err_expected_qualified_after_typenam=
e);
@@ -1218,13 +1271,13 @@
       ASTTemplateArgsPtr TemplateArgsPtr(Actions,
                                          TemplateId->getTemplateArgs(),
                                          TemplateId->NumArgs);
-     =20
+
       Ty =3D Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS,
-                                     /*FIXME:*/SourceLocation(),
+                                     TemplateId->TemplateKWLoc,
                                      TemplateId->Template,
                                      TemplateId->TemplateNameLoc,
                                      TemplateId->LAngleLoc,
-                                     TemplateArgsPtr,=20
+                                     TemplateArgsPtr,
                                      TemplateId->RAngleLoc);
     } else {
       Diag(Tok, diag::err_expected_type_name_after_typename)
@@ -1245,7 +1298,7 @@
   bool wasScopeAnnotation =3D Tok.is(tok::annot_cxxscope);
=20
   CXXScopeSpec SS;
-  if (getLang().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
       return true;
=20
@@ -1257,6 +1310,7 @@
                                             &SS, false,=20
                                             NextToken().is(tok::period),
                                             ParsedType(),
+                                            /*IsCtorOrDtorName=3D*/false,
                                             /*NonTrivialTypeSourceInfo*/tr=
ue,
                                             NeedType ? &CorrectedII : NULL=
)) {
       // A FixIt was applied as a result of typo correction
@@ -1276,7 +1330,7 @@
       return false;
     }
=20
-    if (!getLang().CPlusPlus) {
+    if (!getLangOpts().CPlusPlus) {
       // If we're in C, we can't have :: tokens at all (the lexer won't re=
turn
       // them).  If the identifier is not a type, then it can't be scope e=
ither,
       // just early exit.
@@ -1297,7 +1351,8 @@
                                    Template, MemberOfUnknownSpecialization=
)) {
         // Consume the identifier.
         ConsumeToken();
-        if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateName)) {
+        if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
+                                    TemplateName)) {
           // If an unrecoverable error occurred, we need to return true he=
re,
           // because the token stream is in a damaged state.  We may not r=
eturn
           // a valid identifier.
@@ -1354,11 +1409,11 @@
 /// Note that this routine emits an error if you call it with ::new or ::d=
elete
 /// as the current tokens, so only call it in contexts where these are inv=
alid.
 bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) {
-  assert(getLang().CPlusPlus &&
+  assert(getLangOpts().CPlusPlus &&
          "Call sites of this function should be guarded by checking for C+=
+");
   assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) ||
-          (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolo=
n)))&&
-         "Cannot be a type or scope token!");
+          (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolo=
n)) ||
+         Tok.is(tok::kw_decltype)) && "Cannot be a type or scope token!");
=20
   CXXScopeSpec SS;
   if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext))
@@ -1382,18 +1437,31 @@
   return false;
 }
=20
-bool Parser::isTokenEqualOrMistypedEqualEqual(unsigned DiagID) {
-  if (Tok.is(tok::equalequal)) {
-    // We have '=3D=3D' in a context that we would expect a '=3D'.
-    // The user probably made a typo, intending to type '=3D'. Emit diagno=
stic,
-    // fixit hint to turn '=3D=3D' -> '=3D' and continue as if the user ty=
ped '=3D'.
-    Diag(Tok, DiagID)
-      << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
-                                      getTokenSimpleSpelling(tok::equal));
+bool Parser::isTokenEqualOrEqualTypo() {
+  tok::TokenKind Kind =3D Tok.getKind();
+  switch (Kind) {
+  default:
+    return false;
+  case tok::ampequal:            // &=3D
+  case tok::starequal:           // *=3D
+  case tok::plusequal:           // +=3D
+  case tok::minusequal:          // -=3D
+  case tok::exclaimequal:        // !=3D
+  case tok::slashequal:          // /=3D
+  case tok::percentequal:        // %=3D
+  case tok::lessequal:           // <=3D
+  case tok::lesslessequal:       // <<=3D
+  case tok::greaterequal:        // >=3D
+  case tok::greatergreaterequal: // >>=3D
+  case tok::caretequal:          // ^=3D
+  case tok::pipeequal:           // |=3D
+  case tok::equalequal:          // =3D=3D
+    Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal)
+      << getTokenSimpleSpelling(Kind)
+      << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "=3D=
");
+  case tok::equal:
     return true;
   }
-
-  return Tok.is(tok::equal);
 }
=20
 SourceLocation Parser::handleUnexpectedCodeCompletionToken() {
@@ -1455,98 +1523,134 @@
   Actions.CodeCompleteNaturalLanguage();
 }
=20
-bool Parser::ParseMicrosoftIfExistsCondition(bool& Result) {
+bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) {
   assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) =
&&
          "Expected '__if_exists' or '__if_not_exists'");
-  Token Condition =3D Tok;
-  SourceLocation IfExistsLoc =3D ConsumeToken();
+  Result.IsIfExists =3D Tok.is(tok::kw___if_exists);
+  Result.KeywordLoc =3D ConsumeToken();
=20
   BalancedDelimiterTracker T(*this, tok::l_paren);
   if (T.consumeOpen()) {
-    Diag(Tok, diag::err_expected_lparen_after) << IfExistsLoc;
-    SkipUntil(tok::semi);
+    Diag(Tok, diag::err_expected_lparen_after)=20
+      << (Result.IsIfExists? "__if_exists" : "__if_not_exists");
     return true;
   }
  =20
   // Parse nested-name-specifier.
-  CXXScopeSpec SS;
-  ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false);
+  ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(),=20
+                                 /*EnteringContext=3D*/false);
=20
   // Check nested-name specifier.
-  if (SS.isInvalid()) {
-    SkipUntil(tok::semi);
+  if (Result.SS.isInvalid()) {
+    T.skipToEnd();
     return true;
   }
=20
-  // Parse the unqualified-id.=20
-  UnqualifiedId Name;
-  if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), Name)) {
-    SkipUntil(tok::semi);
+  // Parse the unqualified-id.
+  SourceLocation TemplateKWLoc; // FIXME: parsed, but unused.
+  if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(),
+                         TemplateKWLoc, Result.Name)) {
+    T.skipToEnd();
     return true;
   }
=20
-  T.consumeClose();
-  if (T.getCloseLocation().isInvalid())
+  if (T.consumeClose())
     return true;
+ =20
+  // Check if the symbol exists.
+  switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.Keywo=
rdLoc,
+                                               Result.IsIfExists, Result.S=
S,=20
+                                               Result.Name)) {
+  case Sema::IER_Exists:
+    Result.Behavior =3D Result.IsIfExists ? IEB_Parse : IEB_Skip;
+    break;
=20
-  // Check if the symbol exists.
-  bool Exist =3D Actions.CheckMicrosoftIfExistsSymbol(SS, Name);
+  case Sema::IER_DoesNotExist:
+    Result.Behavior =3D !Result.IsIfExists ? IEB_Parse : IEB_Skip;
+    break;
=20
-  Result =3D ((Condition.is(tok::kw___if_exists) && Exist) ||
-            (Condition.is(tok::kw___if_not_exists) && !Exist));
+  case Sema::IER_Dependent:
+    Result.Behavior =3D IEB_Dependent;
+    break;
+     =20
+  case Sema::IER_Error:
+    return true;
+  }
=20
   return false;
 }
=20
 void Parser::ParseMicrosoftIfExistsExternalDeclaration() {
-  bool Result;
+  IfExistsCondition Result;
   if (ParseMicrosoftIfExistsCondition(Result))
     return;
  =20
-  if (Tok.isNot(tok::l_brace)) {
+  BalancedDelimiterTracker Braces(*this, tok::l_brace);
+  if (Braces.consumeOpen()) {
     Diag(Tok, diag::err_expected_lbrace);
     return;
   }
-  ConsumeBrace();
=20
-  // Condition is false skip all inside the {}.
-  if (!Result) {
-    SkipUntil(tok::r_brace, false);
+  switch (Result.Behavior) {
+  case IEB_Parse:
+    // Parse declarations below.
+    break;
+     =20
+  case IEB_Dependent:
+    llvm_unreachable("Cannot have a dependent external declaration");
+     =20
+  case IEB_Skip:
+    Braces.skipToEnd();
     return;
   }
=20
-  // Condition is true, parse the declaration.
-  while (Tok.isNot(tok::r_brace)) {
+  // Parse the declarations.
+  while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
     ParsedAttributesWithRange attrs(AttrFactory);
     MaybeParseCXX0XAttributes(attrs);
     MaybeParseMicrosoftAttributes(attrs);
     DeclGroupPtrTy Result =3D ParseExternalDeclaration(attrs);
     if (Result && !getCurScope()->getParent())
       Actions.getASTConsumer().HandleTopLevelDecl(Result.get());
-  }
-
-  if (Tok.isNot(tok::r_brace)) {
-    Diag(Tok, diag::err_expected_rbrace);
-    return;
-  }
-  ConsumeBrace();
+  }    =20
+  Braces.consumeClose();
 }
=20
-Parser::DeclGroupPtrTy Parser::ParseModuleImport() {
-  assert(Tok.is(tok::kw___import_module__) &&=20
+Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) {
+  assert(Tok.isObjCAtKeyword(tok::objc___experimental_modules_import) &&=20
          "Improper start to module import");
   SourceLocation ImportLoc =3D ConsumeToken();
  =20
-  // Parse the module name.
-  if (!Tok.is(tok::identifier)) {
-    Diag(Tok, diag::err_module_expected_ident);
-    SkipUntil(tok::semi);
-    return DeclGroupPtrTy();
-  }
+  llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  =20
-  IdentifierInfo &ModuleName =3D *Tok.getIdentifierInfo();
-  SourceLocation ModuleNameLoc =3D ConsumeToken();
-  DeclResult Import =3D Actions.ActOnModuleImport(ImportLoc, ModuleName, M=
oduleNameLoc);
+  // Parse the module path.
+  do {
+    if (!Tok.is(tok::identifier)) {
+      if (Tok.is(tok::code_completion)) {
+        Actions.CodeCompleteModuleImport(ImportLoc, Path);
+        ConsumeCodeCompletionToken();
+        SkipUntil(tok::semi);
+        return DeclGroupPtrTy();
+      }
+     =20
+      Diag(Tok, diag::err_module_expected_ident);
+      SkipUntil(tok::semi);
+      return DeclGroupPtrTy();
+    }
+   =20
+    // Record this part of the module path.
+    Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation=
()));
+    ConsumeToken();
+   =20
+    if (Tok.is(tok::period)) {
+      ConsumeToken();
+      continue;
+    }
+   =20
+    break;
+  } while (true);
+ =20
+  DeclResult Import =3D Actions.ActOnModuleImport(AtLoc, ImportLoc, Path);
   ExpectAndConsumeSemi(diag::err_module_expected_semi);
   if (Import.isInvalid())
     return DeclGroupPtrTy();
@@ -1554,63 +1658,43 @@
   return Actions.ConvertDeclToDeclGroup(Import.get());
 }
=20
-bool Parser::BalancedDelimiterTracker::consumeOpen() {
-  // Try to consume the token we are holding
-  if (P.Tok.is(Kind)) {
-    P.QuantityTracker.push(Kind);
-    Cleanup =3D true;
-    if (P.QuantityTracker.getDepth(Kind) < MaxDepth) {
-      LOpen =3D P.ConsumeAnyToken();
-      return false;
-    } else {
-      P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
-      P.SkipUntil(tok::eof);
-    }
-  }
-  return true;
+bool Parser::BalancedDelimiterTracker::diagnoseOverflow() {
+  P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
+  P.SkipUntil(tok::eof);
+  return true; =20
 }
=20
 bool Parser::BalancedDelimiterTracker::expectAndConsume(unsigned DiagID,=20
                                             const char *Msg,
                                             tok::TokenKind SkipToToc ) {
   LOpen =3D P.Tok.getLocation();
-  if (!P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc)) {
-    P.QuantityTracker.push(Kind);
-    Cleanup =3D true;
-    if (P.QuantityTracker.getDepth(Kind) < MaxDepth) {
-      return false;
-    } else {
-      P.Diag(P.Tok, diag::err_parser_impl_limit_overflow);
-      P.SkipUntil(tok::eof);
-    }
+  if (P.ExpectAndConsume(Kind, DiagID, Msg, SkipToToc))
+    return true;
+ =20
+  if (getDepth() < MaxDepth)
+    return false;
+   =20
+  return diagnoseOverflow();
+}
+
+bool Parser::BalancedDelimiterTracker::diagnoseMissingClose() {
+  assert(!P.Tok.is(Close) && "Should have consumed closing delimiter");
+ =20
+  const char *LHSName =3D "unknown";
+  diag::kind DID;
+  switch (Close) {
+  default: llvm_unreachable("Unexpected balanced token");
+  case tok::r_paren : LHSName =3D "("; DID =3D diag::err_expected_rparen; =
break;
+  case tok::r_brace : LHSName =3D "{"; DID =3D diag::err_expected_rbrace; =
break;
+  case tok::r_square: LHSName =3D "["; DID =3D diag::err_expected_rsquare;=
 break;
   }
+  P.Diag(P.Tok, DID);
+  P.Diag(LOpen, diag::note_matching) << LHSName;
+  if (P.SkipUntil(Close))
+    LClose =3D P.Tok.getLocation();
   return true;
 }
=20
-bool Parser::BalancedDelimiterTracker::consumeClose() {
-  if (P.Tok.is(Close)) {
-    LClose =3D P.ConsumeAnyToken();
-    if (Cleanup)
-      P.QuantityTracker.pop(Kind);
-
-    Cleanup =3D false;
-    return false;
-  } else {
-    const char *LHSName =3D "unknown";
-    diag::kind DID =3D diag::err_parse_error;
-    switch (Close) {
-    default: break;
-    case tok::r_paren : LHSName =3D "("; DID =3D diag::err_expected_rparen=
; break;
-    case tok::r_brace : LHSName =3D "{"; DID =3D diag::err_expected_rbrace=
; break;
-    case tok::r_square: LHSName =3D "["; DID =3D diag::err_expected_rsquar=
e; break;
-    case tok::greater:  LHSName =3D "<"; DID =3D diag::err_expected_greate=
r; break;
-    case tok::greatergreatergreater:
-                        LHSName =3D "<<<"; DID =3D diag::err_expected_ggg;=
 break;
-    }
-    P.Diag(P.Tok, DID);
-    P.Diag(LOpen, diag::note_matching) << LHSName;
-    if (P.SkipUntil(Close))
-      LClose =3D P.Tok.getLocation();
-  }
-  return true;
+void Parser::BalancedDelimiterTracker::skipToEnd() {
+  P.SkipUntil(Close, false);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/FixItRewriter.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/FixItRewriter.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/FixItRewriter.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -14,6 +14,8 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/Rewrite/FixItRewriter.h"
+#include "clang/Edit/Commit.h"
+#include "clang/Edit/EditsReceiver.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
@@ -29,16 +31,19 @@
                              const LangOptions &LangOpts,
                              FixItOptions *FixItOpts)
   : Diags(Diags),
+    Editor(SourceMgr, LangOpts),
     Rewrite(SourceMgr, LangOpts),
     FixItOpts(FixItOpts),
-    NumFailures(0) {
+    NumFailures(0),
+    PrevDiagSilenced(false) {
+  OwnsClient =3D Diags.ownsClient();
   Client =3D Diags.takeClient();
   Diags.setClient(this);
 }
=20
 FixItRewriter::~FixItRewriter() {
   Diags.takeClient();
-  Diags.setClient(Client);
+  Diags.setClient(Client, OwnsClient);
 }
=20
 bool FixItRewriter::WriteFixedFile(FileID ID, raw_ostream &OS) {
@@ -49,26 +54,57 @@
   return false;
 }
=20
-bool FixItRewriter::WriteFixedFiles() {
+namespace {
+
+class RewritesReceiver : public edit::EditsReceiver {
+  Rewriter &Rewrite;
+
+public:
+  RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
+
+  virtual void insert(SourceLocation loc, StringRef text) {
+    Rewrite.InsertText(loc, text);
+  }
+  virtual void replace(CharSourceRange range, StringRef text) {
+    Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), tex=
t);
+  }
+};
+
+}
+
+bool FixItRewriter::WriteFixedFiles(
+            std::vector<std::pair<std::string, std::string> > *RewrittenFi=
les) {
   if (NumFailures > 0 && !FixItOpts->FixWhatYouCan) {
     Diag(FullSourceLoc(), diag::warn_fixit_no_changes);
     return true;
   }
=20
+  RewritesReceiver Rec(Rewrite);
+  Editor.applyRewrites(Rec);
+
   for (iterator I =3D buffer_begin(), E =3D buffer_end(); I !=3D E; ++I) {
     const FileEntry *Entry =3D Rewrite.getSourceMgr().getFileEntryForID(I-=
>first);
-    std::string Filename =3D FixItOpts->RewriteFilename(Entry->getName());
+    int fd;
+    std::string Filename =3D FixItOpts->RewriteFilename(Entry->getName(), =
fd);
     std::string Err;
-    llvm::raw_fd_ostream OS(Filename.c_str(), Err,
-                            llvm::raw_fd_ostream::F_Binary);
+    OwningPtr<llvm::raw_fd_ostream> OS;
+    if (fd !=3D -1) {
+      OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=3D*/true));
+    } else {
+      OS.reset(new llvm::raw_fd_ostream(Filename.c_str(), Err,
+                                        llvm::raw_fd_ostream::F_Binary));
+    }
     if (!Err.empty()) {
       Diags.Report(clang::diag::err_fe_unable_to_open_output)
           << Filename << Err;
       continue;
     }
     RewriteBuffer &RewriteBuf =3D I->second;
-    RewriteBuf.write(OS);
-    OS.flush();
+    RewriteBuf.write(*OS);
+    OS->flush();
+
+    if (RewrittenFiles)
+      RewrittenFiles->push_back(std::make_pair(Entry->getName(), Filename)=
);
   }
=20
   return false;
@@ -83,58 +119,63 @@
   // Default implementation (Warnings/errors count).
   DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
=20
-  Client->HandleDiagnostic(DiagLevel, Info);
+  if (!FixItOpts->Silent ||
+      DiagLevel >=3D DiagnosticsEngine::Error ||
+      (DiagLevel =3D=3D DiagnosticsEngine::Note && !PrevDiagSilenced) ||
+      (DiagLevel > DiagnosticsEngine::Note && Info.getNumFixItHints())) {
+    Client->HandleDiagnostic(DiagLevel, Info);
+    PrevDiagSilenced =3D false;
+  } else {
+    PrevDiagSilenced =3D true;
+  }
=20
   // Skip over any diagnostics that are ignored or notes.
   if (DiagLevel <=3D DiagnosticsEngine::Note)
     return;
+  // Skip over errors if we are only fixing warnings.
+  if (DiagLevel >=3D DiagnosticsEngine::Error && FixItOpts->FixOnlyWarning=
s) {
+    ++NumFailures;
+    return;
+  }
=20
   // Make sure that we can perform all of the modifications we
   // in this diagnostic.
-  bool CanRewrite =3D Info.getNumFixItHints() > 0;
+  edit::Commit commit(Editor);
   for (unsigned Idx =3D 0, Last =3D Info.getNumFixItHints();
        Idx < Last; ++Idx) {
     const FixItHint &Hint =3D Info.getFixItHint(Idx);
-    if (Hint.RemoveRange.isValid() &&
-        Rewrite.getRangeSize(Hint.RemoveRange) =3D=3D -1) {
-      CanRewrite =3D false;
-      break;
+
+    if (Hint.CodeToInsert.empty()) {
+      if (Hint.InsertFromRange.isValid())
+        commit.insertFromRange(Hint.RemoveRange.getBegin(),
+                           Hint.InsertFromRange, /*afterToken=3D*/false,
+                           Hint.BeforePreviousInsertions);
+      else
+        commit.remove(Hint.RemoveRange);
+    } else {
+      if (Hint.RemoveRange.isTokenRange() ||
+          Hint.RemoveRange.getBegin() !=3D Hint.RemoveRange.getEnd())
+        commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
+      else
+        commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
+                    /*afterToken=3D*/false, Hint.BeforePreviousInsertions);
     }
   }
+  bool CanRewrite =3D Info.getNumFixItHints() > 0 && commit.isCommitable();
=20
   if (!CanRewrite) {
     if (Info.getNumFixItHints() > 0)
       Diag(Info.getLocation(), diag::note_fixit_in_macro);
=20
     // If this was an error, refuse to perform any rewriting.
-    if (DiagLevel =3D=3D DiagnosticsEngine::Error ||
-          DiagLevel =3D=3D DiagnosticsEngine::Fatal) {
+    if (DiagLevel >=3D DiagnosticsEngine::Error) {
       if (++NumFailures =3D=3D 1)
         Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
     }
     return;
   }
-
-  bool Failed =3D false;
-  for (unsigned Idx =3D 0, Last =3D Info.getNumFixItHints();
-       Idx < Last; ++Idx) {
-    const FixItHint &Hint =3D Info.getFixItHint(Idx);
-
-    if (Hint.CodeToInsert.empty()) {
-      // We're removing code.
-      if (Rewrite.RemoveText(Hint.RemoveRange))
-        Failed =3D true;
-      continue;
-    }
-
-    // We're replacing code.
-    if (Rewrite.ReplaceText(Hint.RemoveRange.getBegin(),
-                            Rewrite.getRangeSize(Hint.RemoveRange),
-                            Hint.CodeToInsert))
-      Failed =3D true;
-  }
-
-  if (Failed) {
+ =20
+  if (!Editor.commit(commit)) {
     ++NumFailures;
     Diag(Info.getLocation(), diag::note_fixit_failed);
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/FrontendActions.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/FrontendActions.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/FrontendActions.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -12,6 +12,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Parse/Parser.h"
 #include "clang/Basic/FileManager.h"
+#include "clang/Frontend/FrontendActions.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Frontend/Utils.h"
@@ -21,6 +22,8 @@
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Path.h"
+#include "llvm/Support/FileSystem.h"
+
 using namespace clang;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -45,7 +48,10 @@
 namespace {
 class FixItRewriteInPlace : public FixItOptions {
 public:
-  std::string RewriteFilename(const std::string &Filename) { return Filena=
me; }
+  std::string RewriteFilename(const std::string &Filename, int &fd) {
+    fd =3D -1;
+    return Filename;
+  }
 };
=20
 class FixItActionSuffixInserter : public FixItOptions {
@@ -57,13 +63,27 @@
       this->FixWhatYouCan =3D FixWhatYouCan;
   }
=20
-  std::string RewriteFilename(const std::string &Filename) {
-    llvm::SmallString<128> Path(Filename);
+  std::string RewriteFilename(const std::string &Filename, int &fd) {
+    fd =3D -1;
+    SmallString<128> Path(Filename);
     llvm::sys::path::replace_extension(Path,
       NewSuffix + llvm::sys::path::extension(Path));
     return Path.str();
   }
 };
+
+class FixItRewriteToTemp : public FixItOptions {
+public:
+  std::string RewriteFilename(const std::string &Filename, int &fd) {
+    SmallString<128> Path;
+    Path =3D llvm::sys::path::filename(Filename);
+    Path +=3D "-%%%%%%%%";
+    Path +=3D llvm::sys::path::extension(Filename);
+    SmallString<128> NewPath;
+    llvm::sys::fs::unique_file(Path.str(), fd, NewPath);
+    return NewPath.str();
+  }
+};
 } // end anonymous namespace
=20
 bool FixItAction::BeginSourceFileAction(CompilerInstance &CI,
@@ -86,16 +106,63 @@
   Rewriter->WriteFixedFiles();
 }
=20
+bool FixItRecompile::BeginInvocation(CompilerInstance &CI) {
+
+  std::vector<std::pair<std::string, std::string> > RewrittenFiles;
+  bool err =3D false;
+  {
+    const FrontendOptions &FEOpts =3D CI.getFrontendOpts();
+    OwningPtr<FrontendAction> FixAction(new SyntaxOnlyAction());
+    if (FixAction->BeginSourceFile(CI, FEOpts.Inputs[0])) {
+      OwningPtr<FixItOptions> FixItOpts;
+      if (FEOpts.FixToTemporaries)
+        FixItOpts.reset(new FixItRewriteToTemp());
+      else
+        FixItOpts.reset(new FixItRewriteInPlace());
+      FixItOpts->Silent =3D true;
+      FixItOpts->FixWhatYouCan =3D FEOpts.FixWhatYouCan;
+      FixItOpts->FixOnlyWarnings =3D FEOpts.FixOnlyWarnings;
+      FixItRewriter Rewriter(CI.getDiagnostics(), CI.getSourceManager(),
+                             CI.getLangOpts(), FixItOpts.get());
+      FixAction->Execute();
+ =20
+      err =3D Rewriter.WriteFixedFiles(&RewrittenFiles);
+   =20
+      FixAction->EndSourceFile();
+      CI.setSourceManager(0);
+      CI.setFileManager(0);
+    } else {
+      err =3D true;
+    }
+  }
+  if (err)
+    return false;
+  CI.getDiagnosticClient().clear();
+  CI.getDiagnostics().Reset();
+
+  PreprocessorOptions &PPOpts =3D CI.getPreprocessorOpts();
+  PPOpts.RemappedFiles.insert(PPOpts.RemappedFiles.end(),
+                              RewrittenFiles.begin(), RewrittenFiles.end()=
);
+  PPOpts.RemappedFilesKeepOriginalName =3D false;
+
+  return true;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Preprocessor Actions
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 ASTConsumer *RewriteObjCAction::CreateASTConsumer(CompilerInstance &CI,
                                                   StringRef InFile) {
-  if (raw_ostream *OS =3D CI.createDefaultOutputFile(false, InFile, "cpp"))
+  if (raw_ostream *OS =3D CI.createDefaultOutputFile(false, InFile, "cpp")=
) {
+    if (CI.getLangOpts().ObjCNonFragileABI)
+      return CreateModernObjCRewriter(InFile, OS,
+                                CI.getDiagnostics(), CI.getLangOpts(),
+                                CI.getDiagnosticOpts().NoRewriteMacros);
     return CreateObjCRewriter(InFile, OS,
                               CI.getDiagnostics(), CI.getLangOpts(),
                               CI.getDiagnosticOpts().NoRewriteMacros);
+  }
   return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/HTMLPrint.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/HTMLPrint.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/HTMLPrint.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -55,7 +55,7 @@
 }
=20
 void HTMLPrinter::Initialize(ASTContext &context) {
-  R.setSourceMgr(context.getSourceManager(), context.getLangOptions());
+  R.setSourceMgr(context.getSourceManager(), context.getLangOpts());
 }
=20
 void HTMLPrinter::HandleTranslationUnit(ASTContext &Ctx) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/HTMLRewrite.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/HTMLRewrite.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/HTMLRewrite.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -209,7 +209,7 @@
=20
 static void AddLineNumber(RewriteBuffer &RB, unsigned LineNo,
                           unsigned B, unsigned E) {
-  llvm::SmallString<256> Str;
+  SmallString<256> Str;
   llvm::raw_svector_ostream OS(Str);
=20
   OS << "<tr><td class=3D\"num\" id=3D\"LN"
@@ -292,7 +292,7 @@
       " body { font-family:Helvetica, sans-serif; font-size:10pt }\n"
       " h1 { font-size:14pt }\n"
       " .code { border-collapse:collapse; width:100%; }\n"
-      " .code { font-family: \"Andale Mono\", monospace; font-size:10pt }\=
n"
+      " .code { font-family: \"Monospace\", monospace; font-size:10pt }\n"
       " .code { line-height: 1.2em }\n"
       " .comment { color: green; font-style: oblique }\n"
       " .keyword { color: blue }\n"
@@ -360,7 +360,7 @@
=20
   const SourceManager &SM =3D PP.getSourceManager();
   const llvm::MemoryBuffer *FromFile =3D SM.getBuffer(FID);
-  Lexer L(FID, FromFile, SM, PP.getLangOptions());
+  Lexer L(FID, FromFile, SM, PP.getLangOpts());
   const char *BufferStart =3D L.getBufferStart();
=20
   // Inform the preprocessor that we want to retain comments as tokens, so=
 we
@@ -381,7 +381,6 @@
     default: break;
     case tok::identifier:
       llvm_unreachable("tok::identifier in raw lexing mode!");
-      break;
     case tok::raw_identifier: {
       // Fill in Result.IdentifierInfo and update the token kind,
       // looking up the identifier in the identifier table.
@@ -410,6 +409,7 @@
       --TokLen;
       // FALL THROUGH.
     case tok::string_literal:
+      // FIXME: Exclude the optional ud-suffix from the highlighted range.
       HighlightRange(RB, TokOffs, TokOffs+TokLen, BufferStart,
                      "<span class=3D'string_literal'>", "</span>");
       break;
@@ -450,7 +450,7 @@
   std::vector<Token> TokenStream;
=20
   const llvm::MemoryBuffer *FromFile =3D SM.getBuffer(FID);
-  Lexer L(FID, FromFile, SM, PP.getLangOptions());
+  Lexer L(FID, FromFile, SM, PP.getLangOpts());
=20
   // Lex all the tokens in raw mode, to avoid entering #includes or expand=
ing
   // macros.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/RewriteMacros.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/RewriteMacros.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/RewriteMacros.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -66,7 +66,7 @@
   // Create a lexer to lex all the tokens of the main file in raw mode.  E=
ven
   // though it is in raw mode, it will not return comments.
   const llvm::MemoryBuffer *FromFile =3D SM.getBuffer(SM.getMainFileID());
-  Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions());
+  Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
=20
   // Switch on comment lexing because we really do want them.
   RawLex.SetCommentRetentionState(true);
@@ -91,7 +91,7 @@
   SourceManager &SM =3D PP.getSourceManager();
=20
   Rewriter Rewrite;
-  Rewrite.setSourceMgr(SM, PP.getLangOptions());
+  Rewrite.setSourceMgr(SM, PP.getLangOpts());
   RewriteBuffer &RB =3D Rewrite.getEditBuffer(SM.getMainFileID());
=20
   std::vector<Token> RawTokens;
@@ -167,7 +167,7 @@
       // Comment out a whole run of tokens instead of bracketing each one =
with
       // comments.  Add a leading space if RawTok didn't have one.
       bool HasSpace =3D RawTok.hasLeadingSpace();
-      RB.InsertTextAfter(RawOffs, " /*"+HasSpace);
+      RB.InsertTextAfter(RawOffs, &" /*"[HasSpace]);
       unsigned EndPos;
=20
       do {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/RewriteObjC.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/RewriteObjC.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/RewriteObjC.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -32,6 +32,8 @@
=20
 namespace {
   class RewriteObjC : public ASTConsumer {
+  protected:
+   =20
     enum {
       BLOCK_FIELD_IS_OBJECT   =3D  3,  /* id, NSObject, __attribute__((NSO=
bject)),
                                         block, ... */
@@ -53,20 +55,54 @@
       BLOCK_IS_GLOBAL =3D         (1 << 28),
       BLOCK_HAS_DESCRIPTOR =3D    (1 << 29)
     };
+    static const int OBJC_ABI_VERSION =3D 7;
    =20
     Rewriter Rewrite;
     DiagnosticsEngine &Diags;
     const LangOptions &LangOpts;
-    unsigned RewriteFailedDiag;
-    unsigned TryFinallyContainsReturnDiag;
-
     ASTContext *Context;
     SourceManager *SM;
     TranslationUnitDecl *TUDecl;
     FileID MainFileID;
     const char *MainFileStart, *MainFileEnd;
-    SourceLocation LastIncLoc;
-
+    Stmt *CurrentBody;
+    ParentMap *PropParentMap; // created lazily.
+    std::string InFileName;
+    raw_ostream* OutFile;
+    std::string Preamble;
+   =20
+    TypeDecl *ProtocolTypeDecl;
+    VarDecl *GlobalVarDecl;
+    unsigned RewriteFailedDiag;
+    // ObjC string constant support.
+    unsigned NumObjCStringLiterals;
+    VarDecl *ConstantStringClassReference;
+    RecordDecl *NSStringRecord;
+
+    // ObjC foreach break/continue generation support.
+    int BcLabelCount;
+   =20
+    unsigned TryFinallyContainsReturnDiag;
+    // Needed for super.
+    ObjCMethodDecl *CurMethodDef;
+    RecordDecl *SuperStructDecl;
+    RecordDecl *ConstantStringDecl;
+   =20
+    FunctionDecl *MsgSendFunctionDecl;
+    FunctionDecl *MsgSendSuperFunctionDecl;
+    FunctionDecl *MsgSendStretFunctionDecl;
+    FunctionDecl *MsgSendSuperStretFunctionDecl;
+    FunctionDecl *MsgSendFpretFunctionDecl;
+    FunctionDecl *GetClassFunctionDecl;
+    FunctionDecl *GetMetaClassFunctionDecl;
+    FunctionDecl *GetSuperClassFunctionDecl;
+    FunctionDecl *SelGetUidFunctionDecl;
+    FunctionDecl *CFStringFunctionDecl;
+    FunctionDecl *SuperContructorFunctionDecl;
+    FunctionDecl *CurFunctionDef;
+    FunctionDecl *CurFunctionDeclToDeclareForBlock;
+
+    /* Misc. containers needed for meta-data rewrite. */
     SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
     SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
     llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
@@ -79,53 +115,13 @@
     llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
    =20
     llvm::DenseSet<uint64_t> CopyDestroyCache;
-   =20
-    unsigned NumObjCStringLiterals;
-
-    FunctionDecl *MsgSendFunctionDecl;
-    FunctionDecl *MsgSendSuperFunctionDecl;
-    FunctionDecl *MsgSendStretFunctionDecl;
-    FunctionDecl *MsgSendSuperStretFunctionDecl;
-    FunctionDecl *MsgSendFpretFunctionDecl;
-    FunctionDecl *GetClassFunctionDecl;
-    FunctionDecl *GetMetaClassFunctionDecl;
-    FunctionDecl *GetSuperClassFunctionDecl;
-    FunctionDecl *SelGetUidFunctionDecl;
-    FunctionDecl *CFStringFunctionDecl;
-    FunctionDecl *SuperContructorFunctionDecl;
-
-    // ObjC string constant support.
-    VarDecl *ConstantStringClassReference;
-    RecordDecl *NSStringRecord;
-
-    // ObjC foreach break/continue generation support.
-    int BcLabelCount;
-
-    // Needed for super.
-    ObjCMethodDecl *CurMethodDef;
-    RecordDecl *SuperStructDecl;
-    RecordDecl *ConstantStringDecl;
-
-    TypeDecl *ProtocolTypeDecl;
-    QualType getProtocolType();
-
-    // Needed for header files being rewritten
-    bool IsHeader;
-
-    std::string InFileName;
-    raw_ostream* OutFile;
-
-    bool SilenceRewriteMacroWarning;
-    bool objc_impl_method;
-
-    std::string Preamble;
=20
     // Block expressions.
     SmallVector<BlockExpr *, 32> Blocks;
     SmallVector<int, 32> InnerDeclRefsCount;
-    SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
+    SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
    =20
-    SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
+    SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
=20
     // Block related declarations.
     SmallVector<ValueDecl *, 8> BlockByCopyDecls;
@@ -138,36 +134,54 @@
    =20
     llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
=20
-    // This maps a property to it's assignment statement.
-    llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
-    // This maps a property to it's synthesied message expression.
-    // This allows us to rewrite chained getters (e.g. o.a.b.c).
-    llvm::DenseMap<Expr *, Stmt *> PropGetters;
-
     // This maps an original source AST to it's rewritten form. This allows
     // us to avoid rewriting the same node twice (which is very uncommon).
     // This is needed to support some of the exotic property rewriting.
     llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
=20
-    FunctionDecl *CurFunctionDef;
-    FunctionDecl *CurFunctionDeclToDeclareForBlock;
-    VarDecl *GlobalVarDecl;
-
+    // Needed for header files being rewritten
+    bool IsHeader;
+    bool SilenceRewriteMacroWarning;
+    bool objc_impl_method;
+   =20
     bool DisableReplaceStmt;
-
-    static const int OBJC_ABI_VERSION =3D 7;
+    class DisableReplaceStmtScope {
+      RewriteObjC &R;
+      bool SavedValue;
+   =20
+    public:
+      DisableReplaceStmtScope(RewriteObjC &R)
+        : R(R), SavedValue(R.DisableReplaceStmt) {
+        R.DisableReplaceStmt =3D true;
+      }
+      ~DisableReplaceStmtScope() {
+        R.DisableReplaceStmt =3D SavedValue;
+      }
+    };
+    void InitializeCommon(ASTContext &context);
+
   public:
-    virtual void Initialize(ASTContext &context);
=20
     // Top Level Driver code.
-    virtual void HandleTopLevelDecl(DeclGroupRef D) {
+    virtual bool HandleTopLevelDecl(DeclGroupRef D) {
       for (DeclGroupRef::iterator I =3D D.begin(), E =3D D.end(); I !=3D E=
; ++I) {
-        if (isa<ObjCClassDecl>((*I))) {
-          RewriteForwardClassDecl(D);
-          break;
+        if (ObjCInterfaceDecl *Class =3D dyn_cast<ObjCInterfaceDecl>(*I)) {
+          if (!Class->isThisDeclarationADefinition()) {
+            RewriteForwardClassDecl(D);
+            break;
+          }
         }
+
+        if (ObjCProtocolDecl *Proto =3D dyn_cast<ObjCProtocolDecl>(*I)) {
+          if (!Proto->isThisDeclarationADefinition()) {
+            RewriteForwardProtocolDecl(D);
+            break;
+          }
+        }
+
         HandleTopLevelSingleDecl(*I);
       }
+      return true;
     }
     void HandleTopLevelSingleDecl(Decl *D);
     void HandleDeclInMainFile(Decl *D);
@@ -186,7 +200,7 @@
         return; // We can't rewrite the same node twice.
=20
       if (DisableReplaceStmt)
-        return; // Used when rewriting the assignment of a property setter.
+        return;
=20
       // If replacement succeeded or warning disabled return with no warni=
ng.
       if (!Rewrite.ReplaceStmt(Old, New)) {
@@ -200,6 +214,9 @@
     }
=20
     void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
+      if (DisableReplaceStmt)
+        return;
+
       // Measure the old text.
       int Size =3D Rewrite.getRangeSize(SrcRange);
       if (Size =3D=3D -1) {
@@ -245,12 +262,13 @@
     }
=20
     // Syntactic Rewriting.
+    void RewriteRecordBody(RecordDecl *RD);
     void RewriteInclude();
     void RewriteForwardClassDecl(DeclGroupRef D);
     void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
-    void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,=20
+    void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,=20
                                      const std::string &typedefString);
-     =20
+    void RewriteImplementations();
     void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
                                  ObjCImplementationDecl *IMD,
                                  ObjCCategoryImplDecl *CID);
@@ -264,7 +282,8 @@
                             ValueDecl *VD, bool def=3Dfalse);
     void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
     void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
-    void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
+    void RewriteForwardProtocolDecl(DeclGroupRef D);
+    void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
     void RewriteMethodDeclaration(ObjCMethodDecl *Method);
     void RewriteProperty(ObjCPropertyDecl *prop);
     void RewriteFunctionDecl(FunctionDecl *FD);
@@ -274,32 +293,16 @@
     void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
     void RewriteTypeOfDecl(VarDecl *VD);
     void RewriteObjCQualifiedInterfaceTypes(Expr *E);
-    bool needToScanForQualifiers(QualType T);
-    QualType getSuperStructType();
-    QualType getConstantStringStructType();
-    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
-    bool BufferContainsPPDirectives(const char *startBuf, const char *endB=
uf);
-
+ =20
     // Expression Rewriting.
     Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
-    void CollectPropertySetters(Stmt *S);
-
-    Stmt *CurrentBody;
-    ParentMap *PropParentMap; // created lazily.
-
     Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
-    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigS=
tart,
-                                 bool &replaced);
-    Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
-    Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
-    Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *new=
Stmt,
-                                SourceRange SrcRange);
+    Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
+    Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
     Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
     Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
     Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
     Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
-    void WarnAboutReturnGotoStmts(Stmt *S);
-    void HasReturnStmts(Stmt *S, bool &hasReturns);
     void RewriteTryReturnStmts(Stmt *S);
     void RewriteSyncReturnStmts(Stmt *S, std::string buf);
     Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
@@ -307,18 +310,57 @@
     Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
     Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
                                        SourceLocation OrigEnd);
-    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
+    Stmt *RewriteBreakStmt(BreakStmt *S);
+    Stmt *RewriteContinueStmt(ContinueStmt *S);
+    void RewriteCastExpr(CStyleCastExpr *CE);
+   =20
+    // Block rewriting.
+    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
+   =20
+    // Block specific rewrite rules.
+    void RewriteBlockPointerDecl(NamedDecl *VD);
+    void RewriteByRefVar(VarDecl *VD);
+    Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
+    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
+    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
+   =20
+    void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
+                                      std::string &Result);
+   =20
+    virtual void Initialize(ASTContext &context) =3D 0;
+   =20
+    // Metadata Rewriting.
+    virtual void RewriteMetaDataIntoBuffer(std::string &Result) =3D 0;
+    virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtoc=
olDecl> &Prots,
+                                                 StringRef prefix,
+                                                 StringRef ClassName,
+                                                 std::string &Result) =3D =
0;
+    virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
+                                             std::string &Result) =3D 0;
+    virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
+                                     StringRef prefix,
+                                     StringRef ClassName,
+                                     std::string &Result) =3D 0;
+    virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
+                                          std::string &Result) =3D 0;
+   =20
+    // Rewriting ivar access
+    virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) =3D 0;
+    virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
+                                         std::string &Result) =3D 0;
+   =20
+    // Misc. AST transformation routines. Somtimes they end up calling
+    // rewriting routines on the new ASTs.
     CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
-                                      Expr **args, unsigned nargs,
-                                      SourceLocation StartLoc=3DSourceLoca=
tion(),
-                                      SourceLocation EndLoc=3DSourceLocati=
on());
+                                           Expr **args, unsigned nargs,
+                                           SourceLocation StartLoc=3DSourc=
eLocation(),
+                                           SourceLocation EndLoc=3DSourceL=
ocation());
+
     Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
                            SourceLocation StartLoc=3DSourceLocation(),
                            SourceLocation EndLoc=3DSourceLocation());
-    Stmt *RewriteBreakStmt(BreakStmt *S);
-    Stmt *RewriteContinueStmt(ContinueStmt *S);
+   =20
     void SynthCountByEnumWithState(std::string &buf);
-
     void SynthMsgSendFunctionDecl();
     void SynthMsgSendSuperFunctionDecl();
     void SynthMsgSendStretFunctionDecl();
@@ -329,52 +371,8 @@
     void SynthGetSuperClassFunctionDecl();
     void SynthSelGetUidFunctionDecl();
     void SynthSuperContructorFunctionDecl();
-
-    // Metadata emission.
-    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
-                                  std::string &Result);
-
-    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
-                                     std::string &Result);
-
-    template<typename MethodIterator>
-    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
-                                    MethodIterator MethodEnd,
-                                    bool IsInstanceMethod,
-                                    StringRef prefix,
-                                    StringRef ClassName,
-                                    std::string &Result);
-
-    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
-                                     StringRef prefix,
-                                     StringRef ClassName,
-                                     std::string &Result);
-    void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> =
&Prots,
-                                         StringRef prefix,
-                                         StringRef ClassName,
-                                         std::string &Result);
-    void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
-                                      std::string &Result);
-    void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
-                                         std::string &Result);
-    void RewriteImplementations();
-    void SynthesizeMetaDataIntoBuffer(std::string &Result);
-
-    // Block rewriting.
-    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
-    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
-
-    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
-    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
-
-    // Block specific rewrite rules.
-    void RewriteBlockPointerDecl(NamedDecl *VD);
-    void RewriteByRefVar(VarDecl *VD);
+   =20
     std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
-    Stmt *RewriteBlockDeclRefExpr(Expr *VD);
-    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
-    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
-
     std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
                                       StringRef funcName, std::string Tag);
     std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
@@ -388,12 +386,23 @@
     Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
     void SynthesizeBlockLiterals(SourceLocation FunLocStart,
                                  StringRef FunName);
-    void RewriteRecordBody(RecordDecl *RD);
-
+    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
+    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
+            const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
+
+    // Misc. helper routines.
+    QualType getProtocolType();
+    void WarnAboutReturnGotoStmts(Stmt *S);
+    void HasReturnStmts(Stmt *S, bool &hasReturns);
+    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
+    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
+    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
+
+    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
     void CollectBlockDeclRefInfo(BlockExpr *Exp);
     void GetBlockDeclRefExprs(Stmt *S);
     void GetInnerBlockDeclRefExprs(Stmt *S,=20
-                SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
+                SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
                 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
=20
     // We avoid calling Type::isBlockPointerType(), since it operates on t=
he
@@ -414,6 +423,12 @@
       return false;
     }
    =20
+    bool needToScanForQualifiers(QualType T);
+    QualType getSuperStructType();
+    QualType getConstantStringStructType();
+    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
+    bool BufferContainsPPDirectives(const char *startBuf, const char *endB=
uf);
+   =20
     void convertToUnqualifiedObjCType(QualType &T) {
       if (T->isObjCQualifiedIdType())
         T =3D Context->getObjCIdType();
@@ -452,12 +467,7 @@
     bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
     void GetExtentOfArgList(const char *Name, const char *&LParen,
                             const char *&RParen);
-    void RewriteCastExpr(CStyleCastExpr *CE);
-
-    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
-    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
-            const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
-
+   =20
     void QuoteDoublequotes(std::string &From, std::string &To) {
       for (unsigned i =3D 0; i < From.length(); i++) {
         if (From[i] =3D=3D '"')
@@ -477,15 +487,54 @@
       fpi.Variadic =3D variadic;
       return Context->getFunctionType(result, args, numArgs, fpi);
     }
+
+    // Helper function: create a CStyleCastExpr with trivial type source i=
nfo.
+    CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
+                                             CastKind Kind, Expr *E) {
+      TypeSourceInfo *TInfo =3D Ctx->getTrivialTypeSourceInfo(Ty, SourceLo=
cation());
+      return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
+                                    SourceLocation(), SourceLocation());
+    }
   };
-
-  // Helper function: create a CStyleCastExpr with trivial type source inf=
o.
-  CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
-                                           CastKind Kind, Expr *E) {
-    TypeSourceInfo *TInfo =3D Ctx->getTrivialTypeSourceInfo(Ty, SourceLoca=
tion());
-    return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
-                                  SourceLocation(), SourceLocation());
-  }
+ =20
+  class RewriteObjCFragileABI : public RewriteObjC {
+  public:
+   =20
+    RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
+                DiagnosticsEngine &D, const LangOptions &LOpts,
+                bool silenceMacroWarn) : RewriteObjC(inFile, OS,
+                                                     D, LOpts,
+                                                     silenceMacroWarn) {}
+   =20
+    ~RewriteObjCFragileABI() {}
+    virtual void Initialize(ASTContext &context);
+   =20
+    // Rewriting metadata
+    template<typename MethodIterator>
+    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
+                                    MethodIterator MethodEnd,
+                                    bool IsInstanceMethod,
+                                    StringRef prefix,
+                                    StringRef ClassName,
+                                    std::string &Result);
+    virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
+                                             StringRef prefix,
+                                             StringRef ClassName,
+                                             std::string &Result);
+    virtual void RewriteObjCProtocolListMetaData(
+                  const ObjCList<ObjCProtocolDecl> &Prots,
+                  StringRef prefix, StringRef ClassName, std::string &Resu=
lt);
+    virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
+                                          std::string &Result);
+    virtual void RewriteMetaDataIntoBuffer(std::string &Result);
+    virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
+                                             std::string &Result);
+   =20
+    // Rewriting ivar
+    virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
+                                              std::string &Result);
+    virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
+  };
 }
=20
 void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
@@ -541,10 +590,10 @@
                                        DiagnosticsEngine &Diags,
                                        const LangOptions &LOpts,
                                        bool SilenceRewriteMacroWarning) {
-  return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarn=
ing);
+  return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewrit=
eMacroWarning);
 }
=20
-void RewriteObjC::Initialize(ASTContext &context) {
+void RewriteObjC::InitializeCommon(ASTContext &context) {
   Context =3D &context;
   SM =3D &Context->getSourceManager();
   TUDecl =3D Context->getTranslationUnitDecl();
@@ -581,121 +630,9 @@
   MainFileStart =3D MainBuf->getBufferStart();
   MainFileEnd =3D MainBuf->getBufferEnd();
=20
-  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOption=
s());
-
-  // declaring objc_selector outside the parameter list removes a silly
-  // scope related warning...
-  if (IsHeader)
-    Preamble =3D "#pragma once\n";
-  Preamble +=3D "struct objc_selector; struct objc_class;\n";
-  Preamble +=3D "struct __rw_objc_super { struct objc_object *object; ";
-  Preamble +=3D "struct objc_object *superClass; ";
-  if (LangOpts.MicrosoftExt) {
-    // Add a constructor for creating temporary objects.
-    Preamble +=3D "__rw_objc_super(struct objc_object *o, struct objc_obje=
ct *s) "
-                ": ";
-    Preamble +=3D "object(o), superClass(s) {} ";
-  }
-  Preamble +=3D "};\n";
-  Preamble +=3D "#ifndef _REWRITER_typedef_Protocol\n";
-  Preamble +=3D "typedef struct objc_object Protocol;\n";
-  Preamble +=3D "#define _REWRITER_typedef_Protocol\n";
-  Preamble +=3D "#endif\n";
-  if (LangOpts.MicrosoftExt) {
-    Preamble +=3D "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dll=
import)\n";
-    Preamble +=3D "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
-  } else
-  Preamble +=3D "#define __OBJC_RW_DLLIMPORT extern\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
-  Preamble +=3D "(struct objc_object *, struct objc_selector *, ...);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper=
";
-  Preamble +=3D "(struct objc_super *, struct objc_selector *, ...);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stre=
t";
-  Preamble +=3D "(struct objc_object *, struct objc_selector *, ...);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper=
_stret";
-  Preamble +=3D "(struct objc_super *, struct objc_selector *, ...);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
-  Preamble +=3D "(struct objc_object *, struct objc_selector *, ...);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
-  Preamble +=3D "(const char *);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclas=
s";
-  Preamble +=3D "(struct objc_class *);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass=
";
-  Preamble +=3D "(const char *);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc=
_object *);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *)=
;\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);=
\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_ex=
tract(void *);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT int objc_exception_match";
-  Preamble +=3D "(struct objc_class *, struct objc_object *);\n";
-  // @synchronized hooks.
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_obje=
ct *);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_objec=
t *);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char=
 *);\n";
-  Preamble +=3D "#ifndef __FASTENUMERATIONSTATE\n";
-  Preamble +=3D "struct __objcFastEnumerationState {\n\t";
-  Preamble +=3D "unsigned long state;\n\t";
-  Preamble +=3D "void **itemsPtr;\n\t";
-  Preamble +=3D "unsigned long *mutationsPtr;\n\t";
-  Preamble +=3D "unsigned long extra[5];\n};\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct =
objc_object *);\n";
-  Preamble +=3D "#define __FASTENUMERATIONSTATE\n";
-  Preamble +=3D "#endif\n";
-  Preamble +=3D "#ifndef __NSCONSTANTSTRINGIMPL\n";
-  Preamble +=3D "struct __NSConstantStringImpl {\n";
-  Preamble +=3D "  int *isa;\n";
-  Preamble +=3D "  int flags;\n";
-  Preamble +=3D "  char *str;\n";
-  Preamble +=3D "  long length;\n";
-  Preamble +=3D "};\n";
-  Preamble +=3D "#ifdef CF_EXPORT_CONSTANT_STRING\n";
-  Preamble +=3D "extern \"C\" __declspec(dllexport) int __CFConstantString=
ClassReference[];\n";
-  Preamble +=3D "#else\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[=
];\n";
-  Preamble +=3D "#endif\n";
-  Preamble +=3D "#define __NSCONSTANTSTRINGIMPL\n";
-  Preamble +=3D "#endif\n";
-  // Blocks preamble.
-  Preamble +=3D "#ifndef BLOCK_IMPL\n";
-  Preamble +=3D "#define BLOCK_IMPL\n";
-  Preamble +=3D "struct __block_impl {\n";
-  Preamble +=3D "  void *isa;\n";
-  Preamble +=3D "  int Flags;\n";
-  Preamble +=3D "  int Reserved;\n";
-  Preamble +=3D "  void *FuncPtr;\n";
-  Preamble +=3D "};\n";
-  Preamble +=3D "// Runtime copy/destroy helper functions (from Block_priv=
ate.h)\n";
-  Preamble +=3D "#ifdef __OBJC_EXPORT_BLOCKS\n";
-  Preamble +=3D "extern \"C\" __declspec(dllexport) "
-              "void _Block_object_assign(void *, const void *, const int);=
\n";
-  Preamble +=3D "extern \"C\" __declspec(dllexport) void _Block_object_dis=
pose(const void *, const int);\n";
-  Preamble +=3D "extern \"C\" __declspec(dllexport) void *_NSConcreteGloba=
lBlock[32];\n";
-  Preamble +=3D "extern \"C\" __declspec(dllexport) void *_NSConcreteStack=
Block[32];\n";
-  Preamble +=3D "#else\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, con=
st void *, const int);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void=
 *, const int);\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
-  Preamble +=3D "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
-  Preamble +=3D "#endif\n";
-  Preamble +=3D "#endif\n";
-  if (LangOpts.MicrosoftExt) {
-    Preamble +=3D "#undef __OBJC_RW_DLLIMPORT\n";
-    Preamble +=3D "#undef __OBJC_RW_STATICIMPORT\n";
-    Preamble +=3D "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang t=
ests.
-    Preamble +=3D "#define __attribute__(X)\n";
-    Preamble +=3D "#endif\n";
-    Preamble +=3D "#define __weak\n";
-  }
-  else {
-    Preamble +=3D "#define __block\n";
-    Preamble +=3D "#define __weak\n";
-  }
-  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
-  // as this avoids warning in any 64bit/32bit compilation model.
-  Preamble +=3D "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((=
TYPE *)0)->MEMBER)\n";
+  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts()=
);
 }
=20
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Top Level Driver Code
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -722,33 +659,57 @@
       ConstantStringClassReference =3D FVD;
       return;
     }
-  } else if (ObjCInterfaceDecl *MD =3D dyn_cast<ObjCInterfaceDecl>(D)) {
-    RewriteInterfaceDecl(MD);
+  } else if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(D)) {
+    if (ID->isThisDeclarationADefinition())
+      RewriteInterfaceDecl(ID);
   } else if (ObjCCategoryDecl *CD =3D dyn_cast<ObjCCategoryDecl>(D)) {
     RewriteCategoryDecl(CD);
   } else if (ObjCProtocolDecl *PD =3D dyn_cast<ObjCProtocolDecl>(D)) {
-    RewriteProtocolDecl(PD);
-  } else if (ObjCForwardProtocolDecl *FP =3D
-             dyn_cast<ObjCForwardProtocolDecl>(D)){
-    RewriteForwardProtocolDecl(FP);
+    if (PD->isThisDeclarationADefinition())
+      RewriteProtocolDecl(PD);
   } else if (LinkageSpecDecl *LSD =3D dyn_cast<LinkageSpecDecl>(D)) {
     // Recurse into linkage specifications
     for (DeclContext::decl_iterator DI =3D LSD->decls_begin(),
                                  DIEnd =3D LSD->decls_end();
          DI !=3D DIEnd; ) {
-      if (isa<ObjCClassDecl>((*DI))) {
-        SmallVector<Decl *, 8> DG;
-        Decl *D =3D (*DI);
-        SourceLocation Loc =3D D->getLocation();
-        while (DI !=3D DIEnd &&
-               isa<ObjCClassDecl>(D) && D->getLocation() =3D=3D Loc) {
-          DG.push_back(D);
-          ++DI;
-          D =3D (*DI);
+      if (ObjCInterfaceDecl *IFace =3D dyn_cast<ObjCInterfaceDecl>((*DI)))=
 {
+        if (!IFace->isThisDeclarationADefinition()) {
+          SmallVector<Decl *, 8> DG;
+          SourceLocation StartLoc =3D IFace->getLocStart();
+          do {
+            if (isa<ObjCInterfaceDecl>(*DI) &&
+                !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinitio=
n() &&
+                StartLoc =3D=3D (*DI)->getLocStart())
+              DG.push_back(*DI);
+            else
+              break;
+           =20
+            ++DI;
+          } while (DI !=3D DIEnd);
+          RewriteForwardClassDecl(DG);
+          continue;
         }
-        RewriteForwardClassDecl(DG);
-        continue;
       }
+
+      if (ObjCProtocolDecl *Proto =3D dyn_cast<ObjCProtocolDecl>((*DI))) {
+        if (!Proto->isThisDeclarationADefinition()) {
+          SmallVector<Decl *, 8> DG;
+          SourceLocation StartLoc =3D Proto->getLocStart();
+          do {
+            if (isa<ObjCProtocolDecl>(*DI) &&
+                !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition=
() &&
+                StartLoc =3D=3D (*DI)->getLocStart())
+              DG.push_back(*DI);
+            else
+              break;
+           =20
+            ++DI;
+          } while (DI !=3D DIEnd);
+          RewriteForwardProtocolDecl(DG);
+          continue;
+        }
+      }
+     =20
       HandleTopLevelSingleDecl(*DI);
       ++DI;
     }
@@ -868,7 +829,7 @@
       Getr +=3D ";\n";
       Getr +=3D "return (_TYPE)";
       Getr +=3D "objc_getProperty(self, _cmd, ";
-      SynthesizeIvarOffsetComputation(OID, Getr);
+      RewriteIvarOffsetComputation(OID, Getr);
       Getr +=3D ", 1)";
     }
     else
@@ -898,7 +859,7 @@
   // See objc-act.c:objc_synthesize_new_setter() for details.
   if (GenSetProperty) {
     Setr +=3D "objc_setProperty (self, _cmd, ";
-    SynthesizeIvarOffsetComputation(OID, Setr);
+    RewriteIvarOffsetComputation(OID, Setr);
     Setr +=3D ", (id)";
     Setr +=3D PD->getName();
     Setr +=3D ", ";
@@ -932,9 +893,9 @@
   typedefString +=3D ";\n#endif\n";
 }
=20
-void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
+void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
                                               const std::string &typedefSt=
ring) {
-    SourceLocation startLoc =3D ClassDecl->getLocation();
+    SourceLocation startLoc =3D ClassDecl->getLocStart();
     const char *startBuf =3D SM->getCharacterData(startLoc);
     const char *semiPtr =3D strchr(startBuf, ';');=20
     // Replace the @class with typedefs corresponding to the classes.
@@ -944,8 +905,7 @@
 void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
   std::string typedefString;
   for (DeclGroupRef::iterator I =3D D.begin(), E =3D D.end(); I !=3D E; ++=
I) {
-    ObjCClassDecl *ClassDecl =3D cast<ObjCClassDecl>(*I);
-    ObjCInterfaceDecl *ForwardDecl =3D ClassDecl->getForwardInterfaceDecl(=
);
+    ObjCInterfaceDecl *ForwardDecl =3D cast<ObjCInterfaceDecl>(*I);
     if (I =3D=3D D.begin()) {
       // Translate to typedef's that forward reference structs with the sa=
me name
       // as the class. As a convenience, we include the original declarati=
on
@@ -957,15 +917,14 @@
     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
   }
   DeclGroupRef::iterator I =3D D.begin();
-  RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
+  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
 }
=20
 void RewriteObjC::RewriteForwardClassDecl(
                                 const llvm::SmallVector<Decl*, 8> &D) {
   std::string typedefString;
   for (unsigned i =3D 0; i < D.size(); i++) {
-    ObjCClassDecl *ClassDecl =3D cast<ObjCClassDecl>(D[i]);
-    ObjCInterfaceDecl *ForwardDecl =3D ClassDecl->getForwardInterfaceDecl(=
);
+    ObjCInterfaceDecl *ForwardDecl =3D cast<ObjCInterfaceDecl>(D[i]);
     if (i =3D=3D 0) {
       typedefString +=3D "// @class ";
       typedefString +=3D ForwardDecl->getNameAsString();
@@ -973,7 +932,7 @@
     }
     RewriteOneForwardClassDecl(ForwardDecl, typedefString);
   }
-  RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
+  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString=
);
 }
=20
 void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
@@ -1026,7 +985,8 @@
=20
 void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
   SourceLocation LocStart =3D PDecl->getLocStart();
-
+  assert(PDecl->isThisDeclarationADefinition());
+ =20
   // FIXME: handle protocol headers that are declared across multiple line=
s.
   ReplaceText(LocStart, 0, "// ");
=20
@@ -1064,8 +1024,17 @@
   }
 }
=20
-void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDec=
l) {
-  SourceLocation LocStart =3D PDecl->getLocation();
+void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
+  SourceLocation LocStart =3D (*D.begin())->getLocStart();
+  if (LocStart.isInvalid())
+    llvm_unreachable("Invalid SourceLocation");
+  // FIXME: handle forward protocol that are declared across multiple line=
s.
+  ReplaceText(LocStart, 0, "// ");
+}
+
+void=20
+RewriteObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> =
&DG) {
+  SourceLocation LocStart =3D DG[0]->getLocStart();
   if (LocStart.isInvalid())
     llvm_unreachable("Invalid SourceLocation");
   // FIXME: handle forward protocol that are declared across multiple line=
s.
@@ -1168,10 +1137,8 @@
       std::string Name =3D PDecl->getNameAsString();
       QualType QT =3D PDecl->getType();
       // Make sure we convert "t (^)(...)" to "t (*)(...)".
-      if (convertBlockPointerToFunctionPointer(QT))
-        QT.getAsStringInternal(Name, Context->getPrintingPolicy());
-      else
-        PDecl->getType().getAsStringInternal(Name, Context->getPrintingPol=
icy());
+      (void)convertBlockPointerToFunctionPointer(QT);
+      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
       ResultStr +=3D Name;
     }
   }
@@ -1248,7 +1215,7 @@
=20
 void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
   std::string ResultStr;
-  if (!ObjCForwardDecls.count(ClassDecl)) {
+  if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
     // we haven't seen a forward decl - generate a typedef.
     ResultStr =3D "#ifndef _REWRITER_typedef_";
     ResultStr +=3D ClassDecl->getNameAsString();
@@ -1260,9 +1227,9 @@
     ResultStr +=3D ClassDecl->getNameAsString();
     ResultStr +=3D ";\n#endif\n";
     // Mark this typedef as having been generated.
-    ObjCForwardDecls.insert(ClassDecl);
+    ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
   }
-  SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
+  RewriteObjCInternalStruct(ClassDecl, ResultStr);
=20
   for (ObjCInterfaceDecl::prop_iterator I =3D ClassDecl->prop_begin(),
          E =3D ClassDecl->prop_end(); I !=3D E; ++I)
@@ -1281,287 +1248,163 @@
               "/* @end */");
 }
=20
-Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, =
Expr *newStmt,
-                                         SourceRange SrcRange) {
-  ObjCMethodDecl *OMD =3D 0;
-  QualType Ty;
-  Selector Sel;
-  Stmt *Receiver =3D 0;
-  bool Super =3D false;
-  QualType SuperTy;
-  SourceLocation SuperLocation;
-  SourceLocation SelectorLoc;
-  // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplic=
itSetterGetterRefExpr.
-  // This allows us to reuse all the fun and games in SynthMessageExpr().
-  if (ObjCPropertyRefExpr *PropRefExpr =3D
-        dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
-    SelectorLoc =3D PropRefExpr->getLocation();
-    if (PropRefExpr->isExplicitProperty()) {
-      ObjCPropertyDecl *PDecl =3D PropRefExpr->getExplicitProperty();
-      OMD =3D PDecl->getSetterMethodDecl();
-      Ty =3D PDecl->getType();
-      Sel =3D PDecl->getSetterName();
-    } else {
-      OMD =3D PropRefExpr->getImplicitPropertySetter();
-      Sel =3D OMD->getSelector();
-      Ty =3D PropRefExpr->getType();
+Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseud=
oOp) {
+  SourceRange OldRange =3D PseudoOp->getSourceRange();
+
+  // We just magically know some things about the structure of this
+  // expression.
+  ObjCMessageExpr *OldMsg =3D
+    cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
+                            PseudoOp->getNumSemanticExprs() - 1));
+
+  // Because the rewriter doesn't allow us to rewrite rewritten code,
+  // we need to suppress rewriting the sub-statements.
+  Expr *Base, *RHS;
+  {
+    DisableReplaceStmtScope S(*this);
+
+    // Rebuild the base expression if we have one.
+    Base =3D 0;
+    if (OldMsg->getReceiverKind() =3D=3D ObjCMessageExpr::Instance) {
+      Base =3D OldMsg->getInstanceReceiver();
+      Base =3D cast<OpaqueValueExpr>(Base)->getSourceExpr();
+      Base =3D cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
     }
-    Super =3D PropRefExpr->isSuperReceiver();
-    if (!Super) {
-      Receiver =3D PropRefExpr->getBase();
-    } else {
-      SuperTy =3D PropRefExpr->getSuperReceiverType();
-      SuperLocation =3D PropRefExpr->getReceiverLocation();
+
+    // Rebuild the RHS.
+    RHS =3D cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
+    RHS =3D cast<OpaqueValueExpr>(RHS)->getSourceExpr();
+    RHS =3D cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
+  }
+
+  // TODO: avoid this copy.
+  SmallVector<SourceLocation, 1> SelLocs;
+  OldMsg->getSelectorLocs(SelLocs);
+
+  ObjCMessageExpr *NewMsg =3D 0;
+  switch (OldMsg->getReceiverKind()) {
+  case ObjCMessageExpr::Class:
+    NewMsg =3D ObjCMessageExpr::Create(*Context, OldMsg->getType(),
+                                     OldMsg->getValueKind(),
+                                     OldMsg->getLeftLoc(),
+                                     OldMsg->getClassReceiverTypeInfo(),
+                                     OldMsg->getSelector(),
+                                     SelLocs,
+                                     OldMsg->getMethodDecl(),
+                                     RHS,
+                                     OldMsg->getRightLoc(),
+                                     OldMsg->isImplicit());
+    break;
+
+  case ObjCMessageExpr::Instance:
+    NewMsg =3D ObjCMessageExpr::Create(*Context, OldMsg->getType(),
+                                     OldMsg->getValueKind(),
+                                     OldMsg->getLeftLoc(),
+                                     Base,
+                                     OldMsg->getSelector(),
+                                     SelLocs,
+                                     OldMsg->getMethodDecl(),
+                                     RHS,
+                                     OldMsg->getRightLoc(),
+                                     OldMsg->isImplicit());
+    break;
+
+  case ObjCMessageExpr::SuperClass:
+  case ObjCMessageExpr::SuperInstance:
+    NewMsg =3D ObjCMessageExpr::Create(*Context, OldMsg->getType(),
+                                     OldMsg->getValueKind(),
+                                     OldMsg->getLeftLoc(),
+                                     OldMsg->getSuperLoc(),
+                 OldMsg->getReceiverKind() =3D=3D ObjCMessageExpr::SuperIn=
stance,
+                                     OldMsg->getSuperType(),
+                                     OldMsg->getSelector(),
+                                     SelLocs,
+                                     OldMsg->getMethodDecl(),
+                                     RHS,
+                                     OldMsg->getRightLoc(),
+                                     OldMsg->isImplicit());
+    break;
+  }
+
+  Stmt *Replacement =3D SynthMessageExpr(NewMsg);
+  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
+  return Replacement;
+}
+
+Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseud=
oOp) {
+  SourceRange OldRange =3D PseudoOp->getSourceRange();
+
+  // We just magically know some things about the structure of this
+  // expression.
+  ObjCMessageExpr *OldMsg =3D
+    cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
+
+  // Because the rewriter doesn't allow us to rewrite rewritten code,
+  // we need to suppress rewriting the sub-statements.
+  Expr *Base =3D 0;
+  {
+    DisableReplaceStmtScope S(*this);
+
+    // Rebuild the base expression if we have one.
+    if (OldMsg->getReceiverKind() =3D=3D ObjCMessageExpr::Instance) {
+      Base =3D OldMsg->getInstanceReceiver();
+      Base =3D cast<OpaqueValueExpr>(Base)->getSourceExpr();
+      Base =3D cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
     }
   }
- =20
-  assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
-
-  ObjCMessageExpr *MsgExpr;
-  if (Super)
-    MsgExpr =3D ObjCMessageExpr::Create(*Context,=20
-                                      Ty.getNonReferenceType(),
-                                      Expr::getValueKindForType(Ty),
-                                      /*FIXME?*/SourceLocation(),
-                                      SuperLocation,
-                                      /*IsInstanceSuper=3D*/true,
-                                      SuperTy,
-                                      Sel, SelectorLoc, OMD,
-                                      newStmt,
-                                      /*FIXME:*/SourceLocation());
-  else {
-    // FIXME. Refactor this into common code with that in=20
-    // RewritePropertyOrImplicitGetter
-    assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
-    if (Expr *Exp =3D dyn_cast<Expr>(Receiver))
-      if (PropGetters[Exp])
-        // This allows us to handle chain/nested property/implicit getters.
-        Receiver =3D PropGetters[Exp];
- =20
-    MsgExpr =3D ObjCMessageExpr::Create(*Context,=20
-                                      Ty.getNonReferenceType(),
-                                      Expr::getValueKindForType(Ty),
-                                      /*FIXME: */SourceLocation(),
-                                      cast<Expr>(Receiver),
-                                      Sel, SelectorLoc, OMD,
-                                      newStmt,
-                                      /*FIXME:*/SourceLocation());
+
+  // Intentionally empty.
+  SmallVector<SourceLocation, 1> SelLocs;
+  SmallVector<Expr*, 1> Args;
+
+  ObjCMessageExpr *NewMsg =3D 0;
+  switch (OldMsg->getReceiverKind()) {
+  case ObjCMessageExpr::Class:
+    NewMsg =3D ObjCMessageExpr::Create(*Context, OldMsg->getType(),
+                                     OldMsg->getValueKind(),
+                                     OldMsg->getLeftLoc(),
+                                     OldMsg->getClassReceiverTypeInfo(),
+                                     OldMsg->getSelector(),
+                                     SelLocs,
+                                     OldMsg->getMethodDecl(),
+                                     Args,
+                                     OldMsg->getRightLoc(),
+                                     OldMsg->isImplicit());
+    break;
+
+  case ObjCMessageExpr::Instance:
+    NewMsg =3D ObjCMessageExpr::Create(*Context, OldMsg->getType(),
+                                     OldMsg->getValueKind(),
+                                     OldMsg->getLeftLoc(),
+                                     Base,
+                                     OldMsg->getSelector(),
+                                     SelLocs,
+                                     OldMsg->getMethodDecl(),
+                                     Args,
+                                     OldMsg->getRightLoc(),
+                                     OldMsg->isImplicit());
+    break;
+
+  case ObjCMessageExpr::SuperClass:
+  case ObjCMessageExpr::SuperInstance:
+    NewMsg =3D ObjCMessageExpr::Create(*Context, OldMsg->getType(),
+                                     OldMsg->getValueKind(),
+                                     OldMsg->getLeftLoc(),
+                                     OldMsg->getSuperLoc(),
+                 OldMsg->getReceiverKind() =3D=3D ObjCMessageExpr::SuperIn=
stance,
+                                     OldMsg->getSuperType(),
+                                     OldMsg->getSelector(),
+                                     SelLocs,
+                                     OldMsg->getMethodDecl(),
+                                     Args,
+                                     OldMsg->getRightLoc(),
+                                     OldMsg->isImplicit());
+    break;
   }
-  Stmt *ReplacingStmt =3D SynthMessageExpr(MsgExpr);
-
-  // Now do the actual rewrite.
-  ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
-  //delete BinOp;
-  // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
-  // to things that stay around.
-  Context->Deallocate(MsgExpr);
-  return ReplacingStmt;
-}
-
-Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefEx=
pr) {
-  // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGe=
tter.
-  // This allows us to reuse all the fun and games in SynthMessageExpr().
-  Stmt *Receiver =3D 0;
-  ObjCMethodDecl *OMD =3D 0;
-  QualType Ty;
-  Selector Sel;
-  bool Super =3D false;
-  QualType SuperTy;
-  SourceLocation SuperLocation;
-  SourceLocation SelectorLoc;
-  if (ObjCPropertyRefExpr *PropRefExpr =3D=20
-        dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
-    SelectorLoc =3D PropRefExpr->getLocation();
-    if (PropRefExpr->isExplicitProperty()) {
-      ObjCPropertyDecl *PDecl =3D PropRefExpr->getExplicitProperty();
-      OMD =3D PDecl->getGetterMethodDecl();
-      Ty =3D PDecl->getType();
-      Sel =3D PDecl->getGetterName();
-    } else {
-      OMD =3D PropRefExpr->getImplicitPropertyGetter();
-      Sel =3D OMD->getSelector();
-      Ty =3D PropRefExpr->getType();
-    }
-    Super =3D PropRefExpr->isSuperReceiver();
-    if (!Super)
-      Receiver =3D PropRefExpr->getBase();
-    else {
-      SuperTy =3D PropRefExpr->getSuperReceiverType();
-      SuperLocation =3D PropRefExpr->getReceiverLocation();
-    }
-  }
- =20
-  assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
- =20
-  ObjCMessageExpr *MsgExpr;
-  if (Super)
-    MsgExpr =3D ObjCMessageExpr::Create(*Context,=20
-                                      Ty.getNonReferenceType(),
-                                      Expr::getValueKindForType(Ty),
-                                      PropOrGetterRefExpr->getLocStart(),
-                                      SuperLocation,
-                                      /*IsInstanceSuper=3D*/true,
-                                      SuperTy,
-                                      Sel, SelectorLoc, OMD,
-                                      ArrayRef<Expr*>(),=20
-                                      PropOrGetterRefExpr->getLocEnd());
-  else {
-    assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is nul=
l");
-    if (Expr *Exp =3D dyn_cast<Expr>(Receiver))
-      if (PropGetters[Exp])
-        // This allows us to handle chain/nested property/implicit getters.
-        Receiver =3D PropGetters[Exp];
-    MsgExpr =3D ObjCMessageExpr::Create(*Context,=20
-                                      Ty.getNonReferenceType(),
-                                      Expr::getValueKindForType(Ty),
-                                      PropOrGetterRefExpr->getLocStart(),
-                                      cast<Expr>(Receiver),
-                                      Sel, SelectorLoc, OMD,
-                                      ArrayRef<Expr*>(),=20
-                                      PropOrGetterRefExpr->getLocEnd());
-  }
-
-  Stmt *ReplacingStmt =3D SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
-                                         MsgExpr->getLocEnd());
-
-  if (!PropParentMap)
-    PropParentMap =3D new ParentMap(CurrentBody);
-  bool NestedPropertyRef =3D false;
-  Stmt *Parent =3D PropParentMap->getParent(PropOrGetterRefExpr);
-  ImplicitCastExpr*ICE=3D0;
-  if (Parent)
-    if ((ICE =3D dyn_cast<ImplicitCastExpr>(Parent))) {
-      assert((ICE->getCastKind() =3D=3D CK_GetObjCProperty)
-             && "RewritePropertyOrImplicitGetter");
-      Parent =3D PropParentMap->getParent(Parent);
-      NestedPropertyRef =3D (Parent && isa<ObjCPropertyRefExpr>(Parent));
-    }
-  if (NestedPropertyRef) {
-    // We stash away the ReplacingStmt since actually doing the
-    // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
-    PropGetters[ICE] =3D ReplacingStmt;
-    // NOTE: We don't want to call MsgExpr->Destroy(), as it holds referen=
ces
-    // to things that stay around.
-    Context->Deallocate(MsgExpr);
-    return PropOrGetterRefExpr; // return the original...
-  } else {
-    ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
-    // delete PropRefExpr; elsewhere...
-    // NOTE: We don't want to call MsgExpr->Destroy(), as it holds referen=
ces
-    // to things that stay around.
-    Context->Deallocate(MsgExpr);
-    return ReplacingStmt;
-  }
-}
-
-Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
-                                          SourceLocation OrigStart,
-                                          bool &replaced) {
-  ObjCIvarDecl *D =3D IV->getDecl();
-  const Expr *BaseExpr =3D IV->getBase();
-  if (CurMethodDef) {
-    if (BaseExpr->getType()->isObjCObjectPointerType()) {
-      const ObjCInterfaceType *iFaceDecl =3D
-        dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
-      assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
-      // lookup which class implements the instance variable.
-      ObjCInterfaceDecl *clsDeclared =3D 0;
-      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
-                                                   clsDeclared);
-      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
-
-      // Synthesize an explicit cast to gain access to the ivar.
-      std::string RecName =3D clsDeclared->getIdentifier()->getName();
-      RecName +=3D "_IMPL";
-      IdentifierInfo *II =3D &Context->Idents.get(RecName);
-      RecordDecl *RD =3D RecordDecl::Create(*Context, TTK_Struct, TUDecl,
-                                          SourceLocation(), SourceLocation=
(),
-                                          II);
-      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
-      QualType castT =3D Context->getPointerType(Context->getTagDeclType(R=
D));
-      CastExpr *castExpr =3D NoTypeInfoCStyleCastExpr(Context, castT,
-                                                    CK_BitCast,
-                                                    IV->getBase());
-      // Don't forget the parens to enforce the proper binding.
-      ParenExpr *PE =3D new (Context) ParenExpr(IV->getBase()->getLocStart=
(),
-                                              IV->getBase()->getLocEnd(),
-                                              castExpr);
-      replaced =3D true;
-      if (IV->isFreeIvar() &&
-          CurMethodDef->getClassInterface() =3D=3D iFaceDecl->getDecl()) {
-        MemberExpr *ME =3D new (Context) MemberExpr(PE, true, D,
-                                                  IV->getLocation(),
-                                                  D->getType(),
-                                                  VK_LValue, OK_Ordinary);
-        // delete IV; leak for now, see RewritePropertyOrImplicitSetter() =
usage for more info.
-        return ME;
-      }
-      // Get the new text
-      // Cannot delete IV->getBase(), since PE points to it.
-      // Replace the old base with the cast. This is important when doing
-      // embedded rewrites. For example, [newInv->_container addObject:0].
-      IV->setBase(PE);
-      return IV;
-    }
-  } else { // we are outside a method.
-    assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside =
a method");
-
-    // Explicit ivar refs need to have a cast inserted.
-    // FIXME: consider sharing some of this code with the code above.
-    if (BaseExpr->getType()->isObjCObjectPointerType()) {
-      const ObjCInterfaceType *iFaceDecl =3D
-        dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
-      // lookup which class implements the instance variable.
-      ObjCInterfaceDecl *clsDeclared =3D 0;
-      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
-                                                   clsDeclared);
-      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
-
-      // Synthesize an explicit cast to gain access to the ivar.
-      std::string RecName =3D clsDeclared->getIdentifier()->getName();
-      RecName +=3D "_IMPL";
-      IdentifierInfo *II =3D &Context->Idents.get(RecName);
-      RecordDecl *RD =3D RecordDecl::Create(*Context, TTK_Struct, TUDecl,
-                                          SourceLocation(), SourceLocation=
(),
-                                          II);
-      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
-      QualType castT =3D Context->getPointerType(Context->getTagDeclType(R=
D));
-      CastExpr *castExpr =3D NoTypeInfoCStyleCastExpr(Context, castT,
-                                                    CK_BitCast,
-                                                    IV->getBase());
-      // Don't forget the parens to enforce the proper binding.
-      ParenExpr *PE =3D new (Context) ParenExpr(IV->getBase()->getLocStart=
(),
-                                    IV->getBase()->getLocEnd(), castExpr);
-      replaced =3D true;
-      // Cannot delete IV->getBase(), since PE points to it.
-      // Replace the old base with the cast. This is important when doing
-      // embedded rewrites. For example, [newInv->_container addObject:0].
-      IV->setBase(PE);
-      return IV;
-    }
-  }
-  return IV;
-}
-
-Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
-  for (Stmt::child_range CI =3D S->children(); CI; ++CI) {
-    if (*CI) {
-      Stmt *newStmt =3D RewriteObjCNestedIvarRefExpr(*CI, replaced);
-      if (newStmt)
-        *CI =3D newStmt;
-    }
-  }
-  if (ObjCIvarRefExpr *IvarRefExpr =3D dyn_cast<ObjCIvarRefExpr>(S)) {
-    SourceRange OrigStmtRange =3D S->getSourceRange();
-    Stmt *newStmt =3D RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.ge=
tBegin(),
-                                           replaced);
-    return newStmt;
-  }=20
-  if (ObjCMessageExpr *MsgRefExpr =3D dyn_cast<ObjCMessageExpr>(S)) {
-    Stmt *newStmt =3D SynthMessageExpr(MsgRefExpr);
-    return newStmt;
-  }
-  return S;
+
+  Stmt *Replacement =3D SynthMessageExpr(NewMsg);
+  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
+  return Replacement;
 }
=20
 /// SynthCountByEnumWithState - To print:
@@ -1571,7 +1414,7 @@
 ///                        sel_registerName(
 ///                          "countByEnumeratingWithState:objects:count:"),
 ///                        &enumState,
-///                        (id *)items, (unsigned int)16)
+///                        (id *)__rw_items, (unsigned int)16)
 ///
 void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
   buf +=3D "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState=
 *, "
@@ -1581,7 +1424,7 @@
   buf +=3D "sel_registerName(\"countByEnumeratingWithState:objects:count:\=
"),";
   buf +=3D "\n\t\t";
   buf +=3D "&enumState, "
-         "(id *)items, (unsigned int)16)";
+         "(id *)__rw_items, (unsigned int)16)";
 }
=20
 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
@@ -1626,10 +1469,10 @@
 /// {
 ///   type elem;
 ///   struct __objcFastEnumerationState enumState =3D { 0 };
-///   id items[16];
+///   id __rw_items[16];
 ///   id l_collection =3D (id)collection;
 ///   unsigned long limit =3D [l_collection countByEnumeratingWithState:&e=
numState
-///                                       objects:items count:16];
+///                                       objects:__rw_items count:16];
 /// if (limit) {
 ///   unsigned long startMutations =3D *enumState.mutationsPtr;
 ///   do {
@@ -1642,7 +1485,7 @@
 ///             __continue_label: ;
 ///        } while (counter < limit);
 ///   } while (limit =3D [l_collection countByEnumeratingWithState:&enumSt=
ate
-///                                  objects:items count:16]);
+///                                  objects:__rw_items count:16]);
 ///   elem =3D nil;
 ///   __break_label: ;
 ///  }
@@ -1694,8 +1537,8 @@
=20
   // struct __objcFastEnumerationState enumState =3D { 0 };
   buf +=3D "struct __objcFastEnumerationState enumState =3D { 0 };\n\t";
-  // id items[16];
-  buf +=3D "id items[16];\n\t";
+  // id __rw_items[16];
+  buf +=3D "id __rw_items[16];\n\t";
   // id l_collection =3D (id)
   buf +=3D "id l_collection =3D (id)";
   // Find start location of 'collection' the hard way!
@@ -1720,7 +1563,7 @@
   buf =3D ";\n\t";
=20
   // unsigned long limit =3D [l_collection countByEnumeratingWithState:&en=
umState
-  //                                   objects:items count:16];
+  //                                   objects:__rw_items count:16];
   // which is synthesized into:
   // unsigned int limit =3D
   // ((unsigned int (*)
@@ -1729,7 +1572,7 @@
   //                        sel_registerName(
   //                          "countByEnumeratingWithState:objects:count:"=
),
   //                        (struct __objcFastEnumerationState *)&state,
-  //                        (id *)items, (unsigned int)16);
+  //                        (id *)__rw_items, (unsigned int)16);
   buf +=3D "unsigned long limit =3D\n\t\t";
   SynthCountByEnumWithState(buf);
   buf +=3D ";\n\t";
@@ -1758,7 +1601,7 @@
   ///            __continue_label: ;
   ///        } while (counter < limit);
   ///   } while (limit =3D [l_collection countByEnumeratingWithState:&enum=
State
-  ///                                  objects:items count:16]);
+  ///                                  objects:__rw_items count:16]);
   ///   elem =3D nil;
   ///   __break_label: ;
   ///  }
@@ -2200,8 +2043,8 @@
   QualType msgSendType =3D FD->getType();
=20
   // Create a reference to the objc_msgSend() declaration.
-  DeclRefExpr *DRE =3D
-    new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation()=
);
+  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(FD, false, msgSendType,
+                                               VK_LValue, SourceLocation()=
);
=20
   // Now, we cast the reference to a pointer to the objc_msgSend type.
   QualType pToFunc =3D Context->getPointerType(msgSendType);
@@ -2667,7 +2510,7 @@
                                                    false);
 }
=20
-// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
+// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
 void RewriteObjC::SynthGetMetaClassFunctionDecl() {
   IdentifierInfo *getClassIdent =3D &Context->Idents.get("objc_getMetaClas=
s");
   SmallVector<QualType, 16> ArgTys;
@@ -2714,7 +2557,7 @@
   VarDecl *NewVD =3D VarDecl::Create(*Context, TUDecl, SourceLocation(),
                                    SourceLocation(), &Context->Idents.get(=
S),
                                    strType, 0, SC_Static, SC_None);
-  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
+  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(NewVD, false, strType, VK=
_LValue,
                                                SourceLocation());
   Expr *Unop =3D new (Context) UnaryOperator(DRE, UO_AddrOf,
                                  Context->getPointerType(DRE->getType()),
@@ -2842,6 +2685,7 @@
       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
                                CK_BitCast,
                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
+                                             false,
                                              Context->getObjCIdType(),
                                              VK_RValue,
                                              SourceLocation()))
@@ -2862,7 +2706,7 @@
     // (Class)objc_getClass("CurrentClass")
     CastExpr *ArgExpr =3D NoTypeInfoCStyleCastExpr(Context,
                                              Context->getObjCClassType(),
-                                             CK_CPointerToObjCPointerCast,=
 Cls);
+                                             CK_BitCast, Cls);
     ClsExprs.clear();
     ClsExprs.push_back(ArgExpr);
     Cls =3D SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
@@ -2883,7 +2727,7 @@
       SynthSuperContructorFunctionDecl();
       // Simulate a contructor call...
       DeclRefExpr *DRE =3D new (Context) DeclRefExpr(SuperContructorFuncti=
onDecl,
-                                                   superType, VK_LValue,
+                                                   false, superType, VK_LV=
alue,
                                                    SourceLocation());
       SuperRep =3D new (Context) CallExpr(*Context, DRE, &InitExprs[0],
                                         InitExprs.size(),
@@ -2953,6 +2797,7 @@
       NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
                                CK_BitCast,
                    new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
+                                             false,
                                              Context->getObjCIdType(),
                                              VK_RValue, SourceLocation()))
                         ); // set the 'receiver'.
@@ -2992,7 +2837,7 @@
       SynthSuperContructorFunctionDecl();
       // Simulate a contructor call...
       DeclRefExpr *DRE =3D new (Context) DeclRefExpr(SuperContructorFuncti=
onDecl,
-                                                   superType, VK_LValue,
+                                                   false, superType, VK_LV=
alue,
                                                    SourceLocation());
       SuperRep =3D new (Context) CallExpr(*Context, DRE, &InitExprs[0],
                                         InitExprs.size(),
@@ -3144,7 +2989,7 @@
   QualType msgSendType =3D MsgSendFlavor->getType();
=20
   // Create a reference to the objc_msgSend() declaration.
-  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(MsgSendFlavor, msgSendTyp=
e,
+  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(MsgSendFlavor, false, msg=
SendType,
                                                VK_LValue, SourceLocation()=
);
=20
   // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
@@ -3180,7 +3025,8 @@
     // method's return type.
=20
     // Create a reference to the objc_msgSend_stret() declaration.
-    DeclRefExpr *STDRE =3D new (Context) DeclRefExpr(MsgSendStretFlavor, m=
sgSendType,
+    DeclRefExpr *STDRE =3D new (Context) DeclRefExpr(MsgSendStretFlavor,
+                                                   false, msgSendType,
                                                    VK_LValue, SourceLocati=
on());
     // Need to cast objc_msgSend_stret to "void *" (see above comment).
     cast =3D NoTypeInfoCStyleCastExpr(Context,
@@ -3268,8 +3114,8 @@
   VarDecl *VD =3D VarDecl::Create(*Context, TUDecl, SourceLocation(),
                                 SourceLocation(), ID, getProtocolType(), 0,
                                 SC_Extern, SC_None);
-  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(VD, getProtocolType(), VK=
_LValue,
-                                               SourceLocation());
+  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(VD, false, getProtocolTyp=
e(),
+                                               VK_LValue, SourceLocation()=
);
   Expr *DerefExpr =3D new (Context) UnaryOperator(DRE, UO_AddrOf,
                              Context->getPointerType(DRE->getType()),
                              VK_RValue, OK_Ordinary, SourceLocation());
@@ -3277,7 +3123,7 @@
                                                 CK_BitCast,
                                                 DerefExpr);
   ReplaceStmt(Exp, castExpr);
-  ProtocolExprDecls.insert(Exp->getProtocol());
+  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
   // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage=
 for more info.
   return castExpr;
=20
@@ -3309,9 +3155,9 @@
   return false;
 }
=20
-/// SynthesizeObjCInternalStruct - Rewrite one internal struct correspondi=
ng to
+/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding =
to
 /// an objective-c class with ivars.
-void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
+void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
                                                std::string &Result) {
   assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
   assert(CDecl->getName() !=3D "" &&
@@ -3322,14 +3168,14 @@
   ObjCInterfaceDecl *RCDecl =3D CDecl->getSuperClass();
   int NumIvars =3D CDecl->ivar_size();
   SourceLocation LocStart =3D CDecl->getLocStart();
-  SourceLocation LocEnd =3D CDecl->getLocEnd();
+  SourceLocation LocEnd =3D CDecl->getEndOfDefinitionLoc();
=20
   const char *startBuf =3D SM->getCharacterData(LocStart);
   const char *endBuf =3D SM->getCharacterData(LocEnd);
=20
   // If no ivars and no root or if its root, directly or indirectly,
   // have no ivars (thus not synthesized) then no need to synthesize this =
class.
-  if ((CDecl->isForwardDecl() || NumIvars =3D=3D 0) &&
+  if ((!CDecl->isThisDeclarationADefinition() || NumIvars =3D=3D 0) &&
       (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
     endBuf +=3D Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
     ReplaceText(LocStart, endBuf-startBuf, Result);
@@ -3441,667 +3287,10 @@
     llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStr=
uct");
 }
=20
-// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
-/// class methods.
-template<typename MethodIterator>
-void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
-                                             MethodIterator MethodEnd,
-                                             bool IsInstanceMethod,
-                                             StringRef prefix,
-                                             StringRef ClassName,
-                                             std::string &Result) {
-  if (MethodBegin =3D=3D MethodEnd) return;
-
-  if (!objc_impl_method) {
-    /* struct _objc_method {
-       SEL _cmd;
-       char *method_types;
-       void *_imp;
-       }
-     */
-    Result +=3D "\nstruct _objc_method {\n";
-    Result +=3D "\tSEL _cmd;\n";
-    Result +=3D "\tchar *method_types;\n";
-    Result +=3D "\tvoid *_imp;\n";
-    Result +=3D "};\n";
-
-    objc_impl_method =3D true;
-  }
-
-  // Build _objc_method_list for class's methods if needed
-
-  /* struct  {
-   struct _objc_method_list *next_method;
-   int method_count;
-   struct _objc_method method_list[];
-   }
-   */
-  unsigned NumMethods =3D std::distance(MethodBegin, MethodEnd);
-  Result +=3D "\nstatic struct {\n";
-  Result +=3D "\tstruct _objc_method_list *next_method;\n";
-  Result +=3D "\tint method_count;\n";
-  Result +=3D "\tstruct _objc_method method_list[";
-  Result +=3D utostr(NumMethods);
-  Result +=3D "];\n} _OBJC_";
-  Result +=3D prefix;
-  Result +=3D IsInstanceMethod ? "INSTANCE" : "CLASS";
-  Result +=3D "_METHODS_";
-  Result +=3D ClassName;
-  Result +=3D " __attribute__ ((used, section (\"__OBJC, __";
-  Result +=3D IsInstanceMethod ? "inst" : "cls";
-  Result +=3D "_meth\")))=3D ";
-  Result +=3D "{\n\t0, " + utostr(NumMethods) + "\n";
-
-  Result +=3D "\t,{{(SEL)\"";
-  Result +=3D (*MethodBegin)->getSelector().getAsString().c_str();
-  std::string MethodTypeString;
-  Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
-  Result +=3D "\", \"";
-  Result +=3D MethodTypeString;
-  Result +=3D "\", (void *)";
-  Result +=3D MethodInternalNames[*MethodBegin];
-  Result +=3D "}\n";
-  for (++MethodBegin; MethodBegin !=3D MethodEnd; ++MethodBegin) {
-    Result +=3D "\t  ,{(SEL)\"";
-    Result +=3D (*MethodBegin)->getSelector().getAsString().c_str();
-    std::string MethodTypeString;
-    Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
-    Result +=3D "\", \"";
-    Result +=3D MethodTypeString;
-    Result +=3D "\", (void *)";
-    Result +=3D MethodInternalNames[*MethodBegin];
-    Result +=3D "}\n";
-  }
-  Result +=3D "\t }\n};\n";
-}
-
-/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
-void RewriteObjC::
-RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
-                            StringRef ClassName, std::string &Result) {
-  static bool objc_protocol_methods =3D false;
-
-  // Output struct protocol_methods holder of method selector and type.
-  if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
-    /* struct protocol_methods {
-     SEL _cmd;
-     char *method_types;
-     }
-     */
-    Result +=3D "\nstruct _protocol_methods {\n";
-    Result +=3D "\tstruct objc_selector *_cmd;\n";
-    Result +=3D "\tchar *method_types;\n";
-    Result +=3D "};\n";
-
-    objc_protocol_methods =3D true;
-  }
-  // Do not synthesize the protocol more than once.
-  if (ObjCSynthesizedProtocols.count(PDecl))
-    return;
-
-    if (PDecl->instmeth_begin() !=3D PDecl->instmeth_end()) {
-      unsigned NumMethods =3D std::distance(PDecl->instmeth_begin(),
-                                          PDecl->instmeth_end());
-    /* struct _objc_protocol_method_list {
-     int protocol_method_count;
-     struct protocol_methods protocols[];
-     }
-     */
-    Result +=3D "\nstatic struct {\n";
-    Result +=3D "\tint protocol_method_count;\n";
-    Result +=3D "\tstruct _protocol_methods protocol_methods[";
-    Result +=3D utostr(NumMethods);
-    Result +=3D "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
-    Result +=3D PDecl->getNameAsString();
-    Result +=3D " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth=
\")))=3D "
-      "{\n\t" + utostr(NumMethods) + "\n";
-
-    // Output instance methods declared in this protocol.
-    for (ObjCProtocolDecl::instmeth_iterator
-           I =3D PDecl->instmeth_begin(), E =3D PDecl->instmeth_end();
-         I !=3D E; ++I) {
-      if (I =3D=3D PDecl->instmeth_begin())
-        Result +=3D "\t  ,{{(struct objc_selector *)\"";
-      else
-        Result +=3D "\t  ,{(struct objc_selector *)\"";
-      Result +=3D (*I)->getSelector().getAsString();
-      std::string MethodTypeString;
-      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
-      Result +=3D "\", \"";
-      Result +=3D MethodTypeString;
-      Result +=3D "\"}\n";
-    }
-    Result +=3D "\t }\n};\n";
-  }
-
-  // Output class methods declared in this protocol.
-  unsigned NumMethods =3D std::distance(PDecl->classmeth_begin(),
-                                      PDecl->classmeth_end());
-  if (NumMethods > 0) {
-    /* struct _objc_protocol_method_list {
-     int protocol_method_count;
-     struct protocol_methods protocols[];
-     }
-     */
-    Result +=3D "\nstatic struct {\n";
-    Result +=3D "\tint protocol_method_count;\n";
-    Result +=3D "\tstruct _protocol_methods protocol_methods[";
-    Result +=3D utostr(NumMethods);
-    Result +=3D "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
-    Result +=3D PDecl->getNameAsString();
-    Result +=3D " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\=
")))=3D "
-           "{\n\t";
-    Result +=3D utostr(NumMethods);
-    Result +=3D "\n";
-
-    // Output instance methods declared in this protocol.
-    for (ObjCProtocolDecl::classmeth_iterator
-           I =3D PDecl->classmeth_begin(), E =3D PDecl->classmeth_end();
-         I !=3D E; ++I) {
-      if (I =3D=3D PDecl->classmeth_begin())
-        Result +=3D "\t  ,{{(struct objc_selector *)\"";
-      else
-        Result +=3D "\t  ,{(struct objc_selector *)\"";
-      Result +=3D (*I)->getSelector().getAsString();
-      std::string MethodTypeString;
-      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
-      Result +=3D "\", \"";
-      Result +=3D MethodTypeString;
-      Result +=3D "\"}\n";
-    }
-    Result +=3D "\t }\n};\n";
-  }
-
-  // Output:
-  /* struct _objc_protocol {
-   // Objective-C 1.0 extensions
-   struct _objc_protocol_extension *isa;
-   char *protocol_name;
-   struct _objc_protocol **protocol_list;
-   struct _objc_protocol_method_list *instance_methods;
-   struct _objc_protocol_method_list *class_methods;
-   };
-   */
-  static bool objc_protocol =3D false;
-  if (!objc_protocol) {
-    Result +=3D "\nstruct _objc_protocol {\n";
-    Result +=3D "\tstruct _objc_protocol_extension *isa;\n";
-    Result +=3D "\tchar *protocol_name;\n";
-    Result +=3D "\tstruct _objc_protocol **protocol_list;\n";
-    Result +=3D "\tstruct _objc_protocol_method_list *instance_methods;\n";
-    Result +=3D "\tstruct _objc_protocol_method_list *class_methods;\n";
-    Result +=3D "};\n";
-
-    objc_protocol =3D true;
-  }
-
-  Result +=3D "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
-  Result +=3D PDecl->getNameAsString();
-  Result +=3D " __attribute__ ((used, section (\"__OBJC, __protocol\")))=
=3D "
-    "{\n\t0, \"";
-  Result +=3D PDecl->getNameAsString();
-  Result +=3D "\", 0, ";
-  if (PDecl->instmeth_begin() !=3D PDecl->instmeth_end()) {
-    Result +=3D "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INST=
ANCE_METHODS_";
-    Result +=3D PDecl->getNameAsString();
-    Result +=3D ", ";
-  }
-  else
-    Result +=3D "0, ";
-  if (PDecl->classmeth_begin() !=3D PDecl->classmeth_end()) {
-    Result +=3D "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLAS=
S_METHODS_";
-    Result +=3D PDecl->getNameAsString();
-    Result +=3D "\n";
-  }
-  else
-    Result +=3D "0\n";
-  Result +=3D "};\n";
-
-  // Mark this protocol as having been generated.
-  if (!ObjCSynthesizedProtocols.insert(PDecl))
-    llvm_unreachable("protocol already synthesized");
-
-}
-
-void RewriteObjC::
-RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocol=
s,
-                                StringRef prefix, StringRef ClassName,
-                                std::string &Result) {
-  if (Protocols.empty()) return;
-
-  for (unsigned i =3D 0; i !=3D Protocols.size(); i++)
-    RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
-
-  // Output the top lovel protocol meta-data for the class.
-  /* struct _objc_protocol_list {
-   struct _objc_protocol_list *next;
-   int    protocol_count;
-   struct _objc_protocol *class_protocols[];
-   }
-   */
-  Result +=3D "\nstatic struct {\n";
-  Result +=3D "\tstruct _objc_protocol_list *next;\n";
-  Result +=3D "\tint    protocol_count;\n";
-  Result +=3D "\tstruct _objc_protocol *class_protocols[";
-  Result +=3D utostr(Protocols.size());
-  Result +=3D "];\n} _OBJC_";
-  Result +=3D prefix;
-  Result +=3D "_PROTOCOLS_";
-  Result +=3D ClassName;
-  Result +=3D " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")=
))=3D "
-    "{\n\t0, ";
-  Result +=3D utostr(Protocols.size());
-  Result +=3D "\n";
-
-  Result +=3D "\t,{&_OBJC_PROTOCOL_";
-  Result +=3D Protocols[0]->getNameAsString();
-  Result +=3D " \n";
-
-  for (unsigned i =3D 1; i !=3D Protocols.size(); i++) {
-    Result +=3D "\t ,&_OBJC_PROTOCOL_";
-    Result +=3D Protocols[i]->getNameAsString();
-    Result +=3D "\n";
-  }
-  Result +=3D "\t }\n};\n";
-}
-
-
-/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
-/// implementation.
-void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
-                                              std::string &Result) {
-  ObjCInterfaceDecl *ClassDecl =3D IDecl->getClassInterface();
-  // Find category declaration for this implementation.
-  ObjCCategoryDecl *CDecl;
-  for (CDecl =3D ClassDecl->getCategoryList(); CDecl;
-       CDecl =3D CDecl->getNextClassCategory())
-    if (CDecl->getIdentifier() =3D=3D IDecl->getIdentifier())
-      break;
-
-  std::string FullCategoryName =3D ClassDecl->getNameAsString();
-  FullCategoryName +=3D '_';
-  FullCategoryName +=3D IDecl->getNameAsString();
-
-  // Build _objc_method_list for class's instance methods if needed
-  SmallVector<ObjCMethodDecl *, 32>
-    InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
-
-  // If any of our property implementations have associated getters or
-  // setters, produce metadata for them as well.
-  for (ObjCImplDecl::propimpl_iterator Prop =3D IDecl->propimpl_begin(),
-         PropEnd =3D IDecl->propimpl_end();
-       Prop !=3D PropEnd; ++Prop) {
-    if ((*Prop)->getPropertyImplementation() =3D=3D ObjCPropertyImplDecl::=
Dynamic)
-      continue;
-    if (!(*Prop)->getPropertyIvarDecl())
-      continue;
-    ObjCPropertyDecl *PD =3D (*Prop)->getPropertyDecl();
-    if (!PD)
-      continue;
-    if (ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl())
-      InstanceMethods.push_back(Getter);
-    if (PD->isReadOnly())
-      continue;
-    if (ObjCMethodDecl *Setter =3D PD->getSetterMethodDecl())
-      InstanceMethods.push_back(Setter);
-  }
-  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(=
),
-                             true, "CATEGORY_", FullCategoryName.c_str(),
-                             Result);
-
-  // Build _objc_method_list for class's class methods if needed
-  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_en=
d(),
-                             false, "CATEGORY_", FullCategoryName.c_str(),
-                             Result);
-
-  // Protocols referenced in class declaration?
-  // Null CDecl is case of a category implementation with no category inte=
rface
-  if (CDecl)
-    RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATE=
GORY",
-                                    FullCategoryName, Result);
-  /* struct _objc_category {
-   char *category_name;
-   char *class_name;
-   struct _objc_method_list *instance_methods;
-   struct _objc_method_list *class_methods;
-   struct _objc_protocol_list *protocols;
-   // Objective-C 1.0 extensions
-   uint32_t size;     // sizeof (struct _objc_category)
-   struct _objc_property_list *instance_properties;  // category's own
-                                                     // @property decl.
-   };
-   */
-
-  static bool objc_category =3D false;
-  if (!objc_category) {
-    Result +=3D "\nstruct _objc_category {\n";
-    Result +=3D "\tchar *category_name;\n";
-    Result +=3D "\tchar *class_name;\n";
-    Result +=3D "\tstruct _objc_method_list *instance_methods;\n";
-    Result +=3D "\tstruct _objc_method_list *class_methods;\n";
-    Result +=3D "\tstruct _objc_protocol_list *protocols;\n";
-    Result +=3D "\tunsigned int size;\n";
-    Result +=3D "\tstruct _objc_property_list *instance_properties;\n";
-    Result +=3D "};\n";
-    objc_category =3D true;
-  }
-  Result +=3D "\nstatic struct _objc_category _OBJC_CATEGORY_";
-  Result +=3D FullCategoryName;
-  Result +=3D " __attribute__ ((used, section (\"__OBJC, __category\")))=
=3D {\n\t\"";
-  Result +=3D IDecl->getNameAsString();
-  Result +=3D "\"\n\t, \"";
-  Result +=3D ClassDecl->getNameAsString();
-  Result +=3D "\"\n";
-
-  if (IDecl->instmeth_begin() !=3D IDecl->instmeth_end()) {
-    Result +=3D "\t, (struct _objc_method_list *)"
-           "&_OBJC_CATEGORY_INSTANCE_METHODS_";
-    Result +=3D FullCategoryName;
-    Result +=3D "\n";
-  }
-  else
-    Result +=3D "\t, 0\n";
-  if (IDecl->classmeth_begin() !=3D IDecl->classmeth_end()) {
-    Result +=3D "\t, (struct _objc_method_list *)"
-           "&_OBJC_CATEGORY_CLASS_METHODS_";
-    Result +=3D FullCategoryName;
-    Result +=3D "\n";
-  }
-  else
-    Result +=3D "\t, 0\n";
-
-  if (CDecl && CDecl->protocol_begin() !=3D CDecl->protocol_end()) {
-    Result +=3D "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCO=
LS_";
-    Result +=3D FullCategoryName;
-    Result +=3D "\n";
-  }
-  else
-    Result +=3D "\t, 0\n";
-  Result +=3D "\t, sizeof(struct _objc_category), 0\n};\n";
-}
-
-/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation =
of
-/// ivar offset.
-void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
-                                                  std::string &Result) {
-  if (ivar->isBitField()) {
-    // FIXME: The hack below doesn't work for bitfields. For now, we simply
-    // place all bitfields at offset 0.
-    Result +=3D "0";
-  } else {
-    Result +=3D "__OFFSETOFIVAR__(struct ";
-    Result +=3D ivar->getContainingInterface()->getNameAsString();
-    if (LangOpts.MicrosoftExt)
-      Result +=3D "_IMPL";
-    Result +=3D ", ";
-    Result +=3D ivar->getNameAsString();
-    Result +=3D ")";
-  }
-}
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Meta Data Emission
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
-                                           std::string &Result) {
-  ObjCInterfaceDecl *CDecl =3D IDecl->getClassInterface();
-
-  // Explicitly declared @interface's are already synthesized.
-  if (CDecl->isImplicitInterfaceDecl()) {
-    // FIXME: Implementation of a class with no @interface (legacy) doese =
not
-    // produce correct synthesis as yet.
-    SynthesizeObjCInternalStruct(CDecl, Result);
-  }
-
-  // Build _objc_ivar_list metadata for classes ivars if needed
-  unsigned NumIvars =3D !IDecl->ivar_empty()
-                      ? IDecl->ivar_size()
-                      : (CDecl ? CDecl->ivar_size() : 0);
-  if (NumIvars > 0) {
-    static bool objc_ivar =3D false;
-    if (!objc_ivar) {
-      /* struct _objc_ivar {
-          char *ivar_name;
-          char *ivar_type;
-          int ivar_offset;
-        };
-       */
-      Result +=3D "\nstruct _objc_ivar {\n";
-      Result +=3D "\tchar *ivar_name;\n";
-      Result +=3D "\tchar *ivar_type;\n";
-      Result +=3D "\tint ivar_offset;\n";
-      Result +=3D "};\n";
-
-      objc_ivar =3D true;
-    }
-
-    /* struct {
-       int ivar_count;
-       struct _objc_ivar ivar_list[nIvars];
-       };
-     */
-    Result +=3D "\nstatic struct {\n";
-    Result +=3D "\tint ivar_count;\n";
-    Result +=3D "\tstruct _objc_ivar ivar_list[";
-    Result +=3D utostr(NumIvars);
-    Result +=3D "];\n} _OBJC_INSTANCE_VARIABLES_";
-    Result +=3D IDecl->getNameAsString();
-    Result +=3D " __attribute__ ((used, section (\"__OBJC, __instance_vars=
\")))=3D "
-      "{\n\t";
-    Result +=3D utostr(NumIvars);
-    Result +=3D "\n";
-
-    ObjCInterfaceDecl::ivar_iterator IVI, IVE;
-    SmallVector<ObjCIvarDecl *, 8> IVars;
-    if (!IDecl->ivar_empty()) {
-      for (ObjCInterfaceDecl::ivar_iterator
-             IV =3D IDecl->ivar_begin(), IVEnd =3D IDecl->ivar_end();
-           IV !=3D IVEnd; ++IV)
-        IVars.push_back(*IV);
-      IVI =3D IDecl->ivar_begin();
-      IVE =3D IDecl->ivar_end();
-    } else {
-      IVI =3D CDecl->ivar_begin();
-      IVE =3D CDecl->ivar_end();
-    }
-    Result +=3D "\t,{{\"";
-    Result +=3D (*IVI)->getNameAsString();
-    Result +=3D "\", \"";
-    std::string TmpString, StrEncoding;
-    Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
-    QuoteDoublequotes(TmpString, StrEncoding);
-    Result +=3D StrEncoding;
-    Result +=3D "\", ";
-    SynthesizeIvarOffsetComputation(*IVI, Result);
-    Result +=3D "}\n";
-    for (++IVI; IVI !=3D IVE; ++IVI) {
-      Result +=3D "\t  ,{\"";
-      Result +=3D (*IVI)->getNameAsString();
-      Result +=3D "\", \"";
-      std::string TmpString, StrEncoding;
-      Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
-      QuoteDoublequotes(TmpString, StrEncoding);
-      Result +=3D StrEncoding;
-      Result +=3D "\", ";
-      SynthesizeIvarOffsetComputation((*IVI), Result);
-      Result +=3D "}\n";
-    }
-
-    Result +=3D "\t }\n};\n";
-  }
-
-  // Build _objc_method_list for class's instance methods if needed
-  SmallVector<ObjCMethodDecl *, 32>
-    InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
-
-  // If any of our property implementations have associated getters or
-  // setters, produce metadata for them as well.
-  for (ObjCImplDecl::propimpl_iterator Prop =3D IDecl->propimpl_begin(),
-         PropEnd =3D IDecl->propimpl_end();
-       Prop !=3D PropEnd; ++Prop) {
-    if ((*Prop)->getPropertyImplementation() =3D=3D ObjCPropertyImplDecl::=
Dynamic)
-      continue;
-    if (!(*Prop)->getPropertyIvarDecl())
-      continue;
-    ObjCPropertyDecl *PD =3D (*Prop)->getPropertyDecl();
-    if (!PD)
-      continue;
-    if (ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl())
-      if (!Getter->isDefined())
-        InstanceMethods.push_back(Getter);
-    if (PD->isReadOnly())
-      continue;
-    if (ObjCMethodDecl *Setter =3D PD->getSetterMethodDecl())
-      if (!Setter->isDefined())
-        InstanceMethods.push_back(Setter);
-  }
-  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(=
),
-                             true, "", IDecl->getName(), Result);
-
-  // Build _objc_method_list for class's class methods if needed
-  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_en=
d(),
-                             false, "", IDecl->getName(), Result);
-
-  // Protocols referenced in class declaration?
-  RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
-                                  "CLASS", CDecl->getName(), Result);
-
-  // Declaration of class/meta-class metadata
-  /* struct _objc_class {
-   struct _objc_class *isa; // or const char *root_class_name when metadata
-   const char *super_class_name;
-   char *name;
-   long version;
-   long info;
-   long instance_size;
-   struct _objc_ivar_list *ivars;
-   struct _objc_method_list *methods;
-   struct objc_cache *cache;
-   struct objc_protocol_list *protocols;
-   const char *ivar_layout;
-   struct _objc_class_ext  *ext;
-   };
-  */
-  static bool objc_class =3D false;
-  if (!objc_class) {
-    Result +=3D "\nstruct _objc_class {\n";
-    Result +=3D "\tstruct _objc_class *isa;\n";
-    Result +=3D "\tconst char *super_class_name;\n";
-    Result +=3D "\tchar *name;\n";
-    Result +=3D "\tlong version;\n";
-    Result +=3D "\tlong info;\n";
-    Result +=3D "\tlong instance_size;\n";
-    Result +=3D "\tstruct _objc_ivar_list *ivars;\n";
-    Result +=3D "\tstruct _objc_method_list *methods;\n";
-    Result +=3D "\tstruct objc_cache *cache;\n";
-    Result +=3D "\tstruct _objc_protocol_list *protocols;\n";
-    Result +=3D "\tconst char *ivar_layout;\n";
-    Result +=3D "\tstruct _objc_class_ext  *ext;\n";
-    Result +=3D "};\n";
-    objc_class =3D true;
-  }
-
-  // Meta-class metadata generation.
-  ObjCInterfaceDecl *RootClass =3D 0;
-  ObjCInterfaceDecl *SuperClass =3D CDecl->getSuperClass();
-  while (SuperClass) {
-    RootClass =3D SuperClass;
-    SuperClass =3D SuperClass->getSuperClass();
-  }
-  SuperClass =3D CDecl->getSuperClass();
-
-  Result +=3D "\nstatic struct _objc_class _OBJC_METACLASS_";
-  Result +=3D CDecl->getNameAsString();
-  Result +=3D " __attribute__ ((used, section (\"__OBJC, __meta_class\")))=
=3D "
-  "{\n\t(struct _objc_class *)\"";
-  Result +=3D (RootClass ? RootClass->getNameAsString() : CDecl->getNameAs=
String());
-  Result +=3D "\"";
-
-  if (SuperClass) {
-    Result +=3D ", \"";
-    Result +=3D SuperClass->getNameAsString();
-    Result +=3D "\", \"";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D "\"";
-  }
-  else {
-    Result +=3D ", 0, \"";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D "\"";
-  }
-  // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
-  // 'info' field is initialized to CLS_META(2) for metaclass
-  Result +=3D ", 0,2, sizeof(struct _objc_class), 0";
-  if (IDecl->classmeth_begin() !=3D IDecl->classmeth_end()) {
-    Result +=3D "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
-    Result +=3D IDecl->getNameAsString();
-    Result +=3D "\n";
-  }
-  else
-    Result +=3D ", 0\n";
-  if (CDecl->protocol_begin() !=3D CDecl->protocol_end()) {
-    Result +=3D "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOL=
S_";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D ",0,0\n";
-  }
-  else
-    Result +=3D "\t,0,0,0,0\n";
-  Result +=3D "};\n";
-
-  // class metadata generation.
-  Result +=3D "\nstatic struct _objc_class _OBJC_CLASS_";
-  Result +=3D CDecl->getNameAsString();
-  Result +=3D " __attribute__ ((used, section (\"__OBJC, __class\")))=3D "
-            "{\n\t&_OBJC_METACLASS_";
-  Result +=3D CDecl->getNameAsString();
-  if (SuperClass) {
-    Result +=3D ", \"";
-    Result +=3D SuperClass->getNameAsString();
-    Result +=3D "\", \"";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D "\"";
-  }
-  else {
-    Result +=3D ", 0, \"";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D "\"";
-  }
-  // 'info' field is initialized to CLS_CLASS(1) for class
-  Result +=3D ", 0,1";
-  if (!ObjCSynthesizedStructs.count(CDecl))
-    Result +=3D ",0";
-  else {
-    // class has size. Must synthesize its size.
-    Result +=3D ",sizeof(struct ";
-    Result +=3D CDecl->getNameAsString();
-    if (LangOpts.MicrosoftExt)
-      Result +=3D "_IMPL";
-    Result +=3D ")";
-  }
-  if (NumIvars > 0) {
-    Result +=3D ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D "\n\t";
-  }
-  else
-    Result +=3D ",0";
-  if (IDecl->instmeth_begin() !=3D IDecl->instmeth_end()) {
-    Result +=3D ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D ", 0\n\t";
-  }
-  else
-    Result +=3D ",0,0";
-  if (CDecl->protocol_begin() !=3D CDecl->protocol_end()) {
-    Result +=3D ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
-    Result +=3D CDecl->getNameAsString();
-    Result +=3D ", 0,0\n";
-  }
-  else
-    Result +=3D ",0,0,0\n";
-  Result +=3D "};\n";
-}
=20
 /// RewriteImplementations - This routine rewrites all method implementati=
ons
 /// and emits meta-data.
@@ -4118,103 +3307,6 @@
     RewriteImplementationDecl(CategoryImplementation[i]);
 }
=20
-void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
-  int ClsDefCount =3D ClassImplementation.size();
-  int CatDefCount =3D CategoryImplementation.size();
- =20
-  // For each implemented class, write out all its meta data.
-  for (int i =3D 0; i < ClsDefCount; i++)
-    RewriteObjCClassMetaData(ClassImplementation[i], Result);
-
-  // For each implemented category, write out all its meta data.
-  for (int i =3D 0; i < CatDefCount; i++)
-    RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
-
-  // Write objc_symtab metadata
-  /*
-   struct _objc_symtab
-   {
-   long sel_ref_cnt;
-   SEL *refs;
-   short cls_def_cnt;
-   short cat_def_cnt;
-   void *defs[cls_def_cnt + cat_def_cnt];
-   };
-   */
-
-  Result +=3D "\nstruct _objc_symtab {\n";
-  Result +=3D "\tlong sel_ref_cnt;\n";
-  Result +=3D "\tSEL *refs;\n";
-  Result +=3D "\tshort cls_def_cnt;\n";
-  Result +=3D "\tshort cat_def_cnt;\n";
-  Result +=3D "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
-  Result +=3D "};\n\n";
-
-  Result +=3D "static struct _objc_symtab "
-         "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\=
")))=3D {\n";
-  Result +=3D "\t0, 0, " + utostr(ClsDefCount)
-            + ", " + utostr(CatDefCount) + "\n";
-  for (int i =3D 0; i < ClsDefCount; i++) {
-    Result +=3D "\t,&_OBJC_CLASS_";
-    Result +=3D ClassImplementation[i]->getNameAsString();
-    Result +=3D "\n";
-  }
-
-  for (int i =3D 0; i < CatDefCount; i++) {
-    Result +=3D "\t,&_OBJC_CATEGORY_";
-    Result +=3D CategoryImplementation[i]->getClassInterface()->getNameAsS=
tring();
-    Result +=3D "_";
-    Result +=3D CategoryImplementation[i]->getNameAsString();
-    Result +=3D "\n";
-  }
-
-  Result +=3D "};\n\n";
-
-  // Write objc_module metadata
-
-  /*
-   struct _objc_module {
-    long version;
-    long size;
-    const char *name;
-    struct _objc_symtab *symtab;
-   }
-  */
-
-  Result +=3D "\nstruct _objc_module {\n";
-  Result +=3D "\tlong version;\n";
-  Result +=3D "\tlong size;\n";
-  Result +=3D "\tconst char *name;\n";
-  Result +=3D "\tstruct _objc_symtab *symtab;\n";
-  Result +=3D "};\n\n";
-  Result +=3D "static struct _objc_module "
-    "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\=
")))=3D {\n";
-  Result +=3D "\t" + utostr(OBJC_ABI_VERSION) +
-  ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
-  Result +=3D "};\n\n";
-
-  if (LangOpts.MicrosoftExt) {
-    if (ProtocolExprDecls.size()) {
-      Result +=3D "#pragma section(\".objc_protocol$B\",long,read,write)\n=
";
-      Result +=3D "#pragma data_seg(push, \".objc_protocol$B\")\n";
-      for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I =3D Protoco=
lExprDecls.begin(),
-           E =3D ProtocolExprDecls.end(); I !=3D E; ++I) {
-        Result +=3D "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_=
";
-        Result +=3D (*I)->getNameAsString();
-        Result +=3D " =3D &_OBJC_PROTOCOL_";
-        Result +=3D (*I)->getNameAsString();
-        Result +=3D ";\n";
-      }
-      Result +=3D "#pragma data_seg(pop)\n\n";
-    }
-    Result +=3D "#pragma section(\".objc_module_info$B\",long,read,write)\=
n";
-    Result +=3D "#pragma data_seg(push, \".objc_module_info$B\")\n";
-    Result +=3D "static struct _objc_module *_POINTER_OBJC_MODULES =3D ";
-    Result +=3D "&_OBJC_MODULES;\n";
-    Result +=3D "#pragma data_seg(pop)\n\n";
-  }
-}
-
 void RewriteObjC::RewriteByRefString(std::string &ResultStr,=20
                                      const std::string &Name,
                                      ValueDecl *VD, bool def) {
@@ -4261,10 +3353,8 @@
       if (AI !=3D BD->param_begin()) S +=3D ", ";
       ParamStr =3D (*AI)->getNameAsString();
       QualType QT =3D (*AI)->getType();
-      if (convertBlockPointerToFunctionPointer(QT))
-        QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
-      else
-        QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());   =
  =20
+      (void)convertBlockPointerToFunctionPointer(QT);
+      QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
       S +=3D ParamStr;
     }
     if (FT->isVariadic()) {
@@ -4539,20 +3629,20 @@
     // Need to copy-in the inner copied-in variables not actually used in =
this
     // block.
     for (int j =3D 0; j < InnerDeclRefsCount[i]; j++) {
-      BlockDeclRefExpr *Exp =3D InnerDeclRefs[count++];
+      DeclRefExpr *Exp =3D InnerDeclRefs[count++];
       ValueDecl *VD =3D Exp->getDecl();
       BlockDeclRefs.push_back(Exp);
-      if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
+      if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD))=
 {
         BlockByCopyDeclsPtrSet.insert(VD);
         BlockByCopyDecls.push_back(VD);
       }
-      if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
+      if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
         BlockByRefDeclsPtrSet.insert(VD);
         BlockByRefDecls.push_back(VD);
       }
       // imported objects in the inner blocks not used in the outer
       // blocks must be copied/disposed in the outer block as well.
-      if (Exp->isByRef() ||
+      if (VD->hasAttr<BlocksAttr>() ||
           VD->getType()->isObjCObjectPointerType() ||=20
           VD->getType()->isBlockPointerType())
         ImportedBlockDecls.insert(VD);
@@ -4641,25 +3731,21 @@
         GetBlockDeclRefExprs(*CI);
     }
   // Handle specific things.
-  if (BlockDeclRefExpr *CDRE =3D dyn_cast<BlockDeclRefExpr>(S)) {
-    // FIXME: Handle enums.
-    if (!isa<FunctionDecl>(CDRE->getDecl()))
-      BlockDeclRefs.push_back(CDRE);
+  if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(S)) {
+    if (DRE->refersToEnclosingLocal()) {
+      // FIXME: Handle enums.
+      if (!isa<FunctionDecl>(DRE->getDecl()))
+        BlockDeclRefs.push_back(DRE);
+      if (HasLocalVariableExternalStorage(DRE->getDecl()))
+        BlockDeclRefs.push_back(DRE);
+    }
   }
-  else if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(S))
-    if (HasLocalVariableExternalStorage(DRE->getDecl())) {
-        BlockDeclRefExpr *BDRE =3D=20
-          new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
-                                        DRE->getType(),=20
-                                        VK_LValue, DRE->getLocation(), fal=
se);
-        BlockDeclRefs.push_back(BDRE);
-    }
  =20
   return;
 }
=20
 void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,=20
-                SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
+                SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
                 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
   for (Stmt::child_range CI =3D S->children(); CI; ++CI)
     if (*CI) {
@@ -4676,15 +3762,15 @@
=20
     }
   // Handle specific things.
-  if (BlockDeclRefExpr *CDRE =3D dyn_cast<BlockDeclRefExpr>(S)) {
-    if (!isa<FunctionDecl>(CDRE->getDecl()) &&
-        !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
-      InnerBlockDeclRefs.push_back(CDRE);
-  }
-  else if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(S)) {
-    if (VarDecl *Var =3D dyn_cast<VarDecl>(DRE->getDecl()))
-      if (Var->isFunctionOrMethodVarDecl())
-        ImportedLocalExternalDecls.insert(Var);
+  if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(S)) {
+    if (DRE->refersToEnclosingLocal()) {
+      if (!isa<FunctionDecl>(DRE->getDecl()) &&
+          !InnerContexts.count(DRE->getDecl()->getDeclContext()))
+        InnerBlockDeclRefs.push_back(DRE);
+      if (VarDecl *Var =3D dyn_cast<VarDecl>(DRE->getDecl()))
+        if (Var->isFunctionOrMethodVarDecl())
+          ImportedLocalExternalDecls.insert(Var);
+    }
   }
  =20
   return;
@@ -4727,9 +3813,6 @@
=20
   if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(BlockExp)) {
     CPT =3D DRE->getType()->getAs<BlockPointerType>();
-  } else if (const BlockDeclRefExpr *CDRE =3D=20
-              dyn_cast<BlockDeclRefExpr>(BlockExp)) {
-    CPT =3D CDRE->getType()->getAs<BlockPointerType>();
   } else if (const MemberExpr *MExpr =3D dyn_cast<MemberExpr>(BlockExp)) {
     CPT =3D MExpr->getType()->getAs<BlockPointerType>();
   }=20
@@ -4753,6 +3836,9 @@
     return CondExpr;
   } else if (const ObjCIvarRefExpr *IRE =3D dyn_cast<ObjCIvarRefExpr>(Bloc=
kExp)) {
     CPT =3D IRE->getType()->getAs<BlockPointerType>();
+  } else if (const PseudoObjectExpr *POE
+               =3D dyn_cast<PseudoObjectExpr>(BlockExp)) {
+    CPT =3D POE->getType()->castAs<BlockPointerType>();
   } else {
     assert(1 && "RewriteBlockClass: Bad type");
   }
@@ -4839,17 +3925,11 @@
 //        i =3D 77;
 //    };
 //}
-Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
+Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
   // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR=20
   // for each DeclRefExp where BYREFVAR is name of the variable.
-  ValueDecl *VD;
-  bool isArrow =3D true;
-  if (BlockDeclRefExpr *BDRE =3D dyn_cast<BlockDeclRefExpr>(DeclRefExp))
-    VD =3D BDRE->getDecl();
-  else {
-    VD =3D cast<DeclRefExpr>(DeclRefExp)->getDecl();
-    isArrow =3D false;
-  }
+  ValueDecl *VD =3D DeclRefExp->getDecl();
+  bool isArrow =3D DeclRefExp->refersToEnclosingLocal();
  =20
   FieldDecl *FD =3D FieldDecl::Create(*Context, 0, SourceLocation(),
                                     SourceLocation(),
@@ -5343,7 +4423,7 @@
   if (BlockDeclRefs.size()) {
     // Unique all "by copy" declarations.
     for (unsigned i =3D 0; i < BlockDeclRefs.size(); i++)
-      if (!BlockDeclRefs[i]->isByRef()) {
+      if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
         if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
           BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
           BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
@@ -5351,7 +4431,7 @@
       }
     // Unique all "by ref" declarations.
     for (unsigned i =3D 0; i < BlockDeclRefs.size(); i++)
-      if (BlockDeclRefs[i]->isByRef()) {
+      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
         if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
           BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
           BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
@@ -5359,7 +4439,7 @@
       }
     // Find any imported blocks...they will need special attention.
     for (unsigned i =3D 0; i < BlockDeclRefs.size(); i++)
-      if (BlockDeclRefs[i]->isByRef() ||
+      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
           BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||=20
           BlockDeclRefs[i]->getType()->isBlockPointerType())
         ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
@@ -5375,7 +4455,7 @@
 }
=20
 Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
-          const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
+          const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
   const BlockDecl *block =3D Exp->getBlockDecl();
   Blocks.push_back(Exp);
=20
@@ -5385,9 +4465,9 @@
  int countOfInnerDecls =3D 0;
   if (!InnerBlockDeclRefs.empty()) {
     for (unsigned i =3D 0; i < InnerBlockDeclRefs.size(); i++) {
-      BlockDeclRefExpr *Exp =3D InnerBlockDeclRefs[i];
+      DeclRefExpr *Exp =3D InnerBlockDeclRefs[i];
       ValueDecl *VD =3D Exp->getDecl();
-      if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
+      if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD))=
 {
       // We need to save the copied-in variables in nested
       // blocks because it is needed at the end for some of the API genera=
tions.
       // See SynthesizeBlockLiterals routine.
@@ -5396,7 +4476,7 @@
         BlockByCopyDeclsPtrSet.insert(VD);
         BlockByCopyDecls.push_back(VD);
       }
-      if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
+      if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
         InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
         BlockDeclRefs.push_back(Exp);
         BlockByRefDeclsPtrSet.insert(VD);
@@ -5405,7 +4485,7 @@
     }
     // Find any imported blocks...they will need special attention.
     for (unsigned i =3D 0; i < InnerBlockDeclRefs.size(); i++)
-      if (InnerBlockDeclRefs[i]->isByRef() ||
+      if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
           InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||=20
           InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
         ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
@@ -5435,15 +4515,15 @@
=20
   // Simulate a contructor call...
   FD =3D SynthBlockInitFunctionDecl(Tag);
-  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(FD, FType, VK_RValue,
+  DeclRefExpr *DRE =3D new (Context) DeclRefExpr(FD, false, FType, VK_RVal=
ue,
                                                SourceLocation());
=20
   SmallVector<Expr*, 4> InitExprs;
=20
   // Initialize the block function.
   FD =3D SynthBlockInitFunctionDecl(Func);
-  DeclRefExpr *Arg =3D new (Context) DeclRefExpr(FD, FD->getType(), VK_LVa=
lue,
-                                               SourceLocation());
+  DeclRefExpr *Arg =3D new (Context) DeclRefExpr(FD, false, FD->getType(),
+                                               VK_LValue, SourceLocation()=
);
   CastExpr *castExpr =3D NoTypeInfoCStyleCastExpr(Context, Context->VoidPt=
rTy,
                                                 CK_BitCast, Arg);
   InitExprs.push_back(castExpr);
@@ -5457,7 +4537,7 @@
                                    Context->VoidPtrTy, 0,
                                    SC_Static, SC_None);
   UnaryOperator *DescRefExpr =3D
-    new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
+    new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
                                                           Context->VoidPtr=
Ty,
                                                           VK_LValue,
                                                           SourceLocation()=
),=20
@@ -5476,7 +4556,7 @@
       if (isObjCType((*I)->getType())) {
         // FIXME: Conform to ABI ([[obj retain] autorelease]).
         FD =3D SynthBlockInitFunctionDecl((*I)->getName());
-        Exp =3D new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
+        Exp =3D new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LVa=
lue,
                                         SourceLocation());
         if (HasLocalVariableExternalStorage(*I)) {
           QualType QT =3D (*I)->getType();
@@ -5486,13 +4566,13 @@
         }
       } else if (isTopLevelBlockPointerType((*I)->getType())) {
         FD =3D SynthBlockInitFunctionDecl((*I)->getName());
-        Arg =3D new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
+        Arg =3D new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LVa=
lue,
                                         SourceLocation());
         Exp =3D NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
                                        CK_BitCast, Arg);
       } else {
         FD =3D SynthBlockInitFunctionDecl((*I)->getName());
-        Exp =3D new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
+        Exp =3D new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LVa=
lue,
                                         SourceLocation());
         if (HasLocalVariableExternalStorage(*I)) {
           QualType QT =3D (*I)->getType();
@@ -5520,7 +4600,7 @@
       QualType castT =3D Context->getPointerType(Context->getTagDeclType(R=
D));
      =20
       FD =3D SynthBlockInitFunctionDecl((*I)->getName());
-      Exp =3D new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
+      Exp =3D new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValu=
e,
                                       SourceLocation());
       bool isNestedCapturedVar =3D false;
       if (block)
@@ -5580,26 +4660,6 @@
 // Function Body / Expression rewriting
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalIniti=
alizer().
-// The allows the main rewrite loop to associate all ObjCPropertyRefExprs =
with
-// their respective BinaryOperator. Without this knowledge, we'd need to r=
ewrite
-// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
-// Since the rewriter isn't capable of rewriting rewritten code, it's impo=
rtant
-// we get this right.
-void RewriteObjC::CollectPropertySetters(Stmt *S) {
-  // Perform a bottom up traversal of all children.
-  for (Stmt::child_range CI =3D S->children(); CI; ++CI)
-    if (*CI)
-      CollectPropertySetters(*CI);
-
-  if (BinaryOperator *BinOp =3D dyn_cast<BinaryOperator>(S)) {
-    if (BinOp->isAssignmentOp()) {
-      if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
-        PropSetters[BinOp->getLHS()] =3D BinOp;
-    }
-  }
-}
-
 Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
   if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
       isa<DoStmt>(S) || isa<ForStmt>(S))
@@ -5609,50 +4669,32 @@
     ObjCBcLabelNo.push_back(++BcLabelCount);
   }
=20
+  // Pseudo-object operations and ivar references need special
+  // treatment because we're going to recursively rewrite them.
+  if (PseudoObjectExpr *PseudoOp =3D dyn_cast<PseudoObjectExpr>(S)) {
+    if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
+      return RewritePropertyOrImplicitSetter(PseudoOp);
+    } else {
+      return RewritePropertyOrImplicitGetter(PseudoOp);
+    }
+  } else if (ObjCIvarRefExpr *IvarRefExpr =3D dyn_cast<ObjCIvarRefExpr>(S)=
) {
+    return RewriteObjCIvarRefExpr(IvarRefExpr);
+  }
+
   SourceRange OrigStmtRange =3D S->getSourceRange();
=20
   // Perform a bottom up rewrite of all children.
   for (Stmt::child_range CI =3D S->children(); CI; ++CI)
     if (*CI) {
-      Stmt *newStmt;
-      Stmt *ChildStmt =3D (*CI);
-      if (ObjCIvarRefExpr *IvarRefExpr =3D dyn_cast<ObjCIvarRefExpr>(Child=
Stmt)) {
-        Expr *OldBase =3D IvarRefExpr->getBase();
-        bool replaced =3D false;
-        newStmt =3D RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
-        if (replaced) {
-          if (ObjCIvarRefExpr *IRE =3D dyn_cast<ObjCIvarRefExpr>(newStmt))
-            ReplaceStmt(OldBase, IRE->getBase());
-          else
-            ReplaceStmt(ChildStmt, newStmt);
-        }
+      Stmt *childStmt =3D (*CI);
+      Stmt *newStmt =3D RewriteFunctionBodyOrGlobalInitializer(childStmt);
+      if (newStmt) {
+        *CI =3D newStmt;
       }
-      else
-        newStmt =3D RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
-      if (newStmt) {
-          if (Expr *PropOrImplicitRefExpr =3D dyn_cast<Expr>(ChildStmt))
-            if (PropSetters[PropOrImplicitRefExpr] =3D=3D S) {
-              S =3D newStmt;
-              newStmt =3D 0;
-            }
-        if (newStmt)
-          *CI =3D newStmt;
-      }
-      // If dealing with an assignment with LHS being a property reference
-      // expression, the entire assignment tree is rewritten into a proper=
ty
-      // setter messaging. This involvs the RHS too. Do not attempt to rew=
rite
-      // RHS again.
-      if (Expr *Exp =3D dyn_cast<Expr>(ChildStmt))
-        if (isa<ObjCPropertyRefExpr>(Exp)) {
-          if (PropSetters[Exp]) {
-            ++CI;
-            continue;
-          }
-        }
     }
=20
   if (BlockExpr *BE =3D dyn_cast<BlockExpr>(S)) {
-    SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
+    SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
     llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
     InnerContexts.insert(BE->getBlockDecl());
     ImportedLocalExternalDecls.clear();
@@ -5661,7 +4703,6 @@
     // Rewrite the block body in place.
     Stmt *SaveCurrentBody =3D CurrentBody;
     CurrentBody =3D BE->getBody();
-    CollectPropertySetters(CurrentBody);
     PropParentMap =3D 0;
     // block literal on rhs of a property-dot-sytax assignment
     // must be replaced by its synthesize ast so getRewrittenText
@@ -5689,67 +4730,6 @@
   if (ObjCEncodeExpr *AtEncode =3D dyn_cast<ObjCEncodeExpr>(S))
     return RewriteAtEncode(AtEncode);
=20
-  if (isa<ObjCPropertyRefExpr>(S)) {
-    Expr *PropOrImplicitRefExpr =3D dyn_cast<Expr>(S);
-    assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is=
 null");
-   =20
-    BinaryOperator *BinOp =3D PropSetters[PropOrImplicitRefExpr];
-    if (BinOp) {
-      // Because the rewriter doesn't allow us to rewrite rewritten code,
-      // we need to rewrite the right hand side prior to rewriting the set=
ter.
-      DisableReplaceStmt =3D true;
-      // Save the source range. Even if we disable the replacement, the
-      // rewritten node will have been inserted into the tree. If the synt=
hesized
-      // node is at the 'end', the rewriter will fail. Consider this:
-      //    self.errorHandler =3D handler ? handler :
-      //              ^(NSURL *errorURL, NSError *error) { return (BOOL)1;=
 };
-      SourceRange SrcRange =3D BinOp->getSourceRange();
-      Stmt *newStmt =3D RewriteFunctionBodyOrGlobalInitializer(BinOp->getR=
HS());
-      // Need to rewrite the ivar access expression if need be.
-      if (isa<ObjCIvarRefExpr>(newStmt)) {
-        bool replaced =3D false;
-        newStmt =3D RewriteObjCNestedIvarRefExpr(newStmt, replaced);
-      }
-     =20
-      DisableReplaceStmt =3D false;
-      //
-      // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
-      // we changed the RHS of BinOp, the rewriter would fail (since it ne=
eds
-      // to see the original expression). Consider this example:
-      //
-      // Foo *obj1, *obj2;
-      //
-      // obj1.i =3D [obj2 rrrr];
-      //
-      // 'BinOp' for the previous expression looks like:
-      //
-      // (BinaryOperator 0x231ccf0 'int' '=3D'
-      //   (ObjCPropertyRefExpr 0x231cc70 'int' Kind=3DPropertyRef Propert=
y=3D"i"
-      //     (DeclRefExpr 0x231cc50 'Foo *' Var=3D'obj1' 0x231cbb0))
-      //   (ObjCMessageExpr 0x231ccb0 'int' selector=3Drrrr
-      //     (DeclRefExpr 0x231cc90 'Foo *' Var=3D'obj2' 0x231cbe0)))
-      //
-      // 'newStmt' represents the rewritten message expression. For exampl=
e:
-      //
-      // (CallExpr 0x231d300 'id':'struct objc_object *'
-      //   (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
-      //     (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
-      //       (CStyleCastExpr 0x231d220 'void *'
-      //         (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl=
=3D'objc_msgSend' 0x231cdc0))))
-      //
-      // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter =
so that it
-      // can be used as the setter argument. ReplaceStmt() will still 'see'
-      // the original RHS (since we haven't altered BinOp).
-      //
-      // This implies the Rewrite* routines can no longer delete the origi=
nal
-      // node. As a result, we now leak the original AST nodes.
-      //
-      return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt=
), SrcRange);
-    } else {
-      return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
-    }
-  }
- =20
   if (ObjCSelectorExpr *AtSelector =3D dyn_cast<ObjCSelectorExpr>(S))
     return RewriteAtSelector(AtSelector);
=20
@@ -5859,10 +4839,6 @@
     Stmts.pop_back();
   }
   // Handle blocks rewriting.
-  if (BlockDeclRefExpr *BDRE =3D dyn_cast<BlockDeclRefExpr>(S)) {
-    if (BDRE->isByRef())
-      return RewriteBlockDeclRefExpr(BDRE);
-  }
   if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(S)) {
     ValueDecl *VD =3D DRE->getDecl();=20
     if (VD->hasAttr<BlocksAttr>())
@@ -5917,108 +4893,124 @@
 /// HandleDeclInMainFile - This is called for each top-level decl defined =
in the
 /// main file of the input.
 void RewriteObjC::HandleDeclInMainFile(Decl *D) {
-  if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
-    if (FD->isOverloadedOperator())
-      return;
-
-    // Since function prototypes don't have ParmDecl's, we check the funct=
ion
-    // prototype. This enables us to rewrite function declarations and
-    // definitions using the same code.
-    RewriteBlocksInFunctionProtoType(FD->getType(), FD);
-
-    // FIXME: If this should support Obj-C++, support CXXTryStmt
-    if (CompoundStmt *Body =3D dyn_cast_or_null<CompoundStmt>(FD->getBody(=
))) {
-      CurFunctionDef =3D FD;
-      CurFunctionDeclToDeclareForBlock =3D FD;
-      CollectPropertySetters(Body);
-      CurrentBody =3D Body;
-      Body =3D
-       cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(B=
ody));
-      FD->setBody(Body);
-      CurrentBody =3D 0;
-      if (PropParentMap) {
-        delete PropParentMap;
-        PropParentMap =3D 0;
+  switch (D->getKind()) {
+    case Decl::Function: {
+      FunctionDecl *FD =3D cast<FunctionDecl>(D);
+      if (FD->isOverloadedOperator())
+        return;
+
+      // Since function prototypes don't have ParmDecl's, we check the fun=
ction
+      // prototype. This enables us to rewrite function declarations and
+      // definitions using the same code.
+      RewriteBlocksInFunctionProtoType(FD->getType(), FD);
+
+      if (!FD->isThisDeclarationADefinition())
+        break;
+
+      // FIXME: If this should support Obj-C++, support CXXTryStmt
+      if (CompoundStmt *Body =3D dyn_cast_or_null<CompoundStmt>(FD->getBod=
y())) {
+        CurFunctionDef =3D FD;
+        CurFunctionDeclToDeclareForBlock =3D FD;
+        CurrentBody =3D Body;
+        Body =3D
+        cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(=
Body));
+        FD->setBody(Body);
+        CurrentBody =3D 0;
+        if (PropParentMap) {
+          delete PropParentMap;
+          PropParentMap =3D 0;
+        }
+        // This synthesizes and inserts the block "impl" struct, invoke fu=
nction,
+        // and any copy/dispose helper functions.
+        InsertBlockLiteralsWithinFunction(FD);
+        CurFunctionDef =3D 0;
+        CurFunctionDeclToDeclareForBlock =3D 0;
       }
-      // This synthesizes and inserts the block "impl" struct, invoke func=
tion,
-      // and any copy/dispose helper functions.
-      InsertBlockLiteralsWithinFunction(FD);
-      CurFunctionDef =3D 0;
-      CurFunctionDeclToDeclareForBlock =3D 0;
+      break;
     }
-    return;
-  }
-  if (ObjCMethodDecl *MD =3D dyn_cast<ObjCMethodDecl>(D)) {
-    if (CompoundStmt *Body =3D MD->getCompoundBody()) {
-      CurMethodDef =3D MD;
-      CollectPropertySetters(Body);
-      CurrentBody =3D Body;
-      Body =3D
-       cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(B=
ody));
-      MD->setBody(Body);
-      CurrentBody =3D 0;
-      if (PropParentMap) {
-        delete PropParentMap;
-        PropParentMap =3D 0;
+    case Decl::ObjCMethod: {
+      ObjCMethodDecl *MD =3D cast<ObjCMethodDecl>(D);
+      if (CompoundStmt *Body =3D MD->getCompoundBody()) {
+        CurMethodDef =3D MD;
+        CurrentBody =3D Body;
+        Body =3D
+          cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitialize=
r(Body));
+        MD->setBody(Body);
+        CurrentBody =3D 0;
+        if (PropParentMap) {
+          delete PropParentMap;
+          PropParentMap =3D 0;
+        }
+        InsertBlockLiteralsWithinMethod(MD);
+        CurMethodDef =3D 0;
       }
-      InsertBlockLiteralsWithinMethod(MD);
-      CurMethodDef =3D 0;
+      break;
     }
-  }
-  if (ObjCImplementationDecl *CI =3D dyn_cast<ObjCImplementationDecl>(D))
-    ClassImplementation.push_back(CI);
-  else if (ObjCCategoryImplDecl *CI =3D dyn_cast<ObjCCategoryImplDecl>(D))
-    CategoryImplementation.push_back(CI);
-  else if (isa<ObjCClassDecl>(D))
-    llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
-  else if (VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
-    RewriteObjCQualifiedInterfaceTypes(VD);
-    if (isTopLevelBlockPointerType(VD->getType()))
-      RewriteBlockPointerDecl(VD);
-    else if (VD->getType()->isFunctionPointerType()) {
-      CheckFunctionPointerDecl(VD->getType(), VD);
+    case Decl::ObjCImplementation: {
+      ObjCImplementationDecl *CI =3D cast<ObjCImplementationDecl>(D);
+      ClassImplementation.push_back(CI);
+      break;
+    }
+    case Decl::ObjCCategoryImpl: {
+      ObjCCategoryImplDecl *CI =3D cast<ObjCCategoryImplDecl>(D);
+      CategoryImplementation.push_back(CI);
+      break;
+    }
+    case Decl::Var: {
+      VarDecl *VD =3D cast<VarDecl>(D);
+      RewriteObjCQualifiedInterfaceTypes(VD);
+      if (isTopLevelBlockPointerType(VD->getType()))
+        RewriteBlockPointerDecl(VD);
+      else if (VD->getType()->isFunctionPointerType()) {
+        CheckFunctionPointerDecl(VD->getType(), VD);
+        if (VD->getInit()) {
+          if (CStyleCastExpr *CE =3D dyn_cast<CStyleCastExpr>(VD->getInit(=
))) {
+            RewriteCastExpr(CE);
+          }
+        }
+      } else if (VD->getType()->isRecordType()) {
+        RecordDecl *RD =3D VD->getType()->getAs<RecordType>()->getDecl();
+        if (RD->isCompleteDefinition())
+          RewriteRecordBody(RD);
+      }
       if (VD->getInit()) {
+        GlobalVarDecl =3D VD;
+        CurrentBody =3D VD->getInit();
+        RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
+        CurrentBody =3D 0;
+        if (PropParentMap) {
+          delete PropParentMap;
+          PropParentMap =3D 0;
+        }
+        SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
+        GlobalVarDecl =3D 0;
+         =20
+        // This is needed for blocks.
         if (CStyleCastExpr *CE =3D dyn_cast<CStyleCastExpr>(VD->getInit())=
) {
-          RewriteCastExpr(CE);
+            RewriteCastExpr(CE);
         }
       }
-    } else if (VD->getType()->isRecordType()) {
-      RecordDecl *RD =3D VD->getType()->getAs<RecordType>()->getDecl();
-      if (RD->isCompleteDefinition())
+      break;
+    }
+    case Decl::TypeAlias:
+    case Decl::Typedef: {
+      if (TypedefNameDecl *TD =3D dyn_cast<TypedefNameDecl>(D)) {
+        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
+          RewriteBlockPointerDecl(TD);
+        else if (TD->getUnderlyingType()->isFunctionPointerType())
+          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
+      }
+      break;
+    }
+    case Decl::CXXRecord:
+    case Decl::Record: {
+      RecordDecl *RD =3D cast<RecordDecl>(D);
+      if (RD->isCompleteDefinition())=20
         RewriteRecordBody(RD);
+      break;
     }
-    if (VD->getInit()) {
-      GlobalVarDecl =3D VD;
-      CollectPropertySetters(VD->getInit());
-      CurrentBody =3D VD->getInit();
-      RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
-      CurrentBody =3D 0;
-      if (PropParentMap) {
-        delete PropParentMap;
-        PropParentMap =3D 0;
-      }
-      SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
-                              VD->getName());
-      GlobalVarDecl =3D 0;
-
-      // This is needed for blocks.
-      if (CStyleCastExpr *CE =3D dyn_cast<CStyleCastExpr>(VD->getInit())) {
-        RewriteCastExpr(CE);
-      }
-    }
-    return;
-  }
-  if (TypedefNameDecl *TD =3D dyn_cast<TypedefNameDecl>(D)) {
-    if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
-      RewriteBlockPointerDecl(TD);
-    else if (TD->getUnderlyingType()->isFunctionPointerType())
-      CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
-    return;
-  }
-  if (RecordDecl *RD =3D dyn_cast<RecordDecl>(D)) {
-    if (RD->isCompleteDefinition())=20
-      RewriteRecordBody(RD);
-    return;
+    default:
+      break;
   }
   // Nothing yet.
 }
@@ -6053,9 +5045,974 @@
       ProtocolExprDecls.size()) {
     // Rewrite Objective-c meta data*
     std::string ResultStr;
-    SynthesizeMetaDataIntoBuffer(ResultStr);
+    RewriteMetaDataIntoBuffer(ResultStr);
     // Emit metadata.
     *OutFile << ResultStr;
   }
   OutFile->flush();
 }
+
+void RewriteObjCFragileABI::Initialize(ASTContext &context) {
+  InitializeCommon(context);
+ =20
+  // declaring objc_selector outside the parameter list removes a silly
+  // scope related warning...
+  if (IsHeader)
+    Preamble =3D "#pragma once\n";
+  Preamble +=3D "struct objc_selector; struct objc_class;\n";
+  Preamble +=3D "struct __rw_objc_super { struct objc_object *object; ";
+  Preamble +=3D "struct objc_object *superClass; ";
+  if (LangOpts.MicrosoftExt) {
+    // Add a constructor for creating temporary objects.
+    Preamble +=3D "__rw_objc_super(struct objc_object *o, struct objc_obje=
ct *s) "
+    ": ";
+    Preamble +=3D "object(o), superClass(s) {} ";
+  }
+  Preamble +=3D "};\n";
+  Preamble +=3D "#ifndef _REWRITER_typedef_Protocol\n";
+  Preamble +=3D "typedef struct objc_object Protocol;\n";
+  Preamble +=3D "#define _REWRITER_typedef_Protocol\n";
+  Preamble +=3D "#endif\n";
+  if (LangOpts.MicrosoftExt) {
+    Preamble +=3D "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dll=
import)\n";
+    Preamble +=3D "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
+  } else
+    Preamble +=3D "#define __OBJC_RW_DLLIMPORT extern\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
+  Preamble +=3D "(struct objc_object *, struct objc_selector *, ...);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper=
";
+  Preamble +=3D "(struct objc_super *, struct objc_selector *, ...);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stre=
t";
+  Preamble +=3D "(struct objc_object *, struct objc_selector *, ...);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper=
_stret";
+  Preamble +=3D "(struct objc_super *, struct objc_selector *, ...);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
+  Preamble +=3D "(struct objc_object *, struct objc_selector *, ...);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
+  Preamble +=3D "(const char *);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclas=
s";
+  Preamble +=3D "(struct objc_class *);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass=
";
+  Preamble +=3D "(const char *);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc=
_object *);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *)=
;\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);=
\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_ex=
tract(void *);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT int objc_exception_match";
+  Preamble +=3D "(struct objc_class *, struct objc_object *);\n";
+  // @synchronized hooks.
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_obje=
ct *);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_objec=
t *);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char=
 *);\n";
+  Preamble +=3D "#ifndef __FASTENUMERATIONSTATE\n";
+  Preamble +=3D "struct __objcFastEnumerationState {\n\t";
+  Preamble +=3D "unsigned long state;\n\t";
+  Preamble +=3D "void **itemsPtr;\n\t";
+  Preamble +=3D "unsigned long *mutationsPtr;\n\t";
+  Preamble +=3D "unsigned long extra[5];\n};\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct =
objc_object *);\n";
+  Preamble +=3D "#define __FASTENUMERATIONSTATE\n";
+  Preamble +=3D "#endif\n";
+  Preamble +=3D "#ifndef __NSCONSTANTSTRINGIMPL\n";
+  Preamble +=3D "struct __NSConstantStringImpl {\n";
+  Preamble +=3D "  int *isa;\n";
+  Preamble +=3D "  int flags;\n";
+  Preamble +=3D "  char *str;\n";
+  Preamble +=3D "  long length;\n";
+  Preamble +=3D "};\n";
+  Preamble +=3D "#ifdef CF_EXPORT_CONSTANT_STRING\n";
+  Preamble +=3D "extern \"C\" __declspec(dllexport) int __CFConstantString=
ClassReference[];\n";
+  Preamble +=3D "#else\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[=
];\n";
+  Preamble +=3D "#endif\n";
+  Preamble +=3D "#define __NSCONSTANTSTRINGIMPL\n";
+  Preamble +=3D "#endif\n";
+  // Blocks preamble.
+  Preamble +=3D "#ifndef BLOCK_IMPL\n";
+  Preamble +=3D "#define BLOCK_IMPL\n";
+  Preamble +=3D "struct __block_impl {\n";
+  Preamble +=3D "  void *isa;\n";
+  Preamble +=3D "  int Flags;\n";
+  Preamble +=3D "  int Reserved;\n";
+  Preamble +=3D "  void *FuncPtr;\n";
+  Preamble +=3D "};\n";
+  Preamble +=3D "// Runtime copy/destroy helper functions (from Block_priv=
ate.h)\n";
+  Preamble +=3D "#ifdef __OBJC_EXPORT_BLOCKS\n";
+  Preamble +=3D "extern \"C\" __declspec(dllexport) "
+  "void _Block_object_assign(void *, const void *, const int);\n";
+  Preamble +=3D "extern \"C\" __declspec(dllexport) void _Block_object_dis=
pose(const void *, const int);\n";
+  Preamble +=3D "extern \"C\" __declspec(dllexport) void *_NSConcreteGloba=
lBlock[32];\n";
+  Preamble +=3D "extern \"C\" __declspec(dllexport) void *_NSConcreteStack=
Block[32];\n";
+  Preamble +=3D "#else\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, con=
st void *, const int);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void=
 *, const int);\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
+  Preamble +=3D "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
+  Preamble +=3D "#endif\n";
+  Preamble +=3D "#endif\n";
+  if (LangOpts.MicrosoftExt) {
+    Preamble +=3D "#undef __OBJC_RW_DLLIMPORT\n";
+    Preamble +=3D "#undef __OBJC_RW_STATICIMPORT\n";
+    Preamble +=3D "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang t=
ests.
+    Preamble +=3D "#define __attribute__(X)\n";
+    Preamble +=3D "#endif\n";
+    Preamble +=3D "#define __weak\n";
+  }
+  else {
+    Preamble +=3D "#define __block\n";
+    Preamble +=3D "#define __weak\n";
+  }
+  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
+  // as this avoids warning in any 64bit/32bit compilation model.
+  Preamble +=3D "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((=
TYPE *)0)->MEMBER)\n";
+}
+
+/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
+/// ivar offset.
+void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *iva=
r,
+                                                         std::string &Resu=
lt) {
+  if (ivar->isBitField()) {
+    // FIXME: The hack below doesn't work for bitfields. For now, we simply
+    // place all bitfields at offset 0.
+    Result +=3D "0";
+  } else {
+    Result +=3D "__OFFSETOFIVAR__(struct ";
+    Result +=3D ivar->getContainingInterface()->getNameAsString();
+    if (LangOpts.MicrosoftExt)
+      Result +=3D "_IMPL";
+    Result +=3D ", ";
+    Result +=3D ivar->getNameAsString();
+    Result +=3D ")";
+  }
+}
+
+/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
+void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
+                            ObjCProtocolDecl *PDecl, StringRef prefix,
+                            StringRef ClassName, std::string &Result) {
+  static bool objc_protocol_methods =3D false;
+ =20
+  // Output struct protocol_methods holder of method selector and type.
+  if (!objc_protocol_methods && PDecl->hasDefinition()) {
+    /* struct protocol_methods {
+     SEL _cmd;
+     char *method_types;
+     }
+     */
+    Result +=3D "\nstruct _protocol_methods {\n";
+    Result +=3D "\tstruct objc_selector *_cmd;\n";
+    Result +=3D "\tchar *method_types;\n";
+    Result +=3D "};\n";
+   =20
+    objc_protocol_methods =3D true;
+  }
+  // Do not synthesize the protocol more than once.
+  if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
+    return;
+ =20
+  if (ObjCProtocolDecl *Def =3D PDecl->getDefinition())
+    PDecl =3D Def;
+ =20
+  if (PDecl->instmeth_begin() !=3D PDecl->instmeth_end()) {
+    unsigned NumMethods =3D std::distance(PDecl->instmeth_begin(),
+                                        PDecl->instmeth_end());
+    /* struct _objc_protocol_method_list {
+     int protocol_method_count;
+     struct protocol_methods protocols[];
+     }
+     */
+    Result +=3D "\nstatic struct {\n";
+    Result +=3D "\tint protocol_method_count;\n";
+    Result +=3D "\tstruct _protocol_methods protocol_methods[";
+    Result +=3D utostr(NumMethods);
+    Result +=3D "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
+    Result +=3D PDecl->getNameAsString();
+    Result +=3D " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth=
\")))=3D "
+    "{\n\t" + utostr(NumMethods) + "\n";
+   =20
+    // Output instance methods declared in this protocol.
+    for (ObjCProtocolDecl::instmeth_iterator
+         I =3D PDecl->instmeth_begin(), E =3D PDecl->instmeth_end();
+         I !=3D E; ++I) {
+      if (I =3D=3D PDecl->instmeth_begin())
+        Result +=3D "\t  ,{{(struct objc_selector *)\"";
+      else
+        Result +=3D "\t  ,{(struct objc_selector *)\"";
+      Result +=3D (*I)->getSelector().getAsString();
+      std::string MethodTypeString;
+      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
+      Result +=3D "\", \"";
+      Result +=3D MethodTypeString;
+      Result +=3D "\"}\n";
+    }
+    Result +=3D "\t }\n};\n";
+  }
+ =20
+  // Output class methods declared in this protocol.
+  unsigned NumMethods =3D std::distance(PDecl->classmeth_begin(),
+                                      PDecl->classmeth_end());
+  if (NumMethods > 0) {
+    /* struct _objc_protocol_method_list {
+     int protocol_method_count;
+     struct protocol_methods protocols[];
+     }
+     */
+    Result +=3D "\nstatic struct {\n";
+    Result +=3D "\tint protocol_method_count;\n";
+    Result +=3D "\tstruct _protocol_methods protocol_methods[";
+    Result +=3D utostr(NumMethods);
+    Result +=3D "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
+    Result +=3D PDecl->getNameAsString();
+    Result +=3D " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\=
")))=3D "
+    "{\n\t";
+    Result +=3D utostr(NumMethods);
+    Result +=3D "\n";
+   =20
+    // Output instance methods declared in this protocol.
+    for (ObjCProtocolDecl::classmeth_iterator
+         I =3D PDecl->classmeth_begin(), E =3D PDecl->classmeth_end();
+         I !=3D E; ++I) {
+      if (I =3D=3D PDecl->classmeth_begin())
+        Result +=3D "\t  ,{{(struct objc_selector *)\"";
+      else
+        Result +=3D "\t  ,{(struct objc_selector *)\"";
+      Result +=3D (*I)->getSelector().getAsString();
+      std::string MethodTypeString;
+      Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
+      Result +=3D "\", \"";
+      Result +=3D MethodTypeString;
+      Result +=3D "\"}\n";
+    }
+    Result +=3D "\t }\n};\n";
+  }
+ =20
+  // Output:
+  /* struct _objc_protocol {
+   // Objective-C 1.0 extensions
+   struct _objc_protocol_extension *isa;
+   char *protocol_name;
+   struct _objc_protocol **protocol_list;
+   struct _objc_protocol_method_list *instance_methods;
+   struct _objc_protocol_method_list *class_methods;
+   };
+   */
+  static bool objc_protocol =3D false;
+  if (!objc_protocol) {
+    Result +=3D "\nstruct _objc_protocol {\n";
+    Result +=3D "\tstruct _objc_protocol_extension *isa;\n";
+    Result +=3D "\tchar *protocol_name;\n";
+    Result +=3D "\tstruct _objc_protocol **protocol_list;\n";
+    Result +=3D "\tstruct _objc_protocol_method_list *instance_methods;\n";
+    Result +=3D "\tstruct _objc_protocol_method_list *class_methods;\n";
+    Result +=3D "};\n";
+   =20
+    objc_protocol =3D true;
+  }
+ =20
+  Result +=3D "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
+  Result +=3D PDecl->getNameAsString();
+  Result +=3D " __attribute__ ((used, section (\"__OBJC, __protocol\")))=
=3D "
+  "{\n\t0, \"";
+  Result +=3D PDecl->getNameAsString();
+  Result +=3D "\", 0, ";
+  if (PDecl->instmeth_begin() !=3D PDecl->instmeth_end()) {
+    Result +=3D "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INST=
ANCE_METHODS_";
+    Result +=3D PDecl->getNameAsString();
+    Result +=3D ", ";
+  }
+  else
+    Result +=3D "0, ";
+  if (PDecl->classmeth_begin() !=3D PDecl->classmeth_end()) {
+    Result +=3D "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLAS=
S_METHODS_";
+    Result +=3D PDecl->getNameAsString();
+    Result +=3D "\n";
+  }
+  else
+    Result +=3D "0\n";
+  Result +=3D "};\n";
+ =20
+  // Mark this protocol as having been generated.
+  if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
+    llvm_unreachable("protocol already synthesized");
+ =20
+}
+
+void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
+                                const ObjCList<ObjCProtocolDecl> &Protocol=
s,
+                                StringRef prefix, StringRef ClassName,
+                                std::string &Result) {
+  if (Protocols.empty()) return;
+ =20
+  for (unsigned i =3D 0; i !=3D Protocols.size(); i++)
+    RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
+ =20
+  // Output the top lovel protocol meta-data for the class.
+  /* struct _objc_protocol_list {
+   struct _objc_protocol_list *next;
+   int    protocol_count;
+   struct _objc_protocol *class_protocols[];
+   }
+   */
+  Result +=3D "\nstatic struct {\n";
+  Result +=3D "\tstruct _objc_protocol_list *next;\n";
+  Result +=3D "\tint    protocol_count;\n";
+  Result +=3D "\tstruct _objc_protocol *class_protocols[";
+  Result +=3D utostr(Protocols.size());
+  Result +=3D "];\n} _OBJC_";
+  Result +=3D prefix;
+  Result +=3D "_PROTOCOLS_";
+  Result +=3D ClassName;
+  Result +=3D " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")=
))=3D "
+  "{\n\t0, ";
+  Result +=3D utostr(Protocols.size());
+  Result +=3D "\n";
+ =20
+  Result +=3D "\t,{&_OBJC_PROTOCOL_";
+  Result +=3D Protocols[0]->getNameAsString();
+  Result +=3D " \n";
+ =20
+  for (unsigned i =3D 1; i !=3D Protocols.size(); i++) {
+    Result +=3D "\t ,&_OBJC_PROTOCOL_";
+    Result +=3D Protocols[i]->getNameAsString();
+    Result +=3D "\n";
+  }
+  Result +=3D "\t }\n};\n";
+}
+
+void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDec=
l *IDecl,
+                                           std::string &Result) {
+  ObjCInterfaceDecl *CDecl =3D IDecl->getClassInterface();
+ =20
+  // Explicitly declared @interface's are already synthesized.
+  if (CDecl->isImplicitInterfaceDecl()) {
+    // FIXME: Implementation of a class with no @interface (legacy) does n=
ot
+    // produce correct synthesis as yet.
+    RewriteObjCInternalStruct(CDecl, Result);
+  }
+ =20
+  // Build _objc_ivar_list metadata for classes ivars if needed
+  unsigned NumIvars =3D !IDecl->ivar_empty()
+  ? IDecl->ivar_size()
+  : (CDecl ? CDecl->ivar_size() : 0);
+  if (NumIvars > 0) {
+    static bool objc_ivar =3D false;
+    if (!objc_ivar) {
+      /* struct _objc_ivar {
+       char *ivar_name;
+       char *ivar_type;
+       int ivar_offset;
+       };
+       */
+      Result +=3D "\nstruct _objc_ivar {\n";
+      Result +=3D "\tchar *ivar_name;\n";
+      Result +=3D "\tchar *ivar_type;\n";
+      Result +=3D "\tint ivar_offset;\n";
+      Result +=3D "};\n";
+     =20
+      objc_ivar =3D true;
+    }
+   =20
+    /* struct {
+     int ivar_count;
+     struct _objc_ivar ivar_list[nIvars];
+     };
+     */
+    Result +=3D "\nstatic struct {\n";
+    Result +=3D "\tint ivar_count;\n";
+    Result +=3D "\tstruct _objc_ivar ivar_list[";
+    Result +=3D utostr(NumIvars);
+    Result +=3D "];\n} _OBJC_INSTANCE_VARIABLES_";
+    Result +=3D IDecl->getNameAsString();
+    Result +=3D " __attribute__ ((used, section (\"__OBJC, __instance_vars=
\")))=3D "
+    "{\n\t";
+    Result +=3D utostr(NumIvars);
+    Result +=3D "\n";
+   =20
+    ObjCInterfaceDecl::ivar_iterator IVI, IVE;
+    SmallVector<ObjCIvarDecl *, 8> IVars;
+    if (!IDecl->ivar_empty()) {
+      for (ObjCInterfaceDecl::ivar_iterator
+           IV =3D IDecl->ivar_begin(), IVEnd =3D IDecl->ivar_end();
+           IV !=3D IVEnd; ++IV)
+        IVars.push_back(*IV);
+      IVI =3D IDecl->ivar_begin();
+      IVE =3D IDecl->ivar_end();
+    } else {
+      IVI =3D CDecl->ivar_begin();
+      IVE =3D CDecl->ivar_end();
+    }
+    Result +=3D "\t,{{\"";
+    Result +=3D (*IVI)->getNameAsString();
+    Result +=3D "\", \"";
+    std::string TmpString, StrEncoding;
+    Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
+    QuoteDoublequotes(TmpString, StrEncoding);
+    Result +=3D StrEncoding;
+    Result +=3D "\", ";
+    RewriteIvarOffsetComputation(*IVI, Result);
+    Result +=3D "}\n";
+    for (++IVI; IVI !=3D IVE; ++IVI) {
+      Result +=3D "\t  ,{\"";
+      Result +=3D (*IVI)->getNameAsString();
+      Result +=3D "\", \"";
+      std::string TmpString, StrEncoding;
+      Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
+      QuoteDoublequotes(TmpString, StrEncoding);
+      Result +=3D StrEncoding;
+      Result +=3D "\", ";
+      RewriteIvarOffsetComputation((*IVI), Result);
+      Result +=3D "}\n";
+    }
+   =20
+    Result +=3D "\t }\n};\n";
+  }
+ =20
+  // Build _objc_method_list for class's instance methods if needed
+  SmallVector<ObjCMethodDecl *, 32>
+  InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
+ =20
+  // If any of our property implementations have associated getters or
+  // setters, produce metadata for them as well.
+  for (ObjCImplDecl::propimpl_iterator Prop =3D IDecl->propimpl_begin(),
+       PropEnd =3D IDecl->propimpl_end();
+       Prop !=3D PropEnd; ++Prop) {
+    if ((*Prop)->getPropertyImplementation() =3D=3D ObjCPropertyImplDecl::=
Dynamic)
+      continue;
+    if (!(*Prop)->getPropertyIvarDecl())
+      continue;
+    ObjCPropertyDecl *PD =3D (*Prop)->getPropertyDecl();
+    if (!PD)
+      continue;
+    if (ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl())
+      if (!Getter->isDefined())
+        InstanceMethods.push_back(Getter);
+    if (PD->isReadOnly())
+      continue;
+    if (ObjCMethodDecl *Setter =3D PD->getSetterMethodDecl())
+      if (!Setter->isDefined())
+        InstanceMethods.push_back(Setter);
+  }
+  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(=
),
+                             true, "", IDecl->getName(), Result);
+ =20
+  // Build _objc_method_list for class's class methods if needed
+  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_en=
d(),
+                             false, "", IDecl->getName(), Result);
+ =20
+  // Protocols referenced in class declaration?
+  RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
+                                  "CLASS", CDecl->getName(), Result);
+ =20
+  // Declaration of class/meta-class metadata
+  /* struct _objc_class {
+   struct _objc_class *isa; // or const char *root_class_name when metadata
+   const char *super_class_name;
+   char *name;
+   long version;
+   long info;
+   long instance_size;
+   struct _objc_ivar_list *ivars;
+   struct _objc_method_list *methods;
+   struct objc_cache *cache;
+   struct objc_protocol_list *protocols;
+   const char *ivar_layout;
+   struct _objc_class_ext  *ext;
+   };
+   */
+  static bool objc_class =3D false;
+  if (!objc_class) {
+    Result +=3D "\nstruct _objc_class {\n";
+    Result +=3D "\tstruct _objc_class *isa;\n";
+    Result +=3D "\tconst char *super_class_name;\n";
+    Result +=3D "\tchar *name;\n";
+    Result +=3D "\tlong version;\n";
+    Result +=3D "\tlong info;\n";
+    Result +=3D "\tlong instance_size;\n";
+    Result +=3D "\tstruct _objc_ivar_list *ivars;\n";
+    Result +=3D "\tstruct _objc_method_list *methods;\n";
+    Result +=3D "\tstruct objc_cache *cache;\n";
+    Result +=3D "\tstruct _objc_protocol_list *protocols;\n";
+    Result +=3D "\tconst char *ivar_layout;\n";
+    Result +=3D "\tstruct _objc_class_ext  *ext;\n";
+    Result +=3D "};\n";
+    objc_class =3D true;
+  }
+ =20
+  // Meta-class metadata generation.
+  ObjCInterfaceDecl *RootClass =3D 0;
+  ObjCInterfaceDecl *SuperClass =3D CDecl->getSuperClass();
+  while (SuperClass) {
+    RootClass =3D SuperClass;
+    SuperClass =3D SuperClass->getSuperClass();
+  }
+  SuperClass =3D CDecl->getSuperClass();
+ =20
+  Result +=3D "\nstatic struct _objc_class _OBJC_METACLASS_";
+  Result +=3D CDecl->getNameAsString();
+  Result +=3D " __attribute__ ((used, section (\"__OBJC, __meta_class\")))=
=3D "
+  "{\n\t(struct _objc_class *)\"";
+  Result +=3D (RootClass ? RootClass->getNameAsString() : CDecl->getNameAs=
String());
+  Result +=3D "\"";
+ =20
+  if (SuperClass) {
+    Result +=3D ", \"";
+    Result +=3D SuperClass->getNameAsString();
+    Result +=3D "\", \"";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D "\"";
+  }
+  else {
+    Result +=3D ", 0, \"";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D "\"";
+  }
+  // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
+  // 'info' field is initialized to CLS_META(2) for metaclass
+  Result +=3D ", 0,2, sizeof(struct _objc_class), 0";
+  if (IDecl->classmeth_begin() !=3D IDecl->classmeth_end()) {
+    Result +=3D "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
+    Result +=3D IDecl->getNameAsString();
+    Result +=3D "\n";
+  }
+  else
+    Result +=3D ", 0\n";
+  if (CDecl->protocol_begin() !=3D CDecl->protocol_end()) {
+    Result +=3D "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOL=
S_";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D ",0,0\n";
+  }
+  else
+    Result +=3D "\t,0,0,0,0\n";
+  Result +=3D "};\n";
+ =20
+  // class metadata generation.
+  Result +=3D "\nstatic struct _objc_class _OBJC_CLASS_";
+  Result +=3D CDecl->getNameAsString();
+  Result +=3D " __attribute__ ((used, section (\"__OBJC, __class\")))=3D "
+  "{\n\t&_OBJC_METACLASS_";
+  Result +=3D CDecl->getNameAsString();
+  if (SuperClass) {
+    Result +=3D ", \"";
+    Result +=3D SuperClass->getNameAsString();
+    Result +=3D "\", \"";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D "\"";
+  }
+  else {
+    Result +=3D ", 0, \"";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D "\"";
+  }
+  // 'info' field is initialized to CLS_CLASS(1) for class
+  Result +=3D ", 0,1";
+  if (!ObjCSynthesizedStructs.count(CDecl))
+    Result +=3D ",0";
+  else {
+    // class has size. Must synthesize its size.
+    Result +=3D ",sizeof(struct ";
+    Result +=3D CDecl->getNameAsString();
+    if (LangOpts.MicrosoftExt)
+      Result +=3D "_IMPL";
+    Result +=3D ")";
+  }
+  if (NumIvars > 0) {
+    Result +=3D ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D "\n\t";
+  }
+  else
+    Result +=3D ",0";
+  if (IDecl->instmeth_begin() !=3D IDecl->instmeth_end()) {
+    Result +=3D ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D ", 0\n\t";
+  }
+  else
+    Result +=3D ",0,0";
+  if (CDecl->protocol_begin() !=3D CDecl->protocol_end()) {
+    Result +=3D ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
+    Result +=3D CDecl->getNameAsString();
+    Result +=3D ", 0,0\n";
+  }
+  else
+    Result +=3D ",0,0,0\n";
+  Result +=3D "};\n";
+}
+
+void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result)=
 {
+  int ClsDefCount =3D ClassImplementation.size();
+  int CatDefCount =3D CategoryImplementation.size();
+ =20
+  // For each implemented class, write out all its meta data.
+  for (int i =3D 0; i < ClsDefCount; i++)
+    RewriteObjCClassMetaData(ClassImplementation[i], Result);
+ =20
+  // For each implemented category, write out all its meta data.
+  for (int i =3D 0; i < CatDefCount; i++)
+    RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
+ =20
+  // Write objc_symtab metadata
+  /*
+   struct _objc_symtab
+   {
+   long sel_ref_cnt;
+   SEL *refs;
+   short cls_def_cnt;
+   short cat_def_cnt;
+   void *defs[cls_def_cnt + cat_def_cnt];
+   };
+   */
+ =20
+  Result +=3D "\nstruct _objc_symtab {\n";
+  Result +=3D "\tlong sel_ref_cnt;\n";
+  Result +=3D "\tSEL *refs;\n";
+  Result +=3D "\tshort cls_def_cnt;\n";
+  Result +=3D "\tshort cat_def_cnt;\n";
+  Result +=3D "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
+  Result +=3D "};\n\n";
+ =20
+  Result +=3D "static struct _objc_symtab "
+  "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))=3D=
 {\n";
+  Result +=3D "\t0, 0, " + utostr(ClsDefCount)
+  + ", " + utostr(CatDefCount) + "\n";
+  for (int i =3D 0; i < ClsDefCount; i++) {
+    Result +=3D "\t,&_OBJC_CLASS_";
+    Result +=3D ClassImplementation[i]->getNameAsString();
+    Result +=3D "\n";
+  }
+ =20
+  for (int i =3D 0; i < CatDefCount; i++) {
+    Result +=3D "\t,&_OBJC_CATEGORY_";
+    Result +=3D CategoryImplementation[i]->getClassInterface()->getNameAsS=
tring();
+    Result +=3D "_";
+    Result +=3D CategoryImplementation[i]->getNameAsString();
+    Result +=3D "\n";
+  }
+ =20
+  Result +=3D "};\n\n";
+ =20
+  // Write objc_module metadata
+ =20
+  /*
+   struct _objc_module {
+   long version;
+   long size;
+   const char *name;
+   struct _objc_symtab *symtab;
+   }
+   */
+ =20
+  Result +=3D "\nstruct _objc_module {\n";
+  Result +=3D "\tlong version;\n";
+  Result +=3D "\tlong size;\n";
+  Result +=3D "\tconst char *name;\n";
+  Result +=3D "\tstruct _objc_symtab *symtab;\n";
+  Result +=3D "};\n\n";
+  Result +=3D "static struct _objc_module "
+  "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")=
))=3D {\n";
+  Result +=3D "\t" + utostr(OBJC_ABI_VERSION) +
+  ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
+  Result +=3D "};\n\n";
+ =20
+  if (LangOpts.MicrosoftExt) {
+    if (ProtocolExprDecls.size()) {
+      Result +=3D "#pragma section(\".objc_protocol$B\",long,read,write)\n=
";
+      Result +=3D "#pragma data_seg(push, \".objc_protocol$B\")\n";
+      for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I =3D Protoco=
lExprDecls.begin(),
+           E =3D ProtocolExprDecls.end(); I !=3D E; ++I) {
+        Result +=3D "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_=
";
+        Result +=3D (*I)->getNameAsString();
+        Result +=3D " =3D &_OBJC_PROTOCOL_";
+        Result +=3D (*I)->getNameAsString();
+        Result +=3D ";\n";
+      }
+      Result +=3D "#pragma data_seg(pop)\n\n";
+    }
+    Result +=3D "#pragma section(\".objc_module_info$B\",long,read,write)\=
n";
+    Result +=3D "#pragma data_seg(push, \".objc_module_info$B\")\n";
+    Result +=3D "static struct _objc_module *_POINTER_OBJC_MODULES =3D ";
+    Result +=3D "&_OBJC_MODULES;\n";
+    Result +=3D "#pragma data_seg(pop)\n\n";
+  }
+}
+
+/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
+/// implementation.
+void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDe=
cl *IDecl,
+                                              std::string &Result) {
+  ObjCInterfaceDecl *ClassDecl =3D IDecl->getClassInterface();
+  // Find category declaration for this implementation.
+  ObjCCategoryDecl *CDecl;
+  for (CDecl =3D ClassDecl->getCategoryList(); CDecl;
+       CDecl =3D CDecl->getNextClassCategory())
+    if (CDecl->getIdentifier() =3D=3D IDecl->getIdentifier())
+      break;
+ =20
+  std::string FullCategoryName =3D ClassDecl->getNameAsString();
+  FullCategoryName +=3D '_';
+  FullCategoryName +=3D IDecl->getNameAsString();
+ =20
+  // Build _objc_method_list for class's instance methods if needed
+  SmallVector<ObjCMethodDecl *, 32>
+  InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
+ =20
+  // If any of our property implementations have associated getters or
+  // setters, produce metadata for them as well.
+  for (ObjCImplDecl::propimpl_iterator Prop =3D IDecl->propimpl_begin(),
+       PropEnd =3D IDecl->propimpl_end();
+       Prop !=3D PropEnd; ++Prop) {
+    if ((*Prop)->getPropertyImplementation() =3D=3D ObjCPropertyImplDecl::=
Dynamic)
+      continue;
+    if (!(*Prop)->getPropertyIvarDecl())
+      continue;
+    ObjCPropertyDecl *PD =3D (*Prop)->getPropertyDecl();
+    if (!PD)
+      continue;
+    if (ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl())
+      InstanceMethods.push_back(Getter);
+    if (PD->isReadOnly())
+      continue;
+    if (ObjCMethodDecl *Setter =3D PD->getSetterMethodDecl())
+      InstanceMethods.push_back(Setter);
+  }
+  RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(=
),
+                             true, "CATEGORY_", FullCategoryName.c_str(),
+                             Result);
+ =20
+  // Build _objc_method_list for class's class methods if needed
+  RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_en=
d(),
+                             false, "CATEGORY_", FullCategoryName.c_str(),
+                             Result);
+ =20
+  // Protocols referenced in class declaration?
+  // Null CDecl is case of a category implementation with no category inte=
rface
+  if (CDecl)
+    RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATE=
GORY",
+                                    FullCategoryName, Result);
+  /* struct _objc_category {
+   char *category_name;
+   char *class_name;
+   struct _objc_method_list *instance_methods;
+   struct _objc_method_list *class_methods;
+   struct _objc_protocol_list *protocols;
+   // Objective-C 1.0 extensions
+   uint32_t size;     // sizeof (struct _objc_category)
+   struct _objc_property_list *instance_properties;  // category's own
+   // @property decl.
+   };
+   */
+ =20
+  static bool objc_category =3D false;
+  if (!objc_category) {
+    Result +=3D "\nstruct _objc_category {\n";
+    Result +=3D "\tchar *category_name;\n";
+    Result +=3D "\tchar *class_name;\n";
+    Result +=3D "\tstruct _objc_method_list *instance_methods;\n";
+    Result +=3D "\tstruct _objc_method_list *class_methods;\n";
+    Result +=3D "\tstruct _objc_protocol_list *protocols;\n";
+    Result +=3D "\tunsigned int size;\n";
+    Result +=3D "\tstruct _objc_property_list *instance_properties;\n";
+    Result +=3D "};\n";
+    objc_category =3D true;
+  }
+  Result +=3D "\nstatic struct _objc_category _OBJC_CATEGORY_";
+  Result +=3D FullCategoryName;
+  Result +=3D " __attribute__ ((used, section (\"__OBJC, __category\")))=
=3D {\n\t\"";
+  Result +=3D IDecl->getNameAsString();
+  Result +=3D "\"\n\t, \"";
+  Result +=3D ClassDecl->getNameAsString();
+  Result +=3D "\"\n";
+ =20
+  if (IDecl->instmeth_begin() !=3D IDecl->instmeth_end()) {
+    Result +=3D "\t, (struct _objc_method_list *)"
+    "&_OBJC_CATEGORY_INSTANCE_METHODS_";
+    Result +=3D FullCategoryName;
+    Result +=3D "\n";
+  }
+  else
+    Result +=3D "\t, 0\n";
+  if (IDecl->classmeth_begin() !=3D IDecl->classmeth_end()) {
+    Result +=3D "\t, (struct _objc_method_list *)"
+    "&_OBJC_CATEGORY_CLASS_METHODS_";
+    Result +=3D FullCategoryName;
+    Result +=3D "\n";
+  }
+  else
+    Result +=3D "\t, 0\n";
+ =20
+  if (CDecl && CDecl->protocol_begin() !=3D CDecl->protocol_end()) {
+    Result +=3D "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCO=
LS_";
+    Result +=3D FullCategoryName;
+    Result +=3D "\n";
+  }
+  else
+    Result +=3D "\t, 0\n";
+  Result +=3D "\t, sizeof(struct _objc_category), 0\n};\n";
+}
+
+// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
+/// class methods.
+template<typename MethodIterator>
+void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator Meth=
odBegin,
+                                             MethodIterator MethodEnd,
+                                             bool IsInstanceMethod,
+                                             StringRef prefix,
+                                             StringRef ClassName,
+                                             std::string &Result) {
+  if (MethodBegin =3D=3D MethodEnd) return;
+ =20
+  if (!objc_impl_method) {
+    /* struct _objc_method {
+     SEL _cmd;
+     char *method_types;
+     void *_imp;
+     }
+     */
+    Result +=3D "\nstruct _objc_method {\n";
+    Result +=3D "\tSEL _cmd;\n";
+    Result +=3D "\tchar *method_types;\n";
+    Result +=3D "\tvoid *_imp;\n";
+    Result +=3D "};\n";
+   =20
+    objc_impl_method =3D true;
+  }
+ =20
+  // Build _objc_method_list for class's methods if needed
+ =20
+  /* struct  {
+   struct _objc_method_list *next_method;
+   int method_count;
+   struct _objc_method method_list[];
+   }
+   */
+  unsigned NumMethods =3D std::distance(MethodBegin, MethodEnd);
+  Result +=3D "\nstatic struct {\n";
+  Result +=3D "\tstruct _objc_method_list *next_method;\n";
+  Result +=3D "\tint method_count;\n";
+  Result +=3D "\tstruct _objc_method method_list[";
+  Result +=3D utostr(NumMethods);
+  Result +=3D "];\n} _OBJC_";
+  Result +=3D prefix;
+  Result +=3D IsInstanceMethod ? "INSTANCE" : "CLASS";
+  Result +=3D "_METHODS_";
+  Result +=3D ClassName;
+  Result +=3D " __attribute__ ((used, section (\"__OBJC, __";
+  Result +=3D IsInstanceMethod ? "inst" : "cls";
+  Result +=3D "_meth\")))=3D ";
+  Result +=3D "{\n\t0, " + utostr(NumMethods) + "\n";
+ =20
+  Result +=3D "\t,{{(SEL)\"";
+  Result +=3D (*MethodBegin)->getSelector().getAsString().c_str();
+  std::string MethodTypeString;
+  Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
+  Result +=3D "\", \"";
+  Result +=3D MethodTypeString;
+  Result +=3D "\", (void *)";
+  Result +=3D MethodInternalNames[*MethodBegin];
+  Result +=3D "}\n";
+  for (++MethodBegin; MethodBegin !=3D MethodEnd; ++MethodBegin) {
+    Result +=3D "\t  ,{(SEL)\"";
+    Result +=3D (*MethodBegin)->getSelector().getAsString().c_str();
+    std::string MethodTypeString;
+    Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
+    Result +=3D "\", \"";
+    Result +=3D MethodTypeString;
+    Result +=3D "\", (void *)";
+    Result +=3D MethodInternalNames[*MethodBegin];
+    Result +=3D "}\n";
+  }
+  Result +=3D "\t }\n};\n";
+}
+
+Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
+  SourceRange OldRange =3D IV->getSourceRange();
+  Expr *BaseExpr =3D IV->getBase();
+ =20
+  // Rewrite the base, but without actually doing replaces.
+  {
+    DisableReplaceStmtScope S(*this);
+    BaseExpr =3D cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExp=
r));
+    IV->setBase(BaseExpr);
+  }
+ =20
+  ObjCIvarDecl *D =3D IV->getDecl();
+ =20
+  Expr *Replacement =3D IV;
+  if (CurMethodDef) {
+    if (BaseExpr->getType()->isObjCObjectPointerType()) {
+      const ObjCInterfaceType *iFaceDecl =3D
+      dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
+      assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
+      // lookup which class implements the instance variable.
+      ObjCInterfaceDecl *clsDeclared =3D 0;
+      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
+                                                   clsDeclared);
+      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
+     =20
+      // Synthesize an explicit cast to gain access to the ivar.
+      std::string RecName =3D clsDeclared->getIdentifier()->getName();
+      RecName +=3D "_IMPL";
+      IdentifierInfo *II =3D &Context->Idents.get(RecName);
+      RecordDecl *RD =3D RecordDecl::Create(*Context, TTK_Struct, TUDecl,
+                                          SourceLocation(), SourceLocation=
(),
+                                          II);
+      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
+      QualType castT =3D Context->getPointerType(Context->getTagDeclType(R=
D));
+      CastExpr *castExpr =3D NoTypeInfoCStyleCastExpr(Context, castT,
+                                                    CK_BitCast,
+                                                    IV->getBase());
+      // Don't forget the parens to enforce the proper binding.
+      ParenExpr *PE =3D new (Context) ParenExpr(OldRange.getBegin(),
+                                              OldRange.getEnd(),
+                                              castExpr);
+      if (IV->isFreeIvar() &&
+          declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl-=
>getDecl())) {
+        MemberExpr *ME =3D new (Context) MemberExpr(PE, true, D,
+                                                  IV->getLocation(),
+                                                  D->getType(),
+                                                  VK_LValue, OK_Ordinary);
+        Replacement =3D ME;
+      } else {
+        IV->setBase(PE);
+      }
+    }
+  } else { // we are outside a method.
+    assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside =
a method");
+   =20
+    // Explicit ivar refs need to have a cast inserted.
+    // FIXME: consider sharing some of this code with the code above.
+    if (BaseExpr->getType()->isObjCObjectPointerType()) {
+      const ObjCInterfaceType *iFaceDecl =3D
+      dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
+      // lookup which class implements the instance variable.
+      ObjCInterfaceDecl *clsDeclared =3D 0;
+      iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
+                                                   clsDeclared);
+      assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
+     =20
+      // Synthesize an explicit cast to gain access to the ivar.
+      std::string RecName =3D clsDeclared->getIdentifier()->getName();
+      RecName +=3D "_IMPL";
+      IdentifierInfo *II =3D &Context->Idents.get(RecName);
+      RecordDecl *RD =3D RecordDecl::Create(*Context, TTK_Struct, TUDecl,
+                                          SourceLocation(), SourceLocation=
(),
+                                          II);
+      assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
+      QualType castT =3D Context->getPointerType(Context->getTagDeclType(R=
D));
+      CastExpr *castExpr =3D NoTypeInfoCStyleCastExpr(Context, castT,
+                                                    CK_BitCast,
+                                                    IV->getBase());
+      // Don't forget the parens to enforce the proper binding.
+      ParenExpr *PE =3D new (Context) ParenExpr(IV->getBase()->getLocStart=
(),
+                                              IV->getBase()->getLocEnd(), =
castExpr);
+      // Cannot delete IV->getBase(), since PE points to it.
+      // Replace the old base with the cast. This is important when doing
+      // embedded rewrites. For example, [newInv->_container addObject:0].
+      IV->setBase(PE);
+    }
+  }
+ =20
+  ReplaceStmtWithRange(IV, Replacement, OldRange);
+  return Replacement; =20
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/RewriteTest.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/RewriteTest.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/RewriteTest.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -18,7 +18,7 @@
=20
 void clang::DoRewriteTest(Preprocessor &PP, raw_ostream* OS) {
   SourceManager &SM =3D PP.getSourceManager();
-  const LangOptions &LangOpts =3D PP.getLangOptions();
+  const LangOptions &LangOpts =3D PP.getLangOpts();
=20
   TokenRewriter Rewriter(SM.getMainFileID(), SM, LangOpts);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Rewr=
ite/Rewriter.cpp
--- a/head/contrib/llvm/tools/clang/lib/Rewrite/Rewriter.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Rewrite/Rewriter.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/Lex/Lexer.h"
 #include "clang/Basic/SourceManager.h"
+#include "llvm/ADT/SmallString.h"
 using namespace clang;
=20
 raw_ostream &RewriteBuffer::write(raw_ostream &os) const {
@@ -235,7 +236,7 @@
   FileID FID;
   unsigned StartOffs =3D getLocationOffsetAndFileID(Loc, FID);
=20
-  llvm::SmallString<128> indentedStr;
+  SmallString<128> indentedStr;
   if (indentNewLines && Str.find('\n') !=3D StringRef::npos) {
     StringRef MB =3D SourceMgr->getBufferData(FID);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/AnalysisBasedWarnings.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/AnalysisBasedWarnings.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -63,7 +63,7 @@
 }
=20
 /// CheckUnreachable - Check for unreachable code.
-static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
+static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
   UnreachableCodeHandler UC(S);
   reachable_code::FindUnreachableCode(AC, UC);
 }
@@ -89,7 +89,7 @@
 /// return.  We assume NeverFallThrough iff we never fall off the end of t=
he
 /// statement but we may return.  We assume that functions not marked nore=
turn
 /// will return.
-static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
+static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
   CFG *cfg =3D AC.getCFG();
   if (cfg =3D=3D 0) return UnknownFallThrough;
=20
@@ -218,7 +218,7 @@
   unsigned diag_AlwaysFallThrough_HasNoReturn;
   unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
   unsigned diag_NeverFallThroughOrReturn;
-  bool funMode;
+  enum { Function, Block, Lambda } funMode;
   SourceLocation FuncLoc;
=20
   static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
@@ -241,19 +241,8 @@
    =20
     // Don't suggest that template instantiations be marked "noreturn"
     bool isTemplateInstantiation =3D false;
-    if (const FunctionDecl *Function =3D dyn_cast<FunctionDecl>(Func)) {
-      switch (Function->getTemplateSpecializationKind()) {
-      case TSK_Undeclared:
-      case TSK_ExplicitSpecialization:
-        break;
-       =20
-      case TSK_ImplicitInstantiation:
-      case TSK_ExplicitInstantiationDeclaration:
-      case TSK_ExplicitInstantiationDefinition:
-        isTemplateInstantiation =3D true;
-        break;
-      }
-    }
+    if (const FunctionDecl *Function =3D dyn_cast<FunctionDecl>(Func))
+      isTemplateInstantiation =3D Function->isTemplateInstantiation();
        =20
     if (!isVirtualMethod && !isTemplateInstantiation)
       D.diag_NeverFallThroughOrReturn =3D
@@ -261,7 +250,7 @@
     else
       D.diag_NeverFallThroughOrReturn =3D 0;
    =20
-    D.funMode =3D true;
+    D.funMode =3D Function;
     return D;
   }
=20
@@ -277,13 +266,28 @@
       diag::err_falloff_nonvoid_block;
     D.diag_NeverFallThroughOrReturn =3D
       diag::warn_suggest_noreturn_block;
-    D.funMode =3D false;
+    D.funMode =3D Block;
+    return D;
+  }
+
+  static CheckFallThroughDiagnostics MakeForLambda() {
+    CheckFallThroughDiagnostics D;
+    D.diag_MaybeFallThrough_HasNoReturn =3D
+      diag::err_noreturn_lambda_has_return_expr;
+    D.diag_MaybeFallThrough_ReturnsNonVoid =3D
+      diag::warn_maybe_falloff_nonvoid_lambda;
+    D.diag_AlwaysFallThrough_HasNoReturn =3D
+      diag::err_noreturn_lambda_has_return_expr;
+    D.diag_AlwaysFallThrough_ReturnsNonVoid =3D
+      diag::warn_falloff_nonvoid_lambda;
+    D.diag_NeverFallThroughOrReturn =3D 0;
+    D.funMode =3D Lambda;
     return D;
   }
=20
   bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
                         bool HasNoReturn) const {
-    if (funMode) {
+    if (funMode =3D=3D Function) {
       return (ReturnsVoid ||
               D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_functi=
on,
                                    FuncLoc) =3D=3D DiagnosticsEngine::Igno=
red)
@@ -295,9 +299,9 @@
               =3D=3D DiagnosticsEngine::Ignored);
     }
=20
-    // For blocks.
-    return  ReturnsVoid && !HasNoReturn
-            && (!ReturnsVoid ||
+    // For blocks / lambdas.
+    return ReturnsVoid && !HasNoReturn
+            && ((funMode =3D=3D Lambda) ||
                 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, Fu=
ncLoc)
                   =3D=3D DiagnosticsEngine::Ignored);
   }
@@ -312,7 +316,7 @@
 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Bo=
dy,
                                     const BlockExpr *blkExpr,
                                     const CheckFallThroughDiagnostics& CD,
-                                    AnalysisContext &AC) {
+                                    AnalysisDeclContext &AC) {
=20
   bool ReturnsVoid =3D false;
   bool HasNoReturn =3D false;
@@ -421,47 +425,27 @@
 }
=20
 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
+  QualType VariableTy =3D VD->getType().getCanonicalType();
+  if (VariableTy->isBlockPointerType() &&
+      !VD->hasAttr<BlocksAttr>()) {
+    S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initializatio=
n) << VD->getDeclName()
+    << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
+    return true;
+  }
+ =20
   // Don't issue a fixit if there is already an initializer.
   if (VD->getInit())
     return false;
-
+ =20
   // Suggest possible initialization (if any).
-  const char *initialization =3D 0;
-  QualType VariableTy =3D VD->getType().getCanonicalType();
-
-  if (VariableTy->isObjCObjectPointerType() ||
-      VariableTy->isBlockPointerType()) {
-    // Check if 'nil' is defined.
-    if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
-      initialization =3D " =3D nil";
-    else
-      initialization =3D " =3D 0";
-  }
-  else if (VariableTy->isRealFloatingType())
-    initialization =3D " =3D 0.0";
-  else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlus=
Plus)
-    initialization =3D " =3D false";
-  else if (VariableTy->isEnumeralType())
+  const char *Init =3D S.getFixItZeroInitializerForType(VariableTy);
+  if (!Init)
     return false;
-  else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType(=
)) {
-    if (S.Context.getLangOptions().CPlusPlus0x)
-      initialization =3D " =3D nullptr";
-    // Check if 'NULL' is defined.
-    else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL")))
-      initialization =3D " =3D NULL";
-    else
-      initialization =3D " =3D 0";
-  }
-  else if (VariableTy->isScalarType())
-    initialization =3D " =3D 0";
-
-  if (initialization) {
-    SourceLocation loc =3D S.PP.getLocForEndOfToken(VD->getLocEnd());
-    S.Diag(loc, diag::note_var_fixit_add_initialization) << VD->getDeclNam=
e()
-      << FixItHint::CreateInsertion(loc, initialization);
-    return true;
-  }
-  return false;
+  SourceLocation Loc =3D S.PP.getLocForEndOfToken(VD->getLocEnd());
+ =20
+  S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
+    << FixItHint::CreateInsertion(Loc, Init);
+  return true;
 }
=20
 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
@@ -512,10 +496,15 @@
     }
   } else {
     const BlockExpr *BE =3D cast<BlockExpr>(E);
-    S.Diag(BE->getLocStart(),
-           isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
-                          : diag::warn_maybe_uninit_var_captured_by_block)
-      << VD->getDeclName();
+    if (VD->getType()->isBlockPointerType() &&
+        !VD->hasAttr<BlocksAttr>())
+      S.Diag(BE->getLocStart(), diag::warn_uninit_byref_blockvar_captured_=
by_block)
+        << VD->getDeclName();
+    else
+      S.Diag(BE->getLocStart(),
+             isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
+                            : diag::warn_maybe_uninit_var_captured_by_bloc=
k)
+        << VD->getDeclName();
   }
=20
   // Report where the variable was declared when the use wasn't within
@@ -586,9 +575,10 @@
       // Specially handle the case where we have uses of an uninitialized=20
       // variable, but the root cause is an idiomatic self-init.  We want
       // to report the diagnostic at the self-init since that is the root =
cause.
-      if (!vec->empty() && hasSelfInit)
+      if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
         DiagnoseUninitializedUse(S, vd, vd->getInit()->IgnoreParenCasts(),
-                                 true, /* alwaysReportSelfInit */ true);
+                                 /* isAlwaysUninit */ true,
+                                 /* alwaysReportSelfInit */ true);
       else {
         // Sort the uses by their SourceLocations.  While not strictly
         // guaranteed to produce them in line/column order, this will prov=
ide
@@ -610,6 +600,16 @@
     }
     delete uses;
   }
+
+private:
+  static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
+  for (UsesVec::const_iterator i =3D vec->begin(), e =3D vec->end(); i !=
=3D e; ++i) {
+    if (i->second) {
+      return true;
+    }
+  }
+  return false;
+}
 };
 }
=20
@@ -619,49 +619,60 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 namespace clang {
 namespace thread_safety {
-typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag;
-typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
+typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
+typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
+typedef std::list<DelayedDiag> DiagList;
=20
 struct SortDiagBySourceLocation {
-  Sema &S;
-  SortDiagBySourceLocation(Sema &S) : S(S) {}
+  SourceManager &SM;
+  SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
=20
   bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
     // Although this call will be slow, this is only called when outputting
     // multiple warnings.
-    return S.getSourceManager().isBeforeInTranslationUnit(left.first,
-                                                          right.first);
+    return SM.isBeforeInTranslationUnit(left.first.first, right.first.firs=
t);
   }
 };
=20
+namespace {
 class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHand=
ler {
   Sema &S;
   DiagList Warnings;
+  SourceLocation FunLocation, FunEndLocation;
=20
   // Helper functions
   void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc=
) {
-    PartialDiagnostic Warning =3D S.PDiag(DiagID) << LockName;
-    Warnings.push_back(DelayedDiag(Loc, Warning));
+    // Gracefully handle rare cases when the analysis can't get a more
+    // precise source location.
+    if (!Loc.isValid())
+      Loc =3D FunLocation;
+    PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
+    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
   }
=20
  public:
-  ThreadSafetyReporter(Sema &S) : S(S) {}
+  ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
+    : S(S), FunLocation(FL), FunEndLocation(FEL) {}
=20
   /// \brief Emit all buffered diagnostics in order of sourcelocation.
   /// We need to output diagnostics produced while iterating through
   /// the lockset in deterministic order, so this function orders diagnost=
ics
   /// and outputs them.
   void emitDiagnostics() {
-    SortDiagBySourceLocation SortDiagBySL(S);
-    sort(Warnings.begin(), Warnings.end(), SortDiagBySL);
+    Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
     for (DiagList::iterator I =3D Warnings.begin(), E =3D Warnings.end();
-         I !=3D E; ++I)
-      S.Diag(I->first, I->second);
+         I !=3D E; ++I) {
+      S.Diag(I->first.first, I->first.second);
+      const OptionalNotes &Notes =3D I->second;
+      for (unsigned NoteI =3D 0, NoteN =3D Notes.size(); NoteI !=3D NoteN;=
 ++NoteI)
+        S.Diag(Notes[NoteI].first, Notes[NoteI].second);
+    }
   }
=20
   void handleInvalidLockExp(SourceLocation Loc) {
-    PartialDiagnostic Warning =3D S.PDiag(diag::warn_cannot_resolve_lock) =
<< Loc;
-    Warnings.push_back(DelayedDiag(Loc, Warning));
+    PartialDiagnosticAt Warning(Loc,
+                                S.PDiag(diag::warn_cannot_resolve_lock) <<=
 Loc);
+    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
   }
   void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
     warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
@@ -671,12 +682,13 @@
     warnLockMismatch(diag::warn_double_lock, LockName, Loc);
   }
=20
-  void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc,
+  void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
+                                 SourceLocation LocEndOfScope,
                                  LockErrorKind LEK){
     unsigned DiagID =3D 0;
     switch (LEK) {
       case LEK_LockedSomePredecessors:
-        DiagID =3D diag::warn_lock_at_end_of_scope;
+        DiagID =3D diag::warn_lock_some_predecessors;
         break;
       case LEK_LockedSomeLoopIterations:
         DiagID =3D diag::warn_expecting_lock_held_on_loop;
@@ -685,18 +697,22 @@
         DiagID =3D diag::warn_no_unlock;
         break;
     }
-    warnLockMismatch(DiagID, LockName, Loc);
+    if (LocEndOfScope.isInvalid())
+      LocEndOfScope =3D FunEndLocation;
+
+    PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName=
);
+    PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
+    Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
   }
=20
=20
   void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
                                 SourceLocation Loc2) {
-    PartialDiagnostic Warning =3D
-      S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName;
-    PartialDiagnostic Note =3D
-      S.PDiag(diag::note_lock_exclusive_and_shared) << LockName;
-    Warnings.push_back(DelayedDiag(Loc1, Warning));
-    Warnings.push_back(DelayedDiag(Loc2, Note));
+    PartialDiagnosticAt Warning(
+      Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
+    PartialDiagnosticAt Note(
+      Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
+    Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
   }
=20
   void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
@@ -706,9 +722,9 @@
     unsigned DiagID =3D POK =3D=3D POK_VarAccess?
                         diag::warn_variable_requires_any_lock:
                         diag::warn_var_deref_requires_any_lock;
-    PartialDiagnostic Warning =3D S.PDiag(DiagID)
-      << D->getName() << getLockKindFromAccessKind(AK);
-    Warnings.push_back(DelayedDiag(Loc, Warning));
+    PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
+      << D->getName() << getLockKindFromAccessKind(AK));
+    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
   }
=20
   void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
@@ -725,19 +741,20 @@
         DiagID =3D diag::warn_fun_requires_lock;
         break;
     }
-    PartialDiagnostic Warning =3D S.PDiag(DiagID)
-      << D->getName() << LockName << LK;
-    Warnings.push_back(DelayedDiag(Loc, Warning));
+    PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
+      << D->getName() << LockName << LK);
+    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
   }
=20
   void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation L=
oc) {
-    PartialDiagnostic Warning =3D
-      S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName;
-    Warnings.push_back(DelayedDiag(Loc, Warning));
+    PartialDiagnosticAt Warning(Loc,
+      S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
+    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
   }
 };
 }
 }
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-=
based
@@ -813,7 +830,7 @@
   const Stmt *Body =3D D->getBody();
   assert(Body);
=20
-  AnalysisContext AC(D, 0);
+  AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0,  D, 0);
=20
   // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
   // explosion for destrutors that can result and the compile time hit.
@@ -828,8 +845,8 @@
   // prototyping, but we need a way for analyses to say what expressions t=
hey
   // expect to always be CFGElements and then fill in the BuildOptions
   // appropriately.  This is essentially a layering violation.
-  if (P.enableCheckUnreachable) {
-    // Unreachable code analysis requires a linearized CFG.
+  if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
+    // Unreachable code analysis and thread safety require a linearized CF=
G.
     AC.getCFGBuildOptions().setAllAlwaysAdd();
   }
   else {
@@ -868,8 +885,12 @@
         bool processed =3D false;
         if (const Stmt *stmt =3D i->stmt) {
           const CFGBlock *block =3D AC.getBlockForRegisteredExpression(stm=
t);
-          assert(block);
-          if (CFGReverseBlockReachabilityAnalysis *cra =3D AC.getCFGReacha=
blityAnalysis()) {
+          CFGReverseBlockReachabilityAnalysis *cra =3D
+              AC.getCFGReachablityAnalysis();
+          // FIXME: We should be able to assert that block is non-null, but
+          // the CFG analysis can skip potentially-evaluated expressions in
+          // edge cases; see test/Sema/vla-2.c.
+          if (block && cra) {
             // Can this block be reached from the entrance?
             if (cra->isReachable(&AC.getCFG()->getEntry(), block))
               S.Diag(D.Loc, D.PD);
@@ -892,17 +913,32 @@
   if (P.enableCheckFallThrough) {
     const CheckFallThroughDiagnostics &CD =3D
       (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
-                         : CheckFallThroughDiagnostics::MakeForFunction(D)=
);
+       : (isa<CXXMethodDecl>(D) &&
+          cast<CXXMethodDecl>(D)->getOverloadedOperator() =3D=3D OO_Call &&
+          cast<CXXMethodDecl>(D)->getParent()->isLambda())
+            ? CheckFallThroughDiagnostics::MakeForLambda()
+            : CheckFallThroughDiagnostics::MakeForFunction(D));
     CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
   }
=20
   // Warning: check for unreachable code
-  if (P.enableCheckUnreachable)
-    CheckUnreachable(S, AC);
+  if (P.enableCheckUnreachable) {
+    // Only check for unreachable code on non-template instantiations.
+    // Different template instantiations can effectively change the contro=
l-flow
+    // and it is very difficult to prove that a snippet of code in a templ=
ate
+    // is unreachable for all instantiations.
+    bool isTemplateInstantiation =3D false;
+    if (const FunctionDecl *Function =3D dyn_cast<FunctionDecl>(D))
+      isTemplateInstantiation =3D Function->isTemplateInstantiation();
+    if (!isTemplateInstantiation)
+      CheckUnreachable(S, AC);
+  }
=20
   // Check for thread safety violations
   if (P.enableThreadSafetyAnalysis) {
-    thread_safety::ThreadSafetyReporter Reporter(S);
+    SourceLocation FL =3D AC.getDecl()->getLocation();
+    SourceLocation FEL =3D AC.getDecl()->getLocEnd();
+    thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
     thread_safety::runThreadSafetyAnalysis(AC, Reporter);
     Reporter.emitDiagnostics();
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/AttributeList.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/AttributeList.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/AttributeList.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -101,135 +101,26 @@
   StringRef AttrName =3D Name->getName();
=20
   // Normalize the attribute name, __foo__ becomes foo.
-  if (AttrName.startswith("__") && AttrName.endswith("__"))
+  if (AttrName.startswith("__") && AttrName.endswith("__") &&
+      AttrName.size() >=3D 4)
     AttrName =3D AttrName.substr(2, AttrName.size() - 4);
=20
   return llvm::StringSwitch<AttributeList::Kind>(AttrName)
-    .Case("weak", AT_weak)
-    .Case("weakref", AT_weakref)
-    .Case("objc_arc_weak_reference_unavailable", AT_arc_weakref_unavailabl=
e)
-    .Case("pure", AT_pure)
+    #include "clang/Sema/AttrParsedAttrKinds.inc"
+    .Case("address_space", AT_address_space)
+    .Case("align", AT_aligned) // FIXME - should it be "aligned"?
+    .Case("base_check", AT_base_check)
+    .Case("bounded", IgnoredAttribute)       // OpenBSD
+    .Case("__const", AT_const) // some GCC headers do contain this spelling
+    .Case("cf_returns_autoreleased", AT_cf_returns_autoreleased)
     .Case("mode", AT_mode)
-    .Case("used", AT_used)
-    .Case("alias", AT_alias)
-    .Case("align", AT_aligned)
-    .Case("cdecl", AT_cdecl)
-    .Case("const", AT_const)
-    .Case("__const", AT_const) // some GCC headers do contain this spelling
-    .Case("blocks", AT_blocks)
-    .Case("format", AT_format)
-    .Case("malloc", AT_malloc)
-    .Case("packed", AT_packed)
-    .Case("unused", AT_unused)
-    .Case("aligned", AT_aligned)
-    .Case("cleanup", AT_cleanup)
-    .Case("naked", AT_naked)
-    .Case("nodebug", AT_nodebug)
-    .Case("nonnull", AT_nonnull)
-    .Case("nothrow", AT_nothrow)
-    .Case("objc_gc", AT_objc_gc)
-    .Case("regparm", AT_regparm)
-    .Case("section", AT_section)
-    .Case("stdcall", AT_stdcall)
-    .Case("annotate", AT_annotate)
-    .Case("fastcall", AT_fastcall)
-    .Case("ibaction", AT_IBAction)
-    .Case("iboutlet", AT_IBOutlet)
-    .Case("iboutletcollection", AT_IBOutletCollection)
-    .Case("noreturn", AT_noreturn)
-    .Case("noinline", AT_noinline)
-    .Case("sentinel", AT_sentinel)
-    .Case("NSObject", AT_nsobject)
-    .Case("dllimport", AT_dllimport)
-    .Case("dllexport", AT_dllexport)
-    .Case("may_alias", AT_may_alias)
-    .Case("base_check", AT_base_check)
-    .Case("deprecated", AT_deprecated)
-    .Case("availability", AT_availability)
-    .Case("visibility", AT_visibility)
-    .Case("destructor", AT_destructor)
-    .Case("format_arg", AT_format_arg)
-    .Case("gnu_inline", AT_gnu_inline)
-    .Case("weak_import", AT_weak_import)
-    .Case("vecreturn", AT_vecreturn)
-    .Case("vector_size", AT_vector_size)
-    .Case("constructor", AT_constructor)
-    .Case("unavailable", AT_unavailable)
-    .Case("overloadable", AT_overloadable)
-    .Case("address_space", AT_address_space)
-    .Case("opencl_image_access", AT_opencl_image_access)
-    .Case("always_inline", AT_always_inline)
-    .Case("returns_twice", AT_returns_twice)
     .Case("vec_type_hint", IgnoredAttribute)
-    .Case("objc_exception", AT_objc_exception)
-    .Case("objc_method_family", AT_objc_method_family)
-    .Case("objc_returns_inner_pointer", AT_objc_returns_inner_pointer)
     .Case("ext_vector_type", AT_ext_vector_type)
     .Case("neon_vector_type", AT_neon_vector_type)
     .Case("neon_polyvector_type", AT_neon_polyvector_type)
-    .Case("transparent_union", AT_transparent_union)
-    .Case("analyzer_noreturn", AT_analyzer_noreturn)
-    .Case("warn_unused_result", AT_warn_unused_result)
-    .Case("carries_dependency", AT_carries_dependency)
-    .Case("ns_bridged", AT_ns_bridged)
-    .Case("ns_consumed", AT_ns_consumed)
-    .Case("ns_consumes_self", AT_ns_consumes_self)
-    .Case("ns_returns_autoreleased", AT_ns_returns_autoreleased)
-    .Case("ns_returns_not_retained", AT_ns_returns_not_retained)
-    .Case("ns_returns_retained", AT_ns_returns_retained)
-    .Case("cf_audited_transfer", AT_cf_audited_transfer)
-    .Case("cf_consumed", AT_cf_consumed)
-    .Case("cf_returns_not_retained", AT_cf_returns_not_retained)
-    .Case("cf_returns_retained", AT_cf_returns_retained)
-    .Case("cf_returns_autoreleased", AT_cf_returns_autoreleased)
-    .Case("cf_unknown_transfer", AT_cf_unknown_transfer)
-    .Case("ns_consumes_self", AT_ns_consumes_self)
-    .Case("ns_consumed", AT_ns_consumed)
+    .Case("opencl_image_access", AT_opencl_image_access)
+    .Case("objc_gc", AT_objc_gc)
     .Case("objc_ownership", AT_objc_ownership)
-    .Case("objc_precise_lifetime", AT_objc_precise_lifetime)
-    .Case("ownership_returns", AT_ownership_returns)
-    .Case("ownership_holds", AT_ownership_holds)
-    .Case("ownership_takes", AT_ownership_takes)
-    .Case("reqd_work_group_size", AT_reqd_wg_size)
-    .Case("init_priority", AT_init_priority)
-    .Case("no_instrument_function", AT_no_instrument_function)
-    .Case("thiscall", AT_thiscall)
-    .Case("bounded", IgnoredAttribute)       // OpenBSD
-    .Case("pascal", AT_pascal)
-    .Case("__cdecl", AT_cdecl)
-    .Case("__stdcall", AT_stdcall)
-    .Case("__fastcall", AT_fastcall)
-    .Case("__thiscall", AT_thiscall)
-    .Case("__pascal", AT_pascal)
-    .Case("constant", AT_constant)
-    .Case("device", AT_device)
-    .Case("global", AT_global)
-    .Case("host", AT_host)
-    .Case("shared", AT_shared)
-    .Case("launch_bounds", AT_launch_bounds)
-    .Case("common", AT_common)
-    .Case("nocommon", AT_nocommon)
-    .Case("opencl_kernel_function", AT_opencl_kernel_function)
-    .Case("uuid", AT_uuid)
-    .Case("pcs", AT_pcs)
-    .Case("ms_struct", AT_MsStruct)
-    .Case("guarded_var", AT_guarded_var)
-    .Case("pt_guarded_var", AT_pt_guarded_var)
-    .Case("scoped_lockable", AT_scoped_lockable)
-    .Case("lockable", AT_lockable)
-    .Case("no_thread_safety_analysis", AT_no_thread_safety_analysis)
-    .Case("guarded_by", AT_guarded_by)
-    .Case("pt_guarded_by", AT_pt_guarded_by)
-    .Case("acquired_after", AT_acquired_after)
-    .Case("acquired_before", AT_acquired_before)
-    .Case("exclusive_lock_function", AT_exclusive_lock_function)
-    .Case("exclusive_locks_required", AT_exclusive_locks_required)
-    .Case("exclusive_trylock_function", AT_exclusive_trylock_function)
-    .Case("lock_returned", AT_lock_returned)
-    .Case("locks_excluded", AT_locks_excluded)
-    .Case("shared_lock_function", AT_shared_lock_function)
-    .Case("shared_locks_required", AT_shared_locks_required)
-    .Case("shared_trylock_function", AT_shared_trylock_function)
-    .Case("unlock_function", AT_unlock_function)
+    .Case("vector_size", AT_vector_size)
     .Default(UnknownAttribute);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/CodeCompleteConsumer.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/CodeCompleteConsumer.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/CodeCompleteConsumer.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang-c/Index.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/raw_ostream.h"
@@ -71,8 +72,8 @@
   case CCC_ObjCCategoryName:
     return false;
   }
- =20
-  return false;
+
+  llvm_unreachable("Invalid CodeCompletionContext::Kind!");
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -93,7 +94,6 @@
=20
   case CK_Optional:
     llvm_unreachable("Optional strings cannot be created from text");
-    break;
      =20
   case CK_LeftParen:
     this->Text =3D "(";
@@ -192,9 +192,12 @@
                                            unsigned Priority,=20
                                            CXAvailabilityKind Availability,
                                            const char **Annotations,
-                                           unsigned NumAnnotations)
-  : NumChunks(NumChunks), NumAnnotations(NumAnnotations)
-  , Priority(Priority), Availability(Availability)
+                                           unsigned NumAnnotations,
+                                           CXCursorKind ParentKind,
+                                           StringRef ParentName)
+  : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
+    Priority(Priority), Availability(Availability), ParentKind(ParentKind),
+    ParentName(ParentName)
 {=20
   assert(NumChunks <=3D 0xffff);
   assert(NumAnnotations <=3D 0xffff);
@@ -260,23 +263,137 @@
   // FIXME: It would be more efficient to teach Twine to tell us its size =
and
   // then add a routine there to fill in an allocated char* with the conte=
nts
   // of the string.
-  llvm::SmallString<128> Data;
+  SmallString<128> Data;
   return CopyString(String.toStringRef(Data));
 }
=20
+StringRef CodeCompletionTUInfo::getParentName(DeclContext *DC) {
+  NamedDecl *ND =3D dyn_cast<NamedDecl>(DC);
+  if (!ND)
+    return StringRef();
+ =20
+  // Check whether we've already cached the parent name.
+  StringRef &CachedParentName =3D ParentNames[DC];
+  if (!CachedParentName.empty())
+    return CachedParentName;
+
+  // If we already processed this DeclContext and assigned empty to it, the
+  // data pointer will be non-null.
+  if (CachedParentName.data() !=3D 0)
+    return StringRef();
+
+  // Find the interesting names.
+  llvm::SmallVector<DeclContext *, 2> Contexts;
+  while (DC && !DC->isFunctionOrMethod()) {
+    if (NamedDecl *ND =3D dyn_cast<NamedDecl>(DC)) {
+      if (ND->getIdentifier())
+        Contexts.push_back(DC);
+    }
+   =20
+    DC =3D DC->getParent();
+  }
+
+  {
+    llvm::SmallString<128> S;
+    llvm::raw_svector_ostream OS(S);
+    bool First =3D true;
+    for (unsigned I =3D Contexts.size(); I !=3D 0; --I) {
+      if (First)
+        First =3D false;
+      else {
+        OS << "::";
+      }
+     =20
+      DeclContext *CurDC =3D Contexts[I-1];
+      if (ObjCCategoryImplDecl *CatImpl =3D dyn_cast<ObjCCategoryImplDecl>=
(CurDC))
+        CurDC =3D CatImpl->getCategoryDecl();
+     =20
+      if (ObjCCategoryDecl *Cat =3D dyn_cast<ObjCCategoryDecl>(CurDC)) {
+        ObjCInterfaceDecl *Interface =3D Cat->getClassInterface();
+        if (!Interface) {
+          // Assign an empty StringRef but with non-null data to distingui=
sh
+          // between empty because we didn't process the DeclContext yet.
+          CachedParentName =3D StringRef((const char *)~0U, 0);
+          return StringRef();
+        }
+       =20
+        OS << Interface->getName() << '(' << Cat->getName() << ')';
+      } else {
+        OS << cast<NamedDecl>(CurDC)->getName();
+      }
+    }
+   =20
+    CachedParentName =3D AllocatorRef->CopyString(OS.str());
+  }
+
+  return CachedParentName;
+}
+
 CodeCompletionString *CodeCompletionBuilder::TakeString() {
-  void *Mem =3D Allocator.Allocate(
+  void *Mem =3D getAllocator().Allocate(
                   sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.si=
ze()
                                     + sizeof(const char *) * Annotations.s=
ize(),
                                  llvm::alignOf<CodeCompletionString>());
   CodeCompletionString *Result=20
     =3D new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
                                      Priority, Availability,
-                                     Annotations.data(), Annotations.size(=
));
+                                     Annotations.data(), Annotations.size(=
),
+                                     ParentKind, ParentName);
   Chunks.clear();
   return Result;
 }
=20
+void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
+  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
+}
+
+void CodeCompletionBuilder::AddTextChunk(const char *Text) {
+  Chunks.push_back(Chunk::CreateText(Text));
+}
+
+void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optiona=
l) {
+  Chunks.push_back(Chunk::CreateOptional(Optional));
+}
+
+void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
+  Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
+}
+
+void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
+  Chunks.push_back(Chunk::CreateInformative(Text));
+}
+
+void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
+  Chunks.push_back(Chunk::CreateResultType(ResultType));
+}
+
+void
+CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParamet=
er) {
+  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
+}
+
+void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
+                                     const char *Text) {
+  Chunks.push_back(Chunk(CK, Text));
+}
+
+void CodeCompletionBuilder::addParentContext(DeclContext *DC) {
+  if (DC->isTranslationUnit()) {
+    ParentKind =3D CXCursor_TranslationUnit;
+    return;
+  }
+ =20
+  if (DC->isFunctionOrMethod())
+    return;
+ =20
+  NamedDecl *ND =3D dyn_cast<NamedDecl>(DC);
+  if (!ND)
+    return;
+ =20
+  ParentKind =3D getCursorKindForDecl(ND);
+  ParentName =3D getCodeCompletionTUInfo().getParentName(DC);
+}
+
 unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
   if (!ND)
     return CCP_Unlikely;
@@ -330,8 +447,8 @@
   case CK_FunctionType:
     return Type;
   }
- =20
-  return 0;
+
+  llvm_unreachable("Invalid CandidateKind!");
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -356,7 +473,8 @@
       if (Results[I].Hidden)
         OS << " (Hidden)";
       if (CodeCompletionString *CCS=20
-            =3D Results[I].CreateCodeCompletionString(SemaRef, Allocator))=
 {
+            =3D Results[I].CreateCodeCompletionString(SemaRef, getAllocato=
r(),
+                                                    CCTUInfo)) {
         OS << " : " << CCS->getAsString();
       }
        =20
@@ -370,7 +488,8 @@
     case CodeCompletionResult::RK_Macro: {
       OS << Results[I].Macro->getName();
       if (CodeCompletionString *CCS=20
-            =3D Results[I].CreateCodeCompletionString(SemaRef, Allocator))=
 {
+            =3D Results[I].CreateCodeCompletionString(SemaRef, getAllocato=
r(),
+                                                    CCTUInfo)) {
         OS << " : " << CCS->getAsString();
       }
       OS << '\n';
@@ -394,17 +513,32 @@
   for (unsigned I =3D 0; I !=3D NumCandidates; ++I) {
     if (CodeCompletionString *CCS
           =3D Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
-                                                Allocator)) {
+                                                getAllocator(), CCTUInfo))=
 {
       OS << "OVERLOAD: " << CCS->getAsString() << "\n";
     }
   }
 }
=20
+/// \brief Retrieve the effective availability of the given declaration.
+static AvailabilityResult getDeclAvailability(Decl *D) {
+  AvailabilityResult AR =3D D->getAvailability();
+  if (isa<EnumConstantDecl>(D))
+    AR =3D std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability()=
);
+  return AR;
+}
+
 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessibl=
e) {
   switch (Kind) {
-  case RK_Declaration:
+  case RK_Pattern:
+    if (!Declaration) {
+      // Do nothing: Patterns can come with cursor kinds!
+      break;
+    }
+    // Fall through
+     =20
+  case RK_Declaration: {
     // Set the availability based on attributes.
-    switch (Declaration->getAvailability()) {
+    switch (getDeclAvailability(Declaration)) {
     case AR_Available:
     case AR_NotYetIntroduced:
       Availability =3D CXAvailability_Available;     =20
@@ -424,9 +558,19 @@
         Availability =3D CXAvailability_NotAvailable;
      =20
     CursorKind =3D getCursorKindForDecl(Declaration);
-    if (CursorKind =3D=3D CXCursor_UnexposedDecl)
-      CursorKind =3D CXCursor_NotImplemented;
+    if (CursorKind =3D=3D CXCursor_UnexposedDecl) {
+      // FIXME: Forward declarations of Objective-C classes and protocols=20
+      // are not directly exposed, but we want code completion to treat th=
em=20
+      // like a definition.
+      if (isa<ObjCInterfaceDecl>(Declaration))
+        CursorKind =3D CXCursor_ObjCInterfaceDecl;
+      else if (isa<ObjCProtocolDecl>(Declaration))
+        CursorKind =3D CXCursor_ObjCProtocolDecl;
+      else
+        CursorKind =3D CXCursor_NotImplemented;
+    }
     break;
+  }
=20
   case RK_Macro:
     Availability =3D CXAvailability_Available;     =20
@@ -436,11 +580,7 @@
   case RK_Keyword:
     Availability =3D CXAvailability_Available;     =20
     CursorKind =3D CXCursor_NotImplemented;
-    break;
-     =20
-  case RK_Pattern:
-    // Do nothing: Patterns can come with cursor kinds!
-    break;
+    break;     =20
   }
=20
   if (!Accessible)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/DeclSpec.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/DeclSpec.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/DeclSpec.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,6 +15,7 @@
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/LocInfoType.h"
 #include "clang/Sema/ParsedTemplate.h"
+#include "clang/Sema/SemaDiagnostic.h"
 #include "clang/Sema/Sema.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Expr.h"
@@ -150,6 +151,9 @@
                                              unsigned TypeQuals,
                                              bool RefQualifierIsLvalueRef,
                                              SourceLocation RefQualifierLo=
c,
+                                             SourceLocation ConstQualifier=
Loc,
+                                             SourceLocation
+                                                 VolatileQualifierLoc,
                                              SourceLocation MutableLoc,
                                              ExceptionSpecificationType
                                                  ESpecType,
@@ -176,6 +180,8 @@
   I.Fun.ArgInfo                 =3D 0;
   I.Fun.RefQualifierIsLValueRef =3D RefQualifierIsLvalueRef;
   I.Fun.RefQualifierLoc         =3D RefQualifierLoc.getRawEncoding();
+  I.Fun.ConstQualifierLoc       =3D ConstQualifierLoc.getRawEncoding();
+  I.Fun.VolatileQualifierLoc    =3D VolatileQualifierLoc.getRawEncoding();
   I.Fun.MutableLoc              =3D MutableLoc.getRawEncoding();
   I.Fun.ExceptionSpecType       =3D ESpecType;
   I.Fun.ExceptionSpecLoc        =3D ESpecLoc.getRawEncoding();
@@ -239,7 +245,6 @@
       return false;
     }
     llvm_unreachable("Invalid type chunk");
-    return false;
   }
  =20
   switch (DS.getTypeSpecType()) {
@@ -259,6 +264,7 @@
     case TST_float:
     case TST_half:
     case TST_int:
+    case TST_int128:
     case TST_struct:
     case TST_union:
     case TST_unknown_anytype:
@@ -289,8 +295,8 @@
       return QT->isFunctionType();
     }
   }
- =20
-  return false;
+
+  llvm_unreachable("Invalid TypeSpecType!");
 }
=20
 /// getParsedSpecifiers - Return a bitmask of which flavors of specifiers =
this
@@ -374,6 +380,7 @@
   case DeclSpec::TST_char16:      return "char16_t";
   case DeclSpec::TST_char32:      return "char32_t";
   case DeclSpec::TST_int:         return "int";
+  case DeclSpec::TST_int128:      return "__int128";
   case DeclSpec::TST_half:        return "half";
   case DeclSpec::TST_float:       return "float";
   case DeclSpec::TST_double:      return "double";
@@ -416,7 +423,7 @@
   // It seems sensible to prohibit private_extern too
   // The cl_clang_storage_class_specifiers extension enables support for
   // these storage-class specifiers.
-  if (S.getLangOptions().OpenCL &&
+  if (S.getLangOpts().OpenCL &&
       !S.getOpenCLOptions().cl_clang_storage_class_specifiers) {
     switch (SC) {
     case SCS_extern:
@@ -435,7 +442,7 @@
   if (StorageClassSpec !=3D SCS_unspecified) {
     // Maybe this is an attempt to use C++0x 'auto' outside of C++0x mode.
     bool isInvalid =3D true;
-    if (TypeSpecType =3D=3D TST_unspecified && S.getLangOptions().CPlusPlu=
s) {
+    if (TypeSpecType =3D=3D TST_unspecified && S.getLangOpts().CPlusPlus) {
       if (SC =3D=3D SCS_auto)
         return SetTypeSpecType(TST_auto, Loc, PrevSpec, DiagID);
       if (StorageClassSpec =3D=3D SCS_auto) {
@@ -813,7 +820,7 @@
   if (TypeSpecSign !=3D TSS_unspecified) {
     if (TypeSpecType =3D=3D TST_unspecified)
       TypeSpecType =3D TST_int; // unsigned -> unsigned int, signed -> sig=
ned int.
-    else if (TypeSpecType !=3D TST_int  &&
+    else if (TypeSpecType !=3D TST_int  && TypeSpecType !=3D TST_int128 &&
              TypeSpecType !=3D TST_char && TypeSpecType !=3D TST_wchar) {
       Diag(D, TSSLoc, diag::err_invalid_sign_spec)
         << getSpecifierName((TST)TypeSpecType);
@@ -861,7 +868,8 @@
       TypeSpecType =3D TST_double;   // _Complex -> _Complex double.
     } else if (TypeSpecType =3D=3D TST_int || TypeSpecType =3D=3D TST_char=
) {
       // Note that this intentionally doesn't include _Complex _Bool.
-      Diag(D, TSTLoc, diag::ext_integer_complex);
+      if (!PP.getLangOpts().CPlusPlus)
+        Diag(D, TSTLoc, diag::ext_integer_complex);
     } else if (TypeSpecType !=3D TST_float && TypeSpecType !=3D TST_double=
) {
       Diag(D, TSCLoc, diag::err_invalid_complex_spec)
         << getSpecifierName((TST)TypeSpecType);
@@ -874,7 +882,7 @@
   // class specifier, then assume this is an attempt to use C++0x's 'auto'
   // type specifier.
   // FIXME: Does Microsoft really support implicit int in C++?
-  if (PP.getLangOptions().CPlusPlus && !PP.getLangOptions().MicrosoftExt &&
+  if (PP.getLangOpts().CPlusPlus && !PP.getLangOpts().MicrosoftExt &&
       TypeSpecType =3D=3D TST_unspecified && StorageClassSpec =3D=3D SCS_a=
uto) {
     TypeSpecType =3D TST_auto;
     StorageClassSpec =3D StorageClassSpecAsWritten =3D SCS_unspecified;
@@ -883,12 +891,17 @@
   }
   // Diagnose if we've recovered from an ill-formed 'auto' storage class
   // specifier in a pre-C++0x dialect of C++.
-  if (!PP.getLangOptions().CPlusPlus0x && TypeSpecType =3D=3D TST_auto)
+  if (!PP.getLangOpts().CPlusPlus0x && TypeSpecType =3D=3D TST_auto)
     Diag(D, TSTLoc, diag::ext_auto_type_specifier);
-  if (PP.getLangOptions().CPlusPlus && !PP.getLangOptions().CPlusPlus0x &&
+  if (PP.getLangOpts().CPlusPlus && !PP.getLangOpts().CPlusPlus0x &&
       StorageClassSpec =3D=3D SCS_auto)
     Diag(D, StorageClassSpecLoc, diag::warn_auto_storage_class)
       << FixItHint::CreateRemoval(StorageClassSpecLoc);
+  if (TypeSpecType =3D=3D TST_char16 || TypeSpecType =3D=3D TST_char32)
+    Diag(D, TSTLoc, diag::warn_cxx98_compat_unicode_type)
+      << (TypeSpecType =3D=3D TST_char16 ? "char16_t" : "char32_t");
+  if (Constexpr_specified)
+    Diag(D, ConstexprLoc, diag::warn_cxx98_compat_constexpr);
=20
   // C++ [class.friend]p6:
   //   No storage-class-specifier shall appear in the decl-specifier-seq
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/DelayedDiagnostic.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/DelayedDiagnostic.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/DelayedDiagnostic.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -20,13 +20,15 @@
 using namespace sema;
=20
 DelayedDiagnostic DelayedDiagnostic::makeDeprecation(SourceLocation Loc,
-                                                     const NamedDecl *D,
-                                                     StringRef Msg) {
+                                    const NamedDecl *D,
+                                    const ObjCInterfaceDecl *UnknownObjCCl=
ass,
+                                    StringRef Msg) {
   DelayedDiagnostic DD;
   DD.Kind =3D Deprecation;
   DD.Triggered =3D false;
   DD.Loc =3D Loc;
   DD.DeprecationData.Decl =3D D;
+  DD.DeprecationData.UnknownObjCClass =3D UnknownObjCClass;
   char *MessageData =3D 0;
   if (Msg.size()) {
     MessageData =3D new char [Msg.size()];
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/IdentifierResolver.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/IdentifierResolver.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/IdentifierResolver.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -15,7 +15,10 @@
 #include "clang/Sema/IdentifierResolver.h"
 #include "clang/Sema/Scope.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Lex/ExternalPreprocessorSource.h"
+#include "clang/Lex/Preprocessor.h"
=20
 using namespace clang;
=20
@@ -93,9 +96,11 @@
 // IdentifierResolver Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-IdentifierResolver::IdentifierResolver(const LangOptions &langOpt)
-    : LangOpt(langOpt), IdDeclInfos(new IdDeclInfoMap) {
+IdentifierResolver::IdentifierResolver(Preprocessor &PP)
+  : LangOpt(PP.getLangOpts()), PP(PP),
+    IdDeclInfos(new IdDeclInfoMap) {
 }
+
 IdentifierResolver::~IdentifierResolver() {
   delete IdDeclInfos;
 }
@@ -108,7 +113,7 @@
                              bool ExplicitInstantiationOrSpecialization) c=
onst {
   Ctx =3D Ctx->getRedeclContext();
=20
-  if (Ctx->isFunctionOrMethod()) {
+  if (Ctx->isFunctionOrMethod() || S->isFunctionPrototypeScope()) {
     // Ignore the scopes associated within transparent declaration context=
s.
     while (S->getEntity() &&
            ((DeclContext *)S->getEntity())->isTransparentContext())
@@ -146,7 +151,7 @@
 void IdentifierResolver::AddDecl(NamedDecl *D) {
   DeclarationName Name =3D D->getDeclName();
   if (IdentifierInfo *II =3D Name.getAsIdentifierInfo())
-    II->setIsFromAST(false);
+    updatingIdentifier(*II);
=20
   void *Ptr =3D Name.getFETokenInfo<void>();
=20
@@ -170,6 +175,9 @@
=20
 void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) {
   DeclarationName Name =3D D->getDeclName();
+  if (IdentifierInfo *II =3D Name.getAsIdentifierInfo())
+    updatingIdentifier(*II);
+ =20
   void *Ptr =3D Name.getFETokenInfo<void>();
  =20
   if (!Ptr) {
@@ -194,9 +202,6 @@
     return;
   }
=20
-  if (IdentifierInfo *II =3D Name.getAsIdentifierInfo())
-    II->setIsFromAST(false);
- =20
   // General case: insert the declaration at the appropriate point in the=20
   // list, which already has at least two elements.
   IdDeclInfo *IDI =3D toIdDeclInfo(Ptr);
@@ -212,7 +217,7 @@
   assert(D && "null param passed");
   DeclarationName Name =3D D->getDeclName();
   if (IdentifierInfo *II =3D Name.getAsIdentifierInfo())
-    II->setIsFromAST(false);
+    updatingIdentifier(*II);
=20
   void *Ptr =3D Name.getFETokenInfo<void>();
=20
@@ -233,7 +238,7 @@
=20
   DeclarationName Name =3D Old->getDeclName();
   if (IdentifierInfo *II =3D Name.getAsIdentifierInfo())
-    II->setIsFromAST(false);
+    updatingIdentifier(*II);
=20
   void *Ptr =3D Name.getFETokenInfo<void>();
=20
@@ -254,6 +259,9 @@
 /// begin - Returns an iterator for decls with name 'Name'.
 IdentifierResolver::iterator
 IdentifierResolver::begin(DeclarationName Name) {
+  if (IdentifierInfo *II =3D Name.getAsIdentifierInfo())
+    readingIdentifier(*II);
+   =20
   void *Ptr =3D Name.getFETokenInfo<void>();
   if (!Ptr) return end();
=20
@@ -269,27 +277,133 @@
   return end();
 }
=20
-void IdentifierResolver::AddDeclToIdentifierChain(IdentifierInfo *II,
-                                                  NamedDecl *D) {
-  II->setIsFromAST(false);
-  void *Ptr =3D II->getFETokenInfo<void>();
+namespace {
+  enum DeclMatchKind {
+    DMK_Different,
+    DMK_Replace,
+    DMK_Ignore
+  };
+}
=20
+/// \brief Compare two declarations to see whether they are different or,
+/// if they are the same, whether the new declaration should replace the=20
+/// existing declaration.
+static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *N=
ew) {
+  // If the declarations are identical, ignore the new one.
+  if (Existing =3D=3D New)
+    return DMK_Ignore;
+
+  // If the declarations have different kinds, they're obviously different.
+  if (Existing->getKind() !=3D New->getKind())
+    return DMK_Different;
+
+  // If the declarations are redeclarations of each other, keep the newest=
 one.
+  if (Existing->getCanonicalDecl() =3D=3D New->getCanonicalDecl()) {
+    // If the existing declaration is somewhere in the previous declaration
+    // chain of the new declaration, then prefer the new declaration.
+    for (Decl::redecl_iterator RD =3D New->redecls_begin(),=20
+                            RDEnd =3D New->redecls_end();
+         RD !=3D RDEnd; ++RD) {
+      if (*RD =3D=3D Existing)
+        return DMK_Replace;
+       =20
+      if (RD->isCanonicalDecl())
+        break;
+    }
+   =20
+    return DMK_Ignore;
+  }
+ =20
+  return DMK_Different;
+}
+
+bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName =
Name){
+  if (IdentifierInfo *II =3D Name.getAsIdentifierInfo())
+    readingIdentifier(*II);
+ =20
+  void *Ptr =3D Name.getFETokenInfo<void>();
+   =20
   if (!Ptr) {
-    II->setFETokenInfo(D);
-    return;
+    Name.setFETokenInfo(D);
+    return true;
   }
+ =20
+  IdDeclInfo *IDI;
+ =20
+  if (isDeclPtr(Ptr)) {
+    NamedDecl *PrevD =3D static_cast<NamedDecl*>(Ptr);
+   =20
+    switch (compareDeclarations(PrevD, D)) {
+    case DMK_Different:
+      break;
+     =20
+    case DMK_Ignore:
+      return false;
+     =20
+    case DMK_Replace:
+      Name.setFETokenInfo(D);
+      return true;
+    }
+   =20
+    Name.setFETokenInfo(NULL);
+    IDI =3D &(*IdDeclInfos)[Name];
+   =20
+    // If the existing declaration is not visible in translation unit scop=
e,
+    // then add the new top-level declaration first.
+    if (!PrevD->getDeclContext()->getRedeclContext()->isTranslationUnit())=
 {
+      IDI->AddDecl(D);
+      IDI->AddDecl(PrevD);
+    } else {
+      IDI->AddDecl(PrevD);
+      IDI->AddDecl(D);
+    }
+    return true;
+  }=20
+ =20
+  IDI =3D toIdDeclInfo(Ptr);
=20
-  IdDeclInfo *IDI;
+  // See whether this declaration is identical to any existing declaration=
s.
+  // If not, find the right place to insert it.
+  for (IdDeclInfo::DeclsTy::iterator I =3D IDI->decls_begin(),=20
+                                  IEnd =3D IDI->decls_end();
+       I !=3D IEnd; ++I) {
+   =20
+    switch (compareDeclarations(*I, D)) {
+    case DMK_Different:
+      break;
+     =20
+    case DMK_Ignore:
+      return false;
+     =20
+    case DMK_Replace:
+      *I =3D D;
+      return true;
+    }
+   =20
+    if (!(*I)->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
+      // We've found a declaration that is not visible from the translation
+      // unit (it's in an inner scope). Insert our declaration here.
+      IDI->InsertDecl(I, D);
+      return true;
+    }
+  }
+ =20
+  // Add the declaration to the end.
+  IDI->AddDecl(D);
+  return true;
+}
=20
-  if (isDeclPtr(Ptr)) {
-    II->setFETokenInfo(NULL);
-    IDI =3D &(*IdDeclInfos)[II];
-    NamedDecl *PrevD =3D static_cast<NamedDecl*>(Ptr);
-    IDI->AddDecl(PrevD);
-  } else
-    IDI =3D toIdDeclInfo(Ptr);
+void IdentifierResolver::readingIdentifier(IdentifierInfo &II) {
+  if (II.isOutOfDate())
+    PP.getExternalSource()->updateOutOfDateIdentifier(II); =20
+}
=20
-  IDI->AddDecl(D);
+void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) {
+  if (II.isOutOfDate())
+    PP.getExternalSource()->updateOutOfDateIdentifier(II);
+ =20
+  if (II.isFromAST())
+    II.setChangedSinceDeserialization();
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/JumpDiagnostics.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/JumpDiagnostics.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/JumpDiagnostics.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -42,10 +42,10 @@
     /// the parent scope is the function body.
     unsigned ParentScope;
=20
-    /// InDiag - The diagnostic to emit if there is a jump into this scope.
+    /// InDiag - The note to emit if there is a jump into this scope.
     unsigned InDiag;
=20
-    /// OutDiag - The diagnostic to emit if there is an indirect jump out
+    /// OutDiag - The note to emit if there is an indirect jump out
     /// of this scope.  Direct jumps always clean up their current scope
     /// in an orderly way.
     unsigned OutDiag;
@@ -74,10 +74,12 @@
  =20
   void VerifyJumps();
   void VerifyIndirectJumps();
+  void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
   void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
                             LabelDecl *Target, unsigned TargetScope);
   void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
-                 unsigned JumpDiag, unsigned JumpDiagWarning);
+                 unsigned JumpDiag, unsigned JumpDiagWarning,
+                 unsigned JumpDiagCXX98Compat);
=20
   unsigned GetDeepestCommonScope(unsigned A, unsigned B);
 };
@@ -133,7 +135,7 @@
       return ScopePair(diag::note_protected_by_cleanup,
                        diag::note_exits_cleanup);
=20
-    if (Context.getLangOptions().ObjCAutoRefCount && VD->hasLocalStorage()=
) {
+    if (Context.getLangOpts().ObjCAutoRefCount && VD->hasLocalStorage()) {
       switch (VD->getType().getObjCLifetime()) {
       case Qualifiers::OCL_None:
       case Qualifiers::OCL_ExplicitNone:
@@ -147,8 +149,8 @@
       }
     }
=20
-    if (Context.getLangOptions().CPlusPlus && VD->hasLocalStorage()) {
-      // C++0x [stmt.dcl]p3:
+    if (Context.getLangOpts().CPlusPlus && VD->hasLocalStorage()) {
+      // C++11 [stmt.dcl]p3:
       //   A program that jumps from a point where a variable with automat=
ic
       //   storage duration is not in scope to a point where it is in scope
       //   is ill-formed unless the variable has scalar type, class type w=
ith
@@ -177,13 +179,12 @@
           record =3D ctor->getParent();
=20
           if (ctor->isTrivial() && ctor->isDefaultConstructor()) {
-            if (Context.getLangOptions().CPlusPlus0x) {
-              inDiagToUse =3D (record->hasTrivialDestructor() ? 0 :
-                        diag::note_protected_by_variable_nontriv_destructo=
r);
-            } else {
-              if (record->isPOD())
-                inDiagToUse =3D 0;
-            }
+            if (!record->hasTrivialDestructor())
+              inDiagToUse =3D diag::note_protected_by_variable_nontriv_des=
tructor;
+            else if (!record->isPOD())
+              inDiagToUse =3D diag::note_protected_by_variable_non_pod;
+            else
+              inDiagToUse =3D 0;
           }
         } else if (VD->getType()->isArrayType()) {
           record =3D VD->getType()->getBaseElementTypeUnsafe()
@@ -258,7 +259,7 @@
                           diag::note_exits_block_captures_weak);
         break;
       case QualType::DK_none:
-        llvm_unreachable("no-liftime captured variable");
+        llvm_unreachable("non-lifetime captured variable");
     }
     SourceLocation Loc =3D D->getLocation();
     if (Loc.isInvalid())
@@ -477,7 +478,8 @@
     if (GotoStmt *GS =3D dyn_cast<GotoStmt>(Jump)) {
       CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
                 diag::err_goto_into_protected_scope,
-                diag::warn_goto_into_protected_scope);
+                diag::warn_goto_into_protected_scope,
+                diag::warn_cxx98_compat_goto_into_protected_scope);
       continue;
     }
=20
@@ -486,7 +488,8 @@
       LabelDecl *Target =3D IGS->getConstantTarget();
       CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
                 diag::err_goto_into_protected_scope,
-                diag::warn_goto_into_protected_scope);
+                diag::warn_goto_into_protected_scope,
+                diag::warn_cxx98_compat_goto_into_protected_scope);
       continue;
     }
=20
@@ -495,7 +498,8 @@
          SC =3D SC->getNextSwitchCase()) {
       assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
       CheckJump(SS, SC, SC->getLocStart(),
-                diag::err_switch_into_protected_scope, 0);
+                diag::err_switch_into_protected_scope, 0,
+                diag::warn_cxx98_compat_switch_into_protected_scope);
     }
   }
 }
@@ -639,6 +643,39 @@
   }
 }
=20
+/// Return true if a particular error+note combination must be downgraded =
to a
+/// warning in Microsoft mode.
+static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote)=
 {
+  return (JumpDiag =3D=3D diag::err_goto_into_protected_scope &&
+         (InDiagNote =3D=3D diag::note_protected_by_variable_init ||
+          InDiagNote =3D=3D diag::note_protected_by_variable_nontriv_destr=
uctor));
+}
+
+/// Return true if a particular note should be downgraded to a compatibili=
ty
+/// warning in C++11 mode.
+static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
+  return S.getLangOpts().CPlusPlus0x &&
+         InDiagNote =3D=3D diag::note_protected_by_variable_non_pod;
+}
+
+/// Produce primary diagnostic for an indirect jump statement.
+static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
+                                     LabelDecl *Target, bool &Diagnosed) {
+  if (Diagnosed)
+    return;
+  S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
+  S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target=
);
+  Diagnosed =3D true;
+}
+
+/// Produce note diagnostics for a jump into a protected scope.
+void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
+  assert(!ToScopes.empty());
+  for (unsigned I =3D 0, E =3D ToScopes.size(); I !=3D E; ++I)
+    if (Scopes[ToScopes[I]].InDiag)
+      S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
+}
+
 /// Diagnose an indirect jump which is known to cross scopes.
 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
                                             unsigned JumpScope,
@@ -646,36 +683,41 @@
                                             unsigned TargetScope) {
   assert(JumpScope !=3D TargetScope);
=20
-  S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
-  S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target=
);
-
   unsigned Common =3D GetDeepestCommonScope(JumpScope, TargetScope);
+  bool Diagnosed =3D false;
=20
   // Walk out the scope chain until we reach the common ancestor.
   for (unsigned I =3D JumpScope; I !=3D Common; I =3D Scopes[I].ParentScop=
e)
-    if (Scopes[I].OutDiag)
+    if (Scopes[I].OutDiag) {
+      DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
       S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
+    }
+
+  SmallVector<unsigned, 10> ToScopesCXX98Compat;
=20
   // Now walk into the scopes containing the label whose address was taken.
   for (unsigned I =3D TargetScope; I !=3D Common; I =3D Scopes[I].ParentSc=
ope)
-    if (Scopes[I].InDiag)
+    if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
+      ToScopesCXX98Compat.push_back(I);
+    else if (Scopes[I].InDiag) {
+      DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
       S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
+    }
+
+  // Diagnose this jump if it would be ill-formed in C++98.
+  if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
+    S.Diag(Jump->getGotoLoc(),
+           diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
+    S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_targ=
et);
+    NoteJumpIntoScopes(ToScopesCXX98Compat);
+  }
 }
=20
-/// Return true if a particular error+note combination must be downgraded
-/// to a warning in Microsoft mode.
-static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote)
-{
-    return (JumpDiag =3D=3D diag::err_goto_into_protected_scope &&=20
-           (InDiagNote =3D=3D diag::note_protected_by_variable_init ||=20
-            InDiagNote =3D=3D diag::note_protected_by_variable_nontriv_des=
tructor));
-}
-
-
 /// CheckJump - Validate that the specified jump statement is valid: that =
it is
 /// jumping within or out of its current scope, not into a deeper one.
 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation Diag=
Loc,
-                             unsigned JumpDiagError, unsigned JumpDiagWarn=
ing) {
+                               unsigned JumpDiagError, unsigned JumpDiagWa=
rning,
+                                 unsigned JumpDiagCXX98Compat) {
   assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scope=
s?");
   unsigned FromScope =3D LabelAndGotoScopes[From];
=20
@@ -691,12 +733,15 @@
   if (CommonScope =3D=3D ToScope) return;
=20
   // Pull out (and reverse) any scopes we might need to diagnose skipping.
+  SmallVector<unsigned, 10> ToScopesCXX98Compat;
   SmallVector<unsigned, 10> ToScopesError;
   SmallVector<unsigned, 10> ToScopesWarning;
   for (unsigned I =3D ToScope; I !=3D CommonScope; I =3D Scopes[I].ParentS=
cope) {
-    if (S.getLangOptions().MicrosoftMode && JumpDiagWarning !=3D 0 &&
+    if (S.getLangOpts().MicrosoftMode && JumpDiagWarning !=3D 0 &&
         IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
       ToScopesWarning.push_back(I);
+    else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
+      ToScopesCXX98Compat.push_back(I);
     else if (Scopes[I].InDiag)
       ToScopesError.push_back(I);
   }
@@ -704,16 +749,19 @@
   // Handle warnings.
   if (!ToScopesWarning.empty()) {
     S.Diag(DiagLoc, JumpDiagWarning);
-    for (unsigned i =3D 0, e =3D ToScopesWarning.size(); i !=3D e; ++i)
-      S.Diag(Scopes[ToScopesWarning[i]].Loc, Scopes[ToScopesWarning[i]].In=
Diag);
+    NoteJumpIntoScopes(ToScopesWarning);
   }
=20
   // Handle errors.
   if (!ToScopesError.empty()) {
     S.Diag(DiagLoc, JumpDiagError);
-    // Emit diagnostics note for whatever is left in ToScopesError.
-    for (unsigned i =3D 0, e =3D ToScopesError.size(); i !=3D e; ++i)
-      S.Diag(Scopes[ToScopesError[i]].Loc, Scopes[ToScopesError[i]].InDiag=
);
+    NoteJumpIntoScopes(ToScopesError);
+  }
+
+  // Handle -Wc++98-compat warnings if the jump is well-formed.
+  if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
+    S.Diag(DiagLoc, JumpDiagCXX98Compat);
+    NoteJumpIntoScopes(ToScopesCXX98Compat);
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/Scope.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/Scope.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/Scope.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -19,23 +19,28 @@
 void Scope::Init(Scope *parent, unsigned flags) {
   AnyParent =3D parent;
   Flags =3D flags;
-   =20
+
+  if (parent && !(flags & FnScope)) {
+    BreakParent    =3D parent->BreakParent;
+    ContinueParent =3D parent->ContinueParent;
+  } else {
+    // Control scopes do not contain the contents of nested function scope=
s for
+    // control flow purposes.
+    BreakParent =3D ContinueParent =3D 0;
+  }
+
   if (parent) {
     Depth =3D parent->Depth + 1;
     PrototypeDepth =3D parent->PrototypeDepth;
     PrototypeIndex =3D 0;
     FnParent       =3D parent->FnParent;
-    BreakParent    =3D parent->BreakParent;
-    ContinueParent =3D parent->ContinueParent;
-    ControlParent  =3D parent->ControlParent;
     BlockParent    =3D parent->BlockParent;
     TemplateParamParent =3D parent->TemplateParamParent;
   } else {
     Depth =3D 0;
     PrototypeDepth =3D 0;
     PrototypeIndex =3D 0;
-    FnParent =3D BreakParent =3D ContinueParent =3D BlockParent =3D 0;
-    ControlParent =3D 0;
+    FnParent =3D BlockParent =3D 0;
     TemplateParamParent =3D 0;
   }
=20
@@ -43,7 +48,6 @@
   if (flags & FnScope)            FnParent =3D this;
   if (flags & BreakScope)         BreakParent =3D this;
   if (flags & ContinueScope)      ContinueParent =3D this;
-  if (flags & ControlScope)       ControlParent =3D this;
   if (flags & BlockScope)         BlockParent =3D this;
   if (flags & TemplateParamScope) TemplateParamParent =3D this;
=20
@@ -55,3 +59,13 @@
   Entity =3D 0;
   ErrorTrap.reset();
 }
+
+bool Scope::containedInPrototypeScope() const {
+  const Scope *S =3D this;
+  while (S) {
+    if (S->isFunctionPrototypeScope())
+      return true;
+    S =3D S->getParent();
+  }
+  return false;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/Sema.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/Sema.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/Sema.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -33,6 +33,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/StmtCXX.h"
+#include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/PartialDiagnostic.h"
@@ -54,10 +55,12 @@
 }
=20
 BlockScopeInfo::~BlockScopeInfo() { }
+LambdaScopeInfo::~LambdaScopeInfo() { }
=20
-PrintingPolicy Sema::getPrintingPolicy() const {
+PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
+                                       const Preprocessor &PP) {
   PrintingPolicy Policy =3D Context.getPrintingPolicy();
-  Policy.Bool =3D getLangOptions().Bool;
+  Policy.Bool =3D Context.getLangOpts().Bool;
   if (!Policy.Bool) {
     if (MacroInfo *BoolMacro =3D PP.getMacroInfo(&Context.Idents.get("bool=
"))) {
       Policy.Bool =3D BoolMacro->isObjectLike() &&=20
@@ -74,36 +77,26 @@
   PushDeclContext(S, Context.getTranslationUnitDecl());
=20
   VAListTagName =3D PP.getIdentifierInfo("__va_list_tag");
-
-  if (PP.getLangOptions().ObjC1) {
-    // Synthesize "@class Protocol;
-    if (Context.getObjCProtoType().isNull()) {
-      ObjCInterfaceDecl *ProtocolDecl =3D
-        ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
-                                  &Context.Idents.get("Protocol"),
-                                  SourceLocation(), true);
-      Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
-      PushOnScopeChains(ProtocolDecl, TUScope, false);
-    } =20
-  }
 }
=20
 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
            TranslationUnitKind TUKind,
            CodeCompleteConsumer *CodeCompleter)
-  : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
-    LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consume=
r),
+  : TheTargetAttributesSema(0), FPFeatures(pp.getLangOpts()),
+    LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
     Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
     CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter),
     CurContext(0), OriginalLexicalContext(0),
     PackContext(0), MSStructPragmaOn(false), VisContext(0),
-    ExprNeedsCleanups(0), LateTemplateParser(0), OpaqueParser(0),
-    IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
+    ExprNeedsCleanups(false), LateTemplateParser(0), OpaqueParser(0),
+    IdResolver(pp), StdInitializerList(0), CXXTypeInfoDecl(0), MSVCGuidDec=
l(0),
+    NSNumberDecl(0), NSArrayDecl(0), ArrayWithObjectsMethod(0),=20
+    NSDictionaryDecl(0), DictionaryWithObjectsMethod(0),
     GlobalNewDeleteDeclared(false),=20
     ObjCShouldCallSuperDealloc(false),
     ObjCShouldCallSuperFinalize(false),
     TUKind(TUKind),
-    NumSFINAEErrors(0), SuppressAccessChecking(false),=20
+    NumSFINAEErrors(0), InFunctionDeclarator(0), SuppressAccessChecking(fa=
lse),=20
     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
     CurrentInstantiationScope(0), TyposCorrected(0),
@@ -111,8 +104,13 @@
 {
   TUScope =3D 0;
   LoadedExternalKnownNamespaces =3D false;
- =20
-  if (getLangOptions().CPlusPlus)
+  for (unsigned I =3D 0; I !=3D NSAPI::NumNSNumberLiteralMethods; ++I)
+    NSNumberLiteralMethods[I] =3D 0;
+
+  if (getLangOpts().ObjC1)
+    NSAPIObj.reset(new NSAPI(Context));
+
+  if (getLangOpts().CPlusPlus)
     FieldCollector.reset(new CXXFieldCollector());
=20
   // Tell diagnostics how to render things from the AST library.
@@ -120,7 +118,8 @@
                                        &Context);
=20
   ExprEvalContexts.push_back(
-        ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0, false));
+        ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0,
+                                          false, 0, false));
=20
   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
 }
@@ -143,33 +142,38 @@
     // If either of the 128-bit integer types are unavailable to name look=
up,
     // define them now.
     DeclarationName Int128 =3D &Context.Idents.get("__int128_t");
-    if (IdentifierResolver::begin(Int128) =3D=3D IdentifierResolver::end())
+    if (IdResolver.begin(Int128) =3D=3D IdResolver.end())
       PushOnScopeChains(Context.getInt128Decl(), TUScope);
=20
     DeclarationName UInt128 =3D &Context.Idents.get("__uint128_t");
-    if (IdentifierResolver::begin(UInt128) =3D=3D IdentifierResolver::end(=
))
+    if (IdResolver.begin(UInt128) =3D=3D IdResolver.end())
       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
   }
  =20
=20
   // Initialize predefined Objective-C types:
-  if (PP.getLangOptions().ObjC1) {
+  if (PP.getLangOpts().ObjC1) {
     // If 'SEL' does not yet refer to any declarations, make it refer to t=
he
     // predefined 'SEL'.
     DeclarationName SEL =3D &Context.Idents.get("SEL");
-    if (IdentifierResolver::begin(SEL) =3D=3D IdentifierResolver::end())
+    if (IdResolver.begin(SEL) =3D=3D IdResolver.end())
       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
=20
     // If 'id' does not yet refer to any declarations, make it refer to the
     // predefined 'id'.
     DeclarationName Id =3D &Context.Idents.get("id");
-    if (IdentifierResolver::begin(Id) =3D=3D IdentifierResolver::end())
+    if (IdResolver.begin(Id) =3D=3D IdResolver.end())
       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
    =20
     // Create the built-in typedef for 'Class'.
     DeclarationName Class =3D &Context.Idents.get("Class");
-    if (IdentifierResolver::begin(Class) =3D=3D IdentifierResolver::end())
+    if (IdResolver.begin(Class) =3D=3D IdResolver.end())
       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
+
+    // Create the built-in forward declaratino for 'Protocol'.
+    DeclarationName Protocol =3D &Context.Idents.get("Protocol");
+    if (IdResolver.begin(Protocol) =3D=3D IdResolver.end())
+      PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
   }
 }
=20
@@ -240,13 +244,28 @@
                                    CastKind Kind, ExprValueKind VK,
                                    const CXXCastPath *BasePath,
                                    CheckedConversionKind CCK) {
+#ifndef NDEBUG
+  if (VK =3D=3D VK_RValue && !E->isRValue()) {
+    switch (Kind) {
+    default:
+      assert(0 && "can't implicitly cast lvalue to rvalue with this cast k=
ind");
+    case CK_LValueToRValue:
+    case CK_ArrayToPointerDecay:
+    case CK_FunctionToPointerDecay:
+    case CK_ToVoid:
+      break;
+    }
+  }
+  assert((VK =3D=3D VK_RValue || !E->isRValue()) && "can't cast rvalue to =
lvalue");
+#endif
+
   QualType ExprTy =3D Context.getCanonicalType(E->getType());
   QualType TypeTy =3D Context.getCanonicalType(Ty);
=20
   if (ExprTy =3D=3D TypeTy)
     return Owned(E);
=20
-  if (getLangOptions().ObjCAutoRefCount)
+  if (getLangOpts().ObjCAutoRefCount)
     CheckObjCARCConversion(SourceRange(), Ty, E, CCK);
=20
   // If this is a derived-to-base cast to a through a virtual base, we
@@ -303,7 +322,7 @@
=20
     // Later redecls may add new information resulting in not having to wa=
rn,
     // so check again.
-    DeclToCheck =3D FD->getMostRecentDeclaration();
+    DeclToCheck =3D FD->getMostRecentDecl();
     if (DeclToCheck !=3D FD)
       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
   }
@@ -317,7 +336,7 @@
=20
     // Later redecls may add new information resulting in not having to wa=
rn,
     // so check again.
-    DeclToCheck =3D VD->getMostRecentDeclaration();
+    DeclToCheck =3D VD->getMostRecentDecl();
     if (DeclToCheck !=3D VD)
       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
   }
@@ -407,6 +426,8 @@
   // Only complete translation units define vtables and perform implicit
   // instantiations.
   if (TUKind =3D=3D TU_Complete) {
+    DiagnoseUseOfUnimplementedSelectors();
+
     // If any dynamic classes have their key function defined within
     // this translation unit, then those vtables are considered "used" and=
 must
     // be emitted.
@@ -468,34 +489,32 @@
   }
=20
   if (TUKind =3D=3D TU_Module) {
-    // Mark any macros from system headers (in /usr/include) as exported, =
along
-    // with our own Clang headers.
-    // FIXME: This is a gross hack to deal with the fact that system heade=
rs
-    // are #include'd in many places within module headers, but are not=20
-    // themselves modularized. This doesn't actually work, but it lets us
-    // focus on other issues for the moment.
-    for (Preprocessor::macro_iterator M =3D PP.macro_begin(false),
-                                   MEnd =3D PP.macro_end(false);
-         M !=3D MEnd; ++M) {
-      if (M->second &&=20
-          !M->second->isExported() &&
-          !M->second->isBuiltinMacro()) {
-        SourceLocation Loc =3D M->second->getDefinitionLoc();
-        if (SourceMgr.isInSystemHeader(Loc)) {
-          const FileEntry *File
-            =3D SourceMgr.getFileEntryForID(SourceMgr.getFileID(Loc));
-          if (File &&=20
-              ((StringRef(File->getName()).find("lib/clang")=20
-                  !=3D StringRef::npos) ||
-               (StringRef(File->getName()).find("usr/include")=20
-                  !=3D StringRef::npos) ||
-               (StringRef(File->getName()).find("usr/local/include")=20
-                  !=3D StringRef::npos)))
-            M->second->setExportLocation(Loc);
+    // If we are building a module, resolve all of the exported declaratio=
ns
+    // now.
+    if (Module *CurrentModule =3D PP.getCurrentModule()) {
+      ModuleMap &ModMap =3D PP.getHeaderSearchInfo().getModuleMap();
+     =20
+      llvm::SmallVector<Module *, 2> Stack;
+      Stack.push_back(CurrentModule);
+      while (!Stack.empty()) {
+        Module *Mod =3D Stack.back();
+        Stack.pop_back();
+       =20
+        // Resolve the exported declarations.
+        // FIXME: Actually complain, once we figure out how to teach the
+        // diagnostic client to deal with complains in the module map at t=
his
+        // point.
+        ModMap.resolveExports(Mod, /*Complain=3D*/false);
+       =20
+        // Queue the submodules, so their exports will also be resolved.
+        for (Module::submodule_iterator Sub =3D Mod->submodule_begin(),
+                                     SubEnd =3D Mod->submodule_end();
+             Sub !=3D SubEnd; ++Sub) {
+          Stack.push_back(*Sub);
         }
       }
     }
-         =20
+   =20
     // Modules don't need any of the checking below.
     TUScope =3D 0;
     return;
@@ -620,8 +639,16 @@
 DeclContext *Sema::getFunctionLevelDeclContext() {
   DeclContext *DC =3D CurContext;
=20
-  while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
-    DC =3D DC->getParent();
+  while (true) {
+    if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) {
+      DC =3D DC->getParent();
+    } else if (isa<CXXMethodDecl>(DC) &&
+               cast<CXXMethodDecl>(DC)->getOverloadedOperator() =3D=3D OO_=
Call &&
+               cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
+      DC =3D DC->getParent()->getParent();
+    }
+    else break;
+  }
=20
   return DC;
 }
@@ -646,58 +673,75 @@
   return 0;
 }
=20
-Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
-  if (!isActive())
-    return;
- =20
-  if (llvm::Optional<TemplateDeductionInfo*> Info =3D SemaRef.isSFINAECont=
ext()) {
-    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
+void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
+  // FIXME: It doesn't make sense to me that DiagID is an incoming argumen=
t here
+  // and yet we also use the current diag ID on the DiagnosticsEngine. Thi=
s has
+  // been made more painfully obvious by the refactor that introduced this
+  // function, but it is possible that the incoming argument can be
+  // eliminnated. If it truly cannot be (for example, there is some reentr=
ancy
+  // issue I am not seeing yet), then there should at least be a clarifying
+  // comment somewhere.
+  if (llvm::Optional<TemplateDeductionInfo*> Info =3D isSFINAEContext()) {
+    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
+              Diags.getCurrentDiagID())) {
     case DiagnosticIDs::SFINAE_Report:
-      // Fall through; we'll report the diagnostic below.
+      // We'll report the diagnostic below.
       break;
      =20
-    case DiagnosticIDs::SFINAE_AccessControl:
-      // Per C++ Core Issue 1170, access control is part of SFINAE.
-      // Additionally, the AccessCheckingSFINAE flag can be used to tempor=
ary
-      // make access control a part of SFINAE for the purposes of checking
-      // type traits.
-      if (!SemaRef.AccessCheckingSFINAE &&
-          !SemaRef.getLangOptions().CPlusPlus0x)
-        break;
-       =20
     case DiagnosticIDs::SFINAE_SubstitutionFailure:
       // Count this failure so that we know that template argument deducti=
on
       // has failed.
-      ++SemaRef.NumSFINAEErrors;
-      SemaRef.Diags.setLastDiagnosticIgnored();
-      SemaRef.Diags.Clear();
-      Clear();
+      ++NumSFINAEErrors;
+      Diags.setLastDiagnosticIgnored();
+      Diags.Clear();
       return;
      =20
+    case DiagnosticIDs::SFINAE_AccessControl: {
+      // Per C++ Core Issue 1170, access control is part of SFINAE.
+      // Additionally, the AccessCheckingSFINAE flag can be used to tempor=
arily
+      // make access control a part of SFINAE for the purposes of checking
+      // type traits.
+      if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus0x)
+        break;
+
+      SourceLocation Loc =3D Diags.getCurrentDiagLoc();
+
+      // Suppress this diagnostic.
+      ++NumSFINAEErrors;
+      Diags.setLastDiagnosticIgnored();
+      Diags.Clear();
+
+      // Now the diagnostic state is clear, produce a C++98 compatibility
+      // warning.
+      Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
+
+      // The last diagnostic which Sema produced was ignored. Suppress any
+      // notes attached to it.
+      Diags.setLastDiagnosticIgnored();
+      return;
+    }
+
     case DiagnosticIDs::SFINAE_Suppress:
       // Make a copy of this suppressed diagnostic and store it with the
       // template-deduction information;
-      FlushCounts();
-      Diagnostic DiagInfo(&SemaRef.Diags);
+      Diagnostic DiagInfo(&Diags);
        =20
       if (*Info)
         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
-                        PartialDiagnostic(DiagInfo,
-                                          SemaRef.Context.getDiagAllocator=
()));
+                        PartialDiagnostic(DiagInfo,Context.getDiagAllocato=
r()));
        =20
       // Suppress this diagnostic.       =20
-      SemaRef.Diags.setLastDiagnosticIgnored();
-      SemaRef.Diags.Clear();
-      Clear();
+      Diags.setLastDiagnosticIgnored();
+      Diags.Clear();
       return;
     }
   }
  =20
   // Set up the context's printing policy based on our current state.
-  SemaRef.Context.setPrintingPolicy(SemaRef.getPrintingPolicy());
+  Context.setPrintingPolicy(getPrintingPolicy());
  =20
   // Emit the diagnostic.
-  if (!this->Emit())
+  if (!Diags.EmitCurrentDiagnostic())
     return;
=20
   // If this is not a note, and we're in a template instantiation
@@ -705,20 +749,14 @@
   // we emitted an error, print a template instantiation
   // backtrace.
   if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
-      !SemaRef.ActiveTemplateInstantiations.empty() &&
-      SemaRef.ActiveTemplateInstantiations.back()
-        !=3D SemaRef.LastTemplateInstantiationErrorContext) {
-    SemaRef.PrintInstantiationStack();
-    SemaRef.LastTemplateInstantiationErrorContext
-      =3D SemaRef.ActiveTemplateInstantiations.back();
+      !ActiveTemplateInstantiations.empty() &&
+      ActiveTemplateInstantiations.back()
+        !=3D LastTemplateInstantiationErrorContext) {
+    PrintInstantiationStack();
+    LastTemplateInstantiationErrorContext =3D ActiveTemplateInstantiations=
.back();
   }
 }
=20
-Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID=
) {
-  DiagnosticBuilder DB =3D Diags.Report(Loc, DiagID);
-  return SemaDiagnosticBuilder(DB, *this, DiagID);
-}
-
 Sema::SemaDiagnosticBuilder
 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
@@ -795,8 +833,14 @@
                                               BlockScope, Block));
 }
=20
-void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP,
-                                   const Decl *D, const BlockExpr *blkExpr=
) {
+void Sema::PushLambdaScope(CXXRecordDecl *Lambda,=20
+                           CXXMethodDecl *CallOperator) {
+  FunctionScopes.push_back(new LambdaScopeInfo(getDiagnostics(), Lambda,
+                                               CallOperator));
+}
+
+void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
+                                const Decl *D, const BlockExpr *blkExpr) {
   FunctionScopeInfo *Scope =3D FunctionScopes.pop_back_val(); =20
   assert(!FunctionScopes.empty() && "mismatched push/pop!");
  =20
@@ -818,6 +862,17 @@
   }
 }
=20
+void Sema::PushCompoundScope() {
+  getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
+}
+
+void Sema::PopCompoundScope() {
+  FunctionScopeInfo *CurFunction =3D getCurFunction();
+  assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
+
+  CurFunction->CompoundScopes.pop_back();
+}
+
 /// \brief Determine whether any errors occurred within this function/meth=
od/
 /// block.
 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
@@ -831,13 +886,17 @@
   return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); =20
 }
=20
+LambdaScopeInfo *Sema::getCurLambda() {
+  if (FunctionScopes.empty())
+    return 0;
+ =20
+  return dyn_cast<LambdaScopeInfo>(FunctionScopes.back()); =20
+}
+
 // Pin this vtable to this file.
 ExternalSemaSource::~ExternalSemaSource() {}
=20
-std::pair<ObjCMethodList, ObjCMethodList>
-ExternalSemaSource::ReadMethodPool(Selector Sel) {
-  return std::pair<ObjCMethodList, ObjCMethodList>();
-}
+void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
=20
 void ExternalSemaSource::ReadKnownNamespaces(
                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {=
 =20
@@ -963,7 +1022,7 @@
     }
=20
     NamedDecl *Fn =3D (*It)->getUnderlyingDecl();
-    S.Diag(Fn->getLocStart(), diag::note_possible_target_of_call);
+    S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
     ++ShownOverloads;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaAccess.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaAccess.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaAccess.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclFriend.h"
+#include "clang/AST/DeclObjC.h"
 #include "clang/AST/DependentDiagnostic.h"
 #include "clang/AST/ExprCXX.h"
=20
@@ -164,6 +165,10 @@
     initialize();
   }
=20
+  bool isInstanceMember() const {
+    return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
+  }
+
   bool hasInstanceContext() const {
     return HasInstanceContext;
   }
@@ -264,6 +269,9 @@
   SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
=20
   while (true) {
+    if (Derived->isDependentContext() && !Derived->hasDefinition())
+      return AR_dependent;
+   =20
     for (CXXRecordDecl::base_class_const_iterator
            I =3D Derived->bases_begin(), E =3D Derived->bases_end(); I !=
=3D E; ++I) {
=20
@@ -667,18 +675,25 @@
 }
=20
 /// Search for a class P that EC is a friend of, under the constraint
-///   InstanceContext <=3D P <=3D NamingClass
+///   InstanceContext <=3D P
+/// if InstanceContext exists, or else
+///   NamingClass <=3D P
 /// and with the additional restriction that a protected member of
-/// NamingClass would have some natural access in P.
+/// NamingClass would have some natural access in P, which implicitly
+/// imposes the constraint that P <=3D NamingClass.
 ///
-/// That second condition isn't actually quite right: the condition in
-/// the standard is whether the target would have some natural access
-/// in P.  The difference is that the target might be more accessible
-/// along some path not passing through NamingClass.  Allowing that
+/// This isn't quite the condition laid out in the standard.
+/// Instead of saying that a notional protected member of NamingClass
+/// would have to have some natural access in P, it says the actual
+/// target has to have some natural access in P, which opens up the
+/// possibility that the target (which is not necessarily a member
+/// of NamingClass) might be more accessible along some path not
+/// passing through it.  That's really a bad idea, though, because it
 /// introduces two problems:
-///   - It breaks encapsulation because you can suddenly access a
-///     forbidden base class's members by subclassing it elsewhere.
-///   - It makes access substantially harder to compute because it
+///   - Most importantly, it breaks encapsulation because you can
+///     access a forbidden base class's members by directly subclassing
+///     it elsewhere.
+///   - It also makes access substantially harder to compute because it
 ///     breaks the hill-climbing algorithm: knowing that the target is
 ///     accessible in some base class would no longer let you change
 ///     the question solely to whether the base class is accessible,
@@ -688,9 +703,15 @@
 static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext=
 &EC,
                                            const CXXRecordDecl *InstanceCo=
ntext,
                                            const CXXRecordDecl *NamingClas=
s) {
-  assert(InstanceContext->getCanonicalDecl() =3D=3D InstanceContext);
+  assert(InstanceContext =3D=3D 0 ||
+         InstanceContext->getCanonicalDecl() =3D=3D InstanceContext);
   assert(NamingClass->getCanonicalDecl() =3D=3D NamingClass);
=20
+  // If we don't have an instance context, our constraints give us
+  // that NamingClass <=3D P <=3D NamingClass, i.e. P =3D=3D NamingClass.
+  // This is just the usual friendship check.
+  if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
+
   ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
   if (PRC.findFriendship(InstanceContext)) return AR_accessible;
   if (PRC.EverDependent) return AR_dependent;
@@ -733,15 +754,6 @@
       case AR_dependent: OnFailure =3D AR_dependent; continue;
       }
=20
-      if (!Target.hasInstanceContext())
-        return AR_accessible;
-
-      const CXXRecordDecl *InstanceContext =3D Target.resolveInstanceConte=
xt(S);
-      if (!InstanceContext) {
-        OnFailure =3D AR_dependent;
-        continue;
-      }
-
       // C++ [class.protected]p1:
       //   An additional access check beyond those described earlier in
       //   [class.access] is applied when a non-static data member or
@@ -754,8 +766,49 @@
       //   expression. In this case, the class of the object expression
       //   shall be C or a class derived from C.
       //
-      // We interpret this as a restriction on [M3].  Most of the
-      // conditions are encoded by not having any instance context.
+      // We interpret this as a restriction on [M3].
+
+      // In this part of the code, 'C' is just our context class ECRecord.
+     =20
+      // These rules are different if we don't have an instance context.
+      if (!Target.hasInstanceContext()) {
+        // If it's not an instance member, these restrictions don't apply.
+        if (!Target.isInstanceMember()) return AR_accessible;
+
+        // If it's an instance member, use the pointer-to-member rule
+        // that the naming class has to be derived from the effective
+        // context.
+
+        // Despite the standard's confident wording, there is a case
+        // where you can have an instance member that's neither in a
+        // pointer-to-member expression nor in a member access:  when
+        // it names a field in an unevaluated context that can't be an
+        // implicit member.  Pending clarification, we just apply the
+        // same naming-class restriction here.
+        //   FIXME: we're probably not correctly adding the
+        //   protected-member restriction when we retroactively convert
+        //   an expression to being evaluated.
+
+        // We know that ECRecord derives from NamingClass.  The
+        // restriction says to check whether NamingClass derives from
+        // ECRecord, but that's not really necessary: two distinct
+        // classes can't be recursively derived from each other.  So
+        // along this path, we just need to check whether the classes
+        // are equal.
+        if (NamingClass =3D=3D ECRecord) return AR_accessible;
+
+        // Otherwise, this context class tells us nothing;  on to the next.
+        continue;
+      }
+
+      assert(Target.isInstanceMember());
+
+      const CXXRecordDecl *InstanceContext =3D Target.resolveInstanceConte=
xt(S);
+      if (!InstanceContext) {
+        OnFailure =3D AR_dependent;
+        continue;
+      }
+
       switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
       case AR_accessible: return AR_accessible;
       case AR_inaccessible: continue;
@@ -774,9 +827,14 @@
   // *unless* the [class.protected] restriction applies.  If it does,
   // however, we should ignore whether the naming class is a friend,
   // and instead rely on whether any potential P is a friend.
-  if (Access =3D=3D AS_protected && Target.hasInstanceContext()) {
-    const CXXRecordDecl *InstanceContext =3D Target.resolveInstanceContext=
(S);
-    if (!InstanceContext) return AR_dependent;
+  if (Access =3D=3D AS_protected && Target.isInstanceMember()) {
+    // Compute the instance context if possible.
+    const CXXRecordDecl *InstanceContext =3D 0;
+    if (Target.hasInstanceContext()) {
+      InstanceContext =3D Target.resolveInstanceContext(S);
+      if (!InstanceContext) return AR_dependent;
+    }
+
     switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
     case AR_accessible: return AR_accessible;
     case AR_inaccessible: return OnFailure;
@@ -793,7 +851,6 @@
=20
   // Silence bogus warnings
   llvm_unreachable("impossible friendship kind");
-  return OnFailure;
 }
=20
 /// Finds the best path from the naming class to the declaring class,
@@ -947,31 +1004,46 @@
 static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
                                        AccessTarget &Target) {
   // Only applies to instance accesses.
-  if (!Target.hasInstanceContext())
+  if (!Target.isInstanceMember())
     return false;
+
   assert(Target.isMemberAccess());
-  NamedDecl *D =3D Target.getTargetDecl();
=20
-  const CXXRecordDecl *DeclaringClass =3D Target.getDeclaringClass();
-  DeclaringClass =3D DeclaringClass->getCanonicalDecl();
+  const CXXRecordDecl *NamingClass =3D Target.getNamingClass();
+  NamingClass =3D NamingClass->getCanonicalDecl();
=20
   for (EffectiveContext::record_iterator
          I =3D EC.Records.begin(), E =3D EC.Records.end(); I !=3D E; ++I) {
     const CXXRecordDecl *ECRecord =3D *I;
-    switch (IsDerivedFromInclusive(ECRecord, DeclaringClass)) {
+    switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
     case AR_accessible: break;
     case AR_inaccessible: continue;
     case AR_dependent: continue;
     }
=20
     // The effective context is a subclass of the declaring class.
-    // If that class isn't a superclass of the instance context,
-    // then the [class.protected] restriction applies.
+    // Check whether the [class.protected] restriction is limiting
+    // access.
=20
     // To get this exactly right, this might need to be checked more
     // holistically;  it's not necessarily the case that gaining
     // access here would grant us access overall.
=20
+    NamedDecl *D =3D Target.getTargetDecl();
+
+    // If we don't have an instance context, [class.protected] says the
+    // naming class has to equal the context class.
+    if (!Target.hasInstanceContext()) {
+      // If it does, the restriction doesn't apply.
+      if (NamingClass =3D=3D ECRecord) continue;
+
+      // TODO: it would be great to have a fixit here, since this is
+      // such an obvious error.
+      S.Diag(D->getLocation(), diag::note_access_protected_restricted_noob=
ject)
+        << S.Context.getTypeDeclType(ECRecord);
+      return true;
+    }
+
     const CXXRecordDecl *InstanceContext =3D Target.resolveInstanceContext=
(S);
     assert(InstanceContext && "diagnosing dependent access");
=20
@@ -979,12 +1051,25 @@
     case AR_accessible: continue;
     case AR_dependent: continue;
     case AR_inaccessible:
-      S.Diag(D->getLocation(), diag::note_access_protected_restricted)
-        << (InstanceContext !=3D Target.getNamingClass()->getCanonicalDecl=
())
-        << S.Context.getTypeDeclType(InstanceContext)
-        << S.Context.getTypeDeclType(ECRecord);
+      break;
+    }
+
+    // Okay, the restriction seems to be what's limiting us.
+
+    // Use a special diagnostic for constructors and destructors.
+    if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D) ||
+        (isa<FunctionTemplateDecl>(D) &&
+         isa<CXXConstructorDecl>(
+                cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
+      S.Diag(D->getLocation(), diag::note_access_protected_restricted_ctor=
dtor)
+        << isa<CXXDestructorDecl>(D);
       return true;
     }
+
+    // Otherwise, use the generic diagnostic.
+    S.Diag(D->getLocation(), diag::note_access_protected_restricted_object)
+      << S.Context.getTypeDeclType(ECRecord);
+    return true;
   }
=20
   return false;
@@ -996,8 +1081,6 @@
                                const EffectiveContext &EC,
                                AccessTarget &Entity) {
   AccessSpecifier Access =3D Entity.getAccess();
-  const CXXRecordDecl *NamingClass =3D Entity.getNamingClass();
-  NamingClass =3D NamingClass->getCanonicalDecl();
=20
   NamedDecl *D =3D (Entity.isMemberAccess() ? Entity.getTargetDecl() : 0);
   const CXXRecordDecl *DeclaringClass =3D Entity.getDeclaringClass();
@@ -1016,15 +1099,15 @@
       while (D->isOutOfLine()) {
         NamedDecl *PrevDecl =3D 0;
         if (VarDecl *VD =3D dyn_cast<VarDecl>(D))
-          PrevDecl =3D VD->getPreviousDeclaration();
+          PrevDecl =3D VD->getPreviousDecl();
         else if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D))
-          PrevDecl =3D FD->getPreviousDeclaration();
+          PrevDecl =3D FD->getPreviousDecl();
         else if (TypedefNameDecl *TND =3D dyn_cast<TypedefNameDecl>(D))
-          PrevDecl =3D TND->getPreviousDeclaration();
+          PrevDecl =3D TND->getPreviousDecl();
         else if (TagDecl *TD =3D dyn_cast<TagDecl>(D)) {
           if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassNa=
me())
             break;
-          PrevDecl =3D TD->getPreviousDeclaration();
+          PrevDecl =3D TD->getPreviousDecl();
         }
         if (!PrevDecl) break;
         D =3D PrevDecl;
@@ -1064,7 +1147,6 @@
=20
     case AR_dependent:
       llvm_unreachable("can't diagnose dependent access failures");
-      return;
     }
   }
=20
@@ -1162,7 +1244,7 @@
     if (Entity.getTargetDecl()->getAccess() =3D=3D AS_private &&=20
         (OrigDecl->getAccess() =3D=3D AS_public ||
          OrigDecl->getAccess() =3D=3D AS_protected)) {
-      S.Diag(AccessLoc, diag::war_ms_using_declaration_inaccessible)=20
+      S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
         << Shadow->getUsingDecl()->getQualifiedNameAsString()
         << OrigDecl->getQualifiedNameAsString();
       return true;
@@ -1274,7 +1356,7 @@
                                          AccessTarget &Entity) {
   assert(Entity.getAccess() !=3D AS_public && "called for public access!");
=20
-  if (S.getLangOptions().MicrosoftMode &&
+  if (S.getLangOpts().MicrosoftMode &&
       IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
     return AR_accessible;
=20
@@ -1294,7 +1376,6 @@
=20
   // silence unnecessary warning
   llvm_unreachable("invalid access result");
-  return AR_accessible;
 }
=20
 static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
@@ -1329,7 +1410,6 @@
   case AR_dependent: return Sema::AR_dependent;
   }
   llvm_unreachable("falling off end");
-  return Sema::AR_accessible;
 }
=20
 void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *decl) {
@@ -1396,7 +1476,7 @@
=20
 Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr =
*E,
                                                      DeclAccessPair Found)=
 {
-  if (!getLangOptions().AccessControl ||
+  if (!getLangOpts().AccessControl ||
       !E->getNamingClass() ||
       Found.getAccess() =3D=3D AS_public)
     return AR_accessible;
@@ -1412,7 +1492,7 @@
 /// access which has now been resolved to a member.
 Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr =
*E,
                                                      DeclAccessPair Found)=
 {
-  if (!getLangOptions().AccessControl ||
+  if (!getLangOpts().AccessControl ||
       Found.getAccess() =3D=3D AS_public)
     return AR_accessible;
=20
@@ -1427,10 +1507,34 @@
   return CheckAccess(*this, E->getMemberLoc(), Entity);
 }
=20
+/// Is the given special member function accessible for the purposes of
+/// deciding whether to define a special member function as deleted?
+bool Sema::isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
+                                                AccessSpecifier access,
+                                                QualType objectType) {
+  // Fast path.
+  if (access =3D=3D AS_public || !getLangOpts().AccessControl) return true;
+
+  AccessTarget entity(Context, AccessTarget::Member, decl->getParent(),
+                      DeclAccessPair::make(decl, access), objectType);
+
+  // Suppress diagnostics.
+  entity.setDiag(PDiag());
+
+  switch (CheckAccess(*this, SourceLocation(), entity)) {
+  case AR_accessible: return true;
+  case AR_inaccessible: return false;
+  case AR_dependent: llvm_unreachable("dependent for =3Ddelete computation=
");
+  case AR_delayed: llvm_unreachable("cannot delay =3Ddelete computation");
+  }
+  llvm_unreachable("bad access result");
+}
+
 Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
                                                CXXDestructorDecl *Dtor,
-                                               const PartialDiagnostic &PD=
iag) {
-  if (!getLangOptions().AccessControl)
+                                               const PartialDiagnostic &PD=
iag,
+                                               QualType ObjectTy) {
+  if (!getLangOpts().AccessControl)
     return AR_accessible;
=20
   // There's never a path involved when checking implicit destructor acces=
s.
@@ -1439,9 +1543,11 @@
     return AR_accessible;
=20
   CXXRecordDecl *NamingClass =3D Dtor->getParent();
+  if (ObjectTy.isNull()) ObjectTy =3D Context.getTypeDeclType(NamingClass);
+
   AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
                       DeclAccessPair::make(Dtor, Access),
-                      QualType());
+                      ObjectTy);
   Entity.setDiag(PDiag); // TODO: avoid copy
=20
   return CheckAccess(*this, Loc, Entity);
@@ -1453,14 +1559,9 @@
                                                 const InitializedEntity &E=
ntity,
                                                 AccessSpecifier Access,
                                                 bool IsCopyBindingRefToTem=
p) {
-  if (!getLangOptions().AccessControl ||
-      Access =3D=3D AS_public)
+  if (!getLangOpts().AccessControl || Access =3D=3D AS_public)
     return AR_accessible;
=20
-  CXXRecordDecl *NamingClass =3D Constructor->getParent();
-  AccessTarget AccessEntity(Context, AccessTarget::Member, NamingClass,
-                            DeclAccessPair::make(Constructor, Access),
-                            QualType());
   PartialDiagnostic PD(PDiag());
   switch (Entity.getKind()) {
   default:
@@ -1483,28 +1584,47 @@
     break;
   }
=20
+  case InitializedEntity::EK_LambdaCapture: {
+    const VarDecl *Var =3D Entity.getCapturedVar();
+    PD =3D PDiag(diag::err_access_lambda_capture);
+    PD << Var->getName() << Entity.getType() << getSpecialMember(Construct=
or);
+    break;
   }
=20
-  return CheckConstructorAccess(UseLoc, Constructor, Access, PD);
+  }
+
+  return CheckConstructorAccess(UseLoc, Constructor, Entity, Access, PD);
 }
=20
 /// Checks access to a constructor.
 Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
                                                 CXXConstructorDecl *Constr=
uctor,
+                                                const InitializedEntity &E=
ntity,
                                                 AccessSpecifier Access,
-                                                PartialDiagnostic PD) {
-  if (!getLangOptions().AccessControl ||
+                                                const PartialDiagnostic &P=
D) {
+  if (!getLangOpts().AccessControl ||
       Access =3D=3D AS_public)
     return AR_accessible;
=20
   CXXRecordDecl *NamingClass =3D Constructor->getParent();
+
+  // Initializing a base sub-object is an instance method call on an
+  // object of the derived class.  Otherwise, we have an instance method
+  // call on an object of the constructed type.
+  CXXRecordDecl *ObjectClass;
+  if (Entity.getKind() =3D=3D InitializedEntity::EK_Base) {
+    ObjectClass =3D cast<CXXConstructorDecl>(CurContext)->getParent();
+  } else {
+    ObjectClass =3D NamingClass;
+  }
+
   AccessTarget AccessEntity(Context, AccessTarget::Member, NamingClass,
                             DeclAccessPair::make(Constructor, Access),
-                            QualType());
+                            Context.getTypeDeclType(ObjectClass));
   AccessEntity.setDiag(PD);
=20
   return CheckAccess(*this, UseLoc, AccessEntity);
-}
+}=20
=20
 /// Checks direct (i.e. non-inherited) access to an arbitrary class
 /// member.
@@ -1512,7 +1632,7 @@
                                                  NamedDecl *Target,
                                            const PartialDiagnostic &Diag) {
   AccessSpecifier Access =3D Target->getAccess();
-  if (!getLangOptions().AccessControl ||
+  if (!getLangOpts().AccessControl ||
       Access =3D=3D AS_public)
     return AR_accessible;
=20
@@ -1531,7 +1651,7 @@
                                                CXXRecordDecl *NamingClass,
                                                DeclAccessPair Found,
                                                bool Diagnose) {
-  if (!getLangOptions().AccessControl ||
+  if (!getLangOpts().AccessControl ||
       !NamingClass ||
       Found.getAccess() =3D=3D AS_public)
     return AR_accessible;
@@ -1551,7 +1671,7 @@
                                                    Expr *ObjectExpr,
                                                    Expr *ArgExpr,
                                                    DeclAccessPair Found) {
-  if (!getLangOptions().AccessControl ||
+  if (!getLangOpts().AccessControl ||
       Found.getAccess() =3D=3D AS_public)
     return AR_accessible;
=20
@@ -1569,7 +1689,7 @@
=20
 Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
                                                     DeclAccessPair Found) {
-  if (!getLangOptions().AccessControl ||
+  if (!getLangOpts().AccessControl ||
       Found.getAccess() =3D=3D AS_none ||
       Found.getAccess() =3D=3D AS_public)
     return AR_accessible;
@@ -1578,7 +1698,7 @@
   CXXRecordDecl *NamingClass =3D Ovl->getNamingClass();
=20
   AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
-                      Context.getTypeDeclType(NamingClass));
+                      /*no instance context*/ QualType());
   Entity.setDiag(diag::err_access)
     << Ovl->getSourceRange();
=20
@@ -1601,7 +1721,7 @@
                                               unsigned DiagID,
                                               bool ForceCheck,
                                               bool ForceUnprivileged) {
-  if (!ForceCheck && !getLangOptions().AccessControl)
+  if (!ForceCheck && !getLangOpts().AccessControl)
     return AR_accessible;
=20
   if (Path.Access =3D=3D AS_public)
@@ -1630,7 +1750,7 @@
=20
 /// Checks access to all the declarations in the given result set.
 void Sema::CheckLookupAccess(const LookupResult &R) {
-  assert(getLangOptions().AccessControl
+  assert(getLangOpts().AccessControl
          && "performing access check without access control");
   assert(R.getNamingClass() && "performing access check without naming cla=
ss");
=20
@@ -1651,19 +1771,63 @@
 /// \param Decl the declaration to check if it can be accessed
 /// \param Class the class/context from which to start the search
 /// \return true if the Decl is accessible from the Class, false otherwise.
-bool Sema::IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *Class) {
-  if (!Class || !Decl->isCXXClassMember())
-    return true;
+bool Sema::IsSimplyAccessible(NamedDecl *Decl, DeclContext *Ctx) {
+  if (CXXRecordDecl *Class =3D dyn_cast<CXXRecordDecl>(Ctx)) {
+    if (!Decl->isCXXClassMember())
+      return true;
=20
-  QualType qType =3D Class->getTypeForDecl()->getCanonicalTypeInternal();
-  AccessTarget Entity(Context, AccessedEntity::Member, Class,
-                      DeclAccessPair::make(Decl, Decl->getAccess()),
-                      qType);
-  if (Entity.getAccess() =3D=3D AS_public)
-    return true;
+    QualType qType =3D Class->getTypeForDecl()->getCanonicalTypeInternal();
+    AccessTarget Entity(Context, AccessedEntity::Member, Class,
+                        DeclAccessPair::make(Decl, Decl->getAccess()),
+                        qType);
+    if (Entity.getAccess() =3D=3D AS_public)
+      return true;
=20
-  EffectiveContext EC(CurContext);
-  return ::IsAccessible(*this, EC, Entity) !=3D ::AR_inaccessible;
+    EffectiveContext EC(CurContext);
+    return ::IsAccessible(*this, EC, Entity) !=3D ::AR_inaccessible;
+  }
+ =20
+  if (ObjCIvarDecl *Ivar =3D dyn_cast<ObjCIvarDecl>(Decl)) {
+    // @public and @package ivars are always accessible.
+    if (Ivar->getCanonicalAccessControl() =3D=3D ObjCIvarDecl::Public ||
+        Ivar->getCanonicalAccessControl() =3D=3D ObjCIvarDecl::Package)
+      return true;
+   =20
+   =20
+   =20
+    // If we are inside a class or category implementation, determine the
+    // interface we're in.
+    ObjCInterfaceDecl *ClassOfMethodDecl =3D 0;
+    if (ObjCMethodDecl *MD =3D getCurMethodDecl())
+      ClassOfMethodDecl =3D  MD->getClassInterface();
+    else if (FunctionDecl *FD =3D getCurFunctionDecl()) {
+      if (ObjCImplDecl *Impl=20
+            =3D dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
+        if (ObjCImplementationDecl *IMPD
+              =3D dyn_cast<ObjCImplementationDecl>(Impl))
+          ClassOfMethodDecl =3D IMPD->getClassInterface();
+        else if (ObjCCategoryImplDecl* CatImplClass
+                   =3D dyn_cast<ObjCCategoryImplDecl>(Impl))
+          ClassOfMethodDecl =3D CatImplClass->getClassInterface();
+      }
+    }
+   =20
+    // If we're not in an interface, this ivar is inaccessible.
+    if (!ClassOfMethodDecl)
+      return false;
+   =20
+    // If we're inside the same interface that owns the ivar, we're fine.
+    if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface=
()))
+      return true;
+   =20
+    // If the ivar is private, it's inaccessible.
+    if (Ivar->getCanonicalAccessControl() =3D=3D ObjCIvarDecl::Private)
+      return false;
+   =20
+    return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDec=
l);
+  }
+ =20
+  return true;
 }
=20
 void Sema::ActOnStartSuppressingAccessChecks() {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaAttr.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaAttr.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaAttr.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -263,9 +263,6 @@
         Context->setAlignment(AlignmentVal);
     }
     break;
-
-  default:
-    llvm_unreachable("Invalid #pragma pack kind.");
   }
 }
=20
@@ -348,9 +345,9 @@
   Stack->push_back(std::make_pair(type, loc));
 }
=20
-void Sema::ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisTyp=
e,
+void Sema::ActOnPragmaVisibility(const IdentifierInfo* VisType,
                                  SourceLocation PragmaLoc) {
-  if (IsPush) {
+  if (VisType) {
     // Compute visibility to use.
     VisibilityAttr::VisibilityType type;
     if (VisType->isStr("default"))
@@ -368,7 +365,7 @@
     }
     PushPragmaVisibility(*this, type, PragmaLoc);
   } else {
-    PopPragmaVisibility();
+    PopPragmaVisibility(false, PragmaLoc);
   }
 }
=20
@@ -381,28 +378,49 @@
     FPFeatures.fp_contract =3D 0;=20
     break;
   case tok::OOS_DEFAULT:
-    FPFeatures.fp_contract =3D getLangOptions().DefaultFPContract;
+    FPFeatures.fp_contract =3D getLangOpts().DefaultFPContract;
     break;
   }
 }
=20
-void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr) {
+void Sema::PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
+                                       SourceLocation Loc) {
   // Visibility calculations will consider the namespace's visibility.
   // Here we just want to note that we're in a visibility context
   // which overrides any enclosing #pragma context, but doesn't itself
   // contribute visibility.
-  PushPragmaVisibility(*this, NoVisibility, SourceLocation());
+  PushPragmaVisibility(*this, NoVisibility, Loc);
 }
=20
-void Sema::PopPragmaVisibility() {
-  // Pop visibility from stack, if there is one on the stack.
-  if (VisContext) {
-    VisStack *Stack =3D static_cast<VisStack*>(VisContext);
+void Sema::PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc)=
 {
+  if (!VisContext) {
+    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
+    return;
+  }
=20
-    Stack->pop_back();
-    // To simplify the implementation, never keep around an empty stack.
-    if (Stack->empty())
-      FreeVisContext();
+  // Pop visibility from stack
+  VisStack *Stack =3D static_cast<VisStack*>(VisContext);
+
+  const std::pair<unsigned, SourceLocation> *Back =3D &Stack->back();
+  bool StartsWithPragma =3D Back->first !=3D NoVisibility;
+  if (StartsWithPragma && IsNamespaceEnd) {
+    Diag(Back->second, diag::err_pragma_push_visibility_mismatch);
+    Diag(EndLoc, diag::note_surrounding_namespace_ends_here);
+
+    // For better error recovery, eat all pushes inside the namespace.
+    do {
+      Stack->pop_back();
+      Back =3D &Stack->back();
+      StartsWithPragma =3D Back->first !=3D NoVisibility;
+    } while (StartsWithPragma);
+  } else if (!StartsWithPragma && !IsNamespaceEnd) {
+    Diag(EndLoc, diag::err_pragma_pop_visibility_mismatch);
+    Diag(Back->second, diag::note_surrounding_namespace_starts_here);
+    return;
   }
-  // FIXME: Add diag for pop without push.
+
+  Stack->pop_back();
+  // To simplify the implementation, never keep around an empty stack.
+  if (Stack->empty())
+    FreeVisContext();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaCXXScopeSpec.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaCXXScopeSpec.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaCXXScopeSpec.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -13,6 +13,7 @@
=20
 #include "clang/Sema/SemaInternal.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/Template.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
@@ -150,14 +151,13 @@
     const TagType *Tag =3D NNS->getAsType()->getAs<TagType>();
     assert(Tag && "Non-tag type in nested-name-specifier");
     return Tag->getDecl();
-  } break;
+  }
=20
   case NestedNameSpecifier::Global:
     return Context.getTranslationUnitDecl();
   }
=20
-  // Required to silence a GCC warning.
-  return 0;
+  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
 }
=20
 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
@@ -187,7 +187,7 @@
 ///
 /// \param NNS a dependent nested name specifier.
 CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
-  assert(getLangOptions().CPlusPlus && "Only callable in C++");
+  assert(getLangOpts().CPlusPlus && "Only callable in C++");
   assert(NNS->isDependent() && "Only dependent nested-name-specifier allow=
ed");
=20
   if (!NNS->getAsType())
@@ -210,43 +210,56 @@
                                       DeclContext *DC) {
   assert(DC !=3D 0 && "given null context");
=20
-  if (TagDecl *tag =3D dyn_cast<TagDecl>(DC)) {
-    // If this is a dependent type, then we consider it complete.
-    if (tag->isDependentContext())
-      return false;
+  TagDecl *tag =3D dyn_cast<TagDecl>(DC);
=20
-    // If we're currently defining this type, then lookup into the
-    // type is okay: don't complain that it isn't complete yet.
-    QualType type =3D Context.getTypeDeclType(tag);
-    const TagType *tagType =3D type->getAs<TagType>();
-    if (tagType && tagType->isBeingDefined())
-      return false;
+  // If this is a dependent type, then we consider it complete.
+  if (!tag || tag->isDependentContext())
+    return false;
=20
-    SourceLocation loc =3D SS.getLastQualifierNameLoc();
-    if (loc.isInvalid()) loc =3D SS.getRange().getBegin();
+  // If we're currently defining this type, then lookup into the
+  // type is okay: don't complain that it isn't complete yet.
+  QualType type =3D Context.getTypeDeclType(tag);
+  const TagType *tagType =3D type->getAs<TagType>();
+  if (tagType && tagType->isBeingDefined())
+    return false;
=20
-    // The type must be complete.
-    if (RequireCompleteType(loc, type,
-                            PDiag(diag::err_incomplete_nested_name_spec)
-                              << SS.getRange())) {
-      SS.SetInvalid(SS.getRange());
-      return true;
-    }
+  SourceLocation loc =3D SS.getLastQualifierNameLoc();
+  if (loc.isInvalid()) loc =3D SS.getRange().getBegin();
=20
-    // Fixed enum types are complete, but they aren't valid as scopes
-    // until we see a definition, so awkwardly pull out this special
-    // case.
-    if (const EnumType *enumType =3D dyn_cast_or_null<EnumType>(tagType)) {
-      if (!enumType->getDecl()->isCompleteDefinition()) {
-        Diag(loc, diag::err_incomplete_nested_name_spec)
-          << type << SS.getRange();
+  // The type must be complete.
+  if (RequireCompleteType(loc, type,
+                          PDiag(diag::err_incomplete_nested_name_spec)
+                            << SS.getRange())) {
+    SS.SetInvalid(SS.getRange());
+    return true;
+  }
+
+  // Fixed enum types are complete, but they aren't valid as scopes
+  // until we see a definition, so awkwardly pull out this special
+  // case.
+  const EnumType *enumType =3D dyn_cast_or_null<EnumType>(tagType);
+  if (!enumType || enumType->getDecl()->isCompleteDefinition())
+    return false;
+
+  // Try to instantiate the definition, if this is a specialization of an
+  // enumeration temploid.
+  EnumDecl *ED =3D enumType->getDecl();
+  if (EnumDecl *Pattern =3D ED->getInstantiatedFromMemberEnum()) {
+    MemberSpecializationInfo *MSI =3D ED->getMemberSpecializationInfo();
+    if (MSI->getTemplateSpecializationKind() !=3D TSK_ExplicitSpecializati=
on) {
+      if (InstantiateEnum(loc, ED, Pattern, getTemplateInstantiationArgs(E=
D),
+                          TSK_ImplicitInstantiation)) {
         SS.SetInvalid(SS.getRange());
         return true;
       }
+      return false;
     }
   }
=20
-  return false;
+  Diag(loc, diag::err_incomplete_nested_name_spec)
+    << type << SS.getRange();
+  SS.SetInvalid(SS.getRange());
+  return true;
 }
=20
 bool Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
@@ -268,18 +281,18 @@
   if (!isa<TypeDecl>(SD))
     return false;
=20
-  // Determine whether we have a class (or, in C++0x, an enum) or
+  // Determine whether we have a class (or, in C++11, an enum) or
   // a typedef thereof. If so, build the nested-name-specifier.
   QualType T =3D Context.getTypeDeclType(cast<TypeDecl>(SD));
   if (T->isDependentType())
     return true;
   else if (TypedefNameDecl *TD =3D dyn_cast<TypedefNameDecl>(SD)) {
     if (TD->getUnderlyingType()->isRecordType() ||
-        (Context.getLangOptions().CPlusPlus0x &&
+        (Context.getLangOpts().CPlusPlus0x &&
          TD->getUnderlyingType()->isEnumeralType()))
       return true;
   } else if (isa<RecordDecl>(SD) ||
-             (Context.getLangOptions().CPlusPlus0x && isa<EnumDecl>(SD)))
+             (Context.getLangOpts().CPlusPlus0x && isa<EnumDecl>(SD)))
     return true;
=20
   return false;
@@ -363,6 +376,25 @@
   return false;
 }
=20
+namespace {
+
+// Callback to only accept typo corrections that can be a valid C++ member
+// intializer: either a non-static field member or a base class.
+class NestedNameSpecifierValidatorCCC : public CorrectionCandidateCallback=
 {
+ public:
+  explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
+      : SRef(SRef) {}
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDec=
l());
+  }
+
+ private:
+  Sema &SRef;
+};
+
+}
+
 /// \brief Build a new nested-name-specifier for "identifier::", as descri=
bed
 /// by ActOnCXXNestedNameSpecifier.
 ///
@@ -478,14 +510,14 @@
     // We haven't found anything, and we're not recovering from a
     // different kind of error, so look for typos.
     DeclarationName Name =3D Found.getLookupName();
+    NestedNameSpecifierValidatorCCC Validator(*this);
     TypoCorrection Corrected;
     Found.clear();
     if ((Corrected =3D CorrectTypo(Found.getLookupNameInfo(),
-                                 Found.getLookupKind(), S, &SS, LookupCtx,
-                                 EnteringContext, CTC_NoKeywords)) &&
-        isAcceptableNestedNameSpecifier(Corrected.getCorrectionDecl())) {
-      std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
-      std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())=
);
+                                 Found.getLookupKind(), S, &SS, Validator,
+                                 LookupCtx, EnteringContext))) {
+      std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
+      std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
       if (LookupCtx)
         Diag(Found.getNameLoc(), diag::err_no_member_suggest)
           << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
@@ -596,6 +628,9 @@
       llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
     }
=20
+    if (T->isEnumeralType())
+      Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
+
     SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, =
T),
               CCLoc);
     return false;
@@ -631,7 +666,7 @@
   // public:
   //   void foo() { D::foo2(); }
   // };
-  if (getLangOptions().MicrosoftExt) {
+  if (getLangOpts().MicrosoftExt) {
     DeclContext *DC =3D LookupCtx ? LookupCtx : CurContext;
     if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
       SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
@@ -673,6 +708,29 @@
                                      /*ScopeLookupResult=3D*/0, false);
 }
=20
+bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
+                                               const DeclSpec &DS,
+                                               SourceLocation ColonColonLo=
c) {
+  if (SS.isInvalid() || DS.getTypeSpecType() =3D=3D DeclSpec::TST_error)
+    return true;
+
+  assert(DS.getTypeSpecType() =3D=3D DeclSpec::TST_decltype);
+
+  QualType T =3D BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLo=
c());
+  if (!T->isDependentType() && !T->getAs<TagType>()) {
+    Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class)=20
+      << T << getLangOpts().CPlusPlus;
+    return true;
+  }
+
+  TypeLocBuilder TLB;
+  DecltypeTypeLoc DecltypeTL =3D TLB.push<DecltypeTypeLoc>(T);
+  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
+  SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
+            ColonColonLoc);
+  return false;
+}
+
 /// IsInvalidUnlessNestedName - This method is used for error recovery
 /// purposes to determine whether the specified identifier is only valid as
 /// a nested name specifier, for example a namespace name.  It is
@@ -695,8 +753,8 @@
 }
=20
 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
-                                       SourceLocation TemplateLoc,=20
-                                       CXXScopeSpec &SS,=20
+                                       CXXScopeSpec &SS,
+                                       SourceLocation TemplateKWLoc,
                                        TemplateTy Template,
                                        SourceLocation TemplateNameLoc,
                                        SourceLocation LAngleLoc,
@@ -723,17 +781,18 @@
    =20
     // Create source-location information for this type.
     TypeLocBuilder Builder;
-    DependentTemplateSpecializationTypeLoc SpecTL=20
+    DependentTemplateSpecializationTypeLoc SpecTL
       =3D Builder.push<DependentTemplateSpecializationTypeLoc>(T);
+    SpecTL.setElaboratedKeywordLoc(SourceLocation());
+    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
+    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
+    SpecTL.setTemplateNameLoc(TemplateNameLoc);
     SpecTL.setLAngleLoc(LAngleLoc);
     SpecTL.setRAngleLoc(RAngleLoc);
-    SpecTL.setKeywordLoc(SourceLocation());
-    SpecTL.setNameLoc(TemplateNameLoc);
-    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
     for (unsigned I =3D 0, N =3D TemplateArgs.size(); I !=3D N; ++I)
       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
    =20
-    SS.Extend(Context, TemplateLoc, Builder.getTypeLocInContext(Context, T=
),=20
+    SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context,=
 T),
               CCLoc);
     return false;
   }
@@ -766,20 +825,19 @@
     return true;
   }
=20
-  // Provide source-location information for the template specialization=20
-  // type.
+  // Provide source-location information for the template specialization t=
ype.
   TypeLocBuilder Builder;
-  TemplateSpecializationTypeLoc SpecTL=20
+  TemplateSpecializationTypeLoc SpecTL
     =3D Builder.push<TemplateSpecializationTypeLoc>(T);
- =20
+  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
+  SpecTL.setTemplateNameLoc(TemplateNameLoc);
   SpecTL.setLAngleLoc(LAngleLoc);
   SpecTL.setRAngleLoc(RAngleLoc);
-  SpecTL.setTemplateNameLoc(TemplateNameLoc);
   for (unsigned I =3D 0, N =3D TemplateArgs.size(); I !=3D N; ++I)
     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
=20
=20
-  SS.Extend(Context, TemplateLoc, Builder.getTypeLocInContext(Context, T),=20
+  SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T=
),
             CCLoc);
   return false;
 }
@@ -854,8 +912,7 @@
     return true;
   }
=20
-  // Silence bogus warning.
-  return false;
+  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
 }
=20
 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (glob=
al
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaCast.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaCast.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaCast.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -49,7 +49,7 @@
       : Self(S), SrcExpr(src), DestType(destType),
         ResultType(destType.getNonLValueExprType(S.Context)),
         ValueKind(Expr::getValueKindForType(destType)),
-        Kind(CK_Dependent) {
+        Kind(CK_Dependent), IsARCUnbridgedCast(false) {
=20
       if (const BuiltinType *placeholder =3D
             src.get()->getType()->getAsPlaceholderType()) {
@@ -67,6 +67,7 @@
     CastKind Kind;
     BuiltinType::Kind PlaceholderKind;
     CXXCastPath BasePath;
+    bool IsARCUnbridgedCast;
=20
     SourceRange OpRange;
     SourceRange DestRange;
@@ -76,9 +77,23 @@
     void CheckReinterpretCast();
     void CheckStaticCast();
     void CheckDynamicCast();
-    void CheckCXXCStyleCast(bool FunctionalCast);
+    void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
     void CheckCStyleCast();
=20
+    /// Complete an apparently-successful cast operation that yields
+    /// the given expression.
+    ExprResult complete(CastExpr *castExpr) {
+      // If this is an unbridged cast, wrap the result in an implicit
+      // cast that yields the unbridged-cast placeholder type.
+      if (IsARCUnbridgedCast) {
+        castExpr =3D ImplicitCastExpr::Create(Self.Context,
+                                            Self.Context.ARCUnbridgedCastT=
y,
+                                            CK_Dependent, castExpr, 0,
+                                            castExpr->getValueKind());
+      }
+      return Self.Owned(castExpr);
+    }
+
     // Internal convenience methods.
=20
     /// Try to handle the given placeholder expression kind.  Return
@@ -103,8 +118,12 @@
     }
=20
     void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
+      assert(Self.getLangOpts().ObjCAutoRefCount);
+
       Expr *src =3D SrcExpr.get();
-      Self.CheckObjCARCConversion(OpRange, DestType, src, CCK);
+      if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) =3D=3D
+            Sema::ACR_unbridged)
+        IsARCUnbridgedCast =3D true;
       SrcExpr =3D src;
     }
=20
@@ -171,15 +190,15 @@
                                            QualType DestType,=20
                                            Sema::CheckedConversionKind CCK,
                                            const SourceRange &OpRange,
-                                           unsigned &msg,
-                                           CastKind &Kind);
+                                           unsigned &msg, CastKind &Kind,
+                                           bool ListInitialization);
 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
                                    QualType DestType,=20
                                    Sema::CheckedConversionKind CCK,
                                    const SourceRange &OpRange,
-                                   unsigned &msg,
-                                   CastKind &Kind,
-                                   CXXCastPath &BasePath);
+                                   unsigned &msg, CastKind &Kind,
+                                   CXXCastPath &BasePath,
+                                   bool ListInitialization);
 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType Dest=
Type,
                                   bool CStyle, unsigned &msg);
 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
@@ -203,7 +222,7 @@
   if (D.isInvalidType())
     return ExprError();
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // Check that there are no default arguments (C++ only).
     CheckExtraCXXDefaultArguments(D);
   }
@@ -237,9 +256,9 @@
       if (Op.SrcExpr.isInvalid())
         return ExprError();
     }
-    return Owned(CXXConstCastExpr::Create(Context, Op.ResultType, Op.Value=
Kind,
-                                          Op.SrcExpr.take(), DestTInfo, Op=
Loc,
-                                          Parens.getEnd()));
+    return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
+                                  Op.ValueKind, Op.SrcExpr.take(), DestTIn=
fo,
+                                                OpLoc, Parens.getEnd()));
=20
   case tok::kw_dynamic_cast: {
     if (!TypeDependent) {
@@ -247,10 +266,10 @@
       if (Op.SrcExpr.isInvalid())
         return ExprError();
     }
-    return Owned(CXXDynamicCastExpr::Create(Context, Op.ResultType,
-                                            Op.ValueKind, Op.Kind,
-                                            Op.SrcExpr.take(), &Op.BasePat=
h,
-                                            DestTInfo, OpLoc, Parens.getEn=
d()));
+    return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
+                                    Op.ValueKind, Op.Kind, Op.SrcExpr.take=
(),
+                                                  &Op.BasePath, DestTInfo,
+                                                  OpLoc, Parens.getEnd()));
   }
   case tok::kw_reinterpret_cast: {
     if (!TypeDependent) {
@@ -258,11 +277,10 @@
       if (Op.SrcExpr.isInvalid())
         return ExprError();
     }
-    return Owned(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
-                                                Op.ValueKind, Op.Kind,
-                                                Op.SrcExpr.take(), 0,
-                                                DestTInfo, OpLoc,
-                                                Parens.getEnd()));
+    return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultTy=
pe,
+                                    Op.ValueKind, Op.Kind, Op.SrcExpr.take=
(),
+                                                      0, DestTInfo, OpLoc,
+                                                      Parens.getEnd()));
   }
   case tok::kw_static_cast: {
     if (!TypeDependent) {
@@ -271,21 +289,20 @@
         return ExprError();
     }
    =20
-    return Owned(CXXStaticCastExpr::Create(Context, Op.ResultType, Op.Valu=
eKind,
-                                           Op.Kind, Op.SrcExpr.take(),
-                                           &Op.BasePath, DestTInfo, OpLoc,
-                                           Parens.getEnd()));
+    return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
+                                   Op.ValueKind, Op.Kind, Op.SrcExpr.take(=
),
+                                                 &Op.BasePath, DestTInfo,
+                                                 OpLoc, Parens.getEnd()));
   }
   }
-
-  return ExprError();
 }
=20
 /// Try to diagnose a failed overloaded cast.  Returns true if
 /// diagnostics were emitted.
 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
                                       SourceRange range, Expr *src,
-                                      QualType destType) {
+                                      QualType destType,
+                                      bool listInitialization) {
   switch (CT) {
   // These cast kinds don't consider user-defined conversions.
   case CT_Const:
@@ -307,8 +324,9 @@
   InitializedEntity entity =3D InitializedEntity::InitializeTemporary(dest=
Type);
   InitializationKind initKind
     =3D (CT =3D=3D CT_CStyle)? InitializationKind::CreateCStyleCast(range.=
getBegin(),
-                                                              range)
-    : (CT =3D=3D CT_Functional)? InitializationKind::CreateFunctionalCast(=
range)
+                                                      range, listInitializ=
ation)
+    : (CT =3D=3D CT_Functional)? InitializationKind::CreateFunctionalCast(=
range,
+                                                             listInitializ=
ation)
     : InitializationKind::CreateCast(/*type range?*/ range);
   InitializationSequence sequence(S, entity, initKind, &src, 1);
=20
@@ -328,7 +346,6 @@
=20
   switch (sequence.getFailedOverloadResult()) {
   case OR_Success: llvm_unreachable("successful failed overload");
-    return false;
   case OR_No_Viable_Function:
     if (candidates.empty())
       msg =3D diag::err_ovl_no_conversion_in_cast;
@@ -352,21 +369,23 @@
     << CT << srcType << destType
     << range << src->getSourceRange();
=20
-  candidates.NoteCandidates(S, howManyCandidates, &src, 1);
+  candidates.NoteCandidates(S, howManyCandidates, src);
=20
   return true;
 }
=20
 /// Diagnose a failed cast.
 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
-                            SourceRange opRange, Expr *src, QualType destT=
ype) {
+                            SourceRange opRange, Expr *src, QualType destT=
ype,
+                            bool listInitialization) {
   if (src->getType() =3D=3D S.Context.BoundMemberTy) {
     (void) S.CheckPlaceholderExpr(src); // will always fail
     return;
   }
=20
   if (msg =3D=3D diag::err_bad_cxx_cast_generic &&
-      tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
+      tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
+                                listInitialization))
     return;
=20
   S.Diag(opRange.getBegin(), msg) << castType
@@ -443,7 +462,7 @@
   // If the only checking we care about is for Objective-C lifetime qualif=
iers,
   // and we're not in ARC mode, there's nothing to check.
   if (!CheckCVR && CheckObjCLifetime &&=20
-      !Self.Context.getLangOptions().ObjCAutoRefCount)
+      !Self.Context.getLangOpts().ObjCAutoRefCount)
     return false;
    =20
   // Casting away constness is defined in C++ 5.2.11p8 with reference to
@@ -511,6 +530,13 @@
 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runt=
ime-
 /// checked downcasts in class hierarchies.
 void CastOperation::CheckDynamicCast() {
+  if (ValueKind =3D=3D VK_RValue)
+    SrcExpr =3D Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
+  else if (isPlaceholder())
+    SrcExpr =3D Self.CheckPlaceholderExpr(SrcExpr.take());
+  if (SrcExpr.isInvalid()) // if conversion failed, don't report another e=
rror
+    return;
+
   QualType OrigSrcType =3D SrcExpr.get()->getType();
   QualType DestType =3D Self.Context.getCanonicalType(this->DestType);
=20
@@ -638,11 +664,12 @@
 /// const char *str =3D "literal";
 /// legacy_function(const_cast\<char*\>(str));
 void CastOperation::CheckConstCast() {
-  if (ValueKind =3D=3D VK_RValue && !isPlaceholder(BuiltinType::Overload))=
 {
+  if (ValueKind =3D=3D VK_RValue)
     SrcExpr =3D Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
-    if (SrcExpr.isInvalid()) // if conversion failed, don't report another=
 error
-      return;
-  }
+  else if (isPlaceholder())
+    SrcExpr =3D Self.CheckPlaceholderExpr(SrcExpr.take());
+  if (SrcExpr.isInvalid()) // if conversion failed, don't report another e=
rror
+    return;
=20
   unsigned msg =3D diag::err_bad_cxx_cast_generic;
   if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) !=
=3D TC_Success
@@ -657,11 +684,12 @@
 /// like this:
 /// char *bytes =3D reinterpret_cast\<char*\>(int_ptr);
 void CastOperation::CheckReinterpretCast() {
-  if (ValueKind =3D=3D VK_RValue && !isPlaceholder(BuiltinType::Overload))=
 {
+  if (ValueKind =3D=3D VK_RValue && !isPlaceholder(BuiltinType::Overload))
     SrcExpr =3D Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
-    if (SrcExpr.isInvalid()) // if conversion failed, don't report another=
 error
-      return;
-  }
+  else
+    checkNonOverloadPlaceholders();
+  if (SrcExpr.isInvalid()) // if conversion failed, don't report another e=
rror
+    return;
=20
   unsigned msg =3D diag::err_bad_cxx_cast_generic;
   TryCastResult tcr =3D=20
@@ -679,9 +707,10 @@
       Self.NoteAllOverloadCandidates(SrcExpr.get());
=20
     } else {
-      diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), D=
estType);
+      diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
+                      DestType, /*listInitialization=3D*/false);
     }
-  } else if (tcr =3D=3D TC_Success && Self.getLangOptions().ObjCAutoRefCou=
nt) {
+  } else if (tcr =3D=3D TC_Success && Self.getLangOpts().ObjCAutoRefCount)=
 {
     checkObjCARCConversion(Sema::CCK_OtherCast);
   }
 }
@@ -726,7 +755,7 @@
   unsigned msg =3D diag::err_bad_cxx_cast_generic;
   TryCastResult tcr
     =3D TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRang=
e, msg,
-                    Kind, BasePath);
+                    Kind, BasePath, /*ListInitialization=3D*/false);
   if (tcr !=3D TC_Success && msg !=3D 0) {
     if (SrcExpr.isInvalid())
       return;
@@ -737,12 +766,13 @@
         << oe->getQualifierLoc().getSourceRange();
       Self.NoteAllOverloadCandidates(SrcExpr.get());
     } else {
-      diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestTy=
pe);
+      diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestTy=
pe,
+                      /*listInitialization=3D*/false);
     }
   } else if (tcr =3D=3D TC_Success) {
     if (Kind =3D=3D CK_BitCast)
       checkCastAlign();
-    if (Self.getLangOptions().ObjCAutoRefCount)
+    if (Self.getLangOpts().ObjCAutoRefCount)
       checkObjCARCConversion(Sema::CCK_OtherCast);
   } else if (Kind =3D=3D CK_BitCast) {
     checkCastAlign();
@@ -756,8 +786,8 @@
                                    QualType DestType,=20
                                    Sema::CheckedConversionKind CCK,
                                    const SourceRange &OpRange, unsigned &m=
sg,
-                                   CastKind &Kind,
-                                   CXXCastPath &BasePath) {
+                                   CastKind &Kind, CXXCastPath &BasePath,
+                                   bool ListInitialization) {
   // Determine whether we have the semantics of a C-style cast.
   bool CStyle=20
     =3D (CCK =3D=3D Sema::CCK_CStyleCast || CCK =3D=3D Sema::CCK_Functiona=
lCast);
@@ -782,23 +812,23 @@
   // C++ 5.2.9p5, reference downcast.
   // See the function for details.
   // DR 427 specifies that this is to be applied before paragraph 2.
-  tcr =3D TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle=
, OpRange,
-                                   msg, Kind, BasePath);
+  tcr =3D TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
+                                   OpRange, msg, Kind, BasePath);
   if (tcr !=3D TC_NotApplicable)
     return tcr;
=20
   // C++0x [expr.static.cast]p3:=20
   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to=
 cv2
   //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
-  tcr =3D TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kin=
d, BasePath,=20
-                              msg);
+  tcr =3D TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kin=
d,=20
+                              BasePath, msg);
   if (tcr !=3D TC_NotApplicable)
     return tcr;
=20
   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
   //   [...] if the declaration "T t(e);" is well-formed, [...].
   tcr =3D TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
-                              Kind);
+                              Kind, ListInitialization);
   if (SrcExpr.isInvalid())
     return TC_Failed;
   if (tcr !=3D TC_NotApplicable)
@@ -1269,7 +1299,7 @@
 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
                       Sema::CheckedConversionKind CCK,=20
                       const SourceRange &OpRange, unsigned &msg,
-                      CastKind &Kind) {
+                      CastKind &Kind, bool ListInitialization) {
   if (DestType->isRecordType()) {
     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
                                  diag::err_bad_dynamic_cast_incomplete)) {
@@ -1277,13 +1307,14 @@
       return TC_Failed;
     }
   }
- =20
+
   InitializedEntity Entity =3D InitializedEntity::InitializeTemporary(Dest=
Type);
   InitializationKind InitKind
     =3D (CCK =3D=3D Sema::CCK_CStyleCast)
-        ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
+        ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
+                                               ListInitialization)
     : (CCK =3D=3D Sema::CCK_FunctionalCast)
-        ? InitializationKind::CreateFunctionalCast(OpRange)
+        ? InitializationKind::CreateFunctionalCast(OpRange, ListInitializa=
tion)
     : InitializationKind::CreateCast(OpRange);
   Expr *SrcExprRaw =3D SrcExpr.get();
   InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
@@ -1497,6 +1528,8 @@
     case OK_BitField:        inappropriate =3D "bit-field";           brea=
k;
     case OK_VectorComponent: inappropriate =3D "vector element";      brea=
k;
     case OK_ObjCProperty:    inappropriate =3D "property expression"; brea=
k;
+    case OK_ObjCSubscript:   inappropriate =3D "container subscripting exp=
ression";=20
+                             break;
     }
     if (inappropriate) {
       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_referen=
ce)
@@ -1545,7 +1578,8 @@
     }
=20
     // A valid member pointer cast.
-    Kind =3D IsLValueCast? CK_LValueBitCast : CK_BitCast;
+    assert(!IsLValueCast);
+    Kind =3D CK_ReinterpretMemberPointer;
     return TC_Success;
   }
=20
@@ -1592,7 +1626,27 @@
    =20
     return TC_Failed;
   }
- =20
+
+  if (SrcType =3D=3D DestType) {
+    // C++ 5.2.10p2 has a note that mentions that, subject to all other
+    // restrictions, a cast to the same type is allowed so long as it does=
 not
+    // cast away constness. In C++98, the intent was not entirely clear he=
re,=20
+    // since all other paragraphs explicitly forbid casts to the same type.
+    // C++11 clarifies this case with p2.
+    //
+    // The only allowed types are: integral, enumeration, pointer, or=20
+    // pointer-to-member types.  We also won't restrict Obj-C pointers eit=
her.
+    Kind =3D CK_NoOp;
+    TryCastResult Result =3D TC_NotApplicable;
+    if (SrcType->isIntegralOrEnumerationType() ||
+        SrcType->isAnyPointerType() ||
+        SrcType->isMemberPointerType() ||
+        SrcType->isBlockPointerType()) {
+      Result =3D TC_Success;
+    }
+    return Result;
+  }
+
   bool destIsPtr =3D DestType->isAnyPointerType() ||
                    DestType->isBlockPointerType();
   bool srcIsPtr =3D SrcType->isAnyPointerType() ||
@@ -1603,17 +1657,6 @@
     return TC_NotApplicable;
   }
=20
-  if (SrcType =3D=3D DestType) {
-    // C++ 5.2.10p2 has a note that mentions that, subject to all other
-    // restrictions, a cast to the same type is allowed. The intent is not
-    // entirely clear here, since all other paragraphs explicitly forbid c=
asts
-    // to the same type. However, the behavior of compilers is pretty cons=
istent
-    // on this point: allow same-type conversion if the involved types are
-    // pointers, disallow otherwise.
-    Kind =3D CK_NoOp;
-    return TC_Success;
-  }
-
   if (DestType->isIntegralType(Self.Context)) {
     assert(srcIsPtr && "One type must be a pointer");
     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
@@ -1621,7 +1664,7 @@
     //   integral type size doesn't matter.
     if ((Self.Context.getTypeSize(SrcType) >
          Self.Context.getTypeSize(DestType)) &&
-         !Self.getLangOptions().MicrosoftExt) {
+         !Self.getLangOpts().MicrosoftExt) {
       msg =3D diag::err_bad_reinterpret_cast_small_int;
       return TC_Failed;
     }
@@ -1694,15 +1737,19 @@
     // casting the return value of dlsym() and GetProcAddress().
     // FIXME: Conditionally-supported behavior should be configurable in t=
he
     // TargetInfo or similar.
-    if (!Self.getLangOptions().CPlusPlus0x)
-      Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
+    Self.Diag(OpRange.getBegin(),
+              Self.getLangOpts().CPlusPlus0x ?
+                diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_ob=
j)
+      << OpRange;
     return TC_Success;
   }
=20
   if (DestType->isFunctionPointerType()) {
     // See above.
-    if (!Self.getLangOptions().CPlusPlus0x)
-      Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
+    Self.Diag(OpRange.getBegin(),
+              Self.getLangOpts().CPlusPlus0x ?
+                diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_ob=
j)
+      << OpRange;
     return TC_Success;
   }
  =20
@@ -1714,7 +1761,8 @@
   return TC_Success;
 }                                    =20
=20
-void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle) {
+void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
+                                       bool ListInitialization) {
   // Handle placeholders.
   if (isPlaceholder()) {
     // C-style casts can resolve __unknown_any types.
@@ -1728,7 +1776,7 @@
     checkNonOverloadPlaceholders();
     if (SrcExpr.isInvalid())
       return;
-  } =20
+  }
=20
   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv v=
oid".
   // This test is outside everything else because it's the only case where
@@ -1797,7 +1845,7 @@
   if (tcr =3D=3D TC_NotApplicable) {
     // ... or if that is not possible, a static_cast, ignoring const, ...
     tcr =3D TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
-                        msg, Kind, BasePath);
+                        msg, Kind, BasePath, ListInitialization);
     if (SrcExpr.isInvalid())
       return;
=20
@@ -1810,7 +1858,7 @@
     }
   }
=20
-  if (Self.getLangOptions().ObjCAutoRefCount && tcr =3D=3D TC_Success)
+  if (Self.getLangOpts().ObjCAutoRefCount && tcr =3D=3D TC_Success)
     checkObjCARCConversion(CCK);
=20
   if (tcr !=3D TC_Success && msg !=3D 0) {
@@ -1826,7 +1874,7 @@
=20
     } else {
       diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CSt=
yle),
-                      OpRange, SrcExpr.get(), DestType);
+                      OpRange, SrcExpr.get(), DestType, ListInitialization=
);
     }
   } else if (Kind =3D=3D CK_BitCast) {
     checkCastAlign();
@@ -1839,26 +1887,15 @@
=20
 /// Check the semantics of a C-style cast operation, in C.
 void CastOperation::CheckCStyleCast() {
-  assert(!Self.getLangOptions().CPlusPlus);
+  assert(!Self.getLangOpts().CPlusPlus);
=20
-  // Handle placeholders.
-  if (isPlaceholder()) {
-    // C-style casts can resolve __unknown_any types.
-    if (claimPlaceholder(BuiltinType::UnknownAny)) {
-      SrcExpr =3D Self.checkUnknownAnyCast(DestRange, DestType,
-                                         SrcExpr.get(), Kind,
-                                         ValueKind, BasePath);
-      return;
-    }
-
-    // We allow overloads in C, but we don't allow them to be resolved
-    // by anything except calls.
-    SrcExpr =3D Self.CheckPlaceholderExpr(SrcExpr.take());
-    if (SrcExpr.isInvalid())
-      return;
-  } =20
-
-  assert(!isPlaceholder());
+  // C-style casts can resolve __unknown_any types.
+  if (claimPlaceholder(BuiltinType::UnknownAny)) {
+    SrcExpr =3D Self.checkUnknownAnyCast(DestRange, DestType,
+                                       SrcExpr.get(), Kind,
+                                       ValueKind, BasePath);
+    return;
+  }
=20
   // C99 6.5.4p2: the cast type needs to be void or scalar and the express=
ion
   // type needs to be scalar.
@@ -1878,6 +1915,12 @@
     return;
   QualType SrcType =3D SrcExpr.get()->getType();
=20
+  // You can cast an _Atomic(T) to anything you can cast a T to.
+  if (const AtomicType *AtomicSrcType =3D SrcType->getAs<AtomicType>())
+    SrcType =3D AtomicSrcType->getValueType();
+
+  assert(!SrcType->isPlaceholderType());
+
   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
                                diag::err_typecheck_cast_to_incomplete)) {
     SrcExpr =3D ExprError();
@@ -1983,14 +2026,14 @@
         DestType->isArithmeticType()) {
       Self.Diag(SrcExpr.get()->getLocStart(),
            diag::err_cast_pointer_to_non_pointer_int)
-        << SrcType << SrcExpr.get()->getSourceRange();
+        << DestType << SrcExpr.get()->getSourceRange();
       SrcExpr =3D ExprError();
       return;
     }
   }
=20
   // ARC imposes extra restrictions on casts.
-  if (Self.getLangOptions().ObjCAutoRefCount) {
+  if (Self.getLangOpts().ObjCAutoRefCount) {
     checkObjCARCConversion(Sema::CCK_CStyleCast);
     if (SrcExpr.isInvalid())
       return;
@@ -2035,8 +2078,9 @@
   Op.DestRange =3D CastTypeInfo->getTypeLoc().getSourceRange();
   Op.OpRange =3D SourceRange(LPLoc, CastExpr->getLocEnd());
=20
-  if (getLangOptions().CPlusPlus) {
-    Op.CheckCXXCStyleCast(/*FunctionalStyle=3D*/ false);
+  if (getLangOpts().CPlusPlus) {
+    Op.CheckCXXCStyleCast(/*FunctionalStyle=3D*/ false,
+                          isa<InitListExpr>(CastExpr));
   } else {
     Op.CheckCStyleCast();
   }
@@ -2044,26 +2088,25 @@
   if (Op.SrcExpr.isInvalid())
     return ExprError();
=20
-  return Owned(CStyleCastExpr::Create(Context, Op.ResultType, Op.ValueKind,
-                                      Op.Kind, Op.SrcExpr.take(), &Op.Base=
Path,
-                                      CastTypeInfo, LPLoc, RPLoc));
+  return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
+                              Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
+                              &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
 }
=20
 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
                                             SourceLocation LPLoc,
                                             Expr *CastExpr,
                                             SourceLocation RPLoc) {
+  assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
   Op.DestRange =3D CastTypeInfo->getTypeLoc().getSourceRange();
   Op.OpRange =3D SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd(=
));
=20
-  Op.CheckCXXCStyleCast(/*FunctionalStyle=3D*/ true);
+  Op.CheckCXXCStyleCast(/*FunctionalStyle=3D*/true, /*ListInit=3D*/false);
   if (Op.SrcExpr.isInvalid())
     return ExprError();
=20
-  return Owned(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
-                                             Op.ValueKind, CastTypeInfo,
-                                             Op.DestRange.getBegin(),
-                                             Op.Kind, Op.SrcExpr.take(),
-                                             &Op.BasePath, RPLoc));
+  return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
+                         Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin=
(),
+                         Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaChecking.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -30,6 +30,7 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include "clang/Basic/TargetBuiltins.h"
@@ -42,31 +43,7 @@
 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *S=
L,
                                                     unsigned ByteNo) const=
 {
   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
-                               PP.getLangOptions(), PP.getTargetInfo());
-}
- =20
-
-/// CheckablePrintfAttr - does a function call have a "printf" attribute
-/// and arguments that merit checking?
-bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall=
) {
-  if (Format->getType() =3D=3D "printf") return true;
-  if (Format->getType() =3D=3D "printf0") {
-    // printf0 allows null "format" string; if so don't check format/args
-    unsigned format_idx =3D Format->getFormatIdx() - 1;
-    // Does the index refer to the implicit object argument?
-    if (isa<CXXMemberCallExpr>(TheCall)) {
-      if (format_idx =3D=3D 0)
-        return false;
-      --format_idx;
-    }
-    if (format_idx < TheCall->getNumArgs()) {
-      Expr *Format =3D TheCall->getArg(format_idx)->IgnoreParenCasts();
-      if (!Format->isNullPointerConstant(Context,
-                                         Expr::NPC_ValueDependentIsNull))
-        return true;
-    }
-  }
-  return false;
+                               PP.getLangOpts(), PP.getTargetInfo());
 }
=20
 /// Checks that a call expression's argument count is the desired number.
@@ -183,43 +160,101 @@
     TheCall->setType(Context.IntTy);
     break;
   case Builtin::BI__sync_fetch_and_add:
+  case Builtin::BI__sync_fetch_and_add_1:
+  case Builtin::BI__sync_fetch_and_add_2:
+  case Builtin::BI__sync_fetch_and_add_4:
+  case Builtin::BI__sync_fetch_and_add_8:
+  case Builtin::BI__sync_fetch_and_add_16:
   case Builtin::BI__sync_fetch_and_sub:
+  case Builtin::BI__sync_fetch_and_sub_1:
+  case Builtin::BI__sync_fetch_and_sub_2:
+  case Builtin::BI__sync_fetch_and_sub_4:
+  case Builtin::BI__sync_fetch_and_sub_8:
+  case Builtin::BI__sync_fetch_and_sub_16:
   case Builtin::BI__sync_fetch_and_or:
+  case Builtin::BI__sync_fetch_and_or_1:
+  case Builtin::BI__sync_fetch_and_or_2:
+  case Builtin::BI__sync_fetch_and_or_4:
+  case Builtin::BI__sync_fetch_and_or_8:
+  case Builtin::BI__sync_fetch_and_or_16:
   case Builtin::BI__sync_fetch_and_and:
+  case Builtin::BI__sync_fetch_and_and_1:
+  case Builtin::BI__sync_fetch_and_and_2:
+  case Builtin::BI__sync_fetch_and_and_4:
+  case Builtin::BI__sync_fetch_and_and_8:
+  case Builtin::BI__sync_fetch_and_and_16:
   case Builtin::BI__sync_fetch_and_xor:
+  case Builtin::BI__sync_fetch_and_xor_1:
+  case Builtin::BI__sync_fetch_and_xor_2:
+  case Builtin::BI__sync_fetch_and_xor_4:
+  case Builtin::BI__sync_fetch_and_xor_8:
+  case Builtin::BI__sync_fetch_and_xor_16:
   case Builtin::BI__sync_add_and_fetch:
+  case Builtin::BI__sync_add_and_fetch_1:
+  case Builtin::BI__sync_add_and_fetch_2:
+  case Builtin::BI__sync_add_and_fetch_4:
+  case Builtin::BI__sync_add_and_fetch_8:
+  case Builtin::BI__sync_add_and_fetch_16:
   case Builtin::BI__sync_sub_and_fetch:
+  case Builtin::BI__sync_sub_and_fetch_1:
+  case Builtin::BI__sync_sub_and_fetch_2:
+  case Builtin::BI__sync_sub_and_fetch_4:
+  case Builtin::BI__sync_sub_and_fetch_8:
+  case Builtin::BI__sync_sub_and_fetch_16:
   case Builtin::BI__sync_and_and_fetch:
+  case Builtin::BI__sync_and_and_fetch_1:
+  case Builtin::BI__sync_and_and_fetch_2:
+  case Builtin::BI__sync_and_and_fetch_4:
+  case Builtin::BI__sync_and_and_fetch_8:
+  case Builtin::BI__sync_and_and_fetch_16:
   case Builtin::BI__sync_or_and_fetch:
+  case Builtin::BI__sync_or_and_fetch_1:
+  case Builtin::BI__sync_or_and_fetch_2:
+  case Builtin::BI__sync_or_and_fetch_4:
+  case Builtin::BI__sync_or_and_fetch_8:
+  case Builtin::BI__sync_or_and_fetch_16:
   case Builtin::BI__sync_xor_and_fetch:
+  case Builtin::BI__sync_xor_and_fetch_1:
+  case Builtin::BI__sync_xor_and_fetch_2:
+  case Builtin::BI__sync_xor_and_fetch_4:
+  case Builtin::BI__sync_xor_and_fetch_8:
+  case Builtin::BI__sync_xor_and_fetch_16:
   case Builtin::BI__sync_val_compare_and_swap:
+  case Builtin::BI__sync_val_compare_and_swap_1:
+  case Builtin::BI__sync_val_compare_and_swap_2:
+  case Builtin::BI__sync_val_compare_and_swap_4:
+  case Builtin::BI__sync_val_compare_and_swap_8:
+  case Builtin::BI__sync_val_compare_and_swap_16:
   case Builtin::BI__sync_bool_compare_and_swap:
+  case Builtin::BI__sync_bool_compare_and_swap_1:
+  case Builtin::BI__sync_bool_compare_and_swap_2:
+  case Builtin::BI__sync_bool_compare_and_swap_4:
+  case Builtin::BI__sync_bool_compare_and_swap_8:
+  case Builtin::BI__sync_bool_compare_and_swap_16:
   case Builtin::BI__sync_lock_test_and_set:
+  case Builtin::BI__sync_lock_test_and_set_1:
+  case Builtin::BI__sync_lock_test_and_set_2:
+  case Builtin::BI__sync_lock_test_and_set_4:
+  case Builtin::BI__sync_lock_test_and_set_8:
+  case Builtin::BI__sync_lock_test_and_set_16:
   case Builtin::BI__sync_lock_release:
+  case Builtin::BI__sync_lock_release_1:
+  case Builtin::BI__sync_lock_release_2:
+  case Builtin::BI__sync_lock_release_4:
+  case Builtin::BI__sync_lock_release_8:
+  case Builtin::BI__sync_lock_release_16:
   case Builtin::BI__sync_swap:
+  case Builtin::BI__sync_swap_1:
+  case Builtin::BI__sync_swap_2:
+  case Builtin::BI__sync_swap_4:
+  case Builtin::BI__sync_swap_8:
+  case Builtin::BI__sync_swap_16:
     return SemaBuiltinAtomicOverloaded(move(TheCallResult));
-  case Builtin::BI__atomic_load:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
-  case Builtin::BI__atomic_store:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
-  case Builtin::BI__atomic_exchange:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
-  case Builtin::BI__atomic_compare_exchange_strong:
-    return SemaAtomicOpsOverloaded(move(TheCallResult),
-                                   AtomicExpr::CmpXchgStrong);
-  case Builtin::BI__atomic_compare_exchange_weak:
-    return SemaAtomicOpsOverloaded(move(TheCallResult),
-                                   AtomicExpr::CmpXchgWeak);
-  case Builtin::BI__atomic_fetch_add:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
-  case Builtin::BI__atomic_fetch_sub:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
-  case Builtin::BI__atomic_fetch_and:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
-  case Builtin::BI__atomic_fetch_or:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
-  case Builtin::BI__atomic_fetch_xor:
-    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
+#define BUILTIN(ID, TYPE, ATTRS)
+#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
+  case Builtin::BI##ID: \
+    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::AO##ID=
);
+#include "clang/Basic/Builtins.def"
   case Builtin::BI__builtin_annotation:
     if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
       return ExprError();
@@ -245,29 +280,52 @@
=20
 // Get the valid immediate range for the specified NEON type code.
 static unsigned RFT(unsigned t, bool shift =3D false) {
-  bool quad =3D t & 0x10;
- =20
-  switch (t & 0x7) {
-    case 0: // i8
-      return shift ? 7 : (8 << (int)quad) - 1;
-    case 1: // i16
-      return shift ? 15 : (4 << (int)quad) - 1;
-    case 2: // i32
-      return shift ? 31 : (2 << (int)quad) - 1;
-    case 3: // i64
-      return shift ? 63 : (1 << (int)quad) - 1;
-    case 4: // f32
-      assert(!shift && "cannot shift float types!");
-      return (2 << (int)quad) - 1;
-    case 5: // poly8
-      return shift ? 7 : (8 << (int)quad) - 1;
-    case 6: // poly16
-      return shift ? 15 : (4 << (int)quad) - 1;
-    case 7: // float16
-      assert(!shift && "cannot shift float types!");
-      return (4 << (int)quad) - 1;
+  NeonTypeFlags Type(t);
+  int IsQuad =3D Type.isQuad();
+  switch (Type.getEltType()) {
+  case NeonTypeFlags::Int8:
+  case NeonTypeFlags::Poly8:
+    return shift ? 7 : (8 << IsQuad) - 1;
+  case NeonTypeFlags::Int16:
+  case NeonTypeFlags::Poly16:
+    return shift ? 15 : (4 << IsQuad) - 1;
+  case NeonTypeFlags::Int32:
+    return shift ? 31 : (2 << IsQuad) - 1;
+  case NeonTypeFlags::Int64:
+    return shift ? 63 : (1 << IsQuad) - 1;
+  case NeonTypeFlags::Float16:
+    assert(!shift && "cannot shift float types!");
+    return (4 << IsQuad) - 1;
+  case NeonTypeFlags::Float32:
+    assert(!shift && "cannot shift float types!");
+    return (2 << IsQuad) - 1;
   }
-  return 0;
+  llvm_unreachable("Invalid NeonTypeFlag!");
+}
+
+/// getNeonEltType - Return the QualType corresponding to the elements of
+/// the vector type specified by the NeonTypeFlags.  This is used to check
+/// the pointer arguments for Neon load/store intrinsics.
+static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
+  switch (Flags.getEltType()) {
+  case NeonTypeFlags::Int8:
+    return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCha=
rTy;
+  case NeonTypeFlags::Int16:
+    return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
+  case NeonTypeFlags::Int32:
+    return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
+  case NeonTypeFlags::Int64:
+    return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongL=
ongTy;
+  case NeonTypeFlags::Poly8:
+    return Context.SignedCharTy;
+  case NeonTypeFlags::Poly16:
+    return Context.ShortTy;
+  case NeonTypeFlags::Float16:
+    return Context.UnsignedShortTy;
+  case NeonTypeFlags::Float32:
+    return Context.FloatTy;
+  }
+  llvm_unreachable("Invalid NeonTypeFlag!");
 }
=20
 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCa=
ll) {
@@ -275,6 +333,8 @@
=20
   unsigned mask =3D 0;
   unsigned TV =3D 0;
+  int PtrArgNum =3D -1;
+  bool HasConstPtr =3D false;
   switch (BuiltinID) {
 #define GET_NEON_OVERLOAD_CHECK
 #include "clang/Basic/arm_neon.inc"
@@ -283,15 +343,35 @@
  =20
   // For NEON intrinsics which are overloaded on vector element type, vali=
date
   // the immediate which specifies which variant to emit.
+  unsigned ImmArg =3D TheCall->getNumArgs()-1;
   if (mask) {
-    unsigned ArgNo =3D TheCall->getNumArgs()-1;
-    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
+    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
       return true;
    =20
-    TV =3D Result.getLimitedValue(32);
-    if ((TV > 31) || (mask & (1 << TV)) =3D=3D 0)
+    TV =3D Result.getLimitedValue(64);
+    if ((TV > 63) || (mask & (1 << TV)) =3D=3D 0)
       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
-        << TheCall->getArg(ArgNo)->getSourceRange();
+        << TheCall->getArg(ImmArg)->getSourceRange();
+  }
+
+  if (PtrArgNum >=3D 0) {
+    // Check that pointer arguments have the specified type.
+    Expr *Arg =3D TheCall->getArg(PtrArgNum);
+    if (ImplicitCastExpr *ICE =3D dyn_cast<ImplicitCastExpr>(Arg))
+      Arg =3D ICE->getSubExpr();
+    ExprResult RHS =3D DefaultFunctionArrayLvalueConversion(Arg);
+    QualType RHSTy =3D RHS.get()->getType();
+    QualType EltTy =3D getNeonEltType(NeonTypeFlags(TV), Context);
+    if (HasConstPtr)
+      EltTy =3D EltTy.withConst();
+    QualType LHSTy =3D Context.getPointerType(EltTy);
+    AssignConvertType ConvTy;
+    ConvTy =3D CheckSingleAssignmentConstraints(LHSTy, RHS);
+    if (RHS.isInvalid())
+      return true;
+    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
+                                 RHS.get(), AA_Assigning))
+      return true;
   }
  =20
   // For NEON intrinsics which take an immediate value as part of the=20
@@ -341,16 +421,7 @@
   for (specific_attr_iterator<FormatAttr>
          i =3D FDecl->specific_attr_begin<FormatAttr>(),
          e =3D FDecl->specific_attr_end<FormatAttr>(); i !=3D e ; ++i) {
-
-    const FormatAttr *Format =3D *i;
-    const bool b =3D Format->getType() =3D=3D "scanf";
-    if (b || CheckablePrintfAttr(Format, TheCall)) {
-      bool HasVAListArg =3D Format->getFirstArg() =3D=3D 0;
-      CheckPrintfScanfArguments(TheCall, HasVAListArg,
-                                Format->getFormatIdx() - 1,
-                                HasVAListArg ? 0 : Format->getFirstArg() -=
 1,
-                                !b);
-    }
+    CheckFormatArguments(*i, TheCall);
   }
=20
   for (specific_attr_iterator<NonNullAttr>
@@ -360,98 +431,42 @@
                           TheCall->getCallee()->getLocStart());
   }
=20
-  // Builtin handling
-  int CMF =3D -1;
-  switch (FDecl->getBuiltinID()) {
-  case Builtin::BI__builtin_memset:
-  case Builtin::BI__builtin___memset_chk:
-  case Builtin::BImemset:
-    CMF =3D CMF_Memset;
-    break;
-   =20
-  case Builtin::BI__builtin_memcpy:
-  case Builtin::BI__builtin___memcpy_chk:
-  case Builtin::BImemcpy:
-    CMF =3D CMF_Memcpy;
-    break;
-   =20
-  case Builtin::BI__builtin_memmove:
-  case Builtin::BI__builtin___memmove_chk:
-  case Builtin::BImemmove:
-    CMF =3D CMF_Memmove;
-    break;
-
-  case Builtin::BIstrlcpy:
-  case Builtin::BIstrlcat:
+  unsigned CMId =3D FDecl->getMemoryFunctionKind();
+  if (CMId =3D=3D 0)
+    return false;
+
+  // Handle memory setting and copying functions.
+  if (CMId =3D=3D Builtin::BIstrlcpy || CMId =3D=3D Builtin::BIstrlcat)
     CheckStrlcpycatArguments(TheCall, FnInfo);
-    break;
-   =20
-  case Builtin::BI__builtin_memcmp:
-    CMF =3D CMF_Memcmp;
-    break;
-   =20
-  case Builtin::BI__builtin_strncpy:
-  case Builtin::BI__builtin___strncpy_chk:
-  case Builtin::BIstrncpy:
-    CMF =3D CMF_Strncpy;
-    break;
-
-  case Builtin::BI__builtin_strncmp:
-    CMF =3D CMF_Strncmp;
-    break;
-
-  case Builtin::BI__builtin_strncasecmp:
-    CMF =3D CMF_Strncasecmp;
-    break;
-
-  case Builtin::BI__builtin_strncat:
-  case Builtin::BIstrncat:
-    CMF =3D CMF_Strncat;
-    break;
-
-  case Builtin::BI__builtin_strndup:
-  case Builtin::BIstrndup:
-    CMF =3D CMF_Strndup;
-    break;
-
-  default:
-    if (FDecl->getLinkage() =3D=3D ExternalLinkage &&
-        (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
-      if (FnInfo->isStr("memset"))
-        CMF =3D CMF_Memset;
-      else if (FnInfo->isStr("memcpy"))
-        CMF =3D CMF_Memcpy;
-      else if (FnInfo->isStr("memmove"))
-        CMF =3D CMF_Memmove;
-      else if (FnInfo->isStr("memcmp"))
-        CMF =3D CMF_Memcmp;
-      else if (FnInfo->isStr("strncpy"))
-        CMF =3D CMF_Strncpy;
-      else if (FnInfo->isStr("strncmp"))
-        CMF =3D CMF_Strncmp;
-      else if (FnInfo->isStr("strncasecmp"))
-        CMF =3D CMF_Strncasecmp;
-      else if (FnInfo->isStr("strncat"))
-        CMF =3D CMF_Strncat;
-      else if (FnInfo->isStr("strndup"))
-        CMF =3D CMF_Strndup;
-    }
-    break;
-  }
-  =20
-  // Memset/memcpy/memmove handling
-  if (CMF !=3D -1)
-    CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
+  else if (CMId =3D=3D Builtin::BIstrncat)
+    CheckStrncatArguments(TheCall, FnInfo);
+  else
+    CheckMemaccessArguments(TheCall, CMId, FnInfo);
=20
   return false;
 }
=20
+bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbra=
c,=20
+                               Expr **Args, unsigned NumArgs) {
+  for (specific_attr_iterator<FormatAttr>
+       i =3D Method->specific_attr_begin<FormatAttr>(),
+       e =3D Method->specific_attr_end<FormatAttr>(); i !=3D e ; ++i) {
+
+    CheckFormatArguments(*i, Args, NumArgs, false, lbrac,=20
+                         Method->getSourceRange());
+  }
+
+  // diagnose nonnull arguments.
+  for (specific_attr_iterator<NonNullAttr>
+       i =3D Method->specific_attr_begin<NonNullAttr>(),
+       e =3D Method->specific_attr_end<NonNullAttr>(); i !=3D e; ++i) {
+    CheckNonNullArguments(*i, Args, lbrac);
+  }
+
+  return false;
+}
+
 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
-  // Printf checking.
-  const FormatAttr *Format =3D NDecl->getAttr<FormatAttr>();
-  if (!Format)
-    return false;
-
   const VarDecl *V =3D dyn_cast<VarDecl>(NDecl);
   if (!V)
     return false;
@@ -460,83 +475,186 @@
   if (!Ty->isBlockPointerType())
     return false;
=20
-  const bool b =3D Format->getType() =3D=3D "scanf";
-  if (!b && !CheckablePrintfAttr(Format, TheCall))
-    return false;
-
-  bool HasVAListArg =3D Format->getFirstArg() =3D=3D 0;
-  CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() =
- 1,
-                            HasVAListArg ? 0 : Format->getFirstArg() - 1, =
!b);
+  // format string checking.
+  for (specific_attr_iterator<FormatAttr>
+       i =3D NDecl->specific_attr_begin<FormatAttr>(),
+       e =3D NDecl->specific_attr_end<FormatAttr>(); i !=3D e ; ++i) {
+    CheckFormatArguments(*i, TheCall);
+  }
=20
   return false;
 }
=20
-ExprResult
-Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::Atomic=
Op Op) {
+ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
+                                         AtomicExpr::AtomicOp Op) {
   CallExpr *TheCall =3D cast<CallExpr>(TheCallResult.get());
   DeclRefExpr *DRE =3Dcast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenC=
asts());
=20
-  // All these operations take one of the following four forms:
-  // T   __atomic_load(_Atomic(T)*, int)                              (loa=
ds)
-  // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/s=
ub)
-  // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
-  //                                                                (cmpxc=
hg)
-  // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything el=
se)
-  // where T is an appropriate type, and the int paremeterss are for order=
ings.
-  unsigned NumVals =3D 1;
-  unsigned NumOrders =3D 1;
-  if (Op =3D=3D AtomicExpr::Load) {
-    NumVals =3D 0;
-  } else if (Op =3D=3D AtomicExpr::CmpXchgWeak || Op =3D=3D AtomicExpr::Cm=
pXchgStrong) {
-    NumVals =3D 2;
-    NumOrders =3D 2;
+  // All these operations take one of the following forms:
+  enum {
+    // C    __c11_atomic_init(A *, C)
+    Init,
+    // C    __c11_atomic_load(A *, int)
+    Load,
+    // void __atomic_load(A *, CP, int)
+    Copy,
+    // C    __c11_atomic_add(A *, M, int)
+    Arithmetic,
+    // C    __atomic_exchange_n(A *, CP, int)
+    Xchg,
+    // void __atomic_exchange(A *, C *, CP, int)
+    GNUXchg,
+    // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
+    C11CmpXchg,
+    // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
+    GNUCmpXchg
+  } Form =3D Init;
+  const unsigned NumArgs[] =3D { 2, 2, 3, 3, 3, 4, 5, 6 };
+  const unsigned NumVals[] =3D { 1, 0, 1, 1, 1, 2, 2, 3 };
+  // where:
+  //   C is an appropriate type,
+  //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builti=
ns,
+  //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
+  //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
+  //   the int parameters are for orderings.
+
+  assert(AtomicExpr::AO__c11_atomic_init =3D=3D 0 &&
+         AtomicExpr::AO__c11_atomic_fetch_xor + 1 =3D=3D AtomicExpr::AO__a=
tomic_load
+         && "need to update code for modified C11 atomics");
+  bool IsC11 =3D Op >=3D AtomicExpr::AO__c11_atomic_init &&
+               Op <=3D AtomicExpr::AO__c11_atomic_fetch_xor;
+  bool IsN =3D Op =3D=3D AtomicExpr::AO__atomic_load_n ||
+             Op =3D=3D AtomicExpr::AO__atomic_store_n ||
+             Op =3D=3D AtomicExpr::AO__atomic_exchange_n ||
+             Op =3D=3D AtomicExpr::AO__atomic_compare_exchange_n;
+  bool IsAddSub =3D false;
+
+  switch (Op) {
+  case AtomicExpr::AO__c11_atomic_init:
+    Form =3D Init;
+    break;
+
+  case AtomicExpr::AO__c11_atomic_load:
+  case AtomicExpr::AO__atomic_load_n:
+    Form =3D Load;
+    break;
+
+  case AtomicExpr::AO__c11_atomic_store:
+  case AtomicExpr::AO__atomic_load:
+  case AtomicExpr::AO__atomic_store:
+  case AtomicExpr::AO__atomic_store_n:
+    Form =3D Copy;
+    break;
+
+  case AtomicExpr::AO__c11_atomic_fetch_add:
+  case AtomicExpr::AO__c11_atomic_fetch_sub:
+  case AtomicExpr::AO__atomic_fetch_add:
+  case AtomicExpr::AO__atomic_fetch_sub:
+  case AtomicExpr::AO__atomic_add_fetch:
+  case AtomicExpr::AO__atomic_sub_fetch:
+    IsAddSub =3D true;
+    // Fall through.
+  case AtomicExpr::AO__c11_atomic_fetch_and:
+  case AtomicExpr::AO__c11_atomic_fetch_or:
+  case AtomicExpr::AO__c11_atomic_fetch_xor:
+  case AtomicExpr::AO__atomic_fetch_and:
+  case AtomicExpr::AO__atomic_fetch_or:
+  case AtomicExpr::AO__atomic_fetch_xor:
+  case AtomicExpr::AO__atomic_fetch_nand:
+  case AtomicExpr::AO__atomic_and_fetch:
+  case AtomicExpr::AO__atomic_or_fetch:
+  case AtomicExpr::AO__atomic_xor_fetch:
+  case AtomicExpr::AO__atomic_nand_fetch:
+    Form =3D Arithmetic;
+    break;
+
+  case AtomicExpr::AO__c11_atomic_exchange:
+  case AtomicExpr::AO__atomic_exchange_n:
+    Form =3D Xchg;
+    break;
+
+  case AtomicExpr::AO__atomic_exchange:
+    Form =3D GNUXchg;
+    break;
+
+  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
+  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
+    Form =3D C11CmpXchg;
+    break;
+
+  case AtomicExpr::AO__atomic_compare_exchange:
+  case AtomicExpr::AO__atomic_compare_exchange_n:
+    Form =3D GNUCmpXchg;
+    break;
   }
=20
-  if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
+  // Check we have the right number of arguments.
+  if (TheCall->getNumArgs() < NumArgs[Form]) {
     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
-      << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
+      << 0 << NumArgs[Form] << TheCall->getNumArgs()
       << TheCall->getCallee()->getSourceRange();
     return ExprError();
-  } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
-    Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
+  } else if (TheCall->getNumArgs() > NumArgs[Form]) {
+    Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
          diag::err_typecheck_call_too_many_args)
-      << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
+      << 0 << NumArgs[Form] << TheCall->getNumArgs()
       << TheCall->getCallee()->getSourceRange();
     return ExprError();
   }
=20
-  // Inspect the first argument of the atomic operation.  This should alwa=
ys be
-  // a pointer to an _Atomic type.
+  // Inspect the first argument of the atomic operation.
   Expr *Ptr =3D TheCall->getArg(0);
   Ptr =3D DefaultFunctionArrayLvalueConversion(Ptr).get();
   const PointerType *pointerType =3D Ptr->getType()->getAs<PointerType>();
   if (!pointerType) {
-    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
+    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
       << Ptr->getType() << Ptr->getSourceRange();
     return ExprError();
   }
=20
-  QualType AtomTy =3D pointerType->getPointeeType();
-  if (!AtomTy->isAtomicType()) {
-    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
+  // For a __c11 builtin, this should be a pointer to an _Atomic type.
+  QualType AtomTy =3D pointerType->getPointeeType(); // 'A'
+  QualType ValType =3D AtomTy; // 'C'
+  if (IsC11) {
+    if (!AtomTy->isAtomicType()) {
+      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
+        << Ptr->getType() << Ptr->getSourceRange();
+      return ExprError();
+    }
+    ValType =3D AtomTy->getAs<AtomicType>()->getValueType();
+  }
+
+  // For an arithmetic operation, the implied arithmetic must be well-form=
ed.
+  if (Form =3D=3D Arithmetic) {
+    // gcc does not enforce these rules for GNU atomics, but we do so for =
sanity.
+    if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()=
) {
+      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
+        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
+      return ExprError();
+    }
+    if (!IsAddSub && !ValType->isIntegerType()) {
+      Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_in=
t)
+        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
+      return ExprError();
+    }
+  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()=
) {
+    // For __atomic_*_n operations, the value type must be a scalar integr=
al or
+    // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
+    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
+      << IsC11 << Ptr->getType() << Ptr->getSourceRange();
+    return ExprError();
+  }
+
+  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
+    // For GNU atomics, require a trivially-copyable type. This is not par=
t of
+    // the GNU atomics specification, but we enforce it for sanity.
+    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
       << Ptr->getType() << Ptr->getSourceRange();
     return ExprError();
   }
-  QualType ValType =3D AtomTy->getAs<AtomicType>()->getValueType();
-
-  if ((Op =3D=3D AtomicExpr::Add || Op =3D=3D AtomicExpr::Sub) &&
-      !ValType->isIntegerType() && !ValType->isPointerType()) {
-    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
-      << Ptr->getType() << Ptr->getSourceRange();
-    return ExprError();
-  }
-
-  if (!ValType->isIntegerType() &&
-      (Op =3D=3D AtomicExpr::And || Op =3D=3D AtomicExpr::Or || Op =3D=3D =
AtomicExpr::Xor)){
-    Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
-      << Ptr->getType() << Ptr->getSourceRange();
-    return ExprError();
-  }
+
+  // FIXME: For any builtin other than a load, the ValType must not be
+  // const-qualified.
=20
   switch (ValType.getObjCLifetime()) {
   case Qualifiers::OCL_None:
@@ -547,61 +665,107 @@
   case Qualifiers::OCL_Weak:
   case Qualifiers::OCL_Strong:
   case Qualifiers::OCL_Autoreleasing:
+    // FIXME: Can this happen? By this point, ValType should be known
+    // to be trivially copyable.
     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
       << ValType << Ptr->getSourceRange();
     return ExprError();
   }
=20
   QualType ResultType =3D ValType;
-  if (Op =3D=3D AtomicExpr::Store)
+  if (Form =3D=3D Copy || Form =3D=3D GNUXchg || Form =3D=3D Init)
     ResultType =3D Context.VoidTy;
-  else if (Op =3D=3D AtomicExpr::CmpXchgWeak || Op =3D=3D AtomicExpr::CmpX=
chgStrong)
+  else if (Form =3D=3D C11CmpXchg || Form =3D=3D GNUCmpXchg)
     ResultType =3D Context.BoolTy;
=20
+  // The type of a parameter passed 'by value'. In the GNU atomics, such
+  // arguments are actually passed as pointers.
+  QualType ByValType =3D ValType; // 'CP'
+  if (!IsC11 && !IsN)
+    ByValType =3D Ptr->getType();
+
   // The first argument --- the pointer --- has a fixed type; we
   // deduce the types of the rest of the arguments accordingly.  Walk
   // the remaining arguments, converting them to the deduced value type.
-  for (unsigned i =3D 1; i !=3D NumVals+NumOrders+1; ++i) {
-    ExprResult Arg =3D TheCall->getArg(i);
+  for (unsigned i =3D 1; i !=3D NumArgs[Form]; ++i) {
     QualType Ty;
-    if (i < NumVals+1) {
-      // The second argument to a cmpxchg is a pointer to the data which w=
ill
-      // be exchanged. The second argument to a pointer add/subtract is the
-      // amount to add/subtract, which must be a ptrdiff_t.  The third
-      // argument to a cmpxchg and the second argument in all other cases
-      // is the type of the value.
-      if (i =3D=3D 1 && (Op =3D=3D AtomicExpr::CmpXchgWeak ||
-                     Op =3D=3D AtomicExpr::CmpXchgStrong))
-         Ty =3D Context.getPointerType(ValType.getUnqualifiedType());
-      else if (!ValType->isIntegerType() &&
-               (Op =3D=3D AtomicExpr::Add || Op =3D=3D AtomicExpr::Sub))
-        Ty =3D Context.getPointerDiffType();
-      else
-        Ty =3D ValType;
+    if (i < NumVals[Form] + 1) {
+      switch (i) {
+      case 1:
+        // The second argument is the non-atomic operand. For arithmetic, =
this
+        // is always passed by value, and for a compare_exchange it is alw=
ays
+        // passed by address. For the rest, GNU uses by-address and C11 us=
es
+        // by-value.
+        assert(Form !=3D Load);
+        if (Form =3D=3D Init || (Form =3D=3D Arithmetic && ValType->isInte=
gerType()))
+          Ty =3D ValType;
+        else if (Form =3D=3D Copy || Form =3D=3D Xchg)
+          Ty =3D ByValType;
+        else if (Form =3D=3D Arithmetic)
+          Ty =3D Context.getPointerDiffType();
+        else
+          Ty =3D Context.getPointerType(ValType.getUnqualifiedType());
+        break;
+      case 2:
+        // The third argument to compare_exchange / GNU exchange is a
+        // (pointer to a) desired value.
+        Ty =3D ByValType;
+        break;
+      case 3:
+        // The fourth argument to GNU compare_exchange is a 'weak' flag.
+        Ty =3D Context.BoolTy;
+        break;
+      }
     } else {
       // The order(s) are always converted to int.
       Ty =3D Context.IntTy;
     }
+
     InitializedEntity Entity =3D
         InitializedEntity::InitializeParameter(Context, Ty, false);
+    ExprResult Arg =3D TheCall->getArg(i);
     Arg =3D PerformCopyInitialization(Entity, SourceLocation(), Arg);
     if (Arg.isInvalid())
       return true;
     TheCall->setArg(i, Arg.get());
   }
=20
+  // Permute the arguments into a 'consistent' order.
   SmallVector<Expr*, 5> SubExprs;
   SubExprs.push_back(Ptr);
-  if (Op =3D=3D AtomicExpr::Load) {
+  switch (Form) {
+  case Init:
+    // Note, AtomicExpr::getVal1() has a special case for this atomic.
+    SubExprs.push_back(TheCall->getArg(1)); // Val1
+    break;
+  case Load:
     SubExprs.push_back(TheCall->getArg(1)); // Order
-  } else if (Op !=3D AtomicExpr::CmpXchgWeak && Op !=3D AtomicExpr::CmpXch=
gStrong) {
+    break;
+  case Copy:
+  case Arithmetic:
+  case Xchg:
     SubExprs.push_back(TheCall->getArg(2)); // Order
     SubExprs.push_back(TheCall->getArg(1)); // Val1
-  } else {
+    break;
+  case GNUXchg:
+    // Note, AtomicExpr::getVal2() has a special case for this atomic.
     SubExprs.push_back(TheCall->getArg(3)); // Order
     SubExprs.push_back(TheCall->getArg(1)); // Val1
     SubExprs.push_back(TheCall->getArg(2)); // Val2
+    break;
+  case C11CmpXchg:
+    SubExprs.push_back(TheCall->getArg(3)); // Order
+    SubExprs.push_back(TheCall->getArg(1)); // Val1
     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
+    SubExprs.push_back(TheCall->getArg(2)); // Val2
+    break;
+  case GNUCmpXchg:
+    SubExprs.push_back(TheCall->getArg(4)); // Order
+    SubExprs.push_back(TheCall->getArg(1)); // Val1
+    SubExprs.push_back(TheCall->getArg(5)); // OrderFail
+    SubExprs.push_back(TheCall->getArg(2)); // Val2
+    SubExprs.push_back(TheCall->getArg(3)); // Weak
+    break;
   }
=20
   return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(=
),
@@ -663,6 +827,12 @@
   // casts here.
   // FIXME: We don't allow floating point scalars as input.
   Expr *FirstArg =3D TheCall->getArg(0);
+  ExprResult FirstArgResult =3D DefaultFunctionArrayLvalueConversion(First=
Arg);
+  if (FirstArgResult.isInvalid())
+    return ExprError();
+  FirstArg =3D FirstArgResult.take();
+  TheCall->setArg(0, FirstArg);
+
   const PointerType *pointerType =3D FirstArg->getType()->getAs<PointerTyp=
e>();
   if (!pointerType) {
     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
@@ -749,34 +919,145 @@
   unsigned BuiltinIndex, NumFixed =3D 1;
   switch (BuiltinID) {
   default: llvm_unreachable("Unknown overloaded atomic builtin!");
-  case Builtin::BI__sync_fetch_and_add: BuiltinIndex =3D 0; break;
-  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex =3D 1; break;
-  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex =3D 2; break;
-  case Builtin::BI__sync_fetch_and_and: BuiltinIndex =3D 3; break;
-  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex =3D 4; break;
-
-  case Builtin::BI__sync_add_and_fetch: BuiltinIndex =3D 5; break;
-  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex =3D 6; break;
-  case Builtin::BI__sync_and_and_fetch: BuiltinIndex =3D 7; break;
-  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex =3D 8; break;
-  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =3D 9; break;
+  case Builtin::BI__sync_fetch_and_add:=20
+  case Builtin::BI__sync_fetch_and_add_1:
+  case Builtin::BI__sync_fetch_and_add_2:
+  case Builtin::BI__sync_fetch_and_add_4:
+  case Builtin::BI__sync_fetch_and_add_8:
+  case Builtin::BI__sync_fetch_and_add_16:
+    BuiltinIndex =3D 0;=20
+    break;
+     =20
+  case Builtin::BI__sync_fetch_and_sub:=20
+  case Builtin::BI__sync_fetch_and_sub_1:
+  case Builtin::BI__sync_fetch_and_sub_2:
+  case Builtin::BI__sync_fetch_and_sub_4:
+  case Builtin::BI__sync_fetch_and_sub_8:
+  case Builtin::BI__sync_fetch_and_sub_16:
+    BuiltinIndex =3D 1;=20
+    break;
+     =20
+  case Builtin::BI__sync_fetch_and_or: =20
+  case Builtin::BI__sync_fetch_and_or_1:
+  case Builtin::BI__sync_fetch_and_or_2:
+  case Builtin::BI__sync_fetch_and_or_4:
+  case Builtin::BI__sync_fetch_and_or_8:
+  case Builtin::BI__sync_fetch_and_or_16:
+    BuiltinIndex =3D 2;=20
+    break;
+     =20
+  case Builtin::BI__sync_fetch_and_and:=20
+  case Builtin::BI__sync_fetch_and_and_1:
+  case Builtin::BI__sync_fetch_and_and_2:
+  case Builtin::BI__sync_fetch_and_and_4:
+  case Builtin::BI__sync_fetch_and_and_8:
+  case Builtin::BI__sync_fetch_and_and_16:
+    BuiltinIndex =3D 3;=20
+    break;
+
+  case Builtin::BI__sync_fetch_and_xor:=20
+  case Builtin::BI__sync_fetch_and_xor_1:
+  case Builtin::BI__sync_fetch_and_xor_2:
+  case Builtin::BI__sync_fetch_and_xor_4:
+  case Builtin::BI__sync_fetch_and_xor_8:
+  case Builtin::BI__sync_fetch_and_xor_16:
+    BuiltinIndex =3D 4;=20
+    break;
+
+  case Builtin::BI__sync_add_and_fetch:=20
+  case Builtin::BI__sync_add_and_fetch_1:
+  case Builtin::BI__sync_add_and_fetch_2:
+  case Builtin::BI__sync_add_and_fetch_4:
+  case Builtin::BI__sync_add_and_fetch_8:
+  case Builtin::BI__sync_add_and_fetch_16:
+    BuiltinIndex =3D 5;=20
+    break;
+     =20
+  case Builtin::BI__sync_sub_and_fetch:=20
+  case Builtin::BI__sync_sub_and_fetch_1:
+  case Builtin::BI__sync_sub_and_fetch_2:
+  case Builtin::BI__sync_sub_and_fetch_4:
+  case Builtin::BI__sync_sub_and_fetch_8:
+  case Builtin::BI__sync_sub_and_fetch_16:
+    BuiltinIndex =3D 6;=20
+    break;
+     =20
+  case Builtin::BI__sync_and_and_fetch:=20
+  case Builtin::BI__sync_and_and_fetch_1:
+  case Builtin::BI__sync_and_and_fetch_2:
+  case Builtin::BI__sync_and_and_fetch_4:
+  case Builtin::BI__sync_and_and_fetch_8:
+  case Builtin::BI__sync_and_and_fetch_16:
+    BuiltinIndex =3D 7;=20
+    break;
+     =20
+  case Builtin::BI__sync_or_and_fetch: =20
+  case Builtin::BI__sync_or_and_fetch_1:
+  case Builtin::BI__sync_or_and_fetch_2:
+  case Builtin::BI__sync_or_and_fetch_4:
+  case Builtin::BI__sync_or_and_fetch_8:
+  case Builtin::BI__sync_or_and_fetch_16:
+    BuiltinIndex =3D 8;=20
+    break;
+     =20
+  case Builtin::BI__sync_xor_and_fetch:=20
+  case Builtin::BI__sync_xor_and_fetch_1:
+  case Builtin::BI__sync_xor_and_fetch_2:
+  case Builtin::BI__sync_xor_and_fetch_4:
+  case Builtin::BI__sync_xor_and_fetch_8:
+  case Builtin::BI__sync_xor_and_fetch_16:
+    BuiltinIndex =3D 9;=20
+    break;
=20
   case Builtin::BI__sync_val_compare_and_swap:
+  case Builtin::BI__sync_val_compare_and_swap_1:
+  case Builtin::BI__sync_val_compare_and_swap_2:
+  case Builtin::BI__sync_val_compare_and_swap_4:
+  case Builtin::BI__sync_val_compare_and_swap_8:
+  case Builtin::BI__sync_val_compare_and_swap_16:
     BuiltinIndex =3D 10;
     NumFixed =3D 2;
     break;
+     =20
   case Builtin::BI__sync_bool_compare_and_swap:
+  case Builtin::BI__sync_bool_compare_and_swap_1:
+  case Builtin::BI__sync_bool_compare_and_swap_2:
+  case Builtin::BI__sync_bool_compare_and_swap_4:
+  case Builtin::BI__sync_bool_compare_and_swap_8:
+  case Builtin::BI__sync_bool_compare_and_swap_16:
     BuiltinIndex =3D 11;
     NumFixed =3D 2;
     ResultType =3D Context.BoolTy;
     break;
-  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex =3D 12; break;
+     =20
+  case Builtin::BI__sync_lock_test_and_set:=20
+  case Builtin::BI__sync_lock_test_and_set_1:
+  case Builtin::BI__sync_lock_test_and_set_2:
+  case Builtin::BI__sync_lock_test_and_set_4:
+  case Builtin::BI__sync_lock_test_and_set_8:
+  case Builtin::BI__sync_lock_test_and_set_16:
+    BuiltinIndex =3D 12;=20
+    break;
+     =20
   case Builtin::BI__sync_lock_release:
+  case Builtin::BI__sync_lock_release_1:
+  case Builtin::BI__sync_lock_release_2:
+  case Builtin::BI__sync_lock_release_4:
+  case Builtin::BI__sync_lock_release_8:
+  case Builtin::BI__sync_lock_release_16:
     BuiltinIndex =3D 13;
     NumFixed =3D 0;
     ResultType =3D Context.VoidTy;
     break;
-  case Builtin::BI__sync_swap: BuiltinIndex =3D 14; break;
+     =20
+  case Builtin::BI__sync_swap:=20
+  case Builtin::BI__sync_swap_1:
+  case Builtin::BI__sync_swap_2:
+  case Builtin::BI__sync_swap_4:
+  case Builtin::BI__sync_swap_8:
+  case Builtin::BI__sync_swap_16:
+    BuiltinIndex =3D 14;=20
+    break;
   }
=20
   // Now that we know how many fixed arguments we expect, first check that=
 we
@@ -827,7 +1108,9 @@
   DeclRefExpr* NewDRE =3D DeclRefExpr::Create(
       Context,
       DRE->getQualifierLoc(),
+      SourceLocation(),
       NewBuiltinDecl,
+      /*enclosing*/ false,
       DRE->getLocation(),
       NewBuiltinDecl->getType(),
       DRE->getValueKind());
@@ -1020,7 +1303,6 @@
              "promotion from float to double is the only expected cast her=
e");
       Cast->setSubExpr(0);
       TheCall->setArg(NumArgs-1, CastArg);
-      OrigArg =3D CastArg;
     }
   }
  =20
@@ -1204,33 +1486,35 @@
 }
=20
 // Handle i > 1 ? "x" : "y", recursively.
-bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
-                                  bool HasVAListArg,
+bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
+                                  unsigned NumArgs, bool HasVAListArg,
                                   unsigned format_idx, unsigned firstDataA=
rg,
-                                  bool isPrintf) {
+                                  FormatStringType Type, bool inFunctionCa=
ll) {
  tryAgain:
   if (E->isTypeDependent() || E->isValueDependent())
     return false;
=20
-  E =3D E->IgnoreParens();
-
-  switch (E->getStmtClass()) {
-  case Stmt::BinaryConditionalOperatorClass:
-  case Stmt::ConditionalOperatorClass: {
-    const AbstractConditionalOperator *C =3D cast<AbstractConditionalOpera=
tor>(E);
-    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
-                                  format_idx, firstDataArg, isPrintf)
-        && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
-                                  format_idx, firstDataArg, isPrintf);
-  }
-
-  case Stmt::IntegerLiteralClass:
+  E =3D E->IgnoreParenCasts();
+
+  if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
     // Technically -Wformat-nonliteral does not warn about this case.
     // The behavior of printf and friends in this case is implementation
     // dependent.  Ideally if the format string cannot be null then
     // it should have a 'nonnull' attribute in the function prototype.
     return true;
=20
+  switch (E->getStmtClass()) {
+  case Stmt::BinaryConditionalOperatorClass:
+  case Stmt::ConditionalOperatorClass: {
+    const AbstractConditionalOperator *C =3D cast<AbstractConditionalOpera=
tor>(E);
+    return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVALi=
stArg,
+                                  format_idx, firstDataArg, Type,
+                                  inFunctionCall)
+       && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVALi=
stArg,
+                                 format_idx, firstDataArg, Type,
+                                 inFunctionCall);
+  }
+
   case Stmt::ImplicitCastExprClass: {
     E =3D cast<ImplicitCastExpr>(E)->getSubExpr();
     goto tryAgain;
@@ -1263,13 +1547,17 @@
       } else if (const PointerType *PT =3D T->getAs<PointerType>()) {
         isConstant =3D T.isConstant(Context) &&
                      PT->getPointeeType().isConstant(Context);
+      } else if (T->isObjCObjectPointerType()) {
+        // In ObjC, there is usually no "const ObjectPointer" type,
+        // so don't check if the pointee type is constant.
+        isConstant =3D T.isConstant(Context);
       }
=20
       if (isConstant) {
         if (const Expr *Init =3D VD->getAnyInitializer())
-          return SemaCheckStringLiteral(Init, TheCall,
+          return SemaCheckStringLiteral(Init, Args, NumArgs,
                                         HasVAListArg, format_idx, firstDat=
aArg,
-                                        isPrintf);
+                                        Type, /*inFunctionCall*/false);
       }
=20
       // For vprintf* functions (i.e., HasVAListArg=3D=3Dtrue), we add a
@@ -1286,32 +1574,46 @@
       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
       //      ...
       //
-      //
-      //  FIXME: We don't have full attribute support yet, so just check t=
o see
-      //    if the argument is a DeclRefExpr that references a parameter. =
 We'll
-      //    add proper support for checking the attribute later.
-      if (HasVAListArg)
-        if (isa<ParmVarDecl>(VD))
-          return true;
+      if (HasVAListArg) {
+        if (const ParmVarDecl *PV =3D dyn_cast<ParmVarDecl>(VD)) {
+          if (const NamedDecl *ND =3D dyn_cast<NamedDecl>(PV->getDeclConte=
xt())) {
+            int PVIndex =3D PV->getFunctionScopeIndex() + 1;
+            for (specific_attr_iterator<FormatAttr>
+                 i =3D ND->specific_attr_begin<FormatAttr>(),
+                 e =3D ND->specific_attr_end<FormatAttr>(); i !=3D e ; ++i=
) {
+              FormatAttr *PVFormat =3D *i;
+              // adjust for implicit parameter
+              if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(ND))
+                if (MD->isInstance())
+                  ++PVIndex;
+              // We also check if the formats are compatible.
+              // We can't pass a 'scanf' string to a 'printf' function.
+              if (PVIndex =3D=3D PVFormat->getFormatIdx() &&
+                  Type =3D=3D GetFormatStringType(PVFormat))
+                return true;
+            }
+          }
+        }
+      }
     }
=20
     return false;
   }
=20
-  case Stmt::CallExprClass: {
+  case Stmt::CallExprClass:
+  case Stmt::CXXMemberCallExprClass: {
     const CallExpr *CE =3D cast<CallExpr>(E);
-    if (const ImplicitCastExpr *ICE
-          =3D dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
-      if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(ICE->getSubExpr=
())) {
-        if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(DRE->getDecl=
())) {
-          if (const FormatArgAttr *FA =3D FD->getAttr<FormatArgAttr>()) {
-            unsigned ArgIndex =3D FA->getFormatIdx();
-            const Expr *Arg =3D CE->getArg(ArgIndex - 1);
-
-            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
-                                          format_idx, firstDataArg, isPrin=
tf);
-          }
-        }
+    if (const NamedDecl *ND =3D dyn_cast_or_null<NamedDecl>(CE->getCalleeD=
ecl())) {
+      if (const FormatArgAttr *FA =3D ND->getAttr<FormatArgAttr>()) {
+        unsigned ArgIndex =3D FA->getFormatIdx();
+        if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(ND))
+          if (MD->isInstance())
+            --ArgIndex;
+        const Expr *Arg =3D CE->getArg(ArgIndex - 1);
+
+        return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
+                                      format_idx, firstDataArg, Type,
+                                      inFunctionCall);
       }
     }
=20
@@ -1327,8 +1629,8 @@
       StrE =3D cast<StringLiteral>(E);
=20
     if (StrE) {
-      CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
-                        firstDataArg, isPrintf);
+      CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
+                        firstDataArg, Type, inFunctionCall);
       return true;
     }
=20
@@ -1354,39 +1656,58 @@
   }
 }
=20
+Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format)=
 {
+  return llvm::StringSwitch<FormatStringType>(Format->getType())
+  .Case("scanf", FST_Scanf)
+  .Cases("printf", "printf0", FST_Printf)
+  .Cases("NSString", "CFString", FST_NSString)
+  .Case("strftime", FST_Strftime)
+  .Case("strfmon", FST_Strfmon)
+  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
+  .Default(FST_Unknown);
+}
+
 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and simil=
ar
 /// functions) for correct use of format strings.
-void
-Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
-                                unsigned format_idx, unsigned firstDataArg,
-                                bool isPrintf) {
-
-  const Expr *Fn =3D TheCall->getCallee();
-
+void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCal=
l) {
+  bool IsCXXMember =3D false;
   // The way the format attribute works in GCC, the implicit this argument
   // of member functions is counted. However, it doesn't appear in our own
   // lists, so decrement format_idx in that case.
-  if (isa<CXXMemberCallExpr>(TheCall)) {
-    const CXXMethodDecl *method_decl =3D
-      dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
-    if (method_decl && method_decl->isInstance()) {
-      // Catch a format attribute mistakenly referring to the object argum=
ent.
-      if (format_idx =3D=3D 0)
-        return;
-      --format_idx;
-      if(firstDataArg !=3D 0)
-        --firstDataArg;
-    }
+  IsCXXMember =3D isa<CXXMemberCallExpr>(TheCall);
+  CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
+                       IsCXXMember, TheCall->getRParenLoc(),=20
+                       TheCall->getCallee()->getSourceRange());
+}
+
+void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
+                                unsigned NumArgs, bool IsCXXMember,
+                                SourceLocation Loc, SourceRange Range) {
+  bool HasVAListArg =3D Format->getFirstArg() =3D=3D 0;
+  unsigned format_idx =3D Format->getFormatIdx() - 1;
+  unsigned firstDataArg =3D HasVAListArg ? 0 : Format->getFirstArg() - 1;
+  if (IsCXXMember) {
+    if (format_idx =3D=3D 0)
+      return;
+    --format_idx;
+    if(firstDataArg !=3D 0)
+      --firstDataArg;
   }
-
+  CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
+                       firstDataArg, GetFormatStringType(Format), Loc, Ran=
ge);
+}
+
+void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
+                                bool HasVAListArg, unsigned format_idx,
+                                unsigned firstDataArg, FormatStringType Ty=
pe,
+                                SourceLocation Loc, SourceRange Range) {
   // CHECK: printf/scanf-like function is called with no format string.
-  if (format_idx >=3D TheCall->getNumArgs()) {
-    Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
-      << Fn->getSourceRange();
+  if (format_idx >=3D NumArgs) {
+    Diag(Loc, diag::warn_missing_format_string) << Range;
     return;
   }
=20
-  const Expr *OrigFormatExpr =3D TheCall->getArg(format_idx)->IgnoreParenC=
asts();
+  const Expr *OrigFormatExpr =3D Args[format_idx]->IgnoreParenCasts();
=20
   // CHECK: format string is not a string literal.
   //
@@ -1400,18 +1721,30 @@
   // C string (e.g. "%d")
   // ObjC string uses the same format specifiers as C string, so we can use
   // the same format string checking logic for both ObjC and C strings.
-  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format=
_idx,
-                             firstDataArg, isPrintf))
+  if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
+                             format_idx, firstDataArg, Type))
     return;  // Literal format string found, check done!
=20
+  // Strftime is particular as it always uses a single 'time' argument,
+  // so it is safe to pass a non-literal string.
+  if (Type =3D=3D FST_Strftime)
+    return;
+
+  // Do not emit diag when the string param is a macro expansion and the
+  // format is either NSString or CFString. This is a hack to prevent
+  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
+  // which are usually used in place of NS and CF string literals.
+  if (Type =3D=3D FST_NSString && Args[format_idx]->getLocStart().isMacroI=
D())
+    return;
+
   // If there are no arguments specified, warn with -Wformat-security, oth=
erwise
   // warn only with -Wformat-nonliteral.
-  if (TheCall->getNumArgs() =3D=3D format_idx+1)
-    Diag(TheCall->getArg(format_idx)->getLocStart(),
+  if (NumArgs =3D=3D format_idx+1)
+    Diag(Args[format_idx]->getLocStart(),
          diag::warn_format_nonliteral_noargs)
       << OrigFormatExpr->getSourceRange();
   else
-    Diag(TheCall->getArg(format_idx)->getLocStart(),
+    Diag(Args[format_idx]->getLocStart(),
          diag::warn_format_nonliteral)
            << OrigFormatExpr->getSourceRange();
 }
@@ -1427,24 +1760,28 @@
   const bool IsObjCLiteral;
   const char *Beg; // Start of format string.
   const bool HasVAListArg;
-  const CallExpr *TheCall;
+  const Expr * const *Args;
+  const unsigned NumArgs;
   unsigned FormatIdx;
   llvm::BitVector CoveredArgs;
   bool usesPositionalArgs;
   bool atFirstArg;
+  bool inFunctionCall;
 public:
   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
                      const Expr *origFormatExpr, unsigned firstDataArg,
                      unsigned numDataArgs, bool isObjCLiteral,
                      const char *beg, bool hasVAListArg,
-                     const CallExpr *theCall, unsigned formatIdx)
+                     Expr **args, unsigned numArgs,
+                     unsigned formatIdx, bool inFunctionCall)
     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
       FirstDataArg(firstDataArg),
       NumDataArgs(numDataArgs),
       IsObjCLiteral(isObjCLiteral), Beg(beg),
       HasVAListArg(hasVAListArg),
-      TheCall(theCall), FormatIdx(formatIdx),
-      usesPositionalArgs(false), atFirstArg(true) {
+      Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
+      usesPositionalArgs(false), atFirstArg(true),
+      inFunctionCall(inFunctionCall) {
         CoveredArgs.resize(numDataArgs);
         CoveredArgs.reset();
       }
@@ -1453,7 +1790,22 @@
=20
   void HandleIncompleteSpecifier(const char *startSpecifier,
                                  unsigned specifierLen);
-   =20
+
+  void HandleNonStandardLengthModifier(
+      const analyze_format_string::LengthModifier &LM,
+      const char *startSpecifier, unsigned specifierLen);
+
+  void HandleNonStandardConversionSpecifier(
+      const analyze_format_string::ConversionSpecifier &CS,
+      const char *startSpecifier, unsigned specifierLen);
+
+  void HandleNonStandardConversionSpecification(
+      const analyze_format_string::LengthModifier &LM,
+      const analyze_format_string::ConversionSpecifier &CS,
+      const char *startSpecifier, unsigned specifierLen);
+
+  virtual void HandlePosition(const char *startPos, unsigned posLen);
+
   virtual void HandleInvalidPosition(const char *startSpecifier,
                                      unsigned specifierLen,
                                      analyze_format_string::PositionContex=
t p);
@@ -1462,11 +1814,23 @@
=20
   void HandleNullChar(const char *nullCharacter);
=20
+  template <typename Range>
+  static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
+                                   const Expr *ArgumentExpr,
+                                   PartialDiagnostic PDiag,
+                                   SourceLocation StringLoc,
+                                   bool IsStringLocation, Range StringRang=
e,
+                                   FixItHint Fixit =3D FixItHint());
+
 protected:
   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation =
Loc,
                                         const char *startSpec,
                                         unsigned specifierLen,
                                         const char *csStart, unsigned csLe=
n);
+
+  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
+                                         const char *startSpec,
+                                         unsigned specifierLen);
  =20
   SourceRange getFormatStringRange();
   CharSourceRange getSpecifierRange(const char *startSpecifier,
@@ -1479,6 +1843,14 @@
                     const analyze_format_string::ConversionSpecifier &CS,
                     const char *startSpecifier, unsigned specifierLen,
                     unsigned argIndex);
+
+  template <typename Range>
+  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation String=
Loc,
+                            bool IsStringLocation, Range StringRange,
+                            FixItHint Fixit =3D FixItHint());
+
+  void CheckPositionalAndNonpositionalArgs(
+      const analyze_format_string::FormatSpecifier *FS);
 };
 }
=20
@@ -1503,37 +1875,80 @@
=20
 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecif=
ier,
                                                    unsigned specifierLen){
-  SourceLocation Loc =3D getLocationOfByte(startSpecifier);
-  S.Diag(Loc, diag::warn_printf_incomplete_specifier)
-    << getSpecifierRange(startSpecifier, specifierLen);
+  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
+                       getLocationOfByte(startSpecifier),
+                       /*IsStringLocation*/true,
+                       getSpecifierRange(startSpecifier, specifierLen));
+}
+
+void CheckFormatHandler::HandleNonStandardLengthModifier(
+    const analyze_format_string::LengthModifier &LM,
+    const char *startSpecifier, unsigned specifierLen) {
+  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toStr=
ing()
+                       << 0,
+                       getLocationOfByte(LM.getStart()),
+                       /*IsStringLocation*/true,
+                       getSpecifierRange(startSpecifier, specifierLen));
+}
+
+void CheckFormatHandler::HandleNonStandardConversionSpecifier(
+    const analyze_format_string::ConversionSpecifier &CS,
+    const char *startSpecifier, unsigned specifierLen) {
+  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toStr=
ing()
+                       << 1,
+                       getLocationOfByte(CS.getStart()),
+                       /*IsStringLocation*/true,
+                       getSpecifierRange(startSpecifier, specifierLen));
+}
+
+void CheckFormatHandler::HandleNonStandardConversionSpecification(
+    const analyze_format_string::LengthModifier &LM,
+    const analyze_format_string::ConversionSpecifier &CS,
+    const char *startSpecifier, unsigned specifierLen) {
+  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_s=
pec)
+                       << LM.toString() << CS.toString(),
+                       getLocationOfByte(LM.getStart()),
+                       /*IsStringLocation*/true,
+                       getSpecifierRange(startSpecifier, specifierLen));
+}
+
+void CheckFormatHandler::HandlePosition(const char *startPos,
+                                        unsigned posLen) {
+  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_a=
rg),
+                               getLocationOfByte(startPos),
+                               /*IsStringLocation*/true,
+                               getSpecifierRange(startPos, posLen));
 }
=20
 void
 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned p=
osLen,
                                      analyze_format_string::PositionContex=
t p) {
-  SourceLocation Loc =3D getLocationOfByte(startPos);
-  S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
-    << (unsigned) p << getSpecifierRange(startPos, posLen);
+  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specif=
ier)
+                         << (unsigned) p,
+                       getLocationOfByte(startPos), /*IsStringLocation*/tr=
ue,
+                       getSpecifierRange(startPos, posLen));
 }
=20
 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
                                             unsigned posLen) {
-  SourceLocation Loc =3D getLocationOfByte(startPos);
-  S.Diag(Loc, diag::warn_format_zero_positional_specifier)
-    << getSpecifierRange(startPos, posLen);
+  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier=
),
+                               getLocationOfByte(startPos),
+                               /*IsStringLocation*/true,
+                               getSpecifierRange(startPos, posLen));
 }
=20
 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
   if (!IsObjCLiteral) {
     // The presence of a null character is likely an error.
-    S.Diag(getLocationOfByte(nullCharacter),
-           diag::warn_printf_format_string_contains_null_char)
-      << getFormatStringRange();
+    EmitFormatDiagnostic(
+      S.PDiag(diag::warn_printf_format_string_contains_null_char),
+      getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
+      getFormatStringRange());
   }
 }
=20
 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
-  return TheCall->getArg(FirstDataArg + i);
+  return Args[FirstDataArg + i];
 }
=20
 void CheckFormatHandler::DoneProcessing() {
@@ -1545,9 +1960,9 @@
     signed notCoveredArg =3D CoveredArgs.find_first();
     if (notCoveredArg >=3D 0) {
       assert((unsigned)notCoveredArg < NumDataArgs);
-      S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
-             diag::warn_printf_data_arg_not_used)
-      << getFormatStringRange();
+      EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
+                           getDataArg((unsigned) notCoveredArg)->getLocSta=
rt(),
+                           /*IsStringLocation*/false, getFormatStringRange=
());
     }
   }
 }
@@ -1575,13 +1990,23 @@
     keepGoing =3D false;
   }
  =20
-  S.Diag(Loc, diag::warn_format_invalid_conversion)
-    << StringRef(csStart, csLen)
-    << getSpecifierRange(startSpec, specifierLen);
+  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
+                         << StringRef(csStart, csLen),
+                       Loc, /*IsStringLocation*/true,
+                       getSpecifierRange(startSpec, specifierLen));
  =20
   return keepGoing;
 }
=20
+void
+CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
+                                                      const char *startSpe=
c,
+                                                      unsigned specifierLe=
n) {
+  EmitFormatDiagnostic(
+    S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
+    Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
+}
+
 bool
 CheckFormatHandler::CheckNumArgs(
   const analyze_format_string::FormatSpecifier &FS,
@@ -1589,23 +2014,74 @@
   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
=20
   if (argIndex >=3D NumDataArgs) {
-    if (FS.usesPositionalArg())  {
-      S.Diag(getLocationOfByte(CS.getStart()),
-             diag::warn_printf_positional_arg_exceeds_data_args)
-      << (argIndex+1) << NumDataArgs
-      << getSpecifierRange(startSpecifier, specifierLen);
-    }
-    else {
-      S.Diag(getLocationOfByte(CS.getStart()),
-             diag::warn_printf_insufficient_data_args)
-      << getSpecifierRange(startSpecifier, specifierLen);
-    }
-   =20
+    PartialDiagnostic PDiag =3D FS.usesPositionalArg()
+      ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
+           << (argIndex+1) << NumDataArgs)
+      : S.PDiag(diag::warn_printf_insufficient_data_args);
+    EmitFormatDiagnostic(
+      PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
+      getSpecifierRange(startSpecifier, specifierLen));
     return false;
   }
   return true;
 }
=20
+template<typename Range>
+void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
+                                              SourceLocation Loc,
+                                              bool IsStringLocation,
+                                              Range StringRange,
+                                              FixItHint FixIt) {
+  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
+                       Loc, IsStringLocation, StringRange, FixIt);
+}
+
+/// \brief If the format string is not within the funcion call, emit a note
+/// so that the function call and string are in diagnostic messages.
+///
+/// \param inFunctionCall if true, the format string is within the function
+/// call and only one diagnostic message will be produced.  Otherwise, an
+/// extra note will be emitted pointing to location of the format string.
+///
+/// \param ArgumentExpr the expression that is passed as the format string
+/// argument in the function call.  Used for getting locations when two
+/// diagnostics are emitted.
+///
+/// \param PDiag the callee should already have provided any strings for t=
he
+/// diagnostic message.  This function only adds locations and fixits
+/// to diagnostics.
+///
+/// \param Loc primary location for diagnostic.  If two diagnostics are
+/// required, one will be at Loc and a new SourceLocation will be created =
for
+/// the other one.
+///
+/// \param IsStringLocation if true, Loc points to the format string shoul=
d be
+/// used for the note.  Otherwise, Loc points to the argument list and will
+/// be used with PDiag.
+///
+/// \param StringRange some or all of the string to highlight.  This is
+/// templated so it can accept either a CharSourceRange or a SourceRange.
+///
+/// \param Fixit optional fix it hint for the format string.
+template<typename Range>
+void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
+                                              const Expr *ArgumentExpr,
+                                              PartialDiagnostic PDiag,
+                                              SourceLocation Loc,
+                                              bool IsStringLocation,
+                                              Range StringRange,
+                                              FixItHint FixIt) {
+  if (InFunctionCall)
+    S.Diag(Loc, PDiag) << StringRange << FixIt;
+  else {
+    S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
+      << ArgumentExpr->getSourceRange();
+    S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
+           diag::note_format_string_defined)
+      << StringRange << FixIt;
+  }
+}
+
 //=3D=3D=3D--- CHECK: Printf format string checking ----------------------=
--------=3D=3D=3D//
=20
 namespace {
@@ -1615,10 +2091,11 @@
                      const Expr *origFormatExpr, unsigned firstDataArg,
                      unsigned numDataArgs, bool isObjCLiteral,
                      const char *beg, bool hasVAListArg,
-                     const CallExpr *theCall, unsigned formatIdx)
+                     Expr **Args, unsigned NumArgs,
+                     unsigned formatIdx, bool inFunctionCall)
   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
-                       theCall, formatIdx) {}
+                       Args, NumArgs, formatIdx, inFunctionCall) {}
  =20
  =20
   bool HandleInvalidPrintfConversionSpecifier(
@@ -1668,9 +2145,11 @@
     if (!HasVAListArg) {
       unsigned argIndex =3D Amt.getArgIndex();
       if (argIndex >=3D NumDataArgs) {
-        S.Diag(getLocationOfByte(Amt.getStart()),
-               diag::warn_printf_asterisk_missing_arg)
-          << k << getSpecifierRange(startSpecifier, specifierLen);
+        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_ar=
g)
+                               << k,
+                             getLocationOfByte(Amt.getStart()),
+                             /*IsStringLocation*/true,
+                             getSpecifierRange(startSpecifier, specifierLe=
n));
         // Don't do any more checking.  We will just emit
         // spurious errors.
         return false;
@@ -1688,12 +2167,12 @@
       assert(ATR.isValid());
=20
       if (!ATR.matchesType(S.Context, T)) {
-        S.Diag(getLocationOfByte(Amt.getStart()),
-               diag::warn_printf_asterisk_wrong_type)
-          << k
-          << ATR.getRepresentativeType(S.Context) << T
-          << getSpecifierRange(startSpecifier, specifierLen)
-          << Arg->getSourceRange();
+        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
+                               << k << ATR.getRepresentativeTypeName(S.Con=
text)
+                               << T << Arg->getSourceRange(),
+                             getLocationOfByte(Amt.getStart()),
+                             /*IsStringLocation*/true,
+                             getSpecifierRange(startSpecifier, specifierLe=
n));
         // Don't do any more checking.  We will just emit
         // spurious errors.
         return false;
@@ -1711,25 +2190,19 @@
                                       unsigned specifierLen) {
   const analyze_printf::PrintfConversionSpecifier &CS =3D
     FS.getConversionSpecifier();
-  switch (Amt.getHowSpecified()) {
-  case analyze_printf::OptionalAmount::Constant:
-    S.Diag(getLocationOfByte(Amt.getStart()),
-        diag::warn_printf_nonsensical_optional_amount)
-      << type
-      << CS.toString()
-      << getSpecifierRange(startSpecifier, specifierLen)
-      << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
-          Amt.getConstantLength()));
-    break;
-
-  default:
-    S.Diag(getLocationOfByte(Amt.getStart()),
-        diag::warn_printf_nonsensical_optional_amount)
-      << type
-      << CS.toString()
-      << getSpecifierRange(startSpecifier, specifierLen);
-    break;
-  }
+
+  FixItHint fixit =3D
+    Amt.getHowSpecified() =3D=3D analyze_printf::OptionalAmount::Constant
+      ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
+                                 Amt.getConstantLength()))
+      : FixItHint();
+
+  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amou=
nt)
+                         << type << CS.toString(),
+                       getLocationOfByte(Amt.getStart()),
+                       /*IsStringLocation*/true,
+                       getSpecifierRange(startSpecifier, specifierLen),
+                       fixit);
 }
=20
 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier =
&FS,
@@ -1739,11 +2212,13 @@
   // Warn about pointless flag with a fixit removal.
   const analyze_printf::PrintfConversionSpecifier &CS =3D
     FS.getConversionSpecifier();
-  S.Diag(getLocationOfByte(flag.getPosition()),
-      diag::warn_printf_nonsensical_flag)
-    << flag.toString() << CS.toString()
-    << getSpecifierRange(startSpecifier, specifierLen)
-    << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
+  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
+                         << flag.toString() << CS.toString(),
+                       getLocationOfByte(flag.getPosition()),
+                       /*IsStringLocation*/true,
+                       getSpecifierRange(startSpecifier, specifierLen),
+                       FixItHint::CreateRemoval(
+                         getSpecifierRange(flag.getPosition(), 1)));
 }
=20
 void CheckPrintfHandler::HandleIgnoredFlag(
@@ -1753,12 +2228,13 @@
                                 const char *startSpecifier,
                                 unsigned specifierLen) {
   // Warn about ignored flag with a fixit removal.
-  S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
-      diag::warn_printf_ignored_flag)
-    << ignoredFlag.toString() << flag.toString()
-    << getSpecifierRange(startSpecifier, specifierLen)
-    << FixItHint::CreateRemoval(getSpecifierRange(
-        ignoredFlag.getPosition(), 1));
+  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
+                         << ignoredFlag.toString() << flag.toString(),
+                       getLocationOfByte(ignoredFlag.getPosition()),
+                       /*IsStringLocation*/true,
+                       getSpecifierRange(startSpecifier, specifierLen),
+                       FixItHint::CreateRemoval(
+                         getSpecifierRange(ignoredFlag.getPosition(), 1)));
 }
=20
 bool
@@ -1777,10 +2253,8 @@
         usesPositionalArgs =3D FS.usesPositionalArg();
     }
     else if (usesPositionalArgs !=3D FS.usesPositionalArg()) {
-      // Cannot mix-and-match positional and non-positional arguments.
-      S.Diag(getLocationOfByte(CS.getStart()),
-             diag::warn_format_mix_positional_nonpositional_args)
-        << getSpecifierRange(startSpecifier, specifierLen);
+      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
+                                        startSpecifier, specifierLen);
       return false;
     }
   }
@@ -1889,18 +2363,29 @@
   // Check the length modifier is valid with the given conversion specifie=
r.
   const LengthModifier &LM =3D FS.getLengthModifier();
   if (!FS.hasValidLengthModifier())
-    S.Diag(getLocationOfByte(LM.getStart()),
-        diag::warn_format_nonsensical_length)
-      << LM.toString() << CS.toString()
-      << getSpecifierRange(startSpecifier, specifierLen)
-      << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
-          LM.getLength()));
+    EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
+                           << LM.toString() << CS.toString(),
+                         getLocationOfByte(LM.getStart()),
+                         /*IsStringLocation*/true,
+                         getSpecifierRange(startSpecifier, specifierLen),
+                         FixItHint::CreateRemoval(
+                           getSpecifierRange(LM.getStart(),
+                                             LM.getLength())));
+  if (!FS.hasStandardLengthModifier())
+    HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
+  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
+    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
+  if (!FS.hasStandardLengthConversionCombination())
+    HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
+                                             specifierLen);
=20
   // Are we using '%n'?
   if (CS.getKind() =3D=3D ConversionSpecifier::nArg) {
     // Issue a warning about this being a possible security issue.
-    S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
-      << getSpecifierRange(startSpecifier, specifierLen);
+    EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
+                         getLocationOfByte(CS.getStart()),
+                         /*IsStringLocation*/true,
+                         getSpecifierRange(startSpecifier, specifierLen));
     // Continue checking the other format specifiers.
     return true;
   }
@@ -1915,7 +2400,8 @@
   // Now type check the data expression that matches the
   // format specifier.
   const Expr *Ex =3D getDataArg(argIndex);
-  const analyze_printf::ArgTypeResult &ATR =3D FS.getArgType(S.Context);
+  const analyze_printf::ArgTypeResult &ATR =3D FS.getArgType(S.Context,
+                                                           IsObjCLiteral);
   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
     // Check if we didn't match because of an implicit cast from a 'char'
     // or 'short' to an 'int'.  This is done because printf is a varargs
@@ -1930,32 +2416,35 @@
=20
     // We may be able to offer a FixItHint if it is a supported type.
     PrintfSpecifier fixedFS =3D FS;
-    bool success =3D fixedFS.fixType(Ex->getType());
+    bool success =3D fixedFS.fixType(Ex->getType(), S.getLangOpts(),
+                                   S.Context, IsObjCLiteral);
=20
     if (success) {
       // Get the fix string from the fixed format specifier
-      llvm::SmallString<128> buf;
+      SmallString<128> buf;
       llvm::raw_svector_ostream os(buf);
       fixedFS.toString(os);
=20
-      // FIXME: getRepresentativeType() perhaps should return a string
-      // instead of a QualType to better handle when the representative
-      // type is 'wint_t' (which is defined in the system headers).
-      S.Diag(getLocationOfByte(CS.getStart()),
-          diag::warn_printf_conversion_argument_type_mismatch)
-        << ATR.getRepresentativeType(S.Context) << Ex->getType()
-        << getSpecifierRange(startSpecifier, specifierLen)
-        << Ex->getSourceRange()
-        << FixItHint::CreateReplacement(
-            getSpecifierRange(startSpecifier, specifierLen),
-            os.str());
+      EmitFormatDiagnostic(
+        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
+          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
+          << Ex->getSourceRange(),
+        getLocationOfByte(CS.getStart()),
+        /*IsStringLocation*/true,
+        getSpecifierRange(startSpecifier, specifierLen),
+        FixItHint::CreateReplacement(
+          getSpecifierRange(startSpecifier, specifierLen),
+          os.str()));
     }
     else {
-      S.Diag(getLocationOfByte(CS.getStart()),
-             diag::warn_printf_conversion_argument_type_mismatch)
-        << ATR.getRepresentativeType(S.Context) << Ex->getType()
-        << getSpecifierRange(startSpecifier, specifierLen)
-        << Ex->getSourceRange();
+      EmitFormatDiagnostic(
+        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
+          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
+          << getSpecifierRange(startSpecifier, specifierLen)
+          << Ex->getSourceRange(),
+        getLocationOfByte(CS.getStart()),
+        true,
+        getSpecifierRange(startSpecifier, specifierLen));
     }
   }
=20
@@ -1971,10 +2460,11 @@
                     const Expr *origFormatExpr, unsigned firstDataArg,
                     unsigned numDataArgs, bool isObjCLiteral,
                     const char *beg, bool hasVAListArg,
-                    const CallExpr *theCall, unsigned formatIdx)
+                    Expr **Args, unsigned NumArgs,
+                    unsigned formatIdx, bool inFunctionCall)
   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
-                       theCall, formatIdx) {}
+                       Args, NumArgs, formatIdx, inFunctionCall) {}
  =20
   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
                             const char *startSpecifier,
@@ -1991,8 +2481,9 @@
=20
 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
                                                  const char *end) {
-  S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
-    << getSpecifierRange(start, end - start);
+  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
+                       getLocationOfByte(end), /*IsStringLocation*/true,
+                       getSpecifierRange(start, end - start));
 }
=20
 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
@@ -2027,10 +2518,8 @@
       usesPositionalArgs =3D FS.usesPositionalArg();
     }
     else if (usesPositionalArgs !=3D FS.usesPositionalArg()) {
-      // Cannot mix-and-match positional and non-positional arguments.
-      S.Diag(getLocationOfByte(CS.getStart()),
-             diag::warn_format_mix_positional_nonpositional_args)
-        << getSpecifierRange(startSpecifier, specifierLen);
+      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
+                                        startSpecifier, specifierLen);
       return false;
     }
   }
@@ -2041,9 +2530,10 @@
     if (Amt.getConstantAmount() =3D=3D 0) {
       const CharSourceRange &R =3D getSpecifierRange(Amt.getStart(),
                                                    Amt.getConstantLength()=
);
-      S.Diag(getLocationOfByte(Amt.getStart()),
-             diag::warn_scanf_nonzero_width)
-        << R << FixItHint::CreateRemoval(R);
+      EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
+                           getLocationOfByte(Amt.getStart()),
+                           /*IsStringLocation*/true, R,
+                           FixItHint::CreateRemoval(R));
     }
   }
  =20
@@ -2065,14 +2555,23 @@
   // Check the length modifier is valid with the given conversion specifie=
r.
   const LengthModifier &LM =3D FS.getLengthModifier();
   if (!FS.hasValidLengthModifier()) {
-    S.Diag(getLocationOfByte(LM.getStart()),
-           diag::warn_format_nonsensical_length)
-      << LM.toString() << CS.toString()
-      << getSpecifierRange(startSpecifier, specifierLen)
-      << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
-                                                    LM.getLength()));
+    const CharSourceRange &R =3D getSpecifierRange(LM.getStart(), LM.getLe=
ngth());
+    EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
+                         << LM.toString() << CS.toString()
+                         << getSpecifierRange(startSpecifier, specifierLen=
),
+                         getLocationOfByte(LM.getStart()),
+                         /*IsStringLocation*/true, R,
+                         FixItHint::CreateRemoval(R));
   }
=20
+  if (!FS.hasStandardLengthModifier())
+    HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
+  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
+    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
+  if (!FS.hasStandardLengthConversionCombination())
+    HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
+                                             specifierLen);
+
   // The remaining checks depend on the data arguments.
   if (HasVAListArg)
     return true;
@@ -2080,22 +2579,57 @@
   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
     return false;
  =20
-  // FIXME: Check that the argument type matches the format specifier.
- =20
+  // Check that the argument type matches the format specifier.
+  const Expr *Ex =3D getDataArg(argIndex);
+  const analyze_scanf::ScanfArgTypeResult &ATR =3D FS.getArgType(S.Context=
);
+  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
+    ScanfSpecifier fixedFS =3D FS;
+    bool success =3D fixedFS.fixType(Ex->getType(), S.getLangOpts(),
+                                   S.Context);
+
+    if (success) {
+      // Get the fix string from the fixed format specifier.
+      SmallString<128> buf;
+      llvm::raw_svector_ostream os(buf);
+      fixedFS.toString(os);
+
+      EmitFormatDiagnostic(
+        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
+          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
+          << Ex->getSourceRange(),
+        getLocationOfByte(CS.getStart()),
+        /*IsStringLocation*/true,
+        getSpecifierRange(startSpecifier, specifierLen),
+        FixItHint::CreateReplacement(
+          getSpecifierRange(startSpecifier, specifierLen),
+          os.str()));
+    } else {
+      EmitFormatDiagnostic(
+        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
+          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
+          << Ex->getSourceRange(),
+        getLocationOfByte(CS.getStart()),
+        /*IsStringLocation*/true,
+        getSpecifierRange(startSpecifier, specifierLen));
+    }
+  }
+
   return true;
 }
=20
 void Sema::CheckFormatString(const StringLiteral *FExpr,
                              const Expr *OrigFormatExpr,
-                             const CallExpr *TheCall, bool HasVAListArg,
-                             unsigned format_idx, unsigned firstDataArg,
-                             bool isPrintf) {
+                             Expr **Args, unsigned NumArgs,
+                             bool HasVAListArg, unsigned format_idx,
+                             unsigned firstDataArg, FormatStringType Type,
+                             bool inFunctionCall) {
  =20
   // CHECK: is the format string a wide literal?
   if (!FExpr->isAscii()) {
-    Diag(FExpr->getLocStart(),
-         diag::warn_format_string_is_wide_literal)
-    << OrigFormatExpr->getSourceRange();
+    CheckFormatHandler::EmitFormatDiagnostic(
+      *this, inFunctionCall, Args[format_idx],
+      PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(=
),
+      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
     return;
   }
  =20
@@ -2103,33 +2637,36 @@
   StringRef StrRef =3D FExpr->getString();
   const char *Str =3D StrRef.data();
   unsigned StrLen =3D StrRef.size();
-  const unsigned numDataArgs =3D TheCall->getNumArgs() - firstDataArg;
+  const unsigned numDataArgs =3D NumArgs - firstDataArg;
  =20
   // CHECK: empty format string?
   if (StrLen =3D=3D 0 && numDataArgs > 0) {
-    Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
-    << OrigFormatExpr->getSourceRange();
+    CheckFormatHandler::EmitFormatDiagnostic(
+      *this, inFunctionCall, Args[format_idx],
+      PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
+      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
     return;
   }
  =20
-  if (isPrintf) {
+  if (Type =3D=3D FST_Printf || Type =3D=3D FST_NSString) {
     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
                          numDataArgs, isa<ObjCStringLiteral>(OrigFormatExp=
r),
-                         Str, HasVAListArg, TheCall, format_idx);
+                         Str, HasVAListArg, Args, NumArgs, format_idx,
+                         inFunctionCall);
  =20
-    bool FormatExtensions =3D getLangOptions().FormatExtensions;
     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
-                                                  FormatExtensions))
+                                                  getLangOpts()))
       H.DoneProcessing();
-  }
-  else {
+  } else if (Type =3D=3D FST_Scanf) {
     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr=
),
-                        Str, HasVAListArg, TheCall, format_idx);
+                        Str, HasVAListArg, Args, NumArgs, format_idx,
+                        inFunctionCall);
    =20
-    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
+    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
+                                                 getLangOpts()))
       H.DoneProcessing();
-  }
+  } // TODO: handle other formats
 }
=20
 //=3D=3D=3D--- CHECK: Standard memory functions --------------------------=
-------=3D=3D=3D//
@@ -2174,16 +2711,19 @@
 ///
 /// \param Call The call expression to diagnose.
 void Sema::CheckMemaccessArguments(const CallExpr *Call,
-                                   CheckedMemoryFunction CMF,
+                                   unsigned BId,
                                    IdentifierInfo *FnName) {
+  assert(BId !=3D 0);
+
   // It is possible to have a non-standard definition of memset.  Validate
   // we have enough arguments, and if not, abort further checking.
-  unsigned ExpectedNumArgs =3D (CMF =3D=3D CMF_Strndup ? 2 : 3);
+  unsigned ExpectedNumArgs =3D (BId =3D=3D Builtin::BIstrndup ? 2 : 3);
   if (Call->getNumArgs() < ExpectedNumArgs)
     return;
=20
-  unsigned LastArg =3D (CMF =3D=3D CMF_Memset || CMF =3D=3D CMF_Strndup ? =
1 : 2);
-  unsigned LenArg =3D (CMF =3D=3D CMF_Strndup ? 1 : 2);
+  unsigned LastArg =3D (BId =3D=3D Builtin::BImemset ||
+                      BId =3D=3D Builtin::BIstrndup ? 1 : 2);
+  unsigned LenArg =3D (BId =3D=3D Builtin::BIstrndup ? 1 : 2);
   const Expr *LenExpr =3D Call->getArg(LenArg)->IgnoreParenImpCasts();
=20
   // We have special checking when the length is a sizeof expression.
@@ -2227,7 +2767,8 @@
           if (Context.getTypeSize(PointeeTy) =3D=3D Context.getCharWidth())
             ActionIdx =3D 2; // If the pointee's size is sizeof(char),
                            // suggest an explicit length.
-          unsigned DestSrcSelect =3D (CMF =3D=3D CMF_Strndup ? 1 : ArgIdx);
+          unsigned DestSrcSelect =3D
+            (BId =3D=3D Builtin::BIstrndup ? 1 : ArgIdx);
           DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
                               PDiag(diag::warn_sizeof_pointer_expr_memacce=
ss)
                                 << FnName << DestSrcSelect << ActionIdx
@@ -2253,16 +2794,29 @@
       }
=20
       // Always complain about dynamic classes.
-      if (isDynamicClassType(PointeeTy))
+      if (isDynamicClassType(PointeeTy)) {
+
+        unsigned OperationType =3D 0;
+        // "overwritten" if we're warning about the destination for any ca=
ll
+        // but memcmp; otherwise a verb appropriate to the call.
+        if (ArgIdx !=3D 0 || BId =3D=3D Builtin::BImemcmp) {
+          if (BId =3D=3D Builtin::BImemcpy)
+            OperationType =3D 1;
+          else if(BId =3D=3D Builtin::BImemmove)
+            OperationType =3D 2;
+          else if (BId =3D=3D Builtin::BImemcmp)
+            OperationType =3D 3;
+        }
+         =20
         DiagRuntimeBehavior(
           Dest->getExprLoc(), Dest,
           PDiag(diag::warn_dyn_class_memaccess)
-            << (CMF =3D=3D CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << =
PointeeTy
-            // "overwritten" if we're warning about the destination for an=
y call
-            // but memcmp; otherwise a verb appropriate to the call.
-            << (ArgIdx =3D=3D 0 && CMF !=3D CMF_Memcmp ? 0 : (unsigned)CMF)
+            << (BId =3D=3D Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
+            << FnName << PointeeTy
+            << OperationType
             << Call->getCallee()->getSourceRange());
-      else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF !=3D CMF_Memse=
t)
+      } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
+               BId !=3D Builtin::BImemset)
         DiagRuntimeBehavior(
           Dest->getExprLoc(), Dest,
           PDiag(diag::warn_arc_object_memaccess)
@@ -2324,7 +2878,7 @@
   else {
     // Look for 'strlcpy(dst, x, strlen(x))'
     if (const CallExpr *SizeCall =3D dyn_cast<CallExpr>(SizeArg)) {
-      if (SizeCall->isBuiltinCall(Context) =3D=3D Builtin::BIstrlen
+      if (SizeCall->isBuiltinCall() =3D=3D Builtin::BIstrlen
           && SizeCall->getNumArgs() =3D=3D 1)
         CompareWithSrc =3D ignoreLiteralAdditions(SizeCall->getArg(0), Con=
text);
     }
@@ -2366,7 +2920,7 @@
     return;
   }
=20
-  llvm::SmallString<128> sizeString;
+  SmallString<128> sizeString;
   llvm::raw_svector_ostream OS(sizeString);
   OS << "sizeof(";
   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
@@ -2377,6 +2931,108 @@
                                     OS.str());
 }
=20
+/// Check if two expressions refer to the same declaration.
+static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
+  if (const DeclRefExpr *D1 =3D dyn_cast_or_null<DeclRefExpr>(E1))
+    if (const DeclRefExpr *D2 =3D dyn_cast_or_null<DeclRefExpr>(E2))
+      return D1->getDecl() =3D=3D D2->getDecl();
+  return false;
+}
+
+static const Expr *getStrlenExprArg(const Expr *E) {
+  if (const CallExpr *CE =3D dyn_cast<CallExpr>(E)) {
+    const FunctionDecl *FD =3D CE->getDirectCallee();
+    if (!FD || FD->getMemoryFunctionKind() !=3D Builtin::BIstrlen)
+      return 0;
+    return CE->getArg(0)->IgnoreParenCasts();
+  }
+  return 0;
+}
+
+// Warn on anti-patterns as the 'size' argument to strncat.
+// The correct size argument should look like following:
+//   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
+void Sema::CheckStrncatArguments(const CallExpr *CE,
+                                 IdentifierInfo *FnName) {
+  // Don't crash if the user has the wrong number of arguments.
+  if (CE->getNumArgs() < 3)
+    return;
+  const Expr *DstArg =3D CE->getArg(0)->IgnoreParenCasts();
+  const Expr *SrcArg =3D CE->getArg(1)->IgnoreParenCasts();
+  const Expr *LenArg =3D CE->getArg(2)->IgnoreParenCasts();
+
+  // Identify common expressions, which are wrongly used as the size argum=
ent
+  // to strncat and may lead to buffer overflows.
+  unsigned PatternType =3D 0;
+  if (const Expr *SizeOfArg =3D getSizeOfExprArg(LenArg)) {
+    // - sizeof(dst)
+    if (referToTheSameDecl(SizeOfArg, DstArg))
+      PatternType =3D 1;
+    // - sizeof(src)
+    else if (referToTheSameDecl(SizeOfArg, SrcArg))
+      PatternType =3D 2;
+  } else if (const BinaryOperator *BE =3D dyn_cast<BinaryOperator>(LenArg)=
) {
+    if (BE->getOpcode() =3D=3D BO_Sub) {
+      const Expr *L =3D BE->getLHS()->IgnoreParenCasts();
+      const Expr *R =3D BE->getRHS()->IgnoreParenCasts();
+      // - sizeof(dst) - strlen(dst)
+      if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
+          referToTheSameDecl(DstArg, getStrlenExprArg(R)))
+        PatternType =3D 1;
+      // - sizeof(src) - (anything)
+      else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
+        PatternType =3D 2;
+    }
+  }
+
+  if (PatternType =3D=3D 0)
+    return;
+
+  // Generate the diagnostic.
+  SourceLocation SL =3D LenArg->getLocStart();
+  SourceRange SR =3D LenArg->getSourceRange();
+  SourceManager &SM  =3D PP.getSourceManager();
+
+  // If the function is defined as a builtin macro, do not show macro expa=
nsion.
+  if (SM.isMacroArgExpansion(SL)) {
+    SL =3D SM.getSpellingLoc(SL);
+    SR =3D SourceRange(SM.getSpellingLoc(SR.getBegin()),
+                     SM.getSpellingLoc(SR.getEnd()));
+  }
+
+  if (PatternType =3D=3D 1)
+    Diag(SL, diag::warn_strncat_large_size) << SR;
+  else
+    Diag(SL, diag::warn_strncat_src_size) << SR;
+
+  // Output a FIXIT hint if the destination is an array (rather than a
+  // pointer to an array).  This could be enhanced to handle some
+  // pointers if we know the actual size, like if DstArg is 'array+2'
+  // we could say 'sizeof(array)-2'.
+  QualType DstArgTy =3D DstArg->getType();
+
+  // Only handle constant-sized or VLAs, but not flexible members.
+  if (const ConstantArrayType *CAT =3D Context.getAsConstantArrayType(DstA=
rgTy)) {
+    // Only issue the FIXIT for arrays of size > 1.
+    if (CAT->getSize().getSExtValue() <=3D 1)
+      return;
+  } else if (!DstArgTy->isVariableArrayType()) {
+    return;
+  }
+
+  SmallString<128> sizeString;
+  llvm::raw_svector_ostream OS(sizeString);
+  OS << "sizeof(";
+  DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
+  OS << ") - ";
+  OS << "strlen(";
+  DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
+  OS << ") - 1";
+
+  Diag(SL, diag::note_strncat_wrong_size)
+    << FixItHint::CreateReplacement(SR, OS.str());
+}
+
 //=3D=3D=3D--- CHECK: Return Address of Stack Variable -------------------=
-------=3D=3D=3D//
=20
 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
@@ -2394,7 +3050,7 @@
   // Perform checking for returned stack addresses, local blocks,
   // label addresses or references to temporaries.
   if (lhsType->isPointerType() ||
-      (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType()=
)) {
+      (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
     stackE =3D EvalAddr(RetValExp, refVars);
   } else if (lhsType->isReferenceType()) {
     stackE =3D EvalVal(RetValExp, refVars);
@@ -2561,42 +3217,39 @@
   case Stmt::AddrLabelExprClass:
     return E; // address of label.
=20
+  case Stmt::ExprWithCleanupsClass:
+    return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
+
   // For casts, we need to handle conversions from arrays to
   // pointer values, and pointer-to-pointer conversions.
   case Stmt::ImplicitCastExprClass:
   case Stmt::CStyleCastExprClass:
   case Stmt::CXXFunctionalCastExprClass:
-  case Stmt::ObjCBridgedCastExprClass: {
-    Expr* SubExpr =3D cast<CastExpr>(E)->getSubExpr();
-    QualType T =3D SubExpr->getType();
-
-    if (SubExpr->getType()->isPointerType() ||
-        SubExpr->getType()->isBlockPointerType() ||
-        SubExpr->getType()->isObjCQualifiedIdType())
-      return EvalAddr(SubExpr, refVars);
-    else if (T->isArrayType())
-      return EvalVal(SubExpr, refVars);
-    else
-      return 0;
-  }
-
-  // C++ casts.  For dynamic casts, static casts, and const casts, we
-  // are always converting from a pointer-to-pointer, so we just blow
-  // through the cast.  In the case the dynamic cast doesn't fail (and
-  // return NULL), we take the conservative route and report cases
-  // where we return the address of a stack variable.  For Reinterpre
-  // FIXME: The comment about is wrong; we're not always converting
-  // from pointer to pointer. I'm guessing that this code should also
-  // handle references to objects.
+  case Stmt::ObjCBridgedCastExprClass:
   case Stmt::CXXStaticCastExprClass:
   case Stmt::CXXDynamicCastExprClass:
   case Stmt::CXXConstCastExprClass:
   case Stmt::CXXReinterpretCastExprClass: {
-      Expr *S =3D cast<CXXNamedCastExpr>(E)->getSubExpr();
-      if (S->getType()->isPointerType() || S->getType()->isBlockPointerTyp=
e())
-        return EvalAddr(S, refVars);
-      else
-        return NULL;
+    Expr* SubExpr =3D cast<CastExpr>(E)->getSubExpr();
+    switch (cast<CastExpr>(E)->getCastKind()) {
+    case CK_BitCast:
+    case CK_LValueToRValue:
+    case CK_NoOp:
+    case CK_BaseToDerived:
+    case CK_DerivedToBase:
+    case CK_UncheckedDerivedToBase:
+    case CK_Dynamic:
+    case CK_CPointerToObjCPointerCast:
+    case CK_BlockPointerToObjCPointerCast:
+    case CK_AnyPointerToBlockPointerCast:
+      return EvalAddr(SubExpr, refVars);
+
+    case CK_ArrayToPointerDecay:
+      return EvalVal(SubExpr, refVars);
+
+    default:
+      return 0;
+    }
   }
=20
   case Stmt::MaterializeTemporaryExprClass:
@@ -2637,6 +3290,9 @@
     return NULL;
   }
=20
+  case Stmt::ExprWithCleanupsClass:
+    return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
+
   case Stmt::DeclRefExprClass: {
     // When we hit a DeclRefExpr we are looking at code that refers to a
     // variable's name. If it's not a reference variable we check if it has
@@ -2766,12 +3422,12 @@
   // Check for comparisons with builtin types.
   if (EmitWarning)
     if (CallExpr* CL =3D dyn_cast<CallExpr>(LeftExprSansParen))
-      if (CL->isBuiltinCall(Context))
+      if (CL->isBuiltinCall())
         EmitWarning =3D false;
=20
   if (EmitWarning)
     if (CallExpr* CR =3D dyn_cast<CallExpr>(RightExprSansParen))
-      if (CR->isBuiltinCall(Context))
+      if (CR->isBuiltinCall())
         EmitWarning =3D false;
=20
   // Emit the diagnostic.
@@ -2870,7 +3526,8 @@
   }
 };
=20
-IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWid=
th) {
+static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
+                              unsigned MaxWidth) {
   if (value.isSigned() && value.isNegative())
     return IntRange(value.getMinSignedBits(), false);
=20
@@ -2882,8 +3539,8 @@
   return IntRange(value.getActiveBits(), true);
 }
=20
-IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
-                       unsigned MaxWidth) {
+static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
+                              unsigned MaxWidth) {
   if (result.isInt())
     return GetValueRange(C, result.getInt(), MaxWidth);
=20
@@ -2907,7 +3564,7 @@
   // FIXME: The only reason we need to pass the type in here is to get
   // the sign right on this one case.  It would be nice if APValue
   // preserved this.
-  assert(result.isLValue());
+  assert(result.isLValue() || result.isAddrLabelDiff());
   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
 }
=20
@@ -2915,19 +3572,19 @@
 /// range of values it might take.
 ///
 /// \param MaxWidth - the width to which the value will be truncated
-IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
+static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
   E =3D E->IgnoreParens();
=20
   // Try a full evaluation first.
   Expr::EvalResult result;
-  if (E->Evaluate(result, C))
+  if (E->EvaluateAsRValue(result, C))
     return GetValueRange(C, result.Val, E->getType(), MaxWidth);
=20
   // I think we only want to look through implicit casts here; if the
   // user has an explicit widening cast, we should treat the value as
   // being of the new, wider type.
   if (ImplicitCastExpr *CE =3D dyn_cast<ImplicitCastExpr>(E)) {
-    if (CE->getCastKind() =3D=3D CK_NoOp)
+    if (CE->getCastKind() =3D=3D CK_NoOp || CE->getCastKind() =3D=3D CK_LV=
alueToRValue)
       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
=20
     IntRange OutputTypeRange =3D IntRange::forValueOfType(C, CE->getType()=
);
@@ -3133,16 +3790,16 @@
   return IntRange::forValueOfType(C, E->getType());
 }
=20
-IntRange GetExprRange(ASTContext &C, Expr *E) {
+static IntRange GetExprRange(ASTContext &C, Expr *E) {
   return GetExprRange(C, E, C.getIntWidth(E->getType()));
 }
=20
 /// Checks whether the given value, which currently has the given
 /// source semantics, has the same value when coerced through the
 /// target semantics.
-bool IsSameFloatAfterCast(const llvm::APFloat &value,
-                          const llvm::fltSemantics &Src,
-                          const llvm::fltSemantics &Tgt) {
+static bool IsSameFloatAfterCast(const llvm::APFloat &value,
+                                 const llvm::fltSemantics &Src,
+                                 const llvm::fltSemantics &Tgt) {
   llvm::APFloat truncated =3D value;
=20
   bool ignored;
@@ -3157,9 +3814,9 @@
 /// target semantics.
 ///
 /// The value might be a vector of floats (or a complex number).
-bool IsSameFloatAfterCast(const APValue &value,
-                          const llvm::fltSemantics &Src,
-                          const llvm::fltSemantics &Tgt) {
+static bool IsSameFloatAfterCast(const APValue &value,
+                                 const llvm::fltSemantics &Src,
+                                 const llvm::fltSemantics &Tgt) {
   if (value.isFloat())
     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
=20
@@ -3175,7 +3832,7 @@
           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
 }
=20
-void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
+static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC=
);
=20
 static bool IsZero(Sema &S, Expr *E) {
   // Suppress cases where we are comparing against an enum constant.
@@ -3204,7 +3861,7 @@
   return E->getType()->isEnumeralType();
 }
=20
-void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
+static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
   BinaryOperatorKind op =3D E->getOpcode();
   if (E->isValueDependent())
     return;
@@ -3230,7 +3887,7 @@
=20
 /// Analyze the operands of the given comparison.  Implements the
 /// fallback case from AnalyzeComparison.
-void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
+static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
 }
@@ -3238,7 +3895,7 @@
 /// \brief Implements -Wsign-compare.
 ///
 /// \param E the binary operator to check for warnings
-void AnalyzeComparison(Sema &S, BinaryOperator *E) {
+static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
   // The type the comparison is being performed in.
   QualType T =3D E->getLHS()->getType();
   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
@@ -3311,8 +3968,8 @@
 /// Analyzes an attempt to assign the given value to a bitfield.
 ///
 /// Returns true if there was something fishy about the attempt.
-bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
-                               SourceLocation InitLoc) {
+static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *=
Init,
+                                      SourceLocation InitLoc) {
   assert(Bitfield->isBitField());
   if (Bitfield->isInvalidDecl())
     return false;
@@ -3330,31 +3987,30 @@
=20
   Expr *OriginalInit =3D Init->IgnoreParenImpCasts();
=20
-  Expr::EvalResult InitValue;
-  if (!OriginalInit->Evaluate(InitValue, S.Context) ||
-      !InitValue.Val.isInt())
+  llvm::APSInt Value;
+  if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEff=
ects))
     return false;
=20
-  const llvm::APSInt &Value =3D InitValue.Val.getInt();
   unsigned OriginalWidth =3D Value.getBitWidth();
   unsigned FieldWidth =3D Bitfield->getBitWidthValue(S.Context);
=20
   if (OriginalWidth <=3D FieldWidth)
     return false;
=20
+  // Compute the value which the bitfield will contain.
   llvm::APSInt TruncatedValue =3D Value.trunc(FieldWidth);
-
-  // It's fairly common to write values into signed bitfields
-  // that, if sign-extended, would end up becoming a different
-  // value.  We don't want to warn about that.
-  if (Value.isSigned() && Value.isNegative())
-    TruncatedValue =3D TruncatedValue.sext(OriginalWidth);
-  else
-    TruncatedValue =3D TruncatedValue.zext(OriginalWidth);
-
+  TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
+
+  // Check whether the stored value is equal to the original value.
+  TruncatedValue =3D TruncatedValue.extend(OriginalWidth);
   if (Value =3D=3D TruncatedValue)
     return false;
=20
+  // Special-case bitfields of width 1: booleans are naturally 0/1, and
+  // therefore don't strictly fit into a signed bitfield of width 1.
+  if (FieldWidth =3D=3D 1 && Value =3D=3D 1)
+    return false;
+
   std::string PrettyValue =3D Value.toString(10);
   std::string PrettyTrunc =3D TruncatedValue.toString(10);
=20
@@ -3367,7 +4023,7 @@
=20
 /// Analyze the given simple or compound assignment for warning-worthy
 /// operations.
-void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
+static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
   // Just recurse on the LHS.
   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
=20
@@ -3386,16 +4042,25 @@
 }
=20
 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversio=
n.
-void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,=20
-                     SourceLocation CContext, unsigned diag) {
+static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualTyp=
e T,=20
+                            SourceLocation CContext, unsigned diag,
+                            bool pruneControlFlow =3D false) {
+  if (pruneControlFlow) {
+    S.DiagRuntimeBehavior(E->getExprLoc(), E,
+                          S.PDiag(diag)
+                            << SourceType << T << E->getSourceRange()
+                            << SourceRange(CContext));
+    return;
+  }
   S.Diag(E->getExprLoc(), diag)
     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
 }
=20
 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversio=
n.
-void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
-                     unsigned diag) {
-  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
+static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
+                            SourceLocation CContext, unsigned diag,
+                            bool pruneControlFlow =3D false) {
+  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
 }
=20
 /// Diagnose an implicit cast from a literal expression. Does not warn whe=
n the
@@ -3425,11 +4090,6 @@
   return ValueInRange.toString(10);
 }
=20
-static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
-  SourceManager &smgr =3D S.Context.getSourceManager();
-  return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc)=
);
-}
-
 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
                              SourceLocation CC, bool *ICContext =3D 0) {
   if (E->isTypeDependent() || E->isValueDependent()) return;
@@ -3455,13 +4115,43 @@
       // by a check in AnalyzeImplicitConversions().
       return DiagnoseImpCast(S, E, T, CC,
                              diag::warn_impcast_string_literal_to_bool);
+    if (Source->isFunctionType()) {
+      // Warn on function to bool. Checks free functions and static member
+      // functions. Weakly imported functions are excluded from the check,
+      // since it's common to test their value to check whether the linker
+      // found a definition for them.
+      ValueDecl *D =3D 0;
+      if (DeclRefExpr* R =3D dyn_cast<DeclRefExpr>(E)) {
+        D =3D R->getDecl();
+      } else if (MemberExpr *M =3D dyn_cast<MemberExpr>(E)) {
+        D =3D M->getMemberDecl();
+      }
+
+      if (D && !D->isWeak()) {
+        if (FunctionDecl* F =3D dyn_cast<FunctionDecl>(D)) {
+          S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
+            << F << E->getSourceRange() << SourceRange(CC);
+          S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
+            << FixItHint::CreateInsertion(E->getExprLoc(), "&");
+          QualType ReturnType;
+          UnresolvedSet<4> NonTemplateOverloads;
+          S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
+          if (!ReturnType.isNull()=20
+              && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
+            S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
+              << FixItHint::CreateInsertion(
+                 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), =
"()");
+          return;
+        }
+      }
+    }
     return; // Other casts to bool are not checked.
   }
=20
   // Strip vector types.
   if (isa<VectorType>(Source)) {
     if (!isa<VectorType>(Target)) {
-      if (isFromSystemMacro(S, CC))
+      if (S.SourceMgr.isInSystemMacro(CC))
         return;
       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar=
);
     }
@@ -3478,7 +4168,7 @@
   // Strip complex types.
   if (isa<ComplexType>(Source)) {
     if (!isa<ComplexType>(Target)) {
-      if (isFromSystemMacro(S, CC))
+      if (S.SourceMgr.isInSystemMacro(CC))
         return;
=20
       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scala=
r);
@@ -3502,7 +4192,7 @@
         // Don't warn about float constants that are precisely
         // representable in the target type.
         Expr::EvalResult result;
-        if (E->Evaluate(result, S.Context)) {
+        if (E->EvaluateAsRValue(result, S.Context)) {
           // Value might be a float, a float vector, or a float complex.
           if (IsSameFloatAfterCast(result.Val,
                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
@@ -3510,7 +4200,7 @@
             return;
         }
=20
-        if (isFromSystemMacro(S, CC))
+        if (S.SourceMgr.isInSystemMacro(CC))
           return;
=20
         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
@@ -3520,7 +4210,7 @@
=20
     // If the target is integral, always warn.   =20
     if ((TargetBT && TargetBT->isInteger())) {
-      if (isFromSystemMacro(S, CC))
+      if (S.SourceMgr.isInSystemMacro(CC))
         return;
      =20
       Expr *InnerE =3D E->IgnoreParenImpCasts();
@@ -3544,8 +4234,11 @@
=20
   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNu=
ll)
            =3D=3D Expr::NPCK_GNUNull) && Target->isIntegerType()) {
-    S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
-        << E->getSourceRange() << clang::SourceRange(CC);
+    SourceLocation Loc =3D E->getSourceRange().getBegin();
+    if (Loc.isMacroID())
+      Loc =3D S.SourceMgr.getImmediateExpansionRange(Loc).first;
+    S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
+        << T << Loc << clang::SourceRange(CC);
     return;
   }
=20
@@ -3557,24 +4250,27 @@
     // TODO: this should happen for bitfield stores, too.
     llvm::APSInt Value(32);
     if (E->isIntegerConstantExpr(Value, S.Context)) {
-      if (isFromSystemMacro(S, CC))
+      if (S.SourceMgr.isInSystemMacro(CC))
         return;
=20
       std::string PrettySourceValue =3D Value.toString(10);
       std::string PrettyTargetValue =3D PrettyPrintInRange(Value, TargetRa=
nge);
=20
-      S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constan=
t)
-        << PrettySourceValue << PrettyTargetValue
-        << E->getType() << T << E->getSourceRange() << clang::SourceRange(=
CC);
+      S.DiagRuntimeBehavior(E->getExprLoc(), E,
+        S.PDiag(diag::warn_impcast_integer_precision_constant)
+            << PrettySourceValue << PrettyTargetValue
+            << E->getType() << T << E->getSourceRange()
+            << clang::SourceRange(CC));
       return;
     }
=20
     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
-    if (isFromSystemMacro(S, CC))
+    if (S.SourceMgr.isInSystemMacro(CC))
       return;
    =20
-    if (SourceRange.Width =3D=3D 64 && TargetRange.Width =3D=3D 32)
-      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32=
);
+    if (TargetRange.Width =3D=3D 32 && S.Context.getIntWidth(E->getType())=
 =3D=3D 64)
+      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
+                             /* pruneControlFlow */ true);
     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precisi=
on);
   }
=20
@@ -3582,7 +4278,7 @@
       (!TargetRange.NonNegative && SourceRange.NonNegative &&
        SourceRange.Width =3D=3D TargetRange.Width)) {
        =20
-    if (isFromSystemMacro(S, CC))
+    if (S.SourceMgr.isInSystemMacro(CC))
       return;
=20
     unsigned DiagID =3D diag::warn_impcast_integer_sign;
@@ -3604,7 +4300,7 @@
   // In C, we pretend that the type of an EnumConstantDecl is its enumerat=
ion
   // type, to give us better diagnostics.
   QualType SourceType =3D E->getType();
-  if (!S.getLangOptions().CPlusPlus) {
+  if (!S.getLangOpts().CPlusPlus) {
     if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E))
       if (EnumConstantDecl *ECD =3D dyn_cast<EnumConstantDecl>(DRE->getDec=
l())) {
         EnumDecl *Enum =3D cast<EnumDecl>(ECD->getDeclContext());
@@ -3620,7 +4316,7 @@
           (TargetEnum->getDecl()->getIdentifier() ||
            TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
           SourceEnum !=3D TargetEnum) {
-        if (isFromSystemMacro(S, CC))
+        if (S.SourceMgr.isInSystemMacro(CC))
           return;
=20
         return DiagnoseImpCast(S, E, SourceType, T, CC,=20
@@ -3712,8 +4408,8 @@
     if (BO->isComparisonOp())
       return AnalyzeComparison(S, BO);
=20
-    // And with assignments and compound assignments.
-    if (BO->isAssignmentOp())
+    // And with simple assignments.
+    if (BO->getOpcode() =3D=3D BO_Assign)
       return AnalyzeAssignment(S, BO);
   }
=20
@@ -3731,7 +4427,10 @@
   BinaryOperator *BO =3D dyn_cast<BinaryOperator>(E);
   bool IsLogicalOperator =3D BO && BO->isLogicalOp();
   for (Stmt::child_range I =3D E->children(); I; ++I) {
-    Expr *ChildExpr =3D cast<Expr>(*I);
+    Expr *ChildExpr =3D dyn_cast_or_null<Expr>(*I);
+    if (!ChildExpr)
+      continue;
+
     if (IsLogicalOperator &&
         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
       // Ignore checking string literals that are in logical operators.
@@ -3801,7 +4500,7 @@
     if (CheckParameterNames &&
         Param->getIdentifier() =3D=3D 0 &&
         !Param->isImplicit() &&
-        !getLangOptions().CPlusPlus)
+        !getLangOpts().CPlusPlus)
       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
=20
     // C99 6.7.5.3p12:
@@ -3897,8 +4596,11 @@
     return false;
=20
   const RecordDecl *RD =3D dyn_cast<RecordDecl>(FD->getDeclContext());
-  if (!RD || !RD->isStruct())
-    return false;
+  if (!RD) return false;
+  if (RD->isUnion()) return false;
+  if (const CXXRecordDecl *CRD =3D dyn_cast<CXXRecordDecl>(RD)) {
+    if (!CRD->isStandardLayout()) return false;
+  }
=20
   // See if this is the last field decl in the record.
   const Decl *D =3D FD;
@@ -3909,21 +4611,24 @@
 }
=20
 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
-                            bool isSubscript, bool AllowOnePastEnd) {
-  const Type* EffectiveType =3D getElementType(BaseExpr);
+                            const ArraySubscriptExpr *ASE,
+                            bool AllowOnePastEnd, bool IndexNegated) {
+  IndexExpr =3D IndexExpr->IgnoreParenImpCasts();
+  if (IndexExpr->isValueDependent())
+    return;
+
+  const Type *EffectiveType =3D getElementType(BaseExpr);
   BaseExpr =3D BaseExpr->IgnoreParenCasts();
-  IndexExpr =3D IndexExpr->IgnoreParenCasts();
-
   const ConstantArrayType *ArrayTy =3D
     Context.getAsConstantArrayType(BaseExpr->getType());
   if (!ArrayTy)
     return;
=20
-  if (IndexExpr->isValueDependent())
+  llvm::APSInt index;
+  if (!IndexExpr->EvaluateAsInt(index, Context))
     return;
-  llvm::APSInt index;
-  if (!IndexExpr->isIntegerConstantExpr(index, Context))
-    return;
+  if (IndexNegated)
+    index =3D -index;
=20
   const NamedDecl *ND =3D NULL;
   if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(BaseExpr))
@@ -3954,15 +4659,15 @@
     }
=20
     if (size.getBitWidth() > index.getBitWidth())
-      index =3D index.sext(size.getBitWidth());
+      index =3D index.zext(size.getBitWidth());
     else if (size.getBitWidth() < index.getBitWidth())
-      size =3D size.sext(index.getBitWidth());
+      size =3D size.zext(index.getBitWidth());
=20
     // For array subscripting the index must be less than size, but for po=
inter
     // arithmetic also allow the index (offset) to be equal to size since
     // computing the next address after the end of the array is legal and
     // commonly done e.g. in C++ iterators and range-based for loops.
-    if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
+    if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
       return;
=20
     // Also don't warn for arrays of size 1 which are members of some
@@ -3971,8 +4676,22 @@
     if (IsTailPaddedMemberArray(*this, size, ND))
       return;
=20
+    // Suppress the warning if the subscript expression (as identified by =
the
+    // ']' location) and the index expression are both from macro expansio=
ns
+    // within a system header.
+    if (ASE) {
+      SourceLocation RBracketLoc =3D SourceMgr.getSpellingLoc(
+          ASE->getRBracketLoc());
+      if (SourceMgr.isInSystemHeader(RBracketLoc)) {
+        SourceLocation IndexLoc =3D SourceMgr.getSpellingLoc(
+            IndexExpr->getLocStart());
+        if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
+          return;
+      }
+    }
+
     unsigned DiagID =3D diag::warn_ptr_arith_exceeds_bounds;
-    if (isSubscript)
+    if (ASE)
       DiagID =3D diag::warn_array_index_exceeds_bounds;
=20
     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
@@ -3982,7 +4701,7 @@
                           << IndexExpr->getSourceRange());
   } else {
     unsigned DiagID =3D diag::warn_array_index_precedes_bounds;
-    if (!isSubscript) {
+    if (!ASE) {
       DiagID =3D diag::warn_ptr_arith_precedes_bounds;
       if (index.isNegative()) index =3D -index;
     }
@@ -3992,6 +4711,17 @@
                           << IndexExpr->getSourceRange());
   }
=20
+  if (!ND) {
+    // Try harder to find a NamedDecl to point at in the note.
+    while (const ArraySubscriptExpr *ASE =3D
+           dyn_cast<ArraySubscriptExpr>(BaseExpr))
+      BaseExpr =3D ASE->getBase()->IgnoreParenCasts();
+    if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(BaseExpr))
+      ND =3D dyn_cast<NamedDecl>(DRE->getDecl());
+    if (const MemberExpr *ME =3D dyn_cast<MemberExpr>(BaseExpr))
+      ND =3D dyn_cast<NamedDecl>(ME->getMemberDecl());
+  }
+
   if (ND)
     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
                         PDiag(diag::note_array_index_out_of_bounds)
@@ -4005,7 +4735,7 @@
     switch (expr->getStmtClass()) {
       case Stmt::ArraySubscriptExprClass: {
         const ArraySubscriptExpr *ASE =3D cast<ArraySubscriptExpr>(expr);
-        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
+        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
                          AllowOnePastEnd > 0);
         return;
       }
@@ -4070,7 +4800,7 @@
   return true;
 }
=20
-static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
+static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner=
) {
   while (true) {
     e =3D e->IgnoreParens();
     if (CastExpr *cast =3D dyn_cast<CastExpr>(e)) {
@@ -4082,22 +4812,6 @@
         e =3D cast->getSubExpr();
         continue;
=20
-      case CK_GetObjCProperty: {
-        // Bail out if this isn't a strong explicit property.
-        const ObjCPropertyRefExpr *pre =3D cast->getSubExpr()->getObjCProp=
erty();
-        if (pre->isImplicitProperty()) return false;
-        ObjCPropertyDecl *property =3D pre->getExplicitProperty();
-        if (!property->isRetaining() &&
-            !(property->getPropertyIvarDecl() &&
-              property->getPropertyIvarDecl()->getType()
-                .getObjCLifetime() =3D=3D Qualifiers::OCL_Strong))
-          return false;
-
-        owner.Indirect =3D true;
-        e =3D const_cast<Expr*>(pre->getBase());
-        continue;
-      }
-       =20
       default:
         return false;
       }
@@ -4109,7 +4823,7 @@
         return false;
=20
       // Try to find a retain cycle in the base.
-      if (!findRetainCycleOwner(ref->getBase(), owner))
+      if (!findRetainCycleOwner(S, ref->getBase(), owner))
         return false;
=20
       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
@@ -4123,12 +4837,6 @@
       return considerVariable(var, ref, owner);
     }
=20
-    if (BlockDeclRefExpr *ref =3D dyn_cast<BlockDeclRefExpr>(e)) {
-      owner.Variable =3D ref->getDecl();
-      owner.setLocsFrom(ref);
-      return true;
-    }
-
     if (MemberExpr *member =3D dyn_cast<MemberExpr>(e)) {
       if (member->isArrow()) return false;
=20
@@ -4137,6 +4845,34 @@
       continue;
     }
=20
+    if (PseudoObjectExpr *pseudo =3D dyn_cast<PseudoObjectExpr>(e)) {
+      // Only pay attention to pseudo-objects on property references.
+      ObjCPropertyRefExpr *pre
+        =3D dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
+                                              ->IgnoreParens());
+      if (!pre) return false;
+      if (pre->isImplicitProperty()) return false;
+      ObjCPropertyDecl *property =3D pre->getExplicitProperty();
+      if (!property->isRetaining() &&
+          !(property->getPropertyIvarDecl() &&
+            property->getPropertyIvarDecl()->getType()
+              .getObjCLifetime() =3D=3D Qualifiers::OCL_Strong))
+          return false;
+
+      owner.Indirect =3D true;
+      if (pre->isSuperReceiver()) {
+        owner.Variable =3D S.getCurMethodDecl()->getSelfDecl();
+        if (!owner.Variable)
+          return false;
+        owner.Loc =3D pre->getLocation();
+        owner.Range =3D pre->getSourceRange();
+        return true;
+      }
+      e =3D const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
+                              ->getSourceExpr());
+      continue;
+    }
+
     // Array ivars?
=20
     return false;
@@ -4157,11 +4893,6 @@
         Capturer =3D ref;
     }
=20
-    void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
-      if (ref->getDecl() =3D=3D Variable && !Capturer)
-        Capturer =3D ref;
-    }
-
     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
       if (Capturer) return;
       Visit(ref->getBase());
@@ -4210,8 +4941,14 @@
=20
   StringRef str =3D sel.getNameForSlot(0);
   while (!str.empty() && str.front() =3D=3D '_') str =3D str.substr(1);
-  if (str.startswith("set") || str.startswith("add"))
+  if (str.startswith("set"))
     str =3D str.substr(3);
+  else if (str.startswith("add")) {
+    // Specially whitelist 'addOperationWithBlock:'.
+    if (sel.getNumArgs() =3D=3D 1 && str.startswith("addOperationWithBlock=
"))
+      return false;
+    str =3D str.substr(3);
+  }
   else
     return false;
=20
@@ -4228,7 +4965,7 @@
   // Try to find a variable that the receiver is strongly owned by.
   RetainCycleOwner owner;
   if (msg->getReceiverKind() =3D=3D ObjCMessageExpr::Instance) {
-    if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
+    if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
       return;
   } else {
     assert(msg->getReceiverKind() =3D=3D ObjCMessageExpr::SuperInstance);
@@ -4246,7 +4983,7 @@
 /// Check a property assign to see if it's likely to cause a retain cycle.
 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
   RetainCycleOwner owner;
-  if (!findRetainCycleOwner(receiver, owner))
+  if (!findRetainCycleOwner(*this, receiver, owner))
     return;
=20
   if (Expr *capturer =3D findCapturingExpr(*this, argument, owner))
@@ -4273,7 +5010,19 @@
=20
 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
                               Expr *LHS, Expr *RHS) {
-  QualType LHSType =3D LHS->getType();
+  QualType LHSType;
+  // PropertyRef on LHS type need be directly obtained from
+  // its declaration as it has a PsuedoType.
+  ObjCPropertyRefExpr *PRE
+    =3D dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
+  if (PRE && !PRE->isImplicitProperty()) {
+    const ObjCPropertyDecl *PD =3D PRE->getExplicitProperty();
+    if (PD)
+      LHSType =3D PD->getType();
+  }
+ =20
+  if (LHSType.isNull())
+    LHSType =3D LHS->getType();
   if (checkUnsafeAssigns(Loc, LHSType, RHS))
     return;
   Qualifiers::ObjCLifetime LT =3D LHSType.getObjCLifetime();
@@ -4281,7 +5030,7 @@
   if (LT !=3D Qualifiers::OCL_None)
     return;
  =20
-  if (ObjCPropertyRefExpr *PRE =3D dyn_cast<ObjCPropertyRefExpr>(LHS)) {
+  if (PRE) {
     if (PRE->isImplicitProperty())
       return;
     const ObjCPropertyDecl *PD =3D PRE->getExplicitProperty();
@@ -4289,7 +5038,15 @@
       return;
    =20
     unsigned Attributes =3D PD->getPropertyAttributes();
-    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
+    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
+      // when 'assign' attribute was not explicitly specified
+      // by user, ignore it and rely on property type itself
+      // for lifetime info.
+      unsigned AsWrittenAttr =3D PD->getPropertyAttributesAsWritten();
+      if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
+          LHSType->isObjCRetainableType())
+        return;
+       =20
       while (ImplicitCastExpr *cast =3D dyn_cast<ImplicitCastExpr>(RHS)) {
         if (cast->getCastKind() =3D=3D CK_ARCConsumeObject) {
           Diag(Loc, diag::warn_arc_retained_property_assign)
@@ -4298,5 +5055,132 @@
         }
         RHS =3D cast->getSubExpr();
       }
+    }
   }
 }
+
+//=3D=3D=3D--- CHECK: Empty statement body (-Wempty-body) ----------------=
-----=3D=3D=3D//
+
+namespace {
+bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
+                                 SourceLocation StmtLoc,
+                                 const NullStmt *Body) {
+  // Do not warn if the body is a macro that expands to nothing, e.g:
+  //
+  // #define CALL(x)
+  // if (condition)
+  //   CALL(0);
+  //
+  if (Body->hasLeadingEmptyMacro())
+    return false;
+
+  // Get line numbers of statement and body.
+  bool StmtLineInvalid;
+  unsigned StmtLine =3D SourceMgr.getSpellingLineNumber(StmtLoc,
+                                                      &StmtLineInvalid);
+  if (StmtLineInvalid)
+    return false;
+
+  bool BodyLineInvalid;
+  unsigned BodyLine =3D SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
+                                                      &BodyLineInvalid);
+  if (BodyLineInvalid)
+    return false;
+
+  // Warn if null statement and body are on the same line.
+  if (StmtLine !=3D BodyLine)
+    return false;
+
+  return true;
+}
+} // Unnamed namespace
+
+void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
+                                 const Stmt *Body,
+                                 unsigned DiagID) {
+  // Since this is a syntactic check, don't emit diagnostic for template
+  // instantiations, this just adds noise.
+  if (CurrentInstantiationScope)
+    return;
+
+  // The body should be a null statement.
+  const NullStmt *NBody =3D dyn_cast<NullStmt>(Body);
+  if (!NBody)
+    return;
+
+  // Do the usual checks.
+  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
+    return;
+
+  Diag(NBody->getSemiLoc(), DiagID);
+  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
+}
+
+void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
+                                 const Stmt *PossibleBody) {
+  assert(!CurrentInstantiationScope); // Ensured by caller
+
+  SourceLocation StmtLoc;
+  const Stmt *Body;
+  unsigned DiagID;
+  if (const ForStmt *FS =3D dyn_cast<ForStmt>(S)) {
+    StmtLoc =3D FS->getRParenLoc();
+    Body =3D FS->getBody();
+    DiagID =3D diag::warn_empty_for_body;
+  } else if (const WhileStmt *WS =3D dyn_cast<WhileStmt>(S)) {
+    StmtLoc =3D WS->getCond()->getSourceRange().getEnd();
+    Body =3D WS->getBody();
+    DiagID =3D diag::warn_empty_while_body;
+  } else
+    return; // Neither `for' nor `while'.
+
+  // The body should be a null statement.
+  const NullStmt *NBody =3D dyn_cast<NullStmt>(Body);
+  if (!NBody)
+    return;
+
+  // Skip expensive checks if diagnostic is disabled.
+  if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) =3D=3D
+          DiagnosticsEngine::Ignored)
+    return;
+
+  // Do the usual checks.
+  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
+    return;
+
+  // `for(...);' and `while(...);' are popular idioms, so in order to keep
+  // noise level low, emit diagnostics only if for/while is followed by a
+  // CompoundStmt, e.g.:
+  //    for (int i =3D 0; i < n; i++);
+  //    {
+  //      a(i);
+  //    }
+  // or if for/while is followed by a statement with more indentation
+  // than for/while itself:
+  //    for (int i =3D 0; i < n; i++);
+  //      a(i);
+  bool ProbableTypo =3D isa<CompoundStmt>(PossibleBody);
+  if (!ProbableTypo) {
+    bool BodyColInvalid;
+    unsigned BodyCol =3D SourceMgr.getPresumedColumnNumber(
+                             PossibleBody->getLocStart(),
+                             &BodyColInvalid);
+    if (BodyColInvalid)
+      return;
+
+    bool StmtColInvalid;
+    unsigned StmtCol =3D SourceMgr.getPresumedColumnNumber(
+                             S->getLocStart(),
+                             &StmtColInvalid);
+    if (StmtColInvalid)
+      return;
+
+    if (BodyCol > StmtCol)
+      ProbableTypo =3D true;
+  }
+
+  if (ProbableTypo) {
+    Diag(NBody->getSemiLoc(), DiagID);
+    Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
+  }
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaCodeComplete.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -20,10 +20,13 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
+#include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/ADT/Twine.h"
@@ -120,6 +123,8 @@
=20
     /// \brief The allocator used to allocate new code-completion strings.
     CodeCompletionAllocator &Allocator;
+
+    CodeCompletionTUInfo &CCTUInfo;
    =20
     /// \brief If non-NULL, a filter function used to remove any code-comp=
letion
     /// results that are not desirable.
@@ -163,9 +168,11 @@
    =20
   public:
     explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocat=
or,
+                           CodeCompletionTUInfo &CCTUInfo,
                            const CodeCompletionContext &CompletionContext,
                            LookupFilter Filter =3D 0)
-      : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter),=20
+      : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
+        Filter(Filter),=20
         AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),=20
         CompletionContext(CompletionContext),
         ObjCImplementation(0)=20
@@ -248,6 +255,8 @@
    =20
     /// \brief Retrieve the allocator used to allocate code completion str=
ings.
     CodeCompletionAllocator &getAllocator() const { return Allocator; }
+
+    CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInf=
o; }
    =20
     /// \brief Determine whether the given declaration is at all interesti=
ng
     /// as a code-completion result.
@@ -271,9 +280,9 @@
     /// of the shadow maps), or replace an existing result (for, e.g., a=20
     /// redeclaration).
     ///
-    /// \param CurContext the result to add (if it is unique).
+    /// \param R the result to add (if it is unique).
     ///
-    /// \param R the context in which this result will be named.
+    /// \param CurContext the context in which this result will be named.
     void MaybeAddResult(Result R, DeclContext *CurContext =3D 0);
    =20
     /// \brief Add a new result to this result set, where we already know
@@ -322,6 +331,7 @@
     bool IsMember(NamedDecl *ND) const;
     bool IsObjCIvar(NamedDecl *ND) const;
     bool IsObjCMessageReceiver(NamedDecl *ND) const;
+    bool IsObjCMessageReceiverOrLambdaCapture(NamedDecl *ND) const;
     bool IsObjCCollection(NamedDecl *ND) const;
     bool IsImpossibleToSatisfy(NamedDecl *ND) const;
     //@}   =20
@@ -510,14 +520,6 @@
         return false;
     }
   }
-  =20
-  // Skip out-of-line declarations and definitions.
-  // NOTE: Unless it's an Objective-C property, method, or ivar, where
-  // the contexts can be messy.
-  if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
-      !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
-        isa<ObjCMethodDecl>(ND)))
-    return false;
=20
   if (Filter =3D=3D &ResultBuilder::IsNestedNameSpecifier ||
       ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
@@ -529,7 +531,7 @@
   // Filter out any unwanted results.
   if (Filter && !(this->*Filter)(ND)) {
     // Check whether it is interesting as a nested-name-specifier.
-    if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&=20
+    if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&=20
         IsNestedNameSpecifier(ND) &&
         (Filter !=3D &ResultBuilder::IsMember ||
          (isa<CXXRecordDecl>(ND) &&=20
@@ -549,7 +551,7 @@
   // In C, there is no way to refer to a hidden name.
   // FIXME: This isn't true; we can find a tag name hidden by an ordinary
   // name if we introduce the tag type.
-  if (!SemaRef.getLangOptions().CPlusPlus)
+  if (!SemaRef.getLangOpts().CPlusPlus)
     return true;
  =20
   DeclContext *HiddenCtx =3D R.Declaration->getDeclContext()->getRedeclCon=
text();
@@ -596,8 +598,7 @@
       default:
         return STC_Arithmetic;
     }
-    return STC_Other;
-   =20
+
   case Type::Complex:
     return STC_Arithmetic;
    =20
@@ -729,7 +730,7 @@
 }
=20
 void ResultBuilder::MaybeAddConstructorResults(Result R) {
-  if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
+  if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
       !CompletionContext.wantConstructorResults())
     return;
  =20
@@ -901,7 +902,7 @@
=20
   if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
     return;
-     =20
+
   // Make sure that any given declaration only shows up in the result set =
once.
   if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
     return;
@@ -985,9 +986,9 @@
   ND =3D cast<NamedDecl>(ND->getUnderlyingDecl());
=20
   unsigned IDNS =3D Decl::IDNS_Ordinary;
-  if (SemaRef.getLangOptions().CPlusPlus)
+  if (SemaRef.getLangOpts().CPlusPlus)
     IDNS |=3D Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
-  else if (SemaRef.getLangOptions().ObjC1) {
+  else if (SemaRef.getLangOpts().ObjC1) {
     if (isa<ObjCIvarDecl>(ND))
       return true;
   }
@@ -1003,9 +1004,9 @@
     return false;
  =20
   unsigned IDNS =3D Decl::IDNS_Ordinary;
-  if (SemaRef.getLangOptions().CPlusPlus)
+  if (SemaRef.getLangOpts().CPlusPlus)
     IDNS |=3D Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
-  else if (SemaRef.getLangOptions().ObjC1) {
+  else if (SemaRef.getLangOpts().ObjC1) {
     if (isa<ObjCIvarDecl>(ND))
       return true;
   }
@@ -1030,7 +1031,7 @@
   ND =3D cast<NamedDecl>(ND->getUnderlyingDecl());
=20
   unsigned IDNS =3D Decl::IDNS_Ordinary;
-  if (SemaRef.getLangOptions().CPlusPlus)
+  if (SemaRef.getLangOpts().CPlusPlus)
     IDNS |=3D Decl::IDNS_Tag | Decl::IDNS_Namespace;
  =20
   return (ND->getIdentifierNamespace() & IDNS) &&=20
@@ -1132,7 +1133,7 @@
     break;
   }
  =20
-  if (!C.getLangOptions().CPlusPlus)
+  if (!C.getLangOpts().CPlusPlus)
     return false;
=20
   // FIXME: We could perform more analysis here to determine whether a=20
@@ -1150,9 +1151,20 @@
   return isObjCReceiverType(SemaRef.Context, T);
 }
=20
+bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(NamedDecl *ND) co=
nst {
+  if (IsObjCMessageReceiver(ND))
+    return true;
+ =20
+  VarDecl *Var =3D dyn_cast<VarDecl>(ND);
+  if (!Var)
+    return false;
+ =20
+  return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
+}
+
 bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
-  if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
-      (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
+  if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
+      (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
     return false;
  =20
   QualType T =3D getDeclUsageType(SemaRef.Context, ND);
@@ -1162,7 +1174,7 @@
   T =3D SemaRef.Context.getBaseElementType(T);
   return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
          T->isObjCIdType() ||=20
-         (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
+         (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
 }
=20
 bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
@@ -1189,11 +1201,9 @@
     virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *=
Ctx,
                            bool InBaseClass) {
       bool Accessible =3D true;
-      if (Ctx) {
-        if (CXXRecordDecl *Class =3D dyn_cast<CXXRecordDecl>(Ctx))
-          Accessible =3D Results.getSema().IsSimplyAccessible(ND, Class);
-        // FIXME: ObjC access checks are missing.
-      }
+      if (Ctx)
+        Accessible =3D Results.getSema().IsSimplyAccessible(ND, Ctx);
+     =20
       ResultBuilder::Result Result(ND, 0, false, Accessible);
       Results.AddResult(Result, CurContext, Hiding, InBaseClass);
     }
@@ -1227,7 +1237,8 @@
     Results.AddResult(Result("restrict", CCP_Type));
   }
  =20
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
   if (LangOpts.CPlusPlus) {
     // C++-specific
     Results.AddResult(Result("bool", CCP_Type +=20
@@ -1337,7 +1348,8 @@
 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
=20
 static void AddTypedefResult(ResultBuilder &Results) {
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
   Builder.AddTypedTextChunk("typedef");
   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
   Builder.AddPlaceholderChunk("type");
@@ -1372,8 +1384,72 @@
   case Sema::PCC_ForInit:
     return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
   }
- =20
-  return false;
+
+  llvm_unreachable("Invalid ParserCompletionContext!");
+}
+
+static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Contex=
t,
+                                                  const Preprocessor &PP) {
+  PrintingPolicy Policy =3D Sema::getPrintingPolicy(Context, PP);
+  Policy.AnonymousTagLocations =3D false;
+  Policy.SuppressStrongLifetime =3D true;
+  Policy.SuppressUnwrittenScope =3D true;
+  return Policy;
+}
+
+/// \brief Retrieve a printing policy suitable for code completion.
+static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
+  return getCompletionPrintingPolicy(S.Context, S.PP);
+}
+
+/// \brief Retrieve the string representation of the given type as a string
+/// that has the appropriate lifetime for code completion.
+///
+/// This routine provides a fast path where we provide constant strings for
+/// common type names.
+static const char *GetCompletionTypeString(QualType T,
+                                           ASTContext &Context,
+                                           const PrintingPolicy &Policy,
+                                           CodeCompletionAllocator &Alloca=
tor) {
+  if (!T.getLocalQualifiers()) {
+    // Built-in type names are constant strings.
+    if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(T))
+      return BT->getName(Policy);
+   =20
+    // Anonymous tag types are constant strings.
+    if (const TagType *TagT =3D dyn_cast<TagType>(T))
+      if (TagDecl *Tag =3D TagT->getDecl())
+        if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
+          switch (Tag->getTagKind()) {
+          case TTK_Struct: return "struct <anonymous>";
+          case TTK_Class:  return "class <anonymous>";           =20
+          case TTK_Union:  return "union <anonymous>";
+          case TTK_Enum:   return "enum <anonymous>";
+          }
+        }
+  }
+ =20
+  // Slow path: format the type as a string.
+  std::string Result;
+  T.getAsStringInternal(Result, Policy);
+  return Allocator.CopyString(Result);
+}
+
+/// \brief Add a completion for "this", if we're in a member function.
+static void addThisCompletion(Sema &S, ResultBuilder &Results) {
+  QualType ThisTy =3D S.getCurrentThisType();
+  if (ThisTy.isNull())
+    return;
+ =20
+  CodeCompletionAllocator &Allocator =3D Results.getAllocator();
+  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo=
());
+  PrintingPolicy Policy =3D getCompletionPrintingPolicy(S);
+  Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,=20
+                                                     S.Context,=20
+                                                     Policy,
+                                                     Allocator));
+  Builder.AddTypedTextChunk("this");
+  Results.AddResult(CodeCompletionResult(Builder.TakeString()));          =
 =20
 }
=20
 /// \brief Add language constructs that show up for "ordinary" names.
@@ -1381,12 +1457,14 @@
                                    Scope *S,
                                    Sema &SemaRef,
                                    ResultBuilder &Results) {
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionAllocator &Allocator =3D Results.getAllocator();
+  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo=
());
+  PrintingPolicy Policy =3D getCompletionPrintingPolicy(SemaRef);
  =20
   typedef CodeCompletionResult Result;
   switch (CCC) {
   case Sema::PCC_Namespace:
-    if (SemaRef.getLangOptions().CPlusPlus) {
+    if (SemaRef.getLangOpts().CPlusPlus) {
       if (Results.includeCodePatterns()) {
         // namespace <identifier> { declarations }
         Builder.AddTypedTextChunk("namespace");
@@ -1431,14 +1509,14 @@
       }
     }
      =20
-    if (SemaRef.getLangOptions().ObjC1)
+    if (SemaRef.getLangOpts().ObjC1)
       AddObjCTopLevelResults(Results, true);
      =20
     AddTypedefResult(Results);
     // Fall through
=20
   case Sema::PCC_Class:
-    if (SemaRef.getLangOptions().CPlusPlus) {
+    if (SemaRef.getLangOpts().CPlusPlus) {
       // Using declaration
       Builder.AddTypedTextChunk("using");
       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
@@ -1464,17 +1542,20 @@
=20
         // public:
         Builder.AddTypedTextChunk("public");
-        Builder.AddChunk(CodeCompletionString::CK_Colon);
+        if (Results.includeCodePatterns())
+          Builder.AddChunk(CodeCompletionString::CK_Colon);
         Results.AddResult(Result(Builder.TakeString()));
=20
         // protected:
         Builder.AddTypedTextChunk("protected");
-        Builder.AddChunk(CodeCompletionString::CK_Colon);
+        if (Results.includeCodePatterns())
+          Builder.AddChunk(CodeCompletionString::CK_Colon);
         Results.AddResult(Result(Builder.TakeString()));
=20
         // private:
         Builder.AddTypedTextChunk("private");
-        Builder.AddChunk(CodeCompletionString::CK_Colon);
+        if (Results.includeCodePatterns())
+          Builder.AddChunk(CodeCompletionString::CK_Colon);
         Results.AddResult(Result(Builder.TakeString()));
       }
     }
@@ -1482,7 +1563,7 @@
=20
   case Sema::PCC_Template:
   case Sema::PCC_MemberTemplate:
-    if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns(=
)) {
+    if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
       // template < parameters >
       Builder.AddTypedTextChunk("template");
       Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
@@ -1491,32 +1572,32 @@
       Results.AddResult(Result(Builder.TakeString()));
     }
=20
-    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
-    AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
+    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
+    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
     break;
=20
   case Sema::PCC_ObjCInterface:
-    AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
-    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
-    AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
+    AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
+    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
+    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
     break;
      =20
   case Sema::PCC_ObjCImplementation:
-    AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
-    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
-    AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
+    AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
+    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
+    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
     break;
      =20
   case Sema::PCC_ObjCInstanceVariableList:
-    AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
+    AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
     break;
      =20
   case Sema::PCC_RecoveryInFunction:
   case Sema::PCC_Statement: {
     AddTypedefResult(Results);
=20
-    if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns(=
) &&
-        SemaRef.getLangOptions().CXXExceptions) {
+    if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
+        SemaRef.getLangOpts().CXXExceptions) {
       Builder.AddTypedTextChunk("try");
       Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
       Builder.AddPlaceholderChunk("statements");
@@ -1532,14 +1613,14 @@
       Builder.AddChunk(CodeCompletionString::CK_RightBrace);
       Results.AddResult(Result(Builder.TakeString()));
     }
-    if (SemaRef.getLangOptions().ObjC1)
+    if (SemaRef.getLangOpts().ObjC1)
       AddObjCStatementResults(Results, true);
    =20
     if (Results.includeCodePatterns()) {
       // if (condition) { statements }
       Builder.AddTypedTextChunk("if");
       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
-      if (SemaRef.getLangOptions().CPlusPlus)
+      if (SemaRef.getLangOpts().CPlusPlus)
         Builder.AddPlaceholderChunk("condition");
       else
         Builder.AddPlaceholderChunk("expression");
@@ -1553,7 +1634,7 @@
       // switch (condition) { }
       Builder.AddTypedTextChunk("switch");
       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
-      if (SemaRef.getLangOptions().CPlusPlus)
+      if (SemaRef.getLangOpts().CPlusPlus)
         Builder.AddPlaceholderChunk("condition");
       else
         Builder.AddPlaceholderChunk("expression");
@@ -1583,7 +1664,7 @@
       /// while (condition) { statements }
       Builder.AddTypedTextChunk("while");
       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
-      if (SemaRef.getLangOptions().CPlusPlus)
+      if (SemaRef.getLangOpts().CPlusPlus)
         Builder.AddPlaceholderChunk("condition");
       else
         Builder.AddPlaceholderChunk("expression");
@@ -1609,7 +1690,7 @@
       // for ( for-init-statement ; condition ; expression ) { statements }
       Builder.AddTypedTextChunk("for");
       Builder.AddChunk(CodeCompletionString::CK_LeftParen);
-      if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C=
99)
+      if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
         Builder.AddPlaceholderChunk("init-statement");
       else
         Builder.AddPlaceholderChunk("init-expression");
@@ -1674,11 +1755,11 @@
   // Fall through (for statement expressions).
   case Sema::PCC_ForInit:
   case Sema::PCC_Condition:
-    AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
+    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
     // Fall through: conditions and statements can have expressions.
=20
   case Sema::PCC_ParenthesizedExpression:
-    if (SemaRef.getLangOptions().ObjCAutoRefCount &&
+    if (SemaRef.getLangOpts().ObjCAutoRefCount &&
         CCC =3D=3D Sema::PCC_ParenthesizedExpression) {
       // (__bridge <type>)<expression>
       Builder.AddTypedTextChunk("__bridge");
@@ -1707,17 +1788,21 @@
     // Fall through
=20
   case Sema::PCC_Expression: {
-    if (SemaRef.getLangOptions().CPlusPlus) {
+    if (SemaRef.getLangOpts().CPlusPlus) {
       // 'this', if we're in a non-static member function.
-      if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(SemaRef.CurCon=
text))
-        if (!Method->isStatic())
-          Results.AddResult(Result("this"));
+      addThisCompletion(SemaRef, Results);
      =20
-      // true, false
-      Results.AddResult(Result("true"));
-      Results.AddResult(Result("false"));
-
-      if (SemaRef.getLangOptions().RTTI) {
+      // true
+      Builder.AddResultTypeChunk("bool");
+      Builder.AddTypedTextChunk("true");
+      Results.AddResult(Result(Builder.TakeString()));
+     =20
+      // false
+      Builder.AddResultTypeChunk("bool");
+      Builder.AddTypedTextChunk("false");
+      Results.AddResult(Result(Builder.TakeString()));
+
+      if (SemaRef.getLangOpts().RTTI) {
         // dynamic_cast < type-id > ( expression )
         Builder.AddTypedTextChunk("dynamic_cast");
         Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
@@ -1759,8 +1844,9 @@
       Builder.AddChunk(CodeCompletionString::CK_RightParen);
       Results.AddResult(Result(Builder.TakeString()));     =20
=20
-      if (SemaRef.getLangOptions().RTTI) {
+      if (SemaRef.getLangOpts().RTTI) {
         // typeid ( expression-or-type )
+        Builder.AddResultTypeChunk("std::type_info");
         Builder.AddTypedTextChunk("typeid");
         Builder.AddChunk(CodeCompletionString::CK_LeftParen);
         Builder.AddPlaceholderChunk("expression-or-type");
@@ -1790,12 +1876,14 @@
       Results.AddResult(Result(Builder.TakeString()));     =20
=20
       // delete expression
+      Builder.AddResultTypeChunk("void");
       Builder.AddTypedTextChunk("delete");
       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
       Builder.AddPlaceholderChunk("expression");
       Results.AddResult(Result(Builder.TakeString()));     =20
=20
       // delete [] expression
+      Builder.AddResultTypeChunk("void");
       Builder.AddTypedTextChunk("delete");
       Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
       Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
@@ -1804,30 +1892,71 @@
       Builder.AddPlaceholderChunk("expression");
       Results.AddResult(Result(Builder.TakeString()));
=20
-      if (SemaRef.getLangOptions().CXXExceptions) {
+      if (SemaRef.getLangOpts().CXXExceptions) {
         // throw expression
+        Builder.AddResultTypeChunk("void");
         Builder.AddTypedTextChunk("throw");
         Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
         Builder.AddPlaceholderChunk("expression");
         Results.AddResult(Result(Builder.TakeString()));
       }
-     =20
+    =20
       // FIXME: Rethrow?
+
+      if (SemaRef.getLangOpts().CPlusPlus0x) {
+        // nullptr
+        Builder.AddResultTypeChunk("std::nullptr_t");
+        Builder.AddTypedTextChunk("nullptr");
+        Results.AddResult(Result(Builder.TakeString()));
+
+        // alignof
+        Builder.AddResultTypeChunk("size_t");
+        Builder.AddTypedTextChunk("alignof");
+        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
+        Builder.AddPlaceholderChunk("type");
+        Builder.AddChunk(CodeCompletionString::CK_RightParen);
+        Results.AddResult(Result(Builder.TakeString()));
+
+        // noexcept
+        Builder.AddResultTypeChunk("bool");
+        Builder.AddTypedTextChunk("noexcept");
+        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
+        Builder.AddPlaceholderChunk("expression");
+        Builder.AddChunk(CodeCompletionString::CK_RightParen);
+        Results.AddResult(Result(Builder.TakeString()));
+
+        // sizeof... expression
+        Builder.AddResultTypeChunk("size_t");
+        Builder.AddTypedTextChunk("sizeof...");
+        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
+        Builder.AddPlaceholderChunk("parameter-pack");
+        Builder.AddChunk(CodeCompletionString::CK_RightParen);
+        Results.AddResult(Result(Builder.TakeString()));
+      }
     }
=20
-    if (SemaRef.getLangOptions().ObjC1) {
+    if (SemaRef.getLangOpts().ObjC1) {
       // Add "super", if we're in an Objective-C class with a superclass.
       if (ObjCMethodDecl *Method =3D SemaRef.getCurMethodDecl()) {
         // The interface can be NULL.
         if (ObjCInterfaceDecl *ID =3D Method->getClassInterface())
-          if (ID->getSuperClass())
-            Results.AddResult(Result("super"));
+          if (ID->getSuperClass()) {
+            std::string SuperType;
+            SuperType =3D ID->getSuperClass()->getNameAsString();
+            if (Method->isInstanceMethod())
+              SuperType +=3D " *";
+           =20
+            Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
+            Builder.AddTypedTextChunk("super");
+            Results.AddResult(Result(Builder.TakeString()));
+          }
       }
=20
       AddObjCExpressionResults(Results, true);
     }
=20
     // sizeof expression
+    Builder.AddResultTypeChunk("size_t");
     Builder.AddTypedTextChunk("sizeof");
     Builder.AddChunk(CodeCompletionString::CK_LeftParen);
     Builder.AddPlaceholderChunk("expression-or-type");
@@ -1841,54 +1970,13 @@
     break;
   }
=20
-  if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
-    AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
-
-  if (SemaRef.getLangOptions().CPlusPlus && CCC !=3D Sema::PCC_Type)
+  if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
+    AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
+
+  if (SemaRef.getLangOpts().CPlusPlus && CCC !=3D Sema::PCC_Type)
     Results.AddResult(Result("operator"));
 }
=20
-/// \brief Retrieve a printing policy suitable for code completion.
-static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
-  PrintingPolicy Policy =3D S.getPrintingPolicy();
-  Policy.AnonymousTagLocations =3D false;
-  Policy.SuppressStrongLifetime =3D true;
-  return Policy;
-}
-
-/// \brief Retrieve the string representation of the given type as a string
-/// that has the appropriate lifetime for code completion.
-///
-/// This routine provides a fast path where we provide constant strings for
-/// common type names.
-static const char *GetCompletionTypeString(QualType T,
-                                           ASTContext &Context,
-                                           const PrintingPolicy &Policy,
-                                           CodeCompletionAllocator &Alloca=
tor) {
-  if (!T.getLocalQualifiers()) {
-    // Built-in type names are constant strings.
-    if (const BuiltinType *BT =3D dyn_cast<BuiltinType>(T))
-      return BT->getName(Policy);
-   =20
-    // Anonymous tag types are constant strings.
-    if (const TagType *TagT =3D dyn_cast<TagType>(T))
-      if (TagDecl *Tag =3D TagT->getDecl())
-        if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
-          switch (Tag->getTagKind()) {
-          case TTK_Struct: return "struct <anonymous>";
-          case TTK_Class:  return "class <anonymous>";           =20
-          case TTK_Union:  return "union <anonymous>";
-          case TTK_Enum:   return "enum <anonymous>";
-          }
-        }
-  }
- =20
-  // Slow path: format the type as a string.
-  std::string Result;
-  T.getAsStringInternal(Result, Policy);
-  return Allocator.CopyString(Result);
-}
-
 /// \brief If the given declaration has an associated type, add it as a re=
sult=20
 /// type chunk.
 static void AddResultTypeChunk(ASTContext &Context,
@@ -1931,7 +2019,7 @@
                              CodeCompletionBuilder &Result) {
   if (SentinelAttr *Sentinel =3D FunctionOrMethod->getAttr<SentinelAttr>())
     if (Sentinel->getSentinel() =3D=3D 0) {
-      if (Context.getLangOptions().ObjC1 &&
+      if (Context.getLangOpts().ObjC1 &&
           Context.Idents.get("nil").hasMacroDefinition())
         Result.AddTextChunk(", nil");
       else if (Context.Idents.get("NULL").hasMacroDefinition())
@@ -1941,32 +2029,28 @@
     }
 }
=20
-static void appendWithSpace(std::string &Result, StringRef Text) {
-  if (!Result.empty())
-    Result +=3D ' ';
-  Result +=3D Text.str();
-}
 static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
   std::string Result;
   if (ObjCQuals & Decl::OBJC_TQ_In)
-    appendWithSpace(Result, "in");
+    Result +=3D "in ";
   else if (ObjCQuals & Decl::OBJC_TQ_Inout)
-    appendWithSpace(Result, "inout");
+    Result +=3D "inout ";
   else if (ObjCQuals & Decl::OBJC_TQ_Out)
-    appendWithSpace(Result, "out");
+    Result +=3D "out ";
   if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
-    appendWithSpace(Result, "bycopy");
+    Result +=3D "bycopy ";
   else if (ObjCQuals & Decl::OBJC_TQ_Byref)
-    appendWithSpace(Result, "byref");
+    Result +=3D "byref ";
   if (ObjCQuals & Decl::OBJC_TQ_Oneway)
-    appendWithSpace(Result, "oneway");
+    Result +=3D "oneway ";
   return Result;
 }
=20
 static std::string FormatFunctionParameter(ASTContext &Context,
                                            const PrintingPolicy &Policy,
                                            ParmVarDecl *Param,
-                                           bool SuppressName =3D false) {
+                                           bool SuppressName =3D false,
+                                           bool SuppressBlock =3D false) {
   bool ObjCMethodParam =3D isa<ObjCMethodDecl>(Param->getDeclContext());
   if (Param->getType()->isDependentType() ||
       !Param->getType()->isBlockPointerType()) {
@@ -1997,20 +2081,22 @@
     TL =3D TSInfo->getTypeLoc().getUnqualifiedLoc();
     while (true) {
       // Look through typedefs.
-      if (TypedefTypeLoc *TypedefTL =3D dyn_cast<TypedefTypeLoc>(&TL)) {
-        if (TypeSourceInfo *InnerTSInfo
-            =3D TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
-          TL =3D InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
+      if (!SuppressBlock) {
+        if (TypedefTypeLoc *TypedefTL =3D dyn_cast<TypedefTypeLoc>(&TL)) {
+          if (TypeSourceInfo *InnerTSInfo
+              =3D TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
+            TL =3D InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
+            continue;
+          }
+        }
+       =20
+        // Look through qualified types
+        if (QualifiedTypeLoc *QualifiedTL =3D dyn_cast<QualifiedTypeLoc>(&=
TL)) {
+          TL =3D QualifiedTL->getUnqualifiedLoc();
           continue;
         }
       }
      =20
-      // Look through qualified types
-      if (QualifiedTypeLoc *QualifiedTL =3D dyn_cast<QualifiedTypeLoc>(&TL=
)) {
-        TL =3D QualifiedTL->getUnqualifiedLoc();
-        continue;
-      }
-     =20
       // Try to get the function prototype behind the block pointer type,
       // then we're done.
       if (BlockPointerTypeLoc *BlockPtr
@@ -2027,6 +2113,9 @@
     // We were unable to find a FunctionProtoTypeLoc with parameter names
     // for the block; just use the parameter type as a placeholder.
     std::string Result;
+    if (!ObjCMethodParam && Param->getIdentifier())
+      Result =3D Param->getIdentifier()->getName();
+
     Param->getType().getUnqualifiedType().getAsStringInternal(Result, Poli=
cy);
    =20
     if (ObjCMethodParam) {
@@ -2038,36 +2127,52 @@
      =20
     return Result;
   }
- =20
+   =20
   // We have the function prototype behind the block pointer type, as it w=
as
   // written in the source.
   std::string Result;
   QualType ResultType =3D Block->getTypePtr()->getResultType();
-  if (!ResultType->isVoidType())
+  if (!ResultType->isVoidType() || SuppressBlock)
     ResultType.getAsStringInternal(Result, Policy);
- =20
-  Result =3D '^' + Result;
+
+  // Format the parameter list.
+  std::string Params;
   if (!BlockProto || Block->getNumArgs() =3D=3D 0) {
     if (BlockProto && BlockProto->getTypePtr()->isVariadic())
-      Result +=3D "(...)";
+      Params =3D "(...)";
     else
-      Result +=3D "(void)";
+      Params =3D "(void)";
   } else {
-    Result +=3D "(";
+    Params +=3D "(";
     for (unsigned I =3D 0, N =3D Block->getNumArgs(); I !=3D N; ++I) {
       if (I)
-        Result +=3D ", ";
-      Result +=3D FormatFunctionParameter(Context, Policy, Block->getArg(I=
));
+        Params +=3D ", ";
+      Params +=3D FormatFunctionParameter(Context, Policy, Block->getArg(I=
),
+                                        /*SuppressName=3D*/false,=20
+                                        /*SuppressBlock=3D*/true);
      =20
       if (I =3D=3D N - 1 && BlockProto->getTypePtr()->isVariadic())
-        Result +=3D ", ...";
+        Params +=3D ", ...";
     }
+    Params +=3D ")";
+  }
+ =20
+  if (SuppressBlock) {
+    // Format as a parameter.
+    Result =3D Result + " (^";
+    if (Param->getIdentifier())
+      Result +=3D Param->getIdentifier()->getName();
     Result +=3D ")";
-  }
- =20
-  if (Param->getIdentifier())
-    Result +=3D Param->getIdentifier()->getName();
-
+    Result +=3D Params;
+  } else {
+    // Format as a block literal argument.
+    Result =3D '^' + Result;
+    Result +=3D Params;
+   =20
+    if (Param->getIdentifier())
+      Result +=3D Param->getIdentifier()->getName();
+  }
+ =20
   return Result;
 }
=20
@@ -2078,7 +2183,6 @@
                                        CodeCompletionBuilder &Result,
                                        unsigned Start =3D 0,
                                        bool InOptional =3D false) {
-  typedef CodeCompletionString::Chunk Chunk;
   bool FirstParameter =3D true;
  =20
   for (unsigned P =3D Start, N =3D Function->getNumParams(); P !=3D N; ++P=
) {
@@ -2087,9 +2191,10 @@
     if (Param->hasDefaultArg() && !InOptional) {
       // When we see an optional default argument, put that argument and
       // the remaining default arguments into a new, optional string.
-      CodeCompletionBuilder Opt(Result.getAllocator());
+      CodeCompletionBuilder Opt(Result.getAllocator(),
+                                Result.getCodeCompletionTUInfo());
       if (!FirstParameter)
-        Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));       =20
+        Opt.AddChunk(CodeCompletionString::CK_Comma);
       AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
       Result.AddOptionalChunk(Opt.TakeString());
       break;
@@ -2098,7 +2203,7 @@
     if (FirstParameter)
       FirstParameter =3D false;
     else
-      Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
+      Result.AddChunk(CodeCompletionString::CK_Comma);
    =20
     InOptional =3D false;
    =20
@@ -2132,7 +2237,6 @@
                                        unsigned MaxParameters =3D 0,
                                        unsigned Start =3D 0,
                                        bool InDefaultArg =3D false) {
-  typedef CodeCompletionString::Chunk Chunk;
   bool FirstParameter =3D true;
  =20
   TemplateParameterList *Params =3D Template->getTemplateParameters();
@@ -2179,9 +2283,10 @@
     if (HasDefaultArg && !InDefaultArg) {
       // When we see an optional default argument, put that argument and
       // the remaining default arguments into a new, optional string.
-      CodeCompletionBuilder Opt(Result.getAllocator());
+      CodeCompletionBuilder Opt(Result.getAllocator(),
+                                Result.getCodeCompletionTUInfo());
       if (!FirstParameter)
-        Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma));
+        Opt.AddChunk(CodeCompletionString::CK_Comma);
       AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParame=
ters,
                                  P - Params->begin(), true);
       Result.AddOptionalChunk(Opt.TakeString());
@@ -2193,7 +2298,7 @@
     if (FirstParameter)
       FirstParameter =3D false;
     else
-      Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
+      Result.AddChunk(CodeCompletionString::CK_Comma);
    =20
     // Add the placeholder string.
     Result.AddPlaceholderChunk(
@@ -2263,8 +2368,6 @@
 /// \brief Add the name of the given declaration=20
 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &P=
olicy,
                               NamedDecl *ND, CodeCompletionBuilder &Result=
) {
-  typedef CodeCompletionString::Chunk Chunk;
- =20
   DeclarationName Name =3D ND->getDeclName();
   if (!Name)
     return;
@@ -2326,15 +2429,21 @@
     Result.AddTypedTextChunk(
                   Result.getAllocator().CopyString(Record->getNameAsString=
()));
     if (ClassTemplateDecl *Template =3D Record->getDescribedClassTemplate(=
)) {
-      Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
+      Result.AddChunk(CodeCompletionString::CK_LeftAngle);
       AddTemplateParameterChunks(Context, Policy, Template, Result);
-      Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
+      Result.AddChunk(CodeCompletionString::CK_RightAngle);
     }
     break;
   }
   }
 }
=20
+CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sem=
a &S,
+                                         CodeCompletionAllocator &Allocato=
r,
+                                         CodeCompletionTUInfo &CCTUInfo) {
+  return CreateCodeCompletionString(S.Context, S.PP, Allocator, CCTUInfo);
+}
+
 /// \brief If possible, create a new code completion string for the given
 /// result.
 ///
@@ -2342,15 +2451,23 @@
 /// how to use this result, or NULL to indicate that the string or name of=
 the
 /// result is all that is needed.
 CodeCompletionString *
-CodeCompletionResult::CreateCodeCompletionString(Sema &S,
-                                           CodeCompletionAllocator &Alloca=
tor) {
-  typedef CodeCompletionString::Chunk Chunk;
-  CodeCompletionBuilder Result(Allocator, Priority, Availability);
- =20
-  PrintingPolicy Policy =3D getCompletionPrintingPolicy(S);
+CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
+                                                 Preprocessor &PP,
+                                           CodeCompletionAllocator &Alloca=
tor,
+                                           CodeCompletionTUInfo &CCTUInfo)=
 {
+  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability=
);
+ =20
+  PrintingPolicy Policy =3D getCompletionPrintingPolicy(Ctx, PP);
   if (Kind =3D=3D RK_Pattern) {
     Pattern->Priority =3D Priority;
     Pattern->Availability =3D Availability;
+   =20
+    if (Declaration) {
+      Result.addParentContext(Declaration->getDeclContext());
+      Pattern->ParentKind =3D Result.getParentKind();
+      Pattern->ParentName =3D Result.getParentName();
+    }
+   =20
     return Pattern;
   }
  =20
@@ -2360,7 +2477,7 @@
   }
  =20
   if (Kind =3D=3D RK_Macro) {
-    MacroInfo *MI =3D S.PP.getMacroInfo(Macro);
+    MacroInfo *MI =3D PP.getMacroInfo(Macro);
     assert(MI && "Not a macro?");
=20
     Result.AddTypedTextChunk(
@@ -2370,54 +2487,44 @@
       return Result.TakeString();
    =20
     // Format a function-like macro with placeholders for the arguments.
-    Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
-    bool CombineVariadicArgument =3D false;
+    Result.AddChunk(CodeCompletionString::CK_LeftParen);
     MacroInfo::arg_iterator A =3D MI->arg_begin(), AEnd =3D MI->arg_end();
-    if (MI->isVariadic() && AEnd - A > 1) {
-      AEnd -=3D 2;
-      CombineVariadicArgument =3D true;
+   =20
+    // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
+    if (MI->isC99Varargs()) {
+      --AEnd;
+     =20
+      if (A =3D=3D AEnd) {
+        Result.AddPlaceholderChunk("...");
+      }
     }
+   =20
     for (MacroInfo::arg_iterator A =3D MI->arg_begin(); A !=3D AEnd; ++A) {
       if (A !=3D MI->arg_begin())
-        Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
-     =20
-      if (!MI->isVariadic() || A + 1 !=3D AEnd) {
-        // Non-variadic argument.
-        Result.AddPlaceholderChunk(
-                            Result.getAllocator().CopyString((*A)->getName=
()));
-        continue;
+        Result.AddChunk(CodeCompletionString::CK_Comma);
+
+      if (MI->isVariadic() && (A+1) =3D=3D AEnd) {
+        SmallString<32> Arg =3D (*A)->getName();
+        if (MI->isC99Varargs())
+          Arg +=3D ", ...";
+        else
+          Arg +=3D "...";
+        Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
+        break;
       }
-     =20
-      // Variadic argument; cope with the difference between GNU and C99
-      // variadic macros, providing a single placeholder for the rest of t=
he
-      // arguments.
-      if ((*A)->isStr("__VA_ARGS__"))
-        Result.AddPlaceholderChunk("...");
-      else {
-        std::string Arg =3D (*A)->getName();
-        Arg +=3D "...";
-        Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
-      }
+
+      // Non-variadic macros are simple.
+      Result.AddPlaceholderChunk(
+                          Result.getAllocator().CopyString((*A)->getName()=
));
     }
-    =20
-    if (CombineVariadicArgument) {
-      // Handle the next-to-last argument, combining it with the variadic
-      // argument.
-      std::string LastArg =3D (*A)->getName();
-      ++A;
-      if ((*A)->isStr("__VA_ARGS__"))
-        LastArg +=3D ", ...";
-      else
-        LastArg +=3D ", " + (*A)->getName().str() + "...";
-      Result.AddPlaceholderChunk(Result.getAllocator().CopyString(LastArg)=
);
-    }
-    Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
+    Result.AddChunk(CodeCompletionString::CK_RightParen);
     return Result.TakeString();
   }
  =20
   assert(Kind =3D=3D RK_Declaration && "Missed a result kind?");
   NamedDecl *ND =3D Declaration;
- =20
+  Result.addParentContext(ND->getDeclContext());
+                         =20
   if (StartsNestedNameSpecifier) {
     Result.AddTypedTextChunk(
                       Result.getAllocator().CopyString(ND->getNameAsString=
()));
@@ -2431,29 +2538,29 @@
     }
   }
  =20
-  AddResultTypeChunk(S.Context, Policy, ND, Result);
+  AddResultTypeChunk(Ctx, Policy, ND, Result);
  =20
   if (FunctionDecl *Function =3D dyn_cast<FunctionDecl>(ND)) {
     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformati=
ve,=20
-                                   S.Context, Policy);
-    AddTypedNameChunk(S.Context, Policy, ND, Result);
-    Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
-    AddFunctionParameterChunks(S.Context, Policy, Function, Result);
-    Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
+                                   Ctx, Policy);
+    AddTypedNameChunk(Ctx, Policy, ND, Result);
+    Result.AddChunk(CodeCompletionString::CK_LeftParen);
+    AddFunctionParameterChunks(Ctx, Policy, Function, Result);
+    Result.AddChunk(CodeCompletionString::CK_RightParen);
     AddFunctionTypeQualsToCompletionString(Result, Function);
     return Result.TakeString();
   }
  =20
   if (FunctionTemplateDecl *FunTmpl =3D dyn_cast<FunctionTemplateDecl>(ND)=
) {
     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformati=
ve,=20
-                                   S.Context, Policy);
+                                   Ctx, Policy);
     FunctionDecl *Function =3D FunTmpl->getTemplatedDecl();
-    AddTypedNameChunk(S.Context, Policy, Function, Result);
+    AddTypedNameChunk(Ctx, Policy, Function, Result);
=20
     // Figure out which template parameters are deduced (or have default
     // arguments).
-    SmallVector<bool, 16> Deduced;
-    S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
+    llvm::SmallBitVector Deduced;
+    Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
     unsigned LastDeducibleArgument;
     for (LastDeducibleArgument =3D Deduced.size(); LastDeducibleArgument >=
 0;
          --LastDeducibleArgument) {
@@ -2484,28 +2591,28 @@
       // Some of the function template arguments cannot be deduced from a
       // function call, so we introduce an explicit template argument list
       // containing all of the arguments up to the first deducible argumen=
t.
-      Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
-      AddTemplateParameterChunks(S.Context, Policy, FunTmpl, Result,=20
+      Result.AddChunk(CodeCompletionString::CK_LeftAngle);
+      AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,=20
                                  LastDeducibleArgument);
-      Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
+      Result.AddChunk(CodeCompletionString::CK_RightAngle);
     }
    =20
     // Add the function parameters
-    Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
-    AddFunctionParameterChunks(S.Context, Policy, Function, Result);
-    Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
+    Result.AddChunk(CodeCompletionString::CK_LeftParen);
+    AddFunctionParameterChunks(Ctx, Policy, Function, Result);
+    Result.AddChunk(CodeCompletionString::CK_RightParen);
     AddFunctionTypeQualsToCompletionString(Result, Function);
     return Result.TakeString();
   }
  =20
   if (TemplateDecl *Template =3D dyn_cast<TemplateDecl>(ND)) {
     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformati=
ve,=20
-                                   S.Context, Policy);
+                                   Ctx, Policy);
     Result.AddTypedTextChunk(
                 Result.getAllocator().CopyString(Template->getNameAsString=
()));
-    Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
-    AddTemplateParameterChunks(S.Context, Policy, Template, Result);
-    Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
+    Result.AddChunk(CodeCompletionString::CK_LeftAngle);
+    AddTemplateParameterChunks(Ctx, Policy, Template, Result);
+    Result.AddChunk(CodeCompletionString::CK_RightAngle);
     return Result.TakeString();
   }
  =20
@@ -2553,7 +2660,7 @@
       std::string Arg;
      =20
       if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
-        Arg =3D FormatFunctionParameter(S.Context, Policy, *P, true);
+        Arg =3D FormatFunctionParameter(Ctx, Policy, *P, true);
       else {
         (*P)->getType().getAsStringInternal(Arg, Policy);
         Arg =3D "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier=
())=20
@@ -2584,7 +2691,7 @@
           Result.AddPlaceholderChunk(", ...");
       }
      =20
-      MaybeAddSentinel(S.Context, Method, Result);
+      MaybeAddSentinel(Ctx, Method, Result);
     }
    =20
     return Result.TakeString();
@@ -2592,7 +2699,7 @@
=20
   if (Qualifier)
     AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformati=
ve,=20
-                                   S.Context, Policy);
+                                   Ctx, Policy);
=20
   Result.AddTypedTextChunk(
                        Result.getAllocator().CopyString(ND->getNameAsStrin=
g()));
@@ -2603,12 +2710,12 @@
 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
                                                           unsigned Current=
Arg,
                                                                Sema &S,
-                                     CodeCompletionAllocator &Allocator) c=
onst {
-  typedef CodeCompletionString::Chunk Chunk;
+                                     CodeCompletionAllocator &Allocator,
+                                     CodeCompletionTUInfo &CCTUInfo) const=
 {
   PrintingPolicy Policy =3D getCompletionPrintingPolicy(S);
=20
   // FIXME: Set priority, availability appropriately.
-  CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available);
+  CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Avail=
able);
   FunctionDecl *FDecl =3D getFunction();
   AddResultTypeChunk(S.Context, Policy, FDecl, Result);
   const FunctionProtoType *Proto=20
@@ -2620,9 +2727,9 @@
     Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
                                                 S.Context, Policy,=20
                                                 Result.getAllocator()));
-    Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
-    Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."=
));
-    Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
+    Result.AddChunk(CodeCompletionString::CK_LeftParen);
+    Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
+    Result.AddChunk(CodeCompletionString::CK_RightParen);
     return Result.TakeString();
   }
  =20
@@ -2634,11 +2741,11 @@
          Result.getAllocator().CopyString(
                                   Proto->getResultType().getAsString(Polic=
y)));
  =20
-  Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
+  Result.AddChunk(CodeCompletionString::CK_LeftParen);
   unsigned NumParams =3D FDecl? FDecl->getNumParams() : Proto->getNumArgs(=
);
   for (unsigned I =3D 0; I !=3D NumParams; ++I) {
     if (I)
-      Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
+      Result.AddChunk(CodeCompletionString::CK_Comma);
    =20
     std::string ArgString;
     QualType ArgType;
@@ -2653,20 +2760,20 @@
     ArgType.getAsStringInternal(ArgString, Policy);
    =20
     if (I =3D=3D CurrentArg)
-      Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,=20
-                             Result.getAllocator().CopyString(ArgString)));
+      Result.AddChunk(CodeCompletionString::CK_CurrentParameter,
+                      Result.getAllocator().CopyString(ArgString));
     else
       Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
   }
  =20
   if (Proto && Proto->isVariadic()) {
-    Result.AddChunk(Chunk(CodeCompletionString::CK_Comma));
+    Result.AddChunk(CodeCompletionString::CK_Comma);
     if (CurrentArg < NumParams)
       Result.AddTextChunk("...");
     else
-      Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..=
."));
-  }
-  Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
+      Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
+  }
+  Result.AddChunk(CodeCompletionString::CK_RightParen);
  =20
   return Result.TakeString();
 }
@@ -2707,13 +2814,8 @@
       return CXCursor_FunctionDecl;
     case Decl::ObjCCategory:       return CXCursor_ObjCCategoryDecl;
     case Decl::ObjCCategoryImpl:   return CXCursor_ObjCCategoryImplDecl;
-    case Decl::ObjCClass:
-      // FIXME
-      return CXCursor_UnexposedDecl;
-    case Decl::ObjCForwardProtocol:
-      // FIXME
-      return CXCursor_UnexposedDecl;     =20
     case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
+
     case Decl::ObjCInterface:      return CXCursor_ObjCInterfaceDecl;
     case Decl::ObjCIvar:           return CXCursor_ObjCIvarDecl;=20
     case Decl::ObjCMethod:
@@ -2754,7 +2856,6 @@
       case ObjCPropertyImplDecl::Synthesize:
         return CXCursor_ObjCSynthesizeDecl;
       }
-      break;
      =20
     default:
       if (TagDecl *TD =3D dyn_cast<TagDecl>(D)) {
@@ -2781,7 +2882,7 @@
        M !=3D MEnd; ++M) {
     Results.AddResult(Result(M->first,=20
                              getMacroUsagePriority(M->first->getName(),
-                                                   PP.getLangOptions(),
+                                                   PP.getLangOpts(),
                                                    TargetTypeIsPointer)));
   }
  =20
@@ -2833,17 +2934,16 @@
   case Sema::PCC_MemberTemplate:
     if (S.CurContext->isFileContext())
       return CodeCompletionContext::CCC_TopLevel;
-    else if (S.CurContext->isRecord())
+    if (S.CurContext->isRecord())
       return CodeCompletionContext::CCC_ClassStructUnion;
-    else=20
-      return CodeCompletionContext::CCC_Other;
+    return CodeCompletionContext::CCC_Other;
      =20
   case Sema::PCC_RecoveryInFunction:
     return CodeCompletionContext::CCC_Recovery;
=20
   case Sema::PCC_ForInit:
-    if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
-        S.getLangOptions().ObjC1)
+    if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
+        S.getLangOpts().ObjC1)
       return CodeCompletionContext::CCC_ParenthesizedExpression;
     else
       return CodeCompletionContext::CCC_Expression;
@@ -2864,8 +2964,8 @@
   case Sema::PCC_LocalDeclarationSpecifiers:
     return CodeCompletionContext::CCC_Type;
   }
- =20
-  return CodeCompletionContext::CCC_Other;
+
+  llvm_unreachable("Invalid ParserCompletionContext!");
 }
=20
 /// \brief If we're in a C++ virtual member function, add completion resul=
ts
@@ -2902,7 +3002,8 @@
   for (CXXMethodDecl::method_iterator M =3D Method->begin_overridden_metho=
ds(),
                                    MEnd =3D Method->end_overridden_methods=
();
        M !=3D MEnd; ++M) {
-    CodeCompletionBuilder Builder(Results.getAllocator());
+    CodeCompletionBuilder Builder(Results.getAllocator(),
+                                  Results.getCodeCompletionTUInfo());
     CXXMethodDecl *Overridden =3D const_cast<CXXMethodDecl *>(*M);
     if (Overridden->getCanonicalDecl() =3D=3D Method->getCanonicalDecl())
       continue;
@@ -2939,15 +3040,70 @@
     Builder.AddChunk(CodeCompletionString::CK_RightParen);
     Results.AddResult(CodeCompletionResult(Builder.TakeString(),
                                            CCP_SuperCompletion,
-                                           CXCursor_CXXMethod));
+                                           CXCursor_CXXMethod,
+                                           CXAvailability_Available,
+                                           Overridden));
     Results.Ignore(Overridden);
   }
 }
=20
+void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,=20
+                                    ModuleIdPath Path) {
+  typedef CodeCompletionResult Result;
+  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
+                        CodeCompletionContext::CCC_Other);
+  Results.EnterNewScope();
+ =20
+  CodeCompletionAllocator &Allocator =3D Results.getAllocator();
+  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo=
());
+  typedef CodeCompletionResult Result;
+  if (Path.empty()) {
+    // Enumerate all top-level modules.
+    llvm::SmallVector<Module *, 8> Modules;
+    PP.getHeaderSearchInfo().collectAllModules(Modules);
+    for (unsigned I =3D 0, N =3D Modules.size(); I !=3D N; ++I) {
+      Builder.AddTypedTextChunk(
+        Builder.getAllocator().CopyString(Modules[I]->Name));
+      Results.AddResult(Result(Builder.TakeString(),
+                               CCP_Declaration,=20
+                               CXCursor_NotImplemented,
+                               Modules[I]->isAvailable()
+                                 ? CXAvailability_Available
+                                  : CXAvailability_NotAvailable));
+    }
+  } else {
+    // Load the named module.
+    Module *Mod =3D PP.getModuleLoader().loadModule(ImportLoc, Path,
+                                                  Module::AllVisible,
+                                                /*IsInclusionDirective=3D*=
/false);
+    // Enumerate submodules.
+    if (Mod) {
+      for (Module::submodule_iterator Sub =3D Mod->submodule_begin(),=20
+                                   SubEnd =3D Mod->submodule_end();
+           Sub !=3D SubEnd; ++Sub) {
+       =20
+        Builder.AddTypedTextChunk(
+          Builder.getAllocator().CopyString((*Sub)->Name));
+        Results.AddResult(Result(Builder.TakeString(),
+                                 CCP_Declaration,=20
+                                 CXCursor_NotImplemented,
+                                 (*Sub)->isAvailable()
+                                   ? CXAvailability_Available
+                                   : CXAvailability_NotAvailable));
+      }
+    }
+  }
+  Results.ExitScope();   =20
+  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionCont=
ext(),
+                            Results.data(),Results.size());
+}
+
 void Sema::CodeCompleteOrdinaryName(Scope *S,=20
                                     ParserCompletionContext CompletionCont=
ext) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         mapCodeCompletionContext(*this, CompletionContext)=
);
   Results.EnterNewScope();
  =20
@@ -2972,12 +3128,12 @@
   case PCC_Expression:
   case PCC_ForInit:
   case PCC_Condition:
-    if (WantTypesInContext(CompletionContext, getLangOptions()))
+    if (WantTypesInContext(CompletionContext, getLangOpts()))
       Results.setFilter(&ResultBuilder::IsOrdinaryName);
     else
       Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
      =20
-    if (getLangOptions().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       MaybeAddOverrideCalls(*this, /*InContext=3D*/0, Results);
     break;
      =20
@@ -3006,7 +3162,7 @@
   case PCC_Statement:
   case PCC_RecoveryInFunction:
     if (S->getFnParent())
-      AddPrettyFunctionResults(PP.getLangOptions(), Results);       =20
+      AddPrettyFunctionResults(PP.getLangOpts(), Results);       =20
     break;
    =20
   case PCC_Namespace:
@@ -3043,6 +3199,7 @@
                                 bool AllowNestedNameSpecifiers) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         AllowNestedNameSpecifiers
                           ? CodeCompletionContext::CCC_PotentiallyQualifie=
dName
                           : CodeCompletionContext::CCC_Name);
@@ -3051,10 +3208,10 @@
   // Type qualifiers can come after names.
   Results.AddResult(Result("const"));
   Results.AddResult(Result("volatile"));
-  if (getLangOptions().C99)
+  if (getLangOpts().C99)
     Results.AddResult(Result("restrict"));
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     if (AllowNonIdentifiers) {
       Results.AddResult(Result("operator"));=20
     }
@@ -3120,12 +3277,13 @@
                                   const CodeCompleteExpressionData &Data) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Expression);
   if (Data.ObjCCollection)
     Results.setFilter(&ResultBuilder::IsObjCCollection);
   else if (Data.IntegralConstantExpression)
     Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
-  else if (WantTypesInContext(PCC_Expression, getLangOptions()))
+  else if (WantTypesInContext(PCC_Expression, getLangOpts()))
     Results.setFilter(&ResultBuilder::IsOrdinaryName);
   else
     Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
@@ -3154,7 +3312,7 @@
   if (S->getFnParent() &&=20
       !Data.ObjCCollection &&=20
       !Data.IntegralConstantExpression)
-    AddPrettyFunctionResults(PP.getLangOptions(), Results);       =20
+    AddPrettyFunctionResults(PP.getLangOpts(), Results);       =20
=20
   if (CodeCompleter->includeMacros())
     AddMacroResults(PP, Results, PreferredTypeIsPointer);
@@ -3167,7 +3325,7 @@
 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
   if (E.isInvalid())
     CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
-  else if (getLangOptions().ObjC1)
+  else if (getLangOpts().ObjC1)
     CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
 }
=20
@@ -3202,33 +3360,14 @@
       if (M->getSelector().isUnarySelector())
         if (IdentifierInfo *Name =3D M->getSelector().getIdentifierInfoFor=
Slot(0))
           if (AddedProperties.insert(Name)) {
-            CodeCompletionBuilder Builder(Results.getAllocator());
+            CodeCompletionBuilder Builder(Results.getAllocator(),
+                                          Results.getCodeCompletionTUInfo(=
));
             AddResultTypeChunk(Context, Policy, *M, Builder);
             Builder.AddTypedTextChunk(
                             Results.getAllocator().CopyString(Name->getNam=
e()));
            =20
-            CXAvailabilityKind Availability =3D CXAvailability_Available;
-            switch (M->getAvailability()) {
-            case AR_Available:
-            case AR_NotYetIntroduced:
-              Availability =3D CXAvailability_Available;     =20
-              break;
-             =20
-            case AR_Deprecated:
-              Availability =3D CXAvailability_Deprecated;
-              break;
-             =20
-            case AR_Unavailable:
-              Availability =3D CXAvailability_NotAvailable;
-              break;
-            }
-
-            Results.MaybeAddResult(Result(Builder.TakeString(),
-                                  CCP_MemberDeclaration + CCD_MethodAsProp=
erty,
-                                          M->isInstanceMethod()
-                                            ? CXCursor_ObjCInstanceMethodD=
ecl
-                                            : CXCursor_ObjCClassMethodDecl,
-                                          Availability),
+            Results.MaybeAddResult(Result(Builder.TakeString(), *M,
+                                  CCP_MemberDeclaration + CCD_MethodAsProp=
erty),
                                           CurContext);
           }
     }
@@ -3274,15 +3413,19 @@
   }
 }
=20
-void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *BaseE,
+void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
                                            SourceLocation OpLoc,
                                            bool IsArrow) {
-  if (!BaseE || !CodeCompleter)
+  if (!Base || !CodeCompleter)
     return;
  =20
+  ExprResult ConvertedBase =3D PerformMemberExprBaseConversion(Base, IsArr=
ow);
+  if (ConvertedBase.isInvalid())
+    return;
+  Base =3D ConvertedBase.get();
+
   typedef CodeCompletionResult Result;
  =20
-  Expr *Base =3D static_cast<Expr *>(BaseE);
   QualType BaseType =3D Base->getType();
=20
   if (IsArrow) {
@@ -3310,6 +3453,7 @@
   }
  =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                   CodeCompletionContext(contextKind,
                                         BaseType),
                         &ResultBuilder::IsMember);
@@ -3325,7 +3469,7 @@
     LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
                        CodeCompleter->includeGlobals());
=20
-    if (getLangOptions().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       if (!Results.empty()) {
         // The "template" keyword can follow "->" or "." in the grammar.
         // However, we only want to suggest the template keyword if someth=
ing
@@ -3419,7 +3563,8 @@
     llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
   }
  =20
-  ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind);
+  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(), ContextK=
ind);
   CodeCompletionDeclConsumer Consumer(Results, CurContext);
=20
   // First pass: look for tags.
@@ -3439,13 +3584,14 @@
=20
 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_TypeQualifiers);
   Results.EnterNewScope();
   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
     Results.AddResult("const");
   if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
     Results.AddResult("volatile");
-  if (getLangOptions().C99 &&
+  if (getLangOpts().C99 &&
       !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
     Results.AddResult("restrict");
   Results.ExitScope();
@@ -3510,18 +3656,16 @@
       }
   }
  =20
-  if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty())=
 {
+  if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
     // If there are no prior enumerators in C++, check whether we have to=20
     // qualify the names of the enumerators that we suggest, because they
     // may not be visible in this scope.
-    Qualifier =3D getRequiredQualification(Context, CurContext,
-                                         Enum->getDeclContext());
-   =20
-    // FIXME: Scoped enums need to start with "EnumDecl" as the context!
+    Qualifier =3D getRequiredQualification(Context, CurContext, Enum);
   }
  =20
   // Add any enumerators that have not yet been mentioned.
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Expression);
   Results.EnterNewScope();
   for (EnumDecl::enumerator_iterator E =3D Enum->enumerator_begin(),
@@ -3544,7 +3688,6 @@
     kind =3D CodeCompletionContext::CCC_OtherWithMacros;
   }
  =20
- =20
   HandleCodeCompleteResults(this, CodeCompleter,=20
                             kind,
                             Results.data(),Results.size());
@@ -3566,19 +3709,19 @@
   };
 }
=20
-static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
-  if (NumArgs && !Args)
+static bool anyNullArguments(llvm::ArrayRef<Expr*> Args) {
+  if (Args.size() && !Args.data())
     return true;
- =20
-  for (unsigned I =3D 0; I !=3D NumArgs; ++I)
+
+  for (unsigned I =3D 0; I !=3D Args.size(); ++I)
     if (!Args[I])
       return true;
- =20
+
   return false;
 }
=20
 void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
-                            Expr **ArgsIn, unsigned NumArgs) {
+                            llvm::ArrayRef<Expr *> Args) {
   if (!CodeCompleter)
     return;
=20
@@ -3588,11 +3731,10 @@
   // e.g., by merging the two kinds of results.
=20
   Expr *Fn =3D (Expr *)FnIn;
-  Expr **Args =3D (Expr **)ArgsIn;
=20
   // Ignore type-dependent call expressions entirely.
-  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
-      Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
+  if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
+      Expr::hasAnyTypeDependentArguments(Args)) {
     CodeCompleteOrdinaryName(S, PCC_Expression);
     return;
   }
@@ -3610,19 +3752,18 @@
=20
   Expr *NakedFn =3D Fn->IgnoreParenCasts();
   if (UnresolvedLookupExpr *ULE =3D dyn_cast<UnresolvedLookupExpr>(NakedFn=
))
-    AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
+    AddOverloadedCallCandidates(ULE, Args, CandidateSet,
                                 /*PartialOverloading=3D*/ true);
   else if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(NakedFn)) {
     FunctionDecl *FDecl =3D dyn_cast<FunctionDecl>(DRE->getDecl());
     if (FDecl) {
-      if (!getLangOptions().CPlusPlus ||=20
+      if (!getLangOpts().CPlusPlus ||=20
           !FDecl->getType()->getAs<FunctionProtoType>())
         Results.push_back(ResultCandidate(FDecl));
       else
         // FIXME: access?
-        AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
-                             Args, NumArgs, CandidateSet,
-                             false, /*PartialOverloading*/true);
+        AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), =
Args,
+                             CandidateSet, false, /*PartialOverloading*/tr=
ue);
     }
   }
  =20
@@ -3645,12 +3786,12 @@
     for (unsigned I =3D 0, N =3D Results.size(); I !=3D N; ++I) {
       if (const FunctionType *FType =3D Results[I].getFunctionType())
         if (const FunctionProtoType *Proto =3D dyn_cast<FunctionProtoType>=
(FType))
-          if (NumArgs < Proto->getNumArgs()) {
+          if (Args.size() < Proto->getNumArgs()) {
             if (ParamType.isNull())
-              ParamType =3D Proto->getArgType(NumArgs);
+              ParamType =3D Proto->getArgType(Args.size());
             else if (!Context.hasSameUnqualifiedType(
                                             ParamType.getNonReferenceType(=
),
-                           Proto->getArgType(NumArgs).getNonReferenceType(=
))) {
+                       Proto->getArgType(Args.size()).getNonReferenceType(=
))) {
               ParamType =3D QualType();
               break;
             }
@@ -3671,8 +3812,8 @@
    =20
     if (const FunctionProtoType *Proto
                                   =3D FunctionType->getAs<FunctionProtoTyp=
e>()) {
-      if (NumArgs < Proto->getNumArgs())
-        ParamType =3D Proto->getArgType(NumArgs);
+      if (Args.size() < Proto->getNumArgs())
+        ParamType =3D Proto->getArgType(Args.size());
     }
   }
=20
@@ -3682,7 +3823,7 @@
     CodeCompleteExpression(S, ParamType);
  =20
   if (!Results.empty())
-    CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(=
),=20
+    CodeCompleter->ProcessOverloadCandidates(*this, Args.size(), Results.d=
ata(),
                                              Results.size());
 }
=20
@@ -3715,6 +3856,7 @@
 void Sema::CodeCompleteAfterIf(Scope *S) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         mapCodeCompletionContext(*this, PCC_Statement));
   Results.setFilter(&ResultBuilder::IsOrdinaryName);
   Results.EnterNewScope();
@@ -3726,14 +3868,17 @@
   AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
  =20
   // "else" block
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
   Builder.AddTypedTextChunk("else");
-  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
-  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
-  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-  Builder.AddPlaceholderChunk("statements");
-  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
+  if (Results.includeCodePatterns()) {
+    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+    Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
+    Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+    Builder.AddPlaceholderChunk("statements");
+    Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+    Builder.AddChunk(CodeCompletionString::CK_RightBrace);
+  }
   Results.AddResult(Builder.TakeString());
=20
   // "else if" block
@@ -3742,23 +3887,25 @@
   Builder.AddTextChunk("if");
   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
-  if (getLangOptions().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     Builder.AddPlaceholderChunk("condition");
   else
     Builder.AddPlaceholderChunk("expression");
   Builder.AddChunk(CodeCompletionString::CK_RightParen);
-  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
-  Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
-  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-  Builder.AddPlaceholderChunk("statements");
-  Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
-  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
+  if (Results.includeCodePatterns()) {
+    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+    Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
+    Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+    Builder.AddPlaceholderChunk("statements");
+    Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
+    Builder.AddChunk(CodeCompletionString::CK_RightBrace);
+  }
   Results.AddResult(Builder.TakeString());
=20
   Results.ExitScope();
  =20
   if (S->getFnParent())
-    AddPrettyFunctionResults(PP.getLangOptions(), Results);       =20
+    AddPrettyFunctionResults(PP.getLangOpts(), Results);       =20
  =20
   if (CodeCompleter->includeMacros())
     AddMacroResults(PP, Results);
@@ -3789,6 +3936,7 @@
     return;
=20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Name);
   Results.EnterNewScope();
  =20
@@ -3820,6 +3968,7 @@
     return;
  =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_PotentiallyQualifiedNam=
e,
                         &ResultBuilder::IsNestedNameSpecifier);
   Results.EnterNewScope();
@@ -3847,6 +3996,7 @@
   // After "using namespace", we expect to see a namespace name or namespa=
ce
   // alias.
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Namespace,
                         &ResultBuilder::IsNamespaceOrAlias);
   Results.EnterNewScope();
@@ -3871,6 +4021,7 @@
     =3D Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl=
>(Ctx);
  =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         SuppressedGlobalResults
                           ? CodeCompletionContext::CCC_Namespace
                           : CodeCompletionContext::CCC_Other,
@@ -3891,7 +4042,8 @@
     // namespace to the list of results.
     Results.EnterNewScope();
     for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator=20
-         NS =3D OrigToLatest.begin(), NSEnd =3D OrigToLatest.end();
+              NS =3D OrigToLatest.begin(),
+           NSEnd =3D OrigToLatest.end();
          NS !=3D NSEnd; ++NS)
       Results.AddResult(CodeCompletionResult(NS->second, 0),
                         CurContext, 0, false);
@@ -3909,6 +4061,7 @@
  =20
   // After "namespace", we expect to see a namespace or alias.
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Namespace,
                         &ResultBuilder::IsNamespaceOrAlias);
   CodeCompletionDeclConsumer Consumer(Results, CurContext);
@@ -3925,6 +4078,7 @@
=20
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Type,
                         &ResultBuilder::IsType);
   Results.EnterNewScope();
@@ -3942,7 +4096,7 @@
                      CodeCompleter->includeGlobals());
  =20
   // Add any type specifiers
-  AddTypeSpecifierResults(getLangOptions(), Results);
+  AddTypeSpecifierResults(getLangOpts(), Results);
   Results.ExitScope();
  =20
   HandleCodeCompleteResults(this, CodeCompleter,=20
@@ -3960,6 +4114,7 @@
     return;
  =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_PotentiallyQualifiedNam=
e);
   Results.EnterNewScope();
  =20
@@ -3976,7 +4131,8 @@
   }
  =20
   // Add completions for base classes.
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
   bool SawLastInitializer =3D (NumInitializers =3D=3D 0);
   CXXRecordDecl *ClassDecl =3D Constructor->getParent();
   for (CXXRecordDecl::base_class_iterator Base =3D ClassDecl->bases_begin(=
),
@@ -4051,7 +4207,9 @@
     Results.AddResult(CodeCompletionResult(Builder.TakeString(),=20
                                    SawLastInitializer? CCP_NextInitializer
                                                      : CCP_MemberDeclarati=
on,
-                                           CXCursor_MemberRef));
+                                           CXCursor_MemberRef,
+                                           CXAvailability_Available,
+                                           *Field));
     SawLastInitializer =3D false;
   }
   Results.ExitScope();
@@ -4060,6 +4218,61 @@
                             Results.data(), Results.size());
 }
=20
+/// \brief Determine whether this scope denotes a namespace.
+static bool isNamespaceScope(Scope *S) {
+  DeclContext *DC =3D static_cast<DeclContext *>(S->getEntity());
+  if (!DC)
+    return false;
+
+  return DC->isFileContext();
+}
+
+void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
+                                        bool AfterAmpersand) {
+  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
+                        CodeCompletionContext::CCC_Other);
+  Results.EnterNewScope();
+
+  // Note what has already been captured.
+  llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
+  bool IncludedThis =3D false;
+  for (SmallVectorImpl<LambdaCapture>::iterator C =3D Intro.Captures.begin=
(),
+                                             CEnd =3D Intro.Captures.end();
+       C !=3D CEnd; ++C) {
+    if (C->Kind =3D=3D LCK_This) {
+      IncludedThis =3D true;
+      continue;
+    }
+   =20
+    Known.insert(C->Id);
+  }
+ =20
+  // Look for other capturable variables.
+  for (; S && !isNamespaceScope(S); S =3D S->getParent()) {
+    for (Scope::decl_iterator D =3D S->decl_begin(), DEnd =3D S->decl_end(=
);
+         D !=3D DEnd; ++D) {
+      VarDecl *Var =3D dyn_cast<VarDecl>(*D);
+      if (!Var ||
+          !Var->hasLocalStorage() ||
+          Var->hasAttr<BlocksAttr>())
+        continue;
+     =20
+      if (Known.insert(Var->getIdentifier()))
+        Results.AddResult(CodeCompletionResult(Var), CurContext, 0, false);
+    }
+  }
+
+  // Add 'this', if it would be valid.
+  if (!IncludedThis && !AfterAmpersand && Intro.Default !=3D LCD_ByCopy)
+    addThisCompletion(*this, Results);
+ =20
+  Results.ExitScope();
+ =20
+  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionCont=
ext(),
+                            Results.data(), Results.size());
+}
+
 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt =
is
 // true or false.
 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keywo=
rd
@@ -4070,7 +4283,8 @@
   // Since we have an implementation, we can end it.
   Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
  =20
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
   if (LangOpts.ObjC2) {
     // @dynamic
     Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
@@ -4108,7 +4322,8 @@
=20
 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
   typedef CodeCompletionResult Result;
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
  =20
   // @class name ;
   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
@@ -4150,12 +4365,13 @@
 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
   if (isa<ObjCImplDecl>(CurContext))
-    AddObjCImplementationResults(getLangOptions(), Results, false);
+    AddObjCImplementationResults(getLangOpts(), Results, false);
   else if (CurContext->isObjCContainer())
-    AddObjCInterfaceResults(getLangOptions(), Results, false);
+    AddObjCInterfaceResults(getLangOpts(), Results, false);
   else
     AddObjCTopLevelResults(Results, false);
   Results.ExitScope();
@@ -4166,9 +4382,15 @@
=20
 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
   typedef CodeCompletionResult Result;
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
=20
   // @encode ( type-name )
+  const char *EncodeType =3D "char[]";
+  if (Results.getSema().getLangOpts().CPlusPlus ||
+      Results.getSema().getLangOpts().ConstStrings)
+    EncodeType =3D " const char[]";
+  Builder.AddResultTypeChunk(EncodeType);
   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
   Builder.AddPlaceholderChunk("type-name");
@@ -4176,6 +4398,7 @@
   Results.AddResult(Result(Builder.TakeString()));
  =20
   // @protocol ( protocol-name )
+  Builder.AddResultTypeChunk("Protocol *");
   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
   Builder.AddPlaceholderChunk("protocol-name");
@@ -4183,16 +4406,38 @@
   Results.AddResult(Result(Builder.TakeString()));
=20
   // @selector ( selector )
+  Builder.AddResultTypeChunk("SEL");
   Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
   Builder.AddPlaceholderChunk("selector");
   Builder.AddChunk(CodeCompletionString::CK_RightParen);
   Results.AddResult(Result(Builder.TakeString()));
+ =20
+  // @[ objects, ... ]
+  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,[));
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddPlaceholderChunk("objects, ...");
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddChunk(CodeCompletionString::CK_RightBracket);
+  Results.AddResult(Result(Builder.TakeString()));
+
+  // @{ key : object, ... }
+  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,{));
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddPlaceholderChunk("key");
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddChunk(CodeCompletionString::CK_Colon);
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddPlaceholderChunk("object, ...");
+  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
+  Results.AddResult(Result(Builder.TakeString()));
 }
=20
 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
   typedef CodeCompletionResult Result;
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
  =20
   if (Results.includeCodePatterns()) {
     // @try { statements } @catch ( declaration ) { statements } @finally
@@ -4248,9 +4493,10 @@
=20
 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
-  AddObjCVisibilityResults(getLangOptions(), Results, false);
+  AddObjCVisibilityResults(getLangOpts(), Results, false);
   Results.ExitScope();
   HandleCodeCompleteResults(this, CodeCompleter,=20
                             CodeCompletionContext::CCC_Other,
@@ -4259,6 +4505,7 @@
=20
 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
   AddObjCStatementResults(Results, false);
@@ -4271,6 +4518,7 @@
=20
 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
   AddObjCExpressionResults(Results, false);
@@ -4324,6 +4572,7 @@
  =20
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
@@ -4346,14 +4595,16 @@
   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
     Results.AddResult(CodeCompletionResult("atomic"));
   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
-    CodeCompletionBuilder Setter(Results.getAllocator());
+    CodeCompletionBuilder Setter(Results.getAllocator(),
+                                 Results.getCodeCompletionTUInfo());
     Setter.AddTypedTextChunk("setter");
     Setter.AddTextChunk(" =3D ");
     Setter.AddPlaceholderChunk("method");
     Results.AddResult(CodeCompletionResult(Setter.TakeString()));
   }
   if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
-    CodeCompletionBuilder Getter(Results.getAllocator());
+    CodeCompletionBuilder Getter(Results.getAllocator(),
+                                 Results.getCodeCompletionTUInfo());
     Getter.AddTypedTextChunk("getter");
     Getter.AddTextChunk(" =3D ");
     Getter.AddPlaceholderChunk("method");
@@ -4467,23 +4718,25 @@
  =20
   // Visit the protocols of protocols.
   if (ObjCProtocolDecl *Protocol =3D dyn_cast<ObjCProtocolDecl>(Container)=
) {
-    const ObjCList<ObjCProtocolDecl> &Protocols
-      =3D Protocol->getReferencedProtocols();
-    for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
-                                              E =3D Protocols.end();=20
-         I !=3D E; ++I)
-      AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelI=
dents,=20
-                     CurContext, Selectors, AllowSameLength, Results, fals=
e);   =20
+    if (Protocol->hasDefinition()) {
+      const ObjCList<ObjCProtocolDecl> &Protocols
+        =3D Protocol->getReferencedProtocols();
+      for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
+                                                E =3D Protocols.end();=20
+           I !=3D E; ++I)
+        AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,=20
+                       NumSelIdents, CurContext, Selectors, AllowSameLengt=
h,=20
+                       Results, false);
+    }
   }
  =20
   ObjCInterfaceDecl *IFace =3D dyn_cast<ObjCInterfaceDecl>(Container);
-  if (!IFace)
+  if (!IFace || !IFace->hasDefinition())
     return;
  =20
   // Add methods in protocols.
-  const ObjCList<ObjCProtocolDecl> &Protocols=3D IFace->getReferencedProto=
cols();
-  for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
-                                            E =3D Protocols.end();=20
+  for (ObjCInterfaceDecl::protocol_iterator I =3D IFace->protocol_begin(),
+                                            E =3D IFace->protocol_end();
        I !=3D E; ++I)
     AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIde=
nts,=20
                    CurContext, Selectors, AllowSameLength, Results, false);
@@ -4542,6 +4795,7 @@
=20
   // Find all of the potential getters.
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
=20
@@ -4571,6 +4825,7 @@
=20
   // Find all of the potential getters.
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
=20
@@ -4588,6 +4843,7 @@
                                        bool IsParameter) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Type);
   Results.EnterNewScope();
  =20
@@ -4619,16 +4875,16 @@
   //   IBAction)<#selector#>:(id)sender
   if (DS.getObjCDeclQualifier() =3D=3D 0 && !IsParameter &&
       Context.Idents.get("IBAction").hasMacroDefinition()) {
-    typedef CodeCompletionString::Chunk Chunk;
-    CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern,=20
-                                  CXAvailability_Available);
+    CodeCompletionBuilder Builder(Results.getAllocator(),
+                                  Results.getCodeCompletionTUInfo(),
+                                  CCP_CodePattern, CXAvailability_Availabl=
e);
     Builder.AddTypedTextChunk("IBAction");
-    Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
+    Builder.AddChunk(CodeCompletionString::CK_RightParen);
     Builder.AddPlaceholderChunk("selector");
-    Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon));
-    Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
+    Builder.AddChunk(CodeCompletionString::CK_Colon);
+    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
     Builder.AddTextChunk("id");
-    Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen));
+    Builder.AddChunk(CodeCompletionString::CK_RightParen);
     Builder.AddTextChunk("sender");
     Results.AddResult(CodeCompletionResult(Builder.TakeString()));
   }
@@ -4792,7 +5048,8 @@
   }
  =20
   // We have a superclass method. Now, form the send-to-super completion.
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
  =20
   // Give this completion a return type.
   AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMetho=
d,=20
@@ -4838,18 +5095,19 @@
     }
   }
  =20
-  Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCo=
mpletion,
-                                         SuperMethod->isInstanceMethod()
-                                           ? CXCursor_ObjCInstanceMethodDe=
cl
-                                           : CXCursor_ObjCClassMethodDecl)=
);
+  Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
+                                         CCP_SuperCompletion));
   return SuperMethod;
 }
                                   =20
 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_ObjCMessageReceiver,
-                        &ResultBuilder::IsObjCMessageReceiver);
+                        getLangOpts().CPlusPlus0x
+                          ? &ResultBuilder::IsObjCMessageReceiverOrLambdaC=
apture
+                          : &ResultBuilder::IsObjCMessageReceiver);
  =20
   CodeCompletionDeclConsumer Consumer(Results, CurContext);
   Results.EnterNewScope();
@@ -4866,6 +5124,9 @@
         AddSuperSendCompletion(*this, /*NeedSuperKeyword=3D*/true, 0, 0, R=
esults);
       }
  =20
+  if (getLangOpts().CPlusPlus0x)
+    addThisCompletion(*this, Results);
+ =20
   Results.ExitScope();
  =20
   if (CodeCompleter->includeMacros())
@@ -4919,9 +5180,11 @@
     } else {
       // Assume that "super" names some kind of value and parse that way.
       CXXScopeSpec SS;
+      SourceLocation TemplateKWLoc;
       UnqualifiedId id;
       id.setIdentifier(Super, SuperLoc);
-      ExprResult SuperExpr =3D ActOnIdExpression(S, SS, id, false, false);
+      ExprResult SuperExpr =3D ActOnIdExpression(S, SS, TemplateKWLoc, id,
+                                               false, false);
       return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
                                              SelIdents, NumSelIdents,
                                              AtArgumentExpression);
@@ -5061,6 +5324,7 @@
   QualType T =3D this->GetTypeFromParser(Receiver);
  =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
               CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMe=
ssage,
                                     T, SelIdents, NumSelIdents));
    =20
@@ -5126,6 +5390,7 @@
=20
   // Build the set of methods we can see.
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
            CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMe=
ssage,
                                  ReceiverType, SelIdents, NumSelIdents));
  =20
@@ -5277,6 +5542,7 @@
   }
  =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_SelectorName);
   Results.EnterNewScope();
   for (GlobalMethodPool::iterator M =3D MethodPool.begin(),
@@ -5287,7 +5553,8 @@
     if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
       continue;
=20
-    CodeCompletionBuilder Builder(Results.getAllocator());
+    CodeCompletionBuilder Builder(Results.getAllocator(),
+                                  Results.getCodeCompletionTUInfo());
     if (Sel.isUnarySelector()) {
       Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
                                                        Sel.getNameForSlot(=
0)));
@@ -5330,25 +5597,15 @@
        D !=3D DEnd; ++D) {
     // Record any protocols we find.
     if (ObjCProtocolDecl *Proto =3D dyn_cast<ObjCProtocolDecl>(*D))
-      if (!OnlyForwardDeclarations || Proto->isForwardDecl())
+      if (!OnlyForwardDeclarations || !Proto->hasDefinition())
         Results.AddResult(Result(Proto, 0), CurContext, 0, false);
-
-    // Record any forward-declared protocols we find.
-    if (ObjCForwardProtocolDecl *Forward
-          =3D dyn_cast<ObjCForwardProtocolDecl>(*D)) {
-      for (ObjCForwardProtocolDecl::protocol_iterator=20
-             P =3D Forward->protocol_begin(),
-             PEnd =3D Forward->protocol_end();
-           P !=3D PEnd; ++P)
-        if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
-          Results.AddResult(Result(*P, 0), CurContext, 0, false);
-    }
   }
 }
=20
 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
                                               unsigned NumProtocols) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_ObjCProtocolName);
  =20
   if (CodeCompleter && CodeCompleter->includeGlobals()) {
@@ -5376,6 +5633,7 @@
=20
 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_ObjCProtocolName);
  =20
   if (CodeCompleter && CodeCompleter->includeGlobals()) {
@@ -5406,23 +5664,15 @@
        D !=3D DEnd; ++D) {
     // Record any interfaces we find.
     if (ObjCInterfaceDecl *Class =3D dyn_cast<ObjCInterfaceDecl>(*D))
-      if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
+      if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
           (!OnlyUnimplemented || !Class->getImplementation()))
         Results.AddResult(Result(Class, 0), CurContext, 0, false);
-
-    // Record any forward-declared interfaces we find.
-    if (ObjCClassDecl *Forward =3D dyn_cast<ObjCClassDecl>(*D)) {
-      ObjCInterfaceDecl *IDecl =3D Forward->getForwardInterfaceDecl();
-      if ((!OnlyForwardDeclarations || IDecl->isForwardDecl()) &&
-          (!OnlyUnimplemented || !IDecl->getImplementation()))
-        Results.AddResult(Result(IDecl, 0), CurContext,
-                          0, false);
-    }
   }
 }
=20
 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {=20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
  =20
@@ -5442,6 +5692,7 @@
 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
                                       SourceLocation ClassNameLoc) {=20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_ObjCInterfaceName);
   Results.EnterNewScope();
  =20
@@ -5466,6 +5717,7 @@
=20
 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {=20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
=20
@@ -5488,6 +5740,7 @@
   typedef CodeCompletionResult Result;
  =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_ObjCCategoryName);
  =20
   // Ignore any categories we find that have already been implemented by t=
his
@@ -5531,6 +5784,7 @@
     return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
    =20
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_ObjCCategoryName);
  =20
   // Add all of the categories that have have corresponding interface=20
@@ -5559,6 +5813,7 @@
 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
=20
   // Figure out where this @synthesize lives.
@@ -5599,6 +5854,7 @@
                                                   IdentifierInfo *Property=
Name) {
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
=20
   // Figure out where this @synthesize lives.
@@ -5668,7 +5924,8 @@
     unsigned Priority =3D CCP_MemberDeclaration + 1;
     typedef CodeCompletionResult Result;
     CodeCompletionAllocator &Allocator =3D Results.getAllocator();
-    CodeCompletionBuilder Builder(Allocator, Priority,CXAvailability_Avail=
able);
+    CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUIn=
fo(),
+                                  Priority,CXAvailability_Available);
=20
     PrintingPolicy Policy =3D getCompletionPrintingPolicy(*this);
     Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Conte=
xt,
@@ -5702,6 +5959,9 @@
                                      bool InOriginalClass =3D true) {
   if (ObjCInterfaceDecl *IFace =3D dyn_cast<ObjCInterfaceDecl>(Container))=
 {
     // Recurse into protocols.
+    if (!IFace->hasDefinition())
+      return;
+   =20
     const ObjCList<ObjCProtocolDecl> &Protocols
       =3D IFace->getReferencedProtocols();
     for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
@@ -5742,14 +6002,16 @@
   }
=20
   if (ObjCProtocolDecl *Protocol =3D dyn_cast<ObjCProtocolDecl>(Container)=
) {
-    // Recurse into protocols.
-    const ObjCList<ObjCProtocolDecl> &Protocols
-      =3D Protocol->getReferencedProtocols();
-    for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
-           E =3D Protocols.end();=20
-         I !=3D E; ++I)
-      FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnTyp=
e,
-                               KnownMethods, false);
+    if (Protocol->hasDefinition()) {
+      // Recurse into protocols.
+      const ObjCList<ObjCProtocolDecl> &Protocols
+        =3D Protocol->getReferencedProtocols();
+      for (ObjCList<ObjCProtocolDecl>::iterator I =3D Protocols.begin(),
+             E =3D Protocols.end();=20
+           I !=3D E; ++I)
+        FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnT=
ype,
+                                 KnownMethods, false);
+    }
   }
=20
   // Add methods in this container. This operation occurs last because
@@ -5771,10 +6033,14 @@
 /// \brief Add the parenthesized return or parameter type chunk to a code=20
 /// completion string.
 static void AddObjCPassingTypeChunk(QualType Type,
+                                    unsigned ObjCDeclQuals,
                                     ASTContext &Context,
                                     const PrintingPolicy &Policy,
                                     CodeCompletionBuilder &Builder) {
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
+  std::string Quals =3D formatObjCParamQualifiers(ObjCDeclQuals);
+  if (!Quals.empty())
+    Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
   Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
                                                Builder.getAllocator()));
   Builder.AddChunk(CodeCompletionString::CK_RightParen);
@@ -5810,7 +6076,7 @@
   // Builder that will create each code completion.
   typedef CodeCompletionResult Result;
   CodeCompletionAllocator &Allocator =3D Results.getAllocator();
-  CodeCompletionBuilder Builder(Allocator);
+  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo=
());
  =20
   // The selector table.
   SelectorTable &Selectors =3D Context.Selectors;
@@ -5849,7 +6115,8 @@
       KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
       ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
     if (ReturnType.isNull())
-      AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builde=
r);
+      AddObjCPassingTypeChunk(Property->getType(), /*Quals=3D*/0,
+                              Context, Policy, Builder);
    =20
     Builder.AddTypedTextChunk(Key);
     Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,=20
@@ -5895,7 +6162,8 @@
       Builder.AddTypedTextChunk(
                                 Allocator.CopyString(SelectorId->getName()=
));
       Builder.AddTypedTextChunk(":");
-      AddObjCPassingTypeChunk(Property->getType(), Context, Policy, Builde=
r);
+      AddObjCPassingTypeChunk(Property->getType(), /*Quals=3D*/0,
+                              Context, Policy, Builder);
       Builder.AddTextChunk(Key);
       Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,=20
                                CXCursor_ObjCInstanceMethodDecl));
@@ -6464,6 +6732,7 @@
   // Add declarations or definitions for each of the known methods.
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
   Results.EnterNewScope();
   PrintingPolicy Policy =3D getCompletionPrintingPolicy(*this);
@@ -6471,13 +6740,16 @@
                               MEnd =3D KnownMethods.end();
        M !=3D MEnd; ++M) {
     ObjCMethodDecl *Method =3D M->second.first;
-    CodeCompletionBuilder Builder(Results.getAllocator());
+    CodeCompletionBuilder Builder(Results.getAllocator(),
+                                  Results.getCodeCompletionTUInfo());
    =20
     // If the result type was not already provided, add it to the
     // pattern as (type).
     if (ReturnType.isNull())
-      AddObjCPassingTypeChunk(Method->getResultType(), Context, Policy,=20
-                              Builder);
+      AddObjCPassingTypeChunk(Method->getResultType(),
+                              Method->getObjCDeclQualifier(),
+                              Context, Policy,
+                              Builder);=20
=20
     Selector Sel =3D Method->getSelector();
=20
@@ -6501,7 +6773,9 @@
         break;
=20
       // Add the parameter type.
-      AddObjCPassingTypeChunk((*P)->getOriginalType(), Context, Policy,=20
+      AddObjCPassingTypeChunk((*P)->getOriginalType(),
+                              (*P)->getObjCDeclQualifier(),
+                              Context, Policy,
                               Builder);
      =20
       if (IdentifierInfo *Id =3D (*P)->getIdentifier())
@@ -6536,15 +6810,12 @@
     if (!M->second.second)
       Priority +=3D CCD_InBaseClass;
    =20
-    Results.AddResult(Result(Builder.TakeString(), Priority,=20
-                             Method->isInstanceMethod()
-                               ? CXCursor_ObjCInstanceMethodDecl
-                               : CXCursor_ObjCClassMethodDecl));
+    Results.AddResult(Result(Builder.TakeString(), Method, Priority));
   }
=20
   // Add Key-Value-Coding and Key-Value-Observing accessor methods for all=
 of=20
   // the properties in this class and its categories.
-  if (Context.getLangOptions().ObjC2) {
+  if (Context.getLangOpts().ObjC2) {
     SmallVector<ObjCContainerDecl *, 4> Containers;
     Containers.push_back(SearchDecl);
    =20
@@ -6605,6 +6876,7 @@
   // Build the set of methods we can see.
   typedef CodeCompletionResult Result;
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_Other);
  =20
   if (ReturnTy)
@@ -6627,7 +6899,8 @@
         if (NumSelIdents && NumSelIdents <=3D MethList->Method->param_size=
()) {
           ParmVarDecl *Param =3D MethList->Method->param_begin()[NumSelIde=
nts-1];
           if (Param->getIdentifier()) {
-            CodeCompletionBuilder Builder(Results.getAllocator());
+            CodeCompletionBuilder Builder(Results.getAllocator(),
+                                          Results.getCodeCompletionTUInfo(=
));
             Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
                                            Param->getIdentifier()->getName=
()));
             Results.AddResult(Builder.TakeString());
@@ -6653,11 +6926,13 @@
=20
 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_PreprocessorDirective);
   Results.EnterNewScope();
  =20
   // #if <condition>
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
   Builder.AddTypedTextChunk("if");
   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
   Builder.AddPlaceholderChunk("condition");
@@ -6756,7 +7031,7 @@
   Builder.AddPlaceholderChunk("arguments");
   Results.AddResult(Builder.TakeString());
=20
-  if (getLangOptions().ObjC1) {
+  if (getLangOpts().ObjC1) {
     // #import "header"
     Builder.AddTypedTextChunk("import");
     Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
@@ -6816,11 +7091,13 @@
=20
 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         IsDefinition? CodeCompletionContext::CCC_MacroName
                                     : CodeCompletionContext::CCC_MacroName=
Use);
   if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros()))=
 {
     // Add just the names of macros, not their arguments.   =20
-    CodeCompletionBuilder Builder(Results.getAllocator());
+    CodeCompletionBuilder Builder(Results.getAllocator(),
+                                  Results.getCodeCompletionTUInfo());
     Results.EnterNewScope();
     for (Preprocessor::macro_iterator M =3D PP.macro_begin(),=20
                                    MEnd =3D PP.macro_end();
@@ -6840,6 +7117,7 @@
=20
 void Sema::CodeCompletePreprocessorExpression() {
   ResultBuilder Results(*this, CodeCompleter->getAllocator(),
+                        CodeCompleter->getCodeCompletionTUInfo(),
                         CodeCompletionContext::CCC_PreprocessorExpression);
  =20
   if (!CodeCompleter || CodeCompleter->includeMacros())
@@ -6847,7 +7125,8 @@
  =20
     // defined (<macro>)
   Results.EnterNewScope();
-  CodeCompletionBuilder Builder(Results.getAllocator());
+  CodeCompletionBuilder Builder(Results.getAllocator(),
+                                Results.getCodeCompletionTUInfo());
   Builder.AddTypedTextChunk("defined");
   Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
   Builder.AddChunk(CodeCompletionString::CK_LeftParen);
@@ -6879,8 +7158,10 @@
 }
=20
 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
+                                       CodeCompletionTUInfo &CCTUInfo,
                  SmallVectorImpl<CodeCompletionResult> &Results) {
-  ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recov=
ery);
+  ResultBuilder Builder(*this, Allocator, CCTUInfo,
+                        CodeCompletionContext::CCC_Recovery);
   if (!CodeCompleter || CodeCompleter->includeGlobals()) {
     CodeCompletionDeclConsumer Consumer(Builder,=20
                                         Context.getTranslationUnitDecl());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaDecl.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaDecl.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -18,7 +18,6 @@
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/ScopeInfo.h"
 #include "TypeLocBuilder.h"
-#include "clang/AST/APValue.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/CXXInheritance.h"
@@ -40,6 +39,7 @@
 #include "clang/Lex/Preprocessor.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/ModuleLoader.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/Triple.h"
 #include <algorithm>
 #include <cstring>
@@ -56,6 +56,30 @@
   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
 }
=20
+namespace {
+
+class TypeNameValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid)=
 {
+    WantExpressionKeywords =3D false;
+    WantCXXNamedCasts =3D false;
+    WantRemainingKeywords =3D false;
+  }
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    if (NamedDecl *ND =3D candidate.getCorrectionDecl())
+      return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
+          (AllowInvalidDecl || !ND->isInvalidDecl());
+    else
+      return candidate.isKeyword();
+  }
+
+ private:
+  bool AllowInvalidDecl;
+};
+
+}
+
 /// \brief If the identifier refers to a type name within this scope,
 /// return the declaration of that type.
 ///
@@ -71,6 +95,7 @@
                              Scope *S, CXXScopeSpec *SS,
                              bool isClassName, bool HasTrailingDot,
                              ParsedType ObjectTypePtr,
+                             bool IsCtorOrDtorName,
                              bool WantNontrivialTypeSourceInfo,
                              IdentifierInfo **CorrectedII) {
   // Determine where we will perform name lookup.
@@ -93,7 +118,7 @@
         //
         // We therefore do not perform any name lookup if the result would
         // refer to a member of an unknown specialization.
-        if (!isClassName)
+        if (!isClassName && !IsCtorOrDtorName)
           return ParsedType();
        =20
         // We know from the grammar that this name refers to a type,
@@ -148,9 +173,9 @@
   case LookupResult::NotFound:
   case LookupResult::NotFoundInCurrentInstantiation:
     if (CorrectedII) {
+      TypeNameValidatorCCC Validator(true);
       TypoCorrection Correction =3D CorrectTypo(Result.getLookupNameInfo(),
-                                              Kind, S, SS, 0, false,
-                                              Sema::CTC_Type);
+                                              Kind, S, SS, Validator);
       IdentifierInfo *NewII =3D Correction.getCorrectionAsIdentifierInfo();
       TemplateTy Template;
       bool MemberOfUnknownSpecialization;
@@ -166,16 +191,17 @@
           // Ignore a correction to a template type as the to-be-corrected
           // identifier is not a template (typo correction for template na=
mes
           // is handled elsewhere).
-          !(getLangOptions().CPlusPlus && NewSSPtr &&
+          !(getLangOpts().CPlusPlus && NewSSPtr &&
             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
                            false, Template, MemberOfUnknownSpecialization)=
)) {
         ParsedType Ty =3D getTypeName(*NewII, NameLoc, S, NewSSPtr,
                                     isClassName, HasTrailingDot, ObjectTyp=
ePtr,
+                                    IsCtorOrDtorName,
                                     WantNontrivialTypeSourceInfo);
         if (Ty) {
-          std::string CorrectedStr(Correction.getAsString(getLangOptions()=
));
+          std::string CorrectedStr(Correction.getAsString(getLangOpts()));
           std::string CorrectedQuotedStr(
-              Correction.getQuoted(getLangOptions()));
+              Correction.getQuoted(getLangOpts()));
           Diag(NameLoc, diag::err_unknown_typename_suggest)
               << Result.getLookupName() << CorrectedQuotedStr
               << FixItHint::CreateReplacement(SourceRange(NameLoc),
@@ -249,8 +275,11 @@
=20
     if (T.isNull())
       T =3D Context.getTypeDeclType(TD);
-   =20
-    if (SS && SS->isNotEmpty()) {
+
+    // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
+    // constructor or destructor name (in such a case, the scope specifier
+    // will be attached to the enclosing Expr or Decl node).
+    if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
       if (WantNontrivialTypeSourceInfo) {
         // Construct a type with type-source information.
         TypeLocBuilder Builder;
@@ -258,7 +287,7 @@
        =20
         T =3D getElaboratedType(ETK_None, *SS, T);
         ElaboratedTypeLoc ElabTL =3D Builder.push<ElaboratedTypeLoc>(T);
-        ElabTL.setKeywordLoc(SourceLocation());
+        ElabTL.setElaboratedKeywordLoc(SourceLocation());
         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
       } else {
@@ -292,7 +321,6 @@
   if (R.getResultKind() =3D=3D LookupResult::Found)
     if (const TagDecl *TD =3D R.getAsSingle<TagDecl>()) {
       switch (TD->getTagKind()) {
-      default:         return DeclSpec::TST_unspecified;
       case TTK_Struct: return DeclSpec::TST_struct;
       case TTK_Union:  return DeclSpec::TST_union;
       case TTK_Class:  return DeclSpec::TST_class;
@@ -341,46 +369,44 @@
  =20
   // There may have been a typo in the name of the type. Look up typo
   // results, in case we have something that we can suggest.
+  TypeNameValidatorCCC Validator(false);
   if (TypoCorrection Corrected =3D CorrectTypo(DeclarationNameInfo(&II, II=
Loc),
-                                             LookupOrdinaryName, S, SS, NU=
LL,
-                                             false, CTC_Type)) {
-    std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
-    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
+                                             LookupOrdinaryName, S, SS,
+                                             Validator)) {
+    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
+    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
=20
     if (Corrected.isKeyword()) {
       // We corrected to a keyword.
       // FIXME: Actually recover with the keyword we suggest, and emit a f=
ix-it.
       Diag(IILoc, diag::err_unknown_typename_suggest)
         << &II << CorrectedQuotedStr;
-      return true;     =20
     } else {
       NamedDecl *Result =3D Corrected.getCorrectionDecl();
-      if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
-          !Result->isInvalidDecl()) {
-        // We found a similarly-named type or interface; suggest that.
-        if (!SS || !SS->isSet())
-          Diag(IILoc, diag::err_unknown_typename_suggest)
-            << &II << CorrectedQuotedStr
-            << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedS=
tr);
-        else if (DeclContext *DC =3D computeDeclContext(*SS, false))
-          Diag(IILoc, diag::err_unknown_nested_typename_suggest)=20
-            << &II << DC << CorrectedQuotedStr << SS->getRange()
-            << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedS=
tr);
-        else
-          llvm_unreachable("could not have corrected a typo here");
-
-        Diag(Result->getLocation(), diag::note_previous_decl)
-          << CorrectedQuotedStr;
-       =20
-        SuggestedType =3D getTypeName(*Result->getIdentifier(), IILoc, S, =
SS,
-                                    false, false, ParsedType(),
-                                    /*NonTrivialTypeSourceInfo=3D*/true);
-        return true;
-      }
-    }
-  }
-
-  if (getLangOptions().CPlusPlus) {
+      // We found a similarly-named type or interface; suggest that.
+      if (!SS || !SS->isSet())
+        Diag(IILoc, diag::err_unknown_typename_suggest)
+          << &II << CorrectedQuotedStr
+          << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr=
);
+      else if (DeclContext *DC =3D computeDeclContext(*SS, false))
+        Diag(IILoc, diag::err_unknown_nested_typename_suggest)
+          << &II << DC << CorrectedQuotedStr << SS->getRange()
+          << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr=
);
+      else
+        llvm_unreachable("could not have corrected a typo here");
+
+      Diag(Result->getLocation(), diag::note_previous_decl)
+        << CorrectedQuotedStr;
+
+      SuggestedType =3D getTypeName(*Result->getIdentifier(), IILoc, S, SS,
+                                  false, false, ParsedType(),
+                                  /*IsCtorOrDtorName=3D*/false,
+                                  /*NonTrivialTypeSourceInfo=3D*/true);
+    }
+    return true;
+  }
+
+  if (getLangOpts().CPlusPlus) {
     // See if II is a class template that the user forgot to pass argument=
s to.
     UnqualifiedId Name;
     Name.setIdentifier(&II, IILoc);
@@ -410,14 +436,15 @@
       << &II << DC << SS->getRange();
   else if (isDependentScopeSpecifier(*SS)) {
     unsigned DiagID =3D diag::err_typename_missing;
-    if (getLangOptions().MicrosoftMode && isMicrosoftMissingTypename(SS, S=
))
+    if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
       DiagID =3D diag::warn_typename_missing;
=20
     Diag(SS->getRange().getBegin(), DiagID)
       << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
       << SourceRange(SS->getRange().getBegin(), IILoc)
       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "=
);
-    SuggestedType =3D ActOnTypenameType(S, SourceLocation(), *SS, II, IILo=
c).get();
+    SuggestedType =3D ActOnTypenameType(S, SourceLocation(), *SS, II, IILo=
c)
+                                                                         .=
get();
   } else {
     assert(SS && SS->isInvalid() &&=20
            "Invalid scope specifier has already been diagnosed");
@@ -429,7 +456,7 @@
 /// \brief Determine whether the given result set contains either a type n=
ame
 /// or=20
 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken=
) {
-  bool CheckTemplate =3D R.getSema().getLangOptions().CPlusPlus &&
+  bool CheckTemplate =3D R.getSema().getLangOpts().CPlusPlus &&
                        NextToken.is(tok::less);
  =20
   for (LookupResult::iterator I =3D R.begin(), IEnd =3D R.end(); I !=3D IE=
nd; ++I) {
@@ -481,7 +508,7 @@
     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
       // In C++, this is an ADL-only call.
       // FIXME: Reference?
-      if (getLangOptions().CPlusPlus)
+      if (getLangOpts().CPlusPlus)
         return BuildDeclarationNameExpr(SS, Result, /*ADL=3D*/true);
      =20
       // C90 6.3.2.2:
@@ -506,7 +533,7 @@
     // In C, we first see whether there is a tag type by the same name, in=20
     // which case it's likely that the user just forget to write "enum",=20
     // "struct", or "union".
-    if (!getLangOptions().CPlusPlus && !SecondTry) {
+    if (!getLangOpts().CPlusPlus && !SecondTry) {
       Result.clear(LookupTagName);
       LookupParsedName(Result, S, &SS);
       if (TagDecl *Tag =3D Result.getAsSingle<TagDecl>()) {
@@ -535,7 +562,7 @@
         }
=20
         Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
-          << Name << TagName << getLangOptions().CPlusPlus
+          << Name << TagName << getLangOpts().CPlusPlus
           << FixItHint::CreateInsertion(NameLoc, FixItTagName);
         break;
       }
@@ -547,17 +574,19 @@
     // close to this name.
     if (!SecondTry) {
       SecondTry =3D true;
+      CorrectionCandidateCallback DefaultValidator;
       if (TypoCorrection Corrected =3D CorrectTypo(Result.getLookupNameInf=
o(),
-                                                 Result.getLookupKind(), S=
, &SS)) {
+                                                 Result.getLookupKind(), S=
,=20
+                                                 &SS, DefaultValidator)) {
         unsigned UnqualifiedDiag =3D diag::err_undeclared_var_use_suggest;
         unsigned QualifiedDiag =3D diag::err_no_member_suggest;
-        std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
-        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions(=
)));
+        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
+        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
        =20
         NamedDecl *FirstDecl =3D Corrected.getCorrectionDecl();
         NamedDecl *UnderlyingFirstDecl
           =3D FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
-        if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
+        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl))=
 {
           UnqualifiedDiag =3D diag::err_no_template_suggest;
           QualifiedDiag =3D diag::err_no_member_template_suggest;
@@ -582,19 +611,19 @@
         // Update the name, so that the caller has the new name.
         Name =3D Corrected.getCorrectionAsIdentifierInfo();
        =20
+        // Typo correction corrected to a keyword.
+        if (Corrected.isKeyword())
+          return Corrected.getCorrectionAsIdentifierInfo();
+
         // Also update the LookupResult...
         // FIXME: This should probably go away at some point
         Result.clear();
         Result.setLookupName(Corrected.getCorrection());
-        if (FirstDecl) Result.addDecl(FirstDecl);
-
-        // Typo correction corrected to a keyword.
-        if (Corrected.isKeyword())
-          return Corrected.getCorrectionAsIdentifierInfo();
-       =20
-        if (FirstDecl)
+        if (FirstDecl) {
+          Result.addDecl(FirstDecl);
           Diag(FirstDecl->getLocation(), diag::note_previous_decl)
             << CorrectedQuotedStr;
+        }
=20
         // If we found an Objective-C instance variable, let
         // LookupInObjCMethod build the appropriate expression to
@@ -614,7 +643,7 @@
     Result.suppressDiagnostics();
     return NameClassification::Unknown();
      =20
-  case LookupResult::NotFoundInCurrentInstantiation:
+  case LookupResult::NotFoundInCurrentInstantiation: {
     // We performed name lookup into the current instantiation, and there =
were=20
     // dependent bases, so we treat this result the same way as any other
     // dependent nested-name-specifier.
@@ -629,7 +658,9 @@
     // perform some heroics to see if we actually have a=20
     // template-argument-list, which would indicate a missing 'template'
     // keyword here.
-    return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=3D*/0);
+    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=3D*/SourceLocatio=
n(),
+                                     NameInfo, /*TemplateArgs=3D*/0);
+  }
=20
   case LookupResult::Found:
   case LookupResult::FoundOverloaded:
@@ -637,7 +668,7 @@
     break;
      =20
   case LookupResult::Ambiguous:
-    if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
+    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
         hasAnyAcceptableTemplateNames(Result)) {
       // C++ [temp.local]p3:
       //   A lookup that finds an injected-class-name (10.2) can result in=
 an
@@ -661,7 +692,7 @@
     return NameClassification::Error();
   }
  =20
-  if (getLangOptions().CPlusPlus && NextToken.is(tok::less) &&
+  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
     // C++ [temp.names]p3:
     //   After name lookup (3.4) finds that a name is a template-name or t=
hat
@@ -735,7 +766,7 @@
   }
  =20
   if (!Result.empty() && (*Result.begin())->isCXXClassMember())
-    return BuildPossibleImplicitMemberExpr(SS, Result, 0);
+    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0=
);
=20
   bool ADL =3D UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_=
paren));
   return BuildDeclarationNameExpr(SS, Result, ADL);
@@ -841,7 +872,13 @@
   if (!FD)
     return;
=20
-  PushDeclContext(S, FD);
+  // Same implementation as PushDeclContext, but enters the context
+  // from the lexical parent, rather than the top-level class.
+  assert(CurContext =3D=3D FD->getLexicalParent() &&
+    "The next DeclContext should be lexically contained in the current one=
.");
+  CurContext =3D FD;
+  S->setEntity(CurContext);
+
   for (unsigned P =3D 0, NumParams =3D FD->getNumParams(); P < NumParams; =
++P) {
     ParmVarDecl *Param =3D FD->getParamDecl(P);
     // If the parameter has an identifier, then add it to the scope
@@ -853,6 +890,15 @@
 }
=20
=20
+void Sema::ActOnExitFunctionContext() {
+  // Same implementation as PopDeclContext, but returns to the lexical par=
ent,
+  // rather than the top-level class.
+  assert(CurContext && "DeclContext imbalance!");
+  CurContext =3D CurContext->getLexicalParent();
+  assert(CurContext && "Popped translation unit!");
+}
+
+
 /// \brief Determine whether we allow overloading of the function
 /// PrevDecl with another declaration.
 ///
@@ -864,7 +910,7 @@
 /// attribute.
 static bool AllowOverloadingOfFunction(LookupResult &Previous,
                                        ASTContext &Context) {
-  if (Context.getLangOptions().CPlusPlus)
+  if (Context.getLangOpts().CPlusPlus)
     return true;
=20
   if (Previous.getResultKind() =3D=3D LookupResult::FoundOverloaded)
@@ -891,7 +937,7 @@
=20
   // Out-of-line definitions shouldn't be pushed into scope in C++.
   // Out-of-line variable and function definitions shouldn't even in C.
-  if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(=
D)) &&
+  if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D))=
 &&
       D->isOutOfLine() &&
       !D->getDeclContext()->getRedeclContext()->Equals(
         D->getLexicalDeclContext()->getRedeclContext()))
@@ -936,6 +982,11 @@
   }
 }
=20
+void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
+  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
+    TUScope->AddDecl(D);
+}
+
 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
                          bool ExplicitInstantiationOrSpecialization) {
   return IdResolver.isDeclInScope(D, Ctx, Context, S,
@@ -1089,7 +1140,7 @@
   if (D->isInvalidDecl())
     return false;
=20
-  if (D->isUsed() || D->hasAttr<UnusedAttr>())
+  if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
     return false;
=20
   if (isa<LabelDecl>(D))
@@ -1101,7 +1152,7 @@
     return false;
=20
   // Types of valid local variables should be complete, so this should suc=
ceed.
-  if (const ValueDecl *VD =3D dyn_cast<ValueDecl>(D)) {
+  if (const VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
=20
     // White-list anything with an __attribute__((unused)) type.
     QualType Ty =3D VD->getType();
@@ -1123,11 +1174,18 @@
         return false;
=20
       if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(Tag)) {
-        // FIXME: Checking for the presence of a user-declared constructor
-        // isn't completely accurate; we'd prefer to check that the initia=
lizer
-        // has no side effects.
-        if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor(=
))
+        if (!RD->hasTrivialDestructor())
           return false;
+
+        if (const Expr *Init =3D VD->getInit()) {
+          const CXXConstructExpr *Construct =3D
+            dyn_cast<CXXConstructExpr>(Init);
+          if (Construct && !Construct->isElidable()) {
+            CXXConstructorDecl *CD =3D Construct->getConstructor();
+            if (!CD->isTrivial())
+              return false;
+          }
+        }
       }
     }
=20
@@ -1141,7 +1199,7 @@
                                      FixItHint &Hint) {
   if (isa<LabelDecl>(D)) {
     SourceLocation AfterColon =3D Lexer::findLocationAfterToken(D->getLocE=
nd(),
-                tok::colon, Ctx.getSourceManager(), Ctx.getLangOptions(), =
true);
+                tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), tru=
e);
     if (AfterColon.isInvalid())
       return;
     Hint =3D FixItHint::CreateRemoval(CharSourceRange::
@@ -1206,6 +1264,15 @@
   }
 }
=20
+void Sema::ActOnStartFunctionDeclarator() {
+  ++InFunctionDeclarator;
+}
+
+void Sema::ActOnEndFunctionDeclarator() {
+  assert(InFunctionDeclarator);
+  --InFunctionDeclarator;
+}
+
 /// \brief Look for an Objective-C class in the translation unit.
 ///
 /// \param Id The name of the Objective-C class we're looking for. If
@@ -1229,10 +1296,11 @@
   if (!IDecl && DoTypoCorrection) {
     // Perform typo correction at the given location, but only if we
     // find an Objective-C class name.
-    TypoCorrection C;
-    if ((C =3D CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryN=
ame,
-                         TUScope, NULL, NULL, false, CTC_NoKeywords)) &&
-        (IDecl =3D C.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
+    DeclFilterCCC<ObjCInterfaceDecl> Validator;
+    if (TypoCorrection C =3D CorrectTypo(DeclarationNameInfo(Id, IdLoc),
+                                       LookupOrdinaryName, TUScope, NULL,
+                                       Validator)) {
+      IDecl =3D C.getCorrectionDeclAs<ObjCInterfaceDecl>();
       Diag(IdLoc, diag::err_undef_interface_suggest)
         << Id << IDecl->getDeclName()=20
         << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
@@ -1242,8 +1310,11 @@
       Id =3D IDecl->getIdentifier();
     }
   }
-
-  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
+  ObjCInterfaceDecl *Def =3D dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
+  // This routine must always return a class definition, if any.
+  if (Def && Def->getDefinition())
+      Def =3D Def->getDefinition();
+  return Def;
 }
=20
 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
@@ -1273,7 +1344,7 @@
   while (((S->getFlags() & Scope::DeclScope) =3D=3D 0) ||
          (S->getEntity() &&
           ((DeclContext *)S->getEntity())->isTransparentContext()) ||
-         (S->isClassScope() && !getLangOptions().CPlusPlus))
+         (S->isClassScope() && !getLangOpts().CPlusPlus))
     S =3D S->getParent();
   return S;
 }
@@ -1362,6 +1433,40 @@
   return New;
 }
=20
+bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
+  QualType OldType;
+  if (TypedefNameDecl *OldTypedef =3D dyn_cast<TypedefNameDecl>(Old))
+    OldType =3D OldTypedef->getUnderlyingType();
+  else
+    OldType =3D Context.getTypeDeclType(Old);
+  QualType NewType =3D New->getUnderlyingType();
+
+  if (NewType->isVariablyModifiedType()) {
+    // Must not redefine a typedef with a variably-modified type.
+    int Kind =3D isa<TypeAliasDecl>(Old) ? 1 : 0;
+    Diag(New->getLocation(), diag::err_redefinition_variably_modified_type=
def)
+      << Kind << NewType;
+    if (Old->getLocation().isValid())
+      Diag(Old->getLocation(), diag::note_previous_definition);
+    New->setInvalidDecl();
+    return true;   =20
+  }
+ =20
+  if (OldType !=3D NewType &&
+      !OldType->isDependentType() &&
+      !NewType->isDependentType() &&
+      !Context.hasSameType(OldType, NewType)) {=20
+    int Kind =3D isa<TypeAliasDecl>(Old) ? 1 : 0;
+    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
+      << Kind << NewType << OldType;
+    if (Old->getLocation().isValid())
+      Diag(Old->getLocation(), diag::note_previous_definition);
+    New->setInvalidDecl();
+    return true;
+  }
+  return false;
+}
+
 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
 /// same name and scope as a previous declaration 'Old'.  Figure out
 /// how to resolve this situation, merging decls or emitting
@@ -1374,7 +1479,7 @@
=20
   // Allow multiple definitions for ObjC built-in typedefs.
   // FIXME: Verify the underlying types are equivalent!
-  if (getLangOptions().ObjC1) {
+  if (getLangOpts().ObjC1) {
     const IdentifierInfo *TypeID =3D New->getIdentifier();
     switch (TypeID->getLength()) {
     default: break;
@@ -1420,46 +1525,20 @@
   if (Old->isInvalidDecl())
     return New->setInvalidDecl();
=20
-  // Determine the "old" type we'll use for checking and diagnostics.
-  QualType OldType;
-  if (TypedefNameDecl *OldTypedef =3D dyn_cast<TypedefNameDecl>(Old))
-    OldType =3D OldTypedef->getUnderlyingType();
-  else
-    OldType =3D Context.getTypeDeclType(Old);
-
   // If the typedef types are not identical, reject them in all languages =
and
   // with any extensions enabled.
-
-  if (OldType !=3D New->getUnderlyingType() &&
-      Context.getCanonicalType(OldType) !=3D
-      Context.getCanonicalType(New->getUnderlyingType())) {
-    int Kind =3D 0;
-    if (isa<TypeAliasDecl>(Old))
-      Kind =3D 1;
-    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
-      << Kind << New->getUnderlyingType() << OldType;
-    if (Old->getLocation().isValid())
-      Diag(Old->getLocation(), diag::note_previous_definition);
-    return New->setInvalidDecl();
-  }
+  if (isIncompatibleTypedef(Old, New))
+    return;
=20
   // The types match.  Link up the redeclaration chain if the old
   // declaration was a typedef.
-  // FIXME: this is a potential source of weirdness if the type
-  // spellings don't match exactly.
   if (TypedefNameDecl *Typedef =3D dyn_cast<TypedefNameDecl>(Old))
     New->setPreviousDeclaration(Typedef);
=20
-  // __module_private__ is propagated to later declarations.
-  if (Old->isModulePrivate())
-    New->setModulePrivate();
-  else if (New->isModulePrivate())
-    diagnoseModulePrivateRedeclaration(New, Old);
-          =20
-  if (getLangOptions().MicrosoftExt)
+  if (getLangOpts().MicrosoftExt)
     return;
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // C++ [dcl.typedef]p2:
     //   In a given non-class scope, a typedef specifier can be used to
     //   redefine the name of any type declared in that scope to refer
@@ -1497,6 +1576,10 @@
     return New->setInvalidDecl();
   }
=20
+  // Modules always permit redefinition of typedefs, as does C11.
+  if (getLangOpts().Modules || getLangOpts().C11)
+    return;
+ =20
   // If we have a redefinition of a typedef in C, emit a warning.  This wa=
rning
   // is normally mapped to an error, but can be controlled with
   // -Wtypedef-redefinition.  If either the original or the redefinition is
@@ -1535,36 +1618,37 @@
 }
=20
 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
-static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl,
-                                ASTContext &C, bool mergeDeprecation =3D t=
rue) {
-  if (!oldDecl->hasAttrs())
+void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
+                               bool MergeDeprecation) {
+  if (!Old->hasAttrs())
     return;
=20
-  bool foundAny =3D newDecl->hasAttrs();
+  bool foundAny =3D New->hasAttrs();
=20
   // Ensure that any moving of objects within the allocated map is done be=
fore
   // we process them.
-  if (!foundAny) newDecl->setAttrs(AttrVec());
+  if (!foundAny) New->setAttrs(AttrVec());
=20
   for (specific_attr_iterator<InheritableAttr>
-       i =3D oldDecl->specific_attr_begin<InheritableAttr>(),
-       e =3D oldDecl->specific_attr_end<InheritableAttr>(); i !=3D e; ++i)=
 {
+         i =3D Old->specific_attr_begin<InheritableAttr>(),
+         e =3D Old->specific_attr_end<InheritableAttr>();=20
+       i !=3D e; ++i) {
     // Ignore deprecated/unavailable/availability attributes if requested.
-    if (!mergeDeprecation &&
+    if (!MergeDeprecation &&
         (isa<DeprecatedAttr>(*i) ||=20
          isa<UnavailableAttr>(*i) ||
          isa<AvailabilityAttr>(*i)))
       continue;
=20
-    if (!DeclHasAttr(newDecl, *i)) {
-      InheritableAttr *newAttr =3D cast<InheritableAttr>((*i)->clone(C));
+    if (!DeclHasAttr(New, *i)) {
+      InheritableAttr *newAttr =3D cast<InheritableAttr>((*i)->clone(Conte=
xt));
       newAttr->setInherited(true);
-      newDecl->addAttr(newAttr);
+      New->addAttr(newAttr);
       foundAny =3D true;
     }
   }
=20
-  if (!foundAny) newDecl->dropAttrs();
+  if (!foundAny) New->dropAttrs();
 }
=20
 /// mergeParamDeclAttributes - Copy attributes from the old parameter
@@ -1651,7 +1735,7 @@
 /// merged with.
 ///
 /// Returns true if there was an error, false otherwise.
-bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
+bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
   // Verify the old decl was also a function.
   FunctionDecl *Old =3D 0;
   if (FunctionTemplateDecl *OldFunctionTemplate
@@ -1693,8 +1777,8 @@
   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
       New->getStorageClass() =3D=3D SC_Static &&
       Old->getStorageClass() !=3D SC_Static &&
-      !canRedefineFunction(Old, getLangOptions())) {
-    if (getLangOptions().MicrosoftExt) {
+      !canRedefineFunction(Old, getLangOpts())) {
+    if (getLangOpts().MicrosoftExt) {
       Diag(New->getLocation(), diag::warn_static_non_static) << New;
       Diag(Old->getLocation(), PrevDiag);
     } else {
@@ -1776,7 +1860,7 @@
     NewQType =3D Context.getCanonicalType(New->getType());
   }
  =20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // (C++98 13.1p2):
     //   Certain function declarations cannot be overloaded:
     //     -- Function declarations that differ only in the return type
@@ -1881,14 +1965,14 @@
     }
=20
     if (OldQTypeForComparison =3D=3D NewQType)
-      return MergeCompatibleFunctionDecls(New, Old);
+      return MergeCompatibleFunctionDecls(New, Old, S);
=20
     // Fall through for conflicting redeclarations and redefinitions.
   }
=20
   // C: Function types need to be compatible, not identical. This handles
   // duplicate function decls like "void f(int); void f(enum X);" properly.
-  if (!getLangOptions().CPlusPlus &&
+  if (!getLangOpts().CPlusPlus &&
       Context.typesAreCompatible(OldQType, NewQType)) {
     const FunctionType *OldFuncType =3D OldQType->getAs<FunctionType>();
     const FunctionType *NewFuncType =3D NewQType->getAs<FunctionType>();
@@ -1926,7 +2010,7 @@
       New->setParams(Params);
     }
=20
-    return MergeCompatibleFunctionDecls(New, Old);
+    return MergeCompatibleFunctionDecls(New, Old, S);
   }
=20
   // GNU C permits a K&R definition to follow a prototype declaration
@@ -1940,7 +2024,7 @@
   // the K&R definition becomes variadic.  This is sort of an edge case, b=
ut
   // it's legal per the standard depending on how you read C99 6.7.5.3p15 =
and
   // C99 6.9.1p8.
-  if (!getLangOptions().CPlusPlus &&
+  if (!getLangOpts().CPlusPlus &&
       Old->hasPrototype() && !New->hasPrototype() &&
       New->getType()->getAs<FunctionProtoType>() &&
       Old->getNumParams() =3D=3D New->getNumParams()) {
@@ -1987,7 +2071,7 @@
       New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
                                            ArgTypes.size(),
                                            OldProto->getExtProtoInfo()));
-      return MergeCompatibleFunctionDecls(New, Old);
+      return MergeCompatibleFunctionDecls(New, Old, S);
     }
=20
     // Fall through to diagnose conflicting types.
@@ -2028,9 +2112,10 @@
 /// redeclaration of Old.
 ///
 /// \returns false
-bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *O=
ld) {
+bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *O=
ld,
+                                        Scope *S) {
   // Merge the attributes
-  mergeDeclAttributes(New, Old, Context);
+  mergeDeclAttributes(New, Old);
=20
   // Merge the storage class.
   if (Old->getStorageClass() !=3D SC_Extern &&
@@ -2041,12 +2126,6 @@
   if (Old->isPure())
     New->setPure();
=20
-  // __module_private__ is propagated to later declarations.
-  if (Old->isModulePrivate())
-    New->setModulePrivate();
-  else if (New->isModulePrivate())
-    diagnoseModulePrivateRedeclaration(New, Old);
-
   // Merge attributes from the parameters.  These can mismatch with K&R
   // declarations.
   if (New->getNumParams() =3D=3D Old->getNumParams())
@@ -2054,21 +2133,21 @@
       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
                                Context);
=20
-  if (getLangOptions().CPlusPlus)
-    return MergeCXXFunctionDecl(New, Old);
+  if (getLangOpts().CPlusPlus)
+    return MergeCXXFunctionDecl(New, Old, S);
=20
   return false;
 }
=20
=20
 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
-                                const ObjCMethodDecl *oldMethod) {
+                                ObjCMethodDecl *oldMethod) {
   // We don't want to merge unavailable and deprecated attributes
   // except from interface to implementation.
   bool mergeDeprecation =3D isa<ObjCImplDecl>(newMethod->getDeclContext());
=20
   // Merge the attributes.
-  mergeDeclAttributes(newMethod, oldMethod, Context, mergeDeprecation);
+  mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
=20
   // Merge attributes from the parameters.
   ObjCMethodDecl::param_const_iterator oi =3D oldMethod->param_begin();
@@ -2085,15 +2164,14 @@
 /// emitting diagnostics as appropriate.
 ///
 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call=
 back
-/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We =
can't
-/// check them before the initializer is attached.
-///
+/// to here in AddInitializerToDecl. We can't check them before the initia=
lizer
+/// is attached.
 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
   if (New->isInvalidDecl() || Old->isInvalidDecl())
     return;
=20
   QualType MergedT;
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     AutoType *AT =3D New->getType()->getContainedAutoType();
     if (AT && !AT->isDeduced()) {
       // We don't know what the new type is until the initializer is attac=
hed.
@@ -2175,8 +2253,9 @@
     New->setInvalidDecl();
   }
  =20
-  mergeDeclAttributes(New, Old, Context);
-  // Warn if an already-declared variable is made a weak_import in a subse=
quent declaration
+  mergeDeclAttributes(New, Old);
+  // Warn if an already-declared variable is made a weak_import in a subse=
quent=20
+  // declaration
   if (New->getAttr<WeakImportAttr>() &&
       Old->getStorageClass() =3D=3D SC_None &&
       !Old->getAttr<WeakImportAttr>()) {
@@ -2230,12 +2309,6 @@
     return New->setInvalidDecl();
   }
=20
-  // __module_private__ is propagated to later declarations.
-  if (Old->isModulePrivate())
-    New->setModulePrivate();
-  else if (New->isModulePrivate())
-    diagnoseModulePrivateRedeclaration(New, Old);
-
   // Variables with external linkage are analyzed in FinalizeDeclaratorGro=
up.
=20
   // FIXME: The test for external storage here seems wrong? We still
@@ -2259,7 +2332,7 @@
=20
   // C++ doesn't have tentative definitions, so go right ahead and check h=
ere.
   const VarDecl *Def;
-  if (getLangOptions().CPlusPlus &&
+  if (getLangOpts().CPlusPlus &&
       New->isThisDeclarationADefinition() =3D=3D VarDecl::Definition &&
       (Def =3D Old->getDefinition())) {
     Diag(New->getLocation(), diag::err_redefinition)
@@ -2315,11 +2388,17 @@
     // Note that the above type specs guarantee that the
     // type rep is a Decl, whereas in many of the others
     // it's a Type.
-    Tag =3D dyn_cast<TagDecl>(TagD);
-  }
-
-  if (Tag)
+    if (isa<TagDecl>(TagD))
+      Tag =3D cast<TagDecl>(TagD);
+    else if (ClassTemplateDecl *CTD =3D dyn_cast<ClassTemplateDecl>(TagD))
+      Tag =3D CTD->getTemplatedDecl();
+  }
+
+  if (Tag) {
     Tag->setFreeStanding();
+    if (Tag->isInvalidDecl())
+      return Tag;
+  }
=20
   if (unsigned TypeQuals =3D DS.getTypeQualifiers()) {
     // Enforce C99 6.7.3p2: "Types other than pointer types derived from o=
bject
@@ -2357,22 +2436,20 @@
   bool emittedWarning =3D false;
         =20
   if (RecordDecl *Record =3D dyn_cast_or_null<RecordDecl>(Tag)) {
-    ProcessDeclAttributeList(S, Record, DS.getAttributes().getList());
-   =20
     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
         DS.getStorageClassSpec() !=3D DeclSpec::SCS_typedef) {
-      if (getLangOptions().CPlusPlus ||
+      if (getLangOpts().CPlusPlus ||
           Record->getDeclContext()->isRecord())
         return BuildAnonymousStructOrUnion(S, DS, AS, Record);
=20
-      Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
+      Diag(DS.getLocStart(), diag::ext_no_declarators)
         << DS.getSourceRange();
       emittedWarning =3D true;
     }
   }
=20
   // Check for Microsoft C extension: anonymous struct.
-  if (getLangOptions().MicrosoftExt && !getLangOptions().CPlusPlus &&
+  if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
       CurContext->isRecord() &&
       DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_unspecified) {
     // Handle 2 kinds of anonymous struct:
@@ -2383,13 +2460,13 @@
     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition(=
)) ||
         (DS.getTypeSpecType() =3D=3D DeclSpec::TST_typename &&
          DS.getRepAsType().get()->isStructureType())) {
-      Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct)
+      Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
         << DS.getSourceRange();
       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
     }
   }
  =20
-  if (getLangOptions().CPlusPlus &&=20
+  if (getLangOpts().CPlusPlus &&=20
       DS.getStorageClassSpec() !=3D DeclSpec::SCS_typedef)
     if (EnumDecl *Enum =3D dyn_cast_or_null<EnumDecl>(Tag))
       if (Enum->enumerator_begin() =3D=3D Enum->enumerator_end() &&
@@ -2407,12 +2484,12 @@
     // extension in both Microsoft and GNU.
     if (DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_typedef &&
         Tag && isa<EnumDecl>(Tag)) {
-      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_nam=
e)
+      Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
         << DS.getSourceRange();
       return Tag;
     }
=20
-    Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
+    Diag(DS.getLocStart(), diag::ext_no_declarators)
       << DS.getSourceRange();
     emittedWarning =3D true;
   }
@@ -2453,30 +2530,31 @@
       << Tag->getTagKind()
       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
=20
-  // FIXME: Warn on useless attributes
+  // Warn about ignored type attributes, for example:
+  // __attribute__((aligned)) struct A;
+  // Attributes should be placed after tag to apply to type declaration.
+  if (!DS.getAttributes().empty()) {
+    DeclSpec::TST TypeSpecType =3D DS.getTypeSpecType();
+    if (TypeSpecType =3D=3D DeclSpec::TST_class ||
+        TypeSpecType =3D=3D DeclSpec::TST_struct ||
+        TypeSpecType =3D=3D DeclSpec::TST_union ||
+        TypeSpecType =3D=3D DeclSpec::TST_enum) {
+      AttributeList* attrs =3D DS.getAttributes().getList();
+      while (attrs) {
+        Diag(attrs->getScopeLoc(),
+             diag::warn_declspec_attribute_ignored)
+        << attrs->getName()
+        << (TypeSpecType =3D=3D DeclSpec::TST_class ? 0 :
+            TypeSpecType =3D=3D DeclSpec::TST_struct ? 1 :
+            TypeSpecType =3D=3D DeclSpec::TST_union ? 2 : 3);
+        attrs =3D attrs->getNext();
+      }
+    }
+  }
=20
   return TagD;
 }
=20
-/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
-/// builds a statement for it and returns it so it is evaluated.
-StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) {
-  StmtResult R;
-  if (DS.getTypeSpecType() =3D=3D DeclSpec::TST_typeofExpr) {
-    Expr *Exp =3D DS.getRepAsExpr();
-    QualType Ty =3D Exp->getType();
-    if (Ty->isPointerType()) {
-      do
-        Ty =3D Ty->getAs<PointerType>()->getPointeeType();
-      while (Ty->isPointerType());
-    }
-    if (Ty->isVariableArrayType()) {
-      R =3D ActOnExprStmt(MakeFullExpr(Exp));
-    }
-  }
-  return R;
-}
-
 /// We are trying to inject an anonymous member into the given scope;
 /// check if there's an existing declaration that can't be overloaded.
 ///
@@ -2629,51 +2707,56 @@
=20
 /// BuildAnonymousStructOrUnion - Handle the declaration of an
 /// anonymous structure or union. Anonymous unions are a C++ feature
-/// (C++ [class.union]) and a GNU C extension; anonymous structures
-/// are a GNU C and GNU C++ extension.
+/// (C++ [class.union]) and a C11 feature; anonymous structures
+/// are a C11 feature and GNU C++ extension.
 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
                                              AccessSpecifier AS,
                                              RecordDecl *Record) {
   DeclContext *Owner =3D Record->getDeclContext();
=20
   // Diagnose whether this anonymous struct/union is an extension.
-  if (Record->isUnion() && !getLangOptions().CPlusPlus)
+  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
     Diag(Record->getLocation(), diag::ext_anonymous_union);
-  else if (!Record->isUnion())
-    Diag(Record->getLocation(), diag::ext_anonymous_struct);
+  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
+    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
+  else if (!Record->isUnion() && !getLangOpts().C11)
+    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
=20
   // C and C++ require different kinds of checks for anonymous
   // structs/unions.
   bool Invalid =3D false;
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     const char* PrevSpec =3D 0;
     unsigned DiagID;
-    // C++ [class.union]p3:
-    //   Anonymous unions declared in a named namespace or in the
-    //   global namespace shall be declared static.
-    if (DS.getStorageClassSpec() !=3D DeclSpec::SCS_static &&
-        (isa<TranslationUnitDecl>(Owner) ||
-         (isa<NamespaceDecl>(Owner) &&
-          cast<NamespaceDecl>(Owner)->getDeclName()))) {
-      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
-      Invalid =3D true;
-
-      // Recover by adding 'static'.
-      DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
-                             PrevSpec, DiagID);
-    }
-    // C++ [class.union]p3:
-    //   A storage class is not allowed in a declaration of an
-    //   anonymous union in a class scope.
-    else if (DS.getStorageClassSpec() !=3D DeclSpec::SCS_unspecified &&
-             isa<RecordDecl>(Owner)) {
-      Diag(DS.getStorageClassSpecLoc(),
-           diag::err_anonymous_union_with_storage_spec);
-      Invalid =3D true;
-
-      // Recover by removing the storage specifier.
-      DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, SourceLocat=
ion(),
-                             PrevSpec, DiagID);
+    if (Record->isUnion()) {
+      // C++ [class.union]p6:
+      //   Anonymous unions declared in a named namespace or in the
+      //   global namespace shall be declared static.
+      if (DS.getStorageClassSpec() !=3D DeclSpec::SCS_static &&
+          (isa<TranslationUnitDecl>(Owner) ||
+           (isa<NamespaceDecl>(Owner) &&
+            cast<NamespaceDecl>(Owner)->getDeclName()))) {
+        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
+          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
+ =20
+        // Recover by adding 'static'.
+        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation=
(),
+                               PrevSpec, DiagID);
+      }
+      // C++ [class.union]p6:
+      //   A storage class is not allowed in a declaration of an
+      //   anonymous union in a class scope.
+      else if (DS.getStorageClassSpec() !=3D DeclSpec::SCS_unspecified &&
+               isa<RecordDecl>(Owner)) {
+        Diag(DS.getStorageClassSpecLoc(),
+             diag::err_anonymous_union_with_storage_spec)
+          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
+ =20
+        // Recover by removing the storage specifier.
+        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,=20
+                               SourceLocation(),
+                               PrevSpec, DiagID);
+      }
     }
=20
     // Ignore const/volatile/restrict qualifiers.
@@ -2683,11 +2766,13 @@
           << Record->isUnion() << 0=20
           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
-        Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qua=
lified)
+        Diag(DS.getVolatileSpecLoc(),=20
+             diag::ext_anonymous_struct_union_qualified)
           << Record->isUnion() << 1
           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
-        Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qua=
lified)
+        Diag(DS.getRestrictSpecLoc(),=20
+             diag::ext_anonymous_struct_union_qualified)
           << Record->isUnion() << 2=20
           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
=20
@@ -2717,7 +2802,7 @@
         //   copy constructor, a non-trivial destructor, or a non-trivial =
copy
         //   assignment operator cannot be a member of a union, nor can an
         //   array of such objects.
-        if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD))
+        if (CheckNontrivialField(FD))
           Invalid =3D true;
       } else if ((*Mem)->isImplicit()) {
         // Any implicit members are fine.
@@ -2730,7 +2815,7 @@
         if (!MemRecord->isAnonymousStructOrUnion() &&
             MemRecord->getDeclName()) {
           // Visual C++ allows type definition in anonymous struct or unio=
n.
-          if (getLangOptions().MicrosoftExt)
+          if (getLangOpts().MicrosoftExt)
             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with=
_type)
               << (int)Record->isUnion();
           else {
@@ -2754,7 +2839,7 @@
           DK =3D diag::err_anonymous_record_with_static;
        =20
         // Visual C++ allows type definition in anonymous struct or union.
-        if (getLangOptions().MicrosoftExt &&
+        if (getLangOpts().MicrosoftExt &&
             DK =3D=3D diag::err_anonymous_record_with_type)
           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
             << (int)Record->isUnion();
@@ -2769,7 +2854,7 @@
=20
   if (!Record->isUnion() && !Owner->isRecord()) {
     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
-      << (int)getLangOptions().CPlusPlus;
+      << (int)getLangOpts().CPlusPlus;
     Invalid =3D true;
   }
=20
@@ -2782,7 +2867,7 @@
   NamedDecl *Anon =3D 0;
   if (RecordDecl *OwningClass =3D dyn_cast<RecordDecl>(Owner)) {
     Anon =3D FieldDecl::Create(Context, OwningClass,
-                             DS.getSourceRange().getBegin(),
+                             DS.getLocStart(),
                              Record->getLocation(),
                              /*IdentifierInfo=3D*/0,
                              Context.getTypeDeclType(Record),
@@ -2790,7 +2875,7 @@
                              /*BitWidth=3D*/0, /*Mutable=3D*/false,
                              /*HasInit=3D*/false);
     Anon->setAccess(AS);
-    if (getLangOptions().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       FieldCollector->Add(cast<FieldDecl>(Anon));
   } else {
     DeclSpec::SCS SCSpec =3D DS.getStorageClassSpec();
@@ -2809,7 +2894,7 @@
       =3D StorageClassSpecToVarDeclStorageClass(SCSpec);
=20
     Anon =3D VarDecl::Create(Context, Owner,
-                           DS.getSourceRange().getBegin(),
+                           DS.getLocStart(),
                            Record->getLocation(), /*IdentifierInfo=3D*/0,
                            Context.getTypeDeclType(Record),
                            TInfo, SC, SCAsWritten);
@@ -2879,8 +2964,8 @@
   // Create a declaration for this anonymous struct.
   NamedDecl* Anon =3D FieldDecl::Create(Context,
                              cast<RecordDecl>(CurContext),
-                             DS.getSourceRange().getBegin(),
-                             DS.getSourceRange().getBegin(),
+                             DS.getLocStart(),
+                             DS.getLocStart(),
                              /*IdentifierInfo=3D*/0,
                              Context.getTypeDeclType(Record),
                              TInfo,
@@ -2897,9 +2982,10 @@
   SmallVector<NamedDecl*, 2> Chain;
   Chain.push_back(Anon);
=20
-  if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
-                                          Record->getDefinition(),
-                                          AS_none, Chain, true))
+  RecordDecl *RecordDef =3D Record->getDefinition();
+  if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurConte=
xt,
+                                                        RecordDef, AS_none,
+                                                        Chain, true))
     Anon->setInvalidDecl();
=20
   return Anon;
@@ -3135,8 +3221,14 @@
 }
=20
 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
-  D.setFunctionDefinition(false);
-  return HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
+  D.setFunctionDefinitionKind(FDK_Declaration);
+  Decl *Dcl =3D HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
+
+  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() =
&&
+      Dcl->getDeclContext()->isFileContext())
+    Dcl->setTopLevelDeclInObjCContainer();
+
+  return Dcl;
 }
=20
 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
@@ -3158,7 +3250,100 @@
=20
   return false;
 }
+
+/// \brief Diagnose a declaration whose declarator-id has the given=20
+/// nested-name-specifier.
+///
+/// \param SS The nested-name-specifier of the declarator-id.
+///
+/// \param DC The declaration context to which the nested-name-specifier=20
+/// resolves.
+///
+/// \param Name The name of the entity being declared.
+///
+/// \param Loc The location of the name of the entity being declared.
+///
+/// \returns true if we cannot safely recover from this error, false other=
wise.
+bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
+                                        DeclarationName Name,
+                                      SourceLocation Loc) {
+  DeclContext *Cur =3D CurContext;
+  while (isa<LinkageSpecDecl>(Cur))
+    Cur =3D Cur->getParent();
  =20
+  // C++ [dcl.meaning]p1:
+  //   A declarator-id shall not be qualified except for the definition
+  //   of a member function (9.3) or static data member (9.4) outside of
+  //   its class, the definition or explicit instantiation of a function=20
+  //   or variable member of a namespace outside of its namespace, or the
+  //   definition of an explicit specialization outside of its namespace,
+  //   or the declaration of a friend function that is a member of=20
+  //   another class or namespace (11.3). [...]
+   =20
+  // The user provided a superfluous scope specifier that refers back to t=
he
+  // class or namespaces in which the entity is already declared.
+  //
+  // class X {
+  //   void X::f();
+  // };
+  if (Cur->Equals(DC)) {
+    Diag(Loc, diag::warn_member_extra_qualification)
+      << Name << FixItHint::CreateRemoval(SS.getRange());
+    SS.clear();
+    return false;
+  }=20
+
+  // Check whether the qualifying scope encloses the scope of the original
+  // declaration.
+  if (!Cur->Encloses(DC)) {
+    if (Cur->isRecord())
+      Diag(Loc, diag::err_member_qualification)
+        << Name << SS.getRange();
+    else if (isa<TranslationUnitDecl>(DC))
+      Diag(Loc, diag::err_invalid_declarator_global_scope)
+        << Name << SS.getRange();
+    else if (isa<FunctionDecl>(Cur))
+      Diag(Loc, diag::err_invalid_declarator_in_function)=20
+        << Name << SS.getRange();
+    else
+      Diag(Loc, diag::err_invalid_declarator_scope)
+      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRang=
e();
+   =20
+    return true;
+  }
+
+  if (Cur->isRecord()) {
+    // Cannot qualify members within a class.
+    Diag(Loc, diag::err_member_qualification)
+      << Name << SS.getRange();
+    SS.clear();
+   =20
+    // C++ constructors and destructors with incorrect scopes can break
+    // our AST invariants by having the wrong underlying types. If
+    // that's the case, then drop this declaration entirely.
+    if ((Name.getNameKind() =3D=3D DeclarationName::CXXConstructorName ||
+         Name.getNameKind() =3D=3D DeclarationName::CXXDestructorName) &&
+        !Context.hasSameType(Name.getCXXNameType(),
+                             Context.getTypeDeclType(cast<CXXRecordDecl>(C=
ur))))
+      return true;
+   =20
+    return false;
+  }
+ =20
+  // C++11 [dcl.meaning]p1:
+  //   [...] "The nested-name-specifier of the qualified declarator-id sha=
ll
+  //   not begin with a decltype-specifer"
+  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
+  while (SpecLoc.getPrefix())
+    SpecLoc =3D SpecLoc.getPrefix();
+  if (dyn_cast_or_null<DecltypeType>(
+        SpecLoc.getNestedNameSpecifier()->getAsType()))
+    Diag(Loc, diag::err_decltype_in_declarator)
+      << SpecLoc.getTypeLoc().getSourceRange();
+
+  return false;
+}
+
 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
                              MultiTemplateParamsArg TemplateParamLists) {
   // TODO: consider using NameInfo for diagnostic.
@@ -3169,7 +3354,7 @@
   // one, the ParsedFreeStandingDeclSpec action should be used.
   if (!Name) {
     if (!D.isInvalidType())  // Reject this if we think it is valid.
-      Diag(D.getDeclSpec().getSourceRange().getBegin(),
+      Diag(D.getDeclSpec().getLocStart(),
            diag::err_declarator_need_ident)
         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
     return 0;
@@ -3209,29 +3394,18 @@
         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
       return 0;
=20
-    if (isa<CXXRecordDecl>(DC)) {
-      if (!cast<CXXRecordDecl>(DC)->hasDefinition()) {
-        Diag(D.getIdentifierLoc(),
-             diag::err_member_def_undefined_record)
-          << Name << DC << D.getCXXScopeSpec().getRange();
+    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition(=
)) {
+      Diag(D.getIdentifierLoc(),
+           diag::err_member_def_undefined_record)
+        << Name << DC << D.getCXXScopeSpec().getRange();
+      D.setInvalidType();
+    } else if (!D.getDeclSpec().isFriendSpecified()) {
+      if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
+                                      Name, D.getIdentifierLoc())) {
+        if (DC->isRecord())
+          return 0;
+       =20
         D.setInvalidType();
-      } else if (isa<CXXRecordDecl>(CurContext) &&=20
-                 !D.getDeclSpec().isFriendSpecified()) {
-        // The user provided a superfluous scope specifier inside a class
-        // definition:
-        //
-        // class X {
-        //   void X::f();
-        // };
-        if (CurContext->Equals(DC))
-          Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
-            << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRan=
ge());
-        else
-          Diag(D.getIdentifierLoc(), diag::err_member_qualification)
-            << Name << D.getCXXScopeSpec().getRange();
-       =20
-        // Pretend that this qualifier was not here.
-        D.getCXXScopeSpec().clear();
       }
     }
=20
@@ -3289,21 +3463,16 @@
   } else { // Something like "int foo::x;"
     LookupQualifiedName(Previous, DC);
=20
-    // Don't consider using declarations as previous declarations for
-    // out-of-line members.
-    RemoveUsingDecls(Previous);
-
-    // C++ 7.3.1.2p2:
-    // Members (including explicit specializations of templates) of a named
-    // namespace can also be defined outside that namespace by explicit
-    // qualification of the name being defined, provided that the entity b=
eing
-    // defined was already declared in the namespace and the definition ap=
pears
-    // after the point of declaration in a namespace that encloses the
-    // declarations namespace.
+    // C++ [dcl.meaning]p1:
+    //   When the declarator-id is qualified, the declaration shall refer =
to a=20
+    //  previously declared member of the class or namespace to which the=20
+    //  qualifier refers (or, in the case of a namespace, of an element of=
 the
+    //  inline namespace set of that namespace (7.3.1)) or to a specializa=
tion
+    //  thereof; [...]=20
     //
-    // Note that we only check the context at this point. We don't yet
-    // have enough information to make sure that PrevDecl is actually
-    // the declaration we want to match. For example, given:
+    // Note that we already checked the context above, and that we do not =
have
+    // enough information to make sure that Previous contains the declarat=
ion
+    // we want to match. For example, given:
     //
     //   class X {
     //     void f();
@@ -3312,40 +3481,23 @@
     //
     //   void X::f(int) { } // ill-formed
     //
-    // In this case, PrevDecl will point to the overload set
+    // In this case, Previous will point to the overload set
     // containing the two f's declared in X, but neither of them
     // matches.
-
-    // First check whether we named the global scope.
-    if (isa<TranslationUnitDecl>(DC)) {
-      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
-        << Name << D.getCXXScopeSpec().getRange();
-    } else {
-      DeclContext *Cur =3D CurContext;
-      while (isa<LinkageSpecDecl>(Cur))
-        Cur =3D Cur->getParent();
-      if (!Cur->Encloses(DC)) {
-        // The qualifying scope doesn't enclose the original declaration.
-        // Emit diagnostic based on current scope.
-        SourceLocation L =3D D.getIdentifierLoc();
-        SourceRange R =3D D.getCXXScopeSpec().getRange();
-        if (isa<FunctionDecl>(Cur))
-          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
-        else
-          Diag(L, diag::err_invalid_declarator_scope)
-            << Name << cast<NamedDecl>(DC) << R;
-        D.setInvalidType();
-      }
-    }
+   =20
+    // C++ [dcl.meaning]p1:
+    //   [...] the member shall not merely have been introduced by a=20
+    //   using-declaration in the scope of the class or namespace nominate=
d by=20
+    //   the nested-name-specifier of the declarator-id.
+    RemoveUsingDecls(Previous);
   }
=20
   if (Previous.isSingleResult() &&
       Previous.getFoundDecl()->isTemplateParameter()) {
     // Maybe we will complain about the shadowed template parameter.
     if (!D.isInvalidType())
-      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
-                                          Previous.getFoundDecl()))
-        D.setInvalidType();
+      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
+                                      Previous.getFoundDecl());
=20
     // Just pretend that we didn't see the previous declaration.
     Previous.clear();
@@ -3434,14 +3586,12 @@
   if (VLATy->getElementType()->isVariablyModifiedType())
     return QualType();
=20
-  Expr::EvalResult EvalResult;
+  llvm::APSInt Res;
   if (!VLATy->getSizeExpr() ||
-      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
-      !EvalResult.Val.isInt())
+      !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
     return QualType();
=20
   // Check whether the array size is negative.
-  llvm::APSInt &Res =3D EvalResult.Val.getInt();
   if (Res.isSigned() && Res.isNegative()) {
     SizeIsNegative =3D true;
     return QualType();
@@ -3548,7 +3698,7 @@
     Previous.clear();
   }
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // Check that there are no default arguments (C++ only).
     CheckExtraCXXDefaultArguments(D);
   }
@@ -3606,7 +3756,8 @@
         else if (T->isVariableArrayType())
           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
         else if (Oversized.getBoolValue())
-          Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversiz=
ed.toString(10);
+          Diag(NewTD->getLocation(), diag::err_array_too_large)=20
+            << Oversized.toString(10);
         else
           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
         NewTD->setInvalidDecl();
@@ -3677,7 +3828,7 @@
   if (!PrevDecl->hasLinkage())
     return false;
=20
-  if (Context.getLangOptions().CPlusPlus) {
+  if (Context.getLangOpts().CPlusPlus) {
     // C++ [basic.link]p6:
     //   If there is a visible declaration of an entity with linkage
     //   having the same name and type, ignoring entities declared
@@ -3766,7 +3917,7 @@
   DeclarationName Name =3D GetNameForDeclarator(D).getName();
=20
   // Check that there are no default arguments (C++ only).
-  if (getLangOptions().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     CheckExtraCXXDefaultArguments(D);
=20
   DeclSpec::SCS SCSpec =3D D.getDeclSpec().getStorageClassSpec();
@@ -3808,7 +3959,7 @@
     }
   }
  =20
-  if (getLangOptions().OpenCL) {
+  if (getLangOpts().OpenCL) {
     // Set up the special work-group-local storage class for variables in =
the
     // OpenCL __local address space.
     if (R.getAddressSpace() =3D=3D LangAS::opencl_local)
@@ -3817,8 +3968,8 @@
=20
   bool isExplicitSpecialization =3D false;
   VarDecl *NewVD;
-  if (!getLangOptions().CPlusPlus) {
-    NewVD =3D VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
+  if (!getLangOpts().CPlusPlus) {
+    NewVD =3D VarDecl::Create(Context, DC, D.getLocStart(),
                             D.getIdentifierLoc(), II,
                             R, TInfo, SC, SCAsWritten);
  =20
@@ -3834,20 +3985,24 @@
       } else if (SC =3D=3D SC_None)
         SC =3D SC_Static;
     }
-    if (SC =3D=3D SC_Static) {
+    if (SC =3D=3D SC_Static && CurContext->isRecord()) {
       if (const CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(DC)) {
         if (RD->isLocalClass())
           Diag(D.getIdentifierLoc(),
                diag::err_static_data_member_not_allowed_in_local_class)
             << Name << RD->getDeclName();
=20
-        // C++ [class.union]p1: If a union contains a static data member,
-        // the program is ill-formed.
-        //
-        // We also disallow static data members in anonymous structs.
-        if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName()=
))
+        // C++98 [class.union]p1: If a union contains a static data member,
+        // the program is ill-formed. C++11 drops this restriction.
+        if (RD->isUnion())
           Diag(D.getIdentifierLoc(),
-               diag::err_static_data_member_not_allowed_in_union_or_anon_s=
truct)
+               getLangOpts().CPlusPlus0x
+                 ? diag::warn_cxx98_compat_static_data_member_in_union
+                 : diag::ext_static_data_member_in_union) << Name;
+        // We conservatively disallow static data members in anonymous str=
ucts.
+        else if (!RD->getDeclName())
+          Diag(D.getIdentifierLoc(),
+               diag::err_static_data_member_not_allowed_in_anon_struct)
             << Name << RD->isUnion();
       }
     }
@@ -3858,7 +4013,7 @@
     bool Invalid =3D false;
     if (TemplateParameterList *TemplateParams
         =3D MatchTemplateParametersToScopeSpecifier(
-                                  D.getDeclSpec().getSourceRange().getBegi=
n(),
+                                  D.getDeclSpec().getLocStart(),
                                                   D.getIdentifierLoc(),
                                                   D.getCXXScopeSpec(),
                                                   TemplateParamLists.get(),
@@ -3884,7 +4039,7 @@
       }
     }
=20
-    NewVD =3D VarDecl::Create(Context, DC, D.getSourceRange().getBegin(),
+    NewVD =3D VarDecl::Create(Context, DC, D.getLocStart(),
                             D.getIdentifierLoc(), II,
                             R, TInfo, SC, SCAsWritten);
=20
@@ -3905,38 +4060,8 @@
                                            TemplateParamLists.release());
     }
=20
-    if (D.getDeclSpec().isConstexprSpecified()) {
-      // FIXME: once we know whether there's an initializer, apply this to
-      // static data members too.
-      if (!NewVD->isStaticDataMember() &&
-          !NewVD->isThisDeclarationADefinition()) {
-        // 'constexpr' is redundant and ill-formed on a non-defining decla=
ration
-        // of a variable. Suggest replacing it with 'const' if appropriate.
-        SourceLocation ConstexprLoc =3D D.getDeclSpec().getConstexprSpecLo=
c();
-        SourceRange ConstexprRange(ConstexprLoc, ConstexprLoc);
-        // If the declarator is complex, we need to move the keyword to the
-        // innermost chunk as we switch it from 'constexpr' to 'const'.
-        int Kind =3D DeclaratorChunk::Paren;
-        for (unsigned I =3D 0, E =3D D.getNumTypeObjects(); I !=3D E; ++I)=
 {
-          Kind =3D D.getTypeObject(I).Kind;
-          if (Kind !=3D DeclaratorChunk::Paren)
-            break;
-        }
-        if ((D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) ||
-            Kind =3D=3D DeclaratorChunk::Reference)
-          Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl)
-            << FixItHint::CreateRemoval(ConstexprRange);
-        else if (Kind =3D=3D DeclaratorChunk::Paren)
-          Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl)
-            << FixItHint::CreateReplacement(ConstexprRange, "const");
-        else
-          Diag(ConstexprLoc, diag::err_invalid_constexpr_var_decl)
-            << FixItHint::CreateRemoval(ConstexprRange)
-            << FixItHint::CreateInsertion(D.getIdentifierLoc(), "const ");
-      } else {
-        NewVD->setConstexpr(true);
-      }
-    }
+    if (D.getDeclSpec().isConstexprSpecified())
+      NewVD->setConstexpr(true);
   }
=20
   // Set the lexical context. If the declarator has a C++ scope specifier,=
 the
@@ -3971,7 +4096,7 @@
=20
   // In auto-retain/release, infer strong retension for variables of
   // retainable type.
-  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
+  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
     NewVD->setInvalidDecl();
=20
   // Handle GNU asm-label extension (encoded as an attribute).
@@ -3999,6 +4124,13 @@
=20
     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
                                                 Context, Label));
+  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
+    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =3D
+      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
+    if (I !=3D ExtnameUndeclaredIdentifiers.end()) {
+      NewVD->addAttr(I->second);
+      ExtnameUndeclaredIdentifiers.erase(I);
+    }
   }
=20
   // Diagnose shadowed variables before filtering for scope.
@@ -4011,7 +4143,7 @@
   FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
                        isExplicitSpecialization);
  =20
-  if (!getLangOptions().CPlusPlus) {
+  if (!getLangOpts().CPlusPlus) {
     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
   } else {
     // Merge the decl with the existing one if appropriate.
@@ -4204,7 +4336,7 @@
=20
   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
       && !NewVD->hasAttr<BlocksAttr>()) {
-    if (getLangOptions().getGC() !=3D LangOptions::NonGC)
+    if (getLangOpts().getGC() !=3D LangOptions::NonGC)
       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
     else
       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
@@ -4284,20 +4416,9 @@
     return false;
   }
=20
-  // Function pointers and references cannot have qualified function type,=
 only
-  // function pointer-to-members can do that.
-  QualType Pointee;
-  unsigned PtrOrRef =3D 0;
-  if (const PointerType *Ptr =3D T->getAs<PointerType>())
-    Pointee =3D Ptr->getPointeeType();
-  else if (const ReferenceType *Ref =3D T->getAs<ReferenceType>()) {
-    Pointee =3D Ref->getPointeeType();
-    PtrOrRef =3D 1;
-  }
-  if (!Pointee.isNull() && Pointee->isFunctionProtoType() &&
-      Pointee->getAs<FunctionProtoType>()->getTypeQuals() !=3D 0) {
-    Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointe=
r)
-        << PtrOrRef;
+  if (NewVD->isConstexpr() && !T->isDependentType() &&
+      RequireLiteralType(NewVD->getLocation(), T,
+                         PDiag(diag::err_constexpr_var_non_literal))) {
     NewVD->setInvalidDecl();
     return false;
   }
@@ -4387,6 +4508,33 @@
   };
 }
=20
+namespace {
+
+// Callback to only accept typo corrections that have a non-zero edit dist=
ance.
+// Also only accept corrections that have the same parent decl.
+class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  DifferentNameValidatorCCC(CXXRecordDecl *Parent)
+      : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    if (candidate.getEditDistance() =3D=3D 0)
+      return false;
+
+    if (CXXMethodDecl *MD =3D candidate.getCorrectionDeclAs<CXXMethodDecl>=
()) {
+      CXXRecordDecl *Parent =3D MD->getParent();
+      return Parent && Parent->getCanonicalDecl() =3D=3D ExpectedParent;
+    }
+
+    return !ExpectedParent;
+  }
+
+ private:
+  CXXRecordDecl *ExpectedParent;
+};
+
+}
+
 /// \brief Generate diagnostics for an invalid function redeclaration.
 ///
 /// This routine handles generating the diagnostic messages for an invalid
@@ -4407,7 +4555,7 @@
   llvm::SmallVector<unsigned, 1> MismatchedParams;
   llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
   TypoCorrection Correction;
-  bool isFriendDecl =3D (SemaRef.getLangOptions().CPlusPlus &&
+  bool isFriendDecl =3D (SemaRef.getLangOpts().CPlusPlus &&
                        ExtraArgs.D.getDeclSpec().isFriendSpecified());
   unsigned DiagMsg =3D isFriendDecl ? diag::err_no_matching_local_friend
                                   : diag::err_member_def_does_not_match;
@@ -4416,6 +4564,8 @@
   SemaRef.LookupQualifiedName(Prev, NewDC);
   assert(!Prev.isAmbiguous() &&
          "Cannot have an ambiguity in previous-declaration lookup");
+  CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(NewFD);
+  DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0);
   if (!Prev.empty()) {
     for (LookupResult::iterator Func =3D Prev.begin(), FuncEnd =3D Prev.en=
d();
          Func !=3D FuncEnd; ++Func) {
@@ -4431,8 +4581,8 @@
     }
   // If the qualified name lookup yielded nothing, try typo correction
   } else if ((Correction =3D SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
-                                         Prev.getLookupKind(), 0, 0, NewDC=
)) &&
-             Correction.getCorrection() !=3D Name) {
+                                         Prev.getLookupKind(), 0, 0,
+                                         Validator, NewDC))) {
     // Trap errors.
     Sema::SFINAETrap Trap(SemaRef);
=20
@@ -4454,12 +4604,11 @@
     // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
     // pieces need to verify the typo-corrected C++ declaraction and hopef=
ully
     // eliminate the need for the parameter pack ExtraArgs.
-    Result =3D SemaRef.ActOnFunctionDeclarator(ExtraArgs.S, ExtraArgs.D,
-                                             NewFD->getDeclContext(),
-                                             NewFD->getTypeSourceInfo(),
-                                             Previous,
-                                             ExtraArgs.TemplateParamLists,
-                                             ExtraArgs.AddToScope);
+    Result =3D SemaRef.ActOnFunctionDeclarator(
+        ExtraArgs.S, ExtraArgs.D,
+        Correction.getCorrectionDecl()->getDeclContext(),
+        NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
+        ExtraArgs.AddToScope);
     if (Trap.hasErrorOccurred()) {
       // Pretend the typo correction never occurred
       ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
@@ -4487,10 +4636,10 @@
=20
   if (Correction)
     SemaRef.Diag(NewFD->getLocation(), DiagMsg)
-        << Name << NewDC << Correction.getQuoted(SemaRef.getLangOptions())
+        << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
         << FixItHint::CreateReplacement(
             NewFD->getLocation(),
-            Correction.getAsString(SemaRef.getLangOptions()));
+            Correction.getAsString(SemaRef.getLangOpts()));
   else
     SemaRef.Diag(NewFD->getLocation(), DiagMsg)
         << Name << NewDC << NewFD->getLocation();
@@ -4509,12 +4658,13 @@
=20
     if (unsigned Idx =3D NearMatch->second) {
       ParmVarDecl *FDParam =3D FD->getParamDecl(Idx-1);
-      SemaRef.Diag(FDParam->getTypeSpecStartLoc(),
-             diag::note_member_def_close_param_match)
+      SourceLocation Loc =3D FDParam->getTypeSpecStartLoc();
+      if (Loc.isInvalid()) Loc =3D FD->getLocation();
+      SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
           << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getT=
ype();
     } else if (Correction) {
       SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
-          << Correction.getQuoted(SemaRef.getLangOptions());
+          << Correction.getQuoted(SemaRef.getLangOpts());
     } else if (FDisConst !=3D NewFDisConst) {
       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_ma=
tch)
           << NewFDisConst << FD->getSourceRange().getEnd();
@@ -4524,7 +4674,8 @@
   return Result;
 }
=20
-static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, D=
eclarator &D) {
+static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,=20
+                                                          Declarator &D) {
   switch (D.getDeclSpec().getStorageClassSpec()) {
   default: llvm_unreachable("Unknown storage class!");
   case DeclSpec::SCS_auto:
@@ -4570,7 +4721,7 @@
   FunctionDecl::StorageClass SCAsWritten
     =3D StorageClassSpecToFunctionDeclStorageClass(SCSpec);
=20
-  if (!SemaRef.getLangOptions().CPlusPlus) {
+  if (!SemaRef.getLangOpts().CPlusPlus) {
     // Determine whether the function was written with a
     // prototype. This true when:
     //   - there is a prototype in the declarator, or
@@ -4580,8 +4731,9 @@
       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
=20
-    NewFD =3D FunctionDecl::Create(SemaRef.Context, DC, D.getSourceRange()=
.getBegin(),
-                                 NameInfo, R, TInfo, SC, SCAsWritten, isIn=
line,
+    NewFD =3D FunctionDecl::Create(SemaRef.Context, DC,=20
+                                 D.getLocStart(), NameInfo, R,=20
+                                 TInfo, SC, SCAsWritten, isInline,=20
                                  HasPrototype);
     if (D.isInvalidType())
       NewFD->setInvalidDecl();
@@ -4612,7 +4764,7 @@
=20
     R =3D SemaRef.CheckConstructorDeclarator(D, R, SC);
     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>=
(DC),
-                                      D.getSourceRange().getBegin(), NameI=
nfo,
+                                      D.getLocStart(), NameInfo,
                                       R, TInfo, isExplicit, isInline,
                                       /*isImplicitlyDeclared=3D*/false,
                                       isConstexpr);
@@ -4624,14 +4776,14 @@
       CXXRecordDecl *Record =3D cast<CXXRecordDecl>(DC);
       CXXDestructorDecl *NewDD =3D CXXDestructorDecl::Create(
                                         SemaRef.Context, Record,
-                                        D.getSourceRange().getBegin(),
+                                        D.getLocStart(),
                                         NameInfo, R, TInfo, isInline,
                                         /*isImplicitlyDeclared=3D*/false);
=20
       // If the class is complete, then we now create the implicit excepti=
on
       // specification. If the class is incomplete or dependent, we can't =
do
       // it yet.
-      if (SemaRef.getLangOptions().CPlusPlus0x && !Record->isDependentType=
() &&
+      if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() =
&&
           Record->getDefinition() && !Record->isBeingDefined() &&
           R->getAs<FunctionProtoType>()->getExceptionSpecType() =3D=3D EST=
_None) {
         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
@@ -4647,7 +4799,7 @@
       // Create a FunctionDecl to satisfy the function definition parsing
       // code path.
       return FunctionDecl::Create(SemaRef.Context, DC,
-                                  D.getSourceRange().getBegin(),
+                                  D.getLocStart(),
                                   D.getIdentifierLoc(), Name, R, TInfo,
                                   SC, SCAsWritten, isInline,
                                   /*hasPrototype=3D*/true, isConstexpr);
@@ -4663,7 +4815,7 @@
     SemaRef.CheckConversionDeclarator(D, R, SC);
     IsVirtualOkay =3D true;
     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(=
DC),
-                                     D.getSourceRange().getBegin(), NameIn=
fo,
+                                     D.getLocStart(), NameInfo,
                                      R, TInfo, isInline, isExplicit,
                                      isConstexpr, SourceLocation());
=20
@@ -4699,7 +4851,7 @@
=20
     // This is a C++ method declaration.
     return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
-                                 D.getSourceRange().getBegin(), NameInfo, =
R,
+                                 D.getLocStart(), NameInfo, R,
                                  TInfo, isStatic, SCAsWritten, isInline,
                                  isConstexpr, SourceLocation());
=20
@@ -4708,7 +4860,7 @@
     // prototype. This true when:
     //   - we're in C++ (where every function has a prototype),
     return FunctionDecl::Create(SemaRef.Context, DC,
-                                D.getSourceRange().getBegin(),
+                                D.getLocStart(),
                                 NameInfo, R, TInfo, SC, SCAsWritten, isInl=
ine,
                                 true/*HasPrototype*/, isConstexpr);
   }
@@ -4760,7 +4912,10 @@
                                               isVirtualOkay);
   if (!NewFD) return 0;
=20
-  if (getLangOptions().CPlusPlus) {
+  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
+    NewFD->setTopLevelDeclInObjCContainer();
+
+  if (getLangOpts().CPlusPlus) {
     bool isInline =3D D.getDeclSpec().isInlineSpecified();
     bool isVirtual =3D D.getDeclSpec().isVirtualSpecified();
     bool isExplicit =3D D.getDeclSpec().isExplicitSpecified();
@@ -4783,13 +4938,13 @@
     // scope specifier, or is the object of a friend declaration, the
     // lexical context will be different from the semantic context.
     NewFD->setLexicalDeclContext(CurContext);
-   =20
+       =20
     // Match up the template parameter lists with the scope specifier, then
     // determine whether we have a template or a template specialization.
     bool Invalid =3D false;
     if (TemplateParameterList *TemplateParams
           =3D MatchTemplateParametersToScopeSpecifier(
-                                  D.getDeclSpec().getSourceRange().getBegi=
n(),
+                                  D.getDeclSpec().getLocStart(),
                                   D.getIdentifierLoc(),
                                   D.getCXXScopeSpec(),
                                   TemplateParamLists.get(),
@@ -4811,7 +4966,7 @@
         }
        =20
         // If we're adding a template to a dependent context, we may need =
to=20
-        // rebuilding some of the types used within the template parameter=
 list,=20
+        // rebuilding some of the types used within the template parameter=
 list,
         // now that we know what the current instantiation is.
         if (DC->isDependentContext()) {
           ContextRAII SavedContext(*this, DC);
@@ -4880,6 +5035,56 @@
         FunctionTemplate->setInvalidDecl();
     }
=20
+    // If we see "T var();" at block scope, where T is a class type, it is
+    // probably an attempt to initialize a variable, not a function declar=
ation.
+    // We don't catch this case earlier, since there is no ambiguity here.
+    if (!FunctionTemplate && D.getFunctionDefinitionKind() =3D=3D FDK_Decl=
aration &&
+        CurContext->isFunctionOrMethod() &&
+        D.getNumTypeObjects() =3D=3D 1 && D.isFunctionDeclarator() &&
+        D.getDeclSpec().getStorageClassSpecAsWritten()
+          =3D=3D DeclSpec::SCS_unspecified) {
+      QualType T =3D R->getAs<FunctionType>()->getResultType();
+      DeclaratorChunk &C =3D D.getTypeObject(0);
+      if (!T->isVoidType() && C.Fun.NumArgs =3D=3D 0 && !C.Fun.isVariadic =
&&
+          !C.Fun.TrailingReturnType &&
+          C.Fun.getExceptionSpecType() =3D=3D EST_None) {
+        SourceRange ParenRange(C.Loc, C.EndLoc);
+        Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRan=
ge;
+
+        // If the declaration looks like:
+        //   T var1,
+        //   f();
+        // and name lookup finds a function named 'f', then the ',' was
+        // probably intended to be a ';'.
+        if (!D.isFirstDeclarator() && D.getIdentifier()) {
+          FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
+          FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
+          if (Comma.getFileID() !=3D Name.getFileID() ||
+              Comma.getSpellingLineNumber() !=3D Name.getSpellingLineNumbe=
r()) {
+            LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
+                                LookupOrdinaryName);
+            if (LookupName(Result, S))
+              Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
+                << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << N=
ewFD;
+          }
+        }
+        const CXXRecordDecl *RD =3D T->getAsCXXRecordDecl();
+        // Empty parens mean value-initialization, and no parens mean defa=
ult
+        // initialization. These are equivalent if the default constructor=
 is
+        // user-provided, or if zero-initialization is a no-op.
+        if (RD && RD->hasDefinition() &&
+            (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
+          Diag(C.Loc, diag::note_empty_parens_default_ctor)
+            << FixItHint::CreateRemoval(ParenRange);
+        else if (const char *Init =3D getFixItZeroInitializerForType(T))
+          Diag(C.Loc, diag::note_empty_parens_zero_initialize)
+            << FixItHint::CreateReplacement(ParenRange, Init);
+        else if (LangOpts.CPlusPlus0x)
+          Diag(C.Loc, diag::note_empty_parens_zero_initialize)
+            << FixItHint::CreateReplacement(ParenRange, "{}");
+      }
+    }
+
     // C++ [dcl.fct.spec]p5:
     //   The virtual specifier shall only be used in declarations of
     //   nonstatic class member functions that appear within a
@@ -4907,7 +5112,8 @@
     }
=20
     // C++ [dcl.fct.spec]p3:
-    //  The inline specifier shall not appear on a block scope function de=
claration.
+    //  The inline specifier shall not appear on a block scope function=20
+    //  declaration.
     if (isInline && !NewFD->isInvalidDecl()) {
       if (CurContext->isFunctionOrMethod()) {
         // 'inline' is not allowed on block scope function declaration.
@@ -4919,8 +5125,8 @@
=20
     // C++ [dcl.fct.spec]p6:
     //  The explicit specifier shall be used only in the declaration of a
-    //  constructor or conversion function within its class definition; se=
e 12.3.1
-    //  and 12.3.2.
+    //  constructor or conversion function within its class definition;=20
+    //  see 12.3.1 and 12.3.2.
     if (isExplicit && !NewFD->isInvalidDecl()) {
       if (!CurContext->isRecord()) {
         // 'explicit' was specified outside of the class.
@@ -4974,10 +5180,26 @@
       NewFD->setAccess(AS_public);
     }
=20
+    // If a function is defined as defaulted or deleted, mark it as such n=
ow.
+    switch (D.getFunctionDefinitionKind()) {
+      case FDK_Declaration:
+      case FDK_Definition:
+        break;
+       =20
+      case FDK_Defaulted:
+        NewFD->setDefaulted();
+        break;
+       =20
+      case FDK_Deleted:
+        NewFD->setDeletedAsWritten();
+        break;
+    }
+
     if (isa<CXXMethodDecl>(NewFD) && DC =3D=3D CurContext &&
         D.isFunctionDefinition()) {
-      // A method is implicitly inline if it's defined in its class
-      // definition.
+      // C++ [class.mfct]p2:
+      //   A member function may be defined (8.4) in its class definition,=
 in=20
+      //   which case it is an inline member function (7.1.2)
       NewFD->setImplicitlyInline();
     }
=20
@@ -5007,6 +5229,13 @@
     StringLiteral *SE =3D cast<StringLiteral>(E);
     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Con=
text,
                                                 SE->getString()));
+  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
+    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =3D
+      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
+    if (I !=3D ExtnameUndeclaredIdentifiers.end()) {
+      NewFD->addAttr(I->second);
+      ExtnameUndeclaredIdentifiers.erase(I);
+    }
   }
=20
   // Copy the parameter declarations from the declarator D to the function
@@ -5028,7 +5257,7 @@
=20
       // In C++, the empty parameter-type-list must be spelled "void"; a
       // typedef of void is not permitted.
-      if (getLangOptions().CPlusPlus &&
+      if (getLangOpts().CPlusPlus &&
           Param->getType().getUnqualifiedType() !=3D Context.VoidTy) {
         bool IsTypeAlias =3D false;
         if (const TypedefType *TT =3D Param->getType()->getAs<TypedefType>=
())
@@ -5077,25 +5306,35 @@
   // Finally, we know we have the right number of parameters, install them.
   NewFD->setParams(Params);
=20
+  // Find all anonymous symbols defined during the declaration of this fun=
ction
+  // and add to NewFD. This lets us track decls such 'enum Y' in:
+  //
+  //   void f(enum Y {AA} x) {}
+  //
+  // which would otherwise incorrectly end up in the translation unit scop=
e.
+  NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
+  DeclsInPrototypeScope.clear();
+
   // Process the non-inheritable attributes on this declaration.
   ProcessDeclAttributes(S, NewFD, D,
                         /*NonInheritable=3D*/true, /*Inheritable=3D*/false=
);
=20
-  if (!getLangOptions().CPlusPlus) {
+  // Functions returning a variably modified type violate C99 6.7.5.2p2
+  // because all functions have linkage.
+  if (!NewFD->isInvalidDecl() &&
+      NewFD->getResultType()->isVariablyModifiedType()) {
+    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
+    NewFD->setInvalidDecl();
+  }
+
+  if (!getLangOpts().CPlusPlus) {
     // Perform semantic checking on the function declaration.
     bool isExplicitSpecialization=3Dfalse;
     if (!NewFD->isInvalidDecl()) {
-      if (NewFD->getResultType()->isVariablyModifiedType()) {
-        // Functions returning a variably modified type violate C99 6.7.5.=
2p2
-        // because all functions have linkage.
-        Diag(NewFD->getLocation(), diag::err_vm_func_decl);
-        NewFD->setInvalidDecl();
-      } else {
-        if (NewFD->isMain())=20
-          CheckMain(NewFD, D.getDeclSpec());
-        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
-                                                    isExplicitSpecializati=
on));
-      }
+      if (NewFD->isMain())
+        CheckMain(NewFD, D.getDeclSpec());
+      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
+                                                  isExplicitSpecialization=
));
     }
     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
             Previous.getResultKind() !=3D LookupResult::FoundOverloaded) &&
@@ -5135,8 +5374,8 @@
         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
           << FixItHint::CreateInsertion(
-                                        D.getDeclSpec().getSourceRange().g=
etBegin(),
-                                                  "template<> ");
+                                    D.getDeclSpec().getLocStart(),
+                                        "template<> ");
         isFunctionTemplateSpecialization =3D true;
       } else {
         // "friend void foo<>(int);" is an implicit specialization decl.
@@ -5173,7 +5412,7 @@
       if (CurContext->isDependentContext() && CurContext->isRecord()=20
           && !isFriend) {
         isDependentClassScopeExplicitSpecialization =3D true;
-        Diag(NewFD->getLocation(), getLangOptions().MicrosoftExt ?=20
+        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?=20
           diag::ext_function_specialization_in_class :
           diag::err_function_specialization_in_class)
           << NewFD->getDeclName();
@@ -5224,10 +5463,6 @@
             Previous.getResultKind() !=3D LookupResult::FoundOverloaded) &&
            "previous declaration set still overloaded");
=20
-    if (NewFD->isConstexpr() && !NewFD->isInvalidDecl() &&
-        !CheckConstexprFunctionDecl(NewFD, CCK_Declaration))
-      NewFD->setInvalidDecl();
-
     NamedDecl *PrincipalDecl =3D (FunctionTemplate
                                 ? cast<NamedDecl>(FunctionTemplate)
                                 : NewFD);
@@ -5235,7 +5470,7 @@
     if (isFriend && D.isRedeclaration()) {
       AccessSpecifier Access =3D AS_public;
       if (!NewFD->isInvalidDecl())
-        Access =3D NewFD->getPreviousDeclaration()->getAccess();
+        Access =3D NewFD->getPreviousDecl()->getAccess();
=20
       NewFD->setAccess(Access);
       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
@@ -5250,9 +5485,10 @@
     // If we have a function template, check the template parameter
     // list. This will check and merge default template arguments.
     if (FunctionTemplate) {
-      FunctionTemplateDecl *PrevTemplate =3D FunctionTemplate->getPrevious=
Declaration();
+      FunctionTemplateDecl *PrevTemplate =3D=20
+                                     FunctionTemplate->getPreviousDecl();
       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
-                                 PrevTemplate? PrevTemplate->getTemplatePa=
rameters() : 0,
+                       PrevTemplate ? PrevTemplate->getTemplateParameters(=
) : 0,
                             D.getDeclSpec().isFriendSpecified()
                               ? (D.isFunctionDefinition()
                                    ? TPC_FriendFunctionTemplateDefinition
@@ -5331,8 +5567,9 @@
       // definition (C++ [dcl.meaning]p1).
       // Note that this is not the case for explicit specializations of
       // function templates or member functions of class templates, per
-      // C++ [temp.expl.spec]p2. We also allow these declarations as an ex=
tension
-      // for compatibility with old SWIG code which likes to generate them.
+      // C++ [temp.expl.spec]p2. We also allow these declarations as an=20
+      // extension for compatibility with old SWIG code which likes to=20
+      // generate them.
       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
         << D.getCXXScopeSpec().getRange();
     }
@@ -5393,7 +5630,7 @@
   // Set this FunctionDecl's range up to the right paren.
   NewFD->setRangeEnd(D.getSourceRange().getEnd());
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     if (FunctionTemplate) {
       if (NewFD->isInvalidDecl())
         FunctionTemplate->setInvalidDecl();
@@ -5403,7 +5640,7 @@
=20
   MarkUnusedFileScopedDecl(NewFD);
=20
-  if (getLangOptions().CUDA)
+  if (getLangOpts().CUDA)
     if (IdentifierInfo *II =3D NewFD->getIdentifier())
       if (!NewFD->isInvalidDecl() &&
           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()=
) {
@@ -5493,7 +5730,7 @@
         break;
       }
=20
-      if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>=
()) {
+      if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>())=
 {
         // If a function name is overloadable in C, then every function
         // with that name must be marked "overloadable".
         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missin=
g)
@@ -5514,7 +5751,7 @@
     if (Redeclaration) {
       // NewFD and OldDecl represent declarations that need to be
       // merged.
-      if (MergeFunctionDecl(NewFD, OldDecl)) {
+      if (MergeFunctionDecl(NewFD, OldDecl, S)) {
         NewFD->setInvalidDecl();
         return Redeclaration;
       }
@@ -5524,7 +5761,7 @@
=20
       if (FunctionTemplateDecl *OldTemplateDecl
                                     =3D dyn_cast<FunctionTemplateDecl>(Old=
Decl)) {
-        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl())=
;       =20
+        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
         FunctionTemplateDecl *NewTemplateDecl
           =3D NewFD->getDescribedFunctionTemplate();
         assert(NewTemplateDecl && "Template/non-template mismatch");
@@ -5542,9 +5779,6 @@
           assert(OldTemplateDecl->isMemberSpecialization());
         }
        =20
-        if (OldTemplateDecl->isModulePrivate())
-          NewTemplateDecl->setModulePrivate();
-       =20
       } else {
         if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line defin=
itions
           NewFD->setAccess(OldDecl->getAccess());
@@ -5554,7 +5788,7 @@
   }
=20
   // Semantic checking for this function declaration (in isolation).
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // C++-specific checks.
     if (CXXConstructorDecl *Constructor =3D dyn_cast<CXXConstructorDecl>(N=
ewFD)) {
       CheckConstructor(Constructor);
@@ -5633,29 +5867,59 @@
         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
       }
     }
+ =20
+    // If this function is declared as being extern "C", then check to see=
 if=20
+    // the function returns a UDT (class, struct, or union type) that is n=
ot C
+    // compatible, and if it does, warn the user.
+    if (NewFD->isExternC()) {
+      QualType R =3D NewFD->getResultType();
+      if (!R.isPODType(Context) &&=20
+          !R->isVoidType())
+        Diag( NewFD->getLocation(), diag::warn_return_value_udt )=20
+          << NewFD << R;
+    }
   }
   return Redeclaration;
 }
=20
 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
-  // C++ [basic.start.main]p3:  A program that declares main to be inline
-  //   or static is ill-formed.
+  // C++11 [basic.start.main]p3:  A program that declares main to be inlin=
e,
+  //   static or constexpr is ill-formed.
   // C99 6.7.4p4:  In a hosted environment, the inline function specifier
   //   shall not appear in a declaration of main.
   // static main is not an error under C99, but we should warn about it.
   if (FD->getStorageClass() =3D=3D SC_Static)
-    Diag(DS.getStorageClassSpecLoc(), getLangOptions().CPlusPlus=20
+    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus=20
          ? diag::err_static_main : diag::warn_static_main)=20
       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
   if (FD->isInlineSpecified())
     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)=20
       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
+  if (FD->isConstexpr()) {
+    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
+      << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
+    FD->setConstexpr(false);
+  }
=20
   QualType T =3D FD->getType();
   assert(T->isFunctionType() && "function decl is not of function type");
-  const FunctionType* FT =3D T->getAs<FunctionType>();
-
-  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy))=
 {
+  const FunctionType* FT =3D T->castAs<FunctionType>();
+
+  // All the standards say that main() should should return 'int'.
+  if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
+    // In C and C++, main magically returns 0 if you fall off the end;
+    // set the flag which tells us that.
+    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
+    FD->setHasImplicitReturnZero(true);
+
+  // In C with GNU extensions we allow main() to have non-integer return
+  // type, but we should warn about the extension, and we disable the
+  // implicit-return-zero rule.
+  } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
+    Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
+
+  // Otherwise, this is just a flat-out error.
+  } else {
     Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
     FD->setInvalidDecl(true);
   }
@@ -5786,7 +6050,8 @@
=20
     void VisitMemberExpr(MemberExpr *E) {
       if (E->getType()->canDecayToPointerType()) return;
-      if (isa<FieldDecl>(E->getMemberDecl()))
+      ValueDecl *VD =3D E->getMemberDecl();
+      if (isa<FieldDecl>(VD) || isa<CXXMethodDecl>(VD))
         if (DeclRefExpr *DRE
               =3D dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts(=
))) {
           HandleDeclRefExpr(DRE);
@@ -5844,17 +6109,6 @@
   if (RealDecl =3D=3D 0 || RealDecl->isInvalidDecl())
     return;
=20
-  // Check for self-references within variable initializers.
-  if (VarDecl *vd =3D dyn_cast<VarDecl>(RealDecl)) {
-    // Variables declared within a function/method body are handled
-    // by a dataflow analysis.
-    if (!vd->hasLocalStorage() && !vd->isStaticLocal())
-      CheckSelfReference(RealDecl, Init);   =20
-  }
-  else {
-    CheckSelfReference(RealDecl, Init);
-  }
-
   if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(RealDecl)) {
     // With declarators parsed the way they are, the parser cannot
     // distinguish between a normal initializer and a pure-specifier.
@@ -5879,48 +6133,88 @@
     return;
   }
=20
-  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
+  // Check for self-references within variable initializers.
+  // Variables declared within a function/method body are handled
+  // by a dataflow analysis.
+  if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
+    CheckSelfReference(RealDecl, Init);
+
+  ParenListExpr *CXXDirectInit =3D dyn_cast<ParenListExpr>(Init);
+
+  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
   if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
+    Expr *DeduceInit =3D Init;
+    // Initializer could be a C++ direct-initializer. Deduction only works=
 if it
+    // contains exactly one expression.
+    if (CXXDirectInit) {
+      if (CXXDirectInit->getNumExprs() =3D=3D 0) {
+        // It isn't possible to write this directly, but it is possible to
+        // end up in this situation with "auto x(some_pack...);"
+        Diag(CXXDirectInit->getLocStart(),
+             diag::err_auto_var_init_no_expression)
+          << VDecl->getDeclName() << VDecl->getType()
+          << VDecl->getSourceRange();
+        RealDecl->setInvalidDecl();
+        return;
+      } else if (CXXDirectInit->getNumExprs() > 1) {
+        Diag(CXXDirectInit->getExpr(1)->getLocStart(),
+             diag::err_auto_var_init_multiple_expressions)
+          << VDecl->getDeclName() << VDecl->getType()
+          << VDecl->getSourceRange();
+        RealDecl->setInvalidDecl();
+        return;
+      } else {
+        DeduceInit =3D CXXDirectInit->getExpr(0);
+      }
+    }
     TypeSourceInfo *DeducedType =3D 0;
-    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
-      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
-        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
-        << Init->getSourceRange();
+    if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType=
) =3D=3D
+            DAR_Failed)
+      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
     if (!DeducedType) {
       RealDecl->setInvalidDecl();
       return;
     }
     VDecl->setTypeSourceInfo(DeducedType);
     VDecl->setType(DeducedType->getType());
-
+    VDecl->ClearLinkageCache();
+   =20
     // In ARC, infer lifetime.
-    if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
+    if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
       VDecl->setInvalidDecl();
=20
     // If this is a redeclaration, check that the type we just deduced mat=
ches
     // the previously declared type.
-    if (VarDecl *Old =3D VDecl->getPreviousDeclaration())
+    if (VarDecl *Old =3D VDecl->getPreviousDecl())
       MergeVarDeclTypes(VDecl, Old);
   }
- =20
-
-  // A definition must end up with a complete type, which means it must be
-  // complete with the restriction that an array type might be completed b=
y the
-  // initializer; note that later code assumes this restriction.
-  QualType BaseDeclType =3D VDecl->getType();
-  if (const ArrayType *Array =3D Context.getAsIncompleteArrayType(BaseDecl=
Type))
-    BaseDeclType =3D Array->getElementType();
-  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
-                          diag::err_typecheck_decl_incomplete_type)) {
-    RealDecl->setInvalidDecl();
+
+  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
+    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
+    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
+    VDecl->setInvalidDecl();
     return;
   }
=20
-  // The variable can not have an abstract class type.
-  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
-                             diag::err_abstract_type_in_decl,
-                             AbstractVariableType))
-    VDecl->setInvalidDecl();
+  if (!VDecl->getType()->isDependentType()) {
+    // A definition must end up with a complete type, which means it must =
be
+    // complete with the restriction that an array type might be completed=
 by
+    // the initializer; note that later code assumes this restriction.
+    QualType BaseDeclType =3D VDecl->getType();
+    if (const ArrayType *Array =3D Context.getAsIncompleteArrayType(BaseDe=
clType))
+      BaseDeclType =3D Array->getElementType();
+    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
+                            diag::err_typecheck_decl_incomplete_type)) {
+      RealDecl->setInvalidDecl();
+      return;
+    }
+
+    // The variable can not have an abstract class type.
+    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
+                               diag::err_abstract_type_in_decl,
+                               AbstractVariableType))
+      VDecl->setInvalidDecl();
+  }
=20
   const VarDecl *Def;
   if ((Def =3D VDecl->getDefinition()) && Def !=3D VDecl) {
@@ -5932,7 +6226,7 @@
   }
  =20
   const VarDecl* PrevInit =3D 0;
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // C++ [class.static.data]p4
     //   If a static data member is of const integral or const
     //   enumeration type, its declaration in the class definition can
@@ -5946,7 +6240,8 @@
     // data members we also need to check whether there was an in-class
     // declaration with an initializer.
     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit))=
 {
-      Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDecl=
Name();
+      Diag(VDecl->getLocation(), diag::err_redefinition)=20
+        << VDecl->getDeclName();
       Diag(PrevInit->getLocation(), diag::note_previous_definition);
       return;
     } =20
@@ -5968,44 +6263,77 @@
     return;
   }
=20
-  // Capture the variable that is being initialized and the style of
-  // initialization.
-  InitializedEntity Entity =3D InitializedEntity::InitializeVariable(VDecl=
);
- =20
-  // FIXME: Poor source location information.
-  InitializationKind Kind
-    =3D DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
-                                                   Init->getLocStart(),
-                                                   Init->getLocEnd())
-                : InitializationKind::CreateCopy(VDecl->getLocation(),
-                                                 Init->getLocStart());
- =20
   // Get the decls type and save a reference for later, since
   // CheckInitializerTypes may change it.
   QualType DclT =3D VDecl->getType(), SavT =3D DclT;
-  if (VDecl->isLocalVarDecl()) {
-    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
-      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
-      VDecl->setInvalidDecl();
-    } else if (!VDecl->isInvalidDecl()) {
-      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
-      ExprResult Result =3D InitSeq.Perform(*this, Entity, Kind,
-                                                MultiExprArg(*this, &Init,=
 1),
-                                                &DclT);
+ =20
+  // Top-level message sends default to 'id' when we're in a debugger
+  // and we are assigning it to a variable of 'id' type.
+  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
+    if (Init->getType() =3D=3D Context.UnknownAnyTy && isa<ObjCMessageExpr=
>(Init)) {
+      ExprResult Result =3D forceUnknownAnyToType(Init, Context.getObjCIdT=
ype());
       if (Result.isInvalid()) {
         VDecl->setInvalidDecl();
         return;
       }
-
-      Init =3D Result.takeAs<Expr>();
-
-      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
-      // Don't check invalid declarations to avoid emitting useless diagno=
stics.
-      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
-        if (VDecl->getStorageClass() =3D=3D SC_Static) // C99 6.7.8p4.
-          CheckForConstantInitializer(Init, DclT);
-      }
-    }
+      Init =3D Result.take();
+    }
+
+  // Perform the initialization.
+  if (!VDecl->isInvalidDecl()) {
+    InitializedEntity Entity =3D InitializedEntity::InitializeVariable(VDe=
cl);
+    InitializationKind Kind
+      =3D DirectInit ?
+          CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocat=
ion(),
+                                                           Init->getLocSta=
rt(),
+                                                           Init->getLocEnd=
())
+                        : InitializationKind::CreateDirectList(
+                                                          VDecl->getLocati=
on())
+                   : InitializationKind::CreateCopy(VDecl->getLocation(),
+                                                    Init->getLocStart());
+
+    Expr **Args =3D &Init;
+    unsigned NumArgs =3D 1;
+    if (CXXDirectInit) {
+      Args =3D CXXDirectInit->getExprs();
+      NumArgs =3D CXXDirectInit->getNumExprs();
+    }
+    InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
+    ExprResult Result =3D InitSeq.Perform(*this, Entity, Kind,
+                                              MultiExprArg(*this, Args,Num=
Args),
+                                              &DclT);
+    if (Result.isInvalid()) {
+      VDecl->setInvalidDecl();
+      return;
+    }
+
+    Init =3D Result.takeAs<Expr>();
+  }
+
+  // If the type changed, it means we had an incomplete type that was
+  // completed by the initializer. For example:
+  //   int ary[] =3D { 1, 3, 5 };
+  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
+  if (!VDecl->isInvalidDecl() && (DclT !=3D SavT))
+    VDecl->setType(DclT);
+
+  // Check any implicit conversions within the expression.
+  CheckImplicitConversions(Init, VDecl->getLocation());
+
+  if (!VDecl->isInvalidDecl())
+    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
+
+  Init =3D MaybeCreateExprWithCleanups(Init);
+  // Attach the initializer to the decl.
+  VDecl->setInit(Init);
+
+  if (VDecl->isLocalVarDecl()) {
+    // C99 6.7.8p4: All the expressions in an initializer for an object th=
at has
+    // static storage duration shall be constant expressions or string lit=
erals.
+    // C++ does not have this restriction.
+    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
+        VDecl->getStorageClass() =3D=3D SC_Static)
+      CheckForConstantInitializer(Init, DclT);
   } else if (VDecl->isStaticDataMember() &&
              VDecl->getLexicalDeclContext()->isRecord()) {
     // This is an in-class initialization for a static data member, e.g.,
@@ -6014,26 +6342,12 @@
     //   static const int value =3D 17;
     // };
=20
-    // Try to perform the initialization regardless.
-    if (!VDecl->isInvalidDecl()) {
-      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
-      ExprResult Result =3D InitSeq.Perform(*this, Entity, Kind,
-                                          MultiExprArg(*this, &Init, 1),
-                                          &DclT);
-      if (Result.isInvalid()) {
-        VDecl->setInvalidDecl();
-        return;
-      }
-
-      Init =3D Result.takeAs<Expr>();
-    }
-
     // C++ [class.mem]p4:
     //   A member-declarator can contain a constant-initializer only
     //   if it declares a static member (9.4) of const integral or
     //   const enumeration type, see 9.4.2.
     //
-    // C++0x [class.static.data]p3:
+    // C++11 [class.static.data]p3:
     //   If a non-volatile const static data member is of integral or
     //   enumeration type, its declaration in the class definition can
     //   specify a brace-or-equal-initializer in which every initalizer-cl=
ause
@@ -6042,28 +6356,27 @@
     //   with the constexpr specifier; if so, its declaration shall specif=
y a
     //   brace-or-equal-initializer in which every initializer-clause that=
 is
     //   an assignment-expression is a constant expression.
-    QualType T =3D VDecl->getType();
=20
     // Do nothing on dependent types.
-    if (T->isDependentType()) {
+    if (DclT->isDependentType()) {
=20
     // Allow any 'static constexpr' members, whether or not they are of li=
teral
-    // type. We separately check that the initializer is a constant expres=
sion,
-    // which implicitly requires the member to be of literal type.
+    // type. We separately check that every constexpr variable is of liter=
al
+    // type.
     } else if (VDecl->isConstexpr()) {
=20
     // Require constness.
-    } else if (!T.isConstQualified()) {
+    } else if (!DclT.isConstQualified()) {
       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
         << Init->getSourceRange();
       VDecl->setInvalidDecl();
=20
     // We allow integer constant expressions in all cases.
-    } else if (T->isIntegralOrEnumerationType()) {
+    } else if (DclT->isIntegralOrEnumerationType()) {
       // Check whether the expression is a constant expression.
       SourceLocation Loc;
-      if (getLangOptions().CPlusPlus0x && T.isVolatileQualified())
-        // In C++0x, a non-constexpr const static data member with an
+      if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
+        // In C++11, a non-constexpr const static data member with an
         // in-class initializer cannot be volatile.
         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile=
);
       else if (Init->isValueDependent())
@@ -6083,88 +6396,65 @@
         VDecl->setInvalidDecl();
       }
=20
-    // We allow floating-point constants as an extension.
-    } else if (T->isFloatingType()) { // also permits complex, which is ok
+    // We allow foldable floating-point constants as an extension.
+    } else if (DclT->isFloatingType()) { // also permits complex, which is=
 ok
       Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
-        << T << Init->getSourceRange();
-      if (getLangOptions().CPlusPlus0x)
+        << DclT << Init->getSourceRange();
+      if (getLangOpts().CPlusPlus0x)
         Diag(VDecl->getLocation(),
              diag::note_in_class_initializer_float_type_constexpr)
           << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "=
);
=20
-      if (!Init->isValueDependent() &&
-          !Init->isConstantInitializer(Context, false)) {
+      if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
         Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_consta=
nt)
           << Init->getSourceRange();
         VDecl->setInvalidDecl();
       }
=20
-    // Suggest adding 'constexpr' in C++0x for literal types.
-    } else if (getLangOptions().CPlusPlus0x && T->isLiteralType()) {
+    // Suggest adding 'constexpr' in C++11 for literal types.
+    } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_ty=
pe)
-        << T << Init->getSourceRange()
+        << DclT << Init->getSourceRange()
         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
       VDecl->setConstexpr(true);
=20
     } else {
       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
-        << T << Init->getSourceRange();
+        << DclT << Init->getSourceRange();
       VDecl->setInvalidDecl();
     }
   } else if (VDecl->isFileVarDecl()) {
-    if (VDecl->getStorageClassAsWritten() =3D=3D SC_Extern &&=20
-        (!getLangOptions().CPlusPlus ||=20
+    if (VDecl->getStorageClassAsWritten() =3D=3D SC_Extern &&
+        (!getLangOpts().CPlusPlus ||
          !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
       Diag(VDecl->getLocation(), diag::warn_extern_init);
-    if (!VDecl->isInvalidDecl()) {
-      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
-      ExprResult Result =3D InitSeq.Perform(*this, Entity, Kind,
-                                                MultiExprArg(*this, &Init,=
 1),
-                                                &DclT);
-      if (Result.isInvalid()) {
-        VDecl->setInvalidDecl();
-        return;
-      }
-
-      Init =3D Result.takeAs<Expr>();
-    }
-
-    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
-    // Don't check invalid declarations to avoid emitting useless diagnost=
ics.
-    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
-      // C99 6.7.8p4. All file scoped initializers need to be constant.
+
+    // C99 6.7.8p4. All file scoped initializers need to be constant.
+    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
       CheckForConstantInitializer(Init, DclT);
-    }
-  }
-  // If the type changed, it means we had an incomplete type that was
-  // completed by the initializer. For example:
-  //   int ary[] =3D { 1, 3, 5 };
-  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
-  if (!VDecl->isInvalidDecl() && (DclT !=3D SavT)) {
-    VDecl->setType(DclT);
-    Init->setType(DclT);
-  }
- =20
-  // Check any implicit conversions within the expression.
-  CheckImplicitConversions(Init, VDecl->getLocation());
- =20
-  if (!VDecl->isInvalidDecl())
-    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
-
-  if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
-      !VDecl->getType()->isDependentType() &&
-      !Init->isTypeDependent() && !Init->isValueDependent() &&
-      !Init->isConstantInitializer(Context,
-                                   VDecl->getType()->isReferenceType())) {
-    // FIXME: Improve this diagnostic to explain why the initializer is not
-    // a constant expression.
-    Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
-      << VDecl << Init->getSourceRange();
-  }
- =20
-  Init =3D MaybeCreateExprWithCleanups(Init);
-  // Attach the initializer to the decl.
-  VDecl->setInit(Init);
+  }
+
+  // We will represent direct-initialization similarly to copy-initializat=
ion:
+  //    int x(1);  -as-> int x =3D 1;
+  //    ClassType x(a,b,c); -as-> ClassType x =3D ClassType(a,b,c);
+  //
+  // Clients that want to distinguish between the two forms, can check for
+  // direct initializer using VarDecl::getInitStyle().
+  // A major benefit is that clients that don't particularly care about wh=
ich
+  // exactly form was it (like the CodeGen) can handle both cases without
+  // special case code.
+
+  // C++ 8.5p11:
+  // The form of initialization (using parentheses or '=3D') is generally
+  // insignificant, but does matter when the entity being initialized has a
+  // class type.
+  if (CXXDirectInit) {
+    assert(DirectInit && "Call-style initializer must be direct init.");
+    VDecl->setInitStyle(VarDecl::CallInit);
+  } else if (DirectInit) {
+    // This must be list-initialization. No other way is direct-initializa=
tion.
+    VDecl->setInitStyle(VarDecl::ListInit);
+  }
=20
   CheckCompleteVariableDeclaration(VDecl);
 }
@@ -6218,7 +6508,7 @@
   if (VarDecl *Var =3D dyn_cast<VarDecl>(RealDecl)) {
     QualType Type =3D Var->getType();
=20
-    // C++0x [dcl.spec.auto]p3
+    // C++11 [dcl.spec.auto]p3
     if (TypeMayContainAuto && Type->getContainedAutoType()) {
       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
         << Var->getDeclName() << Type;
@@ -6226,17 +6516,19 @@
       return;
     }
=20
-    // C++0x [dcl.constexpr]p9: An object or reference declared constexpr =
must
-    // have an initializer.
-    // C++0x [class.static.data]p3: A static data member can be declared w=
ith
+    // C++11 [class.static.data]p3: A static data member can be declared w=
ith
     // the constexpr specifier; if so, its declaration shall specify
     // a brace-or-equal-initializer.
-    //
-    // A static data member's definition may inherit an initializer from an
-    // in-class declaration.
-    if (Var->isConstexpr() && !Var->getAnyInitializer()) {
-      Diag(Var->getLocation(), diag::err_constexpr_var_requires_init)
-        << Var->getDeclName();
+    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied o=
nly to
+    // the definition of a variable [...] or the declaration of a static d=
ata
+    // member.
+    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
+      if (Var->isStaticDataMember())
+        Diag(Var->getLocation(),
+             diag::err_constexpr_static_mem_var_requires_init)
+          << Var->getDeclName();
+      else
+        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
       Var->setInvalidDecl();
       return;
     }
@@ -6295,7 +6587,7 @@
           // is accepted by gcc. Hence here we issue a warning instead of
           // an error and we do not invalidate the static declaration.
           // NOTE: to avoid multiple warnings, only check the first declar=
ation.
-          if (Var->getPreviousDeclaration() =3D=3D 0)
+          if (Var->getPreviousDecl() =3D=3D 0)
             RequireCompleteType(Var->getLocation(), Type,
                                 diag::ext_typecheck_decl_incomplete_type);
         }
@@ -6352,21 +6644,21 @@
     // Check for jumps past the implicit initializer.  C++0x
     // clarifies that this applies to a "variable with automatic
     // storage duration", not a "local variable".
-    // C++0x [stmt.dcl]p3
+    // C++11 [stmt.dcl]p3
     //   A program that jumps from a point where a variable with automatic
     //   storage duration is not in scope to a point where it is in scope =
is
     //   ill-formed unless the variable has scalar type, class type with a
     //   trivial default constructor and a trivial destructor, a cv-qualif=
ied
     //   version of one of these types, or an array of one of the preceding
     //   types and is declared without an initializer.
-    if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) {
+    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
       if (const RecordType *Record
             =3D Context.getBaseElementType(Type)->getAs<RecordType>()) {
         CXXRecordDecl *CXXRecord =3D cast<CXXRecordDecl>(Record->getDecl()=
);
-        if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) ||
-            (getLangOptions().CPlusPlus0x &&
-             (!CXXRecord->hasTrivialDefaultConstructor() ||
-              !CXXRecord->hasTrivialDestructor())))
+        // Mark the function for further checking even if the looser rules=
 of
+        // C++11 do not require such checks, so that we can diagnose
+        // incompatibilities with C++98.
+        if (!CXXRecord->isPOD())
           getCurFunction()->setHasBranchProtectedScope();
       }
     }
@@ -6394,8 +6686,11 @@
                                       MultiExprArg(*this, 0, 0));
     if (Init.isInvalid())
       Var->setInvalidDecl();
-    else if (Init.get())
+    else if (Init.get()) {
       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
+      // This is important for template substitution.
+      Var->setInitStyle(VarDecl::CallInit);
+    }
=20
     CheckCompleteVariableDeclaration(Var);
   }
@@ -6448,7 +6743,7 @@
=20
   // In ARC, don't allow jumps past the implicit initialization of a
   // local retaining variable.
-  if (getLangOptions().ObjCAutoRefCount &&
+  if (getLangOpts().ObjCAutoRefCount &&
       var->hasLocalStorage()) {
     switch (var->getType().getObjCLifetime()) {
     case Qualifiers::OCL_None:
@@ -6464,7 +6759,7 @@
   }
=20
   // All the following checks are C++ only.
-  if (!getLangOptions().CPlusPlus) return;
+  if (!getLangOpts().CPlusPlus) return;
=20
   QualType baseType =3D Context.getBaseElementType(var->getType());
   if (baseType->isDependentType()) return;
@@ -6480,7 +6775,7 @@
=20
     if (type->isStructureOrClassType()) {
       SourceLocation poi =3D var->getLocation();
-      Expr *varRef =3D new (Context) DeclRefExpr(var, type, VK_LValue, poi=
);
+      Expr *varRef =3Dnew (Context) DeclRefExpr(var, false, type, VK_LValu=
e, poi);
       ExprResult result =3D
         PerformCopyInitialization(
                         InitializedEntity::InitializeBlock(poi, type, fals=
e),
@@ -6493,15 +6788,41 @@
     }
   }
=20
-  // Check for global constructors.
-  if (!var->getDeclContext()->isDependentContext() &&
-      var->hasGlobalStorage() &&
-      !var->isStaticLocal() &&
-      var->getInit() &&
-      !var->getInit()->isConstantInitializer(Context,
-                                             baseType->isReferenceType()))
-    Diag(var->getLocation(), diag::warn_global_constructor)
-      << var->getInit()->getSourceRange();
+  Expr *Init =3D var->getInit();
+  bool IsGlobal =3D var->hasGlobalStorage() && !var->isStaticLocal();
+
+  if (!var->getDeclContext()->isDependentContext() && Init) {
+    if (IsGlobal && !var->isConstexpr() &&
+        getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
+                                            var->getLocation())
+          !=3D DiagnosticsEngine::Ignored &&
+        !Init->isConstantInitializer(Context, baseType->isReferenceType()))
+      Diag(var->getLocation(), diag::warn_global_constructor)
+        << Init->getSourceRange();
+
+    if (var->isConstexpr()) {
+      llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
+      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
+        SourceLocation DiagLoc =3D var->getLocation();
+        // If the note doesn't add any useful information other than a sou=
rce
+        // location, fold it into the primary diagnostic.
+        if (Notes.size() =3D=3D 1 && Notes[0].second.getDiagID() =3D=3D
+              diag::note_invalid_subexpr_in_const_expr) {
+          DiagLoc =3D Notes[0].first;
+          Notes.clear();
+        }
+        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
+          << var << Init->getSourceRange();
+        for (unsigned I =3D 0, N =3D Notes.size(); I !=3D N; ++I)
+          Diag(Notes[I].first, Notes[I].second);
+      }
+    } else if (var->isUsableInConstantExpressions(Context)) {
+      // Check whether the initializer of a const variable of integral or
+      // enumeration type is an ICE now, since we can't tell whether it was
+      // initialized by a constant expression if we check later.
+      var->checkInitIsICE();
+    }
+  }
=20
   // Require the destructor.
   if (const RecordType *recordType =3D baseType->getAs<RecordType>())
@@ -6586,11 +6907,16 @@
   const DeclSpec &DS =3D D.getDeclSpec();
=20
   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
+  // C++03 [dcl.stc]p2 also permits 'auto'.
   VarDecl::StorageClass StorageClass =3D SC_None;
   VarDecl::StorageClass StorageClassAsWritten =3D SC_None;
   if (DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_register) {
     StorageClass =3D SC_Register;
     StorageClassAsWritten =3D SC_Register;
+  } else if (getLangOpts().CPlusPlus &&
+             DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_auto) {
+    StorageClass =3D SC_Auto;
+    StorageClassAsWritten =3D SC_Auto;
   } else if (DS.getStorageClassSpec() !=3D DeclSpec::SCS_unspecified) {
     Diag(DS.getStorageClassSpecLoc(),
          diag::err_invalid_storage_class_in_func_decl);
@@ -6608,7 +6934,7 @@
   TypeSourceInfo *TInfo =3D GetTypeForDeclarator(D, S);
   QualType parmDeclType =3D TInfo->getType();
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // Check that there are no default arguments inside the type of this
     // parameter.
     CheckExtraCXXDefaultArguments(D);
@@ -6660,7 +6986,7 @@
   // the enclosing context.  This prevents them from accidentally
   // looking like class members in C++.
   ParmVarDecl *New =3D CheckParameter(Context.getTranslationUnitDecl(),
-                                    D.getSourceRange().getBegin(),
+                                    D.getLocStart(),
                                     D.getIdentifierLoc(), II,
                                     parmDeclType, TInfo,
                                     StorageClass, StorageClassAsWritten);
@@ -6715,7 +7041,7 @@
     return;
=20
   for (; Param !=3D ParamEnd; ++Param) {
-    if (!(*Param)->isUsed() && (*Param)->getDeclName() &&
+    if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
         !(*Param)->hasAttr<UnusedAttr>()) {
       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
         << (*Param)->getDeclName();
@@ -6732,7 +7058,7 @@
=20
   // Warn if the return value is pass-by-value and larger than the specifi=
ed
   // threshold.
-  if (ReturnTy.isPODType(Context)) {
+  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
     unsigned Size =3D Context.getTypeSizeInChars(ReturnTy).getQuantity();
     if (Size > LangOpts.NumLargeByValueCopy)
       Diag(D->getLocation(), diag::warn_return_value_size)
@@ -6743,7 +7069,7 @@
   // threshold.
   for (; Param !=3D ParamEnd; ++Param) {
     QualType T =3D (*Param)->getType();
-    if (!T.isPODType(Context))
+    if (T->isDependentType() || !T.isPODType(Context))
       continue;
     unsigned Size =3D Context.getTypeSizeInChars(T).getQuantity();
     if (Size > LangOpts.NumLargeByValueCopy)
@@ -6758,7 +7084,7 @@
                                   VarDecl::StorageClass StorageClass,
                                   VarDecl::StorageClass StorageClassAsWrit=
ten) {
   // In ARC, infer a lifetime qualifier for appropriate parameter types.
-  if (getLangOptions().ObjCAutoRefCount &&
+  if (getLangOpts().ObjCAutoRefCount &&
       T.getObjCLifetime() =3D=3D Qualifiers::OCL_None &&
       T->isObjCLifetimeType()) {
=20
@@ -6826,7 +7152,7 @@
     for (int i =3D FTI.NumArgs; i !=3D 0; /* decrement in loop */) {
       --i;
       if (FTI.ArgInfo[i].Param =3D=3D 0) {
-        llvm::SmallString<256> Code;
+        SmallString<256> Code;
         llvm::raw_svector_ostream(Code) << "  int "
                                         << FTI.ArgInfo[i].Ident->getName()
                                         << ";\n";
@@ -6856,7 +7182,7 @@
   assert(D.isFunctionDeclarator() && "Not a function declarator!");
   Scope *ParentScope =3D FnBodyScope->getParent();
=20
-  D.setFunctionDefinition(true);
+  D.setFunctionDefinitionKind(FDK_Definition);
   Decl *DP =3D HandleDeclarator(ParentScope, D,
                               MultiTemplateParamsArg(*this));
   return ActOnStartOfFunctionDef(FnBodyScope, DP);
@@ -6892,8 +7218,8 @@
     return false;
=20
   bool MissingPrototype =3D true;
-  for (const FunctionDecl *Prev =3D FD->getPreviousDeclaration();
-       Prev; Prev =3D Prev->getPreviousDeclaration()) {
+  for (const FunctionDecl *Prev =3D FD->getPreviousDecl();
+       Prev; Prev =3D Prev->getPreviousDecl()) {
     // Ignore any declarations that occur in function or method
     // scope, because they aren't visible from the header.
     if (Prev->getDeclContext()->isFunctionOrMethod())
@@ -6911,11 +7237,11 @@
   // was an extern inline function.
   const FunctionDecl *Definition;
   if (FD->isDefined(Definition) &&
-      !canRedefineFunction(Definition, getLangOptions())) {
-    if (getLangOptions().GNUMode && Definition->isInlineSpecified() &&
+      !canRedefineFunction(Definition, getLangOpts())) {
+    if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
         Definition->getStorageClass() =3D=3D SC_Extern)
       Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
-        << FD->getDeclName() << getLangOptions().CPlusPlus;
+        << FD->getDeclName() << getLangOpts().CPlusPlus;
     else
       Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
     Diag(Definition->getLocation(), diag::note_previous_definition);
@@ -6987,6 +7313,43 @@
     }
   }
=20
+  // If we had any tags defined in the function prototype,
+  // introduce them into the function scope.
+  if (FnBodyScope) {
+    for (llvm::ArrayRef<NamedDecl*>::iterator I =3D FD->getDeclsInPrototyp=
eScope().begin(),
+           E =3D FD->getDeclsInPrototypeScope().end(); I !=3D E; ++I) {
+      NamedDecl *D =3D *I;
+
+      // Some of these decls (like enums) may have been pinned to the tran=
slation unit
+      // for lack of a real context earlier. If so, remove from the transl=
ation unit
+      // and reattach to the current context.
+      if (D->getLexicalDeclContext() =3D=3D Context.getTranslationUnitDecl=
()) {
+        // Is the decl actually in the context?
+        for (DeclContext::decl_iterator DI =3D Context.getTranslationUnitD=
ecl()->decls_begin(),
+               DE =3D Context.getTranslationUnitDecl()->decls_end(); DI !=
=3D DE; ++DI) {
+          if (*DI =3D=3D D) { =20
+            Context.getTranslationUnitDecl()->removeDecl(D);
+            break;
+          }
+        }
+        // Either way, reassign the lexical decl context to our FunctionDe=
cl.
+        D->setLexicalDeclContext(CurContext);
+      }
+
+      // If the decl has a non-null name, make accessible in the current s=
cope.
+      if (!D->getName().empty())
+        PushOnScopeChains(D, FnBodyScope, /*AddToContext=3D*/false);
+
+      // Similarly, dive into enums and fish their constants out, making t=
hem
+      // accessible in this scope.
+      if (EnumDecl *ED =3D dyn_cast<EnumDecl>(D)) {
+        for (EnumDecl::enumerator_iterator EI =3D ED->enumerator_begin(),
+               EE =3D ED->enumerator_end(); EI !=3D EE; ++EI)
+          PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=3D*/false);
+      }
+    }
+  }
+
   // Checking attributes of current function definition
   // dllimport attribute.
   DLLImportAttr *DA =3D FD->getAttr<DLLImportAttr>();
@@ -7068,20 +7431,15 @@
=20
   if (FD) {
     FD->setBody(Body);
-    if (FD->isMain()) {
-      // C and C++ allow for main to automagically return 0.
-      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
-      FD->setHasImplicitReturnZero(true);
+
+    // If the function implicitly returns zero (like 'main') or is naked,
+    // don't complain about missing return statements.
+    if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
       WP.disableCheckFallThrough();
-    } else if (FD->hasAttr<NakedAttr>()) {
-      // If the function is marked 'naked', don't complain about missing r=
eturn
-      // statements.
-      WP.disableCheckFallThrough();
-    }
=20
     // MSVC permits the use of pure specifier (=3D0) on function definitio=
n,
     // defined at class scope, warn about this non standard construct.
-    if (getLangOptions().MicrosoftExt && FD->isPure())
+    if (getLangOpts().MicrosoftExt && FD->isPure())
       Diag(FD->getLocation(), diag::warn_pure_function_definition);
=20
     if (!FD->isInvalidDecl()) {
@@ -7096,7 +7454,8 @@
       computeNRVO(Body, getCurFunction());
     }
    =20
-    assert(FD =3D=3D getCurFunctionDecl() && "Function parsing confused");
+    assert((FD =3D=3D getCurFunctionDecl() || getCurLambda()->CallOperator=
 =3D=3D FD) &&
+           "Function parsing confused");
   } else if (ObjCMethodDecl *MD =3D dyn_cast_or_null<ObjCMethodDecl>(dcl))=
 {
     assert(MD =3D=3D getCurMethodDecl() && "Method parsing confused");
     MD->setBody(Body);
@@ -7154,33 +7513,34 @@
     // deletion in some later function.
     if (PP.getDiagnostics().hasErrorOccurred() ||
         PP.getDiagnostics().getSuppressAllDiagnostics()) {
-      ExprTemporaries.clear();
-      ExprNeedsCleanups =3D false;
+      DiscardCleanupsInEvaluationContext();
     } else if (!isa<FunctionTemplateDecl>(dcl)) {
       // Since the body is valid, issue any analysis-based warnings that a=
re
       // enabled.
       ActivePolicy =3D &WP;
     }
=20
-    if (FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
-        !CheckConstexprFunctionBody(FD, Body))
+    if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl(=
) &&
+        (!CheckConstexprFunctionDecl(FD) ||
+         !CheckConstexprFunctionBody(FD, Body)))
       FD->setInvalidDecl();
=20
-    assert(ExprTemporaries.empty() && "Leftover temporaries in function");
+    assert(ExprCleanupObjects.empty() && "Leftover temporaries in function=
");
     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
+    assert(MaybeODRUseExprs.empty() &&
+           "Leftover expressions for odr-use checking");
   }
  =20
   if (!IsInstantiation)
     PopDeclContext();
=20
-  PopFunctionOrBlockScope(ActivePolicy, dcl);
+  PopFunctionScopeInfo(ActivePolicy, dcl);
  =20
   // If any errors have occurred, clear out any temporaries that may have
   // been leftover. This ensures that these temporaries won't be picked up=
 for
   // deletion in some later function.
   if (getDiagnostics().hasErrorOccurred()) {
-    ExprTemporaries.clear();
-    ExprNeedsCleanups =3D false;
+    DiscardCleanupsInEvaluationContext();
   }
=20
   return dcl;
@@ -7191,6 +7551,9 @@
 /// relevant Decl.
 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
                                        ParsedAttributes &Attrs) {
+  // Always attach attributes to the underlying decl.
+  if (TemplateDecl *TD =3D dyn_cast<TemplateDecl>(D))
+    D =3D TD->getTemplatedDecl();
   ProcessDeclAttributeList(S, D, Attrs.getList());
 }
=20
@@ -7212,12 +7575,35 @@
   }
=20
   // Extension in C99.  Legal in C90, but warn about it.
+  unsigned diag_id;
   if (II.getName().startswith("__builtin_"))
-    Diag(Loc, diag::warn_builtin_unknown) << &II;
-  else if (getLangOptions().C99)
-    Diag(Loc, diag::ext_implicit_function_decl) << &II;
+    diag_id =3D diag::warn_builtin_unknown;
+  else if (getLangOpts().C99)
+    diag_id =3D diag::ext_implicit_function_decl;
   else
-    Diag(Loc, diag::warn_implicit_function_decl) << &II;
+    diag_id =3D diag::warn_implicit_function_decl;
+  Diag(Loc, diag_id) << &II;
+
+  // Because typo correction is expensive, only do it if the implicit
+  // function declaration is going to be treated as an error.
+  if (Diags.getDiagnosticLevel(diag_id, Loc) >=3D DiagnosticsEngine::Error=
) {
+    TypoCorrection Corrected;
+    DeclFilterCCC<FunctionDecl> Validator;
+    if (S && (Corrected =3D CorrectTypo(DeclarationNameInfo(&II, Loc),
+                                      LookupOrdinaryName, S, 0, Validator)=
)) {
+      std::string CorrectedStr =3D Corrected.getAsString(getLangOpts());
+      std::string CorrectedQuotedStr =3D Corrected.getQuoted(getLangOpts()=
);
+      FunctionDecl *Func =3D Corrected.getCorrectionDeclAs<FunctionDecl>();
+
+      Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
+          << FixItHint::CreateReplacement(Loc, CorrectedStr);
+
+      if (Func->getLocation().isValid()
+          && !II.getName().startswith("__builtin_"))
+        Diag(Func->getLocation(), diag::note_previous_decl)
+            << CorrectedQuotedStr;
+    }
+  }
=20
   // Set a Declarator for the implicit definition: int foo();
   const char *Dummy;
@@ -7230,6 +7616,7 @@
   Declarator D(DS, Declarator::BlockContext);
   D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(=
), 0,
                                              0, 0, true, SourceLocation(),
+                                             SourceLocation(), SourceLocat=
ion(),
                                              SourceLocation(),
                                              EST_None, SourceLocation(),
                                              0, 0, 0, 0, Loc, Loc, D),
@@ -7272,10 +7659,16 @@
     unsigned FormatIdx;
     bool HasVAListArg;
     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListAr=
g)) {
-      if (!FD->getAttr<FormatAttr>())
+      if (!FD->getAttr<FormatAttr>()) {
+        const char *fmt =3D "printf";
+        unsigned int NumParams =3D FD->getNumParams();
+        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
+            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerTyp=
e())
+          fmt =3D "NSString";
         FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
-                                                "printf", FormatIdx+1,
+                                               fmt, FormatIdx+1,
                                                HasVAListArg ? 0 : FormatId=
x+2));
+      }
     }
     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
                                              HasVAListArg)) {
@@ -7288,7 +7681,7 @@
     // Mark const if we don't care about errno and that is the only
     // thing preventing the function from being const. This allows
     // IRgen to use LLVM intrinsics for such functions.
-    if (!getLangOptions().MathErrno &&
+    if (!getLangOpts().MathErrno &&
         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
       if (!FD->getAttr<ConstAttr>())
         FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
@@ -7306,7 +7699,7 @@
   IdentifierInfo *Name =3D FD->getIdentifier();
   if (!Name)
     return;
-  if ((!getLangOptions().CPlusPlus &&
+  if ((!getLangOpts().CPlusPlus &&
        FD->getDeclContext()->isTranslationUnit()) ||
       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() =3D=3D
@@ -7316,16 +7709,7 @@
   } else
     return;
=20
-  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
-    // FIXME: NSLog and NSLogv should be target specific
-    if (const FormatAttr *Format =3D FD->getAttr<FormatAttr>()) {
-      // FIXME: We known better than our headers.
-      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
-    } else
-      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
-                                             "printf", 1,
-                                             Name->isStr("NSLogv") ? 0 : 2=
));
-  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
+  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
     // target-specific builtins, perhaps?
     if (!FD->getAttr<FormatAttr>())
@@ -7347,7 +7731,7 @@
=20
   // Scope manipulation handled by caller.
   TypedefDecl *NewTD =3D TypedefDecl::Create(Context, CurContext,
-                                           D.getSourceRange().getBegin(),
+                                           D.getLocStart(),
                                            D.getIdentifierLoc(),
                                            D.getIdentifier(),
                                            TInfo);
@@ -7406,6 +7790,52 @@
 }
=20
=20
+/// \brief Check that this is a valid underlying type for an enum declarat=
ion.
+bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
+  SourceLocation UnderlyingLoc =3D TI->getTypeLoc().getBeginLoc();
+  QualType T =3D TI->getType();
+
+  if (T->isDependentType() || T->isIntegralType(Context))
+    return false;
+
+  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
+  return true;
+}
+
+/// Check whether this is a valid redeclaration of a previous enumeration.
+/// \return true if the redeclaration was invalid.
+bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
+                                  QualType EnumUnderlyingTy,
+                                  const EnumDecl *Prev) {
+  bool IsFixed =3D !EnumUnderlyingTy.isNull();
+
+  if (IsScoped !=3D Prev->isScoped()) {
+    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
+      << Prev->isScoped();
+    Diag(Prev->getLocation(), diag::note_previous_use);
+    return true;
+  }
+
+  if (IsFixed && Prev->isFixed()) {
+    if (!EnumUnderlyingTy->isDependentType() &&
+        !Prev->getIntegerType()->isDependentType() &&
+        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
+                                        Prev->getIntegerType())) {
+      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
+        << EnumUnderlyingTy << Prev->getIntegerType();
+      Diag(Prev->getLocation(), diag::note_previous_use);
+      return true;
+    }
+  } else if (IsFixed !=3D Prev->isFixed()) {
+    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
+      << Prev->isFixed();
+    Diag(Prev->getLocation(), diag::note_previous_use);
+    return true;
+  }
+
+  return false;
+}
+
 /// \brief Determine whether a tag with a given kind is acceptable
 /// as a redeclaration of the given tag declaration.
 ///
@@ -7512,15 +7942,18 @@
                      SourceLocation ModulePrivateLoc,
                      MultiTemplateParamsArg TemplateParameterLists,
                      bool &OwnedDecl, bool &IsDependent,
-                     bool ScopedEnum, bool ScopedEnumUsesClassTag,
+                     SourceLocation ScopedEnumKWLoc,
+                     bool ScopedEnumUsesClassTag,
                      TypeResult UnderlyingType) {
   // If this is not a definition, it must have a name.
+  IdentifierInfo *OrigName =3D Name;
   assert((Name !=3D 0 || TUK =3D=3D TUK_Definition) &&
          "Nameless record must be a definition!");
   assert(TemplateParameterLists.size() =3D=3D 0 || TUK !=3D TUK_Reference);
=20
   OwnedDecl =3D false;
   TagTypeKind Kind =3D TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
+  bool ScopedEnum =3D ScopedEnumKWLoc.isValid();
=20
   // FIXME: Check explicit specializations more carefully.
   bool isExplicitSpecialization =3D false;
@@ -7576,23 +8009,18 @@
       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
       // integral type; any cv-qualification is ignored.
       TypeSourceInfo *TI =3D 0;
-      QualType T =3D GetTypeFromParser(UnderlyingType.get(), &TI);
+      GetTypeFromParser(UnderlyingType.get(), &TI);
       EnumUnderlying =3D TI;
=20
-      SourceLocation UnderlyingLoc =3D TI->getTypeLoc().getBeginLoc();
-
-      if (!T->isDependentType() && !T->isIntegralType(Context)) {
-        Diag(UnderlyingLoc, diag::err_enum_invalid_underlying)
-          << T;
+      if (CheckEnumUnderlyingType(TI))
         // Recover by falling back to int.
         EnumUnderlying =3D Context.IntTy.getTypePtr();
-      }
-
-      if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI,=20
+
+      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), =
TI,
                                           UPPC_FixedUnderlyingType))
         EnumUnderlying =3D Context.IntTy.getTypePtr();
=20
-    } else if (getLangOptions().MicrosoftExt)
+    } else if (getLangOpts().MicrosoftMode)
       // Microsoft enums are always of int type.
       EnumUnderlying =3D Context.IntTy.getTypePtr();
   }
@@ -7686,7 +8114,7 @@
     if (Previous.isAmbiguous())
       return 0;
=20
-    if (!getLangOptions().CPlusPlus && TUK !=3D TUK_Reference) {
+    if (!getLangOpts().CPlusPlus && TUK !=3D TUK_Reference) {
       // FIXME: This makes sure that we ignore the contexts associated
       // with C structs, unions, and enums when looking for a matching
       // tag declaration or definition. See the similar lookup tweak
@@ -7697,6 +8125,7 @@
   } else if (S->isFunctionPrototypeScope()) {
     // If this is an enum declaration in function prototype scope, set its
     // initial context to the translation unit.
+    // FIXME: [citation needed]
     SearchDC =3D Context.getTranslationUnitDecl();
   }
=20
@@ -7708,7 +8137,7 @@
     Previous.clear();
   }
=20
-  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
+  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
     // This is a declaration of or a reference to "std::bad_alloc".
     isStdBadAlloc =3D true;
@@ -7759,12 +8188,12 @@
       // Find the context where we'll be declaring the tag.
       // FIXME: We would like to maintain the current DeclContext as the
       // lexical context,
-      while (SearchDC->isRecord() || SearchDC->isTransparentContext())
+      while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
         SearchDC =3D SearchDC->getParent();
=20
       // Find the scope where we'll be declaring the tag.
       while (S->isClassScope() ||
-             (getLangOptions().CPlusPlus &&
+             (getLangOpts().CPlusPlus &&
               S->isFunctionPrototypeScope()) ||
              ((S->getFlags() & Scope::DeclScope) =3D=3D 0) ||
              (S->getEntity() &&
@@ -7781,7 +8210,7 @@
=20
     // In C++, we need to do a redeclaration lookup to properly
     // diagnose some problems.
-    if (getLangOptions().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       Previous.setRedeclarationKind(ForRedeclaration);
       LookupQualifiedName(Previous, SearchDC);
     }
@@ -7799,7 +8228,7 @@
     // technically forbidden by the current standard but which is
     // okay according to the likely resolution of an open issue;
     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
-    if (getLangOptions().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       if (TypedefNameDecl *TD =3D dyn_cast<TypedefNameDecl>(PrevDecl)) {
         if (const TagType *TT =3D TD->getUnderlyingType()->getAs<TagType>(=
)) {
           TagDecl *Tag =3D TT->getDecl();
@@ -7851,36 +8280,28 @@
         if (Kind =3D=3D TTK_Enum && PrevTagDecl->getTagKind() =3D=3D TTK_E=
num) {
           const EnumDecl *PrevEnum =3D cast<EnumDecl>(PrevTagDecl);
=20
-          // All conflicts with previous declarations are recovered by
-          // returning the previous declaration.
-          if (ScopedEnum !=3D PrevEnum->isScoped()) {
-            Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch)
-              << PrevEnum->isScoped();
-            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
+          // If this is an elaborated-type-specifier for a scoped enumerat=
ion,
+          // the 'class' keyword is not necessary and not permitted.
+          if (TUK =3D=3D TUK_Reference || TUK =3D=3D TUK_Friend) {
+            if (ScopedEnum)
+              Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
+                << PrevEnum->isScoped()
+                << FixItHint::CreateRemoval(ScopedEnumKWLoc);
             return PrevTagDecl;
           }
-          else if (EnumUnderlying && PrevEnum->isFixed()) {
-            QualType T;
-            if (TypeSourceInfo *TI =3D EnumUnderlying.dyn_cast<TypeSourceI=
nfo*>())
-                T =3D TI->getType();
-            else
-                T =3D QualType(EnumUnderlying.get<const Type*>(), 0);
-
-            if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerTyp=
e())) {
-              Diag(NameLoc.isValid() ? NameLoc : KWLoc,=20
-                   diag::err_enum_redeclare_type_mismatch)
-                << T
-                << PrevEnum->getIntegerType();
-              Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
-              return PrevTagDecl;
-            }
-          }
-          else if (!EnumUnderlying.isNull() !=3D PrevEnum->isFixed()) {
-            Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch)
-              << PrevEnum->isFixed();
-            Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
-            return PrevTagDecl;
-          }
+
+          QualType EnumUnderlyingTy;
+          if (TypeSourceInfo *TI =3D EnumUnderlying.dyn_cast<TypeSourceInf=
o*>())
+            EnumUnderlyingTy =3D TI->getType();
+          else if (const Type *T =3D EnumUnderlying.dyn_cast<const Type*>(=
))
+            EnumUnderlyingTy =3D QualType(T, 0);
+
+          // All conflicts with previous declarations are recovered by
+          // returning the previous declaration, unless this is a definiti=
on,
+          // in which case we want the caller to bail out.
+          if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
+                                     ScopedEnum, EnumUnderlyingTy, PrevEnu=
m))
+            return TUK =3D=3D TUK_Declaration ? PrevTagDecl : 0;
         }
=20
         if (!Invalid) {
@@ -7891,7 +8312,7 @@
           // For our current ASTs this shouldn't be a problem, but will
           // need to be changed with DeclGroups.
           if ((TUK =3D=3D TUK_Reference && (!PrevTagDecl->getFriendObjectK=
ind() ||
-               getLangOptions().MicrosoftExt)) || TUK =3D=3D TUK_Friend)
+               getLangOpts().MicrosoftExt)) || TUK =3D=3D TUK_Friend)
             return PrevTagDecl;
=20
           // Diagnose attempts to redefine a tag.
@@ -7900,11 +8321,25 @@
               // If we're defining a specialization and the previous defin=
ition
               // is from an implicit instantiation, don't emit an error
               // here; we'll catch this in the general case below.
-              if (!isExplicitSpecialization ||
-                  !isa<CXXRecordDecl>(Def) ||
-                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind(=
)=20
-                                               =3D=3D TSK_ExplicitSpeciali=
zation) {
-                Diag(NameLoc, diag::err_redefinition) << Name;
+              bool IsExplicitSpecializationAfterInstantiation =3D false;
+              if (isExplicitSpecialization) {
+                if (CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(Def))
+                  IsExplicitSpecializationAfterInstantiation =3D
+                    RD->getTemplateSpecializationKind() !=3D
+                    TSK_ExplicitSpecialization;
+                else if (EnumDecl *ED =3D dyn_cast<EnumDecl>(Def))
+                  IsExplicitSpecializationAfterInstantiation =3D
+                    ED->getTemplateSpecializationKind() !=3D
+                    TSK_ExplicitSpecialization;
+              }
+
+              if (!IsExplicitSpecializationAfterInstantiation) {
+                // A redeclaration in function prototype scope in C isn't
+                // visible elsewhere, so merely issue a warning.
+                if (!getLangOpts().CPlusPlus && S->containedInPrototypeSco=
pe())
+                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << =
Name;
+                else
+                  Diag(NameLoc, diag::err_redefinition) << Name;
                 Diag(Def->getLocation(), diag::note_previous_definition);
                 // If this is a redefinition, recover by making this
                 // struct be anonymous, which will make any later
@@ -7951,8 +8386,6 @@
     // lookup.  This is only actually possible in C++, where a few
     // things like templates still live in the tag namespace.
     } else {
-      assert(getLangOptions().CPlusPlus);
-
       // Use a better diagnostic if an elaborated-type-specifier
       // found the wrong kind of type on the first
       // (non-redeclaration) lookup.
@@ -8033,7 +8466,7 @@
     // If this is an undefined enum, warn.
     if (TUK !=3D TUK_Definition && !Invalid) {
       TagDecl *Def;
-      if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
+      if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
         // C++0x: 7.2p2: opaque-enum-declaration.
         // Conflicts are diagnosed above. Do nothing.
       }
@@ -8043,9 +8476,9 @@
         Diag(Def->getLocation(), diag::note_previous_definition);
       } else {
         unsigned DiagID =3D diag::ext_forward_ref_enum;
-        if (getLangOptions().MicrosoftExt)
+        if (getLangOpts().MicrosoftMode)
           DiagID =3D diag::ext_ms_forward_ref_enum;
-        else if (getLangOptions().CPlusPlus)
+        else if (getLangOpts().CPlusPlus)
           DiagID =3D diag::err_forward_ref_enum;
         Diag(Loc, DiagID);
        =20
@@ -8071,7 +8504,7 @@
=20
     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.=
g.:
     // struct X { int A; } D;    D should chain to X.
-    if (getLangOptions().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       // FIXME: Look for a way to use RecordDecl for simple structs.
       New =3D CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, N=
ame,
                                   cast_or_null<CXXRecordDecl>(PrevDecl));
@@ -8086,6 +8519,16 @@
   // Maybe add qualifier info.
   if (SS.isNotEmpty()) {
     if (SS.isSet()) {
+      // If this is either a declaration or a definition, check the=20
+      // nested-name-specifier against the current context. We don't do th=
is
+      // for explicit specializations, because they have similar checking
+      // (with more specific diagnostics) in the call to=20
+      // CheckMemberSpecialization, below.
+      if (!isExplicitSpecialization &&
+          (TUK =3D=3D TUK_Definition || TUK =3D=3D TUK_Declaration) &&
+          diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
+        Invalid =3D true;
+
       New->setQualifierInfo(SS.getWithLocInContext(Context));
       if (TemplateParameterLists.size() > 0) {
         New->setTemplateParameterListsInfo(Context,
@@ -8112,19 +8555,14 @@
     AddMsStructLayoutForRecord(RD);
   }
=20
-  if (PrevDecl && PrevDecl->isModulePrivate())
-    New->setModulePrivate();
-  else if (ModulePrivateLoc.isValid()) {
+  if (ModulePrivateLoc.isValid()) {
     if (isExplicitSpecialization)
       Diag(New->getLocation(), diag::err_module_private_specialization)
         << 2
         << FixItHint::CreateRemoval(ModulePrivateLoc);
-    else if (PrevDecl && !PrevDecl->isModulePrivate())
-      diagnoseModulePrivateRedeclaration(New, PrevDecl, ModulePrivateLoc);
     // __module_private__ does not apply to local classes. However, we only
     // diagnose this as an error when the declaration specifiers are
     // freestanding. Here, we just ignore the __module_private__.
-    // foobar
     else if (!SearchDC->isFunctionOrMethod())
       New->setModulePrivate();
   }
@@ -8133,7 +8571,7 @@
   // check the specialization.
   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
     Invalid =3D true;
-
+          =20
   if (Invalid)
     New->setInvalidDecl();
=20
@@ -8142,7 +8580,7 @@
=20
   // If we're declaring or defining a tag in function prototype scope
   // in C, note that this type can only be used within the function.
-  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
+  if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New=
);
=20
   // Set the lexical context. If the tag has a C++ scope specifier, the
@@ -8155,7 +8593,7 @@
   // the tag name visible.
   if (TUK =3D=3D TUK_Friend)
     New->setObjectOfFriendDecl(/* PreviouslyDeclared =3D */ !Previous.empt=
y() ||
-                               getLangOptions().MicrosoftExt);
+                               getLangOpts().MicrosoftExt);
=20
   // Set the access specifier.
   if (!Invalid && SearchDC->isRecord())
@@ -8172,7 +8610,7 @@
       New->setAccess(PrevDecl->getAccess());
=20
     DeclContext *DC =3D New->getDeclContext()->getRedeclContext();
-    DC->makeDeclVisibleInContext(New, /* Recoverable =3D */ false);
+    DC->makeDeclVisibleInContext(New);
     if (Name) // can be null along some error paths
       if (Scope *EnclosingScope =3D getScopeForDeclContext(S, DC))
         PushOnScopeChains(New, EnclosingScope, /* AddToContext =3D */ fals=
e);
@@ -8180,7 +8618,7 @@
     S =3D getNonFieldDeclScope(S);
     PushOnScopeChains(New, S, !IsForwardReference);
     if (IsForwardReference)
-      SearchDC->makeDeclVisibleInContext(New, /* Recoverable =3D */ false);
+      SearchDC->makeDeclVisibleInContext(New);
=20
   } else {
     CurContext->addDecl(New);
@@ -8193,6 +8631,12 @@
         II->isStr("FILE"))
       Context.setFILEDecl(New);
=20
+  // If we were in function prototype scope (and not in C++ mode), add this
+  // tag to the list of decls to inject into the function definition scope.
+  if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
+      InFunctionDeclarator && Name)
+    DeclsInPrototypeScope.push_back(New);
+
   OwnedDecl =3D true;
   return New;
 }
@@ -8256,6 +8700,13 @@
   TagDecl *Tag =3D cast<TagDecl>(TagD);
   Tag->setRBraceLoc(RBraceLoc);
=20
+  // Make sure we "complete" the definition even it is invalid.
+  if (Tag->isBeingDefined()) {
+    assert(Tag->isInvalidDecl() && "We should already have completed it");
+    if (RecordDecl *RD =3D dyn_cast<RecordDecl>(Tag))
+      RD->completeDefinition();
+  }
+
   if (isa<CXXRecordDecl>(Tag))
     FieldCollector->FinishClass();
=20
@@ -8271,13 +8722,14 @@
   PopDeclContext();
 }
=20
-void Sema::ActOnObjCTemporaryExitContainerContext() {
-  OriginalLexicalContext =3D CurContext;
+void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
+  assert(DC =3D=3D CurContext && "Mismatch of container contexts");
+  OriginalLexicalContext =3D DC;
   ActOnObjCContainerFinishDefinition();
 }
=20
-void Sema::ActOnObjCReenterContainerContext() {
-  ActOnObjCContainerStartDefinition(cast<Decl>(OriginalLexicalContext));
+void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
+  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
   OriginalLexicalContext =3D 0;
 }
=20
@@ -8286,6 +8738,12 @@
   TagDecl *Tag =3D cast<TagDecl>(TagD);
   Tag->setInvalidDecl();
=20
+  // Make sure we "complete" the definition even it is invalid.
+  if (Tag->isBeingDefined()) {
+    if (RecordDecl *RD =3D dyn_cast<RecordDecl>(Tag))
+      RD->completeDefinition();
+  }
+
   // We're undoing ActOnTagStartDefinition here, not
   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
   // the FieldCollector.
@@ -8294,9 +8752,10 @@
 }
=20
 // Note that FieldName may be null for anonymous bitfields.
-bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldNa=
me,
-                          QualType FieldTy, const Expr *BitWidth,
-                          bool *ZeroWidth) {
+ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
+                                IdentifierInfo *FieldName,
+                                QualType FieldTy, Expr *BitWidth,
+                                bool *ZeroWidth) {
   // Default to true; that shouldn't confuse checks for emptiness
   if (ZeroWidth)
     *ZeroWidth =3D true;
@@ -8306,7 +8765,7 @@
   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType=
()) {
     // Handle incomplete types with specific error.
     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
-      return true;
+      return ExprError();
     if (FieldName)
       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
         << FieldName << FieldTy << BitWidth->getSourceRange();
@@ -8314,16 +8773,18 @@
       << FieldTy << BitWidth->getSourceRange();
   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
                                              UPPC_BitFieldWidth))
-    return true;
+    return ExprError();
=20
   // If the bit-width is type- or value-dependent, don't try to check
   // it now.
   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
-    return false;
+    return Owned(BitWidth);
=20
   llvm::APSInt Value;
-  if (VerifyIntegerConstantExpression(BitWidth, &Value))
-    return true;
+  ExprResult ICE =3D VerifyIntegerConstantExpression(BitWidth, &Value);
+  if (ICE.isInvalid())
+    return ICE;
+  BitWidth =3D ICE.take();
=20
   if (Value !=3D 0 && ZeroWidth)
     *ZeroWidth =3D false;
@@ -8343,7 +8804,7 @@
   if (!FieldTy->isDependentType()) {
     uint64_t TypeSize =3D Context.getTypeSize(FieldTy);
     if (Value.getZExtValue() > TypeSize) {
-      if (!getLangOptions().CPlusPlus) {
+      if (!getLangOpts().CPlusPlus) {
         if (FieldName)=20
           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
             << FieldName << (unsigned)Value.getZExtValue()=20
@@ -8363,7 +8824,7 @@
     }
   }
=20
-  return false;
+  return Owned(BitWidth);
 }
=20
 /// ActOnField - Each field of a C struct/union is passed into this in ord=
er
@@ -8388,7 +8849,7 @@
=20
   TypeSourceInfo *TInfo =3D GetTypeForDeclarator(D, S);
   QualType T =3D TInfo->getType();
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     CheckExtraCXXDefaultArguments(D);
=20
     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
@@ -8408,15 +8869,25 @@
       << 2;
  =20
   // Check to see if this name was declared as a member previously
+  NamedDecl *PrevDecl =3D 0;
   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration=
);
   LookupName(Previous, S);
-  assert((Previous.empty() || Previous.isOverloadedResult() ||=20
-          Previous.isSingleResult())=20
-    && "Lookup of member name should be either overloaded, single or null"=
);
-
-  // If the name is overloaded then get any declaration else get the singl=
e result
-  NamedDecl *PrevDecl =3D Previous.isOverloadedResult() ?
-    Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>();
+  switch (Previous.getResultKind()) {
+    case LookupResult::Found:
+    case LookupResult::FoundUnresolvedValue:
+      PrevDecl =3D Previous.getAsSingle<NamedDecl>();
+      break;
+     =20
+    case LookupResult::FoundOverloaded:
+      PrevDecl =3D Previous.getRepresentativeDecl();
+      break;
+     =20
+    case LookupResult::NotFound:
+    case LookupResult::NotFoundInCurrentInstantiation:
+    case LookupResult::Ambiguous:
+      break;
+  }
+  Previous.suppressDiagnostics();
=20
   if (PrevDecl && PrevDecl->isTemplateParameter()) {
     // Maybe we will complain about the shadowed template parameter.
@@ -8430,7 +8901,7 @@
=20
   bool Mutable
     =3D (D.getDeclSpec().getStorageClassSpec() =3D=3D DeclSpec::SCS_mutabl=
e);
-  SourceLocation TSSL =3D D.getSourceRange().getBegin();
+  SourceLocation TSSL =3D D.getLocStart();
   FieldDecl *NewFD
     =3D CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasIn=
it,
                      TSSL, AS, PrevDecl, &D);
@@ -8481,11 +8952,19 @@
   }
=20
   QualType EltTy =3D Context.getBaseElementType(T);
-  if (!EltTy->isDependentType() &&
-      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
-    // Fields of incomplete type force their record to be invalid.
-    Record->setInvalidDecl();
-    InvalidDecl =3D true;
+  if (!EltTy->isDependentType()) {
+    if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
+      // Fields of incomplete type force their record to be invalid.
+      Record->setInvalidDecl();
+      InvalidDecl =3D true;
+    } else {
+      NamedDecl *Def;
+      EltTy->isIncompleteType(&Def);
+      if (Def && Def->isInvalidDecl()) {
+        Record->setInvalidDecl();
+        InvalidDecl =3D true;
+      }
+    }
   }
=20
   // C99 6.7.2.1p8: A member of a structure or union may have any type oth=
er
@@ -8519,11 +8998,13 @@
=20
   bool ZeroWidth =3D false;
   // If this is declared as a bit-field, check the bit-field.
-  if (!InvalidDecl && BitWidth &&
-      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
-    InvalidDecl =3D true;
-    BitWidth =3D 0;
-    ZeroWidth =3D false;
+  if (!InvalidDecl && BitWidth) {
+    BitWidth =3D VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
+    if (!BitWidth) {
+      InvalidDecl =3D true;
+      BitWidth =3D 0;
+      ZeroWidth =3D false;
+    }
   }
=20
   // Check that 'mutable' is consistent with the type of the declaration.
@@ -8555,7 +9036,7 @@
     NewFD->setInvalidDecl();
   }
=20
-  if (!InvalidDecl && getLangOptions().CPlusPlus) {
+  if (!InvalidDecl && getLangOpts().CPlusPlus) {
     if (Record->isUnion()) {
       if (const RecordType *RT =3D EltTy->getAs<RecordType>()) {
         CXXRecordDecl* RDecl =3D cast<CXXRecordDecl>(RT->getDecl());
@@ -8565,7 +9046,7 @@
           // destructor, or a non-trivial copy assignment operator
           // cannot be a member of a union, nor can an array of such
           // objects.
-          if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD))
+          if (CheckNontrivialField(NewFD))
             NewFD->setInvalidDecl();
         }
       }
@@ -8588,7 +9069,7 @@
=20
   // In auto-retain/release, infer strong retension for fields of
   // retainable type.
-  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
+  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
     NewFD->setInvalidDecl();
=20
   if (T.isObjCGCWeak())
@@ -8600,7 +9081,7 @@
=20
 bool Sema::CheckNontrivialField(FieldDecl *FD) {
   assert(FD);
-  assert(getLangOptions().CPlusPlus && "valid check only for C++");
+  assert(getLangOpts().CPlusPlus && "valid check only for C++");
=20
   if (FD->isInvalidDecl())
     return true;
@@ -8624,7 +9105,8 @@
         member =3D CXXDestructor;
=20
       if (member !=3D CXXInvalid) {
-        if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember())=
 {
+        if (!getLangOpts().CPlusPlus0x &&
+            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
           // Objective-C++ ARC: it is an error to have a non-trivial field=
 of
           // a union. However, system headers in Objective-C programs=20
           // occasionally have Objective-C lifetime objects within unions,
@@ -8638,11 +9120,13 @@
             return false;
           }
         }
-       =20
-        Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_mem=
ber)
-              << (int)FD->getParent()->isUnion() << FD->getDeclName() << m=
ember;
+
+        Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
+               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_mem=
ber :
+               diag::err_illegal_union_or_anon_struct_member)
+          << (int)FD->getParent()->isUnion() << FD->getDeclName() << membe=
r;
         DiagnoseNontrivial(RT, member);
-        return true;
+        return !getLangOpts().CPlusPlus0x;
       }
     }
   }
@@ -8650,6 +9134,19 @@
   return false;
 }
=20
+/// If the given constructor is user-provided, produce a diagnostic explai=
ning
+/// that it makes the class non-trivial.
+static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
+                                               CXXConstructorDecl *CD,
+                                               Sema::CXXSpecialMember CSM)=
 {
+  if (!CD->isUserProvided())
+    return false;
+
+  SourceLocation CtorLoc =3D CD->getLocation();
+  S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
+  return true;
+}
+
 /// DiagnoseNontrivial - Given that a class has a non-trivial
 /// special member, figure out why.
 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member=
) {
@@ -8664,17 +9161,20 @@
   case CXXDefaultConstructor:
     if (RD->hasUserDeclaredConstructor()) {
       typedef CXXRecordDecl::ctor_iterator ctor_iter;
-      for (ctor_iter ci =3D RD->ctor_begin(), ce =3D RD->ctor_end(); ci !=
=3D ce;++ci){
-        const FunctionDecl *body =3D 0;
-        ci->hasBody(body);
-        if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(=
)) {
-          SourceLocation CtorLoc =3D ci->getLocation();
-          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << membe=
r;
+      for (ctor_iter CI =3D RD->ctor_begin(), CE =3D RD->ctor_end(); CI !=
=3D CE; ++CI)
+        if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
           return;
-        }
-      }
-
-      llvm_unreachable("found no user-declared constructors");
+
+      // No user-provided constructors; look for constructor templates.
+      typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
+          tmpl_iter;
+      for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
+           TI !=3D TE; ++TI) {
+        CXXConstructorDecl *CD =3D
+            dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
+        if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member=
))
+          return;
+      }
     }
     break;
=20
@@ -8699,7 +9199,7 @@
     if (RD->hasUserDeclaredCopyAssignment()) {
       // FIXME: this should use the location of the copy
       // assignment, not the type.
-      SourceLocation TyLoc =3D RD->getSourceRange().getBegin();
+      SourceLocation TyLoc =3D RD->getLocStart();
       Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
       return;
     }
@@ -8731,7 +9231,7 @@
     // so we just iterate through the direct bases.
     for (base_iter bi =3D RD->bases_begin(), be =3D RD->bases_end(); bi !=
=3D be; ++bi)
       if (bi->isVirtual()) {
-        SourceLocation BaseLoc =3D bi->getSourceRange().getBegin();
+        SourceLocation BaseLoc =3D bi->getLocStart();
         Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
         return;
       }
@@ -8741,7 +9241,7 @@
     for (meth_iter mi =3D RD->method_begin(), me =3D RD->method_end(); mi =
!=3D me;
          ++mi) {
       if (mi->isVirtual()) {
-        SourceLocation MLoc =3D mi->getSourceRange().getBegin();
+        SourceLocation MLoc =3D mi->getLocStart();
         Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
         return;
       }
@@ -8768,7 +9268,7 @@
     assert(BaseRT && "Don't know how to handle dependent bases");
     CXXRecordDecl *BaseRecTy =3D cast<CXXRecordDecl>(BaseRT->getDecl());
     if (!(BaseRecTy->*hasTrivial)()) {
-      SourceLocation BaseLoc =3D bi->getSourceRange().getBegin();
+      SourceLocation BaseLoc =3D bi->getLocStart();
       Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << me=
mber;
       DiagnoseNontrivial(BaseRT, member);
       return;
@@ -8843,10 +9343,9 @@
=20
   if (BitWidth) {
     // 6.7.2.1p3, 6.7.2.1p4
-    if (VerifyBitField(Loc, II, T, BitWidth)) {
+    BitWidth =3D VerifyBitField(Loc, II, T, BitWidth).take();
+    if (!BitWidth)
       D.setInvalidType();
-      BitWidth =3D 0;
-    }
   } else {
     // Not a bitfield.
=20
@@ -8870,6 +9369,8 @@
                                         : ObjCIvarDecl::None;
   // Must set ivar's DeclContext to its enclosing interface.
   ObjCContainerDecl *EnclosingDecl =3D cast<ObjCContainerDecl>(CurContext);
+  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
+    return 0;
   ObjCContainerDecl *EnclosingContext;
   if (ObjCImplementationDecl *IMPDecl =3D
       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
@@ -8914,7 +9415,7 @@
     NewID->setInvalidDecl();
=20
   // In ARC, infer 'retaining' for ivars of retainable type.
-  if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
+  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
     NewID->setInvalidDecl();
=20
   if (D.getDeclSpec().isModulePrivateSpecified())
@@ -8980,11 +9481,23 @@
   if (EnclosingDecl->isInvalidDecl())
     return;
=20
+  RecordDecl *Record =3D dyn_cast<RecordDecl>(EnclosingDecl);
+
+  // Start counting up the number of named members; make sure to include
+  // members of anonymous structs and unions in the total.
+  unsigned NumNamedMembers =3D 0;
+  if (Record) {
+    for (RecordDecl::decl_iterator i =3D Record->decls_begin(),
+                                   e =3D Record->decls_end(); i !=3D e; i+=
+) {
+      if (IndirectFieldDecl *IFD =3D dyn_cast<IndirectFieldDecl>(*i))
+        if (IFD->getDeclName())
+          ++NumNamedMembers;
+    }
+  }
+
   // Verify that all the fields are okay.
-  unsigned NumNamedMembers =3D 0;
   SmallVector<FieldDecl*, 32> RecFields;
=20
-  RecordDecl *Record =3D dyn_cast<RecordDecl>(EnclosingDecl);
   bool ARCErrReported =3D false;
   for (llvm::ArrayRef<Decl *>::iterator i =3D Fields.begin(), end =3D Fiel=
ds.end();
        i !=3D end; ++i) {
@@ -9024,27 +9537,34 @@
       continue;
     } else if (FDTy->isIncompleteArrayType() && Record &&=20
                ((i + 1 =3D=3D Fields.end() && !Record->isUnion()) ||
-                ((getLangOptions().MicrosoftExt ||
-                  getLangOptions().CPlusPlus) &&
+                ((getLangOpts().MicrosoftExt ||
+                  getLangOpts().CPlusPlus) &&
                  (i + 1 =3D=3D Fields.end() || Record->isUnion())))) {
       // Flexible array member.
       // Microsoft and g++ is more permissive regarding flexible array.
       // It will accept flexible array in union and also
       // as the sole element of a struct/class.
-      if (getLangOptions().MicrosoftExt) {
+      if (getLangOpts().MicrosoftExt) {
         if (Record->isUnion())=20
           Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
             << FD->getDeclName();
         else if (Fields.size() =3D=3D 1)=20
           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate=
_ms)
             << FD->getDeclName() << Record->getTagKind();
-      } else if (getLangOptions().CPlusPlus) {
+      } else if (getLangOpts().CPlusPlus) {
         if (Record->isUnion())=20
           Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
             << FD->getDeclName();
         else if (Fields.size() =3D=3D 1)=20
           Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate=
_gnu)
             << FD->getDeclName() << Record->getTagKind();
+      } else if (!getLangOpts().C99) {
+      if (Record->isUnion())
+        Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
+          << FD->getDeclName();
+      else
+        Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
+          << FD->getDeclName() << Record->getTagKind();
       } else if (NumNamedMembers < 1) {
         Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
           << FD->getDeclName();
@@ -9101,8 +9621,8 @@
       QualType T =3D Context.getObjCObjectPointerType(FD->getType());
       FD->setType(T);
     }=20
-    else if (!getLangOptions().CPlusPlus) {
-      if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) {
+    else if (!getLangOpts().CPlusPlus) {
+      if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
         // It's an error in ARC if a field has lifetime.
         // We don't want to report this in a system header, though,
         // so we just make the field unavailable.
@@ -9118,13 +9638,14 @@
                                 "this system field has retaining ownership=
"));
             }
           } else {
-            Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct);
+            Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)=20
+              << T->isBlockPointerType();
           }
           ARCErrReported =3D true;
         }
       }
-      else if (getLangOptions().ObjC1 &&
-               getLangOptions().getGC() !=3D LangOptions::NonGC &&
+      else if (getLangOpts().ObjC1 &&
+               getLangOpts().getGC() !=3D LangOptions::NonGC &&
                Record && !Record->hasObjectMember()) {
         if (FD->getType()->isObjCObjectPointerType() ||
             FD->getType().isObjCGCStrong())
@@ -9168,7 +9689,7 @@
           // non-POD because of the presence of an Objective-C pointer mem=
ber.=20
           // If so, objects of this type cannot be shared between code com=
piled=20
           // with instant objects and code compiled with manual retain/rel=
ease.
-          if (getLangOptions().ObjCAutoRefCount &&
+          if (getLangOpts().ObjCAutoRefCount &&
               CXXRecord->hasObjectMember() &&=20
               CXXRecord->getLinkage() =3D=3D ExternalLinkage) {
             if (CXXRecord->isPOD()) {
@@ -9194,7 +9715,7 @@
           }
          =20
           // Adjust user-defined destructor exception spec.
-          if (getLangOptions().CPlusPlus0x &&
+          if (getLangOpts().CPlusPlus0x &&
               CXXRecord->hasUserDeclaredDestructor())
             AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestruct=
or());
=20
@@ -9266,7 +9787,7 @@
     ObjCIvarDecl **ClsFields =3D
       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
     if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(EnclosingDec=
l)) {
-      ID->setLocEnd(RBrac);
+      ID->setEndOfDefinitionLoc(RBrac);
       // Add ivar's to class's DeclContext.
       for (unsigned i =3D 0, e =3D RecFields.size(); i !=3D e; ++i) {
         ClsFields[i]->setLexicalDeclContext(ID);
@@ -9284,6 +9805,8 @@
         // Only it is in implementation's lexical context.
         ClsFields[I]->setLexicalDeclContext(IMPDecl);
       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac=
);
+      IMPDecl->setIvarLBraceLoc(LBrac);
+      IMPDecl->setIvarRBraceLoc(RBrac);
     } else if (ObjCCategoryDecl *CDecl =3D=20
                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
       // case of ivars in class extension; all other cases have been
@@ -9291,10 +9814,34 @@
       // FIXME. Class extension does not have a LocEnd field.
       // CDecl->setLocEnd(RBrac);
       // Add ivar's to class extension's DeclContext.
+      // Diagnose redeclaration of private ivars.
+      ObjCInterfaceDecl *IDecl =3D CDecl->getClassInterface();
       for (unsigned i =3D 0, e =3D RecFields.size(); i !=3D e; ++i) {
+        if (IDecl) {
+          if (const ObjCIvarDecl *ClsIvar =3D=20
+              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
+            Diag(ClsFields[i]->getLocation(),=20
+                 diag::err_duplicate_ivar_declaration);=20
+            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
+            continue;
+          }
+          for (const ObjCCategoryDecl *ClsExtDecl =3D=20
+                IDecl->getFirstClassExtension();
+               ClsExtDecl; ClsExtDecl =3D ClsExtDecl->getNextClassExtensio=
n()) {
+            if (const ObjCIvarDecl *ClsExtIvar =3D=20
+                ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
+              Diag(ClsFields[i]->getLocation(),=20
+                   diag::err_duplicate_ivar_declaration);=20
+              Diag(ClsExtIvar->getLocation(), diag::note_previous_definiti=
on);
+              continue;
+            }
+          }
+        }
         ClsFields[i]->setLexicalDeclContext(CDecl);
         CDecl->addDecl(ClsFields[i]);
       }
+      CDecl->setIvarLBraceLoc(LBrac);
+      CDecl->setIvarRBraceLoc(RBrac);
     }
   }
=20
@@ -9360,22 +9907,60 @@
   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
     Val =3D 0;
=20
+  if (Val)
+    Val =3D DefaultLvalueConversion(Val).take();
+
   if (Val) {
     if (Enum->isDependentType() || Val->isTypeDependent())
       EltTy =3D Context.DependentTy;
     else {
-      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
       SourceLocation ExpLoc;
-      if (!Val->isValueDependent() &&
-          VerifyIntegerConstantExpression(Val, &EnumVal)) {
-        Val =3D 0;
-      } else {       =20
-        if (!getLangOptions().CPlusPlus) {
+      if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
+          !getLangOpts().MicrosoftMode) {
+        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
+        // constant-expression in the enumerator-definition shall be a con=
verted
+        // constant expression of the underlying type.
+        EltTy =3D Enum->getIntegerType();
+        ExprResult Converted =3D
+          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
+                                           CCEK_Enumerator);
+        if (Converted.isInvalid())
+          Val =3D 0;
+        else
+          Val =3D Converted.take();
+      } else if (!Val->isValueDependent() &&
+                 !(Val =3D VerifyIntegerConstantExpression(Val,
+                                                         &EnumVal).take())=
) {
+        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
+      } else {
+        if (Enum->isFixed()) {
+          EltTy =3D Enum->getIntegerType();
+
+          // In Obj-C and Microsoft mode, require the enumeration value to=
 be
+          // representable in the underlying type of the enumeration. In C=
++11,
+          // we perform a non-narrowing conversion as part of converted co=
nstant
+          // expression checking.
+          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
+            if (getLangOpts().MicrosoftMode) {
+              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
+              Val =3D ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(=
);
+            } else
+              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
+          } else
+            Val =3D ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
+        } else if (getLangOpts().CPlusPlus) {
+          // C++11 [dcl.enum]p5:
+          //   If the underlying type is not fixed, the type of each enume=
rator
+          //   is the type of its initializing value:
+          //     - If an initializer is specified for an enumerator, the=20
+          //       initializing value has the same type as the expression.
+          EltTy =3D Val->getType();
+        } else {
           // C99 6.7.2.2p2:
           //   The expression that defines the value of an enumeration con=
stant
-          //   shall be an integer constant expression that has a value=20
+          //   shall be an integer constant expression that has a value
           //   representable as an int.
-         =20
+
           // Complain if the value is not representable in an int.
           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy=
))
             Diag(IdLoc, diag::ext_enum_value_not_int)
@@ -9385,30 +9970,6 @@
             // Force the type of the expression to 'int'.
             Val =3D ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast)=
.take();
           }
-        }
-       =20
-        if (Enum->isFixed()) {
-          EltTy =3D Enum->getIntegerType();
-
-          // C++0x [dcl.enum]p5:
-          //   ... if the initializing value of an enumerator cannot be
-          //   represented by the underlying type, the program is ill-form=
ed.
-          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
-            if (getLangOptions().MicrosoftExt) {
-              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
-              Val =3D ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(=
);
-            } else=20
-              Diag(IdLoc, diag::err_enumerator_too_large)
-                << EltTy;
-          } else
-            Val =3D ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
-        }
-        else {
-          // C++0x [dcl.enum]p5:
-          //   If the underlying type is not fixed, the type of each enume=
rator
-          //   is the type of its initializing value:
-          //     - If an initializer is specified for an enumerator, the=20
-          //       initializing value has the same type as the expression.
           EltTy =3D Val->getType();
         }
       }
@@ -9483,9 +10044,9 @@
         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
         // permits enumerator values that are representable in some larger
         // integral type.
-        if (!getLangOptions().CPlusPlus && !T.isNull())
+        if (!getLangOpts().CPlusPlus && !T.isNull())
           Diag(IdLoc, diag::warn_enum_value_overflow);
-      } else if (!getLangOptions().CPlusPlus &&
+      } else if (!getLangOpts().CPlusPlus &&
                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
         // Enforce C99 6.7.2.2p2 even when we compute the next value.
         Diag(IdLoc, diag::ext_enum_value_not_int)
@@ -9497,7 +10058,7 @@
   if (!EltTy->isDependentType()) {
     // Make the enumerator value match the signedness and size of the=20
     // enumerator's type.
-    EnumVal =3D EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
+    EnumVal =3D EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
   }
  =20
@@ -9509,11 +10070,10 @@
 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumC=
onst,
                               SourceLocation IdLoc, IdentifierInfo *Id,
                               AttributeList *Attr,
-                              SourceLocation EqualLoc, Expr *val) {
+                              SourceLocation EqualLoc, Expr *Val) {
   EnumDecl *TheEnumDecl =3D cast<EnumDecl>(theEnumDecl);
   EnumConstantDecl *LastEnumConst =3D
     cast_or_null<EnumConstantDecl>(lastEnumConst);
-  Expr *Val =3D static_cast<Expr*>(val);
=20
   // The scope passed in may not be a decl scope.  Zip up the scope tree u=
ntil
   // we find one that is.
@@ -9533,7 +10093,7 @@
   if (PrevDecl) {
     // When in C++, we may get a TagDecl with the same name; in this case =
the
     // enum constant will 'hide' the tag.
-    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
+    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
            "Received TagDecl when not in C++!");
     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S))=
 {
       if (isa<EnumConstantDecl>(PrevDecl))
@@ -9651,7 +10211,11 @@
     Packed =3D true;
=20
   if (Enum->isFixed()) {
-    BestType =3D BestPromotionType =3D Enum->getIntegerType();
+    BestType =3D Enum->getIntegerType();
+    if (BestType->isPromotableIntegerType())
+      BestPromotionType =3D Context.getPromotedIntegerType(BestType);
+    else
+      BestPromotionType =3D BestType;
     // We don't need to set BestWidth, because BestType is going to be the=
 type
     // of the enumerators, but we do anyway because otherwise some compile=
rs
     // warn that it might be used uninitialized.
@@ -9701,13 +10265,13 @@
       BestType =3D Context.UnsignedIntTy;
       BestWidth =3D IntWidth;
       BestPromotionType
-        =3D (NumPositiveBits =3D=3D BestWidth || !getLangOptions().CPlusPl=
us)
+        =3D (NumPositiveBits =3D=3D BestWidth || !getLangOpts().CPlusPlus)
                            ? Context.UnsignedIntTy : Context.IntTy;
     } else if (NumPositiveBits <=3D
                (BestWidth =3D Context.getTargetInfo().getLongWidth())) {
       BestType =3D Context.UnsignedLongTy;
       BestPromotionType
-        =3D (NumPositiveBits =3D=3D BestWidth || !getLangOptions().CPlusPl=
us)
+        =3D (NumPositiveBits =3D=3D BestWidth || !getLangOpts().CPlusPlus)
                            ? Context.UnsignedLongTy : Context.LongTy;
     } else {
       BestWidth =3D Context.getTargetInfo().getLongLongWidth();
@@ -9715,7 +10279,7 @@
              "How could an initializer get larger than ULL?");
       BestType =3D Context.UnsignedLongLongTy;
       BestPromotionType
-        =3D (NumPositiveBits =3D=3D BestWidth || !getLangOptions().CPlusPl=
us)
+        =3D (NumPositiveBits =3D=3D BestWidth || !getLangOpts().CPlusPlus)
                            ? Context.UnsignedLongLongTy : Context.LongLong=
Ty;
     }
   }
@@ -9740,14 +10304,15 @@
     QualType NewTy;
     unsigned NewWidth;
     bool NewSign;
-    if (!getLangOptions().CPlusPlus &&
+    if (!getLangOpts().CPlusPlus &&
+        !Enum->isFixed() &&
         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
       NewTy =3D Context.IntTy;
       NewWidth =3D IntWidth;
       NewSign =3D true;
     } else if (ECD->getType() =3D=3D BestType) {
       // Already the right type!
-      if (getLangOptions().CPlusPlus)
+      if (getLangOpts().CPlusPlus)
         // C++ [dcl.enum]p4: Following the closing brace of an
         // enum-specifier, each enumerator has the type of its
         // enumeration.
@@ -9772,7 +10337,7 @@
                                                 ECD->getInitExpr(),
                                                 /*base paths*/ 0,
                                                 VK_RValue));
-    if (getLangOptions().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       // C++ [dcl.enum]p4: Following the closing brace of an
       // enum-specifier, each enumerator has the type of its
       // enumeration.
@@ -9783,6 +10348,12 @@
=20
   Enum->completeDefinition(BestType, BestPromotionType,
                            NumPositiveBits, NumNegativeBits);
+
+  // If we're declaring a function, ensure this decl isn't forgotten about=
 -
+  // it needs to go into the function scope.
+  if (InFunctionDeclarator)
+    DeclsInPrototypeScope.push_back(Enum);
+
 }
=20
 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
@@ -9797,31 +10368,50 @@
   return New;
 }
=20
-DeclResult Sema::ActOnModuleImport(SourceLocation ImportLoc,
-                                   IdentifierInfo &ModuleName,
-                                   SourceLocation ModuleNameLoc) {
-  ModuleKey Module =3D PP.getModuleLoader().loadModule(ImportLoc,=20
-                                                     ModuleName, ModuleNam=
eLoc);
-  if (!Module)
+DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,=20
+                                   SourceLocation ImportLoc,=20
+                                   ModuleIdPath Path) {
+  Module *Mod =3D PP.getModuleLoader().loadModule(ImportLoc, Path,=20
+                                                Module::AllVisible,
+                                                /*IsIncludeDirective=3D*/f=
alse);
+  if (!Mod)
     return true;
  =20
-  // FIXME: Actually create a declaration to describe the module import.
-  (void)Module;
-  return DeclResult((Decl *)0);
-}
-
-void=20
-Sema::diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old,
-                                         SourceLocation ModulePrivateKeywo=
rd) {
-  assert(!Old->isModulePrivate() && "Old is module-private!");
- =20
-  Diag(New->getLocation(), diag::err_module_private_follows_public)
-    << New->getDeclName() << SourceRange(ModulePrivateKeyword);
-  Diag(Old->getLocation(), diag::note_previous_declaration)
-    << Old->getDeclName();
- =20
-  // Drop the __module_private__ from the new declaration, since it's inva=
lid.
-  New->setModulePrivate(false);
+  llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
+  Module *ModCheck =3D Mod;
+  for (unsigned I =3D 0, N =3D Path.size(); I !=3D N; ++I) {
+    // If we've run out of module parents, just drop the remaining identif=
iers.
+    // We need the length to be consistent.
+    if (!ModCheck)
+      break;
+    ModCheck =3D ModCheck->Parent;
+   =20
+    IdentifierLocs.push_back(Path[I].second);
+  }
+
+  ImportDecl *Import =3D ImportDecl::Create(Context,=20
+                                          Context.getTranslationUnitDecl(),
+                                          AtLoc.isValid()? AtLoc : ImportL=
oc,=20
+                                          Mod, IdentifierLocs);
+  Context.getTranslationUnitDecl()->addDecl(Import);
+  return Import;
+}
+
+void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
+                                      IdentifierInfo* AliasName,
+                                      SourceLocation PragmaLoc,
+                                      SourceLocation NameLoc,
+                                      SourceLocation AliasNameLoc) {
+  Decl *PrevDecl =3D LookupSingleName(TUScope, Name, NameLoc,
+                                    LookupOrdinaryName);
+  AsmLabelAttr *Attr =3D
+     ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getNam=
e());
+
+  if (PrevDecl)=20
+    PrevDecl->addAttr(Attr);
+  else=20
+    (void)ExtnameUndeclaredIdentifiers.insert(
+      std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
 }
=20
 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaDeclAttr.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaDeclAttr.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -35,17 +35,14 @@
   ExpectedVariableOrFunction,
   ExpectedFunctionOrMethod,
   ExpectedParameter,
-  ExpectedParameterOrMethod,
   ExpectedFunctionMethodOrBlock,
-  ExpectedClassOrVirtualMethod,
   ExpectedFunctionMethodOrParameter,
   ExpectedClass,
-  ExpectedVirtualMethod,
-  ExpectedClassMember,
   ExpectedVariable,
   ExpectedMethod,
   ExpectedVariableFunctionOrLabel,
-  ExpectedFieldOrGlobalVar
+  ExpectedFieldOrGlobalVar,
+  ExpectedStruct
 };
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -275,21 +272,25 @@
=20
 /// \brief Thread Safety Analysis: Checks that the passed in RecordType
 /// resolves to a lockable object. May flag an error.
-static bool checkForLockableRecord(Sema &S, Decl *D, const AttributeList &=
Attr,
-                                   const RecordType *RT) {
-  // Flag error if could not get record type for this argument.
+static void checkForLockableRecord(Sema &S, Decl *D, const AttributeList &=
Attr,
+                                   QualType Ty) {
+  const RecordType *RT =3D getRecordType(Ty);
+                                  =20
+  // Warn if could not get record type for this argument.
   if (!RT) {
-    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_class)
-      << Attr.getName();
-    return false;
+    S.Diag(Attr.getLoc(), diag::warn_attribute_argument_not_class)
+      << Attr.getName() << Ty.getAsString();
+    return;
   }
-  // Flag error if the type is not lockable.
+  // Don't check for lockable if the class hasn't been defined yet.=20
+  if (RT->isIncompleteType())
+    return;
+  // Warn if the type is not lockable.
   if (!RT->getDecl()->getAttr<LockableAttr>()) {
-    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_lockable)
-      << Attr.getName();
-    return false;
+    S.Diag(Attr.getLoc(), diag::warn_attribute_argument_not_lockable)
+      << Attr.getName() << Ty.getAsString();
+    return;
   }
-  return true;
 }
=20
 /// \brief Thread Safety Analysis: Checks that all attribute arguments, st=
arting
@@ -331,12 +332,10 @@
           return false;
         }
         ArgTy =3D FD->getParamDecl(ParamIdxFromZero)->getType();
-        RT =3D getRecordType(ArgTy);
       }
     }
=20
-    if (!checkForLockableRecord(S, D, Attr, RT))
-      return false;
+    checkForLockableRecord(S, D, Attr, ArgTy);
=20
     Args.push_back(ArgExp);
   }
@@ -393,13 +392,9 @@
   if (pointer && !checkIsPointer(S, D, Attr))
     return;
=20
-  if (Arg->isTypeDependent())
-    // FIXME: handle attributes with dependent types
-    return;
-
-  // check that the argument is lockable object
-  if (!checkForLockableRecord(S, D, Attr, getRecordType(Arg->getType())))
-    return;
+  if (!Arg->isTypeDependent()) {
+    checkForLockableRecord(S, D, Attr, Arg->getType());
+  }
=20
   if (pointer)
     D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
@@ -446,6 +441,23 @@
                                                           S.Context));
 }
=20
+static void handleNoAddressSafetyAttr(Sema &S, Decl *D,
+                                     const AttributeList &Attr) {
+  assert(!Attr.isInvalid());
+
+  if (!checkAttributeNumArgs(S, Attr, 0))
+    return;
+
+  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
+    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
+      << Attr.getName() << ExpectedFunctionOrMethod;
+    return;
+  }
+
+  D->addAttr(::new (S.Context) NoAddressSafetyAnalysisAttr(Attr.getRange(),
+                                                          S.Context));
+}
+
 static void handleAcquireOrderAttr(Sema &S, Decl *D, const AttributeList &=
Attr,
                                    bool before) {
   assert(!Attr.isInvalid());
@@ -466,7 +478,7 @@
   if (!QT->isDependentType()) {
     const RecordType *RT =3D getRecordType(QT);
     if (!RT || !RT->getDecl()->getAttr<LockableAttr>()) {
-      S.Diag(Attr.getLoc(), diag::err_attribute_decl_not_lockable)
+      S.Diag(Attr.getLoc(), diag::warn_attribute_decl_not_lockable)
               << Attr.getName();
       return;
     }
@@ -636,8 +648,7 @@
     return;
=20
   // check that the argument is lockable object
-  if (!checkForLockableRecord(S, D, Attr, getRecordType(Arg->getType())))
-    return;
+  checkForLockableRecord(S, D, Attr, Arg->getType());
=20
   D->addAttr(::new (S.Context) LockReturnedAttr(Attr.getRange(), S.Context=
, Arg));
 }
@@ -684,10 +695,12 @@
   // Special case where the argument is a template id.
   if (Attr.getParameterName()) {
     CXXScopeSpec SS;
+    SourceLocation TemplateKWLoc;
     UnqualifiedId id;
     id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
    =20
-    ExprResult Size =3D S.ActOnIdExpression(scope, SS, id, false, false);
+    ExprResult Size =3D S.ActOnIdExpression(scope, SS, TemplateKWLoc, id,
+                                          false, false);
     if (Size.isInvalid())
       return;
    =20
@@ -760,14 +773,14 @@
   // have an object reference type.
   if (const ObjCIvarDecl *VD =3D dyn_cast<ObjCIvarDecl>(D)) {
     if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
-      S.Diag(Attr.getLoc(), diag::err_iboutlet_object_type)
+      S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
         << Attr.getName() << VD->getType() << 0;
       return false;
     }
   }
   else if (const ObjCPropertyDecl *PD =3D dyn_cast<ObjCPropertyDecl>(D)) {
     if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
-      S.Diag(Attr.getLoc(), diag::err_iboutlet_object_type)=20
+      S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
         << Attr.getName() << PD->getType() << 1;
       return false;
     }
@@ -776,7 +789,7 @@
     S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
     return false;
   }
- =20
+
   return true;
 }
=20
@@ -805,7 +818,7 @@
=20
   IdentifierInfo *II =3D Attr.getParameterName();
   if (!II)
-    II =3D &S.Context.Idents.get("id");
+    II =3D &S.Context.Idents.get("NSObject");
  =20
   ParsedType TypeRep =3D S.getTypeName(*II, Attr.getLoc(),=20
                         S.getScopeForContext(D->getDeclContext()->getParen=
t()));
@@ -818,8 +831,7 @@
   // FIXME. Gnu attribute extension ignores use of builtin types in
   // attributes. So, __attribute__((iboutletcollection(char))) will be
   // treated as __attribute__((iboutletcollection())).
-  if (!QT->isObjCIdType() && !QT->isObjCClassType() &&
-      !QT->isObjCObjectType()) {
+  if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
     S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
     return;
   }
@@ -1056,8 +1068,6 @@
       }
       break;
     }
-    default:
-      llvm_unreachable("Unknown ownership attribute");
     } // switch
=20
     // Check we don't have a conflict with another ownership attribute.
@@ -1108,7 +1118,6 @@
     return false;
   }
   llvm_unreachable("unknown linkage kind!");
-  return false;
 }
=20
 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr)=
 {
@@ -1580,6 +1589,39 @@
                                           Attr.getRange(), S.Context));
 }
=20
+static void handleObjCRootClassAttr(Sema &S, Decl *D,=20
+                                    const AttributeList &Attr) {
+  if (!isa<ObjCInterfaceDecl>(D)) {
+    S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
+    return;
+  }
+ =20
+  unsigned NumArgs =3D Attr.getNumArgs();
+  if (NumArgs > 0) {
+    S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
+    return;
+  }
+ =20
+  D->addAttr(::new (S.Context) ObjCRootClassAttr(Attr.getRange(), S.Contex=
t));
+}
+
+static void handleObjCRequiresPropertyDefsAttr(Sema &S, Decl *D,=20
+                                            const AttributeList &Attr) {
+  if (!isa<ObjCInterfaceDecl>(D)) {
+    S.Diag(Attr.getLoc(), diag::err_suppress_autosynthesis);
+    return;
+  }
+ =20
+  unsigned NumArgs =3D Attr.getNumArgs();
+  if (NumArgs > 0) {
+    S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 0;
+    return;
+  }
+ =20
+  D->addAttr(::new (S.Context) ObjCRequiresPropertyDefsAttr(
+                                 Attr.getRange(), S.Context));
+}
+
 static void handleAvailabilityAttr(Sema &S, Decl *D,
                                    const AttributeList &Attr) {
   IdentifierInfo *Platform =3D Attr.getParameterName();
@@ -1625,12 +1667,19 @@
     return;
   }
=20
+  StringRef Str;
+  const StringLiteral *SE =3D=20
+    dyn_cast_or_null<const StringLiteral>(Attr.getMessageExpr());
+  if (SE)
+    Str =3D SE->getString();
+ =20
   D->addAttr(::new (S.Context) AvailabilityAttr(Attr.getRange(), S.Context,
                                                 Platform,
                                                 Introduced.Version,
                                                 Deprecated.Version,
                                                 Obsoleted.Version,
-                                                IsUnavailable));
+                                                IsUnavailable,=20
+                                                Str));
 }
=20
 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &At=
tr) {
@@ -1657,9 +1706,16 @@
     type =3D VisibilityAttr::Hidden;
   else if (TypeStr =3D=3D "internal")
     type =3D VisibilityAttr::Hidden; // FIXME
-  else if (TypeStr =3D=3D "protected")
-    type =3D VisibilityAttr::Protected;
-  else {
+  else if (TypeStr =3D=3D "protected") {
+    // Complain about attempts to use protected visibility on targets
+    // (like Darwin) that don't support it.
+    if (!S.Context.getTargetInfo().hasProtectedVisibility()) {
+      S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
+      type =3D VisibilityAttr::Default;
+    } else {
+      type =3D VisibilityAttr::Protected;
+    }
+  } else {
     S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << Type=
Str;
     return;
   }
@@ -1747,6 +1803,15 @@
       return;
     }
   }
+  else if (!isa<ObjCPropertyDecl>(D)) {
+    // It is okay to include this attribute on properties, e.g.:
+    //
+    //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObje=
ct));
+    //
+    // In this case it follows tradition and suppresses an error in the ab=
ove
+    // case.   =20
+    S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
+  }
   D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getRange(), S.Context=
));
 }
=20
@@ -1853,10 +1918,11 @@
       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) <<=
 0;
       return;
     }
-  } else if (isa<BlockDecl>(D)) {
-    // Note! BlockDecl is typeless. Variadic diagnostics will be issued by=
 the
-    // caller.
-    ;
+  } else if (BlockDecl *BD =3D dyn_cast<BlockDecl>(D)) {
+    if (!BD->isVariadic()) {
+      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) <<=
 1;
+      return;
+    }
   } else if (const VarDecl *V =3D dyn_cast<VarDecl>(D)) {
     QualType Ty =3D V->getType();
     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
@@ -1915,6 +1981,10 @@
   }
=20
   if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
+    if (isa<CXXRecordDecl>(D)) {
+      D->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
+      return;
+    }
     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
       << Attr.getName() << ExpectedVariableOrFunction;
     return;
@@ -1946,7 +2016,7 @@
         << "weak_import" << 2 /*variable and function*/;
     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
-              isa<ObjCInterfaceDecl>(D))) {
+              (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
       // Nothing to warn about here.
     } else
       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
@@ -2109,7 +2179,7 @@
   }
=20
   D->addAttr(::new (S.Context) CleanupAttr(Attr.getRange(), S.Context, FD)=
);
-  S.MarkDeclarationReferenced(Attr.getParameterLoc(), FD);
+  S.MarkFunctionReferenced(Attr.getParameterLoc(), FD);
 }
=20
 /// Handle __attribute__((format_arg((idx)))) attribute based on
@@ -2209,8 +2279,7 @@
=20
   // Otherwise, check for supported formats.
   if (Format =3D=3D "scanf" || Format =3D=3D "printf" || Format =3D=3D "pr=
intf0" ||
-      Format =3D=3D "strfmon" || Format =3D=3D "cmn_err" || Format =3D=3D =
"strftime" ||
-      Format =3D=3D "NSString" || Format =3D=3D "CFString" || Format =3D=
=3D "vcmn_err" ||
+      Format =3D=3D "strfmon" || Format =3D=3D "cmn_err" || Format =3D=3D =
"vcmn_err" ||
       Format =3D=3D "zcmn_err" ||
       Format =3D=3D "kprintf")  // OpenBSD.
     return SupportedFormat;
@@ -2226,7 +2295,7 @@
 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
 static void handleInitPriorityAttr(Sema &S, Decl *D,
                                    const AttributeList &Attr) {
-  if (!S.getLangOptions().CPlusPlus) {
+  if (!S.getLangOpts().CPlusPlus) {
     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
     return;
   }
@@ -2541,6 +2610,10 @@
 }
=20
 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E) {
+  // FIXME: Handle pack-expansions here.
+  if (DiagnoseUnexpandedParameterPack(E))
+    return;
+
   if (E->isTypeDependent() || E->isValueDependent()) {
     // Save dependent expressions in the AST to be instantiated.
     D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, E));
@@ -2550,18 +2623,19 @@
   SourceLocation AttrLoc =3D AttrRange.getBegin();
   // FIXME: Cache the number on the Attr object?
   llvm::APSInt Alignment(32);
-  if (!E->isIntegerConstantExpr(Alignment, Context)) {
-    Diag(AttrLoc, diag::err_attribute_argument_not_int)
-      << "aligned" << E->getSourceRange();
+  ExprResult ICE =3D
+    VerifyIntegerConstantExpression(E, &Alignment,
+      PDiag(diag::err_attribute_argument_not_int) << "aligned",
+      /*AllowFold*/ false);
+  if (ICE.isInvalid())
     return;
-  }
   if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
     Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
       << E->getSourceRange();
     return;
   }
=20
-  D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, E));
+  D->addAttr(::new (Context) AlignedAttr(AttrRange, Context, true, ICE.tak=
e()));
 }
=20
 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *=
TS) {
@@ -2975,7 +3049,6 @@
   }
   default:
     llvm_unreachable("unexpected attribute kind");
-    return;
   }
 }
=20
@@ -3024,7 +3097,7 @@
     }
     // FALLS THROUGH
   }
-  default: llvm_unreachable("unexpected attribute kind"); return true;
+  default: llvm_unreachable("unexpected attribute kind");
   }
=20
   return false;
@@ -3195,7 +3268,7 @@
     returnType =3D MD->getResultType();
   else if (ObjCPropertyDecl *PD =3D dyn_cast<ObjCPropertyDecl>(D))
     returnType =3D PD->getType();
-  else if (S.getLangOptions().ObjCAutoRefCount && hasDeclarator(D) &&
+  else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
            (Attr.getKind() =3D=3D AttributeList::AT_ns_returns_retained))
     return; // ignore: was handled as a type attribute
   else if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D))
@@ -3210,7 +3283,7 @@
   bool typeOK;
   bool cf;
   switch (Attr.getKind()) {
-  default: llvm_unreachable("invalid ownership attribute"); return;
+  default: llvm_unreachable("invalid ownership attribute");
   case AttributeList::AT_ns_returns_autoreleased:
   case AttributeList::AT_ns_returns_retained:
   case AttributeList::AT_ns_returns_not_retained:
@@ -3265,7 +3338,7 @@
=20
   if (!isa<ObjCMethodDecl>(method)) {
     S.Diag(method->getLocStart(), diag::err_attribute_wrong_decl_type)
-      << SourceRange(loc, loc) << attr.getName() << 13 /* methods */;
+      << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
     return;
   }
=20
@@ -3290,7 +3363,7 @@
 static void handleCFTransferAttr(Sema &S, Decl *D, const AttributeList &A)=
 {
   if (!isa<FunctionDecl>(D)) {
     S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
-      << A.getRange() << A.getName() << 0 /*function*/;
+      << A.getRange() << A.getName() << ExpectedFunction;
     return;
   }
=20
@@ -3326,7 +3399,7 @@
   RecordDecl *RD =3D dyn_cast<RecordDecl>(D);
   if (!RD || RD->isUnion()) {
     S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
-      << Attr.getRange() << Attr.getName() << 14 /*struct */;
+      << Attr.getRange() << Attr.getName() << ExpectedStruct;
   }
=20
   IdentifierInfo *ParmName =3D Attr.getParameterName();
@@ -3334,7 +3407,7 @@
   // In Objective-C, verify that the type names an Objective-C type.
   // We don't want to check this outside of ObjC because people sometimes
   // do crazy C declarations of Objective-C types.
-  if (ParmName && S.getLangOptions().ObjC1) {
+  if (ParmName && S.getLangOpts().ObjC1) {
     // Check for an existing type with this name.
     LookupResult R(S, DeclarationName(ParmName), Attr.getParameterLoc(),
                    Sema::LookupOrdinaryName);
@@ -3356,14 +3429,14 @@
   if (hasDeclarator(D)) return;
=20
   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
-    << Attr.getRange() << Attr.getName() << 12 /* variable */;
+    << Attr.getRange() << Attr.getName() << ExpectedVariable;
 }
=20
 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
                                           const AttributeList &Attr) {
   if (!isa<VarDecl>(D) && !isa<FieldDecl>(D)) {
     S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
-      << Attr.getRange() << Attr.getName() << 12 /* variable */;
+      << Attr.getRange() << Attr.getName() << ExpectedVariable;
     return;
   }
=20
@@ -3406,9 +3479,19 @@
 }
=20
 static bool isKnownDeclSpecAttr(const AttributeList &Attr) {
-  return Attr.getKind() =3D=3D AttributeList::AT_dllimport ||
-         Attr.getKind() =3D=3D AttributeList::AT_dllexport ||
-         Attr.getKind() =3D=3D AttributeList::AT_uuid;
+  switch (Attr.getKind()) {
+  default:
+    return false;
+  case AttributeList::AT_dllimport:
+  case AttributeList::AT_dllexport:
+  case AttributeList::AT_uuid:
+  case AttributeList::AT_deprecated:
+  case AttributeList::AT_noreturn:
+  case AttributeList::AT_nothrow:
+  case AttributeList::AT_naked:
+  case AttributeList::AT_noinline:
+    return true;
+  }
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -3433,7 +3516,7 @@
=20
     bool IsCurly =3D StrRef.size() > 1 && StrRef.front() =3D=3D '{' &&
                    StrRef.back() =3D=3D '}';
-   =20
+
     // Validate GUID length.
     if (IsCurly && StrRef.size() !=3D 38) {
       S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
@@ -3444,7 +3527,7 @@
       return;
     }
=20
-    // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or=20
+    // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
     // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
     StringRef::iterator I =3D StrRef.begin();
     if (IsCurly) // Skip the optional '{'
@@ -3487,9 +3570,9 @@
 static void ProcessInheritableDeclAttr(Sema &S, Scope *scope, Decl *D,
                                        const AttributeList &Attr) {
   switch (Attr.getKind()) {
-  case AttributeList::AT_IBAction:            handleIBAction(S, D, Attr); =
break;
-    case AttributeList::AT_IBOutlet:          handleIBOutlet(S, D, Attr); =
break;
-  case AttributeList::AT_IBOutletCollection:
+    case AttributeList::AT_ibaction:            handleIBAction(S, D, Attr)=
; break;
+    case AttributeList::AT_iboutlet:          handleIBOutlet(S, D, Attr); =
break;
+    case AttributeList::AT_iboutletcollection:
       handleIBOutletCollection(S, D, Attr); break;
   case AttributeList::AT_address_space:
   case AttributeList::AT_opencl_image_access:
@@ -3574,19 +3657,25 @@
   case AttributeList::AT_cf_returns_retained:
     handleNSReturnsRetainedAttr(S, D, Attr); break;
=20
-  case AttributeList::AT_reqd_wg_size:
+  case AttributeList::AT_reqd_work_group_size:
     handleReqdWorkGroupSize(S, D, Attr); break;
=20
   case AttributeList::AT_init_priority:=20
       handleInitPriorityAttr(S, D, Attr); break;
      =20
   case AttributeList::AT_packed:      handlePackedAttr      (S, D, Attr); =
break;
-  case AttributeList::AT_MsStruct:    handleMsStructAttr    (S, D, Attr); =
break;
+  case AttributeList::AT_ms_struct:    handleMsStructAttr    (S, D, Attr);=
 break;
   case AttributeList::AT_section:     handleSectionAttr     (S, D, Attr); =
break;
   case AttributeList::AT_unavailable: handleUnavailableAttr (S, D, Attr); =
break;
-  case AttributeList::AT_arc_weakref_unavailable:=20
+  case AttributeList::AT_objc_arc_weak_reference_unavailable:=20
     handleArcWeakrefUnavailableAttr (S, D, Attr);=20
     break;
+  case AttributeList::AT_objc_root_class:
+    handleObjCRootClassAttr(S, D, Attr);
+    break;
+  case AttributeList::AT_objc_requires_property_definitions:=20
+    handleObjCRequiresPropertyDefsAttr (S, D, Attr);=20
+    break;
   case AttributeList::AT_unused:      handleUnusedAttr      (S, D, Attr); =
break;
   case AttributeList::AT_returns_twice:
     handleReturnsTwiceAttr(S, D, Attr);
@@ -3607,7 +3696,7 @@
   case AttributeList::AT_objc_method_family:
     handleObjCMethodFamilyAttr(S, D, Attr);
     break;
-  case AttributeList::AT_nsobject:    handleObjCNSObject    (S, D, Attr); =
break;
+  case AttributeList::AT_NSObject:    handleObjCNSObject    (S, D, Attr); =
break;
   case AttributeList::AT_blocks:      handleBlocksAttr      (S, D, Attr); =
break;
   case AttributeList::AT_sentinel:    handleSentinelAttr    (S, D, Attr); =
break;
   case AttributeList::AT_const:       handleConstAttr       (S, D, Attr); =
break;
@@ -3647,6 +3736,9 @@
   case AttributeList::AT_scoped_lockable:
     handleLockableAttr(S, D, Attr, /*scoped =3D */true);
     break;
+  case AttributeList::AT_no_address_safety_analysis:
+    handleNoAddressSafetyAttr(S, D, Attr);
+    break;
   case AttributeList::AT_no_thread_safety_analysis:
     handleNoThreadSafetyAttr(S, D, Attr);
     break;
@@ -3924,7 +4016,7 @@
                         "this system declaration uses an unsupported type"=
));
     return;
   }
-  if (S.getLangOptions().ObjCAutoRefCount)
+  if (S.getLangOpts().ObjCAutoRefCount)
     if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(decl)) {
       // FIXME. we may want to supress diagnostics for all
       // kind of forbidden type messages on unavailable functions.=20
@@ -3982,7 +4074,7 @@
=20
   // We only want to actually emit delayed diagnostics when we
   // successfully parsed a decl.
-  if (decl && !decl->isInvalidDecl()) {
+  if (decl) {
     // We emit all the active diagnostics, not just those starting
     // from the saved state.  The idea is this:  we get one push for a
     // decl spec and another for each declarator;  in a decl group like:
@@ -3997,7 +4089,9 @@
=20
       switch (diag.Kind) {
       case DelayedDiagnostic::Deprecation:
-        S.HandleDelayedDeprecationCheck(diag, decl);
+        // Don't bother giving deprecation diagnostics if the decl is inva=
lid.
+        if (!decl->isInvalidDecl())
+          S.HandleDelayedDeprecationCheck(diag, decl);
         break;
=20
       case DelayedDiagnostic::Access:
@@ -4039,6 +4133,11 @@
     Diag(DD.Loc, diag::warn_deprecated_message)
       << DD.getDeprecationDecl()->getDeclName()
       << DD.getDeprecationMessage();
+  else if (DD.getUnknownObjCClass()) {
+    Diag(DD.Loc, diag::warn_deprecated_fwdclass_message)=20
+      << DD.getDeprecationDecl()->getDeclName();
+    Diag(DD.getUnknownObjCClass()->getLocation(), diag::note_forward_class=
);
+  }
   else
     Diag(DD.Loc, diag::warn_deprecated)
       << DD.getDeprecationDecl()->getDeclName();
@@ -4049,7 +4148,9 @@
                                   const ObjCInterfaceDecl *UnknownObjCClas=
s) {
   // Delay if we're currently parsing a declaration.
   if (DelayedDiagnostics.shouldDelayDiagnostics()) {
-    DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D, Mess=
age));
+    DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D,=20
+                                                              UnknownObjCC=
lass,
+                                                              Message));
     return;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaDeclCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaDeclCXX.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/ScopeInfo.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ASTMutationListener.h"
@@ -31,7 +32,7 @@
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Basic/PartialDiagnostic.h"
 #include "clang/Lex/Preprocessor.h"
-#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include <map>
 #include <set>
@@ -60,6 +61,7 @@
     bool VisitExpr(Expr *Node);
     bool VisitDeclRefExpr(DeclRefExpr *DRE);
     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
+    bool VisitLambdaExpr(LambdaExpr *Lambda);
   };
=20
   /// VisitExpr - Visit all of the children of this expression.
@@ -84,7 +86,7 @@
       //   evaluated. Parameters of a function declared before a default
       //   argument expression are in scope and can hide namespace and
       //   class member names.
-      return S->Diag(DRE->getSourceRange().getBegin(),
+      return S->Diag(DRE->getLocStart(),
                      diag::err_param_default_argument_references_param)
          << Param->getDeclName() << DefaultArg->getSourceRange();
     } else if (VarDecl *VDecl =3D dyn_cast<VarDecl>(Decl)) {
@@ -92,7 +94,7 @@
       //   Local variables shall not be used in default argument
       //   expressions.
       if (VDecl->isLocalVarDecl())
-        return S->Diag(DRE->getSourceRange().getBegin(),
+        return S->Diag(DRE->getLocStart(),
                        diag::err_param_default_argument_references_local)
           << VDecl->getDeclName() << DefaultArg->getSourceRange();
     }
@@ -105,10 +107,21 @@
     // C++ [dcl.fct.default]p8:
     //   The keyword this shall not be used in a default argument of a
     //   member function.
-    return S->Diag(ThisE->getSourceRange().getBegin(),
+    return S->Diag(ThisE->getLocStart(),
                    diag::err_param_default_argument_references_this)
                << ThisE->getSourceRange();
   }
+
+  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
+    // C++11 [expr.lambda.prim]p13:
+    //   A lambda-expression appearing in a default argument shall not
+    //   implicitly or explicitly capture any entity.
+    if (Lambda->capture_begin() =3D=3D Lambda->capture_end())
+      return false;
+
+    return S->Diag(Lambda->getLocStart(),=20
+                   diag::err_lambda_capture_default_arg);
+  }
 }
=20
 void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Metho=
d) {
@@ -267,7 +280,7 @@
   UnparsedDefaultArgLocs.erase(Param);
=20
   // Default arguments are only permitted in C++
-  if (!getLangOptions().CPlusPlus) {
+  if (!getLangOpts().CPlusPlus) {
     Diag(EqualLoc, diag::err_param_default_argument)
       << DefaultArg->getSourceRange();
     Param->setInvalidDecl();
@@ -359,7 +372,8 @@
 // function, once we already know that they have the same
 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
 // error, false otherwise.
-bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
+bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
+                                Scope *S) {
   bool Invalid =3D false;
=20
   // C++ [dcl.fct.default]p4:
@@ -384,7 +398,16 @@
     ParmVarDecl *OldParam =3D Old->getParamDecl(p);
     ParmVarDecl *NewParam =3D New->getParamDecl(p);
=20
-    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
+    bool OldParamHasDfl =3D OldParam->hasDefaultArg();
+    bool NewParamHasDfl =3D NewParam->hasDefaultArg();
+
+    NamedDecl *ND =3D Old;
+    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
+      // Ignore default parameters of old decl if they are not in
+      // the same scope.
+      OldParamHasDfl =3D false;
+
+    if (OldParamHasDfl && NewParamHasDfl) {
=20
       unsigned DiagDefaultParamID =3D
         diag::err_param_default_argument_redefinition;
@@ -392,7 +415,7 @@
       // MSVC accepts that default parameters be redefined for member func=
tions
       // of template class. The new default parameter's value is ignored.
       Invalid =3D true;
-      if (getLangOptions().MicrosoftExt) {
+      if (getLangOpts().MicrosoftExt) {
         CXXMethodDecl* MD =3D dyn_cast<CXXMethodDecl>(New);
         if (MD && MD->getParent()->getDescribedClassTemplate()) {
           // Merge the old default argument into the new parameter.
@@ -420,8 +443,8 @@
      =20
       // Look for the function declaration where the default argument was
       // actually written, which may be a declaration prior to Old.
-      for (FunctionDecl *Older =3D Old->getPreviousDeclaration();
-           Older; Older =3D Older->getPreviousDeclaration()) {
+      for (FunctionDecl *Older =3D Old->getPreviousDecl();
+           Older; Older =3D Older->getPreviousDecl()) {
         if (!Older->getParamDecl(p)->hasDefaultArg())
           break;
        =20
@@ -430,7 +453,7 @@
      =20
       Diag(OldParam->getLocation(), diag::note_previous_definition)
         << OldParam->getDefaultArgRange();
-    } else if (OldParam->hasDefaultArg()) {
+    } else if (OldParamHasDfl) {
       // Merge the old default argument into the new parameter.
       // It's important to use getInit() here;  getDefaultArg()
       // strips off any top-level ExprWithCleanups.
@@ -440,7 +463,7 @@
                                       OldParam->getUninstantiatedDefaultAr=
g());
       else
         NewParam->setDefaultArg(OldParam->getInit());
-    } else if (NewParam->hasDefaultArg()) {
+    } else if (NewParamHasDfl) {
       if (New->getDescribedFunctionTemplate()) {
         // Paragraph 4, quoted above, only applies to non-template functio=
ns.
         Diag(NewParam->getLocation(),
@@ -502,13 +525,9 @@
     }
   }
=20
-  // C++0x [dcl.constexpr]p1: If any declaration of a function or function
+  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
   // template has a constexpr specifier then all its declarations shall
-  // contain the constexpr specifier. [Note: An explicit specialization can
-  // differ from the template declaration with respect to the constexpr
-  // specifier. -- end note]
-  //
-  // FIXME: Don't reject changes in constexpr in explicit specializations.
+  // contain the constexpr specifier.
   if (New->isConstexpr() !=3D Old->isConstexpr()) {
     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
       << New << New->isConstexpr();
@@ -529,7 +548,7 @@
 /// validates compatibility and merges the specs if necessary.
 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
   // Shortcut if exceptions are disabled.
-  if (!getLangOptions().CXXExceptions)
+  if (!getLangOpts().CXXExceptions)
     return;
=20
   assert(Context.hasSameType(New->getType(), Old->getType()) &&
@@ -571,11 +590,25 @@
   unsigned NumParams =3D FD->getNumParams();
   unsigned p;
=20
+  bool IsLambda =3D FD->getOverloadedOperator() =3D=3D OO_Call &&
+                  isa<CXXMethodDecl>(FD) &&
+                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
+             =20
   // Find first parameter with a default argument
   for (p =3D 0; p < NumParams; ++p) {
     ParmVarDecl *Param =3D FD->getParamDecl(p);
-    if (Param->hasDefaultArg())
+    if (Param->hasDefaultArg()) {
+      // C++11 [expr.prim.lambda]p5:
+      //   [...] Default arguments (8.3.6) shall not be specified in the=20
+      //   parameter-declaration-clause of a lambda-declarator.
+      //
+      // FIXME: Core issue 974 strikes this sentence, we only provide an
+      // extension warning.
+      if (IsLambda)
+        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
+          << Param->getDefaultArgRange();
       break;
+    }
   }
=20
   // C++ [dcl.fct.default]p4:
@@ -618,9 +651,9 @@
=20
 // CheckConstexprParameterTypes - Check whether a function's parameter typ=
es
 // are all literal types. If so, return true. If not, produce a suitable
-// diagnostic depending on @p CCK and return false.
-static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl=
 *FD,
-                                         Sema::CheckConstexprKind CCK) {
+// diagnostic and return false.
+static bool CheckConstexprParameterTypes(Sema &SemaRef,
+                                         const FunctionDecl *FD) {
   unsigned ArgIndex =3D 0;
   const FunctionProtoType *FT =3D FD->getType()->getAs<FunctionProtoType>(=
);
   for (FunctionProtoType::arg_type_iterator i =3D FT->arg_type_begin(),
@@ -628,106 +661,72 @@
     const ParmVarDecl *PD =3D FD->getParamDecl(ArgIndex);
     SourceLocation ParamLoc =3D PD->getLocation();
     if (!(*i)->isDependentType() &&
-        SemaRef.RequireLiteralType(ParamLoc, *i, CCK =3D=3D Sema::CCK_Decl=
aration ?
+        SemaRef.RequireLiteralType(ParamLoc, *i,
                             SemaRef.PDiag(diag::err_constexpr_non_literal_=
param)
                                      << ArgIndex+1 << PD->getSourceRange()
-                                     << isa<CXXConstructorDecl>(FD) :
-                                   SemaRef.PDiag(),
-                                   /*AllowIncompleteType*/ true)) {
-      if (CCK =3D=3D Sema::CCK_NoteNonConstexprInstantiation)
-        SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
-          << ArgIndex+1 << PD->getSourceRange()
-          << isa<CXXConstructorDecl>(FD) << *i;
+                                     << isa<CXXConstructorDecl>(FD)))
       return false;
-    }
   }
   return true;
 }
=20
 // CheckConstexprFunctionDecl - Check whether a function declaration satis=
fies
-// the requirements of a constexpr function declaration or a constexpr
-// constructor declaration. Return true if it does, false if not.
+// the requirements of a constexpr function definition or a constexpr
+// constructor definition. If so, return true. If not, produce appropriate
+// diagnostics and return false.
 //
-// This implements C++0x [dcl.constexpr]p3,4, as amended by N3308.
-//
-// \param CCK Specifies whether to produce diagnostics if the function doe=
s not
-// satisfy the requirements.
-bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
-                                      CheckConstexprKind CCK) {
-  assert((CCK !=3D CCK_NoteNonConstexprInstantiation ||
-          (NewFD->getTemplateInstantiationPattern() &&
-           NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
-         "only constexpr templates can be instantiated non-constexpr");
-
-  if (const CXXConstructorDecl *CD =3D dyn_cast<CXXConstructorDecl>(NewFD)=
) {
-    // C++0x [dcl.constexpr]p4:
-    //  In the definition of a constexpr constructor, each of the parameter
-    //  types shall be a literal type.
-    if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
+// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
+bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
+  const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(NewFD);
+  if (MD && MD->isInstance()) {
+    // C++11 [dcl.constexpr]p4:
+    //  The definition of a constexpr constructor shall satisfy the follow=
ing
+    //  constraints:
+    //  - the class shall not have any virtual base classes;
+    const CXXRecordDecl *RD =3D MD->getParent();
+    if (RD->getNumVBases()) {
+      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
+        << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
+        << RD->getNumVBases();
+      for (CXXRecordDecl::base_class_const_iterator I =3D RD->vbases_begin=
(),
+             E =3D RD->vbases_end(); I !=3D E; ++I)
+        Diag(I->getLocStart(),
+             diag::note_constexpr_virtual_base_here) << I->getSourceRange(=
);
       return false;
-
-    //  In addition, either its function-body shall be =3D delete or =3D d=
efault or
-    //  it shall satisfy the following constraints:
-    //  - the class shall not have any virtual base classes;
-    const CXXRecordDecl *RD =3D CD->getParent();
-    if (RD->getNumVBases()) {
-      // Note, this is still illegal if the body is =3D default, since the
-      // implicit body does not satisfy the requirements of a constexpr
-      // constructor. We also reject cases where the body is =3D delete, as
-      // required by N3308.
-      if (CCK !=3D CCK_Instantiation) {
-        Diag(NewFD->getLocation(),
-             CCK =3D=3D CCK_Declaration ? diag::err_constexpr_virtual_base
-                                    : diag::note_constexpr_tmpl_virtual_ba=
se)
-          << RD->isStruct() << RD->getNumVBases();
-        for (CXXRecordDecl::base_class_const_iterator I =3D RD->vbases_beg=
in(),
-               E =3D RD->vbases_end(); I !=3D E; ++I)
-          Diag(I->getSourceRange().getBegin(),
-               diag::note_constexpr_virtual_base_here) << I->getSourceRang=
e();
-      }
-      return false;
-    }
-  } else {
-    // C++0x [dcl.constexpr]p3:
+    }
+  }
+
+  if (!isa<CXXConstructorDecl>(NewFD)) {
+    // C++11 [dcl.constexpr]p3:
     //  The definition of a constexpr function shall satisfy the following
     //  constraints:
     // - it shall not be virtual;
     const CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(NewFD);
     if (Method && Method->isVirtual()) {
-      if (CCK !=3D CCK_Instantiation) {
-        Diag(NewFD->getLocation(),
-             CCK =3D=3D CCK_Declaration ? diag::err_constexpr_virtual
-                                    : diag::note_constexpr_tmpl_virtual);
-
-        // If it's not obvious why this function is virtual, find an overr=
idden
-        // function which uses the 'virtual' keyword.
-        const CXXMethodDecl *WrittenVirtual =3D Method;
-        while (!WrittenVirtual->isVirtualAsWritten())
-          WrittenVirtual =3D *WrittenVirtual->begin_overridden_methods();
-        if (WrittenVirtual !=3D Method)
-          Diag(WrittenVirtual->getLocation(),=20
-               diag::note_overridden_virtual_function);
-      }
+      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
+
+      // If it's not obvious why this function is virtual, find an overrid=
den
+      // function which uses the 'virtual' keyword.
+      const CXXMethodDecl *WrittenVirtual =3D Method;
+      while (!WrittenVirtual->isVirtualAsWritten())
+        WrittenVirtual =3D *WrittenVirtual->begin_overridden_methods();
+      if (WrittenVirtual !=3D Method)
+        Diag(WrittenVirtual->getLocation(),
+             diag::note_overridden_virtual_function);
       return false;
     }
=20
     // - its return type shall be a literal type;
     QualType RT =3D NewFD->getResultType();
     if (!RT->isDependentType() &&
-        RequireLiteralType(NewFD->getLocation(), RT, CCK =3D=3D CCK_Declar=
ation ?
-                           PDiag(diag::err_constexpr_non_literal_return) :
-                           PDiag(),
-                           /*AllowIncompleteType*/ true)) {
-      if (CCK =3D=3D CCK_NoteNonConstexprInstantiation)
-        Diag(NewFD->getLocation(),
-             diag::note_constexpr_tmpl_non_literal_return) << RT;
+        RequireLiteralType(NewFD->getLocation(), RT,
+                           PDiag(diag::err_constexpr_non_literal_return)))
       return false;
-    }
-
-    // - each of its parameter types shall be a literal type;
-    if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
-      return false;
-  }
+  }
+
+  // - each of its parameter types shall be a literal type;
+  if (!CheckConstexprParameterTypes(*this, NewFD))
+    return false;
=20
   return true;
 }
@@ -812,7 +811,11 @@
                                           bool &Diagnosed) {
   if (Field->isUnnamedBitfield())
     return;
- =20
+
+  if (Field->isAnonymousStructOrUnion() &&
+      Field->getType()->getAsCXXRecordDecl()->isEmpty())
+    return;
+
   if (!Inits.count(Field)) {
     if (!Diagnosed) {
       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_in=
it);
@@ -836,13 +839,13 @@
 /// \return true if the body is OK, false if we have diagnosed a problem.
 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body)=
 {
   if (isa<CXXTryStmt>(Body)) {
-    // C++0x [dcl.constexpr]p3:
+    // C++11 [dcl.constexpr]p3:
     //  The definition of a constexpr function shall satisfy the following
     //  constraints: [...]
     // - its function-body shall be =3D delete, =3D default, or a
     //   compound-statement
     //
-    // C++0x [dcl.constexpr]p4:
+    // C++11 [dcl.constexpr]p4:
     //  In the definition of a constexpr constructor, [...]
     // - its function-body shall not be a function-try-block;
     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
@@ -877,12 +880,6 @@
         break;
=20
       ReturnStmts.push_back((*BodyIt)->getLocStart());
-      // FIXME
-      // - every constructor call and implicit conversion used in initiali=
zing
-      //   the return value shall be one of those allowed in a constant
-      //   expression.
-      // Deal with this as part of a general check that the function can p=
roduce
-      // a constant expression (for [dcl.constexpr]p5).
       continue;
=20
     default:
@@ -897,11 +894,14 @@
   if (const CXXConstructorDecl *Constructor
         =3D dyn_cast<CXXConstructorDecl>(Dcl)) {
     const CXXRecordDecl *RD =3D Constructor->getParent();
-    // - every non-static data member and base class sub-object shall be
-    //   initialized;
+    // DR1359:
+    // - every non-variant non-static data member and base class sub-object
+    //   shall be initialized;
+    // - if the class is a non-empty union, or for each non-empty anonymous
+    //   union member of a non-union class, exactly one non-static data me=
mber
+    //   shall be initialized;
     if (RD->isUnion()) {
-      // DR1359: Exactly one member of a union shall be initialized.
-      if (Constructor->getNumCtorInitializers() =3D=3D 0) {
+      if (Constructor->getNumCtorInitializers() =3D=3D 0 && !RD->isEmpty()=
) {
         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
         return false;
       }
@@ -943,20 +943,6 @@
           return false;
       }
     }
-
-    // FIXME
-    // - every constructor involved in initializing non-static data members
-    //   and base class sub-objects shall be a constexpr constructor;
-    // - every assignment-expression that is an initializer-clause appeari=
ng
-    //   directly or indirectly within a brace-or-equal-initializer for
-    //   a non-static data member that is not named by a mem-initializer-id
-    //   shall be a constant expression; and
-    // - every implicit conversion used in converting a constructor argume=
nt
-    //   to the corresponding parameter type and converting
-    //   a full-expression to the corresponding member type shall be one of
-    //   those allowed in a constant expression.
-    // Deal with these as part of a general check that the function can pr=
oduce
-    // a constant expression (for [dcl.constexpr]p5).
   } else {
     if (ReturnStmts.empty()) {
       Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
@@ -970,6 +956,25 @@
     }
   }
=20
+  // C++11 [dcl.constexpr]p5:
+  //   if no function argument values exist such that the function invocat=
ion
+  //   substitution would produce a constant expression, the program is
+  //   ill-formed; no diagnostic required.
+  // C++11 [dcl.constexpr]p3:
+  //   - every constructor call and implicit conversion used in initializi=
ng the
+  //     return value shall be one of those allowed in a constant expressi=
on.
+  // C++11 [dcl.constexpr]p4:
+  //   - every constructor involved in initializing non-static data member=
s and
+  //     base class sub-objects shall be a constexpr constructor.
+  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
+  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
+    Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_e=
xpr)
+      << isa<CXXConstructorDecl>(Dcl);
+    for (size_t I =3D 0, N =3D Diags.size(); I !=3D N; ++I)
+      Diag(Diags[I].first, Diags[I].second);
+    return false;
+  }
+
   return true;
 }
=20
@@ -979,7 +984,7 @@
 /// the innermost class.
 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
                               const CXXScopeSpec *SS) {
-  assert(getLangOptions().CPlusPlus && "No class names in C!");
+  assert(getLangOpts().CPlusPlus && "No class names in C!");
=20
   CXXRecordDecl *CurDecl;
   if (SS && SS->isSet() && !SS->isInvalid()) {
@@ -1133,13 +1138,15 @@
     QualType NewBaseType
       =3D Context.getCanonicalType(Bases[idx]->getType());
     NewBaseType =3D NewBaseType.getLocalUnqualifiedType();
-    if (KnownBaseTypes[NewBaseType]) {
+
+    CXXBaseSpecifier *&KnownBase =3D KnownBaseTypes[NewBaseType];
+    if (KnownBase) {
       // C++ [class.mi]p3:
       //   A class shall not be specified as a direct base class of a
       //   derived class more than once.
-      Diag(Bases[idx]->getSourceRange().getBegin(),
+      Diag(Bases[idx]->getLocStart(),
            diag::err_duplicate_base_class)
-        << KnownBaseTypes[NewBaseType]->getType()
+        << KnownBase->getType()
         << Bases[idx]->getSourceRange();
=20
       // Delete the duplicate base class specifier; we're going to
@@ -1149,8 +1156,12 @@
       Invalid =3D true;
     } else {
       // Okay, add this new base class.
-      KnownBaseTypes[NewBaseType] =3D Bases[idx];
+      KnownBase =3D Bases[idx];
       Bases[NumGoodBases++] =3D Bases[idx];
+      if (const RecordType *Record =3D NewBaseType->getAs<RecordType>())
+        if (const CXXRecordDecl *RD =3D cast<CXXRecordDecl>(Record->getDec=
l()))
+          if (RD->hasAttr<WeakAttr>())
+            Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context=
));
     }
   }
=20
@@ -1190,7 +1201,7 @@
 /// \brief Determine whether the type \p Derived is a C++ class that is
 /// derived from the type \p Base.
 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
-  if (!getLangOptions().CPlusPlus)
+  if (!getLangOpts().CPlusPlus)
     return false;
  =20
   CXXRecordDecl *DerivedRD =3D GetClassForType(Derived);
@@ -1208,7 +1219,7 @@
 /// \brief Determine whether the type \p Derived is a C++ class that is
 /// derived from the type \p Base.
 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Pa=
ths) {
-  if (!getLangOptions().CPlusPlus)
+  if (!getLangOpts().CPlusPlus)
     return false;
  =20
   CXXRecordDecl *DerivedRD =3D GetClassForType(Derived);
@@ -1441,7 +1452,7 @@
=20
   // For anonymous bitfields, the location should point to the type.
   if (Loc.isInvalid())
-    Loc =3D D.getSourceRange().getBegin();
+    Loc =3D D.getLocStart();
=20
   Expr *BitWidth =3D static_cast<Expr*>(BW);
=20
@@ -1527,14 +1538,12 @@
       // class X {
       //   int X::member;
       // };
-      DeclContext *DC =3D 0;
-      if ((DC =3D computeDeclContext(SS, false)) && DC->Equals(CurContext))
-        Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
-        << Name << FixItHint::CreateRemoval(SS.getRange());
+      if (DeclContext *DC =3D computeDeclContext(SS, false))
+        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
       else
         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
           << Name << SS.getRange();
-      =20
+     =20
       SS.clear();
     }
=20
@@ -1631,11 +1640,26 @@
     return;
   }
=20
+  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
+    FD->setInvalidDecl();
+    FD->removeInClassInitializer();
+    return;
+  }
+
   ExprResult Init =3D InitExpr;
   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
-    // FIXME: if there is no EqualLoc, this is list-initialization.
-    Init =3D PerformCopyInitialization(
-      InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
+    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(),=
 0)) {
+      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
+        << /*at end of ctor*/1 << InitExpr->getSourceRange();
+    }
+    Expr **Inits =3D &InitExpr;
+    unsigned NumInits =3D 1;
+    InitializedEntity Entity =3D InitializedEntity::InitializeMember(FD);
+    InitializationKind Kind =3D EqualLoc.isInvalid()
+        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
+        : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc=
);
+    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
+    Init =3D Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits=
));
     if (Init.isInvalid()) {
       FD->setInvalidDecl();
       return;
@@ -1710,11 +1734,13 @@
                           CXXScopeSpec &SS,
                           IdentifierInfo *MemberOrBase,
                           ParsedType TemplateTypeTy,
+                          const DeclSpec &DS,
                           SourceLocation IdLoc,
                           Expr *InitList,
                           SourceLocation EllipsisLoc) {
   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTy=
peTy,
-                             IdLoc, MultiInitializer(InitList), EllipsisLo=
c);
+                             DS, IdLoc, InitList,
+                             EllipsisLoc);
 }
=20
 /// \brief Handle a C++ member initializer using parentheses syntax.
@@ -1724,15 +1750,41 @@
                           CXXScopeSpec &SS,
                           IdentifierInfo *MemberOrBase,
                           ParsedType TemplateTypeTy,
+                          const DeclSpec &DS,
                           SourceLocation IdLoc,
                           SourceLocation LParenLoc,
                           Expr **Args, unsigned NumArgs,
                           SourceLocation RParenLoc,
                           SourceLocation EllipsisLoc) {
+  Expr *List =3D new (Context) ParenListExpr(Context, LParenLoc, Args, Num=
Args,
+                                           RParenLoc);
   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTy=
peTy,
-                             IdLoc, MultiInitializer(LParenLoc, Args, NumA=
rgs,
-                                                     RParenLoc),
-                             EllipsisLoc);
+                             DS, IdLoc, List, EllipsisLoc);
+}
+
+namespace {
+
+// Callback to only accept typo corrections that can be a valid C++ member
+// intializer: either a non-static field member or a base class.
+class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
+      : ClassDecl(ClassDecl) {}
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    if (NamedDecl *ND =3D candidate.getCorrectionDecl()) {
+      if (FieldDecl *Member =3D dyn_cast<FieldDecl>(ND))
+        return Member->getDeclContext()->getRedeclContext()->Equals(ClassD=
ecl);
+      else
+        return isa<TypeDecl>(ND);
+    }
+    return false;
+  }
+
+ private:
+  CXXRecordDecl *ClassDecl;
+};
+
 }
=20
 /// \brief Handle a C++ member initializer.
@@ -1742,8 +1794,9 @@
                           CXXScopeSpec &SS,
                           IdentifierInfo *MemberOrBase,
                           ParsedType TemplateTypeTy,
+                          const DeclSpec &DS,
                           SourceLocation IdLoc,
-                          const MultiInitializer &Args,
+                          Expr *Init,
                           SourceLocation EllipsisLoc) {
   if (!ConstructorD)
     return true;
@@ -1774,28 +1827,18 @@
   //   using a qualified name. ]
   if (!SS.getScopeRep() && !TemplateTypeTy) {
     // Look for a member, first.
-    FieldDecl *Member =3D 0;
     DeclContext::lookup_result Result
       =3D ClassDecl->lookup(MemberOrBase);
     if (Result.first !=3D Result.second) {
-      Member =3D dyn_cast<FieldDecl>(*Result.first);
-
-      if (Member) {
+      ValueDecl *Member;
+      if ((Member =3D dyn_cast<FieldDecl>(*Result.first)) ||
+          (Member =3D dyn_cast<IndirectFieldDecl>(*Result.first))) {
         if (EllipsisLoc.isValid())
           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
-            << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
-
-        return BuildMemberInitializer(Member, Args, IdLoc);
-      }
-
-      // Handle anonymous union case.
-      if (IndirectFieldDecl* IndirectField
-            =3D dyn_cast<IndirectFieldDecl>(*Result.first)) {
-        if (EllipsisLoc.isValid())
-          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
-            << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
-
-         return BuildMemberInitializer(IndirectField, Args, IdLoc);
+            << MemberOrBase
+            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
+
+        return BuildMemberInitializer(Member, Init, IdLoc);
       }
     }
   }
@@ -1805,6 +1848,8 @@
=20
   if (TemplateTypeTy) {
     BaseType =3D GetTypeFromParser(TemplateTypeTy, &TInfo);
+  } else if (DS.getTypeSpecType() =3D=3D TST_decltype) {
+    BaseType =3D BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLo=
c());
   } else {
     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
     LookupParsedName(R, S, &SS);
@@ -1838,24 +1883,23 @@
=20
       // If no results were found, try to correct typos.
       TypoCorrection Corr;
+      MemInitializerValidatorCCC Validator(ClassDecl);
       if (R.empty() && BaseType.isNull() &&
           (Corr =3D CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), =
S, &SS,
-                              ClassDecl, false, CTC_NoKeywords))) {
-        std::string CorrectedStr(Corr.getAsString(getLangOptions()));
-        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
+                              Validator, ClassDecl))) {
+        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
+        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
         if (FieldDecl *Member =3D Corr.getCorrectionDeclAs<FieldDecl>()) {
-          if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDe=
cl)) {
-            // We have found a non-static data member with a similar
-            // name to what was typed; complain and initialize that
-            // member.
-            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_su=
ggest)
-              << MemberOrBase << true << CorrectedQuotedStr
-              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr=
);
-            Diag(Member->getLocation(), diag::note_previous_decl)
-              << CorrectedQuotedStr;
-
-            return BuildMemberInitializer(Member, Args, IdLoc);
-          }
+          // We have found a non-static data member with a similar
+          // name to what was typed; complain and initialize that
+          // member.
+          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_sugg=
est)
+            << MemberOrBase << true << CorrectedQuotedStr
+            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
+          Diag(Member->getLocation(), diag::note_previous_decl)
+            << CorrectedQuotedStr;
+
+          return BuildMemberInitializer(Member, Init, IdLoc);
         } else if (TypeDecl *Type =3D Corr.getCorrectionDeclAs<TypeDecl>()=
) {
           const CXXBaseSpecifier *DirectBaseSpec;
           const CXXBaseSpecifier *VirtualBaseSpec;
@@ -1871,7 +1915,7 @@
=20
             const CXXBaseSpecifier *BaseSpec =3D DirectBaseSpec? DirectBas=
eSpec=20
                                                              : VirtualBase=
Spec;
-            Diag(BaseSpec->getSourceRange().getBegin(),
+            Diag(BaseSpec->getLocStart(),
                  diag::note_base_class_specified_here)
               << BaseSpec->getType()
               << BaseSpec->getSourceRange();
@@ -1883,7 +1927,7 @@
=20
       if (!TyD && BaseType.isNull()) {
         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
-          << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
+          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getE=
nd());
         return true;
       }
     }
@@ -1903,7 +1947,7 @@
   if (!TInfo)
     TInfo =3D Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
=20
-  return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLo=
c);
+  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLo=
c);
 }
=20
 /// Checks a member initializer expression for cases where reference (or
@@ -2030,14 +2074,16 @@
 }
=20
 MemInitResult
-Sema::BuildMemberInitializer(ValueDecl *Member,
-                             const MultiInitializer &Args,
+Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
                              SourceLocation IdLoc) {
   FieldDecl *DirectMember =3D dyn_cast<FieldDecl>(Member);
   IndirectFieldDecl *IndirectMember =3D dyn_cast<IndirectFieldDecl>(Member=
);
   assert((DirectMember || IndirectMember) &&
          "Member must be a FieldDecl or IndirectFieldDecl");
=20
+  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
+    return true;
+
   if (Member->isInvalidDecl())
     return true;
=20
@@ -2045,13 +2091,19 @@
   //   foo(foo)
   // where foo is not also a parameter to the constructor.
   // TODO: implement -Wuninitialized and fold this into that framework.
-  for (MultiInitializer::iterator I =3D Args.begin(), E =3D Args.end();
-       I !=3D E; ++I) {
+  Expr **Args;
+  unsigned NumArgs;
+  if (ParenListExpr *ParenList =3D dyn_cast<ParenListExpr>(Init)) {
+    Args =3D ParenList->getExprs();
+    NumArgs =3D ParenList->getNumExprs();
+  } else {
+    InitListExpr *InitList =3D cast<InitListExpr>(Init);
+    Args =3D InitList->getInits();
+    NumArgs =3D InitList->getNumInits();
+  }
+  for (unsigned i =3D 0; i < NumArgs; ++i) {
     SourceLocation L;
-    Expr *Arg =3D *I;
-    if (DesignatedInitExpr *DIE =3D dyn_cast<DesignatedInitExpr>(Arg))
-      Arg =3D DIE->getInit();
-    if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
+    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
       // FIXME: Return true in the case when other fields are used before =
being
       // uninitialized. For example, let this field be the i'th field. When
       // initializing the i'th field, throw a warning if any of the >=3D i=
'th
@@ -2062,29 +2114,43 @@
     }
   }
=20
-  bool HasDependentArg =3D Args.isTypeDependent();
-
-  Expr *Init;
-  if (Member->getType()->isDependentType() || HasDependentArg) {
+  SourceRange InitRange =3D Init->getSourceRange();
+
+  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
     // Can't check initialization for a member of dependent type or when
     // any of the arguments are type-dependent expressions.
-    Init =3D Args.CreateInitExpr(Context,Member->getType().getNonReference=
Type());
-
     DiscardCleanupsInEvaluationContext();
   } else {
+    bool InitList =3D false;
+    if (isa<InitListExpr>(Init)) {
+      InitList =3D true;
+      Args =3D &Init;
+      NumArgs =3D 1;
+
+      if (isStdInitializerList(Member->getType(), 0)) {
+        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
+            << /*at end of ctor*/1 << InitRange;
+      }
+    }
+
     // Initialize the member.
     InitializedEntity MemberEntity =3D
       DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
                    : InitializedEntity::InitializeMember(IndirectMember, 0=
);
     InitializationKind Kind =3D
-      InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
-                                       Args.getEndLoc());
-
-    ExprResult MemberInit =3D Args.PerformInit(*this, MemberEntity, Kind);
+      InitList ? InitializationKind::CreateDirectList(IdLoc)
+               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegi=
n(),
+                                                  InitRange.getEnd());
+
+    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArg=
s);
+    ExprResult MemberInit =3D InitSeq.Perform(*this, MemberEntity, Kind,
+                                            MultiExprArg(*this, Args, NumA=
rgs),
+                                            0);
     if (MemberInit.isInvalid())
       return true;
=20
-    CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
+    CheckImplicitConversions(MemberInit.get(),
+                             InitRange.getBegin());
=20
     // C++0x [class.base.init]p7:
     //   The initialization of each base and member constitutes a
@@ -2095,14 +2161,13 @@
=20
     // If we are in a dependent context, template instantiation will
     // perform this type-checking again. Just save the arguments that we
-    // received in a ParenListExpr.
+    // received.
     // FIXME: This isn't quite ideal, since our ASTs don't capture all
     // of the information that we have about the member
     // initializer. However, deconstructing the ASTs is a dicey process,
     // and this approach is far more likely to get the corner cases right.
     if (CurContext->isDependentContext()) {
-      Init =3D Args.CreateInitExpr(Context,
-                                 Member->getType().getNonReferenceType());
+      // The existing Init will do fine.
     } else {
       Init =3D MemberInit.get();
       CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
@@ -2110,43 +2175,53 @@
   }
=20
   if (DirectMember) {
-    return new (Context) CXXCtorInitializer(Context, DirectMember,
-                                                    IdLoc, Args.getStartLo=
c(),
-                                                    Init, Args.getEndLoc()=
);
+    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
+                                            InitRange.getBegin(), Init,
+                                            InitRange.getEnd());
   } else {
-    return new (Context) CXXCtorInitializer(Context, IndirectMember,
-                                                    IdLoc, Args.getStartLo=
c(),
-                                                    Init, Args.getEndLoc()=
);
+    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
+                                            InitRange.getBegin(), Init,
+                                            InitRange.getEnd());
   }
 }
=20
 MemInitResult
-Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
-                                 const MultiInitializer &Args,
-                                 SourceLocation NameLoc,
+Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
                                  CXXRecordDecl *ClassDecl) {
-  SourceLocation Loc =3D TInfo->getTypeLoc().getLocalSourceRange().getBegi=
n();
+  SourceLocation NameLoc =3D TInfo->getTypeLoc().getLocalSourceRange().get=
Begin();
   if (!LangOpts.CPlusPlus0x)
-    return Diag(Loc, diag::err_delegation_0x_only)
+    return Diag(NameLoc, diag::err_delegating_ctor)
       << TInfo->getTypeLoc().getLocalSourceRange();
-
+  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
+
+  bool InitList =3D true;
+  Expr **Args =3D &Init;
+  unsigned NumArgs =3D 1;
+  if (ParenListExpr *ParenList =3D dyn_cast<ParenListExpr>(Init)) {
+    InitList =3D false;
+    Args =3D ParenList->getExprs();
+    NumArgs =3D ParenList->getNumExprs();
+  }
+
+  SourceRange InitRange =3D Init->getSourceRange();
   // Initialize the object.
   InitializedEntity DelegationEntity =3D InitializedEntity::InitializeDele=
gation(
                                      QualType(ClassDecl->getTypeForDecl(),=
 0));
   InitializationKind Kind =3D
-    InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
-                                     Args.getEndLoc());
-
-  ExprResult DelegationInit =3D Args.PerformInit(*this, DelegationEntity, =
Kind);
+    InitList ? InitializationKind::CreateDirectList(NameLoc)
+             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegi=
n(),
+                                                InitRange.getEnd());
+  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumA=
rgs);
+  ExprResult DelegationInit =3D InitSeq.Perform(*this, DelegationEntity, K=
ind,
+                                              MultiExprArg(*this, Args,Num=
Args),
+                                              0);
   if (DelegationInit.isInvalid())
     return true;
=20
-  CXXConstructExpr *ConExpr =3D cast<CXXConstructExpr>(DelegationInit.get(=
));
-  CXXConstructorDecl *Constructor
-    =3D ConExpr->getConstructor();
-  assert(Constructor && "Delegating constructor with no target?");
-
-  CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
+  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
+         "Delegating constructor with no target?");
+
+  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
=20
   // C++0x [class.base.init]p7:
   //   The initialization of each base and member constitutes a
@@ -2155,20 +2230,15 @@
   if (DelegationInit.isInvalid())
     return true;
=20
-  assert(!CurContext->isDependentContext());
-  return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
-                                          Constructor,
+  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBeg=
in(),=20
                                           DelegationInit.takeAs<Expr>(),
-                                          Args.getEndLoc());
+                                          InitRange.getEnd());
 }
=20
 MemInitResult
 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
-                           const MultiInitializer &Args,
-                           CXXRecordDecl *ClassDecl,
+                           Expr *Init, CXXRecordDecl *ClassDecl,
                            SourceLocation EllipsisLoc) {
-  bool HasDependentArg =3D Args.isTypeDependent();
-
   SourceLocation BaseLoc
     =3D BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
=20
@@ -2182,13 +2252,14 @@
   //   of that class, the mem-initializer is ill-formed. A
   //   mem-initializer-list can initialize a base class using any
   //   name that denotes that base class type.
-  bool Dependent =3D BaseType->isDependentType() || HasDependentArg;
-
+  bool Dependent =3D BaseType->isDependentType() || Init->isTypeDependent(=
);
+
+  SourceRange InitRange =3D Init->getSourceRange();
   if (EllipsisLoc.isValid()) {
     // This is a pack expansion.
     if (!BaseType->containsUnexpandedParameterPack())  {
       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
-        << SourceRange(BaseLoc, Args.getEndLoc());
+        << SourceRange(BaseLoc, InitRange.getEnd());
=20
       EllipsisLoc =3D SourceLocation();
     }
@@ -2197,7 +2268,7 @@
     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializ=
er))
       return true;
=20
-    if (Args.DiagnoseUnexpandedParameterPack(*this))
+    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
       return true;
   }
=20
@@ -2207,7 +2278,7 @@
   if (!Dependent) {=20
     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(=
),0),
                                        BaseType))
-      return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDec=
l);
+      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
=20
     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,=20
                         VirtualBaseSpec);
@@ -2232,16 +2303,12 @@
   }
=20
   if (Dependent) {
-    // Can't check initialization for a base of dependent type or when
-    // any of the arguments are type-dependent expressions.
-    Expr *BaseInit =3D Args.CreateInitExpr(Context, BaseType);
-
     DiscardCleanupsInEvaluationContext();
=20
     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
                                             /*IsVirtual=3D*/false,
-                                            Args.getStartLoc(), BaseInit,
-                                            Args.getEndLoc(), EllipsisLoc);
+                                            InitRange.getBegin(), Init,
+                                            InitRange.getEnd(), EllipsisLo=
c);
   }
=20
   // C++ [base.class.init]p2:
@@ -2252,23 +2319,34 @@
     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
=20
-  CXXBaseSpecifier *BaseSpec
-    =3D const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
+  CXXBaseSpecifier *BaseSpec =3D const_cast<CXXBaseSpecifier *>(DirectBase=
Spec);
   if (!BaseSpec)
     BaseSpec =3D const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
=20
   // Initialize the base.
+  bool InitList =3D true;
+  Expr **Args =3D &Init;
+  unsigned NumArgs =3D 1;
+  if (ParenListExpr *ParenList =3D dyn_cast<ParenListExpr>(Init)) {
+    InitList =3D false;
+    Args =3D ParenList->getExprs();
+    NumArgs =3D ParenList->getNumExprs();
+  }
+
   InitializedEntity BaseEntity =3D
     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
-  InitializationKind Kind =3D=20
-    InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
-                                     Args.getEndLoc());
-
-  ExprResult BaseInit =3D Args.PerformInit(*this, BaseEntity, Kind);
+  InitializationKind Kind =3D
+    InitList ? InitializationKind::CreateDirectList(BaseLoc)
+             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegi=
n(),
+                                                InitRange.getEnd());
+  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
+  ExprResult BaseInit =3D InitSeq.Perform(*this, BaseEntity, Kind,
+                                          MultiExprArg(*this, Args, NumArg=
s),
+                                          0);
   if (BaseInit.isInvalid())
     return true;
=20
-  CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
+  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
=20
   // C++0x [class.base.init]p7:
   //   The initialization of each base and member constitutes a=20
@@ -2285,13 +2363,13 @@
   // initializer. However, deconstructing the ASTs is a dicey process,
   // and this approach is far more likely to get the corner cases right.
   if (CurContext->isDependentContext())
-    BaseInit =3D Owned(Args.CreateInitExpr(Context, BaseType));
+    BaseInit =3D Owned(Init);
=20
   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
                                           BaseSpec->isVirtual(),
-                                          Args.getStartLoc(),
+                                          InitRange.getBegin(),
                                           BaseInit.takeAs<Expr>(),
-                                          Args.getEndLoc(), EllipsisLoc);
+                                          InitRange.getEnd(), EllipsisLoc);
 }
=20
 // Create a static_cast\<T&&>(expr).
@@ -2342,12 +2420,15 @@
     bool Moving =3D ImplicitInitKind =3D=3D IIK_Move;
     ParmVarDecl *Param =3D Constructor->getParamDecl(0);
     QualType ParamType =3D Param->getType().getNonReferenceType();
-   =20
+
     Expr *CopyCtorArg =3D=20
-      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param=
,=20
+      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
+                          SourceLocation(), Param, false,
                           Constructor->getLocation(), ParamType,
                           VK_LValue, 0);
=20
+    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
+
     // Cast to the base class to avoid ambiguities.
     QualType ArgTy =3D=20
       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedT=
ype(),=20
@@ -2415,11 +2496,14 @@
     // Suppress copying zero-width bitfields.
     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) =
=3D=3D 0)
       return false;
-   =20
+       =20
     Expr *MemberExprBase =3D=20
-      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param=
,=20
+      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
+                          SourceLocation(), Param, false,
                           Loc, ParamType, VK_LValue, 0);
=20
+    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
+
     if (Moving) {
       MemberExprBase =3D CastForMoving(SemaRef, MemberExprBase);
     }
@@ -2436,6 +2520,7 @@
                                          ParamType, Loc,
                                          /*IsArrow=3D*/false,
                                          SS,
+                                         /*TemplateKWLoc=3D*/SourceLocatio=
n(),
                                          /*FirstQualifierInScope=3D*/0,
                                          MemberLookup,
                                          /*TemplateArgs=3D*/0);   =20
@@ -2463,7 +2548,7 @@
       // Create the iteration variable for this array index.
       IdentifierInfo *IterationVarName =3D 0;
       {
-        llvm::SmallString<8> Str;
+        SmallString<8> Str;
         llvm::raw_svector_ostream OS(Str);
         OS << "__i" << IndexVariables.size();
         IterationVarName =3D &SemaRef.Context.Idents.get(OS.str());
@@ -2477,9 +2562,12 @@
      =20
       // Create a reference to the iteration variable.
       ExprResult IterationVarRef
-        =3D SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Lo=
c);
+        =3D SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Lo=
c);
       assert(!IterationVarRef.isInvalid() &&
              "Reference to invented variable cannot fail!");
+      IterationVarRef =3D SemaRef.DefaultLvalueConversion(IterationVarRef.=
take());
+      assert(!IterationVarRef.isInvalid() &&
+             "Conversion of invented variable cannot fail!");
=20
       // Subscript the array with this iteration variable.
       CtorArg =3D SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), =
Loc,
@@ -2597,7 +2685,7 @@
     }
   }
  =20
-  if (SemaRef.getLangOptions().ObjCAutoRefCount &&
+  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
       FieldBaseElementType->isObjCRetainableType() &&
       FieldBaseElementType.getObjCLifetime() !=3D Qualifiers::OCL_None &&
       FieldBaseElementType.getObjCLifetime() !=3D Qualifiers::OCL_Explicit=
None) {
@@ -2635,6 +2723,19 @@
     else
       IIK =3D IIK_Default;
   }
+ =20
+  bool isImplicitCopyOrMove() const {
+    switch (IIK) {
+    case IIK_Copy:
+    case IIK_Move:
+      return true;
+     =20
+    case IIK_Default:
+      return false;
+    }
+
+    llvm_unreachable("Invalid ImplicitInitializerKind!");
+  }
 };
 }
=20
@@ -2651,6 +2752,22 @@
   return false;
 }
=20
+/// \brief Determine whether the given type is an incomplete or zero-lenfg=
th
+/// array type.
+static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualTyp=
e T) {
+  if (T->isIncompleteArrayType())
+    return true;
+ =20
+  while (const ConstantArrayType *ArrayT =3D Context.getAsConstantArrayTyp=
e(T)) {
+    if (!ArrayT->getSize())
+      return true;
+   =20
+    T =3D ArrayT->getElementType();
+  }
+ =20
+  return false;
+}
+
 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
                                     FieldDecl *Field,=20
                                     IndirectFieldDecl *Indirect =3D 0) {
@@ -2664,7 +2781,7 @@
   // C++0x [class.base.init]p8: if the entity is a non-static data member =
that
   // has a brace-or-equal-initializer, the entity is initialized as specif=
ied
   // in [dcl.init].
-  if (Field->hasInClassInitializer()) {
+  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
     CXXCtorInitializer *Init;
     if (Indirect)
       Init =3D new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, I=
ndirect,
@@ -2686,6 +2803,10 @@
       (Indirect && isWithinAnonymousUnion(Indirect)))
     return false;
=20
+  // Don't initialize incomplete or zero-length arrays.
+  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
+    return false;
+
   // Don't try to build an implicit initializer if there were semantic
   // errors in any of the initializers (and therefore we might be
   // missing some that the user actually wrote).
@@ -2714,7 +2835,7 @@
   Constructor->setCtorInitializers(initializer);
=20
   if (CXXDestructorDecl *Dtor =3D LookupDestructor(Constructor->getParent(=
))) {
-    MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
+    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
   }
=20
@@ -2824,13 +2945,7 @@
       //   initialized.
       if (F->isUnnamedBitfield())
         continue;
-     =20
-      if (F->getType()->isIncompleteArrayType()) {
-        assert(ClassDecl->hasFlexibleArrayMember() &&
-               "Incomplete array type is not valid");
-        continue;
-      }
-     =20
+           =20
       // If we're not generating the implicit copy/move constructor, then =
we'll
       // handle anonymous struct/union fields based on their individual
       // indirect fields.
@@ -2997,12 +3112,12 @@
       if (PrevInit->isAnyMemberInitializer())
         D << 0 << PrevInit->getAnyMember()->getDeclName();
       else
-        D << 1 << PrevInit->getBaseClassInfo()->getType();
+        D << 1 << PrevInit->getTypeSourceInfo()->getType();
      =20
       if (Init->isAnyMemberInitializer())
         D << 0 << Init->getAnyMember()->getDeclName();
       else
-        D << 1 << Init->getBaseClassInfo()->getType();
+        D << 1 << Init->getTypeSourceInfo()->getType();
=20
       // Move back to the initializer's location in the ideal list.
       for (IdealIndex =3D 0; IdealIndex !=3D NumIdealInits; ++IdealIndex)
@@ -3053,11 +3168,9 @@
                              RedundantUnionMap &Unions) {
   FieldDecl *Field =3D Init->getAnyMember();
   RecordDecl *Parent =3D Field->getParent();
-  if (!Parent->isAnonymousStructOrUnion())
-    return false;
-
   NamedDecl *Child =3D Field;
-  do {
+
+  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
     if (Parent->isUnion()) {
       UnionEntry &En =3D Unions[Parent];
       if (En.first && En.first !=3D Child) {
@@ -3068,15 +3181,18 @@
         S.Diag(En.second->getSourceLocation(), diag::note_previous_initial=
izer)
           << 0 << En.second->getSourceRange();
         return true;
-      } else if (!En.first) {
+      }=20
+      if (!En.first) {
         En.first =3D Child;
         En.second =3D Init;
       }
+      if (!Parent->isAnonymousStructOrUnion())
+        return false;
     }
=20
     Child =3D Parent;
     Parent =3D cast<RecordDecl>(Parent->getDeclContext());
-  } while (Parent->isAnonymousStructOrUnion());
+  }
=20
   return false;
 }
@@ -3171,6 +3287,11 @@
     FieldDecl *Field =3D *I;
     if (Field->isInvalidDecl())
       continue;
+   =20
+    // Don't destroy incomplete or zero-length arrays.
+    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
+      continue;
+
     QualType FieldType =3D Context.getBaseElementType(Field->getType());
    =20
     const RecordType* RT =3D FieldType->getAs<RecordType>();
@@ -3180,7 +3301,10 @@
     CXXRecordDecl *FieldClassDecl =3D cast<CXXRecordDecl>(RT->getDecl());
     if (FieldClassDecl->isInvalidDecl())
       continue;
-    if (FieldClassDecl->hasTrivialDestructor())
+    if (FieldClassDecl->hasIrrelevantDestructor())
+      continue;
+    // The destructor for an implicit anonymous union member is never invo=
ked.
+    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUn=
ion())
       continue;
=20
     CXXDestructorDecl *Dtor =3D LookupDestructor(FieldClassDecl);
@@ -3190,7 +3314,8 @@
                             << Field->getDeclName()
                             << FieldType);
=20
-    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dto=
r));
+    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
+    DiagnoseUseOfDecl(Dtor, Location);
   }
=20
   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
@@ -3209,20 +3334,21 @@
     // If our base class is invalid, we probably can't get its dtor anyway.
     if (BaseClassDecl->isInvalidDecl())
       continue;
-    // Ignore trivial destructors.
-    if (BaseClassDecl->hasTrivialDestructor())
+    if (BaseClassDecl->hasIrrelevantDestructor())
       continue;
=20
     CXXDestructorDecl *Dtor =3D LookupDestructor(BaseClassDecl);
     assert(Dtor && "No dtor found for BaseClassDecl!");
=20
     // FIXME: caret should be on the start of the class name
-    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
+    CheckDestructorAccess(Base->getLocStart(), Dtor,
                           PDiag(diag::err_access_dtor_base)
                             << Base->getType()
-                            << Base->getSourceRange());
+                            << Base->getSourceRange(),
+                          Context.getTypeDeclType(ClassDecl));
    =20
-    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dto=
r));
+    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
+    DiagnoseUseOfDecl(Dtor, Location);
   }
  =20
   // Virtual bases.
@@ -3230,7 +3356,7 @@
        E =3D ClassDecl->vbases_end(); VBase !=3D E; ++VBase) {
=20
     // Bases are always records in a well-formed non-dependent class.
-    const RecordType *RT =3D VBase->getType()->getAs<RecordType>();
+    const RecordType *RT =3D VBase->getType()->castAs<RecordType>();
=20
     // Ignore direct virtual bases.
     if (DirectVirtualBases.count(RT))
@@ -3240,17 +3366,18 @@
     // If our base class is invalid, we probably can't get its dtor anyway.
     if (BaseClassDecl->isInvalidDecl())
       continue;
-    // Ignore trivial destructors.
-    if (BaseClassDecl->hasTrivialDestructor())
+    if (BaseClassDecl->hasIrrelevantDestructor())
       continue;
=20
     CXXDestructorDecl *Dtor =3D LookupDestructor(BaseClassDecl);
     assert(Dtor && "No dtor found for BaseClassDecl!");
     CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
                           PDiag(diag::err_access_dtor_vbase)
-                            << VBase->getType());
-
-    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dto=
r));
+                            << VBase->getType(),
+                          Context.getTypeDeclType(ClassDecl));
+
+    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
+    DiagnoseUseOfDecl(Dtor, Location);
   }
 }
=20
@@ -3273,7 +3400,7 @@
=20
 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
                                   const PartialDiagnostic &PD) {
-  if (!getLangOptions().CPlusPlus)
+  if (!getLangOpts().CPlusPlus)
     return false;
=20
   if (const ArrayType *AT =3D Context.getAsArrayType(T))
@@ -3538,7 +3665,8 @@
   // complain about any non-static data members of reference or const scal=
ar
   // type, since they will never get initializers.
   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
-      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
+      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
+      !Record->isLambda()) {
     bool Complained =3D false;
     for (RecordDecl::field_iterator F =3D Record->field_begin(),=20
                                  FEnd =3D Record->field_end();
@@ -3609,9 +3737,6 @@
   // const. [...] The class of which that function is a member shall be
   // a literal type.
   //
-  // It's fine to diagnose constructors here too: such constructors cannot
-  // produce a constant expression, so are ill-formed (no diagnostic requi=
red).
-  //
   // If the class has virtual bases, any constexpr members will already ha=
ve
   // been diagnosed by the checks performed on the member declaration, so
   // suppress this (less useful) diagnostic.
@@ -3620,16 +3745,14 @@
     for (CXXRecordDecl::method_iterator M =3D Record->method_begin(),
                                      MEnd =3D Record->method_end();
          M !=3D MEnd; ++M) {
-      if ((*M)->isConstexpr()) {
+      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(=
*M)) {
         switch (Record->getTemplateSpecializationKind()) {
         case TSK_ImplicitInstantiation:
         case TSK_ExplicitInstantiationDeclaration:
         case TSK_ExplicitInstantiationDefinition:
           // If a template instantiates to a non-literal type, but its mem=
bers
           // instantiate to constexpr functions, the template is technical=
ly
-          // ill-formed, but we allow it for sanity. Such members are trea=
ted as
-          // non-constexpr.
-          (*M)->setConstexpr(false);
+          // ill-formed, but we allow it for sanity.
           continue;
=20
         case TSK_Undeclared:
@@ -3725,6 +3848,21 @@
                           *ExceptionType =3D Context.getFunctionType(
                          Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoTy=
pe>();
=20
+  // C++11 [dcl.fct.def.default]p2:
+  //   An explicitly-defaulted function may be declared constexpr only if =
it
+  //   would have been implicitly declared as constexpr,
+  // Do not apply this rule to templates, since core issue 1358 makes such
+  // functions always instantiate to constexpr functions.
+  if (CD->isConstexpr() &&
+      CD->getTemplatedKind() =3D=3D FunctionDecl::TK_NonTemplate) {
+    if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
+      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
+        << CXXDefaultConstructor;
+      HadError =3D true;
+    }
+  }
+  //   and may have an explicit exception-specification only if it is comp=
atible
+  //   with the exception-specification on the implicit declaration.
   if (CtorType->hasExceptionSpec()) {
     if (CheckEquivalentExceptionSpec(
           PDiag(diag::err_incorrect_defaulted_exception_spec)
@@ -3734,11 +3872,24 @@
           CtorType, CD->getLocation())) {
       HadError =3D true;
     }
-  } else if (First) {
-    // We set the declaration to have the computed exception spec here.
-    // We know there are no parameters.
+  }
+
+  //   If a function is explicitly defaulted on its first declaration,
+  if (First) {
+    //  -- it is implicitly considered to be constexpr if the implicit
+    //     definition would be,
+    CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstex=
pr());
+
+    //  -- it is implicitly considered to have the same
+    //     exception-specification as if it had been implicitly declared
+    //
+    // FIXME: a compatible, but different, explicit exception specification
+    // will be silently overridden. We should issue a warning if this happ=
ens.
     EPI.ExtInfo =3D CtorType->getExtInfo();
-    CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
+
+    // Such a function is also trivial if the implicitly-declared function
+    // would have been.
+    CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
   }
=20
   if (HadError) {
@@ -3792,6 +3943,21 @@
     HadError =3D true;
   }
=20
+  // C++11 [dcl.fct.def.default]p2:
+  //   An explicitly-defaulted function may be declared constexpr only if =
it
+  //   would have been implicitly declared as constexpr,
+  // Do not apply this rule to templates, since core issue 1358 makes such
+  // functions always instantiate to constexpr functions.
+  if (CD->isConstexpr() &&
+      CD->getTemplatedKind() =3D=3D FunctionDecl::TK_NonTemplate) {
+    if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
+      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
+        << CXXCopyConstructor;
+      HadError =3D true;
+    }
+  }
+  //   and may have an explicit exception-specification only if it is comp=
atible
+  //   with the exception-specification on the implicit declaration.
   if (CtorType->hasExceptionSpec()) {
     if (CheckEquivalentExceptionSpec(
           PDiag(diag::err_incorrect_defaulted_exception_spec)
@@ -3801,11 +3967,28 @@
           CtorType, CD->getLocation())) {
       HadError =3D true;
     }
-  } else if (First) {
-    // We set the declaration to have the computed exception spec here.
-    // We duplicate the one parameter type.
+  }
+
+  //   If a function is explicitly defaulted on its first declaration,
+  if (First) {
+    //  -- it is implicitly considered to be constexpr if the implicit
+    //     definition would be,
+    CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr(=
));
+
+    //  -- it is implicitly considered to have the same
+    //     exception-specification as if it had been implicitly declared, =
and
+    //
+    // FIXME: a compatible, but different, explicit exception specification
+    // will be silently overridden. We should issue a warning if this happ=
ens.
     EPI.ExtInfo =3D CtorType->getExtInfo();
+
+    //  -- [...] it shall have the same parameter type as if it had been
+    //     implicitly declared.
     CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
+
+    // Such a function is also trivial if the implicitly-declared function
+    // would have been.
+    CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
   }
=20
   if (HadError) {
@@ -3886,12 +4069,17 @@
           OperType, MD->getLocation())) {
       HadError =3D true;
     }
-  } else if (First) {
+  }
+  if (First) {
     // We set the declaration to have the computed exception spec here.
     // We duplicate the one parameter type.
     EPI.RefQualifier =3D OperType->getRefQualifier();
     EPI.ExtInfo =3D OperType->getExtInfo();
     MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
+
+    // Such a function is also trivial if the implicitly-declared function
+    // would have been.
+    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
   }
=20
   if (HadError) {
@@ -3899,7 +4087,7 @@
     return;
   }
=20
-  if (ShouldDeleteCopyAssignmentOperator(MD)) {
+  if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
     if (First) {
       MD->setDeletedAsWritten();
     } else {
@@ -3943,6 +4131,21 @@
     HadError =3D true;
   }
=20
+  // C++11 [dcl.fct.def.default]p2:
+  //   An explicitly-defaulted function may be declared constexpr only if =
it
+  //   would have been implicitly declared as constexpr,
+  // Do not apply this rule to templates, since core issue 1358 makes such
+  // functions always instantiate to constexpr functions.
+  if (CD->isConstexpr() &&
+      CD->getTemplatedKind() =3D=3D FunctionDecl::TK_NonTemplate) {
+    if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
+      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
+        << CXXMoveConstructor;
+      HadError =3D true;
+    }
+  }
+  //   and may have an explicit exception-specification only if it is comp=
atible
+  //   with the exception-specification on the implicit declaration.
   if (CtorType->hasExceptionSpec()) {
     if (CheckEquivalentExceptionSpec(
           PDiag(diag::err_incorrect_defaulted_exception_spec)
@@ -3952,11 +4155,28 @@
           CtorType, CD->getLocation())) {
       HadError =3D true;
     }
-  } else if (First) {
-    // We set the declaration to have the computed exception spec here.
-    // We duplicate the one parameter type.
+  }
+
+  //   If a function is explicitly defaulted on its first declaration,
+  if (First) {
+    //  -- it is implicitly considered to be constexpr if the implicit
+    //     definition would be,
+    CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr(=
));
+
+    //  -- it is implicitly considered to have the same
+    //     exception-specification as if it had been implicitly declared, =
and
+    //
+    // FIXME: a compatible, but different, explicit exception specification
+    // will be silently overridden. We should issue a warning if this happ=
ens.
     EPI.ExtInfo =3D CtorType->getExtInfo();
+
+    //  -- [...] it shall have the same parameter type as if it had been
+    //     implicitly declared.
     CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
+
+    // Such a function is also trivial if the implicitly-declared function
+    // would have been.
+    CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
   }
=20
   if (HadError) {
@@ -4035,12 +4255,17 @@
           OperType, MD->getLocation())) {
       HadError =3D true;
     }
-  } else if (First) {
+  }
+  if (First) {
     // We set the declaration to have the computed exception spec here.
     // We duplicate the one parameter type.
     EPI.RefQualifier =3D OperType->getRefQualifier();
     EPI.ExtInfo =3D OperType->getExtInfo();
     MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
+
+    // Such a function is also trivial if the implicitly-declared function
+    // would have been.
+    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
   }
=20
   if (HadError) {
@@ -4048,7 +4273,7 @@
     return;
   }
=20
-  if (ShouldDeleteMoveAssignmentOperator(MD)) {
+  if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
     if (First) {
       MD->setDeletedAsWritten();
     } else {
@@ -4082,14 +4307,19 @@
       DD->setInvalidDecl();
       return;
     }
-  } else if (First) {
+  }
+  if (First) {
     // We set the declaration to have the computed exception spec here.
     // There are no parameters.
     EPI.ExtInfo =3D DtorType->getExtInfo();
     DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
-  }
-
-  if (ShouldDeleteDestructor(DD)) {
+
+    // Such a function is also trivial if the implicitly-declared function
+    // would have been.
+    DD->setTrivial(DD->getParent()->hasTrivialDestructor());
+  }
+
+  if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
     if (First) {
       DD->setDeletedAsWritten();
     } else {
@@ -4100,652 +4330,412 @@
   }
 }
=20
-/// This function implements the following C++0x paragraphs:
-///  - [class.ctor]/5
-///  - [class.copy]/11
-bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember C=
SM) {
+namespace {
+struct SpecialMemberDeletionInfo {
+  Sema &S;
+  CXXMethodDecl *MD;
+  Sema::CXXSpecialMember CSM;
+  bool Diagnose;
+
+  // Properties of the special member, computed for convenience.
+  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
+  SourceLocation Loc;
+
+  bool AllFieldsAreConst;
+
+  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
+                            Sema::CXXSpecialMember CSM, bool Diagnose)
+    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
+      IsConstructor(false), IsAssignment(false), IsMove(false),
+      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
+      AllFieldsAreConst(true) {
+    switch (CSM) {
+      case Sema::CXXDefaultConstructor:
+      case Sema::CXXCopyConstructor:
+        IsConstructor =3D true;
+        break;
+      case Sema::CXXMoveConstructor:
+        IsConstructor =3D true;
+        IsMove =3D true;
+        break;
+      case Sema::CXXCopyAssignment:
+        IsAssignment =3D true;
+        break;
+      case Sema::CXXMoveAssignment:
+        IsAssignment =3D true;
+        IsMove =3D true;
+        break;
+      case Sema::CXXDestructor:
+        break;
+      case Sema::CXXInvalid:
+        llvm_unreachable("invalid special member kind");
+    }
+
+    if (MD->getNumParams()) {
+      ConstArg =3D MD->getParamDecl(0)->getType().isConstQualified();
+      VolatileArg =3D MD->getParamDecl(0)->getType().isVolatileQualified();
+    }
+  }
+
+  bool inUnion() const { return MD->getParent()->isUnion(); }
+
+  /// Look up the corresponding special member in the given class.
+  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
+    unsigned TQ =3D MD->getTypeQualifiers();
+    return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
+                                 MD->getRefQualifier() =3D=3D RQ_RValue,
+                                 TQ & Qualifiers::Const,
+                                 TQ & Qualifiers::Volatile);
+  }
+
+  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
+
+  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
+  bool shouldDeleteForField(FieldDecl *FD);
+  bool shouldDeleteForAllConstMembers();
+
+  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subob=
j);
+  bool shouldDeleteForSubobjectCall(Subobject Subobj,
+                                    Sema::SpecialMemberOverloadResult *SMO=
R,
+                                    bool IsDtorCallInCtor);
+
+  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
+};
+}
+
+/// Is the given special member inaccessible when used on the given
+/// sub-object.
+bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
+                                             CXXMethodDecl *target) {
+  /// If we're operating on a base class, the object type is the
+  /// type of this special member.
+  QualType objectTy;
+  AccessSpecifier access =3D target->getAccess();;
+  if (CXXBaseSpecifier *base =3D Subobj.dyn_cast<CXXBaseSpecifier*>()) {
+    objectTy =3D S.Context.getTypeDeclType(MD->getParent());
+    access =3D CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), acce=
ss);
+
+  // If we're operating on a field, the object type is the type of the fie=
ld.
+  } else {
+    objectTy =3D S.Context.getTypeDeclType(target->getParent());
+  }
+
+  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
+}
+
+/// Check whether we should delete a special member due to the implicit
+/// definition containing a call to a special member of a subobject.
+bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
+    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
+    bool IsDtorCallInCtor) {
+  CXXMethodDecl *Decl =3D SMOR->getMethod();
+  FieldDecl *Field =3D Subobj.dyn_cast<FieldDecl*>();
+
+  int DiagKind =3D -1;
+
+  if (SMOR->getKind() =3D=3D Sema::SpecialMemberOverloadResult::NoMemberOr=
Deleted)
+    DiagKind =3D !Decl ? 0 : 1;
+  else if (SMOR->getKind() =3D=3D Sema::SpecialMemberOverloadResult::Ambig=
uous)
+    DiagKind =3D 2;
+  else if (!isAccessible(Subobj, Decl))
+    DiagKind =3D 3;
+  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
+           !Decl->isTrivial()) {
+    // A member of a union must have a trivial corresponding special membe=
r.
+    // As a weird special case, a destructor call from a union's construct=
or
+    // must be accessible and non-deleted, but need not be trivial. Such a
+    // destructor is never actually called, but is semantically checked as
+    // if it were.
+    DiagKind =3D 4;
+  }
+
+  if (DiagKind =3D=3D -1)
+    return false;
+
+  if (Diagnose) {
+    if (Field) {
+      S.Diag(Field->getLocation(),
+             diag::note_deleted_special_member_class_subobject)
+        << CSM << MD->getParent() << /*IsField*/true
+        << Field << DiagKind << IsDtorCallInCtor;
+    } else {
+      CXXBaseSpecifier *Base =3D Subobj.get<CXXBaseSpecifier*>();
+      S.Diag(Base->getLocStart(),
+             diag::note_deleted_special_member_class_subobject)
+        << CSM << MD->getParent() << /*IsField*/false
+        << Base->getType() << DiagKind << IsDtorCallInCtor;
+    }
+
+    if (DiagKind =3D=3D 1)
+      S.NoteDeletedFunction(Decl);
+    // FIXME: Explain inaccessibility if DiagKind =3D=3D 3.
+  }
+
+  return true;
+}
+
+/// Check whether we should delete a special member function due to having=
 a
+/// direct or virtual base class or static data member of class type M.
+bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
+    CXXRecordDecl *Class, Subobject Subobj) {
+  FieldDecl *Field =3D Subobj.dyn_cast<FieldDecl*>();
+
+  // C++11 [class.ctor]p5:
+  // -- any direct or virtual base class, or non-static data member with no
+  //    brace-or-equal-initializer, has class type M (or array thereof) and
+  //    either M has no default constructor or overload resolution as appl=
ied
+  //    to M's default constructor results in an ambiguity or in a function
+  //    that is deleted or inaccessible
+  // C++11 [class.copy]p11, C++11 [class.copy]p23:
+  // -- a direct or virtual base class B that cannot be copied/moved becau=
se
+  //    overload resolution, as applied to B's corresponding special membe=
r,
+  //    results in an ambiguity or a function that is deleted or inaccessi=
ble
+  //    from the defaulted special member
+  // C++11 [class.dtor]p5:
+  // -- any direct or virtual base class [...] has a type with a destructor
+  //    that is deleted or inaccessible
+  if (!(CSM =3D=3D Sema::CXXDefaultConstructor &&
+        Field && Field->hasInClassInitializer()) &&
+      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
+    return true;
+
+  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
+  // -- any direct or virtual base class or non-static data member has a
+  //    type with a destructor that is deleted or inaccessible
+  if (IsConstructor) {
+    Sema::SpecialMemberOverloadResult *SMOR =3D
+        S.LookupSpecialMember(Class, Sema::CXXDestructor,
+                              false, false, false, false, false);
+    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
+      return true;
+  }
+
+  return false;
+}
+
+/// Check whether we should delete a special member function due to the cl=
ass
+/// having a particular direct or virtual base class.
+bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base=
) {
+  CXXRecordDecl *BaseClass =3D Base->getType()->getAsCXXRecordDecl();
+  return shouldDeleteForClassSubobject(BaseClass, Base);
+}
+
+/// Check whether we should delete a special member function due to the cl=
ass
+/// having a particular non-static data member.
+bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
+  QualType FieldType =3D S.Context.getBaseElementType(FD->getType());
+  CXXRecordDecl *FieldRecord =3D FieldType->getAsCXXRecordDecl();
+
+  if (CSM =3D=3D Sema::CXXDefaultConstructor) {
+    // For a default constructor, all references must be initialized in-cl=
ass
+    // and, if a union, it must have a non-const member.
+    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
+      if (Diagnose)
+        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_f=
ield)
+          << MD->getParent() << FD << FieldType << /*Reference*/0;
+      return true;
+    }
+    // C++11 [class.ctor]p5: any non-variant non-static data member of
+    // const-qualified type (or array thereof) with no
+    // brace-or-equal-initializer does not have a user-provided default
+    // constructor.
+    if (!inUnion() && FieldType.isConstQualified() &&
+        !FD->hasInClassInitializer() &&
+        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor()=
)) {
+      if (Diagnose)
+        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_f=
ield)
+          << MD->getParent() << FD << FieldType << /*Const*/1;
+      return true;
+    }
+
+    if (inUnion() && !FieldType.isConstQualified())
+      AllFieldsAreConst =3D false;
+  } else if (CSM =3D=3D Sema::CXXCopyConstructor) {
+    // For a copy constructor, data members must not be of rvalue reference
+    // type.
+    if (FieldType->isRValueReferenceType()) {
+      if (Diagnose)
+        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_refe=
rence)
+          << MD->getParent() << FD << FieldType;
+      return true;
+    }
+  } else if (IsAssignment) {
+    // For an assignment operator, data members must not be of reference t=
ype.
+    if (FieldType->isReferenceType()) {
+      if (Diagnose)
+        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
+          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/=
0;
+      return true;
+    }
+    if (!FieldRecord && FieldType.isConstQualified()) {
+      // C++11 [class.copy]p23:
+      // -- a non-static data member of const non-class type (or array the=
reof)
+      if (Diagnose)
+        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
+          << IsMove << MD->getParent() << FD << FieldType << /*Const*/1;
+      return true;
+    }
+  }
+
+  if (FieldRecord) {
+    // Some additional restrictions exist on the variant members.
+    if (!inUnion() && FieldRecord->isUnion() &&
+        FieldRecord->isAnonymousStructOrUnion()) {
+      bool AllVariantFieldsAreConst =3D true;
+
+      // FIXME: Handle anonymous unions declared within anonymous unions.
+      for (CXXRecordDecl::field_iterator UI =3D FieldRecord->field_begin(),
+                                         UE =3D FieldRecord->field_end();
+           UI !=3D UE; ++UI) {
+        QualType UnionFieldType =3D S.Context.getBaseElementType(UI->getTy=
pe());
+
+        if (!UnionFieldType.isConstQualified())
+          AllVariantFieldsAreConst =3D false;
+
+        CXXRecordDecl *UnionFieldRecord =3D UnionFieldType->getAsCXXRecord=
Decl();
+        if (UnionFieldRecord &&
+            shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
+          return true;
+      }
+
+      // At least one member in each anonymous union must be non-const
+      if (CSM =3D=3D Sema::CXXDefaultConstructor && AllVariantFieldsAreCon=
st &&
+          FieldRecord->field_begin() !=3D FieldRecord->field_end()) {
+        if (Diagnose)
+          S.Diag(FieldRecord->getLocation(),
+                 diag::note_deleted_default_ctor_all_const)
+            << MD->getParent() << /*anonymous union*/1;
+        return true;
+      }
+
+      // Don't check the implicit member of the anonymous union type.
+      // This is technically non-conformant, but sanity demands it.
+      return false;
+    }
+
+    if (shouldDeleteForClassSubobject(FieldRecord, FD))
+      return true;
+  }
+
+  return false;
+}
+
+/// C++11 [class.ctor] p5:
+///   A defaulted default constructor for a class X is defined as deleted =
if
+/// X is a union and all of its variant members are of const-qualified typ=
e.
+bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
+  // This is a silly definition, because it gives an empty union a deleted
+  // default constructor. Don't do that.
+  if (CSM =3D=3D Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreC=
onst &&
+      (MD->getParent()->field_begin() !=3D MD->getParent()->field_end())) {
+    if (Diagnose)
+      S.Diag(MD->getParent()->getLocation(),
+             diag::note_deleted_default_ctor_all_const)
+        << MD->getParent() << /*not anonymous union*/0;
+    return true;
+  }
+  return false;
+}
+
+/// Determine whether a defaulted special member function should be define=
d as
+/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
+/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
+bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember C=
SM,
+                                     bool Diagnose) {
   assert(!MD->isInvalidDecl());
   CXXRecordDecl *RD =3D MD->getParent();
   assert(!RD->isDependentType() && "do deletion after instantiation");
   if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
     return false;
=20
-  bool IsUnion =3D RD->isUnion();
-  bool IsConstructor =3D false;
-  bool IsAssignment =3D false;
-  bool IsMove =3D false;
- =20
-  bool ConstArg =3D false;
-
-  switch (CSM) {
-  case CXXDefaultConstructor:
-    IsConstructor =3D true;
-    break;
-  case CXXCopyConstructor:
-    IsConstructor =3D true;
-    ConstArg =3D MD->getParamDecl(0)->getType().isConstQualified();
-    break;
-  case CXXMoveConstructor:
-    IsConstructor =3D true;
-    IsMove =3D true;
-    break;
-  default:
-    llvm_unreachable("function only currently implemented for default ctor=
s");
-  }
-
-  SourceLocation Loc =3D MD->getLocation();
+  // C++11 [expr.lambda.prim]p19:
+  //   The closure type associated with a lambda-expression has a
+  //   deleted (8.4.3) default constructor and a deleted copy
+  //   assignment operator.
+  if (RD->isLambda() &&
+      (CSM =3D=3D CXXDefaultConstructor || CSM =3D=3D CXXCopyAssignment)) {
+    if (Diagnose)
+      Diag(RD->getLocation(), diag::note_lambda_decl);
+    return true;
+  }
+
+  // For an anonymous struct or union, the copy and assignment special mem=
bers
+  // will never be used, so skip the check. For an anonymous union declare=
d at
+  // namespace scope, the constructor and destructor are used.
+  if (CSM !=3D CXXDefaultConstructor && CSM !=3D CXXDestructor &&
+      RD->isAnonymousStructOrUnion())
+    return false;
+
+  // C++11 [class.copy]p7, p18:
+  //   If the class definition declares a move constructor or move assignm=
ent
+  //   operator, an implicitly declared copy constructor or copy assignment
+  //   operator is defined as deleted.
+  if (MD->isImplicit() &&
+      (CSM =3D=3D CXXCopyConstructor || CSM =3D=3D CXXCopyAssignment)) {
+    CXXMethodDecl *UserDeclaredMove =3D 0;
+
+    // In Microsoft mode, a user-declared move only causes the deletion of=
 the
+    // corresponding copy operation, not both copy operations.
+    if (RD->hasUserDeclaredMoveConstructor() &&
+        (!getLangOpts().MicrosoftMode || CSM =3D=3D CXXCopyConstructor)) {
+      if (!Diagnose) return true;
+      UserDeclaredMove =3D RD->getMoveConstructor();
+      assert(UserDeclaredMove);
+    } else if (RD->hasUserDeclaredMoveAssignment() &&
+               (!getLangOpts().MicrosoftMode || CSM =3D=3D CXXCopyAssignme=
nt)) {
+      if (!Diagnose) return true;
+      UserDeclaredMove =3D RD->getMoveAssignmentOperator();
+      assert(UserDeclaredMove);
+    }
+
+    if (UserDeclaredMove) {
+      Diag(UserDeclaredMove->getLocation(),
+           diag::note_deleted_copy_user_declared_move)
+        << (CSM =3D=3D CXXCopyAssignment) << RD
+        << UserDeclaredMove->isMoveAssignmentOperator();
+      return true;
+    }
+  }
=20
   // Do access control from the special member function
   ContextRAII MethodContext(*this, MD);
=20
-  bool AllConst =3D true;
-
-  // We do this because we should never actually use an anonymous
-  // union's constructor.
-  if (IsUnion && RD->isAnonymousStructOrUnion())
-    return false;
-
-  // FIXME: We should put some diagnostic logic right into this function.
-
-  for (CXXRecordDecl::base_class_iterator BI =3D RD->bases_begin(),
-                                          BE =3D RD->bases_end();
-       BI !=3D BE; ++BI) {
-    // We'll handle this one later
-    if (BI->isVirtual())
-      continue;
-
-    CXXRecordDecl *BaseDecl =3D BI->getType()->getAsCXXRecordDecl();
-    assert(BaseDecl && "base isn't a CXXRecordDecl");
-
-    // Unless we have an assignment operator, the base's destructor must
-    // be accessible and not deleted.
-    if (!IsAssignment) {
-      CXXDestructorDecl *BaseDtor =3D LookupDestructor(BaseDecl);
-      if (BaseDtor->isDeleted())
-        return true;
-      if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=3D
-          AR_accessible)
-        return true;
-    }
-
-    // Finding the corresponding member in the base should lead to a
-    // unique, accessible, non-deleted function. If we are doing
-    // a destructor, we have already checked this case.
-    if (CSM !=3D CXXDestructor) {
-      SpecialMemberOverloadResult *SMOR =3D
-        LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
-                            false);
-      if (!SMOR->hasSuccess())
-        return true;
-      CXXMethodDecl *BaseMember =3D SMOR->getMethod();
-      if (IsConstructor) {
-        CXXConstructorDecl *BaseCtor =3D cast<CXXConstructorDecl>(BaseMemb=
er);
-        if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
-                                   PDiag()) !=3D AR_accessible)
-          return true;
-
-        // For a move operation, the corresponding operation must actually
-        // be a move operation (and not a copy selected by overload
-        // resolution) unless we are working on a trivially copyable class.
-        if (IsMove && !BaseCtor->isMoveConstructor() &&
-            !BaseDecl->isTriviallyCopyable())
-          return true;
-      }
-    }
-  }
-
-  for (CXXRecordDecl::base_class_iterator BI =3D RD->vbases_begin(),
-                                          BE =3D RD->vbases_end();
-       BI !=3D BE; ++BI) {
-    CXXRecordDecl *BaseDecl =3D BI->getType()->getAsCXXRecordDecl();
-    assert(BaseDecl && "base isn't a CXXRecordDecl");
-
-    // Unless we have an assignment operator, the base's destructor must
-    // be accessible and not deleted.
-    if (!IsAssignment) {
-      CXXDestructorDecl *BaseDtor =3D LookupDestructor(BaseDecl);
-      if (BaseDtor->isDeleted())
-        return true;
-      if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=3D
-          AR_accessible)
-        return true;
-    }
-
-    // Finding the corresponding member in the base should lead to a
-    // unique, accessible, non-deleted function.
-    if (CSM !=3D CXXDestructor) {
-      SpecialMemberOverloadResult *SMOR =3D
-        LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
-                            false);
-      if (!SMOR->hasSuccess())
-        return true;
-      CXXMethodDecl *BaseMember =3D SMOR->getMethod();
-      if (IsConstructor) {
-        CXXConstructorDecl *BaseCtor =3D cast<CXXConstructorDecl>(BaseMemb=
er);
-        if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
-                                   PDiag()) !=3D AR_accessible)
-          return true;
-
-        // For a move operation, the corresponding operation must actually
-        // be a move operation (and not a copy selected by overload
-        // resolution) unless we are working on a trivially copyable class.
-        if (IsMove && !BaseCtor->isMoveConstructor() &&
-            !BaseDecl->isTriviallyCopyable())
-          return true;
-      }
-    }
-  }
-
-  for (CXXRecordDecl::field_iterator FI =3D RD->field_begin(),
-                                     FE =3D RD->field_end();
-       FI !=3D FE; ++FI) {
-    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
-      continue;
-   =20
-    QualType FieldType =3D Context.getBaseElementType(FI->getType());
-    CXXRecordDecl *FieldRecord =3D FieldType->getAsCXXRecordDecl();
-
-    // For a default constructor, all references must be initialized in-cl=
ass
-    // and, if a union, it must have a non-const member.
-    if (CSM =3D=3D CXXDefaultConstructor) {
-      if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
-        return true;
-
-      if (IsUnion && !FieldType.isConstQualified())
-        AllConst =3D false;
-    // For a copy constructor, data members must not be of rvalue reference
-    // type.
-    } else if (CSM =3D=3D CXXCopyConstructor) {
-      if (FieldType->isRValueReferenceType())
-        return true;
-    }
-
-    if (FieldRecord) {
-      // For a default constructor, a const member must have a user-provid=
ed
-      // default constructor or else be explicitly initialized.
-      if (CSM =3D=3D CXXDefaultConstructor && FieldType.isConstQualified()=
 &&
-          !FI->hasInClassInitializer() &&
-          !FieldRecord->hasUserProvidedDefaultConstructor())
-        return true;
-=20
-      // Some additional restrictions exist on the variant members.
-      if (!IsUnion && FieldRecord->isUnion() &&
-          FieldRecord->isAnonymousStructOrUnion()) {
-        // We're okay to reuse AllConst here since we only care about the
-        // value otherwise if we're in a union.
-        AllConst =3D true;
-
-        for (CXXRecordDecl::field_iterator UI =3D FieldRecord->field_begin=
(),
-                                           UE =3D FieldRecord->field_end();
-             UI !=3D UE; ++UI) {
-          QualType UnionFieldType =3D Context.getBaseElementType(UI->getTy=
pe());
-          CXXRecordDecl *UnionFieldRecord =3D
-            UnionFieldType->getAsCXXRecordDecl();
-
-          if (!UnionFieldType.isConstQualified())
-            AllConst =3D false;
-
-          if (UnionFieldRecord) {
-            // FIXME: Checking for accessibility and validity of this
-            //        destructor is technically going beyond the
-            //        standard, but this is believed to be a defect.
-            if (!IsAssignment) {
-              CXXDestructorDecl *FieldDtor =3D LookupDestructor(UnionField=
Record);
-              if (FieldDtor->isDeleted())
-                return true;
-              if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=3D
-                  AR_accessible)
-                return true;
-              if (!FieldDtor->isTrivial())
-                return true;
-            }
-
-            if (CSM !=3D CXXDestructor) {
-              SpecialMemberOverloadResult *SMOR =3D
-                LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
-                                    false, false, false);
-              // FIXME: Checking for accessibility and validity of this
-              //        corresponding member is technically going beyond t=
he
-              //        standard, but this is believed to be a defect.
-              if (!SMOR->hasSuccess())
-                return true;
-
-              CXXMethodDecl *FieldMember =3D SMOR->getMethod();
-              // A member of a union must have a trivial corresponding
-              // constructor.
-              if (!FieldMember->isTrivial())
-                return true;
-
-              if (IsConstructor) {
-                CXXConstructorDecl *FieldCtor =3D cast<CXXConstructorDecl>=
(FieldMember);
-                if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getA=
ccess(),
-                                           PDiag()) !=3D AR_accessible)
-                return true;
-              }
-            }
-          }
-        }
-
-        // At least one member in each anonymous union must be non-const
-        if (CSM =3D=3D CXXDefaultConstructor && AllConst)
-          return true;
-
-        // Don't try to initialize the anonymous union
-        // This is technically non-conformant, but sanity demands it.
-        continue;
-      }
-
-      // Unless we're doing assignment, the field's destructor must be
-      // accessible and not deleted.
-      if (!IsAssignment) {
-        CXXDestructorDecl *FieldDtor =3D LookupDestructor(FieldRecord);
-        if (FieldDtor->isDeleted())
-          return true;
-        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=3D
-            AR_accessible)
-          return true;
-      }
-
-      // Check that the corresponding member of the field is accessible,
-      // unique, and non-deleted. We don't do this if it has an explicit
-      // initialization when default-constructing.
-      if (CSM !=3D CXXDestructor &&
-          (CSM !=3D CXXDefaultConstructor || !FI->hasInClassInitializer())=
) {
-        SpecialMemberOverloadResult *SMOR =3D
-          LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, fa=
lse,
-                              false);
-        if (!SMOR->hasSuccess())
-          return true;
-
-        CXXMethodDecl *FieldMember =3D SMOR->getMethod();
-        if (IsConstructor) {
-          CXXConstructorDecl *FieldCtor =3D cast<CXXConstructorDecl>(Field=
Member);
-          if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(=
),
-                                     PDiag()) !=3D AR_accessible)
-          return true;
-
-          // For a move operation, the corresponding operation must actual=
ly
-          // be a move operation (and not a copy selected by overload
-          // resolution) unless we are working on a trivially copyable cla=
ss.
-          if (IsMove && !FieldCtor->isMoveConstructor() &&
-              !FieldRecord->isTriviallyCopyable())
-            return true;
-        }
-
-        // We need the corresponding member of a union to be trivial so th=
at
-        // we can safely copy them all simultaneously.
-        // FIXME: Note that performing the check here (where we rely on th=
e lack
-        // of an in-class initializer) is technically ill-formed. However,=
 this
-        // seems most obviously to be a bug in the standard.
-        if (IsUnion && !FieldMember->isTrivial())
-          return true;
-      }
-    } else if (CSM =3D=3D CXXDefaultConstructor && !IsUnion &&
-               FieldType.isConstQualified() && !FI->hasInClassInitializer(=
)) {
-      // We can't initialize a const member of non-class type to any value.
-      return true;
-    }
-  }
-
-  // We can't have all const members in a union when default-constructing,
-  // or else they're all nonsensical garbage values that can't be changed.
-  if (CSM =3D=3D CXXDefaultConstructor && IsUnion && AllConst)
-    return true;
-
-  return false;
-}
-
-bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
-  CXXRecordDecl *RD =3D MD->getParent();
-  assert(!RD->isDependentType() && "do deletion after instantiation");
-  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
-    return false;
-
-  SourceLocation Loc =3D MD->getLocation();
-
-  // Do access control from the constructor
-  ContextRAII MethodContext(*this, MD);
-
-  bool Union =3D RD->isUnion();
-
-  unsigned ArgQuals =3D
-    MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
-      Qualifiers::Const : 0;
-
-  // We do this because we should never actually use an anonymous
-  // union's constructor.
-  if (Union && RD->isAnonymousStructOrUnion())
-    return false;
-
-  // FIXME: We should put some diagnostic logic right into this function.
-
-  // C++0x [class.copy]/20
-  //    A defaulted [copy] assignment operator for class X is defined as d=
eleted
-  //    if X has:
-
-  for (CXXRecordDecl::base_class_iterator BI =3D RD->bases_begin(),
-                                          BE =3D RD->bases_end();
-       BI !=3D BE; ++BI) {
-    // We'll handle this one later
-    if (BI->isVirtual())
-      continue;
-
-    QualType BaseType =3D BI->getType();
-    CXXRecordDecl *BaseDecl =3D BaseType->getAsCXXRecordDecl();
-    assert(BaseDecl && "base isn't a CXXRecordDecl");
-
-    // -- a [direct base class] B that cannot be [copied] because overload
-    //    resolution, as applied to B's [copy] assignment operator, result=
s in
-    //    an ambiguity or a function that is deleted or inaccessible from =
the
-    //    assignment operator
-    CXXMethodDecl *CopyOper =3D LookupCopyingAssignment(BaseDecl, ArgQuals=
, false,
-                                                      0);
-    if (!CopyOper || CopyOper->isDeleted())
-      return true;
-    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) !=3D AR_accessible)
-      return true;
-  }
-
-  for (CXXRecordDecl::base_class_iterator BI =3D RD->vbases_begin(),
-                                          BE =3D RD->vbases_end();
-       BI !=3D BE; ++BI) {
-    QualType BaseType =3D BI->getType();
-    CXXRecordDecl *BaseDecl =3D BaseType->getAsCXXRecordDecl();
-    assert(BaseDecl && "base isn't a CXXRecordDecl");
-
-    // -- a [virtual base class] B that cannot be [copied] because overload
-    //    resolution, as applied to B's [copy] assignment operator, result=
s in
-    //    an ambiguity or a function that is deleted or inaccessible from =
the
-    //    assignment operator
-    CXXMethodDecl *CopyOper =3D LookupCopyingAssignment(BaseDecl, ArgQuals=
, false,
-                                                      0);
-    if (!CopyOper || CopyOper->isDeleted())
-      return true;
-    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) !=3D AR_accessible)
-      return true;
-  }
-
-  for (CXXRecordDecl::field_iterator FI =3D RD->field_begin(),
-                                     FE =3D RD->field_end();
-       FI !=3D FE; ++FI) {
-    if (FI->isUnnamedBitfield())
-      continue;
-   =20
-    QualType FieldType =3D Context.getBaseElementType(FI->getType());
-   =20
-    // -- a non-static data member of reference type
-    if (FieldType->isReferenceType())
-      return true;
-
-    // -- a non-static data member of const non-class type (or array there=
of)
-    if (FieldType.isConstQualified() && !FieldType->isRecordType())
-      return true;
-=20
-    CXXRecordDecl *FieldRecord =3D FieldType->getAsCXXRecordDecl();
-
-    if (FieldRecord) {
-      // This is an anonymous union
-      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion(=
)) {
-        // Anonymous unions inside unions do not variant members create
-        if (!Union) {
-          for (CXXRecordDecl::field_iterator UI =3D FieldRecord->field_beg=
in(),
-                                             UE =3D FieldRecord->field_end=
();
-               UI !=3D UE; ++UI) {
-            QualType UnionFieldType =3D Context.getBaseElementType(UI->get=
Type());
-            CXXRecordDecl *UnionFieldRecord =3D
-              UnionFieldType->getAsCXXRecordDecl();
-
-            // -- a variant member with a non-trivial [copy] assignment op=
erator
-            //    and X is a union-like class
-            if (UnionFieldRecord &&
-                !UnionFieldRecord->hasTrivialCopyAssignment())
-              return true;
-          }
-        }
-
-        // Don't try to initalize an anonymous union
-        continue;
-      // -- a variant member with a non-trivial [copy] assignment operator
-      //    and X is a union-like class
-      } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
-          return true;
-      }
-
-      CXXMethodDecl *CopyOper =3D LookupCopyingAssignment(FieldRecord, Arg=
Quals,
-                                                        false, 0);
-      if (!CopyOper || CopyOper->isDeleted())
-        return true;
-      if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) !=3D AR_accessib=
le)
-        return true;
-    }
-  }
-
-  return false;
-}
-
-bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
-  CXXRecordDecl *RD =3D MD->getParent();
-  assert(!RD->isDependentType() && "do deletion after instantiation");
-  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
-    return false;
-
-  SourceLocation Loc =3D MD->getLocation();
-
-  // Do access control from the constructor
-  ContextRAII MethodContext(*this, MD);
-
-  bool Union =3D RD->isUnion();
-
-  // We do this because we should never actually use an anonymous
-  // union's constructor.
-  if (Union && RD->isAnonymousStructOrUnion())
-    return false;
-
-  // C++0x [class.copy]/20
-  //    A defaulted [move] assignment operator for class X is defined as d=
eleted
-  //    if X has:
-
-  //    -- for the move constructor, [...] any direct or indirect virtual =
base
-  //       class.
-  if (RD->getNumVBases() !=3D 0)
-    return true;
-
-  for (CXXRecordDecl::base_class_iterator BI =3D RD->bases_begin(),
-                                          BE =3D RD->bases_end();
-       BI !=3D BE; ++BI) {
-
-    QualType BaseType =3D BI->getType();
-    CXXRecordDecl *BaseDecl =3D BaseType->getAsCXXRecordDecl();
-    assert(BaseDecl && "base isn't a CXXRecordDecl");
-
-    // -- a [direct base class] B that cannot be [moved] because overload
-    //    resolution, as applied to B's [move] assignment operator, result=
s in
-    //    an ambiguity or a function that is deleted or inaccessible from =
the
-    //    assignment operator
-    CXXMethodDecl *MoveOper =3D LookupMovingAssignment(BaseDecl, false, 0);
-    if (!MoveOper || MoveOper->isDeleted())
-      return true;
-    if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) !=3D AR_accessible)
-      return true;
-
-    // -- for the move assignment operator, a [direct base class] with a t=
ype
-    //    that does not have a move assignment operator and is not trivial=
ly
-    //    copyable.
-    if (!MoveOper->isMoveAssignmentOperator() &&
-        !BaseDecl->isTriviallyCopyable())
-      return true;
-  }
-
-  for (CXXRecordDecl::field_iterator FI =3D RD->field_begin(),
-                                     FE =3D RD->field_end();
-       FI !=3D FE; ++FI) {
-    if (FI->isUnnamedBitfield())
-      continue;
-       =20
-    QualType FieldType =3D Context.getBaseElementType(FI->getType());
-   =20
-    // -- a non-static data member of reference type
-    if (FieldType->isReferenceType())
-      return true;
-
-    // -- a non-static data member of const non-class type (or array there=
of)
-    if (FieldType.isConstQualified() && !FieldType->isRecordType())
-      return true;
-
-    CXXRecordDecl *FieldRecord =3D FieldType->getAsCXXRecordDecl();
-
-    if (FieldRecord) {
-      // This is an anonymous union
-      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion(=
)) {
-        // Anonymous unions inside unions do not variant members create
-        if (!Union) {
-          for (CXXRecordDecl::field_iterator UI =3D FieldRecord->field_beg=
in(),
-                                             UE =3D FieldRecord->field_end=
();
-               UI !=3D UE; ++UI) {
-            QualType UnionFieldType =3D Context.getBaseElementType(UI->get=
Type());
-            CXXRecordDecl *UnionFieldRecord =3D
-              UnionFieldType->getAsCXXRecordDecl();
-
-            // -- a variant member with a non-trivial [move] assignment op=
erator
-            //    and X is a union-like class
-            if (UnionFieldRecord &&
-                !UnionFieldRecord->hasTrivialMoveAssignment())
-              return true;
-          }
-        }
-
-        // Don't try to initalize an anonymous union
-        continue;
-      // -- a variant member with a non-trivial [move] assignment operator
-      //    and X is a union-like class
-      } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
-          return true;
-      }
-
-      CXXMethodDecl *MoveOper =3D LookupMovingAssignment(FieldRecord, fals=
e, 0);
-      if (!MoveOper || MoveOper->isDeleted())
-        return true;
-      if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) !=3D AR_accessib=
le)
-        return true;
-
-      // -- for the move assignment operator, a [non-static data member] w=
ith a
-      //    type that does not have a move assignment operator and is not
-      //    trivially copyable.
-      if (!MoveOper->isMoveAssignmentOperator() &&
-          !FieldRecord->isTriviallyCopyable())
-        return true;
-    }
-  }
-
-  return false;
-}
-
-bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
-  CXXRecordDecl *RD =3D DD->getParent();
-  assert(!RD->isDependentType() && "do deletion after instantiation");
-  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
-    return false;
-
-  SourceLocation Loc =3D DD->getLocation();
-
-  // Do access control from the destructor
-  ContextRAII CtorContext(*this, DD);
-
-  bool Union =3D RD->isUnion();
-
-  // We do this because we should never actually use an anonymous
-  // union's destructor.
-  if (Union && RD->isAnonymousStructOrUnion())
-    return false;
-
-  // C++0x [class.dtor]p5
-  //    A defaulted destructor for a class X is defined as deleted if:
-  for (CXXRecordDecl::base_class_iterator BI =3D RD->bases_begin(),
-                                          BE =3D RD->bases_end();
-       BI !=3D BE; ++BI) {
-    // We'll handle this one later
-    if (BI->isVirtual())
-      continue;
-
-    CXXRecordDecl *BaseDecl =3D BI->getType()->getAsCXXRecordDecl();
-    CXXDestructorDecl *BaseDtor =3D LookupDestructor(BaseDecl);
-    assert(BaseDtor && "base has no destructor");
-
-    // -- any direct or virtual base class has a deleted destructor or
-    //    a destructor that is inaccessible from the defaulted destructor
-    if (BaseDtor->isDeleted())
-      return true;
-    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=3D
-        AR_accessible)
-      return true;
-  }
-
-  for (CXXRecordDecl::base_class_iterator BI =3D RD->vbases_begin(),
-                                          BE =3D RD->vbases_end();
-       BI !=3D BE; ++BI) {
-    CXXRecordDecl *BaseDecl =3D BI->getType()->getAsCXXRecordDecl();
-    CXXDestructorDecl *BaseDtor =3D LookupDestructor(BaseDecl);
-    assert(BaseDtor && "base has no destructor");
-
-    // -- any direct or virtual base class has a deleted destructor or
-    //    a destructor that is inaccessible from the defaulted destructor
-    if (BaseDtor->isDeleted())
-      return true;
-    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=3D
-        AR_accessible)
-      return true;
-  }
-
-  for (CXXRecordDecl::field_iterator FI =3D RD->field_begin(),
-                                     FE =3D RD->field_end();
-       FI !=3D FE; ++FI) {
-    QualType FieldType =3D Context.getBaseElementType(FI->getType());
-    CXXRecordDecl *FieldRecord =3D FieldType->getAsCXXRecordDecl();
-    if (FieldRecord) {
-      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion(=
)) {
-         for (CXXRecordDecl::field_iterator UI =3D FieldRecord->field_begi=
n(),
-                                            UE =3D FieldRecord->field_end(=
);
-              UI !=3D UE; ++UI) {
-           QualType UnionFieldType =3D Context.getBaseElementType(FI->getT=
ype());
-           CXXRecordDecl *UnionFieldRecord =3D
-             UnionFieldType->getAsCXXRecordDecl();
-
-           // -- X is a union-like class that has a variant member with a =
non-
-           //    trivial destructor.
-           if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor=
())
-             return true;
-         }
-      // Technically we are supposed to do this next check unconditionally.
-      // But that makes absolutely no sense.
-      } else {
-        CXXDestructorDecl *FieldDtor =3D LookupDestructor(FieldRecord);
-
-        // -- any of the non-static data members has class type M (or array
-        //    thereof) and M has a deleted destructor or a destructor that=
 is
-        //    inaccessible from the defaulted destructor
-        if (FieldDtor->isDeleted())
-          return true;
-        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=3D
-          AR_accessible)
-        return true;
-       =20
-        // -- X is a union-like class that has a variant member with a non-
-        //    trivial destructor.
-        if (Union && !FieldDtor->isTrivial())
-          return true;
-      }
-    }
-  }
-
-  if (DD->isVirtual()) {
+  // C++11 [class.dtor]p5:
+  // -- for a virtual destructor, lookup of the non-array deallocation fun=
ction
+  //    results in an ambiguity or in a function that is deleted or inacce=
ssible
+  if (CSM =3D=3D CXXDestructor && MD->isVirtual()) {
     FunctionDecl *OperatorDelete =3D 0;
     DeclarationName Name =3D
       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
-    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
-          false))
+    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
+                                 OperatorDelete, false)) {
+      if (Diagnose)
+        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete=
);
       return true;
-  }
-
+    }
+  }
+
+  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
+
+  for (CXXRecordDecl::base_class_iterator BI =3D RD->bases_begin(),
+                                          BE =3D RD->bases_end(); BI !=3D =
BE; ++BI)
+    if (!BI->isVirtual() &&
+        SMI.shouldDeleteForBase(BI))
+      return true;
+
+  for (CXXRecordDecl::base_class_iterator BI =3D RD->vbases_begin(),
+                                          BE =3D RD->vbases_end(); BI !=3D=
 BE; ++BI)
+    if (SMI.shouldDeleteForBase(BI))
+      return true;
+
+  for (CXXRecordDecl::field_iterator FI =3D RD->field_begin(),
+                                     FE =3D RD->field_end(); FI !=3D FE; +=
+FI)
+    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
+        SMI.shouldDeleteForField(*FI))
+      return true;
+
+  if (SMI.shouldDeleteForAllConstMembers())
+    return true;
=20
   return false;
 }
@@ -4876,6 +4866,9 @@
   if (!ClassDecl->hasUserDeclaredCopyConstructor())
     ++ASTContext::NumImplicitCopyConstructors;
=20
+  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor=
())
+    ++ASTContext::NumImplicitMoveConstructors;
+
   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
     ++ASTContext::NumImplicitCopyAssignmentOperators;
    =20
@@ -4887,6 +4880,14 @@
       DeclareImplicitCopyAssignment(ClassDecl);
   }
=20
+  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment(=
)) {
+    ++ASTContext::NumImplicitMoveAssignmentOperators;
+
+    // Likewise for the move assignment operator.
+    if (ClassDecl->isDynamicClass())
+      DeclareImplicitMoveAssignment(ClassDecl);
+  }
+
   if (!ClassDecl->hasUserDeclaredDestructor()) {
     ++ASTContext::NumImplicitDestructors;
    =20
@@ -5139,7 +5140,7 @@
     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
       return true;
=20
-    MarkDeclarationReferenced(Loc, OperatorDelete);
+    MarkFunctionReferenced(Loc, OperatorDelete);
    =20
     Destructor->setOperatorDelete(OperatorDelete);
   }
@@ -5342,9 +5343,11 @@
     R =3D Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()=
);
=20
   // C++0x explicit conversion operators.
-  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus=
0x)
+  if (D.getDeclSpec().isExplicitSpecified())
     Diag(D.getDeclSpec().getExplicitSpecLoc(),
-         diag::warn_explicit_conversion_functions)
+         getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_explicit_conversion_functions :
+           diag::ext_explicit_conversion_functions)
       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
 }
=20
@@ -5413,17 +5416,13 @@
   SourceLocation StartLoc =3D InlineLoc.isValid() ? InlineLoc : NamespaceL=
oc;
   // For anonymous namespace, take the location of the left brace.
   SourceLocation Loc =3D II ? IdentLoc : LBrace;
-  NamespaceDecl *Namespc =3D NamespaceDecl::Create(Context, CurContext,
-                                                 StartLoc, Loc, II);
-  Namespc->setInline(InlineLoc.isValid());
-
+  bool IsInline =3D InlineLoc.isValid();
+  bool IsInvalid =3D false;
+  bool IsStd =3D false;
+  bool AddToKnown =3D false;
   Scope *DeclRegionScope =3D NamespcScope->getParent();
=20
-  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
-
-  if (const VisibilityAttr *Attr =3D Namespc->getAttr<VisibilityAttr>())
-    PushNamespaceVisibilityAttr(Attr);
-
+  NamespaceDecl *PrevNS =3D 0;
   if (II) {
     // C++ [namespace.def]p2:
     //   The identifier in an original-namespace-definition shall not
@@ -5437,11 +5436,11 @@
     // look through using directives, just look for any ordinary names.
    =20
     const unsigned IDNS =3D Decl::IDNS_Ordinary | Decl::IDNS_Member |=20
-      Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |=20
-      Decl::IDNS_Namespace;
+    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |=20
+    Decl::IDNS_Namespace;
     NamedDecl *PrevDecl =3D 0;
     for (DeclContext::lookup_result R=20
-            =3D CurContext->getRedeclContext()->lookup(II);
+         =3D CurContext->getRedeclContext()->lookup(II);
          R.first !=3D R.second; ++R.first) {
       if ((*R.first)->getIdentifierNamespace() & IDNS) {
         PrevDecl =3D *R.first;
@@ -5449,100 +5448,91 @@
       }
     }
    =20
-    if (NamespaceDecl *OrigNS =3D dyn_cast_or_null<NamespaceDecl>(PrevDecl=
)) {
+    PrevNS =3D dyn_cast_or_null<NamespaceDecl>(PrevDecl);
+   =20
+    if (PrevNS) {
       // This is an extended namespace definition.
-      if (Namespc->isInline() !=3D OrigNS->isInline()) {
+      if (IsInline !=3D PrevNS->isInline()) {
         // inline-ness must match
-        if (OrigNS->isInline()) {
+        if (PrevNS->isInline()) {
           // The user probably just forgot the 'inline', so suggest that it
           // be added back.
-          Diag(Namespc->getLocation(),=20
-               diag::warn_inline_namespace_reopened_noninline)
+          Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
             << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
         } else {
-          Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
-            << Namespc->isInline();
+          Diag(Loc, diag::err_inline_namespace_mismatch)
+            << IsInline;
         }
-        Diag(OrigNS->getLocation(), diag::note_previous_definition);
-
-        // Recover by ignoring the new namespace's inline status.
-        Namespc->setInline(OrigNS->isInline());
-      }
-
-      // Attach this namespace decl to the chain of extended namespace
-      // definitions.
-      OrigNS->setNextNamespace(Namespc);
-      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
-
-      // Remove the previous declaration from the scope.
-      if (DeclRegionScope->isDeclScope(OrigNS)) {
-        IdResolver.RemoveDecl(OrigNS);
-        DeclRegionScope->RemoveDecl(OrigNS);
-      }
+        Diag(PrevNS->getLocation(), diag::note_previous_definition);
+       =20
+        IsInline =3D PrevNS->isInline();
+      }     =20
     } else if (PrevDecl) {
       // This is an invalid name redefinition.
-      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
-       << Namespc->getDeclName();
+      Diag(Loc, diag::err_redefinition_different_kind)
+        << II;
       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
-      Namespc->setInvalidDecl();
+      IsInvalid =3D true;
       // Continue on to push Namespc as current DeclContext and return it.
-    } else if (II->isStr("std") &&=20
+    } else if (II->isStr("std") &&
                CurContext->getRedeclContext()->isTranslationUnit()) {
       // This is the first "real" definition of the namespace "std", so up=
date
       // our cache of the "std" namespace to point at this definition.
-      if (NamespaceDecl *StdNS =3D getStdNamespace()) {
-        // We had already defined a dummy namespace "std". Link this new=20
-        // namespace definition to the dummy namespace "std".
-        StdNS->setNextNamespace(Namespc);
-        StdNS->setLocation(IdentLoc);
-        Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
-      }
+      PrevNS =3D getStdNamespace();
+      IsStd =3D true;
+      AddToKnown =3D !IsInline;
+    } else {
+      // We've seen this namespace for the first time.
+      AddToKnown =3D !IsInline;
+    }
+  } else {
+    // Anonymous namespaces.
+   =20
+    // Determine whether the parent already has an anonymous namespace.
+    DeclContext *Parent =3D CurContext->getRedeclContext();
+    if (TranslationUnitDecl *TU =3D dyn_cast<TranslationUnitDecl>(Parent))=
 {
+      PrevNS =3D TU->getAnonymousNamespace();
+    } else {
+      NamespaceDecl *ND =3D cast<NamespaceDecl>(Parent);
+      PrevNS =3D ND->getAnonymousNamespace();
+    }
+
+    if (PrevNS && IsInline !=3D PrevNS->isInline()) {
+      // inline-ness must match
+      Diag(Loc, diag::err_inline_namespace_mismatch)
+        << IsInline;
+      Diag(PrevNS->getLocation(), diag::note_previous_definition);
      =20
-      // Make our StdNamespace cache point at the first real definition of=
 the
-      // "std" namespace.
-      StdNamespace =3D Namespc;
-
-      // Add this instance of "std" to the set of known namespaces
-      KnownNamespaces[Namespc] =3D false;
-    } else if (!Namespc->isInline()) {
-      // Since this is an "original" namespace, add it to the known set of
-      // namespaces if it is not an inline namespace.
-      KnownNamespaces[Namespc] =3D false;
-    }
-
+      // Recover by ignoring the new namespace's inline status.
+      IsInline =3D PrevNS->isInline();
+    }
+  }
+ =20
+  NamespaceDecl *Namespc =3D NamespaceDecl::Create(Context, CurContext, Is=
Inline,
+                                                 StartLoc, Loc, II, PrevNS=
);
+  if (IsInvalid)
+    Namespc->setInvalidDecl();
+ =20
+  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
+
+  // FIXME: Should we be merging attributes?
+  if (const VisibilityAttr *Attr =3D Namespc->getAttr<VisibilityAttr>())
+    PushNamespaceVisibilityAttr(Attr, Loc);
+
+  if (IsStd)
+    StdNamespace =3D Namespc;
+  if (AddToKnown)
+    KnownNamespaces[Namespc] =3D false;
+ =20
+  if (II) {
     PushOnScopeChains(Namespc, DeclRegionScope);
   } else {
-    // Anonymous namespaces.
-    assert(Namespc->isAnonymousNamespace());
-
     // Link the anonymous namespace into its parent.
-    NamespaceDecl *PrevDecl;
     DeclContext *Parent =3D CurContext->getRedeclContext();
     if (TranslationUnitDecl *TU =3D dyn_cast<TranslationUnitDecl>(Parent))=
 {
-      PrevDecl =3D TU->getAnonymousNamespace();
       TU->setAnonymousNamespace(Namespc);
     } else {
-      NamespaceDecl *ND =3D cast<NamespaceDecl>(Parent);
-      PrevDecl =3D ND->getAnonymousNamespace();
-      ND->setAnonymousNamespace(Namespc);
-    }
-
-    // Link the anonymous namespace with its previous declaration.
-    if (PrevDecl) {
-      assert(PrevDecl->isAnonymousNamespace());
-      assert(!PrevDecl->getNextNamespace());
-      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
-      PrevDecl->setNextNamespace(Namespc);
-
-      if (Namespc->isInline() !=3D PrevDecl->isInline()) {
-        // inline-ness must match
-        Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
-          << Namespc->isInline();
-        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
-        Namespc->setInvalidDecl();
-        // Recover by ignoring the new namespace's inline status.
-        Namespc->setInline(PrevDecl->isInline());
-      }
+      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
     }
=20
     CurContext->addDecl(Namespc);
@@ -5563,7 +5553,7 @@
     // declarations semantically contained within an anonymous
     // namespace internal linkage.
=20
-    if (!PrevDecl) {
+    if (!PrevNS) {
       UsingDirectiveDecl* UD
         =3D UsingDirectiveDecl::Create(Context, CurContext,
                                      /* 'using' */ LBrace,
@@ -5602,7 +5592,7 @@
   Namespc->setRBraceLoc(RBrace);
   PopDeclContext();
   if (Namespc->hasAttr<VisibilityAttr>())
-    PopPragmaVisibility();
+    PopPragmaVisibility(true, RBrace);
 }
=20
 CXXRecordDecl *Sema::getStdBadAlloc() const {
@@ -5622,14 +5612,142 @@
     // The "std" namespace has not yet been defined, so build one implicit=
ly.
     StdNamespace =3D NamespaceDecl::Create(Context,=20
                                          Context.getTranslationUnitDecl(),
+                                         /*Inline=3D*/false,
                                          SourceLocation(), SourceLocation(=
),
-                                         &PP.getIdentifierTable().get("std=
"));
+                                         &PP.getIdentifierTable().get("std=
"),
+                                         /*PrevDecl=3D*/0);
     getStdNamespace()->setImplicit(true);
   }
  =20
   return getStdNamespace();
 }
=20
+bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
+  assert(getLangOpts().CPlusPlus &&
+         "Looking for std::initializer_list outside of C++.");
+
+  // We're looking for implicit instantiations of
+  // template <typename E> class std::initializer_list.
+
+  if (!StdNamespace) // If we haven't seen namespace std yet, this can't b=
e it.
+    return false;
+
+  ClassTemplateDecl *Template =3D 0;
+  const TemplateArgument *Arguments =3D 0;
+
+  if (const RecordType *RT =3D Ty->getAs<RecordType>()) {
+
+    ClassTemplateSpecializationDecl *Specialization =3D
+        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
+    if (!Specialization)
+      return false;
+
+    Template =3D Specialization->getSpecializedTemplate();
+    Arguments =3D Specialization->getTemplateArgs().data();
+  } else if (const TemplateSpecializationType *TST =3D
+                 Ty->getAs<TemplateSpecializationType>()) {
+    Template =3D dyn_cast_or_null<ClassTemplateDecl>(
+        TST->getTemplateName().getAsTemplateDecl());
+    Arguments =3D TST->getArgs();
+  }
+  if (!Template)
+    return false;
+
+  if (!StdInitializerList) {
+    // Haven't recognized std::initializer_list yet, maybe this is it.
+    CXXRecordDecl *TemplateClass =3D Template->getTemplatedDecl();
+    if (TemplateClass->getIdentifier() !=3D
+            &PP.getIdentifierTable().get("initializer_list") ||
+        !getStdNamespace()->InEnclosingNamespaceSetOf(
+            TemplateClass->getDeclContext()))
+      return false;
+    // This is a template called std::initializer_list, but is it the right
+    // template?
+    TemplateParameterList *Params =3D Template->getTemplateParameters();
+    if (Params->getMinRequiredArguments() !=3D 1)
+      return false;
+    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
+      return false;
+
+    // It's the right template.
+    StdInitializerList =3D Template;
+  }
+
+  if (Template !=3D StdInitializerList)
+    return false;
+
+  // This is an instance of std::initializer_list. Find the argument type.
+  if (Element)
+    *Element =3D Arguments[0].getAsType();
+  return true;
+}
+
+static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation=
 Loc){
+  NamespaceDecl *Std =3D S.getStdNamespace();
+  if (!Std) {
+    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
+    return 0;
+  }
+
+  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"=
),
+                      Loc, Sema::LookupOrdinaryName);
+  if (!S.LookupQualifiedName(Result, Std)) {
+    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
+    return 0;
+  }
+  ClassTemplateDecl *Template =3D Result.getAsSingle<ClassTemplateDecl>();
+  if (!Template) {
+    Result.suppressDiagnostics();
+    // We found something weird. Complain about the first thing we found.
+    NamedDecl *Found =3D *Result.begin();
+    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
+    return 0;
+  }
+
+  // We found some template called std::initializer_list. Now verify that =
it's
+  // correct.
+  TemplateParameterList *Params =3D Template->getTemplateParameters();
+  if (Params->getMinRequiredArguments() !=3D 1 ||
+      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
+    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_li=
st);
+    return 0;
+  }
+
+  return Template;
+}
+
+QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Lo=
c) {
+  if (!StdInitializerList) {
+    StdInitializerList =3D LookupStdInitializerList(*this, Loc);
+    if (!StdInitializerList)
+      return QualType();
+  }
+
+  TemplateArgumentListInfo Args(Loc, Loc);
+  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
+                                       Context.getTrivialTypeSourceInfo(El=
ement,
+                                                                        Lo=
c)));
+  return Context.getCanonicalType(
+      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
+}
+
+bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
+  // C++ [dcl.init.list]p2:
+  //   A constructor is an initializer-list constructor if its first param=
eter
+  //   is of type std::initializer_list<E> or reference to possibly cv-qua=
lified
+  //   std::initializer_list<E> for some type E, and either there are no o=
ther
+  //   parameters or else all other parameters have default arguments.
+  if (Ctor->getNumParams() < 1 ||
+      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()=
))
+    return false;
+
+  QualType ArgType =3D Ctor->getParamDecl(0)->getType();
+  if (const ReferenceType *RT =3D ArgType->getAs<ReferenceType>())
+    ArgType =3D RT->getPointeeType().getUnqualifiedType();
+
+  return isStdInitializerList(ArgType, 0);
+}
+
 /// \brief Determine whether a using statement is in a context where it wi=
ll be
 /// apply in all contexts.
 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
@@ -5643,35 +5761,46 @@
   }
 }
=20
+namespace {
+
+// Callback to only accept typo corrections that are namespaces.
+class NamespaceValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    if (NamedDecl *ND =3D candidate.getCorrectionDecl()) {
+      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
+    }
+    return false;
+  }
+};
+
+}
+
 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
                                        CXXScopeSpec &SS,
                                        SourceLocation IdentLoc,
                                        IdentifierInfo *Ident) {
+  NamespaceValidatorCCC Validator;
   R.clear();
   if (TypoCorrection Corrected =3D S.CorrectTypo(R.getLookupNameInfo(),
-                                               R.getLookupKind(), Sc, &SS,=
 NULL,
-                                               false, S.CTC_NoKeywords, NU=
LL)) {
-    if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
-        Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
-      std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
-      std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions(=
)));
-      if (DeclContext *DC =3D S.computeDeclContext(SS, false))
-        S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
-          << Ident << DC << CorrectedQuotedStr << SS.getRange()
-          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
-      else
-        S.Diag(IdentLoc, diag::err_using_directive_suggest)
-          << Ident << CorrectedQuotedStr
-          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
-
-      S.Diag(Corrected.getCorrectionDecl()->getLocation(),
-           diag::note_namespace_defined_here) << CorrectedQuotedStr;
-
-      Ident =3D Corrected.getCorrectionAsIdentifierInfo();
-      R.addDecl(Corrected.getCorrectionDecl());
-      return true;
-    }
-    R.setLookupName(Ident);
+                                               R.getLookupKind(), Sc, &SS,
+                                               Validator)) {
+    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
+    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
+    if (DeclContext *DC =3D S.computeDeclContext(SS, false))
+      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
+        << Ident << DC << CorrectedQuotedStr << SS.getRange()
+        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
+    else
+      S.Diag(IdentLoc, diag::err_using_directive_suggest)
+        << Ident << CorrectedQuotedStr
+        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
+
+    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
+         diag::note_namespace_defined_here) << CorrectedQuotedStr;
+
+    R.addDecl(Corrected.getCorrectionDecl());
+    return true;
   }
   return false;
 }
@@ -5757,14 +5886,15 @@
 }
=20
 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
-  // If scope has associated entity, then using directive is at namespace
-  // or translation unit scope. We add UsingDirectiveDecls, into
-  // it's lookup structure.
-  if (DeclContext *Ctx =3D static_cast<DeclContext*>(S->getEntity()))
+  // If the scope has an associated entity and the using directive is at
+  // namespace or translation unit scope, add the UsingDirectiveDecl into
+  // its lookup structure so qualified name lookup can find it.
+  DeclContext *Ctx =3D static_cast<DeclContext*>(S->getEntity());
+  if (Ctx && !Ctx->isFunctionOrMethod())
     Ctx->addDecl(UDir);
   else
-    // Otherwise it is block-sope. using-directives will affect lookup
-    // only to the end of scope.
+    // Otherwise, it is at block sope. The using-directives will affect lo=
okup
+    // only to the end of the scope.
     S->PushUsingDirective(UDir);
 }
=20
@@ -5791,19 +5921,23 @@
   case UnqualifiedId::IK_ConstructorName:
   case UnqualifiedId::IK_ConstructorTemplateId:
     // C++0x inherited constructors.
-    if (getLangOptions().CPlusPlus0x) break;
-
-    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructo=
r)
+    Diag(Name.getLocStart(),
+         getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_using_decl_constructor :
+           diag::err_using_decl_constructor)
       << SS.getRange();
+
+    if (getLangOpts().CPlusPlus0x) break;
+
     return 0;
      =20
   case UnqualifiedId::IK_DestructorName:
-    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
+    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
       << SS.getRange();
     return 0;
      =20
   case UnqualifiedId::IK_TemplateId:
-    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_i=
d)
+    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLo=
c);
     return 0;
   }
@@ -5818,7 +5952,7 @@
   // talk about access decls instead of using decls in the
   // diagnostics.
   if (!HasUsingKeyword) {
-    UsingLoc =3D Name.getSourceRange().getBegin();
+    UsingLoc =3D Name.getLocStart();
    =20
     Diag(UsingLoc, diag::warn_access_decl_deprecated)
       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
@@ -5883,7 +6017,7 @@
   // specialization.  The UsingShadowDecl in D<T> then points directly
   // to A::foo, which will look well-formed when we instantiate.
   // The right solution is to not collapse the shadow-decl chain.
-  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
+  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
     DeclContext *OrigDC =3D Orig->getDeclContext();
=20
     // Handle enums and anonymous structs.
@@ -6148,9 +6282,9 @@
     return UD;
   }
=20
-  // Constructor inheriting using decls get special treatment.
+  // The normal rules do not apply to inheriting constructor declarations.
   if (NameInfo.getName().getNameKind() =3D=3D DeclarationName::CXXConstruc=
torName) {
-    if (CheckInheritedConstructorUsingDecl(UD))
+    if (CheckInheritingConstructorUsingDecl(UD))
       UD->setInvalidDecl();
     return UD;
   }
@@ -6166,6 +6300,13 @@
   if (!IsInstantiation)
     R.setHideTags(false);
=20
+  // For the purposes of this lookup, we have a base object type
+  // equal to that of the current context.
+  if (CurContext->isRecord()) {
+    R.setBaseObjectType(
+                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)=
));
+  }
+
   LookupQualifiedName(R, LookupContext);
=20
   if (R.empty()) {
@@ -6220,11 +6361,8 @@
 }
=20
 /// Additional checks for a using declaration referring to a constructor n=
ame.
-bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
-  if (UD->isTypeName()) {
-    // FIXME: Cannot specify typename when specifying constructor
-    return true;
-  }
+bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
+  assert(!UD->isTypeName() && "expecting a constructor name");
=20
   const Type *SourceType =3D UD->getQualifier()->getAsType();
   assert(SourceType &&
@@ -6239,6 +6377,8 @@
     CanQualType BaseType =3D BaseIt->getType()->getCanonicalTypeUnqualifie=
d();
     if (CanonicalSourceType =3D=3D BaseType)
       break;
+    if (BaseIt->getType()->isDependentType())
+      break;
   }
=20
   if (BaseIt =3D=3D BaseE) {
@@ -6250,7 +6390,8 @@
     return true;
   }
=20
-  BaseIt->setInheritConstructors();
+  if (!CurContext->isDependentContext())
+    BaseIt->setInheritConstructors();
=20
   return false;
 }
@@ -6365,7 +6506,7 @@
       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedConte=
xt))
     return true;
=20
-  if (getLangOptions().CPlusPlus0x) {
+  if (getLangOpts().CPlusPlus0x) {
     // C++0x [namespace.udecl]p3:
     //   In a using-declaration used as a member-declaration, the
     //   nested-name-specifier shall name a base class of the class
@@ -6405,7 +6546,7 @@
   // need to be repeated.
=20
   struct UserData {
-    llvm::DenseSet<const CXXRecordDecl*> Bases;
+    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
=20
     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
       UserData *Data =3D reinterpret_cast<UserData*>(OpaqueData);
@@ -6485,9 +6626,7 @@
   // Warn about shadowing the name of a template parameter.
   if (Previous.isSingleResult() &&
       Previous.getFoundDecl()->isTemplateParameter()) {
-    if (DiagnoseTemplateParameterShadow(Name.StartLocation,
-                                        Previous.getFoundDecl()))
-      Invalid =3D true;
+    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDe=
cl());
     Previous.clear();
   }
=20
@@ -6633,7 +6772,7 @@
=20
   if (R.empty()) {
     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
-      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange=
();
+      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
       return 0;
     }
   }
@@ -6664,7 +6803,7 @@
    =20
     ~ImplicitlyDefinedFunctionScope() {
       S.PopExpressionEvaluationContext();
-      S.PopFunctionOrBlockScope();
+      S.PopFunctionScopeInfo();
     }
   };
 }
@@ -6757,16 +6896,12 @@
   DeclarationName Name
     =3D Context.DeclarationNames.getCXXConstructorName(ClassType);
   DeclarationNameInfo NameInfo(Name, ClassLoc);
-  CXXConstructorDecl *DefaultCon
-    =3D CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
-                                 Context.getFunctionType(Context.VoidTy,
-                                                         0, 0, EPI),
-                                 /*TInfo=3D*/0,
-                                 /*isExplicit=3D*/false,
-                                 /*isInline=3D*/true,
-                                 /*isImplicitlyDeclared=3D*/true,
-                                 // FIXME: apply the rules for definitions=
 here
-                                 /*isConstexpr=3D*/false);
+  CXXConstructorDecl *DefaultCon =3D CXXConstructorDecl::Create(
+      Context, ClassDecl, ClassLoc, NameInfo,
+      Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=3D*/0,
+      /*isExplicit=3D*/false, /*isInline=3D*/true, /*isImplicitlyDeclared=
=3D*/true,
+      /*isConstexpr=3D*/ClassDecl->defaultedDefaultConstructorIsConstexpr(=
) &&
+        getLangOpts().CPlusPlus0x);
   DefaultCon->setAccess(AS_public);
   DefaultCon->setDefaulted();
   DefaultCon->setImplicit();
@@ -6905,7 +7040,6 @@
         Context.getCanonicalType(CtorIt->getType()).getTypePtr());
   }
=20
-  Scope *S =3D getScopeForContext(ClassDecl);
   DeclarationName CreatedCtorName =3D
       Context.DeclarationNames.getCXXConstructorName(
           ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
@@ -6927,10 +7061,12 @@
                                       CtorE =3D BaseDecl->ctor_end();
          CtorIt !=3D CtorE; ++CtorIt) {
       // Find the using declaration for inheriting this base's constructor=
s.
+      // FIXME: Don't perform name lookup just to obtain a source location!
       DeclarationName Name =3D
           Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
-      UsingDecl *UD =3D dyn_cast_or_null<UsingDecl>(
-          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
+      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclNa=
me);
+      LookupQualifiedName(Result, CurContext);
+      UsingDecl *UD =3D Result.getAsSingle<UsingDecl>();
       SourceLocation UsingLoc =3D UD ? UD->getLocation() :
                                      ClassDecl->getLocation();
=20
@@ -7041,7 +7177,6 @@
         NewCtor->setParams(ParamDecls);
         NewCtor->setInheritedConstructor(BaseCtor);
=20
-        PushOnScopeChains(NewCtor, S, false);
         ClassDecl->addDecl(NewCtor);
         result.first->second.second =3D NewCtor;
       }
@@ -7131,18 +7266,19 @@
   // This could be uniqued if it ever proves significant.
   Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
=20
-  if (ShouldDeleteDestructor(Destructor))
+  AddOverriddenMethods(ClassDecl, Destructor);
+
+  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
     Destructor->setDeletedAsWritten();
- =20
-  AddOverriddenMethods(ClassDecl, Destructor);
- =20
+
   return Destructor;
 }
=20
 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
                                     CXXDestructorDecl *Destructor) {
   assert((Destructor->isDefaulted() &&
-          !Destructor->doesThisDeclarationHaveABody()) &&
+          !Destructor->doesThisDeclarationHaveABody() &&
+          !Destructor->isDeleted()) &&
          "DefineImplicitDestructor - call it for implicit default dtor");
   CXXRecordDecl *ClassDecl =3D Destructor->getParent();
   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
@@ -7259,8 +7395,8 @@
     while (F.hasNext()) {
       NamedDecl *D =3D F.next();
       if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(D))
-        if (Copying ? Method->isCopyAssignmentOperator() :
-                      Method->isMoveAssignmentOperator())
+        if (Method->isCopyAssignmentOperator() ||
+            (!Copying && Method->isMoveAssignmentOperator()))
           continue;
=20
       F.erase();
@@ -7290,15 +7426,18 @@
     // reference to operator=3D; this is required to suppress the virtual
     // call mechanism.
     CXXScopeSpec SS;
+    const Type *CanonicalT =3D S.Context.getCanonicalType(T.getTypePtr());
     SS.MakeTrivial(S.Context,=20
                    NestedNameSpecifier::Create(S.Context, 0, false,=20
-                                               T.getTypePtr()),
+                                               CanonicalT),
                    Loc);
    =20
     // Create the reference to operator=3D.
     ExprResult OpEqualRef
       =3D S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=3D*/false, SS,=20
-                                   /*FirstQualifierInScope=3D*/0, OpLookup=
,=20
+                                   /*TemplateKWLoc=3D*/SourceLocation(),
+                                   /*FirstQualifierInScope=3D*/0,
+                                   OpLookup,
                                    /*TemplateArgs=3D*/0,
                                    /*SuppressQualifierCheck=3D*/true);
     if (OpEqualRef.isInvalid())
@@ -7339,7 +7478,7 @@
   // Create the iteration variable.
   IdentifierInfo *IterationVarName =3D 0;
   {
-    llvm::SmallString<8> Str;
+    SmallString<8> Str;
     llvm::raw_svector_ostream OS(Str);
     OS << "__i" << Depth;
     IterationVarName =3D &S.Context.Idents.get(OS.str());
@@ -7356,9 +7495,11 @@
   // Create a reference to the iteration variable; we'll use this several
   // times throughout.
   Expr *IterationVarRef
-    =3D S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
+    =3D S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
   assert(IterationVarRef && "Reference to invented variable cannot fail!");
- =20
+  Expr *IterationVarRefRVal =3D S.DefaultLvalueConversion(IterationVarRef)=
.take();
+  assert(IterationVarRefRVal && "Conversion of invented variable cannot fa=
il!");
+
   // Create the DeclStmt that holds the iteration variable.
   Stmt *InitStmt =3D new (S.Context) DeclStmt(DeclGroupRef(IterationVar),L=
oc,Loc);
  =20
@@ -7366,7 +7507,7 @@
   llvm::APInt Upper
     =3D ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
   Expr *Comparison
-    =3D new (S.Context) BinaryOperator(IterationVarRef,
+    =3D new (S.Context) BinaryOperator(IterationVarRefRVal,
                      IntegerLiteral::Create(S.Context, Upper, SizeType, Lo=
c),
                                      BO_NE, S.Context.BoolTy,
                                      VK_RValue, OK_Ordinary, Loc);
@@ -7378,9 +7519,11 @@
  =20
   // Subscript the "from" and "to" expressions with the iteration variable.
   From =3D AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
-                                                         IterationVarRef, =
Loc));
+                                                         IterationVarRefRV=
al,
+                                                         Loc));
   To =3D AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
-                                                       IterationVarRef, Lo=
c));
+                                                       IterationVarRefRVal,
+                                                       Loc));
   if (!Copying) // Cast to rvalue
     From =3D CastForMoving(S, From);
=20
@@ -7432,7 +7575,7 @@
                             &HasConstCopyAssignment);
   }
=20
-  // In C++0x, the above citation has "or virtual added"
+  // In C++11, the above citation has "or virtual" added
   if (LangOpts.CPlusPlus0x) {
     for (CXXRecordDecl::base_class_iterator Base =3D ClassDecl->vbases_beg=
in(),
                                          BaseEnd =3D ClassDecl->vbases_end=
();
@@ -7565,15 +7708,14 @@
     PushOnScopeChains(CopyAssignment, S, false);
   ClassDecl->addDecl(CopyAssignment);
  =20
-  // C++0x [class.copy]p18:
-  //   ... If the class definition declares a move constructor or move
-  //   assignment operator, the implicitly declared copy assignment operat=
or is
-  //   defined as deleted; ...
-  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
-      ClassDecl->hasUserDeclaredMoveAssignment() ||
-      ShouldDeleteCopyAssignmentOperator(CopyAssignment))
+  // C++0x [class.copy]p19:
+  //   ....  If the class definition does not explicitly declare a copy
+  //   assignment operator, there is no user-declared move constructor, and
+  //   there is no user-declared move assignment operator, a copy assignme=
nt
+  //   operator is implicitly declared as defaulted.
+  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
     CopyAssignment->setDeletedAsWritten();
- =20
+
   AddOverriddenMethods(ClassDecl, CopyAssignment);
   return CopyAssignment;
 }
@@ -7583,7 +7725,8 @@
   assert((CopyAssignOperator->isDefaulted() &&=20
           CopyAssignOperator->isOverloadedOperator() &&
           CopyAssignOperator->getOverloadedOperator() =3D=3D OO_Equal &&
-          !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
+          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
+          !CopyAssignOperator->isDeleted()) &&
          "DefineImplicitCopyAssignment called for wrong function");
=20
   CXXRecordDecl *ClassDecl =3D CopyAssignOperator->getParent();
@@ -7734,10 +7877,12 @@
     MemberLookup.resolveKind();
     ExprResult From =3D BuildMemberReferenceExpr(OtherRef, OtherRefType,
                                                Loc, /*IsArrow=3D*/false,
-                                               SS, 0, MemberLookup, 0);
+                                               SS, SourceLocation(), 0,
+                                               MemberLookup, 0);
     ExprResult To =3D BuildMemberReferenceExpr(This, This->getType(),
                                              Loc, /*IsArrow=3D*/true,
-                                             SS, 0, MemberLookup, 0);
+                                             SS, SourceLocation(), 0,
+                                             MemberLookup, 0);
     assert(!From.isInvalid() && "Implicit field reference cannot fail");
     assert(!To.isInvalid() && "Implicit field reference cannot fail");
    =20
@@ -7869,10 +8014,14 @@
     CopyAssignOperator->setInvalidDecl();
     return;
   }
- =20
-  StmtResult Body =3D ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
-                                            /*isStmtExpr=3D*/false);
-  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
+
+  StmtResult Body;
+  {
+    CompoundScopeRAII CompoundScope(*this);
+    Body =3D ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
+                             /*isStmtExpr=3D*/false);
+    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
+  }
   CopyAssignOperator->setBody(Body.takeAs<Stmt>());
=20
   if (ASTMutationListener *L =3D getASTMutationListener()) {
@@ -7937,7 +8086,115 @@
   return ExceptSpec;
 }
=20
+/// Determine whether the class type has any direct or indirect virtual ba=
se
+/// classes which have a non-trivial move assignment operator.
+static bool
+hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDe=
cl) {
+  for (CXXRecordDecl::base_class_iterator Base =3D ClassDecl->vbases_begin=
(),
+                                          BaseEnd =3D ClassDecl->vbases_en=
d();
+       Base !=3D BaseEnd; ++Base) {
+    CXXRecordDecl *BaseClass =3D
+        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl(=
));
+
+    // Try to declare the move assignment. If it would be deleted, then the
+    // class does not have a non-trivial move assignment.
+    if (BaseClass->needsImplicitMoveAssignment())
+      S.DeclareImplicitMoveAssignment(BaseClass);
+
+    // If the class has both a trivial move assignment and a non-trivial m=
ove
+    // assignment, hasTrivialMoveAssignment() is false.
+    if (BaseClass->hasDeclaredMoveAssignment() &&
+        !BaseClass->hasTrivialMoveAssignment())
+      return true;
+  }
+
+  return false;
+}
+
+/// Determine whether the given type either has a move constructor or is
+/// trivially copyable.
+static bool
+hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
+  Type =3D S.Context.getBaseElementType(Type);
+
+  // FIXME: Technically, non-trivially-copyable non-class types, such as
+  // reference types, are supposed to return false here, but that appears
+  // to be a standard defect.
+  CXXRecordDecl *ClassDecl =3D Type->getAsCXXRecordDecl();
+  if (!ClassDecl)
+    return true;
+
+  if (Type.isTriviallyCopyableType(S.Context))
+    return true;
+
+  if (IsConstructor) {
+    if (ClassDecl->needsImplicitMoveConstructor())
+      S.DeclareImplicitMoveConstructor(ClassDecl);
+    return ClassDecl->hasDeclaredMoveConstructor();
+  }
+
+  if (ClassDecl->needsImplicitMoveAssignment())
+    S.DeclareImplicitMoveAssignment(ClassDecl);
+  return ClassDecl->hasDeclaredMoveAssignment();
+}
+
+/// Determine whether all non-static data members and direct or virtual ba=
ses
+/// of class \p ClassDecl have either a move operation, or are trivially
+/// copyable.
+static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassD=
ecl,
+                                            bool IsConstructor) {
+  for (CXXRecordDecl::base_class_iterator Base =3D ClassDecl->bases_begin(=
),
+                                          BaseEnd =3D ClassDecl->bases_end=
();
+       Base !=3D BaseEnd; ++Base) {
+    if (Base->isVirtual())
+      continue;
+
+    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
+      return false;
+  }
+
+  for (CXXRecordDecl::base_class_iterator Base =3D ClassDecl->vbases_begin=
(),
+                                          BaseEnd =3D ClassDecl->vbases_en=
d();
+       Base !=3D BaseEnd; ++Base) {
+    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
+      return false;
+  }
+
+  for (CXXRecordDecl::field_iterator Field =3D ClassDecl->field_begin(),
+                                     FieldEnd =3D ClassDecl->field_end();
+       Field !=3D FieldEnd; ++Field) {
+    if (!hasMoveOrIsTriviallyCopyable(S, (*Field)->getType(), IsConstructo=
r))
+      return false;
+  }
+
+  return true;
+}
+
 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDec=
l) {
+  // C++11 [class.copy]p20:
+  //   If the definition of a class X does not explicitly declare a move
+  //   assignment operator, one will be implicitly declared as defaulted
+  //   if and only if:
+  //
+  //   - [first 4 bullets]
+  assert(ClassDecl->needsImplicitMoveAssignment());
+
+  // [Checked after we build the declaration]
+  //   - the move assignment operator would not be implicitly defined as
+  //     deleted,
+
+  // [DR1402]:
+  //   - X has no direct or indirect virtual base class with a non-trivial
+  //     move assignment operator, and
+  //   - each of X's non-static data members and direct or virtual base cl=
asses
+  //     has a type that either has a move assignment operator or is trivi=
ally
+  //     copyable.
+  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
+      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/fal=
se)) {
+    ClassDecl->setFailedImplicitMoveAssignment();
+    return 0;
+  }
+
   // Note: The following rules are largely analoguous to the move
   // constructor rules.
=20
@@ -7985,7 +8242,7 @@
   //   [...]
   //   - the move assignment operator would not be implicitly defined as
   //     deleted.
-  if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
+  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
     // Cache this result so that we don't try to generate this over and ov=
er
     // on every lookup, leaking memory and wasting time.
     ClassDecl->setFailedImplicitMoveAssignment();
@@ -8005,7 +8262,8 @@
   assert((MoveAssignOperator->isDefaulted() &&=20
           MoveAssignOperator->isOverloadedOperator() &&
           MoveAssignOperator->getOverloadedOperator() =3D=3D OO_Equal &&
-          !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
+          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
+          !MoveAssignOperator->isDeleted()) &&
          "DefineImplicitMoveAssignment called for wrong function");
=20
   CXXRecordDecl *ClassDecl =3D MoveAssignOperator->getParent();
@@ -8052,7 +8310,7 @@
   // ASTs.
   Expr *This =3D ActOnCXXThis(Loc).takeAs<Expr>();
   assert(This && "Reference to this cannot fail!");
- =20
+
   // Assign base classes.
   bool Invalid =3D false;
   for (CXXRecordDecl::base_class_iterator Base =3D ClassDecl->bases_begin(=
),
@@ -8154,10 +8412,12 @@
     MemberLookup.resolveKind();
     ExprResult From =3D BuildMemberReferenceExpr(OtherRef, OtherRefType,
                                                Loc, /*IsArrow=3D*/false,
-                                               SS, 0, MemberLookup, 0);
+                                               SS, SourceLocation(), 0,
+                                               MemberLookup, 0);
     ExprResult To =3D BuildMemberReferenceExpr(This, This->getType(),
                                              Loc, /*IsArrow=3D*/true,
-                                             SS, 0, MemberLookup, 0);
+                                             SS, SourceLocation(), 0,
+                                             MemberLookup, 0);
     assert(!From.isInvalid() && "Implicit field reference cannot fail");
     assert(!To.isInvalid() && "Implicit field reference cannot fail");
=20
@@ -8299,10 +8559,14 @@
     MoveAssignOperator->setInvalidDecl();
     return;
   }
- =20
-  StmtResult Body =3D ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
-                                            /*isStmtExpr=3D*/false);
-  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
+
+  StmtResult Body;
+  {
+    CompoundScopeRAII CompoundScope(*this);
+    Body =3D ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
+                             /*isStmtExpr=3D*/false);
+    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
+  }
   MoveAssignOperator->setBody(Body.takeAs<Stmt>());
=20
   if (ASTMutationListener *L =3D getASTMutationListener()) {
@@ -8441,21 +8705,17 @@
   DeclarationNameInfo NameInfo(Name, ClassLoc);
=20
   //   An implicitly-declared copy constructor is an inline public
-  //   member of its class.=20
-  CXXConstructorDecl *CopyConstructor
-    =3D CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
-                                 Context.getFunctionType(Context.VoidTy,
-                                                         &ArgType, 1, EPI),
-                                 /*TInfo=3D*/0,
-                                 /*isExplicit=3D*/false,
-                                 /*isInline=3D*/true,
-                                 /*isImplicitlyDeclared=3D*/true,
-                                 // FIXME: apply the rules for definitions=
 here
-                                 /*isConstexpr=3D*/false);
+  //   member of its class.
+  CXXConstructorDecl *CopyConstructor =3D CXXConstructorDecl::Create(
+      Context, ClassDecl, ClassLoc, NameInfo,
+      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=
=3D*/0,
+      /*isExplicit=3D*/false, /*isInline=3D*/true, /*isImplicitlyDeclared=
=3D*/true,
+      /*isConstexpr=3D*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
+        getLangOpts().CPlusPlus0x);
   CopyConstructor->setAccess(AS_public);
   CopyConstructor->setDefaulted();
   CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
- =20
+
   // Note that we have declared this constructor.
   ++ASTContext::NumImplicitCopyConstructorsDeclared;
  =20
@@ -8472,15 +8732,14 @@
     PushOnScopeChains(CopyConstructor, S, false);
   ClassDecl->addDecl(CopyConstructor);
=20
-  // C++0x [class.copy]p7:
-  //   ... If the class definition declares a move constructor or move
-  //   assignment operator, the implicitly declared constructor is defined=
 as
-  //   deleted; ...
-  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
-      ClassDecl->hasUserDeclaredMoveAssignment() ||
-      ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
+  // C++11 [class.copy]p8:
+  //   ... If the class definition does not explicitly declare a copy
+  //   constructor, there is no user-declared move constructor, and there =
is no
+  //   user-declared move assignment operator, a copy constructor is impli=
citly
+  //   declared as defaulted.
+  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
     CopyConstructor->setDeletedAsWritten();
- =20
+
   return CopyConstructor;
 }
=20
@@ -8488,7 +8747,8 @@
                                    CXXConstructorDecl *CopyConstructor) {
   assert((CopyConstructor->isDefaulted() &&
           CopyConstructor->isCopyConstructor() &&
-          !CopyConstructor->doesThisDeclarationHaveABody()) &&
+          !CopyConstructor->doesThisDeclarationHaveABody() &&
+          !CopyConstructor->isDeleted()) &&
          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
=20
   CXXRecordDecl *ClassDecl =3D CopyConstructor->getParent();
@@ -8503,9 +8763,10 @@
       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
     CopyConstructor->setInvalidDecl();
   }  else {
+    Sema::CompoundScopeRAII CompoundScope(*this);
     CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocatio=
n(),
                                                CopyConstructor->getLocatio=
n(),
-                                               MultiStmtArg(*this, 0, 0),=20
+                                               MultiStmtArg(*this, 0, 0),
                                                /*isStmtExpr=3D*/false)
                                                               .takeAs<Stmt=
>());
     CopyConstructor->setImplicitlyDefined(true);
@@ -8561,12 +8822,7 @@
   for (RecordDecl::field_iterator F =3D ClassDecl->field_begin(),
                                FEnd =3D ClassDecl->field_end();
        F !=3D FEnd; ++F) {
-    if (F->hasInClassInitializer()) {
-      if (Expr *E =3D F->getInClassInitializer())
-        ExceptSpec.CalledExpr(E);
-      else if (!F->isInvalidDecl())
-        ExceptSpec.SetDelayed();
-    } else if (const RecordType *RecordTy
+    if (const RecordType *RecordTy
               =3D Context.getBaseElementType(F->getType())->getAs<RecordTy=
pe>()) {
       CXXRecordDecl *FieldRecDecl =3D cast<CXXRecordDecl>(RecordTy->getDec=
l());
       CXXConstructorDecl *Constructor =3D LookupMovingConstructor(FieldRec=
Decl);
@@ -8585,6 +8841,25 @@
=20
 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
                                                     CXXRecordDecl *ClassDe=
cl) {
+  // C++11 [class.copy]p9:
+  //   If the definition of a class X does not explicitly declare a move
+  //   constructor, one will be implicitly declared as defaulted if and on=
ly if:
+  //
+  //   - [first 4 bullets]
+  assert(ClassDecl->needsImplicitMoveConstructor());
+
+  // [Checked after we build the declaration]
+  //   - the move assignment operator would not be implicitly defined as
+  //     deleted,
+
+  // [DR1402]:
+  //   - each of X's non-static data members and direct or virtual base cl=
asses
+  //     has a type that either has a move constructor or is trivially cop=
yable.
+  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/tr=
ue)) {
+    ClassDecl->setFailedImplicitMoveConstructor();
+    return 0;
+  }
+
   ImplicitExceptionSpecification Spec(
       ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
=20
@@ -8601,21 +8876,17 @@
=20
   // C++0x [class.copy]p11:
   //   An implicitly-declared copy/move constructor is an inline public
-  //   member of its class.=20
-  CXXConstructorDecl *MoveConstructor
-    =3D CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
-                                 Context.getFunctionType(Context.VoidTy,
-                                                         &ArgType, 1, EPI),
-                                 /*TInfo=3D*/0,
-                                 /*isExplicit=3D*/false,
-                                 /*isInline=3D*/true,
-                                 /*isImplicitlyDeclared=3D*/true,
-                                 // FIXME: apply the rules for definitions=
 here
-                                 /*isConstexpr=3D*/false);
+  //   member of its class.
+  CXXConstructorDecl *MoveConstructor =3D CXXConstructorDecl::Create(
+      Context, ClassDecl, ClassLoc, NameInfo,
+      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=
=3D*/0,
+      /*isExplicit=3D*/false, /*isInline=3D*/true, /*isImplicitlyDeclared=
=3D*/true,
+      /*isConstexpr=3D*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
+        getLangOpts().CPlusPlus0x);
   MoveConstructor->setAccess(AS_public);
   MoveConstructor->setDefaulted();
   MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
- =20
+
   // Add the parameter to the constructor.
   ParmVarDecl *FromParam =3D ParmVarDecl::Create(Context, MoveConstructor,
                                                ClassLoc, ClassLoc,
@@ -8651,7 +8922,8 @@
                                    CXXConstructorDecl *MoveConstructor) {
   assert((MoveConstructor->isDefaulted() &&
           MoveConstructor->isMoveConstructor() &&
-          !MoveConstructor->doesThisDeclarationHaveABody()) &&
+          !MoveConstructor->doesThisDeclarationHaveABody() &&
+          !MoveConstructor->isDeleted()) &&
          "DefineImplicitMoveConstructor - call it for implicit move ctor");
=20
   CXXRecordDecl *ClassDecl =3D MoveConstructor->getParent();
@@ -8666,9 +8938,10 @@
       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
     MoveConstructor->setInvalidDecl();
   }  else {
+    Sema::CompoundScopeRAII CompoundScope(*this);
     MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocatio=
n(),
                                                MoveConstructor->getLocatio=
n(),
-                                               MultiStmtArg(*this, 0, 0),=20
+                                               MultiStmtArg(*this, 0, 0),
                                                /*isStmtExpr=3D*/false)
                                                               .takeAs<Stmt=
>());
     MoveConstructor->setImplicitlyDefined(true);
@@ -8681,6 +8954,133 @@
   }
 }
=20
+bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
+  return FD->isDeleted() &&=20
+         (FD->isDefaulted() || FD->isImplicit()) &&
+         isa<CXXMethodDecl>(FD);
+}
+
+/// \brief Mark the call operator of the given lambda closure type as "use=
d".
+static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
+  CXXMethodDecl *CallOperator=20
+    =3D cast<CXXMethodDecl>(
+        *Lambda->lookup(
+          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
+  CallOperator->setReferenced();
+  CallOperator->setUsed();
+}
+
+void Sema::DefineImplicitLambdaToFunctionPointerConversion(
+       SourceLocation CurrentLocation,
+       CXXConversionDecl *Conv)=20
+{
+  CXXRecordDecl *Lambda =3D Conv->getParent();
+ =20
+  // Make sure that the lambda call operator is marked used.
+  markLambdaCallOperatorUsed(*this, Lambda);
+ =20
+  Conv->setUsed();
+ =20
+  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
+  DiagnosticErrorTrap Trap(Diags);
+ =20
+  // Return the address of the __invoke function.
+  DeclarationName InvokeName =3D &Context.Idents.get("__invoke");
+  CXXMethodDecl *Invoke=20
+    =3D cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
+  Expr *FunctionRef =3D BuildDeclRefExpr(Invoke, Invoke->getType(),
+                                       VK_LValue, Conv->getLocation()).tak=
e();
+  assert(FunctionRef && "Can't refer to __invoke function?");
+  Stmt *Return =3D ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(=
);
+  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,=20
+                                           Conv->getLocation(),
+                                           Conv->getLocation()));
+   =20
+  // Fill in the __invoke function with a dummy implementation. IR generat=
ion
+  // will fill in the actual details.
+  Invoke->setUsed();
+  Invoke->setReferenced();
+  Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocat=
ion(),
+                                             Conv->getLocation()));
+ =20
+  if (ASTMutationListener *L =3D getASTMutationListener()) {
+    L->CompletedImplicitDefinition(Conv);
+    L->CompletedImplicitDefinition(Invoke);
+  }
+}
+
+void Sema::DefineImplicitLambdaToBlockPointerConversion(
+       SourceLocation CurrentLocation,
+       CXXConversionDecl *Conv)=20
+{
+  Conv->setUsed();
+ =20
+  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
+  DiagnosticErrorTrap Trap(Diags);
+ =20
+  // Copy-initialize the lambda object as needed to capture it.
+  Expr *This =3D ActOnCXXThis(CurrentLocation).take();
+  Expr *DerefThis =3DCreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This)=
.take();
+ =20
+  ExprResult BuildBlock =3D BuildBlockForLambdaConversion(CurrentLocation,
+                                                        Conv->getLocation(=
),
+                                                        Conv, DerefThis);
+
+  // If we're not under ARC, make sure we still get the _Block_copy/autore=
lease
+  // behavior.  Note that only the general conversion function does this
+  // (since it's unusable otherwise); in the case where we inline the
+  // block literal, it has block literal lifetime semantics.
+  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
+    BuildBlock =3D ImplicitCastExpr::Create(Context, BuildBlock.get()->get=
Type(),
+                                          CK_CopyAndAutoreleaseBlockObject,
+                                          BuildBlock.get(), 0, VK_RValue);
+
+  if (BuildBlock.isInvalid()) {
+    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
+    Conv->setInvalidDecl();
+    return;
+  }
+
+  // Create the return statement that returns the block from the conversion
+  // function.
+  StmtResult Return =3D ActOnReturnStmt(Conv->getLocation(), BuildBlock.ge=
t());
+  if (Return.isInvalid()) {
+    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
+    Conv->setInvalidDecl();
+    return;
+  }
+
+  // Set the body of the conversion function.
+  Stmt *ReturnS =3D Return.take();
+  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,=20
+                                           Conv->getLocation(),=20
+                                           Conv->getLocation()));
+ =20
+  // We're done; notify the mutation listener, if any.
+  if (ASTMutationListener *L =3D getASTMutationListener()) {
+    L->CompletedImplicitDefinition(Conv);
+  }
+}
+
+/// \brief Determine whether the given list arguments contains exactly one=20
+/// "real" (non-default) argument.
+static bool hasOneRealArgument(MultiExprArg Args) {
+  switch (Args.size()) {
+  case 0:
+    return false;
+   =20
+  default:
+    if (!Args.get()[1]->isDefaultArgument())
+      return false;
+   =20
+    // fall through
+  case 1:
+    return !Args.get()[0]->isDefaultArgument();
+  }
+ =20
+  return false;
+}
+
 ExprResult
 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInit=
Type,
                             CXXConstructorDecl *Constructor,
@@ -8702,7 +9102,7 @@
   //       can be omitted by constructing the temporary object
   //       directly into the target of the omitted copy/move
   if (ConstructKind =3D=3D CXXConstructExpr::CK_Complete &&
-      Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >=3D 1) {
+      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArg=
s)) {
     Expr *SubExpr =3D ((Expr **)ExprArgs.get())[0];
     Elidable =3D SubExpr->isTemporaryObject(Context, Constructor->getParen=
t());
   }
@@ -8732,10 +9132,11 @@
     CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
   }
=20
-  MarkDeclarationReferenced(ConstructLoc, Constructor);
+  MarkFunctionReferenced(ConstructLoc, Constructor);
   return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLo=
c,
                                         Constructor, Elidable, Exprs, NumE=
xprs,
-                                        HadMultipleCandidates, RequiresZer=
oInit,
+                                        HadMultipleCandidates, /*FIXME*/fa=
lse,
+                                        RequiresZeroInit,
               static_cast<CXXConstructExpr::ConstructionKind>(ConstructKin=
d),
                                         ParenRange));
 }
@@ -8754,7 +9155,7 @@
=20
   Expr *Temp =3D TempResult.takeAs<Expr>();
   CheckImplicitConversions(Temp, VD->getLocation());
-  MarkDeclarationReferenced(VD->getLocation(), Constructor);
+  MarkFunctionReferenced(VD->getLocation(), Constructor);
   Temp =3D MaybeCreateExprWithCleanups(Temp);
   VD->setInit(Temp);
=20
@@ -8766,15 +9167,16 @@
=20
   CXXRecordDecl *ClassDecl =3D cast<CXXRecordDecl>(Record->getDecl());
   if (ClassDecl->isInvalidDecl()) return;
-  if (ClassDecl->hasTrivialDestructor()) return;
+  if (ClassDecl->hasIrrelevantDestructor()) return;
   if (ClassDecl->isDependentContext()) return;
=20
   CXXDestructorDecl *Destructor =3D LookupDestructor(ClassDecl);
-  MarkDeclarationReferenced(VD->getLocation(), Destructor);
+  MarkFunctionReferenced(VD->getLocation(), Destructor);
   CheckDestructorAccess(VD->getLocation(), Destructor,
                         PDiag(diag::err_access_dtor_var)
                         << VD->getDeclName()
                         << VD->getType());
+  DiagnoseUseOfDecl(Destructor, VD->getLocation());
=20
   if (!VD->hasGlobalStorage()) return;
=20
@@ -8787,188 +9189,6 @@
     Diag(VD->getLocation(), diag::warn_global_destructor);
 }
=20
-/// AddCXXDirectInitializerToDecl - This action is called immediately after
-/// ActOnDeclarator, when a C++ direct initializer is present.
-/// e.g: "int x(1);"
-void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
-                                         SourceLocation LParenLoc,
-                                         MultiExprArg Exprs,
-                                         SourceLocation RParenLoc,
-                                         bool TypeMayContainAuto) {
-  assert(Exprs.size() !=3D 0 && Exprs.get() && "missing expressions");
-
-  // If there is no declaration, there was an error parsing it.  Just igno=
re
-  // the initializer.
-  if (RealDecl =3D=3D 0)
-    return;
-
-  VarDecl *VDecl =3D dyn_cast<VarDecl>(RealDecl);
-  if (!VDecl) {
-    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
-    RealDecl->setInvalidDecl();
-    return;
-  }
-
-  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
-  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
-    // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
-    if (Exprs.size() > 1) {
-      Diag(Exprs.get()[1]->getSourceRange().getBegin(),
-           diag::err_auto_var_init_multiple_expressions)
-        << VDecl->getDeclName() << VDecl->getType()
-        << VDecl->getSourceRange();
-      RealDecl->setInvalidDecl();
-      return;
-    }
-
-    Expr *Init =3D Exprs.get()[0];
-    TypeSourceInfo *DeducedType =3D 0;
-    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
-      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
-        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
-        << Init->getSourceRange();
-    if (!DeducedType) {
-      RealDecl->setInvalidDecl();
-      return;
-    }
-    VDecl->setTypeSourceInfo(DeducedType);
-    VDecl->setType(DeducedType->getType());
-
-    // In ARC, infer lifetime.
-    if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
-      VDecl->setInvalidDecl();
-
-    // If this is a redeclaration, check that the type we just deduced mat=
ches
-    // the previously declared type.
-    if (VarDecl *Old =3D VDecl->getPreviousDeclaration())
-      MergeVarDeclTypes(VDecl, Old);
-  }
-
-  // We will represent direct-initialization similarly to copy-initializat=
ion:
-  //    int x(1);  -as-> int x =3D 1;
-  //    ClassType x(a,b,c); -as-> ClassType x =3D ClassType(a,b,c);
-  //
-  // Clients that want to distinguish between the two forms, can check for
-  // direct initializer using VarDecl::hasCXXDirectInitializer().
-  // A major benefit is that clients that don't particularly care about wh=
ich
-  // exactly form was it (like the CodeGen) can handle both cases without
-  // special case code.
-
-  // C++ 8.5p11:
-  // The form of initialization (using parentheses or '=3D') is generally
-  // insignificant, but does matter when the entity being initialized has a
-  // class type.
-
-  if (!VDecl->getType()->isDependentType() &&
-      !VDecl->getType()->isIncompleteArrayType() &&=20
-      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
-                          diag::err_typecheck_decl_incomplete_type)) {
-    VDecl->setInvalidDecl();
-    return;
-  }
-
-  // The variable can not have an abstract class type.
-  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
-                             diag::err_abstract_type_in_decl,
-                             AbstractVariableType))
-    VDecl->setInvalidDecl();
-
-  const VarDecl *Def;
-  if ((Def =3D VDecl->getDefinition()) && Def !=3D VDecl) {
-    Diag(VDecl->getLocation(), diag::err_redefinition)
-    << VDecl->getDeclName();
-    Diag(Def->getLocation(), diag::note_previous_definition);
-    VDecl->setInvalidDecl();
-    return;
-  }
-
-  // C++ [class.static.data]p4
-  //   If a static data member is of const integral or const
-  //   enumeration type, its declaration in the class definition can
-  //   specify a constant-initializer which shall be an integral
-  //   constant expression (5.19). In that case, the member can appear
-  //   in integral constant expressions. The member shall still be
-  //   defined in a namespace scope if it is used in the program and the
-  //   namespace scope definition shall not contain an initializer.
-  //
-  // We already performed a redefinition check above, but for static
-  // data members we also need to check whether there was an in-class
-  // declaration with an initializer.
-  const VarDecl* PrevInit =3D 0;
-  if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
-    Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclNa=
me();
-    Diag(PrevInit->getLocation(), diag::note_previous_definition);
-    return;
-  }=20
-
-  bool IsDependent =3D false;
-  for (unsigned I =3D 0, N =3D Exprs.size(); I !=3D N; ++I) {
-    if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
-      VDecl->setInvalidDecl();
-      return;
-    }
-
-    if (Exprs.get()[I]->isTypeDependent())
-      IsDependent =3D true;
-  }
-
-  // If either the declaration has a dependent type or if any of the
-  // expressions is type-dependent, we represent the initialization
-  // via a ParenListExpr for later use during template instantiation.
-  if (VDecl->getType()->isDependentType() || IsDependent) {
-    // Let clients know that initialization was done with a direct initial=
izer.
-    VDecl->setCXXDirectInitializer(true);
-
-    // Store the initialization expressions as a ParenListExpr.
-    unsigned NumExprs =3D Exprs.size();
-    VDecl->setInit(new (Context) ParenListExpr(
-        Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
-        VDecl->getType().getNonReferenceType()));
-    return;
-  }
- =20
-  // Capture the variable that is being initialized and the style of
-  // initialization.
-  InitializedEntity Entity =3D InitializedEntity::InitializeVariable(VDecl=
);
- =20
-  // FIXME: Poor source location information.
-  InitializationKind Kind
-    =3D InitializationKind::CreateDirect(VDecl->getLocation(),
-                                       LParenLoc, RParenLoc);
- =20
-  QualType T =3D VDecl->getType();
-  InitializationSequence InitSeq(*this, Entity, Kind,=20
-                                 Exprs.get(), Exprs.size());
-  ExprResult Result =3D InitSeq.Perform(*this, Entity, Kind, move(Exprs), =
&T);
-  if (Result.isInvalid()) {
-    VDecl->setInvalidDecl();
-    return;
-  } else if (T !=3D VDecl->getType()) {
-    VDecl->setType(T);
-    Result.get()->setType(T);
-  }
-
- =20
-  Expr *Init =3D Result.get();
-  CheckImplicitConversions(Init, LParenLoc);
- =20
-  if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
-      !Init->isValueDependent() &&
-      !Init->isConstantInitializer(Context,
-                                   VDecl->getType()->isReferenceType())) {
-    // FIXME: Improve this diagnostic to explain why the initializer is not
-    // a constant expression.
-    Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
-      << VDecl << Init->getSourceRange();
-  }
-
-  Init =3D MaybeCreateExprWithCleanups(Init);
-  VDecl->setInit(Init);
-  VDecl->setCXXDirectInitializer(true);
-
-  CheckCompleteVariableDeclaration(VDecl);
-}
-
 /// \brief Given a constructor and the set of arguments provided for the
 /// constructor, convert the arguments and add any required default argume=
nts
 /// to form a proper call to this constructor.
@@ -8978,7 +9198,8 @@
 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
                               MultiExprArg ArgsPtr,
                               SourceLocation Loc,                         =
          =20
-                              ASTOwningVector<Expr*> &ConvertedArgs) {
+                              ASTOwningVector<Expr*> &ConvertedArgs,
+                              bool AllowExplicit) {
   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCa=
ll.
   unsigned NumArgs =3D ArgsPtr.size();
   Expr **Args =3D (Expr **)ArgsPtr.get();
@@ -8999,9 +9220,13 @@
   SmallVector<Expr *, 8> AllArgs;
   bool Invalid =3D GatherArgumentsForCall(Loc, Constructor,
                                         Proto, 0, Args, NumArgs, AllArgs,=20
-                                        CallType);
-  for (unsigned i =3D0, size =3D AllArgs.size(); i < size; i++)
-    ConvertedArgs.push_back(AllArgs[i]);
+                                        CallType, AllowExplicit);
+  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
+
+  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
+
+  // FIXME: Missing call to CheckFunctionCall or equivalent
+
   return Invalid;
 }
=20
@@ -9270,21 +9495,29 @@
 /// of this literal operator function is well-formed. If so, returns
 /// false; otherwise, emits appropriate diagnostics and returns true.
 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
-  DeclContext *DC =3D FnDecl->getDeclContext();
-  Decl::Kind Kind =3D DC->getDeclKind();
-  if (Kind !=3D Decl::TranslationUnit && Kind !=3D Decl::Namespace &&
-      Kind !=3D Decl::LinkageSpec) {
+  if (isa<CXXMethodDecl>(FnDecl)) {
     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespa=
ce)
       << FnDecl->getDeclName();
     return true;
   }
=20
+  if (FnDecl->isExternC()) {
+    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
+    return true;
+  }
+
   bool Valid =3D false;
=20
+  // This might be the definition of a literal operator template.
+  FunctionTemplateDecl *TpDecl =3D FnDecl->getDescribedFunctionTemplate();
+  // This might be a specialization of a literal operator template.
+  if (!TpDecl)
+    TpDecl =3D FnDecl->getPrimaryTemplate();
+
   // template <char...> type operator "" name() is the only valid template
   // signature, and the only valid signature with no parameters.
-  if (FnDecl->param_size() =3D=3D 0) {
-    if (FunctionTemplateDecl *TpDecl =3D FnDecl->getDescribedFunctionTempl=
ate()) {
+  if (TpDecl) {
+    if (FnDecl->param_size() =3D=3D 0) {
       // Must have only one template parameter
       TemplateParameterList *Params =3D TpDecl->getTemplateParameters();
       if (Params->size() =3D=3D 1) {
@@ -9297,11 +9530,11 @@
           Valid =3D true;
       }
     }
-  } else {
+  } else if (FnDecl->param_size()) {
     // Check the first parameter
     FunctionDecl::param_iterator Param =3D FnDecl->param_begin();
=20
-    QualType T =3D (*Param)->getType();
+    QualType T =3D (*Param)->getType().getUnqualifiedType();
=20
     // unsigned long long int, long double, and any character type are all=
owed
     // as the only parameters.
@@ -9321,7 +9554,7 @@
     if (!PT)
       goto FinishedParams;
     T =3D PT->getPointeeType();
-    if (!T.isConstQualified())
+    if (!T.isConstQualified() || T.isVolatileQualified())
       goto FinishedParams;
     T =3D T.getUnqualifiedType();
=20
@@ -9358,30 +9591,28 @@
     return true;
   }
=20
-  StringRef LiteralName=20
+  // A parameter-declaration-clause containing a default argument is not
+  // equivalent to any of the permitted forms.
+  for (FunctionDecl::param_iterator Param =3D FnDecl->param_begin(),
+                                    ParamEnd =3D FnDecl->param_end();
+       Param !=3D ParamEnd; ++Param) {
+    if ((*Param)->hasDefaultArg()) {
+      Diag((*Param)->getDefaultArgRange().getBegin(),
+           diag::err_literal_operator_default_argument)
+        << (*Param)->getDefaultArgRange();
+      break;
+    }
+  }
+
+  StringRef LiteralName
     =3D FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
   if (LiteralName[0] !=3D '_') {
-    // C++0x [usrlit.suffix]p1:
-    //   Literal suffix identifiers that do not start with an underscore a=
re=20
-    //   reserved for future standardization.
-    bool IsHexFloat =3D true;
-    if (LiteralName.size() > 1 &&=20
-        (LiteralName[0] =3D=3D 'P' || LiteralName[0] =3D=3D 'p')) {
-      for (unsigned I =3D 1, N =3D LiteralName.size(); I < N; ++I) {
-        if (!isdigit(LiteralName[I])) {
-          IsHexFloat =3D false;
-          break;
-        }
-      }
-    }
-   =20
-    if (IsHexFloat)
-      Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
-        << LiteralName;
-    else
-      Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
-  }
- =20
+    // C++11 [usrlit.suffix]p1:
+    //   Literal suffix identifiers that do not start with an underscore
+    //   are reserved for future standardization.
+    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
+  }
+
   return false;
 }
=20
@@ -9458,28 +9689,21 @@
     Invalid =3D true;
   }
=20
-  // GCC allows catching pointers and references to incomplete types
-  // as an extension; so do we, but we warn by default.
-
   QualType BaseType =3D ExDeclType;
   int Mode =3D 0; // 0 for direct type, 1 for pointer, 2 for reference
   unsigned DK =3D diag::err_catch_incomplete;
-  bool IncompleteCatchIsInvalid =3D true;
   if (const PointerType *Ptr =3D BaseType->getAs<PointerType>()) {
     BaseType =3D Ptr->getPointeeType();
     Mode =3D 1;
-    DK =3D diag::ext_catch_incomplete_ptr;
-    IncompleteCatchIsInvalid =3D false;
+    DK =3D diag::err_catch_incomplete_ptr;
   } else if (const ReferenceType *Ref =3D BaseType->getAs<ReferenceType>()=
) {
     // For the purpose of error recovery, we treat rvalue refs like lvalue=
 refs.
     BaseType =3D Ref->getPointeeType();
     Mode =3D 2;
-    DK =3D diag::ext_catch_incomplete_ref;
-    IncompleteCatchIsInvalid =3D false;
+    DK =3D diag::err_catch_incomplete_ref;
   }
   if (!Invalid && (Mode =3D=3D 0 || !BaseType->isVoidType()) &&
-      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, D=
K) &&
-      IncompleteCatchIsInvalid)
+      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, D=
K))
     Invalid =3D true;
=20
   if (!Invalid && !ExDeclType->isDependentType() &&
@@ -9490,7 +9714,7 @@
=20
   // Only the non-fragile NeXT runtime currently supports C++ catches
   // of ObjC types, and no runtime supports catching ObjC types by value.
-  if (!Invalid && getLangOptions().ObjC1) {
+  if (!Invalid && getLangOpts().ObjC1) {
     QualType T =3D ExDeclType;
     if (const ReferenceType *RT =3D T->getAs<ReferenceType>())
       T =3D RT->getPointeeType();
@@ -9499,7 +9723,7 @@
       Diag(Loc, diag::err_objc_object_catch);
       Invalid =3D true;
     } else if (T->isObjCObjectPointerType()) {
-      if (!getLangOptions().ObjCNonFragileABI)
+      if (!getLangOpts().ObjCNonFragileABI)
         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
     }
   }
@@ -9508,6 +9732,10 @@
                                     ExDeclType, TInfo, SC_None, SC_None);
   ExDecl->setExceptionVariable(true);
  =20
+  // In ARC, infer 'retaining' for variables of retainable type.
+  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
+    Invalid =3D true;
+
   if (!Invalid && !ExDeclType->isDependentType()) {
     if (const RecordType *recordType =3D ExDeclType->getAs<RecordType>()) {
       // C++ [except.handle]p16:
@@ -9578,6 +9806,7 @@
     if (PrevDecl->isTemplateParameter()) {
       // Maybe we will complain about the shadowed template parameter.
       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
+      PrevDecl =3D 0;
     }
   }
=20
@@ -9588,7 +9817,7 @@
   }
=20
   VarDecl *ExDecl =3D BuildExceptionDeclaration(S, TInfo,
-                                              D.getSourceRange().getBegin(=
),
+                                              D.getLocStart(),
                                               D.getIdentifierLoc(),
                                               D.getIdentifier());
   if (Invalid)
@@ -9611,17 +9840,24 @@
   StringLiteral *AssertMessage =3D cast<StringLiteral>(AssertMessageExpr_);
=20
   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
-    llvm::APSInt Value(32);
-    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
-      Diag(StaticAssertLoc,
-           diag::err_static_assert_expression_is_not_constant) <<
-        AssertExpr->getSourceRange();
+    // In a static_assert-declaration, the constant-expression shall be a
+    // constant expression that can be contextually converted to bool.
+    ExprResult Converted =3D PerformContextuallyConvertToBool(AssertExpr);
+    if (Converted.isInvalid())
       return 0;
-    }
-
-    if (Value =3D=3D 0) {
+
+    llvm::APSInt Cond;
+    if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
+          PDiag(diag::err_static_assert_expression_is_not_constant),
+          /*AllowFold=3D*/false).isInvalid())
+      return 0;
+
+    if (!Cond) {
+      llvm::SmallString<256> MsgBuffer;
+      llvm::raw_svector_ostream Msg(MsgBuffer);
+      AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
       Diag(StaticAssertLoc, diag::err_static_assert_failed)
-        << AssertMessage->getString() << AssertExpr->getSourceRange();
+        << Msg.str() << AssertExpr->getSourceRange();
     }
   }
=20
@@ -9638,46 +9874,54 @@
 /// \brief Perform semantic analysis of the given friend type declaration.
 ///
 /// \returns A friend declaration that.
-FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,=20
+FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
+                                      SourceLocation FriendLoc,
                                       TypeSourceInfo *TSInfo) {
   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
  =20
   QualType T =3D TSInfo->getType();
   SourceRange TypeRange =3D TSInfo->getTypeLoc().getLocalSourceRange();
  =20
-  if (!getLangOptions().CPlusPlus0x) {
-    // C++03 [class.friend]p2:
-    //   An elaborated-type-specifier shall be used in a friend declaration
-    //   for a class.*
-    //
-    //   * The class-key of the elaborated-type-specifier is required.
-    if (!ActiveTemplateInstantiations.empty()) {
-      // Do not complain about the form of friend template types during
-      // template instantiation; we will already have complained when the
-      // template was declared.
-    } else if (!T->isElaboratedTypeSpecifier()) {
-      // If we evaluated the type to a record type, suggest putting
-      // a tag in front.
-      if (const RecordType *RT =3D T->getAs<RecordType>()) {
-        RecordDecl *RD =3D RT->getDecl();
-       =20
-        std::string InsertionText =3D std::string(" ") + RD->getKindName();
-       =20
-        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
-          << (unsigned) RD->getTagKind()
-          << T
-          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
-                                        InsertionText);
-      } else {
-        Diag(FriendLoc, diag::ext_nonclass_type_friend)
-          << T
-          << SourceRange(FriendLoc, TypeRange.getEnd());
-      }
-    } else if (T->getAs<EnumType>()) {
-      Diag(FriendLoc, diag::ext_enum_friend)
+  // C++03 [class.friend]p2:
+  //   An elaborated-type-specifier shall be used in a friend declaration
+  //   for a class.*
+  //
+  //   * The class-key of the elaborated-type-specifier is required.
+  if (!ActiveTemplateInstantiations.empty()) {
+    // Do not complain about the form of friend template types during
+    // template instantiation; we will already have complained when the
+    // template was declared.
+  } else if (!T->isElaboratedTypeSpecifier()) {
+    // If we evaluated the type to a record type, suggest putting
+    // a tag in front.
+    if (const RecordType *RT =3D T->getAs<RecordType>()) {
+      RecordDecl *RD =3D RT->getDecl();
+     =20
+      std::string InsertionText =3D std::string(" ") + RD->getKindName();
+     =20
+      Diag(TypeRange.getBegin(),
+           getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_unelaborated_friend_type :
+             diag::ext_unelaborated_friend_type)
+        << (unsigned) RD->getTagKind()
+        << T
+        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
+                                      InsertionText);
+    } else {
+      Diag(FriendLoc,
+           getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_nonclass_type_friend :
+             diag::ext_nonclass_type_friend)
         << T
         << SourceRange(FriendLoc, TypeRange.getEnd());
     }
+  } else if (T->getAs<EnumType>()) {
+    Diag(FriendLoc,
+         getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_enum_friend :
+           diag::ext_enum_friend)
+      << T
+      << SourceRange(FriendLoc, TypeRange.getEnd());
   }
  =20
   // C++0x [class.friend]p3:
@@ -9688,7 +9932,7 @@
   // FIXME: C++0x has some syntactic restrictions on friend type declarati=
ons
   // in [class.friend]p3 that we do not implement.
  =20
-  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, Friend=
Loc);
+  return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
 }
=20
 /// Handle a friend tag declaration where the scope specifier was
@@ -9732,8 +9976,6 @@
=20
   if (Invalid) return 0;
=20
-  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?=
");
-
   bool isAllExplicitSpecializations =3D true;
   for (unsigned I =3D TempParamLists.size(); I-- > 0; ) {
     if (TempParamLists.get()[I]->size()) {
@@ -9748,6 +9990,18 @@
   // about the template header and build an appropriate non-templated
   // friend.  TODO: for source fidelity, remember the headers.
   if (isAllExplicitSpecializations) {
+    if (SS.isEmpty()) {
+      bool Owned =3D false;
+      bool IsDependent =3D false;
+      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
+                      Attr, AS_public,=20
+                      /*ModulePrivateLoc=3D*/SourceLocation(),
+                      MultiTemplateParamsArg(), Owned, IsDependent,=20
+                      /*ScopedEnumKWLoc=3D*/SourceLocation(),
+                      /*ScopedEnumUsesClassTag=3D*/false,
+                      /*UnderlyingType=3D*/TypeResult());         =20
+    }
+   =20
     NestedNameSpecifierLoc QualifierLoc =3D SS.getWithLocInContext(Context=
);
     ElaboratedTypeKeyword Keyword
       =3D TypeWithKeyword::getKeywordForTagTypeKind(Kind);
@@ -9759,12 +10013,12 @@
     TypeSourceInfo *TSI =3D Context.CreateTypeSourceInfo(T);
     if (isa<DependentNameType>(T)) {
       DependentNameTypeLoc TL =3D cast<DependentNameTypeLoc>(TSI->getTypeL=
oc());
-      TL.setKeywordLoc(TagLoc);
+      TL.setElaboratedKeywordLoc(TagLoc);
       TL.setQualifierLoc(QualifierLoc);
       TL.setNameLoc(NameLoc);
     } else {
       ElaboratedTypeLoc TL =3D cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
-      TL.setKeywordLoc(TagLoc);
+      TL.setElaboratedKeywordLoc(TagLoc);
       TL.setQualifierLoc(QualifierLoc);
       cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
     }
@@ -9775,6 +10029,10 @@
     CurContext->addDecl(Friend);
     return Friend;
   }
+ =20
+  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?=
");
+ =20
+
=20
   // Handle the case of a templated-scope friend class.  e.g.
   //   template <class T> class A<T>::B;
@@ -9783,7 +10041,7 @@
   QualType T =3D Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
   TypeSourceInfo *TSI =3D Context.CreateTypeSourceInfo(T);
   DependentNameTypeLoc TL =3D cast<DependentNameTypeLoc>(TSI->getTypeLoc()=
);
-  TL.setKeywordLoc(TagLoc);
+  TL.setElaboratedKeywordLoc(TagLoc);
   TL.setQualifierLoc(SS.getWithLocInContext(Context));
   TL.setNameLoc(NameLoc);
=20
@@ -9815,7 +10073,7 @@
 ///   template <> template <class T> friend class A<int>::B;
 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
                                 MultiTemplateParamsArg TempParams) {
-  SourceLocation Loc =3D DS.getSourceRange().getBegin();
+  SourceLocation Loc =3D DS.getLocStart();
=20
   assert(DS.isFriendSpecified());
   assert(DS.getStorageClassSpec() =3D=3D DeclSpec::SCS_unspecified);
@@ -9871,7 +10129,7 @@
                                    TSI,
                                    DS.getFriendSpecLoc());
   else
-    D =3D CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
+    D =3D CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
  =20
   if (!D)
     return 0;
@@ -9977,7 +10235,7 @@
       // declarations should stop at the nearest enclosing namespace,
       // not that they should only consider the nearest enclosing
       // namespace.
-      while (DC->isRecord())=20
+      while (DC->isRecord() || DC->isTransparentContext())=20
         DC =3D DC->getParent();
=20
       LookupQualifiedName(Previous, DC);
@@ -9996,15 +10254,17 @@
=20
     // C++ [class.friend]p1: A friend of a class is a function or
     //   class that is not a member of the class . . .
-    // C++0x changes this for both friend types and functions.
+    // C++11 changes this for both friend types and functions.
     // Most C++ 98 compilers do seem to give an error here, so
     // we do, too.
-    if (!Previous.empty() && DC->Equals(CurContext)
-        && !getLangOptions().CPlusPlus0x)
-      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
+    if (!Previous.empty() && DC->Equals(CurContext))
+      Diag(DS.getFriendSpecLoc(),
+           getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_friend_is_member :
+             diag::err_friend_is_member);
=20
     DCScope =3D getScopeForDeclContext(S, DC);
-
+   =20
     // C++ [class.friend]p6:
     //   A function can be defined in a friend declaration of a class if a=
nd=20
     //   only if the class is a non-local class (9.8), the function name is
@@ -10046,7 +10306,10 @@
     // C++ [class.friend]p1: A friend of a class is a function or
     //   class that is not a member of the class . . .
     if (DC->Equals(CurContext))
-      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
+      Diag(DS.getFriendSpecLoc(),
+           getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_friend_is_member :
+             diag::err_friend_is_member);
    =20
     if (D.isFunctionDefinition()) {
       // C++ [class.friend]p6:
@@ -10093,6 +10356,15 @@
     }
   }
=20
+  // FIXME: This is an egregious hack to cope with cases where the scope s=
tack
+  // does not contain the declaration context, i.e., in an out-of-line=20
+  // definition of a class.
+  Scope FakeDCScope(S, Scope::DeclScope, Diags);
+  if (!DCScope) {
+    FakeDCScope.setEntity(DC);
+    DCScope =3D &FakeDCScope;
+  }
+ =20
   bool AddToScope =3D true;
   NamedDecl *ND =3D ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previou=
s,
                                           move(TemplateParams), AddToScope=
);
@@ -10109,7 +10381,7 @@
   // lookup context is in lexical scope.
   if (!CurContext->isDependentContext()) {
     DC =3D DC->getRedeclContext();
-    DC->makeDeclVisibleInContext(ND, /* Recoverable=3D*/ false);
+    DC->makeDeclVisibleInContext(ND);
     if (Scope *EnclosingScope =3D getScopeForDeclContext(S, DC))
       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=3D*/ false);
   }
@@ -10145,13 +10417,42 @@
     Diag(DelLoc, diag::err_deleted_non_function);
     return;
   }
-  if (const FunctionDecl *Prev =3D Fn->getPreviousDeclaration()) {
+  if (const FunctionDecl *Prev =3D Fn->getPreviousDecl()) {
     Diag(DelLoc, diag::err_deleted_decl_not_first);
     Diag(Prev->getLocation(), diag::note_previous_declaration);
     // If the declaration wasn't the first, we delete the function anyway =
for
     // recovery.
   }
   Fn->setDeletedAsWritten();
+
+  CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(Dcl);
+  if (!MD)
+    return;
+
+  // A deleted special member function is trivial if the corresponding
+  // implicitly-declared function would have been.
+  switch (getSpecialMember(MD)) {
+  case CXXInvalid:
+    break;
+  case CXXDefaultConstructor:
+    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
+    break;
+  case CXXCopyConstructor:
+    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
+    break;
+  case CXXMoveConstructor:
+    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
+    break;
+  case CXXCopyAssignment:
+    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
+    break;
+  case CXXMoveAssignment:
+    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
+    break;
+  case CXXDestructor:
+    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
+    break;
+  }
 }
=20
 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
@@ -10245,7 +10546,7 @@
     if (!SubStmt)
       continue;
     if (isa<ReturnStmt>(SubStmt))
-      Self.Diag(SubStmt->getSourceRange().getBegin(),
+      Self.Diag(SubStmt->getLocStart(),
            diag::err_return_in_constructor_handler);
     if (!isa<Expr>(SubStmt))
       SearchForReturnInStmt(Self, SubStmt);
@@ -10376,6 +10677,14 @@
   return true;
 }
=20
+/// \brief Determine whether the given declaration is a static data member.
+static bool isStaticDataMember(Decl *D) {
+  VarDecl *Var =3D dyn_cast_or_null<VarDecl>(D);
+  if (!Var)
+    return false;
+ =20
+  return Var->isStaticDataMember();
+}
 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
 /// is a fresh scope pushed for just this purpose.
@@ -10391,6 +10700,12 @@
   //   int foo::bar;
   assert(D->isOutOfLine());
   EnterDeclaratorContext(S, D->getDeclContext());
+ =20
+  // If we are parsing the initializer for a static data member, push a
+  // new expression evaluation context that is associated with this static
+  // data member.
+  if (isStaticDataMember(D))
+    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
 }
=20
 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
@@ -10399,6 +10714,9 @@
   // If there is no declaration, there was an error parsing it.
   if (D =3D=3D 0 || D->isInvalidDecl()) return;
=20
+  if (isStaticDataMember(D))
+    PopExpressionEvaluationContext(); =20
+
   assert(D->isOutOfLine());
   ExitDeclaratorContext(S);
 }
@@ -10560,7 +10878,10 @@
       if (!KeyFunction ||=20
           (KeyFunction->hasBody(KeyFunctionDef) &&=20
            KeyFunctionDef->isInlined()))
-        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
+        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() =
=3D=3D
+             TSK_ExplicitInstantiationDefinition=20
+             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)=20
+          << Class;
     }
   }
   VTableUses.clear();
@@ -10577,7 +10898,7 @@
     // C++ [basic.def.odr]p2:
     //   [...] A virtual member function is used if it is not pure. [...]
     if (MD->isVirtual() && !MD->isPure())
-      MarkDeclarationReferenced(Loc, MD);
+      MarkFunctionReferenced(Loc, MD);
   }
=20
   // Only classes that have virtual bases need a VTT.
@@ -10597,7 +10918,7 @@
 /// SetIvarInitializers - This routine builds initialization ASTs for the
 /// Objective-C implementation whose ivars need be initialized.
 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)=
 {
-  if (!getLangOptions().CPlusPlus)
+  if (!getLangOpts().CPlusPlus)
     return;
   if (ObjCInterfaceDecl *OID =3D ObjCImplementation->getClassInterface()) {
     SmallVector<ObjCIvarDecl*, 8> ivars;
@@ -10637,7 +10958,7 @@
                                                         ->getAs<RecordType=
>()) {
                     CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RecordTy->ge=
tDecl());
         if (CXXDestructorDecl *Destructor =3D LookupDestructor(RD)) {
-          MarkDeclarationReferenced(Field->getLocation(), Destructor);
+          MarkFunctionReferenced(Field->getLocation(), Destructor);
           CheckDestructorAccess(Field->getLocation(), Destructor,
                             PDiag(diag::err_access_dtor_ivar)
                               << Context.getBaseElementType(Field->getType=
()));
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaDeclObjC.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaDeclObjC.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaDeclObjC.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -21,8 +21,10 @@
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
+#include "clang/AST/ASTMutationListener.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Sema/DeclSpec.h"
+#include "clang/Lex/Preprocessor.h"
 #include "llvm/ADT/DenseSet.h"
=20
 using namespace clang;
@@ -59,7 +61,7 @@
=20
     // It's okay for the result type to still be a forward declaration
     // if we're checking an interface declaration.
-    if (resultClass->isForwardDecl()) {
+    if (!resultClass->hasDefinition()) {
       if (receiverTypeIfCall.isNull() &&
           !isa<ObjCImplementationDecl>(method->getDeclContext()))
         return false;
@@ -156,7 +158,7 @@
       Diag(Overridden->getLocation(),=20
            diag::note_related_result_type_overridden);
   }
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=3D
          Overridden->hasAttr<NSReturnsRetainedAttr>())) {
         Diag(NewMethod->getLocation(),
@@ -241,7 +243,8 @@
   if (ND && ND->isDeprecated()) {
     S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
     if (select =3D=3D 0)
-      S.Diag(ND->getLocation(), diag::note_method_declared_at);
+      S.Diag(ND->getLocation(), diag::note_method_declared_at)
+        << ND->getDeclName();
     else
       S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
   }
@@ -297,7 +300,7 @@
   }
=20
   // In ARC, disallow definition of retain/release/autorelease/retainCount
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     switch (MDecl->getMethodFamily()) {
     case OMF_retain:
     case OMF_retainCount:
@@ -336,16 +339,38 @@
     // Only do this if the current class actually has a superclass.
     if (IC->getSuperClass()) {
       ObjCShouldCallSuperDealloc =3D=20
-        !(Context.getLangOptions().ObjCAutoRefCount ||
-          Context.getLangOptions().getGC() =3D=3D LangOptions::GCOnly) &&
+        !(Context.getLangOpts().ObjCAutoRefCount ||
+          Context.getLangOpts().getGC() =3D=3D LangOptions::GCOnly) &&
         MDecl->getMethodFamily() =3D=3D OMF_dealloc;
       ObjCShouldCallSuperFinalize =3D
-        Context.getLangOptions().getGC() !=3D LangOptions::NonGC &&
+        Context.getLangOpts().getGC() !=3D LangOptions::NonGC &&
         MDecl->getMethodFamily() =3D=3D OMF_finalize;
     }
   }
 }
=20
+namespace {
+
+// Callback to only accept typo corrections that are Objective-C classes.
+// If an ObjCInterfaceDecl* is given to the constructor, then the validati=
on
+// function will reject corrections to that class.
+class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {}
+  explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
+      : CurrentIDecl(IDecl) {}
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    ObjCInterfaceDecl *ID =3D candidate.getCorrectionDeclAs<ObjCInterfaceD=
ecl>();
+    return ID && !declaresSameEntity(ID, CurrentIDecl);
+  }
+
+ private:
+  ObjCInterfaceDecl *CurrentIDecl;
+};
+
+}
+
 Decl *Sema::
 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
                          IdentifierInfo *ClassName, SourceLocation ClassLo=
c,
@@ -364,54 +389,44 @@
     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   }
=20
-  ObjCInterfaceDecl* IDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(PrevDec=
l);
-  if (IDecl) {
-    // Class already seen. Is it a forward declaration?
-    if (!IDecl->isForwardDecl()) {
+  // Create a declaration to describe this @interface.
+  ObjCInterfaceDecl* PrevIDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(Pre=
vDecl);
+  ObjCInterfaceDecl *IDecl
+    =3D ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, Cla=
ssName,
+                                PrevIDecl, ClassLoc);
+ =20
+  if (PrevIDecl) {
+    // Class already seen. Was it a definition?
+    if (ObjCInterfaceDecl *Def =3D PrevIDecl->getDefinition()) {
+      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
+        << PrevIDecl->getDeclName();
+      Diag(Def->getLocation(), diag::note_previous_definition);
       IDecl->setInvalidDecl();
-      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclN=
ame();
-      Diag(IDecl->getLocation(), diag::note_previous_definition);
+    }
+  }
+ =20
+  if (AttrList)
+    ProcessDeclAttributeList(TUScope, IDecl, AttrList);
+  PushOnScopeChains(IDecl, TUScope);
=20
-      // Return the previous class interface.
-      // FIXME: don't leak the objects passed in!
-      return ActOnObjCContainerStartDefinition(IDecl);
-    } else {
-      IDecl->setLocation(ClassLoc);
-      IDecl->setForwardDecl(false);
-      IDecl->setAtStartLoc(AtInterfaceLoc);
-      // If the forward decl was in a PCH, we need to write it again in a
-      // dependent AST file.
-      IDecl->setChangedSinceDeserialization(true);
-     =20
-      // Since this ObjCInterfaceDecl was created by a forward declaration,
-      // we now add it to the DeclContext since it wasn't added before
-      // (see ActOnForwardClassDeclaration).
-      IDecl->setLexicalDeclContext(CurContext);
-      CurContext->addDecl(IDecl);
-     =20
-      if (AttrList)
-        ProcessDeclAttributeList(TUScope, IDecl, AttrList);
-    }
-  } else {
-    IDecl =3D ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLo=
c,
-                                      ClassName, ClassLoc);
-    if (AttrList)
-      ProcessDeclAttributeList(TUScope, IDecl, AttrList);
-
-    PushOnScopeChains(IDecl, TUScope);
-  }
-
+  // Start the definition of this class. If we're in a redefinition case, =
there=20
+  // may already be a definition, so we'll end up adding to it.
+  if (!IDecl->hasDefinition())
+    IDecl->startDefinition();
+ =20
   if (SuperName) {
     // Check if a different kind of symbol declared in this scope.
     PrevDecl =3D LookupSingleName(TUScope, SuperName, SuperLoc,
                                 LookupOrdinaryName);
=20
     if (!PrevDecl) {
-      // Try to correct for a typo in the superclass name.
-      TypoCorrection Corrected =3D CorrectTypo(
+      // Try to correct for a typo in the superclass name without correcti=
ng
+      // to the class we're defining.
+      ObjCInterfaceValidatorCCC Validator(IDecl);
+      if (TypoCorrection Corrected =3D CorrectTypo(
           DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TU=
Scope,
-          NULL, NULL, false, CTC_NoKeywords);
-      if ((PrevDecl =3D Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()=
)) {
+          NULL, Validator)) {
+        PrevDecl =3D Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
         Diag(SuperLoc, diag::err_undef_superclass_suggest)
           << SuperName << ClassName << PrevDecl->getDeclName();
         Diag(PrevDecl->getLocation(), diag::note_previous_decl)
@@ -419,10 +434,10 @@
       }
     }
=20
-    if (PrevDecl =3D=3D IDecl) {
+    if (declaresSameEntity(PrevDecl, IDecl)) {
       Diag(SuperLoc, diag::err_recursive_superclass)
         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
-      IDecl->setLocEnd(ClassLoc);
+      IDecl->setEndOfDefinitionLoc(ClassLoc);
     } else {
       ObjCInterfaceDecl *SuperClassDecl =3D
                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDe=
cl);
@@ -458,27 +473,28 @@
         if (!SuperClassDecl)
           Diag(SuperLoc, diag::err_undef_superclass)
             << SuperName << ClassName << SourceRange(AtInterfaceLoc, Class=
Loc);
-        else if (SuperClassDecl->isForwardDecl()) {
-          Diag(SuperLoc, diag::err_forward_superclass)
-            << SuperClassDecl->getDeclName() << ClassName
-            << SourceRange(AtInterfaceLoc, ClassLoc);
-          Diag(SuperClassDecl->getLocation(), diag::note_forward_class);
+        else if (RequireCompleteType(SuperLoc,=20
+                   Context.getObjCInterfaceType(SuperClassDecl),
+                   PDiag(diag::err_forward_superclass)
+                     << SuperClassDecl->getDeclName()=20
+                     << ClassName
+                   << SourceRange(AtInterfaceLoc, ClassLoc))) {
           SuperClassDecl =3D 0;
         }
       }
       IDecl->setSuperClass(SuperClassDecl);
       IDecl->setSuperClassLoc(SuperLoc);
-      IDecl->setLocEnd(SuperLoc);
+      IDecl->setEndOfDefinitionLoc(SuperLoc);
     }
   } else { // we have a root class.
-    IDecl->setLocEnd(ClassLoc);
+    IDecl->setEndOfDefinitionLoc(ClassLoc);
   }
=20
   // Check then save referenced protocols.
   if (NumProtoRefs) {
     IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
                            ProtoLocs, Context);
-    IDecl->setLocEnd(EndProtoLoc);
+    IDecl->setEndOfDefinitionLoc(EndProtoLoc);
   }
=20
   CheckObjCDeclScope(IDecl);
@@ -550,6 +566,10 @@
         Diag(PrevLoc, diag::note_previous_definition);
         res =3D true;
       }
+     =20
+      if (!PDecl->hasDefinition())
+        continue;
+     =20
       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
             PDecl->getLocation(), PDecl->getReferencedProtocols()))
         res =3D true;
@@ -570,44 +590,52 @@
   bool err =3D false;
   // FIXME: Deal with AttrList.
   assert(ProtocolName && "Missing protocol identifier");
-  ObjCProtocolDecl *PDecl =3D LookupProtocol(ProtocolName, ProtocolLoc);
-  if (PDecl) {
-    // Protocol already seen. Better be a forward protocol declaration
-    if (!PDecl->isForwardDecl()) {
-      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
-      Diag(PDecl->getLocation(), diag::note_previous_definition);
-      // Just return the protocol we already had.
-      // FIXME: don't leak the objects passed in!
-      return ActOnObjCContainerStartDefinition(PDecl);
+  ObjCProtocolDecl *PrevDecl =3D LookupProtocol(ProtocolName, ProtocolLoc,
+                                              ForRedeclaration);
+  ObjCProtocolDecl *PDecl =3D 0;
+  if (ObjCProtocolDecl *Def =3D PrevDecl? PrevDecl->getDefinition() : 0) {
+    // If we already have a definition, complain.
+    Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
+    Diag(Def->getLocation(), diag::note_previous_definition);
+
+    // Create a new protocol that is completely distinct from previous
+    // declarations, and do not make this protocol available for name look=
up.
+    // That way, we'll end up completely ignoring the duplicate.
+    // FIXME: Can we turn this into an error?
+    PDecl =3D ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
+                                     ProtocolLoc, AtProtoInterfaceLoc,
+                                     /*PrevDecl=3D*/0);
+    PDecl->startDefinition();
+  } else {
+    if (PrevDecl) {
+      // Check for circular dependencies among protocol declarations. This=
 can
+      // only happen if this protocol was forward-declared.
+      ObjCList<ObjCProtocolDecl> PList;
+      PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context=
);
+      err =3D CheckForwardProtocolDeclarationForCircularDependency(
+              ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
     }
-    ObjCList<ObjCProtocolDecl> PList;
-    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
-    err =3D CheckForwardProtocolDeclarationForCircularDependency(
-            ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
=20
-    // Make sure the cached decl gets a valid start location.
-    PDecl->setAtStartLoc(AtProtoInterfaceLoc);
-    PDecl->setLocation(ProtocolLoc);
-    PDecl->setForwardDecl(false);
-    // Since this ObjCProtocolDecl was created by a forward declaration,
-    // we now add it to the DeclContext since it wasn't added before
-    PDecl->setLexicalDeclContext(CurContext);
-    CurContext->addDecl(PDecl);
-    // Repeat in dependent AST files.
-    PDecl->setChangedSinceDeserialization(true);
-  } else {
+    // Create the new declaration.
     PDecl =3D ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
-                                     ProtocolLoc, AtProtoInterfaceLoc);
+                                     ProtocolLoc, AtProtoInterfaceLoc,
+                                     /*PrevDecl=3D*/PrevDecl);
+   =20
     PushOnScopeChains(PDecl, TUScope);
-    PDecl->setForwardDecl(false);
+    PDecl->startDefinition();
   }
+ =20
   if (AttrList)
     ProcessDeclAttributeList(TUScope, PDecl, AttrList);
+ =20
+  // Merge attributes from previous declarations.
+  if (PrevDecl)
+    mergeDeclAttributes(PDecl, PrevDecl);
+
   if (!err && NumProtoRefs ) {
     /// Check then save referenced protocols.
     PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
                            ProtoLocs, Context);
-    PDecl->setLocEnd(EndProtoLoc);
   }
=20
   CheckObjCDeclScope(PDecl);
@@ -626,9 +654,10 @@
     ObjCProtocolDecl *PDecl =3D LookupProtocol(ProtocolId[i].first,
                                              ProtocolId[i].second);
     if (!PDecl) {
+      DeclFilterCCC<ObjCProtocolDecl> Validator;
       TypoCorrection Corrected =3D CorrectTypo(
           DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
-          LookupObjCProtocolName, TUScope, NULL, NULL, false, CTC_NoKeywor=
ds);
+          LookupObjCProtocolName, TUScope, NULL, Validator);
       if ((PDecl =3D Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
         Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
           << ProtocolId[i].first << Corrected.getCorrection();
@@ -647,7 +676,7 @@
=20
     // If this is a forward declaration and we are supposed to warn in this
     // case, do it.
-    if (WarnOnDeclarations && PDecl->isForwardDecl())
+    if (WarnOnDeclarations && !PDecl->hasDefinition())
       Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
         << ProtocolId[i].first;
     Protocols.push_back(PDecl);
@@ -684,40 +713,34 @@
 }
=20
 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
-Decl *
+Sema::DeclGroupPtrTy
 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
                                       const IdentifierLocPair *IdentList,
                                       unsigned NumElts,
                                       AttributeList *attrList) {
-  SmallVector<ObjCProtocolDecl*, 32> Protocols;
-  SmallVector<SourceLocation, 8> ProtoLocs;
-
+  SmallVector<Decl *, 8> DeclsInGroup;
   for (unsigned i =3D 0; i !=3D NumElts; ++i) {
     IdentifierInfo *Ident =3D IdentList[i].first;
-    ObjCProtocolDecl *PDecl =3D LookupProtocol(Ident, IdentList[i].second);
-    bool isNew =3D false;
-    if (PDecl =3D=3D 0) { // Not already seen?
-      PDecl =3D ObjCProtocolDecl::Create(Context, CurContext, Ident,
-                                       IdentList[i].second, AtProtocolLoc);
-      PushOnScopeChains(PDecl, TUScope, false);
-      isNew =3D true;
-    }
-    if (attrList) {
+    ObjCProtocolDecl *PrevDecl =3D LookupProtocol(Ident, IdentList[i].seco=
nd,
+                                                ForRedeclaration);
+    ObjCProtocolDecl *PDecl
+      =3D ObjCProtocolDecl::Create(Context, CurContext, Ident,=20
+                                 IdentList[i].second, AtProtocolLoc,
+                                 PrevDecl);
+       =20
+    PushOnScopeChains(PDecl, TUScope);
+    CheckObjCDeclScope(PDecl);
+   =20
+    if (attrList)
       ProcessDeclAttributeList(TUScope, PDecl, attrList);
-      if (!isNew)
-        PDecl->setChangedSinceDeserialization(true);
-    }
-    Protocols.push_back(PDecl);
-    ProtoLocs.push_back(IdentList[i].second);
+   =20
+    if (PrevDecl)
+      mergeDeclAttributes(PDecl, PrevDecl);
+
+    DeclsInGroup.push_back(PDecl);
   }
=20
-  ObjCForwardProtocolDecl *PDecl =3D
-    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
-                                    Protocols.data(), Protocols.size(),
-                                    ProtoLocs.data());
-  CurContext->addDecl(PDecl);
-  CheckObjCDeclScope(PDecl);
-  return PDecl;
+  return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), fa=
lse);
 }
=20
 Decl *Sema::
@@ -733,14 +756,21 @@
   ObjCInterfaceDecl *IDecl =3D getObjCInterfaceDecl(ClassName, ClassLoc, t=
rue);
=20
   /// Check that class of this category is already completely declared.
-  if (!IDecl || IDecl->isForwardDecl()) {
+
+  if (!IDecl=20
+      || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
+                             PDiag(diag::err_category_forward_interface)
+                               << (CategoryName =3D=3D 0))) {
     // Create an invalid ObjCCategoryDecl to serve as context for
     // the enclosing method declarations.  We mark the decl invalid
     // to make it clear that this isn't a valid AST.
     CDecl =3D ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
                                      ClassLoc, CategoryLoc, CategoryName,I=
Decl);
     CDecl->setInvalidDecl();
-    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
+    CurContext->addDecl(CDecl);
+       =20
+    if (!IDecl)
+      Diag(ClassLoc, diag::err_undef_interface) << ClassName;
     return ActOnObjCContainerStartDefinition(CDecl);
   }
=20
@@ -792,24 +822,28 @@
                       IdentifierInfo *CatName, SourceLocation CatLoc) {
   ObjCInterfaceDecl *IDecl =3D getObjCInterfaceDecl(ClassName, ClassLoc, t=
rue);
   ObjCCategoryDecl *CatIDecl =3D 0;
-  if (IDecl) {
+  if (IDecl && IDecl->hasDefinition()) {
     CatIDecl =3D IDecl->FindCategoryDeclaration(CatName);
     if (!CatIDecl) {
       // Category @implementation with no corresponding @interface.
       // Create and install one.
-      CatIDecl =3D ObjCCategoryDecl::Create(Context, CurContext, SourceLoc=
ation(),
-                                          SourceLocation(), SourceLocation=
(),
+      CatIDecl =3D ObjCCategoryDecl::Create(Context, CurContext, AtCatImpl=
Loc,
+                                          ClassLoc, CatLoc,
                                           CatName, IDecl);
+      CatIDecl->setImplicit();
     }
   }
=20
   ObjCCategoryImplDecl *CDecl =3D
     ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
-                                 ClassLoc, AtCatImplLoc);
+                                 ClassLoc, AtCatImplLoc, CatLoc);
   /// Check that class of this category is already completely declared.
-  if (!IDecl || IDecl->isForwardDecl()) {
+  if (!IDecl) {
     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
     CDecl->setInvalidDecl();
+  } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(ID=
ecl),
+                                 diag::err_undef_interface)) {
+    CDecl->setInvalidDecl();
   }
=20
   // FIXME: PushOnScopeChains?
@@ -854,23 +888,21 @@
     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   } else if ((IDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
-    // If this is a forward declaration of an interface, warn.
-    if (IDecl->isForwardDecl()) {
-      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
-      IDecl =3D 0;
-    }
+    RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
+                        diag::warn_undef_interface);
   } else {
     // We did not find anything with the name ClassName; try to correct fo=
r=20
     // typos in the class name.
-    TypoCorrection Corrected =3D CorrectTypo(
+    ObjCInterfaceValidatorCCC Validator;
+    if (TypoCorrection Corrected =3D CorrectTypo(
         DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUSc=
ope,
-        NULL, NULL, false, CTC_NoKeywords);
-    if ((IDecl =3D Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
+        NULL, Validator)) {
       // Suggest the (potentially) correct interface name. However, put the
       // fix-it hint itself in a separate note, since changing the name in=20
       // the warning would make the fix-it change semantics.However, don't
       // provide a code-modification hint or use the typo name for recover=
y,
       // because this is just a warning. The program may actually be corre=
ct.
+      IDecl =3D Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
       DeclarationName CorrectedName =3D Corrected.getCorrection();
       Diag(ClassLoc, diag::warn_undef_interface_suggest)
         << ClassName << CorrectedName;
@@ -894,10 +926,12 @@
       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
     } else {
       SDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
+      if (SDecl && !SDecl->hasDefinition())
+        SDecl =3D 0;
       if (!SDecl)
         Diag(SuperClassLoc, diag::err_undef_superclass)
           << SuperClassname << ClassName;
-      else if (IDecl && IDecl->getSuperClass() !=3D SDecl) {
+      else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)=
) {
         // This implementation and its interface do not have the same
         // super class.
         Diag(SuperClassLoc, diag::err_conflicting_super_class)
@@ -914,16 +948,24 @@
     // FIXME: Do we support attributes on the @implementation? If so we sh=
ould
     // copy them over.
     IDecl =3D ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLo=
c,
-                                      ClassName, ClassLoc, false, true);
-    IDecl->setSuperClass(SDecl);
-    IDecl->setLocEnd(ClassLoc);
-
+                                      ClassName, /*PrevDecl=3D*/0, ClassLo=
c,=20
+                                      true);
+    IDecl->startDefinition();
+    if (SDecl) {
+      IDecl->setSuperClass(SDecl);
+      IDecl->setSuperClassLoc(SuperClassLoc);
+      IDecl->setEndOfDefinitionLoc(SuperClassLoc);
+    } else {
+      IDecl->setEndOfDefinitionLoc(ClassLoc);
+    }
+   =20
     PushOnScopeChains(IDecl, TUScope);
   } else {
     // Mark the interface as being completed, even if it was just as
     //   @class ....;
     // declaration; the user cannot reopen it.
-    IDecl->setForwardDecl(false);
+    if (!IDecl->hasDefinition())
+      IDecl->startDefinition();
   }
=20
   ObjCImplementationDecl* IMPDecl =3D
@@ -951,6 +993,25 @@
   return ActOnObjCContainerStartDefinition(IMPDecl);
 }
=20
+Sema::DeclGroupPtrTy
+Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> De=
cls) {
+  SmallVector<Decl *, 64> DeclsInGroup;
+  DeclsInGroup.reserve(Decls.size() + 1);
+
+  for (unsigned i =3D 0, e =3D Decls.size(); i !=3D e; ++i) {
+    Decl *Dcl =3D Decls[i];
+    if (!Dcl)
+      continue;
+    if (Dcl->getDeclContext()->isFileContext())
+      Dcl->setTopLevelDeclInObjCContainer();
+    DeclsInGroup.push_back(Dcl);
+  }
+
+  DeclsInGroup.push_back(ObjCImpDecl);
+
+  return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), fa=
lse);
+}
+
 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
                                     ObjCIvarDecl **ivars, unsigned numIvar=
s,
                                     SourceLocation RBrace) {
@@ -962,11 +1023,11 @@
   /// (legacy objective-c @implementation decl without an @interface decl).
   /// Add implementations's ivar to the synthesize class's ivar list.
   if (IDecl->isImplicitInterfaceDecl()) {
-    IDecl->setLocEnd(RBrace);
+    IDecl->setEndOfDefinitionLoc(RBrace);
     // Add ivar's to class's DeclContext.
     for (unsigned i =3D 0, e =3D numIvars; i !=3D e; ++i) {
       ivars[i]->setLexicalDeclContext(ImpDecl);
-      IDecl->makeDeclVisibleInContext(ivars[i], false);
+      IDecl->makeDeclVisibleInContext(ivars[i]);
       ImpDecl->addDecl(ivars[i]);
     }
    =20
@@ -990,7 +1051,7 @@
       }
       // Instance ivar to Implementation's DeclContext.
       ImplIvar->setLexicalDeclContext(ImpDecl);
-      IDecl->makeDeclVisibleInContext(ImplIvar, false);
+      IDecl->makeDeclVisibleInContext(ImplIvar);
       ImpDecl->addDecl(ImplIvar);
     }
     return;
@@ -1329,7 +1390,7 @@
 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
                                        ObjCMethodDecl *MethodDecl,
                                        bool IsProtocolMethodDecl) {
-  if (getLangOptions().ObjCAutoRefCount &&
+  if (getLangOpts().ObjCAutoRefCount &&
       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
     return;
=20
@@ -1410,7 +1471,8 @@
   if (match) {
     Diag(ImpMethodDecl->getLocation(),=20
          diag::warn_category_method_impl_match);
-    Diag(MethodDecl->getLocation(), diag::note_method_declared_at);
+    Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
+      << MethodDecl->getDeclName();
   }
 }
=20
@@ -1428,16 +1490,14 @@
                                    const llvm::DenseSet<Selector> &InsMap,
                                    const llvm::DenseSet<Selector> &ClsMap,
                                    ObjCContainerDecl *CDecl) {
-  ObjCInterfaceDecl *IDecl;
-  if (ObjCCategoryDecl *C =3D dyn_cast<ObjCCategoryDecl>(CDecl))
-    IDecl =3D C->getClassInterface();
-  else
-    IDecl =3D dyn_cast<ObjCInterfaceDecl>(CDecl);
+  ObjCCategoryDecl *C =3D dyn_cast<ObjCCategoryDecl>(CDecl);
+  ObjCInterfaceDecl *IDecl =3D C ? C->getClassInterface()=20
+                               : dyn_cast<ObjCInterfaceDecl>(CDecl);
   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
  =20
   ObjCInterfaceDecl *Super =3D IDecl->getSuperClass();
   ObjCInterfaceDecl *NSIDecl =3D 0;
-  if (getLangOptions().NeXTRuntime) {
+  if (getLangOpts().NeXTRuntime) {
     // check to see if class implements forwardInvocation method and objec=
ts
     // of this class are derived from 'NSProxy' so that to forward requests
     // from one object to another.
@@ -1467,20 +1527,28 @@
           !method->isSynthesized() && !InsMap.count(method->getSelector())=
 &&
           (!Super ||
            !Super->lookupInstanceMethod(method->getSelector()))) {
+            // If a method is not implemented in the category implementati=
on but
+            // has been declared in its primary class, superclass,
+            // or in one of their protocols, no need to issue the warning.=20
+            // This is because method will be implemented in the primary c=
lass=20
+            // or one of its super class implementation.
+           =20
             // Ugly, but necessary. Method declared in protcol might have
             // have been synthesized due to a property declared in the cla=
ss which
             // uses the protocol.
-            ObjCMethodDecl *MethodInClass =3D
-            IDecl->lookupInstanceMethod(method->getSelector());
-            if (!MethodInClass || !MethodInClass->isSynthesized()) {
-              unsigned DIAG =3D diag::warn_unimplemented_protocol_method;
-              if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
-                      !=3D DiagnosticsEngine::Ignored) {
-                WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
-                Diag(method->getLocation(), diag::note_method_declared_at);
-                Diag(CDecl->getLocation(), diag::note_required_for_protoco=
l_at)
-                  << PDecl->getDeclName();
-              }
+            if (ObjCMethodDecl *MethodInClass =3D
+                  IDecl->lookupInstanceMethod(method->getSelector(),=20
+                                              true /*shallowCategoryLookup=
*/))
+              if (C || MethodInClass->isSynthesized())
+                continue;
+            unsigned DIAG =3D diag::warn_unimplemented_protocol_method;
+            if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
+                !=3D DiagnosticsEngine::Ignored) {
+              WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
+              Diag(method->getLocation(), diag::note_method_declared_at)
+                << method->getDeclName();
+              Diag(CDecl->getLocation(), diag::note_required_for_protocol_=
at)
+                << PDecl->getDeclName();
             }
           }
     }
@@ -1492,11 +1560,16 @@
     if (method->getImplementationControl() !=3D ObjCMethodDecl::Optional &&
         !ClsMap.count(method->getSelector()) &&
         (!Super || !Super->lookupClassMethod(method->getSelector()))) {
+      // See above comment for instance method lookups.
+      if (C && IDecl->lookupClassMethod(method->getSelector(),=20
+                                        true /*shallowCategoryLookup*/))
+        continue;
       unsigned DIAG =3D diag::warn_unimplemented_protocol_method;
       if (Diags.getDiagnosticLevel(DIAG, ImpLoc) !=3D
             DiagnosticsEngine::Ignored) {
         WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
-        Diag(method->getLocation(), diag::note_method_declared_at);
+        Diag(method->getLocation(), diag::note_method_declared_at)
+          << method->getDeclName();
         Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
           PDecl->getDeclName();
       }
@@ -1505,7 +1578,7 @@
   // Check on this protocols's referenced protocols, recursively.
   for (ObjCProtocolDecl::protocol_iterator PI =3D PDecl->protocol_begin(),
        E =3D PDecl->protocol_end(); PI !=3D E; ++PI)
-    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, I=
Decl);
+    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, C=
Decl);
 }
=20
 /// MatchAllMethodDeclarations - Check methods declared in interface
@@ -1519,7 +1592,7 @@
                                       ObjCContainerDecl* CDecl,
                                       bool &IncompleteImpl,
                                       bool ImmediateClass,
-                                      bool WarnExactMatch) {
+                                      bool WarnCategoryMethodImpl) {
   // Check and see if instance methods in class interface have been
   // implemented in the implementation class. If so, their types match.
   for (ObjCInterfaceDecl::instmeth_iterator I =3D CDecl->instmeth_begin(),
@@ -1541,12 +1614,12 @@
       ObjCMethodDecl *MethodDecl =3D *I;
       // ImpMethodDecl may be null as in a @dynamic property.
       if (ImpMethodDecl) {
-        if (!WarnExactMatch)
+        if (!WarnCategoryMethodImpl)
           WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
                                       isa<ObjCProtocolDecl>(CDecl));
         else if (!MethodDecl->isSynthesized())
           WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
-                               isa<ObjCProtocolDecl>(CDecl));
+                                isa<ObjCProtocolDecl>(CDecl));
       }
     }
   }
@@ -1568,12 +1641,12 @@
       assert(CDecl->getClassMethod((*I)->getSelector()) &&
              "Expected to find the method through lookup as well");
       ObjCMethodDecl *MethodDecl =3D *I;
-      if (!WarnExactMatch)
+      if (!WarnCategoryMethodImpl)
         WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,=20
                                     isa<ObjCProtocolDecl>(CDecl));
       else
         WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
-                             isa<ObjCProtocolDecl>(CDecl));
+                              isa<ObjCProtocolDecl>(CDecl));
     }
   }
  =20
@@ -1584,7 +1657,8 @@
       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
                                  IMPDecl,
                                  const_cast<ObjCCategoryDecl *>(ClsExtDecl=
),=20
-                                 IncompleteImpl, false, WarnExactMatch);
+                                 IncompleteImpl, false,=20
+                                 WarnCategoryMethodImpl);
    =20
     // Check for any implementation of a methods declared in protocol.
     for (ObjCInterfaceDecl::all_protocol_iterator
@@ -1592,11 +1666,12 @@
           E =3D I->all_referenced_protocol_end(); PI !=3D E; ++PI)
       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
                                  IMPDecl,
-                                 (*PI), IncompleteImpl, false, WarnExactMa=
tch);
+                                 (*PI), IncompleteImpl, false,=20
+                                 WarnCategoryMethodImpl);
    =20
     // FIXME. For now, we are not checking for extact match of methods=20
     // in category implementation and its primary class's super class.=20
-    if (!WarnExactMatch && I->getSuperClass())
+    if (!WarnCategoryMethodImpl && I->getSuperClass())
       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
                                  IMPDecl,
                                  I->getSuperClass(), IncompleteImpl, false=
);
@@ -1633,7 +1708,8 @@
   bool IncompleteImpl =3D false;
   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
                              CatIMPDecl, IDecl,
-                             IncompleteImpl, false, true /*WarnExactMatch*=
/);
+                             IncompleteImpl, false,=20
+                             true /*WarnCategoryMethodImpl*/);
 }
=20
 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
@@ -1649,9 +1725,10 @@
   // Check and see if properties declared in the interface have either 1)
   // an implementation or 2) there is a @synthesize/@dynamic implementation
   // of the property in the @implementation.
-  if (isa<ObjCInterfaceDecl>(CDecl) &&
-        !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileAB=
I2))
-    DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
+  if (const ObjCInterfaceDecl *IDecl =3D dyn_cast<ObjCInterfaceDecl>(CDecl=
))
+    if  (!(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileA=
BI2) ||
+      IDecl->isObjCRequiresPropertyDefs())
+      DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
      =20
   llvm::DenseSet<Selector> ClsMap;
   for (ObjCImplementationDecl::classmeth_iterator
@@ -1738,37 +1815,36 @@
       // typedef NSObject < XCElementTogglerP > XCElementToggler;
       // @class XCElementToggler;
       //
-      // FIXME: Make an extension?
+      // Here we have chosen to ignore the forward class declaration
+      // with a warning. Since this is the implied behavior.
       TypedefNameDecl *TDD =3D dyn_cast<TypedefNameDecl>(PrevDecl);
       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentLi=
st[i];
         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
       } else {
         // a forward class declaration matching a typedef name of a class =
refers
-        // to the underlying class.
-        if (const ObjCObjectType *OI =3D
-              TDD->getUnderlyingType()->getAs<ObjCObjectType>())
-          PrevDecl =3D OI->getInterface();
+        // to the underlying class. Just ignore the forward class with a w=
arning
+        // as this will force the intended behavior which is to lookup the=
 typedef
+        // name.
+        if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
+          Diag(AtClassLoc, diag::warn_forward_class_redefinition) << Ident=
List[i];
+          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
+          continue;
+        }
       }
     }
-    ObjCInterfaceDecl *IDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(PrevD=
ecl);
-    if (!IDecl) {  // Not already seen?  Make a forward decl.
-      IDecl =3D ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
-                                        IdentList[i], IdentLocs[i], true);
-     =20
-      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it=
 to
-      // the current DeclContext.  This prevents clients that walk DeclCon=
text
-      // from seeing the imaginary ObjCInterfaceDecl until it is actually
-      // declared later (if at all).  We also take care to explicitly make
-      // sure this declaration is visible for name lookup.
-      PushOnScopeChains(IDecl, TUScope, false);
-      CurContext->makeDeclVisibleInContext(IDecl, true);
-    }
-    ObjCClassDecl *CDecl =3D ObjCClassDecl::Create(Context, CurContext, At=
ClassLoc,
-                                                 IDecl, IdentLocs[i]);
-    CurContext->addDecl(CDecl);
-    CheckObjCDeclScope(CDecl);
-    DeclsInGroup.push_back(CDecl);
+   =20
+    // Create a declaration to describe this forward declaration.
+    ObjCInterfaceDecl *PrevIDecl
+      =3D dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
+    ObjCInterfaceDecl *IDecl
+      =3D ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
+                                  IdentList[i], PrevIDecl, IdentLocs[i]);
+    IDecl->setAtEndRange(IdentLocs[i]);
+   =20
+    PushOnScopeChains(IDecl, TUScope);
+    CheckObjCDeclScope(IDecl);
+    DeclsInGroup.push_back(IDecl);
   }
  =20
   return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), fa=
lse);
@@ -1870,7 +1946,7 @@
                   left->getResultType(), right->getResultType()))
     return false;
=20
-  if (getLangOptions().ObjCAutoRefCount &&
+  if (getLangOpts().ObjCAutoRefCount &&
       (left->hasAttr<NSReturnsRetainedAttr>()
          !=3D right->hasAttr<NSReturnsRetainedAttr>() ||
        left->hasAttr<NSConsumesSelfAttr>()
@@ -1887,76 +1963,81 @@
     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
       return false;
=20
-    if (getLangOptions().ObjCAutoRefCount &&
+    if (getLangOpts().ObjCAutoRefCount &&
         lparm->hasAttr<NSConsumedAttr>() !=3D rparm->hasAttr<NSConsumedAtt=
r>())
       return false;
   }
   return true;
 }
=20
+void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Met=
hod) {
+  // If the list is empty, make it a singleton list.
+  if (List->Method =3D=3D 0) {
+    List->Method =3D Method;
+    List->Next =3D 0;
+    return;
+  }
+ =20
+  // We've seen a method with this name, see if we have already seen this =
type
+  // signature.
+  ObjCMethodList *Previous =3D List;
+  for (; List; Previous =3D List, List =3D List->Next) {
+    if (!MatchTwoMethodDeclarations(Method, List->Method))
+      continue;
+   =20
+    ObjCMethodDecl *PrevObjCMethod =3D List->Method;
+
+    // Propagate the 'defined' bit.
+    if (Method->isDefined())
+      PrevObjCMethod->setDefined(true);
+   =20
+    // If a method is deprecated, push it in the global pool.
+    // This is used for better diagnostics.
+    if (Method->isDeprecated()) {
+      if (!PrevObjCMethod->isDeprecated())
+        List->Method =3D Method;
+    }
+    // If new method is unavailable, push it into global pool
+    // unless previous one is deprecated.
+    if (Method->isUnavailable()) {
+      if (PrevObjCMethod->getAvailability() < AR_Deprecated)
+        List->Method =3D Method;
+    }
+   =20
+    return;
+  }
+ =20
+  // We have a new signature for an existing method - add it.
+  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
+  ObjCMethodList *Mem =3D BumpAlloc.Allocate<ObjCMethodList>();
+  Previous->Next =3D new (Mem) ObjCMethodList(Method, 0);
+}
+
 /// \brief Read the contents of the method pool for a given selector from
 /// external storage.
-///
-/// This routine should only be called once, when the method pool has no e=
ntry
-/// for this selector.
-Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
+void Sema::ReadMethodPool(Selector Sel) {
   assert(ExternalSource && "We need an external AST source");
-  assert(MethodPool.find(Sel) =3D=3D MethodPool.end() &&
-         "Selector data already loaded into the method pool");
-
-  // Read the method list from the external source.
-  GlobalMethods Methods =3D ExternalSource->ReadMethodPool(Sel);
-
-  return MethodPool.insert(std::make_pair(Sel, Methods)).first;
+  ExternalSource->ReadMethodPool(Sel);
 }
=20
 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
                                  bool instance) {
+  // Ignore methods of invalid containers.
+  if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
+    return;
+
+  if (ExternalSource)
+    ReadMethodPool(Method->getSelector());
+ =20
   GlobalMethodPool::iterator Pos =3D MethodPool.find(Method->getSelector()=
);
-  if (Pos =3D=3D MethodPool.end()) {
-    if (ExternalSource)
-      Pos =3D ReadMethodPool(Method->getSelector());
-    else
-      Pos =3D MethodPool.insert(std::make_pair(Method->getSelector(),
-                                             GlobalMethods())).first;
-  }
+  if (Pos =3D=3D MethodPool.end())
+    Pos =3D MethodPool.insert(std::make_pair(Method->getSelector(),
+                                           GlobalMethods())).first;
+ =20
   Method->setDefined(impl);
+ =20
   ObjCMethodList &Entry =3D instance ? Pos->second.first : Pos->second.sec=
ond;
-  if (Entry.Method =3D=3D 0) {
-    // Haven't seen a method with this selector name yet - add it.
-    Entry.Method =3D Method;
-    Entry.Next =3D 0;
-    return;
-  }
-
-  // We've seen a method with this name, see if we have already seen this =
type
-  // signature.
-  for (ObjCMethodList *List =3D &Entry; List; List =3D List->Next) {
-    bool match =3D MatchTwoMethodDeclarations(Method, List->Method);
-
-    if (match) {
-      ObjCMethodDecl *PrevObjCMethod =3D List->Method;
-      PrevObjCMethod->setDefined(impl);
-      // If a method is deprecated, push it in the global pool.
-      // This is used for better diagnostics.
-      if (Method->isDeprecated()) {
-        if (!PrevObjCMethod->isDeprecated())
-          List->Method =3D Method;
-      }
-      // If new method is unavailable, push it into global pool
-      // unless previous one is deprecated.
-      if (Method->isUnavailable()) {
-        if (PrevObjCMethod->getAvailability() < AR_Deprecated)
-          List->Method =3D Method;
-      }
-      return;
-    }
-  }
-
-  // We have a new signature for an existing method - add it.
-  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
-  ObjCMethodList *Mem =3D BumpAlloc.Allocate<ObjCMethodList>();
-  Entry.Next =3D new (Mem) ObjCMethodList(Method, Entry.Next);
+  addMethodToGlobalList(&Entry, Method);
 }
=20
 /// Determines if this is an "acceptable" loose mismatch in the global
@@ -1981,13 +2062,12 @@
 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
                                                bool receiverIdOrClass,
                                                bool warn, bool instance) {
+  if (ExternalSource)
+    ReadMethodPool(Sel);
+   =20
   GlobalMethodPool::iterator Pos =3D MethodPool.find(Sel);
-  if (Pos =3D=3D MethodPool.end()) {
-    if (ExternalSource)
-      Pos =3D ReadMethodPool(Sel);
-    else
-      return 0;
-  }
+  if (Pos =3D=3D MethodPool.end())
+    return 0;
=20
   ObjCMethodList &MethList =3D instance ? Pos->second.first : Pos->second.=
second;
=20
@@ -2014,14 +2094,14 @@
     // differences.  In ARC, however, we also need to check for loose
     // mismatches, because most of them are errors.
     if (!strictSelectorMatch ||
-        (issueDiagnostic && getLangOptions().ObjCAutoRefCount))
+        (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
       for (ObjCMethodList *Next =3D MethList.Next; Next; Next =3D Next->Ne=
xt) {
         // This checks if the methods differ in type mismatch.
         if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
                                         MMS_loose) &&
             !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
           issueDiagnostic =3D true;
-          if (getLangOptions().ObjCAutoRefCount)
+          if (getLangOpts().ObjCAutoRefCount)
             issueError =3D true;
           break;
         }
@@ -2120,15 +2200,39 @@
   }
 }
=20
+Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
+  switch (CurContext->getDeclKind()) {
+    case Decl::ObjCInterface:
+      return Sema::OCK_Interface;
+    case Decl::ObjCProtocol:
+      return Sema::OCK_Protocol;
+    case Decl::ObjCCategory:
+      if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
+        return Sema::OCK_ClassExtension;
+      else
+        return Sema::OCK_Category;
+    case Decl::ObjCImplementation:
+      return Sema::OCK_Implementation;
+    case Decl::ObjCCategoryImpl:
+      return Sema::OCK_CategoryImplementation;
+
+    default:
+      return Sema::OCK_None;
+  }
+}
+
 // Note: For class/category implemenations, allMethods/allProperties is
 // always null.
-void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
-                      Decl **allMethods, unsigned allNum,
-                      Decl **allProperties, unsigned pNum,
-                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
+Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
+                       Decl **allMethods, unsigned allNum,
+                       Decl **allProperties, unsigned pNum,
+                       DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
=20
-  if (!CurContext->isObjCContainer())
-    return;
+  if (getObjCContainerKind() =3D=3D Sema::OCK_None)
+    return 0;
+
+  assert(AtEnd.isValid() && "Invalid location for '@end'");
+
   ObjCContainerDecl *OCD =3D dyn_cast<ObjCContainerDecl>(CurContext);
   Decl *ClassDecl =3D cast<Decl>(OCD);
  =20
@@ -2137,15 +2241,6 @@
          || isa<ObjCProtocolDecl>(ClassDecl);
   bool checkIdenticalMethods =3D isa<ObjCImplementationDecl>(ClassDecl);
=20
-  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
-    // FIXME: This is wrong.  We shouldn't be pretending that there is
-    //  an '@end' in the declaration.
-    SourceLocation L =3D ClassDecl->getLocation();
-    AtEnd.setBegin(L);
-    AtEnd.setEnd(L);
-    Diag(L, diag::err_missing_atend);
-  }
- =20
   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
@@ -2167,8 +2262,14 @@
           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
         Method->setInvalidDecl();
       } else {
-        if (PrevMethod)
+        if (PrevMethod) {
           Method->setAsRedeclaration(PrevMethod);
+          if (!Context.getSourceManager().isInSystemHeader(
+                 Method->getLocation()))
+            Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
+              << Method->getDeclName();
+          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
+        }
         InsMap[Method->getSelector()] =3D Method;
         /// The following allows us to typecheck messages to "id".
         AddInstanceMethodToGlobalPool(Method);
@@ -2188,8 +2289,14 @@
         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
         Method->setInvalidDecl();
       } else {
-        if (PrevMethod)
+        if (PrevMethod) {
           Method->setAsRedeclaration(PrevMethod);
+          if (!Context.getSourceManager().isInSystemHeader(
+                 Method->getLocation()))
+            Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
+              << Method->getDeclName();
+          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
+        }
         ClsMap[Method->getSelector()] =3D Method;
         /// The following allows us to typecheck messages to "Class".
         AddFactoryMethodToGlobalPool(Method);
@@ -2265,11 +2372,39 @@
       AtomicPropertySetterGetterRules(IC, IDecl);
       DiagnoseOwningPropertyGetterSynthesis(IC);
  =20
-      if (LangOpts.ObjCNonFragileABI2)
+      bool HasRootClassAttr =3D IDecl->hasAttr<ObjCRootClassAttr>();
+      if (IDecl->getSuperClass() =3D=3D NULL) {
+        // This class has no superclass, so check that it has been marked =
with
+        // __attribute((objc_root_class)).
+        if (!HasRootClassAttr) {
+          SourceLocation DeclLoc(IDecl->getLocation());
+          SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc));
+          Diag(DeclLoc, diag::warn_objc_root_class_missing)
+            << IDecl->getIdentifier();
+          // See if NSObject is in the current scope, and if it is, suggest
+          // adding " : NSObject " to the class declaration.
+          NamedDecl *IF =3D LookupSingleName(TUScope,
+                                           NSAPIObj->getNSClassId(NSAPI::C=
lassId_NSObject),
+                                           DeclLoc, LookupOrdinaryName);
+          ObjCInterfaceDecl *NSObjectDecl =3D dyn_cast_or_null<ObjCInterfa=
ceDecl>(IF);
+          if (NSObjectDecl && NSObjectDecl->getDefinition()) {
+            Diag(SuperClassLoc, diag::note_objc_needs_superclass)
+              << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
+          } else {
+            Diag(SuperClassLoc, diag::note_objc_needs_superclass);
+          }
+        }
+      } else if (HasRootClassAttr) {
+        // Complain that only root classes may have this attribute.
+        Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
+      }
+
+      if (LangOpts.ObjCNonFragileABI2) {
         while (IDecl->getSuperClass()) {
           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
           IDecl =3D IDecl->getSuperClass();
         }
+      }
     }
     SetIvarInitializers(IC);
   } else if (ObjCCategoryImplDecl* CatImplClass =3D
@@ -2300,6 +2435,15 @@
     }
   }
   ActOnObjCContainerFinishDefinition();
+
+  for (unsigned i =3D 0; i !=3D tuvNum; i++) {
+    DeclGroupRef DG =3D allTUVars[i].getAsVal<DeclGroupRef>();
+    for (DeclGroupRef::iterator I =3D DG.begin(), E =3D DG.end(); I !=3D E=
; ++I)
+      (*I)->setTopLevelDeclInObjCContainer();
+    Consumer.HandleTopLevelDeclInObjCContainer(DG);
+  }
+
+  return ClassDecl;
 }
=20
=20
@@ -2311,13 +2455,36 @@
 }
=20
 static inline
-bool containsInvalidMethodImplAttribute(const AttrVec &A) {
-  // The 'ibaction' attribute is allowed on method definitions because of
-  // how the IBAction macro is used on both method declarations and defini=
tions.
-  // If the method definitions contains any other attributes, return true.
-  for (AttrVec::const_iterator i =3D A.begin(), e =3D A.end(); i !=3D e; +=
+i)
-    if ((*i)->getKind() !=3D attr::IBAction)
+bool containsInvalidMethodImplAttribute(ObjCMethodDecl *IMD,
+                                        const AttrVec &A) {
+  // If method is only declared in implementation (private method),
+  // No need to issue any diagnostics on method definition with attributes.
+  if (!IMD)
+    return false;
+
+  // method declared in interface has no attribute.=20
+  // But implementation has attributes. This is invalid
+  if (!IMD->hasAttrs())
+    return true;
+
+  const AttrVec &D =3D IMD->getAttrs();
+  if (D.size() !=3D A.size())
+    return true;
+
+  // attributes on method declaration and definition must match exactly.
+  // Note that we have at most a couple of attributes on methods, so this
+  // n*n search is good enough.
+  for (AttrVec::const_iterator i =3D A.begin(), e =3D A.end(); i !=3D e; +=
+i) {
+    bool match =3D false;
+    for (AttrVec::const_iterator i1 =3D D.begin(), e1 =3D D.end(); i1 !=3D=
 e1; ++i1) {
+      if ((*i)->getKind() =3D=3D (*i1)->getKind()) {
+        match =3D true;
+        break;
+      }
+    }
+    if (!match)
       return true;
+  }
   return false;
 }
=20
@@ -2352,7 +2519,7 @@
       if (ObjCInterfaceDecl *ResultClass=20
                                       =3D ResultObjectType->getInterfaceDe=
cl()) {
         //   - it is the same as the method's class type, or
-        if (CurrentClass =3D=3D ResultClass)
+        if (declaresSameEntity(CurrentClass, ResultClass))
           return RTC_Compatible;
        =20
         //   - it is a superclass of the method's class type
@@ -2373,10 +2540,11 @@
 /// A helper class for searching for methods which a particular method
 /// overrides.
 class OverrideSearch {
+public:
   Sema &S;
   ObjCMethodDecl *Method;
-  llvm::SmallPtrSet<ObjCContainerDecl*, 8> Searched;
-  llvm::SmallPtrSet<ObjCMethodDecl*, 8> Overridden;
+  llvm::SmallPtrSet<ObjCContainerDecl*, 128> Searched;
+  llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
   bool Recursive;
=20
 public:
@@ -2388,7 +2556,11 @@
     Sema::GlobalMethodPool::iterator it =3D S.MethodPool.find(selector);
     if (it =3D=3D S.MethodPool.end()) {
       if (!S.ExternalSource) return;
-      it =3D S.ReadMethodPool(selector);
+      S.ReadMethodPool(selector);
+     =20
+      it =3D S.MethodPool.find(selector);
+      if (it =3D=3D S.MethodPool.end())
+        return;
     }
     ObjCMethodList &list =3D
       method->isInstanceMethod() ? it->second.first : it->second.second;
@@ -2404,7 +2576,7 @@
     searchFromContainer(container);
   }
=20
-  typedef llvm::SmallPtrSet<ObjCMethodDecl*,8>::iterator iterator;
+  typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
   iterator begin() const { return Overridden.begin(); }
   iterator end() const { return Overridden.end(); }
=20
@@ -2426,6 +2598,9 @@
   }
=20
   void searchFrom(ObjCProtocolDecl *protocol) {
+    if (!protocol->hasDefinition())
+      return;
+   =20
     // A method in a protocol declaration overrides declarations from
     // referenced ("parent") protocols.
     search(protocol->getReferencedProtocols());
@@ -2453,7 +2628,9 @@
=20
   void searchFrom(ObjCInterfaceDecl *iface) {
     // A method in a class declaration overrides declarations from
-
+    if (!iface->hasDefinition())
+      return;
+   =20
     //   - categories,
     for (ObjCCategoryDecl *category =3D iface->getCategoryList();
            category; category =3D category->getNextClassCategory())
@@ -2606,6 +2783,10 @@
     // Apply the attributes to the parameter.
     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
=20
+    if (Param->hasAttr<BlocksAttr>()) {
+      Diag(Param->getLocation(), diag::err_block_on_nonlocal);
+      Param->setInvalidDecl();
+    }
     S->AddDecl(Param);
     IdResolver.AddDecl(Param);
=20
@@ -2649,9 +2830,19 @@
       ImpDecl->addClassMethod(ObjCMethod);
     }
=20
+    ObjCMethodDecl *IMD =3D 0;
+    if (ObjCInterfaceDecl *IDecl =3D ImpDecl->getClassInterface())
+      IMD =3D IDecl->lookupMethod(ObjCMethod->getSelector(),=20
+                                ObjCMethod->isInstanceMethod());
     if (ObjCMethod->hasAttrs() &&
-        containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
-      Diag(EndLoc, diag::warn_attribute_method_def);
+        containsInvalidMethodImplAttribute(IMD, ObjCMethod->getAttrs())) {
+      SourceLocation MethodLoc =3D IMD->getLocation();
+      if (!getSourceManager().isInSystemHeader(MethodLoc)) {
+        Diag(EndLoc, diag::warn_attribute_method_def);
+        Diag(MethodLoc, diag::note_method_declared_at)
+          << ObjCMethod->getDeclName();
+      }
+    }
   } else {
     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
   }
@@ -2701,7 +2892,7 @@
   }
  =20
   bool ARCError =3D false;
-  if (getLangOptions().ObjCAutoRefCount)
+  if (getLangOpts().ObjCAutoRefCount)
     ARCError =3D CheckARCMethodDecl(*this, ObjCMethod);
=20
   // Infer the related result type when possible.
@@ -2741,13 +2932,15 @@
 }
=20
 bool Sema::CheckObjCDeclScope(Decl *D) {
-  if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
-    return false;
   // Following is also an error. But it is caused by a missing @end
   // and diagnostic is issued elsewhere.
-  if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) {
+  if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
     return false;
-  }
+
+  // If we switched context to translation unit while we are still lexical=
ly in
+  // an objc container, it means the parser missed emitting an error.
+  if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
+    return false;
  =20
   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_sc=
ope);
   D->setInvalidDecl();
@@ -2790,7 +2983,7 @@
   for (SmallVectorImpl<Decl*>::iterator D =3D Decls.begin();
        D !=3D Decls.end(); ++D) {
     FieldDecl *FD =3D cast<FieldDecl>(*D);
-    if (getLangOptions().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       PushOnScopeChains(cast<FieldDecl>(FD), S);
     else if (RecordDecl *Record =3D dyn_cast<RecordDecl>(TagD))
       Record->addDecl(FD);
@@ -2830,6 +3023,10 @@
                                  T, TInfo, SC_None, SC_None);
   New->setExceptionVariable(true);
  =20
+  // In ARC, infer 'retaining' for variables of retainable type.
+  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
+    Invalid =3D true;
+
   if (Invalid)
     New->setInvalidDecl();
   return New;
@@ -2855,7 +3052,7 @@
  =20
   // Check that there are no default arguments inside the type of this
   // exception object (C++ only).
-  if (getLangOptions().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     CheckExtraCXXDefaultArguments(D);
  =20
   TypeSourceInfo *TInfo =3D GetTypeForDeclarator(D, S);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaExceptionSpec.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaExceptionSpec.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaExceptionSpec.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
=20
 namespace clang {
=20
@@ -101,7 +102,7 @@
   bool MissingExceptionSpecification =3D false;
   bool MissingEmptyExceptionSpecification =3D false;
   unsigned DiagID =3D diag::err_mismatched_exception_spec;
-  if (getLangOptions().MicrosoftExt)
+  if (getLangOpts().MicrosoftExt)
     DiagID =3D diag::warn_mismatched_exception_spec;=20
  =20
   if (!CheckEquivalentExceptionSpec(PDiag(DiagID),
@@ -170,7 +171,7 @@
=20
     // If exceptions are disabled, suppress the warning about missing
     // exception specifications for new and delete operators.
-    if (!getLangOptions().CXXExceptions) {
+    if (!getLangOpts().CXXExceptions) {
       switch (New->getDeclName().getCXXOverloadedOperator()) {
       case OO_New:
       case OO_Array_New:
@@ -186,7 +187,7 @@
     }=20
=20
     // Warn about the lack of exception specification.
-    llvm::SmallString<128> ExceptionSpecString;
+    SmallString<128> ExceptionSpecString;
     llvm::raw_svector_ostream OS(ExceptionSpecString);
     switch (OldProto->getExceptionSpecType()) {
     case EST_DynamicNone:
@@ -264,7 +265,7 @@
     const FunctionProtoType *Old, SourceLocation OldLoc,
     const FunctionProtoType *New, SourceLocation NewLoc) {
   unsigned DiagID =3D diag::err_mismatched_exception_spec;
-  if (getLangOptions().MicrosoftExt)
+  if (getLangOpts().MicrosoftExt)
     DiagID =3D diag::warn_mismatched_exception_spec;=20
   return CheckEquivalentExceptionSpec(
                                       PDiag(DiagID),
@@ -285,7 +286,7 @@
                                         bool AllowNoexceptAllMatchWithNoSp=
ec,
                                         bool IsOperatorNew) {
   // Just completely ignore this under -fno-exceptions.
-  if (!getLangOptions().CXXExceptions)
+  if (!getLangOpts().CXXExceptions)
     return false;
=20
   if (MissingExceptionSpecification)
@@ -379,7 +380,7 @@
   // As a special compatibility feature, under C++0x we accept no spec and
   // throw(std::bad_alloc) as equivalent for operator new and operator new=
[].
   // This is because the implicit declaration changed, but old code would =
break.
-  if (getLangOptions().CPlusPlus0x && IsOperatorNew) {
+  if (getLangOpts().CPlusPlus0x && IsOperatorNew) {
     const FunctionProtoType *WithExceptions =3D 0;
     if (OldEST =3D=3D EST_None && NewEST =3D=3D EST_Dynamic)
       WithExceptions =3D New;
@@ -473,7 +474,7 @@
     const FunctionProtoType *Subset, SourceLocation SubLoc) {
=20
   // Just auto-succeed under -fno-exceptions.
-  if (!getLangOptions().CXXExceptions)
+  if (!getLangOpts().CXXExceptions)
     return false;
=20
   // FIXME: As usual, we could be more specific in our error messages, but
@@ -611,10 +612,8 @@
       case AR_inaccessible: continue;
       case AR_dependent:
         llvm_unreachable("access check dependent for unprivileged context"=
);
-        break;
       case AR_delayed:
         llvm_unreachable("access check delayed in non-declaration");
-        break;
       }
=20
       Contained =3D true;
@@ -703,7 +702,7 @@
=20
 bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
                                                 const CXXMethodDecl *Old) {
-  if (getLangOptions().CPlusPlus0x && isa<CXXDestructorDecl>(New)) {
+  if (getLangOpts().CPlusPlus0x && isa<CXXDestructorDecl>(New)) {
     // Don't check uninstantiated template destructors at all. We can only
     // synthesize correct specs after the template is instantiated.
     if (New->getParent()->isDependentType())
@@ -717,7 +716,7 @@
     }
   }
   unsigned DiagID =3D diag::err_override_exception_spec;
-  if (getLangOptions().MicrosoftExt)
+  if (getLangOpts().MicrosoftExt)
     DiagID =3D diag::warn_override_exception_spec;
   return CheckExceptionSpecSubset(PDiag(DiagID),
                                   PDiag(diag::note_overridden_virtual_func=
tion),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaExpr.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -12,10 +12,13 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/Sema/SemaInternal.h"
+#include "clang/Sema/DelayedDiagnostic.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
+#include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/AnalysisBasedWarnings.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTMutationListener.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/DeclObjC.h"
@@ -38,6 +41,7 @@
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Sema/SemaFixItUtils.h"
 #include "clang/Sema/Template.h"
+#include "TreeTransform.h"
 using namespace clang;
 using namespace sema;
=20
@@ -53,6 +57,12 @@
     if (FD->isDeleted())
       return false;
   }
+
+  // See if this function is unavailable.
+  if (D->getAvailability() =3D=3D AR_Unavailable &&
+      cast<Decl>(CurContext)->getAvailability() !=3D AR_Unavailable)
+    return false;
+
   return true;
 }
=20
@@ -62,6 +72,13 @@
   // See if this declaration is unavailable or deprecated.
   std::string Message;
   AvailabilityResult Result =3D D->getAvailability(&Message);
+  if (const EnumConstantDecl *ECD =3D dyn_cast<EnumConstantDecl>(D))
+    if (Result =3D=3D AR_Available) {
+      const DeclContext *DC =3D ECD->getDeclContext();
+      if (const EnumDecl *TheEnumDecl =3D dyn_cast<EnumDecl>(DC))
+        Result =3D TheEnumDecl->getAvailability(&Message);
+    }
+ =20
   switch (Result) {
     case AR_Available:
     case AR_NotYetIntroduced:
@@ -91,6 +108,28 @@
     return Result;
 }
=20
+/// \brief Emit a note explaining that this function is deleted or unavail=
able.
+void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
+  CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(Decl);
+
+  if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
+    // If the method was explicitly defaulted, point at that declaration.
+    if (!Method->isImplicit())
+      Diag(Decl->getLocation(), diag::note_implicitly_deleted);
+
+    // Try to diagnose why this special member function was implicitly
+    // deleted. This might fail, if that reason no longer applies.
+    CXXSpecialMember CSM =3D getSpecialMember(Method);
+    if (CSM !=3D CXXInvalid)
+      ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=3D*/true);
+
+    return;
+  }
+
+  Diag(Decl->getLocation(), diag::note_unavailable_here)
+    << 1 << Decl->isDeleted();
+}
+
 /// \brief Determine whether the use of this declaration is valid, and
 /// emit any corresponding diagnostics.
 ///
@@ -105,7 +144,7 @@
 ///
 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
                              const ObjCInterfaceDecl *UnknownObjCClass) {
-  if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
+  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
     // If there were any diagnostics suppressed by template argument deduc=
tion,
     // emit them now.
     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
@@ -134,26 +173,15 @@
   if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
     if (FD->isDeleted()) {
       Diag(Loc, diag::err_deleted_function_use);
-      Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
+      NoteDeletedFunction(FD);
       return true;
     }
   }
-  AvailabilityResult Result =3D
-    DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
+  DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
=20
   // Warn if this is used but marked unused.
   if (D->hasAttr<UnusedAttr>())
     Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
-  // For available enumerator, it will become unavailable/deprecated
-  // if its enum declaration is as such.
-  if (Result =3D=3D AR_Available)
-    if (const EnumConstantDecl *ECD =3D dyn_cast<EnumConstantDecl>(D)) {
-      const DeclContext *DC =3D ECD->getDeclContext();
-      if (const EnumDecl *TheEnumDecl =3D dyn_cast<EnumDecl>(DC))
-        DiagnoseAvailabilityOfDecl(*this,
-                          const_cast< EnumDecl *>(TheEnumDecl),=20
-                          Loc, UnknownObjCClass);
-    }
   return false;
 }
=20
@@ -243,17 +271,7 @@
   Expr *sentinelExpr =3D args[numArgs - numArgsAfterSentinel - 1];
   if (!sentinelExpr) return;
   if (sentinelExpr->isValueDependent()) return;
-
-  // nullptr_t is always treated as null.
-  if (sentinelExpr->getType()->isNullPtrType()) return;
-
-  if (sentinelExpr->getType()->isAnyPointerType() &&
-      sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
-                                            Expr::NPC_ValueDependentIsNull=
))
-    return;
-
-  // Unfortunately, __null has type 'int'.
-  if (isa<GNUNullExpr>(sentinelExpr)) return;
+  if (Context.isSentinelNullExpr(sentinelExpr)) return;
=20
   // Pick a reasonable string to insert.  Optimistically use 'nil' or
   // 'NULL' if those are actually defined in the context.  Only use
@@ -314,7 +332,7 @@
     // An lvalue or rvalue of type "array of N T" or "array of unknown bou=
nd of
     // T" can be converted to an rvalue of type "pointer to T".
     //
-    if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue(=
))
+    if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
       E =3D ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
                             CK_ArrayToPointerDecay).take();
   }
@@ -356,23 +374,9 @@
   QualType T =3D E->getType();
   assert(!T.isNull() && "r-value conversion on typeless expression?");
=20
-  // We can't do lvalue-to-rvalue on atomics yet.
-  if (T->getAs<AtomicType>())
-    return Owned(E);
-
-  // Create a load out of an ObjCProperty l-value, if necessary.
-  if (E->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Res =3D ConvertPropertyForRValue(E);
-    if (Res.isInvalid())
-      return Owned(E);
-    E =3D Res.take();
-    if (!E->isGLValue())
-      return Owned(E);
-  }
-
   // We don't want to throw lvalue-to-rvalue casts on top of
   // expressions of certain types in C++.
-  if (getLangOptions().CPlusPlus &&
+  if (getLangOpts().CPlusPlus &&
       (E->getType() =3D=3D Context.OverloadTy ||
        T->isDependentType() ||
        T->isRecordType()))
@@ -400,9 +404,20 @@
   if (T.hasQualifiers())
     T =3D T.getUnqualifiedType();
=20
+  UpdateMarkingForLValueToRValue(E);
+
   ExprResult Res =3D Owned(ImplicitCastExpr::Create(Context, T, CK_LValueT=
oRValue,
                                                   E, 0, VK_RValue));
=20
+  // C11 6.3.2.1p2:
+  //   ... if the lvalue has atomic type, the value has the non-atomic ver=
sion=20
+  //   of the type of the lvalue ...
+  if (const AtomicType *Atomic =3D T->getAs<AtomicType>()) {
+    T =3D Atomic->getValueType().getUnqualifiedType();
+    Res =3D Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomi=
c,
+                                         Res.get(), 0, VK_RValue));
+  }
+ =20
   return Res;
 }
=20
@@ -495,7 +510,7 @@
   //     is a prvalue for the temporary.
   // FIXME: add some way to gate this entire thing for correctness in
   // potentially potentially evaluated contexts.
-  if (getLangOptions().CPlusPlus && E->isGLValue() &&=20
+  if (getLangOpts().CPlusPlus && E->isGLValue() &&=20
       ExprEvalContexts.back().Context !=3D Unevaluated) {
     ExprResult Temp =3D PerformCopyInitialization(
                        InitializedEntity::InitializeTemporary(E->getType()=
),
@@ -514,11 +529,23 @@
 /// interfaces passed by value.
 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallTyp=
e CT,
                                                   FunctionDecl *FDecl) {
-  ExprResult ExprRes =3D CheckPlaceholderExpr(E);
-  if (ExprRes.isInvalid())
-    return ExprError();
+  if (const BuiltinType *PlaceholderTy =3D E->getType()->getAsPlaceholderT=
ype()) {
+    // Strip the unbridged-cast placeholder expression off, if applicable.
+    if (PlaceholderTy->getKind() =3D=3D BuiltinType::ARCUnbridgedCast &&
+        (CT =3D=3D VariadicMethod ||
+         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
+      E =3D stripARCUnbridgedCast(E);
+
+    // Otherwise, do normal placeholder checking.
+    } else {
+      ExprResult ExprRes =3D CheckPlaceholderExpr(E);
+      if (ExprRes.isInvalid())
+        return ExprError();
+      E =3D ExprRes.take();
+    }
+  }
  =20
-  ExprRes =3D DefaultArgumentPromotion(E);
+  ExprResult ExprRes =3D DefaultArgumentPromotion(E);
   if (ExprRes.isInvalid())
     return ExprError();
   E =3D ExprRes.take();
@@ -540,17 +567,21 @@
     //   or a non-trivial destructor, with no corresponding parameter,=20
     //   is conditionally-supported with implementation-defined semantics.
     bool TrivialEnough =3D false;
-    if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) =
 {
+    if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType())  {
       if (CXXRecordDecl *Record =3D E->getType()->getAsCXXRecordDecl()) {
         if (Record->hasTrivialCopyConstructor() &&
             Record->hasTrivialMoveConstructor() &&
-            Record->hasTrivialDestructor())
+            Record->hasTrivialDestructor()) {
+          DiagRuntimeBehavior(E->getLocStart(), 0,
+            PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
+              << E->getType() << CT);
           TrivialEnough =3D true;
+        }
       }
     }
=20
     if (!TrivialEnough &&
-        getLangOptions().ObjCAutoRefCount &&
+        getLangOpts().ObjCAutoRefCount &&
         E->getType()->isObjCLifetimeType())
       TrivialEnough =3D true;
      =20
@@ -558,14 +589,16 @@
       // Nothing to diagnose. This is okay.
     } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
                           PDiag(diag::warn_cannot_pass_non_pod_arg_to_vara=
rg)
-                            << getLangOptions().CPlusPlus0x << E->getType(=
)=20
+                            << getLangOpts().CPlusPlus0x << E->getType()=20
                             << CT)) {
       // Turn this into a trap.
       CXXScopeSpec SS;
+      SourceLocation TemplateKWLoc;
       UnqualifiedId Name;
       Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
                          E->getLocStart());
-      ExprResult TrapFn =3D ActOnIdExpression(TUScope, SS, Name, true, fal=
se);
+      ExprResult TrapFn =3D ActOnIdExpression(TUScope, SS, TemplateKWLoc, =
Name,
+                                            true, false);
       if (TrapFn.isInvalid())
         return ExprError();
=20
@@ -581,6 +614,11 @@
       E =3D Comma.get();
     }
   }
+  // c++ rules are enforced elsewhere.
+  if (!getLangOpts().CPlusPlus &&
+      RequireCompleteType(E->getExprLoc(), E->getType(),
+                          diag::err_call_incomplete_argument))
+    return ExprError();
  =20
   return Owned(E);
 }
@@ -811,14 +849,21 @@
=20
   if (LHSComplexInt) {
     // int -> _Complex int
+    // FIXME: This needs to take integer ranks into account
+    RHS =3D S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(=
),
+                              CK_IntegralCast);
     RHS =3D S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComp=
lex);
     return LHSType;
   }
=20
   assert(RHSComplexInt);
   // int -> _Complex int
-  if (!IsCompAssign)
+  // FIXME: This needs to take integer ranks into account
+  if (!IsCompAssign) {
+    LHS =3D S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(=
),
+                              CK_IntegralCast);
     LHS =3D S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComp=
lex);
+  }
   return RHSType;
 }
=20
@@ -999,7 +1044,7 @@
       if (Types[i]->getType()->isDependentType()) {
         IsResultDependent =3D true;
       } else {
-        // C1X 6.5.1.1p2 "The type name in a generic association shall spe=
cify a
+        // C11 6.5.1.1p2 "The type name in a generic association shall spe=
cify a
         // complete object type other than a variably modified type."
         unsigned D =3D 0;
         if (Types[i]->getType()->isIncompleteType())
@@ -1016,7 +1061,7 @@
           TypeErrorFound =3D true;
         }
=20
-        // C1X 6.5.1.1p2 "No two generic associations in the same generic
+        // C11 6.5.1.1p2 "No two generic associations in the same generic
         // selection shall specify compatible types."
         for (unsigned j =3D i+1; j < NumAssocs; ++j)
           if (Types[j] && !Types[j]->getType()->isDependentType() &&
@@ -1057,7 +1102,7 @@
       CompatIndices.push_back(i);
   }
=20
-  // C1X 6.5.1.1p2 "The controlling expression of a generic selection shal=
l have
+  // C11 6.5.1.1p2 "The controlling expression of a generic selection shal=
l have
   // type compatible with at most one of the types named in its generic
   // association list."
   if (CompatIndices.size() > 1) {
@@ -1077,7 +1122,7 @@
     return ExprError();
   }
=20
-  // C1X 6.5.1.1p2 "If a generic selection has no default generic associat=
ion,
+  // C11 6.5.1.1p2 "If a generic selection has no default generic associat=
ion,
   // its controlling expression shall have type compatible with exactly on=
e of
   // the types named in its generic association list."
   if (DefaultIndex =3D=3D -1U && CompatIndices.size() =3D=3D 0) {
@@ -1089,7 +1134,7 @@
     return ExprError();
   }
=20
-  // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
+  // C11 6.5.1.1p3 "If a generic selection has a generic association with a
   // type name that is compatible with the type of the controlling express=
ion,
   // then the result expression of the generic selection is the expression
   // in that generic association. Otherwise, the result expression of the
@@ -1104,6 +1149,43 @@
                  ResultIndex));
 }
=20
+/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
+/// location of the token and the offset of the ud-suffix within it.
+static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
+                                     unsigned Offset) {
+  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager=
(),
+                                        S.getLangOpts());
+}
+
+/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Loo=
k up
+/// the corresponding cooked (non-raw) literal operator, and build a call =
to it.
+static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
+                                                 IdentifierInfo *UDSuffix,
+                                                 SourceLocation UDSuffixLo=
c,
+                                                 ArrayRef<Expr*> Args,
+                                                 SourceLocation LitEndLoc)=
 {
+  assert(Args.size() <=3D 2 && "too many arguments for literal operator");
+
+  QualType ArgTy[2];
+  for (unsigned ArgIdx =3D 0; ArgIdx !=3D Args.size(); ++ArgIdx) {
+    ArgTy[ArgIdx] =3D Args[ArgIdx]->getType();
+    if (ArgTy[ArgIdx]->isArrayType())
+      ArgTy[ArgIdx] =3D S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
+  }
+
+  DeclarationName OpName =3D
+    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
+  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
+  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
+
+  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
+  if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.siz=
e()),
+                              /*AllowRawAndTemplate*/false) =3D=3D Sema::L=
OLR_Error)
+    return ExprError();
+
+  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
+}
+
 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle =
string
 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come fr=
om
@@ -1111,7 +1193,8 @@
 /// string.
 ///
 ExprResult
-Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
+Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
+                         Scope *UDLScope) {
   assert(NumStringToks && "Must have at least one string!");
=20
   StringLiteralParser Literal(StringToks, NumStringToks, PP);
@@ -1129,7 +1212,7 @@
     StrTy =3D Context.Char16Ty;
   else if (Literal.isUTF32())
     StrTy =3D Context.Char32Ty;
-  else if (Literal.Pascal)
+  else if (Literal.isPascal())
     StrTy =3D Context.UnsignedCharTy;
=20
   StringLiteral::StringKind Kind =3D StringLiteral::Ascii;
@@ -1143,7 +1226,7 @@
     Kind =3D StringLiteral::UTF32;
=20
   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1=
).
-  if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
+  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
     StrTy.addConst();
=20
   // Get an array type for the string, according to C99 6.4.5.  This inclu=
des
@@ -1154,243 +1237,32 @@
                                        ArrayType::Normal, 0);
=20
   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
-  return Owned(StringLiteral::Create(Context, Literal.GetString(),
-                                     Kind, Literal.Pascal, StrTy,
-                                     &StringTokLocs[0],
-                                     StringTokLocs.size()));
-}
-
-enum CaptureResult {
-  /// No capture is required.
-  CR_NoCapture,
-
-  /// A capture is required.
-  CR_Capture,
-
-  /// A by-ref capture is required.
-  CR_CaptureByRef,
-
-  /// An error occurred when trying to capture the given variable.
-  CR_Error
-};
-
-/// Diagnose an uncapturable value reference.
-///
-/// \param var - the variable referenced
-/// \param DC - the context which we couldn't capture through
-static CaptureResult
-diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
-                                   VarDecl *var, DeclContext *DC) {
-  switch (S.ExprEvalContexts.back().Context) {
-  case Sema::Unevaluated:
-    // The argument will never be evaluated, so don't complain.
-    return CR_NoCapture;
-
-  case Sema::PotentiallyEvaluated:
-  case Sema::PotentiallyEvaluatedIfUsed:
-    break;
-
-  case Sema::PotentiallyPotentiallyEvaluated:
-    // FIXME: delay these!
-    break;
-  }
-
-  // Don't diagnose about capture if we're not actually in code right
-  // now; in general, there are more appropriate places that will
-  // diagnose this.
-  if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
-
-  // Certain madnesses can happen with parameter declarations, which
-  // we want to ignore.
-  if (isa<ParmVarDecl>(var)) {
-    // - If the parameter still belongs to the translation unit, then
-    //   we're actually just using one parameter in the declaration of
-    //   the next.  This is useful in e.g. VLAs.
-    if (isa<TranslationUnitDecl>(var->getDeclContext()))
-      return CR_NoCapture;
-
-    // - This particular madness can happen in ill-formed default
-    //   arguments; claim it's okay and let downstream code handle it.
-    if (S.CurContext =3D=3D var->getDeclContext()->getParent())
-      return CR_NoCapture;
-  }
-
-  DeclarationName functionName;
-  if (FunctionDecl *fn =3D dyn_cast<FunctionDecl>(var->getDeclContext()))
-    functionName =3D fn->getDeclName();
-  // FIXME: variable from enclosing block that we couldn't capture from!
-
-  S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
-    << var->getIdentifier() << functionName;
-  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
-    << var->getIdentifier();
-
-  return CR_Error;
-}
-
-/// There is a well-formed capture at a particular scope level;
-/// propagate it through all the nested blocks.
-static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
-                                      const BlockDecl::Capture &Capture) {
-  VarDecl *var =3D Capture.getVariable();
-
-  // Update all the inner blocks with the capture information.
-  for (unsigned i =3D ValidScopeIndex + 1, e =3D S.FunctionScopes.size();
-         i !=3D e; ++i) {
-    BlockScopeInfo *innerBlock =3D cast<BlockScopeInfo>(S.FunctionScopes[i=
]);
-    innerBlock->Captures.push_back(
-      BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
-                         /*nested*/ true, Capture.getCopyExpr()));
-    innerBlock->CaptureMap[var] =3D innerBlock->Captures.size(); // +1
-  }
-
-  return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
-}
-
-/// shouldCaptureValueReference - Determine if a reference to the
-/// given value in the current context requires a variable capture.
-///
-/// This also keeps the captures set in the BlockScopeInfo records
-/// up-to-date.
-static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation l=
oc,
-                                                 ValueDecl *Value) {
-  // Only variables ever require capture.
-  VarDecl *var =3D dyn_cast<VarDecl>(Value);
-  if (!var) return CR_NoCapture;
-
-  // Fast path: variables from the current context never require capture.
-  DeclContext *DC =3D S.CurContext;
-  if (var->getDeclContext() =3D=3D DC) return CR_NoCapture;
-
-  // Only variables with local storage require capture.
-  // FIXME: What about 'const' variables in C++?
-  if (!var->hasLocalStorage()) return CR_NoCapture;
-
-  // Otherwise, we need to capture.
-
-  unsigned functionScopesIndex =3D S.FunctionScopes.size() - 1;
-  do {
-    // Only blocks (and eventually C++0x closures) can capture; other
-    // scopes don't work.
-    if (!isa<BlockDecl>(DC))
-      return diagnoseUncapturableValueReference(S, loc, var, DC);
-
-    BlockScopeInfo *blockScope =3D
-      cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
-    assert(blockScope->TheDecl =3D=3D static_cast<BlockDecl*>(DC));
-
-    // Check whether we've already captured it in this block.  If so,
-    // we're done.
-    if (unsigned indexPlus1 =3D blockScope->CaptureMap[var])
-      return propagateCapture(S, functionScopesIndex,
-                              blockScope->Captures[indexPlus1 - 1]);
-
-    functionScopesIndex--;
-    DC =3D cast<BlockDecl>(DC)->getDeclContext();
-  } while (var->getDeclContext() !=3D DC);
-
-  // Okay, we descended all the way to the block that defines the variable.
-  // Actually try to capture it.
-  QualType type =3D var->getType();
-
-  // Prohibit variably-modified types.
-  if (type->isVariablyModifiedType()) {
-    S.Diag(loc, diag::err_ref_vm_type);
-    S.Diag(var->getLocation(), diag::note_declared_at);
-    return CR_Error;
-  }
-
-  // Prohibit arrays, even in __block variables, but not references to
-  // them.
-  if (type->isArrayType()) {
-    S.Diag(loc, diag::err_ref_array_type);
-    S.Diag(var->getLocation(), diag::note_declared_at);
-    return CR_Error;
-  }
-
-  S.MarkDeclarationReferenced(loc, var);
-
-  // The BlocksAttr indicates the variable is bound by-reference.
-  bool byRef =3D var->hasAttr<BlocksAttr>();
-
-  // Build a copy expression.
-  Expr *copyExpr =3D 0;
-  const RecordType *rtype;
-  if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
-      (rtype =3D type->getAs<RecordType>())) {
-
-    // The capture logic needs the destructor, so make sure we mark it.
-    // Usually this is unnecessary because most local variables have
-    // their destructors marked at declaration time, but parameters are
-    // an exception because it's technically only the call site that
-    // actually requires the destructor.
-    if (isa<ParmVarDecl>(var))
-      S.FinalizeVarWithDestructor(var, rtype);
-
-    // According to the blocks spec, the capture of a variable from
-    // the stack requires a const copy constructor.  This is not true
-    // of the copy/move done to move a __block variable to the heap.
-    type.addConst();
-
-    Expr *declRef =3D new (S.Context) DeclRefExpr(var, type, VK_LValue, lo=
c);
-    ExprResult result =3D
-      S.PerformCopyInitialization(
-                      InitializedEntity::InitializeBlock(var->getLocation(=
),
-                                                         type, false),
-                                  loc, S.Owned(declRef));
-
-    // Build a full-expression copy expression if initialization
-    // succeeded and used a non-trivial constructor.  Recover from
-    // errors by pretending that the copy isn't necessary.
-    if (!result.isInvalid() &&
-        !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial=
()) {
-      result =3D S.MaybeCreateExprWithCleanups(result);
-      copyExpr =3D result.take();
-    }
-  }
-
-  // We're currently at the declarer; go back to the closure.
-  functionScopesIndex++;
-  BlockScopeInfo *blockScope =3D
-    cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
-
-  // Build a valid capture in this scope.
-  blockScope->Captures.push_back(
-                 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr=
));
-  blockScope->CaptureMap[var] =3D blockScope->Captures.size(); // +1
-
-  // Propagate that to inner captures if necessary.
-  return propagateCapture(S, functionScopesIndex,
-                          blockScope->Captures.back());
-}
-
-static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
-                                        const DeclarationNameInfo &NameInf=
o,
-                                        bool ByRef) {
-  assert(isa<VarDecl>(VD) && "capturing non-variable");
-
-  VarDecl *var =3D cast<VarDecl>(VD);
-  assert(var->hasLocalStorage() && "capturing non-local");
-  assert(ByRef =3D=3D var->hasAttr<BlocksAttr>() && "byref set wrong");
-
-  QualType exprType =3D var->getType().getNonReferenceType();
-
-  BlockDeclRefExpr *BDRE;
-  if (!ByRef) {
-    // The variable will be bound by copy; make it const within the
-    // closure, but record that this was done in the expression.
-    bool constAdded =3D !exprType.isConstQualified();
-    exprType.addConst();
-
-    BDRE =3D new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
-                                            NameInfo.getLoc(), false,
-                                            constAdded);
-  } else {
-    BDRE =3D new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
-                                            NameInfo.getLoc(), true);
-  }
-
-  return S.Owned(BDRE);
+  StringLiteral *Lit =3D StringLiteral::Create(Context, Literal.GetString(=
),
+                                             Kind, Literal.Pascal, StrTy,
+                                             &StringTokLocs[0],
+                                             StringTokLocs.size());
+  if (Literal.getUDSuffix().empty())
+    return Owned(Lit);
+
+  // We're building a user-defined literal.
+  IdentifierInfo *UDSuffix =3D &Context.Idents.get(Literal.getUDSuffix());
+  SourceLocation UDSuffixLoc =3D
+    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
+                   Literal.getUDSuffixOffset());
+
+  // Make sure we're allowed user-defined literals here.
+  if (!UDLScope)
+    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
+
+  // C++11 [lex.ext]p5: The literal L is treated as a call of the form
+  //   operator "" X (str, len)
+  QualType SizeType =3D Context.getSizeType();
+  llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars=
());
+  IntegerLiteral *LenArg =3D IntegerLiteral::Create(Context, Len, SizeType,
+                                                  StringTokLocs[0]);
+  Expr *Args[] =3D { Lit, LenArg };
+  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffi=
xLoc,
+                                        Args, StringTokLocs.back());
 }
=20
 ExprResult
@@ -1407,7 +1279,7 @@
 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
                        const DeclarationNameInfo &NameInfo,
                        const CXXScopeSpec *SS) {
-  if (getLangOptions().CUDA)
+  if (getLangOpts().CUDA)
     if (const FunctionDecl *Caller =3D dyn_cast<FunctionDecl>(CurContext))
       if (const FunctionDecl *Callee =3D dyn_cast<FunctionDecl>(D)) {
         CUDAFunctionTarget CallerTarget =3D IdentifyCUDATarget(Caller),
@@ -1421,12 +1293,18 @@
         }
       }
=20
-  MarkDeclarationReferenced(NameInfo.getLoc(), D);
-
-  Expr *E =3D DeclRefExpr::Create(Context,
-                                SS? SS->getWithLocInContext(Context)=20
-                                  : NestedNameSpecifierLoc(),
-                                D, NameInfo, Ty, VK);
+  bool refersToEnclosingScope =3D
+    (CurContext !=3D D->getDeclContext() &&
+     D->getDeclContext()->isFunctionOrMethod());
+
+  DeclRefExpr *E =3D DeclRefExpr::Create(Context,
+                                       SS ? SS->getWithLocInContext(Contex=
t)
+                                              : NestedNameSpecifierLoc(),
+                                       SourceLocation(),
+                                       D, refersToEnclosingScope,
+                                       NameInfo, Ty, VK);
+
+  MarkDeclRefReferenced(E);
=20
   // Just in case we're building an illegal pointer-to-member.
   FieldDecl *FD =3D dyn_cast<FieldDecl>(D);
@@ -1474,9 +1352,9 @@
 ///
 /// \return false if new lookup candidates were found
 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
-                               CorrectTypoContext CTC,
+                               CorrectionCandidateCallback &CCC,
                                TemplateArgumentListInfo *ExplicitTemplateA=
rgs,
-                               Expr **Args, unsigned NumArgs) {
+                               llvm::ArrayRef<Expr *> Args) {
   DeclarationName Name =3D R.getLookupName();
=20
   unsigned diagnostic =3D diag::err_undeclared_var_use;
@@ -1492,8 +1370,8 @@
   // unqualified lookup.  This is useful when (for example) the
   // original lookup would not have found something because it was a
   // dependent name.
-  for (DeclContext *DC =3D SS.isEmpty() ? CurContext : 0;
-       DC; DC =3D DC->getParent()) {
+  DeclContext *DC =3D SS.isEmpty() ? CurContext : 0;
+  while (DC) {
     if (isa<CXXRecordDecl>(DC)) {
       LookupQualifiedName(R, DC);
=20
@@ -1501,10 +1379,17 @@
         // Don't give errors about ambiguities in this lookup.
         R.suppressDiagnostics();
=20
+        // During a default argument instantiation the CurContext points
+        // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
+        // function parameter list, hence add an explicit check.
+        bool isDefaultArgument =3D !ActiveTemplateInstantiations.empty() &&
+                              ActiveTemplateInstantiations.back().Kind =3D=
=3D
+            ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiat=
ion;
         CXXMethodDecl *CurMethod =3D dyn_cast<CXXMethodDecl>(CurContext);
         bool isInstance =3D CurMethod &&
                           CurMethod->isInstance() &&
-                          DC =3D=3D CurMethod->getParent();
+                          DC =3D=3D CurMethod->getParent() && !isDefaultAr=
gument;
+                         =20
=20
         // Give a code modification hint to insert 'this->'.
         // TODO: fixit for inserting 'Base<T>::' in the other cases.
@@ -1515,11 +1400,12 @@
           CXXMethodDecl *DepMethod =3D cast_or_null<CXXMethodDecl>(
               CurMethod->getInstantiatedFromMemberFunction());
           if (DepMethod) {
-            if (getLangOptions().MicrosoftExt)
+            if (getLangOpts().MicrosoftMode)
               diagnostic =3D diag::warn_found_via_dependent_bases_lookup;
             Diag(R.getNameLoc(), diagnostic) << Name
               << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
             QualType DepThisType =3D DepMethod->getThisType(Context);
+            CheckCXXThisCapture(R.getNameLoc());
             CXXThisExpr *DepThis =3D new (Context) CXXThisExpr(
                                        R.getNameLoc(), DepThisType, false);
             TemplateArgumentListInfo TList;
@@ -1531,7 +1417,8 @@
             CXXDependentScopeMemberExpr *DepExpr =3D
                 CXXDependentScopeMemberExpr::Create(
                     Context, DepThis, DepThisType, true, SourceLocation(),
-                    SS.getWithLocInContext(Context), NULL,
+                    SS.getWithLocInContext(Context),
+                    ULE->getTemplateKeywordLoc(), 0,
                     R.getLookupNameInfo(),
                     ULE->hasExplicitTemplateArgs() ? &TList : 0);
             CallsUndergoingInstantiation.back()->setCallee(DepExpr);
@@ -1541,6 +1428,8 @@
             Diag(R.getNameLoc(), diagnostic) << Name;
           }
         } else {
+          if (getLangOpts().MicrosoftMode)
+            diagnostic =3D diag::warn_found_via_dependent_bases_lookup;
           Diag(R.getNameLoc(), diagnostic) << Name;
         }
=20
@@ -1548,20 +1437,40 @@
         for (LookupResult::iterator I =3D R.begin(), E =3D R.end(); I !=3D=
 E; ++I)
           Diag((*I)->getLocation(), diag::note_dependent_var_use);
=20
+        // Return true if we are inside a default argument instantiation
+        // and the found name refers to an instance member function, other=
wise
+        // the function calling DiagnoseEmptyLookup will try to create an
+        // implicit member call and this is wrong for default argument.
+        if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
+          Diag(R.getNameLoc(), diag::err_member_call_without_object);
+          return true;
+        }
+
         // Tell the callee to try to recover.
         return false;
       }
=20
       R.clear();
     }
+
+    // In Microsoft mode, if we are performing lookup from within a friend
+    // function definition declared at class scope then we must set
+    // DC to the lexical parent to be able to search into the parent
+    // class.
+    if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
+        cast<FunctionDecl>(DC)->getFriendObjectKind() &&
+        DC->getLexicalParent()->isRecord())
+      DC =3D DC->getLexicalParent();
+    else
+      DC =3D DC->getParent();
   }
=20
   // We didn't find anything, so try to correct for a typo.
   TypoCorrection Corrected;
   if (S && (Corrected =3D CorrectTypo(R.getLookupNameInfo(), R.getLookupKi=
nd(),
-                                    S, &SS, NULL, false, CTC))) {
-    std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
-    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
+                                    S, &SS, CCC))) {
+    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
+    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
     R.setLookupName(Corrected.getCorrection());
=20
     if (NamedDecl *ND =3D Corrected.getCorrectionDecl()) {
@@ -1575,11 +1484,11 @@
                    dyn_cast<FunctionTemplateDecl>(*CD))
             AddTemplateOverloadCandidate(
                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateA=
rgs,
-                Args, NumArgs, OCS);
+                Args, OCS);
           else if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(*CD))
             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() =3D=
=3D 0)
               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
-                                   Args, NumArgs, OCS);
+                                   Args, OCS);
         }
         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
           case OR_Success:
@@ -1654,9 +1563,11 @@
=20
 ExprResult Sema::ActOnIdExpression(Scope *S,
                                    CXXScopeSpec &SS,
+                                   SourceLocation TemplateKWLoc,
                                    UnqualifiedId &Id,
                                    bool HasTrailingLParen,
-                                   bool IsAddressOfOperand) {
+                                   bool IsAddressOfOperand,
+                                   CorrectionCandidateCallback *CCC) {
   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
          "cannot be direct & operand and have a trailing lparen");
=20
@@ -1699,10 +1610,9 @@
   }
=20
   if (DependentID)
-    return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
-                                      TemplateArgs);
-
-  bool IvarLookupFollowUp =3D false;
+    return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
+                                      IsAddressOfOperand, TemplateArgs);
+
   // Perform the required lookup.
   LookupResult R(*this, NameInfo,=20
                  (Id.getKind() =3D=3D UnqualifiedId::IK_ImplicitSelfParam)=20
@@ -1719,18 +1629,18 @@
    =20
     if (MemberOfUnknownSpecialization ||
         (R.getResultKind() =3D=3D LookupResult::NotFoundInCurrentInstantia=
tion))
-      return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
-                                        TemplateArgs);
+      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
+                                        IsAddressOfOperand, TemplateArgs);
   } else {
-    IvarLookupFollowUp =3D (!SS.isSet() && II && getCurMethodDecl());
+    bool IvarLookupFollowUp =3D II && !SS.isSet() && getCurMethodDecl();
     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
=20
     // If the result might be in a dependent base class, this is a depende=
nt=20
     // id-expression.
     if (R.getResultKind() =3D=3D LookupResult::NotFoundInCurrentInstantiat=
ion)
-      return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
-                                        TemplateArgs);
-     =20
+      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
+                                        IsAddressOfOperand, TemplateArgs);
+
     // If this reference is in an Objective-C method, then we need to do
     // some special Objective-C lookup, too.
     if (IvarLookupFollowUp) {
@@ -1740,9 +1650,6 @@
=20
       if (Expr *Ex =3D E.takeAs<Expr>())
         return Owned(Ex);
-     =20
-      // for further use, this must be set to false if in class method.
-      IvarLookupFollowUp =3D getCurMethodDecl()->isInstanceMethod();
     }
   }
=20
@@ -1756,7 +1663,7 @@
   if (R.empty() && !ADL) {
     // Otherwise, this could be an implicitly declared function reference =
(legal
     // in C90, extension in C99, forbidden in C++).
-    if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
+    if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
       NamedDecl *D =3D ImplicitlyDefineFunction(NameLoc, *II, S);
       if (D) R.addDecl(D);
     }
@@ -1769,12 +1676,13 @@
       // and we can't resolve an identifier then assume the identifier is =
type
       // dependent. The goal is to postpone name lookup to instantiation t=
ime=20
       // to be able to search into type dependent base classes.
-      if (getLangOptions().MicrosoftMode && CurContext->isDependentContext=
() &&
+      if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() =
&&
           isa<CXXMethodDecl>(CurContext))
-        return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
-                                          TemplateArgs);
-
-      if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
+        return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
+                                          IsAddressOfOperand, TemplateArgs=
);
+
+      CorrectionCandidateCallback DefaultValidator;
+      if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
         return ExprError();
=20
       assert(!R.empty() &&
@@ -1837,11 +1745,12 @@
                               isa<IndirectFieldDecl>(R.getFoundDecl());
=20
     if (MightBeImplicitMember)
-      return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
-  }
-
-  if (TemplateArgs)
-    return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
+      return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
+                                             R, TemplateArgs);
+  }
+
+  if (TemplateArgs || TemplateKWLoc.isValid())
+    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
=20
   return BuildDeclarationNameExpr(SS, R, ADL);
 }
@@ -1855,7 +1764,8 @@
                                         const DeclarationNameInfo &NameInf=
o) {
   DeclContext *DC;
   if (!(DC =3D computeDeclContext(SS, false)) || DC->isDependentContext())
-    return BuildDependentDeclRefExpr(SS, NameInfo, 0);
+    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=3D*/SourceLocatio=
n(),
+                                     NameInfo, /*TemplateArgs=3D*/0);
=20
   if (RequireCompleteDeclContext(SS, DC))
     return ExprError();
@@ -1912,7 +1822,8 @@
   if (LookForIvars) {
     IFace =3D CurMethod->getClassInterface();
     ObjCInterfaceDecl *ClassDeclared;
-    if (ObjCIvarDecl *IV =3D IFace->lookupInstanceVariable(II, ClassDeclar=
ed)) {
+    ObjCIvarDecl *IV =3D 0;
+    if (IFace && (IV =3D IFace->lookupInstanceVariable(II, ClassDeclared))=
) {
       // Diagnose using an ivar in a class method.
       if (IsClassMethod)
         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
@@ -1929,7 +1840,8 @@
=20
       // Diagnose the use of an ivar outside of the declaring class.
       if (IV->getAccessControl() =3D=3D ObjCIvarDecl::Private &&
-          ClassDeclared !=3D IFace)
+          !declaresSameEntity(ClassDeclared, IFace) &&
+          !getLangOpts().DebuggerSupport)
         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
=20
       // FIXME: This should use a new expr for a direct reference, don't
@@ -1939,7 +1851,8 @@
       SelfName.setIdentifier(&II, SourceLocation());
       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
       CXXScopeSpec SelfScopeSpec;
-      ExprResult SelfExpr =3D ActOnIdExpression(S, SelfScopeSpec,
+      SourceLocation TemplateKWLoc;
+      ExprResult SelfExpr =3D ActOnIdExpression(S, SelfScopeSpec, Template=
KWLoc,
                                               SelfName, false, false);
       if (SelfExpr.isInvalid())
         return ExprError();
@@ -1948,26 +1861,33 @@
       if (SelfExpr.isInvalid())
         return ExprError();
=20
-      MarkDeclarationReferenced(Loc, IV);
+      MarkAnyDeclReferenced(Loc, IV);
       return Owned(new (Context)
                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
                                    SelfExpr.take(), true, true));
     }
   } else if (CurMethod->isInstanceMethod()) {
     // We should warn if a local variable hides an ivar.
-    ObjCInterfaceDecl *IFace =3D CurMethod->getClassInterface();
-    ObjCInterfaceDecl *ClassDeclared;
-    if (ObjCIvarDecl *IV =3D IFace->lookupInstanceVariable(II, ClassDeclar=
ed)) {
-      if (IV->getAccessControl() !=3D ObjCIvarDecl::Private ||
-          IFace =3D=3D ClassDeclared)
-        Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
-    }
+    if (ObjCInterfaceDecl *IFace =3D CurMethod->getClassInterface()) {
+      ObjCInterfaceDecl *ClassDeclared;
+      if (ObjCIvarDecl *IV =3D IFace->lookupInstanceVariable(II, ClassDecl=
ared)) {
+        if (IV->getAccessControl() !=3D ObjCIvarDecl::Private ||
+            declaresSameEntity(IFace, ClassDeclared))
+          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
+      }
+    }
+  } else if (Lookup.isSingleResult() &&
+             Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
+    // If accessing a stand-alone ivar in a class method, this is an error.
+    if (const ObjCIvarDecl *IV =3D dyn_cast<ObjCIvarDecl>(Lookup.getFoundD=
ecl()))
+      return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
+                       << IV->getDeclName());
   }
=20
   if (Lookup.empty() && II && AllowBuiltinCreation) {
     // FIXME. Consolidate this with similar code in LookupName.
     if (unsigned BuiltinID =3D II->getBuiltinID()) {
-      if (!(getLangOptions().CPlusPlus &&
+      if (!(getLangOpts().CPlusPlus &&
             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
         NamedDecl *D =3D LazilyCreateBuiltin((IdentifierInfo *)II, Builtin=
ID,
                                            S, Lookup.isForRedeclaration(),
@@ -2159,7 +2079,7 @@
     return false;
=20
   // Only in C++ or ObjC++.
-  if (!getLangOptions().CPlusPlus)
+  if (!getLangOpts().CPlusPlus)
     return false;
=20
   // Turn off ADL when we find certain kinds of declarations during
@@ -2308,30 +2228,7 @@
       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(=
),
                                                       indirectField);
=20
-  // If the identifier reference is inside a block, and it refers to a val=
ue
-  // that is outside the block, create a BlockDeclRefExpr instead of a
-  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot=
 when
-  // the block is formed.
-  //
-  // We do not do this for things like enum constants, global variables, e=
tc,
-  // as they do not get snapshotted.
-  //
-  switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
-  case CR_Error:
-    return ExprError();
-
-  case CR_Capture:
-    assert(!SS.isSet() && "referenced local variable with scope specifier?=
");
-    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
-
-  case CR_CaptureByRef:
-    assert(!SS.isSet() && "referenced local variable with scope specifier?=
");
-    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
-
-  case CR_NoCapture: {
-    // If this reference is not in a block or if the referenced
-    // variable is within the block, create a normal DeclRefExpr.
-
+  {
     QualType type =3D VD->getType();
     ExprValueKind valueKind =3D VK_RValue;
=20
@@ -2343,13 +2240,11 @@
     case Decl::type:
 #include "clang/AST/DeclNodes.inc"
       llvm_unreachable("invalid value decl kind");
-      return ExprError();
=20
     // These shouldn't make it here.
     case Decl::ObjCAtDefsField:
     case Decl::ObjCIvar:
       llvm_unreachable("forming non-member reference to ivar?");
-      return ExprError();
=20
     // Enum constants are always r-values and never references.
     // Unresolved using declarations are dependent.
@@ -2364,7 +2259,7 @@
     // exist in the high-level semantics.
     case Decl::Field:
     case Decl::IndirectField:
-      assert(getLangOptions().CPlusPlus &&
+      assert(getLangOpts().CPlusPlus &&
              "building reference to field in C?");
=20
       // These can't have reference type in well-formed programs, but
@@ -2391,7 +2286,7 @@
=20
     case Decl::Var:
       // In C, "extern void blah;" is valid and is an r-value.
-      if (!getLangOptions().CPlusPlus &&
+      if (!getLangOpts().CPlusPlus &&
           !type.hasQualifiers() &&
           type->isVoidType()) {
         valueKind =3D VK_RValue;
@@ -2400,12 +2295,23 @@
       // fallthrough
=20
     case Decl::ImplicitParam:
-    case Decl::ParmVar:
+    case Decl::ParmVar: {
       // These are always l-values.
       valueKind =3D VK_LValue;
       type =3D type.getNonReferenceType();
+
+      // FIXME: Does the addition of const really only apply in
+      // potentially-evaluated contexts? Since the variable isn't actually
+      // captured in an unevaluated context, it seems that the answer is n=
o.
+      if (ExprEvalContexts.back().Context !=3D Sema::Unevaluated) {
+        QualType CapturedType =3D getCapturedDeclRefType(cast<VarDecl>(VD)=
, Loc);
+        if (!CapturedType.isNull())
+          type =3D CapturedType;
+      }
+     =20
       break;
-
+    }
+       =20
     case Decl::Function: {
       const FunctionType *fty =3D type->castAs<FunctionType>();
=20
@@ -2418,7 +2324,7 @@
       }
=20
       // Functions are l-values in C++.
-      if (getLangOptions().CPlusPlus) {
+      if (getLangOpts().CPlusPlus) {
         valueKind =3D VK_LValue;
         break;
       }
@@ -2466,11 +2372,6 @@
=20
     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
   }
-
-  }
-
-  llvm_unreachable("unknown capture result");
-  return ExprError();
 }
=20
 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Ki=
nd) {
@@ -2507,8 +2408,8 @@
   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
 }
=20
-ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
-  llvm::SmallString<16> CharBuffer;
+ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope)=
 {
+  SmallString<16> CharBuffer;
   bool Invalid =3D false;
   StringRef ThisTok =3D PP.getSpelling(Tok, CharBuffer, &Invalid);
   if (Invalid)
@@ -2520,16 +2421,14 @@
     return ExprError();
=20
   QualType Ty;
-  if (!getLangOptions().CPlusPlus)
-    Ty =3D Context.IntTy;   // 'x' and L'x' -> int in C.
-  else if (Literal.isWide())
-    Ty =3D Context.WCharTy; // L'x' -> wchar_t in C++.
+  if (Literal.isWide())
+    Ty =3D Context.WCharTy; // L'x' -> wchar_t in C and C++.
   else if (Literal.isUTF16())
-    Ty =3D Context.Char16Ty; // u'x' -> char16_t in C++0x.
+    Ty =3D Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
   else if (Literal.isUTF32())
-    Ty =3D Context.Char32Ty; // U'x' -> char32_t in C++0x.
-  else if (Literal.isMultiChar())
-    Ty =3D Context.IntTy;   // 'wxyz' -> int in C++.
+    Ty =3D Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
+  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
+    Ty =3D Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
   else
     Ty =3D Context.CharTy;  // 'x' -> char in C++
=20
@@ -2541,21 +2440,75 @@
   else if (Literal.isUTF32())
     Kind =3D CharacterLiteral::UTF32;
=20
-  return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
-                                              Tok.getLocation()));
-}
-
-ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
+  Expr *Lit =3D new (Context) CharacterLiteral(Literal.getValue(), Kind, T=
y,
+                                             Tok.getLocation());
+
+  if (Literal.getUDSuffix().empty())
+    return Owned(Lit);
+
+  // We're building a user-defined literal.
+  IdentifierInfo *UDSuffix =3D &Context.Idents.get(Literal.getUDSuffix());
+  SourceLocation UDSuffixLoc =3D
+    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
+
+  // Make sure we're allowed user-defined literals here.
+  if (!UDLScope)
+    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
+
+  // C++11 [lex.ext]p6: The literal L is treated as a call of the form
+  //   operator "" X (ch)
+  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffi=
xLoc,
+                                        llvm::makeArrayRef(&Lit, 1),
+                                        Tok.getLocation());
+}
+
+ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
+  unsigned IntSize =3D Context.getTargetInfo().getIntWidth();
+  return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
+                                      Context.IntTy, Loc));
+}
+
+static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
+                                  QualType Ty, SourceLocation Loc) {
+  const llvm::fltSemantics &Format =3D S.Context.getFloatTypeSemantics(Ty);
+
+  using llvm::APFloat;
+  APFloat Val(Format);
+
+  APFloat::opStatus result =3D Literal.GetFloatValue(Val);
+
+  // Overflow is always an error, but underflow is only an error if
+  // we underflowed to zero (APFloat reports denormals as underflow).
+  if ((result & APFloat::opOverflow) ||
+      ((result & APFloat::opUnderflow) && Val.isZero())) {
+    unsigned diagnostic;
+    SmallString<20> buffer;
+    if (result & APFloat::opOverflow) {
+      diagnostic =3D diag::warn_float_overflow;
+      APFloat::getLargest(Format).toString(buffer);
+    } else {
+      diagnostic =3D diag::warn_float_underflow;
+      APFloat::getSmallest(Format).toString(buffer);
+    }
+
+    S.Diag(Loc, diagnostic)
+      << Ty
+      << StringRef(buffer.data(), buffer.size());
+  }
+
+  bool isExact =3D (result =3D=3D APFloat::opOK);
+  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
+}
+
+ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
   // Fast path for a single digit (which is quite common).  A single digit
-  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
+  // cannot have a trigraph, escaped newline, radix prefix, or suffix.
   if (Tok.getLength() =3D=3D 1) {
     const char Val =3D PP.getSpellingOfSingleCharacterNumericConstant(Tok);
-    unsigned IntSize =3D Context.getTargetInfo().getIntWidth();
-    return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-=
'0'),
-                    Context.IntTy, Tok.getLocation()));
-  }
-
-  llvm::SmallString<512> IntegerBuffer;
+    return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
+  }
+
+  SmallString<512> IntegerBuffer;
   // Add padding so that NumericLiteralParser can overread by one characte=
r.
   IntegerBuffer.resize(Tok.getLength()+1);
   const char *ThisTokBegin =3D &IntegerBuffer[0];
@@ -2571,6 +2524,96 @@
   if (Literal.hadError)
     return ExprError();
=20
+  if (Literal.hasUDSuffix()) {
+    // We're building a user-defined literal.
+    IdentifierInfo *UDSuffix =3D &Context.Idents.get(Literal.getUDSuffix()=
);
+    SourceLocation UDSuffixLoc =3D
+      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()=
);
+
+    // Make sure we're allowed user-defined literals here.
+    if (!UDLScope)
+      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
+
+    QualType CookedTy;
+    if (Literal.isFloatingLiteral()) {
+      // C++11 [lex.ext]p4: If S contains a literal operator with paramete=
r type
+      // long double, the literal is treated as a call of the form
+      //   operator "" X (f L)
+      CookedTy =3D Context.LongDoubleTy;
+    } else {
+      // C++11 [lex.ext]p3: If S contains a literal operator with paramete=
r type
+      // unsigned long long, the literal is treated as a call of the form
+      //   operator "" X (n ULL)
+      CookedTy =3D Context.UnsignedLongLongTy;
+    }
+
+    DeclarationName OpName =3D
+      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
+    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
+    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
+
+    // Perform literal operator lookup to determine if we're building a raw
+    // literal or a cooked one.
+    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
+    switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedT=
y, 1),
+                                  /*AllowRawAndTemplate*/true)) {
+    case LOLR_Error:
+      return ExprError();
+
+    case LOLR_Cooked: {
+      Expr *Lit;
+      if (Literal.isFloatingLiteral()) {
+        Lit =3D BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLoca=
tion());
+      } else {
+        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), =
0);
+        if (Literal.GetIntegerValue(ResultVal))
+          Diag(Tok.getLocation(), diag::warn_integer_too_large);
+        Lit =3D IntegerLiteral::Create(Context, ResultVal, CookedTy,
+                                     Tok.getLocation());
+      }
+      return BuildLiteralOperatorCall(R, OpNameInfo,
+                                      llvm::makeArrayRef(&Lit, 1),
+                                      Tok.getLocation());
+    }
+
+    case LOLR_Raw: {
+      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
+      // literal is treated as a call of the form
+      //   operator "" X ("n")
+      SourceLocation TokLoc =3D Tok.getLocation();
+      unsigned Length =3D Literal.getUDSuffixOffset();
+      QualType StrTy =3D Context.getConstantArrayType(
+          Context.CharTy, llvm::APInt(32, Length + 1),
+          ArrayType::Normal, 0);
+      Expr *Lit =3D StringLiteral::Create(
+          Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
+          /*Pascal*/false, StrTy, &TokLoc, 1);
+      return BuildLiteralOperatorCall(R, OpNameInfo,
+                                      llvm::makeArrayRef(&Lit, 1), TokLoc);
+    }
+
+    case LOLR_Template:
+      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
+      // template), L is treated as a call fo the form
+      //   operator "" X <'c1', 'c2', ... 'ck'>()
+      // where n is the source character sequence c1 c2 ... ck.
+      TemplateArgumentListInfo ExplicitArgs;
+      unsigned CharBits =3D Context.getIntWidth(Context.CharTy);
+      bool CharIsUnsigned =3D Context.CharTy->isUnsignedIntegerType();
+      llvm::APSInt Value(CharBits, CharIsUnsigned);
+      for (unsigned I =3D 0, N =3D Literal.getUDSuffixOffset(); I !=3D N; =
++I) {
+        Value =3D ThisTokBegin[I];
+        TemplateArgument Arg(Value, Context.CharTy);
+        TemplateArgumentLocInfo ArgInfo;
+        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
+      }
+      return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
+                                      Tok.getLocation(), &ExplicitArgs);
+    }
+
+    llvm_unreachable("unexpected literal operator lookup result");
+  }
+
   Expr *Res;
=20
   if (Literal.isFloatingLiteral()) {
@@ -2582,39 +2625,12 @@
     else
       Ty =3D Context.LongDoubleTy;
=20
-    const llvm::fltSemantics &Format =3D Context.getFloatTypeSemantics(Ty);
-
-    using llvm::APFloat;
-    APFloat Val(Format);
-
-    APFloat::opStatus result =3D Literal.GetFloatValue(Val);
-
-    // Overflow is always an error, but underflow is only an error if
-    // we underflowed to zero (APFloat reports denormals as underflow).
-    if ((result & APFloat::opOverflow) ||
-        ((result & APFloat::opUnderflow) && Val.isZero())) {
-      unsigned diagnostic;
-      llvm::SmallString<20> buffer;
-      if (result & APFloat::opOverflow) {
-        diagnostic =3D diag::warn_float_overflow;
-        APFloat::getLargest(Format).toString(buffer);
-      } else {
-        diagnostic =3D diag::warn_float_underflow;
-        APFloat::getSmallest(Format).toString(buffer);
-      }
-
-      Diag(Tok.getLocation(), diagnostic)
-        << Ty
-        << StringRef(buffer.data(), buffer.size());
-    }
-
-    bool isExact =3D (result =3D=3D APFloat::opOK);
-    Res =3D FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLoca=
tion());
+    Res =3D BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
=20
     if (Ty =3D=3D Context.DoubleTy) {
-      if (getLangOptions().SinglePrecisionConstants) {
+      if (getLangOpts().SinglePrecisionConstants) {
         Res =3D ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).t=
ake();
-      } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp6=
4) {
+      } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
         Res =3D ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).t=
ake();
       }
@@ -2625,9 +2641,10 @@
     QualType Ty;
=20
     // long long is a C99 feature.
-    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
-        Literal.isLongLong)
-      Diag(Tok.getLocation(), diag::ext_longlong);
+    if (!getLangOpts().C99 && Literal.isLongLong)
+      Diag(Tok.getLocation(),
+           getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_longlong : diag::ext_longlong);
=20
     // Get the value in the widest-possible width.
     llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
@@ -2688,7 +2705,7 @@
           // To be compatible with MSVC, hex integer literals ending with =
the
           // LL or i64 suffix are always signed in Microsoft mode.
           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] =3D=3D 0 ||
-              (getLangOptions().MicrosoftExt && Literal.isLongLong)))
+              (getLangOpts().MicrosoftExt && Literal.isLongLong)))
             Ty =3D Context.LongLongTy;
           else if (AllowUnsigned)
             Ty =3D Context.UnsignedLongLongTy;
@@ -2971,6 +2988,12 @@
   if (isInvalid)
     return ExprError();
=20
+  if (ExprKind =3D=3D UETT_SizeOf && E->getType()->isVariableArrayType()) {
+    PE =3D TranformToPotentiallyEvaluated(E);
+    if (PE.isInvalid()) return ExprError();
+    E =3D PE.take();
+  }
+
   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
       ExprKind, E, Context.getSizeType(), OpLoc,
@@ -3044,6 +3067,11 @@
   case tok::minusminus: Opc =3D UO_PostDec; break;
   }
=20
+  // Since this might is a postfix expression, get rid of ParenListExprs.
+  ExprResult Result =3D MaybeConvertParenListExprToParenExpr(S, Input);
+  if (Result.isInvalid()) return ExprError();
+  Input =3D Result.take();
+
   return BuildUnaryOp(S, OpLoc, Opc, Input);
 }
=20
@@ -3057,7 +3085,7 @@
=20
   Expr *LHSExp =3D Base, *RHSExp =3D Idx;
=20
-  if (getLangOptions().CPlusPlus &&
+  if (getLangOpts().CPlusPlus &&
       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
                                                   Context.DependentTy,
@@ -3065,11 +3093,12 @@
                                                   RLoc));
   }
=20
-  if (getLangOptions().CPlusPlus &&
+  if (getLangOpts().CPlusPlus &&
       (LHSExp->getType()->isRecordType() ||
        LHSExp->getType()->isEnumeralType() ||
        RHSExp->getType()->isRecordType() ||
-       RHSExp->getType()->isEnumeralType())) {
+       RHSExp->getType()->isEnumeralType()) &&
+      !LHSExp->getType()->isObjCObjectPointerType()) {
     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
   }
=20
@@ -3113,17 +3142,20 @@
     BaseExpr =3D LHSExp;
     IndexExpr =3D RHSExp;
     ResultType =3D PTy->getPointeeType();
+  } else if (const ObjCObjectPointerType *PTy =3D
+             LHSTy->getAs<ObjCObjectPointerType>()) {
+    BaseExpr =3D LHSExp;
+    IndexExpr =3D RHSExp;
+    Result =3D BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, =
0);
+    if (!Result.isInvalid())
+      return Owned(Result.take());
+    ResultType =3D PTy->getPointeeType();
   } else if (const PointerType *PTy =3D RHSTy->getAs<PointerType>()) {
      // Handle the uncommon case of "123[Ptr]".
     BaseExpr =3D RHSExp;
     IndexExpr =3D LHSExp;
     ResultType =3D PTy->getPointeeType();
   } else if (const ObjCObjectPointerType *PTy =3D
-               LHSTy->getAs<ObjCObjectPointerType>()) {
-    BaseExpr =3D LHSExp;
-    IndexExpr =3D RHSExp;
-    ResultType =3D PTy->getPointeeType();
-  } else if (const ObjCObjectPointerType *PTy =3D
                RHSTy->getAs<ObjCObjectPointerType>()) {
      // Handle the uncommon case of "123[Ptr]".
     BaseExpr =3D RHSExp;
@@ -3188,7 +3220,7 @@
     return ExprError();
   }
=20
-  if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
+  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
     // GNU extension: subscripting on pointer to void
     Diag(LLoc, diag::ext_gnu_subscript_void_type)
       << BaseExpr->getSourceRange();
@@ -3247,6 +3279,7 @@
       //   the semantic constraints are checked, at the point where the
       //   default argument expression appears.
       ContextRAII SavedContext(*this, FD);
+      LocalInstantiationScope Local(*this);
       Result =3D SubstExpr(UninstExpr, ArgList);
     }
     if (Result.isInvalid())
@@ -3257,7 +3290,7 @@
       =3D InitializedEntity::InitializeParameter(Context, Param);
     InitializationKind Kind
       =3D InitializationKind::CreateCopy(Param->getLocation(),
-             /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
+             /*FIXME:EqualLoc*/UninstExpr->getLocStart());
     Expr *ResultE =3D Result.takeAs<Expr>();
=20
     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
@@ -3276,18 +3309,25 @@
   // be properly destroyed.
   // FIXME: We should really be rebuilding the default argument with new
   // bound temporaries; see the comment in PR5810.
-  for (unsigned i =3D 0, e =3D Param->getNumDefaultArgTemporaries(); i !=
=3D e; ++i) {
-    CXXTemporary *Temporary =3D Param->getDefaultArgTemporary(i);
-    MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),=20
-                    const_cast<CXXDestructorDecl*>(Temporary->getDestructo=
r()));
-    ExprTemporaries.push_back(Temporary);
+  // We don't need to do that with block decls, though, because
+  // blocks in default argument expression can never capture anything.
+  if (isa<ExprWithCleanups>(Param->getInit())) {
+    // Set the "needs cleanups" bit regardless of whether there are
+    // any explicit objects.
     ExprNeedsCleanups =3D true;
+
+    // Append all the objects to the cleanup list.  Right now, this
+    // should always be a no-op, because blocks in default argument
+    // expressions should never be able to capture anything.
+    assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
+           "default argument expression has capturing blocks?");
   }
=20
   // We already type-checked the argument, so we know it works.=20
   // Just mark all of the declarations in this potentially-evaluated expre=
ssion
   // as being "referenced".
-  MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
+  MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
+                                   /*SkipLocalVariables=3D*/true);
   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
 }
=20
@@ -3371,7 +3411,7 @@
     CallType =3D VariadicBlock; // Block
   else if (isa<MemberExpr>(Fn))
     CallType =3D VariadicMethod;
-  Invalid =3D GatherArgumentsForCall(Call->getSourceRange().getBegin(), FD=
ecl,
+  Invalid =3D GatherArgumentsForCall(Call->getLocStart(), FDecl,
                                    Proto, 0, Args, NumArgs, AllArgs, CallT=
ype);
   if (Invalid)
     return true;
@@ -3388,7 +3428,8 @@
                                   unsigned FirstProtoArg,
                                   Expr **Args, unsigned NumArgs,
                                   SmallVector<Expr *, 8> &AllArgs,
-                                  VariadicCallType CallType) {
+                                  VariadicCallType CallType,
+                                  bool AllowExplicit) {
   unsigned NumArgsInProto =3D Proto->getNumArgs();
   unsigned NumArgsToCheck =3D NumArgs;
   bool Invalid =3D false;
@@ -3401,33 +3442,42 @@
     QualType ProtoArgType =3D Proto->getArgType(i);
=20
     Expr *Arg;
+    ParmVarDecl *Param;
     if (ArgIx < NumArgs) {
       Arg =3D Args[ArgIx++];
=20
-      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
+      if (RequireCompleteType(Arg->getLocStart(),
                               ProtoArgType,
                               PDiag(diag::err_call_incomplete_argument)
                               << Arg->getSourceRange()))
         return true;
=20
       // Pass the argument
-      ParmVarDecl *Param =3D 0;
+      Param =3D 0;
       if (FDecl && i < FDecl->getNumParams())
         Param =3D FDecl->getParamDecl(i);
=20
+      // Strip the unbridged-cast placeholder expression off, if applicabl=
e.
+      if (Arg->getType() =3D=3D Context.ARCUnbridgedCastTy &&
+          FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
+          (!Param || !Param->hasAttr<CFConsumedAttr>()))
+        Arg =3D stripARCUnbridgedCast(Arg);
+
       InitializedEntity Entity =3D
         Param? InitializedEntity::InitializeParameter(Context, Param)
              : InitializedEntity::InitializeParameter(Context, ProtoArgTyp=
e,
                                                       Proto->isArgConsumed=
(i));
       ExprResult ArgE =3D PerformCopyInitialization(Entity,
                                                   SourceLocation(),
-                                                  Owned(Arg));
+                                                  Owned(Arg),
+                                                  /*TopLevelOfInitList=3D*=
/false,
+                                                  AllowExplicit);
       if (ArgE.isInvalid())
         return true;
=20
       Arg =3D ArgE.takeAs<Expr>();
     } else {
-      ParmVarDecl *Param =3D FDecl->getParamDecl(i);
+      Param =3D FDecl->getParamDecl(i);
=20
       ExprResult ArgExpr =3D
         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
@@ -3442,6 +3492,9 @@
     // with its own checking, such as a BinaryOperator.
     CheckArrayAccess(Arg);
=20
+    // Check for violations of C99 static array rules (C99 6.7.5.3p7).
+    CheckStaticArrayArgument(CallLoc, Param, Arg);
+
     AllArgs.push_back(Arg);
   }
=20
@@ -3479,6 +3532,60 @@
   return Invalid;
 }
=20
+static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
+  TypeLoc TL =3D PVD->getTypeSourceInfo()->getTypeLoc();
+  if (ArrayTypeLoc *ATL =3D dyn_cast<ArrayTypeLoc>(&TL))
+    S.Diag(PVD->getLocation(), diag::note_callee_static_array)
+      << ATL->getLocalSourceRange();
+}
+
+/// CheckStaticArrayArgument - If the given argument corresponds to a stat=
ic
+/// array parameter, check that it is non-null, and that if it is formed by
+/// array-to-pointer decay, the underlying array is sufficiently large.
+///
+/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] o=
f the
+/// array type derivation, then for each call to the function, the value o=
f the
+/// corresponding actual argument shall provide access to the first elemen=
t of
+/// an array with at least as many elements as specified by the size expre=
ssion.
+void
+Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
+                               ParmVarDecl *Param,
+                               const Expr *ArgExpr) {
+  // Static array parameters are not supported in C++.
+  if (!Param || getLangOpts().CPlusPlus)
+    return;
+
+  QualType OrigTy =3D Param->getOriginalType();
+
+  const ArrayType *AT =3D Context.getAsArrayType(OrigTy);
+  if (!AT || AT->getSizeModifier() !=3D ArrayType::Static)
+    return;
+
+  if (ArgExpr->isNullPointerConstant(Context,
+                                     Expr::NPC_NeverValueDependent)) {
+    Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
+    DiagnoseCalleeStaticArrayParam(*this, Param);
+    return;
+  }
+
+  const ConstantArrayType *CAT =3D dyn_cast<ConstantArrayType>(AT);
+  if (!CAT)
+    return;
+
+  const ConstantArrayType *ArgCAT =3D
+    Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType=
());
+  if (!ArgCAT)
+    return;
+
+  if (ArgCAT->getSize().ult(CAT->getSize())) {
+    Diag(CallLoc, diag::warn_static_array_too_small)
+      << ArgExpr->getSourceRange()
+      << (unsigned) ArgCAT->getSize().getZExtValue()
+      << (unsigned) CAT->getSize().getZExtValue();
+    DiagnoseCalleeStaticArrayParam(*this, Param);
+  }
+}
+
 /// Given a function expression of unknown-any type, try to rebuild it
 /// to have a function type.
 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
@@ -3499,7 +3606,7 @@
=20
   Expr **Args =3D ArgExprs.release();
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // If this is a pseudo-destructor expression, build the call immediate=
ly.
     if (isa<CXXPseudoDestructorExpr>(Fn)) {
       if (NumArgs > 0) {
@@ -3508,8 +3615,6 @@
           << FixItHint::CreateRemoval(
                                     SourceRange(Args[0]->getLocStart(),
                                                 Args[NumArgs-1]->getLocEnd=
()));
-
-        NumArgs =3D 0;
       }
=20
       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidT=
y,
@@ -3523,7 +3628,8 @@
     bool Dependent =3D false;
     if (Fn->isTypeDependent())
       Dependent =3D true;
-    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
+    else if (Expr::hasAnyTypeDependentArguments(
+        llvm::makeArrayRef(Args, NumArgs)))
       Dependent =3D true;
=20
     if (Dependent) {
@@ -3574,6 +3680,11 @@
   }
=20
   // If we're directly calling a function, get the appropriate declaration.
+  if (Fn->getType() =3D=3D Context.UnknownAnyTy) {
+    ExprResult result =3D rebuildUnknownAnyFunction(*this, Fn);
+    if (result.isInvalid()) return ExprError();
+    Fn =3D result.take();
+  }
=20
   Expr *NakedFn =3D Fn->IgnoreParens();
=20
@@ -3601,7 +3712,8 @@
   QualType ConfigQTy =3D ConfigDecl->getType();
=20
   DeclRefExpr *ConfigDR =3D new (Context) DeclRefExpr(
-      ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
+      ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
+  MarkFunctionReferenced(LLLLoc, ConfigDecl);
=20
   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
                        /*IsExecConfig=3D*/true);
@@ -3698,7 +3810,7 @@
       << Fn->getType() << Fn->getSourceRange());
   }
=20
-  if (getLangOptions().CUDA) {
+  if (getLangOpts().CUDA) {
     if (Config) {
       // CUDA: Kernel calls must be to global functions
       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
@@ -3719,7 +3831,7 @@
=20
   // Check for a valid return type
   if (CheckCallReturnType(FuncT->getResultType(),
-                          Fn->getSourceRange().getBegin(), TheCall,
+                          Fn->getLocStart(), TheCall,
                           FDecl))
     return ExprError();
=20
@@ -3778,7 +3890,7 @@
         Arg =3D ArgE.takeAs<Expr>();
       }
      =20
-      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
+      if (RequireCompleteType(Arg->getLocStart(),
                               Arg->getType(),
                               PDiag(diag::err_call_incomplete_argument)
                                 << Arg->getSourceRange()))
@@ -3852,7 +3964,8 @@
     =3D InitializedEntity::InitializeTemporary(literalType);
   InitializationKind Kind
     =3D InitializationKind::CreateCStyleCast(LParenLoc,=20
-                                           SourceRange(LParenLoc, RParenLo=
c));
+                                           SourceRange(LParenLoc, RParenLo=
c),
+                                           /*InitList=3D*/true);
   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
   ExprResult Result =3D InitSeq.Perform(*this, Entity, Kind,
                                        MultiExprArg(*this, &LiteralExpr, 1=
),
@@ -3868,7 +3981,7 @@
   }
=20
   // In C, compound literals are l-values for some reason.
-  ExprValueKind VK =3D getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
+  ExprValueKind VK =3D getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
=20
   return MaybeBindToTemporary(
            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
@@ -3881,6 +3994,20 @@
   unsigned NumInit =3D InitArgList.size();
   Expr **InitList =3D InitArgList.release();
=20
+  // Immediately handle non-overload placeholders.  Overloads can be
+  // resolved contextually, but everything else here can't.
+  for (unsigned I =3D 0; I !=3D NumInit; ++I) {
+    if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
+      ExprResult result =3D CheckPlaceholderExpr(InitList[I]);
+
+      // Ignore failures; dropping the entire initializer list because
+      // of one failure would be terrible for indexing/etc.
+      if (result.isInvalid()) continue;
+
+      InitList[I] =3D result.take();
+    }
+  }
+
   // Semantic analysis for initializers is done by ActOnDeclarator() and
   // CheckInitializer() - it requires knowledge of the object being intial=
ized.
=20
@@ -3896,7 +4023,7 @@
   assert(E.get()->isRValue());
=20
   // Only do this in an r-value context.
-  if (!S.getLangOptions().ObjCAutoRefCount) return;
+  if (!S.getLangOpts().ObjCAutoRefCount) return;
=20
   E =3D ImplicitCastExpr::Create(S.Context, E.get()->getType(),
                                CK_ARCExtendBlockObject, E.get(),
@@ -3927,6 +4054,11 @@
   // pointers.  Everything else should be possible.
=20
   QualType SrcTy =3D Src.get()->getType();
+  if (const AtomicType *SrcAtomicTy =3D SrcTy->getAs<AtomicType>())
+    SrcTy =3D SrcAtomicTy->getValueType();
+  if (const AtomicType *DestAtomicTy =3D DestTy->getAs<AtomicType>())
+    DestTy =3D DestAtomicTy->getValueType();
+
   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
     return CK_NoOp;
=20
@@ -3946,12 +4078,10 @@
     case Type::STK_ObjCObjectPointer:
       if (SrcKind =3D=3D Type::STK_ObjCObjectPointer)
         return CK_BitCast;
-      else if (SrcKind =3D=3D Type::STK_CPointer)
+      if (SrcKind =3D=3D Type::STK_CPointer)
         return CK_CPointerToObjCPointerCast;
-      else {
-        maybeExtendBlockObject(*this, Src);
-        return CK_BlockPointerToObjCPointerCast;
-      }
+      maybeExtendBlockObject(*this, Src);
+      return CK_BlockPointerToObjCPointerCast;
     case Type::STK_Bool:
       return CK_PointerToBoolean;
     case Type::STK_Integral:
@@ -3962,7 +4092,7 @@
     case Type::STK_MemberPointer:
       llvm_unreachable("illegal cast from pointer");
     }
-    break;
+    llvm_unreachable("Should have returned before this");
=20
   case Type::STK_Bool: // casting from bool is like casting from an integer
   case Type::STK_Integral:
@@ -3993,7 +4123,7 @@
     case Type::STK_MemberPointer:
       llvm_unreachable("member pointer type in C");
     }
-    break;
+    llvm_unreachable("Should have returned before this");
=20
   case Type::STK_Floating:
     switch (DestTy->getScalarTypeKind()) {
@@ -4020,7 +4150,7 @@
     case Type::STK_MemberPointer:
       llvm_unreachable("member pointer type in C");
     }
-    break;
+    llvm_unreachable("Should have returned before this");
=20
   case Type::STK_FloatingComplex:
     switch (DestTy->getScalarTypeKind()) {
@@ -4049,7 +4179,7 @@
     case Type::STK_MemberPointer:
       llvm_unreachable("member pointer type in C");
     }
-    break;
+    llvm_unreachable("Should have returned before this");
=20
   case Type::STK_IntegralComplex:
     switch (DestTy->getScalarTypeKind()) {
@@ -4078,7 +4208,7 @@
     case Type::STK_MemberPointer:
       llvm_unreachable("member pointer type in C");
     }
-    break;
+    llvm_unreachable("Should have returned before this");
   }
=20
   llvm_unreachable("Unhandled scalar cast");
@@ -4116,7 +4246,7 @@
   // (See OpenCL 6.2).
   if (SrcTy->isVectorType()) {
     if (Context.getTypeSize(DestTy) !=3D Context.getTypeSize(SrcTy)
-        || (getLangOptions().OpenCL &&
+        || (getLangOpts().OpenCL &&
             (DestTy.getCanonicalType() !=3D SrcTy.getCanonicalType()))) {
       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
         << DestTy << SrcTy << R;
@@ -4156,7 +4286,7 @@
   if (D.isInvalidType())
     return ExprError();
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // Check that there are no default arguments (C++ only).
     CheckExtraCXXDefaultArguments(D);
   }
@@ -4172,7 +4302,7 @@
   // i.e. all the elements are integer constants.
   ParenExpr *PE =3D dyn_cast<ParenExpr>(CastExpr);
   ParenListExpr *PLE =3D dyn_cast<ParenListExpr>(CastExpr);
-  if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
+  if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
        && castType->isVectorType() && (PE || PLE)) {
     if (PLE && PLE->getNumExprs() =3D=3D 0) {
       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
@@ -4239,7 +4369,9 @@
     // be replicated to all the components of the vector
     if (numExprs =3D=3D 1) {
       QualType ElemTy =3D Ty->getAs<VectorType>()->getElementType();
-      ExprResult Literal =3D Owned(exprs[0]);
+      ExprResult Literal =3D DefaultLvalueConversion(exprs[0]);
+      if (Literal.isInvalid())
+        return ExprError();
       Literal =3D ImpCastExprToType(Literal.take(), ElemTy,
                                   PrepareScalarCast(Literal, ElemTy));
       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take=
());
@@ -4250,24 +4382,24 @@
       return ExprError();
     }
     else
-      for (unsigned i =3D 0, e =3D numExprs; i !=3D e; ++i)
-        initExprs.push_back(exprs[i]);
+      initExprs.append(exprs, exprs + numExprs);
   }
   else {
     // For OpenCL, when the number of initializers is a single value,
     // it will be replicated to all components of the vector.
-    if (getLangOptions().OpenCL &&
+    if (getLangOpts().OpenCL &&
         VTy->getVectorKind() =3D=3D VectorType::GenericVector &&
         numExprs =3D=3D 1) {
         QualType ElemTy =3D Ty->getAs<VectorType>()->getElementType();
-        ExprResult Literal =3D Owned(exprs[0]);
+        ExprResult Literal =3D DefaultLvalueConversion(exprs[0]);
+        if (Literal.isInvalid())
+          return ExprError();
         Literal =3D ImpCastExprToType(Literal.take(), ElemTy,
                                     PrepareScalarCast(Literal, ElemTy));
         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.ta=
ke());
     }
    =20
-    for (unsigned i =3D 0, e =3D numExprs; i !=3D e; ++i)
-      initExprs.push_back(exprs[i]);
+    initExprs.append(exprs, exprs + numExprs);
   }
   // FIXME: This means that pretty-printing the final AST will produce cur=
ly
   // braces instead of the original commas.
@@ -4278,8 +4410,8 @@
   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
 }
=20
-/// This is not an AltiVec-style cast, so turn the ParenListExpr into a se=
quence
-/// of comma binary operators.
+/// This is not an AltiVec-style cast or or C++ direct-initialization, so =
turn
+/// the ParenListExpr into a sequence of comma binary operators.
 ExprResult
 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
   ParenListExpr *E =3D dyn_cast<ParenListExpr>(OrigExpr);
@@ -4297,18 +4429,13 @@
   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()=
);
 }
=20
-ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
-                                           SourceLocation R,
-                                           MultiExprArg Val) {
+ExprResult Sema::ActOnParenListExpr(SourceLocation L,
+                                    SourceLocation R,
+                                    MultiExprArg Val) {
   unsigned nexprs =3D Val.size();
   Expr **exprs =3D reinterpret_cast<Expr**>(Val.release());
   assert((exprs !=3D 0) && "ActOnParenOrParenListExpr() missing expr list"=
);
-  Expr *expr;
-  if (nexprs =3D=3D 1)
-    expr =3D new (Context) ParenExpr(L, R, exprs[0]);
-  else
-    expr =3D new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
-                                       exprs[nexprs-1]->getType());
+  Expr *expr =3D new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
   return Owned(expr);
 }
=20
@@ -4358,11 +4485,11 @@
   if (CondTy->isScalarType()) return false;
=20
   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or sca=
lar.
-  if (S.getLangOptions().OpenCL && CondTy->isVectorType())
+  if (S.getLangOpts().OpenCL && CondTy->isVectorType())
     return false;
=20
   // Emit the proper error message.
-  S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
+  S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
                               diag::err_typecheck_cond_expect_scalar :
                               diag::err_typecheck_cond_expect_scalar_or_ve=
ctor)
     << CondTy;
@@ -4446,8 +4573,28 @@
     rhptee =3D RHSTy->castAs<PointerType>()->getPointeeType();
   }
=20
-  if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
-                                    rhptee.getUnqualifiedType())) {
+  // C99 6.5.15p6: If both operands are pointers to compatible types or to
+  // differently qualified versions of compatible types, the result type is
+  // a pointer to an appropriately qualified version of the composite
+  // type.
+
+  // Only CVR-qualifiers exist in the standard, and the differently-qualif=
ied
+  // clause doesn't make sense for our extensions. E.g. address space 2 sh=
ould
+  // be incompatible with address space 3: they may live on different devi=
ces or
+  // anything.
+  Qualifiers lhQual =3D lhptee.getQualifiers();
+  Qualifiers rhQual =3D rhptee.getQualifiers();
+
+  unsigned MergedCVRQual =3D lhQual.getCVRQualifiers() | rhQual.getCVRQual=
ifiers();
+  lhQual.removeCVRQualifiers();
+  rhQual.removeCVRQualifiers();
+
+  lhptee =3D S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQua=
l);
+  rhptee =3D S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQua=
l);
+
+  QualType CompositeTy =3D S.Context.mergeTypes(lhptee, rhptee);
+
+  if (CompositeTy.isNull()) {
     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
       << LHSTy << RHSTy << LHS.get()->getSourceRange()
       << RHS.get()->getSourceRange();
@@ -4461,16 +4608,12 @@
   }
=20
   // The pointer types are compatible.
-  // C99 6.5.15p6: If both operands are pointers to compatible types *or* =
to
-  // differently qualified versions of compatible types, the result type is
-  // a pointer to an appropriately qualified version of the *composite*
-  // type.
-  // FIXME: Need to calculate the composite type.
-  // FIXME: Need to add qualifiers
-
-  LHS =3D S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
-  RHS =3D S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
-  return LHSTy;
+  QualType ResultTy =3D CompositeTy.withCVRQualifiers(MergedCVRQual);
+  ResultTy =3D S.Context.getPointerType(ResultTy);
+
+  LHS =3D S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
+  RHS =3D S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
+  return ResultTy;
 }
=20
 /// \brief Return the resulting type when the operands are both block poin=
ters.
@@ -4574,7 +4717,7 @@
   RHS =3D move(RHSResult);
=20
   // C++ is sufficiently different to merit its own checker.
-  if (getLangOptions().CPlusPlus)
+  if (getLangOpts().CPlusPlus)
     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc=
);
=20
   VK =3D VK_RValue;
@@ -4605,7 +4748,7 @@
   // OpenCL: If the condition is a vector, and both operands are scalar,
   // attempt to implicity convert them to the vector type to act like the
   // built in select.
-  if (getLangOptions().OpenCL && CondTy->isVectorType())
+  if (getLangOpts().OpenCL && CondTy->isVectorType())
     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
       return QualType();
  =20
@@ -4780,6 +4923,14 @@
   }
   // Check Objective-C object pointer types and 'void *'
   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
+    if (getLangOpts().ObjCAutoRefCount) {
+      // ARC forbids the implicit conversion of object pointers to 'void *=
',
+      // so these types are not compatible.
+      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
+          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
+      LHS =3D RHS =3D true;
+      return QualType();
+    }
     QualType lhptee =3D LHSTy->getAs<PointerType>()->getPointeeType();
     QualType rhptee =3D RHSTy->getAs<ObjCObjectPointerType>()->getPointeeT=
ype();
     QualType destPointee
@@ -4792,6 +4943,14 @@
     return destType;
   }
   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
+    if (getLangOpts().ObjCAutoRefCount) {
+      // ARC forbids the implicit conversion of object pointers to 'void *=
',
+      // so these types are not compatible.
+      Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
+          << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
+      LHS =3D RHS =3D true;
+      return QualType();
+    }
     QualType lhptee =3D LHSTy->getAs<ObjCObjectPointerType>()->getPointeeT=
ype();
     QualType rhptee =3D RHSTy->getAs<PointerType>()->getPointeeType();
     QualType destPointee
@@ -4938,7 +5097,7 @@
=20
     // We usually want to apply unary conversions *before* saving, except
     // in the special case of a C++ l-value conditional.
-    if (!(getLangOptions().CPlusPlus
+    if (!(getLangOpts().CPlusPlus
           && !commonExpr->isTypeDependent()
           && commonExpr->getValueKind() =3D=3D RHSExpr->getValueKind()
           && commonExpr->isGLValue()
@@ -4954,7 +5113,8 @@
     opaqueValue =3D new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
                                                 commonExpr->getType(),
                                                 commonExpr->getValueKind(),
-                                                commonExpr->getObjectKind(=
));
+                                                commonExpr->getObjectKind(=
),
+                                                commonExpr);
     LHSExpr =3D CondExpr =3D opaqueValue;
   }
=20
@@ -5019,9 +5179,9 @@
=20
     // It's okay to add or remove GC or lifetime qualifiers when convertin=
g to
     // and from void*.
-    else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
+    else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
                         .compatiblyIncludes(
-                                rhq.withoutObjCGCAttr().withoutObjCGLifeti=
me())
+                                rhq.withoutObjCGCAttr().withoutObjCLifetim=
e())
              && (lhptee->isVoidType() || rhptee->isVoidType()))
       ; // keep old
=20
@@ -5099,7 +5259,7 @@
     // General pointer incompatibility takes priority over qualifiers.
     return Sema::IncompatiblePointer;
   }
-  if (!S.getLangOptions().CPlusPlus &&
+  if (!S.getLangOpts().CPlusPlus &&
       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
     return Sema::IncompatiblePointer;
   return ConvTy;
@@ -5122,7 +5282,7 @@
   rhptee =3D cast<BlockPointerType>(RHSType)->getPointeeType();
=20
   // In C++, the types have to match exactly.
-  if (S.getLangOptions().CPlusPlus)
+  if (S.getLangOpts().CPlusPlus)
     return Sema::IncompatibleBlockPointer;
=20
   Sema::AssignConvertType ConvTy =3D Sema::Compatible;
@@ -5161,7 +5321,9 @@
   QualType lhptee =3D LHSType->getAs<ObjCObjectPointerType>()->getPointeeT=
ype();
   QualType rhptee =3D RHSType->getAs<ObjCObjectPointerType>()->getPointeeT=
ype();
=20
-  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
+  if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
+      // make an exception for id<P>
+      !LHSType->isObjCQualifiedIdType())
     return Sema::CompatiblePointerDiscardsQualifiers;
=20
   if (S.Context.typesAreCompatible(LHSType, RHSType))
@@ -5213,9 +5375,6 @@
   LHSType =3D Context.getCanonicalType(LHSType).getUnqualifiedType();
   RHSType =3D Context.getCanonicalType(RHSType).getUnqualifiedType();
=20
-  // We can't do assignment from/to atomics yet.
-  if (LHSType->isAtomicType())
-    return Incompatible;
=20
   // Common case: no conversion required.
   if (LHSType =3D=3D RHSType) {
@@ -5223,6 +5382,21 @@
     return Compatible;
   }
=20
+  if (const AtomicType *AtomicTy =3D dyn_cast<AtomicType>(LHSType)) {
+    if (AtomicTy->getValueType() =3D=3D RHSType) {
+      Kind =3D CK_NonAtomicToAtomic;
+      return Compatible;
+    }
+  }
+
+  if (const AtomicType *AtomicTy =3D dyn_cast<AtomicType>(RHSType)) {
+    if (AtomicTy->getValueType() =3D=3D LHSType) {
+      Kind =3D CK_AtomicToNonAtomic;
+      return Compatible;
+    }
+  }
+
+
   // If the left-hand side is a reference type, then we are in a
   // (rare!) case where we've allowed the use of references in C,
   // e.g., as a parameter type in a built-in function. In this case,
@@ -5269,7 +5443,7 @@
       // If we are allowing lax vector conversions, and LHS and RHS are bo=
th
       // vectors, the total size only needs to be the same. This is a bitc=
ast;
       // no bits are changed but the result type is different.
-      if (getLangOptions().LaxVectorConversions &&
+      if (getLangOpts().LaxVectorConversions &&
           (Context.getTypeSize(LHSType) =3D=3D Context.getTypeSize(RHSType=
))) {
         Kind =3D CK_BitCast;
         return IncompatibleVectors;
@@ -5280,7 +5454,7 @@
=20
   // Arithmetic conversions.
   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
-      !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
+      !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
     Kind =3D PrepareScalarCast(RHS, LHSType);
     return Compatible;
   }
@@ -5346,7 +5520,7 @@
     }
=20
     // id -> T^
-    if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
+    if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
       Kind =3D CK_AnyPointerToBlockPointerCast;
       return Compatible;
     }
@@ -5368,7 +5542,7 @@
       Kind =3D CK_BitCast;
       Sema::AssignConvertType result =3D=20
         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
-      if (getLangOptions().ObjCAutoRefCount &&
+      if (getLangOpts().ObjCAutoRefCount &&
           result =3D=3D Compatible &&=20
           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
         result =3D IncompatibleObjCWeakRef;
@@ -5535,18 +5709,32 @@
 Sema::AssignConvertType
 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
                                        bool Diagnose) {
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
       // C++ 5.17p3: If the left operand is not of class type, the
       // expression is implicitly converted (C++ 4) to the
       // cv-unqualified type of the left operand.
-      ExprResult Res =3D PerformImplicitConversion(RHS.get(),
-                                                 LHSType.getUnqualifiedTyp=
e(),
-                                                 AA_Assigning, Diagnose);
+      ExprResult Res;
+      if (Diagnose) {
+        Res =3D PerformImplicitConversion(RHS.get(), LHSType.getUnqualifie=
dType(),
+                                        AA_Assigning);
+      } else {
+        ImplicitConversionSequence ICS =3D
+            TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
+                                  /*SuppressUserConversions=3D*/false,
+                                  /*AllowExplicit=3D*/false,
+                                  /*InOverloadResolution=3D*/false,
+                                  /*CStyle=3D*/false,
+                                  /*AllowObjCWritebackConversion=3D*/false=
);
+        if (ICS.isFailure())
+          return Incompatible;
+        Res =3D PerformImplicitConversion(RHS.get(), LHSType.getUnqualifie=
dType(),
+                                        ICS, AA_Assigning);
+      }
       if (Res.isInvalid())
         return Incompatible;
       Sema::AssignConvertType result =3D Compatible;
-      if (getLangOptions().ObjCAutoRefCount &&
+      if (getLangOpts().ObjCAutoRefCount &&
           !CheckObjCARCUnavailableWeakConversion(LHSType,
                                                  RHS.get()->getType()))
         result =3D IncompatibleObjCWeakRef;
@@ -5609,6 +5797,15 @@
=20
 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
                                    SourceLocation Loc, bool IsCompAssign) {
+  if (!IsCompAssign) {
+    LHS =3D DefaultFunctionArrayLvalueConversion(LHS.take());
+    if (LHS.isInvalid())
+      return QualType();
+  }
+  RHS =3D DefaultFunctionArrayLvalueConversion(RHS.take());
+  if (RHS.isInvalid())
+    return QualType();
+
   // For conversion purposes, we ignore any qualifiers.
   // For example, "const float" and "float" are equivalent.
   QualType LHSType =3D
@@ -5633,7 +5830,7 @@
     return RHSType;
   }
=20
-  if (getLangOptions().LaxVectorConversions &&
+  if (getLangOpts().LaxVectorConversions &&
       Context.getTypeSize(LHSType) =3D=3D Context.getTypeSize(RHSType)) {
     // If we are allowing lax vector conversions, and LHS and RHS are both
     // vectors, the total size only needs to be the same. This is a
@@ -5738,9 +5935,15 @@
   if (LHS.isInvalid() || RHS.isInvalid())
     return QualType();
=20
+
   if (!LHS.get()->getType()->isArithmeticType() ||
-      !RHS.get()->getType()->isArithmeticType())
+      !RHS.get()->getType()->isArithmeticType()) {
+    if (IsCompAssign &&
+        LHS.get()->getType()->isAtomicType() &&
+        RHS.get()->getType()->isArithmeticType())
+      return compType;
     return InvalidOperands(Loc, LHS, RHS);
+  }
=20
   // Check for division by zero.
   if (IsDiv &&
@@ -5784,7 +5987,7 @@
 /// \brief Diagnose invalid arithmetic on two void pointers.
 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Lo=
c,
                                                 Expr *LHSExpr, Expr *RHSEx=
pr) {
-  S.Diag(Loc, S.getLangOptions().CPlusPlus
+  S.Diag(Loc, S.getLangOpts().CPlusPlus
                 ? diag::err_typecheck_pointer_arith_void_type
                 : diag::ext_gnu_void_ptr)
     << 1 /* two pointers */ << LHSExpr->getSourceRange()
@@ -5794,7 +5997,7 @@
 /// \brief Diagnose invalid arithmetic on a void pointer.
 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
                                             Expr *Pointer) {
-  S.Diag(Loc, S.getLangOptions().CPlusPlus
+  S.Diag(Loc, S.getLangOpts().CPlusPlus
                 ? diag::err_typecheck_pointer_arith_void_type
                 : diag::ext_gnu_void_ptr)
     << 0 /* one pointer */ << Pointer->getSourceRange();
@@ -5805,7 +6008,7 @@
                                                     Expr *LHS, Expr *RHS) {
   assert(LHS->getType()->isAnyPointerType());
   assert(RHS->getType()->isAnyPointerType());
-  S.Diag(Loc, S.getLangOptions().CPlusPlus
+  S.Diag(Loc, S.getLangOpts().CPlusPlus
                 ? diag::err_typecheck_pointer_arith_function_type
                 : diag::ext_gnu_ptr_func_arith)
     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
@@ -5820,7 +6023,7 @@
 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Lo=
c,
                                                 Expr *Pointer) {
   assert(Pointer->getType()->isAnyPointerType());
-  S.Diag(Loc, S.getLangOptions().CPlusPlus
+  S.Diag(Loc, S.getLangOpts().CPlusPlus
                 ? diag::err_typecheck_pointer_arith_function_type
                 : diag::ext_gnu_ptr_func_arith)
     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
@@ -5861,11 +6064,11 @@
   QualType PointeeTy =3D Operand->getType()->getPointeeType();
   if (PointeeTy->isVoidType()) {
     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
-    return !S.getLangOptions().CPlusPlus;
+    return !S.getLangOpts().CPlusPlus;
   }
   if (PointeeTy->isFunctionType()) {
     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
-    return !S.getLangOptions().CPlusPlus;
+    return !S.getLangOpts().CPlusPlus;
   }
=20
   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
@@ -5900,7 +6103,7 @@
     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExp=
r);
     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
=20
-    return !S.getLangOptions().CPlusPlus;
+    return !S.getLangOpts().CPlusPlus;
   }
=20
   bool isLHSFuncPtr =3D isLHSPointer && LHSPointeeTy->isFunctionType();
@@ -5911,7 +6114,7 @@
                                                                 RHSExpr);
     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
=20
-    return !S.getLangOptions().CPlusPlus;
+    return !S.getLangOpts().CPlusPlus;
   }
=20
   if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
@@ -5934,6 +6137,46 @@
   return false;
 }
=20
+/// diagnoseStringPlusInt - Emit a warning when adding an integer to a str=
ing
+/// literal.
+static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
+                                  Expr *LHSExpr, Expr *RHSExpr) {
+  StringLiteral* StrExpr =3D dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCas=
ts());
+  Expr* IndexExpr =3D RHSExpr;
+  if (!StrExpr) {
+    StrExpr =3D dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
+    IndexExpr =3D LHSExpr;
+  }
+
+  bool IsStringPlusInt =3D StrExpr &&
+      IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
+  if (!IsStringPlusInt)
+    return;
+
+  llvm::APSInt index;
+  if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
+    unsigned StrLenWithNull =3D StrExpr->getLength() + 1;
+    if (index.isNonNegative() &&
+        index <=3D llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWit=
hNull),
+                              index.isUnsigned()))
+      return;
+  }
+
+  SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
+  Self.Diag(OpLoc, diag::warn_string_plus_int)
+      << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
+
+  // Only print a fixit for "str" + int, not for int + "str".
+  if (IndexExpr =3D=3D RHSExpr) {
+    SourceLocation EndLoc =3D Self.PP.getLocForEndOfToken(RHSExpr->getLocE=
nd());
+    Self.Diag(OpLoc, diag::note_string_plus_int_silence)
+        << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
+        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
+        << FixItHint::CreateInsertion(EndLoc, "]");
+  } else
+    Self.Diag(OpLoc, diag::note_string_plus_int_silence);
+}
+
 /// \brief Emit error when two pointers are incompatible.
 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
                                            Expr *LHSExpr, Expr *RHSExpr) {
@@ -5945,7 +6188,8 @@
 }
=20
 QualType Sema::CheckAdditionOperands( // C99 6.5.6
-  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHST=
y) {
+    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
+    QualType* CompLHSTy) {
   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=3D*/false);
=20
   if (LHS.get()->getType()->isVectorType() ||
@@ -5959,6 +6203,10 @@
   if (LHS.isInvalid() || RHS.isInvalid())
     return QualType();
=20
+  // Diagnose "string literal" '+' int.
+  if (Opc =3D=3D BO_Add)
+    diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
+
   // handle the common case first (both operands are arithmetic).
   if (LHS.get()->getType()->isArithmeticType() &&
       RHS.get()->getType()->isArithmeticType()) {
@@ -5966,6 +6214,12 @@
     return compType;
   }
=20
+  if (LHS.get()->getType()->isAtomicType() &&
+      RHS.get()->getType()->isArithmeticType()) {
+    *CompLHSTy =3D LHS.get()->getType();
+    return compType;
+  }
+
   // Put any potential pointer into PExp
   Expr* PExp =3D LHS.get(), *IExp =3D RHS.get();
   if (IExp->getType()->isAnyPointerType())
@@ -6026,6 +6280,12 @@
     return compType;
   }
=20
+  if (LHS.get()->getType()->isAtomicType() &&
+      RHS.get()->getType()->isArithmeticType()) {
+    *CompLHSTy =3D LHS.get()->getType();
+    return compType;
+  }
+
   // Either ptr - int   or   ptr - ptr.
   if (LHS.get()->getType()->isAnyPointerType()) {
     QualType lpointee =3D LHS.get()->getType()->getPointeeType();
@@ -6039,11 +6299,9 @@
       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
         return QualType();
=20
-      Expr *IExpr =3D RHS.get()->IgnoreParenCasts();
-      UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
-                           OK_Ordinary, IExpr->getExprLoc());
       // Check array bounds for pointer arithemtic
-      CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
+      CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
+                       /*AllowOnePastEnd*/true, /*IndexNegated*/true);
=20
       if (CompLHSTy) *CompLHSTy =3D LHS.get()->getType();
       return LHS.get()->getType();
@@ -6054,7 +6312,7 @@
           =3D RHS.get()->getType()->getAs<PointerType>()) {
       QualType rpointee =3D RHSPTy->getPointeeType();
=20
-      if (getLangOptions().CPlusPlus) {
+      if (getLangOpts().CPlusPlus) {
         // Pointee types must be the same: C++ [expr.add]
         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
@@ -6131,7 +6389,7 @@
=20
   // Print the bit representation of the signed integer as an unsigned
   // hexadecimal number.
-  llvm::SmallString<40> HexResult;
+  SmallString<40> HexResult;
   Result.toString(HexResult, 16, /*Signed =3D*/false, /*Literal =3D*/true);
=20
   // If we are only missing a sign bit, this is less likely to result in a=
ctual
@@ -6459,7 +6717,7 @@
     QualType RCanPointeeTy =3D
       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
=20
-    if (getLangOptions().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       if (LCanPointeeTy =3D=3D RCanPointeeTy)
         return ResultTy;
       if (!IsRelational &&
@@ -6515,7 +6773,7 @@
     return ResultTy;
   }
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // Comparison of nullptr_t with itself.
     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
       return ResultTy;
@@ -6639,11 +6897,11 @@
     bool isError =3D false;
     if ((LHSIsNull && LHSType->isIntegerType()) ||
         (RHSIsNull && RHSType->isIntegerType())) {
-      if (IsRelational && !getLangOptions().CPlusPlus)
+      if (IsRelational && !getLangOpts().CPlusPlus)
         DiagID =3D diag::ext_typecheck_ordered_comparison_of_pointer_and_z=
ero;
-    } else if (IsRelational && !getLangOptions().CPlusPlus)
+    } else if (IsRelational && !getLangOpts().CPlusPlus)
       DiagID =3D diag::ext_typecheck_ordered_comparison_of_pointer_integer;
-    else if (getLangOptions().CPlusPlus) {
+    else if (getLangOpts().CPlusPlus) {
       DiagID =3D diag::err_typecheck_comparison_of_pointer_integer;
       isError =3D true;
     } else
@@ -6681,6 +6939,26 @@
   return InvalidOperands(Loc, LHS, RHS);
 }
=20
+
+// Return a signed type that is of identical size and number of elements.
+// For floating point vectors, return an integer type of identical size=20
+// and number of elements.
+QualType Sema::GetSignedVectorType(QualType V) {
+  const VectorType *VTy =3D V->getAs<VectorType>();
+  unsigned TypeSize =3D Context.getTypeSize(VTy->getElementType());
+  if (TypeSize =3D=3D Context.getTypeSize(Context.CharTy))
+    return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
+  else if (TypeSize =3D=3D Context.getTypeSize(Context.ShortTy))
+    return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()=
);
+  else if (TypeSize =3D=3D Context.getTypeSize(Context.IntTy))
+    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
+  else if (TypeSize =3D=3D Context.getTypeSize(Context.LongTy))
+    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
+  assert(TypeSize =3D=3D Context.getTypeSize(Context.LongLongTy) &&
+         "Unhandled vector element size in vector compare");
+  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements(=
));
+}
+
 /// CheckVectorCompareOperands - vector comparisons are a clang extension =
that
 /// operates on extended vector types.  Instead of producing an IntTy resu=
lt,
 /// like a scalar comparison, a vector comparison produces a vector of int=
eger
@@ -6695,7 +6973,6 @@
     return vType;
=20
   QualType LHSType =3D LHS.get()->getType();
-  QualType RHSType =3D RHS.get()->getType();
=20
   // If AltiVec, the comparison results in a numeric type, i.e.
   // bool for C++, int for C
@@ -6706,8 +6983,10 @@
   // x =3D=3D x, x !=3D x, x < x, etc.  These always evaluate to a constan=
t, and
   // often indicate logic errors in the program.
   if (!LHSType->hasFloatingRepresentation()) {
-    if (DeclRefExpr* DRL =3D dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens=
()))
-      if (DeclRefExpr* DRR =3D dyn_cast<DeclRefExpr>(RHS.get()->IgnorePare=
ns()))
+    if (DeclRefExpr* DRL
+          =3D dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
+      if (DeclRefExpr* DRR
+            =3D dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
         if (DRL->getDecl() =3D=3D DRR->getDecl())
           DiagRuntimeBehavior(Loc, 0,
                               PDiag(diag::warn_comparison_always)
@@ -6718,26 +6997,23 @@
=20
   // Check for comparisons of floating point operands using !=3D and =3D=
=3D.
   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
-    assert (RHSType->hasFloatingRepresentation());
+    assert (RHS.get()->getType()->hasFloatingRepresentation());
     CheckFloatComparison(Loc, LHS.get(), RHS.get());
   }
-
-  // Return the type for the comparison, which is the same as vector type =
for
-  // integer vectors, or an integer type of identical size and number of
-  // elements for floating point vectors.
-  if (LHSType->hasIntegerRepresentation())
-    return LHSType;
-
-  const VectorType *VTy =3D LHSType->getAs<VectorType>();
-  unsigned TypeSize =3D Context.getTypeSize(VTy->getElementType());
-  if (TypeSize =3D=3D Context.getTypeSize(Context.IntTy))
-    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
-  if (TypeSize =3D=3D Context.getTypeSize(Context.LongTy))
-    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
-
-  assert(TypeSize =3D=3D Context.getTypeSize(Context.LongLongTy) &&
-         "Unhandled vector element size in vector compare");
-  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements(=
));
+ =20
+  // Return a signed type for the vector.
+  return GetSignedVectorType(LHSType);
+}
+
+QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
+                                          SourceLocation Loc) {
+  // Ensure that either both operands are of the same vector type, or
+  // one operand is of a vector type and the other is of its element type.
+  QualType vType =3D CheckVectorOperands(LHS, RHS, Loc, false);
+  if (vType.isNull() || vType->isFloatingType())
+    return InvalidOperands(Loc, LHS, RHS);
+ =20
+  return GetSignedVectorType(LHS.get()->getType());
 }
=20
 inline QualType Sema::CheckBitwiseOperands(
@@ -6770,6 +7046,10 @@
 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
  =20
+  // Check vector operands differently.
+  if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVect=
orType())
+    return CheckVectorLogicalOperands(LHS, RHS, Loc);
+ =20
   // Diagnose cases where the user write a logical and/or but probably mea=
nt a
   // bitwise one.  We do this when the LHS is a non-bool integer and the R=
HS
   // is a constant.
@@ -6782,10 +7062,10 @@
     // that isn't 0 or 1 (which indicate a potential logical operation that
     // happened to fold to true/false) then warn.
     // Parens on the RHS are ignored.
-    Expr::EvalResult Result;
-    if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
-      if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()=
) ||
-          (Result.Val.getInt() !=3D 0 && Result.Val.getInt() !=3D 1)) {
+    llvm::APSInt Result;
+    if (RHS.get()->EvaluateAsInt(Result, Context))
+      if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
+          (Result !=3D 0 && Result !=3D 1)) {
         Diag(Loc, diag::warn_logical_instead_of_bitwise)
           << RHS.get()->getSourceRange()
           << (Opc =3D=3D BO_LAnd ? "&&" : "||");
@@ -6794,7 +7074,7 @@
             << (Opc =3D=3D BO_LAnd ? "&" : "|")
             << FixItHint::CreateReplacement(SourceRange(
                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
-                                                getLangOptions())),
+                                                getLangOpts())),
                                             Opc =3D=3D BO_LAnd ? "&" : "|"=
);
         if (Opc =3D=3D BO_LAnd)
           // Suggest replacing "Foo() && kNonZero" with "Foo()"
@@ -6803,12 +7083,12 @@
                   SourceRange(
                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
                                                  0, getSourceManager(),
-                                                 getLangOptions()),
+                                                 getLangOpts()),
                       RHS.get()->getLocEnd()));
       }
   }
  =20
-  if (!Context.getLangOptions().CPlusPlus) {
+  if (!Context.getLangOpts().CPlusPlus) {
     LHS =3D UsualUnaryConversions(LHS.take());
     if (LHS.isInvalid())
       return QualType();
@@ -6851,63 +7131,68 @@
 /// depends on various declarations and thus must be treated specially.
 ///
 static bool IsReadonlyProperty(Expr *E, Sema &S) {
-  if (E->getStmtClass() =3D=3D Expr::ObjCPropertyRefExprClass) {
-    const ObjCPropertyRefExpr* PropExpr =3D cast<ObjCPropertyRefExpr>(E);
-    if (PropExpr->isImplicitProperty()) return false;
-
-    ObjCPropertyDecl *PDecl =3D PropExpr->getExplicitProperty();
-    QualType BaseType =3D PropExpr->isSuperReceiver() ?=20
+  const ObjCPropertyRefExpr *PropExpr =3D dyn_cast<ObjCPropertyRefExpr>(E);
+  if (!PropExpr) return false;
+  if (PropExpr->isImplicitProperty()) return false;
+
+  ObjCPropertyDecl *PDecl =3D PropExpr->getExplicitProperty();
+  QualType BaseType =3D PropExpr->isSuperReceiver() ?=20
                             PropExpr->getSuperReceiverType() : =20
                             PropExpr->getBase()->getType();
      =20
-    if (const ObjCObjectPointerType *OPT =3D
-          BaseType->getAsObjCInterfacePointerType())
-      if (ObjCInterfaceDecl *IFace =3D OPT->getInterfaceDecl())
-        if (S.isPropertyReadonly(PDecl, IFace))
-          return true;
-  }
+  if (const ObjCObjectPointerType *OPT =3D
+      BaseType->getAsObjCInterfacePointerType())
+    if (ObjCInterfaceDecl *IFace =3D OPT->getInterfaceDecl())
+      if (S.isPropertyReadonly(PDecl, IFace))
+        return true;
   return false;
 }
=20
-static bool IsConstProperty(Expr *E, Sema &S) {
-  if (E->getStmtClass() =3D=3D Expr::ObjCPropertyRefExprClass) {
-    const ObjCPropertyRefExpr* PropExpr =3D cast<ObjCPropertyRefExpr>(E);
-    if (PropExpr->isImplicitProperty()) return false;
-   =20
-    ObjCPropertyDecl *PDecl =3D PropExpr->getExplicitProperty();
-    QualType T =3D PDecl->getType();
-    if (T->isReferenceType())
-      T =3D T->getAs<ReferenceType>()->getPointeeType();
-    CanQualType CT =3D S.Context.getCanonicalType(T);
-    return CT.isConstQualified();
-  }
-  return false;
-}
-
 static bool IsReadonlyMessage(Expr *E, Sema &S) {
-  if (E->getStmtClass() !=3D Expr::MemberExprClass)=20
-    return false;
-  const MemberExpr *ME =3D cast<MemberExpr>(E);
-  NamedDecl *Member =3D ME->getMemberDecl();
-  if (isa<FieldDecl>(Member)) {
-    Expr *Base =3D ME->getBase()->IgnoreParenImpCasts();
-    if (Base->getStmtClass() !=3D Expr::ObjCMessageExprClass)
-      return false;
-    return cast<ObjCMessageExpr>(Base)->getMethodDecl() !=3D 0;
-  }
-  return false;
+  const MemberExpr *ME =3D dyn_cast<MemberExpr>(E);
+  if (!ME) return false;
+  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
+  ObjCMessageExpr *Base =3D
+    dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
+  if (!Base) return false;
+  return Base->getMethodDecl() !=3D 0;
+}
+
+/// Is the given expression (which must be 'const') a reference to a
+/// variable which was originally non-const, but which has become
+/// 'const' due to being captured within a block?
+enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
+static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
+  assert(E->isLValue() && E->getType().isConstQualified());
+  E =3D E->IgnoreParens();
+
+  // Must be a reference to a declaration from an enclosing scope.
+  DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E);
+  if (!DRE) return NCCK_None;
+  if (!DRE->refersToEnclosingLocal()) return NCCK_None;
+
+  // The declaration must be a variable which is not declared 'const'.
+  VarDecl *var =3D dyn_cast<VarDecl>(DRE->getDecl());
+  if (!var) return NCCK_None;
+  if (var->getType().isConstQualified()) return NCCK_None;
+  assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
+
+  // Decide whether the first capture was for a block or a lambda.
+  DeclContext *DC =3D S.CurContext;
+  while (DC->getParent() !=3D var->getDeclContext())
+    DC =3D DC->getParent();
+  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
 }
=20
 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If n=
ot,
 /// emit an error and return true.  If so, return false.
 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)=
 {
+  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
   SourceLocation OrigLoc =3D Loc;
   Expr::isModifiableLvalueResult IsLV =3D E->isModifiableLvalue(S.Context,
                                                               &Loc);
   if (IsLV =3D=3D Expr::MLV_Valid && IsReadonlyProperty(E, S))
     IsLV =3D Expr::MLV_ReadonlyProperty;
-  else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
-    IsLV =3D Expr::MLV_Valid;
   else if (IsLV =3D=3D Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
     IsLV =3D Expr::MLV_InvalidMessageExpression;
   if (IsLV =3D=3D Expr::MLV_Valid)
@@ -6919,9 +7204,19 @@
   case Expr::MLV_ConstQualified:
     Diag =3D diag::err_typecheck_assign_const;
=20
+    // Use a specialized diagnostic when we're assigning to an object
+    // from an enclosing function or block.
+    if (NonConstCaptureKind NCCK =3D isReferenceToNonConstCapture(S, E)) {
+      if (NCCK =3D=3D NCCK_Block)
+        Diag =3D diag::err_block_decl_ref_not_modifiable_lvalue;
+      else
+        Diag =3D diag::err_lambda_decl_ref_not_modifiable_lvalue;
+      break;
+    }
+
     // In ARC, use some specialized diagnostics for occasions where we
     // infer 'const'.  These are always pseudo-strong variables.
-    if (S.getLangOptions().ObjCAutoRefCount) {
+    if (S.getLangOpts().ObjCAutoRefCount) {
       DeclRefExpr *declRef =3D dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()=
);
       if (declRef && isa<VarDecl>(declRef->getDecl())) {
         VarDecl *var =3D cast<VarDecl>(declRef->getDecl());
@@ -6935,7 +7230,9 @@
           //  - self
           ObjCMethodDecl *method =3D S.getCurMethodDecl();
           if (method && var =3D=3D method->getSelfDecl())
-            Diag =3D diag::err_typecheck_arr_assign_self;
+            Diag =3D method->isClassMethod()
+              ? diag::err_typecheck_arc_assign_self_class_method
+              : diag::err_typecheck_arc_assign_self;
=20
           //  - fast enumeration variables
           else
@@ -6979,15 +7276,9 @@
   case Expr::MLV_DuplicateVectorComponents:
     Diag =3D diag::err_typecheck_duplicate_vector_components_not_mlvalue;
     break;
-  case Expr::MLV_NotBlockQualified:
-    Diag =3D diag::err_block_decl_ref_not_modifiable_lvalue;
-    break;
   case Expr::MLV_ReadonlyProperty:
-    Diag =3D diag::error_readonly_property_assignment;
-    break;
   case Expr::MLV_NoSetterProperty:
-    Diag =3D diag::error_nosetter_property_assignment;
-    break;
+    llvm_unreachable("readonly properties should be processed differently"=
);
   case Expr::MLV_InvalidMessageExpression:
     Diag =3D diag::error_readonly_message_assignment;
     break;
@@ -7012,6 +7303,8 @@
 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
                                        SourceLocation Loc,
                                        QualType CompoundType) {
+  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
+
   // Verify that LHS is a modifiable lvalue, and emit error if not.
   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
     return QualType();
@@ -7022,14 +7315,6 @@
   AssignConvertType ConvTy;
   if (CompoundType.isNull()) {
     QualType LHSTy(LHSType);
-    // Simple assignment "x =3D y".
-    if (LHSExpr->getObjectKind() =3D=3D OK_ObjCProperty) {
-      ExprResult LHSResult =3D Owned(LHSExpr);
-      ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
-      if (LHSResult.isInvalid())
-        return QualType();
-      LHSExpr =3D LHSResult.take();
-    }
     ConvTy =3D CheckSingleAssignmentConstraints(LHSTy, RHS);
     if (RHS.isInvalid())
       return QualType();
@@ -7042,10 +7327,9 @@
       ConvTy =3D Compatible;
=20
     if (ConvTy =3D=3D Compatible &&
-        getLangOptions().ObjCNonFragileABI &&
         LHSType->isObjCObjectType())
-      Diag(Loc, diag::err_assignment_requires_nonfragile_object)
-        << LHSType;
+        Diag(Loc, diag::err_objc_object_assignment)
+          << LHSType;
=20
     // If the RHS is a unary plus or minus, check to see if they =3D and +=
 are
     // right next to each other.  If so, the user may have typo'd "x =3D+ =
4"
@@ -7072,7 +7356,7 @@
     if (ConvTy =3D=3D Compatible) {
       if (LHSType.getObjCLifetime() =3D=3D Qualifiers::OCL_Strong)
         checkRetainCycles(LHSExpr, RHS.get());
-      else if (getLangOptions().ObjCAutoRefCount)
+      else if (getLangOpts().ObjCAutoRefCount)
         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
     }
   } else {
@@ -7093,7 +7377,7 @@
   // is converted to the type of the assignment expression (above).
   // C++ 5.17p1: the type of the assignment expression is that of its left
   // operand.
-  return (getLangOptions().CPlusPlus
+  return (getLangOpts().CPlusPlus
           ? LHSType : LHSType.getUnqualifiedType());
 }
=20
@@ -7117,7 +7401,7 @@
   if (LHS.isInvalid())
     return QualType();
=20
-  if (!S.getLangOptions().CPlusPlus) {
+  if (!S.getLangOpts().CPlusPlus) {
     RHS =3D S.DefaultFunctionArrayLvalueConversion(RHS.take());
     if (RHS.isInvalid())
       return QualType();
@@ -7139,9 +7423,15 @@
     return S.Context.DependentTy;
=20
   QualType ResType =3D Op->getType();
+  // Atomic types can be used for increment / decrement where the non-atom=
ic
+  // versions can, so ignore the _Atomic() specifier for the purpose of
+  // checking.
+  if (const AtomicType *ResAtomicType =3D ResType->getAs<AtomicType>())
+    ResType =3D ResAtomicType->getValueType();
+
   assert(!ResType.isNull() && "no type for increment/decrement expression"=
);
=20
-  if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
+  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
     // Decrement of bool is not allowed.
     if (!IsInc) {
       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
@@ -7168,7 +7458,7 @@
     if (PR.isInvalid()) return QualType();
     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
                                           IsInc, IsPrefix);
-  } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
+  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
   } else {
     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
@@ -7182,7 +7472,7 @@
   // In C++, a prefix increment is the same type as the operand. Otherwise
   // (in C or with postfix), the increment is the unqualified type of the
   // operand.
-  if (IsPrefix && S.getLangOptions().CPlusPlus) {
+  if (IsPrefix && S.getLangOpts().CPlusPlus) {
     VK =3D VK_LValue;
     return ResType;
   } else {
@@ -7190,102 +7480,6 @@
     return ResType.getUnqualifiedType();
   }
 }
-
-ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
-  assert(E->getValueKind() =3D=3D VK_LValue &&
-         E->getObjectKind() =3D=3D OK_ObjCProperty);
-  const ObjCPropertyRefExpr *PRE =3D E->getObjCProperty();
-
-  QualType T =3D E->getType();
-  QualType ReceiverType;
-  if (PRE->isObjectReceiver())
-    ReceiverType =3D PRE->getBase()->getType();
-  else if (PRE->isSuperReceiver())
-    ReceiverType =3D PRE->getSuperReceiverType();
-  else
-    ReceiverType =3D Context.getObjCInterfaceType(PRE->getClassReceiver());
-   =20
-  ExprValueKind VK =3D VK_RValue;
-  if (PRE->isImplicitProperty()) {
-    if (ObjCMethodDecl *GetterMethod =3D=20
-          PRE->getImplicitPropertyGetter()) {
-      T =3D getMessageSendResultType(ReceiverType, GetterMethod,=20
-                                   PRE->isClassReceiver(),=20
-                                   PRE->isSuperReceiver());
-      VK =3D Expr::getValueKindForType(GetterMethod->getResultType());
-    }
-    else {
-      Diag(PRE->getLocation(), diag::err_getter_not_found)
-            << PRE->getBase()->getType();
-    }
-  }
-  else {
-    // lvalue-ness of an explicit property is determined by
-    // getter type.
-    QualType ResT =3D PRE->getGetterResultType();
-    VK =3D Expr::getValueKindForType(ResT);
-  }
-   =20
-  E =3D ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
-                               E, 0, VK);
- =20
-  ExprResult Result =3D MaybeBindToTemporary(E);
-  if (!Result.isInvalid())
-    E =3D Result.take();
-
-  return Owned(E);
-}
-
-void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
-                                    QualType &LHSTy) {
-  assert(LHS.get()->getValueKind() =3D=3D VK_LValue &&
-         LHS.get()->getObjectKind() =3D=3D OK_ObjCProperty);
-  const ObjCPropertyRefExpr *PropRef =3D LHS.get()->getObjCProperty();
-
-  bool Consumed =3D false;
-
-  if (PropRef->isImplicitProperty()) {
-    // If using property-dot syntax notation for assignment, and there is a
-    // setter, RHS expression is being passed to the setter argument. So,
-    // type conversion (and comparison) is RHS to setter's argument type.
-    if (const ObjCMethodDecl *SetterMD =3D PropRef->getImplicitPropertySet=
ter()) {
-      ObjCMethodDecl::param_const_iterator P =3D SetterMD->param_begin();
-      LHSTy =3D (*P)->getType();
-      Consumed =3D (getLangOptions().ObjCAutoRefCount &&
-                  (*P)->hasAttr<NSConsumedAttr>());
-
-    // Otherwise, if the getter returns an l-value, just call that.
-    } else {
-      QualType Result =3D PropRef->getImplicitPropertyGetter()->getResultT=
ype();
-      ExprValueKind VK =3D Expr::getValueKindForType(Result);
-      if (VK =3D=3D VK_LValue) {
-        LHS =3D ImplicitCastExpr::Create(Context, LHS.get()->getType(),
-                                        CK_GetObjCProperty, LHS.take(), 0,=
 VK);
-        return;
-      }
-    }
-  } else if (getLangOptions().ObjCAutoRefCount) {
-    const ObjCMethodDecl *setter
-      =3D PropRef->getExplicitProperty()->getSetterMethodDecl();
-    if (setter) {
-      ObjCMethodDecl::param_const_iterator P =3D setter->param_begin();
-      LHSTy =3D (*P)->getType();
-      Consumed =3D (*P)->hasAttr<NSConsumedAttr>();
-    }
-  }
-
-  if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
-      getLangOptions().ObjCAutoRefCount) {
-    InitializedEntity Entity =3D=20
-      InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
-    ExprResult ArgE =3D PerformCopyInitialization(Entity, SourceLocation()=
, RHS);
-    if (!ArgE.isInvalid()) {
-      RHS =3D ArgE;
-      if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
-        checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get()=
);
-    }
-  }
-}
  =20
=20
 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
@@ -7369,33 +7563,41 @@
 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
 /// In C++, the operand might be an overloaded function name, in which case
 /// we allow the '&' but retain the overloaded-function type.
-static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
+static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
                                       SourceLocation OpLoc) {
-  if (OrigOp->isTypeDependent())
+  if (const BuiltinType *PTy =3D OrigOp.get()->getType()->getAsPlaceholder=
Type()){
+    if (PTy->getKind() =3D=3D BuiltinType::Overload) {
+      if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
+        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
+          << OrigOp.get()->getSourceRange();
+        return QualType();
+      }
+                 =20
+      return S.Context.OverloadTy;
+    }
+
+    if (PTy->getKind() =3D=3D BuiltinType::UnknownAny)
+      return S.Context.UnknownAnyTy;
+
+    if (PTy->getKind() =3D=3D BuiltinType::BoundMember) {
+      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
+        << OrigOp.get()->getSourceRange();
+      return QualType();
+    }
+
+    OrigOp =3D S.CheckPlaceholderExpr(OrigOp.take());
+    if (OrigOp.isInvalid()) return QualType();
+  }
+
+  if (OrigOp.get()->isTypeDependent())
     return S.Context.DependentTy;
-  if (OrigOp->getType() =3D=3D S.Context.OverloadTy) {
-    if (!isa<OverloadExpr>(OrigOp->IgnoreParens())) {
-      S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
-        << OrigOp->getSourceRange();
-      return QualType();
-    }
-                 =20
-    return S.Context.OverloadTy;
-  }
-  if (OrigOp->getType() =3D=3D S.Context.UnknownAnyTy)
-    return S.Context.UnknownAnyTy;
-  if (OrigOp->getType() =3D=3D S.Context.BoundMemberTy) {
-    S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
-      << OrigOp->getSourceRange();
-    return QualType();
-  }
-
-  assert(!OrigOp->getType()->isPlaceholderType());
+
+  assert(!OrigOp.get()->getType()->isPlaceholderType());
=20
   // Make sure to ignore parentheses in subsequent checks
-  Expr *op =3D OrigOp->IgnoreParens();
-
-  if (S.getLangOptions().C99) {
+  Expr *op =3D OrigOp.get()->IgnoreParens();
+
+  if (S.getLangOpts().C99) {
     // Implement C99-only parts of addressof rules.
     if (UnaryOperator* uOp =3D dyn_cast<UnaryOperator>(op)) {
       if (uOp->getOpcode() =3D=3D UO_Deref)
@@ -7426,16 +7628,16 @@
     // If the underlying expression isn't a decl ref, give up.
     if (!isa<DeclRefExpr>(op)) {
       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
-        << OrigOp->getSourceRange();
+        << OrigOp.get()->getSourceRange();
       return QualType();
     }
     DeclRefExpr *DRE =3D cast<DeclRefExpr>(op);
     CXXMethodDecl *MD =3D cast<CXXMethodDecl>(DRE->getDecl());
=20
     // The id-expression was parenthesized.
-    if (OrigOp !=3D DRE) {
+    if (OrigOp.get() !=3D DRE) {
       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
-        << OrigOp->getSourceRange();
+        << OrigOp.get()->getSourceRange();
=20
     // The method was named without a qualifier.
     } else if (!DRE->getQualifier()) {
@@ -7449,10 +7651,15 @@
     // C99 6.5.3.2p1
     // The operand must be either an l-value or a function designator
     if (!op->getType()->isFunctionType()) {
-      // FIXME: emit more specific diag...
-      S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
-        << op->getSourceRange();
-      return QualType();
+      // Use a special diagnostic for loads from property references.
+      if (isa<PseudoObjectExpr>(op)) {
+        AddressOfError =3D AO_Property_Expansion;
+      } else {
+        // FIXME: emit more specific diag...
+        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
+          << op->getSourceRange();
+        return QualType();
+      }
     }
   } else if (op->getObjectKind() =3D=3D OK_BitField) { // C99 6.5.3.2p1
     // The operand cannot be a bit-field
@@ -7460,9 +7667,6 @@
   } else if (op->getObjectKind() =3D=3D OK_VectorComponent) {
     // The operand cannot be an element of a vector
     AddressOfError =3D AO_Vector_Element;
-  } else if (op->getObjectKind() =3D=3D OK_ObjCProperty) {
-    // cannot take address of a property expression.
-    AddressOfError =3D AO_Property_Expansion;
   } else if (dcl) { // C99 6.5.3.2p1
     // We have an lvalue with a decl. Make sure the decl is not declared
     // with the register storage-class specifier.
@@ -7470,7 +7674,7 @@
       // in C++ it is not error to take address of a register
       // variable (c++03 7.1.1P3)
       if (vd->getStorageClass() =3D=3D SC_Register &&
-          !S.getLangOptions().CPlusPlus) {
+          !S.getLangOpts().CPlusPlus) {
         AddressOfError =3D AO_Register_Variable;
       }
     } else if (isa<FunctionTemplateDecl>(dcl)) {
@@ -7562,7 +7766,7 @@
   VK =3D VK_LValue;
=20
   // ...except that certain expressions are never l-values in C.
-  if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
+  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
     VK =3D VK_RValue;
  =20
   return Result;
@@ -7669,6 +7873,25 @@
 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
                                     BinaryOperatorKind Opc,
                                     Expr *LHSExpr, Expr *RHSExpr) {
+  if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
+    // The syntax only allows initializer lists on the RHS of assignment,
+    // so we don't need to worry about accepting invalid code for
+    // non-assignment operators.
+    // C++11 5.17p9:
+    //   The meaning of x =3D {v} [...] is that of x =3D T(v) [...]. The m=
eaning
+    //   of x =3D {} is x =3D T().
+    InitializationKind Kind =3D
+        InitializationKind::CreateDirectList(RHSExpr->getLocStart());
+    InitializedEntity Entity =3D
+        InitializedEntity::InitializeTemporary(LHSExpr->getType());
+    InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
+    ExprResult Init =3D InitSeq.Perform(*this, Entity, Kind,
+                                      MultiExprArg(&RHSExpr, 1));
+    if (Init.isInvalid())
+      return Init;
+    RHSExpr =3D Init.take();
+  }
+
   ExprResult LHS =3D Owned(LHSExpr), RHS =3D Owned(RHSExpr);
   QualType ResultTy;     // Result type of the binary operator.
   // The following two variables are used for compound assignment operators
@@ -7677,27 +7900,10 @@
   ExprValueKind VK =3D VK_RValue;
   ExprObjectKind OK =3D OK_Ordinary;
=20
-  // Check if a 'foo<int>' involved in a binary op, identifies a single=20
-  // function unambiguously (i.e. an lvalue ala 13.4)
-  // But since an assignment can trigger target based overload, exclude it=
 in=20
-  // our blind search. i.e:
-  // template<class T> void f(); template<class T, class U> void f(U);
-  // f<int> =3D=3D 0;  // resolve f<int> blindly
-  // void (*p)(int); p =3D f<int>;  // resolve f<int> using target
-  if (Opc !=3D BO_Assign) {=20
-    ExprResult resolvedLHS =3D CheckPlaceholderExpr(LHS.get());
-    if (!resolvedLHS.isUsable()) return ExprError();
-    LHS =3D move(resolvedLHS);
-
-    ExprResult resolvedRHS =3D CheckPlaceholderExpr(RHS.get());
-    if (!resolvedRHS.isUsable()) return ExprError();
-    RHS =3D move(resolvedRHS);
-  }
-
   switch (Opc) {
   case BO_Assign:
     ResultTy =3D CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()=
);
-    if (getLangOptions().CPlusPlus &&
+    if (getLangOpts().CPlusPlus &&
         LHS.get()->getObjectKind() !=3D OK_ObjCProperty) {
       VK =3D LHS.get()->getValueKind();
       OK =3D LHS.get()->getObjectKind();
@@ -7719,7 +7925,7 @@
     ResultTy =3D CheckRemainderOperands(LHS, RHS, OpLoc);
     break;
   case BO_Add:
-    ResultTy =3D CheckAdditionOperands(LHS, RHS, OpLoc);
+    ResultTy =3D CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
     break;
   case BO_Sub:
     ResultTy =3D CheckSubtractionOperands(LHS, RHS, OpLoc);
@@ -7762,7 +7968,7 @@
       ResultTy =3D CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResu=
ltTy);
     break;
   case BO_AddAssign:
-    CompResultTy =3D CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
+    CompResultTy =3D CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHST=
y);
     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
       ResultTy =3D CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResu=
ltTy);
     break;
@@ -7788,7 +7994,7 @@
     break;
   case BO_Comma:
     ResultTy =3D CheckCommaOperands(*this, LHS, RHS, OpLoc);
-    if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
+    if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
       VK =3D RHS.get()->getValueKind();
       OK =3D RHS.get()->getObjectKind();
     }
@@ -7804,7 +8010,7 @@
   if (CompResultTy.isNull())
     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
                                               ResultTy, VK, OK, OpLoc));
-  if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=3D
+  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=3D
       OK_ObjCProperty) {
     VK =3D VK_LValue;
     OK =3D LHS.get()->getObjectKind();
@@ -7989,38 +8195,98 @@
   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
 }
=20
+/// Build an overloaded binary operator expression in the given scope.
+static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation =
OpLoc,
+                                       BinaryOperatorKind Opc,
+                                       Expr *LHS, Expr *RHS) {
+  // Find all of the overloaded operators visible from this
+  // point. We perform both an operator-name lookup from the local
+  // scope and an argument-dependent lookup based on the types of
+  // the arguments.
+  UnresolvedSet<16> Functions;
+  OverloadedOperatorKind OverOp
+    =3D BinaryOperator::getOverloadedOperator(Opc);
+  if (Sc && OverOp !=3D OO_None)
+    S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
+                                   RHS->getType(), Functions);
+
+  // Build the (potentially-overloaded, potentially-dependent)
+  // binary operation.
+  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
+}
+
 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
                             BinaryOperatorKind Opc,
                             Expr *LHSExpr, Expr *RHSExpr) {
-  if (getLangOptions().CPlusPlus) {
-    bool UseBuiltinOperator;
-
-    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
-      UseBuiltinOperator =3D false;
-    } else if (Opc =3D=3D BO_Assign &&
-               LHSExpr->getObjectKind() =3D=3D OK_ObjCProperty) {
-      UseBuiltinOperator =3D true;
-    } else {
-      UseBuiltinOperator =3D !LHSExpr->getType()->isOverloadableType() &&
-                           !RHSExpr->getType()->isOverloadableType();
-    }
-
-    if (!UseBuiltinOperator) {
-      // Find all of the overloaded operators visible from this
-      // point. We perform both an operator-name lookup from the local
-      // scope and an argument-dependent lookup based on the types of
-      // the arguments.
-      UnresolvedSet<16> Functions;
-      OverloadedOperatorKind OverOp
-        =3D BinaryOperator::getOverloadedOperator(Opc);
-      if (S && OverOp !=3D OO_None)
-        LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
-                                     RHSExpr->getType(), Functions);
-
-      // Build the (potentially-overloaded, potentially-dependent)
-      // binary operation.
-      return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr=
);
-    }
+  // We want to end up calling one of checkPseudoObjectAssignment
+  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
+  // both expressions are overloadable or either is type-dependent),
+  // or CreateBuiltinBinOp (in any other case).  We also want to get
+  // any placeholder types out of the way.
+
+  // Handle pseudo-objects in the LHS.
+  if (const BuiltinType *pty =3D LHSExpr->getType()->getAsPlaceholderType(=
)) {
+    // Assignments with a pseudo-object l-value need special analysis.
+    if (pty->getKind() =3D=3D BuiltinType::PseudoObject &&
+        BinaryOperator::isAssignmentOp(Opc))
+      return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
+
+    // Don't resolve overloads if the other type is overloadable.
+    if (pty->getKind() =3D=3D BuiltinType::Overload) {
+      // We can't actually test that if we still have a placeholder,
+      // though.  Fortunately, none of the exceptions we see in that
+      // code below are valid when the LHS is an overload set.  Note
+      // that an overload set can be dependently-typed, but it never
+      // instantiates to having an overloadable type.
+      ExprResult resolvedRHS =3D CheckPlaceholderExpr(RHSExpr);
+      if (resolvedRHS.isInvalid()) return ExprError();
+      RHSExpr =3D resolvedRHS.take();
+
+      if (RHSExpr->isTypeDependent() ||
+          RHSExpr->getType()->isOverloadableType())
+        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr=
);
+    }
+       =20
+    ExprResult LHS =3D CheckPlaceholderExpr(LHSExpr);
+    if (LHS.isInvalid()) return ExprError();
+    LHSExpr =3D LHS.take();
+  }
+
+  // Handle pseudo-objects in the RHS.
+  if (const BuiltinType *pty =3D RHSExpr->getType()->getAsPlaceholderType(=
)) {
+    // An overload in the RHS can potentially be resolved by the type
+    // being assigned to.
+    if (Opc =3D=3D BO_Assign && pty->getKind() =3D=3D BuiltinType::Overloa=
d) {
+      if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
+        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr=
);
+
+      if (LHSExpr->getType()->isOverloadableType())
+        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr=
);
+
+      return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
+    }
+
+    // Don't resolve overloads if the other type is overloadable.
+    if (pty->getKind() =3D=3D BuiltinType::Overload &&
+        LHSExpr->getType()->isOverloadableType())
+      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
+
+    ExprResult resolvedRHS =3D CheckPlaceholderExpr(RHSExpr);
+    if (!resolvedRHS.isUsable()) return ExprError();
+    RHSExpr =3D resolvedRHS.take();
+  }
+
+  if (getLangOpts().CPlusPlus) {
+    // If either expression is type-dependent, always build an
+    // overloaded op.
+    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
+      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
+
+    // Otherwise, build an overloaded op if either expression has an
+    // overloadable type.
+    if (LHSExpr->getType()->isOverloadableType() ||
+        RHSExpr->getType()->isOverloadableType())
+      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
   }
=20
   // Build a built-in binary operation.
@@ -8046,12 +8312,9 @@
                                                 Opc =3D=3D UO_PreDec);
     break;
   case UO_AddrOf:
-    resultType =3D CheckAddressOfOperand(*this, Input.get(), OpLoc);
+    resultType =3D CheckAddressOfOperand(*this, Input, OpLoc);
     break;
   case UO_Deref: {
-    ExprResult resolved =3D CheckPlaceholderExpr(Input.get());
-    if (!resolved.isUsable()) return ExprError();
-    Input =3D move(resolved);
     Input =3D DefaultFunctionArrayLvalueConversion(Input.take());
     resultType =3D CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
     break;
@@ -8066,18 +8329,13 @@
     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
         resultType->isVectorType())=20
       break;
-    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
+    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
              resultType->isEnumeralType())
       break;
-    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
+    else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
              Opc =3D=3D UO_Plus &&
              resultType->isPointerType())
       break;
-    else if (resultType->isPlaceholderType()) {
-      Input =3D CheckPlaceholderExpr(Input.take());
-      if (Input.isInvalid()) return ExprError();
-      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
-    }
=20
     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
       << resultType << Input.get()->getSourceRange());
@@ -8095,11 +8353,7 @@
         << resultType << Input.get()->getSourceRange();
     else if (resultType->hasIntegerRepresentation())
       break;
-    else if (resultType->isPlaceholderType()) {
-      Input =3D CheckPlaceholderExpr(Input.take());
-      if (Input.isInvalid()) return ExprError();
-      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
-    } else {
+    else {
       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
         << resultType << Input.get()->getSourceRange());
     }
@@ -8121,16 +8375,16 @@
       break;
     if (resultType->isScalarType()) {
       // C99 6.5.3.3p1: ok, fallthrough;
-      if (Context.getLangOptions().CPlusPlus) {
+      if (Context.getLangOpts().CPlusPlus) {
         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
         // operand contextually converted to bool.
         Input =3D ImpCastExprToType(Input.take(), Context.BoolTy,
                                   ScalarTypeToBooleanCastKind(resultType));
       }
-    } else if (resultType->isPlaceholderType()) {
-      Input =3D CheckPlaceholderExpr(Input.take());
-      if (Input.isInvalid()) return ExprError();
-      return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
+    } else if (resultType->isExtVectorType()) {
+      // Vector logical not returns the signed variant of the operand type.
+      resultType =3D GetSignedVectorType(resultType);
+      break;
     } else {
       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
         << resultType << Input.get()->getSourceRange());
@@ -8143,11 +8397,17 @@
   case UO_Real:
   case UO_Imag:
     resultType =3D CheckRealImagOperand(*this, Input, OpLoc, Opc =3D=3D UO=
_Real);
-    // _Real and _Imag map ordinary l-values into ordinary l-values.
+    // _Real maps ordinary l-values into ordinary l-values. _Imag maps ord=
inary
+    // complex l-values to ordinary l-values and all other values to r-val=
ues.
     if (Input.isInvalid()) return ExprError();
-    if (Input.get()->getValueKind() !=3D VK_RValue &&
-        Input.get()->getObjectKind() =3D=3D OK_Ordinary)
-      VK =3D Input.get()->getValueKind();
+    if (Opc =3D=3D UO_Real || Input.get()->getType()->isAnyComplexType()) {
+      if (Input.get()->getValueKind() !=3D VK_RValue &&
+          Input.get()->getObjectKind() =3D=3D OK_Ordinary)
+        VK =3D Input.get()->getValueKind();
+    } else if (!getLangOpts().CPlusPlus) {
+      // In C, a volatile scalar is read by __imag. In C++, it is not.
+      Input =3D DefaultLvalueConversion(Input.take());
+    }
     break;
   case UO_Extension:
     resultType =3D Input.get()->getType();
@@ -8169,10 +8429,79 @@
                                            VK, OK, OpLoc));
 }
=20
+/// \brief Determine whether the given expression is a qualified member
+/// access expression, of a form that could be turned into a pointer to me=
mber
+/// with the address-of operator.
+static bool isQualifiedMemberAccess(Expr *E) {
+  if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E)) {
+    if (!DRE->getQualifier())
+      return false;
+   =20
+    ValueDecl *VD =3D DRE->getDecl();
+    if (!VD->isCXXClassMember())
+      return false;
+   =20
+    if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
+      return true;
+    if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(VD))
+      return Method->isInstance();
+     =20
+    return false;
+  }
+ =20
+  if (UnresolvedLookupExpr *ULE =3D dyn_cast<UnresolvedLookupExpr>(E)) {
+    if (!ULE->getQualifier())
+      return false;
+   =20
+    for (UnresolvedLookupExpr::decls_iterator D =3D ULE->decls_begin(),
+                                           DEnd =3D ULE->decls_end();
+         D !=3D DEnd; ++D) {
+      if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(*D)) {
+        if (Method->isInstance())
+          return true;
+      } else {
+        // Overload set does not contain methods.
+        break;
+      }
+    }
+   =20
+    return false;
+  }
+ =20
+  return false;
+}
+
 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
                               UnaryOperatorKind Opc, Expr *Input) {
-  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()=
 &&
-      UnaryOperator::getOverloadedOperator(Opc) !=3D OO_None) {
+  // First things first: handle placeholders so that the
+  // overloaded-operator check considers the right type.
+  if (const BuiltinType *pty =3D Input->getType()->getAsPlaceholderType())=
 {
+    // Increment and decrement of pseudo-object references.
+    if (pty->getKind() =3D=3D BuiltinType::PseudoObject &&
+        UnaryOperator::isIncrementDecrementOp(Opc))
+      return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
+
+    // extension is always a builtin operator.
+    if (Opc =3D=3D UO_Extension)
+      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
+
+    // & gets special logic for several kinds of placeholder.
+    // The builtin code knows what to do.
+    if (Opc =3D=3D UO_AddrOf &&
+        (pty->getKind() =3D=3D BuiltinType::Overload ||
+         pty->getKind() =3D=3D BuiltinType::UnknownAny ||
+         pty->getKind() =3D=3D BuiltinType::BoundMember))
+      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
+
+    // Anything else needs to be handled now.
+    ExprResult Result =3D CheckPlaceholderExpr(Input);
+    if (Result.isInvalid()) return ExprError();
+    Input =3D Result.take();
+  }
+
+  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
+      UnaryOperator::getOverloadedOperator(Opc) !=3D OO_None &&
+      !(Opc =3D=3D UO_AddrOf && isQualifiedMemberAccess(Input))) {
     // Find all of the overloaded operators visible from this
     // point. We perform both an operator-name lookup from the local
     // scope and an argument-dependent lookup based on the types of
@@ -8227,12 +8556,29 @@
   return cleanups;
 }
=20
+void Sema::ActOnStartStmtExpr() {
+  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
+}
+
+void Sema::ActOnStmtExprError() {
+  // Note that function is also called by TreeTransform when leaving a
+  // StmtExpr scope without rebuilding anything.
+
+  DiscardCleanupsInEvaluationContext();
+  PopExpressionEvaluationContext();
+}
+
 ExprResult
 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
                     SourceLocation RPLoc) { // "({..})"
   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocati=
on!");
   CompoundStmt *Compound =3D cast<CompoundStmt>(SubStmt);
=20
+  if (hasAnyUnrecoverableErrorsInThisFunction())
+    DiscardCleanupsInEvaluationContext();
+  assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bou=
nd!");
+  PopExpressionEvaluationContext();
+
   bool isFileScope
     =3D (getCurFunctionOrMethodDecl() =3D=3D 0) && (getCurBlock() =3D=3D 0=
);
   if (isFileScope)
@@ -8353,15 +8699,19 @@
       } else
         CurrentType =3D Context.DependentTy;
      =20
+      ExprResult IdxRval =3D DefaultLvalueConversion(static_cast<Expr*>(OC=
.U.E));
+      if (IdxRval.isInvalid())
+        return ExprError();
+      Expr *Idx =3D IdxRval.take();
+
       // The expression must be an integral expression.
       // FIXME: An integral constant expression?
-      Expr *Idx =3D static_cast<Expr*>(OC.U.E);
       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
           !Idx->getType()->isIntegerType())
         return ExprError(Diag(Idx->getLocStart(),
                               diag::err_typecheck_subscript_not_integer)
                          << Idx->getSourceRange());
-     =20
+
       // Record this array index.
       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
       Exprs.push_back(Idx);
@@ -8500,11 +8850,11 @@
   } else {
     // The conditional expression is required to be a constant expression.
     llvm::APSInt condEval(32);
-    SourceLocation ExpLoc;
-    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
-      return ExprError(Diag(ExpLoc,
-                       diag::err_typecheck_choose_expr_requires_constant)
-        << CondExpr->getSourceRange());
+    ExprResult CondICE =3D VerifyIntegerConstantExpression(CondExpr, &cond=
Eval,
+      PDiag(diag::err_typecheck_choose_expr_requires_constant), false);
+    if (CondICE.isInvalid())
+      return ExprError();
+    CondExpr =3D CondICE.take();
=20
     // If the condition is > zero, then the AST type is the same as the LS=
HExpr.
     Expr *ActiveExpr =3D condEval.getZExtValue() ? LHSExpr : RHSExpr;
@@ -8534,6 +8884,12 @@
     PushDeclContext(CurScope, Block);
   else
     CurContext =3D Block;
+
+  getCurBlock()->HasImplicitReturnType =3D true;
+
+  // Enter a new evaluation context to insulate the block from any
+  // cleanups from the enclosing full-expression.
+  PushExpressionEvaluationContext(PotentiallyEvaluated); =20
 }
=20
 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
@@ -8585,7 +8941,7 @@
=20
   // Don't allow returning a objc interface by value.
   if (RetTy->isObjCObjectType()) {
-    Diag(ParamInfo.getSourceRange().getBegin(),
+    Diag(ParamInfo.getLocStart(),
          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetT=
y;
     return;
   }
@@ -8594,8 +8950,11 @@
   // return type.  TODO:  what should we do with declarators like:
   //   ^ * { ... }
   // If the answer is "apply template argument deduction"....
-  if (RetTy !=3D Context.DependentTy)
+  if (RetTy !=3D Context.DependentTy) {
     CurBlock->ReturnType =3D RetTy;
+    CurBlock->TheDecl->setBlockMissingReturnType(false);
+    CurBlock->HasImplicitReturnType =3D false;
+  }
=20
   // Push block parameters from the declarator if we had them.
   SmallVector<ParmVarDecl*, 8> Params;
@@ -8605,7 +8964,7 @@
       if (Param->getIdentifier() =3D=3D 0 &&
           !Param->isImplicit() &&
           !Param->isInvalidDecl() &&
-          !getLangOptions().CPlusPlus)
+          !getLangOpts().CPlusPlus)
         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
       Params.push_back(Param);
     }
@@ -8617,7 +8976,7 @@
            I =3D Fn->arg_type_begin(), E =3D Fn->arg_type_end(); I !=3D E;=
 ++I) {
       ParmVarDecl *Param =3D
         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
-                                   ParamInfo.getSourceRange().getBegin(),
+                                   ParamInfo.getLocStart(),
                                    *I);
       Params.push_back(Param);
     }
@@ -8634,12 +8993,6 @@
   // Finally we can process decl attributes.
   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
=20
-  if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
-    Diag(ParamInfo.getAttributes()->getLoc(),
-         diag::warn_attribute_sentinel_not_variadic) << 1;
-    // FIXME: remove the attribute.
-  }
-
   // Put the parameter variables in scope.  We can bail out immediately
   // if we don't have any.
   if (Params.empty())
@@ -8661,9 +9014,13 @@
 /// ActOnBlockError - If there is an error parsing a block, this callback
 /// is invoked to pop the information about the block from the action impl.
 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
+  // Leave the expression-evaluation context.
+  DiscardCleanupsInEvaluationContext();
+  PopExpressionEvaluationContext();
+
   // Pop off CurBlock, handle nested blocks.
   PopDeclContext();
-  PopFunctionOrBlockScope();
+  PopFunctionScopeInfo();
 }
=20
 /// ActOnBlockStmtExpr - This is called when the body of a block statement
@@ -8674,6 +9031,12 @@
   if (!LangOpts.Blocks)
     Diag(CaretLoc, diag::err_blocks_disable);
=20
+  // Leave the expression-evaluation context.
+  if (hasAnyUnrecoverableErrorsInThisFunction())
+    DiscardCleanupsInEvaluationContext();
+  assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!=
");
+  PopExpressionEvaluationContext();
+
   BlockScopeInfo *BSI =3D cast<BlockScopeInfo>(FunctionScopes.back());
  =20
   PopDeclContext();
@@ -8686,8 +9049,18 @@
   QualType BlockTy;
=20
   // Set the captured variables on the block.
-  BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.=
end(),
-                            BSI->CapturesCXXThis);
+  // FIXME: Share capture structure between BlockDecl and CapturingScopeIn=
fo!
+  SmallVector<BlockDecl::Capture, 4> Captures;
+  for (unsigned i =3D 0, e =3D BSI->Captures.size(); i !=3D e; i++) {
+    CapturingScopeInfo::Capture &Cap =3D BSI->Captures[i];
+    if (Cap.isThisCapture())
+      continue;
+    BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
+                              Cap.isNested(), Cap.getCopyExpr());
+    Captures.push_back(NewCap);
+  }
+  BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
+                            BSI->CXXThisCaptureIndex !=3D 0);
=20
   // If the user wrote a function type in some form, try to use that.
   if (!BSI->FunctionType.isNull()) {
@@ -8738,20 +9111,31 @@
=20
   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
=20
-  for (BlockDecl::capture_const_iterator ci =3D BSI->TheDecl->capture_begi=
n(),
-       ce =3D BSI->TheDecl->capture_end(); ci !=3D ce; ++ci) {
-    const VarDecl *variable =3D ci->getVariable();
-    QualType T =3D variable->getType();
-    QualType::DestructionKind destructKind =3D T.isDestructedType();
-    if (destructKind !=3D QualType::DK_none)
-      getCurFunction()->setHasBranchProtectedScope();
-  }
-
   computeNRVO(Body, getCurBlock());
  =20
   BlockExpr *Result =3D new (Context) BlockExpr(BSI->TheDecl, BlockTy);
   const AnalysisBasedWarnings::Policy &WP =3D AnalysisWarnings.getDefaultP=
olicy();
-  PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
+  PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
+
+  // If the block isn't obviously global, i.e. it captures anything at
+  // all, then we need to do a few things in the surrounding context:
+  if (Result->getBlockDecl()->hasCaptures()) {
+    // First, this expression has a new cleanup object.
+    ExprCleanupObjects.push_back(Result->getBlockDecl());
+    ExprNeedsCleanups =3D true;
+
+    // It also gets a branch-protected scope if any of the captured
+    // variables needs destruction.
+    for (BlockDecl::capture_const_iterator
+           ci =3D Result->getBlockDecl()->capture_begin(),
+           ce =3D Result->getBlockDecl()->capture_end(); ci !=3D ce; ++ci)=
 {
+      const VarDecl *var =3D ci->getVariable();
+      if (var->getType().isDestructedType() !=3D QualType::DK_none) {
+        getCurFunction()->setHasBranchProtectedScope();
+        break;
+      }
+    }
+  }
=20
   return Owned(Result);
 }
@@ -8859,7 +9243,7 @@
=20
 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
                                            Expr *SrcExpr, FixItHint &Hint)=
 {
-  if (!SemaRef.getLangOptions().ObjC1)
+  if (!SemaRef.getLangOpts().ObjC1)
     return;
=20
   const ObjCObjectPointerType *PT =3D DstType->getAs<ObjCObjectPointerType=
>();
@@ -8874,8 +9258,15 @@
       return;
   }
=20
-  // Strip off any parens and casts.
-  StringLiteral *SL =3D dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts(=
));
+  // Ignore any parens, implicit casts (should only be
+  // array-to-pointer decays), and not-so-opaque values.  The last is
+  // important for making this trigger for property assignments.
+  SrcExpr =3D SrcExpr->IgnoreParenImpCasts();
+  if (OpaqueValueExpr *OV =3D dyn_cast<OpaqueValueExpr>(SrcExpr))
+    if (OV->getSourceExpr())
+      SrcExpr =3D OV->getSourceExpr()->IgnoreParenImpCasts();
+
+  StringLiteral *SL =3D dyn_cast<StringLiteral>(SrcExpr);
   if (!SL || !SL->isAscii())
     return;
=20
@@ -8893,13 +9284,13 @@
   // Decode the result (notice that AST's are still created for extensions=
).
   bool CheckInferredResultType =3D false;
   bool isInvalid =3D false;
-  unsigned DiagKind;
+  unsigned DiagKind =3D 0;
   FixItHint Hint;
   ConversionFixItGenerator ConvHints;
   bool MayHaveConvFixit =3D false;
+  bool MayHaveFunctionDiff =3D false;
=20
   switch (ConvTy) {
-  default: llvm_unreachable("Unknown conversion type");
   case Compatible: return false;
   case PointerToInt:
     DiagKind =3D diag::ext_typecheck_convert_pointer_int;
@@ -8956,7 +9347,7 @@
     // expression, rather than a type), which should be done as part
     // of a larger effort to fix checkPointerTypesForAssignment for
     // C++ semantics.
-    if (getLangOptions().CPlusPlus &&
+    if (getLangOpts().CPlusPlus &&
         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
       return false;
     DiagKind =3D diag::ext_typecheck_convert_discards_qualifiers;
@@ -8986,6 +9377,7 @@
     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
     MayHaveConvFixit =3D true;
     isInvalid =3D true;
+    MayHaveFunctionDiff =3D true;
     break;
   }
=20
@@ -9015,17 +9407,23 @@
   // If we can fix the conversion, suggest the FixIts.
   assert(ConvHints.isNull() || Hint.isNull());
   if (!ConvHints.isNull()) {
-    for (llvm::SmallVector<FixItHint, 1>::iterator
-        HI =3D ConvHints.Hints.begin(), HE =3D ConvHints.Hints.end();
-        HI !=3D HE; ++HI)
+    for (std::vector<FixItHint>::iterator HI =3D ConvHints.Hints.begin(),
+         HE =3D ConvHints.Hints.end(); HI !=3D HE; ++HI)
       FDiag << *HI;
   } else {
     FDiag << Hint;
   }
   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
=20
+  if (MayHaveFunctionDiff)
+    HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
+
   Diag(Loc, FDiag);
=20
+  if (SecondType =3D=3D Context.OverloadTy)
+    NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
+                              FirstType);
+
   if (CheckInferredResultType)
     EmitRelatedResultTypeNote(SrcExpr);
  =20
@@ -9034,77 +9432,213 @@
   return isInvalid;
 }
=20
-bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Re=
sult){
-  llvm::APSInt ICEResult;
-  if (E->isIntegerConstantExpr(ICEResult, Context)) {
+ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
+                                                 llvm::APSInt *Result) {
+  return VerifyIntegerConstantExpression(E, Result,
+      PDiag(diag::err_expr_not_ice) << LangOpts.CPlusPlus);
+}
+
+ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Re=
sult,
+                                                 PartialDiagnostic NotIceD=
iag,
+                                                 bool AllowFold,
+                                                 PartialDiagnostic FoldDia=
g) {
+  SourceLocation DiagLoc =3D E->getLocStart();
+
+  if (getLangOpts().CPlusPlus0x) {
+    // C++11 [expr.const]p5:
+    //   If an expression of literal class type is used in a context where=
 an
+    //   integral constant expression is required, then that class type sh=
all
+    //   have a single non-explicit conversion function to an integral or
+    //   unscoped enumeration type
+    ExprResult Converted;
+    if (NotIceDiag.getDiagID()) {
+      Converted =3D ConvertToIntegralOrEnumerationType(
+        DiagLoc, E,
+        PDiag(diag::err_ice_not_integral),
+        PDiag(diag::err_ice_incomplete_type),
+        PDiag(diag::err_ice_explicit_conversion),
+        PDiag(diag::note_ice_conversion_here),
+        PDiag(diag::err_ice_ambiguous_conversion),
+        PDiag(diag::note_ice_conversion_here),
+        PDiag(0),
+        /*AllowScopedEnumerations*/ false);
+    } else {
+      // The caller wants to silently enquire whether this is an ICE. Don't
+      // produce any diagnostics if it isn't.
+      Converted =3D ConvertToIntegralOrEnumerationType(
+        DiagLoc, E, PDiag(), PDiag(), PDiag(), PDiag(),
+        PDiag(), PDiag(), PDiag(), false);
+    }
+    if (Converted.isInvalid())
+      return Converted;
+    E =3D Converted.take();
+    if (!E->getType()->isIntegralOrUnscopedEnumerationType())
+      return ExprError();
+  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
+    // An ICE must be of integral or unscoped enumeration type.
+    if (NotIceDiag.getDiagID())
+      Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
+    return ExprError();
+  }
+
+  // Circumvent ICE checking in C++11 to avoid evaluating the expression t=
wice
+  // in the non-ICE case.
+  if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
     if (Result)
-      *Result =3D ICEResult;
-    return false;
+      *Result =3D E->EvaluateKnownConstInt(Context);
+    return Owned(E);
   }
=20
   Expr::EvalResult EvalResult;
-
-  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
-      EvalResult.HasSideEffects) {
-    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
-
-    if (EvalResult.Diag) {
-      // We only show the note if it's not the usual "invalid subexpressio=
n"
-      // or if it's actually in a subexpression.
-      if (EvalResult.Diag !=3D diag::note_invalid_subexpr_in_ice ||
-          E->IgnoreParens() !=3D EvalResult.DiagExpr->IgnoreParens())
-        Diag(EvalResult.DiagLoc, EvalResult.Diag);
-    }
-
-    return true;
-  }
-
-  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
-    E->getSourceRange();
-
-  if (EvalResult.Diag &&
-      Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
-          !=3D DiagnosticsEngine::Ignored)
-    Diag(EvalResult.DiagLoc, EvalResult.Diag);
+  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
+  EvalResult.Diag =3D &Notes;
+
+  // Try to evaluate the expression, and produce diagnostics explaining wh=
y it's
+  // not a constant expression as a side-effect.
+  bool Folded =3D E->EvaluateAsRValue(EvalResult, Context) &&
+                EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
+
+  // In C++11, we can rely on diagnostics being produced for any expression
+  // which is not a constant expression. If no diagnostics were produced, =
then
+  // this is a constant expression.
+  if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
+    if (Result)
+      *Result =3D EvalResult.Val.getInt();
+    return Owned(E);
+  }
+
+  // If our only note is the usual "invalid subexpression" note, just point
+  // the caret at its location rather than producing an essentially
+  // redundant note.
+  if (Notes.size() =3D=3D 1 && Notes[0].second.getDiagID() =3D=3D
+        diag::note_invalid_subexpr_in_const_expr) {
+    DiagLoc =3D Notes[0].first;
+    Notes.clear();
+  }
+
+  if (!Folded || !AllowFold) {
+    if (NotIceDiag.getDiagID()) {
+      Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
+      for (unsigned I =3D 0, N =3D Notes.size(); I !=3D N; ++I)
+        Diag(Notes[I].first, Notes[I].second);
+    }
+
+    return ExprError();
+  }
+
+  if (FoldDiag.getDiagID())
+    Diag(DiagLoc, FoldDiag) << E->getSourceRange();
+  else
+    Diag(DiagLoc, diag::ext_expr_not_ice)
+      << E->getSourceRange() << LangOpts.CPlusPlus;
+  for (unsigned I =3D 0, N =3D Notes.size(); I !=3D N; ++I)
+    Diag(Notes[I].first, Notes[I].second);
=20
   if (Result)
     *Result =3D EvalResult.Val.getInt();
-  return false;
+  return Owned(E);
+}
+
+namespace {
+  // Handle the case where we conclude a expression which we speculatively
+  // considered to be unevaluated is actually evaluated.
+  class TransformToPE : public TreeTransform<TransformToPE> {
+    typedef TreeTransform<TransformToPE> BaseTransform;
+
+  public:
+    TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
+
+    // Make sure we redo semantic analysis
+    bool AlwaysRebuild() { return true; }
+
+    // Make sure we handle LabelStmts correctly.
+    // FIXME: This does the right thing, but maybe we need a more general
+    // fix to TreeTransform?
+    StmtResult TransformLabelStmt(LabelStmt *S) {
+      S->getDecl()->setStmt(0);
+      return BaseTransform::TransformLabelStmt(S);
+    }
+
+    // We need to special-case DeclRefExprs referring to FieldDecls which
+    // are not part of a member pointer formation; normal TreeTransforming
+    // doesn't catch this case because of the way we represent them in the=
 AST.
+    // FIXME: This is a bit ugly; is it really the best way to handle this
+    // case?
+    //
+    // Error on DeclRefExprs referring to FieldDecls.
+    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
+      if (isa<FieldDecl>(E->getDecl()) &&
+          SemaRef.ExprEvalContexts.back().Context !=3D Sema::Unevaluated)
+        return SemaRef.Diag(E->getLocation(),
+                            diag::err_invalid_non_static_member_use)
+            << E->getDecl() << E->getSourceRange();
+
+      return BaseTransform::TransformDeclRefExpr(E);
+    }
+
+    // Exception: filter out member pointer formation
+    ExprResult TransformUnaryOperator(UnaryOperator *E) {
+      if (E->getOpcode() =3D=3D UO_AddrOf && E->getType()->isMemberPointer=
Type())
+        return E;
+
+      return BaseTransform::TransformUnaryOperator(E);
+    }
+
+    ExprResult TransformLambdaExpr(LambdaExpr *E) {
+      // Lambdas never need to be transformed.
+      return E;
+    }
+  };
+}
+
+ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
+  assert(ExprEvalContexts.back().Context =3D=3D Unevaluated &&
+         "Should only transform unevaluated expressions");
+  ExprEvalContexts.back().Context =3D
+      ExprEvalContexts[ExprEvalContexts.size()-2].Context;
+  if (ExprEvalContexts.back().Context =3D=3D Unevaluated)
+    return E;
+  return TransformToPE(*this).TransformExpr(E);
 }
=20
 void
-Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewConte=
xt) {
+Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewConte=
xt,
+                                      Decl *LambdaContextDecl,
+                                      bool IsDecltype) {
   ExprEvalContexts.push_back(
              ExpressionEvaluationContextRecord(NewContext,
-                                               ExprTemporaries.size(),
-                                               ExprNeedsCleanups));
+                                               ExprCleanupObjects.size(),
+                                               ExprNeedsCleanups,
+                                               LambdaContextDecl,
+                                               IsDecltype));
   ExprNeedsCleanups =3D false;
+  if (!MaybeODRUseExprs.empty())
+    std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseEx=
prs);
 }
=20
 void Sema::PopExpressionEvaluationContext() {
-  // Pop the current expression evaluation context off the stack.
-  ExpressionEvaluationContextRecord Rec =3D ExprEvalContexts.back();
-  ExprEvalContexts.pop_back();
-
-  if (Rec.Context =3D=3D PotentiallyPotentiallyEvaluated) {
-    if (Rec.PotentiallyReferenced) {
-      // Mark any remaining declarations in the current position of the st=
ack
-      // as "referenced". If they were not meant to be referenced, semantic
-      // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
-      for (PotentiallyReferencedDecls::iterator
-             I =3D Rec.PotentiallyReferenced->begin(),
-             IEnd =3D Rec.PotentiallyReferenced->end();
-           I !=3D IEnd; ++I)
-        MarkDeclarationReferenced(I->first, I->second);
-    }
-
-    if (Rec.PotentiallyDiagnosed) {
-      // Emit any pending diagnostics.
-      for (PotentiallyEmittedDiagnostics::iterator
-                I =3D Rec.PotentiallyDiagnosed->begin(),
-             IEnd =3D Rec.PotentiallyDiagnosed->end();
-           I !=3D IEnd; ++I)
-        Diag(I->first, I->second);
+  ExpressionEvaluationContextRecord& Rec =3D ExprEvalContexts.back();
+
+  if (!Rec.Lambdas.empty()) {
+    if (Rec.Context =3D=3D Unevaluated) {
+      // C++11 [expr.prim.lambda]p2:
+      //   A lambda-expression shall not appear in an unevaluated operand
+      //   (Clause 5).
+      for (unsigned I =3D 0, N =3D Rec.Lambdas.size(); I !=3D N; ++I)
+        Diag(Rec.Lambdas[I]->getLocStart(),=20
+             diag::err_lambda_unevaluated_operand);
+    } else {
+      // Mark the capture expressions odr-used. This was deferred
+      // during lambda expression creation.
+      for (unsigned I =3D 0, N =3D Rec.Lambdas.size(); I !=3D N; ++I) {
+        LambdaExpr *Lambda =3D Rec.Lambdas[I];
+        for (LambdaExpr::capture_init_iterator=20
+                  C =3D Lambda->capture_init_begin(),
+               CEnd =3D Lambda->capture_init_end();
+             C !=3D CEnd; ++C) {
+          MarkDeclarationsReferencedInExpr(*C);
+        }
+      }
     }
   }
=20
@@ -9112,89 +9646,86 @@
   // temporaries that we may have created as part of the evaluation of
   // the expression in that context: they aren't relevant because they
   // will never be constructed.
-  if (Rec.Context =3D=3D Unevaluated) {
-    ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
-                          ExprTemporaries.end());
+  if (Rec.Context =3D=3D Unevaluated || Rec.Context =3D=3D ConstantEvaluat=
ed) {
+    ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupOb=
jects,
+                             ExprCleanupObjects.end());
     ExprNeedsCleanups =3D Rec.ParentNeedsCleanups;
-
+    CleanupVarDeclMarking();
+    std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
   // Otherwise, merge the contexts together.
   } else {
     ExprNeedsCleanups |=3D Rec.ParentNeedsCleanups;
-  }
-
-  // Destroy the popped expression evaluation record.
-  Rec.Destroy();
+    MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
+                            Rec.SavedMaybeODRUseExprs.end());
+  }
+
+  // Pop the current expression evaluation context off the stack.
+  ExprEvalContexts.pop_back();
 }
=20
 void Sema::DiscardCleanupsInEvaluationContext() {
-  ExprTemporaries.erase(
-              ExprTemporaries.begin() + ExprEvalContexts.back().NumTempora=
ries,
-              ExprTemporaries.end());
+  ExprCleanupObjects.erase(
+         ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupOb=
jects,
+         ExprCleanupObjects.end());
   ExprNeedsCleanups =3D false;
-}
-
-/// \brief Note that the given declaration was referenced in the source co=
de.
-///
-/// This routine should be invoke whenever a given declaration is referenc=
ed
-/// in the source code, and where that reference occurred. If this declara=
tion
-/// reference means that the the declaration is used (C++ [basic.def.odr]p=
2,
-/// C99 6.9p3), then the declaration will be marked as used.
-///
-/// \param Loc the location where the declaration was referenced.
-///
-/// \param D the declaration that has been referenced by the source code.
-void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
-  assert(D && "No declaration?");
-
-  D->setReferenced();
-
-  if (D->isUsed(false))
-    return;
-
-  // Mark a parameter or variable declaration "used", regardless of whether
-  // we're in a template or not. The reason for this is that unevaluated
-  // expressions (e.g. (void)sizeof()) constitute a use for warning purpos=
es
-  // (-Wunused-variables and -Wunused-parameters)
-  if (isa<ParmVarDecl>(D) ||
-      (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
-    D->setUsed();
-    return;
-  }
-
-  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
-    return;
-
+  MaybeODRUseExprs.clear();
+}
+
+ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
+  if (!E->getType()->isVariablyModifiedType())
+    return E;
+  return TranformToPotentiallyEvaluated(E);
+}
+
+static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
   // Do not mark anything as "used" within a dependent context; wait for
   // an instantiation.
-  if (CurContext->isDependentContext())
-    return;
-
-  switch (ExprEvalContexts.back().Context) {
-    case Unevaluated:
+  if (SemaRef.CurContext->isDependentContext())
+    return false;
+
+  switch (SemaRef.ExprEvalContexts.back().Context) {
+    case Sema::Unevaluated:
       // We are in an expression that is not potentially evaluated; do not=
hing.
-      return;
-
-    case PotentiallyEvaluated:
-      // We are in a potentially-evaluated expression, so this declaration=
 is
-      // "used"; handle this below.
-      break;
-
-    case PotentiallyPotentiallyEvaluated:
-      // We are in an expression that may be potentially evaluated; queue =
this
-      // declaration reference until we know whether the expression is
-      // potentially evaluated.
-      ExprEvalContexts.back().addReferencedDecl(Loc, D);
-      return;
-     =20
-    case PotentiallyEvaluatedIfUsed:
+      // (Depending on how you read the standard, we actually do need to do
+      // something here for null pointer constants, but the standard's
+      // definition of a null pointer constant is completely crazy.)
+      return false;
+
+    case Sema::ConstantEvaluated:
+    case Sema::PotentiallyEvaluated:
+      // We are in a potentially evaluated expression (or a constant-expre=
ssion
+      // in C++03); we need to do implicit template instantiation, implici=
tly
+      // define class members, and mark most declarations as used.
+      return true;
+
+    case Sema::PotentiallyEvaluatedIfUsed:
       // Referenced declarations will only be used if the construct in the
       // containing expression is used.
-      return;
-  }
+      return false;
+  }
+  llvm_unreachable("Invalid context");
+}
+
+/// \brief Mark a function referenced, and check whether it is odr-used
+/// (C++ [basic.def.odr]p2, C99 6.9p3)
+void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
+  assert(Func && "No function?");
+
+  Func->setReferenced();
+
+  // Don't mark this function as used multiple times, unless it's a conste=
xpr
+  // function which we need to instantiate.
+  if (Func->isUsed(false) &&
+      !(Func->isConstexpr() && !Func->getBody() &&
+        Func->isImplicitlyInstantiable()))
+    return;
+
+  if (!IsPotentiallyEvaluatedContext(*this))
+    return;
=20
   // Note that this declaration has been used.
-  if (CXXConstructorDecl *Constructor =3D dyn_cast<CXXConstructorDecl>(D))=
 {
-    if (Constructor->isDefaulted()) {
+  if (CXXConstructorDecl *Constructor =3D dyn_cast<CXXConstructorDecl>(Fun=
c)) {
+    if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
       if (Constructor->isDefaultConstructor()) {
         if (Constructor->isTrivial())
           return;
@@ -9210,13 +9741,16 @@
     }
=20
     MarkVTableUsed(Loc, Constructor->getParent());
-  } else if (CXXDestructorDecl *Destructor =3D dyn_cast<CXXDestructorDecl>=
(D)) {
-    if (Destructor->isDefaulted() && !Destructor->isUsed(false))
+  } else if (CXXDestructorDecl *Destructor =3D
+                 dyn_cast<CXXDestructorDecl>(Func)) {
+    if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
+        !Destructor->isUsed(false))
       DefineImplicitDestructor(Loc, Destructor);
     if (Destructor->isVirtual())
       MarkVTableUsed(Loc, Destructor->getParent());
-  } else if (CXXMethodDecl *MethodDecl =3D dyn_cast<CXXMethodDecl>(D)) {
-    if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
+  } else if (CXXMethodDecl *MethodDecl =3D dyn_cast<CXXMethodDecl>(Func)) {
+    if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
+        MethodDecl->isOverloadedOperator() &&
         MethodDecl->getOverloadedOperator() =3D=3D OO_Equal) {
       if (!MethodDecl->isUsed(false)) {
         if (MethodDecl->isCopyAssignmentOperator())
@@ -9224,90 +9758,703 @@
         else
           DefineImplicitMoveAssignment(Loc, MethodDecl);
       }
+    } else if (isa<CXXConversionDecl>(MethodDecl) &&
+               MethodDecl->getParent()->isLambda()) {
+      CXXConversionDecl *Conversion =3D cast<CXXConversionDecl>(MethodDecl=
);
+      if (Conversion->isLambdaToBlockPointerConversion())
+        DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
+      else
+        DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
     } else if (MethodDecl->isVirtual())
       MarkVTableUsed(Loc, MethodDecl->getParent());
   }
-  if (FunctionDecl *Function =3D dyn_cast<FunctionDecl>(D)) {
-    // Recursive functions should be marked when used from another functio=
n.
-    if (CurContext =3D=3D Function) return;
-
-    // Implicit instantiation of function templates and member functions of
-    // class templates.
-    if (Function->isImplicitlyInstantiable()) {
-      bool AlreadyInstantiated =3D false;
-      if (FunctionTemplateSpecializationInfo *SpecInfo
-                                =3D Function->getTemplateSpecializationInf=
o()) {
-        if (SpecInfo->getPointOfInstantiation().isInvalid())
-          SpecInfo->setPointOfInstantiation(Loc);
-        else if (SpecInfo->getTemplateSpecializationKind()
-                   =3D=3D TSK_ImplicitInstantiation)
-          AlreadyInstantiated =3D true;
-      } else if (MemberSpecializationInfo *MSInfo
-                                  =3D Function->getMemberSpecializationInf=
o()) {
-        if (MSInfo->getPointOfInstantiation().isInvalid())
-          MSInfo->setPointOfInstantiation(Loc);
-        else if (MSInfo->getTemplateSpecializationKind()
-                   =3D=3D TSK_ImplicitInstantiation)
-          AlreadyInstantiated =3D true;
+
+  // Recursive functions should be marked when used from another function.
+  // FIXME: Is this really right?
+  if (CurContext =3D=3D Func) return;
+
+  // Implicit instantiation of function templates and member functions of
+  // class templates.
+  if (Func->isImplicitlyInstantiable()) {
+    bool AlreadyInstantiated =3D false;
+    SourceLocation PointOfInstantiation =3D Loc;
+    if (FunctionTemplateSpecializationInfo *SpecInfo
+                              =3D Func->getTemplateSpecializationInfo()) {
+      if (SpecInfo->getPointOfInstantiation().isInvalid())
+        SpecInfo->setPointOfInstantiation(Loc);
+      else if (SpecInfo->getTemplateSpecializationKind()
+                 =3D=3D TSK_ImplicitInstantiation) {
+        AlreadyInstantiated =3D true;
+        PointOfInstantiation =3D SpecInfo->getPointOfInstantiation();
       }
-
+    } else if (MemberSpecializationInfo *MSInfo
+                                =3D Func->getMemberSpecializationInfo()) {
+      if (MSInfo->getPointOfInstantiation().isInvalid())
+        MSInfo->setPointOfInstantiation(Loc);
+      else if (MSInfo->getTemplateSpecializationKind()
+                 =3D=3D TSK_ImplicitInstantiation) {
+        AlreadyInstantiated =3D true;
+        PointOfInstantiation =3D MSInfo->getPointOfInstantiation();
+      }
+    }
+
+    if (!AlreadyInstantiated || Func->isConstexpr()) {
+      if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
+          cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
+        PendingLocalImplicitInstantiations.push_back(
+            std::make_pair(Func, PointOfInstantiation));
+      else if (Func->isConstexpr())
+        // Do not defer instantiations of constexpr functions, to avoid the
+        // expression evaluator needing to call back into Sema if it sees a
+        // call to such a function.
+        InstantiateFunctionDefinition(PointOfInstantiation, Func);
+      else {
+        PendingInstantiations.push_back(std::make_pair(Func,
+                                                       PointOfInstantiatio=
n));
+        // Notify the consumer that a function was implicitly instantiated.
+        Consumer.HandleCXXImplicitFunctionInstantiation(Func);
+      }
+    }
+  } else {
+    // Walk redefinitions, as some of them may be instantiable.
+    for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
+         e(Func->redecls_end()); i !=3D e; ++i) {
+      if (!i->isUsed(false) && i->isImplicitlyInstantiable())
+        MarkFunctionReferenced(Loc, *i);
+    }
+  }
+
+  // Keep track of used but undefined functions.
+  if (!Func->isPure() && !Func->hasBody() &&
+      Func->getLinkage() !=3D ExternalLinkage) {
+    SourceLocation &old =3D UndefinedInternals[Func->getCanonicalDecl()];
+    if (old.isInvalid()) old =3D Loc;
+  }
+
+  Func->setUsed(true);
+}
+
+static void
+diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
+                                   VarDecl *var, DeclContext *DC) {
+  DeclContext *VarDC =3D var->getDeclContext();
+
+  //  If the parameter still belongs to the translation unit, then
+  //  we're actually just using one parameter in the declaration of
+  //  the next.
+  if (isa<ParmVarDecl>(var) &&
+      isa<TranslationUnitDecl>(VarDC))
+    return;
+
+  // For C code, don't diagnose about capture if we're not actually in code
+  // right now; it's impossible to write a non-constant expression outside=
 of
+  // function context, so we'll get other (more useful) diagnostics later.
+  //
+  // For C++, things get a bit more nasty... it would be nice to suppress =
this
+  // diagnostic for certain cases like using a local variable in an array =
bound
+  // for a member of a local class, but the correct predicate is not obvio=
us.
+  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
+    return;
+
+  if (isa<CXXMethodDecl>(VarDC) &&
+      cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
+    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
+      << var->getIdentifier();
+  } else if (FunctionDecl *fn =3D dyn_cast<FunctionDecl>(VarDC)) {
+    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
+      << var->getIdentifier() << fn->getDeclName();
+  } else if (isa<BlockDecl>(VarDC)) {
+    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
+      << var->getIdentifier();
+  } else {
+    // FIXME: Is there any other context where a local variable can be
+    // declared?
+    S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
+      << var->getIdentifier();
+  }
+
+  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
+    << var->getIdentifier();
+
+  // FIXME: Add additional diagnostic info about class etc. which prevents
+  // capture.
+}
+
+/// \brief Capture the given variable in the given lambda expression.
+static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
+                                  VarDecl *Var, QualType FieldType,=20
+                                  QualType DeclRefType,
+                                  SourceLocation Loc) {
+  CXXRecordDecl *Lambda =3D LSI->Lambda;
+
+  // Build the non-static data member.
+  FieldDecl *Field
+    =3D FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
+                        S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
+                        0, false, false);
+  Field->setImplicit(true);
+  Field->setAccess(AS_private);
+  Lambda->addDecl(Field);
+
+  // C++11 [expr.prim.lambda]p21:
+  //   When the lambda-expression is evaluated, the entities that
+  //   are captured by copy are used to direct-initialize each
+  //   corresponding non-static data member of the resulting closure
+  //   object. (For array members, the array elements are
+  //   direct-initialized in increasing subscript order.) These
+  //   initializations are performed in the (unspecified) order in
+  //   which the non-static data members are declared.
+     =20
+  // Introduce a new evaluation context for the initialization, so
+  // that temporaries introduced as part of the capture are retained
+  // to be re-"exported" from the lambda expression itself.
+  S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
+
+  // C++ [expr.prim.labda]p12:
+  //   An entity captured by a lambda-expression is odr-used (3.2) in
+  //   the scope containing the lambda-expression.
+  Expr *Ref =3D new (S.Context) DeclRefExpr(Var, false, DeclRefType,
+                                          VK_LValue, Loc);
+  Var->setReferenced(true);
+  Var->setUsed(true);
+
+  // When the field has array type, create index variables for each
+  // dimension of the array. We use these index variables to subscript
+  // the source array, and other clients (e.g., CodeGen) will perform
+  // the necessary iteration with these index variables.
+  SmallVector<VarDecl *, 4> IndexVariables;
+  QualType BaseType =3D FieldType;
+  QualType SizeType =3D S.Context.getSizeType();
+  LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
+  while (const ConstantArrayType *Array
+                        =3D S.Context.getAsConstantArrayType(BaseType)) {
+    // Create the iteration variable for this array index.
+    IdentifierInfo *IterationVarName =3D 0;
+    {
+      SmallString<8> Str;
+      llvm::raw_svector_ostream OS(Str);
+      OS << "__i" << IndexVariables.size();
+      IterationVarName =3D &S.Context.Idents.get(OS.str());
+    }
+    VarDecl *IterationVar
+      =3D VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
+                        IterationVarName, SizeType,
+                        S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
+                        SC_None, SC_None);
+    IndexVariables.push_back(IterationVar);
+    LSI->ArrayIndexVars.push_back(IterationVar);
+   =20
+    // Create a reference to the iteration variable.
+    ExprResult IterationVarRef
+      =3D S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
+    assert(!IterationVarRef.isInvalid() &&
+           "Reference to invented variable cannot fail!");
+    IterationVarRef =3D S.DefaultLvalueConversion(IterationVarRef.take());
+    assert(!IterationVarRef.isInvalid() &&
+           "Conversion of invented variable cannot fail!");
+   =20
+    // Subscript the array with this iteration variable.
+    ExprResult Subscript =3D S.CreateBuiltinArraySubscriptExpr(
+                             Ref, Loc, IterationVarRef.take(), Loc);
+    if (Subscript.isInvalid()) {
+      S.CleanupVarDeclMarking();
+      S.DiscardCleanupsInEvaluationContext();
+      S.PopExpressionEvaluationContext();
+      return ExprError();
+    }
+
+    Ref =3D Subscript.take();
+    BaseType =3D Array->getElementType();
+  }
+
+  // Construct the entity that we will be initializing. For an array, this
+  // will be first element in the array, which may require several levels
+  // of array-subscript entities.=20
+  SmallVector<InitializedEntity, 4> Entities;
+  Entities.reserve(1 + IndexVariables.size());
+  Entities.push_back(
+    InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
+  for (unsigned I =3D 0, N =3D IndexVariables.size(); I !=3D N; ++I)
+    Entities.push_back(InitializedEntity::InitializeElement(S.Context,
+                                                            0,
+                                                            Entities.back(=
)));
+
+  InitializationKind InitKind
+    =3D InitializationKind::CreateDirect(Loc, Loc, Loc);
+  InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
+  ExprResult Result(true);
+  if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
+    Result =3D Init.Perform(S, Entities.back(), InitKind,=20
+                          MultiExprArg(S, &Ref, 1));
+
+  // If this initialization requires any cleanups (e.g., due to a
+  // default argument to a copy constructor), note that for the
+  // lambda.
+  if (S.ExprNeedsCleanups)
+    LSI->ExprNeedsCleanups =3D true;
+
+  // Exit the expression evaluation context used for the capture.
+  S.CleanupVarDeclMarking();
+  S.DiscardCleanupsInEvaluationContext();
+  S.PopExpressionEvaluationContext();
+  return Result;
+}
+
+bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,=20
+                              TryCaptureKind Kind, SourceLocation Ellipsis=
Loc,
+                              bool BuildAndDiagnose,=20
+                              QualType &CaptureType,
+                              QualType &DeclRefType) {
+  bool Nested =3D false;
+ =20
+  DeclContext *DC =3D CurContext;
+  if (Var->getDeclContext() =3D=3D DC) return true;
+  if (!Var->hasLocalStorage()) return true;
+
+  bool HasBlocksAttr =3D Var->hasAttr<BlocksAttr>();
+
+  // Walk up the stack to determine whether we can capture the variable,
+  // performing the "simple" checks that don't depend on type. We stop when
+  // we've either hit the declared scope of the variable or find an existi=
ng
+  // capture of that variable.
+  CaptureType =3D Var->getType();
+  DeclRefType =3D CaptureType.getNonReferenceType();
+  bool Explicit =3D (Kind !=3D TryCapture_Implicit);
+  unsigned FunctionScopesIndex =3D FunctionScopes.size() - 1;
+  do {
+    // Only block literals and lambda expressions can capture; other
+    // scopes don't work.
+    DeclContext *ParentDC;
+    if (isa<BlockDecl>(DC))
+      ParentDC =3D DC->getParent();
+    else if (isa<CXXMethodDecl>(DC) &&
+             cast<CXXMethodDecl>(DC)->getOverloadedOperator() =3D=3D OO_Ca=
ll &&
+             cast<CXXRecordDecl>(DC->getParent())->isLambda())
+      ParentDC =3D DC->getParent()->getParent();
+    else {
+      if (BuildAndDiagnose)
+        diagnoseUncapturableValueReference(*this, Loc, Var, DC);
+      return true;
+    }
+
+    CapturingScopeInfo *CSI =3D
+      cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
+
+    // Check whether we've already captured it.
+    if (CSI->CaptureMap.count(Var)) {
+      // If we found a capture, any subcaptures are nested.
+      Nested =3D true;
+     =20
+      // Retrieve the capture type for this variable.
+      CaptureType =3D CSI->getCapture(Var).getCaptureType();
+     =20
+      // Compute the type of an expression that refers to this variable.
+      DeclRefType =3D CaptureType.getNonReferenceType();
+     =20
+      const CapturingScopeInfo::Capture &Cap =3D CSI->getCapture(Var);
+      if (Cap.isCopyCapture() &&
+          !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutab=
le))
+        DeclRefType.addConst();
+      break;
+    }
+
+    bool IsBlock =3D isa<BlockScopeInfo>(CSI);
+    bool IsLambda =3D !IsBlock;
+
+    // Lambdas are not allowed to capture unnamed variables
+    // (e.g. anonymous unions).
+    // FIXME: The C++11 rule don't actually state this explicitly, but I'm
+    // assuming that's the intent.
+    if (IsLambda && !Var->getDeclName()) {
+      if (BuildAndDiagnose) {
+        Diag(Loc, diag::err_lambda_capture_anonymous_var);
+        Diag(Var->getLocation(), diag::note_declared_at);
+      }
+      return true;
+    }
+
+    // Prohibit variably-modified types; they're difficult to deal with.
+    if (Var->getType()->isVariablyModifiedType()) {
+      if (BuildAndDiagnose) {
+        if (IsBlock)
+          Diag(Loc, diag::err_ref_vm_type);
+        else
+          Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(=
);
+        Diag(Var->getLocation(), diag::note_previous_decl)=20
+          << Var->getDeclName();
+      }
+      return true;
+    }
+
+    // Lambdas are not allowed to capture __block variables; they don't
+    // support the expected semantics.
+    if (IsLambda && HasBlocksAttr) {
+      if (BuildAndDiagnose) {
+        Diag(Loc, diag::err_lambda_capture_block)=20
+          << Var->getDeclName();
+        Diag(Var->getLocation(), diag::note_previous_decl)=20
+          << Var->getDeclName();
+      }
+      return true;
+    }
+
+    if (CSI->ImpCaptureStyle =3D=3D CapturingScopeInfo::ImpCap_None && !Ex=
plicit) {
+      // No capture-default
+      if (BuildAndDiagnose) {
+        Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
+        Diag(Var->getLocation(), diag::note_previous_decl)=20
+          << Var->getDeclName();
+        Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
+             diag::note_lambda_decl);
+      }
+      return true;
+    }
+
+    FunctionScopesIndex--;
+    DC =3D ParentDC;
+    Explicit =3D false;
+  } while (!Var->getDeclContext()->Equals(DC));
+
+  // Walk back down the scope stack, computing the type of the capture at
+  // each step, checking type-specific requirements, and adding captures if
+  // requested.
+  for (unsigned I =3D ++FunctionScopesIndex, N =3D FunctionScopes.size(); =
I !=3D N;=20
+       ++I) {
+    CapturingScopeInfo *CSI =3D cast<CapturingScopeInfo>(FunctionScopes[I]=
);
+   =20
+    // Compute the type of the capture and of a reference to the capture w=
ithin
+    // this scope.
+    if (isa<BlockScopeInfo>(CSI)) {
+      Expr *CopyExpr =3D 0;
+      bool ByRef =3D false;
+     =20
+      // Blocks are not allowed to capture arrays.
+      if (CaptureType->isArrayType()) {
+        if (BuildAndDiagnose) {
+          Diag(Loc, diag::err_ref_array_type);
+          Diag(Var->getLocation(), diag::note_previous_decl)=20
+          << Var->getDeclName();
+        }
+        return true;
+      }
+
+      // Forbid the block-capture of autoreleasing variables.
+      if (CaptureType.getObjCLifetime() =3D=3D Qualifiers::OCL_Autoreleasi=
ng) {
+        if (BuildAndDiagnose) {
+          Diag(Loc, diag::err_arc_autoreleasing_capture)
+            << /*block*/ 0;
+          Diag(Var->getLocation(), diag::note_previous_decl)
+            << Var->getDeclName();
+        }
+        return true;
+      }
+
+      if (HasBlocksAttr || CaptureType->isReferenceType()) {
+        // Block capture by reference does not change the capture or
+        // declaration reference types.
+        ByRef =3D true;
+      } else {
+        // Block capture by copy introduces 'const'.
+        CaptureType =3D CaptureType.getNonReferenceType().withConst();
+        DeclRefType =3D CaptureType;
+               =20
+        if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
+          if (const RecordType *Record =3D DeclRefType->getAs<RecordType>(=
)) {
+            // The capture logic needs the destructor, so make sure we mar=
k it.
+            // Usually this is unnecessary because most local variables ha=
ve
+            // their destructors marked at declaration time, but parameter=
s are
+            // an exception because it's technically only the call site th=
at
+            // actually requires the destructor.
+            if (isa<ParmVarDecl>(Var))
+              FinalizeVarWithDestructor(Var, Record);
+           =20
+            // According to the blocks spec, the capture of a variable from
+            // the stack requires a const copy constructor.  This is not t=
rue
+            // of the copy/move done to move a __block variable to the hea=
p.
+            Expr *DeclRef =3D new (Context) DeclRefExpr(Var, false,
+                                                      DeclRefType.withCons=
t(),=20
+                                                      VK_LValue, Loc);
+            ExprResult Result
+              =3D PerformCopyInitialization(
+                  InitializedEntity::InitializeBlock(Var->getLocation(),
+                                                     CaptureType, false),
+                  Loc, Owned(DeclRef));
+           =20
+            // Build a full-expression copy expression if initialization
+            // succeeded and used a non-trivial constructor.  Recover from
+            // errors by pretending that the copy isn't necessary.
+            if (!Result.isInvalid() &&
+                !cast<CXXConstructExpr>(Result.get())->getConstructor()
+                   ->isTrivial()) {
+              Result =3D MaybeCreateExprWithCleanups(Result);
+              CopyExpr =3D Result.take();
+            }
+          }
+        }
+      }
+
+      // Actually capture the variable.
+      if (BuildAndDiagnose)
+        CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,=20
+                        SourceLocation(), CaptureType, CopyExpr);
+      Nested =3D true;
+      continue;
+    }=20
+   =20
+    LambdaScopeInfo *LSI =3D cast<LambdaScopeInfo>(CSI);
+   =20
+    // Determine whether we are capturing by reference or by value.
+    bool ByRef =3D false;
+    if (I =3D=3D N - 1 && Kind !=3D TryCapture_Implicit) {
+      ByRef =3D (Kind =3D=3D TryCapture_ExplicitByRef);
+    } else {
+      ByRef =3D (LSI->ImpCaptureStyle =3D=3D LambdaScopeInfo::ImpCap_Lambd=
aByref);
+    }
+   =20
+    // Compute the type of the field that will capture this variable.
+    if (ByRef) {
+      // C++11 [expr.prim.lambda]p15:
+      //   An entity is captured by reference if it is implicitly or
+      //   explicitly captured but not captured by copy. It is
+      //   unspecified whether additional unnamed non-static data
+      //   members are declared in the closure type for entities
+      //   captured by reference.
+      //
+      // FIXME: It is not clear whether we want to build an lvalue referen=
ce
+      // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC a=
ppears
+      // to do the former, while EDG does the latter. Core issue 1249 will=20
+      // clarify, but for now we follow GCC because it's a more permissive=
 and
+      // easily defensible position.
+      CaptureType =3D Context.getLValueReferenceType(DeclRefType);
+    } else {
+      // C++11 [expr.prim.lambda]p14:
+      //   For each entity captured by copy, an unnamed non-static
+      //   data member is declared in the closure type. The
+      //   declaration order of these members is unspecified. The type
+      //   of such a data member is the type of the corresponding
+      //   captured entity if the entity is not a reference to an
+      //   object, or the referenced type otherwise. [Note: If the
+      //   captured entity is a reference to a function, the
+      //   corresponding data member is also a reference to a
+      //   function. - end note ]
+      if (const ReferenceType *RefType =3D CaptureType->getAs<ReferenceTyp=
e>()){
+        if (!RefType->getPointeeType()->isFunctionType())
+          CaptureType =3D RefType->getPointeeType();
+      }
+
+      // Forbid the lambda copy-capture of autoreleasing variables.
+      if (CaptureType.getObjCLifetime() =3D=3D Qualifiers::OCL_Autoreleasi=
ng) {
+        if (BuildAndDiagnose) {
+          Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
+          Diag(Var->getLocation(), diag::note_previous_decl)
+            << Var->getDeclName();
+        }
+        return true;
+      }
+    }
+
+    // Capture this variable in the lambda.
+    Expr *CopyExpr =3D 0;
+    if (BuildAndDiagnose) {
+      ExprResult Result =3D captureInLambda(*this, LSI, Var, CaptureType,
+                                          DeclRefType, Loc);
+      if (!Result.isInvalid())
+        CopyExpr =3D Result.take();
+    }
+   =20
+    // Compute the type of a reference to this captured variable.
+    if (ByRef)
+      DeclRefType =3D CaptureType.getNonReferenceType();
+    else {
+      // C++ [expr.prim.lambda]p5:
+      //   The closure type for a lambda-expression has a public inline=20
+      //   function call operator [...]. This function call operator is=20
+      //   declared const (9.3.1) if and only if the lambda-expression=E2=
=80=99s=20
+      //   parameter-declaration-clause is not followed by mutable.
+      DeclRefType =3D CaptureType.getNonReferenceType();
+      if (!LSI->Mutable && !CaptureType->isReferenceType())
+        DeclRefType.addConst();     =20
+    }
+   =20
+    // Add the capture.
+    if (BuildAndDiagnose)
+      CSI->addCapture(Var, /*IsBlock=3D*/false, ByRef, Nested, Loc,
+                      EllipsisLoc, CaptureType, CopyExpr);
+    Nested =3D true;
+  }
+
+  return false;
+}
+
+bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
+                              TryCaptureKind Kind, SourceLocation Ellipsis=
Loc) { =20
+  QualType CaptureType;
+  QualType DeclRefType;
+  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
+                            /*BuildAndDiagnose=3D*/true, CaptureType,
+                            DeclRefType);
+}
+
+QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
+  QualType CaptureType;
+  QualType DeclRefType;
+ =20
+  // Determine whether we can capture this variable.
+  if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
+                         /*BuildAndDiagnose=3D*/false, CaptureType, DeclRe=
fType))
+    return QualType();
+
+  return DeclRefType;
+}
+
+static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
+                               SourceLocation Loc) {
+  // Keep track of used but undefined variables.
+  // FIXME: We shouldn't suppress this warning for static data members.
+  if (Var->hasDefinition(SemaRef.Context) =3D=3D VarDecl::DeclarationOnly =
&&
+      Var->getLinkage() !=3D ExternalLinkage &&
+      !(Var->isStaticDataMember() && Var->hasInit())) {
+    SourceLocation &old =3D SemaRef.UndefinedInternals[Var->getCanonicalDe=
cl()];
+    if (old.isInvalid()) old =3D Loc;
+  }
+
+  SemaRef.tryCaptureVariable(Var, Loc);
+
+  Var->setUsed(true);
+}
+
+void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
+  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is=20
+  // an object that satisfies the requirements for appearing in a
+  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
+  // is immediately applied."  This function handles the lvalue-to-rvalue
+  // conversion part.
+  MaybeODRUseExprs.erase(E->IgnoreParens());
+}
+
+ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
+  if (!Res.isUsable())
+    return Res;
+
+  // If a constant-expression is a reference to a variable where we delay
+  // deciding whether it is an odr-use, just assume we will apply the
+  // lvalue-to-rvalue conversion.  In the one case where this doesn't happ=
en
+  // (a non-type template argument), we have special handling anyway.
+  UpdateMarkingForLValueToRValue(Res.get());
+  return Res;
+}
+
+void Sema::CleanupVarDeclMarking() {
+  for (llvm::SmallPtrSetIterator<Expr*> i =3D MaybeODRUseExprs.begin(),
+                                        e =3D MaybeODRUseExprs.end();
+       i !=3D e; ++i) {
+    VarDecl *Var;
+    SourceLocation Loc;
+    if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(*i)) {
+      Var =3D cast<VarDecl>(DRE->getDecl());
+      Loc =3D DRE->getLocation();
+    } else if (MemberExpr *ME =3D dyn_cast<MemberExpr>(*i)) {
+      Var =3D cast<VarDecl>(ME->getMemberDecl());
+      Loc =3D ME->getMemberLoc();
+    } else {
+      llvm_unreachable("Unexpcted expression");
+    }
+
+    MarkVarDeclODRUsed(*this, Var, Loc);
+  }
+
+  MaybeODRUseExprs.clear();
+}
+
+// Mark a VarDecl referenced, and perform the necessary handling to compute
+// odr-uses.
+static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
+                                    VarDecl *Var, Expr *E) {
+  Var->setReferenced();
+
+  if (!IsPotentiallyEvaluatedContext(SemaRef))
+    return;
+
+  // Implicit instantiation of static data members of class templates.
+  if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMembe=
r()) {
+    MemberSpecializationInfo *MSInfo =3D Var->getMemberSpecializationInfo(=
);
+    assert(MSInfo && "Missing member specialization information?");
+    bool AlreadyInstantiated =3D !MSInfo->getPointOfInstantiation().isInva=
lid();
+    if (MSInfo->getTemplateSpecializationKind() =3D=3D TSK_ImplicitInstant=
iation &&
+        (!AlreadyInstantiated ||
+         Var->isUsableInConstantExpressions(SemaRef.Context))) {
       if (!AlreadyInstantiated) {
-        if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
-            cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass(=
))
-          PendingLocalImplicitInstantiations.push_back(std::make_pair(Func=
tion,
-                                                                      Loc)=
);
-        else
-          PendingInstantiations.push_back(std::make_pair(Function, Loc));
+        // This is a modification of an existing AST node. Notify listener=
s.
+        if (ASTMutationListener *L =3D SemaRef.getASTMutationListener())
+          L->StaticDataMemberInstantiated(Var);
+        MSInfo->setPointOfInstantiation(Loc);
       }
-    } else {
-      // Walk redefinitions, as some of them may be instantiable.
-      for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
-           e(Function->redecls_end()); i !=3D e; ++i) {
-        if (!i->isUsed(false) && i->isImplicitlyInstantiable())
-          MarkDeclarationReferenced(Loc, *i);
-      }
-    }
-
-    // Keep track of used but undefined functions.
-    if (!Function->isPure() && !Function->hasBody() &&
-        Function->getLinkage() !=3D ExternalLinkage) {
-      SourceLocation &old =3D UndefinedInternals[Function->getCanonicalDec=
l()];
-      if (old.isInvalid()) old =3D Loc;
-    }
-
-    Function->setUsed(true);
+      SourceLocation PointOfInstantiation =3D MSInfo->getPointOfInstantiat=
ion();
+      if (Var->isUsableInConstantExpressions(SemaRef.Context))
+        // Do not defer instantiations of variables which could be used in=
 a
+        // constant expression.
+        SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation=
,Var);
+      else
+        SemaRef.PendingInstantiations.push_back(
+            std::make_pair(Var, PointOfInstantiation));
+    }
+  }
+
+  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is=20
+  // an object that satisfies the requirements for appearing in a
+  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
+  // is immediately applied."  We check the first part here, and
+  // Sema::UpdateMarkingForLValueToRValue deals with the second part.
+  // Note that we use the C++11 definition everywhere because nothing in
+  // C++03 depends on whether we get the C++03 version correct. This does =
not
+  // apply to references, since they are not objects.
+  const VarDecl *DefVD;
+  if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
+      Var->isUsableInConstantExpressions(SemaRef.Context) &&
+      Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
+    SemaRef.MaybeODRUseExprs.insert(E);
+  else
+    MarkVarDeclODRUsed(SemaRef, Var, Loc);
+}
+
+/// \brief Mark a variable referenced, and check whether it is odr-used
+/// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
+/// used directly for normal expressions referring to VarDecl.
+void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
+  DoMarkVarDeclReferenced(*this, Loc, Var, 0);
+}
+
+static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
+                               Decl *D, Expr *E) {
+  if (VarDecl *Var =3D dyn_cast<VarDecl>(D)) {
+    DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
     return;
   }
=20
-  if (VarDecl *Var =3D dyn_cast<VarDecl>(D)) {
-    // Implicit instantiation of static data members of class templates.
-    if (Var->isStaticDataMember() &&
-        Var->getInstantiatedFromStaticDataMember()) {
-      MemberSpecializationInfo *MSInfo =3D Var->getMemberSpecializationInf=
o();
-      assert(MSInfo && "Missing member specialization information?");
-      if (MSInfo->getPointOfInstantiation().isInvalid() &&
-          MSInfo->getTemplateSpecializationKind()=3D=3D TSK_ImplicitInstan=
tiation) {
-        MSInfo->setPointOfInstantiation(Loc);
-        // This is a modification of an existing AST node. Notify listener=
s.
-        if (ASTMutationListener *L =3D getASTMutationListener())
-          L->StaticDataMemberInstantiated(Var);
-        PendingInstantiations.push_back(std::make_pair(Var, Loc));
-      }
-    }
-
-    // Keep track of used but undefined variables.  We make a hole in
-    // the warning for static const data members with in-line
-    // initializers.
-    if (Var->hasDefinition() =3D=3D VarDecl::DeclarationOnly
-        && Var->getLinkage() !=3D ExternalLinkage
-        && !(Var->isStaticDataMember() && Var->hasInit())) {
-      SourceLocation &old =3D UndefinedInternals[Var->getCanonicalDecl()];
-      if (old.isInvalid()) old =3D Loc;
-    }
-
-    D->setUsed(true);
-    return;
-  }
+  SemaRef.MarkAnyDeclReferenced(Loc, D);
+}=20
+
+/// \brief Perform reference-marking and odr-use handling for a DeclRefExp=
r.
+void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
+  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
+}
+
+/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
+void Sema::MarkMemberReferenced(MemberExpr *E) {
+  MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
+}
+
+/// \brief Perform marking for a reference to an arbitrary declaration.  It
+/// marks the declaration referenced, and performs odr-use checking for fu=
nctions
+/// and variables. This method should not be used when building an normal
+/// expression which refers to a variable.
+void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
+  if (VarDecl *VD =3D dyn_cast<VarDecl>(D))
+    MarkVariableReferenced(Loc, VD);
+  else if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D))
+    MarkFunctionReferenced(Loc, FD);
+  else
+    D->setReferenced();
 }
=20
 namespace {
@@ -9331,7 +10478,8 @@
 bool MarkReferencedDecls::TraverseTemplateArgument(
   const TemplateArgument &Arg) {
   if (Arg.getKind() =3D=3D TemplateArgument::Declaration) {
-    S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
+    if (Decl *D =3D Arg.getAsDecl())
+      S.MarkAnyDeclReferenced(Loc, D);
   }
=20
   return Inherited::TraverseTemplateArgument(Arg);
@@ -9357,38 +10505,51 @@
   /// potentially-evaluated subexpressions as "referenced".
   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMar=
ker> {
     Sema &S;
+    bool SkipLocalVariables;
    =20
   public:
     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
    =20
-    explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
+    EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)=20
+      : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables)=
 { }
    =20
     void VisitDeclRefExpr(DeclRefExpr *E) {
-      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
+      // If we were asked not to visit local variables, don't.
+      if (SkipLocalVariables) {
+        if (VarDecl *VD =3D dyn_cast<VarDecl>(E->getDecl()))
+          if (VD->hasLocalStorage())
+            return;
+      }
+     =20
+      S.MarkDeclRefReferenced(E);
     }
    =20
     void VisitMemberExpr(MemberExpr *E) {
-      S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
+      S.MarkMemberReferenced(E);
       Inherited::VisitMemberExpr(E);
     }
    =20
+    void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
+      S.MarkFunctionReferenced(E->getLocStart(),
+            const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructo=
r()));
+      Visit(E->getSubExpr());
+    }
+   =20
     void VisitCXXNewExpr(CXXNewExpr *E) {
-      if (E->getConstructor())
-        S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
       if (E->getOperatorNew())
-        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
+        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
       if (E->getOperatorDelete())
-        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete=
());
+        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
       Inherited::VisitCXXNewExpr(E);
     }
-   =20
+
     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
       if (E->getOperatorDelete())
-        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete=
());
+        S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
       QualType Destroyed =3D S.Context.getBaseElementType(E->getDestroyedT=
ype());
       if (const RecordType *DestroyedRec =3D Destroyed->getAs<RecordType>(=
)) {
         CXXRecordDecl *Record =3D cast<CXXRecordDecl>(DestroyedRec->getDec=
l());
-        S.MarkDeclarationReferenced(E->getLocStart(),=20
+        S.MarkFunctionReferenced(E->getLocStart(),=20
                                     S.LookupDestructor(Record));
       }
      =20
@@ -9396,24 +10557,31 @@
     }
    =20
     void VisitCXXConstructExpr(CXXConstructExpr *E) {
-      S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
+      S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
       Inherited::VisitCXXConstructExpr(E);
     }
    =20
-    void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
-      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
-    }
-   =20
     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
       Visit(E->getExpr());
     }
+
+    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
+      Inherited::VisitImplicitCastExpr(E);
+
+      if (E->getCastKind() =3D=3D CK_LValueToRValue)
+        S.UpdateMarkingForLValueToRValue(E->getSubExpr());
+    }
   };
 }
=20
 /// \brief Mark any declarations that appear within this expression or any
 /// potentially-evaluated subexpressions as "referenced".
-void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
-  EvaluatedExprMarker(*this).Visit(E);
+///
+/// \param SkipLocalVariables If true, don't mark local variables as=20
+/// 'referenced'.
+void Sema::MarkDeclarationsReferencedInExpr(Expr *E,=20
+                                            bool SkipLocalVariables) {
+  EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
 }
=20
 /// \brief Emit a diagnostic that describes an effect on the run-time beha=
vior
@@ -9439,6 +10607,10 @@
     // The argument will never be evaluated, so don't complain.
     break;
=20
+  case ConstantEvaluated:
+    // Relevant diagnostics should be produced by constant evaluation.
+    break;
+
   case PotentiallyEvaluated:
   case PotentiallyEvaluatedIfUsed:
     if (Statement && getCurFunctionOrMethodDecl()) {
@@ -9449,10 +10621,6 @@
       Diag(Loc, PD);
      =20
     return true;
-
-  case PotentiallyPotentiallyEvaluated:
-    ExprEvalContexts.back().addDiagnostic(Loc, PD);
-    break;
   }
=20
   return false;
@@ -9463,6 +10631,13 @@
   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
     return false;
=20
+  // If we're inside a decltype's expression, don't check for a valid retu=
rn
+  // type or construct temporaries until we know whether this is the last =
call.
+  if (ExprEvalContexts.back().IsDecltype) {
+    ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
+    return false;
+  }
+
   PartialDiagnostic Note =3D
     FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_he=
re)
     << FD->getDeclName() : PDiag();
@@ -9522,7 +10697,7 @@
=20
   Diag(Loc, diagnostic) << E->getSourceRange();
=20
-  SourceLocation Open =3D E->getSourceRange().getBegin();
+  SourceLocation Open =3D E->getLocStart();
   SourceLocation Close =3D PP.getLocForEndOfToken(E->getSourceRange().getE=
nd());
   Diag(Loc, diag::note_condition_assign_silence)
         << FixItHint::CreateInsertion(Open, "(")
@@ -9556,9 +10731,10 @@
       SourceLocation Loc =3D opE->getOperatorLoc();
      =20
       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRang=
e();
+      SourceRange ParenERange =3D ParenE->getSourceRange();
       Diag(Loc, diag::note_equality_comparison_silence)
-        << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
-        << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
+        << FixItHint::CreateRemoval(ParenERange.getBegin())
+        << FixItHint::CreateRemoval(ParenERange.getEnd());
       Diag(Loc, diag::note_equality_comparison_to_assign)
         << FixItHint::CreateReplacement(Loc, "=3D");
     }
@@ -9574,7 +10750,7 @@
   E =3D result.take();
=20
   if (!E->isTypeDependent()) {
-    if (getLangOptions().CPlusPlus)
+    if (getLangOpts().CPlusPlus)
       return CheckCXXBooleanCondition(E); // C++ 6.4p4
=20
     ExprResult ERes =3D DefaultFunctionArrayLvalueConversion(E);
@@ -9613,7 +10789,6 @@
=20
     ExprResult VisitStmt(Stmt *S) {
       llvm_unreachable("unexpected statement!");
-      return ExprError();
     }
=20
     ExprResult VisitExpr(Expr *E) {
@@ -9662,7 +10837,7 @@
       E->setType(VD->getType());
=20
       assert(E->getValueKind() =3D=3D VK_RValue);
-      if (S.getLangOptions().CPlusPlus &&
+      if (S.getLangOpts().CPlusPlus &&
           !(isa<CXXMethodDecl>(VD) &&
             cast<CXXMethodDecl>(VD)->isInstance()))
         E->setValueKind(VK_LValue);
@@ -9706,7 +10881,6 @@
=20
     ExprResult VisitStmt(Stmt *S) {
       llvm_unreachable("unexpected statement!");
-      return ExprError();
     }
=20
     ExprResult VisitExpr(Expr *E) {
@@ -9870,20 +11044,39 @@
=20
 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *=
E) {
   // The only case we should ever see here is a function-to-pointer decay.
-  assert(E->getCastKind() =3D=3D CK_FunctionToPointerDecay);
-  assert(E->getValueKind() =3D=3D VK_RValue);
-  assert(E->getObjectKind() =3D=3D OK_Ordinary);
-
-  E->setType(DestType);
-
-  // Rebuild the sub-expression as the pointee (function) type.
-  DestType =3D DestType->castAs<PointerType>()->getPointeeType();
-
-  ExprResult Result =3D Visit(E->getSubExpr());
-  if (!Result.isUsable()) return ExprError();
-
-  E->setSubExpr(Result.take());
-  return S.Owned(E);
+  if (E->getCastKind() =3D=3D CK_FunctionToPointerDecay) {
+    assert(E->getValueKind() =3D=3D VK_RValue);
+    assert(E->getObjectKind() =3D=3D OK_Ordinary);
+ =20
+    E->setType(DestType);
+ =20
+    // Rebuild the sub-expression as the pointee (function) type.
+    DestType =3D DestType->castAs<PointerType>()->getPointeeType();
+ =20
+    ExprResult Result =3D Visit(E->getSubExpr());
+    if (!Result.isUsable()) return ExprError();
+ =20
+    E->setSubExpr(Result.take());
+    return S.Owned(E);
+  } else if (E->getCastKind() =3D=3D CK_LValueToRValue) {
+    assert(E->getValueKind() =3D=3D VK_RValue);
+    assert(E->getObjectKind() =3D=3D OK_Ordinary);
+
+    assert(isa<BlockPointerType>(E->getType()));
+
+    E->setType(DestType);
+
+    // The sub-expression has to be a lvalue reference, so rebuild it as s=
uch.
+    DestType =3D S.Context.getLValueReferenceType(DestType);
+
+    ExprResult Result =3D Visit(E->getSubExpr());
+    if (!Result.isUsable()) return ExprError();
+
+    E->setSubExpr(Result.take());
+    return S.Owned(E);
+  } else {
+    llvm_unreachable("Unhandled cast type!");
+  }
 }
=20
 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
@@ -9915,7 +11108,7 @@
       }
=20
     // Function references aren't l-values in C.
-    if (!S.getLangOptions().CPlusPlus)
+    if (!S.getLangOpts().CPlusPlus)
       ValueKind =3D VK_RValue;
=20
   //  - variables
@@ -9957,6 +11150,10 @@
   return CastExpr;
 }
=20
+ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
+  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
+}
+
 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
   Expr *orig =3D E;
   unsigned diagID =3D diag::err_uncasted_use_of_unknown_any;
@@ -10003,11 +11200,13 @@
 /// Check for operands with placeholder types and complain if found.
 /// Returns true if there was an error and no recovery was possible.
 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
-  // Placeholder types are always *exactly* the appropriate builtin type.
-  QualType type =3D E->getType();
+  const BuiltinType *placeholderType =3D E->getType()->getAsPlaceholderTyp=
e();
+  if (!placeholderType) return Owned(E);
+
+  switch (placeholderType->getKind()) {
=20
   // Overloaded expressions.
-  if (type =3D=3D Context.OverloadTy) {
+  case BuiltinType::Overload: {
     // Try to resolve a single function template specialization.
     // This is obligatory.
     ExprResult result =3D Owned(E);
@@ -10023,19 +11222,37 @@
   }
=20
   // Bound member functions.
-  if (type =3D=3D Context.BoundMemberTy) {
+  case BuiltinType::BoundMember: {
     ExprResult result =3D Owned(E);
     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
                          /*complain*/ true);
     return result;
-  }   =20
+  }
+
+  // ARC unbridged casts.
+  case BuiltinType::ARCUnbridgedCast: {
+    Expr *realCast =3D stripARCUnbridgedCast(E);
+    diagnoseARCUnbridgedCast(realCast);
+    return Owned(realCast);
+  }
=20
   // Expressions of unknown type.
-  if (type =3D=3D Context.UnknownAnyTy)
+  case BuiltinType::UnknownAny:
     return diagnoseUnknownAnyExpr(*this, E);
=20
-  assert(!type->isPlaceholderType());
-  return Owned(E);
+  // Pseudo-objects.
+  case BuiltinType::PseudoObject:
+    return checkPseudoObjectRValue(E);
+
+  // Everything else should be impossible.
+#define BUILTIN_TYPE(Id, SingletonId) \
+  case BuiltinType::Id:
+#define PLACEHOLDER_TYPE(Id, SingletonId)
+#include "clang/AST/BuiltinTypes.def"
+    break;
+  }
+
+  llvm_unreachable("invalid placeholder type!");
 }
=20
 bool Sema::CheckCaseExpression(Expr *E) {
@@ -10045,3 +11262,28 @@
     return E->getType()->isIntegralOrEnumerationType();
   return false;
 }
+
+/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
+ExprResult
+Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
+  assert((Kind =3D=3D tok::kw___objc_yes || Kind =3D=3D tok::kw___objc_no)=
 &&
+         "Unknown Objective-C Boolean value!");
+  QualType ObjCBoolLiteralQT =3D Context.ObjCBuiltinBoolTy;
+  // signed char is the default type for boolean literals. Use 'BOOL'
+  // instead, if BOOL typedef is visible in its scope instead.
+  Decl *TD =3D=20
+    LookupSingleName(TUScope, &Context.Idents.get("BOOL"),=20
+                     SourceLocation(), LookupOrdinaryName);
+  if (TypedefDecl *BoolTD =3D dyn_cast_or_null<TypedefDecl>(TD)) {
+    QualType QT =3D BoolTD->getUnderlyingType();
+    if (!QT->isIntegralOrUnscopedEnumerationType()) {
+      Diag(OpLoc, diag::warn_bool_for_boolean_literal) << QT;
+      Diag(BoolTD->getLocation(), diag::note_previous_declaration);
+    }
+    else
+      ObjCBoolLiteralQT =3D QT;
+  }
+ =20
+  return Owned(new (Context) ObjCBoolLiteralExpr(Kind =3D=3D tok::kw___obj=
c_yes,
+                                        ObjCBoolLiteralQT, OpLoc));
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaExprCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaExprCXX.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "clang/Sema/Scope.h"
 #include "clang/Sema/TemplateDeduction.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/CharUnits.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
@@ -28,6 +29,8 @@
 #include "clang/Basic/PartialDiagnostic.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/Preprocessor.h"
+#include "TypeLocBuilder.h"
+#include "llvm/ADT/APInt.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/ErrorHandling.h"
 using namespace clang;
@@ -265,6 +268,22 @@
   return ParsedType();
 }
=20
+ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectTy=
pe) {
+    if (DS.getTypeSpecType() =3D=3D DeclSpec::TST_error || !ObjectType)
+      return ParsedType();
+    assert(DS.getTypeSpecType() =3D=3D DeclSpec::TST_decltype=20
+           && "only get destructor types from declspecs");
+    QualType T =3D BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecType=
Loc());
+    QualType SearchType =3D GetTypeFromParser(ObjectType);
+    if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(Se=
archType, T)) {
+      return ParsedType::make(T);
+    }
+     =20
+    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
+      << T << SearchType;
+    return ParsedType();
+}
+
 /// \brief Build a C++ typeid expression with a type operand.
 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
                                 SourceLocation TypeidLoc,
@@ -293,7 +312,6 @@
                                 SourceLocation TypeidLoc,
                                 Expr *E,
                                 SourceLocation RParenLoc) {
-  bool isUnevaluatedOperand =3D true;
   if (E && !E->isTypeDependent()) {
     if (E->getType()->isPlaceholderType()) {
       ExprResult result =3D CheckPlaceholderExpr(E);
@@ -315,7 +333,11 @@
       //   polymorphic class type [...] [the] expression is an unevaluated
       //   operand. [...]
       if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
-        isUnevaluatedOperand =3D false;
+        // The subexpression is potentially evaluated; switch the context
+        // and recheck the subexpression.
+        ExprResult Result =3D TranformToPotentiallyEvaluated(E);
+        if (Result.isInvalid()) return ExprError();
+        E =3D Result.take();
=20
         // We require a vtable to query the type at run time.
         MarkVTableUsed(TypeidLoc, RecordD);
@@ -335,12 +357,6 @@
     }
   }
=20
-  // If this is an unevaluated operand, clear out the set of
-  // declaration references we have been computing and eliminate any
-  // temporaries introduced in its computation.
-  if (isUnevaluatedOperand)
-    ExprEvalContexts.back().Context =3D Unevaluated;
-
   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
                                            E,
                                            SourceRange(TypeidLoc, RParenLo=
c)));
@@ -525,7 +541,7 @@
 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,=20
                                bool IsThrownVarInScope) {
   // Don't report an error if 'throw' is used in system headers.
-  if (!getLangOptions().CXXExceptions &&
+  if (!getLangOpts().CXXExceptions &&
       !getSourceManager().isInSystemHeader(OpLoc))
     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
  =20
@@ -621,37 +637,23 @@
   if (isPointer)
     return Owned(E);
=20
-  // If the class has a non-trivial destructor, we must be able to call it.
-  if (RD->hasTrivialDestructor())
+  // If the class has a destructor, we must be able to call it.
+  if (RD->hasIrrelevantDestructor())
     return Owned(E);
=20
-  CXXDestructorDecl *Destructor
-    =3D const_cast<CXXDestructorDecl*>(LookupDestructor(RD));
+  CXXDestructorDecl *Destructor =3D LookupDestructor(RD);
   if (!Destructor)
     return Owned(E);
=20
-  MarkDeclarationReferenced(E->getExprLoc(), Destructor);
+  MarkFunctionReferenced(E->getExprLoc(), Destructor);
   CheckDestructorAccess(E->getExprLoc(), Destructor,
                         PDiag(diag::err_access_dtor_exception) << Ty);
+  DiagnoseUseOfDecl(Destructor, E->getExprLoc());
   return Owned(E);
 }
=20
-QualType Sema::getAndCaptureCurrentThisType() {
-  // Ignore block scopes: we can capture through them.
-  // Ignore nested enum scopes: we'll diagnose non-constant expressions
-  // where they're invalid, and other uses are legitimate.
-  // Don't ignore nested class scopes: you can't use 'this' in a local cla=
ss.
-  DeclContext *DC =3D CurContext;
-  unsigned NumBlocks =3D 0;
-  while (true) {
-    if (isa<BlockDecl>(DC)) {
-      DC =3D cast<BlockDecl>(DC)->getDeclContext();
-      ++NumBlocks;
-    } else if (isa<EnumDecl>(DC))
-      DC =3D cast<EnumDecl>(DC)->getDeclContext();
-    else break;
-  }
-
+QualType Sema::getCurrentThisType() {
+  DeclContext *DC =3D getFunctionLevelDeclContext();
   QualType ThisTy;
   if (CXXMethodDecl *method =3D dyn_cast<CXXMethodDecl>(DC)) {
     if (method && method->isInstance())
@@ -666,23 +668,74 @@
       ThisTy =3D Context.getPointerType(Context.getRecordType(RD));
   }
=20
-  // Mark that we're closing on 'this' in all the block scopes we ignored.
-  if (!ThisTy.isNull())
-    for (unsigned idx =3D FunctionScopes.size() - 1;
-         NumBlocks; --idx, --NumBlocks)
-      cast<BlockScopeInfo>(FunctionScopes[idx])->CapturesCXXThis =3D true;
-
   return ThisTy;
 }
=20
+void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
+  // We don't need to capture this in an unevaluated context.
+  if (ExprEvalContexts.back().Context =3D=3D Unevaluated && !Explicit)
+    return;
+
+  // Otherwise, check that we can capture 'this'.
+  unsigned NumClosures =3D 0;
+  for (unsigned idx =3D FunctionScopes.size() - 1; idx !=3D 0; idx--) {
+    if (CapturingScopeInfo *CSI =3D
+            dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
+      if (CSI->CXXThisCaptureIndex !=3D 0) {
+        // 'this' is already being captured; there isn't anything more to =
do.
+        break;
+      }
+     =20
+      if (CSI->ImpCaptureStyle =3D=3D CapturingScopeInfo::ImpCap_LambdaByr=
ef ||
+          CSI->ImpCaptureStyle =3D=3D CapturingScopeInfo::ImpCap_LambdaByv=
al ||
+          CSI->ImpCaptureStyle =3D=3D CapturingScopeInfo::ImpCap_Block ||
+          Explicit) {
+        // This closure can capture 'this'; continue looking upwards.
+        NumClosures++;
+        Explicit =3D false;
+        continue;
+      }
+      // This context can't implicitly capture 'this'; fail out.
+      Diag(Loc, diag::err_this_capture) << Explicit;
+      return;
+    }
+    break;
+  }
+
+  // Mark that we're implicitly capturing 'this' in all the scopes we skip=
ped.
+  // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluat=
ed
+  // contexts.
+  for (unsigned idx =3D FunctionScopes.size() - 1;
+       NumClosures; --idx, --NumClosures) {
+    CapturingScopeInfo *CSI =3D cast<CapturingScopeInfo>(FunctionScopes[id=
x]);
+    Expr *ThisExpr =3D 0;
+    QualType ThisTy =3D getCurrentThisType();
+    if (LambdaScopeInfo *LSI =3D dyn_cast<LambdaScopeInfo>(CSI)) {
+      // For lambda expressions, build a field and an initializing express=
ion.
+      CXXRecordDecl *Lambda =3D LSI->Lambda;
+      FieldDecl *Field
+        =3D FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
+                            Context.getTrivialTypeSourceInfo(ThisTy, Loc),
+                            0, false, false);
+      Field->setImplicit(true);
+      Field->setAccess(AS_private);
+      Lambda->addDecl(Field);
+      ThisExpr =3D new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=3D*=
/true);
+    }
+    bool isNested =3D NumClosures > 1;
+    CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
+  }
+}
+
 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
   /// C++ 9.3.2: In the body of a non-static member function, the keyword =
this
   /// is a non-lvalue expression whose value is the address of the object =
for
   /// which the function is called.
=20
-  QualType ThisTy =3D getAndCaptureCurrentThisType();
+  QualType ThisTy =3D getCurrentThisType();
   if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
=20
+  CheckCXXThisCapture(Loc);
   return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=3D*/fal=
se));
 }
=20
@@ -715,10 +768,10 @@
   unsigned NumExprs =3D exprs.size();
   Expr **Exprs =3D (Expr**)exprs.get();
   SourceLocation TyBeginLoc =3D TInfo->getTypeLoc().getBeginLoc();
-  SourceRange FullRange =3D SourceRange(TyBeginLoc, RParenLoc);
=20
   if (Ty->isDependentType() ||
-      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
+      CallExpr::hasAnyTypeDependentArguments(
+        llvm::makeArrayRef(Exprs, NumExprs))) {
     exprs.release();
=20
     return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
@@ -727,39 +780,64 @@
                                                     RParenLoc));
   }
=20
-  if (Ty->isArrayType())
-    return ExprError(Diag(TyBeginLoc,
-                          diag::err_value_init_for_array_type) << FullRang=
e);
-  if (!Ty->isVoidType() &&
-      RequireCompleteType(TyBeginLoc, Ty,
-                          PDiag(diag::err_invalid_incomplete_type_use)
-                            << FullRange))
-    return ExprError();
-
-  if (RequireNonAbstractType(TyBeginLoc, Ty,
-                             diag::err_allocation_of_abstract_type))
-    return ExprError();
-
+  bool ListInitialization =3D LParenLoc.isInvalid();
+  assert((!ListInitialization || (NumExprs =3D=3D 1 && isa<InitListExpr>(E=
xprs[0])))
+         && "List initialization must have initializer list as expression.=
");
+  SourceRange FullRange =3D SourceRange(TyBeginLoc,
+      ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc=
);
=20
   // C++ [expr.type.conv]p1:
   // If the expression list is a single expression, the type conversion
   // expression is equivalent (in definedness, and if defined in meaning) =
to the
   // corresponding cast expression.
-  if (NumExprs =3D=3D 1) {
+  if (NumExprs =3D=3D 1 && !ListInitialization) {
     Expr *Arg =3D Exprs[0];
     exprs.release();
     return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
   }
=20
+  QualType ElemTy =3D Ty;
+  if (Ty->isArrayType()) {
+    if (!ListInitialization)
+      return ExprError(Diag(TyBeginLoc,
+                            diag::err_value_init_for_array_type) << FullRa=
nge);
+    ElemTy =3D Context.getBaseElementType(Ty);
+  }
+
+  if (!Ty->isVoidType() &&
+      RequireCompleteType(TyBeginLoc, ElemTy,
+                          PDiag(diag::err_invalid_incomplete_type_use)
+                            << FullRange))
+    return ExprError();
+
+  if (RequireNonAbstractType(TyBeginLoc, Ty,
+                             diag::err_allocation_of_abstract_type))
+    return ExprError();
+
   InitializedEntity Entity =3D InitializedEntity::InitializeTemporary(TInf=
o);
   InitializationKind Kind
-    =3D NumExprs ? InitializationKind::CreateDirect(TyBeginLoc,
-                                                  LParenLoc, RParenLoc)
+    =3D NumExprs ? ListInitialization
+                    ? InitializationKind::CreateDirectList(TyBeginLoc)
+                    : InitializationKind::CreateDirect(TyBeginLoc,
+                                                       LParenLoc, RParenLo=
c)
                : InitializationKind::CreateValue(TyBeginLoc,
                                                  LParenLoc, RParenLoc);
   InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
   ExprResult Result =3D InitSeq.Perform(*this, Entity, Kind, move(exprs));
=20
+  if (!Result.isInvalid() && ListInitialization &&
+      isa<InitListExpr>(Result.get())) {
+    // If the list-initialization doesn't involve a constructor call, we'l=
l get
+    // the initializer-list (with corrected type) back, but that's not wha=
t we
+    // want, since it will be treated as an initializer list in further
+    // processing. Explicitly insert a cast here.
+    InitListExpr *List =3D cast<InitListExpr>(Result.take());
+    Result =3D Owned(CXXFunctionalCastExpr::Create(Context, List->getType(=
),
+                                    Expr::getValueKindForType(TInfo->getTy=
pe()),
+                                                 TInfo, TyBeginLoc, CK_NoO=
p,
+                                                 List, /*Path=3D*/0, RPare=
nLoc));
+  }
+
   // FIXME: Improve AST representation?
   return move(Result);
 }
@@ -820,18 +898,29 @@
   return (del->getNumParams() =3D=3D 2);
 }
=20
-/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
+/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
+
+/// E.g.:
 /// @code new (memory) int[size][4] @endcode
 /// or
 /// @code ::new Foo(23, "hello") @endcode
-/// For the interpretation of this heap of arguments, consult the base ver=
sion.
+///
+/// \param StartLoc The first location of the expression.
+/// \param UseGlobal True if 'new' was prefixed with '::'.
+/// \param PlacementLParen Opening paren of the placement arguments.
+/// \param PlacementArgs Placement new arguments.
+/// \param PlacementRParen Closing paren of the placement arguments.
+/// \param TypeIdParens If the type is in parens, the source range.
+/// \param D The type to be allocated, as well as array dimensions.
+/// \param ConstructorLParen Opening paren of the constructor args, empty =
if
+///                          initializer-list syntax is used.
+/// \param ConstructorArgs Constructor/initialization arguments.
+/// \param ConstructorRParen Closing paren of the constructor args.
 ExprResult
 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
                   SourceLocation PlacementLParen, MultiExprArg PlacementAr=
gs,
                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
-                  Declarator &D, SourceLocation ConstructorLParen,
-                  MultiExprArg ConstructorArgs,
-                  SourceLocation ConstructorRParen) {
+                  Declarator &D, Expr *Initializer) {
   bool TypeContainsAuto =3D D.getDeclSpec().getTypeSpecType() =3D=3D DeclS=
pec::TST_auto;
=20
   Expr *ArraySize =3D 0;
@@ -861,11 +950,11 @@
=20
       DeclaratorChunk::ArrayTypeInfo &Array =3D D.getTypeObject(I).Arr;
       if (Expr *NumElts =3D (Expr *)Array.NumElts) {
-        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() &&
-            !NumElts->isIntegerConstantExpr(Context)) {
-          Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst)
-            << NumElts->getSourceRange();
-          return ExprError();
+        if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
+          Array.NumElts =3D VerifyIntegerConstantExpression(NumElts, 0,
+            PDiag(diag::err_new_array_nonconst)).take();
+          if (!Array.NumElts)
+            return ExprError();
         }
       }
     }
@@ -876,6 +965,10 @@
   if (D.isInvalidType())
     return ExprError();
=20
+  SourceRange DirectInitRange;
+  if (ParenListExpr *List =3D dyn_cast_or_null<ParenListExpr>(Initializer))
+    DirectInitRange =3D List->getSourceRange();
+
   return BuildCXXNew(StartLoc, UseGlobal,
                      PlacementLParen,
                      move(PlacementArgs),
@@ -884,12 +977,30 @@
                      AllocType,
                      TInfo,
                      ArraySize,
-                     ConstructorLParen,
-                     move(ConstructorArgs),
-                     ConstructorRParen,
+                     DirectInitRange,
+                     Initializer,
                      TypeContainsAuto);
 }
=20
+static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Sty=
le,
+                                       Expr *Init) {
+  if (!Init)
+    return true;
+  if (ParenListExpr *PLE =3D dyn_cast<ParenListExpr>(Init))
+    return PLE->getNumExprs() =3D=3D 0;
+  if (isa<ImplicitValueInitExpr>(Init))
+    return true;
+  else if (CXXConstructExpr *CCE =3D dyn_cast<CXXConstructExpr>(Init))
+    return !CCE->isListInitialization() &&
+           CCE->getConstructor()->isDefaultConstructor();
+  else if (Style =3D=3D CXXNewExpr::ListInit) {
+    assert(isa<InitListExpr>(Init) &&
+           "Shouldn't create list CXXConstructExprs for arrays.");
+    return true;
+  }
+  return false;
+}
+
 ExprResult
 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
                   SourceLocation PlacementLParen,
@@ -899,37 +1010,76 @@
                   QualType AllocType,
                   TypeSourceInfo *AllocTypeInfo,
                   Expr *ArraySize,
-                  SourceLocation ConstructorLParen,
-                  MultiExprArg ConstructorArgs,
-                  SourceLocation ConstructorRParen,
+                  SourceRange DirectInitRange,
+                  Expr *Initializer,
                   bool TypeMayContainAuto) {
   SourceRange TypeRange =3D AllocTypeInfo->getTypeLoc().getSourceRange();
=20
+  CXXNewExpr::InitializationStyle initStyle;
+  if (DirectInitRange.isValid()) {
+    assert(Initializer && "Have parens but no initializer.");
+    initStyle =3D CXXNewExpr::CallInit;
+  } else if (Initializer && isa<InitListExpr>(Initializer))
+    initStyle =3D CXXNewExpr::ListInit;
+  else {
+    // In template instantiation, the initializer could be a CXXDefaultArg=
Expr
+    // unwrapped from a CXXConstructExpr that was implicitly built. There =
is no
+    // particularly sane way we can handle this (especially since it can e=
ven
+    // occur for array new), so we throw the initializer away and have it =
be
+    // rebuilt.
+    if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
+      Initializer =3D 0;
+    assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
+            isa<CXXConstructExpr>(Initializer)) &&
+           "Initializer expression that cannot have been implicitly create=
d.");
+    initStyle =3D CXXNewExpr::NoInit;
+  }
+
+  Expr **Inits =3D &Initializer;
+  unsigned NumInits =3D Initializer ? 1 : 0;
+  if (initStyle =3D=3D CXXNewExpr::CallInit) {
+    if (ParenListExpr *List =3D dyn_cast<ParenListExpr>(Initializer)) {
+      Inits =3D List->getExprs();
+      NumInits =3D List->getNumExprs();
+    } else if (CXXConstructExpr *CCE =3D dyn_cast<CXXConstructExpr>(Initia=
lizer)){
+      if (!isa<CXXTemporaryObjectExpr>(CCE)) {
+        // Can happen in template instantiation. Since this is just an imp=
licit
+        // construction, we just take it apart and rebuild it.
+        Inits =3D CCE->getArgs();
+        NumInits =3D CCE->getNumArgs();
+      }
+    }
+  }
+
   // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
   if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
-    if (ConstructorArgs.size() =3D=3D 0)
+    if (initStyle =3D=3D CXXNewExpr::NoInit || NumInits =3D=3D 0)
       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
                        << AllocType << TypeRange);
-    if (ConstructorArgs.size() !=3D 1) {
-      Expr *FirstBad =3D ConstructorArgs.get()[1];
-      return ExprError(Diag(FirstBad->getSourceRange().getBegin(),
+    if (initStyle =3D=3D CXXNewExpr::ListInit)
+      return ExprError(Diag(Inits[0]->getLocStart(),
+                            diag::err_auto_new_requires_parens)
+                       << AllocType << TypeRange);
+    if (NumInits > 1) {
+      Expr *FirstBad =3D Inits[1];
+      return ExprError(Diag(FirstBad->getLocStart(),
                             diag::err_auto_new_ctor_multiple_expressions)
                        << AllocType << TypeRange);
     }
+    Expr *Deduce =3D Inits[0];
     TypeSourceInfo *DeducedType =3D 0;
-    if (!DeduceAutoType(AllocTypeInfo, ConstructorArgs.get()[0], DeducedTy=
pe))
+    if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) =3D=3D
+            DAR_Failed)
       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
-                       << AllocType
-                       << ConstructorArgs.get()[0]->getType()
-                       << TypeRange
-                       << ConstructorArgs.get()[0]->getSourceRange());
+                       << AllocType << Deduce->getType()
+                       << TypeRange << Deduce->getSourceRange());
     if (!DeducedType)
       return ExprError();
=20
     AllocTypeInfo =3D DeducedType;
     AllocType =3D AllocTypeInfo->getType();
   }
- =20
+
   // Per C++0x [expr.new]p5, the type being constructed may be a
   // typedef of an array type.
   if (!ArraySize) {
@@ -945,8 +1095,14 @@
   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
     return ExprError();
=20
+  if (initStyle =3D=3D CXXNewExpr::ListInit && isStdInitializerList(AllocT=
ype, 0)) {
+    Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
+         diag::warn_dangling_std_initializer_list)
+        << /*at end of FE*/0 << Inits[0]->getSourceRange();
+  }
+
   // In ARC, infer 'retaining' for the allocated=20
-  if (getLangOptions().ObjCAutoRefCount &&
+  if (getLangOpts().ObjCAutoRefCount &&
       AllocType.getObjCLifetime() =3D=3D Qualifiers::OCL_None &&
       AllocType->isObjCLifetimeType()) {
     AllocType =3D Context.getLifetimeQualifiedType(AllocType,
@@ -955,53 +1111,73 @@
=20
   QualType ResultType =3D Context.getPointerType(AllocType);
    =20
-  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have in=
tegral
-  //   or enumeration type with a non-negative value."
+  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
+  //   integral or enumeration type with a non-negative value."
+  // C++11 [expr.new]p6: The expression [...] shall be of integral or unsc=
oped
+  //   enumeration type, or a class type for which a single non-explicit
+  //   conversion function to integral or unscoped enumeration type exists.
   if (ArraySize && !ArraySize->isTypeDependent()) {
-
-    QualType SizeType =3D ArraySize->getType();
-
-    ExprResult ConvertedSize
-      =3D ConvertToIntegralOrEnumerationType(StartLoc, ArraySize,
-                                       PDiag(diag::err_array_size_not_inte=
gral),
-                                     PDiag(diag::err_array_size_incomplete=
_type)
-                                       << ArraySize->getSourceRange(),
-                               PDiag(diag::err_array_size_explicit_convers=
ion),
-                                       PDiag(diag::note_array_size_convers=
ion),
-                               PDiag(diag::err_array_size_ambiguous_conver=
sion),
-                                       PDiag(diag::note_array_size_convers=
ion),
-                          PDiag(getLangOptions().CPlusPlus0x? 0
-                                            : diag::ext_array_size_convers=
ion));
+    ExprResult ConvertedSize =3D ConvertToIntegralOrEnumerationType(
+      StartLoc, ArraySize,
+      PDiag(diag::err_array_size_not_integral) << getLangOpts().CPlusPlus0=
x,
+      PDiag(diag::err_array_size_incomplete_type)
+        << ArraySize->getSourceRange(),
+      PDiag(diag::err_array_size_explicit_conversion),
+      PDiag(diag::note_array_size_conversion),
+      PDiag(diag::err_array_size_ambiguous_conversion),
+      PDiag(diag::note_array_size_conversion),
+      PDiag(getLangOpts().CPlusPlus0x ?
+              diag::warn_cxx98_compat_array_size_conversion :
+              diag::ext_array_size_conversion),
+      /*AllowScopedEnumerations*/ false);
     if (ConvertedSize.isInvalid())
       return ExprError();
=20
     ArraySize =3D ConvertedSize.take();
-    SizeType =3D ArraySize->getType();
+    QualType SizeType =3D ArraySize->getType();
     if (!SizeType->isIntegralOrUnscopedEnumerationType())
       return ExprError();
=20
-    // Let's see if this is a constant < 0. If so, we reject it out of han=
d.
-    // We don't care about special rules, so we tell the machinery it's not
-    // evaluated - it gives us a result in more cases.
+    // C++98 [expr.new]p7:
+    //   The expression in a direct-new-declarator shall have integral type
+    //   with a non-negative value.
+    //
+    // Let's see if this is a constant < 0. If so, we reject it out of
+    // hand. Otherwise, if it's not a constant, we must have an unparenthe=
sized
+    // array type.
+    //
+    // Note: such a construct has well-defined semantics in C++11: it thro=
ws
+    // std::bad_array_new_length.
     if (!ArraySize->isValueDependent()) {
       llvm::APSInt Value;
-      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
+      // We've already performed any required implicit conversion to integ=
er or
+      // unscoped enumeration type.
+      if (ArraySize->isIntegerConstantExpr(Value, Context)) {
         if (Value < llvm::APSInt(
                         llvm::APInt::getNullValue(Value.getBitWidth()),
-                                 Value.isUnsigned()))
-          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
-                                diag::err_typecheck_negative_array_size)
-            << ArraySize->getSourceRange());
-
-        if (!AllocType->isDependentType()) {
-          unsigned ActiveSizeBits
-            =3D ConstantArrayType::getNumAddressingBits(Context, AllocType=
, Value);
+                                 Value.isUnsigned())) {
+          if (getLangOpts().CPlusPlus0x)
+            Diag(ArraySize->getLocStart(),
+                 diag::warn_typecheck_negative_array_new_size)
+              << ArraySize->getSourceRange();
+          else
+            return ExprError(Diag(ArraySize->getLocStart(),
+                                  diag::err_typecheck_negative_array_size)
+                             << ArraySize->getSourceRange());
+        } else if (!AllocType->isDependentType()) {
+          unsigned ActiveSizeBits =3D
+            ConstantArrayType::getNumAddressingBits(Context, AllocType, Va=
lue);
           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))=
 {
-            Diag(ArraySize->getSourceRange().getBegin(),
-                 diag::err_array_too_large)
-              << Value.toString(10)
-              << ArraySize->getSourceRange();
-            return ExprError();
+            if (getLangOpts().CPlusPlus0x)
+              Diag(ArraySize->getLocStart(),
+                   diag::warn_array_new_too_large)
+                << Value.toString(10)
+                << ArraySize->getSourceRange();
+            else
+              return ExprError(Diag(ArraySize->getLocStart(),
+                                    diag::err_array_too_large)
+                               << Value.toString(10)
+                               << ArraySize->getSourceRange());
           }
         }
       } else if (TypeIdParens.isValid()) {
@@ -1016,7 +1192,7 @@
     }
=20
     // ARC: warn about ABI issues.
-    if (getLangOptions().ObjCAutoRefCount) {
+    if (getLangOpts().ObjCAutoRefCount) {
       QualType BaseAllocType =3D Context.getBaseElementType(AllocType);
       if (BaseAllocType.hasStrongOrWeakObjCLifetime())
         Diag(StartLoc, diag::warn_err_new_delete_object_array)
@@ -1033,7 +1209,8 @@
   unsigned NumPlaceArgs =3D PlacementArgs.size();
=20
   if (!AllocType->isDependentType() &&
-      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
+      !Expr::hasAnyTypeDependentArguments(
+        llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
       FindAllocationFunctions(StartLoc,
                               SourceRange(PlacementLParen, PlacementRParen=
),
                               UseGlobal, AllocType, ArraySize, PlaceArgs,
@@ -1063,114 +1240,123 @@
     NumPlaceArgs =3D AllPlaceArgs.size();
     if (NumPlaceArgs > 0)
       PlaceArgs =3D &AllPlaceArgs[0];
+
+    DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
+                          PlaceArgs, NumPlaceArgs);
+
+    // FIXME: Missing call to CheckFunctionCall or equivalent
   }
=20
-  bool Init =3D ConstructorLParen.isValid();
-  // --- Choosing a constructor ---
-  CXXConstructorDecl *Constructor =3D 0;
-  bool HadMultipleCandidates =3D false;
-  Expr **ConsArgs =3D (Expr**)ConstructorArgs.get();
-  unsigned NumConsArgs =3D ConstructorArgs.size();
-  ASTOwningVector<Expr*> ConvertedConstructorArgs(*this);
-
-  // Array 'new' can't have any initializers.
-  if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) {
-    SourceRange InitRange(ConsArgs[0]->getLocStart(),
-                          ConsArgs[NumConsArgs - 1]->getLocEnd());
-
-    Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
-    return ExprError();
+  // Warn if the type is over-aligned and is being allocated by global ope=
rator
+  // new.
+  if (NumPlaceArgs =3D=3D 0 && OperatorNew &&=20
+      (OperatorNew->isImplicit() ||
+       getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
+    if (unsigned Align =3D Context.getPreferredTypeAlign(AllocType.getType=
Ptr())){
+      unsigned SuitableAlign =3D Context.getTargetInfo().getSuitableAlign(=
);
+      if (Align > SuitableAlign)
+        Diag(StartLoc, diag::warn_overaligned_type)
+            << AllocType
+            << unsigned(Align / Context.getCharWidth())
+            << unsigned(SuitableAlign / Context.getCharWidth());
+    }
   }
=20
+  QualType InitType =3D AllocType;
+  // Array 'new' can't have any initializers except empty parentheses.
+  // Initializer lists are also allowed, in C++11. Rely on the parser for =
the
+  // dialect distinction.
+  if (ResultType->isArrayType() || ArraySize) {
+    if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
+      SourceRange InitRange(Inits[0]->getLocStart(),
+                            Inits[NumInits - 1]->getLocEnd());
+      Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
+      return ExprError();
+    }
+    if (InitListExpr *ILE =3D dyn_cast_or_null<InitListExpr>(Initializer))=
 {
+      // We do the initialization typechecking against the array type
+      // corresponding to the number of initializers + 1 (to also check
+      // default-initialization).
+      unsigned NumElements =3D ILE->getNumInits() + 1;
+      InitType =3D Context.getConstantArrayType(AllocType,
+          llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumEleme=
nts),
+                                              ArrayType::Normal, 0);
+    }
+  }
+
   if (!AllocType->isDependentType() &&
-      !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) {
-    // C++0x [expr.new]p15:
+      !Expr::hasAnyTypeDependentArguments(
+        llvm::makeArrayRef(Inits, NumInits))) {
+    // C++11 [expr.new]p15:
     //   A new-expression that creates an object of type T initializes that
     //   object as follows:
     InitializationKind Kind
     //     - If the new-initializer is omitted, the object is default-
     //       initialized (8.5); if no initialization is performed,
     //       the object has indeterminate value
-      =3D !Init? InitializationKind::CreateDefault(TypeRange.getBegin())
+      =3D initStyle =3D=3D CXXNewExpr::NoInit
+          ? InitializationKind::CreateDefault(TypeRange.getBegin())
     //     - Otherwise, the new-initializer is interpreted according to the
     //       initialization rules of 8.5 for direct-initialization.
-             : InitializationKind::CreateDirect(TypeRange.getBegin(),
-                                                ConstructorLParen,
-                                                ConstructorRParen);
+          : initStyle =3D=3D CXXNewExpr::ListInit
+              ? InitializationKind::CreateDirectList(TypeRange.getBegin())
+              : InitializationKind::CreateDirect(TypeRange.getBegin(),
+                                                 DirectInitRange.getBegin(=
),
+                                                 DirectInitRange.getEnd());
=20
     InitializedEntity Entity
-      =3D InitializedEntity::InitializeNew(StartLoc, AllocType);
-    InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsA=
rgs);
+      =3D InitializedEntity::InitializeNew(StartLoc, InitType);
+    InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
     ExprResult FullInit =3D InitSeq.Perform(*this, Entity, Kind,
-                                                move(ConstructorArgs));
+                                          MultiExprArg(Inits, NumInits));
     if (FullInit.isInvalid())
       return ExprError();
=20
-    // FullInit is our initializer; walk through it to determine if it's a
-    // constructor call, which CXXNewExpr handles directly.
-    if (Expr *FullInitExpr =3D (Expr *)FullInit.get()) {
-      if (CXXBindTemporaryExpr *Binder
-            =3D dyn_cast<CXXBindTemporaryExpr>(FullInitExpr))
-        FullInitExpr =3D Binder->getSubExpr();
-      if (CXXConstructExpr *Construct
-                    =3D dyn_cast<CXXConstructExpr>(FullInitExpr)) {
-        Constructor =3D Construct->getConstructor();
-        HadMultipleCandidates =3D Construct->hadMultipleCandidates();
-        for (CXXConstructExpr::arg_iterator A =3D Construct->arg_begin(),
-                                         AEnd =3D Construct->arg_end();
-             A !=3D AEnd; ++A)
-          ConvertedConstructorArgs.push_back(*A);
-      } else {
-        // Take the converted initializer.
-        ConvertedConstructorArgs.push_back(FullInit.release());
-      }
-    } else {
-      // No initialization required.
-    }
-
-    // Take the converted arguments and use them for the new expression.
-    NumConsArgs =3D ConvertedConstructorArgs.size();
-    ConsArgs =3D (Expr **)ConvertedConstructorArgs.take();
+    // FullInit is our initializer; strip off CXXBindTemporaryExprs, becau=
se
+    // we don't want the initialized object to be destructed.
+    if (CXXBindTemporaryExpr *Binder =3D
+            dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
+      FullInit =3D Owned(Binder->getSubExpr());
+
+    Initializer =3D FullInit.take();
   }
=20
   // Mark the new and delete operators as referenced.
   if (OperatorNew)
-    MarkDeclarationReferenced(StartLoc, OperatorNew);
+    MarkFunctionReferenced(StartLoc, OperatorNew);
   if (OperatorDelete)
-    MarkDeclarationReferenced(StartLoc, OperatorDelete);
+    MarkFunctionReferenced(StartLoc, OperatorDelete);
=20
   // C++0x [expr.new]p17:
   //   If the new expression creates an array of objects of class type,
   //   access and ambiguity control are done for the destructor.
-  if (ArraySize && Constructor) {
-    if (CXXDestructorDecl *dtor =3D LookupDestructor(Constructor->getParen=
t())) {
-      MarkDeclarationReferenced(StartLoc, dtor);
-      CheckDestructorAccess(StartLoc, dtor,=20
-                            PDiag(diag::err_access_dtor)
-                              << Context.getBaseElementType(AllocType));
+  QualType BaseAllocType =3D Context.getBaseElementType(AllocType);
+  if (ArraySize && !BaseAllocType->isDependentType()) {
+    if (const RecordType *BaseRecordType =3D BaseAllocType->getAs<RecordTy=
pe>()) {
+      if (CXXDestructorDecl *dtor =3D LookupDestructor(
+              cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
+        MarkFunctionReferenced(StartLoc, dtor);
+        CheckDestructorAccess(StartLoc, dtor,=20
+                              PDiag(diag::err_access_dtor)
+                                << BaseAllocType);
+        DiagnoseUseOfDecl(dtor, StartLoc);
+      }
     }
   }
=20
   PlacementArgs.release();
-  ConstructorArgs.release();
=20
   return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
-                                        PlaceArgs, NumPlaceArgs, TypeIdPar=
ens,
-                                        ArraySize, Constructor, Init,
-                                        ConsArgs, NumConsArgs,
-                                        HadMultipleCandidates,
                                         OperatorDelete,
                                         UsualArrayDeleteWantsSize,
+                                        PlaceArgs, NumPlaceArgs, TypeIdPar=
ens,
+                                        ArraySize, initStyle, Initializer,
                                         ResultType, AllocTypeInfo,
-                                        StartLoc,
-                                        Init ? ConstructorRParen :
-                                               TypeRange.getEnd(),
-                                        ConstructorLParen, ConstructorRPar=
en));
+                                        StartLoc, DirectInitRange));
 }
=20
-/// CheckAllocatedType - Checks that a type is suitable as the allocated t=
ype
+/// \brief Checks that a type is suitable as the allocated type
 /// in a new-expression.
-/// dimension off and stores the size expression in ArraySize.
 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
                               SourceRange R) {
   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
@@ -1195,7 +1381,7 @@
   else if (unsigned AddressSpace =3D AllocType.getAddressSpace())
     return Diag(Loc, diag::err_address_space_qualified_new)
       << AllocType.getUnqualifiedType() << AddressSpace;
-  else if (getLangOptions().ObjCAutoRefCount) {
+  else if (getLangOpts().ObjCAutoRefCount) {
     if (const ArrayType *AT =3D Context.getAsArrayType(AllocType)) {
       QualType BaseAllocType =3D Context.getBaseElementType(AT);
       if (BaseAllocType.getObjCLifetime() =3D=3D Qualifiers::OCL_None &&
@@ -1283,7 +1469,7 @@
=20
   // We don't need an operator delete if we're running under
   // -fno-exceptions.
-  if (!getLangOptions().Exceptions) {
+  if (!getLangOpts().Exceptions) {
     OperatorDelete =3D 0;
     return false;
   }
@@ -1401,7 +1587,7 @@
     //   as a placement deallocation function, would have been
     //   selected as a match for the allocation function, the program
     //   is ill-formed.
-    if (NumPlaceArgs && getLangOptions().CPlusPlus0x &&
+    if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
         isNonPlacementDeallocationFunction(OperatorDelete)) {
       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
         << SourceRange(PlaceArgs[0]->getLocStart(),
@@ -1447,14 +1633,16 @@
=20
     if (FunctionTemplateDecl *FnTemplate =3D dyn_cast<FunctionTemplateDecl=
>(D)) {
       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
-                                   /*ExplicitTemplateArgs=3D*/0, Args, Num=
Args,
+                                   /*ExplicitTemplateArgs=3D*/0,
+                                   llvm::makeArrayRef(Args, NumArgs),
                                    Candidates,
                                    /*SuppressUserConversions=3D*/false);
       continue;
     }
=20
     FunctionDecl *Fn =3D cast<FunctionDecl>(D);
-    AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates,
+    AddOverloadCandidate(Fn, Alloc.getPair(),
+                         llvm::makeArrayRef(Args, NumArgs), Candidates,
                          /*SuppressUserConversions=3D*/false);
   }
=20
@@ -1464,7 +1652,7 @@
   case OR_Success: {
     // Got one!
     FunctionDecl *FnDecl =3D Best->Function;
-    MarkDeclarationReferenced(StartLoc, FnDecl);
+    MarkFunctionReferenced(StartLoc, FnDecl);
     // The first argument is size_t, and the first parameter must be size_=
t,
     // too. This is checked on declaration and can be assumed. (It can't be
     // asserted on, though, since invalid decls are left in there.)
@@ -1484,9 +1672,13 @@
=20
       Args[i] =3D Result.takeAs<Expr>();
     }
+
     Operator =3D FnDecl;
-    CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->Found=
Decl,
-                          Diagnose);
+
+    if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
+                              Best->FoundDecl, Diagnose) =3D=3D AR_inacces=
sible)
+      return true;
+
     return false;
   }
=20
@@ -1494,7 +1686,8 @@
     if (Diagnose) {
       Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
         << Name << Range;
-      Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+      Candidates.NoteCandidates(*this, OCD_AllCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     }
     return true;
=20
@@ -1502,7 +1695,8 @@
     if (Diagnose) {
       Diag(StartLoc, diag::err_ovl_ambiguous_call)
         << Name << Range;
-      Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs=
);
+      Candidates.NoteCandidates(*this, OCD_ViableCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     }
     return true;
=20
@@ -1513,7 +1707,8 @@
         << Name=20
         << getDeletedOrUnavailableSuffix(Best->Function)
         << Range;
-      Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+      Candidates.NoteCandidates(*this, OCD_AllCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     }
     return true;
   }
@@ -1568,7 +1763,7 @@
   // lookup.
   // Note that the C++0x versions of operator delete are deallocation func=
tions,
   // and thus are implicitly noexcept.
-  if (!StdBadAlloc && !getLangOptions().CPlusPlus0x) {
+  if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
     // The "std::bad_alloc" class has not yet been declared, so build it
     // implicitly.
     StdBadAlloc =3D CXXRecordDecl::Create(Context, TTK_Class,
@@ -1583,7 +1778,7 @@
=20
   QualType VoidPtr =3D Context.getPointerType(Context.VoidTy);
   QualType SizeT =3D Context.getSizeType();
-  bool AssumeSaneOperatorNew =3D getLangOptions().AssumeSaneOperatorNew;
+  bool AssumeSaneOperatorNew =3D getLangOpts().AssumeSaneOperatorNew;
=20
   DeclareGlobalAllocationFunction(
       Context.DeclarationNames.getCXXOperatorName(OO_New),
@@ -1631,20 +1826,20 @@
   bool HasBadAllocExceptionSpec
     =3D (Name.getCXXOverloadedOperator() =3D=3D OO_New ||
        Name.getCXXOverloadedOperator() =3D=3D OO_Array_New);
-  if (HasBadAllocExceptionSpec && !getLangOptions().CPlusPlus0x) {
+  if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
     assert(StdBadAlloc && "Must have std::bad_alloc declared");
     BadAllocType =3D Context.getTypeDeclType(getStdBadAlloc());
   }
=20
   FunctionProtoType::ExtProtoInfo EPI;
   if (HasBadAllocExceptionSpec) {
-    if (!getLangOptions().CPlusPlus0x) {
+    if (!getLangOpts().CPlusPlus0x) {
       EPI.ExceptionSpecType =3D EST_Dynamic;
       EPI.NumExceptions =3D 1;
       EPI.Exceptions =3D &BadAllocType;
     }
   } else {
-    EPI.ExceptionSpecType =3D getLangOptions().CPlusPlus0x ?
+    EPI.ExceptionSpecType =3D getLangOpts().CPlusPlus0x ?
                                 EST_BasicNoexcept : EST_DynamicNone;
   }
=20
@@ -1704,13 +1899,15 @@
     if (Operator->isDeleted()) {
       if (Diagnose) {
         Diag(StartLoc, diag::err_deleted_function_use);
-        Diag(Operator->getLocation(), diag::note_unavailable_here) << true;
+        NoteDeletedFunction(Operator);
       }
       return true;
     }
=20
-    CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
-                          Matches[0], Diagnose);
+    if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClas=
s(),
+                              Matches[0], Diagnose) =3D=3D AR_inaccessible)
+      return true;
+
     return false;
=20
   // We found multiple suitable operators;  complain about the ambiguity.
@@ -1777,6 +1974,9 @@
   bool UsualArrayDeleteWantsSize =3D false;
=20
   if (!Ex.get()->isTypeDependent()) {
+    // Perform lvalue-to-rvalue cast, if needed.
+    Ex =3D DefaultLvalueConversion(Ex.take());
+
     QualType Type =3D Ex.get()->getType();
=20
     if (const RecordType *Record =3D Type->getAs<RecordType>()) {
@@ -1864,8 +2064,8 @@
     //   (5.2.11) of the pointer expression before it is used as the opera=
nd
     //   of the delete-expression. ]
     if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
-      Ex =3D Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy, CK=
_NoOp,
-                                          Ex.take(), 0, VK_RValue));
+      Ex =3D Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
+                                          CK_BitCast, Ex.take(), 0, VK_RVa=
lue));
=20
     if (Pointee->isArrayType() && !ArrayForm) {
       Diag(StartLoc, diag::warn_delete_array_type)
@@ -1898,9 +2098,9 @@
           UsualArrayDeleteWantsSize =3D (OperatorDelete->getNumParams() =
=3D=3D 2);
       }
=20
-      if (!PointeeRD->hasTrivialDestructor())
+      if (!PointeeRD->hasIrrelevantDestructor())
         if (CXXDestructorDecl *Dtor =3D LookupDestructor(PointeeRD)) {
-          MarkDeclarationReferenced(StartLoc,
+          MarkFunctionReferenced(StartLoc,
                                     const_cast<CXXDestructorDecl*>(Dtor));
           DiagnoseUseOfDecl(Dtor, StartLoc);
         }
@@ -1929,7 +2129,7 @@
         }
       }
=20
-    } else if (getLangOptions().ObjCAutoRefCount &&
+    } else if (getLangOpts().ObjCAutoRefCount &&
                PointeeElem->isObjCLifetimeType() &&
                (PointeeElem.getObjCLifetime() =3D=3D Qualifiers::OCL_Stron=
g ||
                 PointeeElem.getObjCLifetime() =3D=3D Qualifiers::OCL_Weak)=
 &&
@@ -1949,7 +2149,7 @@
         return ExprError();
     }
=20
-    MarkDeclarationReferenced(StartLoc, OperatorDelete);
+    MarkFunctionReferenced(StartLoc, OperatorDelete);
    =20
     // Check access and ambiguity of operator delete and destructor.
     if (PointeeRD) {
@@ -1986,11 +2186,16 @@
                      << ConditionVar->getSourceRange());
=20
   ExprResult Condition =3D
-    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),=20
-                                        ConditionVar,
-                                        ConditionVar->getLocation(),
-                            ConditionVar->getType().getNonReferenceType(),
+    Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
+                              SourceLocation(),
+                              ConditionVar,
+                              /*enclosing*/ false,
+                              ConditionVar->getLocation(),
+                              ConditionVar->getType().getNonReferenceType(=
),
                               VK_LValue));
+
+  MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
+
   if (ConvertToBoolean) {
     Condition =3D CheckBooleanCondition(Condition.take(), StmtLoc);
     if (Condition.isInvalid())
@@ -2071,8 +2276,9 @@
                                   CastLoc, ConstructorArgs))
       return ExprError();
=20
-    S.CheckConstructorAccess(CastLoc, Constructor, Constructor->getAccess(=
),
-                             S.PDiag(diag::err_access_ctor));
+    S.CheckConstructorAccess(CastLoc, Constructor,
+                             InitializedEntity::InitializeTemporary(Ty),
+                             Constructor->getAccess());
    =20
     ExprResult Result
       =3D S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Me=
thod),
@@ -2089,10 +2295,17 @@
     assert(!From->getType()->isPointerType() && "Arg can't have pointer ty=
pe!");
=20
     // Create an implicit call expr that calls it.
-    ExprResult Result =3D S.BuildCXXMemberCallExpr(From, FoundDecl, Method,
+    CXXConversionDecl *Conv =3D cast<CXXConversionDecl>(Method);
+    ExprResult Result =3D S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
                                                  HadMultipleCandidates);
     if (Result.isInvalid())
       return ExprError();
+    // Record usage of conversion in an implicit cast.
+    Result =3D S.Owned(ImplicitCastExpr::Create(S.Context,
+                                              Result.get()->getType(),
+                                              CK_UserDefinedConversion,
+                                              Result.get(), 0,
+                                              Result.get()->getValueKind()=
));
=20
     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
=20
@@ -2126,6 +2339,7 @@
       FunctionDecl *FD =3D ICS.UserDefined.ConversionFunction;
       CastKind CastKind;
       QualType BeforeToType;
+      assert(FD && "FIXME: aggregate initialization from init list");
       if (const CXXConversionDecl *Conv =3D dyn_cast<CXXConversionDecl>(FD=
)) {
         CastKind =3D CK_UserDefinedConversion;
=20
@@ -2243,7 +2457,7 @@
     if (!Fn)
       return ExprError();
=20
-    if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
+    if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
       return ExprError();
=20
     From =3D FixOverloadedFunctionReference(From, Found, Fn);
@@ -2256,20 +2470,14 @@
     // Nothing to do.
     break;
=20
-  case ICK_Lvalue_To_Rvalue:
-    // Should this get its own ICK?
-    if (From->getObjectKind() =3D=3D OK_ObjCProperty) {
-      ExprResult FromRes =3D ConvertPropertyForRValue(From);
-      if (FromRes.isInvalid())
-        return ExprError();
-      From =3D FromRes.take();
-      if (!From->isGLValue()) break;
-    }
-
+  case ICK_Lvalue_To_Rvalue: {
+    assert(From->getObjectKind() !=3D OK_ObjCProperty);
     FromType =3D FromType.getUnqualifiedType();
-    From =3D ImplicitCastExpr::Create(Context, FromType, CK_LValueToRValue,
-                                    From, 0, VK_RValue);
+    ExprResult FromRes =3D DefaultLvalueConversion(From);
+    assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
+    From =3D FromRes.take();
     break;
+  }
=20
   case ICK_Array_To_Pointer:
     FromType =3D Context.getArrayDecayedType(FromType);
@@ -2358,12 +2566,12 @@
     if (SCS.IncompatibleObjC && Action !=3D AA_Casting) {
       // Diagnose incompatible Objective-C conversions
       if (Action =3D=3D AA_Initializing || Action =3D=3D AA_Assigning)
-        Diag(From->getSourceRange().getBegin(),
+        Diag(From->getLocStart(),
              diag::ext_typecheck_convert_incompatible_pointer)
           << ToType << From->getType() << Action
           << From->getSourceRange() << 0;
       else
-        Diag(From->getSourceRange().getBegin(),
+        Diag(From->getLocStart(),
              diag::ext_typecheck_convert_incompatible_pointer)
           << From->getType() << ToType << Action
           << From->getSourceRange() << 0;
@@ -2372,14 +2580,14 @@
           ToType->isObjCObjectPointerType())
         EmitRelatedResultTypeNote(From);
     }=20
-    else if (getLangOptions().ObjCAutoRefCount &&
+    else if (getLangOpts().ObjCAutoRefCount &&
              !CheckObjCARCUnavailableWeakConversion(ToType,=20
                                                     From->getType())) {
       if (Action =3D=3D AA_Initializing)
-        Diag(From->getSourceRange().getBegin(),=20
+        Diag(From->getLocStart(),=20
              diag::err_arc_weak_unavailable_assign);
       else
-        Diag(From->getSourceRange().getBegin(),
+        Diag(From->getLocStart(),
              diag::err_arc_convesion_of_weak_unavailable)=20
           << (Action =3D=3D AA_Casting) << From->getType() << ToType=20
           << From->getSourceRange();
@@ -2546,7 +2754,7 @@
                              CK_NoOp, VK, /*BasePath=3D*/0, CCK).take();
=20
     if (SCS.DeprecatedStringLiteralToCharPtr &&
-        !getLangOptions().WritableStrings)
+        !getLangOpts().WritableStrings)
       Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conve=
rsion)
         << ToType.getNonReferenceType();
=20
@@ -2557,6 +2765,13 @@
     llvm_unreachable("Improper third standard conversion");
   }
=20
+  // If this conversion sequence involved a scalar -> atomic conversion, p=
erform
+  // that conversion now.
+  if (const AtomicType *ToAtomic =3D ToType->getAs<AtomicType>())
+    if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
+      From =3D ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RV=
alue, 0,
+                               CCK).take();
+     =20
   return Owned(From);
 }
=20
@@ -2645,6 +2860,9 @@
   case UTT_IsAbstract:
     // Fall-through
=20
+  // These traits require a complete type.
+  case UTT_IsFinal:
+
     // These trait expressions are designed to help implement predicates in
     // [meta.unary.prop] despite not being named the same. They are specif=
ied
     // by both GCC and the Embarcadero C++ compiler, and require the compl=
ete
@@ -2770,6 +2988,10 @@
     if (const CXXRecordDecl *RD =3D T->getAsCXXRecordDecl())
       return RD->isAbstract();
     return false;
+  case UTT_IsFinal:
+    if (const CXXRecordDecl *RD =3D T->getAsCXXRecordDecl())
+      return RD->hasAttr<FinalAttr>();
+    return false;
   case UTT_IsSigned:
     return T->isSignedIntegerType();
   case UTT_IsUnsigned:
@@ -3020,6 +3242,126 @@
   return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
 }
=20
+static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLo=
c,
+                              ArrayRef<TypeSourceInfo *> Args,
+                              SourceLocation RParenLoc) {
+  switch (Kind) {
+  case clang::TT_IsTriviallyConstructible: {
+    // C++11 [meta.unary.prop]:
+    //   is_trivially_constructible is defined as:
+    //
+    //     is_constructible<T, Args...>::value is true and the variable
+    //     definition for is_constructible, as defined below, is known to =
call no
+    //     operation that is not trivial.
+    //
+    //   The predicate condition for a template specialization=20
+    //   is_constructible<T, Args...> shall be satisfied if and only if th=
e=20
+    //   following variable definition would be well-formed for some inven=
ted=20
+    //   variable t:
+    //
+    //     T t(create<Args>()...);
+    if (Args.empty()) {
+      S.Diag(KWLoc, diag::err_type_trait_arity)
+        << 1 << 1 << 1 << (int)Args.size();
+      return false;
+    }
+   =20
+    bool SawVoid =3D false;
+    for (unsigned I =3D 0, N =3D Args.size(); I !=3D N; ++I) {
+      if (Args[I]->getType()->isVoidType()) {
+        SawVoid =3D true;
+        continue;
+      }
+     =20
+      if (!Args[I]->getType()->isIncompleteType() &&
+        S.RequireCompleteType(KWLoc, Args[I]->getType(),=20
+          diag::err_incomplete_type_used_in_type_trait_expr))
+        return false;
+    }
+   =20
+    // If any argument was 'void', of course it won't type-check.
+    if (SawVoid)
+      return false;
+   =20
+    llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
+    llvm::SmallVector<Expr *, 2> ArgExprs;
+    ArgExprs.reserve(Args.size() - 1);
+    for (unsigned I =3D 1, N =3D Args.size(); I !=3D N; ++I) {
+      QualType T =3D Args[I]->getType();
+      if (T->isObjectType() || T->isFunctionType())
+        T =3D S.Context.getRValueReferenceType(T);
+      OpaqueArgExprs.push_back(
+        OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),=20
+                        T.getNonLValueExprType(S.Context),
+                        Expr::getValueKindForType(T)));
+      ArgExprs.push_back(&OpaqueArgExprs.back());
+    }
+   =20
+    // Perform the initialization in an unevaluated context within a SFINA=
E=20
+    // trap at translation unit scope.
+    EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
+    Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=3D*/true);
+    Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
+    InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
+    InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KW=
Loc,
+                                                                 RParenLoc=
));
+    InitializationSequence Init(S, To, InitKind,=20
+                                ArgExprs.begin(), ArgExprs.size());
+    if (Init.Failed())
+      return false;
+   =20
+    ExprResult Result =3D Init.Perform(S, To, InitKind,=20
+                                     MultiExprArg(ArgExprs.data(),=20
+                                                  ArgExprs.size()));
+    if (Result.isInvalid() || SFINAE.hasErrorOccurred())
+      return false;
+   =20
+    // The initialization succeeded; not make sure there are no non-trivia=
l=20
+    // calls.
+    return !Result.get()->hasNonTrivialCall(S.Context);
+  }
+  }
+ =20
+  return false;
+}
+
+ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,=20
+                                ArrayRef<TypeSourceInfo *> Args,=20
+                                SourceLocation RParenLoc) {
+  bool Dependent =3D false;
+  for (unsigned I =3D 0, N =3D Args.size(); I !=3D N; ++I) {
+    if (Args[I]->getType()->isDependentType()) {
+      Dependent =3D true;
+      break;
+    }
+  }
+ =20
+  bool Value =3D false;
+  if (!Dependent)
+    Value =3D evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
+ =20
+  return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
+                               Args, RParenLoc, Value);
+}
+
+ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,=20
+                                ArrayRef<ParsedType> Args,=20
+                                SourceLocation RParenLoc) {
+  llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
+  ConvertedArgs.reserve(Args.size());
+ =20
+  for (unsigned I =3D 0, N =3D Args.size(); I !=3D N; ++I) {
+    TypeSourceInfo *TInfo;
+    QualType T =3D GetTypeFromParser(Args[I], &TInfo);
+    if (!TInfo)
+      TInfo =3D Context.getTrivialTypeSourceInfo(T, KWLoc);
+   =20
+    ConvertedArgs.push_back(TInfo);   =20
+  }
+ =20
+  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
+}
+
 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
                                     QualType LhsT, QualType RhsT,
                                     SourceLocation KeyLoc) {
@@ -3097,8 +3439,9 @@
     InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,=20
                                                            SourceLocation(=
)));
    =20
-    // Perform the initialization within a SFINAE trap at translation unit=20
-    // scope.
+    // Perform the initialization in an unevaluated context within a SFINA=
E=20
+    // trap at translation unit scope.
+    EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
     Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=3D*/true);
     Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl(=
));
     InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
@@ -3108,6 +3451,54 @@
     ExprResult Result =3D Init.Perform(Self, To, Kind, MultiExprArg(&FromP=
tr, 1));
     return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
   }
+     =20
+  case BTT_IsTriviallyAssignable: {
+    // C++11 [meta.unary.prop]p3:
+    //   is_trivially_assignable is defined as:
+    //     is_assignable<T, U>::value is true and the assignment, as defin=
ed by
+    //     is_assignable, is known to call no operation that is not trivial
+    //
+    //   is_assignable is defined as:
+    //     The expression declval<T>() =3D declval<U>() is well-formed whe=
n=20
+    //     treated as an unevaluated operand (Clause 5).
+    //
+    //   For both, T and U shall be complete types, (possibly cv-qualified=
)=20
+    //   void, or arrays of unknown bound.
+    if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
+        Self.RequireCompleteType(KeyLoc, LhsT,=20
+          diag::err_incomplete_type_used_in_type_trait_expr))
+      return false;
+    if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
+        Self.RequireCompleteType(KeyLoc, RhsT,=20
+          diag::err_incomplete_type_used_in_type_trait_expr))
+      return false;
+
+    // cv void is never assignable.
+    if (LhsT->isVoidType() || RhsT->isVoidType())
+      return false;
+
+    // Build expressions that emulate the effect of declval<T>() and=20
+    // declval<U>().
+    if (LhsT->isObjectType() || LhsT->isFunctionType())
+      LhsT =3D Self.Context.getRValueReferenceType(LhsT);
+    if (RhsT->isObjectType() || RhsT->isFunctionType())
+      RhsT =3D Self.Context.getRValueReferenceType(RhsT);
+    OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
+                        Expr::getValueKindForType(LhsT));
+    OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
+                        Expr::getValueKindForType(RhsT));
+   =20
+    // Attempt the assignment in an unevaluated context within a SFINAE=20
+    // trap at translation unit scope.
+    EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
+    Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=3D*/true);
+    Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl(=
));
+    ExprResult Result =3D Self.BuildBinOp(/*S=3D*/0, KeyLoc, BO_Assign, &L=
hs, &Rhs);
+    if (Result.isInvalid() || SFINAE.hasErrorOccurred())
+      return false;
+
+    return !Result.get()->hasNonTrivialCall(Self.Context);
+  }
   }
   llvm_unreachable("Unknown type trait or not implemented");
 }
@@ -3121,7 +3512,7 @@
   QualType RhsT =3D RhsTSInfo->getType();
=20
   if (BTT =3D=3D BTT_TypeCompatible) {
-    if (getLangOptions().CPlusPlus) {
+    if (getLangOpts().CPlusPlus) {
       Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
         << SourceRange(KWLoc, RParen);
       return ExprError();
@@ -3140,6 +3531,7 @@
   case BTT_IsSame:         ResultType =3D Context.BoolTy; break;
   case BTT_TypeCompatible: ResultType =3D Context.IntTy; break;
   case BTT_IsConvertibleTo: ResultType =3D Context.BoolTy; break;
+  case BTT_IsTriviallyAssignable: ResultType =3D Context.BoolTy;
   }
=20
   return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
@@ -3180,18 +3572,16 @@
   case ATT_ArrayExtent: {
     llvm::APSInt Value;
     uint64_t Dim;
-    if (DimExpr->isIntegerConstantExpr(Value, Self.Context, 0, false)) {
-      if (Value < llvm::APSInt(Value.getBitWidth(), Value.isUnsigned())) {
-        Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
-          DimExpr->getSourceRange();
-        return false;
-      }
-      Dim =3D Value.getLimitedValue();
-    } else {
-      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) <<
-        DimExpr->getSourceRange();
-      return false;
+    if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
+          Self.PDiag(diag::err_dimension_expr_not_constant_integer),
+          false).isInvalid())
+      return 0;
+    if (Value.isSigned() && Value.isNegative()) {
+      Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
+        << DimExpr->getSourceRange();
+      return 0;
     }
+    Dim =3D Value.getLimitedValue();
=20
     if (T->isArrayType()) {
       unsigned D =3D 0;
@@ -3540,7 +3930,7 @@
         break;
       RHS =3D move(RHSRes);
       if (Best->Function)
-        Self.MarkDeclarationReferenced(QuestionLoc, Best->Function);
+        Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
       return false;
     }
    =20
@@ -3832,7 +4222,7 @@
   if (NonStandardCompositeType)
     *NonStandardCompositeType =3D false;
=20
-  assert(getLangOptions().CPlusPlus && "This function assumes C++");
+  assert(getLangOpts().CPlusPlus && "This function assumes C++");
   QualType T1 =3D E1->getType(), T2 =3D E2->getType();
=20
   if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
@@ -4042,7 +4432,7 @@
=20
   // In ARC, calls that return a retainable type can return retained,
   // in which case we have to insert a consuming cast.
-  if (getLangOptions().ObjCAutoRefCount &&
+  if (getLangOpts().ObjCAutoRefCount &&
       E->getType()->isObjCRetainableType()) {
=20
     bool ReturnsRetained;
@@ -4077,6 +4467,12 @@
     } else if (isa<StmtExpr>(E)) {
       ReturnsRetained =3D true;
=20
+    // We hit this case with the lambda conversion-to-block optimization;
+    // we don't want any extra casts here.
+    } else if (isa<CastExpr>(E) &&
+               isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
+      return Owned(E);
+
     // For message sends and property references, we try to find an
     // actual method.  FIXME: we should infer retention by selector in
     // cases where we don't have an actual method.
@@ -4084,11 +4480,13 @@
       ObjCMethodDecl *D =3D 0;
       if (ObjCMessageExpr *Send =3D dyn_cast<ObjCMessageExpr>(E)) {
         D =3D Send->getMethodDecl();
-      } else {
-        CastExpr *CE =3D cast<CastExpr>(E);
-        assert(CE->getCastKind() =3D=3D CK_GetObjCProperty);
-        const ObjCPropertyRefExpr *PRE =3D CE->getSubExpr()->getObjCProper=
ty();
-        D =3D (PRE->isImplicitProperty() ? PRE->getImplicitPropertyGetter(=
) : 0);
+      } else if (ObjCNumericLiteral *NumLit =3D dyn_cast<ObjCNumericLitera=
l>(E)) {
+        D =3D NumLit->getObjCNumericLiteralMethod();
+      } else if (ObjCArrayLiteral *ArrayLit =3D dyn_cast<ObjCArrayLiteral>=
(E)) {
+        D =3D ArrayLit->getArrayWithObjectsMethod();
+      } else if (ObjCDictionaryLiteral *DictLit
+                                        =3D dyn_cast<ObjCDictionaryLiteral=
>(E)) {
+        D =3D DictLit->getDictWithObjectsMethod();
       }
=20
       ReturnsRetained =3D (D && D->hasAttr<NSReturnsRetainedAttr>());
@@ -4101,6 +4499,10 @@
         return Owned(E);
     }
=20
+    // Don't reclaim an object of Class type.
+    if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedTyp=
e())
+      return Owned(E);
+
     ExprNeedsCleanups =3D true;
=20
     CastKind ck =3D (ReturnsRetained ? CK_ARCConsumeObject
@@ -4109,51 +4511,60 @@
                                           VK_RValue));
   }
=20
-  if (!getLangOptions().CPlusPlus)
+  if (!getLangOpts().CPlusPlus)
     return Owned(E);
=20
-  const RecordType *RT =3D E->getType()->getAs<RecordType>();
-  if (!RT)
+  // Search for the base element type (cf. ASTContext::getBaseElementType)=
 with
+  // a fast path for the common case that the type is directly a RecordTyp=
e.
+  const Type *T =3D Context.getCanonicalType(E->getType().getTypePtr());
+  const RecordType *RT =3D 0;
+  while (!RT) {
+    switch (T->getTypeClass()) {
+    case Type::Record:
+      RT =3D cast<RecordType>(T);
+      break;
+    case Type::ConstantArray:
+    case Type::IncompleteArray:
+    case Type::VariableArray:
+    case Type::DependentSizedArray:
+      T =3D cast<ArrayType>(T)->getElementType().getTypePtr();
+      break;
+    default:
+      return Owned(E);
+    }
+  }
+
+  // That should be enough to guarantee that this type is complete, if we'=
re
+  // not processing a decltype expression.
+  CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RT->getDecl());
+  if (RD->isInvalidDecl() || RD->isDependentContext())
     return Owned(E);
=20
-  // That should be enough to guarantee that this type is complete.
-  // If it has a trivial destructor, we can avoid the extra copy.
-  CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RT->getDecl());
-  if (RD->isInvalidDecl() || RD->hasTrivialDestructor())
-    return Owned(E);
-
-  CXXDestructorDecl *Destructor =3D LookupDestructor(RD);
-
-  CXXTemporary *Temp =3D CXXTemporary::Create(Context, Destructor);
+  bool IsDecltype =3D ExprEvalContexts.back().IsDecltype;
+  CXXDestructorDecl *Destructor =3D IsDecltype ? 0 : LookupDestructor(RD);
+
   if (Destructor) {
-    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
+    MarkFunctionReferenced(E->getExprLoc(), Destructor);
     CheckDestructorAccess(E->getExprLoc(), Destructor,
                           PDiag(diag::err_access_dtor_temp)
                             << E->getType());
-
-    ExprTemporaries.push_back(Temp);
+    DiagnoseUseOfDecl(Destructor, E->getExprLoc());
+
+    // If destructor is trivial, we can avoid the extra copy.
+    if (Destructor->isTrivial())
+      return Owned(E);
+
+    // We need a cleanup, but we don't need to remember the temporary.
     ExprNeedsCleanups =3D true;
   }
-  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
-}
-
-Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
-  assert(SubExpr && "sub expression can't be null!");
-
-  unsigned FirstTemporary =3D ExprEvalContexts.back().NumTemporaries;
-  assert(ExprTemporaries.size() >=3D FirstTemporary);
-  assert(ExprNeedsCleanups || ExprTemporaries.size() =3D=3D FirstTemporary=
);
-  if (!ExprNeedsCleanups)
-    return SubExpr;
-
-  Expr *E =3D ExprWithCleanups::Create(Context, SubExpr,
-                                     ExprTemporaries.begin() + FirstTempor=
ary,
-                                     ExprTemporaries.size() - FirstTempora=
ry);
-  ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary,
-                        ExprTemporaries.end());
-  ExprNeedsCleanups =3D false;
-
-  return E;
+
+  CXXTemporary *Temp =3D CXXTemporary::Create(Context, Destructor);
+  CXXBindTemporaryExpr *Bind =3D CXXBindTemporaryExpr::Create(Context, Tem=
p, E);
+
+  if (IsDecltype)
+    ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
+
+  return Owned(Bind);
 }
=20
 ExprResult
@@ -4164,9 +4575,32 @@
   return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
 }
=20
+Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
+  assert(SubExpr && "sub expression can't be null!");
+
+  CleanupVarDeclMarking();
+
+  unsigned FirstCleanup =3D ExprEvalContexts.back().NumCleanupObjects;
+  assert(ExprCleanupObjects.size() >=3D FirstCleanup);
+  assert(ExprNeedsCleanups || ExprCleanupObjects.size() =3D=3D FirstCleanu=
p);
+  if (!ExprNeedsCleanups)
+    return SubExpr;
+
+  ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
+    =3D llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
+                         ExprCleanupObjects.size() - FirstCleanup);
+
+  Expr *E =3D ExprWithCleanups::Create(Context, SubExpr, Cleanups);
+  DiscardCleanupsInEvaluationContext();
+
+  return E;
+}
+
 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
   assert(SubStmt && "sub statement can't be null!");
=20
+  CleanupVarDeclMarking();
+
   if (!ExprNeedsCleanups)
     return SubStmt;
=20
@@ -4182,6 +4616,95 @@
   return MaybeCreateExprWithCleanups(E);
 }
=20
+/// Process the expression contained within a decltype. For such expressio=
ns,
+/// certain semantic checks on temporaries are delayed until this point, a=
nd
+/// are omitted for the 'topmost' call in the decltype expression. If the
+/// topmost call bound a temporary, strip that temporary off the expressio=
n.
+ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
+  ExpressionEvaluationContextRecord &Rec =3D ExprEvalContexts.back();
+  assert(Rec.IsDecltype && "not in a decltype expression");
+
+  // C++11 [expr.call]p11:
+  //   If a function call is a prvalue of object type,
+  // -- if the function call is either
+  //   -- the operand of a decltype-specifier, or
+  //   -- the right operand of a comma operator that is the operand of a
+  //      decltype-specifier,
+  //   a temporary object is not introduced for the prvalue.
+
+  // Recursively rebuild ParenExprs and comma expressions to strip out the
+  // outermost CXXBindTemporaryExpr, if any.
+  if (ParenExpr *PE =3D dyn_cast<ParenExpr>(E)) {
+    ExprResult SubExpr =3D ActOnDecltypeExpression(PE->getSubExpr());
+    if (SubExpr.isInvalid())
+      return ExprError();
+    if (SubExpr.get() =3D=3D PE->getSubExpr())
+      return Owned(E);
+    return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take()=
);
+  }
+  if (BinaryOperator *BO =3D dyn_cast<BinaryOperator>(E)) {
+    if (BO->getOpcode() =3D=3D BO_Comma) {
+      ExprResult RHS =3D ActOnDecltypeExpression(BO->getRHS());
+      if (RHS.isInvalid())
+        return ExprError();
+      if (RHS.get() =3D=3D BO->getRHS())
+        return Owned(E);
+      return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
+                                                BO_Comma, BO->getType(),
+                                                BO->getValueKind(),
+                                                BO->getObjectKind(),
+                                                BO->getOperatorLoc()));
+    }
+  }
+
+  CXXBindTemporaryExpr *TopBind =3D dyn_cast<CXXBindTemporaryExpr>(E);
+  if (TopBind)
+    E =3D TopBind->getSubExpr();
+
+  // Disable the special decltype handling now.
+  Rec.IsDecltype =3D false;
+
+  // Perform the semantic checks we delayed until this point.
+  CallExpr *TopCall =3D dyn_cast<CallExpr>(E);
+  for (unsigned I =3D 0, N =3D Rec.DelayedDecltypeCalls.size(); I !=3D N; =
++I) {
+    CallExpr *Call =3D Rec.DelayedDecltypeCalls[I];
+    if (Call =3D=3D TopCall)
+      continue;
+
+    if (CheckCallReturnType(Call->getCallReturnType(),
+                            Call->getLocStart(),
+                            Call, Call->getDirectCallee()))
+      return ExprError();
+  }
+
+  // Now all relevant types are complete, check the destructors are access=
ible
+  // and non-deleted, and annotate them on the temporaries.
+  for (unsigned I =3D 0, N =3D Rec.DelayedDecltypeBinds.size(); I !=3D N; =
++I) {
+    CXXBindTemporaryExpr *Bind =3D Rec.DelayedDecltypeBinds[I];
+    if (Bind =3D=3D TopBind)
+      continue;
+
+    CXXTemporary *Temp =3D Bind->getTemporary();
+
+    CXXRecordDecl *RD =3D
+      Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
+    CXXDestructorDecl *Destructor =3D LookupDestructor(RD);
+    Temp->setDestructor(Destructor);
+
+    MarkFunctionReferenced(E->getExprLoc(), Destructor);
+    CheckDestructorAccess(E->getExprLoc(), Destructor,
+                          PDiag(diag::err_access_dtor_temp)
+                            << E->getType());
+    DiagnoseUseOfDecl(Destructor, E->getExprLoc());
+
+    // We need a cleanup, but we don't need to remember the temporary.
+    ExprNeedsCleanups =3D true;
+  }
+
+  // Possibly strip off the top CXXBindTemporaryExpr.
+  return Owned(E);
+}
+
 ExprResult
 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation Op=
Loc,
                                    tok::TokenKind OpKind, ParsedType &Obje=
ctType,
@@ -4191,6 +4714,10 @@
   if (Result.isInvalid()) return ExprError();
   Base =3D Result.get();
=20
+  Result =3D CheckPlaceholderExpr(Base);
+  if (Result.isInvalid()) return ExprError();
+  Base =3D Result.take();
+
   QualType BaseType =3D Base->getType();
   MayBePseudoDestructor =3D false;
   if (BaseType->isDependentType()) {
@@ -4232,21 +4759,26 @@
       }
     }
=20
-    if (BaseType->isPointerType())
+    if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
       BaseType =3D BaseType->getPointeeType();
   }
=20
-  // We could end up with various non-record types here, such as extended
-  // vector types or Objective-C interfaces. Just return early and let
-  // ActOnMemberReferenceExpr do the work.
-  if (!BaseType->isRecordType()) {
-    // C++ [basic.lookup.classref]p2:
-    //   [...] If the type of the object expression is of pointer to scalar
-    //   type, the unqualified-id is looked up in the context of the compl=
ete
-    //   postfix-expression.
-    //
-    // This also indicates that we should be parsing a
-    // pseudo-destructor-name.
+  // Objective-C properties allow "." access on Objective-C pointer types,
+  // so adjust the base type to the object type itself.
+  if (BaseType->isObjCObjectPointerType())
+    BaseType =3D BaseType->getPointeeType();
+ =20
+  // C++ [basic.lookup.classref]p2:
+  //   [...] If the type of the object expression is of pointer to scalar
+  //   type, the unqualified-id is looked up in the context of the complete
+  //   postfix-expression.
+  //
+  // This also indicates that we could be parsing a pseudo-destructor-name.
+  // Note that Objective-C class and object types can be pseudo-destructor
+  // expressions or normal member (ivar or property) access expressions.
+  if (BaseType->isObjCObjectOrInterfaceType()) {
+    MayBePseudoDestructor =3D true;
+  } else if (!BaseType->isRecordType()) {
     ObjectType =3D ParsedType();
     MayBePseudoDestructor =3D true;
     return Owned(Base);
@@ -4281,6 +4813,39 @@
                        /*RPLoc*/ ExpectedLParenLoc);
 }
=20
+static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,=20
+                   tok::TokenKind& OpKind, SourceLocation OpLoc) {
+  if (Base->hasPlaceholderType()) {
+    ExprResult result =3D S.CheckPlaceholderExpr(Base);
+    if (result.isInvalid()) return true;
+    Base =3D result.take();
+  }
+  ObjectType =3D Base->getType();
+
+  // C++ [expr.pseudo]p2:
+  //   The left-hand side of the dot operator shall be of scalar type. The
+  //   left-hand side of the arrow operator shall be of pointer to scalar =
type.
+  //   This scalar type is the object type.
+  // Note that this is rather different from the normal handling for the
+  // arrow operator.
+  if (OpKind =3D=3D tok::arrow) {
+    if (const PointerType *Ptr =3D ObjectType->getAs<PointerType>()) {
+      ObjectType =3D Ptr->getPointeeType();
+    } else if (!Base->isTypeDependent()) {
+      // The user wrote "p->" when she probably meant "p."; fix it.
+      S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
+        << ObjectType << true
+        << FixItHint::CreateReplacement(OpLoc, ".");
+      if (S.isSFINAEContext())
+        return true;
+
+      OpKind =3D tok::period;
+    }
+  }
+
+  return false;
+}
+
 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
                                            SourceLocation OpLoc,
                                            tok::TokenKind OpKind,
@@ -4292,29 +4857,16 @@
                                            bool HasTrailingLParen) {
   TypeSourceInfo *DestructedTypeInfo =3D Destructed.getTypeSourceInfo();
=20
-  // C++ [expr.pseudo]p2:
-  //   The left-hand side of the dot operator shall be of scalar type. The
-  //   left-hand side of the arrow operator shall be of pointer to scalar =
type.
-  //   This scalar type is the object type.
-  QualType ObjectType =3D Base->getType();
-  if (OpKind =3D=3D tok::arrow) {
-    if (const PointerType *Ptr =3D ObjectType->getAs<PointerType>()) {
-      ObjectType =3D Ptr->getPointeeType();
-    } else if (!Base->isTypeDependent()) {
-      // The user wrote "p->" when she probably meant "p."; fix it.
-      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
-        << ObjectType << true
-        << FixItHint::CreateReplacement(OpLoc, ".");
-      if (isSFINAEContext())
-        return ExprError();
-
-      OpKind =3D tok::period;
-    }
-  }
+  QualType ObjectType;
+  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
+    return ExprError();
=20
   if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
-    Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
-      << ObjectType << Base->getSourceRange();
+    if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
+      Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
+    else
+      Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
+        << ObjectType << Base->getSourceRange();
     return ExprError();
   }
=20
@@ -4410,25 +4962,9 @@
           SecondTypeName.getKind() =3D=3D UnqualifiedId::IK_Identifier) &&
          "Invalid second type name in pseudo-destructor");
=20
-  // C++ [expr.pseudo]p2:
-  //   The left-hand side of the dot operator shall be of scalar type. The
-  //   left-hand side of the arrow operator shall be of pointer to scalar =
type.
-  //   This scalar type is the object type.
-  QualType ObjectType =3D Base->getType();
-  if (OpKind =3D=3D tok::arrow) {
-    if (const PointerType *Ptr =3D ObjectType->getAs<PointerType>()) {
-      ObjectType =3D Ptr->getPointeeType();
-    } else if (!ObjectType->isDependentType()) {
-      // The user wrote "p->" when she probably meant "p."; fix it.
-      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
-        << ObjectType << true
-        << FixItHint::CreateReplacement(OpLoc, ".");
-      if (isSFINAEContext())
-        return ExprError();
-
-      OpKind =3D tok::period;
-    }
-  }
+  QualType ObjectType;
+  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
+    return ExprError();
=20
   // Compute the object type that we should use for name lookup purposes. =
Only
   // record types and dependent types matter.
@@ -4476,6 +5012,7 @@
                                        TemplateId->getTemplateArgs(),
                                        TemplateId->NumArgs);
     TypeResult T =3D ActOnTemplateIdType(TemplateId->SS,
+                                       TemplateId->TemplateKWLoc,
                                        TemplateId->Template,
                                        TemplateId->TemplateNameLoc,
                                        TemplateId->LAngleLoc,
@@ -4525,6 +5062,7 @@
                                          TemplateId->getTemplateArgs(),
                                          TemplateId->NumArgs);
       TypeResult T =3D ActOnTemplateIdType(TemplateId->SS,
+                                         TemplateId->TemplateKWLoc,
                                          TemplateId->Template,
                                          TemplateId->TemplateNameLoc,
                                          TemplateId->LAngleLoc,
@@ -4548,9 +5086,60 @@
                                    Destructed, HasTrailingLParen);
 }
=20
+ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
+                                           SourceLocation OpLoc,
+                                           tok::TokenKind OpKind,
+                                           SourceLocation TildeLoc,=20
+                                           const DeclSpec& DS,
+                                           bool HasTrailingLParen) {
+  QualType ObjectType;
+  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
+    return ExprError();
+
+  QualType T =3D BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLo=
c());
+
+  TypeLocBuilder TLB;
+  DecltypeTypeLoc DecltypeTL =3D TLB.push<DecltypeTypeLoc>(T);
+  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
+  TypeSourceInfo *DestructedTypeInfo =3D TLB.getTypeSourceInfo(Context, T);
+  PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
+
+  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
+                                   0, SourceLocation(), TildeLoc,
+                                   Destructed, HasTrailingLParen);
+}
+
 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
-                                        CXXMethodDecl *Method,
+                                        CXXConversionDecl *Method,
                                         bool HadMultipleCandidates) {
+  if (Method->getParent()->isLambda() &&
+      Method->getConversionType()->isBlockPointerType()) {
+    // This is a lambda coversion to block pointer; check if the argument
+    // is a LambdaExpr.
+    Expr *SubE =3D E;
+    CastExpr *CE =3D dyn_cast<CastExpr>(SubE);
+    if (CE && CE->getCastKind() =3D=3D CK_NoOp)
+      SubE =3D CE->getSubExpr();
+    SubE =3D SubE->IgnoreParens();
+    if (CXXBindTemporaryExpr *BE =3D dyn_cast<CXXBindTemporaryExpr>(SubE))
+      SubE =3D BE->getSubExpr();
+    if (isa<LambdaExpr>(SubE)) {
+      // For the conversion to block pointer on a lambda expression, we
+      // construct a special BlockLiteral instead; this doesn't really make
+      // a difference in ARC, but outside of ARC the resulting block liter=
al
+      // follows the normal lifetime rules for block literals instead of b=
eing
+      // autoreleased.
+      DiagnosticErrorTrap Trap(Diags);
+      ExprResult Exp =3D BuildBlockForLambdaConversion(E->getExprLoc(),
+                                                     E->getExprLoc(),
+                                                     Method, E);
+      if (Exp.isInvalid())
+        Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
+      return Exp;
+    }
+  }
+     =20
+
   ExprResult Exp =3D PerformObjectArgumentInitialization(E, /*Qualifier=3D=
*/0,
                                           FoundDecl, Method);
   if (Exp.isInvalid())
@@ -4558,7 +5147,7 @@
=20
   MemberExpr *ME =3D
       new (Context) MemberExpr(Exp.take(), /*IsArrow=3D*/false, Method,
-                               SourceLocation(), Method->getType(),
+                               SourceLocation(), Context.BoundMemberTy,
                                VK_RValue, OK_Ordinary);
   if (HadMultipleCandidates)
     ME->setHadMultipleCandidates(true);
@@ -4567,7 +5156,7 @@
   ExprValueKind VK =3D Expr::getValueKindForType(ResultType);
   ResultType =3D ResultType.getNonLValueExprType(Context);
=20
-  MarkDeclarationReferenced(Exp.get()->getLocStart(), Method);
+  MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
   CXXMemberCallExpr *CE =3D
     new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
                                     Exp.get()->getLocEnd());
@@ -4589,6 +5178,12 @@
 /// Perform the conversions required for an expression used in a
 /// context that ignores the result.
 ExprResult Sema::IgnoredValueConversions(Expr *E) {
+  if (E->hasPlaceholderType()) {
+    ExprResult result =3D CheckPlaceholderExpr(E);
+    if (result.isInvalid()) return Owned(E);
+    E =3D result.take();
+  }
+
   // C99 6.3.2.1:
   //   [Except in specific positions,] an lvalue that does not have
   //   array type is converted to the value stored in the
@@ -4598,22 +5193,14 @@
     // are r-values, but we still want to do function-to-pointer decay
     // on them.  This is both technically correct and convenient for
     // some clients.
-    if (!getLangOptions().CPlusPlus && E->getType()->isFunctionType())
+    if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
       return DefaultFunctionArrayConversion(E);
=20
     return Owned(E);
   }
=20
-  // We always want to do this on ObjC property references.
-  if (E->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Res =3D ConvertPropertyForRValue(E);
-    if (Res.isInvalid()) return Owned(E);
-    E =3D Res.take();
-    if (E->isRValue()) return Owned(E);
-  }
-
   // Otherwise, this rule does not apply in C++, at least not for the mome=
nt.
-  if (getLangOptions().CPlusPlus) return Owned(E);
+  if (getLangOpts().CPlusPlus) return Owned(E);
=20
   // GCC seems to also exclude expressions of incomplete enum type.
   if (const EnumType *T =3D E->getType()->getAs<EnumType>()) {
@@ -4644,6 +5231,15 @@
   if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
     return ExprError();
=20
+  // Top-level message sends default to 'id' when we're in a debugger.
+  if (getLangOpts().DebuggerCastResultToId &&
+      FullExpr.get()->getType() =3D=3D Context.UnknownAnyTy &&
+      isa<ObjCMessageExpr>(FullExpr.get())) {
+    FullExpr =3D forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdT=
ype());
+    if (FullExpr.isInvalid())
+      return ExprError();
+  }
+ =20
   FullExpr =3D CheckPlaceholderExpr(FullExpr.take());
   if (FullExpr.isInvalid())
     return ExprError();
@@ -4662,17 +5258,58 @@
   return MaybeCreateStmtWithCleanups(FullStmt);
 }
=20
-bool Sema::CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS,
-                                        UnqualifiedId &Name) {
-  DeclarationNameInfo TargetNameInfo =3D GetNameFromUnqualifiedId(Name);
+Sema::IfExistsResult=20
+Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
+                                   CXXScopeSpec &SS,
+                                   const DeclarationNameInfo &TargetNameIn=
fo) {
   DeclarationName TargetName =3D TargetNameInfo.getName();
   if (!TargetName)
-    return false;
-
+    return IER_DoesNotExist;
+ =20
+  // If the name itself is dependent, then the result is dependent.
+  if (TargetName.isDependentName())
+    return IER_Dependent;
+ =20
   // Do the redeclaration lookup in the current scope.
   LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
                  Sema::NotForRedeclaration);
+  LookupParsedName(R, S, &SS);
   R.suppressDiagnostics();
-  LookupParsedName(R, getCurScope(), &SS);
-  return !R.empty();=20
+ =20
+  switch (R.getResultKind()) {
+  case LookupResult::Found:
+  case LookupResult::FoundOverloaded:
+  case LookupResult::FoundUnresolvedValue:
+  case LookupResult::Ambiguous:
+    return IER_Exists;
+   =20
+  case LookupResult::NotFound:
+    return IER_DoesNotExist;
+   =20
+  case LookupResult::NotFoundInCurrentInstantiation:
+    return IER_Dependent;
+  }
+
+  llvm_unreachable("Invalid LookupResult Kind!");
 }
+
+Sema::IfExistsResult=20
+Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
+                                   bool IsIfExists, CXXScopeSpec &SS,
+                                   UnqualifiedId &Name) {
+  DeclarationNameInfo TargetNameInfo =3D GetNameFromUnqualifiedId(Name);
+ =20
+  // Check for unexpanded parameter packs.
+  SmallVector<UnexpandedParameterPack, 4> Unexpanded;
+  collectUnexpandedParameterPacks(SS, Unexpanded);
+  collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
+  if (!Unexpanded.empty()) {
+    DiagnoseUnexpandedParameterPacks(KeywordLoc,
+                                     IsIfExists? UPPC_IfExists=20
+                                               : UPPC_IfNotExists,=20
+                                     Unexpanded);
+    return IER_Error;
+  }
+ =20
+  return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaExprMember.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaExprMember.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaExprMember.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -56,7 +56,7 @@
   /// The reference may be an implicit instance member access.
   IMA_Mixed,
=20
-  /// The reference may be to an instance member, but it is invalid if
+  /// The reference may be to an instance member, but it might be invalid =
if
   /// so, because the context is not an instance method.
   IMA_Mixed_StaticContext,
=20
@@ -74,6 +74,11 @@
   /// context is not an instance method.
   IMA_Unresolved_StaticContext,
=20
+  // The reference refers to a field which is not a member of the containi=
ng
+  // class, which is allowed because we're in C++11 mode and the context is
+  // unevaluated.
+  IMA_Field_Uneval_Context,
+
   /// All possible referrents are instance members and the current
   /// context is not an instance method.
   IMA_Error_StaticContext,
@@ -86,7 +91,7 @@
 /// The given lookup names class member(s) and is not being used for
 /// an address-of-member expression.  Classify the type of access
 /// according to whether it's possible that this reference names an
-/// instance member.  This is best-effort; it is okay to
+/// instance member.  This is best-effort in dependent contexts; it is oka=
y to
 /// conservatively answer "yes", in which case some errors will simply
 /// not be caught until template-instantiation.
 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
@@ -112,14 +117,14 @@
=20
   // Collect all the declaring classes of instance members we find.
   bool hasNonInstance =3D false;
-  bool hasField =3D false;
+  bool isField =3D false;
   llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
   for (LookupResult::iterator I =3D R.begin(), E =3D R.end(); I !=3D E; ++=
I) {
     NamedDecl *D =3D *I;
=20
     if (D->isCXXInstanceMember()) {
       if (dyn_cast<FieldDecl>(D))
-        hasField =3D true;
+        isField =3D true;
=20
       CXXRecordDecl *R =3D cast<CXXRecordDecl>(D->getDeclContext());
       Classes.insert(R->getCanonicalDecl());
@@ -133,27 +138,28 @@
   if (Classes.empty())
     return IMA_Static;
=20
+  bool IsCXX11UnevaluatedField =3D false;
+  if (SemaRef.getLangOpts().CPlusPlus0x && isField) {
+    // C++11 [expr.prim.general]p12:
+    //   An id-expression that denotes a non-static data member or non-sta=
tic
+    //   member function of a class can only be used:
+    //   (...)
+    //   - if that id-expression denotes a non-static data member and it
+    //     appears in an unevaluated operand.
+    const Sema::ExpressionEvaluationContextRecord& record
+      =3D SemaRef.ExprEvalContexts.back();
+    if (record.Context =3D=3D Sema::Unevaluated)
+      IsCXX11UnevaluatedField =3D true;
+  }
+
   // If the current context is not an instance method, it can't be
   // an implicit member reference.
   if (isStaticContext) {
     if (hasNonInstance)
-        return IMA_Mixed_StaticContext;
-       =20
-    if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
-      // C++0x [expr.prim.general]p10:
-      //   An id-expression that denotes a non-static data member or non-s=
tatic
-      //   member function of a class can only be used:
-      //   (...)
-      //   - if that id-expression denotes a non-static data member and it
-      //     appears in an unevaluated operand.
-      const Sema::ExpressionEvaluationContextRecord& record
-        =3D SemaRef.ExprEvalContexts.back();
-      bool isUnevaluatedExpression =3D (record.Context =3D=3D Sema::Uneval=
uated);
-      if (isUnevaluatedExpression)
-        return IMA_Mixed_StaticContext;
-    }
-   =20
-    return IMA_Error_StaticContext;
+      return IMA_Mixed_StaticContext;
+
+    return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
+                                   : IMA_Error_StaticContext;
   }
=20
   CXXRecordDecl *contextClass;
@@ -169,76 +175,93 @@
   // ...if C is not X or a base class of X, the class member access expres=
sion
   // is ill-formed.
   if (R.getNamingClass() &&
-      contextClass !=3D R.getNamingClass()->getCanonicalDecl() &&
+      contextClass->getCanonicalDecl() !=3D
+        R.getNamingClass()->getCanonicalDecl() &&
       contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
-    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
+    return hasNonInstance ? IMA_Mixed_Unrelated :
+           IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
+                                     IMA_Error_Unrelated;
=20
   // If we can prove that the current context is unrelated to all the
   // declaring classes, it can't be an implicit member reference (in
   // which case it's an error if any of those members are selected).
   if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
-    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
+    return hasNonInstance ? IMA_Mixed_Unrelated :
+           IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
+                                     IMA_Error_Unrelated;
=20
   return (hasNonInstance ? IMA_Mixed : IMA_Instance);
 }
=20
 /// Diagnose a reference to a field with no object available.
-static void DiagnoseInstanceReference(Sema &SemaRef,
+static void diagnoseInstanceReference(Sema &SemaRef,
                                       const CXXScopeSpec &SS,
-                                      NamedDecl *rep,
+                                      NamedDecl *Rep,
                                       const DeclarationNameInfo &nameInfo)=
 {
   SourceLocation Loc =3D nameInfo.getLoc();
   SourceRange Range(Loc);
   if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
- =20
-  if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
-    if (CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(SemaRef.CurContext))=
 {
-      if (MD->isStatic()) {
-        // "invalid use of member 'x' in static member function"
-        SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
+
+  DeclContext *FunctionLevelDC =3D SemaRef.getFunctionLevelDeclContext();
+  CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(FunctionLevelDC);
+  CXXRecordDecl *ContextClass =3D Method ? Method->getParent() : 0;
+  CXXRecordDecl *RepClass =3D dyn_cast<CXXRecordDecl>(Rep->getDeclContext(=
));
+
+  bool InStaticMethod =3D Method && Method->isStatic();
+  bool IsField =3D isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
+
+  if (IsField && InStaticMethod)
+    // "invalid use of member 'x' in static member function"
+    SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
         << Range << nameInfo.getName();
-        return;
-      }
-    }
-   =20
+  else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
+           !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextCl=
ass))
+    // Unqualified lookup in a non-static member function found a member o=
f an
+    // enclosing class.
+    SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
+      << IsField << RepClass << nameInfo.getName() << ContextClass << Rang=
e;
+  else if (IsField)
     SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
-    << nameInfo.getName() << Range;
-    return;
-  }
- =20
-  SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
+      << nameInfo.getName() << Range;
+  else
+    SemaRef.Diag(Loc, diag::err_member_call_without_object)
+      << Range;
 }
=20
 /// Builds an expression which might be an implicit member expression.
 ExprResult
 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
+                                      SourceLocation TemplateKWLoc,
                                       LookupResult &R,
                                 const TemplateArgumentListInfo *TemplateAr=
gs) {
   switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
   case IMA_Instance:
-    return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
+    return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, tru=
e);
=20
   case IMA_Mixed:
   case IMA_Mixed_Unrelated:
   case IMA_Unresolved:
-    return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
+    return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, fal=
se);
=20
+  case IMA_Field_Uneval_Context:
+    Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
+      << R.getLookupNameInfo().getName();
+    // Fall through.
   case IMA_Static:
   case IMA_Mixed_StaticContext:
   case IMA_Unresolved_StaticContext:
-    if (TemplateArgs)
-      return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
+    if (TemplateArgs || TemplateKWLoc.isValid())
+      return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs=
);
     return BuildDeclarationNameExpr(SS, R, false);
=20
   case IMA_Error_StaticContext:
   case IMA_Error_Unrelated:
-    DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
+    diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
                               R.getLookupNameInfo());
     return ExprError();
   }
=20
   llvm_unreachable("unexpected instance member access kind");
-  return ExprError();
 }
=20
 /// Check an ext-vector component access expression.
@@ -403,6 +426,7 @@
 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
                                bool IsArrow, SourceLocation OpLoc,
                                const CXXScopeSpec &SS,
+                               SourceLocation TemplateKWLoc,
                                NamedDecl *FirstQualifierInScope,
                                const DeclarationNameInfo &NameInfo,
                                const TemplateArgumentListInfo *TemplateArg=
s) {
@@ -417,7 +441,7 @@
   // allows this, while still reporting an error if T is a struct pointer.
   if (!IsArrow) {
     const PointerType *PT =3D BaseType->getAs<PointerType>();
-    if (PT && (!getLangOptions().ObjC1 ||
+    if (PT && (!getLangOpts().ObjC1 ||
                PT->getPointeeType()->isRecordType())) {
       assert(BaseExpr && "cannot happen with implicit member accesses");
       Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_=
union)
@@ -435,6 +459,7 @@
   return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, Base=
Type,
                                                    IsArrow, OpLoc,
                                                SS.getWithLocInContext(Cont=
ext),
+                                                   TemplateKWLoc,
                                                    FirstQualifierInScope,
                                                    NameInfo, TemplateArgs)=
);
 }
@@ -451,7 +476,7 @@
   // If this is an implicit member access, use a different set of
   // diagnostics.
   if (!BaseExpr)
-    return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
+    return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
=20
   SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
     << SS.getRange() << rep << BaseType;
@@ -509,6 +534,20 @@
   return true;
 }
=20
+namespace {
+
+// Callback to only accept typo corrections that are either a ValueDecl or=
 a
+// FunctionTemplateDecl.
+class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    NamedDecl *ND =3D candidate.getCorrectionDecl();
+    return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
+  }
+};
+
+}
+
 static bool
 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
                          SourceRange BaseRange, const RecordType *RTy,
@@ -559,17 +598,16 @@
   // We didn't find anything with the given name, so try to correct
   // for typos.
   DeclarationName Name =3D R.getLookupName();
+  RecordMemberExprValidatorCCC Validator;
   TypoCorrection Corrected =3D SemaRef.CorrectTypo(R.getLookupNameInfo(),
                                                  R.getLookupKind(), NULL,
-                                                 &SS, DC, false,
-                                                 Sema::CTC_MemberLookup);
-  NamedDecl *ND =3D Corrected.getCorrectionDecl();
+                                                 &SS, Validator, DC);
   R.clear();
-  if (ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))) {
+  if (NamedDecl *ND =3D Corrected.getCorrectionDecl()) {
     std::string CorrectedStr(
-        Corrected.getAsString(SemaRef.getLangOptions()));
+        Corrected.getAsString(SemaRef.getLangOpts()));
     std::string CorrectedQuotedStr(
-        Corrected.getQuoted(SemaRef.getLangOptions()));
+        Corrected.getQuoted(SemaRef.getLangOpts()));
     R.setLookupName(Corrected.getCorrection());
     R.addDecl(ND);
     SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
@@ -586,6 +624,7 @@
 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
                                SourceLocation OpLoc, bool IsArrow,
                                CXXScopeSpec &SS,
+                               SourceLocation TemplateKWLoc,
                                NamedDecl *FirstQualifierInScope,
                                const DeclarationNameInfo &NameInfo,
                                const TemplateArgumentListInfo *TemplateArg=
s) {
@@ -593,7 +632,7 @@
       (SS.isSet() && isDependentScopeSpecifier(SS)))
     return ActOnDependentMemberExpr(Base, BaseType,
                                     IsArrow, OpLoc,
-                                    SS, FirstQualifierInScope,
+                                    SS, TemplateKWLoc, FirstQualifierInSco=
pe,
                                     NameInfo, TemplateArgs);
=20
   LookupResult R(*this, NameInfo, LookupMemberName);
@@ -631,8 +670,8 @@
   }
=20
   return BuildMemberReferenceExpr(Base, BaseType,
-                                  OpLoc, IsArrow, SS, FirstQualifierInScop=
e,
-                                  R, TemplateArgs);
+                                  OpLoc, IsArrow, SS, TemplateKWLoc,
+                                  FirstQualifierInScope, R, TemplateArgs);
 }
=20
 static ExprResult
@@ -697,7 +736,7 @@
     // We've found a member of an anonymous struct/union that is
     // inside a non-anonymous struct/union, so in a well-formed
     // program our base object expression is "this".
-    QualType ThisTy =3D getAndCaptureCurrentThisType();
+    QualType ThisTy =3D getCurrentThisType();
     if (ThisTy.isNull()) {
       Diag(loc, diag::err_invalid_member_use_in_static_method)
         << indirectField->getDeclName();
@@ -705,6 +744,7 @@
     }
    =20
     // Our base object expression is "this".
+    CheckCXXThisCapture(loc);
     baseObjectExpr=20
       =3D new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=3D*/ true);
     baseObjectIsPointer =3D true;
@@ -754,22 +794,30 @@
 }
=20
 /// \brief Build a MemberExpr AST node.
-static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
-                                   const CXXScopeSpec &SS, ValueDecl *Memb=
er,
+static MemberExpr *BuildMemberExpr(Sema &SemaRef,
+                                   ASTContext &C, Expr *Base, bool isArrow,
+                                   const CXXScopeSpec &SS,
+                                   SourceLocation TemplateKWLoc,
+                                   ValueDecl *Member,
                                    DeclAccessPair FoundDecl,
                                    const DeclarationNameInfo &MemberNameIn=
fo,
                                    QualType Ty,
                                    ExprValueKind VK, ExprObjectKind OK,
                                    const TemplateArgumentListInfo *Templat=
eArgs =3D 0) {
-  return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
-                            Member, FoundDecl, MemberNameInfo,
-                            TemplateArgs, Ty, VK, OK);
+  assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rval=
ue");
+  MemberExpr *E =3D
+      MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
+                         TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
+                         TemplateArgs, Ty, VK, OK);
+  SemaRef.MarkMemberReferenced(E);
+  return E;
 }
=20
 ExprResult
 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
                                SourceLocation OpLoc, bool IsArrow,
                                const CXXScopeSpec &SS,
+                               SourceLocation TemplateKWLoc,
                                NamedDecl *FirstQualifierInScope,
                                LookupResult &R,
                          const TemplateArgumentListInfo *TemplateArgs,
@@ -777,7 +825,7 @@
   QualType BaseType =3D BaseExprType;
   if (IsArrow) {
     assert(BaseType->isPointerType());
-    BaseType =3D BaseType->getAs<PointerType>()->getPointeeType();
+    BaseType =3D BaseType->castAs<PointerType>()->getPointeeType();
   }
   R.setBaseObjectType(BaseType);
=20
@@ -813,7 +861,7 @@
       !SuppressQualifierCheck &&
       CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
     return ExprError();
-
+ =20
   // Construct an unresolved result if we in fact got an unresolved
   // result.
   if (R.isOverloadedResult() || R.isUnresolvableResult()) {
@@ -826,7 +874,7 @@
                                      BaseExpr, BaseExprType,
                                      IsArrow, OpLoc,
                                      SS.getWithLocInContext(Context),
-                                     MemberNameInfo,
+                                     TemplateKWLoc, MemberNameInfo,
                                      TemplateArgs, R.begin(), R.end());
=20
     return Owned(MemExpr);
@@ -853,6 +901,7 @@
     SourceLocation Loc =3D R.getNameLoc();
     if (SS.getRange().isValid())
       Loc =3D SS.getRange().getBegin();
+    CheckCXXThisCapture(Loc);
     BaseExpr =3D new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=
=3D*/true);
   }
=20
@@ -870,15 +919,6 @@
     return ExprError();
   }
=20
-  // Perform a property load on the base regardless of whether we
-  // actually need it for the declaration.
-  if (BaseExpr->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Result =3D ConvertPropertyForRValue(BaseExpr);
-    if (Result.isInvalid())
-      return ExprError();
-    BaseExpr =3D Result.take();
-  }
-
   if (FieldDecl *FD =3D dyn_cast<FieldDecl>(MemberDecl))
     return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
                                    SS, FD, FoundDecl, MemberNameInfo);
@@ -890,9 +930,8 @@
                                                     BaseExpr, OpLoc);
=20
   if (VarDecl *Var =3D dyn_cast<VarDecl>(MemberDecl)) {
-    MarkDeclarationReferenced(MemberLoc, Var);
-    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
-                                 Var, FoundDecl, MemberNameInfo,
+    return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
+                                 TemplateKWLoc, Var, FoundDecl, MemberName=
Info,
                                  Var->getType().getNonReferenceType(),
                                  VK_LValue, OK_Ordinary));
   }
@@ -908,17 +947,16 @@
       type =3D MemberFn->getType();
     }
=20
-    MarkDeclarationReferenced(MemberLoc, MemberDecl);
-    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
-                                 MemberFn, FoundDecl, MemberNameInfo,
-                                 type, valueKind, OK_Ordinary));
+    return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,=20
+                                 TemplateKWLoc, MemberFn, FoundDecl,=20
+                                 MemberNameInfo, type, valueKind,
+                                 OK_Ordinary));
   }
   assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method=
?");
=20
   if (EnumConstantDecl *Enum =3D dyn_cast<EnumConstantDecl>(MemberDecl)) {
-    MarkDeclarationReferenced(MemberLoc, MemberDecl);
-    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
-                                 Enum, FoundDecl, MemberNameInfo,
+    return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
+                                 TemplateKWLoc, Enum, FoundDecl, MemberNam=
eInfo,
                                  Enum->getType(), VK_RValue, OK_Ordinary));
   }
=20
@@ -979,6 +1017,15 @@
   return false;
 }
=20
+/// Perform conversions on the LHS of a member access expression.
+ExprResult
+Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
+  if (IsArrow && !Base->getType()->isFunctionType())
+    return DefaultFunctionArrayLvalueConversion(Base);
+
+  return CheckPlaceholderExpr(Base);
+}
+
 /// Look up the given member of the given non-type-dependent
 /// expression.  This can return in one of two ways:
 ///  * If it returns a sentinel null-but-valid result, the caller will
@@ -997,16 +1044,10 @@
   assert(BaseExpr.get() && "no base expression");
=20
   // Perform default conversions.
-  BaseExpr =3D DefaultFunctionArrayConversion(BaseExpr.take());
+  BaseExpr =3D PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
   if (BaseExpr.isInvalid())
     return ExprError();
=20
-  if (IsArrow) {
-    BaseExpr =3D DefaultLvalueConversion(BaseExpr.take());
-    if (BaseExpr.isInvalid())
-      return ExprError();
-  }
-
   QualType BaseType =3D BaseExpr.get()->getType();
   assert(!BaseType->isDependentType());
=20
@@ -1034,7 +1075,7 @@
         << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
         << FixItHint::CreateReplacement(OpLoc, ".");
       IsArrow =3D false;
-    } else if (BaseType =3D=3D Context.BoundMemberTy) {
+    } else if (BaseType->isFunctionType()) {
       goto fail;
     } else {
       Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
@@ -1071,15 +1112,17 @@
     //   - an interface
     ObjCInterfaceDecl *IDecl =3D OTy->getInterface();
     if (!IDecl) {
-      if (getLangOptions().ObjCAutoRefCount &&
+      if (getLangOpts().ObjCAutoRefCount &&
           (OTy->isObjCId() || OTy->isObjCClass()))
         goto fail;
       // There's an implicit 'isa' ivar on all objects.
       // But we only actually find it this way on objects of type 'id',
-      // apparently.
-      if (OTy->isObjCId() && Member->isStr("isa"))
+      // apparently.ghjg
+      if (OTy->isObjCId() && Member->isStr("isa")) {
+        Diag(MemberLoc, diag::warn_objc_isa_use);
         return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, M=
emberLoc,
                                                Context.getObjCClassType())=
);
+      }
=20
       if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
         return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
@@ -1087,17 +1130,22 @@
       goto fail;
     }
=20
-    ObjCInterfaceDecl *ClassDeclared;
+    if (RequireCompleteType(OpLoc, BaseType,=20
+                            PDiag(diag::err_typecheck_incomplete_tag)
+                              << BaseExpr.get()->getSourceRange()))
+      return ExprError();
+   =20
+    ObjCInterfaceDecl *ClassDeclared =3D 0;
     ObjCIvarDecl *IV =3D IDecl->lookupInstanceVariable(Member, ClassDeclar=
ed);
=20
     if (!IV) {
       // Attempt to correct for typos in ivar names.
-      LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
-                       LookupMemberName);
-      TypoCorrection Corrected =3D CorrectTypo(
-          R.getLookupNameInfo(), LookupMemberName, NULL, NULL, IDecl, fals=
e,
-          IsArrow ? CTC_ObjCIvarLookup : CTC_ObjCPropertyLookup);
-      if ((IV =3D Corrected.getCorrectionDeclAs<ObjCIvarDecl>())) {
+      DeclFilterCCC<ObjCIvarDecl> Validator;
+      Validator.IsObjCIvarLookup =3D IsArrow;
+      if (TypoCorrection Corrected =3D CorrectTypo(R.getLookupNameInfo(),
+                                                 LookupMemberName, NULL, N=
ULL,
+                                                 Validator, IDecl)) {
+        IV =3D Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
         Diag(R.getNameLoc(),
              diag::err_typecheck_member_reference_ivar_suggest)
           << IDecl->getDeclName() << MemberName << IV->getDeclName()
@@ -1105,6 +1153,13 @@
                                           IV->getNameAsString());
         Diag(IV->getLocation(), diag::note_previous_decl)
           << IV->getDeclName();
+       =20
+        // Figure out the class that declares the ivar.
+        assert(!ClassDeclared);
+        Decl *D =3D cast<Decl>(IV->getDeclContext());
+        if (ObjCCategoryDecl *CAT =3D dyn_cast<ObjCCategoryDecl>(D))
+          D =3D CAT->getClassInterface();
+        ClassDeclared =3D cast<ObjCInterfaceDecl>(D);
       } else {
         if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
           Diag(MemberLoc,=20
@@ -1113,8 +1168,6 @@
           << FixItHint::CreateReplacement(OpLoc, ".");
           return ExprError();
         }
-        Res.clear();
-        Res.setLookupName(Member);
=20
         Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
           << IDecl->getDeclName() << MemberName
@@ -1122,6 +1175,8 @@
         return ExprError();
       }
     }
+   =20
+    assert(ClassDeclared);
=20
     // If the decl being referenced had an error, return an error for this
     // sub-expr without emitting another error, in order to avoid cascading
@@ -1151,18 +1206,19 @@
                    dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
           ClassOfMethodDecl =3D CatImplClass->getClassInterface();
       }
-
-      if (IV->getAccessControl() =3D=3D ObjCIvarDecl::Private) {
-        if (ClassDeclared !=3D IDecl ||
-            ClassOfMethodDecl !=3D ClassDeclared)
-          Diag(MemberLoc, diag::error_private_ivar_access)
+      if (!getLangOpts().DebuggerSupport) {
+        if (IV->getAccessControl() =3D=3D ObjCIvarDecl::Private) {
+          if (!declaresSameEntity(ClassDeclared, IDecl) ||
+              !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
+            Diag(MemberLoc, diag::error_private_ivar_access)
+              << IV->getDeclName();
+        } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
+          // @protected
+          Diag(MemberLoc, diag::error_protected_ivar_access)
             << IV->getDeclName();
-      } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
-        // @protected
-        Diag(MemberLoc, diag::error_protected_ivar_access)
-          << IV->getDeclName();
+      }
     }
-    if (getLangOptions().ObjCAutoRefCount) {
+    if (getLangOpts().ObjCAutoRefCount) {
       Expr *BaseExp =3D BaseExpr.get()->IgnoreParenImpCasts();
       if (UnaryOperator *UO =3D dyn_cast<UnaryOperator>(BaseExp))
         if (UO->getOpcode() =3D=3D UO_Deref)
@@ -1209,11 +1265,8 @@
           if (DiagnoseUseOfDecl(PD, MemberLoc))
             return ExprError();
=20
-          QualType T =3D PD->getType();
-          if (ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl())
-            T =3D getMessageSendResultType(BaseType, Getter, false, false);
-        =20
-          return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
+          return Owned(new (Context) ObjCPropertyRefExpr(PD,
+                                                         Context.PseudoObj=
ectTy,
                                                          VK_LValue,
                                                          OK_ObjCProperty,
                                                          MemberLoc,=20
@@ -1231,16 +1284,10 @@
           if (Decl *SDecl =3D FindGetterSetterNameDecl(OPT, /*Property id*=
/0,=20
                                                      SetterSel, Context))
             SMD =3D dyn_cast<ObjCMethodDecl>(SDecl);
-          QualType PType =3D getMessageSendResultType(BaseType, OMD, false=
,=20
-                                                    false);
          =20
-          ExprValueKind VK =3D VK_LValue;
-          if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType(=
))
-            VK =3D VK_RValue;
-          ExprObjectKind OK =3D (VK =3D=3D VK_RValue ? OK_Ordinary : OK_Ob=
jCProperty);
-
-          return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
-                                                         VK, OK,
+          return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
+                                                         Context.PseudoObj=
ectTy,
+                                                         VK_LValue, OK_Obj=
CProperty,
                                                          MemberLoc, BaseEx=
pr.take()));
         }
       }
@@ -1295,23 +1342,9 @@
         return ExprError();
=20
       if (Getter || Setter) {
-        QualType PType;
-
-        ExprValueKind VK =3D VK_LValue;
-        if (Getter) {
-          PType =3D getMessageSendResultType(QualType(OT, 0), Getter, true=
,=20
-                                           false);
-          if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType(=
))
-            VK =3D VK_RValue;
-        } else {
-          // Get the expression type from Setter's incoming parameter.
-          PType =3D (*(Setter->param_end() -1))->getType();
-        }
-        ExprObjectKind OK =3D (VK =3D=3D VK_RValue ? OK_Ordinary : OK_ObjC=
Property);
-
-        // FIXME: we must check that the setter has property type.
         return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
-                                                       PType, VK, OK,
+                                                       Context.PseudoObjec=
tTy,
+                                                       VK_LValue, OK_ObjCP=
roperty,
                                                        MemberLoc, BaseExpr=
.take()));
       }
=20
@@ -1384,7 +1417,7 @@
   if (tryToRecoverWithCall(BaseExpr,
                            PDiag(diag::err_member_reference_needs_call),
                            /*complain*/ false,
-                           IsArrow ? &isRecordType : &isPointerToRecordTyp=
e)) {
+                           IsArrow ? &isPointerToRecordType : &isRecordTyp=
e)) {
     if (BaseExpr.isInvalid())
       return ExprError();
     BaseExpr =3D DefaultFunctionArrayConversion(BaseExpr.take());
@@ -1415,6 +1448,7 @@
                                        SourceLocation OpLoc,
                                        tok::TokenKind OpKind,
                                        CXXScopeSpec &SS,
+                                       SourceLocation TemplateKWLoc,
                                        UnqualifiedId &Id,
                                        Decl *ObjCImpDecl,
                                        bool HasTrailingLParen) {
@@ -1422,7 +1456,7 @@
     return ExprError();
=20
   // Warn about the explicit constructor calls Microsoft extension.
-  if (getLangOptions().MicrosoftExt &&
+  if (getLangOpts().MicrosoftExt &&
       Id.getKind() =3D=3D UnqualifiedId::IK_ConstructorName)
     Diag(Id.getSourceRange().getBegin(),
          diag::ext_ms_explicit_constructor_call);
@@ -1451,7 +1485,7 @@
       isDependentScopeSpecifier(SS)) {
     Result =3D ActOnDependentMemberExpr(Base, Base->getType(),
                                       IsArrow, OpLoc,
-                                      SS, FirstQualifierInScope,
+                                      SS, TemplateKWLoc, FirstQualifierInS=
cope,
                                       NameInfo, TemplateArgs);
   } else {
     LookupResult R(*this, NameInfo, LookupMemberName);
@@ -1480,8 +1514,8 @@
     }
=20
     Result =3D BuildMemberReferenceExpr(Base, Base->getType(),
-                                      OpLoc, IsArrow, SS, FirstQualifierIn=
Scope,
-                                      R, TemplateArgs);
+                                      OpLoc, IsArrow, SS, TemplateKWLoc,
+                                      FirstQualifierInScope, R, TemplateAr=
gs);
   }
=20
   return move(Result);
@@ -1536,13 +1570,13 @@
       MemberType =3D S.Context.getQualifiedType(MemberType, Combined);
   }
  =20
-  S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
   ExprResult Base =3D
   S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
                                   FoundDecl, Field);
   if (Base.isInvalid())
     return ExprError();
-  return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
+  return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
+                                 /*TemplateKWLoc=3D*/SourceLocation(),
                                  Field, FoundDecl, MemberNameInfo,
                                  MemberType, VK, OK));
 }
@@ -1553,6 +1587,7 @@
 /// is from an appropriate type.
 ExprResult
 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
+                              SourceLocation TemplateKWLoc,
                               LookupResult &R,
                               const TemplateArgumentListInfo *TemplateArgs,
                               bool IsKnownInstance) {
@@ -1569,7 +1604,7 @@
   // If this is known to be an instance access, go ahead and build an
   // implicit 'this' expression now.
   // 'this' expression now.
-  QualType ThisTy =3D getAndCaptureCurrentThisType();
+  QualType ThisTy =3D getCurrentThisType();
   assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this=
'");
  =20
   Expr *baseExpr =3D 0; // null signifies implicit access
@@ -1577,13 +1612,14 @@
     SourceLocation Loc =3D R.getNameLoc();
     if (SS.getRange().isValid())
       Loc =3D SS.getRange().getBegin();
+    CheckCXXThisCapture(Loc);
     baseExpr =3D new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=3D*/t=
rue);
   }
  =20
   return BuildMemberReferenceExpr(baseExpr, ThisTy,
                                   /*OpLoc*/ SourceLocation(),
                                   /*IsArrow*/ true,
-                                  SS,
+                                  SS, TemplateKWLoc,
                                   /*FirstQualifierInScope*/ 0,
                                   R, TemplateArgs);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaExprObjC.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -17,6 +17,8 @@
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
+#include "clang/Edit/Rewriters.h"
+#include "clang/Edit/Commit.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprObjC.h"
@@ -43,7 +45,7 @@
   // If we have a multi-part string, merge it all together.
   if (NumStrings !=3D 1) {
     // Concatenate objc strings.
-    llvm::SmallString<128> StrBuf;
+    SmallString<128> StrBuf;
     SmallVector<SourceLocation, 8> StrLocs;
=20
     for (unsigned i =3D 0; i !=3D NumStrings; ++i) {
@@ -70,7 +72,11 @@
                               Context.getPointerType(Context.CharTy),
                               &StrLocs[0], StrLocs.size());
   }
+ =20
+  return BuildObjCStringLiteral(AtLocs[0], S);
+}
=20
+ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLitera=
l *S){
   // Verify that this composite string is acceptable for ObjC strings.
   if (CheckObjCString(S))
     return true;
@@ -82,16 +88,16 @@
   QualType Ty =3D Context.getObjCConstantStringInterface();
   if (!Ty.isNull()) {
     Ty =3D Context.getObjCObjectPointerType(Ty);
-  } else if (getLangOptions().NoConstantCFStrings) {
+  } else if (getLangOpts().NoConstantCFStrings) {
     IdentifierInfo *NSIdent=3D0;
-    std::string StringClass(getLangOptions().ObjCConstantStringClass);
+    std::string StringClass(getLangOpts().ObjCConstantStringClass);
    =20
     if (StringClass.empty())
       NSIdent =3D &Context.Idents.get("NSConstantString");
     else
       NSIdent =3D &Context.Idents.get(StringClass);
    =20
-    NamedDecl *IF =3D LookupSingleName(TUScope, NSIdent, AtLocs[0],
+    NamedDecl *IF =3D LookupSingleName(TUScope, NSIdent, AtLoc,
                                      LookupOrdinaryName);
     if (ObjCInterfaceDecl *StrIF =3D dyn_cast_or_null<ObjCInterfaceDecl>(I=
F)) {
       Context.setObjCConstantStringInterface(StrIF);
@@ -106,20 +112,638 @@
     }
   } else {
     IdentifierInfo *NSIdent =3D &Context.Idents.get("NSString");
-    NamedDecl *IF =3D LookupSingleName(TUScope, NSIdent, AtLocs[0],
+    NamedDecl *IF =3D LookupSingleName(TUScope, NSIdent, AtLoc,
                                      LookupOrdinaryName);
     if (ObjCInterfaceDecl *StrIF =3D dyn_cast_or_null<ObjCInterfaceDecl>(I=
F)) {
       Context.setObjCConstantStringInterface(StrIF);
       Ty =3D Context.getObjCConstantStringInterface();
       Ty =3D Context.getObjCObjectPointerType(Ty);
     } else {
-      // If there is no NSString interface defined then treat constant
-      // strings as untyped objects and let the runtime figure it out late=
r.
-      Ty =3D Context.getObjCIdType();
+      // If there is no NSString interface defined, implicitly declare
+      // a @class NSString; and use that instead. This is to make sure
+      // type of an NSString literal is represented correctly, instead of
+      // being an 'id' type.
+      Ty =3D Context.getObjCNSStringType();
+      if (Ty.isNull()) {
+        ObjCInterfaceDecl *NSStringIDecl =3D=20
+          ObjCInterfaceDecl::Create (Context,=20
+                                     Context.getTranslationUnitDecl(),=20
+                                     SourceLocation(), NSIdent,=20
+                                     0, SourceLocation());
+        Ty =3D Context.getObjCInterfaceType(NSStringIDecl);
+        Context.setObjCNSStringType(Ty);
+      }
+      Ty =3D Context.getObjCObjectPointerType(Ty);
     }
   }
=20
-  return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
+  return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
+}
+
+/// \brief Retrieve the NSNumber factory method that should be used to cre=
ate
+/// an Objective-C literal for the given type.
+static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Lo=
c,
+                                                QualType T, QualType Retur=
nType,
+                                                SourceRange Range) {
+  llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind=20
+    =3D S.NSAPIObj->getNSNumberFactoryMethodKind(T);
+ =20
+  if (!Kind) {
+    S.Diag(Loc, diag::err_invalid_nsnumber_type)
+      << T << Range;
+    return 0;
+  }
+   =20
+  // If we already looked up this method, we're done.
+  if (S.NSNumberLiteralMethods[*Kind])
+    return S.NSNumberLiteralMethods[*Kind];
+ =20
+  Selector Sel =3D S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
+                                                        /*Instance=3D*/fal=
se);
+ =20
+  // Look for the appropriate method within NSNumber.
+  ObjCMethodDecl *Method =3D S.NSNumberDecl->lookupClassMethod(Sel);;
+  if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
+    TypeSourceInfo *ResultTInfo =3D 0;
+    Method =3D ObjCMethodDecl::Create(S.Context, SourceLocation(), SourceL=
ocation(), Sel,
+                           ReturnType,
+                           ResultTInfo,
+                           S.Context.getTranslationUnitDecl(),
+                           false /*Instance*/, false/*isVariadic*/,
+                           /*isSynthesized=3D*/false,
+                           /*isImplicitlyDeclared=3D*/true, /*isDefined=3D=
*/false,
+                           ObjCMethodDecl::Required,
+                           false);
+    ParmVarDecl *value =3D ParmVarDecl::Create(S.Context, Method,
+                                             SourceLocation(), SourceLocat=
ion(),
+                                             &S.Context.Idents.get("value"=
),
+                                             T, /*TInfo=3D*/0, SC_None, SC=
_None, 0);
+    Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
+  }
+
+  if (!Method) {
+    S.Diag(Loc, diag::err_undeclared_nsnumber_method) << Sel;
+    return 0;
+  }
+ =20
+  // Make sure the return type is reasonable.
+  if (!Method->getResultType()->isObjCObjectPointerType()) {
+    S.Diag(Loc, diag::err_objc_literal_method_sig)
+      << Sel;
+    S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
+      << Method->getResultType();
+    return 0;
+  }
+
+  // Note: if the parameter type is out-of-line, we'll catch it later in t=
he
+  // implicit conversion.
+ =20
+  S.NSNumberLiteralMethods[*Kind] =3D Method;
+  return Method;
+}
+
+/// BuildObjCNumericLiteral - builds an ObjCNumericLiteral AST node for the
+/// numeric literal expression. Type of the expression will be "NSNumber *"
+/// or "id" if NSNumber is unavailable.
+ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Numbe=
r) {
+  // Look up the NSNumber class, if we haven't done so already.
+  if (!NSNumberDecl) {
+    NamedDecl *IF =3D LookupSingleName(TUScope,
+                                NSAPIObj->getNSClassId(NSAPI::ClassId_NSNu=
mber),
+                                AtLoc, LookupOrdinaryName);
+    NSNumberDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(IF);
+   =20
+    if (!NSNumberDecl && getLangOpts().DebuggerObjCLiteral)
+      NSNumberDecl =3D  ObjCInterfaceDecl::Create (Context,
+                        Context.getTranslationUnitDecl(),
+                        SourceLocation(),=20
+                        NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
+                        0, SourceLocation());
+    if (!NSNumberDecl) {
+      Diag(AtLoc, diag::err_undeclared_nsnumber);
+      return ExprError();
+    }
+  }
+ =20
+  // Determine the type of the literal.
+  QualType NumberType =3D Number->getType();
+  if (CharacterLiteral *Char =3D dyn_cast<CharacterLiteral>(Number)) {
+    // In C, character literals have type 'int'. That's not the type we wa=
nt
+    // to use to determine the Objective-c literal kind.
+    switch (Char->getKind()) {
+    case CharacterLiteral::Ascii:
+      NumberType =3D Context.CharTy;
+      break;
+     =20
+    case CharacterLiteral::Wide:
+      NumberType =3D Context.getWCharType();
+      break;
+     =20
+    case CharacterLiteral::UTF16:
+      NumberType =3D Context.Char16Ty;
+      break;
+     =20
+    case CharacterLiteral::UTF32:
+      NumberType =3D Context.Char32Ty;
+      break;
+    }
+  }
+ =20
+  ObjCMethodDecl *Method =3D 0;
+  // Look for the appropriate method within NSNumber.
+  // Construct the literal.
+  QualType Ty
+    =3D Context.getObjCObjectPointerType(
+                                    Context.getObjCInterfaceType(NSNumberD=
ecl));
+  Method  =3D getNSNumberFactoryMethod(*this, AtLoc,=20
+                                     NumberType, Ty,=20
+                                     Number->getSourceRange());
+
+  if (!Method)
+    return ExprError();
+
+  // Convert the number to the type that the parameter expects.
+  QualType ElementT =3D Method->param_begin()[0]->getType();
+  ExprResult ConvertedNumber =3D PerformImplicitConversion(Number, Element=
T,
+                                                         AA_Sending);
+  if (ConvertedNumber.isInvalid())
+    return ExprError();
+  Number =3D ConvertedNumber.get();
+ =20
+  return MaybeBindToTemporary(
+           new (Context) ObjCNumericLiteral(Number, Ty, Method, AtLoc));
+}
+
+ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,=20
+                                      SourceLocation ValueLoc,
+                                      bool Value) {
+  ExprResult Inner;
+  if (getLangOpts().CPlusPlus) {
+    Inner =3D ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_=
false);
+  } else {
+    // C doesn't actually have a way to represent literal values of type=20
+    // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
+    Inner =3D ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
+    Inner =3D ImpCastExprToType(Inner.get(), Context.BoolTy,=20
+                              CK_IntegralToBoolean);
+  }
+ =20
+  return BuildObjCNumericLiteral(AtLoc, Inner.get());
+}
+
+/// \brief Check that the given expression is a valid element of an Object=
ive-C
+/// collection literal.
+static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element=
,=20
+                                                    QualType T) { =20
+  // If the expression is type-dependent, there's nothing for us to do.
+  if (Element->isTypeDependent())
+    return Element;
+
+  ExprResult Result =3D S.CheckPlaceholderExpr(Element);
+  if (Result.isInvalid())
+    return ExprError();
+  Element =3D Result.get();
+
+  // In C++, check for an implicit conversion to an Objective-C object poi=
nter=20
+  // type.
+  if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
+    InitializedEntity Entity
+      =3D InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=
=3D*/false);
+    InitializationKind Kind
+      =3D InitializationKind::CreateCopy(Element->getLocStart(), SourceLoc=
ation());
+    InitializationSequence Seq(S, Entity, Kind, &Element, 1);
+    if (!Seq.Failed())
+      return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
+  }
+
+  Expr *OrigElement =3D Element;
+
+  // Perform lvalue-to-rvalue conversion.
+  Result =3D S.DefaultLvalueConversion(Element);
+  if (Result.isInvalid())
+    return ExprError();
+  Element =3D Result.get(); =20
+
+  // Make sure that we have an Objective-C pointer type or block.
+  if (!Element->getType()->isObjCObjectPointerType() &&
+      !Element->getType()->isBlockPointerType()) {
+    bool Recovered =3D false;
+   =20
+    // If this is potentially an Objective-C numeric literal, add the '@'.
+    if (isa<IntegerLiteral>(OrigElement) ||=20
+        isa<CharacterLiteral>(OrigElement) ||
+        isa<FloatingLiteral>(OrigElement) ||
+        isa<ObjCBoolLiteralExpr>(OrigElement) ||
+        isa<CXXBoolLiteralExpr>(OrigElement)) {
+      if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())=
) {
+        int Which =3D isa<CharacterLiteral>(OrigElement) ? 1
+                  : (isa<CXXBoolLiteralExpr>(OrigElement) ||
+                     isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
+                  : 3;
+       =20
+        S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collectio=
n)
+          << Which << OrigElement->getSourceRange()
+          << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
+       =20
+        Result =3D S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
+                                           OrigElement);
+        if (Result.isInvalid())
+          return ExprError();
+       =20
+        Element =3D Result.get();
+        Recovered =3D true;
+      }
+    }
+    // If this is potentially an Objective-C string literal, add the '@'.
+    else if (StringLiteral *String =3D dyn_cast<StringLiteral>(OrigElement=
)) {
+      if (String->isAscii()) {
+        S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collectio=
n)
+          << 0 << OrigElement->getSourceRange()
+          << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
+
+        Result =3D S.BuildObjCStringLiteral(OrigElement->getLocStart(), St=
ring);
+        if (Result.isInvalid())
+          return ExprError();
+       =20
+        Element =3D Result.get();
+        Recovered =3D true;
+      }
+    }
+   =20
+    if (!Recovered) {
+      S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
+        << Element->getType();
+      return ExprError();
+    }
+  }
+ =20
+  // Make sure that the element has the type that the container factory=20
+  // function expects.=20
+  return S.PerformCopyInitialization(
+           InitializedEntity::InitializeParameter(S.Context, T,=20
+                                                  /*Consumed=3D*/false),
+           Element->getLocStart(), Element);
+}
+
+ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *Bas=
eExpr,
+                                        Expr *IndexExpr,
+                                        ObjCMethodDecl *getterMethod,
+                                        ObjCMethodDecl *setterMethod) {
+  // Feature support is for modern abi.
+  if (!LangOpts.ObjCNonFragileABI)
+    return ExprError();
+  // If the expression is type-dependent, there's nothing for us to do.
+  assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) =
&&
+          "base or index cannot have dependent type here");
+  ExprResult Result =3D CheckPlaceholderExpr(IndexExpr);
+  if (Result.isInvalid())
+    return ExprError();
+  IndexExpr =3D Result.get();
+ =20
+  // Perform lvalue-to-rvalue conversion.
+  Result =3D DefaultLvalueConversion(BaseExpr);
+  if (Result.isInvalid())
+    return ExprError();
+  BaseExpr =3D Result.get();
+  return Owned(ObjCSubscriptRefExpr::Create(Context,=20
+                                            BaseExpr,
+                                            IndexExpr,
+                                            Context.PseudoObjectTy,
+                                            getterMethod,
+                                            setterMethod, RB));
+ =20
+}
+
+ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elemen=
ts) {
+  // Look up the NSArray class, if we haven't done so already.
+  if (!NSArrayDecl) {
+    NamedDecl *IF =3D LookupSingleName(TUScope,
+                                 NSAPIObj->getNSClassId(NSAPI::ClassId_NSA=
rray),
+                                 SR.getBegin(),
+                                 LookupOrdinaryName);
+    NSArrayDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(IF);
+    if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
+      NSArrayDecl =3D  ObjCInterfaceDecl::Create (Context,
+                            Context.getTranslationUnitDecl(),
+                            SourceLocation(),
+                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
+                            0, SourceLocation());
+
+    if (!NSArrayDecl) {
+      Diag(SR.getBegin(), diag::err_undeclared_nsarray);
+      return ExprError();
+    }
+  }
+ =20
+  // Find the arrayWithObjects:count: method, if we haven't done so alread=
y.
+  QualType IdT =3D Context.getObjCIdType();
+  if (!ArrayWithObjectsMethod) {
+    Selector
+      Sel =3D NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCo=
unt);
+    ArrayWithObjectsMethod =3D NSArrayDecl->lookupClassMethod(Sel);
+    if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
+      TypeSourceInfo *ResultTInfo =3D 0;
+      ArrayWithObjectsMethod =3D
+                         ObjCMethodDecl::Create(Context,
+                           SourceLocation(), SourceLocation(), Sel,
+                           IdT,
+                           ResultTInfo,
+                           Context.getTranslationUnitDecl(),
+                           false /*Instance*/, false/*isVariadic*/,
+                           /*isSynthesized=3D*/false,
+                           /*isImplicitlyDeclared=3D*/true, /*isDefined=3D=
*/false,
+                           ObjCMethodDecl::Required,
+                           false);
+      SmallVector<ParmVarDecl *, 2> Params;
+      ParmVarDecl *objects =3D ParmVarDecl::Create(Context, ArrayWithObjec=
tsMethod,
+                                                SourceLocation(), SourceLo=
cation(),
+                                                &Context.Idents.get("objec=
ts"),
+                                                Context.getPointerType(IdT=
),
+                                                /*TInfo=3D*/0,
+                                                SC_None,
+                                                SC_None,
+                                                0);
+      Params.push_back(objects);
+      ParmVarDecl *cnt =3D ParmVarDecl::Create(Context, ArrayWithObjectsMe=
thod,
+                                                SourceLocation(), SourceLo=
cation(),
+                                                &Context.Idents.get("cnt"),
+                                                Context.UnsignedLongTy,
+                                                /*TInfo=3D*/0,
+                                                SC_None,
+                                                SC_None,
+                                                0);
+      Params.push_back(cnt);
+      ArrayWithObjectsMethod->setMethodParams(Context, Params,
+                                              ArrayRef<SourceLocation>());
+
+
+    }
+
+    if (!ArrayWithObjectsMethod) {
+      Diag(SR.getBegin(), diag::err_undeclared_arraywithobjects) << Sel;
+      return ExprError();
+    }
+  }
+ =20
+  // Make sure the return type is reasonable.
+  if (!ArrayWithObjectsMethod->getResultType()->isObjCObjectPointerType())=
 {
+    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
+      << ArrayWithObjectsMethod->getSelector();
+    Diag(ArrayWithObjectsMethod->getLocation(),
+         diag::note_objc_literal_method_return)
+      << ArrayWithObjectsMethod->getResultType();
+    return ExprError();
+  }
+
+  // Dig out the type that all elements should be converted to.
+  QualType T =3D ArrayWithObjectsMethod->param_begin()[0]->getType();
+  const PointerType *PtrT =3D T->getAs<PointerType>();
+  if (!PtrT ||=20
+      !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
+    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
+      << ArrayWithObjectsMethod->getSelector();
+    Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
+         diag::note_objc_literal_method_param)
+      << 0 << T=20
+      << Context.getPointerType(IdT.withConst());
+    return ExprError();
+  }
+  T =3D PtrT->getPointeeType();
+ =20
+  // Check that the 'count' parameter is integral.
+  if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType(=
)) {
+    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
+      << ArrayWithObjectsMethod->getSelector();
+    Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
+         diag::note_objc_literal_method_param)
+      << 1=20
+      << ArrayWithObjectsMethod->param_begin()[1]->getType()
+      << "integral";
+    return ExprError();
+  }
+
+  // Check that each of the elements provided is valid in a collection lit=
eral,
+  // performing conversions as necessary.
+  Expr **ElementsBuffer =3D Elements.get();
+  for (unsigned I =3D 0, N =3D Elements.size(); I !=3D N; ++I) {
+    ExprResult Converted =3D CheckObjCCollectionLiteralElement(*this,
+                                                             ElementsBuffe=
r[I],
+                                                             T);
+    if (Converted.isInvalid())
+      return ExprError();
+   =20
+    ElementsBuffer[I] =3D Converted.get();
+  }
+   =20
+  QualType Ty=20
+    =3D Context.getObjCObjectPointerType(
+                                    Context.getObjCInterfaceType(NSArrayDe=
cl));
+
+  return MaybeBindToTemporary(
+           ObjCArrayLiteral::Create(Context,=20
+                                    llvm::makeArrayRef(Elements.get(),=20
+                                                       Elements.size()),=20
+                                    Ty, ArrayWithObjectsMethod, SR));
+}
+
+ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,=20
+                                            ObjCDictionaryElement *Element=
s,
+                                            unsigned NumElements) {
+  // Look up the NSDictionary class, if we haven't done so already.
+  if (!NSDictionaryDecl) {
+    NamedDecl *IF =3D LookupSingleName(TUScope,
+                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictio=
nary),
+                            SR.getBegin(), LookupOrdinaryName);
+    NSDictionaryDecl =3D dyn_cast_or_null<ObjCInterfaceDecl>(IF);
+    if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
+      NSDictionaryDecl =3D  ObjCInterfaceDecl::Create (Context,
+                            Context.getTranslationUnitDecl(),
+                            SourceLocation(),
+                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictio=
nary),
+                            0, SourceLocation());
+
+    if (!NSDictionaryDecl) {
+      Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
+      return ExprError();   =20
+    }
+  }
+ =20
+  // Find the dictionaryWithObjects:forKeys:count: method, if we haven't d=
one
+  // so already.
+  QualType IdT =3D Context.getObjCIdType();
+  if (!DictionaryWithObjectsMethod) {
+    Selector Sel =3D NSAPIObj->getNSDictionarySelector(
+                                    NSAPI::NSDict_dictionaryWithObjectsFor=
KeysCount);
+    DictionaryWithObjectsMethod =3D NSDictionaryDecl->lookupClassMethod(Se=
l);
+    if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral)=
 {
+      DictionaryWithObjectsMethod =3D=20
+                         ObjCMethodDecl::Create(Context, =20
+                           SourceLocation(), SourceLocation(), Sel,
+                           IdT,
+                           0 /*TypeSourceInfo */,
+                           Context.getTranslationUnitDecl(),
+                           false /*Instance*/, false/*isVariadic*/,
+                           /*isSynthesized=3D*/false,
+                           /*isImplicitlyDeclared=3D*/true, /*isDefined=3D=
*/false,
+                           ObjCMethodDecl::Required,
+                           false);
+      SmallVector<ParmVarDecl *, 3> Params;
+      ParmVarDecl *objects =3D ParmVarDecl::Create(Context, DictionaryWith=
ObjectsMethod,
+                                                SourceLocation(), SourceLo=
cation(),
+                                                &Context.Idents.get("objec=
ts"),
+                                                Context.getPointerType(IdT=
),
+                                                /*TInfo=3D*/0,
+                                                SC_None,
+                                                SC_None,
+                                                0);
+      Params.push_back(objects);
+      ParmVarDecl *keys =3D ParmVarDecl::Create(Context, DictionaryWithObj=
ectsMethod,
+                                                SourceLocation(), SourceLo=
cation(),
+                                                &Context.Idents.get("keys"=
),
+                                                Context.getPointerType(IdT=
),
+                                                /*TInfo=3D*/0,
+                                                SC_None,
+                                                SC_None,
+                                                0);
+      Params.push_back(keys);
+      ParmVarDecl *cnt =3D ParmVarDecl::Create(Context, DictionaryWithObje=
ctsMethod,
+                                                SourceLocation(), SourceLo=
cation(),
+                                                &Context.Idents.get("cnt"),
+                                                Context.UnsignedLongTy,
+                                                /*TInfo=3D*/0,
+                                                SC_None,
+                                                SC_None,
+                                                0);
+      Params.push_back(cnt);
+      DictionaryWithObjectsMethod->setMethodParams(Context, Params,=20
+                                                   ArrayRef<SourceLocation=
>());
+    }
+
+    if (!DictionaryWithObjectsMethod) {
+      Diag(SR.getBegin(), diag::err_undeclared_dictwithobjects) << Sel;
+      return ExprError();   =20
+    }
+  }
+ =20
+  // Make sure the return type is reasonable.
+  if (!DictionaryWithObjectsMethod->getResultType()->isObjCObjectPointerTy=
pe()){
+    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
+    << DictionaryWithObjectsMethod->getSelector();
+    Diag(DictionaryWithObjectsMethod->getLocation(),
+         diag::note_objc_literal_method_return)
+    << DictionaryWithObjectsMethod->getResultType();
+    return ExprError();
+  }
+
+  // Dig out the type that all values should be converted to.
+  QualType ValueT =3D  DictionaryWithObjectsMethod->param_begin()[0]->getT=
ype();
+  const PointerType *PtrValue =3D ValueT->getAs<PointerType>();
+  if (!PtrValue ||=20
+      !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
+    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
+      << DictionaryWithObjectsMethod->getSelector();
+    Diag(DictionaryWithObjectsMethod->param_begin()[0]->getLocation(),
+         diag::note_objc_literal_method_param)
+      << 0 << ValueT
+      << Context.getPointerType(IdT.withConst());
+    return ExprError();
+  }
+  ValueT =3D PtrValue->getPointeeType();
+
+  // Dig out the type that all keys should be converted to.
+  QualType KeyT =3D DictionaryWithObjectsMethod->param_begin()[1]->getType=
();
+  const PointerType *PtrKey =3D KeyT->getAs<PointerType>();
+  if (!PtrKey ||=20
+      !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
+                                      IdT)) {
+    bool err =3D true;
+    if (PtrKey) {
+      if (QIDNSCopying.isNull()) {
+        // key argument of selector is id<NSCopying>?
+        if (ObjCProtocolDecl *NSCopyingPDecl =3D
+            LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin()=
)) {
+          ObjCProtocolDecl *PQ[] =3D {NSCopyingPDecl};
+          QIDNSCopying =3D=20
+            Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
+                                      (ObjCProtocolDecl**) PQ,1);
+          QIDNSCopying =3D Context.getObjCObjectPointerType(QIDNSCopying);
+        }
+      }
+      if (!QIDNSCopying.isNull())
+        err =3D !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
+                                              QIDNSCopying);
+    }
+   =20
+    if (err) {
+      Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
+        << DictionaryWithObjectsMethod->getSelector();
+      Diag(DictionaryWithObjectsMethod->param_begin()[1]->getLocation(),
+           diag::note_objc_literal_method_param)
+        << 1 << KeyT
+        << Context.getPointerType(IdT.withConst());
+      return ExprError();
+    }
+  }
+  KeyT =3D PtrKey->getPointeeType();
+
+  // Check that the 'count' parameter is integral.
+  if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
+                                                            ->isIntegerTyp=
e()) {
+    Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
+      << DictionaryWithObjectsMethod->getSelector();
+    Diag(DictionaryWithObjectsMethod->param_begin()[2]->getLocation(),
+         diag::note_objc_literal_method_param)
+      << 2
+      << DictionaryWithObjectsMethod->param_begin()[2]->getType()
+      << "integral";
+    return ExprError();
+  }
+
+  // Check that each of the keys and values provided is valid in a collect=
ion=20
+  // literal, performing conversions as necessary.
+  bool HasPackExpansions =3D false;
+  for (unsigned I =3D 0, N =3D NumElements; I !=3D N; ++I) {
+    // Check the key.
+    ExprResult Key =3D CheckObjCCollectionLiteralElement(*this, Elements[I=
].Key,=20
+                                                       KeyT);
+    if (Key.isInvalid())
+      return ExprError();
+   =20
+    // Check the value.
+    ExprResult Value
+      =3D CheckObjCCollectionLiteralElement(*this, Elements[I].Value, Valu=
eT);
+    if (Value.isInvalid())
+      return ExprError();
+   =20
+    Elements[I].Key =3D Key.get();
+    Elements[I].Value =3D Value.get();
+   =20
+    if (Elements[I].EllipsisLoc.isInvalid())
+      continue;
+   =20
+    if (!Elements[I].Key->containsUnexpandedParameterPack() &&
+        !Elements[I].Value->containsUnexpandedParameterPack()) {
+      Diag(Elements[I].EllipsisLoc,=20
+           diag::err_pack_expansion_without_parameter_packs)
+        << SourceRange(Elements[I].Key->getLocStart(),
+                       Elements[I].Value->getLocEnd());
+      return ExprError();
+    }
+   =20
+    HasPackExpansions =3D true;
+  }
+
+ =20
+  QualType Ty
+    =3D Context.getObjCObjectPointerType(
+                                Context.getObjCInterfaceType(NSDictionaryD=
ecl)); =20
+  return MaybeBindToTemporary(
+           ObjCDictionaryLiteral::Create(Context,=20
+                                         llvm::makeArrayRef(Elements,=20
+                                                            NumElements),
+                                         HasPackExpansions,
+                                         Ty,=20
+                                         DictionaryWithObjectsMethod, SR));
 }
=20
 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
@@ -144,7 +768,7 @@
     // which is an array type.
     StrTy =3D Context.CharTy;
     // A C++ string literal has a const-qualified element type (C++ 2.13.4=
p1).
-    if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
+    if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
       StrTy.addConst();
     StrTy =3D Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size=
()+1),
                                          ArrayType::Normal, 0);
@@ -191,7 +815,7 @@
=20
   // In ARC, forbid the user from using @selector for=20
   // retain/release/autorelease/dealloc/retainCount.
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     switch (Sel.getMethodFamily()) {
     case OMF_retain:
     case OMF_release:
@@ -237,14 +861,8 @@
 }
=20
 /// Try to capture an implicit reference to 'self'.
-ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
-  // Ignore block scopes: we can capture through them.
-  DeclContext *DC =3D CurContext;
-  while (true) {
-    if (isa<BlockDecl>(DC)) DC =3D cast<BlockDecl>(DC)->getDeclContext();
-    else if (isa<EnumDecl>(DC)) DC =3D cast<EnumDecl>(DC)->getDeclContext(=
);
-    else break;
-  }
+ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
+  DeclContext *DC =3D getFunctionLevelDeclContext();
=20
   // If we're not in an ObjC method, error out.  Note that, unlike the
   // C++ case, we don't require an instance method --- class methods
@@ -253,22 +871,7 @@
   if (!method)
     return 0;
=20
-  ImplicitParamDecl *self =3D method->getSelfDecl();
-  assert(self && "capturing 'self' in non-definition?");
-
-  // Mark that we're closing on 'this' in all the block scopes, if applica=
ble.
-  for (unsigned idx =3D FunctionScopes.size() - 1;
-       isa<BlockScopeInfo>(FunctionScopes[idx]);
-       --idx) {
-    BlockScopeInfo *blockScope =3D cast<BlockScopeInfo>(FunctionScopes[idx=
]);
-    unsigned &captureIndex =3D blockScope->CaptureMap[self];
-    if (captureIndex) break;
-
-    bool nested =3D isa<BlockScopeInfo>(FunctionScopes[idx-1]);
-    blockScope->Captures.push_back(
-              BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0=
));
-    captureIndex =3D blockScope->Captures.size(); // +1
-  }
+  tryCaptureVariable(method->getSelfDecl(), Loc);
=20
   return method;
 }
@@ -365,18 +968,18 @@
     }
=20
     unsigned DiagID;
-    if (getLangOptions().ObjCAutoRefCount)
+    if (getLangOpts().ObjCAutoRefCount)
       DiagID =3D diag::err_arc_method_not_found;
     else
       DiagID =3D isClassMessage ? diag::warn_class_method_not_found
                               : diag::warn_inst_method_not_found;
-    if (!getLangOptions().DebuggerSupport)
+    if (!getLangOpts().DebuggerSupport)
       Diag(lbrac, DiagID)
         << Sel << isClassMessage << SourceRange(lbrac, rbrac);
=20
     // In debuggers, we want to use __unknown_anytype for these
     // results so that clients can cast them.
-    if (getLangOptions().DebuggerSupport) {
+    if (getLangOpts().DebuggerSupport) {
       ReturnType =3D Context.UnknownAnyTy;
     } else {
       ReturnType =3D Context.getObjCIdType();
@@ -409,17 +1012,23 @@
=20
     Expr *argExpr =3D Args[i];
=20
-    ParmVarDecl *Param =3D Method->param_begin()[i];
+    ParmVarDecl *param =3D Method->param_begin()[i];
     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
=20
+    // Strip the unbridged-cast placeholder expression off unless it's
+    // a consumed argument.
+    if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
+        !param->hasAttr<CFConsumedAttr>())
+      argExpr =3D stripARCUnbridgedCast(argExpr);
+
     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
-                            Param->getType(),
+                            param->getType(),
                             PDiag(diag::err_call_incomplete_argument)
                               << argExpr->getSourceRange()))
       return true;
=20
     InitializedEntity Entity =3D InitializedEntity::InitializeParameter(Co=
ntext,
-                                                                      Para=
m);
+                                                                      para=
m);
     ExprResult ArgE =3D PerformCopyInitialization(Entity, lbrac, Owned(arg=
Expr));
     if (ArgE.isInvalid())
       IsError =3D true;
@@ -448,27 +1057,24 @@
                        Args[NumArgs-1]->getLocEnd());
     }
   }
-  // diagnose nonnull arguments.
-  for (specific_attr_iterator<NonNullAttr>
-       i =3D Method->specific_attr_begin<NonNullAttr>(),
-       e =3D Method->specific_attr_end<NonNullAttr>(); i !=3D e; ++i) {
-    CheckNonNullArguments(*i, Args, lbrac);
-  }
=20
   DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
+
+  // Do additional checkings on method.
+  IsError |=3D CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
+
   return IsError;
 }
=20
 bool Sema::isSelfExpr(Expr *receiver) {
   // 'self' is objc 'self' in an objc method only.
-  DeclContext *DC =3D CurContext;
-  while (isa<BlockDecl>(DC))
-    DC =3D DC->getParent();
-  if (DC && !isa<ObjCMethodDecl>(DC))
-    return false;
+  ObjCMethodDecl *method =3D
+    dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
+  if (!method) return false;
+
   receiver =3D receiver->IgnoreParenLValueCasts();
   if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(receiver))
-    if (DRE->getDecl()->getIdentifier() =3D=3D &Context.Idents.get("self"))
+    if (DRE->getDecl() =3D=3D method->getSelfDecl())
       return true;
   return false;
 }
@@ -507,6 +1113,9 @@
=20
 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
                                               ObjCInterfaceDecl *ClassDecl=
) {
+  if (!ClassDecl->hasDefinition())
+    return 0;
+
   ObjCMethodDecl *Method =3D 0;
   while (ClassDecl && !Method) {
     // If we have implementations in scope, check "private" methods.
@@ -521,6 +1130,35 @@
   return Method;
 }
=20
+/// LookupMethodInType - Look up a method in an ObjCObjectType.
+ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
+                                               bool isInstance) {
+  const ObjCObjectType *objType =3D type->castAs<ObjCObjectType>();
+  if (ObjCInterfaceDecl *iface =3D objType->getInterface()) {
+    // Look it up in the main interface (and categories, etc.)
+    if (ObjCMethodDecl *method =3D iface->lookupMethod(sel, isInstance))
+      return method;
+
+    // Okay, look for "private" methods declared in any
+    // @implementations we've seen.
+    if (isInstance) {
+      if (ObjCMethodDecl *method =3D LookupPrivateInstanceMethod(sel, ifac=
e))
+        return method;
+    } else {
+      if (ObjCMethodDecl *method =3D LookupPrivateClassMethod(sel, iface))
+        return method;
+    }
+  }
+
+  // Check qualifiers.
+  for (ObjCObjectType::qual_iterator
+         i =3D objType->qual_begin(), e =3D objType->qual_end(); i !=3D e;=
 ++i)
+    if (ObjCMethodDecl *method =3D (*i)->lookupMethod(sel, isInstance))
+      return method;
+
+  return 0;
+}
+
 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifie=
r=20
 /// list of a qualified objective pointer type.
 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
@@ -557,35 +1195,26 @@
   }
  =20
   IdentifierInfo *Member =3D MemberName.getAsIdentifierInfo();
-
-  if (IFace->isForwardDecl()) {
-    Diag(MemberLoc, diag::err_property_not_found_forward_class)
-         << MemberName << QualType(OPT, 0);
-    Diag(IFace->getLocation(), diag::note_forward_class);
+  SourceRange BaseRange =3D Super? SourceRange(SuperLoc)
+                               : BaseExpr->getSourceRange();
+  if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),=20
+                          PDiag(diag::err_property_not_found_forward_class)
+                            << MemberName << BaseRange))
     return ExprError();
-  }
+ =20
   // Search for a declared property first.
   if (ObjCPropertyDecl *PD =3D IFace->FindPropertyDeclaration(Member)) {
     // Check whether we can reference this property.
     if (DiagnoseUseOfDecl(PD, MemberLoc))
       return ExprError();
-    QualType ResTy =3D PD->getType();
-    ResTy =3D ResTy.getNonLValueExprType(Context);
-    Selector Sel =3D PP.getSelectorTable().getNullarySelector(Member);
-    ObjCMethodDecl *Getter =3D IFace->lookupInstanceMethod(Sel);
-    if (Getter &&
-        (Getter->hasRelatedResultType()
-         || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
-        ResTy =3D getMessageSendResultType(QualType(OPT, 0), Getter, false=
,=20
-                                         Super);
             =20
     if (Super)
-      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
+      return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObj=
ectTy,
                                                      VK_LValue, OK_ObjCPro=
perty,
                                                      MemberLoc,=20
                                                      SuperLoc, SuperType));
     else
-      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
+      return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObj=
ectTy,
                                                      VK_LValue, OK_ObjCPro=
perty,
                                                      MemberLoc, BaseExpr));
   }
@@ -597,17 +1226,16 @@
       if (DiagnoseUseOfDecl(PD, MemberLoc))
         return ExprError();
      =20
-      QualType T =3D PD->getType();
-      if (ObjCMethodDecl *Getter =3D PD->getGetterMethodDecl())
-        T =3D getMessageSendResultType(QualType(OPT, 0), Getter, false, Su=
per);
       if (Super)
-        return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
+        return Owned(new (Context) ObjCPropertyRefExpr(PD,
+                                                       Context.PseudoObjec=
tTy,
                                                        VK_LValue,
                                                        OK_ObjCProperty,
                                                        MemberLoc,=20
                                                        SuperLoc, SuperType=
));
       else
-        return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
+        return Owned(new (Context) ObjCPropertyRefExpr(PD,
+                                                       Context.PseudoObjec=
tTy,
                                                        VK_LValue,
                                                        OK_ObjCProperty,
                                                        MemberLoc,
@@ -662,38 +1290,27 @@
     return ExprError();
=20
   if (Getter || Setter) {
-    QualType PType;
-    if (Getter)
-      PType =3D getMessageSendResultType(QualType(OPT, 0), Getter, false, =
Super);
-    else {
-      ParmVarDecl *ArgDecl =3D *Setter->param_begin();
-      PType =3D ArgDecl->getType();
-    }
-   =20
-    ExprValueKind VK =3D VK_LValue;
-    ExprObjectKind OK =3D OK_ObjCProperty;
-    if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
-        PType->isVoidType())
-      VK =3D VK_RValue, OK =3D OK_Ordinary;
-
     if (Super)
       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
-                                                     PType, VK, OK,
+                                                     Context.PseudoObjectT=
y,
+                                                     VK_LValue, OK_ObjCPro=
perty,
                                                      MemberLoc,
                                                      SuperLoc, SuperType));
     else
       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
-                                                     PType, VK, OK,
+                                                     Context.PseudoObjectT=
y,
+                                                     VK_LValue, OK_ObjCPro=
perty,
                                                      MemberLoc, BaseExpr));
=20
   }
=20
   // Attempt to correct for typos in property names.
-  TypoCorrection Corrected =3D CorrectTypo(
+  DeclFilterCCC<ObjCPropertyDecl> Validator;
+  if (TypoCorrection Corrected =3D CorrectTypo(
       DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
-      NULL, IFace, false, CTC_NoKeywords, OPT);
-  if (ObjCPropertyDecl *Property =3D
-      Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
+      NULL, Validator, IFace, false, OPT)) {
+    ObjCPropertyDecl *Property =3D
+        Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
     DeclarationName TypoResult =3D Corrected.getCorrection();
     Diag(MemberLoc, diag::err_property_not_found_suggest)
       << MemberName << QualType(OPT, 0) << TypoResult
@@ -710,14 +1327,10 @@
     QualType T =3D Ivar->getType();
     if (const ObjCObjectPointerType * OBJPT =3D=20
         T->getAsObjCInterfacePointerType()) {
-      const ObjCInterfaceType *IFaceT =3D OBJPT->getInterfaceType();
-      if (ObjCInterfaceDecl *IFace =3D IFaceT->getDecl())
-        if (IFace->isForwardDecl()) {
-          Diag(MemberLoc, diag::err_property_not_as_forward_class)
-          << MemberName << IFace;
-          Diag(IFace->getLocation(), diag::note_forward_class);
-          return ExprError();
-        }
+      if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),=20
+                              PDiag(diag::err_property_not_as_forward_clas=
s)
+                                << MemberName << BaseExpr->getSourceRange(=
)))
+        return ExprError();
     }
     Diag(MemberLoc,=20
          diag::err_ivar_access_using_property_syntax_suggest)
@@ -753,7 +1366,7 @@
     if (receiverNamePtr->isStr("super")) {
       IsSuper =3D true;
=20
-      if (ObjCMethodDecl *CurMethod =3D tryCaptureObjCSelf()) {
+      if (ObjCMethodDecl *CurMethod =3D tryCaptureObjCSelf(receiverNameLoc=
)) {
         if (CurMethod->isInstanceMethod()) {
           QualType T =3D=20
             Context.getObjCInterfaceType(CurMethod->getClassInterface());
@@ -819,34 +1432,17 @@
     return ExprError();
=20
   if (Getter || Setter) {
-    QualType PType;
-
-    ExprValueKind VK =3D VK_LValue;
-    if (Getter) {
-      PType =3D getMessageSendResultType(Context.getObjCInterfaceType(IFac=
e),
-                                       Getter, true,=20
-                                       receiverNamePtr->isStr("super"));
-      if (!getLangOptions().CPlusPlus &&
-          !PType.hasQualifiers() && PType->isVoidType())
-        VK =3D VK_RValue;
-    } else {
-      for (ObjCMethodDecl::param_iterator PI =3D Setter->param_begin(),
-           E =3D Setter->param_end(); PI !=3D E; ++PI)
-        PType =3D (*PI)->getType();
-      VK =3D VK_LValue;
-    }
-
-    ExprObjectKind OK =3D (VK =3D=3D VK_RValue ? OK_Ordinary : OK_ObjCProp=
erty);
-
     if (IsSuper)
     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
-                                                   PType, VK, OK,
+                                                   Context.PseudoObjectTy,
+                                                   VK_LValue, OK_ObjCPrope=
rty,
                                                    propertyNameLoc,
                                                    receiverNameLoc,=20
                                           Context.getObjCInterfaceType(IFa=
ce)));
=20
     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
-                                                   PType, VK, OK,
+                                                   Context.PseudoObjectTy,
+                                                   VK_LValue, OK_ObjCPrope=
rty,
                                                    propertyNameLoc,
                                                    receiverNameLoc, IFace)=
);
   }
@@ -854,6 +1450,24 @@
                      << &propertyName << Context.getObjCInterfaceType(IFac=
e));
 }
=20
+namespace {
+
+class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
+ public:
+  ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
+    // Determine whether "super" is acceptable in the current context.
+    if (Method && Method->getClassInterface())
+      WantObjCSuper =3D Method->getClassInterface()->getSuperClass();
+  }
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
+        candidate.isKeyword("super");
+  }
+};
+
+}
+
 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
                                                IdentifierInfo *Name,
                                                SourceLocation NameLoc,
@@ -878,6 +1492,11 @@
     // FIXME: This is a hack. Ivar lookup should be part of normal
     // lookup.
     if (ObjCMethodDecl *Method =3D getCurMethodDecl()) {
+      if (!Method->getClassInterface()) {
+        // Fall back: let the parser try to parse it as an instance messag=
e.
+        return ObjCInstanceMessage;
+      }
+
       ObjCInterfaceDecl *ClassDeclared;
       if (Method->getClassInterface()->lookupInstanceVariable(Name,=20
                                                               ClassDeclare=
d))
@@ -918,39 +1537,32 @@
   }
   }
=20
-  // Determine our typo-correction context.
-  CorrectTypoContext CTC =3D CTC_Expression;
-  if (ObjCMethodDecl *Method =3D getCurMethodDecl())
-    if (Method->getClassInterface() &&
-        Method->getClassInterface()->getSuperClass())
-      CTC =3D CTC_ObjCMessageReceiver;
-     =20
+  ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
   if (TypoCorrection Corrected =3D CorrectTypo(Result.getLookupNameInfo(),
                                              Result.getLookupKind(), S, NU=
LL,
-                                             NULL, false, CTC)) {
-    if (NamedDecl *ND =3D Corrected.getCorrectionDecl()) {
-      // If we found a declaration, correct when it refers to an Objective=
-C
-      // class.
-      if (ObjCInterfaceDecl *Class =3D dyn_cast<ObjCInterfaceDecl>(ND)) {
-        Diag(NameLoc, diag::err_unknown_receiver_suggest)
-          << Name << Corrected.getCorrection()
-          << FixItHint::CreateReplacement(SourceRange(NameLoc),
-                                          ND->getNameAsString());
-        Diag(ND->getLocation(), diag::note_previous_decl)
-          << Corrected.getCorrection();
-
-        QualType T =3D Context.getObjCInterfaceType(Class);
-        TypeSourceInfo *TSInfo =3D Context.getTrivialTypeSourceInfo(T, Nam=
eLoc);
-        ReceiverType =3D CreateParsedType(T, TSInfo);
-        return ObjCClassMessage;
-      }
-    } else if (Corrected.isKeyword() &&
-               Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
-      // If we've found the keyword "super", this is a send to super.
+                                             Validator)) {
+    if (Corrected.isKeyword()) {
+      // If we've found the keyword "super" (the only keyword that would be
+      // returned by CorrectTypo), this is a send to super.
       Diag(NameLoc, diag::err_unknown_receiver_suggest)
         << Name << Corrected.getCorrection()
         << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
       return ObjCSuperMessage;
+    } else if (ObjCInterfaceDecl *Class =3D
+               Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
+      // If we found a declaration, correct when it refers to an Objective=
-C
+      // class.
+      Diag(NameLoc, diag::err_unknown_receiver_suggest)
+        << Name << Corrected.getCorrection()
+        << FixItHint::CreateReplacement(SourceRange(NameLoc),
+                                        Class->getNameAsString());
+      Diag(Class->getLocation(), diag::note_previous_decl)
+        << Corrected.getCorrection();
+
+      QualType T =3D Context.getObjCInterfaceType(Class);
+      TypeSourceInfo *TSInfo =3D Context.getTrivialTypeSourceInfo(T, NameL=
oc);
+      ReceiverType =3D CreateParsedType(T, TSInfo);
+      return ObjCClassMessage;
     }
   }
  =20
@@ -966,7 +1578,7 @@
                                    SourceLocation RBracLoc,
                                    MultiExprArg Args) {
   // Determine whether we are inside a method or not.
-  ObjCMethodDecl *Method =3D tryCaptureObjCSelf();
+  ObjCMethodDecl *Method =3D tryCaptureObjCSelf(SuperLoc);
   if (!Method) {
     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
     return ExprError();
@@ -1012,6 +1624,68 @@
                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
 }
=20
+
+ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
+                                           bool isSuperReceiver,
+                                           SourceLocation Loc,
+                                           Selector Sel,
+                                           ObjCMethodDecl *Method,
+                                           MultiExprArg Args) {
+  TypeSourceInfo *receiverTypeInfo =3D 0;
+  if (!ReceiverType.isNull())
+    receiverTypeInfo =3D Context.getTrivialTypeSourceInfo(ReceiverType);
+
+  return BuildClassMessage(receiverTypeInfo, ReceiverType,
+                          /*SuperLoc=3D*/isSuperReceiver ? Loc : SourceLoc=
ation(),
+                           Sel, Method, Loc, Loc, Loc, Args,
+                           /*isImplicit=3D*/true);
+
+}
+
+static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
+                               unsigned DiagID,
+                               bool (*refactor)(const ObjCMessageExpr *,
+                                              const NSAPI &, edit::Commit =
&)) {
+  SourceLocation MsgLoc =3D Msg->getExprLoc();
+  if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) =3D=3D DiagnosticsEngine:=
:Ignored)
+    return;
+
+  SourceManager &SM =3D S.SourceMgr;
+  edit::Commit ECommit(SM, S.LangOpts);
+  if (refactor(Msg,*S.NSAPIObj, ECommit)) {
+    DiagnosticBuilder Builder =3D S.Diag(MsgLoc, DiagID)
+                        << Msg->getSelector() << Msg->getSourceRange();
+    // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
+    if (!ECommit.isCommitable())
+      return;
+    for (edit::Commit::edit_iterator
+           I =3D ECommit.edit_begin(), E =3D ECommit.edit_end(); I !=3D E;=
 ++I) {
+      const edit::Commit::Edit &Edit =3D *I;
+      switch (Edit.Kind) {
+      case edit::Commit::Act_Insert:
+        Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
+                                                        Edit.Text,
+                                                        Edit.BeforePrev));
+        break;
+      case edit::Commit::Act_InsertFromRange:
+        Builder.AddFixItHint(
+            FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
+                                                Edit.getInsertFromRange(SM=
),
+                                                Edit.BeforePrev));
+        break;
+      case edit::Commit::Act_Remove:
+        Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM=
)));
+        break;
+      }
+    }
+  }
+}
+
+static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
+  applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
+                     edit::rewriteObjCRedundantCallWithLiteral);
+}
+
 /// \brief Build an Objective-C class message expression.
 ///
 /// This routine takes care of both normal class messages and
@@ -1048,7 +1722,8 @@
                                    SourceLocation LBracLoc,=20
                                    ArrayRef<SourceLocation> SelectorLocs,
                                    SourceLocation RBracLoc,
-                                   MultiExprArg ArgsIn) {
+                                   MultiExprArg ArgsIn,
+                                   bool isImplicit) {
   SourceLocation Loc =3D SuperLoc.isValid()? SuperLoc
     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
   if (LBracLoc.isInvalid()) {
@@ -1066,7 +1741,8 @@
     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
                                          VK_RValue, LBracLoc, ReceiverType=
Info,
                                          Sel, SelectorLocs, /*Method=3D*/0,
-                                         makeArrayRef(Args, NumArgs),RBrac=
Loc));
+                                         makeArrayRef(Args, NumArgs),RBrac=
Loc,
+                                         isImplicit));
   }
  =20
   // Find the class to which we are sending this message.
@@ -1078,20 +1754,23 @@
     return ExprError();
   }
   assert(Class && "We don't know which class we're messaging?");
-  (void)DiagnoseUseOfDecl(Class, Loc);
+  // objc++ diagnoses during typename annotation.
+  if (!getLangOpts().CPlusPlus)
+    (void)DiagnoseUseOfDecl(Class, Loc);
   // Find the method we are messaging.
   if (!Method) {
-    if (Class->isForwardDecl()) {
-      if (getLangOptions().ObjCAutoRefCount) {
-        Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
-      } else {
-        Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName=
();
-      }
-
+    SourceRange TypeRange=20
+      =3D SuperLoc.isValid()? SourceRange(SuperLoc)
+                          : ReceiverTypeInfo->getTypeLoc().getSourceRange(=
);
+    if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),=20
+                            (getLangOpts().ObjCAutoRefCount
+                               ? PDiag(diag::err_arc_receiver_forward_clas=
s)
+                               : PDiag(diag::warn_receiver_forward_class))
+                                   << TypeRange)) {
       // A forward class used in messaging is treated as a 'Class'
       Method =3D LookupFactoryMethodInGlobalPool(Sel,=20
                                                SourceRange(LBracLoc, RBrac=
Loc));
-      if (Method && !getLangOptions().ObjCAutoRefCount)
+      if (Method && !getLangOpts().ObjCAutoRefCount)
         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
           << Method->getDeclName();
     }
@@ -1123,18 +1802,21 @@
     return ExprError();
=20
   // Construct the appropriate ObjCMessageExpr.
-  Expr *Result;
+  ObjCMessageExpr *Result;
   if (SuperLoc.isValid())
     Result =3D ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,=20
                                      SuperLoc, /*IsInstanceSuper=3D*/false=
,=20
                                      ReceiverType, Sel, SelectorLocs,
                                      Method, makeArrayRef(Args, NumArgs),
-                                     RBracLoc);
-  else
+                                     RBracLoc, isImplicit);
+  else {
     Result =3D ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,=20
                                      ReceiverTypeInfo, Sel, SelectorLocs,
                                      Method, makeArrayRef(Args, NumArgs),
-                                     RBracLoc);
+                                     RBracLoc, isImplicit);
+    if (!isImplicit)
+      checkCocoaAPI(*this, Result);
+  }
   return MaybeBindToTemporary(Result);
 }
=20
@@ -1162,6 +1844,18 @@
                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
 }
=20
+ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
+                                              QualType ReceiverType,
+                                              SourceLocation Loc,
+                                              Selector Sel,
+                                              ObjCMethodDecl *Method,
+                                              MultiExprArg Args) {
+  return BuildInstanceMessage(Receiver, ReceiverType,
+                              /*SuperLoc=3D*/!Receiver ? Loc : SourceLocat=
ion(),
+                              Sel, Method, Loc, Loc, Loc, Args,
+                              /*isImplicit=3D*/true);
+}
+
 /// \brief Build an Objective-C instance message expression.
 ///
 /// This routine takes care of both normal instance messages and
@@ -1198,7 +1892,8 @@
                                       SourceLocation LBracLoc,=20
                                       ArrayRef<SourceLocation> SelectorLoc=
s,
                                       SourceLocation RBracLoc,
-                                      MultiExprArg ArgsIn) {
+                                      MultiExprArg ArgsIn,
+                                      bool isImplicit) {
   // The location of the receiver.
   SourceLocation Loc =3D SuperLoc.isValid()? SuperLoc : Receiver->getLocSt=
art();
  =20
@@ -1211,6 +1906,16 @@
   // If we have a receiver expression, perform appropriate promotions
   // and determine receiver type.
   if (Receiver) {
+    if (Receiver->hasPlaceholderType()) {
+      ExprResult Result;
+      if (Receiver->getType() =3D=3D Context.UnknownAnyTy)
+        Result =3D forceUnknownAnyToType(Receiver, Context.getObjCIdType()=
);
+      else
+        Result =3D CheckPlaceholderExpr(Receiver);
+      if (Result.isInvalid()) return ExprError();
+      Receiver =3D Result.take();
+    }
+
     if (Receiver->isTypeDependent()) {
       // If the receiver is type-dependent, we can't type-check anything
       // at this point. Build a dependent expression.
@@ -1221,7 +1926,7 @@
                                            VK_RValue, LBracLoc, Receiver, =
Sel,=20
                                            SelectorLocs, /*Method=3D*/0,
                                            makeArrayRef(Args, NumArgs),
-                                           RBracLoc));
+                                           RBracLoc, isImplicit));
     }
=20
     // If necessary, apply function/array conversion to the receiver.
@@ -1260,7 +1965,8 @@
           if (Method) {
             Diag(Loc, diag::warn_instance_method_on_class_found)
               << Method->getSelector() << Sel;
-            Diag(Method->getLocation(), diag::note_method_declared_at);
+            Diag(Method->getLocation(), diag::note_method_declared_at)
+              << Method->getDeclName();
           }
         }
       } else {
@@ -1314,28 +2020,37 @@
         // We allow sending a message to a pointer to an interface (an obj=
ect).
         ClassDecl =3D OCIType->getInterfaceDecl();
=20
-        if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCoun=
t) {
-          Diag(Loc, diag::err_arc_receiver_forward_instance)
-            << OCIType->getPointeeType()
-            << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperL=
oc));
-          return ExprError();
+        // Try to complete the type. Under ARC, this is a hard error from =
which
+        // we don't try to recover.
+        const ObjCInterfaceDecl *forwardClass =3D 0;
+        if (RequireCompleteType(Loc, OCIType->getPointeeType(),
+              getLangOpts().ObjCAutoRefCount
+                ? PDiag(diag::err_arc_receiver_forward_instance)
+                    << (Receiver ? Receiver->getSourceRange()=20
+                                 : SourceRange(SuperLoc))
+                : PDiag(diag::warn_receiver_forward_instance)
+                    << (Receiver ? Receiver->getSourceRange()=20
+                                 : SourceRange(SuperLoc)))) {
+          if (getLangOpts().ObjCAutoRefCount)
+            return ExprError();
+         =20
+          forwardClass =3D OCIType->getInterfaceDecl();
+          Diag(Receiver ? Receiver->getLocStart()=20
+                        : SuperLoc, diag::note_receiver_is_id);
+          Method =3D 0;
+        } else {
+          Method =3D ClassDecl->lookupInstanceMethod(Sel);
         }
=20
-        // FIXME: consider using LookupInstanceMethodInGlobalPool, since i=
t will be
-        // faster than the following method (which can do *many* linear se=
arches).
-        // The idea is to add class info to MethodPool.
-        Method =3D ClassDecl->lookupInstanceMethod(Sel);
-
         if (!Method)
           // Search protocol qualifiers.
           Method =3D LookupMethodInQualifiedType(Sel, OCIType, true);
        =20
-        const ObjCInterfaceDecl *forwardClass =3D 0;
         if (!Method) {
           // If we have implementations in scope, check "private" methods.
           Method =3D LookupPrivateInstanceMethod(Sel, ClassDecl);
=20
-          if (!Method && getLangOptions().ObjCAutoRefCount) {
+          if (!Method && getLangOpts().ObjCAutoRefCount) {
             Diag(Loc, diag::err_arc_may_not_respond)
               << OCIType->getPointeeType() << Sel;
             return ExprError();
@@ -1348,8 +2063,6 @@
             if (OCIType->qual_empty()) {
               Method =3D LookupInstanceMethodInGlobalPool(Sel,
                                                  SourceRange(LBracLoc, RBr=
acLoc));
-              if (OCIType->getInterfaceDecl()->isForwardDecl())
-                forwardClass =3D OCIType->getInterfaceDecl();
               if (Method && !forwardClass)
                 Diag(Loc, diag::warn_maynot_respond)
                   << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
@@ -1358,7 +2071,7 @@
         }
         if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
           return ExprError();
-      } else if (!getLangOptions().ObjCAutoRefCount &&
+      } else if (!getLangOpts().ObjCAutoRefCount &&
                  !Context.getObjCIdType().isNull() &&
                  (ReceiverType->isPointerType() ||=20
                   ReceiverType->isIntegerType())) {
@@ -1380,7 +2093,7 @@
         ReceiverType =3D Receiver->getType();
       } else {
         ExprResult ReceiverRes;
-        if (getLangOptions().CPlusPlus)
+        if (getLangOpts().CPlusPlus)
           ReceiverRes =3D PerformContextuallyConvertToObjCPointer(Receiver=
);
         if (ReceiverRes.isUsable()) {
           Receiver =3D ReceiverRes.take();
@@ -1424,7 +2137,7 @@
=20
   // In ARC, forbid the user from sending messages to=20
   // retain/release/autorelease/dealloc/retainCount explicitly.
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     ObjCMethodFamily family =3D
       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
     switch (family) {
@@ -1475,7 +2188,8 @@
                   // selector names a +1 method=20
                   Diag(SelLoc,=20
                        diag::err_arc_perform_selector_retains);
-                  Diag(SelMethod->getLocation(), diag::note_method_declare=
d_at);
+                  Diag(SelMethod->getLocation(), diag::note_method_declare=
d_at)
+                    << SelMethod->getDeclName();
                 }
                 break;
               default:
@@ -1484,7 +2198,8 @@
                   // selector names a +1 method
                   Diag(SelLoc,=20
                        diag::err_arc_perform_selector_retains);
-                  Diag(SelMethod->getLocation(), diag::note_method_declare=
d_at);
+                  Diag(SelMethod->getLocation(), diag::note_method_declare=
d_at)
+                    << SelMethod->getDeclName();
                 }
                 break;
             }
@@ -1505,13 +2220,23 @@
     Result =3D ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
                                      SuperLoc,  /*IsInstanceSuper=3D*/true,
                                      ReceiverType, Sel, SelectorLocs, Meth=
od,=20
-                                     makeArrayRef(Args, NumArgs), RBracLoc=
);
-  else
+                                     makeArrayRef(Args, NumArgs), RBracLoc,
+                                     isImplicit);
+  else {
     Result =3D ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
                                      Receiver, Sel, SelectorLocs, Method,
-                                     makeArrayRef(Args, NumArgs), RBracLoc=
);
+                                     makeArrayRef(Args, NumArgs), RBracLoc,
+                                     isImplicit);
+    if (!isImplicit)
+      checkCocoaAPI(*this, Result);
+  }
=20
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
+    if (Receiver &&
+        (Receiver->IgnoreParenImpCasts()->getType().getObjCLifetime()=20
+          =3D=3D Qualifiers::OCL_Weak))
+      Diag(Receiver->getLocStart(), diag::warn_receiver_is_weak);
+   =20
     // In ARC, annotate delegate init calls.
     if (Result->getMethodFamily() =3D=3D OMF_init &&
         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
@@ -1693,7 +2418,6 @@
         case CK_NoOp:
         case CK_LValueToRValue:
         case CK_BitCast:
-        case CK_GetObjCProperty:
         case CK_CPointerToObjCPointerCast:
         case CK_BlockPointerToObjCPointerCast:
         case CK_AnyPointerToBlockPointerCast:
@@ -1721,6 +2445,12 @@
       return merge(left, Visit(e->getFalseExpr()));
     }
=20
+    /// Look through pseudo-objects.
+    ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
+      // If we're getting here, we should always have a result.
+      return Visit(e->getResultExpr());
+    }
+
     /// Statement expressions are okay if their result expression is okay.
     ACCResult VisitStmtExpr(StmtExpr *e) {
       return Visit(e->getSubStmt()->body_back());
@@ -1834,61 +2564,88 @@
   };
 }
=20
-void=20
-Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
-                             Expr *&castExpr, CheckedConversionKind CCK) {
-  QualType castExprType =3D castExpr->getType();
+static bool
+KnownName(Sema &S, const char *name) {
+  LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
+                 Sema::LookupOrdinaryName);
+  return S.LookupName(R, S.TUScope, false);
+}
=20
-  // For the purposes of the classification, we assume reference types
-  // will bind to temporaries.
-  QualType effCastType =3D castType;
-  if (const ReferenceType *ref =3D castType->getAs<ReferenceType>())
-    effCastType =3D ref->getPointeeType();
- =20
-  ARCConversionTypeClass exprACTC =3D classifyTypeForARCConversion(castExp=
rType);
-  ARCConversionTypeClass castACTC =3D classifyTypeForARCConversion(effCast=
Type);
-  if (exprACTC =3D=3D castACTC) return;
-  if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return;
-
-  // Allow all of these types to be cast to integer types (but not
-  // vice-versa).
-  if (castACTC =3D=3D ACTC_none && castType->isIntegralType(Context))
-    return;
- =20
-  // Allow casts between pointers to lifetime types (e.g., __strong id*)
-  // and pointers to void (e.g., cv void *). Casting from void* to lifetim=
e*
-  // must be explicit.
-  if (exprACTC =3D=3D ACTC_indirectRetainable && castACTC =3D=3D ACTC_void=
Ptr)
-    return;
-  if (castACTC =3D=3D ACTC_indirectRetainable && exprACTC =3D=3D ACTC_void=
Ptr &&
-      CCK !=3D CCK_ImplicitConversion)
-    return;
-
-  switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
-  // For invalid casts, fall through.
-  case ACC_invalid:
+static void addFixitForObjCARCConversion(Sema &S,
+                                         DiagnosticBuilder &DiagB,
+                                         Sema::CheckedConversionKind CCK,
+                                         SourceLocation afterLParen,
+                                         QualType castType,
+                                         Expr *castExpr,
+                                         const char *bridgeKeyword,
+                                         const char *CFBridgeName) {
+  // We handle C-style and implicit casts here.
+  switch (CCK) {
+  case Sema::CCK_ImplicitConversion:
+  case Sema::CCK_CStyleCast:
     break;
-
-  // Do nothing for both bottom and +0.
-  case ACC_bottom:
-  case ACC_plusZero:
-    return;
-
-  // If the result is +1, consume it here.
-  case ACC_plusOne:
-    castExpr =3D ImplicitCastExpr::Create(Context, castExpr->getType(),
-                                        CK_ARCConsumeObject, castExpr,
-                                        0, VK_RValue);
-    ExprNeedsCleanups =3D true;
+  case Sema::CCK_FunctionalCast:
+  case Sema::CCK_OtherCast:
     return;
   }
- =20
+
+  if (CFBridgeName) {
+    Expr *castedE =3D castExpr;
+    if (CStyleCastExpr *CCE =3D dyn_cast<CStyleCastExpr>(castedE))
+      castedE =3D CCE->getSubExpr();
+    castedE =3D castedE->IgnoreImpCasts();
+    SourceRange range =3D castedE->getSourceRange();
+    if (isa<ParenExpr>(castedE)) {
+      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
+                         CFBridgeName));
+    } else {
+      std::string namePlusParen =3D CFBridgeName;
+      namePlusParen +=3D "(";
+      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
+                                                    namePlusParen));
+      DiagB.AddFixItHint(FixItHint::CreateInsertion(
+                                       S.PP.getLocForEndOfToken(range.getE=
nd()),
+                                       ")"));
+    }
+    return;
+  }
+
+  if (CCK =3D=3D Sema::CCK_CStyleCast) {
+    DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeywo=
rd));
+  } else {
+    std::string castCode =3D "(";
+    castCode +=3D bridgeKeyword;
+    castCode +=3D castType.getAsString();
+    castCode +=3D ")";
+    Expr *castedE =3D castExpr->IgnoreImpCasts();
+    SourceRange range =3D castedE->getSourceRange();
+    if (isa<ParenExpr>(castedE)) {
+      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
+                         castCode));
+    } else {
+      castCode +=3D "(";
+      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
+                                                    castCode));
+      DiagB.AddFixItHint(FixItHint::CreateInsertion(
+                                       S.PP.getLocForEndOfToken(range.getE=
nd()),
+                                       ")"));
+    }
+  }
+}
+
+static void
+diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
+                          QualType castType, ARCConversionTypeClass castAC=
TC,
+                          Expr *castExpr, ARCConversionTypeClass exprACTC,
+                          Sema::CheckedConversionKind CCK) {
   SourceLocation loc =3D
     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
  =20
-  if (makeUnavailableInSystemHeader(loc,
+  if (S.makeUnavailableInSystemHeader(loc,
                 "converts between Objective-C and C pointers in -fobjc-arc=
"))
     return;
+
+  QualType castExprType =3D castExpr->getType();
  =20
   unsigned srcKind =3D 0;
   switch (exprACTC) {
@@ -1905,51 +2662,235 @@
     break;
   }
  =20
-  if (CCK =3D=3D CCK_CStyleCast) {
-    // Check whether this could be fixed with a bridge cast.
-    SourceLocation AfterLParen =3D PP.getLocForEndOfToken(castRange.getBeg=
in());
-    SourceLocation NoteLoc =3D AfterLParen.isValid()? AfterLParen : loc;
+  // Check whether this could be fixed with a bridge cast.
+  SourceLocation afterLParen =3D S.PP.getLocForEndOfToken(castRange.getBeg=
in());
+  SourceLocation noteLoc =3D afterLParen.isValid() ? afterLParen : loc;
+
+  // Bridge from an ARC type to a CF type.
+  if (castACTC =3D=3D ACTC_retainable && isAnyRetainable(exprACTC)) {
+
+    S.Diag(loc, diag::err_arc_cast_requires_bridge)
+      << unsigned(CCK =3D=3D Sema::CCK_ImplicitConversion) // cast|implicit
+      << 2 // of C pointer type
+      << castExprType
+      << unsigned(castType->isBlockPointerType()) // to ObjC|block type
+      << castType
+      << castRange
+      << castExpr->getSourceRange();
+    bool br =3D KnownName(S, "CFBridgingRelease");
+    {
+      DiagnosticBuilder DiagB =3D S.Diag(noteLoc, diag::note_arc_bridge);
+      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
+                                   castType, castExpr, "__bridge ", 0);
+    }
+    {
+      DiagnosticBuilder DiagB =3D S.Diag(noteLoc, diag::note_arc_bridge_tr=
ansfer)
+        << castExprType << br;
+      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
+                                   castType, castExpr, "__bridge_transfer =
",
+                                   br ? "CFBridgingRelease" : 0);
+    }
+
+    return;
+  }
    =20
-    if (castACTC =3D=3D ACTC_retainable && isAnyRetainable(exprACTC)) {
-      Diag(loc, diag::err_arc_cast_requires_bridge)
-        << 2
-        << castExprType
-        << (castType->isBlockPointerType()? 1 : 0)
-        << castType
-        << castRange
-        << castExpr->getSourceRange();
-      Diag(NoteLoc, diag::note_arc_bridge)
-        << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
-      Diag(NoteLoc, diag::note_arc_bridge_transfer)
-        << castExprType
-        << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
-     =20
-      return;
+  // Bridge from a CF type to an ARC type.
+  if (exprACTC =3D=3D ACTC_retainable && isAnyRetainable(castACTC)) {
+    bool br =3D KnownName(S, "CFBridgingRetain");
+    S.Diag(loc, diag::err_arc_cast_requires_bridge)
+      << unsigned(CCK =3D=3D Sema::CCK_ImplicitConversion) // cast|implicit
+      << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
+      << castExprType
+      << 2 // to C pointer type
+      << castType
+      << castRange
+      << castExpr->getSourceRange();
+
+    {
+      DiagnosticBuilder DiagB =3D S.Diag(noteLoc, diag::note_arc_bridge);
+      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
+                                   castType, castExpr, "__bridge ", 0);
     }
-   =20
-    if (exprACTC =3D=3D ACTC_retainable && isAnyRetainable(castACTC)) {
-      Diag(loc, diag::err_arc_cast_requires_bridge)
-        << (castExprType->isBlockPointerType()? 1 : 0)
-        << castExprType
-        << 2
-        << castType
-        << castRange
-        << castExpr->getSourceRange();
+    {
+      DiagnosticBuilder DiagB =3D S.Diag(noteLoc, diag::note_arc_bridge_re=
tained)
+        << castType << br;
+      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
+                                   castType, castExpr, "__bridge_retained =
",
+                                   br ? "CFBridgingRetain" : 0);
+    }
=20
-      Diag(NoteLoc, diag::note_arc_bridge)
-        << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
-      Diag(NoteLoc, diag::note_arc_bridge_retained)
-        << castType
-        << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
-      return;
-    }
+    return;
   }
  =20
-  Diag(loc, diag::err_arc_mismatched_cast)
-    << (CCK !=3D CCK_ImplicitConversion) << srcKind << castExprType << cas=
tType
+  S.Diag(loc, diag::err_arc_mismatched_cast)
+    << (CCK !=3D Sema::CCK_ImplicitConversion)
+    << srcKind << castExprType << castType
     << castRange << castExpr->getSourceRange();
 }
=20
+Sema::ARCConversionResult
+Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
+                             Expr *&castExpr, CheckedConversionKind CCK) {
+  QualType castExprType =3D castExpr->getType();
+
+  // For the purposes of the classification, we assume reference types
+  // will bind to temporaries.
+  QualType effCastType =3D castType;
+  if (const ReferenceType *ref =3D castType->getAs<ReferenceType>())
+    effCastType =3D ref->getPointeeType();
+ =20
+  ARCConversionTypeClass exprACTC =3D classifyTypeForARCConversion(castExp=
rType);
+  ARCConversionTypeClass castACTC =3D classifyTypeForARCConversion(effCast=
Type);
+  if (exprACTC =3D=3D castACTC) {
+    // check for viablity and report error if casting an rvalue to a
+    // life-time qualifier.
+    if ((castACTC =3D=3D ACTC_retainable) &&
+        (CCK =3D=3D CCK_CStyleCast || CCK =3D=3D CCK_OtherCast) &&
+        (castType !=3D castExprType)) {
+      const Type *DT =3D castType.getTypePtr();
+      QualType QDT =3D castType;
+      // We desugar some types but not others. We ignore those
+      // that cannot happen in a cast; i.e. auto, and those which
+      // should not be de-sugared; i.e typedef.
+      if (const ParenType *PT =3D dyn_cast<ParenType>(DT))
+        QDT =3D PT->desugar();
+      else if (const TypeOfType *TP =3D dyn_cast<TypeOfType>(DT))
+        QDT =3D TP->desugar();
+      else if (const AttributedType *AT =3D dyn_cast<AttributedType>(DT))
+        QDT =3D AT->desugar();
+      if (QDT !=3D castType &&
+          QDT.getObjCLifetime() !=3D  Qualifiers::OCL_None) {
+        SourceLocation loc =3D
+          (castRange.isValid() ? castRange.getBegin()=20
+                              : castExpr->getExprLoc());
+        Diag(loc, diag::err_arc_nolifetime_behavior);
+      }
+    }
+    return ACR_okay;
+  }
+ =20
+  if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
+
+  // Allow all of these types to be cast to integer types (but not
+  // vice-versa).
+  if (castACTC =3D=3D ACTC_none && castType->isIntegralType(Context))
+    return ACR_okay;
+ =20
+  // Allow casts between pointers to lifetime types (e.g., __strong id*)
+  // and pointers to void (e.g., cv void *). Casting from void* to lifetim=
e*
+  // must be explicit.
+  if (exprACTC =3D=3D ACTC_indirectRetainable && castACTC =3D=3D ACTC_void=
Ptr)
+    return ACR_okay;
+  if (castACTC =3D=3D ACTC_indirectRetainable && exprACTC =3D=3D ACTC_void=
Ptr &&
+      CCK !=3D CCK_ImplicitConversion)
+    return ACR_okay;
+
+  switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
+  // For invalid casts, fall through.
+  case ACC_invalid:
+    break;
+
+  // Do nothing for both bottom and +0.
+  case ACC_bottom:
+  case ACC_plusZero:
+    return ACR_okay;
+
+  // If the result is +1, consume it here.
+  case ACC_plusOne:
+    castExpr =3D ImplicitCastExpr::Create(Context, castExpr->getType(),
+                                        CK_ARCConsumeObject, castExpr,
+                                        0, VK_RValue);
+    ExprNeedsCleanups =3D true;
+    return ACR_okay;
+  }
+
+  // If this is a non-implicit cast from id or block type to a
+  // CoreFoundation type, delay complaining in case the cast is used
+  // in an acceptable context.
+  if (exprACTC =3D=3D ACTC_retainable && isAnyRetainable(castACTC) &&
+      CCK !=3D CCK_ImplicitConversion)
+    return ACR_unbridged;
+
+  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
+                            castExpr, exprACTC, CCK);
+  return ACR_okay;
+}
+
+/// Given that we saw an expression with the ARCUnbridgedCastTy
+/// placeholder type, complain bitterly.
+void Sema::diagnoseARCUnbridgedCast(Expr *e) {
+  // We expect the spurious ImplicitCastExpr to already have been stripped.
+  assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
+  CastExpr *realCast =3D cast<CastExpr>(e->IgnoreParens());
+
+  SourceRange castRange;
+  QualType castType;
+  CheckedConversionKind CCK;
+
+  if (CStyleCastExpr *cast =3D dyn_cast<CStyleCastExpr>(realCast)) {
+    castRange =3D SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
+    castType =3D cast->getTypeAsWritten();
+    CCK =3D CCK_CStyleCast;
+  } else if (ExplicitCastExpr *cast =3D dyn_cast<ExplicitCastExpr>(realCas=
t)) {
+    castRange =3D cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRang=
e();
+    castType =3D cast->getTypeAsWritten();
+    CCK =3D CCK_OtherCast;
+  } else {
+    castType =3D cast->getType();
+    CCK =3D CCK_ImplicitConversion;
+  }
+
+  ARCConversionTypeClass castACTC =3D
+    classifyTypeForARCConversion(castType.getNonReferenceType());
+
+  Expr *castExpr =3D realCast->getSubExpr();
+  assert(classifyTypeForARCConversion(castExpr->getType()) =3D=3D ACTC_ret=
ainable);
+
+  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
+                            castExpr, ACTC_retainable, CCK);
+}
+
+/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
+/// type, remove the placeholder cast.
+Expr *Sema::stripARCUnbridgedCast(Expr *e) {
+  assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
+
+  if (ParenExpr *pe =3D dyn_cast<ParenExpr>(e)) {
+    Expr *sub =3D stripARCUnbridgedCast(pe->getSubExpr());
+    return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
+  } else if (UnaryOperator *uo =3D dyn_cast<UnaryOperator>(e)) {
+    assert(uo->getOpcode() =3D=3D UO_Extension);
+    Expr *sub =3D stripARCUnbridgedCast(uo->getSubExpr());
+    return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
+                                   sub->getValueKind(), sub->getObjectKind=
(),
+                                       uo->getOperatorLoc());
+  } else if (GenericSelectionExpr *gse =3D dyn_cast<GenericSelectionExpr>(=
e)) {
+    assert(!gse->isResultDependent());
+
+    unsigned n =3D gse->getNumAssocs();
+    SmallVector<Expr*, 4> subExprs(n);
+    SmallVector<TypeSourceInfo*, 4> subTypes(n);
+    for (unsigned i =3D 0; i !=3D n; ++i) {
+      subTypes[i] =3D gse->getAssocTypeSourceInfo(i);
+      Expr *sub =3D gse->getAssocExpr(i);
+      if (i =3D=3D gse->getResultIndex())
+        sub =3D stripARCUnbridgedCast(sub);
+      subExprs[i] =3D sub;
+    }
+
+    return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(=
),
+                                              gse->getControllingExpr(),
+                                              subTypes.data(), subExprs.da=
ta(),
+                                              n, gse->getDefaultLoc(),
+                                              gse->getRParenLoc(),
+                                       gse->containsUnexpandedParameterPac=
k(),
+                                              gse->getResultIndex());
+  } else {
+    assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
+    return cast<ImplicitCastExpr>(e)->getSubExpr();
+  }
+}
+
 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
                                                  QualType exprType) {
   QualType canCastType =3D=20
@@ -2007,7 +2948,8 @@
     case OBC_Bridge:
       break;
      =20
-    case OBC_BridgeRetained:
+    case OBC_BridgeRetained: {
+      bool br =3D KnownName(*this, "CFBridgingRelease");
       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
         << 2
         << FromType
@@ -2018,12 +2960,14 @@
       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
-        << FromType
+        << FromType << br
         << FixItHint::CreateReplacement(BridgeKeywordLoc,=20
-                                        "__bridge_transfer ");
+                                        br ? "CFBridgingRelease "=20
+                                           : "__bridge_transfer ");
=20
       Kind =3D OBC_Bridge;
       break;
+    }
      =20
     case OBC_BridgeTransfer:
       // We must consume the Objective-C object produced by the cast.
@@ -2047,7 +2991,8 @@
                                          SubExpr, 0, VK_RValue);
       break;
      =20
-    case OBC_BridgeTransfer:
+    case OBC_BridgeTransfer: {
+      bool br =3D KnownName(*this, "CFBridgingRetain");
       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
         << (FromType->isBlockPointerType()? 1 : 0)
         << FromType
@@ -2059,12 +3004,14 @@
       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
-        << T
-        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retain=
ed ");
+        << T << br
+        << FixItHint::CreateReplacement(BridgeKeywordLoc,=20
+                          br ? "CFBridgingRetain " : "__bridge_retained");
        =20
       Kind =3D OBC_Bridge;
       break;
     }
+    }
   } else {
     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
       << FromType << T << Kind
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaFixItUtils.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaFixItUtils.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaFixItUtils.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -158,3 +158,47 @@
=20
   return false;
 }
+
+static bool isMacroDefined(const Sema &S, StringRef Name) {
+  return S.PP.getMacroInfo(&S.getASTContext().Idents.get(Name));
+}
+
+const char *Sema::getFixItZeroInitializerForType(QualType T) const {
+  if (T->isScalarType()) {
+    // Suggest " =3D 0" for non-enumeration scalar types, unless we can fi=
nd a
+    // better initializer.
+    if (T->isEnumeralType())
+      return 0;
+    if ((T->isObjCObjectPointerType() || T->isBlockPointerType()) &&
+        isMacroDefined(*this, "nil"))
+      return " =3D nil";
+    if (T->isRealFloatingType())
+      return " =3D 0.0";
+    if (T->isBooleanType() && LangOpts.CPlusPlus)
+      return " =3D false";
+    if (T->isPointerType() || T->isMemberPointerType()) {
+      if (LangOpts.CPlusPlus0x)
+        return " =3D nullptr";
+      else if (isMacroDefined(*this, "NULL"))
+        return " =3D NULL";
+    }
+    if (T->isCharType())
+      return " =3D '\\0'";
+    if (T->isWideCharType())
+      return " =3D L'\\0'";
+    if (T->isChar16Type())
+      return " =3D u'\\0'";
+    if (T->isChar32Type())
+      return " =3D U'\\0'";
+    return " =3D 0";
+  }
+
+  const CXXRecordDecl *RD =3D T->getAsCXXRecordDecl();
+  if (!RD || !RD->hasDefinition())
+    return 0;
+  if (LangOpts.CPlusPlus0x && !RD->hasUserProvidedDefaultConstructor())
+    return "{}";
+  if (RD->isAggregate())
+    return " =3D {}";
+  return 0;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaInit.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -21,6 +21,8 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/TypeLoc.h"
+#include "llvm/ADT/APInt.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/raw_ostream.h"
 #include <map>
@@ -104,7 +106,7 @@
   // We have an array of character type with known size.  However,
   // the size may be smaller or larger than the string we are initializing.
   // FIXME: Avoid truncation for 64-bit length strings.
-  if (S.getLangOptions().CPlusPlus) {
+  if (S.getLangOpts().CPlusPlus) {
     if (StringLiteral *SL =3D dyn_cast<StringLiteral>(Str)) {
       // For Pascal strings it's OK to strip off the terminating null char=
acter,
       // so the example below is valid:
@@ -116,13 +118,13 @@
  =20
     // [dcl.init.string]p2
     if (StrLength > CAT->getSize().getZExtValue())
-      S.Diag(Str->getSourceRange().getBegin(),
+      S.Diag(Str->getLocStart(),
              diag::err_initializer_string_for_char_array_too_long)
         << Str->getSourceRange();
   } else {
     // C99 6.7.8p14.
     if (StrLength-1 > CAT->getSize().getZExtValue())
-      S.Diag(Str->getSourceRange().getBegin(),
+      S.Diag(Str->getLocStart(),
              diag::warn_initializer_string_for_char_array_too_long)
         << Str->getSourceRange();
   }
@@ -170,7 +172,8 @@
   Sema &SemaRef;
   bool hadError;
   bool VerifyOnly; // no diagnostics, no structure building
-  std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
+  bool AllowBraceElision;
+  llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
   InitListExpr *FullyStructuredList;
=20
   void CheckImplicitInitList(const InitializedEntity &Entity,
@@ -256,9 +259,12 @@
   bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
                               Expr *InitExpr, FieldDecl *Field,
                               bool TopLevelObject);
+  void CheckValueInitializable(const InitializedEntity &Entity);
+
 public:
   InitListChecker(Sema &S, const InitializedEntity &Entity,
-                  InitListExpr *IL, QualType &T, bool VerifyOnly);
+                  InitListExpr *IL, QualType &T, bool VerifyOnly,
+                  bool AllowBraceElision);
   bool HadError() { return hadError; }
=20
   // @brief Retrieves the fully-structured initializer list used for
@@ -267,11 +273,23 @@
 };
 } // end anonymous namespace
=20
+void InitListChecker::CheckValueInitializable(const InitializedEntity &Ent=
ity) {
+  assert(VerifyOnly &&
+         "CheckValueInitializable is only inteded for verification mode.");
+
+  SourceLocation Loc;
+  InitializationKind Kind =3D InitializationKind::CreateValue(Loc, Loc, Lo=
c,
+                                                            true);
+  InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
+  if (InitSeq.Failed())
+    hadError =3D true;
+}
+
 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Fi=
eld,
                                         const InitializedEntity &ParentEnt=
ity,
                                               InitListExpr *ILE,
                                               bool &RequiresSecondPass) {
-  SourceLocation Loc =3D ILE->getSourceRange().getBegin();
+  SourceLocation Loc =3D ILE->getLocStart();
   unsigned NumInits =3D ILE->getNumInits();
   InitializedEntity MemberEntity
     =3D InitializedEntity::InitializeMember(Field, &ParentEntity);
@@ -336,9 +354,9 @@
                                             bool &RequiresSecondPass) {
   assert((ILE->getType() !=3D SemaRef.Context.VoidTy) &&
          "Should not have void type");
-  SourceLocation Loc =3D ILE->getSourceRange().getBegin();
+  SourceLocation Loc =3D ILE->getLocStart();
   if (ILE->getSyntacticForm())
-    Loc =3D ILE->getSyntacticForm()->getSourceRange().getBegin();
+    Loc =3D ILE->getSyntacticForm()->getLocStart();
=20
   if (const RecordType *RType =3D ILE->getType()->getAs<RecordType>()) {
     if (RType->getDecl()->isUnion() &&
@@ -400,7 +418,8 @@
         ElementEntity.getKind() =3D=3D InitializedEntity::EK_VectorElement)
       ElementEntity.setElementIndex(Init);
=20
-    if (Init >=3D NumInits || !ILE->getInit(Init)) {
+    Expr *InitExpr =3D (Init < NumInits ? ILE->getInit(Init) : 0);
+    if (!InitExpr && !ILE->hasArrayFiller()) {
       InitializationKind Kind =3D InitializationKind::CreateValue(Loc, Loc=
, Loc,
                                                                 true);
       InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
@@ -444,7 +463,7 @@
         }
       }
     } else if (InitListExpr *InnerILE
-                 =3D dyn_cast<InitListExpr>(ILE->getInit(Init)))
+                 =3D dyn_cast_or_null<InitListExpr>(InitExpr))
       FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPa=
ss);
   }
 }
@@ -452,8 +471,8 @@
=20
 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
                                  InitListExpr *IL, QualType &T,
-                                 bool VerifyOnly)
-  : SemaRef(S), VerifyOnly(VerifyOnly) {
+                                 bool VerifyOnly, bool AllowBraceElision)
+  : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElisio=
n) {
   hadError =3D false;
=20
   unsigned newIndex =3D 0;
@@ -527,7 +546,7 @@
   InitListExpr *StructuredSubobjectInitList
     =3D getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
                                  StructuredIndex,
-          SourceRange(ParentIList->getInit(Index)->getSourceRange().getBeg=
in(),
+          SourceRange(ParentIList->getInit(Index)->getLocStart(),
                       ParentIList->getSourceRange().getEnd()));
   unsigned StructuredSubobjectInitIndex =3D 0;
=20
@@ -537,10 +556,14 @@
                         /*SubobjectIsDesignatorContext=3D*/false, Index,
                         StructuredSubobjectInitList,
                         StructuredSubobjectInitIndex);
-  unsigned EndIndex =3D (Index =3D=3D StartIndex? StartIndex : Index - 1);
-  if (!VerifyOnly) {
+
+  if (VerifyOnly) {
+    if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
+      hadError =3D true;
+  } else {
     StructuredSubobjectInitList->setType(T);
=20
+    unsigned EndIndex =3D (Index =3D=3D StartIndex? StartIndex : Index - 1=
);
     // Update the structured sub-object initializer so that it's ending
     // range corresponds with the end of the last initializer it used.
     if (EndIndex < ParentIList->getNumInits()) {
@@ -549,10 +572,11 @@
       StructuredSubobjectInitList->setRBraceLoc(EndLoc);
     }
=20
-    // Warn about missing braces.
+    // Complain about missing braces.
     if (T->isArrayType() || T->isRecordType()) {
       SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
-                   diag::warn_missing_braces)
+                    AllowBraceElision ? diag::warn_missing_braces :
+                                        diag::err_missing_braces)
         << StructuredSubobjectInitList->getSourceRange()
         << FixItHint::CreateInsertion(
               StructuredSubobjectInitList->getLocStart(), "{")
@@ -560,6 +584,8 @@
               SemaRef.PP.getLocForEndOfToken(
                                       StructuredSubobjectInitList->getLocE=
nd()),
               "}");
+      if (!AllowBraceElision)
+        hadError =3D true;
     }
   }
 }
@@ -578,7 +604,9 @@
   CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=
=3D*/true,
                         Index, StructuredList, StructuredIndex, TopLevelOb=
ject);
   if (!VerifyOnly) {
-    QualType ExprTy =3D T.getNonLValueExprType(SemaRef.Context);
+    QualType ExprTy =3D T;
+    if (!ExprTy->isArrayType())
+      ExprTy =3D ExprTy.getNonLValueExprType(SemaRef.Context);
     IList->setType(ExprTy);
     StructuredList->setType(ExprTy);
   }
@@ -588,8 +616,8 @@
   if (Index < IList->getNumInits()) {
     // We have leftover initializers
     if (VerifyOnly) {
-      if (SemaRef.getLangOptions().CPlusPlus ||
-          (SemaRef.getLangOptions().OpenCL &&
+      if (SemaRef.getLangOpts().CPlusPlus ||
+          (SemaRef.getLangOpts().OpenCL &&
            IList->getType()->isVectorType())) {
         hadError =3D true;
       }
@@ -599,7 +627,7 @@
     if (StructuredIndex =3D=3D 1 &&
         IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
       unsigned DK =3D diag::warn_excess_initializers_in_char_array_initial=
izer;
-      if (SemaRef.getLangOptions().CPlusPlus) {
+      if (SemaRef.getLangOpts().CPlusPlus) {
         DK =3D diag::err_excess_initializers_in_char_array_initializer;
         hadError =3D true;
       }
@@ -618,11 +646,11 @@
         4;
=20
       unsigned DK =3D diag::warn_excess_initializers;
-      if (SemaRef.getLangOptions().CPlusPlus) {
+      if (SemaRef.getLangOpts().CPlusPlus) {
         DK =3D diag::err_excess_initializers;
         hadError =3D true;
       }
-      if (SemaRef.getLangOptions().OpenCL && initKind =3D=3D 1) {
+      if (SemaRef.getLangOpts().OpenCL && initKind =3D=3D 1) {
         DK =3D diag::err_excess_initializers;
         hadError =3D true;
       }
@@ -754,7 +782,7 @@
=20
     // Fall through for subaggregate initialization.
=20
-  } else if (SemaRef.getLangOptions().CPlusPlus) {
+  } else if (SemaRef.getLangOpts().CPlusPlus) {
     // C++ [dcl.init.aggr]p12:
     //   All implicit type conversions (clause 4) are considered when
     //   initializing the aggregate member with an initializer from
@@ -817,7 +845,7 @@
   //   subaggregate, brace elision is assumed and the initializer is
   //   considered for the initialization of the first member of
   //   the subaggregate.
-  if (!SemaRef.getLangOptions().OpenCL &&=20
+  if (!SemaRef.getLangOpts().OpenCL &&=20
       (ElemType->isAggregateType() || ElemType->isVectorType())) {
     CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
                           StructuredIndex);
@@ -856,7 +884,7 @@
=20
   // This is an extension in C.  (The builtin _Complex type does not exist
   // in the C++ standard.)
-  if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
+  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
     SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
       << IList->getSourceRange();
=20
@@ -879,12 +907,13 @@
                                       InitListExpr *StructuredList,
                                       unsigned &StructuredIndex) {
   if (Index >=3D IList->getNumInits()) {
-    if (!SemaRef.getLangOptions().CPlusPlus0x) {
-      if (!VerifyOnly)
-        SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initiali=
zer)
-          << IList->getSourceRange();
-      hadError =3D true;
-    }
+    if (!VerifyOnly)
+      SemaRef.Diag(IList->getLocStart(),
+                   SemaRef.getLangOpts().CPlusPlus0x ?
+                     diag::warn_cxx98_compat_empty_scalar_initializer :
+                     diag::err_empty_scalar_initializer)
+        << IList->getSourceRange();
+    hadError =3D !SemaRef.getLangOpts().CPlusPlus0x;
     ++Index;
     ++StructuredIndex;
     return;
@@ -902,7 +931,7 @@
     return;
   } else if (isa<DesignatedInitExpr>(expr)) {
     if (!VerifyOnly)
-      SemaRef.Diag(expr->getSourceRange().getBegin(),
+      SemaRef.Diag(expr->getLocStart(),
                    diag::err_designator_for_scalar_init)
         << DeclType << expr->getSourceRange();
     hadError =3D true;
@@ -964,8 +993,7 @@
   }
=20
   Expr *expr =3D IList->getInit(Index);
-  if (isa<InitListExpr>(expr)) {
-    // FIXME: Allowed in C++11.
+  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
     if (!VerifyOnly)
       SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
         << DeclType << IList->getSourceRange();
@@ -1005,15 +1033,20 @@
                                       unsigned &Index,
                                       InitListExpr *StructuredList,
                                       unsigned &StructuredIndex) {
-  if (Index >=3D IList->getNumInits())
-    return;
-
   const VectorType *VT =3D DeclType->getAs<VectorType>();
   unsigned maxElements =3D VT->getNumElements();
   unsigned numEltsInit =3D 0;
   QualType elementType =3D VT->getElementType();
=20
-  if (!SemaRef.getLangOptions().OpenCL) {
+  if (Index >=3D IList->getNumInits()) {
+    // Make sure the element type can be value-initialized.
+    if (VerifyOnly)
+      CheckValueInitializable(
+          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity)=
);
+    return;
+  }
+
+  if (!SemaRef.getLangOpts().OpenCL) {
     // If the initializing element is a vector, try to copy-initialize
     // instead of breaking it apart (which is doomed to failure anyway).
     Expr *Init =3D IList->getInit(Index);
@@ -1055,8 +1088,11 @@
=20
     for (unsigned i =3D 0; i < maxElements; ++i, ++numEltsInit) {
       // Don't attempt to go past the end of the init list
-      if (Index >=3D IList->getNumInits())
+      if (Index >=3D IList->getNumInits()) {
+        if (VerifyOnly)
+          CheckValueInitializable(ElementEntity);
         break;
+      }
=20
       ElementEntity.setElementIndex(Index);
       CheckSubElementType(ElementEntity, IList, elementType, Index,
@@ -1098,11 +1134,13 @@
   }
=20
   // OpenCL requires all elements to be initialized.
-  // FIXME: Shouldn't this set hadError to true then?
-  if (numEltsInit !=3D maxElements && !VerifyOnly)
-    SemaRef.Diag(IList->getSourceRange().getBegin(),
-                 diag::err_vector_incorrect_num_initializers)
-      << (numEltsInit < maxElements) << maxElements << numEltsInit;
+  if (numEltsInit !=3D maxElements) {
+    if (!VerifyOnly)
+      SemaRef.Diag(IList->getLocStart(),
+                   diag::err_vector_incorrect_num_initializers)
+        << (numEltsInit < maxElements) << maxElements << numEltsInit;
+    hadError =3D true;
+  }
 }
=20
 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
@@ -1223,6 +1261,14 @@
     DeclType =3D SemaRef.Context.getConstantArrayType(elementType, maxElem=
ents,
                                                      ArrayType::Normal, 0);
   }
+  if (!hadError && VerifyOnly) {
+    // Check if there are any members of the array that get value-initiali=
zed.
+    // If so, check if doing that is possible.
+    // FIXME: This needs to detect holes left by designated initializers t=
oo.
+    if (maxElementsKnown && elementIndex < maxElements)
+      CheckValueInitializable(InitializedEntity::InitializeElement(
+                                                  SemaRef.Context, 0, Enti=
ty));
+  }
 }
=20
 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Enti=
ty,
@@ -1235,7 +1281,7 @@
       cast<InitListExpr>(InitExpr)->getNumInits() =3D=3D 0) {
     // Empty flexible array init always allowed as an extension
     FlexArrayDiag =3D diag::ext_flexible_array_init;
-  } else if (SemaRef.getLangOptions().CPlusPlus) {
+  } else if (SemaRef.getLangOpts().CPlusPlus) {
     // Disallow flexible array init in C++; it is not required for gcc
     // compatibility, and it needs work to IRGen correctly in general.
     FlexArrayDiag =3D diag::err_flexible_array_init;
@@ -1254,9 +1300,9 @@
   }
=20
   if (!VerifyOnly) {
-    SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
+    SemaRef.Diag(InitExpr->getLocStart(),
                  FlexArrayDiag)
-      << InitExpr->getSourceRange().getBegin();
+      << InitExpr->getLocStart();
     SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
       << Field;
   }
@@ -1283,15 +1329,17 @@
   }
=20
   if (DeclType->isUnionType() && IList->getNumInits() =3D=3D 0) {
-    if (!VerifyOnly) {
-      // Value-initialize the first named member of the union.
-      RecordDecl *RD =3D DeclType->getAs<RecordType>()->getDecl();
-      for (RecordDecl::field_iterator FieldEnd =3D RD->field_end();
-           Field !=3D FieldEnd; ++Field) {
-        if (Field->getDeclName()) {
+    // Value-initialize the first named member of the union.
+    RecordDecl *RD =3D DeclType->getAs<RecordType>()->getDecl();
+    for (RecordDecl::field_iterator FieldEnd =3D RD->field_end();
+         Field !=3D FieldEnd; ++Field) {
+      if (Field->getDeclName()) {
+        if (VerifyOnly)
+          CheckValueInitializable(
+              InitializedEntity::InitializeMember(*Field, &Entity));
+        else
           StructuredList->setInitializedFieldInUnion(*Field);
-          break;
-        }
+        break;
       }
     }
     return;
@@ -1394,6 +1442,17 @@
     }
   }
=20
+  // Check that any remaining fields can be value-initialized.
+  if (VerifyOnly && Field !=3D FieldEnd && !DeclType->isUnionType() &&
+      !Field->getType()->isIncompleteArrayType()) {
+    // FIXME: Should check for holes left by designated initializers too.
+    for (; Field !=3D FieldEnd && !hadError; ++Field) {
+      if (!Field->isUnnamedBitfield())
+        CheckValueInitializable(
+            InitializedEntity::InitializeMember(*Field, &Entity));
+    }
+  }
+
   if (Field =3D=3D FieldEnd || !Field->getType()->isIncompleteArrayType() =
||
       Index >=3D IList->getNumInits())
     return;
@@ -1454,7 +1513,8 @@
                                                  IdentifierInfo *FieldName=
) {
   assert(AnonField->isAnonymousStructOrUnion());
   Decl *NextDecl =3D AnonField->getNextDeclInContext();
-  while (IndirectFieldDecl *IF =3D dyn_cast<IndirectFieldDecl>(NextDecl)) {
+  while (IndirectFieldDecl *IF =3D=20
+          dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
     if (FieldName && FieldName =3D=3D IF->getAnonField()->getIdentifier())
       return IF;
     NextDecl =3D NextDecl->getNextDeclInContext();
@@ -1474,6 +1534,26 @@
                                     DIE->usesGNUSyntax(), DIE->getInit());
 }
=20
+namespace {
+
+// Callback to only accept typo corrections that are for field members of
+// the given struct or union.
+class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
+      : Record(RD) {}
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    FieldDecl *FD =3D candidate.getCorrectionDeclAs<FieldDecl>();
+    return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
+  }
+
+ private:
+  RecordDecl *Record;
+};
+
+}
+
 /// @brief Check the well-formedness of a C99 designated initializer.
 ///
 /// Determines whether the designated initializer @p DIE, which
@@ -1552,7 +1632,7 @@
=20
     // Determine the structural initializer list that corresponds to the
     // current subobject.
-    StructuredList =3D IsFirstDesignator? SyntacticToSemantic[IList]
+    StructuredList =3D IsFirstDesignator? SyntacticToSemantic.lookup(IList)
       : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
                                    StructuredList, StructuredIndex,
                                    SourceRange(D->getStartLocation(),
@@ -1577,7 +1657,7 @@
         Loc =3D D->getFieldLoc();
       if (!VerifyOnly)
         SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
-          << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
+          << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
       ++Index;
       return true;
     }
@@ -1632,19 +1712,17 @@
       if (Lookup.first =3D=3D Lookup.second) {
         // Name lookup didn't find anything. Determine whether this
         // was a typo for another field name.
-        LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
-                       Sema::LookupMemberName);
+        FieldInitializerValidatorCCC Validator(RT->getDecl());
         TypoCorrection Corrected =3D SemaRef.CorrectTypo(
             DeclarationNameInfo(FieldName, D->getFieldLoc()),
-            Sema::LookupMemberName, /*Scope=3D*/NULL, /*SS=3D*/NULL,
-            RT->getDecl(), false, Sema::CTC_NoKeywords);
-        if ((ReplacementField =3D Corrected.getCorrectionDeclAs<FieldDecl>=
()) &&
-            ReplacementField->getDeclContext()->getRedeclContext()
-                                                      ->Equals(RT->getDecl=
())) {
+            Sema::LookupMemberName, /*Scope=3D*/0, /*SS=3D*/0, Validator,
+            RT->getDecl());
+        if (Corrected) {
           std::string CorrectedStr(
-              Corrected.getAsString(SemaRef.getLangOptions()));
+              Corrected.getAsString(SemaRef.getLangOpts()));
           std::string CorrectedQuotedStr(
-              Corrected.getQuoted(SemaRef.getLangOptions()));
+              Corrected.getQuoted(SemaRef.getLangOpts()));
+          ReplacementField =3D Corrected.getCorrectionDeclAs<FieldDecl>();
           SemaRef.Diag(D->getFieldLoc(),
                        diag::err_field_designator_unknown_suggest)
             << FieldName << CurrentObjectType << CorrectedQuotedStr
@@ -1740,7 +1818,7 @@
           !isa<StringLiteral>(DIE->getInit())) {
         // The initializer is not an initializer list.
         if (!VerifyOnly) {
-          SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
+          SemaRef.Diag(DIE->getInit()->getLocStart(),
                         diag::err_flexible_array_init_needs_braces)
             << DIE->getInit()->getSourceRange();
           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_mem=
ber)
@@ -1881,7 +1959,7 @@
     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
     if (DesignatedEndIndex >=3D MaxElements) {
       if (!VerifyOnly)
-        SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
+        SemaRef.Diag(IndexExpr->getLocStart(),
                       diag::err_array_designator_too_large)
           << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
           << IndexExpr->getSourceRange();
@@ -1968,7 +2046,7 @@
     return 0; // No structured list in verification-only mode.
   Expr *ExistingInit =3D 0;
   if (!StructuredList)
-    ExistingInit =3D SyntacticToSemantic[IList];
+    ExistingInit =3D SyntacticToSemantic.lookup(IList);
   else if (StructuredIndex < StructuredList->getNumInits())
     ExistingInit =3D StructuredList->getInit(StructuredIndex);
=20
@@ -1990,7 +2068,7 @@
     SemaRef.Diag(InitRange.getBegin(),
                  diag::warn_subobject_initializer_overrides)
       << InitRange;
-    SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
+    SemaRef.Diag(ExistingInit->getLocStart(),
                   diag::note_previous_initializer)
       << /*FIXME:has side effects=3D*/0
       << ExistingInit->getSourceRange();
@@ -2001,7 +2079,10 @@
                                          InitRange.getBegin(), 0, 0,
                                          InitRange.getEnd());
=20
-  Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
+  QualType ResultType =3D CurrentObjectType;
+  if (!ResultType->isArrayType())
+    ResultType =3D ResultType.getNonLValueExprType(SemaRef.Context);
+  Result->setType(ResultType);
=20
   // Pre-allocate storage for the structured initializer list.
   unsigned NumElements =3D 0;
@@ -2063,10 +2144,10 @@
   if (Expr *PrevInit =3D StructuredList->updateInit(SemaRef.Context,
                                                   StructuredIndex, expr)) {
     // This initializer overwrites a previous initializer. Warn.
-    SemaRef.Diag(expr->getSourceRange().getBegin(),
+    SemaRef.Diag(expr->getLocStart(),
                   diag::warn_initializer_overrides)
       << expr->getSourceRange();
-    SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
+    SemaRef.Diag(PrevInit->getLocStart(),
                   diag::note_previous_initializer)
       << /*FIXME:has side effects=3D*/0
       << PrevInit->getSourceRange();
@@ -2076,26 +2157,27 @@
 }
=20
 /// Check that the given Index expression is a valid array designator
-/// value. This is essentailly just a wrapper around
+/// value. This is essentially just a wrapper around
 /// VerifyIntegerConstantExpression that also checks for negative values
 /// and produces a reasonable diagnostic if there is a
-/// failure. Returns true if there was an error, false otherwise.  If
-/// everything went okay, Value will receive the value of the constant
-/// expression.
-static bool
+/// failure. Returns the index expression, possibly with an implicit cast
+/// added, on success.  If everything went okay, Value will receive the
+/// value of the constant expression.
+static ExprResult
 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
-  SourceLocation Loc =3D Index->getSourceRange().getBegin();
+  SourceLocation Loc =3D Index->getLocStart();
=20
   // Make sure this is an integer constant expression.
-  if (S.VerifyIntegerConstantExpression(Index, &Value))
-    return true;
+  ExprResult Result =3D S.VerifyIntegerConstantExpression(Index, &Value);
+  if (Result.isInvalid())
+    return Result;
=20
   if (Value.isSigned() && Value.isNegative())
     return S.Diag(Loc, diag::err_array_designator_negative)
       << Value.toString(10) << Index->getSourceRange();
=20
   Value.setIsUnsigned(true);
-  return false;
+  return Result;
 }
=20
 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
@@ -2120,9 +2202,9 @@
     case Designator::ArrayDesignator: {
       Expr *Index =3D static_cast<Expr *>(D.getArrayIndex());
       llvm::APSInt IndexValue;
-      if (!Index->isTypeDependent() &&
-          !Index->isValueDependent() &&
-          CheckArrayDesignatorExpr(*this, Index, IndexValue))
+      if (!Index->isTypeDependent() && !Index->isValueDependent())
+        Index =3D CheckArrayDesignatorExpr(*this, Index, IndexValue).take(=
);
+      if (!Index)
         Invalid =3D true;
       else {
         Designators.push_back(ASTDesignator(InitExpressions.size(),
@@ -2142,10 +2224,13 @@
                             StartIndex->isValueDependent();
       bool EndDependent =3D EndIndex->isTypeDependent() ||
                           EndIndex->isValueDependent();
-      if ((!StartDependent &&
-           CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
-          (!EndDependent &&
-           CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
+      if (!StartDependent)
+        StartIndex =3D
+            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
+      if (!EndDependent)
+        EndIndex =3D CheckArrayDesignatorExpr(*this, EndIndex, EndValue).t=
ake();
+
+      if (!StartIndex || !EndIndex)
         Invalid =3D true;
       else {
         // Make sure we're comparing values with the same bit width.
@@ -2187,10 +2272,7 @@
                                  InitExpressions.data(), InitExpressions.s=
ize(),
                                  Loc, GNUSyntax, Init.takeAs<Expr>());
=20
-  if (getLangOptions().CPlusPlus)
-    Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
-      << DIE->getSourceRange();
-  else if (!getLangOptions().C99)
+  if (!getLangOpts().C99)
     Diag(DIE->getLocStart(), diag::ext_designated_init)
       << DIE->getSourceRange();
=20
@@ -2244,6 +2326,9 @@
   case EK_Member:
     return VariableOrMember->getDeclName();
=20
+  case EK_LambdaCapture:
+    return Capture.Var->getDeclName();
+     =20
   case EK_Result:
   case EK_Exception:
   case EK_New:
@@ -2257,8 +2342,7 @@
     return DeclarationName();
   }
=20
-  // Silence GCC warning
-  return DeclarationName();
+  llvm_unreachable("Invalid EntityKind!");
 }
=20
 DeclaratorDecl *InitializedEntity::getDecl() const {
@@ -2280,11 +2364,11 @@
   case EK_VectorElement:
   case EK_ComplexElement:
   case EK_BlockElement:
+  case EK_LambdaCapture:
     return 0;
   }
=20
-  // Silence GCC warning
-  return 0;
+  llvm_unreachable("Invalid EntityKind!");
 }
=20
 bool InitializedEntity::allowsNRVO() const {
@@ -2304,6 +2388,7 @@
   case EK_VectorElement:
   case EK_ComplexElement:
   case EK_BlockElement:
+  case EK_LambdaCapture:
     break;
   }
=20
@@ -2329,15 +2414,19 @@
   case SK_QualificationConversionLValue:
   case SK_ListInitialization:
   case SK_ListConstructorCall:
+  case SK_UnwrapInitList:
+  case SK_RewrapInitList:
   case SK_ConstructorInitialization:
   case SK_ZeroInitialization:
   case SK_CAssignment:
   case SK_StringInit:
   case SK_ObjCObjectConversion:
   case SK_ArrayInit:
+  case SK_ParenthesizedArrayInit:
   case SK_PassByIndirectCopyRestore:
   case SK_PassByIndirectRestore:
   case SK_ProduceObjCObject:
+  case SK_StdInitializerList:
     break;
=20
   case SK_ConversionSequence:
@@ -2373,186 +2462,35 @@
   case FK_ArrayTypeMismatch:
   case FK_NonConstantArrayInit:
   case FK_ListInitializationFailed:
+  case FK_VariableLengthArrayHasInitializer:
+  case FK_PlaceholderType:
+  case FK_InitListElementCopyFailure:
+  case FK_ExplicitConstructor:
     return false;
=20
   case FK_ReferenceInitOverloadFailed:
   case FK_UserConversionOverloadFailed:
   case FK_ConstructorOverloadFailed:
+  case FK_ListConstructorOverloadFailed:
     return FailedOverloadResult =3D=3D OR_Ambiguous;
   }
=20
-  return false;
+  llvm_unreachable("Invalid EntityKind!");
 }
=20
 bool InitializationSequence::isConstructorInitialization() const {
   return !Steps.empty() && Steps.back().Kind =3D=3D SK_ConstructorInitiali=
zation;
 }
=20
-bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
-                                               const Expr *Initializer,
-                                               bool *isInitializerConstant,
-                                               APValue *ConstantValue) con=
st {
-  if (Steps.empty() || Initializer->isValueDependent())
-    return false;
-
-  const Step &LastStep =3D Steps.back();
-  if (LastStep.Kind !=3D SK_ConversionSequence)
-    return false;
-
-  const ImplicitConversionSequence &ICS =3D *LastStep.ICS;
-  const StandardConversionSequence *SCS =3D NULL;
-  switch (ICS.getKind()) {
-  case ImplicitConversionSequence::StandardConversion:
-    SCS =3D &ICS.Standard;
-    break;
-  case ImplicitConversionSequence::UserDefinedConversion:
-    SCS =3D &ICS.UserDefined.After;
-    break;
-  case ImplicitConversionSequence::AmbiguousConversion:
-  case ImplicitConversionSequence::EllipsisConversion:
-  case ImplicitConversionSequence::BadConversion:
-    return false;
-  }
-
-  // Check if SCS represents a narrowing conversion, according to C++0x
-  // [dcl.init.list]p7:
-  //
-  // A narrowing conversion is an implicit conversion ...
-  ImplicitConversionKind PossibleNarrowing =3D SCS->Second;
-  QualType FromType =3D SCS->getToType(0);
-  QualType ToType =3D SCS->getToType(1);
-  switch (PossibleNarrowing) {
-  // * from a floating-point type to an integer type, or
-  //
-  // * from an integer type or unscoped enumeration type to a floating-poi=
nt
-  //   type, except where the source is a constant expression and the actu=
al
-  //   value after conversion will fit into the target type and will produ=
ce
-  //   the original value when converted back to the original type, or
-  case ICK_Floating_Integral:
-    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
-      *isInitializerConstant =3D false;
-      return true;
-    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType=
()) {
-      llvm::APSInt IntConstantValue;
-      if (Initializer &&
-          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
-        // Convert the integer to the floating type.
-        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
-        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigne=
d(),
-                                llvm::APFloat::rmNearestTiesToEven);
-        // And back.
-        llvm::APSInt ConvertedValue =3D IntConstantValue;
-        bool ignored;
-        Result.convertToInteger(ConvertedValue,
-                                llvm::APFloat::rmTowardZero, &ignored);
-        // If the resulting value is different, this was a narrowing conve=
rsion.
-        if (IntConstantValue !=3D ConvertedValue) {
-          *isInitializerConstant =3D true;
-          *ConstantValue =3D APValue(IntConstantValue);
-          return true;
-        }
-      } else {
-        // Variables are always narrowings.
-        *isInitializerConstant =3D false;
-        return true;
-      }
-    }
-    return false;
-
-  // * from long double to double or float, or from double to float, except
-  //   where the source is a constant expression and the actual value after
-  //   conversion is within the range of values that can be represented (e=
ven
-  //   if it cannot be represented exactly), or
-  case ICK_Floating_Conversion:
-    if (1 =3D=3D Ctx.getFloatingTypeOrder(FromType, ToType)) {
-      // FromType is larger than ToType.
-      Expr::EvalResult InitializerValue;
-      // FIXME: Check whether Initializer is a constant expression accordi=
ng
-      // to C++0x [expr.const], rather than just whether it can be folded.
-      if (Initializer->Evaluate(InitializerValue, Ctx) &&
-          !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat=
()) {
-        // Constant! (Except for FIXME above.)
-        llvm::APFloat FloatVal =3D InitializerValue.Val.getFloat();
-        // Convert the source value into the target type.
-        bool ignored;
-        llvm::APFloat::opStatus ConvertStatus =3D FloatVal.convert(
-          Ctx.getFloatTypeSemantics(ToType),
-          llvm::APFloat::rmNearestTiesToEven, &ignored);
-        // If there was no overflow, the source value is within the range =
of
-        // values that can be represented.
-        if (ConvertStatus & llvm::APFloat::opOverflow) {
-          *isInitializerConstant =3D true;
-          *ConstantValue =3D InitializerValue.Val;
-          return true;
-        }
-      } else {
-        *isInitializerConstant =3D false;
-        return true;
-      }
-    }
-    return false;
-
-  // * from an integer type or unscoped enumeration type to an integer type
-  //   that cannot represent all the values of the original type, except w=
here
-  //   the source is a constant expression and the actual value after
-  //   conversion will fit into the target type and will produce the origi=
nal
-  //   value when converted back to the original type.
-  case ICK_Boolean_Conversion:  // Bools are integers too.
-    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
-      // Boolean conversions can be from pointers and pointers to members
-      // [conv.bool], and those aren't considered narrowing conversions.
-      return false;
-    }  // Otherwise, fall through to the integral case.
-  case ICK_Integral_Conversion: {
-    assert(FromType->isIntegralOrUnscopedEnumerationType());
-    assert(ToType->isIntegralOrUnscopedEnumerationType());
-    const bool FromSigned =3D FromType->isSignedIntegerOrEnumerationType();
-    const unsigned FromWidth =3D Ctx.getIntWidth(FromType);
-    const bool ToSigned =3D ToType->isSignedIntegerOrEnumerationType();
-    const unsigned ToWidth =3D Ctx.getIntWidth(ToType);
-
-    if (FromWidth > ToWidth ||
-        (FromWidth =3D=3D ToWidth && FromSigned !=3D ToSigned)) {
-      // Not all values of FromType can be represented in ToType.
-      llvm::APSInt InitializerValue;
-      if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
-        *isInitializerConstant =3D true;
-        *ConstantValue =3D APValue(InitializerValue);
-
-        // Add a bit to the InitializerValue so we don't have to worry abo=
ut
-        // signed vs. unsigned comparisons.
-        InitializerValue =3D InitializerValue.extend(
-          InitializerValue.getBitWidth() + 1);
-        // Convert the initializer to and from the target width and signed=
-ness.
-        llvm::APSInt ConvertedValue =3D InitializerValue;
-        ConvertedValue =3D ConvertedValue.trunc(ToWidth);
-        ConvertedValue.setIsSigned(ToSigned);
-        ConvertedValue =3D ConvertedValue.extend(InitializerValue.getBitWi=
dth());
-        ConvertedValue.setIsSigned(InitializerValue.isSigned());
-        // If the result is different, this was a narrowing conversion.
-        return ConvertedValue !=3D InitializerValue;
-      } else {
-        // Variables are always narrowings.
-        *isInitializerConstant =3D false;
-        return true;
-      }
-    }
-    return false;
-  }
-
-  default:
-    // Other kinds of conversions are not narrowings.
-    return false;
-  }
-}
-
-void InitializationSequence::AddAddressOverloadResolutionStep(
-                                                      FunctionDecl *Functi=
on,
-                                                      DeclAccessPair Found=
) {
+void
+InitializationSequence
+::AddAddressOverloadResolutionStep(FunctionDecl *Function,
+                                   DeclAccessPair Found,
+                                   bool HadMultipleCandidates) {
   Step S;
   S.Kind =3D SK_ResolveAddressOfOverloadedFunction;
   S.Type =3D Function->getType();
-  S.Function.HadMultipleCandidates =3D false;
+  S.Function.HadMultipleCandidates =3D HadMultipleCandidates;
   S.Function.Function =3D Function;
   S.Function.FoundDecl =3D Found;
   Steps.push_back(S);
@@ -2565,7 +2503,6 @@
   case VK_RValue: S.Kind =3D SK_CastDerivedToBaseRValue; break;
   case VK_XValue: S.Kind =3D SK_CastDerivedToBaseXValue; break;
   case VK_LValue: S.Kind =3D SK_CastDerivedToBaseLValue; break;
-  default: llvm_unreachable("No such category");
   }
   S.Type =3D BaseType;
   Steps.push_back(S);
@@ -2586,13 +2523,15 @@
   Steps.push_back(S);
 }
=20
-void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
-                                                   DeclAccessPair FoundDec=
l,
-                                                   QualType T) {
+void
+InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
+                                              DeclAccessPair FoundDecl,
+                                              QualType T,
+                                              bool HadMultipleCandidates) {
   Step S;
   S.Kind =3D SK_UserConversion;
   S.Type =3D T;
-  S.Function.HadMultipleCandidates =3D false;
+  S.Function.HadMultipleCandidates =3D HadMultipleCandidates;
   S.Function.Function =3D Function;
   S.Function.FoundDecl =3D FoundDecl;
   Steps.push_back(S);
@@ -2635,14 +2574,17 @@
 }
=20
 void
-InitializationSequence::AddConstructorInitializationStep(
-                                              CXXConstructorDecl *Construc=
tor,
-                                                       AccessSpecifier Acc=
ess,
-                                                         QualType T) {
+InitializationSequence
+::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
+                                   AccessSpecifier Access,
+                                   QualType T,
+                                   bool HadMultipleCandidates,
+                                   bool FromInitList, bool AsInitList) {
   Step S;
-  S.Kind =3D SK_ConstructorInitialization;
+  S.Kind =3D FromInitList && !AsInitList ? SK_ListConstructorCall
+                                       : SK_ConstructorInitialization;
   S.Type =3D T;
-  S.Function.HadMultipleCandidates =3D false;
+  S.Function.HadMultipleCandidates =3D HadMultipleCandidates;
   S.Function.Function =3D Constructor;
   S.Function.FoundDecl =3D DeclAccessPair::make(Constructor, Access);
   Steps.push_back(S);
@@ -2683,6 +2625,13 @@
   Steps.push_back(S);
 }
=20
+void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
+  Step S;
+  S.Kind =3D SK_ParenthesizedArrayInit;
+  S.Type =3D T;
+  Steps.push_back(S);
+}
+
 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType typ=
e,
                                                               bool shouldC=
opy) {
   Step s;
@@ -2699,6 +2648,28 @@
   Steps.push_back(S);
 }
=20
+void InitializationSequence::AddStdInitializerListConstructionStep(QualTyp=
e T) {
+  Step S;
+  S.Kind =3D SK_StdInitializerList;
+  S.Type =3D T;
+  Steps.push_back(S);
+}
+
+void InitializationSequence::RewrapReferenceInitList(QualType T,
+                                                     InitListExpr *Syntact=
ic) {
+  assert(Syntactic->getNumInits() =3D=3D 1 &&
+         "Can only rewrap trivial init lists.");
+  Step S;
+  S.Kind =3D SK_UnwrapInitList;
+  S.Type =3D Syntactic->getInit(0)->getType();
+  Steps.insert(Steps.begin(), S);
+
+  S.Kind =3D SK_RewrapInitList;
+  S.Type =3D T;
+  S.WrappingSyntacticList =3D Syntactic;
+  Steps.push_back(S);
+}
+
 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
                                                 OverloadingResult Result) {
   setSequenceKind(FailedSequence);
@@ -2713,7 +2684,7 @@
 static void MaybeProduceObjCObject(Sema &S,
                                    InitializationSequence &Sequence,
                                    const InitializedEntity &Entity) {
-  if (!S.getLangOptions().ObjCAutoRefCount) return;
+  if (!S.getLangOpts().ObjCAutoRefCount) return;
=20
   /// When initializing a parameter, produce the value if it's marked
   /// __attribute__((ns_consumed)).
@@ -2737,6 +2708,386 @@
   }
 }
=20
+/// \brief When initializing from init list via constructor, deal with the
+/// empty init list and std::initializer_list special cases.
+///
+/// \return True if this was a special case, false otherwise.
+static bool TryListConstructionSpecialCases(Sema &S,
+                                            InitListExpr *List,
+                                            CXXRecordDecl *DestRecordDecl,
+                                            QualType DestType,
+                                            InitializationSequence &Sequen=
ce) {
+  // C++11 [dcl.init.list]p3:
+  //   List-initialization of an object or reference of type T is defined =
as
+  //   follows:
+  //   - If T is an aggregate, aggregate initialization is performed.
+  if (DestType->isAggregateType())
+    return false;
+
+  //   - Otherwise, if the initializer list has no elements and T is a cla=
ss
+  //     type with a default constructor, the object is value-initialized.
+  if (List->getNumInits() =3D=3D 0) {
+    if (CXXConstructorDecl *DefaultConstructor =3D
+            S.LookupDefaultConstructor(DestRecordDecl)) {
+      if (DefaultConstructor->isDeleted() ||
+          S.isFunctionConsideredUnavailable(DefaultConstructor)) {
+        // Fake an overload resolution failure.
+        OverloadCandidateSet &CandidateSet =3D Sequence.getFailedCandidate=
Set();
+        DeclAccessPair FoundDecl =3D DeclAccessPair::make(DefaultConstruct=
or,
+                                              DefaultConstructor->getAcces=
s());
+        if (FunctionTemplateDecl *ConstructorTmpl =3D
+                dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
+          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
+                                         /*ExplicitArgs*/ 0,
+                                         ArrayRef<Expr*>(), CandidateSet,
+                                         /*SuppressUserConversions*/ false=
);
+        else
+          S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
+                                 ArrayRef<Expr*>(), CandidateSet,
+                                 /*SuppressUserConversions*/ false);
+        Sequence.SetOverloadFailure(
+                       InitializationSequence::FK_ListConstructorOverloadF=
ailed,
+                       OR_Deleted);
+      } else
+        Sequence.AddConstructorInitializationStep(DefaultConstructor,
+                                                DefaultConstructor->getAcc=
ess(),
+                                                  DestType,
+                                                  /*MultipleCandidates=3D*=
/false,
+                                                  /*FromInitList=3D*/true,
+                                                  /*AsInitList=3D*/false);
+      return true;
+    }
+  }
+
+  //   - Otherwise, if T is a specialization of std::initializer_list, [..=
.]
+  QualType E;
+  if (S.isStdInitializerList(DestType, &E)) {
+    // Check that each individual element can be copy-constructed. But sin=
ce we
+    // have no place to store further information, we'll recalculate every=
thing
+    // later.
+    InitializedEntity HiddenArray =3D InitializedEntity::InitializeTempora=
ry(
+        S.Context.getConstantArrayType(E,
+            llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
+                        List->getNumInits()),
+            ArrayType::Normal, 0));
+    InitializedEntity Element =3D InitializedEntity::InitializeElement(S.C=
ontext,
+        0, HiddenArray);
+    for (unsigned i =3D 0, n =3D List->getNumInits(); i < n; ++i) {
+      Element.setElementIndex(i);
+      if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
+        Sequence.SetFailed(
+            InitializationSequence::FK_InitListElementCopyFailure);
+        return true;
+      }
+    }
+    Sequence.AddStdInitializerListConstructionStep(DestType);
+    return true;
+  }
+
+  // Not a special case.
+  return false;
+}
+
+static OverloadingResult
+ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
+                           Expr **Args, unsigned NumArgs,
+                           OverloadCandidateSet &CandidateSet,
+                           DeclContext::lookup_iterator Con,
+                           DeclContext::lookup_iterator ConEnd,
+                           OverloadCandidateSet::iterator &Best,
+                           bool CopyInitializing, bool AllowExplicit,
+                           bool OnlyListConstructors, bool InitListSyntax)=
 {
+  CandidateSet.clear();
+
+  for (; Con !=3D ConEnd; ++Con) {
+    NamedDecl *D =3D *Con;
+    DeclAccessPair FoundDecl =3D DeclAccessPair::make(D, D->getAccess());
+    bool SuppressUserConversions =3D false;
+
+    // Find the constructor (which may be a template).
+    CXXConstructorDecl *Constructor =3D 0;
+    FunctionTemplateDecl *ConstructorTmpl =3D dyn_cast<FunctionTemplateDec=
l>(D);
+    if (ConstructorTmpl)
+      Constructor =3D cast<CXXConstructorDecl>(
+                                           ConstructorTmpl->getTemplatedDe=
cl());
+    else {
+      Constructor =3D cast<CXXConstructorDecl>(D);
+
+      // If we're performing copy initialization using a copy constructor,=
 we
+      // suppress user-defined conversions on the arguments. We do the sam=
e for
+      // move constructors.
+      if ((CopyInitializing || (InitListSyntax && NumArgs =3D=3D 1)) &&
+          Constructor->isCopyOrMoveConstructor())
+        SuppressUserConversions =3D true;
+    }
+
+    if (!Constructor->isInvalidDecl() &&
+        (AllowExplicit || !Constructor->isExplicit()) &&
+        (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
+      if (ConstructorTmpl)
+        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
+                                       /*ExplicitArgs*/ 0,
+                                       llvm::makeArrayRef(Args, NumArgs),
+                                       CandidateSet, SuppressUserConversio=
ns);
+      else {
+        // C++ [over.match.copy]p1:
+        //   - When initializing a temporary to be bound to the first para=
meter=20
+        //     of a constructor that takes a reference to possibly cv-qual=
ified=20
+        //     T as its first argument, called with a single argument in t=
he=20
+        //     context of direct-initialization, explicit conversion funct=
ions
+        //     are also considered.
+        bool AllowExplicitConv =3D AllowExplicit && !CopyInitializing &&=20
+                                 NumArgs =3D=3D 1 &&
+                                 Constructor->isCopyOrMoveConstructor();
+        S.AddOverloadCandidate(Constructor, FoundDecl,
+                               llvm::makeArrayRef(Args, NumArgs), Candidat=
eSet,
+                               SuppressUserConversions,
+                               /*PartialOverloading=3D*/false,
+                               /*AllowExplicit=3D*/AllowExplicitConv);
+      }
+    }
+  }
+
+  // Perform overload resolution and return the result.
+  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
+}
+
+/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
+/// enumerates the constructors of the initialized entity and performs ove=
rload
+/// resolution to select the best.
+/// If InitListSyntax is true, this is list-initialization of a non-aggreg=
ate
+/// class type.
+static void TryConstructorInitialization(Sema &S,
+                                         const InitializedEntity &Entity,
+                                         const InitializationKind &Kind,
+                                         Expr **Args, unsigned NumArgs,
+                                         QualType DestType,
+                                         InitializationSequence &Sequence,
+                                         bool InitListSyntax =3D false) {
+  assert((!InitListSyntax || (NumArgs =3D=3D 1 && isa<InitListExpr>(Args[0=
]))) &&
+         "InitListSyntax must come with a single initializer list argument=
.");
+
+  // Check constructor arguments for self reference.
+  if (DeclaratorDecl *DD =3D Entity.getDecl())
+    // Parameters arguments are occassionially constructed with itself,
+    // for instance, in recursive functions.  Skip them.
+    if (!isa<ParmVarDecl>(DD))
+      for (unsigned i =3D 0; i < NumArgs; ++i)
+        S.CheckSelfReference(DD, Args[i]);
+
+  // The type we're constructing needs to be complete.
+  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
+    Sequence.setIncompleteTypeFailure(DestType);
+    return;
+  }
+
+  const RecordType *DestRecordType =3D DestType->getAs<RecordType>();
+  assert(DestRecordType && "Constructor initialization requires record typ=
e");
+  CXXRecordDecl *DestRecordDecl
+    =3D cast<CXXRecordDecl>(DestRecordType->getDecl());
+
+  if (InitListSyntax &&
+      TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
+                                      DestRecordDecl, DestType, Sequence))
+    return;
+
+  // Build the candidate set directly in the initialization sequence
+  // structure, so that it will persist if we fail.
+  OverloadCandidateSet &CandidateSet =3D Sequence.getFailedCandidateSet();
+
+  // Determine whether we are allowed to call explicit constructors or
+  // explicit conversion operators.
+  bool AllowExplicit =3D Kind.AllowExplicit() || InitListSyntax;
+  bool CopyInitialization =3D Kind.getKind() =3D=3D InitializationKind::IK=
_Copy;
+
+  //   - Otherwise, if T is a class type, constructors are considered. The
+  //     applicable constructors are enumerated, and the best one is chosen
+  //     through overload resolution.
+  DeclContext::lookup_iterator ConStart, ConEnd;
+  llvm::tie(ConStart, ConEnd) =3D S.LookupConstructors(DestRecordDecl);
+
+  OverloadingResult Result =3D OR_No_Viable_Function;
+  OverloadCandidateSet::iterator Best;
+  bool AsInitializerList =3D false;
+
+  // C++11 [over.match.list]p1:
+  //   When objects of non-aggregate type T are list-initialized, overload
+  //   resolution selects the constructor in two phases:
+  //   - Initially, the candidate functions are the initializer-list
+  //     constructors of the class T and the argument list consists of the
+  //     initializer list as a single argument.
+  if (InitListSyntax) {
+    AsInitializerList =3D true;
+    Result =3D ResolveConstructorOverload(S, Kind.getLocation(), Args, Num=
Args,
+                                        CandidateSet, ConStart, ConEnd, Be=
st,
+                                        CopyInitialization, AllowExplicit,
+                                        /*OnlyListConstructor=3D*/true,
+                                        InitListSyntax);
+
+    // Time to unwrap the init list.
+    InitListExpr *ILE =3D cast<InitListExpr>(Args[0]);
+    Args =3D ILE->getInits();
+    NumArgs =3D ILE->getNumInits();
+  }
+
+  // C++11 [over.match.list]p1:
+  //   - If no viable initializer-list constructor is found, overload reso=
lution
+  //     is performed again, where the candidate functions are all the
+  //     constructors of the class T nad the argument list consists of the
+  //     elements of the initializer list.
+  if (Result =3D=3D OR_No_Viable_Function) {
+    AsInitializerList =3D false;
+    Result =3D ResolveConstructorOverload(S, Kind.getLocation(), Args, Num=
Args,
+                                        CandidateSet, ConStart, ConEnd, Be=
st,
+                                        CopyInitialization, AllowExplicit,
+                                        /*OnlyListConstructors=3D*/false,
+                                        InitListSyntax);
+  }
+  if (Result) {
+    Sequence.SetOverloadFailure(InitListSyntax ?
+                      InitializationSequence::FK_ListConstructorOverloadFa=
iled :
+                      InitializationSequence::FK_ConstructorOverloadFailed,
+                                Result);
+    return;
+  }
+
+  // C++0x [dcl.init]p6:
+  //   If a program calls for the default initialization of an object
+  //   of a const-qualified type T, T shall be a class type with a
+  //   user-provided default constructor.
+  if (Kind.getKind() =3D=3D InitializationKind::IK_Default &&
+      Entity.getType().isConstQualified() &&
+      cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
+    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
+    return;
+  }
+
+  // C++11 [over.match.list]p1:
+  //   In copy-list-initialization, if an explicit constructor is chosen, =
the
+  //   initializer is ill-formed.
+  CXXConstructorDecl *CtorDecl =3D cast<CXXConstructorDecl>(Best->Function=
);
+  if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
+    Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
+    return;
+  }
+
+  // Add the constructor initialization step. Any cv-qualification convers=
ion is
+  // subsumed by the initialization.
+  bool HadMultipleCandidates =3D (CandidateSet.size() > 1);
+  Sequence.AddConstructorInitializationStep(CtorDecl,
+                                            Best->FoundDecl.getAccess(),
+                                            DestType, HadMultipleCandidate=
s,
+                                            InitListSyntax, AsInitializerL=
ist);
+}
+
+static bool
+ResolveOverloadedFunctionForReferenceBinding(Sema &S,
+                                             Expr *Initializer,
+                                             QualType &SourceType,
+                                             QualType &UnqualifiedSourceTy=
pe,
+                                             QualType UnqualifiedTargetTyp=
e,
+                                             InitializationSequence &Seque=
nce) {
+  if (S.Context.getCanonicalType(UnqualifiedSourceType) =3D=3D
+        S.Context.OverloadTy) {
+    DeclAccessPair Found;
+    bool HadMultipleCandidates =3D false;
+    if (FunctionDecl *Fn
+        =3D S.ResolveAddressOfOverloadedFunction(Initializer,
+                                               UnqualifiedTargetType,
+                                               false, Found,
+                                               &HadMultipleCandidates)) {
+      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
+                                                HadMultipleCandidates);
+      SourceType =3D Fn->getType();
+      UnqualifiedSourceType =3D SourceType.getUnqualifiedType();
+    } else if (!UnqualifiedTargetType->isRecordType()) {
+      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFaile=
d);
+      return true;
+    }
+  }
+  return false;
+}
+
+static void TryReferenceInitializationCore(Sema &S,
+                                           const InitializedEntity &Entity,
+                                           const InitializationKind &Kind,
+                                           Expr *Initializer,
+                                           QualType cv1T1, QualType T1,
+                                           Qualifiers T1Quals,
+                                           QualType cv2T2, QualType T2,
+                                           Qualifiers T2Quals,
+                                           InitializationSequence &Sequenc=
e);
+
+static void TryListInitialization(Sema &S,
+                                  const InitializedEntity &Entity,
+                                  const InitializationKind &Kind,
+                                  InitListExpr *InitList,
+                                  InitializationSequence &Sequence);
+
+/// \brief Attempt list initialization of a reference.
+static void TryReferenceListInitialization(Sema &S,
+                                           const InitializedEntity &Entity,
+                                           const InitializationKind &Kind,
+                                           InitListExpr *InitList,
+                                           InitializationSequence &Sequenc=
e)
+{
+  // First, catch C++03 where this isn't possible.
+  if (!S.getLangOpts().CPlusPlus0x) {
+    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitLi=
st);
+    return;
+  }
+
+  QualType DestType =3D Entity.getType();
+  QualType cv1T1 =3D DestType->getAs<ReferenceType>()->getPointeeType();
+  Qualifiers T1Quals;
+  QualType T1 =3D S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
+
+  // Reference initialization via an initializer list works thus:
+  // If the initializer list consists of a single element that is
+  // reference-related to the referenced type, bind directly to that eleme=
nt
+  // (possibly creating temporaries).
+  // Otherwise, initialize a temporary with the initializer list and
+  // bind to that.
+  if (InitList->getNumInits() =3D=3D 1) {
+    Expr *Initializer =3D InitList->getInit(0);
+    QualType cv2T2 =3D Initializer->getType();
+    Qualifiers T2Quals;
+    QualType T2 =3D S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
+
+    // If this fails, creating a temporary wouldn't work either.
+    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2=
, T2,
+                                                     T1, Sequence))
+      return;
+
+    SourceLocation DeclLoc =3D Initializer->getLocStart();
+    bool dummy1, dummy2, dummy3;
+    Sema::ReferenceCompareResult RefRelationship
+      =3D S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
+                                       dummy2, dummy3);
+    if (RefRelationship >=3D Sema::Ref_Related) {
+      // Try to bind the reference here.
+      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, =
T1,
+                                     T1Quals, cv2T2, T2, T2Quals, Sequence=
);
+      if (Sequence)
+        Sequence.RewrapReferenceInitList(cv1T1, InitList);
+      return;
+    }
+  }
+
+  // Not reference-related. Create a temporary and bind to that.
+  InitializedEntity TempEntity =3D InitializedEntity::InitializeTemporary(=
cv1T1);
+
+  TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
+  if (Sequence) {
+    if (DestType->isRValueReferenceType() ||
+        (T1Quals.hasConst() && !T1Quals.hasVolatile()))
+      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=3D*/true);
+    else
+      Sequence.SetFailed(
+          InitializationSequence::FK_NonConstLValueReferenceBindingToTempo=
rary);
+  }
+}
+
 /// \brief Attempt list initialization (C++0x [dcl.init.list])
 static void TryListInitialization(Sema &S,
                                   const InitializedEntity &Entity,
@@ -2747,23 +3098,40 @@
=20
   // C++ doesn't allow scalar initialization with more than one argument.
   // But C99 complex numbers are scalars and it makes sense there.
-  if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
+  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
     return;
   }
-  // FIXME: C++0x defines behavior for these two cases.
   if (DestType->isReferenceType()) {
-    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitLi=
st);
+    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
     return;
   }
-  if (DestType->isRecordType() && !DestType->isAggregateType()) {
-    Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationTy=
pe);
-    return;
+  if (DestType->isRecordType()) {
+    if (S.RequireCompleteType(InitList->getLocStart(), DestType, S.PDiag()=
)) {
+      Sequence.setIncompleteTypeFailure(DestType);
+      return;
+    }
+
+    if (!DestType->isAggregateType()) {
+      if (S.getLangOpts().CPlusPlus0x) {
+        Expr *Arg =3D InitList;
+        // A direct-initializer is not list-syntax, i.e. there's no special
+        // treatment of "A a({1, 2});".
+        TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType,=20
+                                     Sequence,
+                               Kind.getKind() !=3D InitializationKind::IK_=
Direct);
+      } else
+        Sequence.SetFailed(
+            InitializationSequence::FK_InitListBadDestinationType);
+      return;
+    }
   }
=20
   InitListChecker CheckInitList(S, Entity, InitList,
-          DestType, /*VerifyOnly=3D*/true);
+          DestType, /*VerifyOnly=3D*/true,
+          Kind.getKind() !=3D InitializationKind::IK_DirectList ||
+            !S.getLangOpts().CPlusPlus0x);
   if (CheckInitList.HadError()) {
     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed=
);
     return;
@@ -2778,8 +3146,8 @@
 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
                                              const InitializedEntity &Enti=
ty,
                                              const InitializationKind &Kin=
d,
-                                                          Expr *Initialize=
r,
-                                                          bool AllowRValue=
s,
+                                             Expr *Initializer,
+                                             bool AllowRValues,
                                              InitializationSequence &Seque=
nce) {
   QualType DestType =3D Entity.getType();
   QualType cv1T1 =3D DestType->getAs<ReferenceType>()->getPointeeType();
@@ -2806,8 +3174,9 @@
=20
   // Determine whether we are allowed to call explicit constructors or
   // explicit conversion operators.
-  bool AllowExplicit =3D Kind.getKind() =3D=3D InitializationKind::IK_Dire=
ct;
-
+  bool AllowExplicit =3D Kind.AllowExplicit();
+  bool AllowExplicitConvs =3D Kind.allowExplicitConversionFunctions();
+ =20
   const RecordType *T1RecordType =3D 0;
   if (AllowRValues && (T1RecordType =3D T1->getAs<RecordType>()) &&
       !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
@@ -2835,11 +3204,11 @@
         if (ConstructorTmpl)
           S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
                                          /*ExplicitArgs*/ 0,
-                                         &Initializer, 1, CandidateSet,
+                                         Initializer, CandidateSet,
                                          /*SuppressUserConversions=3D*/tru=
e);
         else
           S.AddOverloadCandidate(Constructor, FoundDecl,
-                                 &Initializer, 1, CandidateSet,
+                                 Initializer, CandidateSet,
                                  /*SuppressUserConversions=3D*/true);
       }
     }
@@ -2876,7 +3245,7 @@
       // FIXME: Do we need to make sure that we only consider conversion
       // candidates with reference-compatible results? That might be neede=
d to
       // break recursion.
-      if ((AllowExplicit || !Conv->isExplicit()) &&
+      if ((AllowExplicitConvs || !Conv->isExplicit()) &&
           (AllowRValues || Conv->getConversionType()->isLValueReferenceTyp=
e())){
         if (ConvTemplate)
           S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
@@ -2903,7 +3272,7 @@
=20
   // This is the overload that will actually be used for the initializatio=
n, so
   // mark it as used.
-  S.MarkDeclarationReferenced(DeclLoc, Function);
+  S.MarkFunctionReferenced(DeclLoc, Function);
=20
   // Compute the returned type of the conversion.
   if (isa<CXXConversionDecl>(Function))
@@ -2912,8 +3281,10 @@
     T2 =3D cv1T1;
=20
   // Add the user-defined conversion step.
+  bool HadMultipleCandidates =3D (CandidateSet.size() > 1);
   Sequence.AddUserConversionStep(Function, Best->FoundDecl,
-                                 T2.getNonLValueExprType(S.Context));
+                                 T2.getNonLValueExprType(S.Context),
+                                 HadMultipleCandidates);
=20
   // Determine whether we need to perform derived-to-base or
   // cv-qualification adjustments.
@@ -2958,6 +3329,10 @@
   return OR_Success;
 }
=20
+static void CheckCXX98CompatAccessibleCopy(Sema &S,
+                                           const InitializedEntity &Entity,
+                                           Expr *CurInitExpr);
+
 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
 static void TryReferenceInitialization(Sema &S,
                                        const InitializedEntity &Entity,
@@ -2971,26 +3346,31 @@
   QualType cv2T2 =3D Initializer->getType();
   Qualifiers T2Quals;
   QualType T2 =3D S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
-  SourceLocation DeclLoc =3D Initializer->getLocStart();
=20
   // If the initializer is the address of an overloaded function, try
   // to resolve the overloaded function. If all goes well, T2 is the
   // type of the resulting function.
-  if (S.Context.getCanonicalType(T2) =3D=3D S.Context.OverloadTy) {
-    DeclAccessPair Found;
-    if (FunctionDecl *Fn =3D S.ResolveAddressOfOverloadedFunction(Initiali=
zer,
-                                                                T1,
-                                                                false,
-                                                                Found)) {
-      Sequence.AddAddressOverloadResolutionStep(Fn, Found);
-      cv2T2 =3D Fn->getType();
-      T2 =3D cv2T2.getUnqualifiedType();
-    } else if (!T1->isRecordType()) {
-      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFaile=
d);
-      return;
-    }
-  }
-
+  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, =
T2,
+                                                   T1, Sequence))
+    return;
+
+  // Delegate everything else to a subfunction.
+  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
+                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
+}
+
+/// \brief Reference initialization without resolving overloaded functions.
+static void TryReferenceInitializationCore(Sema &S,
+                                           const InitializedEntity &Entity,
+                                           const InitializationKind &Kind,
+                                           Expr *Initializer,
+                                           QualType cv1T1, QualType T1,
+                                           Qualifiers T1Quals,
+                                           QualType cv2T2, QualType T2,
+                                           Qualifiers T2Quals,
+                                           InitializationSequence &Sequenc=
e) {
+  QualType DestType =3D Entity.getType();
+  SourceLocation DeclLoc =3D Initializer->getLocStart();
   // Compute some basic properties of the types and the initializer.
   bool isLValueRef =3D DestType->isLValueReferenceType();
   bool isRValueRef =3D !isLValueRef;
@@ -3108,8 +3488,10 @@
       //
       //   The constructor that would be used to make the copy shall
       //   be callable whether or not the copy is actually done.
-      if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft=
Ext)
+      if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
         Sequence.AddExtraneousCopyToTemporary(cv2T2);
+      else if (S.getLangOpts().CPlusPlus0x)
+        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
     }
=20
     if (DerivedToBase)
@@ -3122,7 +3504,7 @@
     if (T1Quals !=3D T2Quals)
       Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
     Sequence.AddReferenceBindingStep(cv1T1,
-         /*bindingTemporary=3D*/(InitCategory.isPRValue() && !T2->isArrayT=
ype()));
+                                 /*bindingTemporary=3D*/InitCategory.isPRV=
alue());
     return;
   }
=20
@@ -3155,7 +3537,7 @@
=20
   // Determine whether we are allowed to call explicit constructors or
   // explicit conversion operators.
-  bool AllowExplicit =3D (Kind.getKind() =3D=3D InitializationKind::IK_Dir=
ect);
+  bool AllowExplicit =3D Kind.AllowExplicit();
=20
   InitializedEntity TempEntity =3D InitializedEntity::InitializeTemporary(=
cv1T1);
=20
@@ -3219,146 +3601,47 @@
   Sequence.AddStringInitStep(Entity.getType());
 }
=20
-/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
-/// enumerates the constructors of the initialized entity and performs ove=
rload
-/// resolution to select the best.
-static void TryConstructorInitialization(Sema &S,
-                                         const InitializedEntity &Entity,
-                                         const InitializationKind &Kind,
-                                         Expr **Args, unsigned NumArgs,
-                                         QualType DestType,
-                                         InitializationSequence &Sequence)=
 {
-  // Check constructor arguments for self reference.
-  if (DeclaratorDecl *DD =3D Entity.getDecl())
-    // Parameters arguments are occassionially constructed with itself,
-    // for instance, in recursive functions.  Skip them.
-    if (!isa<ParmVarDecl>(DD))
-      for (unsigned i =3D 0; i < NumArgs; ++i)
-        S.CheckSelfReference(DD, Args[i]);
-
-  // Build the candidate set directly in the initialization sequence
-  // structure, so that it will persist if we fail.
-  OverloadCandidateSet &CandidateSet =3D Sequence.getFailedCandidateSet();
-  CandidateSet.clear();
-
-  // Determine whether we are allowed to call explicit constructors or
-  // explicit conversion operators.
-  bool AllowExplicit =3D (Kind.getKind() =3D=3D InitializationKind::IK_Dir=
ect ||
-                        Kind.getKind() =3D=3D InitializationKind::IK_Value=
 ||
-                        Kind.getKind() =3D=3D InitializationKind::IK_Defau=
lt);
-
-  // The type we're constructing needs to be complete.
-  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
-    Sequence.SetFailed(InitializationSequence::FK_Incomplete);
-    return;
-  }
-
-  // The type we're converting to is a class type. Enumerate its construct=
ors
-  // to see if one is suitable.
-  const RecordType *DestRecordType =3D DestType->getAs<RecordType>();
-  assert(DestRecordType && "Constructor initialization requires record typ=
e");
-  CXXRecordDecl *DestRecordDecl
-    =3D cast<CXXRecordDecl>(DestRecordType->getDecl());
-
-  DeclContext::lookup_iterator Con, ConEnd;
-  for (llvm::tie(Con, ConEnd) =3D S.LookupConstructors(DestRecordDecl);
-       Con !=3D ConEnd; ++Con) {
-    NamedDecl *D =3D *Con;
-    DeclAccessPair FoundDecl =3D DeclAccessPair::make(D, D->getAccess());
-    bool SuppressUserConversions =3D false;
-
-    // Find the constructor (which may be a template).
-    CXXConstructorDecl *Constructor =3D 0;
-    FunctionTemplateDecl *ConstructorTmpl =3D dyn_cast<FunctionTemplateDec=
l>(D);
-    if (ConstructorTmpl)
-      Constructor =3D cast<CXXConstructorDecl>(
-                                           ConstructorTmpl->getTemplatedDe=
cl());
-    else {
-      Constructor =3D cast<CXXConstructorDecl>(D);
-
-      // If we're performing copy initialization using a copy constructor,=
 we
-      // suppress user-defined conversions on the arguments.
-      // FIXME: Move constructors?
-      if (Kind.getKind() =3D=3D InitializationKind::IK_Copy &&
-          Constructor->isCopyConstructor())
-        SuppressUserConversions =3D true;
-    }
-
-    if (!Constructor->isInvalidDecl() &&
-        (AllowExplicit || !Constructor->isExplicit())) {
-      if (ConstructorTmpl)
-        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
-                                       /*ExplicitArgs*/ 0,
-                                       Args, NumArgs, CandidateSet,
-                                       SuppressUserConversions);
-      else
-        S.AddOverloadCandidate(Constructor, FoundDecl,
-                               Args, NumArgs, CandidateSet,
-                               SuppressUserConversions);
-    }
-  }
-
-  SourceLocation DeclLoc =3D Kind.getLocation();
-
-  // Perform overload resolution. If it fails, return the failed result.
-  OverloadCandidateSet::iterator Best;
-  if (OverloadingResult Result
-        =3D CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
-    Sequence.SetOverloadFailure(
-                          InitializationSequence::FK_ConstructorOverloadFa=
iled,
-                                Result);
-    return;
-  }
-
-  // C++0x [dcl.init]p6:
-  //   If a program calls for the default initialization of an object
-  //   of a const-qualified type T, T shall be a class type with a
-  //   user-provided default constructor.
-  if (Kind.getKind() =3D=3D InitializationKind::IK_Default &&
-      Entity.getType().isConstQualified() &&
-      cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
-    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
-    return;
-  }
-
-  // Add the constructor initialization step. Any cv-qualification convers=
ion is
-  // subsumed by the initialization.
-  Sequence.AddConstructorInitializationStep(
-                                      cast<CXXConstructorDecl>(Best->Funct=
ion),
-                                      Best->FoundDecl.getAccess(),
-                                      DestType);
-}
-
 /// \brief Attempt value initialization (C++ [dcl.init]p7).
 static void TryValueInitialization(Sema &S,
                                    const InitializedEntity &Entity,
                                    const InitializationKind &Kind,
                                    InitializationSequence &Sequence) {
-  // C++ [dcl.init]p5:
+  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
   //
   //   To value-initialize an object of type T means:
   QualType T =3D Entity.getType();
=20
   //     -- if T is an array type, then each element is value-initialized;
-  while (const ArrayType *AT =3D S.Context.getAsArrayType(T))
-    T =3D AT->getElementType();
+  T =3D S.Context.getBaseElementType(T);
=20
   if (const RecordType *RT =3D T->getAs<RecordType>()) {
     if (CXXRecordDecl *ClassDecl =3D dyn_cast<CXXRecordDecl>(RT->getDecl()=
)) {
+      // C++98:
       // -- if T is a class type (clause 9) with a user-declared
       //    constructor (12.1), then the default constructor for T is
       //    called (and the initialization is ill-formed if T has no
       //    accessible default constructor);
-      //
-      // FIXME: we really want to refer to a single subobject of the array,
-      // but Entity doesn't have a way to capture that (yet).
-      if (ClassDecl->hasUserDeclaredConstructor())
-        return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequ=
ence);
-
-      // -- if T is a (possibly cv-qualified) non-union class type
-      //    without a user-provided constructor, then the object is
-      //    zero-initialized and, if T's implicitly-declared default
-      //    constructor is non-trivial, that constructor is called.
+      if (!S.getLangOpts().CPlusPlus0x) {
+        if (ClassDecl->hasUserDeclaredConstructor())
+          // FIXME: we really want to refer to a single subobject of the a=
rray,
+          // but Entity doesn't have a way to capture that (yet).
+          return TryConstructorInitialization(S, Entity, Kind, 0, 0,
+                                              T, Sequence);
+      } else {
+        // C++11:
+        // -- if T is a class type (clause 9) with either no default const=
ructor
+        //    (12.1 [class.ctor]) or a default constructor that is user-pr=
ovided
+        //    or deleted, then the object is default-initialized;
+        CXXConstructorDecl *CD =3D S.LookupDefaultConstructor(ClassDecl);
+        if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted=
())
+          return TryConstructorInitialization(S, Entity, Kind, 0, 0,
+                                              T, Sequence);
+      }
+
+      // -- if T is a (possibly cv-qualified) non-union class type without=
 a
+      //    user-provided or deleted default constructor, then the object =
is
+      //    zero-initialized and, if T has a non-trivial default construct=
or,
+      //    default-initialized;
       if ((ClassDecl->getTagKind() =3D=3D TTK_Class ||
            ClassDecl->getTagKind() =3D=3D TTK_Struct)) {
         Sequence.AddZeroInitializationStep(Entity.getType());
@@ -3385,7 +3668,7 @@
   //     - if T is a (possibly cv-qualified) class type (Clause 9), the de=
fault
   //       constructor for T is called (and the initialization is ill-form=
ed if
   //       T has no accessible default constructor);
-  if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
+  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
     TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence=
);
     return;
   }
@@ -3395,7 +3678,7 @@
   //   If a program calls for the default initialization of an object of
   //   a const-qualified type T, T shall be a class type with a user-provi=
ded
   //   default constructor.
-  if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
+  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
     return;
   }
@@ -3428,7 +3711,7 @@
=20
   // Determine whether we are allowed to call explicit constructors or
   // explicit conversion operators.
-  bool AllowExplicit =3D Kind.getKind() =3D=3D InitializationKind::IK_Dire=
ct;
+  bool AllowExplicit =3D Kind.AllowExplicit();
=20
   if (const RecordType *DestRecordType =3D DestType->getAs<RecordType>()) {
     // The type we're converting to is a class type. Enumerate its constru=
ctors
@@ -3459,11 +3742,11 @@
           if (ConstructorTmpl)
             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
                                            /*ExplicitArgs*/ 0,
-                                           &Initializer, 1, CandidateSet,
+                                           Initializer, CandidateSet,
                                            /*SuppressUserConversions=3D*/t=
rue);
           else
             S.AddOverloadCandidate(Constructor, FoundDecl,
-                                   &Initializer, 1, CandidateSet,
+                                   Initializer, CandidateSet,
                                    /*SuppressUserConversions=3D*/true);
         }
       }
@@ -3523,29 +3806,35 @@
   }
=20
   FunctionDecl *Function =3D Best->Function;
-  S.MarkDeclarationReferenced(DeclLoc, Function);
+  S.MarkFunctionReferenced(DeclLoc, Function);
+  bool HadMultipleCandidates =3D (CandidateSet.size() > 1);
=20
   if (isa<CXXConstructorDecl>(Function)) {
     // Add the user-defined conversion step. Any cv-qualification conversi=
on is
-    // subsumed by the initialization.
-    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
+    // subsumed by the initialization. Per DR5, the created temporary is o=
f the
+    // cv-unqualified type of the destination.
+    Sequence.AddUserConversionStep(Function, Best->FoundDecl,
+                                   DestType.getUnqualifiedType(),
+                                   HadMultipleCandidates);
     return;
   }
=20
   // Add the user-defined conversion step that calls the conversion functi=
on.
   QualType ConvType =3D Function->getCallResultType();
   if (ConvType->getAs<RecordType>()) {
-    // If we're converting to a class type, there may be an copy if
+    // If we're converting to a class type, there may be an copy of
     // the resulting temporary object (possible to create an object of
     // a base class type). That copy is not a separate conversion, so
     // we just make a note of the actual destination type (possibly a
     // base class of the type returned by the conversion function) and
     // let the user-defined conversion step handle the conversion.
-    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
+    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
+                                   HadMultipleCandidates);
     return;
   }
=20
-  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
+  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
+                                 HadMultipleCandidates);
=20
   // If the conversion following the call to the conversion function
   // is interesting, add it as a separate step.
@@ -3592,16 +3881,11 @@
     }
=20
   // If we have a declaration reference, it had better be a local variable.
-  } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
+  } else if (isa<DeclRefExpr>(e)) {
     if (!isAddressOf) return IIK_nonlocal;
=20
-    VarDecl *var;
-    if (isa<DeclRefExpr>(e)) {
-      var =3D dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
-      if (!var) return IIK_nonlocal;
-    } else {
-      var =3D cast<BlockDeclRefExpr>(e)->getDecl();
-    }
+    VarDecl *var =3D dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
+    if (!var) return IIK_nonlocal;
=20
     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
=20
@@ -3721,7 +4005,7 @@
   QualType DestType =3D Entity.getType();
=20
   if (DestType->isDependentType() ||
-      Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
+      Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs)=
)) {
     SequenceKind =3D DependentSequence;
     return;
   }
@@ -3730,15 +4014,17 @@
   setSequenceKind(NormalSequence);
=20
   for (unsigned I =3D 0; I !=3D NumArgs; ++I)
-    if (Args[I]->getObjectKind() =3D=3D OK_ObjCProperty) {
-      ExprResult Result =3D S.ConvertPropertyForRValue(Args[I]);
-      if (Result.isInvalid()) {
-        SetFailed(FK_ConversionFromPropertyFailed);
+    if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
+      // FIXME: should we be doing this here?
+      ExprResult result =3D S.CheckPlaceholderExpr(Args[I]);
+      if (result.isInvalid()) {
+        SetFailed(FK_PlaceholderType);
         return;
       }
-      Args[I] =3D Result.take();
+      Args[I] =3D result.take();
     }
=20
+
   QualType SourceType;
   Expr *Initializer =3D 0;
   if (NumArgs =3D=3D 1) {
@@ -3747,11 +4033,13 @@
       SourceType =3D Initializer->getType();
   }
=20
-  //     - If the initializer is a braced-init-list, the object is
-  //       list-initialized (8.5.4).
-  if (InitListExpr *InitList =3D dyn_cast_or_null<InitListExpr>(Initialize=
r)) {
-    TryListInitialization(S, Entity, Kind, InitList, *this);
-    return;
+  //     - If the initializer is a (non-parenthesized) braced-init-list, t=
he
+  //       object is list-initialized (8.5.4).
+  if (Kind.getKind() !=3D InitializationKind::IK_Direct) {
+    if (InitListExpr *InitList =3D dyn_cast_or_null<InitListExpr>(Initiali=
zer)) {
+      TryListInitialization(S, Entity, Kind, InitList, *this);
+      return;
+    }
   }
=20
   //     - If the destination type is a reference type, see 8.5.3.
@@ -3787,6 +4075,11 @@
   //     - Otherwise, if the destination type is an array, the program is
   //       ill-formed.
   if (const ArrayType *DestAT =3D Context.getAsArrayType(DestType)) {
+    if (Initializer && isa<VariableArrayType>(DestAT)) {
+      SetFailed(FK_VariableLengthArrayHasInitializer);
+      return;
+    }
+
     if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
       TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
       return;
@@ -3795,7 +4088,7 @@
     // Note: as an GNU C extension, we allow initialization of an
     // array from a compound literal that creates an array of the same
     // type, so long as the initializer has no side effects.
-    if (!S.getLangOptions().CPlusPlus && Initializer &&
+    if (!S.getLangOpts().CPlusPlus && Initializer &&
         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
         Initializer->getType()->isArrayType()) {
       const ArrayType *SourceAT
@@ -3807,6 +4100,15 @@
       else {
         AddArrayInitStep(DestType);
       }
+    }
+    // Note: as a GNU C++ extension, we allow initialization of a
+    // class member from a parenthesized initializer list.
+    else if (S.getLangOpts().CPlusPlus &&
+             Entity.getKind() =3D=3D InitializedEntity::EK_Member &&
+             Initializer && isa<InitListExpr>(Initializer)) {
+      TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initialize=
r),
+                            *this);
+      AddParenthesizedArrayInitStep(DestType);
     } else if (DestAT->getElementType()->isAnyCharacterType())
       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
     else
@@ -3817,12 +4119,12 @@
=20
   // Determine whether we should consider writeback conversions for=20
   // Objective-C ARC.
-  bool allowObjCWritebackConversion =3D S.getLangOptions().ObjCAutoRefCoun=
t &&
+  bool allowObjCWritebackConversion =3D S.getLangOpts().ObjCAutoRefCount &&
     Entity.getKind() =3D=3D InitializedEntity::EK_Parameter;
=20
   // We're at the end of the line for C: it's either a write-back conversi=
on
   // or it's a C assignment. There's no need to check anything else.
-  if (!S.getLangOptions().CPlusPlus) {
+  if (!S.getLangOpts().CPlusPlus) {
     // If allowed, check whether this is an Objective-C writeback conversi=
on.
     if (allowObjCWritebackConversion &&
         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
@@ -3835,7 +4137,7 @@
     return;
   }
=20
-  assert(S.getLangOptions().CPlusPlus);
+  assert(S.getLangOpts().CPlusPlus);
      =20
   //     - If the destination type is a (possibly cv-qualified) class type:
   if (DestType->isRecordType()) {
@@ -3964,10 +4266,11 @@
   case InitializedEntity::EK_VectorElement:
   case InitializedEntity::EK_ComplexElement:
   case InitializedEntity::EK_BlockElement:
+  case InitializedEntity::EK_LambdaCapture:
     return Sema::AA_Initializing;
   }
=20
-  return Sema::AA_Converting;
+  llvm_unreachable("Invalid EntityKind!");
 }
=20
 /// \brief Whether we should binding a created object as a temporary when
@@ -3985,6 +4288,7 @@
   case InitializedEntity::EK_ComplexElement:
   case InitializedEntity::EK_Exception:
   case InitializedEntity::EK_BlockElement:
+  case InitializedEntity::EK_LambdaCapture:
     return false;
=20
   case InitializedEntity::EK_Parameter:
@@ -4007,6 +4311,7 @@
     case InitializedEntity::EK_VectorElement:
     case InitializedEntity::EK_ComplexElement:
     case InitializedEntity::EK_BlockElement:
+    case InitializedEntity::EK_LambdaCapture:
       return false;
=20
     case InitializedEntity::EK_Variable:
@@ -4020,6 +4325,81 @@
   llvm_unreachable("missed an InitializedEntity kind?");
 }
=20
+/// \brief Look for copy and move constructors and constructor templates, =
for
+/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
+static void LookupCopyAndMoveConstructors(Sema &S,
+                                          OverloadCandidateSet &CandidateS=
et,
+                                          CXXRecordDecl *Class,
+                                          Expr *CurInitExpr) {
+  DeclContext::lookup_iterator Con, ConEnd;
+  for (llvm::tie(Con, ConEnd) =3D S.LookupConstructors(Class);
+       Con !=3D ConEnd; ++Con) {
+    CXXConstructorDecl *Constructor =3D 0;
+
+    if ((Constructor =3D dyn_cast<CXXConstructorDecl>(*Con))) {
+      // Handle copy/moveconstructors, only.
+      if (!Constructor || Constructor->isInvalidDecl() ||
+          !Constructor->isCopyOrMoveConstructor() ||
+          !Constructor->isConvertingConstructor(/*AllowExplicit=3D*/true))
+        continue;
+
+      DeclAccessPair FoundDecl
+        =3D DeclAccessPair::make(Constructor, Constructor->getAccess());
+      S.AddOverloadCandidate(Constructor, FoundDecl,
+                             CurInitExpr, CandidateSet);
+      continue;
+    }
+
+    // Handle constructor templates.
+    FunctionTemplateDecl *ConstructorTmpl =3D cast<FunctionTemplateDecl>(*=
Con);
+    if (ConstructorTmpl->isInvalidDecl())
+      continue;
+
+    Constructor =3D cast<CXXConstructorDecl>(
+                                         ConstructorTmpl->getTemplatedDecl=
());
+    if (!Constructor->isConvertingConstructor(/*AllowExplicit=3D*/true))
+      continue;
+
+    // FIXME: Do we need to limit this to copy-constructor-like
+    // candidates?
+    DeclAccessPair FoundDecl
+      =3D DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess=
());
+    S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
+                                   CurInitExpr, CandidateSet, true);
+  }
+}
+
+/// \brief Get the location at which initialization diagnostics should app=
ear.
+static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
+                                           Expr *Initializer) {
+  switch (Entity.getKind()) {
+  case InitializedEntity::EK_Result:
+    return Entity.getReturnLoc();
+
+  case InitializedEntity::EK_Exception:
+    return Entity.getThrowLoc();
+
+  case InitializedEntity::EK_Variable:
+    return Entity.getDecl()->getLocation();
+
+  case InitializedEntity::EK_LambdaCapture:
+    return Entity.getCaptureLoc();
+     =20
+  case InitializedEntity::EK_ArrayElement:
+  case InitializedEntity::EK_Member:
+  case InitializedEntity::EK_Parameter:
+  case InitializedEntity::EK_Temporary:
+  case InitializedEntity::EK_New:
+  case InitializedEntity::EK_Base:
+  case InitializedEntity::EK_Delegating:
+  case InitializedEntity::EK_VectorElement:
+  case InitializedEntity::EK_ComplexElement:
+  case InitializedEntity::EK_BlockElement:
+    return Initializer->getLocStart();
+  }
+  llvm_unreachable("missed an InitializedEntity kind?");
+}
+
 /// \brief Make a (potentially elidable) temporary copy of the object
 /// provided by the given initializer by calling the appropriate copy
 /// constructor.
@@ -4069,79 +4449,18 @@
   // of constructor initialization, while copy elision for exception handl=
ers
   // is handled by the run-time.
   bool Elidable =3D CurInitExpr->isTemporaryObject(S.Context, Class);
-  SourceLocation Loc;
-  switch (Entity.getKind()) {
-  case InitializedEntity::EK_Result:
-    Loc =3D Entity.getReturnLoc();
-    break;
-
-  case InitializedEntity::EK_Exception:
-    Loc =3D Entity.getThrowLoc();
-    break;
-
-  case InitializedEntity::EK_Variable:
-    Loc =3D Entity.getDecl()->getLocation();
-    break;
-
-  case InitializedEntity::EK_ArrayElement:
-  case InitializedEntity::EK_Member:
-  case InitializedEntity::EK_Parameter:
-  case InitializedEntity::EK_Temporary:
-  case InitializedEntity::EK_New:
-  case InitializedEntity::EK_Base:
-  case InitializedEntity::EK_Delegating:
-  case InitializedEntity::EK_VectorElement:
-  case InitializedEntity::EK_ComplexElement:
-  case InitializedEntity::EK_BlockElement:
-    Loc =3D CurInitExpr->getLocStart();
-    break;
-  }
+  SourceLocation Loc =3D getInitializationLoc(Entity, CurInit.get());
=20
   // Make sure that the type we are copying is complete.
   if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete=
)))
     return move(CurInit);
=20
   // Perform overload resolution using the class's copy/move constructors.
-  DeclContext::lookup_iterator Con, ConEnd;
+  // Only consider constructors and constructor templates. Per
+  // C++0x [dcl.init]p16, second bullet to class types, this initialization
+  // is direct-initialization.
   OverloadCandidateSet CandidateSet(Loc);
-  for (llvm::tie(Con, ConEnd) =3D S.LookupConstructors(Class);
-       Con !=3D ConEnd; ++Con) {
-    // Only consider copy/move constructors and constructor templates. Per
-    // C++0x [dcl.init]p16, second bullet to class types, this
-    // initialization is direct-initialization.
-    CXXConstructorDecl *Constructor =3D 0;
-
-    if ((Constructor =3D dyn_cast<CXXConstructorDecl>(*Con))) {
-      // Handle copy/moveconstructors, only.
-      if (!Constructor || Constructor->isInvalidDecl() ||
-          !Constructor->isCopyOrMoveConstructor() ||
-          !Constructor->isConvertingConstructor(/*AllowExplicit=3D*/true))
-        continue;
-
-      DeclAccessPair FoundDecl
-        =3D DeclAccessPair::make(Constructor, Constructor->getAccess());
-      S.AddOverloadCandidate(Constructor, FoundDecl,
-                             &CurInitExpr, 1, CandidateSet);
-      continue;
-    }
-
-    // Handle constructor templates.
-    FunctionTemplateDecl *ConstructorTmpl =3D cast<FunctionTemplateDecl>(*=
Con);
-    if (ConstructorTmpl->isInvalidDecl())
-      continue;
-
-    Constructor =3D cast<CXXConstructorDecl>(
-                                         ConstructorTmpl->getTemplatedDecl=
());
-    if (!Constructor->isConvertingConstructor(/*AllowExplicit=3D*/true))
-      continue;
-
-    // FIXME: Do we need to limit this to copy-constructor-like
-    // candidates?
-    DeclAccessPair FoundDecl
-      =3D DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess=
());
-    S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
-                                   &CurInitExpr, 1, CandidateSet, true);
-  }
+  LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
=20
   bool HadMultipleCandidates =3D (CandidateSet.size() > 1);
=20
@@ -4156,7 +4475,7 @@
            : diag::err_temp_copy_no_viable)
       << (int)Entity.getKind() << CurInitExpr->getType()
       << CurInitExpr->getSourceRange();
-    CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
+    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
     if (!IsExtraneousCopy || S.isSFINAEContext())
       return ExprError();
     return move(CurInit);
@@ -4165,15 +4484,14 @@
     S.Diag(Loc, diag::err_temp_copy_ambiguous)
       << (int)Entity.getKind() << CurInitExpr->getType()
       << CurInitExpr->getSourceRange();
-    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
+    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
     return ExprError();
=20
   case OR_Deleted:
     S.Diag(Loc, diag::err_temp_copy_deleted)
       << (int)Entity.getKind() << CurInitExpr->getType()
       << CurInitExpr->getSourceRange();
-    S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
-      << 1 << Best->Function->isDeleted();
+    S.NoteDeletedFunction(Best->Function);
     return ExprError();
   }
=20
@@ -4210,7 +4528,7 @@
     return S.Owned(CurInitExpr);
   }
=20
-  S.MarkDeclarationReferenced(Loc, Constructor);
+  S.MarkFunctionReferenced(Loc, Constructor);
=20
   // Determine the arguments required to actually perform the
   // constructor call (we might have derived-to-base conversions, or
@@ -4233,6 +4551,60 @@
   return move(CurInit);
 }
=20
+/// \brief Check whether elidable copy construction for binding a referenc=
e to
+/// a temporary would have succeeded if we were building in C++98 mode, for
+/// -Wc++98-compat.
+static void CheckCXX98CompatAccessibleCopy(Sema &S,
+                                           const InitializedEntity &Entity,
+                                           Expr *CurInitExpr) {
+  assert(S.getLangOpts().CPlusPlus0x);
+
+  const RecordType *Record =3D CurInitExpr->getType()->getAs<RecordType>();
+  if (!Record)
+    return;
+
+  SourceLocation Loc =3D getInitializationLoc(Entity, CurInitExpr);
+  if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
+        =3D=3D DiagnosticsEngine::Ignored)
+    return;
+
+  // Find constructors which would have been considered.
+  OverloadCandidateSet CandidateSet(Loc);
+  LookupCopyAndMoveConstructors(
+      S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr=
);
+
+  // Perform overload resolution.
+  OverloadCandidateSet::iterator Best;
+  OverloadingResult OR =3D CandidateSet.BestViableFunction(S, Loc, Best);
+
+  PartialDiagnostic Diag =3D S.PDiag(diag::warn_cxx98_compat_temp_copy)
+    << OR << (int)Entity.getKind() << CurInitExpr->getType()
+    << CurInitExpr->getSourceRange();
+
+  switch (OR) {
+  case OR_Success:
+    S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
+                             Entity, Best->FoundDecl.getAccess(), Diag);
+    // FIXME: Check default arguments as far as that's possible.
+    break;
+
+  case OR_No_Viable_Function:
+    S.Diag(Loc, Diag);
+    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
+    break;
+
+  case OR_Ambiguous:
+    S.Diag(Loc, Diag);
+    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
+    break;
+
+  case OR_Deleted:
+    S.Diag(Loc, Diag);
+    S.NoteDeletedFunction(Best->Function);
+    break;
+  }
+}
+
 void InitializationSequence::PrintInitLocationNote(Sema &S,
                                               const InitializedEntity &Ent=
ity) {
   if (Entity.getKind() =3D=3D InitializedEntity::EK_Parameter && Entity.ge=
tDecl()) {
@@ -4252,6 +4624,130 @@
          s.Kind =3D=3D InitializationSequence::SK_BindReferenceToTemporary;
 }
=20
+static ExprResult
+PerformConstructorInitialization(Sema &S,
+                                 const InitializedEntity &Entity,
+                                 const InitializationKind &Kind,
+                                 MultiExprArg Args,
+                                 const InitializationSequence::Step& Step,
+                                 bool &ConstructorInitRequiresZeroInit) {
+  unsigned NumArgs =3D Args.size();
+  CXXConstructorDecl *Constructor
+    =3D cast<CXXConstructorDecl>(Step.Function.Function);
+  bool HadMultipleCandidates =3D Step.Function.HadMultipleCandidates;
+
+  // Build a call to the selected constructor.
+  ASTOwningVector<Expr*> ConstructorArgs(S);
+  SourceLocation Loc =3D (Kind.isCopyInit() && Kind.getEqualLoc().isValid(=
))
+                         ? Kind.getEqualLoc()
+                         : Kind.getLocation();
+
+  if (Kind.getKind() =3D=3D InitializationKind::IK_Default) {
+    // Force even a trivial, implicit default constructor to be
+    // semantically checked. We do this explicitly because we don't build
+    // the definition for completely trivial constructors.
+    assert(Constructor->getParent() && "No parent class for constructor.");
+    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() =
&&
+        Constructor->isTrivial() && !Constructor->isUsed(false))
+      S.DefineImplicitDefaultConstructor(Loc, Constructor);
+  }
+
+  ExprResult CurInit =3D S.Owned((Expr *)0);
+
+  // C++ [over.match.copy]p1:
+  //   - When initializing a temporary to be bound to the first parameter=20
+  //     of a constructor that takes a reference to possibly cv-qualified=20
+  //     T as its first argument, called with a single argument in the=20
+  //     context of direct-initialization, explicit conversion functions
+  //     are also considered.
+  bool AllowExplicitConv =3D Kind.AllowExplicit() && !Kind.isCopyInit() &&
+                           Args.size() =3D=3D 1 &&=20
+                           Constructor->isCopyOrMoveConstructor();
+
+  // Determine the arguments required to actually perform the constructor
+  // call.
+  if (S.CompleteConstructorCall(Constructor, move(Args),
+                                Loc, ConstructorArgs,
+                                AllowExplicitConv))
+    return ExprError();
+
+
+  if (Entity.getKind() =3D=3D InitializedEntity::EK_Temporary &&
+      (Kind.getKind() =3D=3D InitializationKind::IK_DirectList ||
+       (NumArgs !=3D 1 && // FIXME: Hack to work around cast weirdness
+        (Kind.getKind() =3D=3D InitializationKind::IK_Direct ||
+         Kind.getKind() =3D=3D InitializationKind::IK_Value)))) {
+    // An explicitly-constructed temporary, e.g., X(1, 2).
+    unsigned NumExprs =3D ConstructorArgs.size();
+    Expr **Exprs =3D (Expr **)ConstructorArgs.take();
+    S.MarkFunctionReferenced(Loc, Constructor);
+    S.DiagnoseUseOfDecl(Constructor, Loc);
+
+    TypeSourceInfo *TSInfo =3D Entity.getTypeSourceInfo();
+    if (!TSInfo)
+      TSInfo =3D S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
+    SourceRange ParenRange;
+    if (Kind.getKind() !=3D InitializationKind::IK_DirectList)
+      ParenRange =3D Kind.getParenRange();
+
+    CurInit =3D S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
+                                                             Constructor,
+                                                             TSInfo,
+                                                             Exprs,
+                                                             NumExprs,
+                                                             ParenRange,
+                                                     HadMultipleCandidates,
+                                         ConstructorInitRequiresZeroInit));
+  } else {
+    CXXConstructExpr::ConstructionKind ConstructKind =3D
+      CXXConstructExpr::CK_Complete;
+
+    if (Entity.getKind() =3D=3D InitializedEntity::EK_Base) {
+      ConstructKind =3D Entity.getBaseSpecifier()->isVirtual() ?
+        CXXConstructExpr::CK_VirtualBase :
+        CXXConstructExpr::CK_NonVirtualBase;
+    } else if (Entity.getKind() =3D=3D InitializedEntity::EK_Delegating) {
+      ConstructKind =3D CXXConstructExpr::CK_Delegating;
+    }
+
+    // Only get the parenthesis range if it is a direct construction.
+    SourceRange parenRange =3D
+        Kind.getKind() =3D=3D InitializationKind::IK_Direct ?
+        Kind.getParenRange() : SourceRange();
+
+    // If the entity allows NRVO, mark the construction as elidable
+    // unconditionally.
+    if (Entity.allowsNRVO())
+      CurInit =3D S.BuildCXXConstructExpr(Loc, Entity.getType(),
+                                        Constructor, /*Elidable=3D*/true,
+                                        move_arg(ConstructorArgs),
+                                        HadMultipleCandidates,
+                                        ConstructorInitRequiresZeroInit,
+                                        ConstructKind,
+                                        parenRange);
+    else
+      CurInit =3D S.BuildCXXConstructExpr(Loc, Entity.getType(),
+                                        Constructor,
+                                        move_arg(ConstructorArgs),
+                                        HadMultipleCandidates,
+                                        ConstructorInitRequiresZeroInit,
+                                        ConstructKind,
+                                        parenRange);
+  }
+  if (CurInit.isInvalid())
+    return ExprError();
+
+  // Only check access if all of that succeeded.
+  S.CheckConstructorAccess(Loc, Constructor, Entity,
+                           Step.Function.FoundDecl.getAccess());
+  S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
+
+  if (shouldBindAsTemporary(Entity))
+    CurInit =3D S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
+
+  return move(CurInit);
+}
+
 ExprResult
 InitializationSequence::Perform(Sema &S,
                                 const InitializedEntity &Entity,
@@ -4303,8 +4799,16 @@
=20
       }
     }
+    if (Kind.getKind() =3D=3D InitializationKind::IK_Direct &&
+        !Kind.isExplicitCast()) {
+      // Rebuild the ParenListExpr.
+      SourceRange ParenRange =3D Kind.getParenRange();
+      return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd=
(),
+                                  move(Args));
+    }
     assert(Kind.getKind() =3D=3D InitializationKind::IK_Copy ||
-           Kind.isExplicitCast());
+           Kind.isExplicitCast() ||=20
+           Kind.getKind() =3D=3D InitializationKind::IK_DirectList);
     return ExprResult(Args.release()[0]);
   }
=20
@@ -4340,23 +4844,20 @@
   case SK_ConversionSequence:
   case SK_ListConstructorCall:
   case SK_ListInitialization:
+  case SK_UnwrapInitList:
+  case SK_RewrapInitList:
   case SK_CAssignment:
   case SK_StringInit:
   case SK_ObjCObjectConversion:
   case SK_ArrayInit:
+  case SK_ParenthesizedArrayInit:
   case SK_PassByIndirectCopyRestore:
   case SK_PassByIndirectRestore:
-  case SK_ProduceObjCObject: {
+  case SK_ProduceObjCObject:
+  case SK_StdInitializerList: {
     assert(Args.size() =3D=3D 1);
     CurInit =3D Args.get()[0];
     if (!CurInit.get()) return ExprError();
-
-    // Read from a property when initializing something with it.
-    if (CurInit.get()->getObjectKind() =3D=3D OK_ObjCProperty) {
-      CurInit =3D S.ConvertPropertyForRValue(CurInit.take());
-      if (CurInit.isInvalid())
-        return ExprError();
-    }
     break;
   }
=20
@@ -4466,7 +4967,7 @@
=20
       // If we're binding to an Objective-C object that has lifetime, we
       // need cleanups.
-      if (S.getLangOptions().ObjCAutoRefCount &&
+      if (S.getLangOpts().ObjCAutoRefCount &&
           CurInit.get()->getType()->isObjCLifetimeType())
         S.ExprNeedsCleanups =3D true;
            =20
@@ -4500,7 +5001,7 @@
                                       Loc, ConstructorArgs))
           return ExprError();
=20
-        // Build the an expression that constructs a temporary.
+        // Build an expression that constructs a temporary.
         CurInit =3D S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
                                           move_arg(ConstructorArgs),
                                           HadMultipleCandidates,
@@ -4550,16 +5051,16 @@
       }
=20
       bool RequiresCopy =3D !IsCopy && !isReferenceBinding(Steps.back());
-      if (RequiresCopy || shouldBindAsTemporary(Entity))
-        CurInit =3D S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
-      else if (CreatedObject && shouldDestroyTemporary(Entity)) {
+      bool MaybeBindToTemp =3D RequiresCopy || shouldBindAsTemporary(Entit=
y);
+
+      if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Enti=
ty)) {
         QualType T =3D CurInit.get()->getType();
         if (const RecordType *Record =3D T->getAs<RecordType>()) {
           CXXDestructorDecl *Destructor
             =3D S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
           S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
                                   S.PDiag(diag::err_access_dtor_temp) << T=
);
-          S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destru=
ctor);
+          S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructo=
r);
           S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
         }
       }
@@ -4568,11 +5069,11 @@
                                                  CurInit.get()->getType(),
                                                  CastKind, CurInit.get(), =
0,
                                                 CurInit.get()->getValueKin=
d()));
-
+      if (MaybeBindToTemp)
+        CurInit =3D S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
       if (RequiresCopy)
         CurInit =3D CopyObject(S, Entity.getType().getNonReferenceType(), =
Entity,
                              move(CurInit), /*IsExtraneousCopy=3D*/false);
-
       break;
     }
=20
@@ -4607,120 +5108,89 @@
=20
     case SK_ListInitialization: {
       InitListExpr *InitList =3D cast<InitListExpr>(CurInit.get());
-      QualType Ty =3D Step->Type;
-      InitListChecker PerformInitList(S, Entity, InitList,
-          ResultType ? *ResultType : Ty, /*VerifyOnly=3D*/false);
+      // Hack: We must pass *ResultType if available in order to set the t=
ype
+      // of arrays, e.g. in 'int ar[] =3D {1, 2, 3};'.
+      // But in 'const X &x =3D {1, 2, 3};' we're supposed to initialize a
+      // temporary, not a reference, so we should pass Ty.
+      // Worst case: 'const int (&arref)[] =3D {1, 2, 3};'.
+      // Since this step is never used for a reference directly, we explic=
itly
+      // unwrap references here and rewrap them afterwards.
+      // We also need to create a InitializeTemporary entity for this.
+      QualType Ty =3D ResultType ? ResultType->getNonReferenceType() : Ste=
p->Type;
+      bool IsTemporary =3D Entity.getType()->isReferenceType();
+      InitializedEntity TempEntity =3D InitializedEntity::InitializeTempor=
ary(Ty);
+      InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
+          InitList, Ty, /*VerifyOnly=3D*/false,
+          Kind.getKind() !=3D InitializationKind::IK_DirectList ||
+            !S.getLangOpts().CPlusPlus0x);
       if (PerformInitList.HadError())
         return ExprError();
=20
+      if (ResultType) {
+        if ((*ResultType)->isRValueReferenceType())
+          Ty =3D S.Context.getRValueReferenceType(Ty);
+        else if ((*ResultType)->isLValueReferenceType())
+          Ty =3D S.Context.getLValueReferenceType(Ty,
+            (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue=
());
+        *ResultType =3D Ty;
+      }
+
+      InitListExpr *StructuredInitList =3D
+          PerformInitList.getFullyStructuredList();
       CurInit.release();
-      CurInit =3D S.Owned(PerformInitList.getFullyStructuredList());
+      CurInit =3D S.Owned(StructuredInitList);
       break;
     }
=20
-    case SK_ListConstructorCall:
-      assert(false && "List constructor calls not yet supported.");
+    case SK_ListConstructorCall: {
+      // When an initializer list is passed for a parameter of type "refer=
ence
+      // to object", we don't get an EK_Temporary entity, but instead an
+      // EK_Parameter entity with reference type.
+      // FIXME: This is a hack. What we really should do is create a user
+      // conversion step for this case, but this makes it considerably more
+      // complicated. For now, this will do.
+      InitializedEntity TempEntity =3D InitializedEntity::InitializeTempor=
ary(
+                                        Entity.getType().getNonReferenceTy=
pe());
+      bool UseTemporary =3D Entity.getType()->isReferenceType();
+      InitListExpr *InitList =3D cast<InitListExpr>(CurInit.get());
+      MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
+      CurInit =3D PerformConstructorInitialization(S, UseTemporary ? TempE=
ntity :
+                                                                   Entity,
+                                                 Kind, move(Arg), *Step,
+                                               ConstructorInitRequiresZero=
Init);
+      break;
+    }
+
+    case SK_UnwrapInitList:
+      CurInit =3D S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
+      break;
+
+    case SK_RewrapInitList: {
+      Expr *E =3D CurInit.take();
+      InitListExpr *Syntactic =3D Step->WrappingSyntacticList;
+      InitListExpr *ILE =3D new (S.Context) InitListExpr(S.Context,
+          Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
+      ILE->setSyntacticForm(Syntactic);
+      ILE->setType(E->getType());
+      ILE->setValueKind(E->getValueKind());
+      CurInit =3D S.Owned(ILE);
+      break;
+    }
=20
     case SK_ConstructorInitialization: {
-      unsigned NumArgs =3D Args.size();
-      CXXConstructorDecl *Constructor
-        =3D cast<CXXConstructorDecl>(Step->Function.Function);
-      bool HadMultipleCandidates =3D Step->Function.HadMultipleCandidates;
-
-      // Build a call to the selected constructor.
-      ASTOwningVector<Expr*> ConstructorArgs(S);
-      SourceLocation Loc =3D (Kind.isCopyInit() && Kind.getEqualLoc().isVa=
lid())
-                             ? Kind.getEqualLoc()
-                             : Kind.getLocation();
-
-      if (Kind.getKind() =3D=3D InitializationKind::IK_Default) {
-        // Force even a trivial, implicit default constructor to be
-        // semantically checked. We do this explicitly because we don't bu=
ild
-        // the definition for completely trivial constructors.
-        CXXRecordDecl *ClassDecl =3D Constructor->getParent();
-        assert(ClassDecl && "No parent class for constructor.");
-        if (Constructor->isDefaulted() && Constructor->isDefaultConstructo=
r() &&
-            ClassDecl->hasTrivialDefaultConstructor() &&
-            !Constructor->isUsed(false))
-          S.DefineImplicitDefaultConstructor(Loc, Constructor);
-      }
-
-      // Determine the arguments required to actually perform the construc=
tor
-      // call.
-      if (S.CompleteConstructorCall(Constructor, move(Args),
-                                    Loc, ConstructorArgs))
-        return ExprError();
-
-
-      if (Entity.getKind() =3D=3D InitializedEntity::EK_Temporary &&
-          NumArgs !=3D 1 && // FIXME: Hack to work around cast weirdness
-          (Kind.getKind() =3D=3D InitializationKind::IK_Direct ||
-           Kind.getKind() =3D=3D InitializationKind::IK_Value)) {
-        // An explicitly-constructed temporary, e.g., X(1, 2).
-        unsigned NumExprs =3D ConstructorArgs.size();
-        Expr **Exprs =3D (Expr **)ConstructorArgs.take();
-        S.MarkDeclarationReferenced(Loc, Constructor);
-        S.DiagnoseUseOfDecl(Constructor, Loc);
-
-        TypeSourceInfo *TSInfo =3D Entity.getTypeSourceInfo();
-        if (!TSInfo)
-          TSInfo =3D S.Context.getTrivialTypeSourceInfo(Entity.getType(), =
Loc);
-
-        CurInit =3D S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Conte=
xt,
-                                                                 Construct=
or,
-                                                                 TSInfo,
-                                                                 Exprs,
-                                                                 NumExprs,
-                                                         Kind.getParenRang=
e(),
-                                                         HadMultipleCandid=
ates,
-                                             ConstructorInitRequiresZeroIn=
it));
-      } else {
-        CXXConstructExpr::ConstructionKind ConstructKind =3D
-          CXXConstructExpr::CK_Complete;
-
-        if (Entity.getKind() =3D=3D InitializedEntity::EK_Base) {
-          ConstructKind =3D Entity.getBaseSpecifier()->isVirtual() ?
-            CXXConstructExpr::CK_VirtualBase :
-            CXXConstructExpr::CK_NonVirtualBase;
-        } else if (Entity.getKind() =3D=3D InitializedEntity::EK_Delegatin=
g) {
-          ConstructKind =3D CXXConstructExpr::CK_Delegating;
-        }
-
-        // Only get the parenthesis range if it is a direct construction.
-        SourceRange parenRange =3D
-            Kind.getKind() =3D=3D InitializationKind::IK_Direct ?
-            Kind.getParenRange() : SourceRange();
-
-        // If the entity allows NRVO, mark the construction as elidable
-        // unconditionally.
-        if (Entity.allowsNRVO())
-          CurInit =3D S.BuildCXXConstructExpr(Loc, Entity.getType(),
-                                            Constructor, /*Elidable=3D*/tr=
ue,
-                                            move_arg(ConstructorArgs),
-                                            HadMultipleCandidates,
-                                            ConstructorInitRequiresZeroIni=
t,
-                                            ConstructKind,
-                                            parenRange);
-        else
-          CurInit =3D S.BuildCXXConstructExpr(Loc, Entity.getType(),
-                                            Constructor,
-                                            move_arg(ConstructorArgs),
-                                            HadMultipleCandidates,
-                                            ConstructorInitRequiresZeroIni=
t,
-                                            ConstructKind,
-                                            parenRange);
-      }
-      if (CurInit.isInvalid())
-        return ExprError();
-
-      // Only check access if all of that succeeded.
-      S.CheckConstructorAccess(Loc, Constructor, Entity,
-                               Step->Function.FoundDecl.getAccess());
-      S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
-
-      if (shouldBindAsTemporary(Entity))
-        CurInit =3D S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
-
+      // When an initializer list is passed for a parameter of type "refer=
ence
+      // to object", we don't get an EK_Temporary entity, but instead an
+      // EK_Parameter entity with reference type.
+      // FIXME: This is a hack. What we really should do is create a user
+      // conversion step for this case, but this makes it considerably more
+      // complicated. For now, this will do.
+      InitializedEntity TempEntity =3D InitializedEntity::InitializeTempor=
ary(
+                                        Entity.getType().getNonReferenceTy=
pe());
+      bool UseTemporary =3D Entity.getType()->isReferenceType();
+      CurInit =3D PerformConstructorInitialization(S, UseTemporary ? TempE=
ntity
+                                                                 : Entity,
+                                                 Kind, move(Args), *Step,
+                                               ConstructorInitRequiresZero=
Init);
       break;
     }
=20
@@ -4733,7 +5203,7 @@
         // the call to the object's constructor within the next step.
         ConstructorInitRequiresZeroInit =3D true;
       } else if (Kind.getKind() =3D=3D InitializationKind::IK_Value &&
-                 S.getLangOptions().CPlusPlus &&
+                 S.getLangOpts().CPlusPlus &&
                  !Kind.isImplicitValueInit()) {
         TypeSourceInfo *TSInfo =3D Entity.getTypeSourceInfo();
         if (!TSInfo)
@@ -4819,6 +5289,13 @@
       }
       break;
=20
+    case SK_ParenthesizedArrayInit:
+      // Okay: we checked everything before creating this step. Note that
+      // this is a GNU extension.
+      S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
+        << CurInit.get()->getSourceRange();
+      break;
+
     case SK_PassByIndirectCopyRestore:
     case SK_PassByIndirectRestore:
       checkIndirectCopyRestoreSource(S, CurInit.get());
@@ -4832,6 +5309,54 @@
                                                  CK_ARCProduceObject,
                                                  CurInit.take(), 0, VK_RVa=
lue));
       break;
+
+    case SK_StdInitializerList: {
+      QualType Dest =3D Step->Type;
+      QualType E;
+      bool Success =3D S.isStdInitializerList(Dest, &E);
+      (void)Success;
+      assert(Success && "Destination type changed?");
+
+      // If the element type has a destructor, check it.
+      if (CXXRecordDecl *RD =3D E->getAsCXXRecordDecl()) {
+        if (!RD->hasIrrelevantDestructor()) {
+          if (CXXDestructorDecl *Destructor =3D S.LookupDestructor(RD)) {
+            S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
+            S.CheckDestructorAccess(Kind.getLocation(), Destructor,
+                                    S.PDiag(diag::err_access_dtor_temp) <<=
 E);
+            S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
+          }
+        }
+      }
+
+      InitListExpr *ILE =3D cast<InitListExpr>(CurInit.take());
+      unsigned NumInits =3D ILE->getNumInits();
+      SmallVector<Expr*, 16> Converted(NumInits);
+      InitializedEntity HiddenArray =3D InitializedEntity::InitializeTempo=
rary(
+          S.Context.getConstantArrayType(E,
+              llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
+                          NumInits),
+              ArrayType::Normal, 0));
+      InitializedEntity Element =3DInitializedEntity::InitializeElement(S.=
Context,
+          0, HiddenArray);
+      for (unsigned i =3D 0; i < NumInits; ++i) {
+        Element.setElementIndex(i);
+        ExprResult Init =3D S.Owned(ILE->getInit(i));
+        ExprResult Res =3D S.PerformCopyInitialization(Element,
+                                                     Init.get()->getExprLo=
c(),
+                                                     Init);
+        assert(!Res.isInvalid() && "Result changed since try phase.");
+        Converted[i] =3D Res.take();
+      }
+      InitListExpr *Semantic =3D new (S.Context)
+          InitListExpr(S.Context, ILE->getLBraceLoc(),
+                       Converted.data(), NumInits, ILE->getRBraceLoc());
+      Semantic->setSyntacticForm(ILE);
+      Semantic->setType(Dest);
+      Semantic->setInitializesStdInitializerList();
+      CurInit =3D S.Owned(Semantic);
+      break;
+    }
     }
   }
=20
@@ -4884,6 +5409,11 @@
       << Args[0]->getSourceRange();
     break;
=20
+  case FK_VariableLengthArrayHasInitializer:
+    S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
+      << Args[0]->getSourceRange();
+    break;
+
   case FK_AddressOfOverloadFailed: {
     DeclAccessPair Found;
     S.ResolveAddressOfOverloadedFunction(Args[0],
@@ -4906,14 +5436,16 @@
           << DestType << Args[0]->getType()
           << Args[0]->getSourceRange();
=20
-      FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, Num=
Args);
+      FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
+                                        llvm::makeArrayRef(Args, NumArgs));
       break;
=20
     case OR_No_Viable_Function:
       S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
         << Args[0]->getType() << DestType.getNonReferenceType()
         << Args[0]->getSourceRange();
-      FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArg=
s);
+      FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
+                                        llvm::makeArrayRef(Args, NumArgs));
       break;
=20
     case OR_Deleted: {
@@ -4925,8 +5457,7 @@
         =3D FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), B=
est,
                                                 true);
       if (Ovl =3D=3D OR_Deleted) {
-        S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
-          << 1 << Best->Function->isDeleted();
+        S.NoteDeletedFunction(Best->Function);
       } else {
         llvm_unreachable("Inconsistent overload resolution?");
       }
@@ -4935,11 +5466,20 @@
=20
     case OR_Success:
       llvm_unreachable("Conversion did not fail!");
+    }
+    break;
+
+  case FK_NonConstLValueReferenceBindingToTemporary:
+    if (isa<InitListExpr>(Args[0])) {
+      S.Diag(Kind.getLocation(),
+             diag::err_lvalue_reference_bind_to_initlist)
+      << DestType.getNonReferenceType().isVolatileQualified()
+      << DestType.getNonReferenceType()
+      << Args[0]->getSourceRange();
       break;
     }
-    break;
-
-  case FK_NonConstLValueReferenceBindingToTemporary:
+    // Intentional fallthrough
+
   case FK_NonConstLValueReferenceBindingToUnrelated:
     S.Diag(Kind.getLocation(),
            Failure =3D=3D FK_NonConstLValueReferenceBindingToTemporary
@@ -4977,12 +5517,14 @@
=20
   case FK_ConversionFailed: {
     QualType FromType =3D Args[0]->getType();
-    S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
+    PartialDiagnostic PDiag =3D S.PDiag(diag::err_init_conversion_failed)
       << (int)Entity.getKind()
       << DestType
       << Args[0]->isLValue()
       << FromType
       << Args[0]->getSourceRange();
+    S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
+    S.Diag(Kind.getLocation(), PDiag);
     if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
         Args[0]->getType()->isObjCObjectPointerType())
       S.EmitRelatedResultTypeNote(Args[0]);
@@ -5022,12 +5564,20 @@
       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange=
();
     break;
=20
+  case FK_ListConstructorOverloadFailed:
   case FK_ConstructorOverloadFailed: {
     SourceRange ArgsRange;
     if (NumArgs)
       ArgsRange =3D SourceRange(Args[0]->getLocStart(),
                               Args[NumArgs - 1]->getLocEnd());
=20
+    if (Failure =3D=3D FK_ListConstructorOverloadFailed) {
+      assert(NumArgs =3D=3D 1 && "List construction from other than 1 argu=
ment.");
+      InitListExpr *InitList =3D cast<InitListExpr>(Args[0]);
+      Args =3D InitList->getInits();
+      NumArgs =3D InitList->getNumInits();
+    }
+
     // FIXME: Using "DestType" for the entity we're printing is probably
     // bad.
     switch (FailedOverloadResult) {
@@ -5035,7 +5585,7 @@
         S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
           << DestType << ArgsRange;
         FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
-                                          Args, NumArgs);
+                                          llvm::makeArrayRef(Args, NumArgs=
));
         break;
=20
       case OR_No_Viable_Function:
@@ -5080,30 +5630,41 @@
=20
         S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_ini=
t)
           << DestType << ArgsRange;
-        FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumA=
rgs);
+        FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
+                                          llvm::makeArrayRef(Args, NumArgs=
));
         break;
=20
       case OR_Deleted: {
-        S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
-          << true << DestType << ArgsRange;
         OverloadCandidateSet::iterator Best;
         OverloadingResult Ovl
           =3D FailedCandidateSet.BestViableFunction(S, Kind.getLocation(),=
 Best);
-        if (Ovl =3D=3D OR_Deleted) {
-          S.Diag(Best->Function->getLocation(), diag::note_unavailable_her=
e)
-            << 1 << Best->Function->isDeleted();
-        } else {
+        if (Ovl !=3D OR_Deleted) {
+          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
+            << true << DestType << ArgsRange;
           llvm_unreachable("Inconsistent overload resolution?");
+          break;
         }
+      =20
+        // If this is a defaulted or implicitly-declared function, then
+        // it was implicitly deleted. Make it clear that the deletion was
+        // implicit.
+        if (S.isImplicitlyDeleted(Best->Function))
+          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
+            << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
+            << DestType << ArgsRange;
+        else
+          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
+            << true << DestType << ArgsRange;
+
+        S.NoteDeletedFunction(Best->Function);
         break;
       }
=20
       case OR_Success:
         llvm_unreachable("Conversion did not fail!");
-        break;
     }
-    break;
   }
+  break;
=20
   case FK_DefaultInitOfConst:
     if (Entity.getKind() =3D=3D InitializedEntity::EK_Member &&
@@ -5126,7 +5687,7 @@
     break;
=20
   case FK_Incomplete:
-    S.RequireCompleteType(Kind.getLocation(), DestType,
+    S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
                           diag::err_init_incomplete_type);
     break;
=20
@@ -5135,11 +5696,62 @@
     InitListExpr* InitList =3D cast<InitListExpr>(Args[0]);
     QualType DestType =3D Entity.getType();
     InitListChecker DiagnoseInitList(S, Entity, InitList,
-            DestType, /*VerifyOnly=3D*/false);
+            DestType, /*VerifyOnly=3D*/false,
+            Kind.getKind() !=3D InitializationKind::IK_DirectList ||
+              !S.getLangOpts().CPlusPlus0x);
     assert(DiagnoseInitList.HadError() &&
            "Inconsistent init list check result.");
     break;
   }
+
+  case FK_PlaceholderType: {
+    // FIXME: Already diagnosed!
+    break;
+  }
+
+  case FK_InitListElementCopyFailure: {
+    // Try to perform all copies again.
+    InitListExpr* InitList =3D cast<InitListExpr>(Args[0]);
+    unsigned NumInits =3D InitList->getNumInits();
+    QualType DestType =3D Entity.getType();
+    QualType E;
+    bool Success =3D S.isStdInitializerList(DestType, &E);
+    (void)Success;
+    assert(Success && "Where did the std::initializer_list go?");
+    InitializedEntity HiddenArray =3D InitializedEntity::InitializeTempora=
ry(
+        S.Context.getConstantArrayType(E,
+            llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
+                        NumInits),
+            ArrayType::Normal, 0));
+    InitializedEntity Element =3D InitializedEntity::InitializeElement(S.C=
ontext,
+        0, HiddenArray);
+    // Show at most 3 errors. Otherwise, you'd get a lot of errors for err=
ors
+    // where the init list type is wrong, e.g.
+    //   std::initializer_list<void*> list =3D { 1, 2, 3, 4, 5, 6, 7, 8 };
+    // FIXME: Emit a note if we hit the limit?
+    int ErrorCount =3D 0;
+    for (unsigned i =3D 0; i < NumInits && ErrorCount < 3; ++i) {
+      Element.setElementIndex(i);
+      ExprResult Init =3D S.Owned(InitList->getInit(i));
+      if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), I=
nit)
+           .isInvalid())
+        ++ErrorCount;
+    }
+    break;
+  }
+
+  case FK_ExplicitConstructor: {
+    S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
+      << Args[0]->getSourceRange();
+    OverloadCandidateSet::iterator Best;
+    OverloadingResult Ovl
+      =3D FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Bes=
t);
+    (void)Ovl;
+    assert(Ovl =3D=3D OR_Success && "Inconsistent overload resolution");
+    CXXConstructorDecl *CtorDecl =3D cast<CXXConstructorDecl>(Best->Functi=
on);
+    S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
+    break;
+  }
   }
=20
   PrintInitLocationNote(S, Entity);
@@ -5237,6 +5849,27 @@
=20
     case FK_ListInitializationFailed:
       OS << "list initialization checker failure";
+      break;
+
+    case FK_VariableLengthArrayHasInitializer:
+      OS << "variable length array has an initializer";
+      break;
+
+    case FK_PlaceholderType:
+      OS << "initializer expression isn't contextually valid";
+      break;
+
+    case FK_ListConstructorOverloadFailed:
+      OS << "list constructor overloading failed";
+      break;
+
+    case FK_InitListElementCopyFailure:
+      OS << "copy construction of initializer list element failed";
+      break;
+
+    case FK_ExplicitConstructor:
+      OS << "list copy initialization chose explicit constructor";
+      break;
     }
     OS << '\n';
     return;
@@ -5291,9 +5924,11 @@
=20
     case SK_QualificationConversionRValue:
       OS << "qualification conversion (rvalue)";
+      break;
=20
     case SK_QualificationConversionXValue:
       OS << "qualification conversion (xvalue)";
+      break;
=20
     case SK_QualificationConversionLValue:
       OS << "qualification conversion (lvalue)";
@@ -5313,6 +5948,14 @@
       OS << "list initialization via constructor";
       break;
=20
+    case SK_UnwrapInitList:
+      OS << "unwrap reference initializer list";
+      break;
+
+    case SK_RewrapInitList:
+      OS << "rewrap reference initializer list";
+      break;
+
     case SK_ConstructorInitialization:
       OS << "constructor initialization";
       break;
@@ -5337,6 +5980,10 @@
       OS << "array initialization";
       break;
=20
+    case SK_ParenthesizedArrayInit:
+      OS << "parenthesized array initialization";
+      break;
+
     case SK_PassByIndirectCopyRestore:
       OS << "pass by indirect copy and restore";
       break;
@@ -5348,6 +5995,10 @@
     case SK_ProduceObjCObject:
       OS << "Objective-C object retension";
       break;
+
+    case SK_StdInitializerList:
+      OS << "std::initializer_list from initializer list";
+      break;
     }
   }
 }
@@ -5356,27 +6007,93 @@
   dump(llvm::errs());
 }
=20
-static void DiagnoseNarrowingInInitList(
-    Sema& S, QualType EntityType, const Expr *InitE,
-    bool Constant, const APValue &ConstantValue) {
-  if (Constant) {
-    S.Diag(InitE->getLocStart(),
-           S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft=
Ext
-           ? diag::err_init_list_constant_narrowing
-           : diag::warn_init_list_constant_narrowing)
-      << InitE->getSourceRange()
-      << ConstantValue
+static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &S=
eq,
+                                        QualType EntityType,
+                                        const Expr *PreInit,
+                                        const Expr *PostInit) {
+  if (Seq.step_begin() =3D=3D Seq.step_end() || PreInit->isValueDependent(=
))
+    return;
+
+  // A narrowing conversion can only appear as the final implicit conversi=
on in
+  // an initialization sequence.
+  const InitializationSequence::Step &LastStep =3D Seq.step_end()[-1];
+  if (LastStep.Kind !=3D InitializationSequence::SK_ConversionSequence)
+    return;
+
+  const ImplicitConversionSequence &ICS =3D *LastStep.ICS;
+  const StandardConversionSequence *SCS =3D 0;
+  switch (ICS.getKind()) {
+  case ImplicitConversionSequence::StandardConversion:
+    SCS =3D &ICS.Standard;
+    break;
+  case ImplicitConversionSequence::UserDefinedConversion:
+    SCS =3D &ICS.UserDefined.After;
+    break;
+  case ImplicitConversionSequence::AmbiguousConversion:
+  case ImplicitConversionSequence::EllipsisConversion:
+  case ImplicitConversionSequence::BadConversion:
+    return;
+  }
+
+  // Determine the type prior to the narrowing conversion. If a conversion
+  // operator was used, this may be different from both the type of the en=
tity
+  // and of the pre-initialization expression.
+  QualType PreNarrowingType =3D PreInit->getType();
+  if (Seq.step_begin() + 1 !=3D Seq.step_end())
+    PreNarrowingType =3D Seq.step_end()[-2].Type;
+
+  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
+  APValue ConstantValue;
+  QualType ConstantType;
+  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
+                                ConstantType)) {
+  case NK_Not_Narrowing:
+    // No narrowing occurred.
+    return;
+
+  case NK_Type_Narrowing:
+    // This was a floating-to-integer conversion, which is always consider=
ed a
+    // narrowing conversion even if the value is a constant and can be
+    // represented exactly as an integer.
+    S.Diag(PostInit->getLocStart(),
+           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?=20
+             diag::warn_init_list_type_narrowing
+           : S.isSFINAEContext()?
+             diag::err_init_list_type_narrowing_sfinae
+           : diag::err_init_list_type_narrowing)
+      << PostInit->getSourceRange()
+      << PreNarrowingType.getLocalUnqualifiedType()
       << EntityType.getLocalUnqualifiedType();
-  } else
-    S.Diag(InitE->getLocStart(),
-           S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft=
Ext
-           ? diag::err_init_list_variable_narrowing
-           : diag::warn_init_list_variable_narrowing)
-      << InitE->getSourceRange()
-      << InitE->getType().getLocalUnqualifiedType()
+    break;
+
+  case NK_Constant_Narrowing:
+    // A constant value was narrowed.
+    S.Diag(PostInit->getLocStart(),
+           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?=20
+             diag::warn_init_list_constant_narrowing
+           : S.isSFINAEContext()?
+             diag::err_init_list_constant_narrowing_sfinae
+           : diag::err_init_list_constant_narrowing)
+      << PostInit->getSourceRange()
+      << ConstantValue.getAsString(S.getASTContext(), ConstantType)
       << EntityType.getLocalUnqualifiedType();
-
-  llvm::SmallString<128> StaticCast;
+    break;
+
+  case NK_Variable_Narrowing:
+    // A variable's value may have been narrowed.
+    S.Diag(PostInit->getLocStart(),
+           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x?=20
+             diag::warn_init_list_variable_narrowing
+           : S.isSFINAEContext()?
+             diag::err_init_list_variable_narrowing_sfinae
+           : diag::err_init_list_variable_narrowing)
+      << PostInit->getSourceRange()
+      << PreNarrowingType.getLocalUnqualifiedType()
+      << EntityType.getLocalUnqualifiedType();
+    break;
+  }
+
+  SmallString<128> StaticCast;
   llvm::raw_svector_ostream OS(StaticCast);
   OS << "static_cast<";
   if (const TypedefType *TT =3D EntityType->getAs<TypedefType>()) {
@@ -5387,18 +6104,18 @@
     // getQualifiedNameAsString() includes non-machine-parsable components.
     OS << *TT->getDecl();
   } else if (const BuiltinType *BT =3D EntityType->getAs<BuiltinType>())
-    OS << BT->getName(S.getLangOptions());
+    OS << BT->getName(S.getLangOpts());
   else {
     // Oops, we didn't find the actual type of the variable.  Don't emit a=
 fixit
     // with a broken cast.
     return;
   }
   OS << ">(";
-  S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
-    << InitE->getSourceRange()
-    << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
+  S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
+    << PostInit->getSourceRange()
+    << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
     << FixItHint::CreateInsertion(
-      S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
+      S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -5423,7 +6140,8 @@
 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
                                 SourceLocation EqualLoc,
                                 ExprResult Init,
-                                bool TopLevelOfInitList) {
+                                bool TopLevelOfInitList,
+                                bool AllowExplicit) {
   if (Init.isInvalid())
     return ExprError();
=20
@@ -5434,16 +6152,16 @@
     EqualLoc =3D InitE->getLocStart();
=20
   InitializationKind Kind =3D InitializationKind::CreateCopy(InitE->getLoc=
Start(),
-                                                           EqualLoc);
+                                                           EqualLoc,
+                                                           AllowExplicit);
   InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
   Init.release();
=20
-  bool Constant =3D false;
-  APValue Result;
-  if (TopLevelOfInitList &&
-      Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
-    DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
-                                Constant, Result);
-  }
-  return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
+  ExprResult Result =3D Seq.Perform(*this, Entity, Kind, MultiExprArg(&Ini=
tE, 1));
+
+  if (!Result.isInvalid() && TopLevelOfInitList)
+    DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
+                                InitE, Result.get());
+
+  return Result;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaLookup.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaLookup.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaLookup.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -25,26 +25,28 @@
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclLookups.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/LangOptions.h"
-#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/TinyPtrVector.h"
+#include "llvm/ADT/edit_distance.h"
 #include "llvm/Support/ErrorHandling.h"
+#include <algorithm>
+#include <iterator>
 #include <limits>
 #include <list>
+#include <map>
 #include <set>
+#include <utility>
 #include <vector>
-#include <iterator>
-#include <utility>
-#include <algorithm>
-#include <map>
=20
 using namespace clang;
 using namespace sema;
@@ -105,13 +107,15 @@
       assert(InnermostFileDC && InnermostFileDC->isFileContext());
=20
       for (; S; S =3D S->getParent()) {
-        if (DeclContext *Ctx =3D static_cast<DeclContext*>(S->getEntity())=
) {
-          DeclContext *EffectiveDC =3D (Ctx->isFileContext() ? Ctx : Inner=
mostFileDC);
-          visit(Ctx, EffectiveDC);
-        } else {
+        // C++ [namespace.udir]p1:
+        //   A using-directive shall not appear in class scope, but may
+        //   appear in namespace scope or in block scope.
+        DeclContext *Ctx =3D static_cast<DeclContext*>(S->getEntity());
+        if (Ctx && Ctx->isFileContext()) {
+          visit(Ctx, Ctx);
+        } else if (!Ctx || Ctx->isFunctionOrMethod()) {
           Scope::udir_iterator I =3D S->using_directives_begin(),
                              End =3D S->using_directives_end();
-
           for (; I !=3D End; ++I)
             visit(*I, InnermostFileDC);
         }
@@ -280,7 +284,7 @@
 }
=20
 void LookupResult::configure() {
-  IDNS =3D getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
+  IDNS =3D getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
                  isForRedeclaration());
=20
   // If we're looking for one of the allocation or deallocation
@@ -301,7 +305,9 @@
   }
 }
=20
-void LookupResult::sanity() const {
+void LookupResult::sanityImpl() const {
+  // Note that this function is never called by NDEBUG builds. See
+  // LookupResult::sanity().
   assert(ResultKind !=3D NotFound || Decls.size() =3D=3D 0);
   assert(ResultKind !=3D Found || Decls.size() =3D=3D 1);
   assert(ResultKind !=3D FoundOverloaded || Decls.size() > 1 ||
@@ -321,6 +327,12 @@
   delete Paths;
 }
=20
+static NamedDecl *getVisibleDecl(NamedDecl *D);
+
+NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
+  return getVisibleDecl(D);
+}
+
 /// Resolves the result kind of this lookup.
 void LookupResult::resolveKind() {
   unsigned N =3D Decls.size();
@@ -488,7 +500,7 @@
       if (unsigned BuiltinID =3D II->getBuiltinID()) {
         // In C++, we don't have any predefined library functions like
         // 'malloc'. Instead, we'll just error.
-        if (S.getLangOptions().CPlusPlus &&
+        if (S.getLangOpts().CPlusPlus &&
             S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
           return false;
=20
@@ -518,10 +530,6 @@
 /// the class at this point.
 static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
                                             const CXXRecordDecl *Class) {
-  // Don't do it if the class is invalid.
-  if (Class->isInvalidDecl())
-    return false;
-
   // We need to have a definition for the class.
   if (!Class->getDefinition() || Class->isDependentContext())
     return false;
@@ -550,7 +558,7 @@
   if (!Class->hasDeclaredCopyAssignment())
     DeclareImplicitCopyAssignment(Class);
=20
-  if (getLangOptions().CPlusPlus0x) {
+  if (getLangOpts().CPlusPlus0x) {
     // If the move constructor has not yet been declared, do so now.
     if (Class->needsImplicitMoveConstructor())
       DeclareImplicitMoveConstructor(Class); // might not actually do it
@@ -601,7 +609,7 @@
           S.DeclareImplicitDefaultConstructor(Class);
         if (!Record->hasDeclaredCopyConstructor())
           S.DeclareImplicitCopyConstructor(Class);
-        if (S.getLangOptions().CPlusPlus0x &&
+        if (S.getLangOpts().CPlusPlus0x &&
             Record->needsImplicitMoveConstructor())
           S.DeclareImplicitMoveConstructor(Class);
       }
@@ -624,7 +632,7 @@
         CXXRecordDecl *Class =3D const_cast<CXXRecordDecl *>(Record);
         if (!Record->hasDeclaredCopyAssignment())
           S.DeclareImplicitCopyAssignment(Class);
-        if (S.getLangOptions().CPlusPlus0x &&
+        if (S.getLangOpts().CPlusPlus0x &&
             Record->needsImplicitMoveAssignment())
           S.DeclareImplicitMoveAssignment(Class);
       }
@@ -642,14 +650,14 @@
   bool Found =3D false;
=20
   // Lazily declare C++ special member functions.
-  if (S.getLangOptions().CPlusPlus)
+  if (S.getLangOpts().CPlusPlus)
     DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
=20
   // Perform lookup into this declaration context.
   DeclContext::lookup_const_iterator I, E;
   for (llvm::tie(I, E) =3D DC->lookup(R.getLookupName()); I !=3D E; ++I) {
     NamedDecl *D =3D *I;
-    if (R.isAcceptableDecl(D)) {
+    if ((D =3D R.getAcceptableDecl(D))) {
       R.addDecl(D);
       Found =3D true;
     }
@@ -830,7 +838,7 @@
 }
=20
 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
-  assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
+  assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
=20
   DeclarationName Name =3D R.getLookupName();
=20
@@ -875,9 +883,9 @@
     // Check whether the IdResolver has anything in this scope.
     bool Found =3D false;
     for (; I !=3D IEnd && S->isDeclScope(*I); ++I) {
-      if (R.isAcceptableDecl(*I)) {
+      if (NamedDecl *ND =3D R.getAcceptableDecl(*I)) {
         Found =3D true;
-        R.addDecl(*I);
+        R.addDecl(ND);
       }
     }
     if (Found) {
@@ -926,8 +934,8 @@
                 if (ObjCIvarDecl *Ivar =3D Class->lookupInstanceVariable(
                                                  Name.getAsIdentifierInfo(=
),
                                                              ClassDeclared=
)) {
-                  if (R.isAcceptableDecl(Ivar)) {
-                    R.addDecl(Ivar);
+                  if (NamedDecl *ND =3D R.getAcceptableDecl(Ivar)) {
+                    R.addDecl(ND);
                     R.resolveKind();
                     return true;
                   }
@@ -977,13 +985,13 @@
     // Check whether the IdResolver has anything in this scope.
     bool Found =3D false;
     for (; I !=3D IEnd && S->isDeclScope(*I); ++I) {
-      if (R.isAcceptableDecl(*I)) {
+      if (NamedDecl *ND =3D R.getAcceptableDecl(*I)) {
         // We found something.  Look for anything else in our scope
         // with this same name and in an acceptable identifier
         // namespace, so that we can construct an overload set if we
         // need to.
         Found =3D true;
-        R.addDecl(*I);
+        R.addDecl(ND);
       }
     }
=20
@@ -1047,6 +1055,29 @@
   return !R.empty();
 }
=20
+/// \brief Retrieve the visible declaration corresponding to D, if any.
+///
+/// This routine determines whether the declaration D is visible in the cu=
rrent
+/// module, with the current imports. If not, it checks whether any
+/// redeclaration of D is visible, and if so, returns that declaration.
+///=20
+/// \returns D, or a visible previous declaration of D, whichever is more =
recent
+/// and visible. If no declaration of D is visible, returns null.
+static NamedDecl *getVisibleDecl(NamedDecl *D) {
+  if (LookupResult::isVisible(D))
+    return D;
+ =20
+  for (Decl::redecl_iterator RD =3D D->redecls_begin(), RDEnd =3D D->redec=
ls_end();
+       RD !=3D RDEnd; ++RD) {
+    if (NamedDecl *ND =3D dyn_cast<NamedDecl>(*RD)) {
+      if (LookupResult::isVisible(ND))
+        return ND;
+    }
+  }
+ =20
+  return 0;
+}
+
 /// @brief Perform unqualified name lookup starting from a given
 /// scope.
 ///
@@ -1084,7 +1115,7 @@
=20
   LookupNameKind NameKind =3D R.getLookupKind();
=20
-  if (!getLangOptions().CPlusPlus) {
+  if (!getLangOpts().CPlusPlus) {
     // Unqualified name lookup in C/Objective-C is purely lexical, so
     // search in the declarations attached to the name.
     if (NameKind =3D=3D Sema::LookupRedeclarationWithLinkage) {
@@ -1123,29 +1154,58 @@
                  !isa<ImplicitParamDecl>(*I))
           continue;
        =20
-        R.addDecl(*I);
-
-        if ((*I)->getAttr<OverloadableAttr>()) {
-          // If this declaration has the "overloadable" attribute, we
-          // might have a set of overloaded functions.
-
-          // Figure out what scope the identifier is in.
-          while (!(S->getFlags() & Scope::DeclScope) ||
-                 !S->isDeclScope(*I))
+        // If this declaration is module-private and it came from an AST
+        // file, we can't see it.
+        NamedDecl *D =3D R.isHiddenDeclarationVisible()? *I : getVisibleDe=
cl(*I);
+        if (!D)
+          continue;
+               =20
+        R.addDecl(D);
+
+        // Check whether there are any other declarations with the same na=
me
+        // and in the same scope.
+        if (I !=3D IEnd) {
+          // Find the scope in which this declaration was declared (if it
+          // actually exists in a Scope).
+          while (S && !S->isDeclScope(D))
             S =3D S->getParent();
-
-          // Find the last declaration in this scope (with the same
-          // name, naturally).
+         =20
+          // If the scope containing the declaration is the translation un=
it,
+          // then we'll need to perform our checks based on the matching
+          // DeclContexts rather than matching scopes.
+          if (S && isNamespaceOrTranslationUnitScope(S))
+            S =3D 0;
+
+          // Compute the DeclContext, if we need it.
+          DeclContext *DC =3D 0;
+          if (!S)
+            DC =3D (*I)->getDeclContext()->getRedeclContext();
+           =20
           IdentifierResolver::iterator LastI =3D I;
           for (++LastI; LastI !=3D IEnd; ++LastI) {
-            if (!S->isDeclScope(*LastI))
-              break;
-            R.addDecl(*LastI);
+            if (S) {
+              // Match based on scope.
+              if (!S->isDeclScope(*LastI))
+                break;
+            } else {
+              // Match based on DeclContext.
+              DeclContext *LastDC=20
+                =3D (*LastI)->getDeclContext()->getRedeclContext();
+              if (!LastDC->Equals(DC))
+                break;
+            }
+           =20
+            // If the declaration isn't in the right namespace, skip it.
+            if (!(*LastI)->isInIdentifierNamespace(IDNS))
+              continue;
+                       =20
+            D =3D R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(=
*LastI);
+            if (D)
+              R.addDecl(D);
           }
+
+          R.resolveKind();
         }
-
-        R.resolveKind();
-
         return true;
       }
   } else {
@@ -1203,7 +1263,7 @@
   if (I =3D=3D E) return false;
=20
   // We have at least added all these contexts to the queue.
-  llvm::DenseSet<DeclContext*> Visited;
+  llvm::SmallPtrSet<DeclContext*, 8> Visited;
   Visited.insert(StartDC);
=20
   // We have not yet looked into these namespaces, much less added
@@ -1214,7 +1274,7 @@
   // with its using-children.
   for (; I !=3D E; ++I) {
     NamespaceDecl *ND =3D (*I)->getNominatedNamespace()->getOriginalNamesp=
ace();
-    if (Visited.insert(ND).second)
+    if (Visited.insert(ND))
       Queue.push_back(ND);
   }
=20
@@ -1263,7 +1323,7 @@
=20
     for (llvm::tie(I,E) =3D ND->getUsingDirectives(); I !=3D E; ++I) {
       NamespaceDecl *Nom =3D (*I)->getNominatedNamespace();
-      if (Visited.insert(Nom).second)
+      if (Visited.insert(Nom))
         Queue.push_back(Nom);
     }
   }
@@ -1354,8 +1414,7 @@
   assert((!isa<TagDecl>(LookupCtx) ||
           LookupCtx->isDependentContext() ||
           cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
-          Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType=
>()
-            ->isBeingDefined()) &&
+          cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
          "Declaration context must already be complete!");
=20
   // Perform qualified name lookup into the LookupCtx.
@@ -1561,13 +1620,14 @@
         return false;
=20
       R.setContextRange(SS->getRange());
-
       return LookupQualifiedName(R, DC);
     }
=20
     // We could not resolve the scope specified to a specific declaration
     // context, which means that SS refers to an unknown specialization.
     // Name lookup can't find anything in this case.
+    R.setNotFoundInCurrentInstantiation();
+    R.setContextRange(SS->getRange());
     return false;
   }
=20
@@ -1673,7 +1733,6 @@
   }
=20
   llvm_unreachable("unknown ambiguity kind");
-  return true;
 }
=20
 namespace {
@@ -2022,7 +2081,7 @@
 /// namespaces searched by argument-dependent lookup
 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
 void
-Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
+Sema::FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args,
                                  AssociatedNamespaceSet &AssociatedNamespa=
ces,
                                  AssociatedClassSet &AssociatedClasses) {
   AssociatedNamespaces.clear();
@@ -2037,7 +2096,7 @@
   //   classes is determined entirely by the types of the function
   //   arguments (and the namespace of any template template
   //   argument).
-  for (unsigned ArgIdx =3D 0; ArgIdx !=3D NumArgs; ++ArgIdx) {
+  for (unsigned ArgIdx =3D 0; ArgIdx !=3D Args.size(); ++ArgIdx) {
     Expr *Arg =3D Args[ArgIdx];
=20
     if (Arg->getType() !=3D Context.OverloadTy) {
@@ -2124,9 +2183,10 @@
=20
 /// \brief Find the protocol with the given name, if any.
 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
-                                       SourceLocation IdLoc) {
+                                       SourceLocation IdLoc,
+                                       RedeclarationKind Redecl) {
   Decl *D =3D LookupSingleName(TUScope, II, IdLoc,
-                             LookupObjCProtocolName);
+                             LookupObjCProtocolName, Redecl);
   return cast_or_null<ObjCProtocolDecl>(D);
 }
=20
@@ -2215,8 +2275,9 @@
     CXXDestructorDecl *DD =3D RD->getDestructor();
     assert(DD && "record without a destructor");
     Result->setMethod(DD);
-    Result->setSuccess(DD->isDeleted());
-    Result->setConstParamMatch(false);
+    Result->setKind(DD->isDeleted() ?
+                    SpecialMemberOverloadResult::NoMemberOrDeleted :
+                    SpecialMemberOverloadResult::SuccessNonConst);
     return Result;
   }
=20
@@ -2237,13 +2298,13 @@
       Name =3D Context.DeclarationNames.getCXXConstructorName(CanTy);
       if (!RD->hasDeclaredCopyConstructor())
         DeclareImplicitCopyConstructor(RD);
-      if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveConstructor=
())
+      if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
         DeclareImplicitMoveConstructor(RD);
     } else {
       Name =3D Context.DeclarationNames.getCXXOperatorName(OO_Equal);
       if (!RD->hasDeclaredCopyAssignment())
         DeclareImplicitCopyAssignment(RD);
-      if (getLangOptions().CPlusPlus0x && RD->needsImplicitMoveAssignment(=
))
+      if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
         DeclareImplicitMoveAssignment(RD);
     }
=20
@@ -2286,7 +2347,8 @@
   // will always be a (possibly implicit) declaration to shadow any others.
   OverloadCandidateSet OCS((SourceLocation()));
   DeclContext::lookup_iterator I, E;
-  Result->setConstParamMatch(false);
+  SpecialMemberOverloadResult::Kind SuccessKind =3D
+      SpecialMemberOverloadResult::SuccessNonConst;
=20
   llvm::tie(I, E) =3D RD->lookup(Name);
   assert((I !=3D E) &&
@@ -2311,10 +2373,11 @@
     if (CXXMethodDecl *M =3D dyn_cast<CXXMethodDecl>(Cand)) {
       if (SM =3D=3D CXXCopyAssignment || SM =3D=3D CXXMoveAssignment)
         AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, This=
Ty,
-                           Classification, &Arg, NumArgs, OCS, true);
+                           Classification, llvm::makeArrayRef(&Arg, NumArg=
s),
+                           OCS, true);
       else
-        AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
-                             NumArgs, OCS, true);
+        AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
+                             llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
=20
       // Here we're looking for a const parameter to speed up creation of
       // implicit copy methods.
@@ -2324,17 +2387,19 @@
         QualType ArgType =3D M->getType()->getAs<FunctionProtoType>()->get=
ArgType(0);
         if (!ArgType->isReferenceType() ||
             ArgType->getPointeeType().isConstQualified())
-          Result->setConstParamMatch(true);
+          SuccessKind =3D SpecialMemberOverloadResult::SuccessConst;
       }
     } else if (FunctionTemplateDecl *Tmpl =3D
                  dyn_cast<FunctionTemplateDecl>(Cand)) {
       if (SM =3D=3D CXXCopyAssignment || SM =3D=3D CXXMoveAssignment)
         AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_pub=
lic),
-                                   RD, 0, ThisTy, Classification, &Arg, Nu=
mArgs,
+                                   RD, 0, ThisTy, Classification,
+                                   llvm::makeArrayRef(&Arg, NumArgs),
                                    OCS, true);
       else
         AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_p=
ublic),
-                                     0, &Arg, NumArgs, OCS, true);
+                                     0, llvm::makeArrayRef(&Arg, NumArgs),
+                                     OCS, true);
     } else {
       assert(isa<UsingDecl>(Cand) && "illegal Kind of operator =3D Decl");
     }
@@ -2344,18 +2409,22 @@
   switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
     case OR_Success:
       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
-      Result->setSuccess(true);
+      Result->setKind(SuccessKind);
       break;
=20
     case OR_Deleted:
       Result->setMethod(cast<CXXMethodDecl>(Best->Function));
-      Result->setSuccess(false);
+      Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
       break;
=20
     case OR_Ambiguous:
+      Result->setMethod(0);
+      Result->setKind(SpecialMemberOverloadResult::Ambiguous);
+      break;
+
     case OR_No_Viable_Function:
       Result->setMethod(0);
-      Result->setSuccess(false);
+      Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
       break;
   }
=20
@@ -2404,7 +2473,7 @@
       DeclareImplicitDefaultConstructor(Class);
     if (!Class->hasDeclaredCopyConstructor())
       DeclareImplicitCopyConstructor(Class);
-    if (getLangOptions().CPlusPlus0x && Class->needsImplicitMoveConstructo=
r())
+    if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
       DeclareImplicitMoveConstructor(Class);
   }
=20
@@ -2460,6 +2529,105 @@
                                                      false, false)->getMet=
hod());
 }
=20
+/// LookupLiteralOperator - Determine which literal operator should be use=
d for
+/// a user-defined literal, per C++11 [lex.ext].
+///
+/// Normal overload resolution is not used to select which literal operato=
r to
+/// call for a user-defined literal. Look up the provided literal operator=
 name,
+/// and filter the results to the appropriate set for the given argument t=
ypes.
+Sema::LiteralOperatorLookupResult
+Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
+                            ArrayRef<QualType> ArgTys,
+                            bool AllowRawAndTemplate) {
+  LookupName(R, S);
+  assert(R.getResultKind() !=3D LookupResult::Ambiguous &&
+         "literal operator lookup can't be ambiguous");
+
+  // Filter the lookup results appropriately.
+  LookupResult::Filter F =3D R.makeFilter();
+
+  bool FoundTemplate =3D false;
+  bool FoundRaw =3D false;
+  bool FoundExactMatch =3D false;
+
+  while (F.hasNext()) {
+    Decl *D =3D F.next();
+    if (UsingShadowDecl *USD =3D dyn_cast<UsingShadowDecl>(D))
+      D =3D USD->getTargetDecl();
+
+    bool IsTemplate =3D isa<FunctionTemplateDecl>(D);
+    bool IsRaw =3D false;
+    bool IsExactMatch =3D false;
+
+    if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
+      if (FD->getNumParams() =3D=3D 1 &&
+          FD->getParamDecl(0)->getType()->getAs<PointerType>())
+        IsRaw =3D true;
+      else {
+        IsExactMatch =3D true;
+        for (unsigned ArgIdx =3D 0; ArgIdx !=3D ArgTys.size(); ++ArgIdx) {
+          QualType ParamTy =3D FD->getParamDecl(ArgIdx)->getType();
+          if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
+            IsExactMatch =3D false;
+            break;
+          }
+        }
+      }
+    }
+
+    if (IsExactMatch) {
+      FoundExactMatch =3D true;
+      AllowRawAndTemplate =3D false;
+      if (FoundRaw || FoundTemplate) {
+        // Go through again and remove the raw and template decls we've
+        // already found.
+        F.restart();
+        FoundRaw =3D FoundTemplate =3D false;
+      }
+    } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
+      FoundTemplate |=3D IsTemplate;
+      FoundRaw |=3D IsRaw;
+    } else {
+      F.erase();
+    }
+  }
+
+  F.done();
+
+  // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matchi=
ng
+  // parameter type, that is used in preference to a raw literal operator
+  // or literal operator template.
+  if (FoundExactMatch)
+    return LOLR_Cooked;
+
+  // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a li=
teral
+  // operator template, but not both.
+  if (FoundRaw && FoundTemplate) {
+    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(=
);
+    for (LookupResult::iterator I =3D R.begin(), E =3D R.end(); I !=3D E; =
++I) {
+      Decl *D =3D *I;
+      if (UsingShadowDecl *USD =3D dyn_cast<UsingShadowDecl>(D))
+        D =3D USD->getTargetDecl();
+      if (FunctionTemplateDecl *FunTmpl =3D dyn_cast<FunctionTemplateDecl>=
(D))
+        D =3D FunTmpl->getTemplatedDecl();
+      NoteOverloadCandidate(cast<FunctionDecl>(D));
+    }
+    return LOLR_Error;
+  }
+
+  if (FoundRaw)
+    return LOLR_Raw;
+
+  if (FoundTemplate)
+    return LOLR_Template;
+
+  // Didn't find anything we could use.
+  Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
+    << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
+    << (ArgTys.size() =3D=3D 2 ? ArgTys[1] : QualType()) << AllowRawAndTem=
plate;
+  return LOLR_Error;
+}
+
 void ADLResult::insert(NamedDecl *New) {
   NamedDecl *&Old =3D Decls[cast<NamedDecl>(New->getCanonicalDecl())];
=20
@@ -2482,7 +2650,7 @@
=20
   FunctionDecl *Cursor =3D NewFD;
   while (true) {
-    Cursor =3D Cursor->getPreviousDeclaration();
+    Cursor =3D Cursor->getPreviousDecl();
=20
     // If we got to the end without finding OldFD, OldFD is the newer
     // declaration;  leave things as they are.
@@ -2498,14 +2666,15 @@
 }
=20
 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
-                                   Expr **Args, unsigned NumArgs,
+                                   SourceLocation Loc,
+                                   llvm::ArrayRef<Expr *> Args,
                                    ADLResult &Result,
                                    bool StdNamespaceIsAssociated) {
   // Find all of the associated namespaces and classes based on the
   // arguments we have.
   AssociatedNamespaceSet AssociatedNamespaces;
   AssociatedClassSet AssociatedClasses;
-  FindAssociatedClassesAndNamespaces(Args, NumArgs,
+  FindAssociatedClassesAndNamespaces(Args,
                                      AssociatedNamespaces,
                                      AssociatedClasses);
   if (StdNamespaceIsAssociated && StdNamespace)
@@ -2514,10 +2683,17 @@
   QualType T1, T2;
   if (Operator) {
     T1 =3D Args[0]->getType();
-    if (NumArgs >=3D 2)
+    if (Args.size() >=3D 2)
       T2 =3D Args[1]->getType();
   }
=20
+  // Try to complete all associated classes, in case they contain a
+  // declaration of a friend function.
+  for (AssociatedClassSet::iterator C =3D AssociatedClasses.begin(),
+                                    CEnd =3D AssociatedClasses.end();
+       C !=3D CEnd; ++C)
+    RequireCompleteType(Loc, Context.getRecordType(*C), 0);
+
   // C++ [basic.lookup.argdep]p3:
   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
   //   and let Y be the lookup set produced by argument dependent
@@ -2700,42 +2876,15 @@
     Result.getSema().ForceDeclarationOfImplicitMembers(Class);
=20
   // Enumerate all of the results in this context.
-  for (DeclContext *CurCtx =3D Ctx->getPrimaryContext(); CurCtx;
-       CurCtx =3D CurCtx->getNextContext()) {
-    for (DeclContext::decl_iterator D =3D CurCtx->decls_begin(),
-                                 DEnd =3D CurCtx->decls_end();
-         D !=3D DEnd; ++D) {
-      if (NamedDecl *ND =3D dyn_cast<NamedDecl>(*D)) {
-        if (Result.isAcceptableDecl(ND)) {
+  for (DeclContext::all_lookups_iterator L =3D Ctx->lookups_begin(),
+                                      LEnd =3D Ctx->lookups_end();
+       L !=3D LEnd; ++L) {
+    for (DeclContext::lookup_result R =3D *L; R.first !=3D R.second; ++R.f=
irst) {
+      if (NamedDecl *ND =3D dyn_cast<NamedDecl>(*R.first)) {
+        if ((ND =3D Result.getAcceptableDecl(ND))) {
           Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass=
);
           Visited.add(ND);
         }
-      } else if (ObjCForwardProtocolDecl *ForwardProto
-                                      =3D dyn_cast<ObjCForwardProtocolDecl=
>(*D)) {
-        for (ObjCForwardProtocolDecl::protocol_iterator
-                  P =3D ForwardProto->protocol_begin(),
-               PEnd =3D ForwardProto->protocol_end();
-             P !=3D PEnd;
-             ++P) {
-          if (Result.isAcceptableDecl(*P)) {
-            Consumer.FoundDecl(*P, Visited.checkHidden(*P), Ctx, InBaseCla=
ss);
-            Visited.add(*P);
-          }
-        }
-      } else if (ObjCClassDecl *Class =3D dyn_cast<ObjCClassDecl>(*D)) {
-          ObjCInterfaceDecl *IFace =3D Class->getForwardInterfaceDecl();
-          if (Result.isAcceptableDecl(IFace)) {
-            Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), Ctx,
-                               InBaseClass);
-            Visited.add(IFace);
-          }
-      }
-     =20
-      // Visit transparent contexts and inline namespaces inside this cont=
ext.
-      if (DeclContext *InnerCtx =3D dyn_cast<DeclContext>(*D)) {
-        if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespac=
e())
-          LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBase=
Class,
-                             Consumer, Visited);
       }
     }
   }
@@ -2826,7 +2975,7 @@
     if (IFace->getImplementation()) {
       ShadowContextRAII Shadow(Visited);
       LookupVisibleDecls(IFace->getImplementation(), Result,
-                         QualifiedNameLookup, true, Consumer, Visited);
+                         QualifiedNameLookup, InBaseClass, Consumer, Visit=
ed);
     }
   } else if (ObjCProtocolDecl *Protocol =3D dyn_cast<ObjCProtocolDecl>(Ctx=
)) {
     for (ObjCProtocolDecl::protocol_iterator I =3D Protocol->protocol_begi=
n(),
@@ -2867,7 +3016,7 @@
     for (Scope::decl_iterator D =3D S->decl_begin(), DEnd =3D S->decl_end(=
);
          D !=3D DEnd; ++D) {
       if (NamedDecl *ND =3D dyn_cast<NamedDecl>(*D))
-        if (Result.isAcceptableDecl(ND)) {
+        if ((ND =3D Result.getAcceptableDecl(ND))) {
           Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
           Visited.add(ND);
         }
@@ -2946,7 +3095,7 @@
   // unqualified name lookup.
   Scope *Initial =3D S;
   UnqualUsingDirectiveSet UDirs;
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // Find the first namespace or translation-unit scope.
     while (S && !isNamespaceOrTranslationUnitScope(S))
       S =3D S->getParent();
@@ -3031,15 +3180,11 @@
   /// whether there is a keyword with this name.
   TypoEditDistanceMap BestResults;
=20
-  /// \brief The worst of the best N edit distances found so far.
-  unsigned MaxEditDistance;
-
   Sema &SemaRef;
=20
 public:
   explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
     : Typo(Typo->getName()),
-      MaxEditDistance((std::numeric_limits<unsigned>::max)()),
       SemaRef(SemaRef) { }
=20
   ~TypoCorrectionConsumer() {
@@ -3070,12 +3215,12 @@
     return (*BestResults.begin()->second)[Name];
   }
=20
-  unsigned getMaxEditDistance() const {
-    return MaxEditDistance;
-  }
-
-  unsigned getBestEditDistance() {
-    return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->=
first;
+  unsigned getBestEditDistance(bool Normalized) {
+    if (BestResults.empty())
+      return (std::numeric_limits<unsigned>::max)();
+
+    unsigned BestED =3D BestResults.begin()->first;
+    return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : Be=
stED;
   }
 };
=20
@@ -3101,40 +3246,22 @@
   // Use a simple length-based heuristic to determine the minimum possible
   // edit distance. If the minimum isn't good enough, bail out early.
   unsigned MinED =3D abs((int)Name.size() - (int)Typo.size());
-  if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
+  if (MinED && Typo.size() / MinED < 3)
     return;
=20
   // Compute an upper bound on the allowable edit distance, so that the
   // edit-distance algorithm can short-circuit.
-  unsigned UpperBound =3D
-    std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
+  unsigned UpperBound =3D (Typo.size() + 2) / 3;
=20
   // Compute the edit distance between the typo and the name of this
-  // entity. If this edit distance is not worse than the best edit
-  // distance we've seen so far, add it to the list of results.
-  unsigned ED =3D Typo.edit_distance(Name, true, UpperBound);
-
-  if (ED > MaxEditDistance) {
-    // This result is worse than the best results we've seen so far;
-    // ignore it.
-    return;
-  }
-
-  addName(Name, NULL, ED);
+  // entity, and add the identifier to the list of results.
+  addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
 }
=20
 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
-  // Compute the edit distance between the typo and this keyword.
-  // If this edit distance is not worse than the best edit
-  // distance we've seen so far, add it to the list of results.
-  unsigned ED =3D Typo.edit_distance(Keyword);
-  if (ED > MaxEditDistance) {
-    // This result is worse than the best results we've seen so far;
-    // ignore it.
-    return;
-  }
-
-  addName(Keyword, NULL, ED, NULL, true);
+  // Compute the edit distance between the typo and this keyword,
+  // and add the keyword to the list of results.
+  addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
 }
=20
 void TypoCorrectionConsumer::addName(StringRef Name,
@@ -3149,7 +3276,7 @@
=20
 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
   StringRef Name =3D Correction.getCorrectionAsIdentifierInfo()->getName();
-  TypoResultsMap *& Map =3D BestResults[Correction.getEditDistance()];
+  TypoResultsMap *& Map =3D BestResults[Correction.getEditDistance(false)];
   if (!Map)
     Map =3D new TypoResultsMap;
=20
@@ -3158,8 +3285,8 @@
       // FIXME: The following should be rolled up into an operator< on
       // TypoCorrection with a more principled definition.
       CurrentCorrection.isKeyword() < Correction.isKeyword() ||
-      Correction.getAsString(SemaRef.getLangOptions()) <
-      CurrentCorrection.getAsString(SemaRef.getLangOptions()))
+      Correction.getAsString(SemaRef.getLangOpts()) <
+      CurrentCorrection.getAsString(SemaRef.getLangOpts()))
     CurrentCorrection =3D Correction;
=20
   while (BestResults.size() > MaxTypoDistanceResultSets) {
@@ -3170,6 +3297,47 @@
   }
 }
=20
+// Fill the supplied vector with the IdentifierInfo pointers for each piec=
e of
+// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::b=
ar::",
+// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
+static void getNestedNameSpecifierIdentifiers(
+    NestedNameSpecifier *NNS,
+    SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
+  if (NestedNameSpecifier *Prefix =3D NNS->getPrefix())
+    getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
+  else
+    Identifiers.clear();
+
+  const IdentifierInfo *II =3D NULL;
+
+  switch (NNS->getKind()) {
+  case NestedNameSpecifier::Identifier:
+    II =3D NNS->getAsIdentifier();
+    break;
+
+  case NestedNameSpecifier::Namespace:
+    if (NNS->getAsNamespace()->isAnonymousNamespace())
+      return;
+    II =3D NNS->getAsNamespace()->getIdentifier();
+    break;
+
+  case NestedNameSpecifier::NamespaceAlias:
+    II =3D NNS->getAsNamespaceAlias()->getIdentifier();
+    break;
+
+  case NestedNameSpecifier::TypeSpecWithTemplate:
+  case NestedNameSpecifier::TypeSpec:
+    II =3D QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
+    break;
+
+  case NestedNameSpecifier::Global:
+    return;
+  }
+
+  if (II)
+    Identifiers.push_back(II);
+}
+
 namespace {
=20
 class SpecifierInfo {
@@ -3188,6 +3356,8 @@
 class NamespaceSpecifierSet {
   ASTContext &Context;
   DeclContextList CurContextChain;
+  SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
+  SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
   bool isSorted;
=20
   SpecifierInfoList Specifiers;
@@ -3201,9 +3371,23 @@
   void SortNamespaces();
=20
  public:
-  explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurCont=
ext)
+  NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
+                        CXXScopeSpec *CurScopeSpec)
       : Context(Context), CurContextChain(BuildContextChain(CurContext)),
-        isSorted(true) {}
+        isSorted(true) {
+    if (CurScopeSpec && CurScopeSpec->getScopeRep())
+      getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
+                                        CurNameSpecifierIdentifiers);
+    // Build the list of identifiers that would be used for an absolute
+    // (from the global context) NestedNameSpecifier refering to the curre=
nt
+    // context.
+    for (DeclContextList::reverse_iterator C =3D CurContextChain.rbegin(),
+                                        CEnd =3D CurContextChain.rend();
+         C !=3D CEnd; ++C) {
+      if (NamespaceDecl *ND =3D dyn_cast_or_null<NamespaceDecl>(*C))
+        CurContextIdentifiers.push_back(ND->getIdentifier());
+    }
+  }
=20
   /// \brief Add the namespace to the set, computing the corresponding
   /// NestedNameSpecifier and its distance in the process.
@@ -3241,7 +3425,7 @@
=20
   Specifiers.clear();
   for (SmallVector<unsigned, 4>::iterator DI =3D sortedDistances.begin(),
-                                             DIEnd =3D sortedDistances.end=
();
+                                       DIEnd =3D sortedDistances.end();
        DI !=3D DIEnd; ++DI) {
     SpecifierInfoList &SpecList =3D DistanceMap[*DI];
     Specifiers.append(SpecList.begin(), SpecList.end());
@@ -3255,8 +3439,9 @@
   NestedNameSpecifier *NNS =3D NULL;
   unsigned NumSpecifiers =3D 0;
   DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
-
-  // Eliminate common elements from the two DeclContext chains
+  DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
+
+  // Eliminate common elements from the two DeclContext chains.
   for (DeclContextList::reverse_iterator C =3D CurContextChain.rbegin(),
                                       CEnd =3D CurContextChain.rend();
        C !=3D CEnd && !NamespaceDeclChain.empty() &&
@@ -3264,6 +3449,21 @@
     NamespaceDeclChain.pop_back();
   }
=20
+  // Add an explicit leading '::' specifier if needed.
+  if (NamespaceDecl *ND =3D
+        NamespaceDeclChain.empty() ? NULL :
+          dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
+    IdentifierInfo *Name =3D ND->getIdentifier();
+    if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end=
(),
+                  Name) !=3D CurContextIdentifiers.end() ||
+        std::find(CurNameSpecifierIdentifiers.begin(),
+                  CurNameSpecifierIdentifiers.end(),
+                  Name) !=3D CurNameSpecifierIdentifiers.end()) {
+      NamespaceDeclChain =3D FullNamespaceDeclChain;
+      NNS =3D NestedNameSpecifier::GlobalSpecifier(Context);
+    }
+  }
+
   // Build the NestedNameSpecifier from what is left of the NamespaceDeclC=
hain
   for (DeclContextList::reverse_iterator C =3D NamespaceDeclChain.rbegin(),
                                       CEnd =3D NamespaceDeclChain.rend();
@@ -3275,6 +3475,18 @@
     }
   }
=20
+  // If the built NestedNameSpecifier would be replacing an existing
+  // NestedNameSpecifier, use the number of component identifiers that
+  // would need to be changed as the edit distance instead of the number
+  // of components in the built NestedNameSpecifier.
+  if (NNS && !CurNameSpecifierIdentifiers.empty()) {
+    SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
+    getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
+    NumSpecifiers =3D llvm::ComputeEditDistance(
+      llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
+      llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
+  }
+
   isSorted =3D false;
   Distances.insert(NumSpecifiers);
   DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifie=
rs));
@@ -3287,13 +3499,13 @@
                                       Scope *S, CXXScopeSpec *SS,
                                       DeclContext *MemberContext,
                                       bool EnteringContext,
-                                      Sema::CorrectTypoContext CTC) {
+                                      bool isObjCIvarLookup) {
   Res.suppressDiagnostics();
   Res.clear();
   Res.setLookupName(Name);
   if (MemberContext) {
     if (ObjCInterfaceDecl *Class =3D dyn_cast<ObjCInterfaceDecl>(MemberCon=
text)) {
-      if (CTC =3D=3D Sema::CTC_ObjCIvarLookup) {
+      if (isObjCIvarLookup) {
         if (ObjCIvarDecl *Ivar =3D Class->lookupInstanceVariable(Name)) {
           Res.addDecl(Ivar);
           Res.resolveKind();
@@ -3334,61 +3546,11 @@
 /// \brief Add keywords to the consumer as possible typo corrections.
 static void AddKeywordsToConsumer(Sema &SemaRef,
                                   TypoCorrectionConsumer &Consumer,
-                                  Scope *S, Sema::CorrectTypoContext CTC) {
-  // Add context-dependent keywords.
-  bool WantTypeSpecifiers =3D false;
-  bool WantExpressionKeywords =3D false;
-  bool WantCXXNamedCasts =3D false;
-  bool WantRemainingKeywords =3D false;
-  switch (CTC) {
-    case Sema::CTC_Unknown:
-      WantTypeSpecifiers =3D true;
-      WantExpressionKeywords =3D true;
-      WantCXXNamedCasts =3D true;
-      WantRemainingKeywords =3D true;
-
-      if (ObjCMethodDecl *Method =3D SemaRef.getCurMethodDecl())
-        if (Method->getClassInterface() &&
-            Method->getClassInterface()->getSuperClass())
-          Consumer.addKeywordResult("super");
-
-      break;
-
-    case Sema::CTC_NoKeywords:
-      break;
-
-    case Sema::CTC_Type:
-      WantTypeSpecifiers =3D true;
-      break;
-
-    case Sema::CTC_ObjCMessageReceiver:
-      Consumer.addKeywordResult("super");
-      // Fall through to handle message receivers like expressions.
-
-    case Sema::CTC_Expression:
-      if (SemaRef.getLangOptions().CPlusPlus)
-        WantTypeSpecifiers =3D true;
-      WantExpressionKeywords =3D true;
-      // Fall through to get C++ named casts.
-
-    case Sema::CTC_CXXCasts:
-      WantCXXNamedCasts =3D true;
-      break;
-
-    case Sema::CTC_ObjCPropertyLookup:
-      // FIXME: Add "isa"?
-      break;
-
-    case Sema::CTC_MemberLookup:
-      if (SemaRef.getLangOptions().CPlusPlus)
-        Consumer.addKeywordResult("template");
-      break;
-
-    case Sema::CTC_ObjCIvarLookup:
-      break;
-  }
-
-  if (WantTypeSpecifiers) {
+                                  Scope *S, CorrectionCandidateCallback &C=
CC) {
+  if (CCC.WantObjCSuper)
+    Consumer.addKeywordResult("super");
+
+  if (CCC.WantTypeSpecifiers) {
     // Add type-specifier keywords to the set of results.
     const char *CTypeSpecs[] =3D {
       "char", "const", "double", "enum", "float", "int", "long", "short",
@@ -3402,19 +3564,19 @@
     for (unsigned I =3D 0; I !=3D NumCTypeSpecs; ++I)
       Consumer.addKeywordResult(CTypeSpecs[I]);
=20
-    if (SemaRef.getLangOptions().C99)
+    if (SemaRef.getLangOpts().C99)
       Consumer.addKeywordResult("restrict");
-    if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlu=
s)
+    if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
       Consumer.addKeywordResult("bool");
-    else if (SemaRef.getLangOptions().C99)
+    else if (SemaRef.getLangOpts().C99)
       Consumer.addKeywordResult("_Bool");
    =20
-    if (SemaRef.getLangOptions().CPlusPlus) {
+    if (SemaRef.getLangOpts().CPlusPlus) {
       Consumer.addKeywordResult("class");
       Consumer.addKeywordResult("typename");
       Consumer.addKeywordResult("wchar_t");
=20
-      if (SemaRef.getLangOptions().CPlusPlus0x) {
+      if (SemaRef.getLangOpts().CPlusPlus0x) {
         Consumer.addKeywordResult("char16_t");
         Consumer.addKeywordResult("char32_t");
         Consumer.addKeywordResult("constexpr");
@@ -3423,25 +3585,25 @@
       }
     }
=20
-    if (SemaRef.getLangOptions().GNUMode)
+    if (SemaRef.getLangOpts().GNUMode)
       Consumer.addKeywordResult("typeof");
   }
=20
-  if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
+  if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
     Consumer.addKeywordResult("const_cast");
     Consumer.addKeywordResult("dynamic_cast");
     Consumer.addKeywordResult("reinterpret_cast");
     Consumer.addKeywordResult("static_cast");
   }
=20
-  if (WantExpressionKeywords) {
+  if (CCC.WantExpressionKeywords) {
     Consumer.addKeywordResult("sizeof");
-    if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlu=
s) {
+    if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
       Consumer.addKeywordResult("false");
       Consumer.addKeywordResult("true");
     }
=20
-    if (SemaRef.getLangOptions().CPlusPlus) {
+    if (SemaRef.getLangOpts().CPlusPlus) {
       const char *CXXExprs[] =3D {
         "delete", "new", "operator", "throw", "typeid"
       };
@@ -3453,14 +3615,14 @@
           cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
         Consumer.addKeywordResult("this");
=20
-      if (SemaRef.getLangOptions().CPlusPlus0x) {
+      if (SemaRef.getLangOpts().CPlusPlus0x) {
         Consumer.addKeywordResult("alignof");
         Consumer.addKeywordResult("nullptr");
       }
     }
   }
=20
-  if (WantRemainingKeywords) {
+  if (CCC.WantRemainingKeywords) {
     if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
       // Statements.
       const char *CStmts[] =3D {
@@ -3469,7 +3631,7 @@
       for (unsigned I =3D 0; I !=3D NumCStmts; ++I)
         Consumer.addKeywordResult(CStmts[I]);
=20
-      if (SemaRef.getLangOptions().CPlusPlus) {
+      if (SemaRef.getLangOpts().CPlusPlus) {
         Consumer.addKeywordResult("catch");
         Consumer.addKeywordResult("try");
       }
@@ -3485,7 +3647,7 @@
         Consumer.addKeywordResult("default");
       }
     } else {
-      if (SemaRef.getLangOptions().CPlusPlus) {
+      if (SemaRef.getLangOpts().CPlusPlus) {
         Consumer.addKeywordResult("namespace");
         Consumer.addKeywordResult("template");
       }
@@ -3501,15 +3663,21 @@
       }
     }
=20
-    if (SemaRef.getLangOptions().CPlusPlus) {
+    if (SemaRef.getLangOpts().CPlusPlus) {
       Consumer.addKeywordResult("using");
=20
-      if (SemaRef.getLangOptions().CPlusPlus0x)
+      if (SemaRef.getLangOpts().CPlusPlus0x)
         Consumer.addKeywordResult("static_assert");
     }
   }
 }
=20
+static bool isCandidateViable(CorrectionCandidateCallback &CCC,
+                              TypoCorrection &Candidate) {
+  Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
+  return Candidate.getEditDistance(false) !=3D TypoCorrection::InvalidDist=
ance;
+}
+
 /// \brief Try to "correct" a typo in the source code by finding
 /// visible declarations whose names are similar to the name that was
 /// present in the source code.
@@ -3524,15 +3692,16 @@
 /// \param SS the nested-name-specifier that precedes the name we're
 /// looking for, if present.
 ///
+/// \param CCC A CorrectionCandidateCallback object that provides further
+/// validation of typo correction candidates. It also provides flags for
+/// determining the set of keywords permitted.
+///
 /// \param MemberContext if non-NULL, the context in which to look for
 /// a member access expression.
 ///
 /// \param EnteringContext whether we're entering the context described by
 /// the nested-name-specifier SS.
 ///
-/// \param CTC The context in which typo correction occurs, which impacts =
the
-/// set of keywords permitted.
-///
 /// \param OPT when non-NULL, the search for visible declarations will
 /// also walk the protocols in the qualified interfaces of \p OPT.
 ///
@@ -3543,11 +3712,18 @@
 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
                                  Sema::LookupNameKind LookupKind,
                                  Scope *S, CXXScopeSpec *SS,
+                                 CorrectionCandidateCallback &CCC,
                                  DeclContext *MemberContext,
                                  bool EnteringContext,
-                                 CorrectTypoContext CTC,
                                  const ObjCObjectPointerType *OPT) {
-  if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
+  if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
+    return TypoCorrection();
+
+  // In Microsoft mode, don't perform typo correction in a template member
+  // function dependent context because it interferes with the "lookup into
+  // dependent bases of class templates" feature.
+  if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
+      isa<CXXMethodDecl>(CurContext))
     return TypoCorrection();
=20
   // We only attempt to correct typos for identifiers.
@@ -3565,12 +3741,18 @@
   if (!ActiveTemplateInstantiations.empty())
     return TypoCorrection();
=20
-  NamespaceSpecifierSet Namespaces(Context, CurContext);
+  NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
=20
   TypoCorrectionConsumer Consumer(*this, Typo);
=20
+  // If a callback object considers an empty typo correction candidate to =
be
+  // viable, assume it does not do any actual validation of the candidates.
+  TypoCorrection EmptyCorrection;
+  bool ValidatingCallback =3D !isCandidateViable(CCC, EmptyCorrection);
+
   // Perform name lookup to find visible, similarly-named entities.
   bool IsUnqualifiedLookup =3D false;
+  DeclContext *QualifiedDC =3D MemberContext;
   if (MemberContext) {
     LookupVisibleDecls(MemberContext, LookupKind, Consumer);
=20
@@ -3582,8 +3764,8 @@
         LookupVisibleDecls(*I, LookupKind, Consumer);
     }
   } else if (SS && SS->isSet()) {
-    DeclContext *DC =3D computeDeclContext(*SS, EnteringContext);
-    if (!DC)
+    QualifiedDC =3D computeDeclContext(*SS, EnteringContext);
+    if (!QualifiedDC)
       return TypoCorrection();
=20
     // Provide a stop gap for files that are just seriously broken.  Trying
@@ -3593,49 +3775,65 @@
       return TypoCorrection();
     ++TyposCorrected;
=20
-    LookupVisibleDecls(DC, LookupKind, Consumer);
+    LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
   } else {
     IsUnqualifiedLookup =3D true;
     UnqualifiedTyposCorrectedMap::iterator Cached
       =3D UnqualifiedTyposCorrected.find(Typo);
+    if (Cached !=3D UnqualifiedTyposCorrected.end()) {
+      // Add the cached value, unless it's a keyword or fails validation. =
In the
+      // keyword case, we'll end up adding the keyword below.
+      if (Cached->second) {
+        if (!Cached->second.isKeyword() &&
+            isCandidateViable(CCC, Cached->second))
+          Consumer.addCorrection(Cached->second);
+      } else {
+        // Only honor no-correction cache hits when a callback that will v=
alidate
+        // correction candidates is not being used.
+        if (!ValidatingCallback)
+          return TypoCorrection();
+      }
+    }
     if (Cached =3D=3D UnqualifiedTyposCorrected.end()) {
       // Provide a stop gap for files that are just seriously broken.  Try=
ing
       // to correct all typos can turn into a HUGE performance penalty, ca=
using
       // some files to take minutes to get rejected by the parser.
       if (TyposCorrected + UnqualifiedTyposCorrected.size() >=3D 20)
         return TypoCorrection();
-
-      // For unqualified lookup, look through all of the names that we have
-      // seen in this translation unit.
-      for (IdentifierTable::iterator I =3D Context.Idents.begin(),
-                                  IEnd =3D Context.Idents.end();
-           I !=3D IEnd; ++I)
-        Consumer.FoundName(I->getKey());
-
-      // Walk through identifiers in external identifier sources.
-      if (IdentifierInfoLookup *External
-                              =3D Context.Idents.getExternalIdentifierLook=
up()) {
-        llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers(=
));
-        do {
-          StringRef Name =3D Iter->Next();
-          if (Name.empty())
-            break;
-
-          Consumer.FoundName(Name);
-        } while (true);
-      }
-    } else {
-      // Use the cached value, unless it's a keyword. In the keyword case,=
 we'll
-      // end up adding the keyword below.
-      if (!Cached->second)
-        return TypoCorrection();
-
-      if (!Cached->second.isKeyword())
-        Consumer.addCorrection(Cached->second);
     }
   }
=20
-  AddKeywordsToConsumer(*this, Consumer, S,  CTC);
+  // Determine whether we are going to search in the various namespaces for
+  // corrections.
+  bool SearchNamespaces
+    =3D getLangOpts().CPlusPlus &&
+      (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
+ =20
+  if (IsUnqualifiedLookup || SearchNamespaces) {
+    // For unqualified lookup, look through all of the names that we have
+    // seen in this translation unit.
+    // FIXME: Re-add the ability to skip very unlikely potential correctio=
ns.
+    for (IdentifierTable::iterator I =3D Context.Idents.begin(),
+                                IEnd =3D Context.Idents.end();
+         I !=3D IEnd; ++I)
+      Consumer.FoundName(I->getKey());
+
+    // Walk through identifiers in external identifier sources.
+    // FIXME: Re-add the ability to skip very unlikely potential correctio=
ns.
+    if (IdentifierInfoLookup *External
+                            =3D Context.Idents.getExternalIdentifierLookup=
()) {
+      OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
+      do {
+        StringRef Name =3D Iter->Next();
+        if (Name.empty())
+          break;
+
+        Consumer.FoundName(Name);
+      } while (true);
+    }
+  }
+
+  AddKeywordsToConsumer(*this, Consumer, S, CCC);
=20
   // If we haven't found anything, we're done.
   if (Consumer.empty()) {
@@ -3648,7 +3846,7 @@
=20
   // Make sure that the user typed at least 3 characters for each correcti=
on
   // made. Otherwise, we don't even both looking at the results.
-  unsigned ED =3D Consumer.getBestEditDistance();
+  unsigned ED =3D Consumer.getBestEditDistance(true);
   if (ED > 0 && Typo->getName().size() / ED < 3) {
     // If this was an unqualified lookup, note that no correction was foun=
d.
     if (IsUnqualifiedLookup)
@@ -3657,8 +3855,9 @@
     return TypoCorrection();
   }
=20
-  // Build the NestedNameSpecifiers for the KnownNamespaces
-  if (getLangOptions().CPlusPlus) {
+  // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
+  // to search those namespaces.
+  if (SearchNamespaces) {
     // Load any externally-known namespaces.
     if (ExternalSource && !LoadedExternalKnownNamespaces) {
       SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
@@ -3675,8 +3874,9 @@
       Namespaces.AddNamespace(KNI->first);
   }
=20
-  // Weed out any names that could not be found by name lookup.
-  llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
+  // Weed out any names that could not be found by name lookup or, if a
+  // CorrectionCandidateCallback object was provided, failed validation.
+  llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
   LookupResult TmpRes(*this, TypoName, LookupKind);
   TmpRes.suppressDiagnostics();
   while (!Consumer.empty()) {
@@ -3685,22 +3885,27 @@
     for (TypoCorrectionConsumer::result_iterator I =3D DI->second->begin(),
                                               IEnd =3D DI->second->end();
          I !=3D IEnd; /* Increment in loop. */) {
-      // If the item already has been looked up or is a keyword, keep it
+      // If the item already has been looked up or is a keyword, keep it.
+      // If a validator callback object was given, drop the correction
+      // unless it passes validation.
       if (I->second.isResolved()) {
+        TypoCorrectionConsumer::result_iterator Prev =3D I;
         ++I;
+        if (!isCandidateViable(CCC, Prev->second))
+          DI->second->erase(Prev);
         continue;
       }
=20
       // Perform name lookup on this name.
       IdentifierInfo *Name =3D I->second.getCorrectionAsIdentifierInfo();
       LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
-                                EnteringContext, CTC);
+                                EnteringContext, CCC.IsObjCIvarLookup);
=20
       switch (TmpRes.getResultKind()) {
       case LookupResult::NotFound:
       case LookupResult::NotFoundInCurrentInstantiation:
       case LookupResult::FoundUnresolvedValue:
-        QualifiedResults.insert(Name);
+        QualifiedResults.push_back(I->second);
         // We didn't find this name in our scope, or didn't like what we f=
ound;
         // ignore it.
         {
@@ -3716,32 +3921,40 @@
         return TypoCorrection();
=20
       case LookupResult::FoundOverloaded: {
+        TypoCorrectionConsumer::result_iterator Prev =3D I;
         // Store all of the Decls for overloaded symbols
         for (LookupResult::iterator TRD =3D TmpRes.begin(),
                                  TRDEnd =3D TmpRes.end();
              TRD !=3D TRDEnd; ++TRD)
           I->second.addCorrectionDecl(*TRD);
         ++I;
+        if (!isCandidateViable(CCC, Prev->second))
+          DI->second->erase(Prev);
         break;
       }
=20
-      case LookupResult::Found:
+      case LookupResult::Found: {
+        TypoCorrectionConsumer::result_iterator Prev =3D I;
         I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
         ++I;
+        if (!isCandidateViable(CCC, Prev->second))
+          DI->second->erase(Prev);
         break;
       }
+
+      }
     }
=20
     if (DI->second->empty())
       Consumer.erase(DI);
-    else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !E=
D)
+    else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
       // If there are results in the closest possible bucket, stop
       break;
=20
     // Only perform the qualified lookups for C++
-    if (getLangOptions().CPlusPlus) {
+    if (SearchNamespaces) {
       TmpRes.suppressDiagnostics();
-      for (llvm::SmallPtrSet<IdentifierInfo*,
+      for (llvm::SmallVector<TypoCorrection,
                              16>::iterator QRI =3D QualifiedResults.begin(=
),
                                         QRIEnd =3D QualifiedResults.end();
            QRI !=3D QRIEnd; ++QRI) {
@@ -3749,30 +3962,35 @@
                                           NIEnd =3D Namespaces.end();
              NI !=3D NIEnd; ++NI) {
           DeclContext *Ctx =3D NI->DeclCtx;
-          unsigned QualifiedED =3D ED + NI->EditDistance;
-
-          // Stop searching once the namespaces are too far away to create
+
+          // FIXME: Stop searching once the namespaces are too far away to=
 create
           // acceptable corrections for this identifier (since the namespa=
ces
-          // are sorted in ascending order by edit distance)
-          if (QualifiedED > Consumer.getMaxEditDistance()) break;
+          // are sorted in ascending order by edit distance).
=20
           TmpRes.clear();
-          TmpRes.setLookupName(*QRI);
+          TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
           if (!LookupQualifiedName(TmpRes, Ctx)) continue;
=20
+          // Any corrections added below will be validated in subsequent
+          // iterations of the main while() loop over the Consumer's conte=
nts.
           switch (TmpRes.getResultKind()) {
-          case LookupResult::Found:
-            Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDe=
cl>(),
-                             QualifiedED, NI->NameSpecifier);
+          case LookupResult::Found: {
+            TypoCorrection TC(*QRI);
+            TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
+            TC.setCorrectionSpecifier(NI->NameSpecifier);
+            TC.setQualifierDistance(NI->EditDistance);
+            Consumer.addCorrection(TC);
             break;
+          }
           case LookupResult::FoundOverloaded: {
-            TypoCorrection corr(&Context.Idents.get((*QRI)->getName()), NU=
LL,
-                                NI->NameSpecifier, QualifiedED);
+            TypoCorrection TC(*QRI);
+            TC.setCorrectionSpecifier(NI->NameSpecifier);
+            TC.setQualifierDistance(NI->EditDistance);
             for (LookupResult::iterator TRD =3D TmpRes.begin(),
                                      TRDEnd =3D TmpRes.end();
                  TRD !=3D TRDEnd; ++TRD)
-              corr.addCorrectionDecl(*TRD);
-            Consumer.addCorrection(corr);
+              TC.addCorrectionDecl(*TRD);
+            Consumer.addCorrection(TC);
             break;
           }
           case LookupResult::NotFound:
@@ -3792,32 +4010,18 @@
   if (Consumer.empty()) return TypoCorrection();
=20
   TypoResultsMap &BestResults =3D *Consumer.begin()->second;
-  ED =3D Consumer.begin()->first;
+  ED =3D TypoCorrection::NormalizeEditDistance(Consumer.begin()->first);
=20
   if (ED > 0 && Typo->getName().size() / ED < 3) {
-    // If this was an unqualified lookup, note that no correction was foun=
d.
-    if (IsUnqualifiedLookup)
+    // If this was an unqualified lookup and we believe the callback
+    // object wouldn't have filtered out possible corrections, note
+    // that no correction was found.
+    if (IsUnqualifiedLookup && !ValidatingCallback)
       (void)UnqualifiedTyposCorrected[Typo];
=20
     return TypoCorrection();
   }
=20
-  // If we have multiple possible corrections, eliminate the ones where we
-  // added namespace qualifiers to try to resolve the ambiguity (and to fa=
vor
-  // corrections without additional namespace qualifiers)
-  if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
-    TypoCorrectionConsumer::distance_iterator DI =3D Consumer.begin();
-    for (TypoCorrectionConsumer::result_iterator I =3D DI->second->begin(),
-                                              IEnd =3D DI->second->end();
-         I !=3D IEnd; /* Increment in loop. */) {
-      if (I->second.getCorrectionSpecifier() !=3D NULL) {
-        TypoCorrectionConsumer::result_iterator Cur =3D I;
-        ++I;
-        DI->second->erase(Cur);
-      } else ++I;
-    }
-  }
-
   // If only a single name remains, return that result.
   if (BestResults.size() =3D=3D 1) {
     const llvm::StringMapEntry<TypoCorrection> &Correction =3D *(BestResul=
ts.begin());
@@ -3833,7 +4037,12 @@
=20
     return Result;
   }
-  else if (BestResults.size() > 1 && CTC =3D=3D CTC_ObjCMessageReceiver
+  else if (BestResults.size() > 1
+           // Ugly hack equivalent to CTC =3D=3D CTC_ObjCMessageReceiver;
+           // WantObjCSuper is only true for CTC_ObjCMessageReceiver and f=
or
+           // some instances of CTC_Unknown, while WantRemainingKeywords i=
s true
+           // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
+           && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
            && BestResults["super"].isKeyword()) {
     // Prefer 'super' when we're completing in a message-receiver
     // context.
@@ -3849,7 +4058,9 @@
     return BestResults["super"];
   }
=20
-  if (IsUnqualifiedLookup)
+  // If this was an unqualified lookup and we believe the callback object =
did
+  // not filter out possible corrections, note that no correction was foun=
d.
+  if (IsUnqualifiedLookup && !ValidatingCallback)
     (void)UnqualifiedTyposCorrected[Typo];
=20
   return TypoCorrection();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaObjCProperty.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaObjCProperty.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaObjCProperty.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -17,7 +17,9 @@
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/ASTMutationListener.h"
 #include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
=20
@@ -99,6 +101,7 @@
 }
=20
 Decl *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
+                          SourceLocation LParenLoc,
                           FieldDeclarator &FD,
                           ObjCDeclSpec &ODS,
                           Selector GetterSel,
@@ -109,9 +112,9 @@
   unsigned Attributes =3D ODS.getPropertyAttributes();
   TypeSourceInfo *TSI =3D GetTypeForDeclarator(FD.D, S);
   QualType T =3D TSI->getType();
-  if ((getLangOptions().getGC() !=3D LangOptions::NonGC &&=20
+  if ((getLangOpts().getGC() !=3D LangOptions::NonGC &&=20
        T.isObjCGCWeak()) ||
-      (getLangOptions().ObjCAutoRefCount &&
+      (getLangOpts().ObjCAutoRefCount &&
        T.getObjCLifetime() =3D=3D Qualifiers::OCL_Weak))
     Attributes |=3D ObjCDeclSpec::DQ_PR_weak;
=20
@@ -133,43 +136,80 @@
=20
   if (ObjCCategoryDecl *CDecl =3D dyn_cast<ObjCCategoryDecl>(ClassDecl))
     if (CDecl->IsClassExtension()) {
-      Decl *Res =3D HandlePropertyInClassExtension(S, AtLoc,
+      Decl *Res =3D HandlePropertyInClassExtension(S, AtLoc, LParenLoc,
                                            FD, GetterSel, SetterSel,
                                            isAssign, isReadWrite,
                                            Attributes,
+                                           ODS.getPropertyAttributes(),
                                            isOverridingProperty, TSI,
                                            MethodImplKind);
       if (Res) {
         CheckObjCPropertyAttributes(Res, AtLoc, Attributes);
-        if (getLangOptions().ObjCAutoRefCount)
+        if (getLangOpts().ObjCAutoRefCount)
           checkARCPropertyDecl(*this, cast<ObjCPropertyDecl>(Res));
       }
       return Res;
     }
  =20
-  ObjCPropertyDecl *Res =3D CreatePropertyDecl(S, ClassDecl, AtLoc, FD,
+  ObjCPropertyDecl *Res =3D CreatePropertyDecl(S, ClassDecl, AtLoc, LParen=
Loc, FD,
                                              GetterSel, SetterSel,
                                              isAssign, isReadWrite,
-                                             Attributes, TSI, MethodImplKi=
nd);
+                                             Attributes,
+                                             ODS.getPropertyAttributes(),
+                                             TSI, MethodImplKind);
   if (lexicalDC)
     Res->setLexicalDeclContext(lexicalDC);
=20
   // Validate the attributes on the @property.
   CheckObjCPropertyAttributes(Res, AtLoc, Attributes);
=20
-  if (getLangOptions().ObjCAutoRefCount)
+  if (getLangOpts().ObjCAutoRefCount)
     checkARCPropertyDecl(*this, Res);
=20
   return Res;
 }
=20
+static ObjCPropertyDecl::PropertyAttributeKind
+makePropertyAttributesAsWritten(unsigned Attributes) {
+  unsigned attributesAsWritten =3D 0;
+  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_readonly;
+  if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_readwrite;
+  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_getter;
+  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_setter;
+  if (Attributes & ObjCDeclSpec::DQ_PR_assign)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_assign;
+  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_retain;
+  if (Attributes & ObjCDeclSpec::DQ_PR_strong)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_strong;
+  if (Attributes & ObjCDeclSpec::DQ_PR_weak)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_weak;
+  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_copy;
+  if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
+  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_nonatomic;
+  if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
+    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_atomic;
+ =20
+  return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten;
+}
+
 Decl *
 Sema::HandlePropertyInClassExtension(Scope *S,
-                                     SourceLocation AtLoc, FieldDeclarator=
 &FD,
+                                     SourceLocation AtLoc,
+                                     SourceLocation LParenLoc,
+                                     FieldDeclarator &FD,
                                      Selector GetterSel, Selector SetterSe=
l,
                                      const bool isAssign,
                                      const bool isReadWrite,
                                      const unsigned Attributes,
+                                     const unsigned AttributesAsWritten,
                                      bool *isOverridingProperty,
                                      TypeSourceInfo *T,
                                      tok::ObjCKeywordKind MethodImplKind) {
@@ -198,7 +238,9 @@
   // FIXME. We should really be using CreatePropertyDecl for this.
   ObjCPropertyDecl *PDecl =3D
     ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(),
-                             PropertyId, AtLoc, T);
+                             PropertyId, AtLoc, LParenLoc, T);
+  PDecl->setPropertyAttributesAsWritten(
+                          makePropertyAttributesAsWritten(AttributesAsWrit=
ten));
   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
   if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
@@ -224,23 +266,40 @@
   if (!PIDecl) {
     // No matching property found in the primary class. Just fall thru
     // and add property to continuation class's primary class.
-    ObjCPropertyDecl *PDecl =3D
-      CreatePropertyDecl(S, CCPrimary, AtLoc,
+    ObjCPropertyDecl *PrimaryPDecl =3D
+      CreatePropertyDecl(S, CCPrimary, AtLoc, LParenLoc,
                          FD, GetterSel, SetterSel, isAssign, isReadWrite,
-                         Attributes, T, MethodImplKind, DC);
+                         Attributes,AttributesAsWritten, T, MethodImplKind=
, DC);
=20
     // A case of continuation class adding a new property in the class. Th=
is
     // is not what it was meant for. However, gcc supports it and so shoul=
d we.
     // Make sure setter/getters are declared here.
-    ProcessPropertyDecl(PDecl, CCPrimary, /* redeclaredProperty =3D */ 0,
+    ProcessPropertyDecl(PrimaryPDecl, CCPrimary, /* redeclaredProperty =3D=
 */ 0,
                         /* lexicalDC =3D */ CDecl);
-    return PDecl;
+    PDecl->setGetterMethodDecl(PrimaryPDecl->getGetterMethodDecl());
+    PDecl->setSetterMethodDecl(PrimaryPDecl->getSetterMethodDecl());
+    if (ASTMutationListener *L =3D Context.getASTMutationListener())
+      L->AddedObjCPropertyInClassExtension(PrimaryPDecl, /*OrigProp=3D*/0,=
 CDecl);
+    return PrimaryPDecl;
   }
-  if (PIDecl->getType().getCanonicalType()=20
-      !=3D PDecl->getType().getCanonicalType()) {
-    Diag(AtLoc,=20
-         diag::warn_type_mismatch_continuation_class) << PDecl->getType();
-    Diag(PIDecl->getLocation(), diag::note_property_declare);
+  if (!Context.hasSameType(PIDecl->getType(), PDecl->getType())) {
+    bool IncompatibleObjC =3D false;
+    QualType ConvertedType;
+    // Relax the strict type matching for property type in continuation cl=
ass.
+    // Allow property object type of continuation class to be different as=
 long
+    // as it narrows the object type in its primary class property. Note t=
hat
+    // this conversion is safe only because the wider type is for a 'reado=
nly'
+    // property in primary class and 'narrowed' type for a 'readwrite' pro=
perty
+    // in continuation class.
+    if (!isa<ObjCObjectPointerType>(PIDecl->getType()) ||
+        !isa<ObjCObjectPointerType>(PDecl->getType()) ||
+        (!isObjCPointerConversion(PDecl->getType(), PIDecl->getType(),=20
+                                  ConvertedType, IncompatibleObjC))
+        || IncompatibleObjC) {
+      Diag(AtLoc,=20
+          diag::err_type_mismatch_continuation_class) << PDecl->getType();
+      Diag(PIDecl->getLocation(), diag::note_property_declare);
+    }
   }
    =20
   // The property 'PIDecl's readonly attribute will be over-ridden
@@ -273,7 +332,7 @@
       ContextRAII SavedContext(*this, CCPrimary);
      =20
       Decl *ProtocolPtrTy =3D
-        ActOnProperty(S, AtLoc, FD, ProtocolPropertyODS,
+        ActOnProperty(S, AtLoc, LParenLoc, FD, ProtocolPropertyODS,
                       PIDecl->getGetterName(),
                       PIDecl->getSetterName(),
                       isOverridingProperty,
@@ -306,18 +365,24 @@
   *isOverridingProperty =3D true;
   // Make sure setter decl is synthesized, and added to primary class's li=
st.
   ProcessPropertyDecl(PIDecl, CCPrimary, PDecl, CDecl);
+  PDecl->setGetterMethodDecl(PIDecl->getGetterMethodDecl());
+  PDecl->setSetterMethodDecl(PIDecl->getSetterMethodDecl());
+  if (ASTMutationListener *L =3D Context.getASTMutationListener())
+    L->AddedObjCPropertyInClassExtension(PDecl, PIDecl, CDecl);
   return 0;
 }
=20
 ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S,
                                            ObjCContainerDecl *CDecl,
                                            SourceLocation AtLoc,
+                                           SourceLocation LParenLoc,
                                            FieldDeclarator &FD,
                                            Selector GetterSel,
                                            Selector SetterSel,
                                            const bool isAssign,
                                            const bool isReadWrite,
                                            const unsigned Attributes,
+                                           const unsigned AttributesAsWrit=
ten,
                                            TypeSourceInfo *TInfo,
                                            tok::ObjCKeywordKind MethodImpl=
Kind,
                                            DeclContext *lexicalDC){
@@ -326,7 +391,7 @@
=20
   // Issue a warning if property is 'assign' as default and its object, wh=
ich is
   // gc'able conforms to NSCopying protocol
-  if (getLangOptions().getGC() !=3D LangOptions::NonGC &&
+  if (getLangOpts().getGC() !=3D LangOptions::NonGC &&
       isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign))
     if (const ObjCObjectPointerType *ObjPtrTy =3D
           T->getAs<ObjCObjectPointerType>()) {
@@ -343,7 +408,7 @@
   DeclContext *DC =3D cast<DeclContext>(CDecl);
   ObjCPropertyDecl *PDecl =3D ObjCPropertyDecl::Create(Context, DC,
                                                      FD.D.getIdentifierLoc=
(),
-                                                     PropertyId, AtLoc, TI=
nfo);
+                                                     PropertyId, AtLoc, LP=
arenLoc, TInfo);
=20
   if (ObjCPropertyDecl *prevDecl =3D
         ObjCPropertyDecl::findPropertyDecl(DC, PropertyId)) {
@@ -368,35 +433,8 @@
   // selector names in anticipation of declaration of setter/getter method=
s.
   PDecl->setGetterName(GetterSel);
   PDecl->setSetterName(SetterSel);
-
-  unsigned attributesAsWritten =3D 0;
-  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_readonly;
-  if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_readwrite;
-  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_getter;
-  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_setter;
-  if (Attributes & ObjCDeclSpec::DQ_PR_assign)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_assign;
-  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_retain;
-  if (Attributes & ObjCDeclSpec::DQ_PR_strong)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_strong;
-  if (Attributes & ObjCDeclSpec::DQ_PR_weak)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_weak;
-  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_copy;
-  if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
-  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_nonatomic;
-  if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
-    attributesAsWritten |=3D ObjCPropertyDecl::OBJC_PR_atomic;
-
   PDecl->setPropertyAttributesAsWritten(
-                  (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWri=
tten);
+                          makePropertyAttributesAsWritten(AttributesAsWrit=
ten));
=20
   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
@@ -502,6 +540,33 @@
   S.Diag(property->getLocation(), diag::note_property_declare);
 }
=20
+/// setImpliedPropertyAttributeForReadOnlyProperty -
+/// This routine evaludates life-time attributes for a 'readonly'
+/// property with no known lifetime of its own, using backing
+/// 'ivar's attribute, if any. If no backing 'ivar', property's
+/// life-time is assumed 'strong'.
+static void setImpliedPropertyAttributeForReadOnlyProperty(
+              ObjCPropertyDecl *property, ObjCIvarDecl *ivar) {
+  Qualifiers::ObjCLifetime propertyLifetime =3D=20
+    getImpliedARCOwnership(property->getPropertyAttributes(),
+                           property->getType());
+  if (propertyLifetime !=3D Qualifiers::OCL_None)
+    return;
+ =20
+  if (!ivar) {
+    // if no backing ivar, make property 'strong'.
+    property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
+    return;
+  }
+  // property assumes owenership of backing ivar.
+  QualType ivarType =3D ivar->getType();
+  Qualifiers::ObjCLifetime ivarLifetime =3D ivarType.getObjCLifetime();
+  if (ivarLifetime =3D=3D Qualifiers::OCL_Strong)
+    property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
+  else if (ivarLifetime =3D=3D Qualifiers::OCL_Weak)
+    property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
+  return;
+}
=20
 /// ActOnPropertyImplDecl - This routine performs semantic checks and
 /// builds the AST node for a property implementation declaration; declared
@@ -521,6 +586,8 @@
     Diag(AtLoc, diag::error_missing_property_context);
     return 0;
   }
+  if (PropertyIvarLoc.isInvalid())
+    PropertyIvarLoc =3D PropertyLoc;
   ObjCPropertyDecl *property =3D 0;
   ObjCInterfaceDecl* IDecl =3D 0;
   // Find the class or category class where this property must have
@@ -592,16 +659,26 @@
     // @synthesize
     if (!PropertyIvar)
       PropertyIvar =3D PropertyId;
+    // Check that this is a previously declared 'ivar' in 'IDecl' interface
+    ObjCInterfaceDecl *ClassDeclared;
+    Ivar =3D IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
+    QualType PropType =3D property->getType();
+    QualType PropertyIvarType =3D PropType.getNonReferenceType();
+   =20
+    if (getLangOpts().ObjCAutoRefCount &&
+        (property->getPropertyAttributesAsWritten() &
+         ObjCPropertyDecl::OBJC_PR_readonly) &&
+        PropertyIvarType->isObjCRetainableType()) {
+      setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar);   =20
+    }
+   =20
     ObjCPropertyDecl::PropertyAttributeKind kind=20
       =3D property->getPropertyAttributes();
-    QualType PropType =3D property->getType();
-
-    QualType PropertyIvarType =3D PropType.getNonReferenceType();
=20
     // Add GC __weak to the ivar type if the property is weak.
     if ((kind & ObjCPropertyDecl::OBJC_PR_weak) &&=20
-        getLangOptions().getGC() !=3D LangOptions::NonGC) {
-      assert(!getLangOptions().ObjCAutoRefCount);
+        getLangOpts().getGC() !=3D LangOptions::NonGC) {
+      assert(!getLangOpts().ObjCAutoRefCount);
       if (PropertyIvarType.isObjCGCStrong()) {
         Diag(PropertyLoc, diag::err_gc_weak_property_strong_type);
         Diag(property->getLocation(), diag::note_property_declare);
@@ -611,13 +688,10 @@
       }
     }
=20
-    // Check that this is a previously declared 'ivar' in 'IDecl' interface
-    ObjCInterfaceDecl *ClassDeclared;
-    Ivar =3D IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
     if (!Ivar) {
       // In ARC, give the ivar a lifetime qualifier based on the
       // property attributes.
-      if (getLangOptions().ObjCAutoRefCount &&
+      if (getLangOpts().ObjCAutoRefCount &&
           !PropertyIvarType.getObjCLifetime() &&
           PropertyIvarType->isObjCRetainableType()) {
=20
@@ -632,13 +706,21 @@
           Qualifiers::ObjCLifetime lifetime =3D
             getImpliedARCOwnership(kind, PropertyIvarType);
           assert(lifetime && "no lifetime for property?");
-
-          if (lifetime =3D=3D Qualifiers::OCL_Weak &&
-              !getLangOptions().ObjCRuntimeHasWeak) {
-            Diag(PropertyLoc, diag::err_arc_weak_no_runtime);
-            Diag(property->getLocation(), diag::note_property_declare);
+          if (lifetime =3D=3D Qualifiers::OCL_Weak) {
+            bool err =3D false;
+            if (const ObjCObjectPointerType *ObjT =3D
+                PropertyIvarType->getAs<ObjCObjectPointerType>())
+              if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable()) {
+                Diag(PropertyLoc, diag::err_arc_weak_unavailable_property);
+                Diag(property->getLocation(), diag::note_property_declare);
+                err =3D true;
+              }
+            if (!err && !getLangOpts().ObjCRuntimeHasWeak) {
+              Diag(PropertyLoc, diag::err_arc_weak_no_runtime);
+              Diag(property->getLocation(), diag::note_property_declare);
+            }
           }
-
+         =20
           Qualifiers qs;
           qs.addObjCLifetime(lifetime);
           PropertyIvarType =3D Context.getQualifiedType(PropertyIvarType, =
qs);  =20
@@ -646,27 +728,27 @@
       }
=20
       if (kind & ObjCPropertyDecl::OBJC_PR_weak &&
-          !getLangOptions().ObjCAutoRefCount &&
-          getLangOptions().getGC() =3D=3D LangOptions::NonGC) {
+          !getLangOpts().ObjCAutoRefCount &&
+          getLangOpts().getGC() =3D=3D LangOptions::NonGC) {
         Diag(PropertyLoc, diag::error_synthesize_weak_non_arc_or_gc);
         Diag(property->getLocation(), diag::note_property_declare);
       }
=20
       Ivar =3D ObjCIvarDecl::Create(Context, ClassImpDecl,
-                                  PropertyLoc, PropertyLoc, PropertyIvar,
+                                  PropertyIvarLoc,PropertyIvarLoc, Propert=
yIvar,
                                   PropertyIvarType, /*Dinfo=3D*/0,
                                   ObjCIvarDecl::Private,
                                   (Expr *)0, true);
       ClassImpDecl->addDecl(Ivar);
-      IDecl->makeDeclVisibleInContext(Ivar, false);
+      IDecl->makeDeclVisibleInContext(Ivar);
       property->setPropertyIvarDecl(Ivar);
=20
-      if (!getLangOptions().ObjCNonFragileABI)
+      if (!getLangOpts().ObjCNonFragileABI)
         Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << Prope=
rtyId;
       // Note! I deliberately want it to fall thru so, we have a
       // a property implementation and to avoid future warnings.
-    } else if (getLangOptions().ObjCNonFragileABI &&
-               ClassDeclared !=3D IDecl) {
+    } else if (getLangOpts().ObjCNonFragileABI &&
+               !declaresSameEntity(ClassDeclared, IDecl)) {
       Diag(PropertyLoc, diag::error_ivar_in_superclass_use)
       << property->getDeclName() << Ivar->getDeclName()
       << ClassDeclared->getDeclName();
@@ -686,10 +768,8 @@
                                   PropertyIvarType->getAs<ObjCObjectPointe=
rType>(),
                                   IvarType->getAs<ObjCObjectPointerType>()=
);
       else {
-        SourceLocation Loc =3D PropertyIvarLoc;
-        if (Loc.isInvalid())
-          Loc =3D PropertyLoc;
-        compat =3D (CheckAssignmentConstraints(Loc, PropertyIvarType, Ivar=
Type)
+        compat =3D (CheckAssignmentConstraints(PropertyIvarLoc, PropertyIv=
arType,
+                                             IvarType)
                     =3D=3D Compatible);
       }
       if (!compat) {
@@ -716,7 +796,7 @@
       }
       // __weak is explicit. So it works on Canonical type.
       if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
-           getLangOptions().getGC() !=3D LangOptions::NonGC)) {
+           getLangOpts().getGC() !=3D LangOptions::NonGC)) {
         Diag(PropertyLoc, diag::error_weak_property)
         << property->getDeclName() << Ivar->getDeclName();
         Diag(Ivar->getLocation(), diag::note_ivar_decl);
@@ -725,13 +805,13 @@
       // Fall thru - see previous comment
       if ((property->getType()->isObjCObjectPointerType() ||
            PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
-          getLangOptions().getGC() !=3D LangOptions::NonGC) {
+          getLangOpts().getGC() !=3D LangOptions::NonGC) {
         Diag(PropertyLoc, diag::error_strong_property)
         << property->getDeclName() << Ivar->getDeclName();
         // Fall thru - see previous comment
       }
     }
-    if (getLangOptions().ObjCAutoRefCount)
+    if (getLangOpts().ObjCAutoRefCount)
       checkARCPropertyImpl(*this, PropertyLoc, property, Ivar);
   } else if (PropertyIvar)
     // @dynamic
@@ -747,14 +827,14 @@
                                Ivar, PropertyIvarLoc);
   if (ObjCMethodDecl *getterMethod =3D property->getGetterMethodDecl()) {
     getterMethod->createImplicitParams(Context, IDecl);
-    if (getLangOptions().CPlusPlus && Synthesize &&
+    if (getLangOpts().CPlusPlus && Synthesize &&
         Ivar->getType()->isRecordType()) {
       // For Objective-C++, need to synthesize the AST for the IVAR object=
 to be
       // returned by the getter as it must conform to C++'s copy-return ru=
les.
       // FIXME. Eventually we want to do this for Objective-C as well.
       ImplicitParamDecl *SelfDecl =3D getterMethod->getSelfDecl();
       DeclRefExpr *SelfExpr =3D=20
-        new (Context) DeclRefExpr(SelfDecl, SelfDecl->getType(),
+        new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
                                   VK_RValue, SourceLocation());
       Expr *IvarRefExpr =3D
         new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), AtLoc,
@@ -782,22 +862,20 @@
   }
   if (ObjCMethodDecl *setterMethod =3D property->getSetterMethodDecl()) {
     setterMethod->createImplicitParams(Context, IDecl);
-    if (getLangOptions().CPlusPlus && Synthesize
+    if (getLangOpts().CPlusPlus && Synthesize
         && Ivar->getType()->isRecordType()) {
       // FIXME. Eventually we want to do this for Objective-C as well.
       ImplicitParamDecl *SelfDecl =3D setterMethod->getSelfDecl();
       DeclRefExpr *SelfExpr =3D=20
-        new (Context) DeclRefExpr(SelfDecl, SelfDecl->getType(),
+        new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
                                   VK_RValue, SourceLocation());
       Expr *lhs =3D
         new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), AtLoc,
                                       SelfExpr, true, true);
       ObjCMethodDecl::param_iterator P =3D setterMethod->param_begin();
       ParmVarDecl *Param =3D (*P);
-      QualType T =3D Param->getType();
-      if (T->isReferenceType())
-        T =3D T->getAs<ReferenceType>()->getPointeeType();
-      Expr *rhs =3D new (Context) DeclRefExpr(Param, T,
+      QualType T =3D Param->getType().getNonReferenceType();
+      Expr *rhs =3D new (Context) DeclRefExpr(Param, false, T,
                                             VK_LValue, SourceLocation());
       ExprResult Res =3D BuildBinOp(S, lhs->getLocEnd(),=20
                                   BO_Assign, lhs, rhs);
@@ -808,9 +886,13 @@
               dyn_cast_or_null<CXXOperatorCallExpr>(callExpr))
           if (const FunctionDecl *FuncDecl =3D CXXCE->getDirectCallee())
             if (!FuncDecl->isTrivial())
-              Diag(PropertyLoc,=20
-                   diag::warn_atomic_property_nontrivial_assign_op)=20
+              if (property->getType()->isReferenceType()) {
+                Diag(PropertyLoc,=20
+                     diag::err_atomic_property_nontrivial_assign_op)
                     << property->getType();
+                Diag(FuncDecl->getLocStart(),=20
+                     diag::note_callee_decl) << FuncDecl;
+              }
       }
       PIDecl->setSetterCXXAssignment(Res.takeAs<Expr>());
     }
@@ -833,8 +915,9 @@
       return 0;
     }
     IC->addPropertyImplementation(PIDecl);
-    if (getLangOptions().ObjCDefaultSynthProperties &&
-        getLangOptions().ObjCNonFragileABI2) {
+    if (getLangOpts().ObjCDefaultSynthProperties &&
+        getLangOpts().ObjCNonFragileABI2 &&
+        !IDecl->isObjCRequiresPropertyDefs()) {
       // Diagnose if an ivar was lazily synthesdized due to a previous
       // use and if 1) property is @dynamic or 2) property is synthesized
       // but it requires an ivar of different name.
@@ -848,7 +931,7 @@
       }
       // Issue diagnostics only if Ivar belongs to current class.
       if (Ivar && Ivar->getSynthesize() &&=20
-          IC->getClassInterface() =3D=3D ClassDeclared) {
+          declaresSameEntity(IC->getClassInterface(), ClassDeclared)) {
         Diag(Ivar->getLocation(), diag::err_undeclared_var_use)=20
         << PropertyId;
         Ivar->setInvalidDecl();
@@ -948,7 +1031,8 @@
                                             ObjCMethodDecl *GetterMethod,
                                             SourceLocation Loc) {
   if (GetterMethod &&
-      GetterMethod->getResultType() !=3D property->getType()) {
+      !Context.hasSameType(GetterMethod->getResultType().getNonReferenceTy=
pe(),
+                           property->getType().getNonReferenceType())) {
     AssignConvertType result =3D Incompatible;
     if (property->getType()->isObjCObjectPointerType())
       result =3D CheckAssignmentConstraints(Loc, GetterMethod->getResultTy=
pe(),
@@ -1201,7 +1285,8 @@
     for (ObjCProtocolDecl::prop_iterator P =3D PDecl->prop_begin(),
          E =3D PDecl->prop_end(); P !=3D E; ++P) {
       ObjCPropertyDecl *Prop =3D (*P);
-      PropMap[Prop->getIdentifier()] =3D Prop;
+      if (!PropMap.count(Prop->getIdentifier()))
+        PropMap[Prop->getIdentifier()] =3D Prop;
     }
     // scan through protocol's protocols.
     for (ObjCProtocolDecl::protocol_iterator PI =3D PDecl->protocol_begin(=
),
@@ -1265,7 +1350,7 @@
=20
 static IdentifierInfo * getDefaultSynthIvarName(ObjCPropertyDecl *Prop,
                                                 ASTContext &Ctx) {
-  llvm::SmallString<128> ivarName;
+  SmallString<128> ivarName;
   {
     llvm::raw_svector_ostream os(ivarName);
     os << '_' << Prop->getIdentifier()->getName();
@@ -1305,7 +1390,13 @@
       if (IMPDecl->getInstanceMethod(Prop->getSetterName()))
         continue;
     }
-
+    if (isa<ObjCProtocolDecl>(Prop->getDeclContext())) {
+      // We won't auto-synthesize properties declared in protocols.
+      Diag(IMPDecl->getLocation(),=20
+           diag::warn_auto_synthesizing_protocol_property);
+      Diag(Prop->getLocation(), diag::note_property_declare);
+      continue;
+    }
=20
     // We use invalid SourceLocations for the synthesized ivars since they
     // aren't really synthesized at a particular location; they just exist.
@@ -1326,7 +1417,8 @@
   if (!IC)
     return;
   if (ObjCInterfaceDecl* IDecl =3D IC->getClassInterface())
-    DefaultSynthesizeProperties(S, IC, IDecl);
+    if (!IDecl->isObjCRequiresPropertyDefs())
+      DefaultSynthesizeProperties(S, IC, IDecl);
 }
=20
 void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
@@ -1363,6 +1455,11 @@
       << Prop->getDeclName() << Prop->getGetterName();
       Diag(Prop->getLocation(),
            diag::note_property_declare);
+      if (LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileAB=
I2)
+        if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(CDecl))
+          if (const ObjCInterfaceDecl *RID =3D ID->isObjCRequiresPropertyD=
efs())
+            Diag(RID->getLocation(), diag::note_suppressed_class_declare);
+           =20
     }
=20
     if (!Prop->isReadOnly() && !InsMap.count(Prop->getSetterName())) {
@@ -1373,6 +1470,10 @@
       << Prop->getDeclName() << Prop->getSetterName();
       Diag(Prop->getLocation(),
            diag::note_property_declare);
+      if (LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileAB=
I2)
+        if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(CDecl))
+          if (const ObjCInterfaceDecl *RID =3D ID->isObjCRequiresPropertyD=
efs())
+            Diag(RID->getLocation(), diag::note_suppressed_class_declare);
     }
   }
 }
@@ -1381,7 +1482,7 @@
 Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl,
                                        ObjCContainerDecl* IDecl) {
   // Rules apply in non-GC mode only
-  if (getLangOptions().getGC() !=3D LangOptions::NonGC)
+  if (getLangOpts().getGC() !=3D LangOptions::NonGC)
     return;
   for (ObjCContainerDecl::prop_iterator I =3D IDecl->prop_begin(),
        E =3D IDecl->prop_end();
@@ -1433,7 +1534,34 @@
         Diag(MethodLoc, diag::warn_atomic_property_rule)
           << Property->getIdentifier() << (GetterMethod !=3D 0)
           << (SetterMethod !=3D 0);
-        Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
+        // fixit stuff.
+        if (!AttributesAsWritten) {
+          if (Property->getLParenLoc().isValid()) {
+            // @property () ... case.
+            SourceRange PropSourceRange(Property->getAtLoc(),=20
+                                        Property->getLParenLoc());
+            Diag(Property->getLocation(), diag::note_atomic_property_fixup=
_suggest) <<
+              FixItHint::CreateReplacement(PropSourceRange, "@property (no=
natomic");
+          }
+          else {
+            //@property id etc.
+            SourceLocation endLoc =3D=20
+              Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
+            endLoc =3D endLoc.getLocWithOffset(-1);
+            SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
+            Diag(Property->getLocation(), diag::note_atomic_property_fixup=
_suggest) <<
+              FixItHint::CreateReplacement(PropSourceRange, "@property (no=
natomic) ");
+          }
+        }
+        else if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic)=
) {
+          // @property () ... case.
+          SourceLocation endLoc =3D Property->getLParenLoc();
+          SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
+          Diag(Property->getLocation(), diag::note_atomic_property_fixup_s=
uggest) <<
+           FixItHint::CreateReplacement(PropSourceRange, "@property (nonat=
omic, ");
+        }
+        else
+          Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
         Diag(Property->getLocation(), diag::note_property_declare);
       }
     }
@@ -1441,7 +1569,7 @@
 }
=20
 void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationD=
ecl *D) {
-  if (getLangOptions().getGC() =3D=3D LangOptions::GCOnly)
+  if (getLangOpts().getGC() =3D=3D LangOptions::GCOnly)
     return;
=20
   for (ObjCImplementationDecl::propimpl_iterator
@@ -1459,7 +1587,7 @@
       ObjCMethodFamily family =3D method->getMethodFamily();
       if (family =3D=3D OMF_alloc || family =3D=3D OMF_copy ||
           family =3D=3D OMF_mutableCopy || family =3D=3D OMF_new) {
-        if (getLangOptions().ObjCAutoRefCount)
+        if (getLangOpts().ObjCAutoRefCount)
           Diag(PID->getLocation(), diag::err_ownin_getter_rule);
         else
           Diag(PID->getLocation(), diag::warn_owning_getter_rule);
@@ -1510,7 +1638,8 @@
       Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
     if (SetterMethod->param_size() !=3D 1 ||
         !Context.hasSameUnqualifiedType(
-          (*SetterMethod->param_begin())->getType(), property->getType()))=
 {
+          (*SetterMethod->param_begin())->getType().getNonReferenceType(),=20
+          property->getType().getNonReferenceType())) {
       Diag(property->getLocation(),
            diag::warn_accessor_property_type_mismatch)
         << property->getDeclName()
@@ -1636,6 +1765,21 @@
   ObjCPropertyDecl *PropertyDecl =3D cast<ObjCPropertyDecl>(PDecl);
   QualType PropertyTy =3D PropertyDecl->getType();=20
=20
+  if (getLangOpts().ObjCAutoRefCount &&
+      (Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
+      PropertyTy->isObjCRetainableType()) {
+    // 'readonly' property with no obvious lifetime.
+    // its life time will be determined by its backing ivar.
+    unsigned rel =3D (ObjCDeclSpec::DQ_PR_unsafe_unretained |
+                    ObjCDeclSpec::DQ_PR_copy |
+                    ObjCDeclSpec::DQ_PR_retain |
+                    ObjCDeclSpec::DQ_PR_strong |
+                    ObjCDeclSpec::DQ_PR_weak |
+                    ObjCDeclSpec::DQ_PR_assign);
+    if ((Attributes & rel) =3D=3D 0)
+      return;
+  }
+ =20
   // readonly and readwrite/assign/retain/copy conflict.
   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
       (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
@@ -1669,6 +1813,7 @@
           Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or str=
ong)");
     Attributes &=3D ~(ObjCDeclSpec::DQ_PR_weak   | ObjCDeclSpec::DQ_PR_cop=
y |
                     ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_stron=
g);
+    PropertyDecl->setInvalidDecl();
   }
=20
   // Check for more than one of { assign, copy, retain }.
@@ -1688,7 +1833,7 @@
         << "assign" << "strong";
       Attributes &=3D ~ObjCDeclSpec::DQ_PR_strong;
     }
-    if (getLangOptions().ObjCAutoRefCount  &&
+    if (getLangOpts().ObjCAutoRefCount  &&
         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
         << "assign" << "weak";
@@ -1710,7 +1855,7 @@
         << "unsafe_unretained" << "strong";
       Attributes &=3D ~ObjCDeclSpec::DQ_PR_strong;
     }
-    if (getLangOptions().ObjCAutoRefCount  &&
+    if (getLangOpts().ObjCAutoRefCount  &&
         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
         << "unsafe_unretained" << "weak";
@@ -1759,20 +1904,28 @@
                       ObjCDeclSpec::DQ_PR_unsafe_unretained |
                       ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_str=
ong |
                       ObjCDeclSpec::DQ_PR_weak)) &&
-      !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
       PropertyTy->isObjCObjectPointerType()) {
-      if (getLangOptions().ObjCAutoRefCount)
+      if (getLangOpts().ObjCAutoRefCount)
         // With arc,  @property definitions should default to (strong) whe=
n=20
-        // not specified
+        // not specified; including when property is 'readonly'.
         PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_stro=
ng);
-      else {
+      else if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly)) {
+        bool isAnyClassTy =3D=20
+          (PropertyTy->isObjCClassType() ||=20
+           PropertyTy->isObjCQualifiedClassType());
+        // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no ne=
ed to
+        // issue any warning.
+        if (isAnyClassTy && getLangOpts().getGC() =3D=3D LangOptions::NonG=
C)
+          ;
+        else {
           // Skip this warning in gc-only mode.
-          if (getLangOptions().getGC() !=3D LangOptions::GCOnly)
+          if (getLangOpts().getGC() !=3D LangOptions::GCOnly)
             Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
=20
           // If non-gc code warn that this is likely inappropriate.
-          if (getLangOptions().getGC() =3D=3D LangOptions::NonGC)
+          if (getLangOpts().getGC() =3D=3D LangOptions::NonGC)
             Diag(Loc, diag::warn_objc_property_default_assign_on_object);
+        }
       }
=20
     // FIXME: Implement warning dependent on NSCopying being
@@ -1783,13 +1936,18 @@
=20
   if (!(Attributes & ObjCDeclSpec::DQ_PR_copy)
       &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly)
-      && getLangOptions().getGC() =3D=3D LangOptions::GCOnly
+      && getLangOpts().getGC() =3D=3D LangOptions::GCOnly
       && PropertyTy->isBlockPointerType())
     Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
-  else if (getLangOptions().ObjCAutoRefCount &&
+  else if (getLangOpts().ObjCAutoRefCount &&
            (Attributes & ObjCDeclSpec::DQ_PR_retain) &&
            !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
            !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
            PropertyTy->isBlockPointerType())
       Diag(Loc, diag::warn_objc_property_retain_of_block);
+ =20
+  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
+      (Attributes & ObjCDeclSpec::DQ_PR_setter))
+    Diag(Loc, diag::warn_objc_readonly_property_has_setter);
+     =20
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaOverload.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaOverload.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -40,7 +40,7 @@
 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidate=
s,
                       SourceLocation Loc =3D SourceLocation(),=20
                       const DeclarationNameLoc &LocInfo =3D DeclarationNam=
eLoc()){
-  DeclRefExpr *DRE =3D new (S.Context) DeclRefExpr(Fn, Fn->getType(),
+  DeclRefExpr *DRE =3D new (S.Context) DeclRefExpr(Fn, false, Fn->getType(=
),
                                                  VK_LValue, Loc, LocInfo);
   if (HadMultipleCandidates)
     DRE->setHadMultipleCandidates(true);
@@ -258,6 +258,172 @@
   return false;
 }
=20
+/// Skip any implicit casts which could be either part of a narrowing conv=
ersion
+/// or after one in an implicit conversion.
+static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
+  while (const ImplicitCastExpr *ICE =3D dyn_cast<ImplicitCastExpr>(Conver=
ted)) {
+    switch (ICE->getCastKind()) {
+    case CK_NoOp:
+    case CK_IntegralCast:
+    case CK_IntegralToBoolean:
+    case CK_IntegralToFloating:
+    case CK_FloatingToIntegral:
+    case CK_FloatingToBoolean:
+    case CK_FloatingCast:
+      Converted =3D ICE->getSubExpr();
+      continue;
+
+    default:
+      return Converted;
+    }
+  }
+
+  return Converted;
+}
+
+/// Check if this standard conversion sequence represents a narrowing
+/// conversion, according to C++11 [dcl.init.list]p7.
+///
+/// \param Ctx  The AST context.
+/// \param Converted  The result of applying this standard conversion sequ=
ence.
+/// \param ConstantValue  If this is an NK_Constant_Narrowing conversion, =
the
+///        value of the expression prior to the narrowing conversion.
+/// \param ConstantType  If this is an NK_Constant_Narrowing conversion, t=
he
+///        type of the expression prior to the narrowing conversion.
+NarrowingKind
+StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
+                                             const Expr *Converted,
+                                             APValue &ConstantValue,
+                                             QualType &ConstantType) const=
 {
+  assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
+
+  // C++11 [dcl.init.list]p7:
+  //   A narrowing conversion is an implicit conversion ...
+  QualType FromType =3D getToType(0);
+  QualType ToType =3D getToType(1);
+  switch (Second) {
+  // -- from a floating-point type to an integer type, or
+  //
+  // -- from an integer type or unscoped enumeration type to a floating-po=
int
+  //    type, except where the source is a constant expression and the act=
ual
+  //    value after conversion will fit into the target type and will prod=
uce
+  //    the original value when converted back to the original type, or
+  case ICK_Floating_Integral:
+    if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
+      return NK_Type_Narrowing;
+    } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType=
()) {
+      llvm::APSInt IntConstantValue;
+      const Expr *Initializer =3D IgnoreNarrowingConversion(Converted);
+      if (Initializer &&
+          Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
+        // Convert the integer to the floating type.
+        llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
+        Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigne=
d(),
+                                llvm::APFloat::rmNearestTiesToEven);
+        // And back.
+        llvm::APSInt ConvertedValue =3D IntConstantValue;
+        bool ignored;
+        Result.convertToInteger(ConvertedValue,
+                                llvm::APFloat::rmTowardZero, &ignored);
+        // If the resulting value is different, this was a narrowing conve=
rsion.
+        if (IntConstantValue !=3D ConvertedValue) {
+          ConstantValue =3D APValue(IntConstantValue);
+          ConstantType =3D Initializer->getType();
+          return NK_Constant_Narrowing;
+        }
+      } else {
+        // Variables are always narrowings.
+        return NK_Variable_Narrowing;
+      }
+    }
+    return NK_Not_Narrowing;
+
+  // -- from long double to double or float, or from double to float, exce=
pt
+  //    where the source is a constant expression and the actual value aft=
er
+  //    conversion is within the range of values that can be represented (=
even
+  //    if it cannot be represented exactly), or
+  case ICK_Floating_Conversion:
+    if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
+        Ctx.getFloatingTypeOrder(FromType, ToType) =3D=3D 1) {
+      // FromType is larger than ToType.
+      const Expr *Initializer =3D IgnoreNarrowingConversion(Converted);
+      if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
+        // Constant!
+        assert(ConstantValue.isFloat());
+        llvm::APFloat FloatVal =3D ConstantValue.getFloat();
+        // Convert the source value into the target type.
+        bool ignored;
+        llvm::APFloat::opStatus ConvertStatus =3D FloatVal.convert(
+          Ctx.getFloatTypeSemantics(ToType),
+          llvm::APFloat::rmNearestTiesToEven, &ignored);
+        // If there was no overflow, the source value is within the range =
of
+        // values that can be represented.
+        if (ConvertStatus & llvm::APFloat::opOverflow) {
+          ConstantType =3D Initializer->getType();
+          return NK_Constant_Narrowing;
+        }
+      } else {
+        return NK_Variable_Narrowing;
+      }
+    }
+    return NK_Not_Narrowing;
+
+  // -- from an integer type or unscoped enumeration type to an integer ty=
pe
+  //    that cannot represent all the values of the original type, except =
where
+  //    the source is a constant expression and the actual value after
+  //    conversion will fit into the target type and will produce the orig=
inal
+  //    value when converted back to the original type.
+  case ICK_Boolean_Conversion:  // Bools are integers too.
+    if (!FromType->isIntegralOrUnscopedEnumerationType()) {
+      // Boolean conversions can be from pointers and pointers to members
+      // [conv.bool], and those aren't considered narrowing conversions.
+      return NK_Not_Narrowing;
+    }  // Otherwise, fall through to the integral case.
+  case ICK_Integral_Conversion: {
+    assert(FromType->isIntegralOrUnscopedEnumerationType());
+    assert(ToType->isIntegralOrUnscopedEnumerationType());
+    const bool FromSigned =3D FromType->isSignedIntegerOrEnumerationType();
+    const unsigned FromWidth =3D Ctx.getIntWidth(FromType);
+    const bool ToSigned =3D ToType->isSignedIntegerOrEnumerationType();
+    const unsigned ToWidth =3D Ctx.getIntWidth(ToType);
+
+    if (FromWidth > ToWidth ||
+        (FromWidth =3D=3D ToWidth && FromSigned !=3D ToSigned)) {
+      // Not all values of FromType can be represented in ToType.
+      llvm::APSInt InitializerValue;
+      const Expr *Initializer =3D IgnoreNarrowingConversion(Converted);
+      if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
+        ConstantValue =3D APValue(InitializerValue);
+
+        // Add a bit to the InitializerValue so we don't have to worry abo=
ut
+        // signed vs. unsigned comparisons.
+        InitializerValue =3D InitializerValue.extend(
+          InitializerValue.getBitWidth() + 1);
+        // Convert the initializer to and from the target width and signed=
-ness.
+        llvm::APSInt ConvertedValue =3D InitializerValue;
+        ConvertedValue =3D ConvertedValue.trunc(ToWidth);
+        ConvertedValue.setIsSigned(ToSigned);
+        ConvertedValue =3D ConvertedValue.extend(InitializerValue.getBitWi=
dth());
+        ConvertedValue.setIsSigned(InitializerValue.isSigned());
+        // If the result is different, this was a narrowing conversion.
+        if (ConvertedValue !=3D InitializerValue) {
+          ConstantType =3D Initializer->getType();
+          return NK_Constant_Narrowing;
+        }
+      } else {
+        // Variables are always narrowings.
+        return NK_Variable_Narrowing;
+      }
+    }
+    return NK_Not_Narrowing;
+  }
+
+  default:
+    // Other kinds of conversions are not narrowings.
+    return NK_Not_Narrowing;
+  }
+}
+
 /// DebugPrint - Print this standard conversion sequence to standard
 /// error. Useful for debugging overloading issues.
 void StandardConversionSequence::DebugPrint() const {
@@ -305,7 +471,10 @@
     Before.DebugPrint();
     OS << " -> ";
   }
-  OS << '\'' << *ConversionFunction << '\'';
+  if (ConversionFunction)
+    OS << '\'' << *ConversionFunction << '\'';
+  else
+    OS << "aggregate initialization";
   if (After.First || After.Second || After.Third) {
     OS << " -> ";
     After.DebugPrint();
@@ -538,10 +707,85 @@
 }
=20
 void OverloadCandidateSet::clear() {
-  inherited::clear();
+  for (iterator i =3D begin(), e =3D end(); i !=3D e; ++i)
+    for (unsigned ii =3D 0, ie =3D i->NumConversions; ii !=3D ie; ++ii)
+      i->Conversions[ii].~ImplicitConversionSequence();
+  NumInlineSequences =3D 0;
+  Candidates.clear();
   Functions.clear();
 }
=20
+namespace {
+  class UnbridgedCastsSet {
+    struct Entry {
+      Expr **Addr;
+      Expr *Saved;
+    };
+    SmallVector<Entry, 2> Entries;
+   =20
+  public:
+    void save(Sema &S, Expr *&E) {
+      assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
+      Entry entry =3D { &E, E };
+      Entries.push_back(entry);
+      E =3D S.stripARCUnbridgedCast(E);
+    }
+
+    void restore() {
+      for (SmallVectorImpl<Entry>::iterator
+             i =3D Entries.begin(), e =3D Entries.end(); i !=3D e; ++i)=20
+        *i->Addr =3D i->Saved;
+    }
+  };
+}
+
+/// checkPlaceholderForOverload - Do any interesting placeholder-like
+/// preprocessing on the given expression.
+///
+/// \param unbridgedCasts a collection to which to add unbridged casts;
+///   without this, they will be immediately diagnosed as errors
+///
+/// Return true on unrecoverable error.
+static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
+                                        UnbridgedCastsSet *unbridgedCasts =
=3D 0) {
+  if (const BuiltinType *placeholder =3D  E->getType()->getAsPlaceholderTy=
pe()) {
+    // We can't handle overloaded expressions here because overload
+    // resolution might reasonably tweak them.
+    if (placeholder->getKind() =3D=3D BuiltinType::Overload) return false;
+
+    // If the context potentially accepts unbridged ARC casts, strip
+    // the unbridged cast and add it to the collection for later restorati=
on.
+    if (placeholder->getKind() =3D=3D BuiltinType::ARCUnbridgedCast &&
+        unbridgedCasts) {
+      unbridgedCasts->save(S, E);
+      return false;
+    }
+
+    // Go ahead and check everything else.
+    ExprResult result =3D S.CheckPlaceholderExpr(E);
+    if (result.isInvalid())
+      return true;
+
+    E =3D result.take();
+    return false;
+  }
+
+  // Nothing to do.
+  return false;
+}
+
+/// checkArgPlaceholdersForOverload - Check a set of call operands for
+/// placeholders.
+static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
+                                            unsigned numArgs,
+                                            UnbridgedCastsSet &unbridged) {
+  for (unsigned i =3D 0; i !=3D numArgs; ++i)
+    if (checkPlaceholderForOverload(S, args[i], &unbridged))
+      return true;
+
+  return false;
+}
+
 // IsOverload - Determine whether the given New declaration is an
 // overload of the declarations in Old. This routine returns false if
 // New and Old cannot be overloaded, e.g., if New has the same
@@ -750,6 +994,86 @@
   return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
 }
=20
+/// \brief Tries a user-defined conversion from From to ToType.
+///
+/// Produces an implicit conversion sequence for when a standard conversion
+/// is not an option. See TryImplicitConversion for more information.
+static ImplicitConversionSequence
+TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
+                         bool SuppressUserConversions,
+                         bool AllowExplicit,
+                         bool InOverloadResolution,
+                         bool CStyle,
+                         bool AllowObjCWritebackConversion) {
+  ImplicitConversionSequence ICS;
+
+  if (SuppressUserConversions) {
+    // We're not in the case above, so there is no conversion that
+    // we can perform.
+    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
+    return ICS;
+  }
+
+  // Attempt user-defined conversion.
+  OverloadCandidateSet Conversions(From->getExprLoc());
+  OverloadingResult UserDefResult
+    =3D IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversi=
ons,
+                              AllowExplicit);
+
+  if (UserDefResult =3D=3D OR_Success) {
+    ICS.setUserDefined();
+    // C++ [over.ics.user]p4:
+    //   A conversion of an expression of class type to the same class
+    //   type is given Exact Match rank, and a conversion of an
+    //   expression of class type to a base class of that type is
+    //   given Conversion rank, in spite of the fact that a copy
+    //   constructor (i.e., a user-defined conversion function) is
+    //   called for those cases.
+    if (CXXConstructorDecl *Constructor
+          =3D dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunct=
ion)) {
+      QualType FromCanon
+        =3D S.Context.getCanonicalType(From->getType().getUnqualifiedType(=
));
+      QualType ToCanon
+        =3D S.Context.getCanonicalType(ToType).getUnqualifiedType();
+      if (Constructor->isCopyConstructor() &&
+          (FromCanon =3D=3D ToCanon || S.IsDerivedFrom(FromCanon, ToCanon)=
)) {
+        // Turn this into a "standard" conversion sequence, so that it
+        // gets ranked with standard conversion sequences.
+        ICS.setStandard();
+        ICS.Standard.setAsIdentityConversion();
+        ICS.Standard.setFromType(From->getType());
+        ICS.Standard.setAllToTypes(ToType);
+        ICS.Standard.CopyConstructor =3D Constructor;
+        if (ToCanon !=3D FromCanon)
+          ICS.Standard.Second =3D ICK_Derived_To_Base;
+      }
+    }
+
+    // C++ [over.best.ics]p4:
+    //   However, when considering the argument of a user-defined
+    //   conversion function that is a candidate by 13.3.1.3 when
+    //   invoked for the copying of the temporary in the second step
+    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
+    //   13.3.1.6 in all cases, only standard conversion sequences and
+    //   ellipsis conversion sequences are allowed.
+    if (SuppressUserConversions && ICS.isUserDefined()) {
+      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
+    }
+  } else if (UserDefResult =3D=3D OR_Ambiguous && !SuppressUserConversions=
) {
+    ICS.setAmbiguous();
+    ICS.Ambiguous.setFromType(From->getType());
+    ICS.Ambiguous.setToType(ToType);
+    for (OverloadCandidateSet::iterator Cand =3D Conversions.begin();
+         Cand !=3D Conversions.end(); ++Cand)
+      if (Cand->Viable)
+        ICS.Ambiguous.addConversion(Cand->Function);
+  } else {
+    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
+  }
+
+  return ICS;
+}
+
 /// TryImplicitConversion - Attempt to perform an implicit conversion
 /// from the given expression (Expr) to the given type (ToType). This
 /// function returns an implicit conversion sequence that can be used
@@ -791,7 +1115,7 @@
     return ICS;
   }
=20
-  if (!S.getLangOptions().CPlusPlus) {
+  if (!S.getLangOpts().CPlusPlus) {
     ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
     return ICS;
   }
@@ -825,71 +1149,9 @@
     return ICS;
   }
=20
-  if (SuppressUserConversions) {
-    // We're not in the case above, so there is no conversion that
-    // we can perform.
-    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
-    return ICS;
-  }
-
-  // Attempt user-defined conversion.
-  OverloadCandidateSet Conversions(From->getExprLoc());
-  OverloadingResult UserDefResult
-    =3D IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversi=
ons,
-                              AllowExplicit);
-
-  if (UserDefResult =3D=3D OR_Success) {
-    ICS.setUserDefined();
-    // C++ [over.ics.user]p4:
-    //   A conversion of an expression of class type to the same class
-    //   type is given Exact Match rank, and a conversion of an
-    //   expression of class type to a base class of that type is
-    //   given Conversion rank, in spite of the fact that a copy
-    //   constructor (i.e., a user-defined conversion function) is
-    //   called for those cases.
-    if (CXXConstructorDecl *Constructor
-          =3D dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunct=
ion)) {
-      QualType FromCanon
-        =3D S.Context.getCanonicalType(From->getType().getUnqualifiedType(=
));
-      QualType ToCanon
-        =3D S.Context.getCanonicalType(ToType).getUnqualifiedType();
-      if (Constructor->isCopyConstructor() &&
-          (FromCanon =3D=3D ToCanon || S.IsDerivedFrom(FromCanon, ToCanon)=
)) {
-        // Turn this into a "standard" conversion sequence, so that it
-        // gets ranked with standard conversion sequences.
-        ICS.setStandard();
-        ICS.Standard.setAsIdentityConversion();
-        ICS.Standard.setFromType(From->getType());
-        ICS.Standard.setAllToTypes(ToType);
-        ICS.Standard.CopyConstructor =3D Constructor;
-        if (ToCanon !=3D FromCanon)
-          ICS.Standard.Second =3D ICK_Derived_To_Base;
-      }
-    }
-
-    // C++ [over.best.ics]p4:
-    //   However, when considering the argument of a user-defined
-    //   conversion function that is a candidate by 13.3.1.3 when
-    //   invoked for the copying of the temporary in the second step
-    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
-    //   13.3.1.6 in all cases, only standard conversion sequences and
-    //   ellipsis conversion sequences are allowed.
-    if (SuppressUserConversions && ICS.isUserDefined()) {
-      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
-    }
-  } else if (UserDefResult =3D=3D OR_Ambiguous && !SuppressUserConversions=
) {
-    ICS.setAmbiguous();
-    ICS.Ambiguous.setFromType(From->getType());
-    ICS.Ambiguous.setToType(ToType);
-    for (OverloadCandidateSet::iterator Cand =3D Conversions.begin();
-         Cand !=3D Conversions.end(); ++Cand)
-      if (Cand->Viable)
-        ICS.Ambiguous.addConversion(Cand->Function);
-  } else {
-    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
-  }
-
-  return ICS;
+  return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
+                                  AllowExplicit, InOverloadResolution, CSt=
yle,
+                                  AllowObjCWritebackConversion);
 }
=20
 ImplicitConversionSequence
@@ -912,21 +1174,21 @@
 /// explicit user-defined conversions are permitted.
 ExprResult
 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
-                                AssignmentAction Action, bool AllowExplici=
t,
-                                bool Diagnose) {
+                                AssignmentAction Action, bool AllowExplici=
t) {
   ImplicitConversionSequence ICS;
-  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, IC=
S,
-                                   Diagnose);
+  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, IC=
S);
 }
=20
 ExprResult
 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
                                 AssignmentAction Action, bool AllowExplici=
t,
-                                ImplicitConversionSequence& ICS,
-                                bool Diagnose) {
+                                ImplicitConversionSequence& ICS) {
+  if (checkPlaceholderForOverload(*this, From))
+    return ExprError();
+
   // Objective-C ARC: Determine whether we will allow the writeback conver=
sion.
   bool AllowObjCWritebackConversion
-    =3D getLangOptions().ObjCAutoRefCount &&=20
+    =3D getLangOpts().ObjCAutoRefCount &&=20
       (Action =3D=3D AA_Passing || Action =3D=3D AA_Sending);
=20
   ICS =3D clang::TryImplicitConversion(*this, From, ToType,
@@ -935,8 +1197,6 @@
                                      /*InOverloadResolution=3D*/false,
                                      /*CStyle=3D*/false,
                                      AllowObjCWritebackConversion);
-  if (!Diagnose && ICS.isFailure())
-    return ExprError();
   return PerformImplicitConversion(From, ToType, ICS, Action);
 }
=20
@@ -1024,7 +1284,7 @@
   //   same size
   if (ToType->isVectorType() && FromType->isVectorType()) {
     if (Context.areCompatibleVectorTypes(FromType, ToType) ||
-        (Context.getLangOptions().LaxVectorConversions &&
+        (Context.getLangOpts().LaxVectorConversions &&
          (Context.getTypeSize(FromType) =3D=3D Context.getTypeSize(ToType)=
))) {
       ICK =3D ICK_Vector_Conversion;
       return true;
@@ -1034,6 +1294,11 @@
   return false;
 }
=20
+static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
+                                bool InOverloadResolution,
+                                StandardConversionSequence &SCS,
+                                bool CStyle);
+ =20
 /// IsStandardConversion - Determines whether there is a standard
 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
 /// expression From to the type ToType. Standard conversion sequences
@@ -1059,7 +1324,7 @@
   // There are no standard conversions for class types in C++, so
   // abort early. When overloading in C, however, we do permit
   if (FromType->isRecordType() || ToType->isRecordType()) {
-    if (S.getLangOptions().CPlusPlus)
+    if (S.getLangOpts().CPlusPlus)
       return false;
=20
     // When we're overloading in C, we allow, as standard conversions,
@@ -1129,6 +1394,12 @@
       S.Context.getCanonicalType(FromType) !=3D S.Context.OverloadTy) {
     SCS.First =3D ICK_Lvalue_To_Rvalue;
=20
+    // C11 6.3.2.1p2:
+    //   ... if the lvalue has atomic type, the value has the non-atomic v=
ersion=20
+    //   of the type of the lvalue ...
+    if (const AtomicType *Atomic =3D FromType->getAs<AtomicType>())
+      FromType =3D Atomic->getValueType();
+
     // If T is a non-class type, the type of the rvalue is the
     // cv-unqualified version of T. Otherwise, the type of the rvalue
     // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
@@ -1247,7 +1518,7 @@
   } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
     SCS.Second =3D SecondICK;
     FromType =3D ToType.getUnqualifiedType();
-  } else if (!S.getLangOptions().CPlusPlus &&
+  } else if (!S.getLangOpts().CPlusPlus &&
              S.Context.typesAreCompatible(ToType, FromType)) {
     // Compatible conversions (Clang extension for C function overloading)
     SCS.Second =3D ICK_Compatible_Conversion;
@@ -1260,6 +1531,11 @@
                                              SCS, CStyle)) {
     SCS.Second =3D ICK_TransparentUnionConversion;
     FromType =3D ToType;
+  } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SC=
S,
+                                 CStyle)) {
+    // tryAtomicConversion has updated the standard conversion sequence
+    // appropriately.
+    return true;
   } else {
     // No second conversion required.
     SCS.Second =3D ICK_Identity;
@@ -1480,7 +1756,7 @@
       // C99 6.3.1.5p1:
       //   When a float is promoted to double or long double, or a
       //   double is promoted to long double [...].
-      if (!getLangOptions().CPlusPlus &&
+      if (!getLangOpts().CPlusPlus &&
           (FromBuiltin->getKind() =3D=3D BuiltinType::Float ||
            FromBuiltin->getKind() =3D=3D BuiltinType::Double) &&
           (ToBuiltin->getKind() =3D=3D BuiltinType::LongDouble))
@@ -1646,7 +1922,7 @@
   // , including objective-c pointers.
   QualType ToPointeeType =3D ToTypePtr->getPointeeType();
   if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
-      !getLangOptions().ObjCAutoRefCount) {
+      !getLangOpts().ObjCAutoRefCount) {
     ConvertedType =3D BuildSimilarlyQualifiedPointerType(
                                       FromType->getAs<ObjCObjectPointerTyp=
e>(),
                                                        ToPointeeType,
@@ -1677,7 +1953,7 @@
   }
=20
   // MSVC allows implicit function to void* type conversion.
-  if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
+  if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
       ToPointeeType->isVoidType()) {
     ConvertedType =3D BuildSimilarlyQualifiedPointerType(FromTypePtr,
                                                        ToPointeeType,
@@ -1687,7 +1963,7 @@
=20
   // When we're overloading in C, we allow a special kind of pointer
   // conversion for compatible-but-not-identical pointee types.
-  if (!getLangOptions().CPlusPlus &&
+  if (!getLangOpts().CPlusPlus &&
       Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
     ConvertedType =3D BuildSimilarlyQualifiedPointerType(FromTypePtr,
                                                        ToPointeeType,
@@ -1708,7 +1984,7 @@
   //
   // Note that we do not check for ambiguity or inaccessibility
   // here. That is handled by CheckPointerConversion.
-  if (getLangOptions().CPlusPlus &&
+  if (getLangOpts().CPlusPlus &&
       FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
       !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
       !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) =
&&
@@ -1750,7 +2026,7 @@
 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
                                    QualType& ConvertedType,
                                    bool &IncompatibleObjC) {
-  if (!getLangOptions().ObjC1)
+  if (!getLangOpts().ObjC1)
     return false;
=20
   // The set of qualifiers on the type we're converting from.
@@ -1789,7 +2065,7 @@
     if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
       const ObjCInterfaceType* LHS =3D ToObjCPtr->getInterfaceType();
       const ObjCInterfaceType* RHS =3D FromObjCPtr->getInterfaceType();
-      if (getLangOptions().CPlusPlus && LHS && RHS &&
+      if (getLangOpts().CPlusPlus && LHS && RHS &&
           !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
                                                 FromObjCPtr->getPointeeTyp=
e()))
         return false;
@@ -1945,7 +2221,7 @@
 /// this conversion.
 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
                                      QualType &ConvertedType) {
-  if (!getLangOptions().ObjCAutoRefCount ||=20
+  if (!getLangOpts().ObjCAutoRefCount ||=20
       Context.hasSameUnqualifiedType(FromType, ToType))
     return false;
  =20
@@ -1959,7 +2235,7 @@
   Qualifiers ToQuals =3D ToPointee.getQualifiers();
   if (!ToPointee->isObjCLifetimeType() ||=20
       ToQuals.getObjCLifetime() !=3D Qualifiers::OCL_Autoreleasing ||
-      !ToQuals.withoutObjCGLifetime().empty())
+      !ToQuals.withoutObjCLifetime().empty())
     return false;
  =20
   // Argument must be a pointer to __strong to __weak.
@@ -2049,7 +2325,7 @@
   } else {
     QualType RHS =3D FromFunctionType->getResultType();
     QualType LHS =3D ToFunctionType->getResultType();
-    if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
+    if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
         !RHS.hasQualifiers() && LHS.hasQualifiers())
        LHS =3D LHS.getUnqualifiedType();
=20
@@ -2091,22 +2367,131 @@
    return true;
 }
=20
+enum {
+  ft_default,
+  ft_different_class,
+  ft_parameter_arity,
+  ft_parameter_mismatch,
+  ft_return_type,
+  ft_qualifer_mismatch
+};
+
+/// HandleFunctionTypeMismatch - Gives diagnostic information for differei=
ng
+/// function types.  Catches different number of parameter, mismatch in
+/// parameter types, and different return types.
+void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
+                                      QualType FromType, QualType ToType) {
+  // If either type is not valid, include no extra info.
+  if (FromType.isNull() || ToType.isNull()) {
+    PDiag << ft_default;
+    return;
+  }
+
+  // Get the function type from the pointers.
+  if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
+    const MemberPointerType *FromMember =3D FromType->getAs<MemberPointerT=
ype>(),
+                            *ToMember =3D ToType->getAs<MemberPointerType>=
();
+    if (FromMember->getClass() !=3D ToMember->getClass()) {
+      PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
+            << QualType(FromMember->getClass(), 0);
+      return;
+    }
+    FromType =3D FromMember->getPointeeType();
+    ToType =3D ToMember->getPointeeType();
+  }
+
+  if (FromType->isPointerType())
+    FromType =3D FromType->getPointeeType();
+  if (ToType->isPointerType())
+    ToType =3D ToType->getPointeeType();
+
+  // Remove references.
+  FromType =3D FromType.getNonReferenceType();
+  ToType =3D ToType.getNonReferenceType();
+
+  // Don't print extra info for non-specialized template functions.
+  if (FromType->isInstantiationDependentType() &&
+      !FromType->getAs<TemplateSpecializationType>()) {
+    PDiag << ft_default;
+    return;
+  }
+
+  // No extra info for same types.
+  if (Context.hasSameType(FromType, ToType)) {
+    PDiag << ft_default;
+    return;
+  }
+
+  const FunctionProtoType *FromFunction =3D FromType->getAs<FunctionProtoT=
ype>(),
+                          *ToFunction =3D ToType->getAs<FunctionProtoType>=
();
+
+  // Both types need to be function types.
+  if (!FromFunction || !ToFunction) {
+    PDiag << ft_default;
+    return;
+  }
+
+  if (FromFunction->getNumArgs() !=3D ToFunction->getNumArgs()) {
+    PDiag << ft_parameter_arity << ToFunction->getNumArgs()
+          << FromFunction->getNumArgs();
+    return;
+  }
+
+  // Handle different parameter types.
+  unsigned ArgPos;
+  if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
+    PDiag << ft_parameter_mismatch << ArgPos + 1
+          << ToFunction->getArgType(ArgPos)
+          << FromFunction->getArgType(ArgPos);
+    return;
+  }
+
+  // Handle different return type.
+  if (!Context.hasSameType(FromFunction->getResultType(),
+                           ToFunction->getResultType())) {
+    PDiag << ft_return_type << ToFunction->getResultType()
+          << FromFunction->getResultType();
+    return;
+  }
+
+  unsigned FromQuals =3D FromFunction->getTypeQuals(),
+           ToQuals =3D ToFunction->getTypeQuals();
+  if (FromQuals !=3D ToQuals) {
+    PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
+    return;
+  }
+
+  // Unable to find a difference, so add no extra info.
+  PDiag << ft_default;
+}
+
 /// FunctionArgTypesAreEqual - This routine checks two function proto types
-/// for equlity of their argument types. Caller has already checked that
+/// for equality of their argument types. Caller has already checked that
 /// they have same number of arguments. This routine assumes that Objectiv=
e-C
 /// pointer types which only differ in their protocol qualifiers are equal.
+/// If the parameters are different, ArgPos will have the the parameter in=
dex
+/// of the first different parameter.
 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
-                                    const FunctionProtoType *NewType) {
-  if (!getLangOptions().ObjC1)
-    return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
-                      NewType->arg_type_begin());
+                                    const FunctionProtoType *NewType,
+                                    unsigned *ArgPos) {
+  if (!getLangOpts().ObjC1) {
+    for (FunctionProtoType::arg_type_iterator O =3D OldType->arg_type_begi=
n(),
+         N =3D NewType->arg_type_begin(),
+         E =3D OldType->arg_type_end(); O && (O !=3D E); ++O, ++N) {
+      if (!Context.hasSameType(*O, *N)) {
+        if (ArgPos) *ArgPos =3D O - OldType->arg_type_begin();
+        return false;
+      }
+    }
+    return true;
+  }
=20
   for (FunctionProtoType::arg_type_iterator O =3D OldType->arg_type_begin(=
),
        N =3D NewType->arg_type_begin(),
        E =3D OldType->arg_type_end(); O && (O !=3D E); ++O, ++N) {
     QualType ToType =3D (*O);
     QualType FromType =3D (*N);
-    if (ToType !=3D FromType) {
+    if (!Context.hasSameType(ToType, FromType)) {
       if (const PointerType *PTTo =3D ToType->getAs<PointerType>()) {
         if (const PointerType *PTFr =3D FromType->getAs<PointerType>())
           if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
@@ -2119,9 +2504,12 @@
                  ToType->getAs<ObjCObjectPointerType>()) {
         if (const ObjCObjectPointerType *PTFr =3D
               FromType->getAs<ObjCObjectPointerType>())
-          if (PTTo->getInterfaceDecl() =3D=3D PTFr->getInterfaceDecl())
+          if (Context.hasSameUnqualifiedType(
+                PTTo->getObjectType()->getBaseType(),
+                PTFr->getObjectType()->getBaseType()))
             continue;
       }
+      if (ArgPos) *ArgPos =3D O - OldType->arg_type_begin();
       return false;
     }
   }
@@ -2386,6 +2774,121 @@
   return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,To=
Type);
 }
=20
+/// \brief - Determine whether this is a conversion from a scalar type to =
an
+/// atomic type.
+///
+/// If successful, updates \c SCS's second and third steps in the conversi=
on
+/// sequence to finish the conversion.
+static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
+                                bool InOverloadResolution,
+                                StandardConversionSequence &SCS,
+                                bool CStyle) {
+  const AtomicType *ToAtomic =3D ToType->getAs<AtomicType>();
+  if (!ToAtomic)
+    return false;
+ =20
+  StandardConversionSequence InnerSCS;
+  if (!IsStandardConversion(S, From, ToAtomic->getValueType(),=20
+                            InOverloadResolution, InnerSCS,
+                            CStyle, /*AllowObjCWritebackConversion=3D*/fal=
se))
+    return false;
+ =20
+  SCS.Second =3D InnerSCS.Second;
+  SCS.setToType(1, InnerSCS.getToType(1));
+  SCS.Third =3D InnerSCS.Third;
+  SCS.QualificationIncludesObjCLifetime
+    =3D InnerSCS.QualificationIncludesObjCLifetime;
+  SCS.setToType(2, InnerSCS.getToType(2));
+  return true;
+}
+
+static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
+                                              CXXConstructorDecl *Construc=
tor,
+                                              QualType Type) {
+  const FunctionProtoType *CtorType =3D
+      Constructor->getType()->getAs<FunctionProtoType>();
+  if (CtorType->getNumArgs() > 0) {
+    QualType FirstArg =3D CtorType->getArgType(0);
+    if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType(=
)))
+      return true;
+  }
+  return false;
+}
+
+static OverloadingResult
+IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToTyp=
e,
+                                       CXXRecordDecl *To,
+                                       UserDefinedConversionSequence &User,
+                                       OverloadCandidateSet &CandidateSet,
+                                       bool AllowExplicit) {
+  DeclContext::lookup_iterator Con, ConEnd;
+  for (llvm::tie(Con, ConEnd) =3D S.LookupConstructors(To);
+       Con !=3D ConEnd; ++Con) {
+    NamedDecl *D =3D *Con;
+    DeclAccessPair FoundDecl =3D DeclAccessPair::make(D, D->getAccess());
+
+    // Find the constructor (which may be a template).
+    CXXConstructorDecl *Constructor =3D 0;
+    FunctionTemplateDecl *ConstructorTmpl
+      =3D dyn_cast<FunctionTemplateDecl>(D);
+    if (ConstructorTmpl)
+      Constructor
+        =3D cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
+    else
+      Constructor =3D cast<CXXConstructorDecl>(D);
+
+    bool Usable =3D !Constructor->isInvalidDecl() &&
+                  S.isInitListConstructor(Constructor) &&
+                  (AllowExplicit || !Constructor->isExplicit());
+    if (Usable) {
+      // If the first argument is (a reference to) the target type,
+      // suppress conversions.
+      bool SuppressUserConversions =3D
+          isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType=
);
+      if (ConstructorTmpl)
+        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
+                                       /*ExplicitArgs*/ 0,
+                                       From, CandidateSet,
+                                       SuppressUserConversions);
+      else
+        S.AddOverloadCandidate(Constructor, FoundDecl,
+                               From, CandidateSet,
+                               SuppressUserConversions);
+    }
+  }
+
+  bool HadMultipleCandidates =3D (CandidateSet.size() > 1);
+
+  OverloadCandidateSet::iterator Best;
+  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, tr=
ue)) {
+  case OR_Success: {
+    // Record the standard conversion we used and the conversion function.
+    CXXConstructorDecl *Constructor =3D cast<CXXConstructorDecl>(Best->Fun=
ction);
+    S.MarkFunctionReferenced(From->getLocStart(), Constructor);
+
+    QualType ThisType =3D Constructor->getThisType(S.Context);
+    // Initializer lists don't have conversions as such.
+    User.Before.setAsIdentityConversion();
+    User.HadMultipleCandidates =3D HadMultipleCandidates;
+    User.ConversionFunction =3D Constructor;
+    User.FoundConversionFunction =3D Best->FoundDecl;
+    User.After.setAsIdentityConversion();
+    User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType(=
));
+    User.After.setAllToTypes(ToType);
+    return OR_Success;
+  }
+
+  case OR_No_Viable_Function:
+    return OR_No_Viable_Function;
+  case OR_Deleted:
+    return OR_Deleted;
+  case OR_Ambiguous:
+    return OR_Ambiguous;
+  }
+
+  llvm_unreachable("Invalid OverloadResult!");
+}
+
 /// Determines whether there is a user-defined conversion sequence
 /// (C++ [over.ics.user]) that converts expression From to the type
 /// ToType. If such a conversion exists, User will contain the
@@ -2398,8 +2901,8 @@
 /// functions (C++0x [class.conv.fct]p2).
 static OverloadingResult
 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
-                        UserDefinedConversionSequence& User,
-                        OverloadCandidateSet& CandidateSet,
+                        UserDefinedConversionSequence &User,
+                        OverloadCandidateSet &CandidateSet,
                         bool AllowExplicit) {
   // Whether we will only visit constructors.
   bool ConstructorsOnly =3D false;
@@ -2428,6 +2931,26 @@
       // We're not going to find any constructors.
     } else if (CXXRecordDecl *ToRecordDecl
                  =3D dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
+
+      Expr **Args =3D &From;
+      unsigned NumArgs =3D 1;
+      bool ListInitializing =3D false;
+      if (InitListExpr *InitList =3D dyn_cast<InitListExpr>(From)) {
+        // But first, see if there is an init-list-contructor that will wo=
rk.
+        OverloadingResult Result =3D IsInitializerListConstructorConversio=
n(
+            S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplic=
it);
+        if (Result !=3D OR_No_Viable_Function)
+          return Result;
+        // Never mind.
+        CandidateSet.clear();
+
+        // If we're list-initializing, we pass the individual elements as
+        // arguments, not the entire list.
+        Args =3D InitList->getInits();
+        NumArgs =3D InitList->getNumInits();
+        ListInitializing =3D true;
+      }
+
       DeclContext::lookup_iterator Con, ConEnd;
       for (llvm::tie(Con, ConEnd) =3D S.LookupConstructors(ToRecordDecl);
            Con !=3D ConEnd; ++Con) {
@@ -2444,28 +2967,40 @@
         else
           Constructor =3D cast<CXXConstructorDecl>(D);
=20
-        if (!Constructor->isInvalidDecl() &&
-            Constructor->isConvertingConstructor(AllowExplicit)) {
+        bool Usable =3D !Constructor->isInvalidDecl();
+        if (ListInitializing)
+          Usable =3D Usable && (AllowExplicit || !Constructor->isExplicit(=
));
+        else
+          Usable =3D Usable &&Constructor->isConvertingConstructor(AllowEx=
plicit);
+        if (Usable) {
+          bool SuppressUserConversions =3D !ConstructorsOnly;
+          if (SuppressUserConversions && ListInitializing) {
+            SuppressUserConversions =3D false;
+            if (NumArgs =3D=3D 1) {
+              // If the first argument is (a reference to) the target type,
+              // suppress conversions.
+              SuppressUserConversions =3D isFirstArgumentCompatibleWithTyp=
e(
+                                                S.Context, Constructor, To=
Type);
+            }
+          }
           if (ConstructorTmpl)
             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
                                            /*ExplicitArgs*/ 0,
-                                           &From, 1, CandidateSet,
-                                           /*SuppressUserConversions=3D*/
-                                             !ConstructorsOnly);
+                                           llvm::makeArrayRef(Args, NumArg=
s),
+                                           CandidateSet, SuppressUserConve=
rsions);
           else
             // Allow one user-defined conversion when user specifies a
             // From->ToType conversion via an static cast (c-style, etc).
             S.AddOverloadCandidate(Constructor, FoundDecl,
-                                   &From, 1, CandidateSet,
-                                   /*SuppressUserConversions=3D*/
-                                     !ConstructorsOnly);
+                                   llvm::makeArrayRef(Args, NumArgs),
+                                   CandidateSet, SuppressUserConversions);
         }
       }
     }
   }
=20
   // Enumerate conversion functions, if we're allowed to.
-  if (ConstructorsOnly) {
+  if (ConstructorsOnly || isa<InitListExpr>(From)) {
   } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
                                    S.PDiag(0) << From->getSourceRange())) {
     // No conversion functions from incomplete types.
@@ -2512,7 +3047,7 @@
     // Record the standard conversion we used and the conversion function.
     if (CXXConstructorDecl *Constructor
           =3D dyn_cast<CXXConstructorDecl>(Best->Function)) {
-      S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
+      S.MarkFunctionReferenced(From->getLocStart(), Constructor);
=20
       // C++ [over.ics.user]p1:
       //   If the user-defined conversion is specified by a
@@ -2521,11 +3056,16 @@
       //   the argument of the constructor.
       //
       QualType ThisType =3D Constructor->getThisType(S.Context);
-      if (Best->Conversions[0].isEllipsis())
-        User.EllipsisConversion =3D true;
-      else {
-        User.Before =3D Best->Conversions[0].Standard;
-        User.EllipsisConversion =3D false;
+      if (isa<InitListExpr>(From)) {
+        // Initializer lists don't have conversions as such.
+        User.Before.setAsIdentityConversion();
+      } else {
+        if (Best->Conversions[0].isEllipsis())
+          User.EllipsisConversion =3D true;
+        else {
+          User.Before =3D Best->Conversions[0].Standard;
+          User.EllipsisConversion =3D false;
+        }
       }
       User.HadMultipleCandidates =3D HadMultipleCandidates;
       User.ConversionFunction =3D Constructor;
@@ -2534,9 +3074,10 @@
       User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeTyp=
e());
       User.After.setAllToTypes(ToType);
       return OR_Success;
-    } else if (CXXConversionDecl *Conversion
+    }
+    if (CXXConversionDecl *Conversion
                  =3D dyn_cast<CXXConversionDecl>(Best->Function)) {
-      S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
+      S.MarkFunctionReferenced(From->getLocStart(), Conversion);
=20
       // C++ [over.ics.user]p1:
       //
@@ -2561,10 +3102,8 @@
       //   13.3.3.1).
       User.After =3D Best->FinalConversion;
       return OR_Success;
-    } else {
-      llvm_unreachable("Not a constructor or conversion function?");
-      return OR_No_Viable_Function;
-    }
+    }
+    llvm_unreachable("Not a constructor or conversion function?");
=20
   case OR_No_Viable_Function:
     return OR_No_Viable_Function;
@@ -2576,7 +3115,7 @@
     return OR_Ambiguous;
   }
=20
-  return OR_No_Viable_Function;
+  llvm_unreachable("Invalid OverloadResult!");
 }
=20
 bool
@@ -2587,19 +3126,54 @@
     IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
                             CandidateSet, false);
   if (OvResult =3D=3D OR_Ambiguous)
-    Diag(From->getSourceRange().getBegin(),
+    Diag(From->getLocStart(),
          diag::err_typecheck_ambiguous_condition)
           << From->getType() << ToType << From->getSourceRange();
   else if (OvResult =3D=3D OR_No_Viable_Function && !CandidateSet.empty())
-    Diag(From->getSourceRange().getBegin(),
+    Diag(From->getLocStart(),
          diag::err_typecheck_nonviable_condition)
     << From->getType() << ToType << From->getSourceRange();
   else
     return false;
-  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
+  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
   return true;
 }
=20
+/// \brief Compare the user-defined conversion functions or constructors
+/// of two user-defined conversion sequences to determine whether any orde=
ring
+/// is possible.
+static ImplicitConversionSequence::CompareKind
+compareConversionFunctions(Sema &S,
+                           FunctionDecl *Function1,
+                           FunctionDecl *Function2) {
+  if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
+    return ImplicitConversionSequence::Indistinguishable;
+ =20
+  // Objective-C++:
+  //   If both conversion functions are implicitly-declared conversions fr=
om
+  //   a lambda closure type to a function pointer and a block pointer,=20
+  //   respectively, always prefer the conversion to a function pointer,
+  //   because the function pointer is more lightweight and is more likely
+  //   to keep code working.
+  CXXConversionDecl *Conv1 =3D dyn_cast<CXXConversionDecl>(Function1);
+  if (!Conv1)
+    return ImplicitConversionSequence::Indistinguishable;
+   =20
+  CXXConversionDecl *Conv2 =3D dyn_cast<CXXConversionDecl>(Function2);
+  if (!Conv2)
+    return ImplicitConversionSequence::Indistinguishable;
+ =20
+  if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
+    bool Block1 =3D Conv1->getConversionType()->isBlockPointerType();
+    bool Block2 =3D Conv2->getConversionType()->isBlockPointerType();
+    if (Block1 !=3D Block2)
+      return Block1? ImplicitConversionSequence::Worse=20
+                   : ImplicitConversionSequence::Better;
+  }
+
+  return ImplicitConversionSequence::Indistinguishable;
+}
+ =20
 /// CompareImplicitConversionSequences - Compare two implicit
 /// conversion sequences to determine whether one is better than the
 /// other or if they are indistinguishable (C++ 13.3.3.2).
@@ -2624,7 +3198,7 @@
   //   from any other user-defined conversion sequence.
   if (ICS1.getKindRank() < ICS2.getKindRank())
     return ImplicitConversionSequence::Better;
-  else if (ICS2.getKindRank() < ICS1.getKindRank())
+  if (ICS2.getKindRank() < ICS1.getKindRank())
     return ImplicitConversionSequence::Worse;
=20
   // The following checks require both conversion sequences to be of
@@ -2632,11 +3206,15 @@
   if (ICS1.getKind() !=3D ICS2.getKind())
     return ImplicitConversionSequence::Indistinguishable;
=20
+  ImplicitConversionSequence::CompareKind Result =3D
+      ImplicitConversionSequence::Indistinguishable;
+
   // Two implicit conversion sequences of the same form are
   // indistinguishable conversion sequences unless one of the
   // following rules apply: (C++ 13.3.3.2p3):
   if (ICS1.isStandard())
-    return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Stand=
ard);
+    Result =3D CompareStandardConversionSequences(S,
+                                                ICS1.Standard, ICS2.Standa=
rd);
   else if (ICS1.isUserDefined()) {
     // User-defined conversion sequence U1 is a better conversion
     // sequence than another user-defined conversion sequence U2 if
@@ -2646,12 +3224,31 @@
     // U2 (C++ 13.3.3.2p3).
     if (ICS1.UserDefined.ConversionFunction =3D=3D
           ICS2.UserDefined.ConversionFunction)
-      return CompareStandardConversionSequences(S,
-                                                ICS1.UserDefined.After,
-                                                ICS2.UserDefined.After);
-  }
-
-  return ImplicitConversionSequence::Indistinguishable;
+      Result =3D CompareStandardConversionSequences(S,
+                                                  ICS1.UserDefined.After,
+                                                  ICS2.UserDefined.After);
+    else
+      Result =3D compareConversionFunctions(S,=20
+                                          ICS1.UserDefined.ConversionFunct=
ion,
+                                          ICS2.UserDefined.ConversionFunct=
ion);
+  }
+
+  // List-initialization sequence L1 is a better conversion sequence than
+  // list-initialization sequence L2 if L1 converts to std::initializer_li=
st<X>
+  // for some X and L2 does not.
+  if (Result =3D=3D ImplicitConversionSequence::Indistinguishable &&
+      !ICS1.isBad() &&
+      ICS1.isListInitializationSequence() &&
+      ICS2.isListInitializationSequence()) {
+    if (ICS1.isStdInitializerListElement() &&
+        !ICS2.isStdInitializerListElement())
+      return ImplicitConversionSequence::Better;
+    if (!ICS1.isStdInitializerListElement() &&
+        ICS2.isStdInitializerListElement())
+      return ImplicitConversionSequence::Worse;
+  }
+
+  return Result;
 }
=20
 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
@@ -2899,7 +3496,7 @@
   // }
   // Here, MSVC will call f(int) instead of generating a compile error
   // as clang will do in standard mode.
-  if (S.getLangOptions().MicrosoftMode &&
+  if (S.getLangOpts().MicrosoftMode &&
       SCS1.Second =3D=3D ICK_Integral_Conversion &&
       SCS2.Second =3D=3D ICK_Floating_Integral &&=20
       S.Context.getTypeSize(SCS1.getFromType()) =3D=3D
@@ -3395,7 +3992,7 @@
       return false;
=20
     if (Best->Function)
-      S.MarkDeclarationReferenced(DeclLoc, Best->Function);
+      S.MarkFunctionReferenced(DeclLoc, Best->Function);
     ICS.setUserDefined();
     ICS.UserDefined.Before =3D Best->Conversions[0].Standard;
     ICS.UserDefined.After =3D Best->FinalConversion;
@@ -3423,13 +4020,13 @@
     return false;
   }
=20
-  return false;
+  llvm_unreachable("Invalid OverloadResult!");
 }
=20
 /// \brief Compute an implicit conversion sequence for reference
 /// initialization.
 static ImplicitConversionSequence
-TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
+TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
                  SourceLocation DeclLoc,
                  bool SuppressUserConversions,
                  bool AllowExplicit) {
@@ -3566,7 +4163,7 @@
     // allow the use of rvalue references in C++98/03 for the benefit of
     // standard library implementors; therefore, we need the xvalue check =
here.
     ICS.Standard.DirectBinding =3D
-      S.getLangOptions().CPlusPlus0x ||
+      S.getLangOpts().CPlusPlus0x ||
       (InitCategory.isPRValue() && !T2->isRecordType());
     ICS.Standard.IsLvalueReference =3D !isRValRef;
     ICS.Standard.BindsToFunctionLvalue =3D T2->isFunctionType();
@@ -3692,6 +4289,216 @@
   return ICS;
 }
=20
+static ImplicitConversionSequence
+TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
+                      bool SuppressUserConversions,
+                      bool InOverloadResolution,
+                      bool AllowObjCWritebackConversion,
+                      bool AllowExplicit =3D false);
+
+/// TryListConversion - Try to copy-initialize a value of type ToType from=
 the
+/// initializer list From.
+static ImplicitConversionSequence
+TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
+                  bool SuppressUserConversions,
+                  bool InOverloadResolution,
+                  bool AllowObjCWritebackConversion) {
+  // C++11 [over.ics.list]p1:
+  //   When an argument is an initializer list, it is not an expression and
+  //   special rules apply for converting it to a parameter type.
+
+  ImplicitConversionSequence Result;
+  Result.setBad(BadConversionSequence::no_conversion, From, ToType);
+  Result.setListInitializationSequence();
+
+  // We need a complete type for what follows. Incomplete types can never =
be
+  // initialized from init lists.
+  if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
+    return Result;
+
+  // C++11 [over.ics.list]p2:
+  //   If the parameter type is std::initializer_list<X> or "array of X" a=
nd
+  //   all the elements can be implicitly converted to X, the implicit
+  //   conversion sequence is the worst conversion necessary to convert an
+  //   element of the list to X.
+  bool toStdInitializerList =3D false;
+  QualType X;
+  if (ToType->isArrayType())
+    X =3D S.Context.getBaseElementType(ToType);
+  else
+    toStdInitializerList =3D S.isStdInitializerList(ToType, &X);
+  if (!X.isNull()) {
+    for (unsigned i =3D 0, e =3D From->getNumInits(); i < e; ++i) {
+      Expr *Init =3D From->getInit(i);
+      ImplicitConversionSequence ICS =3D
+          TryCopyInitialization(S, Init, X, SuppressUserConversions,
+                                InOverloadResolution,
+                                AllowObjCWritebackConversion);
+      // If a single element isn't convertible, fail.
+      if (ICS.isBad()) {
+        Result =3D ICS;
+        break;
+      }
+      // Otherwise, look for the worst conversion.
+      if (Result.isBad() ||
+          CompareImplicitConversionSequences(S, ICS, Result) =3D=3D
+              ImplicitConversionSequence::Worse)
+        Result =3D ICS;
+    }
+
+    // For an empty list, we won't have computed any conversion sequence.
+    // Introduce the identity conversion sequence.
+    if (From->getNumInits() =3D=3D 0) {
+      Result.setStandard();
+      Result.Standard.setAsIdentityConversion();
+      Result.Standard.setFromType(ToType);
+      Result.Standard.setAllToTypes(ToType);
+    }
+
+    Result.setListInitializationSequence();
+    Result.setStdInitializerListElement(toStdInitializerList);
+    return Result;
+  }
+
+  // C++11 [over.ics.list]p3:
+  //   Otherwise, if the parameter is a non-aggregate class X and overload
+  //   resolution chooses a single best constructor [...] the implicit
+  //   conversion sequence is a user-defined conversion sequence. If multi=
ple
+  //   constructors are viable but none is better than the others, the
+  //   implicit conversion sequence is a user-defined conversion sequence.
+  if (ToType->isRecordType() && !ToType->isAggregateType()) {
+    // This function can deal with initializer lists.
+    Result =3D TryUserDefinedConversion(S, From, ToType, SuppressUserConve=
rsions,
+                                      /*AllowExplicit=3D*/false,
+                                      InOverloadResolution, /*CStyle=3D*/f=
alse,
+                                      AllowObjCWritebackConversion);
+    Result.setListInitializationSequence();
+    return Result;
+  }
+
+  // C++11 [over.ics.list]p4:
+  //   Otherwise, if the parameter has an aggregate type which can be
+  //   initialized from the initializer list [...] the implicit conversion
+  //   sequence is a user-defined conversion sequence.
+  if (ToType->isAggregateType()) {
+    // Type is an aggregate, argument is an init list. At this point it co=
mes
+    // down to checking whether the initialization works.
+    // FIXME: Find out whether this parameter is consumed or not.
+    InitializedEntity Entity =3D
+        InitializedEntity::InitializeParameter(S.Context, ToType,
+                                               /*Consumed=3D*/false);
+    if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
+      Result.setUserDefined();
+      Result.UserDefined.Before.setAsIdentityConversion();
+      // Initializer lists don't have a type.
+      Result.UserDefined.Before.setFromType(QualType());
+      Result.UserDefined.Before.setAllToTypes(QualType());
+
+      Result.UserDefined.After.setAsIdentityConversion();
+      Result.UserDefined.After.setFromType(ToType);
+      Result.UserDefined.After.setAllToTypes(ToType);
+      Result.UserDefined.ConversionFunction =3D 0;
+    }
+    return Result;
+  }
+
+  // C++11 [over.ics.list]p5:
+  //   Otherwise, if the parameter is a reference, see 13.3.3.1.4.
+  if (ToType->isReferenceType()) {
+    // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
+    // mention initializer lists in any way. So we go by what list-
+    // initialization would do and try to extrapolate from that.
+
+    QualType T1 =3D ToType->getAs<ReferenceType>()->getPointeeType();
+
+    // If the initializer list has a single element that is reference-rela=
ted
+    // to the parameter type, we initialize the reference from that.
+    if (From->getNumInits() =3D=3D 1) {
+      Expr *Init =3D From->getInit(0);
+
+      QualType T2 =3D Init->getType();
+
+      // If the initializer is the address of an overloaded function, try
+      // to resolve the overloaded function. If all goes well, T2 is the
+      // type of the resulting function.
+      if (S.Context.getCanonicalType(T2) =3D=3D S.Context.OverloadTy) {
+        DeclAccessPair Found;
+        if (FunctionDecl *Fn =3D S.ResolveAddressOfOverloadedFunction(
+                                   Init, ToType, false, Found))
+          T2 =3D Fn->getType();
+      }
+
+      // Compute some basic properties of the types and the initializer.
+      bool dummy1 =3D false;
+      bool dummy2 =3D false;
+      bool dummy3 =3D false;
+      Sema::ReferenceCompareResult RefRelationship
+        =3D S.CompareReferenceRelationship(From->getLocStart(), T1, T2, du=
mmy1,
+                                         dummy2, dummy3);
+
+      if (RefRelationship >=3D Sema::Ref_Related)
+        return TryReferenceInit(S, Init, ToType,
+                                /*FIXME:*/From->getLocStart(),
+                                SuppressUserConversions,
+                                /*AllowExplicit=3D*/false);
+    }
+
+    // Otherwise, we bind the reference to a temporary created from the
+    // initializer list.
+    Result =3D TryListConversion(S, From, T1, SuppressUserConversions,
+                               InOverloadResolution,
+                               AllowObjCWritebackConversion);
+    if (Result.isFailure())
+      return Result;
+    assert(!Result.isEllipsis() &&
+           "Sub-initialization cannot result in ellipsis conversion.");
+
+    // Can we even bind to a temporary?
+    if (ToType->isRValueReferenceType() ||
+        (T1.isConstQualified() && !T1.isVolatileQualified())) {
+      StandardConversionSequence &SCS =3D Result.isStandard() ? Result.Sta=
ndard :
+                                            Result.UserDefined.After;
+      SCS.ReferenceBinding =3D true;
+      SCS.IsLvalueReference =3D ToType->isLValueReferenceType();
+      SCS.BindsToRvalue =3D true;
+      SCS.BindsToFunctionLvalue =3D false;
+      SCS.BindsImplicitObjectArgumentWithoutRefQualifier =3D false;
+      SCS.ObjCLifetimeConversionBinding =3D false;
+    } else
+      Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
+                    From, ToType);
+    return Result;
+  }
+
+  // C++11 [over.ics.list]p6:
+  //   Otherwise, if the parameter type is not a class:
+  if (!ToType->isRecordType()) {
+    //    - if the initializer list has one element, the implicit conversi=
on
+    //      sequence is the one required to convert the element to the
+    //      parameter type.
+    unsigned NumInits =3D From->getNumInits();
+    if (NumInits =3D=3D 1)
+      Result =3D TryCopyInitialization(S, From->getInit(0), ToType,
+                                     SuppressUserConversions,
+                                     InOverloadResolution,
+                                     AllowObjCWritebackConversion);
+    //    - if the initializer list has no elements, the implicit conversi=
on
+    //      sequence is the identity conversion.
+    else if (NumInits =3D=3D 0) {
+      Result.setStandard();
+      Result.Standard.setAsIdentityConversion();
+      Result.Standard.setFromType(ToType);
+      Result.Standard.setAllToTypes(ToType);
+    }
+    Result.setListInitializationSequence();
+    return Result;
+  }
+
+  // C++11 [over.ics.list]p7:
+  //   In all cases other than those enumerated above, no conversion is po=
ssible
+  return Result;
+}
+
 /// TryCopyInitialization - Try to copy-initialize a value of type
 /// ToType from the expression From. Return the implicit conversion
 /// sequence required to pass this argument, which may be a bad
@@ -3702,12 +4509,17 @@
 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
                       bool SuppressUserConversions,
                       bool InOverloadResolution,
-                      bool AllowObjCWritebackConversion) {
+                      bool AllowObjCWritebackConversion,
+                      bool AllowExplicit) {
+  if (InitListExpr *FromInitList =3D dyn_cast<InitListExpr>(From))
+    return TryListConversion(S, FromInitList, ToType, SuppressUserConversi=
ons,
+                             InOverloadResolution,AllowObjCWritebackConver=
sion);
+
   if (ToType->isReferenceType())
     return TryReferenceInit(S, From, ToType,
                             /*FIXME:*/From->getLocStart(),
                             SuppressUserConversions,
-                            /*AllowExplicit=3D*/false);
+                            AllowExplicit);
=20
   return TryImplicitConversion(S, From, ToType,
                                SuppressUserConversions,
@@ -3877,7 +4689,7 @@
       Qualifiers ToQs =3D DestType.getQualifiers();
       unsigned CVR =3D FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(=
);
       if (CVR) {
-        Diag(From->getSourceRange().getBegin(),
+        Diag(From->getLocStart(),
              diag::err_member_function_call_bad_cvr)
           << Method->getDeclName() << FromRecordType << (CVR - 1)
           << From->getSourceRange();
@@ -3887,7 +4699,7 @@
       }
     }
=20
-    return Diag(From->getSourceRange().getBegin(),
+    return Diag(From->getLocStart(),
                 diag::err_implicit_object_parameter_init)
        << ImplicitParamRecordType << FromRecordType << From->getSourceRang=
e();
   }
@@ -3902,7 +4714,7 @@
=20
   if (!Context.hasSameType(From->getType(), DestType))
     From =3D ImpCastExprToType(From, DestType, CK_NoOp,
-                      From->getType()->isPointerType() ? VK_RValue : VK_LV=
alue).take();
+                             From->getValueKind()).take();
   return Owned(From);
 }
=20
@@ -3923,17 +4735,190 @@
 /// PerformContextuallyConvertToBool - Perform a contextual conversion
 /// of the expression From to bool (C++0x [conv]p3).
 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
+  if (checkPlaceholderForOverload(*this, From))
+    return ExprError();
+
   ImplicitConversionSequence ICS =3D TryContextuallyConvertToBool(*this, F=
rom);
   if (!ICS.isBad())
     return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Convert=
ing);
=20
   if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
-    return Diag(From->getSourceRange().getBegin(),
+    return Diag(From->getLocStart(),
                 diag::err_typecheck_bool_condition)
                   << From->getType() << From->getSourceRange();
   return ExprError();
 }
=20
+/// Check that the specified conversion is permitted in a converted consta=
nt
+/// expression, according to C++11 [expr.const]p3. Return true if the conv=
ersion
+/// is acceptable.
+static bool CheckConvertedConstantConversions(Sema &S,
+                                              StandardConversionSequence &=
SCS) {
+  // Since we know that the target type is an integral or unscoped enumera=
tion
+  // type, most conversion kinds are impossible. All possible First and Th=
ird
+  // conversions are fine.
+  switch (SCS.Second) {
+  case ICK_Identity:
+  case ICK_Integral_Promotion:
+  case ICK_Integral_Conversion:
+    return true;
+
+  case ICK_Boolean_Conversion:
+    // Conversion from an integral or unscoped enumeration type to bool is
+    // classified as ICK_Boolean_Conversion, but it's also an integral
+    // conversion, so it's permitted in a converted constant expression.
+    return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
+           SCS.getToType(2)->isBooleanType();
+
+  case ICK_Floating_Integral:
+  case ICK_Complex_Real:
+    return false;
+
+  case ICK_Lvalue_To_Rvalue:
+  case ICK_Array_To_Pointer:
+  case ICK_Function_To_Pointer:
+  case ICK_NoReturn_Adjustment:
+  case ICK_Qualification:
+  case ICK_Compatible_Conversion:
+  case ICK_Vector_Conversion:
+  case ICK_Vector_Splat:
+  case ICK_Derived_To_Base:
+  case ICK_Pointer_Conversion:
+  case ICK_Pointer_Member:
+  case ICK_Block_Pointer_Conversion:
+  case ICK_Writeback_Conversion:
+  case ICK_Floating_Promotion:
+  case ICK_Complex_Promotion:
+  case ICK_Complex_Conversion:
+  case ICK_Floating_Conversion:
+  case ICK_TransparentUnionConversion:
+    llvm_unreachable("unexpected second conversion kind");
+
+  case ICK_Num_Conversion_Kinds:
+    break;
+  }
+
+  llvm_unreachable("unknown conversion kind");
+}
+
+/// CheckConvertedConstantExpression - Check that the expression From is a
+/// converted constant expression of type T, perform the conversion and pr=
oduce
+/// the converted expression, per C++11 [expr.const]p3.
+ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
+                                                  llvm::APSInt &Value,
+                                                  CCEKind CCE) {
+  assert(LangOpts.CPlusPlus0x && "converted constant expression outside C+=
+11");
+  assert(T->isIntegralOrEnumerationType() && "unexpected converted const t=
ype");
+
+  if (checkPlaceholderForOverload(*this, From))
+    return ExprError();
+
+  // C++11 [expr.const]p3 with proposed wording fixes:
+  //  A converted constant expression of type T is a core constant express=
ion,
+  //  implicitly converted to a prvalue of type T, where the converted
+  //  expression is a literal constant expression and the implicit convers=
ion
+  //  sequence contains only user-defined conversions, lvalue-to-rvalue
+  //  conversions, integral promotions, and integral conversions other than
+  //  narrowing conversions.
+  ImplicitConversionSequence ICS =3D
+    TryImplicitConversion(From, T,
+                          /*SuppressUserConversions=3D*/false,
+                          /*AllowExplicit=3D*/false,
+                          /*InOverloadResolution=3D*/false,
+                          /*CStyle=3D*/false,
+                          /*AllowObjcWritebackConversion=3D*/false);
+  StandardConversionSequence *SCS =3D 0;
+  switch (ICS.getKind()) {
+  case ImplicitConversionSequence::StandardConversion:
+    if (!CheckConvertedConstantConversions(*this, ICS.Standard))
+      return Diag(From->getLocStart(),
+                  diag::err_typecheck_converted_constant_expression_disall=
owed)
+               << From->getType() << From->getSourceRange() << T;
+    SCS =3D &ICS.Standard;
+    break;
+  case ImplicitConversionSequence::UserDefinedConversion:
+    // We are converting from class type to an integral or enumeration typ=
e, so
+    // the Before sequence must be trivial.
+    if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
+      return Diag(From->getLocStart(),
+                  diag::err_typecheck_converted_constant_expression_disall=
owed)
+               << From->getType() << From->getSourceRange() << T;
+    SCS =3D &ICS.UserDefined.After;
+    break;
+  case ImplicitConversionSequence::AmbiguousConversion:
+  case ImplicitConversionSequence::BadConversion:
+    if (!DiagnoseMultipleUserDefinedConversion(From, T))
+      return Diag(From->getLocStart(),
+                  diag::err_typecheck_converted_constant_expression)
+                    << From->getType() << From->getSourceRange() << T;
+    return ExprError();
+
+  case ImplicitConversionSequence::EllipsisConversion:
+    llvm_unreachable("ellipsis conversion in converted constant expression=
");
+  }
+
+  ExprResult Result =3D PerformImplicitConversion(From, T, ICS, AA_Convert=
ing);
+  if (Result.isInvalid())
+    return Result;
+
+  // Check for a narrowing implicit conversion.
+  APValue PreNarrowingValue;
+  QualType PreNarrowingType;
+  switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
+                                PreNarrowingType)) {
+  case NK_Variable_Narrowing:
+    // Implicit conversion to a narrower type, and the value is not a cons=
tant
+    // expression. We'll diagnose this in a moment.
+  case NK_Not_Narrowing:
+    break;
+
+  case NK_Constant_Narrowing:
+    Diag(From->getLocStart(),
+         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
+                             diag::err_cce_narrowing)
+      << CCE << /*Constant*/1
+      << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
+    break;
+
+  case NK_Type_Narrowing:
+    Diag(From->getLocStart(),
+         isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
+                             diag::err_cce_narrowing)
+      << CCE << /*Constant*/0 << From->getType() << T;
+    break;
+  }
+
+  // Check the expression is a constant expression.
+  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
+  Expr::EvalResult Eval;
+  Eval.Diag =3D &Notes;
+
+  if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
+    // The expression can't be folded, so we can't keep it at this positio=
n in
+    // the AST.
+    Result =3D ExprError();
+  } else {
+    Value =3D Eval.Val.getInt();
+
+    if (Notes.empty()) {
+      // It's a constant expression.
+      return Result;
+    }
+  }
+
+  // It's not a constant expression. Produce an appropriate diagnostic.
+  if (Notes.size() =3D=3D 1 &&
+      Notes[0].second.getDiagID() =3D=3D diag::note_invalid_subexpr_in_con=
st_expr)
+    Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
+  else {
+    Diag(From->getLocStart(), diag::err_expr_not_cce)
+      << CCE << From->getSourceRange();
+    for (unsigned I =3D 0; I < Notes.size(); ++I)
+      Diag(Notes[I].first, Notes[I].second);
+  }
+  return Result;
+}
+
 /// dropPointerConversions - If the given standard conversion sequence
 /// involves any pointer conversions, remove them.  This may change
 /// the result type of the conversion sequence.
@@ -3982,6 +4967,9 @@
 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
 /// conversion of the expression From to an Objective-C pointer type.
 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
+  if (checkPlaceholderForOverload(*this, From))
+    return ExprError();
+
   QualType Ty =3D Context.getObjCIdType();
   ImplicitConversionSequence ICS =3D
     TryContextuallyConvertToObjCPointer(*this, From);
@@ -3990,6 +4978,13 @@
   return ExprError();
 }
=20
+/// Determine whether the provided type is an integral type, or an enumera=
tion
+/// type of a permitted flavor.
+static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
+  return AllowScopedEnum ? T->isIntegralOrEnumerationType()
+                         : T->isIntegralOrUnscopedEnumerationType();
+}
+
 /// \brief Attempt to convert the given expression to an integral or
 /// enumeration type.
 ///
@@ -4024,6 +5019,9 @@
 /// \param ConvDiag The diagnostic to be emitted if we are calling a conve=
rsion
 /// function, which may be an extension in this case.
 ///
+/// \param AllowScopedEnumerations Specifies whether conversions to scoped
+/// enumerations should be considered.
+///
 /// \returns The expression, converted to an integral or enumeration type =
if
 /// successful.
 ExprResult
@@ -4034,24 +5032,32 @@
                                      const PartialDiagnostic &ExplicitConv=
Note,
                                          const PartialDiagnostic &AmbigDia=
g,
                                          const PartialDiagnostic &AmbigNot=
e,
-                                         const PartialDiagnostic &ConvDiag=
) {
+                                         const PartialDiagnostic &ConvDiag,
+                                         bool AllowScopedEnumerations) {
   // We can't perform any more checking for type-dependent expressions.
   if (From->isTypeDependent())
     return Owned(From);
=20
+  // Process placeholders immediately.
+  if (From->hasPlaceholderType()) {
+    ExprResult result =3D CheckPlaceholderExpr(From);
+    if (result.isInvalid()) return result;
+    From =3D result.take();
+  }
+
   // If the expression already has integral or enumeration type, we're gol=
den.
   QualType T =3D From->getType();
-  if (T->isIntegralOrEnumerationType())
-    return Owned(From);
+  if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
+    return DefaultLvalueConversion(From);
=20
   // FIXME: Check for missing '()' if T is a function type?
=20
   // If we don't have a class type in C++, there's no way we can get an
   // expression of integral or enumeration type.
   const RecordType *RecordTy =3D T->getAs<RecordType>();
-  if (!RecordTy || !getLangOptions().CPlusPlus) {
-    Diag(Loc, NotIntDiag)
-      << T << From->getSourceRange();
+  if (!RecordTy || !getLangOpts().CPlusPlus) {
+    if (NotIntDiag.getDiagID())
+      Diag(Loc, NotIntDiag) << T << From->getSourceRange();
     return Owned(From);
   }
=20
@@ -4072,19 +5078,21 @@
        I !=3D E;
        ++I) {
     if (CXXConversionDecl *Conversion
-          =3D dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
-      if (Conversion->getConversionType().getNonReferenceType()
-            ->isIntegralOrEnumerationType()) {
+          =3D dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
+      if (isIntegralOrEnumerationType(
+            Conversion->getConversionType().getNonReferenceType(),
+            AllowScopedEnumerations)) {
         if (Conversion->isExplicit())
           ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
         else
           ViableConversions.addDecl(I.getDecl(), I.getAccess());
       }
+    }
   }
=20
   switch (ViableConversions.size()) {
   case 0:
-    if (ExplicitConversions.size() =3D=3D 1) {
+    if (ExplicitConversions.size() =3D=3D 1 && ExplicitConvDiag.getDiagID(=
)) {
       DeclAccessPair Found =3D ExplicitConversions[0];
       CXXConversionDecl *Conversion
         =3D cast<CXXConversionDecl>(Found->getUnderlyingDecl());
@@ -4115,8 +5123,11 @@
                                                  HadMultipleCandidates);
       if (Result.isInvalid())
         return ExprError();
-
-      From =3D Result.get();
+      // Record usage of conversion in an implicit cast.
+      From =3D ImplicitCastExpr::Create(Context, Result.get()->getType(),
+                                      CK_UserDefinedConversion,
+                                      Result.get(), 0,
+                                      Result.get()->getValueKind());
     }
=20
     // We'll complain below about a non-integral condition type.
@@ -4143,12 +5154,18 @@
                                                HadMultipleCandidates);
     if (Result.isInvalid())
       return ExprError();
-
-    From =3D Result.get();
+    // Record usage of conversion in an implicit cast.
+    From =3D ImplicitCastExpr::Create(Context, Result.get()->getType(),
+                                    CK_UserDefinedConversion,
+                                    Result.get(), 0,
+                                    Result.get()->getValueKind());
     break;
   }
=20
   default:
+    if (!AmbigDiag.getDiagID())
+      return Owned(From);
+
     Diag(Loc, AmbigDiag)
       << T << From->getSourceRange();
     for (unsigned I =3D 0, N =3D ViableConversions.size(); I !=3D N; ++I) {
@@ -4161,11 +5178,11 @@
     return Owned(From);
   }
=20
-  if (!From->getType()->isIntegralOrEnumerationType())
-    Diag(Loc, NotIntDiag)
-      << From->getType() << From->getSourceRange();
-
-  return Owned(From);
+  if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumeration=
s) &&
+      NotIntDiag.getDiagID())
+    Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
+
+  return DefaultLvalueConversion(From);
 }
=20
 /// AddOverloadCandidate - Adds the given function to the set of
@@ -4179,10 +5196,11 @@
 void
 Sema::AddOverloadCandidate(FunctionDecl *Function,
                            DeclAccessPair FoundDecl,
-                           Expr **Args, unsigned NumArgs,
+                           llvm::ArrayRef<Expr *> Args,
                            OverloadCandidateSet& CandidateSet,
                            bool SuppressUserConversions,
-                           bool PartialOverloading) {
+                           bool PartialOverloading,
+                           bool AllowExplicit) {
   const FunctionProtoType* Proto
     =3D dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionTyp=
e>());
   assert(Proto && "Functions without a prototype cannot be overloaded");
@@ -4200,8 +5218,7 @@
       // is irrelevant.
       AddMethodCandidate(Method, FoundDecl, Method->getParent(),
                          QualType(), Expr::Classification::makeSimpleLValu=
e(),
-                         Args, NumArgs, CandidateSet,
-                         SuppressUserConversions);
+                         Args, CandidateSet, SuppressUserConversions);
       return;
     }
     // We treat a constructor like a non-member function, since its object
@@ -4219,7 +5236,7 @@
     //   A member function template is never instantiated to perform the c=
opy
     //   of a class object to an object of its class type.
     QualType ClassType =3D Context.getTypeDeclType(Constructor->getParent(=
));
-    if (NumArgs =3D=3D 1 &&
+    if (Args.size() =3D=3D 1 &&
         Constructor->isSpecializationCopyingObject() &&
         (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
          IsDerivedFrom(Args[0]->getType(), ClassType)))
@@ -4227,21 +5244,20 @@
   }
=20
   // Add this candidate
-  CandidateSet.push_back(OverloadCandidate());
-  OverloadCandidate& Candidate =3D CandidateSet.back();
+  OverloadCandidate &Candidate =3D CandidateSet.addCandidate(Args.size());
   Candidate.FoundDecl =3D FoundDecl;
   Candidate.Function =3D Function;
   Candidate.Viable =3D true;
   Candidate.IsSurrogate =3D false;
   Candidate.IgnoreObjectArgument =3D false;
-  Candidate.ExplicitCallArguments =3D NumArgs;
+  Candidate.ExplicitCallArguments =3D Args.size();
=20
   unsigned NumArgsInProto =3D Proto->getNumArgs();
=20
   // (C++ 13.3.2p2): A candidate function having fewer than m
   // parameters is viable only if it has an ellipsis in its parameter
   // list (8.3.5).
-  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
+  if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto=
 &&
       !Proto->isVariadic()) {
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_too_many_arguments;
@@ -4254,7 +5270,7 @@
   // parameter list is truncated on the right, so that there are
   // exactly m parameters.
   unsigned MinRequiredArgs =3D Function->getMinRequiredArguments();
-  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
+  if (Args.size() < MinRequiredArgs && !PartialOverloading) {
     // Not enough arguments.
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_too_few_arguments;
@@ -4262,7 +5278,7 @@
   }
=20
   // (CUDA B.1): Check for invalid calls between targets.
-  if (getLangOptions().CUDA)
+  if (getLangOpts().CUDA)
     if (const FunctionDecl *Caller =3D dyn_cast<FunctionDecl>(CurContext))
       if (CheckCUDATarget(Caller, Function)) {
         Candidate.Viable =3D false;
@@ -4272,8 +5288,7 @@
=20
   // Determine the implicit conversion sequences for each of the
   // arguments.
-  Candidate.Conversions.resize(NumArgs);
-  for (unsigned ArgIdx =3D 0; ArgIdx < NumArgs; ++ArgIdx) {
+  for (unsigned ArgIdx =3D 0; ArgIdx < Args.size(); ++ArgIdx) {
     if (ArgIdx < NumArgsInProto) {
       // (C++ 13.3.2p3): for F to be a viable function, there shall
       // exist for each argument an implicit conversion sequence
@@ -4285,7 +5300,8 @@
                                 SuppressUserConversions,
                                 /*InOverloadResolution=3D*/true,
                                 /*AllowObjCWritebackConversion=3D*/
-                                  getLangOptions().ObjCAutoRefCount);
+                                  getLangOpts().ObjCAutoRefCount,
+                                AllowExplicit);
       if (Candidate.Conversions[ArgIdx].isBad()) {
         Candidate.Viable =3D false;
         Candidate.FailureKind =3D ovl_fail_bad_conversion;
@@ -4303,9 +5319,10 @@
 /// \brief Add all of the function declarations in the given function set =
to
 /// the overload canddiate set.
 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
-                                 Expr **Args, unsigned NumArgs,
+                                 llvm::ArrayRef<Expr *> Args,
                                  OverloadCandidateSet& CandidateSet,
-                                 bool SuppressUserConversions) {
+                                 bool SuppressUserConversions,
+                               TemplateArgumentListInfo *ExplicitTemplateA=
rgs) {
   for (UnresolvedSetIterator F =3D Fns.begin(), E =3D Fns.end(); F !=3D E;=
 ++F) {
     NamedDecl *D =3D F.getDecl()->getUnderlyingDecl();
     if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
@@ -4313,10 +5330,10 @@
         AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
                            cast<CXXMethodDecl>(FD)->getParent(),
                            Args[0]->getType(), Args[0]->Classify(Context),
-                           Args + 1, NumArgs - 1,
-                           CandidateSet, SuppressUserConversions);
+                           Args.slice(1), CandidateSet,
+                           SuppressUserConversions);
       else
-        AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
+        AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
                              SuppressUserConversions);
     } else {
       FunctionTemplateDecl *FunTmpl =3D cast<FunctionTemplateDecl>(D);
@@ -4324,17 +5341,14 @@
           !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
         AddMethodTemplateCandidate(FunTmpl, F.getPair(),
                               cast<CXXRecordDecl>(FunTmpl->getDeclContext(=
)),
-                                   /*FIXME: explicit args */ 0,
+                                   ExplicitTemplateArgs,
                                    Args[0]->getType(),
-                                   Args[0]->Classify(Context),
-                                   Args + 1, NumArgs - 1,
-                                   CandidateSet,
-                                   SuppressUserConversions);
+                                   Args[0]->Classify(Context), Args.slice(=
1),
+                                   CandidateSet, SuppressUserConversions);
       else
         AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
-                                     /*FIXME: explicit args */ 0,
-                                     Args, NumArgs, CandidateSet,
-                                     SuppressUserConversions);
+                                     ExplicitTemplateArgs, Args,
+                                     CandidateSet, SuppressUserConversions=
);
     }
   }
 }
@@ -4358,12 +5372,13 @@
            "Expected a member function template");
     AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
                                /*ExplicitArgs*/ 0,
-                               ObjectType, ObjectClassification, Args, Num=
Args,
-                               CandidateSet,
+                               ObjectType, ObjectClassification,
+                               llvm::makeArrayRef(Args, NumArgs), Candidat=
eSet,
                                SuppressUserConversions);
   } else {
     AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
-                       ObjectType, ObjectClassification, Args, NumArgs,
+                       ObjectType, ObjectClassification,
+                       llvm::makeArrayRef(Args, NumArgs),
                        CandidateSet, SuppressUserConversions);
   }
 }
@@ -4379,7 +5394,7 @@
 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
                          CXXRecordDecl *ActingContext, QualType ObjectType,
                          Expr::Classification ObjectClassification,
-                         Expr **Args, unsigned NumArgs,
+                         llvm::ArrayRef<Expr *> Args,
                          OverloadCandidateSet& CandidateSet,
                          bool SuppressUserConversions) {
   const FunctionProtoType* Proto
@@ -4395,20 +5410,19 @@
   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
=20
   // Add this candidate
-  CandidateSet.push_back(OverloadCandidate());
-  OverloadCandidate& Candidate =3D CandidateSet.back();
+  OverloadCandidate &Candidate =3D CandidateSet.addCandidate(Args.size() +=
 1);
   Candidate.FoundDecl =3D FoundDecl;
   Candidate.Function =3D Method;
   Candidate.IsSurrogate =3D false;
   Candidate.IgnoreObjectArgument =3D false;
-  Candidate.ExplicitCallArguments =3D NumArgs;
+  Candidate.ExplicitCallArguments =3D Args.size();
=20
   unsigned NumArgsInProto =3D Proto->getNumArgs();
=20
   // (C++ 13.3.2p2): A candidate function having fewer than m
   // parameters is viable only if it has an ellipsis in its parameter
   // list (8.3.5).
-  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
+  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_too_many_arguments;
     return;
@@ -4420,7 +5434,7 @@
   // parameter list is truncated on the right, so that there are
   // exactly m parameters.
   unsigned MinRequiredArgs =3D Method->getMinRequiredArguments();
-  if (NumArgs < MinRequiredArgs) {
+  if (Args.size() < MinRequiredArgs) {
     // Not enough arguments.
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_too_few_arguments;
@@ -4428,7 +5442,6 @@
   }
=20
   Candidate.Viable =3D true;
-  Candidate.Conversions.resize(NumArgs + 1);
=20
   if (Method->isStatic() || ObjectType.isNull())
     // The implicit object argument is ignored.
@@ -4448,7 +5461,7 @@
=20
   // Determine the implicit conversion sequences for each of the
   // arguments.
-  for (unsigned ArgIdx =3D 0; ArgIdx < NumArgs; ++ArgIdx) {
+  for (unsigned ArgIdx =3D 0; ArgIdx < Args.size(); ++ArgIdx) {
     if (ArgIdx < NumArgsInProto) {
       // (C++ 13.3.2p3): for F to be a viable function, there shall
       // exist for each argument an implicit conversion sequence
@@ -4460,7 +5473,7 @@
                                 SuppressUserConversions,
                                 /*InOverloadResolution=3D*/true,
                                 /*AllowObjCWritebackConversion=3D*/
-                                  getLangOptions().ObjCAutoRefCount);
+                                  getLangOpts().ObjCAutoRefCount);
       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
         Candidate.Viable =3D false;
         Candidate.FailureKind =3D ovl_fail_bad_conversion;
@@ -4485,7 +5498,7 @@
                                  TemplateArgumentListInfo *ExplicitTemplat=
eArgs,
                                  QualType ObjectType,
                                  Expr::Classification ObjectClassification,
-                                 Expr **Args, unsigned NumArgs,
+                                 llvm::ArrayRef<Expr *> Args,
                                  OverloadCandidateSet& CandidateSet,
                                  bool SuppressUserConversions) {
   if (!CandidateSet.isNewCandidate(MethodTmpl))
@@ -4503,17 +5516,16 @@
   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
   FunctionDecl *Specialization =3D 0;
   if (TemplateDeductionResult Result
-      =3D DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
-                                Args, NumArgs, Specialization, Info)) {
-    CandidateSet.push_back(OverloadCandidate());
-    OverloadCandidate &Candidate =3D CandidateSet.back();
+      =3D DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
+                                Specialization, Info)) {
+    OverloadCandidate &Candidate =3D CandidateSet.addCandidate();
     Candidate.FoundDecl =3D FoundDecl;
     Candidate.Function =3D MethodTmpl->getTemplatedDecl();
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_bad_deduction;
     Candidate.IsSurrogate =3D false;
     Candidate.IgnoreObjectArgument =3D false;
-    Candidate.ExplicitCallArguments =3D NumArgs;
+    Candidate.ExplicitCallArguments =3D Args.size();
     Candidate.DeductionFailure =3D MakeDeductionFailureInfo(Context, Resul=
t,
                                                           Info);
     return;
@@ -4525,8 +5537,8 @@
   assert(isa<CXXMethodDecl>(Specialization) &&
          "Specialization is not a member function?");
   AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
-                     ActingContext, ObjectType, ObjectClassification,
-                     Args, NumArgs, CandidateSet, SuppressUserConversions);
+                     ActingContext, ObjectType, ObjectClassification, Args,
+                     CandidateSet, SuppressUserConversions);
 }
=20
 /// \brief Add a C++ function template specialization as a candidate
@@ -4536,7 +5548,7 @@
 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
                                    DeclAccessPair FoundDecl,
                                  TemplateArgumentListInfo *ExplicitTemplat=
eArgs,
-                                   Expr **Args, unsigned NumArgs,
+                                   llvm::ArrayRef<Expr *> Args,
                                    OverloadCandidateSet& CandidateSet,
                                    bool SuppressUserConversions) {
   if (!CandidateSet.isNewCandidate(FunctionTemplate))
@@ -4554,17 +5566,16 @@
   TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
   FunctionDecl *Specialization =3D 0;
   if (TemplateDeductionResult Result
-        =3D DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
-                                  Args, NumArgs, Specialization, Info)) {
-    CandidateSet.push_back(OverloadCandidate());
-    OverloadCandidate &Candidate =3D CandidateSet.back();
+        =3D DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs=
, Args,
+                                  Specialization, Info)) {
+    OverloadCandidate &Candidate =3D CandidateSet.addCandidate();
     Candidate.FoundDecl =3D FoundDecl;
     Candidate.Function =3D FunctionTemplate->getTemplatedDecl();
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_bad_deduction;
     Candidate.IsSurrogate =3D false;
     Candidate.IgnoreObjectArgument =3D false;
-    Candidate.ExplicitCallArguments =3D NumArgs;
+    Candidate.ExplicitCallArguments =3D Args.size();
     Candidate.DeductionFailure =3D MakeDeductionFailureInfo(Context, Resul=
t,
                                                           Info);
     return;
@@ -4573,7 +5584,7 @@
   // Add the function template specialization produced by template argument
   // deduction as a candidate.
   assert(Specialization && "Missing function template specialization?");
-  AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, Candidate=
Set,
+  AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
                        SuppressUserConversions);
 }
=20
@@ -4599,8 +5610,7 @@
   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
=20
   // Add this candidate
-  CandidateSet.push_back(OverloadCandidate());
-  OverloadCandidate& Candidate =3D CandidateSet.back();
+  OverloadCandidate &Candidate =3D CandidateSet.addCandidate(1);
   Candidate.FoundDecl =3D FoundDecl;
   Candidate.Function =3D Conversion;
   Candidate.IsSurrogate =3D false;
@@ -4609,7 +5619,6 @@
   Candidate.FinalConversion.setFromType(ConvType);
   Candidate.FinalConversion.setAllToTypes(ToType);
   Candidate.Viable =3D true;
-  Candidate.Conversions.resize(1);
   Candidate.ExplicitCallArguments =3D 1;
=20
   // C++ [over.match.funcs]p4:
@@ -4656,7 +5665,7 @@
   // lvalues/rvalues and the type. Fortunately, we can allocate this
   // call on the stack and we don't need its arguments to be
   // well-formed.
-  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
+  DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
                             VK_LValue, From->getLocStart());
   ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
                                 Context.getPointerType(Conversion->getType=
()),
@@ -4743,8 +5752,7 @@
   if (TemplateDeductionResult Result
         =3D DeduceTemplateArguments(FunctionTemplate, ToType,
                                   Specialization, Info)) {
-    CandidateSet.push_back(OverloadCandidate());
-    OverloadCandidate &Candidate =3D CandidateSet.back();
+    OverloadCandidate &Candidate =3D CandidateSet.addCandidate();
     Candidate.FoundDecl =3D FoundDecl;
     Candidate.Function =3D FunctionTemplate->getTemplatedDecl();
     Candidate.Viable =3D false;
@@ -4774,7 +5782,7 @@
                                  CXXRecordDecl *ActingContext,
                                  const FunctionProtoType *Proto,
                                  Expr *Object,
-                                 Expr **Args, unsigned NumArgs,
+                                 llvm::ArrayRef<Expr *> Args,
                                  OverloadCandidateSet& CandidateSet) {
   if (!CandidateSet.isNewCandidate(Conversion))
     return;
@@ -4782,16 +5790,14 @@
   // Overload resolution is always an unevaluated context.
   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
=20
-  CandidateSet.push_back(OverloadCandidate());
-  OverloadCandidate& Candidate =3D CandidateSet.back();
+  OverloadCandidate &Candidate =3D CandidateSet.addCandidate(Args.size() +=
 1);
   Candidate.FoundDecl =3D FoundDecl;
   Candidate.Function =3D 0;
   Candidate.Surrogate =3D Conversion;
   Candidate.Viable =3D true;
   Candidate.IsSurrogate =3D true;
   Candidate.IgnoreObjectArgument =3D false;
-  Candidate.Conversions.resize(NumArgs + 1);
-  Candidate.ExplicitCallArguments =3D NumArgs;
+  Candidate.ExplicitCallArguments =3D Args.size();
=20
   // Determine the implicit conversion sequence for the implicit
   // object parameter.
@@ -4825,7 +5831,7 @@
   // (C++ 13.3.2p2): A candidate function having fewer than m
   // parameters is viable only if it has an ellipsis in its parameter
   // list (8.3.5).
-  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
+  if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_too_many_arguments;
     return;
@@ -4833,7 +5839,7 @@
=20
   // Function types don't have any default arguments, so just check if
   // we have enough arguments.
-  if (NumArgs < NumArgsInProto) {
+  if (Args.size() < NumArgsInProto) {
     // Not enough arguments.
     Candidate.Viable =3D false;
     Candidate.FailureKind =3D ovl_fail_too_few_arguments;
@@ -4842,7 +5848,7 @@
=20
   // Determine the implicit conversion sequences for each of the
   // arguments.
-  for (unsigned ArgIdx =3D 0; ArgIdx < NumArgs; ++ArgIdx) {
+  for (unsigned ArgIdx =3D 0; ArgIdx < Args.size(); ++ArgIdx) {
     if (ArgIdx < NumArgsInProto) {
       // (C++ 13.3.2p3): for F to be a viable function, there shall
       // exist for each argument an implicit conversion sequence
@@ -4854,7 +5860,7 @@
                                 /*SuppressUserConversions=3D*/false,
                                 /*InOverloadResolution=3D*/false,
                                 /*AllowObjCWritebackConversion=3D*/
-                                  getLangOptions().ObjCAutoRefCount);
+                                  getLangOpts().ObjCAutoRefCount);
       if (Candidate.Conversions[ArgIdx + 1].isBad()) {
         Candidate.Viable =3D false;
         Candidate.FailureKind =3D ovl_fail_bad_conversion;
@@ -4935,8 +5941,7 @@
   EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
=20
   // Add this candidate
-  CandidateSet.push_back(OverloadCandidate());
-  OverloadCandidate& Candidate =3D CandidateSet.back();
+  OverloadCandidate &Candidate =3D CandidateSet.addCandidate(NumArgs);
   Candidate.FoundDecl =3D DeclAccessPair::make(0, AS_none);
   Candidate.Function =3D 0;
   Candidate.IsSurrogate =3D false;
@@ -4948,7 +5953,6 @@
   // Determine the implicit conversion sequences for each of the
   // arguments.
   Candidate.Viable =3D true;
-  Candidate.Conversions.resize(NumArgs);
   Candidate.ExplicitCallArguments =3D NumArgs;
   for (unsigned ArgIdx =3D 0; ArgIdx < NumArgs; ++ArgIdx) {
     // C++ [over.match.oper]p4:
@@ -4974,7 +5978,7 @@
                                 ArgIdx =3D=3D 0 && IsAssignmentOperator,
                                 /*InOverloadResolution=3D*/false,
                                 /*AllowObjCWritebackConversion=3D*/
-                                  getLangOptions().ObjCAutoRefCount);
+                                  getLangOpts().ObjCAutoRefCount);
     }
     if (Candidate.Conversions[ArgIdx].isBad()) {
       Candidate.Viable =3D false;
@@ -6319,7 +7323,7 @@
         S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
       }
=20
-      if (S.getLangOptions().CPlusPlus0x) {
+      if (S.getLangOpts().CPlusPlus0x) {
         for (BuiltinCandidateTypeSet::iterator
                   Enum =3D CandidateTypes[ArgIdx].enumeration_begin(),
                EnumEnd =3D CandidateTypes[ArgIdx].enumeration_end();
@@ -6536,8 +7540,8 @@
 /// candidate set (C++ [basic.lookup.argdep]).
 void
 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
-                                           bool Operator,
-                                           Expr **Args, unsigned NumArgs,
+                                           bool Operator, SourceLocation L=
oc,
+                                           llvm::ArrayRef<Expr *> Args,
                                  TemplateArgumentListInfo *ExplicitTemplat=
eArgs,
                                            OverloadCandidateSet& Candidate=
Set,
                                            bool PartialOverloading,
@@ -6552,7 +7556,7 @@
   // we supposed to consider on ADL candidates, anyway?
=20
   // FIXME: Pass in the explicit template arguments?
-  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
+  ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
                           StdNamespaceIsAssociated);
=20
   // Erase all of the candidates we already knew about.
@@ -6573,12 +7577,12 @@
       if (ExplicitTemplateArgs)
         continue;
=20
-      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
-                           false, PartialOverloading);
+      AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
+                           PartialOverloading);
     } else
       AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
                                    FoundDecl, ExplicitTemplateArgs,
-                                   Args, NumArgs, CandidateSet);
+                                   Args, CandidateSet);
   }
 }
=20
@@ -6611,8 +7615,8 @@
   //   A viable function F1 is defined to be a better function than another
   //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
   //   conversion sequence than ICSi(F2), and then...
-  unsigned NumArgs =3D Cand1.Conversions.size();
-  assert(Cand2.Conversions.size() =3D=3D NumArgs && "Overload candidate mi=
smatch");
+  unsigned NumArgs =3D Cand1.NumConversions;
+  assert(Cand2.NumConversions =3D=3D NumArgs && "Overload candidate mismat=
ch");
   bool HasBetterConversion =3D false;
   for (unsigned ArgIdx =3D StartArg; ArgIdx < NumArgs; ++ArgIdx) {
     switch (CompareImplicitConversionSequences(S,
@@ -6669,6 +7673,15 @@
   if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
       isa<CXXConversionDecl>(Cand1.Function) &&
       isa<CXXConversionDecl>(Cand2.Function)) {
+    // First check whether we prefer one of the conversion functions over =
the
+    // other. This only distinguishes the results in non-standard, extensi=
on
+    // cases such as the conversion from a lambda closure type to a functi=
on
+    // pointer or block.
+    ImplicitConversionSequence::CompareKind FuncResult
+      =3D compareConversionFunctions(S, Cand1.Function, Cand2.Function);
+    if (FuncResult !=3D ImplicitConversionSequence::Indistinguishable)
+      return FuncResult;
+         =20
     switch (CompareStandardConversionSequences(S,
                                                Cand1.FinalConversion,
                                                Cand2.FinalConversion)) {
@@ -6794,9 +7807,11 @@
     if (Meth->isMoveAssignmentOperator())
       return oc_implicit_move_assignment;
=20
-    assert(Meth->isCopyAssignmentOperator()
-           && "implicit method is not copy assignment operator?");
-    return oc_implicit_copy_assignment;
+    if (Meth->isCopyAssignmentOperator())
+      return oc_implicit_copy_assignment;
+
+    assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
+    return oc_method;
   }
=20
   return isTemplate ? oc_function_template : oc_function;
@@ -6815,17 +7830,19 @@
 } // end anonymous namespace
=20
 // Notes the location of an overload candidate.
-void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
+void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
   std::string FnDesc;
   OverloadCandidateKind K =3D ClassifyOverloadCandidate(*this, Fn, FnDesc);
-  Diag(Fn->getLocation(), diag::note_ovl_candidate)
-    << (unsigned) K << FnDesc;
+  PartialDiagnostic PD =3D PDiag(diag::note_ovl_candidate)
+                             << (unsigned) K << FnDesc;
+  HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
+  Diag(Fn->getLocation(), PD);
   MaybeEmitInheritedConstructorNote(*this, Fn);
 }
=20
 //Notes the location of all overload candidates designated through=20
 // OverloadedExpr
-void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
+void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestTy=
pe) {
   assert(OverloadedExpr->getType() =3D=3D Context.OverloadTy);
=20
   OverloadExpr::FindResult Ovl =3D OverloadExpr::find(OverloadedExpr);
@@ -6836,10 +7853,10 @@
        I !=3D IEnd; ++I) {
     if (FunctionTemplateDecl *FunTmpl =3D=20
                 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) =
) {
-      NoteOverloadCandidate(FunTmpl->getTemplatedDecl());  =20
+      NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
     } else if (FunctionDecl *Fun=20
                       =3D dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()=
) ) {
-      NoteOverloadCandidate(Fun);
+      NoteOverloadCandidate(Fun, DestType);
     }
   }
 }
@@ -6915,12 +7932,6 @@
=20
   if (CToTy.getUnqualifiedType() =3D=3D CFromTy.getUnqualifiedType() &&
       !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
-    // It is dumb that we have to do this here.
-    while (isa<ArrayType>(CFromTy))
-      CFromTy =3D CFromTy->getAs<ArrayType>()->getElementType();
-    while (isa<ArrayType>(CToTy))
-      CToTy =3D CFromTy->getAs<ArrayType>()->getElementType();
-
     Qualifiers FromQs =3D CFromTy.getQualifiers();
     Qualifiers ToQs =3D CToTy.getQualifiers();
=20
@@ -7064,9 +8075,8 @@
     << (unsigned) (Cand->Fix.Kind);
=20
   // If we can fix the conversion, suggest the FixIts.
-  for (SmallVector<FixItHint, 1>::iterator
-      HI =3D Cand->Fix.Hints.begin(), HE =3D Cand->Fix.Hints.end();
-      HI !=3D HE; ++HI)
+  for (std::vector<FixItHint>::iterator HI =3D Cand->Fix.Hints.begin(),
+       HE =3D Cand->Fix.Hints.end(); HI !=3D HE; ++HI)
     FDiag << *HI;
   S.Diag(Fn->getLocation(), FDiag);
=20
@@ -7125,7 +8135,7 @@
=20
 /// Diagnose a failed template-argument deduction.
 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
-                          Expr **Args, unsigned NumArgs) {
+                          unsigned NumArgs) {
   FunctionDecl *Fn =3D Cand->Function; // pattern
=20
   TemplateParameter Param =3D Cand->DeductionFailure.getTemplateParameter(=
);
@@ -7273,7 +8283,7 @@
 /// more richly for those diagnostic clients that cared, but we'd
 /// still have to be just as careful with the default diagnostics.
 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
-                           Expr **Args, unsigned NumArgs) {
+                           unsigned NumArgs) {
   FunctionDecl *Fn =3D Cand->Function;
=20
   // Note deleted candidates, but only if they're viable.
@@ -7283,7 +8293,8 @@
     OverloadCandidateKind FnKind =3D ClassifyOverloadCandidate(S, Fn, FnDe=
sc);
=20
     S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
-      << FnKind << FnDesc << Fn->isDeleted();
+      << FnKind << FnDesc
+      << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
     MaybeEmitInheritedConstructorNote(S, Fn);
     return;
   }
@@ -7300,7 +8311,7 @@
     return DiagnoseArityMismatch(S, Cand, NumArgs);
=20
   case ovl_fail_bad_deduction:
-    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
+    return DiagnoseBadDeduction(S, Cand, NumArgs);
=20
   case ovl_fail_trivial_conversion:
   case ovl_fail_bad_final_conversion:
@@ -7309,7 +8320,7 @@
=20
   case ovl_fail_bad_conversion: {
     unsigned I =3D (Cand->IgnoreObjectArgument ? 1 : 0);
-    for (unsigned N =3D Cand->Conversions.size(); I !=3D N; ++I)
+    for (unsigned N =3D Cand->NumConversions; I !=3D N; ++I)
       if (Cand->Conversions[I].isBad())
         return DiagnoseBadConversion(S, Cand, I);
=20
@@ -7361,12 +8372,12 @@
                                   const char *Opc,
                                   SourceLocation OpLoc,
                                   OverloadCandidate *Cand) {
-  assert(Cand->Conversions.size() <=3D 2 && "builtin operator is not binar=
y");
+  assert(Cand->NumConversions <=3D 2 && "builtin operator is not binary");
   std::string TypeStr("operator");
   TypeStr +=3D Opc;
   TypeStr +=3D "(";
   TypeStr +=3D Cand->BuiltinTypes.ParamTypes[0].getAsString();
-  if (Cand->Conversions.size() =3D=3D 1) {
+  if (Cand->NumConversions =3D=3D 1) {
     TypeStr +=3D ")";
     S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
   } else {
@@ -7379,7 +8390,7 @@
=20
 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
                                   OverloadCandidate *Cand) {
-  unsigned NoOperands =3D Cand->Conversions.size();
+  unsigned NoOperands =3D Cand->NumConversions;
   for (unsigned ArgIdx =3D 0; ArgIdx < NoOperands; ++ArgIdx) {
     const ImplicitConversionSequence &ICS =3D Cand->Conversions[ArgIdx];
     if (ICS.isBad()) break; // all meaningless after first invalid
@@ -7483,11 +8494,11 @@
=20
         // If there's any ordering between the defined conversions...
         // FIXME: this might not be transitive.
-        assert(L->Conversions.size() =3D=3D R->Conversions.size());
+        assert(L->NumConversions =3D=3D R->NumConversions);
=20
         int leftBetter =3D 0;
         unsigned I =3D (L->IgnoreObjectArgument || R->IgnoreObjectArgument=
);
-        for (unsigned E =3D L->Conversions.size(); I !=3D E; ++I) {
+        for (unsigned E =3D L->NumConversions; I !=3D E; ++I) {
           switch (CompareImplicitConversionSequences(S,
                                                      L->Conversions[I],
                                                      R->Conversions[I])) {
@@ -7537,7 +8548,7 @@
 /// CompleteNonViableCandidate - Normally, overload resolution only
 /// computes up to the first. Produces the FixIt set if possible.
 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
-                                Expr **Args, unsigned NumArgs) {
+                                llvm::ArrayRef<Expr *> Args) {
   assert(!Cand->Viable);
=20
   // Don't do anything on failures other than bad conversion.
@@ -7550,7 +8561,7 @@
=20
   // Skip forward to the first bad conversion.
   unsigned ConvIdx =3D (Cand->IgnoreObjectArgument ? 1 : 0);
-  unsigned ConvCount =3D Cand->Conversions.size();
+  unsigned ConvCount =3D Cand->NumConversions;
   while (true) {
     assert(ConvIdx !=3D ConvCount && "no bad conversion in candidate");
     ConvIdx++;
@@ -7595,7 +8606,7 @@
                                 SuppressUserConversions,
                                 /*InOverloadResolution*/ true,
                                 /*AllowObjCWritebackConversion=3D*/
-                                  S.getLangOptions().ObjCAutoRefCount);
+                                  S.getLangOpts().ObjCAutoRefCount);
     return;
   }
=20
@@ -7608,7 +8619,7 @@
                                 SuppressUserConversions,
                                 /*InOverloadResolution=3D*/true,
                                 /*AllowObjCWritebackConversion=3D*/
-                                  S.getLangOptions().ObjCAutoRefCount);
+                                  S.getLangOpts().ObjCAutoRefCount);
       // Store the FixIt in the candidate if it exists.
       if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
         Unfixable =3D !Cand->TryToFixBadConversion(ConvIdx, S);
@@ -7625,7 +8636,7 @@
 /// set.
 void OverloadCandidateSet::NoteCandidates(Sema &S,
                                           OverloadCandidateDisplayKind OCD,
-                                          Expr **Args, unsigned NumArgs,
+                                          llvm::ArrayRef<Expr *> Args,
                                           const char *Opc,
                                           SourceLocation OpLoc) {
   // Sort the candidates by viability and position.  Sorting directly would
@@ -7636,7 +8647,7 @@
     if (Cand->Viable)
       Cands.push_back(Cand);
     else if (OCD =3D=3D OCD_AllCandidates) {
-      CompleteNonViableCandidate(S, Cand, Args, NumArgs);
+      CompleteNonViableCandidate(S, Cand, Args);
       if (Cand->Function || Cand->IsSurrogate)
         Cands.push_back(Cand);
       // Otherwise, this a non-viable builtin candidate.  We do not, in ge=
neral,
@@ -7665,7 +8676,7 @@
     ++CandsShown;
=20
     if (Cand->Function)
-      NoteFunctionCandidate(S, Cand, Args, NumArgs);
+      NoteFunctionCandidate(S, Cand, Args.size());
     else if (Cand->IsSurrogate)
       NoteSurrogateCandidate(S, Cand);
     else {
@@ -7854,7 +8865,7 @@
       return false;
=20
     if (FunctionDecl *FunDecl =3D dyn_cast<FunctionDecl>(Fn)) {
-      if (S.getLangOptions().CUDA)
+      if (S.getLangOpts().CUDA)
         if (FunctionDecl *Caller =3D dyn_cast<FunctionDecl>(S.CurContext))
           if (S.CheckCUDATarget(Caller, FunDecl))
             return false;
@@ -7932,7 +8943,7 @@
                              << Matches[0].second->getDeclName(),
                            S.PDiag(diag::note_ovl_candidate)
                              << (unsigned) oc_function_template,
-                           Complain);
+                           Complain, TargetFunctionType);
=20
     if (Result !=3D MatchesCopy.end()) {
       // Make it the first and only element
@@ -7961,7 +8972,7 @@
     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
         << OvlExpr->getName() << TargetFunctionType
         << OvlExpr->getSourceRange();
-    S.NoteAllOverloadCandidates(OvlExpr);
+    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
   }=20
  =20
   bool IsInvalidFormOfPointerToMemberFunction() const {
@@ -7987,9 +8998,11 @@
     S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
       << OvlExpr->getName()
       << OvlExpr->getSourceRange();
-    S.NoteAllOverloadCandidates(OvlExpr);
-  }
- =20
+    S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
+  }
+
+  bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1)=
; }
+
   int getNumMatches() const { return Matches.size(); }
  =20
   FunctionDecl* getMatchingFunctionDecl() const {
@@ -8019,16 +9032,18 @@
 /// resolved, and NULL otherwise. When @p Complain is true, this
 /// routine will emit diagnostics if there is an error.
 FunctionDecl *
-Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType Tar=
getType,
-                                    bool Complain,
-                                    DeclAccessPair &FoundResult) {
-
+Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
+                                         QualType TargetType,
+                                         bool Complain,
+                                         DeclAccessPair &FoundResult,
+                                         bool *pHadMultipleCandidates) {
   assert(AddressOfExpr->getType() =3D=3D Context.OverloadTy);
- =20
-  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Com=
plain);
+
+  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
+                                     Complain);
   int NumMatches =3D Resolver.getNumMatches();
   FunctionDecl* Fn =3D 0;
-  if ( NumMatches =3D=3D 0 && Complain) {
+  if (NumMatches =3D=3D 0 && Complain) {
     if (Resolver.IsInvalidFormOfPointerToMemberFunction())
       Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
     else
@@ -8040,11 +9055,13 @@
     Fn =3D Resolver.getMatchingFunctionDecl();
     assert(Fn);
     FoundResult =3D *Resolver.getMatchingFunctionAccessPair();
-    MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
+    MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
     if (Complain)
       CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
   }
- =20
+
+  if (pHadMultipleCandidates)
+    *pHadMultipleCandidates =3D Resolver.hadMultipleCandidates();
   return Fn;
 }
=20
@@ -8146,7 +9163,7 @@
   ExprResult SingleFunctionExpression;
   if (FunctionDecl *fn =3D ResolveSingleFunctionTemplateSpecialization(
                            ovl.Expression, /*complain*/ false, &found)) {
-    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin()))=
 {
+    if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
       SrcExpr =3D ExprError();
       return true;
     }
@@ -8212,7 +9229,7 @@
 static void AddOverloadedCallCandidate(Sema &S,
                                        DeclAccessPair FoundDecl,
                                  TemplateArgumentListInfo *ExplicitTemplat=
eArgs,
-                                       Expr **Args, unsigned NumArgs,
+                                       llvm::ArrayRef<Expr *> Args,
                                        OverloadCandidateSet &CandidateSet,
                                        bool PartialOverloading,
                                        bool KnownValid) {
@@ -8225,16 +9242,15 @@
       assert(!KnownValid && "Explicit template arguments?");
       return;
     }
-    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
-                           false, PartialOverloading);
+    S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
+                           PartialOverloading);
     return;
   }
=20
   if (FunctionTemplateDecl *FuncTemplate
       =3D dyn_cast<FunctionTemplateDecl>(Callee)) {
     S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
-                                   ExplicitTemplateArgs,
-                                   Args, NumArgs, CandidateSet);
+                                   ExplicitTemplateArgs, Args, CandidateSe=
t);
     return;
   }
=20
@@ -8244,7 +9260,7 @@
 /// \brief Add the overload candidates named by callee and/or found by arg=
ument
 /// dependent lookup to the given overload set.
 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
-                                       Expr **Args, unsigned NumArgs,
+                                       llvm::ArrayRef<Expr *> Args,
                                        OverloadCandidateSet &CandidateSet,
                                        bool PartialOverloading) {
=20
@@ -8287,16 +9303,15 @@
=20
   for (UnresolvedLookupExpr::decls_iterator I =3D ULE->decls_begin(),
          E =3D ULE->decls_end(); I !=3D E; ++I)
-    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
-                               Args, NumArgs, CandidateSet,
-                               PartialOverloading, /*KnownValid*/ true);
+    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, A=
rgs,
+                               CandidateSet, PartialOverloading,
+                               /*KnownValid*/ true);
=20
   if (ULE->requiresADL())
     AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ fals=
e,
-                                         Args, NumArgs,
-                                         ExplicitTemplateArgs,
-                                         CandidateSet,
-                                         PartialOverloading,
+                                         ULE->getExprLoc(),
+                                         Args, ExplicitTemplateArgs,
+                                         CandidateSet, PartialOverloading,
                                          ULE->isStdAssociatedNamespace());
 }
=20
@@ -8310,11 +9325,14 @@
 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
                        const CXXScopeSpec &SS, LookupResult &R,
                        TemplateArgumentListInfo *ExplicitTemplateArgs,
-                       Expr **Args, unsigned NumArgs) {
+                       llvm::ArrayRef<Expr *> Args) {
   if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
     return false;
=20
   for (DeclContext *DC =3D SemaRef.CurContext; DC; DC =3D DC->getParent())=
 {
+    if (DC->isTransparentContext())
+      continue;
+
     SemaRef.LookupQualifiedName(R, DC);
=20
     if (!R.empty()) {
@@ -8330,7 +9348,7 @@
       OverloadCandidateSet Candidates(FnLoc);
       for (LookupResult::iterator I =3D R.begin(), E =3D R.end(); I !=3D E=
; ++I)
         AddOverloadedCallCandidate(SemaRef, I.getPair(),
-                                   ExplicitTemplateArgs, Args, NumArgs,
+                                   ExplicitTemplateArgs, Args,
                                    Candidates, false, /*KnownValid*/ false=
);
=20
       OverloadCandidateSet::iterator Best;
@@ -8345,7 +9363,7 @@
       // declaring the function there instead.
       Sema::AssociatedNamespaceSet AssociatedNamespaces;
       Sema::AssociatedClassSet AssociatedClasses;
-      SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
+      SemaRef.FindAssociatedClassesAndNamespaces(Args,
                                                  AssociatedNamespaces,
                                                  AssociatedClasses);
       // Never suggest declaring a function within namespace 'std'.=20
@@ -8399,12 +9417,75 @@
 static bool
 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
                                SourceLocation OpLoc,
-                               Expr **Args, unsigned NumArgs) {
+                               llvm::ArrayRef<Expr *> Args) {
   DeclarationName OpName =3D
     SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
   LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
   return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
-                                /*ExplicitTemplateArgs=3D*/0, Args, NumArg=
s);
+                                /*ExplicitTemplateArgs=3D*/0, Args);
+}
+
+namespace {
+// Callback to limit the allowed keywords and to only accept typo correcti=
ons
+// that are keywords or whose decls refer to functions (or template functi=
ons)
+// that accept the given number of arguments.
+class RecoveryCallCCC : public CorrectionCandidateCallback {
+ public:
+  RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplat=
eArgs)
+      : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs)=
 {
+    WantTypeSpecifiers =3D SemaRef.getLangOpts().CPlusPlus;
+    WantRemainingKeywords =3D false;
+  }
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    if (!candidate.getCorrectionDecl())
+      return candidate.isKeyword();
+
+    for (TypoCorrection::const_decl_iterator DI =3D candidate.begin(),
+           DIEnd =3D candidate.end(); DI !=3D DIEnd; ++DI) {
+      FunctionDecl *FD =3D 0;
+      NamedDecl *ND =3D (*DI)->getUnderlyingDecl();
+      if (FunctionTemplateDecl *FTD =3D dyn_cast<FunctionTemplateDecl>(ND))
+        FD =3D FTD->getTemplatedDecl();
+      if (!HasExplicitTemplateArgs && !FD) {
+        if (!(FD =3D dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
+          // If the Decl is neither a function nor a template function,
+          // determine if it is a pointer or reference to a function. If s=
o,
+          // check against the number of arguments expected for the pointe=
e.
+          QualType ValType =3D cast<ValueDecl>(ND)->getType();
+          if (ValType->isAnyPointerType() || ValType->isReferenceType())
+            ValType =3D ValType->getPointeeType();
+          if (const FunctionProtoType *FPT =3D ValType->getAs<FunctionProt=
oType>())
+            if (FPT->getNumArgs() =3D=3D NumArgs)
+              return true;
+        }
+      }
+      if (FD && FD->getNumParams() >=3D NumArgs &&
+          FD->getMinRequiredArguments() <=3D NumArgs)
+        return true;
+    }
+    return false;
+  }
+
+ private:
+  unsigned NumArgs;
+  bool HasExplicitTemplateArgs;
+};
+
+// Callback that effectively disabled typo correction
+class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
+ public:
+  NoTypoCorrectionCCC() {
+    WantTypeSpecifiers =3D false;
+    WantExpressionKeywords =3D false;
+    WantCXXNamedCasts =3D false;
+    WantRemainingKeywords =3D false;
+  }
+
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    return false;
+  }
+};
 }
=20
 /// Attempts to recover from a call where no functions were found.
@@ -8414,12 +9495,13 @@
 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
                       UnresolvedLookupExpr *ULE,
                       SourceLocation LParenLoc,
-                      Expr **Args, unsigned NumArgs,
+                      llvm::MutableArrayRef<Expr *> Args,
                       SourceLocation RParenLoc,
-                      bool EmptyLookup) {
+                      bool EmptyLookup, bool AllowTypoCorrection) {
=20
   CXXScopeSpec SS;
   SS.Adopt(ULE->getQualifierLoc());
+  SourceLocation TemplateKWLoc =3D ULE->getTemplateKeywordLoc();
=20
   TemplateArgumentListInfo TABuffer;
   TemplateArgumentListInfo *ExplicitTemplateArgs =3D 0;
@@ -8430,11 +9512,16 @@
=20
   LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
                  Sema::LookupOrdinaryName);
+  RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs !=
=3D 0);
+  NoTypoCorrectionCCC RejectAll;
+  CorrectionCandidateCallback *CCC =3D AllowTypoCorrection ?
+      (CorrectionCandidateCallback*)&Validator :
+      (CorrectionCandidateCallback*)&RejectAll;
   if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
-                              ExplicitTemplateArgs, Args, NumArgs) &&
+                              ExplicitTemplateArgs, Args) &&
       (!EmptyLookup ||
-       SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
-                                   ExplicitTemplateArgs, Args, NumArgs)))
+       SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
+                                   ExplicitTemplateArgs, Args)))
     return ExprError();
=20
   assert(!R.empty() && "lookup results empty despite recovery");
@@ -8443,10 +9530,11 @@
   // casts and such from the call, we don't really care.
   ExprResult NewFn =3D ExprError();
   if ((*R.begin())->isCXXClassMember())
-    NewFn =3D SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
-                                                    ExplicitTemplateArgs);
-  else if (ExplicitTemplateArgs)
-    NewFn =3D SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateA=
rgs);
+    NewFn =3D SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
+                                                    R, ExplicitTemplateArg=
s);
+  else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
+    NewFn =3D SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
+                                        ExplicitTemplateArgs);
   else
     NewFn =3D SemaRef.BuildDeclarationNameExpr(SS, R, false);
=20
@@ -8457,7 +9545,8 @@
   // an expression with viable lookup results, which should never
   // end up here.
   return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
-                               MultiExprArg(Args, NumArgs), RParenLoc);
+                               MultiExprArg(Args.data(), Args.size()),
+                               RParenLoc);
 }
=20
 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
@@ -8472,7 +9561,8 @@
                               SourceLocation LParenLoc,
                               Expr **Args, unsigned NumArgs,
                               SourceLocation RParenLoc,
-                              Expr *ExecConfig) {
+                              Expr *ExecConfig,
+                              bool AllowTypoCorrection) {
 #ifndef NDEBUG
   if (ULE->requiresADL()) {
     // To do ADL, we must have found an unqualified name.
@@ -8487,17 +9577,22 @@
       llvm_unreachable("performing ADL for builtin");
=20
     // We don't perform ADL in C.
-    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
+    assert(getLangOpts().CPlusPlus && "ADL enabled in C");
   } else
     assert(!ULE->isStdAssociatedNamespace() &&
            "std is associated namespace but not doing ADL");
 #endif
=20
+  UnbridgedCastsSet UnbridgedCasts;
+  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts=
))
+    return ExprError();
+
   OverloadCandidateSet CandidateSet(Fn->getExprLoc());
=20
   // Add the functions denoted by the callee to the set of candidate
   // functions, including those from argument-dependent lookup.
-  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
+  AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
+                              CandidateSet);
=20
   // If we found nothing, try to recover.
   // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
@@ -8507,26 +9602,29 @@
     // create a type dependent CallExpr. The goal is to postpone name look=
up
     // to instantiation time to be able to search into type dependent base
     // classes.
-    if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() =
&&=20
-        isa<CXXMethodDecl>(CurContext)) {
+    if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&=20
+        (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext)))=
 {
       CallExpr *CE =3D new (Context) CallExpr(Context, Fn, Args, NumArgs,
                                           Context.DependentTy, VK_RValue,
                                           RParenLoc);
       CE->setTypeDependent(true);
       return Owned(CE);
     }
-    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumAr=
gs,
-                                 RParenLoc, /*EmptyLookup=3D*/true);
-  }
+    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
+                                 llvm::MutableArrayRef<Expr *>(Args, NumAr=
gs),
+                                 RParenLoc, /*EmptyLookup=3D*/true,
+                                 AllowTypoCorrection);
+  }
+
+  UnbridgedCasts.restore();
=20
   OverloadCandidateSet::iterator Best;
   switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best))=
 {
   case OR_Success: {
     FunctionDecl *FDecl =3D Best->Function;
-    MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
+    MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
     CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
-    DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
-                      ULE->getNameLoc());
+    DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
     Fn =3D FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
     return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RPar=
enLoc,
                                  ExecConfig);
@@ -8536,34 +9634,45 @@
     // Try to recover by looking for viable functions which the user might
     // have meant to call.
     ExprResult Recovery =3D BuildRecoveryCallExpr(*this, S, Fn, ULE, LPare=
nLoc,
-                                                Args, NumArgs, RParenLoc,
-                                                /*EmptyLookup=3D*/false);
+                                  llvm::MutableArrayRef<Expr *>(Args, NumA=
rgs),
+                                                RParenLoc,
+                                                /*EmptyLookup=3D*/false,
+                                                AllowTypoCorrection);
     if (!Recovery.isInvalid())
       return Recovery;
=20
-    Diag(Fn->getSourceRange().getBegin(),
+    Diag(Fn->getLocStart(),
          diag::err_ovl_no_viable_function_in_call)
       << ULE->getName() << Fn->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     break;
   }
=20
   case OR_Ambiguous:
-    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
+    Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
       << ULE->getName() << Fn->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs=
);
+    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     break;
=20
   case OR_Deleted:
     {
-      Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
+      Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
         << Best->Function->isDeleted()
         << ULE->getName()
         << getDeletedOrUnavailableSuffix(Best->Function)
         << Fn->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
-    }
-    break;
+      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                  llvm::makeArrayRef(Args, NumArgs));
+
+      // We emitted an error for the unvailable/deleted function call but =
keep
+      // the call in the AST.
+      FunctionDecl *FDecl =3D Best->Function;
+      Fn =3D FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
+      return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
+                                   RParenLoc, ExecConfig);
+    }
   }
=20
   // Overload resolution failed.
@@ -8603,12 +9712,8 @@
   // TODO: provide better source location info.
   DeclarationNameInfo OpNameInfo(OpName, OpLoc);
=20
-  if (Input->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Result =3D ConvertPropertyForRValue(Input);
-    if (Result.isInvalid())
-      return ExprError();
-    Input =3D Result.take();
-  }
+  if (checkPlaceholderForOverload(*this, Input))
+    return ExprError();
=20
   Expr *Args[2] =3D { Input, 0 };
   unsigned NumArgs =3D 1;
@@ -8648,14 +9753,15 @@
   OverloadCandidateSet CandidateSet(OpLoc);
=20
   // Add the candidates from the given function set.
-  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
+  AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateS=
et,
+                        false);
=20
   // Add operator candidates that are member functions.
   AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
=20
   // Add candidates from ADL.
   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
-                                       Args, NumArgs,
+                                       OpLoc, llvm::makeArrayRef(Args, Num=
Args),
                                        /*ExplicitTemplateArgs*/ 0,
                                        CandidateSet);
=20
@@ -8675,7 +9781,7 @@
       // We matched an overloaded operator. Build a call to that
       // operator.
=20
-      MarkDeclarationReferenced(OpLoc, FnDecl);
+      MarkFunctionReferenced(OpLoc, FnDecl);
=20
       // Convert the arguments.
       if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(FnDecl)) {
@@ -8709,7 +9815,7 @@
=20
       // Build the actual expression node.
       ExprResult FnExpr =3D CreateFunctionRefExpr(*this, FnDecl,
-                                                HadMultipleCandidates);
+                                                HadMultipleCandidates, OpL=
oc);
       if (FnExpr.isInvalid())
         return ExprError();
=20
@@ -8741,7 +9847,8 @@
     // This is an erroneous use of an operator which can be overloaded by
     // a non-member function. Check for non-member operators which were
     // defined too late to be candidates.
-    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
+    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
+                                       llvm::makeArrayRef(Args, NumArgs)))
       // FIXME: Recover by calling the found function.
       return ExprError();
=20
@@ -8754,7 +9861,8 @@
         << UnaryOperator::getOpcodeStr(Opc)
         << Input->getType()
         << Input->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
+    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
+                                llvm::makeArrayRef(Args, NumArgs),
                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
     return ExprError();
=20
@@ -8764,7 +9872,8 @@
       << UnaryOperator::getOpcodeStr(Opc)
       << getDeletedOrUnavailableSuffix(Best->Function)
       << Input->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
+    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                llvm::makeArrayRef(Args, NumArgs),
                                 UnaryOperator::getOpcodeStr(Opc), OpLoc);
     return ExprError();
   }
@@ -8841,45 +9950,15 @@
                                                    OpLoc));
   }
=20
-  // Always do property rvalue conversions on the RHS.
-  if (Args[1]->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Result =3D ConvertPropertyForRValue(Args[1]);
-    if (Result.isInvalid())
-      return ExprError();
-    Args[1] =3D Result.take();
-  }
-
-  // The LHS is more complicated.
-  if (Args[0]->getObjectKind() =3D=3D OK_ObjCProperty) {
-
-    // There's a tension for assignment operators between primitive
-    // property assignment and the overloaded operators.
-    if (BinaryOperator::isAssignmentOp(Opc)) {
-      const ObjCPropertyRefExpr *PRE =3D LHS->getObjCProperty();
-
-      // Is the property "logically" settable?
-      bool Settable =3D (PRE->isExplicitProperty() ||
-                       PRE->getImplicitPropertySetter());
-
-      // To avoid gratuitously inventing semantics, use the primitive
-      // unless it isn't.  Thoughts in case we ever really care:
-      // - If the property isn't logically settable, we have to
-      //   load and hope.
-      // - If the property is settable and this is simple assignment,
-      //   we really should use the primitive.
-      // - If the property is settable, then we could try overloading
-      //   on a generic lvalue of the appropriate type;  if it works
-      //   out to a builtin candidate, we would do that same operation
-      //   on the property, and otherwise just error.
-      if (Settable)
-        return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
-    }
-
-    ExprResult Result =3D ConvertPropertyForRValue(Args[0]);
-    if (Result.isInvalid())
-      return ExprError();
-    Args[0] =3D Result.take();
-  }
+  // Always do placeholder-like conversions on the RHS.
+  if (checkPlaceholderForOverload(*this, Args[1]))
+    return ExprError();
+
+  // Do placeholder-like conversion on the LHS; note that we should
+  // not get here with a PseudoObject LHS.
+  assert(Args[0]->getObjectKind() !=3D OK_ObjCProperty);
+  if (checkPlaceholderForOverload(*this, Args[0]))
+    return ExprError();
=20
   // If this is the assignment operator, we only perform overload resoluti=
on
   // if the left-hand side is a class or enumeration type. This is actually
@@ -8899,14 +9978,14 @@
   OverloadCandidateSet CandidateSet(OpLoc);
=20
   // Add the candidates from the given function set.
-  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
+  AddFunctionCandidates(Fns, Args, CandidateSet, false);
=20
   // Add operator candidates that are member functions.
   AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
=20
   // Add candidates from ADL.
   AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
-                                       Args, 2,
+                                       OpLoc, Args,
                                        /*ExplicitTemplateArgs*/ 0,
                                        CandidateSet);
=20
@@ -8926,7 +10005,7 @@
         // We matched an overloaded operator. Build a call to that
         // operator.
=20
-        MarkDeclarationReferenced(OpLoc, FnDecl);
+        MarkFunctionReferenced(OpLoc, FnDecl);
=20
         // Convert the arguments.
         if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(FnDecl)) {
@@ -9032,7 +10111,7 @@
         // This is an erroneous use of an operator which can be overloaded=
 by
         // a non-member function. Check for non-member operators which were
         // defined too late to be candidates.
-        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
+        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
           // FIXME: Recover by calling the found function.
           return ExprError();
=20
@@ -9043,7 +10122,7 @@
       assert(Result.isInvalid() &&
              "C++ binary operator overloading is missing candidates!");
       if (Result.isInvalid())
-        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
+        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
                                     BinaryOperator::getOpcodeStr(Opc), OpL=
oc);
       return move(Result);
     }
@@ -9053,17 +10132,32 @@
           << BinaryOperator::getOpcodeStr(Opc)
           << Args[0]->getType() << Args[1]->getType()
           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
+      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
                                   BinaryOperator::getOpcodeStr(Opc), OpLoc=
);
       return ExprError();
=20
     case OR_Deleted:
-      Diag(OpLoc, diag::err_ovl_deleted_oper)
-        << Best->Function->isDeleted()
-        << BinaryOperator::getOpcodeStr(Opc)
-        << getDeletedOrUnavailableSuffix(Best->Function)
-        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
+      if (isImplicitlyDeleted(Best->Function)) {
+        CXXMethodDecl *Method =3D cast<CXXMethodDecl>(Best->Function);
+        Diag(OpLoc, diag::err_ovl_deleted_special_oper)
+          << getSpecialMember(Method)
+          << BinaryOperator::getOpcodeStr(Opc)
+          << getDeletedOrUnavailableSuffix(Best->Function);
+
+        if (getSpecialMember(Method) !=3D CXXInvalid) {
+          // The user probably meant to call this special member. Just
+          // explain why it's deleted.
+          NoteDeletedFunction(Method);
+          return ExprError();
+        }
+      } else {
+        Diag(OpLoc, diag::err_ovl_deleted_oper)
+          << Best->Function->isDeleted()
+          << BinaryOperator::getOpcodeStr(Opc)
+          << getDeletedOrUnavailableSuffix(Best->Function)
+          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
+      }
+      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
                                   BinaryOperator::getOpcodeStr(Opc), OpLoc=
);
       return ExprError();
   }
@@ -9103,18 +10197,11 @@
                                                    RLoc));
   }
=20
-  if (Args[0]->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Result =3D ConvertPropertyForRValue(Args[0]);
-    if (Result.isInvalid())
-      return ExprError();
-    Args[0] =3D Result.take();
-  }
-  if (Args[1]->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Result =3D ConvertPropertyForRValue(Args[1]);
-    if (Result.isInvalid())
-      return ExprError();
-    Args[1] =3D Result.take();
-  }
+  // Handle placeholders on both operands.
+  if (checkPlaceholderForOverload(*this, Args[0]))
+    return ExprError();
+  if (checkPlaceholderForOverload(*this, Args[1]))
+    return ExprError();
=20
   // Build an empty overload set.
   OverloadCandidateSet CandidateSet(LLoc);
@@ -9140,7 +10227,7 @@
         // We matched an overloaded operator. Build a call to that
         // operator.
=20
-        MarkDeclarationReferenced(LLoc, FnDecl);
+        MarkFunctionReferenced(LLoc, FnDecl);
=20
         CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
         DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
@@ -9172,12 +10259,12 @@
         ResultTy =3D ResultTy.getNonLValueExprType(Context);
=20
         // Build the actual expression node.
-        DeclarationNameLoc LocInfo;
-        LocInfo.CXXOperatorName.BeginOpNameLoc =3D LLoc.getRawEncoding();
-        LocInfo.CXXOperatorName.EndOpNameLoc =3D RLoc.getRawEncoding();
+        DeclarationNameInfo OpLocInfo(OpName, LLoc);
+        OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
         ExprResult FnExpr =3D CreateFunctionRefExpr(*this, FnDecl,
                                                   HadMultipleCandidates,
-                                                  LLoc, LocInfo);
+                                                  OpLocInfo.getLoc(),
+                                                  OpLocInfo.getInfo());
         if (FnExpr.isInvalid())
           return ExprError();
=20
@@ -9222,7 +10309,7 @@
         Diag(LLoc, diag::err_ovl_no_viable_subscript)
           << Args[0]->getType()
           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
+      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
                                   "[]", LLoc);
       return ExprError();
     }
@@ -9232,7 +10319,7 @@
           << "[]"
           << Args[0]->getType() << Args[1]->getType()
           << Args[0]->getSourceRange() << Args[1]->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
+      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
                                   "[]", LLoc);
       return ExprError();
=20
@@ -9241,7 +10328,7 @@
         << Best->Function->isDeleted() << "[]"
         << getDeletedOrUnavailableSuffix(Best->Function)
         << Args[0]->getSourceRange() << Args[1]->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
+      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
                                   "[]", LLoc);
       return ExprError();
     }
@@ -9305,7 +10392,7 @@
                                         resultType, valueKind, RParenLoc);
=20
     if (CheckCallReturnType(proto->getResultType(),
-                            op->getRHS()->getSourceRange().getBegin(),
+                            op->getRHS()->getLocStart(),
                             call, 0))
       return ExprError();
=20
@@ -9315,6 +10402,10 @@
     return MaybeBindToTemporary(call);
   }
=20
+  UnbridgedCastsSet UnbridgedCasts;
+  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts=
))
+    return ExprError();
+
   MemberExpr *MemExpr;
   CXXMethodDecl *Method =3D 0;
   DeclAccessPair FoundDecl =3D DeclAccessPair::make(0, AS_public);
@@ -9324,6 +10415,7 @@
     Method =3D cast<CXXMethodDecl>(MemExpr->getMemberDecl());
     FoundDecl =3D MemExpr->getFoundDecl();
     Qualifier =3D MemExpr->getQualifier();
+    UnbridgedCasts.restore();
   } else {
     UnresolvedMemberExpr *UnresExpr =3D cast<UnresolvedMemberExpr>(NakedMe=
mExpr);
     Qualifier =3D UnresExpr->getQualifier();
@@ -9353,9 +10445,9 @@
=20
=20
       // Microsoft supports direct constructor calls.
-      if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
-        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), =
Args, NumArgs,
-                             CandidateSet);
+      if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
+        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
+                             llvm::makeArrayRef(Args, NumArgs), CandidateS=
et);
       } else if ((Method =3D dyn_cast<CXXMethodDecl>(Func))) {
         // If explicit template arguments were provided, we can't call a
         // non-template member function.
@@ -9364,25 +10456,28 @@
=20
         AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
                            ObjectClassification,
-                           Args, NumArgs, CandidateSet,
+                           llvm::makeArrayRef(Args, NumArgs), CandidateSet,
                            /*SuppressUserConversions=3D*/false);
       } else {
         AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
                                    I.getPair(), ActingDC, TemplateArgs,
                                    ObjectType,  ObjectClassification,
-                                   Args, NumArgs, CandidateSet,
+                                   llvm::makeArrayRef(Args, NumArgs),
+                                   CandidateSet,
                                    /*SuppressUsedConversions=3D*/false);
       }
     }
=20
     DeclarationName DeclName =3D UnresExpr->getMemberName();
=20
+    UnbridgedCasts.restore();
+
     OverloadCandidateSet::iterator Best;
     switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(=
),
                                             Best)) {
     case OR_Success:
       Method =3D cast<CXXMethodDecl>(Best->Function);
-      MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
+      MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
       FoundDecl =3D Best->FoundDecl;
       CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
       DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
@@ -9392,14 +10487,16 @@
       Diag(UnresExpr->getMemberLoc(),
            diag::err_ovl_no_viable_member_function_in_call)
         << DeclName << MemExprE->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                  llvm::makeArrayRef(Args, NumArgs));
       // FIXME: Leaking incoming expressions!
       return ExprError();
=20
     case OR_Ambiguous:
       Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
         << DeclName << MemExprE->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                  llvm::makeArrayRef(Args, NumArgs));
       // FIXME: Leaking incoming expressions!
       return ExprError();
=20
@@ -9409,7 +10506,8 @@
         << DeclName=20
         << getDeletedOrUnavailableSuffix(Best->Function)
         << MemExprE->getSourceRange();
-      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+      CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                  llvm::makeArrayRef(Args, NumArgs));
       // FIXME: Leaking incoming expressions!
       return ExprError();
     }
@@ -9459,6 +10557,8 @@
                               RParenLoc))
     return ExprError();
=20
+  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
+
   if (CheckFunctionCall(Method, TheCall))
     return ExprError();
=20
@@ -9488,12 +10588,13 @@
                                    SourceLocation LParenLoc,
                                    Expr **Args, unsigned NumArgs,
                                    SourceLocation RParenLoc) {
+  if (checkPlaceholderForOverload(*this, Obj))
+    return ExprError();
   ExprResult Object =3D Owned(Obj);
-  if (Object.get()->getObjectKind() =3D=3D OK_ObjCProperty) {
-    Object =3D ConvertPropertyForRValue(Object.take());
-    if (Object.isInvalid())
-      return ExprError();
-  }
+
+  UnbridgedCastsSet UnbridgedCasts;
+  if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts=
))
+    return ExprError();
=20
   assert(Object.get()->getType()->isRecordType() && "Requires object type =
argument");
   const RecordType *Record =3D Object.get()->getType()->getAs<RecordType>(=
);
@@ -9566,7 +10667,8 @@
       if (const FunctionProtoType *Proto =3D ConvType->getAs<FunctionProto=
Type>())
       {
         AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
-                              Object.get(), Args, NumArgs, CandidateSet);
+                              Object.get(), llvm::makeArrayRef(Args, NumAr=
gs),
+                              CandidateSet);
       }
     }
   }
@@ -9584,37 +10686,42 @@
=20
   case OR_No_Viable_Function:
     if (CandidateSet.empty())
-      Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_ope=
r)
+      Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
         << Object.get()->getType() << /*call*/ 1
         << Object.get()->getSourceRange();
     else
-      Diag(Object.get()->getSourceRange().getBegin(),
+      Diag(Object.get()->getLocStart(),
            diag::err_ovl_no_viable_object_call)
         << Object.get()->getType() << Object.get()->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     break;
=20
   case OR_Ambiguous:
-    Diag(Object.get()->getSourceRange().getBegin(),
+    Diag(Object.get()->getLocStart(),
          diag::err_ovl_ambiguous_object_call)
       << Object.get()->getType() << Object.get()->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs=
);
+    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     break;
=20
   case OR_Deleted:
-    Diag(Object.get()->getSourceRange().getBegin(),
+    Diag(Object.get()->getLocStart(),
          diag::err_ovl_deleted_object_call)
       << Best->Function->isDeleted()
       << Object.get()->getType()=20
       << getDeletedOrUnavailableSuffix(Best->Function)
       << Object.get()->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
+    CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
+                                llvm::makeArrayRef(Args, NumArgs));
     break;
   }
=20
   if (Best =3D=3D CandidateSet.end())
     return true;
=20
+  UnbridgedCasts.restore();
+
   if (Best->Function =3D=3D 0) {
     // Since there is no function declaration, this is one of the
     // surrogate candidates. Dig out the conversion function.
@@ -9635,12 +10742,16 @@
                                              Conv, HadMultipleCandidates);
     if (Call.isInvalid())
       return ExprError();
+    // Record usage of conversion in an implicit cast.
+    Call =3D Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
+                                          CK_UserDefinedConversion,
+                                          Call.get(), 0, VK_RValue));
=20
     return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumA=
rgs),
                          RParenLoc);
   }
=20
-  MarkDeclarationReferenced(LParenLoc, Best->Function);
+  MarkFunctionReferenced(LParenLoc, Best->Function);
   CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
   DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
=20
@@ -9668,8 +10779,13 @@
   for (unsigned ArgIdx =3D 0; ArgIdx < NumArgs; ++ArgIdx)
     MethodArgs[ArgIdx + 1] =3D Args[ArgIdx];
=20
+  DeclarationNameInfo OpLocInfo(
+               Context.DeclarationNames.getCXXOperatorName(OO_Call), LPare=
nLoc);
+  OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
   ExprResult NewFn =3D CreateFunctionRefExpr(*this, Method,
-                                           HadMultipleCandidates);
+                                           HadMultipleCandidates,
+                                           OpLocInfo.getLoc(),
+                                           OpLocInfo.getInfo());
   if (NewFn.isInvalid())
     return true;
=20
@@ -9750,6 +10866,8 @@
=20
   if (IsError) return true;
=20
+  DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
+
   if (CheckFunctionCall(Method, TheCall))
     return true;
=20
@@ -9764,12 +10882,8 @@
   assert(Base->getType()->isRecordType() &&
          "left-hand side must have class type");
=20
-  if (Base->getObjectKind() =3D=3D OK_ObjCProperty) {
-    ExprResult Result =3D ConvertPropertyForRValue(Base);
-    if (Result.isInvalid())
-      return ExprError();
-    Base =3D Result.take();
-  }
+  if (checkPlaceholderForOverload(*this, Base))
+    return ExprError();
=20
   SourceLocation Loc =3D Base->getExprLoc();
=20
@@ -9815,13 +10929,13 @@
     else
       Diag(OpLoc, diag::err_ovl_no_viable_oper)
         << "operator->" << Base->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
+    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
     return ExprError();
=20
   case OR_Ambiguous:
     Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
       << "->" << Base->getType() << Base->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
+    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
     return ExprError();
=20
   case OR_Deleted:
@@ -9830,11 +10944,11 @@
       << "->"=20
       << getDeletedOrUnavailableSuffix(Best->Function)
       << Base->getSourceRange();
-    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
+    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
     return ExprError();
   }
=20
-  MarkDeclarationReferenced(OpLoc, Best->Function);
+  MarkFunctionReferenced(OpLoc, Best->Function);
   CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
   DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
=20
@@ -9849,7 +10963,7 @@
=20
   // Build the operator call.
   ExprResult FnExpr =3D CreateFunctionRefExpr(*this, Method,
-                                            HadMultipleCandidates);
+                                            HadMultipleCandidates, OpLoc);
   if (FnExpr.isInvalid())
     return ExprError();
=20
@@ -9867,6 +10981,80 @@
   return MaybeBindToTemporary(TheCall);
 }
=20
+/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a ca=
ll to
+/// a literal operator described by the provided lookup results.
+ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
+                                          DeclarationNameInfo &SuffixInfo,
+                                          ArrayRef<Expr*> Args,
+                                          SourceLocation LitEndLoc,
+                                       TemplateArgumentListInfo *TemplateA=
rgs) {
+  SourceLocation UDSuffixLoc =3D SuffixInfo.getCXXLiteralOperatorNameLoc();
+
+  OverloadCandidateSet CandidateSet(UDSuffixLoc);
+  AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
+                        TemplateArgs);
+
+  bool HadMultipleCandidates =3D (CandidateSet.size() > 1);
+
+  // Perform overload resolution. This will usually be trivial, but might =
need
+  // to perform substitutions for a literal operator template.
+  OverloadCandidateSet::iterator Best;
+  switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
+  case OR_Success:
+  case OR_Deleted:
+    break;
+
+  case OR_No_Viable_Function:
+    Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
+      << R.getLookupName();
+    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
+    return ExprError();
+
+  case OR_Ambiguous:
+    Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(=
);
+    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
+    return ExprError();
+  }
+
+  FunctionDecl *FD =3D Best->Function;
+  MarkFunctionReferenced(UDSuffixLoc, FD);
+  DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
+
+  ExprResult Fn =3D CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
+                                        SuffixInfo.getLoc(),
+                                        SuffixInfo.getInfo());
+  if (Fn.isInvalid())
+    return true;
+
+  // Check the argument types. This should almost always be a no-op, except
+  // that array-to-pointer decay is applied to string literals.
+  Expr *ConvArgs[2];
+  for (unsigned ArgIdx =3D 0; ArgIdx !=3D Args.size(); ++ArgIdx) {
+    ExprResult InputInit =3D PerformCopyInitialization(
+      InitializedEntity::InitializeParameter(Context, FD->getParamDecl(Arg=
Idx)),
+      SourceLocation(), Args[ArgIdx]);
+    if (InputInit.isInvalid())
+      return true;
+    ConvArgs[ArgIdx] =3D InputInit.take();
+  }
+
+  QualType ResultTy =3D FD->getResultType();
+  ExprValueKind VK =3D Expr::getValueKindForType(ResultTy);
+  ResultTy =3D ResultTy.getNonLValueExprType(Context);
+
+  UserDefinedLiteral *UDL =3D
+    new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.si=
ze(),
+                                     ResultTy, VK, LitEndLoc, UDSuffixLoc);
+
+  if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
+    return ExprError();
+
+  if (CheckFunctionCall(FD, UDL))
+    return ExprError();
+
+  return MaybeBindToTemporary(UDL);
+}
+
 /// FixOverloadedFunctionReference - E is an expression that refers to
 /// a C++ overloaded function (possibly with some parentheses and
 /// perhaps a '&' around it). We have resolved the overloaded function
@@ -9954,7 +11142,9 @@
=20
     DeclRefExpr *DRE =3D DeclRefExpr::Create(Context,
                                            ULE->getQualifierLoc(),
+                                           ULE->getTemplateKeywordLoc(),
                                            Fn,
+                                           /*enclosing*/ false, // FIXME?
                                            ULE->getNameLoc(),
                                            Fn->getType(),
                                            VK_LValue,
@@ -9980,7 +11170,9 @@
       if (cast<CXXMethodDecl>(Fn)->isStatic()) {
         DeclRefExpr *DRE =3D DeclRefExpr::Create(Context,
                                                MemExpr->getQualifierLoc(),
+                                               MemExpr->getTemplateKeyword=
Loc(),
                                                Fn,
+                                               /*enclosing*/ false,
                                                MemExpr->getMemberLoc(),
                                                Fn->getType(),
                                                VK_LValue,
@@ -9992,6 +11184,7 @@
         SourceLocation Loc =3D MemExpr->getMemberLoc();
         if (MemExpr->getQualifier())
           Loc =3D MemExpr->getQualifierLoc().getBeginLoc();
+        CheckCXXThisCapture(Loc);
         Base =3D new (Context) CXXThisExpr(Loc,
                                          MemExpr->getBaseType(),
                                          /*isImplicit=3D*/true);
@@ -10012,6 +11205,7 @@
     MemberExpr *ME =3D MemberExpr::Create(Context, Base,
                                         MemExpr->isArrow(),
                                         MemExpr->getQualifierLoc(),
+                                        MemExpr->getTemplateKeywordLoc(),
                                         Fn,
                                         Found,
                                         MemExpr->getMemberNameInfo(),
@@ -10022,7 +11216,6 @@
   }
=20
   llvm_unreachable("Invalid reference to overloaded function");
-  return E;
 }
=20
 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaStmt.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaStmt.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaStmt.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -16,8 +16,8 @@
 #include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/Initialization.h"
 #include "clang/Sema/Lookup.h"
-#include "clang/AST/APValue.h"
 #include "clang/AST/ASTContext.h"
+#include "clang/AST/CharUnits.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
@@ -78,7 +78,7 @@
   // In ARC, we don't need to retain the iteration variable of a fast
   // enumeration loop.  Rather than actually trying to catch that
   // during declaration processing, we remove the consequences here.
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     QualType type =3D var->getType();
=20
     // Only do this if we inferred the lifetime.  Inferred lifetime
@@ -152,7 +152,8 @@
=20
   SourceLocation Loc;
   SourceRange R1, R2;
-  if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
+  if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
+      !E->isUnusedResultAWarning(Loc, R1, R2, Context))
     return;
=20
   // Okay, we have an unused result.  Depending on what the base expressio=
n is,
@@ -189,7 +190,7 @@
       }
     }
   } else if (const ObjCMessageExpr *ME =3D dyn_cast<ObjCMessageExpr>(E)) {
-    if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) {
+    if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
       Diag(Loc, diag::err_arc_unused_init_message) << R1;
       return;
     }
@@ -198,8 +199,12 @@
       Diag(Loc, diag::warn_unused_result) << R1 << R2;
       return;
     }
-  } else if (isa<ObjCPropertyRefExpr>(E)) {
-    DiagID =3D diag::warn_unused_property_expr;
+  } else if (const PseudoObjectExpr *POE =3D dyn_cast<PseudoObjectExpr>(E)=
) {
+    const Expr *Source =3D POE->getSyntacticForm();
+    if (isa<ObjCSubscriptRefExpr>(Source))
+      DiagID =3D diag::warn_unused_container_subscript_expr;
+    else
+      DiagID =3D diag::warn_unused_property_expr;
   } else if (const CXXFunctionalCastExpr *FC
                                        =3D dyn_cast<CXXFunctionalCastExpr>=
(E)) {
     if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
@@ -224,6 +229,18 @@
   DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
 }
=20
+void Sema::ActOnStartOfCompoundStmt() {
+  PushCompoundScope();
+}
+
+void Sema::ActOnFinishOfCompoundStmt() {
+  PopCompoundScope();
+}
+
+sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
+  return getCurFunction()->CompoundScopes.back();
+}
+
 StmtResult
 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
                         MultiStmtArg elts, bool isStmtExpr) {
@@ -231,7 +248,7 @@
   Stmt **Elts =3D reinterpret_cast<Stmt**>(elts.release());
   // If we're in C89 mode, check that we don't have any decls after stmts.=
  If
   // so, emit an extension diagnostic.
-  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
+  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
     // Note that __extension__ can be around a decl.
     unsigned i =3D 0;
     // Skip over all declarations.
@@ -256,6 +273,15 @@
     DiagnoseUnusedExprResult(Elts[i]);
   }
=20
+  // Check for suspicious empty body (null statement) in `for' and `while'
+  // statements.  Don't do anything for template instantiations, this just=
 adds
+  // noise.
+  if (NumElts !=3D 0 && !CurrentInstantiationScope &&
+      getCurCompoundScope().HasEmptyLoopBodies) {
+    for (unsigned i =3D 0; i !=3D NumElts - 1; ++i)
+      DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
+  }
+
   return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
 }
=20
@@ -265,24 +291,28 @@
                     SourceLocation ColonLoc) {
   assert((LHSVal !=3D 0) && "missing expression in case statement");
=20
-  // C99 6.8.4.2p3: The expression shall be an integer constant.
-  // However, GCC allows any evaluatable integer expression.
-  if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
-      VerifyIntegerConstantExpression(LHSVal))
-    return StmtError();
-
-  // GCC extension: The expression shall be an integer constant.
-
-  if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() =
&&
-      VerifyIntegerConstantExpression(RHSVal)) {
-    RHSVal =3D 0;  // Recover by just forgetting about it.
-  }
-
   if (getCurFunction()->SwitchStack.empty()) {
     Diag(CaseLoc, diag::err_case_not_in_switch);
     return StmtError();
   }
=20
+  if (!getLangOpts().CPlusPlus0x) {
+    // C99 6.8.4.2p3: The expression shall be an integer constant.
+    // However, GCC allows any evaluatable integer expression.
+    if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
+      LHSVal =3D VerifyIntegerConstantExpression(LHSVal).take();
+      if (!LHSVal)
+        return StmtError();
+    }
+
+    // GCC extension: The expression shall be an integer constant.
+
+    if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent(=
)) {
+      RHSVal =3D VerifyIntegerConstantExpression(RHSVal).take();
+      // Recover from an error by just forgetting about it.
+    }
+  }
+
   CaseStmt *CS =3D new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotD=
otLoc,
                                         ColonLoc);
   getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
@@ -350,21 +380,9 @@
=20
   DiagnoseUnusedExprResult(thenStmt);
=20
-  // Warn if the if block has a null body without an else value.
-  // this helps prevent bugs due to typos, such as
-  // if (condition);
-  //   do_stuff();
-  //
   if (!elseStmt) {
-    if (NullStmt* stmt =3D dyn_cast<NullStmt>(thenStmt))
-      // But do not warn if the body is a macro that expands to nothing, e=
.g:
-      //
-      // #define CALL(x)
-      // if (condition)
-      //   CALL(0);
-      //
-      if (!stmt->hasLeadingEmptyMacro())
-        Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
+    DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
+                          diag::warn_empty_if_body);
   }
=20
   DiagnoseUnusedExprResult(elseStmt);
@@ -501,7 +519,8 @@
                                          PDiag(diag::note_switch_conversio=
n),
                                    PDiag(diag::err_switch_multiple_convers=
ions),
                                          PDiag(diag::note_switch_conversio=
n),
-                                         PDiag(0));
+                                         PDiag(0),
+                                         /*AllowScopedEnumerations*/ true);
   if (CondResult.isInvalid()) return StmtError();
   Cond =3D CondResult.take();
=20
@@ -617,8 +636,6 @@
     } else {
       CaseStmt *CS =3D cast<CaseStmt>(SC);
=20
-      // We already verified that the expression has a i-c-e value (C99
-      // 6.8.4.2p3) - get that value now.
       Expr *Lo =3D CS->getLHS();
=20
       if (Lo->isTypeDependent() || Lo->isValueDependent()) {
@@ -626,16 +643,39 @@
         break;
       }
=20
-      llvm::APSInt LoVal =3D Lo->EvaluateKnownConstInt(Context);
+      llvm::APSInt LoVal;
=20
-      // Convert the value to the same width/sign as the condition.
+      if (getLangOpts().CPlusPlus0x) {
+        // C++11 [stmt.switch]p2: the constant-expression shall be a conve=
rted
+        // constant expression of the promoted type of the switch conditio=
n.
+        ExprResult ConvLo =3D
+          CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseV=
alue);
+        if (ConvLo.isInvalid()) {
+          CaseListIsErroneous =3D true;
+          continue;
+        }
+        Lo =3D ConvLo.take();
+      } else {
+        // We already verified that the expression has a i-c-e value (C99
+        // 6.8.4.2p3) - get that value now.
+        LoVal =3D Lo->EvaluateKnownConstInt(Context);
+
+        // If the LHS is not the same type as the condition, insert an imp=
licit
+        // cast.
+        Lo =3D DefaultLvalueConversion(Lo).take();
+        Lo =3D ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
+      }
+
+      // Convert the value to the same width/sign as the condition had pri=
or to
+      // integral promotions.
+      //
+      // FIXME: This causes us to reject valid code:
+      //   switch ((char)c) { case 256: case 0: return 0; }
+      // Here we claim there is a duplicated condition value, but there is=
 not.
       ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
                                          Lo->getLocStart(),
                                          diag::warn_case_value_overflow);
=20
-      // If the LHS is not the same type as the condition, insert an impli=
cit
-      // cast.
-      Lo =3D ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
       CS->setLHS(Lo);
=20
       // If this is a case range, remember it in CaseRanges, otherwise Cas=
eVals.
@@ -656,19 +696,15 @@
     // condition is constant.
     llvm::APSInt ConstantCondValue;
     bool HasConstantCond =3D false;
-    bool ShouldCheckConstantCond =3D false;
     if (!HasDependentValue && !TheDefaultStmt) {
-      Expr::EvalResult Result;
-      HasConstantCond =3D CondExprBeforePromotion->Evaluate(Result, Contex=
t);
-      if (HasConstantCond) {
-        assert(Result.Val.isInt() && "switch condition evaluated to non-in=
t");
-        ConstantCondValue =3D Result.Val.getInt();
-        ShouldCheckConstantCond =3D true;
-
-        assert(ConstantCondValue.getBitWidth() =3D=3D CondWidth &&
-               ConstantCondValue.isSigned() =3D=3D CondIsSigned);
-      }
+      HasConstantCond
+        =3D CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Cont=
ext,
+                                                 Expr::SE_AllowSideEffects=
);
+      assert(!HasConstantCond ||
+             (ConstantCondValue.getBitWidth() =3D=3D CondWidth &&
+              ConstantCondValue.isSigned() =3D=3D CondIsSigned));
     }
+    bool ShouldCheckConstantCond =3D HasConstantCond;
=20
     // Sort all the scalar case values so we can easily detect duplicates.
     std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
@@ -705,16 +741,33 @@
         llvm::APSInt &LoVal =3D CaseRanges[i].first;
         CaseStmt *CR =3D CaseRanges[i].second;
         Expr *Hi =3D CR->getRHS();
-        llvm::APSInt HiVal =3D Hi->EvaluateKnownConstInt(Context);
+        llvm::APSInt HiVal;
+
+        if (getLangOpts().CPlusPlus0x) {
+          // C++11 [stmt.switch]p2: the constant-expression shall be a con=
verted
+          // constant expression of the promoted type of the switch condit=
ion.
+          ExprResult ConvHi =3D
+            CheckConvertedConstantExpression(Hi, CondType, HiVal,
+                                             CCEK_CaseValue);
+          if (ConvHi.isInvalid()) {
+            CaseListIsErroneous =3D true;
+            continue;
+          }
+          Hi =3D ConvHi.take();
+        } else {
+          HiVal =3D Hi->EvaluateKnownConstInt(Context);
+
+          // If the RHS is not the same type as the condition, insert an
+          // implicit cast.
+          Hi =3D DefaultLvalueConversion(Hi).take();
+          Hi =3D ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
+        }
=20
         // Convert the value to the same width/sign as the condition.
         ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
                                            Hi->getLocStart(),
                                            diag::warn_case_value_overflow);
=20
-        // If the LHS is not the same type as the condition, insert an imp=
licit
-        // cast.
-        Hi =3D ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
         CR->setRHS(Hi);
=20
         // If the low value is bigger than the high value, the case is emp=
ty.
@@ -821,39 +874,35 @@
         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
=20
       // See which case values aren't in enum.
-      // TODO: we might want to check whether case values are out of the
-      // enum even if we don't want to check whether all cases are handled.
-      if (!TheDefaultStmt) {
-        EnumValsTy::const_iterator EI =3D EnumVals.begin();
-        for (CaseValsTy::const_iterator CI =3D CaseVals.begin();
-             CI !=3D CaseVals.end(); CI++) {
-          while (EI !=3D EIend && EI->first < CI->first)
-            EI++;
-          if (EI =3D=3D EIend || EI->first > CI->first)
-            Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enu=
m)
-              << ED->getDeclName();
+      EnumValsTy::const_iterator EI =3D EnumVals.begin();
+      for (CaseValsTy::const_iterator CI =3D CaseVals.begin();
+           CI !=3D CaseVals.end(); CI++) {
+        while (EI !=3D EIend && EI->first < CI->first)
+          EI++;
+        if (EI =3D=3D EIend || EI->first > CI->first)
+          Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
+            << CondTypeBeforePromotion;
+      }
+      // See which of case ranges aren't in enum
+      EI =3D EnumVals.begin();
+      for (CaseRangesTy::const_iterator RI =3D CaseRanges.begin();
+           RI !=3D CaseRanges.end() && EI !=3D EIend; RI++) {
+        while (EI !=3D EIend && EI->first < RI->first)
+          EI++;
+
+        if (EI =3D=3D EIend || EI->first !=3D RI->first) {
+          Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
+            << CondTypeBeforePromotion;
         }
-        // See which of case ranges aren't in enum
-        EI =3D EnumVals.begin();
-        for (CaseRangesTy::const_iterator RI =3D CaseRanges.begin();
-             RI !=3D CaseRanges.end() && EI !=3D EIend; RI++) {
-          while (EI !=3D EIend && EI->first < RI->first)
-            EI++;
=20
-          if (EI =3D=3D EIend || EI->first !=3D RI->first) {
-            Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enu=
m)
-              << ED->getDeclName();
-          }
-
-          llvm::APSInt Hi =3D=20
-            RI->second->getRHS()->EvaluateKnownConstInt(Context);
-          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
-          while (EI !=3D EIend && EI->first < Hi)
-            EI++;
-          if (EI =3D=3D EIend || EI->first !=3D Hi)
-            Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enu=
m)
-              << ED->getDeclName();
-        }
+        llvm::APSInt Hi =3D=20
+          RI->second->getRHS()->EvaluateKnownConstInt(Context);
+        AdjustAPSInt(Hi, CondWidth, CondIsSigned);
+        while (EI !=3D EIend && EI->first < Hi)
+          EI++;
+        if (EI =3D=3D EIend || EI->first !=3D Hi)
+          Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
+            << CondTypeBeforePromotion;
       }
=20
       // Check which enum vals aren't in switch
@@ -863,7 +912,7 @@
=20
       SmallVector<DeclarationName,8> UnhandledNames;
=20
-      for (EnumValsTy::const_iterator EI =3D EnumVals.begin(); EI !=3D EIe=
nd; EI++){
+      for (EI =3D EnumVals.begin(); EI !=3D EIend; EI++){
         // Drop unneeded case values
         llvm::APSInt CIVal;
         while (CI !=3D CaseVals.end() && CI->first < EI->first)
@@ -883,28 +932,34 @@
=20
         if (RI =3D=3D CaseRanges.end() || EI->first < RI->first) {
           hasCasesNotInSwitch =3D true;
-          if (!TheDefaultStmt)
-            UnhandledNames.push_back(EI->second->getDeclName());
+          UnhandledNames.push_back(EI->second->getDeclName());
         }
       }
=20
+      if (TheDefaultStmt && UnhandledNames.empty())
+        Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_defau=
lt);
+
       // Produce a nice diagnostic if multiple values aren't handled.
       switch (UnhandledNames.size()) {
       case 0: break;
       case 1:
-        Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
+        Diag(CondExpr->getExprLoc(), TheDefaultStmt=20
+          ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
           << UnhandledNames[0];
         break;
       case 2:
-        Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
+        Diag(CondExpr->getExprLoc(), TheDefaultStmt=20
+          ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
           << UnhandledNames[0] << UnhandledNames[1];
         break;
       case 3:
-        Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
+        Diag(CondExpr->getExprLoc(), TheDefaultStmt
+          ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
         break;
       default:
-        Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
+        Diag(CondExpr->getExprLoc(), TheDefaultStmt
+          ? diag::warn_def_missing_cases : diag::warn_missing_cases)
           << (unsigned)UnhandledNames.size()
           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
         break;
@@ -915,6 +970,9 @@
     }
   }
=20
+  DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
+                        diag::warn_empty_switch_body);
+
   // FIXME: If the case list was broken is some way, we don't have a good =
system
   // to patch it up.  Instead, just return the whole substmt as broken.
   if (CaseListIsErroneous)
@@ -941,6 +999,9 @@
=20
   DiagnoseUnusedExprResult(Body);
=20
+  if (isa<NullStmt>(Body))
+    getCurCompoundScope().setHasEmptyLoopBodies();
+
   return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExp=
r,
                                        Body, WhileLoc));
 }
@@ -972,7 +1033,7 @@
                    Stmt *First, FullExprArg second, Decl *secondVar,
                    FullExprArg third,
                    SourceLocation RParenLoc, Stmt *Body) {
-  if (!getLangOptions().CPlusPlus) {
+  if (!getLangOpts().CPlusPlus) {
     if (DeclStmt *DS =3D dyn_cast_or_null<DeclStmt>(First)) {
       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
       // declare identifiers for objects having storage class 'auto' or
@@ -1004,6 +1065,9 @@
   DiagnoseUnusedExprResult(Third);
   DiagnoseUnusedExprResult(Body);
=20
+  if (isa<NullStmt>(Body))
+    getCurCompoundScope().setHasEmptyLoopBodies();
+
   return Owned(new (Context) ForStmt(Context, First,
                                      SecondResult.take(), ConditionVar,
                                      Third, Body, ForLoc, LParenLoc,
@@ -1015,10 +1079,18 @@
 /// x can be an arbitrary l-value expression.  Bind it up as a
 /// full-expression.
 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
+  // Reduce placeholder expressions here.  Note that this rejects the
+  // use of pseudo-object l-values in this position.
+  ExprResult result =3D CheckPlaceholderExpr(E);
+  if (result.isInvalid()) return StmtError();
+  E =3D result.take();
+
   CheckImplicitConversions(E);
-  ExprResult Result =3D MaybeCreateExprWithCleanups(E);
-  if (Result.isInvalid()) return StmtError();
-  return Owned(static_cast<Stmt*>(Result.get()));
+
+  result =3D MaybeCreateExprWithCleanups(E);
+  if (result.isInvalid()) return StmtError();
+
+  return Owned(static_cast<Stmt*>(result.take()));
 }
=20
 ExprResult
@@ -1048,13 +1120,13 @@
   ObjCInterfaceDecl *iface =3D objectType->getInterface();
=20
   // If we have a forward-declared type, we can't do this check.
-  if (iface && iface->isForwardDecl()) {
-    // This is ill-formed under ARC.
-    if (getLangOptions().ObjCAutoRefCount) {
-      Diag(forLoc, diag::err_arc_collection_forward)
-        << pointerType->getPointeeType() << collection->getSourceRange();
-    }
-
+  // Under ARC, it is an error not to have a forward-declared class.
+  if (iface &&=20
+      RequireCompleteType(forLoc, QualType(objectType, 0),
+                          getLangOpts().ObjCAutoRefCount
+                            ? PDiag(diag::err_arc_collection_forward)
+                                << collection->getSourceRange()
+                          : PDiag(0))) {
     // Otherwise, if we have any useful type information, check that
     // the type declares the appropriate method.
   } else if (iface || !objectType->qual_empty()) {
@@ -1157,8 +1229,9 @@
   // Deduce the type for the iterator variable now rather than leaving it =
to
   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
   TypeSourceInfo *InitTSI =3D 0;
-  if (Init->getType()->isVoidType() ||
-      !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI))
+  if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
+      SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) =3D=
=3D
+          Sema::DAR_Failed)
     SemaRef.Diag(Loc, diag) << Init->getType();
   if (!InitTSI) {
     Decl->setInvalidDecl();
@@ -1170,7 +1243,7 @@
   // In ARC, infer lifetime.
   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
   // we're doing the equivalent of fast iteration.
-  if (SemaRef.getLangOptions().ObjCAutoRefCount &&=20
+  if (SemaRef.getLangOpts().ObjCAutoRefCount &&=20
       SemaRef.inferObjCARCLifetime(Decl))
     Decl->setInvalidDecl();
=20
@@ -1223,7 +1296,9 @@
     ExprResult MemberRef =3D
       SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
                                        /*IsPtr=3D*/false, CXXScopeSpec(),
-                                       /*Qualifier=3D*/0, MemberLookup,
+                                       /*TemplateKWLoc=3D*/SourceLocation(=
),
+                                       /*FirstQualifierInScope=3D*/0,
+                                       MemberLookup,
                                        /*TemplateArgs=3D*/0);
     if (MemberRef.isInvalid())
       return ExprError();
@@ -1242,7 +1317,7 @@
                                    FoundNames.begin(), FoundNames.end(),
                                    /*LookInStdNamespace=3D*/true);
     CallExpr =3D SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1=
, Loc,
-                                               0);
+                                               0, /*AllowTypoCorrection=3D=
*/false);
     if (CallExpr.isInvalid()) {
       SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
         << Range->getType();
@@ -1542,7 +1617,12 @@
   if (!S || !B)
     return StmtError();
=20
-  cast<CXXForRangeStmt>(S)->setBody(B);
+  CXXForRangeStmt *ForStmt =3D cast<CXXForRangeStmt>(S);
+  ForStmt->setBody(B);
+
+  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
+                        diag::warn_empty_range_based_for_body);
+
   return S;
 }
=20
@@ -1569,6 +1649,7 @@
     E =3D ExprRes.take();
     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passi=
ng))
       return StmtError();
+    E =3D MaybeCreateExprWithCleanups(E);
   }
=20
   getCurFunction()->setHasIndirectGoto();
@@ -1639,14 +1720,29 @@
   if (!VD)
     return 0;
=20
-  if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
-      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
-      !VD->getType().isVolatileQualified() &&
-      ((VD->getKind() =3D=3D Decl::Var) ||
-       (AllowFunctionParameter && VD->getKind() =3D=3D Decl::ParmVar)))
-    return VD;
+  // ...object (other than a function or catch-clause parameter)...
+  if (VD->getKind() !=3D Decl::Var &&
+      !(AllowFunctionParameter && VD->getKind() =3D=3D Decl::ParmVar))
+    return 0;
+  if (VD->isExceptionVariable()) return 0;
=20
-  return 0;
+  // ...automatic...
+  if (!VD->hasLocalStorage()) return 0;
+
+  // ...non-volatile...
+  if (VD->getType().isVolatileQualified()) return 0;
+  if (VD->getType()->isReferenceType()) return 0;
+
+  // __block variables can't be allocated in a way that permits NRVO.
+  if (VD->hasAttr<BlocksAttr>()) return 0;
+
+  // Variables with higher required alignment than their type's ABI
+  // alignment cannot use NRVO.
+  if (VD->hasAttr<AlignedAttr>() &&
+      Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()=
))
+    return 0;
+
+  return VD;
 }
=20
 /// \brief Perform the initialization of a potentially-movable value, which
@@ -1726,42 +1822,64 @@
   return Res;
 }
=20
-/// ActOnBlockReturnStmt - Utility routine to figure out block's return ty=
pe.
+/// ActOnCapScopeReturnStmt - Utility routine to type-check return stateme=
nts
+/// for capturing scopes.
 ///
 StmtResult
-Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
-  // If this is the first return we've seen in the block, infer the type of
-  // the block from it.
-  BlockScopeInfo *CurBlock =3D getCurBlock();
-  if (CurBlock->ReturnType.isNull()) {
-    if (RetValExp) {
-      // Don't call UsualUnaryConversions(), since we don't want to do
-      // integer promotions here.
+Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
+  // If this is the first return we've seen, infer the return type.
+  // [expr.prim.lambda]p4 in C++11; block literals follow a superset of th=
ose
+  // rules which allows multiple return statements.
+  CapturingScopeInfo *CurCap =3D cast<CapturingScopeInfo>(getCurFunction()=
);
+  if (CurCap->HasImplicitReturnType) {
+    QualType ReturnT;
+    if (RetValExp && !isa<InitListExpr>(RetValExp)) {
       ExprResult Result =3D DefaultFunctionArrayLvalueConversion(RetValExp=
);
       if (Result.isInvalid())
         return StmtError();
       RetValExp =3D Result.take();
=20
-      if (!RetValExp->isTypeDependent()) {
-        CurBlock->ReturnType =3D RetValExp->getType();
-        if (BlockDeclRefExpr *CDRE =3D dyn_cast<BlockDeclRefExpr>(RetValEx=
p)) {
-          // We have to remove a 'const' added to copied-in variable which=
 was
-          // part of the implementation spec. and not the actual qualifier=
 for
-          // the variable.
-          if (CDRE->isConstQualAdded())
-            CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
-        }
-      } else
-        CurBlock->ReturnType =3D Context.DependentTy;
-    } else
-      CurBlock->ReturnType =3D Context.VoidTy;
+      if (!RetValExp->isTypeDependent())
+        ReturnT =3D RetValExp->getType();
+      else
+        ReturnT =3D Context.DependentTy;
+    } else {=20
+      if (RetValExp) {
+        // C++11 [expr.lambda.prim]p4 bans inferring the result from an
+        // initializer list, because it is not an expression (even
+        // though we represent it as one). We still deduce 'void'.
+        Diag(ReturnLoc, diag::err_lambda_return_init_list)
+          << RetValExp->getSourceRange();
+      }
+
+      ReturnT =3D Context.VoidTy;
+    }
+    // We require the return types to strictly match here.
+    if (!CurCap->ReturnType.isNull() &&
+        !CurCap->ReturnType->isDependentType() &&
+        !ReturnT->isDependentType() &&
+        !Context.hasSameType(ReturnT, CurCap->ReturnType)) {=20
+      Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible=
)=20
+          << ReturnT << CurCap->ReturnType
+          << (getCurLambda() !=3D 0);
+      return StmtError();
+    }
+    CurCap->ReturnType =3D ReturnT;
   }
-  QualType FnRetType =3D CurBlock->ReturnType;
+  QualType FnRetType =3D CurCap->ReturnType;
+  assert(!FnRetType.isNull());
=20
-  if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
-    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
-      << getCurFunctionOrMethodDecl()->getDeclName();
-    return StmtError();
+  if (BlockScopeInfo *CurBlock =3D dyn_cast<BlockScopeInfo>(CurCap)) {
+    if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
+      Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
+      return StmtError();
+    }
+  } else {
+    LambdaScopeInfo *LSI =3D cast<LambdaScopeInfo>(CurCap);
+    if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAt=
tr()){
+      Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
+      return StmtError();
+    }
   }
=20
   // Otherwise, verify that this result type matches the previous one.  We=
 are
@@ -1772,12 +1890,17 @@
     // Delay processing for now.  TODO: there are lots of dependent
     // types we can conclusively prove aren't void.
   } else if (FnRetType->isVoidType()) {
-    if (RetValExp &&
-        !(getLangOptions().CPlusPlus &&
+    if (RetValExp && !isa<InitListExpr>(RetValExp) &&
+        !(getLangOpts().CPlusPlus &&
           (RetValExp->isTypeDependent() ||
            RetValExp->getType()->isVoidType()))) {
-      Diag(ReturnLoc, diag::err_return_block_has_expr);
-      RetValExp =3D 0;
+      if (!getLangOpts().CPlusPlus &&
+          RetValExp->getType()->isVoidType())
+        Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
+      else {
+        Diag(ReturnLoc, diag::err_return_block_has_expr);
+        RetValExp =3D 0;
+      }
     }
   } else if (!RetValExp) {
     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
@@ -1793,7 +1916,7 @@
     NRVOCandidate =3D getCopyElisionCandidate(FnRetType, RetValExp, false);
     InitializedEntity Entity =3D InitializedEntity::InitializeResult(Retur=
nLoc,
                                                                    FnRetTy=
pe,
-                                                           NRVOCandidate !=
=3D 0);
+                                                          NRVOCandidate !=
=3D 0);
     ExprResult Res =3D PerformMoveOrCopyInitialization(Entity, NRVOCandida=
te,
                                                      FnRetType, RetValExp);
     if (Res.isInvalid()) {
@@ -1813,7 +1936,7 @@
=20
   // If we need to check for the named return value optimization, save the
   // return statement in our scope for later processing.
-  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&=20
+  if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&=20
       !CurContext->isDependentContext())
     FunctionScopes.back()->Returns.push_back(Result);
=20
@@ -1826,28 +1949,25 @@
   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
     return StmtError();
  =20
-  if (getCurBlock())
-    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
+  if (isa<CapturingScopeInfo>(getCurFunction()))
+    return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
=20
   QualType FnRetType;
-  QualType DeclaredRetType;
+  QualType RelatedRetType;
   if (const FunctionDecl *FD =3D getCurFunctionDecl()) {
     FnRetType =3D FD->getResultType();
-    DeclaredRetType =3D FnRetType;
     if (FD->hasAttr<NoReturnAttr>() ||
         FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
-        << getCurFunctionOrMethodDecl()->getDeclName();
+        << FD->getDeclName();
   } else if (ObjCMethodDecl *MD =3D getCurMethodDecl()) {
-    DeclaredRetType =3D MD->getResultType();
+    FnRetType =3D MD->getResultType();
     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
       // In the implementation of a method with a related return type, the
       // type used to type-check the validity of return statements within =
the=20
       // method body is a pointer to the type of the class being implement=
ed.
-      FnRetType =3D Context.getObjCInterfaceType(MD->getClassInterface());
-      FnRetType =3D Context.getObjCObjectPointerType(FnRetType);
-    } else {
-      FnRetType =3D DeclaredRetType;
+      RelatedRetType =3D Context.getObjCInterfaceType(MD->getClassInterfac=
e());
+      RelatedRetType =3D Context.getObjCObjectPointerType(RelatedRetType);
     }
   } else // If we don't have a function/method context, bail.
     return StmtError();
@@ -1855,7 +1975,26 @@
   ReturnStmt *Result =3D 0;
   if (FnRetType->isVoidType()) {
     if (RetValExp) {
-      if (!RetValExp->isTypeDependent()) {
+      if (isa<InitListExpr>(RetValExp)) {
+        // We simply never allow init lists as the return value of void
+        // functions. This is compatible because this was never allowed be=
fore,
+        // so there's no legacy code to deal with.
+        NamedDecl *CurDecl =3D getCurFunctionOrMethodDecl();
+        int FunctionKind =3D 0;
+        if (isa<ObjCMethodDecl>(CurDecl))
+          FunctionKind =3D 1;
+        else if (isa<CXXConstructorDecl>(CurDecl))
+          FunctionKind =3D 2;
+        else if (isa<CXXDestructorDecl>(CurDecl))
+          FunctionKind =3D 3;
+
+        Diag(ReturnLoc, diag::err_return_init_list)
+          << CurDecl->getDeclName() << FunctionKind
+          << RetValExp->getSourceRange();
+
+        // Drop the expression.
+        RetValExp =3D 0;
+      } else if (!RetValExp->isTypeDependent()) {
         // C99 6.8.6.4p1 (ext_ since GCC warns)
         unsigned D =3D diag::ext_return_has_expr;
         if (RetValExp->getType()->isVoidType())
@@ -1872,7 +2011,7 @@
=20
         // return (some void expression); is legal in C++.
         if (D !=3D diag::ext_return_has_void_expr ||
-            !getLangOptions().CPlusPlus) {
+            !getLangOpts().CPlusPlus) {
           NamedDecl *CurDecl =3D getCurFunctionOrMethodDecl();
=20
           int FunctionKind =3D 0;
@@ -1889,15 +2028,17 @@
         }
       }
=20
-      CheckImplicitConversions(RetValExp, ReturnLoc);
-      RetValExp =3D MaybeCreateExprWithCleanups(RetValExp);
+      if (RetValExp) {
+        CheckImplicitConversions(RetValExp, ReturnLoc);
+        RetValExp =3D MaybeCreateExprWithCleanups(RetValExp);
+      }
     }
=20
     Result =3D new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
   } else if (!RetValExp && !FnRetType->isDependentType()) {
     unsigned DiagID =3D diag::warn_return_missing_expr;  // C90 6.6.6.4p4
     // C99 6.8.6.4p1 (ext_ since GCC warns)
-    if (getLangOptions().C99) DiagID =3D diag::ext_return_missing_expr;
+    if (getLangOpts().C99) DiagID =3D diag::ext_return_missing_expr;
=20
     if (FunctionDecl *FD =3D getCurFunctionDecl())
       Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
@@ -1909,6 +2050,21 @@
     if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
       // we have a non-void function with an expression, continue checking
=20
+      if (!RelatedRetType.isNull()) {
+        // If we have a related result type, perform an extra conversion h=
ere.
+        // FIXME: The diagnostics here don't really describe what is happe=
ning.
+        InitializedEntity Entity =3D
+            InitializedEntity::InitializeTemporary(RelatedRetType);
+       =20
+        ExprResult Res =3D PerformCopyInitialization(Entity, SourceLocatio=
n(),
+                                                   RetValExp);
+        if (Res.isInvalid()) {
+          // FIXME: Cleanup temporaries here, anyway?
+          return StmtError();
+        }
+        RetValExp =3D Res.takeAs<Expr>();
+      }
+
       // C99 6.8.6.4p3(136): The return statement is not an assignment. The
       // overlap restriction of subclause 6.5.16.1 does not apply to the c=
ase of
       // function return.
@@ -1932,17 +2088,6 @@
     }
=20
     if (RetValExp) {
-      // If we type-checked an Objective-C method's return type based
-      // on a related return type, we may need to adjust the return
-      // type again. Do so now.
-      if (DeclaredRetType !=3D FnRetType) {
-        ExprResult result =3D PerformImplicitConversion(RetValExp,
-                                                      DeclaredRetType,
-                                                      AA_Returning);
-        if (result.isInvalid()) return StmtError();
-        RetValExp =3D result.take();
-      }
-
       CheckImplicitConversions(RetValExp, ReturnLoc);
       RetValExp =3D MaybeCreateExprWithCleanups(RetValExp);
     }
@@ -1951,7 +2096,7 @@
=20
   // If we need to check for the named return value optimization, save the
   // return statement in our scope for later processing.
-  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
+  if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
       !CurContext->isDependentContext())
     FunctionScopes.back()->Returns.push_back(Result);
  =20
@@ -1977,7 +2122,7 @@
   // are supposed to allow.
   const Expr *E2 =3D E->IgnoreParenNoopCasts(S.Context);
   if (E !=3D E2 && E2->isLValue()) {
-    if (!S.getLangOptions().HeinousExtensions)
+    if (!S.getLangOpts().HeinousExtensions)
       S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
         << E->getSourceRange();
     else
@@ -2255,7 +2400,7 @@
 StmtResult
 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
                          MultiStmtArg CatchStmts, Stmt *Finally) {
-  if (!getLangOptions().ObjCExceptions)
+  if (!getLangOpts().ObjCExceptions)
     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
=20
   getCurFunction()->setHasBranchProtectedScope();
@@ -2292,7 +2437,7 @@
 StmtResult
 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
                            Scope *CurScope) {
-  if (!getLangOptions().ObjCExceptions)
+  if (!getLangOpts().ObjCExceptions)
     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
=20
   if (!Throw) {
@@ -2392,7 +2537,7 @@
 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
                        MultiStmtArg RawHandlers) {
   // Don't report an error if 'try' is used in system headers.
-  if (!getLangOptions().CXXExceptions &&
+  if (!getLangOpts().CXXExceptions &&
       !getSourceManager().isInSystemHeader(TryLoc))
       Diag(TryLoc, diag::err_exceptions_disabled) << "try";
=20
@@ -2484,3 +2629,26 @@
   assert(Block);
   return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
 }
+
+StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
+                                            bool IsIfExists,
+                                            NestedNameSpecifierLoc Qualifi=
erLoc,
+                                            DeclarationNameInfo NameInfo,
+                                            Stmt *Nested)
+{
+  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
+                                             QualifierLoc, NameInfo,=20
+                                             cast<CompoundStmt>(Nested));
+}
+
+
+StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,=20
+                                            bool IsIfExists,
+                                            CXXScopeSpec &SS,=20
+                                            UnqualifiedId &Name,
+                                            Stmt *Nested) {
+  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,=20
+                                    SS.getWithLocInContext(Context),
+                                    GetNameFromUnqualifiedId(Name),
+                                    Nested);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaTemplate.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplate.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplate.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -26,6 +26,8 @@
 #include "clang/Sema/ParsedTemplate.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/PartialDiagnostic.h"
+#include "llvm/ADT/SmallBitVector.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
 using namespace clang;
 using namespace sema;
@@ -42,11 +44,16 @@
 /// of a template and, if so, return that template declaration. Otherwise,
 /// returns NULL.
 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
-                                           NamedDecl *Orig) {
+                                           NamedDecl *Orig,
+                                           bool AllowFunctionTemplates) {
   NamedDecl *D =3D Orig->getUnderlyingDecl();
=20
-  if (isa<TemplateDecl>(D))
+  if (isa<TemplateDecl>(D)) {
+    if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
+      return 0;
+   =20
     return Orig;
+  }
=20
   if (CXXRecordDecl *Record =3D dyn_cast<CXXRecordDecl>(D)) {
     // C++ [temp.local]p1:
@@ -76,13 +83,15 @@
   return 0;
 }
=20
-void Sema::FilterAcceptableTemplateNames(LookupResult &R) {
+void Sema::FilterAcceptableTemplateNames(LookupResult &R,=20
+                                         bool AllowFunctionTemplates) {
   // The set of class templates we've already seen.
   llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
   LookupResult::Filter filter =3D R.makeFilter();
   while (filter.hasNext()) {
     NamedDecl *Orig =3D filter.next();
-    NamedDecl *Repl =3D isAcceptableTemplateName(Context, Orig);
+    NamedDecl *Repl =3D isAcceptableTemplateName(Context, Orig,=20
+                                               AllowFunctionTemplates);
     if (!Repl)
       filter.erase();
     else if (Repl !=3D Orig) {
@@ -112,9 +121,10 @@
   filter.done();
 }
=20
-bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R) {
+bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
+                                         bool AllowFunctionTemplates) {
   for (LookupResult::iterator I =3D R.begin(), IEnd =3D R.end(); I !=3D IE=
nd; ++I)
-    if (isAcceptableTemplateName(Context, *I))
+    if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
       return true;
  =20
   return false;
@@ -128,7 +138,7 @@
                                       bool EnteringContext,
                                       TemplateTy &TemplateResult,
                                       bool &MemberOfUnknownSpecialization)=
 {
-  assert(getLangOptions().CPlusPlus && "No template names in C!");
+  assert(getLangOpts().CPlusPlus && "No template names in C!");
=20
   DeclarationName TName;
   MemberOfUnknownSpecialization =3D false;
@@ -153,8 +163,7 @@
=20
   QualType ObjectType =3D ObjectTypePtr.get();
=20
-  LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
-                 LookupOrdinaryName);
+  LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
   LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
                      MemberOfUnknownSpecialization);
   if (R.empty()) return TNK_Non_template;
@@ -249,6 +258,12 @@
     isDependent =3D ObjectType->isDependentType();
     assert((isDependent || !ObjectType->isIncompleteType()) &&
            "Caller should have completed object type");
+   =20
+    // Template names cannot appear inside an Objective-C class or object =
type.
+    if (ObjectType->isObjCObjectOrInterfaceType()) {
+      Found.clear();
+      return;
+    }
   } else if (SS.isSet()) {
     // This nested-name-specifier occurs after another nested-name-specifi=
er,
     // so long into the context associated with the prior nested-name-spec=
ifier.
@@ -261,13 +276,13 @@
   }
=20
   bool ObjectTypeSearchedInScope =3D false;
+  bool AllowFunctionTemplatesInLookup =3D true;
   if (LookupCtx) {
     // Perform "qualified" name lookup into the declaration context we
     // computed, which is either the type of the base of a member access
     // expression or the declaration context associated with a prior
     // nested-name-specifier.
     LookupQualifiedName(Found, LookupCtx);
-
     if (!ObjectType.isNull() && Found.empty()) {
       // C++ [basic.lookup.classref]p1:
       //   In a class member access expression (5.2.5), if the . or -> tok=
en is
@@ -280,6 +295,7 @@
       //   or function template.
       if (S) LookupName(Found, S);
       ObjectTypeSearchedInScope =3D true;
+      AllowFunctionTemplatesInLookup =3D false;
     }
   } else if (isDependent && (!S || ObjectType.isNull())) {
     // We cannot look into a dependent object type or nested nme
@@ -289,23 +305,31 @@
   } else {
     // Perform unqualified name lookup in the current scope.
     LookupName(Found, S);
+   =20
+    if (!ObjectType.isNull())
+      AllowFunctionTemplatesInLookup =3D false;
   }
=20
   if (Found.empty() && !isDependent) {
     // If we did not find any names, attempt to correct any typos.
     DeclarationName Name =3D Found.getLookupName();
     Found.clear();
+    // Simple filter callback that, for keywords, only accepts the C++ *_c=
ast
+    CorrectionCandidateCallback FilterCCC;
+    FilterCCC.WantTypeSpecifiers =3D false;
+    FilterCCC.WantExpressionKeywords =3D false;
+    FilterCCC.WantRemainingKeywords =3D false;
+    FilterCCC.WantCXXNamedCasts =3D true;
     if (TypoCorrection Corrected =3D CorrectTypo(Found.getLookupNameInfo(),
                                                Found.getLookupKind(), S, &=
SS,
-                                               LookupCtx, false,
-                                               CTC_CXXCasts)) {
+                                               FilterCCC, LookupCtx)) {
       Found.setLookupName(Corrected.getCorrection());
       if (Corrected.getCorrectionDecl())
         Found.addDecl(Corrected.getCorrectionDecl());
       FilterAcceptableTemplateNames(Found);
       if (!Found.empty()) {
-        std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
-        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions(=
)));
+        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
+        std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
         if (LookupCtx)
           Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
             << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
@@ -323,7 +347,7 @@
     }
   }
=20
-  FilterAcceptableTemplateNames(Found);
+  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
   if (Found.empty()) {
     if (isDependent)
       MemberOfUnknownSpecialization =3D true;
@@ -339,7 +363,7 @@
     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc=
(),
                             LookupOrdinaryName);
     LookupName(FoundOuter, S);
-    FilterAcceptableTemplateNames(FoundOuter);
+    FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=3D*=
/false);
=20
     if (FoundOuter.empty()) {
       //   - if the name is not found, the name found in the class of the
@@ -379,6 +403,7 @@
 /// specifier naming a dependent type.
 ExprResult
 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
+                                 SourceLocation TemplateKWLoc,
                                  const DeclarationNameInfo &NameInfo,
                                  bool isAddressOfOperand,
                            const TemplateArgumentListInfo *TemplateArgs) {
@@ -398,20 +423,23 @@
                                                      /*IsArrow*/ true,
                                                      /*Op*/ SourceLocation=
(),
                                                SS.getWithLocInContext(Cont=
ext),
+                                                     TemplateKWLoc,
                                                      FirstQualifierInScope,
                                                      NameInfo,
                                                      TemplateArgs));
   }
=20
-  return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
+  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateAr=
gs);
 }
=20
 ExprResult
 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
+                                SourceLocation TemplateKWLoc,
                                 const DeclarationNameInfo &NameInfo,
                                 const TemplateArgumentListInfo *TemplateAr=
gs) {
   return Owned(DependentScopeDeclRefExpr::Create(Context,
                                                SS.getWithLocInContext(Cont=
ext),
+                                                 TemplateKWLoc,
                                                  NameInfo,
                                                  TemplateArgs));
 }
@@ -420,12 +448,12 @@
 /// that the template parameter 'PrevDecl' is being shadowed by a new
 /// declaration at location Loc. Returns true to indicate that this is
 /// an error, and false otherwise.
-bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevD=
ecl) {
+void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevD=
ecl) {
   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
=20
   // Microsoft Visual C++ permits template parameters to be shadowed.
-  if (getLangOptions().MicrosoftExt)
-    return false;
+  if (getLangOpts().MicrosoftExt)
+    return;
=20
   // C++ [temp.local]p4:
   //   A template-parameter shall not be redeclared within its
@@ -433,7 +461,7 @@
   Diag(Loc, diag::err_template_param_shadow)
     << cast<NamedDecl>(PrevDecl)->getDeclName();
   Diag(PrevDecl->getLocation(), diag::note_template_param_here);
-  return true;
+  return;
 }
=20
 /// AdjustDeclIfTemplate - If the given decl happens to be a template, res=
et
@@ -491,7 +519,6 @@
   }
=20
   llvm_unreachable("Unhandled parsed template argument");
-  return TemplateArgumentLoc();
 }
=20
 /// \brief Translates template arguments as provided by the parser
@@ -528,9 +555,10 @@
     NamedDecl *PrevDecl =3D LookupSingleName(S, ParamName, ParamNameLoc,
                                            LookupOrdinaryName,
                                            ForRedeclaration);
-    if (PrevDecl && PrevDecl->isTemplateParameter())
-      Invalid =3D Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
-                                                           PrevDecl);
+    if (PrevDecl && PrevDecl->isTemplateParameter()) {
+      DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl);
+      PrevDecl =3D 0;
+    }
   }
=20
   SourceLocation Loc =3D ParamNameLoc;
@@ -615,8 +643,12 @@
       T->isNullPtrType() ||
       // If T is a dependent type, we can't do the check now, so we
       // assume that it is well-formed.
-      T->isDependentType())
-    return T;
+      T->isDependentType()) {
+    // C++ [temp.param]p5: The top-level cv-qualifiers on the template-par=
ameter
+    // are ignored when determining its type.
+    return T.getUnqualifiedType();
+  }
+
   // C++ [temp.param]p8:
   //
   //   A non-type template-parameter of type "array of T" or
@@ -652,9 +684,10 @@
     NamedDecl *PrevDecl =3D LookupSingleName(S, ParamName, D.getIdentifier=
Loc(),
                                            LookupOrdinaryName,
                                            ForRedeclaration);
-    if (PrevDecl && PrevDecl->isTemplateParameter())
-      Invalid =3D Invalid || DiagnoseTemplateParameterShadow(D.getIdentifi=
erLoc(),
-                                                           PrevDecl);
+    if (PrevDecl && PrevDecl->isTemplateParameter()) {
+      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
+      PrevDecl =3D 0;
+    }
   }
=20
   T =3D CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
@@ -666,7 +699,7 @@
   bool IsParameterPack =3D D.hasEllipsis();
   NonTypeTemplateParmDecl *Param
     =3D NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUni=
tDecl(),
-                                      D.getSourceRange().getBegin(),
+                                      D.getLocStart(),
                                       D.getIdentifierLoc(),
                                       Depth, Position, ParamName, T,
                                       IsParameterPack, TInfo);
@@ -839,7 +872,12 @@
   if (SS.isNotEmpty() && !SS.isInvalid()) {
     SemanticContext =3D computeDeclContext(SS, true);
     if (!SemanticContext) {
-      // FIXME: Produce a reasonable diagnostic here
+      // FIXME: Horrible, horrible hack! We can't currently represent this
+      // in the AST, and historically we have just ignored such friend
+      // class templates, so don't complain here.
+      if (TUK !=3D TUK_Friend)
+        Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
+          << SS.getScopeRep() << SS.getRange();
       return true;
     }
=20
@@ -853,7 +891,8 @@
       ContextRAII SavedContext(*this, SemanticContext);
       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
         Invalid =3D true;
-    }
+    } else if (TUK !=3D TUK_Friend && TUK !=3D TUK_Reference)
+      diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
        =20
     LookupQualifiedName(Previous, SemanticContext);
   } else {
@@ -987,9 +1026,11 @@
     // If the name of the template was qualified, we must be defining the
     // template out-of-line.
     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
-        !(TUK =3D=3D TUK_Friend && CurContext->isDependentContext()))
+        !(TUK =3D=3D TUK_Friend && CurContext->isDependentContext())) {
       Diag(NameLoc, diag::err_member_def_does_not_match)
         << Name << SemanticContext << SS.getRange();
+      Invalid =3D true;
+    }
   }
=20
   CXXRecordDecl *NewClass =3D
@@ -1003,21 +1044,19 @@
                                             NumOuterTemplateParamLists,
                                             OuterTemplateParamLists);
=20
+  // Add alignment attributes if necessary; these attributes are checked w=
hen
+  // the ASTContext lays out the structure.
+  AddAlignmentAttributesForRecord(NewClass);
+  AddMsStructLayoutForRecord(NewClass);
+
   ClassTemplateDecl *NewTemplate
     =3D ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
                                 DeclarationName(Name), TemplateParams,
                                 NewClass, PrevClassTemplate);
   NewClass->setDescribedClassTemplate(NewTemplate);
  =20
-  if (PrevClassTemplate && PrevClassTemplate->isModulePrivate()) {
+  if (ModulePrivateLoc.isValid())
     NewTemplate->setModulePrivate();
-  } else if (ModulePrivateLoc.isValid()) {
-    if (PrevClassTemplate && !PrevClassTemplate->isModulePrivate())
-      diagnoseModulePrivateRedeclaration(NewTemplate, PrevClassTemplate,
-                                         ModulePrivateLoc);
-    else
-      NewTemplate->setModulePrivate();
-  }
  =20
   // Build the type for the class template declaration now.
   QualType T =3D NewTemplate->getInjectedClassNameSpecialization();
@@ -1032,7 +1071,7 @@
     PrevClassTemplate->setMemberSpecialization();
=20
   // Set the access specifier.
-  if (!Invalid && TUK !=3D TUK_Friend)
+  if (!Invalid && TUK !=3D TUK_Friend && NewTemplate->getDeclContext()->is=
Record())
     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
=20
   // Set the lexical context of these templates
@@ -1059,7 +1098,7 @@
     // Friend templates are visible in fairly strange ways.
     if (!CurContext->isDependentContext()) {
       DeclContext *DC =3D SemanticContext->getRedeclContext();
-      DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable =3D */ fals=
e);
+      DC->makeDeclVisibleInContext(NewTemplate);
       if (Scope *EnclosingScope =3D getScopeForDeclContext(S, DC))
         PushOnScopeChains(NewTemplate, EnclosingScope,
                           /* AddToContext =3D */ false);
@@ -1103,10 +1142,10 @@
     //   template-argument, that declaration shall be a definition and sha=
ll be
     //   the only declaration of the function template in the translation =
unit.
     // (C++98/03 doesn't have this wording; see DR226).
-    if (!S.getLangOptions().CPlusPlus0x)
-      S.Diag(ParamLoc,
-             diag::ext_template_parameter_default_in_function_template)
-        << DefArgRange;
+    S.Diag(ParamLoc, S.getLangOpts().CPlusPlus0x ?
+         diag::warn_cxx98_compat_template_parameter_default_in_function_te=
mplate
+           : diag::ext_template_parameter_default_in_function_template)
+      << DefArgRange;
     return false;
=20
   case Sema::TPC_ClassTemplateMember:
@@ -1131,7 +1170,7 @@
     // declaration (and it is a definition). Strange!
   }
=20
-  return false;
+  llvm_unreachable("Invalid TemplateParamListContext!");
 }
=20
 /// \brief Check for unexpanded parameter packs within the template parame=
ters
@@ -1195,9 +1234,6 @@
   bool SawDefaultArgument =3D false;
   SourceLocation PreviousDefaultArgLoc;
=20
-  bool SawParameterPack =3D false;
-  SourceLocation ParameterPackLoc;
-
   // Dummy initialization to avoid warnings.
   TemplateParameterList::iterator OldParam =3D NewParams->end();
   if (OldParams)
@@ -1212,18 +1248,11 @@
     SourceLocation OldDefaultLoc;
     SourceLocation NewDefaultLoc;
=20
-    // Variables used to diagnose missing default arguments
+    // Variable used to diagnose missing default arguments
     bool MissingDefaultArg =3D false;
=20
-    // C++0x [temp.param]p11:
-    //   If a template parameter of a primary class template or alias temp=
late
-    //   is a template parameter pack, it shall be the last template param=
eter.
-    if (SawParameterPack &&
-        (TPC =3D=3D TPC_ClassTemplate || TPC =3D=3D TPC_TypeAliasTemplate)=
) {
-      Diag(ParameterPackLoc,
-           diag::err_template_param_pack_must_be_last_template_parameter);
-      Invalid =3D true;
-    }
+    // Variable used to diagnose non-final parameter packs
+    bool SawParameterPack =3D false;
=20
     if (TemplateTypeParmDecl *NewTypeParm
           =3D dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
@@ -1243,7 +1272,6 @@
         assert(!NewTypeParm->hasDefaultArgument() &&
                "Parameter packs can't have a default argument!");
         SawParameterPack =3D true;
-        ParameterPackLoc =3D NewTypeParm->getLocation();
       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
                  NewTypeParm->hasDefaultArgument()) {
         OldDefaultLoc =3D OldTypeParm->getDefaultArgumentLoc();
@@ -1288,7 +1316,6 @@
         assert(!NewNonTypeParm->hasDefaultArgument() &&
                "Parameter packs can't have a default argument!");
         SawParameterPack =3D true;
-        ParameterPackLoc =3D NewNonTypeParm->getLocation();
       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
           NewNonTypeParm->hasDefaultArgument()) {
         OldDefaultLoc =3D OldNonTypeParm->getDefaultArgumentLoc();
@@ -1313,16 +1340,16 @@
       } else if (SawDefaultArgument)
         MissingDefaultArg =3D true;
     } else {
-      // Check the presence of a default argument here.
       TemplateTemplateParmDecl *NewTemplateParm
         =3D cast<TemplateTemplateParmDecl>(*NewParam);
=20
       // Check for unexpanded parameter packs, recursively.
-      if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
+      if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
         Invalid =3D true;
         continue;
       }
=20
+      // Check the presence of a default argument here.
       if (NewTemplateParm->hasDefaultArgument() &&
           DiagnoseDefaultTemplateArgument(*this, TPC,
                                           NewTemplateParm->getLocation(),
@@ -1336,7 +1363,6 @@
         assert(!NewTemplateParm->hasDefaultArgument() &&
                "Parameter packs can't have a default argument!");
         SawParameterPack =3D true;
-        ParameterPackLoc =3D NewTemplateParm->getLocation();
       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() =
&&
           NewTemplateParm->hasDefaultArgument()) {
         OldDefaultLoc =3D OldTemplateParm->getDefaultArgument().getLocatio=
n();
@@ -1363,6 +1389,16 @@
         MissingDefaultArg =3D true;
     }
=20
+    // C++0x [temp.param]p11:
+    //   If a template parameter of a primary class template or alias temp=
late
+    //   is a template parameter pack, it shall be the last template param=
eter.
+    if (SawParameterPack && (NewParam + 1) !=3D NewParamEnd &&=20
+        (TPC =3D=3D TPC_ClassTemplate || TPC =3D=3D TPC_TypeAliasTemplate)=
) {
+      Diag((*NewParam)->getLocation(),
+           diag::err_template_param_pack_must_be_last_template_parameter);
+      Invalid =3D true;
+    }
+
     if (RedundantDefaultArg) {
       // C++ [temp.param]p12:
       //   A template-parameter shall not be given default arguments
@@ -1878,7 +1914,6 @@
   }
 }
=20
-
 QualType Sema::CheckTemplateIdType(TemplateName Name,
                                    SourceLocation TemplateLoc,
                                    TemplateArgumentListInfo &TemplateArgs)=
 {
@@ -1910,18 +1945,17 @@
   // Check that the template argument list is well-formed for this
   // template.
   SmallVector<TemplateArgument, 4> Converted;
+  bool ExpansionIntoFixedList =3D false;
   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
-                                false, Converted))
+                                false, Converted, &ExpansionIntoFixedList))
     return QualType();
=20
-  assert((Converted.size() =3D=3D Template->getTemplateParameters()->size(=
)) &&
-         "Converted template argument list is too short!");
-
   QualType CanonType;
=20
   bool InstantiationDependent =3D false;
-  if (TypeAliasTemplateDecl *AliasTemplate
-        =3D dyn_cast<TypeAliasTemplateDecl>(Template)) {
+  TypeAliasTemplateDecl *AliasTemplate =3D 0;
+  if (!ExpansionIntoFixedList &&
+      (AliasTemplate =3D dyn_cast<TypeAliasTemplateDecl>(Template))) {
     // Find the canonical type for this type alias template specialization.
     TypeAliasDecl *Pattern =3D AliasTemplate->getTemplatedDecl();
     if (Pattern->isInvalidDecl())
@@ -2037,11 +2071,12 @@
 }
=20
 TypeResult
-Sema::ActOnTemplateIdType(CXXScopeSpec &SS,
+Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
                           TemplateTy TemplateD, SourceLocation TemplateLoc,
                           SourceLocation LAngleLoc,
                           ASTTemplateArgsPtr TemplateArgsIn,
-                          SourceLocation RAngleLoc) {
+                          SourceLocation RAngleLoc,
+                          bool IsCtorOrDtorName) {
   if (SS.isInvalid())
     return true;
=20
@@ -2052,20 +2087,21 @@
   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
=20
   if (DependentTemplateName *DTN =3D Template.getAsDependentTemplateName()=
) {
-    QualType T =3D Context.getDependentTemplateSpecializationType(ETK_None,
-                                                           DTN->getQualifi=
er(),=20
-                                                           DTN->getIdentif=
ier(),=20
-                                                                TemplateAr=
gs);
-   =20
-    // Build type-source information.   =20
+    QualType T
+      =3D Context.getDependentTemplateSpecializationType(ETK_None,
+                                                       DTN->getQualifier(),
+                                                       DTN->getIdentifier(=
),
+                                                       TemplateArgs);
+    // Build type-source information.
     TypeLocBuilder TLB;
     DependentTemplateSpecializationTypeLoc SpecTL
       =3D TLB.push<DependentTemplateSpecializationTypeLoc>(T);
-    SpecTL.setKeywordLoc(SourceLocation());
-    SpecTL.setNameLoc(TemplateLoc);
+    SpecTL.setElaboratedKeywordLoc(SourceLocation());
+    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
+    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
+    SpecTL.setTemplateNameLoc(TemplateLoc);
     SpecTL.setLAngleLoc(LAngleLoc);
     SpecTL.setRAngleLoc(RAngleLoc);
-    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
     for (unsigned I =3D 0, N =3D SpecTL.getNumArgs(); I !=3D N; ++I)
       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
@@ -2078,20 +2114,24 @@
     return true;
=20
   // Build type-source information.
-  TypeLocBuilder TLB; =20
+  TypeLocBuilder TLB;
   TemplateSpecializationTypeLoc SpecTL
     =3D TLB.push<TemplateSpecializationTypeLoc>(Result);
+  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
   SpecTL.setTemplateNameLoc(TemplateLoc);
   SpecTL.setLAngleLoc(LAngleLoc);
   SpecTL.setRAngleLoc(RAngleLoc);
   for (unsigned i =3D 0, e =3D SpecTL.getNumArgs(); i !=3D e; ++i)
     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
=20
-  if (SS.isNotEmpty()) {
+  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
+  // constructor or destructor name (in such a case, the scope specifier
+  // will be attached to the enclosing Decl or Expr node).
+  if (SS.isNotEmpty() && !IsCtorOrDtorName) {
     // Create an elaborated-type-specifier containing the nested-name-spec=
ifier.
     Result =3D Context.getElaboratedType(ETK_None, SS.getScopeRep(), Resul=
t);
     ElaboratedTypeLoc ElabTL =3D TLB.push<ElaboratedTypeLoc>(Result);
-    ElabTL.setKeywordLoc(SourceLocation());
+    ElabTL.setElaboratedKeywordLoc(SourceLocation());
     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
   }
  =20
@@ -2102,7 +2142,8 @@
                                         TypeSpecifierType TagSpec,
                                         SourceLocation TagLoc,
                                         CXXScopeSpec &SS,
-                                        TemplateTy TemplateD,=20
+                                        SourceLocation TemplateKWLoc,
+                                        TemplateTy TemplateD,
                                         SourceLocation TemplateLoc,
                                         SourceLocation LAngleLoc,
                                         ASTTemplateArgsPtr TemplateArgsIn,
@@ -2127,12 +2168,13 @@
     // Build type-source information.   =20
     TypeLocBuilder TLB;
     DependentTemplateSpecializationTypeLoc SpecTL
-    =3D TLB.push<DependentTemplateSpecializationTypeLoc>(T);
-    SpecTL.setKeywordLoc(TagLoc);
-    SpecTL.setNameLoc(TemplateLoc);
+      =3D TLB.push<DependentTemplateSpecializationTypeLoc>(T);
+    SpecTL.setElaboratedKeywordLoc(TagLoc);
+    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
+    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
+    SpecTL.setTemplateNameLoc(TemplateLoc);
     SpecTL.setLAngleLoc(LAngleLoc);
     SpecTL.setRAngleLoc(RAngleLoc);
-    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
     for (unsigned I =3D 0, N =3D SpecTL.getNumArgs(); I !=3D N; ++I)
       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
@@ -2167,11 +2209,12 @@
       Diag(D->getLocation(), diag::note_previous_use);
     }
   }
- =20
+
   // Provide source-location information for the template specialization.
   TypeLocBuilder TLB;
   TemplateSpecializationTypeLoc SpecTL
     =3D TLB.push<TemplateSpecializationTypeLoc>(Result);
+  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
   SpecTL.setTemplateNameLoc(TemplateLoc);
   SpecTL.setLAngleLoc(LAngleLoc);
   SpecTL.setRAngleLoc(RAngleLoc);
@@ -2179,18 +2222,19 @@
     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
=20
   // Construct an elaborated type containing the nested-name-specifier (if=
 any)
-  // and keyword.
+  // and tag keyword.
   Result =3D Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
   ElaboratedTypeLoc ElabTL =3D TLB.push<ElaboratedTypeLoc>(Result);
-  ElabTL.setKeywordLoc(TagLoc);
+  ElabTL.setElaboratedKeywordLoc(TagLoc);
   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
 }
=20
 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
+                                     SourceLocation TemplateKWLoc,
                                      LookupResult &R,
                                      bool RequiresADL,
-                                 const TemplateArgumentListInfo &TemplateA=
rgs) {
+                                 const TemplateArgumentListInfo *TemplateA=
rgs) {
   // FIXME: Can we do any checking at this point? I guess we could check t=
he
   // template arguments that we have against the template name, if the tem=
plate
   // name refers to a single template. That's not a terribly common case,
@@ -2211,6 +2255,7 @@
   UnresolvedLookupExpr *ULE
     =3D UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
                                    SS.getWithLocInContext(Context),
+                                   TemplateKWLoc,
                                    R.getLookupNameInfo(),
                                    RequiresADL, TemplateArgs,
                                    R.begin(), R.end());
@@ -2221,13 +2266,15 @@
 // We actually only call this from template instantiation.
 ExprResult
 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
+                                   SourceLocation TemplateKWLoc,
                                    const DeclarationNameInfo &NameInfo,
-                             const TemplateArgumentListInfo &TemplateArgs)=
 {
+                             const TemplateArgumentListInfo *TemplateArgs)=
 {
+  assert(TemplateArgs || TemplateKWLoc.isValid());
   DeclContext *DC;
   if (!(DC =3D computeDeclContext(SS, false)) ||
       DC->isDependentContext() ||
       RequireCompleteDeclContext(SS, DC))
-    return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
+    return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, Template=
Args);
=20
   bool MemberOfUnknownSpecialization;
   LookupResult R(*this, NameInfo, LookupOrdinaryName);
@@ -2251,7 +2298,7 @@
     return ExprError();
   }
=20
-  return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
+  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, Template=
Args);
 }
=20
 /// \brief Form a dependent template name.
@@ -2262,15 +2309,17 @@
 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
 /// of the "template" keyword, and "apply" is the \p Name.
 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
+                                                  CXXScopeSpec &SS,
                                                   SourceLocation TemplateK=
WLoc,
-                                                  CXXScopeSpec &SS,
                                                   UnqualifiedId &Name,
                                                   ParsedType ObjectType,
                                                   bool EnteringContext,
                                                   TemplateTy &Result) {
-  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
-      !getLangOptions().CPlusPlus0x)
-    Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
+  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
+    Diag(TemplateKWLoc,
+         getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_template_outside_of_template :
+           diag::ext_template_outside_of_template)
       << FixItHint::CreateRemoval(TemplateKWLoc);
=20
   DeclContext *LookupCtx =3D 0;
@@ -2305,7 +2354,7 @@
          cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
       // This is a dependent template. Handle it below.
     } else if (TNK =3D=3D TNK_Non_template) {
-      Diag(Name.getSourceRange().getBegin(),
+      Diag(Name.getLocStart(),
            diag::err_template_kw_refers_to_non_template)
         << GetNameFromUnqualifiedId(Name).getName()
         << Name.getSourceRange()
@@ -2339,7 +2388,7 @@
     break;
   }
=20
-  Diag(Name.getSourceRange().getBegin(),
+  Diag(Name.getLocStart(),
        diag::err_template_kw_refers_to_non_template)
     << GetNameFromUnqualifiedId(Name).getName()
     << Name.getSourceRange()
@@ -2391,7 +2440,7 @@
   // Objective-C ARC:
   //   If an explicitly-specified template argument type is a lifetime type
   //   with no lifetime qualifier, the __strong lifetime qualifier is infe=
rred.
-  if (getLangOptions().ObjCAutoRefCount &&
+  if (getLangOpts().ObjCAutoRefCount &&
       ArgType->isObjCLifetimeType() &&
       !ArgType.getObjCLifetime()) {
     Qualifiers Qs;
@@ -2729,9 +2778,14 @@
=20
         CXXScopeSpec SS;
         SS.Adopt(Arg.getTemplateQualifierLoc());
+        // FIXME: the template-template arg was a DependentTemplateName,
+        // so it was provided with a template keyword. However, its source
+        // location is not stored in the template argument structure.
+        SourceLocation TemplateKWLoc;
         ExprResult E =3D Owned(DependentScopeDeclRefExpr::Create(Context,
                                                 SS.getWithLocInContext(Con=
text),
-                                                    NameInfo));
+                                                               TemplateKWL=
oc,
+                                                               NameInfo, 0=
));
=20
         // If we parsed the template argument as a pack expansion, create a
         // pack expansion expression.
@@ -2782,7 +2836,6 @@
=20
     case TemplateArgument::Pack:
       llvm_unreachable("Caller must expand template argument packs");
-      break;
     }
=20
     return false;
@@ -2828,33 +2881,55 @@
     // We have a template template parameter but the template
     // argument does not refer to a template.
     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
-      << getLangOptions().CPlusPlus0x;
+      << getLangOpts().CPlusPlus0x;
     return true;
=20
   case TemplateArgument::Declaration:
-    llvm_unreachable(
-                       "Declaration argument with template template parame=
ter");
-    break;
+    llvm_unreachable("Declaration argument with template template paramete=
r");
   case TemplateArgument::Integral:
-    llvm_unreachable(
-                          "Integral argument with template template parame=
ter");
-    break;
+    llvm_unreachable("Integral argument with template template parameter");
=20
   case TemplateArgument::Pack:
     llvm_unreachable("Caller must expand template argument packs");
-    break;
   }
=20
   return false;
 }
=20
+/// \brief Diagnose an arity mismatch in the=20
+static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
+                                  SourceLocation TemplateLoc,
+                                  TemplateArgumentListInfo &TemplateArgs) {
+  TemplateParameterList *Params =3D Template->getTemplateParameters();
+  unsigned NumParams =3D Params->size();
+  unsigned NumArgs =3D TemplateArgs.size();
+
+  SourceRange Range;
+  if (NumArgs > NumParams)
+    Range =3D SourceRange(TemplateArgs[NumParams].getLocation(),=20
+                        TemplateArgs.getRAngleLoc());
+  S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
+    << (NumArgs > NumParams)
+    << (isa<ClassTemplateDecl>(Template)? 0 :
+        isa<FunctionTemplateDecl>(Template)? 1 :
+        isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
+    << Template << Range;
+  S.Diag(Template->getLocation(), diag::note_template_decl_here)
+    << Params->getSourceRange();
+  return true;
+}
+
 /// \brief Check that the given template argument list is well-formed
 /// for specializing the given template.
 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
                                      SourceLocation TemplateLoc,
                                      TemplateArgumentListInfo &TemplateArg=
s,
                                      bool PartialTemplateArgs,
-                          SmallVectorImpl<TemplateArgument> &Converted) {
+                          SmallVectorImpl<TemplateArgument> &Converted,
+                                     bool *ExpansionIntoFixedList) {
+  if (ExpansionIntoFixedList)
+    *ExpansionIntoFixedList =3D false;
+
   TemplateParameterList *Params =3D Template->getTemplateParameters();
   unsigned NumParams =3D Params->size();
   unsigned NumArgs =3D TemplateArgs.size();
@@ -2864,27 +2939,7 @@
=20
   bool HasParameterPack =3D
     NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterP=
ack();
-
-  if ((NumArgs > NumParams && !HasParameterPack) ||
-      (NumArgs < Params->getMinRequiredArguments() &&
-       !PartialTemplateArgs)) {
-    // FIXME: point at either the first arg beyond what we can handle,
-    // or the '>', depending on whether we have too many or too few
-    // arguments.
-    SourceRange Range;
-    if (NumArgs > NumParams)
-      Range =3D SourceRange(TemplateArgs[NumParams].getLocation(), RAngleL=
oc);
-    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
-      << (NumArgs > NumParams)
-      << (isa<ClassTemplateDecl>(Template)? 0 :
-          isa<FunctionTemplateDecl>(Template)? 1 :
-          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
-      << Template << Range;
-    Diag(Template->getLocation(), diag::note_template_decl_here)
-      << Params->getSourceRange();
-    Invalid =3D true;
-  }
-
+ =20
   // C++ [temp.arg]p1:
   //   [...] The type and form of each template-argument specified in
   //   a template-id shall match the type and form specified for the
@@ -2896,10 +2951,12 @@
                                ParamEnd =3D Params->end();
   unsigned ArgIdx =3D 0;
   LocalInstantiationScope InstScope(*this, true);
+  bool SawPackExpansion =3D false;
   while (Param !=3D ParamEnd) {
     if (ArgIdx < NumArgs) {
       // If we have an expanded parameter pack, make sure we don't have too
       // many arguments.
+      // FIXME: This really should fall out from the normal arity checking.
       if (NonTypeTemplateParmDecl *NTTP
                                 =3D dyn_cast<NonTypeTemplateParmDecl>(*Par=
am)) {
         if (NTTP->isExpandedParameterPack() &&
@@ -2933,6 +2990,15 @@
         // Move to the next template parameter.
         ++Param;
       }
+     =20
+      // If this template argument is a pack expansion, record that fact
+      // and break out; we can't actually check any more.
+      if (TemplateArgs[ArgIdx].getArgument().isPackExpansion()) {
+        SawPackExpansion =3D true;
+        ++ArgIdx;
+        break;
+      }
+     =20
       ++ArgIdx;
       continue;
     }
@@ -2952,7 +3018,7 @@
     if ((*Param)->isTemplateParameterPack())
       break;
    =20
-    // We have a default template argument that we will use.
+    // Check whether we have a default argument.
     TemplateArgumentLoc Arg;
=20
     // Retrieve the default template argument from the template
@@ -2961,10 +3027,9 @@
     // (when the template parameter was part of a nested template) into
     // the default argument.
     if (TemplateTypeParmDecl *TTP =3D dyn_cast<TemplateTypeParmDecl>(*Para=
m)) {
-      if (!TTP->hasDefaultArgument()) {
-        assert(Invalid && "Missing default argument");
-        break;
-      }
+      if (!TTP->hasDefaultArgument())
+        return diagnoseArityMismatch(*this, Template, TemplateLoc,=20
+                                     TemplateArgs);
=20
       TypeSourceInfo *ArgType =3D SubstDefaultTemplateArgument(*this,
                                                              Template,
@@ -2979,10 +3044,9 @@
                                 ArgType);
     } else if (NonTypeTemplateParmDecl *NTTP
                  =3D dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
-      if (!NTTP->hasDefaultArgument()) {
-        assert(Invalid && "Missing default argument");
-        break;
-      }
+      if (!NTTP->hasDefaultArgument())
+        return diagnoseArityMismatch(*this, Template, TemplateLoc,=20
+                                     TemplateArgs);
=20
       ExprResult E =3D SubstDefaultTemplateArgument(*this, Template,
                                                               TemplateLoc,
@@ -2998,10 +3062,9 @@
       TemplateTemplateParmDecl *TempParm
         =3D cast<TemplateTemplateParmDecl>(*Param);
=20
-      if (!TempParm->hasDefaultArgument()) {
-        assert(Invalid && "Missing default argument");
-        break;
-      }
+      if (!TempParm->hasDefaultArgument())
+        return diagnoseArityMismatch(*this, Template, TemplateLoc,=20
+                                     TemplateArgs);
=20
       NestedNameSpecifierLoc QualifierLoc;
       TemplateName Name =3D SubstDefaultTemplateArgument(*this, Template,
@@ -3039,12 +3102,71 @@
     ++ArgIdx;
   }
=20
+  // If we saw a pack expansion, then directly convert the remaining argum=
ents,
+  // because we don't know what parameters they'll match up with.
+  if (SawPackExpansion) {
+    bool AddToArgumentPack
+      =3D Param !=3D ParamEnd && (*Param)->isTemplateParameterPack();
+    while (ArgIdx < NumArgs) {
+      if (AddToArgumentPack)
+        ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
+      else
+        Converted.push_back(TemplateArgs[ArgIdx].getArgument());
+      ++ArgIdx;
+    }
+
+    // Push the argument pack onto the list of converted arguments.
+    if (AddToArgumentPack) {
+      if (ArgumentPack.empty())
+        Converted.push_back(TemplateArgument(0, 0));
+      else {
+        Converted.push_back(
+          TemplateArgument::CreatePackCopy(Context,
+                                           ArgumentPack.data(),
+                                           ArgumentPack.size()));
+        ArgumentPack.clear();
+      }     =20
+    } else if (ExpansionIntoFixedList) {
+      // We have expanded a pack into a fixed list.
+      *ExpansionIntoFixedList =3D true;
+    }
+
+    return Invalid;
+  }
+
+  // If we have any leftover arguments, then there were too many arguments.
+  // Complain and fail.
+  if (ArgIdx < NumArgs)
+    return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArg=
s);
+ =20
+  // If we have an expanded parameter pack, make sure we don't have too
+  // many arguments.
+  // FIXME: This really should fall out from the normal arity checking.
+  if (Param !=3D ParamEnd) {
+    if (NonTypeTemplateParmDecl *NTTP
+          =3D dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
+      if (NTTP->isExpandedParameterPack() &&
+          ArgumentPack.size() < NTTP->getNumExpansionTypes()) {
+        Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
+          << false
+          << (isa<ClassTemplateDecl>(Template)? 0 :
+              isa<FunctionTemplateDecl>(Template)? 1 :
+              isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
+          << Template;
+        Diag(Template->getLocation(), diag::note_template_decl_here)
+          << Params->getSourceRange();
+        return true;
+      }
+    }
+  }
+ =20
   // Form argument packs for each of the parameter packs remaining.
   while (Param !=3D ParamEnd) {
     // If we're checking a partial list of template arguments, don't fill
     // in arguments for non-template parameter packs.
-
     if ((*Param)->isTemplateParameterPack()) {
+      if (!HasParameterPack)
+        return true;
       if (ArgumentPack.empty())
         Converted.push_back(TemplateArgument(0, 0));
       else {
@@ -3053,7 +3175,8 @@
                                                          ArgumentPack.size=
()));
         ArgumentPack.clear();
       }
-    }
+    } else if (!PartialTemplateArgs)
+      return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateA=
rgs);
=20
     ++Param;
   }
@@ -3261,13 +3384,19 @@
=20
 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
   if (Tag->getDeclContext()->isFunctionOrMethod()) {
-    S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
+    S.Diag(SR.getBegin(),
+           S.getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_template_arg_local_type :
+             diag::ext_template_arg_local_type)
       << S.Context.getTypeDeclType(Tag) << SR;
     return true;
   }
=20
   if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
-    S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
+    S.Diag(SR.getBegin(),
+           S.getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_template_arg_unnamed_type :
+             diag::ext_template_arg_unnamed_type) << SR;
     S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
     return true;
   }
@@ -3291,7 +3420,7 @@
   case NestedNameSpecifier::TypeSpecWithTemplate:
     return Visit(QualType(NNS->getAsType(), 0));
   }
-  return false;
+  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
 }
=20
=20
@@ -3317,9 +3446,14 @@
   //   compounded from any of these types shall not be used as a
   //   template-argument for a template type-parameter.
   //
-  // C++0x allows these, and even in C++03 we allow them as an extension w=
ith
+  // C++11 allows these, and even in C++03 we allow them as an extension w=
ith
   // a warning.
-  if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
+  if (LangOpts.CPlusPlus0x ?
+     Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed=
_type,
+                              SR.getBegin()) !=3D DiagnosticsEngine::Ignor=
ed ||
+      Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_=
type,
+                               SR.getBegin()) !=3D DiagnosticsEngine::Igno=
red :
+      Arg->hasUnnamedOrLocalType()) {
     UnnamedLocalNoLinkageFinder Finder(*this, SR);
     (void)Finder.Visit(Context.getCanonicalType(Arg));
   }
@@ -3327,6 +3461,99 @@
   return false;
 }
=20
+enum NullPointerValueKind {
+  NPV_NotNullPointer,
+  NPV_NullPointer,
+  NPV_Error
+};
+
+/// \brief Determine whether the given template argument is a null pointer
+/// value of the appropriate type.
+static NullPointerValueKind
+isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
+                                   QualType ParamType, Expr *Arg) {
+  if (Arg->isValueDependent() || Arg->isTypeDependent())
+    return NPV_NotNullPointer;
+ =20
+  if (!S.getLangOpts().CPlusPlus0x)
+    return NPV_NotNullPointer;
+ =20
+  // Determine whether we have a constant expression.
+  ExprResult ArgRV =3D S.DefaultFunctionArrayConversion(Arg);
+  if (ArgRV.isInvalid())
+    return NPV_Error;
+  Arg =3D ArgRV.take();
+ =20
+  Expr::EvalResult EvalResult;
+  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
+  EvalResult.Diag =3D &Notes;
+  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
+      EvalResult.HasSideEffects) {
+    SourceLocation DiagLoc =3D Arg->getExprLoc();
+   =20
+    // If our only note is the usual "invalid subexpression" note, just po=
int
+    // the caret at its location rather than producing an essentially
+    // redundant note.
+    if (Notes.size() =3D=3D 1 && Notes[0].second.getDiagID() =3D=3D
+        diag::note_invalid_subexpr_in_const_expr) {
+      DiagLoc =3D Notes[0].first;
+      Notes.clear();
+    }
+   =20
+    S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
+      << Arg->getType() << Arg->getSourceRange();
+    for (unsigned I =3D 0, N =3D Notes.size(); I !=3D N; ++I)
+      S.Diag(Notes[I].first, Notes[I].second);
+   =20
+    S.Diag(Param->getLocation(), diag::note_template_param_here);
+    return NPV_Error;
+  }
+ =20
+  // C++11 [temp.arg.nontype]p1:
+  //   - an address constant expression of type std::nullptr_t
+  if (Arg->getType()->isNullPtrType())
+    return NPV_NullPointer;
+ =20
+  //   - a constant expression that evaluates to a null pointer value (4.1=
0); or
+  //   - a constant expression that evaluates to a null member pointer val=
ue
+  //     (4.11); or
+  if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
+      (EvalResult.Val.isMemberPointer() &&
+       !EvalResult.Val.getMemberPointerDecl())) {
+    // If our expression has an appropriate type, we've succeeded.
+    bool ObjCLifetimeConversion;
+    if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
+        S.IsQualificationConversion(Arg->getType(), ParamType, false,
+                                     ObjCLifetimeConversion))
+      return NPV_NullPointer;
+   =20
+    // The types didn't match, but we know we got a null pointer; complain,
+    // then recover as if the types were correct.
+    S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_consta=
nt)
+      << Arg->getType() << ParamType << Arg->getSourceRange();
+    S.Diag(Param->getLocation(), diag::note_template_param_here);
+    return NPV_NullPointer;
+  }
+
+  // If we don't have a null pointer value, but we do have a NULL pointer
+  // constant, suggest a cast to the appropriate type.
+  if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)=
) {
+    std::string Code =3D "static_cast<" + ParamType.getAsString() + ">(";
+    S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
+      << ParamType
+      << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
+      << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEn=
d()),
+                                    ")");
+    S.Diag(Param->getLocation(), diag::note_template_param_here);
+    return NPV_NullPointer;
+  }
+ =20
+  // FIXME: If we ever want to support general, address-constant expressio=
ns
+  // as non-type template arguments, we should return the ExprResult here =
to
+  // be interpreted by the caller.
+  return NPV_NotNullPointer;
+}
+
 /// \brief Checks whether the given template argument is the address
 /// of an object or function according to C++ [temp.arg.nontype]p1.
 static bool
@@ -3339,6 +3566,21 @@
   Expr *Arg =3D ArgIn;
   QualType ArgType =3D Arg->getType();
=20
+  // If our parameter has pointer type, check for a null template value.
+  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
+    switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
+    case NPV_NullPointer:
+      Converted =3D TemplateArgument((Decl *)0);
+      return false;
+
+    case NPV_Error:
+      return true;
+       =20
+    case NPV_NotNullPointer:
+      break;
+    }
+  }
+ =20
   // See through any implicit casts we added to fix the type.
   Arg =3D Arg->IgnoreImpCasts();
=20
@@ -3358,9 +3600,11 @@
   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
   bool ExtraParens =3D false;
   while (ParenExpr *Parens =3D dyn_cast<ParenExpr>(Arg)) {
-    if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
-      S.Diag(Arg->getSourceRange().getBegin(),
-             diag::ext_template_arg_extra_parens)
+    if (!Invalid && !ExtraParens) {
+      S.Diag(Arg->getLocStart(),
+             S.getLangOpts().CPlusPlus0x ?
+               diag::warn_cxx98_compat_template_arg_extra_parens :
+               diag::ext_template_arg_extra_parens)
         << Arg->getSourceRange();
       ExtraParens =3D true;
     }
@@ -3382,7 +3626,7 @@
     }
   }
=20
-  if (S.getLangOptions().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
+  if (S.getLangOpts().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
     Converted =3D TemplateArgument(ArgIn);
     return false;
   }
@@ -3391,62 +3635,78 @@
            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
     Arg =3D subst->getReplacement()->IgnoreImpCasts();
=20
-  DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(Arg);
-  if (!DRE) {
-    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
-      << Arg->getSourceRange();
-    S.Diag(Param->getLocation(), diag::note_template_param_here);
-    return true;
-  }
-
   // Stop checking the precise nature of the argument if it is value depen=
dent,
   // it should be checked when instantiated.
   if (Arg->isValueDependent()) {
     Converted =3D TemplateArgument(ArgIn);
     return false;
   }
+ =20
+  DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(Arg);
+  if (!DRE) {
+    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
+    << Arg->getSourceRange();
+    S.Diag(Param->getLocation(), diag::note_template_param_here);
+    return true;
+  }
=20
   if (!isa<ValueDecl>(DRE->getDecl())) {
-    S.Diag(Arg->getSourceRange().getBegin(),
+    S.Diag(Arg->getLocStart(),
            diag::err_template_arg_not_object_or_func_form)
       << Arg->getSourceRange();
     S.Diag(Param->getLocation(), diag::note_template_param_here);
     return true;
   }
=20
-  NamedDecl *Entity =3D 0;
+  NamedDecl *Entity =3D DRE->getDecl();
=20
   // Cannot refer to non-static data members
-  if (FieldDecl *Field =3D dyn_cast<FieldDecl>(DRE->getDecl())) {
-    S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
+  if (FieldDecl *Field =3D dyn_cast<FieldDecl>(Entity)) {
+    S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
       << Field << Arg->getSourceRange();
     S.Diag(Param->getLocation(), diag::note_template_param_here);
     return true;
   }
=20
   // Cannot refer to non-static member functions
-  if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(DRE->getDecl()))
+  if (CXXMethodDecl *Method =3D dyn_cast<CXXMethodDecl>(Entity)) {
     if (!Method->isStatic()) {
-      S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_meth=
od)
+      S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
         << Method << Arg->getSourceRange();
       S.Diag(Param->getLocation(), diag::note_template_param_here);
       return true;
     }
-
-  // Functions must have external linkage.
-  if (FunctionDecl *Func =3D dyn_cast<FunctionDecl>(DRE->getDecl())) {
-    if (!isExternalLinkage(Func->getLinkage())) {
-      S.Diag(Arg->getSourceRange().getBegin(),
-             diag::err_template_arg_function_not_extern)
-        << Func << Arg->getSourceRange();
-      S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
-        << true;
-      return true;
-    }
-
-    // Okay: we've named a function with external linkage.
-    Entity =3D Func;
-
+  }
+
+  FunctionDecl *Func =3D dyn_cast<FunctionDecl>(Entity);
+  VarDecl *Var =3D dyn_cast<VarDecl>(Entity);
+
+  // A non-type template argument must refer to an object or function.
+  if (!Func && !Var) {
+    // We found something, but we don't know specifically what it is.
+    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
+      << Arg->getSourceRange();
+    S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_h=
ere);
+    return true;
+  }
+
+  // Address / reference template args must have external linkage in C++98.
+  if (Entity->getLinkage() =3D=3D InternalLinkage) {
+    S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus0x ?
+             diag::warn_cxx98_compat_template_arg_object_internal :
+             diag::ext_template_arg_object_internal)
+      << !Func << Entity << Arg->getSourceRange();
+    S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
+      << !Func;
+  } else if (Entity->getLinkage() =3D=3D NoLinkage) {
+    S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
+      << !Func << Entity << Arg->getSourceRange();
+    S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
+      << !Func;
+    return true;
+  }
+
+  if (Func) {
     // If the template parameter has pointer type, the function decays.
     if (ParamType->isPointerType() && !AddressTaken)
       ArgType =3D S.Context.getPointerType(Func->getType());
@@ -3469,27 +3729,24 @@
=20
       ArgType =3D Func->getType();
     }
-  } else if (VarDecl *Var =3D dyn_cast<VarDecl>(DRE->getDecl())) {
-    if (!isExternalLinkage(Var->getLinkage())) {
-      S.Diag(Arg->getSourceRange().getBegin(),
-             diag::err_template_arg_object_not_extern)
-        << Var << Arg->getSourceRange();
-      S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
-        << true;
-      return true;
-    }
-
+  } else {
     // A value of reference type is not an object.
     if (Var->getType()->isReferenceType()) {
-      S.Diag(Arg->getSourceRange().getBegin(),
+      S.Diag(Arg->getLocStart(),
              diag::err_template_arg_reference_var)
         << Var->getType() << Arg->getSourceRange();
       S.Diag(Param->getLocation(), diag::note_template_param_here);
       return true;
     }
=20
-    // Okay: we've named an object with external linkage
-    Entity =3D Var;
+    // A template argument must have static storage duration.
+    // FIXME: Ensure this works for thread_local as well as __thread.
+    if (Var->isThreadSpecified()) {
+      S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
+        << Arg->getSourceRange();
+      S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
+      return true;
+    }
=20
     // If the template parameter has pointer type, we must have taken
     // the address of this object.
@@ -3536,13 +3793,6 @@
         S.Diag(Param->getLocation(), diag::note_template_param_here);
       }
     }
-  } else {
-    // We found something else, but we don't know specifically what it is.
-    S.Diag(Arg->getSourceRange().getBegin(),
-           diag::err_template_arg_not_object_or_func)
-      << Arg->getSourceRange();
-    S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_h=
ere);
-    return true;
   }
=20
   bool ObjCLifetimeConversion;
@@ -3568,7 +3818,7 @@
         unsigned ArgQuals =3D ArgType.getCVRQualifiers();
=20
         if ((ParamQuals | ArgQuals) !=3D ParamQuals) {
-          S.Diag(Arg->getSourceRange().getBegin(),
+          S.Diag(Arg->getLocStart(),
                  diag::err_template_arg_ref_bind_ignores_quals)
             << ParamType << Arg->getType()
             << Arg->getSourceRange();
@@ -3597,16 +3847,47 @@
=20
   // Create the template argument.
   Converted =3D TemplateArgument(Entity->getCanonicalDecl());
-  S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
+  S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity);
   return false;
 }
=20
 /// \brief Checks whether the given template argument is a pointer to
 /// member constant according to C++ [temp.arg.nontype]p1.
-bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
-                                                TemplateArgument &Converte=
d) {
+static bool CheckTemplateArgumentPointerToMember(Sema &S,
+                                                 NonTypeTemplateParmDecl *=
Param,
+                                                 QualType ParamType,
+                                                 Expr *&ResultArg,
+                                                 TemplateArgument &Convert=
ed) {
   bool Invalid =3D false;
=20
+  // Check for a null pointer value.
+  Expr *Arg =3D ResultArg;
+  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
+  case NPV_Error:
+    return true;
+  case NPV_NullPointer:
+    Converted =3D TemplateArgument((Decl *)0);
+    return false;
+  case NPV_NotNullPointer:
+    break;
+  }
+
+  bool ObjCLifetimeConversion;
+  if (S.IsQualificationConversion(Arg->getType(),
+                                  ParamType.getNonReferenceType(),
+                                  false, ObjCLifetimeConversion)) {
+    Arg =3D S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
+                              Arg->getValueKind()).take();
+    ResultArg =3D Arg;
+  } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
+                ParamType.getNonReferenceType())) {
+    // We can't perform this conversion.
+    S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
+      << Arg->getType() << ParamType << Arg->getSourceRange();
+    S.Diag(Param->getLocation(), diag::note_template_param_here);
+    return true;
+  }
+
   // See through any implicit casts we added to fix the type.
   while (ImplicitCastExpr *Cast =3D dyn_cast<ImplicitCastExpr>(Arg))
     Arg =3D Cast->getSubExpr();
@@ -3623,9 +3904,11 @@
   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
   bool ExtraParens =3D false;
   while (ParenExpr *Parens =3D dyn_cast<ParenExpr>(Arg)) {
-    if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
-      Diag(Arg->getSourceRange().getBegin(),
-           diag::ext_template_arg_extra_parens)
+    if (!Invalid && !ExtraParens) {
+      S.Diag(Arg->getLocStart(),
+             S.getLangOpts().CPlusPlus0x ?
+               diag::warn_cxx98_compat_template_arg_extra_parens :
+               diag::ext_template_arg_extra_parens)
         << Arg->getSourceRange();
       ExtraParens =3D true;
     }
@@ -3651,7 +3934,7 @@
       if (VD->getType()->isMemberPointerType()) {
         if (isa<NonTypeTemplateParmDecl>(VD) ||
             (isa<VarDecl>(VD) &&
-             Context.getCanonicalType(VD->getType()).isConstQualified())) {
+             S.Context.getCanonicalType(VD->getType()).isConstQualified())=
) {
           if (Arg->isTypeDependent() || Arg->isValueDependent())
             Converted =3D TemplateArgument(Arg);
           else
@@ -3665,8 +3948,8 @@
   }
=20
   if (!DRE)
-    return Diag(Arg->getSourceRange().getBegin(),
-                diag::err_template_arg_not_pointer_to_member_form)
+    return S.Diag(Arg->getLocStart(),
+                  diag::err_template_arg_not_pointer_to_member_form)
       << Arg->getSourceRange();
=20
   if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())=
) {
@@ -3684,11 +3967,10 @@
   }
=20
   // We found something else, but we don't know specifically what it is.
-  Diag(Arg->getSourceRange().getBegin(),
-       diag::err_template_arg_not_pointer_to_member_form)
-      << Arg->getSourceRange();
-  Diag(DRE->getDecl()->getLocation(),
-       diag::note_template_arg_refers_here);
+  S.Diag(Arg->getLocStart(),
+         diag::err_template_arg_not_pointer_to_member_form)
+    << Arg->getSourceRange();
+  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_her=
e);
   return true;
 }
=20
@@ -3704,7 +3986,7 @@
                                        QualType InstantiatedParamType, Exp=
r *Arg,
                                        TemplateArgument &Converted,
                                        CheckTemplateArgumentKind CTAK) {
-  SourceLocation StartLoc =3D Arg->getSourceRange().getBegin();
+  SourceLocation StartLoc =3D Arg->getLocStart();
=20
   // If either the parameter has a dependent type or the argument is
   // type-dependent, there's nothing we can check now.
@@ -3720,13 +4002,77 @@
   //   template-argument cannot be converted to the type of the
   //   corresponding template-parameter then the program is
   //   ill-formed.
-  //
-  //     -- for a non-type template-parameter of integral or
-  //        enumeration type, integral promotions (4.5) and integral
-  //        conversions (4.7) are applied.
   QualType ParamType =3D InstantiatedParamType;
-  QualType ArgType =3D Arg->getType();
   if (ParamType->isIntegralOrEnumerationType()) {
+    // C++11:
+    //   -- for a non-type template-parameter of integral or
+    //      enumeration type, conversions permitted in a converted
+    //      constant expression are applied.
+    //
+    // C++98:
+    //   -- for a non-type template-parameter of integral or
+    //      enumeration type, integral promotions (4.5) and integral
+    //      conversions (4.7) are applied.
+
+    if (CTAK =3D=3D CTAK_Deduced &&
+        !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
+      // C++ [temp.deduct.type]p17:
+      //   If, in the declaration of a function template with a non-type
+      //   template-parameter, the non-type template-parameter is used
+      //   in an expression in the function parameter-list and, if the
+      //   corresponding template-argument is deduced, the
+      //   template-argument type shall match the type of the
+      //   template-parameter exactly, except that a template-argument
+      //   deduced from an array bound may be of any integral type.
+      Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
+        << Arg->getType().getUnqualifiedType()
+        << ParamType.getUnqualifiedType();
+      Diag(Param->getLocation(), diag::note_template_param_here);
+      return ExprError();
+    }
+
+    if (getLangOpts().CPlusPlus0x) {
+      // We can't check arbitrary value-dependent arguments.
+      // FIXME: If there's no viable conversion to the template parameter =
type,
+      // we should be able to diagnose that prior to instantiation.
+      if (Arg->isValueDependent()) {
+        Converted =3D TemplateArgument(Arg);
+        return Owned(Arg);
+      }
+
+      // C++ [temp.arg.nontype]p1:
+      //   A template-argument for a non-type, non-template template-param=
eter
+      //   shall be one of:
+      //
+      //     -- for a non-type template-parameter of integral or enumerati=
on
+      //        type, a converted constant expression of the type of the
+      //        template-parameter; or
+      llvm::APSInt Value;
+      ExprResult ArgResult =3D
+        CheckConvertedConstantExpression(Arg, ParamType, Value,
+                                         CCEK_TemplateArg);
+      if (ArgResult.isInvalid())
+        return ExprError();
+
+      // Widen the argument value to sizeof(parameter type). This is almost
+      // always a no-op, except when the parameter type is bool. In
+      // that case, this may extend the argument from 1 bit to 8 bits.
+      QualType IntegerType =3D ParamType;
+      if (const EnumType *Enum =3D IntegerType->getAs<EnumType>())
+        IntegerType =3D Enum->getDecl()->getIntegerType();
+      Value =3D Value.extOrTrunc(Context.getTypeSize(IntegerType));
+
+      Converted =3D TemplateArgument(Value, Context.getCanonicalType(Param=
Type));
+      return ArgResult;
+    }
+
+    ExprResult ArgResult =3D DefaultLvalueConversion(Arg);
+    if (ArgResult.isInvalid())
+      return ExprError();
+    Arg =3D ArgResult.take();
+
+    QualType ArgType =3D Arg->getType();
+
     // C++ [temp.arg.nontype]p1:
     //   A template-argument for a non-type, non-template
     //   template-parameter shall be one of:
@@ -3737,16 +4083,16 @@
     SourceLocation NonConstantLoc;
     llvm::APSInt Value;
     if (!ArgType->isIntegralOrEnumerationType()) {
-      Diag(Arg->getSourceRange().getBegin(),
+      Diag(Arg->getLocStart(),
            diag::err_template_arg_not_integral_or_enumeral)
         << ArgType << Arg->getSourceRange();
       Diag(Param->getLocation(), diag::note_template_param_here);
       return ExprError();
-    } else if (!Arg->isValueDependent() &&
-               !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc=
)) {
-      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
-        << ArgType << Arg->getSourceRange();
-      return ExprError();
+    } else if (!Arg->isValueDependent()) {
+      Arg =3D VerifyIntegerConstantExpression(Arg, &Value,
+        PDiag(diag::err_template_arg_not_ice) << ArgType, false).take();
+      if (!Arg)
+        return ExprError();
     }
=20
     // From here on out, all we care about are the unqualified forms
@@ -3757,19 +4103,6 @@
     // Try to convert the argument to the parameter's type.
     if (Context.hasSameType(ParamType, ArgType)) {
       // Okay: no conversion necessary
-    } else if (CTAK =3D=3D CTAK_Deduced) {
-      // C++ [temp.deduct.type]p17:
-      //   If, in the declaration of a function template with a non-type
-      //   template-parameter, the non-type template- parameter is used
-      //   in an expression in the function parameter-list and, if the
-      //   corresponding template-argument is deduced, the
-      //   template-argument type shall match the type of the
-      //   template-parameter exactly, except that a template-argument
-      //   deduced from an array bound may be of any integral type.
-      Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
-        << ArgType << ParamType;
-      Diag(Param->getLocation(), diag::note_template_param_here);
-      return ExprError();
     } else if (ParamType->isBooleanType()) {
       // This is an integral-to-boolean conversion.
       Arg =3D ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take=
();
@@ -3779,7 +4112,7 @@
       Arg =3D ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
     } else {
       // We can't perform this conversion.
-      Diag(Arg->getSourceRange().getBegin(),
+      Diag(Arg->getLocStart(),
            diag::err_template_arg_not_convertible)
         << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(=
);
       Diag(Param->getLocation(), diag::note_template_param_here);
@@ -3820,7 +4153,7 @@
       // Complain if an unsigned parameter received a negative value.
       if (IntegerType->isUnsignedIntegerOrEnumerationType()
                && (OldValue.isSigned() && OldValue.isNegative())) {
-        Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_neg=
ative)
+        Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
           << OldValue.toString(10) << Value.toString(10) << Param->getType=
()
           << Arg->getSourceRange();
         Diag(Param->getLocation(), diag::note_template_param_here);
@@ -3835,7 +4168,7 @@
       else
         RequiredBits =3D OldValue.getMinSignedBits();
       if (RequiredBits > AllowedBits) {
-        Diag(Arg->getSourceRange().getBegin(),
+        Diag(Arg->getLocStart(),
              diag::warn_template_arg_too_large)
           << OldValue.toString(10) << Value.toString(10) << Param->getType=
()
           << Arg->getSourceRange();
@@ -3850,25 +4183,9 @@
     return Owned(Arg);
   }
=20
+  QualType ArgType =3D Arg->getType();
   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
=20
-  // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
-  // from a template argument of type std::nullptr_t to a non-type
-  // template parameter of type pointer to object, pointer to
-  // function, or pointer-to-member, respectively.
-  if (ArgType->isNullPtrType()) {
-    if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
-      Converted =3D TemplateArgument((NamedDecl *)0);
-      return Owned(Arg);
-    }
-   =20
-    if (ParamType->isNullPtrType()) {
-      llvm::APSInt Zero(Context.getTypeSize(Context.NullPtrTy), true);
-      Converted =3D TemplateArgument(Zero, Context.NullPtrTy);
-      return Owned(Arg);
-    }
-  }
-
   // Handle pointer-to-function, reference-to-function, and
   // pointer-to-member-function all in (roughly) the same way.
   if (// -- For a non-type template-parameter of type pointer to
@@ -3897,7 +4214,7 @@
       if (FunctionDecl *Fn =3D ResolveAddressOfOverloadedFunction(Arg, Par=
amType,
                                                                 true,
                                                                 FoundResul=
t)) {
-        if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
+        if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
           return ExprError();
=20
         Arg =3D FixOverloadedFunctionReference(Arg, FoundResult, Fn);
@@ -3914,22 +4231,8 @@
       return Owned(Arg);
     }
=20
-    bool ObjCLifetimeConversion;
-    if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(),
-                                  false, ObjCLifetimeConversion)) {
-      Arg =3D ImpCastExprToType(Arg, ParamType, CK_NoOp,
-                              Arg->getValueKind()).take();
-    } else if (!Context.hasSameUnqualifiedType(ArgType,
-                                           ParamType.getNonReferenceType()=
)) {
-      // We can't perform this conversion.
-      Diag(Arg->getSourceRange().getBegin(),
-           diag::err_template_arg_not_convertible)
-        << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(=
);
-      Diag(Param->getLocation(), diag::note_template_param_here);
-      return ExprError();
-    }
-
-    if (CheckTemplateArgumentPointerToMember(Arg, Converted))
+    if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
+                                             Converted))
       return ExprError();
     return Owned(Arg);
   }
@@ -3964,7 +4267,7 @@
                                                  ParamRefType->getPointeeT=
ype(),
                                                                 true,
                                                                 FoundResul=
t)) {
-        if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
+        if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
           return ExprError();
=20
         Arg =3D FixOverloadedFunctionReference(Arg, FoundResult, Fn);
@@ -3980,27 +4283,35 @@
     return Owned(Arg);
   }
=20
+  // Deal with parameters of type std::nullptr_t.
+  if (ParamType->isNullPtrType()) {
+    if (Arg->isTypeDependent() || Arg->isValueDependent()) {
+      Converted =3D TemplateArgument(Arg);
+      return Owned(Arg);
+    }
+   =20
+    switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Ar=
g)) {
+    case NPV_NotNullPointer:
+      Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
+        << Arg->getType() << ParamType;
+      Diag(Param->getLocation(), diag::note_template_param_here);
+      return ExprError();
+     =20
+    case NPV_Error:
+      return ExprError();
+     =20
+    case NPV_NullPointer:
+      Converted =3D TemplateArgument((Decl *)0);
+      return Owned(Arg);;
+    }
+  }
+
   //     -- For a non-type template-parameter of type pointer to data
   //        member, qualification conversions (4.4) are applied.
   assert(ParamType->isMemberPointerType() && "Only pointers to members rem=
ain");
=20
-  bool ObjCLifetimeConversion;
-  if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
-    // Types match exactly: nothing more to do here.
-  } else if (IsQualificationConversion(ArgType, ParamType, false,=20
-                                       ObjCLifetimeConversion)) {
-    Arg =3D ImpCastExprToType(Arg, ParamType, CK_NoOp,
-                            Arg->getValueKind()).take();
-  } else {
-    // We can't perform this conversion.
-    Diag(Arg->getSourceRange().getBegin(),
-         diag::err_template_arg_not_convertible)
-      << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
-    Diag(Param->getLocation(), diag::note_template_param_here);
-    return ExprError();
-  }
-
-  if (CheckTemplateArgumentPointerToMember(Arg, Converted))
+  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
+                                           Converted))
     return ExprError();
   return Owned(Arg);
 }
@@ -4059,6 +4370,18 @@
                                               SourceLocation Loc) {
   assert(Arg.getKind() =3D=3D TemplateArgument::Declaration &&
          "Only declaration template arguments permitted here");
+ =20
+  // For a NULL non-type template argument, return nullptr casted to the
+  // parameter's type.
+  if (!Arg.getAsDecl()) {
+    return ImpCastExprToType(
+             new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
+                             ParamType,
+                             ParamType->getAs<MemberPointerType>()
+                               ? CK_NullToMemberPointer
+                               : CK_NullToPointer);
+  }
+ =20
   ValueDecl *VD =3D cast<ValueDecl>(Arg.getAsDecl());
=20
   if (VD->getDeclContext()->isRecord() &&
@@ -4426,6 +4749,9 @@
 /// false. Otherwise, issues a diagnostic and returns true.
 bool
 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplatePara=
ms) {
+  if (!S)
+    return false;
+
   // Find the nearest enclosing declaration scope.
   while ((S->getFlags() & Scope::DeclScope) =3D=3D 0 ||
          (S->getFlags() & Scope::TemplateParamScope) !=3D 0)
@@ -4453,7 +4779,7 @@
=20
 /// \brief Determine what kind of template specialization the given declar=
ation
 /// is.
-static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl =
*D) {
+static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
   if (!D)
     return TSK_Undeclared;
=20
@@ -4509,8 +4835,11 @@
     EntityKind =3D 4;
   else if (isa<RecordDecl>(Specialized))
     EntityKind =3D 5;
+  else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus0x)
+    EntityKind =3D 6;
   else {
-    S.Diag(Loc, diag::err_template_spec_unknown_kind);
+    S.Diag(Loc, diag::err_template_spec_unknown_kind)
+      << S.getLangOpts().CPlusPlus0x;
     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
     return true;
   }
@@ -4535,7 +4864,7 @@
   }
=20
   if (S.CurContext->isRecord() && !IsPartialSpecialization) {
-    if (S.getLangOptions().MicrosoftExt) {
+    if (S.getLangOpts().MicrosoftExt) {
       // Do not warn for class scope explicit specialization during
       // instantiation, warning was already emitted during pattern
       // semantic analysis.
@@ -4549,12 +4878,21 @@
     }
   }
=20
+  if (S.CurContext->isRecord() &&
+      !S.CurContext->Equals(Specialized->getDeclContext())) {
+    // Make sure that we're specializing in the right record context.
+    // Otherwise, things can go horribly wrong.
+    S.Diag(Loc, diag::err_template_spec_decl_class_scope)
+      << Specialized;
+    return true;
+  }
+ =20
   // C++ [temp.class.spec]p6:
   //   A class template partial specialization may be declared or redeclar=
ed
   //   in any namespace scope in which its definition may be defined (14.5=
.1
   //   and 14.5.2).
   bool ComplainedAboutScope =3D false;
-  DeclContext *SpecializedContext
+  DeclContext *SpecializedContext=20
     =3D Specialized->getDeclContext()->getEnclosingNamespaceContext();
   DeclContext *DC =3D S.CurContext->getEnclosingNamespaceContext();
   if ((!PrevDecl ||
@@ -4571,24 +4909,28 @@
     // C++0x [temp.expl.spec]p2:
     //   An explicit specialization shall be declared in a namespace enclo=
sing
     //   the specialized template.
-    if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
-        !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContex=
t))) {
-      bool IsCPlusPlus0xExtension
-        =3D !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedCon=
text);
-      if (isa<TranslationUnitDecl>(SpecializedContext))
-        S.Diag(Loc, IsCPlusPlus0xExtension
-                      ? diag::ext_template_spec_decl_out_of_scope_global
-                      : diag::err_template_spec_decl_out_of_scope_global)
+    if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
+      bool IsCPlusPlus0xExtension =3D DC->Encloses(SpecializedContext);
+      if (isa<TranslationUnitDecl>(SpecializedContext)) {
+        assert(!IsCPlusPlus0xExtension &&
+               "DC encloses TU but isn't in enclosing namespace set");
+        S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
           << EntityKind << Specialized;
-      else if (isa<NamespaceDecl>(SpecializedContext))
-        S.Diag(Loc, IsCPlusPlus0xExtension
-                      ? diag::ext_template_spec_decl_out_of_scope
-                      : diag::err_template_spec_decl_out_of_scope)
-          << EntityKind << Specialized
-          << cast<NamedDecl>(SpecializedContext);
+      } else if (isa<NamespaceDecl>(SpecializedContext)) {
+        int Diag;
+        if (!IsCPlusPlus0xExtension)
+          Diag =3D diag::err_template_spec_decl_out_of_scope;
+        else if (!S.getLangOpts().CPlusPlus0x)
+          Diag =3D diag::ext_template_spec_decl_out_of_scope;
+        else
+          Diag =3D diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
+        S.Diag(Loc, Diag)
+          << EntityKind << Specialized << cast<NamedDecl>(SpecializedConte=
xt);
+      }
=20
       S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
-      ComplainedAboutScope =3D true;
+      ComplainedAboutScope =3D
+        !(IsCPlusPlus0xExtension && S.getLangOpts().CPlusPlus0x);
     }
   }
=20
@@ -4718,23 +5060,6 @@
   return false;
 }
=20
-/// \brief Retrieve the previous declaration of the given declaration.
-static NamedDecl *getPreviousDecl(NamedDecl *ND) {
-  if (VarDecl *VD =3D dyn_cast<VarDecl>(ND))
-    return VD->getPreviousDeclaration();
-  if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(ND))
-    return FD->getPreviousDeclaration();
-  if (TagDecl *TD =3D dyn_cast<TagDecl>(ND))
-    return TD->getPreviousDeclaration();
-  if (TypedefNameDecl *TD =3D dyn_cast<TypedefNameDecl>(ND))
-    return TD->getPreviousDeclaration();
-  if (FunctionTemplateDecl *FTD =3D dyn_cast<FunctionTemplateDecl>(ND))
-    return FTD->getPreviousDeclaration();
-  if (ClassTemplateDecl *CTD =3D dyn_cast<ClassTemplateDecl>(ND))
-    return CTD->getPreviousDeclaration();
-  return 0;
-}
-
 DeclResult
 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
                                        TagUseKind TUK,
@@ -4875,9 +5200,6 @@
                                 TemplateArgs, false, Converted))
     return true;
=20
-  assert((Converted.size() =3D=3D ClassTemplate->getTemplateParameters()->=
size()) &&
-         "Converted template argument list is too short!");
-
   // Find the class template (partial) specialization declaration that
   // corresponds to these arguments.
   if (isPartialSpecialization) {
@@ -5005,17 +5327,13 @@
     // partial specialization are deducible from the template
     // arguments. If not, this class template partial specialization
     // will never be used.
-    SmallVector<bool, 8> DeducibleParams;
-    DeducibleParams.resize(TemplateParams->size());
+    llvm::SmallBitVector DeducibleParams(TemplateParams->size());
     MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
                                TemplateParams->getDepth(),
                                DeducibleParams);
-    unsigned NumNonDeducible =3D 0;
-    for (unsigned I =3D 0, N =3D DeducibleParams.size(); I !=3D N; ++I)
-      if (!DeducibleParams[I])
-        ++NumNonDeducible;
-
-    if (NumNonDeducible) {
+
+    if (!DeducibleParams.all()) {
+      unsigned NumNonDeducible =3D DeducibleParams.size()-DeducibleParams.=
count();
       Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
         << (NumNonDeducible > 1)
         << SourceRange(TemplateNameLoc, RAngleLoc);
@@ -5065,7 +5383,7 @@
   //   use occurs; no diagnostic is required.
   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
     bool Okay =3D false;
-    for (NamedDecl *Prev =3D PrevDecl; Prev; Prev =3D getPreviousDecl(Prev=
)) {
+    for (Decl *Prev =3D PrevDecl; Prev; Prev =3D Prev->getPreviousDecl()) {
       // Is there any previous explicit specialization declaration?
       if (getTemplateSpecializationKind(Prev) =3D=3D TSK_ExplicitSpecializ=
ation) {
         Okay =3D true;
@@ -5174,7 +5492,7 @@
=20
   Scope *ParentScope =3D FnBodyScope->getParent();
=20
-  D.setFunctionDefinition(true);
+  D.setFunctionDefinitionKind(FDK_Definition);
   Decl *DP =3D HandleDeclarator(ParentScope, D,
                               move(TemplateParameterLists));
   if (FunctionTemplateDecl *FunctionTemplate
@@ -5189,6 +5507,7 @@
 /// \brief Strips various properties off an implicit instantiation
 /// that has just been explicitly specialized.
 static void StripImplicitInstantiation(NamedDecl *D) {
+  // FIXME: "make check" is clean if the call to dropAttrs() is commented =
out.
   D->dropAttrs();
=20
   if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
@@ -5196,6 +5515,23 @@
   }
 }
=20
+/// \brief Compute the diagnostic location for an explicit instantiation
+//  declaration or definition.
+static SourceLocation DiagLocForExplicitInstantiation(
+    NamedDecl* D, SourceLocation PointOfInstantiation) {
+  // Explicit instantiations following a specialization have no effect and
+  // hence no PointOfInstantiation. In that case, walk decl backwards
+  // until a valid name loc is found.
+  SourceLocation PrevDiagLoc =3D PointOfInstantiation;
+  for (Decl *Prev =3D D; Prev && !PrevDiagLoc.isValid();
+       Prev =3D Prev->getPreviousDecl()) {
+    PrevDiagLoc =3D Prev->getLocation();
+  }
+  assert(PrevDiagLoc.isValid() &&
+         "Explicit instantiation without point of instantiation?");
+  return PrevDiagLoc;
+}
+
 /// \brief Diagnose cases where we have an explicit template specialization
 /// before/after an explicit template instantiation, producing diagnostics
 /// for those cases where they are required and determining whether the
@@ -5262,7 +5598,7 @@
       //   before the first use of that specialization that would cause an
       //   implicit instantiation to take place, in every translation unit=
 in
       //   which such a use occurs; no diagnostic is required.
-      for (NamedDecl *Prev =3D PrevDecl; Prev; Prev =3D getPreviousDecl(Pr=
ev)) {
+      for (Decl *Prev =3D PrevDecl; Prev; Prev =3D Prev->getPreviousDecl()=
) {
         // Is there any previous explicit specialization declaration?
         if (getTemplateSpecializationKind(Prev) =3D=3D TSK_ExplicitSpecial=
ization)
           return false;
@@ -5275,7 +5611,6 @@
=20
       return true;
     }
-    break;
=20
   case TSK_ExplicitInstantiationDeclaration:
     switch (PrevTSK) {
@@ -5306,14 +5641,15 @@
       //   translation unit, the definition shall follow the declaration.
       Diag(NewLoc,
            diag::err_explicit_instantiation_declaration_after_definition);
-      Diag(PrevPointOfInstantiation,
+
+      // Explicit instantiations following a specialization have no effect=
 and
+      // hence no PrevPointOfInstantiation. In that case, walk decl backwa=
rds
+      // until a valid name loc is found.
+      Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiat=
ion),
            diag::note_explicit_instantiation_definition_here);
-      assert(PrevPointOfInstantiation.isValid() &&
-             "Explicit instantiation without point of instantiation?");
       HasNoEffect =3D true;
       return false;
     }
-    break;
=20
   case TSK_ExplicitInstantiationDefinition:
     switch (PrevTSK) {
@@ -5333,18 +5669,32 @@
       // In C++98/03 mode, we only give an extension warning here, because=
 it
       // is not harmful to try to explicitly instantiate something that
       // has been explicitly specialized.
-      if (!getLangOptions().CPlusPlus0x) {
-        Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
-          << PrevDecl;
-        Diag(PrevDecl->getLocation(),
-             diag::note_previous_template_specialization);
-      }
+      Diag(NewLoc, getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_explicit_instantiation_after_specializa=
tion :
+           diag::ext_explicit_instantiation_after_specialization)
+        << PrevDecl;
+      Diag(PrevDecl->getLocation(),
+           diag::note_previous_template_specialization);
       HasNoEffect =3D true;
       return false;
=20
     case TSK_ExplicitInstantiationDeclaration:
       // We're explicity instantiating a definition for something for whic=
h we
       // were previously asked to suppress instantiations. That's fine.
+
+      // C++0x [temp.explicit]p4:
+      //   For a given set of template parameters, if an explicit instanti=
ation
+      //   of a template appears after a declaration of an explicit
+      //   specialization for that template, the explicit instantiation ha=
s no
+      //   effect.
+      for (Decl *Prev =3D PrevDecl; Prev; Prev =3D Prev->getPreviousDecl()=
) {
+        // Is there any previous explicit specialization declaration?
+        if (getTemplateSpecializationKind(Prev) =3D=3D TSK_ExplicitSpecial=
ization) {
+          HasNoEffect =3D true;
+          break;
+        }
+      }
+
       return false;
=20
     case TSK_ExplicitInstantiationDefinition:
@@ -5354,12 +5704,11 @@
       //       in a program,
       Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
         << PrevDecl;
-      Diag(PrevPointOfInstantiation,
+      Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiat=
ion),
            diag::note_previous_explicit_instantiation);
       HasNoEffect =3D true;
       return false;
     }
-    break;
   }
=20
   llvm_unreachable("Missing specialization/instantiation case?");
@@ -5486,8 +5835,13 @@
   // Note: do not overwrite location info if previous template
   // specialization kind was explicit.
   TemplateSpecializationKind TSK =3D SpecInfo->getTemplateSpecializationKi=
nd();
-  if (TSK =3D=3D TSK_Undeclared || TSK =3D=3D TSK_ImplicitInstantiation)
+  if (TSK =3D=3D TSK_Undeclared || TSK =3D=3D TSK_ImplicitInstantiation) {
     Specialization->setLocation(FD->getLocation());
+    // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
+    // function can differ from the template declaration with respect to
+    // the constexpr specifier.
+    Specialization->setConstexpr(FD->isConstexpr());
+  }
=20
   // FIXME: Check if the prior specialization has a point of instantiation.
   // If so, we have run afoul of .
@@ -5601,6 +5955,14 @@
       InstantiatedFrom =3D PrevRecord->getInstantiatedFromMemberClass();
       MSInfo =3D PrevRecord->getMemberSpecializationInfo();
     }
+  } else if (isa<EnumDecl>(Member)) {
+    EnumDecl *PrevEnum;
+    if (Previous.isSingleResult() &&
+        (PrevEnum =3D dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
+      Instantiation =3D PrevEnum;
+      InstantiatedFrom =3D PrevEnum->getInstantiatedFromMemberEnum();
+      MSInfo =3D PrevEnum->getMemberSpecializationInfo();
+    }
   }
=20
   if (!Instantiation) {
@@ -5639,7 +6001,7 @@
=20
   // C++ [temp.expl.spec]p6:
   //   If a template, a member template or the member of a class template =
is
-  //   explicitly specialized then that spe- cialization shall be declared
+  //   explicitly specialized then that specialization shall be declared
   //   before the first use of that specialization that would cause an imp=
licit
   //   instantiation to take place, in every translation unit in which suc=
h a
   //   use occurs; no diagnostic is required.
@@ -5691,8 +6053,7 @@
                                                 cast<VarDecl>(Instantiated=
From),
                                                 TSK_ExplicitSpecialization=
);
     MarkUnusedFileScopedDecl(InstantiationVar);
-  } else {
-    assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
+  } else if (isa<CXXRecordDecl>(Member)) {
     CXXRecordDecl *InstantiationClass =3D cast<CXXRecordDecl>(Instantiatio=
n);
     if (InstantiationClass->getTemplateSpecializationKind() =3D=3D
           TSK_ImplicitInstantiation) {
@@ -5704,6 +6065,18 @@
     cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
                                         cast<CXXRecordDecl>(InstantiatedFr=
om),
                                                    TSK_ExplicitSpecializat=
ion);
+  } else {
+    assert(isa<EnumDecl>(Member) && "Only member enums remain");
+    EnumDecl *InstantiationEnum =3D cast<EnumDecl>(Instantiation);
+    if (InstantiationEnum->getTemplateSpecializationKind() =3D=3D
+          TSK_ImplicitInstantiation) {
+      InstantiationEnum->setTemplateSpecializationKind(
+                                                   TSK_ExplicitSpecializat=
ion);
+      InstantiationEnum->setLocation(Member->getLocation());
+    }
+
+    cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
+        cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
   }
=20
   // Save the caller the trouble of having to figure out which declaration
@@ -5728,45 +6101,41 @@
     return true;
   }
=20
-  // C++0x [temp.explicit]p2:
+  // C++11 [temp.explicit]p3:
   //   An explicit instantiation shall appear in an enclosing namespace of=
 its
-  //   template.
+  //   template. If the name declared in the explicit instantiation is an
+  //   unqualified name, the explicit instantiation shall appear in the
+  //   namespace where its template is declared or, if that namespace is i=
nline
+  //   (7.3.1), any namespace from its enclosing namespace set.
   //
   // This is DR275, which we do not retroactively apply to C++98/03.
-  if (S.getLangOptions().CPlusPlus0x &&
-      !CurContext->Encloses(OrigContext)) {
-    if (NamespaceDecl *NS =3D dyn_cast<NamespaceDecl>(OrigContext))
+  if (WasQualifiedName) {
+    if (CurContext->Encloses(OrigContext))
+      return false;
+  } else {
+    if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
+      return false;
+  }
+
+  if (NamespaceDecl *NS =3D dyn_cast<NamespaceDecl>(OrigContext)) {
+    if (WasQualifiedName)
       S.Diag(InstLoc,
-             S.getLangOptions().CPlusPlus0x?
-                 diag::err_explicit_instantiation_out_of_scope
-               : diag::warn_explicit_instantiation_out_of_scope_0x)
+             S.getLangOpts().CPlusPlus0x?
+               diag::err_explicit_instantiation_out_of_scope :
+               diag::warn_explicit_instantiation_out_of_scope_0x)
         << D << NS;
     else
       S.Diag(InstLoc,
-             S.getLangOptions().CPlusPlus0x?
-                 diag::err_explicit_instantiation_must_be_global
-               : diag::warn_explicit_instantiation_out_of_scope_0x)
-        << D;
-    S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
-    return false;
-  }
-
-  // C++0x [temp.explicit]p2:
-  //   If the name declared in the explicit instantiation is an unqualified
-  //   name, the explicit instantiation shall appear in the namespace where
-  //   its template is declared or, if that namespace is inline (7.3.1), a=
ny
-  //   namespace from its enclosing namespace set.
-  if (WasQualifiedName)
-    return false;
-
-  if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
-    return false;
-
-  S.Diag(InstLoc,
-         S.getLangOptions().CPlusPlus0x?
-             diag::err_explicit_instantiation_unqualified_wrong_namespace
-           : diag::warn_explicit_instantiation_unqualified_wrong_namespace=
_0x)
-    << D << OrigContext;
+             S.getLangOpts().CPlusPlus0x?
+               diag::err_explicit_instantiation_unqualified_wrong_namespac=
e :
+               diag::warn_explicit_instantiation_unqualified_wrong_namespa=
ce_0x)
+        << D << NS;
+  } else
+    S.Diag(InstLoc,
+           S.getLangOpts().CPlusPlus0x?
+             diag::err_explicit_instantiation_must_be_global :
+             diag::warn_explicit_instantiation_must_be_global_0x)
+      << D;
   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
   return false;
 }
@@ -5776,7 +6145,7 @@
   if (!SS.isSet())
     return false;
=20
-  // C++0x [temp.explicit]p2:
+  // C++11 [temp.explicit]p3:
   //   If the explicit instantiation is for a member function, a member cl=
ass
   //   or a static data member of a class template specialization, the nam=
e of
   //   the class template specialization in the qualified-id for the member
@@ -5847,9 +6216,6 @@
                                 TemplateArgs, false, Converted))
     return true;
=20
-  assert((Converted.size() =3D=3D ClassTemplate->getTemplateParameters()->=
size()) &&
-         "Converted template argument list is too short!");
-
   // Find the class template specialization declaration that
   // corresponds to these arguments.
   void *InsertPos =3D 0;
@@ -5932,6 +6298,9 @@
   Specialization->setExternLoc(ExternLoc);
   Specialization->setTemplateKeywordLoc(TemplateLoc);
=20
+  if (Attr)
+    ProcessDeclAttributeList(S, Specialization, Attr);
+
   // Add the explicit instantiation into its lexical context. However,
   // since explicit instantiations are never found by name lookup, we
   // just put it into the declaration context directly.
@@ -6000,7 +6369,7 @@
                         KWLoc, SS, Name, NameLoc, Attr, AS_none,
                         /*ModulePrivateLoc=3D*/SourceLocation(),
                         MultiTemplateParamsArg(*this, 0, 0),
-                        Owned, IsDependent, false, false,
+                        Owned, IsDependent, SourceLocation(), false,
                         TypeResult());
   assert(!IsDependent && "explicit instantiation of dependent name not yet=
 handled");
=20
@@ -6008,11 +6377,7 @@
     return true;
=20
   TagDecl *Tag =3D cast<TagDecl>(TagD);
-  if (Tag->isEnum()) {
-    Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
-      << Context.getTypeDeclType(Tag);
-    return true;
-  }
+  assert(!Tag->isEnum() && "shouldn't see enumerations here");
=20
   if (Tag->isInvalidDecl())
     return true;
@@ -6053,7 +6418,7 @@
=20
   // Verify that it is okay to explicitly instantiate here.
   CXXRecordDecl *PrevDecl
-    =3D cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
+    =3D cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
   if (!PrevDecl && Record->getDefinition())
     PrevDecl =3D Record;
   if (PrevDecl) {
@@ -6120,7 +6485,7 @@
   DeclarationName Name =3D NameInfo.getName();
   if (!Name) {
     if (!D.isInvalidType())
-      Diag(D.getDeclSpec().getSourceRange().getBegin(),
+      Diag(D.getDeclSpec().getLocStart(),
            diag::err_explicit_instantiation_requires_name)
         << D.getDeclSpec().getSourceRange()
         << D.getSourceRange();
@@ -6161,9 +6526,11 @@
   //   inline or constexpr specifiers.
   // Presumably, this also applies to member functions of class templates =
as
   // well.
-  if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
+  if (D.getDeclSpec().isInlineSpecified())
     Diag(D.getDeclSpec().getInlineSpecLoc(),
-         diag::err_explicit_instantiation_inline)
+         getLangOpts().CPlusPlus0x ?
+           diag::err_explicit_instantiation_inline :
+           diag::warn_explicit_instantiation_inline_0x)
       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
   if (D.getDeclSpec().isConstexprSpecified())
     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if =
one is
@@ -6326,7 +6693,7 @@
     return true;
   }
=20
-  FunctionDecl *PrevDecl =3D Specialization->getPreviousDeclaration();
+  FunctionDecl *PrevDecl =3D Specialization->getPreviousDecl();
   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
     PrevDecl =3D Specialization;
=20
@@ -6346,6 +6713,9 @@
   }
=20
   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
+  AttributeList *Attr =3D D.getDeclSpec().getAttributes().getList();
+  if (Attr)
+    ProcessDeclAttributeList(S, Specialization, Attr);
=20
   if (TSK =3D=3D TSK_ExplicitInstantiationDefinition)
     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
@@ -6402,7 +6772,7 @@
   // Create type-source location information for this type.
   TypeLocBuilder TLB;
   DependentNameTypeLoc TL =3D TLB.push<DependentNameTypeLoc>(Result);
-  TL.setKeywordLoc(TagLoc);
+  TL.setElaboratedKeywordLoc(TagLoc);
   TL.setQualifierLoc(SS.getWithLocInContext(Context));
   TL.setNameLoc(NameLoc);
   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
@@ -6415,9 +6785,11 @@
   if (SS.isInvalid())
     return true;
  =20
-  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
-      !getLangOptions().CPlusPlus0x)
-    Diag(TypenameLoc, diag::ext_typename_outside_of_template)
+  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
+    Diag(TypenameLoc,
+         getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_typename_outside_of_template :
+           diag::ext_typename_outside_of_template)
       << FixItHint::CreateRemoval(TypenameLoc);
=20
   NestedNameSpecifierLoc QualifierLoc =3D SS.getWithLocInContext(Context);
@@ -6429,12 +6801,12 @@
   TypeSourceInfo *TSI =3D Context.CreateTypeSourceInfo(T);
   if (isa<DependentNameType>(T)) {
     DependentNameTypeLoc TL =3D cast<DependentNameTypeLoc>(TSI->getTypeLoc=
());
-    TL.setKeywordLoc(TypenameLoc);
+    TL.setElaboratedKeywordLoc(TypenameLoc);
     TL.setQualifierLoc(QualifierLoc);
     TL.setNameLoc(IdLoc);
   } else {
     ElaboratedTypeLoc TL =3D cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
-    TL.setKeywordLoc(TypenameLoc);
+    TL.setElaboratedKeywordLoc(TypenameLoc);
     TL.setQualifierLoc(QualifierLoc);
     cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
   }
@@ -6443,18 +6815,21 @@
 }
=20
 TypeResult
-Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,=20
-                        const CXXScopeSpec &SS,=20
-                        SourceLocation TemplateLoc,=20
+Sema::ActOnTypenameType(Scope *S,
+                        SourceLocation TypenameLoc,
+                        const CXXScopeSpec &SS,
+                        SourceLocation TemplateKWLoc,
                         TemplateTy TemplateIn,
                         SourceLocation TemplateNameLoc,
                         SourceLocation LAngleLoc,
                         ASTTemplateArgsPtr TemplateArgsIn,
                         SourceLocation RAngleLoc) {
-  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
-      !getLangOptions().CPlusPlus0x)
-    Diag(TypenameLoc, diag::ext_typename_outside_of_template)
-    << FixItHint::CreateRemoval(TypenameLoc);
+  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
+    Diag(TypenameLoc,
+         getLangOpts().CPlusPlus0x ?
+           diag::warn_cxx98_compat_typename_outside_of_template :
+           diag::ext_typename_outside_of_template)
+      << FixItHint::CreateRemoval(TypenameLoc);
  =20
   // Translate the parser's template argument list in our AST format.
   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
@@ -6475,11 +6850,12 @@
     TypeLocBuilder Builder;
     DependentTemplateSpecializationTypeLoc SpecTL=20
     =3D Builder.push<DependentTemplateSpecializationTypeLoc>(T);
+    SpecTL.setElaboratedKeywordLoc(TypenameLoc);
+    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
+    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
+    SpecTL.setTemplateNameLoc(TemplateNameLoc);
     SpecTL.setLAngleLoc(LAngleLoc);
     SpecTL.setRAngleLoc(RAngleLoc);
-    SpecTL.setKeywordLoc(TypenameLoc);
-    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
-    SpecTL.setNameLoc(TemplateNameLoc);
     for (unsigned I =3D 0, N =3D TemplateArgs.size(); I !=3D N; ++I)
       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
@@ -6489,22 +6865,20 @@
   if (T.isNull())
     return true;
  =20
-  // Provide source-location information for the template specialization=20
-  // type.
+  // Provide source-location information for the template specialization t=
ype.
   TypeLocBuilder Builder;
-  TemplateSpecializationTypeLoc SpecTL=20
+  TemplateSpecializationTypeLoc SpecTL
     =3D Builder.push<TemplateSpecializationTypeLoc>(T);
- =20
-  // FIXME: No place to set the location of the 'template' keyword!
+  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
+  SpecTL.setTemplateNameLoc(TemplateNameLoc);
   SpecTL.setLAngleLoc(LAngleLoc);
   SpecTL.setRAngleLoc(RAngleLoc);
-  SpecTL.setTemplateNameLoc(TemplateNameLoc);
   for (unsigned I =3D 0, N =3D TemplateArgs.size(); I !=3D N; ++I)
     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  =20
   T =3D Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
   ElaboratedTypeLoc TL =3D Builder.push<ElaboratedTypeLoc>(T);
-  TL.setKeywordLoc(TypenameLoc);
+  TL.setElaboratedKeywordLoc(TypenameLoc);
   TL.setQualifierLoc(SS.getWithLocInContext(Context));
  =20
   TypeSourceInfo *TSI =3D Builder.getTypeSourceInfo(Context, T);
@@ -6588,10 +6962,6 @@
     Referenced =3D Result.getFoundDecl();
     break;
=20
-
-    llvm_unreachable("unresolved using decl in non-dependent context");
-    return QualType();
-
   case LookupResult::FoundOverloaded:
     DiagID =3D diag::err_typename_nested_not_type;
     Referenced =3D *Result.begin();
@@ -6650,6 +7020,11 @@
       this->Loc =3D Loc;
       this->Entity =3D Entity;
     }
+     =20
+    ExprResult TransformLambdaExpr(LambdaExpr *E) {
+      // Lambdas never need to be transformed.
+      return E;
+    }
   };
 }
=20
@@ -6762,7 +7137,7 @@
 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
                                       const TemplateArgument *Args,
                                       unsigned NumArgs) {
-  llvm::SmallString<128> Str;
+  SmallString<128> Str;
   llvm::raw_svector_ostream Out(Str);
=20
   if (!Params || Params->size() =3D=3D 0 || NumArgs =3D=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaTemplateDeduction.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateDeduction.cpp	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateDeduction.cpp	Tue =
Apr 17 11:51:51 2012 +0300
@@ -20,7 +20,7 @@
 #include "clang/AST/StmtVisitor.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprCXX.h"
-#include "llvm/ADT/BitVector.h"
+#include "llvm/ADT/SmallBitVector.h"
 #include "TreeTransform.h"
 #include <algorithm>
=20
@@ -112,15 +112,16 @@
=20
=20
 static Sema::TemplateDeductionResult
-DeduceTemplateArguments(Sema &S,
-                        TemplateParameterList *TemplateParams,
-                        QualType Param,
-                        QualType Arg,
-                        TemplateDeductionInfo &Info,
-                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
-                        unsigned TDF,
-                        bool PartialOrdering =3D false,
-                      SmallVectorImpl<RefParamPartialOrderingComparison> *
+DeduceTemplateArgumentsByTypeMatch(Sema &S,
+                                   TemplateParameterList *TemplateParams,
+                                   QualType Param,
+                                   QualType Arg,
+                                   TemplateDeductionInfo &Info,
+                                   SmallVectorImpl<DeducedTemplateArgument=
> &
+                                                      Deduced,
+                                   unsigned TDF,
+                                   bool PartialOrdering =3D false,
+                            SmallVectorImpl<RefParamPartialOrderingCompari=
son> *
                                                       RefParamComparisons =
=3D 0);
=20
 static Sema::TemplateDeductionResult
@@ -277,7 +278,7 @@
     return X;
   }
=20
-  return DeducedTemplateArgument();
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 /// \brief Deduce the value of the given non-type template parameter
@@ -547,7 +548,7 @@
 /// arguments in a set of argument packs.
 static void PrepareArgumentPackDeduction(Sema &S,
                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
-                             const SmallVectorImpl<unsigned> &PackIndices,
+                                           ArrayRef<unsigned> PackIndices,
                      SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
          SmallVectorImpl<
            SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
@@ -582,7 +583,7 @@
                             TemplateParameterList *TemplateParams,
                             bool HasAnyArguments,
                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
-                            const SmallVectorImpl<unsigned> &PackIndices,
+                            ArrayRef<unsigned> PackIndices,
                     SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
         SmallVectorImpl<
           SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
@@ -705,12 +706,11 @@
       }
=20
       if (Sema::TemplateDeductionResult Result
-            =3D DeduceTemplateArguments(S, TemplateParams,
-                                      Params[ParamIdx],
-                                      Args[ArgIdx],
-                                      Info, Deduced, TDF,
-                                      PartialOrdering,
-                                      RefParamComparisons))
+            =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                 Params[ParamIdx], Args[Ar=
gIdx],
+                                                 Info, Deduced, TDF,
+                                                 PartialOrdering,
+                                                 RefParamComparisons))
         return Result;
=20
       ++ArgIdx;
@@ -736,7 +736,7 @@
     SmallVector<unsigned, 2> PackIndices;
     QualType Pattern =3D Expansion->getPattern();
     {
-      llvm::BitVector SawIndices(TemplateParams->size());
+      llvm::SmallBitVector SawIndices(TemplateParams->size());
       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
       S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
       for (unsigned I =3D 0, N =3D Unexpanded.size(); I !=3D N; ++I) {
@@ -766,9 +766,10 @@
=20
       // Deduce template arguments from the pattern.
       if (Sema::TemplateDeductionResult Result
-            =3D DeduceTemplateArguments(S, TemplateParams, Pattern, Args[A=
rgIdx],
-                                      Info, Deduced, TDF, PartialOrdering,
-                                      RefParamComparisons))
+            =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Patt=
ern,
+                                                 Args[ArgIdx], Info, Deduc=
ed,
+                                                 TDF, PartialOrdering,
+                                                 RefParamComparisons))
         return Result;
=20
       // Capture the deduced template arguments for each parameter pack ex=
panded
@@ -858,14 +859,15 @@
 /// "success" result means that template argument deduction has not yet fa=
iled,
 /// but it may still fail, later, for other reasons.
 static Sema::TemplateDeductionResult
-DeduceTemplateArguments(Sema &S,
-                        TemplateParameterList *TemplateParams,
-                        QualType ParamIn, QualType ArgIn,
-                        TemplateDeductionInfo &Info,
-                     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
-                        unsigned TDF,
-                        bool PartialOrdering,
-    SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparison=
s) {
+DeduceTemplateArgumentsByTypeMatch(Sema &S,
+                                   TemplateParameterList *TemplateParams,
+                                   QualType ParamIn, QualType ArgIn,
+                                   TemplateDeductionInfo &Info,
+                            SmallVectorImpl<DeducedTemplateArgument> &Dedu=
ced,
+                                   unsigned TDF,
+                                   bool PartialOrdering,
+                            SmallVectorImpl<RefParamPartialOrderingCompari=
son> *
+                                                          RefParamComparis=
ons) {
   // We only want to look at the canonical types, since typedefs and
   // sugar are not part of template argument deduction.
   QualType Param =3D S.Context.getCanonicalType(ParamIn);
@@ -960,14 +962,6 @@
     }
   }
=20
-  // If the parameter type is not dependent, there is nothing to deduce.
-  if (!Param->isDependentType()) {
-    if (!(TDF & TDF_SkipNonDependent) && Param !=3D Arg)
-      return Sema::TDK_NonDeducedMismatch;
-
-    return Sema::TDK_Success;
-  }
-
   // C++ [temp.deduct.type]p9:
   //   A template type argument T, a template template argument TT or a
   //   template non-type argument i can be deduced if P and A have one of
@@ -1035,7 +1029,7 @@
     // Objective-C ARC:
     //   If template deduction would produce an argument type with lifetim=
e type
     //   but no lifetime qualifier, the __strong lifetime qualifier is inf=
erred.
-    if (S.getLangOptions().ObjCAutoRefCount &&
+    if (S.getLangOpts().ObjCAutoRefCount &&
         DeducedType->isObjCLifetimeType() &&
         !DeducedQs.hasObjCLifetime())
       DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
@@ -1081,6 +1075,17 @@
       if (Param.getCVRQualifiers() !=3D Arg.getCVRQualifiers())
         return Sema::TDK_NonDeducedMismatch;
     }
+   =20
+    // If the parameter type is not dependent, there is nothing to deduce.
+    if (!Param->isDependentType()) {
+      if (!(TDF & TDF_SkipNonDependent) && Param !=3D Arg)
+        return Sema::TDK_NonDeducedMismatch;
+     =20
+      return Sema::TDK_Success;
+    }
+  } else if (!Param->isDependentType() &&
+             Param.getUnqualifiedType() =3D=3D Arg.getUnqualifiedType()) {
+    return Sema::TDK_Success;
   }
=20
   switch (Param->getTypeClass()) {
@@ -1093,9 +1098,9 @@
     case Type::TemplateTypeParm:
     case Type::SubstTemplateTypeParmPack:
       llvm_unreachable("Type nodes handled above");
-     =20
-    // These types cannot be used in templates or cannot be dependent, so
-    // deduction always fails.
+
+    // These types cannot be dependent, so simply check whether the types =
are
+    // the same.
     case Type::Builtin:
     case Type::VariableArray:
     case Type::Vector:
@@ -1104,23 +1109,32 @@
     case Type::Enum:
     case Type::ObjCObject:
     case Type::ObjCInterface:
-    case Type::ObjCObjectPointer:
-      return Sema::TDK_NonDeducedMismatch;
-
+    case Type::ObjCObjectPointer: {
+      if (TDF & TDF_SkipNonDependent)
+        return Sema::TDK_Success;
+     =20
+      if (TDF & TDF_IgnoreQualifiers) {
+        Param =3D Param.getUnqualifiedType();
+        Arg =3D Arg.getUnqualifiedType();
+      }
+           =20
+      return Param =3D=3D Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMis=
match;
+    }
+     =20
     //     _Complex T   [placeholder extension] =20
     case Type::Complex:
       if (const ComplexType *ComplexArg =3D Arg->getAs<ComplexType>())
-        return DeduceTemplateArguments(S, TemplateParams,=20
+        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,=20
                                     cast<ComplexType>(Param)->getElementTy=
pe(),=20
-                                       ComplexArg->getElementType(),
-                                       Info, Deduced, TDF);
+                                    ComplexArg->getElementType(),
+                                    Info, Deduced, TDF);
=20
       return Sema::TDK_NonDeducedMismatch;
=20
     //     _Atomic T   [extension]
     case Type::Atomic:
       if (const AtomicType *AtomicArg =3D Arg->getAs<AtomicType>())
-        return DeduceTemplateArguments(S, TemplateParams,
+        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
                                        cast<AtomicType>(Param)->getValueTy=
pe(),
                                        AtomicArg->getValueType(),
                                        Info, Deduced, TDF);
@@ -1140,8 +1154,8 @@
       }
=20
       unsigned SubTDF =3D TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
-      return DeduceTemplateArguments(S, TemplateParams,
-                                   cast<PointerType>(Param)->getPointeeTyp=
e(),
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                     cast<PointerType>(Param)->getPointeeT=
ype(),
                                      PointeeType,
                                      Info, Deduced, SubTDF);
     }
@@ -1152,10 +1166,9 @@
       if (!ReferenceArg)
         return Sema::TDK_NonDeducedMismatch;
=20
-      return DeduceTemplateArguments(S, TemplateParams,
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
                            cast<LValueReferenceType>(Param)->getPointeeTyp=
e(),
-                                     ReferenceArg->getPointeeType(),
-                                     Info, Deduced, 0);
+                           ReferenceArg->getPointeeType(), Info, Deduced, =
0);
     }
=20
     //     T && [C++0x]
@@ -1164,10 +1177,10 @@
       if (!ReferenceArg)
         return Sema::TDK_NonDeducedMismatch;
=20
-      return DeduceTemplateArguments(S, TemplateParams,
-                           cast<RValueReferenceType>(Param)->getPointeeTyp=
e(),
-                                     ReferenceArg->getPointeeType(),
-                                     Info, Deduced, 0);
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                             cast<RValueReferenceType>(Param)->getPointeeT=
ype(),
+                             ReferenceArg->getPointeeType(),
+                             Info, Deduced, 0);
     }
=20
     //     T [] (implied, but not stated explicitly)
@@ -1178,10 +1191,10 @@
         return Sema::TDK_NonDeducedMismatch;
=20
       unsigned SubTDF =3D TDF & TDF_IgnoreQualifiers;
-      return DeduceTemplateArguments(S, TemplateParams,
-                     S.Context.getAsIncompleteArrayType(Param)->getElement=
Type(),
-                                     IncompleteArrayArg->getElementType(),
-                                     Info, Deduced, SubTDF);
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                    S.Context.getAsIncompleteArrayType(Param)->getElementT=
ype(),
+                    IncompleteArrayArg->getElementType(),
+                    Info, Deduced, SubTDF);
     }
=20
     //     T [integer-constant]
@@ -1197,10 +1210,10 @@
         return Sema::TDK_NonDeducedMismatch;
=20
       unsigned SubTDF =3D TDF & TDF_IgnoreQualifiers;
-      return DeduceTemplateArguments(S, TemplateParams,
-                                     ConstantArrayParm->getElementType(),
-                                     ConstantArrayArg->getElementType(),
-                                     Info, Deduced, SubTDF);
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                           ConstantArrayParm->getElementTy=
pe(),
+                                           ConstantArrayArg->getElementTyp=
e(),
+                                           Info, Deduced, SubTDF);
     }
=20
     //     type [i]
@@ -1215,10 +1228,10 @@
       const DependentSizedArrayType *DependentArrayParm
         =3D S.Context.getAsDependentSizedArrayType(Param);
       if (Sema::TemplateDeductionResult Result
-            =3D DeduceTemplateArguments(S, TemplateParams,
-                                      DependentArrayParm->getElementType(),
-                                      ArrayArg->getElementType(),
-                                      Info, Deduced, SubTDF))
+            =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                          DependentArrayParm->getElementTy=
pe(),
+                                          ArrayArg->getElementType(),
+                                          Info, Deduced, SubTDF))
         return Result;
=20
       // Determine the array bound is something we can deduce.
@@ -1272,10 +1285,10 @@
=20
       // Check return types.
       if (Sema::TemplateDeductionResult Result
-            =3D DeduceTemplateArguments(S, TemplateParams,
-                                      FunctionProtoParam->getResultType(),
-                                      FunctionProtoArg->getResultType(),
-                                      Info, Deduced, 0))
+            =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                            FunctionProtoParam->getResultT=
ype(),
+                                            FunctionProtoArg->getResultTyp=
e(),
+                                            Info, Deduced, 0))
         return Result;
=20
       return DeduceTemplateArguments(S, TemplateParams,
@@ -1334,8 +1347,8 @@
           SmallVector<const RecordType *, 8> ToVisit;
           ToVisit.push_back(RecordT);
           bool Successful =3D false;
-          SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
-          DeducedOrig =3D Deduced;
+          SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begi=
n(),
+                                                              Deduced.end(=
));
           while (!ToVisit.empty()) {
             // Retrieve the next class in the inheritance hierarchy.
             const RecordType *NextT =3D ToVisit.back();
@@ -1357,7 +1370,8 @@
               // from this base class.
               if (BaseResult =3D=3D Sema::TDK_Success) {
                 Successful =3D true;
-                DeducedOrig =3D Deduced;
+                DeducedOrig.clear();
+                DeducedOrig.append(Deduced.begin(), Deduced.end());
               }
               else
                 Deduced =3D DeducedOrig;
@@ -1399,17 +1413,18 @@
         return Sema::TDK_NonDeducedMismatch;
=20
       if (Sema::TemplateDeductionResult Result
-            =3D DeduceTemplateArguments(S, TemplateParams,
-                                      MemPtrParam->getPointeeType(),
-                                      MemPtrArg->getPointeeType(),
-                                      Info, Deduced,
-                                      TDF & TDF_IgnoreQualifiers))
+            =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                 MemPtrParam->getPointeeTy=
pe(),
+                                                 MemPtrArg->getPointeeType=
(),
+                                                 Info, Deduced,
+                                                 TDF & TDF_IgnoreQualifier=
s))
         return Result;
=20
-      return DeduceTemplateArguments(S, TemplateParams,
-                                     QualType(MemPtrParam->getClass(), 0),
-                                     QualType(MemPtrArg->getClass(), 0),
-                                     Info, Deduced, 0);
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                           QualType(MemPtrParam->getClass(=
), 0),
+                                           QualType(MemPtrArg->getClass(),=
 0),
+                                           Info, Deduced,=20
+                                           TDF & TDF_IgnoreQualifiers);
     }
=20
     //     (clang extension)
@@ -1424,10 +1439,10 @@
       if (!BlockPtrArg)
         return Sema::TDK_NonDeducedMismatch;
=20
-      return DeduceTemplateArguments(S, TemplateParams,
-                                     BlockPtrParam->getPointeeType(),
-                                     BlockPtrArg->getPointeeType(), Info,
-                                     Deduced, 0);
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                BlockPtrParam->getPointeeT=
ype(),
+                                                BlockPtrArg->getPointeeTyp=
e(),
+                                                Info, Deduced, 0);
     }
=20
     //     (clang extension)
@@ -1441,11 +1456,10 @@
           return Sema::TDK_NonDeducedMismatch;
        =20
         // Perform deduction on the element types.
-        return DeduceTemplateArguments(S, TemplateParams,
-                                       VectorParam->getElementType(),
-                                       VectorArg->getElementType(),
-                                       Info, Deduced,
-                                       TDF);
+        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                  VectorParam->getElementT=
ype(),
+                                                  VectorArg->getElementTyp=
e(),
+                                                  Info, Deduced, TDF);
       }
      =20
       if (const DependentSizedExtVectorType *VectorArg=20
@@ -1455,11 +1469,10 @@
         // ordering.
=20
         // Perform deduction on the element types.
-        return DeduceTemplateArguments(S, TemplateParams,
-                                       VectorParam->getElementType(),
-                                       VectorArg->getElementType(),
-                                       Info, Deduced,
-                                       TDF);
+        return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                  VectorParam->getElementT=
ype(),
+                                                  VectorArg->getElementTyp=
e(),
+                                                  Info, Deduced, TDF);
       }
      =20
       return Sema::TDK_NonDeducedMismatch;
@@ -1475,11 +1488,10 @@
       if (const ExtVectorType *VectorArg =3D dyn_cast<ExtVectorType>(Arg))=
 {
         // Perform deduction on the element types.
         if (Sema::TemplateDeductionResult Result
-              =3D DeduceTemplateArguments(S, TemplateParams,
-                                        VectorParam->getElementType(),
-                                        VectorArg->getElementType(),
-                                        Info, Deduced,
-                                        TDF))
+              =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                  VectorParam->getElementT=
ype(),
+                                                   VectorArg->getElementTy=
pe(),
+                                                   Info, Deduced, TDF))
           return Result;
        =20
         // Perform deduction on the vector size, if we can.
@@ -1498,11 +1510,10 @@
                                 =3D dyn_cast<DependentSizedExtVectorType>(=
Arg)) {
         // Perform deduction on the element types.
         if (Sema::TemplateDeductionResult Result
-            =3D DeduceTemplateArguments(S, TemplateParams,
-                                      VectorParam->getElementType(),
-                                      VectorArg->getElementType(),
-                                      Info, Deduced,
-                                      TDF))
+            =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                 VectorParam->getElementTy=
pe(),
+                                                 VectorArg->getElementType=
(),
+                                                 Info, Deduced, TDF))
           return Result;
        =20
         // Perform deduction on the vector size, if we can.
@@ -1531,7 +1542,7 @@
       return Sema::TDK_Success;
   }
=20
-  return Sema::TDK_Success;
+  llvm_unreachable("Invalid Type Class!");
 }
=20
 static Sema::TemplateDeductionResult
@@ -1553,8 +1564,10 @@
=20
   case TemplateArgument::Type:
     if (Arg.getKind() =3D=3D TemplateArgument::Type)
-      return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
-                                     Arg.getAsType(), Info, Deduced, 0);
+      return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                                Param.getAsType(),
+                                                Arg.getAsType(),
+                                                Info, Deduced, 0);
     Info.FirstArg =3D Param;
     Info.SecondArg =3D Arg;
     return Sema::TDK_NonDeducedMismatch;
@@ -1570,12 +1583,10 @@
=20
   case TemplateArgument::TemplateExpansion:
     llvm_unreachable("caller should handle pack expansions");
-    break;
=20
   case TemplateArgument::Declaration:
     if (Arg.getKind() =3D=3D TemplateArgument::Declaration &&
-        Param.getAsDecl()->getCanonicalDecl() =3D=3D
-          Arg.getAsDecl()->getCanonicalDecl())
+        isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
       return Sema::TDK_Success;
=20
     Info.FirstArg =3D Param;
@@ -1630,7 +1641,7 @@
     llvm_unreachable("Argument packs should be expanded by the caller!");
   }
=20
-  return Sema::TDK_Success;
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 /// \brief Determine whether there is a template argument to be used for
@@ -1746,7 +1757,7 @@
     // parameter packs expanded by the pack expansion.
     SmallVector<unsigned, 2> PackIndices;
     {
-      llvm::BitVector SawIndices(TemplateParams->size());
+      llvm::SmallBitVector SawIndices(TemplateParams->size());
       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
       S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
       for (unsigned I =3D 0, N =3D Unexpanded.size(); I !=3D N; ++I) {
@@ -1846,8 +1857,7 @@
              Context.getCanonicalType(Y.getAsType());
=20
     case TemplateArgument::Declaration:
-      return X.getAsDecl()->getCanonicalDecl() =3D=3D
-             Y.getAsDecl()->getCanonicalDecl();
+      return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
=20
     case TemplateArgument::Template:
     case TemplateArgument::TemplateExpansion:
@@ -1880,7 +1890,7 @@
       return true;
   }
=20
-  return false;
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
 /// \brief Allocate a TemplateArgumentLoc where all locations have
@@ -1905,7 +1915,6 @@
   switch (Arg.getKind()) {
   case TemplateArgument::Null:
     llvm_unreachable("Can't get a NULL template argument here");
-    break;
=20
   case TemplateArgument::Type:
     return TemplateArgumentLoc(Arg,
@@ -1914,7 +1923,7 @@
   case TemplateArgument::Declaration: {
     Expr *E
       =3D S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
-    .takeAs<Expr>();
+          .takeAs<Expr>();
     return TemplateArgumentLoc(TemplateArgument(E), E);
   }
=20
@@ -1950,7 +1959,7 @@
     return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
   }
=20
-  return TemplateArgumentLoc();
+  llvm_unreachable("Invalid TemplateArgument Kind!");
 }
=20
=20
@@ -2021,7 +2030,8 @@
                                 const TemplateArgumentList &TemplateArgs,
                       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
                                 TemplateDeductionInfo &Info) {
-  // Trap errors.
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
   Sema::SFINAETrap Trap(S);
=20
   Sema::ContextRAII SavedContext(S, Partial);
@@ -2147,7 +2157,11 @@
   //   argument list if the template arguments of the partial
   //   specialization can be deduced from the actual template argument
   //   list (14.8.2).
+
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   SFINAETrap Trap(*this);
+
   SmallVector<DeducedTemplateArgument, 4> Deduced;
   Deduced.resize(Partial->getTemplateParameters()->size());
   if (TemplateDeductionResult Result
@@ -2228,8 +2242,8 @@
     return TDK_Success;
   }
=20
-  // Substitution of the explicit template arguments into a function templ=
ate
-  /// is a SFINAE context. Trap any errors that might occur.
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   SFINAETrap Trap(*this);
=20
   // C++ [temp.arg.explicit]p3:
@@ -2288,33 +2302,45 @@
     }
   }
=20
+  const FunctionProtoType *Proto
+    =3D Function->getType()->getAs<FunctionProtoType>();
+  assert(Proto && "Function template does not have a prototype?");
+
   // Instantiate the types of each of the function parameters given the
-  // explicitly-specified template arguments.
-  if (SubstParmTypes(Function->getLocation(),
+  // explicitly-specified template arguments. If the function has a traili=
ng
+  // return type, substitute it after the arguments to ensure we substitute
+  // in lexical order.
+  if (Proto->hasTrailingReturn() &&
+      SubstParmTypes(Function->getLocation(),
                      Function->param_begin(), Function->getNumParams(),
                      MultiLevelTemplateArgumentList(*ExplicitArgumentList),
                      ParamTypes))
     return TDK_SubstitutionFailure;
=20
-  // If the caller wants a full function type back, instantiate the return
-  // type and form that function type.
+  // Instantiate the return type.
+  // FIXME: exception-specifications?
+  QualType ResultType
+    =3D SubstType(Proto->getResultType(),
+                MultiLevelTemplateArgumentList(*ExplicitArgumentList),
+                Function->getTypeSpecStartLoc(),
+                Function->getDeclName());
+  if (ResultType.isNull() || Trap.hasErrorOccurred())
+    return TDK_SubstitutionFailure;
+
+  // Instantiate the types of each of the function parameters given the
+  // explicitly-specified template arguments if we didn't do so earlier.
+  if (!Proto->hasTrailingReturn() &&
+      SubstParmTypes(Function->getLocation(),
+                     Function->param_begin(), Function->getNumParams(),
+                     MultiLevelTemplateArgumentList(*ExplicitArgumentList),
+                     ParamTypes))
+    return TDK_SubstitutionFailure;
+
   if (FunctionType) {
-    // FIXME: exception-specifications?
-    const FunctionProtoType *Proto
-      =3D Function->getType()->getAs<FunctionProtoType>();
-    assert(Proto && "Function template does not have a prototype?");
-
-    QualType ResultType
-      =3D SubstType(Proto->getResultType(),
-                  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
-                  Function->getTypeSpecStartLoc(),
-                  Function->getDeclName());
-    if (ResultType.isNull() || Trap.hasErrorOccurred())
-      return TDK_SubstitutionFailure;
-
     *FunctionType =3D BuildFunctionType(ResultType,
                                       ParamTypes.data(), ParamTypes.size(),
                                       Proto->isVariadic(),
+                                      Proto->hasTrailingReturn(),
                                       Proto->getTypeQuals(),
                                       Proto->getRefQualifier(),
                                       Function->getLocation(),
@@ -2451,8 +2477,8 @@
   TemplateParameterList *TemplateParams
     =3D FunctionTemplate->getTemplateParameters();
=20
-  // Template argument deduction for function templates in a SFINAE contex=
t.
-  // Trap any errors that might occur.
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   SFINAETrap Trap(*this);
=20
   // Enter a new template instantiation context while we instantiate the
@@ -2681,36 +2707,48 @@
   if (R.IsAddressOfOperand)
     TDF |=3D TDF_IgnoreQualifiers;
=20
-  // If there were explicit template arguments, we can only find
-  // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
-  // unambiguously name a full specialization.
-  if (Ovl->hasExplicitTemplateArgs()) {
-    // But we can still look for an explicit specialization.
-    if (FunctionDecl *ExplicitSpec
-          =3D S.ResolveSingleFunctionTemplateSpecialization(Ovl))
-      return GetTypeOfFunction(S.Context, R, ExplicitSpec);
-    return QualType();
-  }
-
   // C++0x [temp.deduct.call]p6:
   //   When P is a function type, pointer to function type, or pointer
   //   to member function type:
=20
   if (!ParamType->isFunctionType() &&
       !ParamType->isFunctionPointerType() &&
-      !ParamType->isMemberFunctionPointerType())
+      !ParamType->isMemberFunctionPointerType()) {
+    if (Ovl->hasExplicitTemplateArgs()) {
+      // But we can still look for an explicit specialization.
+      if (FunctionDecl *ExplicitSpec
+            =3D S.ResolveSingleFunctionTemplateSpecialization(Ovl))
+        return GetTypeOfFunction(S.Context, R, ExplicitSpec);
+    }
+
     return QualType();
-
+  }
+ =20
+  // Gather the explicit template arguments, if any.
+  TemplateArgumentListInfo ExplicitTemplateArgs;
+  if (Ovl->hasExplicitTemplateArgs())
+    Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
   QualType Match;
   for (UnresolvedSetIterator I =3D Ovl->decls_begin(),
          E =3D Ovl->decls_end(); I !=3D E; ++I) {
     NamedDecl *D =3D (*I)->getUnderlyingDecl();
=20
-    //   - If the argument is an overload set containing one or more
-    //     function templates, the parameter is treated as a
-    //     non-deduced context.
-    if (isa<FunctionTemplateDecl>(D))
-      return QualType();
+    if (FunctionTemplateDecl *FunTmpl =3D dyn_cast<FunctionTemplateDecl>(D=
)) {
+      //   - If the argument is an overload set containing one or more
+      //     function templates, the parameter is treated as a
+      //     non-deduced context.
+      if (!Ovl->hasExplicitTemplateArgs())
+        return QualType();
+     =20
+      // Otherwise, see if we can resolve a function type=20
+      FunctionDecl *Specialization =3D 0;
+      TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
+      if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
+                                    Specialization, Info))
+        continue;
+     =20
+      D =3D Specialization;
+    }
=20
     FunctionDecl *Fn =3D cast<FunctionDecl>(D);
     QualType ArgType =3D GetTypeOfFunction(S.Context, R, Fn);
@@ -2737,9 +2775,8 @@
       Deduced(TemplateParams->size());
     TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
     Sema::TemplateDeductionResult Result
-      =3D DeduceTemplateArguments(S, TemplateParams,
-                                ParamType, ArgType,
-                                Info, Deduced, TDF);
+      =3D DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
+                                           ArgType, Info, Deduced, TDF);
     if (Result) continue;
     if (!Match.isNull()) return QualType();
     Match =3D ArgType;
@@ -2866,6 +2903,44 @@
                                            FunctionTemplateDecl *FunctionT=
emplate,
                                            QualType T);
=20
+/// \brief Perform template argument deduction by matching a parameter type
+///        against a single expression, where the expression is an element=
 of
+///        an initializer list that was originally matched against the arg=
ument
+///        type.
+static Sema::TemplateDeductionResult
+DeduceTemplateArgumentByListElement(Sema &S,
+                                    TemplateParameterList *TemplateParams,
+                                    QualType ParamType, Expr *Arg,
+                                    TemplateDeductionInfo &Info,
+                              SmallVectorImpl<DeducedTemplateArgument> &De=
duced,
+                                    unsigned TDF) {
+  // Handle the case where an init list contains another init list as the
+  // element.
+  if (InitListExpr *ILE =3D dyn_cast<InitListExpr>(Arg)) {
+    QualType X;
+    if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
+      return Sema::TDK_Success; // Just ignore this expression.
+
+    // Recurse down into the init list.
+    for (unsigned i =3D 0, e =3D ILE->getNumInits(); i < e; ++i) {
+      if (Sema::TemplateDeductionResult Result =3D
+            DeduceTemplateArgumentByListElement(S, TemplateParams, X,
+                                                 ILE->getInit(i),
+                                                 Info, Deduced, TDF))
+        return Result;
+    }
+    return Sema::TDK_Success;
+  }
+
+  // For all other cases, just match by type.
+  QualType ArgType =3D Arg->getType();
+  if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamTy=
pe,=20
+                                                ArgType, Arg, TDF))
+    return Sema::TDK_FailedOverloadResolution;
+  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
+                                            ArgType, Info, Deduced, TDF);
+}
+
 /// \brief Perform template argument deduction from a function call
 /// (C++ [temp.deduct.call]).
 ///
@@ -2895,7 +2970,7 @@
 Sema::TemplateDeductionResult
 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
                               TemplateArgumentListInfo *ExplicitTemplateAr=
gs,
-                              Expr **Args, unsigned NumArgs,
+                              llvm::ArrayRef<Expr *> Args,
                               FunctionDecl *&Specialization,
                               TemplateDeductionInfo &Info) {
   FunctionDecl *Function =3D FunctionTemplate->getTemplatedDecl();
@@ -2904,10 +2979,10 @@
   //   Template argument deduction is done by comparing each function temp=
late
   //   parameter type (call it P) with the type of the corresponding argum=
ent
   //   of the call (call it A) as described below.
-  unsigned CheckArgs =3D NumArgs;
-  if (NumArgs < Function->getMinRequiredArguments())
+  unsigned CheckArgs =3D Args.size();
+  if (Args.size() < Function->getMinRequiredArguments())
     return TDK_TooFewArguments;
-  else if (NumArgs > Function->getNumParams()) {
+  else if (Args.size() > Function->getNumParams()) {
     const FunctionProtoType *Proto
       =3D Function->getType()->getAs<FunctionProtoType>();
     if (Proto->isTemplateVariadic())
@@ -2973,15 +3048,37 @@
       if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamTy=
pe))
         continue;
=20
+      // If the argument is an initializer list ...
+      if (InitListExpr *ILE =3D dyn_cast<InitListExpr>(Arg)) {
+        // ... then the parameter is an undeduced context, unless the para=
meter
+        // type is (reference to cv) std::initializer_list<P'>, in which c=
ase
+        // deduction is done for each element of the initializer list, and=
 the
+        // result is the deduced type if it's the same for all elements.
+        QualType X;
+        // Removing references was already done.
+        if (!isStdInitializerList(ParamType, &X))
+          continue;
+
+        for (unsigned i =3D 0, e =3D ILE->getNumInits(); i < e; ++i) {
+          if (TemplateDeductionResult Result =3D
+                DeduceTemplateArgumentByListElement(*this, TemplateParams,=
 X,
+                                                     ILE->getInit(i),
+                                                     Info, Deduced, TDF))
+            return Result;
+        }
+        // Don't track the argument type, since an initializer list has no=
ne.
+        continue;
+      }
+
       // Keep track of the argument type and corresponding parameter index,
       // so we can check for compatibility between the deduced A and A.
       OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,=20
                                                  ArgType));
=20
       if (TemplateDeductionResult Result
-            =3D ::DeduceTemplateArguments(*this, TemplateParams,
-                                        ParamType, ArgType, Info, Deduced,
-                                        TDF))
+            =3D DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
+                                                 ParamType, ArgType,
+                                                 Info, Deduced, TDF))
         return Result;
=20
       continue;
@@ -3002,7 +3099,7 @@
     QualType ParamPattern =3D ParamExpansion->getPattern();
     SmallVector<unsigned, 2> PackIndices;
     {
-      llvm::BitVector SawIndices(TemplateParams->size());
+      llvm::SmallBitVector SawIndices(TemplateParams->size());
       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
       collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
       for (unsigned I =3D 0, N =3D Unexpanded.size(); I !=3D N; ++I) {
@@ -3026,7 +3123,7 @@
     PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
                                  NewlyDeducedPacks);
     bool HasAnyArguments =3D false;
-    for (; ArgIdx < NumArgs; ++ArgIdx) {
+    for (; ArgIdx < Args.size(); ++ArgIdx) {
       HasAnyArguments =3D true;
=20
       QualType OrigParamType =3D ParamPattern;
@@ -3044,17 +3141,35 @@
         break;
       }
=20
-      // Keep track of the argument type and corresponding argument index,
-      // so we can check for compatibility between the deduced A and A.
-      if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamTyp=
e))
-        OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,=20
-                                                   ArgType));
-
-      if (TemplateDeductionResult Result
-          =3D ::DeduceTemplateArguments(*this, TemplateParams,
-                                      ParamType, ArgType, Info, Deduced,
-                                      TDF))
-        return Result;
+      // As above, initializer lists need special handling.
+      if (InitListExpr *ILE =3D dyn_cast<InitListExpr>(Arg)) {
+        QualType X;
+        if (!isStdInitializerList(ParamType, &X)) {
+          ++ArgIdx;
+          break;
+        }
+
+        for (unsigned i =3D 0, e =3D ILE->getNumInits(); i < e; ++i) {
+          if (TemplateDeductionResult Result =3D
+                DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, =
X,
+                                                   ILE->getInit(i)->getTyp=
e(),
+                                                   Info, Deduced, TDF))
+            return Result;
+        }
+      } else {
+
+        // Keep track of the argument type and corresponding argument inde=
x,
+        // so we can check for compatibility between the deduced A and A.
+        if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamT=
ype))
+          OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx=
,=20
+                                                     ArgType));
+
+        if (TemplateDeductionResult Result
+            =3D DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
+                                                 ParamType, ArgType, Info,
+                                                 Deduced, TDF))
+          return Result;
+      }
=20
       // Capture the deduced template arguments for each parameter pack ex=
panded
       // by this pack expansion, add them to the list of arguments we've d=
educed
@@ -3135,8 +3250,8 @@
     NumExplicitlySpecified =3D Deduced.size();
   }
=20
-  // Template argument deduction for function templates in a SFINAE contex=
t.
-  // Trap any errors that might occur.
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   SFINAETrap Trap(*this);
=20
   Deduced.resize(TemplateParams->size());
@@ -3144,7 +3259,7 @@
   if (!ArgFunctionType.isNull()) {
     // Deduce template arguments from the function type.
     if (TemplateDeductionResult Result
-          =3D ::DeduceTemplateArguments(*this, TemplateParams,
+          =3D DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
                                       FunctionType, ArgFunctionType, Info,
                                       Deduced, TDF_TopLevelParameterTypeLi=
st))
       return Result;
@@ -3220,8 +3335,8 @@
     A =3D A.getUnqualifiedType();
   }
=20
-  // Template argument deduction for function templates in a SFINAE contex=
t.
-  // Trap any errors that might occur.
+  // Unevaluated SFINAE context.
+  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
   SFINAETrap Trap(*this);
=20
   // C++ [temp.deduct.conv]p1:
@@ -3255,8 +3370,8 @@
       (P->isMemberPointerType() && A->isMemberPointerType()))
     TDF |=3D TDF_IgnoreQualifiers;
   if (TemplateDeductionResult Result
-        =3D ::DeduceTemplateArguments(*this, TemplateParams,
-                                    P, A, Info, Deduced, TDF))
+        =3D DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
+                                             P, A, Info, Deduced, TDF))
     return Result;
=20
   // Finish template argument deduction.
@@ -3325,6 +3440,11 @@
         return Result;
       }
     }
+
+    ExprResult TransformLambdaExpr(LambdaExpr *E) {
+      // Lambdas never need to be transformed.
+      return E;
+    }
   };
 }
=20
@@ -3339,14 +3459,18 @@
 /// dependent. This will be set to null if deduction succeeded, but auto
 /// substitution failed; the appropriate diagnostic will already have been
 /// produced in that case.
-///
-/// \returns true if deduction succeeded, false if it failed.
-bool
-Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *Init,
+Sema::DeduceAutoResult
+Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init,
                      TypeSourceInfo *&Result) {
+  if (Init->getType()->isNonOverloadPlaceholderType()) {
+    ExprResult result =3D CheckPlaceholderExpr(Init);
+    if (result.isInvalid()) return DAR_FailedAlreadyDiagnosed;
+    Init =3D result.take();
+  }
+
   if (Init->isTypeDependent()) {
     Result =3D Type;
-    return true;
+    return DAR_Succeeded;
   }
=20
   SourceLocation Loc =3D Init->getExprLoc();
@@ -3372,41 +3496,70 @@
   Deduced.resize(1);
   QualType InitType =3D Init->getType();
   unsigned TDF =3D 0;
-  if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
-                                                FuncParam, InitType, Init,
-                                                TDF))
-    return false;
=20
   TemplateDeductionInfo Info(Context, Loc);
-  if (::DeduceTemplateArguments(*this, &TemplateParams,
-                                FuncParam, InitType, Info, Deduced,
-                                TDF))
-    return false;
+
+  InitListExpr * InitList =3D dyn_cast<InitListExpr>(Init);
+  if (InitList) {
+    for (unsigned i =3D 0, e =3D InitList->getNumInits(); i < e; ++i) {
+      if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,=20
+                                              TemplArg,
+                                              InitList->getInit(i),
+                                              Info, Deduced, TDF))
+        return DAR_Failed;
+    }
+  } else {
+    if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
+                                                  FuncParam, InitType, Ini=
t,
+                                                  TDF))
+      return DAR_Failed;
+   =20
+    if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncPar=
am,
+                                           InitType, Info, Deduced, TDF))
+      return DAR_Failed;
+  }
=20
   QualType DeducedType =3D Deduced[0].getAsType();
   if (DeducedType.isNull())
-    return false;
- =20
+    return DAR_Failed;
+
+  if (InitList) {
+    DeducedType =3D BuildStdInitializerList(DeducedType, Loc);
+    if (DeducedType.isNull())
+      return DAR_FailedAlreadyDiagnosed;
+  }
+
   Result =3D SubstituteAutoTransform(*this, DeducedType).TransformType(Typ=
e);
- =20
+
   // Check that the deduced argument type is compatible with the original
   // argument type per C++ [temp.deduct.call]p4.
-  if (Result &&
+  if (!InitList && Result &&
       CheckOriginalCallArgDeduction(*this,=20
                                     Sema::OriginalCallArg(FuncParam,0,Init=
Type),
                                     Result->getType())) {
     Result =3D 0;
-    return false;
+    return DAR_Failed;
   }
=20
-  return true;
+  return DAR_Succeeded;
 }
=20
+void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
+  if (isa<InitListExpr>(Init))
+    Diag(VDecl->getLocation(),
+         diag::err_auto_var_deduction_failure_from_init_list)
+      << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange(=
);
+  else
+    Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
+      << VDecl->getDeclName() << VDecl->getType() << Init->getType()
+      << Init->getSourceRange();
+}
+
 static void
-MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
+MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
                            bool OnlyDeduced,
                            unsigned Level,
-                           SmallVectorImpl<bool> &Deduced);
+                           llvm::SmallBitVector &Deduced);
=20
 /// \brief If this is a non-static member function,
 static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
@@ -3481,17 +3634,17 @@
     // first argument of the free function or static member, which
     // seems to match existing practice.
     SmallVector<QualType, 4> Args1;
-    unsigned Skip1 =3D !S.getLangOptions().CPlusPlus0x &&
+    unsigned Skip1 =3D !S.getLangOpts().CPlusPlus0x &&
       IsNonStatic2 && !IsNonStatic1;
-    if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
+    if (S.getLangOpts().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
       MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
     Args1.insert(Args1.end(),
                  Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
=20
     SmallVector<QualType, 4> Args2;
-    Skip2 =3D !S.getLangOptions().CPlusPlus0x &&
+    Skip2 =3D !S.getLangOpts().CPlusPlus0x &&
       IsNonStatic1 && !IsNonStatic2;
-    if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
+    if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
       MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
     Args2.insert(Args2.end(),
                  Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
@@ -3515,19 +3668,23 @@
   case TPOC_Conversion:
     //   - In the context of a call to a conversion operator, the return t=
ypes
     //     of the conversion function templates are used.
-    if (DeduceTemplateArguments(S, TemplateParams, Proto2->getResultType(),
-                                Proto1->getResultType(), Info, Deduced,
-                                TDF_None, /*PartialOrdering=3D*/true,
-                                RefParamComparisons))
+    if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                           Proto2->getResultType(),
+                                           Proto1->getResultType(),
+                                           Info, Deduced, TDF_None,
+                                           /*PartialOrdering=3D*/true,
+                                           RefParamComparisons))
       return false;
     break;
=20
   case TPOC_Other:
     //   - In other contexts (14.6.6.2) the function template's function t=
ype
     //     is used.
-    if (DeduceTemplateArguments(S, TemplateParams, FD2->getType(),
-                                FD1->getType(), Info, Deduced, TDF_None,
-                                /*PartialOrdering=3D*/true, RefParamCompar=
isons))
+    if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
+                                           FD2->getType(), FD1->getType(),
+                                           Info, Deduced, TDF_None,
+                                           /*PartialOrdering=3D*/true,
+                                           RefParamComparisons))
       return false;
     break;
   }
@@ -3550,31 +3707,31 @@
   }
=20
   // Figure out which template parameters were used.
-  SmallVector<bool, 4> UsedParameters;
-  UsedParameters.resize(TemplateParams->size());
+  llvm::SmallBitVector UsedParameters(TemplateParams->size());
   switch (TPOC) {
   case TPOC_Call: {
     unsigned NumParams =3D std::min(NumCallArguments,
                                   std::min(Proto1->getNumArgs(),
                                            Proto2->getNumArgs()));
-    if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
-      ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), fal=
se,
+    if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
+      ::MarkUsedTemplateParameters(S.Context, Method2->getThisType(S.Conte=
xt),
+                                   false,
                                    TemplateParams->getDepth(), UsedParamet=
ers);
     for (unsigned I =3D Skip2; I < NumParams; ++I)
-      ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
+      ::MarkUsedTemplateParameters(S.Context, Proto2->getArgType(I), false,
                                    TemplateParams->getDepth(),
                                    UsedParameters);
     break;
   }
=20
   case TPOC_Conversion:
-    ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
+    ::MarkUsedTemplateParameters(S.Context, Proto2->getResultType(), false,
                                  TemplateParams->getDepth(),
                                  UsedParameters);
     break;
=20
   case TPOC_Other:
-    ::MarkUsedTemplateParameters(S, FD2->getType(), false,
+    ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
                                  TemplateParams->getDepth(),
                                  UsedParameters);
     break;
@@ -3777,7 +3934,8 @@
                          const PartialDiagnostic &NoneDiag,
                          const PartialDiagnostic &AmbigDiag,
                          const PartialDiagnostic &CandidateDiag,
-                         bool Complain) {
+                         bool Complain,
+                         QualType TargetType) {
   if (SpecBegin =3D=3D SpecEnd) {
     if (Complain)
       Diag(Loc, NoneDiag);
@@ -3831,11 +3989,16 @@
=20
   if (Complain)
   // FIXME: Can we order the candidates in some sane way?
-    for (UnresolvedSetIterator I =3D SpecBegin; I !=3D SpecEnd; ++I)
-      Diag((*I)->getLocation(), CandidateDiag)
-        << getTemplateArgumentBindingsText(
+    for (UnresolvedSetIterator I =3D SpecBegin; I !=3D SpecEnd; ++I) {
+      PartialDiagnostic PD =3D CandidateDiag;
+      PD << getTemplateArgumentBindingsText(
           cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParamet=
ers(),
                     *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs=
());
+      if (!TargetType.isNull())
+        HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
+                                   TargetType);
+      Diag((*I)->getLocation(), PD);
+    }
=20
   return SpecEnd;
 }
@@ -3887,7 +4050,8 @@
=20
   // Determine whether PS1 is at least as specialized as PS2
   Deduced.resize(PS2->getTemplateParameters()->size());
-  bool Better1 =3D !::DeduceTemplateArguments(*this, PS2->getTemplateParam=
eters(),
+  bool Better1 =3D !DeduceTemplateArgumentsByTypeMatch(*this,
+                                            PS2->getTemplateParameters(),
                                             PT2, PT1, Info, Deduced, TDF_N=
one,
                                             /*PartialOrdering=3D*/true,
                                             /*RefParamComparisons=3D*/0);
@@ -3902,7 +4066,8 @@
   // Determine whether PS2 is at least as specialized as PS1
   Deduced.clear();
   Deduced.resize(PS1->getTemplateParameters()->size());
-  bool Better2 =3D !::DeduceTemplateArguments(*this, PS1->getTemplateParam=
eters(),
+  bool Better2 =3D !DeduceTemplateArgumentsByTypeMatch(*this,
+                                            PS1->getTemplateParameters(),
                                             PT1, PT2, Info, Deduced, TDF_N=
one,
                                             /*PartialOrdering=3D*/true,
                                             /*RefParamComparisons=3D*/0);
@@ -3921,20 +4086,20 @@
 }
=20
 static void
-MarkUsedTemplateParameters(Sema &SemaRef,
+MarkUsedTemplateParameters(ASTContext &Ctx,
                            const TemplateArgument &TemplateArg,
                            bool OnlyDeduced,
                            unsigned Depth,
-                           SmallVectorImpl<bool> &Used);
+                           llvm::SmallBitVector &Used);
=20
 /// \brief Mark the template parameters that are used by the given
 /// expression.
 static void
-MarkUsedTemplateParameters(Sema &SemaRef,
+MarkUsedTemplateParameters(ASTContext &Ctx,
                            const Expr *E,
                            bool OnlyDeduced,
                            unsigned Depth,
-                           SmallVectorImpl<bool> &Used) {
+                           llvm::SmallBitVector &Used) {
   // We can deduce from a pack expansion.
   if (const PackExpansionExpr *Expansion =3D dyn_cast<PackExpansionExpr>(E=
))
     E =3D Expansion->getPattern();
@@ -3961,28 +4126,28 @@
 /// \brief Mark the template parameters that are used by the given
 /// nested name specifier.
 static void
-MarkUsedTemplateParameters(Sema &SemaRef,
+MarkUsedTemplateParameters(ASTContext &Ctx,
                            NestedNameSpecifier *NNS,
                            bool OnlyDeduced,
                            unsigned Depth,
-                           SmallVectorImpl<bool> &Used) {
+                           llvm::SmallBitVector &Used) {
   if (!NNS)
     return;
=20
-  MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
+  MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
                              Used);
-  MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
+  MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
                              OnlyDeduced, Depth, Used);
 }
=20
 /// \brief Mark the template parameters that are used by the given
 /// template name.
 static void
-MarkUsedTemplateParameters(Sema &SemaRef,
+MarkUsedTemplateParameters(ASTContext &Ctx,
                            TemplateName Name,
                            bool OnlyDeduced,
                            unsigned Depth,
-                           SmallVectorImpl<bool> &Used) {
+                           llvm::SmallBitVector &Used) {
   if (TemplateDecl *Template =3D Name.getAsTemplateDecl()) {
     if (TemplateTemplateParmDecl *TTP
           =3D dyn_cast<TemplateTemplateParmDecl>(Template)) {
@@ -3993,20 +4158,20 @@
   }
=20
   if (QualifiedTemplateName *QTN =3D Name.getAsQualifiedTemplateName())
-    MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
+    MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
                                Depth, Used);
   if (DependentTemplateName *DTN =3D Name.getAsDependentTemplateName())
-    MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
+    MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
                                Depth, Used);
 }
=20
 /// \brief Mark the template parameters that are used by the given
 /// type.
 static void
-MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
+MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
                            bool OnlyDeduced,
                            unsigned Depth,
-                           SmallVectorImpl<bool> &Used) {
+                           llvm::SmallBitVector &Used) {
   if (T.isNull())
     return;
=20
@@ -4014,10 +4179,10 @@
   if (!T->isDependentType())
     return;
=20
-  T =3D SemaRef.Context.getCanonicalType(T);
+  T =3D Ctx.getCanonicalType(T);
   switch (T->getTypeClass()) {
   case Type::Pointer:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<PointerType>(T)->getPointeeType(),
                                OnlyDeduced,
                                Depth,
@@ -4025,7 +4190,7 @@
     break;
=20
   case Type::BlockPointer:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<BlockPointerType>(T)->getPointeeType(),
                                OnlyDeduced,
                                Depth,
@@ -4034,7 +4199,7 @@
=20
   case Type::LValueReference:
   case Type::RValueReference:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<ReferenceType>(T)->getPointeeType(),
                                OnlyDeduced,
                                Depth,
@@ -4043,29 +4208,29 @@
=20
   case Type::MemberPointer: {
     const MemberPointerType *MemPtr =3D cast<MemberPointerType>(T.getTypeP=
tr());
-    MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDedu=
ced,
+    MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
                                Depth, Used);
-    MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
+    MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
                                OnlyDeduced, Depth, Used);
     break;
   }
=20
   case Type::DependentSizedArray:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<DependentSizedArrayType>(T)->getSizeEx=
pr(),
                                OnlyDeduced, Depth, Used);
     // Fall through to check the element type
=20
   case Type::ConstantArray:
   case Type::IncompleteArray:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<ArrayType>(T)->getElementType(),
                                OnlyDeduced, Depth, Used);
     break;
=20
   case Type::Vector:
   case Type::ExtVector:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<VectorType>(T)->getElementType(),
                                OnlyDeduced, Depth, Used);
     break;
@@ -4073,19 +4238,19 @@
   case Type::DependentSizedExtVector: {
     const DependentSizedExtVectorType *VecType
       =3D cast<DependentSizedExtVectorType>(T);
-    MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDed=
uced,
+    MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
                                Depth, Used);
-    MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduce=
d,
+    MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
                                Depth, Used);
     break;
   }
=20
   case Type::FunctionProto: {
     const FunctionProtoType *Proto =3D cast<FunctionProtoType>(T);
-    MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduce=
d,
+    MarkUsedTemplateParameters(Ctx, Proto->getResultType(), OnlyDeduced,
                                Depth, Used);
     for (unsigned I =3D 0, N =3D Proto->getNumArgs(); I !=3D N; ++I)
-      MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduce=
d,
+      MarkUsedTemplateParameters(Ctx, Proto->getArgType(I), OnlyDeduced,
                                  Depth, Used);
     break;
   }
@@ -4100,10 +4265,10 @@
   case Type::SubstTemplateTypeParmPack: {
     const SubstTemplateTypeParmPackType *Subst
       =3D cast<SubstTemplateTypeParmPackType>(T);
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                QualType(Subst->getReplacedParameter(), 0),
                                OnlyDeduced, Depth, Used);
-    MarkUsedTemplateParameters(SemaRef, Subst->getArgumentPack(),
+    MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
                                OnlyDeduced, Depth, Used);
     break;
   }
@@ -4115,7 +4280,7 @@
   case Type::TemplateSpecialization: {
     const TemplateSpecializationType *Spec
       =3D cast<TemplateSpecializationType>(T);
-    MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduc=
ed,
+    MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
                                Depth, Used);
=20
     // C++0x [temp.deduct.type]p9:
@@ -4127,28 +4292,28 @@
       break;
=20
     for (unsigned I =3D 0, N =3D Spec->getNumArgs(); I !=3D N; ++I)
-      MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, De=
pth,
+      MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
                                  Used);
     break;
   }
=20
   case Type::Complex:
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef,
+      MarkUsedTemplateParameters(Ctx,
                                  cast<ComplexType>(T)->getElementType(),
                                  OnlyDeduced, Depth, Used);
     break;
=20
   case Type::Atomic:
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef,
+      MarkUsedTemplateParameters(Ctx,
                                  cast<AtomicType>(T)->getValueType(),
                                  OnlyDeduced, Depth, Used);
     break;
=20
   case Type::DependentName:
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef,
+      MarkUsedTemplateParameters(Ctx,
                                  cast<DependentNameType>(T)->getQualifier(=
),
                                  OnlyDeduced, Depth, Used);
     break;
@@ -4157,7 +4322,7 @@
     const DependentTemplateSpecializationType *Spec
       =3D cast<DependentTemplateSpecializationType>(T);
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
+      MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
                                  OnlyDeduced, Depth, Used);
=20
     // C++0x [temp.deduct.type]p9:
@@ -4169,47 +4334,47 @@
       break;
=20
     for (unsigned I =3D 0, N =3D Spec->getNumArgs(); I !=3D N; ++I)
-      MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, De=
pth,
+      MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
                                  Used);
     break;
   }
=20
   case Type::TypeOf:
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef,
+      MarkUsedTemplateParameters(Ctx,
                                  cast<TypeOfType>(T)->getUnderlyingType(),
                                  OnlyDeduced, Depth, Used);
     break;
=20
   case Type::TypeOfExpr:
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef,
+      MarkUsedTemplateParameters(Ctx,
                                  cast<TypeOfExprType>(T)->getUnderlyingExp=
r(),
                                  OnlyDeduced, Depth, Used);
     break;
=20
   case Type::Decltype:
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef,
+      MarkUsedTemplateParameters(Ctx,
                                  cast<DecltypeType>(T)->getUnderlyingExpr(=
),
                                  OnlyDeduced, Depth, Used);
     break;
=20
   case Type::UnaryTransform:
     if (!OnlyDeduced)
-      MarkUsedTemplateParameters(SemaRef,
+      MarkUsedTemplateParameters(Ctx,
                                cast<UnaryTransformType>(T)->getUnderlyingT=
ype(),
                                  OnlyDeduced, Depth, Used);
     break;
=20
   case Type::PackExpansion:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<PackExpansionType>(T)->getPattern(),
                                OnlyDeduced, Depth, Used);
     break;
=20
   case Type::Auto:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                cast<AutoType>(T)->getDeducedType(),
                                OnlyDeduced, Depth, Used);
=20
@@ -4235,31 +4400,31 @@
 /// \brief Mark the template parameters that are used by this
 /// template argument.
 static void
-MarkUsedTemplateParameters(Sema &SemaRef,
+MarkUsedTemplateParameters(ASTContext &Ctx,
                            const TemplateArgument &TemplateArg,
                            bool OnlyDeduced,
                            unsigned Depth,
-                           SmallVectorImpl<bool> &Used) {
+                           llvm::SmallBitVector &Used) {
   switch (TemplateArg.getKind()) {
   case TemplateArgument::Null:
   case TemplateArgument::Integral:
-    case TemplateArgument::Declaration:
+  case TemplateArgument::Declaration:
     break;
=20
   case TemplateArgument::Type:
-    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduc=
ed,
+    MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
                                Depth, Used);
     break;
=20
   case TemplateArgument::Template:
   case TemplateArgument::TemplateExpansion:
-    MarkUsedTemplateParameters(SemaRef,
+    MarkUsedTemplateParameters(Ctx,
                                TemplateArg.getAsTemplateOrTemplatePattern(=
),
                                OnlyDeduced, Depth, Used);
     break;
=20
   case TemplateArgument::Expression:
-    MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduc=
ed,
+    MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
                                Depth, Used);
     break;
=20
@@ -4267,7 +4432,7 @@
     for (TemplateArgument::pack_iterator P =3D TemplateArg.pack_begin(),
                                       PEnd =3D TemplateArg.pack_end();
          P !=3D PEnd; ++P)
-      MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
+      MarkUsedTemplateParameters(Ctx, *P, OnlyDeduced, Depth, Used);
     break;
   }
 }
@@ -4284,7 +4449,7 @@
 void
 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
                                  bool OnlyDeduced, unsigned Depth,
-                                 SmallVectorImpl<bool> &Used) {
+                                 llvm::SmallBitVector &Used) {
   // C++0x [temp.deduct.type]p9:
   //   If the template argument list of P contains a pack expansion that i=
s not
   //   the last template argument, the entire template argument list is a
@@ -4294,15 +4459,16 @@
     return;
=20
   for (unsigned I =3D 0, N =3D TemplateArgs.size(); I !=3D N; ++I)
-    ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
+    ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
                                  Depth, Used);
 }
=20
 /// \brief Marks all of the template parameters that will be deduced by a
 /// call to the given function template.
 void
-Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
-                                    SmallVectorImpl<bool> &Deduced) {
+Sema::MarkDeducedTemplateParameters(ASTContext &Ctx,
+                                    FunctionTemplateDecl *FunctionTemplate,
+                                    llvm::SmallBitVector &Deduced) {
   TemplateParameterList *TemplateParams
     =3D FunctionTemplate->getTemplateParameters();
   Deduced.clear();
@@ -4310,7 +4476,7 @@
=20
   FunctionDecl *Function =3D FunctionTemplate->getTemplatedDecl();
   for (unsigned I =3D 0, N =3D Function->getNumParams(); I !=3D N; ++I)
-    ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType=
(),
+    ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
                                  true, TemplateParams->getDepth(), Deduced=
);
 }
=20
@@ -4322,14 +4488,9 @@
=20
   TemplateParameterList *TemplateParams
     =3D FunctionTemplate->getTemplateParameters();
-  SmallVector<bool, 4> Deduced;
-  Deduced.resize(TemplateParams->size());
-  ::MarkUsedTemplateParameters(S, T, true, TemplateParams->getDepth(),=20
+  llvm::SmallBitVector Deduced(TemplateParams->size());
+  ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDept=
h(),=20
                                Deduced);
=20
-  for (unsigned I =3D 0, N =3D Deduced.size(); I !=3D N; ++I)
-    if (Deduced[I])
-      return true;
-
-  return false;
+  return Deduced.any();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaTemplateInstantiate.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp	Tu=
e Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiate.cpp	Tu=
e Apr 17 11:51:51 2012 +0300
@@ -163,8 +163,8 @@
   case DefaultTemplateArgumentChecking:
     return false;
   }
- =20
-  return true;
+
+  llvm_unreachable("Invalid InstantiationKind!");
 }
=20
 Sema::InstantiatingTemplate::
@@ -404,15 +404,15 @@
                                    SemaRef.ActiveTemplateInstantiations.si=
ze());
   if ((SemaRef.ActiveTemplateInstantiations.size() -=20
           SemaRef.NonInstantiationEntries)
-        <=3D SemaRef.getLangOptions().InstantiationDepth)
+        <=3D SemaRef.getLangOpts().InstantiationDepth)
     return false;
=20
   SemaRef.Diag(PointOfInstantiation,
                diag::err_template_recursion_depth_exceeded)
-    << SemaRef.getLangOptions().InstantiationDepth
+    << SemaRef.getLangOpts().InstantiationDepth
     << InstantiationRange;
   SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
-    << SemaRef.getLangOptions().InstantiationDepth;
+    << SemaRef.getLangOpts().InstantiationDepth;
   return true;
 }
=20
@@ -469,6 +469,11 @@
                      diag::note_template_static_data_member_def_here)
           << VD
           << Active->InstantiationRange;
+      } else if (EnumDecl *ED =3D dyn_cast<EnumDecl>(D)) {
+        Diags.Report(Active->PointOfInstantiation,
+                     diag::note_template_enum_def_here)
+          << ED
+          << Active->InstantiationRange;
       } else {
         Diags.Report(Active->PointOfInstantiation,
                      diag::note_template_type_alias_instantiation_here)
@@ -732,6 +737,14 @@
     /// this declaration.
     Decl *TransformDecl(SourceLocation Loc, Decl *D);
=20
+    void transformAttrs(Decl *Old, Decl *New) {=20
+      SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
+    }
+
+    void transformedLocalDecl(Decl *Old, Decl *New) {
+      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
+    }
+   =20
     /// \brief Transform the definition of the given declaration by
     /// instantiating it.
     Decl *TransformDefinition(SourceLocation Loc, Decl *D);
@@ -778,7 +791,8 @@
                                         FunctionProtoTypeLoc TL);
     ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
                                             int indexAdjustment,
-                                      llvm::Optional<unsigned> NumExpansio=
ns);
+                                        llvm::Optional<unsigned> NumExpans=
ions,
+                                            bool ExpectParameterPack);
=20
     /// \brief Transforms a template type parameter type by performing
     /// substitution of the corresponding template type argument.
@@ -1099,15 +1113,21 @@
     type =3D argExpr->getType();
=20
   } else if (arg.getKind() =3D=3D TemplateArgument::Declaration) {
-    ValueDecl *VD =3D cast<ValueDecl>(arg.getAsDecl());
+    ValueDecl *VD;
+    if (Decl *D =3D arg.getAsDecl()) {
+      VD =3D cast<ValueDecl>(D);
=20
-    // Find the instantiation of the template argument.  This is
-    // required for nested templates.
-    VD =3D cast_or_null<ValueDecl>(
-                       getSema().FindInstantiatedDecl(loc, VD, TemplateArg=
s));
-    if (!VD)
-      return ExprError();
-
+      // Find the instantiation of the template argument.  This is
+      // required for nested templates.
+      VD =3D cast_or_null<ValueDecl>(
+             getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
+      if (!VD)
+        return ExprError();
+    } else {
+      // Propagate NULL template argument.
+      VD =3D 0;
+    }
+   =20
     // Derive the type we want the substituted decl to have.  This had
     // better be non-dependent, or these checks will have serious problems.
     if (parm->isExpandedParameterPack()) {
@@ -1194,9 +1214,10 @@
 ParmVarDecl *
 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
                                                  int indexAdjustment,
-                                       llvm::Optional<unsigned> NumExpansi=
ons) {
+                                       llvm::Optional<unsigned> NumExpansi=
ons,
+                                                 bool ExpectParameterPack)=
 {
   return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
-                                  NumExpansions);
+                                  NumExpansions, ExpectParameterPack);
 }
=20
 QualType
@@ -1450,7 +1471,8 @@
 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,=20
                             const MultiLevelTemplateArgumentList &Template=
Args,
                                     int indexAdjustment,
-                                    llvm::Optional<unsigned> NumExpansions=
) {
+                                    llvm::Optional<unsigned> NumExpansions,
+                                    bool ExpectParameterPack) {
   TypeSourceInfo *OldDI =3D OldParm->getTypeSourceInfo();
   TypeSourceInfo *NewDI =3D 0;
  =20
@@ -1471,7 +1493,16 @@
       // Therefore, make its type a pack expansion type.
       NewDI =3D CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
                                  NumExpansions);
-    }
+    } else if (ExpectParameterPack) {
+      // We expected to get a parameter pack but didn't (because the type
+      // itself is not a pack expansion type), so complain. This can occur=
 when
+      // the substitution goes through an alias template that "loses" the
+      // pack expansion.
+      Diag(OldParm->getLocation(),=20
+           diag::err_function_parameter_pack_without_parameter_packs)
+        << NewDI->getType();
+      return 0;
+    }=20
   } else {
     NewDI =3D SubstType(OldDI, TemplateArgs, OldParm->getLocation(),=20
                       OldParm->getDeclName());
@@ -1506,11 +1537,9 @@
     NewParm->setUninstantiatedDefaultArg(Arg);
=20
   NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
-
-  // FIXME: When OldParm is a parameter pack and NewParm is not a parameter
-  // pack, we actually have a set of instantiated locations. Maintain this=
 set!
+ =20
   if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
-    // Add the new parameter to=20
+    // Add the new parameter to the instantiated parameter pack.
     CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
   } else {
     // Introduce an Old -> New mapping
@@ -1654,6 +1683,59 @@
   return Invalid;
 }
=20
+// Defined via #include from SemaTemplateInstantiateDecl.cpp
+namespace clang {
+  namespace sema {
+    Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema=
 &S,
+                            const MultiLevelTemplateArgumentList &Template=
Args);
+  }
+}
+
+/// Determine whether we would be unable to instantiate this template (bec=
ause
+/// it either has no definition, or is in the process of being instantiate=
d).
+static bool DiagnoseUninstantiableTemplate(Sema &S,
+                                           SourceLocation PointOfInstantia=
tion,
+                                           TagDecl *Instantiation,
+                                           bool InstantiatedFromMember,
+                                           TagDecl *Pattern,
+                                           TagDecl *PatternDef,
+                                           TemplateSpecializationKind TSK,
+                                           bool Complain =3D true) {
+  if (PatternDef && !PatternDef->isBeingDefined())
+    return false;
+
+  if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
+    // Say nothing
+  } else if (PatternDef) {
+    assert(PatternDef->isBeingDefined());
+    S.Diag(PointOfInstantiation,
+           diag::err_template_instantiate_within_definition)
+      << (TSK !=3D TSK_ImplicitInstantiation)
+      << S.Context.getTypeDeclType(Instantiation);
+    // Not much point in noting the template declaration here, since
+    // we're lexically inside it.
+    Instantiation->setInvalidDecl();
+  } else if (InstantiatedFromMember) {
+    S.Diag(PointOfInstantiation,
+           diag::err_implicit_instantiate_member_undefined)
+      << S.Context.getTypeDeclType(Instantiation);
+    S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
+  } else {
+    S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
+      << (TSK !=3D TSK_ImplicitInstantiation)
+      << S.Context.getTypeDeclType(Instantiation);
+    S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
+  }
+
+  // In general, Instantiation isn't marked invalid to get more than one
+  // error for multiple undefined instantiations. But the code that does
+  // explicit declaration -> explicit definition conversion can't handle
+  // invalid declarations, so mark as invalid in that case.
+  if (TSK =3D=3D TSK_ExplicitInstantiationDeclaration)
+    Instantiation->setInvalidDecl();
+  return true;
+}
+
 /// \brief Instantiate the definition of a class from a given pattern.
 ///
 /// \param PointOfInstantiation The point of instantiation within the
@@ -1686,31 +1768,10 @@
=20
   CXXRecordDecl *PatternDef
     =3D cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
-  if (!PatternDef || PatternDef->isBeingDefined()) {
-    if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
-      // Say nothing
-    } else if (PatternDef) {
-      assert(PatternDef->isBeingDefined());
-      Diag(PointOfInstantiation,
-           diag::err_template_instantiate_within_definition)
-        << (TSK !=3D TSK_ImplicitInstantiation)
-        << Context.getTypeDeclType(Instantiation);
-      // Not much point in noting the template declaration here, since
-      // we're lexically inside it.
-      Instantiation->setInvalidDecl();
-    } else if (Pattern =3D=3D Instantiation->getInstantiatedFromMemberClas=
s()) {
-      Diag(PointOfInstantiation,
-           diag::err_implicit_instantiate_member_undefined)
-        << Context.getTypeDeclType(Instantiation);
-      Diag(Pattern->getLocation(), diag::note_member_of_template_here);
-    } else {
-      Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
-        << (TSK !=3D TSK_ImplicitInstantiation)
-        << Context.getTypeDeclType(Instantiation);
-      Diag(Pattern->getLocation(), diag::note_template_decl_here);
-    }
+  if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instanti=
ation,
+                                Instantiation->getInstantiatedFromMemberCl=
ass(),
+                                     Pattern, PatternDef, TSK, Complain))
     return true;
-  }
   Pattern =3D PatternDef;
=20
   // \brief Record the point of instantiation.
@@ -1719,7 +1780,7 @@
     MSInfo->setTemplateSpecializationKind(TSK);
     MSInfo->setPointOfInstantiation(PointOfInstantiation);
   } else if (ClassTemplateSpecializationDecl *Spec=20
-               =3D dyn_cast<ClassTemplateSpecializationDecl>(Instantiation=
)) {
+        =3D dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
     Spec->setTemplateSpecializationKind(TSK);
     Spec->setPointOfInstantiation(PointOfInstantiation);
   }
@@ -1756,6 +1817,10 @@
   SmallVector<Decl*, 4> Fields;
   SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
     FieldsWithMemberInitializers;
+  // Delay instantiation of late parsed attributes.
+  LateInstantiatedAttrVec LateAttrs;
+  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
+
   for (RecordDecl::decl_iterator Member =3D Pattern->decls_begin(),
          MemberEnd =3D Pattern->decls_end();
        Member !=3D MemberEnd; ++Member) {
@@ -1784,7 +1849,21 @@
         if (OldField->getInClassInitializer())
           FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
                                                                 Field));
-      } else if (NewMember->isInvalidDecl())
+      } else if (EnumDecl *Enum =3D dyn_cast<EnumDecl>(NewMember)) {
+        // C++11 [temp.inst]p1: The implicit instantiation of a class temp=
late
+        // specialization causes the implicit instantiation of the definit=
ions
+        // of unscoped member enumerations.
+        // Record a point of instantiation for this implicit instantiation.
+        if (TSK =3D=3D TSK_ImplicitInstantiation && !Enum->isScoped() &&
+            Enum->isCompleteDefinition()) {
+          MemberSpecializationInfo *MSInfo =3DEnum->getMemberSpecializatio=
nInfo();
+          assert(MSInfo && "no spec info for member enum specialization");
+          MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
+          MSInfo->setPointOfInstantiation(PointOfInstantiation);
+        }
+      }
+
+      if (NewMember->isInvalidDecl())
         Invalid =3D true;
     } else {
       // FIXME: Eventually, a NULL return will mean that one of the
@@ -1804,22 +1883,42 @@
     FieldDecl *NewField =3D FieldsWithMemberInitializers[I].second;
     Expr *OldInit =3D OldField->getInClassInitializer();
=20
-    SourceLocation LParenLoc, RParenLoc;
-    ASTOwningVector<Expr*> NewArgs(*this);
-    if (InstantiateInitializer(OldInit, TemplateArgs, LParenLoc, NewArgs,
-                               RParenLoc))
+    ExprResult NewInit =3D SubstInitializer(OldInit, TemplateArgs,
+                                          /*CXXDirectInit=3D*/false);
+    if (NewInit.isInvalid())
       NewField->setInvalidDecl();
     else {
-      assert(NewArgs.size() =3D=3D 1 && "wrong number of in-class initiali=
zers");
-      ActOnCXXInClassMemberInitializer(NewField, LParenLoc, NewArgs[0]);
+      Expr *Init =3D NewInit.take();
+      assert(Init && "no-argument initializer in class");
+      assert(!isa<ParenListExpr>(Init) && "call-style init in class");
+      ActOnCXXInClassMemberInitializer(NewField,
+                                       Init->getSourceRange().getBegin(), =
Init);
     }
   }
=20
+  // Instantiate late parsed attributes, and attach them to their decls.
+  // See Sema::InstantiateAttrs
+  for (LateInstantiatedAttrVec::iterator I =3D LateAttrs.begin(),
+       E =3D LateAttrs.end(); I !=3D E; ++I) {
+    assert(CurrentInstantiationScope =3D=3D Instantiator.getStartingScope(=
));
+    CurrentInstantiationScope =3D I->Scope;
+    Attr *NewAttr =3D
+      instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateAr=
gs);
+    I->NewDecl->addAttr(NewAttr);
+    LocalInstantiationScope::deleteScopes(I->Scope,
+                                          Instantiator.getStartingScope());
+  }
+  Instantiator.disableLateAttributeInstantiation();
+  LateAttrs.clear();
+
   if (!FieldsWithMemberInitializers.empty())
     ActOnFinishDelayedMemberInitializers(Instantiation);
=20
-  if (TSK =3D=3D TSK_ImplicitInstantiation)
+  if (TSK =3D=3D TSK_ImplicitInstantiation) {
+    Instantiation->setLocation(Pattern->getLocation());
+    Instantiation->setLocStart(Pattern->getInnerLocStart());
     Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
+  }
=20
   if (Instantiation->isInvalidDecl())
     Invalid =3D true;
@@ -1854,6 +1953,63 @@
   return Invalid;
 }
=20
+/// \brief Instantiate the definition of an enum from a given pattern.
+///
+/// \param PointOfInstantiation The point of instantiation within the
+///        source code.
+/// \param Instantiation is the declaration whose definition is being
+///        instantiated. This will be a member enumeration of a class
+///        temploid specialization, or a local enumeration within a
+///        function temploid specialization.
+/// \param Pattern The templated declaration from which the instantiation
+///        occurs.
+/// \param TemplateArgs The template arguments to be substituted into
+///        the pattern.
+/// \param TSK The kind of implicit or explicit instantiation to perform.
+///
+/// \return \c true if an error occurred, \c false otherwise.
+bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
+                           EnumDecl *Instantiation, EnumDecl *Pattern,
+                           const MultiLevelTemplateArgumentList &TemplateA=
rgs,
+                           TemplateSpecializationKind TSK) {
+  EnumDecl *PatternDef =3D Pattern->getDefinition();
+  if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instanti=
ation,
+                                 Instantiation->getInstantiatedFromMemberE=
num(),
+                                     Pattern, PatternDef, TSK,/*Complain*/=
true))
+    return true;
+  Pattern =3D PatternDef;
+
+  // Record the point of instantiation.
+  if (MemberSpecializationInfo *MSInfo
+        =3D Instantiation->getMemberSpecializationInfo()) {
+    MSInfo->setTemplateSpecializationKind(TSK);
+    MSInfo->setPointOfInstantiation(PointOfInstantiation);
+  }
+
+  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
+  if (Inst)
+    return true;
+
+  // Enter the scope of this instantiation. We don't use
+  // PushDeclContext because we don't have a scope.
+  ContextRAII SavedContext(*this, Instantiation);
+  EnterExpressionEvaluationContext EvalContext(*this,
+                                               Sema::PotentiallyEvaluated);
+
+  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
+
+  // Pull attributes from the pattern onto the instantiation.
+  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
+
+  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs=
);
+  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
+
+  // Exit the scope of this instantiation.
+  SavedContext.pop();
+
+  return Instantiation->isInvalidDecl();
+}
+
 namespace {
   /// \brief A partial specialization whose template arguments have matched
   /// a given template-id.
@@ -1886,7 +2042,8 @@
      =20
       // If this is an explicit instantiation definition, mark the
       // vtable as used.
-      if (TSK =3D=3D TSK_ExplicitInstantiationDefinition)
+      if (TSK =3D=3D TSK_ExplicitInstantiationDefinition &&
+          !ClassTemplateSpec->isInvalidDecl())
         MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
=20
       return false;
@@ -2120,7 +2277,7 @@
       // Always skip the injected-class-name, along with any
       // redeclarations of nested classes, since both would cause us
       // to try to instantiate the members of a class twice.
-      if (Record->isInjectedClassName() || Record->getPreviousDeclaration(=
))
+      if (Record->isInjectedClassName() || Record->getPreviousDecl())
         continue;
      =20
       MemberSpecializationInfo *MSInfo =3D Record->getMemberSpecialization=
Info();
@@ -2173,6 +2330,36 @@
       if (Pattern)
         InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArg=
s,=20
                                 TSK);
+    } else if (EnumDecl *Enum =3D dyn_cast<EnumDecl>(*D)) {
+      MemberSpecializationInfo *MSInfo =3D Enum->getMemberSpecializationIn=
fo();
+      assert(MSInfo && "No member specialization information?");
+
+      if (MSInfo->getTemplateSpecializationKind()
+            =3D=3D TSK_ExplicitSpecialization)
+        continue;
+
+      if (CheckSpecializationInstantiationRedecl(
+            PointOfInstantiation, TSK, Enum,
+            MSInfo->getTemplateSpecializationKind(),
+            MSInfo->getPointOfInstantiation(), SuppressNew) ||
+          SuppressNew)
+        continue;
+
+      if (Enum->getDefinition())
+        continue;
+
+      EnumDecl *Pattern =3D Enum->getInstantiatedFromMemberEnum();
+      assert(Pattern && "Missing instantiated-from-template information");
+
+      if (TSK =3D=3D TSK_ExplicitInstantiationDefinition) {
+        if (!Pattern->getDefinition())
+          continue;
+
+        InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs,=
 TSK);
+      } else {
+        MSInfo->setTemplateSpecializationKind(TSK);
+        MSInfo->setPointOfInstantiation(PointOfInstantiation);
+      }
     }
   }
 }
@@ -2287,7 +2474,7 @@
       // If this is a tag declaration, it's possible that we need to look =
for
       // a previous declaration.
       if (const TagDecl *Tag =3D dyn_cast<TagDecl>(CheckD))
-        CheckD =3D Tag->getPreviousDeclaration();
+        CheckD =3D Tag->getPreviousDecl();
       else
         CheckD =3D 0;
     } while (CheckD);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaTemplateInstantiateDecl.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cp=
p	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cp=
p	Tue Apr 17 11:51:51 2012 +0300
@@ -57,26 +57,30 @@
   return false;
 }
=20
-// FIXME: Is this still too simple?
+// Include attribute instantiation code.
+#include "clang/Sema/AttrTemplateInstantiate.inc"
+
 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &Template=
Args,
-                            const Decl *Tmpl, Decl *New) {
+                            const Decl *Tmpl, Decl *New,
+                            LateInstantiatedAttrVec *LateAttrs,
+                            LocalInstantiationScope *OuterMostScope) {
   for (AttrVec::const_iterator i =3D Tmpl->attr_begin(), e =3D Tmpl->attr_=
end();
        i !=3D e; ++i) {
     const Attr *TmplAttr =3D *i;
+
     // FIXME: This should be generalized to more than just the AlignedAttr.
     if (const AlignedAttr *Aligned =3D dyn_cast<AlignedAttr>(TmplAttr)) {
       if (Aligned->isAlignmentDependent()) {
-        // The alignment expression is not potentially evaluated.
-        EnterExpressionEvaluationContext Unevaluated(*this,
-                                                     Sema::Unevaluated);
-
         if (Aligned->isAlignmentExpr()) {
+          // The alignment expression is a constant expression.
+          EnterExpressionEvaluationContext Unevaluated(*this,
+                                                       Sema::ConstantEvalu=
ated);
+
           ExprResult Result =3D SubstExpr(Aligned->getAlignmentExpr(),
                                         TemplateArgs);
           if (!Result.isInvalid())
             AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr=
>());
-        }
-        else {
+        } else {
           TypeSourceInfo *Result =3D SubstType(Aligned->getAlignmentType(),
                                              TemplateArgs,
                                              Aligned->getLocation(),
@@ -88,9 +92,18 @@
       }
     }
=20
-    // FIXME: Is cloning correct for all attributes?
-    Attr *NewAttr =3D TmplAttr->clone(Context);
-    New->addAttr(NewAttr);
+    if (TmplAttr->isLateParsed() && LateAttrs) {
+      // Late parsed attributes must be instantiated and attached after the
+      // enclosing class has been instantiated.  See Sema::InstantiateClas=
s.
+      LocalInstantiationScope *Saved =3D 0;
+      if (CurrentInstantiationScope)
+        Saved =3D CurrentInstantiationScope->cloneScopes(OuterMostScope);
+      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)=
);
+    } else {
+      Attr *NewAttr =3D sema::instantiateTemplateAttribute(TmplAttr, Conte=
xt,
+                                                         *this, TemplateAr=
gs);
+      New->addAttr(NewAttr);
+    }
   }
 }
=20
@@ -164,13 +177,18 @@
     }
   }
=20
-  if (TypedefNameDecl *Prev =3D D->getPreviousDeclaration()) {
+  if (TypedefNameDecl *Prev =3D D->getPreviousDecl()) {
     NamedDecl *InstPrev =3D SemaRef.FindInstantiatedDecl(D->getLocation(),=
 Prev,
                                                        TemplateArgs);
     if (!InstPrev)
       return 0;
=20
-    Typedef->setPreviousDeclaration(cast<TypedefNameDecl>(InstPrev));
+    TypedefNameDecl *InstPrevTypedef =3D cast<TypedefNameDecl>(InstPrev);
+
+    // If the typedef types are not identical, reject them.
+    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
+
+    Typedef->setPreviousDeclaration(InstPrevTypedef);
   }
=20
   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
@@ -206,7 +224,7 @@
   TypeAliasDecl *Pattern =3D D->getTemplatedDecl();
=20
   TypeAliasTemplateDecl *PrevAliasTemplate =3D 0;
-  if (Pattern->getPreviousDeclaration()) {
+  if (Pattern->getPreviousDecl()) {
     DeclContext::lookup_result Found =3D Owner->lookup(Pattern->getDeclNam=
e());
     if (Found.first !=3D Found.second) {
       PrevAliasTemplate =3D dyn_cast<TypeAliasTemplateDecl>(*Found.first);
@@ -234,66 +252,6 @@
   return Inst;
 }
=20
-/// \brief Instantiate an initializer, breaking it into separate
-/// initialization arguments.
-///
-/// \param Init The initializer to instantiate.
-///
-/// \param TemplateArgs Template arguments to be substituted into the
-/// initializer.
-///
-/// \param NewArgs Will be filled in with the instantiation arguments.
-///
-/// \returns true if an error occurred, false otherwise
-bool Sema::InstantiateInitializer(Expr *Init,
-                            const MultiLevelTemplateArgumentList &Template=
Args,
-                                  SourceLocation &LParenLoc,
-                                  ASTOwningVector<Expr*> &NewArgs,
-                                  SourceLocation &RParenLoc) {
-  NewArgs.clear();
-  LParenLoc =3D SourceLocation();
-  RParenLoc =3D SourceLocation();
-
-  if (!Init)
-    return false;
-
-  if (ExprWithCleanups *ExprTemp =3D dyn_cast<ExprWithCleanups>(Init))
-    Init =3D ExprTemp->getSubExpr();
-
-  while (CXXBindTemporaryExpr *Binder =3D dyn_cast<CXXBindTemporaryExpr>(I=
nit))
-    Init =3D Binder->getSubExpr();
-
-  if (ImplicitCastExpr *ICE =3D dyn_cast<ImplicitCastExpr>(Init))
-    Init =3D ICE->getSubExprAsWritten();
-
-  if (ParenListExpr *ParenList =3D dyn_cast<ParenListExpr>(Init)) {
-    LParenLoc =3D ParenList->getLParenLoc();
-    RParenLoc =3D ParenList->getRParenLoc();
-    return SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
-                      true, TemplateArgs, NewArgs);
-  }
-
-  if (CXXConstructExpr *Construct =3D dyn_cast<CXXConstructExpr>(Init)) {
-    if (!isa<CXXTemporaryObjectExpr>(Construct)) {
-      if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
-                     TemplateArgs, NewArgs))
-        return true;
-
-      // FIXME: Fake locations!
-      LParenLoc =3D PP.getLocForEndOfToken(Init->getLocStart());
-      RParenLoc =3D LParenLoc;
-      return false;
-    }
-  }
-
-  ExprResult Result =3D SubstExpr(Init, TemplateArgs);
-  if (Result.isInvalid())
-    return true;
-
-  NewArgs.push_back(Result.takeAs<Expr>());
-  return false;
-}
-
 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
   // If this is the variable for an anonymous struct or union,
   // instantiate the anonymous struct/union type first.
@@ -324,8 +282,9 @@
                                  D->getStorageClass(),
                                  D->getStorageClassAsWritten());
   Var->setThreadSpecified(D->isThreadSpecified());
-  Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
+  Var->setInitStyle(D->getInitStyle());
   Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
+  Var->setConstexpr(D->isConstexpr());
=20
   // Substitute the nested name specifier, if any.
   if (SubstQualifier(D, Var))
@@ -351,18 +310,23 @@
                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
   if (D->isStaticDataMember())
     SemaRef.LookupQualifiedName(Previous, Owner, false);
+ =20
+  // In ARC, infer 'retaining' for variables of retainable type.
+  if (SemaRef.getLangOpts().ObjCAutoRefCount &&=20
+      SemaRef.inferObjCARCLifetime(Var))
+    Var->setInvalidDecl();
+
   SemaRef.CheckVariableDeclaration(Var, Previous);
=20
   if (D->isOutOfLine()) {
-    if (!D->isStaticDataMember())
-      D->getLexicalDeclContext()->addDecl(Var);
+    D->getLexicalDeclContext()->addDecl(Var);
     Owner->makeDeclVisibleInContext(Var);
   } else {
     Owner->addDecl(Var);
     if (Owner->isFunctionOrMethod())
       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
   }
-  SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
+  SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
=20
   // Link instantiations of static data members back to the template from
   // which they were instantiated.
@@ -374,31 +338,21 @@
     // We already have an initializer in the class.
   } else if (D->getInit()) {
     if (Var->isStaticDataMember() && !D->isOutOfLine())
-      SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
+      SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
     else
       SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
=20
     // Instantiate the initializer.
-    SourceLocation LParenLoc, RParenLoc;
-    ASTOwningVector<Expr*> InitArgs(SemaRef);
-    if (!SemaRef.InstantiateInitializer(D->getInit(), TemplateArgs, LParen=
Loc,
-                                        InitArgs, RParenLoc)) {
+    ExprResult Init =3D SemaRef.SubstInitializer(D->getInit(), TemplateArg=
s,
+                                        D->getInitStyle() =3D=3D VarDecl::=
CallInit);
+    if (!Init.isInvalid()) {
       bool TypeMayContainAuto =3D true;
-      // Attach the initializer to the declaration, if we have one.
-      if (InitArgs.size() =3D=3D 0)
+      if (Init.get()) {
+        bool DirectInit =3D D->isDirectInit();
+        SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
+                                     TypeMayContainAuto);
+      } else
         SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
-      else if (D->hasCXXDirectInitializer()) {
-        // Add the direct initializer to the declaration.
-        SemaRef.AddCXXDirectInitializerToDecl(Var,
-                                              LParenLoc,
-                                              move_arg(InitArgs),
-                                              RParenLoc,
-                                              TypeMayContainAuto);
-      } else {
-        assert(InitArgs.size() =3D=3D 1);
-        Expr *Init =3D InitArgs.take()[0];
-        SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
-      }
     } else {
       // FIXME: Not too happy about invalidating the declaration
       // because of a bogus initializer.
@@ -456,8 +410,9 @@
   if (Invalid)
     BitWidth =3D 0;
   else if (BitWidth) {
-    // The bit-width expression is not potentially evaluated.
-    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluate=
d);
+    // The bit-width expression is a constant expression.
+    EnterExpressionEvaluationContext Unevaluated(SemaRef,
+                                                 Sema::ConstantEvaluated);
=20
     ExprResult InstantiatedBitWidth
       =3D SemaRef.SubstExpr(BitWidth, TemplateArgs);
@@ -483,7 +438,7 @@
     return 0;
   }
=20
-  SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
+  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScop=
e);
=20
   if (Invalid)
     Field->setInvalidDecl();
@@ -552,7 +507,8 @@
     if (!InstTy)
       return 0;
=20
-    FriendDecl *FD =3D SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), Inst=
Ty);
+    FriendDecl *FD =3D SemaRef.CheckFriendTypeDecl(D->getLocation(),
+                                                 D->getFriendLoc(), InstTy=
);
     if (!FD)
       return 0;
=20
@@ -584,8 +540,9 @@
 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D)=
 {
   Expr *AssertExpr =3D D->getAssertExpr();
=20
-  // The expression in a static assertion is not potentially evaluated.
-  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
+  // The expression in a static assertion is a constant expression.
+  EnterExpressionEvaluationContext Unevaluated(SemaRef,
+                                               Sema::ConstantEvaluated);
=20
   ExprResult InstantiatedAssertExpr
     =3D SemaRef.SubstExpr(AssertExpr, TemplateArgs);
@@ -601,25 +558,32 @@
 }
=20
 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
+  EnumDecl *PrevDecl =3D 0;
+  if (D->getPreviousDecl()) {
+    NamedDecl *Prev =3D SemaRef.FindInstantiatedDecl(D->getLocation(),
+                                                   D->getPreviousDecl(),
+                                                   TemplateArgs);
+    if (!Prev) return 0;
+    PrevDecl =3D cast<EnumDecl>(Prev);
+  }
+
   EnumDecl *Enum =3D EnumDecl::Create(SemaRef.Context, Owner, D->getLocSta=
rt(),
                                     D->getLocation(), D->getIdentifier(),
-                                    /*PrevDecl=3D*/0, D->isScoped(),
+                                    PrevDecl, D->isScoped(),
                                     D->isScopedUsingClassTag(), D->isFixed=
());
   if (D->isFixed()) {
-    if (TypeSourceInfo* TI =3D D->getIntegerTypeSourceInfo()) {
+    if (TypeSourceInfo *TI =3D D->getIntegerTypeSourceInfo()) {
       // If we have type source information for the underlying type, it me=
ans it
       // has been explicitly set by the user. Perform substitution on it b=
efore
       // moving on.
       SourceLocation UnderlyingLoc =3D TI->getTypeLoc().getBeginLoc();
-      Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
-                                                       TemplateArgs,
-                                                       UnderlyingLoc,
-                                                       DeclarationName()));
-
-      if (!Enum->getIntegerTypeSourceInfo())
+      TypeSourceInfo *NewTI =3D SemaRef.SubstType(TI, TemplateArgs, Underl=
yingLoc,
+                                                DeclarationName());
+      if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
         Enum->setIntegerType(SemaRef.Context.IntTy);
-    }
-    else {
+      else
+        Enum->setIntegerTypeSourceInfo(NewTI);
+    } else {
       assert(!D->getIntegerType()->isDependentType()
              && "Dependent type without type source info");
       Enum->setIntegerType(D->getIntegerType());
@@ -628,27 +592,62 @@
=20
   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
=20
-  Enum->setInstantiationOfMemberEnum(D);
+  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
   Enum->setAccess(D->getAccess());
   if (SubstQualifier(D, Enum)) return 0;
   Owner->addDecl(Enum);
-  Enum->startDefinition();
+
+  EnumDecl *Def =3D D->getDefinition();
+  if (Def && Def !=3D D) {
+    // If this is an out-of-line definition of an enum member template, ch=
eck
+    // that the underlying types match in the instantiation of both
+    // declarations.
+    if (TypeSourceInfo *TI =3D Def->getIntegerTypeSourceInfo()) {
+      SourceLocation UnderlyingLoc =3D TI->getTypeLoc().getBeginLoc();
+      QualType DefnUnderlying =3D
+        SemaRef.SubstType(TI->getType(), TemplateArgs,
+                          UnderlyingLoc, DeclarationName());
+      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
+                                     DefnUnderlying, Enum);
+    }
+  }
=20
   if (D->getDeclContext()->isFunctionOrMethod())
     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
=20
+  // C++11 [temp.inst]p1: The implicit instantiation of a class template
+  // specialization causes the implicit instantiation of the declarations,=
 but
+  // not the definitions of scoped member enumerations.
+  // FIXME: There appears to be no wording for what happens for an enum de=
fined
+  // within a block scope, but we treat that much like a member template. =
Only
+  // instantiate the definition when visiting the definition in that case,=
 since
+  // we will visit all redeclarations.
+  if (!Enum->isScoped() && Def &&
+      (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefiniti=
on()))
+    InstantiateEnumDefinition(Enum, Def);
+
+  return Enum;
+}
+
+void TemplateDeclInstantiator::InstantiateEnumDefinition(
+    EnumDecl *Enum, EnumDecl *Pattern) {
+  Enum->startDefinition();
+
+  // Update the location to refer to the definition.
+  Enum->setLocation(Pattern->getLocation());
+
   SmallVector<Decl*, 4> Enumerators;
=20
   EnumConstantDecl *LastEnumConst =3D 0;
-  for (EnumDecl::enumerator_iterator EC =3D D->enumerator_begin(),
-         ECEnd =3D D->enumerator_end();
+  for (EnumDecl::enumerator_iterator EC =3D Pattern->enumerator_begin(),
+         ECEnd =3D Pattern->enumerator_end();
        EC !=3D ECEnd; ++EC) {
     // The specified value for the enumerator.
     ExprResult Value =3D SemaRef.Owned((Expr *)0);
     if (Expr *UninstValue =3D EC->getInitExpr()) {
-      // The enumerator's value expression is not potentially evaluated.
+      // The enumerator's value expression is a constant expression.
       EnterExpressionEvaluationContext Unevaluated(SemaRef,
-                                                   Sema::Unevaluated);
+                                                   Sema::ConstantEvaluated=
);
=20
       Value =3D SemaRef.SubstExpr(UninstValue, TemplateArgs);
     }
@@ -679,7 +678,8 @@
       Enumerators.push_back(EnumConst);
       LastEnumConst =3D EnumConst;
=20
-      if (D->getDeclContext()->isFunctionOrMethod()) {
+      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
+          !Enum->isScoped()) {
         // If the enumeration is within a function or method, record the e=
num
         // constant as a local.
         SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumCons=
t);
@@ -687,14 +687,11 @@
     }
   }
=20
-  // FIXME: Fixup LBraceLoc and RBraceLoc
-  // FIXME: Empty Scope and AttributeList (required to handle attribute pa=
cked).
-  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocat=
ion(),
-                        Enum,
+  // FIXME: Fixup LBraceLoc
+  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
+                        Enum->getRBraceLoc(), Enum,
                         Enumerators.data(), Enumerators.size(),
                         0, 0);
-
-  return Enum;
 }
=20
 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D)=
 {
@@ -728,7 +725,7 @@
   CXXRecordDecl *PrevDecl =3D 0;
   ClassTemplateDecl *PrevClassTemplate =3D 0;
=20
-  if (!isFriend && Pattern->getPreviousDeclaration()) {
+  if (!isFriend && Pattern->getPreviousDecl()) {
     DeclContext::lookup_result Found =3D Owner->lookup(Pattern->getDeclNam=
e());
     if (Found.first !=3D Found.second) {
       PrevClassTemplate =3D dyn_cast<ClassTemplateDecl>(*Found.first);
@@ -860,10 +857,17 @@
=20
   // Finish handling of friends.
   if (isFriend) {
-    DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
+    DC->makeDeclVisibleInContext(Inst);
+    Inst->setLexicalDeclContext(Owner);
+    RecordInst->setLexicalDeclContext(Owner);
     return Inst;
   }
=20
+  if (D->isOutOfLine()) {
+    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
+    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
+  }
+
   Owner->addDecl(Inst);
=20
   if (!PrevClassTemplate) {
@@ -958,9 +962,9 @@
   CXXRecordDecl *PrevDecl =3D 0;
   if (D->isInjectedClassName())
     PrevDecl =3D cast<CXXRecordDecl>(Owner);
-  else if (D->getPreviousDeclaration()) {
+  else if (D->getPreviousDecl()) {
     NamedDecl *Prev =3D SemaRef.FindInstantiatedDecl(D->getLocation(),
-                                                   D->getPreviousDeclarati=
on(),
+                                                   D->getPreviousDecl(),
                                                    TemplateArgs);
     if (!Prev) return 0;
     PrevDecl =3D cast<CXXRecordDecl>(Prev);
@@ -1010,11 +1014,11 @@
   // Check whether there is already a function template specialization for
   // this declaration.
   FunctionTemplateDecl *FunctionTemplate =3D D->getDescribedFunctionTempla=
te();
-  void *InsertPos =3D 0;
   if (FunctionTemplate && !TemplateParams) {
     std::pair<const TemplateArgument *, unsigned> Innermost
       =3D TemplateArgs.getInnermost();
=20
+    void *InsertPos =3D 0;
     FunctionDecl *SpecFunc
       =3D FunctionTemplate->findSpecialization(Innermost.first, Innermost.=
second,
                                              InsertPos);
@@ -1037,8 +1041,7 @@
   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
=20
   SmallVector<ParmVarDecl *, 4> Params;
-  TypeSourceInfo *TInfo =3D D->getTypeSourceInfo();
-  TInfo =3D SubstFunctionType(D, Params);
+  TypeSourceInfo *TInfo =3D SubstFunctionType(D, Params);
   if (!TInfo)
     return 0;
   QualType T =3D TInfo->getType();
@@ -1071,7 +1074,7 @@
                            D->getLocation(), D->getDeclName(), T, TInfo,
                            D->getStorageClass(), D->getStorageClassAsWritt=
en(),
                            D->isInlineSpecified(), D->hasWrittenPrototype(=
),
-                           /*isConstexpr*/ false);
+                           D->isConstexpr());
=20
   if (QualifierLoc)
     Function->setQualifierInfo(QualifierLoc);
@@ -1145,7 +1148,7 @@
                             TemplateArgumentList::CreateCopy(SemaRef.Conte=
xt,
                                                              Innermost.fir=
st,
                                                              Innermost.sec=
ond),
-                                                InsertPos);
+                                                /*InsertPos=3D*/0);
   } else if (isFriend) {
     // Note, we need this connection even if the friend doesn't have a bod=
y.
     // Its body may exist but not have been attached yet due to deferred
@@ -1221,25 +1224,42 @@
   if (isFriend) {
     NamedDecl *PrevDecl;
     if (TemplateParams)
-      PrevDecl =3D FunctionTemplate->getPreviousDeclaration();
+      PrevDecl =3D FunctionTemplate->getPreviousDecl();
     else
-      PrevDecl =3D Function->getPreviousDeclaration();
+      PrevDecl =3D Function->getPreviousDecl();
=20
     PrincipalDecl->setObjectOfFriendDecl(PrevDecl !=3D 0);
-    DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=3D*/ false);
+    DC->makeDeclVisibleInContext(PrincipalDecl);
=20
     bool queuedInstantiation =3D false;
=20
-    if (!SemaRef.getLangOptions().CPlusPlus0x &&
+    // C++98 [temp.friend]p5: When a function is defined in a friend funct=
ion
+    //   declaration in a class template, the function is defined at each
+    //   instantiation of the class template. The function is defined even=
 if it
+    //   is never used.
+    // C++11 [temp.friend]p4: When a function is defined in a friend funct=
ion
+    //   declaration in a class template, the function is instantiated whe=
n the
+    //   function is odr-used.
+    //
+    // If -Wc++98-compat is enabled, we go through the motions of checking=
 for a
+    // redefinition, but don't instantiate the function.
+    if ((!SemaRef.getLangOpts().CPlusPlus0x ||
+         SemaRef.Diags.getDiagnosticLevel(
+             diag::warn_cxx98_compat_friend_redefinition,
+             Function->getLocation())
+           !=3D DiagnosticsEngine::Ignored) &&
         D->isThisDeclarationADefinition()) {
       // Check for a function body.
       const FunctionDecl *Definition =3D 0;
       if (Function->isDefined(Definition) &&
           Definition->getTemplateSpecializationKind() =3D=3D TSK_Undeclare=
d) {
-        SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
-          << Function->getDeclName();
+        SemaRef.Diag(Function->getLocation(),
+                     SemaRef.getLangOpts().CPlusPlus0x ?
+                       diag::warn_cxx98_compat_friend_redefinition :
+                       diag::err_redefinition) << Function->getDeclName();
         SemaRef.Diag(Definition->getLocation(), diag::note_previous_defini=
tion);
-        Function->setInvalidDecl();
+        if (!SemaRef.getLangOpts().CPlusPlus0x)
+          Function->setInvalidDecl();
       }
       // Check for redefinitions due to other instantiations of this or
       // a similar friend function.
@@ -1250,7 +1270,8 @@
           continue;
         switch (R->getFriendObjectKind()) {
         case Decl::FOK_None:
-          if (!queuedInstantiation && R->isUsed(false)) {
+          if (!SemaRef.getLangOpts().CPlusPlus0x &&
+              !queuedInstantiation && R->isUsed(false)) {
             if (MemberSpecializationInfo *MSInfo
                 =3D Function->getMemberSpecializationInfo()) {
               if (MSInfo->getPointOfInstantiation().isInvalid()) {
@@ -1267,10 +1288,14 @@
           if (const FunctionDecl *RPattern
               =3D R->getTemplateInstantiationPattern())
             if (RPattern->isDefined(RPattern)) {
-              SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
+              SemaRef.Diag(Function->getLocation(),
+                           SemaRef.getLangOpts().CPlusPlus0x ?
+                             diag::warn_cxx98_compat_friend_redefinition :
+                             diag::err_redefinition)
                 << Function->getDeclName();
               SemaRef.Diag(R->getLocation(), diag::note_previous_definitio=
n);
-              Function->setInvalidDecl();
+              if (!SemaRef.getLangOpts().CPlusPlus0x)
+                Function->setInvalidDecl();
               break;
             }
         }
@@ -1291,7 +1316,6 @@
                                       TemplateParameterList *TemplateParam=
s,
                                       bool IsClassScopeSpecialization) {
   FunctionTemplateDecl *FunctionTemplate =3D D->getDescribedFunctionTempla=
te();
-  void *InsertPos =3D 0;
   if (FunctionTemplate && !TemplateParams) {
     // We are creating a function template specialization from a function
     // template. Check whether there is already a function template
@@ -1299,6 +1323,7 @@
     std::pair<const TemplateArgument *, unsigned> Innermost
       =3D TemplateArgs.getInnermost();
=20
+    void *InsertPos =3D 0;
     FunctionDecl *SpecFunc
       =3D FunctionTemplate->findSpecialization(Innermost.first, Innermost.=
second,
                                              InsertPos);
@@ -1334,8 +1359,7 @@
   }
=20
   SmallVector<ParmVarDecl *, 4> Params;
-  TypeSourceInfo *TInfo =3D D->getTypeSourceInfo();
-  TInfo =3D SubstFunctionType(D, Params);
+  TypeSourceInfo *TInfo =3D SubstFunctionType(D, Params);
   if (!TInfo)
     return 0;
   QualType T =3D TInfo->getType();
@@ -1395,7 +1419,7 @@
                                         StartLoc, NameInfo, T, TInfo,
                                         Constructor->isExplicit(),
                                         Constructor->isInlineSpecified(),
-                                        false, /*isConstexpr*/ false);
+                                        false, Constructor->isConstexpr());
   } else if (CXXDestructorDecl *Destructor =3D dyn_cast<CXXDestructorDecl>=
(D)) {
     Method =3D CXXDestructorDecl::Create(SemaRef.Context, Record,
                                        StartLoc, NameInfo, T, TInfo,
@@ -1406,7 +1430,7 @@
                                        StartLoc, NameInfo, T, TInfo,
                                        Conversion->isInlineSpecified(),
                                        Conversion->isExplicit(),
-                                       /*isConstexpr*/ false,
+                                       Conversion->isConstexpr(),
                                        Conversion->getLocEnd());
   } else {
     Method =3D CXXMethodDecl::Create(SemaRef.Context, Record,
@@ -1414,7 +1438,7 @@
                                    D->isStatic(),
                                    D->getStorageClassAsWritten(),
                                    D->isInlineSpecified(),
-                                   /*isConstexpr*/ false, D->getLocEnd());
+                                   D->isConstexpr(), D->getLocEnd());
   }
=20
   if (QualifierLoc)
@@ -1452,7 +1476,7 @@
                          TemplateArgumentList::CreateCopy(SemaRef.Context,
                                                           Innermost.first,
                                                           Innermost.second=
),
-                                              InsertPos);
+                                              /*InsertPos=3D*/0);
   } else if (!isFriend) {
     // Record that this is an instantiation of a member function.
     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
@@ -1504,6 +1528,12 @@
=20
   SemaRef.CheckOverrideControl(Method);
=20
+  // If a function is defined as defaulted or deleted, mark it as such now.
+  if (D->isDefaulted())
+    Method->setDefaulted();
+  if (D->isDeletedAsWritten())
+    Method->setDeletedAsWritten();
+
   if (FunctionTemplate) {
     // If there's a function template, let our caller handle it.
   } else if (Method->isInvalidDecl() && !Previous.empty()) {
@@ -1542,7 +1572,8 @@
=20
 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
-                                  llvm::Optional<unsigned>());
+                                  llvm::Optional<unsigned>(),
+                                  /*ExpectParameterPack=3D*/false);
 }
=20
 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
@@ -1825,6 +1856,12 @@
   if (NewUD->isInvalidDecl())
     return NewUD;
=20
+  if (NameInfo.getName().getNameKind() =3D=3D DeclarationName::CXXConstruc=
torName) {
+    if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
+      NewUD->setInvalidDecl();
+    return NewUD;
+  }
+
   bool isFunctionScope =3D Owner->isFunctionOrMethod();
=20
   // Process the shadow decls.
@@ -2094,7 +2131,7 @@
=20
   // Add this partial specialization to the set of class template partial
   // specializations.
-  ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
+  ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=3D*=
/0);
   return InstPartialSpec;
 }
=20
@@ -2124,6 +2161,8 @@
            OldIdx !=3D NumOldParams; ++OldIdx) {
         ParmVarDecl *OldParam =3D OldProtoLoc->getArg(OldIdx);
         if (!OldParam->isParameterPack() ||
+            // FIXME: Is this right? OldParam could expand to an empty par=
ameter
+            // pack and the next parameter could be an unexpanded paramete=
r pack
             (NewIdx < NumNewParams &&
              NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
           // Simple case: normal parameter, or a parameter pack that's
@@ -2280,23 +2319,19 @@
     }
     Expr *NoexceptExpr =3D 0;
     if (Expr *OldNoexceptExpr =3D Proto->getNoexceptExpr()) {
-      EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevalua=
ted);
+      EnterExpressionEvaluationContext Unevaluated(SemaRef,
+                                                   Sema::ConstantEvaluated=
);
       ExprResult E =3D SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
       if (E.isUsable())
         E =3D SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart(=
));
-   =20
+
       if (E.isUsable()) {
-        SourceLocation ErrLoc;
-        llvm::APSInt NoexceptVal;
         NoexceptExpr =3D E.take();
         if (!NoexceptExpr->isTypeDependent() &&
-            !NoexceptExpr->isValueDependent() &&
-            !NoexceptExpr->isIntegerConstantExpr(NoexceptVal, SemaRef.Cont=
ext,
-                                                 &ErrLoc, /*evaluated=3D*/=
false)){
-          SemaRef.Diag(ErrLoc, diag::err_noexcept_needs_constant_expressio=
n)
-            << NoexceptExpr->getSourceRange();
-          NoexceptExpr =3D 0;
-        }
+            !NoexceptExpr->isValueDependent())
+          NoexceptExpr =3D SemaRef.VerifyIntegerConstantExpression(Noexcep=
tExpr,
+            0, SemaRef.PDiag(diag::err_noexcept_needs_constant_expression),
+            /*AllowFold*/ false).take();
       }
     }
=20
@@ -2318,19 +2353,13 @@
                                                  EPI));
   }
=20
-  // C++0x [dcl.constexpr]p6: If the instantiated template specialization =
of
-  // a constexpr function template satisfies the requirements for a conste=
xpr
-  // function, then it is a constexpr function.
-  if (Tmpl->isConstexpr() &&
-      SemaRef.CheckConstexprFunctionDecl(New, Sema::CCK_Instantiation))
-    New->setConstexpr(true);
-
   const FunctionDecl* Definition =3D Tmpl;
=20
   // Get the definition. Leaves the variable unchanged if undefined.
   Tmpl->isDefined(Definition);
=20
-  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New);
+  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
+                           LateAttrs, StartingScope);
=20
   return false;
 }
@@ -2450,6 +2479,9 @@
   if (Inst)
     return;
=20
+  // Copy the inner loc start from the pattern.
+  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
+
   // If we're performing recursive template instantiation, create our own
   // queue of pending implicit instantiations that we will instantiate lat=
er,
   // while we're still within our own instantiation context.
@@ -2474,6 +2506,13 @@
=20
   LocalInstantiationScope Scope(*this, MergeWithParentScope);
=20
+  // Enter the scope of this instantiation. We don't use
+  // PushDeclContext because we don't have a scope.
+  Sema::ContextRAII savedContext(*this, Function);
+
+  MultiLevelTemplateArgumentList TemplateArgs =3D
+    getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
+
   // Introduce the instantiated function parameters into the local
   // instantiation scope, and set the parameter names to those used
   // in the template.
@@ -2483,7 +2522,7 @@
     if (!PatternParam->isParameterPack()) {
       // Simple case: not a parameter pack.
       assert(FParamIdx < Function->getNumParams());
-      ParmVarDecl *FunctionParam =3D Function->getParamDecl(I);
+      ParmVarDecl *FunctionParam =3D Function->getParamDecl(FParamIdx);
       FunctionParam->setDeclName(PatternParam->getDeclName());
       Scope.InstantiatedLocal(PatternParam, FunctionParam);
       ++FParamIdx;
@@ -2492,22 +2531,16 @@
=20
     // Expand the parameter pack.
     Scope.MakeInstantiatedLocalArgPack(PatternParam);
-    for (unsigned NumFParams =3D Function->getNumParams();
-         FParamIdx < NumFParams;
-         ++FParamIdx) {
+    unsigned NumArgumentsInExpansion
+      =3D getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs=
);
+    for (unsigned Arg =3D 0; Arg < NumArgumentsInExpansion; ++Arg) {
       ParmVarDecl *FunctionParam =3D Function->getParamDecl(FParamIdx);
       FunctionParam->setDeclName(PatternParam->getDeclName());
       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
+      ++FParamIdx;
     }
   }
=20
-  // Enter the scope of this instantiation. We don't use
-  // PushDeclContext because we don't have a scope.
-  Sema::ContextRAII savedContext(*this, Function);
-
-  MultiLevelTemplateArgumentList TemplateArgs =3D
-    getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
-
   if (PatternDecl->isDefaulted()) {
     ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=3D*/true);
=20
@@ -2612,21 +2645,29 @@
     return;
   }
=20
+  TemplateSpecializationKind TSK =3D Var->getTemplateSpecializationKind();
+
   // Never instantiate an explicit specialization.
-  if (Var->getTemplateSpecializationKind() =3D=3D TSK_ExplicitSpecializati=
on)
+  if (TSK =3D=3D TSK_ExplicitSpecialization)
     return;
=20
   // C++0x [temp.explicit]p9:
   //   Except for inline functions, other explicit instantiation declarati=
ons
   //   have the effect of suppressing the implicit instantiation of the en=
tity
   //   to which they refer.
-  if (Var->getTemplateSpecializationKind()
-        =3D=3D TSK_ExplicitInstantiationDeclaration)
+  if (TSK =3D=3D TSK_ExplicitInstantiationDeclaration)
     return;
=20
+  Consumer.HandleCXXStaticMemberVarInstantiation(Var);
+
   // If we already have a definition, we're done.
-  if (Var->getDefinition())
+  if (VarDecl *Def =3D Var->getDefinition()) {
+    // We may be explicitly instantiating something we've already implicit=
ly
+    // instantiated.
+    Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(=
),
+                                       PointOfInstantiation);
     return;
+  }
=20
   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
   if (Inst)
@@ -2645,7 +2686,8 @@
   // Enter the scope of this instantiation. We don't use
   // PushDeclContext because we don't have a scope.
   ContextRAII previousContext(*this, Var->getDeclContext());
-
+  LocalInstantiationScope Local(*this);
+ =20
   VarDecl *OldVar =3D Var;
   Var =3D cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
                                         getTemplateInstantiationArgs(Var))=
);
@@ -2660,7 +2702,8 @@
     DeclGroupRef DG(Var);
     Consumer.HandleTopLevelDecl(DG);
   }
-
+  Local.Exit();
+ =20
   if (Recursive) {
     // Define any newly required vtables.
     DefineUsedVTables();
@@ -2683,18 +2726,6 @@
   }
 }
=20
-static MultiInitializer CreateMultiInitializer(SmallVectorImpl<Expr*> &Arg=
s,
-                                               const CXXCtorInitializer *I=
nit) {
-  // FIXME: This is a hack that will do slightly the wrong thing for an
-  // initializer of the form foo({...}).
-  // The right thing to do would be to modify InstantiateInitializer to cr=
eate
-  // the MultiInitializer.
-  if (Args.size() =3D=3D 1 && isa<InitListExpr>(Args[0]))
-    return MultiInitializer(Args[0]);
-  return MultiInitializer(Init->getLParenLoc(), Args.data(),
-                          Args.size(), Init->getRParenLoc());
-}
-
 void
 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
                                  const CXXConstructorDecl *Tmpl,
@@ -2714,14 +2745,11 @@
     if (!Init->isWritten())
       continue;
=20
-    SourceLocation LParenLoc, RParenLoc;
-    ASTOwningVector<Expr*> NewArgs(*this);
-
     SourceLocation EllipsisLoc;
=20
     if (Init->isPackExpansion()) {
       // This is a pack expansion. We should expand it now.
-      TypeLoc BaseTL =3D Init->getBaseClassInfo()->getTypeLoc();
+      TypeLoc BaseTL =3D Init->getTypeSourceInfo()->getTypeLoc();
       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
       bool ShouldExpand =3D false;
@@ -2744,14 +2772,15 @@
         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
=20
         // Instantiate the initializer.
-        if (InstantiateInitializer(Init->getInit(), TemplateArgs,
-                                   LParenLoc, NewArgs, RParenLoc)) {
+        ExprResult TempInit =3D SubstInitializer(Init->getInit(), Template=
Args,
+                                               /*CXXDirectInit=3D*/true);
+        if (TempInit.isInvalid()) {
           AnyErrors =3D true;
           break;
         }
=20
         // Instantiate the base type.
-        TypeSourceInfo *BaseTInfo =3D SubstType(Init->getBaseClassInfo(),
+        TypeSourceInfo *BaseTInfo =3D SubstType(Init->getTypeSourceInfo(),
                                               TemplateArgs,
                                               Init->getSourceLocation(),
                                               New->getDeclName());
@@ -2761,9 +2790,8 @@
         }
=20
         // Build the initializer.
-        MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
         MemInitResult NewInit =3D BuildBaseInitializer(BaseTInfo->getType(=
),
-                                                     BaseTInfo, MultiInit,
+                                                     BaseTInfo, TempInit.t=
ake(),
                                                      New->getParent(),
                                                      SourceLocation());
         if (NewInit.isInvalid()) {
@@ -2772,34 +2800,37 @@
         }
=20
         NewInits.push_back(NewInit.get());
-        NewArgs.clear();
       }
=20
       continue;
     }
=20
     // Instantiate the initializer.
-    if (InstantiateInitializer(Init->getInit(), TemplateArgs,
-                               LParenLoc, NewArgs, RParenLoc)) {
+    ExprResult TempInit =3D SubstInitializer(Init->getInit(), TemplateArgs,
+                                           /*CXXDirectInit=3D*/true);
+    if (TempInit.isInvalid()) {
       AnyErrors =3D true;
       continue;
     }
=20
     MemInitResult NewInit;
-    if (Init->isBaseInitializer()) {
-      TypeSourceInfo *BaseTInfo =3D SubstType(Init->getBaseClassInfo(),
-                                            TemplateArgs,
-                                            Init->getSourceLocation(),
-                                            New->getDeclName());
-      if (!BaseTInfo) {
+    if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
+      TypeSourceInfo *TInfo =3D SubstType(Init->getTypeSourceInfo(),
+                                        TemplateArgs,
+                                        Init->getSourceLocation(),
+                                        New->getDeclName());
+      if (!TInfo) {
         AnyErrors =3D true;
         New->setInvalidDecl();
         continue;
       }
=20
-      MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
-      NewInit =3D BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo, Mu=
ltiInit,
-                                     New->getParent(), EllipsisLoc);
+      if (Init->isBaseInitializer())
+        NewInit =3D BuildBaseInitializer(TInfo->getType(), TInfo, TempInit=
.take(),
+                                       New->getParent(), EllipsisLoc);
+      else
+        NewInit =3D BuildDelegatingInitializer(TInfo, TempInit.take(),
+                                  cast<CXXRecordDecl>(CurContext->getParen=
t()));
     } else if (Init->isMemberInitializer()) {
       FieldDecl *Member =3D cast_or_null<FieldDecl>(FindInstantiatedDecl(
                                                      Init->getMemberLocati=
on(),
@@ -2811,8 +2842,7 @@
         continue;
       }
=20
-      MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
-      NewInit =3D BuildMemberInitializer(Member, MultiInit,
+      NewInit =3D BuildMemberInitializer(Member, TempInit.take(),
                                        Init->getSourceLocation());
     } else if (Init->isIndirectMemberInitializer()) {
       IndirectFieldDecl *IndirectMember =3D
@@ -2826,8 +2856,7 @@
         continue;
       }
=20
-      MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
-      NewInit =3D BuildMemberInitializer(IndirectMember, MultiInit,
+      NewInit =3D BuildMemberInitializer(IndirectMember, TempInit.take(),
                                        Init->getSourceLocation());
     }
=20
@@ -2835,9 +2864,6 @@
       AnyErrors =3D true;
       New->setInvalidDecl();
     } else {
-      // FIXME: It would be nice if ASTOwningVector had a release function.
-      NewArgs.take();
-
       NewInits.push_back(NewInit.get());
     }
   }
@@ -2850,6 +2876,45 @@
                        AnyErrors);
 }
=20
+ExprResult Sema::SubstInitializer(Expr *Init,
+                          const MultiLevelTemplateArgumentList &TemplateAr=
gs,
+                          bool CXXDirectInit) {
+  // Initializers are instantiated like expressions, except that various o=
uter
+  // layers are stripped.
+  if (!Init)
+    return Owned(Init);
+
+  if (ExprWithCleanups *ExprTemp =3D dyn_cast<ExprWithCleanups>(Init))
+    Init =3D ExprTemp->getSubExpr();
+
+  while (CXXBindTemporaryExpr *Binder =3D dyn_cast<CXXBindTemporaryExpr>(I=
nit))
+    Init =3D Binder->getSubExpr();
+
+  if (ImplicitCastExpr *ICE =3D dyn_cast<ImplicitCastExpr>(Init))
+    Init =3D ICE->getSubExprAsWritten();
+
+  // If this is a direct-initializer, we take apart CXXConstructExprs.
+  // Everything else is passed through.
+  CXXConstructExpr *Construct;
+  if (!CXXDirectInit || !(Construct =3D dyn_cast<CXXConstructExpr>(Init)) =
||
+      isa<CXXTemporaryObjectExpr>(Construct))
+    return SubstExpr(Init, TemplateArgs);
+
+  ASTOwningVector<Expr*> NewArgs(*this);
+  if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
+                 TemplateArgs, NewArgs))
+    return ExprError();
+
+  // Treat an empty initializer like none.
+  if (NewArgs.empty())
+    return Owned((Expr*)0);
+
+  // Build a ParenListExpr to represent anything else.
+  // FIXME: Fake locations!
+  SourceLocation Loc =3D PP.getLocForEndOfToken(Init->getLocStart());
+  return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs));
+}
+
 // TODO: this could be templated if the various decl types used the
 // same method name.
 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
@@ -3090,7 +3155,8 @@
   DeclContext *ParentDC =3D D->getDeclContext();
   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
-      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
+      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
+      (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
     // D is a local of some kind. Look into the map of local
     // declarations to their instantiations.
     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
@@ -3120,75 +3186,49 @@
     if (!Record->isDependentContext())
       return D;
=20
-    // If the RecordDecl is actually the injected-class-name or a
-    // "templated" declaration for a class template, class template
-    // partial specialization, or a member class of a class template,
-    // substitute into the injected-class-name of the class template
-    // or partial specialization to find the new DeclContext.
-    QualType T;
+    // Determine whether this record is the "templated" declaration descri=
bing
+    // a class template or class template partial specialization.
     ClassTemplateDecl *ClassTemplate =3D Record->getDescribedClassTemplate=
();
-
-    if (ClassTemplate) {
-      T =3D ClassTemplate->getInjectedClassNameSpecialization();
-    } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
-                 =3D dyn_cast<ClassTemplatePartialSpecializationDecl>(Reco=
rd)) {
-      ClassTemplate =3D PartialSpec->getSpecializedTemplate();
-
-      // If we call SubstType with an InjectedClassNameType here we
-      // can end up in an infinite loop.
-      T =3D Context.getTypeDeclType(Record);
-      assert(isa<InjectedClassNameType>(T) &&
-             "type of partial specialization is not an InjectedClassNameTy=
pe");
-      T =3D cast<InjectedClassNameType>(T)->getInjectedSpecializationType(=
);
-    }
-
-    if (!T.isNull()) {
-      // Substitute into the injected-class-name to get the type
-      // corresponding to the instantiation we want, which may also be
-      // the current instantiation (if we're in a template
-      // definition). This substitution should never fail, since we
-      // know we can instantiate the injected-class-name or we
-      // wouldn't have gotten to the injected-class-name!
-
-      // FIXME: Can we use the CurrentInstantiationScope to avoid this
-      // extra instantiation in the common case?
-      T =3D SubstType(T, TemplateArgs, Loc, DeclarationName());
-      assert(!T.isNull() && "Instantiation of injected-class-name cannot f=
ail.");
-
-      if (!T->isDependentType()) {
-        assert(T->isRecordType() && "Instantiation must produce a record t=
ype");
-        return T->getAs<RecordType>()->getDecl();
+    if (ClassTemplate)
+      ClassTemplate =3D ClassTemplate->getCanonicalDecl();
+    else if (ClassTemplatePartialSpecializationDecl *PartialSpec
+               =3D dyn_cast<ClassTemplatePartialSpecializationDecl>(Record=
))
+      ClassTemplate =3D PartialSpec->getSpecializedTemplate()->getCanonica=
lDecl();
+   =20
+    // Walk the current context to find either the record or an instantiat=
ion of
+    // it.
+    DeclContext *DC =3D CurContext;
+    while (!DC->isFileContext()) {
+      // If we're performing substitution while we're inside the template
+      // definition, we'll find our own context. We're done.
+      if (DC->Equals(Record))
+        return Record;
+     =20
+      if (CXXRecordDecl *InstRecord =3D dyn_cast<CXXRecordDecl>(DC)) {
+        // Check whether we're in the process of instantiating a class tem=
plate
+        // specialization of the template we're mapping.
+        if (ClassTemplateSpecializationDecl *InstSpec
+                      =3D dyn_cast<ClassTemplateSpecializationDecl>(InstRe=
cord)){
+          ClassTemplateDecl *SpecTemplate =3D InstSpec->getSpecializedTemp=
late();
+          if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTempla=
te))
+            return InstRecord;
+        }
+     =20
+        // Check whether we're in the process of instantiating a member cl=
ass.
+        if (isInstantiationOf(Record, InstRecord))
+          return InstRecord;
       }
-
-      // We are performing "partial" template instantiation to create
-      // the member declarations for the members of a class template
-      // specialization. Therefore, D is actually referring to something
-      // in the current instantiation. Look through the current
-      // context, which contains actual instantiations, to find the
-      // instantiation of the "current instantiation" that D refers
-      // to.
-      bool SawNonDependentContext =3D false;
-      for (DeclContext *DC =3D CurContext; !DC->isFileContext();
-           DC =3D DC->getParent()) {
-        if (ClassTemplateSpecializationDecl *Spec
-                          =3D dyn_cast<ClassTemplateSpecializationDecl>(DC=
))
-          if (isInstantiationOf(ClassTemplate,
-                                Spec->getSpecializedTemplate()))
-            return Spec;
-
-        if (!DC->isDependentContext())
-          SawNonDependentContext =3D true;
+     =20
+     =20
+      // Move to the outer template scope.
+      if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(DC)) {
+        if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileConte=
xt()){
+          DC =3D FD->getLexicalDeclContext();
+          continue;
+        }
       }
-
-      // We're performing "instantiation" of a member of the current
-      // instantiation while we are type-checking the
-      // definition. Compute the declaration context and return that.
-      assert(!SawNonDependentContext &&
-             "No dependent context while instantiating record");
-      DeclContext *DC =3D computeDeclContext(T);
-      assert(DC &&
-             "Unable to find declaration for the current instantiation");
-      return cast<CXXRecordDecl>(DC);
+     =20
+      DC =3D DC->getParent();
     }
=20
     // Fall through to deal with other dependent record types (e.g.,
@@ -3260,6 +3300,20 @@
           << D->getDeclName()
           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
+      } else if (EnumConstantDecl *ED =3D dyn_cast<EnumConstantDecl>(D)) {
+        // This enumeration constant was found when the template was defin=
ed,
+        // but can't be found in the instantiation. This can happen if an
+        // unscoped enumeration member is explicitly specialized.
+        EnumDecl *Enum =3D cast<EnumDecl>(ED->getLexicalDeclContext());
+        EnumDecl *Spec =3D cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
+                                                             TemplateArgs)=
);
+        assert(Spec->getTemplateSpecializationKind() =3D=3D
+                 TSK_ExplicitSpecialization);
+        Diag(Loc, diag::err_enumerator_does_not_exist)
+          << D->getDeclName()
+          << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()=
));
+        Diag(Spec->getLocation(), diag::note_enum_specialized_here)
+          << Context.getTypeDeclType(Spec);
       } else {
         // We should have found something, but didn't.
         llvm_unreachable("Unable to find instantiation of declaration!");
@@ -3312,12 +3366,12 @@
=20
     // Don't try to instantiate declarations if the most recent redeclarat=
ion
     // is invalid.
-    if (Var->getMostRecentDeclaration()->isInvalidDecl())
+    if (Var->getMostRecentDecl()->isInvalidDecl())
       continue;
=20
     // Check if the most recent declaration has changed the specialization=
 kind
     // and removed the need for implicit instantiation.
-    switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind=
()) {
+    switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
     case TSK_Undeclared:
       llvm_unreachable("Cannot instantitiate an undeclared specialization.=
");
     case TSK_ExplicitInstantiationDeclaration:
@@ -3326,7 +3380,7 @@
     case TSK_ExplicitInstantiationDefinition:
       // We only need an instantiation if the pending instantiation *is* t=
he
       // explicit instantiation.
-      if (Var !=3D Var->getMostRecentDeclaration()) continue;
+      if (Var !=3D Var->getMostRecentDecl()) continue;
     case TSK_ImplicitInstantiation:
       break;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaTemplateVariadic.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateVariadic.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaTemplateVariadic.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -73,15 +73,6 @@
       return true;
     }
    =20
-    // \brief Record occurrences of function and non-type template paramet=
er
-    // packs in a block-captured expression.
-    bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
-      if (E->getDecl()->isParameterPack())
-        Unexpanded.push_back(std::make_pair(E->getDecl(), E->getLocation()=
));
-     =20
-      return true;
-    }
-   =20
     /// \brief Record occurrences of template template parameter packs.
     bool TraverseTemplateName(TemplateName Template) {
       if (TemplateTemplateParmDecl *TTP=20
@@ -93,6 +84,22 @@
       return inherited::TraverseTemplateName(Template);
     }
=20
+    /// \brief Suppress traversal into Objective-C container literal
+    /// elements that are pack expansions.
+    bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
+      if (!E->containsUnexpandedParameterPack())
+        return true;
+
+      for (unsigned I =3D 0, N =3D E->getNumElements(); I !=3D N; ++I) {
+        ObjCDictionaryElement Element =3D E->getKeyValueElement(I);
+        if (Element.isPackExpansion())
+          continue;
+
+        TraverseStmt(Element.Key);
+        TraverseStmt(Element.Value);
+      }
+      return true;
+    }
     //--------------------------------------------------------------------=
----
     // Pruning the search for unexpanded parameter packs.
     //--------------------------------------------------------------------=
----
@@ -155,10 +162,13 @@
=20
 /// \brief Diagnose all of the unexpanded parameter packs in the given
 /// vector.
-static void=20
-DiagnoseUnexpandedParameterPacks(Sema &S, SourceLocation Loc,
-                                 Sema::UnexpandedParameterPackContext UPPC,
-             const SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
+void
+Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
+                                       UnexpandedParameterPackContext UPPC,
+                                 ArrayRef<UnexpandedParameterPack> Unexpan=
ded) {
+  if (Unexpanded.empty())
+    return;
+ =20
   SmallVector<SourceLocation, 4> Locations;
   SmallVector<IdentifierInfo *, 4> Names;
   llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
@@ -179,13 +189,13 @@
   }
=20
   DiagnosticBuilder DB
-    =3D Names.size() =3D=3D 0? S.Diag(Loc, diag::err_unexpanded_parameter_=
pack_0)
+    =3D Names.size() =3D=3D 0? Diag(Loc, diag::err_unexpanded_parameter_pa=
ck_0)
                            << (int)UPPC
-    : Names.size() =3D=3D 1? S.Diag(Loc, diag::err_unexpanded_parameter_pa=
ck_1)
+    : Names.size() =3D=3D 1? Diag(Loc, diag::err_unexpanded_parameter_pack=
_1)
                            << (int)UPPC << Names[0]
-    : Names.size() =3D=3D 2? S.Diag(Loc, diag::err_unexpanded_parameter_pa=
ck_2)
+    : Names.size() =3D=3D 2? Diag(Loc, diag::err_unexpanded_parameter_pack=
_2)
                            << (int)UPPC << Names[0] << Names[1]
-    : S.Diag(Loc, diag::err_unexpanded_parameter_pack_3_or_more)
+    : Diag(Loc, diag::err_unexpanded_parameter_pack_3_or_more)
         << (int)UPPC << Names[0] << Names[1];
=20
   for (unsigned I =3D 0, N =3D Locations.size(); I !=3D N; ++I)
@@ -205,7 +215,7 @@
   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
                                                               T->getTypeLo=
c());
   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs=
");
-  DiagnoseUnexpandedParameterPacks(*this, Loc, UPPC, Unexpanded);
+  DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
   return true;
 }
=20
@@ -220,7 +230,7 @@
   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs=
");
-  DiagnoseUnexpandedParameterPacks(*this, E->getLocStart(), UPPC, Unexpand=
ed);
+  DiagnoseUnexpandedParameterPacks(E->getLocStart(), UPPC, Unexpanded);
   return true;
 }
=20
@@ -237,7 +247,7 @@
   CollectUnexpandedParameterPacksVisitor(Unexpanded)
     .TraverseNestedNameSpecifier(SS.getScopeRep());
   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs=
");
-  DiagnoseUnexpandedParameterPacks(*this, SS.getRange().getBegin(),=20
+  DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),=20
                                    UPPC, Unexpanded);
   return true;
 }
@@ -274,7 +284,7 @@
   CollectUnexpandedParameterPacksVisitor(Unexpanded)
     .TraverseType(NameInfo.getName().getCXXNameType());
   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs=
");
-  DiagnoseUnexpandedParameterPacks(*this, NameInfo.getLoc(), UPPC, Unexpan=
ded);
+  DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
   return true;
 }
=20
@@ -289,7 +299,7 @@
   CollectUnexpandedParameterPacksVisitor(Unexpanded)
     .TraverseTemplateName(Template);
   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs=
");
-  DiagnoseUnexpandedParameterPacks(*this, Loc, UPPC, Unexpanded);
+  DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
   return true;
 }
=20
@@ -303,7 +313,7 @@
   CollectUnexpandedParameterPacksVisitor(Unexpanded)
     .TraverseTemplateArgumentLoc(Arg);
   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs=
");
-  DiagnoseUnexpandedParameterPacks(*this, Arg.getLocation(), UPPC, Unexpan=
ded);
+  DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
   return true; =20
 }
=20
@@ -329,6 +339,24 @@
   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL); =20
 } =20
=20
+void Sema::collectUnexpandedParameterPacks(CXXScopeSpec &SS,
+                                           SmallVectorImpl<UnexpandedParam=
eterPack> &Unexpanded) {
+  NestedNameSpecifier *Qualifier =3D SS.getScopeRep();
+  if (!Qualifier)
+    return;
+ =20
+  NestedNameSpecifierLoc QualifierLoc(Qualifier, SS.location_data());
+  CollectUnexpandedParameterPacksVisitor(Unexpanded)
+    .TraverseNestedNameSpecifierLoc(QualifierLoc);
+}
+
+void Sema::collectUnexpandedParameterPacks(const DeclarationNameInfo &Name=
Info,
+                         SmallVectorImpl<UnexpandedParameterPack> &Unexpan=
ded) {
+  CollectUnexpandedParameterPacksVisitor(Unexpanded)
+    .TraverseDeclarationNameInfo(NameInfo);
+}
+
+
 ParsedTemplateArgument=20
 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
                          SourceLocation EllipsisLoc) {
@@ -367,7 +395,6 @@
     return Arg.getTemplatePackExpansion(EllipsisLoc);
   }
   llvm_unreachable("Unhandled template argument kind?");
-  return ParsedTemplateArgument();
 }
=20
 TypeResult Sema::ActOnPackExpansion(ParsedType Type,=20
@@ -611,7 +638,6 @@
   }
  =20
   llvm_unreachable("No unexpanded parameter packs in type expansion.");
-  return 0;
 }
=20
 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
@@ -641,6 +667,7 @@
   case TST_char16:
   case TST_char32:
   case TST_int:
+  case TST_int128:
   case TST_half:
   case TST_float:
   case TST_double:
@@ -674,7 +701,6 @@
       // declarator-id (conceptually), so the parser should not invoke this
       // routine at this time.
       llvm_unreachable("Could not have seen this kind of declarator chunk"=
);
-      break;
        =20
     case DeclaratorChunk::MemberPointer:
       if (Chunk.Mem.Scope().getScopeRep() &&
@@ -687,6 +713,19 @@
   return false;
 }
=20
+namespace {
+
+// Callback to only accept typo corrections that refer to parameter packs.
+class ParameterPackValidatorCCC : public CorrectionCandidateCallback {
+ public:
+  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
+    NamedDecl *ND =3D candidate.getCorrectionDecl();
+    return ND && ND->isParameterPack();
+  }
+};
+
+}
+
 /// \brief Called when an expression computing the size of a parameter pack
 /// is parsed.
 ///
@@ -712,6 +751,7 @@
   LookupName(R, S);
  =20
   NamedDecl *ParameterPack =3D 0;
+  ParameterPackValidatorCCC Validator;
   switch (R.getResultKind()) {
   case LookupResult::Found:
     ParameterPack =3D R.getFoundDecl();
@@ -720,19 +760,16 @@
   case LookupResult::NotFound:
   case LookupResult::NotFoundInCurrentInstantiation:
     if (TypoCorrection Corrected =3D CorrectTypo(R.getLookupNameInfo(),
-                                               R.getLookupKind(), S, 0, 0,
-                                               false, CTC_NoKeywords)) {
-      if (NamedDecl *CorrectedResult =3D Corrected.getCorrectionDecl())
-        if (CorrectedResult->isParameterPack()) {
-          std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOption=
s()));
-          ParameterPack =3D CorrectedResult;
-          Diag(NameLoc, diag::err_sizeof_pack_no_pack_name_suggest)
-            << &Name << CorrectedQuotedStr
-            << FixItHint::CreateReplacement(
-                NameLoc, Corrected.getAsString(getLangOptions()));
-          Diag(ParameterPack->getLocation(), diag::note_parameter_pack_her=
e)
-            << CorrectedQuotedStr;
-        }
+                                               R.getLookupKind(), S, 0,
+                                               Validator)) {
+      std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
+      ParameterPack =3D Corrected.getCorrectionDecl();
+      Diag(NameLoc, diag::err_sizeof_pack_no_pack_name_suggest)
+        << &Name << CorrectedQuotedStr
+        << FixItHint::CreateReplacement(
+            NameLoc, Corrected.getAsString(getLangOpts()));
+      Diag(ParameterPack->getLocation(), diag::note_parameter_pack_here)
+        << CorrectedQuotedStr;
     }
      =20
   case LookupResult::FoundOverloaded:
@@ -750,6 +787,8 @@
     return ExprError();
   }
=20
+  MarkAnyDeclReferenced(OpLoc, ParameterPack);
+
   return new (Context) SizeOfPackExpr(Context.getSizeType(), OpLoc,=20
                                       ParameterPack, NameLoc, RParenLoc);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/SemaType.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/SemaType.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -11,6 +11,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "clang/Sema/ScopeInfo.h"
 #include "clang/Sema/SemaInternal.h"
 #include "clang/Sema/Template.h"
 #include "clang/Basic/OpenCL.h"
@@ -25,8 +26,10 @@
 #include "clang/Basic/PartialDiagnostic.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Lex/Preprocessor.h"
+#include "clang/Parse/ParseDiagnostic.h"
 #include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/DelayedDiagnostic.h"
+#include "clang/Sema/Lookup.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/ErrorHandling.h"
 using namespace clang;
@@ -503,7 +506,7 @@
       break;
=20
     case AttributeList::AT_ns_returns_retained:
-      if (!state.getSema().getLangOptions().ObjCAutoRefCount)
+      if (!state.getSema().getLangOpts().ObjCAutoRefCount)
         break;
       // fallthrough
=20
@@ -546,7 +549,7 @@
   // faking up the function chunk is still the right thing to do.
=20
   // Otherwise, we need to fake up a function declarator.
-  SourceLocation loc =3D declarator.getSourceRange().getBegin();
+  SourceLocation loc =3D declarator.getLocStart();
=20
   // ...and *prepend* it to the declarator.
   declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
@@ -555,6 +558,8 @@
                              /*args*/ 0, 0,
                              /*type quals*/ 0,
                              /*ref-qualifier*/true, SourceLocation(),
+                             /*const qualifier*/SourceLocation(),
+                             /*volatile qualifier*/SourceLocation(),
                              /*mutable qualifier*/SourceLocation(),
                              /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
                              /*parens*/ loc, loc,
@@ -580,7 +585,7 @@
   const DeclSpec &DS =3D declarator.getDeclSpec();
   SourceLocation DeclLoc =3D declarator.getIdentifierLoc();
   if (DeclLoc.isInvalid())
-    DeclLoc =3D DS.getSourceRange().getBegin();
+    DeclLoc =3D DS.getLocStart();
  =20
   ASTContext &Context =3D S.Context;
=20
@@ -637,7 +642,10 @@
    =20
     // If this is a missing declspec in a block literal return context, th=
en it
     // is inferred from the return statements inside the block.
-    if (isOmittedBlockReturnType(declarator)) {
+    // The declspec is always missing in a lambda expr context; it is eith=
er
+    // specified with a trailing return type or inferred.
+    if (declarator.getContext() =3D=3D Declarator::LambdaExprContext ||
+        isOmittedBlockReturnType(declarator)) {
       Result =3D Context.DependentTy;
       break;
     }
@@ -649,13 +657,13 @@
     // allowed to be completely missing a declspec.  This is handled in the
     // parser already though by it pretending to have seen an 'int' in this
     // case.
-    if (S.getLangOptions().ImplicitInt) {
+    if (S.getLangOpts().ImplicitInt) {
       // In C89 mode, we only warn if there is a completely missing declsp=
ec
       // when one is not allowed.
       if (DS.isEmpty()) {
         S.Diag(DeclLoc, diag::ext_missing_declspec)
           << DS.getSourceRange()
-        << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int=
");
+        << FixItHint::CreateInsertion(DS.getLocStart(), "int");
       }
     } else if (!DS.hasTypeSpecifier()) {
       // C99 and C++ require a type specifier.  For example, C99 6.7.2p2 s=
ays:
@@ -663,8 +671,8 @@
       // specifiers in each declaration, and in the specifier-qualifier li=
st in
       // each struct declaration and type name."
       // FIXME: Does Microsoft really have the implicit int extension in C=
++?
-      if (S.getLangOptions().CPlusPlus &&
-          !S.getLangOptions().MicrosoftExt) {
+      if (S.getLangOpts().CPlusPlus &&
+          !S.getLangOpts().MicrosoftExt) {
         S.Diag(DeclLoc, diag::err_missing_type_specifier)
           << DS.getSourceRange();
=20
@@ -689,9 +697,10 @@
         Result =3D Context.LongLongTy;
          =20
         // long long is a C99 feature.
-        if (!S.getLangOptions().C99 &&
-            !S.getLangOptions().CPlusPlus0x)
-          S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
+        if (!S.getLangOpts().C99)
+          S.Diag(DS.getTypeSpecWidthLoc(),
+                 S.getLangOpts().CPlusPlus0x ?
+                   diag::warn_cxx98_compat_longlong : diag::ext_longlong);
         break;
       }
     } else {
@@ -703,14 +712,21 @@
         Result =3D Context.UnsignedLongLongTy;
          =20
         // long long is a C99 feature.
-        if (!S.getLangOptions().C99 &&
-            !S.getLangOptions().CPlusPlus0x)
-          S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
+        if (!S.getLangOpts().C99)
+          S.Diag(DS.getTypeSpecWidthLoc(),
+                 S.getLangOpts().CPlusPlus0x ?
+                   diag::warn_cxx98_compat_longlong : diag::ext_longlong);
         break;
       }
     }
     break;
   }
+  case DeclSpec::TST_int128:
+    if (DS.getTypeSpecSign() =3D=3D DeclSpec::TSS_unsigned)
+      Result =3D Context.UnsignedInt128Ty;
+    else
+      Result =3D Context.Int128Ty;
+    break;
   case DeclSpec::TST_half: Result =3D Context.HalfTy; break;
   case DeclSpec::TST_float: Result =3D Context.FloatTy; break;
   case DeclSpec::TST_double:
@@ -719,7 +735,7 @@
     else
       Result =3D Context.DoubleTy;
=20
-    if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
+    if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
       S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
       declarator.setInvalidType(true);
     }
@@ -757,9 +773,6 @@
     ElaboratedTypeKeyword Keyword
       =3D ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
     Result =3D S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
-
-    if (D->isInvalidDecl())
-      declarator.setInvalidType(true);
     break;
   }
   case DeclSpec::TST_typename: {
@@ -875,7 +888,7 @@
=20
   // Handle complex types.
   if (DS.getTypeSpecComplex() =3D=3D DeclSpec::TSC_complex) {
-    if (S.getLangOptions().Freestanding)
+    if (S.getLangOpts().Freestanding)
       S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
     Result =3D Context.getComplexType(Result);
   } else if (DS.isTypeAltiVecVector()) {
@@ -967,6 +980,25 @@
       TypeQuals &=3D ~DeclSpec::TQ_volatile;
     }
=20
+    // C90 6.5.3 constraints: "The same type qualifier shall not appear mo=
re
+    // than once in the same specifier-list or qualifier-list, either dire=
ctly
+    // or via one or more typedefs."
+    if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus=20
+        && TypeQuals & Result.getCVRQualifiers()) {
+      if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
+        S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)=20
+          << "const";
+      }
+
+      if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified(=
)) {
+        S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)=20
+          << "volatile";
+      }
+
+      // C90 doesn't have restrict, so it doesn't force us to produce a wa=
rning
+      // in this case.
+    }
+
     Qualifiers Quals =3D Qualifiers::fromCVRMask(TypeQuals);
     Result =3D Context.getQualifiedType(Result, Quals);
   }
@@ -1049,12 +1081,14 @@
   } else if (type->isObjCARCImplicitlyUnretainedType()) {
     implicitLifetime =3D Qualifiers::OCL_ExplicitNone;
=20
-  // If we are in an unevaluated context, like sizeof, assume ExplicitNone=
 and
-  // don't give error.
+  // If we are in an unevaluated context, like sizeof, skip adding a
+  // qualification.
   } else if (S.ExprEvalContexts.back().Context =3D=3D Sema::Unevaluated) {
-    implicitLifetime =3D Qualifiers::OCL_ExplicitNone;
-
-  // If that failed, give an error and recover using __autoreleasing.
+    return type;
+
+  // If that failed, give an error and recover using __strong.  __strong
+  // is the option most likely to prevent spurious second-order diagnostic=
s,
+  // like when binding a reference to a field.
   } else {
     // These types can show up in private ivars in system headers, so
     // we need this to not be an error in those cases.  Instead we
@@ -1066,7 +1100,7 @@
     } else {
       S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isRefere=
nce;
     }
-    implicitLifetime =3D Qualifiers::OCL_Autoreleasing;
+    implicitLifetime =3D Qualifiers::OCL_Strong;
   }
   assert(implicitLifetime && "didn't infer any lifetime!");
=20
@@ -1100,7 +1134,7 @@
   assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
=20
   // In ARC, it is forbidden to build pointers to unqualified pointers.
-  if (getLangOptions().ObjCAutoRefCount)
+  if (getLangOpts().ObjCAutoRefCount)
     T =3D inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
=20
   // Build the pointer type.
@@ -1157,7 +1191,7 @@
   }
=20
   // In ARC, it is forbidden to build references to unqualified pointers.
-  if (getLangOptions().ObjCAutoRefCount)
+  if (getLangOpts().ObjCAutoRefCount)
     T =3D inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
=20
   // Handle restrict on references.
@@ -1168,23 +1202,12 @@
=20
 /// Check whether the specified array size makes the array type a VLA.  If=
 so,
 /// return true, if not, return the size of the array in SizeVal.
-static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S=
) {
-  // If the size is an ICE, it certainly isn't a VLA.
-  if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
-    return false;
-   =20
-  // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatab=
le
-  // value as an extension.
-  Expr::EvalResult Result;
-  if (S.LangOpts.GNUMode && ArraySize->Evaluate(Result, S.Context)) {
-    if (!Result.hasSideEffects() && Result.Val.isInt()) {
-      SizeVal =3D Result.Val.getInt();
-      S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
-      return false;
-    }
-  }
-
-  return true;
+static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal=
) {
+  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mo=
de
+  // (like gnu99, but not c99) accept any evaluatable value as an extensio=
n.
+  return S.VerifyIntegerConstantExpression(
+      ArraySize, &SizeVal, S.PDiag(), S.LangOpts.GNUMode,
+      S.PDiag(diag::ext_vla_folded_to_constant)).isInvalid();
 }
=20
=20
@@ -1210,7 +1233,7 @@
                               SourceRange Brackets, DeclarationName Entity=
) {
=20
   SourceLocation Loc =3D Brackets.getBegin();
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // C++ [dcl.array]p1:
     //   T is called the array element type; this type shall not be a refe=
rence
     //   type, the (possibly cv-qualified) type void, a function type or a=
n=20
@@ -1262,6 +1285,13 @@
     return QualType();
   }
=20
+  // Do placeholder conversions on the array size expression.
+  if (ArraySize && ArraySize->hasPlaceholderType()) {
+    ExprResult Result =3D CheckPlaceholderExpr(ArraySize);
+    if (Result.isInvalid()) return QualType();
+    ArraySize =3D Result.take();
+  }
+
   // Do lvalue-to-rvalue conversions on the array size expression.
   if (ArraySize && !ArraySize->isRValue()) {
     ExprResult Result =3D DefaultLvalueConversion(ArraySize);
@@ -1272,14 +1302,15 @@
   }
=20
   // C99 6.7.5.2p1: The size expression shall have integer type.
-  // TODO: in theory, if we were insane, we could allow contextual
-  // conversions to integer type here.
-  if (ArraySize && !ArraySize->isTypeDependent() &&
+  // C++11 allows contextual conversions to such types.
+  if (!getLangOpts().CPlusPlus0x &&
+      ArraySize && !ArraySize->isTypeDependent() &&
       !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
     Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
       << ArraySize->getType() << ArraySize->getSourceRange();
     return QualType();
   }
+
   llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
   if (!ArraySize) {
     if (ASM =3D=3D ArrayType::Star)
@@ -1288,11 +1319,19 @@
       T =3D Context.getIncompleteArrayType(T, ASM, Quals);
   } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()=
) {
     T =3D Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Bra=
ckets);
-  } else if (!T->isDependentType() && !T->isIncompleteType() &&
-             !T->isConstantSizeType()) {
+  } else if ((!T->isDependentType() && !T->isIncompleteType() &&
+              !T->isConstantSizeType()) ||
+             isArraySizeVLA(*this, ArraySize, ConstVal)) {
+    // Even in C++11, don't allow contextual conversions in the array bound
+    // of a VLA.
+    if (getLangOpts().CPlusPlus0x &&
+        !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
+      Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
+        << ArraySize->getType() << ArraySize->getSourceRange();
+      return QualType();
+    }
+
     // C99: an array with an element type that has a non-constant-size is =
a VLA.
-    T =3D Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
-  } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
     // C99: an array with a non-ICE size is a VLA.  We accept any expressi=
on
     // that we can fold to a non-zero positive value as an extension.
     T =3D Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
@@ -1315,6 +1354,13 @@
            isSFINAEContext()? diag::err_typecheck_zero_array_size
                             : diag::ext_typecheck_zero_array_size)
         << ArraySize->getSourceRange();
+
+      if (ASM =3D=3D ArrayType::Static) {
+        Diag(ArraySize->getLocStart(),
+             diag::warn_typecheck_zero_static_array_size)
+          << ArraySize->getSourceRange();
+        ASM =3D ArrayType::Normal;
+      }
     } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&=20
                !T->isIncompleteType()) {
       // Is the array too large?     =20
@@ -1329,7 +1375,7 @@
     T =3D Context.getConstantArrayType(T, ConstVal, ASM, Quals);
   }
   // If this is not C99, extwarn about VLA's and C99 array size modifiers.
-  if (!getLangOptions().C99) {
+  if (!getLangOpts().C99) {
     if (T->isVariableArrayType()) {
       // Prohibit the use of non-POD types in VLAs.
       QualType BaseT =3D Context.getBaseElementType(T);
@@ -1349,9 +1395,9 @@
       else
         Diag(Loc, diag::ext_vla);
     } else if (ASM !=3D ArrayType::Normal || Quals !=3D 0)
-      Diag(Loc,=20
-           getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
-                                     : diag::ext_c99_array_usage);
+      Diag(Loc,
+           getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
+                                     : diag::ext_c99_array_usage) << ASM;
   }
=20
   return T;
@@ -1412,6 +1458,8 @@
 ///
 /// \param Variadic Whether this is a variadic function type.
 ///
+/// \param HasTrailingReturn Whether this function has a trailing return t=
ype.
+///
 /// \param Quals The cvr-qualifiers to be applied to the function type.
 ///
 /// \param Loc The location of the entity whose type involves this
@@ -1426,7 +1474,8 @@
 QualType Sema::BuildFunctionType(QualType T,
                                  QualType *ParamTypes,
                                  unsigned NumParamTypes,
-                                 bool Variadic, unsigned Quals,
+                                 bool Variadic, bool HasTrailingReturn,
+                                 unsigned Quals,
                                  RefQualifierKind RefQualifier,
                                  SourceLocation Loc, DeclarationName Entit=
y,
                                  FunctionType::ExtInfo Info) {
@@ -1465,6 +1514,7 @@
=20
   FunctionProtoType::ExtProtoInfo EPI;
   EPI.Variadic =3D Variadic;
+  EPI.HasTrailingReturn =3D HasTrailingReturn;
   EPI.TypeQuals =3D Quals;
   EPI.RefQualifier =3D RefQualifier;
   EPI.ExtInfo =3D Info;
@@ -1476,7 +1526,6 @@
 ///
 /// \param T the type to which the member pointer refers.
 /// \param Class the class type into which the member pointer points.
-/// \param CVR Qualifiers applied to the member pointer type
 /// \param Loc the location where this type begins
 /// \param Entity the name of the entity that will have this member pointe=
r type
 ///
@@ -1764,18 +1813,19 @@
   if (D.getAttributes())
     distributeTypeAttrsFromDeclarator(state, T);
=20
-  // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed con=
text.
-  // In C++0x, a function declarator using 'auto' must have a trailing ret=
urn
+  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed con=
text.
+  // In C++11, a function declarator using 'auto' must have a trailing ret=
urn
   // type (this is checked later) and we can skip this. In other languages
   // using auto, we need to check regardless.
   if (D.getDeclSpec().getTypeSpecType() =3D=3D DeclSpec::TST_auto &&
-      (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())=
) {
+      (!SemaRef.getLangOpts().CPlusPlus0x || !D.isFunctionDeclarator())) {
     int Error =3D -1;
=20
     switch (D.getContext()) {
     case Declarator::KNRTypeListContext:
       llvm_unreachable("K&R type lists aren't allowed in C++");
-      break;
+    case Declarator::LambdaExprContext:
+      llvm_unreachable("Can't specify a type specifier in lambda grammar");
     case Declarator::ObjCParameterContext:
     case Declarator::ObjCResultContext:
     case Declarator::PrototypeContext:
@@ -1808,6 +1858,9 @@
     case Declarator::AliasTemplateContext:
       Error =3D 9; // Type alias
       break;
+    case Declarator::TrailingReturnContext:
+      Error =3D 10; // Function return type
+      break;
     case Declarator::TypeNameContext:
       Error =3D 11; // Generic
       break;
@@ -1826,11 +1879,11 @@
     if (D.isFunctionDeclarator())
       Error =3D 10;
=20
-    // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
+    // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
     // contains a trailing return type. That is only legal at the outermost
     // level. Check all declarator chunks (outermost first) anyway, to give
     // better diagnostics.
-    if (SemaRef.getLangOptions().CPlusPlus0x && Error !=3D -1) {
+    if (SemaRef.getLangOpts().CPlusPlus0x && Error !=3D -1) {
       for (unsigned i =3D 0, e =3D D.getNumTypeObjects(); i !=3D e; ++i) {
         unsigned chunkIndex =3D e - i - 1;
         state.setCurrentChunkIndex(chunkIndex);
@@ -1851,20 +1904,28 @@
         << Error;
       T =3D SemaRef.Context.IntTy;
       D.setInvalidType(true);
-    }
+    } else
+      SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
+                   diag::warn_cxx98_compat_auto_type_specifier);
   }
=20
-  if (SemaRef.getLangOptions().CPlusPlus &&
+  if (SemaRef.getLangOpts().CPlusPlus &&
       OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
     // Check the contexts where C++ forbids the declaration of a new class
     // or enumeration in a type-specifier-seq.
     switch (D.getContext()) {
+    case Declarator::TrailingReturnContext:
+      // Class and enumeration definitions are syntactically not allowed in
+      // trailing return types.
+      llvm_unreachable("parser should not have allowed this");
+      break;
     case Declarator::FileContext:
     case Declarator::MemberContext:
     case Declarator::BlockContext:
     case Declarator::ForContext:
     case Declarator::BlockLiteralContext:
-      // C++0x [dcl.type]p3:
+    case Declarator::LambdaExprContext:
+      // C++11 [dcl.type]p3:
       //   A type-specifier-seq shall not define a class or enumeration un=
less
       //   it appears in the type-id of an alias-declaration (7.1.3) that =
is not
       //   the declaration of a template-declaration.
@@ -1908,6 +1969,66 @@
   return T;
 }
=20
+static std::string getFunctionQualifiersAsString(const FunctionProtoType *=
FnTy){
+  std::string Quals =3D
+    Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
+
+  switch (FnTy->getRefQualifier()) {
+  case RQ_None:
+    break;
+
+  case RQ_LValue:
+    if (!Quals.empty())
+      Quals +=3D ' ';
+    Quals +=3D '&';
+    break;
+
+  case RQ_RValue:
+    if (!Quals.empty())
+      Quals +=3D ' ';
+    Quals +=3D "&&";
+    break;
+  }
+
+  return Quals;
+}
+
+/// Check that the function type T, which has a cv-qualifier or a ref-qual=
ifier,
+/// can be contained within the declarator chunk DeclType, and produce an
+/// appropriate diagnostic if not.
+static void checkQualifiedFunction(Sema &S, QualType T,
+                                   DeclaratorChunk &DeclType) {
+  // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
+  // cv-qualifier or a ref-qualifier can only appear at the topmost level
+  // of a type.
+  int DiagKind =3D -1;
+  switch (DeclType.Kind) {
+  case DeclaratorChunk::Paren:
+  case DeclaratorChunk::MemberPointer:
+    // These cases are permitted.
+    return;
+  case DeclaratorChunk::Array:
+  case DeclaratorChunk::Function:
+    // These cases don't allow function types at all; no need to diagnose =
the
+    // qualifiers separately.
+    return;
+  case DeclaratorChunk::BlockPointer:
+    DiagKind =3D 0;
+    break;
+  case DeclaratorChunk::Pointer:
+    DiagKind =3D 1;
+    break;
+  case DeclaratorChunk::Reference:
+    DiagKind =3D 2;
+    break;
+  }
+
+  assert(DiagKind !=3D -1);
+  S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
+    << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
+    << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
+}
+
 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
                                                 QualType declSpecType,
                                                 TypeSourceInfo *TInfo) {
@@ -1916,7 +2037,7 @@
   Declarator &D =3D state.getDeclarator();
   Sema &S =3D state.getSema();
   ASTContext &Context =3D S.Context;
-  const LangOptions &LangOpts =3D S.getLangOptions();
+  const LangOptions &LangOpts =3D S.getLangOpts();
=20
   bool ImplicitlyNoexcept =3D false;
   if (D.getName().getKind() =3D=3D UnqualifiedId::IK_OperatorFunctionId &&
@@ -1939,6 +2060,11 @@
     D.getContext() =3D=3D Declarator::AliasDeclContext ||
     D.getContext() =3D=3D Declarator::AliasTemplateContext;
=20
+  // Does T refer to a function type with a cv-qualifier or a ref-qualifie=
r?
+  bool IsQualifiedFunction =3D T->isFunctionProtoType() &&
+      (T->castAs<FunctionProtoType>()->getTypeQuals() !=3D 0 ||
+       T->castAs<FunctionProtoType>()->getRefQualifier() !=3D RQ_None);
+
   // Walk the DeclTypeInfo, building the recursive type as we go.
   // DeclTypeInfos are ordered from the identifier out, which is
   // opposite of what we want :).
@@ -1946,8 +2072,11 @@
     unsigned chunkIndex =3D e - i - 1;
     state.setCurrentChunkIndex(chunkIndex);
     DeclaratorChunk &DeclType =3D D.getTypeObject(chunkIndex);
+    if (IsQualifiedFunction) {
+      checkQualifiedFunction(S, T, DeclType);
+      IsQualifiedFunction =3D DeclType.Kind =3D=3D DeclaratorChunk::Paren;
+    }
     switch (DeclType.Kind) {
-    default: llvm_unreachable("Unknown decltype!");
     case DeclaratorChunk::Paren:
       T =3D S.BuildParenType(T);
       break;
@@ -2019,8 +2148,7 @@
         ASM =3D ArrayType::Normal;
         D.setInvalidType(true);
       }
-      T =3D S.BuildArrayType(T, ASM, ArraySize,
-                           Qualifiers::fromCVRMask(ATI.TypeQuals),
+      T =3D S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
                            SourceRange(DeclType.Loc, DeclType.EndLoc), Nam=
e);
       break;
     }
@@ -2029,6 +2157,7 @@
       // does not have a K&R-style identifier list), then the arguments ar=
e part
       // of the type, otherwise the argument list is ().
       const DeclaratorChunk::FunctionTypeInfo &FTI =3D DeclType.Fun;
+      IsQualifiedFunction =3D FTI.TypeQuals || FTI.hasRefQualifier();
=20
       // Check for auto functions and trailing return type and adjust the
       // return type accordingly.
@@ -2048,7 +2177,8 @@
                  diag::err_trailing_return_in_parens)
               << T << D.getDeclSpec().getSourceRange();
             D.setInvalidType(true);
-          } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
+          } else if (D.getContext() !=3D Declarator::LambdaExprContext &&
+                     (T.hasQualifiers() || !isa<AutoType>(T))) {
             S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
                  diag::err_trailing_return_without_auto)
               << T << D.getDeclSpec().getSourceRange();
@@ -2160,6 +2290,7 @@
=20
         FunctionProtoType::ExtProtoInfo EPI;
         EPI.Variadic =3D FTI.isVariadic;
+        EPI.HasTrailingReturn =3D FTI.TrailingReturnType;
         EPI.TypeQuals =3D FTI.TypeQuals;
         EPI.RefQualifier =3D !FTI.hasRefQualifier()? RQ_None
                     : FTI.RefQualifierIsLValueRef? RQ_LValue
@@ -2260,15 +2391,11 @@
                     NoexceptExpr->getType()->getCanonicalTypeUnqualified()=
 =3D=3D
                         Context.BoolTy) &&
                  "Parser should have made sure that the expression is bool=
ean");
-            SourceLocation ErrLoc;
-            llvm::APSInt Dummy;
-            if (!NoexceptExpr->isValueDependent() &&
-                !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrL=
oc,
-                                                     /*evaluated*/false))
-              S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
-                  << NoexceptExpr->getSourceRange();
-            else
-              EPI.NoexceptExpr =3D NoexceptExpr;
+            if (!NoexceptExpr->isValueDependent())
+              NoexceptExpr =3D S.VerifyIntegerConstantExpression(NoexceptE=
xpr, 0,
+                S.PDiag(diag::err_noexcept_needs_constant_expression),
+                /*AllowFold*/ false).take();
+            EPI.NoexceptExpr =3D NoexceptExpr;
           }
         } else if (FTI.getExceptionSpecType() =3D=3D EST_None &&
                    ImplicitlyNoexcept && chunkIndex =3D=3D 0) {
@@ -2303,7 +2430,6 @@
         case NestedNameSpecifier::NamespaceAlias:
         case NestedNameSpecifier::Global:
           llvm_unreachable("Nested-name-specifier must name a type");
-          break;
=20
         case NestedNameSpecifier::TypeSpec:
         case NestedNameSpecifier::TypeSpecWithTemplate:
@@ -2360,7 +2486,8 @@
     // top-level template type arguments.
     bool FreeFunction;
     if (!D.getCXXScopeSpec().isSet()) {
-      FreeFunction =3D (D.getContext() !=3D Declarator::MemberContext ||
+      FreeFunction =3D ((D.getContext() !=3D Declarator::MemberContext &&
+                       D.getContext() !=3D Declarator::LambdaExprContext) =
||
                       D.getDeclSpec().isFriendSpecified());
     } else {
       DeclContext *DC =3D S.computeDeclContext(D.getCXXScopeSpec());
@@ -2370,6 +2497,7 @@
     // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static mem=
ber
     // function that is not a constructor declares that function to be con=
st.
     if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
+        D.getDeclSpec().getStorageClassSpec() !=3D DeclSpec::SCS_static &&
         D.getName().getKind() !=3D UnqualifiedId::IK_ConstructorName &&
         D.getName().getKind() !=3D UnqualifiedId::IK_ConstructorTemplateId=
 &&
         !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
@@ -2381,86 +2509,57 @@
                                   FnTy->getNumArgs(), EPI);
     }
=20
-    // C++0x [dcl.fct]p6:
-    //   A ref-qualifier shall only be part of the function type for a
-    //   non-static member function, the function type to which a pointer =
to
-    //   member refers, or the top-level function type of a function typed=
ef=20
-    //   declaration.
-    if ((FnTy->getTypeQuals() !=3D 0 || FnTy->getRefQualifier()) &&
-        !(D.getContext() =3D=3D Declarator::TemplateTypeArgContext &&
-          !D.isFunctionDeclarator()) && !IsTypedefName &&
-        (FreeFunction ||
-         D.getDeclSpec().getStorageClassSpec() =3D=3D DeclSpec::SCS_static=
)) {
-      if (D.getContext() =3D=3D Declarator::TemplateTypeArgContext) {
-        // Accept qualified function types as template type arguments as a=
 GNU
-        // extension. This is also the subject of C++ core issue 547.
-        std::string Quals;
-        if (FnTy->getTypeQuals() !=3D 0)
-          Quals =3D Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsStr=
ing();
-       =20
-        switch (FnTy->getRefQualifier()) {
-        case RQ_None:
-          break;
-           =20
-        case RQ_LValue:
-          if (!Quals.empty())
-            Quals +=3D ' ';
-          Quals +=3D '&';
-          break;
-         =20
-        case RQ_RValue:
-          if (!Quals.empty())
-            Quals +=3D ' ';
-          Quals +=3D "&&";
-          break;
+    // C++11 [dcl.fct]p6 (w/DR1417):
+    // An attempt to specify a function type with a cv-qualifier-seq or a
+    // ref-qualifier (including by typedef-name) is ill-formed unless it i=
s:
+    //  - the function type for a non-static member function,
+    //  - the function type to which a pointer to member refers,
+    //  - the top-level function type of a function typedef declaration or
+    //    alias-declaration,
+    //  - the type-id in the default argument of a type-parameter, or
+    //  - the type-id of a template-argument for a type-parameter
+    if (IsQualifiedFunction &&
+        !(!FreeFunction &&
+          D.getDeclSpec().getStorageClassSpec() !=3D DeclSpec::SCS_static)=
 &&
+        !IsTypedefName &&
+        D.getContext() !=3D Declarator::TemplateTypeArgContext) {
+      SourceLocation Loc =3D D.getLocStart();
+      SourceRange RemovalRange;
+      unsigned I;
+      if (D.isFunctionDeclarator(I)) {
+        SmallVector<SourceLocation, 4> RemovalLocs;
+        const DeclaratorChunk &Chunk =3D D.getTypeObject(I);
+        assert(Chunk.Kind =3D=3D DeclaratorChunk::Function);
+        if (Chunk.Fun.hasRefQualifier())
+          RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
+        if (Chunk.Fun.TypeQuals & Qualifiers::Const)
+          RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
+        if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
+          RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
+        // FIXME: We do not track the location of the __restrict qualifier.
+        //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
+        //  RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
+        if (!RemovalLocs.empty()) {
+          std::sort(RemovalLocs.begin(), RemovalLocs.end(),
+                    SourceManager::LocBeforeThanCompare(S.getSourceManager=
()));
+          RemovalRange =3D SourceRange(RemovalLocs.front(), RemovalLocs.ba=
ck());
+          Loc =3D RemovalLocs.front();
         }
-       =20
-        S.Diag(D.getIdentifierLoc(),=20
-             diag::ext_qualified_function_type_template_arg)
-          << Quals;
-      } else {
-        if (FnTy->getTypeQuals() !=3D 0) {
-          if (D.isFunctionDeclarator())
-            S.Diag(D.getIdentifierLoc(),=20
-                 diag::err_invalid_qualified_function_type);
-          else
-            S.Diag(D.getIdentifierLoc(),
-                 diag::err_invalid_qualified_typedef_function_type_use)
-              << FreeFunction;
-        }
-         =20
-        if (FnTy->getRefQualifier()) {
-          if (D.isFunctionDeclarator()) {
-            SourceLocation Loc =3D D.getIdentifierLoc();
-            for (unsigned I =3D 0, N =3D D.getNumTypeObjects(); I !=3D N; =
++I) {
-              const DeclaratorChunk &Chunk =3D D.getTypeObject(N-I-1);
-              if (Chunk.Kind =3D=3D DeclaratorChunk::Function &&
-                  Chunk.Fun.hasRefQualifier()) {
-                Loc =3D Chunk.Fun.getRefQualifierLoc();
-                break;
-              }
-            }
-
-            S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
-              << (FnTy->getRefQualifier() =3D=3D RQ_LValue)
-              << FixItHint::CreateRemoval(Loc);
-          } else {
-            S.Diag(D.getIdentifierLoc(),=20
-                 diag::err_invalid_ref_qualifier_typedef_function_type_use)
-              << FreeFunction
-              << (FnTy->getRefQualifier() =3D=3D RQ_LValue);
-          }
-        }
-         =20
-        // Strip the cv-qualifiers and ref-qualifiers from the type.
-        FunctionProtoType::ExtProtoInfo EPI =3D FnTy->getExtProtoInfo();
-        EPI.TypeQuals =3D 0;
-        EPI.RefQualifier =3D RQ_None;
-         =20
-        T =3D Context.getFunctionType(FnTy->getResultType(),=20
-                                    FnTy->arg_type_begin(),
-                                    FnTy->getNumArgs(), EPI);
       }
+
+      S.Diag(Loc, diag::err_invalid_qualified_function_type)
+        << FreeFunction << D.isFunctionDeclarator() << T
+        << getFunctionQualifiersAsString(FnTy)
+        << FixItHint::CreateRemoval(RemovalRange);
+
+      // Strip the cv-qualifiers and ref-qualifiers from the type.
+      FunctionProtoType::ExtProtoInfo EPI =3D FnTy->getExtProtoInfo();
+      EPI.TypeQuals =3D 0;
+      EPI.RefQualifier =3D RQ_None;
+
+      T =3D Context.getFunctionType(FnTy->getResultType(),=20
+                                  FnTy->arg_type_begin(),
+                                  FnTy->getNumArgs(), EPI);
     }
   }
=20
@@ -2540,6 +2639,8 @@
     case Declarator::CXXCatchContext:
     case Declarator::ObjCCatchContext:
     case Declarator::BlockLiteralContext:
+    case Declarator::LambdaExprContext:
+    case Declarator::TrailingReturnContext:
     case Declarator::TemplateTypeArgContext:
       // FIXME: We may want to allow parameter packs in block-literal cont=
exts
       // in the future.
@@ -2573,7 +2674,7 @@
   if (T.isNull())
     return Context.getNullTypeSourceInfo();
=20
-  if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
+  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
     inferARCWriteback(state, T);
  =20
   return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
@@ -2605,7 +2706,7 @@
=20
   const char *attrStr =3D 0;
   switch (ownership) {
-  case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
+  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
   case Qualifiers::OCL_ExplicitNone: attrStr =3D "none"; break;
   case Qualifiers::OCL_Strong: attrStr =3D "strong"; break;
   case Qualifiers::OCL_Weak: attrStr =3D "weak"; break;
@@ -2625,6 +2726,7 @@
   // TODO: mark whether we did this inference?
 }
=20
+/// \brief Used for transfering ownership in casts resulting in l-values.
 static void transferARCOwnership(TypeProcessingState &state,
                                  QualType &declSpecTy,
                                  Qualifiers::ObjCLifetime ownership) {
@@ -2632,6 +2734,7 @@
   Declarator &D =3D state.getDeclarator();
=20
   int inner =3D -1;
+  bool hasIndirection =3D false;
   for (unsigned i =3D 0, e =3D D.getNumTypeObjects(); i !=3D e; ++i) {
     DeclaratorChunk &chunk =3D D.getTypeObject(i);
     switch (chunk.Kind) {
@@ -2642,11 +2745,15 @@
     case DeclaratorChunk::Array:
     case DeclaratorChunk::Reference:
     case DeclaratorChunk::Pointer:
+      if (inner !=3D -1)
+        hasIndirection =3D true;
       inner =3D i;
       break;
=20
     case DeclaratorChunk::BlockPointer:
-      return transferARCOwnershipToDeclaratorChunk(state, ownership, i);
+      if (inner !=3D -1)
+        transferARCOwnershipToDeclaratorChunk(state, ownership, i);
+      return;
=20
     case DeclaratorChunk::Function:
     case DeclaratorChunk::MemberPointer:
@@ -2655,13 +2762,13 @@
   }
=20
   if (inner =3D=3D -1)
-    return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
+    return;
=20
   DeclaratorChunk &chunk =3D D.getTypeObject(inner);=20
   if (chunk.Kind =3D=3D DeclaratorChunk::Pointer) {
     if (declSpecTy->isObjCRetainableType())
       return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
-    if (declSpecTy->isObjCObjectType())
+    if (declSpecTy->isObjCObjectType() && hasIndirection)
       return transferARCOwnershipToDeclaratorChunk(state, ownership, inner=
);
   } else {
     assert(chunk.Kind =3D=3D DeclaratorChunk::Array ||
@@ -2678,7 +2785,7 @@
   if (declSpecTy.isNull())
     return Context.getNullTypeSourceInfo();
=20
-  if (getLangOptions().ObjCAutoRefCount) {
+  if (getLangOpts().ObjCAutoRefCount) {
     Qualifiers::ObjCLifetime ownership =3D Context.getInnerObjCOwnership(F=
romTy);
     if (ownership !=3D Qualifiers::OCL_None)
       transferARCOwnership(state, declSpecTy, ownership);
@@ -2720,7 +2827,6 @@
     return AttributeList::AT_pcs;
   }
   llvm_unreachable("unexpected attribute kind!");
-  return AttributeList::Kind();
 }
=20
 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
@@ -2866,51 +2972,28 @@
           return;
         }
       }
-      TL.setKeywordLoc(Keyword !=3D ETK_None
-                       ? DS.getTypeSpecTypeLoc()
-                       : SourceLocation());
+      TL.setElaboratedKeywordLoc(Keyword !=3D ETK_None
+                                 ? DS.getTypeSpecTypeLoc()
+                                 : SourceLocation());
       const CXXScopeSpec& SS =3D DS.getTypeSpecScope();
       TL.setQualifierLoc(SS.getWithLocInContext(Context));
       Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
     }
     void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
-      ElaboratedTypeKeyword Keyword
-        =3D TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
-      if (DS.getTypeSpecType() =3D=3D TST_typename) {
-        TypeSourceInfo *TInfo =3D 0;
-        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
-        if (TInfo) {
-          TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
-          return;
-        }
-      }
-      TL.setKeywordLoc(Keyword !=3D ETK_None
-                       ? DS.getTypeSpecTypeLoc()
-                       : SourceLocation());
-      const CXXScopeSpec& SS =3D DS.getTypeSpecScope();
-      TL.setQualifierLoc(SS.getWithLocInContext(Context));
-      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
+      assert(DS.getTypeSpecType() =3D=3D TST_typename);
+      TypeSourceInfo *TInfo =3D 0;
+      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
+      assert(TInfo);
+      TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
     }
     void VisitDependentTemplateSpecializationTypeLoc(
                                  DependentTemplateSpecializationTypeLoc TL=
) {
-      ElaboratedTypeKeyword Keyword
-        =3D TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
-      if (Keyword =3D=3D ETK_Typename) {
-        TypeSourceInfo *TInfo =3D 0;
-        Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
-        if (TInfo) {
-          TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
-                    TInfo->getTypeLoc()));
-          return;
-        }
-      }
-      TL.initializeLocal(Context, SourceLocation());
-      TL.setKeywordLoc(Keyword !=3D ETK_None
-                       ? DS.getTypeSpecTypeLoc()
-                       : SourceLocation());
-      const CXXScopeSpec& SS =3D DS.getTypeSpecScope();
-      TL.setQualifierLoc(SS.getWithLocInContext(Context));
-      TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
+      assert(DS.getTypeSpecType() =3D=3D TST_typename);
+      TypeSourceInfo *TInfo =3D 0;
+      Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
+      assert(TInfo);
+      TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
+                TInfo->getTypeLoc()));
     }
     void VisitTagTypeLoc(TagTypeLoc TL) {
       TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
@@ -2972,7 +3055,7 @@
         assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
         {
           DependentNameTypeLoc DNTLoc =3D cast<DependentNameTypeLoc>(ClsTL=
);
-          DNTLoc.setKeywordLoc(SourceLocation());
+          DNTLoc.setElaboratedKeywordLoc(SourceLocation());
           DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
           DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
         }
@@ -2982,7 +3065,7 @@
       case NestedNameSpecifier::TypeSpecWithTemplate:
         if (isa<ElaboratedType>(ClsTy)) {
           ElaboratedTypeLoc ETLoc =3D *cast<ElaboratedTypeLoc>(&ClsTL);
-          ETLoc.setKeywordLoc(SourceLocation());
+          ETLoc.setElaboratedKeywordLoc(SourceLocation());
           ETLoc.setQualifierLoc(NNSLoc.getPrefix());
           TypeLoc NamedTL =3D ETLoc.getNamedTypeLoc();
           NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
@@ -2995,7 +3078,6 @@
       case NestedNameSpecifier::NamespaceAlias:
       case NestedNameSpecifier::Global:
         llvm_unreachable("Nested-name-specifier must name a type");
-        break;
       }
=20
       // Finally fill in MemberPointerLocInfo fields.
@@ -3124,7 +3206,7 @@
   if (D.getContext() !=3D Declarator::ObjCParameterContext)
     checkUnusedDeclAttributes(D);
=20
-  if (getLangOptions().CPlusPlus) {
+  if (getLangOpts().CPlusPlus) {
     // Check that there are no default arguments (C++ only).
     CheckExtraCXXDefaultArguments(D);
   }
@@ -3205,6 +3287,36 @@
   Type =3D S.Context.getAddrSpaceQualType(Type, ASIdx);
 }
=20
+/// Does this type have a "direct" ownership qualifier?  That is,
+/// is it written like "__strong id", as opposed to something like
+/// "typeof(foo)", where that happens to be strong?
+static bool hasDirectOwnershipQualifier(QualType type) {
+  // Fast path: no qualifier at all.
+  assert(type.getQualifiers().hasObjCLifetime());
+
+  while (true) {
+    // __strong id
+    if (const AttributedType *attr =3D dyn_cast<AttributedType>(type)) {
+      if (attr->getAttrKind() =3D=3D AttributedType::attr_objc_ownership)
+        return true;
+
+      type =3D attr->getModifiedType();
+
+    // X *__strong (...)
+    } else if (const ParenType *paren =3D dyn_cast<ParenType>(type)) {
+      type =3D paren->getInnerType();
+  =20
+    // That's it for things we want to complain about.  In particular,
+    // we do not want to look through typedefs, typeof(expr),
+    // typeof(type), or any other way that the type is somehow
+    // abstracted.
+    } else {
+     =20
+      return false;
+    }
+  }
+}
+
 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
 /// attribute on the specified type.
 ///
@@ -3212,20 +3324,27 @@
 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
                                        AttributeList &attr,
                                        QualType &type) {
-  if (!type->isObjCRetainableType() && !type->isDependentType())
-    return false;
+  bool NonObjCPointer =3D false;
+
+  if (!type->isDependentType()) {
+    if (const PointerType *ptr =3D type->getAs<PointerType>()) {
+      QualType pointee =3D ptr->getPointeeType();
+      if (pointee->isObjCRetainableType() || pointee->isPointerType())
+        return false;
+      // It is important not to lose the source info that there was an att=
ribute
+      // applied to non-objc pointer. We will create an attributed type but
+      // its type will be the same as the original type.
+      NonObjCPointer =3D true;
+    } else if (!type->isObjCRetainableType()) {
+      return false;
+    }
+  }
=20
   Sema &S =3D state.getSema();
   SourceLocation AttrLoc =3D attr.getLoc();
   if (AttrLoc.isMacroID())
     AttrLoc =3D S.getSourceManager().getImmediateExpansionRange(AttrLoc).f=
irst;
=20
-  if (type.getQualifiers().getObjCLifetime()) {
-    S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
-      << type;
-    return true;
-  }
-
   if (!attr.getParameterName()) {
     S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
       << "objc_ownership" << 1;
@@ -3233,6 +3352,11 @@
     return true;
   }
=20
+  // Consume lifetime attributes without further comment outside of
+  // ARC mode.
+  if (!S.getLangOpts().ObjCAutoRefCount)
+    return true;
+
   Qualifiers::ObjCLifetime lifetime;
   if (attr.getParameterName()->isStr("none"))
     lifetime =3D Qualifiers::OCL_ExplicitNone;
@@ -3249,15 +3373,49 @@
     return true;
   }
=20
-  // Consume lifetime attributes without further comment outside of
-  // ARC mode.
-  if (!S.getLangOptions().ObjCAutoRefCount)
-    return true;
-
-  Qualifiers qs;
-  qs.setObjCLifetime(lifetime);
+  SplitQualType underlyingType =3D type.split();
+
+  // Check for redundant/conflicting ownership qualifiers.
+  if (Qualifiers::ObjCLifetime previousLifetime
+        =3D type.getQualifiers().getObjCLifetime()) {
+    // If it's written directly, that's an error.
+    if (hasDirectOwnershipQualifier(type)) {
+      S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
+        << type;
+      return true;
+    }
+
+    // Otherwise, if the qualifiers actually conflict, pull sugar off
+    // until we reach a type that is directly qualified.
+    if (previousLifetime !=3D lifetime) {
+      // This should always terminate: the canonical type is
+      // qualified, so some bit of sugar must be hiding it.
+      while (!underlyingType.Quals.hasObjCLifetime()) {
+        underlyingType =3D underlyingType.getSingleStepDesugaredType();
+      }
+      underlyingType.Quals.removeObjCLifetime();
+    }
+  }
+
+  underlyingType.Quals.addObjCLifetime(lifetime);
+
+  if (NonObjCPointer) {
+    StringRef name =3D attr.getName()->getName();
+    switch (lifetime) {
+    case Qualifiers::OCL_None:
+    case Qualifiers::OCL_ExplicitNone:
+      break;
+    case Qualifiers::OCL_Strong: name =3D "__strong"; break;
+    case Qualifiers::OCL_Weak: name =3D "__weak"; break;
+    case Qualifiers::OCL_Autoreleasing: name =3D "__autoreleasing"; break;
+    }
+    S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
+      << name << type;
+  }
+
   QualType origType =3D type;
-  type =3D S.Context.getQualifiedType(type, qs);
+  if (!NonObjCPointer)
+    type =3D S.Context.getQualifiedType(underlyingType);
=20
   // If we have a valid source location for the attribute, use an
   // AttributedType instead.
@@ -3267,7 +3425,7 @@
=20
   // Forbid __weak if the runtime doesn't support it.
   if (lifetime =3D=3D Qualifiers::OCL_Weak &&
-      !S.getLangOptions().ObjCRuntimeHasWeak) {
+      !S.getLangOpts().ObjCRuntimeHasWeak && !NonObjCPointer) {
=20
     // Actually, delay this until we know what we're parsing.
     if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
@@ -3438,9 +3596,9 @@
       SplitQualType SplitOld =3D Old.split();
=20
       // As a special case, tail-recurse if there are no qualifiers.
-      if (SplitOld.second.empty())
-        return wrap(C, SplitOld.first, I);
-      return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.secon=
d);
+      if (SplitOld.Quals.empty())
+        return wrap(C, SplitOld.Ty, I);
+      return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
     }
=20
     QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
@@ -3484,7 +3642,6 @@
       }
=20
       llvm_unreachable("unknown wrapping kind");
-      return QualType();
     }
   };
 }
@@ -3515,7 +3672,7 @@
   // ns_returns_retained is not always a type attribute, but if we got
   // here, we're treating it as one right now.
   if (attr.getKind() =3D=3D AttributeList::AT_ns_returns_retained) {
-    assert(S.getLangOptions().ObjCAutoRefCount &&
+    assert(S.getLangOpts().ObjCAutoRefCount &&
            "ns_returns_retained treated as type attribute in non-ARC");
     if (attr.getNumArgs()) return true;
=20
@@ -3712,11 +3869,12 @@
   // Special case where the argument is a template id.
   if (Attr.getParameterName()) {
     CXXScopeSpec SS;
+    SourceLocation TemplateKWLoc;
     UnqualifiedId id;
     id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
-   =20
-    ExprResult Size =3D S.ActOnIdExpression(S.getCurScope(), SS, id, false=
,=20
-                                          false);
+
+    ExprResult Size =3D S.ActOnIdExpression(S.getCurScope(), SS, TemplateK=
WLoc,
+                                          id, false, false);
     if (Size.isInvalid())
       return;
    =20
@@ -3857,7 +4015,7 @@
       break;
=20
     case AttributeList::AT_ns_returns_retained:
-      if (!state.getSema().getLangOptions().ObjCAutoRefCount)
+      if (!state.getSema().getLangOpts().ObjCAutoRefCount)
 	break;
       // fallthrough into the function attrs
=20
@@ -3988,9 +4146,52 @@
   //         "Can't ask whether a dependent type is complete");
=20
   // If we have a complete type, we're done.
-  if (!T->isIncompleteType())
+  NamedDecl *Def =3D 0;
+  if (!T->isIncompleteType(&Def)) {
+    // If we know about the definition but it is not visible, complain.
+    if (diag !=3D 0 && Def && !LookupResult::isVisible(Def)) {
+      // Suppress this error outside of a SFINAE context if we've already
+      // emitted the error once for this type. There's no usefulness in=20
+      // repeating the diagnostic.
+      // FIXME: Add a Fix-It that imports the corresponding module or incl=
udes
+      // the header.
+      if (isSFINAEContext() || HiddenDefinitions.insert(Def)) {
+        Diag(Loc, diag::err_module_private_definition) << T;
+        Diag(Def->getLocation(), diag::note_previous_definition);
+      }
+    }
+   =20
     return false;
-
+  }
+
+  const TagType *Tag =3D T->getAs<TagType>();
+  const ObjCInterfaceType *IFace =3D 0;
+ =20
+  if (Tag) {
+    // Avoid diagnosing invalid decls as incomplete.
+    if (Tag->getDecl()->isInvalidDecl())
+      return true;
+
+    // Give the external AST source a chance to complete the type.
+    if (Tag->getDecl()->hasExternalLexicalStorage()) {
+      Context.getExternalSource()->CompleteType(Tag->getDecl());
+      if (!Tag->isIncompleteType())
+        return false;
+    }
+  }
+  else if ((IFace =3D T->getAs<ObjCInterfaceType>())) {
+    // Avoid diagnosing invalid decls as incomplete.
+    if (IFace->getDecl()->isInvalidDecl())
+      return true;
+   =20
+    // Give the external AST source a chance to complete the type.
+    if (IFace->getDecl()->hasExternalLexicalStorage()) {
+      Context.getExternalSource()->CompleteType(IFace->getDecl());
+      if (!IFace->isIncompleteType())
+        return false;
+    }
+  }
+   =20
   // If we have a class template specialization or a class member of a
   // class template specialization, or an array with known size of such,
   // try to instantiate it.
@@ -4006,12 +4207,12 @@
                                                       /*Complain=3D*/diag =
!=3D 0);
     } else if (CXXRecordDecl *Rec
                  =3D dyn_cast<CXXRecordDecl>(Record->getDecl())) {
-      if (CXXRecordDecl *Pattern =3D Rec->getInstantiatedFromMemberClass()=
) {
-        MemberSpecializationInfo *MSInfo =3D Rec->getMemberSpecializationI=
nfo();
-        assert(MSInfo && "Missing member specialization information?");
+      CXXRecordDecl *Pattern =3D Rec->getInstantiatedFromMemberClass();
+      if (!Rec->isBeingDefined() && Pattern) {
+        MemberSpecializationInfo *MSI =3D Rec->getMemberSpecializationInfo=
();
+        assert(MSI && "Missing member specialization information?");
         // This record was instantiated from a class within a template.
-        if (MSInfo->getTemplateSpecializationKind()=20
-                                               !=3D TSK_ExplicitSpecializa=
tion)
+        if (MSI->getTemplateSpecializationKind() !=3D TSK_ExplicitSpeciali=
zation)
           return InstantiateClass(Loc, Rec, Pattern,
                                   getTemplateInstantiationArgs(Rec),
                                   TSK_ImplicitInstantiation,
@@ -4022,23 +4223,10 @@
=20
   if (diag =3D=3D 0)
     return true;
-
-  const TagType *Tag =3D T->getAs<TagType>();
-
-  // Avoid diagnosing invalid decls as incomplete.
-  if (Tag && Tag->getDecl()->isInvalidDecl())
-    return true;
-
-  // Give the external AST source a chance to complete the type.
-  if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
-    Context.getExternalSource()->CompleteType(Tag->getDecl());
-    if (!Tag->isIncompleteType())
-      return false;
-  }
-
+   =20
   // We have an incomplete type. Produce a diagnostic.
   Diag(Loc, PD) << T;
-
+   =20
   // If we have a note, produce it.
   if (!Note.first.isInvalid())
     Diag(Note.first, Note.second);
@@ -4049,7 +4237,11 @@
     Diag(Tag->getDecl()->getLocation(),
          Tag->isBeingDefined() ? diag::note_type_being_defined
                                : diag::note_forward_declaration)
-        << QualType(Tag, 0);
+      << QualType(Tag, 0);
+ =20
+  // If the Objective-C class was a forward declaration, produce a note.
+  if (IFace && !IFace->getDecl()->isInvalidDecl())
+    Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
=20
   return true;
 }
@@ -4083,18 +4275,16 @@
 /// @param PD The partial diagnostic that will be printed out if T is not a
 /// literal type.
 ///
-/// @param AllowIncompleteType If true, an incomplete type will be conside=
red
-/// acceptable.
-///
 /// @returns @c true if @p T is not a literal type and a diagnostic was em=
itted,
 /// @c false otherwise.
 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
-                              const PartialDiagnostic &PD,
-                              bool AllowIncompleteType) {
+                              const PartialDiagnostic &PD) {
   assert(!T->isDependentType() && "type should not be dependent");
=20
-  bool Incomplete =3D RequireCompleteType(Loc, T, 0);
-  if (T->isLiteralType() || (AllowIncompleteType && Incomplete))
+  QualType ElemType =3D Context.getBaseElementType(T);
+  RequireCompleteType(Loc, ElemType, 0);
+
+  if (T->isLiteralType())
     return false;
=20
   if (PD.getDiagID() =3D=3D 0)
@@ -4105,50 +4295,35 @@
   if (T->isVariableArrayType())
     return true;
=20
-  const RecordType *RT =3D T->getBaseElementTypeUnsafe()->getAs<RecordType=
>();
+  const RecordType *RT =3D ElemType->getAs<RecordType>();
   if (!RT)
     return true;
=20
   const CXXRecordDecl *RD =3D cast<CXXRecordDecl>(RT->getDecl());
=20
+  // FIXME: Better diagnostic for incomplete class?
+  if (!RD->isCompleteDefinition())
+    return true;
+
   // If the class has virtual base classes, then it's not an aggregate, and
-  // cannot have any constexpr constructors, so is non-literal. This is be=
tter
-  // to diagnose than the resulting absence of constexpr constructors.
+  // cannot have any constexpr constructors or a trivial default construct=
or,
+  // so is non-literal. This is better to diagnose than the resulting abse=
nce
+  // of constexpr constructors.
   if (RD->getNumVBases()) {
     Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
       << RD->isStruct() << RD->getNumVBases();
     for (CXXRecordDecl::base_class_const_iterator I =3D RD->vbases_begin(),
            E =3D RD->vbases_end(); I !=3D E; ++I)
-      Diag(I->getSourceRange().getBegin(),
+      Diag(I->getLocStart(),
            diag::note_constexpr_virtual_base_here) << I->getSourceRange();
-  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor=
()) {
+  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor=
() &&
+             !RD->hasTrivialDefaultConstructor()) {
     Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << =
RD;
-
-    switch (RD->getTemplateSpecializationKind()) {
-    case TSK_Undeclared:
-    case TSK_ExplicitSpecialization:
-      break;
-
-    case TSK_ImplicitInstantiation:
-    case TSK_ExplicitInstantiationDeclaration:
-    case TSK_ExplicitInstantiationDefinition:
-      // If the base template had constexpr constructors which were
-      // instantiated as non-constexpr constructors, explain why.
-      for (CXXRecordDecl::ctor_iterator I =3D RD->ctor_begin(),
-           E =3D RD->ctor_end(); I !=3D E; ++I) {
-        if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor())
-          continue;
-
-        FunctionDecl *Base =3D (*I)->getInstantiatedFromMemberFunction();
-        if (Base && Base->isConstexpr())
-          CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation=
);
-      }
-    }
   } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
     for (CXXRecordDecl::base_class_const_iterator I =3D RD->bases_begin(),
          E =3D RD->bases_end(); I !=3D E; ++I) {
       if (!I->getType()->isLiteralType()) {
-        Diag(I->getSourceRange().getBegin(),
+        Diag(I->getLocStart(),
              diag::note_non_literal_base_class)
           << RD << I->getType() << I->getSourceRange();
         return true;
@@ -4156,12 +4331,11 @@
     }
     for (CXXRecordDecl::field_iterator I =3D RD->field_begin(),
          E =3D RD->field_end(); I !=3D E; ++I) {
-      if (!(*I)->getType()->isLiteralType()) {
+      if (!(*I)->getType()->isLiteralType() ||
+          (*I)->getType().isVolatileQualified()) {
         Diag((*I)->getLocation(), diag::note_non_literal_field)
-          << RD << (*I) << (*I)->getType();
-        return true;
-      } else if ((*I)->isMutable()) {
-        Diag((*I)->getLocation(), diag::note_non_literal_mutable_field) <<=
 RD;
+          << RD << (*I) << (*I)->getType()
+          << (*I)->getType().isVolatileQualified();
         return true;
       }
     }
@@ -4211,12 +4385,73 @@
   return Context.getTypeOfExprType(E);
 }
=20
+/// getDecltypeForExpr - Given an expr, will return the decltype for
+/// that expression, according to the rules in C++11
+/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
+static QualType getDecltypeForExpr(Sema &S, Expr *E) {
+  if (E->isTypeDependent())
+    return S.Context.DependentTy;
+
+  // C++11 [dcl.type.simple]p4:
+  //   The type denoted by decltype(e) is defined as follows:
+  //
+  //     - if e is an unparenthesized id-expression or an unparenthesized =
class
+  //       member access (5.2.5), decltype(e) is the type of the entity na=
med=20
+  //       by e. If there is no such entity, or if e names a set of overlo=
aded=20
+  //       functions, the program is ill-formed;
+  if (const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E)) {
+    if (const ValueDecl *VD =3D dyn_cast<ValueDecl>(DRE->getDecl()))
+      return VD->getType();
+  }
+  if (const MemberExpr *ME =3D dyn_cast<MemberExpr>(E)) {
+    if (const FieldDecl *FD =3D dyn_cast<FieldDecl>(ME->getMemberDecl()))
+      return FD->getType();
+  }
+ =20
+  // C++11 [expr.lambda.prim]p18:
+  //   Every occurrence of decltype((x)) where x is a possibly
+  //   parenthesized id-expression that names an entity of automatic
+  //   storage duration is treated as if x were transformed into an
+  //   access to a corresponding data member of the closure type that
+  //   would have been declared if x were an odr-use of the denoted
+  //   entity.
+  using namespace sema;
+  if (S.getCurLambda()) {
+    if (isa<ParenExpr>(E)) {
+      if (DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
+        if (VarDecl *Var =3D dyn_cast<VarDecl>(DRE->getDecl())) {
+          QualType T =3D S.getCapturedDeclRefType(Var, DRE->getLocation());
+          if (!T.isNull())
+            return S.Context.getLValueReferenceType(T);
+        }
+      }
+    }
+  }
+
+
+  // C++11 [dcl.type.simple]p4:
+  //   [...]
+  QualType T =3D E->getType();
+  switch (E->getValueKind()) {
+  //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is th=
e=20
+  //       type of e;
+  case VK_XValue: T =3D S.Context.getRValueReferenceType(T); break;
+  //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the=20
+  //       type of e;
+  case VK_LValue: T =3D S.Context.getLValueReferenceType(T); break;
+  //  - otherwise, decltype(e) is the type of e.
+  case VK_RValue: break;
+  }
+ =20
+  return T;
+}
+
 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
   ExprResult ER =3D CheckPlaceholderExpr(E);
   if (ER.isInvalid()) return QualType();
   E =3D ER.take();
  =20
-  return Context.getDecltypeType(E);
+  return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
 }
=20
 QualType Sema::BuildUnaryTransformType(QualType BaseType,
@@ -4245,12 +4480,14 @@
=20
 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
   if (!T->isDependentType()) {
+    // FIXME: It isn't entirely clear whether incomplete atomic types
+    // are allowed or not; for simplicity, ban them for the moment.
+    if (RequireCompleteType(Loc, T,
+                            PDiag(diag::err_atomic_specifier_bad_type) << =
0))
+      return QualType();
+
     int DisallowedKind =3D -1;
-    if (T->isIncompleteType())
-      // FIXME: It isn't entirely clear whether incomplete atomic types
-      // are allowed or not; for simplicity, ban them for the moment.
-      DisallowedKind =3D 0;
-    else if (T->isArrayType())
+    if (T->isArrayType())
       DisallowedKind =3D 1;
     else if (T->isFunctionType())
       DisallowedKind =3D 2;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/TargetAttributesSema.cpp
--- a/head/contrib/llvm/tools/clang/lib/Sema/TargetAttributesSema.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/TargetAttributesSema.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -169,7 +169,7 @@
     // Apparently Visual C++ thinks it is okay to not emit a warning
     // in this case, so only emit a warning when -fms-extensions is not
     // specified.
-    if (!S.getLangOptions().MicrosoftExt)
+    if (!S.getLangOpts().MicrosoftExt)
       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
         << Attr.getName() << 2 /*variable and function*/;
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Sema=
/TreeTransform.h
--- a/head/contrib/llvm/tools/clang/lib/Sema/TreeTransform.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Sema/TreeTransform.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -112,6 +112,11 @@
 protected:
   Sema &SemaRef;
  =20
+  /// \brief The set of local declarations that have been transformed, for
+  /// cases where we are forced to build new declarations within the trans=
former
+  /// rather than in the subclass (e.g., lambda closure types).
+  llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
+ =20
 public:
   /// \brief Initializes a new tree transformer.
   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
@@ -351,10 +356,36 @@
   /// \brief Transform the given declaration, which is referenced from a t=
ype
   /// or expression.
   ///
-  /// By default, acts as the identity function on declarations. Subclasses
+  /// By default, acts as the identity function on declarations, unless the
+  /// transformer has had to transform the declaration itself. Subclasses
   /// may override this function to provide alternate behavior.
-  Decl *TransformDecl(SourceLocation Loc, Decl *D) { return D; }
-
+  Decl *TransformDecl(SourceLocation Loc, Decl *D) {=20
+    llvm::DenseMap<Decl *, Decl *>::iterator Known
+      =3D TransformedLocalDecls.find(D);
+    if (Known !=3D TransformedLocalDecls.end())
+      return Known->second;
+   =20
+    return D;=20
+  }
+
+  /// \brief Transform the attributes associated with the given declaratio=
n and=20
+  /// place them on the new declaration.
+  ///
+  /// By default, this operation does nothing. Subclasses may override this
+  /// behavior to transform attributes.
+  void transformAttrs(Decl *Old, Decl *New) { }
+ =20
+  /// \brief Note that a local declaration has been transformed by this
+  /// transformer.
+  ///
+  /// Local declarations are typically transformed via a call to=20
+  /// TransformDefinition. However, in some cases (e.g., lambda expression=
s),
+  /// the transformer itself has to transform the declarations. This routi=
ne
+  /// can be overridden by a subclass that keeps track of such mappings.
+  void transformedLocalDecl(Decl *Old, Decl *New) {
+    TransformedLocalDecls[Old] =3D New;
+  }
+ =20
   /// \brief Transform the definition of the given declaration.
   ///
   /// By default, invokes TransformDecl() to transform the declaration.
@@ -418,7 +449,7 @@
   /// Subclasses may override this function to provide alternate behavior.
   TemplateName TransformTemplateName(CXXScopeSpec &SS,
                                      TemplateName Name,
-                                     SourceLocation NameLoc,              =
                      =20
+                                     SourceLocation NameLoc,
                                      QualType ObjectType =3D QualType(),
                                      NamedDecl *FirstQualifierInScope =3D =
0);
=20
@@ -530,7 +561,8 @@
   ///   scope index;  can be negative
   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
                                           int indexAdjustment,
-                                        llvm::Optional<unsigned> NumExpans=
ions);
+                                        llvm::Optional<unsigned> NumExpans=
ions,
+                                          bool ExpectParameterPack);
=20
   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL=
);
=20
@@ -665,7 +697,8 @@
   QualType RebuildFunctionProtoType(QualType T,
                                     QualType *ParamTypes,
                                     unsigned NumParamTypes,
-                                    bool Variadic, unsigned Quals,
+                                    bool Variadic, bool HasTrailingReturn,
+                                    unsigned Quals,
                                     RefQualifierKind RefQualifier,
                                     const FunctionType::ExtInfo &Info);
=20
@@ -845,7 +878,6 @@
       case LookupResult::FoundOverloaded:
       case LookupResult::FoundUnresolvedValue:
         llvm_unreachable("Tag lookup cannot find non-tags");
-        return QualType();
        =20
       case LookupResult::Ambiguous:
         // Let the LookupResult structure handle ambiguities.
@@ -1291,7 +1323,20 @@
     return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEn=
d,
                                           Cond, Inc, LoopVar, RParenLoc);
   }
- =20
+
+  /// \brief Build a new C++0x range-based for statement.
+  ///
+  /// By default, performs semantic analysis to build the new statement.
+  /// Subclasses may override this routine to provide different behavior.
+  StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,=20
+                                          bool IsIfExists,
+                                          NestedNameSpecifierLoc Qualifier=
Loc,
+                                          DeclarationNameInfo NameInfo,
+                                          Stmt *Nested) {
+    return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
+                                                QualifierLoc, NameInfo, Ne=
sted);
+  }
+
   /// \brief Attach body to a C++0x range-based for statement.
   ///
   /// By default, performs semantic analysis to finish the new statement.
@@ -1450,11 +1495,14 @@
   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
                                bool isArrow,
                                NestedNameSpecifierLoc QualifierLoc,
+                               SourceLocation TemplateKWLoc,
                                const DeclarationNameInfo &MemberNameInfo,
                                ValueDecl *Member,
                                NamedDecl *FoundDecl,
                         const TemplateArgumentListInfo *ExplicitTemplateAr=
gs,
                                NamedDecl *FirstQualifierInScope) {
+    ExprResult BaseResult =3D getSema().PerformMemberExprBaseConversion(Ba=
se,
+                                                                      isAr=
row);
     if (!Member->getDeclName()) {
       // We have a reference to an unnamed field.  This is always the
       // base of an anonymous struct/union member access, i.e. the
@@ -1463,8 +1511,8 @@
       assert(Member->getType()->isRecordType() &&
              "unnamed member not of record type?");
=20
-      ExprResult BaseResult =3D
-        getSema().PerformObjectMemberConversion(Base,=20
+      BaseResult =3D
+        getSema().PerformObjectMemberConversion(BaseResult.take(),
                                                 QualifierLoc.getNestedName=
Specifier(),
                                                 FoundDecl, Member);
       if (BaseResult.isInvalid())
@@ -1482,9 +1530,6 @@
     CXXScopeSpec SS;
     SS.Adopt(QualifierLoc);
=20
-    ExprResult BaseResult =3D getSema().DefaultFunctionArrayConversion(Bas=
e);
-    if (BaseResult.isInvalid())
-      return ExprError();
     Base =3D BaseResult.take();
     QualType BaseType =3D Base->getType();
=20
@@ -1495,7 +1540,8 @@
     R.resolveKind();
=20
     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArr=
ow,
-                                              SS, FirstQualifierInScope,
+                                              SS, TemplateKWLoc,
+                                              FirstQualifierInScope,
                                               R, ExplicitTemplateArgs);
   }
=20
@@ -1559,7 +1605,8 @@
     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
                                               OpLoc, /*IsArrow*/ false,
-                                              SS, /*FirstQualifierInScope*=
/ 0,
+                                              SS, SourceLocation(),
+                                              /*FirstQualifierInScope*/ 0,
                                               NameInfo,
                                               /* TemplateArgs */ 0);
   }
@@ -1629,10 +1676,9 @@
   /// By default, performs semantic analysis to build the new expression.
   /// Subclasses may override this routine to provide different behavior.
   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
-                                        MultiExprArg SubExprs,
-                                        SourceLocation RParenLoc) {
-    return getSema().ActOnParenOrParenListExpr(LParenLoc, RParenLoc,=20
-                                               move(SubExprs));
+                                  MultiExprArg SubExprs,
+                                  SourceLocation RParenLoc) {
+    return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, move(SubExpr=
s));
   }
=20
   /// \brief Build a new address-of-label expression.
@@ -1736,8 +1782,6 @@
     default:
       llvm_unreachable("Invalid C++ named cast");
     }
-
-    return ExprError();
   }
=20
   /// \brief Build a new C++ static_cast expression.
@@ -1878,6 +1922,7 @@
   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
                                 QualType ThisType,
                                 bool isImplicit) {
+    getSema().CheckCXXThisCapture(ThisLoc);
     return getSema().Owned(
                       new (getSema().Context) CXXThisExpr(ThisLoc, ThisTyp=
e,
                                                           isImplicit));
@@ -1928,9 +1973,8 @@
                                QualType AllocatedType,
                                TypeSourceInfo *AllocatedTypeInfo,
                                Expr *ArraySize,
-                               SourceLocation ConstructorLParen,
-                               MultiExprArg ConstructorArgs,
-                               SourceLocation ConstructorRParen) {
+                               SourceRange DirectInitRange,
+                               Expr *Initializer) {
     return getSema().BuildCXXNew(StartLoc, UseGlobal,
                                  PlacementLParen,
                                  move(PlacementArgs),
@@ -1939,9 +1983,8 @@
                                  AllocatedType,
                                  AllocatedTypeInfo,
                                  ArraySize,
-                                 ConstructorLParen,
-                                 move(ConstructorArgs),
-                                 ConstructorRParen);
+                                 DirectInitRange,
+                                 Initializer);
   }
=20
   /// \brief Build a new C++ "delete" expression.
@@ -1979,6 +2022,17 @@
     return getSema().BuildBinaryTypeTrait(Trait, StartLoc, LhsT, RhsT, RPa=
renLoc);
   }
=20
+  /// \brief Build a new type trait expression.
+  ///
+  /// By default, performs semantic analysis to build the new expression.
+  /// Subclasses may override this routine to provide different behavior.
+  ExprResult RebuildTypeTrait(TypeTrait Trait,
+                              SourceLocation StartLoc,
+                              ArrayRef<TypeSourceInfo *> Args,
+                              SourceLocation RParenLoc) {
+    return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
+  }
+ =20
   /// \brief Build a new array type trait expression.
   ///
   /// By default, performs semantic analysis to build the new expression.
@@ -2009,14 +2063,15 @@
   /// Subclasses may override this routine to provide different behavior.
   ExprResult RebuildDependentScopeDeclRefExpr(
                                           NestedNameSpecifierLoc Qualifier=
Loc,
+                                          SourceLocation TemplateKWLoc,
                                        const DeclarationNameInfo &NameInfo,
                               const TemplateArgumentListInfo *TemplateArgs=
) {
     CXXScopeSpec SS;
     SS.Adopt(QualifierLoc);
=20
-    if (TemplateArgs)
-      return getSema().BuildQualifiedTemplateIdExpr(SS, NameInfo,
-                                                    *TemplateArgs);
+    if (TemplateArgs || TemplateKWLoc.isValid())
+      return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc,
+                                                    NameInfo, TemplateArgs=
);
=20
     return getSema().BuildQualifiedDeclarationNameExpr(SS, NameInfo);
   }
@@ -2026,10 +2081,12 @@
   /// By default, performs semantic analysis to build the new expression.
   /// Subclasses may override this routine to provide different behavior.
   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
-                                         LookupResult &R,
-                                         bool RequiresADL,
-                              const TemplateArgumentListInfo &TemplateArgs=
) {
-    return getSema().BuildTemplateIdExpr(SS, R, RequiresADL, TemplateArgs);
+                                   SourceLocation TemplateKWLoc,
+                                   LookupResult &R,
+                                   bool RequiresADL,
+                              const TemplateArgumentListInfo *TemplateArgs=
) {
+    return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
+                                         TemplateArgs);
   }
=20
   /// \brief Build a new object-construction expression.
@@ -2094,6 +2151,7 @@
                                                 bool IsArrow,
                                                 SourceLocation OperatorLoc,
                                           NestedNameSpecifierLoc Qualifier=
Loc,
+                                                SourceLocation TemplateKWL=
oc,
                                             NamedDecl *FirstQualifierInSco=
pe,
                                    const DeclarationNameInfo &MemberNameIn=
fo,
                               const TemplateArgumentListInfo *TemplateArgs=
) {
@@ -2102,7 +2160,8 @@
=20
     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
                                             OperatorLoc, IsArrow,
-                                            SS, FirstQualifierInScope,
+                                            SS, TemplateKWLoc,
+                                            FirstQualifierInScope,
                                             MemberNameInfo,
                                             TemplateArgs);
   }
@@ -2111,20 +2170,21 @@
   ///
   /// By default, performs semantic analysis to build the new expression.
   /// Subclasses may override this routine to provide different behavior.
-  ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE,
-                                               QualType BaseType,
-                                               SourceLocation OperatorLoc,
-                                               bool IsArrow,
-                                           NestedNameSpecifierLoc Qualifie=
rLoc,
-                                               NamedDecl *FirstQualifierIn=
Scope,
-                                               LookupResult &R,
+  ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
+                                         SourceLocation OperatorLoc,
+                                         bool IsArrow,
+                                         NestedNameSpecifierLoc QualifierL=
oc,
+                                         SourceLocation TemplateKWLoc,
+                                         NamedDecl *FirstQualifierInScope,
+                                         LookupResult &R,
                                 const TemplateArgumentListInfo *TemplateAr=
gs) {
     CXXScopeSpec SS;
     SS.Adopt(QualifierLoc);
=20
     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
                                             OperatorLoc, IsArrow,
-                                            SS, FirstQualifierInScope,
+                                            SS, TemplateKWLoc,
+                                            FirstQualifierInScope,
                                             R, TemplateArgs);
   }
=20
@@ -2150,7 +2210,35 @@
                                                 OperatorLoc, Pack, PackLoc=
,=20
                                                 RParenLoc);
   }
-                                  =20
+
+  /// \brief Build a new Objective-C array literal.
+  ///
+  /// By default, performs semantic analysis to build the new expression.
+  /// Subclasses may override this routine to provide different behavior.
+  ExprResult RebuildObjCArrayLiteral(SourceRange Range,
+                                     Expr **Elements, unsigned NumElements=
) {
+    return getSema().BuildObjCArrayLiteral(Range,=20
+                                           MultiExprArg(Elements, NumEleme=
nts));
+  }
+=20
+  ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,=20
+                                         Expr *Base, Expr *Key,
+                                         ObjCMethodDecl *getterMethod,
+                                         ObjCMethodDecl *setterMethod) {
+    return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
+                                                   getterMethod, setterMet=
hod);
+  }
+
+  /// \brief Build a new Objective-C dictionary literal.
+  ///
+  /// By default, performs semantic analysis to build the new expression.
+  /// Subclasses may override this routine to provide different behavior.
+  ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
+                                          ObjCDictionaryElement *Elements,
+                                          unsigned NumElements) {
+    return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElemen=
ts);
+  }
+ =20
   /// \brief Build a new Objective-C @encode expression.
   ///
   /// By default, performs semantic analysis to build the new expression.
@@ -2215,7 +2303,8 @@
       return move(Result);
    =20
     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getT=
ype(),
-                                              /*FIXME:*/IvarLoc, IsArrow, =
SS,=20
+                                              /*FIXME:*/IvarLoc, IsArrow,
+                                              SS, SourceLocation(),
                                               /*FirstQualifierInScope=3D*/=
0,
                                               R,=20
                                               /*TemplateArgs=3D*/0);
@@ -2226,8 +2315,8 @@
   /// By default, performs semantic analysis to build the new expression.
   /// Subclasses may override this routine to provide different behavior.
   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,=20
-                                              ObjCPropertyDecl *Property,
-                                              SourceLocation PropertyLoc) {
+                                        ObjCPropertyDecl *Property,
+                                        SourceLocation PropertyLoc) {
     CXXScopeSpec SS;
     ExprResult Base =3D getSema().Owned(BaseArg);
     LookupResult R(getSema(), Property->getDeclName(), PropertyLoc,
@@ -2244,7 +2333,7 @@
    =20
     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getT=
ype(),
                                               /*FIXME:*/PropertyLoc, IsArr=
ow,=20
-                                              SS,=20
+                                              SS, SourceLocation(),
                                               /*FirstQualifierInScope=3D*/=
0,
                                               R,=20
                                               /*TemplateArgs=3D*/0);
@@ -2286,7 +2375,8 @@
       return move(Result);
    =20
     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getT=
ype(),
-                                              /*FIXME:*/IsaLoc, IsArrow, S=
S,=20
+                                              /*FIXME:*/IsaLoc, IsArrow,
+                                              SS, SourceLocation(),
                                               /*FirstQualifierInScope=3D*/=
0,
                                               R,=20
                                               /*TemplateArgs=3D*/0);
@@ -2309,7 +2399,8 @@
     // Build a reference to the __builtin_shufflevector builtin
     FunctionDecl *Builtin =3D cast<FunctionDecl>(*Lookup.first);
     ExprResult Callee
-      =3D SemaRef.Owned(new (SemaRef.Context) DeclRefExpr(Builtin, Builtin=
->getType(),
+      =3D SemaRef.Owned(new (SemaRef.Context) DeclRefExpr(Builtin, false,
+                                                        Builtin->getType(),
                                                         VK_LValue, Builtin=
Loc));
     Callee =3D SemaRef.UsualUnaryConversions(Callee.take());
     if (Callee.isInvalid())
@@ -2625,10 +2716,13 @@
         return NestedNameSpecifierLoc();
      =20
       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() =
||
-          (SemaRef.getLangOptions().CPlusPlus0x &&=20
+          (SemaRef.getLangOpts().CPlusPlus0x &&=20
            TL.getType()->isEnumeralType())) {
         assert(!TL.getType().hasLocalQualifiers() &&=20
                "Can't get cv-qualifiers here");
+        if (TL.getType()->isEnumeralType())
+          SemaRef.Diag(TL.getBeginLoc(),
+                       diag::warn_cxx98_compat_enum_nested_name_spec);
         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
                   Q.getLocalEndLoc());
         break;
@@ -2797,7 +2891,6 @@
  =20
   // These should be getting filtered out before they reach the AST.
   llvm_unreachable("overloaded function decl survived to here");
-  return TemplateName();
 }
=20
 template<typename Derived>
@@ -2884,8 +2977,9 @@
     Expr *SourceExpr =3D Input.getSourceDeclExpression();
     if (SourceExpr) {
       EnterExpressionEvaluationContext Unevaluated(getSema(),
-                                                   Sema::Unevaluated);
+                                                   Sema::ConstantEvaluated=
);
       ExprResult E =3D getDerived().TransformExpr(SourceExpr);
+      E =3D SemaRef.ActOnConstantExpression(E);
       SourceExpr =3D (E.isInvalid() ? 0 : E.take());
     }
=20
@@ -2918,14 +3012,15 @@
     llvm_unreachable("Caller should expand pack expansions");
=20
   case TemplateArgument::Expression: {
-    // Template argument expressions are not potentially evaluated.
+    // Template argument expressions are constant expressions.
     EnterExpressionEvaluationContext Unevaluated(getSema(),
-                                                 Sema::Unevaluated);
+                                                 Sema::ConstantEvaluated);
=20
     Expr *InputExpr =3D Input.getSourceExpression();
     if (!InputExpr) InputExpr =3D Input.getArgument().getAsExpr();
=20
     ExprResult E =3D getDerived().TransformExpr(InputExpr);
+    E =3D SemaRef.ActOnConstantExpression(E);
     if (E.isInvalid()) return true;
     Output =3D TemplateArgumentLoc(TemplateArgument(E.take()), E.take());
     return false;
@@ -3168,6 +3263,9 @@
=20
 template<typename Derived>
 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
+  // Refine the base location to the type's location.
+  TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
+                       getDerived().getBaseEntity());
   if (getDerived().AlreadyTransformed(DI->getType()))
     return DI;
=20
@@ -3195,7 +3293,6 @@
   }
=20
   llvm_unreachable("unhandled type loc!");
-  return QualType();
 }
=20
 /// FIXME: By default, this routine adds type qualifiers only to types
@@ -3294,7 +3391,7 @@
     TemplateName Template
       =3D getDerived().RebuildTemplateName(SS,=20
                                          *SpecTL.getTypePtr()->getIdentifi=
er(),=20
-                                         SpecTL.getNameLoc(),
+                                         SpecTL.getTemplateNameLoc(),
                                          ObjectType, UnqualLookup);
     if (Template.isNull())
       return TypeLoc();
@@ -3351,7 +3448,7 @@
     TemplateName Template
       =3D getDerived().RebuildTemplateName(SS,=20
                                          *SpecTL.getTypePtr()->getIdentifi=
er(),=20
-                                         SpecTL.getNameLoc(),
+                                         SpecTL.getTemplateNameLoc(),
                                          ObjectType, UnqualLookup);
     if (Template.isNull())
       return 0;
@@ -3574,15 +3671,21 @@
     if (Result.isNull())
       return QualType();
   }
- =20
-  ConstantArrayTypeLoc NewTL =3D TLB.push<ConstantArrayTypeLoc>(Result);
+
+  // We might have either a ConstantArrayType or a VariableArrayType now:
+  // a ConstantArrayType is allowed to have an element type which is a
+  // VariableArrayType if the type is dependent.  Fortunately, all array
+  // types have the same location layout.
+  ArrayTypeLoc NewTL =3D TLB.push<ArrayTypeLoc>(Result);
   NewTL.setLBracketLoc(TL.getLBracketLoc());
   NewTL.setRBracketLoc(TL.getRBracketLoc());
=20
   Expr *Size =3D TL.getSizeExpr();
   if (Size) {
-    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluate=
d);
+    EnterExpressionEvaluationContext Unevaluated(SemaRef,
+                                                 Sema::ConstantEvaluated);
     Size =3D getDerived().TransformExpr(Size).template takeAs<Expr>();
+    Size =3D SemaRef.ActOnConstantExpression(Size).take();
   }
   NewTL.setSizeExpr(Size);
=20
@@ -3626,9 +3729,6 @@
   if (ElementType.isNull())
     return QualType();
=20
-  // Array bounds are not potentially evaluated contexts
-  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
-
   ExprResult SizeResult
     =3D getDerived().TransformExpr(T->getSizeExpr());
   if (SizeResult.isInvalid())
@@ -3666,8 +3766,9 @@
   if (ElementType.isNull())
     return QualType();
=20
-  // Array bounds are not potentially evaluated contexts
-  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
+  // Array bounds are constant expressions.
+  EnterExpressionEvaluationContext Unevaluated(SemaRef,
+                                               Sema::ConstantEvaluated);
=20
   // Prefer the expression from the TypeLoc;  the other may have been uniq=
ued.
   Expr *origSize =3D TL.getSizeExpr();
@@ -3675,6 +3776,7 @@
=20
   ExprResult sizeResult
     =3D getDerived().TransformExpr(origSize);
+  sizeResult =3D SemaRef.ActOnConstantExpression(sizeResult);
   if (sizeResult.isInvalid())
     return QualType();
=20
@@ -3714,10 +3816,12 @@
   if (ElementType.isNull())
     return QualType();
=20
-  // Vector sizes are not potentially evaluated contexts
-  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
+  // Vector sizes are constant expressions.
+  EnterExpressionEvaluationContext Unevaluated(SemaRef,
+                                               Sema::ConstantEvaluated);
=20
   ExprResult Size =3D getDerived().TransformExpr(T->getSizeExpr());
+  Size =3D SemaRef.ActOnConstantExpression(Size);
   if (Size.isInvalid())
     return QualType();
=20
@@ -3796,12 +3900,14 @@
 ParmVarDecl *
 TreeTransform<Derived>::TransformFunctionTypeParam(ParmVarDecl *OldParm,
                                                    int indexAdjustment,
-                                       llvm::Optional<unsigned> NumExpansi=
ons) {
+                                         llvm::Optional<unsigned> NumExpan=
sions,
+                                                   bool ExpectParameterPac=
k) {
   TypeSourceInfo *OldDI =3D OldParm->getTypeSourceInfo();
   TypeSourceInfo *NewDI =3D 0;
  =20
   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
     // If we're substituting into a pack expansion type and we know the=20
+    // length we want to expand to, just substitute for the pattern.
     TypeLoc OldTL =3D OldDI->getTypeLoc();
     PackExpansionTypeLoc OldExpansionTL =3D cast<PackExpansionTypeLoc>(Old=
TL);
    =20
@@ -3898,7 +4004,8 @@
             ParmVarDecl *NewParm=20
               =3D getDerived().TransformFunctionTypeParam(OldParm,
                                                         indexAdjustment++,
-                                                        OrigNumExpansions);
+                                                        OrigNumExpansions,
+                                                /*ExpectParameterPack=3D*/=
false);
             if (!NewParm)
               return true;
            =20
@@ -3914,7 +4021,8 @@
             ParmVarDecl *NewParm=20
               =3D getDerived().TransformFunctionTypeParam(OldParm,
                                                         indexAdjustment++,
-                                                        OrigNumExpansions);
+                                                        OrigNumExpansions,
+                                                /*ExpectParameterPack=3D*/=
false);
             if (!NewParm)
               return true;
            =20
@@ -3938,11 +4046,13 @@
         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
         NewParm =3D getDerived().TransformFunctionTypeParam(OldParm,
                                                           indexAdjustment,
-                                                          NumExpansions);
+                                                          NumExpansions,
+                                                  /*ExpectParameterPack=3D=
*/true);
       } else {
         NewParm =3D getDerived().TransformFunctionTypeParam(OldParm,
                                                           indexAdjustment,
-                                                  llvm::Optional<unsigned>=
());
+                                                          llvm::Optional<u=
nsigned>(),
+                                                /*ExpectParameterPack=3D*/=
false);
       }
=20
       if (!NewParm)
@@ -4096,6 +4206,7 @@
                                                    ParamTypes.data(),
                                                    ParamTypes.size(),
                                                    T->isVariadic(),
+                                                   T->hasTrailingReturn(),
                                                    T->getTypeQuals(),
                                                    T->getRefQualifier(),
                                                    T->getExtInfo());
@@ -4192,6 +4303,10 @@
   if (E.isInvalid())
     return QualType();
=20
+  E =3D SemaRef.HandleExprEvaluationContextForTypeof(E.get());
+  if (E.isInvalid())
+    return QualType();
+
   QualType Result =3D TL.getType();
   if (getDerived().AlwaysRebuild() ||
       E.get() !=3D TL.getUnderlyingExpr()) {
@@ -4239,12 +4354,17 @@
   const DecltypeType *T =3D TL.getTypePtr();
=20
   // decltype expressions are not potentially evaluated contexts
-  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
+  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,=
 0,
+                                               /*IsDecltype=3D*/ true);
=20
   ExprResult E =3D getDerived().TransformExpr(T->getUnderlyingExpr());
   if (E.isInvalid())
     return QualType();
=20
+  E =3D getSema().ActOnDecltypeExpression(E.take());
+  if (E.isInvalid())
+    return QualType();
+
   QualType Result =3D TL.getType();
   if (getDerived().AlwaysRebuild() ||
       E.get() !=3D T->getUnderlyingExpr()) {
@@ -4549,9 +4669,10 @@
     if (isa<DependentTemplateSpecializationType>(Result)) {
       DependentTemplateSpecializationTypeLoc NewTL
         =3D TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
-      NewTL.setKeywordLoc(TL.getTemplateNameLoc());
+      NewTL.setElaboratedKeywordLoc(SourceLocation());
       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
-      NewTL.setNameLoc(TL.getTemplateNameLoc());
+      NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
+      NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
       NewTL.setLAngleLoc(TL.getLAngleLoc());
       NewTL.setRAngleLoc(TL.getRAngleLoc());
       for (unsigned i =3D 0, e =3D NewTemplateArgs.size(); i !=3D e; ++i)
@@ -4561,6 +4682,7 @@
=20
     TemplateSpecializationTypeLoc NewTL
       =3D TLB.push<TemplateSpecializationTypeLoc>(Result);
+    NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
     NewTL.setLAngleLoc(TL.getLAngleLoc());
     NewTL.setRAngleLoc(TL.getRAngleLoc());
@@ -4599,10 +4721,10 @@
   =20
     DependentTemplateSpecializationTypeLoc NewTL
       =3D TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
-    NewTL.setKeywordLoc(TL.getKeywordLoc());
-   =20
+    NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
-    NewTL.setNameLoc(TL.getNameLoc());
+    NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
+    NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
     NewTL.setLAngleLoc(TL.getLAngleLoc());
     NewTL.setRAngleLoc(TL.getRAngleLoc());
     for (unsigned i =3D 0, e =3D NewTemplateArgs.size(); i !=3D e; ++i)
@@ -4612,14 +4734,15 @@
      =20
   QualType Result=20
     =3D getDerived().RebuildTemplateSpecializationType(Template,
-                                                     TL.getNameLoc(),
+                                                     TL.getTemplateNameLoc=
(),
                                                      NewTemplateArgs);
  =20
   if (!Result.isNull()) {
     /// FIXME: Wrap this in an elaborated-type-specifier?
     TemplateSpecializationTypeLoc NewTL
       =3D TLB.push<TemplateSpecializationTypeLoc>(Result);
-    NewTL.setTemplateNameLoc(TL.getNameLoc());
+    NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
+    NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
     NewTL.setLAngleLoc(TL.getLAngleLoc());
     NewTL.setRAngleLoc(TL.getRAngleLoc());
     for (unsigned i =3D 0, e =3D NewTemplateArgs.size(); i !=3D e; ++i)
@@ -4669,7 +4792,7 @@
   if (getDerived().AlwaysRebuild() ||
       QualifierLoc !=3D TL.getQualifierLoc() ||
       NamedT !=3D T->getNamedType()) {
-    Result =3D getDerived().RebuildElaboratedType(TL.getKeywordLoc(),
+    Result =3D getDerived().RebuildElaboratedType(TL.getElaboratedKeywordL=
oc(),
                                                 T->getKeyword(),=20
                                                 QualifierLoc, NamedT);
     if (Result.isNull())
@@ -4677,7 +4800,7 @@
   }
=20
   ElaboratedTypeLoc NewTL =3D TLB.push<ElaboratedTypeLoc>(Result);
-  NewTL.setKeywordLoc(TL.getKeywordLoc());
+  NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   NewTL.setQualifierLoc(QualifierLoc);
   return Result;
 }
@@ -4753,7 +4876,7 @@
=20
   QualType Result
     =3D getDerived().RebuildDependentNameType(T->getKeyword(),
-                                            TL.getKeywordLoc(),
+                                            TL.getElaboratedKeywordLoc(),
                                             QualifierLoc,
                                             T->getIdentifier(),
                                             TL.getNameLoc());
@@ -4765,11 +4888,11 @@
     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
=20
     ElaboratedTypeLoc NewTL =3D TLB.push<ElaboratedTypeLoc>(Result);
-    NewTL.setKeywordLoc(TL.getKeywordLoc());
+    NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
     NewTL.setQualifierLoc(QualifierLoc);
   } else {
     DependentNameTypeLoc NewTL =3D TLB.push<DependentNameTypeLoc>(Result);
-    NewTL.setKeywordLoc(TL.getKeywordLoc());
+    NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
     NewTL.setQualifierLoc(QualifierLoc);
     NewTL.setNameLoc(TL.getNameLoc());
   }
@@ -4814,7 +4937,7 @@
     =3D getDerived().RebuildDependentTemplateSpecializationType(T->getKeyw=
ord(),
                                                               QualifierLoc,
                                                             T->getIdentifi=
er(),
-                                                            TL.getNameLoc(=
),
+                                                       TL.getTemplateNameL=
oc(),
                                                             NewTemplateArg=
s);
   if (Result.isNull())
     return QualType();
@@ -4825,7 +4948,8 @@
     // Copy information relevant to the template specialization.
     TemplateSpecializationTypeLoc NamedTL
       =3D TLB.push<TemplateSpecializationTypeLoc>(NamedT);
-    NamedTL.setTemplateNameLoc(TL.getNameLoc());
+    NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
+    NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
     NamedTL.setLAngleLoc(TL.getLAngleLoc());
     NamedTL.setRAngleLoc(TL.getRAngleLoc());
     for (unsigned I =3D 0, E =3D NewTemplateArgs.size(); I !=3D E; ++I)
@@ -4833,14 +4957,15 @@
    =20
     // Copy information relevant to the elaborated type.
     ElaboratedTypeLoc NewTL =3D TLB.push<ElaboratedTypeLoc>(Result);
-    NewTL.setKeywordLoc(TL.getKeywordLoc());
+    NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
     NewTL.setQualifierLoc(QualifierLoc);
   } else if (isa<DependentTemplateSpecializationType>(Result)) {
     DependentTemplateSpecializationTypeLoc SpecTL
       =3D TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
-    SpecTL.setKeywordLoc(TL.getKeywordLoc());
+    SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
     SpecTL.setQualifierLoc(QualifierLoc);
-    SpecTL.setNameLoc(TL.getNameLoc());
+    SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
+    SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
     SpecTL.setLAngleLoc(TL.getLAngleLoc());
     SpecTL.setRAngleLoc(TL.getRAngleLoc());
     for (unsigned I =3D 0, E =3D NewTemplateArgs.size(); I !=3D E; ++I)
@@ -4848,7 +4973,8 @@
   } else {
     TemplateSpecializationTypeLoc SpecTL
       =3D TLB.push<TemplateSpecializationTypeLoc>(Result);
-    SpecTL.setTemplateNameLoc(TL.getNameLoc());
+    SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
+    SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
     SpecTL.setLAngleLoc(TL.getLAngleLoc());
     SpecTL.setRAngleLoc(TL.getRAngleLoc());
     for (unsigned I =3D 0, E =3D NewTemplateArgs.size(); I !=3D E; ++I)
@@ -4927,6 +5053,8 @@
 StmtResult
 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
                                               bool IsStmtExpr) {
+  Sema::CompoundScopeRAII CompoundScope(getSema());
+
   bool SubStmtInvalid =3D false;
   bool SubStmtChanged =3D false;
   ASTOwningVector<Stmt*> Statements(getSema());
@@ -4966,16 +5094,18 @@
 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
   ExprResult LHS, RHS;
   {
-    // The case value expressions are not potentially evaluated.
-    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluate=
d);
+    EnterExpressionEvaluationContext Unevaluated(SemaRef,
+                                                 Sema::ConstantEvaluated);
=20
     // Transform the left-hand case value.
     LHS =3D getDerived().TransformExpr(S->getLHS());
+    LHS =3D SemaRef.ActOnConstantExpression(LHS);
     if (LHS.isInvalid())
       return StmtError();
=20
     // Transform the right-hand case value (for the GNU case-range extensi=
on).
     RHS =3D getDerived().TransformExpr(S->getRHS());
+    RHS =3D SemaRef.ActOnConstantExpression(RHS);
     if (RHS.isInvalid())
       return StmtError();
   }
@@ -5284,6 +5414,7 @@
   ExprResult Target =3D getDerived().TransformExpr(S->getTarget());
   if (Target.isInvalid())
     return StmtError();
+  Target =3D SemaRef.MaybeCreateExprWithCleanups(Target.take());
=20
   if (!getDerived().AlwaysRebuild() &&
       Target.get() =3D=3D S->getTarget())
@@ -5696,10 +5827,18 @@
   ExprResult Cond =3D getDerived().TransformExpr(S->getCond());
   if (Cond.isInvalid())
     return StmtError();
+  if (Cond.get())
+    Cond =3D SemaRef.CheckBooleanCondition(Cond.take(), S->getColonLoc());
+  if (Cond.isInvalid())
+    return StmtError();
+  if (Cond.get())
+    Cond =3D SemaRef.MaybeCreateExprWithCleanups(Cond.take());
=20
   ExprResult Inc =3D getDerived().TransformExpr(S->getInc());
   if (Inc.isInvalid())
     return StmtError();
+  if (Inc.get())
+    Inc =3D SemaRef.MaybeCreateExprWithCleanups(Inc.take());
=20
   StmtResult LoopVar =3D getDerived().TransformStmt(S->getLoopVarStmt());
   if (LoopVar.isInvalid())
@@ -5739,6 +5878,75 @@
=20
 template<typename Derived>
 StmtResult
+TreeTransform<Derived>::TransformMSDependentExistsStmt(
+                                                    MSDependentExistsStmt =
*S) {
+  // Transform the nested-name-specifier, if any.
+  NestedNameSpecifierLoc QualifierLoc;
+  if (S->getQualifierLoc()) {
+    QualifierLoc=20
+      =3D getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc(=
));
+    if (!QualifierLoc)
+      return StmtError();
+  }
+
+  // Transform the declaration name.
+  DeclarationNameInfo NameInfo =3D S->getNameInfo();
+  if (NameInfo.getName()) {
+    NameInfo =3D getDerived().TransformDeclarationNameInfo(NameInfo);
+    if (!NameInfo.getName())
+      return StmtError();
+  }
+
+  // Check whether anything changed.
+  if (!getDerived().AlwaysRebuild() &&
+      QualifierLoc =3D=3D S->getQualifierLoc() &&
+      NameInfo.getName() =3D=3D S->getNameInfo().getName())
+    return S;
+ =20
+  // Determine whether this name exists, if we can.
+  CXXScopeSpec SS;
+  SS.Adopt(QualifierLoc);
+  bool Dependent =3D false;
+  switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=3D*/0, SS, NameInfo))=
 {
+  case Sema::IER_Exists:
+    if (S->isIfExists())
+      break;
+     =20
+    return new (getSema().Context) NullStmt(S->getKeywordLoc());
+
+  case Sema::IER_DoesNotExist:
+    if (S->isIfNotExists())
+      break;
+   =20
+    return new (getSema().Context) NullStmt(S->getKeywordLoc());
+     =20
+  case Sema::IER_Dependent:
+    Dependent =3D true;
+    break;
+     =20
+  case Sema::IER_Error:
+    return StmtError();
+  }
+ =20
+  // We need to continue with the instantiation, so do so now.
+  StmtResult SubStmt =3D getDerived().TransformCompoundStmt(S->getSubStmt(=
));
+  if (SubStmt.isInvalid())
+    return StmtError();
+ =20
+  // If we have resolved the name, just transform to the substatement.
+  if (!Dependent)
+    return SubStmt;
+ =20
+  // The name is still dependent, so build a dependent expression again.
+  return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
+                                                   S->isIfExists(),
+                                                   QualifierLoc,
+                                                   NameInfo,
+                                                   SubStmt.get());
+}
+
+template<typename Derived>
+StmtResult
 TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
   StmtResult TryBlock; //  =3D getDerived().TransformCompoundStmt(S->getTr=
yBlock());
   if(TryBlock.isInvalid()) return StmtError();
@@ -5829,7 +6037,7 @@
=20
     // Mark it referenced in the new context regardless.
     // FIXME: this is a bit instantiation-specific.
-    SemaRef.MarkDeclarationReferenced(E->getLocation(), ND);
+    SemaRef.MarkDeclRefReferenced(E);
=20
     return SemaRef.Owned(E);
   }
@@ -5881,6 +6089,12 @@
=20
 template<typename Derived>
 ExprResult
+TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E)=
 {
+  return SemaRef.MaybeBindToTemporary(E);
+}
+
+template<typename Derived>
+ExprResult
 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr=
 *E) {
   ExprResult ControllingExpr =3D
     getDerived().TransformExpr(E->getControllingExpr());
@@ -6020,6 +6234,28 @@
=20
 template<typename Derived>
 ExprResult
+TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
+  // Rebuild the syntactic form.  The original syntactic form has
+  // opaque-value expressions in it, so strip those away and rebuild
+  // the result.  This is a really awful way of doing this, but the
+  // better solution (rebuilding the semantic expressions and
+  // rebinding OVEs as necessary) doesn't work; we'd need
+  // TreeTransform to not strip away implicit conversions.
+  Expr *newSyntacticForm =3D SemaRef.recreateSyntacticForm(E);
+  ExprResult result =3D getDerived().TransformExpr(newSyntacticForm);
+  if (result.isInvalid()) return ExprError();
+
+  // If that gives us a pseudo-object result back, the pseudo-object
+  // expression must have been an lvalue-to-rvalue conversion which we
+  // should reapply.
+  if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
+    result =3D SemaRef.checkPseudoObjectRValue(result.take());
+
+  return result;
+}
+
+template<typename Derived>
+ExprResult
 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
                                                 UnaryExprOrTypeTraitExpr *=
E) {
   if (E->isArgumentType()) {
@@ -6037,20 +6273,17 @@
                                                     E->getSourceRange());
   }
=20
-  ExprResult SubExpr;
-  {
-    // C++0x [expr.sizeof]p1:
-    //   The operand is either an expression, which is an unevaluated oper=
and
-    //   [...]
-    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluate=
d);
-
-    SubExpr =3D getDerived().TransformExpr(E->getArgumentExpr());
-    if (SubExpr.isInvalid())
-      return ExprError();
-
-    if (!getDerived().AlwaysRebuild() && SubExpr.get() =3D=3D E->getArgume=
ntExpr())
-      return SemaRef.Owned(E);
-  }
+  // C++0x [expr.sizeof]p1:
+  //   The operand is either an expression, which is an unevaluated operand
+  //   [...]
+  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
+
+  ExprResult SubExpr =3D getDerived().TransformExpr(E->getArgumentExpr());
+  if (SubExpr.isInvalid())
+    return ExprError();
+
+  if (!getDerived().AlwaysRebuild() && SubExpr.get() =3D=3D E->getArgument=
Expr())
+    return SemaRef.Owned(E);
=20
   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
                                                   E->getOperatorLoc(),
@@ -6099,7 +6332,7 @@
   if (!getDerived().AlwaysRebuild() &&
       Callee.get() =3D=3D E->getCallee() &&
       !ArgChanged)
-    return SemaRef.Owned(E);
+    return SemaRef.MaybeBindToTemporary(E);;
=20
   // FIXME: Wrong source location information for the '('.
   SourceLocation FakeLParenLoc
@@ -6124,6 +6357,7 @@
     if (!QualifierLoc)
       return ExprError();
   }
+  SourceLocation TemplateKWLoc =3D E->getTemplateKeywordLoc();
=20
   ValueDecl *Member
     =3D cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc=
(),
@@ -6150,7 +6384,8 @@
    =20
     // Mark it referenced in the new context regardless.
     // FIXME: this is a bit instantiation-specific.
-    SemaRef.MarkDeclarationReferenced(E->getMemberLoc(), Member);
+    SemaRef.MarkMemberReferenced(E);
+
     return SemaRef.Owned(E);
   }
=20
@@ -6177,6 +6412,7 @@
   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
                                         E->isArrow(),
                                         QualifierLoc,
+                                        TemplateKWLoc,
                                         E->getMemberNameInfo(),
                                         Member,
                                         FoundDecl,
@@ -6312,7 +6548,7 @@
   if (!getDerived().AlwaysRebuild() &&
       OldT =3D=3D NewT &&
       Init.get() =3D=3D E->getInitializer())
-    return SemaRef.Owned(E);
+    return SemaRef.MaybeBindToTemporary(E);
=20
   // Note: the expression type doesn't necessarily match the
   // type-as-written, but that's okay, because it should always be
@@ -6500,14 +6736,20 @@
 template<typename Derived>
 ExprResult=20
 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
+  SemaRef.ActOnStartStmtExpr();
   StmtResult SubStmt
     =3D getDerived().TransformCompoundStmt(E->getSubStmt(), true);
-  if (SubStmt.isInvalid())
+  if (SubStmt.isInvalid()) {
+    SemaRef.ActOnStmtExprError();
     return ExprError();
+  }
=20
   if (!getDerived().AlwaysRebuild() &&
-      SubStmt.get() =3D=3D E->getSubStmt())
-    return SemaRef.Owned(E);
+      SubStmt.get() =3D=3D E->getSubStmt()) {
+    // Calling this an 'error' is unintuitive, but it does the right thing.
+    SemaRef.ActOnStmtExprError();
+    return SemaRef.MaybeBindToTemporary(E);
+  }
=20
   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
                                       SubStmt.get(),
@@ -6555,7 +6797,6 @@
   case OO_Array_New:
   case OO_Array_Delete:
     llvm_unreachable("new and delete operators cannot use CXXOperatorCallE=
xpr");
-    return ExprError();
    =20
   case OO_Call: {
     // This is a call to an object's operator().
@@ -6592,12 +6833,10 @@
=20
   case OO_Conditional:
     llvm_unreachable("conditional operator is not actually overloadable");
-    return ExprError();
=20
   case OO_None:
   case NUM_OVERLOADED_OPERATORS:
     llvm_unreachable("not an overloaded operator?");
-    return ExprError();
   }
=20
   ExprResult Callee =3D getDerived().TransformExpr(E->getCallee());
@@ -6619,7 +6858,7 @@
       Callee.get() =3D=3D E->getCallee() &&
       First.get() =3D=3D E->getArg(0) &&
       (E->getNumArgs() !=3D 2 || Second.get() =3D=3D E->getArg(1)))
-    return SemaRef.Owned(E);
+    return SemaRef.MaybeBindToTemporary(E);
=20
   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
                                                  E->getOperatorLoc(),
@@ -6657,7 +6896,7 @@
   if (!getDerived().AlwaysRebuild() &&
       Callee.get() =3D=3D E->getCallee() &&
       !ArgChanged)
-    return SemaRef.Owned(E);
+    return SemaRef.MaybeBindToTemporary(E);
=20
   // FIXME: Wrong source location information for the '('.
   SourceLocation FakeLParenLoc
@@ -6769,11 +7008,11 @@
                                              E->getLocEnd());
   }
=20
-  // We don't know whether the expression is potentially evaluated until
-  // after we perform semantic analysis, so the expression is potentially
+  // We don't know whether the subexpression is potentially evaluated until
+  // after we perform semantic analysis.  We speculatively assume it is
+  // unevaluated; it will get fixed later if the subexpression is in fact
   // potentially evaluated.
-  EnterExpressionEvaluationContext Unevaluated(SemaRef,
-                                      Sema::PotentiallyPotentiallyEvaluate=
d);
+  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
=20
   ExprResult SubExpr =3D getDerived().TransformExpr(E->getExprOperand());
   if (SubExpr.isInvalid())
@@ -6808,9 +7047,6 @@
                                              E->getLocEnd());
   }
=20
-  // We don't know whether the expression is potentially evaluated until
-  // after we perform semantic analysis, so the expression is potentially
-  // potentially evaluated.
   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
=20
   ExprResult SubExpr =3D getDerived().TransformExpr(E->getExprOperand());
@@ -6851,9 +7087,12 @@
     T =3D getSema().Context.getPointerType(
       getSema().Context.getRecordType(cast<CXXRecordDecl>(DC)));
=20
-  if (!getDerived().AlwaysRebuild() && T =3D=3D E->getType())
+  if (!getDerived().AlwaysRebuild() && T =3D=3D E->getType()) {
+    // Make sure that we capture 'this'.
+    getSema().CheckCXXThisCapture(E->getLocStart());
     return SemaRef.Owned(E);
-
+  }
+ =20
   return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplici=
t());
 }
=20
@@ -6925,24 +7164,17 @@
   if (getDerived().TransformExprs(E->getPlacementArgs(),=20
                                   E->getNumPlacementArgs(), true,
                                   PlacementArgs, &ArgumentChanged))
-    return ExprError(); =20
-
-  // transform the constructor arguments (if any).
-  ASTOwningVector<Expr*> ConstructorArgs(SemaRef);
-  if (TransformExprs(E->getConstructorArgs(), E->getNumConstructorArgs(), =
true,
-                     ConstructorArgs, &ArgumentChanged))
-    return ExprError(); =20
-
-  // Transform constructor, new operator, and delete operator.
-  CXXConstructorDecl *Constructor =3D 0;
-  if (E->getConstructor()) {
-    Constructor =3D cast_or_null<CXXConstructorDecl>(
-                                   getDerived().TransformDecl(E->getLocSta=
rt(),
-                                                         E->getConstructor=
()));
-    if (!Constructor)
-      return ExprError();
-  }
-
+    return ExprError();
+
+  // Transform the initializer (if any).
+  Expr *OldInit =3D E->getInitializer();
+  ExprResult NewInit;
+  if (OldInit)
+    NewInit =3D getDerived().TransformExpr(OldInit);
+  if (NewInit.isInvalid())
+    return ExprError();
+
+  // Transform new operator and delete operator.
   FunctionDecl *OperatorNew =3D 0;
   if (E->getOperatorNew()) {
     OperatorNew =3D cast_or_null<FunctionDecl>(
@@ -6964,31 +7196,28 @@
   if (!getDerived().AlwaysRebuild() &&
       AllocTypeInfo =3D=3D E->getAllocatedTypeSourceInfo() &&
       ArraySize.get() =3D=3D E->getArraySize() &&
-      Constructor =3D=3D E->getConstructor() &&
+      NewInit.get() =3D=3D OldInit &&
       OperatorNew =3D=3D E->getOperatorNew() &&
       OperatorDelete =3D=3D E->getOperatorDelete() &&
       !ArgumentChanged) {
     // Mark any declarations we need as referenced.
     // FIXME: instantiation-specific.
-    if (Constructor)
-      SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
     if (OperatorNew)
-      SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorNew);
+      SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
     if (OperatorDelete)
-      SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorDelete);
-   =20
-    if (E->isArray() && Constructor &&=20
-        !E->getAllocatedType()->isDependentType()) {
+      SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
+   =20
+    if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
       QualType ElementType
         =3D SemaRef.Context.getBaseElementType(E->getAllocatedType());
       if (const RecordType *RecordT =3D ElementType->getAs<RecordType>()) {
         CXXRecordDecl *Record =3D cast<CXXRecordDecl>(RecordT->getDecl());
         if (CXXDestructorDecl *Destructor =3D SemaRef.LookupDestructor(Rec=
ord)) {
-          SemaRef.MarkDeclarationReferenced(E->getLocStart(), Destructor);
+          SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
         }
       }
     }
-   =20
+
     return SemaRef.Owned(E);
   }
=20
@@ -7018,7 +7247,7 @@
       }
     }
   }
- =20
+
   return getDerived().RebuildCXXNewExpr(E->getLocStart(),
                                         E->isGlobalNew(),
                                         /*FIXME:*/E->getLocStart(),
@@ -7028,13 +7257,8 @@
                                         AllocType,
                                         AllocTypeInfo,
                                         ArraySize.get(),
-                                        /*FIXME:*/E->hasInitializer()
-                                          ? E->getLocStart()
-                                          : SourceLocation(),
-                                        move_arg(ConstructorArgs),
-                                        /*FIXME:*/E->hasInitializer()
-                                          ? E->getLocEnd()
-                                          : SourceLocation());
+                                        E->getDirectInitRange(),
+                                        NewInit.take());
 }
=20
 template<typename Derived>
@@ -7060,15 +7284,15 @@
     // Mark any declarations we need as referenced.
     // FIXME: instantiation-specific.
     if (OperatorDelete)
-      SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorDelete);
+      SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
    =20
     if (!E->getArgument()->isTypeDependent()) {
       QualType Destroyed =3D SemaRef.Context.getBaseElementType(
                                                          E->getDestroyedTy=
pe());
       if (const RecordType *DestroyedRec =3D Destroyed->getAs<RecordType>(=
)) {
         CXXRecordDecl *Record =3D cast<CXXRecordDecl>(DestroyedRec->getDec=
l());
-        SemaRef.MarkDeclarationReferenced(E->getLocStart(),=20
-                                          SemaRef.LookupDestructor(Record)=
);
+        SemaRef.MarkFunctionReferenced(E->getLocStart(),=20
+                                       SemaRef.LookupDestructor(Record));
       }
     }
    =20
@@ -7118,7 +7342,7 @@
     if (!DestroyedTypeInfo)
       return ExprError();
     Destroyed =3D DestroyedTypeInfo;
-  } else if (ObjectType->isDependentType()) {
+  } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
     // We aren't likely to be able to resolve the identifier down to a type
     // now anyway, so just retain the identifier.
     Destroyed =3D PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifie=
r(),
@@ -7216,8 +7440,11 @@
     R.setNamingClass(NamingClass);
   }
=20
-  // If we have no template arguments, it's a normal declaration name.
-  if (!Old->hasExplicitTemplateArgs())
+  SourceLocation TemplateKWLoc =3D Old->getTemplateKeywordLoc();
+
+  // If we have neither explicit template arguments, nor the template keyw=
ord,
+  // it's a normal declaration name.
+  if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL=
());
=20
   // If we have template arguments, rebuild them, then rebuild the
@@ -7228,8 +7455,8 @@
                                               TransArgs))
     return ExprError();
=20
-  return getDerived().RebuildTemplateIdExpr(SS, R, Old->requiresADL(),
-                                            TransArgs);
+  return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
+                                            Old->requiresADL(), &TransArgs=
);
 }
=20
 template<typename Derived>
@@ -7272,6 +7499,128 @@
=20
 template<typename Derived>
 ExprResult
+TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
+  bool ArgChanged =3D false;
+  llvm::SmallVector<TypeSourceInfo *, 4> Args;
+  for (unsigned I =3D 0, N =3D E->getNumArgs(); I !=3D N; ++I) {
+    TypeSourceInfo *From =3D E->getArg(I);
+    TypeLoc FromTL =3D From->getTypeLoc();
+    if (!isa<PackExpansionTypeLoc>(FromTL)) {
+      TypeLocBuilder TLB;
+      TLB.reserve(FromTL.getFullDataSize());
+      QualType To =3D getDerived().TransformType(TLB, FromTL);
+      if (To.isNull())
+        return ExprError();
+     =20
+      if (To =3D=3D From->getType())
+        Args.push_back(From);
+      else {
+        Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
+        ArgChanged =3D true;
+      }
+      continue;
+    }
+   =20
+    ArgChanged =3D true;
+   =20
+    // We have a pack expansion. Instantiate it.
+    PackExpansionTypeLoc ExpansionTL =3D cast<PackExpansionTypeLoc>(FromTL=
);     =20
+    TypeLoc PatternTL =3D ExpansionTL.getPatternLoc();
+    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
+    SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
+   =20
+    // Determine whether the set of unexpanded parameter packs can and sho=
uld
+    // be expanded.
+    bool Expand =3D true;
+    bool RetainExpansion =3D false;
+    llvm::Optional<unsigned> OrigNumExpansions
+      =3D ExpansionTL.getTypePtr()->getNumExpansions();
+    llvm::Optional<unsigned> NumExpansions =3D OrigNumExpansions;
+    if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
+                                             PatternTL.getSourceRange(),
+                                             Unexpanded,
+                                             Expand, RetainExpansion,
+                                             NumExpansions))
+      return ExprError();
+   =20
+    if (!Expand) {
+      // The transform has determined that we should perform a simple
+      // transformation on the pack expansion, producing another pack=20
+      // expansion.
+      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
+     =20
+      TypeLocBuilder TLB;
+      TLB.reserve(From->getTypeLoc().getFullDataSize());
+
+      QualType To =3D getDerived().TransformType(TLB, PatternTL);
+      if (To.isNull())
+        return ExprError();
+
+      To =3D getDerived().RebuildPackExpansionType(To,=20
+                                                 PatternTL.getSourceRange(=
),
+                                                 ExpansionTL.getEllipsisLo=
c(),
+                                                 NumExpansions);
+      if (To.isNull())
+        return ExprError();
+     =20
+      PackExpansionTypeLoc ToExpansionTL
+        =3D TLB.push<PackExpansionTypeLoc>(To);
+      ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
+      Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
+      continue;
+    }
+
+    // Expand the pack expansion by substituting for each argument in the
+    // pack(s).
+    for (unsigned I =3D 0; I !=3D *NumExpansions; ++I) {
+      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
+      TypeLocBuilder TLB;
+      TLB.reserve(PatternTL.getFullDataSize());
+      QualType To =3D getDerived().TransformType(TLB, PatternTL);
+      if (To.isNull())
+        return ExprError();
+
+      Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
+    }
+   =20
+    if (!RetainExpansion)
+      continue;
+   =20
+    // If we're supposed to retain a pack expansion, do so by temporarily
+    // forgetting the partially-substituted parameter pack.
+    ForgetPartiallySubstitutedPackRAII Forget(getDerived());
+
+    TypeLocBuilder TLB;
+    TLB.reserve(From->getTypeLoc().getFullDataSize());
+   =20
+    QualType To =3D getDerived().TransformType(TLB, PatternTL);
+    if (To.isNull())
+      return ExprError();
+   =20
+    To =3D getDerived().RebuildPackExpansionType(To,=20
+                                               PatternTL.getSourceRange(),
+                                               ExpansionTL.getEllipsisLoc(=
),
+                                               NumExpansions);
+    if (To.isNull())
+      return ExprError();
+   =20
+    PackExpansionTypeLoc ToExpansionTL
+      =3D TLB.push<PackExpansionTypeLoc>(To);
+    ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
+    Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
+  }
+ =20
+  if (!getDerived().AlwaysRebuild() && !ArgChanged)
+    return SemaRef.Owned(E);
+
+  return getDerived().RebuildTypeTrait(E->getTrait(),
+                                       E->getLocStart(),
+                                       Args,
+                                       E->getLocEnd());
+}
+
+template<typename Derived>
+ExprResult
 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E)=
 {
   TypeSourceInfo *T =3D getDerived().TransformType(E->getQueriedTypeSource=
Info());
   if (!T)
@@ -7325,6 +7674,7 @@
   =3D getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   if (!QualifierLoc)
     return ExprError();
+  SourceLocation TemplateKWLoc =3D E->getTemplateKeywordLoc();
=20
   // TODO: If this is a conversion-function-id, verify that the
   // destination type name (if present) resolves the same way after
@@ -7344,6 +7694,7 @@
       return SemaRef.Owned(E);
=20
     return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
+                                                         TemplateKWLoc,
                                                          NameInfo,
                                                          /*TemplateArgs*/ =
0);
   }
@@ -7355,6 +7706,7 @@
     return ExprError();
=20
   return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
+                                                       TemplateKWLoc,
                                                        NameInfo,
                                                        &TransArgs);
 }
@@ -7393,7 +7745,7 @@
       !ArgumentChanged) {
     // Mark the constructor as referenced.
     // FIXME: Instantiation-specific
-    SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
+    SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
     return SemaRef.Owned(E);
   }
=20
@@ -7454,7 +7806,7 @@
       Constructor =3D=3D E->getConstructor() &&
       !ArgumentChanged) {
     // FIXME: Instantiation-specific
-    SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
+    SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
     return SemaRef.MaybeBindToTemporary(E);
   }
  =20
@@ -7466,6 +7818,158 @@
=20
 template<typename Derived>
 ExprResult
+TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
+  // Create the local class that will describe the lambda.
+  CXXRecordDecl *Class
+    =3D getSema().createLambdaClosureType(E->getIntroducerRange(),
+                                        /*KnownDependent=3D*/false);
+  getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
+ =20
+  // Transform the type of the lambda parameters and start the definition =
of
+  // the lambda itself.
+  TypeSourceInfo *MethodTy
+    =3D TransformType(E->getCallOperator()->getTypeSourceInfo()); =20
+  if (!MethodTy)
+    return ExprError();
+
+  // Transform lambda parameters.
+  bool Invalid =3D false;
+  llvm::SmallVector<QualType, 4> ParamTypes;
+  llvm::SmallVector<ParmVarDecl *, 4> Params;
+  if (getDerived().TransformFunctionTypeParams(E->getLocStart(),
+        E->getCallOperator()->param_begin(),
+        E->getCallOperator()->param_size(),
+        0, ParamTypes, &Params))
+    Invalid =3D true; =20
+
+  // Build the call operator.
+  // Note: Once a lambda mangling number and context declaration have been
+  // assigned, they never change.
+  unsigned ManglingNumber =3D E->getLambdaClass()->getLambdaManglingNumber=
();
+  Decl *ContextDecl =3D E->getLambdaClass()->getLambdaContextDecl(); =20
+  CXXMethodDecl *CallOperator
+    =3D getSema().startLambdaDefinition(Class, E->getIntroducerRange(),
+                                      MethodTy,=20
+                                      E->getCallOperator()->getLocEnd(),
+                                      Params, ManglingNumber, ContextDecl);
+  getDerived().transformAttrs(E->getCallOperator(), CallOperator);
+ =20
+  // FIXME: Instantiation-specific.
+  CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),=20
+                                                 TSK_ImplicitInstantiation=
);
+
+  // Introduce the context of the call operator.
+  Sema::ContextRAII SavedContext(getSema(), CallOperator);
+
+  // Enter the scope of the lambda.
+  sema::LambdaScopeInfo *LSI
+    =3D getSema().enterLambdaScope(CallOperator, E->getIntroducerRange(),
+                                 E->getCaptureDefault(),
+                                 E->hasExplicitParameters(),
+                                 E->hasExplicitResultType(),
+                                 E->isMutable());
+ =20
+  // Transform captures.
+  bool FinishedExplicitCaptures =3D false;
+  for (LambdaExpr::capture_iterator C =3D E->capture_begin(),=20
+                                 CEnd =3D E->capture_end();
+       C !=3D CEnd; ++C) {
+    // When we hit the first implicit capture, tell Sema that we've finish=
ed
+    // the list of explicit captures.
+    if (!FinishedExplicitCaptures && C->isImplicit()) {
+      getSema().finishLambdaExplicitCaptures(LSI);
+      FinishedExplicitCaptures =3D true;
+    }
+   =20
+    // Capturing 'this' is trivial.
+    if (C->capturesThis()) {
+      getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
+      continue;
+    }
+   =20
+    // Determine the capture kind for Sema.
+    Sema::TryCaptureKind Kind
+      =3D C->isImplicit()? Sema::TryCapture_Implicit
+                       : C->getCaptureKind() =3D=3D LCK_ByCopy
+                           ? Sema::TryCapture_ExplicitByVal
+                           : Sema::TryCapture_ExplicitByRef;
+    SourceLocation EllipsisLoc;
+    if (C->isPackExpansion()) {
+      UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocati=
on());
+      bool ShouldExpand =3D false;
+      bool RetainExpansion =3D false;
+      llvm::Optional<unsigned> NumExpansions;
+      if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),=20
+                                               C->getLocation(),=20
+                                               Unexpanded,
+                                               ShouldExpand, RetainExpansi=
on,
+                                               NumExpansions))
+        return ExprError();
+     =20
+      if (ShouldExpand) {
+        // The transform has determined that we should perform an expansio=
n;
+        // transform and capture each of the arguments.
+        // expansion of the pattern. Do so.
+        VarDecl *Pack =3D C->getCapturedVar();
+        for (unsigned I =3D 0; I !=3D *NumExpansions; ++I) {
+          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
+          VarDecl *CapturedVar
+            =3D cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLoc=
ation(),=20
+                                                               Pack));
+          if (!CapturedVar) {
+            Invalid =3D true;
+            continue;
+          }
+         =20
+          // Capture the transformed variable.
+          getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind=
);         =20
+        }         =20
+        continue;
+      }
+     =20
+      EllipsisLoc =3D C->getEllipsisLoc();
+    }
+   =20
+    // Transform the captured variable.
+    VarDecl *CapturedVar
+      =3D cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(=
),=20
+                                                         C->getCapturedVar=
()));
+    if (!CapturedVar) {
+      Invalid =3D true;
+      continue;
+    }
+ =20
+    // Capture the transformed variable.
+    getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
+  }
+  if (!FinishedExplicitCaptures)
+    getSema().finishLambdaExplicitCaptures(LSI);
+
+
+  // Enter a new evaluation context to insulate the lambda from any
+  // cleanups from the enclosing full-expression.
+  getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); =20
+
+  if (Invalid) {
+    getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=3D*/0,=20
+                               /*IsInstantiation=3D*/true);
+    return ExprError();
+  }
+
+  // Instantiate the body of the lambda expression.
+  StmtResult Body =3D getDerived().TransformStmt(E->getBody());
+  if (Body.isInvalid()) {
+    getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=3D*/0,=20
+                               /*IsInstantiation=3D*/true);
+    return ExprError();   =20
+  }
+
+  return getSema().ActOnLambdaExpr(E->getLocStart(), Body.take(),=20
+                                   /*CurScope=3D*/0, /*IsInstantiation=3D*=
/true);
+}
+
+template<typename Derived>
+ExprResult
 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
                                                   CXXUnresolvedConstructEx=
pr *E) {
   TypeSourceInfo *T =3D getDerived().TransformType(E->getTypeSourceInfo());
@@ -7542,6 +8046,8 @@
       return ExprError();
   }
=20
+  SourceLocation TemplateKWLoc =3D E->getTemplateKeywordLoc();
+
   // TODO: If this is a conversion-function-id, verify that the
   // destination type name (if present) resolves the same way after
   // instantiation as it did in the local scope.
@@ -7567,6 +8073,7 @@
                                                        E->isArrow(),
                                                        E->getOperatorLoc(),
                                                        QualifierLoc,
+                                                       TemplateKWLoc,
                                                        FirstQualifierInSco=
pe,
                                                        NameInfo,
                                                        /*TemplateArgs*/ 0);
@@ -7583,6 +8090,7 @@
                                                      E->isArrow(),
                                                      E->getOperatorLoc(),
                                                      QualifierLoc,
+                                                     TemplateKWLoc,
                                                      FirstQualifierInScope,
                                                      NameInfo,
                                                      &TransArgs);
@@ -7598,7 +8106,11 @@
     Base =3D getDerived().TransformExpr(Old->getBase());
     if (Base.isInvalid())
       return ExprError();
-    BaseType =3D ((Expr*) Base.get())->getType();
+    Base =3D getSema().PerformMemberExprBaseConversion(Base.take(),
+                                                     Old->isArrow());
+    if (Base.isInvalid())
+      return ExprError();
+    BaseType =3D Base.get()->getType();
   } else {
     BaseType =3D getDerived().TransformType(Old->getBaseType());
   }
@@ -7611,6 +8123,8 @@
       return ExprError();
   }
=20
+  SourceLocation TemplateKWLoc =3D Old->getTemplateKeywordLoc();
+
   LookupResult R(SemaRef, Old->getMemberNameInfo(),
                  Sema::LookupOrdinaryName);
=20
@@ -7678,6 +8192,7 @@
                                                   Old->getOperatorLoc(),
                                                   Old->isArrow(),
                                                   QualifierLoc,
+                                                  TemplateKWLoc,
                                                   FirstQualifierInScope,
                                                   R,
                                               (Old->hasExplicitTemplateArg=
s()
@@ -7778,11 +8293,163 @@
 template<typename Derived>
 ExprResult
 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
+  return SemaRef.MaybeBindToTemporary(E);
+}
+
+template<typename Derived>
+ExprResult
+TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *=
E) {
   return SemaRef.Owned(E);
 }
=20
 template<typename Derived>
 ExprResult
+TreeTransform<Derived>::TransformObjCNumericLiteral(ObjCNumericLiteral *E)=
 {
+  return SemaRef.MaybeBindToTemporary(E);
+}
+
+template<typename Derived>
+ExprResult
+TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
+  // Transform each of the elements.
+  llvm::SmallVector<Expr *, 8> Elements;
+  bool ArgChanged =3D false;
+  if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),=20
+                                  /*IsCall=3D*/false, Elements, &ArgChange=
d))
+    return ExprError();
+ =20
+  if (!getDerived().AlwaysRebuild() && !ArgChanged)
+    return SemaRef.MaybeBindToTemporary(E);
+ =20
+  return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
+                                              Elements.data(),
+                                              Elements.size());
+}
+
+template<typename Derived>
+ExprResult
+TreeTransform<Derived>::TransformObjCDictionaryLiteral(
+                                                    ObjCDictionaryLiteral =
*E) { =20
+  // Transform each of the elements.
+  llvm::SmallVector<ObjCDictionaryElement, 8> Elements;
+  bool ArgChanged =3D false;
+  for (unsigned I =3D 0, N =3D E->getNumElements(); I !=3D N; ++I) {
+    ObjCDictionaryElement OrigElement =3D E->getKeyValueElement(I);
+   =20
+    if (OrigElement.isPackExpansion()) {
+      // This key/value element is a pack expansion.
+      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
+      getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpande=
d);
+      getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpan=
ded);
+      assert(!Unexpanded.empty() && "Pack expansion without parameter pack=
s?");
+
+      // Determine whether the set of unexpanded parameter packs can
+      // and should be expanded.
+      bool Expand =3D true;
+      bool RetainExpansion =3D false;
+      llvm::Optional<unsigned> OrigNumExpansions =3D OrigElement.NumExpans=
ions;
+      llvm::Optional<unsigned> NumExpansions =3D OrigNumExpansions;
+      SourceRange PatternRange(OrigElement.Key->getLocStart(),
+                               OrigElement.Value->getLocEnd());
+     if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
+                                               PatternRange,
+                                               Unexpanded,
+                                               Expand, RetainExpansion,
+                                               NumExpansions))
+        return ExprError();
+
+      if (!Expand) {
+        // The transform has determined that we should perform a simple
+        // transformation on the pack expansion, producing another pack=20
+        // expansion.
+        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
+        ExprResult Key =3D getDerived().TransformExpr(OrigElement.Key);
+        if (Key.isInvalid())
+          return ExprError();
+
+        if (Key.get() !=3D OrigElement.Key)
+          ArgChanged =3D true;
+
+        ExprResult Value =3D getDerived().TransformExpr(OrigElement.Value);
+        if (Value.isInvalid())
+          return ExprError();
+       =20
+        if (Value.get() !=3D OrigElement.Value)
+          ArgChanged =3D true;
+
+        ObjCDictionaryElement Expansion =3D {=20
+          Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
+        };
+        Elements.push_back(Expansion);
+        continue;
+      }
+
+      // Record right away that the argument was changed.  This needs
+      // to happen even if the array expands to nothing.
+      ArgChanged =3D true;
+     =20
+      // The transform has determined that we should perform an elementwise
+      // expansion of the pattern. Do so.
+      for (unsigned I =3D 0; I !=3D *NumExpansions; ++I) {
+        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
+        ExprResult Key =3D getDerived().TransformExpr(OrigElement.Key);
+        if (Key.isInvalid())
+          return ExprError();
+
+        ExprResult Value =3D getDerived().TransformExpr(OrigElement.Value);
+        if (Value.isInvalid())
+          return ExprError();
+
+        ObjCDictionaryElement Element =3D {=20
+          Key.get(), Value.get(), SourceLocation(), NumExpansions
+        };
+
+        // If any unexpanded parameter packs remain, we still have a
+        // pack expansion.
+        if (Key.get()->containsUnexpandedParameterPack() ||
+            Value.get()->containsUnexpandedParameterPack())
+          Element.EllipsisLoc =3D OrigElement.EllipsisLoc;
+         =20
+        Elements.push_back(Element);
+      }
+
+      // We've finished with this pack expansion.
+      continue;
+    }
+
+    // Transform and check key.
+    ExprResult Key =3D getDerived().TransformExpr(OrigElement.Key);
+    if (Key.isInvalid())
+      return ExprError();
+   =20
+    if (Key.get() !=3D OrigElement.Key)
+      ArgChanged =3D true;
+   =20
+    // Transform and check value.
+    ExprResult Value
+      =3D getDerived().TransformExpr(OrigElement.Value);
+    if (Value.isInvalid())
+      return ExprError();
+   =20
+    if (Value.get() !=3D OrigElement.Value)
+      ArgChanged =3D true;
+   =20
+    ObjCDictionaryElement Element =3D {=20
+      Key.get(), Value.get(), SourceLocation(), llvm::Optional<unsigned>()
+    };
+    Elements.push_back(Element);
+  }
+ =20
+  if (!getDerived().AlwaysRebuild() && !ArgChanged)
+    return SemaRef.MaybeBindToTemporary(E);
+
+  return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
+                                                   Elements.data(),
+                                                   Elements.size());
+}
+
+template<typename Derived>
+ExprResult
 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
   TypeSourceInfo *EncodedTypeInfo
     =3D getDerived().TransformType(E->getEncodedTypeSourceInfo());
@@ -7856,7 +8523,7 @@
     // If nothing changed, just retain the existing message send.
     if (!getDerived().AlwaysRebuild() &&
         ReceiverTypeInfo =3D=3D E->getClassReceiverTypeInfo() && !ArgChang=
ed)
-      return SemaRef.Owned(E);
+      return SemaRef.MaybeBindToTemporary(E);
=20
     // Build a new class message send.
     SmallVector<SourceLocation, 16> SelLocs;
@@ -7881,7 +8548,7 @@
   // If nothing changed, just retain the existing message send.
   if (!getDerived().AlwaysRebuild() &&
       Receiver.get() =3D=3D E->getInstanceReceiver() && !ArgChanged)
-    return SemaRef.Owned(E);
+    return SemaRef.MaybeBindToTemporary(E);
  =20
   // Build a new instance message send.
   SmallVector<SourceLocation, 16> SelLocs;
@@ -7953,7 +8620,7 @@
                                                    E->getLocation());
=20
   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
-                                                 E->getType(),
+                                                 SemaRef.Context.PseudoObj=
ectTy,
                                                  E->getImplicitPropertyGet=
ter(),
                                                  E->getImplicitPropertySet=
ter(),
                                                  E->getLocation());
@@ -7961,6 +8628,30 @@
=20
 template<typename Derived>
 ExprResult
+TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr=
 *E) {
+  // Transform the base expression.
+  ExprResult Base =3D getDerived().TransformExpr(E->getBaseExpr());
+  if (Base.isInvalid())
+    return ExprError();
+
+  // Transform the key expression.
+  ExprResult Key =3D getDerived().TransformExpr(E->getKeyExpr());
+  if (Key.isInvalid())
+    return ExprError();
+
+  // If nothing changed, just retain the existing expression.
+  if (!getDerived().AlwaysRebuild() &&
+      Key.get() =3D=3D E->getKeyExpr() && Base.get() =3D=3D E->getBaseExpr=
())
+    return SemaRef.Owned(E);
+
+  return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),=20
+                                                  Base.get(), Key.get(),
+                                                  E->getAtIndexMethodDecl(=
),
+                                                  E->setAtIndexMethodDecl(=
));
+}
+
+template<typename Derived>
+ExprResult
 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
   // Transform the base expression.
   ExprResult Base =3D getDerived().TransformExpr(E->getBase());
@@ -8004,10 +8695,8 @@
   BlockScopeInfo *blockScope =3D SemaRef.getCurBlock();
=20
   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
-  // We built a new blockScopeInfo in call to ActOnBlockStart
-  // in above, CapturesCXXThis need be set here from the block
-  // expression.
-  blockScope->CapturesCXXThis =3D oldBlock->capturesCXXThis();
+  blockScope->TheDecl->setBlockMissingReturnType(
+                         oldBlock->blockMissingReturnType());
  =20
   SmallVector<ParmVarDecl*, 4> params;
   SmallVector<QualType, 4> paramTypes;
@@ -8016,54 +8705,48 @@
   if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
                                                oldBlock->param_begin(),
                                                oldBlock->param_size(),
-                                               0, paramTypes, &params))
-    return true;
+                                               0, paramTypes, &params)) {
+    getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=3D*/0);
+    return ExprError();
+  }
=20
   const FunctionType *exprFunctionType =3D E->getFunctionType();
-  QualType exprResultType =3D exprFunctionType->getResultType();
-  if (!exprResultType.isNull()) {
-    if (!exprResultType->isDependentType())
-      blockScope->ReturnType =3D exprResultType;
-    else if (exprResultType !=3D getSema().Context.DependentTy)
-      blockScope->ReturnType =3D getDerived().TransformType(exprResultType=
);
-  }
- =20
-  // If the return type has not been determined yet, leave it as a depende=
nt
-  // type; it'll get set when we process the body.
-  if (blockScope->ReturnType.isNull())
-    blockScope->ReturnType =3D getSema().Context.DependentTy;
+  QualType exprResultType =3D
+      getDerived().TransformType(exprFunctionType->getResultType());
=20
   // Don't allow returning a objc interface by value.
-  if (blockScope->ReturnType->isObjCObjectType()) {
+  if (exprResultType->isObjCObjectType()) {
     getSema().Diag(E->getCaretLocation(),=20
                    diag::err_object_cannot_be_passed_returned_by_value)=20
-      << 0 << blockScope->ReturnType;
+      << 0 << exprResultType;
+    getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=3D*/0);
     return ExprError();
   }
=20
   QualType functionType =3D getDerived().RebuildFunctionProtoType(
-                                                        blockScope->Return=
Type,
+                                                        exprResultType,
                                                         paramTypes.data(),
                                                         paramTypes.size(),
                                                         oldBlock->isVariad=
ic(),
-                                                        0, RQ_None,
+                                                        false, 0, RQ_None,
                                                exprFunctionType->getExtInf=
o());
   blockScope->FunctionType =3D functionType;
=20
   // Set the parameters on the block decl.
   if (!params.empty())
     blockScope->TheDecl->setParams(params);
- =20
-  // If the return type wasn't explicitly set, it will have been marked as=
 a=20
-  // dependent type (DependentTy); clear out the return type setting so=20
-  // we will deduce the return type when type-checking the block's body.
-  if (blockScope->ReturnType =3D=3D getSema().Context.DependentTy)
-    blockScope->ReturnType =3D QualType();
+
+  if (!oldBlock->blockMissingReturnType()) {
+    blockScope->HasImplicitReturnType =3D false;
+    blockScope->ReturnType =3D exprResultType;
+  }
  =20
   // Transform the body
   StmtResult body =3D getDerived().TransformStmt(E->getBody());
-  if (body.isInvalid())
+  if (body.isInvalid()) {
+    getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=3D*/0);
     return ExprError();
+  }
=20
 #ifndef NDEBUG
   // In builds with assertions, make sure that we captured everything we
@@ -8083,6 +8766,7 @@
                                                  oldCapture));
       assert(blockScope->CaptureMap.count(newCapture));
     }
+    assert(oldBlock->capturesCXXThis() =3D=3D blockScope->isCXXThisCapture=
d());
   }
 #endif
=20
@@ -8092,29 +8776,6 @@
=20
 template<typename Derived>
 ExprResult
-TreeTransform<Derived>::TransformBlockDeclRefExpr(BlockDeclRefExpr *E) {
-  ValueDecl *ND
-  =3D cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
-                                                       E->getDecl()));
-  if (!ND)
-    return ExprError();
-
-  if (!getDerived().AlwaysRebuild() &&
-      ND =3D=3D E->getDecl()) {
-    // Mark it referenced in the new context regardless.
-    // FIXME: this is a bit instantiation-specific.
-    SemaRef.MarkDeclarationReferenced(E->getLocation(), ND);
-   =20
-    return SemaRef.Owned(E);
-  }
- =20
-  DeclarationNameInfo NameInfo(E->getDecl()->getDeclName(), E->getLocation=
());
-  return getDerived().RebuildDeclRefExpr(NestedNameSpecifierLoc(),=20
-                                         ND, NameInfo, 0);
-}
-
-template<typename Derived>
-ExprResult
 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
   llvm_unreachable("Cannot transform asType expressions yet");
 }
@@ -8200,9 +8861,12 @@
       break;
     }
=20
-  IntegerLiteral ArraySize(SemaRef.Context, *Size, SizeType,
-                           /*FIXME*/BracketsRange.getBegin());
-  return SemaRef.BuildArrayType(ElementType, SizeMod, &ArraySize,
+  // Note that we can return a VariableArrayType here in the case where
+  // the element type was a dependent VariableArrayType.
+  IntegerLiteral *ArraySize
+      =3D IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
+                               /*FIXME*/BracketsRange.getBegin());
+  return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
                                 IndexTypeQuals, BracketsRange,
                                 getDerived().getBaseEntity());
 }
@@ -8285,11 +8949,12 @@
                                                           QualType *ParamT=
ypes,
                                                         unsigned NumParamT=
ypes,
                                                           bool Variadic,
+                                                         bool HasTrailingR=
eturn,
                                                           unsigned Quals,
                                                   RefQualifierKind RefQual=
ifier,
                                             const FunctionType::ExtInfo &I=
nfo) {
   return SemaRef.BuildFunctionType(T, ParamTypes, NumParamTypes, Variadic,
-                                   Quals, RefQualifier,
+                                   HasTrailingReturn, Quals, RefQualifier,
                                    getDerived().getBaseLocation(),
                                    getDerived().getBaseEntity(),
                                    Info);
@@ -8382,10 +9047,9 @@
   UnqualifiedId TemplateName;
   TemplateName.setIdentifier(&Name, NameLoc);
   Sema::TemplateTy Template;
+  SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   getSema().ActOnDependentTemplateName(/*Scope=3D*/0,
-                                       /*FIXME:*/SourceLocation(),
-                                       SS,
-                                       TemplateName,
+                                       SS, TemplateKWLoc, TemplateName,
                                        ParsedType::make(ObjectType),
                                        /*EnteringContext=3D*/false,
                                        Template);
@@ -8400,13 +9064,12 @@
                                             QualType ObjectType) {
   UnqualifiedId Name;
   // FIXME: Bogus location information.
-  SourceLocation SymbolLocations[3] =3D { NameLoc, NameLoc, NameLoc };  =20
+  SourceLocation SymbolLocations[3] =3D { NameLoc, NameLoc, NameLoc };
   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
+  SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   Sema::TemplateTy Template;
   getSema().ActOnDependentTemplateName(/*Scope=3D*/0,
-                                       /*FIXME:*/SourceLocation(),
-                                       SS,
-                                       Name,
+                                       SS, TemplateKWLoc, Name,
                                        ParsedType::make(ObjectType),
                                        /*EnteringContext=3D*/false,
                                        Template);
@@ -8543,9 +9206,11 @@
=20
   // FIXME: the ScopeType should be tacked onto SS.
=20
+  SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   return getSema().BuildMemberReferenceExpr(Base, BaseType,
                                             OperatorLoc, isArrow,
-                                            SS, /*FIXME: FirstQualifier*/ =
0,
+                                            SS, TemplateKWLoc,
+                                            /*FIXME: FirstQualifier*/ 0,
                                             NameInfo,
                                             /*TemplateArgs*/ 0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTCommon.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTCommon.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTCommon.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -52,8 +52,11 @@
   case BuiltinType::Char32:     ID =3D PREDEF_TYPE_CHAR32_ID;     break;
   case BuiltinType::Overload:   ID =3D PREDEF_TYPE_OVERLOAD_ID;   break;
   case BuiltinType::BoundMember:ID =3D PREDEF_TYPE_BOUND_MEMBER;  break;
+  case BuiltinType::PseudoObject:ID =3D PREDEF_TYPE_PSEUDO_OBJECT;break;
   case BuiltinType::Dependent:  ID =3D PREDEF_TYPE_DEPENDENT_ID;  break;
   case BuiltinType::UnknownAny: ID =3D PREDEF_TYPE_UNKNOWN_ANY;   break;
+  case BuiltinType::ARCUnbridgedCast:
+                                ID =3D PREDEF_TYPE_ARC_UNBRIDGED_CAST; bre=
ak;
   case BuiltinType::ObjCId:     ID =3D PREDEF_TYPE_OBJC_ID;       break;
   case BuiltinType::ObjCClass:  ID =3D PREDEF_TYPE_OBJC_CLASS;    break;
   case BuiltinType::ObjCSel:    ID =3D PREDEF_TYPE_OBJC_SEL;      break;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTCommon.h
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTCommon.h	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTCommon.h	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -22,7 +22,6 @@
 namespace serialization {
=20
 enum DeclUpdateKind {
-  UPD_CXX_SET_DEFINITIONDATA,
   UPD_CXX_ADDED_IMPLICIT_MEMBER,
   UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
   UPD_CXX_ADDED_ANONYMOUS_NAMESPACE,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTReader.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -14,10 +14,9 @@
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/ASTDeserializationListener.h"
 #include "clang/Serialization/ModuleManager.h"
+#include "clang/Serialization/SerializationDiagnostic.h"
 #include "ASTCommon.h"
 #include "ASTReaderInternals.h"
-#include "clang/Frontend/FrontendDiagnostic.h"
-#include "clang/Frontend/Utils.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Sema/Scope.h"
 #include "clang/AST/ASTConsumer.h"
@@ -28,6 +27,7 @@
 #include "clang/AST/NestedNameSpecifier.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/TypeLocVisitor.h"
+#include "llvm/Support/SaveAndRestore.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/PreprocessingRecord.h"
 #include "clang/Lex/Preprocessor.h"
@@ -64,7 +64,7 @@
=20
 bool
 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
-  const LangOptions &PPLangOpts =3D PP.getLangOptions();
+  const LangOptions &PPLangOpts =3D PP.getLangOpts();
  =20
 #define LANGOPT(Name, Bits, Default, Description)         \
   if (PPLangOpts.Name !=3D LangOpts.Name) {                 \
@@ -193,9 +193,10 @@
   // have a #include entry for the PCH file itself (as normalized by the
   // preprocessor initialization). Find it and skip over it in the checking
   // below.
-  llvm::SmallString<256> PCHInclude;
+  SmallString<256> PCHInclude;
   PCHInclude +=3D "#include \"";
-  PCHInclude +=3D NormalizeDashIncludePath(OriginalFileName, FileMgr);
+  PCHInclude +=3D HeaderSearch::NormalizeDashIncludePath(OriginalFileName,
+                                                       FileMgr);
   PCHInclude +=3D "\"\n";
   std::pair<StringRef,StringRef> Split =3D
     StringRef(PP.getPredefines()).split(PCHInclude.str());
@@ -510,10 +511,13 @@
     // For uninteresting identifiers, just build the IdentifierInfo
     // and associate it with the persistent ID.
     IdentifierInfo *II =3D KnownII;
-    if (!II)
+    if (!II) {
       II =3D &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.seco=
nd));
+      KnownII =3D II;
+    }
     Reader.SetIdentifierInfo(ID, II);
     II->setIsFromAST();
+    Reader.markIdentifierUpToDate(II);   =20
     return II;
   }
=20
@@ -528,8 +532,8 @@
   Bits >>=3D 1;
   bool hasMacroDefinition =3D Bits & 0x01;
   Bits >>=3D 1;
-  unsigned ObjCOrBuiltinID =3D Bits & 0x3FF;
-  Bits >>=3D 10;
+  unsigned ObjCOrBuiltinID =3D Bits & 0x7FF;
+  Bits >>=3D 11;
=20
   assert(Bits =3D=3D 0 && "Extra bits in the identifier?");
   DataLen -=3D 6;
@@ -537,9 +541,12 @@
   // Build the IdentifierInfo itself and link the identifier ID with
   // the new IdentifierInfo.
   IdentifierInfo *II =3D KnownII;
-  if (!II)
+  if (!II) {
     II =3D &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second=
));
-  Reader.SetIdentifierInfo(ID, II);
+    KnownII =3D II;
+  }
+  Reader.markIdentifierUpToDate(II);
+  II->setIsFromAST();
=20
   // Set or check the various bits in the IdentifierInfo structure.
   // Token IDs are read-only.
@@ -560,9 +567,31 @@
   if (hasMacroDefinition) {
     // FIXME: Check for conflicts?
     uint32_t Offset =3D ReadUnalignedLE32(d);
-    Reader.SetIdentifierIsMacro(II, F, Offset);
-    DataLen -=3D 4;
-  }
+    unsigned LocalSubmoduleID =3D ReadUnalignedLE32(d);
+   =20
+    // Determine whether this macro definition should be visible now, or
+    // whether it is in a hidden submodule.
+    bool Visible =3D true;
+    if (SubmoduleID GlobalSubmoduleID
+          =3D Reader.getGlobalSubmoduleID(F, LocalSubmoduleID)) {
+      if (Module *Owner =3D Reader.getSubmodule(GlobalSubmoduleID)) {
+        if (Owner->NameVisibility =3D=3D Module::Hidden) {
+          // The owning module is not visible, and this macro definition s=
hould
+          // not be, either.
+          Visible =3D false;
+         =20
+          // Note that this macro definition was hidden because its owning=20
+          // module is not yet visible.
+          Reader.HiddenNamesMap[Owner].push_back(II);
+        }
+      }=20
+    }
+   =20
+    Reader.setIdentifierIsMacro(II, F, Offset, Visible);
+    DataLen -=3D 8;
+  }
+
+  Reader.SetIdentifierInfo(ID, II);
=20
   // Read all of the declarations visible at global scope with this
   // name.
@@ -573,7 +602,6 @@
     Reader.SetGloballyVisibleDecls(II, DeclIDs);
   }
=20
-  II->setIsFromAST();
   return II;
 }
=20
@@ -724,11 +752,11 @@
                                       unsigned DataLen) {
   using namespace clang::io;
   unsigned NumDecls =3D ReadUnalignedLE16(d);
-  DeclID *Start =3D (DeclID *)d;
+  LE32DeclID *Start =3D (LE32DeclID *)d;
   return std::make_pair(Start, Start + NumDecls);
 }
=20
-bool ASTReader::ReadDeclContextStorage(Module &M,
+bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
                                        llvm::BitstreamCursor &Cursor,
                                    const std::pair<uint64_t, uint64_t> &Of=
fsets,
                                        DeclContextInfo &Info) {
@@ -802,7 +830,7 @@
=20
 /// \brief Read the line table in the source manager block.
 /// \returns true if there was an error.
-bool ASTReader::ParseLineTable(Module &F,
+bool ASTReader::ParseLineTable(ModuleFile &F,
                                SmallVectorImpl<uint64_t> &Record) {
   unsigned Idx =3D 0;
   LineTableInfo &LineTable =3D SourceMgr.getLineTable();
@@ -946,7 +974,7 @@
=20
=20
 /// \brief Read a source manager block
-ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(Module &F) {
+ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
   using namespace SrcMgr;
=20
   llvm::BitstreamCursor &SLocEntryCursor =3D F.SLocEntryCursor;
@@ -1023,10 +1051,10 @@
   assert(OriginalDir !=3D CurrDir &&
          "No point trying to resolve the file if the PCH dir didn't change=
");
   using namespace llvm::sys;
-  llvm::SmallString<128> filePath(Filename);
+  SmallString<128> filePath(Filename);
   fs::make_absolute(filePath);
   assert(path::is_absolute(OriginalDir));
-  llvm::SmallString<128> currPCHPath(CurrDir);
+  SmallString<128> currPCHPath(CurrDir);
=20
   path::const_iterator fileDirI =3D path::begin(path::parent_path(filePath=
)),
                        fileDirE =3D path::end(path::parent_path(filePath));
@@ -1055,7 +1083,7 @@
     return Failure;
   }
=20
-  Module *F =3D GlobalSLocEntryMap.find(-ID)->second;
+  ModuleFile *F =3D GlobalSLocEntryMap.find(-ID)->second;
   F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID=
]);
   llvm::BitstreamCursor &SLocEntryCursor =3D F->SLocEntryCursor;
   unsigned BaseOffset =3D F->SLocEntryBaseOffset;
@@ -1078,9 +1106,24 @@
     return Failure;
=20
   case SM_SLOC_FILE_ENTRY: {
-    std::string Filename(BlobStart, BlobStart + BlobLen);
+    if (Record.size() < 7) {
+      Error("source location entry is incorrect");
+      return Failure;
+    }
+
+    // We will detect whether a file changed and return 'Failure' for it, =
but
+    // we will also try to fail gracefully by setting up the SLocEntry.
+    ASTReader::ASTReadResult Result =3D Success;
+
+    bool OverriddenBuffer =3D Record[6];
+   =20
+    std::string OrigFilename(BlobStart, BlobStart + BlobLen);
+    std::string Filename =3D OrigFilename;
     MaybeAddSystemRootToFilename(Filename);
-    const FileEntry *File =3D FileMgr.getFile(Filename);
+    const FileEntry *File =3D=20
+      OverriddenBuffer? FileMgr.getVirtualFile(Filename, (off_t)Record[4],
+                                               (time_t)Record[5])
+                      : FileMgr.getFile(Filename, /*OpenFile=3D*/false);
     if (File =3D=3D 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
         OriginalDir !=3D CurrentDir) {
       std::string resolved =3D resolveFileRelativeToOriginalDir(Filename,
@@ -1100,11 +1143,6 @@
       return Failure;
     }
=20
-    if (Record.size() < 6) {
-      Error("source location entry is incorrect");
-      return Failure;
-    }
-
     if (!DisableValidation &&
         ((off_t)Record[4] !=3D File->getSize()
 #if !defined(LLVM_ON_WIN32)
@@ -1115,7 +1153,7 @@
 #endif
         )) {
       Error(diag::err_fe_pch_file_modified, Filename);
-      return Failure;
+      Result =3D Failure;
     }
=20
     SourceLocation IncludeLoc =3D ReadSourceLocation(*F, Record[1]);
@@ -1128,10 +1166,40 @@
                                         ID, BaseOffset + Record[0]);
     SrcMgr::FileInfo &FileInfo =3D
           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFil=
e());
-    FileInfo.NumCreatedFIDs =3D Record[6];
+    FileInfo.NumCreatedFIDs =3D Record[7];
     if (Record[3])
       FileInfo.setHasLineDirectives();
+
+    const DeclID *FirstDecl =3D F->FileSortedDecls + Record[8];
+    unsigned NumFileDecls =3D Record[9];
+    if (NumFileDecls) {
+      assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet =
?");
+      FileDeclIDs[FID] =3D FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
+                                                             NumFileDecls)=
);
+    }
    =20
+    const SrcMgr::ContentCache *ContentCache
+      =3D SourceMgr.getOrCreateContentCache(File);
+    if (OverriddenBuffer && !ContentCache->BufferOverridden &&
+        ContentCache->ContentsEntry =3D=3D ContentCache->OrigEntry) {
+      unsigned Code =3D SLocEntryCursor.ReadCode();
+      Record.clear();
+      unsigned RecCode
+        =3D SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
+     =20
+      if (RecCode !=3D SM_SLOC_BUFFER_BLOB) {
+        Error("AST record has invalid code");
+        return Failure;
+      }
+     =20
+      llvm::MemoryBuffer *Buffer
+        =3D llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen =
- 1),
+                                           Filename);
+      SourceMgr.overrideFileContents(File, Buffer);
+    }
+
+    if (Result =3D=3D Failure)
+      return Failure;
     break;
   }
=20
@@ -1149,12 +1217,12 @@
     }
=20
     llvm::MemoryBuffer *Buffer
-    =3D llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
-                                       Name);
+      =3D llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - =
1),
+                                         Name);
     FileID BufferID =3D SourceMgr.createFileIDForMemBuffer(Buffer, ID,
                                                          BaseOffset + Offs=
et);
=20
-    if (strcmp(Name, "<built-in>") =3D=3D 0) {
+    if (strcmp(Name, "<built-in>") =3D=3D 0 && F->Kind =3D=3D MK_PCH) {
       PCHPredefinesBlock Block =3D {
         BufferID,
         StringRef(BlobStart, BlobLen - 1)
@@ -1181,7 +1249,7 @@
 }
=20
 /// \brief Find the location where the module F is imported.
-SourceLocation ASTReader::getImportLocation(Module *F) {
+SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
   if (F->ImportLoc.isValid())
     return F->ImportLoc;
  =20
@@ -1222,7 +1290,7 @@
   }
 }
=20
-void ASTReader::ReadMacroRecord(Module &F, uint64_t Offset) {
+void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
   llvm::BitstreamCursor &Stream =3D F.MacroCursor;
=20
   // Keep track of where we are in the stream, then jump back there
@@ -1276,6 +1344,7 @@
         Error("macro must have a name in AST file");
         return;
       }
+     =20
       SourceLocation Loc =3D ReadSourceLocation(F, Record[1]);
       bool isUsed =3D Record[2];
=20
@@ -1283,8 +1352,9 @@
       MI->setIsUsed(isUsed);
       MI->setIsFromAST();
=20
-      unsigned NextIndex =3D 3;
-      MI->setExportLocation(ReadSourceLocation(F, Record, NextIndex));
+      bool IsPublic =3D Record[3];
+      unsigned NextIndex =3D 4;
+      MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex)=
);
      =20
       if (RecType =3D=3D PP_MACRO_FUNCTION_LIKE) {
         // Decode function-like macro info.
@@ -1304,7 +1374,7 @@
       }
=20
       // Finally, install the macro.
-      PP.setMacroInfo(II, MI);
+      PP.setMacroInfo(II, MI, /*LoadedFromAST=3D*/true);
=20
       // Remember that we saw this macro last so that we add the tokens th=
at
       // form its body to it.
@@ -1340,14 +1410,12 @@
       Macro->AddTokenToBody(Tok);
       break;
     }
-  }
-  }
- =20
-  return;
+    }
+  }
 }
=20
 PreprocessedEntityID=20
-ASTReader::getGlobalPreprocessedEntityID(Module &M, unsigned LocalID) cons=
t {
+ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) =
const {
   ContinuousRangeMap<uint32_t, int, 2>::const_iterator=20
     I =3D M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_ID=
S);
   assert(I !=3D M.PreprocessedEntityRemap.end()=20
@@ -1369,14 +1437,13 @@
  =20
   if (llvm::sys::path::filename(a) !=3D llvm::sys::path::filename(b))
     return false;
- =20
-  // The file names match, but the path names don't. stat() the files to
-  // see if they are the same.     =20
-  struct stat StatBufA, StatBufB;
-  if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
+
+  // Determine whether the actual files are equivalent.
+  bool Result =3D false;
+  if (llvm::sys::fs::equivalent(a, b, Result))
     return false;
  =20
-  return StatBufA.st_ino =3D=3D StatBufB.st_ino;
+  return Result;
 }
    =20
 std::pair<unsigned, unsigned>
@@ -1399,7 +1466,8 @@
   HFI.Resolved =3D (Flags >> 1) & 0x01;
   HFI.IndexHeaderMapHeader =3D Flags & 0x01;
   HFI.NumIncludes =3D ReadUnalignedLE16(d);
-  HFI.ControllingMacroID =3D Reader.getGlobalDeclID(M, ReadUnalignedLE32(d=
));
+  HFI.ControllingMacroID =3D Reader.getGlobalIdentifierID(M,=20
+                                                        ReadUnalignedLE32(=
d));
   if (unsigned FrameworkOffset =3D ReadUnalignedLE32(d)) {
     // The framework offset is 1 greater than the actual offset,=20
     // since 0 is used as an indicator for "no framework name".
@@ -1415,10 +1483,12 @@
   return HFI;
 }
=20
-void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, Module &F,
-                                     uint64_t LocalOffset) {
-  // Note that this identifier has a macro definition.
-  II->setHasMacroDefinition(true);
+void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ModuleFile &F,
+                                     uint64_t LocalOffset, bool Visible) {
+  if (Visible) {
+    // Note that this identifier has a macro definition.
+    II->setHasMacroDefinition(true);
+  }
  =20
   // Adjust the offset to a global offset.
   UnreadMacroRecordOffsets[II] =3D F.GlobalBitOffset + LocalOffset;
@@ -1483,7 +1553,7 @@
 }
=20
 void ASTReader::LoadMacroDefinition(
-                     llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator =
Pos) {
+                    llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator P=
os) {
   assert(Pos !=3D UnreadMacroRecordOffsets.end() && "Unknown macro definit=
ion");
   uint64_t Offset =3D Pos->second;
   UnreadMacroRecordOffsets.erase(Pos);
@@ -1498,6 +1568,72 @@
   LoadMacroDefinition(Pos);
 }
=20
+namespace {
+  /// \brief Visitor class used to look up identifirs in an AST file.
+  class IdentifierLookupVisitor {
+    StringRef Name;
+    unsigned PriorGeneration;
+    IdentifierInfo *Found;
+  public:
+    IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration)=20
+      : Name(Name), PriorGeneration(PriorGeneration), Found() { }
+   =20
+    static bool visit(ModuleFile &M, void *UserData) {
+      IdentifierLookupVisitor *This
+        =3D static_cast<IdentifierLookupVisitor *>(UserData);
+     =20
+      // If we've already searched this module file, skip it now.
+      if (M.Generation <=3D This->PriorGeneration)
+        return true;
+     =20
+      ASTIdentifierLookupTable *IdTable
+        =3D (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
+      if (!IdTable)
+        return false;
+     =20
+      ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
+                                     M, This->Found);
+                                    =20
+      std::pair<const char*, unsigned> Key(This->Name.begin(),=20
+                                           This->Name.size());
+      ASTIdentifierLookupTable::iterator Pos =3D IdTable->find(Key, &Trait=
);
+      if (Pos =3D=3D IdTable->end())
+        return false;
+     =20
+      // Dereferencing the iterator has the effect of building the
+      // IdentifierInfo node and populating it with the various
+      // declarations it needs.
+      This->Found =3D *Pos;
+      return true;
+    }
+   =20
+    // \brief Retrieve the identifier info found within the module
+    // files.
+    IdentifierInfo *getIdentifierInfo() const { return Found; }
+  };
+}
+
+void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
+  unsigned PriorGeneration =3D 0;
+  if (getContext().getLangOpts().Modules)
+    PriorGeneration =3D IdentifierGeneration[&II];
+ =20
+  IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration);
+  ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
+  markIdentifierUpToDate(&II);
+}
+
+void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
+  if (!II)
+    return;
+ =20
+  II->setOutOfDate(false);
+
+  // Update the generation for this identifier.
+  if (getContext().getLangOpts().Modules)
+    IdentifierGeneration[II] =3D CurrentGeneration;
+}
+
 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
   std::string Filename =3D filenameStrRef;
   MaybeAddSystemRootToFilename(Filename);
@@ -1539,7 +1675,7 @@
 }
=20
 ASTReader::ASTReadResult
-ASTReader::ReadASTBlock(Module &F) {
+ASTReader::ReadASTBlock(ModuleFile &F) {
   llvm::BitstreamCursor &Stream =3D F.Stream;
=20
   if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
@@ -1608,7 +1744,7 @@
           =3D F.PreprocessorDetailCursor.GetCurrentBitNo();
          =20
         if (!PP.getPreprocessingRecord())
-          PP.createPreprocessingRecord(true);
+          PP.createPreprocessingRecord(/*RecordConditionalDirectives=3D*/f=
alse);
         if (!PP.getPreprocessingRecord()->getExternalSource())
           PP.getPreprocessingRecord()->SetExternalSource(*this);
         break;
@@ -1626,6 +1762,26 @@
           return IgnorePCH;
         }
         break;
+
+      case SUBMODULE_BLOCK_ID:
+        switch (ReadSubmoduleBlock(F)) {
+        case Success:
+          break;
+         =20
+        case Failure:
+          Error("malformed submodule block in AST file");
+          return Failure;
+         =20
+        case IgnorePCH:
+          return IgnorePCH;           =20
+        }
+        break;
+
+      default:
+        if (!Stream.SkipBlock())
+          break;
+        Error("malformed block record in AST file");
+        return Failure;
       }
       continue;
     }
@@ -1651,6 +1807,12 @@
         return IgnorePCH;
       }
=20
+      bool hasErrors =3D Record[5];
+      if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
+        Diag(diag::err_pch_with_compiler_errors);
+        return IgnorePCH;
+      }
+
       RelocatablePCH =3D Record[4];
       if (Listener) {
         std::string TargetTriple(BlobStart, BlobLen);
@@ -1667,7 +1829,7 @@
         // Read information about the AST file.
         ModuleKind ImportedKind =3D (ModuleKind)Record[Idx++];
         unsigned Length =3D Record[Idx++];
-        llvm::SmallString<128> ImportedFile(Record.begin() + Idx,
+        SmallString<128> ImportedFile(Record.begin() + Idx,
                                             Record.begin() + Idx + Length);
         Idx +=3D Length;
=20
@@ -1697,8 +1859,9 @@
         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
        =20
         // Introduce the local -> global mapping for types within this mod=
ule.
-        F.TypeRemap.insert(std::make_pair(LocalBaseTypeIndex,=20
-                             F.BaseTypeIndex - LocalBaseTypeIndex));
+        F.TypeRemap.insertOrReplace(
+          std::make_pair(LocalBaseTypeIndex,=20
+                         F.BaseTypeIndex - LocalBaseTypeIndex));
        =20
         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
       }
@@ -1710,7 +1873,7 @@
         Error("duplicate DECL_OFFSET record in AST file");
         return Failure;
       }
-      F.DeclOffsets =3D (const uint32_t *)BlobStart;
+      F.DeclOffsets =3D (const DeclOffset *)BlobStart;
       F.LocalNumDecls =3D Record[0];
       unsigned LocalBaseDeclID =3D Record[1];
       F.BaseDeclID =3D getTotalNumDecls();
@@ -1723,8 +1886,12 @@
        =20
         // Introduce the local -> global mapping for declarations within t=
his
         // module.
-        F.DeclRemap.insert(std::make_pair(LocalBaseDeclID,=20
-                                          F.BaseDeclID - LocalBaseDeclID));
+        F.DeclRemap.insertOrReplace(
+          std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
+       =20
+        // Introduce the global -> local mapping for declarations within t=
his
+        // module.
+        F.GlobalToLocalDeclIDs[&F] =3D LocalBaseDeclID;
        =20
         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
       }
@@ -1757,16 +1924,6 @@
       break;
     }
=20
-    case REDECLS_UPDATE_LATEST: {
-      assert(Record.size() % 2 =3D=3D 0 && "Expected pairs of DeclIDs");
-      for (unsigned i =3D 0, e =3D Record.size(); i < e; /* in loop */) {
-        DeclID First =3D ReadDeclID(F, Record, i);
-        DeclID Latest =3D ReadDeclID(F, Record, i);
-        FirstLatestDeclIDs[First] =3D Latest;
-      }
-      break;
-    }
-
     case LANGUAGE_OPTIONS:
       if (ParseLanguageOptions(Record) && !DisableValidation)
         return IgnorePCH;
@@ -1803,9 +1960,9 @@
        =20
         // Introduce the local -> global mapping for identifiers within th=
is
         // module.
-        F.IdentifierRemap.insert(
-                            std::make_pair(LocalBaseIdentifierID,
-                              F.BaseIdentifierID - LocalBaseIdentifierID));
+        F.IdentifierRemap.insertOrReplace(
+          std::make_pair(LocalBaseIdentifierID,
+                         F.BaseIdentifierID - LocalBaseIdentifierID));
        =20
         IdentifiersLoaded.resize(IdentifiersLoaded.size()=20
                                  + F.LocalNumIdentifiers);
@@ -1880,8 +2037,9 @@
        =20
         // Introduce the local -> global mapping for selectors within this=20
         // module.
-        F.SelectorRemap.insert(std::make_pair(LocalBaseSelectorID,
-                                 F.BaseSelectorID - LocalBaseSelectorID));
+        F.SelectorRemap.insertOrReplace(
+          std::make_pair(LocalBaseSelectorID,
+                         F.BaseSelectorID - LocalBaseSelectorID));
=20
         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelector=
s);       =20
       }
@@ -1914,6 +2072,10 @@
       if (!Record.empty() && Listener)
         Listener->ReadCounter(Record[0]);
       break;
+     =20
+    case FILE_SORTED_DECLS:
+      F.FileSortedDecls =3D (const DeclID *)BlobStart;
+      break;
=20
     case SOURCE_LOCATION_OFFSETS: {
       F.SLocEntryOffsets =3D (const uint32_t *)BlobStart;
@@ -1959,6 +2121,8 @@
       ContinuousRangeMap<uint32_t, int, 2>::Builder=20
         PreprocessedEntityRemap(F.PreprocessedEntityRemap);
       ContinuousRangeMap<uint32_t, int, 2>::Builder=20
+        SubmoduleRemap(F.SubmoduleRemap);
+      ContinuousRangeMap<uint32_t, int, 2>::Builder=20
         SelectorRemap(F.SelectorRemap);
       ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
       ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
@@ -1967,7 +2131,7 @@
         uint16_t Len =3D io::ReadUnalignedLE16(Data);
         StringRef Name =3D StringRef((const char*)Data, Len);
         Data +=3D Len;
-        Module *OM =3D ModuleMgr.lookup(Name);
+        ModuleFile *OM =3D ModuleMgr.lookup(Name);
         if (!OM) {
           Error("SourceLocation remap refers to unknown module");
           return Failure;
@@ -1976,6 +2140,7 @@
         uint32_t SLocOffset =3D io::ReadUnalignedLE32(Data);
         uint32_t IdentifierIDOffset =3D io::ReadUnalignedLE32(Data);
         uint32_t PreprocessedEntityIDOffset =3D io::ReadUnalignedLE32(Data=
);
+        uint32_t SubmoduleIDOffset =3D io::ReadUnalignedLE32(Data);
         uint32_t SelectorIDOffset =3D io::ReadUnalignedLE32(Data);
         uint32_t DeclIDOffset =3D io::ReadUnalignedLE32(Data);
         uint32_t TypeIndexOffset =3D io::ReadUnalignedLE32(Data);
@@ -1989,6 +2154,8 @@
         PreprocessedEntityRemap.insert(
           std::make_pair(PreprocessedEntityIDOffset,=20
             OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
+        SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,=20
+                                      OM->BaseSubmoduleID - SubmoduleIDOff=
set));
         SelectorRemap.insert(std::make_pair(SelectorIDOffset,=20
                                OM->BaseSelectorID - SelectorIDOffset));
         DeclRemap.insert(std::make_pair(DeclIDOffset,=20
@@ -1996,6 +2163,9 @@
        =20
         TypeRemap.insert(std::make_pair(TypeIndexOffset,=20
                                     OM->BaseTypeIndex - TypeIndexOffset));
+
+        // Global -> local mappings.
+        F.GlobalToLocalDeclIDs[OM] =3D DeclIDOffset;
       }
       break;
     }
@@ -2124,7 +2294,7 @@
      =20
       unsigned StartingID;
       if (!PP.getPreprocessingRecord())
-        PP.createPreprocessingRecord(true);
+        PP.createPreprocessingRecord(/*RecordConditionalDirectives=3D*/fal=
se);
       if (!PP.getPreprocessingRecord()->getExternalSource())
         PP.getPreprocessingRecord()->SetExternalSource(*this);
       StartingID=20
@@ -2139,7 +2309,7 @@
       =20
         // Introduce the local -> global mapping for preprocessed entities=
 in
         // this module.
-        F.PreprocessedEntityRemap.insert(
+        F.PreprocessedEntityRemap.insertOrReplace(
           std::make_pair(LocalBasePreprocessedEntityID,
             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
       }
@@ -2159,30 +2329,31 @@
     }
=20
     case DECL_REPLACEMENTS: {
-      if (Record.size() % 2 !=3D 0) {
+      if (Record.size() % 3 !=3D 0) {
         Error("invalid DECL_REPLACEMENTS block in AST file");
         return Failure;
       }
-      for (unsigned I =3D 0, N =3D Record.size(); I !=3D N; I +=3D 2)
+      for (unsigned I =3D 0, N =3D Record.size(); I !=3D N; I +=3D 3)
         ReplacedDecls[getGlobalDeclID(F, Record[I])]
-          =3D std::make_pair(&F, Record[I+1]);
+          =3D ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
       break;
     }
=20
-    case OBJC_CHAINED_CATEGORIES: {
-      if (Record.size() % 3 !=3D 0) {
-        Error("invalid OBJC_CHAINED_CATEGORIES block in AST file");
+    case OBJC_CATEGORIES_MAP: {
+      if (F.LocalNumObjCCategoriesInMap !=3D 0) {
+        Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
         return Failure;
       }
-      for (unsigned I =3D 0, N =3D Record.size(); I !=3D N; I +=3D 3) {
-        serialization::GlobalDeclID GlobID =3D getGlobalDeclID(F, Record[I=
]);
-        F.ChainedObjCCategories[GlobID] =3D std::make_pair(Record[I+1],
-                                                         Record[I+2]);
-        ObjCChainedCategoriesInterfaces.insert(GlobID);
-      }
+     =20
+      F.LocalNumObjCCategoriesInMap =3D Record[0];
+      F.ObjCCategoriesMap =3D (const ObjCCategoriesInfo *)BlobStart;
       break;
     }
        =20
+    case OBJC_CATEGORIES:
+      F.ObjCCategories.swap(Record);
+      break;
+       =20
     case CXX_BASE_SPECIFIER_OFFSETS: {
       if (F.LocalNumCXXBaseSpecifiers !=3D 0) {
         Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
@@ -2255,13 +2426,52 @@
       for (unsigned I =3D 0, N =3D Record.size(); I !=3D N; ++I)
         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
       break;
+       =20
+    case IMPORTED_MODULES: {
+      if (F.Kind !=3D MK_Module) {
+        // If we aren't loading a module (which has its own exports), make
+        // all of the imported modules visible.
+        // FIXME: Deal with macros-only imports.
+        for (unsigned I =3D 0, N =3D Record.size(); I !=3D N; ++I) {
+          if (unsigned GlobalID =3D getGlobalSubmoduleID(F, Record[I]))
+            ImportedModules.push_back(GlobalID);
+        }
+      }
+      break;
+    }
+
+    case LOCAL_REDECLARATIONS: {
+      F.RedeclarationChains.swap(Record);
+      break;
+    }
+       =20
+    case LOCAL_REDECLARATIONS_MAP: {
+      if (F.LocalNumRedeclarationsInMap !=3D 0) {
+        Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
+        return Failure;
+      }
+     =20
+      F.LocalNumRedeclarationsInMap =3D Record[0];
+      F.RedeclarationsMap =3D (const LocalRedeclarationsInfo *)BlobStart;
+      break;
+    }
+       =20
+    case MERGED_DECLARATIONS: {
+      for (unsigned Idx =3D 0; Idx < Record.size(); /* increment in loop *=
/) {
+        GlobalDeclID CanonID =3D getGlobalDeclID(F, Record[Idx++]);
+        SmallVectorImpl<GlobalDeclID> &Decls =3D StoredMergedDecls[CanonID=
];
+        for (unsigned N =3D Record[Idx++]; N > 0; --N)
+          Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
+      }
+      break;
+    }
     }
   }
   Error("premature end of bitstream in AST file");
   return Failure;
 }
=20
-ASTReader::ASTReadResult ASTReader::validateFileEntries(Module &M) {
+ASTReader::ASTReadResult ASTReader::validateFileEntries(ModuleFile &M) {
   llvm::BitstreamCursor &SLocEntryCursor =3D M.SLocEntryCursor;
=20
   for (unsigned i =3D 0, e =3D M.LocalNumSLocFileEntries; i !=3D e; ++i) {
@@ -2283,6 +2493,10 @@
       return Failure;
=20
     case SM_SLOC_FILE_ENTRY: {
+      // If the buffer was overridden, the file need not exist.
+      if (Record[6])
+        break;
+     =20
       StringRef Filename(BlobStart, BlobLen);
       const FileEntry *File =3D getFileEntry(Filename);
=20
@@ -2294,7 +2508,7 @@
         return IgnorePCH;
       }
=20
-      if (Record.size() < 6) {
+      if (Record.size() < 7) {
         Error("source location entry is incorrect");
         return Failure;
       }
@@ -2327,45 +2541,125 @@
   return Success;
 }
=20
-namespace {
-  /// \brief Visitor class used to look up identifirs in an AST file.
-  class IdentifierLookupVisitor {
-    StringRef Name;
-    IdentifierInfo *Found;
-  public:
-    explicit IdentifierLookupVisitor(StringRef Name) : Name(Name), Found()=
 { }
+void ASTReader::makeNamesVisible(const HiddenNames &Names) {
+  for (unsigned I =3D 0, N =3D Names.size(); I !=3D N; ++I) {
+    if (Decl *D =3D Names[I].dyn_cast<Decl *>())
+      D->Hidden =3D false;
+    else {
+      IdentifierInfo *II =3D Names[I].get<IdentifierInfo *>();
+      if (!II->hasMacroDefinition()) {
+        II->setHasMacroDefinition(true);
+        if (DeserializationListener)
+          DeserializationListener->MacroVisible(II);
+      }
+    }
+  }
+}
+
+void ASTReader::makeModuleVisible(Module *Mod,=20
+                                  Module::NameVisibilityKind NameVisibilit=
y) {
+  llvm::SmallPtrSet<Module *, 4> Visited;
+  llvm::SmallVector<Module *, 4> Stack;
+  Stack.push_back(Mod); =20
+  while (!Stack.empty()) {
+    Mod =3D Stack.back();
+    Stack.pop_back();
+
+    if (NameVisibility <=3D Mod->NameVisibility) {
+      // This module already has this level of visibility (or greater), so=20
+      // there is nothing more to do.
+      continue;
+    }
    =20
-    static bool visit(Module &M, void *UserData) {
-      IdentifierLookupVisitor *This
-      =3D static_cast<IdentifierLookupVisitor *>(UserData);
+    if (!Mod->isAvailable()) {
+      // Modules that aren't available cannot be made visible.
+      continue;
+    }
+
+    // Update the module's name visibility.
+    Mod->NameVisibility =3D NameVisibility;
+   =20
+    // If we've already deserialized any names from this module,
+    // mark them as visible.
+    HiddenNamesMapType::iterator Hidden =3D HiddenNamesMap.find(Mod);
+    if (Hidden !=3D HiddenNamesMap.end()) {
+      makeNamesVisible(Hidden->second);
+      HiddenNamesMap.erase(Hidden);
+    }
+   =20
+    // Push any non-explicit submodules onto the stack to be marked as
+    // visible.
+    for (Module::submodule_iterator Sub =3D Mod->submodule_begin(),
+                                 SubEnd =3D Mod->submodule_end();
+         Sub !=3D SubEnd; ++Sub) {
+      if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
+        Stack.push_back(*Sub);
+    }
+   =20
+    // Push any exported modules onto the stack to be marked as visible.
+    bool AnyWildcard =3D false;
+    bool UnrestrictedWildcard =3D false;
+    llvm::SmallVector<Module *, 4> WildcardRestrictions;
+    for (unsigned I =3D 0, N =3D Mod->Exports.size(); I !=3D N; ++I) {
+      Module *Exported =3D Mod->Exports[I].getPointer();
+      if (!Mod->Exports[I].getInt()) {
+        // Export a named module directly; no wildcards involved.
+        if (Visited.insert(Exported))
+          Stack.push_back(Exported);
+       =20
+        continue;
+      }
      =20
-      ASTIdentifierLookupTable *IdTable
-        =3D (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
-      if (!IdTable)
-        return false;
+      // Wildcard export: export all of the imported modules that match
+      // the given pattern.
+      AnyWildcard =3D true;
+      if (UnrestrictedWildcard)
+        continue;
+
+      if (Module *Restriction =3D Mod->Exports[I].getPointer())
+        WildcardRestrictions.push_back(Restriction);
+      else {
+        WildcardRestrictions.clear();
+        UnrestrictedWildcard =3D true;
+      }
+    }
+   =20
+    // If there were any wildcards, push any imported modules that were
+    // re-exported by the wildcard restriction.
+    if (!AnyWildcard)
+      continue;
+   =20
+    for (unsigned I =3D 0, N =3D Mod->Imports.size(); I !=3D N; ++I) {
+      Module *Imported =3D Mod->Imports[I];
+      if (Visited.count(Imported))
+        continue;
      =20
-      std::pair<const char*, unsigned> Key(This->Name.begin(),=20
-                                           This->Name.size());
-      ASTIdentifierLookupTable::iterator Pos =3D IdTable->find(Key);
-      if (Pos =3D=3D IdTable->end())
-        return false;
+      bool Acceptable =3D UnrestrictedWildcard;
+      if (!Acceptable) {
+        // Check whether this module meets one of the restrictions.
+        for (unsigned R =3D 0, NR =3D WildcardRestrictions.size(); R !=3D =
NR; ++R) {
+          Module *Restriction =3D WildcardRestrictions[R];
+          if (Imported =3D=3D Restriction || Imported->isSubModuleOf(Restr=
iction)) {
+            Acceptable =3D true;
+            break;
+          }
+        }
+      }
      =20
-      // Dereferencing the iterator has the effect of building the
-      // IdentifierInfo node and populating it with the various
-      // declarations it needs.
-      This->Found =3D *Pos;
-      return true;
-    }
-   =20
-    // \brief Retrieve the identifier info found within the module
-    // files.
-    IdentifierInfo *getIdentifierInfo() const { return Found; }
-  };
-}
-
+      if (!Acceptable)
+        continue;
+     =20
+      Visited.insert(Imported);
+      Stack.push_back(Imported);
+    }
+  }
+}
=20
 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
                                             ModuleKind Type) {
+  // Bump the generation number.
+  unsigned PreviousGeneration =3D CurrentGeneration++;
+ =20
   switch(ReadASTCore(FileName, Type, /*ImportedBy=3D*/0)) {
   case Failure: return Failure;
   case IgnorePCH: return IgnorePCH;
@@ -2373,57 +2667,66 @@
   }
=20
   // Here comes stuff that we only do once the entire chain is loaded.
- =20
+
   // Check the predefines buffers.
-  if (!DisableValidation && Type !=3D MK_Module && Type !=3D MK_Preamble &&
+  if (!DisableValidation && Type =3D=3D MK_PCH &&
       // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
       // if DisableValidation is true, defines that were set on command-li=
ne
       // but not in the PCH file will not be added to SuggestedPredefines.
       CheckPredefinesBuffers())
     return IgnorePCH;
=20
-  // Initialization of keywords and pragmas occurs before the
-  // AST file is read, so there may be some identifiers that were
-  // loaded into the IdentifierTable before we intercepted the
-  // creation of identifiers. Iterate through the list of known
-  // identifiers and determine whether we have to establish
-  // preprocessor definitions or top-level identifier declaration
-  // chains for those identifiers.
-  //
-  // We copy the IdentifierInfo pointers to a small vector first,
-  // since de-serializing declarations or macro definitions can add
-  // new entries into the identifier table, invalidating the
-  // iterators.
-  //
-  // FIXME: We need a lazier way to load this information, e.g., by marking
-  // the identifier data as 'dirty', so that it will be looked up in the
-  // AST file(s) if it is uttered in the source. This could save us some
-  // module load time.
-  SmallVector<IdentifierInfo *, 128> Identifiers;
+  // Mark all of the identifiers in the identifier table as being out of d=
ate,
+  // so that various accessors know to check the loaded modules when the
+  // identifier is used.
   for (IdentifierTable::iterator Id =3D PP.getIdentifierTable().begin(),
                               IdEnd =3D PP.getIdentifierTable().end();
        Id !=3D IdEnd; ++Id)
-    Identifiers.push_back(Id->second);
+    Id->second->setOutOfDate(true);
  =20
-  for (unsigned I =3D 0, N =3D Identifiers.size(); I !=3D N; ++I) {
-    IdentifierLookupVisitor Visitor(Identifiers[I]->getName());
-    ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
-  }
-
+  // Resolve any unresolved module exports.
+  for (unsigned I =3D 0, N =3D UnresolvedModuleImportExports.size(); I !=
=3D N; ++I) {
+    UnresolvedModuleImportExport &Unresolved =3D UnresolvedModuleImportExp=
orts[I];
+    SubmoduleID GlobalID =3D getGlobalSubmoduleID(*Unresolved.File,Unresol=
ved.ID);
+    Module *ResolvedMod =3D getSubmodule(GlobalID);
+   =20
+    if (Unresolved.IsImport) {
+      if (ResolvedMod)
+        Unresolved.Mod->Imports.push_back(ResolvedMod);
+      continue;
+    }
+
+    if (ResolvedMod || Unresolved.IsWildcard)
+      Unresolved.Mod->Exports.push_back(
+        Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
+  }
+  UnresolvedModuleImportExports.clear();
+ =20
   InitializeContext();
=20
   if (DeserializationListener)
     DeserializationListener->ReaderInitialized(this);
=20
-  // If this AST file is a precompiled preamble, then set the preamble fil=
e ID
-  // of the source manager to the file source file from which the preamble=
 was
-  // built.
-  if (Type =3D=3D MK_Preamble) {
-    if (!OriginalFileID.isInvalid()) {
-      OriginalFileID =3D FileID::get(ModuleMgr.getPrimaryModule().SLocEntr=
yBaseID
-                                        + OriginalFileID.getOpaqueValue() =
- 1);
+  if (!OriginalFileID.isInvalid()) {
+    OriginalFileID =3D FileID::get(ModuleMgr.getPrimaryModule().SLocEntryB=
aseID
+                                      + OriginalFileID.getOpaqueValue() - =
1);
+
+    // If this AST file is a precompiled preamble, then set the preamble f=
ile ID
+    // of the source manager to the file source file from which the preamb=
le was
+    // built.
+    if (Type =3D=3D MK_Preamble) {
       SourceMgr.setPreambleFileID(OriginalFileID);
-    }
+    } else if (Type =3D=3D MK_MainFile) {
+      SourceMgr.setMainFileID(OriginalFileID);
+    }
+  }
+ =20
+  // For any Objective-C class definitions we have already loaded, make su=
re
+  // that we load any additional categories.
+  for (unsigned I =3D 0, N =3D ObjCClassesLoaded.size(); I !=3D N; ++I) {
+    loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),=20
+                       ObjCClassesLoaded[I],
+                       PreviousGeneration);
   }
  =20
   return Success;
@@ -2431,12 +2734,12 @@
=20
 ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName,
                                                 ModuleKind Type,
-                                                Module *ImportedBy) {
-  Module *M;
+                                                ModuleFile *ImportedBy) {
+  ModuleFile *M;
   bool NewModule;
   std::string ErrorStr;
   llvm::tie(M, NewModule) =3D ModuleMgr.addModule(FileName, Type, Imported=
By,
-                                                ErrorStr);
+                                                CurrentGeneration, ErrorSt=
r);
=20
   if (!M) {
     // We couldn't load the module.
@@ -2458,7 +2761,7 @@
     if (CurrentDir.empty()) CurrentDir =3D ".";
   }
=20
-  Module &F =3D *M;
+  ModuleFile &F =3D *M;
   llvm::BitstreamCursor &Stream =3D F.Stream;
   Stream.init(F.StreamFile);
   F.SizeInBits =3D F.Buffer->getBufferSize() * 8;
@@ -2522,7 +2825,7 @@
     }
   }
  =20
-  // Once read, set the Module bit base offset and update the size in=20
+  // Once read, set the ModuleFile bit base offset and update the size in=20
   // bits of all files we've seen.
   F.GlobalBitOffset =3D TotalModulesSizeInBits;
   TotalModulesSizeInBits +=3D F.SizeInBits;
@@ -2566,17 +2869,12 @@
   // built-in types. Right now, we just ignore the problem.
  =20
   // Load the special types.
-  if (SpecialTypes.size() > NumSpecialTypeIDs) {
+  if (SpecialTypes.size() >=3D NumSpecialTypeIDs) {
     if (Context.getBuiltinVaListType().isNull()) {
       Context.setBuiltinVaListType(
         GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
     }
    =20
-    if (unsigned Proto =3D SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL]) {
-      if (Context.ObjCProtoType.isNull())
-        Context.ObjCProtoType =3D GetType(Proto);
-    }
-   =20
     if (unsigned String =3D SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING])=
 {
       if (!Context.CFConstantStringTypeDecl)
         Context.setCFConstantStringType(GetType(String));
@@ -2603,7 +2901,7 @@
       }
     }
    =20
-    if (unsigned Jmp_buf =3D SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
+    if (unsigned Jmp_buf =3D SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
       QualType Jmp_bufType =3D GetType(Jmp_buf);
       if (Jmp_bufType.isNull()) {
         Error("jmp_buf type is NULL");
@@ -2624,7 +2922,7 @@
       }
     }
    =20
-    if (unsigned Sigjmp_buf =3D SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
+    if (unsigned Sigjmp_buf =3D SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
       QualType Sigjmp_bufType =3D GetType(Sigjmp_buf);
       if (Sigjmp_bufType.isNull()) {
         Error("sigjmp_buf type is NULL");
@@ -2687,6 +2985,22 @@
     Context.setcudaConfigureCallDecl(
                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[=
0])));
   }
+ =20
+  // Re-export any modules that were imported by a non-module AST file.
+  for (unsigned I =3D 0, N =3D ImportedModules.size(); I !=3D N; ++I) {
+    if (Module *Imported =3D getSubmodule(ImportedModules[I]))
+      makeModuleVisible(Imported, Module::AllVisible);
+  }
+  ImportedModules.clear();
+}
+
+void ASTReader::finalizeForWriting() {
+  for (HiddenNamesMapType::iterator Hidden =3D HiddenNamesMap.begin(),
+                                 HiddenEnd =3D HiddenNamesMap.end();
+       Hidden !=3D HiddenEnd; ++Hidden) {
+    makeNamesVisible(Hidden->second);
+  }
+  HiddenNamesMap.clear();
 }
=20
 /// \brief Retrieve the name of the original source file name
@@ -2697,7 +3011,7 @@
                                              DiagnosticsEngine &Diags) {
   // Open the AST file.
   std::string ErrStr;
-  llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
+  OwningPtr<llvm::MemoryBuffer> Buffer;
   Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
   if (!Buffer) {
     Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
@@ -2770,6 +3084,251 @@
   return std::string();
 }
=20
+ASTReader::ASTReadResult ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
+  // Enter the submodule block.
+  if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
+    Error("malformed submodule block record in AST file");
+    return Failure;
+  }
+
+  ModuleMap &ModMap =3D PP.getHeaderSearchInfo().getModuleMap();
+  bool First =3D true;
+  Module *CurrentModule =3D 0;
+  RecordData Record;
+  while (true) {
+    unsigned Code =3D F.Stream.ReadCode();
+    if (Code =3D=3D llvm::bitc::END_BLOCK) {
+      if (F.Stream.ReadBlockEnd()) {
+        Error("error at end of submodule block in AST file");
+        return Failure;
+      }
+      return Success;
+    }
+   =20
+    if (Code =3D=3D llvm::bitc::ENTER_SUBBLOCK) {
+      // No known subblocks, always skip them.
+      F.Stream.ReadSubBlockID();
+      if (F.Stream.SkipBlock()) {
+        Error("malformed block record in AST file");
+        return Failure;
+      }
+      continue;
+    }
+   =20
+    if (Code =3D=3D llvm::bitc::DEFINE_ABBREV) {
+      F.Stream.ReadAbbrevRecord();
+      continue;
+    }
+   =20
+    // Read a record.
+    const char *BlobStart;
+    unsigned BlobLen;
+    Record.clear();
+    switch (F.Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
+    default:  // Default behavior: ignore.
+      break;
+     =20
+    case SUBMODULE_DEFINITION: {
+      if (First) {
+        Error("missing submodule metadata record at beginning of block");
+        return Failure;
+      }
+
+      if (Record.size() < 7) {
+        Error("malformed module definition");
+        return Failure;
+      }
+     =20
+      StringRef Name(BlobStart, BlobLen);
+      SubmoduleID GlobalID =3D getGlobalSubmoduleID(F, Record[0]);
+      SubmoduleID Parent =3D getGlobalSubmoduleID(F, Record[1]);
+      bool IsFramework =3D Record[2];
+      bool IsExplicit =3D Record[3];
+      bool IsSystem =3D Record[4];
+      bool InferSubmodules =3D Record[5];
+      bool InferExplicitSubmodules =3D Record[6];
+      bool InferExportWildcard =3D Record[7];
+     =20
+      Module *ParentModule =3D 0;
+      if (Parent)
+        ParentModule =3D getSubmodule(Parent);
+     =20
+      // Retrieve this (sub)module from the module map, creating it if
+      // necessary.
+      CurrentModule =3D ModMap.findOrCreateModule(Name, ParentModule,=20
+                                                IsFramework,=20
+                                                IsExplicit).first;
+      SubmoduleID GlobalIndex =3D GlobalID - NUM_PREDEF_SUBMODULE_IDS;
+      if (GlobalIndex >=3D SubmodulesLoaded.size() ||
+          SubmodulesLoaded[GlobalIndex]) {
+        Error("too many submodules");
+        return Failure;
+      }
+     =20
+      CurrentModule->IsFromModuleFile =3D true;
+      CurrentModule->IsSystem =3D IsSystem || CurrentModule->IsSystem;
+      CurrentModule->InferSubmodules =3D InferSubmodules;
+      CurrentModule->InferExplicitSubmodules =3D InferExplicitSubmodules;
+      CurrentModule->InferExportWildcard =3D InferExportWildcard;
+      if (DeserializationListener)
+        DeserializationListener->ModuleRead(GlobalID, CurrentModule);
+     =20
+      SubmodulesLoaded[GlobalIndex] =3D CurrentModule;
+      break;
+    }
+       =20
+    case SUBMODULE_UMBRELLA_HEADER: {
+      if (First) {
+        Error("missing submodule metadata record at beginning of block");
+        return Failure;
+      }
+
+      if (!CurrentModule)
+        break;
+     =20
+      StringRef FileName(BlobStart, BlobLen);
+      if (const FileEntry *Umbrella =3D PP.getFileManager().getFile(FileNa=
me)) {
+        if (!CurrentModule->getUmbrellaHeader())
+          ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
+        else if (CurrentModule->getUmbrellaHeader() !=3D Umbrella) {
+          Error("mismatched umbrella headers in submodule");
+          return Failure;
+        }
+      }
+      break;
+    }
+       =20
+    case SUBMODULE_HEADER: {
+      if (First) {
+        Error("missing submodule metadata record at beginning of block");
+        return Failure;
+      }
+
+      if (!CurrentModule)
+        break;
+     =20
+      // FIXME: Be more lazy about this!
+      StringRef FileName(BlobStart, BlobLen);
+      if (const FileEntry *File =3D PP.getFileManager().getFile(FileName))=
 {
+        if (std::find(CurrentModule->Headers.begin(),=20
+                      CurrentModule->Headers.end(),=20
+                      File) =3D=3D CurrentModule->Headers.end())
+          ModMap.addHeader(CurrentModule, File);
+      }
+      break;     =20
+    }
+       =20
+    case SUBMODULE_UMBRELLA_DIR: {
+      if (First) {
+        Error("missing submodule metadata record at beginning of block");
+        return Failure;
+      }
+     =20
+      if (!CurrentModule)
+        break;
+     =20
+      StringRef DirName(BlobStart, BlobLen);
+      if (const DirectoryEntry *Umbrella
+                                  =3D PP.getFileManager().getDirectory(Dir=
Name)) {
+        if (!CurrentModule->getUmbrellaDir())
+          ModMap.setUmbrellaDir(CurrentModule, Umbrella);
+        else if (CurrentModule->getUmbrellaDir() !=3D Umbrella) {
+          Error("mismatched umbrella directories in submodule");
+          return Failure;
+        }
+      }
+      break;
+    }
+       =20
+    case SUBMODULE_METADATA: {
+      if (!First) {
+        Error("submodule metadata record not at beginning of block");
+        return Failure;
+      }
+      First =3D false;
+     =20
+      F.BaseSubmoduleID =3D getTotalNumSubmodules();
+      F.LocalNumSubmodules =3D Record[0];
+      unsigned LocalBaseSubmoduleID =3D Record[1];
+      if (F.LocalNumSubmodules > 0) {
+        // Introduce the global -> local mapping for submodules within thi=
s=20
+        // module.
+        GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1=
,&F));
+       =20
+        // Introduce the local -> global mapping for submodules within thi=
s=20
+        // module.
+        F.SubmoduleRemap.insertOrReplace(
+          std::make_pair(LocalBaseSubmoduleID,
+                         F.BaseSubmoduleID - LocalBaseSubmoduleID));
+       =20
+        SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmod=
ules);
+      }     =20
+      break;
+    }
+       =20
+    case SUBMODULE_IMPORTS: {
+      if (First) {
+        Error("missing submodule metadata record at beginning of block");
+        return Failure;
+      }
+     =20
+      if (!CurrentModule)
+        break;
+     =20
+      for (unsigned Idx =3D 0; Idx !=3D Record.size(); ++Idx) {
+        UnresolvedModuleImportExport Unresolved;
+        Unresolved.File =3D &F;
+        Unresolved.Mod =3D CurrentModule;
+        Unresolved.ID =3D Record[Idx];
+        Unresolved.IsImport =3D true;
+        Unresolved.IsWildcard =3D false;
+        UnresolvedModuleImportExports.push_back(Unresolved);
+      }
+      break;
+    }
+
+    case SUBMODULE_EXPORTS: {
+      if (First) {
+        Error("missing submodule metadata record at beginning of block");
+        return Failure;
+      }
+     =20
+      if (!CurrentModule)
+        break;
+     =20
+      for (unsigned Idx =3D 0; Idx + 1 < Record.size(); Idx +=3D 2) {
+        UnresolvedModuleImportExport Unresolved;
+        Unresolved.File =3D &F;
+        Unresolved.Mod =3D CurrentModule;
+        Unresolved.ID =3D Record[Idx];
+        Unresolved.IsImport =3D false;
+        Unresolved.IsWildcard =3D Record[Idx + 1];
+        UnresolvedModuleImportExports.push_back(Unresolved);
+      }
+     =20
+      // Once we've loaded the set of exports, there's no reason to keep=20
+      // the parsed, unresolved exports around.
+      CurrentModule->UnresolvedExports.clear();
+      break;
+    }
+    case SUBMODULE_REQUIRES: {
+      if (First) {
+        Error("missing submodule metadata record at beginning of block");
+        return Failure;
+      }
+
+      if (!CurrentModule)
+        break;
+
+      CurrentModule->addRequirement(StringRef(BlobStart, BlobLen),=20
+                                    Context.getLangOpts(),
+                                    Context.getTargetInfo());
+      break;
+    }
+    }
+  }
+}
+
 /// \brief Parse the record that corresponds to a LangOptions data
 /// structure.
 ///
@@ -2788,20 +3347,31 @@
   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
 #include "clang/Basic/LangOptions.def"
    =20
+    unsigned Length =3D Record[Idx++];
+    LangOpts.CurrentModule.assign(Record.begin() + Idx,=20
+                                  Record.begin() + Idx + Length);
     return Listener->ReadLanguageOptions(LangOpts);
   }
=20
   return false;
 }
=20
+std::pair<ModuleFile *, unsigned>
+ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
+  GlobalPreprocessedEntityMapType::iterator
+  I =3D GlobalPreprocessedEntityMap.find(GlobalIndex);
+  assert(I !=3D GlobalPreprocessedEntityMap.end() &&=20
+         "Corrupted global preprocessed entity map");
+  ModuleFile *M =3D I->second;
+  unsigned LocalIndex =3D GlobalIndex - M->BasePreprocessedEntityID;
+  return std::make_pair(M, LocalIndex);
+}
+
 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
   PreprocessedEntityID PPID =3D Index+1;
-  GlobalPreprocessedEntityMapType::iterator
-    I =3D GlobalPreprocessedEntityMap.find(Index);
-  assert(I !=3D GlobalPreprocessedEntityMap.end() &&=20
-         "Corrupted global preprocessed entity map");
-  Module &M =3D *I->second;
-  unsigned LocalIndex =3D Index - M.BasePreprocessedEntityID;
+  std::pair<ModuleFile *, unsigned> PPInfo =3D getModulePreprocessedEntity=
(Index);
+  ModuleFile &M =3D *PPInfo.first;
+  unsigned LocalIndex =3D PPInfo.second;
   const PPEntityOffset &PPOffs =3D M.PreprocessedEntityOffsets[LocalIndex];
=20
   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor); =20
@@ -2876,9 +3446,10 @@
      =20
   case PPD_INCLUSION_DIRECTIVE: {
     const char *FullFileNameStart =3D BlobStart + Record[0];
-    const FileEntry *File
-      =3D PP.getFileManager().getFile(StringRef(FullFileNameStart,
-                                               BlobLen - Record[0]));
+    StringRef FullFileName(FullFileNameStart, BlobLen - Record[0]);
+    const FileEntry *File =3D 0;
+    if (!FullFileName.empty())
+      File =3D PP.getFileManager().getFile(FullFileName);
    =20
     // FIXME: Stable encoding
     InclusionDirective::InclusionKind Kind
@@ -2892,9 +3463,8 @@
     return ID;
   }
   }
- =20
-  Error("invalid offset in preprocessor detail block");
-  return 0;
+
+  llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
 }
=20
 /// \brief \arg SLocMapI points at a chunk of a module that contains no
@@ -2906,7 +3476,7 @@
   ++SLocMapI;
   for (GlobalSLocOffsetMapType::const_iterator
          EndI =3D GlobalSLocOffsetMap.end(); SLocMapI !=3D EndI; ++SLocMap=
I) {
-    Module &M =3D *SLocMapI->second;
+    ModuleFile &M =3D *SLocMapI->second;
     if (M.NumPreprocessedEntities)
       return getGlobalPreprocessedEntityID(M, M.BasePreprocessedEntityID);
   }
@@ -2919,9 +3489,9 @@
 template <unsigned PPEntityOffset::*PPLoc>
 struct PPEntityComp {
   const ASTReader &Reader;
-  Module &M;
-
-  PPEntityComp(const ASTReader &Reader, Module &M) : Reader(Reader), M(M) =
{ }
+  ModuleFile &M;
+
+  PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M=
(M) { }
=20
   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
     SourceLocation LHS =3D getLoc(L);
@@ -2961,7 +3531,7 @@
   if (SLocMapI->second->NumPreprocessedEntities =3D=3D 0)
     return findNextPreprocessedEntity(SLocMapI);
=20
-  Module &M =3D *SLocMapI->second;
+  ModuleFile &M =3D *SLocMapI->second;
   typedef const PPEntityOffset *pp_iterator;
   pp_iterator pp_begin =3D M.PreprocessedEntityOffsets;
   pp_iterator pp_end =3D pp_begin + M.NumPreprocessedEntities;
@@ -3010,7 +3580,7 @@
   if (SLocMapI->second->NumPreprocessedEntities =3D=3D 0)
     return findNextPreprocessedEntity(SLocMapI);
=20
-  Module &M =3D *SLocMapI->second;
+  ModuleFile &M =3D *SLocMapI->second;
   typedef const PPEntityOffset *pp_iterator;
   pp_iterator pp_begin =3D M.PreprocessedEntityOffsets;
   pp_iterator pp_end =3D pp_begin + M.NumPreprocessedEntities;
@@ -3038,6 +3608,28 @@
   return std::make_pair(BeginID, EndID);
 }
=20
+/// \brief Optionally returns true or false if the preallocated preprocess=
ed
+/// entity with index \arg Index came from file \arg FID.
+llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Inde=
x,
+                                                             FileID FID) {
+  if (FID.isInvalid())
+    return false;
+
+  std::pair<ModuleFile *, unsigned> PPInfo =3D getModulePreprocessedEntity=
(Index);
+  ModuleFile &M =3D *PPInfo.first;
+  unsigned LocalIndex =3D PPInfo.second;
+  const PPEntityOffset &PPOffs =3D M.PreprocessedEntityOffsets[LocalIndex];
+ =20
+  SourceLocation Loc =3D ReadSourceLocation(M, PPOffs.Begin);
+  if (Loc.isInvalid())
+    return false;
+ =20
+  if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
+    return true;
+  else
+    return false;
+}
+
 namespace {
   /// \brief Visitor used to search for information about a header file.
   class HeaderFileInfoVisitor {
@@ -3050,7 +3642,7 @@
     HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
       : Reader(Reader), FE(FE) { }
    =20
-    static bool visit(Module &M, void *UserData) {
+    static bool visit(ModuleFile &M, void *UserData) {
       HeaderFileInfoVisitor *This
         =3D static_cast<HeaderFileInfoVisitor *>(UserData);
      =20
@@ -3092,10 +3684,14 @@
=20
 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
   for (ModuleIterator I =3D ModuleMgr.begin(), E =3D ModuleMgr.end(); I !=
=3D E; ++I) {
-    Module &F =3D *(*I);
+    ModuleFile &F =3D *(*I);
     unsigned Idx =3D 0;
     while (Idx < F.PragmaDiagMappings.size()) {
       SourceLocation Loc =3D ReadSourceLocation(F, F.PragmaDiagMappings[Id=
x++]);
+      Diag.DiagStates.push_back(*Diag.GetCurDiagState());
+      Diag.DiagStatePoints.push_back(
+          DiagnosticsEngine::DiagStatePoint(&Diag.DiagStates.back(),
+                                            FullSourceLoc(Loc, SourceMgr))=
);
       while (1) {
         assert(Idx < F.PragmaDiagMappings.size() &&
                "Invalid data, didn't find '-1' marking end of diag/map pai=
rs");
@@ -3108,8 +3704,8 @@
           break; // no more diag/map pairs for this location.
         }
         diag::Mapping Map =3D (diag::Mapping)F.PragmaDiagMappings[Idx++];
-        // The user bit gets set by WritePragmaDiagnosticMappings.
-        Diag.setDiagnosticMapping(DiagID, Map, Loc);
+        DiagnosticMappingInfo MappingInfo =3D Diag.makeMappingInfo(Map, Lo=
c);
+        Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
       }
     }
   }
@@ -3119,7 +3715,7 @@
 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
   GlobalTypeMapType::iterator I =3D GlobalTypeMap.find(Index);
   assert(I !=3D GlobalTypeMap.end() && "Corrupted global type map");
-  Module *M =3D I->second;
+  ModuleFile *M =3D I->second;
   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
 }
=20
@@ -3295,14 +3891,15 @@
       ParamTypes.push_back(readType(*Loc.F, Record, Idx));
=20
     EPI.Variadic =3D Record[Idx++];
+    EPI.HasTrailingReturn =3D Record[Idx++];
     EPI.TypeQuals =3D Record[Idx++];
     EPI.RefQualifier =3D static_cast<RefQualifierKind>(Record[Idx++]);
     ExceptionSpecificationType EST =3D
         static_cast<ExceptionSpecificationType>(Record[Idx++]);
     EPI.ExceptionSpecType =3D EST;
+    SmallVector<QualType, 2> Exceptions;
     if (EST =3D=3D EST_Dynamic) {
       EPI.NumExceptions =3D Record[Idx++];
-      SmallVector<QualType, 2> Exceptions;
       for (unsigned I =3D 0; I !=3D EPI.NumExceptions; ++I)
         Exceptions.push_back(readType(*Loc.F, Record, Idx));
       EPI.Exceptions =3D Exceptions.data();
@@ -3344,8 +3941,10 @@
     return Context.getTypeOfType(UnderlyingType);
   }
=20
-  case TYPE_DECLTYPE:
-    return Context.getDecltypeType(ReadExpr(*Loc.F));
+  case TYPE_DECLTYPE: {
+    QualType UnderlyingType =3D readType(*Loc.F, Record, Idx);
+    return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
+  }
=20
   case TYPE_UNARY_TRANSFORM: {
     QualType BaseType =3D readType(*Loc.F, Record, Idx);
@@ -3364,8 +3963,9 @@
     }
     unsigned Idx =3D 0;
     bool IsDependent =3D Record[Idx++];
-    QualType T
-      =3D Context.getRecordType(ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx=
));
+    RecordDecl *RD =3D ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
+    RD =3D cast_or_null<RecordDecl>(RD->getCanonicalDecl());
+    QualType T =3D Context.getRecordType(RD);
     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
     return T;
   }
@@ -3429,7 +4029,7 @@
     unsigned Idx =3D 0;
     ObjCInterfaceDecl *ItfD
       =3D ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
-    return Context.getObjCInterfaceType(ItfD);
+    return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
   }
=20
   case TYPE_OBJC_OBJECT: {
@@ -3554,13 +4154,12 @@
     return Context.getAtomicType(ValueType);
   }
   }
-  // Suppress a GCC warning
-  return QualType();
+  llvm_unreachable("Invalid TypeCode!");
 }
=20
 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
   ASTReader &Reader;
-  Module &F;
+  ModuleFile &F;
   llvm::BitstreamCursor &DeclsCursor;
   const ASTReader::RecordData &Record;
   unsigned &Idx;
@@ -3576,7 +4175,7 @@
   }
  =20
 public:
-  TypeLocReader(ASTReader &Reader, Module &F,
+  TypeLocReader(ASTReader &Reader, ModuleFile &F,
                 const ASTReader::RecordData &Record, unsigned &Idx)
     : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Id=
x(Idx)
   { }
@@ -3733,6 +4332,7 @@
 }
 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
                                            TemplateSpecializationTypeLoc T=
L) {
+  TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
@@ -3747,22 +4347,23 @@
   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
 }
 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
-  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
+  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
 }
 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc=
 TL) {
   TL.setNameLoc(ReadSourceLocation(Record, Idx));
 }
 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
-  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
+  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
   TL.setNameLoc(ReadSourceLocation(Record, Idx));
 }
 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
        DependentTemplateSpecializationTypeLoc TL) {
-  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
+  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
-  TL.setNameLoc(ReadSourceLocation(Record, Idx));
+  TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
+  TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
   for (unsigned I =3D 0, E =3D TL.getNumArgs(); I !=3D E; ++I)
@@ -3793,7 +4394,7 @@
   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
 }
=20
-TypeSourceInfo *ASTReader::GetTypeSourceInfo(Module &F,
+TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
                                              const RecordData &Record,
                                              unsigned &Idx) {
   QualType InfoTy =3D readType(F, Record, Idx);
@@ -3843,6 +4444,7 @@
     case PREDEF_TYPE_LONGDOUBLE_ID: T =3D Context.LongDoubleTy;       brea=
k;
     case PREDEF_TYPE_OVERLOAD_ID:   T =3D Context.OverloadTy;         brea=
k;
     case PREDEF_TYPE_BOUND_MEMBER:  T =3D Context.BoundMemberTy;      brea=
k;
+    case PREDEF_TYPE_PSEUDO_OBJECT: T =3D Context.PseudoObjectTy;     brea=
k;
     case PREDEF_TYPE_DEPENDENT_ID:  T =3D Context.DependentTy;        brea=
k;
     case PREDEF_TYPE_UNKNOWN_ANY:   T =3D Context.UnknownAnyTy;       brea=
k;
     case PREDEF_TYPE_NULLPTR_ID:    T =3D Context.NullPtrTy;          brea=
k;
@@ -3856,6 +4458,11 @@
     case PREDEF_TYPE_AUTO_RREF_DEDUCT:=20
       T =3D Context.getAutoRRefDeductType();=20
       break;
+
+    case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
+      T =3D Context.ARCUnbridgedCastTy;
+      break;
+
     }
=20
     assert(!T.isNull() && "Unknown predefined type");
@@ -3878,12 +4485,12 @@
   return TypesLoaded[Index].withFastQualifiers(FastQuals);
 }
=20
-QualType ASTReader::getLocalType(Module &F, unsigned LocalID) {
+QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
   return GetType(getGlobalTypeID(F, LocalID));
 }
=20
 serialization::TypeID=20
-ASTReader::getGlobalTypeID(Module &F, unsigned LocalID) const {
+ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
   unsigned FastQuals =3D LocalID & Qualifiers::FastMask;
   unsigned LocalIndex =3D LocalID >> Qualifiers::FastWidth;
  =20
@@ -3899,7 +4506,7 @@
 }
=20
 TemplateArgumentLocInfo
-ASTReader::GetTemplateArgumentLocInfo(Module &F,
+ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
                                       TemplateArgument::ArgKind Kind,
                                       const RecordData &Record,
                                       unsigned &Index) {
@@ -3930,11 +4537,10 @@
     return TemplateArgumentLocInfo();
   }
   llvm_unreachable("unexpected template argument loc");
-  return TemplateArgumentLocInfo();
 }
=20
 TemplateArgumentLoc
-ASTReader::ReadTemplateArgumentLoc(Module &F,
+ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
                                    const RecordData &Record, unsigned &Ind=
ex) {
   TemplateArgument Arg =3D ReadTemplateArgument(F, Record, Index);
=20
@@ -3950,7 +4556,7 @@
   return GetDecl(ID);
 }
=20
-uint64_t ASTReader::readCXXBaseSpecifiers(Module &M, const RecordData &Rec=
ord,=20
+uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData =
&Record,=20
                                           unsigned &Idx){
   if (Idx >=3D Record.size())
     return 0;
@@ -3983,7 +4589,7 @@
 }
=20
 serialization::DeclID=20
-ASTReader::getGlobalDeclID(Module &F, unsigned LocalID) const {
+ASTReader::getGlobalDeclID(ModuleFile &F, unsigned LocalID) const {
   if (LocalID < NUM_PREDEF_DECL_IDS)
     return LocalID;
=20
@@ -3995,12 +4601,39 @@
 }
=20
 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
-                                   Module &M) const {
+                                   ModuleFile &M) const {
   GlobalDeclMapType::const_iterator I =3D GlobalDeclMap.find(ID);
   assert(I !=3D GlobalDeclMap.end() && "Corrupted global declaration map");
   return &M =3D=3D I->second;
 }
=20
+ModuleFile *ASTReader::getOwningModuleFile(Decl *D) {
+  if (!D->isFromASTFile())
+    return 0;
+  GlobalDeclMapType::const_iterator I =3D GlobalDeclMap.find(D->getGlobalI=
D());
+  assert(I !=3D GlobalDeclMap.end() && "Corrupted global declaration map");
+  return I->second;
+}
+
+SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
+  if (ID < NUM_PREDEF_DECL_IDS)
+    return SourceLocation();
+ =20
+  unsigned Index =3D ID - NUM_PREDEF_DECL_IDS;
+
+  if (Index > DeclsLoaded.size()) {
+    Error("declaration ID out-of-range for AST file");
+    return SourceLocation();
+  }
+ =20
+  if (Decl *D =3D DeclsLoaded[Index])
+    return D->getLocation();
+
+  unsigned RawLocation =3D 0;
+  RecordLocation Rec =3D DeclCursorForID(ID, RawLocation);
+  return ReadSourceLocation(*Rec.F, RawLocation);
+}
+
 Decl *ASTReader::GetDecl(DeclID ID) {
   if (ID < NUM_PREDEF_DECL_IDS) {   =20
     switch ((PredefinedDeclIDs)ID) {
@@ -4019,6 +4652,9 @@
     case PREDEF_DECL_OBJC_CLASS_ID:
       return Context.getObjCClassDecl();
        =20
+    case PREDEF_DECL_OBJC_PROTOCOL_ID:
+      return Context.getObjCProtocolDecl();
+       =20
     case PREDEF_DECL_INT_128_ID:
       return Context.getInt128Decl();
=20
@@ -4028,18 +4664,15 @@
     case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
       return Context.getObjCInstanceTypeDecl();
     }
-   =20
-    return 0;
   }
  =20
   unsigned Index =3D ID - NUM_PREDEF_DECL_IDS;
=20
-  if (Index > DeclsLoaded.size()) {
+  if (Index >=3D DeclsLoaded.size()) {
     Error("declaration ID out-of-range for AST file");
-    return 0;
   }
  =20
-if (!DeclsLoaded[Index]) {
+  if (!DeclsLoaded[Index]) {
     ReadDeclRecord(ID);
     if (DeserializationListener)
       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
@@ -4048,7 +4681,24 @@
   return DeclsLoaded[Index];
 }
=20
-serialization::DeclID ASTReader::ReadDeclID(Module &F,=20
+DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,=20
+                                                  DeclID GlobalID) {
+  if (GlobalID < NUM_PREDEF_DECL_IDS)
+    return GlobalID;
+ =20
+  GlobalDeclMapType::const_iterator I =3D GlobalDeclMap.find(GlobalID);
+  assert(I !=3D GlobalDeclMap.end() && "Corrupted global declaration map");
+  ModuleFile *Owner =3D I->second;
+
+  llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
+    =3D M.GlobalToLocalDeclIDs.find(Owner);
+  if (Pos =3D=3D M.GlobalToLocalDeclIDs.end())
+    return 0;
+     =20
+  return GlobalID - Owner->BaseDeclID + Pos->second;
+}
+
+serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,=20
                                             const RecordData &Record,
                                             unsigned &Idx) {
   if (Idx >=3D Record.size()) {
@@ -4093,14 +4743,14 @@
         PredefsVisited[I] =3D false;
     }
=20
-    static bool visit(Module &M, bool Preorder, void *UserData) {
+    static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
       if (Preorder)
         return false;
=20
       FindExternalLexicalDeclsVisitor *This
         =3D static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
=20
-      Module::DeclContextInfosMap::iterator Info
+      ModuleFile::DeclContextInfosMap::iterator Info
         =3D M.DeclContextInfos.find(This->DC);
       if (Info =3D=3D M.DeclContextInfos.end() || !Info->second.LexicalDec=
ls)
         return false;
@@ -4144,31 +4794,118 @@
 }
=20
 namespace {
-  /// \brief Module visitor used to perform name lookup into a
+
+class DeclIDComp {
+  ASTReader &Reader;
+  ModuleFile &Mod;
+
+public:
+  DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
+
+  bool operator()(LocalDeclID L, LocalDeclID R) const {
+    SourceLocation LHS =3D getLocation(L);
+    SourceLocation RHS =3D getLocation(R);
+    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
+  }
+
+  bool operator()(SourceLocation LHS, LocalDeclID R) const {
+    SourceLocation RHS =3D getLocation(R);
+    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
+  }
+
+  bool operator()(LocalDeclID L, SourceLocation RHS) const {
+    SourceLocation LHS =3D getLocation(L);
+    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
+  }
+
+  SourceLocation getLocation(LocalDeclID ID) const {
+    return Reader.getSourceManager().getFileLoc(
+            Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, =
ID)));
+  }
+};
+
+}
+
+void ASTReader::FindFileRegionDecls(FileID File,
+                                    unsigned Offset, unsigned Length,
+                                    SmallVectorImpl<Decl *> &Decls) {
+  SourceManager &SM =3D getSourceManager();
+
+  llvm::DenseMap<FileID, FileDeclsInfo>::iterator I =3D FileDeclIDs.find(F=
ile);
+  if (I =3D=3D FileDeclIDs.end())
+    return;
+
+  FileDeclsInfo &DInfo =3D I->second;
+  if (DInfo.Decls.empty())
+    return;
+
+  SourceLocation
+    BeginLoc =3D SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
+  SourceLocation EndLoc =3D BeginLoc.getLocWithOffset(Length);
+
+  DeclIDComp DIDComp(*this, *DInfo.Mod);
+  ArrayRef<serialization::LocalDeclID>::iterator
+    BeginIt =3D std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
+                               BeginLoc, DIDComp);
+  if (BeginIt !=3D DInfo.Decls.begin())
+    --BeginIt;
+
+  // If we are pointing at a top-level decl inside an objc container, we n=
eed
+  // to backtrack until we find it otherwise we will fail to report that t=
he
+  // region overlaps with an objc container.
+  while (BeginIt !=3D DInfo.Decls.begin() &&
+         GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
+             ->isTopLevelDeclInObjCContainer())
+    --BeginIt;
+
+  ArrayRef<serialization::LocalDeclID>::iterator
+    EndIt =3D std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
+                             EndLoc, DIDComp);
+  if (EndIt !=3D DInfo.Decls.end())
+    ++EndIt;
+ =20
+  for (ArrayRef<serialization::LocalDeclID>::iterator
+         DIt =3D BeginIt; DIt !=3D EndIt; ++DIt)
+    Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
+}
+
+namespace {
+  /// \brief ModuleFile visitor used to perform name lookup into a
   /// declaration context.
   class DeclContextNameLookupVisitor {
     ASTReader &Reader;
+    llvm::SmallVectorImpl<const DeclContext *> &Contexts;
     const DeclContext *DC;
     DeclarationName Name;
     SmallVectorImpl<NamedDecl *> &Decls;
=20
   public:
     DeclContextNameLookupVisitor(ASTReader &Reader,=20
-                                 const DeclContext *DC, DeclarationName Na=
me,
+                                 SmallVectorImpl<const DeclContext *> &Con=
texts,=20
+                                 DeclarationName Name,
                                  SmallVectorImpl<NamedDecl *> &Decls)
-      : Reader(Reader), DC(DC), Name(Name), Decls(Decls) { }
-
-    static bool visit(Module &M, void *UserData) {
+      : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
+
+    static bool visit(ModuleFile &M, void *UserData) {
       DeclContextNameLookupVisitor *This
         =3D static_cast<DeclContextNameLookupVisitor *>(UserData);
=20
       // Check whether we have any visible declaration information for
       // this context in this module.
-      Module::DeclContextInfosMap::iterator Info
-        =3D M.DeclContextInfos.find(This->DC);
-      if (Info =3D=3D M.DeclContextInfos.end() || !Info->second.NameLookup=
TableData)
+      ModuleFile::DeclContextInfosMap::iterator Info;
+      bool FoundInfo =3D false;
+      for (unsigned I =3D 0, N =3D This->Contexts.size(); I !=3D N; ++I) {
+        Info =3D M.DeclContextInfos.find(This->Contexts[I]);
+        if (Info !=3D M.DeclContextInfos.end() &&=20
+            Info->second.NameLookupTableData) {
+          FoundInfo =3D true;
+          break;
+        }
+      }
+
+      if (!FoundInfo)
         return false;
-
+     =20
       // Look for this name within this module.
       ASTDeclContextNameLookupTable *LookupTable =3D
         (ASTDeclContextNameLookupTable*)Info->second.NameLookupTableData;
@@ -4210,13 +4947,75 @@
                                       DeclContext::lookup_iterator(0));
=20
   SmallVector<NamedDecl *, 64> Decls;
-  DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls);
+ =20
+  // Compute the declaration contexts we need to look into. Multiple such
+  // declaration contexts occur when two declaration contexts from disjoint
+  // modules get merged, e.g., when two namespaces with the same name are=20
+  // independently defined in separate modules.
+  SmallVector<const DeclContext *, 2> Contexts;
+  Contexts.push_back(DC);
+ =20
+  if (DC->isNamespace()) {
+    MergedDeclsMap::iterator Merged
+      =3D MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
+    if (Merged !=3D MergedDecls.end()) {
+      for (unsigned I =3D 0, N =3D Merged->second.size(); I !=3D N; ++I)
+        Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
+    }
+  }
+ =20
+  DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
   ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
   ++NumVisibleDeclContextsRead;
   SetExternalVisibleDeclsForName(DC, Name, Decls);
   return const_cast<DeclContext*>(DC)->lookup(Name);
 }
=20
+namespace {
+  /// \brief ModuleFile visitor used to complete the visible decls map of a
+  /// declaration context.
+  class DeclContextVisibleDeclMapVisitor {
+    ASTReader &Reader;
+    DeclContext *DC;
+
+  public:
+    DeclContextVisibleDeclMapVisitor(ASTReader &Reader, DeclContext *DC)
+      : Reader(Reader), DC(DC) { }
+
+    static bool visit(ModuleFile &M, void *UserData) {
+      return static_cast<DeclContextVisibleDeclMapVisitor*>(UserData)->vis=
it(M);
+    }
+
+    bool visit(ModuleFile &M) {
+      // Check whether we have any visible declaration information for
+      // this context in this module.
+      ModuleFile::DeclContextInfosMap::iterator
+        Info =3D M.DeclContextInfos.find(DC);
+      if (Info =3D=3D M.DeclContextInfos.end() ||=20
+          !Info->second.NameLookupTableData)
+        return false;
+     =20
+      // Look for this name within this module.
+      ASTDeclContextNameLookupTable *LookupTable =3D
+        (ASTDeclContextNameLookupTable*)Info->second.NameLookupTableData;
+      for (ASTDeclContextNameLookupTable::key_iterator
+             I =3D LookupTable->key_begin(),
+             E =3D LookupTable->key_end(); I !=3D E; ++I) {
+        DC->lookup(*I); // Force loading of the visible decls for the decl=
 name.
+      }
+
+      return false;
+    }
+  };
+}
+
+void ASTReader::completeVisibleDeclsMap(DeclContext *DC) {
+  if (!DC->hasExternalVisibleStorage())
+    return;
+  DeclContextVisibleDeclMapVisitor Visitor(*this, DC);
+  ModuleMgr.visit(&DeclContextVisibleDeclMapVisitor::visit, &Visitor);
+}
+
 /// \brief Under non-PCH compilation the consumer receives the objc methods
 /// before receiving the implementation, and codegen depends on this.
 /// We simulate this by deserializing and passing to consumer the methods =
of the
@@ -4238,11 +5037,15 @@
     Decl *D =3D InterestingDecls.front();
     InterestingDecls.pop_front();
=20
-    if (ObjCImplDecl *ImplD =3D dyn_cast<ObjCImplDecl>(D))
-      PassObjCImplDeclToConsumer(ImplD, Consumer);
-    else
-      Consumer->HandleInterestingDecl(DeclGroupRef(D));
-  }
+    PassInterestingDeclToConsumer(D);
+  }
+}
+
+void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
+  if (ObjCImplDecl *ImplD =3D dyn_cast<ObjCImplDecl>(D))
+    PassObjCImplDeclToConsumer(ImplD, Consumer);
+  else
+    Consumer->HandleInterestingDecl(DeclGroupRef(D));
 }
=20
 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
@@ -4331,15 +5134,15 @@
   std::fprintf(stderr, "\n");
 }
=20
-template<typename Key, typename Module, unsigned InitialCapacity>
+template<typename Key, typename ModuleFile, unsigned InitialCapacity>
 static void=20
 dumpModuleIDMap(StringRef Name,
-                const ContinuousRangeMap<Key, Module *,=20
+                const ContinuousRangeMap<Key, ModuleFile *,=20
                                          InitialCapacity> &Map) {
   if (Map.begin() =3D=3D Map.end())
     return;
  =20
-  typedef ContinuousRangeMap<Key, Module *, InitialCapacity> MapType;
+  typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
   llvm::errs() << Name << ":\n";
   for (typename MapType::const_iterator I =3D Map.begin(), IEnd =3D Map.en=
d();=20
        I !=3D IEnd; ++I) {
@@ -4349,12 +5152,13 @@
 }
=20
 void ASTReader::dump() {
-  llvm::errs() << "*** PCH/Module Remappings:\n";
+  llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
   dumpModuleIDMap("Global type map", GlobalTypeMap);
   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
+  dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
   dumpModuleIDMap("Global preprocessed entity map",=20
                   GlobalPreprocessedEntityMap);
@@ -4392,10 +5196,8 @@
   // Makes sure any declarations that were deserialized "too early"
   // still get added to the identifier's declaration chains.
   for (unsigned I =3D 0, N =3D PreloadedDecls.size(); I !=3D N; ++I) {
-    if (SemaObj->TUScope)
-      SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
-
-    SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
+    SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I],=20
+                                       PreloadedDecls[I]->getDeclName());
   }
   PreloadedDecls.clear();
=20
@@ -4424,9 +5226,12 @@
 }
=20
 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd)=
 {
-  IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart=
));
+  IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart=
),
+                                  /*PriorGeneration=3D*/0);
   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
-  return Visitor.getIdentifierInfo();
+  IdentifierInfo *II =3D Visitor.getIdentifierInfo();
+  markIdentifierUpToDate(II);
+  return II;
 }
=20
 namespace clang {
@@ -4491,45 +5296,27 @@
 namespace clang { namespace serialization {
   class ReadMethodPoolVisitor {
     ASTReader &Reader;
-    Selector Sel;   =20
+    Selector Sel;
+    unsigned PriorGeneration;
     llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
     llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
=20
-    /// \brief Build an ObjCMethodList from a vector of Objective-C method
-    /// declarations.
-    ObjCMethodList=20
-    buildObjCMethodList(const SmallVectorImpl<ObjCMethodDecl *> &Vec) const
-    {
-      ObjCMethodList List;
-      ObjCMethodList *Prev =3D 0;
-      for (unsigned I =3D 0, N =3D Vec.size(); I !=3D N; ++I) {
-        if (!List.Method) {
-          // This is the first method, which is the easy case.
-          List.Method =3D Vec[I];
-          Prev =3D &List;
-          continue;
-        }
-       =20
-        ObjCMethodList *Mem =3D
-          Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
-        Prev->Next =3D new (Mem) ObjCMethodList(Vec[I], 0);
-        Prev =3D Prev->Next;
-      }
-     =20
-      return List;
-    }
+  public:
+    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,=20
+                          unsigned PriorGeneration)
+      : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
    =20
-  public:
-    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel)
-      : Reader(Reader), Sel(Sel) { }
-   =20
-    static bool visit(Module &M, void *UserData) {
+    static bool visit(ModuleFile &M, void *UserData) {
       ReadMethodPoolVisitor *This
         =3D static_cast<ReadMethodPoolVisitor *>(UserData);
      =20
       if (!M.SelectorLookupTable)
         return false;
      =20
+      // If we've already searched this module file, skip it now.
+      if (M.Generation <=3D This->PriorGeneration)
+        return true;
+
       ASTSelectorLookupTable *PoolTable
         =3D (ASTSelectorLookupTable*)M.SelectorLookupTable;
       ASTSelectorLookupTable::iterator Pos =3D PoolTable->find(This->Sel);
@@ -4552,28 +5339,50 @@
     }
    =20
     /// \brief Retrieve the instance methods found by this visitor.
-    ObjCMethodList getInstanceMethods() const {=20
-      return buildObjCMethodList(InstanceMethods);=20
+    ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {=20
+      return InstanceMethods;=20
     }
=20
     /// \brief Retrieve the instance methods found by this visitor.
-    ObjCMethodList getFactoryMethods() const {=20
-      return buildObjCMethodList(FactoryMethods);=20
+    ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {=20
+      return FactoryMethods;
     }
   };
 } } // end namespace clang::serialization
=20
-std::pair<ObjCMethodList, ObjCMethodList>
-ASTReader::ReadMethodPool(Selector Sel) {
-  ReadMethodPoolVisitor Visitor(*this, Sel);
+/// \brief Add the given set of methods to the method list.
+static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
+                             ObjCMethodList &List) {
+  for (unsigned I =3D 0, N =3D Methods.size(); I !=3D N; ++I) {
+    S.addMethodToGlobalList(&List, Methods[I]);
+  }
+}
+                            =20
+void ASTReader::ReadMethodPool(Selector Sel) {
+  // Get the selector generation and update it to the current generation.
+  unsigned &Generation =3D SelectorGeneration[Sel];
+  unsigned PriorGeneration =3D Generation;
+  Generation =3D CurrentGeneration;
+ =20
+  // Search for methods defined with this selector.
+  ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
   ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
-  std::pair<ObjCMethodList, ObjCMethodList> Result;
-  Result.first =3D Visitor.getInstanceMethods();
-  Result.second =3D Visitor.getFactoryMethods();
  =20
-  if (!Result.first.Method && !Result.second.Method)
+  if (Visitor.getInstanceMethods().empty() &&
+      Visitor.getFactoryMethods().empty()) {
     ++NumMethodPoolMisses;
-  return Result;
+    return;
+  }
+ =20
+  if (!getSema())
+    return;
+ =20
+  Sema &S =3D *getSema();
+  Sema::GlobalMethodPool::iterator Pos
+    =3D S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).fi=
rst;
+ =20
+  addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
+  addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
 }
=20
 void ASTReader::ReadKnownNamespaces(
@@ -4755,13 +5564,10 @@
   for (unsigned I =3D 0, N =3D DeclIDs.size(); I !=3D N; ++I) {
     NamedDecl *D =3D cast<NamedDecl>(GetDecl(DeclIDs[I]));
     if (SemaObj) {
-      if (SemaObj->TUScope) {
-        // Introduce this declaration into the translation-unit scope
-        // and add it to the declaration chain for this identifier, so
-        // that (unqualified) name lookup will find it.
-        SemaObj->TUScope->AddDecl(D);
-      }
-      SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
+      // Introduce this declaration into the translation-unit scope
+      // and add it to the declaration chain for this identifier, so
+      // that (unqualified) name lookup will find it.
+      SemaObj->pushExternalDeclIntoScope(D, II);
     } else {
       // Queue this declaration so that it will be added to the
       // translation unit scope and identifier's declaration chain
@@ -4784,7 +5590,7 @@
   if (!IdentifiersLoaded[ID]) {
     GlobalIdentifierMapType::iterator I =3D GlobalIdentifierMap.find(ID + =
1);
     assert(I !=3D GlobalIdentifierMap.end() && "Corrupted global identifie=
r map");
-    Module *M =3D I->second;
+    ModuleFile *M =3D I->second;
     unsigned Index =3D ID - M->BaseIdentifierID;
     const char *Str =3D M->IdentifierTableData + M->IdentifierOffsets[Inde=
x];
=20
@@ -4805,11 +5611,11 @@
   return IdentifiersLoaded[ID];
 }
=20
-IdentifierInfo *ASTReader::getLocalIdentifier(Module &M, unsigned LocalID)=
 {
+IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned Loca=
lID) {
   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
 }
=20
-IdentifierID ASTReader::getGlobalIdentifierID(Module &M, unsigned LocalID)=
 {
+IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned Loca=
lID) {
   if (LocalID < NUM_PREDEF_IDENT_IDS)
     return LocalID;
  =20
@@ -4825,7 +5631,34 @@
   return ReadSLocEntryRecord(ID) !=3D Success;
 }
=20
-Selector ASTReader::getLocalSelector(Module &M, unsigned LocalID) {
+serialization::SubmoduleID
+ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
+  if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
+    return LocalID;
+ =20
+  ContinuousRangeMap<uint32_t, int, 2>::iterator I
+    =3D M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
+  assert(I !=3D M.SubmoduleRemap.end()=20
+         && "Invalid index into identifier index remap");
+ =20
+  return LocalID + I->second;
+}
+
+Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
+  if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
+    assert(GlobalID =3D=3D 0 && "Unhandled global submodule ID");
+    return 0;
+  }
+ =20
+  if (GlobalID > SubmodulesLoaded.size()) {
+    Error("submodule ID out of range in AST file");
+    return 0;
+  }
+ =20
+  return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
+}
+                              =20
+Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
   return DecodeSelector(getGlobalSelectorID(M, LocalID));
 }
=20
@@ -4842,7 +5675,7 @@
     // Load this selector from the selector table.
     GlobalSelectorMapType::iterator I =3D GlobalSelectorMap.find(ID);
     assert(I !=3D GlobalSelectorMap.end() && "Corrupted global selector ma=
p");
-    Module &M =3D *I->second;
+    ModuleFile &M =3D *I->second;
     ASTSelectorLookupTrait Trait(*this, M);
     unsigned Idx =3D ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
     SelectorsLoaded[ID - 1] =3D
@@ -4864,7 +5697,7 @@
 }
=20
 serialization::SelectorID
-ASTReader::getGlobalSelectorID(Module &M, unsigned LocalID) const {
+ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
     return LocalID;
  =20
@@ -4877,7 +5710,7 @@
 }
=20
 DeclarationName
-ASTReader::ReadDeclarationName(Module &F,=20
+ASTReader::ReadDeclarationName(ModuleFile &F,=20
                                const RecordData &Record, unsigned &Idx) {
   DeclarationName::NameKind Kind =3D (DeclarationName::NameKind)Record[Idx=
++];
   switch (Kind) {
@@ -4913,11 +5746,10 @@
     return DeclarationName::getUsingDirectiveName();
   }
=20
-  // Required to silence GCC warning
-  return DeclarationName();
-}
-
-void ASTReader::ReadDeclarationNameLoc(Module &F,
+  llvm_unreachable("Invalid NameKind!");
+}
+
+void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
                                        DeclarationNameLoc &DNLoc,
                                        DeclarationName Name,
                                       const RecordData &Record, unsigned &=
Idx) {
@@ -4949,7 +5781,7 @@
   }
 }
=20
-void ASTReader::ReadDeclarationNameInfo(Module &F,
+void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
                                         DeclarationNameInfo &NameInfo,
                                       const RecordData &Record, unsigned &=
Idx) {
   NameInfo.setName(ReadDeclarationName(F, Record, Idx));
@@ -4959,7 +5791,7 @@
   NameInfo.setInfo(DNLoc);
 }
=20
-void ASTReader::ReadQualifierInfo(Module &F, QualifierInfo &Info,
+void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
                                   const RecordData &Record, unsigned &Idx)=
 {
   Info.QualifierLoc =3D ReadNestedNameSpecifierLoc(F, Record, Idx);
   unsigned NumTPLists =3D Record[Idx++];
@@ -4972,7 +5804,7 @@
 }
=20
 TemplateName
-ASTReader::ReadTemplateName(Module &F, const RecordData &Record,=20
+ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,=20
                             unsigned &Idx) {
   TemplateName::NameKind Kind =3D (TemplateName::NameKind)Record[Idx++];
   switch (Kind) {
@@ -5031,7 +5863,7 @@
 }
=20
 TemplateArgument
-ASTReader::ReadTemplateArgument(Module &F,
+ASTReader::ReadTemplateArgument(ModuleFile &F,
                                 const RecordData &Record, unsigned &Idx) {
   TemplateArgument::ArgKind Kind =3D (TemplateArgument::ArgKind)Record[Idx=
++];
   switch (Kind) {
@@ -5070,7 +5902,7 @@
 }
=20
 TemplateParameterList *
-ASTReader::ReadTemplateParameterList(Module &F,
+ASTReader::ReadTemplateParameterList(ModuleFile &F,
                                      const RecordData &Record, unsigned &I=
dx) {
   SourceLocation TemplateLoc =3D ReadSourceLocation(F, Record, Idx);
   SourceLocation LAngleLoc =3D ReadSourceLocation(F, Record, Idx);
@@ -5091,7 +5923,7 @@
 void
 ASTReader::
 ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
-                         Module &F, const RecordData &Record,
+                         ModuleFile &F, const RecordData &Record,
                          unsigned &Idx) {
   unsigned NumTemplateArgs =3D Record[Idx++];
   TemplArgs.reserve(NumTemplateArgs);
@@ -5100,7 +5932,7 @@
 }
=20
 /// \brief Read a UnresolvedSet structure.
-void ASTReader::ReadUnresolvedSet(Module &F, UnresolvedSetImpl &Set,
+void ASTReader::ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
                                   const RecordData &Record, unsigned &Idx)=
 {
   unsigned NumDecls =3D Record[Idx++];
   while (NumDecls--) {
@@ -5111,7 +5943,7 @@
 }
=20
 CXXBaseSpecifier
-ASTReader::ReadCXXBaseSpecifier(Module &F,
+ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
                                 const RecordData &Record, unsigned &Idx) {
   bool isVirtual =3D static_cast<bool>(Record[Idx++]);
   bool isBaseOfClass =3D static_cast<bool>(Record[Idx++]);
@@ -5127,7 +5959,7 @@
 }
=20
 std::pair<CXXCtorInitializer **, unsigned>
-ASTReader::ReadCXXCtorInitializers(Module &F, const RecordData &Record,
+ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
                                    unsigned &Idx) {
   CXXCtorInitializer **CtorInitializers =3D 0;
   unsigned NumInitializers =3D Record[Idx++];
@@ -5135,21 +5967,20 @@
     CtorInitializers
         =3D new (Context) CXXCtorInitializer*[NumInitializers];
     for (unsigned i=3D0; i !=3D NumInitializers; ++i) {
-      TypeSourceInfo *BaseClassInfo =3D 0;
+      TypeSourceInfo *TInfo =3D 0;
       bool IsBaseVirtual =3D false;
       FieldDecl *Member =3D 0;
       IndirectFieldDecl *IndirectMember =3D 0;
-      CXXConstructorDecl *Target =3D 0;
=20
       CtorInitializerType Type =3D (CtorInitializerType)Record[Idx++];
       switch (Type) {
-       case CTOR_INITIALIZER_BASE:
-        BaseClassInfo =3D GetTypeSourceInfo(F, Record, Idx);
+      case CTOR_INITIALIZER_BASE:
+        TInfo =3D GetTypeSourceInfo(F, Record, Idx);
         IsBaseVirtual =3D Record[Idx++];
         break;
-
-       case CTOR_INITIALIZER_DELEGATING:
-        Target =3D ReadDeclAs<CXXConstructorDecl>(F, Record, Idx);
+         =20
+      case CTOR_INITIALIZER_DELEGATING:
+        TInfo =3D GetTypeSourceInfo(F, Record, Idx);
         break;
=20
        case CTOR_INITIALIZER_MEMBER:
@@ -5179,12 +6010,12 @@
=20
       CXXCtorInitializer *BOMInit;
       if (Type =3D=3D CTOR_INITIALIZER_BASE) {
-        BOMInit =3D new (Context) CXXCtorInitializer(Context, BaseClassInf=
o, IsBaseVirtual,
+        BOMInit =3D new (Context) CXXCtorInitializer(Context, TInfo, IsBas=
eVirtual,
                                              LParenLoc, Init, RParenLoc,
                                              MemberOrEllipsisLoc);
       } else if (Type =3D=3D CTOR_INITIALIZER_DELEGATING) {
-        BOMInit =3D new (Context) CXXCtorInitializer(Context, MemberOrElli=
psisLoc, LParenLoc,
-                                             Target, Init, RParenLoc);
+        BOMInit =3D new (Context) CXXCtorInitializer(Context, TInfo, LPare=
nLoc,
+                                                   Init, RParenLoc);
       } else if (IsWritten) {
         if (Member)
           BOMInit =3D new (Context) CXXCtorInitializer(Context, Member, Me=
mberOrEllipsisLoc,
@@ -5209,7 +6040,7 @@
 }
=20
 NestedNameSpecifier *
-ASTReader::ReadNestedNameSpecifier(Module &F,
+ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
                                    const RecordData &Record, unsigned &Idx=
) {
   unsigned N =3D Record[Idx++];
   NestedNameSpecifier *NNS =3D 0, *Prev =3D 0;
@@ -5258,7 +6089,7 @@
 }
=20
 NestedNameSpecifierLoc
-ASTReader::ReadNestedNameSpecifierLoc(Module &F, const RecordData &Record,=20
+ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Rec=
ord,=20
                                       unsigned &Idx) {
   unsigned N =3D Record[Idx++];
   NestedNameSpecifierLocBuilder Builder;
@@ -5314,7 +6145,7 @@
 }
=20
 SourceRange
-ASTReader::ReadSourceRange(Module &F, const RecordData &Record,
+ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
                            unsigned &Idx) {
   SourceLocation beg =3D ReadSourceLocation(F, Record, Idx);
   SourceLocation end =3D ReadSourceLocation(F, Record, Idx);
@@ -5361,7 +6192,7 @@
   return VersionTuple(Major, Minor - 1, Subminor - 1);
 }
=20
-CXXTemporary *ASTReader::ReadCXXTemporary(Module &F,=20
+CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,=20
                                           const RecordData &Record,
                                           unsigned &Idx) {
   CXXDestructorDecl *Decl =3D ReadDeclAs<CXXDestructorDecl>(F, Record, Idx=
);
@@ -5399,10 +6230,8 @@
   SwitchCaseStmts.clear();
 }
=20
-void ASTReader::FinishedDeserializing() {
-  assert(NumCurrentElementsDeserializing &&
-         "FinishedDeserializing not paired with StartedDeserializing");
-  if (NumCurrentElementsDeserializing =3D=3D 1) {
+void ASTReader::finishPendingActions() {
+  while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty()) {
     // If any identifiers with corresponding top-level declarations have
     // been loaded, load those declarations now.
     while (!PendingIdentifierInfos.empty()) {
@@ -5410,35 +6239,110 @@
                               PendingIdentifierInfos.front().DeclIDs, true=
);
       PendingIdentifierInfos.pop_front();
     }
-
-    // Ready to load previous declarations of Decls that were delayed.
-    while (!PendingPreviousDecls.empty()) {
-      loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
-                                PendingPreviousDecls.front().second);
-      PendingPreviousDecls.pop_front();
-    }
-
-    // We are not in recursive loading, so it's safe to pass the "interest=
ing"
-    // decls to the consumer.
-    if (Consumer)
-      PassInterestingDeclsToConsumer();
-
-    assert(PendingForwardRefs.size() =3D=3D 0 &&
-           "Some forward refs did not get linked to the definition!");
+ =20
+    // Load pending declaration chains.
+    for (unsigned I =3D 0; I !=3D PendingDeclChains.size(); ++I) {
+      loadPendingDeclChain(PendingDeclChains[I]);
+      PendingDeclChainsKnown.erase(PendingDeclChains[I]);
+    }
+    PendingDeclChains.clear();
+  }
+ =20
+  // If we deserialized any C++ or Objective-C class definitions, any
+  // Objective-C protocol definitions, or any redeclarable templates, make=
 sure
+  // that all redeclarations point to the definitions. Note that this can =
only=20
+  // happen now, after the redeclaration chains have been fully wired.
+  for (llvm::SmallPtrSet<Decl *, 4>::iterator D =3D PendingDefinitions.beg=
in(),
+                                           DEnd =3D PendingDefinitions.end=
();
+       D !=3D DEnd; ++D) {
+    if (TagDecl *TD =3D dyn_cast<TagDecl>(*D)) {
+      if (const TagType *TagT =3D dyn_cast<TagType>(TD->TypeForDecl)) {
+        // Make sure that the TagType points at the definition.
+        const_cast<TagType*>(TagT)->decl =3D TD;
+      }
+     =20
+      if (CXXRecordDecl *RD =3D dyn_cast<CXXRecordDecl>(*D)) {
+        for (CXXRecordDecl::redecl_iterator R =3D RD->redecls_begin(),
+                                         REnd =3D RD->redecls_end();
+             R !=3D REnd; ++R)
+          cast<CXXRecordDecl>(*R)->DefinitionData =3D RD->DefinitionData;
+       =20
+      }
+
+      continue;
+    }
+   =20
+    if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(*D)) {
+      // Make sure that the ObjCInterfaceType points at the definition.
+      const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForD=
ecl))
+        ->Decl =3D ID;
+     =20
+      for (ObjCInterfaceDecl::redecl_iterator R =3D ID->redecls_begin(),
+                                           REnd =3D ID->redecls_end();
+           R !=3D REnd; ++R)
+        R->Data =3D ID->Data;
+     =20
+      continue;
+    }
+   =20
+    if (ObjCProtocolDecl *PD =3D dyn_cast<ObjCProtocolDecl>(*D)) {
+      for (ObjCProtocolDecl::redecl_iterator R =3D PD->redecls_begin(),
+                                          REnd =3D PD->redecls_end();
+           R !=3D REnd; ++R)
+        R->Data =3D PD->Data;
+     =20
+      continue;
+    }
+   =20
+    RedeclarableTemplateDecl *RTD
+      =3D cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
+    for (RedeclarableTemplateDecl::redecl_iterator R =3D RTD->redecls_begi=
n(),
+                                                REnd =3D RTD->redecls_end(=
);
+         R !=3D REnd; ++R)
+      R->Common =3D RTD->Common;   =20
+  }
+  PendingDefinitions.clear();
+}
+
+void ASTReader::FinishedDeserializing() {
+  assert(NumCurrentElementsDeserializing &&
+         "FinishedDeserializing not paired with StartedDeserializing");
+  if (NumCurrentElementsDeserializing =3D=3D 1) {
+    // We decrease NumCurrentElementsDeserializing only after pending acti=
ons
+    // are finished, to avoid recursively re-calling finishPendingActions(=
).
+    finishPendingActions();
   }
   --NumCurrentElementsDeserializing;
+
+  if (NumCurrentElementsDeserializing =3D=3D 0 &&
+      Consumer && !PassingDeclsToConsumer) {
+    // Guard variable to avoid recursively redoing the process of passing
+    // decls to consumer.
+    SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsume=
r,
+                                                     true);
+
+    while (!InterestingDecls.empty()) {
+      // We are not in recursive loading, so it's safe to pass the "intere=
sting"
+      // decls to the consumer.
+      Decl *D =3D InterestingDecls.front();
+      InterestingDecls.pop_front();
+      PassInterestingDeclToConsumer(D);
+    }
+  }
 }
=20
 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
                      StringRef isysroot, bool DisableValidation,
-                     bool DisableStatCache)
+                     bool DisableStatCache, bool AllowASTWithCompilerError=
s)
   : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
     SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
     Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
     Consumer(0), ModuleMgr(FileMgr.getFileSystemOptions()),
     RelocatablePCH(false), isysroot(isysroot),
     DisableValidation(DisableValidation),
-    DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),=20
+    DisableStatCache(DisableStatCache),
+    AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),=20
+    CurrentGeneration(0), NumStatHits(0), NumStatMisses(0),=20
     NumSLocEntriesRead(0), TotalNumSLocEntries(0),=20
     NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),=20
     TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),=20
@@ -5446,6 +6350,7 @@
     NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),=20
     NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
     TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
+    PassingDeclsToConsumer(false),
     NumCXXBaseSpecifiersLoaded(0)
 {
   SourceMgr.setExternalSLocEntrySource(this);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTReaderDecl.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,8 @@
=20
 #include "ASTCommon.h"
 #include "clang/Serialization/ASTReader.h"
+#include "clang/Sema/IdentifierResolver.h"
+#include "clang/Sema/Sema.h"
 #include "clang/Sema/SemaDiagnostic.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
@@ -32,9 +34,10 @@
 namespace clang {
   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
     ASTReader &Reader;
-    Module &F;
+    ModuleFile &F;
     llvm::BitstreamCursor &Cursor;
     const DeclID ThisDeclID;
+    const unsigned RawLocation;
     typedef ASTReader::RecordData RecordData;
     const RecordData &Record;
     unsigned &Idx;
@@ -85,24 +88,123 @@
       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
     }
=20
+    serialization::SubmoduleID readSubmoduleID(const RecordData &R,=20
+                                               unsigned &I) {
+      if (I >=3D R.size())
+        return 0;
+     =20
+      return Reader.getGlobalSubmoduleID(F, R[I++]);
+    }
+   =20
+    Module *readModule(const RecordData &R, unsigned &I) {
+      return Reader.getSubmodule(readSubmoduleID(R, I));
+    }
+   =20
     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
                                const RecordData &R, unsigned &I);
=20
-    void InitializeCXXDefinitionData(CXXRecordDecl *D,
-                                     CXXRecordDecl *DefinitionDecl,
-                                     const RecordData &Record, unsigned &I=
dx);
+    /// \brief RAII class used to capture the first ID within a redeclarat=
ion
+    /// chain and to introduce it into the list of pending redeclaration c=
hains
+    /// on destruction.
+    ///
+    /// The caller can choose not to introduce this ID into the redeclarat=
ion
+    /// chain by calling \c suppress().
+    class RedeclarableResult {
+      ASTReader &Reader;
+      GlobalDeclID FirstID;
+      mutable bool Owning;
+     =20
+      RedeclarableResult &operator=3D(RedeclarableResult&); // DO NOT IMPL=
EMENT
+     =20
+    public:
+      RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID)
+        : Reader(Reader), FirstID(FirstID), Owning(true) { }
+
+      RedeclarableResult(const RedeclarableResult &Other)
+        : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Ownin=
g)=20
+      {=20
+        Other.Owning =3D false;
+      }
+
+      ~RedeclarableResult() {
+        // FIXME: We want to suppress this when the declaration is local to
+        // a function, since there's no reason to search other AST files
+        // for redeclarations (they can't exist). However, this is hard to=20
+        // do locally because the declaration hasn't necessarily loaded its
+        // declaration context yet. Also, local externs still have the fun=
ction
+        // as their (semantic) declaration context, which is wrong and wou=
ld
+        // break this optimize.
+       =20
+        if (FirstID && Owning && Reader.PendingDeclChainsKnown.insert(Firs=
tID))
+          Reader.PendingDeclChains.push_back(FirstID);
+      }
+     =20
+      /// \brief Retrieve the first ID.
+      GlobalDeclID getFirstID() const { return FirstID; }
+     =20
+      /// \brief Do not introduce this declaration ID into the set of pend=
ing
+      /// declaration chains.
+      void suppress() {
+        Owning =3D false;
+      }
+    };
+   =20
+    /// \brief Class used to capture the result of searching for an existi=
ng
+    /// declaration of a specific kind and name, along with the ability
+    /// to update the place where this result was found (the declaration
+    /// chain hanging off an identifier or the DeclContext we searched in)
+    /// if requested.
+    class FindExistingResult {
+      ASTReader &Reader;
+      NamedDecl *New;
+      NamedDecl *Existing;
+      mutable bool AddResult;
+     =20
+      FindExistingResult &operator=3D(FindExistingResult&); // DO NOT IMPL=
EMENT
+     =20
+    public:
+      FindExistingResult(ASTReader &Reader)
+        : Reader(Reader), New(0), Existing(0), AddResult(false) { }
+     =20
+      FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Exi=
sting)
+        : Reader(Reader), New(New), Existing(Existing), AddResult(true) { }
+     =20
+      FindExistingResult(const FindExistingResult &Other)
+        : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),=20
+          AddResult(Other.AddResult)
+      {
+        Other.AddResult =3D false;
+      }
+     =20
+      ~FindExistingResult();
+     =20
+      /// \brief Suppress the addition of this result into the known set of
+      /// names.
+      void suppress() { AddResult =3D false; }
+     =20
+      operator NamedDecl*() const { return Existing; }
+     =20
+      template<typename T>
+      operator T*() const { return dyn_cast_or_null<T>(Existing); }
+    };
+   =20
+    FindExistingResult findExisting(NamedDecl *D);
+   =20
   public:
-    ASTDeclReader(ASTReader &Reader, Module &F,
+    ASTDeclReader(ASTReader &Reader, ModuleFile &F,
                   llvm::BitstreamCursor &Cursor, DeclID thisDeclID,
+                  unsigned RawLocation,
                   const RecordData &Record, unsigned &Idx)
       : Reader(Reader), F(F), Cursor(Cursor), ThisDeclID(thisDeclID),
-        Record(Record), Idx(Idx), TypeIDForTypeDecl(0) { }
+        RawLocation(RawLocation), Record(Record), Idx(Idx),
+        TypeIDForTypeDecl(0) { }
=20
     static void attachPreviousDecl(Decl *D, Decl *previous);
+    static void attachLatestDecl(Decl *D, Decl *latest);
=20
     void Visit(Decl *D);
=20
-    void UpdateDecl(Decl *D, Module &Module,
+    void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
                     const RecordData &Record);
=20
     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
@@ -118,6 +220,7 @@
     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
     void VisitTypeDecl(TypeDecl *TD);
+    void VisitTypedefNameDecl(TypedefNameDecl *TD);
     void VisitTypedefDecl(TypedefDecl *TD);
     void VisitTypeAliasDecl(TypeAliasDecl *TD);
     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
@@ -148,7 +251,7 @@
     void VisitParmVarDecl(ParmVarDecl *PD);
     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
     void VisitTemplateDecl(TemplateDecl *D);
-    void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
+    RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateD=
ecl *D);
     void VisitClassTemplateDecl(ClassTemplateDecl *D);
     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
@@ -157,6 +260,7 @@
     void VisitUsingShadowDecl(UsingShadowDecl *D);
     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
+    void VisitImportDecl(ImportDecl *D);
     void VisitAccessSpecDecl(AccessSpecDecl *D);
     void VisitFriendDecl(FriendDecl *D);
     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
@@ -164,8 +268,13 @@
     void VisitBlockDecl(BlockDecl *BD);
=20
     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
-    template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
+   =20
+    template<typename T>=20
+    RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
=20
+    template<typename T>
+    void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);
+   =20
     // FIXME: Reorder according to DeclNodes.td?
     void VisitObjCMethodDecl(ObjCMethodDecl *D);
     void VisitObjCContainerDecl(ObjCContainerDecl *D);
@@ -173,8 +282,6 @@
     void VisitObjCIvarDecl(ObjCIvarDecl *D);
     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
-    void VisitObjCClassDecl(ObjCClassDecl *D);
-    void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
     void VisitObjCImplDecl(ObjCImplDecl *D);
     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
@@ -207,6 +314,9 @@
   if (TypeDecl *TD =3D dyn_cast<TypeDecl>(D)) {
     // if we have a fully initialized TypeDecl, we can safely read its typ=
e now.
     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull(=
));
+  } else if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(D)) {
+    // if we have a fully initialized TypeDecl, we can safely read its typ=
e now.
+    ID->TypeForDecl =3D Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull=
();
   } else if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
     // FunctionDecl's body was written last after all other Stmts/Exprs.
     if (Record[Idx++])
@@ -214,12 +324,11 @@
   } else if (D->isTemplateParameter()) {
     // If we have a fully initialized template parameter, we can now
     // set its DeclContext.
-    D->setDeclContext(
-          cast_or_null<DeclContext>(
-                            Reader.GetDecl(DeclContextIDForTemplateParmDec=
l)));
-    D->setLexicalDeclContext(
-          cast_or_null<DeclContext>(
-                      Reader.GetDecl(LexicalDeclContextIDForTemplateParmDe=
cl)));
+    DeclContext *SemaDC =3D cast<DeclContext>(
+                              Reader.GetDecl(DeclContextIDForTemplateParmD=
ecl));
+    DeclContext *LexicalDC =3D cast<DeclContext>(
+                       Reader.GetDecl(LexicalDeclContextIDForTemplateParmD=
ecl));
+    D->setDeclContextsImpl(SemaDC, LexicalDC, Reader.getContext());
   }
 }
=20
@@ -233,22 +342,50 @@
     LexicalDeclContextIDForTemplateParmDecl =3D ReadDeclID(Record, Idx);
     D->setDeclContext(Reader.getContext().getTranslationUnitDecl());=20
   } else {
-    D->setDeclContext(ReadDeclAs<DeclContext>(Record, Idx));
-    D->setLexicalDeclContext(ReadDeclAs<DeclContext>(Record, Idx));
+    DeclContext *SemaDC =3D ReadDeclAs<DeclContext>(Record, Idx);
+    DeclContext *LexicalDC =3D ReadDeclAs<DeclContext>(Record, Idx);
+    // Avoid calling setLexicalDeclContext() directly because it uses
+    // Decl::getASTContext() internally which is unsafe during derializati=
on.
+    D->setDeclContextsImpl(SemaDC, LexicalDC, Reader.getContext());
   }
-  D->setLocation(ReadSourceLocation(Record, Idx));
+  D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
   D->setInvalidDecl(Record[Idx++]);
   if (Record[Idx++]) { // hasAttrs
     AttrVec Attrs;
     Reader.ReadAttributes(F, Attrs, Record, Idx);
-    D->setAttrs(Attrs);
+    // Avoid calling setAttrs() directly because it uses Decl::getASTConte=
xt()
+    // internally which is unsafe during derialization.
+    D->setAttrsImpl(Attrs, Reader.getContext());
   }
   D->setImplicit(Record[Idx++]);
   D->setUsed(Record[Idx++]);
   D->setReferenced(Record[Idx++]);
+  D->setTopLevelDeclInObjCContainer(Record[Idx++]);
   D->setAccess((AccessSpecifier)Record[Idx++]);
   D->FromASTFile =3D true;
-  D->ModulePrivate =3D Record[Idx++];
+  D->setModulePrivate(Record[Idx++]);
+  D->Hidden =3D D->isModulePrivate();
+ =20
+  // Determine whether this declaration is part of a (sub)module. If so, it
+  // may not yet be visible.
+  if (unsigned SubmoduleID =3D readSubmoduleID(Record, Idx)) {
+    // Store the owning submodule ID in the declaration.
+    D->setOwningModuleID(SubmoduleID);
+   =20
+    // Module-private declarations are never visible, so there is no work =
to do.
+    if (!D->isModulePrivate()) {
+      if (Module *Owner =3D Reader.getSubmodule(SubmoduleID)) {
+        if (Owner->NameVisibility !=3D Module::AllVisible) {
+          // The owning module is not visible. Mark this declaration as hi=
dden.
+          D->Hidden =3D true;
+         =20
+          // Note that this declaration was hidden because its owning modu=
le is=20
+          // not yet visible.
+          Reader.HiddenNamesMap[Owner].push_back(D);
+        }
+      }
+    }
+  }
 }
=20
 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
@@ -267,31 +404,41 @@
   TypeIDForTypeDecl =3D Reader.getGlobalTypeID(F, Record[Idx++]);
 }
=20
+void ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(TD);
+  VisitTypeDecl(TD);
+ =20
+  TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
+  mergeRedeclarable(TD, Redecl);
+}
+
 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
-  VisitTypeDecl(TD);
-  TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
+  VisitTypedefNameDecl(TD);
 }
=20
 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
-  VisitTypeDecl(TD);
-  TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
+  VisitTypedefNameDecl(TD);
 }
=20
 void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(TD);
   VisitTypeDecl(TD);
-  VisitRedeclarable(TD);
+ =20
   TD->IdentifierNamespace =3D Record[Idx++];
   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
   TD->setCompleteDefinition(Record[Idx++]);
   TD->setEmbeddedInDeclarator(Record[Idx++]);
   TD->setFreeStanding(Record[Idx++]);
   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
+ =20
   if (Record[Idx++]) { // hasExtInfo
     TagDecl::ExtInfo *Info =3D new (Reader.getContext()) TagDecl::ExtInfo(=
);
     ReadQualifierInfo(*Info, Record, Idx);
     TD->TypedefNameDeclOrQualifier =3D Info;
   } else
     TD->setTypedefNameForAnonDecl(ReadDeclAs<TypedefNameDecl>(Record, Idx)=
);
+
+  mergeRedeclarable(TD, Redecl); =20
 }
=20
 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
@@ -306,7 +453,13 @@
   ED->IsScoped =3D Record[Idx++];
   ED->IsScopedUsingClassTag =3D Record[Idx++];
   ED->IsFixed =3D Record[Idx++];
-  ED->setInstantiationOfMemberEnum(ReadDeclAs<EnumDecl>(Record, Idx));
+
+  if (EnumDecl *InstED =3D ReadDeclAs<EnumDecl>(Record, Idx)) {
+    TemplateSpecializationKind TSK =3D (TemplateSpecializationKind)Record[=
Idx++];
+    SourceLocation POI =3D ReadSourceLocation(Record, Idx);
+    ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
+    ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
+  }
 }
=20
 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
@@ -340,14 +493,34 @@
 }
=20
 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(FD);
   VisitDeclaratorDecl(FD);
-  VisitRedeclarable(FD);
=20
   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
   FD->IdentifierNamespace =3D Record[Idx++];
+ =20
+  // FunctionDecl's body is handled last at ASTDeclReader::Visit,
+  // after everything else is read.
+ =20
+  FD->SClass =3D (StorageClass)Record[Idx++];
+  FD->SClassAsWritten =3D (StorageClass)Record[Idx++];
+  FD->IsInline =3D Record[Idx++];
+  FD->IsInlineSpecified =3D Record[Idx++];
+  FD->IsVirtualAsWritten =3D Record[Idx++];
+  FD->IsPure =3D Record[Idx++];
+  FD->HasInheritedPrototype =3D Record[Idx++];
+  FD->HasWrittenPrototype =3D Record[Idx++];
+  FD->IsDeleted =3D Record[Idx++];
+  FD->IsTrivial =3D Record[Idx++];
+  FD->IsDefaulted =3D Record[Idx++];
+  FD->IsExplicitlyDefaulted =3D Record[Idx++];
+  FD->HasImplicitReturnZero =3D Record[Idx++];
+  FD->IsConstexpr =3D Record[Idx++];
+  FD->EndRangeLoc =3D ReadSourceLocation(Record, Idx);
+
   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
-  default: llvm_unreachable("Unhandled TemplatedKind!");
   case FunctionDecl::TK_NonTemplate:
+    mergeRedeclarable(FD, Redecl);     =20
     break;
   case FunctionDecl::TK_FunctionTemplate:
     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Reco=
rd,=20
@@ -441,25 +614,6 @@
   }
   }
=20
-  // FunctionDecl's body is handled last at ASTDeclReader::Visit,
-  // after everything else is read.
-
-  FD->SClass =3D (StorageClass)Record[Idx++];
-  FD->SClassAsWritten =3D (StorageClass)Record[Idx++];
-  FD->IsInline =3D Record[Idx++];
-  FD->IsInlineSpecified =3D Record[Idx++];
-  FD->IsVirtualAsWritten =3D Record[Idx++];
-  FD->IsPure =3D Record[Idx++];
-  FD->HasInheritedPrototype =3D Record[Idx++];
-  FD->HasWrittenPrototype =3D Record[Idx++];
-  FD->IsDeleted =3D Record[Idx++];
-  FD->IsTrivial =3D Record[Idx++];
-  FD->IsDefaulted =3D Record[Idx++];
-  FD->IsExplicitlyDefaulted =3D Record[Idx++];
-  FD->HasImplicitReturnZero =3D Record[Idx++];
-  FD->IsConstexpr =3D Record[Idx++];
-  FD->EndRangeLoc =3D ReadSourceLocation(Record, Idx);
-
   // Read in the parameters.
   unsigned NumParams =3D Record[Idx++];
   SmallVector<ParmVarDecl *, 16> Params;
@@ -518,46 +672,60 @@
 }
=20
 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(ID);
   VisitObjCContainerDecl(ID);
-  ID->setTypeForDecl(Reader.readType(F, Record, Idx).getTypePtrOrNull());
-  ID->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
+  TypeIDForTypeDecl =3D Reader.getGlobalTypeID(F, Record[Idx++]);
+  mergeRedeclarable(ID, Redecl);
  =20
-  // Read the directly referenced protocols and their SourceLocations.
-  unsigned NumProtocols =3D Record[Idx++];
-  SmallVector<ObjCProtocolDecl *, 16> Protocols;
-  Protocols.reserve(NumProtocols);
-  for (unsigned I =3D 0; I !=3D NumProtocols; ++I)
-    Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
-  SmallVector<SourceLocation, 16> ProtoLocs;
-  ProtoLocs.reserve(NumProtocols);
-  for (unsigned I =3D 0; I !=3D NumProtocols; ++I)
-    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
-  ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
-                      Reader.getContext());
+  if (Record[Idx++]) {
+    // Read the definition.
+    ID->allocateDefinitionData();
+   =20
+    // Set the definition data of the canonical declaration, so other
+    // redeclarations will see it.
+    ID->getCanonicalDecl()->Data =3D ID->Data;
+   =20
+    ObjCInterfaceDecl::DefinitionData &Data =3D ID->data();
+   =20
+    // Read the superclass.
+    Data.SuperClass =3D ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
+    Data.SuperClassLoc =3D ReadSourceLocation(Record, Idx);
+
+    Data.EndLoc =3D ReadSourceLocation(Record, Idx);
+   =20
+    // Read the directly referenced protocols and their SourceLocations.
+    unsigned NumProtocols =3D Record[Idx++];
+    SmallVector<ObjCProtocolDecl *, 16> Protocols;
+    Protocols.reserve(NumProtocols);
+    for (unsigned I =3D 0; I !=3D NumProtocols; ++I)
+      Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
+    SmallVector<SourceLocation, 16> ProtoLocs;
+    ProtoLocs.reserve(NumProtocols);
+    for (unsigned I =3D 0; I !=3D NumProtocols; ++I)
+      ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
+    ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
+                        Reader.getContext());
  =20
-  // Read the transitive closure of protocols referenced by this class.
-  NumProtocols =3D Record[Idx++];
-  Protocols.clear();
-  Protocols.reserve(NumProtocols);
-  for (unsigned I =3D 0; I !=3D NumProtocols; ++I)
-    Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
-  ID->AllReferencedProtocols.set(Protocols.data(), NumProtocols,
-                                 Reader.getContext());
+    // Read the transitive closure of protocols referenced by this class.
+    NumProtocols =3D Record[Idx++];
+    Protocols.clear();
+    Protocols.reserve(NumProtocols);
+    for (unsigned I =3D 0; I !=3D NumProtocols; ++I)
+      Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
+    ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
+                                          Reader.getContext());
  =20
-  // Read the ivars.
-  unsigned NumIvars =3D Record[Idx++];
-  SmallVector<ObjCIvarDecl *, 16> IVars;
-  IVars.reserve(NumIvars);
-  for (unsigned I =3D 0; I !=3D NumIvars; ++I)
-    IVars.push_back(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
-  ID->setCategoryList(ReadDeclAs<ObjCCategoryDecl>(Record, Idx));
- =20
-  // We will rebuild this list lazily.
-  ID->setIvarList(0);
-  ID->setForwardDecl(Record[Idx++]);
-  ID->setImplicitInterfaceDecl(Record[Idx++]);
-  ID->setSuperClassLoc(ReadSourceLocation(Record, Idx));
-  ID->setLocEnd(ReadSourceLocation(Record, Idx));
+    // We will rebuild this list lazily.
+    ID->setIvarList(0);
+   =20
+    // Note that we have deserialized a definition.
+    Reader.PendingDefinitions.insert(ID);
+   =20
+    // Note that we've loaded this Objective-C class.
+    Reader.ObjCClassesLoaded.push_back(ID);
+  } else {
+    ID->Data =3D ID->getCanonicalDecl()->Data;
+  }
 }
=20
 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
@@ -570,50 +738,52 @@
 }
=20
 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(PD);
   VisitObjCContainerDecl(PD);
-  PD->setForwardDecl(Record[Idx++]);
-  PD->setLocEnd(ReadSourceLocation(Record, Idx));
-  unsigned NumProtoRefs =3D Record[Idx++];
-  SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
-  ProtoRefs.reserve(NumProtoRefs);
-  for (unsigned I =3D 0; I !=3D NumProtoRefs; ++I)
-    ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
-  SmallVector<SourceLocation, 16> ProtoLocs;
-  ProtoLocs.reserve(NumProtoRefs);
-  for (unsigned I =3D 0; I !=3D NumProtoRefs; ++I)
-    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
-  PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
-                      Reader.getContext());
+  mergeRedeclarable(PD, Redecl);
+ =20
+  if (Record[Idx++]) {
+    // Read the definition.
+    PD->allocateDefinitionData();
+   =20
+    // Set the definition data of the canonical declaration, so other
+    // redeclarations will see it.
+    PD->getCanonicalDecl()->Data =3D PD->Data;
+
+    unsigned NumProtoRefs =3D Record[Idx++];
+    SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
+    ProtoRefs.reserve(NumProtoRefs);
+    for (unsigned I =3D 0; I !=3D NumProtoRefs; ++I)
+      ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
+    SmallVector<SourceLocation, 16> ProtoLocs;
+    ProtoLocs.reserve(NumProtoRefs);
+    for (unsigned I =3D 0; I !=3D NumProtoRefs; ++I)
+      ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
+    PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
+                        Reader.getContext());
+   =20
+    // Note that we have deserialized a definition.
+    Reader.PendingDefinitions.insert(PD);
+  } else {
+    PD->Data =3D PD->getCanonicalDecl()->Data;
+  }
 }
=20
 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
   VisitFieldDecl(FD);
 }
=20
-void ASTDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
-  VisitDecl(CD);
-  ObjCInterfaceDecl *ClassRef =3D ReadDeclAs<ObjCInterfaceDecl>(Record, Id=
x);
-  SourceLocation SLoc =3D ReadSourceLocation(Record, Idx);
-  CD->setClass(Reader.getContext(), ClassRef, SLoc);
-}
-
-void ASTDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *=
FPD) {
-  VisitDecl(FPD);
-  unsigned NumProtoRefs =3D Record[Idx++];
-  SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
-  ProtoRefs.reserve(NumProtoRefs);
-  for (unsigned I =3D 0; I !=3D NumProtoRefs; ++I)
-    ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
-  SmallVector<SourceLocation, 16> ProtoLocs;
-  ProtoLocs.reserve(NumProtoRefs);
-  for (unsigned I =3D 0; I !=3D NumProtoRefs; ++I)
-    ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
-  FPD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
-                       Reader.getContext());
-}
-
 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
   VisitObjCContainerDecl(CD);
+  CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
+  CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
+  CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
+ =20
+  // Note that this category has been deserialized. We do this before
+  // deserializing the interface declaration, so that it will consider this
+  /// category.
+  Reader.CategoriesDeserialized.insert(CD);
+
   CD->ClassInterface =3D ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
   unsigned NumProtoRefs =3D Record[Idx++];
   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
@@ -626,9 +796,7 @@
     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
                       Reader.getContext());
-  CD->NextClassCategory =3D ReadDeclAs<ObjCCategoryDecl>(Record, Idx);
   CD->setHasSynthBitfield(Record[Idx++]);
-  CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
 }
=20
 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *=
CAD) {
@@ -639,6 +807,7 @@
 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
   VisitNamedDecl(D);
   D->setAtLoc(ReadSourceLocation(Record, Idx));
+  D->setLParenLoc(ReadSourceLocation(Record, Idx));
   D->setType(GetTypeSourceInfo(Record, Idx));
   // FIXME: stable encoding
   D->setPropertyAttributes(
@@ -663,11 +832,14 @@
 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
   VisitObjCImplDecl(D);
   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
+  D->CategoryNameLoc =3D ReadSourceLocation(Record, Idx);
 }
=20
 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D)=
 {
   VisitObjCImplDecl(D);
   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
+  D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
+  D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
       =3D Reader.ReadCXXCtorInitializers(F, Record, Idx);
   D->setHasSynthBitfield(Record[Idx++]);
@@ -710,18 +882,30 @@
 }
=20
 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(VD);
   VisitDeclaratorDecl(VD);
-  VisitRedeclarable(VD);
+ =20
   VD->VarDeclBits.SClass =3D (StorageClass)Record[Idx++];
   VD->VarDeclBits.SClassAsWritten =3D (StorageClass)Record[Idx++];
   VD->VarDeclBits.ThreadSpecified =3D Record[Idx++];
-  VD->VarDeclBits.HasCXXDirectInit =3D Record[Idx++];
+  VD->VarDeclBits.InitStyle =3D Record[Idx++];
   VD->VarDeclBits.ExceptionVar =3D Record[Idx++];
   VD->VarDeclBits.NRVOVariable =3D Record[Idx++];
   VD->VarDeclBits.CXXForRangeDecl =3D Record[Idx++];
   VD->VarDeclBits.ARCPseudoStrong =3D Record[Idx++];
-  if (Record[Idx++])
+
+  // Only true variables (not parameters or implicit parameters) can be me=
rged.
+  if (VD->getKind() =3D=3D Decl::Var)
+    mergeRedeclarable(VD, Redecl);
+ =20
+  if (uint64_t Val =3D Record[Idx++]) {
     VD->setInit(Reader.ReadExpr(F));
+    if (Val > 1) {
+      EvaluatedStmt *Eval =3D VD->ensureEvaluatedStmt();
+      Eval->CheckedICE =3D true;
+      Eval->IsICE =3D Val =3D=3D 3;
+    }
+  }
=20
   if (Record[Idx++]) { // HasMemberSpecializationInfo.
     VarDecl *Tmpl =3D ReadDeclAs<VarDecl>(Record, Idx);
@@ -802,17 +986,25 @@
=20
=20
 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(D);
   VisitNamedDecl(D);
-  D->IsInline =3D Record[Idx++];
+  D->setInline(Record[Idx++]);
   D->LocStart =3D ReadSourceLocation(Record, Idx);
   D->RBraceLoc =3D ReadSourceLocation(Record, Idx);
-  D->NextNamespace =3D Record[Idx++];
+  mergeRedeclarable(D, Redecl);
=20
-  bool IsOriginal =3D Record[Idx++];
-  // FIXME: Modules will likely have trouble with pointing directly at
-  // the original namespace.
-  D->OrigOrAnonNamespace.setInt(IsOriginal);
-  D->OrigOrAnonNamespace.setPointer(ReadDeclAs<NamespaceDecl>(Record, Idx)=
);
+  if (Redecl.getFirstID() =3D=3D ThisDeclID) {
+    // Each module has its own anonymous namespace, which is disjoint from
+    // any other module's anonymous namespaces, so don't attach the anonym=
ous
+    // namespace at all.
+    NamespaceDecl *Anon =3D ReadDeclAs<NamespaceDecl>(Record, Idx);
+    if (F.Kind !=3D MK_Module)
+      D->setAnonymousNamespace(Anon);
+  } else {
+    // Link this namespace back to the first declaration, which has already
+    // been deserialized.
+    D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDeclaration());
+  }
 }
=20
 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
@@ -828,7 +1020,7 @@
   D->setUsingLocation(ReadSourceLocation(Record, Idx));
   D->QualifierLoc =3D Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
-  D->FirstUsingShadow =3D ReadDeclAs<UsingShadowDecl>(Record, Idx);
+  D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
   D->setTypeName(Record[Idx++]);
   if (NamedDecl *Pattern =3D ReadDeclAs<NamedDecl>(Record, Idx))
     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
@@ -869,6 +1061,7 @@
 void ASTDeclReader::ReadCXXDefinitionData(
                                    struct CXXRecordDecl::DefinitionData &D=
ata,
                                    const RecordData &Record, unsigned &Idx=
) {
+  // Note: the caller has deserialized the IsLambda bit already.
   Data.UserDeclaredConstructor =3D Record[Idx++];
   Data.UserDeclaredCopyConstructor =3D Record[Idx++];
   Data.UserDeclaredMoveConstructor =3D Record[Idx++];
@@ -886,13 +1079,21 @@
   Data.HasProtectedFields =3D Record[Idx++];
   Data.HasPublicFields =3D Record[Idx++];
   Data.HasMutableFields =3D Record[Idx++];
+  Data.HasOnlyCMembers =3D Record[Idx++];
   Data.HasTrivialDefaultConstructor =3D Record[Idx++];
   Data.HasConstexprNonCopyMoveConstructor =3D Record[Idx++];
+  Data.DefaultedDefaultConstructorIsConstexpr =3D Record[Idx++];
+  Data.DefaultedCopyConstructorIsConstexpr =3D Record[Idx++];
+  Data.DefaultedMoveConstructorIsConstexpr =3D Record[Idx++];
+  Data.HasConstexprDefaultConstructor =3D Record[Idx++];
+  Data.HasConstexprCopyConstructor =3D Record[Idx++];
+  Data.HasConstexprMoveConstructor =3D Record[Idx++];
   Data.HasTrivialCopyConstructor =3D Record[Idx++];
   Data.HasTrivialMoveConstructor =3D Record[Idx++];
   Data.HasTrivialCopyAssignment =3D Record[Idx++];
   Data.HasTrivialMoveAssignment =3D Record[Idx++];
   Data.HasTrivialDestructor =3D Record[Idx++];
+  Data.HasIrrelevantDestructor =3D Record[Idx++];
   Data.HasNonLiteralTypeFieldsOrBases =3D Record[Idx++];
   Data.ComputedVisibleConversions =3D Record[Idx++];
   Data.UserProvidedDefaultConstructor =3D Record[Idx++];
@@ -916,38 +1117,26 @@
   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
   assert(Data.Definition && "Data.Definition should be already set!");
   Data.FirstFriend =3D ReadDeclAs<FriendDecl>(Record, Idx);
-}
-
-void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
-                                                CXXRecordDecl *DefinitionD=
ecl,
-                                                const RecordData &Record,
-                                                unsigned &Idx) {
-  ASTContext &C =3D Reader.getContext();
-
-  if (D =3D=3D DefinitionDecl) {
-    D->DefinitionData =3D new (C) struct CXXRecordDecl::DefinitionData(D);
-    ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
-    // We read the definition info. Check if there are pending forward
-    // references that need to point to this DefinitionData pointer.
-    ASTReader::PendingForwardRefsMap::iterator
-        FindI =3D Reader.PendingForwardRefs.find(D);
-    if (FindI !=3D Reader.PendingForwardRefs.end()) {
-      ASTReader::ForwardRefs &Refs =3D FindI->second;
-      for (ASTReader::ForwardRefs::iterator
-             I =3D Refs.begin(), E =3D Refs.end(); I !=3D E; ++I)
-        (*I)->DefinitionData =3D D->DefinitionData;
-#ifndef NDEBUG
-      // We later check whether PendingForwardRefs is empty to make sure a=
ll
-      // pending references were linked.
-      Reader.PendingForwardRefs.erase(D);
-#endif
-    }
-  } else if (DefinitionDecl) {
-    if (DefinitionDecl->DefinitionData) {
-      D->DefinitionData =3D DefinitionDecl->DefinitionData;
-    } else {
-      // The definition is still initializing.
-      Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
+ =20
+  if (Data.IsLambda) {
+    typedef LambdaExpr::Capture Capture;
+    CXXRecordDecl::LambdaDefinitionData &Lambda
+      =3D static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
+    Lambda.Dependent =3D Record[Idx++];
+    Lambda.NumCaptures =3D Record[Idx++];
+    Lambda.NumExplicitCaptures =3D Record[Idx++];
+    Lambda.ManglingNumber =3D Record[Idx++];
+    Lambda.ContextDecl =3D ReadDecl(Record, Idx);
+    Lambda.Captures=20
+      =3D (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCapt=
ures);
+    Capture *ToCapture =3D Lambda.Captures;
+    for (unsigned I =3D 0, N =3D Lambda.NumCaptures; I !=3D N; ++I) {
+      SourceLocation Loc =3D ReadSourceLocation(Record, Idx);
+      bool IsImplicit =3D Record[Idx++];
+      LambdaCaptureKind Kind =3D static_cast<LambdaCaptureKind>(Record[Idx=
++]);
+      VarDecl *Var =3D ReadDeclAs<VarDecl>(Record, Idx);
+      SourceLocation EllipsisLoc =3D ReadSourceLocation(Record, Idx);
+      *ToCapture++ =3D Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
     }
   }
 }
@@ -955,17 +1144,36 @@
 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
   VisitRecordDecl(D);
=20
-  CXXRecordDecl *DefinitionDecl =3D ReadDeclAs<CXXRecordDecl>(Record, Idx);
-  InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
-
   ASTContext &C =3D Reader.getContext();
+  if (Record[Idx++]) {
+    // Determine whether this is a lambda closure type, so that we can
+    // allocate the appropriate DefinitionData structure.
+    bool IsLambda =3D Record[Idx++];
+    if (IsLambda)
+      D->DefinitionData =3D new (C) CXXRecordDecl::LambdaDefinitionData(D,=
 false);
+    else
+      D->DefinitionData =3D new (C) struct CXXRecordDecl::DefinitionData(D=
);
+   =20
+    // Propagate the DefinitionData pointer to the canonical declaration, =
so
+    // that all other deserialized declarations will see it.
+    // FIXME: Complain if there already is a DefinitionData!
+    D->getCanonicalDecl()->DefinitionData =3D D->DefinitionData;
+   =20
+    ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
+   =20
+    // Note that we have deserialized a definition. Any declarations=20
+    // deserialized before this one will be be given the DefinitionData po=
inter
+    // at the end.
+    Reader.PendingDefinitions.insert(D);
+  } else {
+    // Propagate DefinitionData pointer from the canonical declaration.
+    D->DefinitionData =3D D->getCanonicalDecl()->DefinitionData;   =20
+  }
=20
   enum CXXRecKind {
     CXXRecNotTemplate =3D 0, CXXRecTemplate, CXXRecMemberSpecialization
   };
   switch ((CXXRecKind)Record[Idx++]) {
-  default:
-    llvm_unreachable("Out of sync with ASTDeclWriter::VisitCXXRecordDecl?"=
);
   case CXXRecNotTemplate:
     break;
   case CXXRecTemplate:
@@ -1022,6 +1230,16 @@
   D->IsExplicitSpecified =3D Record[Idx++];
 }
=20
+void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
+  VisitDecl(D);
+  D->ImportedAndComplete.setPointer(readModule(Record, Idx));
+  D->ImportedAndComplete.setInt(Record[Idx++]);
+  SourceLocation *StoredLocs =3D reinterpret_cast<SourceLocation *>(D + 1);
+  for (unsigned I =3D 0, N =3D Record.back(); I !=3D N; ++I)
+    StoredLocs[I] =3D ReadSourceLocation(Record, Idx);
+  ++Idx;
+}
+
 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
   VisitDecl(D);
   D->setColonLoc(ReadSourceLocation(Record, Idx));
@@ -1061,64 +1279,42 @@
   D->init(TemplatedDecl, TemplateParams);
 }
=20
-void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl=
 *D) {
-  // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr=
()
-  // can be used while this is still initializing.
+ASTDeclReader::RedeclarableResult=20
+ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
+  RedeclarableResult Redecl =3D VisitRedeclarable(D);
=20
-  assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on t=
his");
-  DeclID PreviousDeclID =3D ReadDeclID(Record, Idx);
-  DeclID FirstDeclID =3D  PreviousDeclID ? ReadDeclID(Record, Idx) : 0;
-  // We delay loading of the redeclaration chain to avoid deeply nested ca=
lls.
-  // We temporarily set the first (canonical) declaration as the previous =
one
-  // which is the one that matters and mark the real previous DeclID to be
-  // loaded & attached later on.
-  RedeclarableTemplateDecl *FirstDecl =3D
-      cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(FirstDeclID));
-  assert((FirstDecl =3D=3D 0 || FirstDecl->getKind() =3D=3D D->getKind()) =
&&
-         "FirstDecl kind mismatch");
-  if (FirstDecl) {
-    D->CommonOrPrev =3D FirstDecl;
-    // Mark the real previous DeclID to be loaded & attached later on.
-    if (PreviousDeclID !=3D FirstDeclID)
-      Reader.PendingPreviousDecls.push_back(std::make_pair(D, PreviousDecl=
ID));
-  } else {
-    D->CommonOrPrev =3D D->newCommon(Reader.getContext());
+  // Make sure we've allocated the Common pointer first. We do this before
+  // VisitTemplateDecl so that getCommonPtr() can be used during initializ=
ation.
+  RedeclarableTemplateDecl *CanonD =3D D->getCanonicalDecl();
+  if (!CanonD->Common) {
+    CanonD->Common =3D CanonD->newCommon(Reader.getContext());
+    Reader.PendingDefinitions.insert(CanonD);
+  }
+  D->Common =3D CanonD->Common;
+
+  // If this is the first declaration of the template, fill in the informa=
tion
+  // for the 'common' pointer.
+  if (ThisDeclID =3D=3D Redecl.getFirstID()) {
     if (RedeclarableTemplateDecl *RTD
           =3D ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
       assert(RTD->getKind() =3D=3D D->getKind() &&
              "InstantiatedFromMemberTemplate kind mismatch");
-      D->setInstantiatedFromMemberTemplateImpl(RTD);
+      D->setInstantiatedFromMemberTemplate(RTD);
       if (Record[Idx++])
         D->setMemberSpecialization();
     }
-
-    RedeclarableTemplateDecl *LatestDecl
-      =3D ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx);
- =20
-    // This decl is a first one and the latest declaration that it points =
to is
-    // in the same AST file. However, if this actually needs to point to a
-    // redeclaration in another AST file, we need to update it by checking
-    // the FirstLatestDeclIDs map which tracks this kind of decls.
-    assert(Reader.GetDecl(ThisDeclID) =3D=3D D && "Invalid ThisDeclID ?");
-    ASTReader::FirstLatestDeclIDMap::iterator I
-        =3D Reader.FirstLatestDeclIDs.find(ThisDeclID);
-    if (I !=3D Reader.FirstLatestDeclIDs.end()) {
-      if (Decl *NewLatest =3D Reader.GetDecl(I->second))
-        LatestDecl =3D cast<RedeclarableTemplateDecl>(NewLatest);
-    }
-
-    assert(LatestDecl->getKind() =3D=3D D->getKind() && "Latest kind misma=
tch");
-    D->getCommonPtr()->Latest =3D LatestDecl;
   }
-
+    =20
   VisitTemplateDecl(D);
   D->IdentifierNamespace =3D Record[Idx++];
+ =20
+  return Redecl;
 }
=20
 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
-  VisitRedeclarableTemplateDecl(D);
+  RedeclarableResult Redecl =3D VisitRedeclarableTemplateDecl(D);
=20
-  if (D->getPreviousDeclaration() =3D=3D 0) {
+  if (ThisDeclID =3D=3D Redecl.getFirstID()) {
     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of a=
ll of
     // the specializations.
     SmallVector<serialization::DeclID, 2> SpecIDs;
@@ -1140,6 +1336,7 @@
       typedef serialization::DeclID DeclID;
      =20
       ClassTemplateDecl::Common *CommonPtr =3D D->getCommonPtr();
+      // FIXME: Append specializations!
       CommonPtr->LazySpecializations
         =3D new (Reader.getContext()) DeclID [SpecIDs.size()];
       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),=20
@@ -1220,7 +1417,7 @@
   D->SequenceNumber =3D Record[Idx++];
=20
   // These are read/set from/to the first declaration.
-  if (D->getPreviousDeclaration() =3D=3D 0) {
+  if (D->getPreviousDecl() =3D=3D 0) {
     D->InstantiatedFromMember.setPointer(
       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
     D->InstantiatedFromMember.setInt(Record[Idx++]);
@@ -1234,9 +1431,9 @@
 }
=20
 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
-  VisitRedeclarableTemplateDecl(D);
+  RedeclarableResult Redecl =3D VisitRedeclarableTemplateDecl(D);
=20
-  if (D->getPreviousDeclaration() =3D=3D 0) {
+  if (ThisDeclID =3D=3D Redecl.getFirstID()) {
     // This FunctionTemplateDecl owns a CommonPtr; read it.
=20
     // Read the function specialization declarations.
@@ -1311,54 +1508,90 @@
 }
=20
 template <typename T>
-void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
-  enum RedeclKind { NoRedeclaration =3D 0, PointsToPrevious, PointsToLates=
t };
-  RedeclKind Kind =3D (RedeclKind)Record[Idx++];
-  switch (Kind) {
-  default:
-    llvm_unreachable("Out of sync with ASTDeclWriter::VisitRedeclarable or"
-                     " messed up reading");
-  case NoRedeclaration:
-    break;
-  case PointsToPrevious: {
-    DeclID PreviousDeclID =3D ReadDeclID(Record, Idx);
-    DeclID FirstDeclID =3D ReadDeclID(Record, Idx);
+ASTDeclReader::RedeclarableResult=20
+ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
+  DeclID FirstDeclID =3D ReadDeclID(Record, Idx);
+ =20
+  // 0 indicates that this declaration was the only declaration of its ent=
ity,
+  // and is used for space optimization.
+  if (FirstDeclID =3D=3D 0)
+    FirstDeclID =3D ThisDeclID;
+ =20
+  T *FirstDecl =3D cast_or_null<T>(Reader.GetDecl(FirstDeclID));
+  if (FirstDecl !=3D D) {
     // We delay loading of the redeclaration chain to avoid deeply nested =
calls.
     // We temporarily set the first (canonical) declaration as the previou=
s one
     // which is the one that matters and mark the real previous DeclID to =
be
     // loaded & attached later on.
-    D->RedeclLink =3D typename Redeclarable<T>::PreviousDeclLink(
-                                cast_or_null<T>(Reader.GetDecl(FirstDeclID=
)));
-    if (PreviousDeclID !=3D FirstDeclID)
-      Reader.PendingPreviousDecls.push_back(std::make_pair(static_cast<T*>=
(D),
-                                                           PreviousDeclID)=
);
-    break;
-  }
-  case PointsToLatest:
-    D->RedeclLink =3D typename Redeclarable<T>::LatestDeclLink(
-                                                   ReadDeclAs<T>(Record, I=
dx));
-    break;
-  }
+    D->RedeclLink =3D typename Redeclarable<T>::PreviousDeclLink(FirstDecl=
);
+  }   =20
+ =20
+  // Note that this declaration has been deserialized.
+  Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
+                            =20
+  // The result structure takes care to note that we need to load the=20
+  // other declaration chains for this ID.
+  return RedeclarableResult(Reader, FirstDeclID);
+}
=20
-  assert(!(Kind =3D=3D PointsToPrevious &&
-           Reader.FirstLatestDeclIDs.find(ThisDeclID) !=3D
-               Reader.FirstLatestDeclIDs.end()) &&
-         "This decl is not first, it should not be in the map");
-  if (Kind =3D=3D PointsToPrevious)
+/// \brief Attempts to merge the given declaration (D) with another declar=
ation
+/// of the same entity.
+template<typename T>
+void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,=20
+                                      RedeclarableResult &Redecl) {
+  // If modules are not available, there is no reason to perform this merg=
e.
+  if (!Reader.getContext().getLangOpts().Modules)
     return;
-
-  // This decl is a first one and the latest declaration that it points to=
 is in
-  // the same AST file. However, if this actually needs to point to a
-  // redeclaration in another AST file, we need to update it by checking t=
he
-  // FirstLatestDeclIDs map which tracks this kind of decls.
-  assert(Reader.GetDecl(ThisDeclID) =3D=3D static_cast<T*>(D) &&
-         "Invalid ThisDeclID ?");
-  ASTReader::FirstLatestDeclIDMap::iterator I
-      =3D Reader.FirstLatestDeclIDs.find(ThisDeclID);
-  if (I !=3D Reader.FirstLatestDeclIDs.end()) {
-    Decl *NewLatest =3D Reader.GetDecl(I->second);
-    D->RedeclLink
-        =3D typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLa=
test));
+ =20
+  if (FindExistingResult ExistingRes =3D findExisting(static_cast<T*>(D)))=
 {
+    if (T *Existing =3D ExistingRes) {
+      T *ExistingCanon =3D Existing->getCanonicalDecl();
+      T *DCanon =3D static_cast<T*>(D)->getCanonicalDecl();
+      if (ExistingCanon !=3D DCanon) {
+        // Have our redeclaration link point back at the canonical declara=
tion
+        // of the existing declaration, so that this declaration has the=20
+        // appropriate canonical declaration.
+        D->RedeclLink=20
+          =3D typename Redeclarable<T>::PreviousDeclLink(ExistingCanon);
+       =20
+        // When we merge a namespace, update its pointer to the first name=
space.
+        if (NamespaceDecl *Namespace
+              =3D dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
+          Namespace->AnonOrFirstNamespaceAndInline.setPointer(
+            static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)=
));
+        }
+       =20
+        // Don't introduce DCanon into the set of pending declaration chai=
ns.
+        Redecl.suppress();
+       =20
+        // Introduce ExistingCanon into the set of pending declaration cha=
ins,
+        // if in fact it came from a module file.
+        if (ExistingCanon->isFromASTFile()) {
+          GlobalDeclID ExistingCanonID =3D ExistingCanon->getGlobalID();
+          assert(ExistingCanonID && "Unrecorded canonical declaration ID?"=
);
+          if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
+            Reader.PendingDeclChains.push_back(ExistingCanonID);
+        }
+       =20
+        // If this declaration was the canonical declaration, make a note =
of=20
+        // that. We accept the linear algorithm here because the number of=20
+        // unique canonical declarations of an entity should always be tin=
y.
+        if (DCanon =3D=3D static_cast<T*>(D)) {
+          SmallVectorImpl<DeclID> &Merged =3D Reader.MergedDecls[ExistingC=
anon];
+          if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
+                =3D=3D Merged.end())
+            Merged.push_back(Redecl.getFirstID());
+         =20
+          // If ExistingCanon did not come from a module file, introduce t=
he
+          // first declaration that *does* come from a module file to the=20
+          // set of pending declaration chains, so that we merge this=20
+          // declaration.
+          if (!ExistingCanon->isFromASTFile() &&
+              Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
+            Reader.PendingDeclChains.push_back(Merged[0]);
+        }
+      }
+    }
   }
 }
=20
@@ -1367,7 +1600,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 /// \brief Reads attributes from the current stream position.
-void ASTReader::ReadAttributes(Module &F, AttrVec &Attrs,
+void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
                                const RecordData &Record, unsigned &Idx) {
   for (unsigned i =3D 0, e =3D Record[Idx++]; i !=3D e; ++i) {
     Attr *New =3D 0;
@@ -1422,31 +1655,142 @@
=20
 /// \brief Get the correct cursor and offset for loading a declaration.
 ASTReader::RecordLocation
-ASTReader::DeclCursorForID(DeclID ID) {
+ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
   // See if there's an override.
   DeclReplacementMap::iterator It =3D ReplacedDecls.find(ID);
-  if (It !=3D ReplacedDecls.end())
-    return RecordLocation(It->second.first, It->second.second);
+  if (It !=3D ReplacedDecls.end()) {
+    RawLocation =3D It->second.RawLoc;
+    return RecordLocation(It->second.Mod, It->second.Offset);
+  }
=20
   GlobalDeclMapType::iterator I =3D GlobalDeclMap.find(ID);
   assert(I !=3D GlobalDeclMap.end() && "Corrupted global declaration map");
-  Module *M =3D I->second;
-  return RecordLocation(M,=20
-           M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS]);
+  ModuleFile *M =3D I->second;
+  const DeclOffset &
+    DOffs =3D  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
+  RawLocation =3D DOffs.Loc;
+  return RecordLocation(M, DOffs.BitOffset);
 }
=20
 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffs=
et) {
-  ContinuousRangeMap<uint64_t, Module*, 4>::iterator I
+  ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
     =3D GlobalBitOffsetsMap.find(GlobalOffset);
=20
   assert(I !=3D GlobalBitOffsetsMap.end() && "Corrupted global bit offsets=
 map");
   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffs=
et);
 }
=20
-uint64_t ASTReader::getGlobalBitOffset(Module &M, uint32_t LocalOffset) {
+uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset=
) {
   return LocalOffset + M.GlobalBitOffset;
 }
=20
+/// \brief Determine whether the two declarations refer to the same entity.
+static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
+  assert(X->getDeclName() =3D=3D Y->getDeclName() && "Declaration name mis=
match!");
+ =20
+  if (X =3D=3D Y)
+    return true;
+ =20
+  // Must be in the same context.
+  if (!X->getDeclContext()->getRedeclContext()->Equals(
+         Y->getDeclContext()->getRedeclContext()))
+    return false;
+
+  // Two typedefs refer to the same entity if they have the same underlying
+  // type.
+  if (TypedefNameDecl *TypedefX =3D dyn_cast<TypedefNameDecl>(X))
+    if (TypedefNameDecl *TypedefY =3D dyn_cast<TypedefNameDecl>(Y))
+      return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
+                                            TypedefY->getUnderlyingType());
+ =20
+  // Must have the same kind.
+  if (X->getKind() !=3D Y->getKind())
+    return false;
+   =20
+  // Objective-C classes and protocols with the same name always match.
+  if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
+    return true;
+ =20
+  // Compatible tags match.
+  if (TagDecl *TagX =3D dyn_cast<TagDecl>(X)) {
+    TagDecl *TagY =3D cast<TagDecl>(Y);
+    return (TagX->getTagKind() =3D=3D TagY->getTagKind()) ||
+      ((TagX->getTagKind() =3D=3D TTK_Struct || TagX->getTagKind() =3D=3D =
TTK_Class) &&
+       (TagY->getTagKind() =3D=3D TTK_Struct || TagY->getTagKind() =3D=3D =
TTK_Class));
+  }
+ =20
+  // Functions with the same type and linkage match.
+  // FIXME: This needs to cope with function templates, merging of=20
+  //prototyped/non-prototyped functions, etc.
+  if (FunctionDecl *FuncX =3D dyn_cast<FunctionDecl>(X)) {
+    FunctionDecl *FuncY =3D cast<FunctionDecl>(Y);
+    return (FuncX->getLinkage() =3D=3D FuncY->getLinkage()) &&
+      FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType(=
));
+  }
+ =20
+  // Variables with the same type and linkage match.
+  if (VarDecl *VarX =3D dyn_cast<VarDecl>(X)) {
+    VarDecl *VarY =3D cast<VarDecl>(Y);
+    return (VarX->getLinkage() =3D=3D VarY->getLinkage()) &&
+      VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
+  }
+ =20
+  // Namespaces with the same name and inlinedness match.
+  if (NamespaceDecl *NamespaceX =3D dyn_cast<NamespaceDecl>(X)) {
+    NamespaceDecl *NamespaceY =3D cast<NamespaceDecl>(Y);
+    return NamespaceX->isInline() =3D=3D NamespaceY->isInline();
+  }
+     =20
+  // FIXME: Many other cases to implement.
+  return false;
+}
+
+ASTDeclReader::FindExistingResult::~FindExistingResult() {
+  if (!AddResult || Existing)
+    return;
+ =20
+  DeclContext *DC =3D New->getDeclContext()->getRedeclContext();
+  if (DC->isTranslationUnit() && Reader.SemaObj) {
+    Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
+  } else if (DC->isNamespace()) {
+    DC->addDecl(New);
+  }
+}
+
+ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D=
) {
+  DeclarationName Name =3D D->getDeclName();
+  if (!Name) {
+    // Don't bother trying to find unnamed declarations.
+    FindExistingResult Result(Reader, D, /*Existing=3D*/0);
+    Result.suppress();
+    return Result;
+  }
+ =20
+  DeclContext *DC =3D D->getDeclContext()->getRedeclContext();
+  if (!DC->isFileContext())
+    return FindExistingResult(Reader);
+ =20
+  if (DC->isTranslationUnit() && Reader.SemaObj) {
+    IdentifierResolver &IdResolver =3D Reader.SemaObj->IdResolver;
+    for (IdentifierResolver::iterator I =3D IdResolver.begin(Name),=20
+                                   IEnd =3D IdResolver.end();
+         I !=3D IEnd; ++I) {
+      if (isSameEntity(*I, D))
+        return FindExistingResult(Reader, D, *I);
+    }
+  }
+
+  if (DC->isNamespace()) {
+    for (DeclContext::lookup_result R =3D DC->lookup(Name);
+         R.first !=3D R.second; ++R.first) {
+      if (isSameEntity(*R.first, D))
+        return FindExistingResult(Reader, D, *R.first);
+    }
+  }
+ =20
+  return FindExistingResult(Reader, D, /*Existing=3D*/0);
+}
+
 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
   assert(D && previous);
   if (TagDecl *TD =3D dyn_cast<TagDecl>(D)) {
@@ -1455,12 +1799,78 @@
     FD->RedeclLink.setPointer(cast<FunctionDecl>(previous));
   } else if (VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
     VD->RedeclLink.setPointer(cast<VarDecl>(previous));
+  } else if (TypedefNameDecl *TD =3D dyn_cast<TypedefNameDecl>(D)) {
+    TD->RedeclLink.setPointer(cast<TypedefNameDecl>(previous));
+  } else if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(D)) {
+    ID->RedeclLink.setPointer(cast<ObjCInterfaceDecl>(previous));
+  } else if (ObjCProtocolDecl *PD =3D dyn_cast<ObjCProtocolDecl>(D)) {
+    PD->RedeclLink.setPointer(cast<ObjCProtocolDecl>(previous));
+  } else if (NamespaceDecl *ND =3D dyn_cast<NamespaceDecl>(D)) {
+    ND->RedeclLink.setPointer(cast<NamespaceDecl>(previous));
   } else {
     RedeclarableTemplateDecl *TD =3D cast<RedeclarableTemplateDecl>(D);
-    TD->CommonOrPrev =3D cast<RedeclarableTemplateDecl>(previous);
+    TD->RedeclLink.setPointer(cast<RedeclarableTemplateDecl>(previous));
   }
 }
=20
+void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
+  assert(D && Latest);
+  if (TagDecl *TD =3D dyn_cast<TagDecl>(D)) {
+    TD->RedeclLink
+      =3D Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
+  } else if (FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
+    FD->RedeclLink=20
+      =3D Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(La=
test));
+  } else if (VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
+    VD->RedeclLink
+      =3D Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
+  } else if (TypedefNameDecl *TD =3D dyn_cast<TypedefNameDecl>(D)) {
+    TD->RedeclLink
+      =3D Redeclarable<TypedefNameDecl>::LatestDeclLink(
+                                                cast<TypedefNameDecl>(Late=
st));
+  } else if (ObjCInterfaceDecl *ID =3D dyn_cast<ObjCInterfaceDecl>(D)) {
+    ID->RedeclLink
+      =3D Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
+                                              cast<ObjCInterfaceDecl>(Late=
st));
+  } else if (ObjCProtocolDecl *PD =3D dyn_cast<ObjCProtocolDecl>(D)) {
+    PD->RedeclLink
+      =3D Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
+                                                cast<ObjCProtocolDecl>(Lat=
est));
+  } else if (NamespaceDecl *ND =3D dyn_cast<NamespaceDecl>(D)) {
+    ND->RedeclLink
+      =3D Redeclarable<NamespaceDecl>::LatestDeclLink(
+                                                   cast<NamespaceDecl>(Lat=
est));
+  } else {
+    RedeclarableTemplateDecl *TD =3D cast<RedeclarableTemplateDecl>(D);
+    TD->RedeclLink
+      =3D Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
+                                        cast<RedeclarableTemplateDecl>(Lat=
est));
+  }
+}
+
+ASTReader::MergedDeclsMap::iterator
+ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
+  // If we don't have any stored merged declarations, just look in the
+  // merged declarations set.
+  StoredMergedDeclsMap::iterator StoredPos =3D StoredMergedDecls.find(Cano=
nID);
+  if (StoredPos =3D=3D StoredMergedDecls.end())
+    return MergedDecls.find(Canon);
+
+  // Append the stored merged declarations to the merged declarations set.
+  MergedDeclsMap::iterator Pos =3D MergedDecls.find(Canon);
+  if (Pos =3D=3D MergedDecls.end())
+    Pos =3D MergedDecls.insert(std::make_pair(Canon,=20
+                                            SmallVector<DeclID, 2>())).fir=
st;
+  Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
+  StoredMergedDecls.erase(StoredPos);
+ =20
+  // Sort and uniquify the set of merged declarations.
+  llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
+  Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
+                    Pos->second.end());
+  return Pos;
+}
+
 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID I=
D) {
   Decl *previous =3D GetDecl(ID);
   ASTDeclReader::attachPreviousDecl(D, previous);
@@ -1469,7 +1879,8 @@
 /// \brief Read the declaration at the given offset from the AST file.
 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
   unsigned Index =3D ID - NUM_PREDEF_DECL_IDS;
-  RecordLocation Loc =3D DeclCursorForID(ID);
+  unsigned RawLocation =3D 0;
+  RecordLocation Loc =3D DeclCursorForID(ID, RawLocation);
   llvm::BitstreamCursor &DeclsCursor =3D Loc.F->DeclsCursor;
   // Keep track of where we are in the stream, then jump back there
   // after reading this declaration.
@@ -1484,7 +1895,7 @@
   RecordData Record;
   unsigned Code =3D DeclsCursor.ReadCode();
   unsigned Idx =3D 0;
-  ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, Record, Idx);
+  ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, RawLocation, Record=
,Idx);
=20
   Decl *D =3D 0;
   switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
@@ -1492,222 +1903,177 @@
   case DECL_CONTEXT_VISIBLE:
     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
   case DECL_TYPEDEF:
-    D =3D TypedefDecl::Create(Context, 0, SourceLocation(), SourceLocation=
(),
-                            0, 0);
+    D =3D TypedefDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_TYPEALIAS:
-    D =3D TypeAliasDecl::Create(Context, 0, SourceLocation(), SourceLocati=
on(),
-                              0, 0);
+    D =3D TypeAliasDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_ENUM:
-    D =3D EnumDecl::Create(Context, Decl::EmptyShell());
+    D =3D EnumDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_RECORD:
-    D =3D RecordDecl::Create(Context, Decl::EmptyShell());
+    D =3D RecordDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_ENUM_CONSTANT:
-    D =3D EnumConstantDecl::Create(Context, 0, SourceLocation(), 0, QualTy=
pe(),
-                                 0, llvm::APSInt());
+    D =3D EnumConstantDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_FUNCTION:
-    D =3D FunctionDecl::Create(Context, 0, SourceLocation(), SourceLocatio=
n(),
-                             DeclarationName(), QualType(), 0);
+    D =3D FunctionDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_LINKAGE_SPEC:
-    D =3D LinkageSpecDecl::Create(Context, 0, SourceLocation(), SourceLoca=
tion(),
-                                (LinkageSpecDecl::LanguageIDs)0,
-                                SourceLocation());
+    D =3D LinkageSpecDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_LABEL:
-    D =3D LabelDecl::Create(Context, 0, SourceLocation(), 0);
+    D =3D LabelDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_NAMESPACE:
-    D =3D NamespaceDecl::Create(Context, 0, SourceLocation(),
-                              SourceLocation(), 0);
+    D =3D NamespaceDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_NAMESPACE_ALIAS:
-    D =3D NamespaceAliasDecl::Create(Context, 0, SourceLocation(),
-                                   SourceLocation(), 0,=20
-                                   NestedNameSpecifierLoc(),
-                                   SourceLocation(), 0);
+    D =3D NamespaceAliasDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_USING:
-    D =3D UsingDecl::Create(Context, 0, SourceLocation(),
-                          NestedNameSpecifierLoc(), DeclarationNameInfo(),=20
-                          false);
+    D =3D UsingDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_USING_SHADOW:
-    D =3D UsingShadowDecl::Create(Context, 0, SourceLocation(), 0, 0);
+    D =3D UsingShadowDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_USING_DIRECTIVE:
-    D =3D UsingDirectiveDecl::Create(Context, 0, SourceLocation(),
-                                   SourceLocation(), NestedNameSpecifierLo=
c(),
-                                   SourceLocation(), 0, 0);
+    D =3D UsingDirectiveDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_UNRESOLVED_USING_VALUE:
-    D =3D UnresolvedUsingValueDecl::Create(Context, 0, SourceLocation(),
-                                         NestedNameSpecifierLoc(),=20
-                                         DeclarationNameInfo());
+    D =3D UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_UNRESOLVED_USING_TYPENAME:
-    D =3D UnresolvedUsingTypenameDecl::Create(Context, 0, SourceLocation(),
-                                            SourceLocation(),=20
-                                            NestedNameSpecifierLoc(),
-                                            SourceLocation(),
-                                            DeclarationName());
+    D =3D UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CXX_RECORD:
-    D =3D CXXRecordDecl::Create(Context, Decl::EmptyShell());
+    D =3D CXXRecordDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CXX_METHOD:
-    D =3D CXXMethodDecl::Create(Context, 0, SourceLocation(),
-                              DeclarationNameInfo(), QualType(), 0,
-                              false, SC_None, false, false, SourceLocation=
());
+    D =3D CXXMethodDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CXX_CONSTRUCTOR:
-    D =3D CXXConstructorDecl::Create(Context, Decl::EmptyShell());
+    D =3D CXXConstructorDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CXX_DESTRUCTOR:
-    D =3D CXXDestructorDecl::Create(Context, Decl::EmptyShell());
+    D =3D CXXDestructorDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CXX_CONVERSION:
-    D =3D CXXConversionDecl::Create(Context, Decl::EmptyShell());
+    D =3D CXXConversionDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_ACCESS_SPEC:
-    D =3D AccessSpecDecl::Create(Context, Decl::EmptyShell());
+    D =3D AccessSpecDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_FRIEND:
-    D =3D FriendDecl::Create(Context, Decl::EmptyShell());
+    D =3D FriendDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_FRIEND_TEMPLATE:
-    D =3D FriendTemplateDecl::Create(Context, Decl::EmptyShell());
+    D =3D FriendTemplateDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CLASS_TEMPLATE:
-    D =3D ClassTemplateDecl::Create(Context, Decl::EmptyShell());
+    D =3D ClassTemplateDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
-    D =3D ClassTemplateSpecializationDecl::Create(Context, Decl::EmptyShel=
l());
+    D =3D ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
-    D =3D ClassTemplatePartialSpecializationDecl::Create(Context,
-                                                       Decl::EmptyShell());
+    D =3D ClassTemplatePartialSpecializationDecl::CreateDeserialized(Conte=
xt, ID);
     break;
   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
-    D =3D ClassScopeFunctionSpecializationDecl::Create(Context,
-                                                     Decl::EmptyShell());
+    D =3D ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context=
, ID);
     break;
   case DECL_FUNCTION_TEMPLATE:
-      D =3D FunctionTemplateDecl::Create(Context, Decl::EmptyShell());
+    D =3D FunctionTemplateDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_TEMPLATE_TYPE_PARM:
-    D =3D TemplateTypeParmDecl::Create(Context, Decl::EmptyShell());
+    D =3D TemplateTypeParmDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_NON_TYPE_TEMPLATE_PARM:
-    D =3D NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
-                                        SourceLocation(), 0, 0, 0, QualTyp=
e(),
-                                        false, 0);
+    D =3D NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
-    D =3D NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
-                                        SourceLocation(), 0, 0, 0, QualTyp=
e(),
-                                        0, 0, Record[Idx++], 0);
+    D =3D NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[=
Idx++]);
     break;
   case DECL_TEMPLATE_TEMPLATE_PARM:
-    D =3D TemplateTemplateParmDecl::Create(Context, 0, SourceLocation(), 0=
, 0,
-                                         false, 0, 0);
+    D =3D TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_TYPE_ALIAS_TEMPLATE:
-    D =3D TypeAliasTemplateDecl::Create(Context, Decl::EmptyShell());
+    D =3D TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_STATIC_ASSERT:
-    D =3D StaticAssertDecl::Create(Context, 0, SourceLocation(), 0, 0,
-                                 SourceLocation());
+    D =3D StaticAssertDecl::CreateDeserialized(Context, ID);
     break;
-
   case DECL_OBJC_METHOD:
-    D =3D ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation=
(),
-                               Selector(), QualType(), 0, 0);
+    D =3D ObjCMethodDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_INTERFACE:
-    D =3D ObjCInterfaceDecl::Create(Context, 0, SourceLocation(), 0);
+    D =3D ObjCInterfaceDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_IVAR:
-    D =3D ObjCIvarDecl::Create(Context, 0, SourceLocation(), SourceLocatio=
n(),
-                             0, QualType(), 0, ObjCIvarDecl::None);
+    D =3D ObjCIvarDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_PROTOCOL:
-    D =3D ObjCProtocolDecl::Create(Context, 0, 0, SourceLocation(),
-                                 SourceLocation());
+    D =3D ObjCProtocolDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_AT_DEFS_FIELD:
-    D =3D ObjCAtDefsFieldDecl::Create(Context, 0, SourceLocation(),
-                                    SourceLocation(), 0, QualType(), 0);
-    break;
-  case DECL_OBJC_CLASS:
-    D =3D ObjCClassDecl::Create(Context, 0, SourceLocation());
-    break;
-  case DECL_OBJC_FORWARD_PROTOCOL:
-    D =3D ObjCForwardProtocolDecl::Create(Context, 0, SourceLocation());
+    D =3D ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_CATEGORY:
-    D =3D ObjCCategoryDecl::Create(Context, Decl::EmptyShell());
+    D =3D ObjCCategoryDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_CATEGORY_IMPL:
-    D =3D ObjCCategoryImplDecl::Create(Context, 0, 0, 0, SourceLocation(),
-                                     SourceLocation());
+    D =3D ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_IMPLEMENTATION:
-    D =3D ObjCImplementationDecl::Create(Context, 0, 0, 0, SourceLocation(=
),
-                                       SourceLocation());
+    D =3D ObjCImplementationDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_COMPATIBLE_ALIAS:
-    D =3D ObjCCompatibleAliasDecl::Create(Context, 0, SourceLocation(), 0,=
 0);
+    D =3D ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_PROPERTY:
-    D =3D ObjCPropertyDecl::Create(Context, 0, SourceLocation(), 0, Source=
Location(),
-                                 0);
+    D =3D ObjCPropertyDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_OBJC_PROPERTY_IMPL:
-    D =3D ObjCPropertyImplDecl::Create(Context, 0, SourceLocation(),
-                                     SourceLocation(), 0,
-                                     ObjCPropertyImplDecl::Dynamic, 0,
-                                     SourceLocation());
+    D =3D ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_FIELD:
-    D =3D FieldDecl::Create(Context, 0, SourceLocation(), SourceLocation()=
, 0,
-                          QualType(), 0, 0, false, false);
+    D =3D FieldDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_INDIRECTFIELD:
-    D =3D IndirectFieldDecl::Create(Context, 0, SourceLocation(), 0, QualT=
ype(),
-                                  0, 0);
+    D =3D IndirectFieldDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_VAR:
-    D =3D VarDecl::Create(Context, 0, SourceLocation(), SourceLocation(), =
0,
-                        QualType(), 0, SC_None, SC_None);
+    D =3D VarDecl::CreateDeserialized(Context, ID);
     break;
-
   case DECL_IMPLICIT_PARAM:
-    D =3D ImplicitParamDecl::Create(Context, 0, SourceLocation(), 0, QualT=
ype());
+    D =3D ImplicitParamDecl::CreateDeserialized(Context, ID);
     break;
-
   case DECL_PARM_VAR:
-    D =3D ParmVarDecl::Create(Context, 0, SourceLocation(), SourceLocation=
(), 0,
-                            QualType(), 0, SC_None, SC_None, 0);
+    D =3D ParmVarDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_FILE_SCOPE_ASM:
-    D =3D FileScopeAsmDecl::Create(Context, 0, 0, SourceLocation(),
-                                 SourceLocation());
+    D =3D FileScopeAsmDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_BLOCK:
-    D =3D BlockDecl::Create(Context, 0, SourceLocation());
+    D =3D BlockDecl::CreateDeserialized(Context, ID);
     break;
   case DECL_CXX_BASE_SPECIFIERS:
     Error("attempt to read a C++ base-specifier record as a declaration");
     return 0;
+  case DECL_IMPORT:
+    // Note: last entry of the ImportDecl record is the number of stored s=
ource=20
+    // locations.
+    D =3D ImportDecl::CreateDeserialized(Context, ID, Record.back());
+    break;
   }
=20
   assert(D && "Unknown declaration reading AST file");
   LoadedDecl(Index, D);
+  // Set the DeclContext before doing any deserialization, to make sure in=
ternal
+  // calls to Decl::getASTContext() by Decl's methods will find the
+  // TranslationUnitDecl without crashing.
+  D->setDeclContext(Context.getTranslationUnitDecl());
   Reader.Visit(D);
=20
   // If this declaration is also a declaration context, get the
@@ -1743,16 +2109,18 @@
=20
   // Load any relevant update records.
   loadDeclUpdateRecords(ID, D);
- =20
-  if (ObjCChainedCategoriesInterfaces.count(ID))
-    loadObjCChainedCategories(ID, cast<ObjCInterfaceDecl>(D));
+
+  // Load the categories after recursive loading is finished.
+  if (ObjCInterfaceDecl *Class =3D dyn_cast<ObjCInterfaceDecl>(D))
+    if (Class->isThisDeclarationADefinition())
+      loadObjCCategories(ID, Class);
  =20
   // If we have deserialized a declaration that has a definition the
   // AST consumer might need to know about, queue it.
   // We don't pass it to the consumer immediately because we may be in rec=
ursive
   // loading, and some declarations may still be initializing.
   if (isConsumerInterestedIn(D))
-      InterestingDecls.push_back(D);
+    InterestingDecls.push_back(D);
  =20
   return D;
 }
@@ -1766,7 +2134,7 @@
     FileOffsetsTy &UpdateOffsets =3D UpdI->second;
     for (FileOffsetsTy::iterator
          I =3D UpdateOffsets.begin(), E =3D UpdateOffsets.end(); I !=3D E;=
 ++I) {
-      Module *F =3D I->first;
+      ModuleFile *F =3D I->first;
       uint64_t Offset =3D I->second;
       llvm::BitstreamCursor &Cursor =3D F->DeclsCursor;
       SavedStreamPosition SavedPosition(Cursor);
@@ -1778,179 +2146,328 @@
       assert(RecCode =3D=3D DECL_UPDATES && "Expected DECL_UPDATES record!=
");
      =20
       unsigned Idx =3D 0;
-      ASTDeclReader Reader(*this, *F, Cursor, ID, Record, Idx);
+      ASTDeclReader Reader(*this, *F, Cursor, ID, 0, Record, Idx);
       Reader.UpdateDecl(D, *F, Record);
     }
   }
 }
=20
 namespace {
+  struct CompareLocalRedeclarationsInfoToID {
+    bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
+      return X.FirstID < Y;
+    }
+
+    bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
+      return X < Y.FirstID;
+    }
+
+    bool operator()(const LocalRedeclarationsInfo &X,=20
+                    const LocalRedeclarationsInfo &Y) {
+      return X.FirstID < Y.FirstID;
+    }
+    bool operator()(DeclID X, DeclID Y) {
+      return X < Y;
+    }
+  };
+ =20
+  /// \brief Module visitor class that finds all of the redeclarations of =
a=20
+  ///=20
+  class RedeclChainVisitor {
+    ASTReader &Reader;
+    SmallVectorImpl<DeclID> &SearchDecls;
+    llvm::SmallPtrSet<Decl *, 16> &Deserialized;
+    GlobalDeclID CanonID;
+    llvm::SmallVector<Decl *, 4> Chain;
+   =20
+  public:
+    RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchD=
ecls,
+                       llvm::SmallPtrSet<Decl *, 16> &Deserialized,
+                       GlobalDeclID CanonID)
+      : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialize=
d),
+        CanonID(CanonID) {=20
+      for (unsigned I =3D 0, N =3D SearchDecls.size(); I !=3D N; ++I)
+        addToChain(Reader.GetDecl(SearchDecls[I]));
+    }
+   =20
+    static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
+      if (Preorder)
+        return false;
+     =20
+      return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
+    }
+   =20
+    void addToChain(Decl *D) {
+      if (!D)
+        return;
+     =20
+      if (Deserialized.count(D)) {
+        Deserialized.erase(D);
+        Chain.push_back(D);
+      }
+    }
+   =20
+    void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
+      // Map global ID of the first declaration down to the local ID
+      // used in this module file.
+      DeclID ID =3D Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
+      if (!ID)
+        return;
+     =20
+      // Perform a binary search to find the local redeclarations for this
+      // declaration (if any).
+      const LocalRedeclarationsInfo *Result
+        =3D std::lower_bound(M.RedeclarationsMap,
+                           M.RedeclarationsMap + M.LocalNumRedeclarationsI=
nMap,=20
+                           ID, CompareLocalRedeclarationsInfoToID());
+      if (Result =3D=3D M.RedeclarationsMap + M.LocalNumRedeclarationsInMa=
p ||
+          Result->FirstID !=3D ID) {
+        // If we have a previously-canonical singleton declaration that wa=
s=20
+        // merged into another redeclaration chain, create a trivial chain
+        // for this single declaration so that it will get wired into the=20
+        // complete redeclaration chain.
+        if (GlobalID !=3D CanonID &&=20
+            GlobalID - NUM_PREDEF_DECL_IDS >=3D M.BaseDeclID &&=20
+            GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecl=
s) {
+          addToChain(Reader.GetDecl(GlobalID));
+        }
+       =20
+        return;
+      }
+     =20
+      // Dig out all of the redeclarations.
+      unsigned Offset =3D Result->Offset;
+      unsigned N =3D M.RedeclarationChains[Offset];
+      M.RedeclarationChains[Offset++] =3D 0; // Don't try to deserialize a=
gain
+      for (unsigned I =3D 0; I !=3D N; ++I)
+        addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++])=
);
+    }
+   =20
+    bool visit(ModuleFile &M) {
+      // Visit each of the declarations.
+      for (unsigned I =3D 0, N =3D SearchDecls.size(); I !=3D N; ++I)
+        searchForID(M, SearchDecls[I]);
+      return false;
+    }
+   =20
+    ArrayRef<Decl *> getChain() const {
+      return Chain;
+    }
+  };
+}
+
+void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
+  Decl *D =3D GetDecl(ID); =20
+  Decl *CanonDecl =3D D->getCanonicalDecl();
+ =20
+  // Determine the set of declaration IDs we'll be searching for.
+  llvm::SmallVector<DeclID, 1> SearchDecls;
+  GlobalDeclID CanonID =3D 0;
+  if (D =3D=3D CanonDecl) {
+    SearchDecls.push_back(ID); // Always first.
+    CanonID =3D ID;
+  }
+  MergedDeclsMap::iterator MergedPos =3D combineStoredMergedDecls(CanonDec=
l, ID);
+  if (MergedPos !=3D MergedDecls.end())
+    SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end())=
; =20
+ =20
+  // Build up the list of redeclarations.
+  RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, Cano=
nID);
+  ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
+ =20
+  // Retrieve the chains.
+  ArrayRef<Decl *> Chain =3D Visitor.getChain();
+  if (Chain.empty())
+    return;
+   =20
+  // Hook up the chains.
+  Decl *MostRecent =3D CanonDecl->getMostRecentDecl();
+  for (unsigned I =3D 0, N =3D Chain.size(); I !=3D N; ++I) {
+    if (Chain[I] =3D=3D CanonDecl)
+      continue;
+   =20
+    ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
+    MostRecent =3D Chain[I];
+  }
+ =20
+  ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent); =20
+}
+
+namespace {
+  struct CompareObjCCategoriesInfo {
+    bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
+      return X.DefinitionID < Y;
+    }
+   =20
+    bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
+      return X < Y.DefinitionID;
+    }
+   =20
+    bool operator()(const ObjCCategoriesInfo &X,=20
+                    const ObjCCategoriesInfo &Y) {
+      return X.DefinitionID < Y.DefinitionID;
+    }
+    bool operator()(DeclID X, DeclID Y) {
+      return X < Y;
+    }
+  };
+
   /// \brief Given an ObjC interface, goes through the modules and links t=
o the
   /// interface all the categories for it.
-  class ObjCChainedCategoriesVisitor {
+  class ObjCCategoriesVisitor {
     ASTReader &Reader;
     serialization::GlobalDeclID InterfaceID;
     ObjCInterfaceDecl *Interface;
-    ObjCCategoryDecl *GlobHeadCat, *GlobTailCat;
+    llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
+    unsigned PreviousGeneration;
+    ObjCCategoryDecl *Tail;
     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
-
+   =20
+    void add(ObjCCategoryDecl *Cat) {
+      // Only process each category once.
+      if (!Deserialized.count(Cat))
+        return;
+      Deserialized.erase(Cat);
+     =20
+      // Check for duplicate categories.
+      if (Cat->getDeclName()) {
+        ObjCCategoryDecl *&Existing =3D NameCategoryMap[Cat->getDeclName()=
];
+        if (Existing &&=20
+            Reader.getOwningModuleFile(Existing)=20
+                                          !=3D Reader.getOwningModuleFile(=
Cat)) {
+          // FIXME: We should not warn for duplicates in diamond:
+          //
+          //   MT     //
+          //  /  \    //
+          // ML  MR   //
+          //  \  /    //
+          //   MB     //
+          //
+          // If there are duplicates in ML/MR, there will be warning when=20
+          // creating MB *and* when importing MB. We should not warn when=20
+          // importing.
+          Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
+            << Interface->getDeclName() << Cat->getDeclName();
+          Reader.Diag(Existing->getLocation(), diag::note_previous_definit=
ion);
+        } else if (!Existing) {
+          // Record this category.
+          Existing =3D Cat;
+        }
+      }
+     =20
+      // Add this category to the end of the chain.
+      if (Tail)
+        ASTDeclReader::setNextObjCCategory(Tail, Cat);
+      else
+        Interface->setCategoryList(Cat);
+      Tail =3D Cat;
+    }
+   =20
   public:
-    ObjCChainedCategoriesVisitor(ASTReader &Reader,
-                                 serialization::GlobalDeclID InterfaceID,
-                                 ObjCInterfaceDecl *Interface)
+    ObjCCategoriesVisitor(ASTReader &Reader,
+                          serialization::GlobalDeclID InterfaceID,
+                          ObjCInterfaceDecl *Interface,
+                        llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deseria=
lized,
+                          unsigned PreviousGeneration)
       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
-        GlobHeadCat(0), GlobTailCat(0) { }
-
-    static bool visit(Module &M, void *UserData) {
-      return static_cast<ObjCChainedCategoriesVisitor *>(UserData)->visit(=
M);
-    }
-
-    bool visit(Module &M) {
-      if (Reader.isDeclIDFromModule(InterfaceID, M))
-        return true; // We reached the module where the interface originat=
ed
-                    // from. Stop traversing the imported modules.
-
-      Module::ChainedObjCCategoriesMap::iterator
-        I =3D M.ChainedObjCCategories.find(InterfaceID);
-      if (I =3D=3D M.ChainedObjCCategories.end())
-        return false;
-
-      ObjCCategoryDecl *
-        HeadCat =3D Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.f=
irst);
-      ObjCCategoryDecl *
-        TailCat =3D Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.s=
econd);
-
-      addCategories(HeadCat, TailCat);
-      return false;
-    }
-
-    void addCategories(ObjCCategoryDecl *HeadCat,
-                       ObjCCategoryDecl *TailCat =3D 0) {
-      if (!HeadCat) {
-        assert(!TailCat);
-        return;
-      }
-
-      if (!TailCat) {
-        TailCat =3D HeadCat;
-        while (TailCat->getNextClassCategory())
-          TailCat =3D TailCat->getNextClassCategory();
-      }
-
-      if (!GlobHeadCat) {
-        GlobHeadCat =3D HeadCat;
-        GlobTailCat =3D TailCat;
-      } else {
-        ASTDeclReader::setNextObjCCategory(GlobTailCat, HeadCat);
-        GlobTailCat =3D TailCat;
-      }
-
-      llvm::DenseSet<DeclarationName> Checked;
-      for (ObjCCategoryDecl *Cat =3D HeadCat,
-                            *CatEnd =3D TailCat->getNextClassCategory();
-             Cat !=3D CatEnd; Cat =3D Cat->getNextClassCategory()) {
-        if (Checked.count(Cat->getDeclName()))
-          continue;
-        Checked.insert(Cat->getDeclName());
-        checkForDuplicate(Cat);
+        Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
+        Tail(0)=20
+    {
+      // Populate the name -> category map with the set of known categorie=
s.
+      for (ObjCCategoryDecl *Cat =3D Interface->getCategoryList(); Cat;
+           Cat =3D Cat->getNextClassCategory()) {
+        if (Cat->getDeclName())
+          NameCategoryMap[Cat->getDeclName()] =3D Cat;
+       =20
+        // Keep track of the tail of the category list.
+        Tail =3D Cat;
       }
     }
=20
-    /// \brief Warns for duplicate categories that come from different mod=
ules.
-    void checkForDuplicate(ObjCCategoryDecl *Cat) {
-      DeclarationName Name =3D Cat->getDeclName();
-      // Find the top category with the same name. We do not want to warn =
for
-      // duplicates along the established chain because there were already
-      // warnings for them when the module was created. We only want to wa=
rn for
-      // duplicates between non-dependent modules:
-      //
-      //   MT     //
-      //  /  \    //
-      // ML  MR   //
-      //
-      // We want to warn for duplicates between ML and MR,not between ML a=
nd MT.
-      //
-      // FIXME: We should not warn for duplicates in diamond:
-      //
-      //   MT     //
-      //  /  \    //
-      // ML  MR   //
-      //  \  /    //
-      //   MB     //
-      //
-      // If there are duplicates in ML/MR, there will be warning when crea=
ting
-      // MB *and* when importing MB. We should not warn when importing.
-      for (ObjCCategoryDecl *Next =3D Cat->getNextClassCategory(); Next;
-             Next =3D Next->getNextClassCategory()) {
-        if (Next->getDeclName() =3D=3D Name)
-          Cat =3D Next;
-      }
-
-      ObjCCategoryDecl *&PrevCat =3D NameCategoryMap[Name];
-      if (!PrevCat)
-        PrevCat =3D Cat;
-
-      if (PrevCat !=3D Cat) {
-        Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
-          << Interface->getDeclName() << Name;
-        Reader.Diag(PrevCat->getLocation(), diag::note_previous_definition=
);
-      }
+    static bool visit(ModuleFile &M, void *UserData) {
+      return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
     }
=20
-    ObjCCategoryDecl *getHeadCategory() const { return GlobHeadCat; }
+    bool visit(ModuleFile &M) {
+      // If we've loaded all of the category information we care about from
+      // this module file, we're done.
+      if (M.Generation <=3D PreviousGeneration)
+        return true;
+     =20
+      // Map global ID of the definition down to the local ID used in this=20
+      // module file. If there is no such mapping, we'll find nothing here
+      // (or in any module it imports).
+      DeclID LocalID =3D Reader.mapGlobalIDToModuleFileGlobalID(M, Interfa=
ceID);
+      if (!LocalID)
+        return true;
+
+      // Perform a binary search to find the local redeclarations for this
+      // declaration (if any).
+      const ObjCCategoriesInfo *Result
+        =3D std::lower_bound(M.ObjCCategoriesMap,
+                           M.ObjCCategoriesMap + M.LocalNumObjCCategoriesI=
nMap,=20
+                           LocalID, CompareObjCCategoriesInfo());
+      if (Result =3D=3D M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMa=
p ||
+          Result->DefinitionID !=3D LocalID) {
+        // We didn't find anything. If the class definition is in this mod=
ule
+        // file, then the module files it depends on cannot have any categ=
ories,
+        // so suppress further lookup.
+        return Reader.isDeclIDFromModule(InterfaceID, M);
+      }
+     =20
+      // We found something. Dig out all of the categories.
+      unsigned Offset =3D Result->Offset;
+      unsigned N =3D M.ObjCCategories[Offset];
+      M.ObjCCategories[Offset++] =3D 0; // Don't try to deserialize again
+      for (unsigned I =3D 0; I !=3D N; ++I)
+        add(cast_or_null<ObjCCategoryDecl>(
+              Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
+      return true;
+    }
   };
 }
=20
-void ASTReader::loadObjCChainedCategories(serialization::GlobalDeclID ID,
-                                          ObjCInterfaceDecl *D) {
-  ObjCChainedCategoriesVisitor Visitor(*this, ID, D);
-  ModuleMgr.visit(ObjCChainedCategoriesVisitor::visit, &Visitor);
-  // Also add the categories that the interface already links to.
-  Visitor.addCategories(D->getCategoryList());
-  D->setCategoryList(Visitor.getHeadCategory());
+void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
+                                   ObjCInterfaceDecl *D,
+                                   unsigned PreviousGeneration) {
+  ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
+                                PreviousGeneration);
+  ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
 }
=20
-void ASTDeclReader::UpdateDecl(Decl *D, Module &Module,
+void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
                                const RecordData &Record) {
   unsigned Idx =3D 0;
   while (Idx < Record.size()) {
     switch ((DeclUpdateKind)Record[Idx++]) {
-    case UPD_CXX_SET_DEFINITIONDATA: {
-      CXXRecordDecl *RD =3D cast<CXXRecordDecl>(D);
-      CXXRecordDecl *DefinitionDecl
-        =3D Reader.ReadDeclAs<CXXRecordDecl>(Module, Record, Idx);
-      assert(!RD->DefinitionData && "DefinitionData is already set!");
-      InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
-      break;
-    }
-
     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
-      cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(Module, Record, =
Idx));
+      cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Reco=
rd, Idx));
       break;
=20
     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
       // It will be added to the template's specializations set when loade=
d.
-      (void)Reader.ReadDecl(Module, Record, Idx);
+      (void)Reader.ReadDecl(ModuleFile, Record, Idx);
       break;
=20
     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
       NamespaceDecl *Anon
-        =3D Reader.ReadDeclAs<NamespaceDecl>(Module, Record, Idx);
-      // Guard against these being loaded out of original order. Don't use
-      // getNextNamespace(), since it tries to access the context and can'=
t in
-      // the middle of deserialization.
-      if (!Anon->NextNamespace) {
+        =3D Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
+     =20
+      // Each module has its own anonymous namespace, which is disjoint fr=
om
+      // any other module's anonymous namespaces, so don't attach the anon=
ymous
+      // namespace at all.
+      if (ModuleFile.Kind !=3D MK_Module) {
         if (TranslationUnitDecl *TU =3D dyn_cast<TranslationUnitDecl>(D))
           TU->setAnonymousNamespace(Anon);
         else
-          cast<NamespaceDecl>(D)->OrigOrAnonNamespace.setPointer(Anon);
+          cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
       }
       break;
     }
=20
     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantia=
tion(
-          Reader.ReadSourceLocation(Module, Record, Idx));
+          Reader.ReadSourceLocation(ModuleFile, Record, Idx));
       break;
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTReaderInternals.h
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderInternals.h	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderInternals.h	=
Tue Apr 17 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
=20
 #include "clang/Basic/OnDiskHashTable.h"
 #include "clang/AST/DeclarationName.h"
+#include "llvm/Support/Endian.h"
 #include <utility>
 #include <sys/stat.h>
=20
@@ -26,7 +27,7 @@
  =20
 namespace serialization {
=20
-class Module;
+class ModuleFile;
=20
 namespace reader {
=20
@@ -34,14 +35,15 @@
 /// in an AST file.
 class ASTDeclContextNameLookupTrait {
   ASTReader &Reader;
-  Module &F;
+  ModuleFile &F;
  =20
 public:
   /// \brief Pair of begin/end iterators for DeclIDs.
   ///
   /// Note that these declaration IDs are local to the module that contain=
s this
   /// particular lookup t
-  typedef std::pair<DeclID *, DeclID *> data_type;
+  typedef llvm::support::ulittle32_t LE32DeclID;
+  typedef std::pair<LE32DeclID *, LE32DeclID *> data_type;
=20
   /// \brief Special internal key for declaration names.
   /// The hash table creates keys for comparison; we do not create
@@ -56,7 +58,7 @@
   typedef DeclNameKey internal_key_type;
=20
   explicit ASTDeclContextNameLookupTrait(ASTReader &Reader,=20
-                                         Module &F)=20
+                                         ModuleFile &F)=20
     : Reader(Reader), F(F) { }
=20
   static bool EqualKey(const internal_key_type& a,
@@ -84,7 +86,7 @@
 /// \brief Class that performs lookup for an identifier stored in an AST f=
ile.
 class ASTIdentifierLookupTrait {
   ASTReader &Reader;
-  Module &F;
+  ModuleFile &F;
  =20
   // If we know the IdentifierInfo in advance, it is here and we will
   // not build a new one. Used when deserializing information about an
@@ -98,7 +100,7 @@
  =20
   typedef external_key_type internal_key_type;
  =20
-  ASTIdentifierLookupTrait(ASTReader &Reader, Module &F,
+  ASTIdentifierLookupTrait(ASTReader &Reader, ModuleFile &F,
                            IdentifierInfo *II =3D 0)
     : Reader(Reader), F(F), KnownII(II) { }
  =20
@@ -127,6 +129,9 @@
   IdentifierInfo *ReadData(const internal_key_type& k,
                            const unsigned char* d,
                            unsigned DataLen);
+ =20
+  ASTReader &getReader() const { return Reader; }
+ =20
 };
  =20
 /// \brief The on-disk hash table used to contain information about
@@ -138,7 +143,7 @@
 /// method pool stored in an AST file.
 class ASTSelectorLookupTrait {
   ASTReader &Reader;
-  Module &F;
+  ModuleFile &F;
  =20
 public:
   struct data_type {
@@ -150,7 +155,7 @@
   typedef Selector external_key_type;
   typedef external_key_type internal_key_type;
  =20
-  ASTSelectorLookupTrait(ASTReader &Reader, Module &F)=20
+  ASTSelectorLookupTrait(ASTReader &Reader, ModuleFile &F)=20
     : Reader(Reader), F(F) { }
  =20
   static bool EqualKey(const internal_key_type& a,
@@ -185,7 +190,7 @@
 /// and symlinks.
 class HeaderFileInfoTrait {
   ASTReader &Reader;
-  Module &M;
+  ModuleFile &M;
   HeaderSearch *HS;
   const char *FrameworkStrings;
   const char *SearchPath;
@@ -210,7 +215,7 @@
  =20
   typedef HeaderFileInfo data_type;
  =20
-  HeaderFileInfoTrait(ASTReader &Reader, Module &M, HeaderSearch *HS,
+  HeaderFileInfoTrait(ASTReader &Reader, ModuleFile &M, HeaderSearch *HS,
                       const char *FrameworkStrings,
                       const char *SearchPath =3D 0)=20
   : Reader(Reader), M(M), HS(HS), FrameworkStrings(FrameworkStrings),=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTReaderStmt.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderStmt.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTReaderStmt.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/StmtVisitor.h"
+#include "llvm/ADT/SmallString.h"
 using namespace clang;
 using namespace clang::serialization;
=20
@@ -25,7 +26,7 @@
     typedef ASTReader::RecordData RecordData;
    =20
     ASTReader &Reader;
-    Module &F;
+    ModuleFile &F;
     llvm::BitstreamCursor &DeclsCursor;
     const ASTReader::RecordData &Record;
     unsigned &Idx;
@@ -66,7 +67,7 @@
     }
=20
   public:
-    ASTStmtReader(ASTReader &Reader, Module &F,
+    ASTStmtReader(ASTReader &Reader, ModuleFile &F,
                   llvm::BitstreamCursor &Cursor,
                   const ASTReader::RecordData &Record, unsigned &Idx)
       : Reader(Reader), F(F), DeclsCursor(Cursor), Record(Record), Idx(Idx=
) { }
@@ -78,7 +79,10 @@
     /// \brief The number of record fields required for the Expr class
     /// itself.
     static const unsigned NumExprFields =3D NumStmtFields + 7;
-   =20
+
+    /// \brief Read and initialize a ExplicitTemplateArgumentList structur=
e.
+    void ReadTemplateKWAndArgsInfo(ASTTemplateKWAndArgsInfo &Args,
+                                   unsigned NumTemplateArgs);
     /// \brief Read and initialize a ExplicitTemplateArgumentList structur=
e.
     void ReadExplicitTemplateArgumentList(ASTTemplateArgumentListInfo &Arg=
List,
                                           unsigned NumTemplateArgs);
@@ -91,15 +95,16 @@
 }
=20
 void ASTStmtReader::
-ReadExplicitTemplateArgumentList(ASTTemplateArgumentListInfo &ArgList,
-                                 unsigned NumTemplateArgs) {
+ReadTemplateKWAndArgsInfo(ASTTemplateKWAndArgsInfo &Args,
+                          unsigned NumTemplateArgs) {
+  SourceLocation TemplateKWLoc =3D ReadSourceLocation(Record, Idx);
   TemplateArgumentListInfo ArgInfo;
   ArgInfo.setLAngleLoc(ReadSourceLocation(Record, Idx));
   ArgInfo.setRAngleLoc(ReadSourceLocation(Record, Idx));
   for (unsigned i =3D 0; i !=3D NumTemplateArgs; ++i)
     ArgInfo.addArgument(
         Reader.ReadTemplateArgumentLoc(F, Record, Idx));
-  ArgList.initializeFrom(ArgInfo);
+  Args.initializeFrom(TemplateKWLoc, ArgInfo);
 }
=20
 void ASTStmtReader::VisitStmt(Stmt *S) {
@@ -326,10 +331,11 @@
=20
   E->DeclRefExprBits.HasQualifier =3D Record[Idx++];
   E->DeclRefExprBits.HasFoundDecl =3D Record[Idx++];
-  E->DeclRefExprBits.HasExplicitTemplateArgs =3D Record[Idx++];
+  E->DeclRefExprBits.HasTemplateKWAndArgsInfo =3D Record[Idx++];
   E->DeclRefExprBits.HadMultipleCandidates =3D Record[Idx++];
+  E->DeclRefExprBits.RefersToEnclosingLocal =3D Record[Idx++];
   unsigned NumTemplateArgs =3D 0;
-  if (E->hasExplicitTemplateArgs())
+  if (E->hasTemplateKWAndArgsInfo())
     NumTemplateArgs =3D Record[Idx++];
=20
   if (E->hasQualifier())
@@ -339,9 +345,9 @@
   if (E->hasFoundDecl())
     E->getInternalFoundDecl() =3D ReadDeclAs<NamedDecl>(Record, Idx);
=20
-  if (E->hasExplicitTemplateArgs())
-    ReadExplicitTemplateArgumentList(E->getExplicitTemplateArgs(),
-                                     NumTemplateArgs);
+  if (E->hasTemplateKWAndArgsInfo())
+    ReadTemplateKWAndArgsInfo(*E->getTemplateKWAndArgsInfo(),
+                              NumTemplateArgs);
=20
   E->setDecl(ReadDeclAs<ValueDecl>(Record, Idx));
   E->setLocation(ReadSourceLocation(Record, Idx));
@@ -372,12 +378,13 @@
   assert(Record[Idx] =3D=3D E->getNumConcatenated() &&
          "Wrong number of concatenated tokens!");
   ++Idx;
-  E->Kind =3D static_cast<StringLiteral::StringKind>(Record[Idx++]);
-  E->IsPascal =3D Record[Idx++];
+  StringLiteral::StringKind kind =3D
+        static_cast<StringLiteral::StringKind>(Record[Idx++]);
+  bool isPascal =3D Record[Idx++];
=20
   // Read string data
-  llvm::SmallString<16> Str(&Record[Idx], &Record[Idx] + Len);
-  E->setString(Reader.getContext(), Str.str());
+  SmallString<16> Str(&Record[Idx], &Record[Idx] + Len);
+  E->setString(Reader.getContext(), Str.str(), kind, isPascal);
   Idx +=3D Len;
=20
   // Read source locations
@@ -567,8 +574,6 @@
   E->SubExprs[BinaryConditionalOperator::RHS] =3D Reader.ReadSubExpr();
   E->QuestionLoc =3D ReadSourceLocation(Record, Idx);
   E->ColonLoc =3D ReadSourceLocation(Record, Idx);
-
-  E->getOpaqueValue()->setSourceExpr(E->getCommon());
 }
=20
 void ASTStmtReader::VisitImplicitCastExpr(ImplicitCastExpr *E) {
@@ -614,6 +619,7 @@
   } else
     E->ArrayFillerOrUnionFieldInit =3D ReadDeclAs<FieldDecl>(Record, Idx);
   E->sawArrayRangeDesignator(Record[Idx++]);
+  E->setInitializesStdInitializerList(Record[Idx++]);
   unsigned NumInits =3D Record[Idx++];
   E->reserveInits(Reader.getContext(), NumInits);
   if (isArrayFiller) {
@@ -747,14 +753,6 @@
   E->setBlockDecl(ReadDeclAs<BlockDecl>(Record, Idx));
 }
=20
-void ASTStmtReader::VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
-  VisitExpr(E);
-  E->setDecl(ReadDeclAs<VarDecl>(Record, Idx));
-  E->setLocation(ReadSourceLocation(Record, Idx));
-  E->setByRef(Record[Idx++]);
-  E->setConstQualAdded(Record[Idx++]);
-}
-
 void ASTStmtReader::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
   VisitExpr(E);
   E->NumAssocs =3D Record[Idx++];
@@ -774,23 +772,30 @@
   E->RParenLoc =3D ReadSourceLocation(Record, Idx);
 }
=20
+void ASTStmtReader::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
+  VisitExpr(E);
+  unsigned numSemanticExprs =3D Record[Idx++];
+  assert(numSemanticExprs + 1 =3D=3D E->PseudoObjectExprBits.NumSubExprs);
+  E->PseudoObjectExprBits.ResultIndex =3D Record[Idx++];
+
+  // Read the syntactic expression.
+  E->getSubExprsBuffer()[0] =3D Reader.ReadSubExpr();
+
+  // Read all the semantic expressions.
+  for (unsigned i =3D 0; i !=3D numSemanticExprs; ++i) {
+    Expr *subExpr =3D Reader.ReadSubExpr();
+    E->getSubExprsBuffer()[i+1] =3D subExpr;
+  }
+}
+
 void ASTStmtReader::VisitAtomicExpr(AtomicExpr *E) {
   VisitExpr(E);
-  E->setOp(AtomicExpr::AtomicOp(Record[Idx++]));
-  E->setPtr(Reader.ReadSubExpr());
-  E->setOrder(Reader.ReadSubExpr());
-  E->setNumSubExprs(2);
-  if (E->getOp() !=3D AtomicExpr::Load) {
-    E->setVal1(Reader.ReadSubExpr());
-    E->setNumSubExprs(3);
-  }
-  if (E->isCmpXChg()) {
-    E->setOrderFail(Reader.ReadSubExpr());
-    E->setVal2(Reader.ReadSubExpr());
-    E->setNumSubExprs(5);
-  }
-  E->setBuiltinLoc(ReadSourceLocation(Record, Idx));
-  E->setRParenLoc(ReadSourceLocation(Record, Idx));
+  E->Op =3D AtomicExpr::AtomicOp(Record[Idx++]);
+  E->NumSubExprs =3D AtomicExpr::getNumSubExprs(E->Op);
+  for (unsigned I =3D 0; I !=3D E->NumSubExprs; ++I)
+    E->SubExprs[I] =3D Reader.ReadSubExpr();
+  E->BuiltinLoc =3D ReadSourceLocation(Record, Idx);
+  E->RParenLoc =3D ReadSourceLocation(Record, Idx);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -802,6 +807,45 @@
   E->setAtLoc(ReadSourceLocation(Record, Idx));
 }
=20
+void ASTStmtReader::VisitObjCNumericLiteral(ObjCNumericLiteral *E) {
+  VisitExpr(E);
+  // could be one of several IntegerLiteral, FloatLiteral, etc.
+  E->Number =3D Reader.ReadSubStmt();
+  E->ObjCNumericLiteralMethod =3D ReadDeclAs<ObjCMethodDecl>(Record, Idx);
+  E->AtLoc =3D ReadSourceLocation(Record, Idx);
+}
+
+void ASTStmtReader::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
+  VisitExpr(E);
+  unsigned NumElements =3D Record[Idx++];
+  assert(NumElements =3D=3D E->getNumElements() && "Wrong number of elemen=
ts");
+  Expr **Elements =3D E->getElements();
+  for (unsigned I =3D 0, N =3D NumElements; I !=3D N; ++I)
+    Elements[I] =3D Reader.ReadSubExpr();
+  E->ArrayWithObjectsMethod =3D ReadDeclAs<ObjCMethodDecl>(Record, Idx);
+  E->Range =3D ReadSourceRange(Record, Idx);
+}
+
+void ASTStmtReader::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
+  VisitExpr(E);
+  unsigned NumElements =3D Record[Idx++];
+  assert(NumElements =3D=3D E->getNumElements() && "Wrong number of elemen=
ts");
+  bool HasPackExpansions =3D Record[Idx++];
+  assert(HasPackExpansions =3D=3D E->HasPackExpansions &&"Pack expansion m=
ismatch");
+  ObjCDictionaryLiteral::KeyValuePair *KeyValues =3D E->getKeyValues();
+  ObjCDictionaryLiteral::ExpansionData *Expansions =3D E->getExpansionData=
();
+  for (unsigned I =3D 0; I !=3D NumElements; ++I) {
+    KeyValues[I].Key =3D Reader.ReadSubExpr();
+    KeyValues[I].Value =3D Reader.ReadSubExpr();
+    if (HasPackExpansions) {
+      Expansions[I].EllipsisLoc =3D ReadSourceLocation(Record, Idx);
+      Expansions[I].NumExpansionsPlusOne =3D Record[Idx++];
+    }
+  }
+  E->DictWithObjectsMethod =3D ReadDeclAs<ObjCMethodDecl>(Record, Idx);
+  E->Range =3D ReadSourceRange(Record, Idx);
+}
+
 void ASTStmtReader::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
   VisitExpr(E);
   E->setEncodedTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
@@ -834,13 +878,15 @@
=20
 void ASTStmtReader::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
   VisitExpr(E);
+  unsigned MethodRefFlags =3D Record[Idx++];
   bool Implicit =3D Record[Idx++] !=3D 0;
   if (Implicit) {
     ObjCMethodDecl *Getter =3D ReadDeclAs<ObjCMethodDecl>(Record, Idx);
     ObjCMethodDecl *Setter =3D ReadDeclAs<ObjCMethodDecl>(Record, Idx);
-    E->setImplicitProperty(Getter, Setter);
+    E->setImplicitProperty(Getter, Setter, MethodRefFlags);
   } else {
-    E->setExplicitProperty(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
+    E->setExplicitProperty(ReadDeclAs<ObjCPropertyDecl>(Record, Idx),
+                           MethodRefFlags);
   }
   E->setLocation(ReadSourceLocation(Record, Idx));
   E->setReceiverLocation(ReadSourceLocation(Record, Idx));
@@ -857,6 +903,15 @@
   }
 }
=20
+void ASTStmtReader::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
+  VisitExpr(E);
+  E->setRBracket(ReadSourceLocation(Record, Idx));
+  E->setBaseExpr(Reader.ReadSubExpr());
+  E->setKeyExpr(Reader.ReadSubExpr());
+  E->GetAtIndexMethodDecl =3D ReadDeclAs<ObjCMethodDecl>(Record, Idx);
+  E->SetAtIndexMethodDecl =3D ReadDeclAs<ObjCMethodDecl>(Record, Idx);
+}
+
 void ASTStmtReader::VisitObjCMessageExpr(ObjCMessageExpr *E) {
   VisitExpr(E);
   assert(Record[Idx] =3D=3D E->getNumArgs());
@@ -864,6 +919,7 @@
   unsigned NumStoredSelLocs =3D Record[Idx++];
   E->SelLocsKind =3D Record[Idx++];=20
   E->setDelegateInitCall(Record[Idx++]);
+  E->IsImplicit =3D Record[Idx++];
   ObjCMessageExpr::ReceiverKind Kind
     =3D static_cast<ObjCMessageExpr::ReceiverKind>(Record[Idx++]);
   switch (Kind) {
@@ -958,6 +1014,12 @@
   S->setThrowLoc(ReadSourceLocation(Record, Idx));
 }
=20
+void ASTStmtReader::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
+  VisitExpr(E);
+  E->setValue(Record[Idx++]);
+  E->setLocation(ReadSourceLocation(Record, Idx));
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // C++ Expressions and Statements
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -992,6 +1054,15 @@
   S->setBody(Reader.ReadSubStmt());
 }
=20
+void ASTStmtReader::VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
+  VisitStmt(S);
+  S->KeywordLoc =3D ReadSourceLocation(Record, Idx);
+  S->IsIfExists =3D Record[Idx++];
+  S->QualifierLoc =3D Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
+  ReadDeclarationNameInfo(S->NameInfo, Record, Idx);
+  S->SubStmt =3D Reader.ReadSubStmt();
+}
+
 void ASTStmtReader::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   VisitCallExpr(E);
   E->setOperator((OverloadedOperatorKind)Record[Idx++]);
@@ -1018,6 +1089,35 @@
   E->Type =3D GetTypeSourceInfo(Record, Idx);
 }
=20
+void ASTStmtReader::VisitLambdaExpr(LambdaExpr *E) {
+  VisitExpr(E);
+  unsigned NumCaptures =3D Record[Idx++];
+  assert(NumCaptures =3D=3D E->NumCaptures);(void)NumCaptures;
+  unsigned NumArrayIndexVars =3D Record[Idx++];
+  E->IntroducerRange =3D ReadSourceRange(Record, Idx);
+  E->CaptureDefault =3D static_cast<LambdaCaptureDefault>(Record[Idx++]);
+  E->ExplicitParams =3D Record[Idx++];
+  E->ExplicitResultType =3D Record[Idx++];
+  E->ClosingBrace =3D ReadSourceLocation(Record, Idx);
+ =20
+  // Read capture initializers.
+  for (LambdaExpr::capture_init_iterator C =3D E->capture_init_begin(),
+                                      CEnd =3D E->capture_init_end();
+       C !=3D CEnd; ++C)
+    *C =3D Reader.ReadSubExpr();
+ =20
+  // Read array capture index variables.
+  if (NumArrayIndexVars > 0) {
+    unsigned *ArrayIndexStarts =3D E->getArrayIndexStarts();
+    for (unsigned I =3D 0; I !=3D NumCaptures + 1; ++I)
+      ArrayIndexStarts[I] =3D Record[Idx++];
+   =20
+    VarDecl **ArrayIndexVars =3D E->getArrayIndexVars();
+    for (unsigned I =3D 0; I !=3D NumArrayIndexVars; ++I)
+      ArrayIndexVars[I] =3D ReadDeclAs<VarDecl>(Record, Idx);
+  }
+}
+
 void ASTStmtReader::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
   VisitExplicitCastExpr(E);
   SourceRange R =3D ReadSourceRange(Record, Idx);
@@ -1047,6 +1147,11 @@
   E->setRParenLoc(ReadSourceLocation(Record, Idx));
 }
=20
+void ASTStmtReader::VisitUserDefinedLiteral(UserDefinedLiteral *E) {
+  VisitCallExpr(E);
+  E->UDSuffixLoc =3D ReadSourceLocation(Record, Idx);
+}
+
 void ASTStmtReader::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
   VisitExpr(E);
   E->setValue(Record[Idx++]);
@@ -1108,27 +1213,19 @@
 void ASTStmtReader::VisitCXXNewExpr(CXXNewExpr *E) {
   VisitExpr(E);
   E->GlobalNew =3D Record[Idx++];
-  E->Initializer =3D Record[Idx++];
+  bool isArray =3D Record[Idx++];
   E->UsualArrayDeleteWantsSize =3D Record[Idx++];
-  bool isArray =3D Record[Idx++];
-  E->setHadMultipleCandidates(Record[Idx++]);
   unsigned NumPlacementArgs =3D Record[Idx++];
-  unsigned NumCtorArgs =3D Record[Idx++];
+  E->StoredInitializationStyle =3D Record[Idx++];
   E->setOperatorNew(ReadDeclAs<FunctionDecl>(Record, Idx));
   E->setOperatorDelete(ReadDeclAs<FunctionDecl>(Record, Idx));
-  E->setConstructor(ReadDeclAs<CXXConstructorDecl>(Record, Idx));
   E->AllocatedTypeInfo =3D GetTypeSourceInfo(Record, Idx);
-  SourceRange TypeIdParens;
-  TypeIdParens.setBegin(ReadSourceLocation(Record, Idx));
-  TypeIdParens.setEnd(ReadSourceLocation(Record, Idx));
-  E->TypeIdParens =3D TypeIdParens;
+  E->TypeIdParens =3D ReadSourceRange(Record, Idx);
   E->StartLoc =3D ReadSourceLocation(Record, Idx);
-  E->EndLoc =3D ReadSourceLocation(Record, Idx);
-  E->ConstructorLParen =3D ReadSourceLocation(Record, Idx);
-  E->ConstructorRParen =3D ReadSourceLocation(Record, Idx);
+  E->DirectInitRange =3D ReadSourceRange(Record, Idx);
=20
   E->AllocateArgsArray(Reader.getContext(), isArray, NumPlacementArgs,
-                       NumCtorArgs);
+                       E->StoredInitializationStyle !=3D 0);
=20
   // Install all the subexpressions.
   for (CXXNewExpr::raw_arg_iterator I =3D E->raw_arg_begin(),e =3D E->raw_=
arg_end();
@@ -1167,22 +1264,22 @@
=20
 void ASTStmtReader::VisitExprWithCleanups(ExprWithCleanups *E) {
   VisitExpr(E);
-  unsigned NumTemps =3D Record[Idx++];
-  if (NumTemps) {
-    E->setNumTemporaries(Reader.getContext(), NumTemps);
-    for (unsigned i =3D 0; i !=3D NumTemps; ++i)
-      E->setTemporary(i, Reader.ReadCXXTemporary(F, Record, Idx));
-  }
-  E->setSubExpr(Reader.ReadSubExpr());
+
+  unsigned NumObjects =3D Record[Idx++];
+  assert(NumObjects =3D=3D E->getNumObjects());
+  for (unsigned i =3D 0; i !=3D NumObjects; ++i)
+    E->getObjectsBuffer()[i] =3D ReadDeclAs<BlockDecl>(Record, Idx);
+
+  E->SubExpr =3D Reader.ReadSubExpr();
 }
=20
 void
 ASTStmtReader::VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExp=
r *E){
   VisitExpr(E);
- =20
-  if (Record[Idx++])
-    ReadExplicitTemplateArgumentList(E->getExplicitTemplateArgs(),
-                                     Record[Idx++]);
+
+  if (Record[Idx++]) // HasTemplateKWAndArgsInfo
+    ReadTemplateKWAndArgsInfo(*E->getTemplateKWAndArgsInfo(),
+                              /*NumTemplateArgs=3D*/Record[Idx++]);
=20
   E->Base =3D Reader.ReadSubExpr();
   E->BaseType =3D Reader.readType(F, Record, Idx);
@@ -1196,10 +1293,10 @@
 void
 ASTStmtReader::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E=
) {
   VisitExpr(E);
- =20
-  if (Record[Idx++])
-    ReadExplicitTemplateArgumentList(E->getExplicitTemplateArgs(),=20
-                                     Record[Idx++]);
+
+  if (Record[Idx++]) // HasTemplateKWAndArgsInfo
+    ReadTemplateKWAndArgsInfo(*E->getTemplateKWAndArgsInfo(),
+                              /*NumTemplateArgs=3D*/Record[Idx++]);
=20
   E->QualifierLoc =3D Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
   ReadDeclarationNameInfo(E->NameInfo, Record, Idx);
@@ -1219,11 +1316,10 @@
=20
 void ASTStmtReader::VisitOverloadExpr(OverloadExpr *E) {
   VisitExpr(E);
- =20
-  // Read the explicit template argument list, if available.
-  if (Record[Idx++])
-    ReadExplicitTemplateArgumentList(E->getExplicitTemplateArgs(),
-                                     Record[Idx++]);
+
+  if (Record[Idx++]) // HasTemplateKWAndArgsInfo
+    ReadTemplateKWAndArgsInfo(*E->getTemplateKWAndArgsInfo(),
+                              /*NumTemplateArgs=3D*/Record[Idx++]);
=20
   unsigned NumDecls =3D Record[Idx++];
   UnresolvedSet<8> Decls;
@@ -1277,6 +1373,17 @@
   E->RhsType =3D GetTypeSourceInfo(Record, Idx);
 }
=20
+void ASTStmtReader::VisitTypeTraitExpr(TypeTraitExpr *E) {
+  VisitExpr(E);
+  E->TypeTraitExprBits.NumArgs =3D Record[Idx++];
+  E->TypeTraitExprBits.Kind =3D Record[Idx++];
+  E->TypeTraitExprBits.Value =3D Record[Idx++];
+ =20
+  TypeSourceInfo **Args =3D E->getTypeSourceInfos();
+  for (unsigned I =3D 0, N =3D E->getNumArgs(); I !=3D N; ++I)
+    Args[I] =3D GetTypeSourceInfo(Record, Idx);
+}
+
 void ASTStmtReader::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
   VisitExpr(E);
   E->ATT =3D (ArrayTypeTrait)Record[Idx++];
@@ -1348,7 +1455,7 @@
=20
 void ASTStmtReader::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
   VisitExpr(E);
-  Idx++; // skip ID
+  E->SourceExpr =3D Reader.ReadSubExpr();
   E->Loc =3D ReadSourceLocation(Record, Idx);
 }
=20
@@ -1412,7 +1519,7 @@
 // ASTReader Implementation
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-Stmt *ASTReader::ReadStmt(Module &F) {
+Stmt *ASTReader::ReadStmt(ModuleFile &F) {
   switch (ReadingKind) {
   case Read_Decl:
   case Read_Type:
@@ -1422,10 +1529,9 @@
   }
=20
   llvm_unreachable("ReadingKind not set ?");
-  return 0;
 }
=20
-Expr *ASTReader::ReadExpr(Module &F) {
+Expr *ASTReader::ReadExpr(ModuleFile &F) {
   return cast_or_null<Expr>(ReadStmt(F));
 }
=20
@@ -1440,10 +1546,14 @@
 // the stack, with expressions having operands removing those operands fro=
m the
 // stack. Evaluation terminates when we see a STMT_STOP record, and
 // the single remaining expression on the stack is our result.
-Stmt *ASTReader::ReadStmtFromStream(Module &F) {
+Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) {
=20
   ReadingKindTracker ReadingKind(Read_Stmt, *this);
   llvm::BitstreamCursor &Cursor =3D F.DeclsCursor;
+ =20
+  // Map of offset to previously deserialized stmt. The offset points
+  /// just after the stmt record.
+  llvm::DenseMap<uint64_t, Stmt *> StmtEntries;
=20
 #ifndef NDEBUG
   unsigned PrevNumStmts =3D StmtStack.size();
@@ -1483,11 +1593,19 @@
     Idx =3D 0;
     Record.clear();
     bool Finished =3D false;
+    bool IsStmtReference =3D false;
     switch ((StmtCode)Cursor.ReadRecord(Code, Record)) {
     case STMT_STOP:
       Finished =3D true;
       break;
=20
+    case STMT_REF_PTR:
+      IsStmtReference =3D true;
+      assert(StmtEntries.find(Record[0]) !=3D StmtEntries.end() &&
+             "No stmt was recorded for this offset reference!");
+      S =3D StmtEntries[Record[Idx++]];
+      break;
+
     case STMT_NULL_PTR:
       S =3D 0;
       break;
@@ -1569,9 +1687,9 @@
         Context,
         /*HasQualifier=3D*/Record[ASTStmtReader::NumExprFields],
         /*HasFoundDecl=3D*/Record[ASTStmtReader::NumExprFields + 1],
-        /*HasExplicitTemplateArgs=3D*/Record[ASTStmtReader::NumExprFields =
+ 2],
+        /*HasTemplateKWAndArgsInfo=3D*/Record[ASTStmtReader::NumExprFields=
 + 2],
         /*NumTemplateArgs=3D*/Record[ASTStmtReader::NumExprFields + 2] ?
-          Record[ASTStmtReader::NumExprFields + 4] : 0);
+          Record[ASTStmtReader::NumExprFields + 5] : 0);
       break;
=20
     case EXPR_INTEGER_LITERAL:
@@ -1636,9 +1754,11 @@
         QualifierLoc =3D ReadNestedNameSpecifierLoc(F, Record, Idx);
       }
=20
+      SourceLocation TemplateKWLoc;
       TemplateArgumentListInfo ArgInfo;
-      bool HasExplicitTemplateArgs =3D Record[Idx++];
-      if (HasExplicitTemplateArgs) {
+      bool HasTemplateKWAndArgsInfo =3D Record[Idx++];
+      if (HasTemplateKWAndArgsInfo) {
+        TemplateKWLoc =3D ReadSourceLocation(F, Record, Idx);
         unsigned NumTemplateArgs =3D Record[Idx++];
         ArgInfo.setLAngleLoc(ReadSourceLocation(F, Record, Idx));
         ArgInfo.setRAngleLoc(ReadSourceLocation(F, Record, Idx));
@@ -1662,8 +1782,9 @@
       bool IsArrow =3D Record[Idx++];
=20
       S =3D MemberExpr::Create(Context, Base, IsArrow, QualifierLoc,
-                             MemberD, FoundDecl, MemberNameInfo,
-                             HasExplicitTemplateArgs ? &ArgInfo : 0, T, VK=
, OK);
+                             TemplateKWLoc, MemberD, FoundDecl, MemberName=
Info,
+                             HasTemplateKWAndArgsInfo ? &ArgInfo : 0,
+                             T, VK, OK);
       ReadDeclarationNameLoc(F, cast<MemberExpr>(S)->MemberDNLoc,
                              MemberD->getDeclName(), Record, Idx);
       if (HadMultipleCandidates)
@@ -1747,10 +1868,6 @@
       S =3D new (Context) BlockExpr(Empty);
       break;
=20
-    case EXPR_BLOCK_DECL_REF:
-      S =3D new (Context) BlockDeclRefExpr(Empty);
-      break;
-
     case EXPR_GENERIC_SELECTION:
       S =3D new (Context) GenericSelectionExpr(Empty);
       break;
@@ -1758,6 +1875,18 @@
     case EXPR_OBJC_STRING_LITERAL:
       S =3D new (Context) ObjCStringLiteral(Empty);
       break;
+    case EXPR_OBJC_NUMERIC_LITERAL:
+      S =3D new (Context) ObjCNumericLiteral(Empty);
+      break;
+    case EXPR_OBJC_ARRAY_LITERAL:
+      S =3D ObjCArrayLiteral::CreateEmpty(Context,
+                                        Record[ASTStmtReader::NumExprField=
s]);
+      break;
+    case EXPR_OBJC_DICTIONARY_LITERAL:
+      S =3D ObjCDictionaryLiteral::CreateEmpty(Context,
+            Record[ASTStmtReader::NumExprFields],
+            Record[ASTStmtReader::NumExprFields + 1]);
+      break;
     case EXPR_OBJC_ENCODE:
       S =3D new (Context) ObjCEncodeExpr(Empty);
       break;
@@ -1773,9 +1902,11 @@
     case EXPR_OBJC_PROPERTY_REF_EXPR:
       S =3D new (Context) ObjCPropertyRefExpr(Empty);
       break;
+    case EXPR_OBJC_SUBSCRIPT_REF_EXPR:
+      S =3D new (Context) ObjCSubscriptRefExpr(Empty);
+      break;
     case EXPR_OBJC_KVC_REF_EXPR:
       llvm_unreachable("mismatching AST file");
-      break;
     case EXPR_OBJC_MESSAGE_EXPR:
       S =3D ObjCMessageExpr::CreateEmpty(Context,
                                      Record[ASTStmtReader::NumExprFields],
@@ -1813,6 +1944,9 @@
     case STMT_OBJC_AUTORELEASE_POOL:
       S =3D new (Context) ObjCAutoreleasePoolStmt(Empty);
       break;
+    case EXPR_OBJC_BOOL_LITERAL:
+      S =3D new (Context) ObjCBoolLiteralExpr(Empty);
+      break;
     case STMT_SEH_EXCEPT:
       S =3D new (Context) SEHExceptStmt(Empty);
       break;
@@ -1835,6 +1969,13 @@
       S =3D new (Context) CXXForRangeStmt(Empty);
       break;
=20
+    case STMT_MS_DEPENDENT_EXISTS:
+      S =3D new (Context) MSDependentExistsStmt(SourceLocation(), true,
+                                              NestedNameSpecifierLoc(),
+                                              DeclarationNameInfo(),
+                                              0);
+      break;
+       =20
     case EXPR_CXX_OPERATOR_CALL:
       S =3D new (Context) CXXOperatorCallExpr(Context, Empty);
       break;
@@ -1875,6 +2016,10 @@
                        /*PathSize*/ Record[ASTStmtReader::NumExprFields]);
       break;
=20
+    case EXPR_USER_DEFINED_LITERAL:
+      S =3D new (Context) UserDefinedLiteral(Context, Empty);
+      break;
+
     case EXPR_CXX_BOOL_LITERAL:
       S =3D new (Context) CXXBoolLiteralExpr(Empty);
       break;
@@ -1927,12 +2072,13 @@
       break;
        =20
     case EXPR_EXPR_WITH_CLEANUPS:
-      S =3D new (Context) ExprWithCleanups(Empty);
+      S =3D ExprWithCleanups::Create(Context, Empty,
+                                   Record[ASTStmtReader::NumExprFields]);
       break;
      =20
     case EXPR_CXX_DEPENDENT_SCOPE_MEMBER:
       S =3D CXXDependentScopeMemberExpr::CreateEmpty(Context,
-          /*HasExplicitTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s],
+         /*HasTemplateKWAndArgsInfo=3D*/Record[ASTStmtReader::NumExprField=
s],
                   /*NumTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s]
                                    ? Record[ASTStmtReader::NumExprFields +=
 1]=20
                                    : 0);
@@ -1940,7 +2086,7 @@
      =20
     case EXPR_CXX_DEPENDENT_SCOPE_DECL_REF:
       S =3D DependentScopeDeclRefExpr::CreateEmpty(Context,
-          /*HasExplicitTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s],
+         /*HasTemplateKWAndArgsInfo=3D*/Record[ASTStmtReader::NumExprField=
s],
                   /*NumTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s]
                                    ? Record[ASTStmtReader::NumExprFields +=
 1]=20
                                    : 0);
@@ -1953,7 +2099,7 @@
      =20
     case EXPR_CXX_UNRESOLVED_MEMBER:
       S =3D UnresolvedMemberExpr::CreateEmpty(Context,
-          /*HasExplicitTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s],
+         /*HasTemplateKWAndArgsInfo=3D*/Record[ASTStmtReader::NumExprField=
s],
                   /*NumTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s]
                                    ? Record[ASTStmtReader::NumExprFields +=
 1]=20
                                    : 0);
@@ -1961,7 +2107,7 @@
      =20
     case EXPR_CXX_UNRESOLVED_LOOKUP:
       S =3D UnresolvedLookupExpr::CreateEmpty(Context,
-          /*HasExplicitTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s],
+         /*HasTemplateKWAndArgsInfo=3D*/Record[ASTStmtReader::NumExprField=
s],
                   /*NumTemplateArgs=3D*/Record[ASTStmtReader::NumExprField=
s]
                                    ? Record[ASTStmtReader::NumExprFields +=
 1]=20
                                    : 0);
@@ -1975,6 +2121,11 @@
       S =3D new (Context) BinaryTypeTraitExpr(Empty);
       break;
=20
+    case EXPR_TYPE_TRAIT:
+      S =3D TypeTraitExpr::CreateDeserialized(Context,=20
+            Record[ASTStmtReader::NumExprFields]);
+      break;
+       =20
     case EXPR_ARRAY_TYPE_TRAIT:
       S =3D new (Context) ArrayTypeTraitExpr(Empty);
       break;
@@ -2007,20 +2158,9 @@
       S =3D new (Context) MaterializeTemporaryExpr(Empty);
       break;
        =20
-    case EXPR_OPAQUE_VALUE: {
-      unsigned key =3D Record[ASTStmtReader::NumExprFields];
-      OpaqueValueExpr *&expr =3D OpaqueValueExprs[key];
-
-      // If we already have an entry for this opaque value expression,
-      // don't bother reading it again.
-      if (expr) {
-        StmtStack.push_back(expr);
-        continue;
-      }
-
-      S =3D expr =3D new (Context) OpaqueValueExpr(Empty);
+    case EXPR_OPAQUE_VALUE:
+      S =3D new (Context) OpaqueValueExpr(Empty);
       break;
-    }
=20
     case EXPR_CUDA_KERNEL_CALL:
       S =3D new (Context) CUDAKernelCallExpr(Context, Empty);
@@ -2030,9 +2170,23 @@
       S =3D new (Context) AsTypeExpr(Empty);
       break;
=20
+    case EXPR_PSEUDO_OBJECT: {
+      unsigned numSemanticExprs =3D Record[ASTStmtReader::NumExprFields];
+      S =3D PseudoObjectExpr::Create(Context, Empty, numSemanticExprs);
+      break;
+    }
+
     case EXPR_ATOMIC:
       S =3D new (Context) AtomicExpr(Empty);
       break;
+       =20
+    case EXPR_LAMBDA: {
+      unsigned NumCaptures =3D Record[ASTStmtReader::NumExprFields];
+      unsigned NumArrayIndexVars =3D Record[ASTStmtReader::NumExprFields +=
 1];
+      S =3D LambdaExpr::CreateDeserialized(Context, NumCaptures,=20
+                                         NumArrayIndexVars);
+      break;
+    }
     }
    =20
     // We hit a STMT_STOP, so we're done with this expression.
@@ -2041,8 +2195,11 @@
=20
     ++NumStatementsRead;
=20
-    if (S)
+    if (S && !IsStmtReference) {
       Reader.Visit(S);
+      StmtEntries[Cursor.GetCurrentBitNo()] =3D S;
+    }
+
=20
     assert(Idx =3D=3D Record.size() && "Invalid deserialization of stateme=
nt");
     StmtStack.push_back(S);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTWriter.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp	Tue Apr=
 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTWriter.cpp	Tue Apr=
 17 11:51:51 2012 +0300
@@ -185,6 +185,7 @@
   for (unsigned I =3D 0, N =3D T->getNumArgs(); I !=3D N; ++I)
     Writer.AddTypeRef(T->getArgType(I), Record);
   Record.push_back(T->isVariadic());
+  Record.push_back(T->hasTrailingReturn());
   Record.push_back(T->getTypeQuals());
   Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
   Record.push_back(T->getExceptionSpecType());
@@ -221,6 +222,7 @@
 }
=20
 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
+  Writer.AddTypeRef(T->getUnderlyingType(), Record);
   Writer.AddStmt(T->getUnderlyingExpr());
   Code =3D TYPE_DECLTYPE;
 }
@@ -239,7 +241,7 @@
=20
 void ASTTypeWriter::VisitTagType(const TagType *T) {
   Record.push_back(T->isDependentType());
-  Writer.AddDeclRef(T->getDecl(), Record);
+  Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
   assert(!T->isBeingDefined() &&
          "Cannot serialize in the middle of a type definition");
 }
@@ -363,13 +365,13 @@
 }
=20
 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType=
 *T) {
-  Writer.AddDeclRef(T->getDecl(), Record);
+  Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
   Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
   Code =3D TYPE_INJECTED_CLASS_NAME;
 }
=20
 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
-  Writer.AddDeclRef(T->getDecl(), Record);
+  Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
   Code =3D TYPE_OBJC_INTERFACE;
 }
=20
@@ -552,6 +554,7 @@
 }
 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
                                            TemplateSpecializationTypeLoc T=
L) {
+  Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
@@ -564,22 +567,23 @@
   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
 }
 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
-  Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
+  Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
 }
 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc=
 TL) {
   Writer.AddSourceLocation(TL.getNameLoc(), Record);
 }
 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
-  Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
+  Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
   Writer.AddSourceLocation(TL.getNameLoc(), Record);
 }
 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
        DependentTemplateSpecializationTypeLoc TL) {
-  Writer.AddSourceLocation(TL.getKeywordLoc(), Record);
+  Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
-  Writer.AddSourceLocation(TL.getNameLoc(), Record);
+  Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
+  Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
   for (unsigned I =3D 0, E =3D TL.getNumArgs(); I !=3D E; ++I)
@@ -689,9 +693,11 @@
   RECORD(EXPR_GNU_NULL);
   RECORD(EXPR_SHUFFLE_VECTOR);
   RECORD(EXPR_BLOCK);
-  RECORD(EXPR_BLOCK_DECL_REF);
   RECORD(EXPR_GENERIC_SELECTION);
   RECORD(EXPR_OBJC_STRING_LITERAL);
+  RECORD(EXPR_OBJC_NUMERIC_LITERAL);
+  RECORD(EXPR_OBJC_ARRAY_LITERAL);
+  RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
   RECORD(EXPR_OBJC_ENCODE);
   RECORD(EXPR_OBJC_SELECTOR_EXPR);
   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
@@ -705,6 +711,7 @@
   RECORD(STMT_OBJC_AT_TRY);
   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
   RECORD(STMT_OBJC_AT_THROW);
+  RECORD(EXPR_OBJC_BOOL_LITERAL);
   RECORD(EXPR_CXX_OPERATOR_CALL);
   RECORD(EXPR_CXX_CONSTRUCT);
   RECORD(EXPR_CXX_STATIC_CAST);
@@ -712,6 +719,7 @@
   RECORD(EXPR_CXX_REINTERPRET_CAST);
   RECORD(EXPR_CXX_CONST_CAST);
   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
+  RECORD(EXPR_USER_DEFINED_LITERAL);
   RECORD(EXPR_CXX_BOOL_LITERAL);
   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
   RECORD(EXPR_CXX_TYPEID_EXPR);
@@ -778,7 +786,7 @@
   RECORD(IMPORTS);
   RECORD(REFERENCED_SELECTOR_POOL);
   RECORD(TU_UPDATE_LEXICAL);
-  RECORD(REDECLS_UPDATE_LATEST);
+  RECORD(LOCAL_REDECLARATIONS_MAP);
   RECORD(SEMA_DECL_REFS);
   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
@@ -798,7 +806,13 @@
   RECORD(KNOWN_NAMESPACES);
   RECORD(MODULE_OFFSET_MAP);
   RECORD(SOURCE_MANAGER_LINE_TABLE);
- =20
+  RECORD(OBJC_CATEGORIES_MAP);
+  RECORD(FILE_SORTED_DECLS);
+  RECORD(IMPORTED_MODULES);
+  RECORD(MERGED_DECLARATIONS);
+  RECORD(LOCAL_REDECLARATIONS);
+  RECORD(OBJC_CATEGORIES);
+
   // SourceManager Block.
   BLOCK(SOURCE_MANAGER_BLOCK);
   RECORD(SM_SLOC_FILE_ENTRY);
@@ -862,8 +876,6 @@
   RECORD(DECL_OBJC_PROTOCOL);
   RECORD(DECL_OBJC_IVAR);
   RECORD(DECL_OBJC_AT_DEFS_FIELD);
-  RECORD(DECL_OBJC_CLASS);
-  RECORD(DECL_OBJC_FORWARD_PROTOCOL);
   RECORD(DECL_OBJC_CATEGORY);
   RECORD(DECL_OBJC_CATEGORY_IMPL);
   RECORD(DECL_OBJC_IMPLEMENTATION);
@@ -969,6 +981,7 @@
   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang m=
ajor
   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang m=
inor
   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocata=
ble
+  MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Has erro=
rs
   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
   unsigned MetaAbbrevCode =3D Stream.EmitAbbrev(MetaAbbrev);
=20
@@ -979,6 +992,7 @@
   Record.push_back(CLANG_VERSION_MAJOR);
   Record.push_back(CLANG_VERSION_MINOR);
   Record.push_back(!isysroot.empty());
+  Record.push_back(ASTHasCompilerErrors);
   const std::string &Triple =3D Target.getTriple().getTriple();
   Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple);
=20
@@ -1011,7 +1025,7 @@
     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
     unsigned FileAbbrevCode =3D Stream.EmitAbbrev(FileAbbrev);
=20
-    llvm::SmallString<128> MainFilePath(MainFile->getName());
+    SmallString<128> MainFilePath(MainFile->getName());
=20
     llvm::sys::fs::make_absolute(MainFilePath);
=20
@@ -1034,7 +1048,7 @@
     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
     unsigned AbbrevCode =3D Stream.EmitAbbrev(Abbrev);
=20
-    llvm::SmallString<128> OutputPath(OutputFile);
+    SmallString<128> OutputPath(OutputFile);
=20
     llvm::sys::fs::make_absolute(OutputPath);
     StringRef origDir =3D llvm::sys::path::parent_path(OutputPath);
@@ -1063,6 +1077,9 @@
 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
 #include "clang/Basic/LangOptions.def" =20
+ =20
+  Record.push_back(LangOpts.CurrentModule.size());
+  Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end=
());
   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
 }
=20
@@ -1128,7 +1145,7 @@
   }
=20
   // Create the on-disk hash table in a buffer.
-  llvm::SmallString<4096> StatCacheData;
+  SmallString<4096> StatCacheData;
   uint32_t BucketOffset;
   {
     llvm::raw_svector_ostream Out(StatCacheData);
@@ -1171,7 +1188,10 @@
   // FileEntry fields.
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification =
time
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverri=
dden
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
   return Stream.EmitAbbrev(Abbrev);
 }
@@ -1218,14 +1238,14 @@
   // Trait used for the on-disk hash table of header search information.
   class HeaderFileInfoTrait {
     ASTWriter &Writer;
-    HeaderSearch &HS;
+    const HeaderSearch &HS;
    =20
     // Keep track of the framework names we've used during serialization.
     SmallVector<char, 128> FrameworkStringData;
     llvm::StringMap<unsigned> FrameworkNameOffset;
    =20
   public:
-    HeaderFileInfoTrait(ASTWriter &Writer, HeaderSearch &HS)=20
+    HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)=20
       : Writer(Writer), HS(HS) { }
    =20
     typedef const char *key_type;
@@ -1304,7 +1324,7 @@
 /// \param HS The header search structure to save.
 ///
 /// \param Chain Whether we're creating a chained AST file.
-void ASTWriter::WriteHeaderSearch(HeaderSearch &HS, StringRef isysroot) {
+void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysro=
ot) {
   SmallVector<const FileEntry *, 16> FilesByUID;
   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
  =20
@@ -1320,7 +1340,9 @@
     if (!File)
       continue;
=20
-    const HeaderFileInfo &HFI =3D HS.header_file_begin()[UID];
+    // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileIn=
fo
+    // from the external source if it was not provided already.
+    const HeaderFileInfo &HFI =3D HS.getFileInfo(File);
     if (HFI.External && Chain)
       continue;
=20
@@ -1340,7 +1362,7 @@
   }
  =20
   // Create the on-disk hash table in a buffer.
-  llvm::SmallString<4096> TableData;
+  SmallString<4096> TableData;
   uint32_t BucketOffset;
   {
     llvm::raw_svector_ostream Out(TableData);
@@ -1414,7 +1436,8 @@
     // Figure out which record code to use.
     unsigned Code;
     if (SLoc->isFile()) {
-      if (SLoc->getFile().getContentCache()->OrigEntry) {
+      const SrcMgr::ContentCache *Cache =3D SLoc->getFile().getContentCach=
e();
+      if (Cache->OrigEntry) {
         Code =3D SM_SLOC_FILE_ENTRY;
         SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
       } else
@@ -1435,7 +1458,7 @@
       const SrcMgr::ContentCache *Content =3D File.getContentCache();
       if (Content->OrigEntry) {
         assert(Content->OrigEntry =3D=3D Content->ContentsEntry &&
-               "Writing to AST an overriden file is not supported");
+               "Writing to AST an overridden file is not supported");
=20
         // The source location entry is a file. The blob associated
         // with this entry is the file name.
@@ -1443,12 +1466,21 @@
         // Emit size/modification time for this file.
         Record.push_back(Content->OrigEntry->getSize());
         Record.push_back(Content->OrigEntry->getModificationTime());
-
+        Record.push_back(Content->BufferOverridden);
         Record.push_back(File.NumCreatedFIDs);
-
+       =20
+        FileDeclIDsTy::iterator FDI =3D FileDeclIDs.find(SLoc);
+        if (FDI !=3D FileDeclIDs.end()) {
+          Record.push_back(FDI->second->FirstDeclIndex);
+          Record.push_back(FDI->second->DeclIDs.size());
+        } else {
+          Record.push_back(0);
+          Record.push_back(0);
+        }
+       =20
         // Turn the file name into an absolute path, if it isn't already.
         const char *Filename =3D Content->OrigEntry->getName();
-        llvm::SmallString<128> FilePath(Filename);
+        SmallString<128> FilePath(Filename);
=20
         // Ask the file manager to fixup the relative path for us. This wi=
ll=20
         // honor the working directory.
@@ -1461,6 +1493,16 @@
=20
         Filename =3D adjustFilenameForRelocatablePCH(Filename, isysroot);
         Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
+       =20
+        if (Content->BufferOverridden) {
+          Record.clear();
+          Record.push_back(SM_SLOC_BUFFER_BLOB);
+          const llvm::MemoryBuffer *Buffer
+            =3D Content->getBuffer(PP.getDiagnostics(), PP.getSourceManage=
r());
+          Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
+                                    StringRef(Buffer->getBufferStart(),
+                                              Buffer->getBufferSize() + 1)=
);         =20
+        }
       } else {
         // The source location entry is a buffer. The blob associated
         // with this entry contains the contents of the buffer.
@@ -1629,8 +1671,9 @@
   for (Preprocessor::macro_iterator I =3D PP.macro_begin(Chain =3D=3D 0),=20
                                     E =3D PP.macro_end(Chain =3D=3D 0);
        I !=3D E; ++I) {
-    if (!IsModule || I->second->isExported()) {
-      MacroDefinitionsSeen.insert(I->first);
+    const IdentifierInfo *Name =3D I->first;
+    if (!IsModule || I->second->isPublic()) {
+      MacroDefinitionsSeen.insert(Name);
       MacrosToEmit.push_back(std::make_pair(I->first, I->second));
     }
   }
@@ -1664,15 +1707,17 @@
     // chained PCH, by storing the offset into the original PCH rather than
     // writing the macro definition a second time.
     if (MI->isBuiltinMacro() ||
-        (Chain && Name->isFromAST() && MI->isFromAST() &&
-        !MI->hasChangedAfterLoad()))
+        (Chain &&=20
+         Name->isFromAST() && !Name->hasChangedSinceDeserialization() &&=20
+         MI->isFromAST() && !MI->hasChangedAfterLoad()))
       continue;
=20
     AddIdentifierRef(Name, Record);
     MacroOffsets[Name] =3D Stream.GetCurrentBitNo();
     Record.push_back(MI->getDefinitionLoc().getRawEncoding());
     Record.push_back(MI->isUsed());
-    AddSourceLocation(MI->getExportLocation(), Record);
+    Record.push_back(MI->isPublic());
+    AddSourceLocation(MI->getVisibilityLocation(), Record);
     unsigned Code;
     if (MI->isObjectLike()) {
       Code =3D PP_MACRO_OBJECT_LIKE;
@@ -1784,9 +1829,12 @@
       Record.push_back(ID->getFileName().size());
       Record.push_back(ID->wasInQuotes());
       Record.push_back(static_cast<unsigned>(ID->getKind()));
-      llvm::SmallString<64> Buffer;
+      SmallString<64> Buffer;
       Buffer +=3D ID->getFileName();
-      Buffer +=3D ID->getFile()->getName();
+      // Check that the FileEntry is not null because it was not resolved =
and
+      // we create a PCH even with compiler errors.
+      if (ID->getFile())
+        Buffer +=3D ID->getFile()->getName();
       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
       continue;
     }
@@ -1815,6 +1863,202 @@
   }
 }
=20
+unsigned ASTWriter::getSubmoduleID(Module *Mod) {
+  llvm::DenseMap<Module *, unsigned>::iterator Known =3D SubmoduleIDs.find=
(Mod);
+  if (Known !=3D SubmoduleIDs.end())
+    return Known->second;
+ =20
+  return SubmoduleIDs[Mod] =3D NextSubmoduleID++;
+}
+
+/// \brief Compute the number of modules within the given tree (including =
the
+/// given module).
+static unsigned getNumberOfModules(Module *Mod) {
+  unsigned ChildModules =3D 0;
+  for (Module::submodule_iterator Sub =3D Mod->submodule_begin(),
+                               SubEnd =3D Mod->submodule_end();
+       Sub !=3D SubEnd; ++Sub)
+    ChildModules +=3D getNumberOfModules(*Sub);
+ =20
+  return ChildModules + 1;
+}
+
+void ASTWriter::WriteSubmodules(Module *WritingModule) {
+  // Determine the dependencies of our module and each of it's submodules.
+  // FIXME: This feels like it belongs somewhere else, but there are no
+  // other consumers of this information.
+  SourceManager &SrcMgr =3D PP->getSourceManager();
+  ModuleMap &ModMap =3D PP->getHeaderSearchInfo().getModuleMap();
+  for (ASTContext::import_iterator I =3D Context->local_import_begin(),
+                                IEnd =3D Context->local_import_end();
+       I !=3D IEnd; ++I) {
+    if (Module *ImportedFrom
+          =3D ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(=
),=20
+                                                         SrcMgr))) {
+      ImportedFrom->Imports.push_back(I->getImportedModule());
+    }
+  }
+ =20
+  // Enter the submodule description block.
+  Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
+ =20
+  // Write the abbreviations needed for the submodules block.
+  using namespace llvm;
+  BitCodeAbbrev *Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem =20
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodu=
les...
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplici=
t...
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportW=
ild...
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
+  unsigned DefinitionAbbrev =3D Stream.EmitAbbrev(Abbrev);
+
+  Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
+  unsigned UmbrellaAbbrev =3D Stream.EmitAbbrev(Abbrev);
+
+  Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
+  unsigned HeaderAbbrev =3D Stream.EmitAbbrev(Abbrev);
+
+  Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
+  unsigned UmbrellaDirAbbrev =3D Stream.EmitAbbrev(Abbrev);
+
+  Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
+  unsigned RequiresAbbrev =3D Stream.EmitAbbrev(Abbrev);
+
+  // Write the submodule metadata block.
+  RecordData Record;
+  Record.push_back(getNumberOfModules(WritingModule));
+  Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
+  Stream.EmitRecord(SUBMODULE_METADATA, Record);
+ =20
+  // Write all of the submodules.
+  std::queue<Module *> Q;
+  Q.push(WritingModule);
+  while (!Q.empty()) {
+    Module *Mod =3D Q.front();
+    Q.pop();
+    unsigned ID =3D getSubmoduleID(Mod);
+   =20
+    // Emit the definition of the block.
+    Record.clear();
+    Record.push_back(SUBMODULE_DEFINITION);
+    Record.push_back(ID);
+    if (Mod->Parent) {
+      assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
+      Record.push_back(SubmoduleIDs[Mod->Parent]);
+    } else {
+      Record.push_back(0);
+    }
+    Record.push_back(Mod->IsFramework);
+    Record.push_back(Mod->IsExplicit);
+    Record.push_back(Mod->IsSystem);
+    Record.push_back(Mod->InferSubmodules);
+    Record.push_back(Mod->InferExplicitSubmodules);
+    Record.push_back(Mod->InferExportWildcard);
+    Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
+   =20
+    // Emit the requirements.
+    for (unsigned I =3D 0, N =3D Mod->Requires.size(); I !=3D N; ++I) {
+      Record.clear();
+      Record.push_back(SUBMODULE_REQUIRES);
+      Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
+                                Mod->Requires[I].data(),
+                                Mod->Requires[I].size());
+    }
+
+    // Emit the umbrella header, if there is one.
+    if (const FileEntry *UmbrellaHeader =3D Mod->getUmbrellaHeader()) {
+      Record.clear();
+      Record.push_back(SUBMODULE_UMBRELLA_HEADER);
+      Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,=20
+                                UmbrellaHeader->getName());
+    } else if (const DirectoryEntry *UmbrellaDir =3D Mod->getUmbrellaDir()=
) {
+      Record.clear();
+      Record.push_back(SUBMODULE_UMBRELLA_DIR);
+      Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,=20
+                                UmbrellaDir->getName());     =20
+    }
+   =20
+    // Emit the headers.
+    for (unsigned I =3D 0, N =3D Mod->Headers.size(); I !=3D N; ++I) {
+      Record.clear();
+      Record.push_back(SUBMODULE_HEADER);
+      Stream.EmitRecordWithBlob(HeaderAbbrev, Record,=20
+                                Mod->Headers[I]->getName());
+    }
+
+    // Emit the imports.=20
+    if (!Mod->Imports.empty()) {
+      Record.clear();
+      for (unsigned I =3D 0, N =3D Mod->Imports.size(); I !=3D N; ++I) {
+        unsigned ImportedID =3D getSubmoduleID(Mod->Imports[I]);
+        assert(ImportedID && "Unknown submodule!");                       =
                   =20
+        Record.push_back(ImportedID);
+      }
+      Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
+    }
+
+    // Emit the exports.=20
+    if (!Mod->Exports.empty()) {
+      Record.clear();
+      for (unsigned I =3D 0, N =3D Mod->Exports.size(); I !=3D N; ++I) {
+        if (Module *Exported =3D Mod->Exports[I].getPointer()) {
+          unsigned ExportedID =3D SubmoduleIDs[Exported];
+          assert(ExportedID > 0 && "Unknown submodule ID?");
+          Record.push_back(ExportedID);
+        } else {
+          Record.push_back(0);
+        }
+       =20
+        Record.push_back(Mod->Exports[I].getInt());
+      }
+      Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
+    }
+   =20
+    // Queue up the submodules of this module.
+    for (Module::submodule_iterator Sub =3D Mod->submodule_begin(),
+                                 SubEnd =3D Mod->submodule_end();
+         Sub !=3D SubEnd; ++Sub)
+      Q.push(*Sub);
+  }
+ =20
+  Stream.ExitBlock();
+ =20
+  assert((NextSubmoduleID - FirstSubmoduleID
+            =3D=3D getNumberOfModules(WritingModule)) && "Wrong # of submo=
dules");
+}
+
+serialization::SubmoduleID=20
+ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
+  if (Loc.isInvalid() || !WritingModule)
+    return 0; // No submodule
+   =20
+  // Find the module that owns this location.
+  ModuleMap &ModMap =3D PP->getHeaderSearchInfo().getModuleMap();
+  Module *OwningMod=20
+    =3D ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceMana=
ger()));
+  if (!OwningMod)
+    return 0;
+ =20
+  // Check whether this submodule is part of our own module.
+  if (WritingModule !=3D OwningMod && !OwningMod->isSubModuleOf(WritingMod=
ule))
+    return 0;
+ =20
+  return getSubmoduleID(OwningMod);
+}
+
 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Dia=
g) {
   RecordData Record;
   for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
@@ -1970,6 +2214,29 @@
   Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
 }
=20
+void ASTWriter::WriteFileDeclIDsMap() {
+  using namespace llvm;
+  RecordData Record;
+
+  // Join the vectors of DeclIDs from all files.
+  SmallVector<DeclID, 256> FileSortedIDs;
+  for (FileDeclIDsTy::iterator
+         FI =3D FileDeclIDs.begin(), FE =3D FileDeclIDs.end(); FI !=3D FE;=
 ++FI) {
+    DeclIDInFileInfo &Info =3D *FI->second;
+    Info.FirstDeclIndex =3D FileSortedIDs.size();
+    for (LocDeclIDsTy::iterator
+           DI =3D Info.DeclIDs.begin(), DE =3D Info.DeclIDs.end(); DI !=3D=
 DE; ++DI)
+      FileSortedIDs.push_back(DI->second);
+  }
+
+  BitCodeAbbrev *Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
+  unsigned AbbrevCode =3D Stream.EmitAbbrev(Abbrev);
+  Record.push_back(FILE_SORTED_DECLS);
+  Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Global Method Pool and Selector Serialization
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2117,7 +2384,7 @@
     }
=20
     // Create the on-disk hash table in a buffer.
-    llvm::SmallString<4096> MethodPool;
+    SmallString<4096> MethodPool;
     uint32_t BucketOffset;
     {
       ASTMethodPoolTrait Trait(*this);
@@ -2190,6 +2457,7 @@
 class ASTIdentifierTableTrait {
   ASTWriter &Writer;
   Preprocessor &PP;
+  IdentifierResolver &IdResolver;
   bool IsModule;
  =20
   /// \brief Determines whether this is an "interesting" identifier
@@ -2199,6 +2467,7 @@
     if (II->isPoisoned() ||
         II->isExtensionToken() ||
         II->getObjCOrBuiltinID() ||
+        II->hasRevertedTokenIDToIdentifier() ||
         II->getFETokenInfo<void>())
       return true;
=20
@@ -2210,7 +2479,7 @@
       return false;
    =20
     if (Macro || (Macro =3D PP.getMacroInfo(II)))
-      return !Macro->isBuiltinMacro() && (!IsModule || Macro->isExported()=
);
+      return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic());
    =20
     return false;   =20
   }
@@ -2222,24 +2491,26 @@
   typedef IdentID data_type;
   typedef data_type data_type_ref;
=20
-  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, bool IsModu=
le)
-    : Writer(Writer), PP(PP), IsModule(IsModule) { }
+  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,=20
+                          IdentifierResolver &IdResolver, bool IsModule)
+    : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) {=
 }
=20
   static unsigned ComputeHash(const IdentifierInfo* II) {
     return llvm::HashString(II->getName());
   }
=20
   std::pair<unsigned,unsigned>
-    EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
+  EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
     unsigned KeyLen =3D II->getLength() + 1;
     unsigned DataLen =3D 4; // 4 bytes for the persistent ID << 1
     MacroInfo *Macro =3D 0;
     if (isInterestingIdentifier(II, Macro)) {
       DataLen +=3D 2; // 2 bytes for builtin ID, flags
       if (hasMacroDefinition(II, Macro))
-        DataLen +=3D 4;
-      for (IdentifierResolver::iterator D =3D IdentifierResolver::begin(II=
),
-                                     DEnd =3D IdentifierResolver::end();
+        DataLen +=3D 8;
+     =20
+      for (IdentifierResolver::iterator D =3D IdResolver.begin(II),
+                                     DEnd =3D IdResolver.end();
            D !=3D DEnd; ++D)
         DataLen +=3D sizeof(DeclID);
     }
@@ -2271,6 +2542,7 @@
     uint32_t Bits =3D 0;
     bool HasMacroDefinition =3D hasMacroDefinition(II, Macro);
     Bits =3D (uint32_t)II->getObjCOrBuiltinID();
+    assert((Bits & 0x7ff) =3D=3D Bits && "ObjCOrBuiltinID too big for ASTR=
eader.");
     Bits =3D (Bits << 1) | unsigned(HasMacroDefinition);
     Bits =3D (Bits << 1) | unsigned(II->isExtensionToken());
     Bits =3D (Bits << 1) | unsigned(II->isPoisoned());
@@ -2278,20 +2550,22 @@
     Bits =3D (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
     clang::io::Emit16(Out, Bits);
=20
-    if (HasMacroDefinition)
+    if (HasMacroDefinition) {
       clang::io::Emit32(Out, Writer.getMacroOffset(II));
-
+      clang::io::Emit32(Out,=20
+        Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc()));
+    }
+   =20
     // Emit the declaration IDs in reverse order, because the
     // IdentifierResolver provides the declarations as they would be
     // visible (e.g., the function "stat" would come before the struct
-    // "stat"), but IdentifierResolver::AddDeclToIdentifierChain()
-    // adds declarations to the end of the list (so we need to see the
-    // struct "status" before the function "status").
+    // "stat"), but the ASTReader adds declarations to the end of the list=20
+    // (so we need to see the struct "status" before the function "status"=
).
     // Only emit declarations that aren't from a chained PCH, though.
-    SmallVector<Decl *, 16> Decls(IdentifierResolver::begin(II),
-                                        IdentifierResolver::end());
+    SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
+                                  IdResolver.end());
     for (SmallVector<Decl *, 16>::reverse_iterator D =3D Decls.rbegin(),
-                                                      DEnd =3D Decls.rend(=
);
+                                                DEnd =3D Decls.rend();
          D !=3D DEnd; ++D)
       clang::io::Emit32(Out, Writer.getDeclID(*D));
   }
@@ -2303,14 +2577,16 @@
 /// The identifier table consists of a blob containing string data
 /// (the actual identifiers themselves) and a separate "offsets" index
 /// that maps identifier IDs to locations within the blob.
-void ASTWriter::WriteIdentifierTable(Preprocessor &PP, bool IsModule) {
+void ASTWriter::WriteIdentifierTable(Preprocessor &PP,=20
+                                     IdentifierResolver &IdResolver,
+                                     bool IsModule) {
   using namespace llvm;
=20
   // Create and write out the blob that contains the identifier
   // strings.
   {
     OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
-    ASTIdentifierTableTrait Trait(*this, PP, IsModule);
+    ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
=20
     // Look for any identifiers that were named while processing the
     // headers, but are otherwise not needed. We add these to the hash
@@ -2329,16 +2605,17 @@
            ID =3D IdentifierIDs.begin(), IDEnd =3D IdentifierIDs.end();
          ID !=3D IDEnd; ++ID) {
       assert(ID->first && "NULL identifier in identifier table");
-      if (!Chain || !ID->first->isFromAST())
+      if (!Chain || !ID->first->isFromAST() ||=20
+          ID->first->hasChangedSinceDeserialization())
         Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->seco=
nd,=20
                          Trait);
     }
=20
     // Create the on-disk hash table in a buffer.
-    llvm::SmallString<4096> IdentifierTable;
+    SmallString<4096> IdentifierTable;
     uint32_t BucketOffset;
     {
-      ASTIdentifierTableTrait Trait(*this, PP, IsModule);
+      ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
       llvm::raw_svector_ostream Out(IdentifierTable);
       // Make sure that no bucket is at offset 0
       clang::io::Emit32(Out, 0);
@@ -2512,20 +2789,16 @@
   // IdentifierInfo chains, don't bother to build a visible-declarations t=
able.
   // FIXME: In C++ we need the visible declarations in order to "see" the
   // friend declarations, is there a way to do this without writing the ta=
ble ?
-  if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus)
+  if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
     return 0;
=20
-  // Force the DeclContext to build a its name-lookup table.
-  if (!DC->hasExternalVisibleStorage())
-    DC->lookup(DeclarationName());
-
   // Serialize the contents of the mapping used for lookup. Note that,
   // although we have two very different code paths, the serialized
   // representation is the same for both cases: a declaration name,
   // followed by a size, followed by references to the visible
   // declarations that have that name.
   uint64_t Offset =3D Stream.GetCurrentBitNo();
-  StoredDeclsMap *Map =3D static_cast<StoredDeclsMap*>(DC->getLookupPtr());
+  StoredDeclsMap *Map =3D DC->buildLookup();
   if (!Map || Map->empty())
     return 0;
=20
@@ -2565,7 +2838,7 @@
   }
  =20
   // Create the on-disk hash table in a buffer.
-  llvm::SmallString<4096> LookupTable;
+  SmallString<4096> LookupTable;
   uint32_t BucketOffset;
   {
     llvm::raw_svector_ostream Out(LookupTable);
@@ -2590,7 +2863,8 @@
 ///
 /// UPDATE_VISIBLE blocks contain the declarations that are added to an ex=
isting
 /// DeclContext in a dependent AST file. As such, they only exist for the =
TU
-/// (in C++) and for namespaces.
+/// (in C++), for namespaces, and for classes with forward-declared unscop=
ed
+/// enumeration members (in C++11).
 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
   StoredDeclsMap *Map =3D static_cast<StoredDeclsMap*>(DC->getLookupPtr());
   if (!Map || Map->empty())
@@ -2611,7 +2885,7 @@
   }
=20
   // Create the on-disk hash table in a buffer.
-  llvm::SmallString<4096> LookupTable;
+  SmallString<4096> LookupTable;
   uint32_t BucketOffset;
   {
     llvm::raw_svector_ostream Out(LookupTable);
@@ -2637,7 +2911,7 @@
=20
 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
-  if (!SemaRef.Context.getLangOptions().OpenCL)
+  if (!SemaRef.Context.getLangOpts().OpenCL)
     return;
=20
   const OpenCLOptions &Opts =3D SemaRef.getOpenCLOptions();
@@ -2647,6 +2921,143 @@
   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
 }
=20
+void ASTWriter::WriteRedeclarations() {
+  RecordData LocalRedeclChains;
+  SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
+
+  for (unsigned I =3D 0, N =3D Redeclarations.size(); I !=3D N; ++I) {
+    Decl *First =3D Redeclarations[I];
+    assert(First->getPreviousDecl() =3D=3D 0 && "Not the first declaration=
?");
+   =20
+    Decl *MostRecent =3D First->getMostRecentDecl();
+   =20
+    // If we only have a single declaration, there is no point in storing
+    // a redeclaration chain.
+    if (First =3D=3D MostRecent)
+      continue;
+   =20
+    unsigned Offset =3D LocalRedeclChains.size();
+    unsigned Size =3D 0;
+    LocalRedeclChains.push_back(0); // Placeholder for the size.
+   =20
+    // Collect the set of local redeclarations of this declaration.
+    for (Decl *Prev =3D MostRecent; Prev !=3D First;=20
+         Prev =3D Prev->getPreviousDecl()) {=20
+      if (!Prev->isFromASTFile()) {
+        AddDeclRef(Prev, LocalRedeclChains);
+        ++Size;
+      }
+    }
+    LocalRedeclChains[Offset] =3D Size;
+   =20
+    // Reverse the set of local redeclarations, so that we store them in
+    // order (since we found them in reverse order).
+    std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
+   =20
+    // Add the mapping from the first ID to the set of local declarations.
+    LocalRedeclarationsInfo Info =3D { getDeclID(First), Offset };
+    LocalRedeclsMap.push_back(Info);
+   =20
+    assert(N =3D=3D Redeclarations.size() &&=20
+           "Deserialized a declaration we shouldn't have");
+  }
+ =20
+  if (LocalRedeclChains.empty())
+    return;
+ =20
+  // Sort the local redeclarations map by the first declaration ID,
+  // since the reader will be performing binary searches on this informati=
on.
+  llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
+ =20
+  // Emit the local redeclarations map.
+  using namespace llvm;
+  llvm::BitCodeAbbrev *Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
+  unsigned AbbrevID =3D Stream.EmitAbbrev(Abbrev);
+ =20
+  RecordData Record;
+  Record.push_back(LOCAL_REDECLARATIONS_MAP);
+  Record.push_back(LocalRedeclsMap.size());
+  Stream.EmitRecordWithBlob(AbbrevID, Record,=20
+    reinterpret_cast<char*>(LocalRedeclsMap.data()),
+    LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
+
+  // Emit the redeclaration chains.
+  Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
+}
+
+void ASTWriter::WriteObjCCategories() {
+  llvm::SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
+  RecordData Categories;
+ =20
+  for (unsigned I =3D 0, N =3D ObjCClassesWithCategories.size(); I !=3D N;=
 ++I) {
+    unsigned Size =3D 0;
+    unsigned StartIndex =3D Categories.size();
+   =20
+    ObjCInterfaceDecl *Class =3D ObjCClassesWithCategories[I];
+   =20
+    // Allocate space for the size.
+    Categories.push_back(0);
+   =20
+    // Add the categories.
+    for (ObjCCategoryDecl *Cat =3D Class->getCategoryList();
+         Cat; Cat =3D Cat->getNextClassCategory(), ++Size) {
+      assert(getDeclID(Cat) !=3D 0 && "Bogus category");
+      AddDeclRef(Cat, Categories);
+    }
+   =20
+    // Update the size.
+    Categories[StartIndex] =3D Size;
+   =20
+    // Record this interface -> category map.
+    ObjCCategoriesInfo CatInfo =3D { getDeclID(Class), StartIndex };
+    CategoriesMap.push_back(CatInfo);
+  }
+
+  // Sort the categories map by the definition ID, since the reader will be
+  // performing binary searches on this information.
+  llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
+
+  // Emit the categories map.
+  using namespace llvm;
+  llvm::BitCodeAbbrev *Abbrev =3D new BitCodeAbbrev();
+  Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
+  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
+  unsigned AbbrevID =3D Stream.EmitAbbrev(Abbrev);
+ =20
+  RecordData Record;
+  Record.push_back(OBJC_CATEGORIES_MAP);
+  Record.push_back(CategoriesMap.size());
+  Stream.EmitRecordWithBlob(AbbrevID, Record,=20
+                            reinterpret_cast<char*>(CategoriesMap.data()),
+                            CategoriesMap.size() * sizeof(ObjCCategoriesIn=
fo));
+ =20
+  // Emit the category lists.
+  Stream.EmitRecord(OBJC_CATEGORIES, Categories);
+}
+
+void ASTWriter::WriteMergedDecls() {
+  if (!Chain || Chain->MergedDecls.empty())
+    return;
+ =20
+  RecordData Record;
+  for (ASTReader::MergedDeclsMap::iterator I =3D Chain->MergedDecls.begin(=
),
+                                        IEnd =3D Chain->MergedDecls.end();
+       I !=3D IEnd; ++I) {
+    DeclID CanonID =3D I->first->isFromASTFile()? I->first->getGlobalID()
+                                              : getDeclID(I->first);
+    assert(CanonID && "Merged declaration not known?");
+   =20
+    Record.push_back(CanonID);
+    Record.push_back(I->second.size());
+    Record.append(I->second.begin(), I->second.end());
+  }
+  Stream.EmitRecord(MERGED_DECLARATIONS, Record);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // General Serialization Routines
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -2705,10 +3116,13 @@
 }
=20
 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
-  : Stream(Stream), Context(0), Chain(0), WritingAST(false),
+  : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
+    WritingAST(false), ASTHasCompilerErrors(false),
     FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
     FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
     FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),=20
+    FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),=20
+    NextSubmoduleID(FirstSubmoduleID),
     FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelector=
ID),
     CollectedStmts(&StmtsToEmit),
     NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
@@ -2724,11 +3138,20 @@
 {
 }
=20
+ASTWriter::~ASTWriter() {
+  for (FileDeclIDsTy::iterator
+         I =3D FileDeclIDs.begin(), E =3D FileDeclIDs.end(); I !=3D E; ++I)
+    delete I->second;
+}
+
 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
                          const std::string &OutputFile,
-                         bool IsModule, StringRef isysroot) {
+                         Module *WritingModule, StringRef isysroot,
+                         bool hasErrors) {
   WritingAST =3D true;
  =20
+  ASTHasCompilerErrors =3D hasErrors;
+ =20
   // Emit the file header.
   Stream.Emit((unsigned)'C', 8);
   Stream.Emit((unsigned)'P', 8);
@@ -2738,8 +3161,12 @@
   WriteBlockInfoBlock();
=20
   Context =3D &SemaRef.Context;
-  WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, IsModule);
+  PP =3D &SemaRef.PP;
+  this->WritingModule =3D WritingModule;
+  WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule);
   Context =3D 0;
+  PP =3D 0;
+  this->WritingModule =3D 0;
  =20
   WritingAST =3D false;
 }
@@ -2755,9 +3182,14 @@
=20
 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
                              StringRef isysroot,
-                             const std::string &OutputFile, bool IsModule)=
 {
+                             const std::string &OutputFile,=20
+                             Module *WritingModule) {
   using namespace llvm;
=20
+  // Make sure that the AST reader knows to finalize itself.
+  if (Chain)
+    Chain->finalizeForWriting();
+ =20
   ASTContext &Context =3D SemaRef.Context;
   Preprocessor &PP =3D SemaRef.PP;
=20
@@ -2769,6 +3201,8 @@
     DeclIDs[Context.ObjCSelDecl] =3D PREDEF_DECL_OBJC_SEL_ID;
   if (Context.ObjCClassDecl)
     DeclIDs[Context.ObjCClassDecl] =3D PREDEF_DECL_OBJC_CLASS_ID;
+  if (Context.ObjCProtocolClassDecl)
+    DeclIDs[Context.ObjCProtocolClassDecl] =3D PREDEF_DECL_OBJC_PROTOCOL_I=
D;
   if (Context.Int128Decl)
     DeclIDs[Context.Int128Decl] =3D PREDEF_DECL_INT_128_ID;
   if (Context.UInt128Decl)
@@ -2785,11 +3219,20 @@
     IdentifierTable &Table =3D PP.getIdentifierTable();
     SmallVector<const char *, 32> BuiltinNames;
     Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
-                                        Context.getLangOptions().NoBuiltin=
);
+                                        Context.getLangOpts().NoBuiltin);
     for (unsigned I =3D 0, N =3D BuiltinNames.size(); I !=3D N; ++I)
       getIdentifierRef(&Table.get(BuiltinNames[I]));
   }
=20
+  // If there are any out-of-date identifiers, bring them up to date.
+  if (ExternalPreprocessorSource *ExtSource =3D PP.getExternalSource()) {
+    for (IdentifierTable::iterator ID =3D PP.getIdentifierTable().begin(),
+                                IDEnd =3D PP.getIdentifierTable().end();
+         ID !=3D IDEnd; ++ID)
+      if (ID->second->isOutOfDate())
+        ExtSource->updateOutOfDateIdentifier(*ID->second);
+  }
+
   // Build a record containing all of the tentative definitions in this fi=
le, in
   // TentativeDefinitions order.  Generally, this record will be empty for
   // headers.
@@ -2890,52 +3333,9 @@
   RecordData Record;
   Stream.EnterSubblock(AST_BLOCK_ID, 5);
   WriteMetadata(Context, isysroot, OutputFile);
-  WriteLanguageOptions(Context.getLangOptions());
+  WriteLanguageOptions(Context.getLangOpts());
   if (StatCalls && isysroot.empty())
     WriteStatCache(*StatCalls);
-  WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
- =20
-  if (Chain) {
-    // Write the mapping information describing our module dependencies an=
d how
-    // each of those modules were mapped into our own offset/ID space, so =
that
-    // the reader can build the appropriate mapping to its own offset/ID s=
pace.
-    // The map consists solely of a blob with the following format:
-    // *(module-name-len:i16 module-name:len*i8
-    //   source-location-offset:i32
-    //   identifier-id:i32
-    //   preprocessed-entity-id:i32
-    //   macro-definition-id:i32
-    //   selector-id:i32
-    //   declaration-id:i32
-    //   c++-base-specifiers-id:i32
-    //   type-id:i32)
-    //=20
-    llvm::BitCodeAbbrev *Abbrev =3D new BitCodeAbbrev();
-    Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
-    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
-    unsigned ModuleOffsetMapAbbrev =3D Stream.EmitAbbrev(Abbrev);
-    llvm::SmallString<2048> Buffer;
-    {
-      llvm::raw_svector_ostream Out(Buffer);
-      for (ModuleManager::ModuleConstIterator M =3D Chain->ModuleMgr.begin=
(),
-           MEnd =3D Chain->ModuleMgr.end();
-           M !=3D MEnd; ++M) {
-        StringRef FileName =3D (*M)->FileName;
-        io::Emit16(Out, FileName.size());
-        Out.write(FileName.data(), FileName.size());
-        io::Emit32(Out, (*M)->SLocEntryBaseOffset);
-        io::Emit32(Out, (*M)->BaseIdentifierID);
-        io::Emit32(Out, (*M)->BasePreprocessedEntityID);
-        io::Emit32(Out, (*M)->BaseSelectorID);
-        io::Emit32(Out, (*M)->BaseDeclID);
-        io::Emit32(Out, (*M)->BaseTypeIndex);
-      }
-    }
-    Record.clear();
-    Record.push_back(MODULE_OFFSET_MAP);
-    Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
-                              Buffer.data(), Buffer.size());
-  }
=20
   // Create a lexical update block containing all of the declarations in t=
he
   // translation unit that do not come from other AST files.
@@ -2946,8 +3346,6 @@
        I !=3D E; ++I) {
     if (!(*I)->isFromASTFile())
       NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(=
*I)));
-    else if ((*I)->isChangedSinceDeserialization())
-      (void)GetDeclRef(*I); // Make sure it's written, but don't record it.
   }
  =20
   llvm::BitCodeAbbrev *Abv =3D new llvm::BitCodeAbbrev();
@@ -2978,15 +3376,12 @@
     }
   }
  =20
-  // Resolve any declaration pointers within the declaration updates block=
 and
-  // chained Objective-C categories block to declaration IDs.
+  // Resolve any declaration pointers within the declaration updates block.
   ResolveDeclUpdatesBlocks();
-  ResolveChainedObjCCategories();
  =20
   // Form the record of special types.
   RecordData SpecialTypes;
   AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes);
-  AddTypeRef(Context.ObjCProtoType, SpecialTypes);
   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
   AddTypeRef(Context.getFILEType(), SpecialTypes);
   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
@@ -2995,7 +3390,7 @@
   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
- =20
+
   // Keep writing types and declarations until all types and
   // declarations have been written.
   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
@@ -3014,11 +3409,57 @@
   }
   Stream.ExitBlock();
=20
-  WritePreprocessor(PP, IsModule);
+  WriteFileDeclIDsMap();
+  WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
+ =20
+  if (Chain) {
+    // Write the mapping information describing our module dependencies an=
d how
+    // each of those modules were mapped into our own offset/ID space, so =
that
+    // the reader can build the appropriate mapping to its own offset/ID s=
pace.
+    // The map consists solely of a blob with the following format:
+    // *(module-name-len:i16 module-name:len*i8
+    //   source-location-offset:i32
+    //   identifier-id:i32
+    //   preprocessed-entity-id:i32
+    //   macro-definition-id:i32
+    //   submodule-id:i32
+    //   selector-id:i32
+    //   declaration-id:i32
+    //   c++-base-specifiers-id:i32
+    //   type-id:i32)
+    //=20
+    llvm::BitCodeAbbrev *Abbrev =3D new BitCodeAbbrev();
+    Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
+    Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
+    unsigned ModuleOffsetMapAbbrev =3D Stream.EmitAbbrev(Abbrev);
+    SmallString<2048> Buffer;
+    {
+      llvm::raw_svector_ostream Out(Buffer);
+      for (ModuleManager::ModuleConstIterator M =3D Chain->ModuleMgr.begin=
(),
+                                           MEnd =3D Chain->ModuleMgr.end();
+           M !=3D MEnd; ++M) {
+        StringRef FileName =3D (*M)->FileName;
+        io::Emit16(Out, FileName.size());
+        Out.write(FileName.data(), FileName.size());
+        io::Emit32(Out, (*M)->SLocEntryBaseOffset);
+        io::Emit32(Out, (*M)->BaseIdentifierID);
+        io::Emit32(Out, (*M)->BasePreprocessedEntityID);
+        io::Emit32(Out, (*M)->BaseSubmoduleID);
+        io::Emit32(Out, (*M)->BaseSelectorID);
+        io::Emit32(Out, (*M)->BaseDeclID);
+        io::Emit32(Out, (*M)->BaseTypeIndex);
+      }
+    }
+    Record.clear();
+    Record.push_back(MODULE_OFFSET_MAP);
+    Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
+                              Buffer.data(), Buffer.size());
+  }
+  WritePreprocessor(PP, WritingModule !=3D 0);
   WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
   WriteSelectors(SemaRef);
   WriteReferencedSelectorsPool(SemaRef);
-  WriteIdentifierTable(PP, IsModule);
+  WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule !=3D 0);
   WriteFPPragmaOptions(SemaRef.getFPOptions());
   WriteOpenCLExtensions(SemaRef);
=20
@@ -3027,21 +3468,12 @@
=20
   WriteCXXBaseSpecifiersOffsets();
  =20
+  // If we're emitting a module, write out the submodule information. =20
+  if (WritingModule)
+    WriteSubmodules(WritingModule);
+
   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
=20
-  /// Build a record containing first declarations from a chained PCH and =
the
-  /// most recent declarations in this AST that they point to.
-  RecordData FirstLatestDeclIDs;
-  for (FirstLatestDeclMap::iterator I =3D FirstLatestDecls.begin(),=20
-                                    E =3D FirstLatestDecls.end();=20
-       I !=3D E; ++I) {
-    AddDeclRef(I->first, FirstLatestDeclIDs);
-    AddDeclRef(I->second, FirstLatestDeclIDs);
-  }
- =20
-  if (!FirstLatestDeclIDs.empty())
-    Stream.EmitRecord(REDECLS_UPDATE_LATEST, FirstLatestDeclIDs);
-
   // Write the record containing external, unnamed definitions.
   if (!ExternalDefinitions.empty())
     Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
@@ -3103,10 +3535,34 @@
        I !=3D E; ++I)
     WriteDeclContextVisibleUpdate(*I);
=20
+  if (!WritingModule) {
+    // Write the submodules that were imported, if any.
+    RecordData ImportedModules;
+    for (ASTContext::import_iterator I =3D Context.local_import_begin(),
+                                  IEnd =3D Context.local_import_end();
+         I !=3D IEnd; ++I) {
+      assert(SubmoduleIDs.find(I->getImportedModule()) !=3D SubmoduleIDs.e=
nd());
+      ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
+    }
+    if (!ImportedModules.empty()) {
+      // Sort module IDs.
+      llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
+     =20
+      // Unique module IDs.
+      ImportedModules.erase(std::unique(ImportedModules.begin(),=20
+                                        ImportedModules.end()),
+                            ImportedModules.end());
+     =20
+      Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
+    }
+  }
+ =20
   WriteDeclUpdatesBlocks();
   WriteDeclReplacementsBlock();
-  WriteChainedObjCCategories();
-
+  WriteMergedDecls();
+  WriteRedeclarations();
+  WriteObjCCategories();
+ =20
   // Some simple statistics
   Record.clear();
   Record.push_back(NumStatements);
@@ -3125,13 +3581,12 @@
     const Decl *D =3D I->first;
     UpdateRecord &URec =3D I->second;
    =20
-    if (DeclsToRewrite.count(D))
+    if (isRewritten(D))
       continue; // The decl will be written completely
=20
     unsigned Idx =3D 0, N =3D URec.size();
     while (Idx < N) {
       switch ((DeclUpdateKind)URec[Idx++]) {
-      case UPD_CXX_SET_DEFINITIONDATA:
       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
@@ -3158,7 +3613,7 @@
     const Decl *D =3D I->first;
     UpdateRecord &URec =3D I->second;
=20
-    if (DeclsToRewrite.count(D))
+    if (isRewritten(D))
       continue; // The decl will be written completely,no need to store up=
dates.
=20
     uint64_t Offset =3D Stream.GetCurrentBitNo();
@@ -3176,45 +3631,15 @@
     return;
=20
   RecordData Record;
-  for (SmallVector<std::pair<DeclID, uint64_t>, 16>::iterator
+  for (SmallVector<ReplacedDeclInfo, 16>::iterator
            I =3D ReplacedDecls.begin(), E =3D ReplacedDecls.end(); I !=3D =
E; ++I) {
-    Record.push_back(I->first);
-    Record.push_back(I->second);
+    Record.push_back(I->ID);
+    Record.push_back(I->Offset);
+    Record.push_back(I->Loc);
   }
   Stream.EmitRecord(DECL_REPLACEMENTS, Record);
 }
=20
-void ASTWriter::ResolveChainedObjCCategories() {
-  for (SmallVector<ChainedObjCCategoriesData, 16>::iterator
-       I =3D LocalChainedObjCCategories.begin(),
-       E =3D LocalChainedObjCCategories.end(); I !=3D E; ++I) {
-    ChainedObjCCategoriesData &Data =3D *I;
-    Data.InterfaceID =3D GetDeclRef(Data.Interface);
-    Data.TailCategoryID =3D GetDeclRef(Data.TailCategory);
-  }
-
-}
-
-void ASTWriter::WriteChainedObjCCategories() {
-  if (LocalChainedObjCCategories.empty())
-    return;
-
-  RecordData Record;
-  for (SmallVector<ChainedObjCCategoriesData, 16>::iterator
-         I =3D LocalChainedObjCCategories.begin(),
-         E =3D LocalChainedObjCCategories.end(); I !=3D E; ++I) {
-    ChainedObjCCategoriesData &Data =3D *I;
-    serialization::DeclID
-        HeadCatID =3D getDeclID(Data.Interface->getCategoryList());
-    assert(HeadCatID !=3D 0 && "Category not written ?");
-
-    Record.push_back(Data.InterfaceID);
-    Record.push_back(HeadCatID);
-    Record.push_back(Data.TailCategoryID);
-  }
-  Stream.EmitRecord(OBJC_CHAINED_CATEGORIES, Record);
-}
-
 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Reco=
rd) {
   Record.push_back(Loc.getRawEncoding());
 }
@@ -3397,6 +3822,12 @@
   if (D =3D=3D 0) {
     return 0;
   }
+ =20
+  // If D comes from an AST file, its declaration ID is already known and
+  // fixed.
+  if (D->isFromASTFile())
+    return D->getGlobalID();
+ =20
   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer=
");
   DeclID &ID =3D DeclIDs[D];
   if (ID =3D=3D 0) {
@@ -3404,12 +3835,6 @@
     // enqueue it in the list of declarations to emit.
     ID =3D NextDeclID++;
     DeclTypesToEmit.push(const_cast<Decl *>(D));
-  } else if (ID < FirstDeclID && D->isChangedSinceDeserialization()) {
-    // We don't add it to the replacement collection here, because we don't
-    // have the offset yet.
-    DeclTypesToEmit.push(const_cast<Decl *>(D));
-    // Reset the flag, so that we don't add this decl multiple times.
-    const_cast<Decl *>(D)->setChangedSinceDeserialization(false);
   }
=20
   return ID;
@@ -3419,10 +3844,65 @@
   if (D =3D=3D 0)
     return 0;
=20
+  // If D comes from an AST file, its declaration ID is already known and
+  // fixed.
+  if (D->isFromASTFile())
+    return D->getGlobalID();
+
   assert(DeclIDs.find(D) !=3D DeclIDs.end() && "Declaration not emitted!");
   return DeclIDs[D];
 }
=20
+static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> =
L,
+                               std::pair<unsigned, serialization::DeclID> =
R) {
+  return L.first < R.first;
+}
+
+void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
+  assert(ID);
+  assert(D);
+
+  SourceLocation Loc =3D D->getLocation();
+  if (Loc.isInvalid())
+    return;
+
+  // We only keep track of the file-level declarations of each file.
+  if (!D->getLexicalDeclContext()->isFileContext())
+    return;
+  // FIXME: ParmVarDecls that are part of a function type of a parameter of
+  // a function/objc method, should not have TU as lexical context.
+  if (isa<ParmVarDecl>(D))
+    return;
+
+  SourceManager &SM =3D Context->getSourceManager();
+  SourceLocation FileLoc =3D SM.getFileLoc(Loc);
+  assert(SM.isLocalSourceLocation(FileLoc));
+  FileID FID;
+  unsigned Offset;
+  llvm::tie(FID, Offset) =3D SM.getDecomposedLoc(FileLoc);
+  if (FID.isInvalid())
+    return;
+  const SrcMgr::SLocEntry *Entry =3D &SM.getSLocEntry(FID);
+  assert(Entry->isFile());
+
+  DeclIDInFileInfo *&Info =3D FileDeclIDs[Entry];
+  if (!Info)
+    Info =3D new DeclIDInFileInfo();
+
+  std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
+  LocDeclIDsTy &Decls =3D Info->DeclIDs;
+
+  if (Decls.empty() || Decls.back().first <=3D Offset) {
+    Decls.push_back(LocDecl);
+    return;
+  }
+
+  LocDeclIDsTy::iterator
+    I =3D std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDec=
l);
+
+  Decls.insert(I, LocDecl);
+}
+
 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &R=
ecord) {
   // FIXME: Emit a stable enum for NameKind.  0 =3D Identifier etc.
   Record.push_back(Name.getNameKind());
@@ -3776,11 +4256,11 @@
=20
     if (Init->isBaseInitializer()) {
       Record.push_back(CTOR_INITIALIZER_BASE);
-      AddTypeSourceInfo(Init->getBaseClassInfo(), Record);
+      AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
       Record.push_back(Init->isBaseVirtual());
     } else if (Init->isDelegatingInitializer()) {
       Record.push_back(CTOR_INITIALIZER_DELEGATING);
-      AddDeclRef(Init->getTargetConstructor(), Record);
+      AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
     } else if (Init->isMemberInitializer()){
       Record.push_back(CTOR_INITIALIZER_MEMBER);
       AddDeclRef(Init->getMember(), Record);
@@ -3807,6 +4287,7 @@
 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImp=
l &Record) {
   assert(D->DefinitionData);
   struct CXXRecordDecl::DefinitionData &Data =3D *D->DefinitionData;
+  Record.push_back(Data.IsLambda);
   Record.push_back(Data.UserDeclaredConstructor);
   Record.push_back(Data.UserDeclaredCopyConstructor);
   Record.push_back(Data.UserDeclaredMoveConstructor);
@@ -3824,13 +4305,21 @@
   Record.push_back(Data.HasProtectedFields);
   Record.push_back(Data.HasPublicFields);
   Record.push_back(Data.HasMutableFields);
+  Record.push_back(Data.HasOnlyCMembers);
   Record.push_back(Data.HasTrivialDefaultConstructor);
   Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
+  Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
+  Record.push_back(Data.DefaultedCopyConstructorIsConstexpr);
+  Record.push_back(Data.DefaultedMoveConstructorIsConstexpr);
+  Record.push_back(Data.HasConstexprDefaultConstructor);
+  Record.push_back(Data.HasConstexprCopyConstructor);
+  Record.push_back(Data.HasConstexprMoveConstructor);
   Record.push_back(Data.HasTrivialCopyConstructor);
   Record.push_back(Data.HasTrivialMoveConstructor);
   Record.push_back(Data.HasTrivialCopyAssignment);
   Record.push_back(Data.HasTrivialMoveAssignment);
   Record.push_back(Data.HasTrivialDestructor);
+  Record.push_back(Data.HasIrrelevantDestructor);
   Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
   Record.push_back(Data.ComputedVisibleConversions);
   Record.push_back(Data.UserProvidedDefaultConstructor);
@@ -3842,6 +4331,7 @@
   Record.push_back(Data.DeclaredDestructor);
   Record.push_back(Data.FailedImplicitMoveConstructor);
   Record.push_back(Data.FailedImplicitMoveAssignment);
+  // IsLambda bit is already saved.
=20
   Record.push_back(Data.NumBases);
   if (Data.NumBases > 0)
@@ -3858,6 +4348,27 @@
   AddUnresolvedSet(Data.VisibleConversions, Record);
   // Data.Definition is the owning decl, no need to write it.=20
   AddDeclRef(Data.FirstFriend, Record);
+ =20
+  // Add lambda-specific data.
+  if (Data.IsLambda) {
+    CXXRecordDecl::LambdaDefinitionData &Lambda =3D D->getLambdaData();
+    Record.push_back(Lambda.Dependent);
+    Record.push_back(Lambda.NumCaptures);
+    Record.push_back(Lambda.NumExplicitCaptures);
+    Record.push_back(Lambda.ManglingNumber);
+    AddDeclRef(Lambda.ContextDecl, Record);
+    for (unsigned I =3D 0, N =3D Lambda.NumCaptures; I !=3D N; ++I) {
+      LambdaExpr::Capture &Capture =3D Lambda.Captures[I];
+      AddSourceLocation(Capture.getLocation(), Record);
+      Record.push_back(Capture.isImplicit());
+      Record.push_back(Capture.getCaptureKind()); // FIXME: stable!
+      VarDecl *Var =3D Capture.capturesVariable()? Capture.getCapturedVar(=
) : 0;
+      AddDeclRef(Var, Record);
+      AddSourceLocation(Capture.isPackExpansion()? Capture.getEllipsisLoc()
+                                                 : SourceLocation(),=20
+                        Record);
+    }
+  }
 }
=20
 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
@@ -3866,6 +4377,7 @@
   assert(FirstDeclID =3D=3D NextDeclID &&
          FirstTypeID =3D=3D NextTypeID &&
          FirstIdentID =3D=3D NextIdentID &&
+         FirstSubmoduleID =3D=3D NextSubmoduleID &&
          FirstSelectorID =3D=3D NextSelectorID &&
          "Setting chain after writing has started.");
=20
@@ -3874,11 +4386,13 @@
   FirstDeclID =3D NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
   FirstTypeID =3D NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
   FirstIdentID =3D NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
+  FirstSubmoduleID =3D NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmod=
ules();
   FirstSelectorID =3D NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelector=
s();
   NextDeclID =3D FirstDeclID;
   NextTypeID =3D FirstTypeID;
   NextIdentID =3D FirstIdentID;
   NextSelectorID =3D FirstSelectorID;
+  NextSubmoduleID =3D FirstSubmoduleID;
 }
=20
 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
@@ -3898,10 +4412,6 @@
     StoredIdx =3D Idx;
 }
=20
-void ASTWriter::DeclRead(DeclID ID, const Decl *D) {
-  DeclIDs[D] =3D ID;
-}
-
 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
   SelectorIDs[S] =3D ID;
 }
@@ -3912,6 +4422,15 @@
   MacroDefinitions[MD] =3D ID;
 }
=20
+void ASTWriter::MacroVisible(IdentifierInfo *II) {
+  DeserializedMacroNames.push_back(II);
+}
+
+void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
+  assert(SubmoduleIDs.find(Mod) =3D=3D SubmoduleIDs.end());
+  SubmoduleIDs[Mod] =3D ID;
+}
+
 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
   assert(D->isCompleteDefinition());
   assert(!WritingAST && "Already writing the AST!");
@@ -3923,22 +4442,6 @@
       // have created a new definition decl instead ?
       RewriteDecl(RD);
     }
-
-    for (CXXRecordDecl::redecl_iterator
-           I =3D RD->redecls_begin(), E =3D RD->redecls_end(); I !=3D E; +=
+I) {
-      CXXRecordDecl *Redecl =3D cast<CXXRecordDecl>(*I);
-      if (Redecl =3D=3D RD)
-        continue;
-
-      // We are interested when a PCH decl is modified.
-      if (Redecl->isFromASTFile()) {
-        UpdateRecord &Record =3D DeclUpdates[Redecl];
-        Record.push_back(UPD_CXX_SET_DEFINITIONDATA);
-        assert(Redecl->DefinitionData);
-        assert(Redecl->DefinitionData->Definition =3D=3D D);
-        Record.push_back(reinterpret_cast<uint64_t>(D)); // the Definition=
Decl
-      }
-    }
   }
 }
 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
@@ -4023,11 +4526,23 @@
   assert(!WritingAST && "Already writing the AST!");
   if (!IFD->isFromASTFile())
     return; // Declaration not imported from PCH.
-  if (CatD->getNextClassCategory() &&
-      !CatD->getNextClassCategory()->isFromASTFile())
-    return; // We already recorded that the tail of a category chain shoul=
d be
-            // attached to an interface.
-
-  ChainedObjCCategoriesData Data =3D  { IFD, CatD, 0, 0 };
-  LocalChainedObjCCategories.push_back(Data);
+ =20
+  assert(IFD->getDefinition() && "Category on a class without a definition=
?");
+  ObjCClassesWithCategories.insert(
+    const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
 }
+
+
+void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *=
Prop,
+                                          const ObjCPropertyDecl *OrigProp,
+                                          const ObjCCategoryDecl *ClassExt=
) {
+  const ObjCInterfaceDecl *D =3D ClassExt->getClassInterface();
+  if (!D)
+    return;
+
+  assert(!WritingAST && "Already writing the AST!");
+  if (!D->isFromASTFile())
+    return; // Declaration not imported from PCH.
+
+  RewriteDecl(D);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTWriterDecl.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTWriterDecl.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTWriterDecl.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -12,12 +12,14 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/Serialization/ASTWriter.h"
+#include "clang/Serialization/ASTReader.h"
 #include "ASTCommon.h"
 #include "clang/AST/DeclVisitor.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/DeclContextInternals.h"
+#include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Bitcode/BitstreamWriter.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -54,6 +56,7 @@
     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
     void VisitTypeDecl(TypeDecl *D);
+    void VisitTypedefNameDecl(TypedefNameDecl *D);
     void VisitTypedefDecl(TypedefDecl *D);
     void VisitTypeAliasDecl(TypeAliasDecl *D);
     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
@@ -93,6 +96,7 @@
     void VisitUsingShadowDecl(UsingShadowDecl *D);
     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
+    void VisitImportDecl(ImportDecl *D);
     void VisitAccessSpecDecl(AccessSpecDecl *D);
     void VisitFriendDecl(FriendDecl *D);
     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
@@ -111,8 +115,6 @@
     void VisitObjCIvarDecl(ObjCIvarDecl *D);
     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
-    void VisitObjCClassDecl(ObjCClassDecl *D);
-    void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
     void VisitObjCImplDecl(ObjCImplDecl *D);
     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
@@ -146,7 +148,6 @@
 void ASTDeclWriter::VisitDecl(Decl *D) {
   Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
   Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record=
);
-  Writer.AddSourceLocation(D->getLocation(), Record);
   Record.push_back(D->isInvalidDecl());
   Record.push_back(D->hasAttrs());
   if (D->hasAttrs())
@@ -154,8 +155,10 @@
   Record.push_back(D->isImplicit());
   Record.push_back(D->isUsed(false));
   Record.push_back(D->isReferenced());
+  Record.push_back(D->isTopLevelDeclInObjCContainer());
   Record.push_back(D->getAccess());
-  Record.push_back(D->ModulePrivate);
+  Record.push_back(D->isModulePrivate());
+  Record.push_back(Writer.inferSubmoduleIDFromLocation(D->getLocation()));
 }
=20
 void ASTDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
@@ -173,16 +176,21 @@
   Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
 }
=20
+void ASTDeclWriter::VisitTypedefNameDecl(TypedefNameDecl *D) {
+  VisitRedeclarable(D);
+  VisitTypeDecl(D);
+  Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record); =20
+}
+
 void ASTDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
-  VisitTypeDecl(D);
-  Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
-
+  VisitTypedefNameDecl(D);
   if (!D->hasAttrs() &&
       !D->isImplicit() &&
       !D->isUsed(false) &&
-      D->RedeclLink.getNext() =3D=3D D &&
+      D->getFirstDeclaration() =3D=3D D->getMostRecentDecl() &&
       !D->isInvalidDecl() &&
       !D->isReferenced() &&
+      !D->isTopLevelDeclInObjCContainer() &&
       D->getAccess() =3D=3D AS_none &&
       !D->isModulePrivate() &&
       D->getDeclName().getNameKind() =3D=3D DeclarationName::Identifier)
@@ -192,14 +200,13 @@
 }
=20
 void ASTDeclWriter::VisitTypeAliasDecl(TypeAliasDecl *D) {
-  VisitTypeDecl(D);
-  Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
+  VisitTypedefNameDecl(D);
   Code =3D serialization::DECL_TYPEALIAS;
 }
=20
 void ASTDeclWriter::VisitTagDecl(TagDecl *D) {
+  VisitRedeclarable(D);
   VisitTypeDecl(D);
-  VisitRedeclarable(D);
   Record.push_back(D->getIdentifierNamespace());
   Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
   Record.push_back(D->isCompleteDefinition());
@@ -224,15 +231,22 @@
   Record.push_back(D->isScoped());
   Record.push_back(D->isScopedUsingClassTag());
   Record.push_back(D->isFixed());
-  Writer.AddDeclRef(D->getInstantiatedFromMemberEnum(), Record);
+  if (MemberSpecializationInfo *MemberInfo =3D D->getMemberSpecializationI=
nfo()) {
+    Writer.AddDeclRef(MemberInfo->getInstantiatedFrom(), Record);
+    Record.push_back(MemberInfo->getTemplateSpecializationKind());
+    Writer.AddSourceLocation(MemberInfo->getPointOfInstantiation(), Record=
);
+  } else {
+    Writer.AddDeclRef(0, Record);
+  }
=20
   if (!D->hasAttrs() &&
       !D->isImplicit() &&
       !D->isUsed(false) &&
       !D->hasExtInfo() &&
-      D->RedeclLink.getNext() =3D=3D D &&
+      D->getFirstDeclaration() =3D=3D D->getMostRecentDecl() &&
       !D->isInvalidDecl() &&
       !D->isReferenced() &&
+      !D->isTopLevelDeclInObjCContainer() &&
       D->getAccess() =3D=3D AS_none &&
       !D->isModulePrivate() &&
       !CXXRecordDecl::classofKind(D->getKind()) &&
@@ -253,9 +267,10 @@
       !D->isImplicit() &&
       !D->isUsed(false) &&
       !D->hasExtInfo() &&
-      D->RedeclLink.getNext() =3D=3D D &&
+      D->getFirstDeclaration() =3D=3D D->getMostRecentDecl() &&
       !D->isInvalidDecl() &&
       !D->isReferenced() &&
+      !D->isTopLevelDeclInObjCContainer() &&
       D->getAccess() =3D=3D AS_none &&
       !D->isModulePrivate() &&
       !CXXRecordDecl::classofKind(D->getKind()) &&
@@ -289,14 +304,33 @@
 }
=20
 void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
+  VisitRedeclarable(D);
   VisitDeclaratorDecl(D);
-  VisitRedeclarable(D);
=20
   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
   Record.push_back(D->getIdentifierNamespace());
+ =20
+  // FunctionDecl's body is handled last at ASTWriterDecl::Visit,
+  // after everything else is written.
+ =20
+  Record.push_back(D->getStorageClass()); // FIXME: stable encoding
+  Record.push_back(D->getStorageClassAsWritten());
+  Record.push_back(D->IsInline);
+  Record.push_back(D->isInlineSpecified());
+  Record.push_back(D->isVirtualAsWritten());
+  Record.push_back(D->isPure());
+  Record.push_back(D->hasInheritedPrototype());
+  Record.push_back(D->hasWrittenPrototype());
+  Record.push_back(D->isDeletedAsWritten());
+  Record.push_back(D->isTrivial());
+  Record.push_back(D->isDefaulted());
+  Record.push_back(D->isExplicitlyDefaulted());
+  Record.push_back(D->hasImplicitReturnZero());
+  Record.push_back(D->isConstexpr());
+  Writer.AddSourceLocation(D->getLocEnd(), Record);
+
   Record.push_back(D->getTemplatedKind());
   switch (D->getTemplatedKind()) {
-  default: llvm_unreachable("Unhandled TemplatedKind!");
   case FunctionDecl::TK_NonTemplate:
     break;
   case FunctionDecl::TK_FunctionTemplate:
@@ -360,25 +394,6 @@
   }
   }
=20
-  // FunctionDecl's body is handled last at ASTWriterDecl::Visit,
-  // after everything else is written.
-
-  Record.push_back(D->getStorageClass()); // FIXME: stable encoding
-  Record.push_back(D->getStorageClassAsWritten());
-  Record.push_back(D->IsInline);
-  Record.push_back(D->isInlineSpecified());
-  Record.push_back(D->isVirtualAsWritten());
-  Record.push_back(D->isPure());
-  Record.push_back(D->hasInheritedPrototype());
-  Record.push_back(D->hasWrittenPrototype());
-  Record.push_back(D->isDeletedAsWritten());
-  Record.push_back(D->isTrivial());
-  Record.push_back(D->isDefaulted());
-  Record.push_back(D->isExplicitlyDefaulted());
-  Record.push_back(D->hasImplicitReturnZero());
-  Record.push_back(D->isConstexpr());
-  Writer.AddSourceLocation(D->getLocEnd(), Record);
-
   Record.push_back(D->param_size());
   for (FunctionDecl::param_iterator P =3D D->param_begin(), PEnd =3D D->pa=
ram_end();
        P !=3D PEnd; ++P)
@@ -441,39 +456,48 @@
 }
=20
 void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
+  VisitRedeclarable(D);
   VisitObjCContainerDecl(D);
   Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
-  Writer.AddDeclRef(D->getSuperClass(), Record);
=20
-  // Write out the protocols that are directly referenced by the @interfac=
e.
-  Record.push_back(D->ReferencedProtocols.size());
-  for (ObjCInterfaceDecl::protocol_iterator P =3D D->protocol_begin(),
-         PEnd =3D D->protocol_end();
-       P !=3D PEnd; ++P)
-    Writer.AddDeclRef(*P, Record);
-  for (ObjCInterfaceDecl::protocol_loc_iterator PL =3D D->protocol_loc_beg=
in(),
+  Record.push_back(D->isThisDeclarationADefinition());
+  if (D->isThisDeclarationADefinition()) {
+    // Write the DefinitionData
+    ObjCInterfaceDecl::DefinitionData &Data =3D D->data();
+   =20
+    Writer.AddDeclRef(D->getSuperClass(), Record);
+    Writer.AddSourceLocation(D->getSuperClassLoc(), Record);
+    Writer.AddSourceLocation(D->getEndOfDefinitionLoc(), Record);
+
+    // Write out the protocols that are directly referenced by the @interf=
ace.
+    Record.push_back(Data.ReferencedProtocols.size());
+    for (ObjCInterfaceDecl::protocol_iterator P =3D D->protocol_begin(),
+                                           PEnd =3D D->protocol_end();
+         P !=3D PEnd; ++P)
+      Writer.AddDeclRef(*P, Record);
+    for (ObjCInterfaceDecl::protocol_loc_iterator PL =3D D->protocol_loc_b=
egin(),
          PLEnd =3D D->protocol_loc_end();
-       PL !=3D PLEnd; ++PL)
-    Writer.AddSourceLocation(*PL, Record);
-
-  // Write out the protocols that are transitively referenced.
-  Record.push_back(D->AllReferencedProtocols.size());
-  for (ObjCList<ObjCProtocolDecl>::iterator
-        P =3D D->AllReferencedProtocols.begin(),
-        PEnd =3D D->AllReferencedProtocols.end();
-       P !=3D PEnd; ++P)
-    Writer.AddDeclRef(*P, Record);
+         PL !=3D PLEnd; ++PL)
+      Writer.AddSourceLocation(*PL, Record);
+   =20
+    // Write out the protocols that are transitively referenced.
+    Record.push_back(Data.AllReferencedProtocols.size());
+    for (ObjCList<ObjCProtocolDecl>::iterator
+              P =3D Data.AllReferencedProtocols.begin(),
+           PEnd =3D Data.AllReferencedProtocols.end();
+         P !=3D PEnd; ++P)
+      Writer.AddDeclRef(*P, Record);
+   =20
+    if (ObjCCategoryDecl *Cat =3D D->getCategoryList()) {
+      // Ensure that we write out the set of categories for this class.
+      Writer.ObjCClassesWithCategories.insert(D);
+     =20
+      // Make sure that the categories get serialized.
+      for (; Cat; Cat =3D Cat->getNextClassCategory())
+        (void)Writer.GetDeclRef(Cat);
+    }
+  } =20
  =20
-  // Write out the ivars.
-  Record.push_back(D->ivar_size());
-  for (ObjCInterfaceDecl::ivar_iterator I =3D D->ivar_begin(),
-                                     IEnd =3D D->ivar_end(); I !=3D IEnd; =
++I)
-    Writer.AddDeclRef(*I, Record);
-  Writer.AddDeclRef(D->getCategoryList(), Record);
-  Record.push_back(D->isForwardDecl());
-  Record.push_back(D->isImplicitInterfaceDecl());
-  Writer.AddSourceLocation(D->getSuperClassLoc(), Record);
-  Writer.AddSourceLocation(D->getLocEnd(), Record);
   Code =3D serialization::DECL_OBJC_INTERFACE;
 }
=20
@@ -498,17 +522,21 @@
 }
=20
 void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
+  VisitRedeclarable(D);
   VisitObjCContainerDecl(D);
-  Record.push_back(D->isForwardDecl());
-  Writer.AddSourceLocation(D->getLocEnd(), Record);
-  Record.push_back(D->protocol_size());
-  for (ObjCProtocolDecl::protocol_iterator
-       I =3D D->protocol_begin(), IEnd =3D D->protocol_end(); I !=3D IEnd;=
 ++I)
-    Writer.AddDeclRef(*I, Record);
-  for (ObjCProtocolDecl::protocol_loc_iterator PL =3D D->protocol_loc_begi=
n(),
-         PLEnd =3D D->protocol_loc_end();
-       PL !=3D PLEnd; ++PL)
-    Writer.AddSourceLocation(*PL, Record);
+ =20
+  Record.push_back(D->isThisDeclarationADefinition());
+  if (D->isThisDeclarationADefinition()) {
+    Record.push_back(D->protocol_size());
+    for (ObjCProtocolDecl::protocol_iterator
+         I =3D D->protocol_begin(), IEnd =3D D->protocol_end(); I !=3D IEn=
d; ++I)
+      Writer.AddDeclRef(*I, Record);
+    for (ObjCProtocolDecl::protocol_loc_iterator PL =3D D->protocol_loc_be=
gin(),
+           PLEnd =3D D->protocol_loc_end();
+         PL !=3D PLEnd; ++PL)
+      Writer.AddSourceLocation(*PL, Record);
+  }
+ =20
   Code =3D serialization::DECL_OBJC_PROTOCOL;
 }
=20
@@ -517,28 +545,11 @@
   Code =3D serialization::DECL_OBJC_AT_DEFS_FIELD;
 }
=20
-void ASTDeclWriter::VisitObjCClassDecl(ObjCClassDecl *D) {
-  VisitDecl(D);
-  Writer.AddDeclRef(D->getForwardInterfaceDecl(), Record);
-  Writer.AddSourceLocation(D->getForwardDecl()->getLocation(), Record);
-  Code =3D serialization::DECL_OBJC_CLASS;
-}
-
-void ASTDeclWriter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *=
D) {
-  VisitDecl(D);
-  Record.push_back(D->protocol_size());
-  for (ObjCForwardProtocolDecl::protocol_iterator
-       I =3D D->protocol_begin(), IEnd =3D D->protocol_end(); I !=3D IEnd;=
 ++I)
-    Writer.AddDeclRef(*I, Record);
-  for (ObjCForwardProtocolDecl::protocol_loc_iterator=20
-         PL =3D D->protocol_loc_begin(), PLEnd =3D D->protocol_loc_end();
-       PL !=3D PLEnd; ++PL)
-    Writer.AddSourceLocation(*PL, Record);
-  Code =3D serialization::DECL_OBJC_FORWARD_PROTOCOL;
-}
-
 void ASTDeclWriter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
   VisitObjCContainerDecl(D);
+  Writer.AddSourceLocation(D->getCategoryNameLoc(), Record);
+  Writer.AddSourceLocation(D->getIvarLBraceLoc(), Record);
+  Writer.AddSourceLocation(D->getIvarRBraceLoc(), Record);
   Writer.AddDeclRef(D->getClassInterface(), Record);
   Record.push_back(D->protocol_size());
   for (ObjCCategoryDecl::protocol_iterator
@@ -548,9 +559,7 @@
          PL =3D D->protocol_loc_begin(), PLEnd =3D D->protocol_loc_end();
        PL !=3D PLEnd; ++PL)
     Writer.AddSourceLocation(*PL, Record);
-  Writer.AddDeclRef(D->getNextClassCategory(), Record);
   Record.push_back(D->hasSynthBitfield());
-  Writer.AddSourceLocation(D->getCategoryNameLoc(), Record);
   Code =3D serialization::DECL_OBJC_CATEGORY;
 }
=20
@@ -563,6 +572,7 @@
 void ASTDeclWriter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
   VisitNamedDecl(D);
   Writer.AddSourceLocation(D->getAtLoc(), Record);
+  Writer.AddSourceLocation(D->getLParenLoc(), Record);
   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
   // FIXME: stable encoding
   Record.push_back((unsigned)D->getPropertyAttributes());
@@ -586,12 +596,15 @@
 void ASTDeclWriter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
   VisitObjCImplDecl(D);
   Writer.AddIdentifierRef(D->getIdentifier(), Record);
+  Writer.AddSourceLocation(D->getCategoryNameLoc(), Record);
   Code =3D serialization::DECL_OBJC_CATEGORY_IMPL;
 }
=20
 void ASTDeclWriter::VisitObjCImplementationDecl(ObjCImplementationDecl *D)=
 {
   VisitObjCImplDecl(D);
   Writer.AddDeclRef(D->getSuperClass(), Record);
+  Writer.AddSourceLocation(D->getIvarLBraceLoc(), Record);
+  Writer.AddSourceLocation(D->getIvarRBraceLoc(), Record);
   Writer.AddCXXCtorInitializers(D->IvarInitializers, D->NumIvarInitializer=
s,
                                 Record);
   Record.push_back(D->hasSynthBitfield());
@@ -625,6 +638,7 @@
       !D->isUsed(false) &&
       !D->isInvalidDecl() &&
       !D->isReferenced() &&
+      !D->isTopLevelDeclInObjCContainer() &&
       !D->isModulePrivate() &&
       !D->getBitWidth() &&
       !D->hasInClassInitializer() &&
@@ -649,19 +663,22 @@
 }
=20
 void ASTDeclWriter::VisitVarDecl(VarDecl *D) {
+  VisitRedeclarable(D);
   VisitDeclaratorDecl(D);
-  VisitRedeclarable(D);
   Record.push_back(D->getStorageClass()); // FIXME: stable encoding
   Record.push_back(D->getStorageClassAsWritten());
   Record.push_back(D->isThreadSpecified());
-  Record.push_back(D->hasCXXDirectInitializer());
+  Record.push_back(D->getInitStyle());
   Record.push_back(D->isExceptionVariable());
   Record.push_back(D->isNRVOVariable());
   Record.push_back(D->isCXXForRangeDecl());
   Record.push_back(D->isARCPseudoStrong());
-  Record.push_back(D->getInit() ? 1 : 0);
-  if (D->getInit())
+  if (D->getInit()) {
+    Record.push_back(!D->isInitKnownICE() ? 1 : (D->isInitICE() ? 3 : 2));
     Writer.AddStmt(D->getInit());
+  } else {
+    Record.push_back(0);
+  }
=20
   MemberSpecializationInfo *SpecInfo
     =3D D->isStaticDataMember() ? D->getMemberSpecializationInfo() : 0;
@@ -677,12 +694,13 @@
       !D->isUsed(false) &&
       !D->isInvalidDecl() &&
       !D->isReferenced() &&
+      !D->isTopLevelDeclInObjCContainer() &&
       D->getAccess() =3D=3D AS_none &&
       !D->isModulePrivate() &&
       D->getDeclName().getNameKind() =3D=3D DeclarationName::Identifier &&
       !D->hasExtInfo() &&
-      D->RedeclLink.getNext() =3D=3D D &&
-      !D->hasCXXDirectInitializer() &&
+      D->getFirstDeclaration() =3D=3D D->getMostRecentDecl() &&
+      D->getInitStyle() =3D=3D VarDecl::CInit &&
       D->getInit() =3D=3D 0 &&
       !isa<ParmVarDecl>(D) &&
       !SpecInfo)
@@ -718,10 +736,12 @@
       !D->hasExtInfo() &&
       !D->isImplicit() &&
       !D->isUsed(false) &&
+      !D->isInvalidDecl() &&
+      !D->isReferenced() &&
       D->getAccess() =3D=3D AS_none &&
       !D->isModulePrivate() &&
       D->getStorageClass() =3D=3D 0 &&
-      !D->hasCXXDirectInitializer() && // Can params have this ever?
+      D->getInitStyle() =3D=3D VarDecl::CInit && // Can params have anythi=
ng else?
       D->getFunctionScopeDepth() =3D=3D 0 &&
       D->getObjCDeclQualifier() =3D=3D 0 &&
       !D->isKNRPromoted() &&
@@ -732,11 +752,10 @@
=20
   // Check things we know are true of *every* PARM_VAR_DECL, which is more=
 than
   // just us assuming it.
-  assert(!D->isInvalidDecl() && "Shouldn't emit invalid decls");
   assert(!D->isThreadSpecified() && "PARM_VAR_DECL can't be __thread");
   assert(D->getAccess() =3D=3D AS_none && "PARM_VAR_DECL can't be public/p=
rivate");
   assert(!D->isExceptionVariable() && "PARM_VAR_DECL can't be exception va=
r");
-  assert(D->getPreviousDeclaration() =3D=3D 0 && "PARM_VAR_DECL can't be r=
edecl");
+  assert(D->getPreviousDecl() =3D=3D 0 && "PARM_VAR_DECL can't be redecl");
   assert(!D->isStaticDataMember() &&
          "PARM_VAR_DECL can't be static data member");
 }
@@ -791,18 +810,14 @@
=20
=20
 void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) {
+  VisitRedeclarable(D);
   VisitNamedDecl(D);
   Record.push_back(D->isInline());
   Writer.AddSourceLocation(D->getLocStart(), Record);
   Writer.AddSourceLocation(D->getRBraceLoc(), Record);
-  Writer.AddDeclRef(D->getNextNamespace(), Record);
=20
-  // Only write one reference--original or anonymous
-  Record.push_back(D->isOriginalNamespace());
   if (D->isOriginalNamespace())
     Writer.AddDeclRef(D->getAnonymousNamespace(), Record);
-  else
-    Writer.AddDeclRef(D->getOriginalNamespace(), Record);
   Code =3D serialization::DECL_NAMESPACE;
=20
   if (Writer.hasChain() && !D->isOriginalNamespace() &&
@@ -811,9 +826,7 @@
     Writer.AddUpdatedDeclContext(NS);
=20
     // Make sure all visible decls are written. They will be recorded late=
r.
-    NS->lookup(DeclarationName());
-    StoredDeclsMap *Map =3D static_cast<StoredDeclsMap*>(NS->getLookupPtr(=
));
-    if (Map) {
+    if (StoredDeclsMap *Map =3D NS->buildLookup()) {
       for (StoredDeclsMap::iterator D =3D Map->begin(), DEnd =3D Map->end(=
);
            D !=3D DEnd; ++D) {
         DeclContext::lookup_result Result =3D D->second.getLookupResult();
@@ -825,7 +838,8 @@
     }
   }
=20
-  if (Writer.hasChain() && D->isAnonymousNamespace() && !D->getNextNamespa=
ce()){
+  if (Writer.hasChain() && D->isAnonymousNamespace() &&=20
+      D =3D=3D D->getMostRecentDecl()) {
     // This is a most recent reopening of the anonymous namespace. If its =
parent
     // is in a previous PCH (or is the TU), mark that parent for update, b=
ecause
     // the original namespace always points to the latest re-opening of its
@@ -854,7 +868,7 @@
   Writer.AddSourceLocation(D->getUsingLocation(), Record);
   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
-  Writer.AddDeclRef(D->FirstUsingShadow, Record);
+  Writer.AddDeclRef(D->FirstUsingShadow.getPointer(), Record);
   Record.push_back(D->isTypeName());
   Writer.AddDeclRef(Context.getInstantiatedFromUsingDecl(D), Record);
   Code =3D serialization::DECL_USING;
@@ -896,12 +910,8 @@
=20
 void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl *D) {
   VisitRecordDecl(D);
-
-  CXXRecordDecl *DefinitionDecl =3D 0;
-  if (D->DefinitionData)
-    DefinitionDecl =3D D->DefinitionData->Definition;
-  Writer.AddDeclRef(DefinitionDecl, Record);
-  if (D =3D=3D DefinitionDecl)
+  Record.push_back(D->isThisDeclarationADefinition());
+  if (D->isThisDeclarationADefinition())
     Writer.AddCXXDefinitionData(D, Record);
=20
   enum {
@@ -964,6 +974,23 @@
   Code =3D serialization::DECL_CXX_CONVERSION;
 }
=20
+void ASTDeclWriter::VisitImportDecl(ImportDecl *D) {
+  VisitDecl(D);
+  ArrayRef<SourceLocation> IdentifierLocs =3D D->getIdentifierLocs();
+  Record.push_back(!IdentifierLocs.empty());
+  if (IdentifierLocs.empty()) {
+    Writer.AddSourceLocation(D->getLocEnd(), Record);
+    Record.push_back(1);
+  } else {
+    for (unsigned I =3D 0, N =3D IdentifierLocs.size(); I !=3D N; ++I)
+      Writer.AddSourceLocation(IdentifierLocs[I], Record);
+    Record.push_back(IdentifierLocs.size());
+  }
+  // Note: the number of source locations must always be the last element =
in
+  // the record.
+  Code =3D serialization::DECL_IMPORT;
+}
+
 void ASTDeclWriter::VisitAccessSpecDecl(AccessSpecDecl *D) {
   VisitDecl(D);
   Writer.AddSourceLocation(D->getColonLoc(), Record);
@@ -1005,36 +1032,17 @@
 }
=20
 void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl=
 *D) {
+  VisitRedeclarable(D);
+
   // Emit data to initialize CommonOrPrev before VisitTemplateDecl so that
   // getCommonPtr() can be used while this is still initializing.
-
-  Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
-  if (D->getPreviousDeclaration())
-    Writer.AddDeclRef(D->getFirstDeclaration(), Record);
-
-  if (D->getPreviousDeclaration() =3D=3D 0) {
-    // This TemplateDecl owns the CommonPtr; write it.
-    assert(D->isCanonicalDecl());
-
+  if (D->isFirstDeclaration()) {
+    // This declaration owns the 'common' pointer, so serialize that data =
now.
     Writer.AddDeclRef(D->getInstantiatedFromMemberTemplate(), Record);
     if (D->getInstantiatedFromMemberTemplate())
       Record.push_back(D->isMemberSpecialization());
-
-    Writer.AddDeclRef(D->getCommonPtr()->Latest, Record);
-  } else {
-    RedeclarableTemplateDecl *First =3D D->getFirstDeclaration();
-    assert(First !=3D D);
-    // If this is a most recent redeclaration that is pointed to by a firs=
t decl
-    // in a chained PCH, keep track of the association with the map so we =
can
-    // update the first decl during AST reading.
-    if (First->getMostRecentDeclaration() =3D=3D D &&
-        First->isFromASTFile() && !D->isFromASTFile()) {
-      assert(Writer.FirstLatestDecls.find(First)=3D=3DWriter.FirstLatestDe=
cls.end()
-             && "The latest is already set");
-      Writer.FirstLatestDecls[First] =3D D;
-    }
   }
-
+ =20
   VisitTemplateDecl(D);
   Record.push_back(D->getIdentifierNamespace());
 }
@@ -1042,7 +1050,7 @@
 void ASTDeclWriter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
   VisitRedeclarableTemplateDecl(D);
=20
-  if (D->getPreviousDeclaration() =3D=3D 0) {
+  if (D->isFirstDeclaration()) {
     typedef llvm::FoldingSet<ClassTemplateSpecializationDecl> CTSDSetTy;
     CTSDSetTy &CTSDSet =3D D->getSpecializations();
     Record.push_back(CTSDSet.size());
@@ -1111,7 +1119,7 @@
   Record.push_back(D->getSequenceNumber());
=20
   // These are read/set from/to the first declaration.
-  if (D->getPreviousDeclaration() =3D=3D 0) {
+  if (D->getPreviousDecl() =3D=3D 0) {
     Writer.AddDeclRef(D->getInstantiatedFromMember(), Record);
     Record.push_back(D->isMemberSpecialization());
   }
@@ -1130,7 +1138,7 @@
 void ASTDeclWriter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
   VisitRedeclarableTemplateDecl(D);
=20
-  if (D->getPreviousDeclaration() =3D=3D 0) {
+  if (D->isFirstDeclaration()) {
     // This FunctionTemplateDecl owns the CommonPtr; write it.
=20
     // Write the function specialization declarations.
@@ -1230,31 +1238,23 @@
=20
 template <typename T>
 void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) {
-  enum { NoRedeclaration =3D 0, PointsToPrevious, PointsToLatest };
-  if (D->RedeclLink.getNext() =3D=3D D) {
-    Record.push_back(NoRedeclaration);
+  T *First =3D D->getFirstDeclaration();
+  if (First->getMostRecentDecl() !=3D First) {
+    // There is more than one declaration of this entity, so we will need =
to=20
+    // write a redeclaration chain.
+    Writer.AddDeclRef(First, Record);
+    Writer.Redeclarations.insert(First);
+
+    // Make sure that we serialize both the previous and the most-recent=20
+    // declarations, which (transitively) ensures that all declarations in=
 the
+    // chain get serialized.
+    (void)Writer.GetDeclRef(D->getPreviousDecl());
+    (void)Writer.GetDeclRef(First->getMostRecentDecl());
   } else {
-    if (D->RedeclLink.NextIsPrevious()) {
-      Record.push_back(PointsToPrevious);
-      Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
-      Writer.AddDeclRef(D->getFirstDeclaration(), Record);
-    } else {
-      Record.push_back(PointsToLatest);
-      Writer.AddDeclRef(D->RedeclLink.getPointer(), Record);
-    }
+    // We use the sentinel value 0 to indicate an only declaration.
+    Record.push_back(0);
   }
-
-  T *First =3D D->getFirstDeclaration();
-  T *ThisDecl =3D static_cast<T*>(D);
-  // If this is a most recent redeclaration that is pointed to by a first =
decl
-  // in a chained PCH, keep track of the association with the map so we can
-  // update the first decl during AST reading.
-  if (ThisDecl !=3D First && First->getMostRecentDeclaration() =3D=3D This=
Decl &&
-      First->isFromASTFile() && !ThisDecl->isFromASTFile()) {
-    assert(Writer.FirstLatestDecls.find(First) =3D=3D Writer.FirstLatestDe=
cls.end()
-           && "The latest is already set");
-    Writer.FirstLatestDecls[First] =3D ThisDecl;
-  }
+ =20
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1272,14 +1272,15 @@
   // Decl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
-  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
+  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
+  Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCCon=
tainer
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2));  // AccessSpecifier
   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind =3D Iden=
tifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
@@ -1303,14 +1304,15 @@
   // Decl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
-  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
+  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
+  Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCCon=
tainer
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2));  // AccessSpecifier
   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind =3D Iden=
tifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
@@ -1334,25 +1336,26 @@
   // Abbreviation for DECL_ENUM
   Abv =3D new BitCodeAbbrev();
   Abv->Add(BitCodeAbbrevOp(serialization::DECL_ENUM));
+  // Redeclarable
+  Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
   // Decl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
-  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
+  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
+  Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCCon=
tainer
   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifi=
er
   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind =3D Iden=
tifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
   // TypeDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
-  // Redeclarable
-  Abv->Add(BitCodeAbbrevOp(0));                         // No redeclaration
   // TagDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNames=
pace
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getTagKind
@@ -1380,25 +1383,26 @@
   // Abbreviation for DECL_RECORD
   Abv =3D new BitCodeAbbrev();
   Abv->Add(BitCodeAbbrevOp(serialization::DECL_RECORD));
+  // Redeclarable
+  Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
   // Decl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
-  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
+  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
+  Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCCon=
tainer
   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifi=
er
   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind =3D Iden=
tifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
   // TypeDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Source Location
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type Ref
-  // Redeclarable
-  Abv->Add(BitCodeAbbrevOp(0));                         // No redeclaration
   // TagDecl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // IdentifierNames=
pace
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // getTagKind
@@ -1420,17 +1424,20 @@
   // Abbreviation for DECL_PARM_VAR
   Abv =3D new BitCodeAbbrev();
   Abv->Add(BitCodeAbbrevOp(serialization::DECL_PARM_VAR));
+  // Redeclarable
+  Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
   // Decl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
-  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
+  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
+  Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCCon=
tainer
   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifi=
er
   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind =3D Iden=
tifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
@@ -1440,7 +1447,6 @@
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
   // VarDecl
-  Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
   Abv->Add(BitCodeAbbrevOp(0));                       // StorageClass
   Abv->Add(BitCodeAbbrevOp(0));                       // StorageClassAsWri=
tten
   Abv->Add(BitCodeAbbrevOp(0));                       // isThreadSpecified
@@ -1468,17 +1474,20 @@
   // Abbreviation for DECL_TYPEDEF
   Abv =3D new BitCodeAbbrev();
   Abv->Add(BitCodeAbbrevOp(serialization::DECL_TYPEDEF));
+  // Redeclarable
+  Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
   // Decl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
-  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
+  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
+  Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCCon=
tainer
   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifi=
er
   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind =3D Iden=
tifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
@@ -1493,17 +1502,20 @@
   // Abbreviation for DECL_VAR
   Abv =3D new BitCodeAbbrev();
   Abv->Add(BitCodeAbbrevOp(serialization::DECL_VAR));
+  // Redeclarable
+  Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
   // Decl
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
-  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
-  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
+  Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
+  Abv->Add(BitCodeAbbrevOp(0));                   // TopLevelDeclInObjCCon=
tainer
   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifi=
er
   Abv->Add(BitCodeAbbrevOp(0));                       // ModulePrivate
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // SubmoduleID
   // NamedDecl
   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind =3D Iden=
tifier
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
@@ -1513,7 +1525,6 @@
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
   // VarDecl
-  Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // StorageClass
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // StorageClassAsWri=
tten
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isThreadSpecifi=
ed
@@ -1547,6 +1558,7 @@
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //GetDeclFound
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //ExplicitTemplate=
Args
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //HadMultipleCandi=
dates
+  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); //RefersToEnclosin=
gLocal
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclRef
   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
   DeclRefExprAbbrev =3D Stream.EmitAbbrev(Abv);
@@ -1629,6 +1641,20 @@
   RecordData Record;
   ASTDeclWriter W(*this, Context, Record);
=20
+  // Determine the ID for this declaration.
+  serialization::DeclID ID;
+  if (D->isFromASTFile())
+    ID =3D getDeclID(D);
+  else {
+    serialization::DeclID &IDR =3D DeclIDs[D];
+    if (IDR =3D=3D 0)
+      IDR =3D NextDeclID++;
+   =20
+    ID=3D IDR;
+  }
+
+  bool isReplacingADecl =3D ID < FirstDeclID;
+
   // If this declaration is also a DeclContext, write blocks for the
   // declarations that lexically stored inside its context and those
   // declarations that are visible from its context. These blocks
@@ -1638,29 +1664,38 @@
   uint64_t VisibleOffset =3D 0;
   DeclContext *DC =3D dyn_cast<DeclContext>(D);
   if (DC) {
+    if (isReplacingADecl) {
+      // It is replacing a decl from a chained PCH; make sure that the
+      // DeclContext is fully loaded.
+      if (DC->hasExternalLexicalStorage())
+        DC->LoadLexicalDeclsFromExternalStorage();
+      if (DC->hasExternalVisibleStorage())
+        Chain->completeVisibleDeclsMap(DC);
+    }
     LexicalOffset =3D WriteDeclContextLexicalBlock(Context, DC);
     VisibleOffset =3D WriteDeclContextVisibleBlock(Context, DC);
   }
-
-  // Determine the ID for this declaration
-  serialization::DeclID &IDR =3D DeclIDs[D];
-  if (IDR =3D=3D 0)
-    IDR =3D NextDeclID++;
-  serialization::DeclID ID =3D IDR;
-
-  if (ID < FirstDeclID) {
+ =20
+  if (isReplacingADecl) {
     // We're replacing a decl in a previous file.
-    ReplacedDecls.push_back(std::make_pair(ID, Stream.GetCurrentBitNo()));
+    ReplacedDecls.push_back(ReplacedDeclInfo(ID, Stream.GetCurrentBitNo(),
+                                             D->getLocation()));
   } else {
     unsigned Index =3D ID - FirstDeclID;
=20
     // Record the offset for this declaration
+    SourceLocation Loc =3D D->getLocation();
     if (DeclOffsets.size() =3D=3D Index)
-      DeclOffsets.push_back(Stream.GetCurrentBitNo());
+      DeclOffsets.push_back(DeclOffset(Loc, Stream.GetCurrentBitNo()));
     else if (DeclOffsets.size() < Index) {
       DeclOffsets.resize(Index+1);
-      DeclOffsets[Index] =3D Stream.GetCurrentBitNo();
+      DeclOffsets[Index].setLocation(Loc);
+      DeclOffsets[Index].BitOffset =3D Stream.GetCurrentBitNo();
     }
+   =20
+    SourceManager &SM =3D Context.getSourceManager();
+    if (Loc.isValid() && SM.isLocalSourceLocation(Loc))
+      associateDeclWithFile(D, ID);
   }
=20
   // Build and emit a record for this declaration
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ASTWriterStmt.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ASTWriterStmt.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ASTWriterStmt.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -34,9 +34,8 @@
=20
     ASTStmtWriter(ASTWriter &Writer, ASTWriter::RecordData &Record)
       : Writer(Writer), Record(Record) { }
-   =20
-    void
-    AddExplicitTemplateArgumentList(const ASTTemplateArgumentListInfo &Arg=
s);
+
+    void AddTemplateKWAndArgsInfo(const ASTTemplateKWAndArgsInfo &Args);
=20
     void VisitStmt(Stmt *S);
 #define STMT(Type, Base) \
@@ -46,7 +45,8 @@
 }
=20
 void ASTStmtWriter::
-AddExplicitTemplateArgumentList(const ASTTemplateArgumentListInfo &Args) {
+AddTemplateKWAndArgsInfo(const ASTTemplateKWAndArgsInfo &Args) {
+  Writer.AddSourceLocation(Args.getTemplateKeywordLoc(), Record);
   Writer.AddSourceLocation(Args.LAngleLoc, Record);
   Writer.AddSourceLocation(Args.RAngleLoc, Record);
   for (unsigned i=3D0; i !=3D Args.NumTemplateArgs; ++i)
@@ -264,17 +264,18 @@
=20
   Record.push_back(E->hasQualifier());
   Record.push_back(E->getDecl() !=3D E->getFoundDecl());
-  Record.push_back(E->hasExplicitTemplateArgs());
+  Record.push_back(E->hasTemplateKWAndArgsInfo());
   Record.push_back(E->hadMultipleCandidates());
+  Record.push_back(E->refersToEnclosingLocal());
=20
-  if (E->hasExplicitTemplateArgs()) {
+  if (E->hasTemplateKWAndArgsInfo()) {
     unsigned NumTemplateArgs =3D E->getNumTemplateArgs();
     Record.push_back(NumTemplateArgs);
   }
=20
   DeclarationName::NameKind nk =3D (E->getDecl()->getDeclName().getNameKin=
d());
=20
-  if ((!E->hasExplicitTemplateArgs()) && (!E->hasQualifier()) &&
+  if ((!E->hasTemplateKWAndArgsInfo()) && (!E->hasQualifier()) &&
       (E->getDecl() =3D=3D E->getFoundDecl()) &&
       nk =3D=3D DeclarationName::Identifier) {
     AbbrevToUse =3D Writer.getDeclRefExprAbbrev();
@@ -286,8 +287,8 @@
   if (E->getDecl() !=3D E->getFoundDecl())
     Writer.AddDeclRef(E->getFoundDecl(), Record);
=20
-  if (E->hasExplicitTemplateArgs())
-    AddExplicitTemplateArgumentList(E->getExplicitTemplateArgs());
+  if (E->hasTemplateKWAndArgsInfo())
+    AddTemplateKWAndArgsInfo(*E->getTemplateKWAndArgsInfo());
=20
   Writer.AddDeclRef(E->getDecl(), Record);
   Writer.AddSourceLocation(E->getLocation(), Record);
@@ -331,7 +332,7 @@
   // StringLiteral. However, we can't do so now because we have no
   // provision for coping with abbreviations when we're jumping around
   // the AST file during deserialization.
-  Record.append(E->getString().begin(), E->getString().end());
+  Record.append(E->getBytes().begin(), E->getBytes().end());
   for (unsigned I =3D 0, N =3D E->getNumConcatenated(); I !=3D N; ++I)
     Writer.AddSourceLocation(E->getStrTokenLoc(I), Record);
   Code =3D serialization::EXPR_STRING_LITERAL;
@@ -449,8 +450,9 @@
   if (E->hasQualifier())
     Writer.AddNestedNameSpecifierLoc(E->getQualifierLoc(), Record);
=20
-  Record.push_back(E->hasExplicitTemplateArgs());
-  if (E->hasExplicitTemplateArgs()) {
+  Record.push_back(E->HasTemplateKWAndArgsInfo);
+  if (E->HasTemplateKWAndArgsInfo) {
+    Writer.AddSourceLocation(E->getTemplateKeywordLoc(), Record);
     unsigned NumTemplateArgs =3D E->getNumTemplateArgs();
     Record.push_back(NumTemplateArgs);
     Writer.AddSourceLocation(E->getLAngleLoc(), Record);
@@ -597,6 +599,7 @@
   else
     Writer.AddDeclRef(E->getInitializedFieldInUnion(), Record);
   Record.push_back(E->hadArrayRangeDesignator());
+  Record.push_back(E->initializesStdInitializerList());
   Record.push_back(E->getNumInits());
   if (isArrayFiller) {
     // ArrayFiller may have filled "holes" due to designated initializer.
@@ -710,15 +713,6 @@
   Code =3D serialization::EXPR_BLOCK;
 }
=20
-void ASTStmtWriter::VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
-  VisitExpr(E);
-  Writer.AddDeclRef(E->getDecl(), Record);
-  Writer.AddSourceLocation(E->getLocation(), Record);
-  Record.push_back(E->isByRef());
-  Record.push_back(E->isConstQualAdded());
-  Code =3D serialization::EXPR_BLOCK_DECL_REF;
-}
-
 void ASTStmtWriter::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
   VisitExpr(E);
   Record.push_back(E->getNumAssocs());
@@ -736,19 +730,32 @@
   Code =3D serialization::EXPR_GENERIC_SELECTION;
 }
=20
+void ASTStmtWriter::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
+  VisitExpr(E);
+  Record.push_back(E->getNumSemanticExprs());
+
+  // Push the result index.  Currently, this needs to exactly match
+  // the encoding used internally for ResultIndex.
+  unsigned result =3D E->getResultExprIndex();
+  result =3D (result =3D=3D PseudoObjectExpr::NoResult ? 0 : result + 1);
+  Record.push_back(result);
+
+  Writer.AddStmt(E->getSyntacticForm());
+  for (PseudoObjectExpr::semantics_iterator
+         i =3D E->semantics_begin(), e =3D E->semantics_end(); i !=3D e; +=
+i) {
+    Writer.AddStmt(*i);
+  }
+  Code =3D serialization::EXPR_PSEUDO_OBJECT;
+}
+
 void ASTStmtWriter::VisitAtomicExpr(AtomicExpr *E) {
   VisitExpr(E);
   Record.push_back(E->getOp());
-  Writer.AddStmt(E->getPtr());
-  Writer.AddStmt(E->getOrder());
-  if (E->getOp() !=3D AtomicExpr::Load)
-    Writer.AddStmt(E->getVal1());
-  if (E->isCmpXChg()) {
-    Writer.AddStmt(E->getOrderFail());
-    Writer.AddStmt(E->getVal2());
-  }
+  for (unsigned I =3D 0, N =3D E->getNumSubExprs(); I !=3D N; ++I)
+    Writer.AddStmt(E->getSubExprs()[I]);
   Writer.AddSourceLocation(E->getBuiltinLoc(), Record);
   Writer.AddSourceLocation(E->getRParenLoc(), Record);
+  Code =3D serialization::EXPR_ATOMIC;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -762,6 +769,46 @@
   Code =3D serialization::EXPR_OBJC_STRING_LITERAL;
 }
=20
+void ASTStmtWriter::VisitObjCNumericLiteral(ObjCNumericLiteral *E) {
+  VisitExpr(E);
+  Writer.AddStmt(E->getNumber());
+  Writer.AddDeclRef(E->getObjCNumericLiteralMethod(), Record);
+  Writer.AddSourceLocation(E->getAtLoc(), Record);
+  Code =3D serialization::EXPR_OBJC_NUMERIC_LITERAL;
+}
+
+void ASTStmtWriter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
+  VisitExpr(E);
+  Record.push_back(E->getNumElements());
+  for (unsigned i =3D 0; i < E->getNumElements(); i++)
+    Writer.AddStmt(E->getElement(i));
+  Writer.AddDeclRef(E->getArrayWithObjectsMethod(), Record);
+  Writer.AddSourceRange(E->getSourceRange(), Record);
+  Code =3D serialization::EXPR_OBJC_ARRAY_LITERAL;
+}
+
+void ASTStmtWriter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
+  VisitExpr(E);
+  Record.push_back(E->getNumElements());
+  Record.push_back(E->HasPackExpansions);
+  for (unsigned i =3D 0; i < E->getNumElements(); i++) {
+    ObjCDictionaryElement Element =3D E->getKeyValueElement(i);
+    Writer.AddStmt(Element.Key);
+    Writer.AddStmt(Element.Value);
+    if (E->HasPackExpansions) {
+      Writer.AddSourceLocation(Element.EllipsisLoc, Record);
+      unsigned NumExpansions =3D 0;
+      if (Element.NumExpansions)
+        NumExpansions =3D *Element.NumExpansions + 1;
+      Record.push_back(NumExpansions);
+    }
+  }
+   =20
+  Writer.AddDeclRef(E->getDictWithObjectsMethod(), Record);
+  Writer.AddSourceRange(E->getSourceRange(), Record);
+  Code =3D serialization::EXPR_OBJC_DICTIONARY_LITERAL;
+}
+
 void ASTStmtWriter::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
   VisitExpr(E);
   Writer.AddTypeSourceInfo(E->getEncodedTypeSourceInfo(), Record);
@@ -798,6 +845,7 @@
=20
 void ASTStmtWriter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
   VisitExpr(E);
+  Record.push_back(E->SetterAndMethodRefFlags.getInt());
   Record.push_back(E->isImplicitProperty());
   if (E->isImplicitProperty()) {
     Writer.AddDeclRef(E->getImplicitPropertyGetter(), Record);
@@ -821,12 +869,24 @@
   Code =3D serialization::EXPR_OBJC_PROPERTY_REF_EXPR;
 }
=20
+void ASTStmtWriter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
+  VisitExpr(E);
+  Writer.AddSourceLocation(E->getRBracket(), Record);
+  Writer.AddStmt(E->getBaseExpr());
+  Writer.AddStmt(E->getKeyExpr());
+  Writer.AddDeclRef(E->getAtIndexMethodDecl(), Record);
+  Writer.AddDeclRef(E->setAtIndexMethodDecl(), Record);
+ =20
+  Code =3D serialization::EXPR_OBJC_SUBSCRIPT_REF_EXPR;
+}
+
 void ASTStmtWriter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
   VisitExpr(E);
   Record.push_back(E->getNumArgs());
   Record.push_back(E->getNumStoredSelLocs());
   Record.push_back(E->SelLocsKind);
   Record.push_back(E->isDelegateInitCall());
+  Record.push_back(E->IsImplicit);
   Record.push_back((unsigned)E->getReceiverKind()); // FIXME: stable encod=
ing
   switch (E->getReceiverKind()) {
   case ObjCMessageExpr::Instance:
@@ -921,6 +981,13 @@
   Code =3D serialization::STMT_OBJC_AT_THROW;
 }
=20
+void ASTStmtWriter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
+  VisitExpr(E);
+  Record.push_back(E->getValue());
+  Writer.AddSourceLocation(E->getLocation(), Record);
+  Code =3D serialization::EXPR_OBJC_BOOL_LITERAL;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // C++ Expressions and Statements.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -957,6 +1024,16 @@
   Code =3D serialization::STMT_CXX_FOR_RANGE;
 }
=20
+void ASTStmtWriter::VisitMSDependentExistsStmt(MSDependentExistsStmt *S) {
+  VisitStmt(S);
+  Writer.AddSourceLocation(S->getKeywordLoc(), Record);
+  Record.push_back(S->isIfExists());
+  Writer.AddNestedNameSpecifierLoc(S->getQualifierLoc(), Record);
+  Writer.AddDeclarationNameInfo(S->getNameInfo(), Record);
+  Writer.AddStmt(S->getSubStmt());
+  Code =3D serialization::STMT_MS_DEPENDENT_EXISTS;
+}
+
 void ASTStmtWriter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   VisitCallExpr(E);
   Record.push_back(E->getOperator());
@@ -989,6 +1066,38 @@
   Code =3D serialization::EXPR_CXX_TEMPORARY_OBJECT;
 }
=20
+void ASTStmtWriter::VisitLambdaExpr(LambdaExpr *E) {
+  VisitExpr(E);
+  Record.push_back(E->NumCaptures);
+  unsigned NumArrayIndexVars =3D 0;
+  if (E->HasArrayIndexVars)
+    NumArrayIndexVars =3D E->getArrayIndexStarts()[E->NumCaptures];
+  Record.push_back(NumArrayIndexVars);
+  Writer.AddSourceRange(E->IntroducerRange, Record);
+  Record.push_back(E->CaptureDefault); // FIXME: stable encoding
+  Record.push_back(E->ExplicitParams);
+  Record.push_back(E->ExplicitResultType);
+  Writer.AddSourceLocation(E->ClosingBrace, Record);
+ =20
+  // Add capture initializers.
+  for (LambdaExpr::capture_init_iterator C =3D E->capture_init_begin(),
+                                      CEnd =3D E->capture_init_end();
+       C !=3D CEnd; ++C) {
+    Writer.AddStmt(*C);
+  }
+ =20
+  // Add array index variables, if any.
+  if (NumArrayIndexVars) {
+    Record.append(E->getArrayIndexStarts(),=20
+                  E->getArrayIndexStarts() + E->NumCaptures + 1);
+    VarDecl **ArrayIndexVars =3D E->getArrayIndexVars();
+    for (unsigned I =3D 0; I !=3D NumArrayIndexVars; ++I)
+      Writer.AddDeclRef(ArrayIndexVars[I], Record);
+  }
+ =20
+  Code =3D serialization::EXPR_LAMBDA;
+}
+
 void ASTStmtWriter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
   VisitExplicitCastExpr(E);
   Writer.AddSourceRange(SourceRange(E->getOperatorLoc(), E->getRParenLoc()=
),
@@ -1022,6 +1131,12 @@
   Code =3D serialization::EXPR_CXX_FUNCTIONAL_CAST;
 }
=20
+void ASTStmtWriter::VisitUserDefinedLiteral(UserDefinedLiteral *E) {
+  VisitCallExpr(E);
+  Writer.AddSourceLocation(E->UDSuffixLoc, Record);
+  Code =3D serialization::EXPR_USER_DEFINED_LITERAL;
+}
+
 void ASTStmtWriter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
   VisitExpr(E);
   Record.push_back(E->getValue());
@@ -1093,25 +1208,20 @@
 void ASTStmtWriter::VisitCXXNewExpr(CXXNewExpr *E) {
   VisitExpr(E);
   Record.push_back(E->isGlobalNew());
-  Record.push_back(E->hasInitializer());
+  Record.push_back(E->isArray());
   Record.push_back(E->doesUsualArrayDeleteWantSize());
-  Record.push_back(E->isArray());
-  Record.push_back(E->hadMultipleCandidates());
   Record.push_back(E->getNumPlacementArgs());
-  Record.push_back(E->getNumConstructorArgs());
+  Record.push_back(E->StoredInitializationStyle);
   Writer.AddDeclRef(E->getOperatorNew(), Record);
   Writer.AddDeclRef(E->getOperatorDelete(), Record);
-  Writer.AddDeclRef(E->getConstructor(), Record);
   Writer.AddTypeSourceInfo(E->getAllocatedTypeSourceInfo(), Record);
   Writer.AddSourceRange(E->getTypeIdParens(), Record);
   Writer.AddSourceLocation(E->getStartLoc(), Record);
-  Writer.AddSourceLocation(E->getEndLoc(), Record);
-  Writer.AddSourceLocation(E->getConstructorLParen(), Record);
-  Writer.AddSourceLocation(E->getConstructorRParen(), Record);
+  Writer.AddSourceRange(E->getDirectInitRange(), Record);
   for (CXXNewExpr::arg_iterator I =3D E->raw_arg_begin(), e =3D E->raw_arg=
_end();
        I !=3D e; ++I)
     Writer.AddStmt(*I);
- =20
+
   Code =3D serialization::EXPR_CXX_NEW;
 }
=20
@@ -1151,9 +1261,9 @@
=20
 void ASTStmtWriter::VisitExprWithCleanups(ExprWithCleanups *E) {
   VisitExpr(E);
-  Record.push_back(E->getNumTemporaries());
-  for (unsigned i =3D 0, e =3D E->getNumTemporaries(); i !=3D e; ++i)
-    Writer.AddCXXTemporary(E->getTemporary(i), Record);
+  Record.push_back(E->getNumObjects());
+  for (unsigned i =3D 0, e =3D E->getNumObjects(); i !=3D e; ++i)
+    Writer.AddDeclRef(E->getObject(i), Record);
  =20
   Writer.AddStmt(E->getSubExpr());
   Code =3D serialization::EXPR_EXPR_WITH_CLEANUPS;
@@ -1162,17 +1272,17 @@
 void
 ASTStmtWriter::VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExp=
r *E){
   VisitExpr(E);
- =20
-  // Don't emit anything here, hasExplicitTemplateArgs() must be
+
+  // Don't emit anything here, HasTemplateKWAndArgsInfo must be
   // emitted first.
=20
-  Record.push_back(E->hasExplicitTemplateArgs());
-  if (E->hasExplicitTemplateArgs()) {
-    const ASTTemplateArgumentListInfo &Args =3D E->getExplicitTemplateArgs=
();
+  Record.push_back(E->HasTemplateKWAndArgsInfo);
+  if (E->HasTemplateKWAndArgsInfo) {
+    const ASTTemplateKWAndArgsInfo &Args =3D *E->getTemplateKWAndArgsInfo(=
);
     Record.push_back(Args.NumTemplateArgs);
-    AddExplicitTemplateArgumentList(Args);
+    AddTemplateKWAndArgsInfo(Args);
   }
- =20
+
   if (!E->isImplicitAccess())
     Writer.AddStmt(E->getBase());
   else
@@ -1189,14 +1299,15 @@
 void
 ASTStmtWriter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E=
) {
   VisitExpr(E);
- =20
-  // Don't emit anything here, hasExplicitTemplateArgs() must be
+
+  // Don't emit anything here, HasTemplateKWAndArgsInfo must be
   // emitted first.
-  Record.push_back(E->hasExplicitTemplateArgs());
-  if (E->hasExplicitTemplateArgs()) {
-    const ASTTemplateArgumentListInfo &Args =3D E->getExplicitTemplateArgs=
();
+
+  Record.push_back(E->HasTemplateKWAndArgsInfo);
+  if (E->HasTemplateKWAndArgsInfo) {
+    const ASTTemplateKWAndArgsInfo &Args =3D *E->getTemplateKWAndArgsInfo(=
);
     Record.push_back(Args.NumTemplateArgs);
-    AddExplicitTemplateArgumentList(Args);
+    AddTemplateKWAndArgsInfo(Args);
   }
=20
   Writer.AddNestedNameSpecifierLoc(E->getQualifierLoc(), Record);
@@ -1219,13 +1330,15 @@
=20
 void ASTStmtWriter::VisitOverloadExpr(OverloadExpr *E) {
   VisitExpr(E);
- =20
-  // Don't emit anything here, hasExplicitTemplateArgs() must be emitted f=
irst.
-  Record.push_back(E->hasExplicitTemplateArgs());
-  if (E->hasExplicitTemplateArgs()) {
-    const ASTTemplateArgumentListInfo &Args =3D E->getExplicitTemplateArgs=
();
+
+  // Don't emit anything here, HasTemplateKWAndArgsInfo must be
+  // emitted first.
+
+  Record.push_back(E->HasTemplateKWAndArgsInfo);
+  if (E->HasTemplateKWAndArgsInfo) {
+    const ASTTemplateKWAndArgsInfo &Args =3D *E->getTemplateKWAndArgsInfo(=
);
     Record.push_back(Args.NumTemplateArgs);
-    AddExplicitTemplateArgumentList(Args);
+    AddTemplateKWAndArgsInfo(Args);
   }
=20
   Record.push_back(E->getNumDecls());
@@ -1278,6 +1391,16 @@
   Code =3D serialization::EXPR_BINARY_TYPE_TRAIT;
 }
=20
+void ASTStmtWriter::VisitTypeTraitExpr(TypeTraitExpr *E) {
+  VisitExpr(E);
+  Record.push_back(E->TypeTraitExprBits.NumArgs);
+  Record.push_back(E->TypeTraitExprBits.Kind); // FIXME: Stable encoding
+  Record.push_back(E->TypeTraitExprBits.Value);
+  for (unsigned I =3D 0, N =3D E->getNumArgs(); I !=3D N; ++I)
+    Writer.AddTypeSourceInfo(E->getArg(I), Record);
+  Code =3D serialization::EXPR_TYPE_TRAIT;
+}
+
 void ASTStmtWriter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
   VisitExpr(E);
   Record.push_back(E->getTrait());
@@ -1348,7 +1471,7 @@
=20
 void ASTStmtWriter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
   VisitExpr(E);
-  Record.push_back(Writer.getOpaqueValueID(E));
+  Writer.AddStmt(E->getSourceExpr());
   Writer.AddSourceLocation(E->getLocation(), Record);
   Code =3D serialization::EXPR_OPAQUE_VALUE;
 }
@@ -1435,15 +1558,11 @@
   SwitchCaseIDs.clear();
 }
=20
-unsigned ASTWriter::getOpaqueValueID(OpaqueValueExpr *e) {
-  unsigned &entry =3D OpaqueValues[e];
-  if (!entry) entry =3D OpaqueValues.size();
-  return entry;
-}
-
 /// \brief Write the given substatement or subexpression to the
 /// bitstream.
-void ASTWriter::WriteSubStmt(Stmt *S) {
+void ASTWriter::WriteSubStmt(Stmt *S,
+                             llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntr=
ies,
+                             llvm::DenseSet<Stmt *> &ParentStmts) {
   RecordData Record;
   ASTStmtWriter Writer(*this, Record);
   ++NumStatements;
@@ -1453,6 +1572,32 @@
     return;
   }
=20
+  llvm::DenseMap<Stmt *, uint64_t>::iterator I =3D SubStmtEntries.find(S);
+  if (I !=3D SubStmtEntries.end()) {
+    Record.push_back(I->second);
+    Stream.EmitRecord(serialization::STMT_REF_PTR, Record);
+    return;
+  }
+
+#ifndef NDEBUG
+  assert(!ParentStmts.count(S) && "There is a Stmt cycle!");
+
+  struct ParentStmtInserterRAII {
+    Stmt *S;
+    llvm::DenseSet<Stmt *> &ParentStmts;
+
+    ParentStmtInserterRAII(Stmt *S, llvm::DenseSet<Stmt *> &ParentStmts)
+      : S(S), ParentStmts(ParentStmts) {
+      ParentStmts.insert(S);
+    }
+    ~ParentStmtInserterRAII() {
+      ParentStmts.erase(S);
+    }
+  };
+
+  ParentStmtInserterRAII ParentStmtInserter(S, ParentStmts);
+#endif
+
   // Redirect ASTWriter::AddStmt to collect sub stmts.
   SmallVector<Stmt *, 16> SubStmts;
   CollectedStmts =3D &SubStmts;
@@ -1478,9 +1623,11 @@
   // This simplifies reading and allows to store a variable number of sub =
stmts
   // without knowing it in advance.
   while (!SubStmts.empty())
-    WriteSubStmt(SubStmts.pop_back_val());
+    WriteSubStmt(SubStmts.pop_back_val(), SubStmtEntries, ParentStmts);
  =20
   Stream.EmitRecord(Writer.Code, Record, Writer.AbbrevToUse);
+=20
+  SubStmtEntries[S] =3D Stream.GetCurrentBitNo();
 }
=20
 /// \brief Flush all of the statements that have been added to the
@@ -1488,8 +1635,13 @@
 void ASTWriter::FlushStmts() {
   RecordData Record;
=20
+  // We expect to be the only consumer of the two temporary statement maps,
+  // assert that they are empty.
+  assert(SubStmtEntries.empty() && "unexpected entries in sub stmt map");
+  assert(ParentStmts.empty() && "unexpected entries in parent stmt map");
+
   for (unsigned I =3D 0, N =3D StmtsToEmit.size(); I !=3D N; ++I) {
-    WriteSubStmt(StmtsToEmit[I]);
+    WriteSubStmt(StmtsToEmit[I], SubStmtEntries, ParentStmts);
    =20
     assert(N =3D=3D StmtsToEmit.size() &&
            "Substatement written via AddStmt rather than WriteSubStmt!");
@@ -1498,6 +1650,9 @@
     // expression records that follow this one are part of a different
     // expression.
     Stream.EmitRecord(serialization::STMT_STOP, Record);
+
+    SubStmtEntries.clear();
+    ParentStmts.clear();
   }
=20
   StmtsToEmit.clear();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/GeneratePCH.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/GeneratePCH.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/GeneratePCH.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-//=3D=3D=3D--- GeneratePCH.cpp - AST Consumer for PCH Generation ------*- =
C++ -*-=3D=3D=3D//
+//=3D=3D=3D--- GeneratePCH.cpp - Sema Consumer for PCH Generation -----*- =
C++ -*-=3D=3D=3D//
 //
 //                     The LLVM Compiler Infrastructure
 //
@@ -7,12 +7,11 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //
-//  This file defines the CreatePCHGenerate function, which creates an
-//  ASTConsumer that generates a PCH file.
+//  This file defines the PCHGenerator, which as a SemaConsumer that gener=
ates
+//  a PCH file.
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-#include "clang/Frontend/ASTConsumers.h"
 #include "clang/Serialization/ASTWriter.h"
 #include "clang/Sema/SemaConsumer.h"
 #include "clang/AST/ASTContext.h"
@@ -28,10 +27,10 @@
=20
 PCHGenerator::PCHGenerator(const Preprocessor &PP,
                            StringRef OutputFile,
-                           bool IsModule,
+                           clang::Module *Module,
                            StringRef isysroot,
                            raw_ostream *OS)
-  : PP(PP), OutputFile(OutputFile), IsModule(IsModule),=20
+  : PP(PP), OutputFile(OutputFile), Module(Module),=20
     isysroot(isysroot.str()), Out(OS),=20
     SemaPtr(0), StatCalls(0), Stream(Buffer), Writer(Stream) {
   // Install a stat() listener to keep track of all of the stat()
@@ -49,7 +48,7 @@
  =20
   // Emit the PCH file
   assert(SemaPtr && "No Sema?");
-  Writer.WriteAST(*SemaPtr, StatCalls, OutputFile, IsModule, isysroot);
+  Writer.WriteAST(*SemaPtr, StatCalls, OutputFile, Module, isysroot);
=20
   // Write the generated bitstream to "Out".
   Out->write((char *)&Buffer.front(), Buffer.size());
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/Module.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/Module.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/Module.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -20,8 +20,8 @@
 using namespace serialization;
 using namespace reader;
=20
-Module::Module(ModuleKind Kind)
-  : Kind(Kind), DirectlyImported(false), SizeInBits(0),=20
+ModuleFile::ModuleFile(ModuleKind Kind, unsigned Generation)
+  : Kind(Kind), DirectlyImported(false), Generation(Generation), SizeInBit=
s(0),=20
     LocalNumSLocEntries(0), SLocEntryBaseID(0),
     SLocEntryBaseOffset(0), SLocEntryOffsets(0),
     SLocFileOffsets(0), LocalNumIdentifiers(0),=20
@@ -30,15 +30,17 @@
     PreprocessedEntityOffsets(0), NumPreprocessedEntities(0),
     LocalNumHeaderFileInfos(0),=20
     HeaderFileInfoTableData(0), HeaderFileInfoTable(0),
-    HeaderFileFrameworkStrings(0),
+    HeaderFileFrameworkStrings(0), LocalNumSubmodules(0), BaseSubmoduleID(=
0),
     LocalNumSelectors(0), SelectorOffsets(0), BaseSelectorID(0),
     SelectorLookupTableData(0), SelectorLookupTable(0), LocalNumDecls(0),
     DeclOffsets(0), BaseDeclID(0),
     LocalNumCXXBaseSpecifiers(0), CXXBaseSpecifiersOffsets(0),
+    FileSortedDecls(0), RedeclarationsMap(0), LocalNumRedeclarationsInMap(=
0),
+    ObjCCategoriesMap(0), LocalNumObjCCategoriesInMap(0),
     LocalNumTypes(0), TypeOffsets(0), BaseTypeIndex(0), StatCache(0)
 {}
=20
-Module::~Module() {
+ModuleFile::~ModuleFile() {
   for (DeclContextInfosMap::iterator I =3D DeclContextInfos.begin(),
        E =3D DeclContextInfos.end();
        I !=3D E; ++I) {
@@ -67,7 +69,7 @@
   }
 }
=20
-void Module::dump() {
+void ModuleFile::dump() {
   llvm::errs() << "\nModule: " << FileName << "\n";
   if (!Imports.empty()) {
     llvm::errs() << "  Imports: ";
@@ -87,7 +89,11 @@
   llvm::errs() << "  Base identifier ID: " << BaseIdentifierID << '\n'
                << "  Number of identifiers: " << LocalNumIdentifiers << '\=
n';
   dumpLocalRemap("Identifier ID local -> global map", IdentifierRemap);
- =20
+
+  llvm::errs() << "  Base submodule ID: " << BaseSubmoduleID << '\n'
+               << "  Number of submodules: " << LocalNumSubmodules << '\n';
+  dumpLocalRemap("Submodule ID local -> global map", SubmoduleRemap);
+
   llvm::errs() << "  Base selector ID: " << BaseSelectorID << '\n'
                << "  Number of selectors: " << LocalNumSelectors << '\n';
   dumpLocalRemap("Selector ID local -> global map", SelectorRemap);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Seri=
alization/ModuleManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/Serialization/ModuleManager.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/Serialization/ModuleManager.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 using namespace clang;
 using namespace serialization;
=20
-Module *ModuleManager::lookup(StringRef Name) {
+ModuleFile *ModuleManager::lookup(StringRef Name) {
   const FileEntry *Entry =3D FileMgr.getFile(Name);
   return Modules[Entry];
 }
@@ -33,21 +33,22 @@
   return InMemoryBuffers[Entry];
 }
=20
-std::pair<Module *, bool>
+std::pair<ModuleFile *, bool>
 ModuleManager::addModule(StringRef FileName, ModuleKind Type,=20
-                         Module *ImportedBy, std::string &ErrorStr) {
+                         ModuleFile *ImportedBy, unsigned Generation,
+                         std::string &ErrorStr) {
   const FileEntry *Entry =3D FileMgr.getFile(FileName);
   if (!Entry && FileName !=3D "-") {
     ErrorStr =3D "file not found";
-    return std::make_pair(static_cast<Module*>(0), false);
+    return std::make_pair(static_cast<ModuleFile*>(0), false);
   }
  =20
   // Check whether we already loaded this module, before=20
-  Module *&ModuleEntry =3D Modules[Entry];
+  ModuleFile *&ModuleEntry =3D Modules[Entry];
   bool NewModule =3D false;
   if (!ModuleEntry) {
     // Allocate a new module.
-    Module *New =3D new Module(Type);
+    ModuleFile *New =3D new ModuleFile(Type, Generation);
     New->FileName =3D FileName.str();
     Chain.push_back(New);
     NewModule =3D true;
@@ -69,7 +70,7 @@
         New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
      =20
       if (!New->Buffer)
-        return std::make_pair(static_cast<Module*>(0), false);
+        return std::make_pair(static_cast<ModuleFile*>(0), false);
     }
    =20
     // Initialize the stream
@@ -101,16 +102,16 @@
     delete Chain[e - i - 1];
 }
=20
-void ModuleManager::visit(bool (*Visitor)(Module &M, void *UserData),=20
+void ModuleManager::visit(bool (*Visitor)(ModuleFile &M, void *UserData),=20
                           void *UserData) {
   unsigned N =3D size();
  =20
   // Record the number of incoming edges for each module. When we
   // encounter a module with no incoming edges, push it into the queue
   // to seed the queue.
-  SmallVector<Module *, 4> Queue;
+  SmallVector<ModuleFile *, 4> Queue;
   Queue.reserve(N);
-  llvm::DenseMap<Module *, unsigned> UnusedIncomingEdges;=20
+  llvm::DenseMap<ModuleFile *, unsigned> UnusedIncomingEdges;=20
   for (ModuleIterator M =3D begin(), MEnd =3D end(); M !=3D MEnd; ++M) {
     if (unsigned Size =3D (*M)->ImportedBy.size())
       UnusedIncomingEdges[*M] =3D Size;
@@ -118,10 +119,10 @@
       Queue.push_back(*M);
   }
  =20
-  llvm::SmallPtrSet<Module *, 4> Skipped;
+  llvm::SmallPtrSet<ModuleFile *, 4> Skipped;
   unsigned QueueStart =3D 0;
   while (QueueStart < Queue.size()) {
-    Module *CurrentModule =3D Queue[QueueStart++];
+    ModuleFile *CurrentModule =3D Queue[QueueStart++];
    =20
     // Check whether this module should be skipped.
     if (Skipped.count(CurrentModule))
@@ -132,16 +133,16 @@
       // module that the current module depends on. To indicate this
       // behavior, we mark all of the reachable modules as having N
       // incoming edges (which is impossible otherwise).
-      SmallVector<Module *, 4> Stack;
+      SmallVector<ModuleFile *, 4> Stack;
       Stack.push_back(CurrentModule);
       Skipped.insert(CurrentModule);
       while (!Stack.empty()) {
-        Module *NextModule =3D Stack.back();
+        ModuleFile *NextModule =3D Stack.back();
         Stack.pop_back();
        =20
         // For any module that this module depends on, push it on the
         // stack (if it hasn't already been marked as visited).
-        for (llvm::SetVector<Module *>::iterator=20
+        for (llvm::SetVector<ModuleFile *>::iterator=20
              M =3D NextModule->Imports.begin(),
              MEnd =3D NextModule->Imports.end();
              M !=3D MEnd; ++M) {
@@ -154,7 +155,7 @@
    =20
     // For any module that this module depends on, push it on the
     // stack (if it hasn't already been marked as visited).
-    for (llvm::SetVector<Module *>::iterator M =3D CurrentModule->Imports.=
begin(),
+    for (llvm::SetVector<ModuleFile *>::iterator M =3D CurrentModule->Impo=
rts.begin(),
          MEnd =3D CurrentModule->Imports.end();
          M !=3D MEnd; ++M) {
      =20
@@ -170,17 +171,17 @@
 }
=20
 /// \brief Perform a depth-first visit of the current module.
-static bool visitDepthFirst(Module &M,=20
-                            bool (*Visitor)(Module &M, bool Preorder,=20
+static bool visitDepthFirst(ModuleFile &M,=20
+                            bool (*Visitor)(ModuleFile &M, bool Preorder,=20
                                             void *UserData),=20
                             void *UserData,
-                            llvm::SmallPtrSet<Module *, 4> &Visited) {
+                            llvm::SmallPtrSet<ModuleFile *, 4> &Visited) {
   // Preorder visitation
   if (Visitor(M, /*Preorder=3D*/true, UserData))
     return true;
  =20
   // Visit children
-  for (llvm::SetVector<Module *>::iterator IM =3D M.Imports.begin(),
+  for (llvm::SetVector<ModuleFile *>::iterator IM =3D M.Imports.begin(),
        IMEnd =3D M.Imports.end();
        IM !=3D IMEnd; ++IM) {
     if (!Visited.insert(*IM))
@@ -194,10 +195,10 @@
   return Visitor(M, /*Preorder=3D*/false, UserData);
 }
=20
-void ModuleManager::visitDepthFirst(bool (*Visitor)(Module &M, bool Preord=
er,=20
+void ModuleManager::visitDepthFirst(bool (*Visitor)(ModuleFile &M, bool Pr=
eorder,=20
                                                     void *UserData),=20
                                     void *UserData) {
-  llvm::SmallPtrSet<Module *, 4> Visited;
+  llvm::SmallPtrSet<ModuleFile *, 4> Visited;
   for (unsigned I =3D 0, N =3D Chain.size(); I !=3D N; ++I) {
     if (!Visited.insert(Chain[I]))
       continue;
@@ -211,8 +212,8 @@
 namespace llvm {
   template<>
   struct GraphTraits<ModuleManager> {
-    typedef Module NodeType;
-    typedef llvm::SetVector<Module *>::const_iterator ChildIteratorType;
+    typedef ModuleFile NodeType;
+    typedef llvm::SetVector<ModuleFile *>::const_iterator ChildIteratorTyp=
e;
     typedef ModuleManager::ModuleConstIterator nodes_iterator;
    =20
     static ChildIteratorType child_begin(NodeType *Node) {
@@ -241,7 +242,7 @@
       return true;
     }
=20
-    std::string getNodeLabel(Module *M, const ModuleManager&) {
+    std::string getNodeLabel(ModuleFile *M, const ModuleManager&) {
       return llvm::sys::path::stem(M->FileName);
     }
   };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/AdjustedReturnValueChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AdjustedRet=
urnValueChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AdjustedRet=
urnValueChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -37,20 +37,21 @@
   QualType expectedResultTy =3D CE->getType();
=20
   // Fetch the signature of the called function.
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
-  SVal V =3D state->getSVal(CE);
+  SVal V =3D state->getSVal(CE, LCtx);
  =20
   if (V.isUnknown())
     return;
  =20
   // Casting to void?  Discard the value.
   if (expectedResultTy->isVoidType()) {
-    C.generateNode(state->BindExpr(CE, UnknownVal()));
+    C.addTransition(state->BindExpr(CE, LCtx, UnknownVal()));
     return;
   }                  =20
=20
-  const MemRegion *callee =3D state->getSVal(CE->getCallee()).getAsRegion(=
);
+  const MemRegion *callee =3D state->getSVal(CE->getCallee(), LCtx).getAsR=
egion();
   if (!callee)
     return;
=20
@@ -82,7 +83,7 @@
     // the cast avoids some assertion failures elsewhere.
     SValBuilder &svalBuilder =3D C.getSValBuilder();
     V =3D svalBuilder.evalCast(V, expectedResultTy, actualResultTy);
-    C.generateNode(state->BindExpr(CE, V));
+    C.addTransition(state->BindExpr(CE, LCtx, V));
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/AnalyzerStatsChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AnalyzerSta=
tsChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AnalyzerSta=
tsChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -8,6 +8,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // This file reports various statistics about analyzer visitation.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+#define DEBUG_TYPE "StatsChecker"
=20
 #include "ClangSACheckers.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -16,12 +17,20 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
=20
+#include "clang/AST/DeclObjC.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/Statistic.h"
=20
 using namespace clang;
 using namespace ento;
=20
+STATISTIC(NumBlocks,
+          "The # of blocks in top level functions");
+STATISTIC(NumBlocksUnreachable,
+          "The # of unreachable blocks in analyzing top level functions");
+
 namespace {
 class AnalyzerStatsChecker : public Checker<check::EndAnalysis> {
 public:
@@ -33,18 +42,23 @@
                                             BugReporter &B,
                                             ExprEngine &Eng) const {
   const CFG *C  =3D 0;
-  const Decl *D =3D 0;
-  const LocationContext *LC =3D 0;
   const SourceManager &SM =3D B.getSourceManager();
   llvm::SmallPtrSet<const CFGBlock*, 256> reachable;
=20
-  // Iterate over explodedgraph
+  // Root node should have the location context of the top most function.
+  const ExplodedNode *GraphRoot =3D *G.roots_begin();
+  const LocationContext *LC =3D GraphRoot->getLocation().getLocationContex=
t();
+
+  const Decl *D =3D LC->getDecl();
+
+  // Iterate over the exploded graph.
   for (ExplodedGraph::node_iterator I =3D G.nodes_begin();
       I !=3D G.nodes_end(); ++I) {
     const ProgramPoint &P =3D I->getLocation();
-    // Save the LocationContext if we don't have it already
-    if (!LC)
-      LC =3D P.getLocationContext();
+
+    // Only check the coverage in the top level function (optimization).
+    if (D !=3D P.getLocationContext()->getDecl())
+      continue;
=20
     if (const BlockEntrance *BE =3D dyn_cast<BlockEntrance>(&P)) {
       const CFGBlock *CB =3D BE->getBlock();
@@ -52,9 +66,8 @@
     }
   }
=20
-  // Get the CFG and the Decl of this block
+  // Get the CFG and the Decl of this block.
   C =3D LC->getCFG();
-  D =3D LC->getAnalysisContext()->getDecl();
=20
   unsigned total =3D 0, unreachable =3D 0;
=20
@@ -70,33 +83,39 @@
=20
   // We never 'reach' the entry block, so correct the unreachable count
   unreachable--;
+  // There is no BlockEntrance corresponding to the exit block as well, so
+  // assume it is reached as well.
+  unreachable--;
=20
   // Generate the warning string
-  llvm::SmallString<128> buf;
+  SmallString<128> buf;
   llvm::raw_svector_ostream output(buf);
   PresumedLoc Loc =3D SM.getPresumedLoc(D->getLocation());
-  if (Loc.isValid()) {
-    output << Loc.getFilename() << " : ";
+  if (!Loc.isValid())
+    return;
=20
-    if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
-      const NamedDecl *ND =3D cast<NamedDecl>(D);
-      output << *ND;
-    }
-    else if (isa<BlockDecl>(D)) {
-      output << "block(line:" << Loc.getLine() << ":col:" << Loc.getColumn=
();
-    }
+  if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
+    const NamedDecl *ND =3D cast<NamedDecl>(D);
+    output << *ND;
+  }
+  else if (isa<BlockDecl>(D)) {
+    output << "block(line:" << Loc.getLine() << ":col:" << Loc.getColumn();
   }
  =20
+  NumBlocksUnreachable +=3D unreachable;
+  NumBlocks +=3D total;
+  std::string NameOfRootFunction =3D output.str();
+
   output << " -> Total CFGBlocks: " << total << " | Unreachable CFGBlocks:=
 "
       << unreachable << " | Exhausted Block: "
       << (Eng.wasBlocksExhausted() ? "yes" : "no")
       << " | Empty WorkList: "
       << (Eng.hasEmptyWorkList() ? "yes" : "no");
=20
-  B.EmitBasicReport("Analyzer Statistics", "Internal Statistics", output.s=
tr(),
-      PathDiagnosticLocation(D, SM));
+  B.EmitBasicReport(D, "Analyzer Statistics", "Internal Statistics",
+                    output.str(), PathDiagnosticLocation(D, SM));
=20
-  // Emit warning for each block we bailed out on
+  // Emit warning for each block we bailed out on.
   typedef CoreEngine::BlocksExhausted::const_iterator ExhaustedIterator;
   const CoreEngine &CE =3D Eng.getCoreEngine();
   for (ExhaustedIterator I =3D CE.blocks_exhausted_begin(),
@@ -104,10 +123,15 @@
     const BlockEdge &BE =3D  I->first;
     const CFGBlock *Exit =3D BE.getDst();
     const CFGElement &CE =3D Exit->front();
-    if (const CFGStmt *CS =3D dyn_cast<CFGStmt>(&CE))
-      B.EmitBasicReport("Bailout Point", "Internal Statistics", "The analy=
zer "
-          "stopped analyzing at this point",
-          PathDiagnosticLocation::createBegin(CS->getStmt(), SM, LC));
+    if (const CFGStmt *CS =3D dyn_cast<CFGStmt>(&CE)) {
+      SmallString<128> bufI;
+      llvm::raw_svector_ostream outputI(bufI);
+      outputI << "(" << NameOfRootFunction << ")" <<
+                 ": The analyzer generated a sink at this point";
+      B.EmitBasicReport(D, "Sink Point", "Internal Statistics", outputI.st=
r(),
+                        PathDiagnosticLocation::createBegin(CS->getStmt(),
+                                                            SM, LC));
+    }
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ArrayBoundChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundC=
hecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundC=
hecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 namespace {
 class ArrayBoundChecker :=20
     public Checker<check::Location> {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
 public:
   void checkLocation(SVal l, bool isLoad, const Stmt* S,
                      CheckerContext &C) const;
@@ -51,15 +51,15 @@
   if (Idx.isZeroConstant())
     return;
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   // Get the size of the array.
   DefinedOrUnknownSVal NumElements=20
     =3D C.getStoreManager().getSizeInElements(state, ER->getSuperRegion(),=20
                                             ER->getValueType());
=20
-  const ProgramState *StInBound =3D state->assumeInBound(Idx, NumElements,=
 true);
-  const ProgramState *StOutBound =3D state->assumeInBound(Idx, NumElements=
, false);
+  ProgramStateRef StInBound =3D state->assumeInBound(Idx, NumElements, tru=
e);
+  ProgramStateRef StOutBound =3D state->assumeInBound(Idx, NumElements, fa=
lse);
   if (StOutBound && !StInBound) {
     ExplodedNode *N =3D C.generateSink(StOutBound);
     if (!N)
@@ -84,7 +84,6 @@
  =20
   // Array bound check succeeded.  From this point forward the array bound
   // should always succeed.
-  assert(StInBound);
   C.addTransition(StInBound);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundC=
heckerV2.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ArrayBoundC=
heckerV2.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,8 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/AST/CharUnits.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/STLExtras.h"
=20
 using namespace clang;
 using namespace ento;
@@ -26,11 +28,11 @@
 namespace {
 class ArrayBoundCheckerV2 :=20
     public Checker<check::Location> {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
      =20
-  enum OOB_Kind { OOB_Precedes, OOB_Excedes };
+  enum OOB_Kind { OOB_Precedes, OOB_Excedes, OOB_Tainted };
  =20
-  void reportOOB(CheckerContext &C, const ProgramState *errorState,
+  void reportOOB(CheckerContext &C, ProgramStateRef errorState,
                  OOB_Kind kind) const;
      =20
 public:
@@ -54,7 +56,7 @@
   NonLoc getByteOffset() const { return cast<NonLoc>(byteOffset); }
   const SubRegion *getRegion() const { return baseRegion; }
  =20
-  static RegionRawOffsetV2 computeOffset(const ProgramState *state,
+  static RegionRawOffsetV2 computeOffset(ProgramStateRef state,
                                          SValBuilder &svalBuilder,
                                          SVal location);
=20
@@ -92,8 +94,8 @@
   // memory access is within the extent of the base region.  Since we
   // have some flexibility in defining the base region, we can achieve
   // various levels of conservatism in our buffer overflow checking.
-  const ProgramState *state =3D checkerContext.getState(); =20
-  const ProgramState *originalState =3D state;
+  ProgramStateRef state =3D checkerContext.getState(); =20
+  ProgramStateRef originalState =3D state;
=20
   SValBuilder &svalBuilder =3D checkerContext.getSValBuilder();
   const RegionRawOffsetV2 &rawOffset =3D=20
@@ -118,7 +120,7 @@
     if (!lowerBoundToCheck)
       return;
    =20
-    const ProgramState *state_precedesLowerBound, *state_withinLowerBound;
+    ProgramStateRef state_precedesLowerBound, state_withinLowerBound;
     llvm::tie(state_precedesLowerBound, state_withinLowerBound) =3D
       state->assume(*lowerBoundToCheck);
=20
@@ -150,12 +152,20 @@
     if (!upperboundToCheck)
       break;
  =20
-    const ProgramState *state_exceedsUpperBound, *state_withinUpperBound;
+    ProgramStateRef state_exceedsUpperBound, state_withinUpperBound;
     llvm::tie(state_exceedsUpperBound, state_withinUpperBound) =3D
       state->assume(*upperboundToCheck);
+
+    // If we are under constrained and the index variables are tainted, re=
port.
+    if (state_exceedsUpperBound && state_withinUpperBound) {
+      if (state->isTainted(rawOffset.getByteOffset()))
+        reportOOB(checkerContext, state_exceedsUpperBound, OOB_Tainted);
+        return;
+    }
  =20
-    // Are we constrained enough to definitely exceed the upper bound?
-    if (state_exceedsUpperBound && !state_withinUpperBound) {
+    // If we are constrained enough to definitely exceed the upper bound, =
report.
+    if (state_exceedsUpperBound) {
+      assert(!state_withinUpperBound);
       reportOOB(checkerContext, state_exceedsUpperBound, OOB_Excedes);
       return;
     }
@@ -166,11 +176,11 @@
   while (false);
  =20
   if (state !=3D originalState)
-    checkerContext.generateNode(state);
+    checkerContext.addTransition(state);
 }
=20
 void ArrayBoundCheckerV2::reportOOB(CheckerContext &checkerContext,
-                                    const ProgramState *errorState,
+                                    ProgramStateRef errorState,
                                     OOB_Kind kind) const {
  =20
   ExplodedNode *errorNode =3D checkerContext.generateSink(errorState);
@@ -183,11 +193,20 @@
   // FIXME: This diagnostics are preliminary.  We should get far better
   // diagnostics for explaining buffer overruns.
=20
-  llvm::SmallString<256> buf;
+  SmallString<256> buf;
   llvm::raw_svector_ostream os(buf);
-  os << "Out of bound memory access "
-     << (kind =3D=3D OOB_Precedes ? "(accessed memory precedes memory bloc=
k)"
-                              : "(access exceeds upper limit of memory blo=
ck)");
+  os << "Out of bound memory access ";
+  switch (kind) {
+  case OOB_Precedes:
+    os << "(accessed memory precedes memory block)";
+    break;
+  case OOB_Excedes:
+    os << "(access exceeds upper limit of memory block)";
+    break;
+  case OOB_Tainted:
+    os << "(index is tainted)";
+    break;
+  }
=20
   checkerContext.EmitReport(new BugReport(*BT, os.str(), errorNode));
 }
@@ -221,7 +240,7 @@
=20
 // Scale a base value by a scaling factor, and return the scaled
 // value as an SVal.  Used by 'computeOffset'.
-static inline SVal scaleValue(const ProgramState *state,
+static inline SVal scaleValue(ProgramStateRef state,
                               NonLoc baseVal, CharUnits scaling,
                               SValBuilder &sb) {
   return sb.evalBinOpNN(state, BO_Mul, baseVal,
@@ -231,7 +250,7 @@
=20
 // Add an SVal to another, treating unknown and undefined values as
 // summing to UnknownVal.  Used by 'computeOffset'.
-static SVal addValue(const ProgramState *state, SVal x, SVal y,
+static SVal addValue(ProgramStateRef state, SVal x, SVal y,
                      SValBuilder &svalBuilder) {
   // We treat UnknownVals and UndefinedVals the same here because we
   // only care about computing offsets.
@@ -245,7 +264,7 @@
=20
 /// Compute a raw byte offset from a base region.  Used for array bounds
 /// checking.
-RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(const ProgramState *sta=
te,
+RegionRawOffsetV2 RegionRawOffsetV2::computeOffset(ProgramStateRef state,
                                                    SValBuilder &svalBuilde=
r,
                                                    SVal location)
 {
@@ -277,9 +296,9 @@
         offset =3D addValue(state,
                           getValue(offset, svalBuilder),
                           scaleValue(state,
-                                     cast<NonLoc>(index),
-                                     astContext.getTypeSizeInChars(elemTyp=
e),
-                                     svalBuilder),
+                          cast<NonLoc>(index),
+                          astContext.getTypeSizeInChars(elemType),
+                          svalBuilder),
                           svalBuilder);
=20
         if (offset.isUnknownOrUndef())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/AttrNonNullChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AttrNonNull=
Checker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/AttrNonNull=
Checker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 namespace {
 class AttrNonNullChecker
   : public Checker< check::PreStmt<CallExpr> > {
-  mutable llvm::OwningPtr<BugType> BT;
+  mutable OwningPtr<BugType> BT;
 public:
=20
   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
@@ -33,10 +33,11 @@
=20
 void AttrNonNullChecker::checkPreStmt(const CallExpr *CE,
                                       CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
   // Check if the callee has a 'nonnull' attribute.
-  SVal X =3D state->getSVal(CE->getCallee());
+  SVal X =3D state->getSVal(CE->getCallee(), LCtx);
=20
   const FunctionDecl *FD =3D X.getAsFunctionDecl();
   if (!FD)
@@ -55,7 +56,7 @@
     if (!Att->isNonNull(idx))
       continue;
=20
-    SVal V =3D state->getSVal(*I);
+    SVal V =3D state->getSVal(*I, LCtx);
     DefinedSVal *DV =3D dyn_cast<DefinedSVal>(&V);
=20
     // If the value is unknown or undefined, we can't perform this check.
@@ -85,7 +86,7 @@
     }
=20
     ConstraintManager &CM =3D C.getConstraintManager();
-    const ProgramState *stateNotNull, *stateNull;
+    ProgramStateRef stateNotNull, stateNull;
     llvm::tie(stateNotNull, stateNull) =3D CM.assumeDual(state, *DV);
=20
     if (stateNull && !stateNotNull) {
@@ -108,7 +109,7 @@
         const Expr *arg =3D *I;
         R->addRange(arg->getSourceRange());
         R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(errorNo=
de,
-                                                                   arg));
+                                                                   arg, R)=
);
         // Emit the bug report.
         C.EmitReport(R);
       }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/BasicObjCFoundationChecks.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFo=
undationChecks.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BasicObjCFo=
undationChecks.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -28,6 +28,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ASTContext.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -70,7 +71,7 @@
=20
 namespace {
   class NilArgChecker : public Checker<check::PreObjCMessage> {
-    mutable llvm::OwningPtr<APIMisuse> BT;
+    mutable OwningPtr<APIMisuse> BT;
=20
     void WarnNilArg(CheckerContext &C,
                     const ObjCMessage &msg, unsigned Arg) const;
@@ -88,7 +89,7 @@
     BT.reset(new APIMisuse("nil argument"));
  =20
   if (ExplodedNode *N =3D C.generateSink()) {
-    llvm::SmallString<128> sbuf;
+    SmallString<128> sbuf;
     llvm::raw_svector_ostream os(sbuf);
     os << "Argument to '" << GetReceiverNameType(msg) << "' method '"
        << msg.getSelector().getAsString() << "' cannot be nil";
@@ -129,7 +130,7 @@
         Name =3D=3D "compare:options:range:locale:" ||
         Name =3D=3D "componentsSeparatedByCharactersInSet:" ||
         Name =3D=3D "initWithFormat:") {
-      if (isNil(msg.getArgSVal(0, C.getState())))
+      if (isNil(msg.getArgSVal(0, C.getLocationContext(), C.getState())))
         WarnNilArg(C, msg, 0);
     }
   }
@@ -141,7 +142,7 @@
=20
 namespace {
 class CFNumberCreateChecker : public Checker< check::PreStmt<CallExpr> > {
-  mutable llvm::OwningPtr<APIMisuse> BT;
+  mutable OwningPtr<APIMisuse> BT;
   mutable IdentifierInfo* II;
 public:
   CFNumberCreateChecker() : II(0) {}
@@ -249,11 +250,8 @@
=20
 void CFNumberCreateChecker::checkPreStmt(const CallExpr *CE,
                                          CheckerContext &C) const {
-  const Expr *Callee =3D CE->getCallee();
-  const ProgramState *state =3D C.getState();
-  SVal CallV =3D state->getSVal(Callee);
-  const FunctionDecl *FD =3D CallV.getAsFunctionDecl();
-
+  ProgramStateRef state =3D C.getState();
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
   if (!FD)
     return;
  =20
@@ -265,7 +263,8 @@
     return;
=20
   // Get the value of the "theType" argument.
-  SVal TheTypeVal =3D state->getSVal(CE->getArg(1));
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal TheTypeVal =3D state->getSVal(CE->getArg(1), LCtx);
=20
   // FIXME: We really should allow ranges of valid theType values, and
   //   bifurcate the state appropriately.
@@ -283,7 +282,7 @@
   // Look at the value of the integer being passed by reference.  Essentia=
lly
   // we want to catch cases where the value passed in is not equal to the
   // size of the type being created.
-  SVal TheValueExpr =3D state->getSVal(CE->getArg(2));
+  SVal TheValueExpr =3D state->getSVal(CE->getArg(2), LCtx);
=20
   // FIXME: Eventually we should handle arbitrary locations.  We can do th=
is
   //  by having an enhanced memory model that does low-level typing.
@@ -316,8 +315,8 @@
   //  the bits initialized to the provided values.
   //
   if (ExplodedNode *N =3D SourceSize < TargetSize ? C.generateSink()=20
-                                                : C.generateNode()) {
-    llvm::SmallString<128> sbuf;
+                                                : C.addTransition()) {
+    SmallString<128> sbuf;
     llvm::raw_svector_ostream os(sbuf);
    =20
     os << (SourceSize =3D=3D 8 ? "An " : "A ")
@@ -348,7 +347,7 @@
=20
 namespace {
 class CFRetainReleaseChecker : public Checker< check::PreStmt<CallExpr> > {
-  mutable llvm::OwningPtr<APIMisuse> BT;
+  mutable OwningPtr<APIMisuse> BT;
   mutable IdentifierInfo *Retain, *Release;
 public:
   CFRetainReleaseChecker(): Retain(0), Release(0) {}
@@ -363,11 +362,8 @@
   if (CE->getNumArgs() !=3D 1)
     return;
=20
-  // Get the function declaration of the callee.
-  const ProgramState *state =3D C.getState();
-  SVal X =3D state->getSVal(CE->getCallee());
-  const FunctionDecl *FD =3D X.getAsFunctionDecl();
-
+  ProgramStateRef state =3D C.getState();
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
   if (!FD)
     return;
  =20
@@ -388,7 +384,7 @@
=20
   // Get the argument's value.
   const Expr *Arg =3D CE->getArg(0);
-  SVal ArgVal =3D state->getSVal(Arg);
+  SVal ArgVal =3D state->getSVal(Arg, C.getLocationContext());
   DefinedSVal *DefArgVal =3D dyn_cast<DefinedSVal>(&ArgVal);
   if (!DefArgVal)
     return;
@@ -401,7 +397,7 @@
   DefinedOrUnknownSVal ArgIsNull =3D svalBuilder.evalEQ(state, zero, *DefA=
rgVal);
=20
   // Are they equal?
-  const ProgramState *stateTrue, *stateFalse;
+  ProgramStateRef stateTrue, stateFalse;
   llvm::tie(stateTrue, stateFalse) =3D state->assume(ArgIsNull);
=20
   if (stateTrue && !stateFalse) {
@@ -415,7 +411,8 @@
=20
     BugReport *report =3D new BugReport(*BT, description, N);
     report->addRange(Arg->getSourceRange());
-    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, Arg=
));
+    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, Arg,
+                                                                    report=
));
     C.EmitReport(report);
     return;
   }
@@ -434,7 +431,7 @@
   mutable Selector retainS;
   mutable Selector autoreleaseS;
   mutable Selector drainS;
-  mutable llvm::OwningPtr<BugType> BT;
+  mutable OwningPtr<BugType> BT;
=20
 public:
   void checkPreObjCMessage(ObjCMessage msg, CheckerContext &C) const;
@@ -464,8 +461,8 @@
   if (!(S =3D=3D releaseS || S =3D=3D retainS || S =3D=3D autoreleaseS || =
S =3D=3D drainS))
     return;
  =20
-  if (ExplodedNode *N =3D C.generateNode()) {
-    llvm::SmallString<200> buf;
+  if (ExplodedNode *N =3D C.addTransition()) {
+    SmallString<200> buf;
     llvm::raw_svector_ostream os(buf);
=20
     os << "The '" << S.getAsString() << "' message should be sent to insta=
nces "
@@ -488,9 +485,10 @@
   mutable Selector arrayWithObjectsS;
   mutable Selector dictionaryWithObjectsAndKeysS;
   mutable Selector setWithObjectsS;
+  mutable Selector orderedSetWithObjectsS;
   mutable Selector initWithObjectsS;
   mutable Selector initWithObjectsAndKeysS;
-  mutable llvm::OwningPtr<BugType> BT;
+  mutable OwningPtr<BugType> BT;
=20
   bool isVariadicMessage(const ObjCMessage &msg) const;
=20
@@ -533,6 +531,11 @@
     if (isReceiverClassOrSuperclass(Class, "NSSet") &&
         S =3D=3D initWithObjectsS)
       return true;
+
+    // -[NSOrderedSet initWithObjects:]
+    if (isReceiverClassOrSuperclass(Class, "NSOrderedSet") &&
+        S =3D=3D initWithObjectsS)
+      return true;
   } else {
     const ObjCInterfaceDecl *Class =3D msg.getReceiverInterface();
=20
@@ -550,6 +553,11 @@
     if (isReceiverClassOrSuperclass(Class, "NSSet") &&
         S =3D=3D setWithObjectsS)
       return true;
+
+    // -[NSOrderedSet orderedSetWithObjects:]
+    if (isReceiverClassOrSuperclass(Class, "NSOrderedSet") &&
+        S =3D=3D orderedSetWithObjectsS)
+      return true;
   }
=20
   return false;
@@ -566,6 +574,7 @@
     dictionaryWithObjectsAndKeysS =3D=20
       GetUnarySelector("dictionaryWithObjectsAndKeys", Ctx);
     setWithObjectsS =3D GetUnarySelector("setWithObjects", Ctx);
+    orderedSetWithObjectsS =3D GetUnarySelector("orderedSetWithObjects", C=
tx);
=20
     initWithObjectsS =3D GetUnarySelector("initWithObjects", Ctx);
     initWithObjectsAndKeysS =3D GetUnarySelector("initWithObjectsAndKeys",=
 Ctx);
@@ -587,7 +596,7 @@
=20
   // Verify that all arguments have Objective-C types.
   llvm::Optional<ExplodedNode*> errorNode;
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
  =20
   for (unsigned I =3D variadicArgsBegin; I !=3D variadicArgsEnd; ++I) {
     QualType ArgTy =3D msg.getArgType(I);
@@ -599,7 +608,8 @@
       continue;
=20
     // Ignore pointer constants.
-    if (isa<loc::ConcreteInt>(msg.getArgSVal(I, state)))
+    if (isa<loc::ConcreteInt>(msg.getArgSVal(I, C.getLocationContext(),
+                                             state)))
       continue;
    =20
     // Ignore pointer types annotated with 'NSObject' attribute.
@@ -612,13 +622,13 @@
=20
     // Generate only one error node to use for all bug reports.
     if (!errorNode.hasValue()) {
-      errorNode =3D C.generateNode();
+      errorNode =3D C.addTransition();
     }
=20
     if (!errorNode.getValue())
       continue;
=20
-    llvm::SmallString<128> sbuf;
+    SmallString<128> sbuf;
     llvm::raw_svector_ostream os(sbuf);
=20
     if (const char *TypeName =3D GetReceiverNameType(msg))
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/BuiltinFunctionChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunc=
tionChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/BuiltinFunc=
tionChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -30,12 +30,10 @@
 }
=20
 bool BuiltinFunctionChecker::evalCall(const CallExpr *CE,
-                                      CheckerContext &C) const{
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
-
+                                      CheckerContext &C) const {
+  ProgramStateRef state =3D C.getState();
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
+  const LocationContext *LCtx =3D C.getLocationContext();
   if (!FD)
     return false;
=20
@@ -48,8 +46,8 @@
   case Builtin::BI__builtin_expect: {
     // For __builtin_expect, just return the value of the subexpression.
     assert (CE->arg_begin() !=3D CE->arg_end());
-    SVal X =3D state->getSVal(*(CE->arg_begin()));
-    C.generateNode(state->BindExpr(CE, X));
+    SVal X =3D state->getSVal(*(CE->arg_begin()), LCtx);
+    C.addTransition(state->BindExpr(CE, LCtx, X));
     return true;
   }
=20
@@ -57,14 +55,13 @@
     // FIXME: Refactor into StoreManager itself?
     MemRegionManager& RM =3D C.getStoreManager().getRegionManager();
     const AllocaRegion* R =3D
-      RM.getAllocaRegion(CE, C.getCurrentBlockCount(),
-                         C.getPredecessor()->getLocationContext());
+      RM.getAllocaRegion(CE, C.getCurrentBlockCount(), C.getLocationContex=
t());
=20
     // Set the extent of the region in bytes. This enables us to use the
     // SVal of the argument directly. If we save the extent in bits, we
     // cannot represent values like symbol*8.
     DefinedOrUnknownSVal Size =3D
-      cast<DefinedOrUnknownSVal>(state->getSVal(*(CE->arg_begin())));
+      cast<DefinedOrUnknownSVal>(state->getSVal(*(CE->arg_begin()), LCtx));
=20
     SValBuilder& svalBuilder =3D C.getSValBuilder();
     DefinedOrUnknownSVal Extent =3D R->getExtent(svalBuilder);
@@ -72,7 +69,7 @@
       svalBuilder.evalEQ(state, Extent, Size);
     state =3D state->assume(extentMatchesSizeArg, true);
=20
-    C.generateNode(state->BindExpr(CE, loc::MemRegionVal(R)));
+    C.addTransition(state->BindExpr(CE, LCtx, loc::MemRegionVal(R)));
     return true;
   }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CStringChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CStringChec=
ker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CStringChec=
ker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -13,11 +13,14 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "ClangSACheckers.h"
+#include "InterCheckerAPI.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringSwitch.h"
=20
 using namespace clang;
@@ -30,25 +33,40 @@
                                          check::DeadSymbols,
                                          check::RegionChanges
                                          > {
-  mutable llvm::OwningPtr<BugType> BT_Null, BT_Bounds,
-                                   BT_Overlap, BT_NotCString,
-                                   BT_AdditionOverflow;
+  mutable OwningPtr<BugType> BT_Null,
+                             BT_Bounds,
+                             BT_Overlap,
+                             BT_NotCString,
+                             BT_AdditionOverflow;
+
   mutable const char *CurrentFunctionDescription;
=20
 public:
+  /// The filter is used to filter out the diagnostics which are not enabl=
ed by
+  /// the user.
+  struct CStringChecksFilter {
+    DefaultBool CheckCStringNullArg;
+    DefaultBool CheckCStringOutOfBounds;
+    DefaultBool CheckCStringBufferOverlap;
+    DefaultBool CheckCStringNotNullTerm;
+  };
+
+  CStringChecksFilter Filter;
+
   static void *getTag() { static int tag; return &tag; }
=20
   bool evalCall(const CallExpr *CE, CheckerContext &C) const;
   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
-  void checkLiveSymbols(const ProgramState *state, SymbolReaper &SR) const;
+  void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
-  bool wantsRegionChangeUpdate(const ProgramState *state) const;
+  bool wantsRegionChangeUpdate(ProgramStateRef state) const;
=20
-  const ProgramState *
-    checkRegionChanges(const ProgramState *state,
+  ProgramStateRef=20
+    checkRegionChanges(ProgramStateRef state,
                        const StoreManager::InvalidatedSymbols *,
                        ArrayRef<const MemRegion *> ExplicitRegions,
-                       ArrayRef<const MemRegion *> Regions) const;
+                       ArrayRef<const MemRegion *> Regions,
+                       const CallOrObjCMessage *Call) const;
=20
   typedef void (CStringChecker::*FnCheck)(CheckerContext &,
                                           const CallExpr *) const;
@@ -58,7 +76,7 @@
   void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
   void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
   void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
-                      const ProgramState *state,
+                      ProgramStateRef state,
                       const Expr *Size,
                       const Expr *Source,
                       const Expr *Dest,
@@ -95,48 +113,48 @@
                         bool ignoreCase =3D false) const;
=20
   // Utility methods
-  std::pair<const ProgramState*, const ProgramState*>
+  std::pair<ProgramStateRef , ProgramStateRef >
   static assumeZero(CheckerContext &C,
-                    const ProgramState *state, SVal V, QualType Ty);
+                    ProgramStateRef state, SVal V, QualType Ty);
=20
-  static const ProgramState *setCStringLength(const ProgramState *state,
+  static ProgramStateRef setCStringLength(ProgramStateRef state,
                                               const MemRegion *MR,
                                               SVal strLength);
   static SVal getCStringLengthForRegion(CheckerContext &C,
-                                        const ProgramState *&state,
+                                        ProgramStateRef &state,
                                         const Expr *Ex,
                                         const MemRegion *MR,
                                         bool hypothetical);
   SVal getCStringLength(CheckerContext &C,
-                        const ProgramState *&state,
+                        ProgramStateRef &state,
                         const Expr *Ex,
                         SVal Buf,
                         bool hypothetical =3D false) const;
=20
   const StringLiteral *getCStringLiteral(CheckerContext &C,=20
-                                         const ProgramState *&state,
+                                         ProgramStateRef &state,
                                          const Expr *expr, =20
                                          SVal val) const;
=20
-  static const ProgramState *InvalidateBuffer(CheckerContext &C,
-                                              const ProgramState *state,
+  static ProgramStateRef InvalidateBuffer(CheckerContext &C,
+                                              ProgramStateRef state,
                                               const Expr *Ex, SVal V);
=20
   static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
                               const MemRegion *MR);
=20
   // Re-usable checks
-  const ProgramState *checkNonNull(CheckerContext &C,
-                                   const ProgramState *state,
+  ProgramStateRef checkNonNull(CheckerContext &C,
+                                   ProgramStateRef state,
                                    const Expr *S,
                                    SVal l) const;
-  const ProgramState *CheckLocation(CheckerContext &C,
-                                    const ProgramState *state,
+  ProgramStateRef CheckLocation(CheckerContext &C,
+                                    ProgramStateRef state,
                                     const Expr *S,
                                     SVal l,
                                     const char *message =3D NULL) const;
-  const ProgramState *CheckBufferAccess(CheckerContext &C,
-                                        const ProgramState *state,
+  ProgramStateRef CheckBufferAccess(CheckerContext &C,
+                                        ProgramStateRef state,
                                         const Expr *Size,
                                         const Expr *FirstBuf,
                                         const Expr *SecondBuf,
@@ -144,8 +162,8 @@
                                         const char *secondMessage =3D NULL,
                                         bool WarnAboutSize =3D false) cons=
t;
=20
-  const ProgramState *CheckBufferAccess(CheckerContext &C,
-                                        const ProgramState *state,
+  ProgramStateRef CheckBufferAccess(CheckerContext &C,
+                                        ProgramStateRef state,
                                         const Expr *Size,
                                         const Expr *Buf,
                                         const char *message =3D NULL,
@@ -154,18 +172,18 @@
     return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
                              WarnAboutSize);
   }
-  const ProgramState *CheckOverlap(CheckerContext &C,
-                                   const ProgramState *state,
+  ProgramStateRef CheckOverlap(CheckerContext &C,
+                                   ProgramStateRef state,
                                    const Expr *Size,
                                    const Expr *First,
                                    const Expr *Second) const;
   void emitOverlapBug(CheckerContext &C,
-                      const ProgramState *state,
+                      ProgramStateRef state,
                       const Stmt *First,
                       const Stmt *Second) const;
=20
-  const ProgramState *checkAdditionOverflow(CheckerContext &C,
-                                            const ProgramState *state,
+  ProgramStateRef checkAdditionOverflow(CheckerContext &C,
+                                            ProgramStateRef state,
                                             NonLoc left,
                                             NonLoc right) const;
 };
@@ -190,38 +208,41 @@
 // Individual checks and utility methods.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-std::pair<const ProgramState*, const ProgramState*>
-CStringChecker::assumeZero(CheckerContext &C, const ProgramState *state, S=
Val V,
+std::pair<ProgramStateRef , ProgramStateRef >
+CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal =
V,
                            QualType Ty) {
   DefinedSVal *val =3D dyn_cast<DefinedSVal>(&V);
   if (!val)
-    return std::pair<const ProgramState*, const ProgramState *>(state, sta=
te);
+    return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
=20
   SValBuilder &svalBuilder =3D C.getSValBuilder();
   DefinedOrUnknownSVal zero =3D svalBuilder.makeZeroVal(Ty);
   return state->assume(svalBuilder.evalEQ(state, *val, zero));
 }
=20
-const ProgramState *CStringChecker::checkNonNull(CheckerContext &C,
-                                            const ProgramState *state,
+ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
+                                            ProgramStateRef state,
                                             const Expr *S, SVal l) const {
   // If a previous check has failed, propagate the failure.
   if (!state)
     return NULL;
=20
-  const ProgramState *stateNull, *stateNonNull;
+  ProgramStateRef stateNull, stateNonNull;
   llvm::tie(stateNull, stateNonNull) =3D assumeZero(C, state, l, S->getTyp=
e());
=20
   if (stateNull && !stateNonNull) {
+    if (!Filter.CheckCStringNullArg)
+      return NULL;
+
     ExplodedNode *N =3D C.generateSink(stateNull);
     if (!N)
       return NULL;
=20
     if (!BT_Null)
-      BT_Null.reset(new BuiltinBug("API",
+      BT_Null.reset(new BuiltinBug("Unix API",
         "Null pointer argument in call to byte string function"));
=20
-    llvm::SmallString<80> buf;
+    SmallString<80> buf;
     llvm::raw_svector_ostream os(buf);
     assert(CurrentFunctionDescription);
     os << "Null pointer argument in call to " << CurrentFunctionDescriptio=
n;
@@ -231,7 +252,8 @@
     BugReport *report =3D new BugReport(*BT, os.str(), N);
=20
     report->addRange(S->getSourceRange());
-    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, S));
+    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, S,
+                                                                    report=
));
     C.EmitReport(report);
     return NULL;
   }
@@ -242,8 +264,8 @@
 }
=20
 // FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
-const ProgramState *CStringChecker::CheckLocation(CheckerContext &C,
-                                             const ProgramState *state,
+ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
+                                             ProgramStateRef state,
                                              const Expr *S, SVal l,
                                              const char *warningMsg) const=
 {
   // If a previous check has failed, propagate the failure.
@@ -272,8 +294,8 @@
   // Get the index of the accessed element.
   DefinedOrUnknownSVal Idx =3D cast<DefinedOrUnknownSVal>(ER->getIndex());
=20
-  const ProgramState *StInBound =3D state->assumeInBound(Idx, Size, true);
-  const ProgramState *StOutBound =3D state->assumeInBound(Idx, Size, false=
);
+  ProgramStateRef StInBound =3D state->assumeInBound(Idx, Size, true);
+  ProgramStateRef StOutBound =3D state->assumeInBound(Idx, Size, false);
   if (StOutBound && !StInBound) {
     ExplodedNode *N =3D C.generateSink(StOutBound);
     if (!N)
@@ -293,7 +315,7 @@
       assert(CurrentFunctionDescription);
       assert(CurrentFunctionDescription[0] !=3D '\0');
=20
-      llvm::SmallString<80> buf;
+      SmallString<80> buf;
       llvm::raw_svector_ostream os(buf);
       os << (char)toupper(CurrentFunctionDescription[0])
          << &CurrentFunctionDescription[1]
@@ -315,8 +337,8 @@
   return StInBound;
 }
=20
-const ProgramState *CStringChecker::CheckBufferAccess(CheckerContext &C,
-                                                 const ProgramState *state,
+ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
+                                                 ProgramStateRef state,
                                                  const Expr *Size,
                                                  const Expr *FirstBuf,
                                                  const Expr *SecondBuf,
@@ -329,20 +351,25 @@
=20
   SValBuilder &svalBuilder =3D C.getSValBuilder();
   ASTContext &Ctx =3D svalBuilder.getContext();
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
   QualType sizeTy =3D Size->getType();
   QualType PtrTy =3D Ctx.getPointerType(Ctx.CharTy);
=20
   // Check that the first buffer is non-null.
-  SVal BufVal =3D state->getSVal(FirstBuf);
+  SVal BufVal =3D state->getSVal(FirstBuf, LCtx);
   state =3D checkNonNull(C, state, FirstBuf, BufVal);
   if (!state)
     return NULL;
=20
+  // If out-of-bounds checking is turned off, skip the rest.
+  if (!Filter.CheckCStringOutOfBounds)
+    return state;
+
   // Get the access length and make sure it is known.
   // FIXME: This assumes the caller has already checked that the access le=
ngth
   // is positive. And that it's unsigned.
-  SVal LengthVal =3D state->getSVal(Size);
+  SVal LengthVal =3D state->getSVal(Size, LCtx);
   NonLoc *Length =3D dyn_cast<NonLoc>(&LengthVal);
   if (!Length)
     return state;
@@ -368,7 +395,7 @@
=20
   // If there's a second buffer, check it as well.
   if (SecondBuf) {
-    BufVal =3D state->getSVal(SecondBuf);
+    BufVal =3D state->getSVal(SecondBuf, LCtx);
     state =3D checkNonNull(C, state, SecondBuf, BufVal);
     if (!state)
       return NULL;
@@ -387,11 +414,14 @@
   return state;
 }
=20
-const ProgramState *CStringChecker::CheckOverlap(CheckerContext &C,
-                                            const ProgramState *state,
+ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
+                                            ProgramStateRef state,
                                             const Expr *Size,
                                             const Expr *First,
                                             const Expr *Second) const {
+  if (!Filter.CheckCStringBufferOverlap)
+    return state;
+
   // Do a simple check for overlap: if the two arguments are from the same
   // buffer, see if the end of the first is greater than the start of the =
second
   // or vice versa.
@@ -400,11 +430,12 @@
   if (!state)
     return NULL;
=20
-  const ProgramState *stateTrue, *stateFalse;
+  ProgramStateRef stateTrue, stateFalse;
=20
   // Get the buffer values and make sure they're known locations.
-  SVal firstVal =3D state->getSVal(First);
-  SVal secondVal =3D state->getSVal(Second);
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal firstVal =3D state->getSVal(First, LCtx);
+  SVal secondVal =3D state->getSVal(Second, LCtx);
=20
   Loc *firstLoc =3D dyn_cast<Loc>(&firstVal);
   if (!firstLoc)
@@ -456,7 +487,7 @@
   }
=20
   // Get the length, and make sure it too is known.
-  SVal LengthVal =3D state->getSVal(Size);
+  SVal LengthVal =3D state->getSVal(Size, LCtx);
   NonLoc *Length =3D dyn_cast<NonLoc>(&LengthVal);
   if (!Length)
     return state;
@@ -498,7 +529,7 @@
   return stateFalse;
 }
=20
-void CStringChecker::emitOverlapBug(CheckerContext &C, const ProgramState =
*state,
+void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef sta=
te,
                                   const Stmt *First, const Stmt *Second) c=
onst {
   ExplodedNode *N =3D C.generateSink(state);
   if (!N)
@@ -517,10 +548,14 @@
   C.EmitReport(report);
 }
=20
-const ProgramState *CStringChecker::checkAdditionOverflow(CheckerContext &=
C,
-                                                     const ProgramState *s=
tate,
+ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
+                                                     ProgramStateRef state,
                                                      NonLoc left,
                                                      NonLoc right) const {
+  // If out-of-bounds checking is turned off, skip the rest.
+  if (!Filter.CheckCStringOutOfBounds)
+    return state;
+
   // If a previous check has failed, propagate the failure.
   if (!state)
     return NULL;
@@ -532,10 +567,11 @@
   const llvm::APSInt &maxValInt =3D BVF.getMaxValue(sizeTy);
   NonLoc maxVal =3D svalBuilder.makeIntVal(maxValInt);
=20
-  SVal maxMinusRight =3D svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, ri=
ght,
-                                               sizeTy);
-
-  if (maxMinusRight.isUnknownOrUndef()) {
+  SVal maxMinusRight;
+  if (isa<nonloc::ConcreteInt>(right)) {
+    maxMinusRight =3D svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
+                                                 sizeTy);
+  } else {
     // Try switching the operands. (The order of these two assignments is
     // important!)
     maxMinusRight =3D svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,=20
@@ -549,7 +585,7 @@
     SVal willOverflow =3D svalBuilder.evalBinOpNN(state, BO_GT, left,
                                                 *maxMinusRightNL, cmpTy);
=20
-    const ProgramState *stateOverflow, *stateOkay;
+    ProgramStateRef stateOverflow, stateOkay;
     llvm::tie(stateOverflow, stateOkay) =3D
       state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
=20
@@ -585,7 +621,7 @@
   return state;
 }
=20
-const ProgramState *CStringChecker::setCStringLength(const ProgramState *s=
tate,
+ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
                                                 const MemRegion *MR,
                                                 SVal strLength) {
   assert(!strLength.isUndef() && "Attempt to set an undefined string lengt=
h");
@@ -626,7 +662,7 @@
 }
=20
 SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
-                                               const ProgramState *&state,
+                                               ProgramStateRef &state,
                                                const Expr *Ex,
                                                const MemRegion *MR,
                                                bool hypothetical) {
@@ -650,7 +686,7 @@
   return strLength;
 }
=20
-SVal CStringChecker::getCStringLength(CheckerContext &C, const ProgramStat=
e *&state,
+SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &=
state,
                                       const Expr *Ex, SVal Buf,
                                       bool hypothetical) const {
   const MemRegion *MR =3D Buf.getAsRegion();
@@ -659,12 +695,15 @@
     // C string. In the context of locations, the only time we can issue s=
uch
     // a warning is for labels.
     if (loc::GotoLabel *Label =3D dyn_cast<loc::GotoLabel>(&Buf)) {
-      if (ExplodedNode *N =3D C.generateNode(state)) {
+      if (!Filter.CheckCStringNotNullTerm)
+        return UndefinedVal();
+
+      if (ExplodedNode *N =3D C.addTransition(state)) {
         if (!BT_NotCString)
-          BT_NotCString.reset(new BuiltinBug("API",
+          BT_NotCString.reset(new BuiltinBug("Unix API",
             "Argument is not a null-terminated string."));
=20
-        llvm::SmallString<120> buf;
+        SmallString<120> buf;
         llvm::raw_svector_ostream os(buf);
         assert(CurrentFunctionDescription);
         os << "Argument to " << CurrentFunctionDescription
@@ -678,8 +717,8 @@
         report->addRange(Ex->getSourceRange());
         C.EmitReport(report);       =20
       }
+      return UndefinedVal();
=20
-      return UndefinedVal();
     }
=20
     // If it's not a region and not a label, give up.
@@ -716,12 +755,15 @@
     // Other regions (mostly non-data) can't have a reliable C string leng=
th.
     // In this case, an error is emitted and UndefinedVal is returned.
     // The caller should always be prepared to handle this case.
-    if (ExplodedNode *N =3D C.generateNode(state)) {
+    if (!Filter.CheckCStringNotNullTerm)
+      return UndefinedVal();
+
+    if (ExplodedNode *N =3D C.addTransition(state)) {
       if (!BT_NotCString)
-        BT_NotCString.reset(new BuiltinBug("API",
+        BT_NotCString.reset(new BuiltinBug("Unix API",
           "Argument is not a null-terminated string."));
=20
-      llvm::SmallString<120> buf;
+      SmallString<120> buf;
       llvm::raw_svector_ostream os(buf);
=20
       assert(CurrentFunctionDescription);
@@ -745,7 +787,7 @@
 }
=20
 const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
-  const ProgramState *&state, const Expr *expr, SVal val) const {
+  ProgramStateRef &state, const Expr *expr, SVal val) const {
=20
   // Get the memory region pointed to by the val.
   const MemRegion *bufRegion =3D val.getAsRegion();
@@ -764,8 +806,8 @@
   return strRegion->getStringLiteral();
 }
=20
-const ProgramState *CStringChecker::InvalidateBuffer(CheckerContext &C,
-                                                const ProgramState *state,
+ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
+                                                ProgramStateRef state,
                                                 const Expr *E, SVal V) {
   Loc *L =3D dyn_cast<Loc>(&V);
   if (!L)
@@ -786,7 +828,8 @@
=20
     // Invalidate this region.
     unsigned Count =3D C.getCurrentBlockCount();
-    return state->invalidateRegions(R, E, Count);
+    const LocationContext *LCtx =3D C.getPredecessor()->getLocationContext=
();
+    return state->invalidateRegions(R, E, Count, LCtx);
   }
=20
   // If we have a non-region value by chance, just remove the binding.
@@ -838,27 +881,28 @@
=20
 void CStringChecker::evalCopyCommon(CheckerContext &C,=20
                                     const CallExpr *CE,
-                                    const ProgramState *state,
+                                    ProgramStateRef state,
                                     const Expr *Size, const Expr *Dest,
                                     const Expr *Source, bool Restricted,
                                     bool IsMempcpy) const {
   CurrentFunctionDescription =3D "memory copy function";
=20
   // See if the size argument is zero.
-  SVal sizeVal =3D state->getSVal(Size);
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal sizeVal =3D state->getSVal(Size, LCtx);
   QualType sizeTy =3D Size->getType();
=20
-  const ProgramState *stateZeroSize, *stateNonZeroSize;
+  ProgramStateRef stateZeroSize, stateNonZeroSize;
   llvm::tie(stateZeroSize, stateNonZeroSize) =3D
     assumeZero(C, state, sizeVal, sizeTy);
=20
   // Get the value of the Dest.
-  SVal destVal =3D state->getSVal(Dest);
+  SVal destVal =3D state->getSVal(Dest, LCtx);
=20
   // If the size is zero, there won't be any actual memory access, so
   // just bind the return value to the destination buffer and return.
   if (stateZeroSize) {
-    stateZeroSize =3D stateZeroSize->BindExpr(CE, destVal);
+    stateZeroSize =3D stateZeroSize->BindExpr(CE, LCtx, destVal);
     C.addTransition(stateZeroSize);
   }
=20
@@ -873,7 +917,7 @@
       return;
=20
     // Get the value of the Src.
-    SVal srcVal =3D state->getSVal(Source);
+    SVal srcVal =3D state->getSVal(Source, LCtx);
    =20
     // Ensure the source is not null. If it is NULL there will be a
     // NULL pointer dereference.
@@ -909,20 +953,20 @@
                                                           Dest->getType());
      =20
         // The byte after the last byte copied is the return value.
-        state =3D state->BindExpr(CE, lastElement);
+        state =3D state->BindExpr(CE, LCtx, lastElement);
       } else {
         // If we don't know how much we copied, we can at least
         // conjure a return value for later.
         unsigned Count =3D C.getCurrentBlockCount();
         SVal result =3D
-          C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
-        state =3D state->BindExpr(CE, result);
+          C.getSValBuilder().getConjuredSymbolVal(NULL, CE, LCtx, Count);
+        state =3D state->BindExpr(CE, LCtx, result);
       }
=20
     } else {
       // All other copies return the destination buffer.
       // (Well, bcopy() has a void return type, but this won't hurt.)
-      state =3D state->BindExpr(CE, destVal);
+      state =3D state->BindExpr(CE, LCtx, destVal);
     }
=20
     // Invalidate the destination.
@@ -930,46 +974,62 @@
     // can use LazyCompoundVals to copy the source values into the destina=
tion.
     // This would probably remove any existing bindings past the end of the
     // copied region, but that's still an improvement over blank invalidat=
ion.
-    state =3D InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
+    state =3D InvalidateBuffer(C, state, Dest,
+                             state->getSVal(Dest, C.getLocationContext()));
     C.addTransition(state);
   }
 }
=20
=20
 void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) con=
st {
+  if (CE->getNumArgs() < 3)
+    return;
+
   // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
   // The return value is the address of the destination buffer.
   const Expr *Dest =3D CE->getArg(0);
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
 }
=20
 void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) co=
nst {
+  if (CE->getNumArgs() < 3)
+    return;
+
   // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
   // The return value is a pointer to the byte following the last written =
byte.
   const Expr *Dest =3D CE->getArg(0);
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
  =20
   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, t=
rue);
 }
=20
 void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) co=
nst {
+  if (CE->getNumArgs() < 3)
+    return;
+
   // void *memmove(void *dst, const void *src, size_t n);
   // The return value is the address of the destination buffer.
   const Expr *Dest =3D CE->getArg(0);
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
 }
=20
 void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) cons=
t {
+  if (CE->getNumArgs() < 3)
+    return;
+
   // void bcopy(const void *src, void *dst, size_t n);
   evalCopyCommon(C, CE, C.getState(),=20
                  CE->getArg(2), CE->getArg(1), CE->getArg(0));
 }
=20
 void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) con=
st {
+  if (CE->getNumArgs() < 3)
+    return;
+
   // int memcmp(const void *s1, const void *s2, size_t n);
   CurrentFunctionDescription =3D "memory comparison function";
=20
@@ -977,14 +1037,15 @@
   const Expr *Right =3D CE->getArg(1);
   const Expr *Size =3D CE->getArg(2);
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   SValBuilder &svalBuilder =3D C.getSValBuilder();
=20
   // See if the size argument is zero.
-  SVal sizeVal =3D state->getSVal(Size);
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal sizeVal =3D state->getSVal(Size, LCtx);
   QualType sizeTy =3D Size->getType();
=20
-  const ProgramState *stateZeroSize, *stateNonZeroSize;
+  ProgramStateRef stateZeroSize, stateNonZeroSize;
   llvm::tie(stateZeroSize, stateNonZeroSize) =3D
     assumeZero(C, state, sizeVal, sizeTy);
=20
@@ -992,7 +1053,8 @@
   // have to check either of the buffers.
   if (stateZeroSize) {
     state =3D stateZeroSize;
-    state =3D state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
+    state =3D state->BindExpr(CE, LCtx,
+                            svalBuilder.makeZeroVal(CE->getType()));
     C.addTransition(state);
   }
=20
@@ -1002,12 +1064,14 @@
     // If we know the two buffers are the same, we know the result is 0.
     // First, get the two buffers' addresses. Another checker will have al=
ready
     // made sure they're not undefined.
-    DefinedOrUnknownSVal LV =3D cast<DefinedOrUnknownSVal>(state->getSVal(=
Left));
-    DefinedOrUnknownSVal RV =3D cast<DefinedOrUnknownSVal>(state->getSVal(=
Right));
+    DefinedOrUnknownSVal LV =3D
+      cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
+    DefinedOrUnknownSVal RV =3D
+      cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
=20
     // See if they are the same.
     DefinedOrUnknownSVal SameBuf =3D svalBuilder.evalEQ(state, LV, RV);
-    const ProgramState *StSameBuf, *StNotSameBuf;
+    ProgramStateRef StSameBuf, StNotSameBuf;
     llvm::tie(StSameBuf, StNotSameBuf) =3D state->assume(SameBuf);
=20
     // If the two arguments might be the same buffer, we know the result i=
s 0,
@@ -1016,8 +1080,9 @@
       state =3D StSameBuf;
       state =3D CheckBufferAccess(C, state, Size, Left);
       if (state) {
-        state =3D StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getT=
ype()));
-        C.addTransition(state);=20
+        state =3D StSameBuf->BindExpr(CE, LCtx,
+                                    svalBuilder.makeZeroVal(CE->getType())=
);
+        C.addTransition(state);
       }
     }
=20
@@ -1029,8 +1094,8 @@
       if (state) {
         // The return value is the comparison result, which we don't know.
         unsigned Count =3D C.getCurrentBlockCount();
-        SVal CmpV =3D svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
-        state =3D state->BindExpr(CE, CmpV);
+        SVal CmpV =3D svalBuilder.getConjuredSymbolVal(NULL, CE, LCtx, Cou=
nt);
+        state =3D state->BindExpr(CE, LCtx, CmpV);
         C.addTransition(state);
       }
     }
@@ -1039,12 +1104,18 @@
=20
 void CStringChecker::evalstrLength(CheckerContext &C,
                                    const CallExpr *CE) const {
+  if (CE->getNumArgs() < 1)
+    return;
+
   // size_t strlen(const char *s);
   evalstrLengthCommon(C, CE, /* IsStrnlen =3D */ false);
 }
=20
 void CStringChecker::evalstrnLength(CheckerContext &C,
                                     const CallExpr *CE) const {
+  if (CE->getNumArgs() < 2)
+    return;
+
   // size_t strnlen(const char *s, size_t maxlen);
   evalstrLengthCommon(C, CE, /* IsStrnlen =3D */ true);
 }
@@ -1052,13 +1123,14 @@
 void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr=
 *CE,
                                          bool IsStrnlen) const {
   CurrentFunctionDescription =3D "string length function";
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
   if (IsStrnlen) {
     const Expr *maxlenExpr =3D CE->getArg(1);
-    SVal maxlenVal =3D state->getSVal(maxlenExpr);
+    SVal maxlenVal =3D state->getSVal(maxlenExpr, LCtx);
=20
-    const ProgramState *stateZeroSize, *stateNonZeroSize;
+    ProgramStateRef stateZeroSize, stateNonZeroSize;
     llvm::tie(stateZeroSize, stateNonZeroSize) =3D
       assumeZero(C, state, maxlenVal, maxlenExpr->getType());
=20
@@ -1066,7 +1138,7 @@
     // have to check the string itself.
     if (stateZeroSize) {
       SVal zero =3D C.getSValBuilder().makeZeroVal(CE->getType());
-      stateZeroSize =3D stateZeroSize->BindExpr(CE, zero);
+      stateZeroSize =3D stateZeroSize->BindExpr(CE, LCtx, zero);
       C.addTransition(stateZeroSize);
     }
=20
@@ -1080,7 +1152,7 @@
=20
   // Check that the string argument is non-null.
   const Expr *Arg =3D CE->getArg(0);
-  SVal ArgVal =3D state->getSVal(Arg);
+  SVal ArgVal =3D state->getSVal(Arg, LCtx);
=20
   state =3D checkNonNull(C, state, Arg, ArgVal);
=20
@@ -1104,13 +1176,13 @@
     // It's a little unfortunate to be getting this again,
     // but it's not that expensive...
     const Expr *maxlenExpr =3D CE->getArg(1);
-    SVal maxlenVal =3D state->getSVal(maxlenExpr);
+    SVal maxlenVal =3D state->getSVal(maxlenExpr, LCtx);
=20
     NonLoc *strLengthNL =3D dyn_cast<NonLoc>(&strLength);
     NonLoc *maxlenValNL =3D dyn_cast<NonLoc>(&maxlenVal);
=20
     if (strLengthNL && maxlenValNL) {
-      const ProgramState *stateStringTooLong, *stateStringNotTooLong;
+      ProgramStateRef stateStringTooLong, stateStringNotTooLong;
=20
       // Check if the strLength is greater than the maxlen.
       llvm::tie(stateStringTooLong, stateStringNotTooLong) =3D
@@ -1135,7 +1207,7 @@
       // All we know is the return value is the min of the string length
       // and the limit. This is better than nothing.
       unsigned Count =3D C.getCurrentBlockCount();
-      result =3D C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
+      result =3D C.getSValBuilder().getConjuredSymbolVal(NULL, CE, LCtx, C=
ount);
       NonLoc *resultNL =3D cast<NonLoc>(&result);
=20
       if (strLengthNL) {
@@ -1163,17 +1235,20 @@
     // value, so it can be used in constraints, at least.
     if (result.isUnknown()) {
       unsigned Count =3D C.getCurrentBlockCount();
-      result =3D C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
+      result =3D C.getSValBuilder().getConjuredSymbolVal(NULL, CE, LCtx, C=
ount);
     }
   }
=20
   // Bind the return value.
   assert(!result.isUnknown() && "Should have conjured a value by now");
-  state =3D state->BindExpr(CE, result);
+  state =3D state->BindExpr(CE, LCtx, result);
   C.addTransition(state);
 }
=20
 void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) con=
st {
+  if (CE->getNumArgs() < 2)
+    return;
+
   // char *strcpy(char *restrict dst, const char *restrict src);
   evalStrcpyCommon(C, CE,=20
                    /* returnEnd =3D */ false,=20
@@ -1182,6 +1257,9 @@
 }
=20
 void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) co=
nst {
+  if (CE->getNumArgs() < 3)
+    return;
+
   // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
   evalStrcpyCommon(C, CE,=20
                    /* returnEnd =3D */ false,=20
@@ -1190,6 +1268,9 @@
 }
=20
 void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) con=
st {
+  if (CE->getNumArgs() < 2)
+    return;
+
   // char *stpcpy(char *restrict dst, const char *restrict src);
   evalStrcpyCommon(C, CE,=20
                    /* returnEnd =3D */ true,=20
@@ -1198,6 +1279,9 @@
 }
=20
 void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) con=
st {
+  if (CE->getNumArgs() < 2)
+    return;
+
   //char *strcat(char *restrict s1, const char *restrict s2);
   evalStrcpyCommon(C, CE,=20
                    /* returnEnd =3D */ false,=20
@@ -1206,6 +1290,9 @@
 }
=20
 void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) co=
nst {
+  if (CE->getNumArgs() < 3)
+    return;
+
   //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
   evalStrcpyCommon(C, CE,=20
                    /* returnEnd =3D */ false,=20
@@ -1217,11 +1304,12 @@
                                       bool returnEnd, bool isBounded,
                                       bool isAppending) const {
   CurrentFunctionDescription =3D "string copy function";
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
   // Check that the destination is non-null.
   const Expr *Dst =3D CE->getArg(0);
-  SVal DstVal =3D state->getSVal(Dst);
+  SVal DstVal =3D state->getSVal(Dst, LCtx);
=20
   state =3D checkNonNull(C, state, Dst, DstVal);
   if (!state)
@@ -1229,7 +1317,7 @@
=20
   // Check that the source is non-null.
   const Expr *srcExpr =3D CE->getArg(1);
-  SVal srcVal =3D state->getSVal(srcExpr);
+  SVal srcVal =3D state->getSVal(srcExpr, LCtx);
   state =3D checkNonNull(C, state, srcExpr, srcVal);
   if (!state)
     return;
@@ -1256,7 +1344,7 @@
   if (isBounded) {
     // Get the max number of characters to copy.
     const Expr *lenExpr =3D CE->getArg(2);
-    SVal lenVal =3D state->getSVal(lenExpr);
+    SVal lenVal =3D state->getSVal(lenExpr, LCtx);
=20
     // Protect against misdeclared strncpy().
     lenVal =3D svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
@@ -1267,7 +1355,7 @@
     // If we know both values, we might be able to figure out how much
     // we're copying.
     if (strLengthNL && lenValNL) {
-      const ProgramState *stateSourceTooLong, *stateSourceNotTooLong;
+      ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
=20
       // Check if the max number to copy is less than the length of the sr=
c.
       // If the bound is equal to the source length, strncpy won't null-
@@ -1507,32 +1595,44 @@
   // overflow, we still need a result. Conjure a return value.
   if (returnEnd && Result.isUnknown()) {
     unsigned Count =3D C.getCurrentBlockCount();
-    Result =3D svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
+    Result =3D svalBuilder.getConjuredSymbolVal(NULL, CE, LCtx, Count);
   }
=20
   // Set the return value.
-  state =3D state->BindExpr(CE, Result);
+  state =3D state->BindExpr(CE, LCtx, Result);
   C.addTransition(state);
 }
=20
 void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) con=
st {
+  if (CE->getNumArgs() < 2)
+    return;
+
   //int strcmp(const char *s1, const char *s2);
   evalStrcmpCommon(C, CE, /* isBounded =3D */ false, /* ignoreCase =3D */ =
false);
 }
=20
 void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) co=
nst {
+  if (CE->getNumArgs() < 3)
+    return;
+
   //int strncmp(const char *s1, const char *s2, size_t n);
   evalStrcmpCommon(C, CE, /* isBounded =3D */ true, /* ignoreCase =3D */ f=
alse);
 }
=20
 void CStringChecker::evalStrcasecmp(CheckerContext &C,=20
                                     const CallExpr *CE) const {
+  if (CE->getNumArgs() < 2)
+    return;
+
   //int strcasecmp(const char *s1, const char *s2);
   evalStrcmpCommon(C, CE, /* isBounded =3D */ false, /* ignoreCase =3D */ =
true);
 }
=20
 void CStringChecker::evalStrncasecmp(CheckerContext &C,=20
                                      const CallExpr *CE) const {
+  if (CE->getNumArgs() < 3)
+    return;
+
   //int strncasecmp(const char *s1, const char *s2, size_t n);
   evalStrcmpCommon(C, CE, /* isBounded =3D */ true, /* ignoreCase =3D */ t=
rue);
 }
@@ -1540,18 +1640,19 @@
 void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *C=
E,
                                       bool isBounded, bool ignoreCase) con=
st {
   CurrentFunctionDescription =3D "string comparison function";
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
   // Check that the first string is non-null
   const Expr *s1 =3D CE->getArg(0);
-  SVal s1Val =3D state->getSVal(s1);
+  SVal s1Val =3D state->getSVal(s1, LCtx);
   state =3D checkNonNull(C, state, s1, s1Val);
   if (!state)
     return;
=20
   // Check that the second string is non-null.
   const Expr *s2 =3D CE->getArg(1);
-  SVal s2Val =3D state->getSVal(s2);
+  SVal s2Val =3D state->getSVal(s2, LCtx);
   state =3D checkNonNull(C, state, s2, s2Val);
   if (!state)
     return;
@@ -1575,13 +1676,14 @@
   // See if they are the same.
   SValBuilder &svalBuilder =3D C.getSValBuilder();
   DefinedOrUnknownSVal SameBuf =3D svalBuilder.evalEQ(state, LV, RV);
-  const ProgramState *StSameBuf, *StNotSameBuf;
+  ProgramStateRef StSameBuf, StNotSameBuf;
   llvm::tie(StSameBuf, StNotSameBuf) =3D state->assume(SameBuf);
=20
   // If the two arguments might be the same buffer, we know the result is =
0,
   // and we only need to check one size.
   if (StSameBuf) {
-    StSameBuf =3D StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getT=
ype()));
+    StSameBuf =3D StSameBuf->BindExpr(CE, LCtx,
+                                    svalBuilder.makeZeroVal(CE->getType())=
);
     C.addTransition(StSameBuf);
=20
     // If the two arguments are GUARANTEED to be the same, we're done!
@@ -1607,7 +1709,7 @@
     if (isBounded) {
       // Get the max number of characters to compare.
       const Expr *lenExpr =3D CE->getArg(2);
-      SVal lenVal =3D state->getSVal(lenExpr);
+      SVal lenVal =3D state->getSVal(lenExpr, LCtx);
=20
       // If the length is known, we can get the right substrings.
       if (const llvm::APSInt *len =3D svalBuilder.getKnownValue(state, len=
Val)) {
@@ -1644,15 +1746,15 @@
=20
       // Build the SVal of the comparison and bind the return value.
       SVal resultVal =3D svalBuilder.makeIntVal(result, CE->getType());
-      state =3D state->BindExpr(CE, resultVal);
+      state =3D state->BindExpr(CE, LCtx, resultVal);
     }
   }
=20
   if (!canComputeResult) {
     // Conjure a symbolic value. It's the best we can do.
     unsigned Count =3D C.getCurrentBlockCount();
-    SVal resultVal =3D svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
-    state =3D state->BindExpr(CE, resultVal);
+    SVal resultVal =3D svalBuilder.getConjuredSymbolVal(NULL, CE, LCtx, Co=
unt);
+    state =3D state->BindExpr(CE, LCtx, resultVal);
   }
=20
   // Record this as a possible path.
@@ -1664,42 +1766,47 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const=
 {
-  // Get the callee.  All the functions we care about are C functions
-  // with simple identifiers.
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  const FunctionDecl *FD =3D state->getSVal(Callee).getAsFunctionDecl();
+  const FunctionDecl *FDecl =3D C.getCalleeDecl(CE);
=20
-  if (!FD)
+  if (!FDecl)
     return false;
=20
-  // Get the name of the callee. If it's a builtin, strip off the prefix.
-  IdentifierInfo *II =3D FD->getIdentifier();
-  if (!II)   // if no identifier, not a simple C function
-    return false;
-  StringRef Name =3D II->getName();
-  if (Name.startswith("__builtin_"))
-    Name =3D Name.substr(10);
-
-  FnCheck evalFunction =3D llvm::StringSwitch<FnCheck>(Name)
-    .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
-    .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
-    .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
-    .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
-    .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
-    .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
-    .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
-    .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
-    .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
-    .Case("strlen", &CStringChecker::evalstrLength)
-    .Case("strnlen", &CStringChecker::evalstrnLength)
-    .Case("strcmp", &CStringChecker::evalStrcmp)
-    .Case("strncmp", &CStringChecker::evalStrncmp)
-    .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
-    .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
-    .Case("bcopy", &CStringChecker::evalBcopy)
-    .Default(NULL);
-
+  FnCheck evalFunction =3D 0;
+  if (C.isCLibraryFunction(FDecl, "memcpy"))
+    evalFunction =3D  &CStringChecker::evalMemcpy;
+  else if (C.isCLibraryFunction(FDecl, "mempcpy"))
+    evalFunction =3D  &CStringChecker::evalMempcpy;
+  else if (C.isCLibraryFunction(FDecl, "memcmp"))
+    evalFunction =3D  &CStringChecker::evalMemcmp;
+  else if (C.isCLibraryFunction(FDecl, "memmove"))
+    evalFunction =3D  &CStringChecker::evalMemmove;
+  else if (C.isCLibraryFunction(FDecl, "strcpy"))
+    evalFunction =3D  &CStringChecker::evalStrcpy;
+  else if (C.isCLibraryFunction(FDecl, "strncpy"))
+    evalFunction =3D  &CStringChecker::evalStrncpy;
+  else if (C.isCLibraryFunction(FDecl, "stpcpy"))
+    evalFunction =3D  &CStringChecker::evalStpcpy;
+  else if (C.isCLibraryFunction(FDecl, "strcat"))
+    evalFunction =3D  &CStringChecker::evalStrcat;
+  else if (C.isCLibraryFunction(FDecl, "strncat"))
+    evalFunction =3D  &CStringChecker::evalStrncat;
+  else if (C.isCLibraryFunction(FDecl, "strlen"))
+    evalFunction =3D  &CStringChecker::evalstrLength;
+  else if (C.isCLibraryFunction(FDecl, "strnlen"))
+    evalFunction =3D  &CStringChecker::evalstrnLength;
+  else if (C.isCLibraryFunction(FDecl, "strcmp"))
+    evalFunction =3D  &CStringChecker::evalStrcmp;
+  else if (C.isCLibraryFunction(FDecl, "strncmp"))
+    evalFunction =3D  &CStringChecker::evalStrncmp;
+  else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
+    evalFunction =3D  &CStringChecker::evalStrcasecmp;
+  else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
+    evalFunction =3D  &CStringChecker::evalStrncasecmp;
+  else if (C.isCLibraryFunction(FDecl, "bcopy"))
+    evalFunction =3D  &CStringChecker::evalBcopy;
+  else if (C.isCLibraryFunction(FDecl, "bcmp"))
+    evalFunction =3D  &CStringChecker::evalMemcmp;
+ =20
   // If the callee isn't a string function, let another checker handle it.
   if (!evalFunction)
     return false;
@@ -1710,12 +1817,22 @@
=20
   // Check and evaluate the call.
   (this->*evalFunction)(C, CE);
+
+  // If the evaluate call resulted in no change, chain to the next eval ca=
ll
+  // handler.
+  // Note, the custom CString evaluation calls assume that basic safety
+  // properties are held. However, if the user chooses to turn off some of=
 these
+  // checks, we ignore the issues and leave the call evaluation to a gener=
ic
+  // handler.
+  if (!C.isDifferent())
+    return false;
+
   return true;
 }
=20
 void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) c=
onst {
   // Record string length for char a[] =3D "abc";
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   for (DeclStmt::const_decl_iterator I =3D DS->decl_begin(), E =3D DS->dec=
l_end();
        I !=3D E; ++I) {
@@ -1733,12 +1850,12 @@
     if (!isa<StringLiteral>(Init))
       continue;
=20
-    Loc VarLoc =3D state->getLValue(D, C.getPredecessor()->getLocationCont=
ext());
+    Loc VarLoc =3D state->getLValue(D, C.getLocationContext());
     const MemRegion *MR =3D VarLoc.getAsRegion();
     if (!MR)
       continue;
=20
-    SVal StrVal =3D state->getSVal(Init);
+    SVal StrVal =3D state->getSVal(Init, C.getLocationContext());
     assert(StrVal.isValid() && "Initializer string is unknown or undefined=
");
     DefinedOrUnknownSVal strLength
       =3D cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrV=
al));
@@ -1749,16 +1866,17 @@
   C.addTransition(state);
 }
=20
-bool CStringChecker::wantsRegionChangeUpdate(const ProgramState *state) co=
nst {
+bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
   CStringLength::EntryMap Entries =3D state->get<CStringLength>();
   return !Entries.isEmpty();
 }
=20
-const ProgramState *
-CStringChecker::checkRegionChanges(const ProgramState *state,
+ProgramStateRef=20
+CStringChecker::checkRegionChanges(ProgramStateRef state,
                                    const StoreManager::InvalidatedSymbols =
*,
                                    ArrayRef<const MemRegion *> ExplicitReg=
ions,
-                                   ArrayRef<const MemRegion *> Regions) co=
nst {
+                                   ArrayRef<const MemRegion *> Regions,
+                                   const CallOrObjCMessage *Call) const {
   CStringLength::EntryMap Entries =3D state->get<CStringLength>();
   if (Entries.isEmpty())
     return state;
@@ -1806,7 +1924,7 @@
   return state->set<CStringLength>(Entries);
 }
=20
-void CStringChecker::checkLiveSymbols(const ProgramState *state,
+void CStringChecker::checkLiveSymbols(ProgramStateRef state,
                                       SymbolReaper &SR) const {
   // Mark all symbols in our string length map as valid.
   CStringLength::EntryMap Entries =3D state->get<CStringLength>();
@@ -1815,8 +1933,8 @@
        I !=3D E; ++I) {
     SVal Len =3D I.getData();
=20
-    for (SVal::symbol_iterator si =3D Len.symbol_begin(), se =3D Len.symbo=
l_end();
-         si !=3D se; ++si)
+    for (SymExpr::symbol_iterator si =3D Len.symbol_begin(),
+                                  se =3D Len.symbol_end(); si !=3D se; ++s=
i)
       SR.markInUse(*si);
   }
 }
@@ -1826,7 +1944,7 @@
   if (!SR.hasDeadSymbols())
     return;
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   CStringLength::EntryMap Entries =3D state->get<CStringLength>();
   if (Entries.isEmpty())
     return;
@@ -1842,9 +1960,22 @@
   }
=20
   state =3D state->set<CStringLength>(Entries);
-  C.generateNode(state);
+  C.addTransition(state);
 }
=20
-void ento::registerCStringChecker(CheckerManager &mgr) {
-  mgr.registerChecker<CStringChecker>();
+#define REGISTER_CHECKER(name) \
+void ento::register##name(CheckerManager &mgr) {\
+  static CStringChecker *TheChecker =3D 0; \
+  if (TheChecker =3D=3D 0) \
+    TheChecker =3D mgr.registerChecker<CStringChecker>(); \
+  TheChecker->Filter.Check##name =3D true; \
 }
+
+REGISTER_CHECKER(CStringNullArg)
+REGISTER_CHECKER(CStringOutOfBounds)
+REGISTER_CHECKER(CStringBufferOverlap)
+REGISTER_CHECKER(CStringNotNullTerm)
+
+void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
+  registerCStringNullArg(Mgr);
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CallAndMessageChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CallAndMess=
ageChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CallAndMess=
ageChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/Basic/TargetInfo.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -27,12 +28,13 @@
 namespace {
 class CallAndMessageChecker
   : public Checker< check::PreStmt<CallExpr>, check::PreObjCMessage > {
-  mutable llvm::OwningPtr<BugType> BT_call_null;
-  mutable llvm::OwningPtr<BugType> BT_call_undef;
-  mutable llvm::OwningPtr<BugType> BT_call_arg;
-  mutable llvm::OwningPtr<BugType> BT_msg_undef;
-  mutable llvm::OwningPtr<BugType> BT_msg_arg;
-  mutable llvm::OwningPtr<BugType> BT_msg_ret;
+  mutable OwningPtr<BugType> BT_call_null;
+  mutable OwningPtr<BugType> BT_call_undef;
+  mutable OwningPtr<BugType> BT_call_arg;
+  mutable OwningPtr<BugType> BT_msg_undef;
+  mutable OwningPtr<BugType> BT_objc_prop_undef;
+  mutable OwningPtr<BugType> BT_msg_arg;
+  mutable OwningPtr<BugType> BT_msg_ret;
 public:
=20
   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
@@ -40,19 +42,22 @@
=20
 private:
   static void PreVisitProcessArgs(CheckerContext &C,CallOrObjCMessage call=
OrMsg,
-                             const char *BT_desc, llvm::OwningPtr<BugType>=
 &BT);
+                             const char *BT_desc, OwningPtr<BugType> &BT);
   static bool PreVisitProcessArg(CheckerContext &C, SVal V,SourceRange arg=
Range,
-          const Expr *argEx, const char *BT_desc, llvm::OwningPtr<BugType>=
 &BT);
+                                 const Expr *argEx,
+                                 const bool checkUninitFields,
+                                 const char *BT_desc,
+                                 OwningPtr<BugType> &BT);
=20
   static void EmitBadCall(BugType *BT, CheckerContext &C, const CallExpr *=
CE);
   void emitNilReceiverBug(CheckerContext &C, const ObjCMessage &msg,
                           ExplodedNode *N) const;
=20
   void HandleNilReceiver(CheckerContext &C,
-                         const ProgramState *state,
+                         ProgramStateRef state,
                          ObjCMessage msg) const;
=20
-  static void LazyInit_BT(const char *desc, llvm::OwningPtr<BugType> &BT) {
+  static void LazyInit_BT(const char *desc, OwningPtr<BugType> &BT) {
     if (!BT)
       BT.reset(new BuiltinBug(desc));
   }
@@ -67,17 +72,27 @@
=20
   BugReport *R =3D new BugReport(*BT, BT->getName(), N);
   R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                               bugreporter::GetCalleeExpr(N)));
+                               bugreporter::GetCalleeExpr(N), R));
   C.EmitReport(R);
 }
=20
 void CallAndMessageChecker::PreVisitProcessArgs(CheckerContext &C,
                                                 CallOrObjCMessage callOrMs=
g,
                                                 const char *BT_desc,
-                                                llvm::OwningPtr<BugType> &=
BT) {
+                                                OwningPtr<BugType> &BT) {
+  // Don't check for uninitialized field values in arguments if the
+  // caller has a body that is available and we have the chance to inline =
it.
+  // This is a hack, but is a reasonable compromise betweens sometimes war=
ning
+  // and sometimes not depending on if we decide to inline a function.
+  const Decl *D =3D callOrMsg.getDecl();
+  const bool checkUninitFields =3D
+    !(C.getAnalysisManager().shouldInlineCall() &&
+      (D && D->getBody()));
+ =20
   for (unsigned i =3D 0, e =3D callOrMsg.getNumArgs(); i !=3D e; ++i)
     if (PreVisitProcessArg(C, callOrMsg.getArgSVal(i),
                            callOrMsg.getArgSourceRange(i), callOrMsg.getAr=
g(i),
+                           checkUninitFields,
                            BT_desc, BT))
       return;
 }
@@ -85,9 +100,9 @@
 bool CallAndMessageChecker::PreVisitProcessArg(CheckerContext &C,
                                                SVal V, SourceRange argRang=
e,
                                                const Expr *argEx,
+                                               const bool checkUninitField=
s,
                                                const char *BT_desc,
-                                               llvm::OwningPtr<BugType> &B=
T) {
-
+                                               OwningPtr<BugType> &BT) {
   if (V.isUndef()) {
     if (ExplodedNode *N =3D C.generateSink()) {
       LazyInit_BT(BT_desc, BT);
@@ -96,12 +111,16 @@
       BugReport *R =3D new BugReport(*BT, BT->getName(), N);
       R->addRange(argRange);
       if (argEx)
-        R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, argE=
x));
+        R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, argE=
x,
+                                                                   R));
       C.EmitReport(R);
     }
     return true;
   }
=20
+  if (!checkUninitFields)
+    return false;
+ =20
   if (const nonloc::LazyCompoundVal *LV =3D
         dyn_cast<nonloc::LazyCompoundVal>(&V)) {
=20
@@ -133,7 +152,7 @@
                 return true;
             }
             else {
-              const SVal &V =3D StoreMgr.Retrieve(store, loc::MemRegionVal=
(FR));
+              const SVal &V =3D StoreMgr.getBinding(store, loc::MemRegionV=
al(FR));
               if (V.isUndef())
                 return true;
             }
@@ -154,7 +173,7 @@
     if (F.Find(D->getRegion())) {
       if (ExplodedNode *N =3D C.generateSink()) {
         LazyInit_BT(BT_desc, BT);
-        llvm::SmallString<512> Str;
+        SmallString<512> Str;
         llvm::raw_svector_ostream os(Str);
         os << "Passed-by-value struct argument contains uninitialized data=
";
=20
@@ -193,7 +212,8 @@
                                          CheckerContext &C) const{
=20
   const Expr *Callee =3D CE->getCallee()->IgnoreParens();
-  SVal L =3D C.getState()->getSVal(Callee);
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal L =3D C.getState()->getSVal(Callee, LCtx);
=20
   if (L.isUndef()) {
     if (!BT_call_undef)
@@ -210,7 +230,7 @@
     EmitBadCall(BT_call_null.get(), C, CE);
   }
=20
-  PreVisitProcessArgs(C, CallOrObjCMessage(CE, C.getState()),
+  PreVisitProcessArgs(C, CallOrObjCMessage(CE, C.getState(), LCtx),
                       "Function call argument is an uninitialized value",
                       BT_call_arg);
 }
@@ -218,21 +238,33 @@
 void CallAndMessageChecker::checkPreObjCMessage(ObjCMessage msg,
                                                 CheckerContext &C) const {
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
   // FIXME: Handle 'super'?
   if (const Expr *receiver =3D msg.getInstanceReceiver()) {
-    SVal recVal =3D state->getSVal(receiver);
+    SVal recVal =3D state->getSVal(receiver, LCtx);
     if (recVal.isUndef()) {
       if (ExplodedNode *N =3D C.generateSink()) {
-        if (!BT_msg_undef)
-          BT_msg_undef.reset(new BuiltinBug("Receiver in message expressio=
n is "
-                                            "an uninitialized value"));
+        BugType *BT =3D 0;
+        if (msg.isPureMessageExpr()) {
+          if (!BT_msg_undef)
+            BT_msg_undef.reset(new BuiltinBug("Receiver in message express=
ion "
+                                              "is an uninitialized value")=
);
+          BT =3D BT_msg_undef.get();
+        }
+        else {
+          if (!BT_objc_prop_undef)
+            BT_objc_prop_undef.reset(new BuiltinBug("Property access on an=
 "
+                                              "uninitialized object pointe=
r"));
+          BT =3D BT_objc_prop_undef.get();
+        }
         BugReport *R =3D
-          new BugReport(*BT_msg_undef, BT_msg_undef->getName(), N);
+          new BugReport(*BT, BT->getName(), N);
         R->addRange(receiver->getSourceRange());
         R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                                                                   receive=
r));
+                                                                   receive=
r,
+                                                                   R));
         C.EmitReport(R);
       }
       return;
@@ -240,7 +272,7 @@
       // Bifurcate the state into nil and non-nil ones.
       DefinedOrUnknownSVal receiverVal =3D cast<DefinedOrUnknownSVal>(recV=
al);
  =20
-      const ProgramState *notNilState, *nilState;
+      ProgramStateRef notNilState, nilState;
       llvm::tie(notNilState, nilState) =3D state->assume(receiverVal);
  =20
       // Handle receiver must be nil.
@@ -255,7 +287,8 @@
                      "Argument for property setter is an uninitialized val=
ue"
                    : "Argument in message expression is an uninitialized v=
alue";
   // Check for any arguments that are uninitialized/undefined.
-  PreVisitProcessArgs(C, CallOrObjCMessage(msg, state), bugDesc, BT_msg_ar=
g);
+  PreVisitProcessArgs(C, CallOrObjCMessage(msg, state, LCtx),
+                      bugDesc, BT_msg_arg);
 }
=20
 void CallAndMessageChecker::emitNilReceiverBug(CheckerContext &C,
@@ -267,7 +300,7 @@
       new BuiltinBug("Receiver in message expression is "
                      "'nil' and returns a garbage value"));
=20
-  llvm::SmallString<200> buf;
+  SmallString<200> buf;
   llvm::raw_svector_ostream os(buf);
   os << "The receiver of message '" << msg.getSelector().getAsString()
      << "' is nil and returns a value of type '"
@@ -277,48 +310,39 @@
   if (const Expr *receiver =3D msg.getInstanceReceiver()) {
     report->addRange(receiver->getSourceRange());
     report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                                                                    receiv=
er));
+                                                                    receiv=
er,
+                                                                    report=
));
   }
   C.EmitReport(report);
 }
=20
 static bool supportsNilWithFloatRet(const llvm::Triple &triple) {
-  return triple.getVendor() =3D=3D llvm::Triple::Apple &&
-         (!triple.isMacOSXVersionLT(10,5) ||
-          triple.getArch() =3D=3D llvm::Triple::arm ||=20
-          triple.getArch() =3D=3D llvm::Triple::thumb);
+  return (triple.getVendor() =3D=3D llvm::Triple::Apple &&
+          (triple.getOS() =3D=3D llvm::Triple::IOS ||
+           !triple.isMacOSXVersionLT(10,5)));
 }
=20
 void CallAndMessageChecker::HandleNilReceiver(CheckerContext &C,
-                                              const ProgramState *state,
+                                              ProgramStateRef state,
                                               ObjCMessage msg) const {
   ASTContext &Ctx =3D C.getASTContext();
=20
   // Check the return type of the message expression.  A message to nil wi=
ll
   // return different values depending on the return type and the architec=
ture.
   QualType RetTy =3D msg.getType(Ctx);
-
   CanQualType CanRetTy =3D Ctx.getCanonicalType(RetTy);
+  const LocationContext *LCtx =3D C.getLocationContext();
=20
   if (CanRetTy->isStructureOrClassType()) {
-    // FIXME: At some point we shouldn't rely on isConsumedExpr(), but ins=
tead
-    // have the "use of undefined value" be smarter about where the
-    // undefined value came from.
-    if (C.getPredecessor()->getParentMap().isConsumedExpr(msg.getOriginExp=
r())){
-      if (ExplodedNode *N =3D C.generateSink(state))
-        emitNilReceiverBug(C, msg, N);
-      return;
-    }
-
-    // The result is not consumed by a surrounding expression.  Just propa=
gate
-    // the current state.
-    C.addTransition(state);
+    // Structure returns are safe since the compiler zeroes them out.
+    SVal V =3D C.getSValBuilder().makeZeroVal(msg.getType(Ctx));
+    C.addTransition(state->BindExpr(msg.getMessageExpr(), LCtx, V));
     return;
   }
=20
-  // Other cases: check if the return type is smaller than void*.
-  if (CanRetTy !=3D Ctx.VoidTy &&
-      C.getPredecessor()->getParentMap().isConsumedExpr(msg.getOriginExpr(=
))) {
+  // Other cases: check if sizeof(return type) > sizeof(void*)
+  if (CanRetTy !=3D Ctx.VoidTy && C.getLocationContext()->getParentMap()
+                                  .isConsumedExpr(msg.getMessageExpr())) {
     // Compute: sizeof(void *) and sizeof(return type)
     const uint64_t voidPtrSize =3D Ctx.getTypeSize(Ctx.VoidPtrTy);
     const uint64_t returnTypeSize =3D Ctx.getTypeSize(CanRetTy);
@@ -349,7 +373,7 @@
     // of this case unless we have *a lot* more knowledge.
     //
     SVal V =3D C.getSValBuilder().makeZeroVal(msg.getType(Ctx));
-    C.generateNode(state->BindExpr(msg.getOriginExpr(), V));
+    C.addTransition(state->BindExpr(msg.getMessageExpr(), LCtx, V));
     return;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CastSizeChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CastSizeChe=
cker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CastSizeChe=
cker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
=20
 namespace {
 class CastSizeChecker : public Checker< check::PreStmt<CastExpr> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
 public:
   void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
 };
@@ -44,8 +44,8 @@
   if (ToPointeeTy->isIncompleteType())
     return;
=20
-  const ProgramState *state =3D C.getState();
-  const MemRegion *R =3D state->getSVal(E).getAsRegion();
+  ProgramStateRef state =3D C.getState();
+  const MemRegion *R =3D state->getSVal(E, C.getLocationContext()).getAsRe=
gion();
   if (R =3D=3D 0)
     return;
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CastToStructChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CastToStruc=
tChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CastToStruc=
tChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
=20
 namespace {
 class CastToStructChecker : public Checker< check::PreStmt<CastExpr> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
=20
 public:
   void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
@@ -56,7 +56,7 @@
=20
   // Now the cast-to-type is struct pointer, the original type is not void=
*.
   if (!OrigPointeeTy->isRecordType()) {
-    if (ExplodedNode *N =3D C.generateNode()) {
+    if (ExplodedNode *N =3D C.addTransition()) {
       if (!BT)
         BT.reset(new BuiltinBug("Cast from non-struct type to struct type",
                             "Casting a non-structure type to a structure t=
ype "
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CheckObjCDealloc.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCDe=
alloc.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCDe=
alloc.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -177,9 +177,10 @@
=20
     std::string buf;
     llvm::raw_string_ostream os(buf);
-    os << "Objective-C class '" << D << "' lacks a 'dealloc' instance meth=
od";
+    os << "Objective-C class '" << *D << "' lacks a 'dealloc' instance met=
hod";
=20
-    BR.EmitBasicReport(name, os.str(), DLoc);
+    BR.EmitBasicReport(D, name, categories::CoreFoundationObjectiveC,
+                       os.str(), DLoc);
     return;
   }
=20
@@ -192,11 +193,12 @@
=20
     std::string buf;
     llvm::raw_string_ostream os(buf);
-    os << "The 'dealloc' instance method in Objective-C class '" << D
+    os << "The 'dealloc' instance method in Objective-C class '" << *D
        << "' does not send a 'dealloc' message to its super class"
            " (missing [super dealloc])";
=20
-    BR.EmitBasicReport(name, os.str(), DLoc);
+    BR.EmitBasicReport(MD, name, categories::CoreFoundationObjectiveC,
+                       os.str(), DLoc);
     return;
   }
=20
@@ -236,9 +238,7 @@
     bool requiresRelease =3D PD->getSetterKind() !=3D ObjCPropertyDecl::As=
sign;
     if (scan_ivar_release(MD->getBody(), ID, PD, RS, SelfII, Ctx)
        !=3D requiresRelease) {
-      const char *name;
-      const char* category =3D "Memory (Core Foundation/Objective-C)";
-
+      const char *name =3D 0;
       std::string buf;
       llvm::raw_string_ostream os(buf);
=20
@@ -263,7 +263,8 @@
       PathDiagnosticLocation SDLoc =3D
         PathDiagnosticLocation::createBegin((*I), BR.getSourceManager());
=20
-      BR.EmitBasicReport(name, category, os.str(), SDLoc);
+      BR.EmitBasicReport(MD, name, categories::CoreFoundationObjectiveC,
+                         os.str(), SDLoc);
     }
   }
 }
@@ -278,9 +279,9 @@
 public:
   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& mgr,
                     BugReporter &BR) const {
-    if (mgr.getLangOptions().getGC() =3D=3D LangOptions::GCOnly)
+    if (mgr.getLangOpts().getGC() =3D=3D LangOptions::GCOnly)
       return;
-    checkObjCDealloc(cast<ObjCImplementationDecl>(D), mgr.getLangOptions()=
, BR);
+    checkObjCDealloc(cast<ObjCImplementationDecl>(D), mgr.getLangOpts(), B=
R);
   }
 };
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CheckObjCInstMethSignature.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCIn=
stMethSignature.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckObjCIn=
stMethSignature.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -70,7 +70,9 @@
       PathDiagnosticLocation::createBegin(MethDerived,
                                           BR.getSourceManager());
=20
-    BR.EmitBasicReport("Incompatible instance method return type",
+    BR.EmitBasicReport(MethDerived,
+                       "Incompatible instance method return type",
+                       categories::CoreFoundationObjectiveC,
                        os.str(), MethDLoc);
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckSecuri=
tySyntaxOnly.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckSecuri=
tySyntaxOnly.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/raw_ostream.h"
=20
@@ -34,18 +35,40 @@
 }
=20
 namespace {
+struct DefaultBool {
+  bool val;
+  DefaultBool() : val(false) {}
+  operator bool() const { return val; }
+  DefaultBool &operator=3D(bool b) { val =3D b; return *this; }
+};
+ =20
+struct ChecksFilter {
+  DefaultBool check_gets;
+  DefaultBool check_getpw;
+  DefaultBool check_mktemp;
+  DefaultBool check_mkstemp;
+  DefaultBool check_strcpy;
+  DefaultBool check_rand;
+  DefaultBool check_vfork;
+  DefaultBool check_FloatLoopCounter;
+  DefaultBool check_UncheckedReturn;
+};
+ =20
 class WalkAST : public StmtVisitor<WalkAST> {
   BugReporter &BR;
-  AnalysisContext* AC;
+  AnalysisDeclContext* AC;
   enum { num_setids =3D 6 };
   IdentifierInfo *II_setid[num_setids];
=20
   const bool CheckRand;
+  const ChecksFilter &filter;
=20
 public:
-  WalkAST(BugReporter &br, AnalysisContext* ac)
+  WalkAST(BugReporter &br, AnalysisDeclContext* ac,
+          const ChecksFilter &f)
   : BR(br), AC(ac), II_setid(),
-    CheckRand(isArc4RandomAvailable(BR.getContext())) {}
+    CheckRand(isArc4RandomAvailable(BR.getContext())),
+    filter(f) {}
=20
   // Statement visitor methods.
   void VisitCallExpr(CallExpr *CE);
@@ -66,6 +89,7 @@
   void checkCall_gets(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD);
+  void checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD);
   void checkCall_rand(const CallExpr *CE, const FunctionDecl *FD);
@@ -105,6 +129,9 @@
     .Case("gets", &WalkAST::checkCall_gets)
     .Case("getpw", &WalkAST::checkCall_getpw)
     .Case("mktemp", &WalkAST::checkCall_mktemp)
+    .Case("mkstemp", &WalkAST::checkCall_mkstemp)
+    .Case("mkdtemp", &WalkAST::checkCall_mkstemp)
+    .Case("mkstemps", &WalkAST::checkCall_mkstemp)
     .Cases("strcpy", "__strcpy_chk", &WalkAST::checkCall_strcpy)
     .Cases("strcat", "__strcat_chk", &WalkAST::checkCall_strcat)
     .Case("drand48", &WalkAST::checkCall_rand)
@@ -186,6 +213,9 @@
 ///  CERT: FLP30-C, FLP30-CPP.
 ///
 void WalkAST::checkLoopConditionForFloat(const ForStmt *FS) {
+  if (!filter.check_FloatLoopCounter)
+    return;
+
   // Does the loop have a condition?
   const Expr *condition =3D FS->getCond();
=20
@@ -242,7 +272,7 @@
   const DeclRefExpr *drCond =3D vdLHS =3D=3D drInc->getDecl() ? drLHS : dr=
RHS;
=20
   SmallVector<SourceRange, 2> ranges;
-  llvm::SmallString<256> sbuf;
+  SmallString<256> sbuf;
   llvm::raw_svector_ostream os(sbuf);
=20
   os << "Variable '" << drCond->getDecl()->getName()
@@ -256,7 +286,8 @@
=20
   PathDiagnosticLocation FSLoc =3D
     PathDiagnosticLocation::createBegin(FS, BR.getSourceManager(), AC);
-  BR.EmitBasicReport(bugType, "Security", os.str(),
+  BR.EmitBasicReport(AC->getDecl(),
+                     bugType, "Security", os.str(),
                      FSLoc, ranges.data(), ranges.size());
 }
=20
@@ -268,6 +299,9 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void WalkAST::checkCall_gets(const CallExpr *CE, const FunctionDecl *FD) {
+  if (!filter.check_gets)
+    return;
+ =20
   const FunctionProtoType *FPT
     =3D dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
   if (!FPT)
@@ -289,7 +323,8 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport("Potential buffer overflow in call to 'gets'",
+  BR.EmitBasicReport(AC->getDecl(),
+                     "Potential buffer overflow in call to 'gets'",
                      "Security",
                      "Call to function 'gets' is extremely insecure as it =
can "
                      "always result in a buffer overflow",
@@ -302,6 +337,9 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void WalkAST::checkCall_getpw(const CallExpr *CE, const FunctionDecl *FD) {
+  if (!filter.check_getpw)
+    return;
+
   const FunctionProtoType *FPT
     =3D dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
   if (!FPT)
@@ -327,7 +365,8 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport("Potential buffer overflow in call to 'getpw'",
+  BR.EmitBasicReport(AC->getDecl(),
+                     "Potential buffer overflow in call to 'getpw'",
                      "Security",
                      "The getpw() function is dangerous as it may overflow=
 the "
                      "provided buffer. It is obsoleted by getpwuid().",
@@ -335,11 +374,18 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// Check: Any use of 'mktemp' is insecure.It is obsoleted by mkstemp().
+// Check: Any use of 'mktemp' is insecure.  It is obsoleted by mkstemp().
 // CWE-377: Insecure Temporary File
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void WalkAST::checkCall_mktemp(const CallExpr *CE, const FunctionDecl *FD)=
 {
+  if (!filter.check_mktemp) {
+    // Fall back to the security check of looking for enough 'X's in the
+    // format string, since that is a less severe warning.
+    checkCall_mkstemp(CE, FD);
+    return;
+  }
+
   const FunctionProtoType *FPT
     =3D dyn_cast<FunctionProtoType>(FD->getType().IgnoreParens());
   if(!FPT)
@@ -362,13 +408,98 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport("Potential insecure temporary file in call 'mktemp'",
+  BR.EmitBasicReport(AC->getDecl(),
+                     "Potential insecure temporary file in call 'mktemp'",
                      "Security",
                      "Call to function 'mktemp' is insecure as it always "
-                     "creates or uses insecure temporary file.  Use 'mkste=
mp' instead",
+                     "creates or uses insecure temporary file.  Use 'mkste=
mp' "
+                     "instead",
                      CELoc, &R, 1);
 }
=20
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Check: Use of 'mkstemp', 'mktemp', 'mkdtemp' should contain at least 6 =
X's.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+void WalkAST::checkCall_mkstemp(const CallExpr *CE, const FunctionDecl *FD=
) {
+  if (!filter.check_mkstemp)
+    return;
+
+  StringRef Name =3D FD->getIdentifier()->getName();
+  std::pair<signed, signed> ArgSuffix =3D
+    llvm::StringSwitch<std::pair<signed, signed> >(Name)
+      .Case("mktemp", std::make_pair(0,-1))
+      .Case("mkstemp", std::make_pair(0,-1))
+      .Case("mkdtemp", std::make_pair(0,-1))
+      .Case("mkstemps", std::make_pair(0,1))
+      .Default(std::make_pair(-1, -1));
+ =20
+  assert(ArgSuffix.first >=3D 0 && "Unsupported function");
+
+  // Check if the number of arguments is consistent with out expectations.
+  unsigned numArgs =3D CE->getNumArgs();
+  if ((signed) numArgs <=3D ArgSuffix.first)
+    return;
+ =20
+  const StringLiteral *strArg =3D
+    dyn_cast<StringLiteral>(CE->getArg((unsigned)ArgSuffix.first)
+                              ->IgnoreParenImpCasts());
+ =20
+  // Currently we only handle string literals.  It is possible to do bette=
r,
+  // either by looking at references to const variables, or by doing real
+  // flow analysis.
+  if (!strArg || strArg->getCharByteWidth() !=3D 1)
+    return;
+
+  // Count the number of X's, taking into account a possible cutoff suffix.
+  StringRef str =3D strArg->getString();
+  unsigned numX =3D 0;
+  unsigned n =3D str.size();
+
+  // Take into account the suffix.
+  unsigned suffix =3D 0;
+  if (ArgSuffix.second >=3D 0) {
+    const Expr *suffixEx =3D CE->getArg((unsigned)ArgSuffix.second);
+    llvm::APSInt Result;
+    if (!suffixEx->EvaluateAsInt(Result, BR.getContext()))
+      return;
+    // FIXME: Issue a warning.
+    if (Result.isNegative())
+      return;
+    suffix =3D (unsigned) Result.getZExtValue();
+    n =3D (n > suffix) ? n - suffix : 0;
+  }
+ =20
+  for (unsigned i =3D 0; i < n; ++i)
+    if (str[i] =3D=3D 'X') ++numX;
+ =20
+  if (numX >=3D 6)
+    return;
+ =20
+  // Issue a warning.
+  SourceRange R =3D strArg->getSourceRange();
+  PathDiagnosticLocation CELoc =3D
+    PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
+  SmallString<512> buf;
+  llvm::raw_svector_ostream out(buf);
+  out << "Call to '" << Name << "' should have at least 6 'X's in the"
+    " format string to be secure (" << numX << " 'X'";
+  if (numX !=3D 1)
+    out << 's';
+  out << " seen";
+  if (suffix) {
+    out << ", " << suffix << " character";
+    if (suffix > 1)
+      out << 's';
+    out << " used as a suffix";
+  }
+  out << ')';
+  BR.EmitBasicReport(AC->getDecl(),
+                     "Insecure temporary file creation", "Security",
+                     out.str(), CELoc, &R, 1);
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Check: Any use of 'strcpy' is insecure.
 //
@@ -376,6 +507,9 @@
 // the Bounds of a Memory Buffer=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD)=
 {
+  if (!filter.check_strcpy)
+    return;
+ =20
   if (!checkCall_strCommon(CE, FD))
     return;
=20
@@ -383,13 +517,14 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport("Potential insecure memory buffer bounds restriction =
in "
+  BR.EmitBasicReport(AC->getDecl(),
+                     "Potential insecure memory buffer bounds restriction =
in "
                      "call 'strcpy'",
                      "Security",
                      "Call to function 'strcpy' is insecure as it does not=
 "
-		     "provide bounding of the memory buffer. Replace "
-		     "unbounded copy functions with analogous functions that "
-		     "support length arguments such as 'strncpy'. CWE-119.",
+                     "provide bounding of the memory buffer. Replace "
+                     "unbounded copy functions with analogous functions th=
at "
+                     "support length arguments such as 'strlcpy'. CWE-119.=
",
                      CELoc, &R, 1);
 }
=20
@@ -400,6 +535,9 @@
 // the Bounds of a Memory Buffer=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 void WalkAST::checkCall_strcat(const CallExpr *CE, const FunctionDecl *FD)=
 {
+  if (!filter.check_strcpy)
+    return;
+
   if (!checkCall_strCommon(CE, FD))
     return;
=20
@@ -407,13 +545,14 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport("Potential insecure memory buffer bounds restriction =
in "
-		     "call 'strcat'",
-		     "Security",
-		     "Call to function 'strcat' is insecure as it does not "
-		     "provide bounding of the memory buffer. Replace "
-		     "unbounded copy functions with analogous functions that "
-		     "support length arguments such as 'strncat'. CWE-119.",
+  BR.EmitBasicReport(AC->getDecl(),
+                     "Potential insecure memory buffer bounds restriction =
in "
+                     "call 'strcat'",
+                     "Security",
+                     "Call to function 'strcat' is insecure as it does not=
 "
+                     "provide bounding of the memory buffer. Replace "
+                     "unbounded copy functions with analogous functions th=
at "
+                     "support length arguments such as 'strlcat'. CWE-119.=
",
                      CELoc, &R, 1);
 }
=20
@@ -453,7 +592,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void WalkAST::checkCall_rand(const CallExpr *CE, const FunctionDecl *FD) {
-  if (!CheckRand)
+  if (!filter.check_rand || !CheckRand)
     return;
=20
   const FunctionProtoType *FTP
@@ -475,11 +614,11 @@
     return;
=20
   // Issue a warning.
-  llvm::SmallString<256> buf1;
+  SmallString<256> buf1;
   llvm::raw_svector_ostream os1(buf1);
   os1 << '\'' << *FD << "' is a poor random number generator";
=20
-  llvm::SmallString<256> buf2;
+  SmallString<256> buf2;
   llvm::raw_svector_ostream os2(buf2);
   os2 << "Function '" << *FD
       << "' is obsolete because it implements a poor random number generat=
or."
@@ -488,7 +627,8 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport(os1.str(), "Security", os2.str(), CELoc, &R, 1);
+  BR.EmitBasicReport(AC->getDecl(), os1.str(), "Security", os2.str(),
+                     CELoc, &R, 1);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -497,7 +637,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void WalkAST::checkCall_random(const CallExpr *CE, const FunctionDecl *FD)=
 {
-  if (!CheckRand)
+  if (!CheckRand || !filter.check_rand)
     return;
=20
   const FunctionProtoType *FTP
@@ -513,7 +653,8 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport("'random' is not a secure random number generator",
+  BR.EmitBasicReport(AC->getDecl(),
+                     "'random' is not a secure random number generator",
                      "Security",
                      "The 'random' function produces a sequence of values =
that "
                      "an adversary may be able to predict.  Use 'arc4rando=
m' "
@@ -526,11 +667,15 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void WalkAST::checkCall_vfork(const CallExpr *CE, const FunctionDecl *FD) {
+  if (!filter.check_vfork)
+    return;
+
   // All calls to vfork() are insecure, issue a warning.
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport("Potential insecure implementation-specific behavior =
in "
+  BR.EmitBasicReport(AC->getDecl(),
+                     "Potential insecure implementation-specific behavior =
in "
                      "call 'vfork'",
                      "Security",
                      "Call to function 'vfork' is insecure as it can lead =
to "
@@ -546,6 +691,9 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void WalkAST::checkUncheckedReturnValue(CallExpr *CE) {
+  if (!filter.check_UncheckedReturn)
+    return;
+ =20
   const FunctionDecl *FD =3D CE->getDirectCallee();
   if (!FD)
     return;
@@ -586,11 +734,11 @@
       return;
=20
   // Issue a warning.
-  llvm::SmallString<256> buf1;
+  SmallString<256> buf1;
   llvm::raw_svector_ostream os1(buf1);
   os1 << "Return value is not checked in call to '" << *FD << '\'';
=20
-  llvm::SmallString<256> buf2;
+  SmallString<256> buf2;
   llvm::raw_svector_ostream os2(buf2);
   os2 << "The return value from the call to '" << *FD
       << "' is not checked.  If an error occurs in '" << *FD
@@ -599,7 +747,8 @@
   SourceRange R =3D CE->getCallee()->getSourceRange();
   PathDiagnosticLocation CELoc =3D
     PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC);
-  BR.EmitBasicReport(os1.str(), "Security", os2.str(), CELoc, &R, 1);
+  BR.EmitBasicReport(AC->getDecl(), os1.str(), "Security", os2.str(),
+                     CELoc, &R, 1);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -609,14 +758,29 @@
 namespace {
 class SecuritySyntaxChecker : public Checker<check::ASTCodeBody> {
 public:
+  ChecksFilter filter;
+ =20
   void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
                         BugReporter &BR) const {
-    WalkAST walker(BR, mgr.getAnalysisContext(D));
+    WalkAST walker(BR, mgr.getAnalysisDeclContext(D), filter);
     walker.Visit(D->getBody());
   }
 };
 }
=20
-void ento::registerSecuritySyntaxChecker(CheckerManager &mgr) {
-  mgr.registerChecker<SecuritySyntaxChecker>();
+#define REGISTER_CHECKER(name) \
+void ento::register##name(CheckerManager &mgr) {\
+  mgr.registerChecker<SecuritySyntaxChecker>()->filter.check_##name =3D tr=
ue;\
 }
+
+REGISTER_CHECKER(gets)
+REGISTER_CHECKER(getpw)
+REGISTER_CHECKER(mkstemp)
+REGISTER_CHECKER(mktemp)
+REGISTER_CHECKER(strcpy)
+REGISTER_CHECKER(rand)
+REGISTER_CHECKER(vfork)
+REGISTER_CHECKER(FloatLoopCounter)
+REGISTER_CHECKER(UncheckedReturn)
+
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/CheckSizeofPointer.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckSizeof=
Pointer.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/CheckSizeof=
Pointer.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,10 +24,10 @@
 namespace {
 class WalkAST : public StmtVisitor<WalkAST> {
   BugReporter &BR;
-  AnalysisContext* AC;
+  AnalysisDeclContext* AC;
=20
 public:
-  WalkAST(BugReporter &br, AnalysisContext* ac) : BR(br), AC(ac) {}
+  WalkAST(BugReporter &br, AnalysisDeclContext* ac) : BR(br), AC(ac) {}
   void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
   void VisitStmt(Stmt *S) { VisitChildren(S); }
   void VisitChildren(Stmt *S);
@@ -63,7 +63,8 @@
     SourceRange R =3D ArgEx->getSourceRange();
     PathDiagnosticLocation ELoc =3D
       PathDiagnosticLocation::createBegin(E, BR.getSourceManager(), AC);
-    BR.EmitBasicReport("Potential unintended use of sizeof() on pointer ty=
pe",
+    BR.EmitBasicReport(AC->getDecl(),
+                       "Potential unintended use of sizeof() on pointer ty=
pe",
                        "Logic",
                        "The code calls sizeof() on a pointer type. "
                        "This can produce an unexpected result.",
@@ -80,7 +81,7 @@
 public:
   void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
                         BugReporter &BR) const {
-    WalkAST walker(BR, mgr.getAnalysisContext(D));
+    WalkAST walker(BR, mgr.getAnalysisDeclContext(D));
     walker.Visit(D->getBody());
   }
 };
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/Checkers.td
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/Checkers.td=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/Checkers.td=
	Tue Apr 17 11:51:51 2012 +0300
@@ -27,16 +27,21 @@
 def DeadCodeExperimental : Package<"deadcode">, InPackage<Experimental>, H=
idden;
=20
 def Security : Package <"security">;
+def InsecureAPI : Package<"insecureAPI">, InPackage<Security>;
 def SecurityExperimental : Package<"security">, InPackage<Experimental>, H=
idden;
+def Taint : Package<"taint">, InPackage<SecurityExperimental>, Hidden; =20
=20
 def Unix : Package<"unix">;
 def UnixExperimental : Package<"unix">, InPackage<Experimental>, Hidden;
+def CString : Package<"cstring">, InPackage<Unix>, Hidden;
+def CStringExperimental : Package<"cstring">, InPackage<UnixExperimental>,=
 Hidden;
=20
 def OSX : Package<"osx">;
 def OSXExperimental : Package<"osx">, InPackage<Experimental>, Hidden;
 def Cocoa : Package<"cocoa">, InPackage<OSX>;
 def CocoaExperimental : Package<"cocoa">, InPackage<OSXExperimental>, Hidd=
en;
 def CoreFoundation : Package<"coreFoundation">, InPackage<OSX>;
+def Containers : Package<"containers">, InPackage<CoreFoundation>;
=20
 def LLVM : Package<"llvm">;
 def Debug : Package<"debug">;
@@ -83,6 +88,10 @@
=20
 let ParentPackage =3D CoreExperimental in {
=20
+def BoolAssignmentChecker : Checker<"BoolAssignment">,
+  HelpText<"Warn about assigning non-{0,1} values to Boolean variables">,
+  DescFile<"BoolAssignmentChecker.cpp">;
+
 def CastSizeChecker : Checker<"CastSize">,
   HelpText<"Check when casting a malloc'ed type T, whether the size is a m=
ultiple of the size of T">,
   DescFile<"CastSizeChecker.cpp">;
@@ -163,6 +172,10 @@
   HelpText<"Check improper uses of STL vector iterators">,
   DescFile<"IteratorsChecker.cpp">;
=20
+def VirtualCallChecker : Checker<"VirtualCall">,
+  HelpText<"Check virtual function calls during construction or destructio=
n">,=20
+  DescFile<"VirtualCallChecker.cpp">;
+
 } // end: "cplusplus.experimental"
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -174,15 +187,14 @@
 def DeadStoresChecker : Checker<"DeadStores">,
   HelpText<"Check for values stored to variables that are never read after=
wards">,
   DescFile<"DeadStoresChecker.cpp">;
+} // end DeadCode
+
+let ParentPackage =3D DeadCodeExperimental in {
=20
 def IdempotentOperationChecker : Checker<"IdempotentOperations">,
   HelpText<"Warn about idempotent operations">,
   DescFile<"IdempotentOperationChecker.cpp">;
=20
-} // end DeadCode
-
-let ParentPackage =3D DeadCodeExperimental in {
-
 def UnreachableCodeChecker : Checker<"UnreachableCode">,
   HelpText<"Check unreachable code">,
   DescFile<"UnreachableCodeChecker.cpp">;
@@ -193,12 +205,40 @@
 // Security checkers.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+let ParentPackage =3D InsecureAPI in {
+  def gets : Checker<"gets">,
+    HelpText<"Warn on uses of the 'gets' function">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+  def getpw : Checker<"getpw">,
+    HelpText<"Warn on uses of the 'getpw' function">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+  def mktemp : Checker<"mktemp">,
+    HelpText<"Warn on uses of the 'mktemp' function">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+  def mkstemp : Checker<"mkstemp">,
+    HelpText<"Warn when 'mkstemp' is passed fewer than 6 X's in the format=
 string">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+  def rand : Checker<"rand">,
+    HelpText<"Warn on uses of the 'rand', 'random', and related functions"=
>,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+  def strcpy : Checker<"strcpy">,
+    HelpText<"Warn on uses of the 'strcpy' and 'strcat' functions">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+  def vfork : Checker<"vfork">,
+    HelpText<"Warn on uses of the 'vfork' function">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+  def UncheckedReturn : Checker<"UncheckedReturn">,
+    HelpText<"Warn on uses of functions whose return values must be always=
 checked">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+}
+let ParentPackage =3D Security in {
+  def FloatLoopCounter : Checker<"FloatLoopCounter">,
+    HelpText<"Warn on using a floating point value as a loop counter (CERT=
: FLP30-C, FLP30-CPP)">,
+    DescFile<"CheckSecuritySyntaxOnly.cpp">;
+}
+
 let ParentPackage =3D SecurityExperimental in {
=20
-def SecuritySyntaxChecker : Checker<"SecuritySyntactic">,
-  HelpText<"Perform quick security API checks that require no data flow">,
-  DescFile<"CheckSecuritySyntaxOnly.cpp">;
-
 def ArrayBoundChecker : Checker<"ArrayBound">,
   HelpText<"Warn about buffer overflows (older checker)">,
   DescFile<"ArrayBoundChecker.cpp">; =20
@@ -218,6 +258,18 @@
 } // end "security.experimental"
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Taint checkers.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+let ParentPackage =3D Taint in {
+
+def GenericTaintChecker : Checker<"TaintPropagation">,
+  HelpText<"Generate taint information used by other checkers">,
+  DescFile<"GenericTaintChecker.cpp">;
+
+} // end "experimental.security.taint"
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Unix API checkers.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -226,6 +278,10 @@
 def UnixAPIChecker : Checker<"API">,
   HelpText<"Check calls to various UNIX/Posix functions">,
   DescFile<"UnixAPIChecker.cpp">;
+
+def MallocPessimistic : Checker<"Malloc">,
+  HelpText<"Check for memory leaks, double free, and use-after-free proble=
ms.">,
+  DescFile<"MallocChecker.cpp">;
  =20
 } // end "unix"
=20
@@ -235,13 +291,13 @@
   HelpText<"Check improper use of chroot">,
   DescFile<"ChrootChecker.cpp">;
=20
-def CStringChecker : Checker<"CString">,
-  HelpText<"Check calls to functions in <string.h>">,
-  DescFile<"CStringChecker.cpp">;
+def MallocOptimistic : Checker<"MallocWithAnnotations">,
+  HelpText<"Check for memory leaks, double free, and use-after-free proble=
ms. Assumes that all user-defined functions which might free a pointer are =
annotated.">,
+  DescFile<"MallocChecker.cpp">;
=20
-def MallocChecker : Checker<"Malloc">,
-  HelpText<"Check for potential memory leaks, double free, and use-after-f=
ree problems">,
-  DescFile<"MallocChecker.cpp">;
+def MallocSizeofChecker : Checker<"MallocSizeof">,
+  HelpText<"Check for dubious malloc arguments involving sizeof">,
+  DescFile<"MallocSizeofChecker.cpp">;
=20
 def PthreadLockChecker : Checker<"PthreadLock">,
   HelpText<"Simple lock -> unlock checker">,
@@ -253,6 +309,32 @@
=20
 } // end "unix.experimental"
=20
+let ParentPackage =3D CString in {
+
+def CStringNullArg : Checker<"NullArg">,
+  HelpText<"Check for null pointers being passed as arguments to C string =
functions">,
+  DescFile<"CStringChecker.cpp">;
+
+def CStringSyntaxChecker : Checker<"BadSizeArg">,
+  HelpText<"Check the size argument passed into C string functions for com=
mon erroneous patterns">,
+  DescFile<"CStringSyntaxChecker.cpp">; =20
+}
+
+let ParentPackage =3D CStringExperimental in {
+
+def CStringOutOfBounds : Checker<"OutOfBounds">,
+  HelpText<"Check for out-of-bounds access in string functions">,
+  DescFile<"CStringChecker.cpp">;
+
+def CStringBufferOverlap : Checker<"BufferOverlap">,
+  HelpText<"Checks for overlap in two buffer arguments">,
+  DescFile<"CStringChecker.cpp">;
+
+def CStringNotNullTerm : Checker<"NotNullTerminated">,
+  HelpText<"Check for arguments which are not null-terminating strings">,
+  DescFile<"CStringChecker.cpp">;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Mac OS X, Cocoa, and Core Foundation checkers.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -291,7 +373,7 @@
   DescFile<"BasicObjCFoundationChecks.cpp">;
=20
 def VariadicMethodTypeChecker : Checker<"VariadicMethodTypes">,
-  HelpText<"Check for passing non-Objective-C types to variadic methods th=
at expect"
+  HelpText<"Check for passing non-Objective-C types to variadic methods th=
at expect "
            "only Objective-C types">,
   DescFile<"BasicObjCFoundationChecks.cpp">;
=20
@@ -306,7 +388,11 @@
 def ObjCUnusedIvarsChecker : Checker<"UnusedIvars">,
   HelpText<"Warn about private ivars that are never used">,
   DescFile<"ObjCUnusedIVarsChecker.cpp">;
-=20
+
+def ObjCSelfInitChecker : Checker<"SelfInit">,
+  HelpText<"Check that 'self' is properly initialized inside an initialize=
r method">,
+  DescFile<"ObjCSelfInitChecker.cpp">;
+
 def NSErrorChecker : Checker<"NSError">,
   HelpText<"Check usage of NSError** parameters">,
   DescFile<"NSErrorChecker.cpp">;
@@ -319,10 +405,6 @@
=20
 let ParentPackage =3D CocoaExperimental in {
=20
-def ObjCSelfInitChecker : Checker<"SelfInit">,
-  HelpText<"Check that 'self' is properly initialized inside an initialize=
r method">,
-  DescFile<"ObjCSelfInitChecker.cpp">;
-
 def ObjCDeallocChecker : Checker<"Dealloc">,
   HelpText<"Warn about Objective-C classes that lack a correct implementat=
ion of -dealloc">,
   DescFile<"CheckObjCDealloc.cpp">;
@@ -344,6 +426,16 @@
   DescFile<"NSErrorChecker.cpp">;
 }
=20
+let ParentPackage =3D Containers in {
+def ObjCContainersASTChecker : Checker<"PointerSizedValues">,
+  HelpText<"Warns if 'CFArray', 'CFDictionary', 'CFSet' are created with n=
on-pointer-size values">,
+  DescFile<"ObjCContainersASTChecker.cpp">;
+
+def ObjCContainersChecker : Checker<"OutOfBounds">,
+  HelpText<"Checks for index out-of-bounds when using 'CFArray' API">,
+  DescFile<"ObjCContainersChecker.cpp">;
+   =20
+}
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Checkers for LLVM development.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -359,6 +451,10 @@
=20
 let ParentPackage =3D Debug in {
=20
+def DominatorsTreeDumper : Checker<"DumpDominators">,
+  HelpText<"Print the dominance tree for a given CFG">,
+  DescFile<"DebugCheckers.cpp">;
+
 def LiveVariablesDumper : Checker<"DumpLiveVars">,
   HelpText<"Print results of live variable analysis">,
   DescFile<"DebugCheckers.cpp">;
@@ -371,9 +467,21 @@
   HelpText<"Display Control-Flow Graphs">,
   DescFile<"DebugCheckers.cpp">;
=20
+def CallGraphViewer : Checker<"ViewCallGraph">,
+  HelpText<"View Call Graph using GraphViz">,
+  DescFile<"DebugCheckers.cpp">;
+
+def CallGraphDumper : Checker<"DumpCallGraph">,
+  HelpText<"Display Call Graph">,
+  DescFile<"DebugCheckers.cpp">;
+
 def AnalyzerStatsChecker : Checker<"Stats">,
   HelpText<"Emit warnings with analyzer statistics">,
   DescFile<"AnalyzerStatsChecker.cpp">;
=20
+def TaintTesterChecker : Checker<"TaintTest">,
+  HelpText<"Mark tainted symbols as such.">,
+  DescFile<"TaintTesterChecker.cpp">;
+
 } // end "debug"
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ChrootChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ChrootCheck=
er.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ChrootCheck=
er.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
 class ChrootChecker : public Checker<eval::Call, check::PreStmt<CallExpr> =
> {
   mutable IdentifierInfo *II_chroot, *II_chdir;
   // This bug refers to possibly break out of a chroot() jail.
-  mutable llvm::OwningPtr<BuiltinBug> BT_BreakJail;
+  mutable OwningPtr<BuiltinBug> BT_BreakJail;
=20
 public:
   ChrootChecker() : II_chroot(0), II_chdir(0) {}
@@ -62,10 +62,7 @@
 } // end anonymous namespace
=20
 bool ChrootChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
   if (!FD)
     return false;
=20
@@ -88,7 +85,7 @@
 }
=20
 void ChrootChecker::Chroot(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   ProgramStateManager &Mgr =3D state->getStateManager();
  =20
   // Once encouter a chroot(), set the enum value ROOT_CHANGED directly in=20
@@ -98,7 +95,7 @@
 }
=20
 void ChrootChecker::Chdir(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   ProgramStateManager &Mgr =3D state->getStateManager();
=20
   // If there are no jail state in the GDM, just return.
@@ -108,7 +105,7 @@
=20
   // After chdir("/"), enter the jail, set the enum value JAIL_ENTERED.
   const Expr *ArgExpr =3D CE->getArg(0);
-  SVal ArgVal =3D state->getSVal(ArgExpr);
+  SVal ArgVal =3D state->getSVal(ArgExpr, C.getLocationContext());
  =20
   if (const MemRegion *R =3D ArgVal.getAsRegion()) {
     R =3D R->StripCasts();
@@ -125,10 +122,7 @@
=20
 // Check the jail state before any function call except chroot and chdir().
 void ChrootChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) co=
nst {
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
   if (!FD)
     return;
=20
@@ -143,10 +137,10 @@
     return;
  =20
   // If jail state is ROOT_CHANGED, generate BugReport.
-  void *const* k =3D state->FindGDM(ChrootChecker::getTag());
+  void *const* k =3D C.getState()->FindGDM(ChrootChecker::getTag());
   if (k)
     if (isRootChanged((intptr_t) *k))
-      if (ExplodedNode *N =3D C.generateNode()) {
+      if (ExplodedNode *N =3D C.addTransition()) {
         if (!BT_BreakJail)
           BT_BreakJail.reset(new BuiltinBug("Break out of jail",
                                         "No call of chdir(\"/\") immediate=
ly "
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ClangSACheckers.h
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ClangSAChec=
kers.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ClangSAChec=
kers.h	Tue Apr 17 11:51:51 2012 +0300
@@ -12,6 +12,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "clang/StaticAnalyzer/Checkers/CommonBugCategories.h"
+
 #ifndef LLVM_CLANG_SA_LIB_CHECKERS_CLANGSACHECKERS_H
 #define LLVM_CLANG_SA_LIB_CHECKERS_CLANGSACHECKERS_H
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/DeadStoresChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DeadStoresC=
hecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DeadStoresC=
hecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -23,6 +23,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/ParentMap.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -67,22 +68,37 @@
   }
 }
=20
+static const Expr *LookThroughTransitiveAssignments(const Expr *Ex) {
+  while (Ex) {
+    const BinaryOperator *BO =3D
+      dyn_cast<BinaryOperator>(Ex->IgnoreParenCasts());
+    if (!BO)
+      break;
+    if (BO->getOpcode() =3D=3D BO_Assign) {
+      Ex =3D BO->getRHS();
+      continue;
+    }
+    break;
+  }
+  return Ex;
+}
+
 namespace {
 class DeadStoreObs : public LiveVariables::Observer {
   const CFG &cfg;
   ASTContext &Ctx;
   BugReporter& BR;
-  AnalysisContext* AC;
+  AnalysisDeclContext* AC;
   ParentMap& Parents;
   llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
-  llvm::OwningPtr<ReachableCode> reachableCode;
+  OwningPtr<ReachableCode> reachableCode;
   const CFGBlock *currentBlock;
=20
   enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
=20
 public:
   DeadStoreObs(const CFG &cfg, ASTContext &ctx,
-               BugReporter& br, AnalysisContext* ac, ParentMap& parents,
+               BugReporter& br, AnalysisDeclContext* ac, ParentMap& parent=
s,
                llvm::SmallPtrSet<const VarDecl*, 20> &escaped)
     : cfg(cfg), Ctx(ctx), BR(br), AC(ac), Parents(parents),
       Escaped(escaped), currentBlock(0) {}
@@ -104,14 +120,11 @@
     if (!reachableCode->isReachable(currentBlock))
       return;
=20
-    llvm::SmallString<64> buf;
+    SmallString<64> buf;
     llvm::raw_svector_ostream os(buf);
     const char *BugType =3D 0;
=20
     switch (dsk) {
-      default:
-        llvm_unreachable("Impossible dead store type.");
-
       case DeadInit:
         BugType =3D "Dead initialization";
         os << "Value stored to '" << *V
@@ -132,7 +145,7 @@
         return;
     }
=20
-    BR.EmitBasicReport(BugType, "Dead store", os.str(), L, R);
+    BR.EmitBasicReport(AC->getDecl(), BugType, "Dead store", os.str(), L, =
R);
   }
=20
   void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val,
@@ -202,17 +215,18 @@
         if (VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl())) {
           // Special case: check for assigning null to a pointer.
           //  This is a common form of defensive programming.
+          const Expr *RHS =3D LookThroughTransitiveAssignments(B->getRHS()=
);
+         =20
           QualType T =3D VD->getType();
           if (T->isPointerType() || T->isObjCObjectPointerType()) {
-            if (B->getRHS()->isNullPointerConstant(Ctx,
-                                              Expr::NPC_ValueDependentIsNu=
ll))
+            if (RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIs=
Null))
               return;
           }
=20
-          Expr *RHS =3D B->getRHS()->IgnoreParenCasts();
+          RHS =3D RHS->IgnoreParenCasts();
           // Special case: self-assignments.  These are often used to shut=
 up
           //  "unused variable" compiler warnings.
-          if (DeclRefExpr *RhsDR =3D dyn_cast<DeclRefExpr>(RHS))
+          if (const DeclRefExpr *RhsDR =3D dyn_cast<DeclRefExpr>(RHS))
             if (VD =3D=3D dyn_cast<VarDecl>(RhsDR->getDecl()))
               return;
=20
@@ -254,10 +268,15 @@
           if (V->getType()->getAs<ReferenceType>())
             return;
            =20
-          if (Expr *E =3D V->getInit()) {
-            while (ExprWithCleanups *exprClean =3D dyn_cast<ExprWithCleanu=
ps>(E))
+          if (const Expr *E =3D V->getInit()) {
+            while (const ExprWithCleanups *exprClean =3D
+                    dyn_cast<ExprWithCleanups>(E))
               E =3D exprClean->getSubExpr();
            =20
+            // Look through transitive assignments, e.g.:
+            // int x =3D y =3D 0;
+            E =3D LookThroughTransitiveAssignments(E);
+           =20
             // Don't warn on C++ objects (yet) until we can show that their
             // constructors/destructors don't have side effects.
             if (isa<CXXConstructExpr>(E))
@@ -274,11 +293,12 @@
               // If x is EVER assigned a new value later, don't issue
               // a warning.  This is because such initialization can be
               // due to defensive programming.
-              if (E->isConstantInitializer(Ctx, false))
+              if (E->isEvaluatable(Ctx))
                 return;
=20
-              if (DeclRefExpr *DRE=3Ddyn_cast<DeclRefExpr>(E->IgnoreParenC=
asts()))
-                if (VarDecl *VD =3D dyn_cast<VarDecl>(DRE->getDecl())) {
+              if (const DeclRefExpr *DRE =3D
+                  dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
+                if (const VarDecl *VD =3D dyn_cast<VarDecl>(DRE->getDecl()=
)) {
                   // Special case: check for initialization from constant
                   //  variables.
                   //
@@ -350,7 +370,7 @@
                         BugReporter &BR) const {
     if (LiveVariables *L =3D mgr.getAnalysis<LiveVariables>(D)) {
       CFG &cfg =3D *mgr.getCFG(D);
-      AnalysisContext *AC =3D mgr.getAnalysisContext(D);
+      AnalysisDeclContext *AC =3D mgr.getAnalysisDeclContext(D);
       ParentMap &pmap =3D mgr.getParentMap(D);
       FindEscaped FS(&cfg);
       FS.getCFG().VisitBlockStmts(FS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/DebugCheckers.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DebugChecke=
rs.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DebugChecke=
rs.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -15,11 +15,36 @@
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "clang/Analysis/Analyses/LiveVariables.h"
+#include "clang/Analysis/Analyses/Dominators.h"
+#include "clang/Analysis/CallGraph.h"
+#include "llvm/Support/Process.h"
=20
 using namespace clang;
 using namespace ento;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// DominatorsTreeDumper
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+class DominatorsTreeDumper : public Checker<check::ASTCodeBody> {
+public:
+  void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
+                        BugReporter &BR) const {
+    if (AnalysisDeclContext *AC =3D mgr.getAnalysisDeclContext(D)) {
+      DominatorTree dom;
+      dom.buildDominatorTree(*AC);
+      dom.dump();
+    }
+  }
+};
+}
+
+void ento::registerDominatorsTreeDumper(CheckerManager &mgr) {
+  mgr.registerChecker<DominatorsTreeDumper>();
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // LiveVariablesDumper
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -49,7 +74,7 @@
   void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
                         BugReporter &BR) const {
     if (CFG *cfg =3D mgr.getCFG(D)) {
-      cfg->viewCFG(mgr.getLangOptions());
+      cfg->viewCFG(mgr.getLangOpts());
     }
   }
 };
@@ -69,7 +94,8 @@
   void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
                         BugReporter &BR) const {
     if (CFG *cfg =3D mgr.getCFG(D)) {
-      cfg->dump(mgr.getLangOptions());
+      cfg->dump(mgr.getLangOpts(),
+                llvm::sys::Process::StandardErrHasColors());
     }
   }
 };
@@ -78,3 +104,43 @@
 void ento::registerCFGDumper(CheckerManager &mgr) {
   mgr.registerChecker<CFGDumper>();
 }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// CallGraphViewer
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+class CallGraphViewer : public Checker< check::ASTDecl<TranslationUnitDecl=
> > {
+public:
+  void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager& mgr,
+                    BugReporter &BR) const {
+    CallGraph CG;
+    CG.addToCallGraph(const_cast<TranslationUnitDecl*>(TU));
+    CG.viewGraph();
+  }
+};
+}
+
+void ento::registerCallGraphViewer(CheckerManager &mgr) {
+  mgr.registerChecker<CallGraphViewer>();
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// CallGraphDumper
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+namespace {
+class CallGraphDumper : public Checker< check::ASTDecl<TranslationUnitDecl=
> > {
+public:
+  void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager& mgr,
+                    BugReporter &BR) const {
+    CallGraph CG;
+    CG.addToCallGraph(const_cast<TranslationUnitDecl*>(TU));
+    CG.dump();
+  }
+};
+}
+
+void ento::registerCallGraphDumper(CheckerManager &mgr) {
+  mgr.registerChecker<CallGraphDumper>();
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/DereferenceChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/Dereference=
Checker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/Dereference=
Checker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -13,10 +13,12 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "ClangSACheckers.h"
+#include "clang/AST/ExprObjC.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -25,35 +27,42 @@
 class DereferenceChecker
     : public Checker< check::Location,
                         EventDispatcher<ImplicitNullDerefEvent> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT_null;
-  mutable llvm::OwningPtr<BuiltinBug> BT_undef;
+  mutable OwningPtr<BuiltinBug> BT_null;
+  mutable OwningPtr<BuiltinBug> BT_undef;
=20
 public:
   void checkLocation(SVal location, bool isLoad, const Stmt* S,
                      CheckerContext &C) const;
=20
-  static void AddDerefSource(raw_ostream &os,
+  static const MemRegion *AddDerefSource(raw_ostream &os,
                              SmallVectorImpl<SourceRange> &Ranges,
-                             const Expr *Ex, bool loadedFrom =3D false);
+                             const Expr *Ex, const ProgramState *state,
+                             const LocationContext *LCtx,
+                             bool loadedFrom =3D false);
 };
 } // end anonymous namespace
=20
-void DereferenceChecker::AddDerefSource(raw_ostream &os,
-                                        SmallVectorImpl<SourceRange> &Rang=
es,
-                                        const Expr *Ex,
-                                        bool loadedFrom) {
+const MemRegion *
+DereferenceChecker::AddDerefSource(raw_ostream &os,
+                                   SmallVectorImpl<SourceRange> &Ranges,
+                                   const Expr *Ex,
+                                   const ProgramState *state,
+                                   const LocationContext *LCtx,
+                                   bool loadedFrom) {
   Ex =3D Ex->IgnoreParenLValueCasts();
+  const MemRegion *sourceR =3D 0;
   switch (Ex->getStmtClass()) {
     default:
-      return;
+      break;
     case Stmt::DeclRefExprClass: {
       const DeclRefExpr *DR =3D cast<DeclRefExpr>(Ex);
       if (const VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl())) {
         os << " (" << (loadedFrom ? "loaded from" : "from")
            << " variable '" <<  VD->getName() << "')";
         Ranges.push_back(DR->getSourceRange());
+        sourceR =3D state->getLValue(VD, LCtx).getAsRegion();
       }
-      return;
+      break;
     }
     case Stmt::MemberExprClass: {
       const MemberExpr *ME =3D cast<MemberExpr>(Ex);
@@ -64,6 +73,7 @@
       break;
     }
   }
+  return sourceR;
 }
=20
 void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
@@ -77,7 +87,7 @@
       BugReport *report =3D
         new BugReport(*BT_undef, BT_undef->getDescription(), N);
       report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                                        bugreporter::GetDerefExpr(N)));
+                                        bugreporter::GetDerefExpr(N), repo=
rt));
       C.EmitReport(report);
     }
     return;
@@ -89,8 +99,9 @@
   if (!isa<Loc>(location))
     return;
=20
-  const ProgramState *state =3D C.getState();
-  const ProgramState *notNullState, *nullState;
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
+  ProgramStateRef notNullState, nullState;
   llvm::tie(notNullState, nullState) =3D state->assume(location);
=20
   // The explicit NULL case.
@@ -106,20 +117,24 @@
       if (!BT_null)
         BT_null.reset(new BuiltinBug("Dereference of null pointer"));
=20
-      llvm::SmallString<100> buf;
+      SmallString<100> buf;
       SmallVector<SourceRange, 2> Ranges;
      =20
       // Walk through lvalue casts to get the original expression
       // that syntactically caused the load.
       if (const Expr *expr =3D dyn_cast<Expr>(S))
         S =3D expr->IgnoreParenLValueCasts();
+     =20
+      const MemRegion *sourceR =3D 0;
=20
       switch (S->getStmtClass()) {
         case Stmt::ArraySubscriptExprClass: {
           llvm::raw_svector_ostream os(buf);
           os << "Array access";
           const ArraySubscriptExpr *AE =3D cast<ArraySubscriptExpr>(S);
-          AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts());
+          sourceR =3D
+            AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
+                           state.getPtr(), LCtx);
           os << " results in a null pointer dereference";
           break;
         }
@@ -127,7 +142,9 @@
           llvm::raw_svector_ostream os(buf);
           os << "Dereference of null pointer";
           const UnaryOperator *U =3D cast<UnaryOperator>(S);
-          AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(), true=
);
+          sourceR =3D
+            AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
+                           state.getPtr(), LCtx, true);
           break;
         }
         case Stmt::MemberExprClass: {
@@ -136,7 +153,9 @@
             llvm::raw_svector_ostream os(buf);
             os << "Access to field '" << M->getMemberNameInfo()
                << "' results in a dereference of a null pointer";
-            AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(), t=
rue);
+            sourceR =3D
+              AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
+                             state.getPtr(), LCtx, true);
           }
           break;
         }
@@ -163,12 +182,17 @@
                               N);
=20
       report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                                        bugreporter::GetDerefExpr(N)));
+                                        bugreporter::GetDerefExpr(N), repo=
rt));
=20
       for (SmallVectorImpl<SourceRange>::iterator
             I =3D Ranges.begin(), E =3D Ranges.end(); I!=3DE; ++I)
         report->addRange(*I);
=20
+      if (sourceR) {
+        report->markInteresting(sourceR);
+        report->markInteresting(state->getRawSVal(loc::MemRegionVal(source=
R)));
+      }
+
       C.EmitReport(report);
       return;
     }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/DivZeroChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DivZeroChec=
ker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/DivZeroChec=
ker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -23,12 +23,31 @@
=20
 namespace {
 class DivZeroChecker : public Checker< check::PreStmt<BinaryOperator> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
+  void reportBug(const char *Msg,
+                 ProgramStateRef StateZero,
+                 CheckerContext &C) const ;
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
 }; =20
 } // end anonymous namespace
=20
+void DivZeroChecker::reportBug(const char *Msg,
+                               ProgramStateRef StateZero,
+                               CheckerContext &C) const {
+  if (ExplodedNode *N =3D C.generateSink(StateZero)) {
+    if (!BT)
+      BT.reset(new BuiltinBug("Division by zero"));
+
+    BugReport *R =3D
+      new BugReport(*BT, Msg, N);
+
+    R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
+                                 bugreporter::GetDenomExpr(N), R));
+    C.EmitReport(R);
+  }
+}
+
 void DivZeroChecker::checkPreStmt(const BinaryOperator *B,
                                   CheckerContext &C) const {
   BinaryOperator::Opcode Op =3D B->getOpcode();
@@ -42,7 +61,7 @@
       !B->getRHS()->getType()->isScalarType())
     return;
=20
-  SVal Denom =3D C.getState()->getSVal(B->getRHS());
+  SVal Denom =3D C.getState()->getSVal(B->getRHS(), C.getLocationContext()=
);
   const DefinedSVal *DV =3D dyn_cast<DefinedSVal>(&Denom);
=20
   // Divide-by-undefined handled in the generic checking for uses of
@@ -52,22 +71,18 @@
=20
   // Check for divide by zero.
   ConstraintManager &CM =3D C.getConstraintManager();
-  const ProgramState *stateNotZero, *stateZero;
+  ProgramStateRef stateNotZero, stateZero;
   llvm::tie(stateNotZero, stateZero) =3D CM.assumeDual(C.getState(), *DV);
=20
-  if (stateZero && !stateNotZero) {
-    if (ExplodedNode *N =3D C.generateSink(stateZero)) {
-      if (!BT)
-        BT.reset(new BuiltinBug("Division by zero"));
+  if (!stateNotZero) {
+    assert(stateZero);
+    reportBug("Division by zero", stateZero, C);
+    return;
+  }
=20
-      BugReport *R =3D=20
-        new BugReport(*BT, BT->getDescription(), N);
-
-      R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                                   bugreporter::GetDenomExpr(N)));
-
-      C.EmitReport(R);
-    }
+  bool TaintedD =3D C.getState()->isTainted(*DV);
+  if ((stateNotZero && stateZero && TaintedD)) {
+    reportBug("Division by a tainted value, possibly zero", stateZero, C);
     return;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/FixedAddressChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/FixedAddres=
sChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/FixedAddres=
sChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 namespace {
 class FixedAddressChecker=20
   : public Checker< check::PreStmt<BinaryOperator> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
=20
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
@@ -44,14 +44,13 @@
   if (!T->isPointerType())
     return;
=20
-  const ProgramState *state =3D C.getState();
-
-  SVal RV =3D state->getSVal(B->getRHS());
+  ProgramStateRef state =3D C.getState();
+  SVal RV =3D state->getSVal(B->getRHS(), C.getLocationContext());
=20
   if (!RV.isConstant() || RV.isZeroConstant())
     return;
=20
-  if (ExplodedNode *N =3D C.generateNode()) {
+  if (ExplodedNode *N =3D C.addTransition()) {
     if (!BT)
       BT.reset(new BuiltinBug("Use fixed address",=20
                           "Using a fixed address is not portable because t=
hat "
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/IdempotentOperationChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/IdempotentO=
perationChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/IdempotentO=
perationChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -57,6 +57,7 @@
 #include "clang/AST/Stmt.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/Support/ErrorHandling.h"
=20
@@ -82,16 +83,16 @@
=20
   // False positive reduction methods
   static bool isSelfAssign(const Expr *LHS, const Expr *RHS);
-  static bool isUnused(const Expr *E, AnalysisContext *AC);
+  static bool isUnused(const Expr *E, AnalysisDeclContext *AC);
   static bool isTruncationExtensionAssignment(const Expr *LHS,
                                               const Expr *RHS);
-  static bool pathWasCompletelyAnalyzed(AnalysisContext *AC,
+  static bool pathWasCompletelyAnalyzed(AnalysisDeclContext *AC,
                                         const CFGBlock *CB,
                                         const CoreEngine &CE);
   static bool CanVary(const Expr *Ex,
-                      AnalysisContext *AC);
+                      AnalysisDeclContext *AC);
   static bool isConstantOrPseudoConstant(const DeclRefExpr *DR,
-                                         AnalysisContext *AC);
+                                         AnalysisDeclContext *AC);
   static bool containsNonLocalVarDecl(const Stmt *S);
=20
   // Hash table and related data structures
@@ -116,7 +117,7 @@
   // been created yet.
   BinaryOperatorData &Data =3D hash[B];
   Assumption &A =3D Data.assumption;
-  AnalysisContext *AC =3D C.getCurrentAnalysisContext();
+  AnalysisDeclContext *AC =3D C.getCurrentAnalysisDeclContext();
=20
   // If we already have visited this node on a path that does not contain =
an
   // idempotent operation, return immediately.
@@ -141,10 +142,10 @@
         || containsNonLocalVarDecl(RHS);
   }
=20
-  const ProgramState *state =3D C.getState();
-
-  SVal LHSVal =3D state->getSVal(LHS);
-  SVal RHSVal =3D state->getSVal(RHS);
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal LHSVal =3D state->getSVal(LHS, LCtx);
+  SVal RHSVal =3D state->getSVal(RHS, LCtx);
=20
   // If either value is unknown, we can't be 100% sure of all paths.
   if (LHSVal.isUnknownOrUndef() || RHSVal.isUnknownOrUndef()) {
@@ -366,8 +367,8 @@
     // warning
     if (Eng.hasWorkRemaining()) {
       // If we can trace back
-      AnalysisContext *AC =3D (*ES.begin())->getLocationContext()
-                                         ->getAnalysisContext();
+      AnalysisDeclContext *AC =3D (*ES.begin())->getLocationContext()
+                                         ->getAnalysisDeclContext();
       if (!pathWasCompletelyAnalyzed(AC,
                                      AC->getCFGStmtMap()->getBlock(B),
                                      Eng.getCoreEngine()))
@@ -375,7 +376,7 @@
     }
=20
     // Select the error message and SourceRanges to report.
-    llvm::SmallString<128> buf;
+    SmallString<128> buf;
     llvm::raw_svector_ostream os(buf);
     bool LHSRelevant =3D false, RHSRelevant =3D false;
     switch (A) {
@@ -487,7 +488,7 @@
 // Returns true if the Expr points to a VarDecl that is not read anywhere
 // outside of self-assignments.
 bool IdempotentOperationChecker::isUnused(const Expr *E,
-                                          AnalysisContext *AC) {
+                                          AnalysisDeclContext *AC) {
   if (!E)
     return false;
=20
@@ -531,7 +532,7 @@
 // Returns false if a path to this block was not completely analyzed, or t=
rue
 // otherwise.
 bool
-IdempotentOperationChecker::pathWasCompletelyAnalyzed(AnalysisContext *AC,
+IdempotentOperationChecker::pathWasCompletelyAnalyzed(AnalysisDeclContext =
*AC,
                                                       const CFGBlock *CB,
                                                       const CoreEngine &CE=
) {
=20
@@ -615,7 +616,7 @@
 // expression may also involve a variable that behaves like a constant. The
 // function returns true if the expression varies, and false otherwise.
 bool IdempotentOperationChecker::CanVary(const Expr *Ex,
-                                         AnalysisContext *AC) {
+                                         AnalysisDeclContext *AC) {
   // Parentheses and casts are irrelevant here
   Ex =3D Ex->IgnoreParenCasts();
=20
@@ -649,7 +650,6 @@
   case Stmt::InitListExprClass:
   case Stmt::DesignatedInitExprClass:
   case Stmt::BlockExprClass:
-  case Stmt::BlockDeclRefExprClass:
     return false;
=20
   // Cases requiring custom logic
@@ -699,7 +699,7 @@
 // Returns true if a DeclRefExpr is or behaves like a constant.
 bool IdempotentOperationChecker::isConstantOrPseudoConstant(
                                                           const DeclRefExp=
r *DR,
-                                                          AnalysisContext =
*AC) {
+                                                          AnalysisDeclCont=
ext *AC) {
   // Check if the type of the Decl is const-qualified
   if (DR->getType().isConstQualified())
     return true;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/IteratorsChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/IteratorsCh=
ecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/IteratorsCh=
ecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/AST/DeclCXX.h"
-#include "clang/AST/Decl.h"
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/Type.h"
 #include "clang/AST/PrettyPrinter.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -117,17 +117,17 @@
                     CheckerContext &C) const;
=20
 private:
-  const ProgramState *handleAssign(const ProgramState *state,
+  ProgramStateRef handleAssign(ProgramStateRef state,
                                    const Expr *lexp,
                                    const Expr *rexp,
                                    const LocationContext *LC) const;
=20
-  const ProgramState *handleAssign(const ProgramState *state,
+  ProgramStateRef handleAssign(ProgramStateRef state,
                                    const MemRegion *MR,
                                    const Expr *rexp,
                                    const LocationContext *LC) const;
=20
-  const ProgramState *invalidateIterators(const ProgramState *state,
+  ProgramStateRef invalidateIterators(ProgramStateRef state,
                                           const MemRegion *MR,
                                           const MemberExpr *ME) const;
=20
@@ -135,7 +135,7 @@
=20
   void checkArgs(CheckerContext &C, const CallExpr *CE) const;
=20
-  const MemRegion *getRegion(const ProgramState *state,
+  const MemRegion *getRegion(ProgramStateRef state,
                              const Expr *E,
                              const LocationContext *LC) const;
=20
@@ -227,7 +227,7 @@
=20
 // Iterate through our map and invalidate any iterators that were
 // initialized fromt the specified instance MemRegion.
-const ProgramState *IteratorsChecker::invalidateIterators(const ProgramSta=
te *state,
+ProgramStateRef IteratorsChecker::invalidateIterators(ProgramStateRef stat=
e,
                           const MemRegion *MR, const MemberExpr *ME) const=
 {
   IteratorState::EntryMap Map =3D state->get<IteratorState>();
   if (Map.isEmpty())
@@ -246,7 +246,7 @@
 }
=20
 // Handle assigning to an iterator where we don't have the LValue MemRegio=
n.
-const ProgramState *IteratorsChecker::handleAssign(const ProgramState *sta=
te,
+ProgramStateRef IteratorsChecker::handleAssign(ProgramStateRef state,
     const Expr *lexp, const Expr *rexp, const LocationContext *LC) const {
   // Skip the cast if present.
   if (const MaterializeTemporaryExpr *M=20
@@ -254,7 +254,7 @@
     lexp =3D M->GetTemporaryExpr();
   if (const ImplicitCastExpr *ICE =3D dyn_cast<ImplicitCastExpr>(lexp))
     lexp =3D ICE->getSubExpr();
-  SVal sv =3D state->getSVal(lexp);
+  SVal sv =3D state->getSVal(lexp, LC);
   const MemRegion *MR =3D sv.getAsRegion();
   if (!MR)
     return state;
@@ -271,7 +271,7 @@
 }
=20
 // handle assigning to an iterator
-const ProgramState *IteratorsChecker::handleAssign(const ProgramState *sta=
te,
+ProgramStateRef IteratorsChecker::handleAssign(ProgramStateRef state,
     const MemRegion *MR, const Expr *rexp, const LocationContext *LC) cons=
t {
   // Assume unknown until we find something definite.
   state =3D state->set<IteratorState>(MR, RefState::getUnknown());
@@ -376,7 +376,7 @@
 }
=20
 // Get the MemRegion associated with the expresssion.
-const MemRegion *IteratorsChecker::getRegion(const ProgramState *state,
+const MemRegion *IteratorsChecker::getRegion(ProgramStateRef state,
     const Expr *E, const LocationContext *LC) const {
   const DeclRefExpr *DRE =3D getDeclRefExpr(E);
   if (!DRE)
@@ -394,9 +394,8 @@
 // use those nodes.  We also cannot create multiple nodes at one ProgramPo=
int
 // with the same tag.
 void IteratorsChecker::checkExpr(CheckerContext &C, const Expr *E) const {
-  const ProgramState *state =3D C.getState();
-  const MemRegion *MR =3D getRegion(state, E,
-                   C.getPredecessor()->getLocationContext());
+  ProgramStateRef state =3D C.getState();
+  const MemRegion *MR =3D getRegion(state, E, C.getLocationContext());
   if (!MR)
     return;
=20
@@ -405,7 +404,7 @@
   if (!RS)
     return;
   if (RS->isInvalid()) {
-    if (ExplodedNode *N =3D C.generateNode()) {
+    if (ExplodedNode *N =3D C.addTransition()) {
       if (!BT_Invalid)
         // FIXME: We are eluding constness here.
         const_cast<IteratorsChecker*>(this)->BT_Invalid =3D new BuiltinBug=
("");
@@ -428,7 +427,7 @@
     }
   }
   else if (RS->isUndefined()) {
-    if (ExplodedNode *N =3D C.generateNode()) {
+    if (ExplodedNode *N =3D C.addTransition()) {
       if (!BT_Undefined)
         // FIXME: We are eluding constness here.
         const_cast<IteratorsChecker*>(this)->BT_Undefined =3D
@@ -466,8 +465,8 @@
 void IteratorsChecker::checkPreStmt(const CXXOperatorCallExpr *OCE,
                                     CheckerContext &C) const
 {
-  const LocationContext *LC =3D C.getPredecessor()->getLocationContext();
-  const ProgramState *state =3D C.getState();
+  const LocationContext *LC =3D C.getLocationContext();
+  ProgramStateRef state =3D C.getState();
   OverloadedOperatorKind Kind =3D OCE->getOperator();
   if (Kind =3D=3D OO_Equal) {
     checkExpr(C, OCE->getArg(1));
@@ -497,7 +496,7 @@
       if (!RS1)
         return;
       if (RS0->getMemRegion() !=3D RS1->getMemRegion()) {
-      if (ExplodedNode *N =3D C.generateNode()) {
+      if (ExplodedNode *N =3D C.addTransition()) {
           if (!BT_Incompatible)
             const_cast<IteratorsChecker*>(this)->BT_Incompatible =3D
               new BuiltinBug(
@@ -524,8 +523,8 @@
     return;
=20
   // Get the MemRegion associated with the iterator and mark it as Undefin=
ed.
-  const ProgramState *state =3D C.getState();
-  Loc VarLoc =3D state->getLValue(VD, C.getPredecessor()->getLocationConte=
xt());
+  ProgramStateRef state =3D C.getState();
+  Loc VarLoc =3D state->getLValue(VD, C.getLocationContext());
   const MemRegion *MR =3D VarLoc.getAsRegion();
   if (!MR)
     return;
@@ -545,8 +544,7 @@
           E =3D M->GetTemporaryExpr();
         if (const ImplicitCastExpr *ICE =3D dyn_cast<ImplicitCastExpr>(E))
           InitEx =3D ICE->getSubExpr();
-        state =3D handleAssign(state, MR, InitEx,
-                                  C.getPredecessor()->getLocationContext()=
);
+        state =3D handleAssign(state, MR, InitEx, C.getLocationContext());
       }
     }
   }
@@ -576,14 +574,14 @@
   const DeclRefExpr *DRE =3D dyn_cast<DeclRefExpr>(ME->getBase());
   if (!DRE || getTemplateKind(DRE->getType()) !=3D VectorKind)
     return;
-  SVal tsv =3D C.getState()->getSVal(DRE);
+  SVal tsv =3D C.getState()->getSVal(DRE, C.getLocationContext());
   // Get the MemRegion associated with the container instance.
   const MemRegion *MR =3D tsv.getAsRegion();
   if (!MR)
     return;
   // If we are calling a function that invalidates iterators, mark them
   // appropriately by finding matching instances.
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   StringRef mName =3D ME->getMemberDecl()->getName();
   if (llvm::StringSwitch<bool>(mName)
       .Cases("insert", "reserve", "push_back", true)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/LLVMConventionsChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/LLVMConvent=
ionsChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/LLVMConvent=
ionsChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -17,8 +17,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/StmtVisitor.h"
-#include <string>
-#include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -116,8 +115,10 @@
 namespace {
 class StringRefCheckerVisitor : public StmtVisitor<StringRefCheckerVisitor=
> {
   BugReporter &BR;
+  const Decl *DeclWithIssue;
 public:
-  StringRefCheckerVisitor(BugReporter &br) : BR(br) {}
+  StringRefCheckerVisitor(const Decl *declWithIssue, BugReporter &br)
+    : BR(br), DeclWithIssue(declWithIssue) {}
   void VisitChildren(Stmt *S) {
     for (Stmt::child_iterator I =3D S->child_begin(), E =3D S->child_end()=
 ;
       I !=3D E; ++I)
@@ -132,7 +133,7 @@
 } // end anonymous namespace
=20
 static void CheckStringRefAssignedTemporary(const Decl *D, BugReporter &BR=
) {
-  StringRefCheckerVisitor walker(BR);
+  StringRefCheckerVisitor walker(D, BR);
   walker.Visit(D->getBody());
 }
=20
@@ -177,7 +178,7 @@
                      "std::string that it outlives";
   PathDiagnosticLocation VDLoc =3D
     PathDiagnosticLocation::createBegin(VD, BR.getSourceManager());
-  BR.EmitBasicReport(desc, "LLVM Conventions", desc,
+  BR.EmitBasicReport(DeclWithIssue, desc, "LLVM Conventions", desc,
                      VDLoc, Init->getSourceRange());
 }
=20
@@ -253,7 +254,7 @@
 }
=20
 void ASTFieldVisitor::ReportError(QualType T) {
-  llvm::SmallString<1024> buf;
+  SmallString<1024> buf;
   llvm::raw_svector_ostream os(buf);
=20
   os << "AST class '" << Root->getName() << "' has a field '"
@@ -282,7 +283,7 @@
   // the class may be in the header file, for example).
   PathDiagnosticLocation L =3D PathDiagnosticLocation::createBegin(
                                FieldChain.front(), BR.getSourceManager());
-  BR.EmitBasicReport("AST node allocates heap memory", "LLVM Conventions",
+  BR.EmitBasicReport(Root, "AST node allocates heap memory", "LLVM Convent=
ions",
                      os.str(), L);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MacOSKeycha=
inAPIChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MacOSKeycha=
inAPIChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -29,7 +30,7 @@
                                                check::PostStmt<CallExpr>,
                                                check::EndPath,
                                                check::DeadSymbols> {
-  mutable llvm::OwningPtr<BugType> BT;
+  mutable OwningPtr<BugType> BT;
=20
 public:
   /// AllocationState is a part of the checker specific state together wit=
h the
@@ -58,7 +59,7 @@
   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
   void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
-  void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
+  void checkEndPath(CheckerContext &C) const;
=20
 private:
   typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
@@ -100,26 +101,38 @@
                                          const Expr *ArgExpr,
                                          CheckerContext &C) const;
=20
+  /// Find the allocation site for Sym on the path leading to the node N.
+  const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
+                                CheckerContext &C) const;
+
   BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &=
AP,
-                                                    ExplodedNode *N) const;
+                                                    ExplodedNode *N,
+                                                    CheckerContext &C) con=
st;
=20
   /// Check if RetSym evaluates to an error value in the current state.
   bool definitelyReturnedError(SymbolRef RetSym,
-                               const ProgramState *State,
+                               ProgramStateRef State,
                                SValBuilder &Builder,
                                bool noError =3D false) const;
=20
   /// Check if RetSym evaluates to a NoErr value in the current state.
   bool definitelyDidnotReturnError(SymbolRef RetSym,
-                                   const ProgramState *State,
+                                   ProgramStateRef State,
                                    SValBuilder &Builder) const {
     return definitelyReturnedError(RetSym, State, Builder, true);
   }
+                                                =20
+  /// Mark an AllocationPair interesting for diagnostic reporting.
+  void markInteresting(BugReport *R, const AllocationPair &AP) const {
+    R->markInteresting(AP.first);
+    R->markInteresting(AP.second->Region);
+  }
=20
   /// The bug visitor which allows us to print extra diagnostics along the
   /// BugReport path. For example, showing the allocation site of the leak=
ed
   /// region.
-  class SecKeychainBugVisitor : public BugReporterVisitor {
+  class SecKeychainBugVisitor
+    : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
   protected:
     // The allocated region symbol tracked by the main analysis.
     SymbolRef Sym;
@@ -196,18 +209,9 @@
   return InvalidIdx;
 }
=20
-static SymbolRef getSymbolForRegion(CheckerContext &C,
-                                   const MemRegion *R) {
-  // Implicit casts (ex: void* -> char*) can turn Symbolic region into ele=
ment
-  // region, if that is the case, get the underlining region.
-  R =3D R->StripCasts();
-  if (!isa<SymbolicRegion>(R)) {
-      return 0;
-  }
-  return cast<SymbolicRegion>(R)->getSymbol();
-}
-
 static bool isBadDeallocationArgument(const MemRegion *Arg) {
+  if (!Arg)
+    return false;
   if (isa<AllocaRegion>(Arg) ||
       isa<BlockDataRegion>(Arg) ||
       isa<TypedRegion>(Arg)) {
@@ -215,18 +219,19 @@
   }
   return false;
 }
+
 /// Given the address expression, retrieve the value it's pointing to. Ass=
ume
 /// that value is itself an address, and return the corresponding symbol.
 static SymbolRef getAsPointeeSymbol(const Expr *Expr,
                                     CheckerContext &C) {
-  const ProgramState *State =3D C.getState();
-  SVal ArgV =3D State->getSVal(Expr);
+  ProgramStateRef State =3D C.getState();
+  SVal ArgV =3D State->getSVal(Expr, C.getLocationContext());
=20
   if (const loc::MemRegionVal *X =3D dyn_cast<loc::MemRegionVal>(&ArgV)) {
     StoreManager& SM =3D C.getStoreManager();
-    const MemRegion *V =3D SM.Retrieve(State->getStore(), *X).getAsRegion(=
);
-    if (V)
-      return getSymbolForRegion(C, V);
+    SymbolRef sym =3D SM.getBinding(State->getStore(), *X).getAsLocSymbol(=
);
+    if (sym)
+      return sym;
   }
   return 0;
 }
@@ -238,14 +243,14 @@
 // If noError, returns true iff (1).
 // If !noError, returns true iff (2).
 bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
-                                                      const ProgramState *=
State,
+                                                      ProgramStateRef Stat=
e,
                                                       SValBuilder &Builder,
                                                       bool noError) const {
   DefinedOrUnknownSVal NoErrVal =3D Builder.makeIntVal(NoErr,
     Builder.getSymbolManager().getType(RetSym));
   DefinedOrUnknownSVal NoErr =3D Builder.evalEQ(State, NoErrVal,
                                                      nonloc::SymbolVal(Ret=
Sym));
-  const ProgramState *ErrState =3D State->assume(NoErr, noError);
+  ProgramStateRef ErrState =3D State->assume(NoErr, noError);
   if (ErrState =3D=3D State) {
     return true;
   }
@@ -259,14 +264,14 @@
   generateDeallocatorMismatchReport(const AllocationPair &AP,
                                     const Expr *ArgExpr,
                                     CheckerContext &C) const {
-  const ProgramState *State =3D C.getState();
+  ProgramStateRef State =3D C.getState();
   State =3D State->remove<AllocatedData>(AP.first);
-  ExplodedNode *N =3D C.generateNode(State);
+  ExplodedNode *N =3D C.addTransition(State);
=20
   if (!N)
     return;
   initBugType();
-  llvm::SmallString<80> sbuf;
+  SmallString<80> sbuf;
   llvm::raw_svector_ostream os(sbuf);
   unsigned int PDeallocIdx =3D
                FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
@@ -276,23 +281,18 @@
   BugReport *Report =3D new BugReport(*BT, os.str(), N);
   Report->addVisitor(new SecKeychainBugVisitor(AP.first));
   Report->addRange(ArgExpr->getSourceRange());
+  markInteresting(Report, AP);
   C.EmitReport(Report);
 }
=20
 void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
                                            CheckerContext &C) const {
-  const ProgramState *State =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D State->getSVal(Callee);
   unsigned idx =3D InvalidIdx;
+  ProgramStateRef State =3D C.getState();
=20
-  const FunctionDecl *funDecl =3D L.getAsFunctionDecl();
-  if (!funDecl)
+  StringRef funName =3D C.getCalleeName(CE);
+  if (funName.empty())
     return;
-  IdentifierInfo *funI =3D funDecl->getIdentifier();
-  if (!funI)
-    return;
-  StringRef funName =3D funI->getName();
=20
   // If it is a call to an allocator function, it could be a double alloca=
tion.
   idx =3D getTrackedFunctionIndex(funName, true);
@@ -304,11 +304,11 @@
           // Remove the value from the state. The new symbol will be added=
 for
           // tracking when the second allocator is processed in checkPostS=
tmt().
           State =3D State->remove<AllocatedData>(V);
-          ExplodedNode *N =3D C.generateNode(State);
+          ExplodedNode *N =3D C.addTransition(State);
           if (!N)
             return;
           initBugType();
-          llvm::SmallString<128> sbuf;
+          SmallString<128> sbuf;
           llvm::raw_svector_ostream os(sbuf);
           unsigned int DIdx =3D FunctionsToTrack[AS->AllocatorIdx].Dealloc=
atorIdx;
           os << "Allocated data should be released before another call to "
@@ -318,6 +318,7 @@
           BugReport *Report =3D new BugReport(*BT, os.str(), N);
           Report->addVisitor(new SecKeychainBugVisitor(V));
           Report->addRange(ArgExpr->getSourceRange());
+          Report->markInteresting(AS->Region);
           C.EmitReport(Report);
         }
       }
@@ -331,22 +332,22 @@
=20
   // Check the argument to the deallocator.
   const Expr *ArgExpr =3D CE->getArg(FunctionsToTrack[idx].Param);
-  SVal ArgSVal =3D State->getSVal(ArgExpr);
+  SVal ArgSVal =3D State->getSVal(ArgExpr, C.getLocationContext());
=20
   // Undef is reported by another checker.
   if (ArgSVal.isUndef())
     return;
=20
-  const MemRegion *Arg =3D ArgSVal.getAsRegion();
-  if (!Arg)
-    return;
+  SymbolRef ArgSM =3D ArgSVal.getAsLocSymbol();
=20
-  SymbolRef ArgSM =3D getSymbolForRegion(C, Arg);
-  bool RegionArgIsBad =3D ArgSM ? false : isBadDeallocationArgument(Arg);
   // If the argument is coming from the heap, globals, or unknown, do not
   // report it.
-  if (!ArgSM && !RegionArgIsBad)
-    return;
+  bool RegionArgIsBad =3D false;
+  if (!ArgSM) {
+    if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
+      return;
+    RegionArgIsBad =3D true;
+  }
=20
   // Is the argument to the call being tracked?
   const AllocationState *AS =3D State->get<AllocatedData>(ArgSM);
@@ -362,13 +363,15 @@
     if (isEnclosingFunctionParam(ArgExpr))
       return;
=20
-    ExplodedNode *N =3D C.generateNode(State);
+    ExplodedNode *N =3D C.addTransition(State);
     if (!N)
       return;
     initBugType();
     BugReport *Report =3D new BugReport(*BT,
         "Trying to free data which has not been allocated.", N);
     Report->addRange(ArgExpr->getSourceRange());
+    if (AS)
+      Report->markInteresting(AS->Region);
     C.EmitReport(Report);
     return;
   }
@@ -420,16 +423,19 @@
     return;
   }
=20
-  // If the return status is undefined or is error, report a bad call to f=
ree.
-  if (!definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder()))=
 {
-    ExplodedNode *N =3D C.generateNode(State);
+  // If the buffer can be null and the return status can be an error,
+  // report a bad call to free.
+  if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
+      !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder()))=
 {
+    ExplodedNode *N =3D C.addTransition(State);
     if (!N)
       return;
     initBugType();
     BugReport *Report =3D new BugReport(*BT,
-        "Call to free data when error was returned during allocation.", N);
+        "Only call free if a valid (non-NULL) buffer was returned.", N);
     Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
     Report->addRange(ArgExpr->getSourceRange());
+    Report->markInteresting(AS->Region);
     C.EmitReport(Report);
     return;
   }
@@ -439,17 +445,8 @@
=20
 void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
                                             CheckerContext &C) const {
-  const ProgramState *State =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D State->getSVal(Callee);
-
-  const FunctionDecl *funDecl =3D L.getAsFunctionDecl();
-  if (!funDecl)
-    return;
-  IdentifierInfo *funI =3D funDecl->getIdentifier();
-  if (!funI)
-    return;
-  StringRef funName =3D funI->getName();
+  ProgramStateRef State =3D C.getState();
+  StringRef funName =3D C.getCalleeName(CE);
=20
   // If a value has been allocated, add it to the set for tracking.
   unsigned idx =3D getTrackedFunctionIndex(funName, true);
@@ -459,7 +456,8 @@
   const Expr *ArgExpr =3D CE->getArg(FunctionsToTrack[idx].Param);
   // If the argument entered as an enclosing function parameter, skip it to
   // avoid false positives.
-  if (isEnclosingFunctionParam(ArgExpr))
+  if (isEnclosingFunctionParam(ArgExpr) &&
+      C.getLocationContext()->getParent() =3D=3D 0)
     return;
=20
   if (SymbolRef V =3D getAsPointeeSymbol(ArgExpr, C)) {
@@ -475,7 +473,8 @@
     // allocated value symbol, since our diagnostics depend on the value
     // returned by the call. Ex: Data should only be freed if noErr was
     // returned during allocation.)
-    SymbolRef RetStatusSymbol =3D State->getSVal(CE).getAsSymbol();
+    SymbolRef RetStatusSymbol =3D
+      State->getSVal(CE, C.getLocationContext()).getAsSymbol();
     C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
=20
     // Track the allocated value in the checker state.
@@ -492,36 +491,76 @@
   if (!retExpr)
     return;
=20
+  // If inside inlined call, skip it.
+  const LocationContext *LC =3D C.getLocationContext();
+  if (LC->getParent() !=3D 0)
+    return;
+
   // Check  if the value is escaping through the return.
-  const ProgramState *state =3D C.getState();
-  const MemRegion *V =3D state->getSVal(retExpr).getAsRegion();
-  if (!V)
+  ProgramStateRef state =3D C.getState();
+  SymbolRef sym =3D state->getSVal(retExpr, LC).getAsLocSymbol();
+  if (!sym)
     return;
-  state =3D state->remove<AllocatedData>(getSymbolForRegion(C, V));
+  state =3D state->remove<AllocatedData>(sym);
=20
   // Proceed from the new state.
   C.addTransition(state);
 }
=20
+// TODO: This logic is the same as in Malloc checker.
+const Stmt *
+MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
+                                           SymbolRef Sym,
+                                           CheckerContext &C) const {
+  const LocationContext *LeakContext =3D N->getLocationContext();
+  // Walk the ExplodedGraph backwards and find the first node that referre=
d to
+  // the tracked symbol.
+  const ExplodedNode *AllocNode =3D N;
+
+  while (N) {
+    if (!N->getState()->get<AllocatedData>(Sym))
+      break;
+    // Allocation node, is the last node in the current context in which t=
he
+    // symbol was tracked.
+    if (N->getLocationContext() =3D=3D LeakContext)
+      AllocNode =3D N;
+    N =3D N->pred_empty() ? NULL : *(N->pred_begin());
+  }
+
+  ProgramPoint P =3D AllocNode->getLocation();
+  if (!isa<StmtPoint>(P))
+    return 0;
+  return cast<clang::PostStmt>(P).getStmt();
+}
+
 BugReport *MacOSKeychainAPIChecker::
   generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
-                                         ExplodedNode *N) const {
+                                         ExplodedNode *N,
+                                         CheckerContext &C) const {
   const ADFunctionInfo &FI =3D FunctionsToTrack[AP.second->AllocatorIdx];
   initBugType();
-  llvm::SmallString<70> sbuf;
+  SmallString<70> sbuf;
   llvm::raw_svector_ostream os(sbuf);
-
   os << "Allocated data is not released: missing a call to '"
       << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
-  BugReport *Report =3D new BugReport(*BT, os.str(), N);
+
+  // Most bug reports are cached at the location where they occurred.
+  // With leaks, we want to unique them by the location where they were
+  // allocated, and only report a single path.
+  PathDiagnosticLocation LocUsedForUniqueing;
+  if (const Stmt *AllocStmt =3D getAllocationSite(N, AP.first, C))
+    LocUsedForUniqueing =3D PathDiagnosticLocation::createBegin(AllocStmt,
+                            C.getSourceManager(), N->getLocationContext());
+
+  BugReport *Report =3D new BugReport(*BT, os.str(), N, LocUsedForUniquein=
g);
   Report->addVisitor(new SecKeychainBugVisitor(AP.first));
-  Report->addRange(SourceRange());
+  markInteresting(Report, AP);
   return Report;
 }
=20
 void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
                                                CheckerContext &C) const {
-  const ProgramState *State =3D C.getState();
+  ProgramStateRef State =3D C.getState();
   AllocatedSetTy ASet =3D State->get<AllocatedData>();
   if (ASet.isEmpty())
     return;
@@ -541,25 +580,33 @@
       continue;
     Errors.push_back(std::make_pair(I->first, &I->second));
   }
-  if (!Changed)
+  if (!Changed) {
+    // Generate the new, cleaned up state.
+    C.addTransition(State);
     return;
+  }
=20
-  // Generate the new, cleaned up state.
-  ExplodedNode *N =3D C.generateNode(State);
-  if (!N)
-    return;
+  static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsL=
eak");
+  ExplodedNode *N =3D C.addTransition(C.getState(), C.getPredecessor(), &T=
ag);
=20
   // Generate the error reports.
   for (AllocationPairVec::iterator I =3D Errors.begin(), E =3D Errors.end(=
);
                                                        I !=3D E; ++I) {
-    C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
+    C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
   }
+
+  // Generate the new, cleaned up state.
+  C.addTransition(State, N);
 }
=20
 // TODO: Remove this after we ensure that checkDeadSymbols are always call=
ed.
-void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
-                                           ExprEngine &Eng) const {
-  const ProgramState *state =3D B.getState();
+void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
+  ProgramStateRef state =3D C.getState();
+
+  // If inside inlined call, skip it.
+  if (C.getLocationContext()->getParent() !=3D 0)
+    return;
+
   AllocatedSetTy AS =3D state->get<AllocatedData>();
   if (AS.isEmpty())
     return;
@@ -575,26 +622,28 @@
     // allocation, do not report.
     if (state->getSymVal(I.getKey()) ||
         definitelyReturnedError(I->second.Region, state,
-                                Eng.getSValBuilder())) {
+                                C.getSValBuilder())) {
       continue;
     }
     Errors.push_back(std::make_pair(I->first, &I->second));
   }
=20
   // If no change, do not generate a new state.
-  if (!Changed)
+  if (!Changed) {
+    C.addTransition(state);
     return;
+  }
=20
-  ExplodedNode *N =3D B.generateNode(state);
-  if (!N)
-    return;
+  static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak"=
);
+  ExplodedNode *N =3D C.addTransition(C.getState(), C.getPredecessor(), &T=
ag);
=20
   // Generate the error reports.
   for (AllocationPairVec::iterator I =3D Errors.begin(), E =3D Errors.end(=
);
                                                        I !=3D E; ++I) {
-    Eng.getBugReporter().EmitReport(
-      generateAllocatedDataNotReleasedReport(*I, N));
+    C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
   }
+
+  C.addTransition(state, N);
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/MacOSXAPIChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MacOSXAPICh=
ecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MacOSXAPICh=
ecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -31,17 +31,17 @@
=20
 namespace {
 class MacOSXAPIChecker : public Checker< check::PreStmt<CallExpr> > {
-  mutable llvm::OwningPtr<BugType> BT_dispatchOnce;
+  mutable OwningPtr<BugType> BT_dispatchOnce;
=20
 public:
   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
=20
   void CheckDispatchOnce(CheckerContext &C, const CallExpr *CE,
-                         const IdentifierInfo *FI) const;
+                         StringRef FName) const;
=20
   typedef void (MacOSXAPIChecker::*SubChecker)(CheckerContext &,
                                                const CallExpr *,
-                                               const IdentifierInfo *) con=
st;
+                                               StringRef FName) const;
 };
 } //end anonymous namespace
=20
@@ -50,14 +50,15 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 void MacOSXAPIChecker::CheckDispatchOnce(CheckerContext &C, const CallExpr=
 *CE,
-                                         const IdentifierInfo *FI) const {
+                                         StringRef FName) const {
   if (CE->getNumArgs() < 1)
     return;
=20
   // Check if the first argument is stack allocated.  If so, issue a warni=
ng
   // because that's likely to be bad news.
-  const ProgramState *state =3D C.getState();
-  const MemRegion *R =3D state->getSVal(CE->getArg(0)).getAsRegion();
+  ProgramStateRef state =3D C.getState();
+  const MemRegion *R =3D
+    state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
   if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
     return;
=20
@@ -69,9 +70,9 @@
     BT_dispatchOnce.reset(new BugType("Improper use of 'dispatch_once'",
                                       "Mac OS X API"));
=20
-  llvm::SmallString<256> S;
+  SmallString<256> S;
   llvm::raw_svector_ostream os(S);
-  os << "Call to '" << FI->getName() << "' uses";
+  os << "Call to '" << FName << "' uses";
   if (const VarRegion *VR =3D dyn_cast<VarRegion>(R))
     os << " the local variable '" << VR->getDecl()->getName() << '\'';
   else
@@ -92,27 +93,18 @@
=20
 void MacOSXAPIChecker::checkPreStmt(const CallExpr *CE,
                                     CheckerContext &C) const {
-  // FIXME: This sort of logic is common to several checkers, including
-  // UnixAPIChecker, PthreadLockChecker, and CStringChecker.  Should refac=
tor.
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  const FunctionDecl *Fn =3D state->getSVal(Callee).getAsFunctionDecl();
-
-  if (!Fn)
-    return;
-
-  const IdentifierInfo *FI =3D Fn->getIdentifier();
-  if (!FI)
+  StringRef Name =3D C.getCalleeName(CE);
+  if (Name.empty())
     return;
=20
   SubChecker SC =3D
-    llvm::StringSwitch<SubChecker>(FI->getName())
+    llvm::StringSwitch<SubChecker>(Name)
       .Cases("dispatch_once", "dispatch_once_f",
              &MacOSXAPIChecker::CheckDispatchOnce)
       .Default(NULL);
=20
   if (SC)
-    (this->*SC)(C, CE, FI);
+    (this->*SC)(C, CE, Name);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/MallocChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocCheck=
er.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocCheck=
er.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -13,14 +13,21 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "ClangSACheckers.h"
+#include "InterCheckerAPI.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/ImmutableMap.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/STLExtras.h"
+#include <climits>
+
 using namespace clang;
 using namespace ento;
=20
@@ -35,10 +42,9 @@
   RefState(Kind k, const Stmt *s) : K(k), S(s) {}
=20
   bool isAllocated() const { return K =3D=3D AllocateUnchecked; }
-  //bool isFailed() const { return K =3D=3D AllocateFailed; }
   bool isReleased() const { return K =3D=3D Released; }
-  //bool isEscaped() const { return K =3D=3D Escaped; }
-  //bool isRelinquished() const { return K =3D=3D Relinquished; }
+
+  const Stmt *getStmt() const { return S; }
=20
   bool operator=3D=3D(const RefState &X) const {
     return K =3D=3D X.K && S =3D=3D X.S;
@@ -62,61 +68,222 @@
   }
 };
=20
-class RegionState {};
+struct ReallocPair {
+  SymbolRef ReallocatedSym;
+  bool IsFreeOnFailure;
+  ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F)=
 {}
+  void Profile(llvm::FoldingSetNodeID &ID) const {
+    ID.AddInteger(IsFreeOnFailure);
+    ID.AddPointer(ReallocatedSym);
+  }
+  bool operator=3D=3D(const ReallocPair &X) const {
+    return ReallocatedSym =3D=3D X.ReallocatedSym &&
+           IsFreeOnFailure =3D=3D X.IsFreeOnFailure;
+  }
+};
=20
-class MallocChecker : public Checker<eval::Call, check::DeadSymbols, check=
::EndPath, check::PreStmt<ReturnStmt>, check::Location,
-                               check::Bind, eval::Assume> {
-  mutable llvm::OwningPtr<BuiltinBug> BT_DoubleFree;
-  mutable llvm::OwningPtr<BuiltinBug> BT_Leak;
-  mutable llvm::OwningPtr<BuiltinBug> BT_UseFree;
-  mutable llvm::OwningPtr<BuiltinBug> BT_UseRelinquished;
-  mutable llvm::OwningPtr<BuiltinBug> BT_BadFree;
-  mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
+typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
+
+class MallocChecker : public Checker<check::DeadSymbols,
+                                     check::EndPath,
+                                     check::PreStmt<ReturnStmt>,
+                                     check::PreStmt<CallExpr>,
+                                     check::PostStmt<CallExpr>,
+                                     check::PostStmt<BlockExpr>,
+                                     check::Location,
+                                     check::Bind,
+                                     eval::Assume,
+                                     check::RegionChanges>
+{
+  mutable OwningPtr<BugType> BT_DoubleFree;
+  mutable OwningPtr<BugType> BT_Leak;
+  mutable OwningPtr<BugType> BT_UseFree;
+  mutable OwningPtr<BugType> BT_BadFree;
+  mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
+                         *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
=20
 public:
-  MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) =
{}
+  MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
+                    II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup=
(0) {}
=20
-  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
+  /// In pessimistic mode, the checker assumes that it does not know which
+  /// functions might free the memory.
+  struct ChecksFilter {
+    DefaultBool CMallocPessimistic;
+    DefaultBool CMallocOptimistic;
+  };
+
+  ChecksFilter Filter;
+
+  void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
+  void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
+  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
-  void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
+  void checkEndPath(CheckerContext &C) const;
   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
-  const ProgramState *evalAssume(const ProgramState *state, SVal Cond,
+  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
                             bool Assumption) const;
   void checkLocation(SVal l, bool isLoad, const Stmt *S,
                      CheckerContext &C) const;
   void checkBind(SVal location, SVal val, const Stmt*S,
                  CheckerContext &C) const;
+  ProgramStateRef
+  checkRegionChanges(ProgramStateRef state,
+                     const StoreManager::InvalidatedSymbols *invalidated,
+                     ArrayRef<const MemRegion *> ExplicitRegions,
+                     ArrayRef<const MemRegion *> Regions,
+                     const CallOrObjCMessage *Call) const;
+  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
+    return true;
+  }
=20
 private:
-  static void MallocMem(CheckerContext &C, const CallExpr *CE);
-  static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
-                                   const OwnershipAttr* Att);
-  static const ProgramState *MallocMemAux(CheckerContext &C, const CallExp=
r *CE,
+  void initIdentifierInfo(ASTContext &C) const;
+
+  /// Check if this is one of the functions which can allocate/reallocate =
memory=20
+  /// pointed to by one of its arguments.
+  bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
+
+  static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
+                                              const CallExpr *CE,
+                                              const OwnershipAttr* Att);
+  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *C=
E,
                                      const Expr *SizeEx, SVal Init,
-                                     const ProgramState *state) {
-    return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
+                                     ProgramStateRef state) {
+    return MallocMemAux(C, CE,
+                        state->getSVal(SizeEx, C.getLocationContext()),
+                        Init, state);
   }
-  static const ProgramState *MallocMemAux(CheckerContext &C, const CallExp=
r *CE,
+
+  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *C=
E,
                                      SVal SizeEx, SVal Init,
-                                     const ProgramState *state);
+                                     ProgramStateRef state);
=20
-  void FreeMem(CheckerContext &C, const CallExpr *CE) const;
-  void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
-                   const OwnershipAttr* Att) const;
-  const ProgramState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
-                           const ProgramState *state, unsigned Num, bool H=
old) const;
+  /// Update the RefState to reflect the new memory allocation.
+  static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
+                                              const CallExpr *CE,
+                                              ProgramStateRef state);
=20
-  void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
-  static void CallocMem(CheckerContext &C, const CallExpr *CE);
+  ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
+                              const OwnershipAttr* Att) const;
+  ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
+                                 ProgramStateRef state, unsigned Num,
+                                 bool Hold) const;
+
+  ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
+                             bool FreesMemOnFailure) const;
+  static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
  =20
+  bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
+  bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
+                         const Stmt *S =3D 0) const;
+
+  /// Check if the function is not known to us. So, for example, we could
+  /// conservatively assume it can free/reallocate it's pointer arguments.
+  bool doesNotFreeMemory(const CallOrObjCMessage *Call,
+                         ProgramStateRef State) const;
+
   static bool SummarizeValue(raw_ostream &os, SVal V);
   static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
   void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) co=
nst;
+
+  /// Find the location of the allocation for Sym on the path leading to t=
he
+  /// exploded node N.
+  LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
+                             CheckerContext &C) const;
+
+  void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
+
+  /// The bug visitor which allows us to print extra diagnostics along the
+  /// BugReport path. For example, showing the allocation site of the leak=
ed
+  /// region.
+  class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor>=
 {
+  protected:
+    enum NotificationMode {
+      Normal,
+      ReallocationFailed
+    };
+
+    // The allocated region symbol tracked by the main analysis.
+    SymbolRef Sym;
+
+     // The mode we are in, i.e. what kind of diagnostics will be emitted.
+     NotificationMode Mode;
+
+     // A symbol from when the primary region should have been reallocated.
+     SymbolRef FailedReallocSymbol;
+
+   public:
+     MallocBugVisitor(SymbolRef S)
+       : Sym(S), Mode(Normal), FailedReallocSymbol(0) {}
+
+    virtual ~MallocBugVisitor() {}
+
+    void Profile(llvm::FoldingSetNodeID &ID) const {
+      static int X =3D 0;
+      ID.AddPointer(&X);
+      ID.AddPointer(Sym);
+    }
+
+    inline bool isAllocated(const RefState *S, const RefState *SPrev,
+                            const Stmt *Stmt) {
+      // Did not track -> allocated. Other state (released) -> allocated.
+      return (Stmt && isa<CallExpr>(Stmt) &&
+              (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated())=
);
+    }
+
+    inline bool isReleased(const RefState *S, const RefState *SPrev,
+                           const Stmt *Stmt) {
+      // Did not track -> released. Other state (allocated) -> released.
+      return (Stmt && isa<CallExpr>(Stmt) &&
+              (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
+    }
+
+    inline bool isReallocFailedCheck(const RefState *S, const RefState *SP=
rev,
+                                     const Stmt *Stmt) {
+      // If the expression is not a call, and the state change is
+      // released -> allocated, it must be the realloc return value
+      // check. If we have to handle more cases here, it might be cleaner =
just
+      // to track this extra bit in the state itself.
+      return ((!Stmt || !isa<CallExpr>(Stmt)) &&
+              (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
+    }
+
+    PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
+                                   const ExplodedNode *PrevN,
+                                   BugReporterContext &BRC,
+                                   BugReport &BR);
+  private:
+    class StackHintGeneratorForReallocationFailed
+        : public StackHintGeneratorForSymbol {
+    public:
+      StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
+        : StackHintGeneratorForSymbol(S, M) {}
+
+      virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgI=
ndex) {
+        SmallString<200> buf;
+        llvm::raw_svector_ostream os(buf);
+
+        os << "Reallocation of ";
+        // Printed parameters start at 1, not 0.
+        printOrdinal(++ArgIndex, os);
+        os << " parameter failed";
+
+        return os.str();
+      }
+
+      virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
+        return "Reallocation of returned value failed";
+      }
+    };
+  };
 };
 } // end anonymous namespace
=20
 typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
-
+typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
+class RegionState {};
+class ReallocPairs {};
 namespace clang {
 namespace ento {
   template <>
@@ -124,178 +291,230 @@
     : public ProgramStatePartialTrait<RegionStateTy> {
     static void *GDMIndex() { static int x; return &x; }
   };
+
+  template <>
+  struct ProgramStateTrait<ReallocPairs>
+    : public ProgramStatePartialTrait<ReallocMap> {
+    static void *GDMIndex() { static int x; return &x; }
+  };
 }
 }
=20
-bool MallocChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
+namespace {
+class StopTrackingCallback : public SymbolVisitor {
+  ProgramStateRef state;
+public:
+  StopTrackingCallback(ProgramStateRef st) : state(st) {}
+  ProgramStateRef getState() const { return state; }
=20
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
-  if (!FD)
-    return false;
+  bool VisitSymbol(SymbolRef sym) {
+    state =3D state->remove<RegionState>(sym);
+    return true;
+  }
+};
+} // end anonymous namespace
=20
-  ASTContext &Ctx =3D C.getASTContext();
+void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
   if (!II_malloc)
     II_malloc =3D &Ctx.Idents.get("malloc");
   if (!II_free)
     II_free =3D &Ctx.Idents.get("free");
   if (!II_realloc)
     II_realloc =3D &Ctx.Idents.get("realloc");
+  if (!II_reallocf)
+    II_reallocf =3D &Ctx.Idents.get("reallocf");
   if (!II_calloc)
     II_calloc =3D &Ctx.Idents.get("calloc");
-
-  if (FD->getIdentifier() =3D=3D II_malloc) {
-    MallocMem(C, CE);
-    return true;
-  }
-
-  if (FD->getIdentifier() =3D=3D II_free) {
-    FreeMem(C, CE);
-    return true;
-  }
-
-  if (FD->getIdentifier() =3D=3D II_realloc) {
-    ReallocMem(C, CE);
-    return true;
-  }
-
-  if (FD->getIdentifier() =3D=3D II_calloc) {
-    CallocMem(C, CE);
-    return true;
-  }
-
-  // Check all the attributes, if there are any.
-  // There can be multiple of these attributes.
-  bool rv =3D false;
-  if (FD->hasAttrs()) {
-    for (specific_attr_iterator<OwnershipAttr>
-                  i =3D FD->specific_attr_begin<OwnershipAttr>(),
-                  e =3D FD->specific_attr_end<OwnershipAttr>();
-         i !=3D e; ++i) {
-      switch ((*i)->getOwnKind()) {
-      case OwnershipAttr::Returns: {
-        MallocMemReturnsAttr(C, CE, *i);
-        rv =3D true;
-        break;
-      }
-      case OwnershipAttr::Takes:
-      case OwnershipAttr::Holds: {
-        FreeMemAttr(C, CE, *i);
-        rv =3D true;
-        break;
-      }
-      default:
-        break;
-      }
-    }
-  }
-  return rv;
+  if (!II_valloc)
+    II_valloc =3D &Ctx.Idents.get("valloc");
+  if (!II_strdup)
+    II_strdup =3D &Ctx.Idents.get("strdup");
+  if (!II_strndup)
+    II_strndup =3D &Ctx.Idents.get("strndup");
 }
=20
-void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
-  const ProgramState *state =3D MallocMemAux(C, CE, CE->getArg(0), Undefin=
edVal(),
-                                      C.getState());
-  C.addTransition(state);
+bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) c=
onst {
+  if (!FD)
+    return false;
+  IdentifierInfo *FunI =3D FD->getIdentifier();
+  if (!FunI)
+    return false;
+
+  initIdentifierInfo(C);
+
+  if (FunI =3D=3D II_malloc || FunI =3D=3D II_free || FunI =3D=3D II_reall=
oc ||
+      FunI =3D=3D II_reallocf || FunI =3D=3D II_calloc || FunI =3D=3D II_v=
alloc ||
+      FunI =3D=3D II_strdup || FunI =3D=3D II_strndup)
+    return true;
+
+  if (Filter.CMallocOptimistic && FD->hasAttrs() &&
+      FD->specific_attr_begin<OwnershipAttr>() !=3D
+          FD->specific_attr_end<OwnershipAttr>())
+    return true;
+
+
+  return false;
 }
=20
-void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr=
 *CE,
-                                         const OwnershipAttr* Att) {
+void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) c=
onst {
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
+  if (!FD)
+    return;
+
+  initIdentifierInfo(C.getASTContext());
+  IdentifierInfo *FunI =3D FD->getIdentifier();
+  if (!FunI)
+    return;
+
+  ProgramStateRef State =3D C.getState();
+  if (FunI =3D=3D II_malloc || FunI =3D=3D II_valloc) {
+    if (CE->getNumArgs() < 1)
+      return;
+    State =3D MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
+  } else if (FunI =3D=3D II_realloc) {
+    State =3D ReallocMem(C, CE, false);
+  } else if (FunI =3D=3D II_reallocf) {
+    State =3D ReallocMem(C, CE, true);
+  } else if (FunI =3D=3D II_calloc) {
+    State =3D CallocMem(C, CE);
+  } else if (FunI =3D=3D II_free) {
+    State =3D FreeMemAux(C, CE, C.getState(), 0, false);
+  } else if (FunI =3D=3D II_strdup) {
+    State =3D MallocUpdateRefState(C, CE, State);
+  } else if (FunI =3D=3D II_strndup) {
+    State =3D MallocUpdateRefState(C, CE, State);
+  } else if (Filter.CMallocOptimistic) {
+    // Check all the attributes, if there are any.
+    // There can be multiple of these attributes.
+    if (FD->hasAttrs())
+      for (specific_attr_iterator<OwnershipAttr>
+          i =3D FD->specific_attr_begin<OwnershipAttr>(),
+          e =3D FD->specific_attr_end<OwnershipAttr>();
+          i !=3D e; ++i) {
+        switch ((*i)->getOwnKind()) {
+        case OwnershipAttr::Returns:
+          State =3D MallocMemReturnsAttr(C, CE, *i);
+          break;
+        case OwnershipAttr::Takes:
+        case OwnershipAttr::Holds:
+          State =3D FreeMemAttr(C, CE, *i);
+          break;
+        }
+      }
+  }
+  C.addTransition(State);
+}
+
+ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
+                                                    const CallExpr *CE,
+                                                    const OwnershipAttr* A=
tt) {
   if (Att->getModule() !=3D "malloc")
-    return;
+    return 0;
=20
   OwnershipAttr::args_iterator I =3D Att->args_begin(), E =3D Att->args_en=
d();
   if (I !=3D E) {
-    const ProgramState *state =3D
-        MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
-    C.addTransition(state);
-    return;
+    return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState(=
));
   }
-  const ProgramState *state =3D MallocMemAux(C, CE, UnknownVal(), Undefine=
dVal(),
-                                        C.getState());
-  C.addTransition(state);
+  return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
 }
=20
-const ProgramState *MallocChecker::MallocMemAux(CheckerContext &C, =20
+ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
                                            const CallExpr *CE,
                                            SVal Size, SVal Init,
-                                           const ProgramState *state) {
-  unsigned Count =3D C.getCurrentBlockCount();
-  SValBuilder &svalBuilder =3D C.getSValBuilder();
+                                           ProgramStateRef state) {
+  // Get the return value.
+  SVal retVal =3D state->getSVal(CE, C.getLocationContext());
=20
-  // Set the return value.
-  SVal retVal =3D svalBuilder.getConjuredSymbolVal(NULL, CE, CE->getType()=
, Count);
-  state =3D state->BindExpr(CE, retVal);
+  // We expect the malloc functions to return a pointer.
+  if (!isa<Loc>(retVal))
+    return 0;
=20
   // Fill the region with the initialization value.
   state =3D state->bindDefault(retVal, Init);
=20
   // Set the region's extent equal to the Size parameter.
-  const SymbolicRegion *R =3D cast<SymbolicRegion>(retVal.getAsRegion());
-  DefinedOrUnknownSVal Extent =3D R->getExtent(svalBuilder);
-  DefinedOrUnknownSVal DefinedSize =3D cast<DefinedOrUnknownSVal>(Size);
-  DefinedOrUnknownSVal extentMatchesSize =3D
-    svalBuilder.evalEQ(state, Extent, DefinedSize);
+  const SymbolicRegion *R =3D
+      dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
+  if (!R)
+    return 0;
+  if (isa<DefinedOrUnknownSVal>(Size)) {
+    SValBuilder &svalBuilder =3D C.getSValBuilder();
+    DefinedOrUnknownSVal Extent =3D R->getExtent(svalBuilder);
+    DefinedOrUnknownSVal DefinedSize =3D cast<DefinedOrUnknownSVal>(Size);
+    DefinedOrUnknownSVal extentMatchesSize =3D
+        svalBuilder.evalEQ(state, Extent, DefinedSize);
=20
-  state =3D state->assume(extentMatchesSize, true);
-  assert(state);
+    state =3D state->assume(extentMatchesSize, true);
+    assert(state);
+  }
  =20
+  return MallocUpdateRefState(C, CE, state);
+}
+
+ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
+                                                    const CallExpr *CE,
+                                                    ProgramStateRef state)=
 {
+  // Get the return value.
+  SVal retVal =3D state->getSVal(CE, C.getLocationContext());
+
+  // We expect the malloc functions to return a pointer.
+  if (!isa<Loc>(retVal))
+    return 0;
+
   SymbolRef Sym =3D retVal.getAsLocSymbol();
   assert(Sym);
=20
   // Set the symbol's state to Allocated.
   return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
+
 }
=20
-void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D FreeMemAux(C, CE, C.getState(), 0, false);
+ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
+                                           const CallExpr *CE,
+                                           const OwnershipAttr* Att) const=
 {
+  if (Att->getModule() !=3D "malloc")
+    return 0;
=20
-  if (state)
-    C.addTransition(state);
-}
-
-void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
-                                const OwnershipAttr* Att) const {
-  if (Att->getModule() !=3D "malloc")
-    return;
+  ProgramStateRef State =3D C.getState();
=20
   for (OwnershipAttr::args_iterator I =3D Att->args_begin(), E =3D Att->ar=
gs_end();
        I !=3D E; ++I) {
-    const ProgramState *state =3D FreeMemAux(C, CE, C.getState(), *I,
-                                      Att->getOwnKind() =3D=3D OwnershipAt=
tr::Holds);
-    if (state)
-      C.addTransition(state);
+    ProgramStateRef StateI =3D FreeMemAux(C, CE, State, *I,
+                               Att->getOwnKind() =3D=3D OwnershipAttr::Hol=
ds);
+    if (StateI)
+      State =3D StateI;
   }
+  return State;
 }
=20
-const ProgramState *MallocChecker::FreeMemAux(CheckerContext &C, const Cal=
lExpr *CE,
-                                         const ProgramState *state, unsign=
ed Num,
-                                         bool Hold) const {
+ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
+                                          const CallExpr *CE,
+                                          ProgramStateRef state,
+                                          unsigned Num,
+                                          bool Hold) const {
+  if (CE->getNumArgs() < (Num + 1))
+    return 0;
+
   const Expr *ArgExpr =3D CE->getArg(Num);
-  SVal ArgVal =3D state->getSVal(ArgExpr);
-
+  SVal ArgVal =3D state->getSVal(ArgExpr, C.getLocationContext());
+  if (!isa<DefinedOrUnknownSVal>(ArgVal))
+    return 0;
   DefinedOrUnknownSVal location =3D cast<DefinedOrUnknownSVal>(ArgVal);
=20
   // Check for null dereferences.
   if (!isa<Loc>(location))
-    return state;
-
-  // FIXME: Technically using 'Assume' here can result in a path
-  //  bifurcation.  In such cases we need to return two states, not just o=
ne.
-  const ProgramState *notNullState, *nullState;
-  llvm::tie(notNullState, nullState) =3D state->assume(location);
+    return 0;
=20
   // The explicit NULL case, no operation is performed.
+  ProgramStateRef notNullState, nullState;
+  llvm::tie(notNullState, nullState) =3D state->assume(location);
   if (nullState && !notNullState)
-    return nullState;
-
-  assert(notNullState);
+    return 0;
=20
   // Unknown values could easily be okay
   // Undefined values are handled elsewhere
   if (ArgVal.isUnknownOrUndef())
-    return notNullState;
+    return 0;
=20
   const MemRegion *R =3D ArgVal.getAsRegion();
  =20
@@ -303,7 +522,7 @@
   // Non-region locations (labels and fixed addresses) also shouldn't be f=
reed.
   if (!R) {
     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
-    return NULL;
+    return 0;
   }
  =20
   R =3D R->StripCasts();
@@ -311,7 +530,7 @@
   // Blocks might show up as heap data, but should not be free()d
   if (isa<BlockDataRegion>(R)) {
     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
-    return NULL;
+    return 0;
   }
  =20
   const MemSpaceRegion *MS =3D R->getMemorySpace();
@@ -327,14 +546,14 @@
     // False negatives are better than false positives.
    =20
     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
-    return NULL;
+    return 0;
   }
  =20
   const SymbolicRegion *SR =3D dyn_cast<SymbolicRegion>(R);
   // Various cases could lead to non-symbol values here.
   // For now, ignore them.
   if (!SR)
-    return notNullState;
+    return 0;
=20
   SymbolRef Sym =3D SR->getSymbol();
   const RefState *RS =3D state->get<RegionState>(Sym);
@@ -343,27 +562,28 @@
   // called on a pointer that does not get its pointee directly from mallo=
c().=20
   // Full support of this requires inter-procedural analysis.
   if (!RS)
-    return notNullState;
+    return 0;
=20
   // Check double free.
   if (RS->isReleased()) {
     if (ExplodedNode *N =3D C.generateSink()) {
       if (!BT_DoubleFree)
         BT_DoubleFree.reset(
-          new BuiltinBug("Double free",
-                         "Try to free a memory block that has been release=
d"));
-      // FIXME: should find where it's freed last time.
+          new BugType("Double free", "Memory Error"));
       BugReport *R =3D new BugReport(*BT_DoubleFree,=20
-                                   BT_DoubleFree->getDescription(), N);
+                        "Attempt to free released memory", N);
+      R->addRange(ArgExpr->getSourceRange());
+      R->markInteresting(Sym);
+      R->addVisitor(new MallocBugVisitor(Sym));
       C.EmitReport(R);
     }
-    return NULL;
+    return 0;
   }
=20
   // Normal free.
   if (Hold)
-    return notNullState->set<RegionState>(Sym, RefState::getRelinquished(C=
E));
-  return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
+    return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
+  return state->set<RegionState>(Sym, RefState::getReleased(CE));
 }
=20
 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
@@ -400,8 +620,7 @@
   default: {
     const MemSpaceRegion *MS =3D MR->getMemorySpace();
    =20
-    switch (MS->getKind()) {
-    case MemRegion::StackLocalsSpaceRegionKind: {
+    if (isa<StackLocalsSpaceRegion>(MS)) {
       const VarRegion *VR =3D dyn_cast<VarRegion>(MR);
       const VarDecl *VD;
       if (VR)
@@ -415,7 +634,8 @@
         os << "the address of a local stack variable";
       return true;
     }
-    case MemRegion::StackArgumentsSpaceRegionKind: {
+
+    if (isa<StackArgumentsSpaceRegion>(MS)) {
       const VarRegion *VR =3D dyn_cast<VarRegion>(MR);
       const VarDecl *VD;
       if (VR)
@@ -429,8 +649,8 @@
         os << "the address of a parameter";
       return true;
     }
-    case MemRegion::NonStaticGlobalSpaceRegionKind:
-    case MemRegion::StaticGlobalSpaceRegionKind: {
+
+    if (isa<GlobalsSpaceRegion>(MS)) {
       const VarRegion *VR =3D dyn_cast<VarRegion>(MR);
       const VarDecl *VD;
       if (VR)
@@ -447,9 +667,8 @@
         os << "the address of a global variable";
       return true;
     }
-    default:
-      return false;
-    }
+
+    return false;
   }
   }
 }
@@ -458,9 +677,9 @@
                                   SourceRange range) const {
   if (ExplodedNode *N =3D C.generateSink()) {
     if (!BT_BadFree)
-      BT_BadFree.reset(new BuiltinBug("Bad free"));
+      BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
    =20
-    llvm::SmallString<100> buf;
+    SmallString<100> buf;
     llvm::raw_svector_ostream os(buf);
    =20
     const MemRegion *MR =3D ArgVal.getAsRegion();
@@ -487,16 +706,25 @@
     }
    =20
     BugReport *R =3D new BugReport(*BT_BadFree, os.str(), N);
+    R->markInteresting(MR);
     R->addRange(range);
     C.EmitReport(R);
   }
 }
=20
-void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) cons=
t {
-  const ProgramState *state =3D C.getState();
+ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
+                                          const CallExpr *CE,
+                                          bool FreesOnFail) const {
+  if (CE->getNumArgs() < 2)
+    return 0;
+
+  ProgramStateRef state =3D C.getState();
   const Expr *arg0Expr =3D CE->getArg(0);
-  DefinedOrUnknownSVal arg0Val=20
-    =3D cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr));
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal Arg0Val =3D state->getSVal(arg0Expr, LCtx);
+  if (!isa<DefinedOrUnknownSVal>(Arg0Val))
+    return 0;
+  DefinedOrUnknownSVal arg0Val =3D cast<DefinedOrUnknownSVal>(Arg0Val);
=20
   SValBuilder &svalBuilder =3D C.getSValBuilder();
=20
@@ -506,65 +734,166 @@
   // Get the size argument. If there is no size arg then give up.
   const Expr *Arg1 =3D CE->getArg(1);
   if (!Arg1)
-    return;
+    return 0;
=20
   // Get the value of the size argument.
-  DefinedOrUnknownSVal Arg1Val =3D=20
-    cast<DefinedOrUnknownSVal>(state->getSVal(Arg1));
+  SVal Arg1ValG =3D state->getSVal(Arg1, LCtx);
+  if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
+    return 0;
+  DefinedOrUnknownSVal Arg1Val =3D cast<DefinedOrUnknownSVal>(Arg1ValG);
=20
   // Compare the size argument to 0.
   DefinedOrUnknownSVal SizeZero =3D
     svalBuilder.evalEQ(state, Arg1Val,
                        svalBuilder.makeIntValWithPtrWidth(0, false));
=20
+  ProgramStateRef StatePtrIsNull, StatePtrNotNull;
+  llvm::tie(StatePtrIsNull, StatePtrNotNull) =3D state->assume(PtrEQ);
+  ProgramStateRef StateSizeIsZero, StateSizeNotZero;
+  llvm::tie(StateSizeIsZero, StateSizeNotZero) =3D state->assume(SizeZero);
+  // We only assume exceptional states if they are definitely true; if the
+  // state is under-constrained, assume regular realloc behavior.
+  bool PrtIsNull =3D StatePtrIsNull && !StatePtrNotNull;
+  bool SizeIsZero =3D StateSizeIsZero && !StateSizeNotZero;
+
   // If the ptr is NULL and the size is not 0, the call is equivalent to=20
   // malloc(size).
-  const ProgramState *stateEqual =3D state->assume(PtrEQ, true);
-  if (stateEqual && state->assume(SizeZero, false)) {
-    // Hack: set the NULL symbolic region to released to suppress false wa=
rning.
-    // In the future we should add more states for allocated regions, e.g.=
,=20
-    // CheckedNull, CheckedNonNull.
-   =20
-    SymbolRef Sym =3D arg0Val.getAsLocSymbol();
-    if (Sym)
-      stateEqual =3D stateEqual->set<RegionState>(Sym, RefState::getReleas=
ed(CE));
-
-    const ProgramState *stateMalloc =3D MallocMemAux(C, CE, CE->getArg(1),=20
-                                              UndefinedVal(), stateEqual);
-    C.addTransition(stateMalloc);
+  if ( PrtIsNull && !SizeIsZero) {
+    ProgramStateRef stateMalloc =3D MallocMemAux(C, CE, CE->getArg(1),
+                                               UndefinedVal(), StatePtrIsN=
ull);
+    return stateMalloc;
   }
=20
-  if (const ProgramState *stateNotEqual =3D state->assume(PtrEQ, false)) {
-    // If the size is 0, free the memory.
-    if (const ProgramState *stateSizeZero =3D stateNotEqual->assume(SizeZe=
ro, true))
-      if (const ProgramState *stateFree =3D=20
-          FreeMemAux(C, CE, stateSizeZero, 0, false)) {
+  if (PrtIsNull && SizeIsZero)
+    return 0;
=20
-        // Bind the return value to NULL because it is now free.
-        C.addTransition(stateFree->BindExpr(CE, svalBuilder.makeNull(), tr=
ue));
-      }
-    if (const ProgramState *stateSizeNotZero =3D stateNotEqual->assume(Siz=
eZero,false))
-      if (const ProgramState *stateFree =3D FreeMemAux(C, CE, stateSizeNot=
Zero,
-                                                0, false)) {
-        // FIXME: We should copy the content of the original buffer.
-        const ProgramState *stateRealloc =3D MallocMemAux(C, CE, CE->getAr=
g(1),=20
-                                                   UnknownVal(), stateFree=
);
-        C.addTransition(stateRealloc);
-      }
+  // Get the from and to pointer symbols as in toPtr =3D realloc(fromPtr, =
size).
+  assert(!PrtIsNull);
+  SymbolRef FromPtr =3D arg0Val.getAsSymbol();
+  SVal RetVal =3D state->getSVal(CE, LCtx);
+  SymbolRef ToPtr =3D RetVal.getAsSymbol();
+  if (!FromPtr || !ToPtr)
+    return 0;
+
+  // If the size is 0, free the memory.
+  if (SizeIsZero)
+    if (ProgramStateRef stateFree =3D FreeMemAux(C, CE, StateSizeIsZero,0,=
false)){
+      // The semantics of the return value are:
+      // If size was equal to 0, either NULL or a pointer suitable to be p=
assed
+      // to free() is returned.
+      stateFree =3D stateFree->set<ReallocPairs>(ToPtr,
+                                            ReallocPair(FromPtr, FreesOnFa=
il));
+      C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
+      return stateFree;
+    }
+
+  // Default behavior.
+  if (ProgramStateRef stateFree =3D FreeMemAux(C, CE, state, 0, false)) {
+    // FIXME: We should copy the content of the original buffer.
+    ProgramStateRef stateRealloc =3D MallocMemAux(C, CE, CE->getArg(1),
+                                                UnknownVal(), stateFree);
+    if (!stateRealloc)
+      return 0;
+    stateRealloc =3D stateRealloc->set<ReallocPairs>(ToPtr,
+                                            ReallocPair(FromPtr, FreesOnFa=
il));
+    C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
+    return stateRealloc;
   }
+  return 0;
 }
=20
-void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
-  const ProgramState *state =3D C.getState();
+ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr=
 *CE){
+  if (CE->getNumArgs() < 2)
+    return 0;
+
+  ProgramStateRef state =3D C.getState();
   SValBuilder &svalBuilder =3D C.getSValBuilder();
-
-  SVal count =3D state->getSVal(CE->getArg(0));
-  SVal elementSize =3D state->getSVal(CE->getArg(1));
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal count =3D state->getSVal(CE->getArg(0), LCtx);
+  SVal elementSize =3D state->getSVal(CE->getArg(1), LCtx);
   SVal TotalSize =3D svalBuilder.evalBinOp(state, BO_Mul, count, elementSi=
ze,
                                         svalBuilder.getContext().getSizeTy=
pe()); =20
   SVal zeroVal =3D svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy=
);
=20
-  C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
+  return MallocMemAux(C, CE, TotalSize, zeroVal, state);
+}
+
+LeakInfo
+MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
+                                 CheckerContext &C) const {
+  const LocationContext *LeakContext =3D N->getLocationContext();
+  // Walk the ExplodedGraph backwards and find the first node that referre=
d to
+  // the tracked symbol.
+  const ExplodedNode *AllocNode =3D N;
+  const MemRegion *ReferenceRegion =3D 0;
+
+  while (N) {
+    ProgramStateRef State =3D N->getState();
+    if (!State->get<RegionState>(Sym))
+      break;
+
+    // Find the most recent expression bound to the symbol in the current
+    // context.
+    if (!ReferenceRegion) {
+      if (const MemRegion *MR =3D C.getLocationRegionIfPostStore(N)) {
+        SVal Val =3D State->getSVal(MR);
+        if (Val.getAsLocSymbol() =3D=3D Sym)
+          ReferenceRegion =3D MR;
+      }
+    }
+
+    // Allocation node, is the last node in the current context in which t=
he
+    // symbol was tracked.
+    if (N->getLocationContext() =3D=3D LeakContext)
+      AllocNode =3D N;
+    N =3D N->pred_empty() ? NULL : *(N->pred_begin());
+  }
+
+  ProgramPoint P =3D AllocNode->getLocation();
+  const Stmt *AllocationStmt =3D 0;
+  if (isa<StmtPoint>(P))
+    AllocationStmt =3D cast<StmtPoint>(P).getStmt();
+
+  return LeakInfo(AllocationStmt, ReferenceRegion);
+}
+
+void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
+                               CheckerContext &C) const {
+  assert(N);
+  if (!BT_Leak) {
+    BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
+    // Leaks should not be reported if they are post-dominated by a sink:
+    // (1) Sinks are higher importance bugs.
+    // (2) NoReturnFunctionChecker uses sink nodes to represent paths endi=
ng
+    //     with __noreturn functions such as assert() or exit(). We choose=
 not
+    //     to report leaks on such paths.
+    BT_Leak->setSuppressOnSink(true);
+  }
+
+  // Most bug reports are cached at the location where they occurred.
+  // With leaks, we want to unique them by the location where they were
+  // allocated, and only report a single path.
+  PathDiagnosticLocation LocUsedForUniqueing;
+  const Stmt *AllocStmt =3D 0;
+  const MemRegion *Region =3D 0;
+  llvm::tie(AllocStmt, Region) =3D getAllocationSite(N, Sym, C);
+  if (AllocStmt)
+    LocUsedForUniqueing =3D PathDiagnosticLocation::createBegin(AllocStmt,
+                            C.getSourceManager(), N->getLocationContext());
+
+  SmallString<200> buf;
+  llvm::raw_svector_ostream os(buf);
+  os << "Memory is never released; potential leak";
+  if (Region) {
+    os << " of memory pointed to by '";
+    Region->dumpPretty(os);
+    os <<'\'';
+  }
+
+  BugReport *R =3D new BugReport(*BT_Leak, os.str(), N, LocUsedForUniquein=
g);
+  R->markInteresting(Sym);
+  R->addVisitor(new MallocBugVisitor(Sym));
+  C.EmitReport(R);
 }
=20
 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
@@ -573,174 +902,562 @@
   if (!SymReaper.hasDeadSymbols())
     return;
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   RegionStateTy RS =3D state->get<RegionState>();
   RegionStateTy::Factory &F =3D state->get_context<RegionState>();
=20
   bool generateReport =3D false;
- =20
+  llvm::SmallVector<SymbolRef, 2> Errors;
   for (RegionStateTy::iterator I =3D RS.begin(), E =3D RS.end(); I !=3D E;=
 ++I) {
     if (SymReaper.isDead(I->first)) {
-      if (I->second.isAllocated())
+      if (I->second.isAllocated()) {
         generateReport =3D true;
-
+        Errors.push_back(I->first);
+      }
       // Remove the dead symbol from the map.
       RS =3D F.remove(RS, I->first);
=20
     }
   }
  =20
-  ExplodedNode *N =3D C.generateNode(state->set<RegionState>(RS));
+  // Cleanup the Realloc Pairs Map.
+  ReallocMap RP =3D state->get<ReallocPairs>();
+  for (ReallocMap::iterator I =3D RP.begin(), E =3D RP.end(); I !=3D E; ++=
I) {
+    if (SymReaper.isDead(I->first) ||
+        SymReaper.isDead(I->second.ReallocatedSym)) {
+      state =3D state->remove<ReallocPairs>(I->first);
+    }
+  }
=20
-  // FIXME: This does not handle when we have multiple leaks at a single
-  // place.
-  if (N && generateReport) {
-    if (!BT_Leak)
-      BT_Leak.reset(new BuiltinBug("Memory leak",
-              "Allocated memory never released. Potential memory leak."));
-    // FIXME: where it is allocated.
-    BugReport *R =3D new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
-    C.EmitReport(R);
+  // Generate leak node.
+  static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
+  ExplodedNode *N =3D C.addTransition(C.getState(), C.getPredecessor(), &T=
ag);
+
+  if (generateReport) {
+    for (llvm::SmallVector<SymbolRef, 2>::iterator
+         I =3D Errors.begin(), E =3D Errors.end(); I !=3D E; ++I) {
+      reportLeak(*I, N, C);
+    }
   }
+  C.addTransition(state->set<RegionState>(RS), N);
 }
=20
-void MallocChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
-                                 ExprEngine &Eng) const {
-  const ProgramState *state =3D B.getState();
+void MallocChecker::checkEndPath(CheckerContext &C) const {
+  ProgramStateRef state =3D C.getState();
   RegionStateTy M =3D state->get<RegionState>();
=20
+  // If inside inlined call, skip it.
+  if (C.getLocationContext()->getParent() !=3D 0)
+    return;
+
   for (RegionStateTy::iterator I =3D M.begin(), E =3D M.end(); I !=3D E; +=
+I) {
     RefState RS =3D I->second;
     if (RS.isAllocated()) {
-      ExplodedNode *N =3D B.generateNode(state);
-      if (N) {
-        if (!BT_Leak)
-          BT_Leak.reset(new BuiltinBug("Memory leak",
-                    "Allocated memory never released. Potential memory lea=
k."));
-        BugReport *R =3D new BugReport(*BT_Leak, BT_Leak->getDescription()=
, N);
-        Eng.getBugReporter().EmitReport(R);
-      }
+      ExplodedNode *N =3D C.addTransition(state);
+      if (N)
+        reportLeak(I->first, N, C);
+    }
+  }
+}
+
+bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
+                                CheckerContext &C) const {
+  ProgramStateRef state =3D C.getState();
+  const RefState *RS =3D state->get<RegionState>(Sym);
+  if (!RS)
+    return false;
+
+  if (RS->isAllocated()) {
+    state =3D state->set<RegionState>(Sym, RefState::getEscaped(S));
+    C.addTransition(state);
+    return true;
+  }
+  return false;
+}
+
+void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) co=
nst {
+  if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
+    return;
+
+  // Check use after free, when a freed pointer is passed to a call.
+  ProgramStateRef State =3D C.getState();
+  for (CallExpr::const_arg_iterator I =3D CE->arg_begin(),
+                                    E =3D CE->arg_end(); I !=3D E; ++I) {
+    const Expr *A =3D *I;
+    if (A->getType().getTypePtr()->isAnyPointerType()) {
+      SymbolRef Sym =3D State->getSVal(A, C.getLocationContext()).getAsSym=
bol();
+      if (!Sym)
+        continue;
+      if (checkUseAfterFree(Sym, C, A))
+        return;
     }
   }
 }
=20
 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) c=
onst {
-  const Expr *retExpr =3D S->getRetValue();
-  if (!retExpr)
+  const Expr *E =3D S->getRetValue();
+  if (!E)
     return;
=20
-  const ProgramState *state =3D C.getState();
-
-  SymbolRef Sym =3D state->getSVal(retExpr).getAsSymbol();
+  // Check if we are returning a symbol.
+  SVal RetVal =3D C.getState()->getSVal(E, C.getLocationContext());
+  SymbolRef Sym =3D RetVal.getAsSymbol();
+  if (!Sym)
+    // If we are returning a field of the allocated struct or an array ele=
ment,
+    // the callee could still free the memory.
+    // TODO: This logic should be a part of generic symbol escape callback.
+    if (const MemRegion *MR =3D RetVal.getAsRegion())
+      if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
+        if (const SymbolicRegion *BMR =3D
+              dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
+          Sym =3D BMR->getSymbol();
   if (!Sym)
     return;
=20
-  const RefState *RS =3D state->get<RegionState>(Sym);
-  if (!RS)
+  // Check if we are returning freed memory.
+  if (checkUseAfterFree(Sym, C, E))
     return;
=20
-  // FIXME: check other cases.
-  if (RS->isAllocated())
-    state =3D state->set<RegionState>(Sym, RefState::getEscaped(S));
+  // If this function body is not inlined, check if the symbol is escaping.
+  if (C.getLocationContext()->getParent() =3D=3D 0)
+    checkEscape(Sym, E, C);
+}
=20
+// TODO: Blocks should be either inlined or should call invalidate regions
+// upon invocation. After that's in place, special casing here will not be=20
+// needed.
+void MallocChecker::checkPostStmt(const BlockExpr *BE,
+                                  CheckerContext &C) const {
+
+  // Scan the BlockDecRefExprs for any object the retain count checker
+  // may be tracking.
+  if (!BE->getBlockDecl()->hasCaptures())
+    return;
+
+  ProgramStateRef state =3D C.getState();
+  const BlockDataRegion *R =3D
+    cast<BlockDataRegion>(state->getSVal(BE,
+                                         C.getLocationContext()).getAsRegi=
on());
+
+  BlockDataRegion::referenced_vars_iterator I =3D R->referenced_vars_begin=
(),
+                                            E =3D R->referenced_vars_end();
+
+  if (I =3D=3D E)
+    return;
+
+  SmallVector<const MemRegion*, 10> Regions;
+  const LocationContext *LC =3D C.getLocationContext();
+  MemRegionManager &MemMgr =3D C.getSValBuilder().getRegionManager();
+
+  for ( ; I !=3D E; ++I) {
+    const VarRegion *VR =3D *I;
+    if (VR->getSuperRegion() =3D=3D R) {
+      VR =3D MemMgr.getVarRegion(VR->getDecl(), LC);
+    }
+    Regions.push_back(VR);
+  }
+
+  state =3D
+    state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
+                                    Regions.data() + Regions.size()).getSt=
ate();
   C.addTransition(state);
 }
=20
-const ProgramState *MallocChecker::evalAssume(const ProgramState *state, S=
Val Cond,=20
-                                         bool Assumption) const {
-  // If a symblic region is assumed to NULL, set its state to AllocateFail=
ed.
-  // FIXME: should also check symbols assumed to non-null.
+bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
+                                      const Stmt *S) const {
+  assert(Sym);
+  const RefState *RS =3D C.getState()->get<RegionState>(Sym);
+  if (RS && RS->isReleased()) {
+    if (ExplodedNode *N =3D C.generateSink()) {
+      if (!BT_UseFree)
+        BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
=20
-  RegionStateTy RS =3D state->get<RegionState>();
-
-  for (RegionStateTy::iterator I =3D RS.begin(), E =3D RS.end(); I !=3D E;=
 ++I) {
-    // If the symbol is assumed to NULL, this will return an APSInt*.
-    if (state->getSymVal(I.getKey()))
-      state =3D state->set<RegionState>(I.getKey(),RefState::getAllocateFa=
iled());
+      BugReport *R =3D new BugReport(*BT_UseFree,
+                                   "Use of memory after it is freed",N);
+      if (S)
+        R->addRange(S->getSourceRange());
+      R->markInteresting(Sym);
+      R->addVisitor(new MallocBugVisitor(Sym));
+      C.EmitReport(R);
+      return true;
+    }
   }
-
-  return state;
+  return false;
 }
=20
 // Check if the location is a freed symbolic region.
 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
                                   CheckerContext &C) const {
   SymbolRef Sym =3D l.getLocSymbolInBase();
-  if (Sym) {
-    const RefState *RS =3D C.getState()->get<RegionState>(Sym);
-    if (RS && RS->isReleased()) {
-      if (ExplodedNode *N =3D C.generateNode()) {
-        if (!BT_UseFree)
-          BT_UseFree.reset(new BuiltinBug("Use dynamically allocated memor=
y "
-                                          "after it is freed."));
+  if (Sym)
+    checkUseAfterFree(Sym, C);
+}
=20
-        BugReport *R =3D new BugReport(*BT_UseFree, BT_UseFree->getDescrip=
tion(),
-                                     N);
-        C.EmitReport(R);
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Check various ways a symbol can be invalidated.
+// TODO: This logic (the next 3 functions) is copied/similar to the
+// RetainRelease checker. We might want to factor this out.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+// Stop tracking symbols when a value escapes as a result of checkBind.
+// A value escapes in three possible cases:
+// (1) we are binding to something that is not a memory region.
+// (2) we are binding to a memregion that does not have stack storage
+// (3) we are binding to a memregion with stack storage that the store
+//     does not understand.
+void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
+                              CheckerContext &C) const {
+  // Are we storing to something that causes the value to "escape"?
+  bool escapes =3D true;
+  ProgramStateRef state =3D C.getState();
+
+  if (loc::MemRegionVal *regionLoc =3D dyn_cast<loc::MemRegionVal>(&loc)) {
+    escapes =3D !regionLoc->getRegion()->hasStackStorage();
+
+    if (!escapes) {
+      // To test (3), generate a new state with the binding added.  If it =
is
+      // the same state, then it escapes (since the store cannot represent
+      // the binding).
+      escapes =3D (state =3D=3D (state->bindLoc(*regionLoc, val)));
+    }
+    if (!escapes) {
+      // Case 4: We do not currently model what happens when a symbol is
+      // assigned to a struct field, so be conservative here and let the s=
ymbol
+      // go. TODO: This could definitely be improved upon.
+      escapes =3D !isa<VarRegion>(regionLoc->getRegion());
+    }
+  }
+
+  // If our store can represent the binding and we aren't storing to somet=
hing
+  // that doesn't have local storage then just return and have the simulat=
ion
+  // state continue as is.
+  if (!escapes)
+      return;
+
+  // Otherwise, find all symbols referenced by 'val' that we are tracking
+  // and stop tracking them.
+  state =3D state->scanReachableSymbols<StopTrackingCallback>(val).getStat=
e();
+  C.addTransition(state);
+}
+
+// If a symbolic region is assumed to NULL (or another constant), stop tra=
cking
+// it - assuming that allocation failed on this path.
+ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
+                                              SVal Cond,
+                                              bool Assumption) const {
+  RegionStateTy RS =3D state->get<RegionState>();
+  for (RegionStateTy::iterator I =3D RS.begin(), E =3D RS.end(); I !=3D E;=
 ++I) {
+    // If the symbol is assumed to NULL or another constant, this will
+    // return an APSInt*.
+    if (state->getSymVal(I.getKey()))
+      state =3D state->remove<RegionState>(I.getKey());
+  }
+
+  // Realloc returns 0 when reallocation fails, which means that we should
+  // restore the state of the pointer being reallocated.
+  ReallocMap RP =3D state->get<ReallocPairs>();
+  for (ReallocMap::iterator I =3D RP.begin(), E =3D RP.end(); I !=3D E; ++=
I) {
+    // If the symbol is assumed to NULL or another constant, this will
+    // return an APSInt*.
+    if (state->getSymVal(I.getKey())) {
+      SymbolRef ReallocSym =3D I.getData().ReallocatedSym;
+      const RefState *RS =3D state->get<RegionState>(ReallocSym);
+      if (RS) {
+        if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
+          state =3D state->set<RegionState>(ReallocSym,
+                             RefState::getAllocateUnchecked(RS->getStmt())=
);
+      }
+      state =3D state->remove<ReallocPairs>(I.getKey());
+    }
+  }
+
+  return state;
+}
+
+// Check if the function is known to us. So, for example, we could
+// conservatively assume it can free/reallocate it's pointer arguments.
+// (We assume that the pointers cannot escape through calls to system
+// functions not handled by this checker.)
+bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
+                                      ProgramStateRef State) const {
+  if (!Call)
+    return false;
+
+  // For now, assume that any C++ call can free memory.
+  // TODO: If we want to be more optimistic here, we'll need to make sure =
that
+  // regions escape to C++ containers. They seem to do that even now, but =
for
+  // mysterious reasons.
+  if (Call->isCXXCall())
+    return false;
+
+  const Decl *D =3D Call->getDecl();
+  if (!D)
+    return false;
+
+  ASTContext &ASTC =3D State->getStateManager().getContext();
+
+  // If it's one of the allocation functions we can reason about, we model
+  // its behavior explicitly.
+  if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
+    return true;
+  }
+
+  // If it's not a system call, assume it frees memory.
+  SourceManager &SM =3D ASTC.getSourceManager();
+  if (!SM.isInSystemHeader(D->getLocation()))
+    return false;
+
+  // Process C/ObjC functions.
+  if (const FunctionDecl *FD  =3D dyn_cast<FunctionDecl>(D)) {
+    // White list the system functions whose arguments escape.
+    const IdentifierInfo *II =3D FD->getIdentifier();
+    if (!II)
+      return true;
+    StringRef FName =3D II->getName();
+
+    // White list thread local storage.
+    if (FName.equals("pthread_setspecific"))
+      return false;
+
+    // White list the 'XXXNoCopy' ObjC functions.
+    if (FName.endswith("NoCopy")) {
+      // Look for the deallocator argument. We know that the memory owners=
hip
+      // is not transfered only if the deallocator argument is
+      // 'kCFAllocatorNull'.
+      for (unsigned i =3D 1; i < Call->getNumArgs(); ++i) {
+        const Expr *ArgE =3D Call->getArg(i)->IgnoreParenCasts();
+        if (const DeclRefExpr *DE =3D dyn_cast<DeclRefExpr>(ArgE)) {
+          StringRef DeallocatorName =3D DE->getFoundDecl()->getName();
+          if (DeallocatorName =3D=3D "kCFAllocatorNull")
+            return true;
+        }
+      }
+      return false;
+    }
+
+    // PR12101
+    // Many CoreFoundation and CoreGraphics might allow a tracked object=20
+    // to escape.
+    if (Call->isCFCGAllowingEscape(FName))
+      return false;
+
+    // Associating streams with malloced buffers. The pointer can escape if
+    // 'closefn' is specified (and if that function does free memory).
+    // Currently, we do not inspect the 'closefn' function (PR12101).
+    if (FName =3D=3D "funopen")
+      if (Call->getNumArgs() >=3D 4 && !Call->getArgSVal(4).isConstant(0))
+        return false;
+
+    // Do not warn on pointers passed to 'setbuf' when used with std strea=
ms,
+    // these leaks might be intentional when setting the buffer for stdio.
+    // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
+    if (FName =3D=3D "setbuf" || FName =3D=3D"setbuffer" ||
+        FName =3D=3D "setlinebuf" || FName =3D=3D "setvbuf") {
+      if (Call->getNumArgs() >=3D 1)
+        if (const DeclRefExpr *Arg =3D
+              dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
+          if (const VarDecl *D =3D dyn_cast<VarDecl>(Arg->getDecl()))
+              if (D->getCanonicalDecl()->getName().find("std")
+                                                   !=3D StringRef::npos)
+                return false;
+    }
+
+    // A bunch of other functions, which take ownership of a pointer (See =
retain
+    // release checker). Not all the parameters here are invalidated, but =
the
+    // Malloc checker cannot differentiate between them. The right way of =
doing
+    // this would be to implement a pointer escapes callback.
+    if (FName =3D=3D "CVPixelBufferCreateWithBytes" ||
+        FName =3D=3D "CGBitmapContextCreateWithData" ||
+        FName =3D=3D "CVPixelBufferCreateWithPlanarBytes" ||
+        FName =3D=3D "OSAtomicEnqueue") {
+      return false;
+    }
+
+    // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they=
 can
+    // be deallocated by NSMapRemove.
+    if (FName.startswith("NS") && (FName.find("Insert") !=3D StringRef::np=
os))
+      return false;
+
+    // Otherwise, assume that the function does not free memory.
+    // Most system calls, do not free the memory.
+    return true;
+
+  // Process ObjC functions.
+  } else if (const ObjCMethodDecl * ObjCD =3D dyn_cast<ObjCMethodDecl>(D))=
 {
+    Selector S =3D ObjCD->getSelector();
+
+    // White list the ObjC functions which do free memory.
+    // - Anything containing 'freeWhenDone' param set to 1.
+    //   Ex: dataWithBytesNoCopy:length:freeWhenDone.
+    for (unsigned i =3D 1; i < S.getNumArgs(); ++i) {
+      if (S.getNameForSlot(i).equals("freeWhenDone")) {
+        if (Call->getArgSVal(i).isConstant(1))
+          return false;
+        else
+          return true;
       }
     }
+
+    // If the first selector ends with NoCopy, assume that the ownership is
+    // transfered as well.
+    // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
+    if (S.getNameForSlot(0).endswith("NoCopy")) {
+      return false;
+    }
+
+    // Otherwise, assume that the function does not free memory.
+    // Most system calls, do not free the memory.
+    return true;
   }
+
+  // Otherwise, assume that the function can free memory.
+  return false;
+
 }
=20
-void MallocChecker::checkBind(SVal location, SVal val,
-                              const Stmt *BindS, CheckerContext &C) const {
-  // The PreVisitBind implements the same algorithm as already used by the=20
-  // Objective C ownership checker: if the pointer escaped from this scope=
 by=20
-  // assignment, let it go.  However, assigning to fields of a stack-stora=
ge=20
-  // structure does not transfer ownership.
+// If the symbol we are tracking is invalidated, but not explicitly (ex: t=
he &p
+// escapes, when we are tracking p), do not track the symbol as we cannot =
reason
+// about it anymore.
+ProgramStateRef
+MallocChecker::checkRegionChanges(ProgramStateRef State,
+                            const StoreManager::InvalidatedSymbols *invali=
dated,
+                                    ArrayRef<const MemRegion *> ExplicitRe=
gions,
+                                    ArrayRef<const MemRegion *> Regions,
+                                    const CallOrObjCMessage *Call) const {
+  if (!invalidated || invalidated->empty())
+    return State;
+  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
=20
-  const ProgramState *state =3D C.getState();
-  DefinedOrUnknownSVal l =3D cast<DefinedOrUnknownSVal>(location);
+  // If it's a call which might free or reallocate memory, we assume that =
all
+  // regions (explicit and implicit) escaped.
=20
-  // Check for null dereferences.
-  if (!isa<Loc>(l))
-    return;
-
-  // Before checking if the state is null, check if 'val' has a RefState.
-  // Only then should we check for null and bifurcate the state.
-  SymbolRef Sym =3D val.getLocSymbolInBase();
-  if (Sym) {
-    if (const RefState *RS =3D state->get<RegionState>(Sym)) {
-      // If ptr is NULL, no operation is performed.
-      const ProgramState *notNullState, *nullState;
-      llvm::tie(notNullState, nullState) =3D state->assume(l);
-
-      // Generate a transition for 'nullState' to record the assumption
-      // that the state was null.
-      if (nullState)
-        C.addTransition(nullState);
-
-      if (!notNullState)
-        return;
-
-      if (RS->isAllocated()) {
-        // Something we presently own is being assigned somewhere.
-        const MemRegion *AR =3D location.getAsRegion();
-        if (!AR)
-          return;
-        AR =3D AR->StripCasts()->getBaseRegion();
-        do {
-          // If it is on the stack, we still own it.
-          if (AR->hasStackNonParametersStorage())
-            break;
-
-          // If the state can't represent this binding, we still own it.
-          if (notNullState =3D=3D (notNullState->bindLoc(cast<Loc>(locatio=
n),
-                                                     UnknownVal())))
-            break;
-
-          // We no longer own this pointer.
-          notNullState =3D
-            notNullState->set<RegionState>(Sym,
-                                        RefState::getRelinquished(BindS));
-        }
-        while (false);
-      }
-      C.addTransition(notNullState);
+  // Otherwise, whitelist explicit pointers; we still can track them.
+  if (!Call || doesNotFreeMemory(Call, State)) {
+    for (ArrayRef<const MemRegion *>::iterator I =3D ExplicitRegions.begin=
(),
+        E =3D ExplicitRegions.end(); I !=3D E; ++I) {
+      if (const SymbolicRegion *R =3D (*I)->StripCasts()->getAs<SymbolicRe=
gion>())
+        WhitelistedSymbols.insert(R->getSymbol());
     }
   }
+
+  for (StoreManager::InvalidatedSymbols::const_iterator I=3Dinvalidated->b=
egin(),
+       E =3D invalidated->end(); I!=3DE; ++I) {
+    SymbolRef sym =3D *I;
+    if (WhitelistedSymbols.count(sym))
+      continue;
+    // The symbol escaped.
+    if (const RefState *RS =3D State->get<RegionState>(sym))
+      State =3D State->set<RegionState>(sym, RefState::getEscaped(RS->getS=
tmt()));
+  }
+  return State;
 }
=20
-void ento::registerMallocChecker(CheckerManager &mgr) {
-  mgr.registerChecker<MallocChecker>();
+static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
+                                         ProgramStateRef prevState) {
+  ReallocMap currMap =3D currState->get<ReallocPairs>();
+  ReallocMap prevMap =3D prevState->get<ReallocPairs>();
+
+  for (ReallocMap::iterator I =3D prevMap.begin(), E =3D prevMap.end();
+       I !=3D E; ++I) {
+    SymbolRef sym =3D I.getKey();
+    if (!currMap.lookup(sym))
+      return sym;
+  }
+
+  return NULL;
 }
+
+PathDiagnosticPiece *
+MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
+                                           const ExplodedNode *PrevN,
+                                           BugReporterContext &BRC,
+                                           BugReport &BR) {
+  ProgramStateRef state =3D N->getState();
+  ProgramStateRef statePrev =3D PrevN->getState();
+
+  const RefState *RS =3D state->get<RegionState>(Sym);
+  const RefState *RSPrev =3D statePrev->get<RegionState>(Sym);
+  if (!RS && !RSPrev)
+    return 0;
+
+  const Stmt *S =3D 0;
+  const char *Msg =3D 0;
+  StackHintGeneratorForSymbol *StackHint =3D 0;
+
+  // Retrieve the associated statement.
+  ProgramPoint ProgLoc =3D N->getLocation();
+  if (isa<StmtPoint>(ProgLoc))
+    S =3D cast<StmtPoint>(ProgLoc).getStmt();
+  // If an assumption was made on a branch, it should be caught
+  // here by looking at the state transition.
+  if (isa<BlockEdge>(ProgLoc)) {
+    const CFGBlock *srcBlk =3D cast<BlockEdge>(ProgLoc).getSrc();
+    S =3D srcBlk->getTerminator();
+  }
+  if (!S)
+    return 0;
+
+  // Find out if this is an interesting point and what is the kind.
+  if (Mode =3D=3D Normal) {
+    if (isAllocated(RS, RSPrev, S)) {
+      Msg =3D "Memory is allocated";
+      StackHint =3D new StackHintGeneratorForSymbol(Sym,
+                                                  "Returned allocated memo=
ry");
+    } else if (isReleased(RS, RSPrev, S)) {
+      Msg =3D "Memory is released";
+      StackHint =3D new StackHintGeneratorForSymbol(Sym,
+                                                  "Returned released memor=
y");
+    } else if (isReallocFailedCheck(RS, RSPrev, S)) {
+      Mode =3D ReallocationFailed;
+      Msg =3D "Reallocation failed";
+      StackHint =3D new StackHintGeneratorForReallocationFailed(Sym,
+                                                       "Reallocation faile=
d");
+
+      if (SymbolRef sym =3D findFailedReallocSymbol(state, statePrev)) {
+        // Is it possible to fail two reallocs WITHOUT testing in between?
+        assert((!FailedReallocSymbol || FailedReallocSymbol =3D=3D sym) &&
+          "We only support one failed realloc at a time.");
+        BR.markInteresting(sym);
+        FailedReallocSymbol =3D sym;
+      }
+    }
+
+  // We are in a special mode if a reallocation failed later in the path.
+  } else if (Mode =3D=3D ReallocationFailed) {
+    assert(FailedReallocSymbol && "No symbol to look for.");
+
+    // Is this is the first appearance of the reallocated symbol?
+    if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
+      // If we ever hit this assert, that means BugReporter has decided to=
 skip
+      // node pairs or visit them out of order.
+      assert(state->get<RegionState>(FailedReallocSymbol) &&
+        "Missed the reallocation point");
+
+      // We're at the reallocation point.
+      Msg =3D "Attempt to reallocate memory";
+      StackHint =3D new StackHintGeneratorForSymbol(Sym,
+                                                 "Returned reallocated mem=
ory");
+      FailedReallocSymbol =3D NULL;
+      Mode =3D Normal;
+    }
+  }
+
+  if (!Msg)
+    return 0;
+  assert(StackHint);
+
+  // Generate the extra diagnostic.
+  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
+                             N->getLocationContext());
+  return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
+}
+
+
+#define REGISTER_CHECKER(name) \
+void ento::register##name(CheckerManager &mgr) {\
+  registerCStringCheckerBasic(mgr); \
+  mgr.registerChecker<MallocChecker>()->Filter.C##name =3D true;\
+}
+
+REGISTER_CHECKER(MallocPessimistic)
+REGISTER_CHECKER(MallocOptimistic)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/MallocOverflowSecurityChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocOverf=
lowSecurityChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocOverf=
lowSecurityChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -205,7 +205,7 @@
=20
   // Delete any possible overflows which have a comparison.
   CheckOverflowOps c(PossibleMallocOverflows, BR.getContext());
-  c.Visit(mgr.getAnalysisContext(D)->getBody());
+  c.Visit(mgr.getAnalysisDeclContext(D)->getBody());
=20
   // Output warnings for all overflows that are left.
   for (CheckOverflowOps::theVecType::iterator
@@ -214,11 +214,10 @@
        i !=3D e;
        ++i) {
     SourceRange R =3D i->mulop->getSourceRange();
-    BR.EmitBasicReport("MallocOverflowSecurityChecker",
+    BR.EmitBasicReport(D, "malloc() size overflow", categories::UnixAPI,
       "the computation of the size of the memory allocation may overflow",
       PathDiagnosticLocation::createOperatorLoc(i->mulop,
-                                                BR.getSourceManager()),
-      &R, 1);
+                                                BR.getSourceManager()), &R=
, 1);
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NSAutorelea=
sePoolChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NSAutorelea=
sePoolChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
@@ -31,7 +32,7 @@
 namespace {
 class NSAutoreleasePoolChecker
   : public Checker<check::PreObjCMessage> {
-     =20
+  mutable OwningPtr<BugType> BT;
   mutable Selector releaseS;
=20
 public:
@@ -65,20 +66,24 @@
   // Sending 'release' message?
   if (msg.getSelector() !=3D releaseS)
     return;
-                    =20
-  SourceRange R =3D msg.getSourceRange();
-  BugReporter &BR =3D C.getBugReporter();
-  const LocationContext *LC =3D C.getPredecessor()->getLocationContext();
-  const SourceManager &SM =3D BR.getSourceManager();
-  const Expr *E =3D msg.getMsgOrPropExpr();
-  PathDiagnosticLocation L =3D PathDiagnosticLocation::createBegin(E, SM, =
LC);
-  C.getBugReporter().EmitBasicReport("Use -drain instead of -release",
-    "API Upgrade (Apple)",
-    "Use -drain instead of -release when using NSAutoreleasePool "
-    "and garbage collection", L, &R, 1);
+
+  if (!BT)
+    BT.reset(new BugType("Use -drain instead of -release",
+                         "API Upgrade (Apple)"));
+
+  ExplodedNode *N =3D C.addTransition();
+  if (!N) {
+    assert(0);
+    return;
+  }
+
+  BugReport *Report =3D new BugReport(*BT, "Use -drain instead of -release=
 when "
+    "using NSAutoreleasePool and garbage collection", N);
+  Report->addRange(msg.getSourceRange());
+  C.EmitReport(Report);
 }
=20
 void ento::registerNSAutoreleasePoolChecker(CheckerManager &mgr) {
-  if (mgr.getLangOptions().getGC() !=3D LangOptions::NonGC)
+  if (mgr.getLangOpts().getGC() !=3D LangOptions::NonGC)
     mgr.registerChecker<NSAutoreleasePoolChecker>();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/NSErrorChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NSErrorChec=
ker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NSErrorChec=
ker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -74,7 +74,7 @@
         "error occurred";
     PathDiagnosticLocation L =3D
       PathDiagnosticLocation::create(D, BR.getSourceManager());
-    BR.EmitBasicReport("Bad return type when passing NSError**",
+    BR.EmitBasicReport(D, "Bad return type when passing NSError**",
                        "Coding conventions (Apple)", err, L);
   }
 }
@@ -122,7 +122,7 @@
         "error occurred";
     PathDiagnosticLocation L =3D
       PathDiagnosticLocation::create(D, BR.getSourceManager());
-    BR.EmitBasicReport("Bad return type when passing CFErrorRef*",
+    BR.EmitBasicReport(D, "Bad return type when passing CFErrorRef*",
                        "Coding conventions (Apple)", err, L);
   }
 }
@@ -182,7 +182,7 @@
 }
=20
 template <typename T>
-static bool hasFlag(SVal val, const ProgramState *state) {
+static bool hasFlag(SVal val, ProgramStateRef state) {
   if (SymbolRef sym =3D val.getAsSymbol())
     if (const unsigned *attachedFlags =3D state->get<T>(sym))
       return *attachedFlags;
@@ -190,7 +190,7 @@
 }
=20
 template <typename T>
-static void setFlag(const ProgramState *state, SVal val, CheckerContext &C=
) {
+static void setFlag(ProgramStateRef state, SVal val, CheckerContext &C) {
   // We tag the symbol that the SVal wraps.
   if (SymbolRef sym =3D val.getAsSymbol())
     C.addTransition(state->set<T>(sym, true));
@@ -198,7 +198,7 @@
=20
 static QualType parameterTypeFromSVal(SVal val, CheckerContext &C) {
   const StackFrameContext *
-    SFC =3D C.getPredecessor()->getLocationContext()->getCurrentStackFrame=
();
+    SFC =3D C.getLocationContext()->getCurrentStackFrame();
   if (const loc::MemRegionVal* X =3D dyn_cast<loc::MemRegionVal>(&val)) {
     const MemRegion* R =3D X->getRegion();
     if (const VarRegion *VR =3D R->getAs<VarRegion>())
@@ -220,7 +220,7 @@
     return;
=20
   ASTContext &Ctx =3D C.getASTContext();
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   // If we are loading from NSError**/CFErrorRef* parameter, mark the resu=
lting
   // SVal so that we can later check it when handling the
@@ -253,7 +253,7 @@
     return;
=20
   SVal loc =3D event.Location;
-  const ProgramState *state =3D event.SinkNode->getState();
+  ProgramStateRef state =3D event.SinkNode->getState();
   BugReporter &BR =3D *event.BR;
=20
   bool isNSError =3D hasFlag<NSErrorOut>(loc, state);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/NoReturnFunctionChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFun=
ctionChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/NoReturnFun=
ctionChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -36,13 +36,13 @@
=20
 void NoReturnFunctionChecker::checkPostStmt(const CallExpr *CE,
                                             CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   const Expr *Callee =3D CE->getCallee();
=20
   bool BuildSinks =3D getFunctionExtInfo(Callee->getType()).getNoReturn();
=20
   if (!BuildSinks) {
-    SVal L =3D state->getSVal(Callee);
+    SVal L =3D state->getSVal(Callee, C.getLocationContext());
     const FunctionDecl *FD =3D L.getAsFunctionDecl();
     if (!FD)
       return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/OSAtomicChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/OSAtomicChe=
cker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/OSAtomicChe=
cker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -32,31 +32,32 @@
                                   ExprEngine &Eng,
                                   ExplodedNode *Pred,
                                   ExplodedNodeSet &Dst) const;
+};
+}
=20
-  ExplodedNode *generateNode(const ProgramState *State,
-                             ExplodedNode *Pred, const CallExpr *Statement,
-                             StmtNodeBuilder &B, ExplodedNodeSet &Dst) con=
st;
-};
+static StringRef getCalleeName(ProgramStateRef State,
+                               const CallExpr *CE,
+                               const LocationContext *LCtx) {
+  const Expr *Callee =3D CE->getCallee();
+  SVal L =3D State->getSVal(Callee, LCtx);
+  const FunctionDecl *funDecl =3D  L.getAsFunctionDecl();
+  if (!funDecl)
+    return StringRef();
+  IdentifierInfo *funI =3D funDecl->getIdentifier();
+  if (!funI)
+    return StringRef();
+  return funI->getName();
 }
=20
 bool OSAtomicChecker::inlineCall(const CallExpr *CE,
                                  ExprEngine &Eng,
                                  ExplodedNode *Pred,
                                  ExplodedNodeSet &Dst) const {
-  const ProgramState *state =3D Pred->getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
-
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
-  if (!FD)
+  StringRef FName =3D getCalleeName(Pred->getState(),
+                                  CE, Pred->getLocationContext());
+  if (FName.empty())
     return false;
=20
-  const IdentifierInfo *II =3D FD->getIdentifier();
-  if (!II)
-    return false;
- =20
-  StringRef FName(II->getName());
-
   // Check for compare and swap.
   if (FName.startswith("OSAtomicCompareAndSwap") ||
       FName.startswith("objc_atomicCompareAndSwap"))
@@ -66,17 +67,6 @@
   return false;
 }
=20
-ExplodedNode *OSAtomicChecker::generateNode(const ProgramState *State,
-                                            ExplodedNode *Pred,
-                                            const CallExpr *Statement,
-                                            StmtNodeBuilder &B,
-                                            ExplodedNodeSet &Dst) const {
-  ExplodedNode *N =3D B.generateNode(Statement, State, Pred, this);
-  if (N)
-    Dst.Add(N);
-  return N;
-}
-
 bool OSAtomicChecker::evalOSAtomicCompareAndSwap(const CallExpr *CE,
                                                  ExprEngine &Eng,
                                                  ExplodedNode *Pred,
@@ -85,7 +75,6 @@
   if (CE->getNumArgs() !=3D 3)
     return false;
=20
-  StmtNodeBuilder &Builder =3D Eng.getBuilder();
   ASTContext &Ctx =3D Eng.getContext();
   const Expr *oldValueExpr =3D CE->getArg(0);
   QualType oldValueType =3D Ctx.getCanonicalType(oldValueExpr->getType());
@@ -115,9 +104,10 @@
   static SimpleProgramPointTag OSAtomicStoreTag("OSAtomicChecker : Store");
  =20
   // Load 'theValue'.
-  const ProgramState *state =3D Pred->getState();
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
   ExplodedNodeSet Tmp;
-  SVal location =3D state->getSVal(theValueExpr);
+  SVal location =3D state->getSVal(theValueExpr, LCtx);
   // Here we should use the value type of the region as the load type, bec=
ause
   // we are simulating the semantics of the function, not the semantics of=20
   // passing argument. So the type of theValue expr is not we are loading.
@@ -130,15 +120,12 @@
       dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
     LoadTy =3D TR->getValueType();
   }
-  Eng.evalLoad(Tmp, theValueExpr, Pred,
-                  state, location, &OSAtomicLoadTag, LoadTy);
+  Eng.evalLoad(Tmp, CE, theValueExpr, Pred,
+               state, location, &OSAtomicLoadTag, LoadTy);
=20
   if (Tmp.empty()) {
-    // If no nodes were generated, other checkers must generated sinks. Bu=
t=20
-    // since the builder state was restored, we set it manually to prevent=20
-    // auto transition.
-    // FIXME: there should be a better approach.
-    Builder.BuildSinks =3D true;
+    // If no nodes were generated, other checkers must have generated sink=
s.=20
+    // We return an empty Dst.
     return true;
   }
 =20
@@ -146,14 +133,14 @@
        I !=3D E; ++I) {
=20
     ExplodedNode *N =3D *I;
-    const ProgramState *stateLoad =3D N->getState();
+    ProgramStateRef stateLoad =3D N->getState();
=20
     // Use direct bindings from the environment since we are forcing a load
     // from a location that the Environment would typically not be used
     // to bind a value.
-    SVal theValueVal_untested =3D stateLoad->getSVal(theValueExpr, true);
+    SVal theValueVal_untested =3D stateLoad->getSVal(theValueExpr, LCtx, t=
rue);
=20
-    SVal oldValueVal_untested =3D stateLoad->getSVal(oldValueExpr);
+    SVal oldValueVal_untested =3D stateLoad->getSVal(oldValueExpr, LCtx);
=20
     // FIXME: Issue an error.
     if (theValueVal_untested.isUndef() || oldValueVal_untested.isUndef()) {
@@ -171,13 +158,13 @@
     DefinedOrUnknownSVal Cmp =3D
       svalBuilder.evalEQ(stateLoad,theValueVal,oldValueVal);
=20
-    const ProgramState *stateEqual =3D stateLoad->assume(Cmp, true);
+    ProgramStateRef stateEqual =3D stateLoad->assume(Cmp, true);
=20
     // Were they equal?
     if (stateEqual) {
       // Perform the store.
       ExplodedNodeSet TmpStore;
-      SVal val =3D stateEqual->getSVal(newValueExpr);
+      SVal val =3D stateEqual->getSVal(newValueExpr, LCtx);
=20
       // Handle implicit value casts.
       if (const TypedValueRegion *R =3D
@@ -185,40 +172,41 @@
         val =3D svalBuilder.evalCast(val,R->getValueType(), newValueExpr->=
getType());
       }
=20
-      Eng.evalStore(TmpStore, NULL, theValueExpr, N,
-                       stateEqual, location, val, &OSAtomicStoreTag);
+      Eng.evalStore(TmpStore, CE, theValueExpr, N,
+                    stateEqual, location, val, &OSAtomicStoreTag);
=20
       if (TmpStore.empty()) {
-        // If no nodes were generated, other checkers must generated sinks=
. But=20
-        // since the builder state was restored, we set it manually to pre=
vent=20
-        // auto transition.
-        // FIXME: there should be a better approach.
-        Builder.BuildSinks =3D true;
+        // If no nodes were generated, other checkers must have generated =
sinks.=20
+        // We return an empty Dst.
         return true;
       }
-
+     =20
+      StmtNodeBuilder B(TmpStore, Dst, Eng.getBuilderContext());
       // Now bind the result of the comparison.
       for (ExplodedNodeSet::iterator I2 =3D TmpStore.begin(),
            E2 =3D TmpStore.end(); I2 !=3D E2; ++I2) {
         ExplodedNode *predNew =3D *I2;
-        const ProgramState *stateNew =3D predNew->getState();
+        ProgramStateRef stateNew =3D predNew->getState();
         // Check for 'void' return type if we have a bogus function protot=
ype.
         SVal Res =3D UnknownVal();
         QualType T =3D CE->getType();
         if (!T->isVoidType())
           Res =3D Eng.getSValBuilder().makeTruthVal(true, T);
-        generateNode(stateNew->BindExpr(CE, Res), predNew, CE, Builder, Ds=
t);
+        B.generateNode(CE, predNew, stateNew->BindExpr(CE, LCtx, Res),
+                       false, this);
       }
     }
=20
     // Were they not equal?
-    if (const ProgramState *stateNotEqual =3D stateLoad->assume(Cmp, false=
)) {
+    if (ProgramStateRef stateNotEqual =3D stateLoad->assume(Cmp, false)) {
       // Check for 'void' return type if we have a bogus function prototyp=
e.
       SVal Res =3D UnknownVal();
       QualType T =3D CE->getType();
       if (!T->isVoidType())
         Res =3D Eng.getSValBuilder().makeTruthVal(false, CE->getType());
-      generateNode(stateNotEqual->BindExpr(CE, Res), N, CE, Builder, Dst);
+      StmtNodeBuilder B(N, Dst, Eng.getBuilderContext());   =20
+      B.generateNode(CE, N, stateNotEqual->BindExpr(CE, LCtx, Res),
+                     false, this);
     }
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ObjCAtSyncChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCAtSyncC=
hecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCAtSyncC=
hecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -13,6 +13,7 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "ClangSACheckers.h"
+#include "clang/AST/StmtObjC.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
@@ -26,8 +27,8 @@
 namespace {
 class ObjCAtSyncChecker
     : public Checker< check::PreStmt<ObjCAtSynchronizedStmt> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT_null;
-  mutable llvm::OwningPtr<BuiltinBug> BT_undef;
+  mutable OwningPtr<BuiltinBug> BT_null;
+  mutable OwningPtr<BuiltinBug> BT_undef;
=20
 public:
   void checkPreStmt(const ObjCAtSynchronizedStmt *S, CheckerContext &C) co=
nst;
@@ -38,8 +39,8 @@
                                      CheckerContext &C) const {
=20
   const Expr *Ex =3D S->getSynchExpr();
-  const ProgramState *state =3D C.getState();
-  SVal V =3D state->getSVal(Ex);
+  ProgramStateRef state =3D C.getState();
+  SVal V =3D state->getSVal(Ex, C.getLocationContext());
=20
   // Uninitialized value used for the mutex?
   if (isa<UndefinedVal>(V)) {
@@ -49,7 +50,8 @@
                                   "for @synchronized"));
       BugReport *report =3D
         new BugReport(*BT_undef, BT_undef->getDescription(), N);
-      report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, E=
x));
+      report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, E=
x,
+                                                                      repo=
rt));
       C.EmitReport(report);
     }
     return;
@@ -59,20 +61,21 @@
     return;
=20
   // Check for null mutexes.
-  const ProgramState *notNullState, *nullState;
+  ProgramStateRef notNullState, nullState;
   llvm::tie(notNullState, nullState) =3D state->assume(cast<DefinedSVal>(V=
));
=20
   if (nullState) {
     if (!notNullState) {
       // Generate an error node.  This isn't a sink since
       // a null mutex just means no synchronization occurs.
-      if (ExplodedNode *N =3D C.generateNode(nullState)) {
+      if (ExplodedNode *N =3D C.addTransition(nullState)) {
         if (!BT_null)
           BT_null.reset(new BuiltinBug("Nil value used as mutex for @synch=
ronized() "
                                    "(no synchronization will occur)"));
         BugReport *report =3D
           new BugReport(*BT_null, BT_null->getDescription(), N);
-        report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,=
 Ex));
+        report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,=
 Ex,
+                                                                        re=
port));
=20
         C.EmitReport(report);
         return;
@@ -88,6 +91,6 @@
 }
=20
 void ento::registerObjCAtSyncChecker(CheckerManager &mgr) {
-  if (mgr.getLangOptions().ObjC2)
+  if (mgr.getLangOpts().ObjC2)
     mgr.registerChecker<ObjCAtSyncChecker>();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ObjCSelfInitChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCSelfIni=
tChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCSelfIni=
tChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -34,18 +34,8 @@
 // receives a reference to 'self', the checker keeps track and passes the =
flags
 // for 1) and 2) to the new object that 'self' points to after the call.
 //
-// FIXME (rdar://7937506): In the case of:
-//   [super init];
-//   return self;
-// Have an extra PathDiagnosticPiece in the path that says "called [super =
init],
-// but didn't assign the result to self."
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-// FIXME: Somehow stick the link to Apple's documentation about initializi=
ng
-// objects in the diagnostics.
-// http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/=
ObjectiveC/Articles/ocAllocInit.html
-
 #include "ClangSACheckers.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
@@ -64,7 +54,7 @@
 static bool isSelfVar(SVal location, CheckerContext &C);
=20
 namespace {
-class ObjCSelfInitChecker : public Checker<
+class ObjCSelfInitChecker : public Checker<  check::PreObjCMessage,
                                              check::PostObjCMessage,
                                              check::PostStmt<ObjCIvarRefEx=
pr>,
                                              check::PreStmt<ReturnStmt>,
@@ -72,6 +62,7 @@
                                              check::PostStmt<CallExpr>,
                                              check::Location > {
 public:
+  void checkPreObjCMessage(ObjCMessage msg, CheckerContext &C) const;
   void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const;
   void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
@@ -79,6 +70,10 @@
   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
   void checkLocation(SVal location, bool isLoad, const Stmt *S,
                      CheckerContext &C) const;
+
+  void checkPreStmt(const CallOrObjCMessage &CE, CheckerContext &C) const;
+  void checkPostStmt(const CallOrObjCMessage &CE, CheckerContext &C) const;
+
 };
 } // end anonymous namespace
=20
@@ -87,8 +82,8 @@
 class InitSelfBug : public BugType {
   const std::string desc;
 public:
-  InitSelfBug() : BugType("missing \"self =3D [(super or self) init...]\"",
-                          "missing \"self =3D [(super or self) init...]\""=
) {}
+  InitSelfBug() : BugType("Missing \"self =3D [(super or self) init...]\"",
+                          categories::CoreFoundationObjectiveC) {}
 };
=20
 } // end anonymous namespace
@@ -130,7 +125,7 @@
 }
 }
=20
-static SelfFlagEnum getSelfFlags(SVal val, const ProgramState *state) {
+static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
   if (SymbolRef sym =3D val.getAsSymbol())
     if (const unsigned *attachedFlags =3D state->get<SelfFlag>(sym))
       return (SelfFlagEnum)*attachedFlags;
@@ -141,7 +136,7 @@
   return getSelfFlags(val, C.getState());
 }
=20
-static void addSelfFlag(const ProgramState *state, SVal val,
+static void addSelfFlag(ProgramStateRef state, SVal val,
                         SelfFlagEnum flag, CheckerContext &C) {
   // We tag the symbol that the SVal wraps.
   if (SymbolRef sym =3D val.getAsSymbol())
@@ -156,7 +151,7 @@
 /// points to and is an object that did not come from the result of calling
 /// an initializer.
 static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
-  SVal exprVal =3D C.getState()->getSVal(E);
+  SVal exprVal =3D C.getState()->getSVal(E, C.getLocationContext());
   if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
     return false; // value did not come from 'self'.
   if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
@@ -188,25 +183,28 @@
=20
 void ObjCSelfInitChecker::checkPostObjCMessage(ObjCMessage msg,
                                                CheckerContext &C) const {
+  CallOrObjCMessage MsgWrapper(msg, C.getState(), C.getLocationContext());
+  checkPostStmt(MsgWrapper, C);
+
   // When encountering a message that does initialization (init rule),
   // tag the return value so that we know later on that if self has this v=
alue
   // then it is properly initialized.
=20
   // FIXME: A callback should disable checkers at the start of functions.
   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
-                                     C.getCurrentAnalysisContext()->getDec=
l())))
+                                C.getCurrentAnalysisDeclContext()->getDecl=
())))
     return;
=20
   if (isInitMessage(msg)) {
     // Tag the return value as the result of an initializer.
-    const ProgramState *state =3D C.getState();
+    ProgramStateRef state =3D C.getState();
    =20
     // FIXME this really should be context sensitive, where we record
     // the current stack frame (for IPA).  Also, we need to clean this
     // value out when we return from this method.
     state =3D state->set<CalledInit>(true);
    =20
-    SVal V =3D state->getSVal(msg.getOriginExpr());
+    SVal V =3D state->getSVal(msg.getMessageExpr(), C.getLocationContext()=
);
     addSelfFlag(state, V, SelfFlag_InitRes, C);
     return;
   }
@@ -221,7 +219,7 @@
                                         CheckerContext &C) const {
   // FIXME: A callback should disable checkers at the start of functions.
   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
-                                     C.getCurrentAnalysisContext()->getDec=
l())))
+                                 C.getCurrentAnalysisDeclContext()->getDec=
l())))
     return;
=20
   checkForInvalidSelf(E->getBase(), C,
@@ -233,7 +231,7 @@
                                        CheckerContext &C) const {
   // FIXME: A callback should disable checkers at the start of functions.
   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
-                                     C.getCurrentAnalysisContext()->getDec=
l())))
+                                 C.getCurrentAnalysisDeclContext()->getDec=
l())))
     return;
=20
   checkForInvalidSelf(S->getRetValue(), C,
@@ -259,10 +257,28 @@
=20
 void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
                                        CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  for (CallExpr::const_arg_iterator
-         I =3D CE->arg_begin(), E =3D CE->arg_end(); I !=3D E; ++I) {
-    SVal argV =3D state->getSVal(*I);
+  CallOrObjCMessage CEWrapper(CE, C.getState(), C.getLocationContext());
+  checkPreStmt(CEWrapper, C);
+}
+
+void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
+                                        CheckerContext &C) const {
+  CallOrObjCMessage CEWrapper(CE, C.getState(), C.getLocationContext());
+  checkPostStmt(CEWrapper, C);
+}
+
+void ObjCSelfInitChecker::checkPreObjCMessage(ObjCMessage Msg,
+                                              CheckerContext &C) const {
+  CallOrObjCMessage MsgWrapper(Msg, C.getState(), C.getLocationContext());
+  checkPreStmt(MsgWrapper, C);
+}
+
+void ObjCSelfInitChecker::checkPreStmt(const CallOrObjCMessage &CE,
+                                       CheckerContext &C) const {
+  ProgramStateRef state =3D C.getState();
+  unsigned NumArgs =3D CE.getNumArgs();
+  for (unsigned i =3D 0; i < NumArgs; ++i) {
+    SVal argV =3D CE.getArgSVal(i);
     if (isSelfVar(argV, C)) {
       unsigned selfFlags =3D getSelfFlags(state->getSVal(cast<Loc>(argV)),=
 C);
       C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
@@ -275,12 +291,12 @@
   }
 }
=20
-void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
+void ObjCSelfInitChecker::checkPostStmt(const CallOrObjCMessage &CE,
                                         CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  for (CallExpr::const_arg_iterator
-         I =3D CE->arg_begin(), E =3D CE->arg_end(); I !=3D E; ++I) {
-    SVal argV =3D state->getSVal(*I);
+  ProgramStateRef state =3D C.getState();
+  unsigned NumArgs =3D CE.getNumArgs();
+  for (unsigned i =3D 0; i < NumArgs; ++i) {
+    SVal argV =3D CE.getArgSVal(i);
     if (isSelfVar(argV, C)) {
       SelfFlagEnum prevFlags =3D (SelfFlagEnum)state->get<PreCallSelfFlags=
>();
       state =3D state->remove<PreCallSelfFlags>();
@@ -289,7 +305,7 @@
     } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
       SelfFlagEnum prevFlags =3D (SelfFlagEnum)state->get<PreCallSelfFlags=
>();
       state =3D state->remove<PreCallSelfFlags>();
-      addSelfFlag(state, state->getSVal(CE), prevFlags, C);
+      addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
       return;
     }
   }
@@ -300,7 +316,7 @@
                                         CheckerContext &C) const {
   // Tag the result of a load from 'self' so that we can easily know that =
the
   // value is the object that 'self' points to.
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   if (isSelfVar(location, C))
     addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self,=
 C);
 }
@@ -335,7 +351,7 @@
=20
 /// \brief Returns true if the location is 'self'.
 static bool isSelfVar(SVal location, CheckerContext &C) {
-  AnalysisContext *analCtx =3D C.getCurrentAnalysisContext();=20
+  AnalysisDeclContext *analCtx =3D C.getCurrentAnalysisDeclContext();=20
   if (!analCtx->getSelfDecl())
     return false;
   if (!isa<loc::MemRegionVal>(location))
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ObjCUnusedIVarsChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedI=
VarsChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ObjCUnusedI=
VarsChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -161,7 +161,7 @@
=20
       PathDiagnosticLocation L =3D
         PathDiagnosticLocation::create(I->first, BR.getSourceManager());
-      BR.EmitBasicReport("Unused instance variable", "Optimization",
+      BR.EmitBasicReport(D, "Unused instance variable", "Optimization",
                          os.str(), L);
     }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/PointerArithChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PointerArit=
hChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PointerArit=
hChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 namespace {
 class PointerArithChecker=20
   : public Checker< check::PreStmt<BinaryOperator> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
=20
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
@@ -36,9 +36,10 @@
   if (B->getOpcode() !=3D BO_Sub && B->getOpcode() !=3D BO_Add)
     return;
=20
-  const ProgramState *state =3D C.getState();
-  SVal LV =3D state->getSVal(B->getLHS());
-  SVal RV =3D state->getSVal(B->getRHS());
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal LV =3D state->getSVal(B->getLHS(), LCtx);
+  SVal RV =3D state->getSVal(B->getRHS(), LCtx);
=20
   const MemRegion *LR =3D LV.getAsRegion();
=20
@@ -50,7 +51,7 @@
   if (isa<VarRegion>(LR) || isa<CodeTextRegion>(LR) ||=20
       isa<CompoundLiteralRegion>(LR)) {
=20
-    if (ExplodedNode *N =3D C.generateNode()) {
+    if (ExplodedNode *N =3D C.addTransition()) {
       if (!BT)
         BT.reset(new BuiltinBug("Dangerous pointer arithmetic",
                             "Pointer arithmetic done on non-array variable=
s "
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/PointerSubChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PointerSubC=
hecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PointerSubC=
hecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 namespace {
 class PointerSubChecker=20
   : public Checker< check::PreStmt<BinaryOperator> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
=20
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
@@ -39,9 +39,10 @@
   if (B->getOpcode() !=3D BO_Sub)
     return;
=20
-  const ProgramState *state =3D C.getState();
-  SVal LV =3D state->getSVal(B->getLHS());
-  SVal RV =3D state->getSVal(B->getRHS());
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal LV =3D state->getSVal(B->getLHS(), LCtx);
+  SVal RV =3D state->getSVal(B->getRHS(), LCtx);
=20
   const MemRegion *LR =3D LV.getAsRegion();
   const MemRegion *RR =3D RV.getAsRegion();
@@ -59,7 +60,7 @@
   if (isa<SymbolicRegion>(BaseLR) || isa<SymbolicRegion>(BaseRR))
     return;
=20
-  if (ExplodedNode *N =3D C.generateNode()) {
+  if (ExplodedNode *N =3D C.addTransition()) {
     if (!BT)
       BT.reset(new BuiltinBug("Pointer subtraction",=20
                           "Subtraction of two pointers that do not point t=
o "
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/PthreadLockChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PthreadLock=
Checker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/PthreadLock=
Checker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,8 +25,8 @@
=20
 namespace {
 class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > {
-  mutable llvm::OwningPtr<BugType> BT_doublelock;
-  mutable llvm::OwningPtr<BugType> BT_lor;
+  mutable OwningPtr<BugType> BT_doublelock;
+  mutable OwningPtr<BugType> BT_lor;
   enum LockingSemantics {
     NotApplicable =3D 0,
     PthreadSemantics,
@@ -56,43 +56,40 @@
=20
 void PthreadLockChecker::checkPostStmt(const CallExpr *CE,
                                        CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  const FunctionDecl *FD =3D state->getSVal(Callee).getAsFunctionDecl();
-
-  if (!FD)
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
+  StringRef FName =3D C.getCalleeName(CE);
+  if (FName.empty())
     return;
=20
-  // Get the name of the callee.
-  IdentifierInfo *II =3D FD->getIdentifier();
-  if (!II)   // if no identifier, not a simple C function
-    return;
-  StringRef FName =3D II->getName();
-
   if (CE->getNumArgs() !=3D 1)
     return;
=20
   if (FName =3D=3D "pthread_mutex_lock" ||
       FName =3D=3D "pthread_rwlock_rdlock" ||
       FName =3D=3D "pthread_rwlock_wrlock")
-    AcquireLock(C, CE, state->getSVal(CE->getArg(0)), false, PthreadSemant=
ics);
+    AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
+                false, PthreadSemantics);
   else if (FName =3D=3D "lck_mtx_lock" ||
            FName =3D=3D "lck_rw_lock_exclusive" ||
            FName =3D=3D "lck_rw_lock_shared")=20
-    AcquireLock(C, CE, state->getSVal(CE->getArg(0)), false, XNUSemantics);
+    AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
+                false, XNUSemantics);
   else if (FName =3D=3D "pthread_mutex_trylock" ||
            FName =3D=3D "pthread_rwlock_tryrdlock" ||
            FName =3D=3D "pthread_rwlock_tryrwlock")
-    AcquireLock(C, CE, state->getSVal(CE->getArg(0)), true, PthreadSemanti=
cs);
+    AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
+                true, PthreadSemantics);
   else if (FName =3D=3D "lck_mtx_try_lock" ||
            FName =3D=3D "lck_rw_try_lock_exclusive" ||
            FName =3D=3D "lck_rw_try_lock_shared")
-    AcquireLock(C, CE, state->getSVal(CE->getArg(0)), true, XNUSemantics);
+    AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx),
+                true, XNUSemantics);
   else if (FName =3D=3D "pthread_mutex_unlock" ||
            FName =3D=3D "pthread_rwlock_unlock" ||
            FName =3D=3D "lck_mtx_unlock" ||
            FName =3D=3D "lck_rw_done")
-    ReleaseLock(C, CE, state->getSVal(CE->getArg(0)));
+    ReleaseLock(C, CE, state->getSVal(CE->getArg(0), LCtx));
 }
=20
 void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE,
@@ -103,9 +100,9 @@
   if (!lockR)
     return;
  =20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
  =20
-  SVal X =3D state->getSVal(CE);
+  SVal X =3D state->getSVal(CE, C.getLocationContext());
   if (X.isUnknownOrUndef())
     return;
  =20
@@ -125,10 +122,10 @@
     return;
   }
=20
-  const ProgramState *lockSucc =3D state;
+  ProgramStateRef lockSucc =3D state;
   if (isTryLock) {
     // Bifurcate the state, and allow a mode where the lock acquisition fa=
ils.
-    const ProgramState *lockFail;
+    ProgramStateRef lockFail;
     switch (semantics) {
     case PthreadSemantics:
       llvm::tie(lockFail, lockSucc) =3D state->assume(retVal);   =20
@@ -138,7 +135,6 @@
       break;
     default:
       llvm_unreachable("Unknown tryLock locking semantics");
-      break;
     }
     assert(lockFail && lockSucc);
     C.addTransition(lockFail);
@@ -166,7 +162,7 @@
   if (!lockR)
     return;
  =20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   llvm::ImmutableList<const MemRegion*> LS =3D state->get<LockSet>();
=20
   // FIXME: Better analysis requires IPA for wrappers.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/RetainCountChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCount=
Checker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/RetainCount=
Checker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -18,12 +18,12 @@
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
+#include "clang/AST/ParentMap.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
@@ -31,6 +31,7 @@
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/ImmutableList.h"
 #include "llvm/ADT/ImmutableMap.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include <cstdarg>
@@ -45,21 +46,14 @@
 class GenericNodeBuilderRefCount {
   CheckerContext *C;
   const ProgramPointTag *tag;
-  EndOfFunctionNodeBuilder *ENB;
 public:
   GenericNodeBuilderRefCount(CheckerContext &c,
-                             const ProgramPointTag *t)
-  : C(&c), tag(t), ENB(0) {}
-
-  GenericNodeBuilderRefCount(EndOfFunctionNodeBuilder &enb)
-  : C(0), tag(0), ENB(&enb) {}
-
-  ExplodedNode *MakeNode(const ProgramState *state, ExplodedNode *Pred) {
-    if (C)
-      return C->generateNode(state, Pred, tag, false);
-
-    assert(ENB);
-    return ENB->generateNode(state, Pred);
+                             const ProgramPointTag *t =3D 0)
+  : C(&c), tag(t){}
+
+  ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
+                         bool MarkAsSink =3D false) {
+    return C->addTransition(state, Pred, tag, MarkAsSink);
   }
 };
 } // end anonymous namespace
@@ -138,6 +132,11 @@
   static RetEffect MakeNoRet() {
     return RetEffect(NoRet);
   }
+
+  void Profile(llvm::FoldingSetNodeID& ID) const {
+    ID.AddInteger((unsigned) K);
+    ID.AddInteger((unsigned) O);
+  }
 };
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -358,22 +357,22 @@
=20
 namespace {
 class RetainSummary {
-  /// Args - an ordered vector of (index, ArgEffect) pairs, where index
+  /// Args - a map of (index, ArgEffect) pairs, where index
   ///  specifies the argument (starting from 0).  This can be sparsely
   ///  populated; arguments with no entry in Args use 'DefaultArgEffect'.
   ArgEffects Args;
=20
   /// DefaultArgEffect - The default ArgEffect to apply to arguments that
   ///  do not have an entry in Args.
-  ArgEffect   DefaultArgEffect;
+  ArgEffect DefaultArgEffect;
=20
   /// Receiver - If this summary applies to an Objective-C message express=
ion,
   ///  this is the effect applied to the state of the receiver.
-  ArgEffect   Receiver;
+  ArgEffect Receiver;
=20
   /// Ret - The effect on the return value.  Used to indicate if the
   ///  function/method call returns a new tracked symbol.
-  RetEffect   Ret;
+  RetEffect Ret;
=20
 public:
   RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
@@ -419,6 +418,19 @@
     return Args =3D=3D Other.Args && DefaultArgEffect =3D=3D Other.Default=
ArgEffect &&
            Receiver =3D=3D Other.Receiver && Ret =3D=3D Other.Ret;
   }
+
+  /// Profile this summary for inclusion in a FoldingSet.
+  void Profile(llvm::FoldingSetNodeID& ID) const {
+    ID.Add(Args);
+    ID.Add(DefaultArgEffect);
+    ID.Add(Receiver);
+    ID.Add(Ret);
+  }
+
+  /// A retain summary is simple if it has no ArgEffects other than the de=
fault.
+  bool isSimple() const {
+    return Args.isEmpty();
+  }
 };
 } // end anonymous namespace
=20
@@ -443,7 +455,7 @@
   ObjCSummaryKey(Selector s)
     : II(0), S(s) {}
=20
-  IdentifierInfo* getIdentifier() const { return II; }
+  IdentifierInfo *getIdentifier() const { return II; }
   Selector getSelector() const { return S; }
 };
 }
@@ -523,7 +535,7 @@
     return Summ;
   }
=20
-  const RetainSummary * find(IdentifierInfo* II, Selector S) {
+  const RetainSummary *find(IdentifierInfo* II, Selector S) {
     // FIXME: Class method lookup.  Right now we dont' have a good way
     // of going between IdentifierInfo* and the class hierarchy.
     MapTy::iterator I =3D M.find(ObjCSummaryKey(II, S));
@@ -560,6 +572,8 @@
=20
   typedef ObjCSummaryCache ObjCMethodSummariesTy;
=20
+  typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
+
   //=3D=3D----------------------------------------------------------------=
-=3D=3D//
   //  Data.
   //=3D=3D----------------------------------------------------------------=
-=3D=3D//
@@ -591,7 +605,7 @@
   ArgEffects::Factory AF;
=20
   /// ScratchArgs - A holding buffer for construct ArgEffects.
-  ArgEffects ScratchArgs;
+  ArgEffects ScratchArgs;=20
=20
   /// ObjCAllocRetE - Default return effect for methods returning Objectiv=
e-C
   ///  objects.
@@ -601,8 +615,9 @@
   ///   Objective-C objects.
   RetEffect ObjCInitRetE;
=20
-  RetainSummary DefaultSummary;
-  const RetainSummary *StopSummary;
+  /// SimpleSummaries - Used for uniquing summaries that don't have special
+  /// effects.
+  llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
=20
   //=3D=3D----------------------------------------------------------------=
-=3D=3D//
   //  Methods.
@@ -616,40 +631,33 @@
=20
 public:
   RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
-
-  const RetainSummary *getDefaultSummary() {
-    return &DefaultSummary;
-  }
  =20
-  const RetainSummary * getUnarySummary(const FunctionType* FT,
+  const RetainSummary *getUnarySummary(const FunctionType* FT,
                                        UnaryFuncKind func);
=20
-  const RetainSummary * getCFSummaryCreateRule(const FunctionDecl *FD);
-  const RetainSummary * getCFSummaryGetRule(const FunctionDecl *FD);
-  const RetainSummary * getCFCreateGetRuleSummary(const FunctionDecl *FD);
-
-  const RetainSummary * getPersistentSummary(ArgEffects AE, RetEffect RetE=
ff,
-                                            ArgEffect ReceiverEff =3D DoNo=
thing,
-                                            ArgEffect DefaultEff =3D MayEs=
cape);
-
-  const RetainSummary * getPersistentSummary(RetEffect RE,
+  const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
+  const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
+  const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
+
+  const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
+
+  const RetainSummary *getPersistentSummary(RetEffect RetEff,
                                             ArgEffect ReceiverEff =3D DoNo=
thing,
                                             ArgEffect DefaultEff =3D MayEs=
cape) {
-    return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultE=
ff);
+    RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
+    return getPersistentSummary(Summ);
   }
=20
+  const RetainSummary *getDefaultSummary() {
+    return getPersistentSummary(RetEffect::MakeNoRet(),
+                                DoNothing, MayEscape);
+  }
+
   const RetainSummary *getPersistentStopSummary() {
-    if (StopSummary)
-      return StopSummary;
-
-    StopSummary =3D getPersistentSummary(RetEffect::MakeNoRet(),
-                                       StopTracking, StopTracking);
-
-    return StopSummary;
+    return getPersistentSummary(RetEffect::MakeNoRet(),
+                                StopTracking, StopTracking);
   }
=20
-  const RetainSummary *getInitMethodSummary(QualType RetTy);
-
   void InitializeClassMethodSummaries();
   void InitializeMethodSummaries();
 private:
@@ -661,10 +669,11 @@
     ObjCMethodSummaries[S] =3D Summ;
   }
=20
-  void addClassMethSummary(const char* Cls, const char* nullaryName,
-                           const RetainSummary *Summ) {
+  void addClassMethSummary(const char* Cls, const char* name,
+                           const RetainSummary *Summ, bool isNullary =3D t=
rue) {
     IdentifierInfo* ClsII =3D &Ctx.Idents.get(Cls);
-    Selector S =3D GetNullarySelector(nullaryName, Ctx);
+    Selector S =3D isNullary ? GetNullarySelector(name, Ctx)=20
+                           : GetUnarySelector(name, Ctx);
     ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)]  =3D Summ;
   }
=20
@@ -725,50 +734,37 @@
      ObjCInitRetE(gcenabled=20
                     ? RetEffect::MakeGCNotOwned()
                     : (usesARC ? RetEffect::MakeARCNotOwned()
-                               : RetEffect::MakeOwnedWhenTrackedReceiver()=
)),
-     DefaultSummary(AF.getEmptyMap() /* per-argument effects (none) */,
-                    RetEffect::MakeNoRet() /* return effect */,
-                    MayEscape, /* default argument effect */
-                    DoNothing /* receiver effect */),
-     StopSummary(0) {
-
+                               : RetEffect::MakeOwnedWhenTrackedReceiver()=
)) {
     InitializeClassMethodSummaries();
     InitializeMethodSummaries();
   }
=20
-  const RetainSummary * getSummary(const FunctionDecl *FD);
+  const RetainSummary *getSummary(const FunctionDecl *FD);
+
+  const RetainSummary *getMethodSummary(Selector S, IdentifierInfo *ClsNam=
e,
+                                        const ObjCInterfaceDecl *ID,
+                                        const ObjCMethodDecl *MD,
+                                        QualType RetTy,
+                                        ObjCMethodSummariesTy &CachedSumma=
ries);
=20
   const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
-                                                const ProgramState *state,
+                                                ProgramStateRef state,
                                                 const LocationContext *LC);
=20
-  const RetainSummary * getInstanceMethodSummary(const ObjCMessage &msg,
+  const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
                                                 const ObjCInterfaceDecl *I=
D) {
-    return getInstanceMethodSummary(msg.getSelector(), 0,
-                            ID, msg.getMethodDecl(), msg.getType(Ctx));
+    return getMethodSummary(msg.getSelector(), 0, ID, msg.getMethodDecl(),
+                            msg.getType(Ctx), ObjCMethodSummaries);
   }
=20
-  const RetainSummary * getInstanceMethodSummary(Selector S,
-                                                IdentifierInfo *ClsName,
-                                                const ObjCInterfaceDecl *I=
D,
-                                                const ObjCMethodDecl *MD,
-                                                QualType RetTy);
-
-  const RetainSummary *getClassMethodSummary(Selector S,
-                                             IdentifierInfo *ClsName,
-                                             const ObjCInterfaceDecl *ID,
-                                             const ObjCMethodDecl *MD,
-                                             QualType RetTy);
-
   const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
     const ObjCInterfaceDecl *Class =3D 0;
     if (!msg.isInstanceMessage())
       Class =3D msg.getReceiverInterface();
=20
-    return getClassMethodSummary(msg.getSelector(),
-                                 Class? Class->getIdentifier() : 0,
-                                 Class,
-                                 msg.getMethodDecl(), msg.getType(Ctx));
+    return getMethodSummary(msg.getSelector(), Class->getIdentifier(),
+                            Class, msg.getMethodDecl(), msg.getType(Ctx),
+                            ObjCClassMethodSummaries);
   }
=20
   /// getMethodSummary - This version of getMethodSummary is used to query
@@ -780,13 +776,16 @@
     IdentifierInfo *ClsName =3D ID->getIdentifier();
     QualType ResultTy =3D MD->getResultType();
=20
+    ObjCMethodSummariesTy *CachedSummaries;
     if (MD->isInstanceMethod())
-      return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
+      CachedSummaries =3D &ObjCMethodSummaries;
     else
-      return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
+      CachedSummaries =3D &ObjCClassMethodSummaries;
+
+    return getMethodSummary(S, ClsName, ID, MD, ResultTy, *CachedSummaries=
);
   }
=20
-  const RetainSummary * getCommonMethodSummary(const ObjCMethodDecl *MD,
+  const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
                                               Selector S, QualType RetTy);
=20
   void updateSummaryFromAnnotations(const RetainSummary *&Summ,
@@ -800,12 +799,6 @@
   bool isARCEnabled() const { return ARCEnabled; }
  =20
   bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
-
-  const RetainSummary *copySummary(const RetainSummary *OldSumm) {
-    RetainSummary *Summ =3D (RetainSummary *) BPAlloc.Allocate<RetainSumma=
ry>();
-    new (Summ) RetainSummary(*OldSumm);
-    return Summ;
-  }
 };
=20
 // Used to avoid allocating long-term (BPAlloc'd) memory for default retain
@@ -815,23 +808,17 @@
 class RetainSummaryTemplate {
   RetainSummaryManager &Manager;
   const RetainSummary *&RealSummary;
-  const RetainSummary *BaseSummary;
   RetainSummary ScratchSummary;
   bool Accessed;
 public:
-  RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &b=
ase,
-                        RetainSummaryManager &manager)
-  : Manager(manager),
-    RealSummary(real),
-    BaseSummary(&base),
-    ScratchSummary(base),
+  RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &b=
ase,=20
+                        RetainSummaryManager &mgr)
+  : Manager(mgr), RealSummary(real), ScratchSummary(real ? *real : base),
     Accessed(false) {}
=20
   ~RetainSummaryTemplate() {
     if (Accessed)
-      RealSummary =3D Manager.copySummary(&ScratchSummary);
-    else if (!RealSummary)
-      RealSummary =3D BaseSummary;
+      RealSummary =3D Manager.getPersistentSummary(ScratchSummary);
   }
=20
   RetainSummary &operator*() {
@@ -858,12 +845,26 @@
 }
=20
 const RetainSummary *
-RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
-                                           ArgEffect ReceiverEff,
-                                           ArgEffect DefaultEff) {
-  // Create the summary and return it.
+RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
+  // Unique "simple" summaries -- those without ArgEffects.
+  if (OldSumm.isSimple()) {
+    llvm::FoldingSetNodeID ID;
+    OldSumm.Profile(ID);
+
+    void *Pos;
+    CachedSummaryNode *N =3D SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
+
+    if (!N) {
+      N =3D (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
+      new (N) CachedSummaryNode(OldSumm);
+      SimpleSummaries.InsertNode(N, Pos);
+    }
+
+    return &N->getValue();
+  }
+
   RetainSummary *Summ =3D (RetainSummary *) BPAlloc.Allocate<RetainSummary=
>();
-  new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff);
+  new (Summ) RetainSummary(OldSumm);
   return Summ;
 }
=20
@@ -984,6 +985,21 @@
       // correctly.
       ScratchArgs =3D AF.add(ScratchArgs, 12, StopTracking);
       S =3D getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNoth=
ing);
+    } else if (FName =3D=3D "dispatch_set_context") {
+      // <rdar://problem/11059275> - The analyzer currently doesn't have
+      // a good way to reason about the finalizer function for libdispatch.
+      // If we pass a context object that is memory managed, stop tracking=
 it.
+      // FIXME: this hack should possibly go away once we can handle
+      // libdispatch finalizers.
+      ScratchArgs =3D AF.add(ScratchArgs, 1, StopTracking);
+      S =3D getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNoth=
ing);
+    } else if (FName.startswith("NS") &&
+                (FName.find("Insert") !=3D StringRef::npos)) {
+      // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since th=
ey can
+      // be deallocated by NSMapRemove. (radar://11152419)
+      ScratchArgs =3D AF.add(ScratchArgs, 1, StopTracking);
+      ScratchArgs =3D AF.add(ScratchArgs, 2, StopTracking);
+      S =3D getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNoth=
ing);
     }
=20
     // Did we get a summary?
@@ -1106,7 +1122,6 @@
     case cfretain: Effect =3D IncRef; break;
     case cfrelease: Effect =3D DecRef; break;
     case cfmakecollectable: Effect =3D MakeCollectable; break;
-    default: llvm_unreachable("Not a supported unary function.");
   }
=20
   ScratchArgs =3D AF.add(ScratchArgs, 0, Effect);
@@ -1131,25 +1146,13 @@
 // Summary creation for Selectors.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-const RetainSummary *
-RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
-  assert(ScratchArgs.isEmpty());
-  // 'init' methods conceptually return a newly allocated object and claim
-  // the receiver.
-  if (cocoa::isCocoaObjectRef(RetTy) ||
-      coreFoundation::isCFObjectRef(RetTy))
-    return getPersistentSummary(ObjCInitRetE, DecRefMsg);
-
-  return getDefaultSummary();
-}
-
 void
 RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&S=
umm,
                                                    const FunctionDecl *FD)=
 {
   if (!FD)
     return;
=20
-  RetainSummaryTemplate Template(Summ, DefaultSummary, *this);
+  RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
=20
   // Effects on the parameters.
   unsigned parm_idx =3D 0;
@@ -1197,8 +1200,7 @@
   if (!MD)
     return;
=20
-  RetainSummaryTemplate Template(Summ, DefaultSummary, *this);
-
+  RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
   bool isTrackedLoc =3D false;
=20
   // Effects on the receiver.
@@ -1247,8 +1249,8 @@
 }
=20
 const RetainSummary *
-RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl *MD,
-                                             Selector S, QualType RetTy) {
+RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
+                                               Selector S, QualType RetTy)=
 {
=20
   if (MD) {
     // Scan the method decl for 'void*' arguments.  These should be treated
@@ -1265,8 +1267,74 @@
       }
   }
=20
-  // Any special effect for the receiver?
+  // Any special effects?
   ArgEffect ReceiverEff =3D DoNothing;
+  RetEffect ResultEff =3D RetEffect::MakeNoRet();
+
+  // Check the method family, and apply any default annotations.
+  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
+    case OMF_None:
+    case OMF_performSelector:
+      // Assume all Objective-C methods follow Cocoa Memory Management rul=
es.
+      // FIXME: Does the non-threaded performSelector family really belong=
 here?
+      // The selector could be, say, @selector(copy).
+      if (cocoa::isCocoaObjectRef(RetTy))
+        ResultEff =3D RetEffect::MakeNotOwned(RetEffect::ObjC);
+      else if (coreFoundation::isCFObjectRef(RetTy)) {
+        // ObjCMethodDecl currently doesn't consider CF objects as valid r=
eturn=20
+        // values for alloc, new, copy, or mutableCopy, so we have to
+        // double-check with the selector. This is ugly, but there aren't =
that
+        // many Objective-C methods that return CF objects, right?
+        if (MD) {
+          switch (S.getMethodFamily()) {
+          case OMF_alloc:
+          case OMF_new:
+          case OMF_copy:
+          case OMF_mutableCopy:
+            ResultEff =3D RetEffect::MakeOwned(RetEffect::CF, true);
+            break;
+          default:
+            ResultEff =3D RetEffect::MakeNotOwned(RetEffect::CF);       =20
+            break;
+          }
+        } else {
+          ResultEff =3D RetEffect::MakeNotOwned(RetEffect::CF);       =20
+        }
+      }
+      break;
+    case OMF_init:
+      ResultEff =3D ObjCInitRetE;
+      ReceiverEff =3D DecRefMsg;
+      break;
+    case OMF_alloc:
+    case OMF_new:
+    case OMF_copy:
+    case OMF_mutableCopy:
+      if (cocoa::isCocoaObjectRef(RetTy))
+        ResultEff =3D ObjCAllocRetE;
+      else if (coreFoundation::isCFObjectRef(RetTy))
+        ResultEff =3D RetEffect::MakeOwned(RetEffect::CF, true);
+      break;
+    case OMF_autorelease:
+      ReceiverEff =3D Autorelease;
+      break;
+    case OMF_retain:
+      ReceiverEff =3D IncRefMsg;
+      break;
+    case OMF_release:
+      ReceiverEff =3D DecRefMsg;
+      break;
+    case OMF_dealloc:
+      ReceiverEff =3D Dealloc;
+      break;
+    case OMF_self:
+      // -self is handled specially by the ExprEngine to propagate the rec=
eiver.
+      break;
+    case OMF_retainCount:
+    case OMF_finalize:
+      // These methods don't return objects.
+      break;
+  }
=20
   // If one of the arguments in the selector has the keyword 'delegate' we
   // should stop tracking the reference count for the receiver.  This is
@@ -1279,34 +1347,16 @@
       ReceiverEff =3D StopTracking;
   }
=20
-  // Look for methods that return an owned object.
-  if (cocoa::isCocoaObjectRef(RetTy)) {
-    // EXPERIMENTAL: assume the Cocoa conventions for all objects returned
-    //  by instance methods.
-    RetEffect E =3D cocoa::followsFundamentalRule(S, MD)
-                  ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::Obj=
C);
-
-    return getPersistentSummary(E, ReceiverEff, MayEscape);
-  }
-
-  // Look for methods that return an owned core foundation object.
-  if (coreFoundation::isCFObjectRef(RetTy)) {
-    RetEffect E =3D cocoa::followsFundamentalRule(S, MD)
-      ? RetEffect::MakeOwned(RetEffect::CF, true)
-      : RetEffect::MakeNotOwned(RetEffect::CF);
-
-    return getPersistentSummary(E, ReceiverEff, MayEscape);
-  }
-
-  if (ScratchArgs.isEmpty() && ReceiverEff =3D=3D DoNothing)
+  if (ScratchArgs.isEmpty() && ReceiverEff =3D=3D DoNothing &&
+      ResultEff.getKind() =3D=3D RetEffect::NoRet)
     return getDefaultSummary();
=20
-  return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEsca=
pe);
+  return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
 }
=20
 const RetainSummary *
 RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
-                                               const ProgramState *state,
+                                               ProgramStateRef state,
                                                const LocationContext *LC) {
=20
   // We need the type-information of the tracked receiver object
@@ -1319,7 +1369,7 @@
   SVal receiverV;
=20
   if (Receiver) {
-    receiverV =3D state->getSValAsScalarOrLoc(Receiver);
+    receiverV =3D state->getSValAsScalarOrLoc(Receiver, LC);
=20
     // FIXME: Eventually replace the use of state->get<RefBindings> with
     // a generic API for reasoning about the Objective-C types of symbolic
@@ -1348,51 +1398,22 @@
 }
=20
 const RetainSummary *
-RetainSummaryManager::getInstanceMethodSummary(Selector S,
-                                               IdentifierInfo *ClsName,
-                                               const ObjCInterfaceDecl *ID,
-                                               const ObjCMethodDecl *MD,
-                                               QualType RetTy) {
+RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName,
+                                       const ObjCInterfaceDecl *ID,
+                                       const ObjCMethodDecl *MD, QualType =
RetTy,
+                                       ObjCMethodSummariesTy &CachedSummar=
ies) {
=20
   // Look up a summary in our summary cache.
-  const RetainSummary *Summ =3D ObjCMethodSummaries.find(ID, ClsName, S);
+  const RetainSummary *Summ =3D CachedSummaries.find(ID, ClsName, S);
=20
   if (!Summ) {
-    assert(ScratchArgs.isEmpty());
-
-    // "initXXX": pass-through for receiver.
-    if (cocoa::deriveNamingConvention(S, MD) =3D=3D cocoa::InitRule)
-      Summ =3D getInitMethodSummary(RetTy);
-    else
-      Summ =3D getCommonMethodSummary(MD, S, RetTy);
+    Summ =3D getStandardMethodSummary(MD, S, RetTy);
=20
     // Annotations override defaults.
     updateSummaryFromAnnotations(Summ, MD);
=20
     // Memoize the summary.
-    ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] =3D Summ;
-  }
-
-  return Summ;
-}
-
-const RetainSummary *
-RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *Cl=
sName,
-                                            const ObjCInterfaceDecl *ID,
-                                            const ObjCMethodDecl *MD,
-                                            QualType RetTy) {
-
-  assert(ClsName && "Class name must be specified.");
-  const RetainSummary *Summ =3D ObjCClassMethodSummaries.find(ID, ClsName,=
 S);
-
-  if (!Summ) {
-    Summ =3D getCommonMethodSummary(MD, S, RetTy);
-
-    // Annotations override defaults.
-    updateSummaryFromAnnotations(Summ, MD);
-
-    // Memoize the summary.
-    ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] =3D Summ;
+    CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] =3D Summ;
   }
=20
   return Summ;
@@ -1515,6 +1536,7 @@
   // Don't track allocated autorelease pools yet, as it is okay to prematu=
rely
   // exit a method.
   addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
+  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, fa=
lse);
=20
   // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
   addInstMethSummary("QCRenderer", AllocSumm,
@@ -1561,13 +1583,13 @@
 } // end GR namespace
 } // end clang namespace
=20
-static SymbolRef GetCurrentAutoreleasePool(const ProgramState *state) {
+static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
   ARStack stack =3D state->get<AutoreleaseStack>();
   return stack.isEmpty() ? SymbolRef() : stack.getHead();
 }
=20
-static const ProgramState *
-SendAutorelease(const ProgramState *state,
+static ProgramStateRef=20
+SendAutorelease(ProgramStateRef state,
                 ARCounts::Factory &F,
                 SymbolRef sym) {
   SymbolRef pool =3D GetCurrentAutoreleasePool(state);
@@ -1598,7 +1620,7 @@
   class CFRefBug : public BugType {
   protected:
     CFRefBug(StringRef name)
-    : BugType(name, "Memory (Core Foundation/Objective-C)") {}
+    : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
   public:
=20
     // FIXME: Eventually remove.
@@ -1698,7 +1720,7 @@
   // Bug Reports.  //
   //=3D=3D=3D---------=3D=3D=3D//
=20
-  class CFRefReportVisitor : public BugReporterVisitor {
+  class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisi=
tor> {
   protected:
     SymbolRef Sym;
     const SummaryLogTy &SummaryLog;
@@ -1733,6 +1755,15 @@
     PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
                                     const ExplodedNode *N,
                                     BugReport &BR);
+
+    virtual BugReporterVisitor *clone() const {
+      // The curiously-recurring template pattern only works for one level=
 of
+      // subclassing. Rather than make a new template base for
+      // CFRefReportVisitor, we simply override clone() to do the right th=
ing.
+      // This could be trouble someday if BugReporterVisitorImpl is ever
+      // used for something else besides a convenient implementation of cl=
one().
+      return new CFRefLeakReportVisitor(*this);
+    }
   };
=20
   class CFRefReport : public BugReport {
@@ -1771,7 +1802,7 @@
   public:
     CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
                     const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sy=
m,
-                    ExprEngine &Eng);
+                    CheckerContext &Ctx);
=20
     PathDiagnosticLocation getLocation(const SourceManager &SM) const {
       assert(Location.isValid());
@@ -1823,6 +1854,20 @@
   return false;
 }
=20
+static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
+  unsigned maxDepth =3D 4;
+  while (S && maxDepth) {
+    if (const PseudoObjectExpr *PO =3D dyn_cast<PseudoObjectExpr>(S)) {
+      if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
+        return true;
+      return false;
+    }
+    S =3D PM.getParent(S);
+    --maxDepth;
+  }
+  return false;
+}
+
 PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
                                                    const ExplodedNode *Pre=
vN,
                                                    BugReporterContext &BRC,
@@ -1832,8 +1877,9 @@
     return NULL;
=20
   // Check if the type state has changed.
-  const ProgramState *PrevSt =3D PrevN->getState();
-  const ProgramState *CurrSt =3D N->getState();
+  ProgramStateRef PrevSt =3D PrevN->getState();
+  ProgramStateRef CurrSt =3D N->getState();
+  const LocationContext *LCtx =3D N->getLocationContext();
=20
   const RefVal* CurrT =3D CurrSt->get<RefBindings>(Sym);
   if (!CurrT) return NULL;
@@ -1851,40 +1897,49 @@
   if (!PrevT) {
     const Stmt *S =3D cast<StmtPoint>(N->getLocation()).getStmt();
=20
-    if (const CallExpr *CE =3D dyn_cast<CallExpr>(S)) {
-      // Get the name of the callee (if it is available).
-      SVal X =3D CurrSt->getSValAsScalarOrLoc(CE->getCallee());
-      if (const FunctionDecl *FD =3D X.getAsFunctionDecl())
-        os << "Call to function '" << *FD << '\'';
-      else
-        os << "function call";
+    if (isa<ObjCArrayLiteral>(S)) {
+      os << "NSArray literal is an object with a +0 retain count";
     }
-    else if (isa<ObjCMessageExpr>(S)) {
-      os << "Method";
-    } else {
-      os << "Property";
+    else if (isa<ObjCDictionaryLiteral>(S)) {
+      os << "NSDictionary literal is an object with a +0 retain count";
     }
-
-    if (CurrV.getObjKind() =3D=3D RetEffect::CF) {
-      os << " returns a Core Foundation object with a ";
-    }
-    else {
-      assert (CurrV.getObjKind() =3D=3D RetEffect::ObjC);
-      os << " returns an Objective-C object with a ";
-    }
-
-    if (CurrV.isOwned()) {
-      os << "+1 retain count";
-
-      if (GCEnabled) {
-        assert(CurrV.getObjKind() =3D=3D RetEffect::CF);
-        os << ".  "
-        "Core Foundation objects are not automatically garbage collected.";
+    else {     =20
+      if (const CallExpr *CE =3D dyn_cast<CallExpr>(S)) {
+        // Get the name of the callee (if it is available).
+        SVal X =3D CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
+        if (const FunctionDecl *FD =3D X.getAsFunctionDecl())
+          os << "Call to function '" << *FD << '\'';
+        else
+          os << "function call";
       }
-    }
-    else {
-      assert (CurrV.isNotOwned());
-      os << "+0 retain count";
+      else {
+        assert(isa<ObjCMessageExpr>(S));     =20
+        // The message expression may have between written directly or as
+        // a property access.  Lazily determine which case we are looking =
at.
+        os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Meth=
od");
+      }
+
+      if (CurrV.getObjKind() =3D=3D RetEffect::CF) {
+        os << " returns a Core Foundation object with a ";
+      }
+      else {
+        assert (CurrV.getObjKind() =3D=3D RetEffect::ObjC);
+        os << " returns an Objective-C object with a ";
+      }
+
+      if (CurrV.isOwned()) {
+        os << "+1 retain count";
+
+        if (GCEnabled) {
+          assert(CurrV.getObjKind() =3D=3D RetEffect::CF);
+          os << ".  "
+          "Core Foundation objects are not automatically garbage collected=
.";
+        }
+      }
+      else {
+        assert (CurrV.isNotOwned());
+        os << "+0 retain count";
+      }
     }
=20
     PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
@@ -1912,7 +1967,7 @@
=20
         // Retrieve the value of the argument.  Is it the symbol
         // we are interested in?
-        if (CurrSt->getSValAsScalarOrLoc(*AI).getAsLocSymbol() !=3D Sym)
+        if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() !=3D =
Sym)
           continue;
=20
         // We have an argument.  Get the effect!
@@ -1921,7 +1976,8 @@
     }
     else if (const ObjCMessageExpr *ME =3D dyn_cast<ObjCMessageExpr>(S)) {
       if (const Expr *receiver =3D ME->getInstanceReceiver())
-        if (CurrSt->getSValAsScalarOrLoc(receiver).getAsLocSymbol() =3D=3D=
 Sym) {
+        if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
+              .getAsLocSymbol() =3D=3D Sym) {
           // The symbol we are tracking is the receiver.
           AEffects.push_back(Summ->getReceiverEffect());
         }
@@ -1949,7 +2005,8 @@
     if (contains(AEffects, MakeCollectable)) {
       // Get the name of the function.
       const Stmt *S =3D cast<StmtPoint>(N->getLocation()).getStmt();
-      SVal X =3D CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee=
());
+      SVal X =3D
+        CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
       const FunctionDecl *FD =3D X.getAsFunctionDecl();
=20
       if (GCEnabled) {
@@ -2004,8 +2061,8 @@
=20
           if (PrevV.getKind() =3D=3D RefVal::Released) {
             assert(GCEnabled && CurrV.getCount() > 0);
-            os << " The object is not eligible for garbage collection unti=
l the "
-            "retain count reaches 0 again.";
+            os << " The object is not eligible for garbage collection unti=
l "
+                  "the retain count reaches 0 again.";
           }
=20
           break;
@@ -2015,8 +2072,12 @@
           break;
=20
         case RefVal::ReturnedOwned:
-          os << "Object returned to caller as an owning reference (single =
retain "
-          "count transferred to caller)";
+          // Autoreleases can be applied after marking a node ReturnedOwne=
d.
+          if (CurrV.getAutoreleaseCount())
+            return NULL;
+
+          os << "Object returned to caller as an owning reference (single "
+                "retain count transferred to caller)";
           break;
=20
         case RefVal::ReturnedNotOwned:
@@ -2061,7 +2122,7 @@
   for (Stmt::const_child_iterator I =3D S->child_begin(), E =3D S->child_e=
nd();
        I!=3DE; ++I)
     if (const Expr *Exp =3D dyn_cast_or_null<Expr>(*I))
-      if (CurrSt->getSValAsScalarOrLoc(Exp).getAsLocSymbol() =3D=3D Sym) {
+      if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() =3D=3D =
Sym) {
         P->addRange(Exp->getSourceRange());
         break;
       }
@@ -2069,62 +2130,42 @@
   return P;
 }
=20
-namespace {
-  class FindUniqueBinding :
-  public StoreManager::BindingsHandler {
-    SymbolRef Sym;
-    const MemRegion* Binding;
-    bool First;
-
-  public:
-    FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
-
-    bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
-                       SVal val) {
-
-      SymbolRef SymV =3D val.getAsSymbol();
-      if (!SymV || SymV !=3D Sym)
-        return true;
-
-      if (Binding) {
-        First =3D false;
-        return false;
-      }
-      else
-        Binding =3D R;
-
-      return true;
-    }
-
-    operator bool() { return First && Binding; }
-    const MemRegion* getRegion() { return Binding; }
-  };
-}
-
+// Find the first node in the current function context that referred to the
+// tracked symbol and the memory location that value was stored to. Note, =
the
+// value is only reported if the allocation occurred in the same function =
as
+// the leak.
 static std::pair<const ExplodedNode*,const MemRegion*>
 GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
                   SymbolRef Sym) {
-
-  // Find both first node that referred to the tracked symbol and the
-  // memory location that value was store to.
   const ExplodedNode *Last =3D N;
   const MemRegion* FirstBinding =3D 0;
+  const LocationContext *LeakContext =3D N->getLocationContext();
=20
   while (N) {
-    const ProgramState *St =3D N->getState();
+    ProgramStateRef St =3D N->getState();
     RefBindings B =3D St->get<RefBindings>();
=20
     if (!B.lookup(Sym))
       break;
=20
-    FindUniqueBinding FB(Sym);
+    StoreManager::FindUniqueBinding FB(Sym);
     StateMgr.iterBindings(St, FB);
     if (FB) FirstBinding =3D FB.getRegion();
=20
-    Last =3D N;
+    // Allocation node, is the last node in the current context in which t=
he
+    // symbol was tracked.
+    if (N->getLocationContext() =3D=3D LeakContext)
+      Last =3D N;
+
     N =3D N->pred_empty() ? NULL : *(N->pred_begin());
   }
=20
+  // If allocation happened in a function different from the leak node con=
text,
+  // do not report the binding.
+  if (N->getLocationContext() !=3D LeakContext) {
+    FirstBinding =3D 0;
+  }
+
   return std::make_pair(Last, FirstBinding);
 }
=20
@@ -2132,9 +2173,7 @@
 CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
                                const ExplodedNode *EndN,
                                BugReport &BR) {
-  // Tell the BugReporterContext to report cases when the tracked symbol is
-  // assigned to different variables, etc.
-  BRC.addNotableSymbol(Sym);
+  BR.markInteresting(Sym);
   return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
 }
=20
@@ -2145,7 +2184,7 @@
=20
   // Tell the BugReporterContext to report cases when the tracked symbol is
   // assigned to different variables, etc.
-  BRC.addNotableSymbol(Sym);
+  BR.markInteresting(Sym);
=20
   // We are reporting a leak.  Walk up the graph to get to the first node =
where
   // the symbol appeared, and also get the first VarDecl that tracked obje=
ct
@@ -2193,10 +2232,10 @@
     }
     else {
       const FunctionDecl *FD =3D cast<FunctionDecl>(D);
-      os << " is return from a function whose name ('"
-         << FD->getNameAsString()
+      os << " is returned from a function whose name ('"
+         << *FD
          << "') does not contain 'Copy' or 'Create'.  This violates the na=
ming"
-            " convention rules given the Memory Management Guide for Core"
+            " convention rules given in the Memory Management Guide for Co=
re"
             " Foundation";
     }   =20
   }
@@ -2218,7 +2257,7 @@
 CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
                                  bool GCEnabled, const SummaryLogTy &Log,=20
                                  ExplodedNode *n, SymbolRef sym,
-                                 ExprEngine &Eng)
+                                 CheckerContext &Ctx)
 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
=20
   // Most bug reports are cached at the location where they occurred.
@@ -2231,10 +2270,10 @@
   // same SourceLocation.
   const ExplodedNode *AllocNode =3D 0;
=20
-  const SourceManager& SMgr =3D Eng.getContext().getSourceManager();
+  const SourceManager& SMgr =3D Ctx.getSourceManager();
=20
   llvm::tie(AllocNode, AllocBinding) =3D  // Set AllocBinding.
-    GetAllocationSite(Eng.getStateManager(), getErrorNode(), sym);
+    GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
=20
   // Get the SourceLocation for the allocation site.
   ProgramPoint P =3D AllocNode->getLocation();
@@ -2244,15 +2283,14 @@
   // Fill in the description of the bug.
   Description.clear();
   llvm::raw_string_ostream os(Description);
-  unsigned AllocLine =3D SMgr.getExpansionLineNumber(AllocStmt->getLocStar=
t());
   os << "Potential leak ";
   if (GCEnabled)
     os << "(when using garbage collection) ";
-  os << "of an object allocated on line " << AllocLine;
+  os << "of an object";
=20
   // FIXME: AllocBinding doesn't get populated for RegionStore yet.
   if (AllocBinding)
-    os << " and stored into '" << AllocBinding->getString() << '\'';
+    os << " stored into '" << AllocBinding->getString() << '\'';
=20
   addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
 }
@@ -2271,24 +2309,26 @@
                     check::PostStmt<CastExpr>,
                     check::PostStmt<CallExpr>,
                     check::PostStmt<CXXConstructExpr>,
+                    check::PostStmt<ObjCArrayLiteral>,
+                    check::PostStmt<ObjCDictionaryLiteral>,
                     check::PostObjCMessage,
                     check::PreStmt<ReturnStmt>,
                     check::RegionChanges,
                     eval::Assume,
                     eval::Call > {
-  mutable llvm::OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
-  mutable llvm::OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
-  mutable llvm::OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwne=
d;
-  mutable llvm::OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
-  mutable llvm::OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
+  mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
+  mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
+  mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
+  mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
+  mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
=20
   typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolT=
agMap;
=20
   // This map is only used to ensure proper deletion of any allocated tags.
   mutable SymbolTagMap DeadSymbolTags;
=20
-  mutable llvm::OwningPtr<RetainSummaryManager> Summaries;
-  mutable llvm::OwningPtr<RetainSummaryManager> SummariesGC;
+  mutable OwningPtr<RetainSummaryManager> Summaries;
+  mutable OwningPtr<RetainSummaryManager> SummariesGC;
=20
   mutable ARCounts::Factory ARCountFactory;
=20
@@ -2386,7 +2426,7 @@
                                           bool GCEnabled) const {
     // FIXME: We don't support ARC being turned on and off during one anal=
ysis.
     // (nor, for that matter, do we support changing ASTContexts)
-    bool ARCEnabled =3D (bool)Ctx.getLangOptions().ObjCAutoRefCount;
+    bool ARCEnabled =3D (bool)Ctx.getLangOpts().ObjCAutoRefCount;
     if (GCEnabled) {
       if (!SummariesGC)
         SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
@@ -2406,7 +2446,7 @@
     return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
   }
=20
-  void printState(raw_ostream &Out, const ProgramState *State,
+  void printState(raw_ostream &Out, ProgramStateRef State,
                   const char *NL, const char *Sep) const;
=20
   void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) con=
st;
@@ -2415,66 +2455,72 @@
=20
   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
   void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
+  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
+  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) c=
onst;
   void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) con=
st;
+                     =20
   void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Ca=
ll,
                     CheckerContext &C) const;
=20
   bool evalCall(const CallExpr *CE, CheckerContext &C) const;
=20
-  const ProgramState *evalAssume(const ProgramState *state, SVal Cond,
+  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
                                  bool Assumption) const;
=20
-  const ProgramState *
-  checkRegionChanges(const ProgramState *state,
+  ProgramStateRef=20
+  checkRegionChanges(ProgramStateRef state,
                      const StoreManager::InvalidatedSymbols *invalidated,
                      ArrayRef<const MemRegion *> ExplicitRegions,
-                     ArrayRef<const MemRegion *> Regions) const;
+                     ArrayRef<const MemRegion *> Regions,
+                     const CallOrObjCMessage *Call) const;
                                        =20
-  bool wantsRegionChangeUpdate(const ProgramState *state) const {
+  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
     return true;
   }
=20
   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
   void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
                                 ExplodedNode *Pred, RetEffect RE, RefVal X,
-                                SymbolRef Sym, const ProgramState *state) =
const;
+                                SymbolRef Sym, ProgramStateRef state) cons=
t;
                                              =20
   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
-  void checkEndPath(EndOfFunctionNodeBuilder &Builder, ExprEngine &Eng) co=
nst;
-
-  const ProgramState *updateSymbol(const ProgramState *state, SymbolRef sy=
m,
+  void checkEndPath(CheckerContext &C) const;
+
+  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
                                    RefVal V, ArgEffect E, RefVal::Kind &ha=
sErr,
                                    CheckerContext &C) const;
=20
-  void processNonLeakError(const ProgramState *St, SourceRange ErrorRange,
+  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
                            RefVal::Kind ErrorKind, SymbolRef Sym,
                            CheckerContext &C) const;
+                     =20
+  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
=20
   const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
=20
-  const ProgramState *handleSymbolDeath(const ProgramState *state,
+  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
                                         SymbolRef sid, RefVal V,
                                       SmallVectorImpl<SymbolRef> &Leaked) =
const;
=20
-  std::pair<ExplodedNode *, const ProgramState *>
-  handleAutoreleaseCounts(const ProgramState *state,=20
+  std::pair<ExplodedNode *, ProgramStateRef >
+  handleAutoreleaseCounts(ProgramStateRef state,=20
                           GenericNodeBuilderRefCount Bd, ExplodedNode *Pre=
d,
-                          ExprEngine &Eng, SymbolRef Sym, RefVal V) const;
-
-  ExplodedNode *processLeaks(const ProgramState *state,
+                          CheckerContext &Ctx, SymbolRef Sym, RefVal V) co=
nst;
+
+  ExplodedNode *processLeaks(ProgramStateRef state,
                              SmallVectorImpl<SymbolRef> &Leaked,
                              GenericNodeBuilderRefCount &Builder,
-                             ExprEngine &Eng,
+                             CheckerContext &Ctx,
                              ExplodedNode *Pred =3D 0) const;
 };
 } // end anonymous namespace
=20
 namespace {
 class StopTrackingCallback : public SymbolVisitor {
-  const ProgramState *state;
+  ProgramStateRef state;
 public:
-  StopTrackingCallback(const ProgramState *st) : state(st) {}
-  const ProgramState *getState() const { return state; }
+  StopTrackingCallback(ProgramStateRef st) : state(st) {}
+  ProgramStateRef getState() const { return state; }
=20
   bool VisitSymbol(SymbolRef sym) {
     state =3D state->remove<RefBindings>(sym);
@@ -2495,9 +2541,10 @@
   if (!BE->getBlockDecl()->hasCaptures())
     return;
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   const BlockDataRegion *R =3D
-    cast<BlockDataRegion>(state->getSVal(BE).getAsRegion());
+    cast<BlockDataRegion>(state->getSVal(BE,
+                                         C.getLocationContext()).getAsRegi=
on());
=20
   BlockDataRegion::referenced_vars_iterator I =3D R->referenced_vars_begin=
(),
                                             E =3D R->referenced_vars_end();
@@ -2509,7 +2556,7 @@
   // via captured variables, even though captured variables result in a co=
py
   // and in implicit increment/decrement of a retain count.
   SmallVector<const MemRegion*, 10> Regions;
-  const LocationContext *LC =3D C.getPredecessor()->getLocationContext();
+  const LocationContext *LC =3D C.getLocationContext();
   MemRegionManager &MemMgr =3D C.getSValBuilder().getRegionManager();
=20
   for ( ; I !=3D E; ++I) {
@@ -2546,8 +2593,8 @@
       break;
   }
  =20
-  const ProgramState *state =3D C.getState();
-  SymbolRef Sym =3D state->getSVal(CE).getAsLocSymbol();
+  ProgramStateRef state =3D C.getState();
+  SymbolRef Sym =3D state->getSVal(CE, C.getLocationContext()).getAsLocSym=
bol();
   if (!Sym)
     return;
   const RefVal* T =3D state->get<RefBindings>(Sym);
@@ -2563,15 +2610,18 @@
     return;
   }
=20
-  C.generateNode(state);
+  C.addTransition(state);
 }
=20
 void RetainCountChecker::checkPostStmt(const CallExpr *CE,
                                        CheckerContext &C) const {
+  if (C.wasInlined)
+    return;
+ =20
   // Get the callee.
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
+  SVal L =3D state->getSVal(Callee, C.getLocationContext());
=20
   RetainSummaryManager &Summaries =3D getSummaryManager(C);
   const RetainSummary *Summ =3D 0;
@@ -2591,7 +2641,7 @@
   if (!Summ)
     Summ =3D Summaries.getDefaultSummary();
=20
-  checkSummary(*Summ, CallOrObjCMessage(CE, state), C);
+  checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext())=
, C);
 }
=20
 void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
@@ -2607,20 +2657,62 @@
   if (!Summ)
     return;
=20
-  const ProgramState *state =3D C.getState();
-  checkSummary(*Summ, CallOrObjCMessage(CE, state), C);
+  ProgramStateRef state =3D C.getState();
+  checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext())=
, C);
+}
+
+void RetainCountChecker::processObjCLiterals(CheckerContext &C,
+                                             const Expr *Ex) const {
+  ProgramStateRef state =3D C.getState();
+  const ExplodedNode *pred =3D C.getPredecessor(); =20
+  for (Stmt::const_child_iterator it =3D Ex->child_begin(), et =3D Ex->chi=
ld_end() ;
+       it !=3D et ; ++it) {
+    const Stmt *child =3D *it;
+    SVal V =3D state->getSVal(child, pred->getLocationContext());
+    if (SymbolRef sym =3D V.getAsSymbol())
+      if (const RefVal* T =3D state->get<RefBindings>(sym)) {
+        RefVal::Kind hasErr =3D (RefVal::Kind) 0;
+        state =3D updateSymbol(state, sym, *T, MayEscape, hasErr, C);
+        if (hasErr) {
+          processNonLeakError(state, child->getSourceRange(), hasErr, sym,=
 C);
+          return;
+        }
+      }
+  }
+ =20
+  // Return the object as autoreleased.
+  //  RetEffect RE =3D RetEffect::MakeNotOwned(RetEffect::ObjC);
+  if (SymbolRef sym =3D=20
+        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
+    QualType ResultTy =3D Ex->getType();
+    state =3D state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect:=
:ObjC,
+                                                              ResultTy));
+  }
+ =20
+  C.addTransition(state); =20
+}
+
+void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
+                                       CheckerContext &C) const {
+  // Apply the 'MayEscape' to all values.
+  processObjCLiterals(C, AL);
+}
+
+void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
+                                       CheckerContext &C) const {
+  // Apply the 'MayEscape' to all keys and values.
+  processObjCLiterals(C, DL);
 }
=20
 void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,=20
                                               CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  ExplodedNode *Pred =3D C.getPredecessor();
+  ProgramStateRef state =3D C.getState();
=20
   RetainSummaryManager &Summaries =3D getSummaryManager(C);
=20
   const RetainSummary *Summ;
   if (Msg.isInstanceMessage()) {
-    const LocationContext *LC =3D Pred->getLocationContext();
+    const LocationContext *LC =3D C.getLocationContext();
     Summ =3D Summaries.getInstanceMethodSummary(Msg, state, LC);
   } else {
     Summ =3D Summaries.getClassMethodSummary(Msg);   =20
@@ -2630,7 +2722,7 @@
   if (!Summ)
     return;
=20
-  checkSummary(*Summ, CallOrObjCMessage(Msg, state), C);
+  checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()=
), C);
 }
=20
 /// GetReturnType - Used to get the return type of a message expression or
@@ -2664,7 +2756,7 @@
 void RetainCountChecker::checkSummary(const RetainSummary &Summ,
                                       const CallOrObjCMessage &CallOrMsg,
                                       CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   // Evaluate the effect of the arguments.
   RefVal::Kind hasErr =3D (RefVal::Kind) 0;
@@ -2689,7 +2781,7 @@
   // Evaluate the effect on the message receiver.
   bool ReceiverIsTracked =3D false;
   if (!hasErr && CallOrMsg.isObjCMessage()) {
-    const LocationContext *LC =3D C.getPredecessor()->getLocationContext();
+    const LocationContext *LC =3D C.getLocationContext();
     SVal Receiver =3D CallOrMsg.getInstanceMessageReceiver(LC);
     if (SymbolRef Sym =3D Receiver.getAsLocSymbol()) {
       if (const RefVal *T =3D state->get<RefBindings>(Sym)) {
@@ -2722,7 +2814,7 @@
=20
   switch (RE.getKind()) {
     default:
-      llvm_unreachable("Unhandled RetEffect."); break;
+      llvm_unreachable("Unhandled RetEffect.");
=20
     case RetEffect::NoRet:
       // No work necessary.
@@ -2730,7 +2822,8 @@
=20
     case RetEffect::OwnedAllocatedSymbol:
     case RetEffect::OwnedSymbol: {
-      SymbolRef Sym =3D state->getSVal(CallOrMsg.getOriginExpr()).getAsSym=
bol();
+      SymbolRef Sym =3D state->getSVal(CallOrMsg.getOriginExpr(),
+                                     C.getLocationContext()).getAsSymbol();
       if (!Sym)
         break;
=20
@@ -2757,7 +2850,7 @@
     case RetEffect::ARCNotOwnedSymbol:
     case RetEffect::NotOwnedSymbol: {
       const Expr *Ex =3D CallOrMsg.getOriginExpr();
-      SymbolRef Sym =3D state->getSVal(Ex).getAsSymbol();
+      SymbolRef Sym =3D state->getSVal(Ex, C.getLocationContext()).getAsSy=
mbol();
       if (!Sym)
         break;
=20
@@ -2776,7 +2869,7 @@
   if (state =3D=3D C.getState()) {
     NewNode =3D C.getPredecessor();
   } else {
-    NewNode =3D C.generateNode(state);
+    NewNode =3D C.addTransition(state);
   }
=20
   // Annotate the node with summary we used.
@@ -2791,15 +2884,15 @@
 }
=20
=20
-const ProgramState *
-RetainCountChecker::updateSymbol(const ProgramState *state, SymbolRef sym,
+ProgramStateRef=20
+RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
                                  RefVal V, ArgEffect E, RefVal::Kind &hasE=
rr,
                                  CheckerContext &C) const {
   // In GC mode [... release] and [... retain] do nothing.
   // In ARC mode they shouldn't exist at all, but we just ignore them.
   bool IgnoreRetainMsg =3D C.isObjCGCEnabled();
   if (!IgnoreRetainMsg)
-    IgnoreRetainMsg =3D (bool)C.getASTContext().getLangOptions().ObjCAutoR=
efCount;
+    IgnoreRetainMsg =3D (bool)C.getASTContext().getLangOpts().ObjCAutoRefC=
ount;
=20
   switch (E) {
     default: break;
@@ -2822,7 +2915,6 @@
     case IncRefMsg:
     case MakeCollectable:
       llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already conver=
ted");
-      return state;
=20
     case Dealloc:
       // Any use of -dealloc in GC is *bad*.
@@ -2835,7 +2927,6 @@
       switch (V.getKind()) {
         default:
           llvm_unreachable("Invalid RefVal state for an explicit dealloc."=
);
-          break;
         case RefVal::Owned:
           // The object immediately transitions to the released state.
           V =3D V ^ RefVal::Released;
@@ -2879,7 +2970,6 @@
       switch (V.getKind()) {
         default:
           llvm_unreachable("Invalid RefVal state for a retain.");
-          break;
         case RefVal::Owned:
         case RefVal::NotOwned:
           V =3D V + 1;
@@ -2901,7 +2991,6 @@
         default:
           // case 'RefVal::Released' handled above.
           llvm_unreachable("Invalid RefVal state for a release.");
-          break;
=20
         case RefVal::Owned:
           assert(V.getCount() > 0);
@@ -2932,7 +3021,7 @@
   return state->set<RefBindings>(sym, V);
 }
=20
-void RetainCountChecker::processNonLeakError(const ProgramState *St,
+void RetainCountChecker::processNonLeakError(ProgramStateRef St,
                                              SourceRange ErrorRange,
                                              RefVal::Kind ErrorKind,
                                              SymbolRef Sym,
@@ -2945,7 +3034,6 @@
   switch (ErrorKind) {
     default:
       llvm_unreachable("Unhandled error.");
-      return;
     case RefVal::ErrorUseAfterRelease:
       if (!useAfterRelease)
         useAfterRelease.reset(new UseAfterRelease());
@@ -2969,7 +3057,7 @@
   }
=20
   assert(BT);
-  CFRefReport *report =3D new CFRefReport(*BT, C.getASTContext().getLangOp=
tions(),
+  CFRefReport *report =3D new CFRefReport(*BT, C.getASTContext().getLangOp=
ts(),
                                         C.isObjCGCEnabled(), SummaryLog,
                                         N, Sym);
   report->addRange(ErrorRange);
@@ -2982,11 +3070,8 @@
=20
 bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) c=
onst {
   // Get the callee. We're only interested in simple C functions.
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
-
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
+  ProgramStateRef state =3D C.getState();
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
   if (!FD)
     return false;
=20
@@ -3008,7 +3093,7 @@
   // See if it's one of the specific functions we know how to eval.
   bool canEval =3D false;
=20
-  QualType ResultTy =3D FD->getResultType();
+  QualType ResultTy =3D CE->getCallReturnType();
   if (ResultTy->isObjCIdType()) {
     // Handle: id NSMakeCollectable(CFTypeRef)
     canEval =3D II->isStr("NSMakeCollectable");
@@ -3026,14 +3111,15 @@
     return false;
=20
   // Bind the return value.
-  SVal RetVal =3D state->getSVal(CE->getArg(0));
+  const LocationContext *LCtx =3D C.getLocationContext();
+  SVal RetVal =3D state->getSVal(CE->getArg(0), LCtx);
   if (RetVal.isUnknown()) {
     // If the receiver is unknown, conjure a return value.
     SValBuilder &SVB =3D C.getSValBuilder();
     unsigned Count =3D C.getCurrentBlockCount();
-    SVal RetVal =3D SVB.getConjuredSymbolVal(0, CE, ResultTy, Count);
+    SVal RetVal =3D SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
   }
-  state =3D state->BindExpr(CE, RetVal, false);
+  state =3D state->BindExpr(CE, LCtx, RetVal, false);
=20
   // FIXME: This should not be necessary, but otherwise the argument seems=
 to be
   // considered alive during the next statement.
@@ -3046,7 +3132,7 @@
=20
     // Invalidate the argument region.
     unsigned Count =3D C.getCurrentBlockCount();
-    state =3D state->invalidateRegions(ArgRegion, CE, Count);
+    state =3D state->invalidateRegions(ArgRegion, CE, Count, LCtx);
=20
     // Restore the refcount status of the argument.
     if (Binding)
@@ -3061,14 +3147,30 @@
 // Handle return statements.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+// Return true if the current LocationContext has no caller context.
+static bool inTopFrame(CheckerContext &C) {
+  const LocationContext *LC =3D C.getLocationContext();
+  return LC->getParent() =3D=3D 0; =20
+}
+
 void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
                                       CheckerContext &C) const {
+
+  // Only adjust the reference count if this is the top-level call frame,
+  // and not the result of inlining.  In the future, we should do
+  // better checking even for inlined calls, and see if they match
+  // with their expected semantics (e.g., the method should return a retai=
ned
+  // object, etc.).
+  if (!inTopFrame(C))
+    return;
+
   const Expr *RetE =3D S->getRetValue();
   if (!RetE)
     return;
=20
-  const ProgramState *state =3D C.getState();
-  SymbolRef Sym =3D state->getSValAsScalarOrLoc(RetE).getAsLocSymbol();
+  ProgramStateRef state =3D C.getState();
+  SymbolRef Sym =3D
+    state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymb=
ol();
   if (!Sym)
     return;
=20
@@ -3107,7 +3209,7 @@
=20
   // Update the binding.
   state =3D state->set<RefBindings>(Sym, X);
-  ExplodedNode *Pred =3D C.generateNode(state);
+  ExplodedNode *Pred =3D C.addTransition(state);
=20
   // At this point we have updated the state properly.
   // Everything after this is merely checking to see if the return value h=
as
@@ -3121,8 +3223,7 @@
   static SimpleProgramPointTag
          AutoreleaseTag("RetainCountChecker : Autorelease");
   GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
-  llvm::tie(Pred, state) =3D handleAutoreleaseCounts(state, Bd, Pred,
-                                                   C.getEngine(), Sym, X);
+  llvm::tie(Pred, state) =3D handleAutoreleaseCounts(state, Bd, Pred, C, S=
ym, X);
=20
   // Did we cache out?
   if (!Pred)
@@ -3159,7 +3260,7 @@
                                                   ExplodedNode *Pred,
                                                   RetEffect RE, RefVal X,
                                                   SymbolRef Sym,
-                                              const ProgramState *state) c=
onst {
+                                              ProgramStateRef state) const=
 {
   // Any leaks or other errors?
   if (X.isReturnedOwned() && X.getCount() =3D=3D 0) {
     if (RE.getKind() !=3D RetEffect::NoRet) {
@@ -3186,14 +3287,14 @@
=20
         static SimpleProgramPointTag
                ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
-        ExplodedNode *N =3D C.generateNode(state, Pred, &ReturnOwnLeakTag);
+        ExplodedNode *N =3D C.addTransition(state, Pred, &ReturnOwnLeakTag=
);
         if (N) {
-          const LangOptions &LOpts =3D C.getASTContext().getLangOptions();
+          const LangOptions &LOpts =3D C.getASTContext().getLangOpts();
           bool GCEnabled =3D C.isObjCGCEnabled();
           CFRefReport *report =3D
             new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
                                 LOpts, GCEnabled, SummaryLog,
-                                N, Sym, C.getEngine());
+                                N, Sym, C);
           C.EmitReport(report);
         }
       }
@@ -3206,14 +3307,14 @@
=20
       static SimpleProgramPointTag
              ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwne=
d");
-      ExplodedNode *N =3D C.generateNode(state, Pred, &ReturnNotOwnedTag);
+      ExplodedNode *N =3D C.addTransition(state, Pred, &ReturnNotOwnedTag);
       if (N) {
         if (!returnNotOwnedForOwned)
           returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
=20
         CFRefReport *report =3D
             new CFRefReport(*returnNotOwnedForOwned,
-                            C.getASTContext().getLangOptions(),=20
+                            C.getASTContext().getLangOpts(),=20
                             C.isObjCGCEnabled(), SummaryLog, N, Sym);
         C.EmitReport(report);
       }
@@ -3236,7 +3337,7 @@
   // (2) we are binding to a memregion that does not have stack storage
   // (3) we are binding to a memregion with stack storage that the store
   //     does not understand.
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   if (loc::MemRegionVal *regionLoc =3D dyn_cast<loc::MemRegionVal>(&loc)) {
     escapes =3D !regionLoc->getRegion()->hasStackStorage();
@@ -3247,6 +3348,12 @@
       // the binding).
       escapes =3D (state =3D=3D (state->bindLoc(*regionLoc, val)));
     }
+    if (!escapes) {
+      // Case 4: We do not currently model what happens when a symbol is
+      // assigned to a struct field, so be conservative here and let the s=
ymbol
+      // go. TODO: This could definitely be improved upon.
+      escapes =3D !isa<VarRegion>(regionLoc->getRegion());
+    }
   }
=20
   // If our store can represent the binding and we aren't storing to somet=
hing
@@ -3261,7 +3368,7 @@
   C.addTransition(state);
 }
=20
-const ProgramState *RetainCountChecker::evalAssume(const ProgramState *sta=
te,
+ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
                                                    SVal Cond,
                                                    bool Assumption) const {
=20
@@ -3294,11 +3401,12 @@
   return state;
 }
=20
-const ProgramState *
-RetainCountChecker::checkRegionChanges(const ProgramState *state,
+ProgramStateRef=20
+RetainCountChecker::checkRegionChanges(ProgramStateRef state,
                             const StoreManager::InvalidatedSymbols *invali=
dated,
                                     ArrayRef<const MemRegion *> ExplicitRe=
gions,
-                                    ArrayRef<const MemRegion *> Regions) c=
onst {
+                                    ArrayRef<const MemRegion *> Regions,
+                                    const CallOrObjCMessage *Call) const {
   if (!invalidated)
     return state;
=20
@@ -3324,10 +3432,11 @@
 // Handle dead symbols and end-of-path.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-std::pair<ExplodedNode *, const ProgramState *>
-RetainCountChecker::handleAutoreleaseCounts(const ProgramState *state,=20
+std::pair<ExplodedNode *, ProgramStateRef >
+RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,=20
                                             GenericNodeBuilderRefCount Bd,
-                                            ExplodedNode *Pred, ExprEngine=
 &Eng,
+                                            ExplodedNode *Pred,
+                                            CheckerContext &Ctx,
                                             SymbolRef Sym, RefVal V) const=
 {
   unsigned ACnt =3D V.getAutoreleaseCount();
=20
@@ -3335,7 +3444,7 @@
   if (!ACnt)
     return std::make_pair(Pred, state);
=20
-  assert(!Eng.isObjCGCEnabled() && "Autorelease counts in GC mode?");
+  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
   unsigned Cnt =3D V.getCount();
=20
   // FIXME: Handle sending 'autorelease' to already released object.
@@ -3366,10 +3475,8 @@
   V =3D V ^ RefVal::ErrorOverAutorelease;
   state =3D state->set<RefBindings>(Sym, V);
=20
-  if (ExplodedNode *N =3D Bd.MakeNode(state, Pred)) {
-    N->markAsSink();
-
-    llvm::SmallString<128> sbuf;
+  if (ExplodedNode *N =3D Bd.MakeNode(state, Pred, true)) {
+    SmallString<128> sbuf;
     llvm::raw_svector_ostream os(sbuf);
     os << "Object over-autoreleased: object was sent -autorelease ";
     if (V.getAutoreleaseCount() > 1)
@@ -3379,18 +3486,18 @@
     if (!overAutorelease)
       overAutorelease.reset(new OverAutorelease());
=20
-    const LangOptions &LOpts =3D Eng.getContext().getLangOptions();
+    const LangOptions &LOpts =3D Ctx.getASTContext().getLangOpts();
     CFRefReport *report =3D
       new CFRefReport(*overAutorelease, LOpts, /* GCEnabled =3D */ false,
                       SummaryLog, N, Sym, os.str());
-    Eng.getBugReporter().EmitReport(report);
+    Ctx.EmitReport(report);
   }
=20
-  return std::make_pair((ExplodedNode *)0, (const ProgramState *)0);
+  return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
 }
=20
-const ProgramState *
-RetainCountChecker::handleSymbolDeath(const ProgramState *state,
+ProgramStateRef=20
+RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
                                       SymbolRef sid, RefVal V,
                                     SmallVectorImpl<SymbolRef> &Leaked) co=
nst {
   bool hasLeak =3D false;
@@ -3407,10 +3514,11 @@
 }
=20
 ExplodedNode *
-RetainCountChecker::processLeaks(const ProgramState *state,
+RetainCountChecker::processLeaks(ProgramStateRef state,
                                  SmallVectorImpl<SymbolRef> &Leaked,
                                  GenericNodeBuilderRefCount &Builder,
-                                 ExprEngine &Eng, ExplodedNode *Pred) cons=
t {
+                                 CheckerContext &Ctx,
+                                 ExplodedNode *Pred) const {
   if (Leaked.empty())
     return Pred;
=20
@@ -3421,51 +3529,58 @@
     for (SmallVectorImpl<SymbolRef>::iterator
          I =3D Leaked.begin(), E =3D Leaked.end(); I !=3D E; ++I) {
=20
-      const LangOptions &LOpts =3D Eng.getContext().getLangOptions();
-      bool GCEnabled =3D Eng.isObjCGCEnabled();
+      const LangOptions &LOpts =3D Ctx.getASTContext().getLangOpts();
+      bool GCEnabled =3D Ctx.isObjCGCEnabled();
       CFRefBug *BT =3D Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
                           : getLeakAtReturnBug(LOpts, GCEnabled);
       assert(BT && "BugType not initialized.");
=20
       CFRefLeakReport *report =3D new CFRefLeakReport(*BT, LOpts, GCEnable=
d,=20
-                                                    SummaryLog, N, *I, Eng=
);
-      Eng.getBugReporter().EmitReport(report);
+                                                    SummaryLog, N, *I, Ctx=
);
+      Ctx.EmitReport(report);
     }
   }
=20
   return N;
 }
=20
-void RetainCountChecker::checkEndPath(EndOfFunctionNodeBuilder &Builder,
-                                      ExprEngine &Eng) const {
-  const ProgramState *state =3D Builder.getState();
-  GenericNodeBuilderRefCount Bd(Builder);
+void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
+  ProgramStateRef state =3D Ctx.getState();
+  GenericNodeBuilderRefCount Bd(Ctx);
   RefBindings B =3D state->get<RefBindings>();
-  ExplodedNode *Pred =3D Builder.getPredecessor();
+  ExplodedNode *Pred =3D Ctx.getPredecessor();
=20
   for (RefBindings::iterator I =3D B.begin(), E =3D B.end(); I !=3D E; ++I=
) {
-    llvm::tie(Pred, state) =3D handleAutoreleaseCounts(state, Bd, Pred, En=
g,
+    llvm::tie(Pred, state) =3D handleAutoreleaseCounts(state, Bd, Pred, Ct=
x,
                                                      I->first, I->second);
     if (!state)
       return;
   }
=20
+  // If the current LocationContext has a parent, don't check for leaks.
+  // We will do that later.
+  // FIXME: we should instead check for imblances of the retain/releases,
+  // and suggest annotations.
+  if (Ctx.getLocationContext()->getParent())
+    return;
+ =20
   B =3D state->get<RefBindings>();
   SmallVector<SymbolRef, 10> Leaked;
=20
   for (RefBindings::iterator I =3D B.begin(), E =3D B.end(); I !=3D E; ++I)
     state =3D handleSymbolDeath(state, I->first, I->second, Leaked);
=20
-  processLeaks(state, Leaked, Bd, Eng, Pred);
+  processLeaks(state, Leaked, Bd, Ctx, Pred);
 }
=20
 const ProgramPointTag *
 RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
   const SimpleProgramPointTag *&tag =3D DeadSymbolTags[sym];
   if (!tag) {
-    llvm::SmallString<64> buf;
+    SmallString<64> buf;
     llvm::raw_svector_ostream out(buf);
-    out << "RetainCountChecker : Dead Symbol : " << sym->getSymbolID();
+    out << "RetainCountChecker : Dead Symbol : ";
+    sym->dumpToStream(out);
     tag =3D new SimpleProgramPointTag(out.str());
   }
   return tag; =20
@@ -3473,10 +3588,9 @@
=20
 void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
                                           CheckerContext &C) const {
-  ExprEngine &Eng =3D C.getEngine();
   ExplodedNode *Pred =3D C.getPredecessor();
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   RefBindings B =3D state->get<RefBindings>();
=20
   // Update counts from autorelease pools
@@ -3487,7 +3601,7 @@
       // Use the symbol as the tag.
       // FIXME: This might not be as unique as we would like.
       GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
-      llvm::tie(Pred, state) =3D handleAutoreleaseCounts(state, Bd, Pred, =
Eng,
+      llvm::tie(Pred, state) =3D handleAutoreleaseCounts(state, Bd, Pred, =
C,
                                                        Sym, *T);
       if (!state)
         return;
@@ -3505,7 +3619,7 @@
=20
   {
     GenericNodeBuilderRefCount Bd(C, this);
-    Pred =3D processLeaks(state, Leaked, Bd, Eng, Pred);
+    Pred =3D processLeaks(state, Leaked, Bd, C, Pred);
   }
=20
   // Did we cache out?
@@ -3520,7 +3634,7 @@
     B =3D F.remove(B, *I);
=20
   state =3D state->set<RefBindings>(B);
-  C.generateNode(state, Pred);
+  C.addTransition(state, Pred);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -3528,10 +3642,10 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 static void PrintPool(raw_ostream &Out, SymbolRef Sym,
-                      const ProgramState *State) {
+                      ProgramStateRef State) {
   Out << ' ';
   if (Sym)
-    Out << Sym->getSymbolID();
+    Sym->dumpToStream(Out);
   else
     Out << "<pool>";
   Out << ":{";
@@ -3544,14 +3658,14 @@
   Out << '}';
 }
=20
-static bool UsesAutorelease(const ProgramState *state) {
+static bool UsesAutorelease(ProgramStateRef state) {
   // A state uses autorelease if it allocated an autorelease pool or if it=
 has
   // objects in the caller's autorelease pool.
   return !state->get<AutoreleaseStack>().isEmpty() ||
           state->get<AutoreleasePoolContents>(SymbolRef());
 }
=20
-void RetainCountChecker::printState(raw_ostream &Out, const ProgramState *=
State,
+void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef Stat=
e,
                                     const char *NL, const char *Sep) const=
 {
=20
   RefBindings B =3D State->get<RefBindings>();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ReturnPointerRangeChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ReturnPoint=
erRangeChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ReturnPoint=
erRangeChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 namespace {
 class ReturnPointerRangeChecker :=20
     public Checker< check::PreStmt<ReturnStmt> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
 public:
     void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
 };
@@ -33,13 +33,13 @@
=20
 void ReturnPointerRangeChecker::checkPreStmt(const ReturnStmt *RS,
                                              CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   const Expr *RetE =3D RS->getRetValue();
   if (!RetE)
     return;
 =20
-  SVal V =3D state->getSVal(RetE);
+  SVal V =3D state->getSVal(RetE, C.getLocationContext());
   const MemRegion *R =3D V.getAsRegion();
=20
   const ElementRegion *ER =3D dyn_cast_or_null<ElementRegion>(R);
@@ -58,8 +58,8 @@
     =3D C.getStoreManager().getSizeInElements(state, ER->getSuperRegion(),
                                            ER->getValueType());
=20
-  const ProgramState *StInBound =3D state->assumeInBound(Idx, NumElements,=
 true);
-  const ProgramState *StOutBound =3D state->assumeInBound(Idx, NumElements=
, false);
+  ProgramStateRef StInBound =3D state->assumeInBound(Idx, NumElements, tru=
e);
+  ProgramStateRef StOutBound =3D state->assumeInBound(Idx, NumElements, fa=
lse);
   if (StOutBound && !StInBound) {
     ExplodedNode *N =3D C.generateSink(StOutBound);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/ReturnUndefChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ReturnUndef=
Checker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/ReturnUndef=
Checker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 namespace {
 class ReturnUndefChecker :=20
     public Checker< check::PreStmt<ReturnStmt> > {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
 public:
   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
 };
@@ -38,7 +38,7 @@
   if (!RetE)
     return;
  =20
-  if (!C.getState()->getSVal(RetE).isUndef())
+  if (!C.getState()->getSVal(RetE, C.getLocationContext()).isUndef())
     return;
  =20
   ExplodedNode *N =3D C.generateSink();
@@ -54,7 +54,8 @@
     new BugReport(*BT, BT->getDescription(), N);
=20
   report->addRange(RetE->getSourceRange());
-  report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, RetE)=
);
+  report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, RetE,
+                                                                  report));
=20
   C.EmitReport(report);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/StackAddrEscapeChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StackAddrEs=
capeChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StackAddrEs=
capeChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -26,12 +26,12 @@
 namespace {
 class StackAddrEscapeChecker : public Checker< check::PreStmt<ReturnStmt>,
                                                check::EndPath > {
-  mutable llvm::OwningPtr<BuiltinBug> BT_stackleak;
-  mutable llvm::OwningPtr<BuiltinBug> BT_returnstack;
+  mutable OwningPtr<BuiltinBug> BT_stackleak;
+  mutable OwningPtr<BuiltinBug> BT_returnstack;
=20
 public:
   void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
-  void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
+  void checkEndPath(CheckerContext &Ctx) const;
 private:
   void EmitStackError(CheckerContext &C, const MemRegion *R,
                       const Expr *RetE) const;
@@ -100,7 +100,7 @@
                  new BuiltinBug("Return of address to stack-allocated memo=
ry"));
=20
   // Generate a report for this bug.
-  llvm::SmallString<512> buf;
+  SmallString<512> buf;
   llvm::raw_svector_ostream os(buf);
   SourceRange range =3D GenName(os, R, C.getSourceManager());
   os << " returned to caller";
@@ -113,45 +113,53 @@
 }
=20
 void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
-                                        CheckerContext &C) const {
+                                          CheckerContext &C) const {
  =20
   const Expr *RetE =3D RS->getRetValue();
   if (!RetE)
     return;
 =20
-  SVal V =3D C.getState()->getSVal(RetE);
+  SVal V =3D C.getState()->getSVal(RetE, C.getLocationContext());
   const MemRegion *R =3D V.getAsRegion();
=20
-  if (!R || !R->hasStackStorage())
-    return; =20
+  if (!R)
+    return;
  =20
-  if (R->hasStackStorage()) {
-    // Automatic reference counting automatically copies blocks.
-    if (C.getASTContext().getLangOptions().ObjCAutoRefCount &&
-        isa<BlockDataRegion>(R))
-      return;
+  const StackSpaceRegion *SS =3D
+    dyn_cast_or_null<StackSpaceRegion>(R->getMemorySpace());
+   =20
+  if (!SS)
+    return;
=20
-    EmitStackError(C, R, RetE);
+  // Return stack memory in an ancestor stack frame is fine.
+  const StackFrameContext *SFC =3D SS->getStackFrame();
+  if (SFC !=3D C.getLocationContext()->getCurrentStackFrame())
     return;
-  }
+
+  // Automatic reference counting automatically copies blocks.
+  if (C.getASTContext().getLangOpts().ObjCAutoRefCount &&
+      isa<BlockDataRegion>(R))
+    return;
+
+  EmitStackError(C, R, RetE);
 }
=20
-void StackAddrEscapeChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
-                                        ExprEngine &Eng) const {
-
-  const ProgramState *state =3D B.getState();
+void StackAddrEscapeChecker::checkEndPath(CheckerContext &Ctx) const {
+  ProgramStateRef state =3D Ctx.getState();
=20
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
   class CallBack : public StoreManager::BindingsHandler {
   private:
-    ExprEngine &Eng;
+    CheckerContext &Ctx;
     const StackFrameContext *CurSFC;
   public:
     SmallVector<std::pair<const MemRegion*, const MemRegion*>, 10> V;
=20
-    CallBack(ExprEngine &Eng, const LocationContext *LCtx)
-      : Eng(Eng), CurSFC(LCtx->getCurrentStackFrame()) {}
+    CallBack(CheckerContext &CC) :
+      Ctx(CC),
+      CurSFC(CC.getLocationContext()->getCurrentStackFrame())
+    {}
    =20
     bool HandleBinding(StoreManager &SMgr, Store store,
                        const MemRegion *region, SVal val) {
@@ -165,7 +173,7 @@
        =20
       // Under automated retain release, it is okay to assign a block
       // directly to a global variable.
-      if (Eng.getContext().getLangOptions().ObjCAutoRefCount &&
+      if (Ctx.getASTContext().getLangOpts().ObjCAutoRefCount &&
           isa<BlockDataRegion>(vR))
         return true;
=20
@@ -181,14 +189,14 @@
     }
   };
    =20
-  CallBack cb(Eng, B.getPredecessor()->getLocationContext());
+  CallBack cb(Ctx);
   state->getStateManager().getStoreManager().iterBindings(state->getStore(=
),cb);
=20
   if (cb.V.empty())
     return;
=20
   // Generate an error node.
-  ExplodedNode *N =3D B.generateNode(state);
+  ExplodedNode *N =3D Ctx.addTransition(state);
   if (!N)
     return;
=20
@@ -201,10 +209,10 @@
  =20
   for (unsigned i =3D 0, e =3D cb.V.size(); i !=3D e; ++i) {
     // Generate a report for this bug.
-    llvm::SmallString<512> buf;
+    SmallString<512> buf;
     llvm::raw_svector_ostream os(buf);
     SourceRange range =3D GenName(os, cb.V[i].second,
-                                Eng.getContext().getSourceManager());
+                                Ctx.getSourceManager());
     os << " is still referred to by the global variable '";
     const VarRegion *VR =3D cast<VarRegion>(cb.V[i].first->getBaseRegion()=
);
     os << *VR->getDecl()
@@ -213,7 +221,7 @@
     if (range.isValid())
       report->addRange(range);
=20
-    Eng.getBugReporter().EmitReport(report);
+    Ctx.EmitReport(report);
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/StreamChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StreamCheck=
er.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/StreamCheck=
er.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -64,7 +64,7 @@
                  *II_fwrite,=20
                  *II_fseek, *II_ftell, *II_rewind, *II_fgetpos, *II_fsetpo=
s, =20
                  *II_clearerr, *II_feof, *II_ferror, *II_fileno;
-  mutable llvm::OwningPtr<BuiltinBug> BT_nullfp, BT_illegalwhence,
+  mutable OwningPtr<BuiltinBug> BT_nullfp, BT_illegalwhence,
                                       BT_doubleclose, BT_ResourceLeak;
=20
 public:
@@ -75,7 +75,7 @@
=20
   bool evalCall(const CallExpr *CE, CheckerContext &C) const;
   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
-  void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
+  void checkEndPath(CheckerContext &Ctx) const;
   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
=20
 private:
@@ -96,9 +96,9 @@
=20
   void OpenFileAux(CheckerContext &C, const CallExpr *CE) const;
  =20
-  const ProgramState *CheckNullStream(SVal SV, const ProgramState *state,=20
+  ProgramStateRef CheckNullStream(SVal SV, ProgramStateRef state,=20
                                  CheckerContext &C) const;
-  const ProgramState *CheckDoubleClose(const CallExpr *CE, const ProgramSt=
ate *state,=20
+  ProgramStateRef CheckDoubleClose(const CallExpr *CE, ProgramStateRef sta=
te,=20
                                  CheckerContext &C) const;
 };
=20
@@ -115,10 +115,7 @@
 }
=20
 bool StreamChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
+  const FunctionDecl *FD =3D C.getCalleeDecl(CE);
   if (!FD)
     return false;
=20
@@ -221,17 +218,18 @@
 }
=20
 void StreamChecker::OpenFileAux(CheckerContext &C, const CallExpr *CE) con=
st {
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   unsigned Count =3D C.getCurrentBlockCount();
   SValBuilder &svalBuilder =3D C.getSValBuilder();
+  const LocationContext *LCtx =3D C.getPredecessor()->getLocationContext();
   DefinedSVal RetVal =3D
-    cast<DefinedSVal>(svalBuilder.getConjuredSymbolVal(0, CE, Count));
-  state =3D state->BindExpr(CE, RetVal);
+    cast<DefinedSVal>(svalBuilder.getConjuredSymbolVal(0, CE, LCtx, Count)=
);
+  state =3D state->BindExpr(CE, C.getLocationContext(), RetVal);
  =20
   ConstraintManager &CM =3D C.getConstraintManager();
   // Bifurcate the state into two: one with a valid FILE* pointer, the oth=
er
   // with a NULL.
-  const ProgramState *stateNotNull, *stateNull;
+  ProgramStateRef stateNotNull, stateNull;
   llvm::tie(stateNotNull, stateNull) =3D CM.assumeDual(state, RetVal);
  =20
   if (SymbolRef Sym =3D RetVal.getAsSymbol()) {
@@ -247,29 +245,32 @@
 }
=20
 void StreamChecker::Fclose(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D CheckDoubleClose(CE, C.getState(), C);
+  ProgramStateRef state =3D CheckDoubleClose(CE, C.getState(), C);
   if (state)
     C.addTransition(state);
 }
=20
 void StreamChecker::Fread(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(3)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(3), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Fwrite(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(3)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(3), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Fseek(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!(state =3D CheckNullStream(state->getSVal(CE->getArg(0)), state, C)=
))
+  ProgramStateRef state =3D C.getState();
+  if (!(state =3D CheckNullStream(state->getSVal(CE->getArg(0),
+                                               C.getLocationContext()), st=
ate, C)))
     return;
   // Check the legality of the 'whence' argument of 'fseek'.
-  SVal Whence =3D state->getSVal(CE->getArg(2));
+  SVal Whence =3D state->getSVal(CE->getArg(2), C.getLocationContext());
   const nonloc::ConcreteInt *CI =3D dyn_cast<nonloc::ConcreteInt>(&Whence);
=20
   if (!CI)
@@ -279,7 +280,7 @@
   if (x >=3D 0 && x <=3D 2)
     return;
=20
-  if (ExplodedNode *N =3D C.generateNode(state)) {
+  if (ExplodedNode *N =3D C.addTransition(state)) {
     if (!BT_illegalwhence)
       BT_illegalwhence.reset(new BuiltinBug("Illegal whence argument",
 					"The whence argument to fseek() should be "
@@ -291,61 +292,69 @@
 }
=20
 void StreamChecker::Ftell(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Rewind(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Fgetpos(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Fsetpos(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Clearerr(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Feof(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Ferror(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
 void StreamChecker::Fileno(CheckerContext &C, const CallExpr *CE) const {
-  const ProgramState *state =3D C.getState();
-  if (!CheckNullStream(state->getSVal(CE->getArg(0)), state, C))
+  ProgramStateRef state =3D C.getState();
+  if (!CheckNullStream(state->getSVal(CE->getArg(0), C.getLocationContext(=
)),
+                       state, C))
     return;
 }
=20
-const ProgramState *StreamChecker::CheckNullStream(SVal SV, const ProgramS=
tate *state,
+ProgramStateRef StreamChecker::CheckNullStream(SVal SV, ProgramStateRef st=
ate,
                                     CheckerContext &C) const {
   const DefinedSVal *DV =3D dyn_cast<DefinedSVal>(&SV);
   if (!DV)
     return 0;
=20
   ConstraintManager &CM =3D C.getConstraintManager();
-  const ProgramState *stateNotNull, *stateNull;
+  ProgramStateRef stateNotNull, stateNull;
   llvm::tie(stateNotNull, stateNull) =3D CM.assumeDual(state, *DV);
=20
   if (!stateNotNull && stateNull) {
@@ -361,10 +370,11 @@
   return stateNotNull;
 }
=20
-const ProgramState *StreamChecker::CheckDoubleClose(const CallExpr *CE,
-                                               const ProgramState *state,
+ProgramStateRef StreamChecker::CheckDoubleClose(const CallExpr *CE,
+                                               ProgramStateRef state,
                                                CheckerContext &C) const {
-  SymbolRef Sym =3D state->getSVal(CE->getArg(0)).getAsSymbol();
+  SymbolRef Sym =3D
+    state->getSVal(CE->getArg(0), C.getLocationContext()).getAsSymbol();
   if (!Sym)
     return state;
  =20
@@ -399,7 +409,7 @@
   for (SymbolReaper::dead_iterator I =3D SymReaper.dead_begin(),
          E =3D SymReaper.dead_end(); I !=3D E; ++I) {
     SymbolRef Sym =3D *I;
-    const ProgramState *state =3D C.getState();
+    ProgramStateRef state =3D C.getState();
     const StreamState *SS =3D state->get<StreamState>(Sym);
     if (!SS)
       return;
@@ -418,23 +428,22 @@
   }
 }
=20
-void StreamChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
-                                 ExprEngine &Eng) const {
-  const ProgramState *state =3D B.getState();
+void StreamChecker::checkEndPath(CheckerContext &Ctx) const {
+  ProgramStateRef state =3D Ctx.getState();
   typedef llvm::ImmutableMap<SymbolRef, StreamState> SymMap;
   SymMap M =3D state->get<StreamState>();
  =20
   for (SymMap::iterator I =3D M.begin(), E =3D M.end(); I !=3D E; ++I) {
     StreamState SS =3D I->second;
     if (SS.isOpened()) {
-      ExplodedNode *N =3D B.generateNode(state);
+      ExplodedNode *N =3D Ctx.addTransition(state);
       if (N) {
         if (!BT_ResourceLeak)
           BT_ResourceLeak.reset(new BuiltinBug("Resource Leak",=20
                          "Opened File never closed. Potential Resource lea=
k."));
         BugReport *R =3D new BugReport(*BT_ResourceLeak,=20
                                      BT_ResourceLeak->getDescription(), N);
-        Eng.getBugReporter().EmitReport(R);
+        Ctx.EmitReport(R);
       }
     }
   }
@@ -445,8 +454,8 @@
   if (!RetE)
     return;
  =20
-  const ProgramState *state =3D C.getState();
-  SymbolRef Sym =3D state->getSVal(RetE).getAsSymbol();
+  ProgramStateRef state =3D C.getState();
+  SymbolRef Sym =3D state->getSVal(RetE, C.getLocationContext()).getAsSymb=
ol();
  =20
   if (!Sym)
     return;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/UndefBranchChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefBranch=
Checker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefBranch=
Checker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,12 +24,14 @@
 namespace {
=20
 class UndefBranchChecker : public Checker<check::BranchCondition> {
-  mutable llvm::OwningPtr<BuiltinBug> BT;
+  mutable OwningPtr<BuiltinBug> BT;
=20
   struct FindUndefExpr {
-    const ProgramState *St;
+    ProgramStateRef St;
+    const LocationContext *LCtx;
=20
-    FindUndefExpr(const ProgramState *S) : St(S) {}
+    FindUndefExpr(ProgramStateRef S, const LocationContext *L)=20
+      : St(S), LCtx(L) {}
=20
     const Expr *FindExpr(const Expr *Ex) {
       if (!MatchesCriteria(Ex))
@@ -45,25 +47,25 @@
       return Ex;
     }
=20
-    bool MatchesCriteria(const Expr *Ex) { return St->getSVal(Ex).isUndef(=
); }
+    bool MatchesCriteria(const Expr *Ex) {=20
+      return St->getSVal(Ex, LCtx).isUndef();
+    }
   };
=20
 public:
-  void checkBranchCondition(const Stmt *Condition, BranchNodeBuilder &Buil=
der,
-                            ExprEngine &Eng) const;
+  void checkBranchCondition(const Stmt *Condition, CheckerContext &Ctx) co=
nst;
 };
=20
 }
=20
 void UndefBranchChecker::checkBranchCondition(const Stmt *Condition,
-                                              BranchNodeBuilder &Builder,
-                                              ExprEngine &Eng) const {
-  const ProgramState *state =3D Builder.getState();
-  SVal X =3D state->getSVal(Condition);
+                                              CheckerContext &Ctx) const {
+  SVal X =3D Ctx.getState()->getSVal(Condition, Ctx.getLocationContext());
   if (X.isUndef()) {
-    ExplodedNode *N =3D Builder.generateNode(Condition, state);
+    // Generate a sink node, which implicitly marks both outgoing branches=
 as
+    // infeasible.
+    ExplodedNode *N =3D Ctx.generateSink();
     if (N) {
-      N->markAsSink();
       if (!BT)
         BT.reset(
                new BuiltinBug("Branch condition evaluates to a garbage val=
ue"));
@@ -86,25 +88,22 @@
       const Expr *Ex =3D cast<Expr>(Condition);
       ExplodedNode *PrevN =3D *N->pred_begin();
       ProgramPoint P =3D PrevN->getLocation();
-      const ProgramState *St =3D N->getState();
+      ProgramStateRef St =3D N->getState();
=20
       if (PostStmt *PS =3D dyn_cast<PostStmt>(&P))
         if (PS->getStmt() =3D=3D Ex)
           St =3D PrevN->getState();
=20
-      FindUndefExpr FindIt(St);
+      FindUndefExpr FindIt(St, Ctx.getLocationContext());
       Ex =3D FindIt.FindExpr(Ex);
=20
       // Emit the bug report.
       BugReport *R =3D new BugReport(*BT, BT->getDescription(), N);
-      R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, Ex));
+      R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, Ex, R)=
);
       R->addRange(Ex->getSourceRange());
=20
-      Eng.getBugReporter().EmitReport(R);
+      Ctx.EmitReport(R);
     }
-
-    Builder.markInfeasible(true);
-    Builder.markInfeasible(false);
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/UndefCapturedBlockVarChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefCaptur=
edBlockVarChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefCaptur=
edBlockVarChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
=20
 using namespace clang;
@@ -25,23 +26,23 @@
 namespace {
 class UndefCapturedBlockVarChecker
   : public Checker< check::PostStmt<BlockExpr> > {
- mutable llvm::OwningPtr<BugType> BT;
+ mutable OwningPtr<BugType> BT;
=20
 public:
   void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
 };
 } // end anonymous namespace
=20
-static const BlockDeclRefExpr *FindBlockDeclRefExpr(const Stmt *S,
-                                                    const VarDecl *VD){
-  if (const BlockDeclRefExpr *BR =3D dyn_cast<BlockDeclRefExpr>(S))
+static const DeclRefExpr *FindBlockDeclRefExpr(const Stmt *S,
+                                               const VarDecl *VD) {
+  if (const DeclRefExpr *BR =3D dyn_cast<DeclRefExpr>(S))
     if (BR->getDecl() =3D=3D VD)
       return BR;
=20
   for (Stmt::const_child_iterator I =3D S->child_begin(), E =3D S->child_e=
nd();
        I!=3DE; ++I)
     if (const Stmt *child =3D *I) {
-      const BlockDeclRefExpr *BR =3D FindBlockDeclRefExpr(child, VD);
+      const DeclRefExpr *BR =3D FindBlockDeclRefExpr(child, VD);
       if (BR)
         return BR;
     }
@@ -55,9 +56,10 @@
   if (!BE->getBlockDecl()->hasCaptures())
     return;
=20
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
   const BlockDataRegion *R =3D
-    cast<BlockDataRegion>(state->getSVal(BE).getAsRegion());
+    cast<BlockDataRegion>(state->getSVal(BE,
+                                         C.getLocationContext()).getAsRegi=
on());
=20
   BlockDataRegion::referenced_vars_iterator I =3D R->referenced_vars_begin=
(),
                                             E =3D R->referenced_vars_end();
@@ -72,7 +74,7 @@
       continue;
=20
     // Get the VarRegion associated with VD in the local stack frame.
-    const LocationContext *LC =3D C.getPredecessor()->getLocationContext();
+    const LocationContext *LC =3D C.getLocationContext();
     VR =3D C.getSValBuilder().getRegionManager().getVarRegion(VD, LC);
     SVal VRVal =3D state->getSVal(VR);
=20
@@ -82,7 +84,7 @@
           BT.reset(new BuiltinBug("uninitialized variable captured by bloc=
k"));
=20
         // Generate a bug report.
-        llvm::SmallString<128> buf;
+        SmallString<128> buf;
         llvm::raw_svector_ostream os(buf);
=20
         os << "Variable '" << VD->getName()=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/UndefResultChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefResult=
Checker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefResult=
Checker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -26,7 +27,7 @@
 class UndefResultChecker=20
   : public Checker< check::PostStmt<BinaryOperator> > {
=20
-  mutable llvm::OwningPtr<BugType> BT;
+  mutable OwningPtr<BugType> BT;
  =20
 public:
   void checkPostStmt(const BinaryOperator *B, CheckerContext &C) const;
@@ -35,8 +36,9 @@
=20
 void UndefResultChecker::checkPostStmt(const BinaryOperator *B,
                                        CheckerContext &C) const {
-  const ProgramState *state =3D C.getState();
-  if (state->getSVal(B).isUndef()) {
+  ProgramStateRef state =3D C.getState();
+  const LocationContext *LCtx =3D C.getLocationContext();
+  if (state->getSVal(B, LCtx).isUndef()) {
     // Generate an error node.
     ExplodedNode *N =3D C.generateSink();
     if (!N)
@@ -45,16 +47,16 @@
     if (!BT)
       BT.reset(new BuiltinBug("Result of operation is garbage or undefined=
"));
=20
-    llvm::SmallString<256> sbuf;
+    SmallString<256> sbuf;
     llvm::raw_svector_ostream OS(sbuf);
     const Expr *Ex =3D NULL;
     bool isLeft =3D true;
    =20
-    if (state->getSVal(B->getLHS()).isUndef()) {
+    if (state->getSVal(B->getLHS(), LCtx).isUndef()) {
       Ex =3D B->getLHS()->IgnoreParenCasts();
       isLeft =3D true;
     }
-    else if (state->getSVal(B->getRHS()).isUndef()) {
+    else if (state->getSVal(B->getRHS(), LCtx).isUndef()) {
       Ex =3D B->getRHS()->IgnoreParenCasts();
       isLeft =3D false;
     }
@@ -74,10 +76,12 @@
     BugReport *report =3D new BugReport(*BT, OS.str(), N);
     if (Ex) {
       report->addRange(Ex->getSourceRange());
-      report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, E=
x));
+      report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, E=
x,
+                                                                      repo=
rt));
     }
     else
-      report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, B=
));
+      report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, B,
+                                                                      repo=
rt));
     C.EmitReport(report);
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/UndefinedArraySubscriptChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedAr=
raySubscriptChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedAr=
raySubscriptChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 namespace {
 class UndefinedArraySubscriptChecker
   : public Checker< check::PreStmt<ArraySubscriptExpr> > {
-  mutable llvm::OwningPtr<BugType> BT;
+  mutable OwningPtr<BugType> BT;
=20
 public:
   void checkPreStmt(const ArraySubscriptExpr *A, CheckerContext &C) const;
@@ -34,7 +34,7 @@
 void=20
 UndefinedArraySubscriptChecker::checkPreStmt(const ArraySubscriptExpr *A,
                                              CheckerContext &C) const {
-  if (C.getState()->getSVal(A->getIdx()).isUndef()) {
+  if (C.getState()->getSVal(A->getIdx(), C.getLocationContext()).isUndef()=
) {
     if (ExplodedNode *N =3D C.generateSink()) {
       if (!BT)
         BT.reset(new BuiltinBug("Array subscript is undefined"));
@@ -43,7 +43,8 @@
       BugReport *R =3D new BugReport(*BT, BT->getName(), N);
       R->addRange(A->getIdx()->getSourceRange());
       R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                                                                 A->getIdx=
()));
+                                                                 A->getIdx=
(),
+                                                                 R));
       C.EmitReport(R);
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/UndefinedAssignmentChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedAs=
signmentChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UndefinedAs=
signmentChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 namespace {
 class UndefinedAssignmentChecker
   : public Checker<check::Bind> {
-  mutable llvm::OwningPtr<BugType> BT;
+  mutable OwningPtr<BugType> BT;
=20
 public:
   void checkBind(SVal location, SVal val, const Stmt *S,
@@ -54,8 +54,8 @@
   while (StoreE) {
     if (const BinaryOperator *B =3D dyn_cast<BinaryOperator>(StoreE)) {
       if (B->isCompoundAssignmentOp()) {
-        const ProgramState *state =3D C.getState();
-        if (state->getSVal(B->getLHS()).isUndef()) {
+        ProgramStateRef state =3D C.getState();
+        if (state->getSVal(B->getLHS(), C.getLocationContext()).isUndef())=
 {
           str =3D "The left expression of the compound assignment is an "
                 "uninitialized value. The computed value will also be garb=
age";
           ex =3D B->getLHS();
@@ -78,7 +78,7 @@
   BugReport *R =3D new BugReport(*BT, str, N);
   if (ex) {
     R->addRange(ex->getSourceRange());
-    R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, ex));
+    R->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, ex, R));
   }
   C.EmitReport(R);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/UnixAPIChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChec=
ker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/UnixAPIChec=
ker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -19,6 +19,8 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/Basic/TargetInfo.h"
 #include "llvm/ADT/Optional.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringSwitch.h"
 #include <fcntl.h>
=20
@@ -28,7 +30,7 @@
=20
 namespace {
 class UnixAPIChecker : public Checker< check::PreStmt<CallExpr> > {
-  mutable llvm::OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
+  mutable OwningPtr<BugType> BT_open, BT_pthreadOnce, BT_mallocZero;
   mutable Optional<uint64_t> Val_O_CREAT;
=20
 public:
@@ -36,10 +38,24 @@
=20
   void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
   void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
+  void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
   void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
+  void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
+  void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
+  void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
=20
   typedef void (UnixAPIChecker::*SubChecker)(CheckerContext &,
                                              const CallExpr *) const;
+private:
+  bool ReportZeroByteAllocation(CheckerContext &C,
+                                ProgramStateRef falseState,
+                                const Expr *arg,
+                                const char *fn_name) const;
+  void BasicAllocationCheck(CheckerContext &C,
+                            const CallExpr *CE,
+                            const unsigned numArgs,
+                            const unsigned sizeArg,
+                            const char *fn) const;
 };
 } //end anonymous namespace
=20
@@ -47,11 +63,11 @@
 // Utility functions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-static inline void LazyInitialize(llvm::OwningPtr<BugType> &BT,
+static inline void LazyInitialize(OwningPtr<BugType> &BT,
                                   const char *name) {
   if (BT)
     return;
-  BT.reset(new BugType(name, "Unix API"));
+  BT.reset(new BugType(name, categories::UnixAPI));
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -74,7 +90,7 @@
   }
=20
   // Look at the 'oflags' argument for the O_CREAT flag.
-  const ProgramState *state =3D C.getState();
+  ProgramStateRef state =3D C.getState();
=20
   if (CE->getNumArgs() < 2) {
     // The frontend should issue a warning for this case, so this is a san=
ity
@@ -84,7 +100,7 @@
=20
   // Now check if oflags has O_CREAT set.
   const Expr *oflagsEx =3D CE->getArg(1);
-  const SVal V =3D state->getSVal(oflagsEx);
+  const SVal V =3D state->getSVal(oflagsEx, C.getLocationContext());
   if (!isa<NonLoc>(V)) {
     // The case where 'V' can be a location can only be due to a bad heade=
r,
     // so in this case bail out.
@@ -102,7 +118,7 @@
   DefinedSVal maskedFlags =3D cast<DefinedSVal>(maskedFlagsUC);
=20
   // Check if maskedFlags is non-zero.
-  const ProgramState *trueState, *falseState;
+  ProgramStateRef trueState, falseState;
   llvm::tie(trueState, falseState) =3D state->assume(maskedFlags);
=20
   // Only emit an error if the value of 'maskedFlags' is properly
@@ -141,8 +157,9 @@
=20
   // Check if the first argument is stack allocated.  If so, issue a warni=
ng
   // because that's likely to be bad news.
-  const ProgramState *state =3D C.getState();
-  const MemRegion *R =3D state->getSVal(CE->getArg(0)).getAsRegion();
+  ProgramStateRef state =3D C.getState();
+  const MemRegion *R =3D
+    state->getSVal(CE->getArg(0), C.getLocationContext()).getAsRegion();
   if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
     return;
=20
@@ -150,7 +167,7 @@
   if (!N)
     return;
=20
-  llvm::SmallString<256> S;
+  SmallString<256> S;
   llvm::raw_svector_ostream os(S);
   os << "Call to 'pthread_once' uses";
   if (const VarRegion *VR =3D dyn_cast<VarRegion>(R))
@@ -170,78 +187,157 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// "malloc" with allocation size 0
+// "calloc", "malloc", "realloc", "alloca" and "valloc" with allocation si=
ze 0
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// FIXME: Eventually these should be rolled into the MallocChecker, but ri=
ght now
+// they're more basic and valuable for widespread use.
=20
-// FIXME: Eventually this should be rolled into the MallocChecker, but this
-// check is more basic and is valuable for widespread use.
-void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
-                                     const CallExpr *CE) const {
+// Returns true if we try to do a zero byte allocation, false otherwise.
+// Fills in trueState and falseState.
+static bool IsZeroByteAllocation(ProgramStateRef state,
+                                const SVal argVal,
+                                ProgramStateRef *trueState,
+                                ProgramStateRef *falseState) {
+  llvm::tie(*trueState, *falseState) =3D
+    state->assume(cast<DefinedSVal>(argVal));
+ =20
+  return (*falseState && !*trueState);
+}
=20
-  // Sanity check that malloc takes one argument.
-  if (CE->getNumArgs() !=3D 1)
+// Generates an error report, indicating that the function whose name is g=
iven
+// will perform a zero byte allocation.
+// Returns false if an error occured, true otherwise.
+bool UnixAPIChecker::ReportZeroByteAllocation(CheckerContext &C,
+                                              ProgramStateRef falseState,
+                                              const Expr *arg,
+                                              const char *fn_name) const {
+  ExplodedNode *N =3D C.generateSink(falseState);
+  if (!N)
+    return false;
+
+  LazyInitialize(BT_mallocZero,
+    "Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
+
+  SmallString<256> S;
+  llvm::raw_svector_ostream os(S);   =20
+  os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
+  BugReport *report =3D new BugReport(*BT_mallocZero, os.str(), N);
+
+  report->addRange(arg->getSourceRange());
+  report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, arg,
+                                                                  report));
+  C.EmitReport(report);
+
+  return true;
+}
+
+// Does a basic check for 0-sized allocations suitable for most of the bel=
ow
+// functions (modulo "calloc")
+void UnixAPIChecker::BasicAllocationCheck(CheckerContext &C,
+                                          const CallExpr *CE,
+                                          const unsigned numArgs,
+                                          const unsigned sizeArg,
+                                          const char *fn) const {
+  // Sanity check for the correct number of arguments
+  if (CE->getNumArgs() !=3D numArgs)
     return;
=20
   // Check if the allocation size is 0.
-  const ProgramState *state =3D C.getState();
-  SVal argVal =3D state->getSVal(CE->getArg(0));
+  ProgramStateRef state =3D C.getState();
+  ProgramStateRef trueState =3D NULL, falseState =3D NULL;
+  const Expr *arg =3D CE->getArg(sizeArg);
+  SVal argVal =3D state->getSVal(arg, C.getLocationContext());
=20
   if (argVal.isUnknownOrUndef())
     return;
- =20
-  const ProgramState *trueState, *falseState;
-  llvm::tie(trueState, falseState) =3D state->assume(cast<DefinedSVal>(arg=
Val));
- =20
+
   // Is the value perfectly constrained to zero?
-  if (falseState && !trueState) {
-    ExplodedNode *N =3D C.generateSink(falseState);
-    if (!N)
-      return;
-   =20
-    // FIXME: Add reference to CERT advisory, and/or C99 standard in bug
-    // output.
-
-    LazyInitialize(BT_mallocZero, "Undefined allocation of 0 bytes");
-   =20
-    BugReport *report =3D
-      new BugReport(*BT_mallocZero, "Call to 'malloc' has an allocation"
-                                            " size of 0 bytes", N);
-    report->addRange(CE->getArg(0)->getSourceRange());
-    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
-                                                                CE->getArg=
(0)));
-    C.EmitReport(report);
+  if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
+    (void) ReportZeroByteAllocation(C, falseState, arg, fn);=20
     return;
   }
   // Assume the the value is non-zero going forward.
   assert(trueState);
-  if (trueState !=3D state) {
+  if (trueState !=3D state)
+    C.addTransition(trueState);                          =20
+}
+
+void UnixAPIChecker::CheckCallocZero(CheckerContext &C,
+                                     const CallExpr *CE) const {
+  unsigned int nArgs =3D CE->getNumArgs();
+  if (nArgs !=3D 2)
+    return;
+
+  ProgramStateRef state =3D C.getState();
+  ProgramStateRef trueState =3D NULL, falseState =3D NULL;
+
+  unsigned int i;
+  for (i =3D 0; i < nArgs; i++) {
+    const Expr *arg =3D CE->getArg(i);
+    SVal argVal =3D state->getSVal(arg, C.getLocationContext());
+    if (argVal.isUnknownOrUndef()) {
+      if (i =3D=3D 0)
+        continue;
+      else
+        return;
+    }
+
+    if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
+      if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
+        return;
+      else if (i =3D=3D 0)
+        continue;
+      else
+        return;
+    }
+  }
+
+  // Assume the the value is non-zero going forward.
+  assert(trueState);
+  if (trueState !=3D state)
     C.addTransition(trueState);
-  }
 }
- =20
+
+void UnixAPIChecker::CheckMallocZero(CheckerContext &C,
+                                     const CallExpr *CE) const {
+  BasicAllocationCheck(C, CE, 1, 0, "malloc");
+}
+
+void UnixAPIChecker::CheckReallocZero(CheckerContext &C,
+                                      const CallExpr *CE) const {
+  BasicAllocationCheck(C, CE, 2, 1, "realloc");
+}
+
+void UnixAPIChecker::CheckAllocaZero(CheckerContext &C,
+                                     const CallExpr *CE) const {
+  BasicAllocationCheck(C, CE, 1, 0, "alloca");
+}
+
+void UnixAPIChecker::CheckVallocZero(CheckerContext &C,
+                                     const CallExpr *CE) const {
+  BasicAllocationCheck(C, CE, 1, 0, "valloc");
+}
+
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Central dispatch function.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-void UnixAPIChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) c=
onst {
-  // Get the callee.  All the functions we care about are C functions
-  // with simple identifiers.
-  const ProgramState *state =3D C.getState();
-  const Expr *Callee =3D CE->getCallee();
-  const FunctionDecl *Fn =3D state->getSVal(Callee).getAsFunctionDecl();
-
-  if (!Fn)
-    return;
-
-  const IdentifierInfo *FI =3D Fn->getIdentifier();
-  if (!FI)
+void UnixAPIChecker::checkPreStmt(const CallExpr *CE,
+                                  CheckerContext &C) const {
+  StringRef FName =3D C.getCalleeName(CE);
+  if (FName.empty())
     return;
=20
   SubChecker SC =3D
-    llvm::StringSwitch<SubChecker>(FI->getName())
+    llvm::StringSwitch<SubChecker>(FName)
       .Case("open", &UnixAPIChecker::CheckOpen)
       .Case("pthread_once", &UnixAPIChecker::CheckPthreadOnce)
+      .Case("calloc", &UnixAPIChecker::CheckCallocZero)
       .Case("malloc", &UnixAPIChecker::CheckMallocZero)
+      .Case("realloc", &UnixAPIChecker::CheckReallocZero)
+      .Cases("alloca", "__builtin_alloca", &UnixAPIChecker::CheckAllocaZer=
o)
+      .Case("valloc", &UnixAPIChecker::CheckVallocZero)
       .Default(NULL);
=20
   if (SC)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/UnreachableCodeChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/Unreachable=
CodeChecker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/Unreachable=
CodeChecker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 #include "clang/AST/ParentMap.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/SourceManager.h"
-#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallSet.h"
=20
 // The number of CFGBlock pointers we want to reserve memory for. This is =
used
 // once for each function we analyze.
@@ -54,10 +54,11 @@
                                               BugReporter &B,
                                               ExprEngine &Eng) const {
   CFGBlocksSet reachable, visited;
-
+ =20
   if (Eng.hasWorkRemaining())
     return;
=20
+  const Decl *D =3D 0;
   CFG *C =3D 0;
   ParentMap *PM =3D 0;
   const LocationContext *LC =3D 0;
@@ -67,9 +68,11 @@
     const ProgramPoint &P =3D I->getLocation();
     LC =3D P.getLocationContext();
=20
+    if (!D)
+      D =3D LC->getAnalysisDeclContext()->getDecl();
     // Save the CFG if we don't have it already
     if (!C)
-      C =3D LC->getAnalysisContext()->getUnoptimizedCFG();
+      C =3D LC->getAnalysisDeclContext()->getUnoptimizedCFG();
     if (!PM)
       PM =3D &LC->getParentMap();
=20
@@ -80,10 +83,15 @@
   }
=20
   // Bail out if we didn't get the CFG or the ParentMap.
-  if (!C || !PM)
+  if (!D || !C || !PM)
     return;
-
-  ASTContext &Ctx =3D B.getContext();
+ =20
+  // Don't do anything for template instantiations.  Proving that code
+  // in a template instantiation is unreachable means proving that it is
+  // unreachable in all instantiations.
+  if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D))
+    if (FD->isTemplateInstantiation())
+      return;
=20
   // Find CFGBlocks that were not covered by any node
   for (CFG::const_iterator I =3D C->begin(), E =3D C->end(); I !=3D E; ++I=
) {
@@ -108,6 +116,14 @@
     if (CB->size() > 0 && isInvalidPath(CB, *PM))
       continue;
=20
+    // It is good practice to always have a "default" label in a "switch",=
 even
+    // if we should never get there. It can be used to detect errors, for
+    // instance. Unreachable code directly under a "default" label is ther=
efore
+    // likely to be a false positive.
+    if (const Stmt *label =3D CB->getLabel())
+      if (label->getStmtClass() =3D=3D Stmt::DefaultStmtClass)
+        continue;
+
     // Special case for __builtin_unreachable.
     // FIXME: This should be extended to include other unreachable markers,
     // such as llvm_unreachable.
@@ -117,7 +133,7 @@
            ci !=3D ce; ++ci) {
         if (const CFGStmt *S =3D (*ci).getAs<CFGStmt>())
           if (const CallExpr *CE =3D dyn_cast<CallExpr>(S->getStmt())) {
-            if (CE->isBuiltinCall(Ctx) =3D=3D Builtin::BI__builtin_unreach=
able) {
+            if (CE->isBuiltinCall() =3D=3D Builtin::BI__builtin_unreachabl=
e) {
               foundUnreachable =3D true;
               break;
             }
@@ -146,8 +162,8 @@
     if (SM.isInSystemHeader(SL) || SM.isInExternCSystemHeader(SL))
       continue;
=20
-    B.EmitBasicReport("Unreachable code", "Dead code", "This statement is =
never"
-        " executed", DL, SR);
+    B.EmitBasicReport(D, "Unreachable code", "Dead code",
+                      "This statement is never executed", DL, SR);
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Checkers/VLASizeChecker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/VLASizeChec=
ker.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/VLASizeChec=
ker.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -20,20 +20,61 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/AST/CharUnits.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/STLExtras.h"
=20
 using namespace clang;
 using namespace ento;
=20
 namespace {
 class VLASizeChecker : public Checker< check::PreStmt<DeclStmt> > {
-  mutable llvm::OwningPtr<BugType> BT_zero;
-  mutable llvm::OwningPtr<BugType> BT_undef;
- =20
+  mutable OwningPtr<BugType> BT;
+  enum VLASize_Kind { VLA_Garbage, VLA_Zero, VLA_Tainted };
+
+  void reportBug(VLASize_Kind Kind,
+                 const Expr *SizeE,
+                 ProgramStateRef State,
+                 CheckerContext &C) const;
 public:
   void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
 };
 } // end anonymous namespace
=20
+void VLASizeChecker::reportBug(VLASize_Kind Kind,
+                               const Expr *SizeE,
+                               ProgramStateRef State,
+                               CheckerContext &C) const {
+  // Generate an error node.
+  ExplodedNode *N =3D C.generateSink(State);
+  if (!N)
+    return;
+
+  if (!BT)
+    BT.reset(new BuiltinBug("Dangerous variable-length array (VLA) declara=
tion"));
+
+  SmallString<256> buf;
+  llvm::raw_svector_ostream os(buf);
+  os << "Declared variable-length array (VLA) ";
+  switch (Kind) {
+  case VLA_Garbage:
+    os << "uses a garbage value as its size";
+    break;
+  case VLA_Zero:
+    os << "has zero size";
+    break;
+  case VLA_Tainted:
+    os << "has tainted size";
+    break;
+  }
+
+  BugReport *report =3D new BugReport(*BT, os.str(), N);
+  report->addRange(SizeE->getSourceRange());
+  report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, SizeE,
+                                                                  report));
+  C.EmitReport(report);
+  return;
+}
+
 void VLASizeChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) c=
onst {
   if (!DS->isSingleDecl())
     return;
@@ -49,24 +90,11 @@
=20
   // FIXME: Handle multi-dimensional VLAs.
   const Expr *SE =3D VLA->getSizeExpr();
-  const ProgramState *state =3D C.getState();
-  SVal sizeV =3D state->getSVal(SE);
+  ProgramStateRef state =3D C.getState();
+  SVal sizeV =3D state->getSVal(SE, C.getLocationContext());
=20
   if (sizeV.isUndef()) {
-    // Generate an error node.
-    ExplodedNode *N =3D C.generateSink();
-    if (!N)
-      return;
-   =20
-    if (!BT_undef)
-      BT_undef.reset(new BuiltinBug("Declared variable-length array (VLA) "
-                                    "uses a garbage value as its size"));
-
-    BugReport *report =3D
-      new BugReport(*BT_undef, BT_undef->getName(), N);
-    report->addRange(SE->getSourceRange());
-    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, SE)=
);
-    C.EmitReport(report);
+    reportBug(VLA_Garbage, SE, state, C);
     return;
   }
=20
@@ -75,23 +103,20 @@
   if (sizeV.isUnknown())
     return;
  =20
+  // Check if the size is tainted.
+  if (state->isTainted(sizeV)) {
+    reportBug(VLA_Tainted, SE, 0, C);
+    return;
+  }
+
   // Check if the size is zero.
   DefinedSVal sizeD =3D cast<DefinedSVal>(sizeV);
=20
-  const ProgramState *stateNotZero, *stateZero;
+  ProgramStateRef stateNotZero, stateZero;
   llvm::tie(stateNotZero, stateZero) =3D state->assume(sizeD);
=20
   if (stateZero && !stateNotZero) {
-    ExplodedNode *N =3D C.generateSink(stateZero);
-    if (!BT_zero)
-      BT_zero.reset(new BuiltinBug("Declared variable-length array (VLA) h=
as "
-                                   "zero size"));
-
-    BugReport *report =3D
-      new BugReport(*BT_zero, BT_zero->getName(), N);
-    report->addRange(SE->getSourceRange());
-    report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, SE)=
);
-    C.EmitReport(report);
+    reportBug(VLA_Zero, SE, stateZero, C);
     return;
   }
 =20
@@ -117,7 +142,7 @@
                                               cast<NonLoc>(EleSizeVal), Si=
zeTy);
=20
   // Finally, assume that the array's extent matches the given size.
-  const LocationContext *LC =3D C.getPredecessor()->getLocationContext();
+  const LocationContext *LC =3D C.getLocationContext();
   DefinedOrUnknownSVal Extent =3D
     state->getRegion(VD, LC)->getExtent(svalBuilder);
   DefinedOrUnknownSVal ArraySize =3D cast<DefinedOrUnknownSVal>(ArraySizeV=
al);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/AnalysisManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/AnalysisManager=
.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/AnalysisManager=
.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -14,6 +14,8 @@
 using namespace clang;
 using namespace ento;
=20
+void AnalysisManager::anchor() { }
+
 AnalysisManager::AnalysisManager(ASTContext &ctx, DiagnosticsEngine &diags,
                                  const LangOptions &lang,
                                  PathDiagnosticConsumer *pd,
@@ -25,17 +27,27 @@
                                  bool vizdot, bool vizubi,
                                  AnalysisPurgeMode purge,
                                  bool eager, bool trim,
-                                 bool inlinecall, bool useUnoptimizedCFG,
+                                 bool useUnoptimizedCFG,
                                  bool addImplicitDtors, bool addInitialize=
rs,
-                                 bool eagerlyTrimEGraph)
+                                 bool eagerlyTrimEGraph,
+                                 AnalysisIPAMode ipa,
+                                 unsigned inlineMaxStack,
+                                 unsigned inlineMaxFunctionSize,
+                                 AnalysisInliningMode IMode,
+                                 bool NoRetry)
   : AnaCtxMgr(useUnoptimizedCFG, addImplicitDtors, addInitializers),
-    Ctx(ctx), Diags(diags), LangInfo(lang), PD(pd),
+    Ctx(ctx), Diags(diags), LangOpts(lang), PD(pd),
     CreateStoreMgr(storemgr), CreateConstraintMgr(constraintmgr),
     CheckerMgr(checkerMgr), Idxer(idxer),
     AScope(ScopeDecl), MaxNodes(maxnodes), MaxVisit(maxvisit),
     VisualizeEGDot(vizdot), VisualizeEGUbi(vizubi), PurgeDead(purge),
-    EagerlyAssume(eager), TrimGraph(trim), InlineCall(inlinecall),
-    EagerlyTrimEGraph(eagerlyTrimEGraph)
+    EagerlyAssume(eager), TrimGraph(trim),
+    EagerlyTrimEGraph(eagerlyTrimEGraph),
+    IPAMode(ipa),
+    InlineMaxStackDepth(inlineMaxStack),
+    InlineMaxFunctionSize(inlineMaxFunctionSize),
+    InliningMode(IMode),
+    NoRetryExhausted(NoRetry)
 {
   AnaCtxMgr.getCFGBuildOptions().setAllAlwaysAdd();
 }
@@ -46,7 +58,7 @@
               ParentAM.AnaCtxMgr.getCFGBuildOptions().AddImplicitDtors,
               ParentAM.AnaCtxMgr.getCFGBuildOptions().AddInitializers),
     Ctx(ctx), Diags(diags),
-    LangInfo(ParentAM.LangInfo), PD(ParentAM.getPathDiagnosticConsumer()),
+    LangOpts(ParentAM.LangOpts), PD(ParentAM.getPathDiagnosticConsumer()),
     CreateStoreMgr(ParentAM.CreateStoreMgr),
     CreateConstraintMgr(ParentAM.CreateConstraintMgr),
     CheckerMgr(ParentAM.CheckerMgr),
@@ -59,15 +71,19 @@
     PurgeDead(ParentAM.PurgeDead),
     EagerlyAssume(ParentAM.EagerlyAssume),
     TrimGraph(ParentAM.TrimGraph),
-    InlineCall(ParentAM.InlineCall),
-    EagerlyTrimEGraph(ParentAM.EagerlyTrimEGraph)
+    EagerlyTrimEGraph(ParentAM.EagerlyTrimEGraph),
+    IPAMode(ParentAM.IPAMode),
+    InlineMaxStackDepth(ParentAM.InlineMaxStackDepth),
+    InlineMaxFunctionSize(ParentAM.InlineMaxFunctionSize),
+    InliningMode(ParentAM.InliningMode),
+    NoRetryExhausted(ParentAM.NoRetryExhausted)
 {
   AnaCtxMgr.getCFGBuildOptions().setAllAlwaysAdd();
 }
=20
=20
-AnalysisContext *
-AnalysisManager::getAnalysisContextInAnotherTU(const Decl *D) {
+AnalysisDeclContext *
+AnalysisManager::getAnalysisDeclContextInAnotherTU(const Decl *D) {
   idx::Entity Ent =3D idx::Entity::get(const_cast<Decl *>(D),=20
                                      Idxer->getProgram());
   FunctionDecl *FuncDef;
@@ -77,7 +93,7 @@
   if (FuncDef =3D=3D 0)
     return 0;
=20
-  // This AnalysisContext wraps function definition in another translation=
 unit.
+  // This AnalysisDeclContext wraps function definition in another transla=
tion unit.
   // But it is still owned by the AnalysisManager associated with the curr=
ent
   // translation unit.
   return AnaCtxMgr.getContext(FuncDef, TU);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/BasicConstraintManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BasicConstraint=
Manager.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BasicConstraint=
Manager.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -56,59 +56,59 @@
     : SimpleConstraintManager(subengine),=20
       ISetFactory(statemgr.getAllocator()) {}
=20
-  const ProgramState *assumeSymNE(const ProgramState *state,
+  ProgramStateRef assumeSymNE(ProgramStateRef state,
                                   SymbolRef sym,
                                   const llvm::APSInt& V,
                                   const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymEQ(const ProgramState *state,
+  ProgramStateRef assumeSymEQ(ProgramStateRef state,
                                   SymbolRef sym,
                                   const llvm::APSInt& V,
                                   const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymLT(const ProgramState *state,
+  ProgramStateRef assumeSymLT(ProgramStateRef state,
                                   SymbolRef sym,
                                   const llvm::APSInt& V,
                                   const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymGT(const ProgramState *state,
+  ProgramStateRef assumeSymGT(ProgramStateRef state,
                                   SymbolRef sym,
                                   const llvm::APSInt& V,
                                   const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymGE(const ProgramState *state,
+  ProgramStateRef assumeSymGE(ProgramStateRef state,
                                   SymbolRef sym,
                                   const llvm::APSInt& V,
                                   const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymLE(const ProgramState *state,
+  ProgramStateRef assumeSymLE(ProgramStateRef state,
                                   SymbolRef sym,
                                   const llvm::APSInt& V,
                                   const llvm::APSInt& Adjustment);
=20
-  const ProgramState *AddEQ(const ProgramState *state,
+  ProgramStateRef AddEQ(ProgramStateRef state,
                             SymbolRef sym,
                             const llvm::APSInt& V);
=20
-  const ProgramState *AddNE(const ProgramState *state,
+  ProgramStateRef AddNE(ProgramStateRef state,
                             SymbolRef sym,
                             const llvm::APSInt& V);
=20
-  const llvm::APSInt* getSymVal(const ProgramState *state,
+  const llvm::APSInt* getSymVal(ProgramStateRef state,
                                 SymbolRef sym) const;
=20
-  bool isNotEqual(const ProgramState *state,
+  bool isNotEqual(ProgramStateRef state,
                   SymbolRef sym,
                   const llvm::APSInt& V) const;
=20
-  bool isEqual(const ProgramState *state,
+  bool isEqual(ProgramStateRef state,
                SymbolRef sym,
                const llvm::APSInt& V) const;
=20
-  const ProgramState *removeDeadBindings(const ProgramState *state,
+  ProgramStateRef removeDeadBindings(ProgramStateRef state,
                                          SymbolReaper& SymReaper);
=20
-  void print(const ProgramState *state,
+  void print(ProgramStateRef state,
              raw_ostream &Out,
              const char* nl,
              const char *sep);
@@ -122,8 +122,8 @@
   return new BasicConstraintManager(statemgr, subengine);
 }
=20
-const ProgramState*
-BasicConstraintManager::assumeSymNE(const ProgramState *state,
+ProgramStateRef=20
+BasicConstraintManager::assumeSymNE(ProgramStateRef state,
                                     SymbolRef sym,
                                     const llvm::APSInt &V,
                                     const llvm::APSInt &Adjustment) {
@@ -143,8 +143,8 @@
   return AddNE(state, sym, Adjusted);
 }
=20
-const ProgramState*
-BasicConstraintManager::assumeSymEQ(const ProgramState *state,
+ProgramStateRef=20
+BasicConstraintManager::assumeSymEQ(ProgramStateRef state,
                                     SymbolRef sym,
                                     const llvm::APSInt &V,
                                     const llvm::APSInt &Adjustment) {
@@ -165,8 +165,8 @@
 }
=20
 // The logic for these will be handled in another ConstraintManager.
-const ProgramState*
-BasicConstraintManager::assumeSymLT(const ProgramState *state,
+ProgramStateRef=20
+BasicConstraintManager::assumeSymLT(ProgramStateRef state,
                                     SymbolRef sym,
                                     const llvm::APSInt &V,
                                     const llvm::APSInt &Adjustment) {
@@ -180,8 +180,8 @@
   return assumeSymNE(state, sym, V, Adjustment);
 }
=20
-const ProgramState*
-BasicConstraintManager::assumeSymGT(const ProgramState *state,
+ProgramStateRef=20
+BasicConstraintManager::assumeSymGT(ProgramStateRef state,
                                     SymbolRef sym,
                                     const llvm::APSInt &V,
                                     const llvm::APSInt &Adjustment) {
@@ -195,8 +195,8 @@
   return assumeSymNE(state, sym, V, Adjustment);
 }
=20
-const ProgramState*
-BasicConstraintManager::assumeSymGE(const ProgramState *state,
+ProgramStateRef=20
+BasicConstraintManager::assumeSymGE(ProgramStateRef state,
                                     SymbolRef sym,
                                     const llvm::APSInt &V,
                                     const llvm::APSInt &Adjustment) {
@@ -224,8 +224,8 @@
   return state;
 }
=20
-const ProgramState*
-BasicConstraintManager::assumeSymLE(const ProgramState *state,
+ProgramStateRef=20
+BasicConstraintManager::assumeSymLE(ProgramStateRef state,
                                     SymbolRef sym,
                                     const llvm::APSInt &V,
                                     const llvm::APSInt &Adjustment) {
@@ -253,14 +253,14 @@
   return state;
 }
=20
-const ProgramState *BasicConstraintManager::AddEQ(const ProgramState *stat=
e,
+ProgramStateRef BasicConstraintManager::AddEQ(ProgramStateRef state,
                                                   SymbolRef sym,
                                              const llvm::APSInt& V) {
   // Create a new state with the old binding replaced.
   return state->set<ConstEq>(sym, &state->getBasicVals().getValue(V));
 }
=20
-const ProgramState *BasicConstraintManager::AddNE(const ProgramState *stat=
e,
+ProgramStateRef BasicConstraintManager::AddNE(ProgramStateRef state,
                                                   SymbolRef sym,
                                                   const llvm::APSInt& V) {
=20
@@ -275,13 +275,13 @@
   return state->set<ConstNotEq>(sym, S);
 }
=20
-const llvm::APSInt* BasicConstraintManager::getSymVal(const ProgramState *=
state,
+const llvm::APSInt* BasicConstraintManager::getSymVal(ProgramStateRef stat=
e,
                                                       SymbolRef sym) const=
 {
   const ConstEqTy::data_type* T =3D state->get<ConstEq>(sym);
   return T ? *T : NULL;
 }
=20
-bool BasicConstraintManager::isNotEqual(const ProgramState *state,
+bool BasicConstraintManager::isNotEqual(ProgramStateRef state,
                                         SymbolRef sym,
                                         const llvm::APSInt& V) const {
=20
@@ -292,7 +292,7 @@
   return T ? T->contains(&state->getBasicVals().getValue(V)) : false;
 }
=20
-bool BasicConstraintManager::isEqual(const ProgramState *state,
+bool BasicConstraintManager::isEqual(ProgramStateRef state,
                                      SymbolRef sym,
                                      const llvm::APSInt& V) const {
   // Retrieve the EQ-set associated with the given symbol.
@@ -303,8 +303,8 @@
=20
 /// Scan all symbols referenced by the constraints. If the symbol is not a=
live
 /// as marked in LSymbols, mark it as dead in DSymbols.
-const ProgramState*
-BasicConstraintManager::removeDeadBindings(const ProgramState *state,
+ProgramStateRef=20
+BasicConstraintManager::removeDeadBindings(ProgramStateRef state,
                                            SymbolReaper& SymReaper) {
=20
   ConstEqTy CE =3D state->get<ConstEq>();
@@ -329,7 +329,7 @@
   return state->set<ConstNotEq>(CNE);
 }
=20
-void BasicConstraintManager::print(const ProgramState *state,
+void BasicConstraintManager::print(ProgramStateRef state,
                                    raw_ostream &Out,
                                    const char* nl, const char *sep) {
   // Print equality constraints.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/BugReporter.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporter.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/Analysis/CFG.h"
+#include "clang/AST/DeclObjC.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/AST/StmtObjC.h"
@@ -25,8 +26,10 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/IntrusiveRefCntPtr.h"
 #include <queue>
=20
 using namespace clang;
@@ -34,6 +37,8 @@
=20
 BugReporterVisitor::~BugReporterVisitor() {}
=20
+void BugReporterContext::anchor() {}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Helper routines for walking the ExplodedGraph and fetching statements.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -106,6 +111,59 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Diagnostic cleanup.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+/// Recursively scan through a path and prune out calls and macros pieces
+/// that aren't needed.  Return true if afterwards the path contains
+/// "interesting stuff" which means it should be pruned from the parent pa=
th.
+static bool RemoveUneededCalls(PathPieces &pieces) {
+  bool containsSomethingInteresting =3D false;
+  const unsigned N =3D pieces.size();
+ =20
+  for (unsigned i =3D 0 ; i < N ; ++i) {
+    // Remove the front piece from the path.  If it is still something we
+    // want to keep once we are done, we will push it back on the end.
+    IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
+    pieces.pop_front();
+   =20
+    switch (piece->getKind()) {
+      case PathDiagnosticPiece::Call: {
+        PathDiagnosticCallPiece *call =3D cast<PathDiagnosticCallPiece>(pi=
ece);
+        // Recursively clean out the subclass.  Keep this call around if
+        // it contains any informative diagnostics.
+        if (!RemoveUneededCalls(call->path))
+          continue;
+        containsSomethingInteresting =3D true;
+        break;
+      }
+      case PathDiagnosticPiece::Macro: {
+        PathDiagnosticMacroPiece *macro =3D cast<PathDiagnosticMacroPiece>=
(piece);
+        if (!RemoveUneededCalls(macro->subPieces))
+          continue;
+        containsSomethingInteresting =3D true;
+        break;
+      }
+      case PathDiagnosticPiece::Event: {
+        PathDiagnosticEventPiece *event =3D cast<PathDiagnosticEventPiece>=
(piece);
+        // We never throw away an event, but we do throw it away wholesale
+        // as part of a path if we throw the entire path away.
+        if (event->isPrunable())
+          continue;
+        containsSomethingInteresting =3D true;
+        break;
+      }
+      case PathDiagnosticPiece::ControlFlow:
+        break;
+    }
+   =20
+    pieces.push_back(piece);
+  }
+ =20
+  return containsSomethingInteresting;
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // PathDiagnosticBuilder and its associated routines and helper objects.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -128,14 +186,17 @@
 class PathDiagnosticBuilder : public BugReporterContext {
   BugReport *R;
   PathDiagnosticConsumer *PDC;
-  llvm::OwningPtr<ParentMap> PM;
+  OwningPtr<ParentMap> PM;
   NodeMapClosure NMC;
 public:
+  const LocationContext *LC;
+ =20
   PathDiagnosticBuilder(GRBugReporter &br,
                         BugReport *r, NodeBackMap *Backmap,
                         PathDiagnosticConsumer *pdc)
     : BugReporterContext(br),
-      R(r), PDC(pdc), NMC(Backmap) {}
+      R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationConte=
xt())
+  {}
=20
   PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
=20
@@ -145,12 +206,8 @@
   BugReport *getBugReport() { return R; }
=20
   Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
-
-  const LocationContext* getLocationContext() {
-    return R->getErrorNode()->getLocationContext();
-  }
-
-  ParentMap& getParentMap() { return R->getErrorNode()->getParentMap(); }
+ =20
+  ParentMap& getParentMap() { return LC->getParentMap(); }
=20
   const Stmt *getParent(const Stmt *S) {
     return getParentMap().getParent(S);
@@ -173,7 +230,7 @@
 PathDiagnosticLocation
 PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
   if (const Stmt *S =3D GetNextStmt(N))
-    return PathDiagnosticLocation(S, getSourceManager(), getLocationContex=
t());
+    return PathDiagnosticLocation(S, getSourceManager(), LC);
=20
   return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
                                                getSourceManager());
@@ -234,7 +291,6 @@
   assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
   ParentMap &P =3D getParentMap();
   SourceManager &SMgr =3D getSourceManager();
-  const LocationContext *LC =3D getLocationContext();
=20
   while (IsNested(S, P)) {
     const Stmt *Parent =3D P.getParentIgnoreParens(S);
@@ -322,208 +378,87 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// ScanNotableSymbols: closure-like callback for scanning Store bindings.
+// "Minimal" path diagnostic generation algorithm.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiag=
Pair;
+typedef SmallVector<StackDiagPair, 6> StackDiagVector;
=20
-static const VarDecl* GetMostRecentVarDeclBinding(const ExplodedNode *N,
-                                                  ProgramStateManager& VMg=
r,
-                                                  SVal X) {
+static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
+                                         StackDiagVector &CallStack) {
+  // If the piece contains a special message, add it to all the call
+  // pieces on the active stack.
+  if (PathDiagnosticEventPiece *ep =3D
+        dyn_cast<PathDiagnosticEventPiece>(P)) {
=20
-  for ( ; N ; N =3D N->pred_empty() ? 0 : *N->pred_begin()) {
+    if (ep->hasCallStackHint())
+      for (StackDiagVector::iterator I =3D CallStack.begin(),
+                                     E =3D CallStack.end(); I !=3D E; ++I)=
 {
+        PathDiagnosticCallPiece *CP =3D I->first;
+        const ExplodedNode *N =3D I->second;
+        std::string stackMsg =3D ep->getCallStackMessage(N);
=20
-    ProgramPoint P =3D N->getLocation();
-
-    if (!isa<PostStmt>(P))
-      continue;
-
-    const DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getS=
tmt());
-
-    if (!DR)
-      continue;
-
-    SVal Y =3D N->getState()->getSVal(DR);
-
-    if (X !=3D Y)
-      continue;
-
-    const VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl());
-
-    if (!VD)
-      continue;
-
-    return VD;
+        // The last message on the path to final bug is the most important
+        // one. Since we traverse the path backwards, do not add the messa=
ge
+        // if one has been previously added.
+        if  (!CP->hasCallStackMessage())
+          CP->setCallStackMessage(stackMsg);
+      }
   }
-
-  return 0;
 }
=20
-namespace {
-class NotableSymbolHandler
-: public StoreManager::BindingsHandler {
-
-  SymbolRef Sym;
-  const ProgramState *PrevSt;
-  const Stmt *S;
-  ProgramStateManager& VMgr;
-  const ExplodedNode *Pred;
-  PathDiagnostic& PD;
-  BugReporter& BR;
-
-public:
-
-  NotableSymbolHandler(SymbolRef sym,
-                       const ProgramState *prevst,
-                       const Stmt *s,
-                       ProgramStateManager& vmgr,
-                       const ExplodedNode *pred,
-                       PathDiagnostic& pd,
-                       BugReporter& br)
-  : Sym(sym),
-    PrevSt(prevst),
-    S(s),
-    VMgr(vmgr),
-    Pred(pred),
-    PD(pd),
-    BR(br) {}
-
-  bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
-                     SVal V) {
-
-    SymbolRef ScanSym =3D V.getAsSymbol();
-
-    if (ScanSym !=3D Sym)
-      return true;
-
-    // Check if the previous state has this binding.
-    SVal X =3D PrevSt->getSVal(loc::MemRegionVal(R));
-
-    if (X =3D=3D V) // Same binding?
-      return true;
-
-    // Different binding.  Only handle assignments for now.  We don't pull
-    // this check out of the loop because we will eventually handle other
-    // cases.
-
-    VarDecl *VD =3D 0;
-
-    if (const BinaryOperator* B =3D dyn_cast<BinaryOperator>(S)) {
-      if (!B->isAssignmentOp())
-        return true;
-
-      // What variable did we assign to?
-      DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCa=
sts());
-
-      if (!DR)
-        return true;
-
-      VD =3D dyn_cast<VarDecl>(DR->getDecl());
-    }
-    else if (const DeclStmt *DS =3D dyn_cast<DeclStmt>(S)) {
-      // FIXME: Eventually CFGs won't have DeclStmts.  Right now we
-      //  assume that each DeclStmt has a single Decl.  This invariant
-      //  holds by construction in the CFG.
-      VD =3D dyn_cast<VarDecl>(*DS->decl_begin());
-    }
-
-    if (!VD)
-      return true;
-
-    // What is the most recently referenced variable with this binding?
-    const VarDecl *MostRecent =3D GetMostRecentVarDeclBinding(Pred, VMgr, =
V);
-
-    if (!MostRecent)
-      return true;
-
-    // Create the diagnostic.
-    if (Loc::isLocType(VD->getType())) {
-      llvm::SmallString<64> buf;
-      llvm::raw_svector_ostream os(buf);
-      os << '\'' << *VD << "' now aliases '" << *MostRecent << '\'';
-      PathDiagnosticLocation L =3D
-        PathDiagnosticLocation::createBegin(S, BR.getSourceManager(),
-                                                   Pred->getLocationContex=
t());
-      PD.push_front(new PathDiagnosticEventPiece(L, os.str()));
-    }
-
-    return true;
-  }
-};
-}
-
-static void HandleNotableSymbol(const ExplodedNode *N,
-                                const Stmt *S,
-                                SymbolRef Sym, BugReporter& BR,
-                                PathDiagnostic& PD) {
-
-  const ExplodedNode *Pred =3D N->pred_empty() ? 0 : *N->pred_begin();
-  const ProgramState *PrevSt =3D Pred ? Pred->getState() : 0;
-
-  if (!PrevSt)
-    return;
-
-  // Look at the region bindings of the current state that map to the
-  // specified symbol.  Are any of them not in the previous state?
-  ProgramStateManager& VMgr =3D cast<GRBugReporter>(BR).getStateManager();
-  NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
-  cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
-}
-
-namespace {
-class ScanNotableSymbols
-: public StoreManager::BindingsHandler {
-
-  llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
-  const ExplodedNode *N;
-  const Stmt *S;
-  GRBugReporter& BR;
-  PathDiagnostic& PD;
-
-public:
-  ScanNotableSymbols(const ExplodedNode *n, const Stmt *s,
-                     GRBugReporter& br, PathDiagnostic& pd)
-  : N(n), S(s), BR(br), PD(pd) {}
-
-  bool HandleBinding(StoreManager& SMgr, Store store,
-                     const MemRegion* R, SVal V) {
-
-    SymbolRef ScanSym =3D V.getAsSymbol();
-
-    if (!ScanSym)
-      return true;
-
-    if (!BR.isNotable(ScanSym))
-      return true;
-
-    if (AlreadyProcessed.count(ScanSym))
-      return true;
-
-    AlreadyProcessed.insert(ScanSym);
-
-    HandleNotableSymbol(N, S, ScanSym, BR, PD);
-    return true;
-  }
-};
-} // end anonymous namespace
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// "Minimal" path diagnostic generation algorithm.
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager&=
 SM);
+static void CompactPathDiagnostic(PathPieces &path, const SourceManager& S=
M);
=20
 static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
                                           PathDiagnosticBuilder &PDB,
-                                          const ExplodedNode *N) {
+                                          const ExplodedNode *N,
+                                      ArrayRef<BugReporterVisitor *> visit=
ors) {
=20
   SourceManager& SMgr =3D PDB.getSourceManager();
-  const LocationContext *LC =3D PDB.getLocationContext();
+  const LocationContext *LC =3D PDB.LC;
   const ExplodedNode *NextNode =3D N->pred_empty()
                                         ? NULL : *(N->pred_begin());
+
+  StackDiagVector CallStack;
+
   while (NextNode) {
     N =3D NextNode;
+    PDB.LC =3D N->getLocationContext();
     NextNode =3D GetPredecessorNode(N);
=20
     ProgramPoint P =3D N->getLocation();
+   =20
+    if (const CallExit *CE =3D dyn_cast<CallExit>(&P)) {
+      PathDiagnosticCallPiece *C =3D
+        PathDiagnosticCallPiece::construct(N, *CE, SMgr);
+      PD.getActivePath().push_front(C);
+      PD.pushActivePath(&C->path);
+      CallStack.push_back(StackDiagPair(C, N));
+      continue;     =20
+    }
+   =20
+    if (const CallEnter *CE =3D dyn_cast<CallEnter>(&P)) {
+      PD.popActivePath();
+      // The current active path should never be empty.  Either we
+      // just added a bunch of stuff to the top-level path, or
+      // we have a previous CallExit.  If the front of the active
+      // path is not a PathDiagnosticCallPiece, it means that the
+      // path terminated within a function call.  We must then take the
+      // current contents of the active path and place it within
+      // a new PathDiagnosticCallPiece.
+      assert(!PD.getActivePath().empty());
+      PathDiagnosticCallPiece *C =3D=20
+        dyn_cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
+      if (!C) {
+        const Decl *Caller =3D CE->getLocationContext()->getDecl();
+        C =3D PathDiagnosticCallPiece::construct(PD.getActivePath(), Calle=
r);
+      }
+      C->setCallee(*CE, SMgr);
+      if (!CallStack.empty()) {
+        assert(CallStack.back().first =3D=3D C);
+        CallStack.pop_back();
+      }
+      continue;
+    }
=20
     if (const BlockEdge *BE =3D dyn_cast<BlockEdge>(&P)) {
       const CFGBlock *Src =3D BE->getSrc();
@@ -554,8 +489,8 @@
=20
           os << "Control jumps to line "
           << End.asLocation().getExpansionLineNumber();
-          PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
-                                                           os.str()));
+          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece=
(Start, End,
+                                                                os.str()));
           break;
         }
=20
@@ -606,13 +541,13 @@
                 break;
               }
             }
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                                                              os.str()));
           }
           else {
             os << "'Default' branch taken. ";
             const PathDiagnosticLocation &End =3D PDB.ExecutionContinues(o=
s, N);
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                                                              os.str()));
           }
=20
@@ -624,7 +559,7 @@
           std::string sbuf;
           llvm::raw_string_ostream os(sbuf);
           PathDiagnosticLocation End =3D PDB.ExecutionContinues(os, N);
-          PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece=
(Start, End,
                                                            os.str()));
           break;
         }
@@ -646,7 +581,7 @@
           if (const Stmt *S =3D End.asStmt())
             End =3D PDB.getEnclosingStmtLocation(S);
=20
-          PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+          PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece=
(Start, End,
                                                            os.str()));
           break;
         }
@@ -669,14 +604,14 @@
               PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
               PathDiagnosticLocation Start =3D
                 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
-              PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+              PD.getActivePath().push_front(new PathDiagnosticControlFlowP=
iece(Start, End,
                                                                os.str()));
             }
             else {
               os << "true";
               PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
               PathDiagnosticLocation End =3D PDB.ExecutionContinues(N);
-              PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+              PD.getActivePath().push_front(new PathDiagnosticControlFlowP=
iece(Start, End,
                                                                os.str()));
             }
           }
@@ -688,7 +623,7 @@
               os << "false";
               PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
               PathDiagnosticLocation End =3D PDB.ExecutionContinues(N);
-              PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+              PD.getActivePath().push_front(new PathDiagnosticControlFlowP=
iece(Start, End,
                                                                os.str()));
             }
             else {
@@ -696,7 +631,7 @@
               PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
               PathDiagnosticLocation Start =3D
                 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
-              PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+              PD.getActivePath().push_front(new PathDiagnosticControlFlowP=
iece(Start, End,
                                                                os.str()));
             }
           }
@@ -715,7 +650,7 @@
             if (const Stmt *S =3D End.asStmt())
               End =3D PDB.getEnclosingStmtLocation(S);
=20
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                                                              os.str()));
           }
           else {
@@ -724,7 +659,7 @@
             if (const Stmt *S =3D End.asStmt())
               End =3D PDB.getEnclosingStmtLocation(S);
=20
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                               "Loop condition is false.  Exiting loop"));
           }
=20
@@ -742,7 +677,7 @@
             if (const Stmt *S =3D End.asStmt())
               End =3D PDB.getEnclosingStmtLocation(S);
=20
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                                                              os.str()));
           }
           else {
@@ -750,7 +685,7 @@
             if (const Stmt *S =3D End.asStmt())
               End =3D PDB.getEnclosingStmtLocation(S);
=20
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                             "Loop condition is true.  Entering loop body")=
);
           }
=20
@@ -764,10 +699,10 @@
             End =3D PDB.getEnclosingStmtLocation(S);
=20
           if (*(Src->succ_begin()+1) =3D=3D Dst)
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                                                         "Taking false bran=
ch"));
           else
-            PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
+            PD.getActivePath().push_front(new PathDiagnosticControlFlowPie=
ce(Start, End,
                                                          "Taking true bran=
ch"));
=20
           break;
@@ -778,24 +713,20 @@
     if (NextNode) {
       // Add diagnostic pieces from custom visitors.
       BugReport *R =3D PDB.getBugReport();
-      for (BugReport::visitor_iterator I =3D R->visitor_begin(),
-           E =3D R->visitor_end(); I!=3DE; ++I) {
-        if (PathDiagnosticPiece *p =3D (*I)->VisitNode(N, NextNode, PDB, *=
R))
-          PD.push_front(p);
+      for (ArrayRef<BugReporterVisitor *>::iterator I =3D visitors.begin(),
+                                                    E =3D visitors.end();
+           I !=3D E; ++I) {
+        if (PathDiagnosticPiece *p =3D (*I)->VisitNode(N, NextNode, PDB, *=
R)) {
+          PD.getActivePath().push_front(p);
+          updateStackPiecesWithMessage(p, CallStack);
+        }
       }
     }
-
-    if (const PostStmt *PS =3D dyn_cast<PostStmt>(&P)) {
-      // Scan the region bindings, and see if a "notable" symbol has a new
-      // lval binding.
-      ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
-      PDB.getStateManager().iterBindings(N->getState(), SNS);
-    }
   }
=20
   // After constructing the full PathDiagnostic, do a pass over it to comp=
act
   // PathDiagnosticPieces that occur within a macro.
-  CompactPathDiagnostic(PD, PDB.getSourceManager());
+  CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -879,7 +810,7 @@
       }
=20
       if (S !=3D Original)
-        L =3D PathDiagnosticLocation(S, L.getManager(), PDB.getLocationCon=
text());
+        L =3D PathDiagnosticLocation(S, L.getManager(), PDB.LC);
     }
=20
     if (firstCharOnly)
@@ -902,8 +833,8 @@
=20
       // If the PathDiagnostic already has pieces, add the enclosing state=
ment
       // of the first piece as a context as well.
-      if (!PD.empty()) {
-        PrevLoc =3D PD.begin()->getLocation();
+      if (!PD.path.empty()) {
+        PrevLoc =3D (*PD.path.begin())->getLocation();
=20
         if (const Stmt *S =3D PrevLoc.asStmt())
           addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
@@ -916,12 +847,18 @@
     // Finally, add an initial edge from the start location of the first
     // statement (if it doesn't already exist).
     PathDiagnosticLocation L =3D PathDiagnosticLocation::createDeclBegin(
-                                                       PDB.getLocationCont=
ext(),
+                                                       PDB.LC,
                                                        PDB.getSourceManage=
r());
     if (L.isValid())
       rawAddEdge(L);
   }
=20
+  void flushLocations() {
+    while (!CLocs.empty())
+      popLocation();
+    PrevLoc =3D PathDiagnosticLocation();
+  }
+ =20
   void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd =3D false);
=20
   void rawAddEdge(PathDiagnosticLocation NewLoc);
@@ -988,7 +925,7 @@
            SM.getExpansionColumnNumber(ContaineeRBeg)) &&
           (ContainerEndLine !=3D ContaineeEndLine ||
            SM.getExpansionColumnNumber(ContainerREnd) >=3D
-           SM.getExpansionColumnNumber(ContainerREnd)));
+           SM.getExpansionColumnNumber(ContaineeREnd)));
 }
=20
 void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
@@ -1008,7 +945,7 @@
       PrevLocClean.asLocation().getExpansionLoc())
     return;
=20
-  PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocCle=
an));
+  PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocC=
lean, PrevLocClean));
   PrevLoc =3D NewLoc;
 }
=20
@@ -1093,7 +1030,7 @@
   if (!S)
     return;
=20
-  PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.getLocationConte=
xt());
+  PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
=20
   while (!CLocs.empty()) {
     const PathDiagnosticLocation &TopContextLoc =3D CLocs.back();
@@ -1116,9 +1053,11 @@
=20
 static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
                                             PathDiagnosticBuilder &PDB,
-                                            const ExplodedNode *N) {
+                                            const ExplodedNode *N,
+                                      ArrayRef<BugReporterVisitor *> visit=
ors) {
   EdgeBuilder EB(PD, PDB);
   const SourceManager& SM =3D PDB.getSourceManager();
+  StackDiagVector CallStack;
=20
   const ExplodedNode *NextNode =3D N->pred_empty() ? NULL : *(N->pred_begi=
n());
   while (NextNode) {
@@ -1127,14 +1066,74 @@
     ProgramPoint P =3D N->getLocation();
=20
     do {
+      if (const CallExit *CE =3D dyn_cast<CallExit>(&P)) {
+        const StackFrameContext *LCtx =3D
+        CE->getLocationContext()->getCurrentStackFrame();
+        PathDiagnosticLocation Loc(LCtx->getCallSite(),
+                                   PDB.getSourceManager(),
+                                   LCtx);
+        EB.addEdge(Loc, true);
+        EB.flushLocations();
+        PathDiagnosticCallPiece *C =3D
+          PathDiagnosticCallPiece::construct(N, *CE, SM);
+        PD.getActivePath().push_front(C);
+        PD.pushActivePath(&C->path);
+        CallStack.push_back(StackDiagPair(C, N));
+        break;
+      }
+     =20
+      // Pop the call hierarchy if we are done walking the contents
+      // of a function call.
+      if (const CallEnter *CE =3D dyn_cast<CallEnter>(&P)) {
+        // Add an edge to the start of the function.
+        const Decl *D =3D CE->getCalleeContext()->getDecl();
+        PathDiagnosticLocation pos =3D
+          PathDiagnosticLocation::createBegin(D, SM);
+        EB.addEdge(pos);
+       =20
+        // Flush all locations, and pop the active path.
+        EB.flushLocations();
+        PD.popActivePath();
+        assert(!PD.getActivePath().empty());
+        PDB.LC =3D N->getLocationContext();
+
+        // The current active path should never be empty.  Either we
+        // just added a bunch of stuff to the top-level path, or
+        // we have a previous CallExit.  If the front of the active
+        // path is not a PathDiagnosticCallPiece, it means that the
+        // path terminated within a function call.  We must then take the
+        // current contents of the active path and place it within
+        // a new PathDiagnosticCallPiece.
+        PathDiagnosticCallPiece *C =3D
+          dyn_cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
+        if (!C) {
+          const Decl * Caller =3D CE->getLocationContext()->getDecl();
+          C =3D PathDiagnosticCallPiece::construct(PD.getActivePath(), Cal=
ler);
+        }
+        C->setCallee(*CE, SM);
+        EB.addContext(CE->getCallExpr());
+
+        if (!CallStack.empty()) {
+          assert(CallStack.back().first =3D=3D C);
+          CallStack.pop_back();
+        }
+        break;
+      }
+     =20
+      // Note that is important that we update the LocationContext
+      // after looking at CallExits.  CallExit basically adds an
+      // edge in the *caller*, so we don't want to update the LocationCont=
ext
+      // too soon.
+      PDB.LC =3D N->getLocationContext();
+
       // Block edges.
-      if (const BlockEdge *BE =3D dyn_cast<BlockEdge>(&P)) {
+      if (const BlockEdge *BE =3D dyn_cast<BlockEdge>(&P)) {       =20
         const CFGBlock &Blk =3D *BE->getSrc();
         const Stmt *Term =3D Blk.getTerminator();
=20
         // Are we jumping to the head of a loop?  Add a special diagnostic.
         if (const Stmt *Loop =3D BE->getDst()->getLoopTarget()) {
-          PathDiagnosticLocation L(Loop, SM, PDB.getLocationContext());
+          PathDiagnosticLocation L(Loop, SM, PDB.LC);
           const CompoundStmt *CS =3D NULL;
=20
           if (!Term) {
@@ -1147,9 +1146,10 @@
           PathDiagnosticEventPiece *p =3D
             new PathDiagnosticEventPiece(L,
                                         "Looping back to the head of the l=
oop");
+          p->setPrunable(true);
=20
           EB.addEdge(p->getLocation(), true);
-          PD.push_front(p);
+          PD.getActivePath().push_front(p);
=20
           if (CS) {
             PathDiagnosticLocation BL =3D
@@ -1177,6 +1177,8 @@
        =20
         break;
       }
+     =20
+     =20
     } while (0);
=20
     if (!NextNode)
@@ -1184,12 +1186,15 @@
=20
     // Add pieces from custom visitors.
     BugReport *R =3D PDB.getBugReport();
-    for (BugReport::visitor_iterator I =3D R->visitor_begin(),
-                                     E =3D R->visitor_end(); I!=3DE; ++I) {
+    for (ArrayRef<BugReporterVisitor *>::iterator I =3D visitors.begin(),
+                                                  E =3D visitors.end();
+         I !=3D E; ++I) {
       if (PathDiagnosticPiece *p =3D (*I)->VisitNode(N, NextNode, PDB, *R)=
) {
         const PathDiagnosticLocation &Loc =3D p->getLocation();
         EB.addEdge(Loc, true);
-        PD.push_front(p);
+        PD.getActivePath().push_front(p);
+        updateStackPiecesWithMessage(p, CallStack);
+
         if (const Stmt *S =3D Loc.asStmt())
           EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
       }
@@ -1204,10 +1209,14 @@
=20
 void BugType::FlushReports(BugReporter &BR) {}
=20
+void BuiltinBug::anchor() {}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Methods for BugReport and subclasses.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void BugReport::NodeResolver::anchor() {}
+
 void BugReport::addVisitor(BugReporterVisitor* visitor) {
   if (!visitor)
     return;
@@ -1222,7 +1231,8 @@
   }
=20
   CallbacksSet.InsertNode(visitor, InsertPos);
-  Callbacks =3D F.add(visitor, Callbacks);
+  Callbacks.push_back(visitor);
+  ++ConfigurationChangeToken;
 }
=20
 BugReport::~BugReport() {
@@ -1231,10 +1241,24 @@
   }
 }
=20
+const Decl *BugReport::getDeclWithIssue() const {
+  if (DeclWithIssue)
+    return DeclWithIssue;
+ =20
+  const ExplodedNode *N =3D getErrorNode();
+  if (!N)
+    return 0;
+ =20
+  const LocationContext *LC =3D N->getLocationContext();
+  return LC->getCurrentStackFrame()->getDecl();
+}
+
 void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
   hash.AddPointer(&BT);
   hash.AddString(Description);
-  if (Location.isValid()) {
+  if (UniqueingLocation.isValid()) {
+    UniqueingLocation.Profile(hash);
+  } else if (Location.isValid()) {
     Location.Profile(hash);
   } else {
     assert(ErrorNode);
@@ -1251,6 +1275,61 @@
   }
 }
=20
+void BugReport::markInteresting(SymbolRef sym) {
+  if (!sym)
+    return;
+
+  // If the symbol wasn't already in our set, note a configuration change.
+  if (interestingSymbols.insert(sym).second)
+    ++ConfigurationChangeToken;
+
+  if (const SymbolMetadata *meta =3D dyn_cast<SymbolMetadata>(sym))
+    interestingRegions.insert(meta->getRegion());
+}
+
+void BugReport::markInteresting(const MemRegion *R) {
+  if (!R)
+    return;
+
+  // If the base region wasn't already in our set, note a configuration ch=
ange.
+  R =3D R->getBaseRegion();
+  if (interestingRegions.insert(R).second)
+    ++ConfigurationChangeToken;
+
+  if (const SymbolicRegion *SR =3D dyn_cast<SymbolicRegion>(R))
+    interestingSymbols.insert(SR->getSymbol());
+}
+
+void BugReport::markInteresting(SVal V) {
+  markInteresting(V.getAsRegion());
+  markInteresting(V.getAsSymbol());
+}
+
+bool BugReport::isInteresting(SVal V) const {
+  return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
+}
+
+bool BugReport::isInteresting(SymbolRef sym) const {
+  if (!sym)
+    return false;
+  // We don't currently consider metadata symbols to be interesting
+  // even if we know their region is interesting. Is that correct behavior?
+  return interestingSymbols.count(sym);
+}
+
+bool BugReport::isInteresting(const MemRegion *R) const {
+  if (!R)
+    return false;
+  R =3D R->getBaseRegion();
+  bool b =3D interestingRegions.count(R);
+  if (b)
+    return true;
+  if (const SymbolicRegion *SR =3D dyn_cast<SymbolicRegion>(R))
+    return interestingSymbols.count(SR->getSymbol());
+  return false;
+}
+ =20
+
 const Stmt *BugReport::getStmt() const {
   if (!ErrorNode)
     return 0;
@@ -1316,10 +1395,7 @@
 // Methods for BugReporter and subclasses.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-BugReportEquivClass::~BugReportEquivClass() {
-  for (iterator I=3Dbegin(), E=3Dend(); I!=3DE; ++I) delete *I;
-}
-
+BugReportEquivClass::~BugReportEquivClass() { }
 GRBugReporter::~GRBugReporter() { }
 BugReporterData::~BugReporterData() {}
=20
@@ -1394,8 +1470,8 @@
=20
   // Create owning pointers for GTrim and NMap just to ensure that they are
   // released when this function exists.
-  llvm::OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
-  llvm::OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
+  OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
+  OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
=20
   // Find the (first) error node in the trimmed graph.  We just need to co=
nsult
   // the node map (NMap) which maps from nodes in the original graph to no=
des
@@ -1513,19 +1589,28 @@
=20
 /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic o=
bject
 ///  and collapses PathDiagosticPieces that are expanded by macros.
-static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager&=
 SM) {
-  typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation>=
 >
-          MacroStackTy;
+static void CompactPathDiagnostic(PathPieces &path, const SourceManager& S=
M) {
+  typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiec=
e>,
+                                SourceLocation> > MacroStackTy;
=20
-  typedef std::vector<PathDiagnosticPiece*>
+  typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
           PiecesTy;
=20
   MacroStackTy MacroStack;
   PiecesTy Pieces;
=20
-  for (PathDiagnostic::iterator I =3D PD.begin(), E =3D PD.end(); I!=3DE; =
++I) {
+  for (PathPieces::const_iterator I =3D path.begin(), E =3D path.end();
+       I!=3DE; ++I) {
+   =20
+    PathDiagnosticPiece *piece =3D I->getPtr();
+
+    // Recursively compact calls.
+    if (PathDiagnosticCallPiece *call=3Ddyn_cast<PathDiagnosticCallPiece>(=
piece)){
+      CompactPathDiagnostic(call->path, SM);
+    }
+   =20
     // Get the location of the PathDiagnosticPiece.
-    const FullSourceLoc Loc =3D I->getLocation().asLocation();
+    const FullSourceLoc Loc =3D piece->getLocation().asLocation();
=20
     // Determine the instantiation location, which is the location we group
     // related PathDiagnosticPieces.
@@ -1535,7 +1620,7 @@
=20
     if (Loc.isFileID()) {
       MacroStack.clear();
-      Pieces.push_back(&*I);
+      Pieces.push_back(piece);
       continue;
     }
=20
@@ -1543,13 +1628,13 @@
=20
     // Is the PathDiagnosticPiece within the same macro group?
     if (!MacroStack.empty() && InstantiationLoc =3D=3D MacroStack.back().s=
econd) {
-      MacroStack.back().first->push_back(&*I);
+      MacroStack.back().first->subPieces.push_back(piece);
       continue;
     }
=20
     // We aren't in the same group.  Are we descending into a new macro
     // or are part of an old one?
-    PathDiagnosticMacroPiece *MacroGroup =3D 0;
+    IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
=20
     SourceLocation ParentInstantiationLoc =3D InstantiationLoc.isMacroID()=
 ?
                                           SM.getExpansionLoc(Loc) :
@@ -1574,10 +1659,10 @@
       // Create a new macro group and add it to the stack.
       PathDiagnosticMacroPiece *NewGroup =3D
         new PathDiagnosticMacroPiece(
-          PathDiagnosticLocation::createSingleLocation(I->getLocation()));
+          PathDiagnosticLocation::createSingleLocation(piece->getLocation(=
)));
=20
       if (MacroGroup)
-        MacroGroup->push_back(NewGroup);
+        MacroGroup->subPieces.push_back(NewGroup);
       else {
         assert(InstantiationLoc.isFileID());
         Pieces.push_back(NewGroup);
@@ -1588,21 +1673,14 @@
     }
=20
     // Finally, add the PathDiagnosticPiece to the group.
-    MacroGroup->push_back(&*I);
+    MacroGroup->subPieces.push_back(piece);
   }
=20
   // Now take the pieces and construct a new PathDiagnostic.
-  PD.resetPath(false);
+  path.clear();
=20
-  for (PiecesTy::iterator I=3DPieces.begin(), E=3DPieces.end(); I!=3DE; ++=
I) {
-    if (PathDiagnosticMacroPiece *MP=3Ddyn_cast<PathDiagnosticMacroPiece>(=
*I))
-      if (!MP->containsEvent()) {
-        delete MP;
-        continue;
-      }
-
-    PD.push_back(*I);
-  }
+  for (PiecesTy::iterator I=3DPieces.begin(), E=3DPieces.end(); I!=3DE; ++=
I)
+    path.push_back(*I);
 }
=20
 void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
@@ -1626,8 +1704,8 @@
   BugReport *R =3D bugReports[GPair.second.second];
   assert(R && "No original report found for sliced graph.");
=20
-  llvm::OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
-  llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
+  OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
+  OwningPtr<NodeBackMap> BackMap(GPair.first.second);
   const ExplodedNode *N =3D GPair.second.first;
=20
   // Start building the path diagnostic...
@@ -1638,32 +1716,61 @@
   R->addVisitor(new NilReceiverBRVisitor());
   R->addVisitor(new ConditionBRVisitor());
=20
-  // Generate the very last diagnostic piece - the piece is visible before=20
-  // the trace is expanded.
-  PathDiagnosticPiece *LastPiece =3D 0;
-  for (BugReport::visitor_iterator I =3D R->visitor_begin(),
-                                   E =3D R->visitor_end(); I!=3DE; ++I) {
-    if (PathDiagnosticPiece *Piece =3D (*I)->getEndPath(PDB, N, *R)) {
-      assert (!LastPiece &&
-              "There can only be one final piece in a diagnostic.");
-      LastPiece =3D Piece;
+  BugReport::VisitorList visitors;
+  unsigned originalReportConfigToken, finalReportConfigToken;
+
+  // While generating diagnostics, it's possible the visitors will decide
+  // new symbols and regions are interesting, or add other visitors based =
on
+  // the information they find. If they do, we need to regenerate the path
+  // based on our new report configuration.
+  do {
+    // Get a clean copy of all the visitors.
+    for (BugReport::visitor_iterator I =3D R->visitor_begin(),
+                                     E =3D R->visitor_end(); I !=3D E; ++I)
+       visitors.push_back((*I)->clone());
+
+    // Clear out the active path from any previous work.
+    PD.getActivePath().clear();
+    originalReportConfigToken =3D R->getConfigurationChangeToken();
+
+    // Generate the very last diagnostic piece - the piece is visible befo=
re=20
+    // the trace is expanded.
+    PathDiagnosticPiece *LastPiece =3D 0;
+    for (BugReport::visitor_iterator I =3D visitors.begin(), E =3D visitor=
s.end();
+         I !=3D E; ++I) {
+      if (PathDiagnosticPiece *Piece =3D (*I)->getEndPath(PDB, N, *R)) {
+        assert (!LastPiece &&
+                "There can only be one final piece in a diagnostic.");
+        LastPiece =3D Piece;
+      }
     }
-  }
-  if (!LastPiece)
-    LastPiece =3D BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
-  if (LastPiece)
-    PD.push_back(LastPiece);
-  else
-    return;
+    if (!LastPiece)
+      LastPiece =3D BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
+    if (LastPiece)
+      PD.getActivePath().push_back(LastPiece);
+    else
+      return;
=20
-  switch (PDB.getGenerationScheme()) {
+    switch (PDB.getGenerationScheme()) {
     case PathDiagnosticConsumer::Extensive:
-      GenerateExtensivePathDiagnostic(PD, PDB, N);
+      GenerateExtensivePathDiagnostic(PD, PDB, N, visitors);
       break;
     case PathDiagnosticConsumer::Minimal:
-      GenerateMinimalPathDiagnostic(PD, PDB, N);
+      GenerateMinimalPathDiagnostic(PD, PDB, N, visitors);
       break;
-  }
+    }
+
+    // Clean up the visitors we used.
+    llvm::DeleteContainerPointers(visitors);
+
+    // Did anything change while generating this path?
+    finalReportConfigToken =3D R->getConfigurationChangeToken();
+  } while(finalReportConfigToken !=3D originalReportConfigToken);
+
+  // Finally, prune the diagnostic path of uninteresting stuff.
+  bool hasSomethingInteresting =3D RemoveUneededCalls(PD.getMutablePieces(=
));
+  assert(hasSomethingInteresting);
+  (void) hasSomethingInteresting;
 }
=20
 void BugReporter::Register(BugType *BT) {
@@ -1711,17 +1818,17 @@
=20
   BugReportEquivClass::iterator I =3D EQ.begin(), E =3D EQ.end();
   assert(I !=3D E);
-  BugReport *R =3D *I;
-  BugType& BT =3D R->getBugType();
+  BugType& BT =3D I->getBugType();
=20
   // If we don't need to suppress any of the nodes because they are
   // post-dominated by a sink, simply add all the nodes in the equivalence=
 class
   // to 'Nodes'.  Any of the reports will serve as a "representative" repo=
rt.
   if (!BT.isSuppressOnSink()) {
+    BugReport *R =3D I;
     for (BugReportEquivClass::iterator I=3DEQ.begin(), E=3DEQ.end(); I!=3D=
E; ++I) {
       const ExplodedNode *N =3D I->getErrorNode();
       if (N) {
-        R =3D *I;
+        R =3D I;
         bugReports.push_back(R);
       }
     }
@@ -1737,8 +1844,7 @@
   BugReport *exampleReport =3D 0;
=20
   for (; I !=3D E; ++I) {
-    R =3D *I;
-    const ExplodedNode *errorNode =3D R->getErrorNode();
+    const ExplodedNode *errorNode =3D I->getErrorNode();
=20
     if (!errorNode)
       continue;
@@ -1748,9 +1854,9 @@
     }
     // No successors?  By definition this nodes isn't post-dominated by a =
sink.
     if (errorNode->succ_empty()) {
-      bugReports.push_back(R);
+      bugReports.push_back(I);
       if (!exampleReport)
-        exampleReport =3D R;
+        exampleReport =3D I;
       continue;
     }
=20
@@ -1774,9 +1880,9 @@
         if (Succ->succ_empty()) {
           // If we found an end-of-path node that is not a sink.
           if (!Succ->isSink()) {
-            bugReports.push_back(R);
+            bugReports.push_back(I);
             if (!exampleReport)
-              exampleReport =3D R;
+              exampleReport =3D I;
             WL.clear();
             break;
           }
@@ -1857,8 +1963,9 @@
   // Probably doesn't make a difference in practice.
   BugType& BT =3D exampleReport->getBugType();
=20
-  llvm::OwningPtr<PathDiagnostic>
-    D(new PathDiagnostic(exampleReport->getBugType().getName(),
+  OwningPtr<PathDiagnostic>
+    D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
+                         exampleReport->getBugType().getName(),
                          !PD || PD->useVerboseDescription()
                          ? exampleReport->getDescription()=20
                          : exampleReport->getShortDescription(),
@@ -1866,9 +1973,6 @@
=20
   if (!bugReports.empty())
     GeneratePathDiagnostic(*D.get(), bugReports);
-
-  if (IsCachedDiagnostic(exampleReport, D.get()))
-    return;
  =20
   // Get the meta data.
   const BugReport::ExtraTextList &Meta =3D
@@ -1883,24 +1987,23 @@
   llvm::tie(Beg, End) =3D exampleReport->getRanges();
   DiagnosticsEngine &Diag =3D getDiagnostic();
  =20
-  // Search the description for '%', as that will be interpretted as a
-  // format character by FormatDiagnostics.
-  StringRef desc =3D exampleReport->getShortDescription();
-  unsigned ErrorDiag;
-  {
-    llvm::SmallString<512> TmpStr;
+  if (!IsCachedDiagnostic(exampleReport, D.get())) {
+    // Search the description for '%', as that will be interpretted as a
+    // format character by FormatDiagnostics.
+    StringRef desc =3D exampleReport->getShortDescription();
+
+    SmallString<512> TmpStr;
     llvm::raw_svector_ostream Out(TmpStr);
-    for (StringRef::iterator I=3Ddesc.begin(), E=3Ddesc.end(); I!=3DE; ++I)
+    for (StringRef::iterator I=3Ddesc.begin(), E=3Ddesc.end(); I!=3DE; ++I=
) {
       if (*I =3D=3D '%')
         Out << "%%";
       else
         Out << *I;
+    }
    =20
     Out.flush();
-    ErrorDiag =3D Diag.getCustomDiagID(DiagnosticsEngine::Warning, TmpStr);
-  }       =20
+    unsigned ErrorDiag =3D Diag.getCustomDiagID(DiagnosticsEngine::Warning=
, TmpStr);
=20
-  {
     DiagnosticBuilder diagBuilder =3D Diag.Report(
       exampleReport->getLocation(getSourceManager()).asLocation(), ErrorDi=
ag);
     for (BugReport::ranges_iterator I =3D Beg; I !=3D End; ++I)
@@ -1911,25 +2014,21 @@
   if (!PD)
     return;
=20
-  if (D->empty()) {
+  if (D->path.empty()) {
     PathDiagnosticPiece *piece =3D new PathDiagnosticEventPiece(
                                  exampleReport->getLocation(getSourceManag=
er()),
                                  exampleReport->getDescription());
+    for ( ; Beg !=3D End; ++Beg)
+      piece->addRange(*Beg);
=20
-    for ( ; Beg !=3D End; ++Beg) piece->addRange(*Beg);
-    D->push_back(piece);
+    D->getActivePath().push_back(piece);
   }
=20
   PD->HandlePathDiagnostic(D.take());
 }
=20
-void BugReporter::EmitBasicReport(StringRef name, StringRef str,
-                                  PathDiagnosticLocation Loc,
-                                  SourceRange* RBeg, unsigned NumRanges) {
-  EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
-}
-
-void BugReporter::EmitBasicReport(StringRef name,
+void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
+                                  StringRef name,
                                   StringRef category,
                                   StringRef str, PathDiagnosticLocation Lo=
c,
                                   SourceRange* RBeg, unsigned NumRanges) {
@@ -1937,13 +2036,14 @@
   // 'BT' is owned by BugReporter.
   BugType *BT =3D getBugTypeForName(name, category);
   BugReport *R =3D new BugReport(*BT, str, Loc);
+  R->setDeclWithIssue(DeclWithIssue);
   for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
   EmitReport(R);
 }
=20
 BugType *BugReporter::getBugTypeForName(StringRef name,
                                         StringRef category) {
-  llvm::SmallString<136> fullDesc;
+  SmallString<136> fullDesc;
   llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
   llvm::StringMapEntry<BugType *> &
       entry =3D StrBugTypes.GetOrCreateValue(fullDesc);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/BugReporterVisitors.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisi=
tors.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/BugReporterVisi=
tors.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
+#include "llvm/ADT/SmallString.h"
=20
 using namespace clang;
 using namespace ento;
@@ -84,26 +85,8 @@
 BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
                                       const ExplodedNode *EndPathNode,
                                       BugReport &BR) {
-  const ProgramPoint &PP =3D EndPathNode->getLocation();
-  PathDiagnosticLocation L;
-
-  if (const BlockEntrance *BE =3D dyn_cast<BlockEntrance>(&PP)) {
-    const CFGBlock *block =3D BE->getBlock();
-    if (block->getBlockID() =3D=3D 0) {
-      L =3D PathDiagnosticLocation::createDeclEnd(PP.getLocationContext(),
-                                                BRC.getSourceManager());
-    }
-  }
-
-  if (!L.isValid()) {
-    const Stmt *S =3D BR.getStmt();
-
-    if (!S)
-      return NULL;
-
-    L =3D PathDiagnosticLocation(S, BRC.getSourceManager(),
-                                  PP.getLocationContext());
-  }
+  PathDiagnosticLocation L =3D
+    PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManag=
er());
=20
   BugReport::ranges_iterator Beg, End;
   llvm::tie(Beg, End) =3D BR.getRanges();
@@ -138,17 +121,20 @@
   if (!StoreSite) {
     const ExplodedNode *Node =3D N, *Last =3D NULL;
=20
-    for ( ; Node ; Last =3D Node, Node =3D Node->getFirstPred()) {
+    for ( ; Node ; Node =3D Node->getFirstPred()) {
=20
       if (const VarRegion *VR =3D dyn_cast<VarRegion>(R)) {
         if (const PostStmt *P =3D Node->getLocationAs<PostStmt>())
           if (const DeclStmt *DS =3D P->getStmtAs<DeclStmt>())
             if (DS->getSingleDecl() =3D=3D VR->getDecl()) {
+              // Record the last seen initialization point.
               Last =3D Node;
               break;
             }
       }
=20
+      // Does the region still bind to value V?  If not, we are done
+      // looking for store sites.
       if (Node->getState()->getSVal(R) !=3D V)
         break;
     }
@@ -165,7 +151,7 @@
     return NULL;
=20
   satisfied =3D true;
-  llvm::SmallString<256> sbuf;
+  SmallString<256> sbuf;
   llvm::raw_svector_ostream os(sbuf);
=20
   if (const PostStmt *PS =3D N->getLocationAs<PostStmt>()) {
@@ -301,7 +287,8 @@
=20
 BugReporterVisitor *
 bugreporter::getTrackNullOrUndefValueVisitor(const ExplodedNode *N,
-                                             const Stmt *S) {
+                                             const Stmt *S,
+                                             BugReport *report) {
   if (!S || !N)
     return 0;
=20
@@ -321,25 +308,27 @@
   if (!N)
     return 0;
  =20
-  const ProgramState *state =3D N->getState();
+  ProgramStateRef state =3D N->getState();
=20
-  // Walk through lvalue-to-rvalue conversions. =20
-  if (const DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(S)) {
-    if (const VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl())) {
-      const VarRegion *R =3D
-        StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext=
());
+  // Walk through lvalue-to-rvalue conversions.
+  const Expr *Ex =3D dyn_cast<Expr>(S);
+  if (Ex) {
+    Ex =3D Ex->IgnoreParenLValueCasts();
+    if (const DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(Ex)) {
+      if (const VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl())) {
+        const VarRegion *R =3D
+          StateMgr.getRegionManager().getVarRegion(VD, N->getLocationConte=
xt());
=20
-      // What did we load?
-      SVal V =3D state->getSVal(loc::MemRegionVal(R));
-
-      if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)
-          || V.isUndef()) {
+        // What did we load?
+        SVal V =3D state->getSVal(loc::MemRegionVal(R));
+        report->markInteresting(R);
+        report->markInteresting(V);
         return new FindLastStoreBRVisitor(V, R);
       }
     }
   }
=20
-  SVal V =3D state->getSValAsScalarOrLoc(S);
+  SVal V =3D state->getSValAsScalarOrLoc(S, N->getLocationContext());
=20
   // Uncomment this to find cases where we aren't properly getting the
   // base value that was dereferenced.
@@ -353,7 +342,7 @@
     }
=20
     if (R) {
-      assert(isa<SymbolicRegion>(R));
+      report->markInteresting(R);
       return new TrackConstraintBRVisitor(loc::MemRegionVal(R), false);
     }
   }
@@ -366,7 +355,7 @@
                                             const MemRegion *R) {
   assert(R && "The memory region is null.");
=20
-  const ProgramState *state =3D N->getState();
+  ProgramStateRef state =3D N->getState();
   SVal V =3D state->getSVal(R);
   if (V.isUnknown())
     return 0;
@@ -388,8 +377,8 @@
   const Expr *Receiver =3D ME->getInstanceReceiver();
   if (!Receiver)
     return 0;
-  const ProgramState *state =3D N->getState();
-  const SVal &V =3D state->getSVal(Receiver);
+  ProgramStateRef state =3D N->getState();
+  const SVal &V =3D state->getSVal(Receiver, N->getLocationContext());
   const DefinedOrUnknownSVal *DV =3D dyn_cast<DefinedOrUnknownSVal>(&V);
   if (!DV)
     return 0;
@@ -400,11 +389,11 @@
   // The receiver was nil, and hence the method was skipped.
   // Register a BugReporterVisitor to issue a message telling us how
   // the receiver was null.
-  BR.addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, Receiver));
+  BR.addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, Receiver, =
&BR));
   // Issue a message saying that the method was skipped.
   PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
                                      N->getLocationContext());
-  return new PathDiagnosticEventPiece(L, "No method actually called "
+  return new PathDiagnosticEventPiece(L, "No method is called "
       "because the receiver is nil");
 }
=20
@@ -419,7 +408,7 @@
     const Stmt *Head =3D WorkList.front();
     WorkList.pop_front();
=20
-    const ProgramState *state =3D N->getState();
+    ProgramStateRef state =3D N->getState();
     ProgramStateManager &StateMgr =3D state->getStateManager();
=20
     if (const DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(Head)) {
@@ -428,7 +417,7 @@
         StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext=
());
=20
         // What did we load?
-        SVal V =3D state->getSVal(S);
+        SVal V =3D state->getSVal(S, N->getLocationContext());
=20
         if (isa<loc::ConcreteInt>(V) || isa<nonloc::ConcreteInt>(V)) {
           // Register a new visitor with the BugReport.
@@ -450,11 +439,22 @@
                                                    const ExplodedNode *Pre=
v,
                                                    BugReporterContext &BRC,
                                                    BugReport &BR) {
+  PathDiagnosticPiece *piece =3D VisitNodeImpl(N, Prev, BRC, BR);
+  if (PathDiagnosticEventPiece *ev =3D
+      dyn_cast_or_null<PathDiagnosticEventPiece>(piece))
+    ev->setPrunable(true, /* override */ false);
+  return piece;
+}
+
+PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode =
*N,
+                                                       const ExplodedNode =
*Prev,
+                                                       BugReporterContext =
&BRC,
+                                                       BugReport &BR) {
  =20
   const ProgramPoint &progPoint =3D N->getLocation();
=20
-  const ProgramState *CurrentState =3D N->getState();
-  const ProgramState *PrevState =3D Prev->getState();
+  ProgramStateRef CurrentState =3D N->getState();
+  ProgramStateRef PrevState =3D Prev->getState();
  =20
   // Compare the GDMs of the state, because that is where constraints
   // are managed.  Note that ensure that we only look at nodes that
@@ -468,7 +468,7 @@
   if (const BlockEdge *BE =3D dyn_cast<BlockEdge>(&progPoint)) {
     const CFGBlock *srcBlk =3D BE->getSrc();   =20
     if (const Stmt *term =3D srcBlk->getTerminator())
-      return VisitTerminator(term, N, srcBlk, BE->getDst(), BRC);
+      return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
     return 0;
   }
  =20
@@ -482,10 +482,10 @@
     const ProgramPointTag *tag =3D PS->getTag();
     if (tag =3D=3D tags.first)
       return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
-                           BRC, N->getLocationContext());
+                           BRC, BR, N);
     if (tag =3D=3D tags.second)
       return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
-                           BRC, N->getLocationContext());
+                           BRC, BR, N);
                           =20
     return 0;
   }
@@ -498,6 +498,7 @@
                                     const ExplodedNode *N,
                                     const CFGBlock *srcBlk,
                                     const CFGBlock *dstBlk,
+                                    BugReport &R,
                                     BugReporterContext &BRC) {
   const Expr *Cond =3D 0;
  =20
@@ -516,14 +517,15 @@
   assert(srcBlk->succ_size() =3D=3D 2);
   const bool tookTrue =3D *(srcBlk->succ_begin()) =3D=3D dstBlk;
   return VisitTrueTest(Cond->IgnoreParenNoopCasts(BRC.getASTContext()),
-                       tookTrue, BRC, N->getLocationContext());
+                       tookTrue, BRC, R, N);
 }
=20
 PathDiagnosticPiece *
 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
                                   bool tookTrue,
                                   BugReporterContext &BRC,
-                                  const LocationContext *LC) {
+                                  BugReport &R,
+                                  const ExplodedNode *N) {
  =20
   const Expr *Ex =3D Cond;
  =20
@@ -533,9 +535,11 @@
       default:
         return 0;
       case Stmt::BinaryOperatorClass:
-        return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC=
, LC);
+        return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
+                             R, N);
       case Stmt::DeclRefExprClass:
-        return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC, L=
C);
+        return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
+                             R, N);
       case Stmt::UnaryOperatorClass: {
         const UnaryOperator *UO =3D cast<UnaryOperator>(Ex);
         if (UO->getOpcode() =3D=3D UO_LNot) {
@@ -550,14 +554,31 @@
 }
=20
 bool ConditionBRVisitor::patternMatch(const Expr *Ex, llvm::raw_ostream &O=
ut,
-                                      BugReporterContext &BRC) {
+                                      BugReporterContext &BRC,
+                                      BugReport &report,
+                                      const ExplodedNode *N,
+                                      llvm::Optional<bool> &prunable) {
   const Expr *OriginalExpr =3D Ex;
   Ex =3D Ex->IgnoreParenCasts();
=20
   if (const DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(Ex)) {
     const bool quotes =3D isa<VarDecl>(DR->getDecl());
-    if (quotes)
+    if (quotes) {
       Out << '\'';
+      const LocationContext *LCtx =3D N->getLocationContext();
+      const ProgramState *state =3D N->getState().getPtr();
+      if (const MemRegion *R =3D state->getLValue(cast<VarDecl>(DR->getDec=
l()),
+                                                LCtx).getAsRegion()) {
+        if (report.isInteresting(R))
+          prunable =3D false;
+        else {
+          const ProgramState *state =3D N->getState().getPtr();
+          SVal V =3D state->getSVal(R);
+          if (report.isInteresting(V))
+            prunable =3D false;
+        }
+      }
+    }
     Out << DR->getDecl()->getDeclName().getAsString();
     if (quotes)
       Out << '\'';
@@ -591,31 +612,43 @@
                                   const BinaryOperator *BExpr,
                                   const bool tookTrue,
                                   BugReporterContext &BRC,
-                                  const LocationContext *LC) {
+                                  BugReport &R,
+                                  const ExplodedNode *N) {
  =20
   bool shouldInvert =3D false;
+  llvm::Optional<bool> shouldPrune;
  =20
-  llvm::SmallString<128> LhsString, RhsString;
+  SmallString<128> LhsString, RhsString;
   {
-    llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString); =20
-    const bool isVarLHS =3D patternMatch(BExpr->getLHS(), OutLHS, BRC);
-    const bool isVarRHS =3D patternMatch(BExpr->getRHS(), OutRHS, BRC);
+    llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
+    const bool isVarLHS =3D patternMatch(BExpr->getLHS(), OutLHS, BRC, R, =
N,
+                                       shouldPrune);
+    const bool isVarRHS =3D patternMatch(BExpr->getRHS(), OutRHS, BRC, R, =
N,
+                                       shouldPrune);
    =20
     shouldInvert =3D !isVarLHS && isVarRHS;   =20
   }
  =20
+  BinaryOperator::Opcode Op =3D BExpr->getOpcode();
+
+  if (BinaryOperator::isAssignmentOp(Op)) {
+    // For assignment operators, all that we care about is that the LHS
+    // evaluates to "true" or "false".
+    return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
+                                  BRC, R, N);
+  }
+
+  // For non-assignment operations, we require that we can understand
+  // both the LHS and RHS.
   if (LhsString.empty() || RhsString.empty())
     return 0;
-
+ =20
   // Should we invert the strings if the LHS is not a variable name?
- =20
-  llvm::SmallString<256> buf;
+  SmallString<256> buf;
   llvm::raw_svector_ostream Out(buf);
   Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
=20
   // Do we need to invert the opcode?
-  BinaryOperator::Opcode Op =3D BExpr->getOpcode();
-   =20
   if (shouldInvert)
     switch (Op) {
       default: break;
@@ -637,7 +670,7 @@
         return 0;
     }
  =20
-  switch (BExpr->getOpcode()) {
+  switch (Op) {
     case BO_EQ:
       Out << "equal to ";
       break;
@@ -650,9 +683,55 @@
   }
  =20
   Out << (shouldInvert ? LhsString : RhsString);
+  const LocationContext *LCtx =3D N->getLocationContext();
+  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
+  PathDiagnosticEventPiece *event =3D
+    new PathDiagnosticEventPiece(Loc, Out.str());
+  if (shouldPrune.hasValue())
+    event->setPrunable(shouldPrune.getValue());
+  return event;
+}
=20
-  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LC);
-  return new PathDiagnosticEventPiece(Loc, Out.str());
+PathDiagnosticPiece *
+ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
+                                           const Expr *CondVarExpr,
+                                           const bool tookTrue,
+                                           BugReporterContext &BRC,
+                                           BugReport &report,
+                                           const ExplodedNode *N) {
+  SmallString<256> buf;
+  llvm::raw_svector_ostream Out(buf);
+  Out << "Assuming " << LhsString << " is ";
+ =20
+  QualType Ty =3D CondVarExpr->getType();
+
+  if (Ty->isPointerType())
+    Out << (tookTrue ? "not null" : "null");
+  else if (Ty->isObjCObjectPointerType())
+    Out << (tookTrue ? "not nil" : "nil");
+  else if (Ty->isBooleanType())
+    Out << (tookTrue ? "true" : "false");
+  else if (Ty->isIntegerType())
+    Out << (tookTrue ? "non-zero" : "zero");
+  else
+    return 0;
+
+  const LocationContext *LCtx =3D N->getLocationContext();
+  PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
+  PathDiagnosticEventPiece *event =3D
+    new PathDiagnosticEventPiece(Loc, Out.str());
+
+  if (const DeclRefExpr *DR =3D dyn_cast<DeclRefExpr>(CondVarExpr)) {
+    if (const VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl())) {
+      const ProgramState *state =3D N->getState().getPtr();
+      if (const MemRegion *R =3D state->getLValue(VD, LCtx).getAsRegion())=
 {
+        if (report.isInteresting(R))
+          event->setPrunable(false);
+      }
+    }
+  }
+ =20
+  return event;
 }
  =20
 PathDiagnosticPiece *
@@ -660,13 +739,14 @@
                                   const DeclRefExpr *DR,
                                   const bool tookTrue,
                                   BugReporterContext &BRC,
-                                  const LocationContext *LC) {
+                                  BugReport &report,
+                                  const ExplodedNode *N) {
=20
   const VarDecl *VD =3D dyn_cast<VarDecl>(DR->getDecl());
   if (!VD)
     return 0;
  =20
-  llvm::SmallString<256> Buf;
+  SmallString<256> Buf;
   llvm::raw_svector_ostream Out(Buf);
    =20
   Out << "Assuming '";
@@ -684,6 +764,21 @@
   else
     return 0;
  =20
-  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LC);
-  return new PathDiagnosticEventPiece(Loc, Out.str());
+  const LocationContext *LCtx =3D N->getLocationContext();
+  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
+  PathDiagnosticEventPiece *event =3D
+    new PathDiagnosticEventPiece(Loc, Out.str());
+ =20
+  const ProgramState *state =3D N->getState().getPtr();
+  if (const MemRegion *R =3D state->getLValue(VD, LCtx).getAsRegion()) {
+    if (report.isInteresting(R))
+      event->setPrunable(false);
+    else {
+      SVal V =3D state->getSVal(R);
+      if (report.isInteresting(V))
+        event->setPrunable(false);
+    }
+  }
+  return event;
 }
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/Checker.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Checker.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Checker.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -11,6 +11,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
=20
 using namespace clang;
@@ -20,3 +21,11 @@
   // FIXME: We want to return the package + name of the checker here.
   return "A Checker"; =20
 }
+
+void Checker<check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
+             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
+             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
+             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
+             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck,
+             check::_VoidCheck, check::_VoidCheck, check::_VoidCheck
+             >::anchor() { }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/CheckerContext.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerContext.=
cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerContext.=
cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -13,21 +13,71 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/Basic/Builtins.h"
+#include "clang/Lex/Lexer.h"
+
 using namespace clang;
 using namespace ento;
=20
-CheckerContext::~CheckerContext() {
-  // Do we need to autotransition?  'Dst' can get populated in a variety of
-  // ways, including 'addTransition()' adding the predecessor node to Dst
-  // without actually generated a new node.  We also shouldn't autotransit=
ion
-  // if we are building sinks or we generated a node and decided to not
-  // add it as a transition.
-  if (Dst.size() =3D=3D size && !B.BuildSinks && !B.hasGeneratedNode) {
-    if (ST && ST !=3D Pred->getState()) {
-      static SimpleProgramPointTag autoTransitionTag("CheckerContext : aut=
o");
-      addTransition(ST, &autoTransitionTag);
-    }
-    else
-      Dst.Add(Pred);
+const FunctionDecl *CheckerContext::getCalleeDecl(const CallExpr *CE) cons=
t {
+  ProgramStateRef State =3D getState();
+  const Expr *Callee =3D CE->getCallee();
+  SVal L =3D State->getSVal(Callee, Pred->getLocationContext());
+  return L.getAsFunctionDecl();
+}
+
+StringRef CheckerContext::getCalleeName(const FunctionDecl *FunDecl) const=
 {
+  if (!FunDecl)
+    return StringRef();
+  IdentifierInfo *funI =3D FunDecl->getIdentifier();
+  if (!funI)
+    return StringRef();
+  return funI->getName();
+}
+
+
+bool CheckerContext::isCLibraryFunction(const FunctionDecl *FD,
+                                        StringRef Name) {
+  return isCLibraryFunction(FD, Name, getASTContext());
+}
+
+bool CheckerContext::isCLibraryFunction(const FunctionDecl *FD,
+                                        StringRef Name, ASTContext &Contex=
t) {
+  // To avoid false positives (Ex: finding user defined functions with
+  // similar names), only perform fuzzy name matching when it's a builtin.
+  // Using a string compare is slow, we might want to switch on BuiltinID =
here.
+  unsigned BId =3D FD->getBuiltinID();
+  if (BId !=3D 0) {
+    StringRef BName =3D Context.BuiltinInfo.GetName(BId);
+    if (BName.find(Name) !=3D StringRef::npos)
+      return true;
   }
+
+  const IdentifierInfo *II =3D FD->getIdentifier();
+  // If this is a special C++ name without IdentifierInfo, it can't be a
+  // C library function.
+  if (!II)
+    return false;
+
+  StringRef FName =3D II->getName();
+  if (FName.equals(Name))
+    return true;
+
+  if (FName.startswith("__inline") && (FName.find(Name) !=3D StringRef::np=
os))
+    return true;
+
+  if (FName.startswith("__") && FName.endswith("_chk") &&
+      FName.find(Name) !=3D StringRef::npos)
+    return true;
+
+  return false;
 }
+
+StringRef CheckerContext::getMacroNameOrSpelling(SourceLocation &Loc) {
+  if (Loc.isMacroID())
+    return Lexer::getImmediateMacroName(Loc, getSourceManager(),
+                                             getLangOpts());
+  SmallVector<char, 16> buf;
+  return Lexer::getSpelling(Loc, buf, getSourceManager(), getLangOpts());
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/CheckerManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.=
cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerManager.=
cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -93,6 +93,9 @@
 static void expandGraphWithCheckers(CHECK_CTX checkCtx,
                                     ExplodedNodeSet &Dst,
                                     const ExplodedNodeSet &Src) {
+  const NodeBuilderContext &BldrCtx =3D checkCtx.Eng.getBuilderContext();
+  if (Src.empty())
+    return;
=20
   typename CHECK_CTX::CheckersTy::const_iterator
       I =3D checkCtx.checkers_begin(), E =3D checkCtx.checkers_end();
@@ -113,9 +116,15 @@
       CurrSet->clear();
     }
=20
+    NodeBuilder B(*PrevSet, *CurrSet, BldrCtx);
     for (ExplodedNodeSet::iterator NI =3D PrevSet->begin(), NE =3D PrevSet=
->end();
-         NI !=3D NE; ++NI)
-      checkCtx.runChecker(*I, *CurrSet, *NI);
+         NI !=3D NE; ++NI) {
+      checkCtx.runChecker(*I, B, *NI);
+    }
+
+    // If all the produced transitions are sinks, stop.
+    if (CurrSet->empty())
+      return;
=20
     // Update which NodeSet is the current one.
     PrevSet =3D CurrSet;
@@ -129,23 +138,24 @@
     const CheckersTy &Checkers;
     const Stmt *S;
     ExprEngine &Eng;
+    bool wasInlined;
=20
     CheckersTy::const_iterator checkers_begin() { return Checkers.begin();=
 }
     CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
=20
     CheckStmtContext(bool isPreVisit, const CheckersTy &checkers,
-                     const Stmt *s, ExprEngine &eng)
-      : IsPreVisit(isPreVisit), Checkers(checkers), S(s), Eng(eng) { }
+                     const Stmt *s, ExprEngine &eng, bool wasInlined =3D f=
alse)
+      : IsPreVisit(isPreVisit), Checkers(checkers), S(s), Eng(eng),
+        wasInlined(wasInlined) {}
=20
     void runChecker(CheckerManager::CheckStmtFunc checkFn,
-                    ExplodedNodeSet &Dst, ExplodedNode *Pred) {
+                    NodeBuilder &Bldr, ExplodedNode *Pred) {
       // FIXME: Remove respondsToCallback from CheckerContext;
       ProgramPoint::Kind K =3D  IsPreVisit ? ProgramPoint::PreStmtKind :
                                            ProgramPoint::PostStmtKind;
       const ProgramPoint &L =3D ProgramPoint::getProgramPoint(S, K,
                                 Pred->getLocationContext(), checkFn.Checke=
r);
-      CheckerContext C(Dst, Eng.getBuilder(), Eng, Pred, L, 0);
-
+      CheckerContext C(Bldr, Eng, Pred, L, wasInlined);
       checkFn(S, C);
     }
   };
@@ -156,9 +166,10 @@
                                         ExplodedNodeSet &Dst,
                                         const ExplodedNodeSet &Src,
                                         const Stmt *S,
-                                        ExprEngine &Eng) {
+                                        ExprEngine &Eng,
+                                        bool wasInlined) {
   CheckStmtContext C(isPreVisit, *getCachedStmtCheckersFor(S, isPreVisit),
-                     S, Eng);
+                     S, Eng, wasInlined);
   expandGraphWithCheckers(C, Dst, Src);
 }
=20
@@ -178,12 +189,14 @@
       : IsPreVisit(isPreVisit), Checkers(checkers), Msg(msg), Eng(eng) { }
=20
     void runChecker(CheckerManager::CheckObjCMessageFunc checkFn,
-                    ExplodedNodeSet &Dst, ExplodedNode *Pred) {
+                    NodeBuilder &Bldr, ExplodedNode *Pred) {
       ProgramPoint::Kind K =3D  IsPreVisit ? ProgramPoint::PreStmtKind :
                                            ProgramPoint::PostStmtKind;
-      const ProgramPoint &L =3D ProgramPoint::getProgramPoint(Msg.getOrigi=
nExpr(),
-                                K, Pred->getLocationContext(), checkFn.Che=
cker);
-      CheckerContext C(Dst, Eng.getBuilder(), Eng, Pred, L, 0);
+      const ProgramPoint &L =3D
+        ProgramPoint::getProgramPoint(Msg.getMessageExpr(),
+                                      K, Pred->getLocationContext(),
+                                      checkFn.Checker);
+      CheckerContext C(Bldr, Eng, Pred, L);
=20
       checkFn(Msg, C);
     }
@@ -209,35 +222,44 @@
     const CheckersTy &Checkers;
     SVal Loc;
     bool IsLoad;
-    const Stmt *S;
+    const Stmt *NodeEx; /* Will become a CFGStmt */
+    const Stmt *BoundEx;
     ExprEngine &Eng;
=20
     CheckersTy::const_iterator checkers_begin() { return Checkers.begin();=
 }
     CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
=20
     CheckLocationContext(const CheckersTy &checkers,
-                         SVal loc, bool isLoad, const Stmt *s, ExprEngine =
&eng)
-      : Checkers(checkers), Loc(loc), IsLoad(isLoad), S(s), Eng(eng) { }
+                         SVal loc, bool isLoad, const Stmt *NodeEx,
+                         const Stmt *BoundEx,
+                         ExprEngine &eng)
+      : Checkers(checkers), Loc(loc), IsLoad(isLoad), NodeEx(NodeEx),
+        BoundEx(BoundEx), Eng(eng) {}
=20
     void runChecker(CheckerManager::CheckLocationFunc checkFn,
-                    ExplodedNodeSet &Dst, ExplodedNode *Pred) {
+                    NodeBuilder &Bldr, ExplodedNode *Pred) {
       ProgramPoint::Kind K =3D  IsLoad ? ProgramPoint::PreLoadKind :
                                        ProgramPoint::PreStoreKind;
-      const ProgramPoint &L =3D ProgramPoint::getProgramPoint(S, K,
-                                Pred->getLocationContext(), checkFn.Checke=
r);
-      CheckerContext C(Dst, Eng.getBuilder(), Eng, Pred, L, 0);
-
-      checkFn(Loc, IsLoad, S, C);
+      const ProgramPoint &L =3D
+        ProgramPoint::getProgramPoint(NodeEx, K,
+                                      Pred->getLocationContext(),
+                                      checkFn.Checker);
+      CheckerContext C(Bldr, Eng, Pred, L);
+      checkFn(Loc, IsLoad, BoundEx, C);
     }
   };
 }
=20
 /// \brief Run checkers for load/store of a location.
+
 void CheckerManager::runCheckersForLocation(ExplodedNodeSet &Dst,
                                             const ExplodedNodeSet &Src,
                                             SVal location, bool isLoad,
-                                            const Stmt *S, ExprEngine &Eng=
) {
-  CheckLocationContext C(LocationCheckers, location, isLoad, S, Eng);
+                                            const Stmt *NodeEx,
+                                            const Stmt *BoundEx,
+                                            ExprEngine &Eng) {
+  CheckLocationContext C(LocationCheckers, location, isLoad, NodeEx,
+                         BoundEx, Eng);
   expandGraphWithCheckers(C, Dst, Src);
 }
=20
@@ -249,20 +271,21 @@
     SVal Val;
     const Stmt *S;
     ExprEngine &Eng;
+    ProgramPoint::Kind PointKind;
=20
     CheckersTy::const_iterator checkers_begin() { return Checkers.begin();=
 }
     CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
=20
     CheckBindContext(const CheckersTy &checkers,
-                     SVal loc, SVal val, const Stmt *s, ExprEngine &eng)
-      : Checkers(checkers), Loc(loc), Val(val), S(s), Eng(eng) { }
+                     SVal loc, SVal val, const Stmt *s, ExprEngine &eng,
+                     ProgramPoint::Kind PK)
+      : Checkers(checkers), Loc(loc), Val(val), S(s), Eng(eng), PointKind(=
PK) {}
=20
     void runChecker(CheckerManager::CheckBindFunc checkFn,
-                    ExplodedNodeSet &Dst, ExplodedNode *Pred) {
-      ProgramPoint::Kind K =3D  ProgramPoint::PreStmtKind;
-      const ProgramPoint &L =3D ProgramPoint::getProgramPoint(S, K,
+                    NodeBuilder &Bldr, ExplodedNode *Pred) {
+      const ProgramPoint &L =3D ProgramPoint::getProgramPoint(S, PointKind,
                                 Pred->getLocationContext(), checkFn.Checke=
r);
-      CheckerContext C(Dst, Eng.getBuilder(), Eng, Pred, L, 0);
+      CheckerContext C(Bldr, Eng, Pred, L);
=20
       checkFn(Loc, Val, S, C);
     }
@@ -273,8 +296,9 @@
 void CheckerManager::runCheckersForBind(ExplodedNodeSet &Dst,
                                         const ExplodedNodeSet &Src,
                                         SVal location, SVal val,
-                                        const Stmt *S, ExprEngine &Eng) {
-  CheckBindContext C(BindCheckers, location, val, S, Eng);
+                                        const Stmt *S, ExprEngine &Eng,
+                                        ProgramPoint::Kind PointKind) {
+  CheckBindContext C(BindCheckers, location, val, S, Eng, PointKind);
   expandGraphWithCheckers(C, Dst, Src);
 }
=20
@@ -286,27 +310,65 @@
 }
=20
 /// \brief Run checkers for end of path.
-void CheckerManager::runCheckersForEndPath(EndOfFunctionNodeBuilder &B,
+// Note, We do not chain the checker output (like in expandGraphWithChecke=
rs)
+// for this callback since end of path nodes are expected to be final.
+void CheckerManager::runCheckersForEndPath(NodeBuilderContext &BC,
+                                           ExplodedNodeSet &Dst,
                                            ExprEngine &Eng) {
+  ExplodedNode *Pred =3D BC.Pred;
+ =20
+  // We define the builder outside of the loop bacause if at least one che=
ckers
+  // creates a sucsessor for Pred, we do not need to generate an=20
+  // autotransition for it.
+  NodeBuilder Bldr(Pred, Dst, BC);
   for (unsigned i =3D 0, e =3D EndPathCheckers.size(); i !=3D e; ++i) {
-    CheckEndPathFunc fn =3D EndPathCheckers[i];
-    EndOfFunctionNodeBuilder specialB =3D B.withCheckerTag(fn.Checker);
-    fn(specialB, Eng);
+    CheckEndPathFunc checkFn =3D EndPathCheckers[i];
+
+    const ProgramPoint &L =3D BlockEntrance(BC.Block,
+                                          Pred->getLocationContext(),
+                                          checkFn.Checker);
+    CheckerContext C(Bldr, Eng, Pred, L);
+    checkFn(C);
   }
 }
=20
+namespace {
+  struct CheckBranchConditionContext {
+    typedef std::vector<CheckerManager::CheckBranchConditionFunc> Checkers=
Ty;
+    const CheckersTy &Checkers;
+    const Stmt *Condition;
+    ExprEngine &Eng;
+
+    CheckersTy::const_iterator checkers_begin() { return Checkers.begin();=
 }
+    CheckersTy::const_iterator checkers_end() { return Checkers.end(); }
+
+    CheckBranchConditionContext(const CheckersTy &checkers,
+                                const Stmt *Cond, ExprEngine &eng)
+      : Checkers(checkers), Condition(Cond), Eng(eng) {}
+
+    void runChecker(CheckerManager::CheckBranchConditionFunc checkFn,
+                    NodeBuilder &Bldr, ExplodedNode *Pred) {
+      ProgramPoint L =3D PostCondition(Condition, Pred->getLocationContext=
(),
+                                     checkFn.Checker);
+      CheckerContext C(Bldr, Eng, Pred, L);
+      checkFn(Condition, C);
+    }
+  };
+}
+
 /// \brief Run checkers for branch condition.
-void CheckerManager::runCheckersForBranchCondition(const Stmt *condition,
-                                                   BranchNodeBuilder &B,
+void CheckerManager::runCheckersForBranchCondition(const Stmt *Condition,
+                                                   ExplodedNodeSet &Dst,
+                                                   ExplodedNode *Pred,
                                                    ExprEngine &Eng) {
-  for (unsigned i =3D 0, e =3D BranchConditionCheckers.size(); i !=3D e; +=
+i) {
-    CheckBranchConditionFunc fn =3D BranchConditionCheckers[i];
-    fn(condition, B, Eng);
-  }
+  ExplodedNodeSet Src;
+  Src.insert(Pred);
+  CheckBranchConditionContext C(BranchConditionCheckers, Condition, Eng);
+  expandGraphWithCheckers(C, Dst, Src);
 }
=20
 /// \brief Run checkers for live symbols.
-void CheckerManager::runCheckersForLiveSymbols(const ProgramState *state,
+void CheckerManager::runCheckersForLiveSymbols(ProgramStateRef state,
                                                SymbolReaper &SymReaper) {
   for (unsigned i =3D 0, e =3D LiveSymbolsCheckers.size(); i !=3D e; ++i)
     LiveSymbolsCheckers[i](state, SymReaper);
@@ -328,11 +390,11 @@
       : Checkers(checkers), SR(sr), S(s), Eng(eng) { }
=20
     void runChecker(CheckerManager::CheckDeadSymbolsFunc checkFn,
-                    ExplodedNodeSet &Dst, ExplodedNode *Pred) {
+                    NodeBuilder &Bldr, ExplodedNode *Pred) {
       ProgramPoint::Kind K =3D ProgramPoint::PostPurgeDeadSymbolsKind;
       const ProgramPoint &L =3D ProgramPoint::getProgramPoint(S, K,
                                 Pred->getLocationContext(), checkFn.Checke=
r);
-      CheckerContext C(Dst, Eng.getBuilder(), Eng, Pred, L, 0);
+      CheckerContext C(Bldr, Eng, Pred, L);
=20
       checkFn(SR, C);
     }
@@ -350,7 +412,7 @@
 }
=20
 /// \brief True if at least one checker wants to check region changes.
-bool CheckerManager::wantsRegionChangeUpdate(const ProgramState *state) {
+bool CheckerManager::wantsRegionChangeUpdate(ProgramStateRef state) {
   for (unsigned i =3D 0, e =3D RegionChangesCheckers.size(); i !=3D e; ++i)
     if (RegionChangesCheckers[i].WantUpdateFn(state))
       return true;
@@ -359,25 +421,26 @@
 }
=20
 /// \brief Run checkers for region changes.
-const ProgramState *
-CheckerManager::runCheckersForRegionChanges(const ProgramState *state,
+ProgramStateRef=20
+CheckerManager::runCheckersForRegionChanges(ProgramStateRef state,
                             const StoreManager::InvalidatedSymbols *invali=
dated,
                                     ArrayRef<const MemRegion *> ExplicitRe=
gions,
-                                          ArrayRef<const MemRegion *> Regi=
ons) {
+                                          ArrayRef<const MemRegion *> Regi=
ons,
+                                          const CallOrObjCMessage *Call) {
   for (unsigned i =3D 0, e =3D RegionChangesCheckers.size(); i !=3D e; ++i=
) {
     // If any checker declares the state infeasible (or if it starts that =
way),
     // bail out.
     if (!state)
       return NULL;
     state =3D RegionChangesCheckers[i].CheckFn(state, invalidated,=20
-                                             ExplicitRegions, Regions);
+                                             ExplicitRegions, Regions, Cal=
l);
   }
   return state;
 }
=20
 /// \brief Run checkers for handling assumptions on symbolic values.
-const ProgramState *
-CheckerManager::runCheckersForEvalAssume(const ProgramState *state,
+ProgramStateRef=20
+CheckerManager::runCheckersForEvalAssume(ProgramStateRef state,
                                          SVal Cond, bool Assumption) {
   for (unsigned i =3D 0, e =3D EvalAssumeCheckers.size(); i !=3D e; ++i) {
     // If any checker declares the state infeasible (or if it starts that =
way),
@@ -437,11 +500,12 @@
     }
 #endif
=20
+    ExplodedNodeSet checkDst;
+    NodeBuilder B(Pred, checkDst, Eng.getBuilderContext());
     // Next, check if any of the EvalCall callbacks can evaluate the call.
     for (std::vector<EvalCallFunc>::iterator
            EI =3D EvalCallCheckers.begin(), EE =3D EvalCallCheckers.end();
          EI !=3D EE; ++EI) {
-      ExplodedNodeSet checkDst;
       ProgramPoint::Kind K =3D ProgramPoint::PostStmtKind;
       const ProgramPoint &L =3D ProgramPoint::getProgramPoint(CE, K,
                                 Pred->getLocationContext(), EI->Checker);
@@ -449,7 +513,7 @@
       { // CheckerContext generates transitions(populates checkDest) on
         // destruction, so introduce the scope to make sure it gets proper=
ly
         // populated.
-        CheckerContext C(checkDst, Eng.getBuilder(), Eng, Pred, L, 0);
+        CheckerContext C(B, Eng, Pred, L);
         evaluated =3D (*EI)(CE, C);
       }
       assert(!(evaluated && anyEvaluated)
@@ -483,7 +547,7 @@
 }
=20
 void CheckerManager::runCheckersForPrintState(raw_ostream &Out,
-                                              const ProgramState *State,
+                                              ProgramStateRef State,
                                               const char *NL, const char *=
Sep) {
   for (llvm::DenseMap<CheckerTag, CheckerRef>::iterator
         I =3D CheckerTags.begin(), E =3D CheckerTags.end(); I !=3D E; ++I)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/CheckerRegistry.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerRegistry=
.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CheckerRegistry=
.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -9,12 +9,13 @@
=20
 #include "clang/StaticAnalyzer/Core/CheckerRegistry.h"
 #include "clang/StaticAnalyzer/Core/CheckerOptInfo.h"
+#include "llvm/ADT/SetVector.h"
=20
 using namespace clang;
 using namespace ento;
=20
 static const char PackageSeparator =3D '.';
-typedef llvm::DenseSet<const CheckerRegistry::CheckerInfo *> CheckerInfoSe=
t;
+typedef llvm::SetVector<const CheckerRegistry::CheckerInfo *> CheckerInfoS=
et;
=20
=20
 static bool checkerNameLT(const CheckerRegistry::CheckerInfo &a,
@@ -72,7 +73,7 @@
     if (opt.isEnabled())
       collected.insert(&*i);
     else
-      collected.erase(&*i);
+      collected.remove(&*i);
   }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/CoreEngine.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/CoreEngine.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -12,6 +12,8 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#define DEBUG_TYPE "CoreEngine"
+
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
@@ -20,9 +22,16 @@
 #include "clang/AST/StmtCXX.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/Statistic.h"
+
 using namespace clang;
 using namespace ento;
=20
+STATISTIC(NumReachedMaxSteps,
+            "The # of times we reached the max number of steps.");
+STATISTIC(NumPathsExplored,
+            "The # of paths explored by the analyzer.");
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Worklist classes for exploration of reachable states.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -152,7 +161,7 @@
=20
 /// ExecuteWorkList - Run the worklist algorithm for a maximum number of s=
teps.
 bool CoreEngine::ExecuteWorkList(const LocationContext *L, unsigned Steps,
-                                   const ProgramState *InitState) {
+                                   ProgramStateRef InitState) {
=20
   if (G->num_roots() =3D=3D 0) { // Initialize the analysis by constructing
     // the root if none exists.
@@ -165,6 +174,11 @@
     assert (Entry->succ_size() =3D=3D 1 &&
             "Entry block must have 1 successor.");
=20
+    // Mark the entry block as visited.
+    FunctionSummaries->markVisitedBasicBlock(Entry->getBlockID(),
+                                             L->getDecl(),
+                                             L->getCFG()->getNumBlockIDs()=
);
+
     // Get the solitary successor.
     const CFGBlock *Succ =3D *(Entry->succ_begin());
=20
@@ -187,8 +201,10 @@
=20
   while (WList->hasWork()) {
     if (!UnlimitedSteps) {
-      if (Steps =3D=3D 0)
+      if (Steps =3D=3D 0) {
+        NumReachedMaxSteps++;
         break;
+      }
       --Steps;
     }
=20
@@ -200,67 +216,80 @@
     // Retrieve the node.
     ExplodedNode *Node =3D WU.getNode();
=20
-    // Dispatch on the location type.
-    switch (Node->getLocation().getKind()) {
-      case ProgramPoint::BlockEdgeKind:
-        HandleBlockEdge(cast<BlockEdge>(Node->getLocation()), Node);
-        break;
-
-      case ProgramPoint::BlockEntranceKind:
-        HandleBlockEntrance(cast<BlockEntrance>(Node->getLocation()), Node=
);
-        break;
-
-      case ProgramPoint::BlockExitKind:
-        assert (false && "BlockExit location never occur in forward analys=
is.");
-        break;
-
-      case ProgramPoint::CallEnterKind:
-        HandleCallEnter(cast<CallEnter>(Node->getLocation()), WU.getBlock(=
),=20
-                        WU.getIndex(), Node);
-        break;
-
-      case ProgramPoint::CallExitKind:
-        HandleCallExit(cast<CallExit>(Node->getLocation()), Node);
-        break;
-
-      default:
-        assert(isa<PostStmt>(Node->getLocation()) ||=20
-               isa<PostInitializer>(Node->getLocation()));
-        HandlePostStmt(WU.getBlock(), WU.getIndex(), Node);
-        break;
-    }
+    dispatchWorkItem(Node, Node->getLocation(), WU);
   }
-
   SubEng.processEndWorklist(hasWorkRemaining());
   return WList->hasWork();
 }
=20
-void CoreEngine::ExecuteWorkListWithInitialState(const LocationContext *L,=20
-                                                 unsigned Steps,
-                                                 const ProgramState *InitS=
tate,=20
-                                                 ExplodedNodeSet &Dst) {
-  ExecuteWorkList(L, Steps, InitState);
-  for (SmallVectorImpl<ExplodedNode*>::iterator I =3D G->EndNodes.begin(),=20
-                                           E =3D G->EndNodes.end(); I !=3D=
 E; ++I) {
-    Dst.Add(*I);
+void CoreEngine::dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
+                                  const WorkListUnit& WU) {
+  // Dispatch on the location type.
+  switch (Loc.getKind()) {
+    case ProgramPoint::BlockEdgeKind:
+      HandleBlockEdge(cast<BlockEdge>(Loc), Pred);
+      break;
+
+    case ProgramPoint::BlockEntranceKind:
+      HandleBlockEntrance(cast<BlockEntrance>(Loc), Pred);
+      break;
+
+    case ProgramPoint::BlockExitKind:
+      assert (false && "BlockExit location never occur in forward analysis=
.");
+      break;
+
+    case ProgramPoint::CallEnterKind: {
+      CallEnter CEnter =3D cast<CallEnter>(Loc);
+      if (AnalyzedCallees)
+        if (const CallExpr* CE =3D
+            dyn_cast_or_null<CallExpr>(CEnter.getCallExpr()))
+          if (const Decl *CD =3D CE->getCalleeDecl())
+            AnalyzedCallees->insert(CD);
+      SubEng.processCallEnter(CEnter, Pred);
+      break;
+    }
+
+    case ProgramPoint::CallExitKind:
+      SubEng.processCallExit(Pred);
+      break;
+
+    case ProgramPoint::EpsilonKind: {
+      assert(Pred->hasSinglePred() &&
+             "Assume epsilon has exactly one predecessor by construction");
+      ExplodedNode *PNode =3D Pred->getFirstPred();
+      dispatchWorkItem(Pred, PNode->getLocation(), WU);
+      break;
+    }
+    default:
+      assert(isa<PostStmt>(Loc) ||
+             isa<PostInitializer>(Loc));
+      HandlePostStmt(WU.getBlock(), WU.getIndex(), Pred);
+      break;
   }
 }
=20
-void CoreEngine::HandleCallEnter(const CallEnter &L, const CFGBlock *Block,
-                                   unsigned Index, ExplodedNode *Pred) {
-  CallEnterNodeBuilder Builder(*this, Pred, L.getCallExpr(),=20
-                                 L.getCalleeContext(), Block, Index);
-  SubEng.processCallEnter(Builder);
-}
-
-void CoreEngine::HandleCallExit(const CallExit &L, ExplodedNode *Pred) {
-  CallExitNodeBuilder Builder(*this, Pred);
-  SubEng.processCallExit(Builder);
+bool CoreEngine::ExecuteWorkListWithInitialState(const LocationContext *L,
+                                                 unsigned Steps,
+                                                 ProgramStateRef InitState=
,=20
+                                                 ExplodedNodeSet &Dst) {
+  bool DidNotFinish =3D ExecuteWorkList(L, Steps, InitState);
+  for (ExplodedGraph::eop_iterator I =3D G->eop_begin(),=20
+                                   E =3D G->eop_end(); I !=3D E; ++I) {
+    Dst.Add(*I);
+  }
+  return DidNotFinish;
 }
=20
 void CoreEngine::HandleBlockEdge(const BlockEdge &L, ExplodedNode *Pred) {
=20
   const CFGBlock *Blk =3D L.getDst();
+  NodeBuilderContext BuilderCtx(*this, Blk, Pred);
+
+  // Mark this block as visited.
+  const LocationContext *LC =3D Pred->getLocationContext();
+  FunctionSummaries->markVisitedBasicBlock(Blk->getBlockID(),
+                                           LC->getDecl(),
+                                           LC->getCFG()->getNumBlockIDs());
=20
   // Check if we are entering the EXIT block.
   if (Blk =3D=3D &(L.getLocationContext()->getCFG()->getExit())) {
@@ -269,53 +298,42 @@
             && "EXIT block cannot contain Stmts.");
=20
     // Process the final state transition.
-    EndOfFunctionNodeBuilder Builder(Blk, Pred, this);
-    SubEng.processEndOfFunction(Builder);
+    SubEng.processEndOfFunction(BuilderCtx);
=20
     // This path is done. Don't enqueue any more nodes.
     return;
   }
=20
-  // Call into the subengine to process entering the CFGBlock.
+  // Call into the SubEngine to process entering the CFGBlock.
   ExplodedNodeSet dstNodes;
   BlockEntrance BE(Blk, Pred->getLocationContext());
-  GenericNodeBuilder<BlockEntrance> nodeBuilder(*this, Pred, BE);
-  SubEng.processCFGBlockEntrance(dstNodes, nodeBuilder);
+  NodeBuilderWithSinks nodeBuilder(Pred, dstNodes, BuilderCtx, BE);
+  SubEng.processCFGBlockEntrance(L, nodeBuilder);
=20
-  if (dstNodes.empty()) {
-    if (!nodeBuilder.hasGeneratedNode) {
-      // Auto-generate a node and enqueue it to the worklist.
-      generateNode(BE, Pred->State, Pred);   =20
-    }
-  }
-  else {
-    for (ExplodedNodeSet::iterator I =3D dstNodes.begin(), E =3D dstNodes.=
end();
-         I !=3D E; ++I) {
-      WList->enqueue(*I);
-    }
+  // Auto-generate a node.
+  if (!nodeBuilder.hasGeneratedNodes()) {
+    nodeBuilder.generateNode(Pred->State, Pred);
   }
=20
-  for (SmallVectorImpl<ExplodedNode*>::const_iterator
-       I =3D nodeBuilder.sinks().begin(), E =3D nodeBuilder.sinks().end();
-       I !=3D E; ++I) {
-    blocksExhausted.push_back(std::make_pair(L, *I));
-  }
+  // Enqueue nodes onto the worklist.
+  enqueue(dstNodes);
 }
=20
 void CoreEngine::HandleBlockEntrance(const BlockEntrance &L,
                                        ExplodedNode *Pred) {
=20
   // Increment the block counter.
+  const LocationContext *LC =3D Pred->getLocationContext();
+  unsigned BlockId =3D L.getBlock()->getBlockID();
   BlockCounter Counter =3D WList->getBlockCounter();
-  Counter =3D BCounterFactory.IncrementCount(Counter,=20
-                             Pred->getLocationContext()->getCurrentStackFr=
ame(),
-                                           L.getBlock()->getBlockID());
+  Counter =3D BCounterFactory.IncrementCount(Counter, LC->getCurrentStackF=
rame(),
+                                           BlockId);
   WList->setBlockCounter(Counter);
=20
   // Process the entrance of the block.
   if (CFGElement E =3D L.getFirstElement()) {
-    StmtNodeBuilder Builder(L.getBlock(), 0, Pred, this);
-    SubEng.processCFGElement(E, Builder);
+    NodeBuilderContext Ctx(*this, L.getBlock(), Pred);
+    SubEng.processCFGElement(E, Pred, 0, &Ctx);
   }
   else
     HandleBlockExit(L.getBlock(), Pred);
@@ -345,6 +363,19 @@
         HandleBranch(cast<ChooseExpr>(Term)->getCond(), Term, B, Pred);
         return;
=20
+      case Stmt::CXXTryStmtClass: {
+        // Generate a node for each of the successors.
+        // Our logic for EH analysis can certainly be improved.
+        for (CFGBlock::const_succ_iterator it =3D B->succ_begin(),
+             et =3D B->succ_end(); it !=3D et; ++it) {
+          if (const CFGBlock *succ =3D *it) {
+            generateNode(BlockEdge(B, succ, Pred->getLocationContext()),
+                         Pred->State, Pred);
+          }
+        }
+        return;
+      }
+       =20
       case Stmt::DoStmtClass:
         HandleBranch(cast<DoStmt>(Term)->getCond(), Term, B, Pred);
         return;
@@ -417,31 +448,35 @@
 void CoreEngine::HandleBranch(const Stmt *Cond, const Stmt *Term,=20
                                 const CFGBlock * B, ExplodedNode *Pred) {
   assert(B->succ_size() =3D=3D 2);
-  BranchNodeBuilder Builder(B, *(B->succ_begin()), *(B->succ_begin()+1),
-                            Pred, this);
-  SubEng.processBranch(Cond, Term, Builder);
+  NodeBuilderContext Ctx(*this, B, Pred);
+  ExplodedNodeSet Dst;
+  SubEng.processBranch(Cond, Term, Ctx, Pred, Dst,
+                       *(B->succ_begin()), *(B->succ_begin()+1));
+  // Enqueue the new frontier onto the worklist.
+  enqueue(Dst);
 }
=20
 void CoreEngine::HandlePostStmt(const CFGBlock *B, unsigned StmtIdx,=20
                                   ExplodedNode *Pred) {
-  assert (!B->empty());
+  assert(B);
+  assert(!B->empty());
=20
   if (StmtIdx =3D=3D B->size())
     HandleBlockExit(B, Pred);
   else {
-    StmtNodeBuilder Builder(B, StmtIdx, Pred, this);
-    SubEng.processCFGElement((*B)[StmtIdx], Builder);
+    NodeBuilderContext Ctx(*this, B, Pred);
+    SubEng.processCFGElement((*B)[StmtIdx], Pred, StmtIdx, &Ctx);
   }
 }
=20
 /// generateNode - Utility method to generate nodes, hook up successors,
 ///  and add nodes to the worklist.
 void CoreEngine::generateNode(const ProgramPoint &Loc,
-                              const ProgramState *State,
+                              ProgramStateRef State,
                               ExplodedNode *Pred) {
=20
   bool IsNew;
-  ExplodedNode *Node =3D G->getNode(Loc, State, &IsNew);
+  ExplodedNode *Node =3D G->getNode(Loc, State, false, &IsNew);
=20
   if (Pred)
     Node->addPredecessor(Pred, *G);  // Link 'Node' with its predecessor.
@@ -454,225 +489,181 @@
   if (IsNew) WList->enqueue(Node);
 }
=20
-ExplodedNode *
-GenericNodeBuilderImpl::generateNodeImpl(const ProgramState *state,
-                                         ExplodedNode *pred,
-                                         ProgramPoint programPoint,
-                                         bool asSink) {
- =20
-  hasGeneratedNode =3D true;
-  bool isNew;
-  ExplodedNode *node =3D engine.getGraph().getNode(programPoint, state, &i=
sNew);
-  if (pred)
-    node->addPredecessor(pred, engine.getGraph());
-  if (isNew) {
-    if (asSink) {
-      node->markAsSink();
-      sinksGenerated.push_back(node);
-    }
-    return node;
-  }
-  return 0;
-}
-
-StmtNodeBuilder::StmtNodeBuilder(const CFGBlock *b,
-                                 unsigned idx,
-                                 ExplodedNode *N,
-                                 CoreEngine* e)
-  : Eng(*e), B(*b), Idx(idx), Pred(N),
-    PurgingDeadSymbols(false), BuildSinks(false), hasGeneratedNode(false),
-    PointKind(ProgramPoint::PostStmtKind), Tag(0) {
-  Deferred.insert(N);
-}
-
-StmtNodeBuilder::~StmtNodeBuilder() {
-  for (DeferredTy::iterator I=3DDeferred.begin(), E=3DDeferred.end(); I!=
=3DE; ++I)
-    if (!(*I)->isSink())
-      GenerateAutoTransition(*I);
-}
-
-void StmtNodeBuilder::GenerateAutoTransition(ExplodedNode *N) {
+void CoreEngine::enqueueStmtNode(ExplodedNode *N,
+                                 const CFGBlock *Block, unsigned Idx) {
+  assert(Block);
   assert (!N->isSink());
=20
   // Check if this node entered a callee.
   if (isa<CallEnter>(N->getLocation())) {
     // Still use the index of the CallExpr. It's needed to create the call=
ee
     // StackFrameContext.
-    Eng.WList->enqueue(N, &B, Idx);
+    WList->enqueue(N, Block, Idx);
     return;
   }
=20
   // Do not create extra nodes. Move to the next CFG element.
   if (isa<PostInitializer>(N->getLocation())) {
-    Eng.WList->enqueue(N, &B, Idx+1);
+    WList->enqueue(N, Block, Idx+1);
     return;
   }
=20
-  PostStmt Loc(getStmt(), N->getLocationContext());
+  if (isa<EpsilonPoint>(N->getLocation())) {
+    WList->enqueue(N, Block, Idx);
+    return;
+  }
+
+  const CFGStmt *CS =3D (*Block)[Idx].getAs<CFGStmt>();
+  const Stmt *St =3D CS ? CS->getStmt() : 0;
+  PostStmt Loc(St, N->getLocationContext());
=20
   if (Loc =3D=3D N->getLocation()) {
     // Note: 'N' should be a fresh node because otherwise it shouldn't be
     // a member of Deferred.
-    Eng.WList->enqueue(N, &B, Idx+1);
+    WList->enqueue(N, Block, Idx+1);
     return;
   }
=20
   bool IsNew;
-  ExplodedNode *Succ =3D Eng.G->getNode(Loc, N->State, &IsNew);
-  Succ->addPredecessor(N, *Eng.G);
+  ExplodedNode *Succ =3D G->getNode(Loc, N->getState(), false, &IsNew);
+  Succ->addPredecessor(N, *G);
=20
   if (IsNew)
-    Eng.WList->enqueue(Succ, &B, Idx+1);
+    WList->enqueue(Succ, Block, Idx+1);
 }
=20
-ExplodedNode *StmtNodeBuilder::MakeNode(ExplodedNodeSet &Dst,
-                                        const Stmt *S,=20
-                                        ExplodedNode *Pred,
-                                        const ProgramState *St,
-                                        ProgramPoint::Kind K) {
+ExplodedNode *CoreEngine::generateCallExitNode(ExplodedNode *N) {
+  // Create a CallExit node and enqueue it.
+  const StackFrameContext *LocCtx
+                         =3D cast<StackFrameContext>(N->getLocationContext=
());
+  const Stmt *CE =3D LocCtx->getCallSite();
=20
-  ExplodedNode *N =3D generateNode(S, St, Pred, K);
+  // Use the the callee location context.
+  CallExit Loc(CE, LocCtx);
=20
-  if (N) {
-    if (BuildSinks)
-      N->markAsSink();
-    else
-      Dst.Add(N);
+  bool isNew;
+  ExplodedNode *Node =3D G->getNode(Loc, N->getState(), false, &isNew);
+  Node->addPredecessor(N, *G);
+  return isNew ? Node : 0;
+}
+
+
+void CoreEngine::enqueue(ExplodedNodeSet &Set) {
+  for (ExplodedNodeSet::iterator I =3D Set.begin(),
+                                 E =3D Set.end(); I !=3D E; ++I) {
+    WList->enqueue(*I);
   }
- =20
+}
+
+void CoreEngine::enqueue(ExplodedNodeSet &Set,
+                         const CFGBlock *Block, unsigned Idx) {
+  for (ExplodedNodeSet::iterator I =3D Set.begin(),
+                                 E =3D Set.end(); I !=3D E; ++I) {
+    enqueueStmtNode(*I, Block, Idx);
+  }
+}
+
+void CoreEngine::enqueueEndOfFunction(ExplodedNodeSet &Set) {
+  for (ExplodedNodeSet::iterator I =3D Set.begin(), E =3D Set.end(); I !=
=3D E; ++I) {
+    ExplodedNode *N =3D *I;
+    // If we are in an inlined call, generate CallExit node.
+    if (N->getLocationContext()->getParent()) {
+      N =3D generateCallExitNode(N);
+      if (N)
+        WList->enqueue(N);
+    } else {
+      G->addEndOfPath(N);
+      NumPathsExplored++;
+    }
+  }
+}
+
+
+void NodeBuilder::anchor() { }
+
+ExplodedNode* NodeBuilder::generateNodeImpl(const ProgramPoint &Loc,
+                                            ProgramStateRef State,
+                                            ExplodedNode *FromN,
+                                            bool MarkAsSink) {
+  HasGeneratedNodes =3D true;
+  bool IsNew;
+  ExplodedNode *N =3D C.Eng.G->getNode(Loc, State, MarkAsSink, &IsNew);
+  N->addPredecessor(FromN, *C.Eng.G);
+  Frontier.erase(FromN);
+
+  if (!IsNew)
+    return 0;
+
+  if (!MarkAsSink)
+    Frontier.Add(N);
+
   return N;
 }
=20
-ExplodedNode*
-StmtNodeBuilder::generateNodeInternal(const Stmt *S,
-                                      const ProgramState *state,
-                                      ExplodedNode *Pred,
-                                      ProgramPoint::Kind K,
-                                      const ProgramPointTag *tag) {
- =20
-  const ProgramPoint &L =3D ProgramPoint::getProgramPoint(S, K,
-                                        Pred->getLocationContext(), tag);
-  return generateNodeInternal(L, state, Pred);
+void NodeBuilderWithSinks::anchor() { }
+
+StmtNodeBuilder::~StmtNodeBuilder() {
+  if (EnclosingBldr)
+    for (ExplodedNodeSet::iterator I =3D Frontier.begin(),
+                                   E =3D Frontier.end(); I !=3D E; ++I )
+      EnclosingBldr->addNodes(*I);
 }
=20
-ExplodedNode*
-StmtNodeBuilder::generateNodeInternal(const ProgramPoint &Loc,
-                                      const ProgramState *State,
-                                      ExplodedNode *Pred) {
-  bool IsNew;
-  ExplodedNode *N =3D Eng.G->getNode(Loc, State, &IsNew);
-  N->addPredecessor(Pred, *Eng.G);
-  Deferred.erase(Pred);
+void BranchNodeBuilder::anchor() { }
=20
-  if (IsNew) {
-    Deferred.insert(N);
-    return N;
-  }
-
-  return NULL;
-}
-
-// This function generate a new ExplodedNode but not a new branch(block ed=
ge).
-ExplodedNode *BranchNodeBuilder::generateNode(const Stmt *Condition,
-                                              const ProgramState *State) {
-  bool IsNew;
- =20
-  ExplodedNode *Succ=20
-    =3D Eng.G->getNode(PostCondition(Condition, Pred->getLocationContext()=
), State,
-                     &IsNew);
- =20
-  Succ->addPredecessor(Pred, *Eng.G);
- =20
-  Pred =3D Succ;
- =20
-  if (IsNew)=20
-    return Succ;
- =20
-  return NULL;
-}
-
-ExplodedNode *BranchNodeBuilder::generateNode(const ProgramState *State,
-                                              bool branch) {
-
+ExplodedNode *BranchNodeBuilder::generateNode(ProgramStateRef State,
+                                              bool branch,
+                                              ExplodedNode *NodePred) {
   // If the branch has been marked infeasible we should not generate a nod=
e.
   if (!isFeasible(branch))
     return NULL;
=20
-  bool IsNew;
-
-  ExplodedNode *Succ =3D
-    Eng.G->getNode(BlockEdge(Src,branch ? DstT:DstF,Pred->getLocationConte=
xt()),
-                   State, &IsNew);
-
-  Succ->addPredecessor(Pred, *Eng.G);
-
-  if (branch)
-    GeneratedTrue =3D true;
-  else
-    GeneratedFalse =3D true;
-
-  if (IsNew) {
-    Deferred.push_back(Succ);
-    return Succ;
-  }
-
-  return NULL;
+  ProgramPoint Loc =3D BlockEdge(C.Block, branch ? DstT:DstF,
+                               NodePred->getLocationContext());
+  ExplodedNode *Succ =3D generateNodeImpl(Loc, State, NodePred);
+  return Succ;
 }
=20
-BranchNodeBuilder::~BranchNodeBuilder() {
-  if (!GeneratedTrue) generateNode(Pred->State, true);
-  if (!GeneratedFalse) generateNode(Pred->State, false);
-
-  for (DeferredTy::iterator I=3DDeferred.begin(), E=3DDeferred.end(); I!=
=3DE; ++I)
-    if (!(*I)->isSink()) Eng.WList->enqueue(*I);
-}
-
-
 ExplodedNode*
 IndirectGotoNodeBuilder::generateNode(const iterator &I,
-                                      const ProgramState *St,
-                                      bool isSink) {
+                                      ProgramStateRef St,
+                                      bool IsSink) {
   bool IsNew;
-
   ExplodedNode *Succ =3D Eng.G->getNode(BlockEdge(Src, I.getBlock(),
-                                      Pred->getLocationContext()), St, &Is=
New);
-
+                                      Pred->getLocationContext()), St,
+                                      IsSink, &IsNew);
   Succ->addPredecessor(Pred, *Eng.G);
=20
-  if (IsNew) {
+  if (!IsNew)
+    return 0;
=20
-    if (isSink)
-      Succ->markAsSink();
-    else
-      Eng.WList->enqueue(Succ);
+  if (!IsSink)
+    Eng.WList->enqueue(Succ);
=20
-    return Succ;
-  }
-
-  return NULL;
+  return Succ;
 }
=20
=20
 ExplodedNode*
 SwitchNodeBuilder::generateCaseStmtNode(const iterator &I,
-                                        const ProgramState *St) {
+                                        ProgramStateRef St) {
=20
   bool IsNew;
   ExplodedNode *Succ =3D Eng.G->getNode(BlockEdge(Src, I.getBlock(),
-                                      Pred->getLocationContext()),
-                                      St, &IsNew);
+                                      Pred->getLocationContext()), St,
+                                      false, &IsNew);
   Succ->addPredecessor(Pred, *Eng.G);
-  if (IsNew) {
-    Eng.WList->enqueue(Succ);
-    return Succ;
-  }
-  return NULL;
+  if (!IsNew)
+    return 0;
+
+  Eng.WList->enqueue(Succ);
+  return Succ;
 }
=20
=20
 ExplodedNode*
-SwitchNodeBuilder::generateDefaultCaseNode(const ProgramState *St,
-                                           bool isSink) {
+SwitchNodeBuilder::generateDefaultCaseNode(ProgramStateRef St,
+                                           bool IsSink) {
   // Get the block for the default case.
   assert(Src->succ_rbegin() !=3D Src->succ_rend());
   CFGBlock *DefaultBlock =3D *Src->succ_rbegin();
@@ -683,145 +674,16 @@
     return NULL;
  =20
   bool IsNew;
-
   ExplodedNode *Succ =3D Eng.G->getNode(BlockEdge(Src, DefaultBlock,
-                                      Pred->getLocationContext()), St, &Is=
New);
+                                      Pred->getLocationContext()), St,
+                                      IsSink, &IsNew);
   Succ->addPredecessor(Pred, *Eng.G);
=20
-  if (IsNew) {
-    if (isSink)
-      Succ->markAsSink();
-    else
-      Eng.WList->enqueue(Succ);
+  if (!IsNew)
+    return 0;
=20
-    return Succ;
-  }
+  if (!IsSink)
+    Eng.WList->enqueue(Succ);
=20
-  return NULL;
+  return Succ;
 }
-
-EndOfFunctionNodeBuilder::~EndOfFunctionNodeBuilder() {
-  // Auto-generate an EOP node if one has not been generated.
-  if (!hasGeneratedNode) {
-    // If we are in an inlined call, generate CallExit node.
-    if (Pred->getLocationContext()->getParent())
-      GenerateCallExitNode(Pred->State);
-    else
-      generateNode(Pred->State);
-  }
-}
-
-ExplodedNode*
-EndOfFunctionNodeBuilder::generateNode(const ProgramState *State,
-                                       ExplodedNode *P,
-                                       const ProgramPointTag *tag) {
-  hasGeneratedNode =3D true;
-  bool IsNew;
-
-  ExplodedNode *Node =3D Eng.G->getNode(BlockEntrance(&B,
-                               Pred->getLocationContext(), tag ? tag : Tag=
),
-                               State, &IsNew);
-
-  Node->addPredecessor(P ? P : Pred, *Eng.G);
-
-  if (IsNew) {
-    Eng.G->addEndOfPath(Node);
-    return Node;
-  }
-
-  return NULL;
-}
-
-void EndOfFunctionNodeBuilder::GenerateCallExitNode(const ProgramState *st=
ate) {
-  hasGeneratedNode =3D true;
-  // Create a CallExit node and enqueue it.
-  const StackFrameContext *LocCtx
-                         =3D cast<StackFrameContext>(Pred->getLocationCont=
ext());
-  const Stmt *CE =3D LocCtx->getCallSite();
-
-  // Use the the callee location context.
-  CallExit Loc(CE, LocCtx);
-
-  bool isNew;
-  ExplodedNode *Node =3D Eng.G->getNode(Loc, state, &isNew);
-  Node->addPredecessor(Pred, *Eng.G);
-
-  if (isNew)
-    Eng.WList->enqueue(Node);
-}
-                                               =20
-
-void CallEnterNodeBuilder::generateNode(const ProgramState *state) {
-  // Check if the callee is in the same translation unit.
-  if (CalleeCtx->getTranslationUnit() !=3D=20
-      Pred->getLocationContext()->getTranslationUnit()) {
-    // Create a new engine. We must be careful that the new engine should =
not
-    // reference data structures owned by the old engine.
-
-    AnalysisManager &OldMgr =3D Eng.SubEng.getAnalysisManager();
-   =20
-    // Get the callee's translation unit.
-    idx::TranslationUnit *TU =3D CalleeCtx->getTranslationUnit();
-
-    // Create a new AnalysisManager with components of the callee's
-    // TranslationUnit.
-    // The Diagnostic is  actually shared when we create ASTUnits from AST=
 files.
-    AnalysisManager AMgr(TU->getASTContext(), TU->getDiagnostic(), OldMgr);
-
-    // Create the new engine.
-    // FIXME: This cast isn't really safe.
-    bool GCEnabled =3D static_cast<ExprEngine&>(Eng.SubEng).isObjCGCEnable=
d();
-    ExprEngine NewEng(AMgr, GCEnabled);
-
-    // Create the new LocationContext.
-    AnalysisContext *NewAnaCtx =3D AMgr.getAnalysisContext(CalleeCtx->getD=
ecl(),=20
-                                               CalleeCtx->getTranslationUn=
it());
-    const StackFrameContext *OldLocCtx =3D CalleeCtx;
-    const StackFrameContext *NewLocCtx =3D AMgr.getStackFrame(NewAnaCtx,=20
-                                               OldLocCtx->getParent(),
-                                               OldLocCtx->getCallSite(),
-                                               OldLocCtx->getCallSiteBlock=
(),=20
-                                               OldLocCtx->getIndex());
-
-    // Now create an initial state for the new engine.
-    const ProgramState *NewState =3D
-      NewEng.getStateManager().MarshalState(state, NewLocCtx);
-    ExplodedNodeSet ReturnNodes;
-    NewEng.ExecuteWorkListWithInitialState(NewLocCtx, AMgr.getMaxNodes(),=20
-                                           NewState, ReturnNodes);
-    return;
-  }
-
-  // Get the callee entry block.
-  const CFGBlock *Entry =3D &(CalleeCtx->getCFG()->getEntry());
-  assert(Entry->empty());
-  assert(Entry->succ_size() =3D=3D 1);
-
-  // Get the solitary successor.
-  const CFGBlock *SuccB =3D *(Entry->succ_begin());
-
-  // Construct an edge representing the starting location in the callee.
-  BlockEdge Loc(Entry, SuccB, CalleeCtx);
-
-  bool isNew;
-  ExplodedNode *Node =3D Eng.G->getNode(Loc, state, &isNew);
-  Node->addPredecessor(const_cast<ExplodedNode*>(Pred), *Eng.G);
-
-  if (isNew)
-    Eng.WList->enqueue(Node);
-}
-
-void CallExitNodeBuilder::generateNode(const ProgramState *state) {
-  // Get the callee's location context.
-  const StackFrameContext *LocCtx=20
-                         =3D cast<StackFrameContext>(Pred->getLocationCont=
ext());
-  // When exiting an implicit automatic obj dtor call, the callsite is the=
 Stmt
-  // that triggers the dtor.
-  PostStmt Loc(LocCtx->getCallSite(), LocCtx->getParent());
-  bool isNew;
-  ExplodedNode *Node =3D Eng.G->getNode(Loc, state, &isNew);
-  Node->addPredecessor(const_cast<ExplodedNode*>(Pred), *Eng.G);
-  if (isNew)
-    Eng.WList->enqueue(Node, LocCtx->getCallSiteBlock(),
-                       LocCtx->getIndex() + 1);
-}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/Environment.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Environment.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Environment.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -11,6 +11,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Analysis/CFG.h"
@@ -19,7 +20,7 @@
 using namespace clang;
 using namespace ento;
=20
-SVal Environment::lookupExpr(const Stmt *E) const {
+SVal Environment::lookupExpr(const EnvironmentEntry &E) const {
   const SVal* X =3D ExprBindings.lookup(E);
   if (X) {
     SVal V =3D *X;
@@ -28,17 +29,21 @@
   return UnknownVal();
 }
=20
-SVal Environment::getSVal(const Stmt *E, SValBuilder& svalBuilder,
-			  bool useOnlyDirectBindings) const {
+SVal Environment::getSVal(const EnvironmentEntry &Entry,
+                          SValBuilder& svalBuilder,
+                          bool useOnlyDirectBindings) const {
=20
   if (useOnlyDirectBindings) {
     // This branch is rarely taken, but can be exercised by
     // checkers that explicitly bind values to arbitrary
     // expressions.  It is crucial that we do not ignore any
     // expression here, and do a direct lookup.
-    return lookupExpr(E);
+    return lookupExpr(Entry);
   }
=20
+  const Stmt *E =3D Entry.getStmt();
+  const LocationContext *LCtx =3D Entry.getLocationContext();
+ =20
   for (;;) {
     if (const Expr *Ex =3D dyn_cast<Expr>(E))
       E =3D Ex->IgnoreParens();
@@ -55,13 +60,12 @@
       case Stmt::GenericSelectionExprClass:
         llvm_unreachable("ParenExprs and GenericSelectionExprs should "
                          "have been handled by IgnoreParens()");
-        return UnknownVal();
       case Stmt::CharacterLiteralClass: {
         const CharacterLiteral* C =3D cast<CharacterLiteral>(E);
         return svalBuilder.makeIntVal(C->getValue(), C->getType());
       }
       case Stmt::CXXBoolLiteralExprClass: {
-        const SVal *X =3D ExprBindings.lookup(E);
+        const SVal *X =3D ExprBindings.lookup(EnvironmentEntry(E, LCtx));
         if (X)=20
           return *X;
         else=20
@@ -69,12 +73,15 @@
       }
       case Stmt::IntegerLiteralClass: {
         // In C++, this expression may have been bound to a temporary obje=
ct.
-        SVal const *X =3D ExprBindings.lookup(E);
+        SVal const *X =3D ExprBindings.lookup(EnvironmentEntry(E, LCtx));
         if (X)
           return *X;
         else
           return svalBuilder.makeIntVal(cast<IntegerLiteral>(E));
       }
+      case Stmt::ObjCBoolLiteralExprClass:
+        return svalBuilder.makeBoolVal(cast<ObjCBoolLiteralExpr>(E));
+
       // For special C0xx nullptr case, make a null pointer SVal.
       case Stmt::CXXNullPtrLiteralExprClass:
         return svalBuilder.makeNull();
@@ -86,6 +93,24 @@
         continue;
       case Stmt::ObjCPropertyRefExprClass:
         return loc::ObjCPropRef(cast<ObjCPropertyRefExpr>(E));
+      case Stmt::ObjCStringLiteralClass: {
+        MemRegionManager &MRMgr =3D svalBuilder.getRegionManager();
+        const ObjCStringLiteral *SL =3D cast<ObjCStringLiteral>(E);
+        return svalBuilder.makeLoc(MRMgr.getObjCStringRegion(SL));
+      }
+      case Stmt::StringLiteralClass: {
+        MemRegionManager &MRMgr =3D svalBuilder.getRegionManager();
+        const StringLiteral *SL =3D cast<StringLiteral>(E);
+        return svalBuilder.makeLoc(MRMgr.getStringRegion(SL));
+      }
+      case Stmt::ReturnStmtClass: {
+        const ReturnStmt *RS =3D cast<ReturnStmt>(E);
+        if (const Expr *RE =3D RS->getRetValue()) {
+          E =3D RE;
+          continue;
+        }
+        return UndefinedVal();       =20
+      }
        =20
       // Handle all other Stmt* using a lookup.
       default:
@@ -93,32 +118,33 @@
     };
     break;
   }
-  return lookupExpr(E);
+  return lookupExpr(EnvironmentEntry(E, LCtx));
 }
=20
-Environment EnvironmentManager::bindExpr(Environment Env, const Stmt *S,
-                                         SVal V, bool Invalidate) {
-  assert(S);
-
+Environment EnvironmentManager::bindExpr(Environment Env,
+                                         const EnvironmentEntry &E,
+                                         SVal V,
+                                         bool Invalidate) {
   if (V.isUnknown()) {
     if (Invalidate)
-      return Environment(F.remove(Env.ExprBindings, S));
+      return Environment(F.remove(Env.ExprBindings, E));
     else
       return Env;
   }
-
-  return Environment(F.add(Env.ExprBindings, S, V));
+  return Environment(F.add(Env.ExprBindings, E, V));
 }
=20
-static inline const Stmt *MakeLocation(const Stmt *S) {
-  return (const Stmt*) (((uintptr_t) S) | 0x1);
+static inline EnvironmentEntry MakeLocation(const EnvironmentEntry &E) {
+  const Stmt *S =3D E.getStmt();
+  S =3D (const Stmt*) (((uintptr_t) S) | 0x1);
+  return EnvironmentEntry(S, E.getLocationContext());
 }
=20
 Environment EnvironmentManager::bindExprAndLocation(Environment Env,
-                                                    const Stmt *S,
+                                                    const EnvironmentEntry=
 &E,
                                                     SVal location, SVal V)=
 {
-  return Environment(F.add(F.add(Env.ExprBindings, MakeLocation(S), locati=
on),
-                           S, V));
+  return Environment(F.add(F.add(Env.ExprBindings, MakeLocation(E), locati=
on),
+                           E, V));
 }
=20
 namespace {
@@ -126,14 +152,22 @@
   SymbolReaper &SymReaper;
 public:
   MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {}
-  bool VisitSymbol(SymbolRef sym) { SymReaper.markLive(sym); return true; }
+  bool VisitSymbol(SymbolRef sym) {
+    SymReaper.markLive(sym);
+    return true;
+  }
+  bool VisitMemRegion(const MemRegion *R) {
+    SymReaper.markLive(R);
+    return true;
+  }
 };
 } // end anonymous namespace
=20
-// In addition to mapping from Stmt * - > SVals in the Environment, we also
-// maintain a mapping from Stmt * -> SVals (locations) that were used duri=
ng
-// a load and store.
-static inline bool IsLocation(const Stmt *S) {
+// In addition to mapping from EnvironmentEntry - > SVals in the Environme=
nt,
+// we also maintain a mapping from EnvironmentEntry -> SVals (locations)
+// that were used during a load and store.
+static inline bool IsLocation(const EnvironmentEntry &E) {
+  const Stmt *S =3D E.getStmt();
   return (bool) (((uintptr_t) S) & 0x1);
 }
=20
@@ -147,19 +181,19 @@
 Environment
 EnvironmentManager::removeDeadBindings(Environment Env,
                                        SymbolReaper &SymReaper,
-                                       const ProgramState *ST) {
+                                       ProgramStateRef ST) {
=20
   // We construct a new Environment object entirely, as this is cheaper th=
an
   // individually removing all the subexpression bindings (which will grea=
tly
   // outnumber block-level expression bindings).
   Environment NewEnv =3D getInitialEnvironment();
  =20
-  SmallVector<std::pair<const Stmt*, SVal>, 10> deferredLocations;
+  SmallVector<std::pair<EnvironmentEntry, SVal>, 10> deferredLocations;
=20
   MarkLiveCallback CB(SymReaper);
   ScanReachableSymbols RSScaner(ST, CB);
=20
-  llvm::ImmutableMapRef<const Stmt*,SVal>
+  llvm::ImmutableMapRef<EnvironmentEntry,SVal>
     EBMapRef(NewEnv.ExprBindings.getRootWithoutRetain(),
              F.getTreeFactory());
=20
@@ -167,7 +201,7 @@
   for (Environment::iterator I =3D Env.begin(), E =3D Env.end();
        I !=3D E; ++I) {
=20
-    const Stmt *BlkExpr =3D I.getKey();
+    const EnvironmentEntry &BlkExpr =3D I.getKey();
     // For recorded locations (used when evaluating loads and stores), we
     // consider them live only when their associated normal expression is
     // also live.
@@ -179,7 +213,7 @@
     }
     const SVal &X =3D I.getData();
=20
-    if (SymReaper.isLive(BlkExpr)) {
+    if (SymReaper.isLive(BlkExpr.getStmt(), BlkExpr.getLocationContext()))=
 {
       // Copy the binding to the new map.
       EBMapRef =3D EBMapRef.add(BlkExpr, X);
=20
@@ -204,13 +238,58 @@
  =20
   // Go through he deferred locations and add them to the new environment =
if
   // the correspond Stmt* is in the map as well.
-  for (SmallVectorImpl<std::pair<const Stmt*, SVal> >::iterator
+  for (SmallVectorImpl<std::pair<EnvironmentEntry, SVal> >::iterator
       I =3D deferredLocations.begin(), E =3D deferredLocations.end(); I !=
=3D E; ++I) {
-    const Stmt *S =3D (Stmt*) (((uintptr_t) I->first) & (uintptr_t) ~0x1);
-    if (EBMapRef.lookup(S))
-      EBMapRef =3D EBMapRef.add(I->first, I->second);
+    const EnvironmentEntry &En =3D I->first;
+    const Stmt *S =3D (Stmt*) (((uintptr_t) En.getStmt()) & (uintptr_t) ~0=
x1);
+    if (EBMapRef.lookup(EnvironmentEntry(S, En.getLocationContext())))
+      EBMapRef =3D EBMapRef.add(En, I->second);
   }
=20
   NewEnv.ExprBindings =3D EBMapRef.asImmutableMap();
   return NewEnv;
 }
+
+void Environment::print(raw_ostream &Out, const char *NL,
+                        const char *Sep) const {
+  printAux(Out, false, NL, Sep);
+  printAux(Out, true, NL, Sep);
+}
+ =20
+void Environment::printAux(raw_ostream &Out, bool printLocations,
+                           const char *NL,
+                           const char *Sep) const{
+
+  bool isFirst =3D true;
+
+  for (Environment::iterator I =3D begin(), E =3D end(); I !=3D E; ++I) {
+    const EnvironmentEntry &En =3D I.getKey();
+    if (IsLocation(En)) {
+      if (!printLocations)
+        continue;
+    }
+    else {
+      if (printLocations)
+        continue;
+    }
+   =20
+    if (isFirst) {
+      Out << NL << NL
+          << (printLocations ? "Load/Store locations:" : "Expressions:")
+          << NL;     =20
+      isFirst =3D false;
+    } else {
+      Out << NL;
+    }
+   =20
+    const Stmt *S =3D En.getStmt();
+    if (printLocations) {
+      S =3D (Stmt*) (((uintptr_t) S) & ((uintptr_t) ~0x1));
+    }
+   =20
+    Out << " (" << (void*) En.getLocationContext() << ',' << (void*) S << =
") ";
+    LangOptions LO; // FIXME.
+    S->printPretty(Out, 0, PrintingPolicy(LO));
+    Out << " : " << I.getData();
+  }
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ExplodedGraph.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExplodedGraph.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExplodedGraph.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/AST/Stmt.h"
+#include "clang/AST/ParentMap.h"
 #include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallVector.h"
@@ -44,25 +45,18 @@
 // Cleanup.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-typedef std::vector<ExplodedNode*> NodeList;
-static inline NodeList*& getNodeList(void *&p) { return (NodeList*&) p; }
+static const unsigned CounterTop =3D 1000;
=20
-ExplodedGraph::~ExplodedGraph() {
-  if (reclaimNodes) {
-    delete getNodeList(recentlyAllocatedNodes);
-    delete getNodeList(freeNodes);
-  }
-}
+ExplodedGraph::ExplodedGraph()
+  : NumNodes(0), reclaimNodes(false), reclaimCounter(CounterTop) {}
+
+ExplodedGraph::~ExplodedGraph() {}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Node reclamation.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
-  if (!recentlyAllocatedNodes)
-    return;
-  NodeList &nl =3D *getNodeList(recentlyAllocatedNodes);
-=20
+bool ExplodedGraph::shouldCollect(const ExplodedNode *node) {
   // Reclaimn all nodes that match *all* the following criteria:
   //
   // (1) 1 predecessor (that has one successor)
@@ -72,61 +66,86 @@
   // (5) The 'store' is the same as the predecessor.
   // (6) The 'GDM' is the same as the predecessor.
   // (7) The LocationContext is the same as the predecessor.
-  // (8) The PostStmt is for a non-CFGElement expression.
+  // (8) The PostStmt is for a non-consumed Stmt or Expr.
+
+  // Conditions 1 and 2.
+  if (node->pred_size() !=3D 1 || node->succ_size() !=3D 1)
+    return false;
+
+  const ExplodedNode *pred =3D *(node->pred_begin());
+  if (pred->succ_size() !=3D 1)
+    return false;
  =20
-  for (NodeList::iterator i =3D nl.begin(), e =3D nl.end() ; i !=3D e; ++i=
) {
-    ExplodedNode *node =3D *i;
-   =20
-    // Conditions 1 and 2.
-    if (node->pred_size() !=3D 1 || node->succ_size() !=3D 1)
-      continue;
+  const ExplodedNode *succ =3D *(node->succ_begin());
+  if (succ->pred_size() !=3D 1)
+    return false;
=20
-    ExplodedNode *pred =3D *(node->pred_begin());
-    if (pred->succ_size() !=3D 1)
-      continue;
+  // Condition 3.
+  ProgramPoint progPoint =3D node->getLocation();
+  if (!isa<PostStmt>(progPoint) ||
+      (isa<CallEnter>(progPoint) || isa<CallExit>(progPoint)))
+    return false;
=20
-    ExplodedNode *succ =3D *(node->succ_begin());
-    if (succ->pred_size() !=3D 1)
-      continue;
+  // Condition 4.
+  PostStmt ps =3D cast<PostStmt>(progPoint);
+  if (ps.getTag())
+    return false;
+ =20
+  if (isa<BinaryOperator>(ps.getStmt()))
+    return false;
=20
-    // Condition 3.
-    ProgramPoint progPoint =3D node->getLocation();
-    if (!isa<PostStmt>(progPoint))
-      continue;
-    // Condition 4.
-    PostStmt ps =3D cast<PostStmt>(progPoint);
-    if (ps.getTag())
-      continue;
-
-    if (isa<BinaryOperator>(ps.getStmt()))
-      continue;
-
-    // Conditions 5, 6, and 7.
-    const ProgramState *state =3D node->getState();
-    const ProgramState *pred_state =3D pred->getState();   =20
-    if (state->store !=3D pred_state->store || state->GDM !=3D pred_state-=
>GDM ||
-        progPoint.getLocationContext() !=3D pred->getLocationContext())
-      continue;
-
-    // Condition 8.
-    if (node->getCFG().isBlkExpr(ps.getStmt()))
-      continue;
-   =20
-    // If we reach here, we can remove the node.  This means:
-    // (a) changing the predecessors successor to the successor of this no=
de
-    // (b) changing the successors predecessor to the predecessor of this =
node
-    // (c) Putting 'node' onto freeNodes.
-    pred->replaceSuccessor(succ);
-    succ->replacePredecessor(pred);
-    if (!freeNodes)
-      freeNodes =3D new NodeList();
-    getNodeList(freeNodes)->push_back(node);
-    Nodes.RemoveNode(node);
-    --NumNodes;
-    node->~ExplodedNode();
+  // Conditions 5, 6, and 7.
+  ProgramStateRef state =3D node->getState();
+  ProgramStateRef pred_state =3D pred->getState();   =20
+  if (state->store !=3D pred_state->store || state->GDM !=3D pred_state->G=
DM ||
+      progPoint.getLocationContext() !=3D pred->getLocationContext())
+    return false;
+ =20
+  // Condition 8.
+  if (const Expr *Ex =3D dyn_cast<Expr>(ps.getStmt())) {
+    ParentMap &PM =3D progPoint.getLocationContext()->getParentMap();
+    if (!PM.isConsumedExpr(Ex))
+      return false;
   }
  =20
-  nl.clear();
+  return true;=20
+}
+
+void ExplodedGraph::collectNode(ExplodedNode *node) {
+  // Removing a node means:
+  // (a) changing the predecessors successor to the successor of this node
+  // (b) changing the successors predecessor to the predecessor of this no=
de
+  // (c) Putting 'node' onto freeNodes.
+  assert(node->pred_size() =3D=3D 1 || node->succ_size() =3D=3D 1);
+  ExplodedNode *pred =3D *(node->pred_begin());
+  ExplodedNode *succ =3D *(node->succ_begin());
+  pred->replaceSuccessor(succ);
+  succ->replacePredecessor(pred);
+  FreeNodes.push_back(node);
+  Nodes.RemoveNode(node);
+  --NumNodes;
+  node->~ExplodedNode(); =20
+}
+
+void ExplodedGraph::reclaimRecentlyAllocatedNodes() {
+  if (ChangedNodes.empty())
+    return;
+
+  // Only periodically relcaim nodes so that we can build up a set of
+  // nodes that meet the reclamation criteria.  Freshly created nodes
+  // by definition have no successor, and thus cannot be reclaimed (see be=
low).
+  assert(reclaimCounter > 0);
+  if (--reclaimCounter !=3D 0)
+    return;
+  reclaimCounter =3D CounterTop;
+
+  for (NodeVector::iterator it =3D ChangedNodes.begin(), et =3D ChangedNod=
es.end();
+       it !=3D et; ++it) {
+    ExplodedNode *node =3D *it;
+    if (shouldCollect(node))
+      collectNode(node);
+  }
+  ChangedNodes.clear();
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -215,36 +234,33 @@
 }
=20
 ExplodedNode *ExplodedGraph::getNode(const ProgramPoint &L,
-                                     const ProgramState *State, bool* IsNe=
w) {
+                                     ProgramStateRef State,
+                                     bool IsSink,
+                                     bool* IsNew) {
   // Profile 'State' to determine if we already have an existing node.
   llvm::FoldingSetNodeID profile;
   void *InsertPos =3D 0;
=20
-  NodeTy::Profile(profile, L, State);
+  NodeTy::Profile(profile, L, State, IsSink);
   NodeTy* V =3D Nodes.FindNodeOrInsertPos(profile, InsertPos);
=20
   if (!V) {
-    if (freeNodes && !getNodeList(freeNodes)->empty()) {
-      NodeList *nl =3D getNodeList(freeNodes);
-      V =3D nl->back();
-      nl->pop_back();
+    if (!FreeNodes.empty()) {
+      V =3D FreeNodes.back();
+      FreeNodes.pop_back();
     }
     else {
       // Allocate a new node.
       V =3D (NodeTy*) getAllocator().Allocate<NodeTy>();
     }
=20
-    new (V) NodeTy(L, State);
+    new (V) NodeTy(L, State, IsSink);
=20
-    if (reclaimNodes) {
-      if (!recentlyAllocatedNodes)
-        recentlyAllocatedNodes =3D new NodeList();
-      getNodeList(recentlyAllocatedNodes)->push_back(V);
-    }
+    if (reclaimNodes)
+      ChangedNodes.push_back(V);
=20
     // Insert the node into the node set and return it.
     Nodes.InsertNode(V, InsertPos);
-
     ++NumNodes;
=20
     if (IsNew) *IsNew =3D true;
@@ -265,7 +281,7 @@
=20
   assert (NBeg < NEnd);
=20
-  llvm::OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap());
+  OwningPtr<InterExplodedGraphMap> M(new InterExplodedGraphMap());
=20
   ExplodedGraph* G =3D TrimInternal(NBeg, NEnd, M.get(), InverseMap);
=20
@@ -334,7 +350,7 @@
=20
     // Create the corresponding node in the new graph and record the mappi=
ng
     // from the old node to the new node.
-    ExplodedNode *NewN =3D G->getNode(N->getLocation(), N->State, NULL);
+    ExplodedNode *NewN =3D G->getNode(N->getLocation(), N->State, N->isSin=
k(), 0);
     Pass2[N] =3D NewN;
=20
     // Also record the reverse mapping from the new node to the old node.
@@ -372,15 +388,13 @@
       if (Pass1.count(*I))
         WL2.push_back(*I);
     }
-
-    // Finally, explicitly mark all nodes without any successors as sinks.
-    if (N->isSink())
-      NewN->markAsSink();
   }
=20
   return G;
 }
=20
+void InterExplodedGraphMap::anchor() { }
+
 ExplodedNode*
 InterExplodedGraphMap::getMappedNode(const ExplodedNode *N) const {
   llvm::DenseMap<const ExplodedNode*, ExplodedNode*>::const_iterator I =3D
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ExprEngine.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp	=
Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp	=
Tue Apr 17 11:51:51 2012 +0300
@@ -13,22 +13,24 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#define DEBUG_TYPE "ExprEngine"
+
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/ParentMap.h"
 #include "clang/AST/StmtObjC.h"
+#include "clang/AST/StmtCXX.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/Basic/Builtins.h"
 #include "clang/Basic/SourceManager.h"
-#include "clang/Basic/SourceManager.h"
 #include "clang/Basic/PrettyStackTrace.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/ImmutableList.h"
+#include "llvm/ADT/Statistic.h"
=20
 #ifndef NDEBUG
 #include "llvm/Support/GraphWriter.h"
@@ -38,6 +40,19 @@
 using namespace ento;
 using llvm::APSInt;
=20
+STATISTIC(NumRemoveDeadBindings,
+            "The # of times RemoveDeadBindings is called");
+STATISTIC(NumRemoveDeadBindingsSkipped,
+            "The # of times RemoveDeadBindings is skipped");
+STATISTIC(NumMaxBlockCountReached,
+            "The # of aborted paths due to reaching the maximum block coun=
t in "
+            "a top level function");
+STATISTIC(NumMaxBlockCountReachedInInlined,
+            "The # of aborted paths due to reaching the maximum block coun=
t in "
+            "an inlined function");
+STATISTIC(NumTimesRetriedWithoutInlining,
+            "The # of times we re-evaluated a call without inlining");
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Utility functions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -51,17 +66,20 @@
 // Engine construction and deletion.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled)
+ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
+                       SetOfConstDecls *VisitedCallees,
+                       FunctionSummariesTy *FS)
   : AMgr(mgr),
-    Engine(*this),
+    AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
+    Engine(*this, VisitedCallees, FS),
     G(Engine.getGraph()),
-    Builder(NULL),
     StateMgr(getContext(), mgr.getStoreManagerCreator(),
              mgr.getConstraintManagerCreator(), G.getAllocator(),
              *this),
     SymMgr(StateMgr.getSymbolManager()),
     svalBuilder(StateMgr.getSValBuilder()),
-    EntryNode(NULL), currentStmt(NULL),
+    EntryNode(NULL),
+    currentStmt(NULL), currentStmtIdx(0), currentBuilderContext(0),
     NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
     RaiseSel(GetNullarySelector("raise", getContext())),
     ObjCGCEnabled(gcEnabled), BR(mgr, *this) {
@@ -81,15 +99,15 @@
 // Utility methods.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-const ProgramState *ExprEngine::getInitialState(const LocationContext *Ini=
tLoc) {
-  const ProgramState *state =3D StateMgr.getInitialState(InitLoc);
+ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc=
) {
+  ProgramStateRef state =3D StateMgr.getInitialState(InitLoc);
+  const Decl *D =3D InitLoc->getDecl();
=20
   // Preconditions.
-
   // FIXME: It would be nice if we had a more general mechanism to add
   // such preconditions.  Some day.
   do {
-    const Decl *D =3D InitLoc->getDecl();
+
     if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
       // Precondition: the first argument of 'main' is an integer guarante=
ed
       //  to be > 0.
@@ -117,49 +135,45 @@
       if (!Constraint)
         break;
=20
-      if (const ProgramState *newState =3D state->assume(*Constraint, true=
))
+      if (ProgramStateRef newState =3D state->assume(*Constraint, true))
         state =3D newState;
+    }
+    break;
+  }
+  while (0);
=20
-      break;
+  if (const ObjCMethodDecl *MD =3D dyn_cast<ObjCMethodDecl>(D)) {
+    // Precondition: 'self' is always non-null upon entry to an Objective-C
+    // method.
+    const ImplicitParamDecl *SelfD =3D MD->getSelfDecl();
+    const MemRegion *R =3D state->getRegion(SelfD, InitLoc);
+    SVal V =3D state->getSVal(loc::MemRegionVal(R));
+
+    if (const Loc *LV =3D dyn_cast<Loc>(&V)) {
+      // Assume that the pointer value in 'self' is non-null.
+      state =3D state->assume(*LV, true);
+      assert(state && "'self' cannot be null");
     }
+  }
=20
-    if (const ObjCMethodDecl *MD =3D dyn_cast<ObjCMethodDecl>(D)) {
-      // Precondition: 'self' is always non-null upon entry to an Objectiv=
e-C
-      // method.
-      const ImplicitParamDecl *SelfD =3D MD->getSelfDecl();
-      const MemRegion *R =3D state->getRegion(SelfD, InitLoc);
-      SVal V =3D state->getSVal(loc::MemRegionVal(R));
-
-      if (const Loc *LV =3D dyn_cast<Loc>(&V)) {
-        // Assume that the pointer value in 'self' is non-null.
-        state =3D state->assume(*LV, true);
-        assert(state && "'self' cannot be null");
-      }
-    }
-  } while (0);
-
-  return state;
-}
-
-bool
-ExprEngine::doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) =
const
-{
-  if (callOrMessage.isFunctionCall() && !callOrMessage.isCXXCall()) {
-    SVal calleeV =3D callOrMessage.getFunctionCallee();
-    if (const FunctionTextRegion *codeR =3D
-          dyn_cast_or_null<FunctionTextRegion>(calleeV.getAsRegion())) {
-     =20
-      const FunctionDecl *fd =3D codeR->getDecl();
-      if (const IdentifierInfo *ii =3D fd->getIdentifier()) {
-        StringRef fname =3D ii->getName();
-        if (fname =3D=3D "strlen")
-          return false;
+  if (const CXXMethodDecl *MD =3D dyn_cast<CXXMethodDecl>(D)) {
+    if (!MD->isStatic()) {
+      // Precondition: 'this' is always non-null upon entry to the
+      // top-level function.  This is our starting assumption for
+      // analyzing an "open" program.
+      const StackFrameContext *SFC =3D InitLoc->getCurrentStackFrame();
+      if (SFC->getParent() =3D=3D 0) {
+        loc::MemRegionVal L(getCXXThisRegion(MD, SFC));
+        SVal V =3D state->getSVal(L);
+        if (const Loc *LV =3D dyn_cast<Loc>(&V)) {
+          state =3D state->assume(*LV, true);
+          assert(state && "'this' cannot be null");
+        }
       }
     }
   }
- =20
-  // The conservative answer: invalidates globals.
-  return true;
+   =20
+  return state;
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -168,25 +182,26 @@
=20
 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
 ///  logic for handling assumptions on symbolic values.
-const ProgramState *ExprEngine::processAssume(const ProgramState *state,
+ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
                                               SVal cond, bool assumption) {
   return getCheckerManager().runCheckersForEvalAssume(state, cond, assumpt=
ion);
 }
=20
-bool ExprEngine::wantsRegionChangeUpdate(const ProgramState *state) {
+bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
   return getCheckerManager().wantsRegionChangeUpdate(state);
 }
=20
-const ProgramState *
-ExprEngine::processRegionChanges(const ProgramState *state,
+ProgramStateRef=20
+ExprEngine::processRegionChanges(ProgramStateRef state,
                             const StoreManager::InvalidatedSymbols *invali=
dated,
                                  ArrayRef<const MemRegion *> Explicits,
-                                 ArrayRef<const MemRegion *> Regions) {
+                                 ArrayRef<const MemRegion *> Regions,
+                                 const CallOrObjCMessage *Call) {
   return getCheckerManager().runCheckersForRegionChanges(state, invalidate=
d,
-                                                         Explicits, Region=
s);
+                                                      Explicits, Regions, =
Call);
 }
=20
-void ExprEngine::printState(raw_ostream &Out, const ProgramState *State,
+void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
                             const char *NL, const char *Sep) {
   getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
 }
@@ -195,54 +210,77 @@
   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
 }
=20
-void ExprEngine::processCFGElement(const CFGElement E,=20
-                                  StmtNodeBuilder& builder) {
+void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
+                                   unsigned StmtIdx, NodeBuilderContext *C=
tx) {
+  currentStmtIdx =3D StmtIdx;
+  currentBuilderContext =3D Ctx;
+
   switch (E.getKind()) {
     case CFGElement::Invalid:
       llvm_unreachable("Unexpected CFGElement kind.");
     case CFGElement::Statement:
-      ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), builde=
r);
+      ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred);
       return;
     case CFGElement::Initializer:
-      ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), buil=
der);
+      ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred=
);
       return;
     case CFGElement::AutomaticObjectDtor:
     case CFGElement::BaseDtor:
     case CFGElement::MemberDtor:
     case CFGElement::TemporaryDtor:
-      ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), builder);
+      ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred);
       return;
   }
 }
=20
-void ExprEngine::ProcessStmt(const CFGStmt S, StmtNodeBuilder& builder) {
-  // TODO: Use RAII to remove the unnecessary, tagged nodes.
-  //RegisterCreatedNodes registerCreatedNodes(getGraph());
+static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
+                                     const CFGStmt S,
+                                     const ExplodedNode *Pred,
+                                     const LocationContext *LC) {
+ =20
+  // Are we never purging state values?
+  if (AMgr.getPurgeMode() =3D=3D PurgeNone)
+    return false;
=20
+  // Is this the beginning of a basic block?
+  if (isa<BlockEntrance>(Pred->getLocation()))
+    return true;
+
+  // Is this on a non-expression?
+  if (!isa<Expr>(S.getStmt()))
+    return true;
+   =20
+  // Run before processing a call.
+  if (isa<CallExpr>(S.getStmt()))
+    return true;
+
+  // Is this an expression that is consumed by another expression?  If so,
+  // postpone cleaning out the state.
+  ParentMap &PM =3D LC->getAnalysisDeclContext()->getParentMap();
+  return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
+}
+
+void ExprEngine::ProcessStmt(const CFGStmt S,
+                             ExplodedNode *Pred) {
   // Reclaim any unnecessary nodes in the ExplodedGraph.
   G.reclaimRecentlyAllocatedNodes();
-  // Recycle any unused states in the ProgramStateManager.
-  StateMgr.recycleUnusedStates();
  =20
   currentStmt =3D S.getStmt();
   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
                                 currentStmt->getLocStart(),
                                 "Error evaluating statement");
=20
-  // A tag to track convenience transitions, which can be removed at clean=
up.
-  static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
-  Builder =3D &builder;
-  EntryNode =3D builder.getPredecessor();
+  EntryNode =3D Pred;
=20
-  const ProgramState *EntryState =3D EntryNode->getState();
+  ProgramStateRef EntryState =3D EntryNode->getState();
   CleanedState =3D EntryState;
-  ExplodedNode *CleanedNode =3D 0;
=20
   // Create the cleaned state.
   const LocationContext *LC =3D EntryNode->getLocationContext();
   SymbolReaper SymReaper(LC, currentStmt, SymMgr, getStoreManager());
=20
-  if (AMgr.getPurgeMode() !=3D PurgeNone) {
+  if (shouldRemoveDeadBindings(AMgr, S, Pred, LC)) {
+    NumRemoveDeadBindings++;
     getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
=20
     const StackFrameContext *SFC =3D LC->getCurrentStackFrame();
@@ -251,25 +289,23 @@
     // and the store. TODO: The function should just return new env and st=
ore,
     // not a new state.
     CleanedState =3D StateMgr.removeDeadBindings(CleanedState, SFC, SymRea=
per);
+  } else {
+    NumRemoveDeadBindingsSkipped++;
   }
=20
   // Process any special transfer function for dead symbols.
   ExplodedNodeSet Tmp;
+  // A tag to track convenience transitions, which can be removed at clean=
up.
+  static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
+
   if (!SymReaper.hasDeadSymbols()) {
     // Generate a CleanedNode that has the environment and store cleaned
     // up. Since no symbols are dead, we can optimize and not clean out
     // the constraint manager.
-    CleanedNode =3D
-      Builder->generateNode(currentStmt, CleanedState, EntryNode, &cleanup=
Tag);
-    Tmp.Add(CleanedNode);
+    StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
+    Bldr.generateNode(currentStmt, EntryNode, CleanedState, false, &cleanu=
pTag);
=20
   } else {
-    SaveAndRestore<bool> OldSink(Builder->BuildSinks);
-    SaveOr OldHasGen(Builder->hasGeneratedNode);
-
-    SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols);
-    Builder->PurgingDeadSymbols =3D true;
-
     // Call checkers with the non-cleaned state so that they could query t=
he
     // values of the soon to be dead symbols.
     ExplodedNodeSet CheckedSet;
@@ -279,9 +315,10 @@
     // For each node in CheckedSet, generate CleanedNodes that have the
     // environment, the store, and the constraints cleaned up but have the
     // user-supplied states as the predecessors.
+    StmtNodeBuilder Bldr(CheckedSet, Tmp, *currentBuilderContext);
     for (ExplodedNodeSet::const_iterator
           I =3D CheckedSet.begin(), E =3D CheckedSet.end(); I !=3D E; ++I)=
 {
-      const ProgramState *CheckerState =3D (*I)->getState();
+      ProgramStateRef CheckerState =3D (*I)->getState();
=20
       // The constraint manager has not been cleaned up yet, so clean up n=
ow.
       CheckerState =3D getConstraintManager().removeDeadBindings(CheckerSt=
ate,
@@ -296,109 +333,109 @@
=20
       // Create a state based on CleanedState with CheckerState GDM and
       // generate a transition to that state.
-      const ProgramState *CleanedCheckerSt =3D
+      ProgramStateRef CleanedCheckerSt =3D
         StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
-      ExplodedNode *CleanedNode =3D Builder->generateNode(currentStmt,
-                                                        CleanedCheckerSt, =
*I,
-                                                        &cleanupTag);
-      Tmp.Add(CleanedNode);
+      Bldr.generateNode(currentStmt, *I, CleanedCheckerSt, false, &cleanup=
Tag,
+                        ProgramPoint::PostPurgeDeadSymbolsKind);
     }
   }
=20
+  ExplodedNodeSet Dst;
   for (ExplodedNodeSet::iterator I=3DTmp.begin(), E=3DTmp.end(); I!=3DE; +=
+I) {
-    // TODO: Remove Dest set, it's no longer needed.
-    ExplodedNodeSet Dst;
+    ExplodedNodeSet DstI;
     // Visit the statement.
-    Visit(currentStmt, *I, Dst);
+    Visit(currentStmt, *I, DstI);
+    Dst.insert(DstI);
   }
=20
+  // Enqueue the new nodes onto the work list.
+  Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
+
   // NULL out these variables to cleanup.
   CleanedState =3D NULL;
   EntryNode =3D NULL;
   currentStmt =3D 0;
-  Builder =3D NULL;
 }
=20
 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
-                                    StmtNodeBuilder &builder) {
+                                    ExplodedNode *Pred) {
+  ExplodedNodeSet Dst;
+
   // We don't set EntryNode and currentStmt. And we don't clean up state.
   const CXXCtorInitializer *BMI =3D Init.getInitializer();
-
-  ExplodedNode *pred =3D builder.getPredecessor();
-
-  const StackFrameContext *stackFrame =3D cast<StackFrameContext>(pred->ge=
tLocationContext());
-  const CXXConstructorDecl *decl =3D cast<CXXConstructorDecl>(stackFrame->=
getDecl());
+  const StackFrameContext *stackFrame =3D
+                           cast<StackFrameContext>(Pred->getLocationContex=
t());
+  const CXXConstructorDecl *decl =3D
+                           cast<CXXConstructorDecl>(stackFrame->getDecl());
   const CXXThisRegion *thisReg =3D getCXXThisRegion(decl, stackFrame);
=20
-  SVal thisVal =3D pred->getState()->getSVal(thisReg);
+  SVal thisVal =3D Pred->getState()->getSVal(thisReg);
=20
   if (BMI->isAnyMemberInitializer()) {
-    ExplodedNodeSet Dst;
+    // Evaluate the initializer.
=20
-    // Evaluate the initializer.
-    Visit(BMI->getInit(), pred, Dst);
+    StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
+    ProgramStateRef state =3D Pred->getState();
=20
-    for (ExplodedNodeSet::iterator I =3D Dst.begin(), E =3D Dst.end(); I !=
=3D E; ++I){
-      ExplodedNode *Pred =3D *I;
-      const ProgramState *state =3D Pred->getState();
+    const FieldDecl *FD =3D BMI->getAnyMember();
=20
-      const FieldDecl *FD =3D BMI->getAnyMember();
+    SVal FieldLoc =3D state->getLValue(FD, thisVal);
+    SVal InitVal =3D state->getSVal(BMI->getInit(), Pred->getLocationConte=
xt());
+    state =3D state->bindLoc(FieldLoc, InitVal);
=20
-      SVal FieldLoc =3D state->getLValue(FD, thisVal);
-      SVal InitVal =3D state->getSVal(BMI->getInit());
-      state =3D state->bindLoc(FieldLoc, InitVal);
+    // Use a custom node building process.
+    PostInitializer PP(BMI, stackFrame);
+    // Builder automatically add the generated node to the deferred set,
+    // which are processed in the builder's dtor.
+    Bldr.generateNode(PP, Pred, state);
+  } else {
+    assert(BMI->isBaseInitializer());
=20
-      // Use a custom node building process.
-      PostInitializer PP(BMI, stackFrame);
-      // Builder automatically add the generated node to the deferred set,
-      // which are processed in the builder's dtor.
-      builder.generateNode(PP, state, Pred);
-    }
-    return;
+    // Get the base class declaration.
+    const CXXConstructExpr *ctorExpr =3D cast<CXXConstructExpr>(BMI->getIn=
it());
+
+    // Create the base object region.
+    SVal baseVal =3D
+        getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
+    const MemRegion *baseReg =3D baseVal.getAsRegion();
+    assert(baseReg);
+
+    VisitCXXConstructExpr(ctorExpr, baseReg, Pred, Dst);
   }
=20
-  assert(BMI->isBaseInitializer());
-
-  // Get the base class declaration.
-  const CXXConstructExpr *ctorExpr =3D cast<CXXConstructExpr>(BMI->getInit=
());
-
-  // Create the base object region.
-  SVal baseVal =3D=20
-    getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
-  const MemRegion *baseReg =3D baseVal.getAsRegion();
-  assert(baseReg);
-  Builder =3D &builder;
-  ExplodedNodeSet dst;
-  VisitCXXConstructExpr(ctorExpr, baseReg, pred, dst);
+  // Enqueue the new nodes onto the work list.
+  Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
 }
=20
 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
-                                       StmtNodeBuilder &builder) {
-  Builder =3D &builder;
-
+                                     ExplodedNode *Pred) {
+  ExplodedNodeSet Dst;
   switch (D.getKind()) {
   case CFGElement::AutomaticObjectDtor:
-    ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder);
+    ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst);
     break;
   case CFGElement::BaseDtor:
-    ProcessBaseDtor(cast<CFGBaseDtor>(D), builder);
+    ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst);
     break;
   case CFGElement::MemberDtor:
-    ProcessMemberDtor(cast<CFGMemberDtor>(D), builder);
+    ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst);
     break;
   case CFGElement::TemporaryDtor:
-    ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder);
+    ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst);
     break;
   default:
     llvm_unreachable("Unexpected dtor kind.");
   }
+
+  // Enqueue the new nodes onto the work list.
+  Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
 }
=20
-void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor,
-                                           StmtNodeBuilder &builder) {
-  ExplodedNode *pred =3D builder.getPredecessor();
-  const ProgramState *state =3D pred->getState();
-  const VarDecl *varDecl =3D dtor.getVarDecl();
+void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
+                                         ExplodedNode *Pred,
+                                         ExplodedNodeSet &Dst) {
+  ProgramStateRef state =3D Pred->getState();
+  const VarDecl *varDecl =3D Dtor.getVarDecl();
=20
   QualType varType =3D varDecl->getType();
=20
@@ -409,30 +446,29 @@
   assert(recordDecl && "get CXXRecordDecl fail");
   const CXXDestructorDecl *dtorDecl =3D recordDecl->getDestructor();
=20
-  Loc dest =3D state->getLValue(varDecl, pred->getLocationContext());
+  Loc dest =3D state->getLValue(varDecl, Pred->getLocationContext());
=20
-  ExplodedNodeSet dstSet;
   VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
-                     dtor.getTriggerStmt(), pred, dstSet);
+                     Dtor.getTriggerStmt(), Pred, Dst);
 }
=20
 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
-                                   StmtNodeBuilder &builder) {
-}
+                                 ExplodedNode *Pred, ExplodedNodeSet &Dst)=
 {}
=20
 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
-                                     StmtNodeBuilder &builder) {
-}
+                                   ExplodedNode *Pred, ExplodedNodeSet &Ds=
t) {}
=20
 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
-                                        StmtNodeBuilder &builder) {
-}
+                                      ExplodedNode *Pred,
+                                      ExplodedNodeSet &Dst) {}
=20
 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,=20
-                         ExplodedNodeSet &Dst) {
+                       ExplodedNodeSet &DstTop) {
   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
                                 S->getLocStart(),
                                 "Error evaluating statement");
+  ExplodedNodeSet Dst;
+  StmtNodeBuilder Bldr(Pred, DstTop, *currentBuilderContext);
=20
   // Expressions to ignore.
   if (const Expr *Ex =3D dyn_cast<Expr>(S))
@@ -442,19 +478,14 @@
   //  this check when we KNOW that there is no block-level subexpression.
   //  The motivation is that this check requires a hashtable lookup.
=20
-  if (S !=3D currentStmt && Pred->getLocationContext()->getCFG()->isBlkExp=
r(S)) {
-    Dst.Add(Pred);
+  if (S !=3D currentStmt && Pred->getLocationContext()->getCFG()->isBlkExp=
r(S))
     return;
-  }
=20
   switch (S->getStmtClass()) {
     // C++ and ARC stuff we don't support yet.
     case Expr::ObjCIndirectCopyRestoreExprClass:
-    case Stmt::CXXBindTemporaryExprClass:
-    case Stmt::CXXCatchStmtClass:
     case Stmt::CXXDependentScopeMemberExprClass:
     case Stmt::CXXPseudoDestructorExprClass:
-    case Stmt::CXXThrowExprClass:
     case Stmt::CXXTryStmtClass:
     case Stmt::CXXTypeidExprClass:
     case Stmt::CXXUuidofExprClass:
@@ -463,6 +494,7 @@
     case Stmt::DependentScopeDeclRefExprClass:
     case Stmt::UnaryTypeTraitExprClass:
     case Stmt::BinaryTypeTraitExprClass:
+    case Stmt::TypeTraitExprClass:
     case Stmt::ArrayTypeTraitExprClass:
     case Stmt::ExpressionTraitExprClass:
     case Stmt::UnresolvedLookupExprClass:
@@ -472,22 +504,19 @@
     case Stmt::SubstNonTypeTemplateParmPackExprClass:
     case Stmt::SEHTryStmtClass:
     case Stmt::SEHExceptStmtClass:
-    case Stmt::SEHFinallyStmtClass:
-    {
-      SaveAndRestore<bool> OldSink(Builder->BuildSinks);
-      Builder->BuildSinks =3D true;
-      const ExplodedNode *node =3D MakeNode(Dst, S, Pred, Pred->getState()=
);
-      Engine.addAbortedBlock(node, Builder->getBlock());
+    case Stmt::LambdaExprClass:
+    case Stmt::SEHFinallyStmtClass: {
+      const ExplodedNode *node =3D Bldr.generateNode(S, Pred, Pred->getSta=
te(),
+                                                   /* sink */ true);
+      Engine.addAbortedBlock(node, currentBuilderContext->getBlock());
       break;
     }
    =20
     // We don't handle default arguments either yet, but we can fake it
     // for now by just skipping them.
     case Stmt::SubstNonTypeTemplateParmExprClass:
-    case Stmt::CXXDefaultArgExprClass: {
-      Dst.Add(Pred);
+    case Stmt::CXXDefaultArgExprClass:
       break;
-    }
=20
     case Stmt::ParenExprClass:
       llvm_unreachable("ParenExprs already handled.");
@@ -511,38 +540,44 @@
     case Stmt::NullStmtClass:
     case Stmt::SwitchStmtClass:
     case Stmt::WhileStmtClass:
+    case Expr::MSDependentExistsStmtClass:
       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
-      break;
=20
     case Stmt::GNUNullExprClass: {
       // GNU __null is a pointer-width integer, not an actual pointer.
-      const ProgramState *state =3D Pred->getState();
-      state =3D state->BindExpr(S, svalBuilder.makeIntValWithPtrWidth(0, f=
alse));
-      MakeNode(Dst, S, Pred, state);
+      ProgramStateRef state =3D Pred->getState();
+      state =3D state->BindExpr(S, Pred->getLocationContext(),
+                              svalBuilder.makeIntValWithPtrWidth(0, false)=
);
+      Bldr.generateNode(S, Pred, state);
       break;
     }
=20
     case Stmt::ObjCAtSynchronizedStmtClass:
+      Bldr.takeNodes(Pred);
       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, D=
st);
+      Bldr.addNodes(Dst);
       break;
=20
+    // FIXME.
+    case Stmt::ObjCSubscriptRefExprClass:
+      break;
+     =20
     case Stmt::ObjCPropertyRefExprClass:
       // Implicitly handled by Environment::getSVal().
-      Dst.Add(Pred);
       break;
=20
     case Stmt::ImplicitValueInitExprClass: {
-      const ProgramState *state =3D Pred->getState();
+      ProgramStateRef state =3D Pred->getState();
       QualType ty =3D cast<ImplicitValueInitExpr>(S)->getType();
       SVal val =3D svalBuilder.makeZeroVal(ty);
-      MakeNode(Dst, S, Pred, state->BindExpr(S, val));
+      Bldr.generateNode(S, Pred, state->BindExpr(S, Pred->getLocationConte=
xt(),
+                                                 val));
       break;
     }
      =20
-    case Stmt::ExprWithCleanupsClass: {
-      Visit(cast<ExprWithCleanups>(S)->getSubExpr(), Pred, Dst);
+    case Stmt::ExprWithCleanupsClass:
+      // Handled due to fully linearised CFG.
       break;
-    }
=20
     // Cases not handled yet; but will handle some day.
     case Stmt::DesignatedInitExprClass:
@@ -556,7 +591,7 @@
     case Stmt::ObjCIsaExprClass:
     case Stmt::ObjCProtocolExprClass:
     case Stmt::ObjCSelectorExprClass:
-    case Stmt::ObjCStringLiteralClass:
+    case Expr::ObjCNumericLiteralClass:
     case Stmt::ParenListExprClass:
     case Stmt::PredefinedExprClass:
     case Stmt::ShuffleVectorExprClass:
@@ -565,50 +600,101 @@
     case Stmt::OpaqueValueExprClass:
     case Stmt::AsTypeExprClass:
     case Stmt::AtomicExprClass:
-        // Fall through.
+      // Fall through.
=20
+    // Currently all handling of 'throw' just falls to the CFG.  We
+    // can consider doing more if necessary.
+    case Stmt::CXXThrowExprClass:
+      // Fall through.
+     =20
     // Cases we intentionally don't evaluate, since they don't need
     // to be explicitly evaluated.
     case Stmt::AddrLabelExprClass:
     case Stmt::IntegerLiteralClass:
     case Stmt::CharacterLiteralClass:
     case Stmt::CXXBoolLiteralExprClass:
+    case Stmt::ObjCBoolLiteralExprClass:
     case Stmt::FloatingLiteralClass:
     case Stmt::SizeOfPackExprClass:
-    case Stmt::CXXNullPtrLiteralExprClass:
-      Dst.Add(Pred); // No-op. Simply propagate the current state unchange=
d.
+    case Stmt::StringLiteralClass:
+    case Stmt::ObjCStringLiteralClass:
+    case Stmt::CXXBindTemporaryExprClass:
+    case Stmt::CXXNullPtrLiteralExprClass: {
+      Bldr.takeNodes(Pred);
+      ExplodedNodeSet preVisit;
+      getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
+      getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
+      Bldr.addNodes(Dst);
       break;
+    }
+
+    case Expr::ObjCArrayLiteralClass:
+    case Expr::ObjCDictionaryLiteralClass: {
+      Bldr.takeNodes(Pred);
+
+      ExplodedNodeSet preVisit;
+      getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
+     =20
+      // FIXME: explicitly model with a region and the actual contents
+      // of the container.  For now, conjure a symbol.
+      ExplodedNodeSet Tmp;
+      StmtNodeBuilder Bldr2(preVisit, Tmp, *currentBuilderContext);
+
+      for (ExplodedNodeSet::iterator it =3D preVisit.begin(), et =3D preVi=
sit.end();
+           it !=3D et; ++it) {     =20
+        ExplodedNode *N =3D *it;
+        const Expr *Ex =3D cast<Expr>(S);
+        QualType resultType =3D Ex->getType();
+        const LocationContext *LCtx =3D N->getLocationContext();
+        SVal result =3D
+          svalBuilder.getConjuredSymbolVal(0, Ex, LCtx, resultType,=20
+                                 currentBuilderContext->getCurrentBlockCou=
nt());
+        ProgramStateRef state =3D N->getState()->BindExpr(Ex, LCtx, result=
);
+        Bldr2.generateNode(S, N, state);
+      }
+     =20
+      getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
+      Bldr.addNodes(Dst);
+      break;     =20
+    }
=20
     case Stmt::ArraySubscriptExprClass:
+      Bldr.takeNodes(Pred);
       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::AsmStmtClass:
+      Bldr.takeNodes(Pred);
       VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
-    case Stmt::BlockDeclRefExprClass: {
-      const BlockDeclRefExpr *BE =3D cast<BlockDeclRefExpr>(S);
-      VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst);
-      break;
-    }
-
     case Stmt::BlockExprClass:
+      Bldr.takeNodes(Pred);
       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::BinaryOperatorClass: {
       const BinaryOperator* B =3D cast<BinaryOperator>(S);
       if (B->isLogicalOp()) {
+        Bldr.takeNodes(Pred);
         VisitLogicalExpr(B, Pred, Dst);
+        Bldr.addNodes(Dst);
         break;
       }
       else if (B->getOpcode() =3D=3D BO_Comma) {
-        const ProgramState *state =3D Pred->getState();
-        MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS=
())));
+        ProgramStateRef state =3D Pred->getState();
+        Bldr.generateNode(B, Pred,
+                          state->BindExpr(B, Pred->getLocationContext(),
+                                          state->getSVal(B->getRHS(),
+                                                  Pred->getLocationContext=
())));
         break;
       }
=20
+      Bldr.takeNodes(Pred);
+     =20
       if (AMgr.shouldEagerlyAssume() &&
           (B->isRelationalOp() || B->isEqualityOp())) {
         ExplodedNodeSet Tmp;
@@ -618,13 +704,24 @@
       else
         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
=20
+      Bldr.addNodes(Dst);
       break;
     }
=20
     case Stmt::CallExprClass:
     case Stmt::CXXOperatorCallExprClass:
-    case Stmt::CXXMemberCallExprClass: {
+    case Stmt::CXXMemberCallExprClass:
+    case Stmt::UserDefinedLiteralClass: {
+      Bldr.takeNodes(Pred);
       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
+      break;
+    }
+   =20
+    case Stmt::CXXCatchStmtClass: {
+      Bldr.takeNodes(Pred);
+      VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
=20
@@ -633,58 +730,78 @@
       const CXXConstructExpr *C =3D cast<CXXConstructExpr>(S);
       // For block-level CXXConstructExpr, we don't have a destination reg=
ion.
       // Let VisitCXXConstructExpr() create one.
+      Bldr.takeNodes(Pred);
       VisitCXXConstructExpr(C, 0, Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
=20
     case Stmt::CXXNewExprClass: {
+      Bldr.takeNodes(Pred);
       const CXXNewExpr *NE =3D cast<CXXNewExpr>(S);
       VisitCXXNewExpr(NE, Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
=20
     case Stmt::CXXDeleteExprClass: {
+      Bldr.takeNodes(Pred);
       const CXXDeleteExpr *CDE =3D cast<CXXDeleteExpr>(S);
       VisitCXXDeleteExpr(CDE, Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
       // FIXME: ChooseExpr is really a constant.  We need to fix
       //        the CFG do not model them as explicit control-flow.
=20
     case Stmt::ChooseExprClass: { // __builtin_choose_expr
+      Bldr.takeNodes(Pred);
       const ChooseExpr *C =3D cast<ChooseExpr>(S);
       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
=20
     case Stmt::CompoundAssignOperatorClass:
+      Bldr.takeNodes(Pred);
       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::CompoundLiteralExprClass:
+      Bldr.takeNodes(Pred);
       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::BinaryConditionalOperatorClass:
     case Stmt::ConditionalOperatorClass: { // '?' operator
+      Bldr.takeNodes(Pred);
       const AbstractConditionalOperator *C
         =3D cast<AbstractConditionalOperator>(S);
       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
=20
     case Stmt::CXXThisExprClass:
+      Bldr.takeNodes(Pred);
       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::DeclRefExprClass: {
+      Bldr.takeNodes(Pred);
       const DeclRefExpr *DE =3D cast<DeclRefExpr>(S);
       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
=20
     case Stmt::DeclStmtClass:
+      Bldr.takeNodes(Pred);
       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::ImplicitCastExprClass:
@@ -695,6 +812,7 @@
     case Stmt::CXXConstCastExprClass:
     case Stmt::CXXFunctionalCastExprClass:=20
     case Stmt::ObjCBridgedCastExprClass: {
+      Bldr.takeNodes(Pred);
       const CastExpr *C =3D cast<CastExpr>(S);
       // Handle the previsit checks.
       ExplodedNodeSet dstPrevisit;
@@ -709,58 +827,98 @@
=20
       // Handle the postvisit checks.
       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
+      Bldr.addNodes(Dst);
       break;
     }
=20
     case Expr::MaterializeTemporaryExprClass: {
+      Bldr.takeNodes(Pred);
       const MaterializeTemporaryExpr *Materialize
                                             =3D cast<MaterializeTemporaryE=
xpr>(S);
-      if (!Materialize->getType()->isRecordType())
+      if (Materialize->getType()->isRecordType())
+        Dst.Add(Pred);
+      else
         CreateCXXTemporaryObject(Materialize, Pred, Dst);
-      else
-        Visit(Materialize->GetTemporaryExpr(), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
     }
      =20
     case Stmt::InitListExprClass:
+      Bldr.takeNodes(Pred);
       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::MemberExprClass:
+      Bldr.takeNodes(Pred);
       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
+
     case Stmt::ObjCIvarRefExprClass:
+      Bldr.takeNodes(Pred);
       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::ObjCForCollectionStmtClass:
+      Bldr.takeNodes(Pred);
       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst=
);
+      Bldr.addNodes(Dst);
       break;
=20
-    case Stmt::ObjCMessageExprClass:
-      VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
+    case Stmt::ObjCMessageExprClass: {
+      Bldr.takeNodes(Pred);
+      // Is this a property access?
+      const ParentMap &PM =3D Pred->getLocationContext()->getParentMap();
+      const ObjCMessageExpr *ME =3D cast<ObjCMessageExpr>(S);
+      bool evaluated =3D false;
+     =20
+      if (const PseudoObjectExpr *PO =3D
+          dyn_cast_or_null<PseudoObjectExpr>(PM.getParent(S))) {
+        const Expr *syntactic =3D PO->getSyntacticForm();
+        if (const ObjCPropertyRefExpr *PR =3D
+              dyn_cast<ObjCPropertyRefExpr>(syntactic)) {
+          bool isSetter =3D ME->getNumArgs() > 0;
+          VisitObjCMessage(ObjCMessage(ME, PR, isSetter), Pred, Dst);
+          evaluated =3D true;
+        }
+        else if (isa<BinaryOperator>(syntactic)) {
+          VisitObjCMessage(ObjCMessage(ME, 0, true), Pred, Dst);
+        }
+      }
+     =20
+      if (!evaluated)
+        VisitObjCMessage(ME, Pred, Dst);
+
+      Bldr.addNodes(Dst);
       break;
+    }
=20
     case Stmt::ObjCAtThrowStmtClass: {
       // FIXME: This is not complete.  We basically treat @throw as
       // an abort.
-      SaveAndRestore<bool> OldSink(Builder->BuildSinks);
-      Builder->BuildSinks =3D true;
-      MakeNode(Dst, S, Pred, Pred->getState());
+      Bldr.generateNode(S, Pred, Pred->getState());
       break;
     }
=20
     case Stmt::ReturnStmtClass:
+      Bldr.takeNodes(Pred);
       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::OffsetOfExprClass:
+      Bldr.takeNodes(Pred);
       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::UnaryExprOrTypeTraitExprClass:
+      Bldr.takeNodes(Pred);
       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
                                     Pred, Dst);
+      Bldr.addNodes(Dst);
       break;
=20
     case Stmt::StmtExprClass: {
@@ -770,81 +928,154 @@
         // Empty statement expression.
         assert(SE->getType() =3D=3D getContext().VoidTy
                && "Empty statement expression must have void type.");
-        Dst.Add(Pred);
         break;
       }
=20
       if (Expr *LastExpr =3D dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin=
())) {
-        const ProgramState *state =3D Pred->getState();
-        MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExp=
r)));
+        ProgramStateRef state =3D Pred->getState();
+        Bldr.generateNode(SE, Pred,
+                          state->BindExpr(SE, Pred->getLocationContext(),
+                                          state->getSVal(LastExpr,
+                                                  Pred->getLocationContext=
())));
       }
-      else
-        Dst.Add(Pred);
-
       break;
     }
=20
-    case Stmt::StringLiteralClass: {
-      const ProgramState *state =3D Pred->getState();
-      SVal V =3D state->getLValue(cast<StringLiteral>(S));
-      MakeNode(Dst, S, Pred, state->BindExpr(S, V));
-      return;
-    }
-
     case Stmt::UnaryOperatorClass: {
+      Bldr.takeNodes(Pred);
       const UnaryOperator *U =3D cast<UnaryOperator>(S);
-      if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() =3D=3D UO_LNot)) {
+      if (AMgr.shouldEagerlyAssume() && (U->getOpcode() =3D=3D UO_LNot)) {
         ExplodedNodeSet Tmp;
         VisitUnaryOperator(U, Pred, Tmp);
         evalEagerlyAssume(Dst, Tmp, U);
       }
       else
         VisitUnaryOperator(U, Pred, Dst);
+      Bldr.addNodes(Dst);
+      break;
+    }
+
+    case Stmt::PseudoObjectExprClass: {
+      Bldr.takeNodes(Pred);
+      ProgramStateRef state =3D Pred->getState();
+      const PseudoObjectExpr *PE =3D cast<PseudoObjectExpr>(S);
+      if (const Expr *Result =3D PE->getResultExpr()) {=20
+        SVal V =3D state->getSVal(Result, Pred->getLocationContext());
+        Bldr.generateNode(S, Pred,
+                          state->BindExpr(S, Pred->getLocationContext(), V=
));
+      }
+      else
+        Bldr.generateNode(S, Pred,
+                          state->BindExpr(S, Pred->getLocationContext(),
+                                                   UnknownVal()));
+
+      Bldr.addNodes(Dst);
       break;
     }
   }
 }
=20
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// Block entrance.  (Update counters).
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
+                                       const LocationContext *CalleeLC) {
+  const StackFrameContext *CalleeSF =3D CalleeLC->getCurrentStackFrame();
+  const StackFrameContext *CallerSF =3D CalleeSF->getParent()->getCurrentS=
tackFrame();
+  assert(CalleeSF && CallerSF);
+  ExplodedNode *BeforeProcessingCall =3D 0;
=20
-void ExprEngine::processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
-                               GenericNodeBuilder<BlockEntrance> &nodeBuil=
der){
+  // Find the first node before we started processing the call expression.
+  while (N) {
+    ProgramPoint L =3D N->getLocation();
+    BeforeProcessingCall =3D N;
+    N =3D N->pred_empty() ? NULL : *(N->pred_begin());
+
+    // Skip the nodes corresponding to the inlined code.
+    if (L.getLocationContext()->getCurrentStackFrame() !=3D CallerSF)
+      continue;
+    // We reached the caller. Find the node right before we started
+    // processing the CallExpr.
+    if (isa<PostPurgeDeadSymbols>(L))
+      continue;
+    if (const StmtPoint *SP =3D dyn_cast<StmtPoint>(&L))
+      if (SP->getStmt() =3D=3D CalleeSF->getCallSite())
+        continue;
+    break;
+  }
+
+  if (!BeforeProcessingCall)
+    return false;
+
+  // TODO: Clean up the unneeded nodes.
+
+  // Build an Epsilon node from which we will restart the analyzes.
+  const Stmt *CE =3D CalleeSF->getCallSite();
+  ProgramPoint NewNodeLoc =3D
+               EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE=
);
+  // Add the special flag to GDM to signal retrying with no inlining.
+  // Note, changing the state ensures that we are not going to cache out.
+  ProgramStateRef NewNodeState =3D BeforeProcessingCall->getState();
+  NewNodeState =3D NewNodeState->set<ReplayWithoutInlining>((void*)CE);
+
+  // Make the new node a successor of BeforeProcessingCall.
+  bool IsNew =3D false;
+  ExplodedNode *NewNode =3D G.getNode(NewNodeLoc, NewNodeState, false, &Is=
New);
+  // We cached out at this point. Caching out is common due to us backtrac=
king
+  // from the inlined function, which might spawn several paths.
+  if (!IsNew)
+    return true;
+
+  NewNode->addPredecessor(BeforeProcessingCall, G);
+
+  // Add the new node to the work list.
+  Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
+                                  CalleeSF->getIndex());
+  NumTimesRetriedWithoutInlining++;
+  return true;
+}
+
+/// Block entrance.  (Update counters).
+void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
+                                         NodeBuilderWithSinks &nodeBuilder=
) {
  =20
   // FIXME: Refactor this into a checker.
-  const CFGBlock *block =3D nodeBuilder.getProgramPoint().getBlock();
-  ExplodedNode *pred =3D nodeBuilder.getPredecessor();
+  ExplodedNode *pred =3D nodeBuilder.getContext().getPred();
  =20
-  if (nodeBuilder.getBlockCounter().getNumVisited(
-                       pred->getLocationContext()->getCurrentStackFrame(),=20
-                       block->getBlockID()) >=3D AMgr.getMaxVisit()) {
+  if (nodeBuilder.getContext().getCurrentBlockCount() >=3D AMgr.getMaxVisi=
t()) {
     static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
-    nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
+    const ExplodedNode *Sink =3D
+                   nodeBuilder.generateNode(pred->getState(), pred, &tag, =
true);
+
+    // Check if we stopped at the top level function or not.
+    // Root node should have the location context of the top most function.
+    const LocationContext *CalleeLC =3D pred->getLocation().getLocationCon=
text();
+    const LocationContext *CalleeSF =3D CalleeLC->getCurrentStackFrame();
+    const LocationContext *RootLC =3D
+                        (*G.roots_begin())->getLocation().getLocationConte=
xt();
+    if (RootLC->getCurrentStackFrame() !=3D CalleeSF) {
+      Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl=
());
+
+      // Re-run the call evaluation without inlining it, by storing the
+      // no-inlining policy in the state and enqueuing the new work item on
+      // the list. Replay should almost never fail. Use the stats to catch=
 it
+      // if it does.
+      if ((!AMgr.NoRetryExhausted && replayWithoutInlining(pred, CalleeLC)=
))
+        return;
+      NumMaxBlockCountReachedInInlined++;
+    } else
+      NumMaxBlockCountReached++;
+
+    // Make sink nodes as exhausted(for stats) only if retry failed.
+    Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
   }
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-// Generic node creation.
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
-ExplodedNode *ExprEngine::MakeNode(ExplodedNodeSet &Dst, const Stmt *S,
-                                   ExplodedNode *Pred, const ProgramState =
*St,
-                                   ProgramPoint::Kind K,
-                                   const ProgramPointTag *tag) {
-  assert (Builder && "StmtNodeBuilder not present.");
-  SaveAndRestore<const ProgramPointTag*> OldTag(Builder->Tag);
-  Builder->Tag =3D tag;
-  return Builder->MakeNode(Dst, S, Pred, St, K);
-}
-
-//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Branch processing.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-const ProgramState *ExprEngine::MarkBranch(const ProgramState *state,
-                                        const Stmt *Terminator,
-                                        bool branchTaken) {
+ProgramStateRef ExprEngine::MarkBranch(ProgramStateRef state,
+                                           const Stmt *Terminator,
+                                           const LocationContext *LCtx,
+                                           bool branchTaken) {
=20
   switch (Terminator->getStmtClass()) {
     default:
@@ -867,7 +1098,7 @@
                        (Op =3D=3D BO_LOr && !branchTaken)
                        ? B->getRHS() : B->getLHS();
=20
-      return state->BindExpr(B, UndefinedVal(Ex));
+      return state->BindExpr(B, LCtx, UndefinedVal(Ex));
     }
=20
     case Stmt::BinaryConditionalOperatorClass:
@@ -885,7 +1116,7 @@
       else
         Ex =3D C->getFalseExpr();
=20
-      return state->BindExpr(C, UndefinedVal(Ex));
+      return state->BindExpr(C, LCtx, UndefinedVal(Ex));
     }
=20
     case Stmt::ChooseExprClass: { // ?:
@@ -893,7 +1124,7 @@
       const ChooseExpr *C =3D cast<ChooseExpr>(Terminator);
=20
       const Expr *Ex =3D branchTaken ? C->getLHS() : C->getRHS();
-      return state->BindExpr(C, UndefinedVal(Ex));
+      return state->BindExpr(C, LCtx, UndefinedVal(Ex));
     }
   }
 }
@@ -904,8 +1135,9 @@
 /// This function returns the SVal bound to Condition->IgnoreCasts if all =
the
 //  cast(s) did was sign-extend the original value.
 static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
-                                const ProgramState *state,
+                                ProgramStateRef state,
                                 const Stmt *Condition,
+                                const LocationContext *LCtx,
                                 ASTContext &Ctx) {
=20
   const Expr *Ex =3D dyn_cast<Expr>(Condition);
@@ -936,15 +1168,22 @@
   if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
     return UnknownVal();
=20
-  return state->getSVal(Ex);
+  return state->getSVal(Ex, LCtx);
 }
=20
 void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
-                                 BranchNodeBuilder& builder) {
+                               NodeBuilderContext& BldCtx,
+                               ExplodedNode *Pred,
+                               ExplodedNodeSet &Dst,
+                               const CFGBlock *DstT,
+                               const CFGBlock *DstF) {
+  currentBuilderContext =3D &BldCtx;
=20
   // Check for NULL conditions; e.g. "for(;;)"
   if (!Condition) {
-    builder.markInfeasible(false);
+    BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
+    NullCondBldr.markInfeasible(false);
+    NullCondBldr.generateNode(Pred->getState(), true, Pred);
     return;
   }
=20
@@ -952,65 +1191,84 @@
                                 Condition->getLocStart(),
                                 "Error evaluating branch");
=20
-  getCheckerManager().runCheckersForBranchCondition(Condition, builder, *t=
his);
-
-  // If the branch condition is undefined, return;
-  if (!builder.isFeasible(true) && !builder.isFeasible(false))
+  ExplodedNodeSet CheckersOutSet;
+  getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOut=
Set,
+                                                    Pred, *this);
+  // We generated only sinks.
+  if (CheckersOutSet.empty())
     return;
=20
-  const ProgramState *PrevState =3D builder.getState();
-  SVal X =3D PrevState->getSVal(Condition);
+  BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
+  for (NodeBuilder::iterator I =3D CheckersOutSet.begin(),
+                             E =3D CheckersOutSet.end(); E !=3D I; ++I) {
+    ExplodedNode *PredI =3D *I;
=20
-  if (X.isUnknownOrUndef()) {
-    // Give it a chance to recover from unknown.
-    if (const Expr *Ex =3D dyn_cast<Expr>(Condition)) {
-      if (Ex->getType()->isIntegerType()) {
-        // Try to recover some path-sensitivity.  Right now casts of symbo=
lic
-        // integers that promote their values are currently not tracked we=
ll.
-        // If 'Condition' is such an expression, try and recover the
-        // underlying value and use that instead.
-        SVal recovered =3D RecoverCastedSymbol(getStateManager(),
-                                             builder.getState(), Condition,
-                                             getContext());
+    if (PredI->isSink())
+      continue;
=20
-        if (!recovered.isUnknown()) {
-          X =3D recovered;
+    ProgramStateRef PrevState =3D Pred->getState();
+    SVal X =3D PrevState->getSVal(Condition, Pred->getLocationContext());
+
+    if (X.isUnknownOrUndef()) {
+      // Give it a chance to recover from unknown.
+      if (const Expr *Ex =3D dyn_cast<Expr>(Condition)) {
+        if (Ex->getType()->isIntegerType()) {
+          // Try to recover some path-sensitivity.  Right now casts of sym=
bolic
+          // integers that promote their values are currently not tracked =
well.
+          // If 'Condition' is such an expression, try and recover the
+          // underlying value and use that instead.
+          SVal recovered =3D RecoverCastedSymbol(getStateManager(),
+                                               PrevState, Condition,
+                                               Pred->getLocationContext(),
+                                               getContext());
+
+          if (!recovered.isUnknown()) {
+            X =3D recovered;
+          }
         }
       }
     }
+   =20
+    const LocationContext *LCtx =3D PredI->getLocationContext();
+
     // If the condition is still unknown, give up.
     if (X.isUnknownOrUndef()) {
-      builder.generateNode(MarkBranch(PrevState, Term, true), true);
-      builder.generateNode(MarkBranch(PrevState, Term, false), false);
-      return;
+      builder.generateNode(MarkBranch(PrevState, Term, LCtx, true),
+                           true, PredI);
+      builder.generateNode(MarkBranch(PrevState, Term, LCtx, false),
+                           false, PredI);
+      continue;
+    }
+
+    DefinedSVal V =3D cast<DefinedSVal>(X);
+
+    // Process the true branch.
+    if (builder.isFeasible(true)) {
+      if (ProgramStateRef state =3D PrevState->assume(V, true))
+        builder.generateNode(MarkBranch(state, Term, LCtx, true),
+                             true, PredI);
+      else
+        builder.markInfeasible(true);
+    }
+
+    // Process the false branch.
+    if (builder.isFeasible(false)) {
+      if (ProgramStateRef state =3D PrevState->assume(V, false))
+        builder.generateNode(MarkBranch(state, Term, LCtx, false),
+                             false, PredI);
+      else
+        builder.markInfeasible(false);
     }
   }
-
-  DefinedSVal V =3D cast<DefinedSVal>(X);
-
-  // Process the true branch.
-  if (builder.isFeasible(true)) {
-    if (const ProgramState *state =3D PrevState->assume(V, true))
-      builder.generateNode(MarkBranch(state, Term, true), true);
-    else
-      builder.markInfeasible(true);
-  }
-
-  // Process the false branch.
-  if (builder.isFeasible(false)) {
-    if (const ProgramState *state =3D PrevState->assume(V, false))
-      builder.generateNode(MarkBranch(state, Term, false), false);
-    else
-      builder.markInfeasible(false);
-  }
+  currentBuilderContext =3D 0;
 }
=20
 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
 ///  nodes by processing the 'effects' of a computed goto jump.
 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
=20
-  const ProgramState *state =3D builder.getState();
-  SVal V =3D state->getSVal(builder.getTarget());
+  ProgramStateRef state =3D builder.getState();
+  SVal V =3D state->getSVal(builder.getTarget(), builder.getLocationContex=
t());
=20
   // Three possibilities:
   //
@@ -1051,18 +1309,20 @@
=20
 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
 ///  nodes when the control reaches the end of a function.
-void ExprEngine::processEndOfFunction(EndOfFunctionNodeBuilder& builder) {
-  StateMgr.EndPath(builder.getState());
-  getCheckerManager().runCheckersForEndPath(builder, *this);
+void ExprEngine::processEndOfFunction(NodeBuilderContext& BC) {
+  StateMgr.EndPath(BC.Pred->getState());
+  ExplodedNodeSet Dst;
+  getCheckerManager().runCheckersForEndPath(BC, Dst, *this);
+  Engine.enqueueEndOfFunction(Dst);
 }
=20
 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
 ///  nodes by processing the 'effects' of a switch statement.
 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
   typedef SwitchNodeBuilder::iterator iterator;
-  const ProgramState *state =3D builder.getState();
+  ProgramStateRef state =3D builder.getState();
   const Expr *CondE =3D builder.getCondition();
-  SVal  CondV_untested =3D state->getSVal(CondE);
+  SVal  CondV_untested =3D state->getSVal(CondE, builder.getLocationContex=
t());
=20
   if (CondV_untested.isUndef()) {
     //ExplodedNode* N =3D builder.generateDefaultCaseNode(state, true);
@@ -1073,7 +1333,7 @@
   }
   DefinedOrUnknownSVal CondV =3D cast<DefinedOrUnknownSVal>(CondV_untested=
);
=20
-  const ProgramState *DefaultSt =3D state;
+  ProgramStateRef DefaultSt =3D state;
  =20
   iterator I =3D builder.begin(), EI =3D builder.end();
   bool defaultIsFeasible =3D I =3D=3D EI;
@@ -1106,7 +1366,7 @@
                                                CondV, CaseVal);
=20
       // Now "assume" that the case matches.
-      if (const ProgramState *stateNew =3D state->assume(Res, true)) {
+      if (ProgramStateRef stateNew =3D state->assume(Res, true)) {
         builder.generateCaseStmtNode(I, stateNew);
=20
         // If CondV evaluates to a constant, then we know that this
@@ -1119,7 +1379,7 @@
       // Now "assume" that the case doesn't match.  Add this state
       // to the default state (if it is feasible).
       if (DefaultSt) {
-        if (const ProgramState *stateNew =3D DefaultSt->assume(Res, false)=
) {
+        if (ProgramStateRef stateNew =3D DefaultSt->assume(Res, false)) {
           defaultIsFeasible =3D true;
           DefaultSt =3D stateNew;
         }
@@ -1166,7 +1426,10 @@
 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
                                         ExplodedNode *Pred,
                                         ExplodedNodeSet &Dst) {
-  const ProgramState *state =3D Pred->getState();
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
+
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
=20
   if (const VarDecl *VD =3D dyn_cast<VarDecl>(D)) {
     assert(Ex->isLValue());
@@ -1181,22 +1444,29 @@
         V =3D UnknownVal();
     }
=20
-    MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
-             ProgramPoint::PostLValueKind);
+    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
+                      ProgramPoint::PostLValueKind);
     return;
   }
   if (const EnumConstantDecl *ED =3D dyn_cast<EnumConstantDecl>(D)) {
     assert(!Ex->isLValue());
     SVal V =3D svalBuilder.makeIntVal(ED->getInitVal());
-    MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V));
+    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
     return;
   }
   if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D)) {
     SVal V =3D svalBuilder.getFunctionPointer(FD);
-    MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
-             ProgramPoint::PostLValueKind);
+    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
+                      ProgramPoint::PostLValueKind);
     return;
   }
+  if (isa<FieldDecl>(D)) {
+    // FIXME: Compute lvalue of fields.
+    Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, UnknownVal()),
+		      false, 0, ProgramPoint::PostLValueKind);
+    return;
+  }
+
   assert (false &&
           "ValueDecl support for this ValueDecl not implemented.");
 }
@@ -1213,24 +1483,33 @@
   ExplodedNodeSet checkerPreStmt;
   getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this=
);
=20
+  StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currentBuilderContext);
+
   for (ExplodedNodeSet::iterator it =3D checkerPreStmt.begin(),
                                  ei =3D checkerPreStmt.end(); it !=3D ei; =
++it) {
-    const ProgramState *state =3D (*it)->getState();
-    SVal V =3D state->getLValue(A->getType(), state->getSVal(Idx),
-                              state->getSVal(Base));
+    const LocationContext *LCtx =3D (*it)->getLocationContext();
+    ProgramStateRef state =3D (*it)->getState();
+    SVal V =3D state->getLValue(A->getType(),
+                              state->getSVal(Idx, LCtx),
+                              state->getSVal(Base, LCtx));
     assert(A->isLValue());
-    MakeNode(Dst, A, *it, state->BindExpr(A, V), ProgramPoint::PostLValueK=
ind);
+    Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V),
+                      false, 0, ProgramPoint::PostLValueKind);
   }
 }
=20
 /// VisitMemberExpr - Transfer function for member expressions.
 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
-                                 ExplodedNodeSet &Dst) {
+                                 ExplodedNodeSet &TopDst) {
=20
+  StmtNodeBuilder Bldr(Pred, TopDst, *currentBuilderContext);
+  ExplodedNodeSet Dst;
   Decl *member =3D M->getMemberDecl();
   if (VarDecl *VD =3D dyn_cast<VarDecl>(member)) {
     assert(M->isLValue());
+    Bldr.takeNodes(Pred);
     VisitCommonDeclRefExpr(M, VD, Pred, Dst);
+    Bldr.addNodes(Dst);
     return;
   }
  =20
@@ -1239,15 +1518,16 @@
     return;
=20
   Expr *baseExpr =3D M->getBase()->IgnoreParens();
-  const ProgramState *state =3D Pred->getState();
-  SVal baseExprVal =3D state->getSVal(baseExpr);
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
+  SVal baseExprVal =3D state->getSVal(baseExpr, Pred->getLocationContext()=
);
   if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
       isa<nonloc::CompoundVal>(baseExprVal) ||
       // FIXME: This can originate by conjuring a symbol for an unknown
       // temporary struct object, see test/Analysis/fields.c:
       // (p =3D getit()).x
       isa<nonloc::SymbolVal>(baseExprVal)) {
-    MakeNode(Dst, M, Pred, state->BindExpr(M, UnknownVal()));
+    Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, UnknownVal()));
     return;
   }
=20
@@ -1258,9 +1538,13 @@
   // For all other cases, compute an lvalue.   =20
   SVal L =3D state->getLValue(field, baseExprVal);
   if (M->isLValue())
-    MakeNode(Dst, M, Pred, state->BindExpr(M, L), ProgramPoint::PostLValue=
Kind);
-  else
-    evalLoad(Dst, M, Pred, state, L);
+    Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), false, 0,
+                      ProgramPoint::PostLValueKind);
+  else {
+    Bldr.takeNodes(Pred);
+    evalLoad(Dst, M, M, Pred, state, L);
+    Bldr.addNodes(Dst);
+  }
 }
=20
 /// evalBind - Handle the semantics of binding a value to a specific locat=
ion.
@@ -1272,12 +1556,17 @@
   // Do a previsit of the bind.
   ExplodedNodeSet CheckedSet;
   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
-                                         StoreE, *this);
+                                         StoreE, *this,
+                                         ProgramPoint::PostStmtKind);
=20
+  ExplodedNodeSet TmpDst;
+  StmtNodeBuilder Bldr(CheckedSet, TmpDst, *currentBuilderContext);
+
+  const LocationContext *LC =3D Pred->getLocationContext();
   for (ExplodedNodeSet::iterator I =3D CheckedSet.begin(), E =3D CheckedSe=
t.end();
        I!=3DE; ++I) {
-
-    const ProgramState *state =3D (*I)->getState();
+    ExplodedNode *PredI =3D *I;
+    ProgramStateRef state =3D PredI->getState();
=20
     if (atDeclInit) {
       const VarRegion *VR =3D
@@ -1288,8 +1577,15 @@
       state =3D state->bindLoc(location, Val);
     }
=20
-    MakeNode(Dst, StoreE, *I, state);
+    const MemRegion *LocReg =3D 0;
+    if (loc::MemRegionVal *LocRegVal =3D dyn_cast<loc::MemRegionVal>(&loca=
tion))
+      LocReg =3D LocRegVal->getRegion();
+
+    const ProgramPoint L =3D PostStore(StoreE, LC, LocReg, 0);
+    Bldr.generateNode(L, PredI, state, false);
   }
+
+  Dst.insert(TmpDst);
 }
=20
 /// evalStore - Handle the semantics of a store via an assignment.
@@ -1303,24 +1599,19 @@
 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
                              const Expr *LocationE,
                              ExplodedNode *Pred,
-                             const ProgramState *state, SVal location, SVa=
l Val,
+                             ProgramStateRef state, SVal location, SVal Va=
l,
                              const ProgramPointTag *tag) {
-
-  assert(Builder && "StmtNodeBuilder must be defined.");
-
   // Proceed with the store.  We use AssignE as the anchor for the PostSto=
re
   // ProgramPoint if it is non-NULL, and LocationE otherwise.
   const Expr *StoreE =3D AssignE ? AssignE : LocationE;
=20
   if (isa<loc::ObjCPropRef>(location)) {
-    loc::ObjCPropRef prop =3D cast<loc::ObjCPropRef>(location);
-    return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(),
-                                               StoreE, Val), Pred, Dst);
+    assert(false);
   }
=20
   // Evaluate the location (checks for bad dereferences).
   ExplodedNodeSet Tmp;
-  evalLocation(Tmp, LocationE, Pred, state, location, tag, false);
+  evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
=20
   if (Tmp.empty())
     return;
@@ -1328,24 +1619,21 @@
   if (location.isUndef())
     return;
=20
-  SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind,
-                                                   ProgramPoint::PostStore=
Kind);
-
   for (ExplodedNodeSet::iterator NI=3DTmp.begin(), NE=3DTmp.end(); NI!=3DN=
E; ++NI)
-    evalBind(Dst, StoreE, *NI, location, Val);
+    evalBind(Dst, StoreE, *NI, location, Val, false);
 }
=20
-void ExprEngine::evalLoad(ExplodedNodeSet &Dst, const Expr *Ex,
-                            ExplodedNode *Pred,
-                            const ProgramState *state, SVal location,
-                            const ProgramPointTag *tag, QualType LoadTy) {
+void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
+                          const Expr *NodeEx,
+                          const Expr *BoundEx,
+                          ExplodedNode *Pred,
+                          ProgramStateRef state,
+                          SVal location,
+                          const ProgramPointTag *tag,
+                          QualType LoadTy)
+{
   assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
-
-  if (isa<loc::ObjCPropRef>(location)) {
-    loc::ObjCPropRef prop =3D cast<loc::ObjCPropRef>(location);
-    return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex),
-                            Pred, Dst);
-  }
+  assert(!isa<loc::ObjCPropRef>(location));
=20
   // Are we loading from a region?  This actually results in two loads; one
   // to fetch the address of the referenced value and one to fetch the
@@ -1358,72 +1646,84 @@
       static SimpleProgramPointTag
              loadReferenceTag("ExprEngine : Load Reference");
       ExplodedNodeSet Tmp;
-      evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag,
+      evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
+                     location, &loadReferenceTag,
                      getContext().getPointerType(RT->getPointeeType()));
=20
       // Perform the load from the referenced value.
       for (ExplodedNodeSet::iterator I=3DTmp.begin(), E=3DTmp.end() ; I!=
=3DE; ++I) {
         state =3D (*I)->getState();
-        location =3D state->getSVal(Ex);
-        evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy);
+        location =3D state->getSVal(BoundEx, (*I)->getLocationContext());
+        evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, Loa=
dTy);
       }
       return;
     }
   }
=20
-  evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy);
+  evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
 }
=20
-void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex,
-                                  ExplodedNode *Pred,
-                                  const ProgramState *state, SVal location,
-                                  const ProgramPointTag *tag, QualType Loa=
dTy) {
-
+void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
+                                const Expr *NodeEx,
+                                const Expr *BoundEx,
+                                ExplodedNode *Pred,
+                                ProgramStateRef state,
+                                SVal location,
+                                const ProgramPointTag *tag,
+                                QualType LoadTy) {
+  assert(NodeEx);
+  assert(BoundEx);
   // Evaluate the location (checks for bad dereferences).
   ExplodedNodeSet Tmp;
-  evalLocation(Tmp, Ex, Pred, state, location, tag, true);
-
+  evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
   if (Tmp.empty())
     return;
=20
+  StmtNodeBuilder Bldr(Tmp, Dst, *currentBuilderContext);
   if (location.isUndef())
     return;
=20
-  SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind);
-
   // Proceed with the load.
   for (ExplodedNodeSet::iterator NI=3DTmp.begin(), NE=3DTmp.end(); NI!=3DN=
E; ++NI) {
     state =3D (*NI)->getState();
+    const LocationContext *LCtx =3D (*NI)->getLocationContext();
=20
     if (location.isUnknown()) {
       // This is important.  We must nuke the old binding.
-      MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()),
-               ProgramPoint::PostLoadKind, tag);
+      Bldr.generateNode(NodeEx, *NI,
+                        state->BindExpr(BoundEx, LCtx, UnknownVal()),
+                        false, tag,
+                        ProgramPoint::PostLoadKind);
     }
     else {
       if (LoadTy.isNull())
-        LoadTy =3D Ex->getType();
+        LoadTy =3D BoundEx->getType();
       SVal V =3D state->getSVal(cast<Loc>(location), LoadTy);
-      MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V),
-               ProgramPoint::PostLoadKind, tag);
+      Bldr.generateNode(NodeEx, *NI,
+                        state->bindExprAndLocation(BoundEx, LCtx, location=
, V),
+                        false, tag, ProgramPoint::PostLoadKind);
     }
   }
 }
=20
-void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S,
-                                ExplodedNode *Pred,
-                                const ProgramState *state, SVal location,
-                                const ProgramPointTag *tag, bool isLoad) {
+void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
+                              const Stmt *NodeEx,
+                              const Stmt *BoundEx,
+                              ExplodedNode *Pred,
+                              ProgramStateRef state,
+                              SVal location,
+                              const ProgramPointTag *tag,
+                              bool isLoad) {
+  StmtNodeBuilder BldrTop(Pred, Dst, *currentBuilderContext);
   // Early checks for performance reason.
   if (location.isUnknown()) {
-    Dst.Add(Pred);
     return;
   }
=20
   ExplodedNodeSet Src;
-  if (Pred->getState() =3D=3D state) {
-    Src.Add(Pred);
-  } else {
+  BldrTop.takeNodes(Pred);
+  StmtNodeBuilder Bldr(Pred, Src, *currentBuilderContext);
+  if (Pred->getState() !=3D state) {
     // Associate this new state with an ExplodedNode.
     // FIXME: If I pass null tag, the graph is incorrect, e.g for
     //   int *p;
@@ -1435,88 +1735,12 @@
    =20
     // FIXME: why is 'tag' not used instead of etag?
     static SimpleProgramPointTag etag("ExprEngine: Location");
-
-    ExplodedNode *N =3D Builder->generateNode(S, state, Pred, &etag);
-    Src.Add(N ? N : Pred);
+    Bldr.generateNode(NodeEx, Pred, state, false, &etag);
   }
-  getCheckerManager().runCheckersForLocation(Dst, Src, location, isLoad, S,
-                                             *this);
-}
-
-bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE,=20
-                              ExplodedNode *Pred) {
-  return false;
- =20
-  // Inlining isn't correct right now because we:
-  // (a) don't generate CallExit nodes.
-  // (b) we need a way to postpone doing post-visits of CallExprs until
-  // the CallExit.  This means we need CallExits for the non-inline
-  // cases as well.
- =20
-#if 0
-  const ProgramState *state =3D Pred->getState();
-  const Expr *Callee =3D CE->getCallee();
-  SVal L =3D state->getSVal(Callee);
- =20
-  const FunctionDecl *FD =3D L.getAsFunctionDecl();
-  if (!FD)
-    return false;
-
-  // Specially handle CXXMethods.
-  const CXXMethodDecl *methodDecl =3D 0;
- =20
-  switch (CE->getStmtClass()) {
-    default: break;
-    case Stmt::CXXOperatorCallExprClass: {
-      const CXXOperatorCallExpr *opCall =3D cast<CXXOperatorCallExpr>(CE);
-      methodDecl =3D=20
-        dyn_cast_or_null<CXXMethodDecl>(opCall->getCalleeDecl());
-      break;
-    }
-    case Stmt::CXXMemberCallExprClass: {
-      const CXXMemberCallExpr *memberCall =3D cast<CXXMemberCallExpr>(CE);
-      const MemberExpr *memberExpr =3D=20
-        cast<MemberExpr>(memberCall->getCallee()->IgnoreParens());
-      methodDecl =3D cast<CXXMethodDecl>(memberExpr->getMemberDecl());
-      break;
-    }
-  }
-     =20
- =20
- =20
- =20
-  // Check if the function definition is in the same translation unit.
-  if (FD->hasBody(FD)) {
-    const StackFrameContext *stackFrame =3D=20
-      AMgr.getStackFrame(AMgr.getAnalysisContext(FD),=20
-                         Pred->getLocationContext(),
-                         CE, Builder->getBlock(), Builder->getIndex());
-    // Now we have the definition of the callee, create a CallEnter node.
-    CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
-
-    ExplodedNode *N =3D Builder->generateNode(Loc, state, Pred);
-    Dst.Add(N);
-    return true;
-  }
-
-  // Check if we can find the function definition in other translation uni=
ts.
-  if (AMgr.hasIndexer()) {
-    AnalysisContext *C =3D AMgr.getAnalysisContextInAnotherTU(FD);
-    if (C =3D=3D 0)
-      return false;
-    const StackFrameContext *stackFrame =3D=20
-      AMgr.getStackFrame(C, Pred->getLocationContext(),
-                         CE, Builder->getBlock(), Builder->getIndex());
-    CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
-    ExplodedNode *N =3D Builder->generateNode(Loc, state, Pred);
-    Dst.Add(N);
-    return true;
-  }
- =20
-  // Generate the CallExit node.
-
-  return false;
-#endif
+  ExplodedNodeSet Tmp;
+  getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
+                                             NodeEx, BoundEx, *this);
+  BldrTop.addNodes(Tmp);
 }
=20
 std::pair<const ProgramPointTag *, const ProgramPointTag*>
@@ -1528,108 +1752,67 @@
 }
=20
 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &=
Src,
-                                     const Expr *Ex) {
- =20
+                                   const Expr *Ex) {
+  StmtNodeBuilder Bldr(Src, Dst, *currentBuilderContext);
  =20
   for (ExplodedNodeSet::iterator I=3DSrc.begin(), E=3DSrc.end(); I!=3DE; +=
+I) {
     ExplodedNode *Pred =3D *I;
-
     // Test if the previous node was as the same expression.  This can hap=
pen
     // when the expression fails to evaluate to anything meaningful and
     // (as an optimization) we don't generate a node.
     ProgramPoint P =3D Pred->getLocation();
     if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() !=3D Ex) {
-      Dst.Add(Pred);
       continue;
     }
=20
-    const ProgramState *state =3D Pred->getState();
-    SVal V =3D state->getSVal(Ex);
-    if (nonloc::SymExprVal *SEV =3D dyn_cast<nonloc::SymExprVal>(&V)) {
+    ProgramStateRef state =3D Pred->getState();
+    SVal V =3D state->getSVal(Ex, Pred->getLocationContext());
+    nonloc::SymbolVal *SEV =3D dyn_cast<nonloc::SymbolVal>(&V);
+    if (SEV && SEV->isExpression()) {
       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &ta=
gs =3D
         getEagerlyAssumeTags();
=20
       // First assume that the condition is true.
-      if (const ProgramState *StateTrue =3D state->assume(*SEV, true)) {
+      if (ProgramStateRef StateTrue =3D state->assume(*SEV, true)) {
         SVal Val =3D svalBuilder.makeIntVal(1U, Ex->getType());       =20
-        StateTrue =3D StateTrue->BindExpr(Ex, Val);
-        Dst.Add(Builder->generateNode(Ex, StateTrue, Pred, tags.first));
+        StateTrue =3D StateTrue->BindExpr(Ex, Pred->getLocationContext(), =
Val);
+        Bldr.generateNode(Ex, Pred, StateTrue, false, tags.first);
       }
=20
       // Next, assume that the condition is false.
-      if (const ProgramState *StateFalse =3D state->assume(*SEV, false)) {
+      if (ProgramStateRef StateFalse =3D state->assume(*SEV, false)) {
         SVal Val =3D svalBuilder.makeIntVal(0U, Ex->getType());
-        StateFalse =3D StateFalse->BindExpr(Ex, Val);
-        Dst.Add(Builder->generateNode(Ex, StateFalse, Pred, tags.second));
+        StateFalse =3D StateFalse->BindExpr(Ex, Pred->getLocationContext()=
, Val);
+        Bldr.generateNode(Ex, Pred, StateFalse, false, tags.second);
       }
     }
-    else
-      Dst.Add(Pred);
   }
 }
=20
 void ExprEngine::VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred,
-                                ExplodedNodeSet &Dst) {
-  VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred,=
 Dst);
-}
+                              ExplodedNodeSet &Dst) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
+  // We have processed both the inputs and the outputs.  All of the outputs
+  // should evaluate to Locs.  Nuke all of their values.
=20
-void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt *A,
-                                             AsmStmt::const_outputs_iterat=
or I,
-                                             AsmStmt::const_outputs_iterat=
or E,
-                                     ExplodedNode *Pred, ExplodedNodeSet &=
Dst) {
-  if (I =3D=3D E) {
-    VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, =
Dst);
-    return;
+  // FIXME: Some day in the future it would be nice to allow a "plug-in"
+  // which interprets the inline asm and stores proper results in the
+  // outputs.
+
+  ProgramStateRef state =3D Pred->getState();
+
+  for (AsmStmt::const_outputs_iterator OI =3D A->begin_outputs(),
+       OE =3D A->end_outputs(); OI !=3D OE; ++OI) {
+    SVal X =3D state->getSVal(*OI, Pred->getLocationContext());
+    assert (!isa<NonLoc>(X));  // Should be an Lval, or unknown, undef.
+
+    if (isa<Loc>(X))
+      state =3D state->bindLoc(cast<Loc>(X), UnknownVal());
   }
=20
-  ExplodedNodeSet Tmp;
-  Visit(*I, Pred, Tmp);
-  ++I;
-
-  for (ExplodedNodeSet::iterator NI =3D Tmp.begin(), NE =3D Tmp.end();NI !=
=3D NE;++NI)
-    VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst);
+  Bldr.generateNode(A, Pred, state);
 }
=20
-void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt *A,
-                                            AsmStmt::const_inputs_iterator=
 I,
-                                            AsmStmt::const_inputs_iterator=
 E,
-                                            ExplodedNode *Pred,
-                                            ExplodedNodeSet &Dst) {
-  if (I =3D=3D E) {
-
-    // We have processed both the inputs and the outputs.  All of the outp=
uts
-    // should evaluate to Locs.  Nuke all of their values.
-
-    // FIXME: Some day in the future it would be nice to allow a "plug-in"
-    // which interprets the inline asm and stores proper results in the
-    // outputs.
-
-    const ProgramState *state =3D Pred->getState();
-
-    for (AsmStmt::const_outputs_iterator OI =3D A->begin_outputs(),
-                                   OE =3D A->end_outputs(); OI !=3D OE; ++=
OI) {
-
-      SVal X =3D state->getSVal(*OI);
-      assert (!isa<NonLoc>(X));  // Should be an Lval, or unknown, undef.
-
-      if (isa<Loc>(X))
-        state =3D state->bindLoc(cast<Loc>(X), UnknownVal());
-    }
-
-    MakeNode(Dst, A, Pred, state);
-    return;
-  }
-
-  ExplodedNodeSet Tmp;
-  Visit(*I, Pred, Tmp);
-
-  ++I;
-
-  for (ExplodedNodeSet::iterator NI =3D Tmp.begin(), NE =3D Tmp.end(); NI!=
=3DNE; ++NI)
-    VisitAsmStmtHelperInputs(A, I, E, *NI, Dst);
-}
-
-
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Visualization.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1694,6 +1877,10 @@
         Out << "CallExit";
         break;
=20
+      case ProgramPoint::EpsilonKind:
+        Out << "Epsilon Point";
+        break;
+
       default: {
         if (StmtPoint *L =3D dyn_cast<StmtPoint>(&Loc)) {
           const Stmt *S =3D L->getStmt();
@@ -1811,10 +1998,10 @@
       }
     }
=20
-    const ProgramState *state =3D N->getState();
-    Out << "\\|StateID: " << (void*) state
+    ProgramStateRef state =3D N->getState();
+    Out << "\\|StateID: " << (void*) state.getPtr()
         << " NodeID: " << (void*) N << "\\|";
-    state->printDOT(Out, *N->getLocationContext()->getCFG());
+    state->printDOT(Out);
=20
     Out << "\\l";   =20
=20
@@ -1852,9 +2039,7 @@
     // Iterate through the reports and get their nodes.
     for (BugReporter::EQClasses_iterator
            EI =3D BR.EQClasses_begin(), EE =3D BR.EQClasses_end(); EI !=3D=
 EE; ++EI) {
-      BugReportEquivClass& EQ =3D *EI;
-      const BugReport &R =3D **EQ.begin();
-      ExplodedNode *N =3D const_cast<ExplodedNode*>(R.getErrorNode());
+      ExplodedNode *N =3D const_cast<ExplodedNode*>(EI->begin()->getErrorN=
ode());
       if (N) Src.push_back(N);
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ExprEngineC.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,6 @@
=20
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
-#include "clang/Analysis/Support/SaveAndRestore.h"
=20
 using namespace clang;
 using namespace ento;
@@ -35,38 +34,40 @@
   for (ExplodedNodeSet::iterator it=3DCheckedSet.begin(), ei=3DCheckedSet.=
end();
          it !=3D ei; ++it) {
      =20
-    const ProgramState *state =3D (*it)->getState();
-    SVal LeftV =3D state->getSVal(LHS);
-    SVal RightV =3D state->getSVal(RHS);
+    ProgramStateRef state =3D (*it)->getState();
+    const LocationContext *LCtx =3D (*it)->getLocationContext();
+    SVal LeftV =3D state->getSVal(LHS, LCtx);
+    SVal RightV =3D state->getSVal(RHS, LCtx);
      =20
     BinaryOperator::Opcode Op =3D B->getOpcode();
      =20
     if (Op =3D=3D BO_Assign) {
       // EXPERIMENTAL: "Conjured" symbols.
       // FIXME: Handle structs.
-      if (RightV.isUnknown() ||
-          !getConstraintManager().canReasonAbout(RightV)) {
-        unsigned Count =3D Builder->getCurrentBlockCount();
-        RightV =3D svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Cou=
nt);
+      if (RightV.isUnknown()) {
+        unsigned Count =3D currentBuilderContext->getCurrentBlockCount();
+        RightV =3D svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LCt=
x, Count);
       }
       // Simulate the effects of a "store":  bind the value of the RHS
       // to the L-Value represented by the LHS.
       SVal ExprVal =3D B->isLValue() ? LeftV : RightV;
-      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, ExprVal), LeftV, Rig=
htV);
+      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
+                LeftV, RightV);
       continue;
     }
      =20
     if (!B->isAssignmentOp()) {
+      StmtNodeBuilder Bldr(*it, Tmp2, *currentBuilderContext);
       // Process non-assignments except commas or short-circuited
       // logical expressions (LAnd and LOr).
       SVal Result =3D evalBinOp(state, Op, LeftV, RightV, B->getType());  =
   =20
       if (Result.isUnknown()) {
-        MakeNode(Tmp2, B, *it, state);
+        Bldr.generateNode(B, *it, state);
         continue;
       }       =20
=20
-      state =3D state->BindExpr(B, Result);     =20
-      MakeNode(Tmp2, B, *it, state);
+      state =3D state->BindExpr(B, LCtx, Result);     =20
+      Bldr.generateNode(B, *it, state);
       continue;
     }
      =20
@@ -91,13 +92,14 @@
     // null dereferences, and so on.
     ExplodedNodeSet Tmp;
     SVal location =3D LeftV;
-    evalLoad(Tmp, LHS, *it, state, location);
+    evalLoad(Tmp, B, LHS, *it, state, location);
    =20
     for (ExplodedNodeSet::iterator I =3D Tmp.begin(), E =3D Tmp.end(); I !=
=3D E;
          ++I) {
=20
       state =3D (*I)->getState();
-      SVal V =3D state->getSVal(LHS);
+      const LocationContext *LCtx =3D (*I)->getLocationContext();
+      SVal V =3D state->getSVal(LHS, LCtx);
      =20
       // Get the computation type.
       QualType CTy =3D
@@ -122,16 +124,15 @@
      =20
       SVal LHSVal;
      =20
-      if (Result.isUnknown() ||
-          !getConstraintManager().canReasonAbout(Result)) {
+      if (Result.isUnknown()) {
        =20
-        unsigned Count =3D Builder->getCurrentBlockCount();
+        unsigned Count =3D currentBuilderContext->getCurrentBlockCount();
        =20
         // The symbolic value is actually for the type of the left-hand si=
de
         // expression, not the computation type, as this is the value the
         // LValue on the LHS will bind to.
-        LHSVal =3D svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy,
-                                                  Count);
+        LHSVal =3D svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LCt=
x,
+						  LTy, Count);
        =20
         // However, we need to convert the symbol to the computation type.
         Result =3D svalBuilder.evalCast(LHSVal, CTy, LTy);
@@ -145,9 +146,9 @@
       // In C++, assignment and compound assignment operators return an=20
       // lvalue.
       if (B->isLValue())
-        state =3D state->BindExpr(B, location);
+        state =3D state->BindExpr(B, LCtx, location);
       else
-        state =3D state->BindExpr(B, Result);
+        state =3D state->BindExpr(B, LCtx, Result);
      =20
       evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
     }
@@ -165,8 +166,12 @@
                                        Pred->getLocationContext());
  =20
   ExplodedNodeSet Tmp;
-  MakeNode(Tmp, BE, Pred, Pred->getState()->BindExpr(BE, V),
-           ProgramPoint::PostLValueKind);
+  StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
+  Bldr.generateNode(BE, Pred,
+                    Pred->getState()->BindExpr(BE, Pred->getLocationContex=
t(),
+                                               V),
+                    false, 0,
+                    ProgramPoint::PostLValueKind);
  =20
   // FIXME: Move all post/pre visits to ::Visit().
   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
@@ -178,13 +183,13 @@
   ExplodedNodeSet dstPreStmt;
   getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this=
);
  =20
-  if (CastE->getCastKind() =3D=3D CK_LValueToRValue ||
-      CastE->getCastKind() =3D=3D CK_GetObjCProperty) {
+  if (CastE->getCastKind() =3D=3D CK_LValueToRValue) {
     for (ExplodedNodeSet::iterator I =3D dstPreStmt.begin(), E =3D dstPreS=
tmt.end();
          I!=3DE; ++I) {
       ExplodedNode *subExprNode =3D *I;
-      const ProgramState *state =3D subExprNode->getState();
-      evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex));
+      ProgramStateRef state =3D subExprNode->getState();
+      const LocationContext *LCtx =3D subExprNode->getLocationContext();
+      evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, L=
Ctx));
     }
     return;
   }
@@ -196,6 +201,7 @@
   if (const ExplicitCastExpr *ExCast=3Ddyn_cast_or_null<ExplicitCastExpr>(=
CastE))
     T =3D ExCast->getTypeAsWritten();
  =20
+  StmtNodeBuilder Bldr(dstPreStmt, Dst, *currentBuilderContext);
   for (ExplodedNodeSet::iterator I =3D dstPreStmt.begin(), E =3D dstPreStm=
t.end();
        I !=3D E; ++I) {
    =20
@@ -204,10 +210,7 @@
     switch (CastE->getCastKind()) {
       case CK_LValueToRValue:
         llvm_unreachable("LValueToRValue casts handled earlier.");
-      case CK_GetObjCProperty:
-        llvm_unreachable("GetObjCProperty casts handled earlier.");
       case CK_ToVoid:
-        Dst.Add(Pred);
         continue;
         // The analyzer doesn't do anything special with these casts,
         // since it understands retain/release semantics already.
@@ -215,14 +218,21 @@
       case CK_ARCConsumeObject:
       case CK_ARCReclaimReturnedObject:
       case CK_ARCExtendBlockObject: // Fall-through.
+      case CK_CopyAndAutoreleaseBlockObject:
+        // The analyser can ignore atomic casts for now, although some fut=
ure
+        // checkers may want to make certain that you're not modifying the=
 same
+        // value through atomic and nonatomic pointers.
+      case CK_AtomicToNonAtomic:
+      case CK_NonAtomicToAtomic:
         // True no-ops.
       case CK_NoOp:
       case CK_FunctionToPointerDecay: {
         // Copy the SVal of Ex to CastE.
-        const ProgramState *state =3D Pred->getState();
-        SVal V =3D state->getSVal(Ex);
-        state =3D state->BindExpr(CastE, V);
-        MakeNode(Dst, CastE, Pred, state);
+        ProgramStateRef state =3D Pred->getState();
+        const LocationContext *LCtx =3D Pred->getLocationContext();
+        SVal V =3D state->getSVal(Ex, LCtx);
+        state =3D state->BindExpr(CastE, LCtx, V);
+        Bldr.generateNode(CastE, Pred, state);
         continue;
       }
       case CK_Dependent:
@@ -254,30 +264,76 @@
       case CK_AnyPointerToBlockPointerCast: =20
       case CK_ObjCObjectLValueCast: {
         // Delegate to SValBuilder to process.
-        const ProgramState *state =3D Pred->getState();
-        SVal V =3D state->getSVal(Ex);
+        ProgramStateRef state =3D Pred->getState();
+        const LocationContext *LCtx =3D Pred->getLocationContext();
+        SVal V =3D state->getSVal(Ex, LCtx);
         V =3D svalBuilder.evalCast(V, T, ExTy);
-        state =3D state->BindExpr(CastE, V);
-        MakeNode(Dst, CastE, Pred, state);
+        state =3D state->BindExpr(CastE, LCtx, V);
+        Bldr.generateNode(CastE, Pred, state);
         continue;
       }
       case CK_DerivedToBase:
       case CK_UncheckedDerivedToBase: {
         // For DerivedToBase cast, delegate to the store manager.
-        const ProgramState *state =3D Pred->getState();
-        SVal val =3D state->getSVal(Ex);
+        ProgramStateRef state =3D Pred->getState();
+        const LocationContext *LCtx =3D Pred->getLocationContext();
+        SVal val =3D state->getSVal(Ex, LCtx);
         val =3D getStoreManager().evalDerivedToBase(val, T);
-        state =3D state->BindExpr(CastE, val);
-        MakeNode(Dst, CastE, Pred, state);
+        state =3D state->BindExpr(CastE, LCtx, val);
+        Bldr.generateNode(CastE, Pred, state);
         continue;
       }
-        // Various C++ casts that are not handled yet.
-      case CK_Dynamic:
+      // Handle C++ dyn_cast.
+      case CK_Dynamic: {
+        ProgramStateRef state =3D Pred->getState();
+        const LocationContext *LCtx =3D Pred->getLocationContext();
+        SVal val =3D state->getSVal(Ex, LCtx);
+
+        // Compute the type of the result.
+        QualType resultType =3D CastE->getType();
+        if (CastE->isLValue())
+          resultType =3D getContext().getPointerType(resultType);
+
+        bool Failed =3D false;
+
+        // Check if the value being cast evaluates to 0.
+        if (val.isZeroConstant())
+          Failed =3D true;
+        // Else, evaluate the cast.
+        else
+          val =3D getStoreManager().evalDynamicCast(val, T, Failed);
+
+        if (Failed) {
+          if (T->isReferenceType()) {
+            // A bad_cast exception is thrown if input value is a referenc=
e.
+            // Currently, we model this, by generating a sink.
+            Bldr.generateNode(CastE, Pred, state, true);
+            continue;
+          } else {
+            // If the cast fails on a pointer, bind to 0.
+            state =3D state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
+          }
+        } else {
+          // If we don't know if the cast succeeded, conjure a new symbol.
+          if (val.isUnknown()) {
+            DefinedOrUnknownSVal NewSym =3D svalBuilder.getConjuredSymbolV=
al(NULL,
+                                 CastE, LCtx, resultType,
+                                 currentBuilderContext->getCurrentBlockCou=
nt());
+            state =3D state->BindExpr(CastE, LCtx, NewSym);
+          } else=20
+            // Else, bind to the derived region value.
+            state =3D state->BindExpr(CastE, LCtx, val);
+        }
+        Bldr.generateNode(CastE, Pred, state);
+        continue;
+      }
+      // Various C++ casts that are not handled yet.
       case CK_ToUnion:
       case CK_BaseToDerived:
       case CK_NullToMemberPointer:
       case CK_BaseToDerivedMemberPointer:
       case CK_DerivedToBaseMemberPointer:
+      case CK_ReinterpretMemberPointer:
       case CK_UserDefinedConversion:
       case CK_ConstructorConversion:
       case CK_VectorSplat:
@@ -286,13 +342,12 @@
         QualType resultType =3D CastE->getType();
         if (CastE->isLValue())
           resultType =3D getContext().getPointerType(resultType);
-       =20
-        SVal result =3D
-        svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType,
-                                         Builder->getCurrentBlockCount());
-       =20
-        const ProgramState *state =3D Pred->getState()->BindExpr(CastE, re=
sult);
-        MakeNode(Dst, CastE, Pred, state);
+        const LocationContext *LCtx =3D Pred->getLocationContext();
+        SVal result =3D svalBuilder.getConjuredSymbolVal(NULL, CastE, LCtx,
+                    resultType, currentBuilderContext->getCurrentBlockCoun=
t());
+        ProgramStateRef state =3D Pred->getState()->BindExpr(CastE, LCtx,
+                                                               result);
+        Bldr.generateNode(CastE, Pred, state);
         continue;
       }
     }
@@ -302,18 +357,20 @@
 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
                                           ExplodedNode *Pred,
                                           ExplodedNodeSet &Dst) {
+  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
+
   const InitListExpr *ILE=20
     =3D cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
  =20
-  const ProgramState *state =3D Pred->getState();
-  SVal ILV =3D state->getSVal(ILE);
+  ProgramStateRef state =3D Pred->getState();
+  SVal ILV =3D state->getSVal(ILE, Pred->getLocationContext());
   const LocationContext *LC =3D Pred->getLocationContext();
   state =3D state->bindCompoundLiteral(CL, LC, ILV);
  =20
   if (CL->isLValue())
-    MakeNode(Dst, CL, Pred, state->BindExpr(CL, state->getLValue(CL, LC)));
+    B.generateNode(CL, Pred, state->BindExpr(CL, LC, state->getLValue(CL, =
LC)));
   else
-    MakeNode(Dst, CL, Pred, state->BindExpr(CL, ILV));
+    B.generateNode(CL, Pred, state->BindExpr(CL, LC, ILV));
 }
=20
 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
@@ -326,29 +383,32 @@
   // Assumption: The CFG has one DeclStmt per Decl.
   const Decl *D =3D *DS->decl_begin();
  =20
-  if (!D || !isa<VarDecl>(D))
+  if (!D || !isa<VarDecl>(D)) {
+    //TODO:AZ: remove explicit insertion after refactoring is done.
+    Dst.insert(Pred);
     return;
+  }
  =20
   // FIXME: all pre/post visits should eventually be handled by ::Visit().
   ExplodedNodeSet dstPreVisit;
   getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
  =20
+  StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
   const VarDecl *VD =3D dyn_cast<VarDecl>(D);
- =20
   for (ExplodedNodeSet::iterator I =3D dstPreVisit.begin(), E =3D dstPreVi=
sit.end();
        I!=3DE; ++I) {
     ExplodedNode *N =3D *I;
-    const ProgramState *state =3D N->getState();
+    ProgramStateRef state =3D N->getState();
    =20
     // Decls without InitExpr are not initialized explicitly.
     const LocationContext *LC =3D N->getLocationContext();
    =20
     if (const Expr *InitEx =3D VD->getInit()) {
-      SVal InitVal =3D state->getSVal(InitEx);
+      SVal InitVal =3D state->getSVal(InitEx, Pred->getLocationContext());
      =20
       // We bound the temp obj region to the CXXConstructExpr. Now recover
       // the lazy compound value when the variable is not a reference.
-      if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType()=
 &&=20
+      if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&=20
           !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(Init=
Val)){
         InitVal =3D state->getSVal(cast<loc::MemRegionVal>(InitVal).getReg=
ion());
         assert(isa<nonloc::LazyCompoundVal>(InitVal));
@@ -356,40 +416,46 @@
      =20
       // Recover some path-sensitivity if a scalar value evaluated to
       // UnknownVal.
-      if ((InitVal.isUnknown() ||
-           !getConstraintManager().canReasonAbout(InitVal)) &&
-          !VD->getType()->isReferenceType()) {
-        InitVal =3D svalBuilder.getConjuredSymbolVal(NULL, InitEx,
-                                                   Builder->getCurrentBloc=
kCount());
+      if (InitVal.isUnknown()) {
+	QualType Ty =3D InitEx->getType();
+	if (InitEx->isLValue()) {
+	  Ty =3D getContext().getPointerType(Ty);
+	}
+
+        InitVal =3D svalBuilder.getConjuredSymbolVal(NULL, InitEx, LC, Ty,
+                                 currentBuilderContext->getCurrentBlockCou=
nt());
       }
-     =20
-      evalBind(Dst, DS, N, state->getLValue(VD, LC), InitVal, true);
+      B.takeNodes(N);
+      ExplodedNodeSet Dst2;
+      evalBind(Dst2, DS, N, state->getLValue(VD, LC), InitVal, true);
+      B.addNodes(Dst2);
     }
     else {
-      MakeNode(Dst, DS, N, state->bindDeclWithNoInit(state->getRegion(VD, =
LC)));
+      B.generateNode(DS, N,state->bindDeclWithNoInit(state->getRegion(VD, =
LC)));
     }
   }
 }
=20
 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *P=
red,
                                   ExplodedNodeSet &Dst) {
- =20
   assert(B->getOpcode() =3D=3D BO_LAnd ||
          B->getOpcode() =3D=3D BO_LOr);
- =20
-  const ProgramState *state =3D Pred->getState();
-  SVal X =3D state->getSVal(B);
+
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
+  SVal X =3D state->getSVal(B, LCtx);
   assert(X.isUndef());
  =20
   const Expr *Ex =3D (const Expr*) cast<UndefinedVal>(X).getData();
   assert(Ex);
  =20
   if (Ex =3D=3D B->getRHS()) {
-    X =3D state->getSVal(Ex);
+    X =3D state->getSVal(Ex, LCtx);
    =20
     // Handle undefined values.
     if (X.isUndef()) {
-      MakeNode(Dst, B, Pred, state->BindExpr(B, X));
+      Bldr.generateNode(B, Pred, state->BindExpr(B, LCtx, X));
       return;
     }
    =20
@@ -401,13 +467,15 @@
     // value later when necessary.  We don't have the machinery in place f=
or
     // this right now, and since most logical expressions are used for bra=
nches,
     // the payoff is not likely to be large.  Instead, we do eager evaluat=
ion.
-    if (const ProgramState *newState =3D state->assume(XD, true))
-      MakeNode(Dst, B, Pred,
-               newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType=
())));
+    if (ProgramStateRef newState =3D state->assume(XD, true))
+      Bldr.generateNode(B, Pred,
+               newState->BindExpr(B, LCtx,
+                                  svalBuilder.makeIntVal(1U, B->getType())=
));
    =20
-    if (const ProgramState *newState =3D state->assume(XD, false))
-      MakeNode(Dst, B, Pred,
-               newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType=
())));
+    if (ProgramStateRef newState =3D state->assume(XD, false))
+      Bldr.generateNode(B, Pred,
+               newState->BindExpr(B, LCtx,
+                                  svalBuilder.makeIntVal(0U, B->getType())=
));
   }
   else {
     // We took the LHS expression.  Depending on whether we are '&&' or
@@ -415,15 +483,17 @@
     // the short-circuiting.
     X =3D svalBuilder.makeIntVal(B->getOpcode() =3D=3D BO_LAnd ? 0U : 1U,
                                B->getType());
-    MakeNode(Dst, B, Pred, state->BindExpr(B, X));
+    Bldr.generateNode(B, Pred, state->BindExpr(B, LCtx, X));
   }
 }
=20
 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
                                    ExplodedNode *Pred,
                                    ExplodedNodeSet &Dst) {
+  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
=20
-  const ProgramState *state =3D Pred->getState();
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
   QualType T =3D getContext().getCanonicalType(IE->getType());
   unsigned NumInitElements =3D IE->getNumInits();
  =20
@@ -434,24 +504,27 @@
     // e.g: static int* myArray[] =3D {};
     if (NumInitElements =3D=3D 0) {
       SVal V =3D svalBuilder.makeCompoundVal(T, vals);
-      MakeNode(Dst, IE, Pred, state->BindExpr(IE, V));
+      B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
       return;
     }
    =20
     for (InitListExpr::const_reverse_iterator it =3D IE->rbegin(),
          ei =3D IE->rend(); it !=3D ei; ++it) {
-      vals =3D getBasicVals().consVals(state->getSVal(cast<Expr>(*it)), va=
ls);
+      vals =3D getBasicVals().consVals(state->getSVal(cast<Expr>(*it), LCt=
x),
+                                     vals);
     }
    =20
-    MakeNode(Dst, IE, Pred,
-             state->BindExpr(IE, svalBuilder.makeCompoundVal(T, vals)));
+    B.generateNode(IE, Pred,
+                   state->BindExpr(IE, LCtx,
+                                   svalBuilder.makeCompoundVal(T, vals)));
     return;
   }
  =20
   if (Loc::isLocType(T) || T->isIntegerType()) {
     assert(IE->getNumInits() =3D=3D 1);
     const Expr *initEx =3D IE->getInit(0);
-    MakeNode(Dst, IE, Pred, state->BindExpr(IE, state->getSVal(initEx)));
+    B.generateNode(IE, Pred, state->BindExpr(IE, LCtx,
+                                             state->getSVal(initEx, LCtx))=
);
     return;
   }
  =20
@@ -463,33 +536,35 @@
                                   const Expr *R,
                                   ExplodedNode *Pred,
                                   ExplodedNodeSet &Dst) {
+  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
  =20
-  const ProgramState *state =3D Pred->getState();
-  SVal X =3D state->getSVal(Ex); =20
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
+  SVal X =3D state->getSVal(Ex, LCtx); =20
   assert (X.isUndef()); =20
   const Expr *SE =3D (Expr*) cast<UndefinedVal>(X).getData();
   assert(SE);
-  X =3D state->getSVal(SE);
+  X =3D state->getSVal(SE, LCtx);
  =20
   // Make sure that we invalidate the previous binding.
-  MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true));
+  B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, X, true));
 }
=20
 void ExprEngine::
 VisitOffsetOfExpr(const OffsetOfExpr *OOE,=20
                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
-  Expr::EvalResult Res;
-  if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) {
-    const APSInt &IV =3D Res.Val.getInt();
+  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
+  APSInt IV;
+  if (OOE->EvaluateAsInt(IV, getContext())) {
     assert(IV.getBitWidth() =3D=3D getContext().getTypeSize(OOE->getType()=
));
     assert(OOE->getType()->isIntegerType());
     assert(IV.isSigned() =3D=3D OOE->getType()->isSignedIntegerOrEnumerati=
onType());
     SVal X =3D svalBuilder.makeIntVal(IV);
-    MakeNode(Dst, OOE, Pred, Pred->getState()->BindExpr(OOE, X));
-    return;
+    B.generateNode(OOE, Pred,
+                   Pred->getState()->BindExpr(OOE, Pred->getLocationContex=
t(),
+                                              X));
   }
   // FIXME: Handle the case where __builtin_offsetof is not a constant.
-  Dst.Add(Pred);
 }
=20
=20
@@ -497,6 +572,7 @@
 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
                               ExplodedNode *Pred,
                               ExplodedNodeSet &Dst) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
=20
   QualType T =3D Ex->getTypeOfArgument();
  =20
@@ -506,78 +582,69 @@
      =20
       // FIXME: Add support for VLA type arguments and VLA expressions.
       // When that happens, we should probably refactor VLASizeChecker's c=
ode.
-      Dst.Add(Pred);
       return;
     }
     else if (T->getAs<ObjCObjectType>()) {
       // Some code tries to take the sizeof an ObjCObjectType, relying that
       // the compiler has laid out its representation.  Just report Unknown
       // for these.
-      Dst.Add(Pred);
       return;
     }
   }
  =20
-  Expr::EvalResult Result;
-  Ex->Evaluate(Result, getContext());
-  CharUnits amt =3D CharUnits::fromQuantity(Result.Val.getInt().getZExtVal=
ue());
+  APSInt Value =3D Ex->EvaluateKnownConstInt(getContext());
+  CharUnits amt =3D CharUnits::fromQuantity(Value.getZExtValue());
  =20
-  const ProgramState *state =3D Pred->getState();
-  state =3D state->BindExpr(Ex, svalBuilder.makeIntVal(amt.getQuantity(),
+  ProgramStateRef state =3D Pred->getState();
+  state =3D state->BindExpr(Ex, Pred->getLocationContext(),
+                          svalBuilder.makeIntVal(amt.getQuantity(),
                                                      Ex->getType()));
-  MakeNode(Dst, Ex, Pred, state);
+  Bldr.generateNode(Ex, Pred, state);
 }
=20
 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,=20
                                     ExplodedNode *Pred,
-                                    ExplodedNodeSet &Dst) { =20
+                                    ExplodedNodeSet &Dst) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
   switch (U->getOpcode()) {
-    default:
+    default: {
+      Bldr.takeNodes(Pred);
+      ExplodedNodeSet Tmp;
+      VisitIncrementDecrementOperator(U, Pred, Tmp);
+      Bldr.addNodes(Tmp);
+    }
       break;
     case UO_Real: {
       const Expr *Ex =3D U->getSubExpr()->IgnoreParens();
-      ExplodedNodeSet Tmp;
-      Visit(Ex, Pred, Tmp);
-     =20
-      for (ExplodedNodeSet::iterator I=3DTmp.begin(), E=3DTmp.end(); I!=3D=
E; ++I) {
        =20
-        // FIXME: We don't have complex SValues yet.
-        if (Ex->getType()->isAnyComplexType()) {
-          // Just report "Unknown."
-          Dst.Add(*I);
-          continue;
-        }
+      // FIXME: We don't have complex SValues yet.
+      if (Ex->getType()->isAnyComplexType()) {
+        // Just report "Unknown."
+        break;
+      }
        =20
-        // For all other types, UO_Real is an identity operation.
-        assert (U->getType() =3D=3D Ex->getType());
-        const ProgramState *state =3D (*I)->getState();
-        MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
-      }
-     =20
-      return;
+      // For all other types, UO_Real is an identity operation.
+      assert (U->getType() =3D=3D Ex->getType());
+      ProgramStateRef state =3D Pred->getState();
+      const LocationContext *LCtx =3D Pred->getLocationContext();
+      Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
+                                                 state->getSVal(Ex, LCtx))=
);
+      break;
     }
      =20
-    case UO_Imag: {
-     =20
+    case UO_Imag: {     =20
       const Expr *Ex =3D U->getSubExpr()->IgnoreParens();
-      ExplodedNodeSet Tmp;
-      Visit(Ex, Pred, Tmp);
-     =20
-      for (ExplodedNodeSet::iterator I=3DTmp.begin(), E=3DTmp.end(); I!=3D=
E; ++I) {
-        // FIXME: We don't have complex SValues yet.
-        if (Ex->getType()->isAnyComplexType()) {
-          // Just report "Unknown."
-          Dst.Add(*I);
-          continue;
-        }
-       =20
-        // For all other types, UO_Imag returns 0.
-        const ProgramState *state =3D (*I)->getState();
-        SVal X =3D svalBuilder.makeZeroVal(Ex->getType());
-        MakeNode(Dst, U, *I, state->BindExpr(U, X));
+      // FIXME: We don't have complex SValues yet.
+      if (Ex->getType()->isAnyComplexType()) {
+        // Just report "Unknown."
+        break;
       }
-     =20
-      return;
+      // For all other types, UO_Imag returns 0.
+      ProgramStateRef state =3D Pred->getState();
+      const LocationContext *LCtx =3D Pred->getLocationContext();
+      SVal X =3D svalBuilder.makeZeroVal(Ex->getType());
+      Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X));
+      break;
     }
      =20
     case UO_Plus:
@@ -586,22 +653,19 @@
     case UO_Deref:
     case UO_AddrOf:
     case UO_Extension: {
-     =20
+      // FIXME: We can probably just have some magic in Environment::getSV=
al()
+      // that propagates values, instead of creating a new node here.
+      //
       // Unary "+" is a no-op, similar to a parentheses.  We still have pl=
aces
       // where it may be a block-level expression, so we need to
       // generate an extra node that just propagates the value of the
-      // subexpression.
-     =20
+      // subexpression.     =20
       const Expr *Ex =3D U->getSubExpr()->IgnoreParens();
-      ExplodedNodeSet Tmp;
-      Visit(Ex, Pred, Tmp);
-     =20
-      for (ExplodedNodeSet::iterator I=3DTmp.begin(), E=3DTmp.end(); I!=3D=
E; ++I) {
-        const ProgramState *state =3D (*I)->getState();
-        MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
-      }
-     =20
-      return;
+      ProgramStateRef state =3D Pred->getState();
+      const LocationContext *LCtx =3D Pred->getLocationContext();
+      Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
+                                                 state->getSVal(Ex, LCtx))=
);
+      break;
     }
      =20
     case UO_LNot:
@@ -609,144 +673,139 @@
     case UO_Not: {
       assert (!U->isLValue());
       const Expr *Ex =3D U->getSubExpr()->IgnoreParens();
-      ExplodedNodeSet Tmp;
-      Visit(Ex, Pred, Tmp);
-     =20
-      for (ExplodedNodeSet::iterator I=3DTmp.begin(), E=3DTmp.end(); I!=3D=
E; ++I) {
-        const ProgramState *state =3D (*I)->getState();
+      ProgramStateRef state =3D Pred->getState();
+      const LocationContext *LCtx =3D Pred->getLocationContext();
        =20
-        // Get the value of the subexpression.
-        SVal V =3D state->getSVal(Ex);
+      // Get the value of the subexpression.
+      SVal V =3D state->getSVal(Ex, LCtx);
        =20
-        if (V.isUnknownOrUndef()) {
-          MakeNode(Dst, U, *I, state->BindExpr(U, V));
-          continue;
-        }
+      if (V.isUnknownOrUndef()) {
+        Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V));
+        break;
+      }
        =20
-        switch (U->getOpcode()) {
-          default:
-            llvm_unreachable("Invalid Opcode.");
-           =20
-          case UO_Not:
-            // FIXME: Do we need to handle promotions?
-            state =3D state->BindExpr(U, evalComplement(cast<NonLoc>(V)));
-            break;
-           =20
-          case UO_Minus:
-            // FIXME: Do we need to handle promotions?
-            state =3D state->BindExpr(U, evalMinus(cast<NonLoc>(V)));
-            break;
-           =20
-          case UO_LNot:
-           =20
-            // C99 6.5.3.3: "The expression !E is equivalent to (0=3D=3DE)=
."
-            //
-            //  Note: technically we do "E =3D=3D 0", but this is the same=
 in the
-            //    transfer functions as "0 =3D=3D E".
-            SVal Result;
-           =20
-            if (isa<Loc>(V)) {
-              Loc X =3D svalBuilder.makeNull();
-              Result =3D evalBinOp(state, BO_EQ, cast<Loc>(V), X,
-                                 U->getType());
-            }
-            else {
-              nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType=
()));
-              Result =3D evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
-                                 U->getType());
-            }
-           =20
-            state =3D state->BindExpr(U, Result);
-           =20
-            break;
-        }
-       =20
-        MakeNode(Dst, U, *I, state);
+      switch (U->getOpcode()) {
+        default:
+          llvm_unreachable("Invalid Opcode.");
+        case UO_Not:
+          // FIXME: Do we need to handle promotions?
+          state =3D state->BindExpr(U, LCtx, evalComplement(cast<NonLoc>(V=
)));
+          break;
+        case UO_Minus:
+          // FIXME: Do we need to handle promotions?
+          state =3D state->BindExpr(U, LCtx, evalMinus(cast<NonLoc>(V)));
+          break;
+        case UO_LNot:
+          // C99 6.5.3.3: "The expression !E is equivalent to (0=3D=3DE)."
+          //
+          //  Note: technically we do "E =3D=3D 0", but this is the same i=
n the
+          //    transfer functions as "0 =3D=3D E".
+          SVal Result;         =20
+          if (isa<Loc>(V)) {
+            Loc X =3D svalBuilder.makeNull();
+            Result =3D evalBinOp(state, BO_EQ, cast<Loc>(V), X,
+                               U->getType());
+          }
+          else {
+            nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()=
));
+            Result =3D evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
+                               U->getType());
+          }
+         =20
+          state =3D state->BindExpr(U, LCtx, Result);         =20
+          break;
       }
-     =20
-      return;
+      Bldr.generateNode(U, Pred, state);
+      break;
     }
   }
- =20
+
+}
+
+void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
+                                                 ExplodedNode *Pred,
+                                                 ExplodedNodeSet &Dst) {
   // Handle ++ and -- (both pre- and post-increment).
   assert (U->isIncrementDecrementOp());
+  const Expr *Ex =3D U->getSubExpr()->IgnoreParens();
+ =20
+  const LocationContext *LCtx =3D Pred->getLocationContext();
+  ProgramStateRef state =3D Pred->getState();
+  SVal loc =3D state->getSVal(Ex, LCtx);
+ =20
+  // Perform a load.
   ExplodedNodeSet Tmp;
-  const Expr *Ex =3D U->getSubExpr()->IgnoreParens();
-  Visit(Ex, Pred, Tmp);
+  evalLoad(Tmp, U, Ex, Pred, state, loc);
  =20
-  for (ExplodedNodeSet::iterator I =3D Tmp.begin(), E =3D Tmp.end(); I!=3D=
E; ++I) {
+  ExplodedNodeSet Dst2;
+  StmtNodeBuilder Bldr(Tmp, Dst2, *currentBuilderContext);
+  for (ExplodedNodeSet::iterator I=3DTmp.begin(), E=3DTmp.end();I!=3DE;++I=
) {
    =20
-    const ProgramState *state =3D (*I)->getState();
-    SVal loc =3D state->getSVal(Ex);
+    state =3D (*I)->getState();
+    assert(LCtx =3D=3D (*I)->getLocationContext());
+    SVal V2_untested =3D state->getSVal(Ex, LCtx);
    =20
-    // Perform a load.
-    ExplodedNodeSet Tmp2;
-    evalLoad(Tmp2, Ex, *I, state, loc);
+    // Propagate unknown and undefined values.
+    if (V2_untested.isUnknownOrUndef()) {
+      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
+      continue;
+    }
+    DefinedSVal V2 =3D cast<DefinedSVal>(V2_untested);
    =20
-    for (ExplodedNodeSet::iterator I2=3DTmp2.begin(), E2=3DTmp2.end();I2!=
=3DE2;++I2) {
+    // Handle all other values.
+    BinaryOperator::Opcode Op =3D U->isIncrementOp() ? BO_Add : BO_Sub;
+   =20
+    // If the UnaryOperator has non-location type, use its type to create =
the
+    // constant value. If the UnaryOperator has location type, create the
+    // constant with int type and pointer width.
+    SVal RHS;
+   =20
+    if (U->getType()->isAnyPointerType())
+      RHS =3D svalBuilder.makeArrayIndex(1);
+    else
+      RHS =3D svalBuilder.makeIntVal(1, U->getType());
+   =20
+    SVal Result =3D evalBinOp(state, Op, V2, RHS, U->getType());
+   =20
+    // Conjure a new symbol if necessary to recover precision.
+    if (Result.isUnknown()){
+      DefinedOrUnknownSVal SymVal =3D
+	svalBuilder.getConjuredSymbolVal(NULL, Ex, LCtx,
+                               currentBuilderContext->getCurrentBlockCount=
());
+      Result =3D SymVal;
      =20
-      state =3D (*I2)->getState();
-      SVal V2_untested =3D state->getSVal(Ex);
-     =20
-      // Propagate unknown and undefined values.
-      if (V2_untested.isUnknownOrUndef()) {
-        MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested));
-        continue;
-      }
-      DefinedSVal V2 =3D cast<DefinedSVal>(V2_untested);
-     =20
-      // Handle all other values.
-      BinaryOperator::Opcode Op =3D U->isIncrementOp() ? BO_Add
-      : BO_Sub;
-     =20
-      // If the UnaryOperator has non-location type, use its type to creat=
e the
-      // constant value. If the UnaryOperator has location type, create the
-      // constant with int type and pointer width.
-      SVal RHS;
-     =20
-      if (U->getType()->isAnyPointerType())
-        RHS =3D svalBuilder.makeArrayIndex(1);
-      else
-        RHS =3D svalBuilder.makeIntVal(1, U->getType());
-     =20
-      SVal Result =3D evalBinOp(state, Op, V2, RHS, U->getType());
-     =20
-      // Conjure a new symbol if necessary to recover precision.
-      if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Res=
ult)){
-        DefinedOrUnknownSVal SymVal =3D
-        svalBuilder.getConjuredSymbolVal(NULL, Ex,
-                                         Builder->getCurrentBlockCount());
-        Result =3D SymVal;
+      // If the value is a location, ++/-- should always preserve
+      // non-nullness.  Check if the original value was non-null, and if so
+      // propagate that constraint.
+      if (Loc::isLocType(U->getType())) {
+        DefinedOrUnknownSVal Constraint =3D
+        svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())=
);
        =20
-        // If the value is a location, ++/-- should always preserve
-        // non-nullness.  Check if the original value was non-null, and if=
 so
-        // propagate that constraint.
-        if (Loc::isLocType(U->getType())) {
-          DefinedOrUnknownSVal Constraint =3D
-          svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType(=
)));
+        if (!state->assume(Constraint, true)) {
+          // It isn't feasible for the original value to be null.
+          // Propagate this constraint.
+          Constraint =3D svalBuilder.evalEQ(state, SymVal,
+                                       svalBuilder.makeZeroVal(U->getType(=
)));
          =20
-          if (!state->assume(Constraint, true)) {
-            // It isn't feasible for the original value to be null.
-            // Propagate this constraint.
-            Constraint =3D svalBuilder.evalEQ(state, SymVal,
-                                            svalBuilder.makeZeroVal(U->get=
Type()));
-           =20
-           =20
-            state =3D state->assume(Constraint, false);
-            assert(state);
-          }
+         =20
+          state =3D state->assume(Constraint, false);
+          assert(state);
         }
       }
-     =20
-      // Since the lvalue-to-rvalue conversion is explicit in the AST,
-      // we bind an l-value if the operator is prefix and an lvalue (in C+=
+).
-      if (U->isLValue())
-        state =3D state->BindExpr(U, loc);
-      else
-        state =3D state->BindExpr(U, U->isPostfix() ? V2 : Result);
-     =20
-      // Perform the store.
-      evalStore(Dst, NULL, U, *I2, state, loc, Result);
     }
+   =20
+    // Since the lvalue-to-rvalue conversion is explicit in the AST,
+    // we bind an l-value if the operator is prefix and an lvalue (in C++).
+    if (U->isLValue())
+      state =3D state->BindExpr(U, LCtx, loc);
+    else
+      state =3D state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
+   =20
+    // Perform the store.
+    Bldr.takeNodes(*I);
+    ExplodedNodeSet Dst3;
+    evalStore(Dst3, U, U, *I, state, loc, Result);
+    Bldr.addNodes(Dst3);
   }
+  Dst.insert(Dst2);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ExprEngineCXX.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -16,81 +16,11 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
 #include "clang/AST/DeclCXX.h"
+#include "clang/AST/StmtCXX.h"
=20
 using namespace clang;
 using namespace ento;
=20
-namespace {
-class CallExprWLItem {
-public:
-  CallExpr::const_arg_iterator I;
-  ExplodedNode *N;
-
-  CallExprWLItem(const CallExpr::const_arg_iterator &i, ExplodedNode *n)
-    : I(i), N(n) {}
-};
-}
-
-void ExprEngine::evalArguments(ConstExprIterator AI, ConstExprIterator AE,
-                                 const FunctionProtoType *FnType,=20
-                                 ExplodedNode *Pred, ExplodedNodeSet &Dst,
-                                 bool FstArgAsLValue) {
-
-
-  SmallVector<CallExprWLItem, 20> WorkList;
-  WorkList.reserve(AE - AI);
-  WorkList.push_back(CallExprWLItem(AI, Pred));
-
-  while (!WorkList.empty()) {
-    CallExprWLItem Item =3D WorkList.back();
-    WorkList.pop_back();
-
-    if (Item.I =3D=3D AE) {
-      Dst.insert(Item.N);
-      continue;
-    }
-
-    // Evaluate the argument.
-    ExplodedNodeSet Tmp;
-    if (FstArgAsLValue) {
-      FstArgAsLValue =3D false;
-    }
-
-    Visit(*Item.I, Item.N, Tmp);
-    ++(Item.I);
-    for (ExplodedNodeSet::iterator NI=3DTmp.begin(), NE=3DTmp.end(); NI !=
=3D NE; ++NI)
-      WorkList.push_back(CallExprWLItem(Item.I, *NI));
-  }
-}
-
-void ExprEngine::evalCallee(const CallExpr *callExpr,
-                            const ExplodedNodeSet &src,
-                            ExplodedNodeSet &dest) {
- =20
-  const Expr *callee =3D 0;
- =20
-  switch (callExpr->getStmtClass()) {
-    case Stmt::CXXMemberCallExprClass: {
-      // Evaluate the implicit object argument that is the recipient of the
-      // call.
-      callee =3D cast<CXXMemberCallExpr>(callExpr)->getImplicitObjectArgum=
ent();
-     =20
-      // FIXME: handle member pointers.
-      if (!callee)
-        return;
-
-      break;     =20
-    }
-    default: {
-      callee =3D callExpr->getCallee()->IgnoreParens();
-      break;
-    }
-  }
-
-  for (ExplodedNodeSet::iterator i =3D src.begin(), e =3D src.end(); i !=
=3D e; ++i)
-    Visit(callee, *i, dest);
-}
-
 const CXXThisRegion *ExprEngine::getCXXThisRegion(const CXXRecordDecl *D,
                                                  const StackFrameContext *=
SFC) {
   const Type *T =3D D->getTypeForDecl();
@@ -107,19 +37,26 @@
 void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *=
ME,
                                           ExplodedNode *Pred,
                                           ExplodedNodeSet &Dst) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
   const Expr *tempExpr =3D ME->GetTemporaryExpr()->IgnoreParens();
-  const ProgramState *state =3D Pred->getState();
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
=20
   // Bind the temporary object to the value of the expression. Then bind
   // the expression to the location of the object.
-  SVal V =3D state->getSVal(tempExpr);
+  SVal V =3D state->getSVal(tempExpr, Pred->getLocationContext());
=20
   const MemRegion *R =3D
-    svalBuilder.getRegionManager().getCXXTempObjectRegion(ME,
-                                                 Pred->getLocationContext(=
));
+    svalBuilder.getRegionManager().getCXXTempObjectRegion(ME, LCtx);
=20
   state =3D state->bindLoc(loc::MemRegionVal(R), V);
-  MakeNode(Dst, ME, Pred, state->BindExpr(ME, loc::MemRegionVal(R)));
+  Bldr.generateNode(ME, Pred, state->BindExpr(ME, LCtx, loc::MemRegionVal(=
R)));
+}
+
+void ExprEngine::VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr =
*expr,
+                                             ExplodedNode *Pred,
+                                             ExplodedNodeSet &Dst) {
+  VisitCXXConstructExpr(expr, 0, Pred, Dst);
 }
=20
 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *E,=20
@@ -127,8 +64,10 @@
                                        ExplodedNode *Pred,
                                        ExplodedNodeSet &destNodes) {
=20
+#if 0
   const CXXConstructorDecl *CD =3D E->getConstructor();
   assert(CD);
+#endif
  =20
 #if 0
   if (!(CD->doesThisDeclarationHaveABody() && AMgr.shouldInlineCall()))
@@ -136,26 +75,19 @@
     return;
 #endif
  =20
-  // Evaluate other arguments.
-  ExplodedNodeSet argsEvaluated;
-  const FunctionProtoType *FnType =3D CD->getType()->getAs<FunctionProtoTy=
pe>();
-  evalArguments(E->arg_begin(), E->arg_end(), FnType, Pred, argsEvaluated);
-
 #if 0
   // Is the constructor elidable?
   if (E->isElidable()) {
-    VisitAggExpr(E->getArg(0), destNodes, Pred, Dst);
-    // FIXME: this is here to force propagation if VisitAggExpr doesn't
-    if (destNodes.empty())
-      destNodes.Add(Pred);
+    destNodes.Add(Pred);
     return;
   }
 #endif
  =20
   // Perform the previsit of the constructor.
-  ExplodedNodeSet destPreVisit;
-  getCheckerManager().runCheckersForPreStmt(destPreVisit, argsEvaluated, E=
,=20
-                                            *this);
+  ExplodedNodeSet SrcNodes;
+  SrcNodes.Add(Pred);
+  ExplodedNodeSet TmpNodes;
+  getCheckerManager().runCheckersForPreStmt(TmpNodes, SrcNodes, E, *this);
  =20
   // Evaluate the constructor.  Currently we don't now allow checker-speci=
fic
   // implementations of specific constructors (as we do with ordinary
@@ -174,7 +106,8 @@
     // parameter region.
     const StackFrameContext *SFC =3D=20
       AMgr.getStackFrame(CD, Pred->getLocationContext(),
-                         E, Builder->getBlock(), Builder->getIndex());
+                         E, currentBuilderContext->getBlock(),
+                         currentStmtIdx);
=20
     // Create the 'this' region.
     const CXXThisRegion *ThisR =3D
@@ -182,34 +115,33 @@
=20
     CallEnter Loc(E, SFC, Pred->getLocationContext());
=20
-
-    for (ExplodedNodeSet::iterator NI =3D argsEvaluated.begin(),
-                                  NE =3D argsEvaluated.end(); NI !=3D NE; =
++NI) {
-      const ProgramState *state =3D (*NI)->getState();
+    StmtNodeBuilder Bldr(SrcNodes, TmpNodes, *currentBuilderContext);
+    for (ExplodedNodeSet::iterator NI =3D SrcNodes.begin(),
+                                   NE =3D SrcNodes.end(); NI !=3D NE; ++NI=
) {
+      ProgramStateRef state =3D (*NI)->getState();
       // Setup 'this' region, so that the ctor is evaluated on the object =
pointed
       // by 'Dest'.
       state =3D state->bindLoc(loc::MemRegionVal(ThisR), loc::MemRegionVal=
(Dest));
-      if (ExplodedNode *N =3D Builder->generateNode(Loc, state, *NI))
-        destNodes.Add(N);
+      Bldr.generateNode(Loc, *NI, state);
     }
   }
 #endif
  =20
   // Default semantics: invalidate all regions passed as arguments.
   ExplodedNodeSet destCall;
+  {
+    StmtNodeBuilder Bldr(TmpNodes, destCall, *currentBuilderContext);
+    for (ExplodedNodeSet::iterator i =3D TmpNodes.begin(), e =3D TmpNodes.=
end();
+         i !=3D e; ++i)
+    {
+      ExplodedNode *Pred =3D *i;
+      const LocationContext *LC =3D Pred->getLocationContext();
+      ProgramStateRef state =3D Pred->getState();
=20
-  for (ExplodedNodeSet::iterator
-        i =3D destPreVisit.begin(), e =3D destPreVisit.end();
-       i !=3D e; ++i)
-  {
-    ExplodedNode *Pred =3D *i;
-    const LocationContext *LC =3D Pred->getLocationContext();
-    const ProgramState *state =3D Pred->getState();
-
-    state =3D invalidateArguments(state, CallOrObjCMessage(E, state), LC);
-    Builder->MakeNode(destCall, E, Pred, state);
+      state =3D invalidateArguments(state, CallOrObjCMessage(E, state, LC)=
, LC);
+      Bldr.generateNode(E, Pred, state);
+    }
   }
- =20
   // Do the post visit.
   getCheckerManager().runCheckersForPostStmt(destNodes, destCall, E, *this=
); =20
 }
@@ -219,31 +151,33 @@
                                       const Stmt *S,
                                       ExplodedNode *Pred,=20
                                       ExplodedNodeSet &Dst) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
   if (!(DD->doesThisDeclarationHaveABody() && AMgr.shouldInlineCall()))
     return;
+
   // Create the context for 'this' region.
-  const StackFrameContext *SFC =3D AMgr.getStackFrame(DD,
-                                                    Pred->getLocationConte=
xt(),
-                                                    S, Builder->getBlock(),
-                                                    Builder->getIndex());
+  const StackFrameContext *SFC =3D
+    AnalysisDeclContexts.getContext(DD)->
+      getStackFrame(Pred->getLocationContext(), S,
+      currentBuilderContext->getBlock(), currentStmtIdx);
=20
   const CXXThisRegion *ThisR =3D getCXXThisRegion(DD->getParent(), SFC);
=20
   CallEnter PP(S, SFC, Pred->getLocationContext());
=20
-  const ProgramState *state =3D Pred->getState();
+  ProgramStateRef state =3D Pred->getState();
   state =3D state->bindLoc(loc::MemRegionVal(ThisR), loc::MemRegionVal(Des=
t));
-  ExplodedNode *N =3D Builder->generateNode(PP, state, Pred);
-  if (N)
-    Dst.Add(N);
+  Bldr.generateNode(PP, Pred, state);
 }
=20
 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
                                    ExplodedNodeSet &Dst) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  =20
-  unsigned blockCount =3D Builder->getCurrentBlockCount();
+  unsigned blockCount =3D currentBuilderContext->getCurrentBlockCount();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
   DefinedOrUnknownSVal symVal =3D
-    svalBuilder.getConjuredSymbolVal(NULL, CNE, CNE->getType(), blockCount=
);
+    svalBuilder.getConjuredSymbolVal(NULL, CNE, LCtx, CNE->getType(), bloc=
kCount);
   const MemRegion *NewReg =3D cast<loc::MemRegionVal>(symVal).getRegion();=
 =20
   QualType ObjTy =3D CNE->getType()->getAs<PointerType>()->getPointeeType(=
);
   const ElementRegion *EleReg =3D=20
@@ -252,26 +186,31 @@
   if (CNE->isArray()) {
     // FIXME: allocating an array requires simulating the constructors.
     // For now, just return a symbolicated region.
-    const ProgramState *state =3D Pred->getState();
-    state =3D state->BindExpr(CNE, loc::MemRegionVal(EleReg));
-    MakeNode(Dst, CNE, Pred, state);
+    ProgramStateRef state =3D Pred->getState();
+    state =3D state->BindExpr(CNE, Pred->getLocationContext(),
+                            loc::MemRegionVal(EleReg));
+    Bldr.generateNode(CNE, Pred, state);
     return;
   }
=20
+  // FIXME: Update for AST changes.
+#if 0
   // Evaluate constructor arguments.
   const FunctionProtoType *FnType =3D NULL;
   const CXXConstructorDecl *CD =3D CNE->getConstructor();
   if (CD)
     FnType =3D CD->getType()->getAs<FunctionProtoType>();
   ExplodedNodeSet argsEvaluated;
+  Bldr.takeNodes(Pred);
   evalArguments(CNE->constructor_arg_begin(), CNE->constructor_arg_end(),
                 FnType, Pred, argsEvaluated);
+  Bldr.addNodes(argsEvaluated);
=20
   // Initialize the object region and bind the 'new' expression.
   for (ExplodedNodeSet::iterator I =3D argsEvaluated.begin(),=20
                                  E =3D argsEvaluated.end(); I !=3D E; ++I)=
 {
=20
-    const ProgramState *state =3D (*I)->getState();
+    ProgramStateRef state =3D (*I)->getState();
    =20
     // Accumulate list of regions that are invalidated.
     // FIXME: Eventually we should unify the logic for constructor
@@ -281,7 +220,7 @@
           ai =3D CNE->constructor_arg_begin(), ae =3D CNE->constructor_arg=
_end();
           ai !=3D ae; ++ai)
     {
-      SVal val =3D state->getSVal(*ai);
+      SVal val =3D state->getSVal(*ai, (*I)->getLocationContext());
       if (const MemRegion *region =3D val.getAsRegion())
         regionsToInvalidate.push_back(region);
     }
@@ -289,18 +228,21 @@
     if (ObjTy->isRecordType()) {
       regionsToInvalidate.push_back(EleReg);
       // Invalidate the regions.
+      // TODO: Pass the call to new information as the last argument, to l=
imit
+      // the globals which will get invalidated.
       state =3D state->invalidateRegions(regionsToInvalidate,
-                                       CNE, blockCount, 0,
-                                       /* invalidateGlobals =3D */ true);
+                                       CNE, blockCount, 0, 0);
      =20
     } else {
       // Invalidate the regions.
+      // TODO: Pass the call to new information as the last argument, to l=
imit
+      // the globals which will get invalidated.
       state =3D state->invalidateRegions(regionsToInvalidate,
-                                       CNE, blockCount, 0,
-                                       /* invalidateGlobals =3D */ true);
+                                       CNE, blockCount, 0, 0);
=20
       if (CNE->hasInitializer()) {
-        SVal V =3D state->getSVal(*CNE->constructor_arg_begin());
+        SVal V =3D state->getSVal(*CNE->constructor_arg_begin(),
+                                (*I)->getLocationContext());
         state =3D state->bindLoc(loc::MemRegionVal(EleReg), V);
       } else {
         // Explicitly set to undefined, because currently we retrieve symb=
olic
@@ -308,32 +250,51 @@
         state =3D state->bindLoc(loc::MemRegionVal(EleReg), UndefinedVal()=
);
       }
     }
-    state =3D state->BindExpr(CNE, loc::MemRegionVal(EleReg));
-    MakeNode(Dst, CNE, *I, state);
+    state =3D state->BindExpr(CNE, (*I)->getLocationContext(),
+                            loc::MemRegionVal(EleReg));
+    Bldr.generateNode(CNE, *I, state);
   }
+#endif
 }
=20
 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,=20
-                                      ExplodedNode *Pred,ExplodedNodeSet &=
Dst) {
-  // Should do more checking.
-  ExplodedNodeSet Argevaluated;
-  Visit(CDE->getArgument(), Pred, Argevaluated);
-  for (ExplodedNodeSet::iterator I =3D Argevaluated.begin(),=20
-                                 E =3D Argevaluated.end(); I !=3D E; ++I) {
-    const ProgramState *state =3D (*I)->getState();
-    MakeNode(Dst, CDE, *I, state);
+                                    ExplodedNode *Pred, ExplodedNodeSet &D=
st) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
+  ProgramStateRef state =3D Pred->getState();
+  Bldr.generateNode(CDE, Pred, state);
+}
+
+void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
+                                   ExplodedNode *Pred,
+                                   ExplodedNodeSet &Dst) {
+  const VarDecl *VD =3D CS->getExceptionDecl();
+  if (!VD) {
+    Dst.Add(Pred);
+    return;
   }
+
+  const LocationContext *LCtx =3D Pred->getLocationContext();
+  SVal V =3D svalBuilder.getConjuredSymbolVal(CS, LCtx, VD->getType(),
+                                 currentBuilderContext->getCurrentBlockCou=
nt());
+  ProgramStateRef state =3D Pred->getState();
+  state =3D state->bindLoc(state->getLValue(VD, LCtx), V);
+
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
+  Bldr.generateNode(CS, Pred, state);
 }
=20
 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pre=
d,
                                     ExplodedNodeSet &Dst) {
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
+
   // Get the this object region from StoreManager.
+  const LocationContext *LCtx =3D Pred->getLocationContext();
   const MemRegion *R =3D
     svalBuilder.getRegionManager().getCXXThisRegion(
                                   getContext().getCanonicalType(TE->getTyp=
e()),
-                                               Pred->getLocationContext());
+                                                    LCtx);
=20
-  const ProgramState *state =3D Pred->getState();
+  ProgramStateRef state =3D Pred->getState();
   SVal V =3D state->getSVal(loc::MemRegionVal(R));
-  MakeNode(Dst, TE, Pred, state->BindExpr(TE, V));
+  Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ExprEngineCallAndReturn.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallA=
ndReturn.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineCallA=
ndReturn.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -15,40 +15,72 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
 #include "clang/AST/DeclCXX.h"
-#include "clang/Analysis/Support/SaveAndRestore.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/Support/SaveAndRestore.h"
=20
 using namespace clang;
 using namespace ento;
=20
-namespace {
-  // Trait class for recording returned expression in the state.
-  struct ReturnExpr {
-    static int TagInt;
-    typedef const Stmt *data_type;
-  };
-  int ReturnExpr::TagInt;=20
+void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) {
+  // Get the entry block in the CFG of the callee.
+  const StackFrameContext *calleeCtx =3D CE.getCalleeContext();
+  const CFG *CalleeCFG =3D calleeCtx->getCFG();
+  const CFGBlock *Entry =3D &(CalleeCFG->getEntry());
+ =20
+  // Validate the CFG.
+  assert(Entry->empty());
+  assert(Entry->succ_size() =3D=3D 1);
+ =20
+  // Get the solitary sucessor.
+  const CFGBlock *Succ =3D *(Entry->succ_begin());
+ =20
+  // Construct an edge representing the starting location in the callee.
+  BlockEdge Loc(Entry, Succ, calleeCtx);
+
+  // Construct a new state which contains the mapping from actual to
+  // formal arguments.
+  const LocationContext *callerCtx =3D Pred->getLocationContext();
+  ProgramStateRef state =3D Pred->getState()->enterStackFrame(callerCtx,
+                                                                calleeCtx);
+ =20
+  // Construct a new node and add it to the worklist.
+  bool isNew;
+  ExplodedNode *Node =3D G.getNode(Loc, state, false, &isNew);
+  Node->addPredecessor(Pred, G);
+  if (isNew)
+    Engine.getWorkList()->enqueue(Node);
 }
=20
-void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) {
-  const ProgramState *state =3D
-    B.getState()->enterStackFrame(B.getCalleeContext());
-  B.generateNode(state);
+static const ReturnStmt *getReturnStmt(const ExplodedNode *Node) {
+  while (Node) {
+    const ProgramPoint &PP =3D Node->getLocation();
+    // Skip any BlockEdges.
+    if (isa<BlockEdge>(PP) || isa<CallExit>(PP)) {
+      assert(Node->pred_size() =3D=3D 1);
+      Node =3D *Node->pred_begin();
+      continue;
+    }=20
+    if (const StmtPoint *SP =3D dyn_cast<StmtPoint>(&PP)) {
+      const Stmt *S =3D SP->getStmt();
+      return dyn_cast<ReturnStmt>(S);
+    }
+    break;
+  }
+  return 0;
 }
=20
-void ExprEngine::processCallExit(CallExitNodeBuilder &B) {
-  const ProgramState *state =3D B.getState();
-  const ExplodedNode *Pred =3D B.getPredecessor();
+void ExprEngine::processCallExit(ExplodedNode *Pred) {
+  ProgramStateRef state =3D Pred->getState();
   const StackFrameContext *calleeCtx =3D=20
-    cast<StackFrameContext>(Pred->getLocationContext());
+    Pred->getLocationContext()->getCurrentStackFrame();
+  const LocationContext *callerCtx =3D calleeCtx->getParent();
   const Stmt *CE =3D calleeCtx->getCallSite();
  =20
   // If the callee returns an expression, bind its value to CallExpr.
-  const Stmt *ReturnedExpr =3D state->get<ReturnExpr>();
-  if (ReturnedExpr) {
-    SVal RetVal =3D state->getSVal(ReturnedExpr);
-    state =3D state->BindExpr(CE, RetVal);
-    // Clear the return expr GDM.
-    state =3D state->remove<ReturnExpr>();
+  if (const ReturnStmt *RS =3D getReturnStmt(Pred)) {
+    const LocationContext *LCtx =3D Pred->getLocationContext();
+    SVal V =3D state->getSVal(RS, LCtx);
+    state =3D state->BindExpr(CE, callerCtx, V);
   }
  =20
   // Bind the constructed object value to CXXConstructExpr.
@@ -58,14 +90,197 @@
    =20
     SVal ThisV =3D state->getSVal(ThisR);
     // Always bind the region to the CXXConstructExpr.
-    state =3D state->BindExpr(CCE, ThisV);
+    state =3D state->BindExpr(CCE, Pred->getLocationContext(), ThisV);
   }
  =20
-  B.generateNode(state);
+  static SimpleProgramPointTag returnTag("ExprEngine : Call Return");
+  PostStmt Loc(CE, callerCtx, &returnTag);
+  bool isNew;
+  ExplodedNode *N =3D G.getNode(Loc, state, false, &isNew);
+  N->addPredecessor(Pred, G);
+  if (!isNew)
+    return;
+ =20
+  // Perform the post-condition check of the CallExpr.
+  ExplodedNodeSet Dst;
+  NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), N);
+  SaveAndRestore<const NodeBuilderContext*> NBCSave(currentBuilderContext,
+                                                    &Ctx);
+  SaveAndRestore<unsigned> CBISave(currentStmtIdx, calleeCtx->getIndex());
+ =20
+  getCheckerManager().runCheckersForPostStmt(Dst, N, CE, *this,
+                                             /* wasInlined */ true);
+ =20
+  // Enqueue the next element in the block.
+  for (ExplodedNodeSet::iterator I =3D Dst.begin(), E =3D Dst.end(); I !=
=3D E; ++I) {
+    Engine.getWorkList()->enqueue(*I,
+                                  calleeCtx->getCallSiteBlock(),
+                                  calleeCtx->getIndex()+1);
+  }
 }
=20
-const ProgramState *
-ExprEngine::invalidateArguments(const ProgramState *State,
+static unsigned getNumberStackFrames(const LocationContext *LCtx) {
+  unsigned count =3D 0;
+  while (LCtx) {
+    if (isa<StackFrameContext>(LCtx))
+      ++count;
+    LCtx =3D LCtx->getParent();
+  }
+  return count; =20
+}
+
+// Determine if we should inline the call.
+bool ExprEngine::shouldInlineDecl(const FunctionDecl *FD, ExplodedNode *Pr=
ed) {
+  AnalysisDeclContext *CalleeADC =3D AMgr.getAnalysisDeclContext(FD);
+  const CFG *CalleeCFG =3D CalleeADC->getCFG();
+
+  if (getNumberStackFrames(Pred->getLocationContext())
+        =3D=3D AMgr.InlineMaxStackDepth)
+    return false;
+
+  if (Engine.FunctionSummaries->hasReachedMaxBlockCount(FD))
+    return false;
+
+  if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize)
+    return false;
+
+  return true;
+}
+
+// For now, skip inlining variadic functions.
+// We also don't inline blocks.
+static bool shouldInlineCallExpr(const CallExpr *CE, ExprEngine *E) {
+  if (!E->getAnalysisManager().shouldInlineCall())
+    return false;
+  QualType callee =3D CE->getCallee()->getType();
+  const FunctionProtoType *FT =3D 0;
+  if (const PointerType *PT =3D callee->getAs<PointerType>())
+    FT =3D dyn_cast<FunctionProtoType>(PT->getPointeeType());
+  else if (const BlockPointerType *BT =3D callee->getAs<BlockPointerType>(=
)) {
+    // FIXME: inline blocks.
+    // FT =3D dyn_cast<FunctionProtoType>(BT->getPointeeType());
+    (void) BT;
+    return false;
+  }
+  // If we have no prototype, assume the function is okay.
+  if (!FT)
+    return true;
+
+  // Skip inlining of variadic functions.
+  return !FT->isVariadic();
+}
+
+bool ExprEngine::InlineCall(ExplodedNodeSet &Dst,
+                            const CallExpr *CE,=20
+                            ExplodedNode *Pred) {
+  if (!shouldInlineCallExpr(CE, this))
+    return false;
+
+  ProgramStateRef state =3D Pred->getState();
+  const Expr *Callee =3D CE->getCallee();
+  const FunctionDecl *FD =3D
+    state->getSVal(Callee, Pred->getLocationContext()).getAsFunctionDecl();
+  if (!FD || !FD->hasBody(FD))
+    return false;
+ =20
+  switch (CE->getStmtClass()) {
+    default:
+      // FIXME: Handle C++.
+      break;
+    case Stmt::CallExprClass: {
+      if (!shouldInlineDecl(FD, Pred))
+        return false;
+
+      // Construct a new stack frame for the callee.
+      AnalysisDeclContext *CalleeADC =3D AMgr.getAnalysisDeclContext(FD);
+      const StackFrameContext *CallerSFC =3D
+      Pred->getLocationContext()->getCurrentStackFrame();
+      const StackFrameContext *CalleeSFC =3D
+      CalleeADC->getStackFrame(CallerSFC, CE,
+                               currentBuilderContext->getBlock(),
+                               currentStmtIdx);
+     =20
+      CallEnter Loc(CE, CalleeSFC, Pred->getLocationContext());
+      bool isNew;
+      if (ExplodedNode *N =3D G.getNode(Loc, state, false, &isNew)) {
+        N->addPredecessor(Pred, G);
+        if (isNew)
+          Engine.getWorkList()->enqueue(N);
+      }
+      return true;
+    }
+  }
+  return false;
+}
+
+static bool isPointerToConst(const ParmVarDecl *ParamDecl) {
+  QualType PointeeTy =3D ParamDecl->getOriginalType()->getPointeeType();
+  if (PointeeTy !=3D QualType() && PointeeTy.isConstQualified() &&
+      !PointeeTy->isAnyPointerType() && !PointeeTy->isReferenceType()) {
+    return true;
+  }
+  return false;
+}
+
+// Try to retrieve the function declaration and find the function parameter
+// types which are pointers/references to a non-pointer const.
+// We do not invalidate the corresponding argument regions.
+static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs,
+                       const CallOrObjCMessage &Call) {
+  const Decl *CallDecl =3D Call.getDecl();
+  if (!CallDecl)
+    return;
+
+  if (const FunctionDecl *FDecl =3D dyn_cast<FunctionDecl>(CallDecl)) {
+    const IdentifierInfo *II =3D FDecl->getIdentifier();
+
+    // List the cases, where the region should be invalidated even if the
+    // argument is const.
+    if (II) {
+      StringRef FName =3D II->getName();
+      //  - 'int pthread_setspecific(ptheread_key k, const void *)' stores=
 a
+      // value into thread local storage. The value can later be retrieved=
 with
+      // 'void *ptheread_getspecific(pthread_key)'. So even thought the
+      // parameter is 'const void *', the region escapes through the call.
+      //  - funopen - sets a buffer for future IO calls.
+      //  - ObjC functions that end with "NoCopy" can free memory, of the =
passed
+      // in buffer.
+      // - Many CF containers allow objects to escape through custom
+      // allocators/deallocators upon container construction.
+      // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
+      // be deallocated by NSMapRemove.
+      if (FName =3D=3D "pthread_setspecific" ||
+          FName =3D=3D "funopen" ||
+          FName.endswith("NoCopy") ||
+          (FName.startswith("NS") &&
+            (FName.find("Insert") !=3D StringRef::npos)) ||
+          Call.isCFCGAllowingEscape(FName))
+        return;
+    }
+
+    for (unsigned Idx =3D 0, E =3D Call.getNumArgs(); Idx !=3D E; ++Idx) {
+      if (FDecl && Idx < FDecl->getNumParams()) {
+        if (isPointerToConst(FDecl->getParamDecl(Idx)))
+          PreserveArgs.insert(Idx);
+      }
+    }
+    return;
+  }
+
+  if (const ObjCMethodDecl *MDecl =3D dyn_cast<ObjCMethodDecl>(CallDecl)) {
+    assert(MDecl->param_size() <=3D Call.getNumArgs());
+    unsigned Idx =3D 0;
+    for (clang::ObjCMethodDecl::param_const_iterator
+         I =3D MDecl->param_begin(), E =3D MDecl->param_end(); I !=3D E; +=
+I, ++Idx) {
+      if (isPointerToConst(*I))
+        PreserveArgs.insert(Idx);
+    }
+    return;
+  }
+}
+
+ProgramStateRef=20
+ExprEngine::invalidateArguments(ProgramStateRef State,
                                 const CallOrObjCMessage &Call,
                                 const LocationContext *LC) {
   SmallVector<const MemRegion *, 8> RegionsToInvalidate;
@@ -85,13 +300,21 @@
=20
   } else if (Call.isFunctionCall()) {
     // Block calls invalidate all captured-by-reference values.
-    if (const MemRegion *Callee =3D Call.getFunctionCallee().getAsRegion()=
) {
+    SVal CalleeVal =3D Call.getFunctionCallee();
+    if (const MemRegion *Callee =3D CalleeVal.getAsRegion()) {
       if (isa<BlockDataRegion>(Callee))
         RegionsToInvalidate.push_back(Callee);
     }
   }
=20
+  // Indexes of arguments whose values will be preserved by the call.
+  llvm::SmallSet<unsigned, 1> PreserveArgs;
+  findPtrToConstParams(PreserveArgs, Call);
+
   for (unsigned idx =3D 0, e =3D Call.getNumArgs(); idx !=3D e; ++idx) {
+    if (PreserveArgs.count(idx))
+      continue;
+
     SVal V =3D Call.getArgSVal(idx);
=20
     // If we are passing a location wrapped as an integer, unwrap it and
@@ -105,7 +328,7 @@
       // Invalidate the value of the variable passed by reference.
=20
       // Are we dealing with an ElementRegion?  If the element type is
-      // a basic integer type (e.g., char, int) and the underying region
+      // a basic integer type (e.g., char, int) and the underlying region
       // is a variable region then strip off the ElementRegion.
       // FIXME: We really need to think about this for the general case
       //   as sometimes we are reasoning about arrays and other times
@@ -116,7 +339,7 @@
         // we'll leave it in for now until we have a systematic way of
         // handling all of these cases.  Eventually we need to come up
         // with an interface to StoreManager so that this logic can be
-        // approriately delegated to the respective StoreManagers while
+        // appropriately delegated to the respective StoreManagers while
         // still allowing us to do checker-specific logic (e.g.,
         // invalidating reference counts), probably via callbacks.
         if (ER->getElementType()->isIntegralOrEnumerationType()) {
@@ -146,18 +369,29 @@
   //  to identify conjured symbols by an expression pair: the enclosing
   //  expression (the context) and the expression itself.  This should
   //  disambiguate conjured symbols.
-  assert(Builder && "Invalidating arguments outside of a statement context=
");
-  unsigned Count =3D Builder->getCurrentBlockCount();
+  unsigned Count =3D currentBuilderContext->getCurrentBlockCount();
   StoreManager::InvalidatedSymbols IS;
=20
   // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
   //  global variables.
   return State->invalidateRegions(RegionsToInvalidate,
-                                  Call.getOriginExpr(), Count,
-                                  &IS, doesInvalidateGlobals(Call));
+                                  Call.getOriginExpr(), Count, LC,
+                                  &IS, &Call);
=20
 }
=20
+static ProgramStateRef getReplayWithoutInliningState(ExplodedNode *&N,
+                                                     const CallExpr *CE) {
+  void *ReplayState =3D N->getState()->get<ReplayWithoutInlining>();
+  if (!ReplayState)
+    return 0;
+  const CallExpr *ReplayCE =3D reinterpret_cast<const CallExpr*>(ReplaySta=
te);
+  if (CE =3D=3D ReplayCE) {
+    return N->getState()->remove<ReplayWithoutInlining>();
+  }
+  return 0;
+}
+
 void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
                                ExplodedNodeSet &dst) {
   // Perform the previsit of the CallExpr.
@@ -173,20 +407,21 @@
     DefaultEval(ExprEngine &eng, const CallExpr *ce)
     : Eng(eng), CE(ce) {}
     virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) {
-      // Should we inline the call?
-      if (Eng.getAnalysisManager().shouldInlineCall() &&
-          Eng.InlineCall(Dst, CE, Pred)) {
+
+      ProgramStateRef state =3D getReplayWithoutInliningState(Pred, CE);
+
+      // First, try to inline the call.
+      if (state =3D=3D 0 && Eng.InlineCall(Dst, CE, Pred))
         return;
-      }
=20
       // First handle the return value.
-      StmtNodeBuilder &Builder =3D Eng.getBuilder();
-      assert(&Builder && "StmtNodeBuilder must be defined.");
+      StmtNodeBuilder Bldr(Pred, Dst, *Eng.currentBuilderContext);
=20
       // Get the callee.
       const Expr *Callee =3D CE->getCallee()->IgnoreParens();
-      const ProgramState *state =3D Pred->getState();
-      SVal L =3D state->getSVal(Callee);
+      if (state =3D=3D 0)
+        state =3D Pred->getState();
+      SVal L =3D state->getSVal(Callee, Pred->getLocationContext());
=20
       // Figure out the result type. We do this dance to handle references.
       QualType ResultTy;
@@ -200,18 +435,19 @@
=20
       // Conjure a symbol value to use as the result.
       SValBuilder &SVB =3D Eng.getSValBuilder();
-      unsigned Count =3D Builder.getCurrentBlockCount();
-      SVal RetVal =3D SVB.getConjuredSymbolVal(0, CE, ResultTy, Count);
+      unsigned Count =3D Eng.currentBuilderContext->getCurrentBlockCount();
+      const LocationContext *LCtx =3D Pred->getLocationContext();
+      SVal RetVal =3D SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Coun=
t);
=20
       // Generate a new state with the return value set.
-      state =3D state->BindExpr(CE, RetVal);
+      state =3D state->BindExpr(CE, LCtx, RetVal);
=20
       // Invalidate the arguments.
-      const LocationContext *LC =3D Pred->getLocationContext();
-      state =3D Eng.invalidateArguments(state, CallOrObjCMessage(CE, state=
), LC);
+      state =3D Eng.invalidateArguments(state, CallOrObjCMessage(CE, state=
, LCtx),
+                                      LCtx);
=20
       // And make the result node.
-      Eng.MakeNode(Dst, CE, Pred, state);
+      Bldr.generateNode(CE, Pred, state);
     }
   };
  =20
@@ -231,23 +467,16 @@
=20
 void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
                                  ExplodedNodeSet &Dst) {
-  ExplodedNodeSet Src;
-  if (const Expr *RetE =3D RS->getRetValue()) {
-    // Record the returned expression in the state. It will be used in
-    // processCallExit to bind the return value to the call expr.
-    {
-      static SimpleProgramPointTag tag("ExprEngine: ReturnStmt");
-      const ProgramState *state =3D Pred->getState();
-      state =3D state->set<ReturnExpr>(RetE);
-      Pred =3D Builder->generateNode(RetE, state, Pred, &tag);
+ =20
+  ExplodedNodeSet dstPreVisit;
+  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
+
+  StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
+ =20
+  if (RS->getRetValue()) {
+    for (ExplodedNodeSet::iterator it =3D dstPreVisit.begin(),
+                                  ei =3D dstPreVisit.end(); it !=3D ei; ++=
it) {
+      B.generateNode(RS, *it, (*it)->getState());
     }
-    // We may get a NULL Pred because we generated a cached node.
-    if (Pred)
-      Visit(RetE, Pred, Src);
   }
-  else {
-    Src.Add(Pred);
-  }
- =20
-  getCheckerManager().runCheckersForPreStmt(Dst, Src, RS, *this);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ExprEngineObjC.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.=
cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.=
cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -11,10 +11,10 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "clang/AST/StmtObjC.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
-#include "clang/Analysis/Support/SaveAndRestore.h"
=20
 using namespace clang;
 using namespace ento;
@@ -22,13 +22,14 @@
 void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,=20
                                           ExplodedNode *Pred,
                                           ExplodedNodeSet &Dst) {
- =20
-  const ProgramState *state =3D Pred->getState();
-  SVal baseVal =3D state->getSVal(Ex->getBase());
+  ProgramStateRef state =3D Pred->getState();
+  const LocationContext *LCtx =3D Pred->getLocationContext();
+  SVal baseVal =3D state->getSVal(Ex->getBase(), LCtx);
   SVal location =3D state->getLValue(Ex->getDecl(), baseVal);
  =20
   ExplodedNodeSet dstIvar;
-  MakeNode(dstIvar, Ex, Pred, state->BindExpr(Ex, location));
+  StmtNodeBuilder Bldr(Pred, dstIvar, *currentBuilderContext);
+  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, location));
  =20
   // Perform the post-condition check of the ObjCIvarRefExpr and store
   // the created nodes in 'Dst'.
@@ -69,10 +70,11 @@
   //  For now: simulate (1) by assigning either a symbol or nil if the
   //    container is empty.  Thus this transfer function will by default
   //    result in state splitting.
- =20
+
   const Stmt *elem =3D S->getElement();
-  const ProgramState *state =3D Pred->getState();
+  ProgramStateRef state =3D Pred->getState();
   SVal elementV;
+  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  =20
   if (const DeclStmt *DS =3D dyn_cast<DeclStmt>(elem)) {
     const VarDecl *elemD =3D cast<VarDecl>(DS->getSingleDecl());
@@ -80,27 +82,27 @@
     elementV =3D state->getLValue(elemD, Pred->getLocationContext());
   }
   else {
-    elementV =3D state->getSVal(elem);
+    elementV =3D state->getSVal(elem, Pred->getLocationContext());
   }
  =20
   ExplodedNodeSet dstLocation;
-  evalLocation(dstLocation, elem, Pred, state, elementV, NULL, false);
- =20
-  if (dstLocation.empty())
-    return;
+  Bldr.takeNodes(Pred);
+  evalLocation(dstLocation, S, elem, Pred, state, elementV, NULL, false);
+  Bldr.addNodes(dstLocation);
  =20
   for (ExplodedNodeSet::iterator NI =3D dstLocation.begin(),
        NE =3D dstLocation.end(); NI!=3DNE; ++NI) {
     Pred =3D *NI;
-    const ProgramState *state =3D Pred->getState();
+    ProgramStateRef state =3D Pred->getState();
+    const LocationContext *LCtx =3D Pred->getLocationContext();
    =20
     // Handle the case where the container still has elements.
     SVal TrueV =3D svalBuilder.makeTruthVal(1);
-    const ProgramState *hasElems =3D state->BindExpr(S, TrueV);
+    ProgramStateRef hasElems =3D state->BindExpr(S, LCtx, TrueV);
    =20
     // Handle the case where the container has no elements.
     SVal FalseV =3D svalBuilder.makeTruthVal(0);
-    const ProgramState *noElems =3D state->BindExpr(S, FalseV);
+    ProgramStateRef noElems =3D state->BindExpr(S, LCtx, FalseV);
    =20
     if (loc::MemRegionVal *MV =3D dyn_cast<loc::MemRegionVal>(&elementV))
       if (const TypedValueRegion *R =3D=20
@@ -110,8 +112,8 @@
         //  For now, just 'conjure' up a symbolic value.
         QualType T =3D R->getValueType();
         assert(Loc::isLocType(T));
-        unsigned Count =3D Builder->getCurrentBlockCount();
-        SymbolRef Sym =3D SymMgr.getConjuredSymbol(elem, T, Count);
+        unsigned Count =3D currentBuilderContext->getCurrentBlockCount();
+        SymbolRef Sym =3D SymMgr.getConjuredSymbol(elem, LCtx, T, Count);
         SVal V =3D svalBuilder.makeLoc(Sym);
         hasElems =3D hasElems->bindLoc(elementV, V);
        =20
@@ -121,8 +123,8 @@
       }
    =20
     // Create the new nodes.
-    MakeNode(Dst, S, Pred, hasElems);
-    MakeNode(Dst, S, Pred, noElems);
+    Bldr.generateNode(S, Pred, hasElems);
+    Bldr.generateNode(S, Pred, noElems);
   }
 }
=20
@@ -137,29 +139,27 @@
  =20
   // Proceed with evaluate the message expression.
   ExplodedNodeSet dstEval;
- =20
+  StmtNodeBuilder Bldr(dstPrevisit, dstEval, *currentBuilderContext);
+
   for (ExplodedNodeSet::iterator DI =3D dstPrevisit.begin(),
        DE =3D dstPrevisit.end(); DI !=3D DE; ++DI) {
    =20
     ExplodedNode *Pred =3D *DI;
     bool RaisesException =3D false;
-    SaveAndRestore<bool> OldSink(Builder->BuildSinks);
-    SaveOr OldHasGen(Builder->hasGeneratedNode);
    =20
     if (const Expr *Receiver =3D msg.getInstanceReceiver()) {
-      const ProgramState *state =3D Pred->getState();
-      SVal recVal =3D state->getSVal(Receiver);
+      ProgramStateRef state =3D Pred->getState();
+      SVal recVal =3D state->getSVal(Receiver, Pred->getLocationContext());
       if (!recVal.isUndef()) {
         // Bifurcate the state into nil and non-nil ones.
         DefinedOrUnknownSVal receiverVal =3D cast<DefinedOrUnknownSVal>(re=
cVal);
        =20
-        const ProgramState *notNilState, *nilState;
+        ProgramStateRef notNilState, nilState;
         llvm::tie(notNilState, nilState) =3D state->assume(receiverVal);
        =20
         // There are three cases: can be nil or non-nil, must be nil, must=
 be
         // non-nil. We ignore must be nil, and merge the rest two into non=
-nil.
         if (nilState && !notNilState) {
-          dstEval.insert(Pred);
           continue;
         }
        =20
@@ -168,13 +168,10 @@
         if (msg.getSelector() =3D=3D RaiseSel)
           RaisesException =3D true;
        =20
-        // Check if we raise an exception.  For now treat these as sinks.
+        // If we raise an exception, for now treat it as a sink.
         // Eventually we will want to handle exceptions properly.
-        if (RaisesException)
-          Builder->BuildSinks =3D true;
-       =20
         // Dispatch to plug-in transfer function.
-        evalObjCMessage(dstEval, msg, Pred, notNilState);
+        evalObjCMessage(Bldr, msg, Pred, notNilState, RaisesException);
       }
     }
     else if (const ObjCInterfaceDecl *Iface =3D msg.getReceiverInterface()=
) {
@@ -217,16 +214,11 @@
           }
       }
      =20
-      // Check if we raise an exception.  For now treat these as sinks.
+      // If we raise an exception, for now treat it as a sink.
       // Eventually we will want to handle exceptions properly.
-      if (RaisesException)
-        Builder->BuildSinks =3D true;
-     =20
       // Dispatch to plug-in transfer function.
-      evalObjCMessage(dstEval, msg, Pred, Pred->getState());
+      evalObjCMessage(Bldr, msg, Pred, Pred->getState(), RaisesException);
     }
-
-    assert(Builder->BuildSinks || Builder->hasGeneratedNode);
   }
  =20
   // Finally, perform the post-condition check of the ObjCMessageExpr and =
store
@@ -234,11 +226,11 @@
   getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *th=
is);
 }
=20
-void ExprEngine::evalObjCMessage(ExplodedNodeSet &Dst, const ObjCMessage &=
msg,=20
+void ExprEngine::evalObjCMessage(StmtNodeBuilder &Bldr,
+                                 const ObjCMessage &msg,
                                  ExplodedNode *Pred,
-                                 const ProgramState *state) {
-  assert (Builder && "StmtNodeBuilder must be defined.");
-
+                                 ProgramStateRef state,
+                                 bool GenSink) {
   // First handle the return value.
   SVal ReturnValue =3D UnknownVal();
=20
@@ -252,7 +244,7 @@
     // These methods return their receivers.
     const Expr *ReceiverE =3D msg.getInstanceReceiver();
     if (ReceiverE)
-      ReturnValue =3D state->getSVal(ReceiverE);
+      ReturnValue =3D state->getSVal(ReceiverE, Pred->getLocationContext()=
);
     break;
   }
   }
@@ -261,19 +253,21 @@
   if (ReturnValue.isUnknown()) {
     SValBuilder &SVB =3D getSValBuilder();
     QualType ResultTy =3D msg.getResultType(getContext());
-    unsigned Count =3D Builder->getCurrentBlockCount();
+    unsigned Count =3D currentBuilderContext->getCurrentBlockCount();
     const Expr *CurrentE =3D cast<Expr>(currentStmt);
-    ReturnValue =3D SVB.getConjuredSymbolVal(NULL, CurrentE, ResultTy, Cou=
nt);
+    const LocationContext *LCtx =3D Pred->getLocationContext();
+    ReturnValue =3D SVB.getConjuredSymbolVal(NULL, CurrentE, LCtx, ResultT=
y, Count);
   }
=20
   // Bind the return value.
-  state =3D state->BindExpr(currentStmt, ReturnValue);
+  const LocationContext *LCtx =3D Pred->getLocationContext();
+  state =3D state->BindExpr(currentStmt, LCtx, ReturnValue);
=20
   // Invalidate the arguments (and the receiver)
-  const LocationContext *LC =3D Pred->getLocationContext();
-  state =3D invalidateArguments(state, CallOrObjCMessage(msg, state), LC);
+  state =3D invalidateArguments(state, CallOrObjCMessage(msg, state, LCtx)=
, LCtx);
=20
   // And create the new node.
-  MakeNode(Dst, msg.getOriginExpr(), Pred, state);
+  Bldr.generateNode(msg.getMessageExpr(), Pred, state, GenSink);
+  assert(Bldr.hasGeneratedNodes());
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/HTMLDiagnostics.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics=
.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/HTMLDiagnostics=
.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -39,15 +39,13 @@
   llvm::sys::Path Directory, FilePrefix;
   bool createdDir, noDir;
   const Preprocessor &PP;
-  std::vector<const PathDiagnostic*> BatchedDiags;
 public:
   HTMLDiagnostics(const std::string& prefix, const Preprocessor &pp);
=20
   virtual ~HTMLDiagnostics() { FlushDiagnostics(NULL); }
=20
-  virtual void FlushDiagnostics(SmallVectorImpl<std::string> *FilesMade);
-
-  virtual void HandlePathDiagnosticImpl(const PathDiagnostic* D);
+  virtual void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &D=
iags,
+                                    SmallVectorImpl<std::string> *FilesMad=
e);
=20
   virtual StringRef getName() const {
     return "HTMLDiagnostics";
@@ -88,34 +86,49 @@
 // Report processing.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-void HTMLDiagnostics::HandlePathDiagnosticImpl(const PathDiagnostic* D) {
-  if (!D)
-    return;
-
-  if (D->empty()) {
-    delete D;
-    return;
+void HTMLDiagnostics::FlushDiagnosticsImpl(
+  std::vector<const PathDiagnostic *> &Diags,
+  SmallVectorImpl<std::string> *FilesMade) {
+  for (std::vector<const PathDiagnostic *>::iterator it =3D Diags.begin(),
+       et =3D Diags.end(); it !=3D et; ++it) {
+    ReportDiag(**it, FilesMade);
   }
-
-  const_cast<PathDiagnostic*>(D)->flattenLocations();
-  BatchedDiags.push_back(D);
 }
=20
-void
-HTMLDiagnostics::FlushDiagnostics(SmallVectorImpl<std::string> *FilesMade)
-{
-  while (!BatchedDiags.empty()) {
-    const PathDiagnostic* D =3D BatchedDiags.back();
-    BatchedDiags.pop_back();
-    ReportDiag(*D, FilesMade);
-    delete D;
+static void flattenPath(PathPieces &primaryPath, PathPieces &currentPath,
+                        const PathPieces &oldPath) {
+  for (PathPieces::const_iterator it =3D oldPath.begin(), et =3D oldPath.e=
nd();
+       it !=3D et; ++it ) {
+    PathDiagnosticPiece *piece =3D it->getPtr();
+    if (const PathDiagnosticCallPiece *call =3D
+        dyn_cast<PathDiagnosticCallPiece>(piece)) {
+      IntrusiveRefCntPtr<PathDiagnosticEventPiece> callEnter =3D
+        call->getCallEnterEvent();
+      if (callEnter)
+        currentPath.push_back(callEnter);
+      flattenPath(primaryPath, primaryPath, call->path);
+      IntrusiveRefCntPtr<PathDiagnosticEventPiece> callExit =3D
+        call->getCallExitEvent();
+      if (callExit)
+        currentPath.push_back(callExit);
+      continue;
+    }
+    if (PathDiagnosticMacroPiece *macro =3D
+        dyn_cast<PathDiagnosticMacroPiece>(piece)) {
+      currentPath.push_back(piece);
+      PathPieces newPath;
+      flattenPath(primaryPath, newPath, macro->subPieces);
+      macro->subPieces =3D newPath;
+      continue;
+    }
+   =20
+    currentPath.push_back(piece);
   }
-
-  BatchedDiags.clear();
 }
=20
 void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
-                                 SmallVectorImpl<std::string> *FilesMade){
+                                 SmallVectorImpl<std::string> *FilesMade) {
+   =20
   // Create the HTML directory if it is missing.
   if (!createdDir) {
     createdDir =3D true;
@@ -138,47 +151,29 @@
   if (noDir)
     return;
=20
-  const SourceManager &SMgr =3D D.begin()->getLocation().getManager();
-  FileID FID;
+  // First flatten out the entire path to make it easier to use.
+  PathPieces path;
+  flattenPath(path, path, D.path);
=20
-  // Verify that the entire path is from the same FileID.
-  for (PathDiagnostic::const_iterator I =3D D.begin(), E =3D D.end(); I !=
=3D E; ++I) {
-    FullSourceLoc L =3D I->getLocation().asLocation().getExpansionLoc();
-
-    if (FID.isInvalid()) {
-      FID =3D SMgr.getFileID(L);
-    } else if (SMgr.getFileID(L) !=3D FID)
-      return; // FIXME: Emit a warning?
-
-    // Check the source ranges.
-    for (PathDiagnosticPiece::range_iterator RI=3DI->ranges_begin(),
-                                             RE=3DI->ranges_end(); RI!=3DR=
E; ++RI) {
-
-      SourceLocation L =3D SMgr.getExpansionLoc(RI->getBegin());
-
-      if (!L.isFileID() || SMgr.getFileID(L) !=3D FID)
-        return; // FIXME: Emit a warning?
-
-      L =3D SMgr.getExpansionLoc(RI->getEnd());
-
-      if (!L.isFileID() || SMgr.getFileID(L) !=3D FID)
-        return; // FIXME: Emit a warning?
-    }
-  }
-
-  if (FID.isInvalid())
-    return; // FIXME: Emit a warning?
+  // The path as already been prechecked that all parts of the path are
+  // from the same file and that it is non-empty.
+  const SourceManager &SMgr =3D (*path.begin())->getLocation().getManager(=
);
+  assert(!path.empty());
+  FileID FID =3D
+    (*path.begin())->getLocation().asLocation().getExpansionLoc().getFileI=
D();
+  assert(!FID.isInvalid());
=20
   // Create a new rewriter to generate HTML.
-  Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOptions());
+  Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
=20
   // Process the path.
-  unsigned n =3D D.size();
+  unsigned n =3D path.size();
   unsigned max =3D n;
=20
-  for (PathDiagnostic::const_reverse_iterator I=3DD.rbegin(), E=3DD.rend();
-        I!=3DE; ++I, --n)
-    HandlePiece(R, FID, *I, n, max);
+  for (PathPieces::const_reverse_iterator I =3D path.rbegin(),=20
+       E =3D path.rend();
+        I !=3D E; ++I, --n)
+    HandlePiece(R, FID, **I, n, max);
=20
   // Add line numbers, header, footer, etc.
=20
@@ -221,9 +216,9 @@
       << html::EscapeText(Entry->getName())
       << "</td></tr>\n<tr><td class=3D\"rowname\">Location:</td><td>"
          "<a href=3D\"#EndPath\">line "
-      << (*D.rbegin()).getLocation().asLocation().getExpansionLineNumber()
+      << (*path.rbegin())->getLocation().asLocation().getExpansionLineNumb=
er()
       << ", column "
-      << (*D.rbegin()).getLocation().asLocation().getExpansionColumnNumber=
()
+      << (*path.rbegin())->getLocation().asLocation().getExpansionColumnNu=
mber()
       << "</a></td></tr>\n"
          "<tr><td class=3D\"rowname\">Description:</td><td>"
       << D.getDescription() << "</td></tr>\n";
@@ -261,10 +256,10 @@
     os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
=20
     os << "\n<!-- BUGLINE "
-       << D.back()->getLocation().asLocation().getExpansionLineNumber()
+       << path.back()->getLocation().asLocation().getExpansionLineNumber()
        << " -->\n";
=20
-    os << "\n<!-- BUGPATHLENGTH " << D.size() << " -->\n";
+    os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
=20
     // Mark the end of the tags.
     os << "\n<!-- BUGMETAEND -->\n";
@@ -353,6 +348,8 @@
=20
   const char *Kind =3D 0;
   switch (P.getKind()) {
+  case PathDiagnosticPiece::Call:
+      llvm_unreachable("Calls should already be handled");
   case PathDiagnosticPiece::Event:  Kind =3D "Event"; break;
   case PathDiagnosticPiece::ControlFlow: Kind =3D "Control"; break;
     // Setting Kind to "Control" is intentional.
@@ -445,7 +442,7 @@
       assert(L.isFileID());
       StringRef BufferInfo =3D L.getBufferData();
       const char* MacroName =3D L.getDecomposedLoc().second + BufferInfo.d=
ata();
-      Lexer rawLexer(L, PP.getLangOptions(), BufferInfo.begin(),
+      Lexer rawLexer(L, PP.getLangOpts(), BufferInfo.begin(),
                      MacroName, BufferInfo.end());
=20
       Token TheTok;
@@ -518,7 +515,7 @@
                                             const PathDiagnosticMacroPiece=
& P,
                                             unsigned num) {
=20
-  for (PathDiagnosticMacroPiece::const_iterator I=3DP.begin(), E=3DP.end();
+  for (PathPieces::const_iterator I =3D P.subPieces.begin(), E=3DP.subPiec=
es.end();
         I!=3DE; ++I) {
=20
     if (const PathDiagnosticMacroPiece *MP =3D
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/MemRegion.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp	T=
ue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/MemRegion.cpp	T=
ue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,9 @@
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Analysis/Support/BumpVector.h"
 #include "clang/AST/CharUnits.h"
+#include "clang/AST/DeclObjC.h"
 #include "clang/AST/RecordLayout.h"
+#include "clang/Basic/SourceManager.h"
 #include "llvm/Support/raw_ostream.h"
=20
 using namespace clang;
@@ -219,6 +221,17 @@
                                 svalBuilder.getArrayIndexType());
 }
=20
+ObjCIvarRegion::ObjCIvarRegion(const ObjCIvarDecl *ivd, const MemRegion* s=
Reg)
+  : DeclRegion(ivd, sReg, ObjCIvarRegionKind) {}
+
+const ObjCIvarDecl *ObjCIvarRegion::getDecl() const {
+  return cast<ObjCIvarDecl>(D);
+}
+
+QualType ObjCIvarRegion::getValueType() const {
+  return getDecl()->getType();
+}
+
 QualType CXXBaseObjectRegion::getValueType() const {
   return QualType(decl->getTypeForDecl(), 0);
 }
@@ -249,6 +262,14 @@
   ID.AddPointer(superRegion);
 }
=20
+void ObjCStringRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+                                     const ObjCStringLiteral* Str,
+                                     const MemRegion* superRegion) {
+  ID.AddInteger((unsigned) ObjCStringRegionKind);
+  ID.AddPointer(Str);
+  ID.AddPointer(superRegion);
+}
+
 void AllocaRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
                                  const Expr *Ex, unsigned cnt,
                                  const MemRegion *) {
@@ -285,6 +306,12 @@
   CXXThisRegion::ProfileRegion(ID, ThisPointerTy, superRegion);
 }
=20
+void ObjCIvarRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
+                                   const ObjCIvarDecl *ivd,
+                                   const MemRegion* superRegion) {
+  DeclRegion::ProfileRegion(ID, ivd, superRegion, ObjCIvarRegionKind);
+}
+
 void DeclRegion::ProfileRegion(llvm::FoldingSetNodeID& ID, const Decl *D,
                                const MemRegion* superRegion, Kind k) {
   ID.AddInteger((unsigned) k);
@@ -337,7 +364,7 @@
=20
 void BlockTextRegion::ProfileRegion(llvm::FoldingSetNodeID& ID,
                                     const BlockDecl *BD, CanQualType,
-                                    const AnalysisContext *AC,
+                                    const AnalysisDeclContext *AC,
                                     const MemRegion*) {
   ID.AddInteger(MemRegion::BlockTextRegionKind);
   ID.AddPointer(BD);
@@ -384,6 +411,20 @@
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Region anchors.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+void GlobalsSpaceRegion::anchor() { }
+void HeapSpaceRegion::anchor() { }
+void UnknownSpaceRegion::anchor() { }
+void StackLocalsSpaceRegion::anchor() { }
+void StackArgumentsSpaceRegion::anchor() { }
+void TypedRegion::anchor() { }
+void TypedValueRegion::anchor() { }
+void CodeTextRegion::anchor() { }
+void SubRegion::anchor() { }
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Region pretty-printing.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -445,16 +486,16 @@
   os << superRegion << "->" << *getDecl();
 }
=20
-void NonStaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
-  os << "NonStaticGlobalSpaceRegion";
-}
-
 void ObjCIvarRegion::dumpToStream(raw_ostream &os) const {
   os << "ivar{" << superRegion << ',' << *getDecl() << '}';
 }
=20
 void StringRegion::dumpToStream(raw_ostream &os) const {
-  Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOptions()));
+  Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOpts()));
+}
+
+void ObjCStringRegion::dumpToStream(raw_ostream &os) const {
+  Str->printPretty(os, 0, PrintingPolicy(getContext().getLangOpts()));
 }
=20
 void SymbolicRegion::dumpToStream(raw_ostream &os) const {
@@ -477,6 +518,35 @@
   os << "StaticGlobalsMemSpace{" << CR << '}';
 }
=20
+void NonStaticGlobalSpaceRegion::dumpToStream(raw_ostream &os) const {
+  os << "NonStaticGlobalSpaceRegion";
+}
+
+void GlobalInternalSpaceRegion::dumpToStream(raw_ostream &os) const {
+  os << "GlobalInternalSpaceRegion";
+}
+
+void GlobalSystemSpaceRegion::dumpToStream(raw_ostream &os) const {
+  os << "GlobalSystemSpaceRegion";
+}
+
+void GlobalImmutableSpaceRegion::dumpToStream(raw_ostream &os) const {
+  os << "GlobalImmutableSpaceRegion";
+}
+
+void MemRegion::dumpPretty(raw_ostream &os) const {
+  return;
+}
+
+void VarRegion::dumpPretty(raw_ostream &os) const {
+  os << getDecl()->getName();
+}
+
+void FieldRegion::dumpPretty(raw_ostream &os) const {
+  superRegion->dumpPretty(os);
+  os << "->" << getDecl();
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // MemRegionManager methods.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -528,10 +598,18 @@
 }
=20
 const GlobalsSpaceRegion
-*MemRegionManager::getGlobalsRegion(const CodeTextRegion *CR) {
-  if (!CR)
-    return LazyAllocate(globals);
+*MemRegionManager::getGlobalsRegion(MemRegion::Kind K,
+                                    const CodeTextRegion *CR) {
+  if (!CR) {
+    if (K =3D=3D MemRegion::GlobalSystemSpaceRegionKind)
+      return LazyAllocate(SystemGlobals);
+    if (K =3D=3D MemRegion::GlobalImmutableSpaceRegionKind)
+      return LazyAllocate(ImmutableGlobals);
+    assert(K =3D=3D MemRegion::GlobalInternalSpaceRegionKind);
+    return LazyAllocate(InternalGlobals);
+  }
=20
+  assert(K =3D=3D MemRegion::StaticGlobalSpaceRegionKind);
   StaticGlobalSpaceRegion *&R =3D StaticsGlobalSpaceRegions[CR];
   if (R)
     return R;
@@ -556,18 +634,44 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Constructing regions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
-
 const StringRegion* MemRegionManager::getStringRegion(const StringLiteral*=
 Str){
   return getSubRegion<StringRegion>(Str, getGlobalsRegion());
 }
=20
+const ObjCStringRegion *
+MemRegionManager::getObjCStringRegion(const ObjCStringLiteral* Str){
+  return getSubRegion<ObjCStringRegion>(Str, getGlobalsRegion());
+}
+
 const VarRegion* MemRegionManager::getVarRegion(const VarDecl *D,
                                                 const LocationContext *LC)=
 {
   const MemRegion *sReg =3D 0;
=20
-  if (D->hasGlobalStorage() && !D->isStaticLocal())
-    sReg =3D getGlobalsRegion();
-  else {
+  if (D->hasGlobalStorage() && !D->isStaticLocal()) {
+
+    // First handle the globals defined in system headers.
+    if (C.getSourceManager().isInSystemHeader(D->getLocation())) {
+      // Whitelist the system globals which often DO GET modified, assume =
the
+      // rest are immutable.
+      if (D->getName().find("errno") !=3D StringRef::npos)
+        sReg =3D getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
+      else
+        sReg =3D getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKin=
d);
+
+    // Treat other globals as GlobalInternal unless they are constants.
+    } else {
+      QualType GQT =3D D->getType();
+      const Type *GT =3D GQT.getTypePtrOrNull();
+      // TODO: We could walk the complex types here and see if everything =
is
+      // constified.
+      if (GT && GQT.isConstQualified() && GT->isArithmeticType())
+        sReg =3D getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKin=
d);
+      else
+        sReg =3D getGlobalsRegion();
+    }
+ =20
+  // Finally handle static locals. =20
+  } else {
     // FIXME: Once we implement scope handling, we will need to properly l=
ookup
     // 'D' to the proper LocationContext.
     const DeclContext *DC =3D D->getDeclContext();
@@ -585,13 +689,15 @@
         assert(D->isStaticLocal());
         const Decl *D =3D STC->getDecl();
         if (const FunctionDecl *FD =3D dyn_cast<FunctionDecl>(D))
-          sReg =3D getGlobalsRegion(getFunctionTextRegion(FD));
+          sReg =3D getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
+                                  getFunctionTextRegion(FD));
         else if (const BlockDecl *BD =3D dyn_cast<BlockDecl>(D)) {
           const BlockTextRegion *BTR =3D
             getBlockTextRegion(BD,
                      C.getCanonicalType(BD->getSignatureAsWritten()->getTy=
pe()),
-                     STC->getAnalysisContext());
-          sReg =3D getGlobalsRegion(BTR);
+                     STC->getAnalysisDeclContext());
+          sReg =3D getGlobalsRegion(MemRegion::StaticGlobalSpaceRegionKind,
+                                  BTR);
         }
         else {
           // FIXME: For ObjC-methods, we need a new CodeTextRegion.  For n=
ow
@@ -614,18 +720,24 @@
 MemRegionManager::getBlockDataRegion(const BlockTextRegion *BC,
                                      const LocationContext *LC) {
   const MemRegion *sReg =3D 0;
-
-  if (LC) {
-    // FIXME: Once we implement scope handling, we want the parent region
-    // to be the scope.
-    const StackFrameContext *STC =3D LC->getCurrentStackFrame();
-    assert(STC);
-    sReg =3D getStackLocalsRegion(STC);
+  const BlockDecl *BD =3D BC->getDecl();
+  if (!BD->hasCaptures()) {
+    // This handles 'static' blocks.
+    sReg =3D getGlobalsRegion(MemRegion::GlobalImmutableSpaceRegionKind);
   }
   else {
-    // We allow 'LC' to be NULL for cases where want BlockDataRegions
-    // without context-sensitivity.
-    sReg =3D getUnknownRegion();
+    if (LC) {
+      // FIXME: Once we implement scope handling, we want the parent region
+      // to be the scope.
+      const StackFrameContext *STC =3D LC->getCurrentStackFrame();
+      assert(STC);
+      sReg =3D getStackLocalsRegion(STC);
+    }
+    else {
+      // We allow 'LC' to be NULL for cases where want BlockDataRegions
+      // without context-sensitivity.
+      sReg =3D getUnknownRegion();
+    }
   }
=20
   return getSubRegion<BlockDataRegion>(BC, LC, sReg);
@@ -678,7 +790,7 @@
=20
 const BlockTextRegion *
 MemRegionManager::getBlockTextRegion(const BlockDecl *BD, CanQualType locT=
y,
-                                     AnalysisContext *AC) {
+                                     AnalysisDeclContext *AC) {
   return getSubRegion<BlockTextRegion>(BD, locTy, AC, getCodeRegion());
 }
=20
@@ -928,8 +1040,8 @@
   if (ReferencedVars)
     return;
=20
-  AnalysisContext *AC =3D getCodeRegion()->getAnalysisContext();
-  AnalysisContext::referenced_decls_iterator I, E;
+  AnalysisDeclContext *AC =3D getCodeRegion()->getAnalysisDeclContext();
+  AnalysisDeclContext::referenced_decls_iterator I, E;
   llvm::tie(I, E) =3D AC->getReferencedBlockVars(BC->getDecl());
=20
   if (I =3D=3D E) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ObjCMessage.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ObjCMessage.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ObjCMessage.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -13,108 +13,16 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
+#include "clang/AST/DeclCXX.h"
=20
 using namespace clang;
 using namespace ento;
=20
-QualType ObjCMessage::getType(ASTContext &ctx) const {
-  assert(isValid() && "This ObjCMessage is uninitialized!");
-  if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPropE=
))
-    return msgE->getType();
-  const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrProp=
E);
-  if (isPropertySetter())
-    return ctx.VoidTy;
-  return propE->getType();
-}
-
-Selector ObjCMessage::getSelector() const {
-  assert(isValid() && "This ObjCMessage is uninitialized!");
-  if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPropE=
))
-    return msgE->getSelector();
-  const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrProp=
E);
-  if (isPropertySetter())
-    return propE->getSetterSelector();
-  return propE->getGetterSelector();
-}
-
-ObjCMethodFamily ObjCMessage::getMethodFamily() const {
-  assert(isValid() && "This ObjCMessage is uninitialized!");
-  // Case 1.  Explicit message send.
-  if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPropE=
))
-    return msgE->getMethodFamily();
-
-  const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrProp=
E);
-
-  // Case 2.  Reference to implicit property.
-  if (propE->isImplicitProperty()) {
-    if (isPropertySetter())
-      return propE->getImplicitPropertySetter()->getMethodFamily();
-    else
-      return propE->getImplicitPropertyGetter()->getMethodFamily();
-  }
-
-  // Case 3.  Reference to explicit property.
-  const ObjCPropertyDecl *prop =3D propE->getExplicitProperty();
-  if (isPropertySetter()) {
-    if (prop->getSetterMethodDecl())
-      return prop->getSetterMethodDecl()->getMethodFamily();
-    return prop->getSetterName().getMethodFamily();
-  } else {
-    if (prop->getGetterMethodDecl())
-      return prop->getGetterMethodDecl()->getMethodFamily();
-    return prop->getGetterName().getMethodFamily();
-  }
-}
-
-const ObjCMethodDecl *ObjCMessage::getMethodDecl() const {
-  assert(isValid() && "This ObjCMessage is uninitialized!");
-  if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPropE=
))
-    return msgE->getMethodDecl();
-  const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrProp=
E);
-  if (propE->isImplicitProperty())
-    return isPropertySetter() ? propE->getImplicitPropertySetter()
-                              : propE->getImplicitPropertyGetter();
-  return 0;
-}
-
-const ObjCInterfaceDecl *ObjCMessage::getReceiverInterface() const {
-  assert(isValid() && "This ObjCMessage is uninitialized!");
-  if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPropE=
))
-    return msgE->getReceiverInterface();
-  const ObjCPropertyRefExpr *propE =3D cast<ObjCPropertyRefExpr>(MsgOrProp=
E);
-  if (propE->isClassReceiver())
-    return propE->getClassReceiver();
-  QualType recT;
-  if (const Expr *recE =3D getInstanceReceiver())
-    recT =3D recE->getType();
-  else {
-    assert(propE->isSuperReceiver());
-    recT =3D propE->getSuperReceiverType();
-  }
-  if (const ObjCObjectPointerType *Ptr =3D recT->getAs<ObjCObjectPointerTy=
pe>())
-    return Ptr->getInterfaceDecl();
-  return 0;
-}
-
-const Expr *ObjCMessage::getArgExpr(unsigned i) const {
-  assert(isValid() && "This ObjCMessage is uninitialized!");
-  assert(i < getNumArgs() && "Invalid index for argument");
-  if (const ObjCMessageExpr *msgE =3D dyn_cast<ObjCMessageExpr>(MsgOrPropE=
))
-    return msgE->getArg(i);
-  assert(isPropertySetter());
-  if (const BinaryOperator *bop =3D dyn_cast<BinaryOperator>(OriginE))
-    if (bop->isAssignmentOp())
-      return bop->getRHS();
-  return 0;
-}
-
 QualType CallOrObjCMessage::getResultType(ASTContext &ctx) const {
   QualType resultTy;
   bool isLVal =3D false;
=20
   if (isObjCMessage()) {
-    isLVal =3D isa<ObjCMessageExpr>(Msg.getOriginExpr()) &&
-             Msg.getOriginExpr()->isLValue();
     resultTy =3D Msg.getResultType(ctx);
   } else if (const CXXConstructExpr *Ctor =3D
               CallE.dyn_cast<const CXXConstructExpr *>()) {
@@ -124,7 +32,7 @@
=20
     isLVal =3D FunctionCall->isLValue();
     const Expr *Callee =3D FunctionCall->getCallee();
-    if (const FunctionDecl *FD =3D State->getSVal(Callee).getAsFunctionDec=
l())
+    if (const FunctionDecl *FD =3D State->getSVal(Callee, LCtx).getAsFunct=
ionDecl())
       resultTy =3D FD->getResultType();
     else
       resultTy =3D FunctionCall->getType();
@@ -140,7 +48,7 @@
   assert(isFunctionCall());
   assert(!isCXXCall());
   const Expr *Fun =3D CallE.get<const CallExpr *>()->getCallee()->IgnorePa=
rens();
-  return State->getSVal(Fun);
+  return State->getSVal(Fun, LCtx);
 }
=20
 SVal CallOrObjCMessage::getCXXCallee() const {
@@ -154,7 +62,7 @@
   if (!callee)
     return UnknownVal();
  =20
-  return State->getSVal(callee);
+  return State->getSVal(callee, LCtx);
 }
=20
 SVal
@@ -162,3 +70,21 @@
   assert(isObjCMessage());
   return Msg.getInstanceReceiverSVal(State, LC);
 }
+
+const Decl *CallOrObjCMessage::getDecl() const {
+  if (isCXXCall()) {
+    const CXXMemberCallExpr *CE =3D
+        cast<CXXMemberCallExpr>(CallE.dyn_cast<const CallExpr *>());
+    assert(CE);
+    return CE->getMethodDecl();
+  } else if (isObjCMessage()) {
+    return Msg.getMethodDecl();
+  } else if (isFunctionCall()) {
+    // In case of a C style call, use the path sensitive information to fi=
nd
+    // the function declaration.
+    SVal CalleeVal =3D getFunctionCallee();
+    return CalleeVal.getAsFunctionDecl();
+  }
+  return 0;
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/PathDiagnostic.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/PathDiagnostic.=
cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/PathDiagnostic.=
cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -13,6 +13,7 @@
=20
 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
+#include "clang/Basic/SourceManager.h"
 #include "clang/AST/Expr.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
@@ -24,15 +25,14 @@
 using namespace ento;
=20
 bool PathDiagnosticMacroPiece::containsEvent() const {
-  for (const_iterator I =3D begin(), E =3D end(); I!=3DE; ++I) {
+  for (PathPieces::const_iterator I =3D subPieces.begin(), E =3D subPieces=
.end();
+       I!=3DE; ++I) {
     if (isa<PathDiagnosticEventPiece>(*I))
       return true;
-
     if (PathDiagnosticMacroPiece *MP =3D dyn_cast<PathDiagnosticMacroPiece=
>(*I))
       if (MP->containsEvent())
         return true;
   }
-
   return false;
 }
=20
@@ -52,41 +52,189 @@
=20
 PathDiagnosticPiece::~PathDiagnosticPiece() {}
 PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
+PathDiagnosticCallPiece::~PathDiagnosticCallPiece() {}
 PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
+PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {}
=20
-PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {
-  for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I) delete *I;
+
+PathPieces::~PathPieces() {}
+PathDiagnostic::~PathDiagnostic() {}
+
+PathDiagnostic::PathDiagnostic(const Decl *declWithIssue,
+                               StringRef bugtype, StringRef desc,
+                               StringRef category)
+  : DeclWithIssue(declWithIssue),
+    BugType(StripTrailingDots(bugtype)),
+    Desc(StripTrailingDots(desc)),
+    Category(StripTrailingDots(category)),
+    path(pathImpl) {}
+
+void PathDiagnosticConsumer::anchor() { }
+
+PathDiagnosticConsumer::~PathDiagnosticConsumer() {
+  // Delete the contents of the FoldingSet if it isn't empty already.
+  for (llvm::FoldingSet<PathDiagnostic>::iterator it =3D
+       Diags.begin(), et =3D Diags.end() ; it !=3D et ; ++it) {
+    delete &*it;
+  }
 }
=20
-PathDiagnostic::PathDiagnostic() : Size(0) {}
+void PathDiagnosticConsumer::HandlePathDiagnostic(PathDiagnostic *D) {
+  llvm::OwningPtr<PathDiagnostic> OwningD(D);
+ =20
+  if (!D || D->path.empty())
+    return;
+ =20
+  // We need to flatten the locations (convert Stmt* to locations) because
+  // the referenced statements may be freed by the time the diagnostics
+  // are emitted.
+  D->flattenLocations();
=20
-PathDiagnostic::~PathDiagnostic() {
-  for (iterator I =3D begin(), E =3D end(); I !=3D E; ++I) delete &*I;
+  // If the PathDiagnosticConsumer does not support diagnostics that
+  // cross file boundaries, prune out such diagnostics now.
+  if (!supportsCrossFileDiagnostics()) {
+    // Verify that the entire path is from the same FileID.
+    FileID FID;
+    const SourceManager &SMgr =3D (*D->path.begin())->getLocation().getMan=
ager();
+    llvm::SmallVector<const PathPieces *, 5> WorkList;
+    WorkList.push_back(&D->path);
+
+    while (!WorkList.empty()) {
+      const PathPieces &path =3D *WorkList.back();
+      WorkList.pop_back();
+
+      for (PathPieces::const_iterator I =3D path.begin(), E =3D path.end();
+           I !=3D E; ++I) {
+        const PathDiagnosticPiece *piece =3D I->getPtr();
+        FullSourceLoc L =3D piece->getLocation().asLocation().getExpansion=
Loc();
+     =20
+        if (FID.isInvalid()) {
+          FID =3D SMgr.getFileID(L);
+        } else if (SMgr.getFileID(L) !=3D FID)
+          return; // FIXME: Emit a warning?
+     =20
+        // Check the source ranges.
+        for (PathDiagnosticPiece::range_iterator RI =3D piece->ranges_begi=
n(),
+             RE =3D piece->ranges_end();
+             RI !=3D RE; ++RI) {
+          SourceLocation L =3D SMgr.getExpansionLoc(RI->getBegin());
+          if (!L.isFileID() || SMgr.getFileID(L) !=3D FID)
+            return; // FIXME: Emit a warning?
+          L =3D SMgr.getExpansionLoc(RI->getEnd());
+          if (!L.isFileID() || SMgr.getFileID(L) !=3D FID)
+            return; // FIXME: Emit a warning?
+        }
+       =20
+        if (const PathDiagnosticCallPiece *call =3D
+            dyn_cast<PathDiagnosticCallPiece>(piece)) {
+          WorkList.push_back(&call->path);
+        }
+        else if (const PathDiagnosticMacroPiece *macro =3D
+                 dyn_cast<PathDiagnosticMacroPiece>(piece)) {
+          WorkList.push_back(&macro->subPieces);
+        }
+      }
+    }
+   =20
+    if (FID.isInvalid())
+      return; // FIXME: Emit a warning?
+  } =20
+
+  // Profile the node to see if we already have something matching it
+  llvm::FoldingSetNodeID profile;
+  D->Profile(profile);
+  void *InsertPos =3D 0;
+
+  if (PathDiagnostic *orig =3D Diags.FindNodeOrInsertPos(profile, InsertPo=
s)) {
+    // Keep the PathDiagnostic with the shorter path.
+    const unsigned orig_size =3D orig->full_size();
+    const unsigned new_size =3D D->full_size();
+   =20
+    if (orig_size <=3D new_size) {
+      bool shouldKeepOriginal =3D true;
+      if (orig_size =3D=3D new_size) {
+        // Here we break ties in a fairly arbitrary, but deterministic, wa=
y.
+        llvm::FoldingSetNodeID fullProfile, fullProfileOrig;
+        D->FullProfile(fullProfile);
+        orig->FullProfile(fullProfileOrig);
+        if (fullProfile.ComputeHash() < fullProfileOrig.ComputeHash())
+          shouldKeepOriginal =3D false;
+      }
+
+      if (shouldKeepOriginal)
+        return;
+    }
+    Diags.RemoveNode(orig);
+    delete orig;
+  }
+ =20
+  Diags.InsertNode(OwningD.take());
 }
=20
-void PathDiagnostic::resetPath(bool deletePieces) {
-  Size =3D 0;
=20
-  if (deletePieces)
-    for (iterator I=3Dbegin(), E=3Dend(); I!=3DE; ++I)
-      delete &*I;
-
-  path.clear();
+namespace {
+struct CompareDiagnostics {
+  // Compare if 'X' is "<" than 'Y'.
+  bool operator()(const PathDiagnostic *X, const PathDiagnostic *Y) const {
+    // First compare by location
+    const FullSourceLoc &XLoc =3D X->getLocation().asLocation();
+    const FullSourceLoc &YLoc =3D Y->getLocation().asLocation();
+    if (XLoc < YLoc)
+      return true;
+    if (XLoc !=3D YLoc)
+      return false;
+   =20
+    // Next, compare by bug type.
+    StringRef XBugType =3D X->getBugType();
+    StringRef YBugType =3D Y->getBugType();
+    if (XBugType < YBugType)
+      return true;
+    if (XBugType !=3D YBugType)
+      return false;
+   =20
+    // Next, compare by bug description.
+    StringRef XDesc =3D X->getDescription();
+    StringRef YDesc =3D Y->getDescription();
+    if (XDesc < YDesc)
+      return true;
+    if (XDesc !=3D YDesc)
+      return false;
+   =20
+    // FIXME: Further refine by comparing PathDiagnosticPieces?
+    return false;   =20
+  } =20
+}; =20
 }
=20
+void
+PathDiagnosticConsumer::FlushDiagnostics(SmallVectorImpl<std::string> *Fil=
es) {
+  if (flushed)
+    return;
+ =20
+  flushed =3D true;
+ =20
+  std::vector<const PathDiagnostic *> BatchDiags;
+  for (llvm::FoldingSet<PathDiagnostic>::iterator it =3D Diags.begin(),
+       et =3D Diags.end(); it !=3D et; ++it) {
+    BatchDiags.push_back(&*it);
+  }
+ =20
+  // Clear out the FoldingSet.
+  Diags.clear();
=20
-PathDiagnostic::PathDiagnostic(StringRef bugtype, StringRef desc,
-                               StringRef category)
-  : Size(0),
-    BugType(StripTrailingDots(bugtype)),
-    Desc(StripTrailingDots(desc)),
-    Category(StripTrailingDots(category)) {}
+  // Sort the diagnostics so that they are always emitted in a determinist=
ic
+  // order.
+  if (!BatchDiags.empty())
+    std::sort(BatchDiags.begin(), BatchDiags.end(), CompareDiagnostics());
+ =20
+  FlushDiagnosticsImpl(BatchDiags, Files);
=20
-void PathDiagnosticConsumer::HandlePathDiagnostic(const PathDiagnostic *D)=
 {
-  // For now this simply forwards to HandlePathDiagnosticImpl.  In the fut=
ure
-  // we can use this indirection to control for multi-threaded access to
-  // the PathDiagnosticConsumer from multiple bug reporters.
-  HandlePathDiagnosticImpl(D);
+  // Delete the flushed diagnostics.
+  for (std::vector<const PathDiagnostic *>::iterator it =3D BatchDiags.beg=
in(),
+       et =3D BatchDiags.end(); it !=3D et; ++it) {
+    const PathDiagnostic *D =3D *it;
+    delete D;
+  }
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -94,9 +242,9 @@
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
 static SourceLocation getValidSourceLocation(const Stmt* S,
-                                             LocationOrAnalysisContext LAC=
) {
+                                             LocationOrAnalysisDeclContext=
 LAC) {
   SourceLocation L =3D S->getLocStart();
-  assert(!LAC.isNull() && "A valid LocationContext or AnalysisContext shou=
ld "
+  assert(!LAC.isNull() && "A valid LocationContext or AnalysisDeclContext =
should "
                           "be passed to PathDiagnosticLocation upon creati=
on.");
=20
   // S might be a temporary statement that does not have a location in the
@@ -107,7 +255,7 @@
     if (LAC.is<const LocationContext*>())
       PM =3D &LAC.get<const LocationContext*>()->getParentMap();
     else
-      PM =3D &LAC.get<AnalysisContext*>()->getParentMap();
+      PM =3D &LAC.get<AnalysisDeclContext*>()->getParentMap();
=20
     while (!L.isValid()) {
       S =3D PM->getParent(S);
@@ -127,7 +275,7 @@
 PathDiagnosticLocation
   PathDiagnosticLocation::createBegin(const Stmt *S,
                                       const SourceManager &SM,
-                                      LocationOrAnalysisContext LAC) {
+                                      LocationOrAnalysisDeclContext LAC) {
   return PathDiagnosticLocation(getValidSourceLocation(S, LAC),
                                 SM, SingleLocK);
 }
@@ -193,9 +341,6 @@
   }
=20
   return PathDiagnosticLocation(S, SMng, P.getLocationContext());
-
-  if (!S)
-    return PathDiagnosticLocation();
 }
=20
 PathDiagnosticLocation
@@ -212,8 +357,9 @@
       return PathDiagnosticLocation(PS->getStmt(), SM, LC);
     else if (const BlockEdge *BE =3D dyn_cast<BlockEdge>(&P)) {
       const Stmt *Term =3D BE->getSrc()->getTerminator();
-      assert(Term);
-      return PathDiagnosticLocation(Term, SM, LC);
+      if (Term) {
+        return PathDiagnosticLocation(Term, SM, LC);
+      }
     }
     NI =3D NI->succ_empty() ? 0 : *(NI->succ_begin());
   }
@@ -229,7 +375,7 @@
=20
 FullSourceLoc
   PathDiagnosticLocation::genLocation(SourceLocation L,
-                                      LocationOrAnalysisContext LAC) const=
 {
+                                      LocationOrAnalysisDeclContext LAC) c=
onst {
   assert(isValid());
   // Note that we want a 'switch' here so that the compiler can warn us in
   // case we add more cases.
@@ -238,9 +384,15 @@
     case RangeK:
       break;
     case StmtK:
+      // Defensive checking.
+      if (!S)
+        break;
       return FullSourceLoc(getValidSourceLocation(S, LAC),
                            const_cast<SourceManager&>(*SM));
     case DeclK:
+      // Defensive checking.
+      if (!D)
+        break;
       return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*S=
M));
   }
=20
@@ -248,7 +400,7 @@
 }
=20
 PathDiagnosticRange
-  PathDiagnosticLocation::genRange(LocationOrAnalysisContext LAC) const {
+  PathDiagnosticLocation::genRange(LocationOrAnalysisDeclContext LAC) cons=
t {
   assert(isValid());
   // Note that we want a 'switch' here so that the compiler can warn us in
   // case we add more cases.
@@ -321,6 +473,132 @@
   }
 }
=20
+PathDiagnosticLocation PathDiagnostic::getLocation() const {
+  assert(path.size() > 0 &&
+         "getLocation() requires a non-empty PathDiagnostic.");
+ =20
+  PathDiagnosticPiece *p =3D path.rbegin()->getPtr();
+ =20
+  while (true) {
+    if (PathDiagnosticCallPiece *cp =3D dyn_cast<PathDiagnosticCallPiece>(=
p)) {
+      assert(!cp->path.empty());
+      p =3D cp->path.rbegin()->getPtr();
+      continue;
+    }
+    break;
+  }
+ =20
+  return p->getLocation();
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+// Manipulation of PathDiagnosticCallPieces.
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+static PathDiagnosticLocation getLastStmtLoc(const ExplodedNode *N,
+                                             const SourceManager &SM) {
+  while (N) {
+    ProgramPoint PP =3D N->getLocation();
+    if (const StmtPoint *SP =3D dyn_cast<StmtPoint>(&PP))
+      return PathDiagnosticLocation(SP->getStmt(), SM, PP.getLocationConte=
xt());
+    if (N->pred_empty())
+      break;
+    N =3D *N->pred_begin();
+  }
+  return PathDiagnosticLocation();
+}
+
+PathDiagnosticCallPiece *
+PathDiagnosticCallPiece::construct(const ExplodedNode *N,
+                                   const CallExit &CE,
+                                   const SourceManager &SM) {
+  const Decl *caller =3D CE.getLocationContext()->getParent()->getDecl();
+  PathDiagnosticLocation pos =3D getLastStmtLoc(N, SM);
+  return new PathDiagnosticCallPiece(caller, pos);
+}
+
+PathDiagnosticCallPiece *
+PathDiagnosticCallPiece::construct(PathPieces &path,
+                                   const Decl *caller) {
+  PathDiagnosticCallPiece *C =3D new PathDiagnosticCallPiece(path, caller);
+  path.clear();
+  path.push_front(C);
+  return C;
+}
+
+void PathDiagnosticCallPiece::setCallee(const CallEnter &CE,
+                                        const SourceManager &SM) {
+  const Decl *D =3D CE.getCalleeContext()->getDecl();
+  Callee =3D D;
+  callEnter =3D PathDiagnosticLocation(CE.getCallExpr(), SM,
+                                     CE.getLocationContext());
+  callEnterWithin =3D PathDiagnosticLocation::createBegin(D, SM);
+}
+
+IntrusiveRefCntPtr<PathDiagnosticEventPiece>
+PathDiagnosticCallPiece::getCallEnterEvent() const {
+  if (!Callee)
+    return 0; =20
+  SmallString<256> buf;
+  llvm::raw_svector_ostream Out(buf);
+  if (isa<BlockDecl>(Callee))
+    Out << "Calling anonymous block";
+  else if (const NamedDecl *ND =3D dyn_cast<NamedDecl>(Callee))
+    Out << "Calling '" << *ND << "'";
+  StringRef msg =3D Out.str();
+  if (msg.empty())
+    return 0;
+  return new PathDiagnosticEventPiece(callEnter, msg);
+}
+
+IntrusiveRefCntPtr<PathDiagnosticEventPiece>
+PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
+  SmallString<256> buf;
+  llvm::raw_svector_ostream Out(buf);
+  if (const NamedDecl *ND =3D dyn_cast_or_null<NamedDecl>(Caller))
+    Out << "Entered call from '" << *ND << "'";
+  else
+    Out << "Entered call";
+  StringRef msg =3D Out.str();
+  if (msg.empty())
+    return 0;
+  return new PathDiagnosticEventPiece(callEnterWithin, msg);
+}
+
+IntrusiveRefCntPtr<PathDiagnosticEventPiece>
+PathDiagnosticCallPiece::getCallExitEvent() const {
+  if (NoExit)
+    return 0;
+  SmallString<256> buf;
+  llvm::raw_svector_ostream Out(buf);
+  if (!CallStackMessage.empty())
+    Out << CallStackMessage;
+  else if (const NamedDecl *ND =3D dyn_cast_or_null<NamedDecl>(Callee))
+    Out << "Returning from '" << *ND << "'";
+  else
+    Out << "Returning to caller";
+  return new PathDiagnosticEventPiece(callReturn, Out.str());
+}
+
+static void compute_path_size(const PathPieces &pieces, unsigned &size) {
+  for (PathPieces::const_iterator it =3D pieces.begin(),
+                                  et =3D pieces.end(); it !=3D et; ++it) {
+    const PathDiagnosticPiece *piece =3D it->getPtr();
+    if (const PathDiagnosticCallPiece *cp =3D=20
+        dyn_cast<PathDiagnosticCallPiece>(piece)) {
+      compute_path_size(cp->path, size);
+    }
+    else
+      ++size;
+  }
+}
+
+unsigned PathDiagnostic::full_size() {
+  unsigned size =3D 0;
+  compute_path_size(path, size);
+  return size;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // FoldingSet profiling methods.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -343,6 +621,14 @@
   } =20
 }
=20
+void PathDiagnosticCallPiece::Profile(llvm::FoldingSetNodeID &ID) const {
+  PathDiagnosticPiece::Profile(ID);
+  for (PathPieces::const_iterator it =3D path.begin(),=20
+       et =3D path.end(); it !=3D et; ++it) {
+    ID.Add(**it);
+  }
+}
+
 void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
   PathDiagnosticPiece::Profile(ID);
   ID.Add(Pos);
@@ -356,18 +642,114 @@
=20
 void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
   PathDiagnosticSpotPiece::Profile(ID);
-  for (const_iterator I =3D begin(), E =3D end(); I !=3D E; ++I)
+  for (PathPieces::const_iterator I =3D subPieces.begin(), E =3D subPieces=
.end();
+       I !=3D E; ++I)
     ID.Add(**I);
 }
=20
 void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
-  ID.AddInteger(Size);
+  if (!path.empty())
+    getLocation().Profile(ID);
   ID.AddString(BugType);
   ID.AddString(Desc);
   ID.AddString(Category);
-  for (const_iterator I =3D begin(), E =3D end(); I !=3D E; ++I)
-    ID.Add(*I);
- =20
+}
+
+void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID &ID) const {
+  Profile(ID);
+  for (PathPieces::const_iterator I =3D path.begin(), E =3D path.end(); I =
!=3D E; ++I)
+    ID.Add(**I);
   for (meta_iterator I =3D meta_begin(), E =3D meta_end(); I !=3D E; ++I)
     ID.AddString(*I);
 }
+
+StackHintGenerator::~StackHintGenerator() {}
+
+std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
+  ProgramPoint P =3D N->getLocation();
+  const CallExit *CExit =3D dyn_cast<CallExit>(&P);
+  assert(CExit && "Stack Hints should be constructed at CallExit points.");
+
+  const CallExpr *CE =3D dyn_cast_or_null<CallExpr>(CExit->getStmt());
+  if (!CE)
+    return "";
+
+  // Get the successor node to make sure the return statement is evaluated=
 and
+  // CE is set to the result value.
+  N =3D *N->succ_begin();
+  if (!N)
+    return getMessageForSymbolNotFound();
+
+  // Check if one of the parameters are set to the interesting symbol.
+  ProgramStateRef State =3D N->getState();
+  const LocationContext *LCtx =3D N->getLocationContext();
+  unsigned ArgIndex =3D 0;
+  for (CallExpr::const_arg_iterator I =3D CE->arg_begin(),
+                                    E =3D CE->arg_end(); I !=3D E; ++I, ++=
ArgIndex){
+    SVal SV =3D State->getSVal(*I, LCtx);
+
+    // Check if the variable corresponding to the symbol is passed by valu=
e.
+    SymbolRef AS =3D SV.getAsLocSymbol();
+    if (AS =3D=3D Sym) {
+      return getMessageForArg(*I, ArgIndex);
+    }
+
+    // Check if the parameter is a pointer to the symbol.
+    if (const loc::MemRegionVal *Reg =3D dyn_cast<loc::MemRegionVal>(&SV))=
 {
+      SVal PSV =3D State->getSVal(Reg->getRegion());
+      SymbolRef AS =3D PSV.getAsLocSymbol();
+      if (AS =3D=3D Sym) {
+        return getMessageForArg(*I, ArgIndex);
+      }
+    }
+  }
+
+  // Check if we are returning the interesting symbol.
+  SVal SV =3D State->getSVal(CE, LCtx);
+  SymbolRef RetSym =3D SV.getAsLocSymbol();
+  if (RetSym =3D=3D Sym) {
+    return getMessageForReturn(CE);
+  }
+
+  return getMessageForSymbolNotFound();
+}
+
+/// TODO: This is copied from clang diagnostics. Maybe we could just move =
it to
+/// some common place. (Same as HandleOrdinalModifier.)
+void StackHintGeneratorForSymbol::printOrdinal(unsigned ValNo,
+                                               llvm::raw_svector_ostream &=
Out) {
+  assert(ValNo !=3D 0 && "ValNo must be strictly positive!");
+
+  // We could use text forms for the first N ordinals, but the numeric
+  // forms are actually nicer in diagnostics because they stand out.
+  Out << ValNo;
+
+  // It is critically important that we do this perfectly for
+  // user-written sequences with over 100 elements.
+  switch (ValNo % 100) {
+  case 11:
+  case 12:
+  case 13:
+    Out << "th"; return;
+  default:
+    switch (ValNo % 10) {
+    case 1: Out << "st"; return;
+    case 2: Out << "nd"; return;
+    case 3: Out << "rd"; return;
+    default: Out << "th"; return;
+    }
+  }
+}
+
+std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
+                                                        unsigned ArgIndex)=
 {
+  SmallString<200> buf;
+  llvm::raw_svector_ostream os(buf);
+
+  os << Msg << " via ";
+  // Printed parameters start at 1, not 0.
+  printOrdinal(++ArgIndex, os);
+  os << " parameter";
+
+  return os.str();
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/PlistDiagnostics.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/PlistDiagnostic=
s.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/PlistDiagnostic=
s.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -25,56 +25,23 @@
=20
 typedef llvm::DenseMap<FileID, unsigned> FIDMap;
=20
-namespace {
-struct CompareDiagnostics {
-  // Compare if 'X' is "<" than 'Y'.
-  bool operator()(const PathDiagnostic *X, const PathDiagnostic *Y) const {
-    // First compare by location
-    const FullSourceLoc &XLoc =3D X->getLocation().asLocation();
-    const FullSourceLoc &YLoc =3D Y->getLocation().asLocation();
-    if (XLoc < YLoc)
-      return true;
-    if (XLoc !=3D YLoc)
-      return false;
-   =20
-    // Next, compare by bug type.
-    StringRef XBugType =3D X->getBugType();
-    StringRef YBugType =3D Y->getBugType();
-    if (XBugType < YBugType)
-      return true;
-    if (XBugType !=3D YBugType)
-      return false;
-   =20
-    // Next, compare by bug description.
-    StringRef XDesc =3D X->getDescription();
-    StringRef YDesc =3D Y->getDescription();
-    if (XDesc < YDesc)
-      return true;
-    if (XDesc !=3D YDesc)
-      return false;
-   =20
-    // FIXME: Further refine by comparing PathDiagnosticPieces?
-    return false;   =20
-  } =20
-}; =20
-}
=20
 namespace {
   class PlistDiagnostics : public PathDiagnosticConsumer {
-    std::vector<const PathDiagnostic*> BatchedDiags;
     const std::string OutputFile;
     const LangOptions &LangOpts;
-    llvm::OwningPtr<PathDiagnosticConsumer> SubPD;
+    OwningPtr<PathDiagnosticConsumer> SubPD;
     bool flushed;
+    const bool SupportsCrossFileDiagnostics;
   public:
     PlistDiagnostics(const std::string& prefix, const LangOptions &LangOpt=
s,
+                     bool supportsMultipleFiles,
                      PathDiagnosticConsumer *subPD);
=20
-    ~PlistDiagnostics() { FlushDiagnostics(NULL); }
+    virtual ~PlistDiagnostics() {}
=20
-    void FlushDiagnostics(SmallVectorImpl<std::string> *FilesMade);
-   =20
-    void HandlePathDiagnosticImpl(const PathDiagnostic* D);
+    void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
+                              SmallVectorImpl<std::string> *FilesMade);
    =20
     virtual StringRef getName() const {
       return "PlistDiagnostics";
@@ -84,18 +51,29 @@
     bool supportsLogicalOpControlFlow() const { return true; }
     bool supportsAllBlockEdges() const { return true; }
     virtual bool useVerboseDescription() const { return false; }
+    virtual bool supportsCrossFileDiagnostics() const {
+      return SupportsCrossFileDiagnostics;
+    }
   };
 } // end anonymous namespace
=20
 PlistDiagnostics::PlistDiagnostics(const std::string& output,
                                    const LangOptions &LO,
+                                   bool supportsMultipleFiles,
                                    PathDiagnosticConsumer *subPD)
-  : OutputFile(output), LangOpts(LO), SubPD(subPD), flushed(false) {}
+  : OutputFile(output), LangOpts(LO), SubPD(subPD), flushed(false),
+    SupportsCrossFileDiagnostics(supportsMultipleFiles) {}
=20
 PathDiagnosticConsumer*
 ento::createPlistDiagnosticConsumer(const std::string& s, const Preprocess=
or &PP,
                                   PathDiagnosticConsumer *subPD) {
-  return new PlistDiagnostics(s, PP.getLangOptions(), subPD);
+  return new PlistDiagnostics(s, PP.getLangOpts(), false, subPD);
+}
+
+PathDiagnosticConsumer*
+ento::createPlistMultiFileDiagnosticConsumer(const std::string &s,
+                                              const Preprocessor &PP) {
+  return new PlistDiagnostics(s, PP.getLangOpts(), true, 0);
 }
=20
 PathDiagnosticConsumer::PathGenerationScheme
@@ -167,10 +145,9 @@
   Indent(o, indent) << "</array>\n";
 }
=20
-static raw_ostream &EmitString(raw_ostream &o,
-                                     const std::string& s) {
+static raw_ostream &EmitString(raw_ostream &o, StringRef s) {
   o << "<string>";
-  for (std::string::const_iterator I=3Ds.begin(), E=3Ds.end(); I!=3DE; ++I=
) {
+  for (StringRef::const_iterator I =3D s.begin(), E =3D s.end(); I !=3D E;=
 ++I) {
     char c =3D *I;
     switch (c) {
     default:   o << c; break;
@@ -232,7 +209,8 @@
                         const FIDMap& FM,
                         const SourceManager &SM,
                         const LangOptions &LangOpts,
-                        unsigned indent) {
+                        unsigned indent,
+                        unsigned depth) {
=20
   Indent(o, indent) << "<dict>\n";
   ++indent;
@@ -258,6 +236,10 @@
     --indent;
     Indent(o, indent) << "</array>\n";
   }
+ =20
+  // Output the call depth.
+  Indent(o, indent) << "<key>depth</key>"
+                    << "<integer>" << depth << "</integer>\n";
=20
   // Output the text.
   assert(!P.getString().empty());
@@ -269,108 +251,143 @@
   // FIXME: Really use a short string.
   Indent(o, indent) << "<key>message</key>\n";
   EmitString(o, P.getString()) << '\n';
-
+ =20
   // Finish up.
   --indent;
   Indent(o, indent); o << "</dict>\n";
 }
=20
+static void ReportPiece(raw_ostream &o,
+                        const PathDiagnosticPiece &P,
+                        const FIDMap& FM, const SourceManager &SM,
+                        const LangOptions &LangOpts,
+                        unsigned indent,
+                        unsigned depth,
+                        bool includeControlFlow);
+
+static void ReportCall(raw_ostream &o,
+                       const PathDiagnosticCallPiece &P,
+                       const FIDMap& FM, const SourceManager &SM,
+                       const LangOptions &LangOpts,
+                       unsigned indent,
+                       unsigned depth) {
+ =20
+  IntrusiveRefCntPtr<PathDiagnosticEventPiece> callEnter =3D
+    P.getCallEnterEvent(); =20
+
+  if (callEnter)
+    ReportPiece(o, *callEnter, FM, SM, LangOpts, indent, depth, true);
+
+  IntrusiveRefCntPtr<PathDiagnosticEventPiece> callEnterWithinCaller =3D
+    P.getCallEnterWithinCallerEvent();
+ =20
+  ++depth;
+ =20
+  if (callEnterWithinCaller)
+    ReportPiece(o, *callEnterWithinCaller, FM, SM, LangOpts,
+                indent, depth, true);
+ =20
+  for (PathPieces::const_iterator I =3D P.path.begin(), E =3D P.path.end()=
;I!=3DE;++I)
+    ReportPiece(o, **I, FM, SM, LangOpts, indent, depth, true);
+ =20
+  IntrusiveRefCntPtr<PathDiagnosticEventPiece> callExit =3D
+    P.getCallExitEvent();
+
+  if (callExit)
+    ReportPiece(o, *callExit, FM, SM, LangOpts, indent, depth, true);
+}
+
 static void ReportMacro(raw_ostream &o,
                         const PathDiagnosticMacroPiece& P,
                         const FIDMap& FM, const SourceManager &SM,
                         const LangOptions &LangOpts,
-                        unsigned indent) {
+                        unsigned indent,
+                        unsigned depth) {
=20
-  for (PathDiagnosticMacroPiece::const_iterator I=3DP.begin(), E=3DP.end();
+  for (PathPieces::const_iterator I =3D P.subPieces.begin(), E=3DP.subPiec=
es.end();
        I!=3DE; ++I) {
-
-    switch ((*I)->getKind()) {
-    default:
-      break;
-    case PathDiagnosticPiece::Event:
-      ReportEvent(o, cast<PathDiagnosticEventPiece>(**I), FM, SM, LangOpts,
-                  indent);
-      break;
-    case PathDiagnosticPiece::Macro:
-      ReportMacro(o, cast<PathDiagnosticMacroPiece>(**I), FM, SM, LangOpts,
-                  indent);
-      break;
-    }
+    ReportPiece(o, **I, FM, SM, LangOpts, indent, depth, false);
   }
 }
=20
 static void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P,
                        const FIDMap& FM, const SourceManager &SM,
                        const LangOptions &LangOpts) {
+  ReportPiece(o, P, FM, SM, LangOpts, 4, 0, true);
+}
=20
-  unsigned indent =3D 4;
-
+static void ReportPiece(raw_ostream &o,
+                        const PathDiagnosticPiece &P,
+                        const FIDMap& FM, const SourceManager &SM,
+                        const LangOptions &LangOpts,
+                        unsigned indent,
+                        unsigned depth,
+                        bool includeControlFlow) {
   switch (P.getKind()) {
-  case PathDiagnosticPiece::ControlFlow:
-    ReportControlFlow(o, cast<PathDiagnosticControlFlowPiece>(P), FM, SM,
-                      LangOpts, indent);
-    break;
-  case PathDiagnosticPiece::Event:
-    ReportEvent(o, cast<PathDiagnosticEventPiece>(P), FM, SM, LangOpts,
-                indent);
-    break;
-  case PathDiagnosticPiece::Macro:
-    ReportMacro(o, cast<PathDiagnosticMacroPiece>(P), FM, SM, LangOpts,
-                indent);
-    break;
+    case PathDiagnosticPiece::ControlFlow:
+      if (includeControlFlow)
+        ReportControlFlow(o, cast<PathDiagnosticControlFlowPiece>(P), FM, =
SM,
+                          LangOpts, indent);
+      break;
+    case PathDiagnosticPiece::Call:
+      ReportCall(o, cast<PathDiagnosticCallPiece>(P), FM, SM, LangOpts,
+                 indent, depth);
+      break;
+    case PathDiagnosticPiece::Event:
+      ReportEvent(o, cast<PathDiagnosticSpotPiece>(P), FM, SM, LangOpts,
+                  indent, depth);
+      break;
+    case PathDiagnosticPiece::Macro:
+      ReportMacro(o, cast<PathDiagnosticMacroPiece>(P), FM, SM, LangOpts,
+                  indent, depth);
+      break;
   }
 }
=20
-void PlistDiagnostics::HandlePathDiagnosticImpl(const PathDiagnostic* D) {
-  if (!D)
-    return;
-
-  if (D->empty()) {
-    delete D;
-    return;
-  }
-
-  // We need to flatten the locations (convert Stmt* to locations) because
-  // the referenced statements may be freed by the time the diagnostics
-  // are emitted.
-  const_cast<PathDiagnostic*>(D)->flattenLocations();
-  BatchedDiags.push_back(D);
-}
-
-void PlistDiagnostics::FlushDiagnostics(SmallVectorImpl<std::string>
-                                        *FilesMade) {
- =20
-  if (flushed)
-    return;
- =20
-  flushed =3D true;
- =20
-  // Sort the diagnostics so that they are always emitted in a determinist=
ic
-  // order.
-  if (!BatchedDiags.empty())
-    std::sort(BatchedDiags.begin(), BatchedDiags.end(), CompareDiagnostics=
());=20
-
+void PlistDiagnostics::FlushDiagnosticsImpl(
+                                    std::vector<const PathDiagnostic *> &D=
iags,
+                                    SmallVectorImpl<std::string> *FilesMad=
e) {
   // Build up a set of FIDs that we use by scanning the locations and
   // ranges of the diagnostics.
   FIDMap FM;
   SmallVector<FileID, 10> Fids;
   const SourceManager* SM =3D 0;
=20
-  if (!BatchedDiags.empty())
-    SM =3D &(*BatchedDiags.begin())->begin()->getLocation().getManager();
+  if (!Diags.empty())
+    SM =3D &(*(*Diags.begin())->path.begin())->getLocation().getManager();
=20
-  for (std::vector<const PathDiagnostic*>::iterator DI =3D BatchedDiags.be=
gin(),
-       DE =3D BatchedDiags.end(); DI !=3D DE; ++DI) {
+ =20
+  for (std::vector<const PathDiagnostic*>::iterator DI =3D Diags.begin(),
+       DE =3D Diags.end(); DI !=3D DE; ++DI) {
=20
     const PathDiagnostic *D =3D *DI;
=20
-    for (PathDiagnostic::const_iterator I=3DD->begin(), E=3DD->end(); I!=
=3DE; ++I) {
-      AddFID(FM, Fids, SM, I->getLocation().asLocation());
+    llvm::SmallVector<const PathPieces *, 5> WorkList;
+    WorkList.push_back(&D->path);
=20
-      for (PathDiagnosticPiece::range_iterator RI=3DI->ranges_begin(),
-           RE=3DI->ranges_end(); RI!=3DRE; ++RI) {
-        AddFID(FM, Fids, SM, RI->getBegin());
-        AddFID(FM, Fids, SM, RI->getEnd());
+    while (!WorkList.empty()) {
+      const PathPieces &path =3D *WorkList.back();
+      WorkList.pop_back();
+   =20
+      for (PathPieces::const_iterator I =3D path.begin(), E =3D path.end();
+           I!=3DE; ++I) {
+        const PathDiagnosticPiece *piece =3D I->getPtr();
+        AddFID(FM, Fids, SM, piece->getLocation().asLocation());
+
+        for (PathDiagnosticPiece::range_iterator RI =3D piece->ranges_begi=
n(),
+             RE=3D piece->ranges_end(); RI !=3D RE; ++RI) {
+          AddFID(FM, Fids, SM, RI->getBegin());
+          AddFID(FM, Fids, SM, RI->getEnd());
+        }
+
+        if (const PathDiagnosticCallPiece *call =3D
+            dyn_cast<PathDiagnosticCallPiece>(piece)) {
+          WorkList.push_back(&call->path);
+        }
+        else if (const PathDiagnosticMacroPiece *macro =3D
+                 dyn_cast<PathDiagnosticMacroPiece>(piece)) {
+          WorkList.push_back(&macro->subPieces);
+        }
       }
     }
   }
@@ -379,7 +396,7 @@
   std::string ErrMsg;
   llvm::raw_fd_ostream o(OutputFile.c_str(), ErrMsg);
   if (!ErrMsg.empty()) {
-    llvm::errs() << "warning: could not creat file: " << OutputFile << '\n=
';
+    llvm::errs() << "warning: could not create file: " << OutputFile << '\=
n';
     return;
   }
=20
@@ -406,21 +423,19 @@
        " <key>diagnostics</key>\n"
        " <array>\n";
=20
-  for (std::vector<const PathDiagnostic*>::iterator DI=3DBatchedDiags.begi=
n(),
-       DE =3D BatchedDiags.end(); DI!=3DDE; ++DI) {
+  for (std::vector<const PathDiagnostic*>::iterator DI=3DDiags.begin(),
+       DE =3D Diags.end(); DI!=3DDE; ++DI) {
=20
     o << "  <dict>\n"
          "   <key>path</key>\n";
=20
     const PathDiagnostic *D =3D *DI;
-    // Create an owning smart pointer for 'D' just so that we auto-free it
-    // when we exit this method.
-    llvm::OwningPtr<PathDiagnostic> OwnedD(const_cast<PathDiagnostic*>(D));
=20
     o << "   <array>\n";
=20
-    for (PathDiagnostic::const_iterator I=3DD->begin(), E=3DD->end(); I !=
=3D E; ++I)
-      ReportDiag(o, *I, FM, *SM, LangOpts);
+    for (PathPieces::const_iterator I =3D D->path.begin(), E =3D D->path.e=
nd();=20
+         I !=3D E; ++I)
+      ReportDiag(o, **I, FM, *SM, LangOpts);
=20
     o << "   </array>\n";
=20
@@ -431,6 +446,38 @@
     EmitString(o, D->getCategory()) << '\n';
     o << "   <key>type</key>";
     EmitString(o, D->getBugType()) << '\n';
+   =20
+    // Output information about the semantic context where
+    // the issue occurred.
+    if (const Decl *DeclWithIssue =3D D->getDeclWithIssue()) {
+      // FIXME: handle blocks, which have no name.
+      if (const NamedDecl *ND =3D dyn_cast<NamedDecl>(DeclWithIssue)) {
+        StringRef declKind;
+        switch (ND->getKind()) {
+          case Decl::CXXRecord:
+            declKind =3D "C++ class";
+            break;
+          case Decl::CXXMethod:
+            declKind =3D "C++ method";
+            break;
+          case Decl::ObjCMethod:
+            declKind =3D "Objective-C method";
+            break;
+          case Decl::Function:
+            declKind =3D "function";
+            break;
+          default:
+            break;
+        }
+        if (!declKind.empty()) {
+          const std::string &declName =3D ND->getDeclName().getAsString();
+          o << "  <key>issue_context_kind</key>";
+          EmitString(o, declKind) << '\n';
+          o << "  <key>issue_context</key>";
+          EmitString(o, declName) << '\n';
+        }
+      }
+    }
=20
     // Output the location of the bug.
     o << "  <key>location</key>\n";
@@ -438,9 +485,10 @@
=20
     // Output the diagnostic to the sub-diagnostic client, if any.
     if (SubPD) {
-      SubPD->HandlePathDiagnostic(OwnedD.take());
+      std::vector<const PathDiagnostic *> SubDiags;
+      SubDiags.push_back(D);
       SmallVector<std::string, 1> SubFilesMade;
-      SubPD->FlushDiagnostics(SubFilesMade);
+      SubPD->FlushDiagnosticsImpl(SubDiags, &SubFilesMade);
=20
       if (!SubFilesMade.empty()) {
         o << "  <key>" << SubPD->getName() << "_files</key>\n";
@@ -462,6 +510,4 @@
  =20
   if (FilesMade)
     FilesMade->push_back(OutputFile);
- =20
-  BatchedDiags.clear();
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/ProgramState.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ProgramState.cp=
p	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/ProgramState.cp=
p	Tue Apr 17 11:51:51 2012 +0300
@@ -15,6 +15,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/TaintManager.h"
 #include "llvm/Support/raw_ostream.h"
=20
 using namespace clang;
@@ -24,6 +25,26 @@
 // FIXME: Move this elsewhere.
 ConstraintManager::~ConstraintManager() {}
=20
+namespace clang { namespace  ento {
+/// Increments the number of times this state is referenced.
+
+void ProgramStateRetain(const ProgramState *state) {
+  ++const_cast<ProgramState*>(state)->refCount;
+}
+
+/// Decrement the number of times this state is referenced.
+void ProgramStateRelease(const ProgramState *state) {
+  assert(state->refCount > 0);
+  ProgramState *s =3D const_cast<ProgramState*>(state);
+  if (--s->refCount =3D=3D 0) {
+    ProgramStateManager &Mgr =3D s->getStateManager();
+    Mgr.StateSet.RemoveNode(s);
+    s->~ProgramState();   =20
+    Mgr.freeStates.push_back(s);
+  }
+}
+}}
+
 ProgramState::ProgramState(ProgramStateManager *mgr, const Environment& en=
v,
                  StoreRef st, GenericDataMap gdm)
   : stateMgr(mgr),
@@ -55,8 +76,8 @@
     I->second.second(I->second.first);
 }
=20
-const ProgramState*
-ProgramStateManager::removeDeadBindings(const ProgramState *state,
+ProgramStateRef=20
+ProgramStateManager::removeDeadBindings(ProgramStateRef state,
                                    const StackFrameContext *LCtx,
                                    SymbolReaper& SymReaper) {
=20
@@ -79,7 +100,7 @@
   return getPersistentState(NewState);
 }
=20
-const ProgramState *ProgramStateManager::MarshalState(const ProgramState *=
state,
+ProgramStateRef ProgramStateManager::MarshalState(ProgramStateRef state,
                                             const StackFrameContext *InitL=
oc) {
   // make up an empty state for now.
   ProgramState State(this,
@@ -90,7 +111,7 @@
   return getPersistentState(State);
 }
=20
-const ProgramState *ProgramState::bindCompoundLiteral(const CompoundLitera=
lExpr *CL,
+ProgramStateRef ProgramState::bindCompoundLiteral(const CompoundLiteralExp=
r *CL,
                                             const LocationContext *LC,
                                             SVal V) const {
   const StoreRef &newStore =3D=20
@@ -98,21 +119,21 @@
   return makeWithStore(newStore);
 }
=20
-const ProgramState *ProgramState::bindDecl(const VarRegion* VR, SVal IVal)=
 const {
+ProgramStateRef ProgramState::bindDecl(const VarRegion* VR, SVal IVal) con=
st {
   const StoreRef &newStore =3D
     getStateManager().StoreMgr->BindDecl(getStore(), VR, IVal);
   return makeWithStore(newStore);
 }
=20
-const ProgramState *ProgramState::bindDeclWithNoInit(const VarRegion* VR) =
const {
+ProgramStateRef ProgramState::bindDeclWithNoInit(const VarRegion* VR) cons=
t {
   const StoreRef &newStore =3D
     getStateManager().StoreMgr->BindDeclWithNoInit(getStore(), VR);
   return makeWithStore(newStore);
 }
=20
-const ProgramState *ProgramState::bindLoc(Loc LV, SVal V) const {
+ProgramStateRef ProgramState::bindLoc(Loc LV, SVal V) const {
   ProgramStateManager &Mgr =3D getStateManager();
-  const ProgramState *newState =3D makeWithStore(Mgr.StoreMgr->Bind(getSto=
re(),=20
+  ProgramStateRef newState =3D makeWithStore(Mgr.StoreMgr->Bind(getStore()=
,=20
                                                              LV, V));
   const MemRegion *MR =3D LV.getAsRegion();
   if (MR && Mgr.getOwningEngine())
@@ -121,53 +142,55 @@
   return newState;
 }
=20
-const ProgramState *ProgramState::bindDefault(SVal loc, SVal V) const {
+ProgramStateRef ProgramState::bindDefault(SVal loc, SVal V) const {
   ProgramStateManager &Mgr =3D getStateManager();
   const MemRegion *R =3D cast<loc::MemRegionVal>(loc).getRegion();
   const StoreRef &newStore =3D Mgr.StoreMgr->BindDefault(getStore(), R, V);
-  const ProgramState *new_state =3D makeWithStore(newStore);
+  ProgramStateRef new_state =3D makeWithStore(newStore);
   return Mgr.getOwningEngine() ?=20
            Mgr.getOwningEngine()->processRegionChange(new_state, R) :=20
            new_state;
 }
=20
-const ProgramState *
+ProgramStateRef=20
 ProgramState::invalidateRegions(ArrayRef<const MemRegion *> Regions,
                                 const Expr *E, unsigned Count,
+                                const LocationContext *LCtx,
                                 StoreManager::InvalidatedSymbols *IS,
-                                bool invalidateGlobals) const {
+                                const CallOrObjCMessage *Call) const {
   if (!IS) {
     StoreManager::InvalidatedSymbols invalidated;
-    return invalidateRegionsImpl(Regions, E, Count,
-                                 invalidated, invalidateGlobals);
+    return invalidateRegionsImpl(Regions, E, Count, LCtx,
+                                 invalidated, Call);
   }
-  return invalidateRegionsImpl(Regions, E, Count, *IS, invalidateGlobals);
+  return invalidateRegionsImpl(Regions, E, Count, LCtx, *IS, Call);
 }
=20
-const ProgramState *
+ProgramStateRef=20
 ProgramState::invalidateRegionsImpl(ArrayRef<const MemRegion *> Regions,
                                     const Expr *E, unsigned Count,
+                                    const LocationContext *LCtx,
                                     StoreManager::InvalidatedSymbols &IS,
-                                    bool invalidateGlobals) const {
+                                    const CallOrObjCMessage *Call) const {
   ProgramStateManager &Mgr =3D getStateManager();
   SubEngine* Eng =3D Mgr.getOwningEngine();
 =20
   if (Eng && Eng->wantsRegionChangeUpdate(this)) {
     StoreManager::InvalidatedRegions Invalidated;
     const StoreRef &newStore
-      =3D Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, I=
S,
-                                        invalidateGlobals, &Invalidated);
-    const ProgramState *newState =3D makeWithStore(newStore);
-    return Eng->processRegionChanges(newState, &IS, Regions, Invalidated);
+      =3D Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, L=
Ctx, IS,
+                                        Call, &Invalidated);
+    ProgramStateRef newState =3D makeWithStore(newStore);
+    return Eng->processRegionChanges(newState, &IS, Regions, Invalidated, =
Call);
   }
=20
   const StoreRef &newStore =3D
-    Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, IS,
-                                    invalidateGlobals, NULL);
+    Mgr.StoreMgr->invalidateRegions(getStore(), Regions, E, Count, LCtx, I=
S,
+                                    Call, NULL);
   return makeWithStore(newStore);
 }
=20
-const ProgramState *ProgramState::unbindLoc(Loc LV) const {
+ProgramStateRef ProgramState::unbindLoc(Loc LV) const {
   assert(!isa<loc::MemRegionVal>(LV) && "Use invalidateRegion instead.");
=20
   Store OldStore =3D getStore();
@@ -179,9 +202,11 @@
   return makeWithStore(newStore);
 }
=20
-const ProgramState *ProgramState::enterStackFrame(const StackFrameContext =
*frame) const {
+ProgramStateRef=20
+ProgramState::enterStackFrame(const LocationContext *callerCtx,
+                              const StackFrameContext *calleeCtx) const {
   const StoreRef &new_store =3D
-    getStateManager().StoreMgr->enterStackFrame(this, frame);
+    getStateManager().StoreMgr->enterStackFrame(this, callerCtx, calleeCtx=
);
   return makeWithStore(new_store);
 }
=20
@@ -238,9 +263,12 @@
   return V;
 }
=20
-const ProgramState *ProgramState::BindExpr(const Stmt *S, SVal V, bool Inv=
alidate) const{
-  Environment NewEnv =3D getStateManager().EnvMgr.bindExpr(Env, S, V,
-                                                         Invalidate);
+ProgramStateRef ProgramState::BindExpr(const Stmt *S,
+                                           const LocationContext *LCtx,
+                                           SVal V, bool Invalidate) const{
+  Environment NewEnv =3D
+    getStateManager().EnvMgr.bindExpr(Env, EnvironmentEntry(S, LCtx), V,
+                                      Invalidate);
   if (NewEnv =3D=3D Env)
     return this;
=20
@@ -249,10 +277,14 @@
   return getStateManager().getPersistentState(NewSt);
 }
=20
-const ProgramState *ProgramState::bindExprAndLocation(const Stmt *S, SVal =
location,
-                                            SVal V) const {
+ProgramStateRef=20
+ProgramState::bindExprAndLocation(const Stmt *S, const LocationContext *LC=
tx,
+                                  SVal location,
+                                  SVal V) const {
   Environment NewEnv =3D
-    getStateManager().EnvMgr.bindExprAndLocation(Env, S, location, V);
+    getStateManager().EnvMgr.bindExprAndLocation(Env,
+                                                 EnvironmentEntry(S, LCtx),
+                                                 location, V);
=20
   if (NewEnv =3D=3D Env)
     return this;
@@ -262,9 +294,10 @@
   return getStateManager().getPersistentState(NewSt);
 }
=20
-const ProgramState *ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
+ProgramStateRef ProgramState::assumeInBound(DefinedOrUnknownSVal Idx,
                                       DefinedOrUnknownSVal UpperBound,
-                                      bool Assumption) const {
+                                      bool Assumption,
+                                      QualType indexTy) const {
   if (Idx.isUnknown() || UpperBound.isUnknown())
     return this;
=20
@@ -278,7 +311,8 @@
   // Get the offset: the minimum value of the array index type.
   BasicValueFactory &BVF =3D svalBuilder.getBasicValueFactory();
   // FIXME: This should be using ValueManager::ArrayindexTy...somehow.
-  QualType indexTy =3D Ctx.IntTy;
+  if (indexTy.isNull())
+    indexTy =3D Ctx.IntTy;
   nonloc::ConcreteInt Min(BVF.getMinValue(indexTy));
=20
   // Adjust the index.
@@ -307,7 +341,7 @@
   return CM.assume(this, cast<DefinedSVal>(inBound), Assumption);
 }
=20
-const ProgramState *ProgramStateManager::getInitialState(const LocationCon=
text *InitLoc) {
+ProgramStateRef ProgramStateManager::getInitialState(const LocationContext=
 *InitLoc) {
   ProgramState State(this,
                 EnvMgr.getInitialEnvironment(),
                 StoreMgr->getInitialStore(InitLoc),
@@ -316,28 +350,15 @@
   return getPersistentState(State);
 }
=20
-void ProgramStateManager::recycleUnusedStates() {
-  for (std::vector<ProgramState*>::iterator i =3D recentlyAllocatedStates.=
begin(),
-       e =3D recentlyAllocatedStates.end(); i !=3D e; ++i) {
-    ProgramState *state =3D *i;
-    if (state->referencedByExplodedNode())
-      continue;
-    StateSet.RemoveNode(state);
-    freeStates.push_back(state);
-    state->~ProgramState();
-  }
-  recentlyAllocatedStates.clear();
-}
-
-const ProgramState *ProgramStateManager::getPersistentStateWithGDM(
-                                                     const ProgramState *F=
romState,
-                                                     const ProgramState *G=
DMState) {
-  ProgramState NewState =3D *FromState;
+ProgramStateRef ProgramStateManager::getPersistentStateWithGDM(
+                                                     ProgramStateRef FromS=
tate,
+                                                     ProgramStateRef GDMSt=
ate) {
+  ProgramState NewState(*FromState);
   NewState.GDM =3D GDMState->GDM;
   return getPersistentState(NewState);
 }
=20
-const ProgramState *ProgramStateManager::getPersistentState(ProgramState &=
State) {
+ProgramStateRef ProgramStateManager::getPersistentState(ProgramState &Stat=
e) {
=20
   llvm::FoldingSetNodeID ID;
   State.Profile(ID);
@@ -356,12 +377,11 @@
   }
   new (newState) ProgramState(State);
   StateSet.InsertNode(newState, InsertPos);
-  recentlyAllocatedStates.push_back(newState);
   return newState;
 }
=20
-const ProgramState *ProgramState::makeWithStore(const StoreRef &store) con=
st {
-  ProgramState NewSt =3D *this;
+ProgramStateRef ProgramState::makeWithStore(const StoreRef &store) const {
+  ProgramState NewSt(*this);
   NewSt.setStore(store);
   return getStateManager().getPersistentState(NewSt);
 }
@@ -379,92 +399,44 @@
 //  State pretty-printing.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-static bool IsEnvLoc(const Stmt *S) {
-  // FIXME: This is a layering violation.  Should be in environment.
-  return (bool) (((uintptr_t) S) & 0x1);
-}
-
-void ProgramState::print(raw_ostream &Out, CFG &C,
+void ProgramState::print(raw_ostream &Out,
                          const char *NL, const char *Sep) const {
   // Print the store.
   ProgramStateManager &Mgr =3D getStateManager();
   Mgr.getStoreManager().print(getStore(), Out, NL, Sep);
=20
-  // Print Subexpression bindings.
-  bool isFirst =3D true;
+  // Print out the environment.
+  Env.print(Out, NL, Sep);
=20
-  // FIXME: All environment printing should be moved inside Environment.
-  for (Environment::iterator I =3D Env.begin(), E =3D Env.end(); I !=3D E;=
 ++I) {
-    if (C.isBlkExpr(I.getKey()) || IsEnvLoc(I.getKey()))
-      continue;
-
-    if (isFirst) {
-      Out << NL << NL << "Sub-Expressions:" << NL;
-      isFirst =3D false;
-    } else {
-      Out << NL;
-    }
-
-    Out << " (" << (void*) I.getKey() << ") ";
-    LangOptions LO; // FIXME.
-    I.getKey()->printPretty(Out, 0, PrintingPolicy(LO));
-    Out << " : " << I.getData();
-  }
-
-  // Print block-expression bindings.
-  isFirst =3D true;
-
-  for (Environment::iterator I =3D Env.begin(), E =3D Env.end(); I !=3D E;=
 ++I) {
-    if (!C.isBlkExpr(I.getKey()))
-      continue;
-
-    if (isFirst) {
-      Out << NL << NL << "Block-level Expressions:" << NL;
-      isFirst =3D false;
-    } else {
-      Out << NL;
-    }
-
-    Out << " (" << (void*) I.getKey() << ") ";
-    LangOptions LO; // FIXME.
-    I.getKey()->printPretty(Out, 0, PrintingPolicy(LO));
-    Out << " : " << I.getData();
-  }
- =20
-  // Print locations.
-  isFirst =3D true;
- =20
-  for (Environment::iterator I =3D Env.begin(), E =3D Env.end(); I !=3D E;=
 ++I) {
-    if (!IsEnvLoc(I.getKey()))
-      continue;
-   =20
-    if (isFirst) {
-      Out << NL << NL << "Load/store locations:" << NL;
-      isFirst =3D false;
-    } else {
-      Out << NL;
-    }
-
-    const Stmt *S =3D (Stmt*) (((uintptr_t) I.getKey()) & ((uintptr_t) ~0x=
1));
-   =20
-    Out << " (" << (void*) S << ") ";
-    LangOptions LO; // FIXME.
-    S->printPretty(Out, 0, PrintingPolicy(LO));
-    Out << " : " << I.getData();
-  }
-
+  // Print out the constraints.
   Mgr.getConstraintManager().print(this, Out, NL, Sep);
=20
   // Print checker-specific data.
   Mgr.getOwningEngine()->printState(Out, this, NL, Sep);
 }
=20
-void ProgramState::printDOT(raw_ostream &Out, CFG &C) const {
-  print(Out, C, "\\l", "\\|");
+void ProgramState::printDOT(raw_ostream &Out) const {
+  print(Out, "\\l", "\\|");
 }
=20
-void ProgramState::printStdErr(CFG &C) const {
-  print(llvm::errs(), C);
+void ProgramState::dump() const {
+  print(llvm::errs());
+}
+
+void ProgramState::printTaint(raw_ostream &Out,
+                              const char *NL, const char *Sep) const {
+  TaintMapImpl TM =3D get<TaintMap>();
+
+  if (!TM.isEmpty())
+    Out <<"Tainted Symbols:" << NL;
+
+  for (TaintMapImpl::iterator I =3D TM.begin(), E =3D TM.end(); I !=3D E; =
++I) {
+    Out << I->first << " : " << I->second << NL;
+  }
+}
+
+void ProgramState::dumpTaint() const {
+  printTaint(llvm::errs());
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -489,7 +461,7 @@
   return p.first;
 }
=20
-const ProgramState *ProgramStateManager::addGDM(const ProgramState *St, vo=
id *Key, void *Data){
+ProgramStateRef ProgramStateManager::addGDM(ProgramStateRef St, void *Key,=
 void *Data){
   ProgramState::GenericDataMap M1 =3D St->getGDM();
   ProgramState::GenericDataMap M2 =3D GDMFactory.add(M1, Key, Data);
=20
@@ -501,7 +473,7 @@
   return getPersistentState(NewSt);
 }
=20
-const ProgramState *ProgramStateManager::removeGDM(const ProgramState *sta=
te, void *Key) {
+ProgramStateRef ProgramStateManager::removeGDM(ProgramStateRef state, void=
 *Key) {
   ProgramState::GenericDataMap OldM =3D state->getGDM();
   ProgramState::GenericDataMap NewM =3D GDMFactory.remove(OldM, Key);
=20
@@ -513,6 +485,8 @@
   return getPersistentState(NewState);
 }
=20
+void ScanReachableSymbols::anchor() { }
+
 bool ScanReachableSymbols::scan(nonloc::CompoundVal val) {
   for (nonloc::CompoundVal::iterator I=3Dval.begin(), E=3Dval.end(); I!=3D=
E; ++I)
     if (!scan(*I))
@@ -527,10 +501,10 @@
     return true;
   isVisited =3D 1;
  =20
-  if (const SymbolData *sData =3D dyn_cast<SymbolData>(sym))
-    if (!visitor.VisitSymbol(sData))
-      return false;
+  if (!visitor.VisitSymbol(sym))
+    return false;
  =20
+  // TODO: should be rewritten using SymExpr::symbol_iterator.
   switch (sym->getKind()) {
     case SymExpr::RegionValueKind:
     case SymExpr::ConjuredKind:
@@ -538,8 +512,12 @@
     case SymExpr::ExtentKind:
     case SymExpr::MetadataKind:
       break;
+    case SymExpr::CastSymbolKind:
+      return scan(cast<SymbolCast>(sym)->getOperand());
     case SymExpr::SymIntKind:
       return scan(cast<SymIntExpr>(sym)->getLHS());
+    case SymExpr::IntSymKind:
+      return scan(cast<IntSymExpr>(sym)->getRHS());
     case SymExpr::SymSymKind: {
       const SymSymExpr *x =3D cast<SymSymExpr>(sym);
       return scan(x->getLHS()) && scan(x->getRHS());
@@ -575,6 +553,10 @@
   if (isVisited)
     return true;
   isVisited =3D 1;
+ =20
+ =20
+  if (!visitor.VisitMemRegion(R))
+    return false;
=20
   // If this is a symbolic region, visit the symbol for the region.
   if (const SymbolicRegion *SR =3D dyn_cast<SymbolicRegion>(R))
@@ -623,3 +605,105 @@
   }
   return true;
 }
+
+ProgramStateRef ProgramState::addTaint(const Stmt *S,
+                                           const LocationContext *LCtx,
+                                           TaintTagType Kind) const {
+  if (const Expr *E =3D dyn_cast_or_null<Expr>(S))
+    S =3D E->IgnoreParens();
+
+  SymbolRef Sym =3D getSVal(S, LCtx).getAsSymbol();
+  if (Sym)
+    return addTaint(Sym, Kind);
+
+  const MemRegion *R =3D getSVal(S, LCtx).getAsRegion();
+  addTaint(R, Kind);
+
+  // Cannot add taint, so just return the state.
+  return this;
+}
+
+ProgramStateRef ProgramState::addTaint(const MemRegion *R,
+                                           TaintTagType Kind) const {
+  if (const SymbolicRegion *SR =3D dyn_cast_or_null<SymbolicRegion>(R))
+    return addTaint(SR->getSymbol(), Kind);
+  return this;
+}
+
+ProgramStateRef ProgramState::addTaint(SymbolRef Sym,
+                                           TaintTagType Kind) const {
+  // If this is a symbol cast, remove the cast before adding the taint. Ta=
int
+  // is cast agnostic.
+  while (const SymbolCast *SC =3D dyn_cast<SymbolCast>(Sym))
+    Sym =3D SC->getOperand();
+
+  ProgramStateRef NewState =3D set<TaintMap>(Sym, Kind);
+  assert(NewState);
+  return NewState;
+}
+
+bool ProgramState::isTainted(const Stmt *S, const LocationContext *LCtx,
+                             TaintTagType Kind) const {
+  if (const Expr *E =3D dyn_cast_or_null<Expr>(S))
+    S =3D E->IgnoreParens();
+
+  SVal val =3D getSVal(S, LCtx);
+  return isTainted(val, Kind);
+}
+
+bool ProgramState::isTainted(SVal V, TaintTagType Kind) const {
+  if (const SymExpr *Sym =3D V.getAsSymExpr())
+    return isTainted(Sym, Kind);
+  if (const MemRegion *Reg =3D V.getAsRegion())
+    return isTainted(Reg, Kind);
+  return false;
+}
+
+bool ProgramState::isTainted(const MemRegion *Reg, TaintTagType K) const {
+  if (!Reg)
+    return false;
+
+  // Element region (array element) is tainted if either the base or the o=
ffset
+  // are tainted.
+  if (const ElementRegion *ER =3D dyn_cast<ElementRegion>(Reg))
+    return isTainted(ER->getSuperRegion(), K) || isTainted(ER->getIndex(),=
 K);
+
+  if (const SymbolicRegion *SR =3D dyn_cast<SymbolicRegion>(Reg))
+    return isTainted(SR->getSymbol(), K);
+
+  if (const SubRegion *ER =3D dyn_cast<SubRegion>(Reg))
+    return isTainted(ER->getSuperRegion(), K);
+
+  return false;
+}
+
+bool ProgramState::isTainted(SymbolRef Sym, TaintTagType Kind) const {
+  if (!Sym)
+    return false;
+ =20
+  // Traverse all the symbols this symbol depends on to see if any are tai=
nted.
+  bool Tainted =3D false;
+  for (SymExpr::symbol_iterator SI =3D Sym->symbol_begin(), SE =3DSym->sym=
bol_end();
+       SI !=3D SE; ++SI) {
+    assert(isa<SymbolData>(*SI));
+    const TaintTagType *Tag =3D get<TaintMap>(*SI);
+    Tainted =3D (Tag && *Tag =3D=3D Kind);
+
+    // If this is a SymbolDerived with a tainted parent, it's also tainted.
+    if (const SymbolDerived *SD =3D dyn_cast<SymbolDerived>(*SI))
+      Tainted =3D Tainted || isTainted(SD->getParentSymbol(), Kind);
+
+    // If memory region is tainted, data is also tainted.
+    if (const SymbolRegionValue *SRV =3D dyn_cast<SymbolRegionValue>(*SI))
+      Tainted =3D Tainted || isTainted(SRV->getRegion(), Kind);
+
+    // If If this is a SymbolCast from a tainted value, it's also tainted.
+    if (const SymbolCast *SC =3D dyn_cast<SymbolCast>(*SI))
+      Tainted =3D Tainted || isTainted(SC->getOperand(), Kind);
+
+    if (Tainted)
+      return true;
+  }
+ =20
+  return Tainted;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/RangeConstraintManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/RangeConstraint=
Manager.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/RangeConstraint=
Manager.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -204,46 +204,46 @@
=20
 namespace {
 class RangeConstraintManager : public SimpleConstraintManager{
-  RangeSet GetRange(const ProgramState *state, SymbolRef sym);
+  RangeSet GetRange(ProgramStateRef state, SymbolRef sym);
 public:
   RangeConstraintManager(SubEngine &subengine)
     : SimpleConstraintManager(subengine) {}
=20
-  const ProgramState *assumeSymNE(const ProgramState *state, SymbolRef sym,
+  ProgramStateRef assumeSymNE(ProgramStateRef state, SymbolRef sym,
                              const llvm::APSInt& Int,
                              const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymEQ(const ProgramState *state, SymbolRef sym,
+  ProgramStateRef assumeSymEQ(ProgramStateRef state, SymbolRef sym,
                              const llvm::APSInt& Int,
                              const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymLT(const ProgramState *state, SymbolRef sym,
+  ProgramStateRef assumeSymLT(ProgramStateRef state, SymbolRef sym,
                              const llvm::APSInt& Int,
                              const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymGT(const ProgramState *state, SymbolRef sym,
+  ProgramStateRef assumeSymGT(ProgramStateRef state, SymbolRef sym,
                              const llvm::APSInt& Int,
                              const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymGE(const ProgramState *state, SymbolRef sym,
+  ProgramStateRef assumeSymGE(ProgramStateRef state, SymbolRef sym,
                              const llvm::APSInt& Int,
                              const llvm::APSInt& Adjustment);
=20
-  const ProgramState *assumeSymLE(const ProgramState *state, SymbolRef sym,
+  ProgramStateRef assumeSymLE(ProgramStateRef state, SymbolRef sym,
                              const llvm::APSInt& Int,
                              const llvm::APSInt& Adjustment);
=20
-  const llvm::APSInt* getSymVal(const ProgramState *St, SymbolRef sym) con=
st;
+  const llvm::APSInt* getSymVal(ProgramStateRef St, SymbolRef sym) const;
=20
   // FIXME: Refactor into SimpleConstraintManager?
-  bool isEqual(const ProgramState *St, SymbolRef sym, const llvm::APSInt& =
V) const {
+  bool isEqual(ProgramStateRef St, SymbolRef sym, const llvm::APSInt& V) c=
onst {
     const llvm::APSInt *i =3D getSymVal(St, sym);
     return i ? *i =3D=3D V : false;
   }
=20
-  const ProgramState *removeDeadBindings(const ProgramState *St, SymbolRea=
per& SymReaper);
+  ProgramStateRef removeDeadBindings(ProgramStateRef St, SymbolReaper& Sym=
Reaper);
=20
-  void print(const ProgramState *St, raw_ostream &Out,
+  void print(ProgramStateRef St, raw_ostream &Out,
              const char* nl, const char *sep);
=20
 private:
@@ -257,7 +257,7 @@
   return new RangeConstraintManager(subeng);
 }
=20
-const llvm::APSInt* RangeConstraintManager::getSymVal(const ProgramState *=
St,
+const llvm::APSInt* RangeConstraintManager::getSymVal(ProgramStateRef St,
                                                       SymbolRef sym) const=
 {
   const ConstraintRangeTy::data_type *T =3D St->get<ConstraintRange>(sym);
   return T ? T->getConcreteValue() : NULL;
@@ -265,8 +265,8 @@
=20
 /// Scan all symbols referenced by the constraints. If the symbol is not a=
live
 /// as marked in LSymbols, mark it as dead in DSymbols.
-const ProgramState*
-RangeConstraintManager::removeDeadBindings(const ProgramState *state,
+ProgramStateRef=20
+RangeConstraintManager::removeDeadBindings(ProgramStateRef state,
                                            SymbolReaper& SymReaper) {
=20
   ConstraintRangeTy CR =3D state->get<ConstraintRange>();
@@ -282,7 +282,7 @@
 }
=20
 RangeSet
-RangeConstraintManager::GetRange(const ProgramState *state, SymbolRef sym)=
 {
+RangeConstraintManager::GetRange(ProgramStateRef state, SymbolRef sym) {
   if (ConstraintRangeTy::data_type* V =3D state->get<ConstraintRange>(sym))
     return *V;
=20
@@ -305,8 +305,8 @@
 // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX=
-1,
 // UINT_MAX, 0, 1, and 2.
=20
-const ProgramState*
-RangeConstraintManager::assumeSymNE(const ProgramState *state, SymbolRef s=
ym,
+ProgramStateRef=20
+RangeConstraintManager::assumeSymNE(ProgramStateRef state, SymbolRef sym,
                                     const llvm::APSInt& Int,
                                     const llvm::APSInt& Adjustment) {
   BasicValueFactory &BV =3D state->getBasicVals();
@@ -322,8 +322,8 @@
   return New.isEmpty() ? NULL : state->set<ConstraintRange>(sym, New);
 }
=20
-const ProgramState*
-RangeConstraintManager::assumeSymEQ(const ProgramState *state, SymbolRef s=
ym,
+ProgramStateRef=20
+RangeConstraintManager::assumeSymEQ(ProgramStateRef state, SymbolRef sym,
                                     const llvm::APSInt& Int,
                                     const llvm::APSInt& Adjustment) {
   // [Int-Adjustment, Int-Adjustment]
@@ -333,8 +333,8 @@
   return New.isEmpty() ? NULL : state->set<ConstraintRange>(sym, New);
 }
=20
-const ProgramState*
-RangeConstraintManager::assumeSymLT(const ProgramState *state, SymbolRef s=
ym,
+ProgramStateRef=20
+RangeConstraintManager::assumeSymLT(ProgramStateRef state, SymbolRef sym,
                                     const llvm::APSInt& Int,
                                     const llvm::APSInt& Adjustment) {
   BasicValueFactory &BV =3D state->getBasicVals();
@@ -354,8 +354,8 @@
   return New.isEmpty() ? NULL : state->set<ConstraintRange>(sym, New);
 }
=20
-const ProgramState*
-RangeConstraintManager::assumeSymGT(const ProgramState *state, SymbolRef s=
ym,
+ProgramStateRef=20
+RangeConstraintManager::assumeSymGT(ProgramStateRef state, SymbolRef sym,
                                     const llvm::APSInt& Int,
                                     const llvm::APSInt& Adjustment) {
   BasicValueFactory &BV =3D state->getBasicVals();
@@ -375,8 +375,8 @@
   return New.isEmpty() ? NULL : state->set<ConstraintRange>(sym, New);
 }
=20
-const ProgramState*
-RangeConstraintManager::assumeSymGE(const ProgramState *state, SymbolRef s=
ym,
+ProgramStateRef=20
+RangeConstraintManager::assumeSymGE(ProgramStateRef state, SymbolRef sym,
                                     const llvm::APSInt& Int,
                                     const llvm::APSInt& Adjustment) {
   BasicValueFactory &BV =3D state->getBasicVals();
@@ -397,8 +397,8 @@
   return New.isEmpty() ? NULL : state->set<ConstraintRange>(sym, New);
 }
=20
-const ProgramState*
-RangeConstraintManager::assumeSymLE(const ProgramState *state, SymbolRef s=
ym,
+ProgramStateRef=20
+RangeConstraintManager::assumeSymLE(ProgramStateRef state, SymbolRef sym,
                                     const llvm::APSInt& Int,
                                     const llvm::APSInt& Adjustment) {
   BasicValueFactory &BV =3D state->getBasicVals();
@@ -423,18 +423,20 @@
 // Pretty-printing.
 //=3D=3D=3D---------------------------------------------------------------=
---------=3D=3D=3D/
=20
-void RangeConstraintManager::print(const ProgramState *St, raw_ostream &Ou=
t,
+void RangeConstraintManager::print(ProgramStateRef St, raw_ostream &Out,
                                    const char* nl, const char *sep) {
=20
   ConstraintRangeTy Ranges =3D St->get<ConstraintRange>();
=20
-  if (Ranges.isEmpty())
+  if (Ranges.isEmpty()) {
+    Out << nl << sep << "Ranges are empty." << nl;
     return;
+  }
=20
-  Out << nl << sep << "ranges of symbol values:";
-
+  Out << nl << sep << "Ranges of symbol values:";
   for (ConstraintRangeTy::iterator I=3DRanges.begin(), E=3DRanges.end(); I=
!=3DE; ++I){
     Out << nl << ' ' << I.getKey() << " : ";
     I.getData().print(Out);
   }
+  Out << nl;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/RegionStore.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/RegionStore.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/RegionStore.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 #include "clang/Analysis/Analyses/LiveVariables.h"
 #include "clang/Analysis/AnalysisContext.h"
 #include "clang/Basic/TargetInfo.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
@@ -228,6 +229,16 @@
   /// For DerivedToBase casts, create a CXXBaseObjectRegion and return it.
   virtual SVal evalDerivedToBase(SVal derived, QualType basePtrType);
=20
+  /// \brief Evaluates C++ dynamic_cast cast.
+  /// The callback may result in the following 3 scenarios:
+  ///  - Successful cast (ex: derived is subclass of base).
+  ///  - Failed cast (ex: derived is definitely not a subclass of base).
+  ///  - We don't know (base is a symbolic region and we don't have=20
+  ///    enough info to determine if the cast will succeed at run time).
+  /// The function returns an SVal representing the derived class; it's
+  /// valid only if Failed flag is set to false.
+  virtual SVal evalDynamicCast(SVal base, QualType derivedPtrType,bool &Fa=
iled);
+
   StoreRef getInitialStore(const LocationContext *InitLoc) {
     return StoreRef(RBFactory.getEmptyMap().getRootWithoutRetain(), *this);
   }
@@ -235,11 +246,18 @@
   //=3D=3D=3D-------------------------------------------------------------=
------=3D=3D=3D//
   // Binding values to regions.
   //=3D=3D=3D-------------------------------------------------------------=
------=3D=3D=3D//
+  RegionBindings invalidateGlobalRegion(MemRegion::Kind K,
+                                        const Expr *Ex,
+                                        unsigned Count,
+                                        const LocationContext *LCtx,
+                                        RegionBindings B,
+                                        InvalidatedRegions *Invalidated);
=20
   StoreRef invalidateRegions(Store store, ArrayRef<const MemRegion *> Regi=
ons,
                              const Expr *E, unsigned Count,
+                             const LocationContext *LCtx,
                              InvalidatedSymbols &IS,
-                             bool invalidateGlobals,
+                             const CallOrObjCMessage *Call,
                              InvalidatedRegions *Invalidated);
=20
 public:   // Made public for helper classes.
@@ -273,7 +291,8 @@
     RegionBindings B =3D GetRegionBindings(store);
     assert(!lookup(B, R, BindingKey::Default));
     assert(!lookup(B, R, BindingKey::Direct));
-    return StoreRef(addBinding(B, R, BindingKey::Default, V).getRootWithou=
tRetain(), *this);
+    return StoreRef(addBinding(B, R, BindingKey::Default, V)
+                      .getRootWithoutRetain(), *this);
   }
=20
   StoreRef BindCompoundLiteral(Store store, const CompoundLiteralExpr *CL,
@@ -308,12 +327,10 @@
  =20
   bool includedInBindings(Store store, const MemRegion *region) const;
=20
-  //=3D=3D=3D-------------------------------------------------------------=
-----=3D=3D=3D//
-  // Loading values from regions.
-  //=3D=3D=3D-------------------------------------------------------------=
-----=3D=3D=3D//
-
+  /// \brief Return the value bound to specified location in a given state.
+  ///
   /// The high level logic for this method is this:
-  /// Retrieve (L)
+  /// getBinding (L)
   ///   if L has binding
   ///     return L's binding
   ///   else if L is in killset
@@ -323,39 +340,39 @@
   ///       return undefined
   ///     else
   ///       return symbolic
-  SVal Retrieve(Store store, Loc L, QualType T =3D QualType());
+  SVal getBinding(Store store, Loc L, QualType T =3D QualType());
=20
-  SVal RetrieveElement(Store store, const ElementRegion *R);
+  SVal getBindingForElement(Store store, const ElementRegion *R);
=20
-  SVal RetrieveField(Store store, const FieldRegion *R);
+  SVal getBindingForField(Store store, const FieldRegion *R);
=20
-  SVal RetrieveObjCIvar(Store store, const ObjCIvarRegion *R);
+  SVal getBindingForObjCIvar(Store store, const ObjCIvarRegion *R);
=20
-  SVal RetrieveVar(Store store, const VarRegion *R);
+  SVal getBindingForVar(Store store, const VarRegion *R);
=20
-  SVal RetrieveLazySymbol(const TypedValueRegion *R);
+  SVal getBindingForLazySymbol(const TypedValueRegion *R);
=20
-  SVal RetrieveFieldOrElementCommon(Store store, const TypedValueRegion *R,
-                                    QualType Ty, const MemRegion *superR);
+  SVal getBindingForFieldOrElementCommon(Store store, const TypedValueRegi=
on *R,
+                                         QualType Ty, const MemRegion *sup=
erR);
  =20
-  SVal RetrieveLazyBinding(const MemRegion *lazyBindingRegion,
-                           Store lazyBindingStore);
+  SVal getLazyBinding(const MemRegion *lazyBindingRegion,
+                      Store lazyBindingStore);
=20
-  /// Retrieve the values in a struct and return a CompoundVal, used when =
doing
-  /// struct copy:
+  /// Get bindings for the values in a struct and return a CompoundVal, us=
ed
+  /// when doing struct copy:
   /// struct s x, y;
   /// x =3D y;
   /// y's value is retrieved by this method.
-  SVal RetrieveStruct(Store store, const TypedValueRegion* R);
+  SVal getBindingForStruct(Store store, const TypedValueRegion* R);
=20
-  SVal RetrieveArray(Store store, const TypedValueRegion* R);
+  SVal getBindingForArray(Store store, const TypedValueRegion* R);
=20
   /// Used to lazily generate derived symbols for bindings that are defined
   ///  implicitly by default bindings in a super region.
-  Optional<SVal> RetrieveDerivedDefaultValue(RegionBindings B,
-                                             const MemRegion *superR,
-                                             const TypedValueRegion *R,=20
-                                             QualType Ty);
+  Optional<SVal> getBindingForDerivedDefaultValue(RegionBindings B,
+                                                  const MemRegion *superR,
+                                                  const TypedValueRegion *=
R,
+                                                  QualType Ty);
=20
   /// Get the state and region whose binding this region R corresponds to.
   std::pair<Store, const MemRegion*>
@@ -374,15 +391,16 @@
   StoreRef removeDeadBindings(Store store, const StackFrameContext *LCtx,
                               SymbolReaper& SymReaper);
=20
-  StoreRef enterStackFrame(const ProgramState *state,
-                           const StackFrameContext *frame);
+  StoreRef enterStackFrame(ProgramStateRef state,
+                           const LocationContext *callerCtx,
+                           const StackFrameContext *calleeCtx);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-----=3D=3D=3D//
   // Region "extents".
   //=3D=3D=3D-------------------------------------------------------------=
-----=3D=3D=3D//
=20
   // FIXME: This method will soon be eliminated; see the note in Store.h.
-  DefinedOrUnknownSVal getSizeInElements(const ProgramState *state,
+  DefinedOrUnknownSVal getSizeInElements(ProgramStateRef state,
                                          const MemRegion* R, QualType EleT=
y);
=20
   //=3D=3D=3D-------------------------------------------------------------=
-----=3D=3D=3D//
@@ -422,7 +440,8 @@
   return new RegionStoreManager(StMgr, F);
 }
=20
-StoreManager *ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager=
 &StMgr) {
+StoreManager *
+ento::CreateFieldsOnlyRegionStoreManager(ProgramStateManager &StMgr) {
   RegionStoreFeatures F =3D minimal_features_tag();
   F.enableFields(true);
   return new RegionStoreManager(StMgr, F);
@@ -587,6 +606,7 @@
 {
   const Expr *Ex;
   unsigned Count;
+  const LocationContext *LCtx;
   StoreManager::InvalidatedSymbols &IS;
   StoreManager::InvalidatedRegions *Regions;
 public:
@@ -594,11 +614,12 @@
                           ProgramStateManager &stateMgr,
                           RegionBindings b,
                           const Expr *ex, unsigned count,
+                          const LocationContext *lctx,
                           StoreManager::InvalidatedSymbols &is,
                           StoreManager::InvalidatedRegions *r,
                           bool includeGlobals)
     : ClusterAnalysis<invalidateRegionsWorker>(rm, stateMgr, b, includeGlo=
bals),
-      Ex(ex), Count(count), IS(is), Regions(r) {}
+      Ex(ex), Count(count), LCtx(lctx), IS(is), Regions(r) {}
=20
   void VisitCluster(const MemRegion *baseR, BindingKey *I, BindingKey *E);
   void VisitBaseRegion(const MemRegion *baseR);
@@ -674,7 +695,7 @@
     // Invalidate the region by setting its default value to
     // conjured symbol. The type of the symbol is irrelavant.
     DefinedOrUnknownSVal V =3D
-      svalBuilder.getConjuredSymbolVal(baseR, Ex, Ctx.IntTy, Count);
+      svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
     B =3D RM.addBinding(B, baseR, BindingKey::Default, V);
     return;
   }
@@ -690,7 +711,7 @@
     // Invalidate the region by setting its default value to
     // conjured symbol. The type of the symbol is irrelavant.
     DefinedOrUnknownSVal V =3D
-      svalBuilder.getConjuredSymbolVal(baseR, Ex, Ctx.IntTy, Count);
+      svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx, Ctx.IntTy, Count);
     B =3D RM.addBinding(B, baseR, BindingKey::Default, V);
     return;
   }
@@ -698,7 +719,8 @@
   if (const ArrayType *AT =3D Ctx.getAsArrayType(T)) {
       // Set the default value of the array to conjured symbol.
     DefinedOrUnknownSVal V =3D
-    svalBuilder.getConjuredSymbolVal(baseR, Ex, AT->getElementType(), Coun=
t);
+    svalBuilder.getConjuredSymbolVal(baseR, Ex, LCtx,
+                                     AT->getElementType(), Count);
     B =3D RM.addBinding(B, baseR, BindingKey::Default, V);
     return;
   }
@@ -713,20 +735,47 @@
   }
  =20
=20
-  DefinedOrUnknownSVal V =3D svalBuilder.getConjuredSymbolVal(baseR, Ex, T=
, Count);
+  DefinedOrUnknownSVal V =3D svalBuilder.getConjuredSymbolVal(baseR, Ex, L=
Ctx,
+                                                            T,Count);
   assert(SymbolManager::canSymbolicate(T) || V.isUnknown());
   B =3D RM.addBinding(B, baseR, BindingKey::Direct, V);
 }
=20
+RegionBindings RegionStoreManager::invalidateGlobalRegion(MemRegion::Kind =
K,
+                                                          const Expr *Ex,
+                                                          unsigned Count,
+                                                    const LocationContext =
*LCtx,
+                                                          RegionBindings B,
+                                            InvalidatedRegions *Invalidate=
d) {
+  // Bind the globals memory space to a new symbol that we will use to der=
ive
+  // the bindings for all globals.
+  const GlobalsSpaceRegion *GS =3D MRMgr.getGlobalsRegion(K);
+  SVal V =3D
+      svalBuilder.getConjuredSymbolVal(/* SymbolTag =3D */ (void*) GS, Ex,=
 LCtx,
+          /* symbol type, doesn't matter */ Ctx.IntTy,
+          Count);
+
+  B =3D removeBinding(B, GS);
+  B =3D addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
+
+  // Even if there are no bindings in the global scope, we still need to
+  // record that we touched it.
+  if (Invalidated)
+    Invalidated->push_back(GS);
+
+  return B;
+}
+
 StoreRef RegionStoreManager::invalidateRegions(Store store,
                                             ArrayRef<const MemRegion *> Re=
gions,
                                                const Expr *Ex, unsigned Co=
unt,
+                                               const LocationContext *LCtx,
                                                InvalidatedSymbols &IS,
-                                               bool invalidateGlobals,
+                                               const CallOrObjCMessage *Ca=
ll,
                                               InvalidatedRegions *Invalida=
ted) {
   invalidateRegionsWorker W(*this, StateMgr,
                             RegionStoreManager::GetRegionBindings(store),
-                            Ex, Count, IS, Invalidated, invalidateGlobals);
+                            Ex, Count, LCtx, IS, Invalidated, false);
=20
   // Scan the bindings and generate the clusters.
   W.GenerateClusters();
@@ -741,20 +790,20 @@
   // Return the new bindings.
   RegionBindings B =3D W.getRegionBindings();
=20
-  if (invalidateGlobals) {
-    // Bind the non-static globals memory space to a new symbol that we wi=
ll
-    // use to derive the bindings for all non-static globals.
-    const GlobalsSpaceRegion *GS =3D MRMgr.getGlobalsRegion();
-    SVal V =3D
-      svalBuilder.getConjuredSymbolVal(/* SymbolTag =3D */ (void*) GS, Ex,
-                                  /* symbol type, doesn't matter */ Ctx.In=
tTy,
-                                  Count);
-    B =3D addBinding(B, BindingKey::Make(GS, BindingKey::Default), V);
-
-    // Even if there are no bindings in the global scope, we still need to
-    // record that we touched it.
-    if (Invalidated)
-      Invalidated->push_back(GS);
+  // For all globals which are not static nor immutable: determine which g=
lobal
+  // regions should be invalidated and invalidate them.
+  // TODO: This could possibly be more precise with modules.
+  //
+  // System calls invalidate only system globals.
+  if (Call && Call->isInSystemHeader()) {
+    B =3D invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
+                               Ex, Count, LCtx, B, Invalidated);
+  // Internal calls might invalidate both system and internal globals.
+  } else {
+    B =3D invalidateGlobalRegion(MemRegion::GlobalSystemSpaceRegionKind,
+                               Ex, Count, LCtx, B, Invalidated);
+    B =3D invalidateGlobalRegion(MemRegion::GlobalInternalSpaceRegionKind,
+                               Ex, Count, LCtx, B, Invalidated);
   }
=20
   return StoreRef(B.getRootWithoutRetain(), *this);
@@ -764,9 +813,10 @@
 // Extents for regions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-DefinedOrUnknownSVal RegionStoreManager::getSizeInElements(const ProgramSt=
ate *state,
-                                                           const MemRegion=
 *R,
-                                                           QualType EleTy)=
 {
+DefinedOrUnknownSVal
+RegionStoreManager::getSizeInElements(ProgramStateRef state,
+                                      const MemRegion *R,
+                                      QualType EleTy) {
   SVal Size =3D cast<SubRegion>(R)->getExtent(svalBuilder);
   const llvm::APSInt *SizeInt =3D svalBuilder.getKnownValue(state, Size);
   if (!SizeInt)
@@ -837,6 +887,75 @@
   return loc::MemRegionVal(baseReg);
 }
=20
+SVal RegionStoreManager::evalDynamicCast(SVal base, QualType derivedType,
+                                         bool &Failed) {
+  Failed =3D false;
+
+  loc::MemRegionVal *baseRegVal =3D dyn_cast<loc::MemRegionVal>(&base);
+  if (!baseRegVal)
+    return UnknownVal();
+  const MemRegion *BaseRegion =3D baseRegVal->stripCasts();
+
+  // Assume the derived class is a pointer or a reference to a CXX record.
+  derivedType =3D derivedType->getPointeeType();
+  assert(!derivedType.isNull());
+  const CXXRecordDecl *DerivedDecl =3D derivedType->getAsCXXRecordDecl();
+  if (!DerivedDecl && !derivedType->isVoidType())
+    return UnknownVal();
+
+  // Drill down the CXXBaseObject chains, which represent upcasts (casts f=
rom
+  // derived to base).
+  const MemRegion *SR =3D BaseRegion;
+  while (const TypedRegion *TSR =3D dyn_cast_or_null<TypedRegion>(SR)) {
+    QualType BaseType =3D TSR->getLocationType()->getPointeeType();
+    assert(!BaseType.isNull());
+    const CXXRecordDecl *SRDecl =3D BaseType->getAsCXXRecordDecl();
+    if (!SRDecl)
+      return UnknownVal();
+
+    // If found the derived class, the cast succeeds.
+    if (SRDecl =3D=3D DerivedDecl)
+      return loc::MemRegionVal(TSR);
+
+    // If the region type is a subclass of the derived type.
+    if (!derivedType->isVoidType() && SRDecl->isDerivedFrom(DerivedDecl)) {
+      // This occurs in two cases.
+      // 1) We are processing an upcast.
+      // 2) We are processing a downcast but we jumped directly from the
+      // ancestor to a child of the cast value, so conjure the
+      // appropriate region to represent value (the intermediate node).
+      return loc::MemRegionVal(MRMgr.getCXXBaseObjectRegion(DerivedDecl,
+                                                            BaseRegion));
+    }
+
+    // If super region is not a parent of derived class, the cast definite=
ly
+    // fails.
+    if (!derivedType->isVoidType() &&
+        DerivedDecl->isProvablyNotDerivedFrom(SRDecl)) {
+      Failed =3D true;
+      return UnknownVal();
+    }
+
+    if (const CXXBaseObjectRegion *R =3D dyn_cast<CXXBaseObjectRegion>(TSR=
))
+      // Drill down the chain to get the derived classes.
+      SR =3D R->getSuperRegion();
+    else {
+      // We reached the bottom of the hierarchy.
+
+      // If this is a cast to void*, return the region.
+      if (derivedType->isVoidType())
+        return loc::MemRegionVal(TSR);
+
+      // We did not find the derived class. We we must be casting the base=
 to
+      // derived, so the cast should fail.
+      Failed =3D true;
+      return UnknownVal();
+    }
+  }
+
+  return UnknownVal();
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Loading values from regions.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -863,7 +982,7 @@
   return Optional<SVal>();
 }
=20
-SVal RegionStoreManager::Retrieve(Store store, Loc L, QualType T) {
+SVal RegionStoreManager::getBinding(Store store, Loc L, QualType T) {
   assert(!isa<UnknownVal>(L) && "location unknown");
   assert(!isa<UndefinedVal>(L) && "location undefined");
=20
@@ -882,18 +1001,20 @@
=20
   const MemRegion *MR =3D cast<loc::MemRegionVal>(L).getRegion();
=20
-  if (isa<AllocaRegion>(MR) || isa<SymbolicRegion>(MR)) {
+  if (isa<AllocaRegion>(MR) ||
+      isa<SymbolicRegion>(MR) ||
+      isa<CodeTextRegion>(MR)) {
     if (T.isNull()) {
-      const SymbolicRegion *SR =3D cast<SymbolicRegion>(MR);
-      T =3D SR->getSymbol()->getType(Ctx);
+      if (const TypedRegion *TR =3D dyn_cast<TypedRegion>(MR))
+        T =3D TR->getLocationType();
+      else {
+        const SymbolicRegion *SR =3D cast<SymbolicRegion>(MR);
+        T =3D SR->getSymbol()->getType(Ctx);
+      }
     }
     MR =3D GetElementZeroRegion(MR, T);
   }
=20
-  if (isa<CodeTextRegion>(MR)) {
-    llvm_unreachable("Why load from a code text region?");
-  }
-
   // FIXME: Perhaps this method should just take a 'const MemRegion*' argu=
ment
   //  instead of 'Loc', and have the other Loc cases handled at a higher l=
evel.
   const TypedValueRegion *R =3D cast<TypedValueRegion>(MR);
@@ -909,21 +1030,21 @@
   // Such funny addressing will occur due to layering of regions.
=20
   if (RTy->isStructureOrClassType())
-    return RetrieveStruct(store, R);
+    return getBindingForStruct(store, R);
=20
   // FIXME: Handle unions.
   if (RTy->isUnionType())
     return UnknownVal();
=20
   if (RTy->isArrayType())
-    return RetrieveArray(store, R);
+    return getBindingForArray(store, R);
=20
   // FIXME: handle Vector types.
   if (RTy->isVectorType())
     return UnknownVal();
=20
   if (const FieldRegion* FR =3D dyn_cast<FieldRegion>(R))
-    return CastRetrievedVal(RetrieveField(store, FR), FR, T, false);
+    return CastRetrievedVal(getBindingForField(store, FR), FR, T, false);
=20
   if (const ElementRegion* ER =3D dyn_cast<ElementRegion>(R)) {
     // FIXME: Here we actually perform an implicit conversion from the loa=
ded
@@ -931,7 +1052,7 @@
     // more intelligently.  For example, an 'element' can encompass multip=
le
     // bound regions (e.g., several bound bytes), or could be a subset of
     // a larger value.
-    return CastRetrievedVal(RetrieveElement(store, ER), ER, T, false);
+    return CastRetrievedVal(getBindingForElement(store, ER), ER, T, false);
   }
=20
   if (const ObjCIvarRegion *IVR =3D dyn_cast<ObjCIvarRegion>(R)) {
@@ -941,7 +1062,7 @@
     // reinterpretted, it is possible we stored a different value that cou=
ld
     // fit within the ivar.  Either we need to cast these when storing them
     // or reinterpret them lazily (as we do here).
-    return CastRetrievedVal(RetrieveObjCIvar(store, IVR), IVR, T, false);
+    return CastRetrievedVal(getBindingForObjCIvar(store, IVR), IVR, T, fal=
se);
   }
=20
   if (const VarRegion *VR =3D dyn_cast<VarRegion>(R)) {
@@ -951,7 +1072,7 @@
     // variable is reinterpretted, it is possible we stored a different va=
lue
     // that could fit within the variable.  Either we need to cast these w=
hen
     // storing them or reinterpret them lazily (as we do here).
-    return CastRetrievedVal(RetrieveVar(store, VR), VR, T, false);
+    return CastRetrievedVal(getBindingForVar(store, VR), VR, T, false);
   }
=20
   RegionBindings B =3D GetRegionBindings(store);
@@ -1021,7 +1142,7 @@
   return std::make_pair((Store) 0, (const MemRegion *) 0);
 }
=20
-SVal RegionStoreManager::RetrieveElement(Store store,
+SVal RegionStoreManager::getBindingForElement(Store store,
                                          const ElementRegion* R) {
   // Check if the region has a binding.
   RegionBindings B =3D GetRegionBindings(store);
@@ -1043,15 +1164,15 @@
     if (nonloc::ConcreteInt *CI =3D dyn_cast<nonloc::ConcreteInt>(&Idx)) {
       int64_t i =3D CI->getValue().getSExtValue();
       // Abort on string underrun.  This can be possible by arbitrary
-      // clients of RetrieveElement().
+      // clients of getBindingForElement().
       if (i < 0)
         return UndefinedVal();
-      int64_t byteLength =3D Str->getByteLength();
-      // Technically, only i =3D=3D byteLength is guaranteed to be null.
+      int64_t length =3D Str->getLength();
+      // Technically, only i =3D=3D length is guaranteed to be null.
       // However, such overflows should be caught before reaching this poi=
nt;
       // the only time such an access would be made is if a string literal=
 was
       // used to initialize a larger array.
-      char c =3D (i >=3D byteLength) ? '\0' : Str->getString()[i];
+      char c =3D (i >=3D length) ? '\0' : Str->getCodeUnit(i);
       return svalBuilder.makeIntVal(c, T);
     }
   }
@@ -1093,10 +1214,11 @@
       }
     }
   }
-  return RetrieveFieldOrElementCommon(store, R, R->getElementType(), super=
R);
+  return getBindingForFieldOrElementCommon(store, R, R->getElementType(),
+                                           superR);
 }
=20
-SVal RegionStoreManager::RetrieveField(Store store,
+SVal RegionStoreManager::getBindingForField(Store store,
                                        const FieldRegion* R) {
=20
   // Check if the region has a binding.
@@ -1105,14 +1227,14 @@
     return *V;
=20
   QualType Ty =3D R->getValueType();
-  return RetrieveFieldOrElementCommon(store, R, Ty, R->getSuperRegion());
+  return getBindingForFieldOrElementCommon(store, R, Ty, R->getSuperRegion=
());
 }
=20
 Optional<SVal>
-RegionStoreManager::RetrieveDerivedDefaultValue(RegionBindings B,
-                                                const MemRegion *superR,
-                                                const TypedValueRegion *R,
-                                                QualType Ty) {
+RegionStoreManager::getBindingForDerivedDefaultValue(RegionBindings B,
+                                                     const MemRegion *supe=
rR,
+                                                     const TypedValueRegio=
n *R,
+                                                     QualType Ty) {
=20
   if (const Optional<SVal> &D =3D getDefaultBinding(B, superR)) {
     const SVal &val =3D D.getValue();
@@ -1135,30 +1257,39 @@
   return Optional<SVal>();
 }
=20
-SVal RegionStoreManager::RetrieveLazyBinding(const MemRegion *lazyBindingR=
egion,
+SVal RegionStoreManager::getLazyBinding(const MemRegion *lazyBindingRegion,
                                              Store lazyBindingStore) {
   if (const ElementRegion *ER =3D dyn_cast<ElementRegion>(lazyBindingRegio=
n))
-    return RetrieveElement(lazyBindingStore, ER);
+    return getBindingForElement(lazyBindingStore, ER);
  =20
-  return RetrieveField(lazyBindingStore,
-                       cast<FieldRegion>(lazyBindingRegion));
+  return getBindingForField(lazyBindingStore,
+                            cast<FieldRegion>(lazyBindingRegion));
 }
                                        =20
-SVal RegionStoreManager::RetrieveFieldOrElementCommon(Store store,
+SVal RegionStoreManager::getBindingForFieldOrElementCommon(Store store,
                                                       const TypedValueRegi=
on *R,
                                                       QualType Ty,
                                                       const MemRegion *sup=
erR) {
=20
-  // At this point we have already checked in either RetrieveElement or
-  // RetrieveField if 'R' has a direct binding.
-
+  // At this point we have already checked in either getBindingForElement =
or
+  // getBindingForField if 'R' has a direct binding.
   RegionBindings B =3D GetRegionBindings(store);
+ =20
+  // Record whether or not we see a symbolic index.  That can completely
+  // be out of scope of our lookup.
+  bool hasSymbolicIndex =3D false;
=20
   while (superR) {
     if (const Optional<SVal> &D =3D
-        RetrieveDerivedDefaultValue(B, superR, R, Ty))
+        getBindingForDerivedDefaultValue(B, superR, R, Ty))
       return *D;
=20
+    if (const ElementRegion *ER =3D dyn_cast<ElementRegion>(superR)) {
+      NonLoc index =3D ER->getIndex();
+      if (!index.isConstant())
+        hasSymbolicIndex =3D true;
+    }
+   =20
     // If our super region is a field or element itself, walk up the region
     // hierarchy to see if there is a default value installed in an ancest=
or.
     if (const SubRegion *SR =3D dyn_cast<SubRegion>(superR)) {
@@ -1174,10 +1305,10 @@
   llvm::tie(lazyBindingStore, lazyBindingRegion) =3D GetLazyBinding(B, R, =
R);
=20
   if (lazyBindingRegion)
-    return RetrieveLazyBinding(lazyBindingRegion, lazyBindingStore);
+    return getLazyBinding(lazyBindingRegion, lazyBindingStore);
=20
   if (R->hasStackNonParametersStorage()) {
-    if (const ElementRegion *ER =3D dyn_cast<ElementRegion>(R)) {
+    if (isa<ElementRegion>(R)) {
       // Currently we don't reason specially about Clang-style vectors.  C=
heck
       // if superR is a vector and if so return Unknown.
       if (const TypedValueRegion *typedSuperR =3D=20
@@ -1185,13 +1316,15 @@
         if (typedSuperR->getValueType()->isVectorType())
           return UnknownVal();
       }
-     =20
-      // FIXME: We also need to take ElementRegions with symbolic indexes =
into
-      // account.
-      if (!ER->getIndex().isConstant())
-        return UnknownVal();
     }
=20
+    // FIXME: We also need to take ElementRegions with symbolic indexes in=
to
+    // account.  This case handles both directly accessing an ElementRegion
+    // with a symbolic offset, but also fields within an element with
+    // a symbolic offset.
+    if (hasSymbolicIndex)
+      return UnknownVal();
+   =20
     return UndefinedVal();
   }
=20
@@ -1199,7 +1332,8 @@
   return svalBuilder.getRegionValueSymbolVal(R);
 }
=20
-SVal RegionStoreManager::RetrieveObjCIvar(Store store, const ObjCIvarRegio=
n* R){
+SVal RegionStoreManager::getBindingForObjCIvar(Store store,
+                                               const ObjCIvarRegion* R) {
=20
     // Check if the region has a binding.
   RegionBindings B =3D GetRegionBindings(store);
@@ -1218,10 +1352,10 @@
     return UnknownVal();
   }
=20
-  return RetrieveLazySymbol(R);
+  return getBindingForLazySymbol(R);
 }
=20
-SVal RegionStoreManager::RetrieveVar(Store store, const VarRegion *R) {
+SVal RegionStoreManager::getBindingForVar(Store store, const VarRegion *R)=
 {
=20
   // Check if the region has a binding.
   RegionBindings B =3D GetRegionBindings(store);
@@ -1253,7 +1387,8 @@
           }
       }
=20
-      if (const Optional<SVal> &V =3D RetrieveDerivedDefaultValue(B, MS, R=
, CT))
+      if (const Optional<SVal> &V
+            =3D getBindingForDerivedDefaultValue(B, MS, R, CT))
         return V.getValue();
=20
       return svalBuilder.getRegionValueSymbolVal(R);
@@ -1270,19 +1405,18 @@
   return UndefinedVal();
 }
=20
-SVal RegionStoreManager::RetrieveLazySymbol(const TypedValueRegion *R) {
+SVal RegionStoreManager::getBindingForLazySymbol(const TypedValueRegion *R=
) {
   // All other values are symbolic.
   return svalBuilder.getRegionValueSymbolVal(R);
 }
=20
-SVal RegionStoreManager::RetrieveStruct(Store store,=20
+SVal RegionStoreManager::getBindingForStruct(Store store,=20
                                         const TypedValueRegion* R) {
-  QualType T =3D R->getValueType();
-  assert(T->isStructureOrClassType());
+  assert(R->getValueType()->isStructureOrClassType());
   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
 }
=20
-SVal RegionStoreManager::RetrieveArray(Store store,=20
+SVal RegionStoreManager::getBindingForArray(Store store,=20
                                        const TypedValueRegion * R) {
   assert(Ctx.getAsConstantArrayType(R->getValueType()));
   return svalBuilder.makeLazyCompoundVal(StoreRef(store, *this), R);
@@ -1506,11 +1640,15 @@
   RecordDecl::field_iterator FI, FE;
   StoreRef newStore(store, *this);
  =20
-  for (FI =3D RD->field_begin(), FE =3D RD->field_end(); FI !=3D FE; ++FI,=
 ++VI) {
+  for (FI =3D RD->field_begin(), FE =3D RD->field_end(); FI !=3D FE; ++FI)=
 {
=20
     if (VI =3D=3D VE)
       break;
=20
+    // Skip any unnamed bitfields to stay in sync with the initializers.
+    if ((*FI)->isUnnamedBitfield())
+      continue;
+
     QualType FTy =3D (*FI)->getType();
     const FieldRegion* FR =3D MRMgr.getFieldRegion(*FI, R);
=20
@@ -1520,6 +1658,7 @@
       newStore =3D BindStruct(newStore.getStore(), FR, *VI);
     else
       newStore =3D Bind(newStore.getStore(), svalBuilder.makeLoc(FR), *VI);
+    ++VI;
   }
=20
   // There may be fewer values in the initialize list than the fields of s=
truct.
@@ -1556,7 +1695,7 @@
   // Remove the old bindings, using 'subReg' as the root of all regions
   // we will invalidate.
   RegionBindings B =3D GetRegionBindings(store);
-  llvm::OwningPtr<RegionStoreSubRegionMap>
+  OwningPtr<RegionStoreSubRegionMap>
     SubRegions(getRegionStoreSubRegionMap(store));
   RemoveSubRegionBindings(B, subReg, *SubRegions);
=20
@@ -1574,7 +1713,7 @@
   // Nuke the old bindings stemming from R.
   RegionBindings B =3D GetRegionBindings(store);
=20
-  llvm::OwningPtr<RegionStoreSubRegionMap>
+  OwningPtr<RegionStoreSubRegionMap>
     SubRegions(getRegionStoreSubRegionMap(store));
=20
   // B and DVM are updated after the call to RemoveSubRegionBindings.
@@ -1641,7 +1780,8 @@
   const StackFrameContext *CurrentLCtx;
=20
 public:
-  removeDeadBindingsWorker(RegionStoreManager &rm, ProgramStateManager &st=
ateMgr,
+  removeDeadBindingsWorker(RegionStoreManager &rm,
+                           ProgramStateManager &stateMgr,
                            RegionBindings b, SymbolReaper &symReaper,
                            const StackFrameContext *LCtx)
     : ClusterAnalysis<removeDeadBindingsWorker>(rm, stateMgr, b,
@@ -1717,9 +1857,9 @@
   if (const MemRegion *R =3D V.getAsRegion())
     AddToWorkList(R);
=20
-    // Update the set of live symbols.
-  for (SVal::symbol_iterator SI=3DV.symbol_begin(), SE=3DV.symbol_end();
-       SI!=3DSE;++SI)
+  // Update the set of live symbols.
+  for (SymExpr::symbol_iterator SI =3D V.symbol_begin(), SE =3D V.symbol_e=
nd();
+       SI!=3DSE; ++SI)
     SymReaper.markLive(*SI);
 }
=20
@@ -1807,7 +1947,7 @@
       SymReaper.maybeDead(SymR->getSymbol());
=20
     SVal X =3D I.getData();
-    SVal::symbol_iterator SI =3D X.symbol_begin(), SE =3D X.symbol_end();
+    SymExpr::symbol_iterator SI =3D X.symbol_begin(), SE =3D X.symbol_end(=
);
     for (; SI !=3D SE; ++SI)
       SymReaper.maybeDead(*SI);
   }
@@ -1816,37 +1956,41 @@
 }
=20
=20
-StoreRef RegionStoreManager::enterStackFrame(const ProgramState *state,
-                                             const StackFrameContext *fram=
e) {
-  FunctionDecl const *FD =3D cast<FunctionDecl>(frame->getDecl());
+StoreRef RegionStoreManager::enterStackFrame(ProgramStateRef state,
+                                             const LocationContext *caller=
Ctx,
+                                             const StackFrameContext *call=
eeCtx)
+{
+  FunctionDecl const *FD =3D cast<FunctionDecl>(calleeCtx->getDecl());
   FunctionDecl::param_const_iterator PI =3D FD->param_begin(),=20
                                      PE =3D FD->param_end();
   StoreRef store =3D StoreRef(state->getStore(), *this);
=20
-  if (CallExpr const *CE =3D dyn_cast<CallExpr>(frame->getCallSite())) {
+  if (CallExpr const *CE =3D dyn_cast<CallExpr>(calleeCtx->getCallSite()))=
 {
     CallExpr::const_arg_iterator AI =3D CE->arg_begin(), AE =3D CE->arg_en=
d();
=20
     // Copy the arg expression value to the arg variables.  We check that
     // PI !=3D PE because the actual number of arguments may be different =
than
     // the function declaration.
     for (; AI !=3D AE && PI !=3D PE; ++AI, ++PI) {
-      SVal ArgVal =3D state->getSVal(*AI);
+      SVal ArgVal =3D state->getSVal(*AI, callerCtx);
       store =3D Bind(store.getStore(),
-                   svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, frame)), Ar=
gVal);
+                   svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, calleeCtx)),
+                   ArgVal);
     }
   } else if (const CXXConstructExpr *CE =3D
-               dyn_cast<CXXConstructExpr>(frame->getCallSite())) {
+               dyn_cast<CXXConstructExpr>(calleeCtx->getCallSite())) {
     CXXConstructExpr::const_arg_iterator AI =3D CE->arg_begin(),
       AE =3D CE->arg_end();
=20
     // Copy the arg expression value to the arg variables.
     for (; AI !=3D AE; ++AI, ++PI) {
-      SVal ArgVal =3D state->getSVal(*AI);
+      SVal ArgVal =3D state->getSVal(*AI, callerCtx);
       store =3D Bind(store.getStore(),
-                   svalBuilder.makeLoc(MRMgr.getVarRegion(*PI,frame)), Arg=
Val);
+                   svalBuilder.makeLoc(MRMgr.getVarRegion(*PI, calleeCtx)),
+                   ArgVal);
     }
   } else
-    assert(isa<CXXDestructorDecl>(frame->getDecl()));
+    assert(isa<CXXDestructorDecl>(calleeCtx->getDecl()));
=20
   return store;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/SValBuilder.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp=
	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp=
	Tue Apr 17 11:51:51 2012 +0300
@@ -12,6 +12,7 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "clang/AST/ExprCXX.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
@@ -25,6 +26,8 @@
 // Basic SVal creation.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+void SValBuilder::anchor() { }
+
 DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) {
   if (Loc::isLocType(type))
     return makeNull();
@@ -37,23 +40,38 @@
   return UnknownVal();
 }
=20
-
 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode =
op,
                                 const llvm::APSInt& rhs, QualType type) {
   // The Environment ensures we always get a persistent APSInt in
   // BasicValueFactory, so we don't need to get the APSInt from
   // BasicValueFactory again.
+  assert(lhs);
   assert(!Loc::isLocType(type));
-  return nonloc::SymExprVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
+  return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
+}
+
+NonLoc SValBuilder::makeNonLoc(const llvm::APSInt& lhs,
+                               BinaryOperator::Opcode op, const SymExpr *r=
hs,
+                               QualType type) {
+  assert(rhs);
+  assert(!Loc::isLocType(type));
+  return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type));
 }
=20
 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode =
op,
                                const SymExpr *rhs, QualType type) {
-  assert(SymMgr.getType(lhs) =3D=3D SymMgr.getType(rhs));
+  assert(lhs && rhs);
+  assert(haveSameType(lhs->getType(Context), rhs->getType(Context)) =3D=3D=
 true);
   assert(!Loc::isLocType(type));
-  return nonloc::SymExprVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
+  return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
 }
=20
+NonLoc SValBuilder::makeNonLoc(const SymExpr *operand,
+                               QualType fromTy, QualType toTy) {
+  assert(operand);
+  assert(!Loc::isLocType(toTy));
+  return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
+}
=20
 SVal SValBuilder::convertToArrayIndex(SVal val) {
   if (val.isUnknownOrUndef())
@@ -69,6 +87,10 @@
   return evalCastFromNonLoc(cast<NonLoc>(val), ArrayIndexTy);
 }
=20
+nonloc::ConcreteInt SValBuilder::makeBoolVal(const CXXBoolLiteralExpr *boo=
lean){
+  return makeTruthVal(boolean->getValue());
+}
+
 DefinedOrUnknownSVal=20
 SValBuilder::getRegionValueSymbolVal(const TypedValueRegion* region) {
   QualType T =3D region->getValueType();
@@ -84,35 +106,46 @@
   return nonloc::SymbolVal(sym);
 }
=20
-DefinedOrUnknownSVal SValBuilder::getConjuredSymbolVal(const void *symbolT=
ag,
-                                                       const Expr *expr,
-                                                       unsigned count) {
+DefinedOrUnknownSVal
+SValBuilder::getConjuredSymbolVal(const void *symbolTag,
+                                  const Expr *expr,
+                                  const LocationContext *LCtx,
+                                  unsigned count) {
   QualType T =3D expr->getType();
+  return getConjuredSymbolVal(symbolTag, expr, LCtx, T, count);
+}
=20
-  if (!SymbolManager::canSymbolicate(T))
+DefinedOrUnknownSVal
+SValBuilder::getConjuredSymbolVal(const void *symbolTag,
+                                  const Expr *expr,
+                                  const LocationContext *LCtx,
+                                  QualType type,
+                                  unsigned count) {
+  if (!SymbolManager::canSymbolicate(type))
     return UnknownVal();
=20
-  SymbolRef sym =3D SymMgr.getConjuredSymbol(expr, count, symbolTag);
+  SymbolRef sym =3D SymMgr.getConjuredSymbol(expr, LCtx, type, count, symb=
olTag);
=20
-  if (Loc::isLocType(T))
+  if (Loc::isLocType(type))
     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
=20
   return nonloc::SymbolVal(sym);
 }
=20
-DefinedOrUnknownSVal SValBuilder::getConjuredSymbolVal(const void *symbolT=
ag,
-                                                       const Expr *expr,
-                                                       QualType type,
-                                                       unsigned count) {
- =20
+
+DefinedOrUnknownSVal
+SValBuilder::getConjuredSymbolVal(const Stmt *stmt,
+                                  const LocationContext *LCtx,
+                                  QualType type,
+                                  unsigned visitCount) {
   if (!SymbolManager::canSymbolicate(type))
     return UnknownVal();
=20
-  SymbolRef sym =3D SymMgr.getConjuredSymbol(expr, type, count, symbolTag);
-
+  SymbolRef sym =3D SymMgr.getConjuredSymbol(stmt, LCtx, type, visitCount);
+ =20
   if (Loc::isLocType(type))
     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
-
+ =20
   return nonloc::SymbolVal(sym);
 }
=20
@@ -155,14 +188,41 @@
                                          CanQualType locTy,
                                          const LocationContext *locContext=
) {
   const BlockTextRegion *BC =3D
-    MemMgr.getBlockTextRegion(block, locTy, locContext->getAnalysisContext=
());
+    MemMgr.getBlockTextRegion(block, locTy, locContext->getAnalysisDeclCon=
text());
   const BlockDataRegion *BD =3D MemMgr.getBlockDataRegion(BC, locContext);
   return loc::MemRegionVal(BD);
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-SVal SValBuilder::evalBinOp(const ProgramState *state, BinaryOperator::Opc=
ode op,
+SVal SValBuilder::makeGenericVal(ProgramStateRef State,
+                                     BinaryOperator::Opcode Op,
+                                     NonLoc LHS, NonLoc RHS,
+                                     QualType ResultTy) {
+  // If operands are tainted, create a symbol to ensure that we propagate =
taint.
+  if (State->isTainted(RHS) || State->isTainted(LHS)) {
+    const SymExpr *symLHS;
+    const SymExpr *symRHS;
+
+    if (const nonloc::ConcreteInt *rInt =3D dyn_cast<nonloc::ConcreteInt>(=
&RHS)) {
+      symLHS =3D LHS.getAsSymExpr();
+      return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
+    }
+
+    if (const nonloc::ConcreteInt *lInt =3D dyn_cast<nonloc::ConcreteInt>(=
&LHS)) {
+      symRHS =3D RHS.getAsSymExpr();
+      return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
+    }
+
+    symLHS =3D LHS.getAsSymExpr();
+    symRHS =3D RHS.getAsSymExpr();
+    return makeNonLoc(symLHS, Op, symRHS, ResultTy);
+  }
+  return UnknownVal();
+}
+
+
+SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode =
op,
                             SVal lhs, SVal rhs, QualType type) {
=20
   if (lhs.isUndef() || rhs.isUndef())
@@ -190,37 +250,50 @@
   return evalBinOpNN(state, op, cast<NonLoc>(lhs), cast<NonLoc>(rhs), type=
);
 }
=20
-DefinedOrUnknownSVal SValBuilder::evalEQ(const ProgramState *state,
+DefinedOrUnknownSVal SValBuilder::evalEQ(ProgramStateRef state,
                                          DefinedOrUnknownSVal lhs,
                                          DefinedOrUnknownSVal rhs) {
   return cast<DefinedOrUnknownSVal>(evalBinOp(state, BO_EQ, lhs, rhs,
                                               Context.IntTy));
 }
=20
+/// Recursively check if the pointer types are equal modulo const, volatil=
e,
+/// and restrict qualifiers. Assumes the input types are canonical.
+/// TODO: This is based off of code in SemaCast; can we reuse it.
+static bool haveSimilarTypes(ASTContext &Context, QualType T1,
+                                                  QualType T2) {
+  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
+    Qualifiers Quals1, Quals2;
+    T1 =3D Context.getUnqualifiedArrayType(T1, Quals1);
+    T2 =3D Context.getUnqualifiedArrayType(T2, Quals2);
+
+    // Make sure that non cvr-qualifiers the other qualifiers (e.g., addre=
ss
+    // spaces) are identical.
+    Quals1.removeCVRQualifiers();
+    Quals2.removeCVRQualifiers();
+    if (Quals1 !=3D Quals2)
+      return false;
+  }
+
+  if (T1 !=3D T2)
+    return false;
+
+  return true;
+}
+
 // FIXME: should rewrite according to the cast kind.
 SVal SValBuilder::evalCast(SVal val, QualType castTy, QualType originalTy)=
 {
+  castTy =3D Context.getCanonicalType(castTy);
+  originalTy =3D Context.getCanonicalType(originalTy);
   if (val.isUnknownOrUndef() || castTy =3D=3D originalTy)
     return val;
=20
   // For const casts, just propagate the value.
   if (!castTy->isVariableArrayType() && !originalTy->isVariableArrayType())
-    if (Context.hasSameUnqualifiedType(castTy, originalTy))
+    if (haveSimilarTypes(Context, Context.getPointerType(castTy),
+                                  Context.getPointerType(originalTy)))
       return val;
-
-  // Check for casts to real or complex numbers.  We don't handle these at=
 all
-  // right now.
-  if (castTy->isFloatingType() || castTy->isAnyComplexType())
-    return UnknownVal();
  =20
-  // Check for casts from integers to integers.
-  if (castTy->isIntegerType() && originalTy->isIntegerType()) {
-    if (isa<Loc>(val))
-      // This can be a cast to ObjC property of type int.
-      return evalCastFromLoc(cast<Loc>(val), castTy);
-    else
-      return evalCastFromNonLoc(cast<NonLoc>(val), castTy);
-  }
-
   // Check for casts from pointers to integers.
   if (castTy->isIntegerType() && Loc::isLocType(originalTy))
     return evalCastFromLoc(cast<Loc>(val), castTy);
@@ -235,7 +308,7 @@
       }
       return LV->getLoc();
     }
-    goto DispatchCast;
+    return dispatchCast(val, castTy);
   }
=20
   // Just pass through function and block pointers.
@@ -309,8 +382,5 @@
     return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
   }
=20
-DispatchCast:
-  // All other cases.
-  return isa<Loc>(val) ? evalCastFromLoc(cast<Loc>(val), castTy)
-                       : evalCastFromNonLoc(cast<NonLoc>(val), castTy);
+  return dispatchCast(val, castTy);
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/SVals.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SVals.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SVals.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -54,13 +54,16 @@
       return CTR->getDecl();
   }
=20
-  return NULL;
+  return 0;
 }
=20
-/// getAsLocSymbol - If this SVal is a location (subclasses Loc) and
-///  wraps a symbol, return that SymbolRef.  Otherwise return 0.
-// FIXME: should we consider SymbolRef wrapped in CodeTextRegion?
+/// \brief If this SVal is a location (subclasses Loc) and wraps a symbol,
+/// return that SymbolRef.  Otherwise return 0.
+///
+/// Implicit casts (ex: void* -> char*) can turn Symbolic region into Elem=
ent
+/// region. If that is the case, gets the underlining region.
 SymbolRef SVal::getAsLocSymbol() const {
+  // FIXME: should we consider SymbolRef wrapped in CodeTextRegion?
   if (const nonloc::LocAsInteger *X =3D dyn_cast<nonloc::LocAsInteger>(thi=
s))
     return X->getLoc().getAsLocSymbol();
=20
@@ -69,7 +72,7 @@
     if (const SymbolicRegion *SymR =3D dyn_cast<SymbolicRegion>(R))
       return SymR->getSymbol();
   }
-  return NULL;
+  return 0;
 }
=20
 /// Get the symbol in the SVal or its base region.
@@ -91,29 +94,34 @@
   return 0;
 }
=20
-/// getAsSymbol - If this Sval wraps a symbol return that SymbolRef.
+// TODO: The next 3 functions have to be simplified.
+
+/// \brief If this SVal wraps a symbol return that SymbolRef.
 ///  Otherwise return 0.
-// FIXME: should we consider SymbolRef wrapped in CodeTextRegion?
 SymbolRef SVal::getAsSymbol() const {
+  // FIXME: should we consider SymbolRef wrapped in CodeTextRegion?
   if (const nonloc::SymbolVal *X =3D dyn_cast<nonloc::SymbolVal>(this))
     return X->getSymbol();
=20
-  if (const nonloc::SymExprVal *X =3D dyn_cast<nonloc::SymExprVal>(this))
-    if (SymbolRef Y =3D dyn_cast<SymbolData>(X->getSymbolicExpression()))
-      return Y;
-
   return getAsLocSymbol();
 }
=20
 /// getAsSymbolicExpression - If this Sval wraps a symbolic expression then
 ///  return that expression.  Otherwise return NULL.
 const SymExpr *SVal::getAsSymbolicExpression() const {
-  if (const nonloc::SymExprVal *X =3D dyn_cast<nonloc::SymExprVal>(this))
-    return X->getSymbolicExpression();
+  if (const nonloc::SymbolVal *X =3D dyn_cast<nonloc::SymbolVal>(this))
+    return X->getSymbol();
=20
   return getAsSymbol();
 }
=20
+const SymExpr* SVal::getAsSymExpr() const {
+  const SymExpr* Sym =3D getAsSymbol();
+  if (!Sym)
+    Sym =3D getAsSymbolicExpression();
+  return Sym;
+}
+
 const MemRegion *SVal::getAsRegion() const {
   if (const loc::MemRegionVal *X =3D dyn_cast<loc::MemRegionVal>(this))
     return X->getRegion();
@@ -130,50 +138,6 @@
   return R ?  R->StripCasts() : NULL;
 }
=20
-bool SVal::symbol_iterator::operator=3D=3D(const symbol_iterator &X) const=
 {
-  return itr =3D=3D X.itr;
-}
-
-bool SVal::symbol_iterator::operator!=3D(const symbol_iterator &X) const {
-  return itr !=3D X.itr;
-}
-
-SVal::symbol_iterator::symbol_iterator(const SymExpr *SE) {
-  itr.push_back(SE);
-  while (!isa<SymbolData>(itr.back())) expand();
-}
-
-SVal::symbol_iterator &SVal::symbol_iterator::operator++() {
-  assert(!itr.empty() && "attempting to iterate on an 'end' iterator");
-  assert(isa<SymbolData>(itr.back()));
-  itr.pop_back();
-  if (!itr.empty())
-    while (!isa<SymbolData>(itr.back())) expand();
-  return *this;
-}
-
-SymbolRef SVal::symbol_iterator::operator*() {
-  assert(!itr.empty() && "attempting to dereference an 'end' iterator");
-  return cast<SymbolData>(itr.back());
-}
-
-void SVal::symbol_iterator::expand() {
-  const SymExpr *SE =3D itr.back();
-  itr.pop_back();
-
-  if (const SymIntExpr *SIE =3D dyn_cast<SymIntExpr>(SE)) {
-    itr.push_back(SIE->getLHS());
-    return;
-  }
-  else if (const SymSymExpr *SSE =3D dyn_cast<SymSymExpr>(SE)) {
-    itr.push_back(SSE->getLHS());
-    itr.push_back(SSE->getRHS());
-    return;
-  }
-
-  llvm_unreachable("unhandled expansion case");
-}
-
 const void *nonloc::LazyCompoundVal::getStore() const {
   return static_cast<const LazyCompoundValData*>(Data)->getStore();
 }
@@ -281,8 +245,6 @@
     case UndefinedKind:
       os << "Undefined";
       break;
-    default:
-      assert (false && "Invalid SVal.");
   }
 }
=20
@@ -298,13 +260,8 @@
          << C.getValue().getBitWidth() << 'b';
       break;
     }
-    case nonloc::SymbolValKind:
-      os << '$' << cast<nonloc::SymbolVal>(this)->getSymbol();
-      break;
-    case nonloc::SymExprValKind: {
-      const nonloc::SymExprVal& C =3D *cast<nonloc::SymExprVal>(this);
-      const SymExpr *SE =3D C.getSymbolicExpression();
-      os << SE;
+    case nonloc::SymbolValKind: {
+      os << cast<nonloc::SymbolVal>(this)->getSymbol();
       break;
     }
     case nonloc::LocAsIntegerKind: {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/SimpleConstraintManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleConstrain=
tManager.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleConstrain=
tManager.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -23,11 +23,9 @@
 SimpleConstraintManager::~SimpleConstraintManager() {}
=20
 bool SimpleConstraintManager::canReasonAbout(SVal X) const {
-  if (nonloc::SymExprVal *SymVal =3D dyn_cast<nonloc::SymExprVal>(&X)) {
-    const SymExpr *SE =3D SymVal->getSymbolicExpression();
-
-    if (isa<SymbolData>(SE))
-      return true;
+  nonloc::SymbolVal *SymVal =3D dyn_cast<nonloc::SymbolVal>(&X);
+  if (SymVal && SymVal->isExpression()) {
+    const SymExpr *SE =3D SymVal->getSymbol();
=20
     if (const SymIntExpr *SIE =3D dyn_cast<SymIntExpr>(SE)) {
       switch (SIE->getOpcode()) {
@@ -56,7 +54,7 @@
   return true;
 }
=20
-const ProgramState *SimpleConstraintManager::assume(const ProgramState *st=
ate,
+ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
                                                DefinedSVal Cond,
                                                bool Assumption) {
   if (isa<NonLoc>(Cond))
@@ -65,13 +63,13 @@
     return assume(state, cast<Loc>(Cond), Assumption);
 }
=20
-const ProgramState *SimpleConstraintManager::assume(const ProgramState *st=
ate, Loc cond,
+ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state, Loc=
 cond,
                                                bool assumption) {
   state =3D assumeAux(state, cond, assumption);
   return SU.processAssume(state, cond, assumption);
 }
=20
-const ProgramState *SimpleConstraintManager::assumeAux(const ProgramState =
*state,
+ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef state,
                                                   Loc Cond, bool Assumptio=
n) {
=20
   BasicValueFactory &BasicVals =3D state->getBasicVals();
@@ -113,7 +111,7 @@
   } // end switch
 }
=20
-const ProgramState *SimpleConstraintManager::assume(const ProgramState *st=
ate,
+ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
                                                NonLoc cond,
                                                bool assumption) {
   state =3D assumeAux(state, cond, assumption);
@@ -135,16 +133,29 @@
   }
 }
=20
-const ProgramState *SimpleConstraintManager::assumeAux(const ProgramState =
*state,
+
+ProgramStateRef SimpleConstraintManager::assumeAuxForSymbol(
+                                              ProgramStateRef State,
+                                              SymbolRef Sym,
+                                              bool Assumption) {
+  QualType T =3D  State->getSymbolManager().getType(Sym);
+  const llvm::APSInt &zero =3D State->getBasicVals().getValue(0, T);
+  if (Assumption)
+    return assumeSymNE(State, Sym, zero, zero);
+  else
+    return assumeSymEQ(State, Sym, zero, zero);
+}
+
+ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef state,
                                                   NonLoc Cond,
                                                   bool Assumption) {
=20
-  // We cannot reason about SymSymExprs,
-  // and can only reason about some SymIntExprs.
+  // We cannot reason about SymSymExprs, and can only reason about some
+  // SymIntExprs.
   if (!canReasonAbout(Cond)) {
-    // Just return the current state indicating that the path is feasible.
-    // This may be an over-approximation of what is possible.
-    return state;
+    // Just add the constraint to the expression without trying to simplif=
y.
+    SymbolRef sym =3D Cond.getAsSymExpr();
+    return assumeAuxForSymbol(state, sym, Assumption);
   }
=20
   BasicValueFactory &BasicVals =3D state->getBasicVals();
@@ -157,37 +168,33 @@
   case nonloc::SymbolValKind: {
     nonloc::SymbolVal& SV =3D cast<nonloc::SymbolVal>(Cond);
     SymbolRef sym =3D SV.getSymbol();
-    QualType T =3D  SymMgr.getType(sym);
-    const llvm::APSInt &zero =3D BasicVals.getValue(0, T);
-    if (Assumption)
-      return assumeSymNE(state, sym, zero, zero);
-    else
-      return assumeSymEQ(state, sym, zero, zero);
-  }
+    assert(sym);
=20
-  case nonloc::SymExprValKind: {
-    nonloc::SymExprVal V =3D cast<nonloc::SymExprVal>(Cond);
+    // Handle SymbolData.
+    if (!SV.isExpression()) {
+      return assumeAuxForSymbol(state, sym, Assumption);
=20
-    // For now, we only handle expressions whose RHS is an integer.
-    // All other expressions are assumed to be feasible.
-    const SymIntExpr *SE =3D dyn_cast<SymIntExpr>(V.getSymbolicExpression(=
));
-    if (!SE)
-      return state;
+    // Handle symbolic expression.
+    } else {
+      // We can only simplify expressions whose RHS is an integer.
+      const SymIntExpr *SE =3D dyn_cast<SymIntExpr>(sym);
+      if (!SE)
+        return assumeAuxForSymbol(state, sym, Assumption);
=20
-    BinaryOperator::Opcode op =3D SE->getOpcode();
-    // Implicitly compare non-comparison expressions to 0.
-    if (!BinaryOperator::isComparisonOp(op)) {
-      QualType T =3D SymMgr.getType(SE);
-      const llvm::APSInt &zero =3D BasicVals.getValue(0, T);
-      op =3D (Assumption ? BO_NE : BO_EQ);
-      return assumeSymRel(state, SE, op, zero);
+      BinaryOperator::Opcode op =3D SE->getOpcode();
+      // Implicitly compare non-comparison expressions to 0.
+      if (!BinaryOperator::isComparisonOp(op)) {
+        QualType T =3D SymMgr.getType(SE);
+        const llvm::APSInt &zero =3D BasicVals.getValue(0, T);
+        op =3D (Assumption ? BO_NE : BO_EQ);
+        return assumeSymRel(state, SE, op, zero);
+      }
+      // From here on out, op is the real comparison we'll be testing.
+      if (!Assumption)
+        op =3D NegateComparison(op);
+
+      return assumeSymRel(state, SE->getLHS(), op, SE->getRHS());
     }
-
-    // From here on out, op is the real comparison we'll be testing.
-    if (!Assumption)
-      op =3D NegateComparison(op);
- =20
-    return assumeSymRel(state, SE->getLHS(), op, SE->getRHS());
   }
=20
   case nonloc::ConcreteIntKind: {
@@ -202,55 +209,52 @@
   } // end switch
 }
=20
-const ProgramState *SimpleConstraintManager::assumeSymRel(const ProgramSta=
te *state,
+static llvm::APSInt computeAdjustment(const SymExpr *LHS,
+                                      SymbolRef &Sym) {
+  llvm::APSInt DefaultAdjustment;
+  DefaultAdjustment =3D 0;
+
+  // First check if the LHS is a simple symbol reference.
+  if (isa<SymbolData>(LHS))
+    return DefaultAdjustment;
+
+  // Next, see if it's a "($sym+constant1)" expression.
+  const SymIntExpr *SE =3D dyn_cast<SymIntExpr>(LHS);
+
+  // We cannot simplify "($sym1+$sym2)".
+  if (!SE)
+    return DefaultAdjustment;
+
+  // Get the constant out of the expression "($sym+constant1)" or
+  // "<expr>+constant1".
+  Sym =3D SE->getLHS();
+  switch (SE->getOpcode()) {
+  case BO_Add:
+    return SE->getRHS();
+  case BO_Sub:
+    return -SE->getRHS();
+  default:
+    // We cannot simplify non-additive operators.
+    return DefaultAdjustment;
+  }
+}
+
+ProgramStateRef SimpleConstraintManager::assumeSymRel(ProgramStateRef stat=
e,
                                                      const SymExpr *LHS,
                                                      BinaryOperator::Opcod=
e op,
                                                      const llvm::APSInt& I=
nt) {
   assert(BinaryOperator::isComparisonOp(op) &&
          "Non-comparison ops should be rewritten as comparisons to zero.");
=20
-   // We only handle simple comparisons of the form "$sym =3D=3D constant"
-   // or "($sym+constant1) =3D=3D constant2".
-   // The adjustment is "constant1" in the above expression. It's used to
-   // "slide" the solution range around for modular arithmetic. For exampl=
e,
-   // x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], =
which
-   // in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
-   // the subclasses of SimpleConstraintManager to handle the adjustment.
-   llvm::APSInt Adjustment;
-
-  // First check if the LHS is a simple symbol reference.
-  SymbolRef Sym =3D dyn_cast<SymbolData>(LHS);
-  if (Sym) {
-    Adjustment =3D 0;
-  } else {
-    // Next, see if it's a "($sym+constant1)" expression.
-    const SymIntExpr *SE =3D dyn_cast<SymIntExpr>(LHS);
-
-    // We don't handle "($sym1+$sym2)".
-    // Give up and assume the constraint is feasible.
-    if (!SE)
-      return state;
-
-    // We don't handle "(<expr>+constant1)".
-    // Give up and assume the constraint is feasible.
-    Sym =3D dyn_cast<SymbolData>(SE->getLHS());
-    if (!Sym)
-      return state;
-
-    // Get the constant out of the expression "($sym+constant1)".
-    switch (SE->getOpcode()) {
-    case BO_Add:
-      Adjustment =3D SE->getRHS();
-      break;
-    case BO_Sub:
-      Adjustment =3D -SE->getRHS();
-      break;
-    default:
-      // We don't handle non-additive operators.
-      // Give up and assume the constraint is feasible.
-      return state;
-    }
-  }
+  // We only handle simple comparisons of the form "$sym =3D=3D constant"
+  // or "($sym+constant1) =3D=3D constant2".
+  // The adjustment is "constant1" in the above expression. It's used to
+  // "slide" the solution range around for modular arithmetic. For example,
+  // x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], w=
hich
+  // in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
+  // the subclasses of SimpleConstraintManager to handle the adjustment.
+  SymbolRef Sym =3D LHS;
+  llvm::APSInt Adjustment =3D computeAdjustment(LHS, Sym);
=20
   // FIXME: This next section is a hack. It silently converts the integers=
 to
   // be of the same type as the symbol, which is not always correct. Reall=
y the
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/SimpleConstraintManager.h
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleConstrain=
tManager.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleConstrain=
tManager.h	Tue Apr 17 11:51:51 2012 +0300
@@ -31,16 +31,14 @@
   // Common implementation for the interface provided by ConstraintManager.
   //=3D=3D=3D-------------------------------------------------------------=
-----=3D=3D=3D//
=20
-  bool canReasonAbout(SVal X) const;
-
-  const ProgramState *assume(const ProgramState *state, DefinedSVal Cond,
+  ProgramStateRef assume(ProgramStateRef state, DefinedSVal Cond,
                         bool Assumption);
=20
-  const ProgramState *assume(const ProgramState *state, Loc Cond, bool Ass=
umption);
+  ProgramStateRef assume(ProgramStateRef state, Loc Cond, bool Assumption);
=20
-  const ProgramState *assume(const ProgramState *state, NonLoc Cond, bool =
Assumption);
+  ProgramStateRef assume(ProgramStateRef state, NonLoc Cond, bool Assumpti=
on);
=20
-  const ProgramState *assumeSymRel(const ProgramState *state,
+  ProgramStateRef assumeSymRel(ProgramStateRef state,
                               const SymExpr *LHS,
                               BinaryOperator::Opcode op,
                               const llvm::APSInt& Int);
@@ -53,27 +51,27 @@
=20
   // Each of these is of the form "$sym+Adj <> V", where "<>" is the compa=
rison
   // operation for the method being invoked.
-  virtual const ProgramState *assumeSymNE(const ProgramState *state, Symbo=
lRef sym,
+  virtual ProgramStateRef assumeSymNE(ProgramStateRef state, SymbolRef sym,
                                      const llvm::APSInt& V,
                                      const llvm::APSInt& Adjustment) =3D 0;
=20
-  virtual const ProgramState *assumeSymEQ(const ProgramState *state, Symbo=
lRef sym,
+  virtual ProgramStateRef assumeSymEQ(ProgramStateRef state, SymbolRef sym,
                                      const llvm::APSInt& V,
                                      const llvm::APSInt& Adjustment) =3D 0;
=20
-  virtual const ProgramState *assumeSymLT(const ProgramState *state, Symbo=
lRef sym,
+  virtual ProgramStateRef assumeSymLT(ProgramStateRef state, SymbolRef sym,
                                      const llvm::APSInt& V,
                                      const llvm::APSInt& Adjustment) =3D 0;
=20
-  virtual const ProgramState *assumeSymGT(const ProgramState *state, Symbo=
lRef sym,
+  virtual ProgramStateRef assumeSymGT(ProgramStateRef state, SymbolRef sym,
                                      const llvm::APSInt& V,
                                      const llvm::APSInt& Adjustment) =3D 0;
=20
-  virtual const ProgramState *assumeSymLE(const ProgramState *state, Symbo=
lRef sym,
+  virtual ProgramStateRef assumeSymLE(ProgramStateRef state, SymbolRef sym,
                                      const llvm::APSInt& V,
                                      const llvm::APSInt& Adjustment) =3D 0;
=20
-  virtual const ProgramState *assumeSymGE(const ProgramState *state, Symbo=
lRef sym,
+  virtual ProgramStateRef assumeSymGE(ProgramStateRef state, SymbolRef sym,
                                      const llvm::APSInt& V,
                                      const llvm::APSInt& Adjustment) =3D 0;
=20
@@ -81,9 +79,19 @@
   // Internal implementation.
   //=3D=3D=3D-------------------------------------------------------------=
-----=3D=3D=3D//
=20
-  const ProgramState *assumeAux(const ProgramState *state, Loc Cond,bool A=
ssumption);
+  bool canReasonAbout(SVal X) const;
=20
-  const ProgramState *assumeAux(const ProgramState *state, NonLoc Cond, bo=
ol Assumption);
+  ProgramStateRef assumeAux(ProgramStateRef state,
+                                Loc Cond,
+                                bool Assumption);
+
+  ProgramStateRef assumeAux(ProgramStateRef state,
+                                NonLoc Cond,
+                                bool Assumption);
+
+  ProgramStateRef assumeAuxForSymbol(ProgramStateRef State,
+                                         SymbolRef Sym,
+                                         bool Assumption);
 };
=20
 } // end GR namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/SimpleSValBuilder.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleSValBuild=
er.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SimpleSValBuild=
er.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -20,6 +20,7 @@
 namespace {
 class SimpleSValBuilder : public SValBuilder {
 protected:
+  virtual SVal dispatchCast(SVal val, QualType castTy);
   virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy);
   virtual SVal evalCastFromLoc(Loc val, QualType castTy);
=20
@@ -31,16 +32,16 @@
=20
   virtual SVal evalMinus(NonLoc val);
   virtual SVal evalComplement(NonLoc val);
-  virtual SVal evalBinOpNN(const ProgramState *state, BinaryOperator::Opco=
de op,
+  virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode o=
p,
                            NonLoc lhs, NonLoc rhs, QualType resultTy);
-  virtual SVal evalBinOpLL(const ProgramState *state, BinaryOperator::Opco=
de op,
+  virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode o=
p,
                            Loc lhs, Loc rhs, QualType resultTy);
-  virtual SVal evalBinOpLN(const ProgramState *state, BinaryOperator::Opco=
de op,
+  virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode o=
p,
                            Loc lhs, NonLoc rhs, QualType resultTy);
=20
   /// getKnownValue - evaluates a given SVal. If the SVal has only one pos=
sible
   ///  (integer) value, that value is returned. Otherwise, returns NULL.
-  virtual const llvm::APSInt *getKnownValue(const ProgramState *state, SVa=
l V);
+  virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V);
  =20
   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
                      const llvm::APSInt &RHS, QualType resultTy);
@@ -57,6 +58,12 @@
 // Transfer function for Casts.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
+  assert(isa<Loc>(&Val) || isa<NonLoc>(&Val));
+  return isa<Loc>(Val) ? evalCastFromLoc(cast<Loc>(Val), CastTy)
+                       : evalCastFromNonLoc(cast<NonLoc>(Val), CastTy);
+}
+
 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
=20
   bool isLocType =3D Loc::isLocType(castTy);
@@ -74,25 +81,27 @@
=20
   if (const SymExpr *se =3D val.getAsSymbolicExpression()) {
     QualType T =3D Context.getCanonicalType(se->getType(Context));
-    if (T =3D=3D Context.getCanonicalType(castTy))
-      return val;
-   =20
+    // If types are the same or both are integers, ignore the cast.
     // FIXME: Remove this hack when we support symbolic truncation/extensi=
on.
     // HACK: If both castTy and T are integers, ignore the cast.  This is
     // not a permanent solution.  Eventually we want to precisely handle
     // extension/truncation of symbolic integers.  This prevents us from l=
osing
     // precision when we assign 'x =3D y' and 'y' is symbolic and x and y =
are
     // different integer types.
-    if (T->isIntegerType() && castTy->isIntegerType())
+   if (haveSameType(T, castTy))
       return val;
=20
+    if (!isLocType)
+      return makeNonLoc(se, T, castTy);
     return UnknownVal();
   }
=20
+  // If value is a non integer constant, produce unknown.
   if (!isa<nonloc::ConcreteInt>(val))
     return UnknownVal();
=20
-  // Only handle casts from integers to integers.
+  // Only handle casts from integers to integers - if val is an integer co=
nstant
+  // being cast to a non integer type, produce unknown.
   if (!isLocType && !castTy->isIntegerType())
     return UnknownVal();
=20
@@ -259,18 +268,15 @@
   // Idempotent ops (like a*1) can still change the type of an expression.
   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
   // dirty work.
-  if (isIdempotent) {
-    if (SymbolRef LHSSym =3D dyn_cast<SymbolData>(LHS))
-      return evalCastFromNonLoc(nonloc::SymbolVal(LHSSym), resultTy);
-    return evalCastFromNonLoc(nonloc::SymExprVal(LHS), resultTy);
-  }
+  if (isIdempotent)
+      return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
=20
   // If we reach this point, the expression cannot be simplified.
-  // Make a SymExprVal for the entire thing.
+  // Make a SymbolVal for the entire expression.
   return makeNonLoc(LHS, op, RHS, resultTy);
 }
=20
-SVal SimpleSValBuilder::evalBinOpNN(const ProgramState *state,
+SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
                                   BinaryOperator::Opcode op,
                                   NonLoc lhs, NonLoc rhs,
                                   QualType resultTy)  {
@@ -298,7 +304,7 @@
   while (1) {
     switch (lhs.getSubKind()) {
     default:
-      return UnknownVal();
+      return makeGenericVal(state, op, lhs, rhs, resultTy);
     case nonloc::LocAsIntegerKind: {
       Loc lhsL =3D cast<nonloc::LocAsInteger>(lhs).getLoc();
       switch (rhs.getSubKind()) {
@@ -321,94 +327,10 @@
               return makeTruthVal(true, resultTy);
             default:
               // This case also handles pointer arithmetic.
-              return UnknownVal();
+              return makeGenericVal(state, op, lhs, rhs, resultTy);
           }
       }
     }
-    case nonloc::SymExprValKind: {
-      nonloc::SymExprVal *selhs =3D cast<nonloc::SymExprVal>(&lhs);
-
-      // Only handle LHS of the form "$sym op constant", at least for now.
-      const SymIntExpr *symIntExpr =3D
-        dyn_cast<SymIntExpr>(selhs->getSymbolicExpression());
-
-      if (!symIntExpr)
-        return UnknownVal();
-
-      // Is this a logical not? (!x is represented as x =3D=3D 0.)
-      if (op =3D=3D BO_EQ && rhs.isZeroConstant()) {
-        // We know how to negate certain expressions. Simplify them here.
-
-        BinaryOperator::Opcode opc =3D symIntExpr->getOpcode();
-        switch (opc) {
-        default:
-          // We don't know how to negate this operation.
-          // Just handle it as if it were a normal comparison to 0.
-          break;
-        case BO_LAnd:
-        case BO_LOr:
-          llvm_unreachable("Logical operators handled by branching logic."=
);
-        case BO_Assign:
-        case BO_MulAssign:
-        case BO_DivAssign:
-        case BO_RemAssign:
-        case BO_AddAssign:
-        case BO_SubAssign:
-        case BO_ShlAssign:
-        case BO_ShrAssign:
-        case BO_AndAssign:
-        case BO_XorAssign:
-        case BO_OrAssign:
-        case BO_Comma:
-          llvm_unreachable("'=3D' and ',' operators handled by ExprEngine.=
");
-        case BO_PtrMemD:
-        case BO_PtrMemI:
-          llvm_unreachable("Pointer arithmetic not handled here.");
-        case BO_LT:
-        case BO_GT:
-        case BO_LE:
-        case BO_GE:
-        case BO_EQ:
-        case BO_NE:
-          // Negate the comparison and make a value.
-          opc =3D NegateComparison(opc);
-          assert(symIntExpr->getType(Context) =3D=3D resultTy);
-          return makeNonLoc(symIntExpr->getLHS(), opc,
-                                   symIntExpr->getRHS(), resultTy);
-        }
-      }
-
-      // For now, only handle expressions whose RHS is a constant.
-      const nonloc::ConcreteInt *rhsInt =3D dyn_cast<nonloc::ConcreteInt>(=
&rhs);
-      if (!rhsInt)
-        return UnknownVal();
-
-      // If both the LHS and the current expression are additive,
-      // fold their constants.
-      if (BinaryOperator::isAdditiveOp(op)) {
-        BinaryOperator::Opcode lop =3D symIntExpr->getOpcode();
-        if (BinaryOperator::isAdditiveOp(lop)) {
-          // resultTy may not be the best type to convert to, but it's
-          // probably the best choice in expressions with mixed type
-          // (such as x+1U+2LL). The rules for implicit conversions should
-          // choose a reasonable type to preserve the expression, and will
-          // at least match how the value is going to be used.
-          const llvm::APSInt &first =3D
-            BasicVals.Convert(resultTy, symIntExpr->getRHS());
-          const llvm::APSInt &second =3D
-            BasicVals.Convert(resultTy, rhsInt->getValue());
-          const llvm::APSInt *newRHS;
-          if (lop =3D=3D op)
-            newRHS =3D BasicVals.evalAPSInt(BO_Add, first, second);
-          else
-            newRHS =3D BasicVals.evalAPSInt(BO_Sub, first, second);
-          return MakeSymIntVal(symIntExpr->getLHS(), lop, *newRHS, resultT=
y);
-        }
-      }
-
-      // Otherwise, make a SymExprVal out of the expression.
-      return MakeSymIntVal(symIntExpr, op, rhsInt->getValue(), resultTy);
-    }
     case nonloc::ConcreteIntKind: {
       const nonloc::ConcreteInt& lhsInt =3D cast<nonloc::ConcreteInt>(lhs);
=20
@@ -467,76 +389,165 @@
             if (lhsValue =3D=3D 0)
               // At this point lhs and rhs have been swapped.
               return rhs;
-            return UnknownVal();
+            return makeGenericVal(state, op, rhs, lhs, resultTy);
           default:
-            return UnknownVal();
+            return makeGenericVal(state, op, rhs, lhs, resultTy);
         }
       }
     }
     case nonloc::SymbolValKind: {
-      nonloc::SymbolVal *slhs =3D cast<nonloc::SymbolVal>(&lhs);
-      SymbolRef Sym =3D slhs->getSymbol();
-      QualType lhsType =3D Sym->getType(Context);
+      nonloc::SymbolVal *selhs =3D cast<nonloc::SymbolVal>(&lhs);
=20
-      // The conversion type is usually the result type, but not in the ca=
se
-      // of relational expressions.
-      QualType conversionType =3D resultTy;
-      if (BinaryOperator::isRelationalOp(op))
-        conversionType =3D lhsType;
+      // LHS is a symbolic expression.
+      if (selhs->isExpression()) {
=20
-      // Does the symbol simplify to a constant?  If so, "fold" the consta=
nt
-      // by setting 'lhs' to a ConcreteInt and try again.
-      if (lhsType->isIntegerType())
-        if (const llvm::APSInt *Constant =3D state->getSymVal(Sym)) {
-          // The symbol evaluates to a constant. If necessary, promote the
-          // folded constant (LHS) to the result type.
-          const llvm::APSInt &lhs_I =3D BasicVals.Convert(conversionType,
-                                                        *Constant);
-          lhs =3D nonloc::ConcreteInt(lhs_I);
-         =20
-          // Also promote the RHS (if necessary).
+        // Only handle LHS of the form "$sym op constant", at least for no=
w.
+        const SymIntExpr *symIntExpr =3D
+            dyn_cast<SymIntExpr>(selhs->getSymbol());
=20
-          // For shifts, it is not necessary to promote the RHS.
-          if (BinaryOperator::isShiftOp(op))
-            continue;
-         =20
-          // Other operators: do an implicit conversion.  This shouldn't be
-          // necessary once we support truncation/extension of symbolic va=
lues.
-          if (nonloc::ConcreteInt *rhs_I =3D dyn_cast<nonloc::ConcreteInt>=
(&rhs)){
-            rhs =3D nonloc::ConcreteInt(BasicVals.Convert(conversionType,
-                                                        rhs_I->getValue())=
);
+        if (!symIntExpr)
+          return makeGenericVal(state, op, lhs, rhs, resultTy);
+
+        // Is this a logical not? (!x is represented as x =3D=3D 0.)
+        if (op =3D=3D BO_EQ && rhs.isZeroConstant()) {
+          // We know how to negate certain expressions. Simplify them here.
+
+          BinaryOperator::Opcode opc =3D symIntExpr->getOpcode();
+          switch (opc) {
+          default:
+            // We don't know how to negate this operation.
+            // Just handle it as if it were a normal comparison to 0.
+            break;
+          case BO_LAnd:
+          case BO_LOr:
+            llvm_unreachable("Logical operators handled by branching logic=
.");
+          case BO_Assign:
+          case BO_MulAssign:
+          case BO_DivAssign:
+          case BO_RemAssign:
+          case BO_AddAssign:
+          case BO_SubAssign:
+          case BO_ShlAssign:
+          case BO_ShrAssign:
+          case BO_AndAssign:
+          case BO_XorAssign:
+          case BO_OrAssign:
+          case BO_Comma:
+            llvm_unreachable("'=3D' and ',' operators handled by ExprEngin=
e.");
+          case BO_PtrMemD:
+          case BO_PtrMemI:
+            llvm_unreachable("Pointer arithmetic not handled here.");
+          case BO_LT:
+          case BO_GT:
+          case BO_LE:
+          case BO_GE:
+          case BO_EQ:
+          case BO_NE:
+            // Negate the comparison and make a value.
+            opc =3D NegateComparison(opc);
+            assert(symIntExpr->getType(Context) =3D=3D resultTy);
+            return makeNonLoc(symIntExpr->getLHS(), opc,
+                symIntExpr->getRHS(), resultTy);
           }
-         =20
-          continue;
         }
=20
-      // Is the RHS a symbol we can simplify?
-      if (const nonloc::SymbolVal *srhs =3D dyn_cast<nonloc::SymbolVal>(&r=
hs)) {
-        SymbolRef RSym =3D srhs->getSymbol();
-        if (RSym->getType(Context)->isIntegerType()) {
-          if (const llvm::APSInt *Constant =3D state->getSymVal(RSym)) {
-            // The symbol evaluates to a constant.
-            const llvm::APSInt &rhs_I =3D BasicVals.Convert(conversionType,
-                                                          *Constant);
-            rhs =3D nonloc::ConcreteInt(rhs_I);
+        // For now, only handle expressions whose RHS is a constant.
+        const nonloc::ConcreteInt *rhsInt =3D dyn_cast<nonloc::ConcreteInt=
>(&rhs);
+        if (!rhsInt)
+          return makeGenericVal(state, op, lhs, rhs, resultTy);
+
+        // If both the LHS and the current expression are additive,
+        // fold their constants.
+        if (BinaryOperator::isAdditiveOp(op)) {
+          BinaryOperator::Opcode lop =3D symIntExpr->getOpcode();
+          if (BinaryOperator::isAdditiveOp(lop)) {
+            // resultTy may not be the best type to convert to, but it's
+            // probably the best choice in expressions with mixed type
+            // (such as x+1U+2LL). The rules for implicit conversions shou=
ld
+            // choose a reasonable type to preserve the expression, and wi=
ll
+            // at least match how the value is going to be used.
+            const llvm::APSInt &first =3D
+                BasicVals.Convert(resultTy, symIntExpr->getRHS());
+            const llvm::APSInt &second =3D
+                BasicVals.Convert(resultTy, rhsInt->getValue());
+            const llvm::APSInt *newRHS;
+            if (lop =3D=3D op)
+              newRHS =3D BasicVals.evalAPSInt(BO_Add, first, second);
+            else
+              newRHS =3D BasicVals.evalAPSInt(BO_Sub, first, second);
+            return MakeSymIntVal(symIntExpr->getLHS(), lop, *newRHS, resul=
tTy);
           }
         }
+
+        // Otherwise, make a SymbolVal out of the expression.
+        return MakeSymIntVal(symIntExpr, op, rhsInt->getValue(), resultTy);
+
+      // LHS is a simple symbol (not a symbolic expression).
+      } else {
+        nonloc::SymbolVal *slhs =3D cast<nonloc::SymbolVal>(&lhs);
+        SymbolRef Sym =3D slhs->getSymbol();
+        QualType lhsType =3D Sym->getType(Context);
+
+        // The conversion type is usually the result type, but not in the =
case
+        // of relational expressions.
+        QualType conversionType =3D resultTy;
+        if (BinaryOperator::isRelationalOp(op))
+          conversionType =3D lhsType;
+
+        // Does the symbol simplify to a constant?  If so, "fold" the cons=
tant
+        // by setting 'lhs' to a ConcreteInt and try again.
+        if (lhsType->isIntegerType())
+          if (const llvm::APSInt *Constant =3D state->getSymVal(Sym)) {
+            // The symbol evaluates to a constant. If necessary, promote t=
he
+            // folded constant (LHS) to the result type.
+            const llvm::APSInt &lhs_I =3D BasicVals.Convert(conversionType,
+                *Constant);
+            lhs =3D nonloc::ConcreteInt(lhs_I);
+
+            // Also promote the RHS (if necessary).
+
+            // For shifts, it is not necessary to promote the RHS.
+            if (BinaryOperator::isShiftOp(op))
+              continue;
+
+            // Other operators: do an implicit conversion.  This shouldn't=
 be
+            // necessary once we support truncation/extension of symbolic =
values.
+            if (nonloc::ConcreteInt *rhs_I =3D dyn_cast<nonloc::ConcreteIn=
t>(&rhs)){
+              rhs =3D nonloc::ConcreteInt(BasicVals.Convert(conversionType,
+                  rhs_I->getValue()));
+            }
+
+            continue;
+          }
+
+        // Is the RHS a symbol we can simplify?
+        if (const nonloc::SymbolVal *srhs =3D dyn_cast<nonloc::SymbolVal>(=
&rhs)) {
+          SymbolRef RSym =3D srhs->getSymbol();
+          if (RSym->getType(Context)->isIntegerType()) {
+            if (const llvm::APSInt *Constant =3D state->getSymVal(RSym)) {
+              // The symbol evaluates to a constant.
+              const llvm::APSInt &rhs_I =3D BasicVals.Convert(conversionTy=
pe,
+                  *Constant);
+              rhs =3D nonloc::ConcreteInt(rhs_I);
+            }
+          }
+        }
+
+        if (isa<nonloc::ConcreteInt>(rhs)) {
+          return MakeSymIntVal(slhs->getSymbol(), op,
+              cast<nonloc::ConcreteInt>(rhs).getValue(),
+              resultTy);
+        }
+
+        return makeGenericVal(state, op, lhs, rhs, resultTy);
       }
-
-      if (isa<nonloc::ConcreteInt>(rhs)) {
-        return MakeSymIntVal(slhs->getSymbol(), op,
-                             cast<nonloc::ConcreteInt>(rhs).getValue(),
-                             resultTy);
-      }
-
-      return UnknownVal();
     }
     }
   }
 }
=20
 // FIXME: all this logic will change if/when we have MemRegion::getLocatio=
n().
-SVal SimpleSValBuilder::evalBinOpLL(const ProgramState *state,
+SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
                                   BinaryOperator::Opcode op,
                                   Loc lhs, Loc rhs,
                                   QualType resultTy) {
@@ -703,6 +714,24 @@
=20
     // The two regions are from the same base region. See if they're both a
     // type of region we know how to compare.
+    const MemSpaceRegion *LeftMS =3D LeftBase->getMemorySpace();
+    const MemSpaceRegion *RightMS =3D RightBase->getMemorySpace();
+
+    // Heuristic: assume that no symbolic region (whose memory space is
+    // unknown) is on the stack.
+    // FIXME: we should be able to be more precise once we can do better
+    // aliasing constraints for symbolic regions, but this is a reasonable,
+    // albeit unsound, assumption that holds most of the time.
+    if (isa<StackSpaceRegion>(LeftMS) ^ isa<StackSpaceRegion>(RightMS)) {
+      switch (op) {
+        default:
+          break;
+        case BO_EQ:
+          return makeTruthVal(false, resultTy);
+        case BO_NE:
+          return makeTruthVal(true, resultTy);
+      }
+    }
=20
     // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
     // ElementRegion path and the FieldRegion path below should be unified.
@@ -831,7 +860,7 @@
   }
 }
=20
-SVal SimpleSValBuilder::evalBinOpLN(const ProgramState *state,
+SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
                                   BinaryOperator::Opcode op,
                                   Loc lhs, NonLoc rhs, QualType resultTy) {
  =20
@@ -925,7 +954,7 @@
   return UnknownVal(); =20
 }
=20
-const llvm::APSInt *SimpleSValBuilder::getKnownValue(const ProgramState *s=
tate,
+const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
                                                    SVal V) {
   if (V.isUnknownOrUndef())
     return NULL;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/Store.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Store.cpp	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/Store.cpp	Tue A=
pr 17 11:51:51 2012 +0300
@@ -14,6 +14,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/AST/CharUnits.h"
+#include "clang/AST/DeclObjC.h"
=20
 using namespace clang;
 using namespace ento;
@@ -22,8 +23,9 @@
   : svalBuilder(stateMgr.getSValBuilder()), StateMgr(stateMgr),
     MRMgr(svalBuilder.getRegionManager()), Ctx(stateMgr.getContext()) {}
=20
-StoreRef StoreManager::enterStackFrame(const ProgramState *state,
-                                       const StackFrameContext *frame) {
+StoreRef StoreManager::enterStackFrame(ProgramStateRef state,
+                                       const LocationContext *callerCtx,
+                                       const StackFrameContext *calleeCtx)=
 {
   return StoreRef(state->getStore(), *this);
 }
=20
@@ -101,8 +103,10 @@
     case MemRegion::StackArgumentsSpaceRegionKind:
     case MemRegion::HeapSpaceRegionKind:
     case MemRegion::UnknownSpaceRegionKind:
-    case MemRegion::NonStaticGlobalSpaceRegionKind:
-    case MemRegion::StaticGlobalSpaceRegionKind: {
+    case MemRegion::StaticGlobalSpaceRegionKind:
+    case MemRegion::GlobalInternalSpaceRegionKind:
+    case MemRegion::GlobalSystemSpaceRegionKind:
+    case MemRegion::GlobalImmutableSpaceRegionKind: {
       llvm_unreachable("Invalid region cast");
     }
=20
@@ -116,6 +120,7 @@
     case MemRegion::CompoundLiteralRegionKind:
     case MemRegion::FieldRegionKind:
     case MemRegion::ObjCIvarRegionKind:
+    case MemRegion::ObjCStringRegionKind:
     case MemRegion::VarRegionKind:
     case MemRegion::CXXTempObjectRegionKind:
     case MemRegion::CXXBaseObjectRegionKind:
@@ -212,7 +217,7 @@
 SVal StoreManager::CastRetrievedVal(SVal V, const TypedValueRegion *R,
                                     QualType castTy, bool performTestOnly)=
 {
  =20
-  if (castTy.isNull())
+  if (castTy.isNull() || V.isUnknownOrUndef())
     return V;
  =20
   ASTContext &Ctx =3D svalBuilder.getContext();
@@ -227,12 +232,7 @@
     return V;
   }
  =20
-  if (const Loc *L =3D dyn_cast<Loc>(&V))
-    return svalBuilder.evalCastFromLoc(*L, castTy);
-  else if (const NonLoc *NL =3D dyn_cast<NonLoc>(&V))
-    return svalBuilder.evalCastFromNonLoc(*NL, castTy);
- =20
-  return V;
+  return svalBuilder.dispatchCast(V, castTy);
 }
=20
 SVal StoreManager::getLValueFieldOrIvar(const Decl *D, SVal Base) {
@@ -270,6 +270,10 @@
   return loc::MemRegionVal(MRMgr.getFieldRegion(cast<FieldDecl>(D), BaseR)=
);
 }
=20
+SVal StoreManager::getLValueIvar(const ObjCIvarDecl *decl, SVal base) {
+  return getLValueFieldOrIvar(decl, base);
+}
+
 SVal StoreManager::getLValueElement(QualType elementType, NonLoc Offset,=20
                                     SVal Base) {
=20
@@ -336,3 +340,23 @@
=20
 StoreManager::BindingsHandler::~BindingsHandler() {}
=20
+bool StoreManager::FindUniqueBinding::HandleBinding(StoreManager& SMgr,
+                                                    Store store,
+                                                    const MemRegion* R,
+                                                    SVal val) {
+  SymbolRef SymV =3D val.getAsLocSymbol();
+  if (!SymV || SymV !=3D Sym)
+    return true;
+
+  if (Binding) {
+    First =3D false;
+    return false;
+  }
+  else
+    Binding =3D R;
+
+  return true;
+}
+
+void SubRegionMap::anchor() { }
+void SubRegionMap::Visitor::anchor() { }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/SymbolManager.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SymbolManager.c=
pp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/SymbolManager.c=
pp	Tue Apr 17 11:51:51 2012 +0300
@@ -21,6 +21,8 @@
 using namespace clang;
 using namespace ento;
=20
+void SymExpr::anchor() { }
+
 void SymExpr::dump() const {
   dumpToStream(llvm::errs());
 }
@@ -57,6 +59,15 @@
   if (getRHS().isUnsigned()) os << 'U';
 }
=20
+void IntSymExpr::dumpToStream(raw_ostream &os) const {
+  os << ' ' << getLHS().getZExtValue();
+  if (getLHS().isUnsigned()) os << 'U';
+  print(os, getOpcode());
+  os << '(';
+  getRHS()->dumpToStream(os);
+  os << ") ";
+}
+
 void SymSymExpr::dumpToStream(raw_ostream &os) const {
   os << '(';
   getLHS()->dumpToStream(os);
@@ -66,6 +77,12 @@
   os << ')';
 }
=20
+void SymbolCast::dumpToStream(raw_ostream &os) const {
+  os << '(' << ToTy.getAsString() << ") (";
+  Operand->dumpToStream(os);
+  os << ')';
+}
+
 void SymbolConjured::dumpToStream(raw_ostream &os) const {
   os << "conj_$" << getSymbolID() << '{' << T.getAsString() << '}';
 }
@@ -84,10 +101,69 @@
      << getRegion() << ',' << T.getAsString() << '}';
 }
=20
+void SymbolData::anchor() { }
+
 void SymbolRegionValue::dumpToStream(raw_ostream &os) const {
   os << "reg_$" << getSymbolID() << "<" << R << ">";
 }
=20
+bool SymExpr::symbol_iterator::operator=3D=3D(const symbol_iterator &X) co=
nst {
+  return itr =3D=3D X.itr;
+}
+
+bool SymExpr::symbol_iterator::operator!=3D(const symbol_iterator &X) cons=
t {
+  return itr !=3D X.itr;
+}
+
+SymExpr::symbol_iterator::symbol_iterator(const SymExpr *SE) {
+  itr.push_back(SE);
+  while (!isa<SymbolData>(itr.back())) expand();
+}
+
+SymExpr::symbol_iterator &SymExpr::symbol_iterator::operator++() {
+  assert(!itr.empty() && "attempting to iterate on an 'end' iterator");
+  assert(isa<SymbolData>(itr.back()));
+  itr.pop_back();
+  if (!itr.empty())
+    while (!isa<SymbolData>(itr.back())) expand();
+  return *this;
+}
+
+SymbolRef SymExpr::symbol_iterator::operator*() {
+  assert(!itr.empty() && "attempting to dereference an 'end' iterator");
+  return cast<SymbolData>(itr.back());
+}
+
+void SymExpr::symbol_iterator::expand() {
+  const SymExpr *SE =3D itr.back();
+  itr.pop_back();
+
+  switch (SE->getKind()) {
+    case SymExpr::RegionValueKind:
+    case SymExpr::ConjuredKind:
+    case SymExpr::DerivedKind:
+    case SymExpr::ExtentKind:
+    case SymExpr::MetadataKind:
+      return;
+    case SymExpr::CastSymbolKind:
+      itr.push_back(cast<SymbolCast>(SE)->getOperand());
+      return;
+    case SymExpr::SymIntKind:
+      itr.push_back(cast<SymIntExpr>(SE)->getLHS());
+      return;
+    case SymExpr::IntSymKind:
+      itr.push_back(cast<IntSymExpr>(SE)->getRHS());
+      return;
+    case SymExpr::SymSymKind: {
+      const SymSymExpr *x =3D cast<SymSymExpr>(SE);
+      itr.push_back(x->getLHS());
+      itr.push_back(x->getRHS());
+      return;
+    }
+  }
+  llvm_unreachable("unhandled expansion case");
+}
+
 const SymbolRegionValue*
 SymbolManager::getRegionValueSymbol(const TypedValueRegion* R) {
   llvm::FoldingSetNodeID profile;
@@ -105,16 +181,17 @@
 }
=20
 const SymbolConjured*
-SymbolManager::getConjuredSymbol(const Stmt *E, QualType T, unsigned Count,
+SymbolManager::getConjuredSymbol(const Stmt *E, const LocationContext *LCt=
x,
+                                 QualType T, unsigned Count,
                                  const void *SymbolTag) {
=20
   llvm::FoldingSetNodeID profile;
-  SymbolConjured::Profile(profile, E, T, Count, SymbolTag);
+  SymbolConjured::Profile(profile, E, T, Count, LCtx, SymbolTag);
   void *InsertPos;
   SymExpr *SD =3D DataSet.FindNodeOrInsertPos(profile, InsertPos);
   if (!SD) {
     SD =3D (SymExpr*) BPAlloc.Allocate<SymbolConjured>();
-    new (SD) SymbolConjured(SymbolCounter, E, T, Count, SymbolTag);
+    new (SD) SymbolConjured(SymbolCounter, E, LCtx, T, Count, SymbolTag);
     DataSet.InsertNode(SD, InsertPos);
     ++SymbolCounter;
   }
@@ -174,6 +251,22 @@
   return cast<SymbolMetadata>(SD);
 }
=20
+const SymbolCast*
+SymbolManager::getCastSymbol(const SymExpr *Op,
+                             QualType From, QualType To) {
+  llvm::FoldingSetNodeID ID;
+  SymbolCast::Profile(ID, Op, From, To);
+  void *InsertPos;
+  SymExpr *data =3D DataSet.FindNodeOrInsertPos(ID, InsertPos);
+  if (!data) {
+    data =3D (SymbolCast*) BPAlloc.Allocate<SymbolCast>();
+    new (data) SymbolCast(Op, From, To);
+    DataSet.InsertNode(data, InsertPos);
+  }
+
+  return cast<SymbolCast>(data);
+}
+
 const SymIntExpr *SymbolManager::getSymIntExpr(const SymExpr *lhs,
                                                BinaryOperator::Opcode op,
                                                const llvm::APSInt& v,
@@ -192,6 +285,24 @@
   return cast<SymIntExpr>(data);
 }
=20
+const IntSymExpr *SymbolManager::getIntSymExpr(const llvm::APSInt& lhs,
+                                               BinaryOperator::Opcode op,
+                                               const SymExpr *rhs,
+                                               QualType t) {
+  llvm::FoldingSetNodeID ID;
+  IntSymExpr::Profile(ID, lhs, op, rhs, t);
+  void *InsertPos;
+  SymExpr *data =3D DataSet.FindNodeOrInsertPos(ID, InsertPos);
+
+  if (!data) {
+    data =3D (IntSymExpr*) BPAlloc.Allocate<IntSymExpr>();
+    new (data) IntSymExpr(lhs, op, rhs, t);
+    DataSet.InsertNode(data, InsertPos);
+  }
+
+  return cast<IntSymExpr>(data);
+}
+
 const SymSymExpr *SymbolManager::getSymSymExpr(const SymExpr *lhs,
                                                BinaryOperator::Opcode op,
                                                const SymExpr *rhs,
@@ -381,7 +492,16 @@
   return isa<SymbolRegionValue>(sym);
 }
=20
-bool SymbolReaper::isLive(const Stmt *ExprVal) const {
+bool
+SymbolReaper::isLive(const Stmt *ExprVal, const LocationContext *ELCtx) co=
nst {
+  if (LCtx !=3D ELCtx) {
+    // If the reaper's location context is a parent of the expression's
+    // location context, then the expression value is now "out of scope".
+    if (LCtx->isParentOf(ELCtx))
+      return false;
+    return true;
+  }
+
   return LCtx->getAnalysis<RelaxedLiveVariables>()->isLive(Loc, ExprVal);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Core/TextPathDiagnostics.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/TextPathDiagnos=
tics.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Core/TextPathDiagnos=
tics.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -31,9 +31,8 @@
   TextPathDiagnostics(const std::string& output, DiagnosticsEngine &diag)
     : OutputFile(output), Diag(diag) {}
=20
-  void HandlePathDiagnosticImpl(const PathDiagnostic* D);
-
-  void FlushDiagnostics(SmallVectorImpl<std::string> *FilesMade) { }
+  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
+                            SmallVectorImpl<std::string> *FilesMade);
  =20
   virtual StringRef getName() const {
     return "TextPathDiagnostics";
@@ -53,18 +52,18 @@
   return new TextPathDiagnostics(out, PP.getDiagnostics());
 }
=20
-void TextPathDiagnostics::HandlePathDiagnosticImpl(const PathDiagnostic* D=
) {
-  if (!D)
-    return;
-
-  if (D->empty()) {
-    delete D;
-    return;
-  }
-
-  for (PathDiagnostic::const_iterator I=3DD->begin(), E=3DD->end(); I !=3D=
 E; ++I) {
-    unsigned diagID =3D Diag.getDiagnosticIDs()->getCustomDiagID(
-                                           DiagnosticIDs::Note, I->getStri=
ng());
-    Diag.Report(I->getLocation().asLocation(), diagID);
+void TextPathDiagnostics::FlushDiagnosticsImpl(
+                              std::vector<const PathDiagnostic *> &Diags,
+                              SmallVectorImpl<std::string> *FilesMade) {
+  for (std::vector<const PathDiagnostic *>::iterator it =3D Diags.begin(),
+       et =3D Diags.end(); it !=3D et; ++it) {
+    const PathDiagnostic *D =3D *it;
+    for (PathPieces::const_iterator I =3D D->path.begin(), E =3D D->path.e=
nd();=20
+         I !=3D E; ++I) {
+      unsigned diagID =3D
+        Diag.getDiagnosticIDs()->getCustomDiagID(DiagnosticIDs::Note,
+                                                 (*I)->getString());
+      Diag.Report((*I)->getLocation().asLocation(), diagID);
+    }
   }
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Frontend/AnalysisConsumer.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Frontend/AnalysisCon=
sumer.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Frontend/AnalysisCon=
sumer.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -11,13 +11,17 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#define DEBUG_TYPE "AnalysisConsumer"
+
 #include "AnalysisConsumer.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/ParentMap.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/Analysis/CFG.h"
+#include "clang/Analysis/CallGraph.h"
 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
@@ -34,13 +38,26 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
+#include "llvm/Support/Timer.h"
+#include "llvm/ADT/DepthFirstIterator.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/Statistic.h"
+
+#include <queue>
=20
 using namespace clang;
 using namespace ento;
+using llvm::SmallPtrSet;
=20
 static ExplodedNode::Auditor* CreateUbiViz();
=20
+STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
+STATISTIC(NumFunctionsAnalyzed, "The # of functions analysed (as top level=
).");
+STATISTIC(NumBlocksInAnalyzedFunctions,
+                     "The # of basic blocks in the analyzed functions.");
+STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Special PathDiagnosticConsumers.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -59,7 +76,19 @@
=20
 namespace {
=20
-class AnalysisConsumer : public ASTConsumer {
+class AnalysisConsumer : public ASTConsumer,
+                         public RecursiveASTVisitor<AnalysisConsumer> {
+  enum AnalysisMode {
+    ANALYSIS_SYNTAX,
+    ANALYSIS_PATH,
+    ANALYSIS_ALL
+  };
+
+  /// Mode of the analyzes while recursively visiting Decls.
+  AnalysisMode RecVisitorMode;
+  /// Bug Reporter to use while recursively visiting Decls.
+  BugReporter *RecVisitorBR;
+
 public:
   ASTContext *Ctx;
   const Preprocessor &PP;
@@ -67,21 +96,45 @@
   AnalyzerOptions Opts;
   ArrayRef<std::string> Plugins;
=20
+  /// \brief Stores the declarations from the local translation unit.
+  /// Note, we pre-compute the local declarations at parse time as an
+  /// optimization to make sure we do not deserialize everything from disk.
+  /// The local declaration to all declarations ratio might be very small =
when
+  /// working with a PCH file.
+  SetOfDecls LocalTUDecls;
+
   // PD is owned by AnalysisManager.
   PathDiagnosticConsumer *PD;
=20
   StoreManagerCreator CreateStoreMgr;
   ConstraintManagerCreator CreateConstraintMgr;
=20
-  llvm::OwningPtr<CheckerManager> checkerMgr;
-  llvm::OwningPtr<AnalysisManager> Mgr;
+  OwningPtr<CheckerManager> checkerMgr;
+  OwningPtr<AnalysisManager> Mgr;
+
+  /// Time the analyzes time of each translation unit.
+  static llvm::Timer* TUTotalTimer;
+
+  /// The information about analyzed functions shared throughout the
+  /// translation unit.
+  FunctionSummariesTy FunctionSummaries;
=20
   AnalysisConsumer(const Preprocessor& pp,
                    const std::string& outdir,
                    const AnalyzerOptions& opts,
                    ArrayRef<std::string> plugins)
-    : Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins), PD(0) {
+    : RecVisitorMode(ANALYSIS_ALL), RecVisitorBR(0),
+      Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins), PD(0) {
     DigestAnalyzerOptions();
+    if (Opts.PrintStats) {
+      llvm::EnableStatistics();
+      TUTotalTimer =3D new llvm::Timer("Analyzer Total Time");
+    }
+  }
+
+  ~AnalysisConsumer() {
+    if (Opts.PrintStats)
+      delete TUTotalTimer;
   }
=20
   void DigestAnalyzerOptions() {
@@ -117,15 +170,20 @@
     }
   }
=20
-  void DisplayFunction(const Decl *D) {
+  void DisplayFunction(const Decl *D, AnalysisMode Mode) {
     if (!Opts.AnalyzerDisplayProgress)
       return;
=20
     SourceManager &SM =3D Mgr->getASTContext().getSourceManager();
     PresumedLoc Loc =3D SM.getPresumedLoc(D->getLocation());
     if (Loc.isValid()) {
-      llvm::errs() << "ANALYZE: " << Loc.getFilename();
-
+      llvm::errs() << "ANALYZE";
+      switch (Mode) {
+        case ANALYSIS_SYNTAX: llvm::errs() << "(Syntax)"; break;
+        case ANALYSIS_PATH: llvm::errs() << "(Path Sensitive)"; break;
+        case ANALYSIS_ALL: break;
+      };
+      llvm::errs() << ": " << Loc.getFilename();
       if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) {
         const NamedDecl *ND =3D cast<NamedDecl>(D);
         llvm::errs() << ' ' << *ND << '\n';
@@ -143,112 +201,236 @@
=20
   virtual void Initialize(ASTContext &Context) {
     Ctx =3D &Context;
-    checkerMgr.reset(createCheckerManager(Opts, PP.getLangOptions(), Plugi=
ns,
+    checkerMgr.reset(createCheckerManager(Opts, PP.getLangOpts(), Plugins,
                                           PP.getDiagnostics()));
     Mgr.reset(new AnalysisManager(*Ctx, PP.getDiagnostics(),
-                                  PP.getLangOptions(), PD,
+                                  PP.getLangOpts(), PD,
                                   CreateStoreMgr, CreateConstraintMgr,
                                   checkerMgr.get(),
                                   /* Indexer */ 0,=20
                                   Opts.MaxNodes, Opts.MaxLoop,
                                   Opts.VisualizeEGDot, Opts.VisualizeEGUbi,
                                   Opts.AnalysisPurgeOpt, Opts.EagerlyAssum=
e,
-                                  Opts.TrimGraph, Opts.InlineCall,
+                                  Opts.TrimGraph,
                                   Opts.UnoptimizedCFG, Opts.CFGAddImplicit=
Dtors,
                                   Opts.CFGAddInitializers,
-                                  Opts.EagerlyTrimEGraph));
+                                  Opts.EagerlyTrimEGraph,
+                                  Opts.IPAMode,
+                                  Opts.InlineMaxStackDepth,
+                                  Opts.InlineMaxFunctionSize,
+                                  Opts.InliningMode,
+                                  Opts.NoRetryExhausted));
   }
=20
+  /// \brief Store the top level decls in the set to be processed later on.
+  /// (Doing this pre-processing avoids deserialization of data from PCH.)
+  virtual bool HandleTopLevelDecl(DeclGroupRef D);
+  virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D);
+
   virtual void HandleTranslationUnit(ASTContext &C);
-  void HandleDeclContext(ASTContext &C, DeclContext *dc);
-  void HandleDeclContextDecl(ASTContext &C, Decl *D);
=20
-  void HandleCode(Decl *D);
+  /// \brief Build the call graph for all the top level decls of this TU a=
nd
+  /// use it to define the order in which the functions should be visited.
+  void HandleDeclsGallGraph();
+
+  /// \brief Run analyzes(syntax or path sensitive) on the given function.
+  /// \param Mode - determines if we are requesting syntax only or path
+  /// sensitive only analysis.
+  /// \param VisitedCallees - The output parameter, which is populated wit=
h the
+  /// set of functions which should be considered analyzed after analyzing=
 the
+  /// given root function.
+  void HandleCode(Decl *D, AnalysisMode Mode,
+                  SetOfConstDecls *VisitedCallees =3D 0);
+
+  void RunPathSensitiveChecks(Decl *D, SetOfConstDecls *VisitedCallees);
+  void ActionExprEngine(Decl *D, bool ObjCGCEnabled,
+                        SetOfConstDecls *VisitedCallees);
+
+  /// Visitors for the RecursiveASTVisitor.
+
+  /// Handle callbacks for arbitrary Decls.
+  bool VisitDecl(Decl *D) {
+    checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
+    return true;
+  }
+
+  bool VisitFunctionDecl(FunctionDecl *FD) {
+    IdentifierInfo *II =3D FD->getIdentifier();
+    if (II && II->getName().startswith("__inline"))
+      return true;
+
+    // We skip function template definitions, as their semantics is
+    // only determined when they are instantiated.
+    if (FD->isThisDeclarationADefinition() &&
+        !FD->isDependentContext()) {
+      HandleCode(FD, RecVisitorMode);
+    }
+    return true;
+  }
+
+  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
+    checkerMgr->runCheckersOnASTDecl(MD, *Mgr, *RecVisitorBR);
+    if (MD->isThisDeclarationADefinition())
+      HandleCode(MD, RecVisitorMode);
+    return true;
+  }
+
+private:
+  void storeTopLevelDecls(DeclGroupRef DG);
+
+  /// \brief Check if we should skip (not analyze) the given function.
+  bool skipFunction(Decl *D);
+
 };
 } // end anonymous namespace
=20
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // AnalysisConsumer implementation.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+llvm::Timer* AnalysisConsumer::TUTotalTimer =3D 0;
=20
-void AnalysisConsumer::HandleDeclContext(ASTContext &C, DeclContext *dc) {
-  for (DeclContext::decl_iterator I =3D dc->decls_begin(), E =3D dc->decls=
_end();
-       I !=3D E; ++I) {
-    HandleDeclContextDecl(C, *I);
+bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
+  storeTopLevelDecls(DG);
+  return true;
+}
+
+void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
+  storeTopLevelDecls(DG);
+}
+
+void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
+  for (DeclGroupRef::iterator I =3D DG.begin(), E =3D DG.end(); I !=3D E; =
++I) {
+
+    // Skip ObjCMethodDecl, wait for the objc container to avoid
+    // analyzing twice.
+    if (isa<ObjCMethodDecl>(*I))
+      continue;
+
+    LocalTUDecls.insert(*I);
   }
 }
=20
-void AnalysisConsumer::HandleDeclContextDecl(ASTContext &C, Decl *D) {
-  { // Handle callbacks for arbitrary decls.
-    BugReporter BR(*Mgr);
-    checkerMgr->runCheckersOnASTDecl(D, *Mgr, BR);
+void AnalysisConsumer::HandleDeclsGallGraph() {
+  // Otherwise, use the Callgraph to derive the order.
+  // Build the Call Graph.
+  CallGraph CG;
+  // Add all the top level declarations to the graph.
+  for (SetOfDecls::iterator I =3D LocalTUDecls.begin(),
+                            E =3D LocalTUDecls.end(); I !=3D E; ++I)
+    CG.addToCallGraph(*I);
+
+  // Find the top level nodes - children of root + the unreachable (parent=
less)
+  // nodes.
+  llvm::SmallVector<CallGraphNode*, 24> TopLevelFunctions;
+  for (CallGraph::nodes_iterator TI =3D CG.parentless_begin(),
+                                 TE =3D CG.parentless_end(); TI !=3D TE; +=
+TI) {
+    TopLevelFunctions.push_back(*TI);
+    NumFunctionTopLevel++;
+  }
+  CallGraphNode *Entry =3D CG.getRoot();
+  for (CallGraphNode::iterator I =3D Entry->begin(),
+                               E =3D Entry->end(); I !=3D E; ++I) {
+    TopLevelFunctions.push_back(*I);
+    NumFunctionTopLevel++;
   }
=20
-  switch (D->getKind()) {
-    case Decl::Namespace: {
-      HandleDeclContext(C, cast<NamespaceDecl>(D));
-      break;
+  // Make sure the nodes are sorted in order reverse of their definition i=
n the=20
+  // translation unit. This step is very important for performance. It ens=
ures=20
+  // that we analyze the root functions before the externally available=20
+  // subroutines.
+  std::queue<CallGraphNode*> BFSQueue;
+  for (llvm::SmallVector<CallGraphNode*, 24>::reverse_iterator
+         TI =3D TopLevelFunctions.rbegin(), TE =3D TopLevelFunctions.rend(=
);
+         TI !=3D TE; ++TI)
+    BFSQueue.push(*TI);
+
+  // BFS over all of the functions, while skipping the ones inlined into
+  // the previously processed functions. Use external Visited set, which is
+  // also modified when we inline a function.
+  SmallPtrSet<CallGraphNode*,24> Visited;
+  while(!BFSQueue.empty()) {
+    CallGraphNode *N =3D BFSQueue.front();
+    BFSQueue.pop();
+
+    // Skip the functions which have been processed already or previously
+    // inlined.
+    if (Visited.count(N))
+      continue;
+
+    // Analyze the function.
+    SetOfConstDecls VisitedCallees;
+    Decl *D =3D N->getDecl();
+    assert(D);
+    HandleCode(D, ANALYSIS_PATH,
+               (Mgr->InliningMode =3D=3D All ? 0 : &VisitedCallees));
+
+    // Add the visited callees to the global visited set.
+    for (SetOfConstDecls::const_iterator I =3D VisitedCallees.begin(),
+                                         E =3D VisitedCallees.end(); I !=
=3D E; ++I){
+      CallGraphNode *VN =3D CG.getNode(*I);
+      if (VN)
+        Visited.insert(VN);
     }
-    case Decl::CXXConstructor:
-    case Decl::CXXDestructor:
-    case Decl::CXXConversion:
-    case Decl::CXXMethod:
-    case Decl::Function: {
-      FunctionDecl *FD =3D cast<FunctionDecl>(D);
-      // We skip function template definitions, as their semantics is
-      // only determined when they are instantiated.
-      if (FD->isThisDeclarationADefinition() &&
-          !FD->isDependentContext()) {
-        if (!Opts.AnalyzeSpecificFunction.empty() &&
-            FD->getDeclName().getAsString() !=3D Opts.AnalyzeSpecificFunct=
ion)
-          break;
-        DisplayFunction(FD);
-        HandleCode(FD);
-      }
-      break;
+    Visited.insert(N);
+
+    // Push the children into the queue.
+    for (CallGraphNode::const_iterator CI =3D N->begin(),
+                                       CE =3D N->end(); CI !=3D CE; ++CI) {
+      BFSQueue.push(*CI);
     }
-    =20
-    case Decl::ObjCCategoryImpl:
-    case Decl::ObjCImplementation: {
-      ObjCImplDecl *ID =3D cast<ObjCImplDecl>(D);
-      HandleCode(ID);
-     =20
-      for (ObjCContainerDecl::method_iterator MI =3D ID->meth_begin(),=20
-           ME =3D ID->meth_end(); MI !=3D ME; ++MI) {
-        BugReporter BR(*Mgr);
-        checkerMgr->runCheckersOnASTDecl(*MI, *Mgr, BR);
-
-        if ((*MI)->isThisDeclarationADefinition()) {
-          if (!Opts.AnalyzeSpecificFunction.empty() &&
-              Opts.AnalyzeSpecificFunction !=3D=20
-                (*MI)->getSelector().getAsString())
-            continue;
-          DisplayFunction(*MI);
-          HandleCode(*MI);
-        }
-      }
-      break;
-    }
-     =20
-    default:
-      break;
   }
 }
=20
 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
-  BugReporter BR(*Mgr);
-  TranslationUnitDecl *TU =3D C.getTranslationUnitDecl();
-  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
-  HandleDeclContext(C, TU);
+  // Don't run the actions if an error has occurred with parsing the file.
+  DiagnosticsEngine &Diags =3D PP.getDiagnostics();
+  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
+    return;
=20
-  // After all decls handled, run checkers on the entire TranslationUnit.
-  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
+  {
+    if (TUTotalTimer) TUTotalTimer->startTimer();
+
+    // Introduce a scope to destroy BR before Mgr.
+    BugReporter BR(*Mgr);
+    TranslationUnitDecl *TU =3D C.getTranslationUnitDecl();
+    checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
+
+    // Run the AST-only checks using the order in which functions are defi=
ned.
+    // If inlining is not turned on, use the simplest function order for p=
ath
+    // sensitive analyzes as well.
+    RecVisitorMode =3D (Mgr->shouldInlineCall() ? ANALYSIS_SYNTAX : ANALYS=
IS_ALL);
+    RecVisitorBR =3D &BR;
+
+    // Process all the top level declarations.
+    for (SetOfDecls::iterator I =3D LocalTUDecls.begin(),
+                              E =3D LocalTUDecls.end(); I !=3D E; ++I)
+      TraverseDecl(*I);
+
+    if (Mgr->shouldInlineCall())
+      HandleDeclsGallGraph();
+
+    // After all decls handled, run checkers on the entire TranslationUnit.
+    checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
+
+    RecVisitorBR =3D 0;
+  }
=20
   // Explicitly destroy the PathDiagnosticConsumer.  This will flush its o=
utput.
   // FIXME: This should be replaced with something that doesn't rely on
   // side-effects in PathDiagnosticConsumer's destructor. This is required=
 when
   // used with option -disable-free.
   Mgr.reset(NULL);
+
+  if (TUTotalTimer) TUTotalTimer->stopTimer();
+
+  // Count how many basic blocks we have not covered.
+  NumBlocksInAnalyzedFunctions =3D FunctionSummaries.getTotalNumBasicBlock=
s();
+  if (NumBlocksInAnalyzedFunctions > 0)
+    PercentReachableBlocks =3D
+      (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
+        NumBlocksInAnalyzedFunctions;
+
 }
=20
 static void FindBlocks(DeclContext *D, SmallVectorImpl<Decl*> &WL) {
@@ -261,24 +443,41 @@
       FindBlocks(DC, WL);
 }
=20
-static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &m=
gr,
-                                   Decl *D);
+static std::string getFunctionName(const Decl *D) {
+  if (const ObjCMethodDecl *ID =3D dyn_cast<ObjCMethodDecl>(D)) {
+    return ID->getSelector().getAsString();
+  }
+  if (const FunctionDecl *ND =3D dyn_cast<FunctionDecl>(D)) {
+    IdentifierInfo *II =3D ND->getIdentifier();
+    if (II)
+      return II->getName();
+  }
+  return "";
+}
=20
-void AnalysisConsumer::HandleCode(Decl *D) {
-
-  // Don't run the actions if an error has occurred with parsing the file.
-  DiagnosticsEngine &Diags =3D PP.getDiagnostics();
-  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
-    return;
+bool AnalysisConsumer::skipFunction(Decl *D) {
+  if (!Opts.AnalyzeSpecificFunction.empty() &&
+      getFunctionName(D) !=3D Opts.AnalyzeSpecificFunction)
+    return true;
=20
   // Don't run the actions on declarations in header files unless
   // otherwise specified.
   SourceManager &SM =3D Ctx->getSourceManager();
   SourceLocation SL =3D SM.getExpansionLoc(D->getLocation());
   if (!Opts.AnalyzeAll && !SM.isFromMainFile(SL))
+    return true;
+
+  return false;
+}
+
+void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
+                                  SetOfConstDecls *VisitedCallees) {
+  if (skipFunction(D))
     return;
=20
-  // Clear the AnalysisManager of old AnalysisContexts.
+  DisplayFunction(D, Mode);
+
+  // Clear the AnalysisManager of old AnalysisDeclContexts.
   Mgr->ClearContexts();
=20
   // Dispatch on the actions.
@@ -292,9 +491,12 @@
   for (SmallVectorImpl<Decl*>::iterator WI=3DWL.begin(), WE=3DWL.end();
        WI !=3D WE; ++WI)
     if ((*WI)->hasBody()) {
-      checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
-      if (checkerMgr->hasPathSensitiveCheckers())
-        RunPathSensitiveChecks(*this, *Mgr, *WI);
+      if (Mode !=3D ANALYSIS_PATH)
+        checkerMgr->runCheckersOnASTBody(*WI, *Mgr, BR);
+      if (Mode !=3D ANALYSIS_SYNTAX && checkerMgr->hasPathSensitiveChecker=
s()) {
+        RunPathSensitiveChecks(*WI, VisitedCallees);
+        NumFunctionsAnalyzed++;
+      }
     }
 }
=20
@@ -302,53 +504,53 @@
 // Path-sensitive checking.
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
-static void ActionExprEngine(AnalysisConsumer &C, AnalysisManager &mgr,
-                             Decl *D, bool ObjCGCEnabled) {
+void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled,
+                                        SetOfConstDecls *VisitedCallees) {
   // Construct the analysis engine.  First check if the CFG is valid.
   // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
-  if (!mgr.getCFG(D))
+  if (!Mgr->getCFG(D))
     return;
-  ExprEngine Eng(mgr, ObjCGCEnabled);
+
+  ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries);
=20
   // Set the graph auditor.
-  llvm::OwningPtr<ExplodedNode::Auditor> Auditor;
-  if (mgr.shouldVisualizeUbigraph()) {
+  OwningPtr<ExplodedNode::Auditor> Auditor;
+  if (Mgr->shouldVisualizeUbigraph()) {
     Auditor.reset(CreateUbiViz());
     ExplodedNode::SetAuditor(Auditor.get());
   }
=20
   // Execute the worklist algorithm.
-  Eng.ExecuteWorkList(mgr.getStackFrame(D, 0), mgr.getMaxNodes());
+  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D=
, 0),
+                      Mgr->getMaxNodes());
=20
   // Release the auditor (if any) so that it doesn't monitor the graph
   // created BugReporter.
   ExplodedNode::SetAuditor(0);
=20
   // Visualize the exploded graph.
-  if (mgr.shouldVisualizeGraphviz())
-    Eng.ViewGraph(mgr.shouldTrimGraph());
+  if (Mgr->shouldVisualizeGraphviz())
+    Eng.ViewGraph(Mgr->shouldTrimGraph());
=20
   // Display warnings.
   Eng.getBugReporter().FlushReports();
 }
=20
-static void RunPathSensitiveChecks(AnalysisConsumer &C, AnalysisManager &m=
gr,
-                                   Decl *D) {
+void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
+                                              SetOfConstDecls *Visited) {
=20
-  switch (mgr.getLangOptions().getGC()) {
-  default:
-    llvm_unreachable("Invalid GC mode.");
+  switch (Mgr->getLangOpts().getGC()) {
   case LangOptions::NonGC:
-    ActionExprEngine(C, mgr, D, false);
+    ActionExprEngine(D, false, Visited);
     break;
  =20
   case LangOptions::GCOnly:
-    ActionExprEngine(C, mgr, D, true);
+    ActionExprEngine(D, true, Visited);
     break;
  =20
   case LangOptions::HybridGC:
-    ActionExprEngine(C, mgr, D, false);
-    ActionExprEngine(C, mgr, D, true);
+    ActionExprEngine(D, false, Visited);
+    ActionExprEngine(D, true, Visited);
     break;
   }
 }
@@ -374,7 +576,7 @@
 namespace {
=20
 class UbigraphViz : public ExplodedNode::Auditor {
-  llvm::OwningPtr<raw_ostream> Out;
+  OwningPtr<raw_ostream> Out;
   llvm::sys::Path Dir, Filename;
   unsigned Cntr;
=20
@@ -408,7 +610,7 @@
=20
   llvm::errs() << "Writing '" << Filename.str() << "'.\n";
=20
-  llvm::OwningPtr<llvm::raw_fd_ostream> Stream;
+  OwningPtr<llvm::raw_fd_ostream> Stream;
   Stream.reset(new llvm::raw_fd_ostream(Filename.c_str(), ErrMsg));
=20
   if (!ErrMsg.empty())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/lib/Stat=
icAnalyzer/Frontend/CheckerRegistration.cpp
--- a/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Frontend/CheckerRegi=
stration.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/lib/StaticAnalyzer/Frontend/CheckerRegi=
stration.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -104,7 +104,7 @@
                                            const LangOptions &langOpts,
                                            ArrayRef<std::string> plugins,
                                            DiagnosticsEngine &diags) {
-  llvm::OwningPtr<CheckerManager> checkerMgr(new CheckerManager(langOpts));
+  OwningPtr<CheckerManager> checkerMgr(new CheckerManager(langOpts));
=20
   SmallVector<CheckerOptInfo, 8> checkerOpts;
   for (unsigned i =3D 0, e =3D opts.CheckersControlList.size(); i !=3D e; =
++i) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/tools/dr=
iver/cc1_main.cpp
--- a/head/contrib/llvm/tools/clang/tools/driver/cc1_main.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/tools/driver/cc1_main.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -30,6 +30,7 @@
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/raw_ostream.h"
+#include "llvm/LinkAllPasses.h"
 #include <cstdio>
 using namespace clang;
=20
@@ -76,7 +77,8 @@
   // Create a compiler invocation.
   llvm::errs() << "cc1 creating invocation.\n";
   CompilerInvocation Invocation;
-  CompilerInvocation::CreateFromArgs(Invocation, ArgBegin, ArgEnd, Diags);
+  if (!CompilerInvocation::CreateFromArgs(Invocation, ArgBegin, ArgEnd, Di=
ags))
+    return 1;
=20
   // Convert the invocation back to argument strings.
   std::vector<std::string> InvocationArgs;
@@ -94,8 +96,9 @@
   // Convert those arguments to another invocation, and check that we got =
the
   // same thing.
   CompilerInvocation Invocation2;
-  CompilerInvocation::CreateFromArgs(Invocation2, Invocation2Args.begin(),
-                                     Invocation2Args.end(), Diags);
+  if (!CompilerInvocation::CreateFromArgs(Invocation2, Invocation2Args.beg=
in(),
+                                          Invocation2Args.end(), Diags))
+    return 1;
=20
   // FIXME: Implement CompilerInvocation comparison.
   if (true) {
@@ -114,8 +117,8 @@
=20
 int cc1_main(const char **ArgBegin, const char **ArgEnd,
              const char *Argv0, void *MainAddr) {
-  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  OwningPtr<CompilerInstance> Clang(new CompilerInstance());
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
=20
   // Run clang -cc1 test.
   if (ArgBegin !=3D ArgEnd && StringRef(ArgBegin[0]) =3D=3D "-cc1test") {
@@ -134,8 +137,9 @@
   // well formed diagnostic object.
   TextDiagnosticBuffer *DiagsBuffer =3D new TextDiagnosticBuffer;
   DiagnosticsEngine Diags(DiagID, DiagsBuffer);
-  CompilerInvocation::CreateFromArgs(Clang->getInvocation(), ArgBegin, Arg=
End,
-                                     Diags);
+  bool Success;
+  Success =3D CompilerInvocation::CreateFromArgs(Clang->getInvocation(),
+                                               ArgBegin, ArgEnd, Diags);
=20
   // Infer the builtin include path if unspecified.
   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
@@ -154,9 +158,11 @@
                                   static_cast<void*>(&Clang->getDiagnostic=
s()));
=20
   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
+  if (!Success)
+    return 1;
=20
   // Execute the frontend actions.
-  bool Success =3D ExecuteCompilerInvocation(Clang.get());
+  Success =3D ExecuteCompilerInvocation(Clang.get());
=20
   // If any timers were active but haven't been destroyed yet, print their
   // results now.  This happens in -disable-free mode.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/tools/dr=
iver/cc1as_main.cpp
--- a/head/contrib/llvm/tools/clang/tools/driver/cc1as_main.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/tools/driver/cc1as_main.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -63,8 +63,17 @@
   /// @name Target Options
   /// @{
=20
+  /// The name of the target triple to assemble for.
   std::string Triple;
=20
+  /// If given, the name of the target CPU to determine which instructions
+  /// are legal.
+  std::string CPU;
+
+  /// The list of target specific features to enable or disable -- this sh=
ould
+  /// be a list of strings starting with '+' or '-'.
+  std::vector<std::string> Features;
+
   /// @}
   /// @name Language Options
   /// @{
@@ -72,6 +81,8 @@
   std::vector<std::string> IncludePaths;
   unsigned NoInitialTextSection : 1;
   unsigned SaveTemporaryLabels : 1;
+  unsigned GenDwarfForAssembly : 1;
+  std::string DwarfDebugFlags;
=20
   /// @}
   /// @name Frontend Options
@@ -120,17 +131,19 @@
     NoExecStack =3D 0;
   }
=20
-  static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBeg=
in,
+  static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBeg=
in,
                              const char **ArgEnd, DiagnosticsEngine &Diags=
);
 };
=20
 }
=20
-void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
+bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
                                          const char **ArgBegin,
                                          const char **ArgEnd,
                                          DiagnosticsEngine &Diags) {
   using namespace clang::driver::cc1asoptions;
+  bool Success =3D true;
+
   // Parse the arguments.
   OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
   unsigned MissingArgIndex, MissingArgCount;
@@ -138,26 +151,36 @@
     OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
=20
   // Check for missing argument error.
-  if (MissingArgCount)
+  if (MissingArgCount) {
     Diags.Report(diag::err_drv_missing_argument)
       << Args->getArgString(MissingArgIndex) << MissingArgCount;
+    Success =3D false;
+  }
=20
   // Issue errors on unknown arguments.
   for (arg_iterator it =3D Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
-         ie =3D Args->filtered_end(); it !=3D ie; ++it)
+         ie =3D Args->filtered_end(); it !=3D ie; ++it) {
     Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*A=
rgs);
+    Success =3D false;
+  }
=20
   // Construct the invocation.
=20
   // Target Options
-  Opts.Triple =3D Triple::normalize(Args->getLastArgValue(OPT_triple));
-  if (Opts.Triple.empty()) // Use the host triple if unspecified.
-    Opts.Triple =3D sys::getHostTriple();
+  Opts.Triple =3D llvm::Triple::normalize(Args->getLastArgValue(OPT_triple=
));
+  Opts.CPU =3D Args->getLastArgValue(OPT_target_cpu);
+  Opts.Features =3D Args->getAllArgValues(OPT_target_feature);
+
+  // Use the default target triple if unspecified.
+  if (Opts.Triple.empty())
+    Opts.Triple =3D llvm::sys::getDefaultTargetTriple();
=20
   // Language Options
   Opts.IncludePaths =3D Args->getAllArgValues(OPT_I);
   Opts.NoInitialTextSection =3D Args->hasArg(OPT_n);
   Opts.SaveTemporaryLabels =3D Args->hasArg(OPT_L);
+  Opts.GenDwarfForAssembly =3D Args->hasArg(OPT_g);
+  Opts.DwarfDebugFlags =3D Args->getLastArgValue(OPT_dwarf_debug_flags);
=20
   // Frontend Options
   if (Args->hasArg(OPT_INPUT)) {
@@ -167,8 +190,10 @@
       const Arg *A =3D it;
       if (First)
         Opts.InputFile =3D A->getValue(*Args);
-      else
+      else {
         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Ar=
gs);
+        Success =3D false;
+      }
     }
   }
   Opts.LLVMArgs =3D Args->getAllArgValues(OPT_mllvm);
@@ -182,10 +207,11 @@
       .Case("null", FT_Null)
       .Case("obj", FT_Obj)
       .Default(~0U);
-    if (OutputType =3D=3D ~0U)
+    if (OutputType =3D=3D ~0U) {
       Diags.Report(diag::err_drv_invalid_value)
         << A->getAsString(*Args) << Name;
-    else
+      Success =3D false;
+    } else
       Opts.OutputType =3D FileType(OutputType);
   }
   Opts.ShowHelp =3D Args->hasArg(OPT_help);
@@ -200,6 +226,8 @@
   // Assemble Options
   Opts.RelaxAll =3D Args->hasArg(OPT_relax_all);
   Opts.NoExecStack =3D  Args->hasArg(OPT_no_exec_stack);
+
+  return Success;
 }
=20
 static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
@@ -267,23 +295,36 @@
   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
   // MCObjectFileInfo needs a MCContext reference in order to initialize i=
tself.
   OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
-  MCContext Ctx(*MAI, *MRI, MOFI.get());
+  MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
   // FIXME: Assembler behavior can change with -static.
   MOFI->InitMCObjectFileInfo(Opts.Triple,
                              Reloc::Default, CodeModel::Default, Ctx);
   if (Opts.SaveTemporaryLabels)
     Ctx.setAllowTemporaryLabels(false);
+  if (Opts.GenDwarfForAssembly)
+    Ctx.setGenDwarfForAssembly(true);
+  if (!Opts.DwarfDebugFlags.empty())
+    Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
+
+  // Build up the feature string from the target feature list.
+  std::string FS;
+  if (!Opts.Features.empty()) {
+    FS =3D Opts.Features[0];
+    for (unsigned i =3D 1, e =3D Opts.Features.size(); i !=3D e; ++i)
+      FS +=3D "," + Opts.Features[i];
+  }
=20
   OwningPtr<MCStreamer> Str;
=20
   OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
   OwningPtr<MCSubtargetInfo>
-    STI(TheTarget->createMCSubtargetInfo(Opts.Triple, "", ""));
+    STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
=20
   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
   if (Opts.OutputType =3D=3D AssemblerInvocation::FT_Asm) {
     MCInstPrinter *IP =3D
-      TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *STI);
+      TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *=
MRI,
+                                     *STI);
     MCCodeEmitter *CE =3D 0;
     MCAsmBackend *MAB =3D 0;
     if (Opts.ShowEncoding) {
@@ -292,7 +333,9 @@
     }
     Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
                                            /*useLoc*/ true,
-                                           /*useCFI*/ true, IP, CE, MAB,
+                                           /*useCFI*/ true,
+                                           /*useDwarfDirectory*/ true,
+                                           IP, CE, MAB,
                                            Opts.ShowInst));
   } else if (Opts.OutputType =3D=3D AssemblerInvocation::FT_Null) {
     Str.reset(createNullStreamer(Ctx));
@@ -354,7 +397,7 @@
   TextDiagnosticPrinter *DiagClient
     =3D new TextDiagnosticPrinter(errs(), DiagnosticOptions());
   DiagClient->setPrefix("clang -cc1as");
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
   DiagnosticsEngine Diags(DiagID, DiagClient);
=20
   // Set an error handler, so that any LLVM backend diagnostics go through=
 our
@@ -364,11 +407,12 @@
=20
   // Parse the arguments.
   AssemblerInvocation Asm;
-  AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
+  if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
+    return 1;
=20
   // Honor -help.
   if (Asm.ShowHelp) {
-    llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
+    OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
     Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assemb=
ler");
     return 0;
   }
@@ -391,7 +435,7 @@
     for (unsigned i =3D 0; i !=3D NumArgs; ++i)
       Args[i + 1] =3D Asm.LLVMArgs[i].c_str();
     Args[NumArgs + 1] =3D 0;
-    llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Arg=
s));
+    llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
   }
=20
   // Execute the invocation, unless there were parsing errors.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/tools/dr=
iver/driver.cpp
--- a/head/contrib/llvm/tools/clang/tools/driver/driver.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/tools/driver/driver.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -12,17 +12,21 @@
 //
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
+#include "clang/Driver/ArgList.h"
+#include "clang/Driver/CC1Options.h"
 #include "clang/Driver/Compilation.h"
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/Option.h"
+#include "clang/Driver/OptTable.h"
+#include "clang/Frontend/CompilerInvocation.h"
 #include "clang/Frontend/DiagnosticOptions.h"
 #include "clang/Frontend/TextDiagnosticPrinter.h"
+#include "clang/Frontend/Utils.h"
=20
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/OwningPtr.h"
-#include "llvm/Config/config.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/ManagedStatic.h"
@@ -187,7 +191,7 @@
                               SmallVectorImpl<const char*> &ArgVector,
                               std::set<std::string> &SavedStrings) {
   const char *FName =3D Arg + 1;
-  llvm::OwningPtr<llvm::MemoryBuffer> MemBuf;
+  OwningPtr<llvm::MemoryBuffer> MemBuf;
   if (llvm::MemoryBuffer::getFile(FName, MemBuf)) {
     ArgVector.push_back(SaveStringInSet(SavedStrings, Arg));
     return;
@@ -272,7 +276,7 @@
   // the function tries to identify a target as prefix. E.g.
   // "x86_64-linux-clang" as interpreted as suffix "clang" with
   // target prefix "x86_64-linux". If such a target prefix is found,
-  // is gets added via -ccc-host-triple as implicit first argument.
+  // is gets added via -target as implicit first argument.
   static const struct {
     const char *Suffix;
     bool IsCXX;
@@ -332,7 +336,7 @@
       ++it;
     ArgVector.insert(it, SaveStringInSet(SavedStrings, Prefix));
     ArgVector.insert(it,
-      SaveStringInSet(SavedStrings, std::string("-ccc-host-triple")));
+      SaveStringInSet(SavedStrings, std::string("-target")));
   }
 }
=20
@@ -371,25 +375,41 @@
=20
   llvm::sys::Path Path =3D GetExecutablePath(argv[0], CanonicalPrefixes);
=20
+  DiagnosticOptions DiagOpts;
+  {
+    // Note that ParseDiagnosticArgs() uses the cc1 option table.
+    OwningPtr<OptTable> CC1Opts(createCC1OptTable());
+    unsigned MissingArgIndex, MissingArgCount;
+    OwningPtr<InputArgList> Args(CC1Opts->ParseArgs(argv.begin()+1, argv.e=
nd(),
+                                            MissingArgIndex, MissingArgCou=
nt));
+    // We ignore MissingArgCount and the return value of ParseDiagnosticAr=
gs.
+    // Any errors that would be diagnosed here will also be diagnosed late=
r,
+    // when the DiagnosticsEngine actually exists.
+    (void) ParseDiagnosticArgs(DiagOpts, *Args);
+  }
+  // Now we can create the DiagnosticsEngine with a properly-filled-out
+  // DiagnosticOptions instance.
   TextDiagnosticPrinter *DiagClient
-    =3D new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
+    =3D new TextDiagnosticPrinter(llvm::errs(), DiagOpts);
   DiagClient->setPrefix(llvm::sys::path::stem(Path.str()));
-  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
+
   DiagnosticsEngine Diags(DiagID, DiagClient);
+  ProcessWarningOptions(Diags, DiagOpts);
=20
 #ifdef CLANG_IS_PRODUCTION
   const bool IsProduction =3D true;
 #else
   const bool IsProduction =3D false;
 #endif
-  Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
+  Driver TheDriver(Path.str(), llvm::sys::getDefaultTargetTriple(),
                    "a.out", IsProduction, Diags);
=20
   // Attempt to find the original path used to invoke the driver, to deter=
mine
   // the installed path. We do this manually, because we want to support t=
hat
   // path being a symlink.
   {
-    llvm::SmallString<128> InstalledPath(argv[0]);
+    SmallString<128> InstalledPath(argv[0]);
=20
     // Do a PATH lookup, if there are no directory components.
     if (llvm::sys::path::filename(InstalledPath) =3D=3D InstalledPath) {
@@ -449,7 +469,7 @@
     argv.insert(&argv[1], ExtraArgs.begin(), ExtraArgs.end());
   }
=20
-  llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(argv));
+  OwningPtr<Compilation> C(TheDriver.BuildCompilation(argv));
   int Res =3D 0;
   const Command *FailingCommand =3D 0;
   if (C.get())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/utils/Ta=
bleGen/ClangAttrEmitter.cpp
--- a/head/contrib/llvm/tools/clang/utils/TableGen/ClangAttrEmitter.cpp	Tue=
 Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/utils/TableGen/ClangAttrEmitter.cpp	Tue=
 Apr 17 11:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "llvm/TableGen/Record.h"
 #include <algorithm>
 #include <cctype>
+#include <set>
=20
 using namespace llvm;
=20
@@ -33,8 +34,6 @@
     assert(*i && "Got a null element in a ListInit");
     if (StringInit *S =3D dynamic_cast<StringInit *>(*i))
       Strings.push_back(S->getValue());
-    else if (CodeInit *C =3D dynamic_cast<CodeInit *>(*i))
-      Strings.push_back(C->getValue());
     else
       assert(false && "Got a non-string, non-code element in a ListInit");
   }
@@ -67,6 +66,30 @@
     .Default("Record.push_back(" + std::string(name) + ");\n");
 }
=20
+// Normalize attribute name by removing leading and trailing
+// underscores. For example, __foo, foo__, __foo__ would
+// become foo.
+static StringRef NormalizeAttrName(StringRef AttrName) {
+  if (AttrName.startswith("__"))
+    AttrName =3D AttrName.substr(2, AttrName.size());
+
+  if (AttrName.endswith("__"))
+    AttrName =3D AttrName.substr(0, AttrName.size() - 2);
+
+  return AttrName;
+}
+
+// Normalize attribute spelling only if the spelling has both leading
+// and trailing underscores. For example, __ms_struct__ will be=20
+// normalized to "ms_struct"; __cdecl will remain intact.
+static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
+  if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
+    AttrSpelling =3D AttrSpelling.substr(2, AttrSpelling.size() - 4);
+  }
+
+  return AttrSpelling;
+}
+
 namespace {
   class Argument {
     std::string lowerName, upperName;
@@ -91,6 +114,8 @@
     virtual void writeAccessors(raw_ostream &OS) const =3D 0;
     virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
     virtual void writeCloneArgs(raw_ostream &OS) const =3D 0;
+    virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const =3D=
 0;
+    virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
     virtual void writeCtorBody(raw_ostream &OS) const {}
     virtual void writeCtorInitializers(raw_ostream &OS) const =3D 0;
     virtual void writeCtorParameters(raw_ostream &OS) const =3D 0;
@@ -98,6 +123,7 @@
     virtual void writePCHReadArgs(raw_ostream &OS) const =3D 0;
     virtual void writePCHReadDecls(raw_ostream &OS) const =3D 0;
     virtual void writePCHWrite(raw_ostream &OS) const =3D 0;
+    virtual void writeValue(raw_ostream &OS) const =3D 0;
   };
=20
   class SimpleArgument : public Argument {
@@ -108,6 +134,8 @@
       : Argument(Arg, Attr), type(T)
     {}
=20
+    std::string getType() const { return type; }
+
     void writeAccessors(raw_ostream &OS) const {
       OS << "  " << type << " get" << getUpperName() << "() const {\n";
       OS << "    return " << getLowerName() << ";\n";
@@ -116,6 +144,9 @@
     void writeCloneArgs(raw_ostream &OS) const {
       OS << getLowerName();
     }
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      OS << "A->get" << getUpperName() << "()";
+    }
     void writeCtorInitializers(raw_ostream &OS) const {
       OS << getLowerName() << "(" << getUpperName() << ")";
     }
@@ -136,6 +167,19 @@
       OS << "    " << WritePCHRecord(type, "SA->get" +
                                            std::string(getUpperName()) + "=
()");
     }
+    void writeValue(raw_ostream &OS) const {
+      if (type =3D=3D "FunctionDecl *") {
+        OS << "\" << get" << getUpperName() << "()->getNameInfo().getAsStr=
ing() << \"";
+      } else if (type =3D=3D "IdentifierInfo *") {
+        OS << "\" << get" << getUpperName() << "()->getName() << \"";
+      } else if (type =3D=3D "QualType") {
+        OS << "\" << get" << getUpperName() << "().getAsString() << \"";
+      } else if (type =3D=3D "SourceLocation") {
+        OS << "\" << get" << getUpperName() << "().getRawEncoding() << \"";
+      } else {
+        OS << "\" << get" << getUpperName() << "() << \"";
+      }
+    }
   };
=20
   class StringArgument : public Argument {
@@ -164,6 +208,9 @@
     void writeCloneArgs(raw_ostream &OS) const {
       OS << "get" << getUpperName() << "()";
     }
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      OS << "A->get" << getUpperName() << "()";
+    }
     void writeCtorBody(raw_ostream &OS) const {
       OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName=
()
          << ".data(), " << getLowerName() << "Length);";
@@ -190,6 +237,9 @@
     void writePCHWrite(raw_ostream &OS) const {
       OS << "    AddString(SA->get" << getUpperName() << "(), Record);\n";
     }
+    void writeValue(raw_ostream &OS) const {
+      OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
+    }
   };
=20
   class AlignedArgument : public Argument {
@@ -251,6 +301,10 @@
          << "Expr) : " << getLowerName()
          << "Type";
     }
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      // FIXME: move the definition in Sema::InstantiateAttrs to here.
+      // In the meantime, aligned attributes are cloned.
+    }
     void writeCtorBody(raw_ostream &OS) const {
       OS << "    if (is" << getLowerName() << "Expr)\n";
       OS << "       " << getLowerName() << "Expr =3D reinterpret_cast<Expr=
 *>("
@@ -293,6 +347,9 @@
       OS << "      AddTypeSourceInfo(SA->get" << getUpperName()
          << "Type(), Record);\n";
     }
+    void writeValue(raw_ostream &OS) const {
+      OS << "\" << get" << getUpperName() << "(Ctx) << \"";
+    }
   };
=20
   class VariadicArgument : public Argument {
@@ -317,12 +374,17 @@
          << "Size;\n";
       OS << "  }\n";
       OS << "  unsigned " << getLowerName() << "_size() const {\n"
-         << "    return " << getLowerName() << "Size;\n;";
+         << "    return " << getLowerName() << "Size;\n";
       OS << "  }";
     }
     void writeCloneArgs(raw_ostream &OS) const {
       OS << getLowerName() << ", " << getLowerName() << "Size";
     }
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      // This isn't elegant, but we have to go through public methods...
+      OS << "A->" << getLowerName() << "_begin(), "
+         << "A->" << getLowerName() << "_size()";
+    }
     void writeCtorBody(raw_ostream &OS) const {
       // FIXME: memcpy is not safe on non-trivial types.
       OS << "    std::memcpy(" << getLowerName() << ", " << getUpperName()
@@ -362,6 +424,18 @@
          << getLowerName() << "_end(); i !=3D e; ++i)\n";
       OS << "      " << WritePCHRecord(type, "(*i)");
     }
+    void writeValue(raw_ostream &OS) const {
+      OS << "\";\n";
+      OS << "  bool isFirst =3D true;\n"
+         << "  for (" << getAttrName() << "Attr::" << getLowerName()
+         << "_iterator i =3D " << getLowerName() << "_begin(), e =3D "
+         << getLowerName() << "_end(); i !=3D e; ++i) {\n"
+         << "    if (isFirst) isFirst =3D false;\n"
+         << "    else OS << \", \";\n"
+         << "    OS << *i;\n"
+         << "  }\n";
+      OS << "  OS << \"";
+    }
   };
=20
   class EnumArgument : public Argument {
@@ -382,6 +456,9 @@
     void writeCloneArgs(raw_ostream &OS) const {
       OS << getLowerName();
     }
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      OS << "A->get" << getUpperName() << "()";
+    }
     void writeCtorInitializers(raw_ostream &OS) const {
       OS << getLowerName() << "(" << getUpperName() << ")";
     }
@@ -422,6 +499,9 @@
     void writePCHWrite(raw_ostream &OS) const {
       OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
     }
+    void writeValue(raw_ostream &OS) const {
+      OS << "\" << get" << getUpperName() << "() << \"";
+    }
   };
=20
   class VersionArgument : public Argument {
@@ -442,6 +522,9 @@
     void writeCloneArgs(raw_ostream &OS) const {
       OS << "get" << getUpperName() << "()";
     }
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      OS << "A->get" << getUpperName() << "()";
+    }
     void writeCtorBody(raw_ostream &OS) const {
     }
     void writeCtorInitializers(raw_ostream &OS) const {
@@ -463,6 +546,64 @@
     void writePCHWrite(raw_ostream &OS) const {
       OS << "    AddVersionTuple(SA->get" << getUpperName() << "(), Record=
);\n";
     }
+    void writeValue(raw_ostream &OS) const {
+      OS << getLowerName() << "=3D\" << get" << getUpperName() << "() << \=
"";
+    }
+  };
+
+  class ExprArgument : public SimpleArgument {
+  public:
+    ExprArgument(Record &Arg, StringRef Attr)
+      : SimpleArgument(Arg, Attr, "Expr *")
+    {}
+
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      OS << "tempInst" << getUpperName();
+    }
+
+    void writeTemplateInstantiation(raw_ostream &OS) const {
+      OS << "      " << getType() << " tempInst" << getUpperName() << ";\n=
";
+      OS << "      {\n";
+      OS << "        EnterExpressionEvaluationContext "
+         << "Unevaluated(S, Sema::Unevaluated);\n";
+      OS << "        ExprResult " << "Result =3D S.SubstExpr("
+         << "A->get" << getUpperName() << "(), TemplateArgs);\n";
+      OS << "        tempInst" << getUpperName() << " =3D "
+         << "Result.takeAs<Expr>();\n";
+      OS << "      }\n";
+    }
+  };
+
+  class VariadicExprArgument : public VariadicArgument {
+  public:
+    VariadicExprArgument(Record &Arg, StringRef Attr)
+      : VariadicArgument(Arg, Attr, "Expr *")
+    {}
+
+    void writeTemplateInstantiationArgs(raw_ostream &OS) const {
+      OS << "tempInst" << getUpperName() << ", "
+         << "A->" << getLowerName() << "_size()";
+    }
+
+    void writeTemplateInstantiation(raw_ostream &OS) const {
+      OS << "      " << getType() << " *tempInst" << getUpperName()
+         << " =3D new (C, 16) " << getType()
+         << "[A->" << getLowerName() << "_size()];\n";
+      OS << "      {\n";
+      OS << "        EnterExpressionEvaluationContext "
+         << "Unevaluated(S, Sema::Unevaluated);\n";
+      OS << "        " << getType() << " *TI =3D tempInst" << getUpperName=
()
+         << ";\n";
+      OS << "        " << getType() << " *I =3D A->" << getLowerName()
+         << "_begin();\n";
+      OS << "        " << getType() << " *E =3D A->" << getLowerName()
+         << "_end();\n";
+      OS << "        for (; I !=3D E; ++I, ++TI) {\n";
+      OS << "          ExprResult Result =3D S.SubstExpr(*I, TemplateArgs)=
;\n";
+      OS << "          *TI =3D Result.takeAs<Expr>();\n";
+      OS << "        }\n";
+      OS << "      }\n";
+    }
   };
 }
=20
@@ -476,8 +617,7 @@
=20
   if (ArgName =3D=3D "AlignedArgument") Ptr =3D new AlignedArgument(Arg, A=
ttr);
   else if (ArgName =3D=3D "EnumArgument") Ptr =3D new EnumArgument(Arg, At=
tr);
-  else if (ArgName =3D=3D "ExprArgument") Ptr =3D new SimpleArgument(Arg, =
Attr,
-                                                               "Expr *");
+  else if (ArgName =3D=3D "ExprArgument") Ptr =3D new ExprArgument(Arg, At=
tr);
   else if (ArgName =3D=3D "FunctionArgument")
     Ptr =3D new SimpleArgument(Arg, Attr, "FunctionDecl *");
   else if (ArgName =3D=3D "IdentifierArgument")
@@ -495,7 +635,7 @@
   else if (ArgName =3D=3D "VariadicUnsignedArgument")
     Ptr =3D new VariadicArgument(Arg, Attr, "unsigned");
   else if (ArgName =3D=3D "VariadicExprArgument")
-    Ptr =3D new VariadicArgument(Arg, Attr, "Expr *");
+    Ptr =3D new VariadicExprArgument(Arg, Attr);
   else if (ArgName =3D=3D "VersionArgument")
     Ptr =3D new VersionArgument(Arg, Attr);
=20
@@ -511,6 +651,15 @@
   return Ptr;
 }
=20
+static void writeAvailabilityValue(raw_ostream &OS) {
+  OS << "\" << getPlatform()->getName();\n"
+     << "  if (!getIntroduced().empty()) OS << \", introduced=3D\" << getI=
ntroduced();\n"
+     << "  if (!getDeprecated().empty()) OS << \", deprecated=3D\" << getD=
eprecated();\n"
+     << "  if (!getObsoleted().empty()) OS << \", obsoleted=3D\" << getObs=
oleted();\n"
+     << "  if (getUnavailable()) OS << \", unavailable\";\n"
+     << "  OS << \"";
+}
+
 void ClangAttrClassEmitter::run(raw_ostream &OS) {
   OS << "// This file is generated by TableGen. Do not edit.\n\n";
   OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
@@ -571,19 +720,25 @@
     OS << "  }\n\n";
=20
     OS << "  virtual " << R.getName() << "Attr *clone (ASTContext &C) cons=
t;\n";
+    OS << "  virtual void printPretty(llvm::raw_ostream &OS, ASTContext &C=
tx) const;\n";
=20
     for (ai =3D Args.begin(); ai !=3D ae; ++ai) {
       (*ai)->writeAccessors(OS);
       OS << "\n\n";
     }
=20
-    OS << R.getValueAsCode("AdditionalMembers");
+    OS << R.getValueAsString("AdditionalMembers");
     OS << "\n\n";
=20
     OS << "  static bool classof(const Attr *A) { return A->getKind() =3D=
=3D "
        << "attr::" << R.getName() << "; }\n";
     OS << "  static bool classof(const " << R.getName()
        << "Attr *) { return true; }\n";
+
+    bool LateParsed =3D R.getValueAsBit("LateParsed");
+    OS << "  virtual bool isLateParsed() const { return "
+       << LateParsed << "; }\n";
+
     OS << "};\n\n";
   }
=20
@@ -600,6 +755,7 @@
   for (; i !=3D e; ++i) {
     Record &R =3D **i;
     std::vector<Record*> ArgRecords =3D R.getValueAsListOfDefs("Args");
+    std::vector<StringRef> Spellings =3D getValueAsListOfStrings(R, "Spell=
ings");
     std::vector<Argument*> Args;
     for (ri =3D ArgRecords.begin(), re =3D ArgRecords.end(); ri !=3D re; +=
+ri)
       Args.push_back(createArgument(**ri, R.getName()));
@@ -615,6 +771,24 @@
       (*ai)->writeCloneArgs(OS);
     }
     OS << ");\n}\n\n";
+
+    OS << "void " << R.getName() << "Attr::printPretty("
+       << "llvm::raw_ostream &OS, ASTContext &Ctx) const {\n";
+    if (Spellings.begin() !=3D Spellings.end()) {
+      OS << "  OS << \" __attribute__((" << *Spellings.begin();
+      if (Args.size()) OS << "(";
+      if (*Spellings.begin()=3D=3D"availability") {
+        writeAvailabilityValue(OS);
+      } else {
+        for (ai =3D Args.begin(); ai !=3D ae; ++ai) {
+          if (ai!=3DArgs.begin()) OS <<", ";
+          (*ai)->writeValue(OS);
+        }
+      }
+      if (Args.size()) OS << ")";
+      OS << "))\";\n";
+    }
+    OS << "}\n\n";
   }
 }
=20
@@ -786,3 +960,133 @@
     }
   }
 }
+
+
+void ClangAttrTemplateInstantiateEmitter::run(raw_ostream &OS) {
+  OS << "// This file is generated by TableGen. Do not edit.\n\n";
+
+  std::vector<Record*> Attrs =3D Records.getAllDerivedDefinitions("Attr");
+
+  OS << "namespace clang {\n"
+     << "namespace sema {\n\n"
+     << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C,=
 "
+     << "Sema &S,\n"
+     << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
+     << "  switch (At->getKind()) {\n"
+     << "    default:\n"
+     << "      break;\n";
+
+  for (std::vector<Record*>::iterator I =3D Attrs.begin(), E =3D Attrs.end=
();
+       I !=3D E; ++I) {
+    Record &R =3D **I;
+
+    OS << "    case attr::" << R.getName() << ": {\n";
+    OS << "      const " << R.getName() << "Attr *A =3D cast<"
+       << R.getName() << "Attr>(At);\n";
+    bool TDependent =3D R.getValueAsBit("TemplateDependent");
+
+    if (!TDependent) {
+      OS << "      return A->clone(C);\n";
+      OS << "    }\n";
+      continue;
+    }
+
+    std::vector<Record*> ArgRecords =3D R.getValueAsListOfDefs("Args");
+    std::vector<Argument*> Args;
+    std::vector<Argument*>::iterator ai, ae;
+    Args.reserve(ArgRecords.size());
+
+    for (std::vector<Record*>::iterator ri =3D ArgRecords.begin(),
+                                        re =3D ArgRecords.end();
+         ri !=3D re; ++ri) {
+      Record &ArgRecord =3D **ri;
+      Argument *Arg =3D createArgument(ArgRecord, R.getName());
+      assert(Arg);
+      Args.push_back(Arg);
+    }
+    ae =3D Args.end();
+
+    for (ai =3D Args.begin(); ai !=3D ae; ++ai) {
+      (*ai)->writeTemplateInstantiation(OS);
+    }
+    OS << "      return new (C) " << R.getName() << "Attr(A->getLocation()=
, C";
+    for (ai =3D Args.begin(); ai !=3D ae; ++ai) {
+      OS << ", ";
+      (*ai)->writeTemplateInstantiationArgs(OS);
+    }
+    OS << ");\n    }\n";
+  }
+  OS << "  } // end switch\n"
+     << "  llvm_unreachable(\"Unknown attribute!\");\n"
+     << "  return 0;\n"
+     << "}\n\n"
+     << "} // end namespace sema\n"
+     << "} // end namespace clang\n";
+}
+
+void ClangAttrParsedAttrListEmitter::run(raw_ostream &OS) {
+  OS << "// This file is generated by TableGen. Do not edit.\n\n";
+ =20
+  OS << "#ifndef PARSED_ATTR\n";
+  OS << "#define PARSED_ATTR(NAME) NAME\n";
+  OS << "#endif\n\n";
+ =20
+  std::vector<Record*> Attrs =3D Records.getAllDerivedDefinitions("Attr");
+  std::set<StringRef> ProcessedAttrs;
+
+  for (std::vector<Record*>::iterator I =3D Attrs.begin(), E =3D Attrs.end=
();
+       I !=3D E; ++I) {
+    Record &Attr =3D **I;
+   =20
+    bool SemaHandler =3D Attr.getValueAsBit("SemaHandler");
+   =20
+    if (SemaHandler) {
+      std::vector<StringRef> Spellings =3D
+        getValueAsListOfStrings(Attr, "Spellings");
+     =20
+      for (std::vector<StringRef>::const_iterator I =3D Spellings.begin(),
+           E =3D Spellings.end(); I !=3D E; ++I) {
+        StringRef AttrName =3D *I;
+
+        AttrName =3D NormalizeAttrName(AttrName);
+        // skip if a normalized version has been processed.
+        if (ProcessedAttrs.find(AttrName) !=3D ProcessedAttrs.end())
+          continue;
+        else
+          ProcessedAttrs.insert(AttrName);
+
+        OS << "PARSED_ATTR(" << AttrName << ")\n";
+      }
+    }
+  }
+}
+
+void ClangAttrParsedAttrKindsEmitter::run(raw_ostream &OS) {
+  OS << "// This file is generated by TableGen. Do not edit.\n\n";
+
+  std::vector<Record*> Attrs =3D Records.getAllDerivedDefinitions("Attr");
+
+  for (std::vector<Record*>::iterator I =3D Attrs.begin(), E =3D Attrs.end=
();
+       I !=3D E; ++I) {
+    Record &Attr =3D **I;
+   =20
+    bool SemaHandler =3D Attr.getValueAsBit("SemaHandler");
+   =20
+    if (SemaHandler) {
+      std::vector<StringRef> Spellings =3D
+        getValueAsListOfStrings(Attr, "Spellings");
+
+      for (std::vector<StringRef>::const_iterator I =3D Spellings.begin(),
+           E =3D Spellings.end(); I !=3D E; ++I) {
+       StringRef AttrName =3D *I, Spelling =3D *I;
+      =20
+       AttrName =3D NormalizeAttrName(AttrName);
+       Spelling =3D NormalizeAttrSpelling(Spelling);
+
+       OS << ".Case(\"" << Spelling << "\", " << "AT_" << AttrName << ")\n=
";
+      }
+    }
+  }
+}
+
+
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/utils/Ta=
bleGen/ClangAttrEmitter.h
--- a/head/contrib/llvm/tools/clang/utils/TableGen/ClangAttrEmitter.h	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/utils/TableGen/ClangAttrEmitter.h	Tue A=
pr 17 11:51:51 2012 +0300
@@ -109,6 +109,45 @@
   void run(raw_ostream &OS);
 };
=20
+/// ClangAttrTemplateInstantiateEmitter emits code to instantiate dependent
+/// attributes on templates.
+class ClangAttrTemplateInstantiateEmitter : public TableGenBackend {
+  RecordKeeper &Records;
+
+ public:
+  explicit ClangAttrTemplateInstantiateEmitter(RecordKeeper &R)
+    : Records(R)
+    {}
+
+  void run(raw_ostream &OS);
+};
+
+/// ClangAttrParsedAttrListEmitter emits the list of parsed attributes
+/// for clang.
+class ClangAttrParsedAttrListEmitter : public TableGenBackend {
+  RecordKeeper &Records;
+
+public:
+  explicit ClangAttrParsedAttrListEmitter(RecordKeeper &R)
+    : Records(R)
+    {}
+
+  void run(raw_ostream &OS);
+};
+
+/// ClangAttrParsedAttrKindsEmitter emits the kind list of parsed attribut=
es
+/// for clang.
+class ClangAttrParsedAttrKindsEmitter : public TableGenBackend {
+  RecordKeeper &Records;
+
+public:
+  explicit ClangAttrParsedAttrKindsEmitter(RecordKeeper &R)
+    : Records(R)
+    {}
+
+  void run(raw_ostream &OS);
+};
+
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/utils/Ta=
bleGen/ClangDiagnosticsEmitter.cpp
--- a/head/contrib/llvm/tools/clang/utils/TableGen/ClangDiagnosticsEmitter.=
cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/utils/TableGen/ClangDiagnosticsEmitter.=
cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -16,13 +16,12 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/ADT/DenseSet.h"
-#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/VectorExtras.h"
 #include <map>
 #include <algorithm>
 #include <functional>
+#include <set>
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -51,7 +50,6 @@
 };
 } // end anonymous namespace.
=20
-
 static std::string
 getCategoryFromDiagGroup(const Record *Group,
                          DiagGroupParentMap &DiagGroupParents) {
@@ -120,8 +118,44 @@
     iterator begin() { return CategoryStrings.begin(); }
     iterator end() { return CategoryStrings.end(); }
   };
+
+  struct GroupInfo {
+    std::vector<const Record*> DiagsInGroup;
+    std::vector<std::string> SubGroups;
+    unsigned IDNo;
+  };
 } // end anonymous namespace.
=20
+/// \brief Invert the 1-[0/1] mapping of diags to group into a one to many
+/// mapping of groups to diags in the group.
+static void groupDiagnostics(const std::vector<Record*> &Diags,
+                             const std::vector<Record*> &DiagGroups,
+                             std::map<std::string, GroupInfo> &DiagsInGrou=
p) {
+  for (unsigned i =3D 0, e =3D Diags.size(); i !=3D e; ++i) {
+    const Record *R =3D Diags[i];
+    DefInit *DI =3D dynamic_cast<DefInit*>(R->getValueInit("Group"));
+    if (DI =3D=3D 0) continue;
+    std::string GroupName =3D DI->getDef()->getValueAsString("GroupName");
+    DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
+  }
+ =20
+  // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up =
empty
+  // groups (these are warnings that GCC supports that clang never produce=
s).
+  for (unsigned i =3D 0, e =3D DiagGroups.size(); i !=3D e; ++i) {
+    Record *Group =3D DiagGroups[i];
+    GroupInfo &GI =3D DiagsInGroup[Group->getValueAsString("GroupName")];
+   =20
+    std::vector<Record*> SubGroups =3D Group->getValueAsListOfDefs("SubGro=
ups");
+    for (unsigned j =3D 0, e =3D SubGroups.size(); j !=3D e; ++j)
+      GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
+  }
+ =20
+  // Assign unique ID numbers to the groups.
+  unsigned IDNo =3D 0;
+  for (std::map<std::string, GroupInfo>::iterator
+       I =3D DiagsInGroup.begin(), E =3D DiagsInGroup.end(); I !=3D E; ++I=
, ++IDNo)
+    I->second.IDNo =3D IDNo;
+}
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 // Warning Tables (.inc file) generation.
@@ -130,7 +164,7 @@
 void ClangDiagsDefsEmitter::run(raw_ostream &OS) {
   // Write the #if guard
   if (!Component.empty()) {
-    std::string ComponentName =3D UppercaseString(Component);
+    std::string ComponentName =3D StringRef(Component).upper();
     OS << "#ifdef " << ComponentName << "START\n";
     OS << "__" << ComponentName << "START =3D DIAG_START_" << ComponentName
        << ",\n";
@@ -140,7 +174,13 @@
=20
   const std::vector<Record*> &Diags =3D
     Records.getAllDerivedDefinitions("Diagnostic");
- =20
+
+  std::vector<Record*> DiagGroups
+    =3D Records.getAllDerivedDefinitions("DiagGroup");
+
+  std::map<std::string, GroupInfo> DiagsInGroup;
+  groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
+
   DiagCategoryIDMap CategoryIDs(Records);
   DiagGroupParentMap DGParentMap(Records);
=20
@@ -158,12 +198,15 @@
     OS << ", \"";
     OS.write_escaped(R.getValueAsString("Text")) << '"';
    =20
-    // Warning associated with the diagnostic.
+    // Warning associated with the diagnostic. This is stored as an index =
into
+    // the alphabetically sorted warning table.
     if (DefInit *DI =3D dynamic_cast<DefInit*>(R.getValueInit("Group"))) {
-      OS << ", \"";
-      OS.write_escaped(DI->getDef()->getValueAsString("GroupName")) << '"';
+      std::map<std::string, GroupInfo>::iterator I =3D
+          DiagsInGroup.find(DI->getDef()->getValueAsString("GroupName"));
+      assert(I !=3D DiagsInGroup.end());
+      OS << ", " << I->second.IDNo;
     } else {
-      OS << ", \"\"";
+      OS << ", 0";
     }
=20
     // SFINAE bit
@@ -196,14 +239,6 @@
  =20
     // Category number.
     OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap)=
);
-
-    // Brief
-    OS << ", \"";
-    OS.write_escaped(R.getValueAsString("Brief")) << '"';
-
-    // Explanation=20
-    OS << ", \"";
-    OS.write_escaped(R.getValueAsString("Explanation")) << '"';
     OS << ")\n";
   }
 }
@@ -215,56 +250,24 @@
 static std::string getDiagCategoryEnum(llvm::StringRef name) {
   if (name.empty())
     return "DiagCat_None";
-  llvm::SmallString<256> enumName =3D llvm::StringRef("DiagCat_");
+  SmallString<256> enumName =3D llvm::StringRef("DiagCat_");
   for (llvm::StringRef::iterator I =3D name.begin(), E =3D name.end(); I !=
=3D E; ++I)
     enumName +=3D isalnum(*I) ? *I : '_';
   return enumName.str();
 }
=20
-namespace {
-struct GroupInfo {
-  std::vector<const Record*> DiagsInGroup;
-  std::vector<std::string> SubGroups;
-  unsigned IDNo;
-};
-} // end anonymous namespace.
-
 void ClangDiagGroupsEmitter::run(raw_ostream &OS) {
   // Compute a mapping from a DiagGroup to all of its parents.
   DiagGroupParentMap DGParentMap(Records);
  =20
-  // Invert the 1-[0/1] mapping of diags to group into a one to many mappi=
ng of
-  // groups to diags in the group.
-  std::map<std::string, GroupInfo> DiagsInGroup;
- =20
   std::vector<Record*> Diags =3D
     Records.getAllDerivedDefinitions("Diagnostic");
-  for (unsigned i =3D 0, e =3D Diags.size(); i !=3D e; ++i) {
-    const Record *R =3D Diags[i];
-    DefInit *DI =3D dynamic_cast<DefInit*>(R->getValueInit("Group"));
-    if (DI =3D=3D 0) continue;
-    std::string GroupName =3D DI->getDef()->getValueAsString("GroupName");
-    DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
-  }
  =20
-  // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up =
empty
-  // groups (these are warnings that GCC supports that clang never produce=
s).
   std::vector<Record*> DiagGroups
     =3D Records.getAllDerivedDefinitions("DiagGroup");
-  for (unsigned i =3D 0, e =3D DiagGroups.size(); i !=3D e; ++i) {
-    Record *Group =3D DiagGroups[i];
-    GroupInfo &GI =3D DiagsInGroup[Group->getValueAsString("GroupName")];
-   =20
-    std::vector<Record*> SubGroups =3D Group->getValueAsListOfDefs("SubGro=
ups");
-    for (unsigned j =3D 0, e =3D SubGroups.size(); j !=3D e; ++j)
-      GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
-  }
- =20
-  // Assign unique ID numbers to the groups.
-  unsigned IDNo =3D 0;
-  for (std::map<std::string, GroupInfo>::iterator
-       I =3D DiagsInGroup.begin(), E =3D DiagsInGroup.end(); I !=3D E; ++I=
, ++IDNo)
-    I->second.IDNo =3D IDNo;
+
+  std::map<std::string, GroupInfo> DiagsInGroup;
+  groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
  =20
   // Walk through the groups emitting an array for each diagnostic of the =
diags
   // that are mapped to.
@@ -304,6 +307,10 @@
     OS << "  { ";
     OS << I->first.size() << ", ";
     OS << "\"";
+    if (I->first.find_first_not_of("abcdefghijklmnopqrstuvwxyz"
+                                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+                                   "0123456789!@#$%^*-+=3D:?")!=3Dstd::str=
ing::npos)
+      throw "Invalid character in diagnostic group '" + I->first + "'";
     OS.write_escaped(I->first) << "\","
                                << std::string(MaxLen-I->first.size()+1, ' =
');
    =20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/utils/Ta=
bleGen/NeonEmitter.cpp
--- a/head/contrib/llvm/tools/clang/utils/TableGen/NeonEmitter.cpp	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/utils/TableGen/NeonEmitter.cpp	Tue Apr =
17 11:51:51 2012 +0300
@@ -28,6 +28,7 @@
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <string>
=20
 using namespace llvm;
@@ -56,7 +57,6 @@
       default:
         throw TGError(r->getLoc(),
                       "Unexpected letter: " + std::string(data + len, 1));
-        break;
     }
     TV.push_back(StringRef(data, len + 1));
     data +=3D len + 1;
@@ -78,7 +78,6 @@
       return 'f';
     default: throw "unhandled type in widen!";
   }
-  return '\0';
 }
=20
 /// Narrow - Convert a type code into the next smaller type.  short -> cha=
r,
@@ -95,7 +94,6 @@
       return 'h';
     default: throw "unhandled type in narrow!";
   }
-  return '\0';
 }
=20
 /// For a particular StringRef, return the base type code, and whether it =
has
@@ -266,7 +264,6 @@
       break;
     default:
       throw "unhandled type!";
-      break;
   }
=20
   if (mod =3D=3D '2')
@@ -449,7 +446,6 @@
     break;
   default:
     throw "unhandled type!";
-    break;
   }
   if (ck =3D=3D ClassB)
     s +=3D "_v";
@@ -526,12 +522,6 @@
   for (unsigned i =3D 1, e =3D proto.size(); i !=3D e; ++i, ++arg) {
     // Do not create a temporary for an immediate argument.
     // That would defeat the whole point of using a macro!
-    // FIXME: For other (non-immediate) arguments that are used directly, a
-    // local temporary (or some other method) is still needed to get the
-    // correct type checking, even if that temporary is not used for anyth=
ing.
-    // This is omitted for now because it turns out the the use of
-    // "__extension__" in the macro disables any warnings from the pointer
-    // assignment.
     if (MacroArgUsedDirectly(proto, i))
       continue;
     generatedLocal =3D true;
@@ -594,7 +584,6 @@
   case 'f': nElts =3D 2; break;
   default:
     throw "unhandled type!";
-    break;
   }
   if (quad) nElts <<=3D 1;
   return nElts;
@@ -826,14 +815,12 @@
   }
   default:
     throw "unknown OpKind!";
-    break;
   }
   return s;
 }
=20
 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
   unsigned mod =3D proto[0];
-  unsigned ret =3D 0;
=20
   if (mod =3D=3D 'v' || mod =3D=3D 'f')
     mod =3D proto[1];
@@ -851,35 +838,31 @@
   // Based on the modifying character, change the type and width if necess=
ary.
   type =3D ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
=20
-  if (usgn)
-    ret |=3D 0x08;
-  if (quad && proto[1] !=3D 'g')
-    ret |=3D 0x10;
-
+  NeonTypeFlags::EltType ET;
   switch (type) {
     case 'c':
-      ret |=3D poly ? 5 : 0;
+      ET =3D poly ? NeonTypeFlags::Poly8 : NeonTypeFlags::Int8;
       break;
     case 's':
-      ret |=3D poly ? 6 : 1;
+      ET =3D poly ? NeonTypeFlags::Poly16 : NeonTypeFlags::Int16;
       break;
     case 'i':
-      ret |=3D 2;
+      ET =3D NeonTypeFlags::Int32;
       break;
     case 'l':
-      ret |=3D 3;
+      ET =3D NeonTypeFlags::Int64;
       break;
     case 'h':
-      ret |=3D 7;
+      ET =3D NeonTypeFlags::Float16;
       break;
     case 'f':
-      ret |=3D 4;
+      ET =3D NeonTypeFlags::Float32;
       break;
     default:
       throw "unhandled type!";
-      break;
   }
-  return ret;
+  NeonTypeFlags Flags(ET, usgn, quad && proto[1] !=3D 'g');
+  return Flags.getFlags();
 }
=20
 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
@@ -1249,10 +1232,7 @@
       return (1 << (int)quad) - 1;
     default:
       throw "unhandled type!";
-      break;
   }
-  assert(0 && "unreachable");
-  return 0;
 }
=20
 /// runHeader - Emit a file with sections defining:
@@ -1346,14 +1326,57 @@
         mask |=3D 1 << GetNeonEnum(Proto, TypeVec[ti]);
       }
     }
-    if (mask)
+
+    // Check if the builtin function has a pointer or const pointer argume=
nt.
+    int PtrArgNum =3D -1;
+    bool HasConstPtr =3D false;
+    for (unsigned arg =3D 1, arge =3D Proto.size(); arg !=3D arge; ++arg) {
+      char ArgType =3D Proto[arg];
+      if (ArgType =3D=3D 'c') {
+        HasConstPtr =3D true;
+        PtrArgNum =3D arg - 1;
+        break;
+      }
+      if (ArgType =3D=3D 'p') {
+        PtrArgNum =3D arg - 1;
+        break;
+      }
+    }
+    // For sret builtins, adjust the pointer argument index.
+    if (PtrArgNum >=3D 0 && (Proto[0] >=3D '2' && Proto[0] <=3D '4'))
+      PtrArgNum +=3D 1;
+
+    // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
+    // and vst1_lane intrinsics.  Using a pointer to the vector element
+    // type with one of those operations causes codegen to select an align=
ed
+    // load/store instruction.  If you want an unaligned operation,
+    // the pointer argument needs to have less alignment than element type,
+    // so just accept any pointer type.
+    if (name =3D=3D "vld1_lane" || name =3D=3D "vld1_dup" || name =3D=3D "=
vst1_lane") {
+      PtrArgNum =3D -1;
+      HasConstPtr =3D false;
+    }
+
+    if (mask) {
       OS << "case ARM::BI__builtin_neon_"
          << MangleName(name, TypeVec[si], ClassB)
-         << ": mask =3D " << "0x" << utohexstr(mask) << "; break;\n";
-    if (qmask)
+         << ": mask =3D " << "0x" << utohexstr(mask);
+      if (PtrArgNum >=3D 0)
+        OS << "; PtrArgNum =3D " << PtrArgNum;
+      if (HasConstPtr)
+        OS << "; HasConstPtr =3D true";
+      OS << "; break;\n";
+    }
+    if (qmask) {
       OS << "case ARM::BI__builtin_neon_"
          << MangleName(name, TypeVec[qi], ClassB)
-         << ": mask =3D " << "0x" << utohexstr(qmask) << "; break;\n";
+         << ": mask =3D " << "0x" << utohexstr(qmask);
+      if (PtrArgNum >=3D 0)
+        OS << "; PtrArgNum =3D " << PtrArgNum;
+      if (HasConstPtr)
+        OS << "; HasConstPtr =3D true";
+      OS << "; break;\n";
+    }
   }
   OS << "#endif\n\n";
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/utils/Ta=
bleGen/NeonEmitter.h
--- a/head/contrib/llvm/tools/clang/utils/TableGen/NeonEmitter.h	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/utils/TableGen/NeonEmitter.h	Tue Apr 17=
 11:51:51 2012 +0300
@@ -86,6 +86,40 @@
   ClassB            // bitcast arguments with enum argument to specify type
 };
=20
+/// NeonTypeFlags - Flags to identify the types for overloaded Neon
+/// builtins.  These must be kept in sync with the flags in
+/// include/clang/Basic/TargetBuiltins.h.
+class NeonTypeFlags {
+  enum {
+    EltTypeMask =3D 0xf,
+    UnsignedFlag =3D 0x10,
+    QuadFlag =3D 0x20
+  };
+  uint32_t Flags;
+
+public:
+  enum EltType {
+    Int8,
+    Int16,
+    Int32,
+    Int64,
+    Poly8,
+    Poly16,
+    Float16,
+    Float32
+  };
+
+  NeonTypeFlags(unsigned F) : Flags(F) {}
+  NeonTypeFlags(EltType ET, bool IsUnsigned, bool IsQuad) : Flags(ET) {
+    if (IsUnsigned)
+      Flags |=3D UnsignedFlag;
+    if (IsQuad)
+      Flags |=3D QuadFlag;
+  }
+
+  uint32_t getFlags() const { return Flags; }
+};
+
 namespace llvm {
=20
   class NeonEmitter : public TableGenBackend {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/clang/utils/Ta=
bleGen/TableGen.cpp
--- a/head/contrib/llvm/tools/clang/utils/TableGen/TableGen.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/clang/utils/TableGen/TableGen.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -36,6 +36,9 @@
   GenClangAttrPCHWrite,
   GenClangAttrSpellingList,
   GenClangAttrLateParsedList,
+  GenClangAttrTemplateInstantiate,
+  GenClangAttrParsedAttrList,
+  GenClangAttrParsedAttrKinds,
   GenClangDiagsDefs,
   GenClangDiagGroups,
   GenClangDiagsIndexName,
@@ -71,6 +74,15 @@
                     clEnumValN(GenClangAttrLateParsedList,
                                "gen-clang-attr-late-parsed-list",
                                "Generate a clang attribute LateParsed list=
"),
+                    clEnumValN(GenClangAttrTemplateInstantiate,
+                               "gen-clang-attr-template-instantiate",
+                               "Generate a clang template instantiate code=
"),
+                    clEnumValN(GenClangAttrParsedAttrList,
+                               "gen-clang-attr-parsed-attr-list",
+                               "Generate a clang parsed attribute list"),
+                    clEnumValN(GenClangAttrParsedAttrKinds,
+                               "gen-clang-attr-parsed-attr-kinds",
+                               "Generate a clang parsed attribute kinds"),
                     clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs",
                                "Generate Clang diagnostics definitions"),
                     clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups",
@@ -96,7 +108,6 @@
   ClangComponent("clang-component",
                  cl::desc("Only use warnings from specified component"),
                  cl::value_desc("component"), cl::Hidden);
-}
=20
 class ClangTableGenAction : public TableGenAction {
 public:
@@ -123,6 +134,15 @@
     case GenClangAttrLateParsedList:
       ClangAttrLateParsedListEmitter(Records).run(OS);
       break;
+    case GenClangAttrTemplateInstantiate:
+      ClangAttrTemplateInstantiateEmitter(Records).run(OS);
+      break;
+    case GenClangAttrParsedAttrList:
+      ClangAttrParsedAttrListEmitter(Records).run(OS);
+      break;
+    case GenClangAttrParsedAttrKinds:
+      ClangAttrParsedAttrKindsEmitter(Records).run(OS);
+      break;
     case GenClangDiagsDefs:
       ClangDiagsDefsEmitter(Records, ClangComponent).run(OS);
       break;
@@ -157,14 +177,12 @@
     case GenArmNeonTest:
       NeonEmitter(Records).runTests(OS);
       break;
-    default:
-      assert(1 && "Invalid Action");
-      return true;
     }
=20
     return false;
   }
 };
+}
=20
 int main(int argc, char **argv) {
   sys::PrintStackTraceOnErrorSignal();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llc/llc.cpp
--- a/head/contrib/llvm/tools/llc/llc.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/llc/llc.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,6 @@
 #include "llvm/Support/IRReader.h"
 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
-#include "llvm/Config/config.h"
 #include "llvm/MC/SubtargetFeature.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
@@ -133,11 +132,147 @@
 cl::opt<bool> DisableCFI("disable-cfi", cl::Hidden,
                          cl::desc("Do not use .cfi_* directives"));
=20
+cl::opt<bool> EnableDwarfDirectory("enable-dwarf-directory", cl::Hidden,
+    cl::desc("Use .file directives with an explicit directory."));
+
 static cl::opt<bool>
 DisableRedZone("disable-red-zone",
   cl::desc("Do not emit code that uses the red zone."),
   cl::init(false));
=20
+static cl::opt<bool>
+EnableFPMAD("enable-fp-mad",
+  cl::desc("Enable less precise MAD instructions to be generated"),
+  cl::init(false));
+
+static cl::opt<bool>
+PrintCode("print-machineinstrs",
+  cl::desc("Print generated machine code"),
+  cl::init(false));
+
+static cl::opt<bool>
+DisableFPElim("disable-fp-elim",
+  cl::desc("Disable frame pointer elimination optimization"),
+  cl::init(false));
+
+static cl::opt<bool>
+DisableFPElimNonLeaf("disable-non-leaf-fp-elim",
+  cl::desc("Disable frame pointer elimination optimization for non-leaf fu=
ncs"),
+  cl::init(false));
+
+static cl::opt<bool>
+DisableExcessPrecision("disable-excess-fp-precision",
+  cl::desc("Disable optimizations that may increase FP precision"),
+  cl::init(false));
+
+static cl::opt<bool>
+EnableUnsafeFPMath("enable-unsafe-fp-math",
+  cl::desc("Enable optimizations that may decrease FP precision"),
+  cl::init(false));
+
+static cl::opt<bool>
+EnableNoInfsFPMath("enable-no-infs-fp-math",
+  cl::desc("Enable FP math optimizations that assume no +-Infs"),
+  cl::init(false));
+
+static cl::opt<bool>
+EnableNoNaNsFPMath("enable-no-nans-fp-math",
+  cl::desc("Enable FP math optimizations that assume no NaNs"),
+  cl::init(false));
+
+static cl::opt<bool>
+EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-=
math",
+  cl::Hidden,
+  cl::desc("Force codegen to assume rounding mode can change dynamically"),
+  cl::init(false));
+
+static cl::opt<bool>
+GenerateSoftFloatCalls("soft-float",
+  cl::desc("Generate software floating point library calls"),
+  cl::init(false));
+
+static cl::opt<llvm::FloatABI::ABIType>
+FloatABIForCalls("float-abi",
+  cl::desc("Choose float ABI type"),
+  cl::init(FloatABI::Default),
+  cl::values(
+    clEnumValN(FloatABI::Default, "default",
+               "Target default float ABI type"),
+    clEnumValN(FloatABI::Soft, "soft",
+               "Soft float ABI (implied by -soft-float)"),
+    clEnumValN(FloatABI::Hard, "hard",
+               "Hard float ABI (uses FP registers)"),
+    clEnumValEnd));
+
+static cl::opt<bool>
+DontPlaceZerosInBSS("nozero-initialized-in-bss",
+  cl::desc("Don't place zero-initialized symbols into bss section"),
+  cl::init(false));
+
+static cl::opt<bool>
+EnableJITExceptionHandling("jit-enable-eh",
+  cl::desc("Emit exception handling information"),
+  cl::init(false));
+
+// In debug builds, make this default to true.
+#ifdef NDEBUG
+#define EMIT_DEBUG false
+#else
+#define EMIT_DEBUG true
+#endif
+static cl::opt<bool>
+EmitJitDebugInfo("jit-emit-debug",
+  cl::desc("Emit debug information to debugger"),
+  cl::init(EMIT_DEBUG));
+#undef EMIT_DEBUG
+
+static cl::opt<bool>
+EmitJitDebugInfoToDisk("jit-emit-debug-to-disk",
+  cl::Hidden,
+  cl::desc("Emit debug info objfiles to disk"),
+  cl::init(false));
+
+static cl::opt<bool>
+EnableGuaranteedTailCallOpt("tailcallopt",
+  cl::desc("Turn fastcc calls into tail calls by (potentially) changing AB=
I."),
+  cl::init(false));
+
+static cl::opt<bool>
+DisableTailCalls("disable-tail-calls",
+  cl::desc("Never emit tail calls"),
+  cl::init(false));
+
+static cl::opt<unsigned>
+OverrideStackAlignment("stack-alignment",
+  cl::desc("Override default stack alignment"),
+  cl::init(0));
+
+static cl::opt<bool>
+EnableRealignStack("realign-stack",
+  cl::desc("Realign stack if needed"),
+  cl::init(true));
+
+static cl::opt<bool>
+DisableSwitchTables(cl::Hidden, "disable-jump-tables",
+  cl::desc("Do not generate jump tables."),
+  cl::init(false));
+
+static cl::opt<std::string>
+TrapFuncName("trap-func", cl::Hidden,
+  cl::desc("Emit a call to trap function rather than a trap instruction"),
+  cl::init(""));
+
+static cl::opt<bool>
+EnablePIE("enable-pie",
+  cl::desc("Assume the creation of a position independent executable."),
+  cl::init(false));
+
+static cl::opt<bool>
+SegmentedStacks("segmented-stacks",
+  cl::desc("Use segmented stacks if possible."),
+  cl::init(false));
+
+
 // GetFileNameRoot - Helper function to get the basename of a filename.
 static inline std::string
 GetFileNameRoot(const std::string &InputFilename) {
@@ -166,7 +301,6 @@
       OutputFilename =3D GetFileNameRoot(InputFilename);
=20
       switch (FileType) {
-      default: assert(0 && "Unknown file type");
       case TargetMachine::CGFT_AssemblyFile:
         if (TargetName[0] =3D=3D 'c') {
           if (TargetName[1] =3D=3D 0)
@@ -194,7 +328,6 @@
   // Decide if we need "binary" output.
   bool Binary =3D false;
   switch (FileType) {
-  default: assert(0 && "Unknown file type");
   case TargetMachine::CGFT_AssemblyFile:
     break;
   case TargetMachine::CGFT_ObjectFile:
@@ -247,7 +380,7 @@
=20
   M.reset(ParseIRFile(InputFilename, Err, Context));
   if (M.get() =3D=3D 0) {
-    Err.Print(argv[0], errs());
+    Err.print(argv[0], errs());
     return 1;
   }
   Module &mod =3D *M.get();
@@ -258,7 +391,7 @@
=20
   Triple TheTriple(mod.getTargetTriple());
   if (TheTriple.getTriple().empty())
-    TheTriple.setTriple(sys::getHostTriple());
+    TheTriple.setTriple(sys::getDefaultTargetTriple());
=20
   // Allocate target machine.  First, check whether the user has explicitly
   // specified an architecture to compile for. If so we have to look it up=
 by
@@ -303,29 +436,6 @@
     FeaturesStr =3D Features.getString();
   }
=20
-  std::auto_ptr<TargetMachine>
-    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
-                                          MCPU, FeaturesStr,
-                                          RelocModel, CMModel));
-  assert(target.get() && "Could not allocate target machine!");
-  TargetMachine &Target =3D *target.get();
-
-  if (DisableDotLoc)
-    Target.setMCUseLoc(false);
-
-  if (DisableCFI)
-    Target.setMCUseCFI(false);
-
-  // Disable .loc support for older OS X versions.
-  if (TheTriple.isMacOSX() &&
-      TheTriple.isMacOSXVersionLT(10, 6))
-    Target.setMCUseLoc(false);
-
-  // Figure out where we are going to send the output...
-  OwningPtr<tool_output_file> Out
-    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
-  if (!Out) return 1;
-
   CodeGenOpt::Level OLvl =3D CodeGenOpt::Default;
   switch (OptLevel) {
   default:
@@ -338,6 +448,62 @@
   case '3': OLvl =3D CodeGenOpt::Aggressive; break;
   }
=20
+  TargetOptions Options;
+  Options.LessPreciseFPMADOption =3D EnableFPMAD;
+  Options.PrintMachineCode =3D PrintCode;
+  Options.NoFramePointerElim =3D DisableFPElim;
+  Options.NoFramePointerElimNonLeaf =3D DisableFPElimNonLeaf;
+  Options.NoExcessFPPrecision =3D DisableExcessPrecision;
+  Options.UnsafeFPMath =3D EnableUnsafeFPMath;
+  Options.NoInfsFPMath =3D EnableNoInfsFPMath;
+  Options.NoNaNsFPMath =3D EnableNoNaNsFPMath;
+  Options.HonorSignDependentRoundingFPMathOption =3D
+      EnableHonorSignDependentRoundingFPMath;
+  Options.UseSoftFloat =3D GenerateSoftFloatCalls;
+  if (FloatABIForCalls !=3D FloatABI::Default)
+    Options.FloatABIType =3D FloatABIForCalls;
+  Options.NoZerosInBSS =3D DontPlaceZerosInBSS;
+  Options.JITExceptionHandling =3D EnableJITExceptionHandling;
+  Options.JITEmitDebugInfo =3D EmitJitDebugInfo;
+  Options.JITEmitDebugInfoToDisk =3D EmitJitDebugInfoToDisk;
+  Options.GuaranteedTailCallOpt =3D EnableGuaranteedTailCallOpt;
+  Options.DisableTailCalls =3D DisableTailCalls;
+  Options.StackAlignmentOverride =3D OverrideStackAlignment;
+  Options.RealignStack =3D EnableRealignStack;
+  Options.DisableJumpTables =3D DisableSwitchTables;
+  Options.TrapFuncName =3D TrapFuncName;
+  Options.PositionIndependentExecutable =3D EnablePIE;
+  Options.EnableSegmentedStacks =3D SegmentedStacks;
+
+  std::auto_ptr<TargetMachine>
+    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
+                                          MCPU, FeaturesStr, Options,
+                                          RelocModel, CMModel, OLvl));
+  assert(target.get() && "Could not allocate target machine!");
+  TargetMachine &Target =3D *target.get();
+
+  if (DisableDotLoc)
+    Target.setMCUseLoc(false);
+
+  if (DisableCFI)
+    Target.setMCUseCFI(false);
+
+  if (EnableDwarfDirectory)
+    Target.setMCUseDwarfDirectory(true);
+
+  if (GenerateSoftFloatCalls)
+    FloatABIForCalls =3D FloatABI::Soft;
+
+  // Disable .loc support for older OS X versions.
+  if (TheTriple.isMacOSX() &&
+      TheTriple.isMacOSXVersionLT(10, 6))
+    Target.setMCUseLoc(false);
+
+  // Figure out where we are going to send the output...
+  OwningPtr<tool_output_file> Out
+    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
+  if (!Out) return 1;
+
   // Build up all of the passes that we want to do to the module.
   PassManager PM;
=20
@@ -362,7 +528,7 @@
     formatted_raw_ostream FOS(Out->os());
=20
     // Ask the target to add backend passes as necessary.
-    if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
+    if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify)) {
       errs() << argv[0] << ": target does not support generation of this"
              << " file type!\n";
       return 1;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/lli/lli.cpp
--- a/head/contrib/llvm/tools/lli/lli.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/lli/lli.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -23,6 +23,7 @@
 #include "llvm/ExecutionEngine/Interpreter.h"
 #include "llvm/ExecutionEngine/JIT.h"
 #include "llvm/ExecutionEngine/JITEventListener.h"
+#include "llvm/ExecutionEngine/JITMemoryManager.h"
 #include "llvm/ExecutionEngine/MCJIT.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/IRReader.h"
@@ -94,12 +95,12 @@
                      "of the executable"),
             cl::value_desc("function"),
             cl::init("main"));
- =20
+
   cl::opt<std::string>
   FakeArgv0("fake-argv0",
             cl::desc("Override the 'argv[0]' value passed into the executi=
ng"
                      " program"), cl::value_desc("executable"));
- =20
+
   cl::opt<bool>
   DisableCoreFiles("disable-core-files", cl::Hidden,
                    cl::desc("Disable emission of core files if possible"));
@@ -158,7 +159,7 @@
 int main(int argc, char **argv, char * const *envp) {
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
- =20
+
   LLVMContext &Context =3D getGlobalContext();
   atexit(do_shutdown);  // Call llvm_shutdown() on exit.
=20
@@ -173,12 +174,12 @@
   // If the user doesn't want core files, disable them.
   if (DisableCoreFiles)
     sys::Process::PreventCoreFiles();
- =20
+
   // Load the bitcode...
   SMDiagnostic Err;
   Module *Mod =3D ParseIRFile(InputFile, Err, Context);
   if (!Mod) {
-    Err.Print(argv[0], errs());
+    Err.print(argv[0], errs());
     return 1;
   }
=20
@@ -199,6 +200,8 @@
   builder.setRelocationModel(RelocModel);
   builder.setCodeModel(CMModel);
   builder.setErrorStr(&ErrorMsg);
+  builder.setJITMemoryManager(ForceInterpreter ? 0 :
+                              JITMemoryManager::CreateDefaultMemManager());
   builder.setEngineKind(ForceInterpreter
                         ? EngineKind::Interpreter
                         : EngineKind::JIT);
@@ -207,9 +210,11 @@
   if (!TargetTriple.empty())
     Mod->setTargetTriple(Triple::normalize(TargetTriple));
=20
-  // Enable MCJIT, if desired.
-  if (UseMCJIT)
+  // Enable MCJIT if desired.
+  if (UseMCJIT && !ForceInterpreter) {
     builder.setUseMCJIT(true);
+    builder.setJITMemoryManager(JITMemoryManager::CreateDefaultMemManager(=
));
+  }
=20
   CodeGenOpt::Level OLvl =3D CodeGenOpt::Default;
   switch (OptLevel) {
@@ -233,7 +238,12 @@
     exit(1);
   }
=20
-  EE->RegisterJITEventListener(createOProfileJITEventListener());
+  // The following functions have no effect if their respective profiling
+  // support wasn't enabled in the build configuration.
+  EE->RegisterJITEventListener(
+                JITEventListener::createOProfileJITEventListener());
+  EE->RegisterJITEventListener(
+                JITEventListener::createIntelJITEventListener());
=20
   EE->DisableLazyCompilation(NoLazyCompilation);
=20
@@ -262,15 +272,15 @@
     return -1;
   }
=20
-  // If the program doesn't explicitly call exit, we will need the Exit=20
-  // function later on to make an explicit call, so get the function now.=20
+  // If the program doesn't explicitly call exit, we will need the Exit
+  // function later on to make an explicit call, so get the function now.
   Constant *Exit =3D Mod->getOrInsertFunction("exit", Type::getVoidTy(Cont=
ext),
                                                     Type::getInt32Ty(Conte=
xt),
                                                     NULL);
- =20
+
   // Reset errno to zero on entry to main.
   errno =3D 0;
-=20
+
   // Run static constructors.
   EE->runStaticConstructorsDestructors(false);
=20
@@ -287,8 +297,8 @@
=20
   // Run static destructors.
   EE->runStaticConstructorsDestructors(true);
- =20
-  // If the program didn't call exit explicitly, we should call it now.=20
+
+  // If the program didn't call exit explicitly, we should call it now.
   // This ensures that any atexit handlers get called correctly.
   if (Function *ExitF =3D dyn_cast<Function>(Exit)) {
     std::vector<GenericValue> Args;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-as/llvm-a=
s.cpp
--- a/head/contrib/llvm/tools/llvm-as/llvm-as.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/tools/llvm-as/llvm-as.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -96,7 +96,7 @@
   SMDiagnostic Err;
   std::auto_ptr<Module> M(ParseAssemblyFile(InputFilename, Err, Context));
   if (M.get() =3D=3D 0) {
-    Err.Print(argv[0], errs());
+    Err.print(argv[0], errs());
     return 1;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-bcanalyze=
r/llvm-bcanalyzer.cpp
--- a/head/contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-bcanalyzer/llvm-bcanalyzer.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -102,14 +102,13 @@
   default:                           return 0;
   case bitc::MODULE_BLOCK_ID:        return "MODULE_BLOCK";
   case bitc::PARAMATTR_BLOCK_ID:     return "PARAMATTR_BLOCK";
-  case bitc::TYPE_BLOCK_ID_OLD:      return "TYPE_BLOCK_ID_OLD";
   case bitc::TYPE_BLOCK_ID_NEW:      return "TYPE_BLOCK_ID";
   case bitc::CONSTANTS_BLOCK_ID:     return "CONSTANTS_BLOCK";
   case bitc::FUNCTION_BLOCK_ID:      return "FUNCTION_BLOCK";
-  case bitc::TYPE_SYMTAB_BLOCK_ID_OLD: return "TYPE_SYMTAB_OLD";
   case bitc::VALUE_SYMTAB_BLOCK_ID:  return "VALUE_SYMTAB";
   case bitc::METADATA_BLOCK_ID:      return "METADATA_BLOCK";
   case bitc::METADATA_ATTACHMENT_ID: return "METADATA_ATTACHMENT_BLOCK";
+  case bitc::USELIST_BLOCK_ID:       return "USELIST_BLOCK_ID";
   }
 }
=20
@@ -163,7 +162,6 @@
     default: return 0;
     case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
     }
-  case bitc::TYPE_BLOCK_ID_OLD:
   case bitc::TYPE_BLOCK_ID_NEW:
     switch (CodeID) {
     default: return 0;
@@ -175,8 +173,6 @@
     case bitc::TYPE_CODE_OPAQUE:       return "OPAQUE";
     case bitc::TYPE_CODE_INTEGER:      return "INTEGER";
     case bitc::TYPE_CODE_POINTER:      return "POINTER";
-    case bitc::TYPE_CODE_FUNCTION:     return "FUNCTION";
-    case bitc::TYPE_CODE_STRUCT_OLD:   return "STRUCT_OLD";
     case bitc::TYPE_CODE_ARRAY:        return "ARRAY";
     case bitc::TYPE_CODE_VECTOR:       return "VECTOR";
     case bitc::TYPE_CODE_X86_FP80:     return "X86_FP80";
@@ -186,6 +182,7 @@
     case bitc::TYPE_CODE_STRUCT_ANON:  return "STRUCT_ANON";
     case bitc::TYPE_CODE_STRUCT_NAME:  return "STRUCT_NAME";
     case bitc::TYPE_CODE_STRUCT_NAMED: return "STRUCT_NAMED";
+    case bitc::TYPE_CODE_FUNCTION:     return "FUNCTION";
     }
=20
   case bitc::CONSTANTS_BLOCK_ID:
@@ -211,6 +208,8 @@
     case bitc::CST_CODE_CE_CMP:          return "CE_CMP";
     case bitc::CST_CODE_INLINEASM:       return "INLINEASM";
     case bitc::CST_CODE_CE_SHUFVEC_EX:   return "CE_SHUFVEC_EX";
+    case bitc::CST_CODE_BLOCKADDRESS:    return "CST_CODE_BLOCKADDRESS";
+    case bitc::CST_CODE_DATA:            return "DATA";
     }
   case bitc::FUNCTION_BLOCK_ID:
     switch (CodeID) {
@@ -231,7 +230,6 @@
     case bitc::FUNC_CODE_INST_BR:           return "INST_BR";
     case bitc::FUNC_CODE_INST_SWITCH:       return "INST_SWITCH";
     case bitc::FUNC_CODE_INST_INVOKE:       return "INST_INVOKE";
-    case bitc::FUNC_CODE_INST_UNWIND:       return "INST_UNWIND";
     case bitc::FUNC_CODE_INST_UNREACHABLE:  return "INST_UNREACHABLE";
=20
     case bitc::FUNC_CODE_INST_PHI:          return "INST_PHI";
@@ -247,11 +245,6 @@
     case bitc::FUNC_CODE_INST_CALL:         return "INST_CALL";
     case bitc::FUNC_CODE_DEBUG_LOC:         return "DEBUG_LOC";
     }
-  case bitc::TYPE_SYMTAB_BLOCK_ID_OLD:
-    switch (CodeID) {
-    default: return 0;
-    case bitc::TST_CODE_ENTRY: return "ENTRY";
-    }
   case bitc::VALUE_SYMTAB_BLOCK_ID:
     switch (CodeID) {
     default: return 0;
@@ -273,6 +266,11 @@
     case bitc::METADATA_FN_NODE:     return "METADATA_FN_NODE";
     case bitc::METADATA_NAMED_NODE:  return "METADATA_NAMED_NODE";
     }
+  case bitc::USELIST_BLOCK_ID:
+    switch(CodeID) {
+    default:return 0;
+    case bitc::USELIST_CODE_ENTRY:   return "USELIST_CODE_ENTRY";
+    }
   }
 }
=20
@@ -333,7 +331,7 @@
=20
   // BLOCKINFO is a special part of the stream.
   if (BlockID =3D=3D bitc::BLOCKINFO_BLOCK_ID) {
-    if (Dump) errs() << Indent << "<BLOCKINFO_BLOCK/>\n";
+    if (Dump) outs() << Indent << "<BLOCKINFO_BLOCK/>\n";
     if (Stream.ReadBlockInfoBlock())
       return Error("Malformed BlockInfoBlock");
     uint64_t BlockBitEnd =3D Stream.GetCurrentBitNo();
@@ -347,16 +345,16 @@
=20
   const char *BlockName =3D 0;
   if (Dump) {
-    errs() << Indent << "<";
+    outs() << Indent << "<";
     if ((BlockName =3D GetBlockName(BlockID, *Stream.getBitStreamReader())=
))
-      errs() << BlockName;
+      outs() << BlockName;
     else
-      errs() << "UnknownBlock" << BlockID;
+      outs() << "UnknownBlock" << BlockID;
=20
     if (NonSymbolic && BlockName)
-      errs() << " BlockID=3D" << BlockID;
+      outs() << " BlockID=3D" << BlockID;
=20
-    errs() << " NumWords=3D" << NumWords
+    outs() << " NumWords=3D" << NumWords
            << " BlockCodeSize=3D" << Stream.GetAbbrevIDWidth() << ">\n";
   }
=20
@@ -378,11 +376,11 @@
       uint64_t BlockBitEnd =3D Stream.GetCurrentBitNo();
       BlockStats.NumBits +=3D BlockBitEnd-BlockBitStart;
       if (Dump) {
-        errs() << Indent << "</";
+        outs() << Indent << "</";
         if (BlockName)
-          errs() << BlockName << ">\n";
+          outs() << BlockName << ">\n";
         else
-          errs() << "UnknownBlock" << BlockID << ">\n";
+          outs() << "UnknownBlock" << BlockID << ">\n";
       }
       return false;
     }
@@ -424,25 +422,25 @@
         BlockStats.CodeFreq[Code].NumAbbrev++;
=20
       if (Dump) {
-        errs() << Indent << "  <";
+        outs() << Indent << "  <";
         if (const char *CodeName =3D
               GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
-          errs() << CodeName;
+          outs() << CodeName;
         else
-          errs() << "UnknownCode" << Code;
+          outs() << "UnknownCode" << Code;
         if (NonSymbolic &&
             GetCodeName(Code, BlockID, *Stream.getBitStreamReader()))
-          errs() << " codeid=3D" << Code;
+          outs() << " codeid=3D" << Code;
         if (AbbrevID !=3D bitc::UNABBREV_RECORD)
-          errs() << " abbrevid=3D" << AbbrevID;
+          outs() << " abbrevid=3D" << AbbrevID;
=20
         for (unsigned i =3D 0, e =3D Record.size(); i !=3D e; ++i)
-          errs() << " op" << i << "=3D" << (int64_t)Record[i];
+          outs() << " op" << i << "=3D" << (int64_t)Record[i];
=20
-        errs() << "/>";
+        outs() << "/>";
=20
         if (BlobStart) {
-          errs() << " blob data =3D ";
+          outs() << " blob data =3D ";
           bool BlobIsPrintable =3D true;
           for (unsigned i =3D 0; i !=3D BlobLen; ++i)
             if (!isprint(BlobStart[i])) {
@@ -451,12 +449,12 @@
             }
=20
           if (BlobIsPrintable)
-            errs() << "'" << std::string(BlobStart, BlobStart+BlobLen) <<"=
'";
+            outs() << "'" << std::string(BlobStart, BlobStart+BlobLen) <<"=
'";
           else
-            errs() << "unprintable, " << BlobLen << " bytes.";
+            outs() << "unprintable, " << BlobLen << " bytes.";
         }
=20
-        errs() << "\n";
+        outs() << "\n";
       }
=20
       break;
@@ -485,13 +483,13 @@
   if (MemBuf->getBufferSize() & 3)
     return Error("Bitcode stream should be a multiple of 4 bytes in length=
");
=20
-  unsigned char *BufPtr =3D (unsigned char *)MemBuf->getBufferStart();
-  unsigned char *EndBufPtr =3D BufPtr+MemBuf->getBufferSize();
+  const unsigned char *BufPtr =3D (unsigned char *)MemBuf->getBufferStart(=
);
+  const unsigned char *EndBufPtr =3D BufPtr+MemBuf->getBufferSize();
=20
   // If we have a wrapper header, parse it and ignore the non-bc file cont=
ents.
   // The magic number is 0x0B17C0DE stored in little endian.
   if (isBitcodeWrapper(BufPtr, EndBufPtr))
-    if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr))
+    if (SkipBitcodeWrapperHeader(BufPtr, EndBufPtr, true))
       return Error("Invalid bitcode wrapper header");
=20
   BitstreamReader StreamFile(BufPtr, EndBufPtr);
@@ -527,59 +525,58 @@
     ++NumTopBlocks;
   }
=20
-  if (Dump) errs() << "\n\n";
+  if (Dump) outs() << "\n\n";
=20
   uint64_t BufferSizeBits =3D (EndBufPtr-BufPtr)*CHAR_BIT;
   // Print a summary of the read file.
-  errs() << "Summary of " << InputFilename << ":\n";
-  errs() << "         Total size: ";
+  outs() << "Summary of " << InputFilename << ":\n";
+  outs() << "         Total size: ";
   PrintSize(BufferSizeBits);
-  errs() << "\n";
-  errs() << "        Stream type: ";
+  outs() << "\n";
+  outs() << "        Stream type: ";
   switch (CurStreamType) {
-  default: assert(0 && "Unknown bitstream type");
-  case UnknownBitstream: errs() << "unknown\n"; break;
-  case LLVMIRBitstream:  errs() << "LLVM IR\n"; break;
+  case UnknownBitstream: outs() << "unknown\n"; break;
+  case LLVMIRBitstream:  outs() << "LLVM IR\n"; break;
   }
-  errs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
-  errs() << "\n";
+  outs() << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
+  outs() << "\n";
=20
   // Emit per-block stats.
-  errs() << "Per-block Summary:\n";
+  outs() << "Per-block Summary:\n";
   for (std::map<unsigned, PerBlockIDStats>::iterator I =3D BlockIDStats.be=
gin(),
        E =3D BlockIDStats.end(); I !=3D E; ++I) {
-    errs() << "  Block ID #" << I->first;
+    outs() << "  Block ID #" << I->first;
     if (const char *BlockName =3D GetBlockName(I->first, StreamFile))
-      errs() << " (" << BlockName << ")";
-    errs() << ":\n";
+      outs() << " (" << BlockName << ")";
+    outs() << ":\n";
=20
     const PerBlockIDStats &Stats =3D I->second;
-    errs() << "      Num Instances: " << Stats.NumInstances << "\n";
-    errs() << "         Total Size: ";
+    outs() << "      Num Instances: " << Stats.NumInstances << "\n";
+    outs() << "         Total Size: ";
     PrintSize(Stats.NumBits);
-    errs() << "\n";
+    outs() << "\n";
     double pct =3D (Stats.NumBits * 100.0) / BufferSizeBits;
     errs() << "    Percent of file: " << format("%2.4f%%", pct) << "\n";
     if (Stats.NumInstances > 1) {
-      errs() << "       Average Size: ";
+      outs() << "       Average Size: ";
       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
-      errs() << "\n";
-      errs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
+      outs() << "\n";
+      outs() << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
              << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
-      errs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
+      outs() << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
              << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
-      errs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
+      outs() << "    Tot/Avg Records: " << Stats.NumRecords << "/"
              << Stats.NumRecords/(double)Stats.NumInstances << "\n";
     } else {
-      errs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
-      errs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
-      errs() << "        Num Records: " << Stats.NumRecords << "\n";
+      outs() << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
+      outs() << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
+      outs() << "        Num Records: " << Stats.NumRecords << "\n";
     }
     if (Stats.NumRecords) {
       double pct =3D (Stats.NumAbbreviatedRecords * 100.0) / Stats.NumReco=
rds;
-      errs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
+      outs() << "    Percent Abbrevs: " << format("%2.4f%%", pct) << "\n";
     }
-    errs() << "\n";
+    outs() << "\n";
=20
     // Print a histogram of the codes we see.
     if (!NoHistogram && !Stats.CodeFreq.empty()) {
@@ -590,7 +587,7 @@
       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
       std::reverse(FreqPairs.begin(), FreqPairs.end());
=20
-      errs() << "\tRecord Histogram:\n";
+      outs() << "\tRecord Histogram:\n";
       fprintf(stderr, "\t\t  Count    # Bits   %% Abv  Record Kind\n");
       for (unsigned i =3D 0, e =3D FreqPairs.size(); i !=3D e; ++i) {
         const PerRecordStats &RecStats =3D Stats.CodeFreq[FreqPairs[i].sec=
ond];
@@ -610,7 +607,7 @@
         else
           fprintf(stderr, "UnknownCode%d\n", FreqPairs[i].second);
       }
-      errs() << "\n";
+      outs() << "\n";
=20
     }
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-diff/Diff=
Consumer.cpp
--- a/head/contrib/llvm/tools/llvm-diff/DiffConsumer.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-diff/DiffConsumer.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -44,6 +44,8 @@
 }
=20
=20
+void Consumer::anchor() { }
+
 void DiffConsumer::printValue(Value *V, bool isL) {
   if (V->hasName()) {
     out << (isa<GlobalValue>(V) ? '@' : '%') << V->getName();
@@ -64,6 +66,10 @@
     }
     return;
   }
+  if (isa<Constant>(V)) {
+    out << *V;
+    return;
+  }
=20
   unsigned N =3D contexts.size();
   while (N > 0) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-diff/Diff=
Consumer.h
--- a/head/contrib/llvm/tools/llvm-diff/DiffConsumer.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/llvm-diff/DiffConsumer.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -29,6 +29,7 @@
=20
   /// The interface for consumers of difference data.
   class Consumer {
+    virtual void anchor();
   public:
     /// Record that a local context has been entered.  Left and
     /// Right are IR "containers" of some sort which are being
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-diff/Diff=
erenceEngine.cpp
--- a/head/contrib/llvm/tools/llvm-diff/DifferenceEngine.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-diff/DifferenceEngine.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -319,15 +319,19 @@
       bool Difference =3D false;
=20
       DenseMap<ConstantInt*,BasicBlock*> LCases;
-      for (unsigned I =3D 1, E =3D LI->getNumCases(); I !=3D E; ++I)
-        LCases[LI->getCaseValue(I)] =3D LI->getSuccessor(I);
-      for (unsigned I =3D 1, E =3D RI->getNumCases(); I !=3D E; ++I) {
-        ConstantInt *CaseValue =3D RI->getCaseValue(I);
+     =20
+      for (SwitchInst::CaseIt I =3D LI->case_begin(), E =3D LI->case_end();
+           I !=3D E; ++I)
+        LCases[I.getCaseValue()] =3D I.getCaseSuccessor();
+       =20
+      for (SwitchInst::CaseIt I =3D RI->case_begin(), E =3D RI->case_end();
+           I !=3D E; ++I) {
+        ConstantInt *CaseValue =3D I.getCaseValue();
         BasicBlock *LCase =3D LCases[CaseValue];
         if (LCase) {
-          if (TryUnify) tryUnify(LCase, RI->getSuccessor(I));
+          if (TryUnify) tryUnify(LCase, I.getCaseSuccessor());
           LCases.erase(CaseValue);
-        } else if (!Difference) {
+        } else if (Complain || !Difference) {
           if (Complain)
             Engine.logf("right switch has extra case %r") << CaseValue;
           Difference =3D true;
@@ -628,6 +632,8 @@
=20
 }
=20
+void DifferenceEngine::Oracle::anchor() { }
+
 void DifferenceEngine::diff(Function *L, Function *R) {
   Context C(*this, L, R);
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-diff/Diff=
erenceEngine.h
--- a/head/contrib/llvm/tools/llvm-diff/DifferenceEngine.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-diff/DifferenceEngine.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -50,7 +50,9 @@
=20
     /// An oracle for answering whether two values are equivalent as
     /// operands.
-    struct Oracle {
+    class Oracle {
+      virtual void anchor();
+    public:
       virtual bool operator()(Value *L, Value *R) =3D 0;
=20
     protected:
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-diff/llvm=
-diff.cpp
--- a/head/contrib/llvm/tools/llvm-diff/llvm-diff.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/tools/llvm-diff/llvm-diff.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -38,7 +38,7 @@
   SMDiagnostic Diag;
   Module *M =3D ParseIRFile(Name, Diag, Context);
   if (!M)
-    Diag.Print("llvmdiff", errs());
+    Diag.print("llvm-diff", errs());
   return M;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-dis/llvm-=
dis.cpp
--- a/head/contrib/llvm/tools/llvm-dis/llvm-dis.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/tools/llvm-dis/llvm-dis.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -24,6 +24,7 @@
 #include "llvm/Analysis/DebugInfo.h"
 #include "llvm/Assembly/AssemblyAnnotationWriter.h"
 #include "llvm/Support/CommandLine.h"
+#include "llvm/Support/DataStream.h"
 #include "llvm/Support/FormattedStream.h"
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/MemoryBuffer.h"
@@ -126,12 +127,19 @@
   std::string ErrorMessage;
   std::auto_ptr<Module> M;
=20
-  {
-    OwningPtr<MemoryBuffer> BufferPtr;
-    if (error_code ec =3D MemoryBuffer::getFileOrSTDIN(InputFilename, Buff=
erPtr))
-      ErrorMessage =3D ec.message();
+  // Use the bitcode streaming interface
+  DataStreamer *streamer =3D getDataFileStreamer(InputFilename, &ErrorMess=
age);
+  if (streamer) {
+    std::string DisplayFilename;
+    if (InputFilename =3D=3D "-")
+      DisplayFilename =3D "<stdin>";
     else
-      M.reset(ParseBitcodeFile(BufferPtr.get(), Context, &ErrorMessage));
+      DisplayFilename =3D InputFilename;
+    M.reset(getStreamedBitcodeModule(DisplayFilename, streamer, Context,
+                                     &ErrorMessage));
+    if(M.get() !=3D 0 && M->MaterializeAllPermanently(&ErrorMessage)) {
+      M.reset();
+    }
   }
=20
   if (M.get() =3D=3D 0) {
@@ -183,4 +191,3 @@
=20
   return 0;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-extract/l=
lvm-extract.cpp
--- a/head/contrib/llvm/tools/llvm-extract/llvm-extract.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-extract/llvm-extract.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -90,7 +90,7 @@
   M.reset(getLazyIRFileModule(InputFilename, Err, Context));
=20
   if (M.get() =3D=3D 0) {
-    Err.Print(argv[0], errs());
+    Err.print(argv[0], errs());
     return 1;
   }
=20
@@ -99,7 +99,7 @@
=20
   // Figure out which globals we should extract.
   for (size_t i =3D 0, e =3D ExtractGlobals.size(); i !=3D e; ++i) {
-    GlobalValue *GV =3D M.get()->getNamedGlobal(ExtractGlobals[i]);
+    GlobalValue *GV =3D M->getNamedGlobal(ExtractGlobals[i]);
     if (!GV) {
       errs() << argv[0] << ": program doesn't contain global named '"
              << ExtractGlobals[i] << "'!\n";
@@ -117,8 +117,8 @@
         "invalid regex: " << Error;
     }
     bool match =3D false;
-    for (Module::global_iterator GV =3D M.get()->global_begin(),=20
-           E =3D M.get()->global_end(); GV !=3D E; GV++) {
+    for (Module::global_iterator GV =3D M->global_begin(),
+           E =3D M->global_end(); GV !=3D E; GV++) {
       if (RegEx.match(GV->getName())) {
         GVs.insert(&*GV);
         match =3D true;
@@ -133,7 +133,7 @@
=20
   // Figure out which functions we should extract.
   for (size_t i =3D 0, e =3D ExtractFuncs.size(); i !=3D e; ++i) {
-    GlobalValue *GV =3D M.get()->getFunction(ExtractFuncs[i]);
+    GlobalValue *GV =3D M->getFunction(ExtractFuncs[i]);
     if (!GV) {
       errs() << argv[0] << ": program doesn't contain function named '"
              << ExtractFuncs[i] << "'!\n";
@@ -151,7 +151,7 @@
         "invalid regex: " << Error;
     }
     bool match =3D false;
-    for (Module::iterator F =3D M.get()->begin(), E =3D M.get()->end(); F =
!=3D E;=20
+    for (Module::iterator F =3D M->begin(), E =3D M->end(); F !=3D E;
          F++) {
       if (RegEx.match(F->getName())) {
         GVs.insert(&*F);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-ld/llvm-l=
d.cpp
--- a/head/contrib/llvm/tools/llvm-ld/llvm-ld.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/tools/llvm-ld/llvm-ld.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -37,7 +37,6 @@
 #include "llvm/Support/SystemUtils.h"
 #include "llvm/Support/ToolOutputFile.h"
 #include "llvm/Support/Signals.h"
-#include "llvm/Config/config.h"
 #include <memory>
 #include <cstring>
 using namespace llvm;
@@ -424,7 +423,7 @@
     PrintAndExit(ErrMsg, M);
=20
   return;
-#endif
+#else
=20
   // Output the script to start the program...
   std::string ErrorInfo;
@@ -470,6 +469,7 @@
   }
   Out2.os() << "    "  << BitcodeOutputFilename << " ${1+\"$@\"}\n";
   Out2.keep();
+#endif
 }
=20
 // BuildLinkItems -- This function generates a LinkItemList for the LinkIt=
ems
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-link/llvm=
-link.cpp
--- a/head/contrib/llvm/tools/llvm-link/llvm-link.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/tools/llvm-link/llvm-link.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -69,7 +69,7 @@
   Result =3D ParseIRFile(FNStr, Err, Context);
   if (Result) return std::auto_ptr<Module>(Result);   // Load successful!
=20
-  Err.Print(argv0, errs());
+  Err.print(argv0, errs());
   return std::auto_ptr<Module>();
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-mc/Disass=
embler.cpp
--- a/head/contrib/llvm/tools/llvm-mc/Disassembler.cpp	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/tools/llvm-mc/Disassembler.cpp	Tue Apr 17 11:51:51 =
2012 +0300
@@ -21,6 +21,8 @@
 #include "llvm/MC/MCDisassembler.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCInstPrinter.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/Triple.h"
@@ -72,14 +74,16 @@
     switch (S) {
     case MCDisassembler::Fail:
       SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
-                      "invalid instruction encoding", "warning");
+                      SourceMgr::DK_Warning,
+                      "invalid instruction encoding");
       if (Size =3D=3D 0)
         Size =3D 1; // skip illegible bytes
       break;
=20
     case MCDisassembler::SoftFail:
       SM.PrintMessage(SMLoc::getFromPointer(Bytes[Index].second),
-                      "potentially undefined instruction encoding", "warni=
ng");
+                      SourceMgr::DK_Warning,
+                      "potentially undefined instruction encoding");
       // Fall through
=20
     case MCDisassembler::Success:
@@ -125,8 +129,8 @@
     unsigned ByteVal;
     if (Value.getAsInteger(0, ByteVal) || ByteVal > 255) {
       // If we have an error, print it and skip to the end of line.
-      SM.PrintMessage(SMLoc::getFromPointer(Value.data()),
-                      "invalid input token", "error");
+      SM.PrintMessage(SMLoc::getFromPointer(Value.data()), SourceMgr::DK_E=
rror,
+                      "invalid input token");
       Str =3D Str.substr(Str.find('\n'));
       ByteArray.clear();
       continue;
@@ -153,21 +157,34 @@
     return -1;
   }
=20
-  OwningPtr<const MCSubtargetInfo> STI(T.createMCSubtargetInfo(Triple, Cpu=
, FeaturesStr));
+  OwningPtr<const MCSubtargetInfo> STI(T.createMCSubtargetInfo(Triple, Cpu,
+                                                               FeaturesStr=
));
   if (!STI) {
     errs() << "error: no subtarget info for target " << Triple << "\n";
     return -1;
   }
- =20
+
   OwningPtr<const MCDisassembler> DisAsm(T.createMCDisassembler(*STI));
   if (!DisAsm) {
     errs() << "error: no disassembler for target " << Triple << "\n";
     return -1;
   }
=20
+  OwningPtr<const MCRegisterInfo> MRI(T.createMCRegInfo(Triple));
+  if (!MRI) {
+    errs() << "error: no register info for target " << Triple << "\n";
+    return -1;
+  }
+
+  OwningPtr<const MCInstrInfo> MII(T.createMCInstrInfo());
+  if (!MII) {
+    errs() << "error: no instruction info for target " << Triple << "\n";
+    return -1;
+  }
+
   int AsmPrinterVariant =3D AsmInfo->getAssemblerDialect();
-  OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant,
-                                                    *AsmInfo, *STI));
+  OwningPtr<MCInstPrinter> IP(T.createMCInstPrinter(AsmPrinterVariant, *As=
mInfo,
+                                                    *MII, *MRI, *STI));
   if (!IP) {
     errs() << "error: no instruction printer for target " << Triple << '\n=
';
     return -1;
@@ -247,7 +264,6 @@
     break;
   }
=20
-  EDDisassembler::initialize();
   OwningPtr<EDDisassembler>
     disassembler(EDDisassembler::getDisassembler(TS.c_str(), AS));
=20
@@ -294,7 +310,6 @@
         Out << operandIndex << "-";
=20
       switch (token->type()) {
-      default: Out << "?"; break;
       case EDToken::kTokenWhitespace: Out << "w"; break;
       case EDToken::kTokenPunctuation: Out << "p"; break;
       case EDToken::kTokenOpcode: Out << "o"; break;
@@ -365,4 +380,3 @@
=20
   return 0;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-mc/llvm-m=
c.cpp
--- a/head/contrib/llvm/tools/llvm-mc/llvm-mc.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/tools/llvm-mc/llvm-mc.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -70,9 +70,6 @@
 static cl::opt<bool>
 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"=
));
=20
-static cl::opt<bool>
-EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
-
 enum OutputFileType {
   OFT_Null,
   OFT_AssemblyFile,
@@ -152,6 +149,10 @@
 static cl::opt<bool>
 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
=20
+static cl::opt<bool>
+GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assem=
bly "
+                                  "source files"));
+
 enum ActionType {
   AC_AsLex,
   AC_Assemble,
@@ -175,7 +176,7 @@
 static const Target *GetTarget(const char *ProgName) {
   // Figure out the target triple.
   if (TripleName.empty())
-    TripleName =3D sys::getHostTriple();
+    TripleName =3D sys::getDefaultTargetTriple();
   Triple TheTriple(Triple::normalize(TripleName));
=20
   const Target *TheTarget =3D 0;
@@ -230,6 +231,17 @@
   return Out;
 }
=20
+static std::string DwarfDebugFlags;
+static void setDwarfDebugFlags(int argc, char **argv) {
+  if (!getenv("RC_DEBUG_OPTIONS"))
+    return;
+  for (int i =3D 0; i < argc; i++) {
+    DwarfDebugFlags +=3D argv[i];
+    if (i + 1 < argc)
+      DwarfDebugFlags +=3D " ";
+  }
+}
+
 static int AsLexInput(const char *ProgName) {
   OwningPtr<MemoryBuffer> BufferPtr;
   if (error_code ec =3D MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer=
Ptr)) {
@@ -267,7 +279,8 @@
=20
     switch (Tok.getKind()) {
     default:
-      SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
+      SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
+                          "unknown token");
       Error =3D true;
       break;
     case AsmToken::Error:
@@ -370,12 +383,16 @@
   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
   // MCObjectFileInfo needs a MCContext reference in order to initialize i=
tself.
   OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
-  MCContext Ctx(*MAI, *MRI, MOFI.get());
+  MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
   MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
=20
   if (SaveTempLabels)
     Ctx.setAllowTemporaryLabels(false);
=20
+  Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
+  if (!DwarfDebugFlags.empty())=20
+    Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
+
   // Package up features to be passed to target/subtarget
   std::string FeaturesStr;
   if (MAttrs.size()) {
@@ -399,7 +416,7 @@
   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
   if (FileType =3D=3D OFT_AssemblyFile) {
     MCInstPrinter *IP =3D
-      TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *STI);
+      TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, =
*STI);
     MCCodeEmitter *CE =3D 0;
     MCAsmBackend *MAB =3D 0;
     if (ShowEncoding) {
@@ -408,8 +425,10 @@
     }
     Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
                                            /*useLoc*/ true,
-                                           /*useCFI*/ true, IP, CE, MAB,
-                                           ShowInst));
+                                           /*useCFI*/ true,
+                                           /*useDwarfDirectory*/ true,
+                                           IP, CE, MAB, ShowInst));
+
   } else if (FileType =3D=3D OFT_Null) {
     Str.reset(createNullStreamer(Ctx));
   } else {
@@ -421,10 +440,6 @@
                                                 NoExecStack));
   }
=20
-  if (EnableLogging) {
-    Str.reset(createLoggingStreamer(Str.take(), errs()));
-  }
-
   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
                                                   *Str.get(), *MAI));
   OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Par=
ser));
@@ -497,11 +512,14 @@
   llvm::InitializeAllAsmParsers();
   llvm::InitializeAllDisassemblers();
=20
+  // Register the target printer for --version.
+  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVers=
ion);
+
   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"=
);
   TripleName =3D Triple::normalize(TripleName);
+  setDwarfDebugFlags(argc, argv);
=20
   switch (Action) {
-  default:
   case AC_AsLex:
     return AsLexInput(argv[0]);
   case AC_Assemble:
@@ -511,7 +529,4 @@
   case AC_EDisassemble:
     return DisassembleInput(argv[0], true);
   }
-
-  return 0;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-nm/llvm-n=
m.cpp
--- a/head/contrib/llvm/tools/llvm-nm/llvm-nm.cpp	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/llvm/tools/llvm-nm/llvm-nm.cpp	Tue Apr 17 11:51:51 2012 =
+0300
@@ -27,6 +27,7 @@
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/PrettyStackTrace.h"
+#include "llvm/Support/Program.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/Format.h"
@@ -60,6 +61,12 @@
   cl::alias UndefinedOnly2("u", cl::desc("Alias for --undefined-only"),
                            cl::aliasopt(UndefinedOnly));
=20
+  cl::opt<bool> DynamicSyms("dynamic",
+                             cl::desc("Display the dynamic symbols instead=
 "
+                                      "of normal symbols."));
+  cl::alias DynamicSyms2("D", cl::desc("Alias for --dynamic"),
+                         cl::aliasopt(DynamicSyms));
+
   cl::opt<bool> DefinedOnly("defined-only",
                             cl::desc("Show only defined symbols"));
=20
@@ -110,6 +117,19 @@
   std::string ToolName;
 }
=20
+
+static void error(Twine message, Twine path =3D Twine()) {
+  errs() << ToolName << ": " << path << ": " << message << ".\n";
+}
+
+static bool error(error_code ec, Twine path =3D Twine()) {
+  if (ec) {
+    error(ec.message(), path);
+    return true;
+  }
+  return false;
+}
+
 namespace {
   struct NMSymbol {
     uint64_t  Address;
@@ -144,14 +164,6 @@
   StringRef CurrentFilename;
   typedef std::vector<NMSymbol> SymbolListT;
   SymbolListT SymbolList;
-
-  bool error(error_code ec) {
-    if (!ec) return false;
-
-    outs() << ToolName << ": error reading file: " << ec.message() << ".\n=
";
-    outs().flush();
-    return true;
-  }
 }
=20
 static void SortAndPrintSymbolList() {
@@ -192,9 +204,10 @@
       strcpy(SymbolSizeStr, "        ");
=20
     if (i->Address !=3D object::UnknownAddressOrSize)
-      format("%08"PRIx64, i->Address).print(SymbolAddrStr, sizeof(SymbolAd=
drStr));
+      format("%08" PRIx64, i->Address).print(SymbolAddrStr,
+                                             sizeof(SymbolAddrStr));
     if (i->Size !=3D object::UnknownAddressOrSize)
-      format("%08"PRIx64, i->Size).print(SymbolSizeStr, sizeof(SymbolSizeS=
tr));
+      format("%08" PRIx64, i->Size).print(SymbolSizeStr, sizeof(SymbolSize=
Str));
=20
     if (OutputFormat =3D=3D posix) {
       outs() << i->Name << " " << i->TypeChar << " "
@@ -271,13 +284,17 @@
=20
 static void DumpSymbolNamesFromObject(ObjectFile *obj) {
   error_code ec;
-  for (symbol_iterator i =3D obj->begin_symbols(),
-                       e =3D obj->end_symbols();
-                       i !=3D e; i.increment(ec)) {
+  symbol_iterator ibegin =3D obj->begin_symbols();
+  symbol_iterator iend =3D obj->end_symbols();
+  if (DynamicSyms) {
+    ibegin =3D obj->begin_dynamic_symbols();
+    iend =3D obj->end_dynamic_symbols();
+  }
+  for (symbol_iterator i =3D ibegin; i !=3D iend; i.increment(ec)) {
     if (error(ec)) break;
-    bool internal;
-    if (error(i->isInternal(internal))) break;
-    if (!DebugSyms && internal)
+    uint32_t symflags;
+    if (error(i->getFlags(symflags))) break;
+    if (!DebugSyms && (symflags & SymbolRef::SF_FormatSpecific))
       continue;
     NMSymbol s;
     s.Size =3D object::UnknownAddressOrSize;
@@ -286,7 +303,7 @@
       if (error(i->getSize(s.Size))) break;
     }
     if (PrintAddress)
-      if (error(i->getOffset(s.Address))) break;
+      if (error(i->getAddress(s.Address))) break;
     if (error(i->getNMTypeChar(s.TypeChar))) break;
     if (error(i->getName(s.Name))) break;
     SymbolList.push_back(s);
@@ -297,38 +314,39 @@
 }
=20
 static void DumpSymbolNamesFromFile(std::string &Filename) {
+  if (Filename !=3D "-" && !sys::fs::exists(Filename)) {
+    errs() << ToolName << ": '" << Filename << "': " << "No such file\n";
+    return;
+  }
+
+  OwningPtr<MemoryBuffer> Buffer;
+  if (error(MemoryBuffer::getFileOrSTDIN(Filename, Buffer), Filename))
+    return;
+
+  sys::fs::file_magic magic =3D sys::fs::identify_magic(Buffer->getBuffer(=
));
+
   LLVMContext &Context =3D getGlobalContext();
   std::string ErrorMessage;
-  sys::Path aPath(Filename);
-  bool exists;
-  if (sys::fs::exists(aPath.str(), exists) || !exists)
-    errs() << ToolName << ": '" << Filename << "': " << "No such file\n";
-  // Note: Currently we do not support reading an archive from stdin.
-  if (Filename =3D=3D "-" || aPath.isBitcodeFile()) {
-    OwningPtr<MemoryBuffer> Buffer;
-    if (error_code ec =3D MemoryBuffer::getFileOrSTDIN(Filename, Buffer))
-      ErrorMessage =3D ec.message();
+  if (magic =3D=3D sys::fs::file_magic::bitcode) {
     Module *Result =3D 0;
-    if (Buffer.get())
-      Result =3D ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
-
+    Result =3D ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
     if (Result) {
       DumpSymbolNamesFromModule(Result);
       delete Result;
-    } else
-      errs() << ToolName << ": " << Filename << ": " << ErrorMessage << "\=
n";
-
-  } else if (aPath.isArchive()) {
-    OwningPtr<Binary> arch;
-    if (error_code ec =3D object::createBinary(aPath.str(), arch)) {
-      errs() << ToolName << ": " << Filename << ": " << ec.message() << ".=
\n";
+    } else {
+      error(ErrorMessage, Filename);
       return;
     }
+  } else if (magic =3D=3D sys::fs::file_magic::archive) {
+    OwningPtr<Binary> arch;
+    if (error(object::createBinary(Buffer.take(), arch), Filename))
+      return;
+
     if (object::Archive *a =3D dyn_cast<object::Archive>(arch.get())) {
       for (object::Archive::child_iterator i =3D a->begin_children(),
                                            e =3D a->end_children(); i !=3D=
 e; ++i) {
         OwningPtr<Binary> child;
-        if (error_code ec =3D i->getAsBinary(child)) {
+        if (i->getAsBinary(child)) {
           // Try opening it as a bitcode file.
           OwningPtr<MemoryBuffer> buff(i->getBuffer());
           Module *Result =3D 0;
@@ -347,12 +365,10 @@
         }
       }
     }
-  } else if (aPath.isObjectFile()) {
+  } else if (magic.is_object()) {
     OwningPtr<Binary> obj;
-    if (error_code ec =3D object::createBinary(aPath.str(), obj)) {
-      errs() << ToolName << ": " << Filename << ": " << ec.message() << ".=
\n";
+    if (error(object::createBinary(Buffer.take(), obj), Filename))
       return;
-    }
     if (object::ObjectFile *o =3D dyn_cast<ObjectFile>(obj.get()))
       DumpSymbolNamesFromObject(o);
   } else {
@@ -370,6 +386,10 @@
   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
   cl::ParseCommandLineOptions(argc, argv, "llvm symbol table dumper\n");
=20
+  // llvm-nm only reads binary files.
+  if (error(sys::Program::ChangeStdinToBinary()))
+    return 1;
+
   ToolName =3D argv[0];
   if (BSDFormat) OutputFormat =3D bsd;
   if (POSIXFormat) OutputFormat =3D posix;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-objdump/M=
achODump.cpp
--- a/head/contrib/llvm/tools/llvm-objdump/MachODump.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-objdump/MachODump.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -14,7 +14,7 @@
 #include "llvm-objdump.h"
 #include "MCFunction.h"
 #include "llvm/Support/MachO.h"
-#include "llvm/Object/MachOObject.h"
+#include "llvm/Object/MachO.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/ADT/STLExtras.h"
@@ -26,6 +26,7 @@
 #include "llvm/MC/MCInstrAnalysis.h"
 #include "llvm/MC/MCInstrDesc.h"
 #include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
@@ -53,27 +54,28 @@
=20
 static const Target *GetTarget(const MachOObject *MachOObj) {
   // Figure out the target triple.
-  llvm::Triple TT("unknown-unknown-unknown");
-  switch (MachOObj->getHeader().CPUType) {
-  case llvm::MachO::CPUTypeI386:
-    TT.setArch(Triple::ArchType(Triple::x86));
-    break;
-  case llvm::MachO::CPUTypeX86_64:
-    TT.setArch(Triple::ArchType(Triple::x86_64));
-    break;
-  case llvm::MachO::CPUTypeARM:
-    TT.setArch(Triple::ArchType(Triple::arm));
-    break;
-  case llvm::MachO::CPUTypePowerPC:
-    TT.setArch(Triple::ArchType(Triple::ppc));
-    break;
-  case llvm::MachO::CPUTypePowerPC64:
-    TT.setArch(Triple::ArchType(Triple::ppc64));
-    break;
+  if (TripleName.empty()) {
+    llvm::Triple TT("unknown-unknown-unknown");
+    switch (MachOObj->getHeader().CPUType) {
+    case llvm::MachO::CPUTypeI386:
+      TT.setArch(Triple::ArchType(Triple::x86));
+      break;
+    case llvm::MachO::CPUTypeX86_64:
+      TT.setArch(Triple::ArchType(Triple::x86_64));
+      break;
+    case llvm::MachO::CPUTypeARM:
+      TT.setArch(Triple::ArchType(Triple::arm));
+      break;
+    case llvm::MachO::CPUTypePowerPC:
+      TT.setArch(Triple::ArchType(Triple::ppc));
+      break;
+    case llvm::MachO::CPUTypePowerPC64:
+      TT.setArch(Triple::ArchType(Triple::ppc64));
+      break;
+    }
+    TripleName =3D TT.str();
   }
=20
-  TripleName =3D TT.str();
-
   // Get the target specific parser.
   std::string Error;
   const Target *TheTarget =3D TargetRegistry::lookupTarget(TripleName, Err=
or);
@@ -85,57 +87,43 @@
   return 0;
 }
=20
-struct Section {
-  char Name[16];
-  uint64_t Address;
-  uint64_t Size;
-  uint32_t Offset;
-  uint32_t NumRelocs;
-  uint64_t RelocTableOffset;
+struct SymbolSorter {
+  bool operator()(const SymbolRef &A, const SymbolRef &B) {
+    SymbolRef::Type AType, BType;
+    A.getType(AType);
+    B.getType(BType);
+
+    uint64_t AAddr, BAddr;
+    if (AType !=3D SymbolRef::ST_Function)
+      AAddr =3D 0;
+    else
+      A.getAddress(AAddr);
+    if (BType !=3D SymbolRef::ST_Function)
+      BAddr =3D 0;
+    else
+      B.getAddress(BAddr);
+    return AAddr < BAddr;
+  }
 };
=20
-struct Symbol {
-  uint64_t Value;
-  uint32_t StringIndex;
-  uint8_t SectionIndex;
-  bool operator<(const Symbol &RHS) const { return Value < RHS.Value; }
-};
-
-template <typename T>
-static Section copySection(const T &Sect) {
-  Section S;
-  memcpy(S.Name, Sect->Name, 16);
-  S.Address =3D Sect->Address;
-  S.Size =3D Sect->Size;
-  S.Offset =3D Sect->Offset;
-  S.NumRelocs =3D Sect->NumRelocationTableEntries;
-  S.RelocTableOffset =3D Sect->RelocationTableOffset;
-  return S;
-}
-
-template <typename T>
-static Symbol copySymbol(const T &STE) {
-  Symbol S;
-  S.StringIndex =3D STE->StringIndex;
-  S.SectionIndex =3D STE->SectionIndex;
-  S.Value =3D STE->Value;
-  return S;
-}
-
 // Print additional information about an address, if available.
-static void DumpAddress(uint64_t Address, ArrayRef<Section> Sections,
+static void DumpAddress(uint64_t Address, ArrayRef<SectionRef> Sections,
                         MachOObject *MachOObj, raw_ostream &OS) {
   for (unsigned i =3D 0; i !=3D Sections.size(); ++i) {
-    uint64_t addr =3D Address-Sections[i].Address;
-    if (Sections[i].Address <=3D Address &&
-        Sections[i].Address + Sections[i].Size > Address) {
-      StringRef bytes =3D MachOObj->getData(Sections[i].Offset,
-                                          Sections[i].Size);
+    uint64_t SectAddr =3D 0, SectSize =3D 0;
+    Sections[i].getAddress(SectAddr);
+    Sections[i].getSize(SectSize);
+    uint64_t addr =3D SectAddr;
+    if (SectAddr <=3D Address &&
+        SectAddr + SectSize > Address) {
+      StringRef bytes, name;
+      Sections[i].getContents(bytes);
+      Sections[i].getName(name);
       // Print constant strings.
-      if (!strcmp(Sections[i].Name, "__cstring"))
+      if (!name.compare("__cstring"))
         OS << '"' << bytes.substr(addr, bytes.find('\0', addr)) << '"';
       // Print constant CFStrings.
-      if (!strcmp(Sections[i].Name, "__cfstring"))
+      if (!name.compare("__cfstring"))
         OS << "@\"" << bytes.substr(addr, bytes.find('\0', addr)) << '"';
     }
   }
@@ -212,59 +200,34 @@
 }
=20
 static void getSectionsAndSymbols(const macho::Header &Header,
-                                  MachOObject *MachOObj,
+                                  MachOObjectFile *MachOObj,
                              InMemoryStruct<macho::SymtabLoadCommand> *Sym=
tabLC,
-                                  std::vector<Section> &Sections,
-                                  std::vector<Symbol> &Symbols,
+                                  std::vector<SectionRef> &Sections,
+                                  std::vector<SymbolRef> &Symbols,
                                   SmallVectorImpl<uint64_t> &FoundFns) {
-  // Make a list of all symbols in the object file.
+  error_code ec;
+  for (symbol_iterator SI =3D MachOObj->begin_symbols(),
+       SE =3D MachOObj->end_symbols(); SI !=3D SE; SI.increment(ec))
+    Symbols.push_back(*SI);
+
+  for (section_iterator SI =3D MachOObj->begin_sections(),
+       SE =3D MachOObj->end_sections(); SI !=3D SE; SI.increment(ec)) {
+    SectionRef SR =3D *SI;
+    StringRef SectName;
+    SR.getName(SectName);
+    Sections.push_back(*SI);
+  }
+
   for (unsigned i =3D 0; i !=3D Header.NumLoadCommands; ++i) {
-    const MachOObject::LoadCommandInfo &LCI =3D MachOObj->getLoadCommandIn=
fo(i);
-    if (LCI.Command.Type =3D=3D macho::LCT_Segment) {
-      InMemoryStruct<macho::SegmentLoadCommand> SegmentLC;
-      MachOObj->ReadSegmentLoadCommand(LCI, SegmentLC);
-
-      // Store the sections in this segment.
-      for (unsigned SectNum =3D 0; SectNum !=3D SegmentLC->NumSections; ++=
SectNum) {
-        InMemoryStruct<macho::Section> Sect;
-        MachOObj->ReadSection(LCI, SectNum, Sect);
-        Sections.push_back(copySection(Sect));
-
-      }
-    } else if (LCI.Command.Type =3D=3D macho::LCT_Segment64) {
-      InMemoryStruct<macho::Segment64LoadCommand> Segment64LC;
-      MachOObj->ReadSegment64LoadCommand(LCI, Segment64LC);
-
-      // Store the sections in this segment.
-      for (unsigned SectNum =3D 0; SectNum !=3D Segment64LC->NumSections;
-          ++SectNum) {
-        InMemoryStruct<macho::Section64> Sect64;
-        MachOObj->ReadSection64(LCI, SectNum, Sect64);
-        Sections.push_back(copySection(Sect64));
-      }
-    } else if (LCI.Command.Type =3D=3D macho::LCT_FunctionStarts) {
+    const MachOObject::LoadCommandInfo &LCI =3D
+       MachOObj->getObject()->getLoadCommandInfo(i);
+    if (LCI.Command.Type =3D=3D macho::LCT_FunctionStarts) {
       // We found a function starts segment, parse the addresses for later
       // consumption.
       InMemoryStruct<macho::LinkeditDataLoadCommand> LLC;
-      MachOObj->ReadLinkeditDataLoadCommand(LCI, LLC);
+      MachOObj->getObject()->ReadLinkeditDataLoadCommand(LCI, LLC);
=20
-      MachOObj->ReadULEB128s(LLC->DataOffset, FoundFns);
-    }
-  }
-  // Store the symbols.
-  if (SymtabLC) {
-    for (unsigned i =3D 0; i !=3D (*SymtabLC)->NumSymbolTableEntries; ++i)=
 {
-      if (MachOObj->is64Bit()) {
-        InMemoryStruct<macho::Symbol64TableEntry> STE;
-        MachOObj->ReadSymbol64TableEntry((*SymtabLC)->SymbolTableOffset, i,
-                                         STE);
-        Symbols.push_back(copySymbol(STE));
-      } else {
-        InMemoryStruct<macho::SymbolTableEntry> STE;
-        MachOObj->ReadSymbolTableEntry((*SymtabLC)->SymbolTableOffset, i,
-                                       STE);
-        Symbols.push_back(copySymbol(STE));
-      }
+      MachOObj->getObject()->ReadULEB128s(LLC->DataOffset, FoundFns);
     }
   }
 }
@@ -277,9 +240,11 @@
     return;
   }
=20
-  OwningPtr<MachOObject> MachOObj(MachOObject::LoadFromBuffer(Buff.take())=
);
+  OwningPtr<MachOObjectFile> MachOOF(static_cast<MachOObjectFile*>(
+        ObjectFile::createMachOObjectFile(Buff.take())));
+  MachOObject *MachOObj =3D MachOOF->getObject();
=20
-  const Target *TheTarget =3D GetTarget(MachOObj.get());
+  const Target *TheTarget =3D GetTarget(MachOObj);
   if (!TheTarget) {
     // GetTarget prints out stuff.
     return;
@@ -293,9 +258,11 @@
   OwningPtr<const MCSubtargetInfo>
     STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
   OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*=
STI));
+  OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleNam=
e));
   int AsmPrinterVariant =3D AsmInfo->getAssemblerDialect();
-  OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
-                              AsmPrinterVariant, *AsmInfo, *STI));
+  OwningPtr<MCInstPrinter>
+    IP(TheTarget->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *InstrI=
nfo,
+                                      *MRI, *STI));
=20
   if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
     errs() << "error: couldn't initialize disassembler for target "
@@ -322,17 +289,17 @@
   MachOObj->ReadSymtabLoadCommand(*SymtabLCI, SymtabLC);
   MachOObj->RegisterStringTable(*SymtabLC);
=20
-  std::vector<Section> Sections;
-  std::vector<Symbol> Symbols;
+  std::vector<SectionRef> Sections;
+  std::vector<SymbolRef> Symbols;
   SmallVector<uint64_t, 8> FoundFns;
=20
-  getSectionsAndSymbols(Header, MachOObj.get(), &SymtabLC, Sections, Symbo=
ls,
+  getSectionsAndSymbols(Header, MachOOF.get(), &SymtabLC, Sections, Symbol=
s,
                         FoundFns);
=20
   // Make a copy of the unsorted symbol list. FIXME: duplication
-  std::vector<Symbol> UnsortedSymbols(Symbols);
+  std::vector<SymbolRef> UnsortedSymbols(Symbols);
   // Sort the symbols by address, just in case they didn't come in that wa=
y.
-  array_pod_sort(Symbols.begin(), Symbols.end());
+  std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
=20
 #ifndef NDEBUG
   raw_ostream &DebugOut =3D DebugFlag ? dbgs() : nulls();
@@ -343,12 +310,12 @@
   StringRef DebugAbbrevSection, DebugInfoSection, DebugArangesSection,
             DebugLineSection, DebugStrSection;
   OwningPtr<DIContext> diContext;
-  OwningPtr<MachOObject> DSYMObj;
-  MachOObject *DbgInfoObj =3D MachOObj.get();
+  OwningPtr<MachOObjectFile> DSYMObj;
+  MachOObject *DbgInfoObj =3D MachOObj;
   // Try to find debug info and set up the DIContext for it.
   if (UseDbg) {
-    ArrayRef<Section> DebugSections =3D Sections;
-    std::vector<Section> DSYMSections;
+    ArrayRef<SectionRef> DebugSections =3D Sections;
+    std::vector<SectionRef> DSYMSections;
=20
     // A separate DSym file path was specified, parse it as a macho file,
     // get the sections and supply it to the section name parsing machiner=
y.
@@ -358,34 +325,33 @@
         errs() << "llvm-objdump: " << Filename << ": " << ec.message() << =
'\n';
         return;
       }
-      DSYMObj.reset(MachOObject::LoadFromBuffer(Buf.take()));
-      const macho::Header &Header =3D DSYMObj->getHeader();
+      DSYMObj.reset(static_cast<MachOObjectFile*>(
+            ObjectFile::createMachOObjectFile(Buf.take())));
+      const macho::Header &Header =3D DSYMObj->getObject()->getHeader();
=20
-      std::vector<Symbol> Symbols;
+      std::vector<SymbolRef> Symbols;
       SmallVector<uint64_t, 8> FoundFns;
       getSectionsAndSymbols(Header, DSYMObj.get(), 0, DSYMSections, Symbol=
s,
                             FoundFns);
       DebugSections =3D DSYMSections;
-      DbgInfoObj =3D DSYMObj.get();
+      DbgInfoObj =3D DSYMObj.get()->getObject();
     }
=20
     // Find the named debug info sections.
     for (unsigned SectIdx =3D 0; SectIdx !=3D DebugSections.size(); SectId=
x++) {
-      if (!strcmp(DebugSections[SectIdx].Name, "__debug_abbrev"))
-        DebugAbbrevSection =3D DbgInfoObj->getData(DebugSections[SectIdx].=
Offset,
-                                                 DebugSections[SectIdx].Si=
ze);
-      else if (!strcmp(DebugSections[SectIdx].Name, "__debug_info"))
-        DebugInfoSection =3D DbgInfoObj->getData(DebugSections[SectIdx].Of=
fset,
-                                               DebugSections[SectIdx].Size=
);
-      else if (!strcmp(DebugSections[SectIdx].Name, "__debug_aranges"))
-        DebugArangesSection =3D DbgInfoObj->getData(DebugSections[SectIdx]=
.Offset,
-                                                  DebugSections[SectIdx].S=
ize);
-      else if (!strcmp(DebugSections[SectIdx].Name, "__debug_line"))
-        DebugLineSection =3D DbgInfoObj->getData(DebugSections[SectIdx].Of=
fset,
-                                               DebugSections[SectIdx].Size=
);
-      else if (!strcmp(DebugSections[SectIdx].Name, "__debug_str"))
-        DebugStrSection =3D DbgInfoObj->getData(DebugSections[SectIdx].Off=
set,
-                                              DebugSections[SectIdx].Size);
+      StringRef SectName;
+      if (!DebugSections[SectIdx].getName(SectName)) {
+        if (SectName.equals("__DWARF,__debug_abbrev"))
+          DebugSections[SectIdx].getContents(DebugAbbrevSection);
+        else if (SectName.equals("__DWARF,__debug_info"))
+          DebugSections[SectIdx].getContents(DebugInfoSection);
+        else if (SectName.equals("__DWARF,__debug_aranges"))
+          DebugSections[SectIdx].getContents(DebugArangesSection);
+        else if (SectName.equals("__DWARF,__debug_line"))
+          DebugSections[SectIdx].getContents(DebugLineSection);
+        else if (SectName.equals("__DWARF,__debug_str"))
+          DebugSections[SectIdx].getContents(DebugStrSection);
+      }
     }
=20
     // Setup the DIContext.
@@ -401,68 +367,115 @@
   FunctionListTy Functions;
=20
   for (unsigned SectIdx =3D 0; SectIdx !=3D Sections.size(); SectIdx++) {
-    if (strcmp(Sections[SectIdx].Name, "__text"))
+    StringRef SectName;
+    if (Sections[SectIdx].getName(SectName) ||
+        SectName.compare("__TEXT,__text"))
       continue; // Skip non-text sections
=20
     // Insert the functions from the function starts segment into our map.
-    uint64_t VMAddr =3D Sections[SectIdx].Address - Sections[SectIdx].Offs=
et;
-    for (unsigned i =3D 0, e =3D FoundFns.size(); i !=3D e; ++i)
-      FunctionMap.insert(std::make_pair(FoundFns[i]+VMAddr, (MCFunction*)0=
));
+    uint64_t VMAddr;
+    Sections[SectIdx].getAddress(VMAddr);
+    for (unsigned i =3D 0, e =3D FoundFns.size(); i !=3D e; ++i) {
+      StringRef SectBegin;
+      Sections[SectIdx].getContents(SectBegin);
+      uint64_t Offset =3D (uint64_t)SectBegin.data();
+      FunctionMap.insert(std::make_pair(VMAddr + FoundFns[i]-Offset,
+                                        (MCFunction*)0));
+    }
=20
-    StringRef Bytes =3D MachOObj->getData(Sections[SectIdx].Offset,
-                                        Sections[SectIdx].Size);
+    StringRef Bytes;
+    Sections[SectIdx].getContents(Bytes);
     StringRefMemoryObject memoryObject(Bytes);
     bool symbolTableWorked =3D false;
=20
     // Parse relocations.
-    std::vector<std::pair<uint64_t, uint32_t> > Relocs;
-    for (unsigned j =3D 0; j !=3D Sections[SectIdx].NumRelocs; ++j) {
-      InMemoryStruct<macho::RelocationEntry> RE;
-      MachOObj->ReadRelocationEntry(Sections[SectIdx].RelocTableOffset, j,=
 RE);
-      Relocs.push_back(std::make_pair(RE->Word0, RE->Word1 & 0xffffff));
+    std::vector<std::pair<uint64_t, SymbolRef> > Relocs;
+    error_code ec;
+    for (relocation_iterator RI =3D Sections[SectIdx].begin_relocations(),
+         RE =3D Sections[SectIdx].end_relocations(); RI !=3D RE; RI.increm=
ent(ec)) {
+      uint64_t RelocOffset, SectionAddress;
+      RI->getAddress(RelocOffset);
+      Sections[SectIdx].getAddress(SectionAddress);
+      RelocOffset -=3D SectionAddress;
+
+      SymbolRef RelocSym;
+      RI->getSymbol(RelocSym);
+
+      Relocs.push_back(std::make_pair(RelocOffset, RelocSym));
     }
     array_pod_sort(Relocs.begin(), Relocs.end());
=20
     // Disassemble symbol by symbol.
     for (unsigned SymIdx =3D 0; SymIdx !=3D Symbols.size(); SymIdx++) {
+      StringRef SymName;
+      Symbols[SymIdx].getName(SymName);
+
+      SymbolRef::Type ST;
+      Symbols[SymIdx].getType(ST);
+      if (ST !=3D SymbolRef::ST_Function)
+        continue;
+
       // Make sure the symbol is defined in this section.
-      if ((unsigned)Symbols[SymIdx].SectionIndex - 1 !=3D SectIdx)
+      bool containsSym =3D false;
+      Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
+      if (!containsSym)
         continue;
=20
       // Start at the address of the symbol relative to the section's addr=
ess.
-      uint64_t Start =3D Symbols[SymIdx].Value - Sections[SectIdx].Address;
+      uint64_t SectionAddress =3D 0;
+      uint64_t Start =3D 0;
+      Sections[SectIdx].getAddress(SectionAddress);
+      Symbols[SymIdx].getAddress(Start);
+      Start -=3D SectionAddress;
+
       // Stop disassembling either at the beginning of the next symbol or =
at
       // the end of the section.
-      uint64_t End =3D (SymIdx+1 =3D=3D Symbols.size() ||
-          Symbols[SymIdx].SectionIndex !=3D Symbols[SymIdx+1].SectionIndex=
) ?
-          Sections[SectIdx].Size :
-          Symbols[SymIdx+1].Value - Sections[SectIdx].Address;
+      bool containsNextSym =3D true;
+      uint64_t NextSym =3D 0;
+      uint64_t NextSymIdx =3D SymIdx+1;
+      while (Symbols.size() > NextSymIdx) {
+        SymbolRef::Type NextSymType;
+        Symbols[NextSymIdx].getType(NextSymType);
+        if (NextSymType =3D=3D SymbolRef::ST_Function) {
+          Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
+                                           containsNextSym);
+          Symbols[NextSymIdx].getAddress(NextSym);
+          NextSym -=3D SectionAddress;
+          break;
+        }
+        ++NextSymIdx;
+      }
+
+      uint64_t SectSize;
+      Sections[SectIdx].getSize(SectSize);
+      uint64_t End =3D containsNextSym ?  NextSym : SectSize;
       uint64_t Size;
=20
-      if (Start >=3D End)
-        continue;
-
       symbolTableWorked =3D true;
=20
       if (!CFG) {
         // Normal disassembly, print addresses, bytes and mnemonic form.
-        outs() << MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex)
-          << ":\n";
+        StringRef SymName;
+        Symbols[SymIdx].getName(SymName);
+
+        outs() << SymName << ":\n";
         DILineInfo lastLine;
         for (uint64_t Index =3D Start; Index < End; Index +=3D Size) {
           MCInst Inst;
=20
           if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
                                      DebugOut, nulls())) {
-            outs() << format("%8llx:\t", Sections[SectIdx].Address + Index=
);
+            uint64_t SectAddress =3D 0;
+            Sections[SectIdx].getAddress(SectAddress);
+            outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
+
             DumpBytes(StringRef(Bytes.data() + Index, Size));
             IP->printInst(&Inst, outs(), "");
=20
             // Print debug info.
             if (diContext) {
               DILineInfo dli =3D
-                diContext->getLineInfoForAddress(Sections[SectIdx].Address=
 +
-                                                 Index);
+                diContext->getLineInfoForAddress(SectAddress + Index);
               // Print valid line info if it changed.
               if (dli !=3D lastLine && dli.getLine() !=3D 0)
                 outs() << "\t## " << dli.getFileName() << ':'
@@ -478,20 +491,24 @@
         }
       } else {
         // Create CFG and use it for disassembly.
+        StringRef SymName;
+        Symbols[SymIdx].getName(SymName);
         createMCFunctionAndSaveCalls(
-            MachOObj->getStringAtIndex(Symbols[SymIdx].StringIndex),
-            DisAsm.get(), memoryObject, Start, End, InstrAnalysis.get(),
-            Start, DebugOut, FunctionMap, Functions);
+            SymName, DisAsm.get(), memoryObject, Start, End,
+            InstrAnalysis.get(), Start, DebugOut, FunctionMap, Functions);
       }
     }
=20
     if (CFG) {
       if (!symbolTableWorked) {
         // Reading the symbol table didn't work, create a big __TEXT symbo=
l.
+        uint64_t SectSize =3D 0, SectAddress =3D 0;
+        Sections[SectIdx].getSize(SectSize);
+        Sections[SectIdx].getAddress(SectAddress);
         createMCFunctionAndSaveCalls("__TEXT", DisAsm.get(), memoryObject,
-                                     0, Sections[SectIdx].Size,
+                                     0, SectSize,
                                      InstrAnalysis.get(),
-                                     Sections[SectIdx].Offset, DebugOut,
+                                     SectAddress, DebugOut,
                                      FunctionMap, Functions);
       }
       for (std::map<uint64_t, MCFunction*>::iterator mi =3D FunctionMap.be=
gin(),
@@ -499,11 +516,14 @@
         if (mi->second =3D=3D 0) {
           // Create functions for the remaining callees we have gathered,
           // but we didn't find a name for them.
+          uint64_t SectSize =3D 0;
+          Sections[SectIdx].getSize(SectSize);
+
           SmallVector<uint64_t, 16> Calls;
           MCFunction f =3D
             MCFunction::createFunctionFromMC("unknown", DisAsm.get(),
                                              memoryObject, mi->first,
-                                             Sections[SectIdx].Size,
+                                             SectSize,
                                              InstrAnalysis.get(), DebugOut,
                                              Calls);
           Functions.push_back(f);
@@ -535,13 +555,17 @@
               break;
             }
=20
+          uint64_t SectSize =3D 0, SectAddress;
+          Sections[SectIdx].getSize(SectSize);
+          Sections[SectIdx].getAddress(SectAddress);
+
           // No predecessors, this is a data block. Print as .byte directi=
ves.
           if (!hasPreds) {
-            uint64_t End =3D llvm::next(fi) =3D=3D fe ? Sections[SectIdx].=
Size :
+            uint64_t End =3D llvm::next(fi) =3D=3D fe ? SectSize :
                                                   llvm::next(fi)->first;
             outs() << "# " << End-fi->first << " bytes of data:\n";
             for (unsigned pos =3D fi->first; pos !=3D End; ++pos) {
-              outs() << format("%8x:\t", Sections[SectIdx].Address + pos);
+              outs() << format("%8x:\t", SectAddress + pos);
               DumpBytes(StringRef(Bytes.data() + pos, 1));
               outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
             }
@@ -558,13 +582,12 @@
             const MCDecodedInst &Inst =3D fi->second.getInsts()[ii];
=20
             // If there's a symbol at this address, print its name.
-            if (FunctionMap.find(Sections[SectIdx].Address + Inst.Address)=
 !=3D
+            if (FunctionMap.find(SectAddress + Inst.Address) !=3D
                 FunctionMap.end())
-              outs() << FunctionMap[Sections[SectIdx].Address + Inst.Addre=
ss]->
-                                                             getName() << =
":\n";
+              outs() << FunctionMap[SectAddress + Inst.Address]-> getName()
+                     << ":\n";
=20
-            outs() << format("%8llx:\t", Sections[SectIdx].Address +
-                                         Inst.Address);
+            outs() << format("%8" PRIx64 ":\t", SectAddress + Inst.Address=
);
             DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
=20
             if (fi->second.contains(fi->first)) // Indent simple loops.
@@ -575,15 +598,15 @@
             // Look for relocations inside this instructions, if there is =
one
             // print its target and additional information if available.
             for (unsigned j =3D 0; j !=3D Relocs.size(); ++j)
-              if (Relocs[j].first >=3D Sections[SectIdx].Address + Inst.Ad=
dress &&
-                  Relocs[j].first < Sections[SectIdx].Address + Inst.Addre=
ss +
-                                    Inst.Size) {
-                outs() << "\t# "
-                   << MachOObj->getStringAtIndex(
-                                  UnsortedSymbols[Relocs[j].second].String=
Index)
-                   << ' ';
-                DumpAddress(UnsortedSymbols[Relocs[j].second].Value, Secti=
ons,
-                            MachOObj.get(), outs());
+              if (Relocs[j].first >=3D SectAddress + Inst.Address &&
+                  Relocs[j].first < SectAddress + Inst.Address + Inst.Size=
) {
+                StringRef SymName;
+                uint64_t Addr;
+                Relocs[j].second.getAddress(Addr);
+                Relocs[j].second.getName(SymName);
+
+                outs() << "\t# " << SymName << ' ';
+                DumpAddress(Addr, Sections, MachOObj, outs());
               }
=20
             // If this instructions contains an address, see if we can eva=
luate
@@ -592,13 +615,12 @@
                                                           Inst.Address,
                                                           Inst.Size);
             if (targ !=3D -1ULL)
-              DumpAddress(targ, Sections, MachOObj.get(), outs());
+              DumpAddress(targ, Sections, MachOObj, outs());
=20
             // Print debug info.
             if (diContext) {
               DILineInfo dli =3D
-                diContext->getLineInfoForAddress(Sections[SectIdx].Address=
 +
-                                                 Inst.Address);
+                diContext->getLineInfoForAddress(SectAddress + Inst.Addres=
s);
               // Print valid line info if it changed.
               if (dli !=3D lastLine && dli.getLine() !=3D 0)
                 outs() << "\t## " << dli.getFileName() << ':'
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-objdump/l=
lvm-objdump.cpp
--- a/head/contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-objdump/llvm-objdump.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -16,14 +16,18 @@
 #include "llvm-objdump.h"
 #include "MCFunction.h"
 #include "llvm/Object/Archive.h"
+#include "llvm/Object/COFF.h"
 #include "llvm/Object/ObjectFile.h"
 #include "llvm/ADT/OwningPtr.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/Triple.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/MC/MCAsmInfo.h"
 #include "llvm/MC/MCDisassembler.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCInstPrinter.h"
+#include "llvm/MC/MCInstrInfo.h"
+#include "llvm/MC/MCRegisterInfo.h"
 #include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/CommandLine.h"
@@ -43,6 +47,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/system_error.h"
 #include <algorithm>
+#include <cctype>
 #include <cstring>
 using namespace llvm;
 using namespace object;
@@ -61,6 +66,12 @@
 Relocations("r", cl::desc("Display the relocation entries in the file"));
=20
 static cl::opt<bool>
+SectionContents("s", cl::desc("Display the content of each section"));
+
+static cl::opt<bool>
+SymbolTable("t", cl::desc("Display the symbol table"));
+
+static cl::opt<bool>
 MachO("macho", cl::desc("Use MachO specific object file parser"));
 static cl::alias
 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
@@ -118,6 +129,8 @@
   return 0;
 }
=20
+void llvm::StringRefMemoryObject::anchor() { }
+
 void llvm::DumpBytes(StringRef bytes) {
   static const char hex_rep[] =3D "0123456789abcdef";
   // FIXME: The real way to do this is to figure out the longest instructi=
on
@@ -158,10 +171,6 @@
     return;
   }
=20
-  outs() << '\n';
-  outs() << Obj->getFileName()
-         << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
-
   error_code ec;
   for (section_iterator i =3D Obj->begin_sections(),
                         e =3D Obj->end_sections();
@@ -182,7 +191,9 @@
       bool contains;
       if (!error(i->containsSymbol(*si, contains)) && contains) {
         uint64_t Address;
-        if (error(si->getOffset(Address))) break;
+        if (error(si->getAddress(Address))) break;
+        Address -=3D SectionAddr;
+
         StringRef Name;
         if (error(si->getName(Name))) break;
         Symbols.push_back(std::make_pair(Address, Name));
@@ -238,9 +249,21 @@
       return;
     }
=20
+    OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleN=
ame));
+    if (!MRI) {
+      errs() << "error: no register info for target " << TripleName << "\n=
";
+      return;
+    }
+
+    OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
+    if (!MII) {
+      errs() << "error: no instruction info for target " << TripleName << =
"\n";
+      return;
+    }
+
     int AsmPrinterVariant =3D AsmInfo->getAssemblerDialect();
     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
-                                AsmPrinterVariant, *AsmInfo, *STI));
+                                AsmPrinterVariant, *AsmInfo, *MII, *MRI, *=
STI));
     if (!IP) {
       errs() << "error: no instruction printer for target " << TripleName
              << '\n';
@@ -285,7 +308,7 @@
=20
         if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
                                    DebugOut, nulls())) {
-          outs() << format("%8"PRIx64":\t", SectionAddr + Index);
+          outs() << format("%8" PRIx64 ":\t", SectionAddr + Index);
           DumpBytes(StringRef(Bytes.data() + Index, Size));
           IP->printInst(&Inst, outs(), "");
           outs() << "\n";
@@ -297,17 +320,23 @@
=20
         // Print relocation for instruction.
         while (rel_cur !=3D rel_end) {
+          bool hidden =3D false;
           uint64_t addr;
           SmallString<16> name;
           SmallString<32> val;
+
+          // If this relocation is hidden, skip it.
+          if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
+          if (hidden) goto skip_print_rel;
+
           if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
           // Stop when rel_cur's address is past the current instruction.
-          if (addr > Index + Size) break;
+          if (addr >=3D Index + Size) break;
           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
=20
-          outs() << format("\t\t\t%8"PRIx64": ", SectionAddr + addr) << na=
me << "\t"
-                 << val << "\n";
+          outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << =
name
+                 << "\t" << val << "\n";
=20
         skip_print_rel:
           ++rel_cur;
@@ -332,9 +361,12 @@
                              ri !=3D re; ri.increment(ec)) {
       if (error(ec)) return;
=20
+      bool hidden;
       uint64_t address;
       SmallString<32> relocname;
       SmallString<32> valuestr;
+      if (error(ri->getHidden(hidden))) continue;
+      if (hidden) continue;
       if (error(ri->getTypeName(relocname))) continue;
       if (error(ri->getAddress(address))) continue;
       if (error(ri->getValueString(valuestr))) continue;
@@ -364,19 +396,179 @@
     if (error(si->isBSS(BSS))) return;
     std::string Type =3D (std::string(Text ? "TEXT " : "") +
                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
-    outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.st=
r().c_str(), Size,
-                     Address, Type.c_str());
+    outs() << format("%3d %-13s %09" PRIx64 " %017" PRIx64 " %s\n",
+                     i, Name.str().c_str(), Size, Address, Type.c_str());
     ++i;
   }
 }
=20
+static void PrintSectionContents(const ObjectFile *o) {
+  error_code ec;
+  for (section_iterator si =3D o->begin_sections(),
+                        se =3D o->end_sections();
+                        si !=3D se; si.increment(ec)) {
+    if (error(ec)) return;
+    StringRef Name;
+    StringRef Contents;
+    uint64_t BaseAddr;
+    if (error(si->getName(Name))) continue;
+    if (error(si->getContents(Contents))) continue;
+    if (error(si->getAddress(BaseAddr))) continue;
+
+    outs() << "Contents of section " << Name << ":\n";
+
+    // Dump out the content as hex and printable ascii characters.
+    for (std::size_t addr =3D 0, end =3D Contents.size(); addr < end; addr=
 +=3D 16) {
+      outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
+      // Dump line of hex.
+      for (std::size_t i =3D 0; i < 16; ++i) {
+        if (i !=3D 0 && i % 4 =3D=3D 0)
+          outs() << ' ';
+        if (addr + i < end)
+          outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
+                 << hexdigit(Contents[addr + i] & 0xF, true);
+        else
+          outs() << "  ";
+      }
+      // Print ascii.
+      outs() << "  ";
+      for (std::size_t i =3D 0; i < 16 && addr + i < end; ++i) {
+        if (std::isprint(Contents[addr + i] & 0xFF))
+          outs() << Contents[addr + i];
+        else
+          outs() << ".";
+      }
+      outs() << "\n";
+    }
+  }
+}
+
+static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
+  const coff_file_header *header;
+  if (error(coff->getHeader(header))) return;
+  int aux_count =3D 0;
+  const coff_symbol *symbol =3D 0;
+  for (int i =3D 0, e =3D header->NumberOfSymbols; i !=3D e; ++i) {
+    if (aux_count--) {
+      // Figure out which type of aux this is.
+      if (symbol->StorageClass =3D=3D COFF::IMAGE_SYM_CLASS_STATIC
+          && symbol->Value =3D=3D 0) { // Section definition.
+        const coff_aux_section_definition *asd;
+        if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
+          return;
+        outs() << "AUX "
+               << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
+                         , unsigned(asd->Length)
+                         , unsigned(asd->NumberOfRelocations)
+                         , unsigned(asd->NumberOfLinenumbers)
+                         , unsigned(asd->CheckSum))
+               << format("assoc %d comdat %d\n"
+                         , unsigned(asd->Number)
+                         , unsigned(asd->Selection));
+      } else {
+        outs() << "AUX Unknown\n";
+      }
+    } else {
+      StringRef name;
+      if (error(coff->getSymbol(i, symbol))) return;
+      if (error(coff->getSymbolName(symbol, name))) return;
+      outs() << "[" << format("%2d", i) << "]"
+             << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
+             << "(fl 0x00)" // Flag bits, which COFF doesn't have.
+             << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
+             << "(scl " << format("%3x", unsigned(symbol->StorageClass)) <=
< ") "
+             << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
+             << "0x" << format("%08x", unsigned(symbol->Value)) << " "
+             << name << "\n";
+      aux_count =3D symbol->NumberOfAuxSymbols;
+    }
+  }
+}
+
+static void PrintSymbolTable(const ObjectFile *o) {
+  outs() << "SYMBOL TABLE:\n";
+
+  if (const COFFObjectFile *coff =3D dyn_cast<const COFFObjectFile>(o))
+    PrintCOFFSymbolTable(coff);
+  else {
+    error_code ec;
+    for (symbol_iterator si =3D o->begin_symbols(),
+                         se =3D o->end_symbols(); si !=3D se; si.increment=
(ec)) {
+      if (error(ec)) return;
+      StringRef Name;
+      uint64_t Address;
+      SymbolRef::Type Type;
+      uint64_t Size;
+      uint32_t Flags;
+      section_iterator Section =3D o->end_sections();
+      if (error(si->getName(Name))) continue;
+      if (error(si->getAddress(Address))) continue;
+      if (error(si->getFlags(Flags))) continue;
+      if (error(si->getType(Type))) continue;
+      if (error(si->getSize(Size))) continue;
+      if (error(si->getSection(Section))) continue;
+
+      bool Global =3D Flags & SymbolRef::SF_Global;
+      bool Weak =3D Flags & SymbolRef::SF_Weak;
+      bool Absolute =3D Flags & SymbolRef::SF_Absolute;
+
+      if (Address =3D=3D UnknownAddressOrSize)
+        Address =3D 0;
+      if (Size =3D=3D UnknownAddressOrSize)
+        Size =3D 0;
+      char GlobLoc =3D ' ';
+      if (Type !=3D SymbolRef::ST_Unknown)
+        GlobLoc =3D Global ? 'g' : 'l';
+      char Debug =3D (Type =3D=3D SymbolRef::ST_Debug || Type =3D=3D Symbo=
lRef::ST_File)
+                   ? 'd' : ' ';
+      char FileFunc =3D ' ';
+      if (Type =3D=3D SymbolRef::ST_File)
+        FileFunc =3D 'f';
+      else if (Type =3D=3D SymbolRef::ST_Function)
+        FileFunc =3D 'F';
+
+      outs() << format("%08" PRIx64, Address) << " "
+             << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
+             << (Weak ? 'w' : ' ') // Weak?
+             << ' ' // Constructor. Not supported yet.
+             << ' ' // Warning. Not supported yet.
+             << ' ' // Indirect reference to another symbol.
+             << Debug // Debugging (d) or dynamic (D) symbol.
+             << FileFunc // Name of function (F), file (f) or object (O).
+             << ' ';
+      if (Absolute)
+        outs() << "*ABS*";
+      else if (Section =3D=3D o->end_sections())
+        outs() << "*UND*";
+      else {
+        StringRef SectionName;
+        if (error(Section->getName(SectionName)))
+          SectionName =3D "";
+        outs() << SectionName;
+      }
+      outs() << '\t'
+             << format("%08" PRIx64 " ", Size)
+             << Name
+             << '\n';
+    }
+  }
+}
+
 static void DumpObject(const ObjectFile *o) {
+  outs() << '\n';
+  outs() << o->getFileName()
+         << ":\tfile format " << o->getFileFormatName() << "\n\n";
+
   if (Disassemble)
     DisassembleObject(o, Relocations);
   if (Relocations && !Disassemble)
     PrintRelocations(o);
   if (SectionHeaders)
     PrintSectionHeaders(o);
+  if (SectionContents)
+    PrintSectionContents(o);
+  if (SymbolTable)
+    PrintSymbolTable(o);
 }
=20
 /// @brief Dump each object file in \a a;
@@ -385,8 +577,10 @@
                                e =3D a->end_children(); i !=3D e; ++i) {
     OwningPtr<Binary> child;
     if (error_code ec =3D i->getAsBinary(child)) {
-      errs() << ToolName << ": '" << a->getFileName() << "': " << ec.messa=
ge()
-             << ".\n";
+      // Ignore non-object files.
+      if (ec !=3D object_error::invalid_file_type)
+        errs() << ToolName << ": '" << a->getFileName() << "': " << ec.mes=
sage()
+               << ".\n";
       continue;
     }
     if (ObjectFile *o =3D dyn_cast<ObjectFile>(child.get()))
@@ -447,7 +641,11 @@
   if (InputFilenames.size() =3D=3D 0)
     InputFilenames.push_back("a.out");
=20
-  if (!Disassemble && !Relocations && !SectionHeaders) {
+  if (!Disassemble
+      && !Relocations
+      && !SectionHeaders
+      && !SectionContents
+      && !SymbolTable) {
     cl::PrintHelpMessage();
     return 2;
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-objdump/l=
lvm-objdump.h
--- a/head/contrib/llvm/tools/llvm-objdump/llvm-objdump.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-objdump/llvm-objdump.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -25,7 +25,7 @@
 void DisassembleInputMachO(StringRef Filename);
=20
 class StringRefMemoryObject : public MemoryObject {
-private:
+  virtual void anchor();
   StringRef Bytes;
 public:
   StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-prof/llvm=
-prof.cpp
--- a/head/contrib/llvm/tools/llvm-prof/llvm-prof.cpp	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/contrib/llvm/tools/llvm-prof/llvm-prof.cpp	Tue Apr 17 11:51:51 2=
012 +0300
@@ -200,9 +200,9 @@
     }
=20
     outs() << format("%3d", i+1) << ". "
-      << format("%5.2g", FunctionCounts[i].second) << "/"
-      << format("%g", TotalExecutions) << " "
-      << FunctionCounts[i].first->getNameStr() << "\n";
+           << format("%5.2g", FunctionCounts[i].second) << "/"
+           << format("%g", TotalExecutions) << " "
+           << FunctionCounts[i].first->getName() << "\n";
   }
=20
   std::set<Function*> FunctionsToPrint;
@@ -225,12 +225,12 @@
   for (unsigned i =3D 0; i !=3D BlocksToPrint; ++i) {
     if (Counts[i].second =3D=3D 0) break;
     Function *F =3D Counts[i].first->getParent();
-    outs() << format("%3d", i+1) << ". "=20
-      << format("%5g", Counts[i].second/(double)TotalExecutions*100) << "%=
 "
-      << format("%5.0f", Counts[i].second) << "/"
-      << format("%g", TotalExecutions) << "\t"
-      << F->getNameStr() << "() - "
-       << Counts[i].first->getNameStr() << "\n";
+    outs() << format("%3d", i+1) << ". "
+           << format("%5g", Counts[i].second/(double)TotalExecutions*100)<=
<"% "
+           << format("%5.0f", Counts[i].second) << "/"
+           << format("%g", TotalExecutions) << "\t"
+           << F->getName() << "() - "
+           << Counts[i].first->getName() << "\n";
     FunctionsToPrint.insert(F);
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/llvm-rtdyld/ll=
vm-rtdyld.cpp
--- a/head/contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/tools/llvm-rtdyld/llvm-rtdyld.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -51,22 +51,30 @@
 class TrivialMemoryManager : public RTDyldMemoryManager {
 public:
   SmallVector<sys::MemoryBlock, 16> FunctionMemory;
+  SmallVector<sys::MemoryBlock, 16> DataMemory;
=20
-  uint8_t *startFunctionBody(const char *Name, uintptr_t &Size);
-  void endFunctionBody(const char *Name, uint8_t *FunctionStart,
-                       uint8_t *FunctionEnd);
+  uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
+                               unsigned SectionID);
+  uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
+                               unsigned SectionID);
+
+  virtual void *getPointerToNamedFunction(const std::string &Name,
+                                          bool AbortOnFailure =3D true) {
+    return 0;
+  }
+
 };
=20
-uint8_t *TrivialMemoryManager::startFunctionBody(const char *Name,
-                                                 uintptr_t &Size) {
+uint8_t *TrivialMemoryManager::allocateCodeSection(uintptr_t Size,
+                                                   unsigned Alignment,
+                                                   unsigned SectionID) {
   return (uint8_t*)sys::Memory::AllocateRWX(Size, 0, 0).base();
 }
=20
-void TrivialMemoryManager::endFunctionBody(const char *Name,
-                                           uint8_t *FunctionStart,
-                                           uint8_t *FunctionEnd) {
-  uintptr_t Size =3D FunctionEnd - FunctionStart + 1;
-  FunctionMemory.push_back(sys::MemoryBlock(FunctionStart, Size));
+uint8_t *TrivialMemoryManager::allocateDataSection(uintptr_t Size,
+                                                   unsigned Alignment,
+                                                   unsigned SectionID) {
+  return (uint8_t*)sys::Memory::AllocateRWX(Size, 0, 0).base();
 }
=20
 static const char *ProgramName;
@@ -142,10 +150,7 @@
   cl::ParseCommandLineOptions(argc, argv, "llvm MC-JIT tool\n");
=20
   switch (Action) {
-  default:
   case AC_Execute:
     return executeInput();
   }
-
-  return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/opt/PrintSCC.c=
pp
--- a/head/contrib/llvm/tools/opt/PrintSCC.cpp	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/contrib/llvm/tools/opt/PrintSCC.cpp	Tue Apr 17 11:51:51 2012 +03=
00
@@ -101,8 +101,8 @@
     errs() << "\nSCC #" << ++sccNum << " : ";
     for (std::vector<CallGraphNode*>::const_iterator I =3D nextSCC.begin(),
            E =3D nextSCC.end(); I !=3D E; ++I)
-      errs() << ((*I)->getFunction() ? (*I)->getFunction()->getNameStr()
-                 : std::string("external node")) << ", ";
+      errs() << ((*I)->getFunction() ? (*I)->getFunction()->getName()
+                                     : "external node") << ", ";
     if (nextSCC.size() =3D=3D 1 && SCCI.hasLoop())
       errs() << " (Has self-loop).";
   }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/tools/opt/opt.cpp
--- a/head/contrib/llvm/tools/opt/opt.cpp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/llvm/tools/opt/opt.cpp	Tue Apr 17 11:51:51 2012 +0300
@@ -291,8 +291,8 @@
   virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
     if (!Quiet) {
       Out << "Printing analysis '" << PassToPrint->getPassName() << "' for=
 "
-        << "region: '" << R->getNameStr() << "' in function '"
-        << R->getEntry()->getParent()->getNameStr() << "':\n";
+          << "region: '" << R->getNameStr() << "' in function '"
+          << R->getEntry()->getParent()->getName() << "':\n";
     }
     // Get and print pass...
    getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
@@ -407,6 +407,8 @@
 /// OptLevel - Optimization Level
 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager=
 &FPM,
                                   unsigned OptLevel) {
+  FPM.add(createVerifierPass());                  // Verify that input is =
correct
+
   PassManagerBuilder Builder;
   Builder.OptLevel =3D OptLevel;
=20
@@ -478,6 +480,7 @@
   PassRegistry &Registry =3D *PassRegistry::getPassRegistry();
   initializeCore(Registry);
   initializeScalarOpts(Registry);
+  initializeVectorization(Registry);
   initializeIPO(Registry);
   initializeAnalysis(Registry);
   initializeIPA(Registry);
@@ -505,7 +508,7 @@
   M.reset(ParseIRFile(InputFilename, Err, Context));
=20
   if (M.get() =3D=3D 0) {
-    Err.Print(argv[0], errs());
+    Err.print(argv[0], errs());
     return 1;
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/AsmMa=
tcherEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/AsmMatcherEmitter.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/AsmMatcherEmitter.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -99,6 +99,7 @@
 #include "AsmMatcherEmitter.h"
 #include "CodeGenTarget.h"
 #include "StringMatcher.h"
+#include "StringToOffsetTable.h"
 #include "llvm/ADT/OwningPtr.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -107,6 +108,7 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
 #include <map>
@@ -251,12 +253,7 @@
=20
     switch (Kind) {
     case Invalid:
-      assert(0 && "Invalid kind!");
-    case Token:
-      // Tokens are comparable by value.
-      //
-      // FIXME: Compare by enum value.
-      return ValueName < RHS.ValueName;
+      llvm_unreachable("Invalid kind!");
=20
     default:
       // This class precedes the RHS if it is a proper subset of the RHS.
@@ -287,7 +284,11 @@
     /// The suboperand index within SrcOpName, or -1 for the entire operan=
d.
     int SubOpIdx;
=20
-    explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1) {}
+    /// Register record if this token is singleton register.
+    Record *SingletonReg;
+
+    explicit AsmOperand(StringRef T) : Token(T), Class(0), SubOpIdx(-1),
+                                       SingletonReg(0) {}
   };
=20
   /// ResOperand - This represents a single operand in the result instruct=
ion
@@ -366,6 +367,9 @@
     }
   };
=20
+  /// AsmVariantID - Target's assembly syntax variant no.
+  int AsmVariantID;
+
   /// TheDef - This is the definition of the instruction or InstAlias that=
 this
   /// matchable came from.
   Record *const TheDef;
@@ -406,24 +410,28 @@
   std::string ConversionFnKind;
=20
   MatchableInfo(const CodeGenInstruction &CGI)
-    : TheDef(CGI.TheDef), DefRec(&CGI), AsmString(CGI.AsmString) {
+    : AsmVariantID(0), TheDef(CGI.TheDef), DefRec(&CGI),
+      AsmString(CGI.AsmString) {
   }
=20
   MatchableInfo(const CodeGenInstAlias *Alias)
-    : TheDef(Alias->TheDef), DefRec(Alias), AsmString(Alias->AsmString) {
+    : AsmVariantID(0), TheDef(Alias->TheDef), DefRec(Alias),
+      AsmString(Alias->AsmString) {
   }
=20
   void Initialize(const AsmMatcherInfo &Info,
-                  SmallPtrSet<Record*, 16> &SingletonRegisters);
+                  SmallPtrSet<Record*, 16> &SingletonRegisters,
+                  int AsmVariantNo, std::string &RegisterPrefix);
=20
   /// Validate - Return true if this matchable is a valid thing to match a=
gainst
   /// and perform a bunch of validity checking.
   bool Validate(StringRef CommentDelimiter, bool Hack) const;
=20
-  /// getSingletonRegisterForAsmOperand - If the specified token is a sing=
leton
-  /// register, return the Record for it, otherwise return null.
-  Record *getSingletonRegisterForAsmOperand(unsigned i,
-                                            const AsmMatcherInfo &Info) co=
nst;
+  /// extractSingletonRegisterForAsmOperand - Extract singleton register,
+  /// if present, from specified token.
+  void
+  extractSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &=
Info,
+                                        std::string &RegisterPrefix);
=20
   /// FindAsmOperand - Find the AsmOperand with the specified name and
   /// suboperand index.
@@ -557,9 +565,6 @@
   /// Target - The target information.
   CodeGenTarget &Target;
=20
-  /// The AsmParser "RegisterPrefix" value.
-  std::string RegisterPrefix;
-
   /// The classes which are needed for matching.
   std::vector<ClassInfo*> Classes;
=20
@@ -591,7 +596,8 @@
=20
   /// getOperandClass - Lookup or create the class for the given operand.
   ClassInfo *getOperandClass(const CGIOperandList::OperandInfo &OI,
-                             int SubOpIdx =3D -1);
+                             int SubOpIdx);
+  ClassInfo *getOperandClass(Record *Rec, int SubOpIdx);
=20
   /// BuildRegisterClasses - Build the ClassInfo* instances for register
   /// classes.
@@ -645,9 +651,11 @@
 }
=20
 void MatchableInfo::Initialize(const AsmMatcherInfo &Info,
-                               SmallPtrSet<Record*, 16> &SingletonRegister=
s) {
-  // TODO: Eventually support asmparser for Variant !=3D 0.
-  AsmString =3D CodeGenInstruction::FlattenAsmStringVariants(AsmString, 0);
+                               SmallPtrSet<Record*, 16> &SingletonRegister=
s,
+                               int AsmVariantNo, std::string &RegisterPref=
ix) {
+  AsmVariantID =3D AsmVariantNo;
+  AsmString =3D
+    CodeGenInstruction::FlattenAsmStringVariants(AsmString, AsmVariantNo);
=20
   TokenizeAsmString(Info);
=20
@@ -660,7 +668,8 @@
=20
   // Collect singleton registers, if used.
   for (unsigned i =3D 0, e =3D AsmOperands.size(); i !=3D e; ++i) {
-    if (Record *Reg =3D getSingletonRegisterForAsmOperand(i, Info))
+    extractSingletonRegisterForAsmOperand(i, Info, RegisterPrefix);
+    if (Record *Reg =3D AsmOperands[i].SingletonReg)
       SingletonRegisters.insert(Reg);
   }
 }
@@ -736,9 +745,12 @@
=20
   // The first token of the instruction is the mnemonic, which must be a
   // simple string, not a $foo variable or a singleton register.
-  assert(!AsmOperands.empty() && "Instruction has no tokens?");
+  if (AsmOperands.empty())
+    throw TGError(TheDef->getLoc(),
+                  "Instruction '" + TheDef->getName() + "' has no tokens");
   Mnemonic =3D AsmOperands[0].Token;
-  if (Mnemonic[0] =3D=3D '$' || getSingletonRegisterForAsmOperand(0, Info))
+  // FIXME : Check and raise an error if it is a register.
+  if (Mnemonic[0] =3D=3D '$')
     throw TGError(TheDef->getLoc(),
                   "Invalid instruction mnemonic '" + Mnemonic.str() + "'!"=
);
=20
@@ -801,28 +813,30 @@
   return true;
 }
=20
-/// getSingletonRegisterForAsmOperand - If the specified token is a single=
ton
-/// register, return the register name, otherwise return a null StringRef.
-Record *MatchableInfo::
-getSingletonRegisterForAsmOperand(unsigned i, const AsmMatcherInfo &Info) =
const{
-  StringRef Tok =3D AsmOperands[i].Token;
-  if (!Tok.startswith(Info.RegisterPrefix))
-    return 0;
-
-  StringRef RegName =3D Tok.substr(Info.RegisterPrefix.size());
+/// extractSingletonRegisterForAsmOperand - Extract singleton register,
+/// if present, from specified token.
+void MatchableInfo::
+extractSingletonRegisterForAsmOperand(unsigned OperandNo,
+                                      const AsmMatcherInfo &Info,
+                                      std::string &RegisterPrefix) {
+  StringRef Tok =3D AsmOperands[OperandNo].Token;
+  if (RegisterPrefix.empty()) {
+    std::string LoweredTok =3D Tok.lower();
+    if (const CodeGenRegister *Reg =3D Info.Target.getRegisterByName(Lower=
edTok))
+      AsmOperands[OperandNo].SingletonReg =3D Reg->TheDef;
+    return;
+  }
+
+  if (!Tok.startswith(RegisterPrefix))
+    return;
+
+  StringRef RegName =3D Tok.substr(RegisterPrefix.size());
   if (const CodeGenRegister *Reg =3D Info.Target.getRegisterByName(RegName=
))
-    return Reg->TheDef;
+    AsmOperands[OperandNo].SingletonReg =3D Reg->TheDef;
=20
   // If there is no register prefix (i.e. "%" in "%eax"), then this may
   // be some random non-register token, just ignore it.
-  if (Info.RegisterPrefix.empty())
-    return 0;
-
-  // Otherwise, we have something invalid prefixed with the register prefi=
x,
-  // such as %foo.
-  std::string Err =3D "unable to find register for '" + RegName.str() +
-  "' (which matches register prefix)";
-  throw TGError(TheDef->getLoc(), Err);
+  return;
 }
=20
 static std::string getEnumNameForToken(StringRef Str) {
@@ -870,7 +884,11 @@
   Record *Rec =3D OI.Rec;
   if (SubOpIdx !=3D -1)
     Rec =3D dynamic_cast<DefInit*>(OI.MIOperandInfo->getArg(SubOpIdx))->ge=
tDef();
-
+  return getOperandClass(Rec, SubOpIdx);
+}
+
+ClassInfo *
+AsmMatcherInfo::getOperandClass(Record *Rec, int SubOpIdx) {
   if (Rec->isSubClassOf("RegisterOperand")) {
     // RegisterOperand may have an associated ParserMatchClass. If it does,
     // use it, else just fall back to the underlying register class.
@@ -1102,8 +1120,7 @@
 AsmMatcherInfo::AsmMatcherInfo(Record *asmParser,
                                CodeGenTarget &target,
                                RecordKeeper &records)
-  : Records(records), AsmParser(asmParser), Target(target),
-    RegisterPrefix(AsmParser->getValueAsString("RegisterPrefix")) {
+  : Records(records), AsmParser(asmParser), Target(target) {
 }
=20
 /// BuildOperandMatchInfo - Build the necessary information to handle user
@@ -1158,86 +1175,92 @@
     assert(FeatureNo < 32 && "Too many subtarget features!");
   }
=20
-  std::string CommentDelimiter =3D AsmParser->getValueAsString("CommentDel=
imiter");
-
   // Parse the instructions; we need to do this first so that we can gathe=
r the
   // singleton register classes.
   SmallPtrSet<Record*, 16> SingletonRegisters;
-  for (CodeGenTarget::inst_iterator I =3D Target.inst_begin(),
-       E =3D Target.inst_end(); I !=3D E; ++I) {
-    const CodeGenInstruction &CGI =3D **I;
-
-    // If the tblgen -match-prefix option is specified (for tblgen hackers=
),
-    // filter the set of instructions we consider.
-    if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
-      continue;
-
-    // Ignore "codegen only" instructions.
-    if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
-      continue;
-
-    // Validate the operand list to ensure we can handle this instruction.
-    for (unsigned i =3D 0, e =3D CGI.Operands.size(); i !=3D e; ++i) {
-      const CGIOperandList::OperandInfo &OI =3D CGI.Operands[i];
-
-      // Validate tied operands.
-      if (OI.getTiedRegister() !=3D -1) {
-        // If we have a tied operand that consists of multiple MCOperands,
-        // reject it.  We reject aliases and ignore instructions for now.
-        if (OI.MINumOperands !=3D 1) {
-          // FIXME: Should reject these.  The ARM backend hits this with $=
lane
-          // in a bunch of instructions. It is unclear what the right answ=
er is.
-          DEBUG({
-            errs() << "warning: '" << CGI.TheDef->getName() << "': "
-            << "ignoring instruction with multi-operand tied operand '"
-            << OI.Name << "'\n";
-          });
-          continue;
+  unsigned VariantCount =3D Target.getAsmParserVariantCount();
+  for (unsigned VC =3D 0; VC !=3D VariantCount; ++VC) {
+    Record *AsmVariant =3D Target.getAsmParserVariant(VC);
+    std::string CommentDelimiter =3D AsmVariant->getValueAsString("Comment=
Delimiter");
+    std::string RegisterPrefix =3D AsmVariant->getValueAsString("RegisterP=
refix");
+    int AsmVariantNo =3D AsmVariant->getValueAsInt("Variant");
+
+    for (CodeGenTarget::inst_iterator I =3D Target.inst_begin(),
+           E =3D Target.inst_end(); I !=3D E; ++I) {
+      const CodeGenInstruction &CGI =3D **I;
+
+      // If the tblgen -match-prefix option is specified (for tblgen hacke=
rs),
+      // filter the set of instructions we consider.
+      if (!StringRef(CGI.TheDef->getName()).startswith(MatchPrefix))
+        continue;
+
+      // Ignore "codegen only" instructions.
+      if (CGI.TheDef->getValueAsBit("isCodeGenOnly"))
+        continue;
+
+      // Validate the operand list to ensure we can handle this instructio=
n.
+      for (unsigned i =3D 0, e =3D CGI.Operands.size(); i !=3D e; ++i) {
+        const CGIOperandList::OperandInfo &OI =3D CGI.Operands[i];
+
+        // Validate tied operands.
+        if (OI.getTiedRegister() !=3D -1) {
+          // If we have a tied operand that consists of multiple MCOperand=
s,
+          // reject it.  We reject aliases and ignore instructions for now.
+          if (OI.MINumOperands !=3D 1) {
+            // FIXME: Should reject these.  The ARM backend hits this with=
 $lane
+            // in a bunch of instructions. It is unclear what the right an=
swer is.
+            DEBUG({
+                errs() << "warning: '" << CGI.TheDef->getName() << "': "
+                       << "ignoring instruction with multi-operand tied op=
erand '"
+                       << OI.Name << "'\n";
+              });
+            continue;
+          }
         }
       }
+
+      OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
+
+      II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPref=
ix);
+
+      // Ignore instructions which shouldn't be matched and diagnose inval=
id
+      // instruction definitions with an error.
+      if (!II->Validate(CommentDelimiter, true))
+        continue;
+
+      // Ignore "Int_*" and "*_Int" instructions, which are internal alias=
es.
+      //
+      // FIXME: This is a total hack.
+      if (StringRef(II->TheDef->getName()).startswith("Int_") ||
+          StringRef(II->TheDef->getName()).endswith("_Int"))
+        continue;
+
+      Matchables.push_back(II.take());
     }
=20
-    OwningPtr<MatchableInfo> II(new MatchableInfo(CGI));
-
-    II->Initialize(*this, SingletonRegisters);
-
-    // Ignore instructions which shouldn't be matched and diagnose invalid
-    // instruction definitions with an error.
-    if (!II->Validate(CommentDelimiter, true))
-      continue;
-
-    // Ignore "Int_*" and "*_Int" instructions, which are internal aliases.
-    //
-    // FIXME: This is a total hack.
-    if (StringRef(II->TheDef->getName()).startswith("Int_") ||
-        StringRef(II->TheDef->getName()).endswith("_Int"))
-      continue;
-
-     Matchables.push_back(II.take());
-  }
-
-  // Parse all of the InstAlias definitions and stick them in the list of
-  // matchables.
-  std::vector<Record*> AllInstAliases =3D
-    Records.getAllDerivedDefinitions("InstAlias");
-  for (unsigned i =3D 0, e =3D AllInstAliases.size(); i !=3D e; ++i) {
-    CodeGenInstAlias *Alias =3D new CodeGenInstAlias(AllInstAliases[i], Ta=
rget);
-
-    // If the tblgen -match-prefix option is specified (for tblgen hackers=
),
-    // filter the set of instruction aliases we consider, based on the tar=
get
-    // instruction.
-    if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
-          MatchPrefix))
-      continue;
-
-    OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
-
-    II->Initialize(*this, SingletonRegisters);
-
-    // Validate the alias definitions.
-    II->Validate(CommentDelimiter, false);
-
-    Matchables.push_back(II.take());
+    // Parse all of the InstAlias definitions and stick them in the list of
+    // matchables.
+    std::vector<Record*> AllInstAliases =3D
+      Records.getAllDerivedDefinitions("InstAlias");
+    for (unsigned i =3D 0, e =3D AllInstAliases.size(); i !=3D e; ++i) {
+      CodeGenInstAlias *Alias =3D new CodeGenInstAlias(AllInstAliases[i], =
Target);
+
+      // If the tblgen -match-prefix option is specified (for tblgen hacke=
rs),
+      // filter the set of instruction aliases we consider, based on the t=
arget
+      // instruction.
+      if (!StringRef(Alias->ResultInst->TheDef->getName()).startswith(
+                                                                      Matc=
hPrefix))
+        continue;
+
+      OwningPtr<MatchableInfo> II(new MatchableInfo(Alias));
+
+      II->Initialize(*this, SingletonRegisters, AsmVariantNo, RegisterPref=
ix);
+
+      // Validate the alias definitions.
+      II->Validate(CommentDelimiter, false);
+
+      Matchables.push_back(II.take());
+    }
   }
=20
   // Build info for the register classes.
@@ -1260,7 +1283,7 @@
       StringRef Token =3D Op.Token;
=20
       // Check for singleton registers.
-      if (Record *RegRecord =3D II->getSingletonRegisterForAsmOperand(i, *=
this)) {
+      if (Record *RegRecord =3D II->AsmOperands[i].SingletonReg) {
         Op.Class =3D RegisterClasses[RegRecord];
         assert(Op.Class && Op.Class->Registers.size() =3D=3D 1 &&
                "Unexpected class for singleton register");
@@ -1297,6 +1320,17 @@
       II->BuildAliasResultOperands();
   }
=20
+  // Process token alias definitions and set up the associated superclass
+  // information.
+  std::vector<Record*> AllTokenAliases =3D
+    Records.getAllDerivedDefinitions("TokenAlias");
+  for (unsigned i =3D 0, e =3D AllTokenAliases.size(); i !=3D e; ++i) {
+    Record *Rec =3D AllTokenAliases[i];
+    ClassInfo *FromClass =3D getTokenClass(Rec->getValueAsString("FromToke=
n"));
+    ClassInfo *ToClass =3D getTokenClass(Rec->getValueAsString("ToToken"));
+    FromClass->SuperClasses.push_back(ToClass);
+  }
+
   // Reorder classes so that classes precede super classes.
   std::sort(Classes.begin(), Classes.end(), less_ptr<ClassInfo>());
 }
@@ -1375,9 +1409,11 @@
         CGA.ResultOperands[i].getName() =3D=3D OperandName) {
       // It's safe to go with the first one we find, because CodeGenInstAl=
ias
       // validates that all operands with the same name have the same reco=
rd.
-      unsigned ResultIdx =3D CGA.ResultInstOperandIndex[i].first;
       Op.SubOpIdx =3D CGA.ResultInstOperandIndex[i].second;
-      Op.Class =3D getOperandClass(CGA.ResultInst->Operands[ResultIdx],
+      // Use the match class from the Alias definition, not the
+      // destination instruction, as we may have an immediate that's
+      // being munged by the match class.
+      Op.Class =3D getOperandClass(CGA.ResultOperands[i].getRecord(),
                                  Op.SubOpIdx);
       Op.SrcOpName =3D OperandName;
       return;
@@ -1453,7 +1489,6 @@
       // Find out what operand from the asmparser that this MCInst operand
       // comes from.
       switch (CGA.ResultOperands[AliasOpNo].Kind) {
-      default: assert(0 && "unexpected InstAlias operand kind");
       case CodeGenInstAlias::ResultOperand::K_Record: {
         StringRef Name =3D CGA.ResultOperands[AliasOpNo].getName();
         int SrcOperand =3D FindAsmOperand(Name, SubIdx);
@@ -1656,7 +1691,7 @@
 /// EmitValidateOperandClass - Emit the function to validate an operand cl=
ass.
 static void EmitValidateOperandClass(AsmMatcherInfo &Info,
                                      raw_ostream &OS) {
-  OS << "static bool ValidateOperandClass(MCParsedAsmOperand *GOp, "
+  OS << "static bool validateOperandClass(MCParsedAsmOperand *GOp, "
      << "MatchClassKind Kind) {\n";
   OS << "  " << Info.Target.getName() << "Operand &Operand =3D *("
      << Info.Target.getName() << "Operand*)GOp;\n";
@@ -1667,7 +1702,8 @@
=20
   // Check for Token operands first.
   OS << "  if (Operand.isToken())\n";
-  OS << "    return MatchTokenString(Operand.getToken()) =3D=3D Kind;\n\n";
+  OS << "    return isSubclass(matchTokenString(Operand.getToken()), Kind)=
;"
+     << "\n\n";
=20
   // Check for register operands, including sub-classes.
   OS << "  if (Operand.isReg()) {\n";
@@ -1681,7 +1717,7 @@
        << it->first->getName() << ": OpKind =3D " << it->second->Name
        << "; break;\n";
   OS << "    }\n";
-  OS << "    return IsSubclass(OpKind, Kind);\n";
+  OS << "    return isSubclass(OpKind, Kind);\n";
   OS << "  }\n\n";
=20
   // Check the user classes. We don't care what order since we're only
@@ -1708,8 +1744,8 @@
 static void EmitIsSubclass(CodeGenTarget &Target,
                            std::vector<ClassInfo*> &Infos,
                            raw_ostream &OS) {
-  OS << "/// IsSubclass - Compute whether \\arg A is a subclass of \\arg B=
.\n";
-  OS << "static bool IsSubclass(MatchClassKind A, MatchClassKind B) {\n";
+  OS << "/// isSubclass - Compute whether \\arg A is a subclass of \\arg B=
.\n";
+  OS << "static bool isSubclass(MatchClassKind A, MatchClassKind B) {\n";
   OS << "  if (A =3D=3D B)\n";
   OS << "    return true;\n\n";
=20
@@ -1720,32 +1756,30 @@
          ie =3D Infos.end(); it !=3D ie; ++it) {
     ClassInfo &A =3D **it;
=20
-    if (A.Kind !=3D ClassInfo::Token) {
-      std::vector<StringRef> SuperClasses;
-      for (std::vector<ClassInfo*>::iterator it =3D Infos.begin(),
-             ie =3D Infos.end(); it !=3D ie; ++it) {
-        ClassInfo &B =3D **it;
-
-        if (&A !=3D &B && A.isSubsetOf(B))
-          SuperClasses.push_back(B.Name);
-      }
-
-      if (SuperClasses.empty())
-        continue;
-
-      OS << "\n  case " << A.Name << ":\n";
-
-      if (SuperClasses.size() =3D=3D 1) {
-        OS << "    return B =3D=3D " << SuperClasses.back() << ";\n";
-        continue;
-      }
-
-      OS << "    switch (B) {\n";
-      OS << "    default: return false;\n";
-      for (unsigned i =3D 0, e =3D SuperClasses.size(); i !=3D e; ++i)
-        OS << "    case " << SuperClasses[i] << ": return true;\n";
-      OS << "    }\n";
+    std::vector<StringRef> SuperClasses;
+    for (std::vector<ClassInfo*>::iterator it =3D Infos.begin(),
+         ie =3D Infos.end(); it !=3D ie; ++it) {
+      ClassInfo &B =3D **it;
+
+      if (&A !=3D &B && A.isSubsetOf(B))
+        SuperClasses.push_back(B.Name);
     }
+
+    if (SuperClasses.empty())
+      continue;
+
+    OS << "\n  case " << A.Name << ":\n";
+
+    if (SuperClasses.size() =3D=3D 1) {
+      OS << "    return B =3D=3D " << SuperClasses.back() << ";\n";
+      continue;
+    }
+
+    OS << "    switch (B) {\n";
+    OS << "    default: return false;\n";
+    for (unsigned i =3D 0, e =3D SuperClasses.size(); i !=3D e; ++i)
+      OS << "    case " << SuperClasses[i] << ": return true;\n";
+    OS << "    }\n";
   }
   OS << "  }\n";
   OS << "}\n\n";
@@ -1767,7 +1801,7 @@
                                                   "return " + CI.Name + ";=
"));
   }
=20
-  OS << "static MatchClassKind MatchTokenString(StringRef Name) {\n";
+  OS << "static MatchClassKind matchTokenString(StringRef Name) {\n";
=20
   StringMatcher("Name", Matches, OS).Emit();
=20
@@ -1905,7 +1939,7 @@
     Info.getRecords().getAllDerivedDefinitions("MnemonicAlias");
   if (Aliases.empty()) return false;
=20
-  OS << "static void ApplyMnemonicAliases(StringRef &Mnemonic, "
+  OS << "static void applyMnemonicAliases(StringRef &Mnemonic, "
         "unsigned Features) {\n";
=20
   // Keep track of all the aliases from a mnemonic.  Use an std::map so th=
at the
@@ -1975,45 +2009,62 @@
   return true;
 }
=20
+static const char *getMinimalTypeForRange(uint64_t Range) {
+  assert(Range < 0xFFFFFFFFULL && "Enum too large");
+  if (Range > 0xFFFF)
+    return "uint32_t";
+  if (Range > 0xFF)
+    return "uint16_t";
+  return "uint8_t";
+}
+
 static void EmitCustomOperandParsing(raw_ostream &OS, CodeGenTarget &Targe=
t,
                               const AsmMatcherInfo &Info, StringRef ClassN=
ame) {
   // Emit the static custom operand parsing table;
   OS << "namespace {\n";
   OS << "  struct OperandMatchEntry {\n";
-  OS << "    const char *Mnemonic;\n";
-  OS << "    unsigned OperandMask;\n";
-  OS << "    MatchClassKind Class;\n";
-  OS << "    unsigned RequiredFeatures;\n";
+  OS << "    static const char *const MnemonicTable;\n";
+  OS << "    uint32_t OperandMask;\n";
+  OS << "    uint32_t Mnemonic;\n";
+  OS << "    " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.si=
ze())
+               << " RequiredFeatures;\n";
+  OS << "    " << getMinimalTypeForRange(Info.Classes.size())
+               << " Class;\n\n";
+  OS << "    StringRef getMnemonic() const {\n";
+  OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
+  OS << "                       MnemonicTable[Mnemonic]);\n";
+  OS << "    }\n";
   OS << "  };\n\n";
=20
   OS << "  // Predicate for searching for an opcode.\n";
   OS << "  struct LessOpcodeOperand {\n";
   OS << "    bool operator()(const OperandMatchEntry &LHS, StringRef RHS) =
{\n";
-  OS << "      return StringRef(LHS.Mnemonic) < RHS;\n";
+  OS << "      return LHS.getMnemonic()  < RHS;\n";
   OS << "    }\n";
   OS << "    bool operator()(StringRef LHS, const OperandMatchEntry &RHS) =
{\n";
-  OS << "      return LHS < StringRef(RHS.Mnemonic);\n";
+  OS << "      return LHS < RHS.getMnemonic();\n";
   OS << "    }\n";
   OS << "    bool operator()(const OperandMatchEntry &LHS,";
   OS << " const OperandMatchEntry &RHS) {\n";
-  OS << "      return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n=
";
+  OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
   OS << "    }\n";
   OS << "  };\n";
=20
   OS << "} // end anonymous namespace.\n\n";
=20
+  StringToOffsetTable StringTable;
+
   OS << "static const OperandMatchEntry OperandMatchTable["
      << Info.OperandMatchInfo.size() << "] =3D {\n";
=20
-  OS << "  /* Mnemonic, Operand List Mask, Operand Class, Features */\n";
+  OS << "  /* Operand List Mask, Mnemonic, Operand Class, Features */\n";
   for (std::vector<OperandMatchEntry>::const_iterator it =3D
        Info.OperandMatchInfo.begin(), ie =3D Info.OperandMatchInfo.end();
        it !=3D ie; ++it) {
     const OperandMatchEntry &OMI =3D *it;
     const MatchableInfo &II =3D *OMI.MI;
=20
-    OS << "  { \"" << II.Mnemonic << "\""
-       << ", " << OMI.OperandMask;
+    OS << "  { " << OMI.OperandMask;
=20
     OS << " /* ";
     bool printComma =3D false;
@@ -2026,8 +2077,10 @@
       }
     OS << " */";
=20
-    OS << ", " << OMI.CI->Name
-       << ", ";
+    // Store a pascal-style length byte in the mnemonic.
+    std::string LenMnemonic =3D char(II.Mnemonic.size()) + II.Mnemonic.str=
();
+    OS << ", " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
+       << " /* " << II.Mnemonic << " */, ";
=20
     // Write the required features mask.
     if (!II.RequiredFeatures.empty()) {
@@ -2037,15 +2090,22 @@
       }
     } else
       OS << "0";
+
+    OS << ", " << OMI.CI->Name;
+
     OS << " },\n";
   }
   OS << "};\n\n";
=20
+  OS << "const char *const OperandMatchEntry::MnemonicTable =3D\n";
+  StringTable.EmitString(OS);
+  OS << ";\n\n";
+
   // Emit the operand class switch to call the correct custom parser for
   // the found operand class.
   OS << Target.getName() << ClassName << "::OperandMatchResultTy "
      << Target.getName() << ClassName << "::\n"
-     << "TryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
+     << "tryCustomParseOperand(SmallVectorImpl<MCParsedAsmOperand*>"
      << " &Operands,\n                      unsigned MCK) {\n\n"
      << "  switch(MCK) {\n";
=20
@@ -2094,7 +2154,7 @@
      << "       *ie =3D MnemonicRange.second; it !=3D ie; ++it) {\n";
=20
   OS << "    // equal_range guarantees that instruction mnemonic matches.\=
n";
-  OS << "    assert(Mnemonic =3D=3D it->Mnemonic);\n\n";
+  OS << "    assert(Mnemonic =3D=3D it->getMnemonic());\n\n";
=20
   // Emit check that the required features are available.
   OS << "    // check if the available features match\n";
@@ -2111,7 +2171,7 @@
   // Emit call to the custom parser method
   OS << "    // call custom parse method to handle the operand\n";
   OS << "    OperandMatchResultTy Result =3D ";
-  OS << "TryCustomParseOperand(Operands, it->Class);\n";
+  OS << "tryCustomParseOperand(Operands, it->Class);\n";
   OS << "    if (Result !=3D MatchOperand_NoMatch)\n";
   OS << "      return Result;\n";
   OS << "  }\n\n";
@@ -2186,7 +2246,7 @@
   OS << "  bool MnemonicIsValid(StringRef Mnemonic);\n";
   OS << "  unsigned MatchInstructionImpl(\n";
   OS << "    const SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
-  OS << "    MCInst &Inst, unsigned &ErrorInfo);\n";
+  OS << "    MCInst &Inst, unsigned &ErrorInfo, unsigned VariantID =3D 0);=
\n";
=20
   if (Info.OperandMatchInfo.size()) {
     OS << "\n  enum OperandMatchResultTy {\n";
@@ -2198,7 +2258,7 @@
     OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
     OS << "    StringRef Mnemonic);\n";
=20
-    OS << "  OperandMatchResultTy TryCustomParseOperand(\n";
+    OS << "  OperandMatchResultTy tryCustomParseOperand(\n";
     OS << "    SmallVectorImpl<MCParsedAsmOperand*> &Operands,\n";
     OS << "    unsigned MCK);\n\n";
   }
@@ -2260,28 +2320,39 @@
   // following the mnemonic.
   OS << "namespace {\n";
   OS << "  struct MatchEntry {\n";
-  OS << "    unsigned Opcode;\n";
-  OS << "    const char *Mnemonic;\n";
-  OS << "    ConversionKind ConvertFn;\n";
-  OS << "    MatchClassKind Classes[" << MaxNumOperands << "];\n";
-  OS << "    unsigned RequiredFeatures;\n";
+  OS << "    static const char *const MnemonicTable;\n";
+  OS << "    uint32_t Mnemonic;\n";
+  OS << "    uint16_t Opcode;\n";
+  OS << "    " << getMinimalTypeForRange(Info.Matchables.size())
+               << " ConvertFn;\n";
+  OS << "    " << getMinimalTypeForRange(1ULL << Info.SubtargetFeatures.si=
ze())
+               << " RequiredFeatures;\n";
+  OS << "    " << getMinimalTypeForRange(Info.Classes.size())
+               << " Classes[" << MaxNumOperands << "];\n";
+  OS << "    uint8_t AsmVariantID;\n\n";
+  OS << "    StringRef getMnemonic() const {\n";
+  OS << "      return StringRef(MnemonicTable + Mnemonic + 1,\n";
+  OS << "                       MnemonicTable[Mnemonic]);\n";
+  OS << "    }\n";
   OS << "  };\n\n";
=20
   OS << "  // Predicate for searching for an opcode.\n";
   OS << "  struct LessOpcode {\n";
   OS << "    bool operator()(const MatchEntry &LHS, StringRef RHS) {\n";
-  OS << "      return StringRef(LHS.Mnemonic) < RHS;\n";
+  OS << "      return LHS.getMnemonic() < RHS;\n";
   OS << "    }\n";
   OS << "    bool operator()(StringRef LHS, const MatchEntry &RHS) {\n";
-  OS << "      return LHS < StringRef(RHS.Mnemonic);\n";
+  OS << "      return LHS < RHS.getMnemonic();\n";
   OS << "    }\n";
   OS << "    bool operator()(const MatchEntry &LHS, const MatchEntry &RHS)=
 {\n";
-  OS << "      return StringRef(LHS.Mnemonic) < StringRef(RHS.Mnemonic);\n=
";
+  OS << "      return LHS.getMnemonic() < RHS.getMnemonic();\n";
   OS << "    }\n";
   OS << "  };\n";
=20
   OS << "} // end anonymous namespace.\n\n";
=20
+  StringToOffsetTable StringTable;
+
   OS << "static const MatchEntry MatchTable["
      << Info.Matchables.size() << "] =3D {\n";
=20
@@ -2290,16 +2361,13 @@
        it !=3D ie; ++it) {
     MatchableInfo &II =3D **it;
=20
-    OS << "  { " << Target.getName() << "::"
-       << II.getResultInst()->TheDef->getName() << ", \"" << II.Mnemonic <=
< "\""
-       << ", " << II.ConversionFnKind << ", { ";
-    for (unsigned i =3D 0, e =3D II.AsmOperands.size(); i !=3D e; ++i) {
-      MatchableInfo::AsmOperand &Op =3D II.AsmOperands[i];
-
-      if (i) OS << ", ";
-      OS << Op.Class->Name;
-    }
-    OS << " }, ";
+    // Store a pascal-style length byte in the mnemonic.
+    std::string LenMnemonic =3D char(II.Mnemonic.size()) + II.Mnemonic.str=
();
+    OS << "  { " << StringTable.GetOrAddStringOffset(LenMnemonic, false)
+       << " /* " << II.Mnemonic << " */, "
+       << Target.getName() << "::"
+       << II.getResultInst()->TheDef->getName() << ", "
+       << II.ConversionFnKind << ", ";
=20
     // Write the required features mask.
     if (!II.RequiredFeatures.empty()) {
@@ -2310,11 +2378,23 @@
     } else
       OS << "0";
=20
+    OS << ", { ";
+    for (unsigned i =3D 0, e =3D II.AsmOperands.size(); i !=3D e; ++i) {
+      MatchableInfo::AsmOperand &Op =3D II.AsmOperands[i];
+
+      if (i) OS << ", ";
+      OS << Op.Class->Name;
+    }
+    OS << " }, " << II.AsmVariantID;
     OS << "},\n";
   }
=20
   OS << "};\n\n";
=20
+  OS << "const char *const MatchEntry::MnemonicTable =3D\n";
+  StringTable.EmitString(OS);
+  OS << ";\n\n";
+
   // A method to determine if a mnemonic is in the list.
   OS << "bool " << Target.getName() << ClassName << "::\n"
      << "MnemonicIsValid(StringRef Mnemonic) {\n";
@@ -2330,7 +2410,8 @@
      << Target.getName() << ClassName << "::\n"
      << "MatchInstructionImpl(const SmallVectorImpl<MCParsedAsmOperand*>"
      << " &Operands,\n";
-  OS << "                     MCInst &Inst, unsigned &ErrorInfo) {\n";
+  OS << "                     MCInst &Inst, unsigned &ErrorInfo,\n";
+  OS << "                     unsigned VariantID) {\n";
=20
   // Emit code to get the available features.
   OS << "  // Get the current feature set.\n";
@@ -2342,7 +2423,9 @@
=20
   if (HasMnemonicAliases) {
     OS << "  // Process all MnemonicAliases to remap the mnemonic.\n";
-    OS << "  ApplyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
+    OS << "  // FIXME : Add an entry in AsmParserVariant to check this.\n";
+    OS << "  if (!VariantID)\n";
+    OS << "    applyMnemonicAliases(Mnemonic, AvailableFeatures);\n\n";
   }
=20
   // Emit code to compute the class list for this operand vector.
@@ -2375,16 +2458,18 @@
   OS << "       it !=3D ie; ++it) {\n";
=20
   OS << "    // equal_range guarantees that instruction mnemonic matches.\=
n";
-  OS << "    assert(Mnemonic =3D=3D it->Mnemonic);\n";
+  OS << "    assert(Mnemonic =3D=3D it->getMnemonic());\n";
=20
   // Emit check that the subclasses match.
+  OS << "    if (VariantID !=3D it->AsmVariantID) continue;\n";
   OS << "    bool OperandsValid =3D true;\n";
   OS << "    for (unsigned i =3D 0; i !=3D " << MaxNumOperands << "; ++i) =
{\n";
   OS << "      if (i + 1 >=3D Operands.size()) {\n";
   OS << "        OperandsValid =3D (it->Classes[i] =3D=3D " <<"InvalidMatc=
hClass);\n";
   OS << "        break;\n";
   OS << "      }\n";
-  OS << "      if (ValidateOperandClass(Operands[i+1], it->Classes[i]))\n";
+  OS << "      if (validateOperandClass(Operands[i+1], "
+                                       "(MatchClassKind)it->Classes[i]))\n=
";
   OS << "        continue;\n";
   OS << "      // If this operand is broken for all of the instances of th=
is\n";
   OS << "      // mnemonic, keep track of it so we can report loc info.\n";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/AsmWr=
iterEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/AsmWriterEmitter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/AsmWriterEmitter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "AsmWriterInst.h"
 #include "CodeGenTarget.h"
 #include "StringToOffsetTable.h"
+#include "SequenceToOffsetTable.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MathExtras.h"
@@ -277,12 +278,27 @@
     CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i])=
);
=20
   // Build an aggregate string, and build a table of offsets into it.
-  StringToOffsetTable StringTable;
+  SequenceToOffsetTable<std::string> StringTable;
=20
   /// OpcodeInfo - This encodes the index of the string to use for the fir=
st
   /// chunk of the output as well as indices used for operand printing.
   std::vector<unsigned> OpcodeInfo;
=20
+  // Add all strings to the string table upfront so it can generate an opt=
imized
+  // representation.
+  for (unsigned i =3D 0, e =3D NumberedInstructions.size(); i !=3D e; ++i)=
 {
+    AsmWriterInst *AWI =3D CGIAWIMap[NumberedInstructions[i]];
+    if (AWI !=3D 0 &&
+        AWI->Operands[0].OperandType =3D=3D AsmWriterOperand::isLiteralTex=
tOperand &&
+        !AWI->Operands[0].Str.empty()) {
+      std::string Str =3D AWI->Operands[0].Str;
+      UnescapeString(Str);
+      StringTable.add(Str);
+    }
+  }
+
+  StringTable.layout();
+
   unsigned MaxStringIdx =3D 0;
   for (unsigned i =3D 0, e =3D NumberedInstructions.size(); i !=3D e; ++i)=
 {
     AsmWriterInst *AWI =3D CGIAWIMap[NumberedInstructions[i]];
@@ -294,11 +310,11 @@
                         AsmWriterOperand::isLiteralTextOperand ||
                AWI->Operands[0].Str.empty()) {
       // Something handled by the asmwriter printer, but with no leading s=
tring.
-      Idx =3D StringTable.GetOrAddStringOffset("");
+      Idx =3D StringTable.get("");
     } else {
       std::string Str =3D AWI->Operands[0].Str;
       UnescapeString(Str);
-      Idx =3D StringTable.GetOrAddStringOffset(Str);
+      Idx =3D StringTable.get(Str);
       MaxStringIdx =3D std::max(MaxStringIdx, Idx);
=20
       // Nuke the string from the operand list.  It is now handled!
@@ -373,9 +389,9 @@
   O << "  };\n\n";
=20
   // Emit the string itself.
-  O << "  const char *AsmStrs =3D \n";
-  StringTable.EmitString(O);
-  O << ";\n\n";
+  O << "  const char AsmStrs[] =3D {\n";
+  StringTable.emit(O, printChar);
+  O << "  };\n\n";
=20
   O << "  O << \"\\t\";\n\n";
=20
@@ -461,13 +477,13 @@
=20
 static void
 emitRegisterNameString(raw_ostream &O, StringRef AltName,
-  const std::vector<CodeGenRegister*> &Registers) {
-  StringToOffsetTable StringTable;
-  O << "  static const unsigned RegAsmOffset" << AltName << "[] =3D {\n   =
 ";
+                       const std::vector<CodeGenRegister*> &Registers) {
+  SequenceToOffsetTable<std::string> StringTable;
+  SmallVector<std::string, 4> AsmNames(Registers.size());
   for (unsigned i =3D 0, e =3D Registers.size(); i !=3D e; ++i) {
     const CodeGenRegister &Reg =3D *Registers[i];
+    std::string &AsmName =3D AsmNames[i];
=20
-    std::string AsmName;
     // "NoRegAltName" is special. We don't need to do a lookup for that,
     // as it's just a reference to the default register name.
     if (AltName =3D=3D "" || AltName =3D=3D "NoRegAltName") {
@@ -495,21 +511,22 @@
         AsmName =3D AltNames[Idx];
       }
     }
+    StringTable.add(AsmName);
+  }
=20
-    O << StringTable.GetOrAddStringOffset(AsmName);
-    if (((i + 1) % 14) =3D=3D 0)
-      O << ",\n    ";
-    else
-      O << ", ";
+  StringTable.layout();
+  O << "  static const char AsmStrs" << AltName << "[] =3D {\n";
+  StringTable.emit(O, printChar);
+  O << "  };\n\n";
=20
+  O << "  static const unsigned RegAsmOffset" << AltName << "[] =3D {";
+  for (unsigned i =3D 0, e =3D Registers.size(); i !=3D e; ++i) {
+    if ((i % 14) =3D=3D 0)
+      O << "\n    ";
+    O << StringTable.get(AsmNames[i]) << ", ";
   }
-  O << "0\n"
-    << "  };\n"
+  O << "\n  };\n"
     << "\n";
-
-  O << "  const char *AsmStrs" << AltName << " =3D\n";
-  StringTable.EmitString(O);
-  O << ";\n";
 }
=20
 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
@@ -544,7 +561,7 @@
     O << "  const unsigned *RegAsmOffset;\n"
       << "  const char *AsmStrs;\n"
       << "  switch(AltIdx) {\n"
-      << "  default: assert(0 && \"Invalid register alt name index!\");\n";
+      << "  default: llvm_unreachable(\"Invalid register alt name index!\"=
);\n";
     for (unsigned i =3D 0, e =3D AltNameIndices.size(); i < e; ++i) {
       StringRef Namespace =3D AltNameIndices[1]->getValueAsString("Namespa=
ce");
       StringRef AltName(AltNameIndices[i]->getName());
@@ -563,48 +580,6 @@
     << "}\n";
 }
=20
-void AsmWriterEmitter::EmitGetInstructionName(raw_ostream &O) {
-  CodeGenTarget Target(Records);
-  Record *AsmWriter =3D Target.getAsmWriter();
-  std::string ClassName =3D AsmWriter->getValueAsString("AsmWriterClassNam=
e");
-
-  const std::vector<const CodeGenInstruction*> &NumberedInstructions =3D
-    Target.getInstructionsByEnumValue();
-
-  StringToOffsetTable StringTable;
-  O <<
-"\n\n#ifdef GET_INSTRUCTION_NAME\n"
-"#undef GET_INSTRUCTION_NAME\n\n"
-"/// getInstructionName: This method is automatically generated by tblgen\=
n"
-"/// from the instruction set description.  This returns the enum name of =
the\n"
-"/// specified instruction.\n"
-  "const char *" << Target.getName() << ClassName
-  << "::getInstructionName(unsigned Opcode) {\n"
-  << "  assert(Opcode < " << NumberedInstructions.size()
-  << " && \"Invalid instruction number!\");\n"
-  << "\n"
-  << "  static const unsigned InstAsmOffset[] =3D {";
-  for (unsigned i =3D 0, e =3D NumberedInstructions.size(); i !=3D e; ++i)=
 {
-    const CodeGenInstruction &Inst =3D *NumberedInstructions[i];
-
-    std::string AsmName =3D Inst.TheDef->getName();
-    if ((i % 14) =3D=3D 0)
-      O << "\n    ";
-
-    O << StringTable.GetOrAddStringOffset(AsmName) << ", ";
-  }
-  O << "0\n"
-  << "  };\n"
-  << "\n";
-
-  O << "  const char *Strs =3D\n";
-  StringTable.EmitString(O);
-  O << ";\n";
-
-  O << "  return Strs+InstAsmOffset[Opcode];\n"
-  << "}\n\n#endif\n";
-}
-
 namespace {
 // IAPrinter - Holds information about an InstAlias. Two InstAliases match=
 if
 // they both have the same conditionals. In which case, we cannot print ou=
t the
@@ -694,70 +669,7 @@
   O << "         I =3D OpMap.begin(), E =3D OpMap.end(); I !=3D E; ++I)\n";
   O << "    if (I->first =3D=3D Name)\n";
   O << "      return I->second;\n";
-  O << "  assert(false && \"Operand not in map!\");\n";
-  O << "  return 0;\n";
-  O << "}\n\n";
-}
-
-void AsmWriterEmitter::EmitRegIsInRegClass(raw_ostream &O) {
-  CodeGenTarget Target(Records);
-
-  // Enumerate the register classes.
-  ArrayRef<CodeGenRegisterClass*> RegisterClasses =3D
-    Target.getRegBank().getRegClasses();
-
-  O << "namespace { // Register classes\n";
-  O << "  enum RegClass {\n";
-
-  // Emit the register enum value for each RegisterClass.
-  for (unsigned I =3D 0, E =3D RegisterClasses.size(); I !=3D E; ++I) {
-    if (I !=3D 0) O << ",\n";
-    O << "    RC_" << RegisterClasses[I]->getName();
-  }
-
-  O << "\n  };\n";
-  O << "} // end anonymous namespace\n\n";
-
-  // Emit a function that returns 'true' if a regsiter is part of a partic=
ular
-  // register class. I.e., RAX is part of GR64 on X86.
-  O << "static bool regIsInRegisterClass"
-    << "(unsigned RegClass, unsigned Reg) {\n";
-
-  // Emit the switch that checks if a register belongs to a particular reg=
ister
-  // class.
-  O << "  switch (RegClass) {\n";
-  O << "  default: break;\n";
-
-  for (unsigned I =3D 0, E =3D RegisterClasses.size(); I !=3D E; ++I) {
-    const CodeGenRegisterClass &RC =3D *RegisterClasses[I];
-
-    // Give the register class a legal C name if it's anonymous.
-    std::string Name =3D RC.getName();
-    O << "  case RC_" << Name << ":\n";
- =20
-    // Emit the register list now.
-    unsigned IE =3D RC.getOrder().size();
-    if (IE =3D=3D 1) {
-      O << "    if (Reg =3D=3D " << getQualifiedName(RC.getOrder()[0]) << =
")\n";
-      O << "      return true;\n";
-    } else {
-      O << "    switch (Reg) {\n";
-      O << "    default: break;\n";
-
-      for (unsigned II =3D 0; II !=3D IE; ++II) {
-        Record *Reg =3D RC.getOrder()[II];
-        O << "    case " << getQualifiedName(Reg) << ":\n";
-      }
-
-      O << "      return true;\n";
-      O << "    }\n";
-    }
-
-    O << "    break;\n";
-  }
-
-  O << "  }\n\n";
-  O << "  return false;\n";
+  O << "  llvm_unreachable(\"Operand not in map!\");\n";
   O << "}\n\n";
 }
=20
@@ -804,8 +716,6 @@
   O << "\n#ifdef PRINT_ALIAS_INSTR\n";
   O << "#undef PRINT_ALIAS_INSTR\n\n";
=20
-  EmitRegIsInRegClass(O);
-
   // Emit the method that prints the alias instruction.
   std::string ClassName =3D AsmWriter->getValueAsString("AsmWriterClassNam=
e");
=20
@@ -858,7 +768,6 @@
         const CodeGenInstAlias::ResultOperand &RO =3D CGA->ResultOperands[=
i];
=20
         switch (RO.Kind) {
-        default: assert(0 && "unexpected InstAlias operand kind");
         case CodeGenInstAlias::ResultOperand::K_Record: {
           const Record *Rec =3D RO.getRecord();
           StringRef ROName =3D RO.getName();
@@ -872,9 +781,9 @@
=20
             if (!IAP->isOpMapped(ROName)) {
               IAP->addOperand(ROName, i);
-              Cond =3D std::string("regIsInRegisterClass(RC_") +
-                CGA->ResultOperands[i].getRecord()->getName() +
-                ", MI->getOperand(" + llvm::utostr(i) + ").getReg())";
+              Cond =3D std::string("MRI.getRegClass(") + Target.getName() =
+ "::" +
+                CGA->ResultOperands[i].getRecord()->getName() + "RegClassI=
D)"
+                ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg(=
))";
               IAP->addCond(Cond);
             } else {
               Cond =3D std::string("MI->getOperand(") +
@@ -900,6 +809,13 @@
           IAP->addCond(Cond);
           break;
         case CodeGenInstAlias::ResultOperand::K_Reg:
+          // If this is zero_reg, something's playing tricks we're not
+          // equipped to handle.
+          if (!CGA->ResultOperands[i].getRegister()) {
+            CantHandle =3D true;
+            break;
+          }
+
           Cond =3D std::string("MI->getOperand(") +
             llvm::utostr(i) + ").getReg() =3D=3D " + Target.getName() +
             "::" + CGA->ResultOperands[i].getRegister()->getName();
@@ -1015,7 +931,6 @@
=20
   EmitPrintInstruction(O);
   EmitGetRegisterName(O);
-  EmitGetInstructionName(O);
   EmitPrintAliasInstruction(O);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/AsmWr=
iterEmitter.h
--- a/head/contrib/llvm/utils/TableGen/AsmWriterEmitter.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/AsmWriterEmitter.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -37,8 +37,6 @@
 private:
     void EmitPrintInstruction(raw_ostream &o);
     void EmitGetRegisterName(raw_ostream &o);
-    void EmitGetInstructionName(raw_ostream &o);
-    void EmitRegIsInRegClass(raw_ostream &O);
     void EmitPrintAliasInstruction(raw_ostream &O);
    =20
     AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Calli=
ngConvEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/CallingConvEmitter.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CallingConvEmitter.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -96,7 +96,7 @@
         O << IndentStr << "if (unsigned Reg =3D State.AllocateReg(";
         O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n";
       } else {
-        O << IndentStr << "static const unsigned RegList" << ++Counter
+        O << IndentStr << "static const uint16_t RegList" << ++Counter
           << "[] =3D {\n";
         O << IndentStr << "  ";
         for (unsigned i =3D 0, e =3D RegList->getSize(); i !=3D e; ++i) {
@@ -127,7 +127,7 @@
         unsigned RegListNumber =3D ++Counter;
         unsigned ShadowRegListNumber =3D ++Counter;
=20
-        O << IndentStr << "static const unsigned RegList" << RegListNumber
+        O << IndentStr << "static const uint16_t RegList" << RegListNumber
           << "[] =3D {\n";
         O << IndentStr << "  ";
         for (unsigned i =3D 0, e =3D RegList->getSize(); i !=3D e; ++i) {
@@ -136,7 +136,7 @@
         }
         O << "\n" << IndentStr << "};\n";
=20
-        O << IndentStr << "static const unsigned RegList"
+        O << IndentStr << "static const uint16_t RegList"
           << ShadowRegListNumber << "[] =3D {\n";
         O << IndentStr << "  ";
         for (unsigned i =3D 0, e =3D ShadowRegList->getSize(); i !=3D e; +=
+i) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeE=
mitterGen.cpp
--- a/head/contrib/llvm/utils/TableGen/CodeEmitterGen.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeEmitterGen.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -163,19 +163,19 @@
       --bit;
     }
     =20
-    unsigned opMask =3D ~0U >> (32-N);
+    uint64_t opMask =3D ~(uint64_t)0 >> (64-N);
     int opShift =3D beginVarBit - N + 1;
     opMask <<=3D opShift;
     opShift =3D beginInstBit - beginVarBit;
    =20
     if (opShift > 0) {
-      Case +=3D "      Value |=3D (op & " + utostr(opMask) + "U) << " +
+      Case +=3D "      Value |=3D (op & UINT64_C(" + utostr(opMask) + ")) =
<< " +
               itostr(opShift) + ";\n";
     } else if (opShift < 0) {
-      Case +=3D "      Value |=3D (op & " + utostr(opMask) + "U) >> " +=20
+      Case +=3D "      Value |=3D (op & UINT64_C(" + utostr(opMask) + ")) =
>> " +=20
               itostr(-opShift) + ";\n";
     } else {
-      Case +=3D "      Value |=3D op & " + utostr(opMask) + "U;\n";
+      Case +=3D "      Value |=3D op & UINT64_C(" + utostr(opMask) + ");\n=
";
     }
   }
 }
@@ -220,7 +220,7 @@
     Target.getInstructionsByEnumValue();
=20
   // Emit function declaration
-  o << "unsigned " << Target.getName();
+  o << "uint64_t " << Target.getName();
   if (MCEmitter)
     o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
       << "    SmallVectorImpl<MCFixup> &Fixups) const {\n";
@@ -228,7 +228,7 @@
     o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const=
 {\n";
=20
   // Emit instruction base values
-  o << "  static const unsigned InstBits[] =3D {\n";
+  o << "  static const uint64_t InstBits[] =3D {\n";
   for (std::vector<const CodeGenInstruction*>::const_iterator
           IN =3D NumberedInstructions.begin(),
           EN =3D NumberedInstructions.end();
@@ -238,21 +238,21 @@
=20
     if (R->getValueAsString("Namespace") =3D=3D "TargetOpcode" ||
         R->getValueAsBit("isPseudo")) {
-      o << "    0U,\n";
+      o << "    UINT64_C(0),\n";
       continue;
     }
=20
     BitsInit *BI =3D R->getValueAsBitsInit("Inst");
=20
     // Start by filling in fixed values.
-    unsigned Value =3D 0;
+    uint64_t Value =3D 0;
     for (unsigned i =3D 0, e =3D BI->getNumBits(); i !=3D e; ++i) {
       if (BitInit *B =3D dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
-        Value |=3D B->getValue() << (e-i-1);
+        Value |=3D (uint64_t)B->getValue() << (e-i-1);
     }
-    o << "    " << Value << "U," << '\t' << "// " << R->getName() << "\n";
+    o << "    UINT64_C(" << Value << ")," << '\t' << "// " << R->getName()=
 << "\n";
   }
-  o << "    0U\n  };\n";
+  o << "    UINT64_C(0)\n  };\n";
=20
   // Map to accumulate all the cases.
   std::map<std::string, std::vector<std::string> > CaseMap;
@@ -273,8 +273,8 @@
=20
   // Emit initial function code
   o << "  const unsigned opcode =3D MI.getOpcode();\n"
-    << "  unsigned Value =3D InstBits[opcode];\n"
-    << "  unsigned op =3D 0;\n"
+    << "  uint64_t Value =3D InstBits[opcode];\n"
+    << "  uint64_t op =3D 0;\n"
     << "  (void)op;  // suppress warning\n"
     << "  switch (opcode) {\n";
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeG=
enDAGPatterns.cpp
--- a/head/contrib/llvm/utils/TableGen/CodeGenDAGPatterns.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeGenDAGPatterns.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -18,8 +18,10 @@
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
+#include <algorithm>
+#include <cstdio>
 #include <set>
-#include <algorithm>
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -629,11 +631,11 @@
 }
=20
 std::string TreePredicateFn::getPredCode() const {
-  return PatFragRec->getRecord()->getValueAsCode("PredicateCode");
+  return PatFragRec->getRecord()->getValueAsString("PredicateCode");
 }
=20
 std::string TreePredicateFn::getImmCode() const {
-  return PatFragRec->getRecord()->getValueAsCode("ImmediateCode");
+  return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
 }
=20
=20
@@ -748,7 +750,7 @@
 #ifndef NDEBUG
         Def->dump();
 #endif
-        assert(0 && "Unknown predicate type!");
+        llvm_unreachable("Unknown predicate type!");
       }
       if (!PredicateCheck.empty())
         PredicateCheck +=3D " && ";
@@ -839,7 +841,6 @@
   TreePatternNode *NodeToApply =3D getOperandNum(OperandNo, N, NodeInfo, R=
esNo);
=20
   switch (ConstraintType) {
-  default: assert(0 && "Unknown constraint type!");
   case SDTCisVT:
     // Operand must be a particular type.
     return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
@@ -913,7 +914,7 @@
       EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
   }
   }
-  return false;
+  llvm_unreachable("Invalid ConstraintType!");
 }
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -1609,10 +1610,9 @@
         MadeChange |=3D Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
       } else if (OperandNode->getName() =3D=3D "unknown") {
         // Nothing to do.
-      } else {
-        assert(0 && "Unknown operand type!");
-        abort();
-      }
+      } else
+        llvm_unreachable("Unknown operand type!");
+
       MadeChange |=3D Child->ApplyTypeConstraints(TP, NotRegisters);
     }
=20
@@ -2071,7 +2071,7 @@
   while (!Xforms.empty()) {
     Record *XFormNode =3D Xforms.back();
     Record *SDNode =3D XFormNode->getValueAsDef("Opcode");
-    std::string Code =3D XFormNode->getValueAsCode("XFormFunction");
+    std::string Code =3D XFormNode->getValueAsString("XFormFunction");
     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code))=
);
=20
     Xforms.pop_back();
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeG=
enDAGPatterns.h
--- a/head/contrib/llvm/utils/TableGen/CodeGenDAGPatterns.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeGenDAGPatterns.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -19,6 +19,7 @@
 #include "CodeGenIntrinsics.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringMap.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <set>
 #include <algorithm>
 #include <vector>
@@ -723,8 +724,7 @@
       if (Intrinsics[i].TheDef =3D=3D R) return Intrinsics[i];
     for (unsigned i =3D 0, e =3D TgtIntrinsics.size(); i !=3D e; ++i)
       if (TgtIntrinsics[i].TheDef =3D=3D R) return TgtIntrinsics[i];
-    assert(0 && "Unknown intrinsic!");
-    abort();
+    llvm_unreachable("Unknown intrinsic!");
   }
=20
   const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
@@ -732,8 +732,7 @@
       return Intrinsics[IID-1];
     if (IID-Intrinsics.size()-1 < TgtIntrinsics.size())
       return TgtIntrinsics[IID-Intrinsics.size()-1];
-    assert(0 && "Bad intrinsic ID!");
-    abort();
+    llvm_unreachable("Bad intrinsic ID!");
   }
=20
   unsigned getIntrinsicID(Record *R) const {
@@ -741,8 +740,7 @@
       if (Intrinsics[i].TheDef =3D=3D R) return i;
     for (unsigned i =3D 0, e =3D TgtIntrinsics.size(); i !=3D e; ++i)
       if (TgtIntrinsics[i].TheDef =3D=3D R) return i + Intrinsics.size();
-    assert(0 && "Unknown intrinsic!");
-    abort();
+    llvm_unreachable("Unknown intrinsic!");
   }
=20
   const DAGDefaultOperand &getDefaultOperand(Record *R) const {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeG=
enInstruction.cpp
--- a/head/contrib/llvm/utils/TableGen/CodeGenInstruction.cpp	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeGenInstruction.cpp	Tue Apr 17 11=
:51:51 2012 +0300
@@ -245,7 +245,7 @@
   if (!Ops[DestOp.first].Constraints[DestOp.second].isNone())
     throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
   Ops[DestOp.first].Constraints[DestOp.second] =3D
-  CGIOperandList::ConstraintInfo::getTied(FlatOpNo);
+    CGIOperandList::ConstraintInfo::getTied(FlatOpNo);
 }
=20
 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops)=
 {
@@ -423,6 +423,18 @@
     return true;
   }
=20
+  // For register operands, the source register class can be a subclass
+  // of the instruction register class, not just an exact match.
+  if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
+    if (!InstOpRec->isSubClassOf("RegisterClass"))
+      return false;
+    if (!T.getRegisterClass(InstOpRec)
+              .hasSubClass(&T.getRegisterClass(ADI->getDef())))
+      return false;
+    ResOp =3D ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
+    return true;
+  }
+
   // Handle explicit registers.
   if (ADI && ADI->getDef()->isSubClassOf("Register")) {
     if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
@@ -456,14 +468,19 @@
   if (ADI && ADI->getDef()->getName() =3D=3D "zero_reg") {
=20
     // Check if this is an optional def.
-    if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
-      throw TGError(Loc, "reg0 used for result that is not an "
-                    "OptionalDefOperand!");
+    // Tied operands where the source is a sub-operand of a complex operand
+    // need to represent both operands in the alias destination instructio=
n.
+    // Allow zero_reg for the tied portion. This can and should go away on=
ce
+    // the MC representation of things doesn't use tied operands at all.
+    //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
+    //  throw TGError(Loc, "reg0 used for result that is not an "
+    //                "OptionalDefOperand!");
=20
     ResOp =3D ResultOperand(static_cast<Record*>(0));
     return true;
   }
=20
+  // Literal integers.
   if (IntInit *II =3D dynamic_cast<IntInit*>(Arg)) {
     if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
       return false;
@@ -475,6 +492,19 @@
     return true;
   }
=20
+  // If both are Operands with the same MVT, allow the conversion. It's
+  // up to the user to make sure the values are appropriate, just like
+  // for isel Pat's.
+  if (InstOpRec->isSubClassOf("Operand") &&
+      ADI->getDef()->isSubClassOf("Operand")) {
+    // FIXME: What other attributes should we check here? Identical
+    // MIOperandInfo perhaps?
+    if (InstOpRec->getValueInit("Type") !=3D ADI->getDef()->getValueInit("=
Type"))
+      return false;
+    ResOp =3D ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
+    return true;
+  }
+
   return false;
 }
=20
@@ -511,8 +541,11 @@
   unsigned AliasOpNo =3D 0;
   for (unsigned i =3D 0, e =3D ResultInst->Operands.size(); i !=3D e; ++i)=
 {
=20
-    // Tied registers don't have an entry in the result dag.
-    if (ResultInst->Operands[i].getTiedRegister() !=3D -1)
+    // Tied registers don't have an entry in the result dag unless they're=
 part
+    // of a complex operand, in which case we include them anyways, as we
+    // don't have any other way to specify the whole operand.
+    if (ResultInst->Operands[i].MINumOperands =3D=3D 1 &&
+        ResultInst->Operands[i].getTiedRegister() !=3D -1)
       continue;
=20
     if (AliasOpNo >=3D Result->getNumArgs())
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeG=
enRegisters.cpp
--- a/head/contrib/llvm/utils/TableGen/CodeGenRegisters.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeGenRegisters.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -15,6 +15,7 @@
 #include "CodeGenRegisters.h"
 #include "CodeGenTarget.h"
 #include "llvm/TableGen/Error.h"
+#include "llvm/ADT/IntEqClasses.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
@@ -22,6 +23,57 @@
 using namespace llvm;
=20
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+//                             CodeGenSubRegIndex
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
+
+CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
+  : TheDef(R),
+    EnumValue(Enum)
+{}
+
+std::string CodeGenSubRegIndex::getNamespace() const {
+  if (TheDef->getValue("Namespace"))
+    return TheDef->getValueAsString("Namespace");
+  else
+    return "";
+}
+
+const std::string &CodeGenSubRegIndex::getName() const {
+  return TheDef->getName();
+}
+
+std::string CodeGenSubRegIndex::getQualifiedName() const {
+  std::string N =3D getNamespace();
+  if (!N.empty())
+    N +=3D "::";
+  N +=3D getName();
+  return N;
+}
+
+void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
+  std::vector<Record*> Comps =3D TheDef->getValueAsListOfDefs("ComposedOf"=
);
+  if (Comps.empty())
+    return;
+  if (Comps.size() !=3D 2)
+    throw TGError(TheDef->getLoc(), "ComposedOf must have exactly two entr=
ies");
+  CodeGenSubRegIndex *A =3D RegBank.getSubRegIdx(Comps[0]);
+  CodeGenSubRegIndex *B =3D RegBank.getSubRegIdx(Comps[1]);
+  CodeGenSubRegIndex *X =3D A->addComposite(B, this);
+  if (X)
+    throw TGError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
+}
+
+void CodeGenSubRegIndex::cleanComposites() {
+  // Clean out redundant mappings of the form this+X -> X.
+  for (CompMap::iterator i =3D Composed.begin(), e =3D Composed.end(); i !=
=3D e;) {
+    CompMap::iterator j =3D i;
+    ++i;
+    if (j->first =3D=3D j->second)
+      Composed.erase(j);
+  }
+}
+
+//=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                              CodeGenRegister
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
=20
@@ -29,6 +81,7 @@
   : TheDef(R),
     EnumValue(Enum),
     CostPerUse(R->getValueAsInt("CostPerUse")),
+    CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
     SubRegsComplete(false)
 {}
=20
@@ -37,12 +90,81 @@
 }
=20
 namespace {
-  struct Orphan {
-    CodeGenRegister *SubReg;
-    Record *First, *Second;
-    Orphan(CodeGenRegister *r, Record *a, Record *b)
-      : SubReg(r), First(a), Second(b) {}
-  };
+// Iterate over all register units in a set of registers.
+class RegUnitIterator {
+  CodeGenRegister::Set::const_iterator RegI, RegE;
+  CodeGenRegister::RegUnitList::const_iterator UnitI, UnitE;
+
+public:
+  RegUnitIterator(const CodeGenRegister::Set &Regs):
+    RegI(Regs.begin()), RegE(Regs.end()), UnitI(), UnitE() {
+
+    if (RegI !=3D RegE) {
+      UnitI =3D (*RegI)->getRegUnits().begin();
+      UnitE =3D (*RegI)->getRegUnits().end();
+      advance();
+    }
+  }
+
+  bool isValid() const { return UnitI !=3D UnitE; }
+
+  unsigned operator* () const { assert(isValid()); return *UnitI; };
+
+  const CodeGenRegister *getReg() const { assert(isValid()); return *RegI;=
 }
+
+  /// Preincrement.  Move to the next unit.
+  void operator++() {
+    assert(isValid() && "Cannot advance beyond the last operand");
+    ++UnitI;
+    advance();
+  }
+
+protected:
+  void advance() {
+    while (UnitI =3D=3D UnitE) {
+      if (++RegI =3D=3D RegE)
+        break;
+      UnitI =3D (*RegI)->getRegUnits().begin();
+      UnitE =3D (*RegI)->getRegUnits().end();
+    }
+  }
+};
+} // namespace
+
+// Merge two RegUnitLists maintaining the order and removing duplicates.
+// Overwrites MergedRU in the process.
+static void mergeRegUnits(CodeGenRegister::RegUnitList &MergedRU,
+                          const CodeGenRegister::RegUnitList &RRU) {
+  CodeGenRegister::RegUnitList LRU =3D MergedRU;
+  MergedRU.clear();
+  std::set_union(LRU.begin(), LRU.end(), RRU.begin(), RRU.end(),
+                 std::back_inserter(MergedRU));
+}
+
+// Return true of this unit appears in RegUnits.
+static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Un=
it) {
+  return std::count(RegUnits.begin(), RegUnits.end(), Unit);
+}
+
+// Inherit register units from subregisters.
+// Return true if the RegUnits changed.
+bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
+  unsigned OldNumUnits =3D RegUnits.size();
+  for (SubRegMap::const_iterator I =3D SubRegs.begin(), E =3D SubRegs.end(=
);
+       I !=3D E; ++I) {
+    // Strangely a register may have itself as a subreg (self-cycle) e.g. =
XMM.
+    // Only create a unit if no other subregs have units.
+    CodeGenRegister *SR =3D I->second;
+    if (SR =3D=3D this) {
+      // RegUnits are only empty during getSubRegs, prior to computing wei=
ght.
+      if (RegUnits.empty())
+        RegUnits.push_back(RegBank.newRegUnit(0));
+      continue;
+    }
+    // Merge the subregister's units into this register's RegUnits.
+    mergeRegUnits(RegUnits, SR->RegUnits);
+  }
+  return OldNumUnits !=3D RegUnits.size();
 }
=20
 const CodeGenRegister::SubRegMap &
@@ -53,23 +175,26 @@
   SubRegsComplete =3D true;
=20
   std::vector<Record*> SubList =3D TheDef->getValueAsListOfDefs("SubRegs");
-  std::vector<Record*> Indices =3D TheDef->getValueAsListOfDefs("SubRegInd=
ices");
-  if (SubList.size() !=3D Indices.size())
+  std::vector<Record*> IdxList =3D TheDef->getValueAsListOfDefs("SubRegInd=
ices");
+  if (SubList.size() !=3D IdxList.size())
     throw TGError(TheDef->getLoc(), "Register " + getName() +
                   " SubRegIndices doesn't match SubRegs");
=20
   // First insert the direct subregs and make sure they are fully indexed.
+  SmallVector<CodeGenSubRegIndex*, 8> Indices;
   for (unsigned i =3D 0, e =3D SubList.size(); i !=3D e; ++i) {
     CodeGenRegister *SR =3D RegBank.getReg(SubList[i]);
-    if (!SubRegs.insert(std::make_pair(Indices[i], SR)).second)
-      throw TGError(TheDef->getLoc(), "SubRegIndex " + Indices[i]->getName=
() +
+    CodeGenSubRegIndex *Idx =3D RegBank.getSubRegIdx(IdxList[i]);
+    Indices.push_back(Idx);
+    if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
+      throw TGError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
                     " appears twice in Register " + getName());
   }
=20
   // Keep track of inherited subregs and how they can be reached.
-  SmallVector<Orphan, 8> Orphans;
+  SmallPtrSet<CodeGenRegister*, 8> Orphans;
=20
-  // Clone inherited subregs and place duplicate entries on Orphans.
+  // Clone inherited subregs and place duplicate entries in Orphans.
   // Here the order is important - earlier subregs take precedence.
   for (unsigned i =3D 0, e =3D SubList.size(); i !=3D e; ++i) {
     CodeGenRegister *SR =3D RegBank.getReg(SubList[i]);
@@ -83,7 +208,7 @@
     for (SubRegMap::const_iterator SI =3D Map.begin(), SE =3D Map.end(); S=
I !=3D SE;
          ++SI) {
       if (!SubRegs.insert(*SI).second)
-        Orphans.push_back(Orphan(SI->second, Indices[i], SI->first));
+        Orphans.insert(SI->second);
=20
       // Noop sub-register indexes are possible, so avoid duplicates.
       if (SI->second !=3D SR)
@@ -91,6 +216,33 @@
     }
   }
=20
+  // Expand any composed subreg indices.
+  // If dsub_2 has ComposedOf =3D [qsub_1, dsub_0], and this register has a
+  // qsub_1 subreg, add a dsub_2 subreg.  Keep growing Indices and process
+  // expanded subreg indices recursively.
+  for (unsigned i =3D 0; i !=3D Indices.size(); ++i) {
+    CodeGenSubRegIndex *Idx =3D Indices[i];
+    const CodeGenSubRegIndex::CompMap &Comps =3D Idx->getComposites();
+    CodeGenRegister *SR =3D SubRegs[Idx];
+    const SubRegMap &Map =3D SR->getSubRegs(RegBank);
+
+    // Look at the possible compositions of Idx.
+    // They may not all be supported by SR.
+    for (CodeGenSubRegIndex::CompMap::const_iterator I =3D Comps.begin(),
+           E =3D Comps.end(); I !=3D E; ++I) {
+      SubRegMap::const_iterator SRI =3D Map.find(I->first);
+      if (SRI =3D=3D Map.end())
+        continue; // Idx + I->first doesn't exist in SR.
+      // Add I->second as a name for the subreg SRI->second, assuming it is
+      // orphaned, and the name isn't already used for something else.
+      if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
+        continue;
+      // We found a new name for the orphaned sub-register.
+      SubRegs.insert(std::make_pair(I->second, SRI->second));
+      Indices.push_back(I->second);
+    }
+  }
+
   // Process the composites.
   ListInit *Comps =3D TheDef->getValueAsListInit("CompositeIndices");
   for (unsigned i =3D 0, e =3D Comps->size(); i !=3D e; ++i) {
@@ -103,6 +255,7 @@
     if (!BaseIdxInit || !BaseIdxInit->getDef()->isSubClassOf("SubRegIndex"=
))
       throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
                     Pat->getAsString());
+    CodeGenSubRegIndex *BaseIdx =3D RegBank.getSubRegIdx(BaseIdxInit->getD=
ef());
=20
     // Resolve list of subreg indices into R2.
     CodeGenRegister *R2 =3D this;
@@ -112,8 +265,9 @@
       if (!IdxInit || !IdxInit->getDef()->isSubClassOf("SubRegIndex"))
         throw TGError(TheDef->getLoc(), "Invalid SubClassIndex in " +
                       Pat->getAsString());
+      CodeGenSubRegIndex *Idx =3D RegBank.getSubRegIdx(IdxInit->getDef());
       const SubRegMap &R2Subs =3D R2->getSubRegs(RegBank);
-      SubRegMap::const_iterator ni =3D R2Subs.find(IdxInit->getDef());
+      SubRegMap::const_iterator ni =3D R2Subs.find(Idx);
       if (ni =3D=3D R2Subs.end())
         throw TGError(TheDef->getLoc(), "Composite " + Pat->getAsString() +
                       " refers to bad index in " + R2->getName());
@@ -121,37 +275,78 @@
     }
=20
     // Insert composite index. Allow overriding inherited indices etc.
-    SubRegs[BaseIdxInit->getDef()] =3D R2;
+    SubRegs[BaseIdx] =3D R2;
=20
     // R2 is no longer an orphan.
-    for (unsigned j =3D 0, je =3D Orphans.size(); j !=3D je; ++j)
-      if (Orphans[j].SubReg =3D=3D R2)
-          Orphans[j].SubReg =3D 0;
+    Orphans.erase(R2);
   }
=20
   // Now Orphans contains the inherited subregisters without a direct inde=
x.
   // Create inferred indexes for all missing entries.
-  for (unsigned i =3D 0, e =3D Orphans.size(); i !=3D e; ++i) {
-    Orphan &O =3D Orphans[i];
-    if (!O.SubReg)
-      continue;
-    SubRegs[RegBank.getCompositeSubRegIndex(O.First, O.Second, true)] =3D
-      O.SubReg;
+  // Work backwards in the Indices vector in order to compose subregs bott=
om-up.
+  // Consider this subreg sequence:
+  //
+  //   qsub_1 -> dsub_0 -> ssub_0
+  //
+  // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 regist=
er
+  // can be reached in two different ways:
+  //
+  //   qsub_1 -> ssub_0
+  //   dsub_2 -> ssub_0
+  //
+  // We pick the latter composition because another register may have [dsu=
b_0,
+  // dsub_1, dsub_2] subregs without neccessarily having a qsub_1 subreg. =
 The
+  // dsub_2 -> ssub_0 composition can be shared.
+  while (!Indices.empty() && !Orphans.empty()) {
+    CodeGenSubRegIndex *Idx =3D Indices.pop_back_val();
+    CodeGenRegister *SR =3D SubRegs[Idx];
+    const SubRegMap &Map =3D SR->getSubRegs(RegBank);
+    for (SubRegMap::const_iterator SI =3D Map.begin(), SE =3D Map.end(); S=
I !=3D SE;
+         ++SI)
+      if (Orphans.erase(SI->second))
+        SubRegs[RegBank.getCompositeSubRegIndex(Idx, SI->first)] =3D SI->s=
econd;
   }
+
+  // Initialize RegUnitList. A register with no subregisters creates its o=
wn
+  // unit. Otherwise, it inherits all its subregister's units. Because
+  // getSubRegs is called recursively, this processes the register hierarc=
hy in
+  // postorder.
+  //
+  // TODO: We currently assume all register units correspond to a named "l=
eaf"
+  // register. We should also unify register units for ad-hoc register
+  // aliases. This can be done by iteratively merging units for aliasing
+  // registers using a worklist.
+  assert(RegUnits.empty() && "Should only initialize RegUnits once");
+  if (SubRegs.empty())
+    RegUnits.push_back(RegBank.newRegUnit(0));
+  else
+    inheritRegUnits(RegBank);
   return SubRegs;
 }
=20
 void
-CodeGenRegister::addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) con=
st {
+CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSe=
t,
+                                    CodeGenRegBank &RegBank) const {
   assert(SubRegsComplete && "Must precompute sub-registers");
   std::vector<Record*> Indices =3D TheDef->getValueAsListOfDefs("SubRegInd=
ices");
   for (unsigned i =3D 0, e =3D Indices.size(); i !=3D e; ++i) {
-    CodeGenRegister *SR =3D SubRegs.find(Indices[i])->second;
+    CodeGenSubRegIndex *Idx =3D RegBank.getSubRegIdx(Indices[i]);
+    CodeGenRegister *SR =3D SubRegs.find(Idx)->second;
     if (OSet.insert(SR))
-      SR->addSubRegsPreOrder(OSet);
+      SR->addSubRegsPreOrder(OSet, RegBank);
   }
 }
=20
+// Get the sum of this register's unit weights.
+unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
+  unsigned Weight =3D 0;
+  for (RegUnitList::const_iterator I =3D RegUnits.begin(), E =3D RegUnits.=
end();
+       I !=3D E; ++I) {
+    Weight +=3D RegBank.getRegUnitWeight(*I);
+  }
+  return Weight;
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                               RegisterTuples
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -215,30 +410,40 @@
       for (unsigned i =3D 0, e =3D Proto->getValues().size(); i !=3D e; ++=
i) {
         RecordVal RV =3D Proto->getValues()[i];
=20
+        // Skip existing fields, like NAME.
+        if (NewReg->getValue(RV.getNameInit()))
+          continue;
+
+        StringRef Field =3D RV.getName();
+
         // Replace the sub-register list with Tuple.
-        if (RV.getName() =3D=3D "SubRegs")
+        if (Field =3D=3D "SubRegs")
           RV.setValue(ListInit::get(Tuple, RegisterRecTy));
=20
         // Provide a blank AsmName. MC hacks are required anyway.
-        if (RV.getName() =3D=3D "AsmName")
+        if (Field =3D=3D "AsmName")
           RV.setValue(BlankName);
=20
         // CostPerUse is aggregated from all Tuple members.
-        if (RV.getName() =3D=3D "CostPerUse")
+        if (Field =3D=3D "CostPerUse")
           RV.setValue(IntInit::get(CostPerUse));
=20
+        // Composite registers are always covered by sub-registers.
+        if (Field =3D=3D "CoveredBySubRegs")
+          RV.setValue(BitInit::get(true));
+
         // Copy fields from the RegisterTuples def.
-        if (RV.getName() =3D=3D "SubRegIndices" ||
-            RV.getName() =3D=3D "CompositeIndices") {
-          NewReg->addValue(*Def->getValue(RV.getName()));
+        if (Field =3D=3D "SubRegIndices" ||
+            Field =3D=3D "CompositeIndices") {
+          NewReg->addValue(*Def->getValue(Field));
           continue;
         }
=20
         // Some fields get their default uninitialized value.
-        if (RV.getName() =3D=3D "DwarfNumbers" ||
-            RV.getName() =3D=3D "DwarfAlias" ||
-            RV.getName() =3D=3D "Aliases") {
-          if (const RecordVal *DefRV =3D RegisterCl->getValue(RV.getName()=
))
+        if (Field =3D=3D "DwarfNumbers" ||
+            Field =3D=3D "DwarfAlias" ||
+            Field =3D=3D "Aliases") {
+          if (const RecordVal *DefRV =3D RegisterCl->getValue(Field))
             NewReg->addValue(*DefRV);
           continue;
         }
@@ -330,7 +535,7 @@
   SpillAlignment =3D R->getValueAsInt("Alignment");
   CopyCost =3D R->getValueAsInt("CopyCost");
   Allocatable =3D R->getValueAsBit("isAllocatable");
-  AltOrderSelect =3D R->getValueAsCode("AltOrderSelect");
+  AltOrderSelect =3D R->getValueAsString("AltOrderSelect");
 }
=20
 // Create an inferred register class that was missing from the .td files.
@@ -448,7 +653,7 @@
     return 1;
=20
   // Finally order by name as a tie breaker.
-  return A->getName() < B->getName();
+  return StringRef(A->getName()).compare(B->getName());
 }
=20
 std::string CodeGenRegisterClass::getQualifiedName() const {
@@ -504,6 +709,30 @@
       RegClasses[rci]->inheritProperties(RegBank);
 }
=20
+void
+CodeGenRegisterClass::getSuperRegClasses(CodeGenSubRegIndex *SubIdx,
+                                         BitVector &Out) const {
+  DenseMap<CodeGenSubRegIndex*,
+           SmallPtrSet<CodeGenRegisterClass*, 8> >::const_iterator
+    FindI =3D SuperRegClasses.find(SubIdx);
+  if (FindI =3D=3D SuperRegClasses.end())
+    return;
+  for (SmallPtrSet<CodeGenRegisterClass*, 8>::const_iterator I =3D
+       FindI->second.begin(), E =3D FindI->second.end(); I !=3D E; ++I)
+    Out.set((*I)->EnumValue);
+}
+
+// Populate a unique sorted list of units from a register set.
+void CodeGenRegisterClass::buildRegUnitSet(
+  std::vector<unsigned> &RegUnits) const {
+  std::vector<unsigned> TmpUnits;
+  for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI)
+    TmpUnits.push_back(*UnitI);
+  std::sort(TmpUnits.begin(), TmpUnits.end());
+  std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
+                   std::back_inserter(RegUnits));
+}
+
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
 //                               CodeGenRegBank
 //=3D=3D=3D---------------------------------------------------------------=
-------=3D=3D=3D//
@@ -511,13 +740,19 @@
 CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records) : Records(Records) {
   // Configure register Sets to understand register classes and tuples.
   Sets.addFieldExpander("RegisterClass", "MemberList");
+  Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
   Sets.addExpander("RegisterTuples", new TupleExpander());
=20
   // Read in the user-defined (named) sub-register indices.
   // More indices will be synthesized later.
-  SubRegIndices =3D Records.getAllDerivedDefinitions("SubRegIndex");
-  std::sort(SubRegIndices.begin(), SubRegIndices.end(), LessRecord());
-  NumNamedIndices =3D SubRegIndices.size();
+  std::vector<Record*> SRIs =3D Records.getAllDerivedDefinitions("SubRegIn=
dex");
+  std::sort(SRIs.begin(), SRIs.end(), LessRecord());
+  NumNamedIndices =3D SRIs.size();
+  for (unsigned i =3D 0, e =3D SRIs.size(); i !=3D e; ++i)
+    getSubRegIdx(SRIs[i]);
+  // Build composite maps from ComposedOf fields.
+  for (unsigned i =3D 0, e =3D SubRegIndices.size(); i !=3D e; ++i)
+    SubRegIndices[i]->updateComponents(*this);
=20
   // Read in the register definitions.
   std::vector<Record*> Regs =3D Records.getAllDerivedDefinitions("Register=
");
@@ -538,9 +773,14 @@
=20
   // Precompute all sub-register maps now all the registers are known.
   // This will create Composite entries for all inferred sub-register indi=
ces.
+  NumRegUnits =3D 0;
   for (unsigned i =3D 0, e =3D Registers.size(); i !=3D e; ++i)
     Registers[i]->getSubRegs(*this);
=20
+  // Native register units are associated with a leaf register. They've al=
l been
+  // discovered now.
+  NumNativeRegUnits =3D NumRegUnits;
+
   // Read in register class definitions.
   std::vector<Record*> RCs =3D Records.getAllDerivedDefinitions("RegisterC=
lass");
   if (RCs.empty())
@@ -561,6 +801,15 @@
   CodeGenRegisterClass::computeSubClasses(*this);
 }
=20
+CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
+  CodeGenSubRegIndex *&Idx =3D Def2SubRegIdx[Def];
+  if (Idx)
+    return Idx;
+  Idx =3D new CodeGenSubRegIndex(Def, SubRegIndices.size() + 1);
+  SubRegIndices.push_back(Idx);
+  return Idx;
+}
+
 CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
   CodeGenRegister *&Reg =3D Def2Reg[Def];
   if (Reg)
@@ -582,6 +831,23 @@
   Key2RC.insert(std::make_pair(K, RC));
 }
=20
+// Create a synthetic sub-class if it is missing.
+CodeGenRegisterClass*
+CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
+                                    const CodeGenRegister::Set *Members,
+                                    StringRef Name) {
+  // Synthetic sub-class has the same size and alignment as RC.
+  CodeGenRegisterClass::Key K(Members, RC->SpillSize, RC->SpillAlignment);
+  RCKeyMap::const_iterator FoundI =3D Key2RC.find(K);
+  if (FoundI !=3D Key2RC.end())
+    return FoundI->second;
+
+  // Sub-class doesn't exist, create a new one.
+  CodeGenRegisterClass *NewRC =3D new CodeGenRegisterClass(Name, K);
+  addToMaps(NewRC);
+  return NewRC;
+}
+
 CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
   if (CodeGenRegisterClass *RC =3D Def2RC[Def])
     return RC;
@@ -589,34 +855,28 @@
   throw TGError(Def->getLoc(), "Not a known RegisterClass!");
 }
=20
-Record *CodeGenRegBank::getCompositeSubRegIndex(Record *A, Record *B,
-                                                bool create) {
+CodeGenSubRegIndex*
+CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
+                                        CodeGenSubRegIndex *B) {
   // Look for an existing entry.
-  Record *&Comp =3D Composite[std::make_pair(A, B)];
-  if (Comp || !create)
+  CodeGenSubRegIndex *Comp =3D A->compose(B);
+  if (Comp)
     return Comp;
=20
   // None exists, synthesize one.
   std::string Name =3D A->getName() + "_then_" + B->getName();
-  Comp =3D new Record(Name, SMLoc(), Records);
-  SubRegIndices.push_back(Comp);
+  Comp =3D getSubRegIdx(new Record(Name, SMLoc(), Records));
+  A->addComposite(B, Comp);
   return Comp;
 }
=20
-unsigned CodeGenRegBank::getSubRegIndexNo(Record *idx) {
-  std::vector<Record*>::const_iterator i =3D
-    std::find(SubRegIndices.begin(), SubRegIndices.end(), idx);
-  assert(i !=3D SubRegIndices.end() && "Not a SubRegIndex");
-  return (i - SubRegIndices.begin()) + 1;
-}
-
 void CodeGenRegBank::computeComposites() {
   for (unsigned i =3D 0, e =3D Registers.size(); i !=3D e; ++i) {
     CodeGenRegister *Reg1 =3D Registers[i];
     const CodeGenRegister::SubRegMap &SRM1 =3D Reg1->getSubRegs();
     for (CodeGenRegister::SubRegMap::const_iterator i1 =3D SRM1.begin(),
          e1 =3D SRM1.end(); i1 !=3D e1; ++i1) {
-      Record *Idx1 =3D i1->first;
+      CodeGenSubRegIndex *Idx1 =3D i1->first;
       CodeGenRegister *Reg2 =3D i1->second;
       // Ignore identity compositions.
       if (Reg1 =3D=3D Reg2)
@@ -625,7 +885,7 @@
       // Try composing Idx1 with another SubRegIndex.
       for (CodeGenRegister::SubRegMap::const_iterator i2 =3D SRM2.begin(),
            e2 =3D SRM2.end(); i2 !=3D e2; ++i2) {
-        std::pair<Record*, Record*> IdxPair(Idx1, i2->first);
+      CodeGenSubRegIndex *Idx2 =3D i2->first;
         CodeGenRegister *Reg3 =3D i2->second;
         // Ignore identity compositions.
         if (Reg2 =3D=3D Reg3)
@@ -634,16 +894,13 @@
         for (CodeGenRegister::SubRegMap::const_iterator i1d =3D SRM1.begin=
(),
              e1d =3D SRM1.end(); i1d !=3D e1d; ++i1d) {
           if (i1d->second =3D=3D Reg3) {
-            std::pair<CompositeMap::iterator, bool> Ins =3D
-              Composite.insert(std::make_pair(IdxPair, i1d->first));
             // Conflicting composition? Emit a warning but allow it.
-            if (!Ins.second && Ins.first->second !=3D i1d->first) {
-              errs() << "Warning: SubRegIndex " << getQualifiedName(Idx1)
-                     << " and " << getQualifiedName(IdxPair.second)
+            if (CodeGenSubRegIndex *Prev =3D Idx1->addComposite(Idx2, i1d-=
>first))
+              errs() << "Warning: SubRegIndex " << Idx1->getQualifiedName()
+                     << " and " << Idx2->getQualifiedName()
                      << " compose ambiguously as "
-                     << getQualifiedName(Ins.first->second) << " or "
-                     << getQualifiedName(i1d->first) << "\n";
-            }
+                     << Prev->getQualifiedName() << " or "
+                     << i1d->first->getQualifiedName() << "\n";
           }
         }
       }
@@ -652,12 +909,388 @@
=20
   // We don't care about the difference between (Idx1, Idx2) -> Idx2 and i=
nvalid
   // compositions, so remove any mappings of that form.
-  for (CompositeMap::iterator i =3D Composite.begin(), e =3D Composite.end=
();
-       i !=3D e;) {
-    CompositeMap::iterator j =3D i;
-    ++i;
-    if (j->first.second =3D=3D j->second)
-      Composite.erase(j);
+  for (unsigned i =3D 0, e =3D SubRegIndices.size(); i !=3D e; ++i)
+    SubRegIndices[i]->cleanComposites();
+}
+
+namespace {
+// UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet=
 is
+// the transitive closure of the union of overlapping register
+// classes. Together, the UberRegSets form a partition of the registers. I=
f we
+// consider overlapping register classes to be connected, then each UberRe=
gSet
+// is a set of connected components.
+//
+// An UberRegSet will likely be a horizontal slice of register names of
+// the same width. Nontrivial subregisters should then be in a separate
+// UberRegSet. But this property isn't required for valid computation of
+// register unit weights.
+//
+// A Weight field caches the max per-register unit weight in each UberRegS=
et.
+//
+// A set of SingularDeterminants flags single units of some register in th=
is set
+// for which the unit weight equals the set weight. These units should not=
 have
+// their weight increased.
+struct UberRegSet {
+  CodeGenRegister::Set Regs;
+  unsigned Weight;
+  CodeGenRegister::RegUnitList SingularDeterminants;
+
+  UberRegSet(): Weight(0) {}
+};
+} // namespace
+
+// Partition registers into UberRegSets, where each set is the transitive
+// closure of the union of overlapping register classes.
+//
+// UberRegSets[0] is a special non-allocatable set.
+static void computeUberSets(std::vector<UberRegSet> &UberSets,
+                            std::vector<UberRegSet*> &RegSets,
+                            CodeGenRegBank &RegBank) {
+
+  const std::vector<CodeGenRegister*> &Registers =3D RegBank.getRegisters(=
);
+
+  // The Register EnumValue is one greater than its index into Registers.
+  assert(Registers.size() =3D=3D Registers[Registers.size()-1]->EnumValue =
&&
+         "register enum value mismatch");
+
+  // For simplicitly make the SetID the same as EnumValue.
+  IntEqClasses UberSetIDs(Registers.size()+1);
+  std::set<unsigned> AllocatableRegs;
+  for (unsigned i =3D 0, e =3D RegBank.getRegClasses().size(); i !=3D e; +=
+i) {
+
+    CodeGenRegisterClass *RegClass =3D RegBank.getRegClasses()[i];
+    if (!RegClass->Allocatable)
+      continue;
+
+    const CodeGenRegister::Set &Regs =3D RegClass->getMembers();
+    if (Regs.empty())
+      continue;
+
+    unsigned USetID =3D UberSetIDs.findLeader((*Regs.begin())->EnumValue);
+    assert(USetID && "register number 0 is invalid");
+
+    AllocatableRegs.insert((*Regs.begin())->EnumValue);
+    for (CodeGenRegister::Set::const_iterator I =3D llvm::next(Regs.begin(=
)),
+           E =3D Regs.end(); I !=3D E; ++I) {
+      AllocatableRegs.insert((*I)->EnumValue);
+      UberSetIDs.join(USetID, (*I)->EnumValue);
+    }
+  }
+  // Combine non-allocatable regs.
+  for (unsigned i =3D 0, e =3D Registers.size(); i !=3D e; ++i) {
+    unsigned RegNum =3D Registers[i]->EnumValue;
+    if (AllocatableRegs.count(RegNum))
+      continue;
+
+    UberSetIDs.join(0, RegNum);
+  }
+  UberSetIDs.compress();
+
+  // Make the first UberSet a special unallocatable set.
+  unsigned ZeroID =3D UberSetIDs[0];
+
+  // Insert Registers into the UberSets formed by union-find.
+  // Do not resize after this.
+  UberSets.resize(UberSetIDs.getNumClasses());
+  for (unsigned i =3D 0, e =3D Registers.size(); i !=3D e; ++i) {
+    const CodeGenRegister *Reg =3D Registers[i];
+    unsigned USetID =3D UberSetIDs[Reg->EnumValue];
+    if (!USetID)
+      USetID =3D ZeroID;
+    else if (USetID =3D=3D ZeroID)
+      USetID =3D 0;
+
+    UberRegSet *USet =3D &UberSets[USetID];
+    USet->Regs.insert(Reg);
+    RegSets[i] =3D USet;
+  }
+}
+
+// Recompute each UberSet weight after changing unit weights.
+static void computeUberWeights(std::vector<UberRegSet> &UberSets,
+                               CodeGenRegBank &RegBank) {
+  // Skip the first unallocatable set.
+  for (std::vector<UberRegSet>::iterator I =3D llvm::next(UberSets.begin()=
),
+         E =3D UberSets.end(); I !=3D E; ++I) {
+
+    // Initialize all unit weights in this set, and remember the max units=
/reg.
+    const CodeGenRegister *Reg =3D 0;
+    unsigned MaxWeight =3D 0, Weight =3D 0;
+    for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
+      if (Reg !=3D UnitI.getReg()) {
+        if (Weight > MaxWeight)
+          MaxWeight =3D Weight;
+        Reg =3D UnitI.getReg();
+        Weight =3D 0;
+      }
+      unsigned UWeight =3D RegBank.getRegUnitWeight(*UnitI);
+      if (!UWeight) {
+        UWeight =3D 1;
+        RegBank.increaseRegUnitWeight(*UnitI, UWeight);
+      }
+      Weight +=3D UWeight;
+    }
+    if (Weight > MaxWeight)
+      MaxWeight =3D Weight;
+
+    // Update the set weight.
+    I->Weight =3D MaxWeight;
+
+    // Find singular determinants.
+    for (CodeGenRegister::Set::iterator RegI =3D I->Regs.begin(),
+           RegE =3D I->Regs.end(); RegI !=3D RegE; ++RegI) {
+      if ((*RegI)->getRegUnits().size() =3D=3D 1
+          && (*RegI)->getWeight(RegBank) =3D=3D I->Weight)
+        mergeRegUnits(I->SingularDeterminants, (*RegI)->getRegUnits());
+    }
+  }
+}
+
+// normalizeWeight is a computeRegUnitWeights helper that adjusts the weig=
ht of
+// a register and its subregisters so that they have the same weight as th=
eir
+// UberSet. Self-recursion processes the subregister tree in postorder so
+// subregisters are normalized first.
+//
+// Side effects:
+// - creates new adopted register units
+// - causes superregisters to inherit adopted units
+// - increases the weight of "singular" units
+// - induces recomputation of UberWeights.
+static bool normalizeWeight(CodeGenRegister *Reg,
+                            std::vector<UberRegSet> &UberSets,
+                            std::vector<UberRegSet*> &RegSets,
+                            CodeGenRegister::RegUnitList &NormalUnits,
+                            CodeGenRegBank &RegBank) {
+  bool Changed =3D false;
+  const CodeGenRegister::SubRegMap &SRM =3D Reg->getSubRegs();
+  for (CodeGenRegister::SubRegMap::const_iterator SRI =3D SRM.begin(),
+         SRE =3D SRM.end(); SRI !=3D SRE; ++SRI) {
+    if (SRI->second =3D=3D Reg)
+      continue; // self-cycles happen
+
+    Changed |=3D
+      normalizeWeight(SRI->second, UberSets, RegSets, NormalUnits, RegBank=
);
+  }
+  // Postorder register normalization.
+
+  // Inherit register units newly adopted by subregisters.
+  if (Reg->inheritRegUnits(RegBank))
+    computeUberWeights(UberSets, RegBank);
+
+  // Check if this register is too skinny for its UberRegSet.
+  UberRegSet *UberSet =3D RegSets[RegBank.getRegIndex(Reg)];
+
+  unsigned RegWeight =3D Reg->getWeight(RegBank);
+  if (UberSet->Weight > RegWeight) {
+    // A register unit's weight can be adjusted only if it is the singular=
 unit
+    // for this register, has not been used to normalize a subregister's s=
et,
+    // and has not already been used to singularly determine this UberRegS=
et.
+    unsigned AdjustUnit =3D Reg->getRegUnits().front();
+    if (Reg->getRegUnits().size() !=3D 1
+        || hasRegUnit(NormalUnits, AdjustUnit)
+        || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
+      // We don't have an adjustable unit, so adopt a new one.
+      AdjustUnit =3D RegBank.newRegUnit(UberSet->Weight - RegWeight);
+      Reg->adoptRegUnit(AdjustUnit);
+      // Adopting a unit does not immediately require recomputing set weig=
hts.
+    }
+    else {
+      // Adjust the existing single unit.
+      RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeigh=
t);
+      // The unit may be shared among sets and registers within this set.
+      computeUberWeights(UberSets, RegBank);
+    }
+    Changed =3D true;
+  }
+
+  // Mark these units normalized so superregisters can't change their weig=
hts.
+  mergeRegUnits(NormalUnits, Reg->getRegUnits());
+
+  return Changed;
+}
+
+// Compute a weight for each register unit created during getSubRegs.
+//
+// The goal is that two registers in the same class will have the same wei=
ght,
+// where each register's weight is defined as sum of its units' weights.
+void CodeGenRegBank::computeRegUnitWeights() {
+  assert(RegUnitWeights.empty() && "Only initialize RegUnitWeights once");
+
+  // Only allocatable units will be initialized to nonzero weight.
+  RegUnitWeights.resize(NumRegUnits);
+
+  std::vector<UberRegSet> UberSets;
+  std::vector<UberRegSet*> RegSets(Registers.size());
+  computeUberSets(UberSets, RegSets, *this);
+  // UberSets and RegSets are now immutable.
+
+  computeUberWeights(UberSets, *this);
+
+  // Iterate over each Register, normalizing the unit weights until reachi=
ng
+  // a fix point.
+  unsigned NumIters =3D 0;
+  for (bool Changed =3D true; Changed; ++NumIters) {
+    assert(NumIters <=3D NumNativeRegUnits && "Runaway register unit weigh=
ts");
+    Changed =3D false;
+    for (unsigned i =3D 0, e =3D Registers.size(); i !=3D e; ++i) {
+      CodeGenRegister::RegUnitList NormalUnits;
+      Changed |=3D
+        normalizeWeight(Registers[i], UberSets, RegSets, NormalUnits, *thi=
s);
+    }
+  }
+}
+
+// Find a set in UniqueSets with the same elements as Set.
+// Return an iterator into UniqueSets.
+static std::vector<RegUnitSet>::const_iterator
+findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
+               const RegUnitSet &Set) {
+  std::vector<RegUnitSet>::const_iterator
+    I =3D UniqueSets.begin(), E =3D UniqueSets.end();
+  for(;I !=3D E; ++I) {
+    if (I->Units =3D=3D Set.Units)
+      break;
+  }
+  return I;
+}
+
+// Return true if the RUSubSet is a subset of RUSuperSet.
+static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
+                            const std::vector<unsigned> &RUSuperSet) {
+  return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
+                       RUSubSet.begin(), RUSubSet.end());
+}
+
+// Iteratively prune unit sets.
+void CodeGenRegBank::pruneUnitSets() {
+  assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets");
+
+  // Form an equivalence class of UnitSets with no significant difference.
+  std::vector<unsigned> SuperSetIDs;
+  for (unsigned SubIdx =3D 0, EndIdx =3D RegUnitSets.size();
+       SubIdx !=3D EndIdx; ++SubIdx) {
+    const RegUnitSet &SubSet =3D RegUnitSets[SubIdx];
+    unsigned SuperIdx =3D 0;
+    for (; SuperIdx !=3D EndIdx; ++SuperIdx) {
+      if (SuperIdx =3D=3D SubIdx)
+        continue;
+
+      const RegUnitSet &SuperSet =3D RegUnitSets[SuperIdx];
+      if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
+          && (SubSet.Units.size() + 3 > SuperSet.Units.size())) {
+        break;
+      }
+    }
+    if (SuperIdx =3D=3D EndIdx)
+      SuperSetIDs.push_back(SubIdx);
+  }
+  // Populate PrunedUnitSets with each equivalence class's superset.
+  std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
+  for (unsigned i =3D 0, e =3D SuperSetIDs.size(); i !=3D e; ++i) {
+    unsigned SuperIdx =3D SuperSetIDs[i];
+    PrunedUnitSets[i].Name =3D RegUnitSets[SuperIdx].Name;
+    PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
+  }
+  RegUnitSets.swap(PrunedUnitSets);
+}
+
+// Create a RegUnitSet for each RegClass that contains all units in the cl=
ass
+// including adopted units that are necessary to model register pressure. =
Then
+// iteratively compute RegUnitSets such that the union of any two overlapp=
ing
+// RegUnitSets is repreresented.
+//
+// RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
+// RegUnitSet that is a superset of that RegUnitClass.
+void CodeGenRegBank::computeRegUnitSets() {
+
+  // Compute a unique RegUnitSet for each RegClass.
+  const ArrayRef<CodeGenRegisterClass*> &RegClasses =3D getRegClasses();
+  unsigned NumRegClasses =3D RegClasses.size();
+  for (unsigned RCIdx =3D 0, RCEnd =3D NumRegClasses; RCIdx !=3D RCEnd; ++=
RCIdx) {
+    if (!RegClasses[RCIdx]->Allocatable)
+      continue;
+
+    // Speculatively grow the RegUnitSets to hold the new set.
+    RegUnitSets.resize(RegUnitSets.size() + 1);
+    RegUnitSets.back().Name =3D RegClasses[RCIdx]->getName();
+
+    // Compute a sorted list of units in this class.
+    RegClasses[RCIdx]->buildRegUnitSet(RegUnitSets.back().Units);
+
+    // Find an existing RegUnitSet.
+    std::vector<RegUnitSet>::const_iterator SetI =3D
+      findRegUnitSet(RegUnitSets, RegUnitSets.back());
+    if (SetI !=3D llvm::prior(RegUnitSets.end()))
+      RegUnitSets.pop_back();
+  }
+
+  // Iteratively prune unit sets.
+  pruneUnitSets();
+
+  // Iterate over all unit sets, including new ones added by this loop.
+  unsigned NumRegUnitSubSets =3D RegUnitSets.size();
+  for (unsigned Idx =3D 0, EndIdx =3D RegUnitSets.size(); Idx !=3D EndIdx;=
 ++Idx) {
+    // In theory, this is combinatorial. In practice, it needs to be bound=
ed
+    // by a small number of sets for regpressure to be efficient.
+    // If the assert is hit, we need to implement pruning.
+    assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference");
+
+    // Compare new sets with all original classes.
+    for (unsigned SearchIdx =3D (Idx >=3D NumRegUnitSubSets) ? 0 : Idx+1;
+         SearchIdx !=3D EndIdx; ++SearchIdx) {
+      std::set<unsigned> Intersection;
+      std::set_intersection(RegUnitSets[Idx].Units.begin(),
+                            RegUnitSets[Idx].Units.end(),
+                            RegUnitSets[SearchIdx].Units.begin(),
+                            RegUnitSets[SearchIdx].Units.end(),
+                            std::inserter(Intersection, Intersection.begin=
()));
+      if (Intersection.empty())
+        continue;
+
+      // Speculatively grow the RegUnitSets to hold the new set.
+      RegUnitSets.resize(RegUnitSets.size() + 1);
+      RegUnitSets.back().Name =3D
+        RegUnitSets[Idx].Name + "+" + RegUnitSets[SearchIdx].Name;
+
+      std::set_union(RegUnitSets[Idx].Units.begin(),
+                     RegUnitSets[Idx].Units.end(),
+                     RegUnitSets[SearchIdx].Units.begin(),
+                     RegUnitSets[SearchIdx].Units.end(),
+                     std::inserter(RegUnitSets.back().Units,
+                                   RegUnitSets.back().Units.begin()));
+
+      // Find an existing RegUnitSet, or add the union to the unique sets.
+      std::vector<RegUnitSet>::const_iterator SetI =3D
+        findRegUnitSet(RegUnitSets, RegUnitSets.back());
+      if (SetI !=3D llvm::prior(RegUnitSets.end()))
+        RegUnitSets.pop_back();
+    }
+  }
+
+  // Iteratively prune unit sets after inferring supersets.
+  pruneUnitSets();
+
+  // For each register class, list the UnitSets that are supersets.
+  RegClassUnitSets.resize(NumRegClasses);
+  for (unsigned RCIdx =3D 0, RCEnd =3D NumRegClasses; RCIdx !=3D RCEnd; ++=
RCIdx) {
+    if (!RegClasses[RCIdx]->Allocatable)
+      continue;
+
+    // Recompute the sorted list of units in this class.
+    std::vector<unsigned> RegUnits;
+    RegClasses[RCIdx]->buildRegUnitSet(RegUnits);
+
+    // Don't increase pressure for unallocatable regclasses.
+    if (RegUnits.empty())
+      continue;
+
+    // Find all supersets.
+    for (unsigned USIdx =3D 0, USEnd =3D RegUnitSets.size();
+         USIdx !=3D USEnd; ++USIdx) {
+      if (isRegUnitSubSet(RegUnits, RegUnitSets[USIdx].Units))
+        RegClassUnitSets[RCIdx].push_back(USIdx);
+    }
+    assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regcl=
ass");
   }
 }
=20
@@ -737,62 +1370,187 @@
=20
 void CodeGenRegBank::computeDerivedInfo() {
   computeComposites();
+
+  // Compute a weight for each register unit created during getSubRegs.
+  // This may create adopted register units (with unit # >=3D NumNativeReg=
Units).
+  computeRegUnitWeights();
+
+  // Compute a unique set of RegUnitSets. One for each RegClass and inferr=
ed
+  // supersets for the union of overlapping sets.
+  computeRegUnitSets();
 }
=20
+//
+// Synthesize missing register class intersections.
+//
+// Make sure that sub-classes of RC exists such that getCommonSubClass(RC,=
 X)
+// returns a maximal register class for all X.
+//
+void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
+  for (unsigned rci =3D 0, rce =3D RegClasses.size(); rci !=3D rce; ++rci)=
 {
+    CodeGenRegisterClass *RC1 =3D RC;
+    CodeGenRegisterClass *RC2 =3D RegClasses[rci];
+    if (RC1 =3D=3D RC2)
+      continue;
+
+    // Compute the set intersection of RC1 and RC2.
+    const CodeGenRegister::Set &Memb1 =3D RC1->getMembers();
+    const CodeGenRegister::Set &Memb2 =3D RC2->getMembers();
+    CodeGenRegister::Set Intersection;
+    std::set_intersection(Memb1.begin(), Memb1.end(),
+                          Memb2.begin(), Memb2.end(),
+                          std::inserter(Intersection, Intersection.begin()=
),
+                          CodeGenRegister::Less());
+
+    // Skip disjoint class pairs.
+    if (Intersection.empty())
+      continue;
+
+    // If RC1 and RC2 have different spill sizes or alignments, use the
+    // larger size for sub-classing.  If they are equal, prefer RC1.
+    if (RC2->SpillSize > RC1->SpillSize ||
+        (RC2->SpillSize =3D=3D RC1->SpillSize &&
+         RC2->SpillAlignment > RC1->SpillAlignment))
+      std::swap(RC1, RC2);
+
+    getOrCreateSubClass(RC1, &Intersection,
+                        RC1->getName() + "_and_" + RC2->getName());
+  }
+}
+
+//
+// Synthesize missing sub-classes for getSubClassWithSubReg().
+//
+// Make sure that the set of registers in RC with a given SubIdx sub-regis=
ter
+// form a register class.  Update RC->SubClassWithSubReg.
+//
+void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
+  // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
+  typedef std::map<CodeGenSubRegIndex*, CodeGenRegister::Set,
+                   CodeGenSubRegIndex::Less> SubReg2SetMap;
+
+  // Compute the set of registers supporting each SubRegIndex.
+  SubReg2SetMap SRSets;
+  for (CodeGenRegister::Set::const_iterator RI =3D RC->getMembers().begin(=
),
+       RE =3D RC->getMembers().end(); RI !=3D RE; ++RI) {
+    const CodeGenRegister::SubRegMap &SRM =3D (*RI)->getSubRegs();
+    for (CodeGenRegister::SubRegMap::const_iterator I =3D SRM.begin(),
+         E =3D SRM.end(); I !=3D E; ++I)
+      SRSets[I->first].insert(*RI);
+  }
+
+  // Find matching classes for all SRSets entries.  Iterate in SubRegIndex
+  // numerical order to visit synthetic indices last.
+  for (unsigned sri =3D 0, sre =3D SubRegIndices.size(); sri !=3D sre; ++s=
ri) {
+    CodeGenSubRegIndex *SubIdx =3D SubRegIndices[sri];
+    SubReg2SetMap::const_iterator I =3D SRSets.find(SubIdx);
+    // Unsupported SubRegIndex. Skip it.
+    if (I =3D=3D SRSets.end())
+      continue;
+    // In most cases, all RC registers support the SubRegIndex.
+    if (I->second.size() =3D=3D RC->getMembers().size()) {
+      RC->setSubClassWithSubReg(SubIdx, RC);
+      continue;
+    }
+    // This is a real subset.  See if we have a matching class.
+    CodeGenRegisterClass *SubRC =3D
+      getOrCreateSubClass(RC, &I->second,
+                          RC->getName() + "_with_" + I->first->getName());
+    RC->setSubClassWithSubReg(SubIdx, SubRC);
+  }
+}
+
+//
+// Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
+//
+// Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx,=
 X)
+// has a maximal result for any SubIdx and any X >=3D FirstSubRegRC.
+//
+
+void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
+                                                unsigned FirstSubRegRC) {
+  SmallVector<std::pair<const CodeGenRegister*,
+                        const CodeGenRegister*>, 16> SSPairs;
+
+  // Iterate in SubRegIndex numerical order to visit synthetic indices las=
t.
+  for (unsigned sri =3D 0, sre =3D SubRegIndices.size(); sri !=3D sre; ++s=
ri) {
+    CodeGenSubRegIndex *SubIdx =3D SubRegIndices[sri];
+    // Skip indexes that aren't fully supported by RC's registers. This was
+    // computed by inferSubClassWithSubReg() above which should have been
+    // called first.
+    if (RC->getSubClassWithSubReg(SubIdx) !=3D RC)
+      continue;
+
+    // Build list of (Super, Sub) pairs for this SubIdx.
+    SSPairs.clear();
+    for (CodeGenRegister::Set::const_iterator RI =3D RC->getMembers().begi=
n(),
+         RE =3D RC->getMembers().end(); RI !=3D RE; ++RI) {
+      const CodeGenRegister *Super =3D *RI;
+      const CodeGenRegister *Sub =3D Super->getSubRegs().find(SubIdx)->sec=
ond;
+      assert(Sub && "Missing sub-register");
+      SSPairs.push_back(std::make_pair(Super, Sub));
+    }
+
+    // Iterate over sub-register class candidates.  Ignore classes created=
 by
+    // this loop. They will never be useful.
+    for (unsigned rci =3D FirstSubRegRC, rce =3D RegClasses.size(); rci !=
=3D rce;
+         ++rci) {
+      CodeGenRegisterClass *SubRC =3D RegClasses[rci];
+      // Compute the subset of RC that maps into SubRC.
+      CodeGenRegister::Set SubSet;
+      for (unsigned i =3D 0, e =3D SSPairs.size(); i !=3D e; ++i)
+        if (SubRC->contains(SSPairs[i].second))
+          SubSet.insert(SSPairs[i].first);
+      if (SubSet.empty())
+        continue;
+      // RC injects completely into SubRC.
+      if (SubSet.size() =3D=3D SSPairs.size()) {
+        SubRC->addSuperRegClass(SubIdx, RC);
+        continue;
+      }
+      // Only a subset of RC maps into SubRC. Make sure it is represented =
by a
+      // class.
+      getOrCreateSubClass(RC, &SubSet, RC->getName() +
+                          "_with_" + SubIdx->getName() +
+                          "_in_" + SubRC->getName());
+    }
+  }
+}
+
+
+//
 // Infer missing register classes.
 //
-// For every register class RC, make sure that the set of registers in RC =
with
-// a given SubIxx sub-register form a register class.
 void CodeGenRegBank::computeInferredRegisterClasses() {
   // When this function is called, the register classes have not been sort=
ed
   // and assigned EnumValues yet.  That means getSubClasses(),
   // getSuperClasses(), and hasSubClass() functions are defunct.
-
-  // Map SubRegIndex to register set.
-  typedef std::map<Record*, CodeGenRegister::Set, LessRecord> SubReg2SetMa=
p;
+  unsigned FirstNewRC =3D RegClasses.size();
=20
   // Visit all register classes, including the ones being added by the loo=
p.
   for (unsigned rci =3D 0; rci !=3D RegClasses.size(); ++rci) {
-    CodeGenRegisterClass &RC =3D *RegClasses[rci];
+    CodeGenRegisterClass *RC =3D RegClasses[rci];
=20
-    // Compute the set of registers supporting each SubRegIndex.
-    SubReg2SetMap SRSets;
-    for (CodeGenRegister::Set::const_iterator RI =3D RC.getMembers().begin=
(),
-         RE =3D RC.getMembers().end(); RI !=3D RE; ++RI) {
-      const CodeGenRegister::SubRegMap &SRM =3D (*RI)->getSubRegs();
-      for (CodeGenRegister::SubRegMap::const_iterator I =3D SRM.begin(),
-           E =3D SRM.end(); I !=3D E; ++I)
-        SRSets[I->first].insert(*RI);
-    }
+    // Synthesize answers for getSubClassWithSubReg().
+    inferSubClassWithSubReg(RC);
=20
-    // Find matching classes for all SRSets entries.  Iterate in SubRegInd=
ex
-    // numerical order to visit synthetic indices last.
-    for (unsigned sri =3D 0, sre =3D SubRegIndices.size(); sri !=3D sre; +=
+sri) {
-      Record *SubIdx =3D SubRegIndices[sri];
-      SubReg2SetMap::const_iterator I =3D SRSets.find(SubIdx);
-      // Unsupported SubRegIndex. Skip it.
-      if (I =3D=3D SRSets.end())
-        continue;
-      // In most cases, all RC registers support the SubRegIndex.
-      if (I->second.size() =3D=3D RC.getMembers().size()) {
-        RC.setSubClassWithSubReg(SubIdx, &RC);
-        continue;
-      }
+    // Synthesize answers for getCommonSubClass().
+    inferCommonSubClass(RC);
=20
-      // This is a real subset.  See if we have a matching class.
-      CodeGenRegisterClass::Key K(&I->second, RC.SpillSize, RC.SpillAlignm=
ent);
-      RCKeyMap::const_iterator FoundI =3D Key2RC.find(K);
-      if (FoundI !=3D Key2RC.end()) {
-        RC.setSubClassWithSubReg(SubIdx, FoundI->second);
-        continue;
-      }
+    // Synthesize answers for getMatchingSuperRegClass().
+    inferMatchingSuperRegClass(RC);
=20
-      // Class doesn't exist.
-      CodeGenRegisterClass *NewRC =3D
-        new CodeGenRegisterClass(RC.getName() + "_with_" +
-                                 I->first->getName(), K);
-      addToMaps(NewRC);
-      RC.setSubClassWithSubReg(SubIdx, NewRC);
+    // New register classes are created while this loop is running, and we=
 need
+    // to visit all of them.  I  particular, inferMatchingSuperRegClass ne=
eds
+    // to match old super-register classes with sub-register classes creat=
ed
+    // after inferMatchingSuperRegClass was called.  At this point,
+    // inferMatchingSuperRegClass has checked SuperRC =3D [0..rci] with Su=
bRC =3D
+    // [0..FirstNewRC).  We need to cover SubRC =3D [FirstNewRC..rci].
+    if (rci + 1 =3D=3D FirstNewRC) {
+      unsigned NextNewRC =3D RegClasses.size();
+      for (unsigned rci2 =3D 0; rci2 !=3D FirstNewRC; ++rci2)
+        inferMatchingSuperRegClass(RegClasses[rci2], FirstNewRC);
+      FirstNewRC =3D NextNewRC;
     }
   }
 }
@@ -843,3 +1601,45 @@
   }
   return FoundRC;
 }
+
+BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
+  SetVector<const CodeGenRegister*> Set;
+
+  // First add Regs with all sub-registers.
+  for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
+    CodeGenRegister *Reg =3D getReg(Regs[i]);
+    if (Set.insert(Reg))
+      // Reg is new, add all sub-registers.
+      // The pre-ordering is not important here.
+      Reg->addSubRegsPreOrder(Set, *this);
+  }
+
+  // Second, find all super-registers that are completely covered by the s=
et.
+  for (unsigned i =3D 0; i !=3D Set.size(); ++i) {
+    const CodeGenRegister::SuperRegList &SR =3D Set[i]->getSuperRegs();
+    for (unsigned j =3D 0, e =3D SR.size(); j !=3D e; ++j) {
+      const CodeGenRegister *Super =3D SR[j];
+      if (!Super->CoveredBySubRegs || Set.count(Super))
+        continue;
+      // This new super-register is covered by its sub-registers.
+      bool AllSubsInSet =3D true;
+      const CodeGenRegister::SubRegMap &SRM =3D Super->getSubRegs();
+      for (CodeGenRegister::SubRegMap::const_iterator I =3D SRM.begin(),
+             E =3D SRM.end(); I !=3D E; ++I)
+        if (!Set.count(I->second)) {
+          AllSubsInSet =3D false;
+          break;
+        }
+      // All sub-registers in Set, add Super as well.
+      // We will visit Super later to recheck its super-registers.
+      if (AllSubsInSet)
+        Set.insert(Super);
+    }
+  }
+
+  // Convert to BitVector.
+  BitVector BV(Registers.size() + 1);
+  for (unsigned i =3D 0, e =3D Set.size(); i !=3D e; ++i)
+    BV.set(Set[i]->EnumValue);
+  return BV;
+}
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeG=
enRegisters.h
--- a/head/contrib/llvm/utils/TableGen/CodeGenRegisters.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeGenRegisters.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -22,6 +22,7 @@
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SetVector.h"
+#include "llvm/Support/ErrorHandling.h"
 #include <cstdlib>
 #include <map>
 #include <string>
@@ -31,14 +32,69 @@
 namespace llvm {
   class CodeGenRegBank;
=20
+  /// CodeGenSubRegIndex - Represents a sub-register index.
+  class CodeGenSubRegIndex {
+    Record *const TheDef;
+    const unsigned EnumValue;
+
+  public:
+    CodeGenSubRegIndex(Record *R, unsigned Enum);
+
+    const std::string &getName() const;
+    std::string getNamespace() const;
+    std::string getQualifiedName() const;
+
+    // Order CodeGenSubRegIndex pointers by EnumValue.
+    struct Less {
+      bool operator()(const CodeGenSubRegIndex *A,
+                      const CodeGenSubRegIndex *B) const {
+        assert(A && B);
+        return A->EnumValue < B->EnumValue;
+      }
+    };
+
+    // Map of composite subreg indices.
+    typedef std::map<CodeGenSubRegIndex*, CodeGenSubRegIndex*, Less> CompM=
ap;
+
+    // Returns the subreg index that results from composing this with Idx.
+    // Returns NULL if this and Idx don't compose.
+    CodeGenSubRegIndex *compose(CodeGenSubRegIndex *Idx) const {
+      CompMap::const_iterator I =3D Composed.find(Idx);
+      return I =3D=3D Composed.end() ? 0 : I->second;
+    }
+
+    // Add a composite subreg index: this+A =3D B.
+    // Return a conflicting composite, or NULL
+    CodeGenSubRegIndex *addComposite(CodeGenSubRegIndex *A,
+                                     CodeGenSubRegIndex *B) {
+      std::pair<CompMap::iterator, bool> Ins =3D
+        Composed.insert(std::make_pair(A, B));
+      return (Ins.second || Ins.first->second =3D=3D B) ? 0 : Ins.first->s=
econd;
+    }
+
+    // Update the composite maps of components specified in 'ComposedOf'.
+    void updateComponents(CodeGenRegBank&);
+
+    // Clean out redundant composite mappings.
+    void cleanComposites();
+
+    // Return the map of composites.
+    const CompMap &getComposites() const { return Composed; }
+
+  private:
+    CompMap Composed;
+  };
+
   /// CodeGenRegister - Represents a register definition.
   struct CodeGenRegister {
     Record *TheDef;
     unsigned EnumValue;
     unsigned CostPerUse;
+    bool CoveredBySubRegs;
=20
     // Map SubRegIndex -> Register.
-    typedef std::map<Record*, CodeGenRegister*, LessRecord> SubRegMap;
+    typedef std::map<CodeGenSubRegIndex*, CodeGenRegister*,
+                     CodeGenSubRegIndex::Less> SubRegMap;
=20
     CodeGenRegister(Record *R, unsigned Enum);
=20
@@ -54,18 +110,37 @@
     }
=20
     // Add sub-registers to OSet following a pre-order defined by the .td =
file.
-    void addSubRegsPreOrder(SetVector<CodeGenRegister*> &OSet) const;
+    void addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
+                            CodeGenRegBank&) const;
=20
     // List of super-registers in topological order, small to large.
-    typedef std::vector<CodeGenRegister*> SuperRegList;
+    typedef std::vector<const CodeGenRegister*> SuperRegList;
=20
-    // Get the list of super-registers.
-    // This is only valid after computeDerivedInfo has visited all registe=
rs.
+    // Get the list of super-registers. This is valid after getSubReg
+    // visits all registers during RegBank construction.
     const SuperRegList &getSuperRegs() const {
       assert(SubRegsComplete && "Must precompute sub-registers");
       return SuperRegs;
     }
=20
+    // List of register units in ascending order.
+    typedef SmallVector<unsigned, 16> RegUnitList;
+
+    // Get the list of register units.
+    // This is only valid after getSubRegs() completes.
+    const RegUnitList &getRegUnits() const { return RegUnits; }
+
+    // Inherit register units from subregisters.
+    // Return true if the RegUnits changed.
+    bool inheritRegUnits(CodeGenRegBank &RegBank);
+
+    // Adopt a register unit for pressure tracking.
+    // A unit is adopted iff its unit number is >=3D NumNativeRegUnits.
+    void adoptRegUnit(unsigned RUID) { RegUnits.push_back(RUID); }
+
+    // Get the sum of this register's register unit weights.
+    unsigned getWeight(const CodeGenRegBank &RegBank) const;
+
     // Order CodeGenRegister pointers by EnumValue.
     struct Less {
       bool operator()(const CodeGenRegister *A,
@@ -82,6 +157,7 @@
     bool SubRegsComplete;
     SubRegMap SubRegs;
     SuperRegList SuperRegs;
+    RegUnitList RegUnits;
   };
=20
=20
@@ -101,8 +177,17 @@
     // super-class.
     void inheritProperties(CodeGenRegBank&);
=20
-    // Map SubRegIndex -> sub-class
-    DenseMap<Record*, CodeGenRegisterClass*> SubClassWithSubReg;
+    // Map SubRegIndex -> sub-class.  This is the largest sub-class where =
all
+    // registers have a SubRegIndex sub-register.
+    DenseMap<CodeGenSubRegIndex*, CodeGenRegisterClass*> SubClassWithSubRe=
g;
+
+    // Map SubRegIndex -> set of super-reg classes.  This is all register
+    // classes SuperRC such that:
+    //
+    //   R:SubRegIndex in this RC for all R in SuperRC.
+    //
+    DenseMap<CodeGenSubRegIndex*,
+             SmallPtrSet<CodeGenRegisterClass*, 8> > SuperRegClasses;
=20
   public:
     unsigned EnumValue;
@@ -128,8 +213,7 @@
     MVT::SimpleValueType getValueTypeNum(unsigned VTNum) const {
       if (VTNum < VTs.size())
         return VTs[VTNum];
-      assert(0 && "VTNum greater than number of ValueTypes in RegClass!");
-      abort();
+      llvm_unreachable("VTNum greater than number of ValueTypes in RegClas=
s!");
     }
=20
     // Return true if this this class contains the register.
@@ -150,14 +234,26 @@
=20
     // getSubClassWithSubReg - Returns the largest sub-class where all
     // registers have a SubIdx sub-register.
-    CodeGenRegisterClass *getSubClassWithSubReg(Record *SubIdx) const {
+    CodeGenRegisterClass*
+    getSubClassWithSubReg(CodeGenSubRegIndex *SubIdx) const {
       return SubClassWithSubReg.lookup(SubIdx);
     }
=20
-    void setSubClassWithSubReg(Record *SubIdx, CodeGenRegisterClass *SubRC=
) {
+    void setSubClassWithSubReg(CodeGenSubRegIndex *SubIdx,
+                               CodeGenRegisterClass *SubRC) {
       SubClassWithSubReg[SubIdx] =3D SubRC;
     }
=20
+    // getSuperRegClasses - Returns a bit vector of all register classes
+    // containing only SubIdx super-registers of this class.
+    void getSuperRegClasses(CodeGenSubRegIndex *SubIdx, BitVector &Out) co=
nst;
+
+    // addSuperRegClass - Add a class containing only SudIdx super-registe=
rs.
+    void addSuperRegClass(CodeGenSubRegIndex *SubIdx,
+                          CodeGenRegisterClass *SuperRC) {
+      SuperRegClasses[SubIdx].insert(SuperRC);
+    }
+
     // getSubClasses - Returns a constant BitVector of subclasses indexed =
by
     // EnumValue.
     // The SubClasses vector includs an entry for this class.
@@ -183,6 +279,9 @@
     // getOrder(0).
     const CodeGenRegister::Set &getMembers() const { return Members; }
=20
+    // Populate a unique sorted list of units from a register set.
+    void buildRegUnitSet(std::vector<unsigned> &RegUnits) const;
+
     CodeGenRegisterClass(CodeGenRegBank&, Record *R);
=20
     // A key representing the parts of a register class used for forming
@@ -217,16 +316,34 @@
     static void computeSubClasses(CodeGenRegBank&);
   };
=20
+  // Each RegUnitSet is a sorted vector with a name.
+  struct RegUnitSet {
+    typedef std::vector<unsigned>::const_iterator iterator;
+
+    std::string Name;
+    std::vector<unsigned> Units;
+  };
+
   // CodeGenRegBank - Represent a target's registers and the relations bet=
ween
   // them.
   class CodeGenRegBank {
     RecordKeeper &Records;
     SetTheory Sets;
=20
-    std::vector<Record*> SubRegIndices;
+    // SubRegIndices.
+    std::vector<CodeGenSubRegIndex*> SubRegIndices;
+    DenseMap<Record*, CodeGenSubRegIndex*> Def2SubRegIdx;
     unsigned NumNamedIndices;
+
+    // Registers.
     std::vector<CodeGenRegister*> Registers;
     DenseMap<Record*, CodeGenRegister*> Def2Reg;
+    unsigned NumNativeRegUnits;
+    unsigned NumRegUnits; // # native + adopted register units.
+
+    // Map each register unit to a weight (for register pressure).
+    // Includes native and adopted register units.
+    std::vector<unsigned> RegUnitWeights;
=20
     // Register classes.
     std::vector<CodeGenRegisterClass*> RegClasses;
@@ -234,16 +351,38 @@
     typedef std::map<CodeGenRegisterClass::Key, CodeGenRegisterClass*> RCK=
eyMap;
     RCKeyMap Key2RC;
=20
+    // Remember each unique set of register units. Initially, this contain=
s a
+    // unique set for each register class. Simliar sets are coalesced with
+    // pruneUnitSets and new supersets are inferred during computeRegUnitS=
ets.
+    std::vector<RegUnitSet> RegUnitSets;
+
+    // Map RegisterClass index to the index of the RegUnitSet that contain=
s the
+    // class's units and any inferred RegUnit supersets.
+    std::vector<std::vector<unsigned> > RegClassUnitSets;
+
     // Add RC to *2RC maps.
     void addToMaps(CodeGenRegisterClass*);
=20
+    // Create a synthetic sub-class if it is missing.
+    CodeGenRegisterClass *getOrCreateSubClass(const CodeGenRegisterClass *=
RC,
+                                              const CodeGenRegister::Set *=
Membs,
+                                              StringRef Name);
+
     // Infer missing register classes.
     void computeInferredRegisterClasses();
+    void inferCommonSubClass(CodeGenRegisterClass *RC);
+    void inferSubClassWithSubReg(CodeGenRegisterClass *RC);
+    void inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
+                                    unsigned FirstSubRegRC =3D 0);
=20
-    // Composite SubRegIndex instances.
-    // Map (SubRegIndex, SubRegIndex) -> SubRegIndex.
-    typedef DenseMap<std::pair<Record*, Record*>, Record*> CompositeMap;
-    CompositeMap Composite;
+    // Iteratively prune unit sets.
+    void pruneUnitSets();
+
+    // Compute a weight for each register unit created during getSubRegs.
+    void computeRegUnitWeights();
+
+    // Create a RegUnitSet for each RegClass and infer superclasses.
+    void computeRegUnitSets();
=20
     // Populate the Composite map from sub-register relationships.
     void computeComposites();
@@ -256,20 +395,44 @@
     // Sub-register indices. The first NumNamedIndices are defined by the =
user
     // in the .td files. The rest are synthesized such that all sub-regist=
ers
     // have a unique name.
-    const std::vector<Record*> &getSubRegIndices() { return SubRegIndices;=
 }
+    ArrayRef<CodeGenSubRegIndex*> getSubRegIndices() { return SubRegIndice=
s; }
     unsigned getNumNamedIndices() { return NumNamedIndices; }
=20
-    // Map a SubRegIndex Record to its enum value.
-    unsigned getSubRegIndexNo(Record *idx);
+    // Find a SubRegIndex form its Record def.
+    CodeGenSubRegIndex *getSubRegIdx(Record*);
=20
     // Find or create a sub-register index representing the A+B compositio=
n.
-    Record *getCompositeSubRegIndex(Record *A, Record *B, bool create =3D =
false);
+    CodeGenSubRegIndex *getCompositeSubRegIndex(CodeGenSubRegIndex *A,
+                                                CodeGenSubRegIndex *B);
=20
     const std::vector<CodeGenRegister*> &getRegisters() { return Registers=
; }
=20
     // Find a register from its Record def.
     CodeGenRegister *getReg(Record*);
=20
+    // Get a Register's index into the Registers array.
+    unsigned getRegIndex(const CodeGenRegister *Reg) const {
+      return Reg->EnumValue - 1;
+    }
+
+    // Create a new non-native register unit that can be adopted by a regi=
ster
+    // to increase its pressure. Note that NumNativeRegUnits is not increa=
sed.
+    unsigned newRegUnit(unsigned Weight) {
+      if (!RegUnitWeights.empty()) {
+        assert(Weight && "should only add allocatable units");
+        RegUnitWeights.resize(NumRegUnits+1);
+        RegUnitWeights[NumRegUnits] =3D Weight;
+      }
+      return NumRegUnits++;
+    }
+
+    // Native units are the singular unit of a leaf register. Register ali=
asing
+    // is completely characterized by native units. Adopted units exist to=
 give
+    // register additional weight but don't affect aliasing.
+    bool isNativeUnit(unsigned RUID) {
+      return RUID < NumNativeRegUnits;
+    }
+
     ArrayRef<CodeGenRegisterClass*> getRegClasses() const {
       return RegClasses;
     }
@@ -284,6 +447,41 @@
     /// return the superclass.  Otherwise return null.
     const CodeGenRegisterClass* getRegClassForRegister(Record *R);
=20
+    // Get a register unit's weight. Zero for unallocatable registers.
+    unsigned getRegUnitWeight(unsigned RUID) const {
+      return RegUnitWeights[RUID];
+    }
+
+    // Get the sum of unit weights.
+    unsigned getRegUnitSetWeight(const std::vector<unsigned> &Units) const=
 {
+      unsigned Weight =3D 0;
+      for (std::vector<unsigned>::const_iterator
+             I =3D Units.begin(), E =3D Units.end(); I !=3D E; ++I)
+        Weight +=3D getRegUnitWeight(*I);
+      return Weight;
+    }
+
+    // Increase a RegUnitWeight.
+    void increaseRegUnitWeight(unsigned RUID, unsigned Inc) {
+      RegUnitWeights[RUID] +=3D Inc;
+    }
+
+    // Get the number of register pressure dimensions.
+    unsigned getNumRegPressureSets() const { return RegUnitSets.size(); }
+
+    // Get a set of register unit IDs for a given dimension of pressure.
+    RegUnitSet getRegPressureSet(unsigned Idx) const {
+      return RegUnitSets[Idx];
+    }
+
+    // Get a list of pressure set IDs for a register class. Liveness of a
+    // register in this class impacts each pressure set in this list by the
+    // weight of the register. An exact solution requires all registers in=
 a
+    // class to have the same class, but it is not strictly guaranteed.
+    ArrayRef<unsigned> getRCPressureSetIDs(unsigned RCIdx) const {
+      return RegClassUnitSets[RCIdx];
+    }
+
     // Computed derived records such as missing sub-register indices.
     void computeDerivedInfo();
=20
@@ -295,6 +493,15 @@
     // If R1 is a sub-register of R2, Map[R1] is a subset of Map[R2].
     void computeOverlaps(std::map<const CodeGenRegister*,
                                   CodeGenRegister::Set> &Map);
+
+    // Compute the set of registers completely covered by the registers in=
 Regs.
+    // The returned BitVector will have a bit set for each register in Reg=
s,
+    // all sub-registers, and all super-registers that are covered by the
+    // registers in Regs.
+    //
+    // This is used to compute the mask of call-preserved registers from a=
 list
+    // of callee-saves.
+    BitVector computeCoveredRegisters(ArrayRef<Record*> Regs);
   };
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeG=
enTarget.cpp
--- a/head/contrib/llvm/utils/TableGen/CodeGenTarget.cpp	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeGenTarget.cpp	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -58,6 +58,7 @@
   case MVT::iAny:     return "MVT::iAny";
   case MVT::fAny:     return "MVT::fAny";
   case MVT::vAny:     return "MVT::vAny";
+  case MVT::f16:      return "MVT::f16";
   case MVT::f32:      return "MVT::f32";
   case MVT::f64:      return "MVT::f64";
   case MVT::f80:      return "MVT::f80";
@@ -82,6 +83,7 @@
   case MVT::v2i64:    return "MVT::v2i64";
   case MVT::v4i64:    return "MVT::v4i64";
   case MVT::v8i64:    return "MVT::v8i64";
+  case MVT::v2f16:    return "MVT::v2f16";
   case MVT::v2f32:    return "MVT::v2f32";
   case MVT::v4f32:    return "MVT::v4f32";
   case MVT::v8f32:    return "MVT::v8f32";
@@ -90,8 +92,8 @@
   case MVT::Metadata: return "MVT::Metadata";
   case MVT::iPTR:     return "MVT::iPTR";
   case MVT::iPTRAny:  return "MVT::iPTRAny";
-  case MVT::untyped:  return "MVT::untyped";
-  default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
+  case MVT::Untyped:  return "MVT::Untyped";
+  default: llvm_unreachable("ILLEGAL VALUE TYPE!");
   }
 }
=20
@@ -149,6 +151,26 @@
   return LI[AsmParserNum];
 }
=20
+/// getAsmParserVariant - Return the AssmblyParserVariant definition for
+/// this target.
+///
+Record *CodeGenTarget::getAsmParserVariant(unsigned i) const {
+  std::vector<Record*> LI =3D=20
+    TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
+  if (i >=3D LI.size())
+    throw "Target does not have an AsmParserVariant #" + utostr(i) + "!";
+  return LI[i];
+}
+
+/// getAsmParserVariantCount - Return the AssmblyParserVariant definition=20
+/// available for this target.
+///
+unsigned CodeGenTarget::getAsmParserVariantCount() const {
+  std::vector<Record*> LI =3D=20
+    TargetRec->getValueAsListOfDefs("AssemblyParserVariants");
+  return LI.size();
+}
+
 /// getAsmWriter - Return the AssemblyWriter definition for this target.
 ///
 Record *CodeGenTarget::getAsmWriter() const {
@@ -267,6 +289,7 @@
     "DBG_VALUE",
     "REG_SEQUENCE",
     "COPY",
+    "BUNDLE",
     0
   };
   const DenseMap<const Record*, CodeGenInstruction*> &Insts =3D getInstruc=
tions();
@@ -492,7 +515,7 @@
       unsigned ArgNo =3D Property->getValueAsInt("ArgNo");
       ArgumentAttributes.push_back(std::make_pair(ArgNo, NoCapture));
     } else
-      assert(0 && "Unknown property!");
+      llvm_unreachable("Unknown property!");
   }
=20
   // Sort the argument attributes for later benefit.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/CodeG=
enTarget.h
--- a/head/contrib/llvm/utils/TableGen/CodeGenTarget.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/CodeGenTarget.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -91,6 +91,16 @@
   ///
   Record *getAsmParser() const;
=20
+  /// getAsmParserVariant - Return the AssmblyParserVariant definition for
+  /// this target.
+  ///
+  Record *getAsmParserVariant(unsigned i) const;
+
+  /// getAsmParserVariantCount - Return the AssmblyParserVariant definitio=
n=20
+  /// available for this target.
+  ///
+  unsigned getAsmParserVariantCount() const;
+
   /// getAsmWriter - Return the AssemblyWriter definition for this target.
   ///
   Record *getAsmWriter() const;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/DAGIS=
elMatcher.cpp
--- a/head/contrib/llvm/utils/TableGen/DAGISelMatcher.cpp	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/DAGISelMatcher.cpp	Tue Apr 17 11:51:=
51 2012 +0300
@@ -15,6 +15,8 @@
 #include "llvm/ADT/StringExtras.h"
 using namespace llvm;
=20
+void Matcher::anchor() { }
+
 void Matcher::dump() const {
   print(errs(), 0);
 }
@@ -324,6 +326,10 @@
 }
=20
=20
+void EmitNodeMatcher::anchor() { }
+
+void MorphNodeToMatcher::anchor() { }
+
 unsigned MarkGlueResultsMatcher::getHashImpl() const {
   return HashUnsigneds(GlueResultNodes.begin(), GlueResultNodes.end());
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/DAGIS=
elMatcher.h
--- a/head/contrib/llvm/utils/TableGen/DAGISelMatcher.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/DAGISelMatcher.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -41,6 +41,7 @@
   // The next matcher node that is executed after this one.  Null if this =
is the
   // last stage of a match.
   OwningPtr<Matcher> Next;
+  virtual void anchor();
 public:
   enum KindTy {
     // Matcher state manipulation.
@@ -1011,6 +1012,7 @@
=20
 /// EmitNodeMatcher - This signals a successful match and generates a node.
 class EmitNodeMatcher : public EmitNodeMatcherCommon {
+  virtual void anchor();
   unsigned FirstResultSlot;
 public:
   EmitNodeMatcher(const std::string &opcodeName,
@@ -1033,6 +1035,7 @@
 };
=20
 class MorphNodeToMatcher : public EmitNodeMatcherCommon {
+  virtual void anchor();
   const PatternToMatch &Pattern;
 public:
   MorphNodeToMatcher(const std::string &opcodeName,
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/DAGIS=
elMatcherEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/DAGISelMatcherEmitter.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/DAGISelMatcherEmitter.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -573,8 +573,7 @@
     return 2 + NumResultBytes;
   }
   }
-  assert(0 && "Unreachable");
-  return 0;
+  llvm_unreachable("Unreachable");
 }
=20
 /// EmitMatcherList - Emit the bytes for the specified matcher subtree.
@@ -601,7 +600,7 @@
   if (!PatternPredicates.empty()) {
     OS << "bool CheckPatternPredicate(unsigned PredNo) const {\n";
     OS << "  switch (PredNo) {\n";
-    OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
+    OS << "  default: llvm_unreachable(\"Invalid predicate in table?\");\n=
";
     for (unsigned i =3D 0, e =3D PatternPredicates.size(); i !=3D e; ++i)
       OS << "  case " << i << ": return "  << PatternPredicates[i] << ";\n=
";
     OS << "  }\n";
@@ -619,7 +618,7 @@
   if (!NodePredicates.empty()) {
     OS << "bool CheckNodePredicate(SDNode *Node, unsigned PredNo) const {\=
n";
     OS << "  switch (PredNo) {\n";
-    OS << "  default: assert(0 && \"Invalid predicate in table?\");\n";
+    OS << "  default: llvm_unreachable(\"Invalid predicate in table?\");\n=
";
     for (unsigned i =3D 0, e =3D NodePredicates.size(); i !=3D e; ++i) {
       // Emit the predicate code corresponding to this pattern.
       TreePredicateFn PredFn =3D NodePredicates[i];
@@ -641,7 +640,7 @@
     OS << "         SmallVectorImpl<std::pair<SDValue, SDNode*> > &Result)=
 {\n";
     OS << "  unsigned NextRes =3D Result.size();\n";
     OS << "  switch (PatternNo) {\n";
-    OS << "  default: assert(0 && \"Invalid pattern # in table?\");\n";
+    OS << "  default: llvm_unreachable(\"Invalid pattern # in table?\");\n=
";
     for (unsigned i =3D 0, e =3D ComplexPatterns.size(); i !=3D e; ++i) {
       const ComplexPattern &P =3D *ComplexPatterns[i];
       unsigned NumOps =3D P.getNumOperands();
@@ -679,7 +678,7 @@
   if (!NodeXForms.empty()) {
     OS << "SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo) {\n";
     OS << "  switch (XFormNo) {\n";
-    OS << "  default: assert(0 && \"Invalid xform # in table?\");\n";
+    OS << "  default: llvm_unreachable(\"Invalid xform # in table?\");\n";
=20
     // FIXME: The node xform could take SDValue's instead of SDNode*'s.
     for (unsigned i =3D 0, e =3D NodeXForms.size(); i !=3D e; ++i) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/DAGIS=
elMatcherGen.cpp
--- a/head/contrib/llvm/utils/TableGen/DAGISelMatcherGen.cpp	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/DAGISelMatcherGen.cpp	Tue Apr 17 11:=
51:51 2012 +0300
@@ -217,7 +217,7 @@
=20
   DefInit *DI =3D dynamic_cast<DefInit*>(N->getLeafValue());
   if (DI =3D=3D 0) {
-    errs() << "Unknown leaf kind: " << *DI << "\n";
+    errs() << "Unknown leaf kind: " << *N << "\n";
     abort();
   }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Disas=
semblerEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/DisassemblerEmitter.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/DisassemblerEmitter.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -11,7 +11,6 @@
 #include "CodeGenTarget.h"
 #include "X86DisassemblerTables.h"
 #include "X86RecognizableInstr.h"
-#include "ARMDecoderEmitter.h"
 #include "FixedLenDecoderEmitter.h"
 #include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/EDEmi=
tter.cpp
--- a/head/contrib/llvm/utils/TableGen/EDEmitter.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/utils/TableGen/EDEmitter.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -287,6 +287,7 @@
   IMM("i64i8imm");
   IMM("i64i32imm");
   IMM("SSECC");
+  IMM("AVXCC");
=20
   // all R, I, R, I, R
   MEM("i8mem");
@@ -519,6 +520,8 @@
       // ignore (doesn't go anywhere we know about)
     } else if (name.find("VMCALL") !=3D name.npos) {
       // ignore (rather different semantics than a regular call)
+    } else if (name.find("VMMCALL") !=3D name.npos) {
+      // ignore (rather different semantics than a regular call)
     } else if (name.find("FAR") !=3D name.npos && name.find("i") !=3D name=
.npos) {
       CALL("off");
     } else {
@@ -567,12 +570,23 @@
   REG("DPR");
   REG("DPR_VFP2");
   REG("DPR_8");
+  REG("DPair");
   REG("SPR");
   REG("QPR");
   REG("QQPR");
   REG("QQQQPR");
+  REG("VecListOneD");
+  REG("VecListDPair");
+  REG("VecListDPairSpaced");
+  REG("VecListThreeD");
+  REG("VecListFourD");
+  REG("VecListOneDAllLanes");
+  REG("VecListDPairAllLanes");
+  REG("VecListDPairSpacedAllLanes");
=20
   IMM("i32imm");
+  IMM("fbits16");
+  IMM("fbits32");
   IMM("i32imm_hilo16");
   IMM("bf_inv_mask_imm");
   IMM("lsb_pos_imm");
@@ -597,6 +611,20 @@
   IMM("imm1_16");
   IMM("imm1_32");
   IMM("nModImm");
+  IMM("nImmSplatI8");
+  IMM("nImmSplatI16");
+  IMM("nImmSplatI32");
+  IMM("nImmSplatI64");
+  IMM("nImmVMOVI32");
+  IMM("nImmVMOVF32");
+  IMM("imm8");
+  IMM("imm16");
+  IMM("imm32");
+  IMM("imm1_7");
+  IMM("imm1_15");
+  IMM("imm1_31");
+  IMM("imm0_1");
+  IMM("imm0_3");
   IMM("imm0_7");
   IMM("imm0_15");
   IMM("imm0_255");
@@ -735,7 +763,7 @@
       errs() << "Operand type: " << rec.getName() << '\n';
       errs() << "Operand name: " << operandInfo.Name << '\n';
       errs() << "Instruction name: " << inst.TheDef->getName() << '\n';
-      llvm_unreachable("Unhandled type");
+      throw("Unhandled type in EDEmitter");
     }
   }
 }
@@ -956,11 +984,7 @@
=20
   emitCommonEnums(o, i);
=20
-  o << "namespace {\n";
-
-  o << "llvm::EDInstInfo instInfo" << target.getName().c_str() << "[] =3D =
";
+  o << "static const llvm::EDInstInfo instInfo" << target.getName() << "[]=
 =3D ";
   infoArray.emit(o, i);
   o << ";" << "\n";
-
-  o << "}\n";
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/FastI=
SelEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/FastISelEmitter.cpp	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/FastISelEmitter.cpp	Tue Apr 17 11:51=
:51 2012 +0300
@@ -21,7 +21,6 @@
 #include "llvm/TableGen/Error.h"
 #include "llvm/TableGen/Record.h"
 #include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/VectorExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/ErrorHandling.h"
 using namespace llvm;
@@ -280,7 +279,7 @@
       } else if (Operands[i].isImm()) {
         OS << "uint64_t imm" << i;
       } else if (Operands[i].isFP()) {
-        OS << "ConstantFP *f" << i;
+        OS << "const ConstantFP *f" << i;
       } else {
         llvm_unreachable("Unknown operand kind!");
       }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Fixed=
LenDecoderEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/FixedLenDecoderEmitter.cpp	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -17,6 +17,7 @@
 #include "FixedLenDecoderEmitter.h"
 #include "CodeGenTarget.h"
 #include "llvm/TableGen/Record.h"
+#include "llvm/ADT/APInt.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -48,7 +49,7 @@
 static int Value(bit_value_t V) {
   return ValueNotSet(V) ? -1 : (V =3D=3D BIT_FALSE ? 0 : 1);
 }
-static bit_value_t bitFromBits(BitsInit &bits, unsigned index) {
+static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
   if (BitInit *bit =3D dynamic_cast<BitInit*>(bits.getBit(index)))
     return bit->getValue() ? BIT_TRUE : BIT_FALSE;
=20
@@ -56,7 +57,7 @@
   return BIT_UNSET;
 }
 // Prints the bit value for each position.
-static void dumpBits(raw_ostream &o, BitsInit &bits) {
+static void dumpBits(raw_ostream &o, const BitsInit &bits) {
   unsigned index;
=20
   for (index =3D bits.getNumBits(); index > 0; index--) {
@@ -71,7 +72,7 @@
       o << "_";
       break;
     default:
-      assert(0 && "unexpected return value from bitFromBits");
+      llvm_unreachable("unexpected return value from bitFromBits");
     }
   }
 }
@@ -125,7 +126,7 @@
 /// version and return the Opcode since the two have the same Asm format s=
tring.
 class Filter {
 protected:
-  FilterChooser *Owner; // points to the FilterChooser who owns this filter
+  const FilterChooser *Owner;// points to the FilterChooser who owns this =
filter
   unsigned StartBit; // the starting bit position
   unsigned NumBits; // number of bits to filter
   bool Mixed; // a mixed region contains both set and unset bits
@@ -137,7 +138,7 @@
   std::vector<unsigned> VariableInstructions;
=20
   // Map of well-known segment value to its delegate.
-  std::map<unsigned, FilterChooser*> FilterChooserMap;
+  std::map<unsigned, const FilterChooser*> FilterChooserMap;
=20
   // Number of instructions which fall under FilteredInstructions category.
   unsigned NumFiltered;
@@ -145,19 +146,15 @@
   // Keeps track of the last opcode in the filtered bucket.
   unsigned LastOpcFiltered;
=20
-  // Number of instructions which fall under VariableInstructions category.
-  unsigned NumVariable;
-
 public:
-  unsigned getNumFiltered() { return NumFiltered; }
-  unsigned getNumVariable() { return NumVariable; }
-  unsigned getSingletonOpc() {
+  unsigned getNumFiltered() const { return NumFiltered; }
+  unsigned getSingletonOpc() const {
     assert(NumFiltered =3D=3D 1);
     return LastOpcFiltered;
   }
   // Return the filter chooser for the group of instructions without const=
ant
   // segment values.
-  FilterChooser &getVariableFC() {
+  const FilterChooser &getVariableFC() const {
     assert(NumFiltered =3D=3D 1);
     assert(FilterChooserMap.size() =3D=3D 1);
     return *(FilterChooserMap.find((unsigned)-1)->second);
@@ -177,7 +174,7 @@
   void recurse();
=20
   // Emit code to decode instructions given a segment or segments of bits.
-  void emit(raw_ostream &o, unsigned &Indentation);
+  void emit(raw_ostream &o, unsigned &Indentation) const;
=20
   // Returns the number of fanout produced by the filter.  More fanout imp=
lies
   // the filter distinguishes more categories of instructions.
@@ -217,10 +214,10 @@
   const std::vector<const CodeGenInstruction*> &AllInstructions;
=20
   // Vector of uid's for this filter chooser to work on.
-  const std::vector<unsigned> Opcodes;
+  const std::vector<unsigned> &Opcodes;
=20
   // Lookup table for the operand decoding of instructions.
-  std::map<unsigned, std::vector<OperandInfo> > &Operands;
+  const std::map<unsigned, std::vector<OperandInfo> > &Operands;
=20
   // Vector of candidate filters.
   std::vector<Filter> Filters;
@@ -230,7 +227,7 @@
   std::vector<bit_value_t> FilterBitValues;
=20
   // Links to the FilterChooser above us in the decoding tree.
-  FilterChooser *Parent;
+  const FilterChooser *Parent;
=20
   // Index of the best filter from Filters.
   int BestIndex;
@@ -242,19 +239,19 @@
   const FixedLenDecoderEmitter *Emitter;
=20
 public:
-  FilterChooser(const FilterChooser &FC) :
-    AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
+  FilterChooser(const FilterChooser &FC)
+    : AllInstructions(FC.AllInstructions), Opcodes(FC.Opcodes),
       Operands(FC.Operands), Filters(FC.Filters),
       FilterBitValues(FC.FilterBitValues), Parent(FC.Parent),
-    BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
-    Emitter(FC.Emitter) { }
+      BestIndex(FC.BestIndex), BitWidth(FC.BitWidth),
+      Emitter(FC.Emitter) { }
=20
   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
                 const std::vector<unsigned> &IDs,
-    std::map<unsigned, std::vector<OperandInfo> > &Ops,
+                const std::map<unsigned, std::vector<OperandInfo> > &Ops,
                 unsigned BW,
-                const FixedLenDecoderEmitter *E) :
-      AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
+                const FixedLenDecoderEmitter *E)
+    : AllInstructions(Insts), Opcodes(IDs), Operands(Ops), Filters(),
       Parent(NULL), BestIndex(-1), BitWidth(BW), Emitter(E) {
     for (unsigned i =3D 0; i < BitWidth; ++i)
       FilterBitValues.push_back(BIT_UNFILTERED);
@@ -264,10 +261,10 @@
=20
   FilterChooser(const std::vector<const CodeGenInstruction*> &Insts,
                 const std::vector<unsigned> &IDs,
-        std::map<unsigned, std::vector<OperandInfo> > &Ops,
-                std::vector<bit_value_t> &ParentFilterBitValues,
-                FilterChooser &parent) :
-      AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
+                const std::map<unsigned, std::vector<OperandInfo> > &Ops,
+                const std::vector<bit_value_t> &ParentFilterBitValues,
+                const FilterChooser &parent)
+    : AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
       Filters(), FilterBitValues(ParentFilterBitValues),
       Parent(&parent), BestIndex(-1), BitWidth(parent.BitWidth),
       Emitter(parent.Emitter) {
@@ -275,18 +272,31 @@
   }
=20
   // The top level filter chooser has NULL as its parent.
-  bool isTopLevel() { return Parent =3D=3D NULL; }
+  bool isTopLevel() const { return Parent =3D=3D NULL; }
=20
   // Emit the top level typedef and decodeInstruction() function.
-  void emitTop(raw_ostream &o, unsigned Indentation, std::string Namespace=
);
+  void emitTop(raw_ostream &o, unsigned Indentation,
+               const std::string &Namespace) const;
=20
 protected:
   // Populates the insn given the uid.
   void insnWithID(insn_t &Insn, unsigned Opcode) const {
     BitsInit &Bits =3D getBitsField(*AllInstructions[Opcode]->TheDef, "Ins=
t");
=20
-    for (unsigned i =3D 0; i < BitWidth; ++i)
-      Insn.push_back(bitFromBits(Bits, i));
+    // We may have a SoftFail bitmask, which specifies a mask where an enc=
oding
+    // may differ from the value in "Inst" and yet still be valid, but the
+    // disassembler should return SoftFail instead of Success.
+    //
+    // This is used for marking UNPREDICTABLE instructions in the ARM worl=
d.
+    BitsInit *SFBits =3D
+      AllInstructions[Opcode]->TheDef->getValueAsBitsInit("SoftFail");
+
+    for (unsigned i =3D 0; i < BitWidth; ++i) {
+      if (SFBits && bitFromBits(*SFBits, i) =3D=3D BIT_TRUE)
+        Insn.push_back(BIT_UNSET);
+      else
+        Insn.push_back(bitFromBits(Bits, i));
+    }
   }
=20
   // Returns the record name.
@@ -300,15 +310,16 @@
   // Returns false if there exists any uninitialized bit value in the rang=
e.
   // Returns true, otherwise.
   bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
-      unsigned NumBits) const;
+                     unsigned NumBits) const;
=20
   /// dumpFilterArray - dumpFilterArray prints out debugging info for the =
given
   /// filter array as a series of chars.
-  void dumpFilterArray(raw_ostream &o, std::vector<bit_value_t> & filter);
+  void dumpFilterArray(raw_ostream &o,
+                       const std::vector<bit_value_t> & filter) const;
=20
   /// dumpStack - dumpStack traverses the filter chooser chain and calls
   /// dumpFilterArray on each filter chooser up to the top level one.
-  void dumpStack(raw_ostream &o, const char *prefix);
+  void dumpStack(raw_ostream &o, const char *prefix) const;
=20
   Filter &bestFilter() {
     assert(BestIndex !=3D -1 && "BestIndex not set");
@@ -316,9 +327,9 @@
   }
=20
   // Called from Filter::recurse() when singleton exists.  For debug purpo=
se.
-  void SingletonExists(unsigned Opc);
+  void SingletonExists(unsigned Opc) const;
=20
-  bool PositionFiltered(unsigned i) {
+  bool PositionFiltered(unsigned i) const {
     return ValueSet(FilterBitValues[i]);
   }
=20
@@ -327,31 +338,37 @@
   // Inst{20} =3D 1 && Inst{3-0} =3D=3D 0b1111 represents two islands of y=
et-to-be
   // decoded bits in order to verify that the instruction matches the Opco=
de.
   unsigned getIslands(std::vector<unsigned> &StartBits,
-      std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
-      insn_t &Insn);
+                      std::vector<unsigned> &EndBits,
+                      std::vector<uint64_t> &FieldVals,
+                      const insn_t &Insn) const;
=20
   // Emits code to check the Predicates member of an instruction are true.
   // Returns true if predicate matches were emitted, false otherwise.
-  bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,unsigned O=
pc);
+  bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
+                          unsigned Opc) const;
+
+  void emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
+                         unsigned Opc) const;
=20
   // Emits code to decode the singleton.  Return true if we have matched a=
ll the
   // well-known bits.
-  bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,unsigned=
 Opc);
+  bool emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
+                            unsigned Opc) const;
=20
   // Emits code to decode the singleton, and then to decode the rest.
-  void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,Filter &=
Best);
+  void emitSingletonDecoder(raw_ostream &o, unsigned &Indentation,
+                            const Filter &Best) const;
=20
   void emitBinaryParser(raw_ostream &o , unsigned &Indentation,
-                        OperandInfo &OpInfo);
+                        const OperandInfo &OpInfo) const;
=20
   // Assign a single filter and run with it.
-  void runSingleFilter(FilterChooser &owner, unsigned startBit, unsigned n=
umBit,
-      bool mixed);
+  void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
=20
   // reportRegion is a helper function for filterProcessor to mark a regio=
n as
   // eligible for use as a filter region.
   void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
-      bool AllowMixed);
+                    bool AllowMixed);
=20
   // FilterProcessor scans the well-known encoding bits of the instruction=
s and
   // builds up a list of candidate filters.  It chooses the best filter and
@@ -366,31 +383,30 @@
   // Emits code to decode our share of instructions.  Returns true if the
   // emitted code causes a return, which occurs if we know how to decode
   // the instruction at this level or the instruction is not decodeable.
-  bool emit(raw_ostream &o, unsigned &Indentation);
+  bool emit(raw_ostream &o, unsigned &Indentation) const;
 };
=20
 ///////////////////////////
 //                       //
-// Filter Implmenetation //
+// Filter Implementation //
 //                       //
 ///////////////////////////
=20
-Filter::Filter(const Filter &f) :
-  Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
-  FilteredInstructions(f.FilteredInstructions),
-  VariableInstructions(f.VariableInstructions),
-  FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
-  LastOpcFiltered(f.LastOpcFiltered), NumVariable(f.NumVariable) {
+Filter::Filter(const Filter &f)
+  : Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixe=
d),
+    FilteredInstructions(f.FilteredInstructions),
+    VariableInstructions(f.VariableInstructions),
+    FilterChooserMap(f.FilterChooserMap), NumFiltered(f.NumFiltered),
+    LastOpcFiltered(f.LastOpcFiltered) {
 }
=20
 Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
-    bool mixed) : Owner(&owner), StartBit(startBit), NumBits(numBits),
-                  Mixed(mixed) {
+               bool mixed)
+  : Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
   assert(StartBit + NumBits - 1 < Owner->BitWidth);
=20
   NumFiltered =3D 0;
   LastOpcFiltered =3D 0;
-  NumVariable =3D 0;
=20
   for (unsigned i =3D 0, e =3D Owner->Opcodes.size(); i !=3D e; ++i) {
     insn_t Insn;
@@ -409,10 +425,9 @@
       FilteredInstructions[Field].push_back(LastOpcFiltered);
       ++NumFiltered;
     } else {
-      // Some of the encoding bit(s) are unspecfied.  This contributes to
+      // Some of the encoding bit(s) are unspecified.  This contributes to
       // one additional member of "Variable" instructions.
       VariableInstructions.push_back(Owner->Opcodes[i]);
-      ++NumVariable;
     }
   }
=20
@@ -421,7 +436,7 @@
 }
=20
 Filter::~Filter() {
-  std::map<unsigned, FilterChooser*>::iterator filterIterator;
+  std::map<unsigned, const FilterChooser*>::iterator filterIterator;
   for (filterIterator =3D FilterChooserMap.begin();
        filterIterator !=3D FilterChooserMap.end();
        filterIterator++) {
@@ -450,7 +465,7 @@
=20
     // Delegates to an inferior filter chooser for further processing on t=
his
     // group of instructions whose segment values are variable.
-    FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
+    FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
                               (unsigned)-1,
                               new FilterChooser(Owner->AllInstructions,
                                                 VariableInstructions,
@@ -483,7 +498,7 @@
=20
     // Delegates to an inferior filter chooser for further processing on t=
his
     // category of instructions.
-    FilterChooserMap.insert(std::pair<unsigned, FilterChooser*>(
+    FilterChooserMap.insert(std::pair<unsigned, const FilterChooser*>(
                               mapIterator->first,
                               new FilterChooser(Owner->AllInstructions,
                                                 mapIterator->second,
@@ -495,7 +510,7 @@
 }
=20
 // Emit code to decode instructions given a segment or segments of bits.
-void Filter::emit(raw_ostream &o, unsigned &Indentation) {
+void Filter::emit(raw_ostream &o, unsigned &Indentation) const {
   o.indent(Indentation) << "// Check Inst{";
=20
   if (NumBits > 1)
@@ -507,7 +522,7 @@
                         << "(insn, " << StartBit << ", "
                         << NumBits << ")) {\n";
=20
-  std::map<unsigned, FilterChooser*>::iterator filterIterator;
+  std::map<unsigned, const FilterChooser*>::const_iterator filterIterator;
=20
   bool DefaultCase =3D false;
   for (filterIterator =3D FilterChooserMap.begin();
@@ -537,12 +552,12 @@
     // encoding bits do not match exactly.
     if (!DefaultCase) { ++Indentation; ++Indentation; }
=20
-    bool finished =3D filterIterator->second->emit(o, Indentation);
+    filterIterator->second->emit(o, Indentation);
     // For top level default case, there's no need for a break statement.
     if (Owner->isTopLevel() && DefaultCase)
       break;
-    if (!finished)
-      o.indent(Indentation) << "break;\n";
+   =20
+    o.indent(Indentation) << "break;\n";
=20
     if (!DefaultCase) { --Indentation; --Indentation; }
   }
@@ -571,13 +586,17 @@
=20
 // Emit the top level typedef and decodeInstruction() function.
 void FilterChooser::emitTop(raw_ostream &o, unsigned Indentation,
-                            std::string Namespace) {
+                            const std::string &Namespace) const {
   o.indent(Indentation) <<
-    "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruct=
ion" << BitWidth
-    << "(MCInst &MI, uint" << BitWidth << "_t insn, uint64_t Address, "
+    "static MCDisassembler::DecodeStatus decode" << Namespace << "Instruct=
ion"
+    << BitWidth << "(MCInst &MI, uint" << BitWidth
+    << "_t insn, uint64_t Address, "
     << "const void *Decoder, const MCSubtargetInfo &STI) {\n";
-  o.indent(Indentation) << "  unsigned tmp =3D 0;\n  (void)tmp;\n" << Emit=
ter->Locals << "\n";
+  o.indent(Indentation) << "  unsigned tmp =3D 0;\n";
+  o.indent(Indentation) << "  (void)tmp;\n";
+  o.indent(Indentation) << Emitter->Locals << "\n";
   o.indent(Indentation) << "  uint64_t Bits =3D STI.getFeatureBits();\n";
+  o.indent(Indentation) << "  (void)Bits;\n";
=20
   ++Indentation; ++Indentation;
   // Emits code to decode the instructions.
@@ -598,7 +617,7 @@
 // Returns false if and on the first uninitialized bit value encountered.
 // Returns true, otherwise.
 bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
-    unsigned StartBit, unsigned NumBits) const {
+                                  unsigned StartBit, unsigned NumBits) con=
st {
   Field =3D 0;
=20
   for (unsigned i =3D 0; i < NumBits; ++i) {
@@ -615,7 +634,7 @@
 /// dumpFilterArray - dumpFilterArray prints out debugging info for the gi=
ven
 /// filter array as a series of chars.
 void FilterChooser::dumpFilterArray(raw_ostream &o,
-                                    std::vector<bit_value_t> &filter) {
+                                 const std::vector<bit_value_t> &filter) c=
onst {
   unsigned bitIndex;
=20
   for (bitIndex =3D BitWidth; bitIndex > 0; bitIndex--) {
@@ -638,8 +657,8 @@
=20
 /// dumpStack - dumpStack traverses the filter chooser chain and calls
 /// dumpFilterArray on each filter chooser up to the top level one.
-void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) {
-  FilterChooser *current =3D this;
+void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
+  const FilterChooser *current =3D this;
=20
   while (current) {
     o << prefix;
@@ -650,7 +669,7 @@
 }
=20
 // Called from Filter::recurse() when singleton exists.  For debug purpose.
-void FilterChooser::SingletonExists(unsigned Opc) {
+void FilterChooser::SingletonExists(unsigned Opc) const {
   insn_t Insn0;
   insnWithID(Insn0, Opc);
=20
@@ -663,7 +682,7 @@
   errs() << '\n';
=20
   dumpStack(errs(), "\t\t");
-  for (unsigned i =3D 0; i < Opcodes.size(); i++) {
+  for (unsigned i =3D 0; i < Opcodes.size(); ++i) {
     const std::string &Name =3D nameWithID(Opcodes[i]);
=20
     errs() << '\t' << Name << " ";
@@ -678,8 +697,9 @@
 // Inst{20} =3D 1 && Inst{3-0} =3D=3D 0b1111 represents two islands of yet=
-to-be
 // decoded bits in order to verify that the instruction matches the Opcode.
 unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
-    std::vector<unsigned> &EndBits, std::vector<uint64_t> &FieldVals,
-    insn_t &Insn) {
+                                   std::vector<unsigned> &EndBits,
+                                   std::vector<uint64_t> &FieldVals,
+                                   const insn_t &Insn) const {
   unsigned Num, BitNo;
   Num =3D BitNo =3D 0;
=20
@@ -695,9 +715,7 @@
     Val =3D Value(Insn[i]);
     bool Filtered =3D PositionFiltered(i);
     switch (State) {
-    default:
-      assert(0 && "Unreachable code!");
-      break;
+    default: llvm_unreachable("Unreachable code!");
     case 0:
     case 1:
       if (Filtered || Val =3D=3D -1)
@@ -736,17 +754,17 @@
 }
=20
 void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
-                         OperandInfo &OpInfo) {
-  std::string &Decoder =3D OpInfo.Decoder;
+                                     const OperandInfo &OpInfo) const {
+  const std::string &Decoder =3D OpInfo.Decoder;
=20
   if (OpInfo.numFields() =3D=3D 1) {
-    OperandInfo::iterator OI =3D OpInfo.begin();
+    OperandInfo::const_iterator OI =3D OpInfo.begin();
     o.indent(Indentation) << "  tmp =3D fieldFromInstruction" << BitWidth
                             << "(insn, " << OI->Base << ", " << OI->Width
                             << ");\n";
   } else {
     o.indent(Indentation) << "  tmp =3D 0;\n";
-    for (OperandInfo::iterator OI =3D OpInfo.begin(), OE =3D OpInfo.end();
+    for (OperandInfo::const_iterator OI =3D OpInfo.begin(), OE =3D OpInfo.=
end();
          OI !=3D OE; ++OI) {
       o.indent(Indentation) << "  tmp |=3D (fieldFromInstruction" << BitWi=
dth
                             << "(insn, " << OI->Base << ", " << OI->Width
@@ -756,14 +774,15 @@
=20
   if (Decoder !=3D "")
     o.indent(Indentation) << "  " << Emitter->GuardPrefix << Decoder
-                          << "(MI, tmp, Address, Decoder)" << Emitter->Gua=
rdPostfix << "\n";
+                          << "(MI, tmp, Address, Decoder)"
+                          << Emitter->GuardPostfix << "\n";
   else
     o.indent(Indentation) << "  MI.addOperand(MCOperand::CreateImm(tmp));\=
n";
=20
 }
=20
 static void emitSinglePredicateMatch(raw_ostream &o, StringRef str,
-                                     std::string PredicateNamespace) {
+                                     const std::string &PredicateNamespace=
) {
   if (str[0] =3D=3D '!')
     o << "!(Bits & " << PredicateNamespace << "::"
       << str.slice(1,str.size()) << ")";
@@ -772,8 +791,9 @@
 }
=20
 bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentati=
on,
-                                           unsigned Opc) {
-  ListInit *Predicates =3D AllInstructions[Opc]->TheDef->getValueAsListIni=
t("Predicates");
+                                       unsigned Opc) const {
+  ListInit *Predicates =3D
+    AllInstructions[Opc]->TheDef->getValueAsListInit("Predicates");
   for (unsigned i =3D 0; i < Predicates->getSize(); ++i) {
     Record *Pred =3D Predicates->getElementAsRecord(i);
     if (!Pred->getValue("AssemblerMatcherPredicate"))
@@ -799,10 +819,70 @@
   return Predicates->getSize() > 0;
 }
=20
+void FilterChooser::emitSoftFailCheck(raw_ostream &o, unsigned Indentation,
+                                      unsigned Opc) const {
+  BitsInit *SFBits =3D
+    AllInstructions[Opc]->TheDef->getValueAsBitsInit("SoftFail");
+  if (!SFBits) return;
+  BitsInit *InstBits =3D AllInstructions[Opc]->TheDef->getValueAsBitsInit(=
"Inst");
+
+  APInt PositiveMask(BitWidth, 0ULL);
+  APInt NegativeMask(BitWidth, 0ULL);
+  for (unsigned i =3D 0; i < BitWidth; ++i) {
+    bit_value_t B =3D bitFromBits(*SFBits, i);
+    bit_value_t IB =3D bitFromBits(*InstBits, i);
+
+    if (B !=3D BIT_TRUE) continue;
+
+    switch (IB) {
+    case BIT_FALSE:
+      // The bit is meant to be false, so emit a check to see if it is tru=
e.
+      PositiveMask.setBit(i);
+      break;
+    case BIT_TRUE:
+      // The bit is meant to be true, so emit a check to see if it is fals=
e.
+      NegativeMask.setBit(i);
+      break;
+    default:
+      // The bit is not set; this must be an error!
+      StringRef Name =3D AllInstructions[Opc]->TheDef->getName();
+      errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
+             << Name
+             << " is set but Inst{" << i <<"} is unset!\n"
+             << "  - You can only mark a bit as SoftFail if it is fully de=
fined"
+             << " (1/0 - not '?') in Inst\n";
+      o << "#error SoftFail Conflict, " << Name << "::SoftFail{" << i=20
+        << "} set but Inst{" << i << "} undefined!\n";
+    }
+  }
+
+  bool NeedPositiveMask =3D PositiveMask.getBoolValue();
+  bool NeedNegativeMask =3D NegativeMask.getBoolValue();
+
+  if (!NeedPositiveMask && !NeedNegativeMask)
+    return;
+
+  std::string PositiveMaskStr =3D PositiveMask.toString(16, /*signed=3D*/f=
alse);
+  std::string NegativeMaskStr =3D NegativeMask.toString(16, /*signed=3D*/f=
alse);
+  StringRef BitExt =3D "";
+  if (BitWidth > 32)
+    BitExt =3D "ULL";
+
+  o.indent(Indentation) << "if (";
+  if (NeedPositiveMask)
+    o << "insn & 0x" << PositiveMaskStr << BitExt;
+  if (NeedPositiveMask && NeedNegativeMask)
+    o << " || ";
+  if (NeedNegativeMask)
+    o << "~insn & 0x" << NegativeMaskStr << BitExt;
+  o << ")\n";
+  o.indent(Indentation+2) << "S =3D MCDisassembler::SoftFail;\n";
+}
+
 // Emits code to decode the singleton.  Return true if we have matched all=
 the
 // well-known bits.
 bool FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indenta=
tion,
-                                         unsigned Opc) {
+                                         unsigned Opc) const {
   std::vector<unsigned> StartBits;
   std::vector<unsigned> EndBits;
   std::vector<uint64_t> FieldVals;
@@ -821,22 +901,26 @@
     if (!emitPredicateMatch(o, Indentation, Opc))
       o << "1";
     o << ") {\n";
+    emitSoftFailCheck(o, Indentation+2, Opc);
     o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
-    std::vector<OperandInfo>& InsnOperands =3D Operands[Opc];
-    for (std::vector<OperandInfo>::iterator
+    std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =
=3D
+      Operands.find(Opc);
+    const std::vector<OperandInfo>& InsnOperands =3D OpIter->second;
+    for (std::vector<OperandInfo>::const_iterator
          I =3D InsnOperands.begin(), E =3D InsnOperands.end(); I !=3D E; +=
+I) {
       // If a custom instruction decoder was specified, use that.
       if (I->numFields() =3D=3D 0 && I->Decoder.size()) {
         o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
-                              << "(MI, insn, Address, Decoder)" << Emitter=
->GuardPostfix << "\n";
+                              << "(MI, insn, Address, Decoder)"
+                              << Emitter->GuardPostfix << "\n";
         break;
       }
=20
       emitBinaryParser(o, Indentation, *I);
     }
=20
-    o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // " <=
< nameWithID(Opc)
-                          << '\n';
+    o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
+                          << nameWithID(Opc) << '\n';
     o.indent(Indentation) << "}\n"; // Closing predicate block.
     return true;
   }
@@ -870,21 +954,25 @@
     else
       o << ") {\n";
   }
+  emitSoftFailCheck(o, Indentation+2, Opc);
   o.indent(Indentation) << "  MI.setOpcode(" << Opc << ");\n";
-  std::vector<OperandInfo>& InsnOperands =3D Operands[Opc];
-  for (std::vector<OperandInfo>::iterator
+  std::map<unsigned, std::vector<OperandInfo> >::const_iterator OpIter =3D
+    Operands.find(Opc);
+  const std::vector<OperandInfo>& InsnOperands =3D OpIter->second;
+  for (std::vector<OperandInfo>::const_iterator
        I =3D InsnOperands.begin(), E =3D InsnOperands.end(); I !=3D E; ++I=
) {
     // If a custom instruction decoder was specified, use that.
     if (I->numFields() =3D=3D 0 && I->Decoder.size()) {
       o.indent(Indentation) << "  " << Emitter->GuardPrefix << I->Decoder
-                            << "(MI, insn, Address, Decoder)" << Emitter->=
GuardPostfix << "\n";
+                            << "(MI, insn, Address, Decoder)"
+                            << Emitter->GuardPostfix << "\n";
       break;
     }
=20
     emitBinaryParser(o, Indentation, *I);
   }
-  o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // " << =
nameWithID(Opc)
-                        << '\n';
+  o.indent(Indentation) << "  return " << Emitter->ReturnOK << "; // "
+                        << nameWithID(Opc) << '\n';
   o.indent(Indentation) << "}\n";
=20
   return false;
@@ -892,7 +980,7 @@
=20
 // Emits code to decode the singleton, and then to decode the rest.
 void FilterChooser::emitSingletonDecoder(raw_ostream &o, unsigned &Indenta=
tion,
-    Filter &Best) {
+                                         const Filter &Best) const {
=20
   unsigned Opc =3D Best.getSingletonOpc();
=20
@@ -908,8 +996,8 @@
=20
 // Assign a single filter and run with it.  Top level API client can initi=
alize
 // with a single filter to start the filtering process.
-void FilterChooser::runSingleFilter(FilterChooser &owner, unsigned startBi=
t,
-    unsigned numBit, bool mixed) {
+void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
+                                    bool mixed) {
   Filters.clear();
   Filter F(*this, startBit, numBit, true);
   Filters.push_back(F);
@@ -920,7 +1008,7 @@
 // reportRegion is a helper function for filterProcessor to mark a region =
as
 // eligible for use as a filter region.
 void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
-    unsigned BitIndex, bool AllowMixed) {
+                                 unsigned BitIndex, bool AllowMixed) {
   if (RA =3D=3D ATTR_MIXED && AllowMixed)
     Filters.push_back(Filter(*this, StartBit, BitIndex - StartBit, true));
   else if (RA =3D=3D ATTR_ALL_SET && !AllowMixed)
@@ -957,8 +1045,7 @@
       // Look for islands of undecoded bits of any instruction.
       if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
         // Found an instruction with island(s).  Now just assign a filter.
-        runSingleFilter(*this, StartBits[0], EndBits[0] - StartBits[0] + 1,
-                        true);
+        runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
         return true;
       }
     }
@@ -1066,7 +1153,7 @@
         RA =3D ATTR_MIXED;
         break;
       default:
-        assert(0 && "Unexpected bitAttr!");
+        llvm_unreachable("Unexpected bitAttr!");
       }
       break;
     case ATTR_ALL_SET:
@@ -1087,7 +1174,7 @@
         RA =3D ATTR_MIXED;
         break;
       default:
-        assert(0 && "Unexpected bitAttr!");
+        llvm_unreachable("Unexpected bitAttr!");
       }
       break;
     case ATTR_MIXED:
@@ -1109,13 +1196,13 @@
       case ATTR_MIXED:
         break;
       default:
-        assert(0 && "Unexpected bitAttr!");
+        llvm_unreachable("Unexpected bitAttr!");
       }
       break;
     case ATTR_ALL_UNSET:
-      assert(0 && "regionAttr state machine has no ATTR_UNSET state");
+      llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
     case ATTR_FILTERED:
-      assert(0 && "regionAttr state machine has no ATTR_FILTERED state");
+      llvm_unreachable("regionAttr state machine has no ATTR_FILTERED stat=
e");
     }
   }
=20
@@ -1189,7 +1276,7 @@
 // Emits code to decode our share of instructions.  Returns true if the
 // emitted code causes a return, which occurs if we know how to decode
 // the instruction at this level or the instruction is not decodeable.
-bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) {
+bool FilterChooser::emit(raw_ostream &o, unsigned &Indentation) const {
   if (Opcodes.size() =3D=3D 1)
     // There is only one instruction in the set, which is great!
     // Call emitSingletonDecoder() to see whether there are any remaining
@@ -1198,11 +1285,11 @@
=20
   // Choose the best filter to do the decodings!
   if (BestIndex !=3D -1) {
-    Filter &Best =3D bestFilter();
+    const Filter &Best =3D Filters[BestIndex];
     if (Best.getNumFiltered() =3D=3D 1)
       emitSingletonDecoder(o, Indentation, Best);
     else
-      bestFilter().emit(o, Indentation);
+      Best.emit(o, Indentation);
     return false;
   }
=20
@@ -1222,7 +1309,7 @@
=20
   dumpStack(errs(), "\t\t");
=20
-  for (unsigned i =3D 0; i < Opcodes.size(); i++) {
+  for (unsigned i =3D 0; i < Opcodes.size(); ++i) {
     const std::string &Name =3D nameWithID(Opcodes[i]);
=20
     errs() << '\t' << Name << " ";
@@ -1234,9 +1321,8 @@
   return true;
 }
=20
-static bool populateInstruction(const CodeGenInstruction &CGI,
-                                unsigned Opc,
-                      std::map<unsigned, std::vector<OperandInfo> >& Opera=
nds){
+static bool populateInstruction(const CodeGenInstruction &CGI, unsigned Op=
c,
+                       std::map<unsigned, std::vector<OperandInfo> > &Oper=
ands){
   const Record &Def =3D *CGI.TheDef;
   // If all the bit positions are not specified; do not decode this instru=
ction.
   // We are bound to fail!  For proper disassembly, the well-known encodin=
g bits
@@ -1290,7 +1376,7 @@
   }
=20
   // For each operand, see if we can figure out where it is encoded.
-  for (std::vector<std::pair<Init*, std::string> >::iterator
+  for (std::vector<std::pair<Init*, std::string> >::const_iterator
        NI =3D InOutOperands.begin(), NE =3D InOutOperands.end(); NI !=3D N=
E; ++NI) {
     std::string Decoder =3D "";
=20
@@ -1435,8 +1521,7 @@
 }
=20
 // Emits disassembler code for instruction decoding.
-void FixedLenDecoderEmitter::run(raw_ostream &o)
-{
+void FixedLenDecoderEmitter::run(raw_ostream &o) {
   o << "#include \"llvm/MC/MCInst.h\"\n";
   o << "#include \"llvm/Support/DataTypes.h\"\n";
   o << "#include <assert.h>\n";
@@ -1444,14 +1529,15 @@
   o << "namespace llvm {\n\n";
=20
   // Parameterize the decoders based on namespace and instruction width.
-  NumberedInstructions =3D Target.getInstructionsByEnumValue();
+  const std::vector<const CodeGenInstruction*> &NumberedInstructions =3D
+    Target.getInstructionsByEnumValue();
   std::map<std::pair<std::string, unsigned>,
            std::vector<unsigned> > OpcMap;
   std::map<unsigned, std::vector<OperandInfo> > Operands;
=20
   for (unsigned i =3D 0; i < NumberedInstructions.size(); ++i) {
     const CodeGenInstruction *Inst =3D NumberedInstructions[i];
-    Record *Def =3D Inst->TheDef;
+    const Record *Def =3D Inst->TheDef;
     unsigned Size =3D Def->getValueAsInt("Size");
     if (Def->getValueAsString("Namespace") =3D=3D "TargetOpcode" ||
         Def->getValueAsBit("isPseudo") ||
@@ -1470,7 +1556,7 @@
=20
   std::set<unsigned> Sizes;
   for (std::map<std::pair<std::string, unsigned>,
-                std::vector<unsigned> >::iterator
+                std::vector<unsigned> >::const_iterator
        I =3D OpcMap.begin(), E =3D OpcMap.end(); I !=3D E; ++I) {
     // If we haven't visited this instruction width before, emit the
     // helper method to extract fields.
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Fixed=
LenDecoderEmitter.h
--- a/head/contrib/llvm/utils/TableGen/FixedLenDecoderEmitter.h	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/FixedLenDecoderEmitter.h	Tue Apr 17 =
11:51:51 2012 +0300
@@ -39,12 +39,12 @@
     Fields.push_back(EncodingField(Base, Width, Offset));
   }
=20
-  unsigned numFields() { return Fields.size(); }
+  unsigned numFields() const { return Fields.size(); }
=20
-  typedef std::vector<EncodingField>::iterator iterator;
+  typedef std::vector<EncodingField>::const_iterator const_iterator;
=20
-  iterator begin() { return Fields.begin(); }
-  iterator end()   { return Fields.end();   }
+  const_iterator begin() const { return Fields.begin(); }
+  const_iterator end() const   { return Fields.end();   }
 };
=20
 class FixedLenDecoderEmitter : public TableGenBackend {
@@ -52,12 +52,12 @@
   FixedLenDecoderEmitter(RecordKeeper &R,
                          std::string PredicateNamespace,
                          std::string GPrefix  =3D "if (",
-                         std::string GPostfix =3D " =3D=3D MCDisassembler:=
:Fail) return MCDisassembler::Fail;",
+                         std::string GPostfix =3D " =3D=3D MCDisassembler:=
:Fail)"
+                         " return MCDisassembler::Fail;",
                          std::string ROK      =3D "MCDisassembler::Success=
",
                          std::string RFail    =3D "MCDisassembler::Fail",
                          std::string L        =3D "") :
-    Records(R), Target(R),
-    NumberedInstructions(Target.getInstructionsByEnumValue()),
+    Target(R),
     PredicateNamespace(PredicateNamespace),
     GuardPrefix(GPrefix), GuardPostfix(GPostfix),
     ReturnOK(ROK), ReturnFail(RFail), Locals(L) {}
@@ -66,11 +66,7 @@
   void run(raw_ostream &o);
=20
 private:
-  RecordKeeper &Records;
   CodeGenTarget Target;
-  std::vector<const CodeGenInstruction*> NumberedInstructions;
-  std::vector<unsigned> Opcodes;
-  std::map<unsigned, std::vector<OperandInfo> > Operands;
 public:
   std::string PredicateNamespace;
   std::string GuardPrefix, GuardPostfix;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Instr=
InfoEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/InstrInfoEmitter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/InstrInfoEmitter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -14,14 +14,16 @@
=20
 #include "InstrInfoEmitter.h"
 #include "CodeGenTarget.h"
+#include "SequenceToOffsetTable.h"
 #include "llvm/TableGen/Record.h"
 #include "llvm/ADT/StringExtras.h"
 #include <algorithm>
+#include <cstdio>
 using namespace llvm;
=20
 static void PrintDefList(const std::vector<Record*> &Uses,
                          unsigned Num, raw_ostream &OS) {
-  OS << "static const unsigned ImplicitList" << Num << "[] =3D { ";
+  OS << "static const uint16_t ImplicitList" << Num << "[] =3D { ";
   for (unsigned i =3D 0, e =3D Uses.size(); i !=3D e; ++i)
     OS << getQualifiedName(Uses[i]) << ", ";
   OS << "0 };\n";
@@ -106,6 +108,11 @@
       if (Inst.Operands[i].Rec->isSubClassOf("OptionalDefOperand"))
         Res +=3D "|(1<<MCOI::OptionalDef)";
=20
+      // Fill in operand type.
+      Res +=3D ", MCOI::";
+      assert(!Inst.Operands[i].OperandType.empty() && "Invalid operand typ=
e.");
+      Res +=3D Inst.Operands[i].OperandType;
+
       // Fill in constraint info.
       Res +=3D ", ";
=20
@@ -121,11 +128,6 @@
                     " << 16) | (1 << MCOI::TIED_TO))";
       }
=20
-      // Fill in operand type.
-      Res +=3D ", MCOI::";
-      assert(!Inst.Operands[i].OperandType.empty() && "Invalid operand typ=
e.");
-      Res +=3D Inst.Operands[i].OperandType;
-
       Result.push_back(Res);
     }
   }
@@ -203,7 +205,7 @@
=20
   // Emit all of the MCInstrDesc records in their ENUM ordering.
   //
-  OS << "\nMCInstrDesc " << TargetName << "Insts[] =3D {\n";
+  OS << "\nextern const MCInstrDesc " << TargetName << "Insts[] =3D {\n";
   const std::vector<const CodeGenInstruction*> &NumberedInstructions =3D
     Target.getInstructionsByEnumValue();
=20
@@ -212,10 +214,33 @@
                OperandInfoIDs, OS);
   OS << "};\n\n";
=20
+  // Build an array of instruction names
+  SequenceToOffsetTable<std::string> InstrNames;
+  for (unsigned i =3D 0, e =3D NumberedInstructions.size(); i !=3D e; ++i)=
 {
+    const CodeGenInstruction *Instr =3D NumberedInstructions[i];
+    InstrNames.add(Instr->TheDef->getName());
+  }
+
+  InstrNames.layout();
+  OS << "extern const char " << TargetName << "InstrNameData[] =3D {\n";
+  InstrNames.emit(OS, printChar);
+  OS << "};\n\n";
+
+  OS << "extern const unsigned " << TargetName <<"InstrNameIndices[] =3D {=
";
+  for (unsigned i =3D 0, e =3D NumberedInstructions.size(); i !=3D e; ++i)=
 {
+    if (i % 8 =3D=3D 0)
+      OS << "\n    ";
+    const CodeGenInstruction *Instr =3D NumberedInstructions[i];
+    OS << InstrNames.get(Instr->TheDef->getName()) << "U, ";
+  }
+
+  OS << "\n};\n\n";
+
   // MCInstrInfo initialization routine.
   OS << "static inline void Init" << TargetName
      << "MCInstrInfo(MCInstrInfo *II) {\n";
   OS << "  II->InitMCInstrInfo(" << TargetName << "Insts, "
+     << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData=
, "
      << NumberedInstructions.size() << ");\n}\n\n";
=20
   OS << "} // End llvm namespace \n";
@@ -239,10 +264,13 @@
   OS << "#undef GET_INSTRINFO_CTOR\n";
=20
   OS << "namespace llvm {\n";
-  OS << "extern MCInstrDesc " << TargetName << "Insts[];\n";
+  OS << "extern const MCInstrDesc " << TargetName << "Insts[];\n";
+  OS << "extern const unsigned " << TargetName << "InstrNameIndices[];\n";
+  OS << "extern const char " << TargetName << "InstrNameData[];\n";
   OS << ClassName << "::" << ClassName << "(int SO, int DO)\n"
      << "  : TargetInstrInfoImpl(SO, DO) {\n"
      << "  InitMCInstrInfo(" << TargetName << "Insts, "
+     << TargetName << "InstrNameIndices, " << TargetName << "InstrNameData=
, "
      << NumberedInstructions.size() << ");\n}\n";
   OS << "} // End llvm namespace \n";
=20
@@ -264,8 +292,7 @@
   OS << Num << ",\t" << MinOperands << ",\t"
      << Inst.Operands.NumDefs << ",\t"
      << getItinClassNumber(Inst.TheDef) << ",\t"
-     << Inst.TheDef->getValueAsInt("Size") << ",\t\""
-     << Inst.TheDef->getName() << "\", 0";
+     << Inst.TheDef->getValueAsInt("Size") << ",\t0";
=20
   // Emit all of the target indepedent flags...
   if (Inst.isPseudo)           OS << "|(1<<MCID::Pseudo)";
@@ -346,7 +373,7 @@
=20
   // We must emit the PHI opcode first...
   std::string Namespace =3D Target.getInstNamespace();
- =20
+
   if (Namespace.empty()) {
     fprintf(stderr, "No instructions defined!\n");
     exit(1);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Instr=
InfoEmitter.h
--- a/head/contrib/llvm/utils/TableGen/InstrInfoEmitter.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/InstrInfoEmitter.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -31,19 +31,19 @@
   RecordKeeper &Records;
   CodeGenDAGPatterns CDP;
   std::map<std::string, unsigned> ItinClassMap;
- =20
+
 public:
   InstrInfoEmitter(RecordKeeper &R) : Records(R), CDP(R) { }
=20
-  // run - Output the instruction set description, returning true on failu=
re.
+  // run - Output the instruction set description.
   void run(raw_ostream &OS);
=20
 private:
   void emitEnums(raw_ostream &OS);
=20
-  typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy; =20
+  typedef std::map<std::vector<std::string>, unsigned> OperandInfoMapTy;
   void emitRecord(const CodeGenInstruction &Inst, unsigned Num,
-                  Record *InstrInfo,=20
+                  Record *InstrInfo,
                   std::map<std::vector<Record*>, unsigned> &EL,
                   const OperandInfoMapTy &OpInfo,
                   raw_ostream &OS);
@@ -51,7 +51,7 @@
   // Itinerary information.
   void GatherItinClasses();
   unsigned getItinClassNumber(const Record *InstRec);
- =20
+
   // Operand information.
   void EmitOperandInfo(raw_ostream &OS, OperandInfoMapTy &OperandInfoIDs);
   std::vector<std::string> GetOperandInfo(const CodeGenInstruction &Inst);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Intri=
nsicEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/IntrinsicEmitter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/IntrinsicEmitter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -57,9 +57,6 @@
   // Emit intrinsic alias analysis mod/ref behavior.
   EmitModRefBehavior(Ints, OS);
=20
-  // Emit a list of intrinsics with corresponding GCC builtins.
-  EmitGCCBuiltinList(Ints, OS);
-
   // Emit code to translate GCC builtins into LLVM intrinsics.
   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
=20
@@ -160,17 +157,20 @@
 void IntrinsicEmitter::
 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,=20
                          raw_ostream &OS) {
-  OS << "// Intrinsic ID to overload table\n";
+  OS << "// Intrinsic ID to overload bitset\n";
   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
-  OS << "  // Note that entry #0 is the invalid intrinsic!\n";
+  OS << "static const uint8_t OTable[] =3D {\n";
+  OS << "  0";
   for (unsigned i =3D 0, e =3D Ints.size(); i !=3D e; ++i) {
-    OS << "  ";
+    // Add one to the index so we emit a null bit for the invalid #0 intri=
nsic.
+    if ((i+1)%8 =3D=3D 0)
+      OS << ",\n  0";
     if (Ints[i].isOverloaded)
-      OS << "true";
-    else
-      OS << "false";
-    OS << ",\n";
+      OS << " | (1<<" << (i+1)%8 << ')';
   }
+  OS << "\n};\n\n";
+  // OTable contains a true bit at the position if the intrinsic is overlo=
aded.
+  OS << "return (OTable[id/8] & (1 << (id%8))) !=3D 0;\n";
   OS << "#endif\n\n";
 }
=20
@@ -181,6 +181,8 @@
   } else if (VT =3D=3D MVT::Other) {
     // MVT::OtherVT is used to mean the empty struct type here.
     OS << "StructType::get(Context)";
+  } else if (VT =3D=3D MVT::f16) {
+    OS << "Type::getHalfTy(Context)";
   } else if (VT =3D=3D MVT::f32) {
     OS << "Type::getFloatTy(Context)";
   } else if (VT =3D=3D MVT::f64) {
@@ -318,7 +320,7 @@
   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
   OS << "  switch (ID) {\n";
-  OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
+  OS << "  default: llvm_unreachable(\"Invalid intrinsic!\");\n";
  =20
   // This checking can emit a lot of very common code.  To reduce the amou=
nt of
   // code that we emit, batch up cases that have identical types.  This av=
oids
@@ -414,7 +416,7 @@
   OS << "// Code for generating Intrinsic function declarations.\n";
   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
   OS << "  switch (id) {\n";
-  OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
+  OS << "  default: llvm_unreachable(\"Invalid intrinsic!\");\n";
  =20
   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
   // types.
@@ -483,8 +485,7 @@
     case CodeGenIntrinsic::ReadWriteMem:
       return MRK_none;
     }
-    assert(0 && "bad mod-ref kind");
-    return MRK_none;
+    llvm_unreachable("bad mod-ref kind");
   }
=20
   struct AttributeComparator {
@@ -516,37 +517,50 @@
   else
     OS << "AttrListPtr Intrinsic::getAttributes(ID id) {\n";
=20
-  // Compute the maximum number of attribute arguments.
-  std::vector<const CodeGenIntrinsic*> sortedIntrinsics(Ints.size());
+  // Compute the maximum number of attribute arguments and the map
+  typedef std::map<const CodeGenIntrinsic*, unsigned,
+                   AttributeComparator> UniqAttrMapTy;
+  UniqAttrMapTy UniqAttributes;
   unsigned maxArgAttrs =3D 0;
+  unsigned AttrNum =3D 0;
   for (unsigned i =3D 0, e =3D Ints.size(); i !=3D e; ++i) {
     const CodeGenIntrinsic &intrinsic =3D Ints[i];
-    sortedIntrinsics[i] =3D &intrinsic;
     maxArgAttrs =3D
       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
+    unsigned &N =3D UniqAttributes[&intrinsic];
+    if (N) continue;
+    assert(AttrNum < 256 && "Too many unique attributes for table!");
+    N =3D ++AttrNum;
   }
=20
   // Emit an array of AttributeWithIndex.  Most intrinsics will have
   // at least one entry, for the function itself (index ~1), which is
   // usually nounwind.
+  OS << "  static const uint8_t IntrinsicsToAttributesMap[] =3D {\n";
+
+  for (unsigned i =3D 0, e =3D Ints.size(); i !=3D e; ++i) {
+    const CodeGenIntrinsic &intrinsic =3D Ints[i];
+
+    OS << "    " << UniqAttributes[&intrinsic] << ", // "
+       << intrinsic.Name << "\n";
+  }
+  OS << "  };\n\n";
+
   OS << "  AttributeWithIndex AWI[" << maxArgAttrs+1 << "];\n";
   OS << "  unsigned NumAttrs =3D 0;\n";
-  OS << "  switch (id) {\n";
-  OS << "    default: break;\n";
+  OS << "  if (id !=3D 0) {\n";
+  OS << "    switch(IntrinsicsToAttributesMap[id - ";
+  if (TargetOnly)
+    OS << "Intrinsic::num_intrinsics";
+  else
+    OS << "1";
+  OS << "]) {\n";
+  OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
+  for (UniqAttrMapTy::const_iterator I =3D UniqAttributes.begin(),
+       E =3D UniqAttributes.end(); I !=3D E; ++I) {
+    OS << "    case " << I->second << ":\n";
=20
-  AttributeComparator precedes;
-
-  std::stable_sort(sortedIntrinsics.begin(), sortedIntrinsics.end(), prece=
des);
-
-  for (unsigned i =3D 0, e =3D sortedIntrinsics.size(); i !=3D e; ++i) {
-    const CodeGenIntrinsic &intrinsic =3D *sortedIntrinsics[i];
-    OS << "  case " << TargetPrefix << "Intrinsic::"
-       << intrinsic.EnumName << ":\n";
-
-    // Fill out the case if this is the last case for this range of
-    // intrinsics.
-    if (i + 1 !=3D e && !precedes(&intrinsic, sortedIntrinsics[i + 1]))
-      continue;
+    const CodeGenIntrinsic &intrinsic =3D *(I->first);
=20
     // Keep track of the number of attributes we're writing out.
     unsigned numAttrs =3D 0;
@@ -554,8 +568,8 @@
     // The argument attributes are alreadys sorted by argument index.
     for (unsigned ai =3D 0, ae =3D intrinsic.ArgumentAttributes.size(); ai=
 !=3D ae;) {
       unsigned argNo =3D intrinsic.ArgumentAttributes[ai].first;
-     =20
-      OS << "    AWI[" << numAttrs++ << "] =3D AttributeWithIndex::get("
+
+      OS << "      AWI[" << numAttrs++ << "] =3D AttributeWithIndex::get("
          << argNo+1 << ", ";
=20
       bool moreThanOne =3D false;
@@ -579,7 +593,7 @@
     ModRefKind modRef =3D getModRefKind(intrinsic);
=20
     if (!intrinsic.canThrow || modRef) {
-      OS << "    AWI[" << numAttrs++ << "] =3D AttributeWithIndex::get(~0,=
 ";
+      OS << "      AWI[" << numAttrs++ << "] =3D AttributeWithIndex::get(~=
0, ";
       if (!intrinsic.canThrow) {
         OS << "Attribute::NoUnwind";
         if (modRef) OS << '|';
@@ -593,13 +607,14 @@
     }
=20
     if (numAttrs) {
-      OS << "    NumAttrs =3D " << numAttrs << ";\n";
-      OS << "    break;\n";
+      OS << "      NumAttrs =3D " << numAttrs << ";\n";
+      OS << "      break;\n";
     } else {
-      OS << "    return AttrListPtr();\n";
+      OS << "      return AttrListPtr();\n";
     }
   }
  =20
+  OS << "    }\n";
   OS << "  }\n";
   OS << "  return AttrListPtr::get(AWI, NumAttrs);\n";
   OS << "}\n";
@@ -609,50 +624,36 @@
 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavi=
or.
 void IntrinsicEmitter::
 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream =
&OS){
-  OS << "// Determine intrinsic alias analysis mod/ref behavior.\n";
-  OS << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n";
-  OS << "switch (iid) {\n";
-  OS << "default:\n    return UnknownModRefBehavior;\n";
+  OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
+     << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
+     << "assert(iid <=3D Intrinsic::" << Ints.back().EnumName << " && "
+     << "\"Unknown intrinsic.\");\n\n";
+
+  OS << "static const uint8_t IntrinsicModRefBehavior[] =3D {\n"
+     << "  /* invalid */ UnknownModRefBehavior,\n";
   for (unsigned i =3D 0, e =3D Ints.size(); i !=3D e; ++i) {
-    if (Ints[i].ModRef =3D=3D CodeGenIntrinsic::ReadWriteMem)
-      continue;
-    OS << "case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName
-      << ":\n";
+    OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
     switch (Ints[i].ModRef) {
-    default:
-      assert(false && "Unknown Mod/Ref type!");
     case CodeGenIntrinsic::NoMem:
-      OS << "  return DoesNotAccessMemory;\n";
+      OS << "DoesNotAccessMemory,\n";
       break;
     case CodeGenIntrinsic::ReadArgMem:
-      OS << "  return OnlyReadsArgumentPointees;\n";
+      OS << "OnlyReadsArgumentPointees,\n";
       break;
     case CodeGenIntrinsic::ReadMem:
-      OS << "  return OnlyReadsMemory;\n";
+      OS << "OnlyReadsMemory,\n";
       break;
     case CodeGenIntrinsic::ReadWriteArgMem:
-      OS << "  return OnlyAccessesArgumentPointees;\n";
+      OS << "OnlyAccessesArgumentPointees,\n";
+      break;
+    case CodeGenIntrinsic::ReadWriteMem:
+      OS << "UnknownModRefBehavior,\n";
       break;
     }
   }
-  OS << "}\n";
-  OS << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
-}
-
-void IntrinsicEmitter::
-EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream =
&OS){
-  OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
-  OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
-  OS << "  switch (F->getIntrinsicID()) {\n";
-  OS << "  default: BuiltinName =3D \"\"; break;\n";
-  for (unsigned i =3D 0, e =3D Ints.size(); i !=3D e; ++i) {
-    if (!Ints[i].GCCBuiltinName.empty()) {
-      OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName =3D=
 \""
-         << Ints[i].GCCBuiltinName << "\"; break;\n";
-    }
-  }
-  OS << "  }\n";
-  OS << "#endif\n\n";
+  OS << "};\n\n"
+     << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);=
\n"
+     << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
 }
=20
 /// EmitTargetBuiltins - All of the builtins in the specified map are for =
the
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Intri=
nsicEmitter.h
--- a/head/contrib/llvm/utils/TableGen/IntrinsicEmitter.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/IntrinsicEmitter.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -48,8 +48,6 @@
                         raw_ostream &OS);
     void EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints,
                             raw_ostream &OS);
-    void EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints,=20
-                            raw_ostream &OS);
     void EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> =
&Ints,=20
                                       raw_ostream &OS);
     void EmitSuffix(raw_ostream &OS);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Pseud=
oLoweringEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/PseudoLoweringEmitter.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/PseudoLoweringEmitter.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -67,7 +67,7 @@
       // Since we added more than one, we also need to adjust the base.
       BaseIdx +=3D NewOps - 1;
     } else
-      assert(0 && "Unhandled pseudo-expansion argument type!");
+      llvm_unreachable("Unhandled pseudo-expansion argument type!");
   }
   return OpsAdded;
 }
@@ -100,8 +100,11 @@
     throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() +
                                  "' operand count mismatch");
=20
+  unsigned NumMIOperands =3D 0;
+  for (unsigned i =3D 0, e =3D Insn.Operands.size(); i !=3D e; ++i)
+    NumMIOperands +=3D Insn.Operands[i].MINumOperands;
   IndexedMap<OpData> OperandMap;
-  OperandMap.grow(Insn.Operands.size());
+  OperandMap.grow(NumMIOperands);
=20
   addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0);
=20
@@ -176,8 +179,6 @@
       for (unsigned i =3D 0, e =3D Dest.Operands[OpNo].MINumOperands;
            i !=3D e; ++i) {
         switch (Expansion.OperandMap[MIOpNo + i].Kind) {
-        default:
-          llvm_unreachable("Unknown operand type?!");
         case OpData::Operand:
           o << "      lowerOperand(MI->getOperand("
             << Source.Operands[Expansion.OperandMap[MIOpNo].Data
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Regis=
terInfoEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/RegisterInfoEmitter.cpp	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/RegisterInfoEmitter.cpp	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -16,6 +16,7 @@
 #include "RegisterInfoEmitter.h"
 #include "CodeGenTarget.h"
 #include "CodeGenRegisters.h"
+#include "SequenceToOffsetTable.h"
 #include "llvm/TableGen/Record.h"
 #include "llvm/ADT/BitVector.h"
 #include "llvm/ADT/StringExtras.h"
@@ -31,6 +32,9 @@
                               CodeGenTarget &Target, CodeGenRegBank &Bank)=
 {
   const std::vector<CodeGenRegister*> &Registers =3D Bank.getRegisters();
=20
+  // Register enums are stored as uint16_t in the tables. Make sure we'll =
fit
+  assert(Registers.size() <=3D 0xffff && "Too many regs to fit in tables");
+
   std::string Namespace =3D Registers[0]->TheDef->getValueAsString("Namesp=
ace");
=20
   EmitSourceFileHeader("Target Register Enum Values", OS);
@@ -41,7 +45,8 @@
   OS << "namespace llvm {\n\n";
=20
   OS << "class MCRegisterClass;\n"
-     << "extern MCRegisterClass " << Namespace << "MCRegisterClasses[];\n\=
n";
+     << "extern const MCRegisterClass " << Namespace
+     << "MCRegisterClasses[];\n\n";
=20
   if (!Namespace.empty())
     OS << "namespace " << Namespace << " {\n";
@@ -59,6 +64,11 @@
=20
   ArrayRef<CodeGenRegisterClass*> RegisterClasses =3D Bank.getRegClasses();
   if (!RegisterClasses.empty()) {
+
+    // RegisterClass enums are stored as uint16_t in the tables.
+    assert(RegisterClasses.size() <=3D 0xffff &&
+           "Too many register classes to fit in tables");
+
     OS << "\n// Register classes\n";
     if (!Namespace.empty())
       OS << "namespace " << Namespace << " {\n";
@@ -89,16 +99,104 @@
       OS << "}\n";
   }
=20
+  ArrayRef<CodeGenSubRegIndex*> SubRegIndices =3D Bank.getSubRegIndices();
+  if (!SubRegIndices.empty()) {
+    OS << "\n// Subregister indices\n";
+    std::string Namespace =3D
+      SubRegIndices[0]->getNamespace();
+    if (!Namespace.empty())
+      OS << "namespace " << Namespace << " {\n";
+    OS << "enum {\n  NoSubRegister,\n";
+    for (unsigned i =3D 0, e =3D Bank.getNumNamedIndices(); i !=3D e; ++i)
+      OS << "  " << SubRegIndices[i]->getName() << ",\t// " << i+1 << "\n";
+    OS << "  NUM_TARGET_NAMED_SUBREGS\n};\n";
+    if (!Namespace.empty())
+      OS << "}\n";
+  }
=20
   OS << "} // End llvm namespace \n";
   OS << "#endif // GET_REGINFO_ENUM\n\n";
 }
=20
+void RegisterInfoEmitter::
+EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
+                    const std::string &ClassName) {
+  unsigned NumRCs =3D RegBank.getRegClasses().size();
+  unsigned NumSets =3D RegBank.getNumRegPressureSets();
+
+  OS << "/// Get the weight in units of pressure for this register class.\=
n"
+     << "const RegClassWeight &" << ClassName << "::\n"
+     << "getRegClassWeight(const TargetRegisterClass *RC) const {\n"
+     << "  static const RegClassWeight RCWeightTable[] =3D {\n";
+  for (unsigned i =3D 0, e =3D NumRCs; i !=3D e; ++i) {
+    const CodeGenRegisterClass &RC =3D *RegBank.getRegClasses()[i];
+    const CodeGenRegister::Set &Regs =3D RC.getMembers();
+    if (Regs.empty())
+      OS << "    {0, 0";
+    else {
+      std::vector<unsigned> RegUnits;
+      RC.buildRegUnitSet(RegUnits);
+      OS << "    {" << (*Regs.begin())->getWeight(RegBank)
+         << ", " << RegBank.getRegUnitSetWeight(RegUnits);
+    }
+    OS << "},  \t// " << RC.getName() << "\n";
+  }
+  OS << "    {0, 0} };\n"
+     << "  return RCWeightTable[RC->getID()];\n"
+     << "}\n\n";
+
+  OS << "\n"
+     << "// Get the number of dimensions of register pressure.\n"
+     << "unsigned " << ClassName << "::getNumRegPressureSets() const {\n"
+     << "  return " << NumSets << ";\n}\n\n";
+
+  OS << "// Get the register unit pressure limit for this dimension.\n"
+     << "// This limit must be adjusted dynamically for reserved registers=
.\n"
+     << "unsigned " << ClassName << "::\n"
+     << "getRegPressureSetLimit(unsigned Idx) const {\n"
+     << "  static const unsigned PressureLimitTable[] =3D {\n";
+  for (unsigned i =3D 0; i < NumSets; ++i ) {
+    const RegUnitSet &RegUnits =3D RegBank.getRegPressureSet(i);
+    OS << "    " << RegBank.getRegUnitSetWeight(RegUnits.Units)
+       << ",  \t// " << i << ": " << RegBank.getRegPressureSet(i).Name << =
"\n";
+  }
+  OS << "    0 };\n"
+     << "  return PressureLimitTable[Idx];\n"
+     << "}\n\n";
+
+  OS << "/// Get the dimensions of register pressure "
+     << "impacted by this register class.\n"
+     << "/// Returns a -1 terminated array of pressure set IDs\n"
+     << "const int* " << ClassName << "::\n"
+     << "getRegClassPressureSets(const TargetRegisterClass *RC) const {\n"
+     << "  static const int RCSetsTable[] =3D {\n    ";
+  std::vector<unsigned> RCSetStarts(NumRCs);
+  for (unsigned i =3D 0, StartIdx =3D 0, e =3D NumRCs; i !=3D e; ++i) {
+    RCSetStarts[i] =3D StartIdx;
+    ArrayRef<unsigned> PSetIDs =3D RegBank.getRCPressureSetIDs(i);
+    for (ArrayRef<unsigned>::iterator PSetI =3D PSetIDs.begin(),
+           PSetE =3D PSetIDs.end(); PSetI !=3D PSetE; ++PSetI) {
+      OS << *PSetI << ",  ";
+      ++StartIdx;
+    }
+    OS << "-1,  \t// " << RegBank.getRegClasses()[i]->getName() << "\n    =
";
+    ++StartIdx;
+  }
+  OS << "-1 };\n";
+  OS << "  static const unsigned RCSetStartTable[] =3D {\n    ";
+  for (unsigned i =3D 0, e =3D NumRCs; i !=3D e; ++i) {
+    OS << RCSetStarts[i] << ",";
+  }
+  OS << "0 };\n"
+     << "  unsigned SetListStart =3D RCSetStartTable[RC->getID()];\n"
+     << "  return &RCSetsTable[SetListStart];\n"
+     << "}\n\n";
+}
+
 void
-RegisterInfoEmitter::EmitRegMapping(raw_ostream &OS,
-                                    const std::vector<CodeGenRegister*> &R=
egs,
-                                    bool isCtor) {
-
+RegisterInfoEmitter::EmitRegMappingTables(raw_ostream &OS,
+                                       const std::vector<CodeGenRegister*>=
 &Regs,
+                                          bool isCtor) {
   // Collect all information about dwarf register numbers
   typedef std::map<Record*, std::vector<int64_t>, LessRecord> DwarfRegNums=
MapTy;
   DwarfRegNumsMapTy DwarfRegNums;
@@ -124,39 +222,52 @@
     for (unsigned i =3D I->second.size(), e =3D maxLength; i !=3D e; ++i)
       I->second.push_back(-1);
=20
+  std::string Namespace =3D Regs[0]->TheDef->getValueAsString("Namespace");
+
+  OS << "// " << Namespace << " Dwarf<->LLVM register mappings.\n";
+
   // Emit reverse information about the dwarf register numbers.
   for (unsigned j =3D 0; j < 2; ++j) {
-    OS << "  switch (";
-    if (j =3D=3D 0)
-      OS << "DwarfFlavour";
-    else
-      OS << "EHFlavour";
-    OS << ") {\n"
-     << "  default:\n"
-     << "    assert(0 && \"Unknown DWARF flavour\");\n"
-     << "    break;\n";
+    for (unsigned i =3D 0, e =3D maxLength; i !=3D e; ++i) {
+      OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
+      OS << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour");
+      OS << i << "Dwarf2L[]";
=20
-    for (unsigned i =3D 0, e =3D maxLength; i !=3D e; ++i) {
-      OS << "  case " << i << ":\n";
-      for (DwarfRegNumsMapTy::iterator
-             I =3D DwarfRegNums.begin(), E =3D DwarfRegNums.end(); I !=3D =
E; ++I) {
-        int DwarfRegNo =3D I->second[i];
-        if (DwarfRegNo < 0)
-          continue;
-        OS << "    ";
-        if (!isCtor)
-          OS << "RI->";
-        OS << "mapDwarfRegToLLVMReg(" << DwarfRegNo << ", "
-           << getQualifiedName(I->first) << ", ";
-        if (j =3D=3D 0)
-          OS << "false";
-        else
-          OS << "true";
-        OS << " );\n";
+      if (!isCtor) {
+        OS << " =3D {\n";
+
+        // Store the mapping sorted by the LLVM reg num so lookup can be d=
one
+        // with a binary search.
+        std::map<uint64_t, Record*> Dwarf2LMap;
+        for (DwarfRegNumsMapTy::iterator
+               I =3D DwarfRegNums.begin(), E =3D DwarfRegNums.end(); I !=
=3D E; ++I) {
+          int DwarfRegNo =3D I->second[i];
+          if (DwarfRegNo < 0)
+            continue;
+          Dwarf2LMap[DwarfRegNo] =3D I->first;
+        }
+
+        for (std::map<uint64_t, Record*>::iterator
+               I =3D Dwarf2LMap.begin(), E =3D Dwarf2LMap.end(); I !=3D E;=
 ++I)
+          OS << "  { " << I->first << "U, " << getQualifiedName(I->second)
+             << " },\n";
+
+        OS << "};\n";
+      } else {
+        OS << ";\n";
       }
-      OS << "    break;\n";
+
+      // We have to store the size in a const global, it's used in multiple
+      // places.
+      OS << "extern const unsigned " << Namespace
+         << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour") << i << "Dwarf2LSi=
ze";
+      if (!isCtor)
+        OS << " =3D sizeof(" << Namespace
+           << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour") << i
+           << "Dwarf2L)/sizeof(MCRegisterInfo::DwarfLLVMRegPair);\n\n";
+      else
+        OS << ";\n\n";
     }
-    OS << "  }\n";
   }
=20
   for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
@@ -172,6 +283,93 @@
=20
   // Emit information about the dwarf register numbers.
   for (unsigned j =3D 0; j < 2; ++j) {
+    for (unsigned i =3D 0, e =3D maxLength; i !=3D e; ++i) {
+      OS << "extern const MCRegisterInfo::DwarfLLVMRegPair " << Namespace;
+      OS << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour");
+      OS << i << "L2Dwarf[]";
+      if (!isCtor) {
+        OS << " =3D {\n";
+        // Store the mapping sorted by the Dwarf reg num so lookup can be =
done
+        // with a binary search.
+        for (DwarfRegNumsMapTy::iterator
+               I =3D DwarfRegNums.begin(), E =3D DwarfRegNums.end(); I !=
=3D E; ++I) {
+          int RegNo =3D I->second[i];
+          if (RegNo =3D=3D -1) // -1 is the default value, don't emit a ma=
pping.
+            continue;
+
+          OS << "  { " << getQualifiedName(I->first) << ", " << RegNo
+             << "U },\n";
+        }
+        OS << "};\n";
+      } else {
+        OS << ";\n";
+      }
+
+      // We have to store the size in a const global, it's used in multiple
+      // places.
+      OS << "extern const unsigned " << Namespace
+         << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour") << i << "L2DwarfSi=
ze";
+      if (!isCtor)
+        OS << " =3D sizeof(" << Namespace
+           << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour") << i
+           << "L2Dwarf)/sizeof(MCRegisterInfo::DwarfLLVMRegPair);\n\n";
+      else
+        OS << ";\n\n";
+    }
+  }
+}
+
+void
+RegisterInfoEmitter::EmitRegMapping(raw_ostream &OS,
+                                    const std::vector<CodeGenRegister*> &R=
egs,
+                                    bool isCtor) {
+  // Emit the initializer so the tables from EmitRegMappingTables get wire=
d up
+  // to the MCRegisterInfo object.
+  unsigned maxLength =3D 0;
+  for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
+    Record *Reg =3D Regs[i]->TheDef;
+    maxLength =3D std::max((size_t)maxLength,
+                         Reg->getValueAsListOfInts("DwarfNumbers").size());
+  }
+
+  if (!maxLength)
+    return;
+
+  std::string Namespace =3D Regs[0]->TheDef->getValueAsString("Namespace");
+
+  // Emit reverse information about the dwarf register numbers.
+  for (unsigned j =3D 0; j < 2; ++j) {
+    OS << "  switch (";
+    if (j =3D=3D 0)
+      OS << "DwarfFlavour";
+    else
+      OS << "EHFlavour";
+    OS << ") {\n"
+     << "  default:\n"
+     << "    llvm_unreachable(\"Unknown DWARF flavour\");\n";
+
+    for (unsigned i =3D 0, e =3D maxLength; i !=3D e; ++i) {
+      OS << "  case " << i << ":\n";
+      OS << "    ";
+      if (!isCtor)
+        OS << "RI->";
+      std::string Tmp;
+      raw_string_ostream(Tmp) << Namespace
+                              << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour=
") << i
+                              << "Dwarf2L";
+      OS << "mapDwarfRegsToLLVMRegs(" << Tmp << ", " << Tmp << "Size, ";
+      if (j =3D=3D 0)
+          OS << "false";
+        else
+          OS << "true";
+      OS << ");\n";
+      OS << "    break;\n";
+    }
+    OS << "  }\n";
+  }
+
+  // Emit information about the dwarf register numbers.
+  for (unsigned j =3D 0; j < 2; ++j) {
     OS << "  switch (";
     if (j =3D=3D 0)
       OS << "DwarfFlavour";
@@ -179,26 +377,23 @@
       OS << "EHFlavour";
     OS << ") {\n"
        << "  default:\n"
-       << "    assert(0 && \"Unknown DWARF flavour\");\n"
-       << "    break;\n";
+       << "    llvm_unreachable(\"Unknown DWARF flavour\");\n";
=20
     for (unsigned i =3D 0, e =3D maxLength; i !=3D e; ++i) {
       OS << "  case " << i << ":\n";
-      // Sort by name to get a stable order.
-      for (DwarfRegNumsMapTy::iterator
-             I =3D DwarfRegNums.begin(), E =3D DwarfRegNums.end(); I !=3D =
E; ++I) {
-        int RegNo =3D I->second[i];
-        OS << "    ";
-        if (!isCtor)
-          OS << "RI->";
-        OS << "mapLLVMRegToDwarfReg(" << getQualifiedName(I->first) << ", "
-           <<  RegNo << ", ";
-        if (j =3D=3D 0)
+      OS << "    ";
+      if (!isCtor)
+        OS << "RI->";
+      std::string Tmp;
+      raw_string_ostream(Tmp) << Namespace
+                              << (j =3D=3D 0 ? "DwarfFlavour" : "EHFlavour=
") << i
+                              << "L2Dwarf";
+      OS << "mapLLVMRegsToDwarfRegs(" << Tmp << ", " << Tmp << "Size, ";
+      if (j =3D=3D 0)
           OS << "false";
         else
           OS << "true";
-        OS << " );\n";
-      }
+      OS << ");\n";
       OS << "    break;\n";
     }
     OS << "  }\n";
@@ -235,6 +430,14 @@
   }
 };
=20
+static void printRegister(raw_ostream &OS, const CodeGenRegister *Reg) {
+  OS << getQualifiedName(Reg->TheDef);
+}
+
+static void printSimpleValueType(raw_ostream &OS, MVT::SimpleValueType VT)=
 {
+  OS << getEnumName(VT);
+}
+
 //
 // runMCDesc - Print out MC register descriptions.
 //
@@ -246,87 +449,79 @@
   OS << "\n#ifdef GET_REGINFO_MC_DESC\n";
   OS << "#undef GET_REGINFO_MC_DESC\n";
=20
+  const std::vector<CodeGenRegister*> &Regs =3D RegBank.getRegisters();
   std::map<const CodeGenRegister*, CodeGenRegister::Set> Overlaps;
   RegBank.computeOverlaps(Overlaps);
=20
+  // The lists of sub-registers, super-registers, and overlaps all go in t=
he
+  // same array. That allows us to share suffixes.
+  typedef std::vector<const CodeGenRegister*> RegVec;
+  SmallVector<RegVec, 4> SubRegLists(Regs.size());
+  SmallVector<RegVec, 4> OverlapLists(Regs.size());
+  SequenceToOffsetTable<RegVec, CodeGenRegister::Less> RegSeqs;
+
+  // Precompute register lists for the SequenceToOffsetTable.
+  for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
+    const CodeGenRegister *Reg =3D Regs[i];
+
+    // Compute the ordered sub-register list.
+    SetVector<const CodeGenRegister*> SR;
+    Reg->addSubRegsPreOrder(SR, RegBank);
+    RegVec &SubRegList =3D SubRegLists[i];
+    SubRegList.assign(SR.begin(), SR.end());
+    RegSeqs.add(SubRegList);
+
+    // Super-registers are already computed.
+    const RegVec &SuperRegList =3D Reg->getSuperRegs();
+    RegSeqs.add(SuperRegList);
+
+    // The list of overlaps doesn't need to have any particular order, exc=
ept
+    // Reg itself must be the first element. Pick an ordering that has one=
 of
+    // the other lists as a suffix.
+    RegVec &OverlapList =3D OverlapLists[i];
+    const RegVec &Suffix =3D SubRegList.size() > SuperRegList.size() ?
+                           SubRegList : SuperRegList;
+    CodeGenRegister::Set Omit(Suffix.begin(), Suffix.end());
+
+    // First element is Reg itself.
+    OverlapList.push_back(Reg);
+    Omit.insert(Reg);
+
+    // Any elements not in Suffix.
+    const CodeGenRegister::Set &OSet =3D Overlaps[Reg];
+    std::set_difference(OSet.begin(), OSet.end(),
+                        Omit.begin(), Omit.end(),
+                        std::back_inserter(OverlapList),
+                        CodeGenRegister::Less());
+
+    // Finally, Suffix itself.
+    OverlapList.insert(OverlapList.end(), Suffix.begin(), Suffix.end());
+    RegSeqs.add(OverlapList);
+  }
+
+  // Compute the final layout of the sequence table.
+  RegSeqs.layout();
+
   OS << "namespace llvm {\n\n";
=20
   const std::string &TargetName =3D Target.getName();
-  std::string ClassName =3D TargetName + "GenMCRegisterInfo";
-  OS << "struct " << ClassName << " : public MCRegisterInfo {\n"
-     << "  explicit " << ClassName << "(const MCRegisterDesc *D);\n";
-  OS << "};\n";
=20
-  OS << "\nnamespace {\n";
+  // Emit the shared table of register lists.
+  OS << "extern const uint16_t " << TargetName << "RegLists[] =3D {\n";
+  RegSeqs.emit(OS, printRegister);
+  OS << "};\n\n";
=20
-  const std::vector<CodeGenRegister*> &Regs =3D RegBank.getRegisters();
+  OS << "extern const MCRegisterDesc " << TargetName
+     << "RegDesc[] =3D { // Descriptors\n";
+  OS << "  { \"NOREG\", 0, 0, 0 },\n";
=20
-  // Emit an overlap list for all registers.
+  // Emit the register descriptors now.
   for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
     const CodeGenRegister *Reg =3D Regs[i];
-    const CodeGenRegister::Set &O =3D Overlaps[Reg];
-    // Move Reg to the front so TRI::getAliasSet can share the list.
-    OS << "  const unsigned " << Reg->getName() << "_Overlaps[] =3D { "
-       << getQualifiedName(Reg->TheDef) << ", ";
-    for (CodeGenRegister::Set::const_iterator I =3D O.begin(), E =3D O.end=
();
-         I !=3D E; ++I)
-      if (*I !=3D Reg)
-        OS << getQualifiedName((*I)->TheDef) << ", ";
-    OS << "0 };\n";
-  }
-
-  // Emit the empty sub-registers list
-  OS << "  const unsigned Empty_SubRegsSet[] =3D { 0 };\n";
-  // Loop over all of the registers which have sub-registers, emitting the
-  // sub-registers list to memory.
-  for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
-    const CodeGenRegister &Reg =3D *Regs[i];
-    if (Reg.getSubRegs().empty())
-     continue;
-    // getSubRegs() orders by SubRegIndex. We want a topological order.
-    SetVector<CodeGenRegister*> SR;
-    Reg.addSubRegsPreOrder(SR);
-    OS << "  const unsigned " << Reg.getName() << "_SubRegsSet[] =3D { ";
-    for (unsigned j =3D 0, je =3D SR.size(); j !=3D je; ++j)
-      OS << getQualifiedName(SR[j]->TheDef) << ", ";
-    OS << "0 };\n";
-  }
-
-  // Emit the empty super-registers list
-  OS << "  const unsigned Empty_SuperRegsSet[] =3D { 0 };\n";
-  // Loop over all of the registers which have super-registers, emitting t=
he
-  // super-registers list to memory.
-  for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
-    const CodeGenRegister &Reg =3D *Regs[i];
-    const CodeGenRegister::SuperRegList &SR =3D Reg.getSuperRegs();
-    if (SR.empty())
-      continue;
-    OS << "  const unsigned " << Reg.getName() << "_SuperRegsSet[] =3D { ";
-    for (unsigned j =3D 0, je =3D SR.size(); j !=3D je; ++j)
-      OS << getQualifiedName(SR[j]->TheDef) << ", ";
-    OS << "0 };\n";
-  }
-  OS << "}\n";       // End of anonymous namespace...
-
-  OS << "\nMCRegisterDesc " << TargetName
-     << "RegDesc[] =3D { // Descriptors\n";
-  OS << "  { \"NOREG\",\t0,\t0,\t0 },\n";
-
-  // Now that register alias and sub-registers sets have been emitted, emi=
t the
-  // register descriptors now.
-  for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
-    const CodeGenRegister &Reg =3D *Regs[i];
-    OS << "  { \"";
-    OS << Reg.getName() << "\",\t" << Reg.getName() << "_Overlaps,\t";
-    if (!Reg.getSubRegs().empty())
-      OS << Reg.getName() << "_SubRegsSet,\t";
-    else
-      OS << "Empty_SubRegsSet,\t";
-    if (!Reg.getSuperRegs().empty())
-      OS << Reg.getName() << "_SuperRegsSet";
-    else
-      OS << "Empty_SuperRegsSet";
-    OS << " },\n";
+    OS << "  { \"" << Reg->getName() << "\", "
+       << RegSeqs.get(OverlapLists[i]) << ", "
+       << RegSeqs.get(SubRegLists[i]) << ", "
+       << RegSeqs.get(Reg->getSuperRegs()) << " },\n";
   }
   OS << "};\n\n";      // End of register descriptors...
=20
@@ -345,7 +540,7 @@
=20
     // Emit the register list now.
     OS << "  // " << Name << " Register Class...\n"
-       << "  static const unsigned " << Name
+       << "  const uint16_t " << Name
        << "[] =3D {\n    ";
     for (unsigned i =3D 0, e =3D Order.size(); i !=3D e; ++i) {
       Record *Reg =3D Order[i];
@@ -354,7 +549,7 @@
     OS << "\n  };\n\n";
=20
     OS << "  // " << Name << " Bit set.\n"
-       << "  static const unsigned char " << Name
+       << "  const uint8_t " << Name
        << "Bits[] =3D {\n    ";
     BitVectorEmitter BVE;
     for (unsigned i =3D 0, e =3D Order.size(); i !=3D e; ++i) {
@@ -367,37 +562,81 @@
   }
   OS << "}\n\n";
=20
-  OS << "MCRegisterClass " << TargetName << "MCRegisterClasses[] =3D {\n";
+  OS << "extern const MCRegisterClass " << TargetName
+     << "MCRegisterClasses[] =3D {\n";
=20
   for (unsigned rc =3D 0, e =3D RegisterClasses.size(); rc !=3D e; ++rc) {
     const CodeGenRegisterClass &RC =3D *RegisterClasses[rc];
-    OS << "  MCRegisterClass(" << RC.getQualifiedName() + "RegClassID" << =
", "
-       << '\"' << RC.getName() << "\", "
+
+    // Asserts to make sure values will fit in table assuming types from
+    // MCRegisterInfo.h
+    assert((RC.SpillSize/8) <=3D 0xffff && "SpillSize too large.");
+    assert((RC.SpillAlignment/8) <=3D 0xffff && "SpillAlignment too large.=
");
+    assert(RC.CopyCost >=3D -128 && RC.CopyCost <=3D 127 && "Copy cost too=
 large.");
+
+    OS << "  { " << '\"' << RC.getName() << "\", "
+       << RC.getName() << ", " << RC.getName() << "Bits, "
+       << RC.getOrder().size() << ", sizeof(" << RC.getName() << "Bits), "
+       << RC.getQualifiedName() + "RegClassID" << ", "
        << RC.SpillSize/8 << ", "
        << RC.SpillAlignment/8 << ", "
        << RC.CopyCost << ", "
-       << RC.Allocatable << ", "
-       << RC.getName() << ", " << RC.getName() << " + "
-       << RC.getOrder().size() << ", "
-       << RC.getName() << "Bits, sizeof(" << RC.getName() << "Bits)"
-       << "),\n";
+       << RC.Allocatable << " },\n";
   }
=20
   OS << "};\n\n";
=20
+  // Emit the data table for getSubReg().
+  ArrayRef<CodeGenSubRegIndex*> SubRegIndices =3D RegBank.getSubRegIndices=
();
+  if (SubRegIndices.size()) {
+    OS << "const uint16_t " << TargetName << "SubRegTable[]["
+       << SubRegIndices.size() << "] =3D {\n";
+    for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
+      const CodeGenRegister::SubRegMap &SRM =3D Regs[i]->getSubRegs();
+      OS << "  /* " << Regs[i]->TheDef->getName() << " */\n";
+      if (SRM.empty()) {
+        OS << "  {0},\n";
+        continue;
+      }
+      OS << "  {";
+      for (unsigned j =3D 0, je =3D SubRegIndices.size(); j !=3D je; ++j) {
+        // FIXME: We really should keep this to 80 columns...
+        CodeGenRegister::SubRegMap::const_iterator SubReg =3D
+          SRM.find(SubRegIndices[j]);
+        if (SubReg !=3D SRM.end())
+          OS << getQualifiedName(SubReg->second->TheDef);
+        else
+          OS << "0";
+        if (j !=3D je - 1)
+          OS << ", ";
+      }
+      OS << "}" << (i !=3D e ? "," : "") << "\n";
+    }
+    OS << "};\n\n";
+    OS << "const uint16_t *get" << TargetName
+       << "SubRegTable() {\n  return (const uint16_t *)" << TargetName
+       << "SubRegTable;\n}\n\n";
+  }
+
+  EmitRegMappingTables(OS, Regs, false);
+
   // MCRegisterInfo initialization routine.
   OS << "static inline void Init" << TargetName
      << "MCRegisterInfo(MCRegisterInfo *RI, unsigned RA, "
      << "unsigned DwarfFlavour =3D 0, unsigned EHFlavour =3D 0) {\n";
   OS << "  RI->InitMCRegisterInfo(" << TargetName << "RegDesc, "
      << Regs.size()+1 << ", RA, " << TargetName << "MCRegisterClasses, "
-     << RegisterClasses.size() << ");\n\n";
+     << RegisterClasses.size() << ", " << TargetName << "RegLists, ";
+  if (SubRegIndices.size() !=3D 0)
+    OS << "(uint16_t*)" << TargetName << "SubRegTable, "
+       << SubRegIndices.size() << ");\n\n";
+  else
+    OS << "NULL, 0);\n\n";
=20
   EmitRegMapping(OS, Regs, false);
=20
   OS << "}\n\n";
=20
-
   OS << "} // End llvm namespace \n";
   OS << "#endif // GET_REGINFO_MC_DESC\n\n";
 }
@@ -413,8 +652,7 @@
   const std::string &TargetName =3D Target.getName();
   std::string ClassName =3D TargetName + "GenRegisterInfo";
=20
-  OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n";
-  OS << "#include <string>\n\n";
+  OS << "#include \"llvm/Target/TargetRegisterInfo.h\"\n\n";
=20
   OS << "namespace llvm {\n\n";
=20
@@ -423,28 +661,20 @@
      << "(unsigned RA, unsigned D =3D 0, unsigned E =3D 0);\n"
      << "  virtual bool needsStackRealignment(const MachineFunction &) con=
st\n"
      << "     { return false; }\n"
-     << "  unsigned getSubReg(unsigned RegNo, unsigned Index) const;\n"
-     << "  unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) cons=
t;\n"
      << "  unsigned composeSubRegIndices(unsigned, unsigned) const;\n"
      << "  const TargetRegisterClass *"
         "getSubClassWithSubReg(const TargetRegisterClass*, unsigned) const=
;\n"
+     << "  const TargetRegisterClass *getMatchingSuperRegClass("
+        "const TargetRegisterClass*, const TargetRegisterClass*, "
+        "unsigned) const;\n"
+     << "  const RegClassWeight &getRegClassWeight("
+     << "const TargetRegisterClass *RC) const;\n"
+     << "  unsigned getNumRegPressureSets() const;\n"
+     << "  unsigned getRegPressureSetLimit(unsigned Idx) const;\n"
+     << "  const int *getRegClassPressureSets("
+     << "const TargetRegisterClass *RC) const;\n"
      << "};\n\n";
=20
-  const std::vector<Record*> &SubRegIndices =3D RegBank.getSubRegIndices();
-  if (!SubRegIndices.empty()) {
-    OS << "\n// Subregister indices\n";
-    std::string Namespace =3D SubRegIndices[0]->getValueAsString("Namespac=
e");
-    if (!Namespace.empty())
-      OS << "namespace " << Namespace << " {\n";
-    OS << "enum {\n  NoSubRegister,\n";
-    for (unsigned i =3D 0, e =3D RegBank.getNumNamedIndices(); i !=3D e; +=
+i)
-      OS << "  " << SubRegIndices[i]->getName() << ",\t// " << i+1 << "\n";
-    OS << "  NUM_TARGET_NAMED_SUBREGS =3D " << SubRegIndices.size()+1 << "=
\n";
-    OS << "};\n";
-    if (!Namespace.empty())
-      OS << "}\n";
-  }
-
   ArrayRef<CodeGenRegisterClass*> RegisterClasses =3D RegBank.getRegClasse=
s();
=20
   if (!RegisterClasses.empty()) {
@@ -455,19 +685,11 @@
       const CodeGenRegisterClass &RC =3D *RegisterClasses[i];
       const std::string &Name =3D RC.getName();
=20
-      // Output the register class definition.
-      OS << "  struct " << Name << "Class : public TargetRegisterClass {\n"
-         << "    " << Name << "Class();\n";
-      if (!RC.AltOrderSelect.empty())
-        OS << "    ArrayRef<unsigned> "
-              "getRawAllocationOrder(const MachineFunction&) const;\n";
-      OS << "  };\n";
-
       // Output the extern for the instance.
-      OS << "  extern " << Name << "Class\t" << Name << "RegClass;\n";
+      OS << "  extern const TargetRegisterClass " << Name << "RegClass;\n";
       // Output the extern for the pointer to the instance (should remove).
-      OS << "  static TargetRegisterClass * const "<< Name <<"RegisterClas=
s =3D &"
-         << Name << "RegClass;\n";
+      OS << "  static const TargetRegisterClass * const " << Name
+         << "RegisterClass =3D &" << Name << "RegClass;\n";
     }
     OS << "} // end of namespace " << TargetName << "\n\n";
   }
@@ -489,8 +711,8 @@
   OS << "namespace llvm {\n\n";
=20
   // Get access to MCRegisterClass data.
-  OS << "extern MCRegisterClass " << Target.getName()
-    << "MCRegisterClasses[];\n";
+  OS << "extern const MCRegisterClass " << Target.getName()
+     << "MCRegisterClasses[];\n";
=20
   // Start out by emitting each of the register classes.
   ArrayRef<CodeGenRegisterClass*> RegisterClasses =3D RegBank.getRegClasse=
s();
@@ -507,38 +729,21 @@
       AllocatableRegs.insert(Order.begin(), Order.end());
   }
=20
-  OS << "namespace {     // Register classes...\n";
-
-  // Emit the ValueType arrays for each RegisterClass
-  for (unsigned rc =3D 0, e =3D RegisterClasses.size(); rc !=3D e; ++rc) {
-    const CodeGenRegisterClass &RC =3D *RegisterClasses[rc];
-
-    // Give the register class a legal C name if it's anonymous.
-    std::string Name =3D RC.getName() + "VTs";
-
-    // Emit the register list now.
-    OS << "  // " << Name
-       << " Register Class Value Types...\n"
-       << "  static const EVT " << Name
-       << "[] =3D {\n    ";
-    for (unsigned i =3D 0, e =3D RC.VTs.size(); i !=3D e; ++i)
-      OS << getEnumName(RC.VTs[i]) << ", ";
-    OS << "MVT::Other\n  };\n\n";
-  }
-  OS << "}  // end anonymous namespace\n\n";
+  // Build a shared array of value types.
+  SequenceToOffsetTable<std::vector<MVT::SimpleValueType> > VTSeqs;
+  for (unsigned rc =3D 0, e =3D RegisterClasses.size(); rc !=3D e; ++rc)
+    VTSeqs.add(RegisterClasses[rc]->VTs);
+  VTSeqs.layout();
+  OS << "\nstatic const MVT::SimpleValueType VTLists[] =3D {\n";
+  VTSeqs.emit(OS, printSimpleValueType, "MVT::Other");
+  OS << "};\n";
=20
   // Now that all of the structs have been emitted, emit the instances.
   if (!RegisterClasses.empty()) {
-    OS << "namespace " << RegisterClasses[0]->Namespace
-       << " {   // Register class instances\n";
-    for (unsigned i =3D 0, e =3D RegisterClasses.size(); i !=3D e; ++i)
-      OS << "  " << RegisterClasses[i]->getName()  << "Class\t"
-         << RegisterClasses[i]->getName() << "RegClass;\n";
-
     std::map<unsigned, std::set<unsigned> > SuperRegClassMap;
=20
-    OS << "\n  static const TargetRegisterClass* const "
-      << "NullRegClasses[] =3D { NULL };\n\n";
+    OS << "\nstatic const TargetRegisterClass *const "
+       << "NullRegClasses[] =3D { NULL };\n\n";
=20
     unsigned NumSubRegIndices =3D RegBank.getSubRegIndices().size();
=20
@@ -563,10 +768,10 @@
         // Give the register class a legal C name if it's anonymous.
         std::string Name =3D RC.getName();
=20
-        OS << "  // " << Name
+        OS << "// " << Name
            << " Super-register Classes...\n"
-           << "  static const TargetRegisterClass* const "
-           << Name << "SuperRegClasses[] =3D {\n    ";
+           << "static const TargetRegisterClass *const "
+           << Name << "SuperRegClasses[] =3D {\n  ";
=20
         bool Empty =3D true;
         std::map<unsigned, std::set<unsigned> >::iterator I =3D
@@ -583,7 +788,7 @@
         }
=20
         OS << (!Empty ? ", " : "") << "NULL";
-        OS << "\n  };\n\n";
+        OS << "\n};\n\n";
       }
     }
=20
@@ -594,9 +799,9 @@
       // Give the register class a legal C name if it's anonymous.
       std::string Name =3D RC.getName();
=20
-      OS << "  static const unsigned " << Name << "SubclassMask[] =3D { ";
+      OS << "static const uint32_t " << Name << "SubclassMask[] =3D {\n  ";
       printBitVectorAsHex(OS, RC.getSubClasses(), 32);
-      OS << "};\n\n";
+      OS << "\n};\n\n";
     }
=20
     // Emit NULL terminated super-class lists.
@@ -608,54 +813,71 @@
       if (Supers.empty())
         continue;
=20
-      OS << "  static const TargetRegisterClass* const "
+      OS << "static const TargetRegisterClass *const "
          << RC.getName() << "Superclasses[] =3D {\n";
       for (unsigned i =3D 0; i !=3D Supers.size(); ++i)
-        OS << "    &" << Supers[i]->getQualifiedName() << "RegClass,\n";
-      OS << "    NULL\n  };\n\n";
+        OS << "  &" << Supers[i]->getQualifiedName() << "RegClass,\n";
+      OS << "  NULL\n};\n\n";
     }
=20
     // Emit methods.
     for (unsigned i =3D 0, e =3D RegisterClasses.size(); i !=3D e; ++i) {
       const CodeGenRegisterClass &RC =3D *RegisterClasses[i];
-      OS << RC.getName() << "Class::" << RC.getName()
-         << "Class()  : TargetRegisterClass(&"
-         << Target.getName() << "MCRegisterClasses["
-         << RC.getName() + "RegClassID" << "], "
-         << RC.getName() + "VTs" << ", "
-         << RC.getName() + "SubclassMask" << ", ";
-      if (RC.getSuperClasses().empty())
-        OS << "NullRegClasses, ";
-      else
-        OS << RC.getName() + "Superclasses, ";
-      OS << (NumSubRegIndices ? RC.getName() + "Super" : std::string("Null=
"))
-         << "RegClasses"
-         << ") {}\n";
       if (!RC.AltOrderSelect.empty()) {
         OS << "\nstatic inline unsigned " << RC.getName()
            << "AltOrderSelect(const MachineFunction &MF) {"
-           << RC.AltOrderSelect << "}\n\nArrayRef<unsigned> "
-           << RC.getName() << "Class::"
-           << "getRawAllocationOrder(const MachineFunction &MF) const {\n";
+           << RC.AltOrderSelect << "}\n\n"
+           << "static ArrayRef<uint16_t> " << RC.getName()
+           << "GetRawAllocationOrder(const MachineFunction &MF) {\n";
         for (unsigned oi =3D 1 , oe =3D RC.getNumOrders(); oi !=3D oe; ++o=
i) {
           ArrayRef<Record*> Elems =3D RC.getOrder(oi);
-          OS << "  static const unsigned AltOrder" << oi << "[] =3D {";
-          for (unsigned elem =3D 0; elem !=3D Elems.size(); ++elem)
-            OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
-          OS << " };\n";
+          if (!Elems.empty()) {
+            OS << "  static const uint16_t AltOrder" << oi << "[] =3D {";
+            for (unsigned elem =3D 0; elem !=3D Elems.size(); ++elem)
+              OS << (elem ? ", " : " ") << getQualifiedName(Elems[elem]);
+            OS << " };\n";
+          }
         }
         OS << "  const MCRegisterClass &MCR =3D " << Target.getName()
-           << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID]=
;"
-           << "  static const ArrayRef<unsigned> Order[] =3D {\n"
+           << "MCRegisterClasses[" << RC.getQualifiedName() + "RegClassID]=
;\n"
+           << "  const ArrayRef<uint16_t> Order[] =3D {\n"
            << "    makeArrayRef(MCR.begin(), MCR.getNumRegs()";
         for (unsigned oi =3D 1, oe =3D RC.getNumOrders(); oi !=3D oe; ++oi)
-          OS << "),\n    makeArrayRef(AltOrder" << oi;
+          if (RC.getOrder(oi).empty())
+            OS << "),\n    ArrayRef<uint16_t>(";
+          else
+            OS << "),\n    makeArrayRef(AltOrder" << oi;
         OS << ")\n  };\n  const unsigned Select =3D " << RC.getName()
            << "AltOrderSelect(MF);\n  assert(Select < " << RC.getNumOrders=
()
            << ");\n  return Order[Select];\n}\n";
         }
     }
=20
+    // Now emit the actual value-initialized register class instances.
+    OS << "namespace " << RegisterClasses[0]->Namespace
+       << " {   // Register class instances\n";
+
+    for (unsigned i =3D 0, e =3D RegisterClasses.size(); i !=3D e; ++i) {
+      const CodeGenRegisterClass &RC =3D *RegisterClasses[i];
+      OS << "  extern const TargetRegisterClass "
+         << RegisterClasses[i]->getName() << "RegClass =3D {\n    "
+         << '&' << Target.getName() << "MCRegisterClasses[" << RC.getName()
+         << "RegClassID],\n    "
+         << "VTLists + " << VTSeqs.get(RC.VTs) << ",\n    "
+         << RC.getName() << "SubclassMask,\n    ";
+      if (RC.getSuperClasses().empty())
+        OS << "NullRegClasses,\n    ";
+      else
+        OS << RC.getName() << "Superclasses,\n    ";
+      OS << (NumSubRegIndices ? RC.getName() + "Super" : std::string("Null=
"))
+         << "RegClasses,\n    ";
+      if (RC.AltOrderSelect.empty())
+        OS << "0\n";
+      else
+        OS << RC.getName() << "GetRawAllocationOrder\n";
+      OS << "  };\n\n";
+    }
+
     OS << "}\n";
   }
=20
@@ -669,28 +891,27 @@
=20
   // Emit extra information about registers.
   const std::string &TargetName =3D Target.getName();
-  OS << "\n  static const TargetRegisterInfoDesc "
-     << TargetName << "RegInfoDesc[] =3D "
-     << "{ // Extra Descriptors\n";
-  OS << "    { 0, 0 },\n";
+  OS << "\nstatic const TargetRegisterInfoDesc "
+     << TargetName << "RegInfoDesc[] =3D { // Extra Descriptors\n";
+  OS << "  { 0, 0 },\n";
=20
   const std::vector<CodeGenRegister*> &Regs =3D RegBank.getRegisters();
   for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
     const CodeGenRegister &Reg =3D *Regs[i];
-    OS << "    { ";
+    OS << "  { ";
     OS << Reg.CostPerUse << ", "
        << int(AllocatableRegs.count(Reg.TheDef)) << " },\n";
   }
-  OS << "  };\n";      // End of register descriptors...
+  OS << "};\n";      // End of register descriptors...
=20
=20
   // Calculate the mapping of subregister+index pairs to physical register=
s.
-  // This will also create further anonymous indexes.
+  // This will also create further anonymous indices.
   unsigned NamedIndices =3D RegBank.getNumNamedIndices();
=20
   // Emit SubRegIndex names, skipping 0
-  const std::vector<Record*> &SubRegIndices =3D RegBank.getSubRegIndices();
-  OS << "\n  static const char *const " << TargetName
+  ArrayRef<CodeGenSubRegIndex*> SubRegIndices =3D RegBank.getSubRegIndices=
();
+  OS << "\nstatic const char *const " << TargetName
      << "SubRegIndexTable[] =3D { \"";
   for (unsigned i =3D 0, e =3D SubRegIndices.size(); i !=3D e; ++i) {
     OS << SubRegIndices[i]->getName();
@@ -699,7 +920,7 @@
   }
   OS << "\" };\n\n";
=20
-  // Emit names of the anonymus subreg indexes.
+  // Emit names of the anonymous subreg indices.
   if (SubRegIndices.size() > NamedIndices) {
     OS << "  enum {";
     for (unsigned i =3D NamedIndices, e =3D SubRegIndices.size(); i !=3D e=
; ++i) {
@@ -713,48 +934,6 @@
=20
   std::string ClassName =3D Target.getName() + "GenRegisterInfo";
=20
-  // Emit the subregister + index mapping function based on the information
-  // calculated above.
-  OS << "unsigned " << ClassName
-     << "::getSubReg(unsigned RegNo, unsigned Index) const {\n"
-     << "  switch (RegNo) {\n"
-     << "  default:\n    return 0;\n";
-  for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
-    const CodeGenRegister::SubRegMap &SRM =3D Regs[i]->getSubRegs();
-    if (SRM.empty())
-      continue;
-    OS << "  case " << getQualifiedName(Regs[i]->TheDef) << ":\n";
-    OS << "    switch (Index) {\n";
-    OS << "    default: return 0;\n";
-    for (CodeGenRegister::SubRegMap::const_iterator ii =3D SRM.begin(),
-         ie =3D SRM.end(); ii !=3D ie; ++ii)
-      OS << "    case " << getQualifiedName(ii->first)
-         << ": return " << getQualifiedName(ii->second->TheDef) << ";\n";
-    OS << "    };\n" << "    break;\n";
-  }
-  OS << "  };\n";
-  OS << "  return 0;\n";
-  OS << "}\n\n";
-
-  OS << "unsigned " << ClassName
-     << "::getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const {\n"
-     << "  switch (RegNo) {\n"
-     << "  default:\n    return 0;\n";
-   for (unsigned i =3D 0, e =3D Regs.size(); i !=3D e; ++i) {
-     const CodeGenRegister::SubRegMap &SRM =3D Regs[i]->getSubRegs();
-     if (SRM.empty())
-       continue;
-    OS << "  case " << getQualifiedName(Regs[i]->TheDef) << ":\n";
-    for (CodeGenRegister::SubRegMap::const_iterator ii =3D SRM.begin(),
-         ie =3D SRM.end(); ii !=3D ie; ++ii)
-      OS << "    if (SubRegNo =3D=3D " << getQualifiedName(ii->second->The=
Def)
-         << ")  return " << getQualifiedName(ii->first) << ";\n";
-    OS << "    return 0;\n";
-  }
-  OS << "  };\n";
-  OS << "  return 0;\n";
-  OS << "}\n\n";
-
   // Emit composeSubRegIndices
   OS << "unsigned " << ClassName
      << "::composeSubRegIndices(unsigned IdxA, unsigned IdxB) const {\n"
@@ -763,15 +942,15 @@
   for (unsigned i =3D 0, e =3D SubRegIndices.size(); i !=3D e; ++i) {
     bool Open =3D false;
     for (unsigned j =3D 0; j !=3D e; ++j) {
-      if (Record *Comp =3D RegBank.getCompositeSubRegIndex(SubRegIndices[i=
],
-                                                         SubRegIndices[j])=
) {
+      if (CodeGenSubRegIndex *Comp =3D
+            SubRegIndices[i]->compose(SubRegIndices[j])) {
         if (!Open) {
-          OS << "  case " << getQualifiedName(SubRegIndices[i])
+          OS << "  case " << SubRegIndices[i]->getQualifiedName()
              << ": switch(IdxB) {\n    default: return IdxB;\n";
           Open =3D true;
         }
-        OS << "    case " << getQualifiedName(SubRegIndices[j])
-           << ": return " << getQualifiedName(Comp) << ";\n";
+        OS << "    case " << SubRegIndices[j]->getQualifiedName()
+           << ": return " << Comp->getQualifiedName() << ";\n";
       }
     }
     if (Open)
@@ -800,7 +979,7 @@
       const CodeGenRegisterClass &RC =3D *RegisterClasses[rci];
       OS << "    {\t// " << RC.getName() << "\n";
       for (unsigned sri =3D 0, sre =3D SubRegIndices.size(); sri !=3D sre;=
 ++sri) {
-        Record *Idx =3D SubRegIndices[sri];
+        CodeGenSubRegIndex *Idx =3D SubRegIndices[sri];
         if (CodeGenRegisterClass *SRC =3D RC.getSubClassWithSubReg(Idx))
           OS << "      " << SRC->EnumValue + 1 << ",\t// " << Idx->getName=
()
              << " -> " << SRC->getName() << "\n";
@@ -817,22 +996,106 @@
   }
   OS << "}\n\n";
=20
+  // Emit getMatchingSuperRegClass.
+  OS << "const TargetRegisterClass *" << ClassName
+     << "::getMatchingSuperRegClass(const TargetRegisterClass *A,"
+        " const TargetRegisterClass *B, unsigned Idx) const {\n";
+  if (SubRegIndices.empty()) {
+    OS << "  llvm_unreachable(\"Target has no sub-registers\");\n";
+  } else {
+    // We need to find the largest sub-class of A such that every register=
 has
+    // an Idx sub-register in B.  Map (B, Idx) to a bit-vector of
+    // super-register classes that map into B. Then compute the largest co=
mmon
+    // sub-class with A by taking advantage of the register class ordering,
+    // like getCommonSubClass().
+
+    // Bitvector table is NumRCs x NumSubIndexes x BVWords, where BVWords =
is
+    // the number of 32-bit words required to represent all register class=
es.
+    const unsigned BVWords =3D (RegisterClasses.size()+31)/32;
+    BitVector BV(RegisterClasses.size());
+
+    OS << "  static const uint32_t Table[" << RegisterClasses.size()
+       << "][" << SubRegIndices.size() << "][" << BVWords << "] =3D {\n";
+    for (unsigned rci =3D 0, rce =3D RegisterClasses.size(); rci !=3D rce;=
 ++rci) {
+      const CodeGenRegisterClass &RC =3D *RegisterClasses[rci];
+      OS << "    {\t// " << RC.getName() << "\n";
+      for (unsigned sri =3D 0, sre =3D SubRegIndices.size(); sri !=3D sre;=
 ++sri) {
+        CodeGenSubRegIndex *Idx =3D SubRegIndices[sri];
+        BV.reset();
+        RC.getSuperRegClasses(Idx, BV);
+        OS << "      { ";
+        printBitVectorAsHex(OS, BV, 32);
+        OS << "},\t// " << Idx->getName() << '\n';
+      }
+      OS << "    },\n";
+    }
+    OS << "  };\n  assert(A && B && \"Missing regclass\");\n"
+       << "  --Idx;\n"
+       << "  assert(Idx < " << SubRegIndices.size() << " && \"Bad subreg\"=
);\n"
+       << "  const uint32_t *TV =3D Table[B->getID()][Idx];\n"
+       << "  const uint32_t *SC =3D A->getSubClassMask();\n"
+       << "  for (unsigned i =3D 0; i !=3D " << BVWords << "; ++i)\n"
+       << "    if (unsigned Common =3D TV[i] & SC[i])\n"
+       << "      return getRegClass(32*i + CountTrailingZeros_32(Common));=
\n"
+       << "  return 0;\n";
+  }
+  OS << "}\n\n";
+
+  EmitRegUnitPressure(OS, RegBank, ClassName);
+
   // Emit the constructor of the class...
-  OS << "extern MCRegisterDesc " << TargetName << "RegDesc[];\n";
+  OS << "extern const MCRegisterDesc " << TargetName << "RegDesc[];\n";
+  OS << "extern const uint16_t " << TargetName << "RegLists[];\n";
+  if (SubRegIndices.size() !=3D 0)
+    OS << "extern const uint16_t *get" << TargetName
+       << "SubRegTable();\n";
=20
-  OS << ClassName << "::" << ClassName
+  EmitRegMappingTables(OS, Regs, true);
+
+  OS << ClassName << "::\n" << ClassName
      << "(unsigned RA, unsigned DwarfFlavour, unsigned EHFlavour)\n"
      << "  : TargetRegisterInfo(" << TargetName << "RegInfoDesc"
      << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<=
",\n"
-     << "                 " << TargetName << "SubRegIndexTable) {\n"
+     << "             " << TargetName << "SubRegIndexTable) {\n"
      << "  InitMCRegisterInfo(" << TargetName << "RegDesc, "
-     << Regs.size()+1 << ", RA, " << TargetName << "MCRegisterClasses, "
-     << RegisterClasses.size() << ");\n\n";
+     << Regs.size()+1 << ", RA,\n                     " << TargetName
+     << "MCRegisterClasses, " << RegisterClasses.size() << ",\n"
+     << "                     " << TargetName << "RegLists,\n"
+     << "                     ";
+  if (SubRegIndices.size() !=3D 0)
+    OS << "get" << TargetName << "SubRegTable(), "
+       << SubRegIndices.size() << ");\n\n";
+  else
+    OS << "NULL, 0);\n\n";
=20
   EmitRegMapping(OS, Regs, true);
=20
   OS << "}\n\n";
=20
+
+  // Emit CalleeSavedRegs information.
+  std::vector<Record*> CSRSets =3D
+    Records.getAllDerivedDefinitions("CalleeSavedRegs");
+  for (unsigned i =3D 0, e =3D CSRSets.size(); i !=3D e; ++i) {
+    Record *CSRSet =3D CSRSets[i];
+    const SetTheory::RecVec *Regs =3D RegBank.getSets().expand(CSRSet);
+    assert(Regs && "Cannot expand CalleeSavedRegs instance");
+
+    // Emit the *_SaveList list of callee-saved registers.
+    OS << "static const uint16_t " << CSRSet->getName()
+       << "_SaveList[] =3D { ";
+    for (unsigned r =3D 0, re =3D Regs->size(); r !=3D re; ++r)
+      OS << getQualifiedName((*Regs)[r]) << ", ";
+    OS << "0 };\n";
+
+    // Emit the *_RegMask bit mask of call-preserved registers.
+    OS << "static const uint32_t " << CSRSet->getName()
+       << "_RegMask[] =3D { ";
+    printBitVectorAsHex(OS, RegBank.computeCoveredRegisters(*Regs), 32);
+    OS << "};\n";
+  }
+  OS << "\n\n";
+
   OS << "} // End llvm namespace \n";
   OS << "#endif // GET_REGINFO_TARGET_DESC\n\n";
 }
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Regis=
terInfoEmitter.h
--- a/head/contrib/llvm/utils/TableGen/RegisterInfoEmitter.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/RegisterInfoEmitter.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -50,7 +50,13 @@
 private:
   void EmitRegMapping(raw_ostream &o,
                       const std::vector<CodeGenRegister*> &Regs, bool isCt=
or);
+  void EmitRegMappingTables(raw_ostream &o,
+                            const std::vector<CodeGenRegister*> &Regs,
+                            bool isCtor);
   void EmitRegClasses(raw_ostream &OS, CodeGenTarget &Target);
+
+  void EmitRegUnitPressure(raw_ostream &OS, const CodeGenRegBank &RegBank,
+                           const std::string &ClassName);
 };
=20
 } // End llvm namespace
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/SetTh=
eory.cpp
--- a/head/contrib/llvm/utils/TableGen/SetTheory.cpp	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/contrib/llvm/utils/TableGen/SetTheory.cpp	Tue Apr 17 11:51:51 20=
12 +0300
@@ -139,6 +139,24 @@
   }
 };
=20
+// (interleave S1, S2, ...) Interleave elements of the arguments.
+struct InterleaveOp : public SetTheory::Operator {
+  void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
+    // Evaluate the arguments individually.
+    SmallVector<RecSet, 4> Args(Expr->getNumArgs());
+    unsigned MaxSize =3D 0;
+    for (unsigned i =3D 0, e =3D Expr->getNumArgs(); i !=3D e; ++i) {
+      ST.evaluate(Expr->getArg(i), Args[i]);
+      MaxSize =3D std::max(MaxSize, unsigned(Args[i].size()));
+    }
+    // Interleave arguments into Elts.
+    for (unsigned n =3D 0; n !=3D MaxSize; ++n)
+      for (unsigned i =3D 0, e =3D Expr->getNumArgs(); i !=3D e; ++i)
+        if (n < Args[i].size())
+          Elts.insert(Args[i][n]);
+  }
+};
+
 // (sequence "Format", From, To) Generate a sequence of records by name.
 struct SequenceOp : public SetTheory::Operator {
   void apply(SetTheory &ST, DagInit *Expr, RecSet &Elts) {
@@ -198,6 +216,10 @@
 };
 } // end anonymous namespace
=20
+void SetTheory::Operator::anchor() { }
+
+void SetTheory::Expander::anchor() { }
+
 SetTheory::SetTheory() {
   addOperator("add", new AddOp);
   addOperator("sub", new SubOp);
@@ -207,6 +229,7 @@
   addOperator("rotl", new RotOp(false));
   addOperator("rotr", new RotOp(true));
   addOperator("decimate", new DecimateOp);
+  addOperator("interleave", new InterleaveOp);
   addOperator("sequence", new SequenceOp);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/SetTh=
eory.h
--- a/head/contrib/llvm/utils/TableGen/SetTheory.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/llvm/utils/TableGen/SetTheory.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -65,7 +65,9 @@
   typedef SmallSetVector<Record*, 16> RecSet;
=20
   /// Operator - A callback representing a DAG operator.
-  struct Operator {
+  class Operator {
+    virtual void anchor();
+  public:
     virtual ~Operator() {}
=20
     /// apply - Apply this operator to Expr's arguments and insert the res=
ult
@@ -76,7 +78,9 @@
   /// Expander - A callback function that can transform a Record represent=
ing a
   /// set into a fully expanded list of elements. Expanders provide a way =
for
   /// users to define named sets that can be used in DAG expressions.
-  struct Expander {
+  class Expander {
+    virtual void anchor();
+  public:
     virtual ~Expander() {}
=20
     virtual void expand(SetTheory&, Record*, RecSet &Elts) =3D0;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Strin=
gToOffsetTable.h
--- a/head/contrib/llvm/utils/TableGen/StringToOffsetTable.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/StringToOffsetTable.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -26,16 +26,17 @@
   std::string AggregateString;
 public:
  =20
-  unsigned GetOrAddStringOffset(StringRef Str) {
-    unsigned &Entry =3D StringOffset[Str];
-    if (Entry =3D=3D 0) {
+  unsigned GetOrAddStringOffset(StringRef Str, bool appendZero =3D true) {
+    StringMapEntry<unsigned> &Entry =3D StringOffset.GetOrCreateValue(Str,=
 -1U);
+    if (Entry.getValue() =3D=3D -1U) {
       // Add the string to the aggregate if this is the first time found.
-      Entry =3D AggregateString.size();
+      Entry.setValue(AggregateString.size());
       AggregateString.append(Str.begin(), Str.end());
-      AggregateString +=3D '\0';
+      if (appendZero)
+        AggregateString +=3D '\0';
     }
    =20
-    return Entry;
+    return Entry.getValue();
   }
  =20
   void EmitString(raw_ostream &O) {
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Subta=
rgetEmitter.cpp
--- a/head/contrib/llvm/utils/TableGen/SubtargetEmitter.cpp	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/SubtargetEmitter.cpp	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -39,29 +39,42 @@
=20
   OS << "namespace " << Target << " {\n";
=20
-  // Open enumeration
-  OS << "enum {\n";
+  // For bit flag enumerations with more than 32 items, emit constants.
+  // Emit an enum for everything else.
+  if (isBits && N > 32) {
+    // For each record
+    for (unsigned i =3D 0; i < N; i++) {
+      // Next record
+      Record *Def =3D DefList[i];
=20
-  // For each record
-  for (unsigned i =3D 0; i < N;) {
-    // Next record
-    Record *Def =3D DefList[i];
+      // Get and emit name and expression (1 << i)
+      OS << "  const uint64_t " << Def->getName() << " =3D 1ULL << " << i =
<< ";\n";
+    }
+  } else {
+    // Open enumeration
+    OS << "enum {\n";
=20
-    // Get and emit name
-    OS << "  " << Def->getName();
+    // For each record
+    for (unsigned i =3D 0; i < N;) {
+      // Next record
+      Record *Def =3D DefList[i];
=20
-    // If bit flags then emit expression (1 << i)
-    if (isBits)  OS << " =3D " << " 1ULL << " << i;
+      // Get and emit name
+      OS << "  " << Def->getName();
=20
-    // Depending on 'if more in the list' emit comma
-    if (++i < N) OS << ",";
+      // If bit flags then emit expression (1 << i)
+      if (isBits)  OS << " =3D " << " 1ULL << " << i;
=20
-    OS << "\n";
+      // Depending on 'if more in the list' emit comma
+      if (++i < N) OS << ",";
+
+      OS << "\n";
+    }
+
+    // Close enumeration
+    OS << "};\n";
   }
=20
-  // Close enumeration
-  OS << "};\n";
-
   OS << "}\n";
 }
=20
@@ -81,7 +94,8 @@
=20
   // Begin feature table
   OS << "// Sorted (by key) array of values for CPU features.\n"
-     << "llvm::SubtargetFeatureKV " << Target << "FeatureKV[] =3D {\n";
+     << "extern const llvm::SubtargetFeatureKV " << Target
+     << "FeatureKV[] =3D {\n";
=20
   // For each feature
   unsigned NumFeatures =3D 0;
@@ -140,7 +154,8 @@
=20
   // Begin processor table
   OS << "// Sorted (by key) array of values for CPU subtype.\n"
-     << "llvm::SubtargetFeatureKV " << Target << "SubTypeKV[] =3D {\n";
+     << "extern const llvm::SubtargetFeatureKV " << Target
+     << "SubTypeKV[] =3D {\n";
=20
   // For each processor
   for (unsigned i =3D 0, N =3D ProcessorList.size(); i < N;) {
@@ -327,9 +342,9 @@
       OS << "\n// Pipeline forwarding pathes for itineraries \"" << Name
          << "\"\n" << "namespace " << Name << "Bypass {\n";
=20
-      OS << "  unsigned NoBypass =3D 0;\n";
+      OS << "  const unsigned NoBypass =3D 0;\n";
       for (unsigned j =3D 0, BPN =3D BPs.size(); j < BPN; ++j)
-        OS << "  unsigned " << BPs[j]->getName()
+        OS << "  const unsigned " << BPs[j]->getName()
            << " =3D 1 << " << j << ";\n";
=20
       OS << "}\n";
@@ -337,16 +352,17 @@
   }
=20
   // Begin stages table
-  std::string StageTable =3D "\nllvm::InstrStage " + Target + "Stages[] =
=3D {\n";
+  std::string StageTable =3D "\nextern const llvm::InstrStage " + Target +
+                           "Stages[] =3D {\n";
   StageTable +=3D "  { 0, 0, 0, llvm::InstrStage::Required }, // No itiner=
ary\n";
=20
   // Begin operand cycle table
-  std::string OperandCycleTable =3D "unsigned " + Target +
+  std::string OperandCycleTable =3D "extern const unsigned " + Target +
     "OperandCycles[] =3D {\n";
   OperandCycleTable +=3D "  0, // No itinerary\n";
=20
   // Begin pipeline bypass table
-  std::string BypassTable =3D "unsigned " + Target +
+  std::string BypassTable =3D "extern const unsigned " + Target +
     "ForwardingPathes[] =3D {\n";
   BypassTable +=3D "  0, // No itinerary\n";
=20
@@ -488,7 +504,7 @@
=20
     // Begin processor itinerary table
     OS << "\n";
-    OS << "llvm::InstrItinerary " << Name << "[] =3D {\n";
+    OS << "static const llvm::InstrItinerary " << Name << "[] =3D {\n";
=20
     // For each itinerary class
     std::vector<InstrItinerary> &ItinList =3D *ProcListIter++;
@@ -530,7 +546,7 @@
   // Begin processor table
   OS << "\n";
   OS << "// Sorted (by key) array of itineraries for CPU subtype.\n"
-     << "llvm::SubtargetInfoKV "
+     << "extern const llvm::SubtargetInfoKV "
      << Target << "ProcItinKV[] =3D {\n";
=20
   // For each processor
@@ -708,9 +724,13 @@
=20
   std::string ClassName =3D Target + "GenSubtargetInfo";
   OS << "namespace llvm {\n";
+  OS << "class DFAPacketizer;\n";
   OS << "struct " << ClassName << " : public TargetSubtargetInfo {\n"
      << "  explicit " << ClassName << "(StringRef TT, StringRef CPU, "
      << "StringRef FS);\n"
+     << "public:\n"
+     << "  DFAPacketizer *createDFAPacketizer(const InstrItineraryData *II=
D)"
+     << " const;\n"
      << "};\n";
   OS << "} // End llvm namespace \n";
=20
@@ -720,13 +740,13 @@
   OS << "#undef GET_SUBTARGETINFO_CTOR\n";
=20
   OS << "namespace llvm {\n";
-  OS << "extern llvm::SubtargetFeatureKV " << Target << "FeatureKV[];\n";
-  OS << "extern llvm::SubtargetFeatureKV " << Target << "SubTypeKV[];\n";
+  OS << "extern const llvm::SubtargetFeatureKV " << Target << "FeatureKV[]=
;\n";
+  OS << "extern const llvm::SubtargetFeatureKV " << Target << "SubTypeKV[]=
;\n";
   if (HasItineraries) {
-    OS << "extern llvm::SubtargetInfoKV " << Target << "ProcItinKV[];\n";
-    OS << "extern llvm::InstrStage " << Target << "Stages[];\n";
-    OS << "extern unsigned " << Target << "OperandCycles[];\n";
-    OS << "extern unsigned " << Target << "ForwardingPathes[];\n";
+    OS << "extern const llvm::SubtargetInfoKV " << Target << "ProcItinKV[]=
;\n";
+    OS << "extern const llvm::InstrStage " << Target << "Stages[];\n";
+    OS << "extern const unsigned " << Target << "OperandCycles[];\n";
+    OS << "extern const unsigned " << Target << "ForwardingPathes[];\n";
   }
=20
   OS << ClassName << "::" << ClassName << "(StringRef TT, StringRef CPU, "
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/Table=
Gen.cpp
--- a/head/contrib/llvm/utils/TableGen/TableGen.cpp	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/contrib/llvm/utils/TableGen/TableGen.cpp	Tue Apr 17 11:51:51 201=
2 +0300
@@ -16,6 +16,7 @@
 #include "CallingConvEmitter.h"
 #include "CodeEmitterGen.h"
 #include "DAGISelEmitter.h"
+#include "DFAPacketizerEmitter.h"
 #include "DisassemblerEmitter.h"
 #include "EDEmitter.h"
 #include "FastISelEmitter.h"
@@ -23,7 +24,6 @@
 #include "IntrinsicEmitter.h"
 #include "PseudoLoweringEmitter.h"
 #include "RegisterInfoEmitter.h"
-#include "ARMDecoderEmitter.h"
 #include "SubtargetEmitter.h"
 #include "SetTheory.h"
=20
@@ -44,11 +44,11 @@
   GenInstrInfo,
   GenAsmWriter,
   GenAsmMatcher,
-  GenARMDecoder,
   GenDisassembler,
   GenPseudoLowering,
   GenCallingConv,
   GenDAGISel,
+  GenDFAPacketizer,
   GenFastISel,
   GenSubtarget,
   GenIntrinsic,
@@ -73,8 +73,6 @@
                                "Generate calling convention descriptions"),
                     clEnumValN(GenAsmWriter, "gen-asm-writer",
                                "Generate assembly writer"),
-                    clEnumValN(GenARMDecoder, "gen-arm-decoder",
-                               "Generate decoders for ARM/Thumb"),
                     clEnumValN(GenDisassembler, "gen-disassembler",
                                "Generate disassembler"),
                     clEnumValN(GenPseudoLowering, "gen-pseudo-lowering",
@@ -83,6 +81,8 @@
                                "Generate assembly instruction matcher"),
                     clEnumValN(GenDAGISel, "gen-dag-isel",
                                "Generate a DAG instruction selector"),
+                    clEnumValN(GenDFAPacketizer, "gen-dfa-packetizer",
+                               "Generate DFA Packetizer for VLIW targets"),
                     clEnumValN(GenFastISel, "gen-fast-isel",
                                "Generate a \"fast\" instruction selector"),
                     clEnumValN(GenSubtarget, "gen-subtarget",
@@ -101,93 +101,90 @@
=20
   cl::opt<std::string>
   Class("class", cl::desc("Print Enum list for this class"),
-        cl::value_desc("class name"));
+          cl::value_desc("class name"));
+ =20
+  class LLVMTableGenAction : public TableGenAction {
+  public:
+    bool operator()(raw_ostream &OS, RecordKeeper &Records) {
+      switch (Action) {
+      case PrintRecords:
+        OS << Records;           // No argument, dump all contents
+        break;
+      case GenEmitter:
+        CodeEmitterGen(Records).run(OS);
+        break;
+      case GenRegisterInfo:
+        RegisterInfoEmitter(Records).run(OS);
+        break;
+      case GenInstrInfo:
+        InstrInfoEmitter(Records).run(OS);
+        break;
+      case GenCallingConv:
+        CallingConvEmitter(Records).run(OS);
+        break;
+      case GenAsmWriter:
+        AsmWriterEmitter(Records).run(OS);
+        break;
+      case GenAsmMatcher:
+        AsmMatcherEmitter(Records).run(OS);
+        break;
+      case GenDisassembler:
+        DisassemblerEmitter(Records).run(OS);
+        break;
+      case GenPseudoLowering:
+        PseudoLoweringEmitter(Records).run(OS);
+        break;
+      case GenDAGISel:
+        DAGISelEmitter(Records).run(OS);
+        break;
+      case GenDFAPacketizer:
+        DFAGen(Records).run(OS);
+        break;
+      case GenFastISel:
+        FastISelEmitter(Records).run(OS);
+        break;
+      case GenSubtarget:
+        SubtargetEmitter(Records).run(OS);
+        break;
+      case GenIntrinsic:
+        IntrinsicEmitter(Records).run(OS);
+        break;
+      case GenTgtIntrinsic:
+        IntrinsicEmitter(Records, true).run(OS);
+        break;
+      case GenEDInfo:
+        EDEmitter(Records).run(OS);
+        break;
+      case PrintEnums:
+      {
+        std::vector<Record*> Recs =3D Records.getAllDerivedDefinitions(Cla=
ss);
+        for (unsigned i =3D 0, e =3D Recs.size(); i !=3D e; ++i)
+          OS << Recs[i]->getName() << ", ";
+        OS << "\n";
+        break;
+      }
+      case PrintSets:
+      {
+        SetTheory Sets;
+        Sets.addFieldExpander("Set", "Elements");
+        std::vector<Record*> Recs =3D Records.getAllDerivedDefinitions("Se=
t");
+        for (unsigned i =3D 0, e =3D Recs.size(); i !=3D e; ++i) {
+          OS << Recs[i]->getName() << " =3D [";
+          const std::vector<Record*> *Elts =3D Sets.expand(Recs[i]);
+          assert(Elts && "Couldn't expand Set instance");
+          for (unsigned ei =3D 0, ee =3D Elts->size(); ei !=3D ee; ++ei)
+            OS << ' ' << (*Elts)[ei]->getName();
+          OS << " ]\n";
+        }
+        break;
+      }
+      }
+ =20
+      return false;
+    }
+  };
 }
=20
-class LLVMTableGenAction : public TableGenAction {
-public:
-  bool operator()(raw_ostream &OS, RecordKeeper &Records) {
-    switch (Action) {
-    case PrintRecords:
-      OS << Records;           // No argument, dump all contents
-      break;
-    case GenEmitter:
-      CodeEmitterGen(Records).run(OS);
-      break;
-    case GenRegisterInfo:
-      RegisterInfoEmitter(Records).run(OS);
-      break;
-    case GenInstrInfo:
-      InstrInfoEmitter(Records).run(OS);
-      break;
-    case GenCallingConv:
-      CallingConvEmitter(Records).run(OS);
-      break;
-    case GenAsmWriter:
-      AsmWriterEmitter(Records).run(OS);
-      break;
-    case GenARMDecoder:
-      ARMDecoderEmitter(Records).run(OS);
-      break;
-    case GenAsmMatcher:
-      AsmMatcherEmitter(Records).run(OS);
-      break;
-    case GenDisassembler:
-      DisassemblerEmitter(Records).run(OS);
-      break;
-    case GenPseudoLowering:
-      PseudoLoweringEmitter(Records).run(OS);
-      break;
-    case GenDAGISel:
-      DAGISelEmitter(Records).run(OS);
-      break;
-    case GenFastISel:
-      FastISelEmitter(Records).run(OS);
-      break;
-    case GenSubtarget:
-      SubtargetEmitter(Records).run(OS);
-      break;
-    case GenIntrinsic:
-      IntrinsicEmitter(Records).run(OS);
-      break;
-    case GenTgtIntrinsic:
-      IntrinsicEmitter(Records, true).run(OS);
-      break;
-    case GenEDInfo:
-      EDEmitter(Records).run(OS);
-      break;
-    case PrintEnums:
-    {
-      std::vector<Record*> Recs =3D Records.getAllDerivedDefinitions(Class=
);
-      for (unsigned i =3D 0, e =3D Recs.size(); i !=3D e; ++i)
-        OS << Recs[i]->getName() << ", ";
-      OS << "\n";
-      break;
-    }
-    case PrintSets:
-    {
-      SetTheory Sets;
-      Sets.addFieldExpander("Set", "Elements");
-      std::vector<Record*> Recs =3D Records.getAllDerivedDefinitions("Set"=
);
-      for (unsigned i =3D 0, e =3D Recs.size(); i !=3D e; ++i) {
-        OS << Recs[i]->getName() << " =3D [";
-        const std::vector<Record*> *Elts =3D Sets.expand(Recs[i]);
-        assert(Elts && "Couldn't expand Set instance");
-        for (unsigned ei =3D 0, ee =3D Elts->size(); ei !=3D ee; ++ei)
-          OS << ' ' << (*Elts)[ei]->getName();
-        OS << " ]\n";
-      }
-      break;
-    }
-    default:
-      assert(1 && "Invalid Action");
-      return true;
-    }
-
-    return false;
-  }
-};
-
 int main(int argc, char **argv) {
   sys::PrintStackTraceOnErrorSignal();
   PrettyStackTraceProgram X(argc, argv);
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/X86Di=
sassemblerTables.cpp
--- a/head/contrib/llvm/utils/TableGen/X86DisassemblerTables.cpp	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/X86DisassemblerTables.cpp	Tue Apr 17=
 11:51:51 2012 +0300
@@ -41,15 +41,20 @@
   case IC:
     return(inheritsFrom(child, IC_64BIT) ||
            inheritsFrom(child, IC_OPSIZE) ||
+           inheritsFrom(child, IC_ADSIZE) ||
            inheritsFrom(child, IC_XD) ||
            inheritsFrom(child, IC_XS));
   case IC_64BIT:
     return(inheritsFrom(child, IC_64BIT_REXW)   ||
            inheritsFrom(child, IC_64BIT_OPSIZE) ||
+           inheritsFrom(child, IC_64BIT_ADSIZE) ||
            inheritsFrom(child, IC_64BIT_XD)     ||
            inheritsFrom(child, IC_64BIT_XS));
   case IC_OPSIZE:
     return inheritsFrom(child, IC_64BIT_OPSIZE);
+  case IC_ADSIZE:
+  case IC_64BIT_ADSIZE:
+    return false;
   case IC_XD:
     return inheritsFrom(child, IC_64BIT_XD);
   case IC_XS:
@@ -95,11 +100,13 @@
   case IC_VEX_L:
   case IC_VEX_L_XS:
   case IC_VEX_L_XD:
+    return false;
   case IC_VEX_L_OPSIZE:
+    return inheritsFrom(child, IC_VEX_L_W_OPSIZE);
+  case IC_VEX_L_W_OPSIZE:
     return false;
   default:
     llvm_unreachable("Unknown instruction class");
-    return false;
   }
 }
=20
@@ -138,8 +145,6 @@
   INSTRUCTION_CONTEXTS
 #undef ENUM_ENTRY
   }
-
-  return 0;
 }
=20
 /// stringForOperandType - Like stringForContext, but for OperandTypes.
@@ -194,8 +199,7 @@
 /// @param i        - The indentation level for that output stream.
 static void emitEmptyTable(raw_ostream &o, uint32_t &i)
 {
-  o.indent(i * 2) << "static const InstrUID modRMEmptyTable[1] =3D { 0 };\=
n";
-  o << "\n";
+  o.indent(i * 2) << "0x0, /* EmptyTable */\n";
 }
=20
 /// getDecisionType - Determines whether a ModRM decision with 255 entries=
 can
@@ -207,28 +211,40 @@
 {
   bool satisfiesOneEntry =3D true;
   bool satisfiesSplitRM =3D true;
- =20
+  bool satisfiesSplitReg =3D true;
+
   uint16_t index;
- =20
+
   for (index =3D 0; index < 256; ++index) {
     if (decision.instructionIDs[index] !=3D decision.instructionIDs[0])
       satisfiesOneEntry =3D false;
-   =20
+
     if (((index & 0xc0) =3D=3D 0xc0) &&
        (decision.instructionIDs[index] !=3D decision.instructionIDs[0xc0]))
       satisfiesSplitRM =3D false;
-   =20
+
     if (((index & 0xc0) !=3D 0xc0) &&
        (decision.instructionIDs[index] !=3D decision.instructionIDs[0x00]))
       satisfiesSplitRM =3D false;
+
+    if (((index & 0xc0) =3D=3D 0xc0) &&
+       (decision.instructionIDs[index] !=3D decision.instructionIDs[index&=
0xf8]))
+      satisfiesSplitReg =3D false;
+
+    if (((index & 0xc0) !=3D 0xc0) &&
+       (decision.instructionIDs[index] !=3D decision.instructionIDs[index&=
0x38]))
+      satisfiesSplitReg =3D false;
   }
- =20
+
   if (satisfiesOneEntry)
     return MODRM_ONEENTRY;
- =20
+
   if (satisfiesSplitRM)
     return MODRM_SPLITRM;
- =20
+
+  if (satisfiesSplitReg)
+    return MODRM_SPLITREG;
+
   return MODRM_FULL;
 }
=20
@@ -291,71 +307,76 @@
                                            ModRMDecision &decision)
   const {
   static uint64_t sTableNumber =3D 0;
-  uint64_t thisTableNumber =3D sTableNumber;
+  static uint64_t sEntryNumber =3D 1;
   ModRMDecisionType dt =3D getDecisionType(decision);
   uint16_t index;
- =20
+
   if (dt =3D=3D MODRM_ONEENTRY && decision.instructionIDs[0] =3D=3D 0)
   {
     o2.indent(i2) << "{ /* ModRMDecision */" << "\n";
     i2++;
-   =20
+
     o2.indent(i2) << stringForDecisionType(dt) << "," << "\n";
-    o2.indent(i2) << "modRMEmptyTable";
-   =20
+    o2.indent(i2) << 0 << " /* EmptyTable */\n";
+
     i2--;
     o2.indent(i2) << "}";
     return;
   }
-   =20
-  o1.indent(i1) << "static const InstrUID modRMTable" << thisTableNumber;
-   =20
+
+  o1 << "/* Table" << sTableNumber << " */\n";
+  i1++;
+
   switch (dt) {
     default:
       llvm_unreachable("Unknown decision type");
     case MODRM_ONEENTRY:
-      o1 << "[1]";
+      emitOneID(o1, i1, decision.instructionIDs[0], true);
       break;
     case MODRM_SPLITRM:
-      o1 << "[2]";
+      emitOneID(o1, i1, decision.instructionIDs[0x00], true); // mod =3D 0=
b00
+      emitOneID(o1, i1, decision.instructionIDs[0xc0], true); // mod =3D 0=
b11
+      break;
+    case MODRM_SPLITREG:
+      for (index =3D 0; index < 64; index +=3D 8)
+        emitOneID(o1, i1, decision.instructionIDs[index], true);
+      for (index =3D 0xc0; index < 256; index +=3D 8)
+        emitOneID(o1, i1, decision.instructionIDs[index], true);
       break;
     case MODRM_FULL:
-      o1 << "[256]";
-      break;     =20
+      for (index =3D 0; index < 256; ++index)
+        emitOneID(o1, i1, decision.instructionIDs[index], true);
+      break;
   }
=20
-  o1 << " =3D {" << "\n";
-  i1++;
-   =20
+  i1--;
+
+  o2.indent(i2) << "{ /* struct ModRMDecision */" << "\n";
+  i2++;
+
+  o2.indent(i2) << stringForDecisionType(dt) << "," << "\n";
+  o2.indent(i2) << sEntryNumber << " /* Table" << sTableNumber << " */\n";
+
+  i2--;
+  o2.indent(i2) << "}";
+
   switch (dt) {
     default:
       llvm_unreachable("Unknown decision type");
     case MODRM_ONEENTRY:
-      emitOneID(o1, i1, decision.instructionIDs[0], false);
+      sEntryNumber +=3D 1;
       break;
     case MODRM_SPLITRM:
-      emitOneID(o1, i1, decision.instructionIDs[0x00], true); // mod =3D 0=
b00
-      emitOneID(o1, i1, decision.instructionIDs[0xc0], false); // mod =3D =
0b11
+      sEntryNumber +=3D 2;
+      break;
+    case MODRM_SPLITREG:
+      sEntryNumber +=3D 16;
       break;
     case MODRM_FULL:
-      for (index =3D 0; index < 256; ++index)
-        emitOneID(o1, i1, decision.instructionIDs[index], index < 255);
+      sEntryNumber +=3D 256;
       break;
   }
-   =20
-  i1--;
-  o1.indent(i1) << "};" << "\n";
-  o1 << "\n";
-   =20
-  o2.indent(i2) << "{ /* struct ModRMDecision */" << "\n";
-  i2++;
-   =20
-  o2.indent(i2) << stringForDecisionType(dt) << "," << "\n";
-  o2.indent(i2) << "modRMTable" << sTableNumber << "\n";
-   =20
-  i2--;
-  o2.indent(i2) << "}";
-   =20
+
   ++sTableNumber;
 }
=20
@@ -436,11 +457,11 @@
   for (index =3D 0; index < numInstructions; ++index) {
     o.indent(i * 2) << "{ /* " << index << " */" << "\n";
     i++;
-   =20
-    o.indent(i * 2) <<=20
-      stringForModifierType(InstructionSpecifiers[index].modifierType);
+
+    o.indent(i * 2) << stringForModifierType(
+                       (ModifierType)InstructionSpecifiers[index].modifier=
Type);
     o << "," << "\n";
-   =20
+
     o.indent(i * 2) << "0x";
     o << format("%02hhx", (uint16_t)InstructionSpecifiers[index].modifierB=
ase);
     o << "," << "\n";
@@ -450,11 +471,11 @@
=20
     for (operandIndex =3D 0; operandIndex < X86_MAX_OPERANDS; ++operandInd=
ex) {
       o.indent(i * 2) << "{ ";
-      o << stringForOperandEncoding(InstructionSpecifiers[index]
-                                    .operands[operandIndex]
-                                    .encoding);
+      o <<stringForOperandEncoding((OperandEncoding)InstructionSpecifiers[=
index]
+                                   .operands[operandIndex]
+                                   .encoding);
       o << ", ";
-      o << stringForOperandType(InstructionSpecifiers[index]
+      o << stringForOperandType((OperandType)InstructionSpecifiers[index]
                                 .operands[operandIndex]
                                 .type);
       o << " }";
@@ -468,7 +489,7 @@
     i--;
     o.indent(i * 2) << "}," << "\n";
    =20
-    o.indent(i * 2) << "\"" << InstructionSpecifiers[index].name << "\"";
+    o.indent(i * 2) << "/* " << InstructionSpecifiers[index].name << " */";
     o << "\n";
=20
     i--;
@@ -494,7 +515,9 @@
   for (index =3D 0; index < 256; ++index) {
     o.indent(i * 2);
=20
-    if ((index & ATTR_VEXL) && (index & ATTR_OPSIZE))
+    if ((index & ATTR_VEXL) && (index & ATTR_REXW) && (index & ATTR_OPSIZE=
))
+      o << "IC_VEX_L_W_OPSIZE";
+    else if ((index & ATTR_VEXL) && (index & ATTR_OPSIZE))
       o << "IC_VEX_L_OPSIZE";
     else if ((index & ATTR_VEXL) && (index & ATTR_XD))
       o << "IC_VEX_L_XD";
@@ -535,6 +558,8 @@
       o << "IC_64BIT_XD";
     else if ((index & ATTR_64BIT) && (index & ATTR_OPSIZE))
       o << "IC_64BIT_OPSIZE";
+    else if ((index & ATTR_64BIT) && (index & ATTR_ADSIZE))
+      o << "IC_64BIT_ADSIZE";
     else if ((index & ATTR_64BIT) && (index & ATTR_REXW))
       o << "IC_64BIT_REXW";
     else if ((index & ATTR_64BIT))
@@ -549,6 +574,8 @@
       o << "IC_XD";
     else if (index & ATTR_OPSIZE)
       o << "IC_OPSIZE";
+    else if (index & ATTR_ADSIZE)
+      o << "IC_ADSIZE";
     else
       o << "IC";
=20
@@ -594,11 +621,16 @@
=20
   emitContextTable(o, i2);
   o << "\n";
- =20
+
+  o << "static const InstrUID modRMTable[] =3D {\n";
+  i1++;
   emitEmptyTable(o1, i1);
+  i1--;
   emitContextDecisions(o1, o2, i1, i2);
- =20
+
   o << o1.str();
+  o << "  0x0\n";
+  o << "};\n";
   o << "\n";
   o << o2.str();
   o << "\n";
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/X86Mo=
dRMFilters.h
--- a/head/contrib/llvm/utils/TableGen/X86ModRMFilters.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/X86ModRMFilters.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -27,6 +27,7 @@
 /// ModRMFilter - Abstract base class for clases that recognize patterns in
 ///   ModR/M bytes.
 class ModRMFilter {
+  virtual void anchor();
 public:
   /// Destructor    - Override as necessary.
   virtual ~ModRMFilter() { }
@@ -49,6 +50,7 @@
 ///   require a ModR/M byte or instructions where the entire ModR/M byte i=
s used
 ///   for operands.
 class DumbFilter : public ModRMFilter {
+  virtual void anchor();
 public:
   bool isDumb() const {
     return true;
@@ -63,7 +65,7 @@
 ///   Some instructions are classified based on whether they are 11 or any=
thing
 ///   else.  This filter performs that classification.
 class ModFilter : public ModRMFilter {
-private:
+  virtual void anchor();
   bool R;
 public:
   /// Constructor
@@ -90,7 +92,7 @@
 ///   possible value.  Otherwise, there is one instruction for each value =
of the
 ///   nnn field [bits 5-3], known elsewhere as the reg field.
 class EscapeFilter : public ModRMFilter {
-private:
+  virtual void anchor();
   bool C0_FF;
   uint8_t NNN_or_ModRM;
 public:
@@ -121,7 +123,7 @@
 ///   maps to a single instruction.  Such instructions require the ModR/M =
byte
 ///   to fall between 0xc0 and 0xff.
 class AddRegEscapeFilter : public ModRMFilter {
-private:
+  virtual void anchor();
   uint8_t ModRM;
 public:
   /// Constructor
@@ -142,7 +144,7 @@
 /// ExtendedFilter - Extended opcodes are classified based on the value of=
 the
 ///   mod field [bits 7-6] and the value of the nnn field [bits 5-3].=20
 class ExtendedFilter : public ModRMFilter {
-private:
+  virtual void anchor();
   bool R;
   uint8_t NNN;
 public:
@@ -169,9 +171,8 @@
=20
 /// ExactFilter - The occasional extended opcode (such as VMCALL or MONITO=
R)
 ///   requires the ModR/M byte to have a specific value.
-class ExactFilter : public ModRMFilter
-{
-private:
+class ExactFilter : public ModRMFilter {
+  virtual void anchor();
   uint8_t ModRM;
 public:
   /// Constructor
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/X86Re=
cognizableInstr.cpp
--- a/head/contrib/llvm/utils/TableGen/X86RecognizableInstr.cpp	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/X86RecognizableInstr.cpp	Tue Apr 17 =
11:51:51 2012 +0300
@@ -36,7 +36,16 @@
   MAP(F8, 41)           \
   MAP(F9, 42)           \
   MAP(D0, 45)           \
-  MAP(D1, 46)
+  MAP(D1, 46)           \
+  MAP(D4, 47)           \
+  MAP(D8, 48)           \
+  MAP(D9, 49)           \
+  MAP(DA, 50)           \
+  MAP(DB, 51)           \
+  MAP(DC, 52)           \
+  MAP(DD, 53)           \
+  MAP(DE, 54)           \
+  MAP(DF, 55)
=20
 // A clone of X86 since we can't depend on something that is generated.
 namespace X86Local {
@@ -68,7 +77,7 @@
     DC =3D 7, DD =3D 8, DE =3D 9, DF =3D 10,
     XD =3D 11,  XS =3D 12,
     T8 =3D 13,  P_TA =3D 14,
-    A6 =3D 15,  A7 =3D 16, TF =3D 17
+    A6 =3D 15,  A7 =3D 16, T8XD =3D 17, T8XS =3D 18, TAXD =3D 19
   };
 }
=20
@@ -119,6 +128,9 @@
   EXTENSION_TABLE(ba)             \
   EXTENSION_TABLE(c7)
=20
+#define THREE_BYTE_38_EXTENSION_TABLES \
+  EXTENSION_TABLE(F3)
+
 using namespace X86Disassembler;
=20
 /// needsModRMForDecode - Indicates whether a particular instruction requi=
res a
@@ -213,10 +225,13 @@
   SegOvr   =3D byteFromRec(Rec, "SegOvrBits");
  =20
   HasOpSizePrefix  =3D Rec->getValueAsBit("hasOpSizePrefix");
+  HasAdSizePrefix  =3D Rec->getValueAsBit("hasAdSizePrefix");
   HasREX_WPrefix   =3D Rec->getValueAsBit("hasREX_WPrefix");
   HasVEXPrefix     =3D Rec->getValueAsBit("hasVEXPrefix");
   HasVEX_4VPrefix  =3D Rec->getValueAsBit("hasVEX_4VPrefix");
+  HasVEX_4VOp3Prefix =3D Rec->getValueAsBit("hasVEX_4VOp3Prefix");
   HasVEX_WPrefix   =3D Rec->getValueAsBit("hasVEX_WPrefix");
+  HasMemOp4Prefix  =3D Rec->getValueAsBit("hasMemOp4Prefix");
   IgnoresVEX_L     =3D Rec->getValueAsBit("ignoresVEX_L");
   HasLockPrefix    =3D Rec->getValueAsBit("hasLockPrefix");
   IsCodeGenOnly    =3D Rec->getValueAsBit("isCodeGenOnly");
@@ -230,7 +245,7 @@
                      (Name.find("CRC32") !=3D Name.npos);
   HasFROperands    =3D hasFROperands();
   HasVEX_LPrefix   =3D has256BitOperands() || Rec->getValueAsBit("hasVEX_L=
");
- =20
+
   // Check for 64-bit inst which does not require REX
   Is32Bit =3D false;
   Is64Bit =3D false;
@@ -254,10 +269,6 @@
              Rec->getName() =3D=3D "PUSHFS64" ||=20
              Rec->getName() =3D=3D "PUSHGS64" ||
              Rec->getName() =3D=3D "REX64_PREFIX" ||
-             Rec->getName().find("VMREAD64") !=3D Name.npos ||
-             Rec->getName().find("VMWRITE64") !=3D Name.npos ||
-             Rec->getName().find("INVEPT64") !=3D Name.npos ||
-             Rec->getName().find("INVVPID64") !=3D Name.npos ||
              Rec->getName().find("MOV64") !=3D Name.npos ||=20
              Rec->getName().find("PUSH64") !=3D Name.npos ||
              Rec->getName().find("POP64") !=3D Name.npos;
@@ -284,67 +295,90 @@
 InstructionContext RecognizableInstr::insnContext() const {
   InstructionContext insnContext;
=20
-  if (HasVEX_4VPrefix || HasVEXPrefix) {
-    if (HasVEX_LPrefix && HasVEX_WPrefix)
-      llvm_unreachable("Don't support VEX.L and VEX.W together");
-    else if (HasOpSizePrefix && HasVEX_LPrefix)
+  if (HasVEX_4VPrefix || HasVEX_4VOp3Prefix|| HasVEXPrefix) {
+    if (HasVEX_LPrefix && HasVEX_WPrefix) {
+      if (HasOpSizePrefix)
+        insnContext =3D IC_VEX_L_W_OPSIZE;
+      else
+        llvm_unreachable("Don't support VEX.L and VEX.W together");
+    } else if (HasOpSizePrefix && HasVEX_LPrefix)
       insnContext =3D IC_VEX_L_OPSIZE;
     else if (HasOpSizePrefix && HasVEX_WPrefix)
       insnContext =3D IC_VEX_W_OPSIZE;
     else if (HasOpSizePrefix)
       insnContext =3D IC_VEX_OPSIZE;
-    else if (HasVEX_LPrefix && Prefix =3D=3D X86Local::XS)
+    else if (HasVEX_LPrefix &&
+             (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS))
       insnContext =3D IC_VEX_L_XS;
-    else if (HasVEX_LPrefix && Prefix =3D=3D X86Local::XD)
+    else if (HasVEX_LPrefix && (Prefix =3D=3D X86Local::XD ||
+                                Prefix =3D=3D X86Local::T8XD ||
+                                Prefix =3D=3D X86Local::TAXD))
       insnContext =3D IC_VEX_L_XD;
-    else if (HasVEX_WPrefix && Prefix =3D=3D X86Local::XS)
+    else if (HasVEX_WPrefix &&
+             (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS))
       insnContext =3D IC_VEX_W_XS;
-    else if (HasVEX_WPrefix && Prefix =3D=3D X86Local::XD)
+    else if (HasVEX_WPrefix && (Prefix =3D=3D X86Local::XD ||
+                                Prefix =3D=3D X86Local::T8XD ||
+                                Prefix =3D=3D X86Local::TAXD))
       insnContext =3D IC_VEX_W_XD;
     else if (HasVEX_WPrefix)
       insnContext =3D IC_VEX_W;
     else if (HasVEX_LPrefix)
       insnContext =3D IC_VEX_L;
-    else if (Prefix =3D=3D X86Local::XD)
+    else if (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::T8XD ||
+             Prefix =3D=3D X86Local::TAXD)
       insnContext =3D IC_VEX_XD;
-    else if (Prefix =3D=3D X86Local::XS)
+    else if (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS)
       insnContext =3D IC_VEX_XS;
     else
       insnContext =3D IC_VEX;
   } else if (Is64Bit || HasREX_WPrefix) {
     if (HasREX_WPrefix && HasOpSizePrefix)
       insnContext =3D IC_64BIT_REXW_OPSIZE;
+    else if (HasOpSizePrefix && (Prefix =3D=3D X86Local::XD ||
+                                 Prefix =3D=3D X86Local::T8XD ||
+                                 Prefix =3D=3D X86Local::TAXD))
+      insnContext =3D IC_64BIT_XD_OPSIZE;
     else if (HasOpSizePrefix &&
-             (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::TF))
-      insnContext =3D IC_64BIT_XD_OPSIZE;
-    else if (HasOpSizePrefix && Prefix =3D=3D X86Local::XS)
+             (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS))
       insnContext =3D IC_64BIT_XS_OPSIZE;
     else if (HasOpSizePrefix)
       insnContext =3D IC_64BIT_OPSIZE;
-    else if (HasREX_WPrefix && Prefix =3D=3D X86Local::XS)
+    else if (HasAdSizePrefix)
+      insnContext =3D IC_64BIT_ADSIZE;
+    else if (HasREX_WPrefix &&
+             (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS))
       insnContext =3D IC_64BIT_REXW_XS;
-    else if (HasREX_WPrefix &&
-             (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::TF))
+    else if (HasREX_WPrefix && (Prefix =3D=3D X86Local::XD ||
+                                Prefix =3D=3D X86Local::T8XD ||
+                                Prefix =3D=3D X86Local::TAXD))
       insnContext =3D IC_64BIT_REXW_XD;
-    else if (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::TF)
+    else if (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::T8XD ||
+             Prefix =3D=3D X86Local::TAXD)
       insnContext =3D IC_64BIT_XD;
-    else if (Prefix =3D=3D X86Local::XS)
+    else if (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS)
       insnContext =3D IC_64BIT_XS;
     else if (HasREX_WPrefix)
       insnContext =3D IC_64BIT_REXW;
     else
       insnContext =3D IC_64BIT;
   } else {
-    if (HasOpSizePrefix &&
-        (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::TF))
+    if (HasOpSizePrefix && (Prefix =3D=3D X86Local::XD ||
+                            Prefix =3D=3D X86Local::T8XD ||
+                            Prefix =3D=3D X86Local::TAXD))
       insnContext =3D IC_XD_OPSIZE;
-    else if (HasOpSizePrefix && Prefix =3D=3D X86Local::XS)
+    else if (HasOpSizePrefix &&
+             (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS))
       insnContext =3D IC_XS_OPSIZE;
     else if (HasOpSizePrefix)
       insnContext =3D IC_OPSIZE;
-    else if (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::TF)
+    else if (HasAdSizePrefix)
+      insnContext =3D IC_ADSIZE;
+    else if (Prefix =3D=3D X86Local::XD || Prefix =3D=3D X86Local::T8XD ||
+             Prefix =3D=3D X86Local::TAXD)
       insnContext =3D IC_XD;
-    else if (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::REP)
+    else if (Prefix =3D=3D X86Local::XS || Prefix =3D=3D X86Local::T8XS ||
+             Prefix =3D=3D X86Local::REP)
       insnContext =3D IC_XS;
     else
       insnContext =3D IC;
@@ -371,19 +405,12 @@
     return FILTER_STRONG;
    =20
    =20
-  // Filter out artificial instructions
+  // Filter out artificial instructions but leave in the LOCK_PREFIX so it=
 is
+  // printed as a separate "instruction".
    =20
-  if (Name.find("TAILJMP") !=3D Name.npos    ||
-      Name.find("_Int") !=3D Name.npos       ||
-      Name.find("_int") !=3D Name.npos       ||
+  if (Name.find("_Int") !=3D Name.npos       ||
       Name.find("Int_") !=3D Name.npos       ||
       Name.find("_NOREX") !=3D Name.npos     ||
-      Name.find("_TC") !=3D Name.npos        ||
-      Name.find("EH_RETURN") !=3D Name.npos  ||
-      Name.find("V_SET") !=3D Name.npos      ||
-      Name.find("LOCK_") !=3D Name.npos      ||
-      Name.find("WIN") !=3D Name.npos        ||
-      Name.find("_AVX") !=3D Name.npos       ||
       Name.find("2SDL") !=3D Name.npos)
     return FILTER_STRONG;
=20
@@ -421,12 +448,6 @@
       Name.find("Xrr") !=3D Name.npos ||
       Name.find("rr64") !=3D Name.npos)
     return FILTER_WEAK;
-   =20
-  if (Name =3D=3D "VMASKMOVDQU64"  ||
-      Name =3D=3D "VEXTRACTPSrr64" ||
-      Name =3D=3D "VMOVQd64rr"     ||
-      Name =3D=3D "VMOVQs64rr")
-    return FILTER_WEAK;
=20
   // Special cases.
=20
@@ -441,29 +462,15 @@
     return FILTER_WEAK;
   if (Name.find("Fs") !=3D Name.npos)
     return FILTER_WEAK;
-  if (Name =3D=3D "MOVLPDrr"          ||
-      Name =3D=3D "MOVLPSrr"          ||
-      Name =3D=3D "PUSHFQ"            ||
-      Name =3D=3D "BSF16rr"           ||
-      Name =3D=3D "BSF16rm"           ||
-      Name =3D=3D "BSR16rr"           ||
-      Name =3D=3D "BSR16rm"           ||
-      Name =3D=3D "MOVSX16rm8"        ||
-      Name =3D=3D "MOVSX16rr8"        ||
-      Name =3D=3D "MOVZX16rm8"        ||
-      Name =3D=3D "MOVZX16rr8"        ||
-      Name =3D=3D "PUSH32i16"         ||
-      Name =3D=3D "PUSH64i16"         ||
+  if (Name =3D=3D "PUSH64i16"         ||
       Name =3D=3D "MOVPQI2QImr"       ||
       Name =3D=3D "VMOVPQI2QImr"      ||
-      Name =3D=3D "MOVSDmr"           ||
-      Name =3D=3D "MOVSDrm"           ||
-      Name =3D=3D "MOVSSmr"           ||
-      Name =3D=3D "MOVSSrm"           ||
       Name =3D=3D "MMX_MOVD64rrv164"  ||
-      Name =3D=3D "CRC32m16"          ||
       Name =3D=3D "MOV64ri64i32"      ||
-      Name =3D=3D "CRC32r16")
+      Name =3D=3D "VMASKMOVDQU64"     ||
+      Name =3D=3D "VEXTRACTPSrr64"    ||
+      Name =3D=3D "VMOVQd64rr"        ||
+      Name =3D=3D "VMOVQs64rr")
     return FILTER_WEAK;
=20
   if (HasFROperands && Name.find("MOV") !=3D Name.npos &&
@@ -566,7 +573,7 @@
  =20
   bool hasFROperands =3D false;
  =20
-  assert(numOperands < X86_MAX_OPERANDS && "X86_MAX_OPERANDS is not large =
enough");
+  assert(numOperands <=3D X86_MAX_OPERANDS && "X86_MAX_OPERANDS is not lar=
ge enough");
  =20
   for (operandIndex =3D 0; operandIndex < numOperands; ++operandIndex) {
     if (OperandList[operandIndex].Constraints.size()) {
@@ -684,31 +691,40 @@
     // - In AVX, there is a register operand in the VEX.vvvv field here -
     // Operand 3 (optional) is an immediate.
=20
-    if (HasVEX_4VPrefix)
-      assert(numPhysicalOperands >=3D 3 && numPhysicalOperands <=3D 4 &&
+    if (HasVEX_4VPrefix || HasVEX_4VOp3Prefix)
+      assert(numPhysicalOperands >=3D 3 && numPhysicalOperands <=3D 5 &&
              "Unexpected number of operands for MRMSrcRegFrm with VEX_4V")=
;=20
     else
       assert(numPhysicalOperands >=3D 2 && numPhysicalOperands <=3D 3 &&
              "Unexpected number of operands for MRMSrcRegFrm");
  =20
     HANDLE_OPERAND(roRegister)
-      =20
+
     if (HasVEX_4VPrefix)
       // FIXME: In AVX, the register below becomes the one encoded
       // in ModRMVEX and the one above the one in the VEX.VVVV field
       HANDLE_OPERAND(vvvvRegister)
-         =20
+
+    if (HasMemOp4Prefix)
+      HANDLE_OPERAND(immediate)
+
     HANDLE_OPERAND(rmRegister)
-    HANDLE_OPTIONAL(immediate)
+
+    if (HasVEX_4VOp3Prefix)
+      HANDLE_OPERAND(vvvvRegister)
+
+    if (!HasMemOp4Prefix)
+      HANDLE_OPTIONAL(immediate)
+    HANDLE_OPTIONAL(immediate) // above might be a register in 7:4
     break;
   case X86Local::MRMSrcMem:
     // Operand 1 is a register operand in the Reg/Opcode field.
     // Operand 2 is a memory operand (possibly SIB-extended)
     // - In AVX, there is a register operand in the VEX.vvvv field here -
     // Operand 3 (optional) is an immediate.
-   =20
-    if (HasVEX_4VPrefix)
-      assert(numPhysicalOperands >=3D 3 && numPhysicalOperands <=3D 4 &&
+
+    if (HasVEX_4VPrefix || HasVEX_4VOp3Prefix)
+      assert(numPhysicalOperands >=3D 3 && numPhysicalOperands <=3D 5 &&
              "Unexpected number of operands for MRMSrcMemFrm with VEX_4V")=
;=20
     else
       assert(numPhysicalOperands >=3D 2 && numPhysicalOperands <=3D 3 &&
@@ -721,8 +737,17 @@
       // in ModRMVEX and the one above the one in the VEX.VVVV field
       HANDLE_OPERAND(vvvvRegister)
=20
+    if (HasMemOp4Prefix)
+      HANDLE_OPERAND(immediate)
+
     HANDLE_OPERAND(memory)
-    HANDLE_OPTIONAL(immediate)
+
+    if (HasVEX_4VOp3Prefix)
+      HANDLE_OPERAND(vvvvRegister)
+
+    if (!HasMemOp4Prefix)
+      HANDLE_OPTIONAL(immediate)
+    HANDLE_OPTIONAL(immediate) // above might be a register in 7:4
     break;
   case X86Local::MRM0r:
   case X86Local::MRM1r:
@@ -736,12 +761,12 @@
     // Operand 2 (optional) is an immediate or relocation.
     if (HasVEX_4VPrefix)
       assert(numPhysicalOperands <=3D 3 &&
-             "Unexpected number of operands for MRMSrcMemFrm with VEX_4V");
+             "Unexpected number of operands for MRMnRFrm with VEX_4V");
     else
       assert(numPhysicalOperands <=3D 2 &&
              "Unexpected number of operands for MRMnRFrm");
     if (HasVEX_4VPrefix)
-      HANDLE_OPERAND(vvvvRegister);
+      HANDLE_OPERAND(vvvvRegister)
     HANDLE_OPTIONAL(rmRegister)
     HANDLE_OPTIONAL(relocation)
     break;
@@ -755,8 +780,14 @@
   case X86Local::MRM7m:
     // Operand 1 is a memory operand (possibly SIB-extended)
     // Operand 2 (optional) is an immediate or relocation.
-    assert(numPhysicalOperands >=3D 1 && numPhysicalOperands <=3D 2 &&
-           "Unexpected number of operands for MRMnMFrm");
+    if (HasVEX_4VPrefix)
+      assert(numPhysicalOperands >=3D 2 && numPhysicalOperands <=3D 3 &&
+             "Unexpected number of operands for MRMnMFrm");
+    else
+      assert(numPhysicalOperands >=3D 1 && numPhysicalOperands <=3D 2 &&
+             "Unexpected number of operands for MRMnMFrm");
+    if (HasVEX_4VPrefix)
+      HANDLE_OPERAND(vvvvRegister)
     HANDLE_OPERAND(memory)
     HANDLE_OPTIONAL(relocation)
     break;
@@ -843,15 +874,50 @@
     opcodeToSet =3D Opcode;
     break;
   case X86Local::T8:
-  case X86Local::TF:
+  case X86Local::T8XD:
+  case X86Local::T8XS:
     opcodeType =3D THREEBYTE_38;
-    if (needsModRMForDecode(Form))
-      filter =3D new ModFilter(isRegFormat(Form));
-    else
-      filter =3D new DumbFilter();
+    switch (Opcode) {
+    default:
+      if (needsModRMForDecode(Form))
+        filter =3D new ModFilter(isRegFormat(Form));
+      else
+        filter =3D new DumbFilter();
+      break;
+#define EXTENSION_TABLE(n) case 0x##n:
+    THREE_BYTE_38_EXTENSION_TABLES
+#undef EXTENSION_TABLE
+      switch (Form) {
+      default:
+        llvm_unreachable("Unhandled two-byte extended opcode");
+      case X86Local::MRM0r:
+      case X86Local::MRM1r:
+      case X86Local::MRM2r:
+      case X86Local::MRM3r:
+      case X86Local::MRM4r:
+      case X86Local::MRM5r:
+      case X86Local::MRM6r:
+      case X86Local::MRM7r:
+        filter =3D new ExtendedFilter(true, Form - X86Local::MRM0r);
+        break;
+      case X86Local::MRM0m:
+      case X86Local::MRM1m:
+      case X86Local::MRM2m:
+      case X86Local::MRM3m:
+      case X86Local::MRM4m:
+      case X86Local::MRM5m:
+      case X86Local::MRM6m:
+      case X86Local::MRM7m:
+        filter =3D new ExtendedFilter(false, Form - X86Local::MRM0m);
+        break;
+      MRM_MAPPING
+      } // switch (Form)
+      break;
+    } // switch (Opcode)
     opcodeToSet =3D Opcode;
     break;
   case X86Local::P_TA:
+  case X86Local::TAXD:
     opcodeType =3D THREEBYTE_3A;
     if (needsModRMForDecode(Form))
       filter =3D new ModFilter(isRegFormat(Form));
@@ -1049,6 +1115,7 @@
   TYPE("i16imm_pcrel",        TYPE_REL16)
   TYPE("i32imm_pcrel",        TYPE_REL32)
   TYPE("SSECC",               TYPE_IMM3)
+  TYPE("AVXCC",               TYPE_IMM5)
   TYPE("brtarget",            TYPE_RELv)
   TYPE("uncondbrtarget",      TYPE_RELv)
   TYPE("brtarget8",           TYPE_REL8)
@@ -1090,6 +1157,7 @@
   ENCODING("i32i8imm",        ENCODING_IB)
   ENCODING("u32u8imm",        ENCODING_IB)
   ENCODING("SSECC",           ENCODING_IB)
+  ENCODING("AVXCC",           ENCODING_IB)
   ENCODING("i16imm",          ENCODING_Iv)
   ENCODING("i16i8imm",        ENCODING_IB)
   ENCODING("i32imm",          ENCODING_Iv)
diff -r 428842767fa6 -r f2935497fa04 head/contrib/llvm/utils/TableGen/X86Re=
cognizableInstr.h
--- a/head/contrib/llvm/utils/TableGen/X86RecognizableInstr.h	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/contrib/llvm/utils/TableGen/X86RecognizableInstr.h	Tue Apr 17 11=
:51:51 2012 +0300
@@ -50,17 +50,23 @@
   uint8_t SegOvr;
   /// The hasOpSizePrefix field from the record
   bool HasOpSizePrefix;
+  /// The hasAdSizePrefix field from the record
+  bool HasAdSizePrefix;
   /// The hasREX_WPrefix field from the record
   bool HasREX_WPrefix;
   /// The hasVEXPrefix field from the record
   bool HasVEXPrefix;
   /// The hasVEX_4VPrefix field from the record
   bool HasVEX_4VPrefix;
+  /// The hasVEX_4VOp3Prefix field from the record
+  bool HasVEX_4VOp3Prefix;
   /// The hasVEX_WPrefix field from the record
   bool HasVEX_WPrefix;
   /// Inferred from the operands; indicates whether the L bit in the VEX p=
refix is set
   bool HasVEX_LPrefix;
-  // The ignoreVEX_L field from the record
+  /// The hasMemOp4Prefix field from the record
+  bool HasMemOp4Prefix;
+  /// The ignoreVEX_L field from the record
   bool IgnoresVEX_L;
   /// The hasLockPrefix field from the record
   bool HasLockPrefix;
@@ -70,7 +76,7 @@
   bool Is64Bit;
   // Whether the instruction has the predicate "In32BitMode"
   bool Is32Bit;
- =20
+
   /// The instruction name as listed in the tables
   std::string Name;
   /// The AT&T AsmString for the instruction
diff -r 428842767fa6 -r f2935497fa04 head/contrib/openbsm/libauditd/auditd_=
lib.c
--- a/head/contrib/openbsm/libauditd/auditd_lib.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/contrib/openbsm/libauditd/auditd_lib.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -520,6 +520,7 @@
 				}
=20
 		}
+		closedir(dirp);
 	}
=20
 	oldest_time =3D current_time - expire_age;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/openpam/lib/openpam_confi=
gure.c
--- a/head/contrib/openpam/lib/openpam_configure.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/contrib/openpam/lib/openpam_configure.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -360,7 +360,7 @@
 	pam_chain_t *this, **next;
 	pam_facility_t fclt;
 	pam_control_t ctlf;
-	char *line, *str, *name;
+	char *line0, *line, *str, *name;
 	char *option, **optv;
 	int len, lineno, ret;
 	FILE *f;
@@ -377,18 +377,18 @@
 	this =3D NULL;
 	name =3D NULL;
 	lineno =3D 0;
-	while ((line =3D openpam_readline(f, &lineno, NULL)) !=3D NULL) {
+	while ((line0 =3D line =3D openpam_readline(f, &lineno, NULL)) !=3D NULL)=
 {
 		/* get service name if necessary */
 		if (style =3D=3D pam_conf_style) {
 			if ((len =3D parse_service_name(&line, &str)) =3D=3D 0) {
 				openpam_log(PAM_LOG_NOTICE,
 				    "%s(%d): invalid service name (ignored)",
 				    filename, lineno);
-				FREE(line);
+				FREE(line0);
 				continue;
 			}
 			if (strlcmp(service, str, len) !=3D 0) {
-				FREE(line);
+				FREE(line0);
 				continue;
 			}
 		}
@@ -401,7 +401,7 @@
 			goto fail;
 		}
 		if (facility !=3D fclt && facility !=3D PAM_FACILITY_ANY) {
-			FREE(line);
+			FREE(line0);
 			continue;
 		}
=20
@@ -425,7 +425,7 @@
 			FREE(name);
 			if (ret !=3D PAM_SUCCESS)
 				goto fail;
-			FREE(line);
+			FREE(line0);
 			continue;
 		}
=20
@@ -486,7 +486,7 @@
 		this =3D NULL;
=20
 		/* next please... */
-		FREE(line);
+		FREE(line0);
 	}
 	if (!feof(f))
 		goto syserr;
diff -r 428842767fa6 -r f2935497fa04 head/contrib/telnet/libtelnet/kerberos=
5.c
--- a/head/contrib/telnet/libtelnet/kerberos5.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/contrib/telnet/libtelnet/kerberos5.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -53,7 +53,7 @@
=20
 #include <sys/cdefs.h>
=20
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/contrib/telnet/libtelnet/kerberos5.c 233932 2012-=
04-06 00:03:45Z stas $");
=20
 #ifdef	KRB5
=20
@@ -100,6 +100,16 @@
 static krb5_context context;
 static krb5_auth_context auth_context;
=20
+static void
+print_krb5_error(krb5_context context, krb5_error_code code, const char *m=
sg)
+{
+	const char *error_message;
+
+	error_message =3D krb5_get_error_message(context, code);
+	printf(msg, error_message);
+	krb5_free_error_message(context, error_message);
+}
+
 static int
 Data(Authenticator *ap, int type, const char *d, int c)
 {
@@ -182,8 +192,7 @@
     ret =3D krb5_cc_default(context, &ccache);
     if (ret) {
 	if (auth_debug_mode) {
-	    printf("Kerberos V5: could not get default ccache: %s\r\n",
-		   krb5_get_err_text (context, ret));
+	    print_krb5_error(context, ret, "Kerberos V5: could not get default cc=
ache: %s\r\n");
 	}
 	return 0;
     }
@@ -197,8 +206,7 @@
     ret =3D krb5_auth_con_init (context, &auth_context);
     if (ret) {
 	if (auth_debug_mode) {
-	    printf("Kerberos V5: krb5_auth_con_init failed (%s)\r\n",
-		   krb5_get_err_text(context, ret));
+	    print_krb5_error(context, ret, "Kerberos V5: krb5_auth_con_init faile=
d (%s)\r\n");
 	}
 	return(0);
     }
@@ -208,9 +216,8 @@
 					  &net);
     if (ret) {
 	if (auth_debug_mode) {
-	    printf ("Kerberos V5:"
-		    " krb5_auth_con_setaddrs_from_fd failed (%s)\r\n",
-		    krb5_get_err_text(context, ret));
+	    print_krb5_error(context, ret, "Kerberos V5:"
+		    " krb5_auth_con_setaddrs_from_fd failed (%s)\r\n");
 	}
 	return(0);
     }
@@ -236,18 +243,21 @@
 				       &service);
 	if(ret) {
 	    if (auth_debug_mode) {
-		printf ("Kerberos V5:"
+		const char *err_str;
+	=09
+		err_str =3D krb5_get_error_message(context, ret);
+		printf("Kerberosr V5:"
 			" krb5_sname_to_principal(%s) failed (%s)\r\n",
-			RemoteHostName, krb5_get_err_text(context, ret));
+			RemoteHostName, err_str);
+		krb5_free_error_message(context, err_str);
 	    }
 	    return 0;
 	}
 	ret =3D krb5_unparse_name_fixed(context, service, sname, sizeof(sname));
 	if(ret) {
 	    if (auth_debug_mode) {
-		printf ("Kerberos V5:"
-			" krb5_unparse_name_fixed failed (%s)\r\n",
-			krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5:"
+			" krb5_unparse_name_fixed failed (%s)\r\n");
 	    }
 	    return 0;
 	}
@@ -260,8 +270,7 @@
     }
     if (ret) {
 	if (1 || auth_debug_mode) {
-	    printf("Kerberos V5: mk_req failed (%s)\r\n",
-		   krb5_get_err_text(context, ret));
+	    print_krb5_error(context, ret, "Kerberos V5: mk_req failed (%s)\r\n");
 	}
 	return(0);
     }
@@ -319,8 +328,7 @@
 	    Data(ap, KRB_REJECT, "krb5_auth_con_init failed", -1);
 	    auth_finished(ap, AUTH_REJECT);
 	    if (auth_debug_mode)
-		printf("Kerberos V5: krb5_auth_con_init failed (%s)\r\n",
-		       krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5: krb5_auth_con_init failed (=
%s)\r\n");
 	    return;
 	}
=20
@@ -331,9 +339,8 @@
 	    Data(ap, KRB_REJECT, "krb5_auth_con_setaddrs_from_fd failed", -1);
 	    auth_finished(ap, AUTH_REJECT);
 	    if (auth_debug_mode)
-		printf("Kerberos V5: "
-		       "krb5_auth_con_setaddrs_from_fd failed (%s)\r\n",
-		       krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5: "
+		       "krb5_auth_con_setaddrs_from_fd failed (%s)\r\n");
 	    return;
 	}
=20
@@ -346,9 +353,8 @@
 	    Data(ap, KRB_REJECT, "krb5_sock_to_principal failed", -1);
 	    auth_finished(ap, AUTH_REJECT);
 	    if (auth_debug_mode)
-		printf("Kerberos V5: "
-		       "krb5_sock_to_principal failed (%s)\r\n",
-		       krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5: "
+		       "krb5_sock_to_principal failed (%s)\r\n");
 	    return;
 	}
=20
@@ -363,10 +369,12 @@
 	krb5_free_principal (context, server);
 	if (ret) {
 	    char *errbuf;
+	    const char *err_str;
=20
+	    err_str =3D krb5_get_error_message(context, ret);
 	    asprintf(&errbuf,
-		     "Read req failed: %s",
-		     krb5_get_err_text(context, ret));
+		     "Read req failed: %s", err_str);
+	    krb5_free_error_message(context, err_str);
 	    Data(ap, KRB_REJECT, errbuf, -1);
 	    if (auth_debug_mode)
 		printf("%s\r\n", errbuf);
@@ -387,8 +395,11 @@
=20
 	    if (ret) {
 		char *errbuf;
-		asprintf(&errbuf, "Bad checksum: %s",=20
-			 krb5_get_err_text(context, ret));
+		const char *err_str;
+
+		err_str =3D krb5_get_error_message(context, ret);
+		asprintf(&errbuf, "Bad checksum: %s", err_str);
+		krb5_free_error_message(context, err_str);
 		Data(ap, KRB_REJECT, errbuf, -1);
 		if (auth_debug_mode)
 		    printf ("%s\r\n", errbuf);
@@ -404,9 +415,8 @@
 	    Data(ap, KRB_REJECT, "krb5_auth_con_getremotesubkey failed", -1);
 	    auth_finished(ap, AUTH_REJECT);
 	    if (auth_debug_mode)
-		printf("Kerberos V5: "
-		       "krb5_auth_con_getremotesubkey failed (%s)\r\n",
-		       krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5: "
+		       "krb5_auth_con_getremotesubkey failed (%s)\r\n");
 	    return;
 	}
=20
@@ -419,9 +429,8 @@
 	    Data(ap, KRB_REJECT, "krb5_auth_con_getkey failed", -1);
 	    auth_finished(ap, AUTH_REJECT);
 	    if (auth_debug_mode)
-		printf("Kerberos V5: "
-		       "krb5_auth_con_getkey failed (%s)\r\n",
-		       krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5: "
+		       "krb5_auth_con_getkey failed (%s)\r\n");
 	    return;
 	}
 	if (key_block =3D=3D NULL) {
@@ -440,9 +449,8 @@
 		     "krb5_mk_rep failed", -1);
 		auth_finished(ap, AUTH_REJECT);
 		if (auth_debug_mode)
-		    printf("Kerberos V5: "
-			   "krb5_mk_rep failed (%s)\r\n",
-			   krb5_get_err_text(context, ret));
+		    print_krb5_error(context, ret, "Kerberos V5: "
+			   "krb5_mk_rep failed (%s)\r\n");
 		return;
 	    }
 	    Data(ap, KRB_RESPONSE, outbuf.data, outbuf.length);
@@ -509,8 +517,7 @@
 	ret =3D krb5_cc_resolve (context, ccname, &ccache);
 	if (ret) {
 	    if (auth_debug_mode)
-		printf ("Kerberos V5: could not get ccache: %s\r\n",
-			krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5: could not get ccache: %s\r\=
n");
 	    break;
 	}
=20
@@ -519,8 +526,7 @@
 				  ticket->client);
 	if (ret) {
 	    if (auth_debug_mode)
-		printf ("Kerberos V5: could not init ccache: %s\r\n",
-			krb5_get_err_text(context, ret));
+		print_krb5_error(context, ret, "Kerberos V5: could not init ccache: %s\r=
\n");
 	    break;
 	}
=20
@@ -533,10 +539,12 @@
 			     &inbuf);
 	if(ret) {
 	    char *errbuf;
+	    const char *err_str;
=20
+	    err_str =3D krb5_get_error_message(context, ret);
 	    asprintf (&errbuf,
-		      "Read forwarded creds failed: %s",
-		      krb5_get_err_text (context, ret));
+		      "Read forwarded creds failed: %s", err_str);
+	    krb5_free_error_message(context, err_str);
 	    if(errbuf =3D=3D NULL)
 		Data(ap, KRB_FORWARD_REJECT, NULL, 0);
 	    else
@@ -604,8 +612,7 @@
 					auth_context,
 					&keyblock);
 	if(ret) {
-	    printf("[ krb5_auth_con_getkey: %s ]\r\n",
-		   krb5_get_err_text(context, ret));
+	    print_krb5_error(context, ret, "[ krb5_auth_con_getkey: %s ]\r\n");
 	    auth_send_retry();
 	    return;
 	}
@@ -632,8 +639,7 @@
=20
 	  ret =3D krb5_rd_rep(context, auth_context, &inbuf, &reply);
 	  if (ret) {
-	      printf("[ Mutual authentication failed: %s ]\r\n",
-		     krb5_get_err_text (context, ret));
+	      print_krb5_error(context, ret, "[ Mutual authentication failed: %s =
]\r\n");
 	      auth_send_retry();
 	      return;
 	  }
@@ -748,16 +754,14 @@
     ret =3D krb5_cc_default (context, &ccache);
     if (ret) {
 	if (auth_debug_mode)
-	    printf ("KerberosV5: could not get default ccache: %s\r\n",
-		    krb5_get_err_text (context, ret));
+	    print_krb5_error(context, ret, "KerberosV5: could not get default cca=
che: %s\r\n");
 	return;
     }
=20
     ret =3D krb5_cc_get_principal (context, ccache, &principal);
     if (ret) {
 	if (auth_debug_mode)
-	    printf ("KerberosV5: could not get principal: %s\r\n",
-		    krb5_get_err_text (context, ret));
+	    print_krb5_error(context, ret, "KerberosV5: could not get principal: =
%s\r\n");
 	return;
     }
=20
@@ -775,8 +779,7 @@
=20
     if (ret) {
 	if (auth_debug_mode)
-	    printf ("KerberosV5: could not get principal: %s\r\n",
-		    krb5_get_err_text (context, ret));
+	    print_krb5_error(context, ret, "KerberosV5: could not get principal: =
%s\r\n");
 	return;
     }
=20
@@ -796,8 +799,7 @@
 				    &out_data);
     if (ret) {
 	if (auth_debug_mode)
-	    printf ("Kerberos V5: error getting forwarded creds: %s\r\n",
-		    krb5_get_err_text (context, ret));
+	    print_krb5_error(context, ret, "Kerberos V5: error getting forwarded =
creds: %s\r\n");
 	return;
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/antarctica
--- a/head/contrib/tzdata/antarctica	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/antarctica	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 # <pre>
-# @(#)antarctica	8.9
+# @(#)antarctica	8.10
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
=20
@@ -42,8 +42,19 @@
 Rule	ChileAQ	1998	only	-	Mar	Sun>=3D9	3:00u	0	-
 Rule	ChileAQ	1998	only	-	Sep	27	4:00u	1:00	S
 Rule	ChileAQ	1999	only	-	Apr	 4	3:00u	0	-
-Rule	ChileAQ	1999	max	-	Oct	Sun>=3D9	4:00u	1:00	S
-Rule	ChileAQ	2000	max	-	Mar	Sun>=3D9	3:00u	0	-
+Rule	ChileAQ	1999	2010	-	Oct	Sun>=3D9	4:00u	1:00	S
+Rule	ChileAQ	2000	2007	-	Mar	Sun>=3D9	3:00u	0	-
+# N.B.: the end of March 29 in Chile is March 30 in Universal time,
+# which is used below in specifying the transition.
+Rule	ChileAQ	2008	only	-	Mar	30	3:00u	0	-
+Rule	ChileAQ	2009	only	-	Mar	Sun>=3D9	3:00u	0	-
+Rule	ChileAQ	2010	only	-	Apr	Sun>=3D1	3:00u	0	-
+Rule	ChileAQ	2011	only	-	May	Sun>=3D2	3:00u	0	-
+Rule	ChileAQ	2011	only	-	Aug	Sun>=3D16	4:00u	1:00	S
+Rule	ChileAQ	2012	only	-	Apr	Sun>=3D23	3:00u	0	-
+Rule	ChileAQ	2012	only	-	Sep	Sun>=3D2	4:00u	1:00	S
+Rule	ChileAQ	2013	max	-	Mar	Sun>=3D9	3:00u	0	-
+Rule	ChileAQ	2013	max	-	Oct	Sun>=3D9	4:00u	1:00	S
=20
 # These rules are stolen from the `australasia' file.
 Rule	AusAQ	1917	only	-	Jan	 1	0:01	1:00	-
@@ -142,12 +153,16 @@
 						# Western (Aus) Standard Time
 			11:00	-	CAST	2010 Mar 5 2:00
 						# Casey Time
+			8:00	-	WST	2011 Oct 28 2:00
+			11:00	-	CAST	2012 Feb 21 17:00u
 			8:00	-	WST
 Zone Antarctica/Davis	0	-	zzz	1957 Jan 13
 			7:00	-	DAVT	1964 Nov # Davis Time
 			0	-	zzz	1969 Feb
 			7:00	-	DAVT	2009 Oct 18 2:00
 			5:00	-	DAVT	2010 Mar 10 20:00u
+			7:00	-	DAVT	2011 Oct 28 2:00
+			5:00	-	DAVT	2012 Feb 21 20:00u
 			7:00	-	DAVT
 Zone Antarctica/Mawson	0	-	zzz	1954 Feb 13
 			6:00	-	MAWT	2009 Oct 18 2:00
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/asia
--- a/head/contrib/tzdata/asia	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/asia	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# @(#)asia	8.69
+# @(#)asia	8.70
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
=20
@@ -77,10 +77,6 @@
 Rule RussiaAsia	1993	1995	-	Sep	lastSun	 2:00s	0	-
 Rule RussiaAsia	1996	max	-	Oct	lastSun	 2:00s	0	-
=20
-# From Arthur David Olson (2011-06-15):
-# While Russia abandoned DST in 2011, Armenia may choose to
-# follow Russia's "old" rules.
-
 # Afghanistan
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Kabul	4:36:48 -	LMT	1890
@@ -97,6 +93,21 @@
 # in 1996, though it did use DST in 1995.  IATA SSIM (1991/1998) reports t=
hat
 # Armenia switched from 3:00 to 4:00 in 1998 and observed DST after 1991,
 # but started switching at 3:00s in 1998.
+
+# From Arthur David Olson (2011-06-15):
+# While Russia abandoned DST in 2011, Armenia may choose to
+# follow Russia's "old" rules.
+
+# From Alexander Krivenyshev (2012-02-10):
+# According to News Armenia, on Feb 9, 2012,
+# http://newsarmenia.ru/society/20120209/42609695.html
+#=20
+# The Armenia National Assembly adopted final reading of Amendments to the
+# Law "On procedure of calculation time on the territory of the Republic of
+# Armenia" according to which Armenia [is] abolishing Daylight Saving Time.
+# or
+# (brief)
+# http://www.worldtimezone.com/dst_news/dst_news_armenia03.html
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Yerevan	2:58:00 -	LMT	1924 May  2
 			3:00	-	YERT	1957 Mar    # Yerevan Time
@@ -104,7 +115,8 @@
 			3:00	1:00	YERST	1991 Sep 23 # independence
 			3:00 RussiaAsia	AM%sT	1995 Sep 24 2:00s
 			4:00	-	AMT	1997
-			4:00 RussiaAsia	AM%sT
+			4:00 RussiaAsia	AM%sT	2012 Mar 25 2:00s
+			4:00	-	AMT
=20
 # Azerbaijan
 # From Rustam Aliyev of the Azerbaijan Internet Forum (2005-10-23):
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/australasia
--- a/head/contrib/tzdata/australasia	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/australasia	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 # <pre>
-# @(#)australasia	8.29
+# @(#)australasia	8.30
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
=20
@@ -616,6 +616,11 @@
 # Dateline Change skip Friday 30th Dec 2011
 # Thursday 29th December 2011	23:59:59 Hours
 # Saturday 31st December 2011	00:00:00 Hours
+#
+# Clarification by Tim Parenti (2012-01-03):
+# Although Samoa has used Daylight Saving Time in the 2010-2011 and 2011-2=
012
+# seasons, there is not yet any indication that this trend will continue on
+# a regular basis. For now, we have explicitly listed the transitions belo=
w.
 Zone Pacific/Apia	 12:33:04 -	LMT	1879 Jul  5
 			-11:26:56 -	LMT	1911
 			-11:30	-	SAMT	1950		# Samoa Time
@@ -633,9 +638,28 @@
 			11:00	-	SBT	# Solomon Is Time
=20
 # Tokelau Is
+#
+# From Gwillim Law (2011-12-29)
+# A correspondent informed me that Tokelau, like Samoa, will be skipping
+# December 31 this year, thereby changing its time zone from UTC-10 to
+# UTC+14. When I tried to verify this statement, I found a confirming
+# article in Time magazine online
+# <a href=3D"http://www.time.com/time/world/article/0,8599,2103243,00.html=
">
+# (http://www.time.com/time/world/article/0,8599,2103243,00.html).
+# </a>
+#
+# From Jonathan Leffler (2011-12-29)
+# Information from the BBC to the same effect:
+# <a href=3D"http://www.bbc.co.uk/news/world-asia-16351377">
+# http://www.bbc.co.uk/news/world-asia-16351377
+# </a>
+#
+# Patch supplied by Tim Parenti (2011-12-29)
+
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Pacific/Fakaofo	-11:24:56 -	LMT	1901
-			-10:00	-	TKT	# Tokelau Time
+			-10:00	-	TKT 2011 Dec 30	# Tokelau Time
+			14:00	-	TKT
=20
 # Tonga
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/europe
--- a/head/contrib/tzdata/europe	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/europe	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 # <pre>
-# @(#)europe	8.40
+# @(#)europe	8.41
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
=20
@@ -211,9 +211,15 @@
 # the history of summer time legislation in the United Kingdom.
 # Since 1998 Joseph S. Myers has been updating
 # and extending this list, which can be found in
-# <a href=3D"http://student.cusu.cam.ac.uk/~jsm28/british-time/">
+# http://student.cusu.cam.ac.uk/~jsm28/british-time/
+# <a href=3D"http://www.polyomino.org.uk/british-time/">
 # History of legal time in Britain
 # </a>
+# Rob Crowther (2012-01-04) reports that that URL no longer
+# exists, and the article can now be found at:
+# <a href=3D"http://www.polyomino.org.uk/british-time/">
+# http://www.polyomino.org.uk/british-time/
+# </a>
=20
 # From Joseph S. Myers (1998-01-06):
 #
@@ -1151,10 +1157,10 @@
 # write that they were used in Monaco and in many French locations.
 # Le Corre writes that the upper limit of the free zone was Arneguy, Orthe=
z,
 # Mont-de-Marsan, Bazas, Langon, Lamotte-Montravel, Marouil, La
-# Rochefoucault, Champagne-Mouton, La Roche-Posay, La Haye-Decartes,
+# Rochefoucault, Champagne-Mouton, La Roche-Posay, La Haye-Descartes,
 # Loches, Montrichard, Vierzon, Bourges, Moulins, Digoin,
 # Paray-le-Monial, Montceau-les-Mines, Chalons-sur-Saone, Arbois,
-# Dole, Morez, St-Claude, and Collognes (Haute-Savioe).
+# Dole, Morez, St-Claude, and Collonges (Haute-Savoie).
 Rule	France	1941	only	-	May	 5	 0:00	2:00	M # Midsummer
 # Shanks & Pottenger say this transition occurred at Oct 6 1:00,
 # but go with Denis Excoffier (1997-12-12),
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/leapseconds
--- a/head/contrib/tzdata/leapseconds	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/leapseconds	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 # <pre>
-# @(#)leapseconds	8.11
+# @(#)leapseconds	8.13
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
=20
@@ -48,40 +48,54 @@
 Leap	1998	Dec	31	23:59:60	+	S
 Leap	2005	Dec	31	23:59:60	+	S
 Leap	2008	Dec	31	23:59:60	+	S
+Leap	2012	Jun	30	23:59:60	+	S
=20
 # INTERNATIONAL EARTH ROTATION AND REFERENCE SYSTEMS SERVICE (IERS)
 #
 # SERVICE INTERNATIONAL DE LA ROTATION TERRESTRE ET DES SYSTEMES DE REFERE=
NCE
 #
+#
 # SERVICE DE LA ROTATION TERRESTRE
 # OBSERVATOIRE DE PARIS
 # 61, Av. de l'Observatoire 75014 PARIS (France)
-# Tel.      : 33 (0) 1 40 51 22 29
+# Tel.      : 33 (0) 1 40 51 22 26
 # FAX       : 33 (0) 1 40 51 22 91
-# Internet  : services.iers at obspm.fr
+# e-mail    : (E-Mail Removed)
+# http://hpiers.obspm.fr/eop-pc
 #
-# Paris, 2 February 2011
+# Paris, 5 January 2012
 #
-# Bulletin C 41
+#
+# Bulletin C 43
 #
 # To authorities responsible
 # for the measurement and
 # distribution of time
 #
-# INFORMATION ON UTC - TAI
 #
-# NO positive leap second will be introduced at the end of June 2011.
-# The difference between Coordinated Universal Time UTC and the
-# International Atomic Time TAI is :	=09
+# UTC TIME STEP
+# on the 1st of July 2012
 #
-# from 2009 January 1, 0h UTC, until further notice : UTC-TAI =3D -34 s
+#
+# A positive leap second will be introduced at the end of June 2012.
+# The sequence of dates of the UTC second markers will be:	=09
+# 	=09
+#                          2012 June 30,     23h 59m 59s
+#                          2012 June 30,     23h 59m 60s
+#                          2012 July  1,      0h  0m  0s
+#
+# The difference between UTC and the International Atomic Time TAI is:
+#
+# from 2009 January 1, 0h UTC, to 2012 July 1  0h UTC  : UTC-TAI =3D - 34s
+# from 2012 July 1,    0h UTC, until further notice    : UTC-TAI =3D - 35s
 #
 # Leap seconds can be introduced in UTC at the end of the months of Decemb=
er
-# or June,  depending on the evolution of UT1-TAI. Bulletin C is mailed ev=
ery
-# six months, either to announce a time step in UTC, or to confirm that th=
ere
+# or June, depending on the evolution of UT1-TAI. Bulletin C is mailed eve=
ry
+# six months, either to announce a time step in UTC or to confirm that the=
re
 # will be no time step at the next possible date.
 #
+#
 # Daniel GAMBIS
-# Head		=09
-# Earth Orientation Center of the IERS
+# Head	=09
+# Earth Orientation Center of IERS
 # Observatoire de Paris, France
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/northamerica
--- a/head/contrib/tzdata/northamerica	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/northamerica	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 # <pre>
-# @(#)northamerica	8.51
+# @(#)northamerica	8.52
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
=20
@@ -1120,9 +1120,26 @@
 # For now, assume all of DST-observing Canada will fall into line with the
 # new US DST rules,
=20
+# From Chris Walton (2011-12-01)
+# In the first of Tammy Hardwick's articles
+# <a href=3D"http://www.ilovecreston.com/?p=3Darticles&t=3Dspec&ar=3D260">
+# http://www.ilovecreston.com/?p=3Darticles&t=3Dspec&ar=3D260
+# </a>
+# she quotes the Friday November 1/1918 edition of the Creston Review.
+# The quote includes these two statements:
+# 'Sunday the CPR went back to the old system of time...'
+# '... The daylight saving scheme was dropped all over Canada at the same =
time,'
+# These statements refer to a transition from daylight time to standard ti=
me
+# that occurred nationally on Sunday October 27/1918.  This transition was
+# also documented in the Saturday October 26/1918 edition of the Toronto S=
tar.
+
+# In light of that evidence, we alter the date from the earlier believed
+# Oct 31, to Oct 27, 1918 (and Sunday is a more likely transition day
+# than Thursday) in all Canadian rulesets.
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Canada	1918	only	-	Apr	14	2:00	1:00	D
-Rule	Canada	1918	only	-	Oct	31	2:00	0	S
+Rule	Canada	1918	only	-	Oct	27	2:00	0	S
 Rule	Canada	1942	only	-	Feb	 9	2:00	1:00	W # War
 Rule	Canada	1945	only	-	Aug	14	23:00u	1:00	P # Peace
 Rule	Canada	1945	only	-	Sep	30	2:00	0	S
@@ -1645,7 +1662,7 @@
 Rule	Winn	1916	only	-	Apr	23	0:00	1:00	D
 Rule	Winn	1916	only	-	Sep	17	0:00	0	S
 Rule	Winn	1918	only	-	Apr	14	2:00	1:00	D
-Rule	Winn	1918	only	-	Oct	31	2:00	0	S
+Rule	Winn	1918	only	-	Oct	27	2:00	0	S
 Rule	Winn	1937	only	-	May	16	2:00	1:00	D
 Rule	Winn	1937	only	-	Sep	26	2:00	0	S
 Rule	Winn	1942	only	-	Feb	 9	2:00	1:00	W # War
@@ -1728,7 +1745,7 @@
=20
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Regina	1918	only	-	Apr	14	2:00	1:00	D
-Rule	Regina	1918	only	-	Oct	31	2:00	0	S
+Rule	Regina	1918	only	-	Oct	27	2:00	0	S
 Rule	Regina	1930	1934	-	May	Sun>=3D1	0:00	1:00	D
 Rule	Regina	1930	1934	-	Oct	Sun>=3D1	0:00	0	S
 Rule	Regina	1937	1941	-	Apr	Sun>=3D8	0:00	1:00	D
@@ -1765,7 +1782,7 @@
=20
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Edm	1918	1919	-	Apr	Sun>=3D8	2:00	1:00	D
-Rule	Edm	1918	only	-	Oct	31	2:00	0	S
+Rule	Edm	1918	only	-	Oct	27	2:00	0	S
 Rule	Edm	1919	only	-	May	27	2:00	0	S
 Rule	Edm	1920	1923	-	Apr	lastSun	2:00	1:00	D
 Rule	Edm	1920	only	-	Oct	lastSun	2:00	0	S
@@ -1795,9 +1812,68 @@
 # Dawson Creek uses MST.  Much of east BC is like Edmonton.
 # Matthews and Vincent (1998) write that Creston is like Dawson Creek.
=20
+# It seems though that (re: Creston) is not entirely correct:
+
+# From Chris Walton (2011-12-01):
+# There are two areas within the Canadian province of British Columbia
+# that do not currently observe daylight saving:
+# a) The Creston Valley (includes the town of Creston and surrounding area)
+# b) The eastern half of the Peace River Regional District
+# (includes the cities of Dawson Creek and Fort St. John)
+
+# Earlier this year I stumbled across a detailed article about the time
+# keeping history of Creston; it was written by Tammy Hardwick who is the
+# manager of the Creston & District Museum. The article was written in May=
 2009.
+# <a href=3D"http://www.ilovecreston.com/?p=3Darticles&t=3Dspec&ar=3D260">
+# http://www.ilovecreston.com/?p=3Darticles&t=3Dspec&ar=3D260
+# </a>
+# According to the article, Creston has not changed its clocks since June =
1918.
+# i.e. Creston has been stuck on UTC-7 for 93 years.
+# Dawson Creek, on the other hand, changed its clocks as recently as April=
 1972.
+
+# Unfortunately the exact date for the time change in June 1918 remains
+# unknown and will be difficult to ascertain.  I e-mailed Tammy a few mont=
hs
+# ago to ask if Sunday June 2 was a reasonable guess.  She said it was just
+# as plausible as any other date (in June).  She also said that after writ=
ing the
+# article she had discovered another time change in 1916; this is the subj=
ect
+# of another article which she wrote in October 2010.
+# <a href=3D"http://www.creston.museum.bc.ca/index.php?module=3Dcomments&u=
op=3Dview_comment&cm+id=3D56">
+# http://www.creston.museum.bc.ca/index.php?module=3Dcomments&uop=3Dview_c=
omment&cm+id=3D56
+# </a>
+
+# Here is a summary of the three clock change events in Creston's history:
+# 1. 1884 or 1885: adoption of Mountain Standard Time (GMT-7)
+# Exact date unknown
+# 2. Oct 1916: switch to Pacific Standard Time (GMT-8)=20
+# Exact date in October unknown;  Sunday October 1 is a reasonable guess.
+# 3. June 1918: switch to Pacific Daylight Time (GMT-7)
+# Exact date in June unknown; Sunday June 2 is a reasonable guess.
+# note#1:
+# On Oct 27/1918 when daylight saving ended in the rest of Canada,
+# Creston did not change its clocks.
+# note#2:
+# During WWII when the Federal Government legislated a mandatory clock cha=
nge,
+# Creston did not oblige.
+# note#3:
+# There is no guarantee that Creston will remain on Mountain Standard Time
+# (UTC-7) forever.
+# The subject was debated at least once this year by the town Council.
+# <a href=3D"http://www.bclocalnews.com/kootenay_rockies/crestonvalleyadva=
nce/news/116760809.html">
+# http://www.bclocalnews.com/kootenay_rockies/crestonvalleyadvance/news/11=
6760809.html
+# </a>
+
+# During a period WWII, summer time (Daylight saying) was mandatory in Can=
ada.
+# In Creston, that was handled by shifting the area to PST (-8:00) then ap=
plying
+# summer time to cause the offset to be -7:00, the same as it had been bef=
ore
+# the change.  It can be argued that the timezone abbreviation during this
+# period should be PDT rather than MST, but that doesn't seem important en=
ough
+# (to anyone) to further complicate the rules.
+
+# The transition dates (and times) are guesses.
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Vanc	1918	only	-	Apr	14	2:00	1:00	D
-Rule	Vanc	1918	only	-	Oct	31	2:00	0	S
+Rule	Vanc	1918	only	-	Oct	27	2:00	0	S
 Rule	Vanc	1942	only	-	Feb	 9	2:00	1:00	W # War
 Rule	Vanc	1945	only	-	Aug	14	23:00u	1:00	P # Peace
 Rule	Vanc	1945	only	-	Sep	30	2:00	0	S
@@ -1813,7 +1889,10 @@
 			-8:00	Canada	P%sT	1947
 			-8:00	Vanc	P%sT	1972 Aug 30 2:00
 			-7:00	-	MST
-
+Zone America/Creston	-7:46:04 -	LMT	1884
+			-7:00	-	MST	1916 Oct 1
+			-8:00	-	PST	1918 Jun 2
+			-7:00	-	MST
=20
 # Northwest Territories, Nunavut, Yukon
=20
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/southamerica
--- a/head/contrib/tzdata/southamerica	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/southamerica	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 # <pre>
-# @(#)southamerica	8.52
+# @(#)southamerica	8.53
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
=20
@@ -1218,6 +1218,28 @@
 # August, not in October as they have since 1968. This is a pilot plan
 # which will be reevaluated in 2012.
=20
+# From Mauricio Parada (2012-02-22), translated by Glenn Eychaner (2012-02=
-23):
+# As stated in the website of the Chilean Energy Ministry
+# http://www.minenergia.cl/ministerio/noticias/generales/gobierno-anuncia-=
fechas-de-cambio-de.html
+# The Chilean Government has decided to postpone the entrance into winter =
time
+# (to leave DST) from March 11 2012 to April 28th 2012. The decision has n=
ot
+# been yet formalized but it will within the next days.
+# Quote from the website communication:
+#
+# 6. For the year 2012, the dates of entry into winter time will be as fol=
lows:
+# a. Saturday April 28, 2012, clocks should go back 60 minutes; that is, at
+# 23:59:59, instead of passing to 0:00, the time should be adjusted to be =
23:00
+# of the same day.
+# b. Saturday, September 1, 2012, clocks should go forward 60 minutes; tha=
t is,
+# at 23:59:59, instead of passing to 0:00, the time should be adjusted to =
be
+# 01:00 on September 2.
+#
+# Note that...this is yet another "temporary" change that will be reevalua=
ted
+# AGAIN in 2013.
+
+# NOTE: ChileAQ rules for Antarctic bases are stored separately in the
+# 'antarctica' file.
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Chile	1927	1932	-	Sep	 1	0:00	1:00	S
 Rule	Chile	1928	1932	-	Apr	 1	0:00	0	-
@@ -1248,8 +1270,6 @@
 Rule	Chile	1998	only	-	Sep	27	4:00u	1:00	S
 Rule	Chile	1999	only	-	Apr	 4	3:00u	0	-
 Rule	Chile	1999	2010	-	Oct	Sun>=3D9	4:00u	1:00	S
-Rule	Chile	2011	only	-	Aug	Sun>=3D16	4:00u	1:00	S
-Rule	Chile	2012	max	-	Oct	Sun>=3D9	4:00u	1:00	S
 Rule	Chile	2000	2007	-	Mar	Sun>=3D9	3:00u	0	-
 # N.B.: the end of March 29 in Chile is March 30 in Universal time,
 # which is used below in specifying the transition.
@@ -1257,7 +1277,11 @@
 Rule	Chile	2009	only	-	Mar	Sun>=3D9	3:00u	0	-
 Rule	Chile	2010	only	-	Apr	Sun>=3D1	3:00u	0	-
 Rule	Chile	2011	only	-	May	Sun>=3D2	3:00u	0	-
-Rule	Chile	2012	max	-	Mar	Sun>=3D9	3:00u	0	-
+Rule	Chile	2011	only	-	Aug	Sun>=3D16	4:00u	1:00	S
+Rule	Chile	2012	only	-	Apr	Sun>=3D23	3:00u	0	-
+Rule	Chile	2012	only	-	Sep	Sun>=3D2	4:00u	1:00	S
+Rule	Chile	2013	max	-	Mar	Sun>=3D9	3:00u	0	-
+Rule	Chile	2013	max	-	Oct	Sun>=3D9	4:00u	1:00	S
 # IATA SSIM anomalies: (1992-02) says 1992-03-14;
 # (1996-09) says 1998-03-08.  Ignore these.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -1403,6 +1427,21 @@
 # will not revert to local mean time, but clocks will remain on Summer
 # time (UTC/GMT - 3 hours) throughout the whole of 2011.  Any long term
 # change to local time following the trial period will be notified.
+#
+# From Andrew Newman (2012-02-24)
+# A letter from Justin McPhee, Chief Executive,
+# Cable & Wireless Falkland Islands (dated 2012-02-22)
+# states...
+#   The current Atlantic/Stanley entry under South America expects the
+#   clocks to go back to standard Falklands Time (FKT) on the 15th April.
+#   The database entry states that in 2011 Stanley was staying on fixed
+#   summer time on a trial basis only.  FIG need to contact IANA and/or
+#   the maintainers of the database to inform them we're adopting
+#   the same policy this year and suggest recommendations for future years.
+#
+# For now we will assume permanent summer time for the Falklands
+# until advised differently (to apply for 2012 and beyond, after the 2011
+# experiment was apparently successful.)
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Falk	1937	1938	-	Sep	lastSun	0:00	1:00	S
 Rule	Falk	1938	1942	-	Mar	Sun>=3D19	0:00	0	-
@@ -1415,14 +1454,14 @@
 Rule	Falk	1985	2000	-	Sep	Sun>=3D9	0:00	1:00	S
 Rule	Falk	1986	2000	-	Apr	Sun>=3D16	0:00	0	-
 Rule	Falk	2001	2010	-	Apr	Sun>=3D15	2:00	0	-
-Rule	Falk	2012	max	-	Apr	Sun>=3D15	2:00	0	-
-Rule	Falk	2001	max	-	Sep	Sun>=3D1	2:00	1:00	S
+Rule	Falk	2001	2010	-	Sep	Sun>=3D1	2:00	1:00	S
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Atlantic/Stanley	-3:51:24 -	LMT	1890
 			-3:51:24 -	SMT	1912 Mar 12  # Stanley Mean Time
 			-4:00	Falk	FK%sT	1983 May     # Falkland Is Time
 			-3:00	Falk	FK%sT	1985 Sep 15
-			-4:00	Falk	FK%sT
+			-4:00	Falk	FK%sT	2010 Sep 5 02:00
+			-3:00	-	FKST
=20
 # French Guiana
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
diff -r 428842767fa6 -r f2935497fa04 head/contrib/tzdata/zone.tab
--- a/head/contrib/tzdata/zone.tab	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/contrib/tzdata/zone.tab	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 # <pre>
-# @(#)zone.tab	8.52
+# @(#)zone.tab	8.54
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 #
@@ -131,6 +131,7 @@
 CA	+690650-1050310	America/Cambridge_Bay	Mountain Time - west Nunavut
 CA	+6227-11421	America/Yellowknife	Mountain Time - central Northwest Terri=
tories
 CA	+682059-1334300	America/Inuvik	Mountain Time - west Northwest Territori=
es
+CA	+4906-11631	America/Creston		Mountain Standard Time - Creston, British =
Columbia
 CA	+5946-12014	America/Dawson_Creek	Mountain Standard Time - Dawson Creek =
& Fort Saint John, British Columbia
 CA	+4916-12307	America/Vancouver	Pacific Time - west British Columbia
 CA	+6043-13503	America/Whitehorse	Pacific Time - south Yukon
@@ -333,7 +334,7 @@
 RU	+5443+02030	Europe/Kaliningrad	Moscow-01 - Kaliningrad
 RU	+5545+03735	Europe/Moscow	Moscow+00 - west Russia
 RU	+4844+04425	Europe/Volgograd	Moscow+00 - Caspian Sea
-RU	+5312+05009	Europe/Samara	Moscow - Samara, Udmurtia
+RU	+5312+05009	Europe/Samara	Moscow+00 - Samara, Udmurtia
 RU	+5651+06036	Asia/Yekaterinburg	Moscow+02 - Urals
 RU	+5500+07324	Asia/Omsk	Moscow+03 - west Siberia
 RU	+5502+08255	Asia/Novosibirsk	Moscow+03 - Novosibirsk
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/ChangeLog
--- a/head/crypto/heimdal/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,457 @@
-2008-01-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
=20
-	* Release 1.1
+We stop writing change logs, see the source code version control systems h=
istory log instead
+=09
+2008-07-28  Love Hornquist Astrand  <lha at h5l.org>
=20
-2008-01-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+	* lib/krb5/v4_glue.c: The "kaserver" part of Heimdal occasionally
+	issues invalid AFS tokens
+	(here "occasionally" means for certain users in certain realms).
+=09
+	In lib/krb5/v4_glue.c, in the routine storage_to_etext the ticket
+	is padded to a multiple of 8 bytes. If it is already a multiple of
+	8 bytes, 8 additional 0-bytes are added.
+=09
+	This catches the AFS krb4 ticket decoder by surprise: unless the
+	ticket is exactly 56 bytes, it only supports the minimum necessary
+	padding.  It detects the superfluous padding by comparing the
+	ticket length decoded to the advertised ticket length.
+=09
+	Hence a 7-letter userid in "cern.ch" which resulted in a ticket of
+	40 bytes, got "padded" to 48 bytes which the rxkad decoder
+	rejected.
+=09
+	From Rainer Toebbicke.
+
+2008-07-25  Love H=C3=B6rnquist =C3=85strand  <lha at h5l.org>
+
+	* kuser/kinit.c: add --ok-as-delegate and --windows flags
+
+	* kpasswd/kpasswd-generator.c: Switch to krb5_set_password.
+
+	* kuser/kinit.c: Use krb5_cc_set_config.
+
+	* lib/krb5/cache.c: Add krb5_cc_[gs]et_config.
+
+2008-07-22  Love H=C3=B6rnquist =C3=85strand  <lha at h5l.org>
+
+	* lib/krb5/crypto.c: Allow numbers to be enctypes to as long as
+	they are valid.
+
+2008-07-17  Love H=C3=B6rnquist =C3=85strand  <lha at h5l.org>
+
+	* lib/hdb/version-script.map: some random bits needed for libkadm
+
+2008-07-15  Love H=C3=B6rnquist =C3=85strand  <lha at h5l.org>
+
+	* lib/krb5/send_to_kdc_plugin.h: add name for send_to_kdc plugin.
+=09
+	* lib/krb5/krbhst.c: handle KRB5_PLUGIN_NO_HANDLE for lookup
+	plugin.
+
+	* lib/krb5/send_to_kdc.c: Add support for the send_to_kdc plugin
+	interface.
+
+	* lib/krb5/Makefile.am: add send_to_kdc_plugin.h
+=09
+	* lib/krb5/krb5_err.et: add plugin error codes
+
+2008-07-14  Love Hornquist Astrand  <lha at kth.se>
+
+	* lib/hdb/Makefile.am: EXTRA_DIST +=3D version-script.map
+
+2008-07-14  Love Hornquist Astrand  <lha at kth.se>
+
+	* lib/krb5/krb5_{address,ccache}.3: spelling, from openbsd via janne
+	johansson
+
+2008-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* lib/krb5/version-script.map: add krb5_free_error_message
+
+2008-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* lib/krb5/init_creds_pw.c: switch to krb5_set_password().
+
+2008-06-18  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* lib/krb5/time.c (krb5_set_real_time): handle negative usec
+
+2008-05-31  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* lib/krb5/krb5_locl.h: Add <wind.h>
+
+	* lib/krb5/crypto.c: Use wind_utf8ucs2_length to convert the password to =
utf16.
+
+2008-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* lib/krb5/kcm.c: Add back krb5_kcmcache argument to try_door().
+
+2008-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* lib/krb5/error_string.c (krb5_free_error_message): constify
+=09
+	* lib/krb5/error_string.c: Add krb5_get_error_message().
+
+	* lib/krb5/doxygen.c: krb5_cc_new_unique() is name of the creation
+	function.
+=09
+2008-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/hdb/hdb-ldap.c: Use the _ext api for OpenLDAP, from Honza
+	Machacek (gentoo).
+
+2008-04-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/crypto.c: Use DES_set_key_unchecked().
+
+	* lib/krb5/krb5.conf.5: Document default_cc_type.
+
+	* lib/krb5/cache.c: Pick up [libdefaults]default_cc_type
+
+2008-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* kdc/kaserver.c: Use DES_set_key_unchecked().
+
+2008-04-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* doc/hx509.texi: About the pkcs11 module.
+
+	* doc/hx509.texi: Pick up version from vars.texi
+
+	* doc/hx509.texi: No MIT code in hx509.
+
+	* hx509 now includes a pkcs11 implementation.
+
+2008-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/hdb/Makefile.am: Move OpenLDAP includes to AM_CPPFLAGS to
+	avoid dropping other defines for the library.
+
+2008-04-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5: add __declspec() for windows.
+
+	* configure.in: Update rk_WIN32_EXPORT, add gssapi to
+	rk_WIN32_EXPORT.
+=09
+	* configure.in: Lets try dependency tracking for automake 1.10 and
+	later.
+=09
+	* configure.in: Use at least libtool-2.2.
+
+	* configure.in: Use LT_INIT the right way.
+
+	* lib/krb5/Makefile.am: Update make-proto usage.
+
+	* configure.in: Run autoupdate, use LT_INIT().
+
+2008-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/test_forward.c: Don't print krb5_error_code since we
+	are using krb5_err().
+
+	* lib/krb5/ticket.c: Cast krb5_error_code to int to avoid warning.
+
+	* lib/krb5/scache.c: Cast krb5_error_code to int to avoid warning.
+
+	* lib/krb5/principal.c: Cast enum to int to avoid warning.
+
+	* lib/krb5/pkinit.c: Cast krb5_error_code to int to avoid warning.
+
+	* lib/krb5/pac.c: Cast size_t to unsigned long to avoid warning.
+
+	* lib/krb5/error_string.c: Cast krb5_error_code to int to avoid
+	warning.
+
+	* lib/krb5/keytab_keyfile.c: Make num_entries an uint32 to avoid
+	negative numbers and type warnings.
+
+	* lib/krb5: cc_get_version returns an int, update.
+
+2008-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* configure.in: Check for <asl.h>.
+
+2008-04-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/version-script.map: sort and export _krb5_pk_kdf
+
+	* lib/krb5/crypto.c: Check kdf params. calculate the second half
+	of the key.
+
+	* lib/krb5/Makefile.am: Add test_pknistkdf
+
+	* lib/krb5/test_pknistkdf.c: Test the new pkinit nist kdf.
+
+	* lib/krb5/crypto.c: Complete _krb5_pk_kdf.
+
+	* lib/krb5/crypto.c: First version of KDF in
+	draft-ietf-krb-wg-pkinit-alg-agility-03.txt.
+=09
+2008-04-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* doc/setup.texi: Add text about smbk5pwd overlay from Buchan
+	Milne.
+=09
+	* lib/krb5/krb5_locl.h: Name the pkinit type enum.
+
+	* kdc/pkinit.c: Rename constants to match global header.
+
+	* lib/krb5/pkinit.c: Drop krb5_pk_identity and rename constants to
+	match global header.
+
+	* kdc/pkinit.c: Pick up krb5_pk_identity from krb5_locl.h.
+
+	* lib/krb5/scache.c (scc_alloc): %x is unsigned int.
+=09
+2008-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/version-script.map: Sort and add krb5_cc_switch.
+
+	* lib/krb5/acache.c: Use unsigned where appropriate.
+
+	* kcm/glue.c: Adapt to chenge to krb5_cc_ops.
+
+	* kcm/acl.c: Add missing op.
+
+	* kdc/connect.c: Use unsigned where appropriate.
+
+	* lib/krb5/n-fold.c: Use size_t where appropriate.
+
+	* lib/krb5/get_addrs.c: Use unsigned where appropriate.
+
+	* lib/krb5/crypto.c: Use unsigned where appropriate.
+
+	* lib/krb5/crc.c: Use unsigned where appropriate.
+
+	* lib/krb5/changepw.c: simplify
+
+	* lib/krb5/copy_host_realm.c: simplify
+
+	* kuser/kswitch.c: Implement --principal.
+
+2008-04-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/cache.c: allow returning the default cc-type.
+
+	* kuser/kswitch.c: Enable switching between existing caches.
+
+	* lib/krb5/cache.c: Add krb5_cc_switch, to set the default
+	credential cache.
+
+	* lib/krb5/acache.c: Implement set_default.
+
+	* lib/krb5/krb5.h: Extend krb5_cc_ops and add set_default to set
+	the default cc name for a credential type.
+
+2008-04-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/test_cc.c: test remove
+
+	* lib/krb5/fcache.c: Make the remove cred slight more atomic, now
+	it might lose creds, but there will be no empty cache at any time.
+
+	* lib/krb5/scache.c: Do credential iteration by temporary table.
+
+2008-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/acache.c: Translate ccErrInvalidCCache.
+
+	* lib/krb5/scache.c: implemetation of a sqlite3 backed credential
+	cache.
+
+	* lib/krb5/test_cc.c: test acc and scc
+
+	* lib/krb5/acache.c: Only release context if its in use.
+
+2008-04-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* doc/setup.texi: No patching of OpenLDAP is needed, from Buchan
+	Milne.
+
+2008-03-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/Makefile.am: Add scache.
+
+	* lib/krb5/scache.c: initial implementation
+
+	* lib/Makefile.am: sqlite
+
+	* configure.in: lib/sqlite/Makefile
+
+2008-03-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/fcache.c: Make the storing credential an atomic
+	write(2) to avoid signal races, bug traced by Harald Barth and Lars
+	Malinowsky.
+
+2008-03-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/fcache.c: Make erase_file() do locking too.
+
+	* kcm/protocol.c: Make work when moving to a non-existant
+	cred-cache.
+
+	* lib/krb5/test_cc.c: more verbose info.
+=09
+	* lib/krb5/test_cc.c: test krb5_cc_move().
+=09
+2008-03-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* lib/krb5/get_cred.c: Try both kdc server referral and the old
+	client chasing mode.
+
+	* lib/krb5/get_cred.c: Don't do canonicalize by default, make
+	add_cred() sane, make loop detection in credential fetching
+	better.
+
+	* lib/krb5/krb5_locl.h: Add flag EXTRACT_TICKET_AS_REQ.
+
+	* lib/krb5/init_creds_pw.c: Tell _krb5_extract_ticket that this is
+	an AS-REQ.
+
+	* lib/krb5/get_in_tkt.c: Make server referral work.
+=09
+2008-03-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* lib/krb5/get_in_tkt.c: check no server referral, don't use
+	stringent length tests since encryption layer does padding for
+	us...
+
+	* kdc/kerberos5.c: Match name in ClientCanonicalizedNames with -10
+
+	* lib/krb5/principal.c (_krb5_principal_compare_PrincipalName):
+	new function to compare a principal to a PrincipalName.
+
+	* lib/krb5/init_creds_pw.c: Move client referral checking to
+	_krb5_extract_ticket().
+
+	* lib/krb5/get_in_tkt.c: More bits for server referral.
+
+	* lib/krb5/get_in_tkt.c: Make working with client referrals.
+
+	* lib/krb5/get_cred.c: Try moving referrals checking into
+	_krb5_extract_ticket().
+
+	* lib/krb5/get_in_tkt.c: Try moving referrals checking into
+	_krb5_extract_ticket().
+
+2008-03-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* kdc/krb5tgs.c: Send SERVER-REFERRAL data in rep.padata instead
+	of auth_data in ticket.
+
+2008-03-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/init_creds_pw.c: remove lost bits from using
+	krb5_principal_set_realm
+=09
+	* kdc/krb5tgs.c: Better referrals support, use canonicalize flag.
+
+	* kdc/hprop.c: use krb5_principal_set_realm
+
+	* lib/krb5/init_creds_pw.c: use krb5_principal_set_realm
+
+	* lib/krb5/verify_user.c: use krb5_principal_set_realm
+
+	* lib/krb5/version-script.map: add krb5_principal_set_realm
+
+	* lib/krb5/principal.c: add krb5_principal_set_realm
+
+	* lib/krb5/get_cred.c: Insecure tgs referrals.
+
+	* lib/krb5/get_cred.c: Dont try key usage KRB5_KU_AP_REQ_AUTH for
+	TGS-REQ. This drop compatibility with pre 0.3d KDCs.
+=09
+	* lib/krb5/get_cred.c: catch KRB5_GC_CANONICALIZE.
+
+	* lib/krb5/krb5.h: set KRB5_GC_CANONICALIZE.
+
+	* kuser/kgetcred.c: set KRB5_GC_CANONICALIZE.
+
+	* kuser/kgetcred.c: Add stub --canonicalize implementation.
+
+2008-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* doc/setup.texi: Fix sasl-regexp, from Howard Chu.
+
+2008-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* kdc/kx509.c: Adapt to hx509_env changes.
+=09
+2008-03-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/pkinit.c: Try searchin the key by to use by first
+	looking for for PK-INIT EKU, then the Microsoft smart card EKU and
+	last, no special EKU at all.
+
+2008-03-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/acache.c: Create a new credential cache is ->get_name
+	is called, make acc_initialize() reset the existing credential
+	cache if needed.
+
+	* lib/krb5/acache.c (acc_get_name): just return the cache_name
+	directly instead of trying to resolve it.
+
+2008-02-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* include/Makefile.am (CLEANFILES): add wind.h and wind_err.h and
+	sort.
+
+2008-02-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/hdb/hdb-ldap.c: Use malloc() instead of static buffer.
+
+	* lib/hdb/hdb-ldap.c: Use ldap_get_values_len, from LaMont Jones
+	via Brian May and Debian.
+
+	* doc/Makefile.am: add libwind
+
+2008-02-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/test_renew.c: Remove extra ;, From Dennis Davis.
+
+	* lib/krb5/store_emem.c: Make compile on-pre c99 compilers. From
+	Dennis Davis.
+
+2008-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* tools/heimdal-gssapi.pc.in: Add wind.
+
+	* tools/krb5-config.in: Add wind.
+
+	* lib/krb5/pac.c: Use libwind.
+
+2008-02-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/Makefile.am: SUBDIRS: add wind
+
+2008-01-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* doc/programming.texi: See the Kerberos 5 API introduction and
+	documentation on the Heimdal webpage.
+=09
+2008-01-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5: better error strings for the keytab fetching functions
+
+	* lib/krb5/verify_krb5_conf.c: Catch deprecated entries.
+
+	* lib/krb5/get_cred.c: Remove support
+	for [libdefaults]capath (not [libdefaults] capaths though).
+
+2008-01-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* tools/heimdal-gssapi.pc.in: Fix caps of prefix, from Joakim
+	Fallsjo.
+
+2008-01-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* lib/krb5/fcache.c (fcc_move): more explict why the fcc_move
+	failes, handle cross device moves.
+=09
+2008-01-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_for_creds.c: Use on variable less.
=20
@@ -20,1337 +469,17 @@
=20
 	* kdc/Makefile.am: drop CHECK_SYMBOLS
=20
-2008-01-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/version-script.map: Add krb5_digest_probe.
 =09
-2008-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/pkinit.c: Replace hx509_name_to_der_name with
 	hx509_name_binary.
=20
-2008-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: add missing files
=20
-2007-12-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/digest.c: Log probe message, add NTLM_TARGET_DOMAIN to the
-	type2 message.
-
-2007-12-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/hdb/dbinfo.c: Add hdb_default_db().
-
-	* Makefile.am: Add some extra cf/*.
-
-2007-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* kuser/kgetcred.c: Fix type of name-type. From Andy Polyakov.
-
-2007-12-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/log.c: Use hdb_db_dir().
-
-	* kpasswd/kpasswdd.c: Use hdb_db_dir().
-
-2007-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* kdc/config.c: Use hdb_db_dir().
-
-	* kdc/kdc_locl.h: add KDC_LOG_FILE
-
-	* kdc/hpropd.c: Use hdb_default_db().
-
-	* kdc/kstash.c: Use hdb_db_dir().
-
-	* kdc/pkinit.c: Adapt to hx509 changes, use hdb_db_dir().
-
-	* lib/krb5/rd_req.c: Document krb5_rd_req_in_set_pac_check.
-
-	* lib/krb5/verify_krb5_conf.c: Check check_pac.
-
-	* lib/krb5/rd_req.c: use KRB5_CTX_F_CHECK_PAC to init check_pac
-	field in the krb5_rd_req_in_ctx
-
-	* lib/krb5/expand_hostname.c: Adapt to changing
-	dns_canonicalize_hostname into flags field.
-
-	* lib/krb5/context.c: Adapt to changing dns_canonicalize_hostname
-	into flags field, add check-pac as an libdefaults option.
-
-	* lib/krb5/pkinit.c: Adapt to changes in hx509 interface.
-
-	* doc: add doxygen documentation to hcrypto
-
-	* doc/doxytmpl.dxy: generate links
-=09
-2007-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/Makefile.am: build_HEADERZ +=3D heim_threads.h
-
-	* lib/hdb/dbinfo.c (hdb_db_dir): Return the directory where the
-	hdb database resides.
-
-	* configure.in: Add --with-hdbdir to specify where the database is
-	stored.
-
-	* lib/krb5/crypto.c: revert previous patch, the problem is located
-	in the RAND_file_name() function that will cause recursive nss
-	lookups, can't fix that here.
-
-2007-12-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/crypto.c (krb5_generate_random_block): try to avoid the
-	dead-lock in by not holding the lock while running
-	RAND_file_name. Prompted by Hai Zaar.
-
-	* lib/krb5/n-fold.c: spelling
-=09
-2007-12-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kuser/kdigest.c (digest-probe): implement command.
-
-	* kuser/kdigest-commands.in (digest-probe): new command
-=09
-	* kdc/digest.c: Implement supportedMechs request.
-
-	* lib/krb5/error_string.c: Make krb5_get_error_string return an
-	allocated string to make the function indempotent. From
-	Zeqing (Fred) Xia.
-
-2007-12-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_locl.h (krb5_context_data): Flag if
-	default_cc_name was set by the user.
-
-	* lib/krb5/fcache.c (fcc_move): make sure ->version is uptodate.
-
-	* kcm/acquire.c: use krb5_free_cred_contents
-
-	* kuser/kimpersonate.c: use krb5_free_cred_contents
-=09
-	* kuser/kinit.c: Use krb5_cc_move to make an atomic switch of the
-	cred cache.
-
-	* lib/krb5/cache.c: Put back code that was needed, move gen_new
-	into new_unique.
-
-	* lib/krb5/mcache.c (mcc_default_name): Remove const
-
-	* lib/krb5/krb5_locl.h: Add KRB5_DEFAULT_CCNAME_KCM, redefine
-	KRB5_DEFAULT_CCNAME to KRB5_DEFAULT_CCTYPE
-
-	* lib/krb5/cache.c: Use krb5_cc_ops->default_name to get the
-	default name.
-
-	* lib/krb5/kcm.c: Implement krb5_cc_ops->default_name.
-
-	* lib/krb5/mcache.c: Implement krb5_cc_ops->default_name.
-
-	* lib/krb5/fcache.c: Implement krb5_cc_ops->default_name.
-
-	* lib/krb5/krb5.h: Add krb5_cc_ops->default_name.
-
-	* lib/krb5/acache.c: Free context when done, implement
-	krb5_cc_ops->default_name.
-
-	* lib/krb5/kcm.c: implement dummy kcm_move
-
-	* lib/krb5/mcache.c: Implement the move operation.
-
-	* lib/krb5/version-script.map: export krb5_cc_move
-
-	* lib/krb5/cache.c: New function krb5_cc_move().
-
-	* lib/krb5/fcache.c: Implement the move operation.
-
-	* lib/krb5/krb5.h: Add move to the krb5_cc_ops, causes major
-	version bump.
-
-	* lib/krb5/acache.c: Implement the move operation. Avoid using
-	cc_set_principal() since it broken on Mac OS X 10.5.0.
-=09
-2007-12-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_ccapi.h: Drop variable names to avoid -Wshadow.
-=09
-2007-11-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/krb5tgs.c: Should pass different key usage constants
-	depending on whether or not optional sub-session key was passed by
-	the client for the check of authorization data. The constant is
-	used to derive "specific key" and its values are specified in
-	7.5.1 of RFC4120.
-=09
-	Patch from Andy Polyakov.
-
-	* kdc/krb5tgs.c: Don't send auth data in referrals, microsoft
-	clients have started to not like that. Thanks to Andy Polyakov for
-	excellent research.
-
-2007-11-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/creds.c: use krb5_data_cmp
-
-	* lib/krb5/acache.c: use krb5_free_cred_contents
-
-	* lib/krb5/test_renew.c: use krb5_free_cred_contents
-=09
-2007-11-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/acl.c: doxygen documentation
-
-	* lib/krb5/addr_families.c: doxygen documentation
-
-	* doc: add doxygen
-
-	* lib/krb5/plugin.c: doxygen documentation
-
-	* lib/krb5/kcm.c: doxygen documentation
-
-	* lib/krb5/fcache.c: doxygen documentation
-
-	* lib/krb5/cache.c: doxygen documentations
-=09
-	* lib/krb5/doxygen.c: doxygen introduction
-
-	* lib/krb5/error_string.c: Doxygen documentation.
-
-2007-11-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/test_plugin.c: expose krb5_plugin_register
-
-	* lib/krb5/plugin.c: expose krb5_plugin_register
-
-	* lib/krb5/version-script.map: sort, expose krb5_plugin_register
-
-2007-10-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/kerberos5.c: Adding same enctype is enough one time. From
-	Andy Polyakov and Bjorn Sandell.
-=09
-2007-10-18  Love  <lha at stacken.kth.se>
-
-	* lib/krb5/cache.c (krb5_cc_retrieve_cred): check return value
-	from krb5_cc_start_seq_get. From Zeqing (Fred) Xia
-=09
-	* lib/krb5/fcache.c (init_fcc): provide better error codes
-
-	* kdc/kerberos5.c (get_pa_etype_info2): more paranoia, avoid
-	sending warning about pruned etypes.
-
-	* kdc/kerberos5.c (older_enctype): old windows enctypes (arcfour
-	based) "old", this to support windows 2000 clients (unjoined to a
-	domain). From Andy Polyakov.
-
-2007-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/setup.texi: Spelling, from Mark Peoples via Bjorn Sandell.
-=09
-2007-10-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/krb5tgs.c: More prettier printing of enctype, from KAMADA
-	Ken'ichi.
-
-	* lib/krb5/crypto.c (krb5_enctype_to_string): make sure string is
-	NULL on failure.
-
-2007-10-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/kdc-replay.c: Catch KRB5_PROG_ATYPE_NOSUPP from
-	krb5_addr2sockaddr and igore thte test is that case.
-=09
-2007-09-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/context.c (krb5_free_context): free
-	default_cc_name_env, from Gunther Deschner.
-
-2007-08-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/{krb5.h,pac.c,test_pac.c,send_to_kdc.c,rd_req.c}: Make
-	work with c++, reported by Hai Zaar
-
-	* lib/krb5/{digest.c,krb5.h}: Make work with c++, reported by Hai Zaar
-
-2007-08-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/hdb/Makefile.am: EXTRA_DIST +=3D hdb.schema
-
-2007-07-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* check return value of alloc functions, from Charles Longeau
-
-	* lib/krb5/principal.c: spelling.
-
-	* kadmin/kadmin.8: spelling
-
-	* lib/krb5/crypto.c: Check return values from alloc
-	functions. Prompted by patch of Charles Longeau.
-
-	* lib/krb5/n-fold.c: Make _krb5_n_fold return a error
-	code. Prompted by patch of Charles Longeau.
-
-2007-07-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/init_creds.c: Always set the ticket options, use
-	KRB5_ADDRESSLESS_DEFAULT as the default value, this make the unset
-	tri-state not so useful.
-
-2007-07-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* tools/heimdal-gssapi.pc.in: Add LIB_pkinit to the list of
-	libraries.
-
-	* tools/heimdal-gssapi.pc.in: pkg-config file for libgssapi in
-	heimdal.
-
-	* tools/Makefile.am: Add heimdal-gssapi.pc and install it into
-	$(libdir)/pkgconfig
-
-2007-07-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/pkinit.c: Add RFC3526 modp group14 as a default.
-
-2007-07-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/hdb/dbinfo.c (get_dbinfo): use dbname instead of realm as
-	key if the entry is a correct entry.
-
-	* lib/krb5/get_cred.c: Make krb5_get_renewed_creds work, from
-	Gunther Deschner.
-
-	* lib/krb5/Makefile.am: Add test_renew to noinst_PROGRAMS.
-
-	* lib/krb5/test_renew.c: Test for krb5_get_renewed_creds.
-
-2007-07-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/hdb/keys.c: Make parse_key_set handle key set string "v5",
-	from Peter Meinecke.
-
-	* kdc/kaserver.c: Don't ovewrite the error code, from Peter
-	Meinecke.
-
-2007-07-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* TODO-1.0: remove=20
-
-	* Makefile.am: remove TODO-1.0
-
-2007-07-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* Heimdal 1.0 release branch cut here
-=09
-	* doc/hx509.texi: use version.texi
-=09
-	* doc/heimdal.texi: use version.texi
-=09
-	* doc/version.texi: version.texi
-
-	* lib/hdb/db3.c: avoid type-punned pointer warning.
-
-	* kdc/kx509.c: Use unsigned char * as argument to HMAC_Update to
-	please OpenSSL and gcc.
-
-	* kdc/digest.c: Use unsigned char * as argument to MD5_Update to
-	please OpenSSL and gcc.
-
-2007-07-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* include/Makefile.am: Add krb_err.h.
-
-	* kdc/set_dbinfo.c: Print acl file too.
-
-	* kdc/kerberos4.c: Error codes are just fine, remove XXX now.
-
-	* lib/krb5/krb5-v4compat.h: Drop duplicate error codes.
-
-	* kdc/kerberos4.c: switch to ET errors.
-
-	* lib/krb5/Makefile.am: Add krb_err.h to build_HEADERZ.
-
-	* lib/krb5/v4_glue.c: If its a Kerberos 4 error-code, remove the
-	et BASE.
-
-2007-07-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5-v4compat.h: Include "krb_err.h".
-
-	* lib/krb5/v4_glue.c: return more interesting error codes.
-
-	* lib/krb5/plugin.c: Prefix enum plugin_type.
-
-	* lib/krb5/krb5_locl.h: Expose plugin structures.
-=09
-	* lib/krb5/krb5.h: Add plugin structures.
-
-	* lib/krb5/krb_err.et: V4 errors.
-
-	* lib/krb5/version-script.map: First version of version script.
-
-2007-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/kerberos5.c: Java 1.6 expects the name to be the same type,
-	lets allow that for uncomplicated name-types.
-
-2007-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/v4_glue.c (_krb5_krb_rd_req): if ticket contains
-	address 0, its ticket less and don't really care about
-	from_addr. return better error codes.
-
-	* kpasswd/kpasswdd.c: Fix pointer vs strict alias rules.
-
-2007-07-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/hdb/hdb-ldap.c: When using sambaNTPassword, avoid adding
-	more then one enctype 23 to krb5EncryptionType.
-
-	* lib/krb5/cache.c: Spelling.
-
-	* kdc/kerberos5.c: Don't send newer enctypes in ETYPE-INFO.
-	(get_pa_etype_info2): return the enctypes as sorted in the
-	database
-
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kuser/kinit.c: krb5-v4compat.h defines prototypes for
-	v4 (semiprivate functions) in libkrb5, don't include
-	krb5-private.h any longer.
-
-	* lib/krb5/krbhst.c: Set error string when there is no KDC for a
-	realm.
-
-	* lib/krb5/Makefile.am: New library version.
-
-	* kdc/Makefile.am: New library version.
-
-	* lib/krb5/krb5_locl.h: Add default_cc_name_env.
-
-	* lib/krb5/cache.c (enviroment_changed): return non-zero if
-	enviroment that will determine default krb5cc name has changed.
-	(krb5_cc_default_name): also check if cached value is uptodate.
-
-	* lib/krb5/krb5_locl.h: Drop pkinit_flags.
-
-2007-07-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* configure.in: add tests/java/Makefile
-
-	* lib/hdb/dbinfo.c: Add hdb_dbinfo_get_log_file.
-
-2007-07-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/kerberos5.c: Improve the default salt detection to avoid
-	returning v4 password salting to java that doesn't look at the
-	returning padata for salting.
-
-	* kdc: Split out krb5_kdc_set_dbinfo, From Andrew Bartlett
-
-2007-07-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/digest.c: Try harder to provide better error message for
-	digest messages.
-
-	* lib/krb5/Makefile.am: verify_krb5_conf_OBJECTS depends on
-	krb5-pr*.h, make -j finds this.
-=09
-2007-06-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/digest.c: On success, print username, not ip-adress.
-
-2007-06-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/get_cred.c: Add krb5_get_renewed_creds.
-
-	* lib/krb5/krb5_get_credentials.3: add krb5_get_renewed_creds
-
-	* lib/krb5/pkinit.c: Use hx509_cms_unwrap_ContentInfo.
-=09
-2007-06-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/setup.texi: Add example for pkinit_win2k_require_binding
-	in [kdc] section.
-
-	* kdc/default_config.c: Rename require_binding to
-	win2k_require_binding to match client configuration.
-
-	* kdc/default_config.c: Add [kdc]pkinit_require_binding option.
-
-	* kdc/pkinit.c (pk_mk_pa_reply_enckey): only allow non-bound reply
-	if its not required.
-
-	* kdc/default_config.c: rename pkinit_princ_in_cert and add
-	pkinit_require_binding
-
-	* kdc/kdc.h: rename pkinit_princ_in_cert and add
-	pkinit_require_binding
-
-	* kdc/pkinit.c: rename pkinit_princ_in_cert
-
-2007-06-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/pkinit.c: Adapt to hx509_verify_hostname change.
-
-2007-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/krb5tgs.c: Drop unused variable.
-
-	* kdc/krb5tgs.c: disable anonyous tgs requests
-
-	* kdc/krb5tgs.c: Don't check PAC on cross realm for now.
-
-	* kuser/kgetcred.c: Set KRB5_GC_CONSTRAINED_DELEGATION and parse
-	nametypes.
-
-	* lib/krb5/krb5_principal.3: Document krb5_parse_nametype.
-
-	* lib/krb5/principal.c (krb5_parse_nametype): parse nametype and
-	return their integer values.
-
-	* lib/krb5/krb5.h (krb5_get_creds): Add
-	KRB5_GC_CONSTRAINED_DELEGATION.
-
-	* lib/krb5/get_cred.c (krb5_get_creds): if
-	KRB5_GC_CONSTRAINED_DELEGATION is set, set both request_anonymous
-	and constrained_delegation.
-
-2007-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/digest.c: Return an error message instead of dropping the
-	packet for more failure cases.
-
-	* lib/krb5/krb5_principal.3: Add KRB5_PRINCIPAL_UNPARSE_DISPLAY.
-
-	* appl/gssmask/gssmask.c (AcquirePKInitCreds): fail more
-	gracefully
-=09
-2007-06-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/pac.c: make compile.
-=09
-	* lib/krb5/pac.c (verify_checksum): memset cksum to avoid using
-	pointer from stack.
-
-	* lib/krb5/plugin.c: Don't expose free pointer.
-
-	* lib/krb5/pkinit.c (_krb5_pk_load_id): fail directoy for first
-	calloc.
-=09
-	* lib/krb5/pkinit.c (get_reply_key*): don't expose freed memory
-
-	* lib/krb5/krbhst.c: Host is static memory, don't free.
-
-	* lib/krb5/crypto.c (decrypt_internal_derived): make sure length
-	is longer then confounder + checksum.
-
-	* kdc: export get_dbinfo as krb5_kdc_set_dbinfo and call from
-	users. This to allows libkdc users to to specify their own
-	databases
-
-	* lib/krb5/pkinit.c (pk_rd_pa_reply_enckey): simplify handling of
-	content data (and avoid leaking memory).
-
-	* kdc/misc.c (_kdc_db_fetch): set error string for failures.
-=09
-2007-06-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/pkinit.c: Use KRB5_AUTHDATA_INITIAL_VERIFIED_CAS.
-
-2007-06-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/pkinit.c: tell user when they got a pk-init request with
-	pkinit disabled.
-
-2007-06-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* lib/krb5/principal.c: Rename UNPARSE_NO_QUOTE to
-	UNPARSE_DISPLAY.
-
-	* lib/krb5/krb5.h: Rename UNPARSE_NO_QUOTE to UNPARSE_DISPLAY.
-
-	* lib/krb5/principal.c: Make no-quote mean replace strange chars
-	with space.
-
-	* lib/krb5/principal.c: Support KRB5_PRINCIPAL_UNPARSE_NO_QUOTE.
-
-	* lib/krb5/krb5.h: Add KRB5_PRINCIPAL_UNPARSE_NO_QUOTE.
-
-	* lib/krb5/test_princ.c: Test quoteing.
-
-	* lib/krb5/pkinit.c: update (c)
-=09
-	* lib/krb5/get_cred.c: use krb5_sendto_context to talk to the KDC.
-
-	* lib/krb5/send_to_kdc.c (_krb5_kdc_retry): check if the whole
-	process needs to restart or just skip this KDC.
-
-	* lib/krb5/init_creds_pw.c: Use krb5_sendto_context to talk to
-	KDC.
-
-	* lib/krb5/krb5.h: Add sendto hooks and opaque structure.
-
-	* lib/krb5/krb5_rd_error.3: Update prototype.
-
-	* lib/krb5/send_to_kdc.c: Add hooks for processing the reply from
-	the server.
-=09
-2007-06-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_err.et: Some new error codes from RFC 4120.
-=09
-2007-06-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/krb5tgs.c: Constify.
-
-	* kdc/kerberos5.c: Constify.
-
-	* kdc/pkinit.c: Check for KRB5-PADATA-PK-AS-09-BINDING. Constify.
-
-2007-06-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* include/Makefile.am: Make krb5-types.h nodist_include_HEADERS.
-
-	* kdc/Makefile.am: EXTRA_DIST +=3D version-script.map.
-=09
-2007-06-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* Makefile.am (print-distdir): print name of dist
-
-	* kdc/pkinit.c: Break out loading of mappings file to a separate
-	function and remove warning that it can't open the mapping file,
-	there are now mappings in the db, maybe the users uses that
-	instead...
-
-	* lib/krb5/crypto.c: Require the raw key have the correct size and
-	do away with the minsize.  Minsize was a thing that originated
-	from RC2, but since RC2 is done in the x509/cms subsystem now
-	there is no need to keep that around.
-
-	* lib/hdb/dbinfo.c: If there is no default dbname, also check for
-	unset mkey_file and set it default mkey name, make backward compat
-	stuff work.
-
-	* kdc/version-script.map: add new symbols
-
-	* kdc/kdc-replay.c: Also update krb5_context view of what the time
-	is.
-
-	* configure.in: add tests/can/Makefile
-
-	* kdc/kdc-replay.c: Add --[version|help].
-
-	* kdc/pkinit.c: Push down the kdc time into the x509 library.
-
-	* kdc/connect.c: Move up krb5_kdc_save_request so we can catch the
-	reply data too.
-
-	* kdc/kdc-replay.c: verify reply by checking asn1 class, type and
-	tag of the reply if there is one.
-
-	* kdc/process.c: Save asn1 class, type and tag of the reply if
-	there is one. Used to verify the reply in kdc-replay.
-
-2007-06-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/kdc_locl.h: extern for request_log.
-
-	* kdc/Makefile.am: Add kdc-replay.
-
-	* kdc/kdc-replay.c: Replay kdc messages to the KDC library.
-
-	* kdc/config.c: Pick up request_log from [kdc]kdc-request-log.
-
-	* kdc/connect.c: Option to save the request to disk.
-
-	* kdc/process.c (krb5_kdc_save_request): save request to file.
-
-	* kdc/process.c (krb5_kdc_process*): dont update _kdc_time
-	automagicly.
-	(krb5_kdc_update_time): set or get current kdc-time.
-
-	* kdc/pkinit.c (_kdc_pk_rd_padata): accept both pkcs-7 and
-	pkauthdata as the signeddata oid
-=09
-	* kdc/pkinit.c (_kdc_pk_rd_padata): Try to log what went wrong.
-
-2007-06-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* kdc/pkinit.c: Use oid_id_pkcs7_data for pkinit-9 encKey reply to
-	match windows DC behavior better.
-=09
-2007-06-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* configure.in: use test for -framework Security
-
-	* appl/test/uu_server.c: Print status to stdout.
-
-	* kdc/digest.c (digest ntlm): provide log entires by setting ret
-	to an error.
-=09
-2007-06-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/hx509.texi: Indent crl-sign.
-
-	* doc/hx509.texi: One more crl-sign example.
-
-	* lib/krb5/test_princ.c: plug memory leaks.
-
-	* lib/krb5/pac.c: plug memory leaks.
-
-	* lib/krb5/test_pac.c: plug memory leaks.
-
-	* lib/krb5/test_prf.c: plug memory leak.
-
-	* lib/krb5/test_cc.c: plug memory leaks.
-
-	* doc/hx509.texi: Simple blob about publishing CRLs.
-
-	* doc/win2k.texi: drop text about enctypes.
-=09
-2007-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/pkinit.c: In case of OCSP verification failure, referash
-	every 5 min. In case of success, refreash 2 min before expiring or
-	faster.
-=09
-2007-05-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* lib/krb5/krb5_err.et: add error 68, WRONG_REALM
-
-	* kdc/pkinit.c: Handle the ms san in a propper way, still cheat
-	with the realm name.
-
-	* kdc/kerberos5.c: If _kdc_pk_check_client failes, bail out
-	directly and hand the error back to the client.
-
-	* lib/krb5/krb5_err.et: Add missing REVOCATION_STATUS_UNAVAILABLE
-	and fix error message for CLIENT_NAME_MISMATCH.
-
-	* kdc/pkinit.c: More logging for pk-init client mismatch.
-
-	* kdc/kerberos5.c: Also add a KRB5_PADATA_PK_AS_REQ_WIN for
-	windows pk-init (-9) to make MIT clients happy.
-=09
-2007-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* kdc/pkinit.c: Force des3 for win2k.
-
-	* kdc/pkinit.c: Add wrapping to ContentInfo wrapping to
-	COMPAT_WIN2K.
-
-	* lib/krb5/keytab_keyfile.c: Spelling.
-
-	* kdc/pkinit.c: Allow matching by MS UPN SAN, note that this delta
-	doesn't deal with case of realm.
-=09
-2007-05-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/crypto.c (krb5_crypto_overhead): return static overhead
-	of encryption.
-=09
-2007-05-10  Dave Love  <fx at gnu.org>
-=09
-	* doc/win2k.texi: Update some URLs.
-
-2007-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kuser/kimpersonate.c: Fix version number of ticket, it should be
-	5 not the kvno.
-=09
-2007-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/setup.texi: Salting is really Encryption types and salting.
-=09
-2007-05-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* doc/setup.texi: spelling, from Ronny Blomme
-
-	* doc/win2k.texi: Fix ksetup /SetComputerPassword, from Ronny
-	Blomme
-=09
-2007-05-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/hdb/dbinfo.c (hdb_get_dbinfo) If there are no database
-	specified, create one and let it use the defaults.
-=09
-2007-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* lib/hdb/test_dbinfo.c: test acl file
-
-	* lib/hdb/test_dbinfo.c: test acl file
-
-	* lib/hdb/dbinfo.c: add acl file
-
-	* etc: ignore Makefile.in
-
-	* Makefile.am: SUBDIRS +=3D etc
-
-	* configure.in: Add etc/Makefile.
-
-	* etc/Makefile.am: make sure services.append is distributed
-
-2007-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc: rename windc_init to krb5_kdc_windc_init
-
-	* kdc/version-script.map: version script for libkdc
-=09
-	* kdc/Makefile.am: version script for libkdc
-=09
-2007-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/init_creds.c (krb5_get_init_creds_opt_get_error):
-	correct the order of the arguments.
-
-	* lib/hdb/Makefile.am: Add and test dbinfo.
-
-	* lib/hdb/hdb.h: Forward declaration for struct hdb_dbinfo;
-
-	* kdc/config.c: Use krb5_kdc_get_config and just fill in what the
-	users wanted differently.
-
-	* kdc/default_config.c: Make the default configuration fetch info
-	from the krb5.conf.
-=09
-2007-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/store.c (krb5_store_creds_tag): use session.keytype to
-	determine if to send the session-key, for the second place in the
-	function.
-
-	* tools/krb5-config.in: rename des to hcrypto
-
-	* kuser/Makefile.am: depend on libheimntlm
-
-	* kuser/kinit.c: Add --ntlm-domain that store the ntlm cred for
-	this domain if the Kerberos password auth worked.
-
-	* kuser/klist.c: add new option --hidden that doesn't display
-	principal that starts with @
-
-	* tools/krb5-config.in: Add heimntlm when we use gssapi.
-
-	* lib/krb5/krb5_ccache.3 (krb5_cc_retrieve_cred): document what to
-	free 'cred' with.
-
-	* lib/krb5/cache.c (krb5_cc_retrieve_cred): document what to free
-	'cred' with.
-=09
-2007-04-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/store.c (krb5_store_creds_tag): use session.keytype to
-	determine if to send the session-key.
-
-	* kcm/client.c (kcm_ccache_new_client): make root be able to pass
-	the name constraints, not the opposite. From Bryan Jacobs.
-=09
-2007-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kcm/acl.c: make compile again.
-
-	* kcm/client.c: fix warning.
-=09
-	* kcm: First, it allows root to ignore the naming conventions.
-	Second, it allows root to always perform any operation on any
-	ccache.  Note that root could do this anyway with FILE ccaches.
-	From Bryan Jacobs.
-
-	* Rename libdes to libhcrypto.
-
-2007-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kinit: remove code that depend on kerberos 4 library
-=09
-	* kdc: remove code that depend on kerberos 4 library
-=09
-	* configure.in: Drop kerberos 4 support.
-
-	* kdc/hpropd.c (main): free the message when done with it.
-
-	* lib/krb5/pkinit.c (_krb5_get_init_creds_opt_free_pkinit):
-	remember to free memory too.
-
-	* lib/krb5/pkinit.c (pk_rd_pa_reply_dh): free content-type when
-	done.
-
-	* configure.in: test rk_VERSIONSCRIPT
-=09
-2007-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* fix-export: remove, all done by make dist now
-
-2007-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_get_credentials.3: spelling, from Jason McIntyre
-
-2007-04-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/kstash.8: Spelling, from raga <raga at comcast.net>=20
-	via Bjorn Sandell.
-
-	* lib/krb5/store_mem.c: indent.
-
-	* lib/krb5/recvauth.c: Set error string.
-
-	* lib/krb5/rd_req.c: clear error strings.
-
-	* lib/krb5/rd_cred.c: clear error string.
-
-	* lib/krb5/pkinit.c: Set error strings.
-
-	* lib/krb5/get_cred.c: Tell what principal we are not finding for
-	all KRB5_CC_NOTFOUND.
-=09
-2007-02-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* kdc/kerberos5.c: Return the same error codes as a windows KDC.
-
-	* kuser/kinit.c: KRB5KDC_ERR_PREAUTH_FAILED is also a password
-	failed.
-=09
-	* kdc/kerberos5.c: Make handling of replying e_data more generic,
-	from metze.
-
-	* kdc/kerberos5.c: Fix (string const and shadow) warnings, from
-	metze.
-
-	* lib/krb5/pac.c: Create the PAC element in the same order as
-	w2k3, maybe there's some broken code in windows which relies on
-	this... From metze.
-
-	* kdc/kerberos5.c: Select a session enctype from the list of the
-	crypto systems supported enctype, is supported by the client and
-	is one of the enctype of the enctype of the krbtgt.
-=09
-	The later is used as a hint what enctype all KDC are supporting to
-	make sure a newer version of KDC wont generate a session enctype
-	that and older version of a KDC in the same realm can't decrypt.
-=09
-	But if the KDC admin is paranoid and doesn't want to have "no the
-	best" enctypes on the krbtgt, lets save the best pick from the
-	client list and hope that that will work for any other KDCs.
-=09
-	Reported by metze.
-
-	* kdc/hprop.c (propagate_database): on any failure, drop the
-	connection to the peer and try next one.
-=09
-2007-02-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_get_init_creds.3: document new options.
-
-	* kdc/krb5tgs.c: Only check service key for cross realm PACs.
-
-	* lib/krb5/init_creds.c: use the new merged flags field.
-	(krb5_get_init_creds_opt_set_win2k): new function, turn on all w2k
-	compat flags.
-
-	* lib/krb5/init_creds_pw.c: use the new merged flags field.
-
-	* lib/krb5/krb5_locl.h: merge all flags into one entity
-=09
-2007-02-11  Dave Love  <fx at gnu.org>
-=09
-	* lib/krb5/krb5_aname_to_localname.3: Small fixes
-=09
-	* lib/krb5/krb5_digest.3: Small fixes
-=09
-	* kuser/kimpersonate.1: Small fixes
-
-2007-02-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/init_creds_pw.c (find_pa_data): if there is no list,
-	there is no entry.
-
-	* kdc/krb5tgs.c: Don't check PACs on cross realm requests.
-
-	* lib/krb5/krb5.h: add KRB5_KU_CANONICALIZED_NAMES.
-
-	* lib/krb5/init_creds_pw.c: Verify client referral data.
-
-	* kdc/kerberos5.c: switch some "return ret" to "goto out".
-=09
-	* kdc/kerberos5.c: Pass down canonicalize request to hdb layer,
-	sign client referrals.
-=09
-	* lib/hdb/hdb.h: Add HDB_F_CANON.
-
-	* lib/hdb: add simple alias support to the database backends
-
-2007-02-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kuser/kinit.c: Add canonicalize flag.
-
-	* lib/krb5/init_creds_pw.c: Use EXTRACT_TICKET_* flags, support
-	canonicalize.
-
-	* lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_canonicalize):
-	new function.
-=09
-	* lib/krb5/get_cred.c: Use EXTRACT_TICKET_* flags.
-
-	* lib/krb5/get_in_tkt.c: Use EXTRACT_TICKET_* flags.
-
-	* lib/krb5/krb5_locl.h: Add EXTRACT_TICKET_* flags.
-=09
-2007-02-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/test_princ.c: test parsing enterprise-names.
-
-	* lib/krb5/principal.c: Add support for parsing enterprise-names.
-
-	* lib/krb5/krb5.h: Add KRB5_PRINCIPAL_PARSE_ENTERPRISE.
-
-	* lib/hdb/hdb-ldap.c: Make work again.
-=09
-2007-02-11  Dave Love  <fx at gnu.org>
-
-	* kcm/client.c (kcm_ccache_new_client): Cast snprintf'ed value.
-=09
-2007-02-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* doc/setup.texi: prune trailing space
-
-	* lib/hdb/db.c: Be better at setting and clearing error string.
-
-	* lib/hdb/hdb.c: Be better at setting and clearing error string.
-
-2007-02-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/keytab.c (krb5_kt_get_entry): Use krb5_kt_get_full_name
-	to print out the keytab name.
-
-	* doc/setup.texi: Spelling, from Guido Guenther
-=09
-2007-02-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/rd_cred.c: Plug memory leak, from Michael B Allen.
-
-2007-02-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/test_store.c (test_uint16): unsigned ints can't be
-	negative
-=09
-2007-02-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/pkinit.c: pass extra flags for detached signatures.
-
-	* lib/krb5/pkinit.c: pass extra flags for detached signatures.
-
-	* kdc/digest.c: Remove debug output.
-
-	* kuser/kdigest.c: Add support for ms-chap-v2 client.
-=09
-2007-02-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-	=09
-	* kdc/digest.c: Fix ms-chap-v2 get_masterkey
-
-	* kdc/digest.c: Fix ms-chap-v2 mutual response auth code.
-
-	* kuser/kdigest.c: Print session key if there is one.
-
-	* lib/krb5/digest.c: rename hash-a1 to session key
-
-	* kdc/digest.c: Add get_master from RFC 3079 3.4 for MS-CHAP-V2
-
-	* kuser/kdigest.c: print rsp if there is one, from Klas.
-
-	* kdc/digest.c: Use right size, from Klas Lindfors.
-
-	* kuser/kdigest.c: Set client nonce if avaible, from Klas.
-
-	* kdc/digest.c: First version from kllin.
-
-	* kuser/kdigest.c: Don't restrict the type.
-=09
-2007-02-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* kuser/kdigest-commands.in: add --client-response
-
-	* kuser/kdigest.c: Print status instead of response.
-
-	* kdc/digest.c: Better logging and return status =3D FALSE when
-	checksum doesn't match.
-
-	* kdc/digest.c: Check the digest response in the KDC.
-
-	* lib/krb5/digest.c: New functions to send in requestResponse to
-	KDC and get status of the request.
-
-	* kdc/digest.c: Add support for MS-CHAP v2.
-
-	* lib/hdb/hdb-ldap.c: Set hdb->hdb_db for ldap.
-=09
-2007-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* fix-export: Make hx509.info too
-
-	* kdc/digest.c: don't verify identifier in CHAP, its the client
-	that chooses it.
-=09
-2007-01-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/Makefile.am: Basic test of prf.
-
-	* lib/krb5/test_prf.c: Basic test of prf.
-
-	* lib/krb5/mit_glue.c: Add MIT glue for Kerberos RFC 3961 PRF
-	functions.
-
-	* lib/krb5/crypto.c: Add Kerberos RFC 3961 PRF functions.
-
-	* lib/krb5/krb5_data.3: Document krb5_data_cmp.
-
-	* lib/krb5/data.c: Add krb5_data_cmp.
-=09
-2007-01-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/kx509.c: Don't use C99 syntax.
-=09
-2007-01-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* configure.in: its LIBADD_roken (and shouldn't really exist, our
-	libtool usage it broken)
-
-	* configure.in: Add an extra variable for roken, LIBADD, that
-	should be used for library depencies.
-
-	* lib/krb5/send_to_kdc.c (krb5_sendto): zero out receive buffer.
-
-	* lib/krb5/krb5_init_context.3: fix mdoc errors
-
-	* Heimdal 0.8 branch cut today
-
-	* doc/hx509.texi: Spelling and more about proxy certificates.
-
-	* configure.in: check for arc4random
-=09
-2007-01-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* lib/krb5/send_to_kdc.c (krb5_sendto): zero receive krb5_data
-	before starting
-
-	* tools/heimdal-build.sh: make cvs keep quiet
-
-	* kuser/kverify.c: Use argument as principal if passed an
-	argument. Bug report from Douglas E. Engert
-=09
-2007-01-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* lib/krb5/rd_req.c (krb5_rd_req_ctx): The code failed to consider
-	the enc_tkt_in_skey case, from Douglas E. Engert.
-
-	* kdc/kx509.c: Issue certificates.
-
-	* kdc/config.c: Parse kx509/kca configuration.
-
-	* kdc/kdc.h: add kx509 config
-=09
-2007-01-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* kdc/kerberos5.c (_kdc_find_padata): if there is not padata,
-	there is nothing find.
-
-	* doc/hx509.texi: Examples for pk-init.
-
-	* doc/hx509.texi: About extending ca lifetime and sub cas.
-=09
-2007-01-13  Love H=F6rnquist =C5strand <lha at it.su.se>
-=09
-	* doc/hx509.texi: More about certificates.
-=09
-2007-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/hx509.texi: add Application requirements and write about
-	xmpp/jabber.
-=09
-2007-01-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/hx509.texi: More about issuing certificates.
-
-	* doc/hx509.texi: Start of a x.509 manual.
-
-	* include/Makefile.am: remove install headerfiles
-
-	* lib/krb5/test_pac.c: Use more interesting data to cause more
-	errors.
-
-	* include/Makefile.am: remove install headerfiles
-
-	* lib/krb5/mcache.c: MCC_CURSOR not used, remove.
-
-	* lib/krb5/crypto.c: macro kcrypto_oid_enc now longer used
-
-	* lib/krb5/rd_safe.c (krb5_rd_safe): set length before trying to
-	allocate data
-=09
-2007-01-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* doc/setup.texi: Hint about hxtool validate.
-
-	* appl/test/uu_server.c: print both "server" and "client"
-
-	* kdc/krb5tgs.c: Rename keys to be more obvious what they do.
-
-	* kdc/kerberos5.c: Use other keys to sign PAC with. From Andrew
-	Bartlett
-=09
-	* kdc/windc.c: ident, spelling.
-
-	* kdc/windc_plugin.h: indent.
-
-	* kdc/krb5tgs.c: Pass down server entry to verify_pac function.
-	from Andrew Bartlett
-
-	* kdc/windc.c: pass down server entry to verify_pac function, from
-	Andrew Bartlett
-
-	* kdc/windc_plugin.h: pass down server entry to verify_pac
-	function, from Andrew Bartlett
-
-	* configure.in: Provide a automake symbol ENABLE_SHARED if shared
-	libraries are built.
-
-	* lib/krb5/rd_req.c (krb5_rd_req_ctx): Use the correct keyblock
-	when verifying the PAC.  From Andrew Bartlett.
-=09
-2007-01-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/test_pac.c: move around to code test on real PAC.
-
-	* lib/krb5/pac.c: A tiny 2 char diffrence that make the code work
-	for real.
-
-	* lib/krb5/test_pac.c: Test more PAC (note that the values used in
-	this test is wrong, they have to be fixed when the pac code is
-	fixed).
-
-	* doc/setup.texi: Update to new hxtool issue-certificate usage
-
-	* lib/krb5/init_creds_pw.c: Make sure we don't sent both ENC-TS
-	and PK-INIT pa data, no need to expose our password protecting our
-	PKCS12 key.
-
-	* kuser/klist.c (print_cred_verbose): include ticket length in the
-	verbose output
-=09
-2007-01-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* lib/krb5/acache.c (loadlib): pass RTLD_LAZY to dlopen, without
-	it linux is unhappy.
-
-	* lib/krb5/plugin.c (loadlib): pass RTLD_LAZY to dlopen, without
-	it linux is unhappy.
-
-	* lib/krb5/name-45-test.c: One of the hosts I sometimes uses is
-	named "bar.domain", this make one of the tests pass when it
-	shouldn't.
-
-2007-01-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/setup.texi: Change --key argument to --out-key.
-
-	* kuser/kimpersonate.1: mangle my name
-=09
-2007-01-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* doc/setup.texi: describe how to use hx509 to create
-	certificates.
-
-	* tools/heimdal-build.sh: Add --distcheck.
-
-	* kdc/kerberos5.c: Check for KRB5_PADATA_PA_PAC_REQUEST to check
-	if we should include the PAC in the krbtgt.
-
-	* kdc/pkinit.c (_kdc_as_rep): check if
-	krb5_generate_random_keyblock failes.
-
-	* kdc/kerberos5.c (_kdc_as_rep): check if
-	krb5_generate_random_keyblock failes.
-
-	* kdc/krb5tgs.c (tgs_build_reply): check if
-	krb5_generate_random_keyblock failes.
-
-	* kdc/krb5tgs.c: Scope etype.
-
-	* lib/krb5/rd_req.c: Make it possible to turn off PAC check, its
-	default on.
-
-	* lib/krb5/rd_req.c (krb5_rd_req_ctx): If there is a PAC, verify
-	its server signature.
-
-	* kdc/kerberos5.c (_kdc_as_rep): call windc client access hook.
-	(_kdc_tkt_add_if_relevant_ad): constify in data argument.
-
-	* kdc/windc_plugin.h: More comments add a client_access hook.
-
-	* kdc/windc.c: Add _kdc_windc_client_access.
-
-	* kdc/krb5tgs.c: rename functions after export some more pac
-	functions.
-
-	* lib/krb5/test_pac.c: export some more pac functions.
-
-	* lib/krb5/pac.c: export some more pac functions.
-
-	* kdc/krb5tgs.c: Resign the PAC in tgsreq if we have a PAC.
-
-	* configure.in: add tests/plugin/Makefile
-=09
-2007-01-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* kdc/krb5tgs.c: Get right key for PAC krbtgt verification.
-
-	* kdc/config.c: spelling
-
-	* lib/krb5/krb5.h: typedef for krb5_pac.
-
-	* kdc/headers.h: Include <windc_plugin.h>.
-
-	* kdc/Makefile.am: Include windc.c and use windc_plugin.h
-
-	* kdc/krb5tgs.c: Call callbacks for emulating a Windows Domain
-	Controller.
-
-	* kdc/kerberos5.c: Call callbacks for emulating a Windows Domain
-	Controller.  Move the some of the log related stuff to its own
-	function.
-
-	* kdc/config.c: Init callbacks for emulating a Windows Domain
-	Controller.
-
-	* kdc/windc.c: Rename the init function to windc instead of pac.
-
-	* kdc/windc.c: Callbacks specific to emulating a Windows Domain
-	Controller.
-
-	* kdc/windc_plugin.h: Callbacks specific to emulating a Windows
-	Domain Controller.
-
-	* lib/krb5/Makefile.am: add krb5_HEADERS to build_HEADERZ
-
-	* lib/krb5/pac.c: Support all keyed checksum types.
-=09
-2007-01-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-	* lib/krb5/pac.c (krb5_pac_get_types): Return list of types.
-=09
-	* lib/krb5/test_pac.c: test krb5_pac_get_types
-
-	* lib/krb5/krbhst.c: Add KRB5_KRBHST_KCA.
-
-	* lib/krb5/krbhst.c: Add KRB5_KRBHST_KCA.
-
-	* lib/krb5/krb5.h: Add KRB5_KRBHST_KCA.
-
-	* lib/krb5/test_pac.c: test Add/remove pac buffer functions.
-
-	* lib/krb5/pac.c: Add/remove pac buffer functions.
-
-	* lib/krb5/pac.c: sprinkle const
-
-	* lib/krb5/pac.c: rename DCHECK to CHECK
-=09
-	* Happy New Year.
+	* Happy new year.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/ChangeLog.2002
--- a/head/crypto/heimdal/ChangeLog.2002	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/ChangeLog.2002	Tue Apr 17 11:51:51 2012 +0300
@@ -663,7 +663,7 @@
=20
 	* lib/krb5/keytab_keyfile.c (akf_add_entry): don't create the file
 	before we need to write to it
-	(from =C5ke Sandgren)
+	(from =C3=85ke Sandgren)
=20
 2002-02-14  Johan Danielsson  <joda at pdc.kth.se>
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/ChangeLog.2003
--- a/head/crypto/heimdal/ChangeLog.2003	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/ChangeLog.2003	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-2003-12-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/error_string.c: protect error_string with mutex
 =09
@@ -6,28 +6,28 @@
 =09
 	* lib/krb5/krb5.h (krb5_context_data): add mutex for error_string
 =09
-2003-12-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: make -9 work again
 =09
-2003-12-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c: try handle ts preauth better, still
 	not good, but at least it work with older heimdal releases that
 	doesn't send back KRB5KDC_ERR_PREAUTH_REQUIRED when preauth was
 	sent
=20
-2003-12-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb.asn1: remove enforce-transited-policy, its no longer
 	used
=20
-2003-12-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/pkinit.c (_krb5_pk_create_sign): fill in NULL as
 	parameters, required by CMS
=20
-2003-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/get_in_tkt_with_keytab.c (krb5_get_in_tkt_with_keytab):
 	avoid memory leak that snuck in when krb5_keytab_key_proc was
@@ -49,12 +49,12 @@
 	* lib/krb5/auth_context.c: add krb5_auth_con_addflags and
 	krb5_auth_con_removeflags
=20
-2003-12-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c (decrypt_internal_derived): move up padsize to
 	avoid memory leak
=20
-2003-12-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c: require cipher-text to be padded to padsize
 =09
@@ -65,7 +65,7 @@
 	EAI_NODATA, because its depricated in RFC3493 Pointed out by
 	Hajimu UMEMOTO <ume at mahoroba.org> on heimdal-discuss
=20
-2003-12-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: move test_crypto to noinst_PROGRAMS
 =09
@@ -73,7 +73,7 @@
 =09
 	* kuser/kinit.c (main): return the return value from simple_execvp
 =09
-2003-11-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: don't use PKINIT DH per default since its too
 	slow
@@ -86,13 +86,13 @@
 	* lib/krb5/pkinit.c: clean up error handling, make enc-type work
 	again
=20
-2003-11-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: add flag to make it work with pkinit dh
 =09
 	* lib/krb5/pkinit.c: make PKINIT DH support work
 =09
-2003-11-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/Makefile.am (LDADD): link with LIB_dlopen
 =09
@@ -119,7 +119,7 @@
 =09
 	* lib/krb5/pkinit.c: fix bugs, improve error reporting
=20
-2003-11-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: add some "struct foo;" glue for pkinit
 	structures that isn't used
@@ -139,22 +139,22 @@
 =09
 	* lib/krb5/heim_threads.h: include pthread.h in the pthread case
 =09
-2003-11-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswdd.c (main): parse kdc.conf
 	From: Jeffrey Hutzelman <jhutz at cmu.edu>
 =09
-2003-11-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am (TESTS): add test_crypto
 =09
 	* lib/krb5/test_crypto.c: time crypto operations
 =09
-2003-11-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/init-creds: spelling, Bruno Rohee <bruno at rohee.com>
 =09
-2003-11-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/rd_req.c (krb5_verify_ap_req2): krb5_free_ticket free
 	the ticket now, rewrite error handling to handle that
@@ -170,7 +170,7 @@
 =09
 	* lib/krb5/krb5_ticket.3: krb5_free_ticket free the whole ticket
 =09
-2003-11-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/padata.c: add krb5_padata_add
 =09
@@ -195,7 +195,7 @@
 	implements -09 of the draft), verify that it conforms the new
 	draft
=20
-2003-11-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/der_copy.c (copy_oid): copy all components
 =09
@@ -218,7 +218,7 @@
 	* kdc/config.c: change enforce_transited_policy to a tri-state
 	variable
=20
-2003-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/transited.c (krb5_domain_x500_encode): always zero out
 	encoding to make sure it have a defined value on failure
@@ -232,7 +232,7 @@
 	* kdc/kerberos5.c (fix_transited_encoding): always print
 	cross-realm information
 =09
-2003-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: spelling, From: Tracy Di Marco White
 =09
@@ -249,7 +249,7 @@
=20
 	* lib/hdb/hdb.asn1: add flag to enforce transited policy
=20
-2003-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/transited.c (krb5_domain_x500_decode): set *num_realms
 	to zero not num_realms
@@ -281,7 +281,7 @@
 	the cache at the same time, and there is no simple way to add a
 	timeout to the lock.
=20
-2003-10-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c: print the error value
 	krb5_init_context failed with
@@ -302,13 +302,13 @@
 	* kuser/klist.c (print_tickets): bail out if krb5_cc_next_cred
 	returns error other than KRB5_CC_END
=20
-2003-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c: add some help function that is common
 	between ENC_TS and SAM2, free the etype{,2}-infos on failure, move
 	the pa counter into krb5_get_init_creds_ctx
 =09
-2003-10-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kaserver.c (do_getticket): if times data is shorter then 8
 	byte, request is malformed.
@@ -323,13 +323,13 @@
=20
 	* lib/krb5/verify_krb5_conf.c: parse [kdc]use_2b and [gssapi]
 =09
-2003-10-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/lex.l: add BOOLEAN
 =09
 	* lib/asn1/parse.y: add BOOLEAN
 =09
-2003-10-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: When running kinit in "fork mode" do pagsh
 	independent of krb4, also always do krb4 setup of cc. Always try
@@ -374,12 +374,12 @@
 =09
 	* lib/asn1: add boolean support
=20
-2003-10-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/changepw.c (setpw_send_request): free ap_req_data on
 	failure
=20
-2003-09-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/test/http_client.c (do_connect): use ai_protocol 0
 =09
@@ -402,7 +402,7 @@
 	* lib/krb5/krb5.h: flags for krb5_krbhst_init_flags (and
 	krb5_send_to_kdc_flags)
=20
-2003-09-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/rd_req.c (krb5_rd_req): if we have a keyblock in auth
 	context, use that
@@ -411,7 +411,7 @@
 =09
 	* lib/asn1/asn1_print.c: decode IA5Stringa and UTF8String
 =09
-2003-09-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c: use _krb5_get_init_creds_opt_copy
 	* lib/krb5/init_creds.c: don't export krb5_get_init_creds_opt_copy
@@ -420,7 +420,7 @@
 =09
 	* kuser/kinit.c: don't get v4 tickets by default
 =09
-2003-09-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswdd.c (process): remove a abort()
 =09
@@ -432,7 +432,7 @@
 	defined by RFC3244 -- Microsoft Windows 2000 Kerberos Change
 	Password and Set Password Protocols
=20
-2003-09-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/db3.c: improve readability of ->open ifdef, check if
 	version >=3D 4.1
@@ -444,7 +444,7 @@
 	keytab can still pass in the key of the service (matches behavior
 	of MIT Kerberos).
 =09
-2003-09-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c: collect all init_creds context into a
 	structure so it can easier be passed around, also, while here,
@@ -460,12 +460,12 @@
 	* lib/krb5/log.c (log_realloc): increase len after realloc returns
 	sucessfully
=20
-2003-09-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/config_file.c: fix prototypes
 	From: Fredrik Ljungberg <flag at pobox.se>
 =09
-2003-09-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/test/http_client.c: close socket when we are done, don't
 	allow the server to restart gssapi negotiation
@@ -486,7 +486,7 @@
 =09
 	* appl/test/Makefile.am: build http_client
 =09
-2003-09-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/asn1_print.c: add support for printing Enumerated
 =09
@@ -502,7 +502,7 @@
 	* kdc/kerberos5.c (only_older_enctype_p): check request if the
 	client only supports old enctypes, before it used the database
 =09
-2003-09-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* **/*.c: add context argument to krb5_get_init_creds_opt_alloc
=20
@@ -511,7 +511,7 @@
=20
 	* lib/krb5/krb5_get_init_creds.3: spelling
 =09
-2003-09-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c (add_file): make len argument an pointer to
 	an integer
@@ -526,7 +526,7 @@
=20
 	* lib/krb5/krb5.conf.5: document appdefaults/{forward,encrypt}
=20
-2003-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h: Add key usage for encryption of the
 	SAM-NONCE-OR-SAD field.
@@ -597,7 +597,7 @@
 	* lib/krb5/krb5_locl.h: add struct
 	_krb5_get_init_creds_opt_private
=20
-2003-09-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h: add SAM keyusage numbers, add s2k proc typedef,
 	add a pointer to a private part of krb5_get_init_creds_opt
@@ -605,7 +605,7 @@
 	* kdc/string2key.c (main): avoid const warning by using a extra
 	variable
=20
-2003-08-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/ticket.c (krb5_ticket_get_authorization_data_type):
 	reindent
@@ -614,18 +614,18 @@
 	failing, copy data to right memory, the later pointed out by Luke
 	Howard.
=20
-2003-08-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h: cfx-01 use diffrent usage numbers
 =09
-2003-08-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/db3.c: try to include more db headers
=20
 	* lib/hdb/db3.c: patch for working with DB4 on heimdal-discuss
 	From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-08-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h: add KEYTYPE_ARCFOUR_56
 =09
@@ -635,18 +635,18 @@
 =09
 	* lib/asn1/k5.asn1: add KRB5_NT_SMTP_NAME and KRB5_NT_ENTERPRISE
 =09
-2003-08-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/test/uu_client.c (proto): fill in client in the match cred
 =09
-2003-08-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h: CFX uses slightly diffrent usage numbers
 =09
 	* lib/krb5/crypto.c (usage2arcfour): simplify, only include
 	special cases From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: code rewrite from Luke Howard
 	<lukeh at PADL.COM>
@@ -656,7 +656,7 @@
 =09
 	* doc/ack.texi: update Luke Howard email address
 =09
-2003-08-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_encrypt.3: document:
 	krb5_crypto_getconfoundersize, krb5_crypto_getblocksize
@@ -666,7 +666,7 @@
 	krb5_crypto_getconfoundersize): added From: Luke Howard
 	<lukeh at PADL.COM>
=20
-2003-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/connect.c (handle_tcp): handle recvfrom returning 0
 	(connection closed)
@@ -689,7 +689,7 @@
 	* lib/asn1/gen.c: s/UTF8String/heim_utf8_string/ in generated code
 	From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-08-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* include/make_crypto.c: include aes.h inc in the local libdes
 	case too
@@ -700,7 +700,7 @@
 =09
 	* lib/asn1/gen_free.c: set free'd poiners to NULL
 =09
-2003-08-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/heim_threads.h: XXX don't use "plain" pthread support
 	on netbsd
@@ -709,7 +709,7 @@
 	krb5_create_checksum and krb5_verify_checksum, From: Luke Howard
 	<lukeh at PADL.COM>
=20
-2003-08-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_config.c: check krb5_prepend_config_files_default
 	and krb5_prepend_config_files
@@ -717,7 +717,7 @@
 	* lib/krb5/context.c: add krb5_prepend_config_files and
 	krb5_prepend_config_files_default
=20
-2003-08-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/mkey.c (read_master_mit): krb5_ret_int16 takes a int16_t
 	as argument
@@ -743,7 +743,7 @@
 	with the mit implemtation, don't free `creds' argument when done,
 	its up the the caller to do that, also allow a NULL ccache.
 =09
-2003-08-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.conf.5: document tgs_require_subkey
 =09
@@ -766,35 +766,35 @@
=20
 	* kdc/kerberos5.c (*): handle krb5_unparse_name returning non-zero
 =09
-2003-08-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/principal.c (unparse_name): len can't be zero, so,
 	don't check for that
=20
-2003-08-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/principal.c (unparse_name): make sure there are space
 	for a NUL, set *name to NULL when there is a failure (so caller
 	can't get hold of a freed pointer)
=20
-2003-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/kerberos.8: remove duplicate manual, from
 	cjep at netbsd.org
=20
-2003-07-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/cache.c: indent
 =09
 	* lib/krb5/cache.c (krb5_cc_set_default_name): only read
 	KRB5CCNAME when not suid
=20
-2003-07-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab_krb4.c (read_v4_entry): the des key is 8 bytes,
 	use a char array instead of des_cblock
=20
-2003-07-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c: add support for KRB5_PADATA_ETYPE_INFO2
 =09
@@ -802,7 +802,7 @@
 	memory, update callsites to either return error or use krb5_abortx
 	(krb5_hmac): expose hmac
=20
-2003-07-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/keyblock.c (krb5_keyblock_get_enctype): return enctype
 	of keyblock
@@ -845,7 +845,7 @@
 	error string when there is a context
 	(krb5_checksum_is_collision_proof): ditto
=20
-2003-07-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/mit_glue.c (krb5_c_get_checksum): make type and data
 	argument optional
@@ -862,7 +862,7 @@
=20
 	* lib/krb5/krb5.h: add krb5_enc_data
 =09
-2003-07-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.3: add krb5_c_ functions
 =09
@@ -880,7 +880,7 @@
 	only matter for aes, for all other enctypes the key and unkeyed
 	checksum have the same length.
=20
-2003-07-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/mit_glue.c: first version of krb5_c encryption glue
=20
@@ -890,11 +890,11 @@
 	static to avoid warning from dynamic backend when using a known
 	static backend
=20
-2003-07-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/cache.c: don't return value in void function
 =09
-2003-07-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/creds.c (krb5_compare_creds): if client is specified in
 	the mcreds, check that too
@@ -904,11 +904,11 @@
 =09
 	* lib/asn1: prefix typedefs and structs with heim_
=20
-2003-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb.c: avoid unnecessary setting of variable
 =09
-2003-07-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/klist.c (check_for_tgt): use krb5_cc_clear_mcred
 =09
@@ -923,12 +923,12 @@
 	* lib/krb5/cache.c (krb5_cc_clear_mcred): new function, clear a
 	krb5_creds to use with krb5_cc_retrieve_cred
 =09
-2003-06-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb.c (find_dynamic_method): if there isn't a prefix,
 	don't load anything
=20
-2003-06-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb.c: Dynamic backend loading, based on patch from Luke
 	Howard <lukeh at PADL.COM>
@@ -936,7 +936,7 @@
 	* lib/hdb/hdb.h: add struct hdb_so_method and
 	HDB_INTERFACE_VERSION
=20
-2003-06-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/mk_req_ext.c (krb5_mk_req_internal): when using
 	arcfour-hmac-md5, use an unkeyed checksum (rsa-md5), since
@@ -956,12 +956,12 @@
 	* lib/krb5/krb5_kuserok.3: put Nd argument in double quotes since
 	it contains more than 9 words; from wiz
=20
-2003-06-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c: add missing " within #if 0, from
 	stefan sokoll <stefansokoll at yahoo.de>
=20
-2003-06-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_timeofday.3: improve krb5_set_real_time text
 =09
@@ -973,7 +973,7 @@
=20
 	* kuser/kinit.c: add -A as an alias for --no-addresses
=20
-2003-06-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_for_creds.c (krb5_get_forwarded_creds): pass in a
 	krb5_timestamp to krb5_us_timeofday
@@ -993,7 +993,7 @@
 	* lib/asn1/k5.asn1: make the aes and sha1 checksum types match
 	draft-ietf-krb-wg-crypto-05
=20
-2003-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/aes-test.c: add a test for aes kcrypto encrypted data
 =09
@@ -1004,12 +1004,12 @@
 	(derive_key): always remove the key->schedule since its
 	will contain the wrong (parent key) info
=20
-2003-06-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/aes-test.c: add aes256 test vectors from Ken Raeburn
 	* doc/setup.texi: add more kdc's to the example
 =09
-2003-06-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: use int2HDBFlags/HDBFlags2int From: Alberto
 	Patino <jalbertop at aranea.com.mx>, Luke Howard <lukeh at PADL.COM>
@@ -1028,13 +1028,13 @@
 	* lib/krb5/crypto.c: add _krb5_AES_string_to_default_iterator add
 	krb5_string_to_key_salt_opaque() fix keylengh for keytype_aes256
 =09
-2003-06-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: Point out that slave needs /var/heimdal
 	directory and masterkey From: Mans Nilsson <mansaxel at sunet.se>,
 	Fix spelling while here
 =09
-2003-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am, krb5_get_in_cred.3, krb5.3:
 	add manpage for: krb5_get_in_cred, krb5_get_in_tkt,
@@ -1052,7 +1052,7 @@
 	"unsigned" integers. If MSB is set, we need to pad with a zero
 	byte.
=20
-2003-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_c_make_checksum.3: some more mdoc fixes
 =09
@@ -1062,14 +1062,14 @@
 =09
 	From Alberto Patino <jalbertop at aranea.com.mx>
=20
-2003-05-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/*.[0-9]: pacify mdoclink
=20
 	* lib/krb5/krb5_ccache.3: document diffrences between mit and
 	heimdal krb5_cc_gen_new ccache -> credential cache s/[\t ]+$//
 =09
-2003-05-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* appl/test/gssapi_server.c (proto): start to use
 	gss_krb5_copy_ccache
@@ -1077,14 +1077,14 @@
 	* appl/test/nt_gss_server.c (proto): comment out gss_ctx_id_t
 	groveling for now
=20
-2003-05-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1:
 	- add parser/generate glue for UTF8String and NULL
 	  (DER primitive encode/decode functions missing)
 	- handle parsing of DEFAULT and, ...
=20
-2003-05-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/heim_threads.h: add missing argument to mutex_init
 =09
@@ -1097,7 +1097,7 @@
 	* lib/krb5/heim_threads.h: wrapper macros for thread
 	synchronization primitives
=20
-2003-05-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_principal.3
 	lib/krb5/Makefile.am:
@@ -1109,7 +1109,7 @@
 	* lib/krb5/krb5_sname_to_principal.3: remove file
 	* lib/krb5/krb5_principal_get_realm.3: remove file
=20
-2003-05-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.8: sort sections, from netbsd
 =09
@@ -1148,7 +1148,7 @@
 	* kuser/kinit.1: setup -> set up, new sentence, new line from
 	Thomas Klausner <wiz at netbsd.org>
 =09
-2003-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswd.1: handle setting passwords for multiple
 	principals at the same time
@@ -1160,7 +1160,7 @@
 	rfc3244 share the response packet sure more constants now that
 	they exists
=20
-2003-05-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h: some define for rfc3244
 =09
@@ -1182,7 +1182,7 @@
 	* lib/asn1/k5.asn1: add ChangePasswdDataMS, for
 	RFC3244
=20
-2003-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kuser/kdestroy.c: destroy tokens even if there isn't v4 support
=20
@@ -1199,7 +1199,7 @@
 	everything with hex-codes, and cast to unsigned char* to make some
 	compilers happy
=20
-2003-05-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_in_tkt.c (make_pa_enc_timestamp): make sure first
 	argument to krb5_us_timeofday have correct type
@@ -1208,12 +1208,12 @@
=20
 	* include/make_crypto.c (main): include aes.h if ENABLE_AES
=20
-2003-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* make-release: when fixing a valid cvs tag from release name
 	replace all number. to number- for all non-overlapping matches
 =09
-2003-05-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/Makefile.am: gen_files +=3D asn1_ETYPE_INFO2.x and
 	asn1_ETYPE_INFO2_ENTRY.x
@@ -1231,20 +1231,20 @@
 	* doc/apps.texi: text about applications using kerberos
 	move afs text here
 =09
-2003-05-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: add cross realm text
 =09
-2003-04-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_crypto_init.3: document krb5_enctype_to_string and
 	krb5_string_to_enctype
=20
-2003-04-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/v4_dump.c (v4_prop_dump): limit strings length, from openbsd
 =09
-2003-04-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/aes-test.c: use _krb5_PKCS5_PBKDF2
 	* lib/krb5/crypto.c: unexport krb5_PKCS5_PBKDF2
@@ -1267,12 +1267,12 @@
 	* lib/krb5/krb5.h (krb5_replay_data): make usec signed (matching
 	asn1)
=20
-2003-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/programming.texi: s/managment/management/, from jmc
 	<jmc at prioris.mini.pw.edu.pl>
=20
-2003-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c (default_etypes): also advertise that we
 	handle aes encryption types
@@ -1287,11 +1287,11 @@
=20
 	* lib/asn1/k5.asn1: add ETYPE-INFO2 and ETYPE-INFO2-ENTRY
 =09
-2003-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krbhst.c: copy NUL too, from janj at wenf.org via openbsd
 =09
-2003-04-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/der_copy.c (copy_general_string): use strdup
 	* lib/asn1/der_put.c: remove sprintf
@@ -1303,7 +1303,7 @@
 =09
 	* lib/krb5/test_alname.c: add --version and --help
 =09
-2003-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_warn.3: add krb5_get_err_text
 =09
@@ -1320,7 +1320,7 @@
 	needs to be defined on the command line, since lex likes to
 	include stdio.h before we get to config.h
=20
-2003-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/*.3: Change .Fd #include <header.h> to .In header.h,
 	from Thomas Klausner <wiz at netbsd.org>
@@ -1328,19 +1328,19 @@
 	* lib/krb5/krb5.conf.5: spelling, from Thomas Klausner
 	<wiz at netbsd.org>
=20
-2003-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c: fix some more memory leaks
 =09
-2003-04-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/kf/kf.1: spelling, from jmc <jmc at prioris.mini.pw.edu.pl>
 =09
-2003-04-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* admin/ktutil.8: typos, from jmc <jmc at acn.waw.pl>
 =09
-2003-04-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.3: s/kerberos/Kerberos/
 	* lib/krb5/krb5_data.3: s/kerberos/Kerberos/
@@ -1350,7 +1350,7 @@
 	* kuser/kinit.1: s/kerberos/Kerberos/
 	* kdc/kdc.8: s/kerberos/Kerberos/
 =09
-2003-04-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_alname.c: more krb5_aname_to_localname tests
 =09
@@ -1372,21 +1372,21 @@
 	kvno the resulting kvno is going to be. Now two ktutil change in a
 	row works. XXX fix the protocol to pass the kvno back.
 =09
-2003-03-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/kf/kf.1: afs->AFS, from jmc <jmc at acn.waw.pl>
 =09
-2003-03-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: add description on how to turn on v4, 524 and
 	kaserver support
=20
-2003-03-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c (appdefaults_entries): add afslog
 	and afs-use-524
=20
-2003-03-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (as_rep): when the second enctype_to_string
 	failes, remember to free memory from the first enctype_to_string
@@ -1403,13 +1403,13 @@
 	* lib/krb5/crypto.c (krb5_enctype_keysize): return key size of
 	encyption type, inspired by Aidan Cully <aidan at kublai.com>
 =09
-2003-03-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab.c (krb5_kt_get_entry): avoid printing 0
 	(wildcard kvno) after principal when the keytab entry isn't found,
 	reported by Chris Chiappa <chris at chiappa.net>
 =09
-2003-03-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/misc.texi: update 2b example to match reality (from
 	mattiasa at e.kth.se)
@@ -1417,7 +1417,7 @@
 	* doc/misc.texi: spelling and add `Configuring AFS clients'
 	subsection
=20
-2003-03-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.3: add krb5_free_data_contents.3
 =09
@@ -1438,15 +1438,15 @@
=20
 	* kdc/string2key.c: print the used enctype for kerberos 5 keys
=20
-2003-03-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/aes-test.c: add another arcfour test
 =09
-2003-03-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/aes-test.c: sneek in a test for arcfour-hmac-md5
 =09
-2003-03-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/krb5_ccache.3: update .Dd
=20
@@ -1461,7 +1461,7 @@
 	change. reported by Iain Moffat @ ufl.edu via Howard Chu
 	<hyc at highlandsun.com>
=20
-2003-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_keytab.3: spelling, from
 	<jmc at prioris.mini.pw.edu.pl>
@@ -1474,7 +1474,7 @@
 	* lib/krb5/krb5_auth_context.3: spelling, from
 	<jmc at prioris.mini.pw.edu.pl>
=20
-2003-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/Makefile.am: INCLUDES: -I$(srcdir)/../lib/krb5
 =09
@@ -1498,7 +1498,7 @@
 	* kdc/config.c: add --enable-kerberos4-cross-realm option (default
 	to off)
=20
-2003-03-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am (man_MANS) +=3D krb5_aname_to_localname.3
 =09
@@ -1507,7 +1507,7 @@
=20
 	* lib/krb5/krb5_kuserok.3: s/KRB5_USEROK/KRB5_KUSEROK/
 =09
-2003-03-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am (man_MANS): add krb5_set_default_realm.3
=20
@@ -1533,14 +1533,14 @@
 	* lib/krb5/cache.c (krb5_cc_get_ops): new function, return ops for
 	a id
=20
-2003-03-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/intro.texi: add reference to source code, binaries and the
 	manual
=20
 	* lib/krb5/krb5.3: krb5.h isn't in krb5 directory in heimdal
 =09
-2003-03-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kdc.8: better/difrent english
=20
@@ -1554,7 +1554,7 @@
 	* lib/krb5/krb5_ccache.3: add missing name of argument
 	(krb5_context) to most functions
=20
-2003-03-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/kuserok.c (krb5_kuserok): preserve old behviour of
 	function and return FALSE when there isn't a local account for
@@ -1563,12 +1563,12 @@
 	* lib/krb5/krb5_kuserok.3: fix prototype, spelling and more text
 	describing the function
=20
-2003-03-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/cache.c (krb5_cc_default): if krb5_cc_default_name
 	returned memory, don't return ENOMEM
=20
-2003-03-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.3: add krb5_address stuff and sort
 =09
@@ -1579,7 +1579,7 @@
 	* lib/krb5/krb5_address.3: document types krb5_address and
 	krb5_addresses and their helper functions
=20
-2003-03-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am (man_MANS): +=3D krb5_kuserok.3
=20
@@ -1622,20 +1622,20 @@
=20
 	* lib/krb5/krb5.h (krb5_context_data): add default_cc_name
 =09
-2003-02-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/kf/kf.1: s/securly/securely/ from NetBSD
 =09
-2003-02-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/connect.c: s/intialize/initialize, from
 	<jmc at prioris.mini.pw.edu.pl>
=20
-2003-02-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: add AM_MAINTAINER_MODE
 =09
-2003-02-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* **/*.[0-9]: add copyright/licenses on all manpages
=20
@@ -1645,35 +1645,35 @@
 	PA-ENC-TIMESTAMP in the AS-REQ, using the first encryption
 	type specified by the KDC.
=20
-2003-02-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* fix-export: some autoconf put their version number in
 	autom4te.cache, so remove autom4te*.cache
 =09
 	* fix-export: make sure $1 is a directory
 =09
-2003-02-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswdd.8: spelling, from jmc <jmc at prioris.mini.pw.edu.pl>
=20
 	* kdc/kdc.8: spelling, from jmc <jmc at prioris.mini.pw.edu.pl>
 =09
-2003-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/hpropd.8: s/databases/a database/ s/Not/not/
=20
 	* kdc/hprop.8: add missing .
 =09
-2003-01-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.conf.5: documentation for of boolean, etypes,
 	address, write out encryption type in sentences, s/Host/host
 =09
-2003-01-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/check-gen.c: add checks for Authenticator too
 =09
-2003-01-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: in the hprop example, use hprop and the first
 	component, not host
@@ -1682,7 +1682,7 @@
 	point-to-point might not have an address, just ignore
 	those. Reported by Harald Barth.
=20
-2003-01-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c (check_section): when key isn't
 	found, don't print out all known keys
@@ -1713,7 +1713,7 @@
 	* lib/asn1/check-der.c: move out the generic asn1/der functions to
 	a common file
=20
-2003-01-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/misc.texi: more text about afs, how to get get your KeyFile,
 	and how to start use 2b tokens
@@ -1726,7 +1726,7 @@
 	* kuser/kuser_locl.h: include crypto-headers.h for
 	des_read_pw_string prototype
=20
-2003-01-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* admin/ktutil.8: document -v, --verbose
=20
@@ -1736,7 +1736,7 @@
 	* admin/copy.c (kt_copy): remove adding verbose_flag to args
 	struct, since it will overrun the args array (from Sumit Bose)
 =09
-2003-01-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.conf.5: write more about [realms] REALM =3D { kdc =3D
 	... }
@@ -1770,7 +1770,7 @@
 	* lib/krb5/krb5.h (krb5_keytype): add KEYTYPE_AES128,
 	KEYTYPE_AES256
=20
-2003-01-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/common.c (_hdb_fetch): handle error code from
 	hdb_value2entry
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/ChangeLog.2004
--- a/head/crypto/heimdal/ChangeLog.2004	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/ChangeLog.2004	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,9 @@
-2004-12-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am (CHECK_SYMBOLS): add heim_ and pkcs7_ for
 	now (used in pkinit)
=20
-2004-12-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/Makefile.am: add CHECK_SYMBOLS
=20
@@ -32,7 +32,7 @@
=20
 	* lib/krb5/krb5.h: add key usage for server referrals
 =09
-2004-12-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/principal.c: make default_v4_name_convert static
 =09
@@ -40,7 +40,7 @@
 =09
 	* lib/krb5/acache.c: make default_acc_name static
 =09
-2004-12-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: add some text about samba, use example.com
 =09
@@ -48,24 +48,24 @@
 	F.  Hranicky <jfh at cise.ufl.edu>.
 	Add LDAP_addmod_integer and use it.
=20
-2004-12-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/{Makefile.am,setup.texi,win2k.texi}: spelling and text
 	fixes, from Dave Love
=20
-2004-12-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/heim_threads.h: NetBSD 2.99.11 (any maybe 2.1) just
 	needs pthread.h, threadlib is dead
=20
-2004-12-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/config.c (configure): check for deprecated
 	enforce-transited-policy is set and fail if it is
 =09
 	* lib/asn1/asn1_print.c: don't print garabage for octet strings
 =09
-2004-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/main.c (main): catch sigpipe, we don't bother select()ing
 	for errors
@@ -81,7 +81,7 @@
 =09
 	* lib/hdb/hdb-ldap.c (pos): uppercase in character
=20
-2004-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c (LDAP__bytes2hex,LDAP__hex2bytes): encode
 	nibbels in the other order
@@ -90,7 +90,7 @@
 	attribute exists before we try to delete it LDAP__bytes2hex
 	encodes in strange byte order, is this really right ?
 =09
-2004-12-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c (LDAP_firstkey): When iterating over all
 	entries, search for samba accounts too, From: "James F. Hranicky"
@@ -103,13 +103,13 @@
 	both krb5PrincipalName and uid, it must be broken, ignore it and
 	return it doesn't exists.
=20
-2004-12-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/hpropd.8: spelling, from OpenBSD
 =09
 	* kdc/kdc.8: use keeps for options, From OpenBSD k
 =09
-2004-12-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: document --random-key and the need to do backup
 	of the master key
@@ -118,7 +118,7 @@
 =09
 	* kdc/kstash.c: add --random-key
 =09
-2004-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.8: spelling, from openbsd
 =09
@@ -135,25 +135,25 @@
 =09
 	* kdc/hprop.8: use keeps around options, from OpenBSD
 =09
-2004-11-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c (krb5_free_context): clear error string
 	before destroying mutex
 	(krb5_init_context): don't call krb5_free_context before there is a
 	mutex initialized
=20
-2004-11-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c (get_new_tickets): only complain about ticket
 	renewable lifetime when the user asked for a specific renewable
 	lifetime
=20
-2004-11-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (find_keys): log what principal is missing
 	enctypes
=20
-2004-11-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_in_tkt.c (krb5_get_in_cred): clear pointer after
 	freeing data
@@ -161,21 +161,21 @@
 	* lib/krb5/init_creds_pw.c (change_password): handle old_options
 	being NULL From Guenther Deschner on samba-technical.
 =09
-2004-11-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_get_init_creds.3: add more text describing the
 	krb5_get_init_creds functions
=20
-2004-11-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c: make krb5_get_init_creds_keytab work
 	again
=20
-2004-11-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb.asn1: use constrained integers
 =09
-2004-11-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_get_init_creds.3: add description for opt_init,
 	opt_alloc, opt_free
@@ -191,12 +191,12 @@
 	* lib/krb5/init_creds.c (_krb5_get_init_creds_opt_copy): if the in
 	options NULL, just make a clean copy
=20
-2004-11-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/sendauth.c (krb5_rd_rep): free ap_rep message earlier
 	so we don't leak it on error
=20
-2004-10-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.conf.5: unbreak 2b entry
 =09
@@ -204,18 +204,18 @@
 	sockaddr but rather a kerberos address, deal with that.  Based on
 	bug report from Jakob Schlyter <jakob at rfc.se>.
=20
-2004-10-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/connect.c: Make sure argument passed to ctype isn't signed
 	char
=20
-2004-10-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: match new error names
 =09
 	* lib/krb5/krb5_err.et: make error messages sane again
 =09
-2004-10-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab.c: use KRB5_KT_BADNAME
=20
@@ -238,7 +238,7 @@
 =09
 	* lib/asn1/lex.l: support hex numbers
 =09
-2004-10-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: use ETYPE_DES3_CBC_NONE_CMS
 =09
@@ -250,7 +250,7 @@
 	Requested by Andrew Bartlett <abartlet at samba.org> for hdb-ldb
 	backend.
=20
-2004-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: adapt to new signature of
 	krb5_get_init_creds_opt_set_pkinit
@@ -266,7 +266,7 @@
=20
 	* kuser/klist.c: use rtbl_set_separator
 =09
-2004-10-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: filter out dup openssl engine keys, parse
 	user options first
@@ -280,7 +280,7 @@
 =09
 	* kdc/pkinit.c: stop using AlgorithmIdentifierNonOpt
 =09
-2004-09-30  Love H=F6rnquist =C5strand <lha at it.su.se>
+2004-09-30  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/krb5.conf.5: assume minutes for time
=20
@@ -294,7 +294,7 @@
 	minute for compatibility with MIT Kerberos.
 =09
=20
-2004-09-28  Love H=F6rnquist =C5strand <lha at it.su.se>
+2004-09-28  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/get_cred.c (get_cred_kdc_usage): retry using "large
 	message safe" transport if we get back
@@ -319,7 +319,7 @@
=20
 	* kuser/kinit.c: make sure we don't always get renewable creds
 =09
-2004-09-11   Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-11   Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/acache.c: use krb5_ccapi.h
 =09
@@ -329,12 +329,12 @@
 	* lib/krb5/Makefile.am: add AM_CPPFLAGS to libkrb5_la_CPPFLAGS
 	since AM_CPPFLAGS overridden by target specific _CPPFLAGS
 =09
-2004-09-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: make variable shorter, make error messages
 	from pkinit, make freeing easier
 =09
-2004-09-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: link libkrb5 with LIB_dlopen
 =09
@@ -342,7 +342,7 @@
 	is uninitialized, make valgrind unhappy. Pointd out by
 	abartlet at samba.org. While where, plug the fd leak.
 =09
-2004-09-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/der_get.c (decode_*): name all tag-length variables the
 	same
@@ -351,18 +351,18 @@
 	* lib/asn1/der_get.c (decode_boolean): fail if length of tag is
 	larger then len
=20
-2004-08-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c (krb5_get_init_creds): kdc_reply can be
 	set in case of failure too, free unconditionally on exit to avoid
 	memory leak
=20
-2004-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_cred.c (set_auth_data): set pointer to NULL after
 	free
=20
-2004-08-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c (krb5_get_err_text): if neither of com_right
 	nor strerror finds the error-code, return Unknown error.
@@ -374,7 +374,7 @@
 	* lib/krb5/kuserok.c: if a .k5login file exist, don't give
 	implicit rights to anyone; also check owner/mode of .k5login
=20
-2004-08-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: man_MANS =3D krb5_getportbyname.3
 =09
@@ -386,19 +386,19 @@
=20
 	* lib/krb5/krb5_encrypt.3: document krb5_enctype_valid
 =09
-2004-08-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (get_pa_etype_info{,2}): check for dup enctypes
 	from the client and filter them out.
 =09
 	* lib/krb5/krb5_string_to_key.3: document krb5_free_salt
 =09
-2004-08-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_ticket.3: data needs to be freed when using
 	krb5_ticket_get_authorization_data_type
=20
-2004-08-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_cc.c: test variables in default_cc_name
 =09
@@ -416,7 +416,7 @@
 	* lib/krb5/cache.c (krb5_cc_set_default_name):
 	s/libdefault/libdefaults/
=20
-2004-08-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/acache.c: replace magic 3 with ccapi_version_3
 =09
@@ -434,13 +434,13 @@
 	since its not possible to glue in user information (like uid), but
 	for CCAPI it works just fine
=20
-2004-08-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kgetcred.1: document --cache/-c
 =09
 	* kuser/kgetcred.c: allow to specify what credential cache to use
 =09
-2004-08-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: add krb5_eai_to_heim_errno.3
 =09
@@ -450,7 +450,7 @@
 	* lib/krb5/krb5.3: add krb5_eai_to_heim_errno,
 	krb5_h_errno_to_heim_errno
=20
-2004-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_expand_hostname.3: krb5_expand_hostname_realms
 	result should be free with krb5_free_host_realm drop
@@ -483,39 +483,39 @@
 	* lib/krb5/krb5_get_credentials.3: krb5_get_credentials and
 	friends
=20
-2004-07-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/klist.c (print_cred_verbose): keytypes are no longer, use
 	enctype
=20
-2004-07-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c (LDAP_entry2mods): allow for pre-c99
 	compilers, From metze at samba.org
=20
-2004-07-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_cc.c: more cc tests
 =09
 	* lib/krb5/krb5_check_transited.3: document krb5_check_transited
 =09
-2004-07-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c (pk_principal_from_X509): reverse test, makes
 	principal in cert work From: Mayur Patel <patelm4 at rpi.edu>
 =09
-2004-07-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: add krb5_verify_init_creds.3
=20
 	* lib/krb5/krb5_verify_init_creds.3: add krb5_verify_init_creds
 =09
-2004-07-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_set_password.3: spelling from wiz at netbsd.org
 	description for krb5_passwd_result_to_string
 =09
-2004-07-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_set_password.3: Remove superfluous comma; grammar
 	fixes; split sentence in two for better understanding.  From
@@ -527,21 +527,21 @@
 	* lib/krb5/changepw.c (process_reply): cast ssize_t to long and
 	print that From NetBSD via Havard Eidnes.
 =09
-2004-07-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: fix helpstring for hdb-openldap-module
 =09
 	* lib/krb5/test_cc.c: don't use krb5_err on error code 0
 =09
-2004-07-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c (LDAP_seq): try handling errors better
 =09
-2004-07-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_in_tkt.c (set_ptypes): make ptypes const
 =09
-2004-07-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c (LDAP__connect): call ldap_initialize with
 	right argument
@@ -572,27 +572,27 @@
 	OtherName of subjectAltName Based on patch from Mayur Patel
 	<patelm4 at rpi.edu>
=20
-2004-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_cred.c (init_tgs_req): if subkey not avaible, use
 	session key for authorization-data
=20
-2004-06-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/connect.c (handle_tcp): note who is what that closed the
 	connection on us
=20
-2004-06-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* admin/get.c (kt_get): catch errors from krb5_parse_name
 =09
-2004-06-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: if its the entry just contains the
 	structural object (no samba nor heimdal object), add an aux
 	heimdal object on to it.
 =09
-2004-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswd.c: use krb5_set_password_using_ccache
 =09
@@ -611,7 +611,7 @@
=20
 	* lib/hdb/hdb-ldap.c: indent like the rest of the code
 =09
-2004-06-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: check return values from ldap operations and
 	close it we get back LDAP_SERVER_DOWN. stupid ldap client lib, you
@@ -620,19 +620,19 @@
 	* lib/hdb/hdb-ldap.c: require search base to be configured, create
 	local context structure
 =09
-2004-05-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: more ldap text, partly from Tarjei Huse
 	<tarjei at nu.no>
=20
-2004-05-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/hdb/hdb-ldap.c: clean, indent
 =09
 	* lib/hdb/hdb-ldap.c (LDAP_entry2mods): make sure
 	krb5KeyVersionNumber is added on new entires
=20
-2004-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: minor fixes, partly from Tarjei Huse
 	<tarjei at nu.no>
@@ -642,15 +642,15 @@
 	* lib/krb5/krb5.conf.5: default value for
 	hdb-ldap-structural-object is account
=20
-2004-05-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/Makefile.am: use ! instead of , as sed delimiter
 =09
-2004-05-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/*.c: add KRB5_LIB_FUNCTION to all exported functions
=20
-2004-05-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: make samba_forwardable a krb5_boolean
 =09
@@ -667,11 +667,11 @@
 	case, make sure ent->etypes are allocated, From: Andrew Bartlett
 	<abartlet at samba.org>
=20
-2004-05-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: move "setpag if (argc < 1)" to common path
 =09
-2004-05-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c: pacify pre c99 compilers
 =09
@@ -681,7 +681,7 @@
=20
 	* kuser/kinit.c: print some diagnostics if the exec fails
 =09
-2004-04-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (pk_rd_pa_reply_dh): use krb5_random_to_key
 	From: Luke Howard <lukeh at padl.com>
@@ -689,11 +689,11 @@
 	* lib/krb5/rd_req.c (krb5_verify_ap_req2): clear the whole ticket,
 	not just a pointer size of it From: Luke Howard <lukeh at padl.com>
 =09
-2004-04-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* fix-export: add -E flag where needed to make-proto
 =09
-2004-04-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c: add set_param for RC2
 =09
@@ -772,7 +772,7 @@
 	* lib/krb5/store.c (krb5_store_creds): set is_skey flag if length
 	of second ticket is > 0
=20
-2004-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/pkinit.c: use the right oid for pkauthdata
 =09
@@ -806,7 +806,7 @@
 	* lib/krb5/{krb5.h,store.c,fcache.c}: Fix the cache flags bitorder
 	issue with a storage flag instead of a separate function.
 =09
-2004-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: move out the oid check from get_reply_key
=20
@@ -830,7 +830,7 @@
 	digestAlgorithm to sha1 (both for SignerInfo and SignedData, add
 	new function _set_digest_alg to set it
=20
-2004-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* include/make_crypto.c: include rc2.h, and when I'm here, make
 	aes mandatory
@@ -852,7 +852,7 @@
 	* lib/krb5/string-to-key-test.c: comment out the "@"/"" test for
 	now
=20
-2004-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_string_to_key.3: document that
 	krb5_string_to_key_derived is broken for non 3des enctypes and
@@ -868,7 +868,7 @@
 =09
 	* lib/krb5/krb5_keyblock.3: document krb5_random_to_key
 =09
-2004-04-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: use the first proposed enable enctype
 =09
@@ -877,28 +877,28 @@
=20
 	* kdc/pkinit.c: at least try to handle diffrent enveloped enctypes
 =09
-2004-04-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/der_get.c: 1.28.2.16: (der_get_oid): handle all oid
 	components being smaller then 127 and allocate one extra element
 	since first byte is split to to elements.
 =09
-2004-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/k5.asn1: ETYPE_DIGEST_MD5_NONE, ETYPE_CRAM_MD5_NONE:
 	private use, lukeh at padl.com
=20
-2004-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (build_auth_pack): use heim_integer to encode
 	DH public key
=20
-2004-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_init_context.3: add krb5_context to so its added
 	as manpage-link too
=20
-2004-04-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/fcache.c (fcc_remove_cred): simplistic implementation,
 	XXX add locking
@@ -913,7 +913,7 @@
 =09
 	* kdc/config.c: merge certificate/private_key to a user_id
 =09
-2004-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kdc_locl.h: update prototype for pk_initialize
 =09
@@ -926,11 +926,11 @@
 	* kdc/pkinit.c: adapt to heim_integer changes,
 	merge certificate/private_key to a user_id
 =09
-2004-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: use KRB5_PADATA_PK_AS_REQ_WIN free X509_STORE
 =09
-2004-04-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: define BUILD_KRB5_LIB when building
 	libkrb5.la, add KRB5_LIB_FUNCTION proto
@@ -957,25 +957,25 @@
 =09
 	* lib/krb5/krb5_ccache.3: add krb5_cc_get_prefix_ops
 =09
-2004-04-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/test/http_client.c: support GSS_C_DELEG_FLAG and
 	GSS_C_MUTUAL_FLAG
=20
 	* appl/test/http_client.c: verbose logging
 =09
-2004-04-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/connect.c: case size_t to unsigned long for LP64 platforms
 =09
-2004-04-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c (hdb_ldap_create): allow configuration of
 	default structural object
=20
 	* tools/Makefile.am: handle sed expression breaking
 =09
-2004-03-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krbhst.c: also lookup _kpasswd._tcp SRV-rr
 =09
@@ -987,7 +987,7 @@
 	* lib/krb5/krb5_acl_match_file.3: try to pacify mdoc macros on
 	osf/1
=20
-2004-03-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c (pa_data_add_pac_request): don't
 	increase md->len, krb5_padata_add already does that
@@ -999,11 +999,11 @@
 	* kdc/kerberos4.c: stop the client from renewing tickets into the
 	future From: Jeffrey Hutzelman <jhutz at cmu.edu>
=20
-2004-03-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: try to handle sys/strtty.h needing sys/stream.h
 =09
-2004-03-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/send_to_kdc.c: remove function krb5_sendto_kdc2, its no
 	longer used
@@ -1018,11 +1018,11 @@
 	* lib/krb5/mk_req_ext.c: unexport krb5_mk_req_internal to external
 	users by prefixing it with _
=20
-2004-03-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: add missing }
 =09
-2004-03-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: adapt to change of signature of
 	_krb5_pk_load_openssl_id
@@ -1076,7 +1076,7 @@
 	* lib/krb5/krb5_ticket.3: document
 	krb5_ticket_get_authorization_data_type
=20
-2004-03-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/aes-test.c: remove #if 0'ed code
 =09
@@ -1157,7 +1157,7 @@
 	make it not fall over when no non matching acl,
 	make fnmatch matching useful by switching arguments
 =09
-2004-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/config.c: add --builtin-hdb command
 =09
@@ -1176,7 +1176,7 @@
 	* lib/krb5/krb5.conf.5: add a bunch of Li and document [kadmin]
 	password_lifetime; from Henry B. Hotz
=20
-2004-03-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/mk_rep.c (krb5_mk_rep): if KRB5_AUTH_CONTEXT_USE_SUBKEY
 	is set send subkey
@@ -1184,13 +1184,13 @@
=20
 	* lib/krb5/krb5.h: add KRB5_AUTH_CONTEXT_USE_SUBKEY
 =09
-2004-03-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: clean up error handling, plug memory leaks,
 	and free memory in error path, assume realloc(NULL, ...) works,
 	factor out common code, indent
=20
-2004-03-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c: understand [password_quality]
 	spelling
@@ -1199,12 +1199,12 @@
 =09
 	* kuser/kgetcred.c: add --canonicalize
 =09
-2004-03-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/fcache.c (fcc_store_cred): NULL terminate
 	krb5_config_get_bool_default' arglist
 =09
-2004-03-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c: add missing req argument to pk_mk_pa_reply
 =09
@@ -1234,7 +1234,7 @@
 	* lib/krb5/store.c (krb5_ret_creds): Runtime detect the what is
 	the higher bits of the bitfield
 =09
-2004-03-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/store.c (krb5_store_creds): add disabled code that
 	store the ticket flags in reverse order
@@ -1244,7 +1244,7 @@
 	are set, its a mit cache, reverse the bits, bug pointed out by
 	Sergio Gelato <Sergio.Gelato at astro.su.se>
=20
-2004-03-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: use macro for HDB * -> LDAP *
 =09
@@ -1280,7 +1280,7 @@
 =09
 	* lib/asn1/k5.asn1: drop SMTP_NAME
 =09
-2004-03-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/Makefile.am: support building ldap backend as module
 	sort asn1 hdb files
@@ -1300,7 +1300,7 @@
 	the original data test case from Ronnie Sahlberg
 	<ronnie_sahlberg at ozemail.com.au>
=20
-2004-03-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_cc.c: more cc tests, mostly related to mcc
 	behavior
@@ -1312,7 +1312,7 @@
 	as dead since that doesn't always work. Based on patch from
 	Jeffrey Hutzelman <jhutz at cmu.edu>, tweeked by me
 =09
-2004-02-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: adapt to rename of oid_cmp to heim_oid_cmp
 =09
@@ -1323,7 +1323,7 @@
 	* doc/setup.texi: add text about hostname to realm mapping using
 	DNS
=20
-2004-02-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: update error codes
 =09
@@ -1331,7 +1331,7 @@
=20
 	* lib/krb5/pkinit.c: update error codes
 =09
-2004-02-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: indent, use krb5_abortx() instead of abort()
 =09
@@ -1342,7 +1342,7 @@
 	* lib/krb5/fcache.c (_krb5_xlock): handle that everything was ok,
 	and don't put an error in the error strings then
 =09
-2004-02-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: s/heim_big_integer/heim_integer/
 =09
@@ -1355,18 +1355,18 @@
 =09
 	* lib/krb5/heim_err.et: add HEIM_PKINIT specific errors
 =09
-2004-02-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: rename AC_WFLAGS to rk_WFLAGS
 =09
 	* acinclude.m4: use m4_define, over-quote string
 =09
-2004-02-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c (change_password): handle that
 	printf("%.*s", 0, (void*)NULL); doesn't work on solaris
 =09
-2004-02-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswd.c (change_password): handle that printf("%.*s",
 	0, (void*)NULL); doesn't work on solaris
@@ -1375,7 +1375,7 @@
 	some locate.updatedb, use FILES section to describe where the file
 	is instead.
=20
-2004-02-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/check-der.c: test for "der_length.c: Fix len_unsigned
 	for certain negative integers, it got the length wrong" , from
@@ -1393,7 +1393,7 @@
 	* configure.in: Check for sys/socket.h, net/if.h.  Modify term.h,
 	security/pam_appl.h tests.
 =09
-2004-02-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/check-gen.c: test for: (length_type): TSequenceOf: add
 	up the size of all the elements, don't use just the size of the
@@ -1431,11 +1431,11 @@
 	* lib/krb5/build_ap_req.c (krb5_build_ap_req): abort on internal
 	asn1 encode error
=20
-2004-01-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: some text about order of [capaths] realms
 =09
-2004-01-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c: register WRFILE ops
 =09
@@ -1446,30 +1446,30 @@
 	* kpasswd/kpasswdd.c (change): use the right password when
 	changing the password
=20
-2004-01-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/fcache.c (_krb5_xlock): catch EINVAL and assume that it
 	means that the filesystem doesn't support locking
 =09
 	* lib/krb5/keytab.c: remove #if 0 out file locking code
 =09
-2004-01-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/gen_length.c (length_type): TSequenceOf: add up the
 	size of all the elements, don't use just the size of the last
 	element.
=20
-2004-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c (renew_validate): if renewable_flag and not time
 	specifed, use "1 month"
=20
-2004-01-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_keyblock.3: add prototypes, describe
 	krb5_keyblock_zero
=20
-2004-01-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_for_creds.c (add_addrs): don't add same address
 	multiple times
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/ChangeLog.2005
--- a/head/crypto/heimdal/ChangeLog.2005	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/ChangeLog.2005	Tue Apr 17 11:51:51 2012 +0300
@@ -1,16 +1,16 @@
-2005-12-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (tgs_make_reply): less const on hdb_entry_ex to
 	make samba happy
=20
 	* fix-export: Build kdc-private.h.
 =09
-2005-12-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (tgs_rep2): also print the principal for which
 	the enctype was missing
 =09
-2005-12-13  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-12-13  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* kdc/kaserver.c: Finish up transition from hdb_entry to
 	hdb_entry_ex.
@@ -35,7 +35,7 @@
 =09
 	* lib/hdb/db.c: memset hdb_entry_ex before use
 =09
-2005-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.3: Add some more entrypoints.
=20
@@ -66,11 +66,11 @@
=20
 	* Makefile.am: Split long line
=20
-	* doc/apps.texi: Spelling, From M=E5ns Nilsson.
-
-	* doc/install.texi: spelling, From M=E5ns Nilsson
+	* doc/apps.texi: Spelling, From M=C3=A5ns Nilsson.
+
+	* doc/install.texi: spelling, From M=C3=A5ns Nilsson
 =09
-2005-12-11  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-12-11  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/krb5_principal.3: Constify principal argument to on
 	krb5_principal_get_ functions.
@@ -78,12 +78,12 @@
 	* lib/krb5/principal.c: Constify principal argument to on
 	krb5_principal_get_ functions.
 =09
-2005-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb: drop convert_db, 0.0 to 0.1 transition was a long long
 	time ago
=20
-2005-12-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_keytab.c: more tests, From Andrew Bartlet
=20
@@ -91,7 +91,7 @@
 	NULL on success in the case 0 entries are allocated, From Andrew
 	Bartlet
 =09
-2005-12-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/acl.c (acl_parse_format): tmp needs to be freed too on
 	failure to parse format specifier.
@@ -105,9 +105,9 @@
=20
 	* lib/krb5/derived-key-test.c: Free more of the allocated memory.
 =09
-2005-12-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* doc/setup.texi: spelling, From M=E5ns Nilsson
+2005-12-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* doc/setup.texi: spelling, From M=C3=A5ns Nilsson
=20
 	* lib/krb5/krb5_keytab.3: Memory keytab are now named and
 	refcounted.
@@ -117,7 +117,7 @@
 	* lib/krb5/keytab_memory.c: Index by name and start reference
 	counting on entries.
 =09
-2005-11-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h (krb5_address_type): add
 	KRB5_ADDRESS_NETBIOS (20)
@@ -131,7 +131,7 @@
=20
 	* kcm/connect.c (kcm_loop): Use HAVE_DOOR_CREATE, not HAVE_DOORS.
 =09
-2005-11-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c (libdefaults_entries): add
 	default_cc_name
@@ -162,7 +162,7 @@
=20
 	* lib/hdb/db.c (hdb_db_create): use calloc to allocate memory
=20
-2005-11-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_for_creds.c (krb5_get_forwarded_creds): use session
 	key for delegated credentials
@@ -170,41 +170,41 @@
 	* kdc/kerberos5.c (_kdc_as_rep): add comment when we send
 	ETYPE-INFO and ETYPE-INFO2, from Andrew Bartlett
 =09
-2005-11-25  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-11-25  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/keytab.c (krb5_kt_get_full_name): new function
 =09
-2005-11-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_crypto.c: Split encryption and s2k iterations to
 	diffrent counters, 38seconds of aes256 s2k is way too long.
=20
 	* lib/krb5/test_crypto.c: Add timing code for s2k function.
=20
-2005-11-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/kerberos5.c: Print the time the principal expired, based on
 	patch from Andrew Bartlett.
 =09
-2005-11-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/cache.c (krb5_cc_get_full_name): Add
 =09
-2005-11-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: Spelling, From Michael Banck <mbanck at debian.org>
 =09
-2005-10-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kcm/headers.h: Maybe include <sys/param.h>.
=20
-2005-10-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/ticket.c (krb5_ticket_get_authorization_data_type):
 	understand KRB5_AUTHDATA_IF_RELEVANT and KRB5_AUTHDATA_AND_OR (but
 	have KRB5_AUTHDATA_KDC_ISSUED commented out for now)
 =09
-2005-10-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/klist.c: In the list caches view, rename the Status field
 	to Expires.
@@ -212,13 +212,13 @@
 	* lib/krb5/krb5_encrypt.3: Fix mdoc for
 	krb5_encrypt_EncryptedData, Johnny Lam <jlam at pkgsrc.org>
 =09
-2005-10-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/test/gssapi_client.c: Check return value from asprintf
 	instead of string !=3D NULL since it undefined behavior on
-	Linux. From Bj=F6rn Sandell
+	Linux. From Bj=C3=B6rn Sandell
 =09
-2005-10-21  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-10-21  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (_krb5_dh_group_ok): if not enough bits are
 	generated from the DH groups, fail.
@@ -231,12 +231,12 @@
=20
 	* kdc/kdc.h: Add pkinit_dh_min_bits to krb5_kdc_configuration.
 =09
-2005-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Add option to require binding between reply
 	and response for the win2k version of the protocol.
 =09
-2005-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/programming.texi: Text about Kerberos errors.
 =09
@@ -258,17 +258,17 @@
 	* lib/krb5/krb5_ccache.3: Add krb5_cc_start_seq_get and an
 	example.
=20
-2005-10-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/programming.texi: Try to explain krb5_ccache, krb5_principal
 	and errors.
 =09
-2005-10-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_get_credentials.3: Add example how to use
 	krb5_get_credentials.
 =09
-2005-10-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds.c: Rename private to opt_private.
=20
@@ -280,7 +280,7 @@
 	* lib/krb5/krb5.h (krb5_get_init_creds_opt): rename element
 	private to opt_private to make c++ picky compilers less upset.
 =09
-2005-10-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krbhst.c (_krb5_krbhost_info_move): new function
 	(_krb5_free_krbhst_info): expose to internal use
@@ -292,7 +292,7 @@
 	rename COMPAT_27 to COMPAT_IETF, pass down a krb5_krbhst_info for
 	verification of KDC info, and general cleaning up.
 =09
-2005-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: Install krb5.moduli in sysconfdir.
=20
@@ -324,14 +324,14 @@
 	* lib/krb5/pkinit.c: Add support for reading a moduli-file for DH
 	parameters.
 =09
-2005-10-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/klist.1: Document --list-caches
=20
 	* kuser/klist.c: Change short flag of --list-caches to -l (-v is
 	already used).
=20
-2005-10-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/kerberos.8: RFC 1510 was obsoleted by 4120.
 =09
@@ -340,11 +340,11 @@
 	(acc_get_cache_first): don't leak memory or abort on malloc
 	failure
 =09
-2005-10-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/kerberos.8: Update text about Kerberos RFC's.
 =09
-2005-10-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/klist.c: Add option --list-caches that lists the avaible
 	caches and their status.
@@ -356,7 +356,7 @@
 	lha/root at SU.SE   0                        Expired
 	lha at N.L.NXS.SE   Initial default ccache   Expired
 =09
-2005-09-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/keytab_keyfile.c: Use all DES keys, not just
 	des-cbc-md5, verify that they all are the same.
@@ -372,7 +372,7 @@
=20
 	* lib/krb5/krb5.h (krb5_cc_ops): add cache iteration functions
 =09
-2005-09-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_mk_req.3: Remove leftovers, remove extra space.
=20
@@ -385,18 +385,18 @@
 	store it though), don't check the oid of the DH signedData for
 	now.
 =09
-2005-09-22 Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-09-22 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/rd_cred.c (krb5_rd_cred): try both the session key and
 	the sender subkey. Both RFC1510 and RFC4120 say that you have to
 	use the session key, Heimdal uses subkey.
 =09
-2005-09-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Don't check oid's too closely, they change in
 	Windows Vista.
 =09
-2005-09-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Disable sending -19, fix parsing -27 of the
 	protocol.
@@ -406,7 +406,7 @@
 	* lib/krb5/pkinit.c (pk_verify_chain_standard): set cert to NULL
 	to make sure its not freed.
 =09
-2005-09-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c (krb5_DES_string_to_key): If the opaque length
 	it set to 1, and content is 0x01, use the afs3 string-to-key.
@@ -417,17 +417,17 @@
=20
 	* lib/krb5/kcm.c: Remove signedness warnings.
 =09
-2005-09-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: Use libtool's default values for building
 	shared/static libaries, ie remove AC_ENABLE_SHARED(no), solves
 	building problems users have on Mac OS X.
 =09
-2005-09-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/changepw.c: Constify password.
 =09
-2005-09-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_mk_req.3: Document krb5_rd_req.
 =09
@@ -438,16 +438,16 @@
 	krb5_mk_rep, krb5_mk_rep_exact, krb5_mk_rep_extended, krb5_rd_rep,
 	krb5_build_ap_req, krb5_verify_ap_req.
 =09
-2005-09-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (make_etype_info_entry): Dont send salttype at
 	all, use KRB5-PADATA-AFS3-SALT
 =09
-2005-08-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (log_timestamp): endtime, not endtype
 =09
-2005-08-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: Check for <sys/ucred.h>.
=20
@@ -456,7 +456,7 @@
 =09
 	* kcm/headers.h: include <sys/ucred.h>
 =09
-2005-08-27 Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-08-27 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/rd_req.c (check_transited): Allow empty content of type
 	0 because that is was Microsoft generates in their TGT.
@@ -464,15 +464,15 @@
 	* kdc/kerberos5.c (fix_transited_encoding): Allow empty content of
 	type 0 because that is was Microsoft enerates in their TGT.
=20
-2005-08-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/intro.texi: RFC 4120 replaces RFC 1510
 =09
-2005-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: Add --disable-afs-support.
=20
-2005-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: Add test_hostname to check_PROGRAMS but
 	not TESTS, I have no same dns to use.
@@ -492,29 +492,29 @@
 	krb5_config_free_strings
 	(nothing). Mdoc nit.
 =09
-2005-08-22 Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-22 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/klist.c (check_for_tgt): Re-order code so it only free the
 	credential if one was returned.
 =09
 	* lib/krb5/test_crypto_wrapping.c: Fix printing of size_t.
=20
-2005-08-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/dbinfo.c: provide interface to find databases
=20
 	* lib/hdb/mkey.c: hdb_seal_key_mkey): dont double encrypt keys
=20
-2005-08-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kdc_locl.h: Update prototype for _kdc_pk_mk_pa_reply.
=20
-2005-08-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c: Save the request buffer so that
 	pre-auth mechanism that needs it can verify the reply.
=20
-2005-08-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/test_mem.c: Rename logf to avoid shadowing.
 =09
@@ -548,7 +548,7 @@
 	* kdc/kerberos5.c (_kdc_as_rep): Pass down the request buffer to
 	_kdc_pk_mk_pa_reply.
=20
-2005-08-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/ext.c: HDB extensions access glue.
=20
@@ -570,7 +570,7 @@
 =09
 	* lib/hdb/hdb.asn1: Add support for HDB-extension.
=20
-2005-08-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_pkinit_dh2key.c: add tests vectors from
 	"Liqiang(Larry) Zhu" <lzhu at windows.microsoft.com>
@@ -579,7 +579,7 @@
=20
 	* lib/krb5/test_pkinit_dh2key.c: even more bits, not done yet
 =09
-2005-08-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (_kdc_as_rep): preserve the error code in the
 	ENC-TS case.  From: Andrew Bartlett <abartlet at samba.org>
@@ -603,11 +603,11 @@
 	instead of letting them slip though to d->cursor. Bug repport from
 	Andrew Bartlett <abartlet at samba.org>
=20
-2005-07-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/Makefile.am (kdc_LDADD): add LDADD
 =09
-2005-07-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (_kdc_as_rep): log what enctypes was using in
 	ENC-TS preauth, both for failure and success.
@@ -621,15 +621,15 @@
 	keyusage 0 in case the key was encrypted with MIT Kerberos (old
 	patch from Johan)
=20
-2005-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: update to pkinit-27
=20
-2005-07-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Adapt to IMPLICIT changes in CMS module.
=20
-2005-07-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_pkinit_dh2key.c: framework for testing
 	_krb5_pk_octetstring2key
@@ -643,18 +643,18 @@
 	* lib/krb5/crypto.c (_krb5_pk_octetstring2key): make sha1 output
 	unsigned char to match openssl
=20
-2005-07-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/common.c: Check encoder lengths from ASN1_MALLOC_ENCODE.
=20
-2005-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/rd_cred.c (krb5_rd_cred): don't leak memory
=20
 	* lib/krb5/get_cred.c (krb5_get_credentials_with_flags): only call
 	krb5_cc_retrieve_cred once, and plug memory leak.
=20
-2005-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/Makefile.am: the new asn.1 compiler includes the modules
 	name in the depend file
@@ -667,7 +667,7 @@
=20
 	* lib/krb5/crypto.c (_krb5_pk_octetstring2key): fix arguments
=20
-2005-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: clean up pk-init DH support, not finished
 	yet; improve error reporting
@@ -684,11 +684,11 @@
 	support for tags. This compiler support most of what is needed for
 	PK-INIT, LDAP, X.509, PKCS-12 and many other protocols.
=20
-2005-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1: make scope variables unique to avoid shadow warnings
=20
-2005-07-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.h: comment out paramenter name in typedef
 	functions to avoid shadow warnings
@@ -711,7 +711,7 @@
=20
 	* lib/krb5/test_crypto.c (time_encryption): free cleartext buffer
=20
-2005-07-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: run AM_INIT_AUTOMAKE before AM_PROG_CC_C_O
 	otherwise am_aux_dir will be expanded using ac_aux_dir before the
@@ -724,7 +724,7 @@
=20
 	* configure.in: add AM_PROG_CC_C_O for automake 1.9
=20
-2005-07-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab.c (krb5_kt_get_entry): clear error string when
 	returning a new error
@@ -735,7 +735,7 @@
 	* lib/krb5/verify_init.c (krb5_verify_init_creds): `entry' unused,
 	remove From: "Henry B. Hotz" <hotz at jpl.nasa.gov>
=20
-2005-07-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/win2k.texi: arcfour-hmac-md5 support for windows cross was
 	added in w2k3-sp1 From David Love
@@ -747,7 +747,7 @@
 =09
 	* fix-export: build kdc-protos.h
=20
-2005-07-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc: prefix pkinit symbols with _kdc
=20
@@ -757,7 +757,7 @@
=20
 	* kdc: adapt pkinit code to libkdc split
=20
-2005-06-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/Makefile.am: add depency on LIB_dlopen and LIB_door_create
 =09
@@ -781,7 +781,7 @@
 	* configure.in: add --disable-afs-string-to-key to allow removal
 	of support for afs string2key (and dependency on crypt)
=20
-2005-06-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c: Add logging of all timestamps in AS-REQ and
 	TGS-REQ, for auditing
@@ -798,11 +798,11 @@
 	* kcm/connect.c: don't send socket address in msghdr, it
 	  returns an already connected error on Linux
=20
-2005-06-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/524.c: Always include <krb5-v4compat.h>.
=20
-2005-06-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/intro.texi: no more libdes, gssapi lib is complete
 =09
@@ -821,11 +821,11 @@
=20
 	* lib/hdb/db.c (DB_open): in case of error, close database
=20
-2005-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kcm/kcm.8: fix example
=20
-2005-06-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/rd_rep.c: indent
=20
@@ -884,7 +884,7 @@
=20
 	* lib/krb5/crypto.c: rename `encrypt' to avoid shadow warning
 =09
-2005-06-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/principal.c: rename index to idx
 =09
@@ -944,11 +944,11 @@
 	* kdc/kerberos5.c (tgs_rep2): rename loop to nloop to avoid shadow
 	warning
=20
-2005-06-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Release 0.7, see branch
 =09
-2005-06-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: TESTS +=3D test_mem libkrb5_la_SOURCES +=3D
 	kcm.h
@@ -966,7 +966,7 @@
 	* lib/krb5/verify_krb5_conf.c: Add more missig entires, from
 	Mathias Feiler <feiler at uni-hohenheim.de>
=20
-2005-06-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c (pk_principal_from_X509): remember to free
 	KRB5PrincipalName
@@ -974,7 +974,7 @@
 	* lib/krb5/log.c (krb5_closelog): free all content in
 	krb5_log_facility
=20
-2005-06-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/524.c: init kvno to please gcc
=20
@@ -993,7 +993,7 @@
=20
 	* kcm/kcm_locl.h (disallow_getting_krbtgt): Declare.
=20
-2005-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/mit_dump.c (mit_prop_dump): cast argument to
 	krb5_parse_principal to avoid warning
@@ -1002,7 +1002,7 @@
 	mit_KRB5_TL_MOD_PRINC to hint its a constant originating from mit
 	codebase
=20
-2005-06-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/store.c: If we are allocating 0 entires, avoid failing
 	if ALLOC returns NULL
@@ -1012,7 +1012,7 @@
 	* lib/krb5/cache.c: When returning a new error code, set error
 	string.
=20
-2005-05-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab_file.c: Adapt to changed signature of
 	_krb5_xunlock, clear more error string where needed.
@@ -1020,7 +1020,7 @@
 	* lib/krb5/fcache.c (_krb5_xunlock): catch the error and turn it
 	into something sensable
=20
-2005-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/kerberos5.c (tgs_make_reply): copy ok-as-delegate flag from
 	server entry to encrypted ticket flags
@@ -1036,7 +1036,7 @@
 	* kdc/main.c (sigterm): set exit_flag to signal causing exit;
 	(main): trap SIGXCPU
=20
-2005-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kcm/kcm.8: document --disallow-getting-krbtgt and --door-path
=20
@@ -1056,11 +1056,11 @@
 	* kcm/events.c: if credentials have expired when attempting
 	to renew, attempt to reacquire them using initial creds
=20
-2005-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_principal.3: Spelling, from Bj=F6rn Sandell
+2005-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/krb5_principal.3: Spelling, from Bj=C3=B6rn Sandell
 =09
-	* doc/setup.texi: spelling, from Bj=F6rn Sandell
+	* doc/setup.texi: spelling, from Bj=C3=B6rn Sandell
=20
 	* lib/krb5/name-45-test.c: XXX don't run the test unless the
 	machine is in kth.se or su.se because it depends on local resolver
@@ -1124,15 +1124,15 @@
 =09
 	* kcm/connect.c: add LOCAL_PEERCRED and experimental doors support
=20
-2005-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/kf/kfd.c: case uid_t to unsigned long in printf format
=20
-2005-05-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_auth_context.3: remove trailing space
=20
-2005-05-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kcm/connect.c (do_request): use sendmsg to send the reply
 =09
@@ -1159,7 +1159,7 @@
=20
 	* kcm/kcm.8: KRB5CCNAME needs an literal uid, not ${uid}, spelling
=20
-2005-05-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kcm/protocol.c: Merge the description and function jumptables
 	into one structure.  Use the length of the array when checking if
@@ -1180,11 +1180,11 @@
=20
 	* kdc/main.c: Don't test HAVE_DAEMON since roken supplies it.
=20
-2005-05-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_keytab.3: document WRFILE and JAVA14
=20
-2005-05-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krbhst.c (srv_get_hosts): if srv_get_hosts failes,
 	return and ignore the error
@@ -1194,7 +1194,7 @@
 =09
 	* lib/krb5/test_keytab.c: tests all keytab format
 =09
-2005-05-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (_krb5_pk_rd_pa_reply): non non asn1 decoding
 	errors, fail. Make sure we free memory on error.
@@ -1229,7 +1229,7 @@
 	krb5_kt_free_entry after each fkt_next_entry_int. From: Wynn
 	Wilkes <wwilkes at vintela.com>
=20
-2005-05-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: TESTS +=3D test_keytab
=20
@@ -1257,7 +1257,7 @@
 =09
 	* lib/krb5/krb5.3: add krb5_cc_new_unique
=20
-2005-05-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/fcache.c (fcc_get_first): check return value from
 	malloc, memset the structure, make sure cursor doesn't point to
@@ -1285,13 +1285,13 @@
 	be unencrypted, for compatibility with mit kerberos and java
 	kerberos. krb5_javakt_ops: export
=20
-2005-05-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab_file.c: Add new keytab file format JAVA14 that
 	doesn't the use extended kvnos, as hinted, this is needed for
 	Java's Kerberos implementation.
=20
-2005-05-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: handle pkinit-9, pkinit-19, and pkinit-25
 	enckey, still no DH
@@ -1309,32 +1309,32 @@
=20
 	* lib/krb5/{krb5_compare_creds.3,krb5_get_init_creds.3,
 	krb5_krbhst_init.3,krb5_storage.3}:
-	make more pretty, from Bj=F6rn Sandell
+	make more pretty, from Bj=C3=B6rn Sandell
=20
 2005-05-09  Dave Love  <fx at gnu.org>
=20
 	* doc/setup.texi: Fix and clarify password quality check examples.
 =09
-2005-05-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/kuserok.c (krb5_kuserok): use POSIX_GETPWNAM_R instead
 	of HAVE_GETPWNAM_R From: Dave Love <d.love at dl.ac.uk>
=20
-2005-05-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/addr_families.c (krb5_print_address): catch when the
-	unknown adress don't fit. From Bj=F6rn Sandell <biorn at dce.chalmers.se>
+	unknown adress don't fit. From Bj=C3=B6rn Sandell <biorn at dce.chalmers.se>
=20
 2005-05-05  Dave Love  <d.love at dl.ac.uk>
=20
 	* configure.in: fix type right test, include <termios.h> for
 	sys/strtty.h, not sys/ptyvar.h
 =09
-2005-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.conf.5: spelling
=20
-2005-05-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5.conf.5: expand on what "trailing component" means
 =09
@@ -1349,7 +1349,7 @@
 	* lib/krb5/kuserok.c: check the user's ~/.k5login.d directory for
 	access files, all of which is handled like the regular ~/.k5login
 =09
-2005-05-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/ack.texi: Clearify what version of libdes we are using and
 	who's code in it we are using.
@@ -1367,7 +1367,7 @@
=20
 	* configure.in: sys/tty.h (for sys/ptyvar.h) might need termios.h.
=20
-2005-05-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/krb5-config.in: add com_err to required libs
 =09
@@ -1384,7 +1384,7 @@
 	* lib/krb5/crypto.c: Don't declare des_salt &c as static with
 	incomplete type (invalid in c89, at least).
 =09
-2005-05-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_locl.h: include <crypt.h>
=20
@@ -1394,7 +1394,7 @@
 	namespace collision.
 	(handle_stream): Cast arg of krb5_warnx.
=20
-2005-04-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c: if we are using PKINIT, strip of the
 	highest bit to make windows PK-INIT happy. Also make the nonces
@@ -1418,11 +1418,11 @@
 =09
 	* lib/krb5/Makefile.am: use LIB_com_err for libkrb5.la
=20
-2005-04-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/Makefile.am: use $(LIB_com_err)
 =09
-2005-04-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c (krb5_set_config_files): ignore permission
 	denied on configuration files, user might not be allowed to read
@@ -1433,19 +1433,19 @@
 	* lib/krb5/krb5_locl.h: define _POSIX_PTHREAD_SEMANTICS so we get
 	posix getpwnam_r
=20
-2005-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/gen_glue.c: switch the units variable to a
 	function. gcc-4.1 needs the size of the structure if its defined
 	as extern struct units foo_units[] an we don't want to include
 	<parse_units.h> in the generate headerfile
=20
-2005-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb.schema: add EQUALITY rule for krb5ValidStart,
 	krb5ValidEnd, krb5PasswordEnd From Howard Chu
=20
-2005-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/whatis.texi: comment out docbook stuff for now
 =09
@@ -1488,22 +1488,22 @@
 	* doc/heimdal.texi: change the wrapping around the Top node to
 	ifnottex, make html generation work
=20
-	* lib/krb5/krb5_krbhst_init.3: spelling, from Bj=F6rn Sandell
+	* lib/krb5/krb5_krbhst_init.3: spelling, from Bj=C3=B6rn Sandell
 	<biorn at dce.chalmers.se>
=20
-	* lib/krb5/krb5_get_krbhst.3: spelling, from Bj=F6rn Sandell
+	* lib/krb5/krb5_get_krbhst.3: spelling, from Bj=C3=B6rn Sandell
 	<biorn at dce.chalmers.se>
=20
-	* lib/krb5/krb5_data.3: spelling, from Bj=F6rn Sandell
+	* lib/krb5/krb5_data.3: spelling, from Bj=C3=B6rn Sandell
 	<biorn at dce.chalmers.se>
=20
-	* lib/krb5/krb5_aname_to_localname.3: spelling, from Bj=F6rn Sandell
+	* lib/krb5/krb5_aname_to_localname.3: spelling, from Bj=C3=B6rn Sandell
 	<biorn at dce.chalmers.se>
=20
-	* lib/krb5/krb5_address.3: spelling, from Bj=F6rn Sandell
+	* lib/krb5/krb5_address.3: spelling, from Bj=C3=B6rn Sandell
 	<biorn at dce.chalmers.se>
=20
-2005-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/config.c: Use the new Kerberos 4 functions in libkrb5 and so
 	kerberos 4 is always compiled in (still default disabled)
@@ -1521,19 +1521,19 @@
 =09
 	* lib/krb5/krb5-v4compat.h: add more v4 defines
 =09
-2005-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswdd.c: Support multi-realms databases, requires
 	that all the realms are configured on the KDC in krb5.conf with
 	[libdefaults]default_realm stanzas.
=20
-2005-04-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c: spell succeeded correctly, From Sean Chittenden
=20
 	* lib/krb5/addr_families.c: catch two more snprintf problems
 =09
-2005-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/Makefile.am: this lib include com_err, add -com_err to
 	CHECK_SYMBOLS
@@ -1541,7 +1541,7 @@
 	* appl/test/http_client.c: cast ssize_t to unsigned long, fix
 	printf format
=20
-2005-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/kuserok.c: use asprintf to avoid truncating pathnames
 =09
@@ -1563,7 +1563,7 @@
=20
 	* lib/krb5/test_kuserok.c: test program for krb5_kuserok
=20
-2005-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/acache.c (acc_resolve): if open_default_ccache failed
 	with ccErrCCacheNotFound try again with create_default_ccache,
@@ -1580,7 +1580,7 @@
 	* include/make_crypto.c: cast to unsigned char to make sure its
 	not negative when passing it to is* functions
=20
-2005-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/programming.texi: remove manpage macro, add some more
 	references to manpages
@@ -1594,7 +1594,7 @@
=20
 	* lib/krb5/krb5_keyblock.3: document krb5_keyblock_init
 =09
-2005-04-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kaserver.c: AUTHENTICATE and AUTHENTICATE_V2 is almost the
 	same, and clients
@@ -1604,25 +1604,25 @@
 	* lib/krb5/keyblock.c: Add krb5_keyblock_init to allocate an fill
 	in a keyblock from key data.
 =09
-2005-04-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: rk_WIN32_EXPORT for roken
=20
-2005-04-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* appl/test/gssapi_server.c: print out client principla of
 	delegated credential
=20
-2005-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c (process_pa_data_to_key): also check
 	for KRB5_PADATA_PK_AS_REP_19, From: Douglas Engert
=20
-2005-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* .cvsignore: ignore more generate files
 =09
-2005-04-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/asn1/check-der.c: use size_t, print size_t by casting to
 	unsigned long
@@ -1645,7 +1645,7 @@
 	between PA-PK-AS-REP-19 and PA-PK-AS-REQ-Win2k, try harder to
 	verify both cases
=20
-2005-04-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/test/uu_client.c: print size_t by casting to unsigned long
 =09
@@ -1670,7 +1670,7 @@
 	* lib/asn1/gen.c: avoid const string warnings steming from
 	writeable-string
=20
-2005-03-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: TESTS +=3D test_addr
=20
@@ -1683,13 +1683,13 @@
 	* lib/krb5/krb5_keytab.3: stop memory leak in example, expand on
 	wildcards
=20
-2005-03-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_principal.3: spelling, from Tomas Olsson
=20
 	* lib/krb5/krb5_warn.3: spelling, from Tomas Olsson
=20
-2005-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/acache.c: add mutex for global variables, clean up
 	returned error codes, implement storing addresses into the ccapi
@@ -1708,7 +1708,7 @@
 	* appl/test/http_client.c: Make constent with rest of the gssapi
 	test programs
=20
-2005-03-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/keys.c: AES is enabled by default, remove ifdefs
 =09
@@ -1719,11 +1719,11 @@
=20
 	* kdc/kerberos5.c: AES is enabled by default, remove ifdefs
=20
-2005-03-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: Add some text about modifying the database
 =09
-2005-03-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: widen lifetime/renewal warning text field, also
 	make use of unparse_time_approx, no need to be specific to the
@@ -1737,12 +1737,12 @@
 	* lib/krb5/crypto.c: fix signedness issues, prompted by report of
 	Magnus Ahltorp
=20
-2005-03-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_keytab.3: more text about how to free returned
 	resources
=20
-2005-03-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: handle the -25 generation path
=20
@@ -1750,28 +1750,28 @@
 =09
 	* lib/krb5/pkinit.c: fold in pk-init-25 asn1 changes
 =09
-2005-03-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: use generated oid's
 =09
 	* lib/krb5/pkinit.c: use generated oid's
 =09
-2005-03-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: update to the asn1 structures used in -25's
=20
 	* lib/krb5/pkinit.c: update to the asn1 structures used in -25's
=20
-2005-03-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/hdb/hdb-ldap.c: use the newly written hex function from
 	roken and remove the old implementation
=20
-2005-03-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/test/http_client.c: allow specifing port to connect to
=20
-2005-02-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/Makefile.am: bump version to 21:0:4
=20
@@ -1779,7 +1779,7 @@
 =09
 	* lib/asn1/Makefile.am: bump version to 7:0:1
=20
-2005-02-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c (DES_string_to_key_int): must check for weak
 	keys after doing the DES_cbc_cksum
@@ -1790,17 +1790,17 @@
 	  config_get_hosts() in kpasswd_get_next()
 	  From: Wynn Wilkes <wynnw at vintela.com>
=20
-2005-02-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/db3.c (DB_open): correct the check for O_RDONLY
 	From: Chaskiel M Grundman <cg2v at andrew.cmu.edu>
=20
-2005-02-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c (krb5_random_to_key): cast size_t to int to
 	make %d work
=20
-2005-02-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab.c (krb5_kt_get_entry): tell what enctype the
 	caller requested to provide the user with a glue what the caller
@@ -1816,7 +1816,7 @@
 	* kcm/config.c: allow KCM system ccache to be configured from
 	  krb5.conf, in the system_ccache stanza of [kcm]
=20
-2005-02-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kcm/protocol.c: use -1 as the invalid pid number
=20
@@ -1849,7 +1849,7 @@
=20
 	* kcm: add KCM daemon
=20
-2005-02-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/send_to_kdc.c (send_and_recv_udp): make private again
=20
@@ -1889,17 +1889,17 @@
 	* kdc/kerberos5.c: don't crash when logging no server etype
 	  support if client =3D=3D NULL
=20
-2005-01-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kstash.c: s/random_key/random_key_flag/, From Dave Love
 	<d.love at dl.ac.uk>
=20
-2005-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/apps.texi: Texinfo fixes. Text about irix 6.5 using
 	PAM. From: Dave Love <d.love at dl.ac.uk>
=20
-2005-01-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c: cast argument to isdigit to
 	unsigned char
@@ -1935,7 +1935,7 @@
 	krb5_enctype_valid, so use the later since its older and the api
 	doesn't really need another entry point
=20
-2005-01-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswdd.8: document --addresses, controls what
 	addresses kpasswd should listen too
@@ -1993,12 +1993,12 @@
 	* lib/asn1/k5.asn1: add authorization data types for enctype
 	negotiation implementation
=20
-2005-01-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/changepw.c (change_password_loop): on failing to find a
 	kdc, set result_code to KRB5_KPASSWD_HARDERROR
 =09
-2005-01-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/heimdal.texi: Happy New Year
 =09
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/ChangeLog.2006
--- a/head/crypto/heimdal/ChangeLog.2006	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/ChangeLog.2006	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-2006-12-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/process.c: Handle kx509 requests.
=20
@@ -26,13 +26,13 @@
 	* lib/krb5/digest.c (krb5_ntlm_rep_get_sessionkey): return value
 	is krb5_error_code
 =09
-2006-12-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/mk_req_ext.c (_krb5_mk_req_internal): use md5 for
 	des-cbc-md4 and des-cbc-md5.  This is for (older) windows that
 	will be unhappy anything else.  From Inna Bort-Shatsky
 =09
-2006-12-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/digest.c: Prefix internal symbol with _kdc_.
=20
@@ -48,11 +48,11 @@
=20
 	* kdc/digest.c: Add digest acl's
 =09
-2006-12-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* fix-export: build ntlm-private.h
 =09
-2006-12-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* include/make_crypto.c: Include <.../hmac.h>.
=20
@@ -65,21 +65,21 @@
 	* kdc/digest.c: Add support for generating NTLM2 session security
 	answer.
 =09
-2006-12-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/digest.c: Add sessionkey accessor functions.
 =09
-2006-12-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/digest.c: Unwrap the NTLM session key and return it to the
 	server.
 =09
-2006-12-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/store.c (krb5_ret_principal): Fix a bug in the malloc
 	failure part, noticed by Arnaud Lacombe in NetBSD coverity scan.
 =09
-2006-12-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/fcache.c (fcc_get_cache_next): avoid const warning.
=20
@@ -111,12 +111,12 @@
 	* lib/krb5/krb5_locl.h: Expand the default root for some of the cc
 	type names.
 =09
-2006-12-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/init_creds_pw.c (free_paid): free the krb5_data
 	structure too.  Bug report from Stefan Metzmacher.
 =09
-2006-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kuser/kinit.c: Read the appdefault configration before we try to
 	use the flags.  Bug reported by Ingemar Nilsson.
@@ -125,23 +125,23 @@
=20
 	* kuser/kdigest-commands.in: prefix digest commands with digest-
 =09
-2006-12-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/hprop.c: Return error codes on failure, improve error
 	reporting.
 =09
-2006-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: sprinkle more _krb5_pk_copy_error
=20
 	* lib/krb5/pkinit.c: Copy more hx509 error strings to krb5 error
 	strings
 =09
-2006-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* include/Makefile.am: CLEANFILES +=3D vis.h
 =09
-2006-12-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (_kdc_as_rep): add AD-INITAL-VERIFIED-CAS to the
 	encrypted ticket
@@ -164,31 +164,31 @@
 	really should be the trust anchors of the client.
=20
 	* kuser/generate-requests.c: Use strcspn to remove \n from
-	string returned by fgets.  From Bj=F6rn Sandell
+	string returned by fgets.  From Bj=C3=B6rn Sandell
 =09
 	* kpasswd/kpasswd-generator.c: Use strcspn to remove \n from
-	string returned by fgets.  From Bj=F6rn Sandell
+	string returned by fgets.  From Bj=C3=B6rn Sandell
 =09
-2006-12-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: Clear errno before calling the strtol
-	functions. From Paul Stoeber to OpenBSD by Ray Lai and Bj=F6rn
+	functions. From Paul Stoeber to OpenBSD by Ray Lai and Bj=C3=B6rn
 	Sandell.
=20
 	* lib/krb5/config_file.c: Use strcspn to remove \n from fgets
-	result. Prompted by change by Ray Lai of OpenBSD via Bj=F6rn
+	result. Prompted by change by Ray Lai of OpenBSD via Bj=C3=B6rn
 	Sandell.
=20
 	* kdc/string2key.c: Use strcspn to remove \n from fgets
-	result. Prompted by change by Ray Lai of OpenBSD via Bj=F6rn
+	result. Prompted by change by Ray Lai of OpenBSD via Bj=C3=B6rn
 	Sandell.
 =09
-2006-11-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krbhst.c (plugin_get_hosts): be more paranoid and pass
 	in a NULLed plugin list
 =09
-2006-11-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_krb5_conf.c: add more pkinit options.
=20
@@ -201,7 +201,7 @@
=20
 	* lib/hdb/Makefile.am: Add LIB_com_err to pacify AIX
 =09
-2006-11-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: Make build again from the hdb_entry
 	wrapping. Patch from Andreas Hasenack.
@@ -209,7 +209,7 @@
 	* kdc/pkinit.c: Need better code in the DH parameter rejection
 	case, add comment to that effect.
 =09
-2006-11-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/krb5tgs.c: Reply KRB5KRB_ERR_RESPONSE_TOO_BIG for too large
 	packets when using datagram based transports.
@@ -218,7 +218,7 @@
=20
 	* lib/krb5/pkinit.c (build_auth_pack): set supportedCMSTypes.
 =09
-2006-11-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Pass down hx509_peer_info.
=20
@@ -228,19 +228,19 @@
 	* kdc/pkinit.c (_kdc_pk_rd_padata): Pick up supportedCMSTypes and
 	pass in into hx509_cms_create_signed_1 via hx509_peer_info blob.
 =09
-2006-11-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/send_to_kdc.c: Set the large_msg_size to 1400, lets not
 	fragment packets and avoid stupid linklayers that doesn't allow
 	fragmented packets (unix dgram sockets on Mac OS X)
 =09
-2006-11-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (_krb5_pk_create_sign): stuff down the users
 	certs in the pool to make sure a path is returned, without this
 	proxy certificates wont work.
 =09
-2006-11-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/config.c: Make all pkinit options prefixed with pkinit_
=20
@@ -257,7 +257,7 @@
 	* lib/krb5/get_cred.c: Use KRB5_KU_OTHER_CKSUM for the impersonate
 	checksum.
 =09
-2006-11-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/verify_user.c: Make krb5_get_init_creds_opt_free take a
 	context argument.
@@ -286,14 +286,14 @@
 	* appl/gssmask/gssmask.c: Make krb5_get_init_creds_opt_free take a
 	context argument.
 =09
-2006-11-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* doc/setup.texi: fix pkinit option (s/-/_/)
=20
 	* kdc/config.c: revert the enable-pkinit change, and make it
 	consistant with all other other enable- options
 =09
-2006-11-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: Make all pkinit options prefixed with pkinit_
=20
@@ -310,7 +310,7 @@
 	* lib/krb5/mit_glue.c (krb5_c_keylength): mit changed the api,
 	deal.
 =09
-2006-11-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/pac.c (fill_zeros): stop using MIN.
=20
@@ -325,7 +325,7 @@
 	* lib/krb5/krbhst.c: Use plugin for the other realm locate types
 	too.
 =09
-2006-11-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_locl.h: Add plugin api
=20
@@ -344,7 +344,7 @@
=20
 	* lib/krb5/krb5.h: Add struct krb5_pac.
 =09
-2006-11-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/test_pac.c: PAC testing.
=20
@@ -362,7 +362,7 @@
=20
 	* lib/krb5/mit_glue.c: Add krb5_c_keylength.
 =09
-2006-11-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pac.c: Almost enough code to do PAC parsing and
 	verification, missing in the unix2NTTIME and ucs2 corner. The
@@ -372,7 +372,7 @@
=20
 	* kdc/hpropd.c: Remove support dumping to a kerberos 4 database.
 =09
-2006-11-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c: rename krb5_[gs]et_time_wrap to
 	krb5_[gs]et_max_time_skew
@@ -382,7 +382,7 @@
=20
 	* lib/krb5/rd_req.c: Add more krb5_rd_req_out_get functions.
=20
-2006-11-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/krb5.h: krb5_rd_req{,_in,_out}_ctx.
=20
@@ -390,11 +390,11 @@
 	dancing version of the krb5_rd_req and implement krb5_rd_req and
 	krb5_rd_req_with_keyblock using it.
=20
-2006-11-04 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-11-04 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* kdc/kerberos5.c (_kdc_as_rep): More verbose time skew logging.
 =09
-2006-11-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/expand_hostname.c: Rename various routines and
 	constants from canonize to canonicalize.  From Andrew Bartlett
@@ -407,12 +407,12 @@
 	* appl/gssmask/common.c (add_list): fix alloc statement.
 	From Alex Deiter
 =09
-2006-10-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* include/Makefile.am: Move version.h and version.h.in to
 	DISTCLEANFILES.
 =09
-2006-10-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/gssmask/gssmask.c: Only log when there are resources left.
=20
@@ -421,11 +421,11 @@
 	* appl/gssmask/gssmask.c (AcquireCreds): free
 	krb5_get_init_creds_opt
 =09
-2006-10-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* configure.in: heimdal 0.8-RC1
=20
-2006-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/digest.c: Try to not leak memory.
=20
@@ -459,7 +459,7 @@
=20
 	* lib/krb5/crypto.c (AES_string_to_key): Try to not leak memory.
=20
-2006-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/heimdal-build.sh: Add --test-environment
=20
@@ -468,7 +468,7 @@
 	* lib/hdb/Makefile.am: remove dependency on et files covert_db
 	that now is removed
 =09
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* include/Makefile.am: add gssapi to subdirs
=20
@@ -507,7 +507,7 @@
=20
 	* lib/krb5/Makefile.am: add more files
 =09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/Makefile.am: Add heimdal-build.sh to EXTRA_DIST.
=20
@@ -521,7 +521,7 @@
=20
 	* configure.in: make --disable-pk-init help text also negative
 =09
-2006-10-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kuser/kgetcred.c: Avoid memory leak.
=20
@@ -538,7 +538,7 @@
=20
 	* lib/krb5/test_princ.c: Test principal parsing and unparsing.
 =09
-2006-10-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_host_realm.c (krb5_get_host_realm): make sure we
 	don't recurse
@@ -591,11 +591,11 @@
=20
 	* kdc/kerberos5.c: Prefix asn1 primitives with der_.
 =09
-2006-10-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* fix-export: Build lib/asn1/der-protos.h.
 =09
-2006-10-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/gssmask/Makefile.am: Add explit depenency on libroken.
=20
@@ -618,7 +618,7 @@
=20
 	* lib/krb5/data.c: Prefix der primitives with der_.
 =09
-2006-10-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/pkinit.c (pk_mk_pa_reply_enckey): add missing break. From
 	Olga Kornievskaia.
@@ -627,13 +627,13 @@
=20
 	* include/bits.c: Include Xint64 types.
 =09
-2006-10-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/heimdal-build.sh: Add socketwrapper and cputime limit.
=20
 	* kdc/connect.c (loop): Log that the kdc have started.
 =09
-2006-10-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/connect.c (do_request): tell krb5_kdc_process_request if its
 	a datagram reply or not
@@ -658,7 +658,7 @@
 	* kdc/krb5tgs.c (tgs_parse_request): set cusec, not csec from
 	auth->cusec.
 =09
-2006-10-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* fix-export: dist_-ify libkadm5clnt_la_SOURCES too
=20
@@ -677,7 +677,7 @@
 	checksum is done over the whole packet. Reported by Olga
 	Kornievskaia
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* include/Makefile.am: crypto-headers.h is a nodist header
=20
@@ -698,7 +698,7 @@
 	* kdc/kerberos5.c: Adapt to signature change of
 	_krb5_principalname2krb5_principal.
 =09
-2006-10-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krbhst.c (common_init): don't try DNS when there is
 	realm w/o a dot.
@@ -736,7 +736,7 @@
=20
 	* appl/gssmask/common.h: Maybe include <sys/wait.h>.
 =09
-2006-10-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* appl/gssmask/common.h: disable ENABLE_PTHREAD_SUPPORT and
 	explain why
@@ -749,7 +749,7 @@
=20
 	* tools/heimdal-build.sh: first cut
 =09
-2006-10-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* configure.in: Call AB_INIT.
=20
@@ -762,11 +762,11 @@
=20
 	* lib/krb5/krb5_digest.3: Add all protos
 =09
-2006-10-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/krb5_digest.3: Basic krb5_digest manpage.
 =09
-2006-10-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* fix-export: build gssapi mech private files
 =09
@@ -786,7 +786,7 @@
=20
 	* fix-export: build gssapi mech private files
 =09
-2006-09-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* appl/gssmask/gssmaestro.c: Handle FIRST_CALL in the context
 	building, better error handling.
@@ -799,18 +799,18 @@
 	* appl/gssmask/gssmaestro.c: Check that the pre-wrapped data is
 	the same as afterward.
 =09
-2006-09-25  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-09-25  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* appl/gssmask/gssmaestro.c: Remove stray GSS_C_DCE_STYLE.
=20
 	* appl/gssmask/gssmaestro.c: Add logsocket support.
 =09
-2006-09-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* appl/gssmask/gssmaestro.c (build_context): print the step the
 	context exchange.
 =09
-2006-09-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/gssmask/gssmaestro.c: Add GSS_C_INTEG_FLAG|GSS_C_CONF_FLAG
 	to all context flags
@@ -826,7 +826,7 @@
 	* lib/krb5/rd_req.c: disable ETypeList parsing usage for now, cfx
 	seems broken and its not good to upgrade to a broken enctype.
 =09
-2006-09-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* appl/gssmask/gssmask.c: Add wrap/unwrap ops
=20
@@ -842,7 +842,7 @@
 	* appl/gssmask/gssmaestro.c: test self context building and all
 	permutation of clients
 =09
-2006-09-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/gssmask/gssmask.c: add --logfile option, use htons() on
 	port number
@@ -851,7 +851,7 @@
=20
 	* configure.in: Make pk-init turned on by default.
 =09
-2006-09-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* fix-export: Build lib/hx509/{hx509-protos.h,hx509-private.h}.
=20
@@ -864,20 +864,20 @@
 	* kdc/krb5tgs.c: Check the adtkt in the constrained delegation
 	case too.
 =09
-2006-09-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/main.c (sigterm): don't _exit, let loop() catch the signal
 	instead.
=20
-	* lib/krb5/krb5_timeofday.3: Fixes from Bj=F6rn Sandell.
-
-	* lib/krb5/krb5_get_init_creds.3: Fixes from Bj=F6rn Sandell.
+	* lib/krb5/krb5_timeofday.3: Fixes from Bj=C3=B6rn Sandell.
+
+	* lib/krb5/krb5_get_init_creds.3: Fixes from Bj=C3=B6rn Sandell.
 =09
-2006-09-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/krb5-config.in: Add "kafs" option.
 =09
-2006-09-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/db.c: By using full function calling conversion (*func)
 	we avoid problem when close(fd) is overridden using a macro.
@@ -886,7 +886,7 @@
 	conversion (*func) we avoid problem when close(fd) is overridden
 	using a macro.
 =09
-2006-09-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/kerberos5.c: Signing outgoing tickets.
=20
@@ -896,17 +896,17 @@
 	* lib/krb5/pkinit.c: Adapt to new signature of
 	hx509_cms_unenvelope.
 =09
-2006-09-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (pk_verify_host): set errorstrings in a
 	sensable way
 =09
-2006-09-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_init_context.3: Prevent a font generation warning,
 	from Jason McIntyre.
 =09
-2006-09-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/context.c (krb5_init_ets): Add the hx errortable
=20
@@ -915,7 +915,7 @@
 	* lib/krb5/pkinit.c (_krb5_pk_verify_sign): catch the error string
 	from the hx509 lib
 =09
-2006-09-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds.c (krb5_get_init_creds_opt_set_default_flags):
 	fix argument to krb5_get_init_creds_opt_set_addressless.
@@ -945,14 +945,14 @@
 	instead of passing in the empty set of address into
 	krb5_get_init_creds_opt_set_addresses.
 =09
-2006-09-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kuser/kinit.c (renew_validate): inherit the proxiable and
 	forwardable from the orignal ticket, pointed out by Bernard
 	Antoine of CERN.
 =09
 	* doc/setup.texi: More text about the acl_file entry and
-	hdb-ldap-structural-object.  From R=FCdiger Ranft.
+	hdb-ldap-structural-object.  From R=C3=BCdiger Ranft.
=20
 	* lib/krb5/krbhst.c (fallback_get_hosts): limit the fallback
 	lookups to 5.  Patch from Wesley Craig, umich.edu
@@ -963,7 +963,7 @@
 	* appl/test/tcp_server.c (proto): use keytab for krb5_recvauth
 	Patch from Ingemar Nilsson <init at pdc.kth.se>
 =09
-2006-08-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kdigest.c (help): use sl_slc_help().
=20
@@ -971,7 +971,7 @@
=20
 	* lib/krb5/digest.c: Catch more error.
=20
-2006-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: language.
=20
@@ -984,7 +984,7 @@
 	* lib/krb5/digest.c: In the case where we get a DigestError back,
 	save the error string and code.
 =09
-2006-08-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c: Remove _kdc_find_etype(), its no longer used.
=20
@@ -1027,7 +1027,7 @@
 	tgt etype, now the krbtgt can be a aes-only key without the need
 	to support not-as-good etypes for the krbtgt.
 =09
-2006-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/misc.c: Change _kdc_db_fetch() to return the database
 	pointer to if needed by the consumer.
@@ -1059,13 +1059,13 @@
 =09
 	* lib/krb5/digest.c: Add digest support to the client side.
 =09
-2006-08-21  Love H=F6rnquist =C5strand  <lha at it.kth.se>
+2006-08-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.kth.se>
=20
 	* lib/krb5/rd_rep.c (krb5_rd_rep): free krb5_ap_rep_enc_part on
 	error and set return pointer to NULL
 	(krb5_free_ap_rep_enc_part): permit freeing of NULL
 =09
-2006-08-18  Love H=F6rnquist =C5strand  <lha at it.kth.se>
+2006-08-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.kth.se>
=20
 	* kdc/{Makefile.am,kdigest.c,kdigest-commands.in}:
 	Frontend for remote digest service in KDC
@@ -1081,7 +1081,7 @@
 	* lib/krb5/init_creds.c (krb5_get_init_creds_opt_get_error): clear
 	error string on error.
 =09
-2006-07-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c: remove aes-192 (CMS)
=20
@@ -1089,7 +1089,7 @@
 =09
 	* lib/krb5/crypto.c: Remove CMS symmetric encryption support.
 =09
-2006-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c (_kdc_pk_check_client): make it not crash when
 	there are no acl
@@ -1105,7 +1105,7 @@
=20
 	* lib/hdb/ext.c: Add hdb_entry_get_pkinit_hash().
 =09
-2006-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: If --password-file gets STDIN, read the password
 	from the standard input.
@@ -1114,20 +1114,20 @@
=20
 	* lib/krb5/krb5_string_to_key.3: Remove duplicate to.
 =09
-2006-07-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/krb5tgs.c: (tgs_build_reply): when checking for removed
 	principals, check the second component of the krbtgt, otherwise
 	cross realm wont work.  Prompted by report from Mattias Amnefelt.
=20
-2006-07-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/connect.c (handle_vanilla_tcp): use unsigned integer for for
 	length
 	(handle_tcp): if the high bit it set in the unknown case, send
 	back a KRB_ERR_FIELD_TOOLONG
 =09
-2006-07-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/gssmask/gssmaestro.c: Add get_version_capa, cache
 	target_name.
@@ -1143,7 +1143,7 @@
 	* appl/gssmask/gssmaestro.c: break out out the build context
 	function
 =09
-2006-07-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* appl/gssmask/gssmaestro.c: externalize slave handling, add
 	GetTargetName glue
@@ -1160,7 +1160,7 @@
 	* appl/gssmask: break out common function; add gssmaestro (that
 	only tests one context for now)
=20
-2006-06-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/store_fd.c (krb5_storage_from_fd): don't leak fd on
 	malloc failure
@@ -1173,11 +1173,11 @@
 	* lib/krb5/cache.c (krb5_cc_new_unique): use KRB5_DEFAULT_CCNAME
 	as the default prefix
 =09
-2006-06-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/heimdal.texi: Add Doug Rabson's license
 =09
-2006-06-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds.c: Add storing and getting KRB-ERROR in the
 	krb5_get_init_creds_opt structure.
@@ -1187,11 +1187,11 @@
 	* lib/krb5/krb5_locl.h (_krb5_get_init_creds_opt_private): add
 	KRB-ERROR
 =09
-2006-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: section about verify_krb5_conf and kadmin check
 =09
-2006-06-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/init_creds_pw.c (get_init_creds_common): drop cred
 	argument, its unused
@@ -1200,7 +1200,7 @@
 =09
 	* lib/krb5/krb5_get_creds.3: new file
 =09
-2006-06-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb-ldap.c: don't use the sambaNTPassword if there is
 	ARCFOUR key already.  Idea from Andreas Hasenack.  While here, set
@@ -1211,7 +1211,7 @@
=20
 	* kdc/kdc.h: Add enable_v4_per_principal
 =09
-2006-06-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c (_kdc_as_rep): if kdc_time +
 	config->kdc_warn_pwexpire is past pw_end, add expiration
@@ -1222,11 +1222,11 @@
=20
 	* kdc/kerberos5.c: indent.
 =09
-2006-06-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos5.c: constify
 =09
-2006-06-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/get_cred.c: Allow setting additional tickets in the
 	tgs-req
@@ -1252,7 +1252,7 @@
 	* lib/krb5/krb5.h: Add krb5_get_creds_opt_data and some more
 	KRB5_GC flags.
 =09
-2006-06-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/hdb/ext.c (hdb_entry_get_ConstrainedDelegACL): new function.
=20
@@ -1271,13 +1271,13 @@
 	* kdc/kerberos5.c: split out krb5 tgs req to make it easier to
  	reorganize the code.
 =09
-2006-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_get_init_creds.3: spelling Bj=F6rn Sandell
-
-	* lib/krb5/krb5_get_in_cred.3: spelling Bj=F6rn Sandell
+2006-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/krb5_get_init_creds.3: spelling Bj=C3=B6rn Sandell
+
+	* lib/krb5/krb5_get_in_cred.3: spelling Bj=C3=B6rn Sandell
 =09
-2006-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kpasswd/kpasswdd.c (change): select the realm based on the
 	target principal From Gabor Gombas
@@ -1286,7 +1286,7 @@
 =09
 	* lib/krb5/krb5.h: Add KRB5_PROMPT_TYPE_INFO
 =09
-2006-05-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Hidden field of hx509 prompter is removed.
 	Fix a warning.
@@ -1307,7 +1307,7 @@
 	* lib/krb5/krb5_acl_match_file.3: Various tweaks, from Jason
 	McIntyre.
 =09
-2006-05-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kuser/kinit.c: Move parsing of the PK-INIT configuration file to
 	the library so application doesn't need to deal with it.
@@ -1322,7 +1322,7 @@
 	* lib/krb5/pkinit.c (hx_pass_prompter): return 0 on success and 1
 	on failure. Pointed out by Douglas E. Engert.
 =09
-2006-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/crypto.c: Catches both keyed checkout w/o crypto
 	context cases and doesn't reset the string, and corrects the
@@ -1331,7 +1331,7 @@
 	* lib/krb5/crypto.c: Drop aes-cbc, rc2 and CMS padding support,
 	its all containted in libhcrypto and libhx509 now.
 =09
-2006-05-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/pkinit.c (_krb5_pk_verify_sign): Use
 	hx509_get_one_cert.
@@ -1339,7 +1339,7 @@
 	* lib/krb5/crypto.c (create_checksum): provide a error message
 	that a key checksum needs a key.  From Andew Bartlett.
 =09
-2006-05-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/pkinit.c: Now that hcrypto supports DH, remove check
 	for hx509 null DH.
@@ -1357,21 +1357,21 @@
 	* kcm/acl.c: Multicache kcm interation isn't done yet, let wait
 	with this enum.
 =09
-2006-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* lib/krb5/krb5_set_default_realm.3: Spelling/mdoc from Bj=F6rn
+2006-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* lib/krb5/krb5_set_default_realm.3: Spelling/mdoc from Bj=C3=B6rn
 	Sandell
=20
-	* lib/krb5/krb5_rcache.3: Spelling/mdoc from Bj=F6rn Sandell
-
-	* lib/krb5/krb5_keytab.3: Spelling/mdoc from Bj=F6rn Sandell
-
-	* lib/krb5/krb5_get_in_cred.3: Spelling/mdoc from Bj=F6rn Sandell
-
-	* lib/krb5/krb5_expand_hostname.3: Spelling/mdoc from Bj=F6rn
+	* lib/krb5/krb5_rcache.3: Spelling/mdoc from Bj=C3=B6rn Sandell
+
+	* lib/krb5/krb5_keytab.3: Spelling/mdoc from Bj=C3=B6rn Sandell
+
+	* lib/krb5/krb5_get_in_cred.3: Spelling/mdoc from Bj=C3=B6rn Sandell
+
+	* lib/krb5/krb5_expand_hostname.3: Spelling/mdoc from Bj=C3=B6rn
 	Sandell
=20
-	* lib/krb5/krb5_c_make_checksum.3: Spelling/mdoc from Bj=F6rn
+	* lib/krb5/krb5_c_make_checksum.3: Spelling/mdoc from Bj=C3=B6rn
 	Sandell
=20
 	* lib/krb5/keytab_file.c (fkt_next_entry_int): read the 32 bit
@@ -1399,7 +1399,7 @@
=20
 	* lib/krb5/store.c: Rewrite the krb5_ret_u as proposed by Johan.
 =09
-2006-05-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/kerberos4.c: Use the new unsigned integer storage types.
=20
@@ -1417,7 +1417,7 @@
=20
 	* lib/krb5/test_store.c: Test the integer storage types.
 =09
-2006-05-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/store.c (krb5_store_principal): make it take a
 	krb5_const_principal, indent
@@ -1432,79 +1432,79 @@
=20
 	* kdc/config.c: read [kdc]pki-kdc-ocsp
 =09
-2006-05-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/pkinit.c (_kdc_pk_mk_pa_reply): send back ocsp response if
 	it seems to be valid, simplfy the pkinit-windows DH case (it
 	doesn't exists).
 =09
-2006-05-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
-	* lib/krb5/krb5_warn.3: Spelling/mdoc changes, from Bj=F6rn Sandell.
-
-	* lib/krb5/krb5_verify_user.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_warn.3: Spelling/mdoc changes, from Bj=C3=B6rn Sandell.
+
+	* lib/krb5/krb5_verify_user.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
 	* lib/krb5/krb5_verify_init_creds.3: Spelling/mdoc changes, from
-	Bj=F6rn Sandell.
-
-	* lib/krb5/krb5_timeofday.3: Spelling/mdoc changes, from Bj=F6rn
+	Bj=C3=B6rn Sandell.
+
+	* lib/krb5/krb5_timeofday.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
-	* lib/krb5/krb5_ticket.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_ticket.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
-	* lib/krb5/krb5_rd_safe.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_rd_safe.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
-	* lib/krb5/krb5_rcache.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_rcache.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
-	* lib/krb5/krb5_principal.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_principal.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
-	* lib/krb5/krb5_parse_name.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_parse_name.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
-	* lib/krb5/krb5_mk_safe.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_mk_safe.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
-	* lib/krb5/krb5_keyblock.3: Spelling/mdoc changes, from Bj=F6rn
+	* lib/krb5/krb5_keyblock.3: Spelling/mdoc changes, from Bj=C3=B6rn
 	Sandell.
=20
 	* lib/krb5/krb5_is_thread_safe.3: Spelling/mdoc changes, from
-	Bj=F6rn Sandell.
+	Bj=C3=B6rn Sandell.
=20
 	* lib/krb5/krb5_generate_random_block.3: Spelling/mdoc changes,
-	from Bj=F6rn Sandell.
+	from Bj=C3=B6rn Sandell.
=20
 	* lib/krb5/krb5_generate_random_block.3: Spelling/mdoc changes,
-	from Bj=F6rn Sandell.
+	from Bj=C3=B6rn Sandell.
=20
 	* lib/krb5/krb5_expand_hostname.3: Spelling/mdoc changes, from
-	Bj=F6rn Sandell.
+	Bj=C3=B6rn Sandell.
=20
 	* lib/krb5/krb5_check_transited.3: Spelling/mdoc changes, from
-	Bj=F6rn Sandell.
+	Bj=C3=B6rn Sandell.
=20
 	* lib/krb5/krb5_c_make_checksum.3: Spelling/mdoc changes, from
-	Bj=F6rn Sandell.
+	Bj=C3=B6rn Sandell.
=20
 	* lib/krb5/krb5_address.3: Spelling/mdoc changes, from
-	Bj=F6rn Sandell.
+	Bj=C3=B6rn Sandell.
=20
 	* lib/krb5/krb5_acl_match_file.3: Spelling/mdoc changes, from
-	Bj=F6rn Sandell.
-
-	* lib/krb5/krb5.3: Spelling, from Bj=F6rn Sandell.
+	Bj=C3=B6rn Sandell.
+
+	* lib/krb5/krb5.3: Spelling, from Bj=C3=B6rn Sandell.
 =09
-	* doc/ack.texi: add Bj=F6rn
-
-2006-04-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+	* doc/ack.texi: add Bj=C3=B6rn
+
+2006-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (cert2epi): don't include subject if its null
 =09
-2006-04-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Send over what trust anchors the client have
 	configured.
@@ -1516,7 +1516,7 @@
 	* kdc/pkinit.c (_kdc_pk_check_client): reorganize and make log
 	when a SAN matches.
 =09
-2006-04-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* doc/setup.texi: More options and some text about windows
 	clients, certificate and KDCs.
@@ -1529,7 +1529,7 @@
=20
 	* lib/hdb/hdb.h: Bump hdb interface version to 4.
 =09
-2006-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kuser/kdestroy.1: Document --credential=3Dprincipal.
=20
@@ -1556,7 +1556,7 @@
 	the entry and pass it in as a seprate argument. Add more flags to
 	->hdb_get(). Re-indent.
 =09
-2006-04-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* doc/setup.texi: document pki-allow-proxy-certificate
=20
@@ -1576,7 +1576,7 @@
 	* kdc/kerberos5.c (find_keys): add client_name and server_name
 	argument and use them, and adapt callers.
 =09
-2006-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kuser/kinit.1: document option password-file
=20
@@ -1594,7 +1594,7 @@
 	* lib/hdb/keys.c (parse_key_set): handle error case better
 	(hdb_generate_key_set): return better error
 =09
-2006-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/hdb/hdb.c (hdb_create): print out what we don't support
=20
@@ -1619,7 +1619,7 @@
 	* lib/krb5/init_creds_pw.c: Pass down realm to
 	_krb5_pk_rd_pa_reply
 =09
-2006-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (pk_verify_host): Add begining of finding
 	subjectAltName_otherName pk-init-san and verifing it.
@@ -1639,13 +1639,13 @@
=20
 	* tools/kdc-log-analyze.pl: count v5 cross realms too
 =09
-2006-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/pkinit.c: Adapt to change in hx509_cms_create_signed_1.
=20
 	* lib/krb5/pkinit.c: Adapt to change in hx509_cms_create_signed_1.
 =09
-2006-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c (_kdc_pk_rd_padata): use
 	hx509_cms_unwrap_ContentInfo.
@@ -1658,7 +1658,7 @@
 	* kdc/config.c: Rename pki-chain to pki-pool to match rest of
 	code.
 =09
-2006-04-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/rd_priv.c: Fix argument to krb5_data_zero.
=20
@@ -1673,7 +1673,7 @@
 	* lib/krb5/pkinit.c (_krb5_pk_load_id): Added certificate revoke
 	information, ie CRL's
 =09
-2006-04-10 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-04-10 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* lib/krb5/replay.c (krb5_rc_resolve_full): make compile again.
=20
@@ -1718,15 +1718,15 @@
 	calloc. removed check that was never really used. Coverity NetBSD
 	CID#2370
 =09
-2006-04-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
-	* lib/krb5/rd_req.c (krb5_verify_ap_req2): make sure `ticket=B4
+	* lib/krb5/rd_req.c (krb5_verify_ap_req2): make sure `ticket=C2=B4
 	points to NULL in case of error, add error handling, use calloc.
=20
 	* kpasswd/kpasswdd.c (doit): when done, close all fd in the
 	sockets array and free it.  Coverity NetBSD CID#1916
 =09
-2006-04-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/store.c (krb5_ret_principal): fix memory leak Coverity,
 	NetBSD CID#1695
@@ -1734,7 +1734,7 @@
 	* kdc/524.c (_kdc_do_524): Handle memory allocation failure
 	Coverity, NetBSD CID#2752
 =09
-2006-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/keytab_file.c (krb5_kt_ret_principal): plug a memory
 	leak Coverity NetBSD CID#1890
@@ -1749,12 +1749,12 @@
=20
 	* kdc/hprop.c (main): remove dead code.  Coverity NetBSD CID#633
 =09
-2006-04-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kpasswd/kpasswd-generator.c (read_words): catch empty file case,
 	will cause PBE (division by zero) later. From Tobias Stoeckmann.
 =09
-2006-04-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/hdb/keytab.c: Remove a delta from last revision that should
 	have gone in later.
@@ -1832,7 +1832,7 @@
 	* lib/krb5/log.c (krb5_addlog_dest): make string length match
 	strings in strcasecmp.  Found by IBM checker.
 =09
-2006-03-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/hdb/hdb-ldap.c (LDAP_message2entry): in declaration set
 	variable_name as "hdb_entry_ex"
@@ -1846,7 +1846,7 @@
 	* kuser/kinit.c: Add pool of certificates to help certificate path
 	building for clients sending incomplete path in the signedData.
 =09
-2006-03-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/pkinit.c: Add pool of certificates to help certificate path
 	building for clients sending incomplete path in the signedData.
@@ -1855,7 +1855,7 @@
 	path building for clients sending incomplete path in the
 	signedData.
 =09
-2006-03-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kdc/config.c: Allow passing in related certificates used to
 	build the chain.
@@ -1872,7 +1872,7 @@
=20
 	* tools/Makefile.am: Add hx509 when using PK-INIT.
 =09
-2006-03-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/acache.c: Use ticket flags definition, might fix Mac OS
 	X Kerberos.app problems.
@@ -1896,30 +1896,30 @@
=20
 	* lib/krb5/pkinit.c: Switch to hx509.
 =09
-2006-03-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kdc/kerberos5.c (log_patypes): log the patypes requested by the
 	client
 =09
-2006-03-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c (_krb5_pk_rd_pa_reply): pass down the
 	req_buffer in the w2k case too. From Douglas E. Engert.
 =09
-2006-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/mk_req_ext.c (_krb5_mk_req_internal): on failure, goto
 	error handling.  Fixes Coverity NetBSD CID 2591 by catching a
 	failing krb5_copy_keyblock()
 =09
-2006-03-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/addr_families.c (krb5_free_addresses): reset val,len in
 	address when free-ing.  Fixes Coverity NetBSD bug #2605
 	(krb5_parse_address): reset val,len before possibly return errors
 	Fixes Coverity NetBSD bug #2605
 =09
-2006-03-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* lib/krb5/send_to_kdc.c (recv_loop): it should never happen, but
 	make sure nbytes > 0
@@ -1930,7 +1930,7 @@
 	* lib/krb5/crypto.c (decrypt_*): handle the case where the
 	plaintext is 0 bytes long, realloc might then return NULL.
 =09
-2006-02-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_string_to_key.3: Drop krb5_string_to_key_derived.
=20
@@ -1949,24 +1949,24 @@
 	else, they should be around the example, not inside it, and
 	probably shouldn't be used in html at all
=20
-2006-02-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_warn.3: Document that applications want to use
 	krb5_get_error_message, add example.
=20
-2006-02-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/crypto.c (krb5_generate_random_block): check return
 	value from RAND_bytes
=20
 	* lib/krb5/error_string.c: Change indentation, update (c)
=20
-2006-02-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: Make struct krb5_dh_moduli available when
 	compiling w/o pkinit.
 =09
-2006-02-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/pkinit.c: update to new paChecksum definition, update
 	the dhgroup handling
@@ -1974,14 +1974,14 @@
 	* kdc/pkinit.c: update to new paChecksum definition, use
 	hdb_entry_ex
 =09
-2006-02-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/krb5_locl.h: Move Configurable options to last in the
 	file.
 =09
 	* lib/krb5/krb5_locl.h: Wrap KRB5_ADDRESSLESS_DEFAULT with #ifndef
 =09
-2006-02-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kpasswd/kpasswdd.c: Send back a better error-message to the
 	client in case the password change was rejected.
@@ -2011,23 +2011,23 @@
 	* lib/krb5/krb5_locl.h: Introduce KRB5_ADDRESSLESS_DEFAULT that
 	controlls all address-less behavior.  Defaults to false.
 =09
-2006-02-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lib/krb5/n-fold-test.c: main is not a KRB5_LIB_FUNCTION
=20
 	* lib/krb5/mk_priv.c (krb5_mk_priv): abort if ASN1_MALLOC_ENCODE
 	failes to produce the matching lenghts.
 =09
-2006-01-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kcm/protocol.c (kcm_op_retrieve): remove unused variable
 =09
-2006-01-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* tools/krb5-config.in: Move depenency on @LIB_dbopen@ to
 	kadm-server, kerberos library doesn't depend on db-library.
 =09
-2006-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* include/Makefile.am: Don't clean crypto headers, they now live
 	in hcrypto/.  Add hcrypto to SUBDIRS.
@@ -2039,7 +2039,7 @@
 	* include/make_crypto.c: Include more crypto headerfiles. Remove
 	support for old hash names.
 =09
-2006-01-02  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-01-02  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* kdc/misc.c (_kdc_db_fetch): use calloc to allocate the entry,
 	from Andrew Bartlet.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/LICENSE
--- a/head/crypto/heimdal/LICENSE	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/LICENSE	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-Copyright (c) 1995 - 2007 Kungliga Tekniska H=F6gskolan
+Copyright (c) 1995 - 2011 Kungliga Tekniska H=C3=B6gskolan
 (Royal Institute of Technology, Stockholm, Sweden).=20
 All rights reserved.=20
=20
@@ -28,3 +28,6 @@
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY=20
 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 SUCH DAMAGE.=20
+
+
+Please see info documentation for the complete list of licenses.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/Makefile.am
--- a/head/crypto/heimdal/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 22497 2008-01-21 12:12:23Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -6,13 +6,21 @@
 kcm_dir =3D kcm
 endif
=20
-SUBDIRS=3D  include lib kuser kdc admin kadmin kpasswd=20
-SUBDIRS+=3D $(kcm_dir) appl doc tools tests packages etc
+SUBDIRS=3D  include base lib kuser kdc admin kadmin kpasswd=20
+SUBDIRS+=3D $(kcm_dir) appl tools tests packages etc po
+
+if HEIMDAL_DOCUMENTATION
+SUBDIRS+=3D doc
+endif
+
+
=20
 ## ACLOCAL =3D @ACLOCAL@ -I cf
 ACLOCAL_AMFLAGS =3D -I cf
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	windows \
 	TODO \
 	LICENSE \
 	README \
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/Makefile.am.common
--- a/head/crypto/heimdal/Makefile.am.common	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/Makefile.am.common	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
 include $(top_srcdir)/cf/Makefile.am.common
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/Makefile.in
--- a/head/crypto/heimdal/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22497 2008-01-21 12:12:23Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -40,12 +42,13 @@
 DIST_COMMON =3D README $(am__configure_deps) $(srcdir)/Makefile.am \
 	$(srcdir)/Makefile.in $(top_srcdir)/Makefile.am.common \
 	$(top_srcdir)/cf/Makefile.am.common $(top_srcdir)/configure \
-	ChangeLog NEWS TODO compile config.guess config.sub install-sh \
-	ltmain.sh missing ylwrap
+	ChangeLog NEWS TODO compile config.guess config.sub depcomp \
+	install-sh ltmain.sh missing ylwrap
+ at HEIMDAL_DOCUMENTATION_TRUE@am__append_1 =3D doc
 subdir =3D .
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +63,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +77,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,7 +90,7 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 am__CONFIG_DISTCLEAN_FILES =3D config.status config.cache config.log \
@@ -92,8 +98,7 @@
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 RECURSIVE_TARGETS =3D all-recursive check-recursive dvi-recursive \
@@ -105,17 +110,45 @@
 	ps-recursive uninstall-recursive
 RECURSIVE_CLEAN_TARGETS =3D mostlyclean-recursive clean-recursive	\
   distclean-recursive maintainer-clean-recursive
+AM_RECURSIVE_TARGETS =3D $(RECURSIVE_TARGETS:-recursive=3D) \
+	$(RECURSIVE_CLEAN_TARGETS:-recursive=3D) tags TAGS ctags CTAGS \
+	distdir dist dist-all distcheck
 ETAGS =3D etags
 CTAGS =3D ctags
-DIST_SUBDIRS =3D include lib kuser kdc admin kadmin kpasswd kcm appl doc \
-	tools tests packages etc
+DIST_SUBDIRS =3D include base lib kuser kdc admin kadmin kpasswd kcm \
+	appl tools tests packages etc po doc
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 distdir =3D $(PACKAGE)-$(VERSION)
 top_distdir =3D $(distdir)
 am__remove_distdir =3D \
-  { test ! -d $(distdir) \
-    || { find $(distdir) -type d ! -perm -200 -exec chmod u+w {} ';' \
-         && rm -fr $(distdir); }; }
+  { test ! -d "$(distdir)" \
+    || { find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \
+         && rm -fr "$(distdir)"; }; }
+am__relativize =3D \
+  dir0=3D`pwd`; \
+  sed_first=3D's,^\([^/]*\)/.*$$,\1,'; \
+  sed_rest=3D's,^[^/]*/*,,'; \
+  sed_last=3D's,^.*/\([^/]*\)$$,\1,'; \
+  sed_butlast=3D's,/*[^/]*$$,,'; \
+  while test -n "$$dir1"; do \
+    first=3D`echo "$$dir1" | sed -e "$$sed_first"`; \
+    if test "$$first" !=3D "."; then \
+      if test "$$first" =3D ".."; then \
+        dir2=3D`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
+        dir0=3D`echo "$$dir0" | sed -e "$$sed_butlast"`; \
+      else \
+        first2=3D`echo "$$dir2" | sed -e "$$sed_first"`; \
+        if test "$$first2" =3D "$$first"; then \
+          dir2=3D`echo "$$dir2" | sed -e "$$sed_rest"`; \
+        else \
+          dir2=3D"../$$dir2"; \
+        fi; \
+        dir0=3D"$$dir0"/"$$first"; \
+      fi; \
+    fi; \
+    dir1=3D`echo "$$dir1" | sed -e "$$sed_rest"`; \
+  done; \
+  reldir=3D"$$dir2"
 DIST_ARCHIVES =3D $(distdir).tar.gz
 GZIP_ENV =3D --best
 distuninstallcheck_listfiles =3D find . -type f -print
@@ -124,49 +157,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -190,10 +232,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -210,6 +253,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -225,31 +270,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -264,10 +323,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -308,35 +369,42 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 @KCM_TRUE at kcm_dir =3D kcm
-SUBDIRS =3D include lib kuser kdc admin kadmin kpasswd $(kcm_dir) appl \
-	doc tools tests packages etc
+SUBDIRS =3D include base lib kuser kdc admin kadmin kpasswd $(kcm_dir) \
+	appl tools tests packages etc po $(am__append_1)
 ACLOCAL_AMFLAGS =3D -I cf
 EXTRA_DIST =3D \
+	NTMakefile \
+	windows \
 	TODO \
 	LICENSE \
 	README \
@@ -373,22 +441,22 @@
 all: all-recursive
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 am--refresh:
 	@:
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      echo ' cd $(srcdir) && $(AUTOMAKE) --foreign  --ignore-deps'; \
-	      cd $(srcdir) && $(AUTOMAKE) --foreign  --ignore-deps \
+	      echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \
+	      $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \
 		&& exit 0; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps Makefile'=
; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -404,9 +472,10 @@
 	$(SHELL) ./config.status --recheck
=20
 $(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)
-	cd $(srcdir) && $(AUTOCONF)
+	$(am__cd) $(srcdir) && $(AUTOCONF)
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
-	cd $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
+	$(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS)
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -415,7 +484,7 @@
 	-rm -rf .libs _libs
=20
 distclean-libtool:
-	-rm -f libtool
+	-rm -f libtool config.lt
=20
 # This directory's subdirectories are mostly independent; you can cd
 # into them and run `make' without going through this Makefile.
@@ -424,7 +493,7 @@
 #     (which will cause the Makefiles to be regenerated when you run `make=
');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -441,7 +510,7 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done; \
 	if test "$$dot_seen" =3D "no"; then \
@@ -449,7 +518,7 @@
 	fi; test -z "$$fail"
=20
 $(RECURSIVE_CLEAN_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -475,16 +544,16 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done && test -z "$$fail"
 tags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags);=
 \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 tags); \
 	done
 ctags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags)=
; \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 ctags); \
 	done
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
@@ -492,14 +561,14 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
 	  include_option=3D--etags-include; \
@@ -511,46 +580,50 @@
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test ! -f $$subdir/TAGS || \
-	      tags=3D"$$tags $$include_option=3D$$here/$$subdir/TAGS"; \
+	      set "$$@" "$$include_option=3D$$here/$$subdir/TAGS"; \
 	  fi; \
 	done; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
 	$(am__remove_distdir)
-	test -d $(distdir) || mkdir $(distdir)
+	test -d "$(distdir)" || mkdir "$(distdir)"
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -566,29 +639,44 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
-	list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test -d "$(distdir)/$$subdir" \
 	    || $(MKDIR_P) "$(distdir)/$$subdir" \
 	    || exit 1; \
-	    distdir=3D`$(am__cd) $(distdir) && pwd`; \
-	    top_distdir=3D`$(am__cd) $(top_distdir) && pwd`; \
-	    (cd $$subdir && \
+	  fi; \
+	done
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" =3D .; then :; else \
+	    dir1=3D$$subdir; dir2=3D"$(distdir)/$$subdir"; \
+	    $(am__relativize); \
+	    new_distdir=3D$$reldir; \
+	    dir1=3D$$subdir; dir2=3D"$(top_distdir)"; \
+	    $(am__relativize); \
+	    new_top_distdir=3D$$reldir; \
+	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir=3D"$$new_t=
op_distdir" distdir=3D"$$new_distdir" \\"; \
+	    echo "     am__remove_distdir=3D: am__skip_length_check=3D: am__skip_=
mode_fix=3D: distdir)"; \
+	    ($(am__cd) $$subdir && \
 	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir=3D"$$top_distdir" \
-	        distdir=3D"$$distdir/$$subdir" \
+	        top_distdir=3D"$$new_top_distdir" \
+	        distdir=3D"$$new_distdir" \
 		am__remove_distdir=3D: \
 		am__skip_length_check=3D: \
+		am__skip_mode_fix=3D: \
 	        distdir) \
 	      || exit 1; \
 	  fi; \
@@ -596,11 +684,13 @@
 	$(MAKE) $(AM_MAKEFLAGS) \
 	  top_distdir=3D"$(top_distdir)" distdir=3D"$(distdir)" \
 	  dist-hook
-	-find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \
+	-test -n "$(am__skip_mode_fix)" \
+	|| find "$(distdir)" -type d ! -perm -755 \
+		-exec chmod u+rwx,go+rx {} \; -o \
 	  ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
 	  ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
 	  ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \
-	|| chmod -R a+r $(distdir)
+	|| chmod -R a+r "$(distdir)"
 dist-gzip: distdir
 	tardir=3D$(distdir) && $(am__tar) | GZIP=3D$(GZIP_ENV) gzip -c >$(distdir=
).tar.gz
 	$(am__remove_distdir)
@@ -609,6 +699,14 @@
 	tardir=3D$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2
 	$(am__remove_distdir)
=20
+dist-lzma: distdir
+	tardir=3D$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma
+	$(am__remove_distdir)
+
+dist-xz: distdir
+	tardir=3D$(distdir) && $(am__tar) | xz -c >$(distdir).tar.xz
+	$(am__remove_distdir)
+
 dist-tarZ: distdir
 	tardir=3D$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
 	$(am__remove_distdir)
@@ -632,13 +730,17 @@
 distcheck: dist
 	case '$(DIST_ARCHIVES)' in \
 	*.tar.gz*) \
-	  GZIP=3D$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\
+	  GZIP=3D$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\
 	*.tar.bz2*) \
-	  bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\
+	  bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\
+	*.tar.lzma*) \
+	  lzma -dc $(distdir).tar.lzma | $(am__untar) ;;\
+	*.tar.xz*) \
+	  xz -dc $(distdir).tar.xz | $(am__untar) ;;\
 	*.tar.Z*) \
 	  uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
 	*.shar.gz*) \
-	  GZIP=3D$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\
+	  GZIP=3D$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\
 	*.zip*) \
 	  unzip $(distdir).zip ;;\
 	esac
@@ -646,9 +748,11 @@
 	mkdir $(distdir)/_build
 	mkdir $(distdir)/_inst
 	chmod a-w $(distdir)
+	test -d $(distdir)/_build || exit 0; \
 	dc_install_base=3D`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]=
:[\\/],/,'` \
 	  && dc_destdir=3D"$${TMPDIR-/tmp}/am-dc-$$$$/" \
-	  && cd $(distdir)/_build \
+	  && am__cwd=3D`pwd` \
+	  && $(am__cd) $(distdir)/_build \
 	  && ../configure --srcdir=3D.. --prefix=3D"$$dc_install_base" \
 	    $(DISTCHECK_CONFIGURE_FLAGS) \
 	  && $(MAKE) $(AM_MAKEFLAGS) \
@@ -670,13 +774,15 @@
 	  && rm -rf "$$dc_destdir" \
 	  && $(MAKE) $(AM_MAKEFLAGS) dist \
 	  && rm -rf $(DIST_ARCHIVES) \
-	  && $(MAKE) $(AM_MAKEFLAGS) distcleancheck
+	  && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \
+	  && cd "$$am__cwd" \
+	  || exit 1
 	$(am__remove_distdir)
 	@(echo "$(distdir) archives ready for distribution: "; \
 	  list=3D'$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
 	  sed -e 1h -e 1s/./=3D/g -e 1p -e 1x -e '$$p' -e '$$x'
 distuninstallcheck:
-	@cd $(distuninstallcheck_dir) \
+	@$(am__cd) '$(distuninstallcheck_dir)' \
 	&& test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \
 	   || { echo "ERROR: files left after uninstall:" ; \
 	        if test -n "$(DESTDIR)"; then \
@@ -719,6 +825,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -739,6 +846,8 @@
=20
 html: html-recursive
=20
+html-am:
+
 info: info-recursive
=20
 info-am:
@@ -746,23 +855,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-recursive
=20
-install-dvi: install-dvi-recursive
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-recursive
=20
+install-html-am:
+
 install-info: install-info-recursive
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-recursive
=20
+install-pdf-am:
+
 install-ps: install-ps-recursive
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-recursive
@@ -786,26 +903,27 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \
-	install-data-am install-exec-am install-strip uninstall-am
+.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) check-am \
+	ctags-recursive install-am install-data-am install-exec-am \
+	install-strip tags-recursive uninstall-am
=20
 .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
 	all all-am all-local am--refresh check check-am check-local \
 	clean clean-generic clean-libtool ctags ctags-recursive dist \
-	dist-all dist-bzip2 dist-gzip dist-hook dist-shar dist-tarZ \
-	dist-zip distcheck distclean distclean-generic \
-	distclean-libtool distclean-tags distcleancheck distdir \
-	distuninstallcheck dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am \
-	install-data-hook install-dvi install-dvi-am install-exec \
-	install-exec-am install-exec-hook install-html install-html-am \
-	install-info install-info-am install-man install-pdf \
-	install-pdf-am install-ps install-ps-am install-strip \
-	installcheck installcheck-am installdirs installdirs-am \
-	maintainer-clean maintainer-clean-generic mostlyclean \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags tags-recursive uninstall uninstall-am uninstall-hook
+	dist-all dist-bzip2 dist-gzip dist-hook dist-lzma dist-shar \
+	dist-tarZ dist-xz dist-zip distcheck distclean \
+	distclean-generic distclean-libtool distclean-tags \
+	distcleancheck distdir distuninstallcheck dvi dvi-am html \
+	html-am info info-am install install-am install-data \
+	install-data-am install-data-hook install-dvi install-dvi-am \
+	install-exec install-exec-am install-exec-hook install-html \
+	install-html-am install-info install-info-am install-man \
+	install-pdf install-pdf-am install-ps install-ps-am \
+	install-strip installcheck installcheck-am installdirs \
+	installdirs-am maintainer-clean maintainer-clean-generic \
+	mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \
+	ps ps-am tags tags-recursive uninstall uninstall-am \
+	uninstall-hook
=20
=20
 install-suid-programs:
@@ -876,6 +994,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -961,7 +1082,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -977,6 +1098,7 @@
=20
 print-distdir:
 	@echo $(distdir)
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/NEWS
--- a/head/crypto/heimdal/NEWS	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/NEWS	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,175 @@
+Release Notes - Heimdal - Version Heimdal 1.5.2
+
+ Security fixes
+ - CVE-2011-4862 Buffer overflow in libtelnet/encrypt.c in telnetd - escal=
ation of privilege
+ - Check that key types strictly match - denial of service
+
+Release Notes - Heimdal - Version Heimdal 1.5.1
+
+ Bug fixes
+ - Fix building on Solaris, requires c99
+ - Fix building on Windows
+ - Build system updates
+
+Release Notes - Heimdal - Version Heimdal 1.5
+
+New features
+
+ - Support GSS name extensions/attributes
+ - SHA512 support
+ - No Kerberos 4 support
+ - Basic support for MIT Admin protocol (SECGSS flavor)
+   in kadmind (extract keytab)
+ - Replace editline with libedit
+
+Release Notes - Heimdal - Version Heimdal 1.4
+
+ New features
+=20
+ - Support for reading MIT database file directly
+ - KCM is polished up and now used in production
+ - NTLM first class citizen, credentials stored in KCM
+ - Table driven ASN.1 compiler, smaller!, not enabled by default
+ - Native Windows client support
+
+Notes
+
+ - Disabled write support NDBM hdb backend (read still in there) since
+   it can't handle large records, please migrate to a diffrent backend
+   (like BDB4)
+
+Release Notes - Heimdal - Version Heimdal 1.3.3
+
+ Bug fixes
+ - Check the GSS-API checksum exists before trying to use it [CVE-2010-132=
1]
+ - Check NULL pointers before dereference them [kdc]
+
+Release Notes - Heimdal - Version Heimdal 1.3.2
+
+ Bug fixes
+
+ - Don't mix length when clearing hmac (could memset too much)
+ - More paranoid underrun checking when decrypting packets
+ - Check the password change requests and refuse to answer empty packets
+ - Build on OpenSolaris=20
+ - Renumber AD-SIGNED-TICKET since it was stolen from US
+ - Don't cache /dev/*random file descriptor, it doesn't get unloaded
+ - Make C++ safe
+ - Misc warnings
+
+Release Notes - Heimdal - Version Heimdal 1.3.1
+
+ Bug fixes
+
+ - Store KDC offset in credentials
+ - Many many more bug fixes
+
+Release Notes - Heimdal - Version Heimdal 1.3.1
+
+ New features
+
+ - Make work with OpenLDAPs krb5 overlay
+
+Release Notes - Heimdal - Version Heimdal 1.3
+
+ New features
+
+ - Partial support for MIT kadmind rpc protocol in kadmind
+ - Better support for finding keytab entries when using SPN aliases in the=
 KDC
+ - Support BER in ASN.1 library (needed for CMS)
+ - Support decryption in Keychain private keys
+ - Support for new sqlite based credential cache
+ - Try both KDC referals and the common DNS reverse lookup in GSS-API
+ - Fix the KCM to not leak resources on failure
+ - Add IPv6 support to iprop
+ - Support localization of error strings in
+   kinit/klist/kdestroy and Kerberos library
+ - Remove Kerberos 4 support in application (still in KDC)
+ - Deprecate DES
+ - Support i18n password in windows domains (using UTF-8)
+ - More complete API emulation of OpenSSL in hcrypto
+ - Support for ECDSA and ECDH when linking with OpenSSL
+
+ API changes
+
+ - Support for settin friendly name on credential caches
+ - Move to using doxygen to generate documentation.
+ - Sprinkling __attribute__((depricated)) for old function to be removed
+ - Support to export LAST-REQUST information in AS-REQ
+ - Support for client deferrals in in AS-REQ
+ - Add seek support for krb5_storage.
+ - Support for split AS-REQ, first step for IA-KERB
+ - Fix many memory leaks and bugs
+ - Improved regression test
+ - Support krb5_cccol
+ - Switch to krb5_set_error_message
+ - Support krb5_crypto_*_iov=09
+ - Switch to use EVP for most function
+ - Use SOCK_CLOEXEC and O_CLOEXEC (close on exec)
+ - Add support for GSS_C_DELEG_POLICY_FLAG
+ - Add krb5_cc_[gs]et_config to store data in the credential caches
+ - PTY testing application
+
+Bugfixes
+ - Make building on AIX6 possible.
+ - Bugfixes in LDAP KDC code to make it more stable
+ - Make ipropd-slave reconnect when master down gown
+
+
+Release Notes - Heimdal - Version Heimdal 1.2.1
+
+* Bug
+
+  [HEIMDAL-147] - Heimdal 1.2 not compiling on Solaris
+  [HEIMDAL-151] - Make canned tests work again after cert expired
+  [HEIMDAL-152] - iprop test: use full hostname to avoid realm
+                  resolving errors
+  [HEIMDAL-153] - ftp: Use the correct length for unmap, msync
+
+Release Notes - Heimdal - Version Heimdal 1.2
+
+* Bug
+
+  [HEIMDAL-10] - Follow-up on bug report for SEGFAULT in
+  		 gss_display_name/gss_export_name when using SPNEGO
+  [HEIMDAL-15] - Re: [Heimdal-bugs] potential bug in Heimdal 1.1
+  [HEIMDAL-17] - Remove support for depricated [libdefaults]capath
+  [HEIMDAL-52] - hdb overwrite aliases for db databases
+  [HEIMDAL-54] - Two issues which affect credentials delegation
+  [HEIMDAL-58] - sockbuf.c calls setsockopt with bad args
+  [HEIMDAL-62] - Fix printing of sig_atomic_t
+  [HEIMDAL-87] - heimdal 1.1 not building under cygwin in hcrypto
+  [HEIMDAL-105] - rcp: sync rcp with upstream bsd rcp codebase
+  [HEIMDAL-117] - Use libtool to detect symbol versioning (Debian Bug#4532=
41)
+
+* Improvement
+  [HEIMDAL-67] - Fix locking and store credential in atomic writes
+                 in the FILE credential cache
+  [HEIMDAL-106] - make compile on cygwin again
+  [HEIMDAL-107] - Replace old random key generation in des module
+                  and use it with RAND_ function instead
+  [HEIMDAL-115] - Better documentation and compatibility in hcrypto
+                  in regards to OpenSSL
+
+* New Feature
+  [HEIMDAL-3] - pkinit alg agility PRF test vectors
+  [HEIMDAL-14] - Add libwind to Heimdal
+  [HEIMDAL-16] - Use libwind in hx509
+  [HEIMDAL-55] - Add flag to krb5 to not add GSS-API INT|CONF to
+                 the negotiation
+  [HEIMDAL-74] - Add support to report extended error message back
+                 in AS-REQ to support windows clients
+  [HEIMDAL-116] - test pty based application (using rkpty)
+  [HEIMDAL-120] - Use new OpenLDAP API (older deprecated)
+
+* Task
+  [HEIMDAL-63] - Dont try key usage KRB5_KU_AP_REQ_AUTH for TGS-REQ.
+                 This drop compatibility with pre 0.3d KDCs.
+  [HEIMDAL-64] - kcm: first implementation of kcm-move-cache
+  [HEIMDAL-65] - Failed to compile with --disable-pk-init
+  [HEIMDAL-80] - verify that [VU#162289]: gcc silently discards some
+                 wraparound checks doesn't apply to Heimdal
+
 Changes in release 1.1
=20
  * Read-only PKCS11 provider built-in to hx509.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/README
--- a/head/crypto/heimdal/README	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/README	Tue Apr 17 11:51:51 2012 +0300
@@ -1,16 +1,15 @@
-$Id: README 8839 2000-07-27 02:33:54Z assar $
=20
 Heimdal is a Kerberos 5 implementation.
=20
-Please see the manual in doc, by default installed in
-/usr/heimdal/info/heimdal.info for information on how to install.
-There are also briefer man pages for most of the commands.
+For information how to install see <http://www.h5l.org/compile.html>.
+
+There are briefer man pages for most of the commands.
=20
 Bug reports and bugs are appreciated, see more under Bug reports in
-the manual on how we prefer them.
+the manual on how we prefer them: <heimdal-bugs at h5l.org>.
=20
 For more information see the web-page at
-<http://www.pdc.kth.se/heimdal/> or the mailing lists:
+<http://www.h5l.org/> or the mailing lists:
=20
 heimdal-announce at sics.se	low-volume announcement
 heimdal-discuss at sics.se		high-volume discussion
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/acinclude.m4
--- a/head/crypto/heimdal/acinclude.m4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/acinclude.m4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,4 @@
-dnl $Id: acinclude.m4 13337 2004-02-12 14:19:16Z lha $
-dnl $FreeBSD$
+dnl $Id$
 dnl
 dnl Only put things that for some reason can't live in the `cf'
 dnl directory in this file.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/aclocal.m4
--- a/head/crypto/heimdal/aclocal.m4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/aclocal.m4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-# generated automatically by aclocal 1.10 -*- Autoconf -*-
+# generated automatically by aclocal 1.11.1 -*- Autoconf -*-
=20
 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
-# 2005, 2006  Free Software Foundation, Inc.
+# 2005, 2006, 2007, 2008, 2009  Free Software Foundation, Inc.
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -11,6389 +11,15 @@
 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 # PARTICULAR PURPOSE.
=20
-m4_if(m4_PACKAGE_VERSION, [2.61],,
-[m4_fatal([this file was generated for autoconf 2.61.
-You have another version of autoconf.  If you want to use that,
-you should regenerate the build system entirely.], [63])])
+m4_ifndef([AC_AUTOCONF_VERSION],
+  [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
+m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.65],,
+[m4_warning([this file was generated for autoconf 2.65.
+You have another version of autoconf.  It may work, but is not guaranteed =
to.
+If you have problems, you may need to regenerate the build system entirely.
+To do so, use the procedure documented by the package, typically `autoreco=
nf'.])])
=20
-# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*-
-
-# serial 48 AC_PROG_LIBTOOL
-
-
-# AC_PROVIDE_IFELSE(MACRO-NAME, IF-PROVIDED, IF-NOT-PROVIDED)
-# -----------------------------------------------------------
-# If this macro is not defined by Autoconf, define it here.
-m4_ifdef([AC_PROVIDE_IFELSE],
-         [],
-         [m4_define([AC_PROVIDE_IFELSE],
-	         [m4_ifdef([AC_PROVIDE_$1],
-		           [$2], [$3])])])
-
-
-# AC_PROG_LIBTOOL
-# ---------------
-AC_DEFUN([AC_PROG_LIBTOOL],
-[AC_REQUIRE([_AC_PROG_LIBTOOL])dnl
-dnl If AC_PROG_CXX has already been expanded, run AC_LIBTOOL_CXX
-dnl immediately, otherwise, hook it in at the end of AC_PROG_CXX.
-  AC_PROVIDE_IFELSE([AC_PROG_CXX],
-    [AC_LIBTOOL_CXX],
-    [define([AC_PROG_CXX], defn([AC_PROG_CXX])[AC_LIBTOOL_CXX
-  ])])
-dnl And a similar setup for Fortran 77 support
-  AC_PROVIDE_IFELSE([AC_PROG_F77],
-    [AC_LIBTOOL_F77],
-    [define([AC_PROG_F77], defn([AC_PROG_F77])[AC_LIBTOOL_F77
-])])
-
-dnl Quote A][M_PROG_GCJ so that aclocal doesn't bring it in needlessly.
-dnl If either AC_PROG_GCJ or A][M_PROG_GCJ have already been expanded, run
-dnl AC_LIBTOOL_GCJ immediately, otherwise, hook it in at the end of both.
-  AC_PROVIDE_IFELSE([AC_PROG_GCJ],
-    [AC_LIBTOOL_GCJ],
-    [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],
-      [AC_LIBTOOL_GCJ],
-      [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],
-	[AC_LIBTOOL_GCJ],
-      [ifdef([AC_PROG_GCJ],
-	     [define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])
-       ifdef([A][M_PROG_GCJ],
-	     [define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[AC_LIBTOOL_GCJ])])
-       ifdef([LT_AC_PROG_GCJ],
-	     [define([LT_AC_PROG_GCJ],
-		defn([LT_AC_PROG_GCJ])[AC_LIBTOOL_GCJ])])])])
-])])# AC_PROG_LIBTOOL
-
-
-# _AC_PROG_LIBTOOL
-# ----------------
-AC_DEFUN([_AC_PROG_LIBTOOL],
-[AC_REQUIRE([AC_LIBTOOL_SETUP])dnl
-AC_BEFORE([$0],[AC_LIBTOOL_CXX])dnl
-AC_BEFORE([$0],[AC_LIBTOOL_F77])dnl
-AC_BEFORE([$0],[AC_LIBTOOL_GCJ])dnl
-
-# This can be used to rebuild libtool when needed
-LIBTOOL_DEPS=3D"$ac_aux_dir/ltmain.sh"
-
-# Always use our own libtool.
-LIBTOOL=3D'$(SHELL) $(top_builddir)/libtool'
-AC_SUBST(LIBTOOL)dnl
-
-# Prevent multiple expansion
-define([AC_PROG_LIBTOOL], [])
-])# _AC_PROG_LIBTOOL
-
-
-# AC_LIBTOOL_SETUP
-# ----------------
-AC_DEFUN([AC_LIBTOOL_SETUP],
-[AC_PREREQ(2.50)dnl
-AC_REQUIRE([AC_ENABLE_SHARED])dnl
-AC_REQUIRE([AC_ENABLE_STATIC])dnl
-AC_REQUIRE([AC_ENABLE_FAST_INSTALL])dnl
-AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([AC_PROG_LD])dnl
-AC_REQUIRE([AC_PROG_LD_RELOAD_FLAG])dnl
-AC_REQUIRE([AC_PROG_NM])dnl
-
-AC_REQUIRE([AC_PROG_LN_S])dnl
-AC_REQUIRE([AC_DEPLIBS_CHECK_METHOD])dnl
-# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compiler=
s!
-AC_REQUIRE([AC_OBJEXT])dnl
-AC_REQUIRE([AC_EXEEXT])dnl
-dnl
-
-AC_LIBTOOL_SYS_MAX_CMD_LEN
-AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
-AC_LIBTOOL_OBJDIR
-
-AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
-_LT_AC_PROG_ECHO_BACKSLASH
-
-case $host_os in
-aix3*)
-  # AIX sometimes has problems with the GCC collect2 program.  For some
-  # reason, if we set the COLLECT_NAMES environment variable, the problems
-  # vanish in a puff of smoke.
-  if test "X${COLLECT_NAMES+set}" !=3D Xset; then
-    COLLECT_NAMES=3D
-    export COLLECT_NAMES
-  fi
-  ;;
-esac
-
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed=3D'sed -e 1s/^X//'
-[sed_quote_subst=3D's/\([\\"\\`$\\\\]\)/\\\1/g']
-
-# Same as above, but do not quote variable references.
-[double_quote_subst=3D's/\([\\"\\`\\\\]\)/\\\1/g']
-
-# Sed substitution to delay expansion of an escaped shell variable in a
-# double_quote_subst'ed string.
-delay_variable_subst=3D's/\\\\\\\\\\\$/\\\\\\$/g'
-
-# Sed substitution to avoid accidental globbing in evaled expressions
-no_glob_subst=3D's/\*/\\\*/g'
-
-# Constants:
-rm=3D"rm -f"
-
-# Global variables:
-default_ofile=3Dlibtool
-can_build_shared=3Dyes
-
-# All known linkers require a `.a' archive for static linking (except MSVC,
-# which needs '.lib').
-libext=3Da
-ltmain=3D"$ac_aux_dir/ltmain.sh"
-ofile=3D"$default_ofile"
-with_gnu_ld=3D"$lt_cv_prog_gnu_ld"
-
-AC_CHECK_TOOL(AR, ar, false)
-AC_CHECK_TOOL(RANLIB, ranlib, :)
-AC_CHECK_TOOL(STRIP, strip, :)
-
-old_CC=3D"$CC"
-old_CFLAGS=3D"$CFLAGS"
-
-# Set sane defaults for various variables
-test -z "$AR" && AR=3Dar
-test -z "$AR_FLAGS" && AR_FLAGS=3Dcru
-test -z "$AS" && AS=3Das
-test -z "$CC" && CC=3Dcc
-test -z "$LTCC" && LTCC=3D$CC
-test -z "$LTCFLAGS" && LTCFLAGS=3D$CFLAGS
-test -z "$DLLTOOL" && DLLTOOL=3Ddlltool
-test -z "$LD" && LD=3Dld
-test -z "$LN_S" && LN_S=3D"ln -s"
-test -z "$MAGIC_CMD" && MAGIC_CMD=3Dfile
-test -z "$NM" && NM=3Dnm
-test -z "$SED" && SED=3Dsed
-test -z "$OBJDUMP" && OBJDUMP=3Dobjdump
-test -z "$RANLIB" && RANLIB=3D:
-test -z "$STRIP" && STRIP=3D:
-test -z "$ac_objext" && ac_objext=3Do
-
-# Determine commands to create old-style static archives.
-old_archive_cmds=3D'$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs'
-old_postinstall_cmds=3D'chmod 644 $oldlib'
-old_postuninstall_cmds=3D
-
-if test -n "$RANLIB"; then
-  case $host_os in
-  openbsd*)
-    old_postinstall_cmds=3D"$old_postinstall_cmds~\$RANLIB -t \$oldlib"
-    ;;
-  *)
-    old_postinstall_cmds=3D"$old_postinstall_cmds~\$RANLIB \$oldlib"
-    ;;
-  esac
-  old_archive_cmds=3D"$old_archive_cmds~\$RANLIB \$oldlib"
-fi
-
-_LT_CC_BASENAME([$compiler])
-
-# Only perform the check for file, if the check method requires it
-case $deplibs_check_method in
-file_magic*)
-  if test "$file_magic_cmd" =3D '$MAGIC_CMD'; then
-    AC_PATH_MAGIC
-  fi
-  ;;
-esac
-
-AC_PROVIDE_IFELSE([AC_LIBTOOL_DLOPEN], enable_dlopen=3Dyes, enable_dlopen=
=3Dno)
-AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL],
-enable_win32_dll=3Dyes, enable_win32_dll=3Dno)
-
-AC_ARG_ENABLE([libtool-lock],
-    [AC_HELP_STRING([--disable-libtool-lock],
-	[avoid locking (might break parallel builds)])])
-test "x$enable_libtool_lock" !=3D xno && enable_libtool_lock=3Dyes
-
-AC_ARG_WITH([pic],
-    [AC_HELP_STRING([--with-pic],
-	[try to use only PIC/non-PIC objects @<:@default=3Duse both@:>@])],
-    [pic_mode=3D"$withval"],
-    [pic_mode=3Ddefault])
-test -z "$pic_mode" && pic_mode=3Ddefault
-
-# Use C for the default configuration in the libtool script
-tagname=3D
-AC_LIBTOOL_LANG_C_CONFIG
-_LT_AC_TAGCONFIG
-])# AC_LIBTOOL_SETUP
-
-
-# _LT_AC_SYS_COMPILER
-# -------------------
-AC_DEFUN([_LT_AC_SYS_COMPILER],
-[AC_REQUIRE([AC_PROG_CC])dnl
-
-# If no C compiler was specified, use CC.
-LTCC=3D${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=3D${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=3D$CC
-])# _LT_AC_SYS_COMPILER
-
-
-# _LT_CC_BASENAME(CC)
-# -------------------
-# Calculate cc_basename.  Skip known compiler wrappers and cross-prefix.
-AC_DEFUN([_LT_CC_BASENAME],
-[for cc_temp in $1""; do
-  case $cc_temp in
-    compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;;
-    distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
-])
-
-
-# _LT_COMPILER_BOILERPLATE
-# ------------------------
-# Check for compiler boilerplate output or warnings with
-# the simple compiler test code.
-AC_DEFUN([_LT_COMPILER_BOILERPLATE],
-[ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=3D`cat conftest.err`
-$rm conftest*
-])# _LT_COMPILER_BOILERPLATE
-
-
-# _LT_LINKER_BOILERPLATE
-# ----------------------
-# Check for linker boilerplate output or warnings with
-# the simple link test code.
-AC_DEFUN([_LT_LINKER_BOILERPLATE],
-[ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=3D`cat conftest.err`
-$rm conftest*
-])# _LT_LINKER_BOILERPLATE
-
-
-# _LT_AC_SYS_LIBPATH_AIX
-# ----------------------
-# Links a minimal program and checks the executable
-# for the system default hardcoded library path. In most cases,
-# this is /usr/lib:/lib, but when the MPI compilers are used
-# the location of the communication and MPI libs are included too.
-# If we don't find anything, use the default library path according
-# to the aix ld manual.
-AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX],
-[AC_LINK_IFELSE(AC_LANG_PROGRAM,[
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi],[])
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-])# _LT_AC_SYS_LIBPATH_AIX
-
-
-# _LT_AC_SHELL_INIT(ARG)
-# ----------------------
-AC_DEFUN([_LT_AC_SHELL_INIT],
-[ifdef([AC_DIVERSION_NOTICE],
-	     [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)],
-	 [AC_DIVERT_PUSH(NOTICE)])
-$1
-AC_DIVERT_POP
-])# _LT_AC_SHELL_INIT
-
-
-# _LT_AC_PROG_ECHO_BACKSLASH
-# --------------------------
-# Add some code to the start of the generated configure script which
-# will find an echo command which doesn't interpret backslashes.
-AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH],
-[_LT_AC_SHELL_INIT([
-# Check that we are running under the correct shell.
-SHELL=3D${CONFIG_SHELL-/bin/sh}
-
-case X$ECHO in
-X*--fallback-echo)
-  # Remove one level of quotation (which was required for Make).
-  ECHO=3D`echo "$ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','`
-  ;;
-esac
-
-echo=3D${ECHO-echo}
-if test "X[$]1" =3D X--no-reexec; then
-  # Discard the --no-reexec flag, and continue.
-  shift
-elif test "X[$]1" =3D X--fallback-echo; then
-  # Avoid inline document here, it may be left over
-  :
-elif test "X`($echo '\t') 2>/dev/null`" =3D 'X\t' ; then
-  # Yippee, $echo works!
-  :
-else
-  # Restart under the correct shell.
-  exec $SHELL "[$]0" --no-reexec ${1+"[$]@"}
-fi
-
-if test "X[$]1" =3D X--fallback-echo; then
-  # used as fallback echo
-  shift
-  cat <<EOF
-[$]*
-EOF
-  exit 0
-fi
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-if test -z "$ECHO"; then
-if test "X${echo_test_string+set}" !=3D Xset; then
-# find a string as large as possible, as long as the shell can cope with it
-  for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[=
$]0"' 'echo test'; do
-    # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
-    if (echo_test_string=3D`eval $cmd`) 2>/dev/null &&
-       echo_test_string=3D`eval $cmd` &&
-       (test "X$echo_test_string" =3D "X$echo_test_string") 2>/dev/null
-    then
-      break
-    fi
-  done
-fi
-
-if test "X`($echo '\t') 2>/dev/null`" =3D 'X\t' &&
-   echo_testing_string=3D`($echo "$echo_test_string") 2>/dev/null` &&
-   test "X$echo_testing_string" =3D "X$echo_test_string"; then
-  :
-else
-  # The Solaris, AIX, and Digital Unix default echo programs unquote
-  # backslashes.  This makes it impossible to quote backslashes using
-  #   echo "$something" | sed 's/\\/\\\\/g'
-  #
-  # So, first we look for a working echo in the user's PATH.
-
-  lt_save_ifs=3D"$IFS"; IFS=3D$PATH_SEPARATOR
-  for dir in $PATH /usr/ucb; do
-    IFS=3D"$lt_save_ifs"
-    if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
-       test "X`($dir/echo '\t') 2>/dev/null`" =3D 'X\t' &&
-       echo_testing_string=3D`($dir/echo "$echo_test_string") 2>/dev/null`=
 &&
-       test "X$echo_testing_string" =3D "X$echo_test_string"; then
-      echo=3D"$dir/echo"
-      break
-    fi
-  done
-  IFS=3D"$lt_save_ifs"
-
-  if test "X$echo" =3D Xecho; then
-    # We didn't find a better echo, so look for alternatives.
-    if test "X`(print -r '\t') 2>/dev/null`" =3D 'X\t' &&
-       echo_testing_string=3D`(print -r "$echo_test_string") 2>/dev/null` =
&&
-       test "X$echo_testing_string" =3D "X$echo_test_string"; then
-      # This shell has a builtin print -r that does the trick.
-      echo=3D'print -r'
-    elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) &&
-	 test "X$CONFIG_SHELL" !=3D X/bin/ksh; then
-      # If we have ksh, try running configure again with it.
-      ORIGINAL_CONFIG_SHELL=3D${CONFIG_SHELL-/bin/sh}
-      export ORIGINAL_CONFIG_SHELL
-      CONFIG_SHELL=3D/bin/ksh
-      export CONFIG_SHELL
-      exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"}
-    else
-      # Try using printf.
-      echo=3D'printf %s\n'
-      if test "X`($echo '\t') 2>/dev/null`" =3D 'X\t' &&
-	 echo_testing_string=3D`($echo "$echo_test_string") 2>/dev/null` &&
-	 test "X$echo_testing_string" =3D "X$echo_test_string"; then
-	# Cool, printf works
-	:
-      elif echo_testing_string=3D`($ORIGINAL_CONFIG_SHELL "[$]0" --fallbac=
k-echo '\t') 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D 'X\t' &&
-	   echo_testing_string=3D`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo =
"$echo_test_string") 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D "X$echo_test_string"; then
-	CONFIG_SHELL=3D$ORIGINAL_CONFIG_SHELL
-	export CONFIG_SHELL
-	SHELL=3D"$CONFIG_SHELL"
-	export SHELL
-	echo=3D"$CONFIG_SHELL [$]0 --fallback-echo"
-      elif echo_testing_string=3D`($CONFIG_SHELL "[$]0" --fallback-echo '\=
t') 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D 'X\t' &&
-	   echo_testing_string=3D`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_te=
st_string") 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D "X$echo_test_string"; then
-	echo=3D"$CONFIG_SHELL [$]0 --fallback-echo"
-      else
-	# maybe with a smaller string...
-	prev=3D:
-
-	for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' =
'sed 50q "[$]0"'; do
-	  if (test "X$echo_test_string" =3D "X`eval $cmd`") 2>/dev/null
-	  then
-	    break
-	  fi
-	  prev=3D"$cmd"
-	done
-
-	if test "$prev" !=3D 'sed 50q "[$]0"'; then
-	  echo_test_string=3D`eval $prev`
-	  export echo_test_string
-	  exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"}
-	else
-	  # Oops.  We lost completely, so just stick with echo.
-	  echo=3Decho
-	fi
-      fi
-    fi
-  fi
-fi
-fi
-
-# Copy echo and quote the copy suitably for passing to libtool from
-# the Makefile, instead of quoting the original, which is used later.
-ECHO=3D$echo
-if test "X$ECHO" =3D "X$CONFIG_SHELL [$]0 --fallback-echo"; then
-   ECHO=3D"$CONFIG_SHELL \\\$\[$]0 --fallback-echo"
-fi
-
-AC_SUBST(ECHO)
-])])# _LT_AC_PROG_ECHO_BACKSLASH
-
-
-# _LT_AC_LOCK
-# -----------
-AC_DEFUN([_LT_AC_LOCK],
-[AC_ARG_ENABLE([libtool-lock],
-    [AC_HELP_STRING([--disable-libtool-lock],
-	[avoid locking (might break parallel builds)])])
-test "x$enable_libtool_lock" !=3D xno && enable_libtool_lock=3Dyes
-
-# Some flags need to be propagated to the compiler or linker for good
-# libtool support.
-case $host in
-ia64-*-hpux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.$ac_objext` in
-    *ELF-32*)
-      HPUX_IA64_MODE=3D"32"
-      ;;
-    *ELF-64*)
-      HPUX_IA64_MODE=3D"64"
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-*-*-irix6*)
-  # Find out which ABI we are using.
-  echo '[#]line __oline__ "configure"' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-   if test "$lt_cv_prog_gnu_ld" =3D yes; then
-    case `/usr/bin/file conftest.$ac_objext` in
-    *32-bit*)
-      LD=3D"${LD-ld} -melf32bsmip"
-      ;;
-    *N32*)
-      LD=3D"${LD-ld} -melf32bmipn32"
-      ;;
-    *64-bit*)
-      LD=3D"${LD-ld} -melf64bmip"
-      ;;
-    esac
-   else
-    case `/usr/bin/file conftest.$ac_objext` in
-    *32-bit*)
-      LD=3D"${LD-ld} -32"
-      ;;
-    *N32*)
-      LD=3D"${LD-ld} -n32"
-      ;;
-    *64-bit*)
-      LD=3D"${LD-ld} -64"
-      ;;
-    esac
-   fi
-  fi
-  rm -rf conftest*
-  ;;
-
-x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-    *32-bit*)
-      case $host in
-        x86_64-*linux*)
-          LD=3D"${LD-ld} -m elf_i386"
-          ;;
-        ppc64-*linux*|powerpc64-*linux*)
-          LD=3D"${LD-ld} -m elf32ppclinux"
-          ;;
-        s390x-*linux*)
-          LD=3D"${LD-ld} -m elf_s390"
-          ;;
-        sparc64-*linux*)
-          LD=3D"${LD-ld} -m elf32_sparc"
-          ;;
-      esac
-      ;;
-    *64-bit*)
-      case $host in
-        x86_64-*linux*)
-          LD=3D"${LD-ld} -m elf_x86_64"
-          ;;
-        ppc*-*linux*|powerpc*-*linux*)
-          LD=3D"${LD-ld} -m elf64ppc"
-          ;;
-        s390*-*linux*)
-          LD=3D"${LD-ld} -m elf64_s390"
-          ;;
-        sparc*-*linux*)
-          LD=3D"${LD-ld} -m elf64_sparc"
-          ;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-*-*-sco3.2v5*)
-  # On SCO OpenServer 5, we need -belf to get full-featured binaries.
-  SAVE_CFLAGS=3D"$CFLAGS"
-  CFLAGS=3D"$CFLAGS -belf"
-  AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf,
-    [AC_LANG_PUSH(C)
-     AC_TRY_LINK([],[],[lt_cv_cc_needs_belf=3Dyes],[lt_cv_cc_needs_belf=3D=
no])
-     AC_LANG_POP])
-  if test x"$lt_cv_cc_needs_belf" !=3D x"yes"; then
-    # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
-    CFLAGS=3D"$SAVE_CFLAGS"
-  fi
-  ;;
-sparc*-*solaris*)
-  # Find out which ABI we are using.
-  echo 'int i;' > conftest.$ac_ext
-  if AC_TRY_EVAL(ac_compile); then
-    case `/usr/bin/file conftest.o` in
-    *64-bit*)
-      case $lt_cv_prog_gnu_ld in
-      yes*) LD=3D"${LD-ld} -m elf64_sparc" ;;
-      *)    LD=3D"${LD-ld} -64" ;;
-      esac
-      ;;
-    esac
-  fi
-  rm -rf conftest*
-  ;;
-
-AC_PROVIDE_IFELSE([AC_LIBTOOL_WIN32_DLL],
-[*-*-cygwin* | *-*-mingw* | *-*-pw32*)
-  AC_CHECK_TOOL(DLLTOOL, dlltool, false)
-  AC_CHECK_TOOL(AS, as, false)
-  AC_CHECK_TOOL(OBJDUMP, objdump, false)
-  ;;
-  ])
-esac
-
-need_locks=3D"$enable_libtool_lock"
-
-])# _LT_AC_LOCK
-
-
-# AC_LIBTOOL_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#		[OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE])
-# ----------------------------------------------------------------
-# Check whether the given compiler option works
-AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION],
-[AC_REQUIRE([LT_AC_PROG_SED])
-AC_CACHE_CHECK([$1], [$2],
-  [$2=3Dno
-  ifelse([$4], , [ac_outfile=3Dconftest.$ac_objext], [ac_outfile=3D$4])
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag=3D"$3"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=3D$?
-   cat conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:__oline__: \$? =3D $ac_status" >&AS_MESSAGE_LOG_FD
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/nul=
l; then
-       $2=3Dyes
-     fi
-   fi
-   $rm conftest*
-])
-
-if test x"[$]$2" =3D xyes; then
-    ifelse([$5], , :, [$5])
-else
-    ifelse([$6], , :, [$6])
-fi
-])# AC_LIBTOOL_COMPILER_OPTION
-
-
-# AC_LIBTOOL_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS,
-#                          [ACTION-SUCCESS], [ACTION-FAILURE])
-# ------------------------------------------------------------
-# Check whether the given compiler option works
-AC_DEFUN([AC_LIBTOOL_LINKER_OPTION],
-[AC_CACHE_CHECK([$1], [$2],
-  [$2=3Dno
-   save_LDFLAGS=3D"$LDFLAGS"
-   LDFLAGS=3D"$LDFLAGS $3"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&AS_MESSAGE_LOG_FD
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         $2=3Dyes
-       fi
-     else
-       $2=3Dyes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS=3D"$save_LDFLAGS"
-])
-
-if test x"[$]$2" =3D xyes; then
-    ifelse([$4], , :, [$4])
-else
-    ifelse([$5], , :, [$5])
-fi
-])# AC_LIBTOOL_LINKER_OPTION
-
-
-# AC_LIBTOOL_SYS_MAX_CMD_LEN
-# --------------------------
-AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN],
-[# find the maximum length of command line arguments
-AC_MSG_CHECKING([the maximum length of command line arguments])
-AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl
-  i=3D0
-  teststring=3D"ABCD"
-
-  case $build_os in
-  msdosdjgpp*)
-    # On DJGPP, this test can blow up pretty badly due to problems in libc
-    # (any single argument exceeding 2000 bytes causes a buffer overrun
-    # during glob expansion).  Even if it were fixed, the result of this
-    # check would be larger than it should be.
-    lt_cv_sys_max_cmd_len=3D12288;    # 12K is about right
-    ;;
-
-  gnu*)
-    # Under GNU Hurd, this test is not required because there is
-    # no limit to the length of command line arguments.
-    # Libtool will interpret -1 as no limit whatsoever
-    lt_cv_sys_max_cmd_len=3D-1;
-    ;;
-
-  cygwin* | mingw*)
-    # On Win9x/ME, this test blows up -- it succeeds, but takes
-    # about 5 minutes as the teststring grows exponentially.
-    # Worse, since 9x/ME are not pre-emptively multitasking,
-    # you end up with a "frozen" computer, even though with patience
-    # the test eventually succeeds (with a max line length of 256k).
-    # Instead, let's just punt: use the minimum linelength reported by
-    # all of the supported platforms: 8192 (on NT/2K/XP).
-    lt_cv_sys_max_cmd_len=3D8192;
-    ;;
-
-  amigaos*)
-    # On AmigaOS with pdksh, this test takes hours, literally.
-    # So we just punt and use a minimum line length of 8192.
-    lt_cv_sys_max_cmd_len=3D8192;
-    ;;
-
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
-    # This has been around since 386BSD, at least.  Likely further.
-    if test -x /sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=3D`/sbin/sysctl -n kern.argmax`
-    elif test -x /usr/sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=3D`/usr/sbin/sysctl -n kern.argmax`
-    else
-      lt_cv_sys_max_cmd_len=3D65536	# usable default for all BSDs
-    fi
-    # And add a safety zone
-    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BS=
D)
-    lt_cv_sys_max_cmd_len=3D196608
-    ;;
-
-  osf*)
-    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running conf=
igure
-    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
-    # nice to cause kernel panics so lets avoid the loop below.
-    # First set a reasonable default.
-    lt_cv_sys_max_cmd_len=3D16384
-    #
-    if test -x /sbin/sysconfig; then
-      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
-        *1*) lt_cv_sys_max_cmd_len=3D-1 ;;
-      esac
-    fi
-    ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=3D102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=3D`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=3D`echo $kargmax | sed 's/.*[[ 	]]//'`
-    else
-      lt_cv_sys_max_cmd_len=3D32768
-    fi
-    ;;
-  *)
-    # If test is not a shell built-in, we'll probably end up computing a
-    # maximum length that is only half of the actual maximum length, but
-    # we can't tell.
-    SHELL=3D${SHELL-${CONFIG_SHELL-/bin/sh}}
-    while (test "X"`$SHELL [$]0 --fallback-echo "X$teststring" 2>/dev/null=
` \
-	       =3D "XX$teststring") >/dev/null 2>&1 &&
-	    new_result=3D`expr "X$teststring" : ".*" 2>&1` &&
-	    lt_cv_sys_max_cmd_len=3D$new_result &&
-	    test $i !=3D 17 # 1/2 MB should be enough
-    do
-      i=3D`expr $i + 1`
-      teststring=3D$teststring$teststring
-    done
-    teststring=3D
-    # Add a significant safety factor because C++ compilers can tack on ma=
ssive
-    # amounts of additional arguments before passing them to the linker.
-    # It appears as though 1/2 is a usable value.
-    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \/ 2`
-    ;;
-  esac
-])
-if test -n $lt_cv_sys_max_cmd_len ; then
-  AC_MSG_RESULT($lt_cv_sys_max_cmd_len)
-else
-  AC_MSG_RESULT(none)
-fi
-])# AC_LIBTOOL_SYS_MAX_CMD_LEN
-
-
-# _LT_AC_CHECK_DLFCN
-# ------------------
-AC_DEFUN([_LT_AC_CHECK_DLFCN],
-[AC_CHECK_HEADERS(dlfcn.h)dnl
-])# _LT_AC_CHECK_DLFCN
-
-
-# _LT_AC_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE,
-#                           ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING)
-# ---------------------------------------------------------------------
-AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF],
-[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
-if test "$cross_compiling" =3D yes; then :
-  [$4]
-else
-  lt_dlunknown=3D0; lt_dlno_uscore=3D1; lt_dlneed_uscore=3D2
-  lt_status=3D$lt_dlunknown
-  cat > conftest.$ac_ext <<EOF
-[#line __oline__ "configure"
-#include "confdefs.h"
-
-#if HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-
-#include <stdio.h>
-
-#ifdef RTLD_GLOBAL
-#  define LT_DLGLOBAL		RTLD_GLOBAL
-#else
-#  ifdef DL_GLOBAL
-#    define LT_DLGLOBAL		DL_GLOBAL
-#  else
-#    define LT_DLGLOBAL		0
-#  endif
-#endif
-
-/* We may have to define LT_DLLAZY_OR_NOW in the command line if we
-   find out it does not work in some platform. */
-#ifndef LT_DLLAZY_OR_NOW
-#  ifdef RTLD_LAZY
-#    define LT_DLLAZY_OR_NOW		RTLD_LAZY
-#  else
-#    ifdef DL_LAZY
-#      define LT_DLLAZY_OR_NOW		DL_LAZY
-#    else
-#      ifdef RTLD_NOW
-#        define LT_DLLAZY_OR_NOW	RTLD_NOW
-#      else
-#        ifdef DL_NOW
-#          define LT_DLLAZY_OR_NOW	DL_NOW
-#        else
-#          define LT_DLLAZY_OR_NOW	0
-#        endif
-#      endif
-#    endif
-#  endif
-#endif
-
-#ifdef __cplusplus
-extern "C" void exit (int);
-#endif
-
-void fnord() { int i=3D42;}
-int main ()
-{
-  void *self =3D dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
-  int status =3D $lt_dlunknown;
-
-  if (self)
-    {
-      if (dlsym (self,"fnord"))       status =3D $lt_dlno_uscore;
-      else if (dlsym( self,"_fnord")) status =3D $lt_dlneed_uscore;
-      /* dlclose (self); */
-    }
-  else
-    puts (dlerror ());
-
-    exit (status);
-}]
-EOF
-  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then
-    (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null
-    lt_status=3D$?
-    case x$lt_status in
-      x$lt_dlno_uscore) $1 ;;
-      x$lt_dlneed_uscore) $2 ;;
-      x$lt_dlunknown|x*) $3 ;;
-    esac
-  else :
-    # compilation failed
-    $3
-  fi
-fi
-rm -fr conftest*
-])# _LT_AC_TRY_DLOPEN_SELF
-
-
-# AC_LIBTOOL_DLOPEN_SELF
-# ----------------------
-AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF],
-[AC_REQUIRE([_LT_AC_CHECK_DLFCN])dnl
-if test "x$enable_dlopen" !=3D xyes; then
-  enable_dlopen=3Dunknown
-  enable_dlopen_self=3Dunknown
-  enable_dlopen_self_static=3Dunknown
-else
-  lt_cv_dlopen=3Dno
-  lt_cv_dlopen_libs=3D
-
-  case $host_os in
-  beos*)
-    lt_cv_dlopen=3D"load_add_on"
-    lt_cv_dlopen_libs=3D
-    lt_cv_dlopen_self=3Dyes
-    ;;
-
-  mingw* | pw32*)
-    lt_cv_dlopen=3D"LoadLibrary"
-    lt_cv_dlopen_libs=3D
-   ;;
-
-  cygwin*)
-    lt_cv_dlopen=3D"dlopen"
-    lt_cv_dlopen_libs=3D
-   ;;
-
-  darwin*)
-  # if libdl is installed we need to link against it
-    AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-ldl"],[
-    lt_cv_dlopen=3D"dyld"
-    lt_cv_dlopen_libs=3D
-    lt_cv_dlopen_self=3Dyes
-    ])
-   ;;
-
-  *)
-    AC_CHECK_FUNC([shl_load],
-	  [lt_cv_dlopen=3D"shl_load"],
-      [AC_CHECK_LIB([dld], [shl_load],
-	    [lt_cv_dlopen=3D"shl_load" lt_cv_dlopen_libs=3D"-dld"],
-	[AC_CHECK_FUNC([dlopen],
-	      [lt_cv_dlopen=3D"dlopen"],
-	  [AC_CHECK_LIB([dl], [dlopen],
-		[lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-ldl"],
-	    [AC_CHECK_LIB([svld], [dlopen],
-		  [lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-lsvld"],
-	      [AC_CHECK_LIB([dld], [dld_link],
-		    [lt_cv_dlopen=3D"dld_link" lt_cv_dlopen_libs=3D"-dld"])
-	      ])
-	    ])
-	  ])
-	])
-      ])
-    ;;
-  esac
-
-  if test "x$lt_cv_dlopen" !=3D xno; then
-    enable_dlopen=3Dyes
-  else
-    enable_dlopen=3Dno
-  fi
-
-  case $lt_cv_dlopen in
-  dlopen)
-    save_CPPFLAGS=3D"$CPPFLAGS"
-    test "x$ac_cv_header_dlfcn_h" =3D xyes && CPPFLAGS=3D"$CPPFLAGS -DHAVE=
_DLFCN_H"
-
-    save_LDFLAGS=3D"$LDFLAGS"
-    wl=3D$lt_prog_compiler_wl eval LDFLAGS=3D\"\$LDFLAGS $export_dynamic_f=
lag_spec\"
-
-    save_LIBS=3D"$LIBS"
-    LIBS=3D"$lt_cv_dlopen_libs $LIBS"
-
-    AC_CACHE_CHECK([whether a program can dlopen itself],
-	  lt_cv_dlopen_self, [dnl
-	  _LT_AC_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self=3Dyes, lt_cv_dlopen_self=3Dyes,
-	    lt_cv_dlopen_self=3Dno, lt_cv_dlopen_self=3Dcross)
-    ])
-
-    if test "x$lt_cv_dlopen_self" =3D xyes; then
-      wl=3D$lt_prog_compiler_wl eval LDFLAGS=3D\"\$LDFLAGS $lt_prog_compil=
er_static\"
-      AC_CACHE_CHECK([whether a statically linked program can dlopen itsel=
f],
-    	  lt_cv_dlopen_self_static, [dnl
-	  _LT_AC_TRY_DLOPEN_SELF(
-	    lt_cv_dlopen_self_static=3Dyes, lt_cv_dlopen_self_static=3Dyes,
-	    lt_cv_dlopen_self_static=3Dno,  lt_cv_dlopen_self_static=3Dcross)
-      ])
-    fi
-
-    CPPFLAGS=3D"$save_CPPFLAGS"
-    LDFLAGS=3D"$save_LDFLAGS"
-    LIBS=3D"$save_LIBS"
-    ;;
-  esac
-
-  case $lt_cv_dlopen_self in
-  yes|no) enable_dlopen_self=3D$lt_cv_dlopen_self ;;
-  *) enable_dlopen_self=3Dunknown ;;
-  esac
-
-  case $lt_cv_dlopen_self_static in
-  yes|no) enable_dlopen_self_static=3D$lt_cv_dlopen_self_static ;;
-  *) enable_dlopen_self_static=3Dunknown ;;
-  esac
-fi
-])# AC_LIBTOOL_DLOPEN_SELF
-
-
-# AC_LIBTOOL_PROG_CC_C_O([TAGNAME])
-# ---------------------------------
-# Check to see if options -c and -o are simultaneously supported by compil=
er
-AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O],
-[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
-AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext],
-  [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)],
-  [_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=3Dno
-   $rm -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag=3D"-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=3D$?
-   cat out/conftest.err >&AS_MESSAGE_LOG_FD
-   echo "$as_me:__oline__: \$? =3D $ac_status" >&AS_MESSAGE_LOG_FD
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.=
exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.e=
r2 >/dev/null; then
-       _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=3Dyes
-     fi
-   fi
-   chmod u+w . 2>&AS_MESSAGE_LOG_FD
-   $rm conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
-   $rm out/* && rmdir out
-   cd ..
-   rmdir conftest
-   $rm conftest*
-])
-])# AC_LIBTOOL_PROG_CC_C_O
-
-
-# AC_LIBTOOL_SYS_HARD_LINK_LOCKS([TAGNAME])
-# -----------------------------------------
-# Check to see if we can do hard links to lock some files if needed
-AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS],
-[AC_REQUIRE([_LT_AC_LOCK])dnl
-
-hard_links=3D"nottested"
-if test "$_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)" =3D no && test "$nee=
d_locks" !=3D no; then
-  # do not overwrite the value of need_locks provided by the user
-  AC_MSG_CHECKING([if we can lock with hard links])
-  hard_links=3Dyes
-  $rm conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=3Dno
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  AC_MSG_RESULT([$hard_links])
-  if test "$hard_links" =3D no; then
-    AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsaf=
e])
-    need_locks=3Dwarn
-  fi
-else
-  need_locks=3Dno
-fi
-])# AC_LIBTOOL_SYS_HARD_LINK_LOCKS
-
-
-# AC_LIBTOOL_OBJDIR
-# -----------------
-AC_DEFUN([AC_LIBTOOL_OBJDIR],
-[AC_CACHE_CHECK([for objdir], [lt_cv_objdir],
-[rm -f .libs 2>/dev/null
-mkdir .libs 2>/dev/null
-if test -d .libs; then
-  lt_cv_objdir=3D.libs
-else
-  # MS-DOS does not allow filenames that begin with a dot.
-  lt_cv_objdir=3D_libs
-fi
-rmdir .libs 2>/dev/null])
-objdir=3D$lt_cv_objdir
-])# AC_LIBTOOL_OBJDIR
-
-
-# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH([TAGNAME])
-# ----------------------------------------------
-# Check hardcoding attributes.
-AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH],
-[AC_MSG_CHECKING([how to hardcode library paths into programs])
-_LT_AC_TAGVAR(hardcode_action, $1)=3D
-if test -n "$_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)" || \
-   test -n "$_LT_AC_TAGVAR(runpath_var, $1)" || \
-   test "X$_LT_AC_TAGVAR(hardcode_automatic, $1)" =3D "Xyes" ; then
-
-  # We can hardcode non-existant directories.
-  if test "$_LT_AC_TAGVAR(hardcode_direct, $1)" !=3D no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)" !=3D no &&
-     test "$_LT_AC_TAGVAR(hardcode_minus_L, $1)" !=3D no; then
-    # Linking always hardcodes the temporary library directory.
-    _LT_AC_TAGVAR(hardcode_action, $1)=3Drelink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    _LT_AC_TAGVAR(hardcode_action, $1)=3Dimmediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  _LT_AC_TAGVAR(hardcode_action, $1)=3Dunsupported
-fi
-AC_MSG_RESULT([$_LT_AC_TAGVAR(hardcode_action, $1)])
-
-if test "$_LT_AC_TAGVAR(hardcode_action, $1)" =3D relink; then
-  # Fast installation is not supported
-  enable_fast_install=3Dno
-elif test "$shlibpath_overrides_runpath" =3D yes ||
-     test "$enable_shared" =3D no; then
-  # Fast installation is not necessary
-  enable_fast_install=3Dneedless
-fi
-])# AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH
-
-
-# AC_LIBTOOL_SYS_LIB_STRIP
-# ------------------------
-AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP],
-[striplib=3D
-old_striplib=3D
-AC_MSG_CHECKING([whether stripping libraries is possible])
-if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
-  test -z "$old_striplib" && old_striplib=3D"$STRIP --strip-debug"
-  test -z "$striplib" && striplib=3D"$STRIP --strip-unneeded"
-  AC_MSG_RESULT([yes])
-else
-# FIXME - insert some real tests, host_os isn't really good enough
-  case $host_os in
-   darwin*)
-       if test -n "$STRIP" ; then
-         striplib=3D"$STRIP -x"
-         AC_MSG_RESULT([yes])
-       else
-  AC_MSG_RESULT([no])
-fi
-       ;;
-   *)
-  AC_MSG_RESULT([no])
-    ;;
-  esac
-fi
-])# AC_LIBTOOL_SYS_LIB_STRIP
-
-
-# AC_LIBTOOL_SYS_DYNAMIC_LINKER
-# -----------------------------
-# PORTME Fill in your ld.so characteristics
-AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER],
-[AC_MSG_CHECKING([dynamic linker characteristics])
-library_names_spec=3D
-libname_spec=3D'lib$name'
-soname_spec=3D
-shrext_cmds=3D".so"
-postinstall_cmds=3D
-postuninstall_cmds=3D
-finish_cmds=3D
-finish_eval=3D
-shlibpath_var=3D
-shlibpath_overrides_runpath=3Dunknown
-version_type=3Dnone
-dynamic_linker=3D"$host_os ld.so"
-sys_lib_dlsearch_path_spec=3D"/lib /usr/lib"
-if test "$GCC" =3D yes; then
-  sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^libraries:" =
| $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-  if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that shou=
ld
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED -e=
 's/;/ /g'`
-  else
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED  -=
e "s/$PATH_SEPARATOR/ /g"`
-  fi
-else
-  sys_lib_search_path_spec=3D"/lib /usr/lib /usr/local/lib"
-fi
-need_lib_prefix=3Dunknown
-hardcode_into_libs=3Dno
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=3Dunknown
-
-case $host_os in
-aix3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $libna=
me.a'
-  shlibpath_var=3DLIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the n=
ame.
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  ;;
-
-aix4* | aix5*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  hardcode_into_libs=3Dyes
-  if test "$host_cpu" =3D ia64; then
-    # AIX 5 supports IA64
-    library_names_spec=3D'${libname}${release}${shared_ext}$major ${libnam=
e}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[[01]] | aix4.[[01]].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ =3D=3D 2 && __GNUC_MINOR__ =
>=3D 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
-	:
-      else
-	can_build_shared=3Dno
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not h=
ardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" =3D yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec=3D'${libname}${release}.a $libname.a'
-      soname_spec=3D'${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=3DLIBPATH
-  fi
-  ;;
-
-amigaos*)
-  library_names_spec=3D'$libname.ixlibrary $libname.a'
-  # Create ${libname}_ixlibrary.a entries in /sys/libs.
-  finish_eval=3D'for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libna=
me=3D`$echo "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; =
test $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $li=
b ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.=
a || exit 1; done'
-  ;;
-
-beos*)
-  library_names_spec=3D'${libname}${shared_ext}'
-  dynamic_linker=3D"$host_os ld.so"
-  shlibpath_var=3DLIBRARY_PATH
-  ;;
-
-bsdi[[45]]*)
-  version_type=3Dlinux
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/shlib /usr/lib /usr/X11/lib /usr/contrib/li=
b /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec=3D"/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32*)
-  version_type=3Dwindows
-  shrext_cmds=3D".dll"
-  need_version=3Dno
-  need_lib_prefix=3Dno
-
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32*)
-    library_names_spec=3D'$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds=3D'base_file=3D`basename \${file}`~
-      dlpath=3D`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dl=
name'\''`~
-      dldir=3D$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
-    postuninstall_cmds=3D'dldll=3D`$SHELL 2>&1 -c '\''. $file; echo \$dlna=
me'\''`~
-      dlpath=3D$dir/\$dldll~
-       $rm \$dlpath'
-    shlibpath_overrides_runpath=3Dyes
-
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec=3D'`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${relea=
se} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D"/usr/lib /lib/w32api /lib /usr/local/lib"
-      ;;
-    mingw*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec=3D'${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${=
versuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^librarie=
s:" | $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-      if echo "$sys_lib_search_path_spec" | [grep ';[c-zC-Z]:/' >/dev/null=
]; then
-        # It is most probably a Windows format PATH printed by
-        # mingw gcc, but we are running on Cygwin. Gcc prints its search
-        # path with ; separators, and with drive letters. We can handle the
-        # drive letters (cygwin fileutils understands them), so leave them,
-        # especially as we might pass files found there to a mingw objdump,
-        # which wouldn't understand a cygwinified path. Ahh.
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D  -e "s/$PATH_SEPARATOR/ /g"`
-      fi
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec=3D'`echo ${libname} | sed -e 's/^lib/pw/'``echo $=
{release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    ;;
-
-  *)
-    library_names_spec=3D'${libname}`echo ${release} | $SED -e 's/[[.]]/-/=
g'`${versuffix}${shared_ext} $libname.lib'
-    ;;
-  esac
-  dynamic_linker=3D'Win32 ld.exe'
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=3DPATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker=3D"$host_os dyld"
-  version_type=3Ddarwin
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${major}$shared_ext ${libname}=
$shared_ext ${libname}${release}${versuffix}$shared_ext'
-  soname_spec=3D'${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=3Dyes
-  shlibpath_var=3DDYLD_LIBRARY_PATH
-  shrext_cmds=3D'`test .$module =3D .yes && echo .so || echo .dylib`'
-  # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
-  if test "$GCC" =3D yes; then
-    sys_lib_search_path_spec=3D`$CC -print-search-dirs | tr "\n" "$PATH_SE=
PARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^librar=
ies:" | sed -e "s/^libraries://" -e "s,=3D/,/,g" -e "s,$PATH_SEPARATOR, ,g"=
 -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
-  else
-    sys_lib_search_path_spec=3D'/lib /usr/lib /usr/local/lib'
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-freebsd1*)
-  dynamic_linker=3Dno
-  ;;
-
-kfreebsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=3D`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[[123]]*) objformat=3Daout ;;
-    *) objformat=3Delf ;;
-    esac
-  fi
-  version_type=3Dfreebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=3Dno
-      need_lib_prefix=3Dno
-      ;;
-    freebsd-*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $l=
ibname${shared_ext}$versuffix'
-      need_version=3Dyes
-      ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_os in
-  freebsd2*)
-    shlibpath_overrides_runpath=3Dyes
-    ;;
-  freebsd3.[[01]]* | freebsdelf3.[[01]]*)
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \
-  freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=3Dno
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  esac
-  ;;
-
-gnu*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuse=
s to
-  # link against other versions.
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  case $host_cpu in
-  ia64*)
-    shrext_cmds=3D'.so'
-    hardcode_into_libs=3Dyes
-    dynamic_linker=3D"$host_os dld.so"
-    shlibpath_var=3DLD_LIBRARY_PATH
-    shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" =3D X32; then
-      sys_lib_search_path_spec=3D"/usr/lib/hpux32 /usr/local/lib/hpux32 /u=
sr/local/lib"
-    else
-      sys_lib_search_path_spec=3D"/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-    ;;
-   hppa*64*)
-     shrext_cmds=3D'.sl'
-     hardcode_into_libs=3Dyes
-     dynamic_linker=3D"$host_os dld.sl"
-     shlibpath_var=3DLD_LIBRARY_PATH # How should we handle SHLIB_PATH
-     shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-     library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${l=
ibname}${release}${shared_ext}$major $libname${shared_ext}'
-     soname_spec=3D'${libname}${release}${shared_ext}$major'
-     sys_lib_search_path_spec=3D"/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-     sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-     ;;
-   *)
-    shrext_cmds=3D'.sl'
-    dynamic_linker=3D"$host_os dld.sl"
-    shlibpath_var=3DSHLIB_PATH
-    shlibpath_overrides_runpath=3Dno # +s is required to enable SHLIB_PATH
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
-  postinstall_cmds=3D'chmod 555 $lib'
-  ;;
-
-interix3*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  dynamic_linker=3D'Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=3Dnonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" =3D yes; then
-		version_type=3Dlinux
-	else
-		version_type=3Dirix
-	fi ;;
-  esac
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libnam=
e${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff=3D shlibsuff=3D
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff=3D shlibsuff=3D libmagic=3D32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=3D32 shlibsuff=3DN32 libmagic=3DN32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=3D64 shlibsuff=3D64 libmagic=3D64-bit;;
-    *) libsuff=3D shlibsuff=3D libmagic=3Dnever-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=3Dno
-  sys_lib_search_path_spec=3D"/usr/lib${libsuff} /lib${libsuff} /usr/local=
/lib${libsuff}"
-  sys_lib_dlsearch_path_spec=3D"/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=3Dyes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=3Dno
-  ;;
-
-# This must be Linux ELF.
-linux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=3Dyes
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=3D`awk '/^include / { system(sprintf("cd /etc; cat %s", \[=
$]2)); skip =3D 1; } { if (!skip) print \[$]0; skip =3D 0; }' < /etc/ld.so.=
conf | $SED -e 's/#.*//;s/[:,	]/ /g;s/=3D[^=3D]*$//;s/=3D[^=3D ]* / /g;/^$/=
d' | tr '\n' ' '`
-    sys_lib_dlsearch_path_spec=3D"/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker=3D'GNU/Linux ld.so'
-  ;;
-
-knetbsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-netbsd*)
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${shared_ext}$versuffix'
-    finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker=3D'NetBSD (a.out) ld.so'
-  else
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    dynamic_linker=3D'NetBSD ld.elf_so'
-  fi
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  ;;
-
-newsos6)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-nto-qnx*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-openbsd*)
-  version_type=3Dsunos
-  sys_lib_dlsearch_path_spec=3D"/usr/lib"
-  need_lib_prefix=3Dno
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=3Dyes ;;
-    *)                         need_version=3Dno  ;;
-  esac
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[[89]] | openbsd2.[[89]].*)
-	shlibpath_overrides_runpath=3Dno
-	;;
-      *)
-	shlibpath_overrides_runpath=3Dyes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=3Dyes
-  fi
-  ;;
-
-os2*)
-  libname_spec=3D'$name'
-  shrext_cmds=3D".dll"
-  need_lib_prefix=3Dno
-  library_names_spec=3D'$libname${shared_ext} $libname.a'
-  dynamic_linker=3D'OS/2 ld.exe'
-  shlibpath_var=3DLIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=3Dosf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /=
usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec=3D"$sys_lib_search_path_spec"
-  ;;
-
-solaris*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  # ldd complains unless libraries are executable
-  postinstall_cmds=3D'chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=3Dsunos
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    need_lib_prefix=3Dno
-  fi
-  need_version=3Dyes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=3Dno
-      need_lib_prefix=3Dno
-      export_dynamic_flag_spec=3D'${wl}-Blargedynsym'
-      runpath_var=3DLD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=3Dno
-      ;;
-    motorola)
-      need_lib_prefix=3Dno
-      need_version=3Dno
-      shlibpath_overrides_runpath=3Dno
-      sys_lib_search_path_spec=3D'/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=3Dlinux
-    library_names_spec=3D'$libname${shared_ext}.$versuffix $libname${share=
d_ext}.$major $libname${shared_ext}'
-    soname_spec=3D'$libname${shared_ext}.$major'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=3Dfreebsd-elf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    sys_lib_search_path_spec=3D'/usr/local/lib /usr/gnu/lib /usr/ccs/lib /=
usr/lib /lib'
-    shlibpath_overrides_runpath=3Dno
-  else
-    sys_lib_search_path_spec=3D'/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=3Dyes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec=3D"$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/lib'
-  ;;
-
-uts4*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=3Dno
-  ;;
-esac
-AC_MSG_RESULT([$dynamic_linker])
-test "$dynamic_linker" =3D no && can_build_shared=3Dno
-
-variables_saved_for_relink=3D"PATH $shlibpath_var $runpath_var"
-if test "$GCC" =3D yes; then
-  variables_saved_for_relink=3D"$variables_saved_for_relink GCC_EXEC_PREFI=
X COMPILER_PATH LIBRARY_PATH"
-fi
-])# AC_LIBTOOL_SYS_DYNAMIC_LINKER
-
-
-# _LT_AC_TAGCONFIG
-# ----------------
-AC_DEFUN([_LT_AC_TAGCONFIG],
-[AC_ARG_WITH([tags],
-    [AC_HELP_STRING([--with-tags@<:@=3DTAGS@:>@],
-        [include additional configurations @<:@automatic@:>@])],
-    [tagnames=3D"$withval"])
-
-if test -f "$ltmain" && test -n "$tagnames"; then
-  if test ! -f "${ofile}"; then
-    AC_MSG_WARN([output file `$ofile' does not exist])
-  fi
-
-  if test -z "$LTCC"; then
-    eval "`$SHELL ${ofile} --config | grep '^LTCC=3D'`"
-    if test -z "$LTCC"; then
-      AC_MSG_WARN([output file `$ofile' does not look like a libtool scrip=
t])
-    else
-      AC_MSG_WARN([using `LTCC=3D$LTCC', extracted from `$ofile'])
-    fi
-  fi
-  if test -z "$LTCFLAGS"; then
-    eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS=3D'`"
-  fi
-
-  # Extract list of available tagged configurations in $ofile.
-  # Note that this assumes the entire list is on one line.
-  available_tags=3D`grep "^available_tags=3D" "${ofile}" | $SED -e 's/avai=
lable_tags=3D\(.*$\)/\1/' -e 's/\"//g'`
-
-  lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-  for tagname in $tagnames; do
-    IFS=3D"$lt_save_ifs"
-    # Check whether tagname contains only valid characters
-    case `$echo "X$tagname" | $Xsed -e 's:[[-_ABCDEFGHIJKLMNOPQRSTUVWXYZab=
cdefghijklmnopqrstuvwxyz1234567890,/]]::g'` in
-    "") ;;
-    *)  AC_MSG_ERROR([invalid tag name: $tagname])
-	;;
-    esac
-
-    if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /d=
ev/null
-    then
-      AC_MSG_ERROR([tag name \"$tagname\" already exists])
-    fi
-
-    # Update the list of available tags.
-    if test -n "$tagname"; then
-      echo appending configuration tag \"$tagname\" to $ofile
-
-      case $tagname in
-      CXX)
-	if test -n "$CXX" && ( test "X$CXX" !=3D "Xno" &&
-	    ( (test "X$CXX" =3D "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-	    (test "X$CXX" !=3D "Xg++"))) ; then
-	  AC_LIBTOOL_LANG_CXX_CONFIG
-	else
-	  tagname=3D""
-	fi
-	;;
-
-      F77)
-	if test -n "$F77" && test "X$F77" !=3D "Xno"; then
-	  AC_LIBTOOL_LANG_F77_CONFIG
-	else
-	  tagname=3D""
-	fi
-	;;
-
-      GCJ)
-	if test -n "$GCJ" && test "X$GCJ" !=3D "Xno"; then
-	  AC_LIBTOOL_LANG_GCJ_CONFIG
-	else
-	  tagname=3D""
-	fi
-	;;
-
-      RC)
-	AC_LIBTOOL_LANG_RC_CONFIG
-	;;
-
-      *)
-	AC_MSG_ERROR([Unsupported tag name: $tagname])
-	;;
-      esac
-
-      # Append the new tag name to the list of available tags.
-      if test -n "$tagname" ; then
-      available_tags=3D"$available_tags $tagname"
-    fi
-    fi
-  done
-  IFS=3D"$lt_save_ifs"
-
-  # Now substitute the updated list of available tags.
-  if eval "sed -e 's/^available_tags=3D.*\$/available_tags=3D\"$available_=
tags\"/' \"$ofile\" > \"${ofile}T\""; then
-    mv "${ofile}T" "$ofile"
-    chmod +x "$ofile"
-  else
-    rm -f "${ofile}T"
-    AC_MSG_ERROR([unable to update list of available tagged configurations=
.])
-  fi
-fi
-])# _LT_AC_TAGCONFIG
-
-
-# AC_LIBTOOL_DLOPEN
-# -----------------
-# enable checks for dlopen support
-AC_DEFUN([AC_LIBTOOL_DLOPEN],
- [AC_BEFORE([$0],[AC_LIBTOOL_SETUP])
-])# AC_LIBTOOL_DLOPEN
-
-
-# AC_LIBTOOL_WIN32_DLL
-# --------------------
-# declare package support for building win32 DLLs
-AC_DEFUN([AC_LIBTOOL_WIN32_DLL],
-[AC_BEFORE([$0], [AC_LIBTOOL_SETUP])
-])# AC_LIBTOOL_WIN32_DLL
-
-
-# AC_ENABLE_SHARED([DEFAULT])
-# ---------------------------
-# implement the --enable-shared flag
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-AC_DEFUN([AC_ENABLE_SHARED],
-[define([AC_ENABLE_SHARED_DEFAULT], ifelse($1, no, no, yes))dnl
-AC_ARG_ENABLE([shared],
-    [AC_HELP_STRING([--enable-shared@<:@=3DPKGS@:>@],
-	[build shared libraries @<:@default=3D]AC_ENABLE_SHARED_DEFAULT[@:>@])],
-    [p=3D${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=3Dyes ;;
-    no) enable_shared=3Dno ;;
-    *)
-      enable_shared=3Dno
-      # Look at the argument we got.  We use all the common list separator=
s.
-      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS=3D"$lt_save_ifs"
-	if test "X$pkg" =3D "X$p"; then
-	  enable_shared=3Dyes
-	fi
-      done
-      IFS=3D"$lt_save_ifs"
-      ;;
-    esac],
-    [enable_shared=3D]AC_ENABLE_SHARED_DEFAULT)
-])# AC_ENABLE_SHARED
-
-
-# AC_DISABLE_SHARED
-# -----------------
-# set the default shared flag to --disable-shared
-AC_DEFUN([AC_DISABLE_SHARED],
-[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
-AC_ENABLE_SHARED(no)
-])# AC_DISABLE_SHARED
-
-
-# AC_ENABLE_STATIC([DEFAULT])
-# ---------------------------
-# implement the --enable-static flag
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-AC_DEFUN([AC_ENABLE_STATIC],
-[define([AC_ENABLE_STATIC_DEFAULT], ifelse($1, no, no, yes))dnl
-AC_ARG_ENABLE([static],
-    [AC_HELP_STRING([--enable-static@<:@=3DPKGS@:>@],
-	[build static libraries @<:@default=3D]AC_ENABLE_STATIC_DEFAULT[@:>@])],
-    [p=3D${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=3Dyes ;;
-    no) enable_static=3Dno ;;
-    *)
-     enable_static=3Dno
-      # Look at the argument we got.  We use all the common list separator=
s.
-      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS=3D"$lt_save_ifs"
-	if test "X$pkg" =3D "X$p"; then
-	  enable_static=3Dyes
-	fi
-      done
-      IFS=3D"$lt_save_ifs"
-      ;;
-    esac],
-    [enable_static=3D]AC_ENABLE_STATIC_DEFAULT)
-])# AC_ENABLE_STATIC
-
-
-# AC_DISABLE_STATIC
-# -----------------
-# set the default static flag to --disable-static
-AC_DEFUN([AC_DISABLE_STATIC],
-[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
-AC_ENABLE_STATIC(no)
-])# AC_DISABLE_STATIC
-
-
-# AC_ENABLE_FAST_INSTALL([DEFAULT])
-# ---------------------------------
-# implement the --enable-fast-install flag
-# DEFAULT is either `yes' or `no'.  If omitted, it defaults to `yes'.
-AC_DEFUN([AC_ENABLE_FAST_INSTALL],
-[define([AC_ENABLE_FAST_INSTALL_DEFAULT], ifelse($1, no, no, yes))dnl
-AC_ARG_ENABLE([fast-install],
-    [AC_HELP_STRING([--enable-fast-install@<:@=3DPKGS@:>@],
-    [optimize for fast installation @<:@default=3D]AC_ENABLE_FAST_INSTALL_=
DEFAULT[@:>@])],
-    [p=3D${PACKAGE-default}
-    case $enableval in
-    yes) enable_fast_install=3Dyes ;;
-    no) enable_fast_install=3Dno ;;
-    *)
-      enable_fast_install=3Dno
-      # Look at the argument we got.  We use all the common list separator=
s.
-      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS=3D"$lt_save_ifs"
-	if test "X$pkg" =3D "X$p"; then
-	  enable_fast_install=3Dyes
-	fi
-      done
-      IFS=3D"$lt_save_ifs"
-      ;;
-    esac],
-    [enable_fast_install=3D]AC_ENABLE_FAST_INSTALL_DEFAULT)
-])# AC_ENABLE_FAST_INSTALL
-
-
-# AC_DISABLE_FAST_INSTALL
-# -----------------------
-# set the default to --disable-fast-install
-AC_DEFUN([AC_DISABLE_FAST_INSTALL],
-[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
-AC_ENABLE_FAST_INSTALL(no)
-])# AC_DISABLE_FAST_INSTALL
-
-
-# AC_LIBTOOL_PICMODE([MODE])
-# --------------------------
-# implement the --with-pic flag
-# MODE is either `yes' or `no'.  If omitted, it defaults to `both'.
-AC_DEFUN([AC_LIBTOOL_PICMODE],
-[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
-pic_mode=3Difelse($#,1,$1,default)
-])# AC_LIBTOOL_PICMODE
-
-
-# AC_PROG_EGREP
-# -------------
-# This is predefined starting with Autoconf 2.54, so this conditional
-# definition can be removed once we require Autoconf 2.54 or later.
-m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP],
-[AC_CACHE_CHECK([for egrep], [ac_cv_prog_egrep],
-   [if echo a | (grep -E '(a|b)') >/dev/null 2>&1
-    then ac_cv_prog_egrep=3D'grep -E'
-    else ac_cv_prog_egrep=3D'egrep'
-    fi])
- EGREP=3D$ac_cv_prog_egrep
- AC_SUBST([EGREP])
-])])
-
-
-# AC_PATH_TOOL_PREFIX
-# -------------------
-# find a file program which can recognise shared library
-AC_DEFUN([AC_PATH_TOOL_PREFIX],
-[AC_REQUIRE([AC_PROG_EGREP])dnl
-AC_MSG_CHECKING([for $1])
-AC_CACHE_VAL(lt_cv_path_MAGIC_CMD,
-[case $MAGIC_CMD in
-[[\\/*] |  ?:[\\/]*])
-  lt_cv_path_MAGIC_CMD=3D"$MAGIC_CMD" # Let the user override the test wit=
h a path.
-  ;;
-*)
-  lt_save_MAGIC_CMD=3D"$MAGIC_CMD"
-  lt_save_ifs=3D"$IFS"; IFS=3D$PATH_SEPARATOR
-dnl $ac_dummy forces splitting on constant user-supplied paths.
-dnl POSIX.2 word splitting is done only on the output of word expansions,
-dnl not every word.  This closes a longstanding sh security hole.
-  ac_dummy=3D"ifelse([$2], , $PATH, [$2])"
-  for ac_dir in $ac_dummy; do
-    IFS=3D"$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=3D.
-    if test -f $ac_dir/$1; then
-      lt_cv_path_MAGIC_CMD=3D"$ac_dir/$1"
-      if test -n "$file_magic_test_file"; then
-	case $deplibs_check_method in
-	"file_magic "*)
-	  file_magic_regex=3D`expr "$deplibs_check_method" : "file_magic \(.*\)"`
-	  MAGIC_CMD=3D"$lt_cv_path_MAGIC_CMD"
-	  if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null |
-	    $EGREP "$file_magic_regex" > /dev/null; then
-	    :
-	  else
-	    cat <<EOF 1>&2
-
-*** Warning: the command libtool uses to detect shared libraries,
-*** $file_magic_cmd, produces output that libtool cannot recognize.
-*** The result is that libtool may fail to recognize shared libraries
-*** as such.  This will affect the creation of libtool libraries that
-*** depend on shared libraries, but programs linked with such libtool
-*** libraries will work regardless of this problem.  Nevertheless, you
-*** may want to report the problem to your system manager and/or to
-*** bug-libtool at gnu.org
-
-EOF
-	  fi ;;
-	esac
-      fi
-      break
-    fi
-  done
-  IFS=3D"$lt_save_ifs"
-  MAGIC_CMD=3D"$lt_save_MAGIC_CMD"
-  ;;
-esac])
-MAGIC_CMD=3D"$lt_cv_path_MAGIC_CMD"
-if test -n "$MAGIC_CMD"; then
-  AC_MSG_RESULT($MAGIC_CMD)
-else
-  AC_MSG_RESULT(no)
-fi
-])# AC_PATH_TOOL_PREFIX
-
-
-# AC_PATH_MAGIC
-# -------------
-# find a file program which can recognise a shared library
-AC_DEFUN([AC_PATH_MAGIC],
-[AC_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH)
-if test -z "$lt_cv_path_MAGIC_CMD"; then
-  if test -n "$ac_tool_prefix"; then
-    AC_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH)
-  else
-    MAGIC_CMD=3D:
-  fi
-fi
-])# AC_PATH_MAGIC
-
-
-# AC_PROG_LD
-# ----------
-# find the pathname to the GNU or non-GNU linker
-AC_DEFUN([AC_PROG_LD],
-[AC_ARG_WITH([gnu-ld],
-    [AC_HELP_STRING([--with-gnu-ld],
-	[assume the C compiler uses GNU ld @<:@default=3Dno@:>@])],
-    [test "$withval" =3D no || with_gnu_ld=3Dyes],
-    [with_gnu_ld=3Dno])
-AC_REQUIRE([LT_AC_PROG_SED])dnl
-AC_REQUIRE([AC_PROG_CC])dnl
-AC_REQUIRE([AC_CANONICAL_HOST])dnl
-AC_REQUIRE([AC_CANONICAL_BUILD])dnl
-ac_prog=3Dld
-if test "$GCC" =3D yes; then
-  # Check if gcc -print-prog-name=3Dld gives a path.
-  AC_MSG_CHECKING([for ld used by $CC])
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=3D`($CC -print-prog-name=3Dld) 2>&5 | tr -d '\015'` ;;
-  *)
-    ac_prog=3D`($CC -print-prog-name=3Dld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [[\\/]]* | ?:[[\\/]]*)
-      re_direlt=3D'/[[^/]][[^/]]*/\.\./'
-      # Canonicalize the pathname of ld
-      ac_prog=3D`echo $ac_prog| $SED 's%\\\\%/%g'`
-      while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=3D`echo $ac_prog| $SED "s%$re_direlt%/%"`
-      done
-      test -z "$LD" && LD=3D"$ac_prog"
-      ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=3Dld
-    ;;
-  *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=3Dunknown
-    ;;
-  esac
-elif test "$with_gnu_ld" =3D yes; then
-  AC_MSG_CHECKING([for GNU ld])
-else
-  AC_MSG_CHECKING([for non-GNU ld])
-fi
-AC_CACHE_VAL(lt_cv_path_LD,
-[if test -z "$LD"; then
-  lt_save_ifs=3D"$IFS"; IFS=3D$PATH_SEPARATOR
-  for ac_dir in $PATH; do
-    IFS=3D"$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=3D.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext";=
 then
-      lt_cv_path_LD=3D"$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
-      *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" !=3D no && break
-	;;
-      *)
-	test "$with_gnu_ld" !=3D yes && break
-	;;
-      esac
-    fi
-  done
-  IFS=3D"$lt_save_ifs"
-else
-  lt_cv_path_LD=3D"$LD" # Let the user override the test with a path.
-fi])
-LD=3D"$lt_cv_path_LD"
-if test -n "$LD"; then
-  AC_MSG_RESULT($LD)
-else
-  AC_MSG_RESULT(no)
-fi
-test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
-AC_PROG_LD_GNU
-])# AC_PROG_LD
-
-
-# AC_PROG_LD_GNU
-# --------------
-AC_DEFUN([AC_PROG_LD_GNU],
-[AC_REQUIRE([AC_PROG_EGREP])dnl
-AC_CACHE_CHECK([if the linker ($LD) is GNU ld], lt_cv_prog_gnu_ld,
-[# I'd rather use --version here, but apparently some GNU lds only accept =
-v.
-case `$LD -v 2>&1 </dev/null` in
-*GNU* | *'with BFD'*)
-  lt_cv_prog_gnu_ld=3Dyes
-  ;;
-*)
-  lt_cv_prog_gnu_ld=3Dno
-  ;;
-esac])
-with_gnu_ld=3D$lt_cv_prog_gnu_ld
-])# AC_PROG_LD_GNU
-
-
-# AC_PROG_LD_RELOAD_FLAG
-# ----------------------
-# find reload flag for linker
-#   -- PORTME Some linkers may need a different reload flag.
-AC_DEFUN([AC_PROG_LD_RELOAD_FLAG],
-[AC_CACHE_CHECK([for $LD option to reload object files],
-  lt_cv_ld_reload_flag,
-  [lt_cv_ld_reload_flag=3D'-r'])
-reload_flag=3D$lt_cv_ld_reload_flag
-case $reload_flag in
-"" | " "*) ;;
-*) reload_flag=3D" $reload_flag" ;;
-esac
-reload_cmds=3D'$LD$reload_flag -o $output$reload_objs'
-case $host_os in
-  darwin*)
-    if test "$GCC" =3D yes; then
-      reload_cmds=3D'$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_o=
bjs'
-    else
-      reload_cmds=3D'$LD$reload_flag -o $output$reload_objs'
-    fi
-    ;;
-esac
-])# AC_PROG_LD_RELOAD_FLAG
-
-
-# AC_DEPLIBS_CHECK_METHOD
-# -----------------------
-# how to check for library dependencies
-#  -- PORTME fill in with the dynamic library characteristics
-AC_DEFUN([AC_DEPLIBS_CHECK_METHOD],
-[AC_CACHE_CHECK([how to recognise dependent libraries],
-lt_cv_deplibs_check_method,
-[lt_cv_file_magic_cmd=3D'$MAGIC_CMD'
-lt_cv_file_magic_test_file=3D
-lt_cv_deplibs_check_method=3D'unknown'
-# Need to set the preceding variable on all platforms that support
-# interlibrary dependencies.
-# 'none' -- dependencies not supported.
-# `unknown' -- same as none, but documents that we really don't know.
-# 'pass_all' -- all dependencies passed with no checks.
-# 'test_compile' -- check by making test program.
-# 'file_magic [[regex]]' -- check by looking for files in library path
-# which responds to the $file_magic_cmd with a given extended regex.
-# If you have `file' or equivalent on your system and you're not sure
-# whether `pass_all' will *always* work, you probably want this one.
-
-case $host_os in
-aix4* | aix5*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-beos*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-bsdi[[45]]*)
-  lt_cv_deplibs_check_method=3D'file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]S=
B (shared object|dynamic lib)'
-  lt_cv_file_magic_cmd=3D'/usr/bin/file -L'
-  lt_cv_file_magic_test_file=3D/shlib/libc.so
-  ;;
-
-cygwin*)
-  # func_win32_libid is a shell function defined in ltmain.sh
-  lt_cv_deplibs_check_method=3D'file_magic ^x86 archive import|^x86 DLL'
-  lt_cv_file_magic_cmd=3D'func_win32_libid'
-  ;;
-
-mingw* | pw32*)
-  # Base MSYS/MinGW do not provide the 'file' command needed by
-  # func_win32_libid shell function, so use a weaker test based on 'objdum=
p'.
-  lt_cv_deplibs_check_method=3D'file_magic file format pei*-i386(.*archite=
cture: i386)?'
-  lt_cv_file_magic_cmd=3D'$OBJDUMP -f'
-  ;;
-
-darwin* | rhapsody*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-freebsd* | kfreebsd*-gnu | dragonfly*)
-  if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
-    case $host_cpu in
-    i*86 )
-      # Not sure whether the presence of OpenBSD here was a mistake.
-      # Let's accept both of them until this is cleared up.
-      lt_cv_deplibs_check_method=3D'file_magic (FreeBSD|OpenBSD|DragonFly)=
/i[[3-9]]86 (compact )?demand paged shared library'
-      lt_cv_file_magic_cmd=3D/usr/bin/file
-      lt_cv_file_magic_test_file=3D`echo /usr/lib/libc.so.*`
-      ;;
-    esac
-  else
-    lt_cv_deplibs_check_method=3Dpass_all
-  fi
-  ;;
-
-gnu*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-hpux10.20* | hpux11*)
-  lt_cv_file_magic_cmd=3D/usr/bin/file
-  case $host_cpu in
-  ia64*)
-    lt_cv_deplibs_check_method=3D'file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[=
[0-9]][[0-9]]) shared object file - IA64'
-    lt_cv_file_magic_test_file=3D/usr/lib/hpux32/libc.so
-    ;;
-  hppa*64*)
-    [lt_cv_deplibs_check_method=3D'file_magic (s[0-9][0-9][0-9]|ELF-[0-9][=
0-9]) shared object file - PA-RISC [0-9].[0-9]']
-    lt_cv_file_magic_test_file=3D/usr/lib/pa20_64/libc.sl
-    ;;
-  *)
-    lt_cv_deplibs_check_method=3D'file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RI=
SC[[0-9]].[[0-9]]) shared library'
-    lt_cv_file_magic_test_file=3D/usr/lib/libc.sl
-    ;;
-  esac
-  ;;
-
-interix3*)
-  # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
-  lt_cv_deplibs_check_method=3D'match_pattern /lib[[^/]]+(\.so|\.a)$'
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $LD in
-  *-32|*"-32 ") libmagic=3D32-bit;;
-  *-n32|*"-n32 ") libmagic=3DN32;;
-  *-64|*"-64 ") libmagic=3D64-bit;;
-  *) libmagic=3Dnever-match;;
-  esac
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-# This must be Linux ELF.
-linux*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-netbsd*)
-  if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
-    lt_cv_deplibs_check_method=3D'match_pattern /lib[[^/]]+(\.so\.[[0-9]]+=
\.[[0-9]]+|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method=3D'match_pattern /lib[[^/]]+(\.so|_pic\.a)$'
-  fi
-  ;;
-
-newos6*)
-  lt_cv_deplibs_check_method=3D'file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]S=
B (executable|dynamic lib)'
-  lt_cv_file_magic_cmd=3D/usr/bin/file
-  lt_cv_file_magic_test_file=3D/usr/lib/libnls.so
-  ;;
-
-nto-qnx*)
-  lt_cv_deplibs_check_method=3Dunknown
-  ;;
-
-openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
-    lt_cv_deplibs_check_method=3D'match_pattern /lib[[^/]]+(\.so\.[[0-9]]+=
\.[[0-9]]+|\.so|_pic\.a)$'
-  else
-    lt_cv_deplibs_check_method=3D'match_pattern /lib[[^/]]+(\.so\.[[0-9]]+=
\.[[0-9]]+|_pic\.a)$'
-  fi
-  ;;
-
-osf3* | osf4* | osf5*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-solaris*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-
-sysv4 | sysv4.3*)
-  case $host_vendor in
-  motorola)
-    lt_cv_deplibs_check_method=3D'file_magic ELF [[0-9]][[0-9]]*-bit [[ML]=
]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]'
-    lt_cv_file_magic_test_file=3D`echo /usr/lib/libc.so*`
-    ;;
-  ncr)
-    lt_cv_deplibs_check_method=3Dpass_all
-    ;;
-  sequent)
-    lt_cv_file_magic_cmd=3D'/bin/file'
-    lt_cv_deplibs_check_method=3D'file_magic ELF [[0-9]][[0-9]]*-bit [[LM]=
]SB (shared object|dynamic lib )'
-    ;;
-  sni)
-    lt_cv_file_magic_cmd=3D'/bin/file'
-    lt_cv_deplibs_check_method=3D"file_magic ELF [[0-9]][[0-9]]*-bit [[LM]=
]SB dynamic lib"
-    lt_cv_file_magic_test_file=3D/lib/libc.so
-    ;;
-  siemens)
-    lt_cv_deplibs_check_method=3Dpass_all
-    ;;
-  pc)
-    lt_cv_deplibs_check_method=3Dpass_all
-    ;;
-  esac
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  lt_cv_deplibs_check_method=3Dpass_all
-  ;;
-esac
-])
-file_magic_cmd=3D$lt_cv_file_magic_cmd
-deplibs_check_method=3D$lt_cv_deplibs_check_method
-test -z "$deplibs_check_method" && deplibs_check_method=3Dunknown
-])# AC_DEPLIBS_CHECK_METHOD
-
-
-# AC_PROG_NM
-# ----------
-# find the pathname to a BSD-compatible name lister
-AC_DEFUN([AC_PROG_NM],
-[AC_CACHE_CHECK([for BSD-compatible nm], lt_cv_path_NM,
-[if test -n "$NM"; then
-  # Let the user override the test.
-  lt_cv_path_NM=3D"$NM"
-else
-  lt_nm_to_check=3D"${ac_tool_prefix}nm"
-  if test -n "$ac_tool_prefix" && test "$build" =3D "$host"; then=20
-    lt_nm_to_check=3D"$lt_nm_to_check nm"
-  fi
-  for lt_tmp_nm in $lt_nm_to_check; do
-    lt_save_ifs=3D"$IFS"; IFS=3D$PATH_SEPARATOR
-    for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do
-      IFS=3D"$lt_save_ifs"
-      test -z "$ac_dir" && ac_dir=3D.
-      tmp_nm=3D"$ac_dir/$lt_tmp_nm"
-      if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then
-	# Check to see if the nm accepts a BSD-compat flag.
-	# Adding the `sed 1q' prevents false positives on HP-UX, which says:
-	#   nm: unknown option "B" ignored
-	# Tru64's nm complains that /dev/null is an invalid object file
-	case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in
-	*/dev/null* | *'Invalid file or object type'*)
-	  lt_cv_path_NM=3D"$tmp_nm -B"
-	  break
-	  ;;
-	*)
-	  case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in
-	  */dev/null*)
-	    lt_cv_path_NM=3D"$tmp_nm -p"
-	    break
-	    ;;
-	  *)
-	    lt_cv_path_NM=3D${lt_cv_path_NM=3D"$tmp_nm"} # keep the first match, =
but
-	    continue # so that we can try to find one that supports BSD flags
-	    ;;
-	  esac
-	  ;;
-	esac
-      fi
-    done
-    IFS=3D"$lt_save_ifs"
-  done
-  test -z "$lt_cv_path_NM" && lt_cv_path_NM=3Dnm
-fi])
-NM=3D"$lt_cv_path_NM"
-])# AC_PROG_NM
-
-
-# AC_CHECK_LIBM
-# -------------
-# check for math library
-AC_DEFUN([AC_CHECK_LIBM],
-[AC_REQUIRE([AC_CANONICAL_HOST])dnl
-LIBM=3D
-case $host in
-*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*)
-  # These system don't have libm, or don't need it
-  ;;
-*-ncr-sysv4.3*)
-  AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM=3D"-lmw")
-  AC_CHECK_LIB(m, cos, LIBM=3D"$LIBM -lm")
-  ;;
-*)
-  AC_CHECK_LIB(m, cos, LIBM=3D"-lm")
-  ;;
-esac
-])# AC_CHECK_LIBM
-
-
-# AC_LIBLTDL_CONVENIENCE([DIRECTORY])
-# -----------------------------------
-# sets LIBLTDL to the link flags for the libltdl convenience library and
-# LTDLINCL to the include flags for the libltdl header and adds
-# --enable-ltdl-convenience to the configure arguments.  Note that
-# AC_CONFIG_SUBDIRS is not called here.  If DIRECTORY is not provided,
-# it is assumed to be `libltdl'.  LIBLTDL will be prefixed with
-# '${top_builddir}/' and LTDLINCL will be prefixed with '${top_srcdir}/'
-# (note the single quotes!).  If your package is not flat and you're not
-# using automake, define top_builddir and top_srcdir appropriately in
-# the Makefiles.
-AC_DEFUN([AC_LIBLTDL_CONVENIENCE],
-[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
-  case $enable_ltdl_convenience in
-  no) AC_MSG_ERROR([this package needs a convenience libltdl]) ;;
-  "") enable_ltdl_convenience=3Dyes
-      ac_configure_args=3D"$ac_configure_args --enable-ltdl-convenience" ;;
-  esac
-  LIBLTDL=3D'${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdlc.la
-  LTDLINCL=3D'-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl'])
-  # For backwards non-gettext consistent compatibility...
-  INCLTDL=3D"$LTDLINCL"
-])# AC_LIBLTDL_CONVENIENCE
-
-
-# AC_LIBLTDL_INSTALLABLE([DIRECTORY])
-# -----------------------------------
-# sets LIBLTDL to the link flags for the libltdl installable library and
-# LTDLINCL to the include flags for the libltdl header and adds
-# --enable-ltdl-install to the configure arguments.  Note that
-# AC_CONFIG_SUBDIRS is not called here.  If DIRECTORY is not provided,
-# and an installed libltdl is not found, it is assumed to be `libltdl'.
-# LIBLTDL will be prefixed with '${top_builddir}/'# and LTDLINCL with
-# '${top_srcdir}/' (note the single quotes!).  If your package is not
-# flat and you're not using automake, define top_builddir and top_srcdir
-# appropriately in the Makefiles.
-# In the future, this macro may have to be called after AC_PROG_LIBTOOL.
-AC_DEFUN([AC_LIBLTDL_INSTALLABLE],
-[AC_BEFORE([$0],[AC_LIBTOOL_SETUP])dnl
-  AC_CHECK_LIB(ltdl, lt_dlinit,
-  [test x"$enable_ltdl_install" !=3D xyes && enable_ltdl_install=3Dno],
-  [if test x"$enable_ltdl_install" =3D xno; then
-     AC_MSG_WARN([libltdl not installed, but installation disabled])
-   else
-     enable_ltdl_install=3Dyes
-   fi
-  ])
-  if test x"$enable_ltdl_install" =3D x"yes"; then
-    ac_configure_args=3D"$ac_configure_args --enable-ltdl-install"
-    LIBLTDL=3D'${top_builddir}/'ifelse($#,1,[$1],['libltdl'])/libltdl.la
-    LTDLINCL=3D'-I${top_srcdir}/'ifelse($#,1,[$1],['libltdl'])
-  else
-    ac_configure_args=3D"$ac_configure_args --enable-ltdl-install=3Dno"
-    LIBLTDL=3D"-lltdl"
-    LTDLINCL=3D
-  fi
-  # For backwards non-gettext consistent compatibility...
-  INCLTDL=3D"$LTDLINCL"
-])# AC_LIBLTDL_INSTALLABLE
-
-
-# AC_LIBTOOL_CXX
-# --------------
-# enable support for C++ libraries
-AC_DEFUN([AC_LIBTOOL_CXX],
-[AC_REQUIRE([_LT_AC_LANG_CXX])
-])# AC_LIBTOOL_CXX
-
-
-# _LT_AC_LANG_CXX
-# ---------------
-AC_DEFUN([_LT_AC_LANG_CXX],
-[AC_REQUIRE([AC_PROG_CXX])
-AC_REQUIRE([_LT_AC_PROG_CXXCPP])
-_LT_AC_SHELL_INIT([tagnames=3D${tagnames+${tagnames},}CXX])
-])# _LT_AC_LANG_CXX
-
-# _LT_AC_PROG_CXXCPP
-# ------------------
-AC_DEFUN([_LT_AC_PROG_CXXCPP],
-[
-AC_REQUIRE([AC_PROG_CXX])
-if test -n "$CXX" && ( test "X$CXX" !=3D "Xno" &&
-    ( (test "X$CXX" =3D "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-    (test "X$CXX" !=3D "Xg++"))) ; then
-  AC_PROG_CXXCPP
-fi
-])# _LT_AC_PROG_CXXCPP
-
-# AC_LIBTOOL_F77
-# --------------
-# enable support for Fortran 77 libraries
-AC_DEFUN([AC_LIBTOOL_F77],
-[AC_REQUIRE([_LT_AC_LANG_F77])
-])# AC_LIBTOOL_F77
-
-
-# _LT_AC_LANG_F77
-# ---------------
-AC_DEFUN([_LT_AC_LANG_F77],
-[AC_REQUIRE([AC_PROG_F77])
-_LT_AC_SHELL_INIT([tagnames=3D${tagnames+${tagnames},}F77])
-])# _LT_AC_LANG_F77
-
-
-# AC_LIBTOOL_GCJ
-# --------------
-# enable support for GCJ libraries
-AC_DEFUN([AC_LIBTOOL_GCJ],
-[AC_REQUIRE([_LT_AC_LANG_GCJ])
-])# AC_LIBTOOL_GCJ
-
-
-# _LT_AC_LANG_GCJ
-# ---------------
-AC_DEFUN([_LT_AC_LANG_GCJ],
-[AC_PROVIDE_IFELSE([AC_PROG_GCJ],[],
-  [AC_PROVIDE_IFELSE([A][M_PROG_GCJ],[],
-    [AC_PROVIDE_IFELSE([LT_AC_PROG_GCJ],[],
-      [ifdef([AC_PROG_GCJ],[AC_REQUIRE([AC_PROG_GCJ])],
-	 [ifdef([A][M_PROG_GCJ],[AC_REQUIRE([A][M_PROG_GCJ])],
-	   [AC_REQUIRE([A][C_PROG_GCJ_OR_A][M_PROG_GCJ])])])])])])
-_LT_AC_SHELL_INIT([tagnames=3D${tagnames+${tagnames},}GCJ])
-])# _LT_AC_LANG_GCJ
-
-
-# AC_LIBTOOL_RC
-# -------------
-# enable support for Windows resource files
-AC_DEFUN([AC_LIBTOOL_RC],
-[AC_REQUIRE([LT_AC_PROG_RC])
-_LT_AC_SHELL_INIT([tagnames=3D${tagnames+${tagnames},}RC])
-])# AC_LIBTOOL_RC
-
-
-# AC_LIBTOOL_LANG_C_CONFIG
-# ------------------------
-# Ensure that the configuration vars for the C compiler are
-# suitably defined.  Those variables are subsequently used by
-# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
-AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG], [_LT_AC_LANG_C_CONFIG])
-AC_DEFUN([_LT_AC_LANG_C_CONFIG],
-[lt_save_CC=3D"$CC"
-AC_LANG_PUSH(C)
-
-# Source file extension for C test sources.
-ac_ext=3Dc
-
-# Object file extension for compiled C test sources.
-objext=3Do
-_LT_AC_TAGVAR(objext, $1)=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"int some_variable =3D 0;\n"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D'int main(){return(0);}\n'
-
-_LT_AC_SYS_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
-AC_LIBTOOL_PROG_COMPILER_PIC($1)
-AC_LIBTOOL_PROG_CC_C_O($1)
-AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
-AC_LIBTOOL_PROG_LD_SHLIBS($1)
-AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
-AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
-AC_LIBTOOL_SYS_LIB_STRIP
-AC_LIBTOOL_DLOPEN_SELF
-
-# Report which library types will actually be built
-AC_MSG_CHECKING([if libtool supports shared libraries])
-AC_MSG_RESULT([$can_build_shared])
-
-AC_MSG_CHECKING([whether to build shared libraries])
-test "$can_build_shared" =3D "no" && enable_shared=3Dno
-
-# On AIX, shared libraries and static libraries use the same namespace, and
-# are all built from PIC.
-case $host_os in
-aix3*)
-  test "$enable_shared" =3D yes && enable_static=3Dno
-  if test -n "$RANLIB"; then
-    archive_cmds=3D"$archive_cmds~\$RANLIB \$lib"
-    postinstall_cmds=3D'$RANLIB $lib'
-  fi
-  ;;
-
-aix4* | aix5*)
-  if test "$host_cpu" !=3D ia64 && test "$aix_use_runtimelinking" =3D no ;=
 then
-    test "$enable_shared" =3D yes && enable_static=3Dno
-  fi
-    ;;
-esac
-AC_MSG_RESULT([$enable_shared])
-
-AC_MSG_CHECKING([whether to build static libraries])
-# Make sure either enable_shared or enable_static is yes.
-test "$enable_shared" =3D yes || enable_static=3Dyes
-AC_MSG_RESULT([$enable_static])
-
-AC_LIBTOOL_CONFIG($1)
-
-AC_LANG_POP
-CC=3D"$lt_save_CC"
-])# AC_LIBTOOL_LANG_C_CONFIG
-
-
-# AC_LIBTOOL_LANG_CXX_CONFIG
-# --------------------------
-# Ensure that the configuration vars for the C compiler are
-# suitably defined.  Those variables are subsequently used by
-# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
-AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG], [_LT_AC_LANG_CXX_CONFIG(CXX)])
-AC_DEFUN([_LT_AC_LANG_CXX_CONFIG],
-[AC_LANG_PUSH(C++)
-AC_REQUIRE([AC_PROG_CXX])
-AC_REQUIRE([_LT_AC_PROG_CXXCPP])
-
-_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D
-_LT_AC_TAGVAR(always_export_symbols, $1)=3Dno
-_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D
-_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D
-_LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D
-_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=3D
-_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D
-_LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dno
-_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dunsupported
-_LT_AC_TAGVAR(hardcode_automatic, $1)=3Dno
-_LT_AC_TAGVAR(module_cmds, $1)=3D
-_LT_AC_TAGVAR(module_expsym_cmds, $1)=3D
-_LT_AC_TAGVAR(link_all_deplibs, $1)=3Dunknown
-_LT_AC_TAGVAR(old_archive_cmds, $1)=3D$old_archive_cmds
-_LT_AC_TAGVAR(no_undefined_flag, $1)=3D
-_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D
-_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=3Dno
-
-# Dependencies to place before and after the object being linked:
-_LT_AC_TAGVAR(predep_objects, $1)=3D
-_LT_AC_TAGVAR(postdep_objects, $1)=3D
-_LT_AC_TAGVAR(predeps, $1)=3D
-_LT_AC_TAGVAR(postdeps, $1)=3D
-_LT_AC_TAGVAR(compiler_lib_search_path, $1)=3D
-
-# Source file extension for C++ test sources.
-ac_ext=3Dcpp
-
-# Object file extension for compiled C++ test sources.
-objext=3Do
-_LT_AC_TAGVAR(objext, $1)=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"int some_variable =3D 0;\n"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D'int main(int, char *[[]]) { return(0); }\n'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_AC_SYS_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D$CC
-lt_save_LD=3D$LD
-lt_save_GCC=3D$GCC
-GCC=3D$GXX
-lt_save_with_gnu_ld=3D$with_gnu_ld
-lt_save_path_LD=3D$lt_cv_path_LD
-if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
-  lt_cv_prog_gnu_ld=3D$lt_cv_prog_gnu_ldcxx
-else
-  $as_unset lt_cv_prog_gnu_ld
-fi
-if test -n "${lt_cv_path_LDCXX+set}"; then
-  lt_cv_path_LD=3D$lt_cv_path_LDCXX
-else
-  $as_unset lt_cv_path_LD
-fi
-test -z "${LDCXX+set}" || LD=3D$LDCXX
-CC=3D${CXX-"c++"}
-compiler=3D$CC
-_LT_AC_TAGVAR(compiler, $1)=3D$CC
-_LT_CC_BASENAME([$compiler])
-
-# We don't want -fno-exception wen compiling C++ code, so set the
-# no_builtin_flag separately
-if test "$GXX" =3D yes; then
-  _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=3D' -fno-builtin'
-else
-  _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=3D
-fi
-
-if test "$GXX" =3D yes; then
-  # Set up default GNU C++ configuration
-
-  AC_PROG_LD
-
-  # Check if GNU C++ uses GNU ld as the underlying linker, since the
-  # archiving commands below assume that GNU ld is being used.
-  if test "$with_gnu_ld" =3D yes; then
-    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib $predep_objec=
ts $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$sona=
me -o $lib'
-    _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared -nostdlib $prede=
p_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $=
wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}--rpath ${wl}$lib=
dir'
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}--export-dynamic'
-
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
-    #     investigate it a little bit more. (MM)
-    wlarc=3D'${wl}'
-
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if eval "`$CC -print-prog-name=3Dld` --help 2>&1" | \
-	grep 'no-whole-archive' > /dev/null; then
-      _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D"$wlarc"'--whole-archiv=
e$convenience '"$wlarc"'--no-whole-archive'
-    else
-      _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D
-    fi
-  else
-    with_gnu_ld=3Dno
-    wlarc=3D
-
-    # A generic and very simple default shared library creation
-    # command for GNU C++ for the case where it uses the native
-    # linker, instead of GNU ld.  If possible, this setting should
-    # overridden to take advantage of the native linker features on
-    # the platform it is being used on.
-    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib $predep_objec=
ts $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-  fi
-
-  # Commands to make compiler produce verbose output that lists
-  # what "hidden" libraries, object files and flags are used when
-  # linking a shared library.
-  output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&1 =
| grep "\-L"'
-
-else
-  GXX=3Dno
-  with_gnu_ld=3Dno
-  wlarc=3D
-fi
-
-# PORTME: fill in a description of your system's C++ link characteristics
-AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared librar=
ies])
-_LT_AC_TAGVAR(ld_shlibs, $1)=3Dyes
-case $host_os in
-  aix3*)
-    # FIXME: insert proper C++ library support
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-  aix4* | aix5*)
-    if test "$host_cpu" =3D ia64; then
-      # On IA64, the linker does run time linking by default, so we don't
-      # have to do anything special.
-      aix_use_runtimelinking=3Dno
-      exp_sym_flag=3D'-Bexport'
-      no_entry_flag=3D""
-    else
-      aix_use_runtimelinking=3Dno
-
-      # Test if we are trying to use run time linking or normal
-      # AIX style linking. If -brtl is somewhere in LDFLAGS, we
-      # need to do runtime linking.
-      case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*)
-	for ld_flag in $LDFLAGS; do
-	  case $ld_flag in
-	  *-brtl*)
-	    aix_use_runtimelinking=3Dyes
-	    break
-	    ;;
-	  esac
-	done
-	;;
-      esac
-
-      exp_sym_flag=3D'-bexport'
-      no_entry_flag=3D'-bnoentry'
-    fi
-
-    # When large executables or shared objects are built, AIX ld can
-    # have problems creating the table of contents.  If linking a library
-    # or program results in "error TOC overflow" add -mminimal-toc to
-    # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-    # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-    _LT_AC_TAGVAR(archive_cmds, $1)=3D''
-    _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-    _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D':'
-    _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-
-    if test "$GXX" =3D yes; then
-      case $host_os in aix4.[[012]]|aix4.[[012]].*)
-      # We only want to do this on AIX 4.2 and lower, the check
-      # below for broken collect2 doesn't work under 4.3+
-	collect2name=3D`${CC} -print-prog-name=3Dcollect2`
-	if test -f "$collect2name" && \
-	   strings "$collect2name" | grep resolve_lib_name >/dev/null
-	then
-	  # We have reworked collect2
-	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-	else
-	  # We have old collect2
-	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dunsupported
-	  # It fails to find uninstalled libraries when the uninstalled
-	  # path is not listed in the libpath.  Setting hardcode_minus_L
-	  # to unsupported forces relinking
-	  _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D
-	fi
-	;;
-      esac
-      shared_flag=3D'-shared'
-      if test "$aix_use_runtimelinking" =3D yes; then
-	shared_flag=3D"$shared_flag "'${wl}-G'
-      fi
-    else
-      # not using gcc
-      if test "$host_cpu" =3D ia64; then
-	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	# chokes on -Wl,-G. The following line is correct:
-	shared_flag=3D'-G'
-      else
-	if test "$aix_use_runtimelinking" =3D yes; then
-	  shared_flag=3D'${wl}-G'
-	else
-	  shared_flag=3D'${wl}-bM:SRE'
-	fi
-      fi
-    fi
-
-    # It seems that -bexpall does not export symbols beginning with
-    # underscore (_), so it is better to generate a list of symbols to exp=
ort.
-    _LT_AC_TAGVAR(always_export_symbols, $1)=3Dyes
-    if test "$aix_use_runtimelinking" =3D yes; then
-      # Warning - without using the other runtime loading flags (-brtl),
-      # -berok will link without error, but may produce a broken library.
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'-berok'
-      # Determine the default libpath from the value encoded in an empty e=
xecutable.
-      _LT_AC_SYS_LIBPATH_AIX
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-blibpath:$libd=
ir:'"$aix_libpath"
-
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D"\$CC"' -o $output_objdir/$=
soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test =
"x${allow_undefined_flag}" !=3D "x"; then echo "${wl}${allow_undefined_flag=
}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-     else
-      if test "$host_cpu" =3D ia64; then
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-R $libdir:/usr/lib:=
/lib'
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D"-z nodefs"
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D"\$CC $shared_flag"' -o $output_=
objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags $=
{wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-      else
-	# Determine the default libpath from the value encoded in an empty execut=
able.
-	_LT_AC_SYS_LIBPATH_AIX
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-blibpath:$libdir:'"=
$aix_libpath"
-	# Warning - without using the other run time loading flags,
-	# -berok will link without error, but may produce a broken library.
-	_LT_AC_TAGVAR(no_undefined_flag, $1)=3D' ${wl}-bernotok'
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' ${wl}-berok'
-	# Exported symbols can be pulled into shared objects from archives
-	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'$convenience'
-	_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dyes
-	# This is similar to how AIX traditionally builds its shared libraries.
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D"\$CC $shared_flag"' -o $output_=
objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$e=
xport_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$=
release.a $output_objdir/$soname'
-      fi
-    fi
-    ;;
-
-  beos*)
-    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; th=
en
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=3Dunsupported
-      # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-      # support --undefined.  This deserves some investigation.  FIXME
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -nostart $libobjs $deplibs $c=
ompiler_flags ${wl}-soname $wl$soname -o $lib'
-    else
-      _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    fi
-    ;;
-
-  chorus*)
-    case $cc_basename in
-      *)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-    esac
-    ;;
-
-  cygwin* | mingw* | pw32*)
-    # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless,
-    # as there is no search path for DLLs.
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-    _LT_AC_TAGVAR(allow_undefined_flag, $1)=3Dunsupported
-    _LT_AC_TAGVAR(always_export_symbols, $1)=3Dno
-    _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=3Dyes
-
-    if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib $predep_obj=
ects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$=
soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      # If the export-symbols file already is a .def file (1st line
-      # is EXPORTS), use it as is; otherwise, prepend...
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'if test "x`$SED 1q $export=
_symbols`" =3D xEXPORTS; then
-	cp $export_symbols $output_objdir/$soname.def;
-      else
-	echo EXPORTS > $output_objdir/$soname.def;
-	cat $export_symbols >> $output_objdir/$soname.def;
-      fi~
-      $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $li=
bobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $=
{wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-    else
-      _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    fi
-  ;;
-      darwin* | rhapsody*)
-        case $host_os in
-        rhapsody* | darwin1.[[012]])
-         _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-undefined ${wl}s=
uppress'
-         ;;
-       *) # Darwin 1.3 on
-         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
-           _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-flat_namespace=
 ${wl}-undefined ${wl}suppress'
-         else
-           case ${MACOSX_DEPLOYMENT_TARGET} in
-             10.[[012]])
-               _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-flat_names=
pace ${wl}-undefined ${wl}suppress'
-               ;;
-             10.*)
-               _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-undefined =
${wl}dynamic_lookup'
-               ;;
-           esac
-         fi
-         ;;
-        esac
-      _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_automatic, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dunsupported
-      _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D''
-      _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-
-    if test "$GXX" =3D yes ; then
-      lt_int_apple_cc_single_mod=3Dno
-      output_verbose_link_cmd=3D'echo'
-      if $CC -dumpspecs 2>&1 | $EGREP 'single_module' >/dev/null ; then
-       lt_int_apple_cc_single_mod=3Dyes
-      fi
-      if test "X$lt_int_apple_cc_single_mod" =3D Xyes ; then
-       _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -dynamiclib -single_module $=
allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags -install_nam=
e $rpath/$soname $verstring'
-      else
-          _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -r -keep_private_externs =
-nostdlib -o ${lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag=
 -o $lib ${lib}-master.o $deplibs $compiler_flags -install_name $rpath/$son=
ame $verstring'
-        fi
-        _LT_AC_TAGVAR(module_cmds, $1)=3D'$CC $allow_undefined_flag -o $li=
b -bundle $libobjs $deplibs$compiler_flags'
-        # Don't fix this by using the ld -exported_symbols_list flag, it d=
oesn't exist in older darwin lds
-          if test "X$lt_int_apple_cc_single_mod" =3D Xyes ; then
-            _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e =
"s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${lib=
name}-symbols.expsym~$CC -dynamiclib -single_module $allow_undefined_flag -=
o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$soname $vers=
tring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          else
-            _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e =
"s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${lib=
name}-symbols.expsym~$CC -r -keep_private_externs -nostdlib -o ${lib}-maste=
r.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o =
$deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s =
$output_objdir/${libname}-symbols.expsym ${lib}'
-          fi
-            _LT_AC_TAGVAR(module_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e "=
s,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libn=
ame}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $de=
plibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${l=
ib}'
-      else
-      case $cc_basename in
-        xlc*)
-         output_verbose_link_cmd=3D'echo'
-          _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -qmkshrobj ${wl}-single_m=
odule $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}=
-install_name ${wl}`echo $rpath/$soname` $verstring'
-          _LT_AC_TAGVAR(module_cmds, $1)=3D'$CC $allow_undefined_flag -o $=
lib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it=
 doesn't exist in older darwin lds
-          _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e "s=
,^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libna=
me}-symbols.expsym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag=
 -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$=
soname $verstring~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          _LT_AC_TAGVAR(module_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e "s,=
^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libnam=
e}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $depl=
ibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib=
}'
-          ;;
-       *)
-         _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-          ;;
-      esac
-      fi
-        ;;
-
-  dgux*)
-    case $cc_basename in
-      ec++*)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      ghcx*)
-	# Green Hills C++ Compiler
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-    esac
-    ;;
-  freebsd[[12]]*)
-    # C++ shared libraries reported to be fairly broken before switch to E=
LF
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-  freebsd-elf*)
-    _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-    ;;
-  freebsd* | kfreebsd*-gnu | dragonfly*)
-    # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
-    # conventions
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dyes
-    ;;
-  gnu*)
-    ;;
-  hpux9*)
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}+b ${wl}$libdir'
-    _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-    _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-    _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes # Not in the search PATH,
-				# but as the default
-				# location of the library.
-
-    case $cc_basename in
-    CC*)
-      # FIXME: insert proper C++ library support
-      _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      ;;
-    aCC*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$rm $output_objdir/$soname~$CC -b=
 ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $li=
bobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname=
 =3D $lib || mv $output_objdir/$soname $lib'
-      # Commands to make compiler produce verbose output that lists
-      # what "hidden" libraries, object files and flags are used when
-      # linking a shared library.
-      #
-      # There doesn't appear to be a way to prevent this compiler from
-      # explicitly linking system object files so we need to strip them
-      # from the output so that they don't get included in the library
-      # dependencies.
-      output_verbose_link_cmd=3D'templist=3D`($CC -b $CFLAGS -v conftest.$=
objext 2>&1) | grep "[[-]]L"`; list=3D""; for z in $templist; do case $z in=
 conftest.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z";;e=
sac; done; echo $list'
-      ;;
-    *)
-      if test "$GXX" =3D yes; then
-        _LT_AC_TAGVAR(archive_cmds, $1)=3D'$rm $output_objdir/$soname~$CC =
-shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$son=
ame $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test=
 $output_objdir/$soname =3D $lib || mv $output_objdir/$soname $lib'
-      else
-        # FIXME: insert proper C++ library support
-        _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      fi
-      ;;
-    esac
-    ;;
-  hpux10*|hpux11*)
-    if test $with_gnu_ld =3D no; then
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}+b ${wl}$libdir'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-      case $host_cpu in
-      hppa*64*|ia64*)
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=3D'+b $libdir'
-        ;;
-      *)
-	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-        ;;
-      esac
-    fi
-    case $host_cpu in
-    hppa*64*|ia64*)
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-    *)
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes # Not in the search PATH,
-					      # but as the default
-					      # location of the library.
-      ;;
-    esac
-
-    case $cc_basename in
-      CC*)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      aCC*)
-	case $host_cpu in
-	hppa*64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -b ${wl}+h ${wl}$soname -o $lib =
$predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+no=
defaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $co=
mpiler_flags'
-	  ;;
-	*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+b =
${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_obj=
ects $compiler_flags'
-	  ;;
-	esac
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`($CC -b $CFLAGS -v conftest.$objex=
t 2>&1) | grep "\-L"`; list=3D""; for z in $templist; do case $z in conftes=
t.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z";;esac; don=
e; echo $list'
-	;;
-      *)
-	if test "$GXX" =3D yes; then
-	  if test $with_gnu_ld =3D no; then
-	    case $host_cpu in
-	    hppa*64*)
-	      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib -fPIC ${wl=
}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects=
 $compiler_flags'
-	      ;;
-	    ia64*)
-	      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib -fPIC ${wl=
}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $dep=
libs $postdep_objects $compiler_flags'
-	      ;;
-	    *)
-	      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib -fPIC ${wl=
}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libo=
bjs $deplibs $postdep_objects $compiler_flags'
-	      ;;
-	    esac
-	  fi
-	else
-	  # FIXME: insert proper C++ library support
-	  _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	fi
-	;;
-    esac
-    ;;
-  interix3*)
-    _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-    _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-    # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-    # Instead, shared libraries are loaded at an image base (0x10000000 by
-    # default) and relocated if they conflict, which is a slow very memory
-    # consuming and fragmenting process.  To avoid this, we pick a random,
-    # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-    # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $pic_flag $libobjs $dep=
libs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} %=
 4096 / 2 \* 262144 + 1342177280` -o $lib'
-    _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'sed "s,^,_," $export_symbols=
 >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $co=
mpiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$son=
ame.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342=
177280` -o $lib'
-    ;;
-  irix5* | irix6*)
-    case $cc_basename in
-      CC*)
-	# SGI C++
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -all -multigot $predep_obj=
ects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `te=
st -n "$verstring" && echo -set_version $verstring` -update_registry ${outp=
ut_objdir}/so_locations -o $lib'
-
-	# Archives containing C++ object files must be created using
-	# "CC -ar", where "CC" is the IRIX C++ compiler.  This is
-	# necessary to make sure instantiated templates are included
-	# in the archive.
-	_LT_AC_TAGVAR(old_archive_cmds, $1)=3D'$CC -ar -WR,-u -o $oldlib $oldobjs'
-	;;
-      *)
-	if test "$GXX" =3D yes; then
-	  if test "$with_gnu_ld" =3D no; then
-	    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib $predep_obje=
cts $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$s=
oname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl=
}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-	  else
-	    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib $predep_obje=
cts $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$s=
oname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $=
lib'
-	  fi
-	fi
-	_LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-	;;
-    esac
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$libd=
ir'
-    _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-    ;;
-  linux*)
-    case $cc_basename in
-      KCC*)
-	# Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	# KCC will only create a shared library if the output file
-	# ends with ".so" (or ".sl" for HP-UX), so rename the library
-	# to its proper name (with version) after linking.
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'tempext=3D`echo $shared_ext | $SED -e =
'\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $SED -e =
"s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_o=
bjects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'tempext=3D`echo $shared_ext | $=
SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $=
SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $po=
stdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-sy=
mbols-file,$export_symbols; mv \$templib $lib'
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC $CFLAGS -v conftest.$objext -o=
 libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; li=
st=3D""; for z in $templist; do case $z in conftest.$objext) list=3D"$list =
$z";; *.$objext);; *) list=3D"$list $z";;esac; done; echo $list'
-
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}--rpath,$libdir'
-	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}--export-dynamic'
-
-	# Archives containing C++ object files must be created using
-	# "CC -Bstatic", where "CC" is the KAI C++ compiler.
-	_LT_AC_TAGVAR(old_archive_cmds, $1)=3D'$CC -Bstatic -o $oldlib $oldobjs'
-	;;
-      icpc*)
-	# Intel C++
-	with_gnu_ld=3Dyes
-	# version 8.0 and above of icpc choke on multiply defined symbols
-	# if we add $predep_objects and $postdep_objects, however 7.1 and
-	# earlier do not add the objects themselves.
-	case `$CC -V 2>&1` in
-	*"Version 7."*)
-  	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $predep_objects $libob=
js $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $li=
b'
-  	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $predep_objects=
 $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname=
 ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
-	  ;;
-	*)  # Version 8.0 or newer
-	  tmp_idyn=3D
-	  case $host_cpu in
-	    ia64*) tmp_idyn=3D' -i_dynamic';;
-	  esac
-  	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared'"$tmp_idyn"' $libobjs =
$deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared'"$tmp_idyn"' $lib=
objs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-=
file $wl$export_symbols -o $lib'
-	  ;;
-	esac
-	_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}--export-dynamic'
-	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'${wl}--whole-archive$conven=
ience ${wl}--no-whole-archive'
-	;;
-      pgCC*)
-        # Portland Group C++ compiler
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $pic_flag $predep_objects =
$libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$sonam=
e -o $lib'
-  	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $pic_flag $predep=
_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${=
wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib'
-
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}--rpath ${wl}$libdir'
-	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}--export-dynamic'
-	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'${wl}--whole-archive`for co=
nv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_c=
onvenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archi=
ve'
-        ;;
-      cxx*)
-	# Compaq C++
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $predep_objects $libobjs $=
deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $predep_objects $li=
bobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o=
 $lib ${wl}-retain-symbols-file $wl$export_symbols'
-
-	runpath_var=3DLD_RUN_PATH
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-rpath $libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC -shared $CFLAGS -v conftest.$o=
bjext 2>&1 | grep "ld"`; templist=3D`echo $templist | $SED "s/\(^.*ld.*\)\(=
 .*ld .*$\)/\1/"`; list=3D""; for z in $templist; do case $z in conftest.$o=
bjext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z";;esac; done; e=
cho $list'
-	;;
-    esac
-    ;;
-  lynxos*)
-    # FIXME: insert proper C++ library support
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-  m88k*)
-    # FIXME: insert proper C++ library support
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-  mvs*)
-    case $cc_basename in
-      cxx*)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-    esac
-    ;;
-  netbsd*)
-    if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -Bshareable  -o $lib $predep_=
objects $libobjs $deplibs $postdep_objects $linker_flags'
-      wlarc=3D
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-R$libdir'
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-    fi
-    # Workaround some broken pre-1.5 toolchains
-    output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&=
1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
-    ;;
-  openbsd2*)
-    # C++ shared libraries are fairly broken
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-  openbsd*)
-    _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-    _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $pic_flag $predep_objec=
ts $libobjs $deplibs $postdep_objects $compiler_flags -o $lib'
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-    if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_o=
s-$host_cpu" =3D "openbsd2.8-powerpc"; then
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $pic_flag $pre=
dep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain=
-symbols-file,$export_symbols -o $lib'
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-      _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D"$wlarc"'--whole-archiv=
e$convenience '"$wlarc"'--no-whole-archive'
-    fi
-    output_verbose_link_cmd=3D'echo'
-    ;;
-  osf3*)
-    case $cc_basename in
-      KCC*)
-	# Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	# KCC will only create a shared library if the output file
-	# ends with ".so" (or ".sl" for HP-UX), so rename the library
-	# to its proper name (with version) after linking.
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'tempext=3D`echo $shared_ext | $SED -e =
'\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $SED -e =
"s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_o=
bjects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	# Archives containing C++ object files must be created using
-	# "CC -Bstatic", where "CC" is the KAI C++ compiler.
-	_LT_AC_TAGVAR(old_archive_cmds, $1)=3D'$CC -Bstatic -o $oldlib $oldobjs'
-
-	;;
-      RCC*)
-	# Rational C++ 2.4.1
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      cxx*)
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' ${wl}-expect_unresolved ${wl}=
\*'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared${allow_undefined_flag} $pr=
edep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-sonam=
e $soname `test -n "$verstring" && echo ${wl}-set_version $verstring` -upda=
te_registry ${output_objdir}/so_locations -o $lib'
-
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC -shared $CFLAGS -v conftest.$o=
bjext 2>&1 | grep "ld" | grep -v "ld:"`; templist=3D`echo $templist | $SED =
"s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=3D""; for z in $templist; do case $z=
 in conftest.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z"=
;;esac; done; echo $list'
-	;;
-      *)
-	if test "$GXX" =3D yes && test "$with_gnu_ld" =3D no; then
-	  _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' ${wl}-expect_unresolved ${w=
l}\*'
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib ${allow_undefi=
ned_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flag=
s ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version=
 ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations =
-o $lib'
-
-	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$libdi=
r'
-	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	  # Commands to make compiler produce verbose output that lists
-	  # what "hidden" libraries, object files and flags are used when
-	  # linking a shared library.
-	  output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&1=
 | grep "\-L"'
-
-	else
-	  # FIXME: insert proper C++ library support
-	  _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	fi
-	;;
-    esac
-    ;;
-  osf4* | osf5*)
-    case $cc_basename in
-      KCC*)
-	# Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	# KCC will only create a shared library if the output file
-	# ends with ".so" (or ".sl" for HP-UX), so rename the library
-	# to its proper name (with version) after linking.
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'tempext=3D`echo $shared_ext | $SED -e =
'\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $SED -e =
"s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_o=
bjects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib'
-
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	# Archives containing C++ object files must be created using
-	# the KAI C++ compiler.
-	_LT_AC_TAGVAR(old_archive_cmds, $1)=3D'$CC -o $oldlib $oldobjs'
-	;;
-      RCC*)
-	# Rational C++ 2.4.1
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      cxx*)
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' -expect_unresolved \*'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared${allow_undefined_flag} $pr=
edep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -sona=
me $soname `test -n "$verstring" && echo -set_version $verstring` -update_r=
egistry ${output_objdir}/so_locations -o $lib'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'for i in `cat $export_symbols`;=
 do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~
-	  echo "-hidden">> $lib.exp~
-	  $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $pos=
tdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp =
 `test -n "$verstring" && echo -set_version	$verstring` -update_registry ${=
output_objdir}/so_locations -o $lib~
-	  $rm $lib.exp'
-
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-rpath $libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC -shared $CFLAGS -v conftest.$o=
bjext 2>&1 | grep "ld" | grep -v "ld:"`; templist=3D`echo $templist | $SED =
"s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=3D""; for z in $templist; do case $z=
 in conftest.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z"=
;;esac; done; echo $list'
-	;;
-      *)
-	if test "$GXX" =3D yes && test "$with_gnu_ld" =3D no; then
-	  _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' ${wl}-expect_unresolved ${w=
l}\*'
-	 _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib ${allow_undefin=
ed_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags=
 ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-s=
et_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_=
locations -o $lib'
-
-	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$libdi=
r'
-	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	  # Commands to make compiler produce verbose output that lists
-	  # what "hidden" libraries, object files and flags are used when
-	  # linking a shared library.
-	  output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&1=
 | grep "\-L"'
-
-	else
-	  # FIXME: insert proper C++ library support
-	  _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	fi
-	;;
-    esac
-    ;;
-  psos*)
-    # FIXME: insert proper C++ library support
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-  sunos4*)
-    case $cc_basename in
-      CC*)
-	# Sun C++ 4.x
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      lcc*)
-	# Lucid
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-    esac
-    ;;
-  solaris*)
-    case $cc_basename in
-      CC*)
-	# Sun C++ 4.2, 5.x and Centerline C++
-        _LT_AC_TAGVAR(archive_cmds_need_lc,$1)=3Dyes
-	_LT_AC_TAGVAR(no_undefined_flag, $1)=3D' -zdefs'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -G${allow_undefined_flag}  -h$sona=
me -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_fla=
gs'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$echo "{ global:" > $lib.exp~ca=
t $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };=
" >> $lib.exp~
-	$CC -G${allow_undefined_flag}  ${wl}-M ${wl}$lib.exp -h$soname -o $lib $p=
redep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.e=
xp'
-
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-R$libdir'
-	_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-	case $host_os in
-	  solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-	  *)
-	    # The C++ compiler is used as linker so we must use $wl
-	    # flag to pass the commands to the underlying system
-	    # linker. We must also pass each convience library through
-	    # to the system linker between allextract/defaultextract.
-	    # The C++ compiler will combine linker options so we
-	    # cannot just pass the convience library names through
-	    # without $wl.
-	    # Supported since Solaris 2.6 (maybe 2.5.1?)
-	    _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'${wl}-z ${wl}allextract=
`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=3D\"=
$new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}de=
faultextract'
-	    ;;
-	esac
-	_LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-
-	output_verbose_link_cmd=3D'echo'
-
-	# Archives containing C++ object files must be created using
-	# "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	# necessary to make sure instantiated templates are included
-	# in the archive.
-	_LT_AC_TAGVAR(old_archive_cmds, $1)=3D'$CC -xar -o $oldlib $oldobjs'
-	;;
-      gcx*)
-	# Green Hills C++ Compiler
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $predep_objects $libobjs $=
deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-
-	# The C++ compiler must be used to create the archive.
-	_LT_AC_TAGVAR(old_archive_cmds, $1)=3D'$CC $LDFLAGS -archive -o $oldlib $=
oldobjs'
-	;;
-      *)
-	# GNU C++ compiler with Solaris linker
-	if test "$GXX" =3D yes && test "$with_gnu_ld" =3D no; then
-	  _LT_AC_TAGVAR(no_undefined_flag, $1)=3D' ${wl}-z ${wl}defs'
-	  if $CC --version | grep -v '^2\.7' > /dev/null; then
-	    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -nostdlib $LDFLAGS $pr=
edep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl=
$soname -o $lib'
-	    _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$echo "{ global:" > $lib.ex=
p~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *=
; };" >> $lib.exp~
-		$CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libob=
js $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    output_verbose_link_cmd=3D"$CC -shared $CFLAGS -v conftest.$objext 2>=
&1 | grep \"\-L\""
-	  else
-	    # g++ 2.7 appears to require `-G' NOT `-shared' on this
-	    # platform.
-	    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -G -nostdlib $LDFLAGS $predep_=
objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$sona=
me -o $lib'
-	    _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$echo "{ global:" > $lib.ex=
p~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *=
; };" >> $lib.exp~
-		$CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $d=
eplibs $postdep_objects $compiler_flags~$rm $lib.exp'
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    output_verbose_link_cmd=3D"$CC -G $CFLAGS -v conftest.$objext 2>&1 | =
grep \"\-L\""
-	  fi
-
-	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-R $wl$libdir'
-	fi
-	;;
-    esac
-    ;;
-  sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7*=
 | sco3.2v5.0.[[024]]*)
-    _LT_AC_TAGVAR(no_undefined_flag, $1)=3D'${wl}-z,text'
-    _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-    _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-    runpath_var=3D'LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -G ${wl}-h,$soname -o $lib $libobj=
s $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -G ${wl}-Bexport:$export_sy=
mbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-      *)
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared ${wl}-h,$soname -o $lib $l=
ibobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared ${wl}-Bexport:$expo=
rt_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-    esac
-    ;;
-  sysv5* | sco3.2v5* | sco5v6*)
-    # Note: We can NOT use -z defs as we might desire, because we do not
-    # link with -lc, and that would cause any symbols used from libc to
-    # always be unresolved, which means just about no library would
-    # ever link correctly.  If we're not using GNU ld we use -z text
-    # though, which does catch some bad symbols but isn't as heavy-handed
-    # as -z defs.
-    # For security reasons, it is highly recommended that you always
-    # use absolute paths for naming shared libraries, and exclude the
-    # DT_RUNPATH tag from executables and libraries.  But doing so
-    # requires that you compile everything twice, which is a pain.
-    # So that behaviour is only enabled if SCOABSPATH is set to a
-    # non-empty value in the environment.  Most likely only useful for
-    # creating official distributions of packages.
-    # This is a hack until libtool officially supports absolute path
-    # names for shared libraries.
-    _LT_AC_TAGVAR(no_undefined_flag, $1)=3D'${wl}-z,text'
-    _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-z,nodefs'
-    _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-    _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'`test -z "$SCOABSPATH"=
 && echo ${wl}-R,$libdir`'
-    _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D':'
-    _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-Bexport'
-    runpath_var=3D'LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -G ${wl}-h,\${SCOABSPATH:+${instal=
l_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -G ${wl}-Bexport:$export_sy=
mbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $d=
eplibs $compiler_flags'
-	;;
-      *)
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared ${wl}-h,\${SCOABSPATH:+${i=
nstall_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared ${wl}-Bexport:$expo=
rt_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libob=
js $deplibs $compiler_flags'
-	;;
-    esac
-    ;;
-  tandem*)
-    case $cc_basename in
-      NCC*)
-	# NonStop-UX NCC 3.20
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	;;
-    esac
-    ;;
-  vxworks*)
-    # FIXME: insert proper C++ library support
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-  *)
-    # FIXME: insert proper C++ library support
-    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-    ;;
-esac
-AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)])
-test "$_LT_AC_TAGVAR(ld_shlibs, $1)" =3D no && can_build_shared=3Dno
-
-_LT_AC_TAGVAR(GCC, $1)=3D"$GXX"
-_LT_AC_TAGVAR(LD, $1)=3D"$LD"
-
-AC_LIBTOOL_POSTDEP_PREDEP($1)
-AC_LIBTOOL_PROG_COMPILER_PIC($1)
-AC_LIBTOOL_PROG_CC_C_O($1)
-AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
-AC_LIBTOOL_PROG_LD_SHLIBS($1)
-AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
-AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
-
-AC_LIBTOOL_CONFIG($1)
-
-AC_LANG_POP
-CC=3D$lt_save_CC
-LDCXX=3D$LD
-LD=3D$lt_save_LD
-GCC=3D$lt_save_GCC
-with_gnu_ldcxx=3D$with_gnu_ld
-with_gnu_ld=3D$lt_save_with_gnu_ld
-lt_cv_path_LDCXX=3D$lt_cv_path_LD
-lt_cv_path_LD=3D$lt_save_path_LD
-lt_cv_prog_gnu_ldcxx=3D$lt_cv_prog_gnu_ld
-lt_cv_prog_gnu_ld=3D$lt_save_with_gnu_ld
-])# AC_LIBTOOL_LANG_CXX_CONFIG
-
-# AC_LIBTOOL_POSTDEP_PREDEP([TAGNAME])
-# ------------------------------------
-# Figure out "hidden" library dependencies from verbose
-# compiler output when linking a shared library.
-# Parse the compiler output and extract the necessary
-# objects, libraries and library flags.
-AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP],[
-dnl we can't use the lt_simple_compile_test_code here,
-dnl because it contains code intended for an executable,
-dnl not a library.  It's possible we should let each
-dnl tag define a new lt_????_link_test_code variable,
-dnl but it's only used here...
-ifelse([$1],[],[cat > conftest.$ac_ext <<EOF
-int a;
-void foo (void) { a =3D 0; }
-EOF
-],[$1],[CXX],[cat > conftest.$ac_ext <<EOF
-class Foo
-{
-public:
-  Foo (void) { a =3D 0; }
-private:
-  int a;
-};
-EOF
-],[$1],[F77],[cat > conftest.$ac_ext <<EOF
-      subroutine foo
-      implicit none
-      integer*4 a
-      a=3D0
-      return
-      end
-EOF
-],[$1],[GCJ],[cat > conftest.$ac_ext <<EOF
-public class foo {
-  private int a;
-  public void bar (void) {
-    a =3D 0;
-  }
-};
-EOF
-])
-dnl Parse the compiler output and extract the necessary
-dnl objects, libraries and library flags.
-if AC_TRY_EVAL(ac_compile); then
-  # Parse the compiler output and extract the necessary
-  # objects, libraries and library flags.
-
-  # Sentinel used to keep track of whether or not we are before
-  # the conftest object file.
-  pre_test_object_deps_done=3Dno
-
-  # The `*' in the case matches for architectures that use `case' in
-  # $output_verbose_cmd can trigger glob expansion during the loop
-  # eval without this substitution.
-  output_verbose_link_cmd=3D`$echo "X$output_verbose_link_cmd" | $Xsed -e =
"$no_glob_subst"`
-
-  for p in `eval $output_verbose_link_cmd`; do
-    case $p in
-
-    -L* | -R* | -l*)
-       # Some compilers place space between "-{L,R}" and the path.
-       # Remove the space.
-       if test $p =3D "-L" \
-	  || test $p =3D "-R"; then
-	 prev=3D$p
-	 continue
-       else
-	 prev=3D
-       fi
-
-       if test "$pre_test_object_deps_done" =3D no; then
-	 case $p in
-	 -L* | -R*)
-	   # Internal compiler library paths should come after those
-	   # provided the user.  The postdeps already come after the
-	   # user supplied libs so there is no need to process them.
-	   if test -z "$_LT_AC_TAGVAR(compiler_lib_search_path, $1)"; then
-	     _LT_AC_TAGVAR(compiler_lib_search_path, $1)=3D"${prev}${p}"
-	   else
-	     _LT_AC_TAGVAR(compiler_lib_search_path, $1)=3D"${_LT_AC_TAGVAR(compi=
ler_lib_search_path, $1)} ${prev}${p}"
-	   fi
-	   ;;
-	 # The "-l" case would never come before the object being
-	 # linked, so don't bother handling this case.
-	 esac
-       else
-	 if test -z "$_LT_AC_TAGVAR(postdeps, $1)"; then
-	   _LT_AC_TAGVAR(postdeps, $1)=3D"${prev}${p}"
-	 else
-	   _LT_AC_TAGVAR(postdeps, $1)=3D"${_LT_AC_TAGVAR(postdeps, $1)} ${prev}$=
{p}"
-	 fi
-       fi
-       ;;
-
-    *.$objext)
-       # This assumes that the test object file only shows up
-       # once in the compiler output.
-       if test "$p" =3D "conftest.$objext"; then
-	 pre_test_object_deps_done=3Dyes
-	 continue
-       fi
-
-       if test "$pre_test_object_deps_done" =3D no; then
-	 if test -z "$_LT_AC_TAGVAR(predep_objects, $1)"; then
-	   _LT_AC_TAGVAR(predep_objects, $1)=3D"$p"
-	 else
-	   _LT_AC_TAGVAR(predep_objects, $1)=3D"$_LT_AC_TAGVAR(predep_objects, $1=
) $p"
-	 fi
-       else
-	 if test -z "$_LT_AC_TAGVAR(postdep_objects, $1)"; then
-	   _LT_AC_TAGVAR(postdep_objects, $1)=3D"$p"
-	 else
-	   _LT_AC_TAGVAR(postdep_objects, $1)=3D"$_LT_AC_TAGVAR(postdep_objects, =
$1) $p"
-	 fi
-       fi
-       ;;
-
-    *) ;; # Ignore the rest.
-
-    esac
-  done
-
-  # Clean up.
-  rm -f a.out a.exe
-else
-  echo "libtool.m4: error: problem compiling $1 test program"
-fi
-
-$rm -f confest.$objext
-
-# PORTME: override above test on systems where it is broken
-ifelse([$1],[CXX],
-[case $host_os in
-interix3*)
-  # Interix 3.5 installs completely hosed .la files for C++, so rather than
-  # hack all around it, let's just trust "g++" to DTRT.
-  _LT_AC_TAGVAR(predep_objects,$1)=3D
-  _LT_AC_TAGVAR(postdep_objects,$1)=3D
-  _LT_AC_TAGVAR(postdeps,$1)=3D
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC*)
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    _LT_AC_TAGVAR(postdeps,$1)=3D'-lCstd -lCrun'
-    ;;
-  esac
-  ;;
-esac
-])
-
-case " $_LT_AC_TAGVAR(postdeps, $1) " in
-*" -lc "*) _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno ;;
-esac
-])# AC_LIBTOOL_POSTDEP_PREDEP
-
-# AC_LIBTOOL_LANG_F77_CONFIG
-# --------------------------
-# Ensure that the configuration vars for the C compiler are
-# suitably defined.  Those variables are subsequently used by
-# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
-AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG], [_LT_AC_LANG_F77_CONFIG(F77)])
-AC_DEFUN([_LT_AC_LANG_F77_CONFIG],
-[AC_REQUIRE([AC_PROG_F77])
-AC_LANG_PUSH(Fortran 77)
-
-_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D
-_LT_AC_TAGVAR(always_export_symbols, $1)=3Dno
-_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D
-_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D
-_LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D
-_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=3D
-_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D
-_LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dno
-_LT_AC_TAGVAR(hardcode_automatic, $1)=3Dno
-_LT_AC_TAGVAR(module_cmds, $1)=3D
-_LT_AC_TAGVAR(module_expsym_cmds, $1)=3D
-_LT_AC_TAGVAR(link_all_deplibs, $1)=3Dunknown
-_LT_AC_TAGVAR(old_archive_cmds, $1)=3D$old_archive_cmds
-_LT_AC_TAGVAR(no_undefined_flag, $1)=3D
-_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D
-_LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=3Dno
-
-# Source file extension for f77 test sources.
-ac_ext=3Df
-
-# Object file extension for compiled f77 test sources.
-objext=3Do
-_LT_AC_TAGVAR(objext, $1)=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"      subroutine t\n      return\n      end=
\n"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D"      program t\n      end\n"
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_AC_SYS_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D"$CC"
-CC=3D${F77-"f77"}
-compiler=3D$CC
-_LT_AC_TAGVAR(compiler, $1)=3D$CC
-_LT_CC_BASENAME([$compiler])
-
-AC_MSG_CHECKING([if libtool supports shared libraries])
-AC_MSG_RESULT([$can_build_shared])
-
-AC_MSG_CHECKING([whether to build shared libraries])
-test "$can_build_shared" =3D "no" && enable_shared=3Dno
-
-# On AIX, shared libraries and static libraries use the same namespace, and
-# are all built from PIC.
-case $host_os in
-aix3*)
-  test "$enable_shared" =3D yes && enable_static=3Dno
-  if test -n "$RANLIB"; then
-    archive_cmds=3D"$archive_cmds~\$RANLIB \$lib"
-    postinstall_cmds=3D'$RANLIB $lib'
-  fi
-  ;;
-aix4* | aix5*)
-  if test "$host_cpu" !=3D ia64 && test "$aix_use_runtimelinking" =3D no ;=
 then
-    test "$enable_shared" =3D yes && enable_static=3Dno
-  fi
-  ;;
-esac
-AC_MSG_RESULT([$enable_shared])
-
-AC_MSG_CHECKING([whether to build static libraries])
-# Make sure either enable_shared or enable_static is yes.
-test "$enable_shared" =3D yes || enable_static=3Dyes
-AC_MSG_RESULT([$enable_static])
-
-_LT_AC_TAGVAR(GCC, $1)=3D"$G77"
-_LT_AC_TAGVAR(LD, $1)=3D"$LD"
-
-AC_LIBTOOL_PROG_COMPILER_PIC($1)
-AC_LIBTOOL_PROG_CC_C_O($1)
-AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
-AC_LIBTOOL_PROG_LD_SHLIBS($1)
-AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
-AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
-
-AC_LIBTOOL_CONFIG($1)
-
-AC_LANG_POP
-CC=3D"$lt_save_CC"
-])# AC_LIBTOOL_LANG_F77_CONFIG
-
-
-# AC_LIBTOOL_LANG_GCJ_CONFIG
-# --------------------------
-# Ensure that the configuration vars for the C compiler are
-# suitably defined.  Those variables are subsequently used by
-# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
-AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG], [_LT_AC_LANG_GCJ_CONFIG(GCJ)])
-AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG],
-[AC_LANG_SAVE
-
-# Source file extension for Java test sources.
-ac_ext=3Djava
-
-# Object file extension for compiled Java test sources.
-objext=3Do
-_LT_AC_TAGVAR(objext, $1)=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"class foo {}\n"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D'public class conftest { public static void mai=
n(String[[]] argv) {}; }\n'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_AC_SYS_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D"$CC"
-CC=3D${GCJ-"gcj"}
-compiler=3D$CC
-_LT_AC_TAGVAR(compiler, $1)=3D$CC
-_LT_CC_BASENAME([$compiler])
-
-# GCJ did not exist at the time GCC didn't implicitly link libc in.
-_LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-
-_LT_AC_TAGVAR(old_archive_cmds, $1)=3D$old_archive_cmds
-
-AC_LIBTOOL_PROG_COMPILER_NO_RTTI($1)
-AC_LIBTOOL_PROG_COMPILER_PIC($1)
-AC_LIBTOOL_PROG_CC_C_O($1)
-AC_LIBTOOL_SYS_HARD_LINK_LOCKS($1)
-AC_LIBTOOL_PROG_LD_SHLIBS($1)
-AC_LIBTOOL_SYS_DYNAMIC_LINKER($1)
-AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH($1)
-
-AC_LIBTOOL_CONFIG($1)
-
-AC_LANG_RESTORE
-CC=3D"$lt_save_CC"
-])# AC_LIBTOOL_LANG_GCJ_CONFIG
-
-
-# AC_LIBTOOL_LANG_RC_CONFIG
-# -------------------------
-# Ensure that the configuration vars for the Windows resource compiler are
-# suitably defined.  Those variables are subsequently used by
-# AC_LIBTOOL_CONFIG to write the compiler configuration to `libtool'.
-AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG], [_LT_AC_LANG_RC_CONFIG(RC)])
-AC_DEFUN([_LT_AC_LANG_RC_CONFIG],
-[AC_LANG_SAVE
-
-# Source file extension for RC test sources.
-ac_ext=3Drc
-
-# Object file extension for compiled RC test sources.
-objext=3Do
-_LT_AC_TAGVAR(objext, $1)=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D'sample MENU { MENUITEM "&Soup", 100, CHECKE=
D }\n'
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D"$lt_simple_compile_test_code"
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-_LT_AC_SYS_COMPILER
-
-# save warnings/boilerplate of simple test code
-_LT_COMPILER_BOILERPLATE
-_LT_LINKER_BOILERPLATE
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D"$CC"
-CC=3D${RC-"windres"}
-compiler=3D$CC
-_LT_AC_TAGVAR(compiler, $1)=3D$CC
-_LT_CC_BASENAME([$compiler])
-_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)=3Dyes
-
-AC_LIBTOOL_CONFIG($1)
-
-AC_LANG_RESTORE
-CC=3D"$lt_save_CC"
-])# AC_LIBTOOL_LANG_RC_CONFIG
-
-
-# AC_LIBTOOL_CONFIG([TAGNAME])
-# ----------------------------
-# If TAGNAME is not passed, then create an initial libtool script
-# with a default configuration from the untagged config vars.  Otherwise
-# add code to config.status for appending the configuration named by
-# TAGNAME from the matching tagged config vars.
-AC_DEFUN([AC_LIBTOOL_CONFIG],
-[# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our comm=
ands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTC=
FLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    _LT_AC_TAGVAR(compiler, $1) \
-    _LT_AC_TAGVAR(CC, $1) \
-    _LT_AC_TAGVAR(LD, $1) \
-    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1) \
-    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1) \
-    _LT_AC_TAGVAR(lt_prog_compiler_static, $1) \
-    _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) \
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1) \
-    _LT_AC_TAGVAR(thread_safe_flag_spec, $1) \
-    _LT_AC_TAGVAR(whole_archive_flag_spec, $1) \
-    _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1) \
-    _LT_AC_TAGVAR(old_archive_cmds, $1) \
-    _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) \
-    _LT_AC_TAGVAR(predep_objects, $1) \
-    _LT_AC_TAGVAR(postdep_objects, $1) \
-    _LT_AC_TAGVAR(predeps, $1) \
-    _LT_AC_TAGVAR(postdeps, $1) \
-    _LT_AC_TAGVAR(compiler_lib_search_path, $1) \
-    _LT_AC_TAGVAR(archive_cmds, $1) \
-    _LT_AC_TAGVAR(archive_expsym_cmds, $1) \
-    _LT_AC_TAGVAR(postinstall_cmds, $1) \
-    _LT_AC_TAGVAR(postuninstall_cmds, $1) \
-    _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) \
-    _LT_AC_TAGVAR(allow_undefined_flag, $1) \
-    _LT_AC_TAGVAR(no_undefined_flag, $1) \
-    _LT_AC_TAGVAR(export_symbols_cmds, $1) \
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) \
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1) \
-    _LT_AC_TAGVAR(hardcode_libdir_separator, $1) \
-    _LT_AC_TAGVAR(hardcode_automatic, $1) \
-    _LT_AC_TAGVAR(module_cmds, $1) \
-    _LT_AC_TAGVAR(module_expsym_cmds, $1) \
-    _LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1) \
-    _LT_AC_TAGVAR(exclude_expsyms, $1) \
-    _LT_AC_TAGVAR(include_expsyms, $1); do
-
-    case $var in
-    _LT_AC_TAGVAR(old_archive_cmds, $1) | \
-    _LT_AC_TAGVAR(old_archive_from_new_cmds, $1) | \
-    _LT_AC_TAGVAR(archive_cmds, $1) | \
-    _LT_AC_TAGVAR(archive_expsym_cmds, $1) | \
-    _LT_AC_TAGVAR(module_cmds, $1) | \
-    _LT_AC_TAGVAR(module_expsym_cmds, $1) | \
-    _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1) | \
-    _LT_AC_TAGVAR(export_symbols_cmds, $1) | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quot=
e_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
-      ;;
-    *)
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_s=
ubst\"\`\\\""
-      ;;
-    esac
-  done
-
-  case $lt_echo in
-  *'\[$]0 --fallback-echo"')
-    lt_echo=3D`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\[$]0 --fallback-echo=
"[$]/[$]0 --fallback-echo"/'`
-    ;;
-  esac
-
-ifelse([$1], [],
-  [cfgfile=3D"${ofile}T"
-  trap "$rm \"$cfgfile\"; exit 1" 1 2 15
-  $rm -f "$cfgfile"
-  AC_MSG_NOTICE([creating $ofile])],
-  [cfgfile=3D"$ofile"])
-
-  cat <<__EOF__ >> "$cfgfile"
-ifelse([$1], [],
-[#! $SHELL
-
-# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-buildi=
ng support services.
-# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP)
-# NOTE: Changes made to this file will be lost: look at ltmain.sh.
-#
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
-# Free Software Foundation, Inc.
-#
-# This file is part of GNU Libtool:
-# Originally by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301=
, USA.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# A sed program that does not truncate output.
-SED=3D$lt_SED
-
-# Sed that helps us avoid accidentally triggering echo(1) options like -n.
-Xsed=3D"$SED -e 1s/^X//"
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-# The names of the tagged configurations supported by this script.
-available_tags=3D
-
-# ### BEGIN LIBTOOL CONFIG],
-[# ### BEGIN LIBTOOL TAG CONFIG: $tagname])
-
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed=
 1q`:
-
-# Shell to use when invoking shell scripts.
-SHELL=3D$lt_SHELL
-
-# Whether or not to build shared libraries.
-build_libtool_libs=3D$enable_shared
-
-# Whether or not to build static libraries.
-build_old_libs=3D$enable_static
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=3D$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)
-
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=3D$_LT_AC_TAGVAR(enable_shared_wit=
h_static_runtimes, $1)
-
-# Whether or not to optimize for fast installation.
-fast_install=3D$enable_fast_install
-
-# The host system.
-host_alias=3D$host_alias
-host=3D$host
-host_os=3D$host_os
-
-# The build system.
-build_alias=3D$build_alias
-build=3D$build
-build_os=3D$build_os
-
-# An echo program that does not interpret backslashes.
-echo=3D$lt_echo
-
-# The archiver.
-AR=3D$lt_AR
-AR_FLAGS=3D$lt_AR_FLAGS
-
-# A C compiler.
-LTCC=3D$lt_LTCC
-
-# LTCC compiler flags.
-LTCFLAGS=3D$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=3D$lt_[]_LT_AC_TAGVAR(compiler, $1)
-
-# Is the compiler the GNU C compiler?
-with_gcc=3D$_LT_AC_TAGVAR(GCC, $1)
-
-# An ERE matcher.
-EGREP=3D$lt_EGREP
-
-# The linker used to build libraries.
-LD=3D$lt_[]_LT_AC_TAGVAR(LD, $1)
-
-# Whether we need hard or soft links.
-LN_S=3D$lt_LN_S
-
-# A BSD-compatible nm program.
-NM=3D$lt_NM
-
-# A symbol stripping program
-STRIP=3D$lt_STRIP
-
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=3D$MAGIC_CMD
-
-# Used on cygwin: DLL creation program.
-DLLTOOL=3D"$DLLTOOL"
-
-# Used on cygwin: object dumper.
-OBJDUMP=3D"$OBJDUMP"
-
-# Used on cygwin: assembler.
-AS=3D"$AS"
-
-# The name of the directory that contains temporary libtool files.
-objdir=3D$objdir
-
-# How to create reloadable object files.
-reload_flag=3D$lt_reload_flag
-reload_cmds=3D$lt_reload_cmds
-
-# How to pass a linker flag through the compiler.
-wl=3D$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)
-
-# Object file suffix (normally "o").
-objext=3D"$ac_objext"
-
-# Old archive suffix (normally "a").
-libext=3D"$libext"
-
-# Shared library suffix (normally ".so").
-shrext_cmds=3D'$shrext_cmds'
-
-# Executable file suffix (normally "").
-exeext=3D"$exeext"
-
-# Additional compiler flags for building library objects.
-pic_flag=3D$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)
-pic_mode=3D$pic_mode
-
-# What is the maximum length of a command?
-max_cmd_len=3D$lt_cv_sys_max_cmd_len
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=3D$lt_[]_LT_AC_TAGVAR(lt_cv_prog_compiler_c_o, $1)
-
-# Must we lock files when doing compilation?
-need_locks=3D$lt_need_locks
-
-# Do we need the lib prefix for modules?
-need_lib_prefix=3D$need_lib_prefix
-
-# Do we need a version for libraries?
-need_version=3D$need_version
-
-# Whether dlopen is supported.
-dlopen_support=3D$enable_dlopen
-
-# Whether dlopen of programs is supported.
-dlopen_self=3D$enable_dlopen_self
-
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=3D$enable_dlopen_self_static
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=3D$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_static, $1)
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=3D$lt_[]_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=3D$lt_[]_LT_AC_TAGVAR(export_dynamic_flag_spec, $=
1)
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=3D$lt_[]_LT_AC_TAGVAR(whole_archive_flag_spec, $1)
-
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=3D$lt_[]_LT_AC_TAGVAR(thread_safe_flag_spec, $1)
-
-# Library versioning type.
-version_type=3D$version_type
-
-# Format of library name prefix.
-libname_spec=3D$lt_libname_spec
-
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=3D$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=3D$lt_soname_spec
-
-# Commands used to build and install an old-style archive.
-RANLIB=3D$lt_RANLIB
-old_archive_cmds=3D$lt_[]_LT_AC_TAGVAR(old_archive_cmds, $1)
-old_postinstall_cmds=3D$lt_old_postinstall_cmds
-old_postuninstall_cmds=3D$lt_old_postuninstall_cmds
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=3D$lt_[]_LT_AC_TAGVAR(old_archive_from_new_cmds,=
 $1)
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=3D$lt_[]_LT_AC_TAGVAR(old_archive_from_expsy=
ms_cmds, $1)
-
-# Commands used to build and install a shared archive.
-archive_cmds=3D$lt_[]_LT_AC_TAGVAR(archive_cmds, $1)
-archive_expsym_cmds=3D$lt_[]_LT_AC_TAGVAR(archive_expsym_cmds, $1)
-postinstall_cmds=3D$lt_postinstall_cmds
-postuninstall_cmds=3D$lt_postuninstall_cmds
-
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=3D$lt_[]_LT_AC_TAGVAR(module_cmds, $1)
-module_expsym_cmds=3D$lt_[]_LT_AC_TAGVAR(module_expsym_cmds, $1)
-
-# Commands to strip libraries.
-old_striplib=3D$lt_old_striplib
-striplib=3D$lt_striplib
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=3D$lt_[]_LT_AC_TAGVAR(predep_objects, $1)
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=3D$lt_[]_LT_AC_TAGVAR(postdep_objects, $1)
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=3D$lt_[]_LT_AC_TAGVAR(predeps, $1)
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=3D$lt_[]_LT_AC_TAGVAR(postdeps, $1)
-
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=3D$lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $=
1)
-
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=3D$lt_deplibs_check_method
-
-# Command to use when deplibs_check_method =3D=3D file_magic.
-file_magic_cmd=3D$lt_file_magic_cmd
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=3D$lt_[]_LT_AC_TAGVAR(allow_undefined_flag, $1)
-
-# Flag that forces no undefined symbols.
-no_undefined_flag=3D$lt_[]_LT_AC_TAGVAR(no_undefined_flag, $1)
-
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=3D$lt_finish_cmds
-
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=3D$lt_finish_eval
-
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=3D$lt_lt_cv_sys_global_symbol_pipe
-
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=3D$lt_lt_cv_sys_global_symbol_to_cdecl
-
-# Transform the output of nm in a C name address pair
-global_symbol_to_c_name_address=3D$lt_lt_cv_sys_global_symbol_to_c_name_ad=
dress
-
-# This is the shared library runtime path variable.
-runpath_var=3D$runpath_var
-
-# This is the shared library path variable.
-shlibpath_var=3D$shlibpath_var
-
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=3D$shlibpath_overrides_runpath
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=3D$_LT_AC_TAGVAR(hardcode_action, $1)
-
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=3D$hardcode_into_libs
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist.
-hardcode_libdir_flag_spec=3D$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_spec,=
 $1)
-
-# If ld is used when linking, flag to hardcode \$libdir into
-# a binary during linking. This must work even if \$libdir does
-# not exist.
-hardcode_libdir_flag_spec_ld=3D$lt_[]_LT_AC_TAGVAR(hardcode_libdir_flag_sp=
ec_ld, $1)
-
-# Whether we need a single -rpath flag with a separated argument.
-hardcode_libdir_separator=3D$lt_[]_LT_AC_TAGVAR(hardcode_libdir_separator,=
 $1)
-
-# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DI=
R into the
-# resulting binary.
-hardcode_direct=3D$_LT_AC_TAGVAR(hardcode_direct, $1)
-
-# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
-# resulting binary.
-hardcode_minus_L=3D$_LT_AC_TAGVAR(hardcode_minus_L, $1)
-
-# Set to yes if using SHLIBPATH_VAR=3DDIR during linking hardcodes DIR into
-# the resulting binary.
-hardcode_shlibpath_var=3D$_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)
-
-# Set to yes if building a shared library automatically hardcodes DIR into=
 the library
-# and all subsequent libraries and executables linked against it.
-hardcode_automatic=3D$_LT_AC_TAGVAR(hardcode_automatic, $1)
-
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at relink time.
-variables_saved_for_relink=3D"$variables_saved_for_relink"
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=3D$_LT_AC_TAGVAR(link_all_deplibs, $1)
-
-# Compile-time system search path for libraries
-sys_lib_search_path_spec=3D$lt_sys_lib_search_path_spec
-
-# Run-time system search path for libraries
-sys_lib_dlsearch_path_spec=3D$lt_sys_lib_dlsearch_path_spec
-
-# Fix the shell variable \$srcfile for the compiler.
-fix_srcfile_path=3D"$_LT_AC_TAGVAR(fix_srcfile_path, $1)"
-
-# Set to yes if exported symbols are required.
-always_export_symbols=3D$_LT_AC_TAGVAR(always_export_symbols, $1)
-
-# The commands to list exported symbols.
-export_symbols_cmds=3D$lt_[]_LT_AC_TAGVAR(export_symbols_cmds, $1)
-
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=3D$lt_extract_expsyms_cmds
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=3D$lt_[]_LT_AC_TAGVAR(exclude_expsyms, $1)
-
-# Symbols that must always be exported.
-include_expsyms=3D$lt_[]_LT_AC_TAGVAR(include_expsyms, $1)
-
-ifelse([$1],[],
-[# ### END LIBTOOL CONFIG],
-[# ### END LIBTOOL TAG CONFIG: $tagname])
-
-__EOF__
-
-ifelse([$1],[], [
-  case $host_os in
-  aix3*)
-    cat <<\EOF >> "$cfgfile"
-
-# AIX sometimes has problems with the GCC collect2 program.  For some
-# reason, if we set the COLLECT_NAMES environment variable, the problems
-# vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" !=3D Xset; then
-  COLLECT_NAMES=3D
-  export COLLECT_NAMES
-fi
-EOF
-    ;;
-  esac
-
-  # We use sed instead of cat because bash on DJGPP gets confused if
-  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
-  # text mode, it properly converts lines to CR/LF.  This bash problem
-  # is reportedly fixed, but why not run on old versions too?
-  sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1)
-
-  mv -f "$cfgfile" "$ofile" || \
-    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
-  chmod +x "$ofile"
-])
-else
-  # If there is no Makefile yet, we rely on a make rule to execute
-  # `config.status --recheck' to rerun these tests and create the
-  # libtool script then.
-  ltmain_in=3D`echo $ltmain | sed -e 's/\.sh$/.in/'`
-  if test -f "$ltmain_in"; then
-    test -f Makefile && make "$ltmain"
-  fi
-fi
-])# AC_LIBTOOL_CONFIG
-
-
-# AC_LIBTOOL_PROG_COMPILER_NO_RTTI([TAGNAME])
-# -------------------------------------------
-AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI],
-[AC_REQUIRE([_LT_AC_SYS_COMPILER])dnl
-
-_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=3D
-
-if test "$GCC" =3D yes; then
-  _LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=3D' -fno-builtin'
-
-  AC_LIBTOOL_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-excepti=
ons],
-    lt_cv_prog_compiler_rtti_exceptions,
-    [-fno-rtti -fno-exceptions], [],
-    [_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=3D"$_LT_AC_TAGVAR=
(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"])
-fi
-])# AC_LIBTOOL_PROG_COMPILER_NO_RTTI
-
-
-# AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
-# ---------------------------------
-AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE],
-[AC_REQUIRE([AC_CANONICAL_HOST])
-AC_REQUIRE([AC_PROG_NM])
-AC_REQUIRE([AC_OBJEXT])
-# Check for command to grab the raw symbol name followed by C symbol from =
nm.
-AC_MSG_CHECKING([command to parse $NM output from $compiler object])
-AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe],
-[
-# These are sane defaults that work on at least a few old systems.
-# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
-
-# Character class describing NM global symbol codes.
-symcode=3D'[[BCDEGRST]]'
-
-# Regexp to match symbols that can be accessed directly from C.
-sympat=3D'\([[_A-Za-z]][[_A-Za-z0-9]]*\)'
-
-# Transform an extracted symbol line into a proper C declaration
-lt_cv_sys_global_symbol_to_cdecl=3D"sed -n -e 's/^. .* \(.*\)$/extern int =
\1;/p'"
-
-# Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address=3D"sed -n -e 's/^: \([[^ ]]*\) $=
/  {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([[^ ]]*\) \([[^ ]]*\)$/  =
{\"\2\", (lt_ptr) \&\2},/p'"
-
-# Define system-specific variables.
-case $host_os in
-aix*)
-  symcode=3D'[[BCDT]]'
-  ;;
-cygwin* | mingw* | pw32*)
-  symcode=3D'[[ABCDGISTW]]'
-  ;;
-hpux*) # Its linker distinguishes data from code symbols
-  if test "$host_cpu" =3D ia64; then
-    symcode=3D'[[ABCDEGRST]]'
-  fi
-  lt_cv_sys_global_symbol_to_cdecl=3D"sed -n -e 's/^T .* \(.*\)$/extern in=
t \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-  lt_cv_sys_global_symbol_to_c_name_address=3D"sed -n -e 's/^: \([[^ ]]*\)=
 $/  {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$=
/  {\"\2\", (lt_ptr) \&\2},/p'"
-  ;;
-linux*)
-  if test "$host_cpu" =3D ia64; then
-    symcode=3D'[[ABCDGIRSTW]]'
-    lt_cv_sys_global_symbol_to_cdecl=3D"sed -n -e 's/^T .* \(.*\)$/extern =
int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-    lt_cv_sys_global_symbol_to_c_name_address=3D"sed -n -e 's/^: \([[^ ]]*=
\) $/  {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\=
)$/  {\"\2\", (lt_ptr) \&\2},/p'"
-  fi
-  ;;
-irix* | nonstopux*)
-  symcode=3D'[[BCDEGRST]]'
-  ;;
-osf*)
-  symcode=3D'[[BCDEGQRST]]'
-  ;;
-solaris*)
-  symcode=3D'[[BDRT]]'
-  ;;
-sco3.2v5*)
-  symcode=3D'[[DT]]'
-  ;;
-sysv4.2uw2*)
-  symcode=3D'[[DT]]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode=3D'[[ABDT]]'
-  ;;
-sysv4)
-  symcode=3D'[[DFNSTU]]'
-  ;;
-esac
-
-# Handle CRLF in mingw tool chain
-opt_cr=3D
-case $build_os in
-mingw*)
-  opt_cr=3D`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp
-  ;;
-esac
-
-# If we're using GNU nm, then use its standard symbol codes.
-case `$NM -V 2>&1` in
-*GNU* | *'with BFD'*)
-  symcode=3D'[[ABCDGIRSTW]]' ;;
-esac
-
-# Try without a prefix undercore, then with it.
-for ac_symprfx in "" "_"; do
-
-  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbo=
l.
-  symxfrm=3D"\\1 $ac_symprfx\\2 \\2"
-
-  # Write the raw and C identifiers.
-  lt_cv_sys_global_symbol_pipe=3D"sed -n -e 's/^.*[[ 	]]\($symcode$symcode=
*\)[[ 	]][[ 	]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
-
-  # Check to see that the pipe works correctly.
-  pipe_works=3Dno
-
-  rm -f conftest*
-  cat > conftest.$ac_ext <<EOF
-#ifdef __cplusplus
-extern "C" {
-#endif
-char nm_test_var;
-void nm_test_func(){}
-#ifdef __cplusplus
-}
-#endif
-int main(){nm_test_var=3D'a';nm_test_func();return(0);}
-EOF
-
-  if AC_TRY_EVAL(ac_compile); then
-    # Now try to grab the symbols.
-    nlist=3Dconftest.nm
-    if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe=
 \> $nlist) && test -s "$nlist"; then
-      # Try sorting and uniquifying the output.
-      if sort "$nlist" | uniq > "$nlist"T; then
-	mv -f "$nlist"T "$nlist"
-      else
-	rm -f "$nlist"T
-      fi
-
-      # Make sure that we snagged all the symbols we need.
-      if grep ' nm_test_var$' "$nlist" >/dev/null; then
-	if grep ' nm_test_func$' "$nlist" >/dev/null; then
-	  cat <<EOF > conftest.$ac_ext
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-EOF
-	  # Now generate the symbol file.
-	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> =
conftest.$ac_ext'
-
-	  cat <<EOF >> conftest.$ac_ext
-#if defined (__STDC__) && __STDC__
-# define lt_ptr_t void *
-#else
-# define lt_ptr_t char *
-# define const
-#endif
-
-/* The mapping between symbol names and symbols. */
-const struct {
-  const char *name;
-  lt_ptr_t address;
-}
-lt_preloaded_symbols[[]] =3D
-{
-EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (lt_ptr_t) \&\2},/=
" < "$nlist" | grep -v main >> conftest.$ac_ext
-	  cat <<\EOF >> conftest.$ac_ext
-  {0, (lt_ptr_t) 0}
-};
-
-#ifdef __cplusplus
-}
-#endif
-EOF
-	  # Now try linking the two files.
-	  mv conftest.$ac_objext conftstm.$ac_objext
-	  lt_save_LIBS=3D"$LIBS"
-	  lt_save_CFLAGS=3D"$CFLAGS"
-	  LIBS=3D"conftstm.$ac_objext"
-	  CFLAGS=3D"$CFLAGS$_LT_AC_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)"
-	  if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then
-	    pipe_works=3Dyes
-	  fi
-	  LIBS=3D"$lt_save_LIBS"
-	  CFLAGS=3D"$lt_save_CFLAGS"
-	else
-	  echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD
-	fi
-      else
-	echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD
-      fi
-    else
-      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD
-    fi
-  else
-    echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD
-    cat conftest.$ac_ext >&5
-  fi
-  rm -f conftest* conftst*
-
-  # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" =3D yes; then
-    break
-  else
-    lt_cv_sys_global_symbol_pipe=3D
-  fi
-done
-])
-if test -z "$lt_cv_sys_global_symbol_pipe"; then
-  lt_cv_sys_global_symbol_to_cdecl=3D
-fi
-if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl=
"; then
-  AC_MSG_RESULT(failed)
-else
-  AC_MSG_RESULT(ok)
-fi
-]) # AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE
-
-
-# AC_LIBTOOL_PROG_COMPILER_PIC([TAGNAME])
-# ---------------------------------------
-AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC],
-[_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D
-_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D
-_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D
-
-AC_MSG_CHECKING([for $compiler option to produce PIC])
- ifelse([$1],[CXX],[
-  # C++ specific cases for pic, static, wl, etc.
-  if test "$GXX" =3D yes; then
-    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-static'
-
-    case $host_os in
-    aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      fi
-      ;;
-    amigaos*)
-      # FIXME: we need at least 68020 code to build shared libraries, but
-      # adding the `-m68020' flag to GCC prevents building anything better,
-      # like `-m68040'.
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-m68020 -resident32 -malw=
ays-restore-a4'
-      ;;
-    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-    mingw* | os2* | pw32*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-DDLL_EXPORT'
-      ;;
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fno-common'
-      ;;
-    *djgpp*)
-      # DJGPP does not support shared libraries at all
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D
-      ;;
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D-Kconform_pic
-      fi
-      ;;
-    hpux*)
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	;;
-      *)
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fPIC'
-	;;
-      esac
-      ;;
-    *)
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fPIC'
-      ;;
-    esac
-  else
-    case $host_os in
-      aix4* | aix5*)
-	# All AIX code is PIC.
-	if test "$host_cpu" =3D ia64; then
-	  # AIX 5 now supports IA64 processor
-	  _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-	else
-	  _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-bnso -bI:/lib/syscalls.e=
xp'
-	fi
-	;;
-      chorus*)
-	case $cc_basename in
-	cxch68*)
-	  # Green Hills C++ Compiler
-	  # _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D"--no_auto_instantiation=
 -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/C=
C/libC.a $MVME_DIR/lib/classix/libcx.s.a"
-	  ;;
-	esac
-	;;
-       darwin*)
-         # PIC is the default on this platform
-         # Common symbols not allowed in MH_DYLIB files
-         case $cc_basename in
-           xlc*)
-           _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-qnocommon'
-           _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-           ;;
-         esac
-       ;;
-      dgux*)
-	case $cc_basename in
-	  ec++*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-	    ;;
-	  ghcx*)
-	    # Green Hills C++ Compiler
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      freebsd* | kfreebsd*-gnu | dragonfly*)
-	# FreeBSD uses GNU C++
-	;;
-      hpux9* | hpux10* | hpux11*)
-	case $cc_basename in
-	  CC*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'${wl}-a ${wl}archive'
-	    if test "$host_cpu" !=3D ia64; then
-	      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'+Z'
-	    fi
-	    ;;
-	  aCC*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'${wl}-a ${wl}archive'
-	    case $host_cpu in
-	    hppa*64*|ia64*)
-	      # +Z the default
-	      ;;
-	    *)
-	      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'+Z'
-	      ;;
-	    esac
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      interix*)
-	# This is c89, which is MS Visual C++ (no shared libs)
-	# Anyone wants to do a port?
-	;;
-      irix5* | irix6* | nonstopux*)
-	case $cc_basename in
-	  CC*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-non_shared'
-	    # CC pic flag -KPIC is the default.
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      linux*)
-	case $cc_basename in
-	  KCC*)
-	    # KAI C++ Compiler
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'--backend -Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fPIC'
-	    ;;
-	  icpc* | ecpc*)
-	    # Intel C++
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-static'
-	    ;;
-	  pgCC*)
-	    # Portland Group C++ compiler.
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fpic'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-	    ;;
-	  cxx*)
-	    # Compaq C++
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-non_shared'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      lynxos*)
-	;;
-      m88k*)
-	;;
-      mvs*)
-	case $cc_basename in
-	  cxx*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-W c,exportall'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      netbsd*)
-	;;
-      osf3* | osf4* | osf5*)
-	case $cc_basename in
-	  KCC*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'--backend -Wl,'
-	    ;;
-	  RCC*)
-	    # Rational C++ 2.4.1
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-pic'
-	    ;;
-	  cxx*)
-	    # Digital/Compaq C++
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-non_shared'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      psos*)
-	;;
-      solaris*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Qoption ld '
-	    ;;
-	  gcx*)
-	    # Green Hills C++ Compiler
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-PIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sunos4*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.x
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-pic'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-	    ;;
-	  lcc*)
-	    # Lucid
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      tandem*)
-	case $cc_basename in
-	  NCC*)
-	    # NonStop-UX NCC 3.20
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-	case $cc_basename in
-	  CC*)
-	    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-	    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-	    ;;
-	esac
-	;;
-      vxworks*)
-	;;
-      *)
-	_LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=3Dno
-	;;
-    esac
-  fi
-],
-[
-  if test "$GCC" =3D yes; then
-    _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-    _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-static'
-
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      # FIXME: we need at least 68020 code to build shared libraries, but
-      # adding the `-m68020' flag to GCC prevents building anything better,
-      # like `-m68040'.
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-m68020 -resident32 -malw=
ays-restore-a4'
-      ;;
-
-    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-DDLL_EXPORT'
-      ;;
-
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fno-common'
-      ;;
-
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared librar=
ies
-      # on systems that don't support them.
-      _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=3Dno
-      enable_shared=3Dno
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D-Kconform_pic
-      fi
-      ;;
-
-    hpux*)
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fPIC'
-	;;
-      esac
-      ;;
-
-    *)
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fPIC'
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compil=
er.
-    case $host_os in
-    aix*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      else
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-      darwin*)
-        # PIC is the default on this platform
-        # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
-         xlc*)
-         _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-qnocommon'
-         _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-         ;;
-       esac
-       ;;
-
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-DDLL_EXPORT'
-      ;;
-
-    hpux9* | hpux10* | hpux11*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bund=
led CC?
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'${wl}-a ${wl}archive'
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-      # PIC (with -KPIC) is the default.
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-non_shared'
-      ;;
-
-    newsos6)
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      ;;
-
-    linux*)
-      case $cc_basename in
-      icc* | ecc*)
-	_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-static'
-        ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-fpic'
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-        ;;
-      ccc*)
-        _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-        # All Alpha code is PIC.
-        _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-non_shared'
-        ;;
-      esac
-      ;;
-
-    osf3* | osf4* | osf5*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-      # All OSF/1 code is PIC.
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-non_shared'
-      ;;
-
-    solaris*)
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Qoption ld ';;
-      *)
-	_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,';;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Qoption ld '
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-PIC'
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      ;;
-
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-Kconform_pic'
-	_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      fi
-      ;;
-
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-KPIC'
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      ;;
-
-    unicos*)
-      _LT_AC_TAGVAR(lt_prog_compiler_wl, $1)=3D'-Wl,'
-      _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=3Dno
-      ;;
-
-    uts4*)
-      _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D'-pic'
-      _LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D'-Bstatic'
-      ;;
-
-    *)
-      _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=3Dno
-      ;;
-    esac
-  fi
-])
-AC_MSG_RESULT([$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)])
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)"; then
-  AC_LIBTOOL_COMPILER_OPTION([if $compiler PIC flag $_LT_AC_TAGVAR(lt_prog=
_compiler_pic, $1) works],
-    _LT_AC_TAGVAR(lt_prog_compiler_pic_works, $1),
-    [$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)ifelse([$1],[],[ -DPIC],[ifel=
se([$1],[CXX],[ -DPIC],[])])], [],
-    [case $_LT_AC_TAGVAR(lt_prog_compiler_pic, $1) in
-     "" | " "*) ;;
-     *) _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D" $_LT_AC_TAGVAR(lt_prog=
_compiler_pic, $1)" ;;
-     esac],
-    [_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D
-     _LT_AC_TAGVAR(lt_prog_compiler_can_build_shared, $1)=3Dno])
-fi
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D
-    ;;
-  *)
-    _LT_AC_TAGVAR(lt_prog_compiler_pic, $1)=3D"$_LT_AC_TAGVAR(lt_prog_comp=
iler_pic, $1)ifelse([$1],[],[ -DPIC],[ifelse([$1],[CXX],[ -DPIC],[])])"
-    ;;
-esac
-
-#
-# Check to make sure the static flag actually works.
-#
-wl=3D$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=3D\"$=
_LT_AC_TAGVAR(lt_prog_compiler_static, $1)\"
-AC_LIBTOOL_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag wor=
ks],
-  _LT_AC_TAGVAR(lt_prog_compiler_static_works, $1),
-  $lt_tmp_static_flag,
-  [],
-  [_LT_AC_TAGVAR(lt_prog_compiler_static, $1)=3D])
-])
-
-
-# AC_LIBTOOL_PROG_LD_SHLIBS([TAGNAME])
-# ------------------------------------
-# See if the linker supports building shared libraries.
-AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS],
-[AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libra=
ries])
-ifelse([$1],[CXX],[
-  _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM $libobjs $convenience | $g=
lobal_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  case $host_os in
-  aix4* | aix5*)
-    # If we're using GNU nm, then we don't want the "-C" option.
-    # -C means demangle to AIX nm, but means don't demangle with GNU nm
-    if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
-      _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM -Bpg $libobjs $conveni=
ence | awk '\''{ if (((\[$]2 =3D=3D "T") || (\[$]2 =3D=3D "D") || (\[$]2 =
=3D=3D "B")) && ([substr](\[$]3,1,1) !=3D ".")) { print \[$]3 } }'\'' | sor=
t -u > $export_symbols'
-    else
-      _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM -BCpg $libobjs $conven=
ience | awk '\''{ if (((\[$]2 =3D=3D "T") || (\[$]2 =3D=3D "D") || (\[$]2 =
=3D=3D "B")) && ([substr](\[$]3,1,1) !=3D ".")) { print \[$]3 } }'\'' | sor=
t -u > $export_symbols'
-    fi
-    ;;
-  pw32*)
-    _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D"$ltdll_cmds"
-  ;;
-  cygwin* | mingw*)
-    _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM $libobjs $convenience | =
$global_symbol_pipe | $SED -e '\''/^[[BCDGRS]] /s/.* \([[^ ]]*\)/\1 DATA/;/=
^.* __nm__/s/^.* __nm__\([[^ ]]*\) [[^ ]]*/\1 DATA/;/^I /d;/^[[AITW]] /s/.*=
 //'\'' | sort | uniq > $export_symbols'
-  ;;
-  *)
-    _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM $libobjs $convenience | =
$global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  ;;
-  esac
-],[
-  runpath_var=3D
-  _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D
-  _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=3Dno
-  _LT_AC_TAGVAR(archive_cmds, $1)=3D
-  _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D
-  _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)=3D
-  _LT_AC_TAGVAR(old_archive_from_expsyms_cmds, $1)=3D
-  _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D
-  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D
-  _LT_AC_TAGVAR(thread_safe_flag_spec, $1)=3D
-  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D
-  _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=3D
-  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D
-  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-  _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dno
-  _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dunsupported
-  _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dunknown
-  _LT_AC_TAGVAR(hardcode_automatic, $1)=3Dno
-  _LT_AC_TAGVAR(module_cmds, $1)=3D
-  _LT_AC_TAGVAR(module_expsym_cmds, $1)=3D
-  _LT_AC_TAGVAR(always_export_symbols, $1)=3Dno
-  _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM $libobjs $convenience | $g=
lobal_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  # include_expsyms should be a list of space-separated symbols to be *alw=
ays*
-  # included in the symbol list
-  _LT_AC_TAGVAR(include_expsyms, $1)=3D
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `=
bc',
-  # as well as any symbol that contains `d'.
-  _LT_AC_TAGVAR(exclude_expsyms, $1)=3D"_GLOBAL_OFFSET_TABLE_"
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  extract_expsyms_cmds=3D
-  # Just being paranoid about ensuring that cc_basename is set.
-  _LT_CC_BASENAME([$compiler])
-  case $host_os in
-  cygwin* | mingw* | pw32*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" !=3D yes; then
-      with_gnu_ld=3Dno
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (=3D MSVC++)
-    with_gnu_ld=3Dyes
-    ;;
-  openbsd*)
-    with_gnu_ld=3Dno
-    ;;
-  esac
-
-  _LT_AC_TAGVAR(ld_shlibs, $1)=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc=3D'${wl}'
-
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=3DLD_RUN_PATH
-    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}--rpath ${wl}$lib=
dir'
-    _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D"$wlarc"'--whole-archive$con=
venience '"$wlarc"'--no-whole-archive'
-      else
-  	_LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D
-    fi
-    supports_anon_versioning=3Dno
-    case `$LD -v 2>/dev/null` in
-      *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=3Dyes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=3Dyes ;; # Mandrake 8.2=
 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=3Dyes ;;
-    esac
-
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix3* | aix4* | aix5*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" !=3D ia64; then
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	cat <<EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.9.1, is reported
-*** to be unable to reliably create shared libraries on AIX.
-*** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to modify your PATH
-*** so that a non-GNU linker is found, and then restart.
-
-EOF
-      fi
-      ;;
-
-    amigaos*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$rm $output_objdir/a2ixlibrary.da=
ta~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#=
define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERS=
ION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $rev=
ision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANL=
IB $lib~(cd $output_objdir && a2ixlibrary -32)'
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-
-      # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
-      # that the semantics of dynamic libraries on AmigaOS, at least up
-      # to version 4, is to share data among multiple programs linked
-      # with the same dynamic library.  Since this doesn't match the
-      # behavior of shared libraries on other platforms, we can't use
-      # them.
-      _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      ;;
-
-    beos*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3Dunsupported
-	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -nostart $libobjs $deplibs $compil=
er_flags ${wl}-soname $wl$soname -o $lib'
-      else
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      fi
-      ;;
-
-    cygwin* | mingw* | pw32*)
-      # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningle=
ss,
-      # as there is no search path for DLLs.
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=3Dunsupported
-      _LT_AC_TAGVAR(always_export_symbols, $1)=3Dno
-      _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=3Dyes
-      _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM $libobjs $convenience =
| $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]] /s/.* \([[^ ]]*\)/\1 DATA/=
'\'' | $SED -e '\''/^[[AITW]] /s/.* //'\'' | sort | uniq > $export_symbols'
-
-      if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-        _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $libobjs $deplibs $=
compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xli=
nker --out-implib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'if test "x`$SED 1q $export_symb=
ols`" =3D xEXPORTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags =
-o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-impl=
ib -Xlinker $lib'
-      else
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      fi
-      ;;
-
-    interix3*)
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gc=
c.
-      # Instead, shared libraries are loaded at an image base (0x10000000 =
by
-      # default) and relocated if they conflict, which is a slow very memo=
ry
-      # consuming and fragmenting process.  To avoid this, we pick a rando=
m,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at li=
nk
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $pic_flag $libobjs $d=
eplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$}=
 % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'sed "s,^,_," $export_symbo=
ls >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $=
compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$s=
oname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 13=
42177280` -o $lib'
-      ;;
-
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	tmp_addflag=3D
-	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'${wl}--whole-archive`for =
conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new=
_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-arc=
hive'
-	  tmp_addflag=3D' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'${wl}--whole-archive`for =
conv in $convenience\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new=
_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-arc=
hive'
-	  tmp_addflag=3D' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
-	  tmp_addflag=3D' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=3D' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=3D' -nofor_main' ;;
-	esac
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared'"$tmp_addflag"' $libobjs $=
deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib'
-
-	if test $supports_anon_versioning =3D yes; then
-	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$echo "{ global:" > $output_o=
bjdir/$libname.ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.=
ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-son=
ame $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $li=
b'
-	fi
-      else
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      fi
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -Bshareable $libobjs $deplibs $lin=
ker_flags -o $lib'
-	wlarc=3D
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $libobjs $deplibs $compile=
r_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $libobjs $deplibs $=
compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export=
_symbols -o $lib'
-      fi
-      ;;
-
-    solaris*)
-      if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	cat <<EOF 1>&2
-
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-EOF
-      elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null=
; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $libobjs $deplibs $compile=
r_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $libobjs $deplibs $=
compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export=
_symbols -o $lib'
-      else
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*)=20
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'`test -z "$SCOABSPATH=
" && echo ${wl}-rpath,$libdir`'
-	    _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $libobjs $deplibs $com=
piler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $libobjs $depli=
bs $compiler_flags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-=
retain-symbols-file,$export_symbols -o $lib'
-	  else
-	    _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-	  fi
-	;;
-      esac
-      ;;
-
-    sunos4*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -assert pure-text -Bshareable=
 -o $lib $libobjs $deplibs $linker_flags'
-      wlarc=3D
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    *)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $libobjs $deplibs $compile=
r_flags ${wl}-soname $wl$soname -o $lib'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $libobjs $deplibs $=
compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export=
_symbols -o $lib'
-      else
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      fi
-      ;;
-    esac
-
-    if test "$_LT_AC_TAGVAR(ld_shlibs, $1)" =3D no; then
-      runpath_var=3D
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D
-      _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
-    case $host_os in
-    aix3*)
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=3Dunsupported
-      _LT_AC_TAGVAR(always_export_symbols, $1)=3Dyes
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$LD -o $output_objdir/$son=
ame $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE=
~$AR $AR_FLAGS $lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-      if test "$GCC" =3D yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	_LT_AC_TAGVAR(hardcode_direct, $1)=3Dunsupported
-      fi
-      ;;
-
-    aix4* | aix5*)
-      if test "$host_cpu" =3D ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=3Dno
-	exp_sym_flag=3D'-Bexport'
-	no_entry_flag=3D""
-      else
-	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
-	  _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM -Bpg $libobjs $convenienc=
e | awk '\''{ if (((\[$]2 =3D=3D "T") || (\[$]2 =3D=3D "D") || (\[$]2 =3D=
=3D "B")) && ([substr](\[$]3,1,1) !=3D ".")) { print \[$]3 } }'\'' | sort -=
u > $export_symbols'
-	else
-	  _LT_AC_TAGVAR(export_symbols_cmds, $1)=3D'$NM -BCpg $libobjs $convenien=
ce | awk '\''{ if (((\[$]2 =3D=3D "T") || (\[$]2 =3D=3D "D") || (\[$]2 =3D=
=3D "B")) && ([substr](\[$]3,1,1) !=3D ".")) { print \[$]3 } }'\'' | sort -=
u > $export_symbols'
-	fi
-	aix_use_runtimelinking=3Dno
-
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[[23]]|aix4.[[23]].*|aix5*)
-	  for ld_flag in $LDFLAGS; do
-  	  if (test $ld_flag =3D "-brtl" || test $ld_flag =3D "-Wl,-brtl"); then
-  	    aix_use_runtimelinking=3Dyes
-  	    break
-  	  fi
-	  done
-	  ;;
-	esac
-
-	exp_sym_flag=3D'-bexport'
-	no_entry_flag=3D'-bnoentry'
-      fi
-
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D''
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D':'
-      _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-
-      if test "$GCC" =3D yes; then
-	case $host_os in aix4.[[012]]|aix4.[[012]].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=3D`${CC} -print-prog-name=3Dcollect2`
-	  if test -f "$collect2name" && \
-  	   strings "$collect2name" | grep resolve_lib_name >/dev/null
-	  then
-  	  # We have reworked collect2
-  	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-	  else
-  	  # We have old collect2
-  	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dunsupported
-  	  # It fails to find uninstalled libraries when the uninstalled
-  	  # path is not listed in the libpath.  Setting hardcode_minus_L
-  	  # to unsupported forces relinking
-  	  _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-  	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-  	  _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D
-	  fi
-	  ;;
-	esac
-	shared_flag=3D'-shared'
-	if test "$aix_use_runtimelinking" =3D yes; then
-	  shared_flag=3D"$shared_flag "'${wl}-G'
-	fi
-      else
-	# not using gcc
-	if test "$host_cpu" =3D ia64; then
-  	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-  	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag=3D'-G'
-	else
-	  if test "$aix_use_runtimelinking" =3D yes; then
-	    shared_flag=3D'${wl}-G'
-	  else
-	    shared_flag=3D'${wl}-bM:SRE'
-	  fi
-	fi
-      fi
-
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to e=
xport.
-      _LT_AC_TAGVAR(always_export_symbols, $1)=3Dyes
-      if test "$aix_use_runtimelinking" =3D yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'-berok'
-       # Determine the default libpath from the value encoded in an empty =
executable.
-       _LT_AC_SYS_LIBPATH_AIX
-       _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-blibpath:$lib=
dir:'"$aix_libpath"
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D"\$CC"' -o $output_objdir/$sonam=
e $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${a=
llow_undefined_flag}" !=3D "x"; then echo "${wl}${allow_undefined_flag}"; e=
lse :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-       else
-	if test "$host_cpu" =3D ia64; then
-	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-R $libdir:/usr/li=
b:/lib'
-	  _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D"-z nodefs"
-	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D"\$CC $shared_flag"' -o $outpu=
t_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags=
 ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an empty execu=
table.
-	 _LT_AC_SYS_LIBPATH_AIX
-	 _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-blibpath:$libdir:'=
"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  _LT_AC_TAGVAR(no_undefined_flag, $1)=3D' ${wl}-bernotok'
-	  _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' ${wl}-berok'
-	  # Exported symbols can be pulled into shared objects from archives
-	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'$convenience'
-	  _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dyes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D"\$CC $shared_flag"' -o $outpu=
t_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:=
$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libnam=
e$release.a $output_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$rm $output_objdir/a2ixlibrary.da=
ta~$echo "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#=
define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERS=
ION $major" >> $output_objdir/a2ixlibrary.data~$echo "#define REVISION $rev=
ision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANL=
IB $lib~(cd $output_objdir && a2ixlibrary -32)'
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-      # see comment about different semantics on the GNU ld section
-      _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      ;;
-
-    bsdi[[45]]*)
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D-rdynamic
-      ;;
-
-    cygwin* | mingw* | pw32*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # hardcode_libdir_flag_spec is actually meaningless, as there is
-      # no search path for DLLs.
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D' '
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=3Dunsupported
-      # Tell ltmain to make .lib files, not .a files.
-      libext=3Dlib
-      # Tell ltmain to make .dll files, not .so files.
-      shrext_cmds=3D".dll"
-      # FIXME: Setting linknames here is a bad hack.
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -o $lib $libobjs $compiler_fl=
ags `echo "$deplibs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=3D'
-      # The linker will automatically build a .lib file if we build a DLL.
-      _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)=3D'true'
-      # FIXME: Should let the user specify the lib program.
-      _LT_AC_TAGVAR(old_archive_cmds, $1)=3D'lib /OUT:$oldlib$oldobjs$old_=
deplibs'
-      _LT_AC_TAGVAR(fix_srcfile_path, $1)=3D'`cygpath -w "$srcfile"`'
-      _LT_AC_TAGVAR(enable_shared_with_static_runtimes, $1)=3Dyes
-      ;;
-
-    darwin* | rhapsody*)
-      case $host_os in
-        rhapsody* | darwin1.[[012]])
-         _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-undefined ${wl}s=
uppress'
-         ;;
-       *) # Darwin 1.3 on
-         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
-           _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-flat_namespace=
 ${wl}-undefined ${wl}suppress'
-         else
-           case ${MACOSX_DEPLOYMENT_TARGET} in
-             10.[[012]])
-               _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-flat_names=
pace ${wl}-undefined ${wl}suppress'
-               ;;
-             10.*)
-               _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-undefined =
${wl}dynamic_lookup'
-               ;;
-           esac
-         fi
-         ;;
-      esac
-      _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_automatic, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dunsupported
-      _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D''
-      _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-    if test "$GCC" =3D yes ; then
-    	output_verbose_link_cmd=3D'echo'
-        _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -dynamiclib $allow_undefine=
d_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$sona=
me $verstring'
-      _LT_AC_TAGVAR(module_cmds, $1)=3D'$CC $allow_undefined_flag -o $lib =
-bundle $libobjs $deplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doe=
sn't exist in older darwin lds
-      _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e "s,^[ =
   ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-=
symbols.expsym~$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $depl=
ibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s $outp=
ut_objdir/${libname}-symbols.expsym ${lib}'
-      _LT_AC_TAGVAR(module_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e "s,^[  =
  ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-s=
ymbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$=
compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    else
-      case $cc_basename in
-        xlc*)
-         output_verbose_link_cmd=3D'echo'
-         _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -qmkshrobj $allow_undefine=
d_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`e=
cho $rpath/$soname` $verstring'
-         _LT_AC_TAGVAR(module_cmds, $1)=3D'$CC $allow_undefined_flag -o $l=
ib -bundle $libobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it=
 doesn't exist in older darwin lds
-         _LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e "s,=
^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libnam=
e}-symbols.expsym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $de=
plibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nme=
dit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          _LT_AC_TAGVAR(module_expsym_cmds, $1)=3D'sed -e "s,#.*,," -e "s,=
^[    ]*,," -e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libnam=
e}-symbols.expsym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $depl=
ibs$compiler_flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib=
}'
-          ;;
-       *)
-         _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-          ;;
-      esac
-    fi
-      ;;
-
-    dgux*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -h $soname -o $lib $libobj=
s $deplibs $linker_flags'
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    freebsd1*)
-      _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      ;;
-
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ construct=
or
-    # support.  Future versions do this automatically, but an explicit c++=
rt0.o
-    # does not break anything, and helps significantly (at the cost of a l=
ittle
-    # extra space).
-    freebsd2.2*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -Bshareable -o $lib $libobjs =
$deplibs $linker_flags /usr/lib/c++rt0.o'
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-R$libdir'
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -Bshareable -o $lib $libobjs =
$deplibs $linker_flags'
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | kfreebsd*-gnu | dragonfly*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -o $lib $libobjs $dep=
libs $compiler_flags'
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-R$libdir'
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    hpux9*)
-      if test "$GCC" =3D yes; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$rm $output_objdir/$soname~$CC -shared=
 -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $dep=
libs $compiler_flags~test $output_objdir/$soname =3D $lib || mv $output_obj=
dir/$soname $lib'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$rm $output_objdir/$soname~$LD -b +b $=
install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~te=
st $output_objdir/$soname =3D $lib || mv $output_objdir/$soname $lib'
-      fi
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}+b ${wl}$libdir'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-      ;;
-
-    hpux10*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -fPIC ${wl}+h ${wl}$soname=
 ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -b +h $soname +b $install_libdir -=
o $lib $libobjs $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" =3D no; then
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}+b ${wl}$libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	_LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	_LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-      fi
-      ;;
-
-    hpux11*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
-	case $host_cpu in
-	hppa*64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared ${wl}+h ${wl}$soname -o =
$lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared ${wl}+h ${wl}$soname ${w=
l}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared -fPIC ${wl}+h ${wl}$sona=
me ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -b ${wl}+h ${wl}$soname -o $lib =
$libobjs $deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+no=
defaultrpath -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+b =
${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" =3D no; then
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}+b ${wl}$libdir'
-	_LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  _LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=3D'+b $libdir'
-	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-	  _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-	  ;;
-	*)
-	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-	  _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-	  ;;
-	esac
-      fi
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      if test "$GCC" =3D yes; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $libobjs $deplibs $compile=
r_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_v=
ersion ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_loca=
tions -o $lib'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -shared $libobjs $deplibs $linker_=
flags -soname $soname `test -n "$verstring" && echo -set_version $verstring=
` -update_registry ${output_objdir}/so_locations -o $lib'
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec_ld, $1)=3D'-rpath $libdir'
-      fi
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$li=
bdir'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-      _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -Bshareable -o $lib $libobjs $depl=
ibs $linker_flags'  # a.out
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -shared -o $lib $libobjs $deplibs =
$linker_flags'      # ELF
-      fi
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-R$libdir'
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    newsos6)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -h $soname -o $lib $libobj=
s $deplibs $linker_flags'
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$li=
bdir'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    openbsd*)
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host=
_os-$host_cpu" =3D "openbsd2.8-powerpc"; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $pic_flag -o $lib $libobjs=
 $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared $pic_flag -o $lib $=
libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-	_LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-E'
-      else
-       case $host_os in
-	 openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*)
-	   _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -Bshareable -o $lib $libobjs $d=
eplibs $linker_flags'
-	   _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-R$libdir'
-	   ;;
-	 *)
-	   _LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared $pic_flag -o $lib $libo=
bjs $deplibs $compiler_flags'
-	   _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath,$libdir'
-	   ;;
-       esac
-      fi
-      ;;
-
-    os2*)
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=3Dunsupported
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$echo "LIBRARY $libname INITINSTA=
NCE" > $output_objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $out=
put_objdir/$libname.def~$echo DATA >> $output_objdir/$libname.def~$echo " S=
INGLE NONSHARED" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_ob=
jdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll =
-Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.=
def'
-      _LT_AC_TAGVAR(old_archive_From_new_cmds, $1)=3D'emximp -o $output_ob=
jdir/$libname.a $output_objdir/$libname.def'
-      ;;
-
-    osf3*)
-      if test "$GCC" =3D yes; then
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' ${wl}-expect_unresolved ${wl}=
\*'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared${allow_undefined_flag} $li=
bobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstri=
ng" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}$=
{output_objdir}/so_locations -o $lib'
-      else
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' -expect_unresolved \*'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -shared${allow_undefined_flag} $li=
bobjs $deplibs $linker_flags -soname $soname `test -n "$verstring" && echo =
-set_version $verstring` -update_registry ${output_objdir}/so_locations -o =
$lib'
-      fi
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$li=
bdir'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-      ;;
-
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" =3D yes; then
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' ${wl}-expect_unresolved ${wl}=
\*'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared${allow_undefined_flag} $li=
bobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -=
n "$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_regi=
stry ${wl}${output_objdir}/so_locations -o $lib'
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'${wl}-rpath ${wl}$libdir'
-      else
-	_LT_AC_TAGVAR(allow_undefined_flag, $1)=3D' -expect_unresolved \*'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -shared${allow_undefined_flag} $li=
bobjs $deplibs $linker_flags -msym -soname $soname `test -n "$verstring" &&=
 echo -set_version $verstring` -update_registry ${output_objdir}/so_locatio=
ns -o $lib'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'for i in `cat $export_symbols`;=
 do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidd=
en">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs=
 $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verst=
ring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
-
-	# Both c and cxx compiler support -rpath directly
-	_LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-rpath $libdir'
-      fi
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D:
-      ;;
-
-    solaris*)
-      _LT_AC_TAGVAR(no_undefined_flag, $1)=3D' -z text'
-      if test "$GCC" =3D yes; then
-	wlarc=3D'${wl}'
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared ${wl}-h ${wl}$soname -o $l=
ib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$echo "{ global:" > $lib.exp~ca=
t $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };=
" >> $lib.exp~
-	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs=
 $deplibs $compiler_flags~$rm $lib.exp'
-      else
-	wlarc=3D''
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G${allow_undefined_flag} -h $sona=
me -o $lib $libobjs $deplibs $linker_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$echo "{ global:" > $lib.exp~ca=
t $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };=
" >> $lib.exp~
-  	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $=
deplibs $linker_flags~$rm $lib.exp'
-      fi
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-R$libdir'
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      case $host_os in
-      solaris2.[[0-5]] | solaris2.[[0-5]].*) ;;
-      *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'-z allextract$convenienc=
e -z defaultextract' ;;
- 	*)
- 	  _LT_AC_TAGVAR(whole_archive_flag_spec, $1)=3D'${wl}-z ${wl}allextract`=
for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=3D\"$=
new_convenience,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}def=
aultextract' ;;
- 	esac ;;
-      esac
-      _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-      ;;
-
-    sunos4*)
-      if test "x$host_vendor" =3D xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -G ${wl}-h $soname -o $lib $libobj=
s $deplibs $compiler_flags'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -assert pure-text -Bstatic -o $lib=
 $libobjs $deplibs $linker_flags'
-      fi
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-      _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_minus_L, $1)=3Dyes
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    sysv4)
-      case $host_vendor in
-	sni)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -h $soname -o $lib $libobjs $=
deplibs $linker_flags'
-	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dyes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -o $lib $libobjs $deplibs $li=
nker_flags'
-	  _LT_AC_TAGVAR(reload_cmds, $1)=3D'$CC -r -o $output$reload_objs'
-	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno
-        ;;
-	motorola)
-	  _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -h $soname -o $lib $libobjs $=
deplibs $linker_flags'
-	  _LT_AC_TAGVAR(hardcode_direct, $1)=3Dno #Motorola manual says yes, but =
my tests say they lie
-	;;
-      esac
-      runpath_var=3D'LD_RUN_PATH'
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    sysv4.3*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -h $soname -o $lib $libobj=
s $deplibs $linker_flags'
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'-Bexport'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -h $soname -o $lib $libobjs $de=
plibs $linker_flags'
-	_LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-	runpath_var=3DLD_RUN_PATH
-	hardcode_runpath_var=3Dyes
-	_LT_AC_TAGVAR(ld_shlibs, $1)=3Dyes
-      fi
-      ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware=
7*)
-      _LT_AC_TAGVAR(no_undefined_flag, $1)=3D'${wl}-z,text'
-      _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      runpath_var=3D'LD_RUN_PATH'
-
-      if test "$GCC" =3D yes; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared ${wl}-h,$soname -o $lib $l=
ibobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared ${wl}-Bexport:$expo=
rt_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -G ${wl}-h,$soname -o $lib $libobj=
s $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -G ${wl}-Bexport:$export_sy=
mbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      _LT_AC_TAGVAR(no_undefined_flag, $1)=3D'${wl}-z,text'
-      _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D'${wl}-z,nodefs'
-      _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'`test -z "$SCOABSPAT=
H" && echo ${wl}-R,$libdir`'
-      _LT_AC_TAGVAR(hardcode_libdir_separator, $1)=3D':'
-      _LT_AC_TAGVAR(link_all_deplibs, $1)=3Dyes
-      _LT_AC_TAGVAR(export_dynamic_flag_spec, $1)=3D'${wl}-Bexport'
-      runpath_var=3D'LD_RUN_PATH'
-
-      if test "$GCC" =3D yes; then
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -shared ${wl}-h,\${SCOABSPATH:+${i=
nstall_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -shared ${wl}-Bexport:$expo=
rt_symbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libob=
js $deplibs $compiler_flags'
-      else
-	_LT_AC_TAGVAR(archive_cmds, $1)=3D'$CC -G ${wl}-h,\${SCOABSPATH:+${instal=
l_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	_LT_AC_TAGVAR(archive_expsym_cmds, $1)=3D'$CC -G ${wl}-Bexport:$export_sy=
mbols ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $d=
eplibs $compiler_flags'
-      fi
-      ;;
-
-    uts4*)
-      _LT_AC_TAGVAR(archive_cmds, $1)=3D'$LD -G -h $soname -o $lib $libobj=
s $deplibs $linker_flags'
-      _LT_AC_TAGVAR(hardcode_libdir_flag_spec, $1)=3D'-L$libdir'
-      _LT_AC_TAGVAR(hardcode_shlibpath_var, $1)=3Dno
-      ;;
-
-    *)
-      _LT_AC_TAGVAR(ld_shlibs, $1)=3Dno
-      ;;
-    esac
-  fi
-])
-AC_MSG_RESULT([$_LT_AC_TAGVAR(ld_shlibs, $1)])
-test "$_LT_AC_TAGVAR(ld_shlibs, $1)" =3D no && can_build_shared=3Dno
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)" in
-x|xyes)
-  # Assume -lc should be added
-  _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dyes
-
-  if test "$enable_shared" =3D yes && test "$GCC" =3D yes; then
-    case $_LT_AC_TAGVAR(archive_cmds, $1) in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      AC_MSG_CHECKING([whether -lc should be explicitly linked in])
-      $rm conftest*
-      printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-      if AC_TRY_EVAL(ac_compile) 2>conftest.err; then
-        soname=3Dconftest
-        lib=3Dconftest
-        libobjs=3Dconftest.$ac_objext
-        deplibs=3D
-        wl=3D$_LT_AC_TAGVAR(lt_prog_compiler_wl, $1)
-	pic_flag=3D$_LT_AC_TAGVAR(lt_prog_compiler_pic, $1)
-        compiler_flags=3D-v
-        linker_flags=3D-v
-        verstring=3D
-        output_objdir=3D.
-        libname=3Dconftest
-        lt_save_allow_undefined_flag=3D$_LT_AC_TAGVAR(allow_undefined_flag=
, $1)
-        _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D
-        if AC_TRY_EVAL(_LT_AC_TAGVAR(archive_cmds, $1) 2\>\&1 \| grep \" -=
lc \" \>/dev/null 2\>\&1)
-        then
-	  _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dno
-        else
-	  _LT_AC_TAGVAR(archive_cmds_need_lc, $1)=3Dyes
-        fi
-        _LT_AC_TAGVAR(allow_undefined_flag, $1)=3D$lt_save_allow_undefined=
_flag
-      else
-        cat conftest.err 1>&5
-      fi
-      $rm conftest*
-      AC_MSG_RESULT([$_LT_AC_TAGVAR(archive_cmds_need_lc, $1)])
-      ;;
-    esac
-  fi
-  ;;
-esac
-])# AC_LIBTOOL_PROG_LD_SHLIBS
-
-
-# _LT_AC_FILE_LTDLL_C
-# -------------------
-# Be careful that the start marker always follows a newline.
-AC_DEFUN([_LT_AC_FILE_LTDLL_C], [
-# /* ltdll.c starts here */
-# #define WIN32_LEAN_AND_MEAN
-# #include <windows.h>
-# #undef WIN32_LEAN_AND_MEAN
-# #include <stdio.h>
-#
-# #ifndef __CYGWIN__
-# #  ifdef __CYGWIN32__
-# #    define __CYGWIN__ __CYGWIN32__
-# #  endif
-# #endif
-#
-# #ifdef __cplusplus
-# extern "C" {
-# #endif
-# BOOL APIENTRY DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved);
-# #ifdef __cplusplus
-# }
-# #endif
-#
-# #ifdef __CYGWIN__
-# #include <cygwin/cygwin_dll.h>
-# DECLARE_CYGWIN_DLL( DllMain );
-# #endif
-# HINSTANCE __hDllInstance_base;
-#
-# BOOL APIENTRY
-# DllMain (HINSTANCE hInst, DWORD reason, LPVOID reserved)
-# {
-#   __hDllInstance_base =3D hInst;
-#   return TRUE;
-# }
-# /* ltdll.c ends here */
-])# _LT_AC_FILE_LTDLL_C
-
-
-# _LT_AC_TAGVAR(VARNAME, [TAGNAME])
-# ---------------------------------
-AC_DEFUN([_LT_AC_TAGVAR], [ifelse([$2], [], [$1], [$1_$2])])
-
-
-# old names
-AC_DEFUN([AM_PROG_LIBTOOL],   [AC_PROG_LIBTOOL])
-AC_DEFUN([AM_ENABLE_SHARED],  [AC_ENABLE_SHARED($@)])
-AC_DEFUN([AM_ENABLE_STATIC],  [AC_ENABLE_STATIC($@)])
-AC_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)])
-AC_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)])
-AC_DEFUN([AM_PROG_LD],        [AC_PROG_LD])
-AC_DEFUN([AM_PROG_NM],        [AC_PROG_NM])
-
-# This is just to silence aclocal about the macro not being used
-ifelse([AC_DISABLE_FAST_INSTALL])
-
-AC_DEFUN([LT_AC_PROG_GCJ],
-[AC_CHECK_TOOL(GCJ, gcj, no)
-  test "x${GCJFLAGS+set}" =3D xset || GCJFLAGS=3D"-g -O2"
-  AC_SUBST(GCJFLAGS)
-])
-
-AC_DEFUN([LT_AC_PROG_RC],
-[AC_CHECK_TOOL(RC, windres, no)
-])
-
-# NOTE: This macro has been submitted for inclusion into   #
-#  GNU Autoconf as AC_PROG_SED.  When it is available in   #
-#  a released version of Autoconf we should remove this    #
-#  macro and use it instead.                               #
-# LT_AC_PROG_SED
-# --------------
-# Check for a fully-functional sed program, that truncates
-# as few characters as possible.  Prefer GNU sed if found.
-AC_DEFUN([LT_AC_PROG_SED],
-[AC_MSG_CHECKING([for a sed that does not truncate output])
-AC_CACHE_VAL(lt_cv_path_SED,
-[# Loop through the user's path and test for sed and gsed.
-# Then use that list of sed's as ones to test for truncation.
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for lt_ac_prog in sed gsed; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
-        lt_ac_sed_list=3D"$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
-      fi
-    done
-  done
-done
-lt_ac_max=3D0
-lt_ac_count=3D0
-# Add /usr/xpg4/bin/sed as it is typically found on Solaris
-# along with /bin/sed that truncates output.
-for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
-  test ! -f $lt_ac_sed && continue
-  cat /dev/null > conftest.in
-  lt_ac_count=3D0
-  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
-  # Check for GNU sed and select it if it is found.
-  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
-    lt_cv_path_SED=3D$lt_ac_sed
-    break
-  fi
-  while true; do
-    cat conftest.in conftest.in >conftest.tmp
-    mv conftest.tmp conftest.in
-    cp conftest.in conftest.nl
-    echo >>conftest.nl
-    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
-    cmp -s conftest.out conftest.nl || break
-    # 10000 chars as input seems more than enough
-    test $lt_ac_count -gt 10 && break
-    lt_ac_count=3D`expr $lt_ac_count + 1`
-    if test $lt_ac_count -gt $lt_ac_max; then
-      lt_ac_max=3D$lt_ac_count
-      lt_cv_path_SED=3D$lt_ac_sed
-    fi
-  done
-done
-])
-SED=3D$lt_cv_path_SED
-AC_MSG_RESULT([$SED])
-])
-
-# Copyright (C) 2002, 2003, 2005, 2006  Free Software Foundation, Inc.
+# Copyright (C) 2002, 2003, 2005, 2006, 2007, 2008  Free Software Foundati=
on, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -6405,10 +31,10 @@
 # generated from the m4 files accompanying Automake X.Y.
 # (This private macro should not be called outside this file.)
 AC_DEFUN([AM_AUTOMAKE_VERSION],
-[am__api_version=3D'1.10'
+[am__api_version=3D'1.11'
 dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to
 dnl require some minimum version.  Point them to the right macro.
-m4_if([$1], [1.10], [],
+m4_if([$1], [1.11.1], [],
       [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl
 ])
=20
@@ -6422,10 +48,12 @@
 # AM_SET_CURRENT_AUTOMAKE_VERSION
 # -------------------------------
 # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced.
-# This function is AC_REQUIREd by AC_INIT_AUTOMAKE.
+# This function is AC_REQUIREd by AM_INIT_AUTOMAKE.
 AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
-[AM_AUTOMAKE_VERSION([1.10])dnl
-_AM_AUTOCONF_VERSION(m4_PACKAGE_VERSION)])
+[AM_AUTOMAKE_VERSION([1.11.1])dnl
+m4_ifndef([AC_AUTOCONF_VERSION],
+  [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
+_AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))])
=20
 # AM_AUX_DIR_EXPAND                                         -*- Autoconf -=
*-
=20
@@ -6482,14 +110,14 @@
=20
 # AM_CONDITIONAL                                            -*- Autoconf -=
*-
=20
-# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006
+# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006, 2008
 # Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
-# serial 8
+# serial 9
=20
 # AM_CONDITIONAL(NAME, SHELL-CONDITION)
 # -------------------------------------
@@ -6502,6 +130,7 @@
 AC_SUBST([$1_FALSE])dnl
 _AM_SUBST_NOTMAKE([$1_TRUE])dnl
 _AM_SUBST_NOTMAKE([$1_FALSE])dnl
+m4_define([_AM_COND_VALUE_$1], [$2])dnl
 if $2; then
   $1_TRUE=3D
   $1_FALSE=3D'#'
@@ -6515,16 +144,278 @@
 Usually this means the macro was only invoked conditionally.]])
 fi])])
=20
-# Do all the work for Automake.                             -*- Autoconf -=
*-
-
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
-# 2005, 2006 Free Software Foundation, Inc.
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2009
+# Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
-# serial 12
+# serial 10
+
+# There are a few dirty hacks below to avoid letting `AC_PROG_CC' be
+# written in clear, in which case automake, when reading aclocal.m4,
+# will think it sees a *use*, and therefore will trigger all it's
+# C support machinery.  Also note that it means that autoscan, seeing
+# CC etc. in the Makefile, will ask for an AC_PROG_CC use...
+
+
+# _AM_DEPENDENCIES(NAME)
+# ----------------------
+# See how the compiler implements dependency checking.
+# NAME is "CC", "CXX", "GCJ", or "OBJC".
+# We try a few techniques and use that to set a single cache variable.
+#
+# We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was
+# modified to invoke _AM_DEPENDENCIES(CC); we would have a circular
+# dependency, and given that the user is not expected to run this macro,
+# just rely on AC_PROG_CC.
+AC_DEFUN([_AM_DEPENDENCIES],
+[AC_REQUIRE([AM_SET_DEPDIR])dnl
+AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl
+AC_REQUIRE([AM_MAKE_INCLUDE])dnl
+AC_REQUIRE([AM_DEP_TRACK])dnl
+
+ifelse([$1], CC,   [depcc=3D"$CC"   am_compiler_list=3D],
+       [$1], CXX,  [depcc=3D"$CXX"  am_compiler_list=3D],
+       [$1], OBJC, [depcc=3D"$OBJC" am_compiler_list=3D'gcc3 gcc'],
+       [$1], UPC,  [depcc=3D"$UPC"  am_compiler_list=3D],
+       [$1], GCJ,  [depcc=3D"$GCJ"  am_compiler_list=3D'gcc3 gcc'],
+                   [depcc=3D"$$1"   am_compiler_list=3D])
+
+AC_CACHE_CHECK([dependency style of $depcc],
+               [am_cv_$1_dependencies_compiler_type],
+[if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
+  # We make a subdir and do the tests there.  Otherwise we can end up
+  # making bogus files that we don't know about and never remove.  For
+  # instance it was reported that on HP-UX the gcc test will end up
+  # making a dummy file named `D' -- because `-MD' means `put the output
+  # in D'.
+  mkdir conftest.dir
+  # Copy depcomp to subdir because otherwise we won't find it if we're
+  # using a relative directory.
+  cp "$am_depcomp" conftest.dir
+  cd conftest.dir
+  # We will build objects and dependencies in a subdirectory because
+  # it helps to detect inapplicable dependency modes.  For instance
+  # both Tru64's cc and ICC support -MD to output dependencies as a
+  # side effect of compilation, but ICC will put the dependencies in
+  # the current directory while Tru64 will put them in the object
+  # directory.
+  mkdir sub
+
+  am_cv_$1_dependencies_compiler_type=3Dnone
+  if test "$am_compiler_list" =3D ""; then
+     am_compiler_list=3D`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depco=
mp`
+  fi
+  am__universal=3Dfalse
+  m4_case([$1], [CC],
+    [case " $depcc " in #(
+     *\ -arch\ *\ -arch\ *) am__universal=3Dtrue ;;
+     esac],
+    [CXX],
+    [case " $depcc " in #(
+     *\ -arch\ *\ -arch\ *) am__universal=3Dtrue ;;
+     esac])
+
+  for depmode in $am_compiler_list; do
+    # Setup a source with many dependencies, because some compilers
+    # like to wrap large dependency lists on column 80 (with \), and
+    # we should not choose a depcomp mode which is confused by this.
+    #
+    # We need to recreate these files for each test, as the compiler may
+    # overwrite some of them when testing with obscure command lines.
+    # This happens at least with the AIX C compiler.
+    : > sub/conftest.c
+    for i in 1 2 3 4 5 6; do
+      echo '#include "conftst'$i'.h"' >> sub/conftest.c
+      # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with
+      # Solaris 8's {/usr,}/bin/sh.
+      touch sub/conftst$i.h
+    done
+    echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
+
+    # We check with `-c' and `-o' for the sake of the "dashmstdout"
+    # mode.  It turns out that the SunPro C++ compiler does not properly
+    # handle `-M -o', and we need to detect this.  Also, some Intel
+    # versions had trouble with output in subdirs
+    am__obj=3Dsub/conftest.${OBJEXT-o}
+    am__minus_obj=3D"-o $am__obj"
+    case $depmode in
+    gcc)
+      # This depmode causes a compiler race in universal mode.
+      test "$am__universal" =3D false || continue
+      ;;
+    nosideeffect)
+      # after this tag, mechanisms are not by side-effect, so they'll
+      # only be used when explicitly requested
+      if test "x$enable_dependency_tracking" =3D xyes; then
+	continue
+      else
+	break
+      fi
+      ;;
+    msvisualcpp | msvcmsys)
+      # This compiler won't grok `-c -o', but also, the minuso test has
+      # not run yet.  These depmodes are late enough in the game, and
+      # so weak that their functioning should not be impacted.
+      am__obj=3Dconftest.${OBJEXT-o}
+      am__minus_obj=3D
+      ;;
+    none) break ;;
+    esac
+    if depmode=3D$depmode \
+       source=3Dsub/conftest.c object=3D$am__obj \
+       depfile=3Dsub/conftest.Po tmpdepfile=3Dsub/conftest.TPo \
+       $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \
+         >/dev/null 2>conftest.err &&
+       grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
+       grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
+       grep $am__obj sub/conftest.Po > /dev/null 2>&1 &&
+       ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
+      # icc doesn't choke on unknown options, it will just issue warnings
+      # or remarks (even with -Werror).  So we grep stderr for any message
+      # that says an option was ignored or not supported.
+      # When given -MP, icc 7.0 and 7.1 complain thusly:
+      #   icc: Command line warning: ignoring option '-M'; no argument req=
uired
+      # The diagnosis changed in icc 8.0:
+      #   icc: Command line remark: option '-MP' not supported
+      if (grep 'ignoring option' conftest.err ||
+          grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
+        am_cv_$1_dependencies_compiler_type=3D$depmode
+        break
+      fi
+    fi
+  done
+
+  cd ..
+  rm -rf conftest.dir
+else
+  am_cv_$1_dependencies_compiler_type=3Dnone
+fi
+])
+AC_SUBST([$1DEPMODE], [depmode=3D$am_cv_$1_dependencies_compiler_type])
+AM_CONDITIONAL([am__fastdep$1], [
+  test "x$enable_dependency_tracking" !=3D xno \
+  && test "$am_cv_$1_dependencies_compiler_type" =3D gcc3])
+])
+
+
+# AM_SET_DEPDIR
+# -------------
+# Choose a directory name for dependency files.
+# This macro is AC_REQUIREd in _AM_DEPENDENCIES
+AC_DEFUN([AM_SET_DEPDIR],
+[AC_REQUIRE([AM_SET_LEADING_DOT])dnl
+AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl
+])
+
+
+# AM_DEP_TRACK
+# ------------
+AC_DEFUN([AM_DEP_TRACK],
+[AC_ARG_ENABLE(dependency-tracking,
+[  --disable-dependency-tracking  speeds up one-time build
+  --enable-dependency-tracking   do not reject slow dependency extractors])
+if test "x$enable_dependency_tracking" !=3D xno; then
+  am_depcomp=3D"$ac_aux_dir/depcomp"
+  AMDEPBACKSLASH=3D'\'
+fi
+AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" !=3D xno])
+AC_SUBST([AMDEPBACKSLASH])dnl
+_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl
+])
+
+# Generate code to set up dependency tracking.              -*- Autoconf -=
*-
+
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2008
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+#serial 5
+
+# _AM_OUTPUT_DEPENDENCY_COMMANDS
+# ------------------------------
+AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS],
+[{
+  # Autoconf 2.62 quotes --file arguments for eval, but not when files
+  # are listed without --file.  Let's play safe and only enable the eval
+  # if we detect the quoting.
+  case $CONFIG_FILES in
+  *\'*) eval set x "$CONFIG_FILES" ;;
+  *)   set x $CONFIG_FILES ;;
+  esac
+  shift
+  for mf
+  do
+    # Strip MF so we end up with the name of the file.
+    mf=3D`echo "$mf" | sed -e 's/:.*$//'`
+    # Check whether this is an Automake generated Makefile or not.
+    # We used to match only the files named `Makefile.in', but
+    # some people rename them; so instead we look at the file content.
+    # Grep'ing the first line is not enough: some people post-process
+    # each Makefile.in and add a new line on top of each file to say so.
+    # Grep'ing the whole file is not good either: AIX grep has a line
+    # limit of 2048, but all sed's we know have understand at least 4000.
+    if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/nul=
l 2>&1; then
+      dirpart=3D`AS_DIRNAME("$mf")`
+    else
+      continue
+    fi
+    # Extract the definition of DEPDIR, am__include, and am__quote
+    # from the Makefile without running `make'.
+    DEPDIR=3D`sed -n 's/^DEPDIR =3D //p' < "$mf"`
+    test -z "$DEPDIR" && continue
+    am__include=3D`sed -n 's/^am__include =3D //p' < "$mf"`
+    test -z "am__include" && continue
+    am__quote=3D`sed -n 's/^am__quote =3D //p' < "$mf"`
+    # When using ansi2knr, U may be empty or an underscore; expand it
+    U=3D`sed -n 's/^U =3D //p' < "$mf"`
+    # Find all dependency output files, they are included files with
+    # $(DEPDIR) in their names.  We invoke sed twice because it is the
+    # simplest approach to changing $(DEPDIR) to its actual value in the
+    # expansion.
+    for file in `sed -n "
+      s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf"=
 | \
+	 sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
+      # Make sure the directory exists.
+      test -f "$dirpart/$file" && continue
+      fdir=3D`AS_DIRNAME(["$file"])`
+      AS_MKDIR_P([$dirpart/$fdir])
+      # echo "creating $dirpart/$file"
+      echo '# dummy' > "$dirpart/$file"
+    done
+  done
+}
+])# _AM_OUTPUT_DEPENDENCY_COMMANDS
+
+
+# AM_OUTPUT_DEPENDENCY_COMMANDS
+# -----------------------------
+# This macro should only be invoked once -- use via AC_REQUIRE.
+#
+# This code is only required when automatic dependency tracking
+# is enabled.  FIXME.  This creates each `.P' file that we will
+# need in order to bootstrap the dependency handling code.
+AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS],
+[AC_CONFIG_COMMANDS([depfiles],
+     [test x"$AMDEP_TRUE" !=3D x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS],
+     [AMDEP_TRUE=3D"$AMDEP_TRUE" ac_aux_dir=3D"$ac_aux_dir"])
+])
+
+# Do all the work for Automake.                             -*- Autoconf -=
*-
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+# 2005, 2006, 2008, 2009 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 16
=20
 # This macro actually does too much.  Some checks are only needed if
 # your package does certain things.  But this isn't really a big deal.
@@ -6541,7 +432,7 @@
 # arguments mandatory, and then we can depend on a new Autoconf
 # release and drop the old call support.
 AC_DEFUN([AM_INIT_AUTOMAKE],
-[AC_PREREQ([2.60])dnl
+[AC_PREREQ([2.62])dnl
 dnl Autoconf wants to disallow AM_ names.  We explicitly allow
 dnl the ones we care about.
 m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl
@@ -6592,8 +483,8 @@
 AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version})
 AM_MISSING_PROG(AUTOHEADER, autoheader)
 AM_MISSING_PROG(MAKEINFO, makeinfo)
-AM_PROG_INSTALL_SH
-AM_PROG_INSTALL_STRIP
+AC_REQUIRE([AM_PROG_INSTALL_SH])dnl
+AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl
 AC_REQUIRE([AM_PROG_MKDIR_P])dnl
 # We need awk for the "check" target.  The system "awk" is bad on
 # some platforms.
@@ -6601,24 +492,37 @@
 AC_REQUIRE([AC_PROG_MAKE_SET])dnl
 AC_REQUIRE([AM_SET_LEADING_DOT])dnl
 _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])],
-              [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
-	      		     [_AM_PROG_TAR([v7])])])
+	      [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
+			     [_AM_PROG_TAR([v7])])])
 _AM_IF_OPTION([no-dependencies],,
 [AC_PROVIDE_IFELSE([AC_PROG_CC],
-                  [_AM_DEPENDENCIES(CC)],
-                  [define([AC_PROG_CC],
-                          defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl
+		  [_AM_DEPENDENCIES(CC)],
+		  [define([AC_PROG_CC],
+			  defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl
 AC_PROVIDE_IFELSE([AC_PROG_CXX],
-                  [_AM_DEPENDENCIES(CXX)],
-                  [define([AC_PROG_CXX],
-                          defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl
+		  [_AM_DEPENDENCIES(CXX)],
+		  [define([AC_PROG_CXX],
+			  defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl
 AC_PROVIDE_IFELSE([AC_PROG_OBJC],
-                  [_AM_DEPENDENCIES(OBJC)],
-                  [define([AC_PROG_OBJC],
-                          defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])d=
nl
+		  [_AM_DEPENDENCIES(OBJC)],
+		  [define([AC_PROG_OBJC],
+			  defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl
 ])
+_AM_IF_OPTION([silent-rules], [AC_REQUIRE([AM_SILENT_RULES])])dnl
+dnl The `parallel-tests' driver may need to know about EXEEXT, so add the
+dnl `am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen.  This macro
+dnl is hooked onto _AC_COMPILER_EXEEXT early, see below.
+AC_CONFIG_COMMANDS_PRE(dnl
+[m4_provide_if([_AM_COMPILER_EXEEXT],
+  [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl
 ])
=20
+dnl Hook into `_AC_COMPILER_EXEEXT' early to learn its expansion.  Do not
+dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further
+dnl mangled by Autoconf and run in a shell conditional statement.
+m4_define([_AC_COMPILER_EXEEXT],
+m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])])
+
=20
 # When config.status generates a header, we must update the stamp-h file.
 # This file resides in the same directory as the config header
@@ -6629,18 +533,19 @@
 # our stamp files there.
 AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK],
 [# Compute $1's index in $config_headers.
+_am_arg=3D$1
 _am_stamp_count=3D1
 for _am_header in $config_headers :; do
   case $_am_header in
-    $1 | $1:* )
+    $_am_arg | $_am_arg:* )
       break ;;
     * )
       _am_stamp_count=3D`expr $_am_stamp_count + 1` ;;
   esac
 done
-echo "timestamp for $1" >`AS_DIRNAME([$1])`/stamp-h[]$_am_stamp_count])
+echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_st=
amp_count])
=20
-# Copyright (C) 2001, 2003, 2005  Free Software Foundation, Inc.
+# Copyright (C) 2001, 2003, 2005, 2008  Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
@@ -6651,7 +556,14 @@
 # Define $install_sh.
 AC_DEFUN([AM_PROG_INSTALL_SH],
 [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-install_sh=3D${install_sh-"\$(SHELL) $am_aux_dir/install-sh"}
+if test x"${install_sh}" !=3D xset; then
+  case $am_aux_dir in
+  *\ * | *\	*)
+    install_sh=3D"\${SHELL} '$am_aux_dir/install-sh'" ;;
+  *)
+    install_sh=3D"\${SHELL} $am_aux_dir/install-sh"
+  esac
+fi
 AC_SUBST(install_sh)])
=20
 # Copyright (C) 2003, 2005  Free Software Foundation, Inc.
@@ -6699,40 +611,103 @@
 # Add --enable-maintainer-mode option to configure.         -*- Autoconf -=
*-
 # From Jim Meyering
=20
-# Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005
+# Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2008
 # Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
+# serial 5
+
+# AM_MAINTAINER_MODE([DEFAULT-MODE])
+# ----------------------------------
+# Control maintainer-specific portions of Makefiles.
+# Default is to disable them, unless `enable' is passed literally.
+# For symmetry, `disable' may be passed as well.  Anyway, the user
+# can override the default with the --enable/--disable switch.
+AC_DEFUN([AM_MAINTAINER_MODE],
+[m4_case(m4_default([$1], [disable]),
+       [enable], [m4_define([am_maintainer_other], [disable])],
+       [disable], [m4_define([am_maintainer_other], [enable])],
+       [m4_define([am_maintainer_other], [enable])
+        m4_warn([syntax], [unexpected argument to AM@&t at _MAINTAINER_MODE: =
$1])])
+AC_MSG_CHECKING([whether to am_maintainer_other maintainer-specific portio=
ns of Makefiles])
+  dnl maintainer-mode's default is 'disable' unless 'enable' is passed
+  AC_ARG_ENABLE([maintainer-mode],
+[  --][am_maintainer_other][-maintainer-mode  am_maintainer_other make rul=
es and dependencies not useful
+			  (and sometimes confusing) to the casual installer],
+      [USE_MAINTAINER_MODE=3D$enableval],
+      [USE_MAINTAINER_MODE=3D]m4_if(am_maintainer_other, [enable], [no], [=
yes]))
+  AC_MSG_RESULT([$USE_MAINTAINER_MODE])
+  AM_CONDITIONAL([MAINTAINER_MODE], [test $USE_MAINTAINER_MODE =3D yes])
+  MAINT=3D$MAINTAINER_MODE_TRUE
+  AC_SUBST([MAINT])dnl
+]
+)
+
+AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE])
+
+# Check to see how 'make' treats includes.	            -*- Autoconf -*-
+
+# Copyright (C) 2001, 2002, 2003, 2005, 2009  Free Software Foundation, In=
c.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
 # serial 4
=20
-AC_DEFUN([AM_MAINTAINER_MODE],
-[AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefi=
les])
-  dnl maintainer-mode is disabled by default
-  AC_ARG_ENABLE(maintainer-mode,
-[  --enable-maintainer-mode  enable make rules and dependencies not useful
-			  (and sometimes confusing) to the casual installer],
-      USE_MAINTAINER_MODE=3D$enableval,
-      USE_MAINTAINER_MODE=3Dno)
-  AC_MSG_RESULT([$USE_MAINTAINER_MODE])
-  AM_CONDITIONAL(MAINTAINER_MODE, [test $USE_MAINTAINER_MODE =3D yes])
-  MAINT=3D$MAINTAINER_MODE_TRUE
-  AC_SUBST(MAINT)dnl
-]
-)
+# AM_MAKE_INCLUDE()
+# -----------------
+# Check to see how make treats includes.
+AC_DEFUN([AM_MAKE_INCLUDE],
+[am_make=3D${MAKE-make}
+cat > confinc << 'END'
+am__doit:
+	@echo this is the am__doit target
+.PHONY: am__doit
+END
+# If we don't find an include directive, just comment out the code.
+AC_MSG_CHECKING([for style of include used by $am_make])
+am__include=3D"#"
+am__quote=3D
+_am_result=3Dnone
+# First try GNU make style include.
+echo "include confinc" > confmf
+# Ignore all kinds of additional output from `make'.
+case `$am_make -s -f confmf 2> /dev/null` in #(
+*the\ am__doit\ target*)
+  am__include=3Dinclude
+  am__quote=3D
+  _am_result=3DGNU
+  ;;
+esac
+# Now try BSD make style include.
+if test "$am__include" =3D "#"; then
+   echo '.include "confinc"' > confmf
+   case `$am_make -s -f confmf 2> /dev/null` in #(
+   *the\ am__doit\ target*)
+     am__include=3D.include
+     am__quote=3D"\""
+     _am_result=3DBSD
+     ;;
+   esac
+fi
+AC_SUBST([am__include])
+AC_SUBST([am__quote])
+AC_MSG_RESULT([$_am_result])
+rm -f confinc confmf
+])
=20
-AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE])
-
-# Copyright (C) 1999, 2000, 2001, 2003, 2004, 2005
+# Copyright (C) 1999, 2000, 2001, 2003, 2004, 2005, 2008
 # Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
-# serial 5
+# serial 6
=20
 # AM_PROG_CC_C_O
 # --------------
@@ -6744,8 +719,9 @@
 # FIXME: we rely on the cache variable name because
 # there is no other way.
 set dummy $CC
-ac_cc=3D`echo $[2] | sed ['s/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/']`
-if eval "test \"`echo '$ac_cv_prog_cc_'${ac_cc}_c_o`\" !=3D yes"; then
+am_cc=3D`echo $[2] | sed ['s/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/']`
+eval am_t=3D\$ac_cv_prog_cc_${am_cc}_c_o
+if test "$am_t" !=3D yes; then
    # Losing compiler, so override with the script.
    # FIXME: It is wrong to rewrite CC.
    # But if we don't then we get into trouble of one sort or another.
@@ -6761,14 +737,14 @@
=20
 # Fake the existence of programs that GNU maintainers use.  -*- Autoconf -=
*-
=20
-# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005
+# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005, 2008
 # Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
-# serial 5
+# serial 6
=20
 # AM_MISSING_PROG(NAME, PROGRAM)
 # ------------------------------
@@ -6785,7 +761,14 @@
 AC_DEFUN([AM_MISSING_HAS_RUN],
 [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
 AC_REQUIRE_AUX_FILE([missing])dnl
-test x"${MISSING+set}" =3D xset || MISSING=3D"\${SHELL} $am_aux_dir/missin=
g"
+if test x"${MISSING+set}" !=3D xset; then
+  case $am_aux_dir in
+  *\ * | *\	*)
+    MISSING=3D"\${SHELL} \"$am_aux_dir/missing\"" ;;
+  *)
+    MISSING=3D"\${SHELL} $am_aux_dir/missing" ;;
+  esac
+fi
 # Use eval to expand $SHELL
 if eval "$MISSING --run true"; then
   am_missing_run=3D"$MISSING --run "
@@ -6823,13 +806,13 @@
=20
 # Helper functions for option handling.                     -*- Autoconf -=
*-
=20
-# Copyright (C) 2001, 2002, 2003, 2005  Free Software Foundation, Inc.
+# Copyright (C) 2001, 2002, 2003, 2005, 2008  Free Software Foundation, In=
c.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
-# serial 3
+# serial 4
=20
 # _AM_MANGLE_OPTION(NAME)
 # -----------------------
@@ -6846,7 +829,7 @@
 # ----------------------------------
 # OPTIONS is a space-separated list of Automake options.
 AC_DEFUN([_AM_SET_OPTIONS],
-[AC_FOREACH([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])])
+[m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])])
=20
 # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET])
 # -------------------------------------------
@@ -6856,14 +839,14 @@
=20
 # Check to make sure that the build environment is sane.    -*- Autoconf -=
*-
=20
-# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005
+# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005, 2008
 # Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
-# serial 4
+# serial 5
=20
 # AM_SANITY_CHECK
 # ---------------
@@ -6872,16 +855,29 @@
 # Just in case
 sleep 1
 echo timestamp > conftest.file
+# Reject unsafe characters in $srcdir or the absolute working directory
+# name.  Accept space and tab only in the latter.
+am_lf=3D'
+'
+case `pwd` in
+  *[[\\\"\#\$\&\'\`$am_lf]]*)
+    AC_MSG_ERROR([unsafe absolute working directory name]);;
+esac
+case $srcdir in
+  *[[\\\"\#\$\&\'\`$am_lf\ \	]]*)
+    AC_MSG_ERROR([unsafe srcdir value: `$srcdir']);;
+esac
+
 # Do `set' in a subshell so we don't clobber the current shell's
 # arguments.  Must try -L first in case configure is actually a
 # symlink; some systems play weird games with the mod time of symlinks
 # (eg FreeBSD returns the mod time of the symlink's containing
 # directory).
 if (
-   set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null`
+   set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null`
    if test "$[*]" =3D "X"; then
       # -L didn't work.
-      set X `ls -t $srcdir/configure conftest.file`
+      set X `ls -t "$srcdir/configure" conftest.file`
    fi
    rm -f conftest.file
    if test "$[*]" !=3D "X $srcdir/configure conftest.file" \
@@ -6934,18 +930,25 @@
 INSTALL_STRIP_PROGRAM=3D"\$(install_sh) -c -s"
 AC_SUBST([INSTALL_STRIP_PROGRAM])])
=20
-# Copyright (C) 2006  Free Software Foundation, Inc.
+# Copyright (C) 2006, 2008  Free Software Foundation, Inc.
 #
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
=20
+# serial 2
+
 # _AM_SUBST_NOTMAKE(VARIABLE)
 # ---------------------------
-# Prevent Automake from outputing VARIABLE =3D @VARIABLE@ in Makefile.in.
+# Prevent Automake from outputting VARIABLE =3D @VARIABLE@ in Makefile.in.
 # This macro is traced by Automake.
 AC_DEFUN([_AM_SUBST_NOTMAKE])
=20
+# AM_SUBST_NOTMAKE(VARIABLE)
+# ---------------------------
+# Public sister of _AM_SUBST_NOTMAKE.
+AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)])
+
 # Check how to create a tarball.                            -*- Autoconf -=
*-
=20
 # Copyright (C) 2004, 2005  Free Software Foundation, Inc.
@@ -7044,7 +1047,6 @@
=20
 m4_include([cf/aix.m4])
 m4_include([cf/auth-modules.m4])
-m4_include([cf/autobuild.m4])
 m4_include([cf/broken-getaddrinfo.m4])
 m4_include([cf/broken-glob.m4])
 m4_include([cf/broken-realloc.m4])
@@ -7064,6 +1066,7 @@
 m4_include([cf/crypto.m4])
 m4_include([cf/db.m4])
 m4_include([cf/destdirs.m4])
+m4_include([cf/dispatch.m4])
 m4_include([cf/dlopen.m4])
 m4_include([cf/find-func-no-libs.m4])
 m4_include([cf/find-func-no-libs2.m4])
@@ -7081,11 +1084,17 @@
 m4_include([cf/krb-struct-spwd.m4])
 m4_include([cf/krb-struct-winsize.m4])
 m4_include([cf/largefile.m4])
+m4_include([cf/libtool.m4])
+m4_include([cf/ltoptions.m4])
+m4_include([cf/ltsugar.m4])
+m4_include([cf/ltversion.m4])
+m4_include([cf/lt~obsolete.m4])
 m4_include([cf/mips-abi.m4])
 m4_include([cf/misc.m4])
 m4_include([cf/need-proto.m4])
 m4_include([cf/osfc2.m4])
 m4_include([cf/otp.m4])
+m4_include([cf/pkg.m4])
 m4_include([cf/proto-compat.m4])
 m4_include([cf/pthreads.m4])
 m4_include([cf/resolv.m4])
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/ChangeLog
--- a/head/crypto/heimdal/admin/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add man_MANS to EXTRA_DIST
=20
 	* Makefile.am: split build files into dist_ and noinst_ SOURCES
 =09
-2005-07-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ktutil.c: rename optind to optidx
=20
@@ -18,7 +18,7 @@
 	shadowing; make a copy of realm and admin_server to avoid
 	un-consting.
=20
-2005-05-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* change.c (kt_change): plug memory leak from
 	krb5_kt_remove_entry, print principal on error.
@@ -27,11 +27,11 @@
=20
 	* ktutil.c (help): Don't use non-constant initializer for `fake'.
=20
-2005-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ktutil_locl.h: include <hex.h>
=20
-2005-04-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* add.c: add option -H --hex to the add command
 =09
@@ -39,7 +39,7 @@
 =09
 	* ktutil.8: document option -H --hex to the add command
=20
-2004-09-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* list.c: un c99'ify, from Anders.Magnusson at ltu.se
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/Makefile.am
--- a/head/crypto/heimdal/admin/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,11 +1,9 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
 AM_CPPFLAGS +=3D $(INCLUDE_readline) $(INCLUDE_hcrypto)
=20
-SLC =3D $(top_builddir)/lib/sl/slc
-
 man_MANS =3D ktutil.8
=20
 sbin_PROGRAMS =3D ktutil
@@ -14,6 +12,7 @@
 	add.c					\
 	change.c				\
 	copy.c					\
+	destroy.c				\
 	get.c					\
 	ktutil.c				\
 	ktutil_locl.h				\
@@ -41,4 +40,4 @@
 	$(LIB_readline) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS) ktutil-commands.in
+EXTRA_DIST =3D NTMakefile ktutil-version.rc $(man_MANS) ktutil-commands.in
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/Makefile.in
--- a/head/crypto/heimdal/admin/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D admin
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,18 +89,19 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(man8dir)"
-sbinPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(sbin_PROGRAMS)
 dist_ktutil_OBJECTS =3D add.$(OBJEXT) change.$(OBJEXT) copy.$(OBJEXT) \
-	get.$(OBJEXT) ktutil.$(OBJEXT) list.$(OBJEXT) purge.$(OBJEXT) \
-	remove.$(OBJEXT) rename.$(OBJEXT)
+	destroy.$(OBJEXT) get.$(OBJEXT) ktutil.$(OBJEXT) \
+	list.$(OBJEXT) purge.$(OBJEXT) remove.$(OBJEXT) \
+	rename.$(OBJEXT)
 nodist_ktutil_OBJECTS =3D ktutil-commands.$(OBJEXT)
 ktutil_OBJECTS =3D $(dist_ktutil_OBJECTS) $(nodist_ktutil_OBJECTS)
 ktutil_LDADD =3D $(LDADD)
@@ -105,9 +111,9 @@
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(top_builddir)/lib/sl/libsl.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -119,6 +125,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(dist_ktutil_SOURCES) $(nodist_ktutil_SOURCES)
 DIST_SOURCES =3D $(dist_ktutil_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -128,49 +155,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -194,10 +230,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -214,6 +251,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -229,31 +268,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -268,10 +321,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -312,37 +367,41 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_readline) $(INCLUDE_hcrypto)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_readline) $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
-SLC =3D $(top_builddir)/lib/sl/slc
 man_MANS =3D ktutil.8
 dist_ktutil_SOURCES =3D \
 	add.c					\
 	change.c				\
 	copy.c					\
+	destroy.c				\
 	get.c					\
 	ktutil.c				\
 	ktutil_locl.h				\
@@ -364,23 +423,23 @@
 	$(LIB_readline) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS) ktutil-commands.in
+EXTRA_DIST =3D NTMakefile ktutil-version.rc $(man_MANS) ktutil-commands.in
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps admin/Mak=
efile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps admin/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign admin/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign admin/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -398,34 +457,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-sbinPROGRAMS: $(sbin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(sbindir)" || $(MKDIR_P) "$(DESTDIR)$(sbindir)"
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRA=
MS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRAMS_INST=
ALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$d=
ir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || =
exit $$?; \
+	    } \
+	; done
=20
 uninstall-sbinPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(sbindir)/$$f"; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(sbindir)" && rm -f $$files
=20
 clean-sbinPROGRAMS:
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 ktutil$(EXEEXT): $(ktutil_OBJECTS) $(ktutil_DEPENDENCIES)=20
 	@rm -f ktutil$(EXEEXT)
 	$(LINK) $(ktutil_OBJECTS) $(ktutil_LDADD) $(LIBS)
@@ -436,115 +511,149 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/add.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/change.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/copy.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/destroy.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/get.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ktutil-commands.Po at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ktutil.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/list.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/purge.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/remove.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rename.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man8: $(man8_MANS) $(man_MANS)
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -560,13 +669,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -602,6 +715,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -612,6 +726,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -622,6 +737,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -629,26 +746,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -668,11 +794,10 @@
 uninstall-am: uninstall-man uninstall-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libtool clean-sbinPROGRAMS ctags \
@@ -759,6 +884,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -844,7 +972,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -862,6 +990,7 @@
=20
 ktutil-commands.c ktutil-commands.h: ktutil-commands.in
 	$(SLC) $(srcdir)/ktutil-commands.in
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/add.c
--- a/head/crypto/heimdal/admin/add.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/add.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
=20
-RCSID("$Id: add.c 14793 2005-04-14 16:45:14Z lha $");
+RCSID("$Id$");
=20
 static char *
 readstring(const char *prompt, char *buf, size_t len)
@@ -104,7 +104,7 @@
 	if (opt->hex_flag) {
 	    size_t len;
 	    void *data;
-	   =20
+
 	    len =3D (strlen(opt->password_string) + 1) / 2;
=20
 	    data =3D malloc(len);
@@ -113,13 +113,13 @@
 		goto out;
 	    }
=20
-	    if (hex_decode(opt->password_string, data, len) !=3D len) {
+	    if ((size_t)hex_decode(opt->password_string, data, len) !=3D len) {
 		free(data);
 		krb5_warn(context, ENOMEM, "hex decode failed");
 		goto out;
 	    }
=20
-	    ret =3D krb5_keyblock_init(context, enctype,=20
+	    ret =3D krb5_keyblock_init(context, enctype,
 				     data, len, &entry.keyblock);
 	    free(data);
 	} else if (!opt->salt_flag) {
@@ -134,7 +134,7 @@
 	    ret =3D krb5_string_to_key_data_salt(context, enctype, pw, salt,
 					       &entry.keyblock);
         } else {
-	    ret =3D krb5_string_to_key(context, enctype, opt->password_string,=20
+	    ret =3D krb5_string_to_key(context, enctype, opt->password_string,
 				     entry.principal, &entry.keyblock);
 	}
 	memset (opt->password_string, 0, strlen(opt->password_string));
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/change.c
--- a/head/crypto/heimdal/admin/change.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/change.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
=20
-RCSID("$Id: change.c 15578 2005-07-07 20:44:48Z lha $");
+RCSID("$Id$");
=20
 static krb5_error_code
 change_entry (krb5_keytab keytab,
@@ -61,19 +61,19 @@
     conf.realm =3D strdup(realm);
     if (conf.realm =3D=3D NULL) {
 	free (client_name);
-	krb5_set_error_string(context, "malloc failed");
+	krb5_set_error_message(context, ENOMEM, "malloc failed");
 	return ENOMEM;
     }
     conf.mask |=3D KADM5_CONFIG_REALM;
-   =20
+
     if (admin_server) {
 	conf.admin_server =3D strdup(admin_server);
 	if (conf.admin_server =3D=3D NULL) {
 	    free(client_name);
 	    free(conf.realm);
-	    krb5_set_error_string(context, "malloc failed");
+	    krb5_set_error_message(context, ENOMEM, "malloc failed");
 	    return ENOMEM;
-	}	   =20
+	}
 	conf.mask |=3D KADM5_CONFIG_ADMIN_SERVER;
     }
=20
@@ -140,7 +140,7 @@
     int i, j, max;
     struct change_set *changeset;
     int errors =3D 0;
-   =20
+
     if((keytab =3D ktutil_open_keytab()) =3D=3D NULL)
 	return 1;
=20
@@ -222,20 +222,20 @@
 	    if (verbose_flag) {
 		char *client_name;
=20
-		ret =3D krb5_unparse_name (context, changeset[i].principal,=20
+		ret =3D krb5_unparse_name (context, changeset[i].principal,
 					 &client_name);
 		if (ret) {
 		    krb5_warn (context, ret, "krb5_unparse_name");
 		} else {
-		    printf("Changing %s kvno %d\n",=20
+		    printf("Changing %s kvno %d\n",
 			   client_name, changeset[i].kvno);
 		    free(client_name);
 		}
 	    }
-	    ret =3D change_entry (keytab,=20
+	    ret =3D change_entry (keytab,
 				changeset[i].principal, changeset[i].kvno,
-				opt->realm_string,=20
-				opt->admin_server_string,=20
+				opt->realm_string,
+				opt->admin_server_string,
 				opt->server_port_integer);
 	    if (ret !=3D 0)
 		errors =3D 1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/copy.c
--- a/head/crypto/heimdal/admin/copy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/copy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
=20
-RCSID("$Id: copy.c 14260 2004-09-23 14:45:29Z joda $");
+RCSID("$Id$");
=20
=20
 static krb5_boolean
@@ -46,13 +46,15 @@
     return TRUE;
 }
=20
-static int
-kt_copy_int (const char *from, const char *to)
+int
+kt_copy (void *opt, int argc, char **argv)
 {
     krb5_error_code ret;
     krb5_keytab src_keytab, dst_keytab;
     krb5_kt_cursor cursor;
     krb5_keytab_entry entry, dummy;
+    const char *from =3D argv[0];
+    const char *to =3D argv[1];
=20
     ret =3D krb5_kt_resolve (context, from, &src_keytab);
     if (ret) {
@@ -90,9 +92,9 @@
 	    krb5_warn(context, ret, "krb5_enctype_to_string");
 	    etype_str =3D NULL; /* XXX */
 	}
-	ret =3D krb5_kt_get_entry(context, dst_keytab,=20
-				entry.principal,=20
-				entry.vno,=20
+	ret =3D krb5_kt_get_entry(context, dst_keytab,
+				entry.principal,
+				entry.vno,
 				entry.keyblock.keytype,
 				&dummy);
 	if(ret =3D=3D 0) {
@@ -101,7 +103,7 @@
                is weird, so complain about that */
 	    if(!compare_keyblock(&entry.keyblock, &dummy.keyblock)) {
 		krb5_warnx(context, "entry with different keyvalue "
-			   "already exists for %s, keytype %s, kvno %d",=20
+			   "already exists for %s, keytype %s, kvno %d",
 			   name_str, etype_str, entry.vno);
 	    }
 	    krb5_kt_free_entry(context, &dummy);
@@ -110,7 +112,7 @@
 	    free(etype_str);
 	    continue;
 	} else if(ret !=3D KRB5_KT_NOTFOUND) {
-	    krb5_warn (context, ret, "%s: fetching %s/%s/%u",=20
+	    krb5_warn (context, ret, "%s: fetching %s/%s/%u",
 		       to, name_str, etype_str, entry.vno);
 	    krb5_kt_free_entry (context, &entry);
 	    free(name_str);
@@ -118,12 +120,12 @@
 	    break;
 	}
 	if (verbose_flag)
-	    fprintf (stderr, "copying %s, keytype %s, kvno %d\n", name_str,=20
+	    fprintf (stderr, "copying %s, keytype %s, kvno %d\n", name_str,
 		     etype_str, entry.vno);
 	ret =3D krb5_kt_add_entry (context, dst_keytab, &entry);
 	krb5_kt_free_entry (context, &entry);
 	if (ret) {
-	    krb5_warn (context, ret, "%s: adding %s/%s/%u",=20
+	    krb5_warn (context, ret, "%s: adding %s/%s/%u",
 		       to, name_str, etype_str, entry.vno);
 	    free(name_str);
 	    free(etype_str);
@@ -139,37 +141,3 @@
     krb5_kt_close (context, dst_keytab);
     return ret !=3D 0;
 }
-
-int
-kt_copy (void *opt, int argc, char **argv)
-{
-    return kt_copy_int(argv[0], argv[1]);
-}
-
-int
-srvconv(struct srvconvert_options *opt, int argc, char **argv)
-{
-    char kt4[1024], kt5[1024];
-
-    snprintf(kt4, sizeof(kt4), "krb4:%s", opt->srvtab_string);
-
-    if(keytab_string !=3D NULL)
-	return kt_copy_int(kt4, keytab_string);
-
-    krb5_kt_default_modify_name(context, kt5, sizeof(kt5));
-    return kt_copy_int(kt4, kt5);
-}
-
-int
-srvcreate(struct srvcreate_options *opt, int argc, char **argv)
-{
-    char kt4[1024], kt5[1024];
-
-    snprintf(kt4, sizeof(kt4), "krb4:%s", opt->srvtab_string);
-
-    if(keytab_string !=3D NULL)
-	return kt_copy_int(keytab_string, kt4);
-
-    krb5_kt_default_name(context, kt5, sizeof(kt5));
-    return kt_copy_int(kt5, kt4);
-}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/get.c
--- a/head/crypto/heimdal/admin/get.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/get.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,44 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
=20
-RCSID("$Id: get.c 15583 2005-07-07 21:44:37Z lha $");
+RCSID("$Id$");
=20
 static void*
 open_kadmin_connection(char *principal,
-		       const char *realm,=20
-		       char *admin_server,=20
+		       const char *realm,
+		       char *admin_server,
 		       int server_port)
 {
     static kadm5_config_params conf;
@@ -49,12 +49,12 @@
     if(realm) {
 	conf.realm =3D strdup(realm);
 	if (conf.realm =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, 0, "malloc: out of memory");
 	    return NULL;
 	}
 	conf.mask |=3D KADM5_CONFIG_REALM;
     }
-   =20
+
     if (admin_server) {
 	conf.admin_server =3D admin_server;
 	conf.mask |=3D KADM5_CONFIG_ADMIN_SERVER;
@@ -68,11 +68,11 @@
     /* should get realm from each principal, instead of doing
        everything with the same (local) realm */
=20
-    ret =3D kadm5_init_with_password_ctx(context,=20
+    ret =3D kadm5_init_with_password_ctx(context,
 				       principal,
 				       NULL,
 				       KADM5_ADMIN_SERVICE,
-				       &conf, 0, 0,=20
+				       &conf, 0, 0,
 				       &kadm_handle);
     free(conf.realm);
     if(ret) {
@@ -90,9 +90,10 @@
     void *kadm_handle =3D NULL;
     krb5_enctype *etypes =3D NULL;
     size_t netypes =3D 0;
-    int i, j;
+    size_t i;
+    int a, j;
     unsigned int failed =3D 0;
-   =20
+
     if((keytab =3D ktutil_open_keytab()) =3D=3D NULL)
 	return 1;
=20
@@ -108,8 +109,8 @@
 	}
 	netypes =3D opt->enctypes_strings.num_strings;
 	for(i =3D 0; i < netypes; i++) {
-	    ret =3D krb5_string_to_enctype(context,=20
-					 opt->enctypes_strings.strings[i],=20
+	    ret =3D krb5_string_to_enctype(context,
+					 opt->enctypes_strings.strings[i],
 					 &etypes[i]);
 	    if(ret) {
 		krb5_warnx(context, "unrecognized enctype: %s",
@@ -119,8 +120,8 @@
 	}
     }
=20
-   =20
-    for(i =3D 0; i < argc; i++){
+
+    for(a =3D 0; a < argc; a++){
 	krb5_principal princ_ent;
 	kadm5_principal_ent_rec princ;
 	int mask =3D 0;
@@ -129,9 +130,9 @@
 	int created =3D 0;
 	krb5_keytab_entry entry;
=20
-	ret =3D krb5_parse_name(context, argv[i], &princ_ent);
+	ret =3D krb5_parse_name(context, argv[a], &princ_ent);
 	if (ret) {
-	    krb5_warn(context, ret, "can't parse principal %s", argv[i]);
+	    krb5_warn(context, ret, "can't parse principal %s", argv[a]);
 	    failed++;
 	    continue;
 	}
@@ -149,35 +150,35 @@
 		r =3D opt->realm_string;
 	    else
 		r =3D krb5_principal_get_realm(context, princ_ent);
-	    kadm_handle =3D open_kadmin_connection(opt->principal_string,=20
-						 r,=20
-						 opt->admin_server_string,=20
+	    kadm_handle =3D open_kadmin_connection(opt->principal_string,
+						 r,
+						 opt->admin_server_string,
 						 opt->server_port_integer);
 	    if(kadm_handle =3D=3D NULL)
 		break;
 	}
-=09
+
 	ret =3D kadm5_create_principal(kadm_handle, &princ, mask, "x");
 	if(ret =3D=3D 0)
 	    created =3D 1;
 	else if(ret !=3D KADM5_DUP) {
-	    krb5_warn(context, ret, "kadm5_create_principal(%s)", argv[i]);
+	    krb5_warn(context, ret, "kadm5_create_principal(%s)", argv[a]);
 	    krb5_free_principal(context, princ_ent);
 	    failed++;
 	    continue;
 	}
 	ret =3D kadm5_randkey_principal(kadm_handle, princ_ent, &keys, &n_keys);
 	if (ret) {
-	    krb5_warn(context, ret, "kadm5_randkey_principal(%s)", argv[i]);
+	    krb5_warn(context, ret, "kadm5_randkey_principal(%s)", argv[a]);
 	    krb5_free_principal(context, princ_ent);
 	    failed++;
 	    continue;
 	}
-=09
-	ret =3D kadm5_get_principal(kadm_handle, princ_ent, &princ,=20
+
+	ret =3D kadm5_get_principal(kadm_handle, princ_ent, &princ,
 			      KADM5_PRINCIPAL | KADM5_KVNO | KADM5_ATTRIBUTES);
 	if (ret) {
-	    krb5_warn(context, ret, "kadm5_get_principal(%s)", argv[i]);
+	    krb5_warn(context, ret, "kadm5_get_principal(%s)", argv[a]);
 	    for (j =3D 0; j < n_keys; j++)
 		krb5_free_keyblock_contents(context, &keys[j]);
 	    krb5_free_principal(context, princ_ent);
@@ -185,7 +186,7 @@
 	    continue;
 	}
 	if(!created && (princ.attributes & KRB5_KDB_DISALLOW_ALL_TIX))
-	    krb5_warnx(context, "%s: disallow-all-tix flag set - clearing", argv[=
i]);
+	    krb5_warnx(context, "%s: disallow-all-tix flag set - clearing", argv[=
a]);
 	princ.attributes &=3D (~KRB5_KDB_DISALLOW_ALL_TIX);
 	mask =3D KADM5_ATTRIBUTES;
 	if(created) {
@@ -194,7 +195,7 @@
 	}
 	ret =3D kadm5_modify_principal(kadm_handle, &princ, mask);
 	if (ret) {
-	    krb5_warn(context, ret, "kadm5_modify_principal(%s)", argv[i]);
+	    krb5_warn(context, ret, "kadm5_modify_principal(%s)", argv[a]);
 	    for (j =3D 0; j < n_keys; j++)
 		krb5_free_keyblock_contents(context, &keys[j]);
 	    krb5_free_principal(context, princ_ent);
@@ -205,7 +206,7 @@
 	    int do_add =3D TRUE;
=20
 	    if (netypes) {
-		int k;
+		size_t k;
=20
 		do_add =3D FALSE;
 		for (k =3D 0; k < netypes; ++k)
@@ -225,7 +226,7 @@
 	    }
 	    krb5_free_keyblock_contents(context, &keys[j]);
 	}
-=09
+
 	kadm5_free_principal_ent(kadm_handle, &princ);
 	krb5_free_principal(context, princ_ent);
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/ktutil-comma=
nds.in
--- a/head/crypto/heimdal/admin/ktutil-commands.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/admin/ktutil-commands.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).=20
  * All rights reserved.=20
  *
@@ -30,7 +30,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
  * SUCH DAMAGE.=20
  */
-/* $Id: ktutil-commands.in 14793 2005-04-14 16:45:14Z lha $ */
+/* $Id$ */
=20
 command =3D {
 	name =3D "add"
@@ -227,36 +227,17 @@
 	min_args =3D "2"
 	max_args =3D "2"
 	help =3D "Renames an entry in the keytab."
+	option =3D {
+		long =3D "delete"
+		type =3D "-flag"
+		help =3D "don't delete orignal entry"
+	}
 }
 command =3D {
-	name =3D "srvconvert"
-	name =3D "srv2keytab"
-	option =3D {
-		long =3D "srvtab"
-		short =3D "s"
-		type =3D "string"
-		argument =3D "file"
-		help =3D "name of Kerberos 4 srvtab"
-		default =3D "/etc/srvtab"
-	}
+	name =3D "destroy"
+	function =3D "kt_destroy"
 	max_args =3D "0"
-	function =3D "srvconv"
-	help =3D "Convert a Kerberos 4 srvtab to a keytab."
-}
-command =3D {
-	name =3D "srvcreate"
-	name =3D "key2srvtab"
-	option =3D {
-		long =3D "srvtab"
-		short =3D "s"
-		type =3D "string"
-		argument =3D "file"
-		help =3D "name of Kerberos 4 srvtab"
-		default =3D "/etc/srvtab"
-	}
-	max_args =3D "0"
-	function =3D "srvcreate"
-	help =3D "Convert a keytab to a Kerberos 4 srvtab."
+	help =3D "Destroy (remove) the keytab."
 }
 command =3D {
 	name =3D "help"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/ktutil.8
--- a/head/crypto/heimdal/admin/ktutil.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/ktutil.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: ktutil.8 14792 2005-04-14 16:43:57Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd April 14, 2005
 .Dt KTUTIL 8
@@ -40,12 +40,12 @@
 .Sh SYNOPSIS
 .Nm
 .Oo Fl k Ar keytab \*(Ba Xo
-.Fl -keytab=3D Ns Ar keytab
+.Fl Fl keytab=3D Ns Ar keytab
 .Xc
 .Oc
-.Op Fl v | Fl -verbose
-.Op Fl -version
-.Op Fl h | Fl -help
+.Op Fl v | Fl Fl verbose
+.Op Fl Fl version
+.Op Fl h | Fl Fl help
 .Ar command
 .Op Ar args
 .Sh DESCRIPTION
@@ -53,72 +53,43 @@
 is a program for managing keytabs.
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl v ,
-.Fl -verbose
-.Xc
+.It Fl v , Fl Fl verbose
 Verbose output.
 .El
 .Pp
 .Ar command
 can be one of the following:
 .Bl -tag -width srvconvert
-.It add Xo
-.Op Fl p Ar principal
-.Op Fl -principal=3D Ns Ar principal
-.Op Fl V Ar kvno
-.Op Fl -kvno=3D Ns Ar kvno
-.Op Fl e Ar enctype
-.Op Fl -enctype=3D Ns Ar enctype
-.Op Fl w Ar password
-.Op Fl -password=3D Ns Ar password
-.Op Fl r
-.Op Fl -random
-.Op Fl s
-.Op Fl -no-salt
-.Op Fl H
-.Op Fl -hex
-.Xc
+.It add Oo Fl p Ar principal Oc Oo Fl Fl principal=3D Ns Ar principal Oc \
+Oo Fl V Ar kvno Oc Oo Fl Fl kvno=3D Ns Ar kvno Oc Oo Fl e Ar enctype Oc \
+Oo Fl Fl enctype=3D Ns Ar enctype Oc Oo Fl w Ar password Oc \
+Oo Fl Fl password=3D Ns Ar password Oc Oo Fl r Oc Oo Fl Fl random Oc \
+Oo Fl s Oc Oo Fl Fl no-salt Oc Oo Fl H Oc Op Fl Fl hex
 Adds a key to the keytab. Options that are not specified will be
 prompted for. This requires that you know the password or the hex key of t=
he
 principal to add; if what you really want is to add a new principal to
 the keytab, you should consider the
 .Ar get
 command, which talks to the kadmin server.
-.It change Xo
-.Op Fl r Ar realm
-.Op Fl -realm=3D Ns Ar realm
-.Op Fl -a Ar host
-.Op Fl -admin-server=3D Ns Ar host
-.Op Fl -s Ar port
-.Op Fl -server-port=3D Ns Ar port
-.Xc
+.It change Oo Fl r Ar realm Oc Oo Fl Fl realm=3D Ns Ar realm Oc \
+Oo Fl Fl a Ar host Oc Oo Fl Fl admin-server=3D Ns Ar host Oc \
+Oo Fl Fl s Ar port Oc Op Fl Fl server-port=3D Ns Ar port
 Update one or several keys to new versions.  By default, use the admin
 server for the realm of a keytab entry.  Otherwise it will use the
 values specified by the options.
 .Pp
 If no principals are given, all the ones in the keytab are updated.
-.It copy Xo
-.Ar keytab-src
-.Ar keytab-dest
-.Xc
+.It copy Ar keytab-src Ar keytab-dest
 Copies all the entries from
 .Ar keytab-src
 to
 .Ar keytab-dest .
-.It get Xo
-.Op Fl p Ar admin principal
-.Op Fl -principal=3D Ns Ar admin principal
-.Op Fl e Ar enctype
-.Op Fl -enctypes=3D Ns Ar enctype
-.Op Fl r Ar realm
-.Op Fl -realm=3D Ns Ar realm
-.Op Fl a Ar admin server
-.Op Fl -admin-server=3D Ns Ar admin server
-.Op Fl s Ar server port
-.Op Fl -server-port=3D Ns Ar server port
-.Ar principal ...
-.Xc
+.It get Oo Fl p Ar admin principal Oc \
+Oo Fl Fl principal=3D Ns Ar admin principal Oc Oo Fl e Ar enctype Oc \
+Oo Fl Fl enctypes=3D Ns Ar enctype Oc Oo Fl r Ar realm Oc \
+Oo Fl Fl realm=3D Ns Ar realm Oc Oo Fl a Ar admin server Oc \
+Oo Fl Fl admin-server=3D Ns Ar admin server Oc Oo Fl s Ar server port Oc \
+Oo Fl Fl server-port=3D Ns Ar server port Oc Ar principal ...
 For each
 .Ar principal ,
 generate a new key for it (creating it if it doesn't already exist),
@@ -128,69 +99,26 @@
 .Ar realm
 is specified, the realm to operate on is taken from the first
 principal.
-.It list Xo
-.Op Fl -keys
-.Op Fl -timestamp
-.Xc
+.It list Oo Fl Fl keys Oc Op Fl Fl timestamp
 List the keys stored in the keytab.
-.It remove Xo
-.Op Fl p Ar principal
-.Op Fl -principal=3D Ns Ar principal
-.Op Fl V kvno
-.Op Fl -kvno=3D Ns Ar kvno
-.Op Fl e enctype
-.Op Fl -enctype=3D Ns Ar enctype
-.Xc
+.It remove Oo Fl p Ar principal Oc Oo Fl Fl principal=3D Ns Ar principal O=
c \
+Oo Fl V kvno Oc Oo Fl Fl kvno=3D Ns Ar kvno Oc Oo Fl e enctype Oc \
+Oo Fl Fl enctype=3D Ns Ar enctype Oc
 Removes the specified key or keys. Not specifying a
 .Ar kvno
 removes keys with any version number. Not specifying an
 .Ar enctype
 removes keys of any type.
-.It rename Xo
-.Ar from-principal
-.Ar to-principal
-.Xc
+.It rename Ar from-principal Ar to-principal
 Renames all entries in the keytab that match the
 .Ar from-principal
 to
 .Ar to-principal .
-.It purge Xo
-.Op Fl -age=3D Ns Ar age
-.Xc
+.It purge Op Fl Fl age=3D Ns Ar age
 Removes all old versions of a key for which there is a newer version
 that is at least
 .Ar age
 (default one week) old.
-.It srvconvert
-.It srv2keytab Xo
-.Op Fl s Ar srvtab
-.Op Fl -srvtab=3D Ns Ar srvtab
-.Xc
-Converts the version 4 srvtab in
-.Ar srvtab
-to a version 5 keytab and stores it in
-.Ar keytab .
-Identical to:
-.Bd -ragged -offset indent
-.Li ktutil copy
-.Li krb4: Ns Ar srvtab
-.Ar keytab
-.Ed
-.It srvcreate
-.It key2srvtab Xo
-.Op Fl s Ar srvtab
-.Op Fl -srvtab=3D Ns Ar srvtab
-.Xc
-Converts the version 5 keytab in
-.Ar keytab
-to a version 4 srvtab and stores it in
-.Ar srvtab .
-Identical to:
-.Bd -ragged -offset indent
-.Li ktutil copy
-.Ar keytab
-.Li krb4: Ns Ar srvtab
-.Ed
 .El
 .Sh SEE ALSO
 .Xr kadmin 8
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/ktutil.c
--- a/head/crypto/heimdal/admin/ktutil.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/ktutil.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,71 +1,71 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
 #include <err.h>
=20
-RCSID("$Id: ktutil.c 15585 2005-07-07 21:52:04Z lha $");
+RCSID("$Id$");
=20
 static int help_flag;
 static int version_flag;
 int verbose_flag;
-char *keytab_string;=20
+char *keytab_string;
 static char keytab_buf[256];
=20
 static struct getargs args[] =3D {
-    {=20
+    {
 	"version",
 	0,
 	arg_flag,
 	&version_flag,
 	NULL,
-	NULL=20
-    },
-    {=20
-	"help",	   =20
-	'h',  =20
-	arg_flag,=20
-	&help_flag,=20
-	NULL,=20
 	NULL
     },
-    {=20
-	"keytab",	   =20
-	'k',  =20
-	arg_string,=20
-	&keytab_string,=20
-	"keytab",=20
-	"keytab to operate on"=20
+    {
+	"help",
+	'h',
+	arg_flag,
+	&help_flag,
+	NULL,
+	NULL
+    },
+    {
+	"keytab",
+	'k',
+	arg_string,
+	&keytab_string,
+	"keytab",
+	"keytab to operate on"
     },
     {
 	"verbose",
@@ -101,7 +101,7 @@
     }
     if (verbose_flag)
 	fprintf (stderr, "Using keytab %s\n", keytab_string);
-=09
+
     return keytab;
 }
=20
@@ -118,8 +118,11 @@
 		     argv[0]);
 	} else {
 	    if(c->func) {
-		char *fake[] =3D { NULL, "--help", NULL };
+		char shelp[] =3D "--help";
+		char *fake[3];
 		fake[0] =3D argv[0];
+		fake[1] =3D shelp;
+		fake[2] =3D NULL;
 		(*c->func)(2, fake);
 		fprintf(stderr, "\n");
 	    }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/ktutil_locl.h
--- a/head/crypto/heimdal/admin/ktutil_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/ktutil_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,47 +1,45 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/*=20
- * $Id: ktutil_locl.h 14799 2005-04-15 05:02:39Z lha $
- * $FreeBSD$
+/*
+ * $Id$
  */
=20
 #ifndef __KTUTIL_LOCL_H__
 #define __KTUTIL_LOCL_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -67,7 +65,7 @@
 extern krb5_context context;
=20
 extern int verbose_flag;
-extern char *keytab_string;=20
+extern char *keytab_string;
=20
 krb5_keytab ktutil_open_keytab(void);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/list.c
--- a/head/crypto/heimdal/admin/list.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/list.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
 #include <rtbl.h>
=20
-RCSID("$Id: list.c 21745 2007-07-31 16:11:25Z lha $");
+RCSID("$Id$");
=20
 static int
 do_list(struct list_options *opt, const char *keytab_str)
@@ -51,7 +51,7 @@
 	char buf[1024];
 	keytab_str +=3D 4;
 	ret =3D 0;
-	while (strsep_copy((const char**)&keytab_str, ",",=20
+	while (strsep_copy((const char**)&keytab_str, ",",
 			   buf, sizeof(buf)) !=3D -1) {
 	    if(flag)
 		printf("\n");
@@ -76,7 +76,7 @@
     }
=20
     printf ("%s:\n\n", keytab_str);
-=09
+
     table =3D rtbl_create();
     rtbl_add_column_by_id(table, 0, "Vno", RTBL_ALIGN_RIGHT);
     rtbl_add_column_by_id(table, 1, "Type", 0);
@@ -85,15 +85,16 @@
 	rtbl_add_column_by_id(table, 3, "Date", 0);
     if(opt->keys_flag)
 	rtbl_add_column_by_id(table, 4, "Key", 0);
+    rtbl_add_column_by_id(table, 5, "Aliases", 0);
     rtbl_set_separator(table, "  ");
=20
-    while((ret =3D krb5_kt_next_entry(context, keytab, &entry, &cursor)) =
=3D=3D 0){
+    while(krb5_kt_next_entry(context, keytab, &entry, &cursor) =3D=3D 0){
 	char buf[1024], *s;
=20
 	snprintf(buf, sizeof(buf), "%d", entry.vno);
 	rtbl_add_column_entry_by_id(table, 0, buf);
=20
-	ret =3D krb5_enctype_to_string(context,=20
+	ret =3D krb5_enctype_to_string(context,
 				     entry.keyblock.keytype, &s);
 	if (ret !=3D 0) {
 	    snprintf(buf, sizeof(buf), "unknown (%d)", entry.keyblock.keytype);
@@ -107,12 +108,12 @@
 	rtbl_add_column_entry_by_id(table, 2, buf);
=20
 	if (opt->timestamp_flag) {
-	    krb5_format_time(context, entry.timestamp, buf,=20
+	    krb5_format_time(context, entry.timestamp, buf,
 			     sizeof(buf), FALSE);
 	    rtbl_add_column_entry_by_id(table, 3, buf);
 	}
 	if(opt->keys_flag) {
-	    int i;
+	    size_t i;
 	    s =3D malloc(2 * entry.keyblock.keyvalue.length + 1);
 	    if (s =3D=3D NULL) {
 		krb5_warnx(context, "malloc failed");
@@ -120,11 +121,24 @@
 		goto out;
 	    }
 	    for(i =3D 0; i < entry.keyblock.keyvalue.length; i++)
-		snprintf(s + 2 * i, 3, "%02x",=20
+		snprintf(s + 2 * i, 3, "%02x",
 			 ((unsigned char*)entry.keyblock.keyvalue.data)[i]);
 	    rtbl_add_column_entry_by_id(table, 4, s);
 	    free(s);
 	}
+	if (entry.aliases) {
+	    unsigned int i;
+	    struct rk_strpool *p =3D NULL;
+
+	    for (i =3D 0; i< entry.aliases->len; i++) {
+		krb5_unparse_name_fixed(context, entry.principal, buf, sizeof(buf));
+		rk_strpoolprintf(p, "%s%s", buf,
+				 i + 1 < entry.aliases->len ? ", " : "");
+
+	    }
+	    rtbl_add_column_entry_by_id(table, 5, rk_strpoolcollect(p));
+	}
+
 	krb5_kt_free_entry(context, &entry);
     }
     ret =3D krb5_kt_end_seq_get(context, keytab, &cursor);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/purge.c
--- a/head/crypto/heimdal/admin/purge.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/purge.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
=20
-RCSID("$Id: purge.c 14261 2004-09-23 14:46:43Z joda $");
+RCSID("$Id$");
=20
 /*
  * keep track of the highest version for every principal.
@@ -125,11 +125,11 @@
 	goto out;
     }
=20
-    while((ret =3D krb5_kt_next_entry(context, keytab, &entry, &cursor)) =
=3D=3D 0) {
+    while(krb5_kt_next_entry(context, keytab, &entry, &cursor) =3D=3D 0) {
 	add_entry (entry.principal, entry.vno, entry.timestamp, &head);
 	krb5_kt_free_entry(context, &entry);
     }
-    ret =3D krb5_kt_end_seq_get(context, keytab, &cursor);
+    krb5_kt_end_seq_get(context, keytab, &cursor);
=20
     judgement_day =3D time (NULL);
=20
@@ -139,7 +139,7 @@
 	goto out;
     }
=20
-    while((ret =3D krb5_kt_next_entry(context, keytab, &entry, &cursor)) =
=3D=3D 0) {
+    while(krb5_kt_next_entry(context, keytab, &entry, &cursor) =3D=3D 0) {
 	struct e *e =3D get_entry (entry.principal, head);
=20
 	if (e =3D=3D NULL) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/remove.c
--- a/head/crypto/heimdal/admin/remove.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/remove.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
=20
-RCSID("$Id: remove.c 17004 2006-04-07 13:06:37Z lha $");
+RCSID("$Id$");
=20
 int
 kt_remove(struct remove_options *opt, int argc, char **argv)
@@ -66,7 +66,7 @@
 	}
     }
     if (!principal && !enctype && !opt->kvno_integer) {
-	krb5_warnx(context,=20
+	krb5_warnx(context,
 		   "You must give at least one of "
 		   "principal, enctype or kvno.");
 	ret =3D EINVAL;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/admin/rename.c
--- a/head/crypto/heimdal/admin/rename.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/admin/rename.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 2001-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ktutil_locl.h"
=20
-RCSID("$Id: rename.c 14260 2004-09-23 14:45:29Z joda $");
+RCSID("$Id$");
=20
 int
-kt_rename(void *opt, int argc, char **argv)
+kt_rename(struct rename_options *opt, int argc, char **argv)
 {
     krb5_error_code ret =3D 0;
     krb5_keytab_entry entry;
@@ -89,13 +89,15 @@
 		krb5_warn(context, ret, "adding entry");
 		break;
 	    }
-	    entry.principal =3D from_princ;
-	    ret =3D krb5_kt_remove_entry(context, keytab, &entry);
-	    if(ret) {
-		entry.principal =3D NULL;
-		krb5_kt_free_entry(context, &entry);
-		krb5_warn(context, ret, "removing entry");
-		break;
+	    if (opt->delete_flag) {
+		entry.principal =3D from_princ;
+		ret =3D krb5_kt_remove_entry(context, keytab, &entry);
+		if(ret) {
+		    entry.principal =3D NULL;
+		    krb5_kt_free_entry(context, &entry);
+		    krb5_warn(context, ret, "removing entry");
+		    break;
+		}
 	    }
 	    entry.principal =3D NULL;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/Makefile.am
--- a/head/crypto/heimdal/appl/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 17775 2006-06-30 20:26:15Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -25,3 +25,5 @@
 	  kx					\
 	  kf					\
 	  $(dir_dce)
+
+EXTRA_DIST =3D NTMakefile
\ No newline at end of file
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/Makefile.in
--- a/head/crypto/heimdal/appl/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 17775 2006-06-30 20:26:15Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D appl
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 RECURSIVE_TARGETS =3D all-recursive check-recursive dvi-recursive \
@@ -101,58 +105,95 @@
 	ps-recursive uninstall-recursive
 RECURSIVE_CLEAN_TARGETS =3D mostlyclean-recursive clean-recursive	\
   distclean-recursive maintainer-clean-recursive
+AM_RECURSIVE_TARGETS =3D $(RECURSIVE_TARGETS:-recursive=3D) \
+	$(RECURSIVE_CLEAN_TARGETS:-recursive=3D) tags TAGS ctags CTAGS \
+	distdir
 ETAGS =3D etags
 CTAGS =3D ctags
 DIST_SUBDIRS =3D afsutil ftp login otp gssmask popper push rsh rcp su \
 	xnlock telnet test kx kf dceutils
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+am__relativize =3D \
+  dir0=3D`pwd`; \
+  sed_first=3D's,^\([^/]*\)/.*$$,\1,'; \
+  sed_rest=3D's,^[^/]*/*,,'; \
+  sed_last=3D's,^.*/\([^/]*\)$$,\1,'; \
+  sed_butlast=3D's,/*[^/]*$$,,'; \
+  while test -n "$$dir1"; do \
+    first=3D`echo "$$dir1" | sed -e "$$sed_first"`; \
+    if test "$$first" !=3D "."; then \
+      if test "$$first" =3D ".."; then \
+        dir2=3D`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
+        dir0=3D`echo "$$dir0" | sed -e "$$sed_butlast"`; \
+      else \
+        first2=3D`echo "$$dir2" | sed -e "$$sed_first"`; \
+        if test "$$first2" =3D "$$first"; then \
+          dir2=3D`echo "$$dir2" | sed -e "$$sed_rest"`; \
+        else \
+          dir2=3D"../$$dir2"; \
+        fi; \
+        dir0=3D"$$dir0"/"$$first"; \
+      fi; \
+    fi; \
+    dir1=3D`echo "$$dir1" | sed -e "$$sed_rest"`; \
+  done; \
+  reldir=3D"$$dir2"
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -176,10 +217,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -196,6 +238,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -211,31 +255,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -250,10 +308,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -294,29 +354,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 @OTP_TRUE at dir_otp =3D otp
 @DCE_TRUE at dir_dce =3D dceutils
@@ -338,22 +403,23 @@
 	  kf					\
 	  $(dir_dce)
=20
+EXTRA_DIST =3D NTMakefile
 all: all-recursive
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/Make=
file'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -371,6 +437,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -385,7 +452,7 @@
 #     (which will cause the Makefiles to be regenerated when you run `make=
');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -402,7 +469,7 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done; \
 	if test "$$dot_seen" =3D "no"; then \
@@ -410,7 +477,7 @@
 	fi; test -z "$$fail"
=20
 $(RECURSIVE_CLEAN_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -436,16 +503,16 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done && test -z "$$fail"
 tags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags);=
 \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 tags); \
 	done
 ctags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags)=
; \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 ctags); \
 	done
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
@@ -453,14 +520,14 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
 	  include_option=3D--etags-include; \
@@ -472,39 +539,43 @@
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test ! -f $$subdir/TAGS || \
-	      tags=3D"$$tags $$include_option=3D$$here/$$subdir/TAGS"; \
+	      set "$$@" "$$include_option=3D$$here/$$subdir/TAGS"; \
 	  fi; \
 	done; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -525,29 +596,44 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
-	list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test -d "$(distdir)/$$subdir" \
 	    || $(MKDIR_P) "$(distdir)/$$subdir" \
 	    || exit 1; \
-	    distdir=3D`$(am__cd) $(distdir) && pwd`; \
-	    top_distdir=3D`$(am__cd) $(top_distdir) && pwd`; \
-	    (cd $$subdir && \
+	  fi; \
+	done
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" =3D .; then :; else \
+	    dir1=3D$$subdir; dir2=3D"$(distdir)/$$subdir"; \
+	    $(am__relativize); \
+	    new_distdir=3D$$reldir; \
+	    dir1=3D$$subdir; dir2=3D"$(top_distdir)"; \
+	    $(am__relativize); \
+	    new_top_distdir=3D$$reldir; \
+	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir=3D"$$new_t=
op_distdir" distdir=3D"$$new_distdir" \\"; \
+	    echo "     am__remove_distdir=3D: am__skip_length_check=3D: am__skip_=
mode_fix=3D: distdir)"; \
+	    ($(am__cd) $$subdir && \
 	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir=3D"$$top_distdir" \
-	        distdir=3D"$$distdir/$$subdir" \
+	        top_distdir=3D"$$new_top_distdir" \
+	        distdir=3D"$$new_distdir" \
 		am__remove_distdir=3D: \
 		am__skip_length_check=3D: \
+		am__skip_mode_fix=3D: \
 	        distdir) \
 	      || exit 1; \
 	  fi; \
@@ -581,6 +667,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -599,6 +686,8 @@
=20
 html: html-recursive
=20
+html-am:
+
 info: info-recursive
=20
 info-am:
@@ -606,23 +695,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-recursive
=20
-install-dvi: install-dvi-recursive
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-recursive
=20
+install-html-am:
+
 install-info: install-info-recursive
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-recursive
=20
+install-pdf-am:
+
 install-ps: install-ps-recursive
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-recursive
@@ -644,9 +741,9 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \
-	install-data-am install-exec-am install-strip uninstall-am
+.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) check-am \
+	ctags-recursive install-am install-data-am install-exec-am \
+	install-strip tags-recursive uninstall-am
=20
 .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
 	all all-am all-local check check-am check-local clean \
@@ -732,6 +829,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -817,7 +917,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -830,6 +930,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/afsutil/Chang=
eLog
--- a/head/crypto/heimdal/appl/afsutil/ChangeLog	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/afsutil/ChangeLog	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-2007-04-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* pagsh.1,afslog.1: - options must be lexicographically ordered;
 	  again, options without arguments must be placed before options
@@ -8,11 +8,11 @@
 =09
 	From Igor Sobrado.
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add man_MANS to EXTRA_DIST
 =09
-2006-01-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afslog.1: Document options to allow select principal or
 	credential cache when doing afslog.
@@ -20,7 +20,7 @@
 	* afslog.c: Add options to allow select principal or credential
 	cache when doing afslog.
 =09
-2005-02-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: man_MANS +=3D pagsh.1
=20
@@ -30,12 +30,12 @@
=20
 	* pagsh.1: manpage for pagsh
=20
-2004-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afslog.c: use negative string help string for arg_negative_flag
 	Pointed out by Harald Barth
 =09
-2004-07-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* pagsh.c: use setprogname, if we stripped off -c, try use the
 	fallback code
@@ -44,22 +44,22 @@
=20
 	* pagsh.c: mkstemp formats must end in exactly six X's
=20
-2003-07-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afslog.c (do_afslog): is cell is unset, set it "<default cell>"
 	for error printing
=20
 	* pagsh.c: unconditionally set KRBTKFILE
 =09
-2003-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afslog.c (log_func): drop the error number
 =09
-2003-04-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afslog.c: set kafs log function if verbose is turned on
 =09
-2003-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am (LDADD): use LIB_kafs
 =09
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/afsutil/Makef=
ile.am
--- a/head/crypto/heimdal/appl/afsutil/Makefile.am	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/afsutil/Makefile.am	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -19,4 +19,4 @@
 	$(LIB_hcrypto) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/afsutil/Makef=
ile.in
--- a/head/crypto/heimdal/appl/afsutil/Makefile.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/afsutil/Makefile.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/afsutil
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,14 +89,14 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS)
 am_afslog_OBJECTS =3D afslog.$(OBJEXT)
 afslog_OBJECTS =3D $(am_afslog_OBJECTS)
@@ -110,9 +115,9 @@
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -124,6 +129,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(afslog_SOURCES) $(pagsh_SOURCES)
 DIST_SOURCES =3D $(afslog_SOURCES) $(pagsh_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -133,49 +159,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -199,10 +234,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -219,6 +255,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -234,31 +272,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -273,10 +325,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -317,30 +371,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_krb4)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 afslog_SOURCES =3D afslog.c
 pagsh_SOURCES =3D pagsh.c
@@ -352,23 +410,23 @@
 	$(LIB_hcrypto) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/afsu=
til/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/afsutil/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/afsutil/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/afsutil/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -386,34 +444,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 afslog$(EXEEXT): $(afslog_OBJECTS) $(afslog_DEPENDENCIES)=20
 	@rm -f afslog$(EXEEXT)
 	$(LINK) $(afslog_OBJECTS) $(afslog_LDADD) $(LIBS)
@@ -427,115 +501,140 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/afslog.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pagsh.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -551,13 +650,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -592,6 +695,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -601,6 +705,7 @@
 clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -611,6 +716,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -618,26 +725,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -657,11 +773,10 @@
 uninstall-am: uninstall-binPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libtool ctags \
@@ -748,6 +863,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -833,7 +951,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -846,6 +964,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/afsutil/afslo=
g.1
--- a/head/crypto/heimdal/appl/afsutil/afslog.1	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/afsutil/afslog.1	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,66 +1,65 @@
-.\" Copyright (c) 2002 - 2007 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2002 - 2007 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: afslog.1 20310 2007-04-11 11:22:23Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd November 26, 2002
 .Dt AFSLOG 1
 .Os HEIMDAL
 .Sh NAME
 .Nm afslog
-.Nd
-obtain AFS tokens
+.Nd obtain AFS tokens
 .Sh SYNOPSIS
 .Nm
-.Op Fl h | Fl -help
-.Op Fl -no-v4
-.Op Fl -no-v5
-.Op Fl u | Fl -unlog
-.Op Fl v | Fl -verbose
-.Op Fl -version
+.Op Fl h | Fl Fl help
+.Op Fl Fl no-v4
+.Op Fl Fl no-v5
+.Op Fl u | Fl Fl unlog
+.Op Fl v | Fl Fl verbose
+.Op Fl Fl version
 .Oo Fl c Ar cell \*(Ba Xo
-.Fl -cell=3D Ns Ar cell
+.Fl Fl cell=3D Ns Ar cell
 .Xc
 .Oc
 .Oo Fl k Ar realm \*(Ba Xo
-.Fl -realm=3D Ns Ar realm
+.Fl Fl realm=3D Ns Ar realm
 .Xc
 .Oc
 .Oo Fl P Ar principal \*(Ba Xo
-.Fl -principal=3D Ns Ar principal
+.Fl Fl principal=3D Ns Ar principal
 .Xc
 .Oc
 .Bk -words
 .Oo Fl p Ar path \*(Ba Xo
-.Fl -file=3D Ns Ar path
+.Fl Fl file=3D Ns Ar path
 .Xc
 .Oc
 .Ek
@@ -71,57 +70,57 @@
 can either be specified as an explicit list, as file paths to get
 tokens for, or be left unspecified, in which case
 .Nm
-will use whatever magic=20
+will use whatever magic
 .Xr krb_afslog 3
 decides upon.
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Fl -no-v4
+.It Fl Fl no-v4
 This makes
 .Nm
 not try using Kerberos 4.
-.It Fl -no-v5
+.It Fl Fl no-v5
 This makes
 .Nm
 not try using Kerberos 5.
 .It Xo
 .Fl P Ar principal ,
-.Fl -principal Ar principal
+.Fl Fl principal Ar principal
 .Xc
 select what Kerberos 5 principal to use.
-.It Fl -cache Ar cache
+.It Fl Fl cache Ar cache
 select what Kerberos 5 credential cache to use.
-.Fl -principal
+.Fl Fl principal
 overrides this option.
 .It Xo
 .Fl u ,
-.Fl -unlog
+.Fl Fl unlog
 .Xc
 Destroy tokens instead of obtaining new. If this is specified, all
 other options are ignored (except for
-.Fl -help
+.Fl Fl help
 and
-.Fl -version ) .
+.Fl Fl version ) .
 .It Xo
 .Fl v ,
-.Fl -verbose
+.Fl Fl verbose
 .Xc
 Adds more verbosity for what is actually going on.
 .It Xo
 .Fl c Ar cell,
-.Fl -cell=3D Ns Ar cell
+.Fl Fl cell=3D Ns Ar cell
 .Xc
 This specified one or more cell names to get tokens for.
 .It Xo
 .Fl k Ar realm ,
-.Fl -realm=3D Ns Ar realm
+.Fl Fl realm=3D Ns Ar realm
 .Xc
 This is the Kerberos realm the AFS servers live in, this should
 normally not be specified.
 .It Xo
 .Fl p Ar path ,
-.Fl -file=3D Ns Ar path
+.Fl Fl file=3D Ns Ar path
 .Xc
 This specified one or more file paths for which tokens should be
 obtained.
@@ -132,22 +131,22 @@
 and
 .Fl p ,
 you may also pass a list of cells and file paths after any other
-options. These arguments are considered files if they are either=20
+options. These arguments are considered files if they are either
 the strings
 .Do . Dc
 or
-.Dq ..=20
+.Dq ..
 or they contain a slash, or if there exists a file by that name.
 .Sh EXAMPLES
-Assuming that there is no file called=20
+Assuming that there is no file called
 .Dq openafs.org
-in the current directory, and that=20
+in the current directory, and that
 .Pa /afs/openafs.org
 points to that cell, the follwing should be identical:
 .Bd -literal -offset indent
 $ afslog -c openafs.org
 $ afslog openafs.org
 $ afslog /afs/openafs.org/some/file
-.Ed=20
+.Ed
 .Sh SEE ALSO
 .Xr krb_afslog 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/afsutil/afslo=
g.c
--- a/head/crypto/heimdal/appl/afsutil/afslog.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/afsutil/afslog.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,47 +1,44 @@
 /*
- * Copyright (c) 1997-2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: afslog.c 16438 2006-01-03 09:27:54Z lha $");
+RCSID("$Id$");
 #endif
 #include <ctype.h>
 #ifdef KRB5
 #include <krb5.h>
 #endif
-#ifdef KRB4
-#include <krb.h>
-#endif
 #include <kafs.h>
 #include <roken.h>
 #include <getarg.h>
@@ -54,9 +51,6 @@
 static getarg_strings files;
 static int unlog_flag;
 static int verbose;
-#ifdef KRB4
-static int use_krb4 =3D 1;
-#endif
 #ifdef KRB5
 static char *client_string;
 static char *cache_string;
@@ -68,9 +62,6 @@
     { "file",	'p', arg_strings, &files, "files to get tokens for", "path" =
},
     { "realm",	'k', arg_string, &realm, "realm for afs cell", "realm" },
     { "unlog",	'u', arg_flag, &unlog_flag, "remove tokens" },
-#ifdef KRB4
-    { "v4",	 0, arg_negative_flag, &use_krb4, "don't use Kerberos 4" },
-#endif
 #ifdef KRB5
     { "principal",'P',arg_string,&client_string,"principal to use","princi=
pal"},
     { "cache",   0,  arg_string, &cache_string, "ccache to use", "cache"},
@@ -189,9 +180,9 @@
 static int
 do_afslog(const char *cell)
 {
-    int k5ret, k4ret;
+    int k5ret;
=20
-    k5ret =3D k4ret =3D 0;
+    k5ret =3D 0;
=20
 #ifdef KRB5
     if(context !=3D NULL && id !=3D NULL && use_krb5) {
@@ -200,24 +191,13 @@
 	    return 0;
     }
 #endif
-#if KRB4
-    if (use_krb4) {
-	k4ret =3D krb_afslog(cell, realm);
-	if(k4ret =3D=3D 0)
-	    return 0;
-    }
-#endif
     if (cell =3D=3D NULL)
 	cell =3D "<default cell>";
 #ifdef KRB5
     if (k5ret)
-	warnx("krb5_afslog(%s): %s", cell, krb5_get_err_text(context, k5ret));
+	krb5_warn(context, k5ret, "krb5_afslog(%s)", cell);
 #endif
-#ifdef KRB4
-    if (k4ret)
-	warnx("krb_afslog(%s): %s", cell, krb_get_err_text(k4ret));
-#endif
-    if (k5ret || k4ret)
+    if (k5ret)
 	return 1;
     return 0;
 }
@@ -237,7 +217,7 @@
     int ret =3D 0;
     int failed =3D 0;
     struct cell_list *p;
-   =20
+
     setprogname(argv[0]);
=20
     if(getarg(args, num_args, argc, argv, &optind))
@@ -266,7 +246,7 @@
=20
 	    ret =3D krb5_parse_name(context, client_string, &client);
 	    if (ret =3D=3D 0)
-		ret =3D krb5_cc_cache_match(context, client, NULL, &id);
+		ret =3D krb5_cc_cache_match(context, client, &id);
 	    if (ret)
 		id =3D NULL;
 	}
@@ -306,7 +286,7 @@
 	    afslog_file(argv[i]);
 	else
 	    afslog_cell(argv[i], 1);
-    }   =20
+    }
     if(num =3D=3D 0) {
 	if(do_afslog(NULL))
 	    failed++;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/afsutil/pagsh=
.1
--- a/head/crypto/heimdal/appl/afsutil/pagsh.1	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/afsutil/pagsh.1	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,79 +1,80 @@
-.\" Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: pagsh.1 20311 2007-04-11 11:27:51Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd February 12, 2005
 .Dt PAGSH 1
 .Os Heimdal
 .Sh NAME
 .Nm pagsh
-.Nd
-creates a new credential cache sandbox
+.Nd creates a new credential cache sandbox
 .Sh SYNOPSIS
 .Nm
-.Op Fl c
-.Op Fl h | Fl -help
-.Op Fl -version
-.Op Fl -cache-type=3D Ns Ar string
+.Op Fl c Ar command-string
+.Op Fl h | Fl Fl help
+.Op Fl Fl version
+.Op Fl Fl cache-type=3D Ns Ar string
 .Ar command [args...]
 .Sh DESCRIPTION
 Supported options:
 .Bl -tag -width Ds
 .It Xo
-.Fl c
+.Fl c Ar command-string
+Executes command(s) contained in
+.Ar command-string .
 .Xc
 .It Xo
-.Fl -cache-type=3D Ns Ar string
+.Fl Fl cache-type=3D Ns Ar string
 .Xc
 .It Xo
 .Fl h ,
-.Fl -help
+.Fl Fl help
 .Xc
 .It Xo
-.Fl -version
+.Fl Fl version
 .Xc
 .El
 .Pp
 .Nm
 creates a new credential cache sandbox for the user to live in.
 If AFS is installed on the computer, the user is put in a newly
-created PAG.
+created Process Authentication Group (PAG).
 .Pp
 For Kerberos 5, the credential cache type that is used is the same as
 the credential cache type that was used at the time of
 .Nm
 invocation.
 The credential cache type can be controlled by the option
-.Fl -cache-type .
+.Fl Fl cache-type .
 .Sh EXAMPLES
 Create a new sandbox where new credentials can be used, while the old
 credentials can be used by other processes.
@@ -89,4 +90,5 @@
 klist: No ticket file: /tmp/krb5cc_03014a
 .Ed
 .Sh SEE ALSO
-.Xr afslog 1
+.Xr afslog 1 ,
+.Xr kinit 1
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/afsutil/pagsh=
.c
--- a/head/crypto/heimdal/appl/afsutil/pagsh.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/afsutil/pagsh.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -35,7 +35,7 @@
 #include <config.h>
 #endif
=20
-RCSID("$Id: pagsh.c 14574 2005-02-12 14:23:28Z lha $");
+RCSID("$Id$");
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -55,9 +55,6 @@
 #ifdef KRB5
 #include <krb5.h>
 #endif
-#ifdef KRB4
-#include <krb.h>
-#endif
 #include <kafs.h>
=20
 #include <err.h>
@@ -106,7 +103,7 @@
=20
     char *path;
     char **args;
-    int i;
+    unsigned int i;
     int optind =3D 0;
=20
     setprogname(argv[0]);
@@ -124,7 +121,6 @@
=20
 #ifdef KRB5
     {
-	const krb5_cc_ops *type;
 	krb5_error_code ret;
 	krb5_context context;
 	krb5_ccache id;
@@ -134,29 +130,7 @@
 	if (ret) /* XXX should this really call exit ? */
 	    errx(1, "no kerberos 5 support");
=20
-	if (typename_arg =3D=3D NULL) {
-	    char *s;
-
-	    name =3D krb5_cc_default_name(context);
-	    if (name =3D=3D NULL)
-		krb5_errx(context, 1, "Failed getting default "
-			  "credential cache type");
-	   =20
-	    typename_arg =3D strdup(name);
-	    if (typename_arg =3D=3D NULL)
-		errx(1, "strdup");
-	   =20
-	    s =3D strchr(typename_arg, ':');
-	    if (s)
-		*s =3D '\0';
-	}
-
-	type =3D krb5_cc_get_prefix_ops(context, typename_arg);
-	if (type =3D=3D NULL)
-	    krb5_err(context, 1, ret, "Failed getting ops for %s "
-		     "credential cache", typename_arg);
-    =20
-	ret =3D krb5_cc_gen_new(context, type, &id);
+	ret =3D krb5_cc_new_unique(context, typename_arg, NULL, &id);
 	if (ret)
 	    krb5_err(context, 1, ret, "Failed generating credential cache");
=20
@@ -164,7 +138,7 @@
 	if (name =3D=3D NULL)
 	    krb5_errx(context, 1, "Generated credential cache have no name");
=20
-	snprintf(tf, sizeof(tf), "%s:%s", typename_arg, name);
+	snprintf(tf, sizeof(tf), "%s:%s", krb5_cc_get_type(context, id), name);
=20
 	ret =3D krb5_cc_close(context, id);
 	if (ret)
@@ -190,11 +164,13 @@
     if (args =3D=3D NULL)
 	errx (1, "Out of memory allocating %lu bytes",
 	      (unsigned long)((argc + 10)*sizeof(char *)));
- =20
+
     if(*argv =3D=3D NULL) {
 	path =3D getenv("SHELL");
 	if(path =3D=3D NULL){
 	    struct passwd *pw =3D k_getpwuid(geteuid());
+	    if (pw =3D=3D NULL)
+		errx(1, "no such user: %d", (int)geteuid());
 	    path =3D strdup(pw->pw_shell);
 	}
     } else {
@@ -202,7 +178,7 @@
     }
     if (path =3D=3D NULL)
 	errx (1, "Out of memory copying path");
- =20
+
     p=3Dstrrchr(path, '/');
     if(p)
 	args[i] =3D strdup(p+1);
@@ -211,7 +187,7 @@
=20
     if (args[i++] =3D=3D NULL)
 	errx (1, "Out of memory copying arguments");
- =20
+
     while(*argv)
 	args[i++] =3D *argv++;
=20
@@ -224,7 +200,7 @@
     execvp(path, args);
     if (errno =3D=3D ENOENT || c_flag) {
 	char **sh_args =3D malloc ((i + 2) * sizeof(char *));
-	int j;
+	unsigned int j;
=20
 	if (sh_args =3D=3D NULL)
 	    errx (1, "Out of memory copying sh arguments");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ChangeLog
--- a/head/crypto/heimdal/appl/ftp/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/ftp/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,24 @@
-2007-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* ftp/ftp.c: use the correct length to munmap and use msync.
+
+2008-05-28  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* ftp/ftp.c: Rewrite sliding window code so it doesn't have a
+	integer overrun.
+
+	* ftp/ftp.c: Try sliding mmap window over memory file (10MB
+	window), works better with larger files (ie doesn't fail).
+=09
+2008-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* ftpd/logwtmp.c: Use asl for logging ftpd wtmp messages.
+
+2007-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/gssapi.c: Fix pointer vs strict alias rules.
=20
-2007-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/security.c: if no mech have no session, its ok, just don't
 	call it.
@@ -11,20 +27,20 @@
=20
 	* move ksetpag after initgroups to make it work on Linux when its
 	without syscall hooks to change sys_setgroups preserve the
-	pag. From Alexsander Bostr=F6m.
+	pag. From Alexsander Bostr=C3=B6m.
 =09
-2007-06-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/Makefile.am: don't clean yacc/lex files in CLEANFILES,
 	maintainers clean will do that for us.
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/Makefile.am: Add man_MANS to EXTRA_DIST
=20
 	* ftp/Makefile.am: Add man_MANS to EXTRA_DIST
 =09
-2006-08-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.c: Add comment by seteuid call isn't not needed.
=20
@@ -32,16 +48,16 @@
 	advisory.  Thanks to Tom Yu at MIT, and Michael Calmer and Marcus
 	Meissner at SUSE.  Either of CVE-2006-3083 or CVE-2006-3084.
 =09
-2006-06-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/gss_userok.c (gss_userok): create a local krb5_context and
 	use that instead of the libgssapi context (that might not exist).
 =09
-2006-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Rename u_intXX_t to uintXX_t
=20
-2006-03-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/ftp.1: Add undocument flags and spelling, from Ted Percival
 	<Ted.Percival at quest.com>
@@ -51,7 +67,7 @@
 	* ftpd/ftpd.8: fix grammar in --no-insecure-oob option (partly
 	from Thomas Klausner)
 =09
-2006-01-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/ftp.c: Indent.
 =09
@@ -59,20 +75,20 @@
=20
 	* ftpd/ftpd.c (pass): remove unused variable in the !OTP case
 =09
-2005-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ftpd/ls.c: Check return value from asprintf instead of string !=3D
-	NULL since it undefined behavior on Linux. From Bj=F6rn Sandell
+	NULL since it undefined behavior on Linux. From Bj=C3=B6rn Sandell
=20
 	* ftpd/gss_userok.c: Check return value from asprintf instead of
-	string !=3D NULL since it undefined behavior on Linux. From Bj=F6rn
+	string !=3D NULL since it undefined behavior on Linux. From Bj=C3=B6rn
 	Sandell
=20
 	* ftpd/ftpd.c: Check return value from asprintf instead of string
-	!=3D NULL since it undefined behavior on Linux. From Bj=F6rn Sandell
+	!=3D NULL since it undefined behavior on Linux. From Bj=C3=B6rn Sandell
=20
 	* ftp/gssapi.c: Check return value from asprintf instead of string
-	!=3D NULL since it undefined behavior on Linux. From Bj=F6rn Sandell
+	!=3D NULL since it undefined behavior on Linux. From Bj=C3=B6rn Sandell
 =09
 2005-10-12  Johan Danielsson  <joda at pdc.kth.se>
=20
@@ -95,7 +111,7 @@
 =09
 	* ftp/main.c: add -x (encrypt) option
 =09
-2005-07-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpcmd.y: Fix shadow warning.
=20
@@ -108,11 +124,11 @@
 =09
 	* ftp/cmds.c: fix shadow warnings
=20
-	* Add Kerberos 5 klist, old patch from Tomas Nystr=F6m (remove krb4
+	* Add Kerberos 5 klist, old patch from Tomas Nystr=C3=B6m (remove krb4
 	support). Support klist in client for kerberos 5 clase.
 	Clean up delegation of gss tokens and do afslog.
=20
-2005-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/gssapi.c (gss_adat): avoid leaking memory
 	(gss_auth): always try next kname if there is one, independant of
@@ -121,7 +137,7 @@
 	* ftp/gssapi.c: avoid const warning, use sin4 instead of sin to
 	avoid shadow warning, free target_name
=20
-2005-07-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/security.c: keep track of if CCC was passed
=20
@@ -130,12 +146,12 @@
 	* ftpd/ftpcmd.y: sprinkel check_secure, check if CCC was passed in
 	check_secure
=20
-2005-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.c (filename_check): change signednes of p to avoid
 	warning, move typecasts
=20
-2005-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.c: avoid 'unused variable' warnings
=20
@@ -143,45 +159,45 @@
=20
 	* ftpd/pathnames.h: #ifdef protect _PATH_ISSUE
=20
-2005-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/domacro.c: handle string trunctions
=20
-2005-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/security.c: use strlcat
 =09
 	* ftp/domacro.c: use strlcpy
 =09
-2005-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/security.c: cast size_t to unsigned long
=20
-2005-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.c (statcmd): cast argument to isdigit to unsigned char
=20
 	* ftp/cmds.c (mget): cast char to unsigned char to make sure its
 	not negative when passing it to tolower
=20
-2005-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/ftp.c: fix 3 'var' might be used uninitialized warnings
=20
-2005-04-04 Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-04 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/cmds.c: MacOS is also a unix that doesn't define
 	__unix__/unix While here, rewrite this part of the function to not
 	modify that string, but rather take a copy of it and them modify
 	is, all this just to pacify gcc
 =09
-2005-01-09 Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-09 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/domacro.c: cast argument to is* to unsigned char
=20
 	* ftp/ftp.c: cast argument to tolower to unsigned char
=20
-2004-08-20 Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-20 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/ftp.c: send ABOR protect with security layer if its there
=20
@@ -200,16 +216,16 @@
 	* ftp/main.c: reverse help strings for --no-gss-bindings and
 	--no-gss-delegate
=20
-2004-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpcmd.y: make cbuf 64k to handle lager tickets From:
 	MAAAAA MOOOR <huaraz at btinternet.com>
 =09
-2004-03-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.c (main): setpag if there is krb4 OR krb5 support
 =09
-2003-12-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/security.h: add ftp_do_gss_delegate
 =09
@@ -217,13 +233,13 @@
 =09
 	* ftp/gssapi.c (ftp_do_gss_delegate): delegate creds (default on)
 =09
-2003-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/ftp.c: s/des_read_pw_string/UI_UTIL_read_pw_string/
 =09
 	* ftp/cmds.c: s/des_read_pw_string/UI_UTIL_read_pw_string/
 =09
-2003-07-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/security.h: add ftp_do_gss_bindings
 =09
@@ -246,7 +262,7 @@
=20
 	* ftp/gssapi.c (gss_adat): fix name allocation bug
=20
-2003-05-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/gss_userok.c (gss_userok): release delegated cred handle
 =09
@@ -256,12 +272,12 @@
 	* ftpd/gss_userok.c (gss_userok): remove poking inside the
 	delegated handle
=20
-2003-05-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpcmd.y: support afslog <cell> and afslog when compiled
 	with krb5
=20
-2003-05-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/cmdtab.c: include afslog in both the krb4 and krb5 case
 =09
@@ -269,21 +285,21 @@
 =09
 	* ftp/Makefile.am: always include auth.c
 =09
-2003-05-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ftpd/Makefile.am: always include auth.c
=20
 	* ftpd/kauth.c: do afslog in the krb5 case too
 =09
-2003-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/ftp.1: replace > with \*[Gt]
 =09
-2003-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.c: make sure argument to is* functions are unsigned
 =09
-2003-04-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.8: s/kerberos/Kerberos/
 =09
@@ -291,7 +307,7 @@
=20
 	* ftpd/pathnames.h (_PATH_FTPUSERS): conditionalize
=20
-2003-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ftpd.c (krb5_verify): always do krb5_afslog, remove setpag
 	(its done in main)
@@ -305,17 +321,17 @@
=20
 	* ftpd/ftpd_locl.h: always include kafs
 =09
-2003-03-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/gssapi.c (gss_adat): now that gss_export_name exports a
 	principal, bandaid with gss_display_name, and check that oid is
 	GSS_KRB5_NT_PRINCIPAL_NAME, also free memory
 =09
-2003-02-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftp/gssapi.c (gss_auth): print out the name we authenticated too
 =09
-2003-02-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ftpd/ls.c: use readlink with bufsize - 1, From NetBSD
=20
@@ -329,7 +345,7 @@
=20
 2002-10-29  Johan Danielsson  <joda at pdc.kth.se>
=20
-	* ftp/main.c: reinstate -n flag (from Torbj=F6rn Granlund)
+	* ftp/main.c: reinstate -n flag (from Torbj=C3=B6rn Granlund)
=20
 2002-10-16  Johan Danielsson  <joda at pdc.kth.se>
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/Makefile.=
am
--- a/head/crypto/heimdal/appl/ftp/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/ftp/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,7 @@
-# $Id: Makefile.am 5652 1999-03-20 13:58:20Z joda $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
 SUBDIRS =3D common ftp ftpd
+
+EXTRA_DIST =3D NTMakefile
\ No newline at end of file
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/Makefile.=
in
--- a/head/crypto/heimdal/appl/ftp/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/ftp/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 5652 1999-03-20 13:58:20Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D appl/ftp
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 RECURSIVE_TARGETS =3D all-recursive check-recursive dvi-recursive \
@@ -101,57 +105,94 @@
 	ps-recursive uninstall-recursive
 RECURSIVE_CLEAN_TARGETS =3D mostlyclean-recursive clean-recursive	\
   distclean-recursive maintainer-clean-recursive
+AM_RECURSIVE_TARGETS =3D $(RECURSIVE_TARGETS:-recursive=3D) \
+	$(RECURSIVE_CLEAN_TARGETS:-recursive=3D) tags TAGS ctags CTAGS \
+	distdir
 ETAGS =3D etags
 CTAGS =3D ctags
 DIST_SUBDIRS =3D $(SUBDIRS)
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+am__relativize =3D \
+  dir0=3D`pwd`; \
+  sed_first=3D's,^\([^/]*\)/.*$$,\1,'; \
+  sed_rest=3D's,^[^/]*/*,,'; \
+  sed_last=3D's,^.*/\([^/]*\)$$,\1,'; \
+  sed_butlast=3D's,/*[^/]*$$,,'; \
+  while test -n "$$dir1"; do \
+    first=3D`echo "$$dir1" | sed -e "$$sed_first"`; \
+    if test "$$first" !=3D "."; then \
+      if test "$$first" =3D ".."; then \
+        dir2=3D`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
+        dir0=3D`echo "$$dir0" | sed -e "$$sed_butlast"`; \
+      else \
+        first2=3D`echo "$$dir2" | sed -e "$$sed_first"`; \
+        if test "$$first2" =3D "$$first"; then \
+          dir2=3D`echo "$$dir2" | sed -e "$$sed_rest"`; \
+        else \
+          dir2=3D"../$$dir2"; \
+        fi; \
+        dir0=3D"$$dir0"/"$$first"; \
+      fi; \
+    fi; \
+    dir1=3D`echo "$$dir1" | sed -e "$$sed_rest"`; \
+  done; \
+  reldir=3D"$$dir2"
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -175,10 +216,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -195,6 +237,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -210,31 +254,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -249,10 +307,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -293,47 +353,53 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 SUBDIRS =3D common ftp ftpd
+EXTRA_DIST =3D NTMakefile
 all: all-recursive
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/ftp/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/ftp/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -351,6 +417,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -365,7 +432,7 @@
 #     (which will cause the Makefiles to be regenerated when you run `make=
');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -382,7 +449,7 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done; \
 	if test "$$dot_seen" =3D "no"; then \
@@ -390,7 +457,7 @@
 	fi; test -z "$$fail"
=20
 $(RECURSIVE_CLEAN_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -416,16 +483,16 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done && test -z "$$fail"
 tags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags);=
 \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 tags); \
 	done
 ctags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags)=
; \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 ctags); \
 	done
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
@@ -433,14 +500,14 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
 	  include_option=3D--etags-include; \
@@ -452,39 +519,43 @@
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test ! -f $$subdir/TAGS || \
-	      tags=3D"$$tags $$include_option=3D$$here/$$subdir/TAGS"; \
+	      set "$$@" "$$include_option=3D$$here/$$subdir/TAGS"; \
 	  fi; \
 	done; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -505,29 +576,44 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
-	list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test -d "$(distdir)/$$subdir" \
 	    || $(MKDIR_P) "$(distdir)/$$subdir" \
 	    || exit 1; \
-	    distdir=3D`$(am__cd) $(distdir) && pwd`; \
-	    top_distdir=3D`$(am__cd) $(top_distdir) && pwd`; \
-	    (cd $$subdir && \
+	  fi; \
+	done
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" =3D .; then :; else \
+	    dir1=3D$$subdir; dir2=3D"$(distdir)/$$subdir"; \
+	    $(am__relativize); \
+	    new_distdir=3D$$reldir; \
+	    dir1=3D$$subdir; dir2=3D"$(top_distdir)"; \
+	    $(am__relativize); \
+	    new_top_distdir=3D$$reldir; \
+	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir=3D"$$new_t=
op_distdir" distdir=3D"$$new_distdir" \\"; \
+	    echo "     am__remove_distdir=3D: am__skip_length_check=3D: am__skip_=
mode_fix=3D: distdir)"; \
+	    ($(am__cd) $$subdir && \
 	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir=3D"$$top_distdir" \
-	        distdir=3D"$$distdir/$$subdir" \
+	        top_distdir=3D"$$new_top_distdir" \
+	        distdir=3D"$$new_distdir" \
 		am__remove_distdir=3D: \
 		am__skip_length_check=3D: \
+		am__skip_mode_fix=3D: \
 	        distdir) \
 	      || exit 1; \
 	  fi; \
@@ -561,6 +647,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -579,6 +666,8 @@
=20
 html: html-recursive
=20
+html-am:
+
 info: info-recursive
=20
 info-am:
@@ -586,23 +675,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-recursive
=20
-install-dvi: install-dvi-recursive
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-recursive
=20
+install-html-am:
+
 install-info: install-info-recursive
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-recursive
=20
+install-pdf-am:
+
 install-ps: install-ps-recursive
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-recursive
@@ -624,9 +721,9 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \
-	install-data-am install-exec-am install-strip uninstall-am
+.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) check-am \
+	ctags-recursive install-am install-data-am install-exec-am \
+	install-strip tags-recursive uninstall-am
=20
 .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
 	all all-am all-local check check-am check-local clean \
@@ -712,6 +809,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -797,7 +897,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -810,6 +910,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/common/Ma=
kefile.am
--- a/head/crypto/heimdal/appl/ftp/common/Makefile.am	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/appl/ftp/common/Makefile.am	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 14164 2004-08-26 11:55:29Z joda $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -10,3 +10,5 @@
 	sockbuf.c \
 	buffer.c \
 	common.h
+
+EXTRA_DIST =3D NTMakefile
\ No newline at end of file
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/common/Ma=
kefile.in
--- a/head/crypto/heimdal/appl/ftp/common/Makefile.in	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/appl/ftp/common/Makefile.in	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 14164 2004-08-26 11:55:29Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -44,7 +46,7 @@
 subdir =3D appl/ftp/common
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -59,7 +61,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -73,9 +75,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -83,21 +88,22 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 LIBRARIES =3D $(noinst_LIBRARIES)
 ARFLAGS =3D cru
 libcommon_a_AR =3D $(AR) $(ARFLAGS)
 libcommon_a_LIBADD =3D
 am_libcommon_a_OBJECTS =3D sockbuf.$(OBJEXT) buffer.$(OBJEXT)
 libcommon_a_OBJECTS =3D $(am_libcommon_a_OBJECTS)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -116,49 +122,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -182,10 +197,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -202,6 +218,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -217,31 +235,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -256,10 +288,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -300,30 +334,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_krb4)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 noinst_LIBRARIES =3D libcommon.a
 libcommon_a_SOURCES =3D \
@@ -331,22 +369,23 @@
 	buffer.c \
 	common.h
=20
+EXTRA_DIST =3D NTMakefile
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/=
common/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/common/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/ftp/common/Makefile=
'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/ftp/common/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -364,6 +403,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 clean-noinstLIBRARIES:
 	-test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
@@ -378,14 +418,29 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/buffer.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/sockbuf.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -398,45 +453,49 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -457,13 +516,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -495,6 +558,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -505,6 +569,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -515,6 +580,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -522,26 +589,35 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -561,9 +637,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libtool clean-noinstLIBRARIES ctags \
@@ -648,6 +723,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -733,7 +811,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -746,6 +824,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/common/bu=
ffer.c
--- a/head/crypto/heimdal/appl/ftp/common/buffer.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/ftp/common/buffer.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -36,7 +36,7 @@
 #include <err.h>
 #include "roken.h"
=20
-RCSID("$Id: buffer.c 9129 2000-10-23 04:49:25Z joda $");
+RCSID("$Id$");
=20
 /*
  * Allocate a buffer enough to handle st->st_blksize, if
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/common/co=
mmon.h
--- a/head/crypto/heimdal/appl/ftp/common/common.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/ftp/common/common.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: common.h 7463 1999-12-02 16:58:55Z joda $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/common/so=
ckbuf.c
--- a/head/crypto/heimdal/appl/ftp/common/sockbuf.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/ftp/common/sockbuf.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -39,16 +39,30 @@
 #include <sys/socket.h>
 #endif
=20
-RCSID("$Id: sockbuf.c 7463 1999-12-02 16:58:55Z joda $");
+RCSID("$Id$");
=20
 void
 set_buffer_size(int fd, int read)
 {
 #if defined(SO_RCVBUF) && defined(SO_SNDBUF) && defined(HAVE_SETSOCKOPT)
-    size_t size =3D 4194304;
-    while(size >=3D 131072 &&=20
-	  setsockopt(fd, SOL_SOCKET, read ? SO_RCVBUF : SO_SNDBUF,=20
-		     (void *)&size, sizeof(size)) < 0)
+    int size =3D 4194304;
+    int optname =3D read ? SO_RCVBUF : SO_SNDBUF;
+
+#ifdef HAVE_GETSOCKOPT
+    int curr=3D0;
+    socklen_t optlen;
+
+    optlen =3D sizeof(curr);
+    if(getsockopt(fd, SOL_SOCKET, optname, (void *)&curr, &optlen) =3D=3D =
0) {
+        if(curr >=3D size) {
+            /* Already large enough */
+            return;
+        }
+    }
+#endif /* HAVE_GETSOCKOPT */
+
+    while(size >=3D 131072 &&
+	  setsockopt(fd, SOL_SOCKET, optname, (void *)&size, sizeof(size)) < 0)
 	size /=3D 2;
 #endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/Makef=
ile.am
--- a/head/crypto/heimdal/appl/ftp/ftp/Makefile.am	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/Makefile.am	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,16 +1,13 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D -I$(srcdir)/../common $(INCLUDE_readline) $(INCLUDE_krb4)=
 $(INCLUDE_hcrypto)
+AM_CPPFLAGS +=3D -I$(srcdir)/../common $(INCLUDE_readline) $(INCLUDE_hcryp=
to)
=20
 bin_PROGRAMS =3D ftp
=20
 CHECK_LOCAL =3D=20
=20
-if KRB4
-krb4_sources =3D krb4.c
-endif
 if KRB5
 krb5_sources =3D gssapi.c
 endif
@@ -30,10 +27,9 @@
 	security.c \
 	security.h \
 	kauth.c \
-	$(krb4_sources) \
 	$(krb5_sources)
=20
-EXTRA_ftp_SOURCES =3D krb4.c gssapi.c
+EXTRA_ftp_SOURCES =3D gssapi.c
=20
 man_MANS =3D ftp.1
=20
@@ -41,9 +37,8 @@
 	../common/libcommon.a \
 	$(LIB_gssapi) \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_roken) \
 	$(LIB_readline)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/Makef=
ile.in
--- a/head/crypto/heimdal/appl/ftp/ftp/Makefile.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/Makefile.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/ftp/ftp
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,33 +89,32 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS)
 am__ftp_SOURCES_DIST =3D cmds.c cmdtab.c extern.h ftp.c ftp_locl.h \
 	ftp_var.h main.c pathnames.h ruserpass.c domacro.c globals.c \
-	security.c security.h kauth.c krb4.c gssapi.c
- at KRB4_TRUE@am__objects_1 =3D krb4.$(OBJEXT)
- at KRB5_TRUE@am__objects_2 =3D gssapi.$(OBJEXT)
+	security.c security.h kauth.c gssapi.c
+ at KRB5_TRUE@am__objects_1 =3D gssapi.$(OBJEXT)
 am_ftp_OBJECTS =3D cmds.$(OBJEXT) cmdtab.$(OBJEXT) ftp.$(OBJEXT) \
 	main.$(OBJEXT) ruserpass.$(OBJEXT) domacro.$(OBJEXT) \
 	globals.$(OBJEXT) security.$(OBJEXT) kauth.$(OBJEXT) \
-	$(am__objects_1) $(am__objects_2)
+	$(am__objects_1)
 ftp_OBJECTS =3D $(am_ftp_OBJECTS)
 ftp_LDADD =3D $(LDADD)
 am__DEPENDENCIES_1 =3D
 ftp_DEPENDENCIES =3D ../common/libcommon.a $(LIB_gssapi) $(LIB_krb5) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -122,6 +126,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(ftp_SOURCES) $(EXTRA_ftp_SOURCES)
 DIST_SOURCES =3D $(am__ftp_SOURCES_DIST) $(EXTRA_ftp_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -131,49 +156,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -197,10 +231,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -217,6 +252,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -232,31 +269,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -271,10 +322,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -315,34 +368,37 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	-I$(srcdir)/../common $(INCLUDE_readline) $(INCLUDE_krb4) \
-	$(INCLUDE_hcrypto)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I$(srcdir)/../common \
+	$(INCLUDE_readline) $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 CHECK_LOCAL =3D=20
- at KRB4_TRUE@krb4_sources =3D krb4.c
 @KRB5_TRUE at krb5_sources =3D gssapi.c
 ftp_SOURCES =3D \
 	cmds.c \
@@ -359,37 +415,35 @@
 	security.c \
 	security.h \
 	kauth.c \
-	$(krb4_sources) \
 	$(krb5_sources)
=20
-EXTRA_ftp_SOURCES =3D krb4.c gssapi.c
+EXTRA_ftp_SOURCES =3D gssapi.c
 man_MANS =3D ftp.1
 LDADD =3D \
 	../common/libcommon.a \
 	$(LIB_gssapi) \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_roken) \
 	$(LIB_readline)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/=
ftp/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/ftp/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/ftp/ftp/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/ftp/ftp/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -407,34 +461,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 ftp$(EXEEXT): $(ftp_OBJECTS) $(ftp_DEPENDENCIES)=20
 	@rm -f ftp$(EXEEXT)
 	$(LINK) $(ftp_OBJECTS) $(ftp_LDADD) $(LIBS)
@@ -445,115 +515,148 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/cmds.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/cmdtab.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/domacro.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ftp.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/globals.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gssapi.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kauth.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/main.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ruserpass.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/security.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -569,13 +672,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -610,6 +717,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -619,6 +727,7 @@
 clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -629,6 +738,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -636,26 +747,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -675,11 +795,10 @@
 uninstall-am: uninstall-binPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libtool ctags \
@@ -766,6 +885,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -851,7 +973,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -864,6 +986,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/cmds.c
--- a/head/crypto/heimdal/appl/ftp/ftp/cmds.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/cmds.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include "ftp_locl.h"
-RCSID("$Id: cmds.c 15673 2005-07-19 18:19:33Z lha $");
+RCSID("$Id$");
=20
 typedef void (*sighand)(int);
=20
@@ -189,7 +189,7 @@
 				unix_proxy =3D 0;
 			else
 				unix_server =3D 0;
-			if (overbose &&=20
+			if (overbose &&
 			    !strncmp(reply_string, "215 TOPS20", 10))
 				printf(
 "Remember to set tenex mode when transfering binary files from this machin=
e.\n");
@@ -682,15 +682,15 @@
 			tm->tm_year +=3D 1900;
=20
 			if ((tm->tm_year > yy) ||
-			    (tm->tm_year =3D=3D yy &&=20
+			    (tm->tm_year =3D=3D yy &&
 			     tm->tm_mon > mo) ||
-			    (tm->tm_mon =3D=3D mo &&=20
+			    (tm->tm_mon =3D=3D mo &&
 			     tm->tm_mday > day) ||
-			    (tm->tm_mday =3D=3D day &&=20
+			    (tm->tm_mday =3D=3D day &&
 			     tm->tm_hour > hour) ||
-			    (tm->tm_hour =3D=3D hour &&=20
+			    (tm->tm_hour =3D=3D hour &&
 			     tm->tm_min > min) ||
-			    (tm->tm_min =3D=3D min &&=20
+			    (tm->tm_min =3D=3D min &&
 			     tm->tm_sec > sec))
 				return (1);
 		}
@@ -868,7 +868,7 @@
 	sec_status();
 	printf("Mode: %s; Type: %s; Form: %s; Structure: %s\n",
 		modename, typename, formname, structname);
-	printf("Verbose: %s; Bell: %s; Prompting: %s; Globbing: %s\n",=20
+	printf("Verbose: %s; Bell: %s; Prompting: %s; Globbing: %s\n",
 		onoff(verbose), onoff(bell), onoff(interactive),
 		onoff(doglob));
 	printf("Store unique: %s; Receive unique: %s\n", onoff(sunique),
@@ -987,7 +987,7 @@
 void
 setglob(int argc, char **argv)
 {
-=09
+
 	doglob =3D !doglob;
 	printf("Globbing %s.\n", onoff(doglob));
 	code =3D doglob;
@@ -1171,7 +1171,7 @@
 		return;
 	}
 	if (strcmp(argv[2], "-") && *argv[2] !=3D '|')
-	    if (!globulize(&argv[2]) || !confirm("output to local-file:",=20
+	    if (!globulize(&argv[2]) || !confirm("output to local-file:",
 						 argv[2])) {
 		code =3D -1;
 		return;
@@ -1237,7 +1237,7 @@
 {
 	pid_t pid;
 	RETSIGTYPE (*old1)(int), (*old2)(int);
-	char shellnam[40], *shellpath, *namep;=20
+	char shellnam[40], *shellpath, *namep;
 	int waitstatus;
=20
 	old1 =3D signal (SIGINT, SIG_IGN);
@@ -1759,6 +1759,11 @@
 	mapflag =3D 1;
 	code =3D 1;
 	cp =3D strchr(altarg, ' ');
+	if (cp =3D=3D NULL) {
+		printf("Usage: %s missing space\n",argv[0]);
+		code =3D -1;
+		return;
+	}
 	if (proxy) {
 		while(*++cp =3D=3D ' ')
 			continue;
@@ -1833,7 +1838,7 @@
 				break;
 			case '[':
 LOOP:
-				if (*++cp2 =3D=3D '$' && isdigit((unsigned char)*(cp2+1))) {=20
+				if (*++cp2 =3D=3D '$' && isdigit((unsigned char)*(cp2+1))) {
 					if (*++cp2 =3D=3D '0') {
 						char *cp3 =3D name;
=20
@@ -1852,7 +1857,7 @@
 					}
 				}
 				else {
-					while (*cp2 && *cp2 !=3D ',' &&=20
+					while (*cp2 && *cp2 !=3D ',' &&
 					    *cp2 !=3D ']') {
 						if (*cp2 =3D=3D '\\') {
 							cp2++;
@@ -2137,7 +2142,7 @@
 	code =3D -1;
 	return;
     }
-   =20
+
     ret =3D command("SITE KLIST");
     code =3D (ret =3D=3D COMPLETE);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/cmdta=
b.c
--- a/head/crypto/heimdal/appl/ftp/ftp/cmdtab.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/ftp/ftp/cmdtab.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -106,17 +106,10 @@
=20
 char	prothelp[] =3D 	"set protection level";
 char	prothelp_c[] =3D	"set command protection level";
-#ifdef KRB4
-char	kauthhelp[] =3D 	"get remote tokens";
-#endif
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 char	klisthelp[] =3D	"show remote tickets";
 #endif
-#ifdef KRB4
-char	kdestroyhelp[] =3D "destroy remote tickets";
-char	krbtkfilehelp[] =3D "set filename of remote tickets";
-#endif
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 char	afsloghelp[] =3D 	"obtain remote AFS tokens";
 #endif
=20
@@ -197,20 +190,13 @@
 	{ "protect", 	prothelp, 	0, 	1, 	0,	sec_prot },
 	/* what MIT uses */
 	{ "cprotect",	prothelp_c,	0,	1,	1,	sec_prot_command },
-#ifdef KRB4
-	{ "kauth", 	kauthhelp, 	0, 	1, 	0,	kauth },
-#endif
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 	{ "klist", 	klisthelp, 	0, 	1, 	0,	klist },
 #endif
-#ifdef KRB4
-	{ "kdestroy",	kdestroyhelp,	0,	1,	0,	kdestroy },
-	{ "krbtkfile",	krbtkfilehelp,	0,	1,	0,	krbtkfile },
-#endif
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 	{ "afslog",	afsloghelp,	0,	1,	0,	afslog },
 #endif
-=09
+
 	{ 0 },
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/domac=
ro.c
--- a/head/crypto/heimdal/appl/ftp/ftp/domacro.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/domacro.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -32,7 +32,7 @@
  */
=20
 #include "ftp_locl.h"
-RCSID("$Id: domacro.c 14951 2005-04-25 13:09:26Z lha $");
+RCSID("$Id$");
=20
 void
 domacro(int argc, char **argv)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/exter=
n.h
--- a/head/crypto/heimdal/appl/ftp/ftp/extern.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/ftp/ftp/extern.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -33,7 +33,7 @@
  *	@(#)extern.h	8.3 (Berkeley) 10/9/94
  */
=20
-/* $Id: extern.h 9075 2000-09-19 13:15:12Z assar $ */
+/* $Id$ */
=20
 #include <setjmp.h>
 #include <stdlib.h>
@@ -117,7 +117,7 @@
 void	restart (int, char **);
 void	rmthelp (int, char **);
 void	rmtstatus (int, char **);
-int	ruserpass (char *, char **, char **, char **);
+int	ruserpassword (char *, char **, char **, char **);
 void    sendrequest (char *, char *, char *, char *, int);
 void	setascii (int, char **);
 void	setbell (int, char **);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/ftp.1
--- a/head/crypto/heimdal/appl/ftp/ftp/ftp.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/ftp.1	Tue Apr 17 11:51:51 2012 +0300
@@ -53,8 +53,8 @@
 .Op Fl t
 .Op Fl v
 .Op Fl x
-.Op Fl -no-gss-bindings
-.Op Fl -no-gss-delegate
+.Op Fl Fl no-gss-bindings
+.Op Fl Fl no-gss-delegate
 .Op Ar host
 .Sh DESCRIPTION
 .Nm
@@ -103,10 +103,10 @@
 Enables debugging.
 .It Fl g
 Disables file name globbing.
- .It Fl -no-gss-bindings
+ .It Fl Fl no-gss-bindings
 Don't use GSS-API bindings when talking to peer. IP addresses will not
 be checked to ensure they match.
-.It Fl -no-gss-delegate
+.It Fl Fl no-gss-delegate
 Disable delegation of GSSAPI credentials.
 .It Fl l
 Disables command line editing.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/ftp.c
--- a/head/crypto/heimdal/appl/ftp/ftp/ftp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/ftp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  */
=20
 #include "ftp_locl.h"
-RCSID ("$Id: ftp.c 16650 2006-01-24 08:16:08Z lha $");
+RCSID ("$Id$");
=20
 struct sockaddr_storage hisctladdr_ss;
 struct sockaddr *hisctladdr =3D (struct sockaddr *)&hisctladdr_ss;
@@ -89,7 +89,7 @@
 	    strlcpy (hostnamebuf, a->ai_canonname, sizeof(hostnamebuf));
=20
 	memcpy (hisctladdr, a->ai_addr, a->ai_addrlen);
-=09
+
 	error =3D connect (s, a->ai_addr, a->ai_addrlen);
 	if (error < 0) {
 	    char addrstr[256];
@@ -98,7 +98,7 @@
 			     addrstr, sizeof(addrstr),
 			     NULL, 0, NI_NUMERICHOST) !=3D 0)
 		strlcpy (addrstr, "unknown address", sizeof(addrstr));
-			    =20
+
 	    warn ("connect %s", addrstr);
 	    close (s);
 	    s =3D -1;
@@ -167,6 +167,7 @@
     char tmp[80];
     char defaultpass[128];
     char *userstr, *pass, *acctstr;
+    char *ruserstr, *rpass, *racctstr;
     int n, aflag =3D 0;
=20
     char *myname =3D NULL;
@@ -175,7 +176,7 @@
     if (pw !=3D NULL)
 	myname =3D pw->pw_name;
=20
-    userstr =3D pass =3D acctstr =3D 0;
+    ruserstr =3D rpass =3D racctstr =3D NULL;
=20
     if(sec_login(host))
 	printf("\n*** Using plaintext user and password ***\n\n");
@@ -183,10 +184,14 @@
 	printf("Authentication successful.\n\n");
     }
=20
-    if (ruserpass (host, &userstr, &pass, &acctstr) < 0) {
+    if (ruserpassword (host, &ruserstr, &rpass, &racctstr) < 0) {
 	code =3D -1;
 	return (0);
     }
+    userstr =3D ruserstr;
+    pass =3D rpass;
+    acctstr =3D racctstr;
+
     while (userstr =3D=3D NULL) {
 	if (myname)
 	    printf ("Name (%s:%s): ", host, myname);
@@ -201,17 +206,20 @@
 	    userstr =3D tmp;
     }
     strlcpy(username, userstr, sizeof(username));
+    if (ruserstr)
+	free(ruserstr);
+
     n =3D command("USER %s", userstr);
-    if (n =3D=3D COMPLETE)=20
+    if (n =3D=3D COMPLETE)
        n =3D command("PASS dummy"); /* DK: Compatibility with gssftp daemo=
n */
     else if(n =3D=3D CONTINUE) {
 	if (pass =3D=3D NULL) {
 	    char prompt[128];
-	    if(myname &&=20
+	    if(myname &&
 	       (!strcmp(userstr, "ftp") || !strcmp(userstr, "anonymous"))) {
-		snprintf(defaultpass, sizeof(defaultpass),=20
+		snprintf(defaultpass, sizeof(defaultpass),
 			 "%s@%s", myname, mydomain);
-		snprintf(prompt, sizeof(prompt),=20
+		snprintf(prompt, sizeof(prompt),
 			 "Password (%s): ", defaultpass);
 	    } else if (sec_complete) {
 		pass =3D myname;
@@ -227,19 +235,25 @@
 	    }
 	}
 	n =3D command ("PASS %s", pass);
+	if (rpass)
+	    free(rpass);
     }
     if (n =3D=3D CONTINUE) {
 	aflag++;
+	UI_UTIL_read_pw_string (tmp, sizeof(tmp), "Account:", 0);
 	acctstr =3D tmp;
-	UI_UTIL_read_pw_string (acctstr, 128, "Account:", 0);
 	n =3D command ("ACCT %s", acctstr);
     }
     if (n !=3D COMPLETE) {
+	if (racctstr)
+	    free(racctstr);
 	warnx ("Login failed.");
 	return (0);
     }
     if (!aflag && acctstr !=3D NULL)
 	command ("ACCT %s", acctstr);
+    if (racctstr)
+	free(racctstr);
     if (proxy)
 	return (1);
     for (n =3D 0; n < macnum; ++n) {
@@ -417,7 +431,7 @@
 	    continue;
 	default:
 	    if(p < buf + sizeof(buf) - 1)
-		*p++ =3D c;=20
+		*p++ =3D c;
 	    else if(long_warn =3D=3D 0) {
 		fprintf(stderr, "WARNING: incredibly long line received\n");
 		long_warn =3D 1;
@@ -579,6 +593,9 @@
=20
 #if defined(HAVE_MMAP) && !defined(NO_MMAP)
     void *chunk;
+    size_t off;
+
+#define BLOCKSIZE (1024 * 1024 * 10)
=20
 #ifndef MAP_FAILED
 #define MAP_FAILED (-1)
@@ -590,17 +607,35 @@
 	 */
 	if (st.st_size =3D=3D 0)
 	    return 0;
-	chunk =3D mmap (0, st.st_size, PROT_READ, MAP_SHARED, fileno (from), 0);
-	if (chunk !=3D (void *) MAP_FAILED) {
-	    int res;
+	off =3D 0;
+	while (off !=3D st.st_size) {
+	    size_t len;
+	    ssize_t res;
=20
-	    res =3D sec_write (fileno (to), chunk, st.st_size);
-	    if (munmap (chunk, st.st_size) < 0)
+	    len =3D st.st_size - off;
+	    if (len > BLOCKSIZE)
+		len =3D BLOCKSIZE;
+
+	    chunk =3D mmap (0, len, PROT_READ, MAP_SHARED, fileno (from), off);
+	    if (chunk =3D=3D (void *) MAP_FAILED) {
+		if (off =3D=3D 0) /* try read if mmap doesn't work */
+		    goto try_read;
+		break;
+	    }
+
+	    res =3D sec_write (fileno (to), chunk, len);
+	    if (msync (chunk, len, MS_ASYNC))
+		warn ("msync");
+	    if (munmap (chunk, len) < 0)
 		warn ("munmap");
 	    sec_fflush (to);
-	    return res;
+	    if (res !=3D len)
+		return off;
+	    off +=3D len;
 	}
+	return off;
     }
+try_read:
 #endif
=20
     buf =3D alloc_buffer (buf, &bufsize,
@@ -643,7 +678,7 @@
     char *rmode =3D "w";
=20
     if (verbose && printnames) {
-	if (local && strcmp (local, "-") !=3D 0)
+	if (strcmp (local, "-") !=3D 0)
 	    printf ("local: %s ", local);
 	if (remote)
 	    printf ("remote: %s\n", remote);
@@ -696,8 +731,7 @@
 	    return;
 	}
 	closefunc =3D fclose;
-	if (fstat (fileno (fin), &st) < 0 ||
-	    (st.st_mode & S_IFMT) !=3D S_IFREG) {
+	if (fstat (fileno (fin), &st) < 0 || !S_ISREG(st.st_mode)) {
 	    fprintf (stdout, "%s: not a plain file.\n", local);
 	    signal (SIGINT, oldintr);
 	    fclose (fin);
@@ -875,7 +909,7 @@
=20
     is_retr =3D strcmp (cmd, "RETR") =3D=3D 0;
     if (is_retr && verbose && printnames) {
-	if (local && strcmp (local, "-") !=3D 0)
+	if (strcmp (local, "-") !=3D 0)
 	    printf ("local: %s ", local);
 	if (remote)
 	    printf ("remote: %s\n", remote);
@@ -902,7 +936,7 @@
 	return;
     }
     oldintr =3D signal (SIGINT, abortrecv);
-    if (!local_given || (strcmp (local, "-") && *local !=3D '|')) {
+    if (!local_given || (strcmp(local, "-") && *local !=3D '|')) {
 	if (access (local, 2) < 0) {
 	    char *dir =3D strrchr (local, '/');
=20
@@ -1317,7 +1351,7 @@
 	    verbose  =3D -1;
=20
 	result =3D command ("EPRT |%d|%s|%d|",
-			  inet_af, addr_str,=20
+			  inet_af, addr_str,
 			  ntohs(socket_get_port (data_addr)));
 	verbose =3D overbose;
=20
@@ -1332,7 +1366,7 @@
 		goto bad;
 	    }
=20
-	    result =3D command("PORT %d,%d,%d,%d,%d,%d",=20
+	    result =3D command("PORT %d,%d,%d,%d,%d,%d",
 			     (a >> 24) & 0xff,
 			     (a >> 16) & 0xff,
 			     (a >> 8) & 0xff,
@@ -1371,7 +1405,7 @@
 int
 initconn (void)
 {
-    if (passivemode)=20
+    if (passivemode)
 	return passive_mode ();
     else
 	return active_mode ();
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/ftp_l=
ocl.h
--- a/head/crypto/heimdal/appl/ftp/ftp/ftp_locl.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/ftp_locl.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,8 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: ftp_locl.h 11444 2002-09-10 20:03:49Z joda $ */
-/* $FreeBSD$ */
+/* $Id$ */
=20
 #ifndef __FTP_LOCL_H__
 #define __FTP_LOCL_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/globa=
ls.c
--- a/head/crypto/heimdal/appl/ftp/ftp/globals.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/globals.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,5 +1,5 @@
 #include "ftp_locl.h"
-RCSID("$Id: globals.c 16160 2005-10-12 09:42:47Z joda $");
+RCSID("$Id$");
=20
 /*
  * Options and other state info.
@@ -74,6 +74,6 @@
=20
 char username[32];
=20
-/* these are set in ruserpass */
+/* these are set in ruserpassword */
 char myhostname[MaxHostNameLen];
 char *mydomain;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/gssap=
i.c
--- a/head/crypto/heimdal/appl/ftp/ftp/gssapi.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/ftp/ftp/gssapi.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1998 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifdef FTP_SERVER
@@ -36,17 +36,18 @@
 #else
 #include "ftp_locl.h"
 #endif
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
 #include <krb5_err.h>
=20
-RCSID("$Id: gssapi.c 21513 2007-07-12 12:45:25Z lha $");
+RCSID("$Id$");
=20
 int ftp_do_gss_bindings =3D 0;
 int ftp_do_gss_delegate =3D 1;
=20
-struct gss_data {
+struct gssapi_data {
     gss_ctx_id_t context_hdl;
-    char *client_name;
+    gss_name_t client_name;
     gss_cred_id_t delegated_cred_handle;
     void *mech_data;
 };
@@ -54,7 +55,7 @@
 static int
 gss_init(void *app_data)
 {
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     d->context_hdl =3D GSS_C_NO_CONTEXT;
     d->delegated_cred_handle =3D GSS_C_NO_CREDENTIAL;
 #if defined(FTP_SERVER)
@@ -84,7 +85,7 @@
     gss_buffer_desc input, output;
     gss_qop_t qop_state;
     int conf_state;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     size_t ret_len;
=20
     input.length =3D len;
@@ -116,7 +117,7 @@
     OM_uint32 maj_stat, min_stat;
     gss_buffer_desc input, output;
     int conf_state;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
=20
     input.length =3D length;
     input.value =3D from;
@@ -157,7 +158,7 @@
     }
     default :
 	errx (1, "unknown address family %d", sa->sa_family);
-=09
+
     }
 }
=20
@@ -172,7 +173,7 @@
     gss_buffer_desc input_token, output_token;
     OM_uint32 maj_stat, min_stat;
     gss_name_t client_name;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     gss_channel_bindings_t bindings;
=20
     if (ftp_do_gss_bindings) {
@@ -186,7 +187,7 @@
 	sockaddr_to_gss_address (ctrl_addr,
 				 &bindings->acceptor_addrtype,
 				 &bindings->acceptor_address);
-=09
+
 	bindings->application_data.length =3D 0;
 	bindings->application_data.value =3D NULL;
     } else
@@ -218,32 +219,8 @@
 	gss_release_buffer(&min_stat, &output_token);
     }
     if(maj_stat =3D=3D GSS_S_COMPLETE){
-	char *name;
-	gss_buffer_desc export_name;
-	gss_OID oid;
-
-	maj_stat =3D gss_display_name(&min_stat, client_name,
-				    &export_name, &oid);
-	if(maj_stat !=3D 0) {
-	    reply(500, "Error displaying name");
-	    goto out;
-	}
-	/* XXX kerberos */
-	if(oid !=3D GSS_KRB5_NT_PRINCIPAL_NAME) {
-	    reply(500, "OID not kerberos principal name");
-	    gss_release_buffer(&min_stat, &export_name);
-	    goto out;
-	}
-	name =3D malloc(export_name.length + 1);
-	if(name =3D=3D NULL) {
-	    reply(500, "Out of memory");
-	    gss_release_buffer(&min_stat, &export_name);
-	    goto out;
-	}
-	memcpy(name, export_name.value, export_name.length);
-	name[export_name.length] =3D '\0';
-	gss_release_buffer(&min_stat, &export_name);
-	d->client_name =3D name;
+	d->client_name =3D client_name;
+	client_name =3D GSS_C_NO_NAME;
 	if(p)
 	    reply(235, "ADAT=3D%s", p);
 	else
@@ -265,24 +242,25 @@
 			   GSS_C_NO_OID,
 			   &msg_ctx,
 			   &status_string);
-	syslog(LOG_ERR, "gss_accept_sec_context: %s",=20
+	syslog(LOG_ERR, "gss_accept_sec_context: %.*s",
+	       (int)status_string.length,
 	       (char*)status_string.value);
 	gss_release_buffer(&new_stat, &status_string);
 	reply(431, "Security resource unavailable");
     }
-  out:
+
     if (client_name)
 	gss_release_name(&min_stat, &client_name);
     free(p);
     return 0;
 }
=20
-int gss_userok(void*, char*);
-int gss_session(void*, char*);
+int gssapi_userok(void*, char*);
+int gssapi_session(void*, char*);
=20
 struct sec_server_mech gss_server_mech =3D {
     "GSSAPI",
-    sizeof(struct gss_data),
+    sizeof(struct gssapi_data),
     gss_init, /* init */
     NULL, /* end */
     gss_check_prot,
@@ -294,8 +272,8 @@
     gss_adat,
     NULL, /* pbsz */
     NULL, /* ccc */
-    gss_userok,
-    gss_session
+    gssapi_userok,
+    gssapi_session
 };
=20
 #else /* FTP_SERVER */
@@ -324,15 +302,17 @@
 	OM_uint32 new_stat;
 	OM_uint32 msg_ctx =3D 0;
 	gss_buffer_desc status_string;
-	   =20
+
 	gss_display_status(&new_stat,
 			   min_stat,
 			   GSS_C_MECH_CODE,
 			   GSS_C_NO_OID,
 			   &msg_ctx,
 			   &status_string);
-	printf("Error importing name %s: %s\n",=20
+	printf("Error importing name %.*s: %.*s\n",
+	       (int)name.length,
 	       (char *)name.value,
+	       (int)status_string.length,
 	       (char *)status_string.value);
 	free(name.value);
 	gss_release_buffer(&new_stat, &status_string);
@@ -345,7 +325,7 @@
 static int
 gss_auth(void *app_data, char *host)
 {
-   =20
+
     OM_uint32 maj_stat, min_stat;
     gss_name_t target_name;
     gss_buffer_desc input, output_token;
@@ -353,12 +333,12 @@
     char *p;
     int n;
     gss_channel_bindings_t bindings;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     OM_uint32 mech_flags =3D GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG;
=20
     const char *knames[] =3D { "ftp", "host", NULL }, **kname =3D knames;
-	   =20
-   =20
+
+
     if(import_name(*kname++, host, &target_name))
 	return AUTH_ERROR;
=20
@@ -369,14 +349,14 @@
 	bindings =3D malloc(sizeof(*bindings));
 	if (bindings =3D=3D NULL)
 	    errx(1, "out of memory");
-=09
+
 	sockaddr_to_gss_address (myctladdr,
 				 &bindings->initiator_addrtype,
 				 &bindings->initiator_address);
 	sockaddr_to_gss_address (hisctladdr,
 				 &bindings->acceptor_addrtype,
 				 &bindings->acceptor_address);
-=09
+
 	bindings->application_data.length =3D 0;
 	bindings->application_data.value =3D NULL;
     } else
@@ -417,7 +397,7 @@
 		}
 		continue;
 	    }
-	   =20
+
 	    if (bindings !=3D GSS_C_NO_CHANNEL_BINDINGS)
 		free(bindings);
=20
@@ -427,7 +407,8 @@
 			       GSS_C_NO_OID,
 			       &msg_ctx,
 			       &status_string);
-	    printf("Error initializing security context: %s\n",=20
+	    printf("Error initializing security context: %.*s\n",
+		   (int)status_string.length,
 		   (char*)status_string.value);
 	    gss_release_buffer(&new_stat, &status_string);
 	    return AUTH_CONTINUE;
@@ -501,13 +482,15 @@
 					 &name,
 					 NULL);
 	    if (GSS_ERROR(maj_stat) =3D=3D 0) {
-		printf("Authenticated to <%s>\n", (char *)name.value);
+		printf("Authenticated to <%.*s>\n",
+			(int)name.length,
+			(char *)name.value);
 		gss_release_buffer(&min_stat, &name);
 	    }
 	    gss_release_name(&min_stat, &targ_name);
 	} else
 	    printf("Failed to get gss name of peer.\n");
-    }	   =20
+    }
=20
=20
     return AUTH_OK;
@@ -515,7 +498,7 @@
=20
 struct sec_client_mech gss_client_mech =3D {
     "GSSAPI",
-    sizeof(struct gss_data),
+    sizeof(struct gssapi_data),
     gss_init,
     gss_auth,
     NULL, /* end */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/kauth=
.c
--- a/head/crypto/heimdal/appl/ftp/ftp/kauth.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/ftp/ftp/kauth.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -32,145 +32,9 @@
  */
=20
 #include "ftp_locl.h"
-RCSID("$Id: kauth.c 15666 2005-07-19 17:08:11Z lha $");
+RCSID("$Id$");
=20
-#ifdef KRB4
-#include <krb.h>
-
-void
-kauth(int argc, char **argv)
-{
-    int ret;
-    char buf[1024];
-    des_cblock key;
-    des_key_schedule schedule;
-    KTEXT_ST tkt, tktcopy;
-    char *name;
-    char *p;
-    int overbose;
-    char passwd[100];
-    int tmp;
-=09
-    int save;
-
-    if(argc > 2){
-	printf("usage: %s [principal]\n", argv[0]);
-	code =3D -1;
-	return;
-    }
-    if(argc =3D=3D 2)
-	name =3D argv[1];
-    else
-	name =3D username;
-
-    overbose =3D verbose;
-    verbose =3D 0;
-
-    save =3D set_command_prot(prot_private);
-    ret =3D command("SITE KAUTH %s", name);
-    if(ret !=3D CONTINUE){
-	verbose =3D overbose;
-	set_command_prot(save);
-	code =3D -1;
-	return;
-    }
-    verbose =3D overbose;
-    p =3D strstr(reply_string, "T=3D");
-    if(!p){
-	printf("Bad reply from server.\n");
-	set_command_prot(save);
-	code =3D -1;
-	return;
-    }
-    p +=3D 2;
-    tmp =3D base64_decode(p, &tkt.dat);
-    if(tmp < 0){
-	printf("Failed to decode base64 in reply.\n");
-	set_command_prot(save);
-	code =3D -1;
-	return;
-    }
-    tkt.length =3D tmp;
-    tktcopy.length =3D tkt.length;
-   =20
-    p =3D strstr(reply_string, "P=3D");
-    if(!p){
-	printf("Bad reply from server.\n");
-	verbose =3D overbose;
-	set_command_prot(save);
-	code =3D -1;
-	return;
-    }
-    name =3D p + 2;
-    for(; *p && *p !=3D ' ' && *p !=3D '\r' && *p !=3D '\n'; p++);
-    *p =3D 0;
-   =20
-    snprintf(buf, sizeof(buf), "Password for %s:", name);
-    if (des_read_pw_string (passwd, sizeof(passwd)-1, buf, 0))
-        *passwd =3D '\0';
-    des_string_to_key (passwd, &key);
-
-    des_key_sched(&key, schedule);
-   =20
-    des_pcbc_encrypt((des_cblock*)tkt.dat, (des_cblock*)tktcopy.dat,
-		     tkt.length,
-		     schedule, &key, DES_DECRYPT);
-    if (strcmp ((char*)tktcopy.dat + 8,
-		KRB_TICKET_GRANTING_TICKET) !=3D 0) {
-        afs_string_to_key (passwd, krb_realmofhost(hostname), &key);
-	des_key_sched (&key, schedule);
-	des_pcbc_encrypt((des_cblock*)tkt.dat, (des_cblock*)tktcopy.dat,
-			 tkt.length,
-			 schedule, &key, DES_DECRYPT);
-    }
-    memset(key, 0, sizeof(key));
-    memset(schedule, 0, sizeof(schedule));
-    memset(passwd, 0, sizeof(passwd));
-    if(base64_encode(tktcopy.dat, tktcopy.length, &p) < 0) {
-	printf("Out of memory base64-encoding.\n");
-	set_command_prot(save);
-	code =3D -1;
-	return;
-    }
-    memset (tktcopy.dat, 0, tktcopy.length);
-    ret =3D command("SITE KAUTH %s %s", name, p);
-    free(p);
-    set_command_prot(save);
-    if(ret !=3D COMPLETE){
-	code =3D -1;
-	return;
-    }
-    code =3D 0;
-}
-
-void
-kdestroy(int argc, char **argv)
-{
-    int ret;
-    if (argc !=3D 1) {
-	printf("usage: %s\n", argv[0]);
-	code =3D -1;
-	return;
-    }
-    ret =3D command("SITE KDESTROY");
-    code =3D (ret =3D=3D COMPLETE);
-}
-
-void
-krbtkfile(int argc, char **argv)
-{
-    int ret;
-    if(argc !=3D 2) {
-	printf("usage: %s tktfile\n", argv[0]);
-	code =3D -1;
-	return;
-    }
-    ret =3D command("SITE KRBTKFILE %s", argv[1]);
-    code =3D (ret =3D=3D COMPLETE);
-}
-#endif
-
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
=20
 void
 afslog(int argc, char **argv)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/main.c
--- a/head/crypto/heimdal/appl/ftp/ftp/main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -38,7 +38,7 @@
 #include "ftp_locl.h"
 #include <getarg.h>
=20
-RCSID("$Id: main.c 16160 2005-10-12 09:42:47Z joda $");
+RCSID("$Id$");
=20
 static int help_flag;
 static int version_flag;
@@ -142,7 +142,7 @@
 	}
 	if (argc > 0) {
 	    char *xargv[5];
-	   =20
+
 	    if (setjmp(toplevel))
 		exit(0);
 	    signal(SIGINT, intr);
@@ -217,7 +217,7 @@
 	char *filename;
 {
 	char *s;
-=09
+
 	while (*filename) {
 		s =3D strrchr(filename, '/');
 		if (s =3D=3D NULL)
@@ -555,10 +555,9 @@
 		for (i =3D 0; i < lines; i++) {
 			for (j =3D 0; j < columns; j++) {
 				c =3D cmdtab + j * lines + i;
-				if (c->c_name && (!proxy || c->c_proxy)) {
+				if ((!proxy || c->c_proxy)) {
 					printf("%s", c->c_name);
-				}
-				else if (c->c_name) {
+				} else {
 					for (k=3D0; k < strlen(c->c_name); k++) {
 						putchar(' ');
 					}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/ruser=
pass.c
--- a/head/crypto/heimdal/appl/ftp/ftp/ruserpass.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/ruserpass.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -32,7 +32,7 @@
  */
=20
 #include "ftp_locl.h"
-RCSID("$Id: ruserpass.c 16161 2005-10-12 09:44:24Z joda $");
+RCSID("$Id$");
=20
 static	int token (void);
 static	FILE *cfile;
@@ -59,7 +59,7 @@
 	{ "account",	ACCOUNT },
 	{ "machine",	MACH },
 	{ "macdef",	MACDEF },
-	{ "prot", 	PROT },=20
+	{ "prot", 	PROT },
 	{ NULL,		0 }
 };
=20
@@ -105,7 +105,7 @@
 }
=20
 int
-ruserpass(char *host, char **aname, char **apass, char **aacct)
+ruserpassword(char *host, char **aname, char **apass, char **aacct)
 {
     char *hdir, buf[BUFSIZ], *tmp;
     int t, i, c, usedefault =3D 0;
@@ -137,7 +137,7 @@
 		continue;
 	    /*
 	     * Allow match either for user's input host name
-	     * or official hostname.  Also allow match of=20
+	     * or official hostname.  Also allow match of
 	     * incompletely-specified host in local domain.
 	     */
 	    if (strcasecmp(host, tokval) =3D=3D 0)
@@ -163,7 +163,7 @@
=20
 	case LOGIN:
 	    if (token()) {
-		if (*aname =3D=3D 0) {=20
+		if (*aname =3D=3D 0) {
 		    *aname =3D strdup(tokval);
 		} else {
 		    if (strcmp(*aname, tokval))
@@ -199,7 +199,7 @@
 		fclose(cfile);
 		return (0);
 	    }
-	    while ((c=3Dgetc(cfile)) !=3D EOF &&=20
+	    while ((c=3Dgetc(cfile)) !=3D EOF &&
 		   (c =3D=3D ' ' || c =3D=3D '\t'));
 	    if (c =3D=3D EOF || c =3D=3D '\n') {
 		printf("Missing macdef name argument.\n");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/secur=
ity.c
--- a/head/crypto/heimdal/appl/ftp/ftp/security.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/security.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1998-2002, 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1998-2002, 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -37,7 +37,7 @@
 #include "ftp_locl.h"
 #endif
=20
-RCSID("$Id: security.c 21225 2007-06-20 10:16:02Z lha $");
+RCSID("$Id$");
=20
 static enum protection_level command_prot;
 static enum protection_level data_prot;
@@ -74,14 +74,14 @@
 }
=20
 #ifndef FTP_SERVER /* not used in server */
-static enum protection_level=20
+static enum protection_level
 name_to_level(const char *name)
 {
     int i;
     for(i =3D 0; i < sizeof(level_names) / sizeof(level_names[0]); i++)
 	if(!strncasecmp(level_names[i].name, name, strlen(name)))
 	    return level_names[i].level;
-    return (enum protection_level)-1;
+    return prot_invalid;
 }
 #endif
=20
@@ -91,9 +91,6 @@
 #ifdef KRB5
     &gss_server_mech,
 #endif
-#ifdef KRB4
-    &krb4_server_mech,
-#endif
     NULL
 };
=20
@@ -105,9 +102,6 @@
 #ifdef KRB5
     &gss_client_mech,
 #endif
-#ifdef KRB4
-    &krb4_client_mech,
-#endif
     NULL
 };
=20
@@ -229,12 +223,12 @@
 	in_buffer.eof_flag =3D 0;
 	return 0;
     }
-   =20
+
     len =3D buffer_read(&in_buffer, dataptr, length);
     length -=3D len;
     rx +=3D len;
     dataptr =3D (char*)dataptr + len;
-   =20
+
     while(length){
 	int ret;
=20
@@ -286,7 +280,7 @@
 {
     int len =3D buffer_size;
     int tx =3D 0;
-     =20
+
     if(data_prot =3D=3D prot_clear)
 	return write(fd, dataptr, length);
=20
@@ -337,7 +331,7 @@
     char ch =3D c;
     if(data_prot =3D=3D prot_clear)
 	return putc(c, F);
-   =20
+
     buffer_write(&out_buffer, &ch, 1);
     if(c =3D=3D '\n' || out_buffer.index >=3D 1024 /* XXX */) {
 	sec_write(fileno(F), out_buffer.data, out_buffer.index);
@@ -352,14 +346,14 @@
     int len;
     char *buf;
     int return_code;
-   =20
+
     buf =3D malloc(strlen(s));
     len =3D base64_decode(s + 4, buf); /* XXX */
-   =20
+
     len =3D (*mech->decode)(app_data, buf, len, level);
     if(len < 0)
 	return -1;
-   =20
+
     buf[len] =3D '\0';
=20
     if(buf[3] =3D=3D '-')
@@ -381,7 +375,7 @@
     int len;
     if(!sec_complete)
 	return vfprintf(f, fmt, ap);
-   =20
+
     if (vasprintf(&buf, fmt, ap) =3D=3D -1) {
 	printf("Failed to allocate command.\n");
 	return -1;
@@ -520,10 +514,10 @@
 	reply(504, "Unrecognized protection level.");
 	return;
     }
-   =20
+
     if(sec_complete){
 	if((*mech->check_prot)(app_data, p)){
-	    reply(536, "%s does not support %s protection.",=20
+	    reply(536, "%s does not support %s protection.",
 		  mech->name, level_to_name(p));
 	}else{
 	    data_prot =3D (enum protection_level)p;
@@ -556,14 +550,20 @@
     }
     buf_size =3D strlen(msg) + 2;
     buf =3D malloc(buf_size);
+    if (buf =3D=3D NULL) {
+	reply(501, "Failed to allocate %lu", (unsigned long)buf_size);
+	return;
+    }
     len =3D base64_decode(msg, buf);
     command_prot =3D level;
     if(len =3D=3D (size_t)-1) {
+	free(buf);
 	reply(501, "Failed to base64-decode command");
 	return;
     }
     len =3D (*mech->decode)(app_data, buf, len, level);
     if(len =3D=3D (size_t)-1) {
+	free(buf);
 	reply(535, "Failed to decode command");
 	return;
     }
@@ -628,7 +628,7 @@
 	printf("Using %s command channel.\n", level_to_name(command_prot));
 	printf("Using %s data channel.\n", level_to_name(data_prot));
 	if(buffer_size > 0)
-	    printf("Protection buffer size: %lu.\n",=20
+	    printf("Protection buffer size: %lu.\n",
 		   (unsigned long)buffer_size);
     }else{
 	printf("Not using any security mechanism.\n");
@@ -669,7 +669,7 @@
 	printf("Failed to set protection level.\n");
 	return -1;
     }
-   =20
+
     data_prot =3D (enum protection_level)level;
     return 0;
 }
@@ -683,7 +683,7 @@
 	ret =3D command("CCC");
 	if(ret !=3D COMPLETE) {
 	    printf("Failed to clear command channel.\n");
-	    return -1;
+	    return prot_invalid;
 	}
     }
     command_prot =3D level;
@@ -708,17 +708,17 @@
 	return;
     }
     level =3D name_to_level(argv[argc - 1]);
-   =20
+
     if(level =3D=3D -1)
 	goto usage;
-   =20
+
     if((*mech->check_prot)(app_data, level)) {
-	printf("%s does not implement %s protection.\n",=20
+	printf("%s does not implement %s protection.\n",
 	       mech->name, level_to_name(level));
 	code =3D -1;
 	return;
     }
-   =20
+
     if(argc =3D=3D 2 || strncasecmp(argv[1], "data", strlen(argv[1])) =3D=
=3D 0) {
 	if(sec_prot_internal(level) < 0){
 	    code =3D -1;
@@ -759,9 +759,9 @@
 	level =3D name_to_level(argv[1]);
 	if(level =3D=3D -1)
 	    goto usage;
-   =20
+
 	if((*mech->check_prot)(app_data, level)) {
-	    printf("%s does not implement %s protection.\n",=20
+	    printf("%s does not implement %s protection.\n",
 		   mech->name, level_to_name(level));
 	    code =3D -1;
 	    return;
@@ -808,7 +808,7 @@
=20
     verbose =3D -1; /* shut up all messages this will produce (they
 		     are usually not very user friendly) */
-   =20
+
     for(m =3D mechs; *m && (*m)->name; m++) {
 	void *tmp;
=20
@@ -818,7 +818,7 @@
 	    return -1;
 	}
 	app_data =3D tmp;
-	   =20
+
 	if((*m)->init && (*(*m)->init)(app_data) !=3D 0) {
 	    printf("Skipping %s...\n", (*m)->name);
 	    continue;
@@ -840,7 +840,7 @@
 	}
=20
 	ret =3D (*(*m)->auth)(app_data, host);
-=09
+
 	if(ret =3D=3D AUTH_CONTINUE)
 	    continue;
 	else if(ret !=3D AUTH_OK){
@@ -852,13 +852,13 @@
 	sec_complete =3D 1;
 	if(doencrypt) {
 	    command_prot =3D prot_private;
-	    request_data_prot =3D prot_private;=20
+	    request_data_prot =3D prot_private;
 	} else {
 	    command_prot =3D prot_safe;
 	}
 	break;
     }
-   =20
+
     verbose =3D old_verbose;
     return *m =3D=3D NULL;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftp/secur=
ity.h
--- a/head/crypto/heimdal/appl/ftp/ftp/security.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/ftp/ftp/security.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,46 +1,47 @@
 /*
- * Copyright (c) 1998 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: security.h 21224 2007-06-20 10:15:13Z lha $ */
+/* $Id$ */
=20
 #ifndef __security_h__
 #define __security_h__
=20
-enum protection_level {=20
-    prot_clear,=20
-    prot_safe,=20
-    prot_confidential,=20
-    prot_private=20
+enum protection_level {
+    prot_invalid =3D -1,
+    prot_clear =3D 0,
+    prot_safe =3D 1,
+    prot_confidential =3D 2,
+    prot_private =3D 3
 };
=20
 struct sec_client_mech {
@@ -137,4 +138,4 @@
=20
 #endif
=20
-#endif /* __security_h__ */ =20
+#endif /* __security_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/Make=
file.am
--- a/head/crypto/heimdal/appl/ftp/ftpd/Makefile.am	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/Makefile.am	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 21031 2007-06-09 05:00:27Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -8,9 +8,6 @@
=20
 CHECK_LOCAL =3D=20
=20
-if KRB4
-krb4_sources =3D krb4.c
-endif
 if KRB5
 krb5_sources =3D gssapi.c gss_userok.c
 endif
@@ -30,7 +27,7 @@
 	$(krb4_sources) \
 	$(krb5_sources)
=20
-EXTRA_ftpd_SOURCES =3D krb4.c kauth.c gssapi.c gss_userok.c
+EXTRA_ftpd_SOURCES =3D kauth.c gssapi.c gss_userok.c
=20
 $(ftpd_OBJECTS): security.h
=20
@@ -38,12 +35,10 @@
 	@test -f security.c || $(LN_S) $(srcdir)/../ftp/security.c .
 security.h:
 	@test -f security.h || $(LN_S) $(srcdir)/../ftp/security.h .
-krb4.c:
-	@test -f krb4.c || $(LN_S) $(srcdir)/../ftp/krb4.c .
 gssapi.c:
 	@test -f gssapi.c || $(LN_S) $(srcdir)/../ftp/gssapi.c .
=20
-CLEANFILES =3D security.c security.h krb4.c gssapi.c
+CLEANFILES =3D security.c security.h gssapi.c
=20
 man_MANS =3D ftpd.8 ftpusers.5
=20
@@ -56,4 +51,4 @@
 	$(LIB_hcrypto) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/Make=
file.in
--- a/head/crypto/heimdal/appl/ftp/ftpd/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 21031 2007-06-09 05:00:27Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/ftp/ftpd
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,25 +89,23 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(man5dir)" \
 	"$(DESTDIR)$(man8dir)"
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(libexec_PROGRAMS)
 am__ftpd_SOURCES_DIST =3D extern.h ftpcmd.y ftpd.c ftpd_locl.h logwtmp.c \
-	ls.c pathnames.h popen.c security.c kauth.c klist.c krb4.c \
-	gssapi.c gss_userok.c
- at KRB4_TRUE@am__objects_1 =3D krb4.$(OBJEXT)
- at KRB5_TRUE@am__objects_2 =3D gssapi.$(OBJEXT) gss_userok.$(OBJEXT)
+	ls.c pathnames.h popen.c security.c kauth.c klist.c gssapi.c \
+	gss_userok.c
+ at KRB5_TRUE@am__objects_1 =3D gssapi.$(OBJEXT) gss_userok.$(OBJEXT)
 am_ftpd_OBJECTS =3D ftpcmd.$(OBJEXT) ftpd.$(OBJEXT) logwtmp.$(OBJEXT) \
 	ls.$(OBJEXT) popen.$(OBJEXT) security.$(OBJEXT) \
-	kauth.$(OBJEXT) klist.$(OBJEXT) $(am__objects_1) \
-	$(am__objects_2)
+	kauth.$(OBJEXT) klist.$(OBJEXT) $(am__objects_1)
 ftpd_OBJECTS =3D $(am_ftpd_OBJECTS)
 ftpd_LDADD =3D $(LDADD)
 am__DEPENDENCIES_1 =3D
@@ -112,9 +115,9 @@
 	$(LIB_gssapi) $(LIB_krb5) $(am__DEPENDENCIES_2) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -131,6 +134,27 @@
 YLWRAP =3D $(top_srcdir)/ylwrap
 SOURCES =3D $(ftpd_SOURCES) $(EXTRA_ftpd_SOURCES)
 DIST_SOURCES =3D $(am__ftpd_SOURCES_DIST) $(EXTRA_ftpd_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man5dir =3D $(mandir)/man5
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
@@ -141,49 +165,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -207,10 +240,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -227,6 +261,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -242,31 +278,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -281,10 +331,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -325,33 +377,37 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	-I$(srcdir)/../common $(INCLUDE_krb4) -DFTP_SERVER
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I$(srcdir)/../common $(INCLUDE_krb4) \
+	-DFTP_SERVER
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 CHECK_LOCAL =3D=20
- at KRB4_TRUE@krb4_sources =3D krb4.c
 @KRB5_TRUE at krb5_sources =3D gssapi.c gss_userok.c
 ftpd_SOURCES =3D \
 	extern.h	\
@@ -368,8 +424,8 @@
 	$(krb4_sources) \
 	$(krb5_sources)
=20
-EXTRA_ftpd_SOURCES =3D krb4.c kauth.c gssapi.c gss_userok.c
-CLEANFILES =3D security.c security.h krb4.c gssapi.c
+EXTRA_ftpd_SOURCES =3D kauth.c gssapi.c gss_userok.c
+CLEANFILES =3D security.c security.h gssapi.c
 man_MANS =3D ftpd.8 ftpusers.5
 LDADD =3D ../common/libcommon.a \
 	$(LIB_otp) \
@@ -380,23 +436,23 @@
 	$(LIB_hcrypto) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj=
 .y
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj .y
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/=
ftpd/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/ftp/ftpd/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/ftp/ftpd/Makefile';=
 \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/ftp/ftpd/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -414,34 +470,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 ftpd$(EXEEXT): $(ftpd_OBJECTS) $(ftpd_DEPENDENCIES)=20
 	@rm -f ftpd$(EXEEXT)
 	$(LINK) $(ftpd_OBJECTS) $(ftpd_LDADD) $(LIBS)
@@ -452,14 +524,37 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ftpcmd.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ftpd.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gss_userok.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gssapi.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kauth.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/klist.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/logwtmp.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ls.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/popen.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/security.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 .y.c:
 	$(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h $*.h y.output $*=
.output -- $(YACCCOMPILE)
@@ -469,146 +564,149 @@
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man5: $(man5_MANS) $(man_MANS)
+install-man5: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man5dir)" || $(MKDIR_P) "$(DESTDIR)$(man5dir)"
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man5:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
-install-man8: $(man8_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man5dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man5dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -624,13 +722,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -666,6 +768,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -677,6 +780,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -687,6 +791,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -694,26 +800,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man5 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -733,11 +848,10 @@
 uninstall-am: uninstall-libexecPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man5 uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libexecPROGRAMS clean-libtool ctags \
@@ -825,6 +939,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -910,7 +1027,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -930,10 +1047,9 @@
 	@test -f security.c || $(LN_S) $(srcdir)/../ftp/security.c .
 security.h:
 	@test -f security.h || $(LN_S) $(srcdir)/../ftp/security.h .
-krb4.c:
-	@test -f krb4.c || $(LN_S) $(srcdir)/../ftp/krb4.c .
 gssapi.c:
 	@test -f gssapi.c || $(LN_S) $(srcdir)/../ftp/gssapi.c .
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/exte=
rn.h
--- a/head/crypto/heimdal/appl/ftp/ftpd/extern.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/extern.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -63,7 +63,7 @@
 void	abor(void);
 void	blkfree(char **);
 char  **copyblk(char **);
-void	cwd(char *);
+void	cwd(const char *);
 void	do_delete(char *);
 void	dologout(int);
 void	eprt(char *);
@@ -129,6 +129,7 @@
 extern	int logged_in;
 extern	struct passwd *pw;
 extern	int guest;
+extern  int dochroot;
 extern	int logging;
 extern	int type;
 extern off_t file_size;
@@ -144,5 +145,6 @@
 extern	char proctitle[];
 extern	int usedefault;
 extern  char tmpline[];
+extern  int paranoid;
=20
 #endif /* _EXTERN_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/ftpc=
md.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/ftpcmd.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/ftpcmd.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -242,7 +242,7 @@
=20
=20
 #include "ftpd_locl.h"
-RCSID("$Id: ftpcmd.y 15677 2005-07-19 18:33:08Z lha $");
+RCSID("$Id$");
=20
 off_t	restart_point;
=20
@@ -665,16 +665,16 @@
 /* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
 static const yytype_uint16 yyrline[] =3D
 {
-       0,   129,   129,   131,   136,   140,   146,   153,   164,   170,
-     175,   180,   186,   223,   237,   251,   257,   263,   272,   281,
-     290,   295,   304,   309,   315,   322,   327,   334,   348,   353,
-     358,   365,   370,   387,   392,   399,   406,   411,   416,   426,
-     433,   438,   443,   451,   464,   478,   485,   502,   525,   530,
-     539,   552,   563,   576,   583,   588,   595,   613,   630,   658,
-     665,   671,   681,   691,   696,   701,   706,   711,   716,   721,
-     726,   734,   739,   742,   746,   750,   763,   767,   771,   778,
-     783,   788,   793,   798,   802,   807,   813,   821,   825,   829,
-     836,   840,   844,   851,   879,   883,   909,   917,   928
+       0,   129,   129,   131,   136,   140,   146,   154,   175,   181,
+     186,   191,   197,   234,   248,   262,   268,   274,   283,   292,
+     301,   306,   315,   320,   326,   333,   338,   345,   359,   364,
+     373,   380,   385,   402,   407,   414,   421,   426,   431,   441,
+     448,   453,   458,   466,   479,   493,   500,   517,   521,   526,
+     530,   534,   545,   558,   565,   570,   577,   595,   612,   640,
+     647,   653,   663,   673,   678,   683,   688,   693,   698,   703,
+     708,   716,   721,   724,   728,   732,   745,   749,   753,   760,
+     765,   770,   775,   780,   784,   789,   795,   803,   807,   811,
+     818,   822,   826,   833,   861,   865,   891,   899,   910
 };
 #endif
=20
@@ -1794,21 +1794,31 @@
     break;
=20
   case 7:
-#line 154 "ftpcmd.y"
+#line 155 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i)) {
-			usedefault =3D 0;
-			if (pdata >=3D 0) {
+			if (paranoid &&
+			    (data_dest->sa_family !=3D his_addr->sa_family ||
+			     (socket_get_port(data_dest) < IPPORT_RESERVED) ||
+			     memcmp(socket_get_address(data_dest),
+				    socket_get_address(his_addr),
+				    socket_addr_size(his_addr)) !=3D 0)) {
+			    usedefault =3D 1;
+			    reply(500, "Illegal PORT range rejected.");
+			} else {
+			    usedefault =3D 0;
+			    if (pdata >=3D 0) {
 				close(pdata);
 				pdata =3D -1;
+			    }
+			    reply(200, "PORT command successful.");
 			}
-			reply(200, "PORT command successful.");
 		    }
 		}
     break;
=20
   case 8:
-#line 165 "ftpcmd.y"
+#line 176 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i))
 			eprt ((yyvsp[(3) - (5)].s));
@@ -1817,7 +1827,7 @@
     break;
=20
   case 9:
-#line 171 "ftpcmd.y"
+#line 182 "ftpcmd.y"
     {
 		    if((yyvsp[(3) - (3)].i))
 			pasv ();
@@ -1825,7 +1835,7 @@
     break;
=20
   case 10:
-#line 176 "ftpcmd.y"
+#line 187 "ftpcmd.y"
     {
 		    if((yyvsp[(3) - (3)].i))
 			epsv (NULL);
@@ -1833,7 +1843,7 @@
     break;
=20
   case 11:
-#line 181 "ftpcmd.y"
+#line 192 "ftpcmd.y"
     {
 		    if((yyvsp[(5) - (5)].i))
 			epsv ((yyvsp[(3) - (5)].s));
@@ -1842,7 +1852,7 @@
     break;
=20
   case 12:
-#line 187 "ftpcmd.y"
+#line 198 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i)) {
 			switch (cmd_type) {
@@ -1882,7 +1892,7 @@
     break;
=20
   case 13:
-#line 224 "ftpcmd.y"
+#line 235 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i)) {
 			switch ((yyvsp[(3) - (5)].i)) {
@@ -1899,7 +1909,7 @@
     break;
=20
   case 14:
-#line 238 "ftpcmd.y"
+#line 249 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i)) {
 			switch ((yyvsp[(3) - (5)].i)) {
@@ -1916,7 +1926,7 @@
     break;
=20
   case 15:
-#line 252 "ftpcmd.y"
+#line 263 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i)) {
 			reply(202, "ALLO command ignored.");
@@ -1925,7 +1935,7 @@
     break;
=20
   case 16:
-#line 258 "ftpcmd.y"
+#line 269 "ftpcmd.y"
     {
 		    if ((yyvsp[(9) - (9)].i)) {
 			reply(202, "ALLO command ignored.");
@@ -1934,7 +1944,7 @@
     break;
=20
   case 17:
-#line 264 "ftpcmd.y"
+#line 275 "ftpcmd.y"
     {
 			char *name =3D (yyvsp[(3) - (5)].s);
=20
@@ -1946,7 +1956,7 @@
     break;
=20
   case 18:
-#line 273 "ftpcmd.y"
+#line 284 "ftpcmd.y"
     {
 			char *name =3D (yyvsp[(3) - (5)].s);
=20
@@ -1958,7 +1968,7 @@
     break;
=20
   case 19:
-#line 282 "ftpcmd.y"
+#line 293 "ftpcmd.y"
     {
 			char *name =3D (yyvsp[(3) - (5)].s);
=20
@@ -1970,7 +1980,7 @@
     break;
=20
   case 20:
-#line 291 "ftpcmd.y"
+#line 302 "ftpcmd.y"
     {
 			if ((yyvsp[(3) - (3)].i))
 				send_file_list(".");
@@ -1978,7 +1988,7 @@
     break;
=20
   case 21:
-#line 296 "ftpcmd.y"
+#line 307 "ftpcmd.y"
     {
 			char *name =3D (yyvsp[(3) - (5)].s);
=20
@@ -1990,7 +2000,7 @@
     break;
=20
   case 22:
-#line 305 "ftpcmd.y"
+#line 316 "ftpcmd.y"
     {
 		    if((yyvsp[(3) - (3)].i))
 			list_file(".");
@@ -1998,7 +2008,7 @@
     break;
=20
   case 23:
-#line 310 "ftpcmd.y"
+#line 321 "ftpcmd.y"
     {
 		    if((yyvsp[(5) - (5)].i))
 			list_file((yyvsp[(3) - (5)].s));
@@ -2007,7 +2017,7 @@
     break;
=20
   case 24:
-#line 316 "ftpcmd.y"
+#line 327 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL)
 				statfilecmd((yyvsp[(3) - (5)].s));
@@ -2017,7 +2027,7 @@
     break;
=20
   case 25:
-#line 323 "ftpcmd.y"
+#line 334 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i))
 			statcmd();
@@ -2025,7 +2035,7 @@
     break;
=20
   case 26:
-#line 328 "ftpcmd.y"
+#line 339 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL)
 				do_delete((yyvsp[(3) - (5)].s));
@@ -2035,7 +2045,7 @@
     break;
=20
   case 27:
-#line 335 "ftpcmd.y"
+#line 346 "ftpcmd.y"
     {
 			if((yyvsp[(5) - (5)].i)){
 				if (fromname) {
@@ -2052,7 +2062,7 @@
     break;
=20
   case 28:
-#line 349 "ftpcmd.y"
+#line 360 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i))
 			reply(225, "ABOR command successful.");
@@ -2060,15 +2070,19 @@
     break;
=20
   case 29:
-#line 354 "ftpcmd.y"
+#line 365 "ftpcmd.y"
     {
-			if ((yyvsp[(3) - (3)].i))
-				cwd(pw->pw_dir);
+			if ((yyvsp[(3) - (3)].i)) {
+				const char *path =3D pw->pw_dir;
+				if (dochroot || guest)
+					path =3D "/";
+				cwd(path);
+			}
 		}
     break;
=20
   case 30:
-#line 359 "ftpcmd.y"
+#line 374 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL)
 				cwd((yyvsp[(3) - (5)].s));
@@ -2078,7 +2092,7 @@
     break;
=20
   case 31:
-#line 366 "ftpcmd.y"
+#line 381 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i))
 			help(cmdtab, (char *) 0);
@@ -2086,7 +2100,7 @@
     break;
=20
   case 32:
-#line 371 "ftpcmd.y"
+#line 386 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i)) {
 			char *cp =3D (yyvsp[(3) - (5)].s);
@@ -2106,7 +2120,7 @@
     break;
=20
   case 33:
-#line 388 "ftpcmd.y"
+#line 403 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i))
 			reply(200, "NOOP command successful.");
@@ -2114,7 +2128,7 @@
     break;
=20
   case 34:
-#line 393 "ftpcmd.y"
+#line 408 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL)
 				makedir((yyvsp[(3) - (5)].s));
@@ -2124,7 +2138,7 @@
     break;
=20
   case 35:
-#line 400 "ftpcmd.y"
+#line 415 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL)
 				removedir((yyvsp[(3) - (5)].s));
@@ -2134,7 +2148,7 @@
     break;
=20
   case 36:
-#line 407 "ftpcmd.y"
+#line 422 "ftpcmd.y"
     {
 			if ((yyvsp[(3) - (3)].i))
 				pwd();
@@ -2142,7 +2156,7 @@
     break;
=20
   case 37:
-#line 412 "ftpcmd.y"
+#line 427 "ftpcmd.y"
     {
 			if ((yyvsp[(3) - (3)].i))
 				cwd("..");
@@ -2150,7 +2164,7 @@
     break;
=20
   case 38:
-#line 417 "ftpcmd.y"
+#line 432 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i)) {
 			lreply(211, "Supported features:");
@@ -2163,7 +2177,7 @@
     break;
=20
   case 39:
-#line 427 "ftpcmd.y"
+#line 442 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i))
 			reply(501, "Bad options");
@@ -2172,7 +2186,7 @@
     break;
=20
   case 40:
-#line 434 "ftpcmd.y"
+#line 449 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i))
 			help(sitetab, (char *) 0);
@@ -2180,7 +2194,7 @@
     break;
=20
   case 41:
-#line 439 "ftpcmd.y"
+#line 454 "ftpcmd.y"
     {
 		    if ((yyvsp[(7) - (7)].i))
 			help(sitetab, (yyvsp[(5) - (7)].s));
@@ -2188,7 +2202,7 @@
     break;
=20
   case 42:
-#line 444 "ftpcmd.y"
+#line 459 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i)) {
 				int oldmask =3D umask(0);
@@ -2199,7 +2213,7 @@
     break;
=20
   case 43:
-#line 452 "ftpcmd.y"
+#line 467 "ftpcmd.y"
     {
 			if ((yyvsp[(7) - (7)].i)) {
 				if (((yyvsp[(5) - (7)].i) =3D=3D -1) || ((yyvsp[(5) - (7)].i) > 0777))=
 {
@@ -2215,7 +2229,7 @@
     break;
=20
   case 44:
-#line 465 "ftpcmd.y"
+#line 480 "ftpcmd.y"
     {
 			if ((yyvsp[(9) - (9)].i) && (yyvsp[(7) - (9)].s) !=3D NULL) {
 				if ((yyvsp[(5) - (9)].i) > 0777)
@@ -2232,7 +2246,7 @@
     break;
=20
   case 45:
-#line 479 "ftpcmd.y"
+#line 494 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i))
 			reply(200,
@@ -2242,7 +2256,7 @@
     break;
=20
   case 46:
-#line 486 "ftpcmd.y"
+#line 501 "ftpcmd.y"
     {
 		    if ((yyvsp[(7) - (7)].i)) {
 			if ((yyvsp[(5) - (7)].i) < 30 || (yyvsp[(5) - (7)].i) > maxtimeout) {
@@ -2261,33 +2275,14 @@
     break;
=20
   case 47:
-#line 503 "ftpcmd.y"
+#line 518 "ftpcmd.y"
     {
-#ifdef KRB4
-			char *p;
-		=09
-			if(guest)
-				reply(500, "Can't be done as guest.");
-			else{
-				if((yyvsp[(7) - (7)].i) && (yyvsp[(5) - (7)].s) !=3D NULL){
-				    p =3D strpbrk((yyvsp[(5) - (7)].s), " \t");
-				    if(p){
-					*p++ =3D 0;
-					kauth((yyvsp[(5) - (7)].s), p + strspn(p, " \t"));
-				    }else
-					kauth((yyvsp[(5) - (7)].s), NULL);
-				}
-			}
-			if((yyvsp[(5) - (7)].s) !=3D NULL)
-			    free((yyvsp[(5) - (7)].s));
-#else
 			reply(500, "Command not implemented.");
-#endif
 		}
     break;
=20
   case 48:
-#line 526 "ftpcmd.y"
+#line 522 "ftpcmd.y"
     {
 		    if((yyvsp[(5) - (5)].i))
 			klist();
@@ -2295,37 +2290,23 @@
     break;
=20
   case 49:
+#line 527 "ftpcmd.y"
+    {
+		    reply(500, "Command not implemented.");
+		}
+    break;
+
+  case 50:
 #line 531 "ftpcmd.y"
     {
-#ifdef KRB4
-		    if((yyvsp[(5) - (5)].i))
-			kdestroy();
-#else
 		    reply(500, "Command not implemented.");
-#endif
 		}
     break;
=20
-  case 50:
-#line 540 "ftpcmd.y"
+  case 51:
+#line 535 "ftpcmd.y"
     {
-#ifdef KRB4
-		    if(guest)
-			reply(500, "Can't be done as guest.");
-		    else if((yyvsp[(7) - (7)].i) && (yyvsp[(5) - (7)].s))
-			krbtkfile((yyvsp[(5) - (7)].s));
-		    if((yyvsp[(5) - (7)].s))
-			free((yyvsp[(5) - (7)].s));
-#else
-		    reply(500, "Command not implemented.");
-#endif
-		}
-    break;
-
-  case 51:
-#line 553 "ftpcmd.y"
-    {
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 		    if(guest)
 			reply(500, "Can't be done as guest.");
 		    else if((yyvsp[(5) - (5)].i))
@@ -2337,9 +2318,9 @@
     break;
=20
   case 52:
-#line 564 "ftpcmd.y"
+#line 546 "ftpcmd.y"
     {
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 		    if(guest)
 			reply(500, "Can't be done as guest.");
 		    else if((yyvsp[(7) - (7)].i))
@@ -2353,7 +2334,7 @@
     break;
=20
   case 53:
-#line 577 "ftpcmd.y"
+#line 559 "ftpcmd.y"
     {
 		    if((yyvsp[(7) - (7)].i) && (yyvsp[(5) - (7)].s) !=3D NULL)
 			find((yyvsp[(5) - (7)].s));
@@ -2363,7 +2344,7 @@
     break;
=20
   case 54:
-#line 584 "ftpcmd.y"
+#line 566 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i))
 			reply(200, "http://www.pdc.kth.se/heimdal/");
@@ -2371,7 +2352,7 @@
     break;
=20
   case 55:
-#line 589 "ftpcmd.y"
+#line 571 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL)
 				do_store((yyvsp[(3) - (5)].s), "w", 1);
@@ -2381,7 +2362,7 @@
     break;
=20
   case 56:
-#line 596 "ftpcmd.y"
+#line 578 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i)) {
 #if !defined(WIN32) && !defined(__EMX__) && !defined(__OS2__) && !defined(=
__CYGWIN32__)
@@ -2394,7 +2375,7 @@
     break;
=20
   case 57:
-#line 614 "ftpcmd.y"
+#line 596 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL)
 				sizecmd((yyvsp[(3) - (5)].s));
@@ -2404,7 +2385,7 @@
     break;
=20
   case 58:
-#line 631 "ftpcmd.y"
+#line 613 "ftpcmd.y"
     {
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s) !=3D NULL) {
 				struct stat stbuf;
@@ -2435,7 +2416,7 @@
     break;
=20
   case 59:
-#line 659 "ftpcmd.y"
+#line 641 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i)) {
 			reply(221, "Goodbye.");
@@ -2445,14 +2426,14 @@
     break;
=20
   case 60:
-#line 666 "ftpcmd.y"
+#line 648 "ftpcmd.y"
     {
 			yyerrok;
 		}
     break;
=20
   case 61:
-#line 672 "ftpcmd.y"
+#line 654 "ftpcmd.y"
     {
 			restart_point =3D (off_t) 0;
 			if ((yyvsp[(5) - (5)].i) && (yyvsp[(3) - (5)].s)) {
@@ -2465,7 +2446,7 @@
     break;
=20
   case 62:
-#line 682 "ftpcmd.y"
+#line 664 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i)) {
 			fromname =3D (char *) 0;
@@ -2478,7 +2459,7 @@
     break;
=20
   case 63:
-#line 692 "ftpcmd.y"
+#line 674 "ftpcmd.y"
     {
 			auth((yyvsp[(3) - (4)].s));
 			free((yyvsp[(3) - (4)].s));
@@ -2486,7 +2467,7 @@
     break;
=20
   case 64:
-#line 697 "ftpcmd.y"
+#line 679 "ftpcmd.y"
     {
 			adat((yyvsp[(3) - (4)].s));
 			free((yyvsp[(3) - (4)].s));
@@ -2494,7 +2475,7 @@
     break;
=20
   case 65:
-#line 702 "ftpcmd.y"
+#line 684 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i))
 			pbsz((yyvsp[(3) - (5)].i));
@@ -2502,7 +2483,7 @@
     break;
=20
   case 66:
-#line 707 "ftpcmd.y"
+#line 689 "ftpcmd.y"
     {
 		    if ((yyvsp[(5) - (5)].i))
 			prot((yyvsp[(3) - (5)].s));
@@ -2510,7 +2491,7 @@
     break;
=20
   case 67:
-#line 712 "ftpcmd.y"
+#line 694 "ftpcmd.y"
     {
 		    if ((yyvsp[(3) - (3)].i))
 			ccc();
@@ -2518,7 +2499,7 @@
     break;
=20
   case 68:
-#line 717 "ftpcmd.y"
+#line 699 "ftpcmd.y"
     {
 			mec((yyvsp[(3) - (4)].s), prot_safe);
 			free((yyvsp[(3) - (4)].s));
@@ -2526,7 +2507,7 @@
     break;
=20
   case 69:
-#line 722 "ftpcmd.y"
+#line 704 "ftpcmd.y"
     {
 			mec((yyvsp[(3) - (4)].s), prot_confidential);
 			free((yyvsp[(3) - (4)].s));
@@ -2534,7 +2515,7 @@
     break;
=20
   case 70:
-#line 727 "ftpcmd.y"
+#line 709 "ftpcmd.y"
     {
 			mec((yyvsp[(3) - (4)].s), prot_private);
 			free((yyvsp[(3) - (4)].s));
@@ -2542,47 +2523,47 @@
     break;
=20
   case 72:
-#line 739 "ftpcmd.y"
+#line 721 "ftpcmd.y"
     {
 			(yyval.s) =3D (char *)calloc(1, sizeof(char));
 		}
     break;
=20
   case 75:
-#line 752 "ftpcmd.y"
+#line 734 "ftpcmd.y"
     {
 			struct sockaddr_in *sin4 =3D (struct sockaddr_in *)data_dest;
=20
 			sin4->sin_family =3D AF_INET;
 			sin4->sin_port =3D htons((yyvsp[(9) - (11)].i) * 256 + (yyvsp[(11) - (1=
1)].i));
-			sin4->sin_addr.s_addr =3D=20
+			sin4->sin_addr.s_addr =3D
 			    htonl(((yyvsp[(1) - (11)].i) << 24) | ((yyvsp[(3) - (11)].i) << 16)=
 | ((yyvsp[(5) - (11)].i) << 8) | (yyvsp[(7) - (11)].i));
 		}
     break;
=20
   case 76:
-#line 764 "ftpcmd.y"
+#line 746 "ftpcmd.y"
     {
 			(yyval.i) =3D FORM_N;
 		}
     break;
=20
   case 77:
-#line 768 "ftpcmd.y"
+#line 750 "ftpcmd.y"
     {
 			(yyval.i) =3D FORM_T;
 		}
     break;
=20
   case 78:
-#line 772 "ftpcmd.y"
+#line 754 "ftpcmd.y"
     {
 			(yyval.i) =3D FORM_C;
 		}
     break;
=20
   case 79:
-#line 779 "ftpcmd.y"
+#line 761 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_A;
 			cmd_form =3D FORM_N;
@@ -2590,7 +2571,7 @@
     break;
=20
   case 80:
-#line 784 "ftpcmd.y"
+#line 766 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_A;
 			cmd_form =3D (yyvsp[(3) - (3)].i);
@@ -2598,7 +2579,7 @@
     break;
=20
   case 81:
-#line 789 "ftpcmd.y"
+#line 771 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_E;
 			cmd_form =3D FORM_N;
@@ -2606,7 +2587,7 @@
     break;
=20
   case 82:
-#line 794 "ftpcmd.y"
+#line 776 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_E;
 			cmd_form =3D (yyvsp[(3) - (3)].i);
@@ -2614,14 +2595,14 @@
     break;
=20
   case 83:
-#line 799 "ftpcmd.y"
+#line 781 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_I;
 		}
     break;
=20
   case 84:
-#line 803 "ftpcmd.y"
+#line 785 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_L;
 			cmd_bytesz =3D NBBY;
@@ -2629,7 +2610,7 @@
     break;
=20
   case 85:
-#line 808 "ftpcmd.y"
+#line 790 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_L;
 			cmd_bytesz =3D (yyvsp[(3) - (3)].i);
@@ -2637,7 +2618,7 @@
     break;
=20
   case 86:
-#line 814 "ftpcmd.y"
+#line 796 "ftpcmd.y"
     {
 			cmd_type =3D TYPE_L;
 			cmd_bytesz =3D (yyvsp[(2) - (2)].i);
@@ -2645,49 +2626,49 @@
     break;
=20
   case 87:
-#line 822 "ftpcmd.y"
+#line 804 "ftpcmd.y"
     {
 			(yyval.i) =3D STRU_F;
 		}
     break;
=20
   case 88:
-#line 826 "ftpcmd.y"
+#line 808 "ftpcmd.y"
     {
 			(yyval.i) =3D STRU_R;
 		}
     break;
=20
   case 89:
-#line 830 "ftpcmd.y"
+#line 812 "ftpcmd.y"
     {
 			(yyval.i) =3D STRU_P;
 		}
     break;
=20
   case 90:
-#line 837 "ftpcmd.y"
+#line 819 "ftpcmd.y"
     {
 			(yyval.i) =3D MODE_S;
 		}
     break;
=20
   case 91:
-#line 841 "ftpcmd.y"
+#line 823 "ftpcmd.y"
     {
 			(yyval.i) =3D MODE_B;
 		}
     break;
=20
   case 92:
-#line 845 "ftpcmd.y"
+#line 827 "ftpcmd.y"
     {
 			(yyval.i) =3D MODE_C;
 		}
     break;
=20
   case 93:
-#line 852 "ftpcmd.y"
+#line 834 "ftpcmd.y"
     {
 			/*
 			 * Problem: this production is used for all pathname
@@ -2715,7 +2696,7 @@
     break;
=20
   case 95:
-#line 884 "ftpcmd.y"
+#line 866 "ftpcmd.y"
     {
 			int ret, dec, multby, digit;
=20
@@ -2741,7 +2722,7 @@
     break;
=20
   case 96:
-#line 910 "ftpcmd.y"
+#line 892 "ftpcmd.y"
     {
 			(yyval.i) =3D (yyvsp[(1) - (1)].i) && !guest;
 			if((yyvsp[(1) - (1)].i) && !(yyval.i))
@@ -2750,7 +2731,7 @@
     break;
=20
   case 97:
-#line 918 "ftpcmd.y"
+#line 900 "ftpcmd.y"
     {
 		    if((yyvsp[(1) - (1)].i)) {
 			if(((yyval.i) =3D logged_in) =3D=3D 0)
@@ -2761,7 +2742,7 @@
     break;
=20
   case 98:
-#line 928 "ftpcmd.y"
+#line 910 "ftpcmd.y"
     {
 		    (yyval.i) =3D 1;
 		    if(sec_complete && !ccc_passed && !secure_command()) {
@@ -2774,7 +2755,7 @@
=20
=20
 /* Line 1267 of yacc.c.  */
-#line 2778 "ftpcmd.c"
+#line 2759 "ftpcmd.c"
       default: break;
     }
   YY_SYMBOL_PRINT ("-> $$ =3D", yyr1[yyn], &yyval, &yyloc);
@@ -2988,7 +2969,7 @@
 }
=20
=20
-#line 938 "ftpcmd.y"
+#line 920 "ftpcmd.y"
=20
=20
 #define	CMD	0	/* beginning of command */
@@ -3085,7 +3066,7 @@
 	{ "FIND", LOCATE, STR1, 1,	"<sp> globexpr" },
=20
 	{ "URL",  URL,  ARGS, 1,	"?" },
-=09
+
 	{ NULL,   0,    0,    0,	0 }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/ftpc=
md.y
--- a/head/crypto/heimdal/appl/ftp/ftpd/ftpcmd.y	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/ftpcmd.y	Tue Apr 17 11:51:51 2012 +=
0300
@@ -43,7 +43,7 @@
 %{
=20
 #include "ftpd_locl.h"
-RCSID("$Id: ftpcmd.y 15677 2005-07-19 18:33:08Z lha $");
+RCSID("$Id$");
=20
 off_t	restart_point;
=20
@@ -150,15 +150,26 @@
 		    memset ($3, 0, strlen($3));
 		    free($3);
 		}
+
 	| PORT SP host_port CRLF check_secure
 		{
 		    if ($5) {
-			usedefault =3D 0;
-			if (pdata >=3D 0) {
+			if (paranoid &&
+			    (data_dest->sa_family !=3D his_addr->sa_family ||
+			     (socket_get_port(data_dest) < IPPORT_RESERVED) ||
+			     memcmp(socket_get_address(data_dest),
+				    socket_get_address(his_addr),
+				    socket_addr_size(his_addr)) !=3D 0)) {
+			    usedefault =3D 1;
+			    reply(500, "Illegal PORT range rejected.");
+			} else {
+			    usedefault =3D 0;
+			    if (pdata >=3D 0) {
 				close(pdata);
 				pdata =3D -1;
+			    }
+			    reply(200, "PORT command successful.");
 			}
-			reply(200, "PORT command successful.");
 		    }
 		}
 	| EPRT SP STRING CRLF check_secure
@@ -352,8 +363,12 @@
 		}
 	| CWD CRLF check_login
 		{
-			if ($3)
-				cwd(pw->pw_dir);
+			if ($3) {
+				const char *path =3D pw->pw_dir;
+				if (dochroot || guest)
+					path =3D "/";
+				cwd(path);
+			}
 		}
 	| CWD SP pathname CRLF check_login
 		{
@@ -501,26 +516,7 @@
=20
 	| SITE SP KAUTH SP STRING CRLF check_login
 		{
-#ifdef KRB4
-			char *p;
-		=09
-			if(guest)
-				reply(500, "Can't be done as guest.");
-			else{
-				if($7 && $5 !=3D NULL){
-				    p =3D strpbrk($5, " \t");
-				    if(p){
-					*p++ =3D 0;
-					kauth($5, p + strspn(p, " \t"));
-				    }else
-					kauth($5, NULL);
-				}
-			}
-			if($5 !=3D NULL)
-			    free($5);
-#else
 			reply(500, "Command not implemented.");
-#endif
 		}
 	| SITE SP KLIST CRLF check_login
 		{
@@ -529,29 +525,15 @@
 		}
 	| SITE SP KDESTROY CRLF check_login
 		{
-#ifdef KRB4
-		    if($5)
-			kdestroy();
-#else
 		    reply(500, "Command not implemented.");
-#endif
 		}
 	| SITE SP KRBTKFILE SP STRING CRLF check_login
 		{
-#ifdef KRB4
-		    if(guest)
-			reply(500, "Can't be done as guest.");
-		    else if($7 && $5)
-			krbtkfile($5);
-		    if($5)
-			free($5);
-#else
 		    reply(500, "Command not implemented.");
-#endif
 		}
 	| SITE SP AFSLOG CRLF check_login
 		{
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 		    if(guest)
 			reply(500, "Can't be done as guest.");
 		    else if($5)
@@ -562,7 +544,7 @@
 		}
 	| SITE SP AFSLOG SP STRING CRLF check_login
 		{
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 		    if(guest)
 			reply(500, "Can't be done as guest.");
 		    else if($7)
@@ -754,7 +736,7 @@
=20
 			sin4->sin_family =3D AF_INET;
 			sin4->sin_port =3D htons($9 * 256 + $11);
-			sin4->sin_addr.s_addr =3D=20
+			sin4->sin_addr.s_addr =3D
 			    htonl(($1 << 24) | ($3 << 16) | ($5 << 8) | $7);
 		}
 	;
@@ -1031,7 +1013,7 @@
 	{ "FIND", LOCATE, STR1, 1,	"<sp> globexpr" },
=20
 	{ "URL",  URL,  ARGS, 1,	"?" },
-=09
+
 	{ NULL,   0,    0,    0,	0 }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/ftpd=
.8
--- a/head/crypto/heimdal/appl/ftp/ftpd/ftpd.8	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/ftp/ftpd/ftpd.8	Tue Apr 17 11:51:51 2012 +03=
00
@@ -47,11 +47,11 @@
 .Op Fl p Ar port
 .Op Fl T Ar maxtimeout
 .Op Fl t Ar timeout
-.Op Fl -gss-bindings
-.Op Fl I | Fl -no-insecure-oob
+.Op Fl Fl gss-bindings
+.Op Fl I | Fl Fl no-insecure-oob
 .Op Fl u Ar default umask
-.Op Fl B | Fl -builtin-ls
-.Op Fl -good-chars=3D Ns Ar string
+.Op Fl B | Fl Fl builtin-ls
+.Op Fl Fl good-chars=3D Ns Ar string
 .Sh DESCRIPTION
 .Nm Ftpd
 is the
@@ -101,7 +101,7 @@
 .It Fl g
 Anonymous users will get a umask of
 .Ar umask .
-.It Fl -gss-bindings
+.It Fl Fl gss-bindings
 require the peer to use GSS-API bindings (ie make sure IP addresses match).
 .It Fl i
 Open a socket and wait for a connection. This is mainly used for
@@ -144,16 +144,16 @@
 Verbose mode.
 .It Xo
 .Fl B ,
-.Fl -builtin-ls
+.Fl Fl builtin-ls
 .Xc
 use built-in ls to list files
 .It Xo
-.Fl -good-chars=3D Ns Ar string
+.Fl Fl good-chars=3D Ns Ar string
 .Xc
 allowed anonymous upload filename chars
 .It Xo
 .Fl I
-.Fl -no-insecure-oob
+.Fl Fl no-insecure-oob
 .Xc
 don't allow insecure out of band.
 Heimdal ftp clients before 0.6.3 doesn't support secure oob, so turning
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/ftpd=
.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/ftpd.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/ftp/ftpd/ftpd.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -38,7 +38,7 @@
 #endif
 #include "getarg.h"
=20
-RCSID("$Id: ftpd.c 21222 2007-06-20 10:11:14Z lha $");
+RCSID("$Id$");
=20
 static char version[] =3D "Version 6.00";
=20
@@ -91,6 +91,7 @@
 char	hostname[MaxHostNameLen];
 char	remotehost[MaxHostNameLen];
 static char ttyline[20];
+int     paranoid =3D 1;
=20
 #define AUTH_PLAIN	(1 << 0) /* allow sending passwords */
 #define AUTH_OTP	(1 << 1) /* passwords are one-time */
@@ -190,7 +191,7 @@
 	else
 	    warnx("bad value for -a: `%s'", p);
     }
-    return ret;	   =20
+    return ret;
 }
=20
 /*
@@ -225,7 +226,7 @@
     { "builtin-ls", 'B', arg_flag, &use_builtin_ls, "use built-in ls to li=
st files" },
     { "good-chars", 0, arg_string, &good_chars, "allowed anonymous upload =
filename chars" },
     { "insecure-oob", 'I', arg_negative_flag, &allow_insecure_oob, "don't =
allow insecure OOB ABOR/STAT" },
-#ifdef KRB5   =20
+#ifdef KRB5
     { "gss-bindings", 0,  arg_flag, &ftp_do_gss_bindings, "Require GSS-API=
 bindings", NULL},
 #endif
     { "version", 0, arg_flag, &version_flag },
@@ -271,22 +272,12 @@
=20
     setprogname (argv[0]);
=20
-    /* detach from any tickets and tokens */
-    {
-#ifdef KRB4
-	char tkfile[1024];
-	snprintf(tkfile, sizeof(tkfile),
-		 "/tmp/ftp_%u", (unsigned)getpid());
-	krb_set_tkt_string(tkfile);
-#endif
-    }
-
     if(getarg(args, num_args, argc, argv, &optind))
 	usage(1);
=20
     if(help_flag)
 	usage(0);
-=09
+
     if(version_flag) {
 	print_version(NULL);
 	exit(0);
@@ -297,7 +288,7 @@
     {
 	char *p;
 	long val =3D 0;
-	   =20
+
 	if(guest_umask_string) {
 	    val =3D strtol(guest_umask_string, &p, 8);
 	    if (*p !=3D '\0' || val < 0)
@@ -328,7 +319,7 @@
 	    else
 		warnx("bad value for -p");
     }
-		   =20
+
     if (maxtimeout < ftpd_timeout)
 	maxtimeout =3D ftpd_timeout;
=20
@@ -338,7 +329,7 @@
 #endif
=20
     if(interactive_flag)
-	mini_inetd (port);
+	mini_inetd(port, NULL);
=20
     /*
      * LOG_NDELAY sets up the logging connection immediately,
@@ -355,14 +346,9 @@
 	syslog(LOG_ERR, "getsockname (%s): %m",argv[0]);
 	exit(1);
     }
-#if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
-    {
-	int tos =3D IPTOS_LOWDELAY;
-
-	if (setsockopt(STDIN_FILENO, IPPROTO_IP, IP_TOS,
-		       (void *)&tos, sizeof(int)) < 0)
-	    syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
-    }
+#if defined(IP_TOS)
+    if (ctrl_addr->sa_family =3D=3D AF_INET)
+	socket_set_tos(STDIN_FILENO, IP_TOS);
 #endif
     data_source->sa_family =3D ctrl_addr->sa_family;
     socket_set_port (data_source,
@@ -410,21 +396,15 @@
     show_file(_PATH_FTPWELCOME, 220);
     /* reply(220,) must follow */
     gethostname(hostname, sizeof(hostname));
-=09
+
     reply(220, "%s FTP server (%s"
 #ifdef KRB5
 	  "+%s"
 #endif
-#ifdef KRB4
-	  "+%s"
-#endif
 	  ") ready.", hostname, version
 #ifdef KRB5
 	  ,heimdal_version
 #endif
-#ifdef KRB4
-	  ,krb4_version
-#endif
 	  );
=20
     for (;;)
@@ -528,7 +508,7 @@
 	guest =3D 0;
 	if (strcmp(name, "ftp") =3D=3D 0 || strcmp(name, "anonymous") =3D=3D 0) {
 	    if ((auth_level & AUTH_FTP) =3D=3D 0 ||
-		checkaccess("ftp") ||=20
+		checkaccess("ftp") ||
 		checkaccess("anonymous"))
 		reply(530, "User %s access denied.", name);
 	    else if ((pw =3D sgetpwnam("ftp")) !=3D NULL) {
@@ -661,7 +641,7 @@
=20
=20
 /*
- * Determine whether a user has access, based on information in=20
+ * Determine whether a user has access, based on information in
  * _PATH_FTPUSERS. The users are listed one per line, with `allow'
  * or `deny' after the username. If anything other than `allow', or
  * just nothing, is given after the username, `deny' is assumed.
@@ -689,9 +669,9 @@
     int allowed =3D ALLOWED;
     char *user, *perm, line[BUFSIZ];
     char *foo;
-   =20
+
     fd =3D fopen(_PATH_FTPUSERS, "r");
-   =20
+
     if(fd =3D=3D NULL)
 	return allowed;
=20
@@ -724,7 +704,7 @@
 	return -1;
     }
     initgroups(pw->pw_name, pw->pw_gid);
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
     if(k_hasafs())
 	k_setpag();
 #endif
@@ -799,7 +779,7 @@
 				 sizeof(data_addr));
=20
 	    syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s(%s), %s",
-		   remotehost,=20
+		   remotehost,
 		   data_addr,
 		   passwd);
 	}
@@ -850,11 +830,11 @@
 static int
 krb5_verify(struct passwd *pwd, char *passwd)
 {
-   krb5_context context; =20
+   krb5_context context;
    krb5_ccache  id;
    krb5_principal princ;
    krb5_error_code ret;
- =20
+
    ret =3D krb5_init_context(&context);
    if(ret)
         return ret;
@@ -864,7 +844,7 @@
         krb5_free_context(context);
         return ret;
   }
-  ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &id);
+  ret =3D krb5_cc_new_unique(context, "MEMORY", NULL, &id);
   if(ret){
         krb5_free_principal(context, princ);
         krb5_free_context(context);
@@ -882,7 +862,7 @@
   }
   krb5_cc_destroy(context, id);
   krb5_free_context (context);
-  if(ret)=20
+  if(ret)
       return ret;
   return 0;
 }
@@ -917,21 +897,6 @@
 #ifdef KRB5
 		    rval =3D krb5_verify(pw, passwd);
 #endif
-#ifdef KRB4
-		    if (rval) {
-			char realm[REALM_SZ];
-			if((rval =3D krb_get_lrealm(realm, 1)) =3D=3D KSUCCESS)
-			    rval =3D krb_verify_user(pw->pw_name,
-						   "", realm,=20
-						   passwd,=20
-						   KRB_VERIFY_SECURE, NULL);
-			if (rval =3D=3D KSUCCESS ) {
-			    chown (tkt_string(), pw->pw_uid, pw->pw_gid);
-			    if(k_hasafs())
-				krb_afslog(0, 0);
-			}
-		    }
-#endif
 		    if (rval)
 			rval =3D unix_verify_user(pw->pw_name, passwd);
 		} else {
@@ -977,7 +942,7 @@
 	}
 	if(!do_login(230, passwd))
 	  return;
-=09
+
 	/* Forget all about it... */
 	end_login();
 }
@@ -1013,7 +978,7 @@
 		    for(p =3D cmds; p->ext; p++){
 			char *tail =3D name + strlen(name) - strlen(p->ext);
 			char c =3D *tail;
-		=09
+
 			if(strcmp(tail, p->ext) =3D=3D 0 &&
 			   (*tail  =3D 0) =3D=3D 0 &&
 			   access(name, R_OK) =3D=3D 0){
@@ -1037,7 +1002,7 @@
 			        free(ext);
 			    }
 			}
-		=09
+
 		    }
 		    if(p->ext){
 			fin =3D ftpd_popen(line, "r", 0, 0);
@@ -1106,7 +1071,7 @@
=20
 /* filename sanity check */
=20
-int=20
+int
 filename_check(char *filename)
 {
     char *p;
@@ -1127,7 +1092,7 @@
     lreply(553, "\"%s\" is not an acceptable filename.", filename);
     lreply(553, "The filename must start with an alphanumeric "
 	   "character and must only");
-    reply(553, "consist of alphanumeric characters or any of the following=
: %s",=20
+    reply(553, "consist of alphanumeric characters or any of the following=
: %s",
 	  good_chars);
     return 1;
 }
@@ -1141,10 +1106,14 @@
=20
 	if(guest && filename_check(name))
 	    return;
-	if (unique && stat(name, &st) =3D=3D 0 &&
-	    (name =3D gunique(name)) =3D=3D NULL) {
-		LOGCMD(*mode =3D=3D 'w' ? "put" : "append", name);
-		return;
+	if (unique) {
+	    char *uname;
+	    if (stat(name, &st) =3D=3D 0) {
+		if ((uname =3D gunique(name)) =3D=3D NULL)
+		    return;
+		name =3D uname;
+	    }
+	    LOGCMD(*mode =3D=3D 'w' ? "put" : "append", name);
 	}
=20
 	if (restart_point)
@@ -1252,7 +1221,7 @@
 }
=20
 static int
-accept_with_timeout(int socket,=20
+accept_with_timeout(int socket,
 		    struct sockaddr *address,
 		    socklen_t *address_len,
 		    struct timeval *timeout)
@@ -1302,13 +1271,9 @@
 		}
 		close(pdata);
 		pdata =3D s;
-#if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
-		{
-		    int tos =3D IPTOS_THROUGHPUT;
-		   =20
-		    setsockopt(s, IPPROTO_IP, IP_TOS, (void *)&tos,
-			       sizeof(tos));
-		}
+#if defined(IPTOS_THROUGHPUT)
+		if (from->sa_family =3D=3D AF_INET)
+		    socket_set_tos(s, IPTOS_THROUGHPUT);
 #endif
 		reply(150, "Opening %s mode data connection for '%s'%s.",
 		     type =3D=3D TYPE_A ? "ASCII" : "BINARY", name, sizebuf);
@@ -1323,7 +1288,7 @@
 	if (usedefault)
 		data_dest =3D his_addr;
 	usedefault =3D 1;
-	/*=20
+	/*
 	 * Default to using the same socket type as the ctrl address,
 	 * unless we know the type of the data address.
 	 */
@@ -1399,7 +1364,7 @@
 		goto data_err;
 	    reply(226, "Transfer complete.");
 	    return;
-	=09
+
 	case TYPE_I:
 	case TYPE_L:
 #if 0 /* XXX handle urg flag */
@@ -1411,7 +1376,7 @@
 		struct stat st;
 		char *chunk;
 		int in =3D fileno(instr);
-		if(fstat(in, &st) =3D=3D 0 && S_ISREG(st.st_mode)=20
+		if(fstat(in, &st) =3D=3D 0 && S_ISREG(st.st_mode)
 		   && st.st_size > 0) {
 		    /*
 		     * mmap zero bytes has potential of loosing, don't do it.
@@ -1505,7 +1470,7 @@
 	perror_reply(451, "Local resource failure: malloc");
 	return -1;
     }
-   =20
+
     switch (type) {
=20
     case TYPE_I:
@@ -1534,7 +1499,7 @@
 	char *p, *q;
 	int cr_flag =3D 0;
 	while ((cnt =3D sec_read(fileno(instr),
-				buf + cr_flag,=20
+				buf + cr_flag,
 				bufsize - cr_flag)) > 0){
 	    if (urgflag && handleoobcmd())
 		return (-1);
@@ -1583,13 +1548,13 @@
 	urgflag =3D 0;
 	return (-1);
     }
-=09
+
 data_err:
     transflag =3D 0;
     urgflag =3D 0;
     perror_reply(426, "Data Connection");
     return (-1);
-=09
+
 file_err:
     transflag =3D 0;
     urgflag =3D 0;
@@ -1772,7 +1737,7 @@
 		perror_reply(550, name);
 		return;
 	}
-	if ((st.st_mode&S_IFMT) =3D=3D S_IFDIR) {
+	if (S_ISDIR(st.st_mode)) {
 		if (rmdir(name) < 0) {
 			perror_reply(550, name);
 			return;
@@ -1788,7 +1753,7 @@
 }
=20
 void
-cwd(char *path)
+cwd(const char *path)
 {
=20
 	if (chdir(path) < 0)
@@ -1831,7 +1796,7 @@
     char *ret;
=20
     /* SunOS has a broken getcwd that does popen(pwd) (!!!), this
-     * failes miserably when running chroot=20
+     * failes miserably when running chroot
      */
     ret =3D getcwd(path, sizeof(path));
     if (ret =3D=3D NULL)
@@ -1902,7 +1867,7 @@
     transflag =3D 0;
     urgflag =3D 0;
     if (logged_in) {
-#if KRB4 || KRB5
+#if KRB5
 	cond_kdestroy();
 #endif
 	seteuid((uid_t)0); /* No need to check, we call exit() below */
@@ -1913,7 +1878,7 @@
     exit(status);
 #else
     _exit(status);
-#endif=09
+#endif
 }
=20
 void abor(void)
@@ -2017,8 +1982,8 @@
 	socket_set_address_and_port (pasv_addr,
 				     socket_get_address (ctrl_addr),
 				     0);
-	socket_set_portrange(pdata, restricted_data_ports,=20
-	    pasv_addr->sa_family);=20
+	socket_set_portrange(pdata, restricted_data_ports,
+	    pasv_addr->sa_family);
 	if (seteuid(0) < 0)
 		fatal("Failed to seteuid");
 	if (bind(pdata, pasv_addr, socket_sockaddr_size (pasv_addr)) < 0) {
@@ -2064,8 +2029,8 @@
 	socket_set_address_and_port (pasv_addr,
 				     socket_get_address (ctrl_addr),
 				     0);
-	socket_set_portrange(pdata, restricted_data_ports,=20
-	    pasv_addr->sa_family);=20
+	socket_set_portrange(pdata, restricted_data_ports,
+	    pasv_addr->sa_family);
 	if (seteuid(0) < 0)
 		fatal("Failed to seteuid");
 	if (bind(pdata, pasv_addr, socket_sockaddr_size (pasv_addr)) < 0) {
@@ -2123,7 +2088,7 @@
 	case 2 :
 	    data_dest->sa_family =3D AF_INET6;
 	    break;
-#endif	=09
+#endif
 	case 1 :
 	    data_dest->sa_family =3D AF_INET;
 		break;
@@ -2154,7 +2119,18 @@
 		reply(500, "Bad port syntax in EPRT");
 		return;
 	}
+	if (port < IPPORT_RESERVED) {
+		reply(500, "Bad port in invalid range in EPRT");
+		return;
+	}
 	socket_set_port (data_dest, htons(port));
+
+	if (paranoid &&
+	    (data_dest->sa_family !=3D his_addr->sa_family ||
+	     memcmp(socket_get_address(data_dest), socket_get_address(his_addr), =
socket_sockaddr_size(data_dest)) !=3D 0))
+	{
+		reply(500, "Bad address in EPRT");
+	}
 	reply(200, "EPRT command successful.");
 }
=20
@@ -2353,15 +2329,13 @@
     transflag =3D 0;
     if (dout !=3D NULL){
 	sec_write(fileno(dout), buf, 0); /* XXX flush */
-	   =20
+
 	fclose(dout);
     }
     data =3D -1;
     pdata =3D -1;
-    if (freeglob) {
-	freeglob =3D 0;
+    if (freeglob)
 	globfree(&gl);
-    }
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/ftpd=
_locl.h
--- a/head/crypto/heimdal/appl/ftp/ftpd/ftpd_locl.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/ftpd_locl.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: ftpd_locl.h 14933 2005-04-24 19:58:14Z lha $ */
+/* $Id$ */
=20
 #ifndef __ftpd_locl_h__
 #define __ftpd_locl_h__
@@ -145,14 +145,10 @@
 #include <krb5.h>
 #endif /* KRB5 */
=20
-#ifdef KRB4
-#include <krb.h>
+#if defined(KRB5)
+#include <kafs.h>
 #endif
=20
-#if defined(KRB4) || defined(KRB5)
-#include <kafs.h>
-#endif
-=20
 #ifdef OTP
 #include <otp.h>
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/ftpu=
sers.5
--- a/head/crypto/heimdal/appl/ftp/ftpd/ftpusers.5	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/ftpusers.5	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,4 +1,4 @@
-.\"	$Id: ftpusers.5 11176 2002-08-20 17:07:29Z joda $
+.\"	$Id$
 .\"
 .Dd May 7, 1997
 .Dt FTPUSERS 5
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/gss_=
userok.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/gss_userok.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/gss_userok.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,155 +1,75 @@
 /*
- * Copyright (c) 1998 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "ftpd_locl.h"
-#include <gssapi.h>
-#include <krb5.h>
-
-RCSID("$Id: gss_userok.c 21222 2007-06-20 10:11:14Z lha $");
-
-/* XXX a bit too much of krb5 dependency here...=20
-   What is the correct way to do this?=20
-   */
-
-struct gss_krb5_data {
-    krb5_context context;
-};
+#include <gssapi/gssapi.h>
=20
 /* XXX sync with gssapi.c */
-struct gss_data {
+struct gssapi_data {
     gss_ctx_id_t context_hdl;
-    char *client_name;
+    gss_name_t client_name;
     gss_cred_id_t delegated_cred_handle;
     void *mech_data;
 };
=20
-int gss_userok(void*, char*); /* to keep gcc happy */
-int gss_session(void*, char*); /* to keep gcc happy */
+int gssapi_userok(void*, char*); /* to keep gcc happy */
+int gssapi_session(void*, char*); /* to keep gcc happy */
=20
 int
-gss_userok(void *app_data, char *username)
+gssapi_userok(void *app_data, char *username)
 {
-    struct gss_data *data =3D app_data;
-    krb5_error_code ret;
-    krb5_principal client;
-    struct gss_krb5_data *kdata;
+    struct gssapi_data *data =3D app_data;
=20
-    kdata =3D calloc(1, sizeof(struct gss_krb5_data));
-    if (kdata =3D=3D NULL)
-	return 1;
-    data->mech_data =3D kdata;
-
-    ret =3D krb5_init_context(&(kdata->context));
-    if (ret) {
-	free(kdata);
-	return 1;
-    }
-
-    ret =3D krb5_parse_name(kdata->context, data->client_name, &client);
-    if(ret) {
-	krb5_free_context(kdata->context);
-	free(kdata);
-	return 1;
-    }
-    ret =3D krb5_kuserok(kdata->context, client, username);
-    if (!ret) {
-	krb5_free_principal(kdata->context, client);
-	krb5_free_context(kdata->context);
-	free(kdata);
-	return 1;
-    }
-       =20
-    ret =3D 0;
-    krb5_free_principal(kdata->context, client);
-    return ret;
+    /* Yes, this logic really is inverted. */
+    return !gss_userok(data->client_name, username);
 }
=20
 int
-gss_session(void *app_data, char *username)
+gssapi_session(void *app_data, char *username)
 {
-    struct gss_data *data =3D app_data;
-    krb5_error_code ret;
-    OM_uint32 minor_status;
-    struct gss_krb5_data *kdata;
+    struct gssapi_data *data =3D app_data;
+    OM_uint32 major, minor;
+    int ret =3D 0;
=20
-    ret =3D 0;
+    if (data->delegated_cred_handle !=3D GSS_C_NO_CREDENTIAL) {
+        major =3D gss_store_cred(&minor, data->delegated_cred_handle,
+                               GSS_C_INITIATE, GSS_C_NO_OID,
+                               1, 1, NULL, NULL);
+        if (GSS_ERROR(major))
+            ret =3D 1;
+	afslog(NULL, 1);
+    }
=20
-    kdata =3D (struct gss_krb5_data *)(data->mech_data);
-       =20
-    /* more of krb-depend stuff :-( */
-    /* gss_add_cred() ? */
-    if (data->delegated_cred_handle !=3D GSS_C_NO_CREDENTIAL) {
-	krb5_ccache ccache =3D NULL;=20
-	const char* ticketfile;
-	struct passwd *kpw;
-          =20
-	ret =3D krb5_cc_gen_new(kdata->context, &krb5_fcc_ops, &ccache);
-	if (ret)
-	    goto fail;
-	  =20
-	ticketfile =3D krb5_cc_get_name(kdata->context, ccache);
-       =20
-	ret =3D gss_krb5_copy_ccache(&minor_status,
-				   data->delegated_cred_handle,
-				   ccache);
-	if (ret) {
-	    ret =3D 0;
-	    goto fail;
-	}
-          =20
-	do_destroy_tickets =3D 1;
-
-	kpw =3D getpwnam(username);
-          =20
-	if (kpw =3D=3D NULL) {
-	    unlink(ticketfile);
-	    ret =3D 1;
-	    goto fail;
-	}
-
-	chown (ticketfile, kpw->pw_uid, kpw->pw_gid);
-          =20
-	if (asprintf(&k5ccname, "FILE:%s", ticketfile) !=3D -1) {
-	    esetenv ("KRB5CCNAME", k5ccname, 1);
-	}
-	afslog(NULL, 1);
-    fail:
-	if (ccache)
-	    krb5_cc_close(kdata->context, ccache);=20
-    }
-          =20
-    gss_release_cred(&minor_status, &data->delegated_cred_handle);
-    krb5_free_context(kdata->context);
-    free(kdata);
+    gss_release_cred(&minor, &data->delegated_cred_handle);
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/gssa=
pi.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/gssapi.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/gssapi.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1998 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifdef FTP_SERVER
@@ -36,17 +36,18 @@
 #else
 #include "ftp_locl.h"
 #endif
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
 #include <krb5_err.h>
=20
-RCSID("$Id: gssapi.c 21513 2007-07-12 12:45:25Z lha $");
+RCSID("$Id$");
=20
 int ftp_do_gss_bindings =3D 0;
 int ftp_do_gss_delegate =3D 1;
=20
-struct gss_data {
+struct gssapi_data {
     gss_ctx_id_t context_hdl;
-    char *client_name;
+    gss_name_t client_name;
     gss_cred_id_t delegated_cred_handle;
     void *mech_data;
 };
@@ -54,7 +55,7 @@
 static int
 gss_init(void *app_data)
 {
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     d->context_hdl =3D GSS_C_NO_CONTEXT;
     d->delegated_cred_handle =3D GSS_C_NO_CREDENTIAL;
 #if defined(FTP_SERVER)
@@ -84,7 +85,7 @@
     gss_buffer_desc input, output;
     gss_qop_t qop_state;
     int conf_state;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     size_t ret_len;
=20
     input.length =3D len;
@@ -116,7 +117,7 @@
     OM_uint32 maj_stat, min_stat;
     gss_buffer_desc input, output;
     int conf_state;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
=20
     input.length =3D length;
     input.value =3D from;
@@ -157,7 +158,7 @@
     }
     default :
 	errx (1, "unknown address family %d", sa->sa_family);
-=09
+
     }
 }
=20
@@ -172,7 +173,7 @@
     gss_buffer_desc input_token, output_token;
     OM_uint32 maj_stat, min_stat;
     gss_name_t client_name;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     gss_channel_bindings_t bindings;
=20
     if (ftp_do_gss_bindings) {
@@ -186,7 +187,7 @@
 	sockaddr_to_gss_address (ctrl_addr,
 				 &bindings->acceptor_addrtype,
 				 &bindings->acceptor_address);
-=09
+
 	bindings->application_data.length =3D 0;
 	bindings->application_data.value =3D NULL;
     } else
@@ -218,32 +219,8 @@
 	gss_release_buffer(&min_stat, &output_token);
     }
     if(maj_stat =3D=3D GSS_S_COMPLETE){
-	char *name;
-	gss_buffer_desc export_name;
-	gss_OID oid;
-
-	maj_stat =3D gss_display_name(&min_stat, client_name,
-				    &export_name, &oid);
-	if(maj_stat !=3D 0) {
-	    reply(500, "Error displaying name");
-	    goto out;
-	}
-	/* XXX kerberos */
-	if(oid !=3D GSS_KRB5_NT_PRINCIPAL_NAME) {
-	    reply(500, "OID not kerberos principal name");
-	    gss_release_buffer(&min_stat, &export_name);
-	    goto out;
-	}
-	name =3D malloc(export_name.length + 1);
-	if(name =3D=3D NULL) {
-	    reply(500, "Out of memory");
-	    gss_release_buffer(&min_stat, &export_name);
-	    goto out;
-	}
-	memcpy(name, export_name.value, export_name.length);
-	name[export_name.length] =3D '\0';
-	gss_release_buffer(&min_stat, &export_name);
-	d->client_name =3D name;
+	d->client_name =3D client_name;
+	client_name =3D GSS_C_NO_NAME;
 	if(p)
 	    reply(235, "ADAT=3D%s", p);
 	else
@@ -265,24 +242,25 @@
 			   GSS_C_NO_OID,
 			   &msg_ctx,
 			   &status_string);
-	syslog(LOG_ERR, "gss_accept_sec_context: %s",=20
+	syslog(LOG_ERR, "gss_accept_sec_context: %.*s",
+	       (int)status_string.length,
 	       (char*)status_string.value);
 	gss_release_buffer(&new_stat, &status_string);
 	reply(431, "Security resource unavailable");
     }
-  out:
+
     if (client_name)
 	gss_release_name(&min_stat, &client_name);
     free(p);
     return 0;
 }
=20
-int gss_userok(void*, char*);
-int gss_session(void*, char*);
+int gssapi_userok(void*, char*);
+int gssapi_session(void*, char*);
=20
 struct sec_server_mech gss_server_mech =3D {
     "GSSAPI",
-    sizeof(struct gss_data),
+    sizeof(struct gssapi_data),
     gss_init, /* init */
     NULL, /* end */
     gss_check_prot,
@@ -294,8 +272,8 @@
     gss_adat,
     NULL, /* pbsz */
     NULL, /* ccc */
-    gss_userok,
-    gss_session
+    gssapi_userok,
+    gssapi_session
 };
=20
 #else /* FTP_SERVER */
@@ -324,15 +302,17 @@
 	OM_uint32 new_stat;
 	OM_uint32 msg_ctx =3D 0;
 	gss_buffer_desc status_string;
-	   =20
+
 	gss_display_status(&new_stat,
 			   min_stat,
 			   GSS_C_MECH_CODE,
 			   GSS_C_NO_OID,
 			   &msg_ctx,
 			   &status_string);
-	printf("Error importing name %s: %s\n",=20
+	printf("Error importing name %.*s: %.*s\n",
+	       (int)name.length,
 	       (char *)name.value,
+	       (int)status_string.length,
 	       (char *)status_string.value);
 	free(name.value);
 	gss_release_buffer(&new_stat, &status_string);
@@ -345,7 +325,7 @@
 static int
 gss_auth(void *app_data, char *host)
 {
-   =20
+
     OM_uint32 maj_stat, min_stat;
     gss_name_t target_name;
     gss_buffer_desc input, output_token;
@@ -353,12 +333,12 @@
     char *p;
     int n;
     gss_channel_bindings_t bindings;
-    struct gss_data *d =3D app_data;
+    struct gssapi_data *d =3D app_data;
     OM_uint32 mech_flags =3D GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG;
=20
     const char *knames[] =3D { "ftp", "host", NULL }, **kname =3D knames;
-	   =20
-   =20
+
+
     if(import_name(*kname++, host, &target_name))
 	return AUTH_ERROR;
=20
@@ -369,14 +349,14 @@
 	bindings =3D malloc(sizeof(*bindings));
 	if (bindings =3D=3D NULL)
 	    errx(1, "out of memory");
-=09
+
 	sockaddr_to_gss_address (myctladdr,
 				 &bindings->initiator_addrtype,
 				 &bindings->initiator_address);
 	sockaddr_to_gss_address (hisctladdr,
 				 &bindings->acceptor_addrtype,
 				 &bindings->acceptor_address);
-=09
+
 	bindings->application_data.length =3D 0;
 	bindings->application_data.value =3D NULL;
     } else
@@ -417,7 +397,7 @@
 		}
 		continue;
 	    }
-	   =20
+
 	    if (bindings !=3D GSS_C_NO_CHANNEL_BINDINGS)
 		free(bindings);
=20
@@ -427,7 +407,8 @@
 			       GSS_C_NO_OID,
 			       &msg_ctx,
 			       &status_string);
-	    printf("Error initializing security context: %s\n",=20
+	    printf("Error initializing security context: %.*s\n",
+		   (int)status_string.length,
 		   (char*)status_string.value);
 	    gss_release_buffer(&new_stat, &status_string);
 	    return AUTH_CONTINUE;
@@ -501,13 +482,15 @@
 					 &name,
 					 NULL);
 	    if (GSS_ERROR(maj_stat) =3D=3D 0) {
-		printf("Authenticated to <%s>\n", (char *)name.value);
+		printf("Authenticated to <%.*s>\n",
+			(int)name.length,
+			(char *)name.value);
 		gss_release_buffer(&min_stat, &name);
 	    }
 	    gss_release_name(&min_stat, &targ_name);
 	} else
 	    printf("Failed to get gss name of peer.\n");
-    }	   =20
+    }
=20
=20
     return AUTH_OK;
@@ -515,7 +498,7 @@
=20
 struct sec_client_mech gss_client_mech =3D {
     "GSSAPI",
-    sizeof(struct gss_data),
+    sizeof(struct gssapi_data),
     gss_init,
     gss_auth,
     NULL, /* end */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/kaut=
h.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/kauth.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/kauth.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 1999, 2003 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 1999, 2003 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,226 +33,15 @@
=20
 #include "ftpd_locl.h"
=20
-RCSID("$Id: kauth.c 15666 2005-07-19 17:08:11Z lha $");
+RCSID("$Id$");
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
=20
 int do_destroy_tickets =3D 1;
 char *k5ccname;
=20
 #endif
=20
-#ifdef KRB4
-
-static KTEXT_ST cip;
-static unsigned int lifetime;
-static time_t local_time;
-
-static krb_principal pr;
-
-static int
-save_tkt(const char *user,
-	 const char *instance,
-	 const char *realm,
-	 const void *arg,=20
-	 key_proc_t key_proc,
-	 KTEXT *cipp)
-{
-    local_time =3D time(0);
-    memmove(&cip, *cipp, sizeof(cip));
-    return -1;
-}
-
-static int
-store_ticket(KTEXT cip)
-{
-    char *ptr;
-    des_cblock session;
-    krb_principal sp;
-    unsigned char kvno;
-    KTEXT_ST tkt;
-    int left =3D cip->length;
-    int len;
-    int kerror;
-   =20
-    ptr =3D (char *) cip->dat;
-
-    /* extract session key */
-    memmove(session, ptr, 8);
-    ptr +=3D 8;
-    left -=3D 8;
-
-    len =3D strnlen(ptr, left);
-    if (len =3D=3D left)
-	return(INTK_BADPW);
-   =20
-    /* extract server's name */
-    strlcpy(sp.name, ptr, sizeof(sp.name));
-    ptr +=3D len + 1;
-    left -=3D len + 1;
-
-    len =3D strnlen(ptr, left);
-    if (len =3D=3D left)
-	return(INTK_BADPW);
-   =20
-    /* extract server's instance */
-    strlcpy(sp.instance, ptr, sizeof(sp.instance));
-    ptr +=3D len + 1;
-    left -=3D len + 1;
-
-    len =3D strnlen(ptr, left);
-    if (len =3D=3D left)
-	return(INTK_BADPW);
-   =20
-    /* extract server's realm */
-    strlcpy(sp.realm, ptr, sizeof(sp.realm));
-    ptr +=3D len + 1;
-    left -=3D len + 1;
-
-    if(left < 3)
-	return INTK_BADPW;
-    /* extract ticket lifetime, server key version, ticket length */
-    /* be sure to avoid sign extension on lifetime! */
-    lifetime =3D (unsigned char) ptr[0];
-    kvno =3D (unsigned char) ptr[1];
-    tkt.length =3D (unsigned char) ptr[2];
-    ptr +=3D 3;
-    left -=3D 3;
-   =20
-    if (tkt.length > left)
-	return(INTK_BADPW);
-
-    /* extract ticket itself */
-    memmove(tkt.dat, ptr, tkt.length);
-    ptr +=3D tkt.length;
-    left -=3D tkt.length;
-
-    /* Here is where the time should be verified against the KDC.
-     * Unfortunately everything is sent in host byte order (receiver
-     * makes wrong) , and at this stage there is no way for us to know
-     * which byteorder the KDC has. So we simply ignore the time,
-     * there are no security risks with this, the only thing that can
-     * happen is that we might receive a replayed ticket, which could
-     * at most be useless.
-     */
-   =20
-#if 0
-    /* check KDC time stamp */
-    {
-	time_t kdc_time;
-
-	memmove(&kdc_time, ptr, sizeof(kdc_time));
-	if (swap_bytes) swap_u_long(kdc_time);
-
-	ptr +=3D 4;
-   =20
-	if (abs((int)(local_time - kdc_time)) > CLOCK_SKEW) {
-	    return(RD_AP_TIME);		/* XXX should probably be better
-					   code */
-	}
-    }
-#endif
-
-    /* initialize ticket cache */
-
-    if (tf_create(TKT_FILE) !=3D KSUCCESS)
-	return(INTK_ERR);
-
-    if (tf_put_pname(pr.name) !=3D KSUCCESS ||
-	tf_put_pinst(pr.instance) !=3D KSUCCESS) {
-	tf_close();
-	return(INTK_ERR);
-    }
-
-   =20
-    kerror =3D tf_save_cred(sp.name, sp.instance, sp.realm, session,=20
-			  lifetime, kvno, &tkt, local_time);
-    tf_close();
-
-    return(kerror);
-}
-
-void
-kauth(char *principal, char *ticket)
-{
-    char *p;
-    int ret;
- =20
-    if(get_command_prot() !=3D prot_private) {
-	reply(500, "Request denied (bad protection level)");
-	return;
-    }
-    ret =3D krb_parse_name(principal, &pr);
-    if(ret){
-	reply(500, "Bad principal: %s.", krb_get_err_text(ret));
-	return;
-    }
-    if(pr.realm[0] =3D=3D 0)
-	krb_get_lrealm(pr.realm, 1);
-
-    if(ticket){
-	cip.length =3D base64_decode(ticket, &cip.dat);
-	if(cip.length =3D=3D -1){
-	    reply(500, "Failed to decode data.");
-	    return;
-	}
-	ret =3D store_ticket(&cip);
-	if(ret){
-	    reply(500, "Kerberos error: %s.", krb_get_err_text(ret));
-	    memset(&cip, 0, sizeof(cip));
-	    return;
-	}
-	do_destroy_tickets =3D 1;
-
-	if(k_hasafs())
-	    krb_afslog(0, 0);
-	reply(200, "Tickets will be destroyed on exit.");
-	return;
-    }
-   =20
-    ret =3D krb_get_in_tkt (pr.name,
-			  pr.instance,
-			  pr.realm,
-			  KRB_TICKET_GRANTING_TICKET,
-			  pr.realm,
-			  DEFAULT_TKT_LIFE,
-			  NULL, save_tkt, NULL);
-    if(ret !=3D INTK_BADPW){
-	reply(500, "Kerberos error: %s.", krb_get_err_text(ret));
-	return;
-    }
-    if(base64_encode(cip.dat, cip.length, &p) < 0) {
-	reply(500, "Out of memory while base64-encoding.");
-	return;
-    }
-    reply(300, "P=3D%s T=3D%s", krb_unparse_name(&pr), p);
-    free(p);
-    memset(&cip, 0, sizeof(cip));
-}
-
-
-static char *
-short_date(int32_t dp)
-{
-    char *cp;
-    time_t t =3D (time_t)dp;
-
-    if (t =3D=3D (time_t)(-1L)) return "***  Never  *** ";
-    cp =3D ctime(&t) + 4;
-    cp[15] =3D '\0';
-    return (cp);
-}
-
-void
-krbtkfile(const char *tkfile)
-{
-    do_destroy_tickets =3D 0;
-    krb_set_tkt_string(tkfile);
-    reply(200, "Using ticket file %s", tkfile);
-}
-
-#endif /* KRB4 */
-
 #ifdef KRB5
=20
 static void
@@ -261,7 +50,7 @@
     krb5_context context;
     krb5_error_code ret;
     krb5_ccache id;
-   =20
+
     ret =3D krb5_init_context(&context);
     if (ret =3D=3D 0) {
 	if (k5ccname)
@@ -278,7 +67,7 @@
 }
 #endif
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
=20
 /*
  * Only destroy if we created the tickets
@@ -288,9 +77,6 @@
 cond_kdestroy(void)
 {
     if (do_destroy_tickets) {
-#if KRB4
-	dest_tkt();
-#endif
 #if KRB5
 	dest_cc();
 #endif
@@ -302,9 +88,6 @@
 void
 kdestroy(void)
 {
-#if KRB4
-    dest_tkt();
-#endif
 #if KRB5
     dest_cc();
 #endif
@@ -337,9 +120,6 @@
 	    krb5_free_context (context);
 	}
 #endif
-#ifdef KRB4
-	krb_afslog(cell, 0);
-#endif
 	if (!quiet)
 	    reply(200, "afslog done");
     } else {
@@ -357,4 +137,4 @@
=20
 #else
 int ftpd_afslog_placeholder;
-#endif /* KRB4 || KRB5 */
+#endif /* KRB5 */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/klis=
t.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/klist.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/klist.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -48,7 +48,7 @@
 	krb5_format_time(context, cred->times.starttime, t1, sizeof(t1), 1);
     else
 	krb5_format_time(context, cred->times.authtime, t1, sizeof(t1), 1);
-   =20
+
     if(cred->times.endtime > sec)
 	krb5_format_time(context, cred->times.endtime, t2, sizeof(t2), 1);
     else
@@ -81,7 +81,7 @@
 	return 500;
     }
=20
-    lreply(200, "%17s: %s:%s",=20
+    lreply(200, "%17s: %s:%s",
 	   "Credentials cache",
 	   krb5_cc_get_type(context, ccache),
 	   krb5_cc_get_name(context, ccache));
@@ -101,7 +101,7 @@
 				     &cursor,
 				     &cred)) =3D=3D 0) {
 	if (print_cred(context, &cred))
-	    return 500;	=09
+	    return 500;
 	krb5_free_cred_contents (context, &cred);
     }
     if (ret !=3D KRB5_CC_END) {
@@ -137,7 +137,7 @@
     else
 	ret =3D krb5_cc_default (context, &ccache);
     if (ret) {
-	lreply(500, "krb5_cc_default: %d", ret);	   =20
+	lreply(500, "krb5_cc_default: %d", ret);
 	return 500;
     }
=20
@@ -155,7 +155,7 @@
=20
     ret =3D krb5_cc_close (context, ccache);
     if (ret) {
-	lreply(500, "krb5_cc_close: %d", ret);	   =20
+	lreply(500, "krb5_cc_close: %d", ret);
 	exit_status =3D 500;
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/logw=
tmp.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/logwtmp.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/logwtmp.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,7 +33,7 @@
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: logwtmp.c 9079 2000-09-19 13:17:20Z assar $");
+RCSID("$Id$");
 #endif
=20
 #include <stdio.h>
@@ -58,9 +58,13 @@
 #ifdef HAVE_UTMPX_H
 #include <utmpx.h>
 #endif
+#ifdef HAVE_ASL_H
+#include <asl.h>
+#endif
 #include <roken.h>
 #include "extern.h"
=20
+#ifndef HAVE_UTMPX_H
 #ifndef WTMP_FILE
 #ifdef _PATH_WTMP
 #define WTMP_FILE _PATH_WTMP
@@ -68,20 +72,56 @@
 #define WTMP_FILE "/var/adm/wtmp"
 #endif
 #endif
+#endif
=20
-void
-ftpd_logwtmp(char *line, char *name, char *host)
+#ifdef HAVE_ASL_H
+
+#ifndef ASL_KEY_FACILITY
+#define ASL_KEY_FACILITY "Facility"
+#endif
+
+static void
+ftpd_logwtmp_asl(char *line, char *name, char *host)
+{
+    static aslmsg m =3D NULL;
+    static int init =3D 0;
+
+    if (!init) {
+	init =3D 1;
+	m =3D asl_new(ASL_TYPE_MSG);
+	if (m =3D=3D NULL)
+	    return;
+	asl_set(m, ASL_KEY_FACILITY, "org.h5l.ftpd");
+    }
+    if (m)
+	asl_log(NULL, m, ASL_LEVEL_NOTICE,
+		"host %s/%s user %s%sconnected pid %d",
+		host, line, name, name[0] ? " " : "dis", (int)getpid());
+}
+
+#endif
+
+#ifndef HAVE_ASL_H
+
+static void
+ftpd_logwtmp_wtmp(char *line, char *name, char *host)
 {
     static int init =3D 0;
     static int fd;
 #ifdef WTMPX_FILE
     static int fdx;
 #endif
+#ifdef HAVE_UTMP_H
     struct utmp ut;
-#ifdef WTMPX_FILE
+#endif
+#if defined(WTMPX_FILE) || defined(HAVE_UTMPX_H)
     struct utmpx utx;
 #endif
=20
+#ifdef HAVE_UTMPX_H
+    memset(&utx, 0, sizeof(struct utmpx));
+#endif
+#ifdef HAVE_UTMP_H
     memset(&ut, 0, sizeof(struct utmp));
 #ifdef HAVE_STRUCT_UTMP_UT_TYPE
     if(name[0])
@@ -98,8 +138,9 @@
     strncpy(ut.ut_host, host, sizeof(ut.ut_host));
 #endif
     ut.ut_time =3D time(NULL);
+#endif
=20
-#ifdef WTMPX_FILE
+#if defined(WTMPX_FILE) || defined(HAVE_UTMPX_H)
     strncpy(utx.ut_line, line, sizeof(utx.ut_line));
     strncpy(utx.ut_user, name, sizeof(utx.ut_user));
     strncpy(utx.ut_host, host, sizeof(utx.ut_host));
@@ -122,17 +163,37 @@
 	utx.ut_type =3D DEAD_PROCESS;
 #endif
=20
+#ifdef HAVE_UTMPX_H
+    pututxline(&utx);
+#endif
+
     if(!init){
+#ifdef WTMP_FILE
 	fd =3D open(WTMP_FILE, O_WRONLY|O_APPEND, 0);
+#endif
 #ifdef WTMPX_FILE
 	fdx =3D open(WTMPX_FILE, O_WRONLY|O_APPEND, 0);
 #endif
 	init =3D 1;
     }
     if(fd >=3D 0) {
+#ifdef WTMP_FILE
 	write(fd, &ut, sizeof(struct utmp)); /* XXX */
+#endif
 #ifdef WTMPX_FILE
 	write(fdx, &utx, sizeof(struct utmpx));
-#endif=09
+#endif
     }
 }
+
+#endif /* !HAVE_ASL_H */
+
+void
+ftpd_logwtmp(char *line, char *name, char *host)
+{
+#ifdef HAVE_ASL_H
+    ftpd_logwtmp_asl(line, name, host);
+#else
+    ftpd_logwtmp_wtmp(line, name, host);
+#endif
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/ls.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/ls.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/ls.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,7 +33,7 @@
 #ifndef TEST
 #include "ftpd_locl.h"
=20
-RCSID("$Id: ls.c 16216 2005-10-22 13:15:43Z lha $");
+RCSID("$Id$");
=20
 #else
 #include <stdio.h>
@@ -152,10 +152,10 @@
     char buf[128];
     int file_type =3D 0;
     struct stat *st =3D &file->st;
-   =20
+
     file->inode =3D st->st_ino;
     file->bsize =3D block_convert(st->st_blocks);
-   =20
+
     if(S_ISDIR(st->st_mode)) {
 	file->mode[0] =3D 'd';
 	file_type =3D '/';
@@ -187,10 +187,10 @@
 	file_type =3D '%';
     }
 #endif
-    else=20
+    else
 	file->mode[0] =3D '?';
     {
-	char *x[] =3D { "---", "--x", "-w-", "-wx",=20
+	char *x[] =3D { "---", "--x", "-w-", "-wx",
 		      "r--", "r-x", "rw-", "rwx" };
 	strcpy(file->mode + 1, x[(st->st_mode & S_IRWXU) >> 6]);
 	strcpy(file->mode + 4, x[(st->st_mode & S_IRWXG) >> 3]);
@@ -241,7 +241,7 @@
 	    return -1;
 	}
     }
-   =20
+
     if(S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)) {
 #if defined(major) && defined(minor)
 	if (asprintf(&file->major, "%u", (unsigned)major(st->st_rdev)) =3D=3D -1)
@@ -405,16 +405,16 @@
  * have to fetch them.
  */
=20
-#ifdef KRB4
+#ifdef KRB5
 static int do_the_afs_dance =3D 1;
 #endif
=20
 static int
 lstat_file (const char *file, struct stat *sb)
 {
-#ifdef KRB4
+#ifdef KRB5
     if (do_the_afs_dance &&
-	k_hasafs()=20
+	k_hasafs()
 	&& strcmp(file, ".")
 	&& strcmp(file, "..")
 	&& strcmp(file, "/"))
@@ -425,19 +425,19 @@
 	static ino_t	   ino_counter =3D 0, ino_last =3D 0;
 	int		   ret;
 	const int	   maxsize =3D 2048;
-=09
+
 	path_bkp =3D strdup (file);
 	if (path_bkp =3D=3D NULL)
 	    return -1;
-=09
+
 	a_params.out =3D malloc (maxsize);
-	if (a_params.out =3D=3D NULL) {=20
+	if (a_params.out =3D=3D NULL) {
 	    free (path_bkp);
 	    return -1;
 	}
-=09
+
 	/* If path contains more than the filename alone - split it */
-=09
+
 	last =3D strrchr (path_bkp, '/');
 	if (last !=3D NULL) {
 	    if(last[1] =3D=3D '\0')
@@ -457,10 +457,10 @@
 	    dir =3D ".";
 	    a_params.in =3D path_bkp;
 	}
-=09
+
 	a_params.in_size  =3D strlen (a_params.in) + 1;
 	a_params.out_size =3D maxsize;
-=09
+
 	ret =3D k_pioctl (dir, VIOC_AFS_STAT_MT_PT, &a_params, 0);
 	free (a_params.out);
 	if (ret < 0) {
@@ -473,7 +473,7 @@
 		return lstat (file, sb);
 	}
=20
-	/*=20
+	/*
 	 * wow this was a mountpoint, lets cook the struct stat
 	 * use . as a prototype
 	 */
@@ -494,7 +494,7 @@
=20
 	return 0;
     }
-#endif /* KRB4 */
+#endif /* KRB5 */
     return lstat (file, sb);
 }
=20
@@ -551,15 +551,15 @@
     }
     switch(SORT_MODE(flags)) {
     case LS_SORT_NAME:
-	qsort(fi, n_files, sizeof(*fi),=20
+	qsort(fi, n_files, sizeof(*fi),
 	      (int (*)(const void*, const void*))compare_filename);
 	break;
     case LS_SORT_MTIME:
-	qsort(fi, n_files, sizeof(*fi),=20
+	qsort(fi, n_files, sizeof(*fi),
 	      (int (*)(const void*, const void*))compare_mtime);
 	break;
     case LS_SORT_SIZE:
-	qsort(fi, n_files, sizeof(*fi),=20
+	qsort(fi, n_files, sizeof(*fi),
 	      (int (*)(const void*, const void*))compare_size);
 	break;
     }
@@ -602,7 +602,7 @@
 	max_inode =3D find_log10(max_inode);
 	max_bsize =3D find_log10(max_bsize);
 	max_n_link =3D find_log10(max_n_link);
-=09
+
 	if(n_print > 0)
 	    sec_fprintf2(out, "total %lu\r\n", (unsigned long)total_blocks);
 	if(flags & LS_SORT_REVERSE)
@@ -633,7 +633,7 @@
 			   max_major,
 			   max_minor,
 			   max_date);
-    } else if(DISP_MODE(flags) =3D=3D LS_DISP_COLUMN ||=20
+    } else if(DISP_MODE(flags) =3D=3D LS_DISP_COLUMN ||
 	      DISP_MODE(flags) =3D=3D LS_DISP_CROSS) {
 	int max_len =3D 0;
 	int size_len =3D 0;
@@ -660,14 +660,14 @@
 	    max_len =3D 80 / columns;
 	}
 	if(flags & LS_SIZE)
-	    sec_fprintf2(out, "total %lu\r\n",=20
+	    sec_fprintf2(out, "total %lu\r\n",
 			 (unsigned long)total_blocks);
 	if(DISP_MODE(flags) =3D=3D LS_DISP_CROSS) {
 	    for(i =3D 0, j =3D 0; i < n_files; i++) {
 		if(fi[i].filename =3D=3D NULL)
 		    continue;
 		if(flags & LS_SIZE)
-		    sec_fprintf2(out, "%*u %-*s", size_len, fi[i].bsize,=20
+		    sec_fprintf2(out, "%*u %-*s", size_len, fi[i].bsize,
 				 max_len, fi[i].filename);
 		else
 		    sec_fprintf2(out, "%-*s", max_len, fi[i].filename);
@@ -681,13 +681,13 @@
 		sec_fprintf2(out, "\r\n");
 	} else {
 	    int skip =3D (num_files + columns - 1) / columns;
-	    j =3D 0;
+
 	    for(i =3D 0; i < skip; i++) {
 		for(j =3D i; j < n_files;) {
 		    while(j < n_files && fi[j].filename =3D=3D NULL)
 			j++;
 		    if(flags & LS_SIZE)
-			sec_fprintf2(out, "%*u %-*s", size_len, fi[j].bsize,=20
+			sec_fprintf2(out, "%*u %-*s", size_len, fi[j].bsize,
 				     max_len, fi[j].filename);
 		    else
 			sec_fprintf2(out, "%-*s", max_len, fi[j].filename);
@@ -710,7 +710,7 @@
 		const char *p =3D strrchr(files[i], '/');
 		if(p =3D=3D NULL)
 		    p =3D files[i];
-		else=20
+		else
 		    p++;
 		if(!(flags & LS_DIR_FLAG) || !IS_DOT_DOTDOT(p)) {
 		    if((flags & LS_SHOW_DIRNAME)) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/pope=
n.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/popen.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/popen.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -37,7 +37,7 @@
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: popen.c 10900 2002-04-02 11:57:39Z joda $");
+RCSID("$Id$");
 #endif
=20
 #include <sys/types.h>
@@ -65,7 +65,7 @@
 #include "extern.h"
=20
=20
-/*=20
+/*
  * Special version of popen which avoids call to shell.  This ensures
  * no one may create a pipe to a hidden program as a side effect of a
  * list or dir command.
@@ -73,8 +73,6 @@
 static int *pids;
 static int fds;
=20
-extern int dochroot;
-
 /* return path prepended with ~ftp if that file exists, otherwise
  * return path unchanged
  */
@@ -148,8 +146,8 @@
 		    ;
=20
 		memset(&gl, 0, sizeof(gl));
-		if (no_glob ||=20
-		    glob(argv[argc], flags, NULL, &gl) ||=20
+		if (no_glob ||
+		    glob(argv[argc], flags, NULL, &gl) ||
 		    gl.gl_pathc =3D=3D 0)
 			gargv[gargc++] =3D strdup(argv[argc]);
 		else
@@ -198,8 +196,8 @@
 		close(pdes[0]);
 	}
 	pids[fileno(iop)] =3D pid;
-=09
-pfree:=09
+
+pfree:
 	for (argc =3D 1; gargv[argc] !=3D NULL; argc++)
 	    free(gargv[argc]);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/ftp/ftpd/secu=
rity.c
--- a/head/crypto/heimdal/appl/ftp/ftpd/security.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/ftp/ftpd/security.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1998-2002, 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1998-2002, 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -37,7 +37,7 @@
 #include "ftp_locl.h"
 #endif
=20
-RCSID("$Id: security.c 21225 2007-06-20 10:16:02Z lha $");
+RCSID("$Id$");
=20
 static enum protection_level command_prot;
 static enum protection_level data_prot;
@@ -74,14 +74,14 @@
 }
=20
 #ifndef FTP_SERVER /* not used in server */
-static enum protection_level=20
+static enum protection_level
 name_to_level(const char *name)
 {
     int i;
     for(i =3D 0; i < sizeof(level_names) / sizeof(level_names[0]); i++)
 	if(!strncasecmp(level_names[i].name, name, strlen(name)))
 	    return level_names[i].level;
-    return (enum protection_level)-1;
+    return prot_invalid;
 }
 #endif
=20
@@ -91,9 +91,6 @@
 #ifdef KRB5
     &gss_server_mech,
 #endif
-#ifdef KRB4
-    &krb4_server_mech,
-#endif
     NULL
 };
=20
@@ -105,9 +102,6 @@
 #ifdef KRB5
     &gss_client_mech,
 #endif
-#ifdef KRB4
-    &krb4_client_mech,
-#endif
     NULL
 };
=20
@@ -229,12 +223,12 @@
 	in_buffer.eof_flag =3D 0;
 	return 0;
     }
-   =20
+
     len =3D buffer_read(&in_buffer, dataptr, length);
     length -=3D len;
     rx +=3D len;
     dataptr =3D (char*)dataptr + len;
-   =20
+
     while(length){
 	int ret;
=20
@@ -286,7 +280,7 @@
 {
     int len =3D buffer_size;
     int tx =3D 0;
-     =20
+
     if(data_prot =3D=3D prot_clear)
 	return write(fd, dataptr, length);
=20
@@ -337,7 +331,7 @@
     char ch =3D c;
     if(data_prot =3D=3D prot_clear)
 	return putc(c, F);
-   =20
+
     buffer_write(&out_buffer, &ch, 1);
     if(c =3D=3D '\n' || out_buffer.index >=3D 1024 /* XXX */) {
 	sec_write(fileno(F), out_buffer.data, out_buffer.index);
@@ -352,14 +346,14 @@
     int len;
     char *buf;
     int return_code;
-   =20
+
     buf =3D malloc(strlen(s));
     len =3D base64_decode(s + 4, buf); /* XXX */
-   =20
+
     len =3D (*mech->decode)(app_data, buf, len, level);
     if(len < 0)
 	return -1;
-   =20
+
     buf[len] =3D '\0';
=20
     if(buf[3] =3D=3D '-')
@@ -381,7 +375,7 @@
     int len;
     if(!sec_complete)
 	return vfprintf(f, fmt, ap);
-   =20
+
     if (vasprintf(&buf, fmt, ap) =3D=3D -1) {
 	printf("Failed to allocate command.\n");
 	return -1;
@@ -520,10 +514,10 @@
 	reply(504, "Unrecognized protection level.");
 	return;
     }
-   =20
+
     if(sec_complete){
 	if((*mech->check_prot)(app_data, p)){
-	    reply(536, "%s does not support %s protection.",=20
+	    reply(536, "%s does not support %s protection.",
 		  mech->name, level_to_name(p));
 	}else{
 	    data_prot =3D (enum protection_level)p;
@@ -556,14 +550,20 @@
     }
     buf_size =3D strlen(msg) + 2;
     buf =3D malloc(buf_size);
+    if (buf =3D=3D NULL) {
+	reply(501, "Failed to allocate %lu", (unsigned long)buf_size);
+	return;
+    }
     len =3D base64_decode(msg, buf);
     command_prot =3D level;
     if(len =3D=3D (size_t)-1) {
+	free(buf);
 	reply(501, "Failed to base64-decode command");
 	return;
     }
     len =3D (*mech->decode)(app_data, buf, len, level);
     if(len =3D=3D (size_t)-1) {
+	free(buf);
 	reply(535, "Failed to decode command");
 	return;
     }
@@ -628,7 +628,7 @@
 	printf("Using %s command channel.\n", level_to_name(command_prot));
 	printf("Using %s data channel.\n", level_to_name(data_prot));
 	if(buffer_size > 0)
-	    printf("Protection buffer size: %lu.\n",=20
+	    printf("Protection buffer size: %lu.\n",
 		   (unsigned long)buffer_size);
     }else{
 	printf("Not using any security mechanism.\n");
@@ -669,7 +669,7 @@
 	printf("Failed to set protection level.\n");
 	return -1;
     }
-   =20
+
     data_prot =3D (enum protection_level)level;
     return 0;
 }
@@ -683,7 +683,7 @@
 	ret =3D command("CCC");
 	if(ret !=3D COMPLETE) {
 	    printf("Failed to clear command channel.\n");
-	    return -1;
+	    return prot_invalid;
 	}
     }
     command_prot =3D level;
@@ -708,17 +708,17 @@
 	return;
     }
     level =3D name_to_level(argv[argc - 1]);
-   =20
+
     if(level =3D=3D -1)
 	goto usage;
-   =20
+
     if((*mech->check_prot)(app_data, level)) {
-	printf("%s does not implement %s protection.\n",=20
+	printf("%s does not implement %s protection.\n",
 	       mech->name, level_to_name(level));
 	code =3D -1;
 	return;
     }
-   =20
+
     if(argc =3D=3D 2 || strncasecmp(argv[1], "data", strlen(argv[1])) =3D=
=3D 0) {
 	if(sec_prot_internal(level) < 0){
 	    code =3D -1;
@@ -759,9 +759,9 @@
 	level =3D name_to_level(argv[1]);
 	if(level =3D=3D -1)
 	    goto usage;
-   =20
+
 	if((*mech->check_prot)(app_data, level)) {
-	    printf("%s does not implement %s protection.\n",=20
+	    printf("%s does not implement %s protection.\n",
 		   mech->name, level_to_name(level));
 	    code =3D -1;
 	    return;
@@ -808,7 +808,7 @@
=20
     verbose =3D -1; /* shut up all messages this will produce (they
 		     are usually not very user friendly) */
-   =20
+
     for(m =3D mechs; *m && (*m)->name; m++) {
 	void *tmp;
=20
@@ -818,7 +818,7 @@
 	    return -1;
 	}
 	app_data =3D tmp;
-	   =20
+
 	if((*m)->init && (*(*m)->init)(app_data) !=3D 0) {
 	    printf("Skipping %s...\n", (*m)->name);
 	    continue;
@@ -840,7 +840,7 @@
 	}
=20
 	ret =3D (*(*m)->auth)(app_data, host);
-=09
+
 	if(ret =3D=3D AUTH_CONTINUE)
 	    continue;
 	else if(ret !=3D AUTH_OK){
@@ -852,13 +852,13 @@
 	sec_complete =3D 1;
 	if(doencrypt) {
 	    command_prot =3D prot_private;
-	    request_data_prot =3D prot_private;=20
+	    request_data_prot =3D prot_private;
 	} else {
 	    command_prot =3D prot_safe;
 	}
 	break;
     }
-   =20
+
     verbose =3D old_verbose;
     return *m =3D=3D NULL;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/gssmask/Makef=
ile.am
--- a/head/crypto/heimdal/appl/gssmask/Makefile.am	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/gssmask/Makefile.am	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 18468 2006-10-14 13:50:51Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -8,5 +8,6 @@
=20
 gssmaestro_SOURCES =3D gssmaestro.c common.c common.h protocol.h
=20
-LDADD =3D $(top_builddir)/lib/gssapi/libgssapi.la $(LIB_roken)
+LDADD =3D $(top_builddir)/lib/gssapi/libgssapi.la $(LIB_roken) $(top_build=
dir)/lib/krb5/libkrb5.la
=20
+EXTRA_DIST =3D NTMakefile
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/gssmask/Makef=
ile.in
--- a/head/crypto/heimdal/appl/gssmask/Makefile.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/gssmask/Makefile.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 18468 2006-10-14 13:50:51Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/gssmask
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,27 +89,28 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 PROGRAMS =3D $(noinst_PROGRAMS)
 am_gssmaestro_OBJECTS =3D gssmaestro.$(OBJEXT) common.$(OBJEXT)
 gssmaestro_OBJECTS =3D $(am_gssmaestro_OBJECTS)
 gssmaestro_LDADD =3D $(LDADD)
 am__DEPENDENCIES_1 =3D
 gssmaestro_DEPENDENCIES =3D $(top_builddir)/lib/gssapi/libgssapi.la \
-	$(am__DEPENDENCIES_1)
+	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la
 am_gssmask_OBJECTS =3D gssmask.$(OBJEXT) common.$(OBJEXT)
 gssmask_OBJECTS =3D $(am_gssmask_OBJECTS)
 gssmask_LDADD =3D $(LDADD)
 gssmask_DEPENDENCIES =3D $(top_builddir)/lib/gssapi/libgssapi.la \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -123,49 +129,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -189,10 +204,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -209,6 +225,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -224,31 +242,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -263,10 +295,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -307,49 +341,55 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 gssmask_SOURCES =3D gssmask.c common.c common.h protocol.h
 gssmaestro_SOURCES =3D gssmaestro.c common.c common.h protocol.h
-LDADD =3D $(top_builddir)/lib/gssapi/libgssapi.la $(LIB_roken)
+LDADD =3D $(top_builddir)/lib/gssapi/libgssapi.la $(LIB_roken) $(top_build=
dir)/lib/krb5/libkrb5.la
+EXTRA_DIST =3D NTMakefile
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/gssm=
ask/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/gssmask/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/gssmask/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/gssmask/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -367,13 +407,16 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 gssmaestro$(EXEEXT): $(gssmaestro_OBJECTS) $(gssmaestro_DEPENDENCIES)=20
 	@rm -f gssmaestro$(EXEEXT)
 	$(LINK) $(gssmaestro_OBJECTS) $(gssmaestro_LDADD) $(LIBS)
@@ -387,14 +430,30 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/common.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gssmaestro.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gssmask.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -407,45 +466,49 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -466,13 +529,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -504,6 +571,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -514,6 +582,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -524,6 +593,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -531,26 +602,35 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -570,9 +650,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libtool clean-noinstPROGRAMS ctags \
@@ -657,6 +736,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -742,7 +824,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -755,6 +837,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/gssmask/commo=
n.c
--- a/head/crypto/heimdal/appl/gssmask/common.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/gssmask/common.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,7 +32,7 @@
  */
=20
 #include <common.h>
-RCSID("$Id: common.c 18900 2006-11-03 05:21:01Z lha $");
+RCSID("$Id$");
=20
 krb5_error_code
 store_string(krb5_storage *sp, const char *str)
@@ -62,8 +62,8 @@
 }
=20
 static void
-permute(char ****list, size_t *listlen,=20
-	char **str, const int start, const int len)=20
+permute(char ****list, size_t *listlen,
+	char **str, const int start, const int len)
 {
     int i, j;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/gssmask/commo=
n.h
--- a/head/crypto/heimdal/appl/gssmask/common.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/gssmask/common.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -31,13 +31,13 @@
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
=20
-/* $Id: common.h 18250 2006-10-06 07:22:00Z lha $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
=20
-/*=20
+/*
  * pthread support is disable because the pthread
  * test have no "application pthread libflags" variable,
  * when this is fixed pthread support can be enabled again.
@@ -55,7 +55,9 @@
=20
 #include <assert.h>
 #include <krb5.h>
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
+#include <gssapi/gssapi_spnego.h>
 #include <unistd.h>
=20
 #include <roken.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/gssmask/gssma=
estro.c
--- a/head/crypto/heimdal/appl/gssmask/gssmaestro.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/gssmask/gssmaestro.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,7 +32,7 @@
  */
=20
 #include <common.h>
-RCSID("$Id: gssmaestro.c 21605 2007-07-17 06:51:57Z lha $");
+RCSID("$Id$");
=20
 static FILE *logfile;
=20
@@ -61,9 +61,9 @@
 static int num_clients;
=20
 static int
-init_sec_context(struct client *client,=20
+init_sec_context(struct client *client,
 		 int32_t *hContext, int32_t *hCred,
-		 int32_t flags,=20
+		 int32_t flags,
 		 const char *targetname,
 		 const krb5_data *itoken, krb5_data *otoken)
 {
@@ -82,7 +82,7 @@
 }
=20
 static int
-accept_sec_context(struct client *client,=20
+accept_sec_context(struct client *client,
 		   int32_t *hContext,
 		   int32_t flags,
 		   const krb5_data *itoken,
@@ -103,7 +103,7 @@
 }
=20
 static int
-acquire_cred(struct client *client,=20
+acquire_cred(struct client *client,
 	     const char *username,
 	     const char *password,
 	     int32_t flags,
@@ -120,7 +120,7 @@
 }
=20
 static int
-toast_resource(struct client *client,=20
+toast_resource(struct client *client,
 	       int32_t hCred)
 {
     int32_t val;
@@ -138,7 +138,7 @@
 }
=20
 static int
-get_targetname(struct client *client,=20
+get_targetname(struct client *client,
 	       char **target)
 {
     put32(client, eGetTargetName);
@@ -162,7 +162,7 @@
 }
=20
 static int32_t
-decrypt_token(struct client *client, int32_t hContext, int flags,=20
+decrypt_token(struct client *client, int32_t hContext, int flags,
 	     krb5_data *in, krb5_data *out)
 {
     int32_t val;
@@ -177,6 +177,42 @@
 }
=20
 static int32_t
+wrap_token_ext(struct client *client, int32_t hContext, int32_t flags,
+	       int32_t bflags, krb5_data *header, krb5_data *in, krb5_data *trail=
er,
+	       krb5_data *out)
+{
+    int32_t val;
+    put32(client, eWrapExt);
+    put32(client, hContext);
+    put32(client, flags);
+    put32(client, bflags);
+    putdata(client, *header);
+    putdata(client, *in);
+    putdata(client, *trailer);
+    ret32(client, val);
+    retdata(client, *out);
+    return val;
+}
+
+static int32_t
+unwrap_token_ext(struct client *client, int32_t hContext, int32_t flags,
+	       int32_t bflags, krb5_data *header, krb5_data *in, krb5_data *trail=
er,
+	       krb5_data *out)
+{
+    int32_t val;
+    put32(client, eUnwrapExt);
+    put32(client, hContext);
+    put32(client, flags);
+    put32(client, bflags);
+    putdata(client, *header);
+    putdata(client, *in);
+    putdata(client, *trailer);
+    ret32(client, val);
+    retdata(client, *out);
+    return val;
+}
+
+static int32_t
 get_mic(struct client *client, int32_t hContext,
 	krb5_data *in, krb5_data *mic)
 {
@@ -192,7 +228,7 @@
 }
=20
 static int32_t
-verify_mic(struct client *client, int32_t hContext,=20
+verify_mic(struct client *client, int32_t hContext,
 	   krb5_data *in, krb5_data *mic)
 {
     int32_t val;
@@ -208,7 +244,7 @@
=20
=20
 static int32_t
-get_version_capa(struct client *client,=20
+get_version_capa(struct client *client,
 		 int32_t *version, int32_t *capa,
 		 char **version_str)
 {
@@ -220,7 +256,7 @@
 }
=20
 static int32_t
-get_moniker(struct client *client,=20
+get_moniker(struct client *client,
 	    char **moniker)
 {
     put32(client, eGetMoniker);
@@ -291,7 +327,7 @@
     krb5_data_zero(&itoken);
=20
     while (!iDone || !aDone) {
-=09
+
 	if (iDone) {
 	    warnx("iPeer already done, aPeer want extra rtt");
 	    val =3D GSMERR_ERROR;
@@ -310,7 +346,7 @@
 	case GSMERR_CONTINUE_NEEDED:
 	    break;
 	default:
-	    warnx("iPeer %s failed with %d (step %d)",=20
+	    warnx("iPeer %s failed with %d (step %d)",
 		  ipeer->name, (int)val, step);
 	    goto out;
 	}
@@ -369,13 +405,13 @@
 out:
     return val;
 }
-			=20
+
 static void
 test_mic(struct client *c1, int32_t hc1, struct client *c2, int32_t hc2)
 {
     krb5_data msg, mic;
     int32_t val;
-   =20
+
     msg.data =3D "foo";
     msg.length =3D 3;
=20
@@ -392,12 +428,12 @@
 }
=20
 static int32_t
-test_wrap(struct client *c1, int32_t hc1, struct client *c2, int32_t hc2,=20
+test_wrap(struct client *c1, int32_t hc1, struct client *c2, int32_t hc2,
 	  int conf)
 {
     krb5_data msg, wrapped, out;
     int32_t val;
-   =20
+
     msg.data =3D "foo";
     msg.length =3D 3;
=20
@@ -431,22 +467,95 @@
 }
=20
 static int32_t
-test_token(struct client *c1, int32_t hc1, struct client *c2, int32_t hc2)
+test_wrap_ext(struct client *c1, int32_t hc1, struct client *c2, int32_t h=
c2,
+	      int conf, int bflags)
+{
+    krb5_data header, msg, trailer, wrapped, out;
+    int32_t val;
+
+    header.data =3D "header";
+    header.length =3D 6;
+
+    msg.data =3D "0123456789abcdef"; /* padded for most enctypes */
+    msg.length =3D 32;
+
+    trailer.data =3D "trailer";
+    trailer.length =3D 7;
+
+    krb5_data_zero(&wrapped);
+    krb5_data_zero(&out);
+
+    val =3D wrap_token_ext(c1, hc1, conf, bflags, &header, &msg, &trailer,=
 &wrapped);
+    if (val) {
+	warnx("encrypt_token failed to host: %s", c1->moniker);
+	return val;
+    }
+    val =3D unwrap_token_ext(c2, hc2, conf, bflags, &header, &wrapped, &tr=
ailer, &out);
+    if (val) {
+	krb5_data_free(&wrapped);
+	warnx("decrypt_token failed to host: %s", c2->moniker);
+	return val;
+    }
+
+    if (msg.length !=3D out.length) {
+	warnx("decrypted'ed token have wrong length (%lu !=3D %lu)",
+	      (unsigned long)msg.length, (unsigned long)out.length);
+	val =3D GSMERR_ERROR;
+    } else if (memcmp(msg.data, out.data, msg.length) !=3D 0) {
+	warnx("decryptd'ed token have wrong data");
+	val =3D GSMERR_ERROR;
+    }
+
+    krb5_data_free(&wrapped);
+    krb5_data_free(&out);
+    return val;
+}
+
+
+static int32_t
+test_token(struct client *c1, int32_t hc1, struct client *c2, int32_t hc2,=
 int wrap_ext)
 {
     int32_t val;
     int i;
=20
     for (i =3D 0; i < 10; i++) {
+	/* mic */
 	test_mic(c1, hc1, c2, hc2);
 	test_mic(c2, hc2, c1, hc1);
+
+	/* wrap */
 	val =3D test_wrap(c1, hc1, c2, hc2, 0);
 	if (val) return val;
 	val =3D test_wrap(c2, hc2, c1, hc1, 0);
 	if (val) return val;
+
 	val =3D test_wrap(c1, hc1, c2, hc2, 1);
 	if (val) return val;
 	val =3D test_wrap(c2, hc2, c1, hc1, 1);
 	if (val) return val;
+
+	if (wrap_ext) {
+	    /* wrap ext */
+	    val =3D test_wrap_ext(c1, hc1, c2, hc2, 1, 0);
+	    if (val) return val;
+	    val =3D test_wrap_ext(c2, hc2, c1, hc1, 1, 0);
+	    if (val) return val;
+
+	    val =3D test_wrap_ext(c1, hc1, c2, hc2, 1, 1);
+	    if (val) return val;
+	    val =3D test_wrap_ext(c2, hc2, c1, hc1, 1, 1);
+	    if (val) return val;
+
+	    val =3D test_wrap_ext(c1, hc1, c2, hc2, 0, 0);
+	    if (val) return val;
+	    val =3D test_wrap_ext(c2, hc2, c1, hc1, 0, 0);
+	    if (val) return val;
+
+	    val =3D test_wrap_ext(c1, hc1, c2, hc2, 0, 1);
+	    if (val) return val;
+	    val =3D test_wrap_ext(c2, hc2, c1, hc1, 0, 1);
+	    if (val) return val;
+	}
     }
     return GSMERR_OK;
 }
@@ -476,9 +585,9 @@
 		goto out;
 	    if (krb5_ret_string(c->logsock, &string))
 		goto out;
-	    printf("%s:%lu: %s\n",=20
+	    printf("%s:%lu: %s\n",
 		   file, (unsigned long)line, string);
-	    fprintf(logfile, "%s:%lu: %s\n",=20
+	    fprintf(logfile, "%s:%lu: %s\n",
 		    file, (unsigned long)line, string);
 	    fflush(logfile);
 	    free(file);
@@ -510,7 +619,7 @@
     *port++ =3D 0;
=20
     c->name =3D estrdup(slave);
-   =20
+
     memset(&hints, 0, sizeof(hints));
     hints.ai_family =3D PF_UNSPEC;
     hints.ai_socktype =3D SOCK_STREAM;
@@ -584,7 +693,7 @@
=20
=20
     clients =3D erealloc(clients, (num_clients + 1) * sizeof(*clients));
-   =20
+
     clients[num_clients] =3D c;
     num_clients++;
=20
@@ -607,6 +716,7 @@
=20
 static int version_flag;
 static int help_flag;
+static int wrap_ext =3D 0;
 static char *logfile_str;
 static getarg_strings principals;
 static getarg_strings slaves;
@@ -618,6 +728,8 @@
       NULL },
     { "log-file", 0, arg_string,	&logfile_str,	"Logfile",
       NULL },
+    { "wrap-ext", 0,  arg_flag,		&wrap_ext,	"test wrap extended",
+      NULL },
     { "version", 0,  arg_flag,		&version_flag,	"Print version",
       NULL },
     { "help",	 0,  arg_flag,		&help_flag,	NULL,
@@ -668,7 +780,7 @@
     if (password =3D=3D NULL)
 	errx(1, "password missing from %s", user);
     *password++ =3D 0;
-=09
+
     if (slaves.num_strings =3D=3D 0)
 	errx(1, "no principals");
=20
@@ -703,7 +815,7 @@
=20
 	val =3D acquire_cred(clients[i], user, password, 1, &hCred);
 	if (val !=3D GSMERR_OK) {
-	    warnx("Failed to acquire_cred on host %s: %d",=20
+	    warnx("Failed to acquire_cred on host %s: %d",
 		 clients[i]->moniker, (int)val);
 	    failed =3D 1;
 	} else
@@ -713,7 +825,7 @@
     if (failed)
 	goto out;
=20
-    /*=20
+    /*
      * First test if all slaves can build context to them-self.
      */
=20
@@ -722,7 +834,7 @@
 	int32_t hCred, val, delegCred;
 	int32_t clientC, serverC;
 	struct client *c =3D clients[i];
-=09
+
 	if (c->target_name =3D=3D NULL)
 	    continue;
=20
@@ -732,14 +844,14 @@
 	val =3D acquire_cred(c, user, password, 1, &hCred);
 	if (val !=3D GSMERR_OK)
 	    errx(1, "failed to acquire_cred: %d", (int)val);
-   =20
-	val =3D build_context(c, c,=20
+
+	val =3D build_context(c, c,
 			    GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG|
 			    GSS_C_INTEG_FLAG|GSS_C_CONF_FLAG|
 			    GSS_C_DELEG_FLAG|GSS_C_MUTUAL_FLAG,
 			    hCred, &clientC, &serverC, &delegCred);
 	if (val =3D=3D GSMERR_OK) {
-	    test_token(c, clientC, c, serverC);
+	    test_token(c, clientC, c, serverC, wrap_ext);
 	    toast_resource(c, clientC);
 	    toast_resource(c, serverC);
 	    if (delegCred)
@@ -755,7 +867,7 @@
 			    GSS_C_INTEG_FLAG|GSS_C_CONF_FLAG,
 			    hCred, &clientC, &serverC, &delegCred);
 	if (val =3D=3D GSMERR_OK) {
-	    test_token(c, clientC, c, serverC);
+	    test_token(c, clientC, c, serverC, wrap_ext);
 	    toast_resource(c, clientC);
 	    toast_resource(c, serverC);
 	    if (delegCred)
@@ -781,18 +893,18 @@
 	int32_t hCred, val, delegCred =3D 0;
 	int32_t clientC =3D 0, serverC =3D 0;
 	struct client *client, *server;
-=09
+
 	p =3D list[i];
-=09
+
 	client =3D get_client(p[0]);
-=09
+
 	val =3D acquire_cred(client, user, password, 1, &hCred);
 	if (val !=3D GSMERR_OK)
 	    errx(1, "failed to acquire_cred: %d", (int)val);
=20
 	for (j =3D 1; j < num_clients + 1; j++) {
 	    server =3D get_client(p[j % num_clients]);
-	   =20
+
 	    if (server->target_name =3D=3D NULL)
 		break;
=20
@@ -809,11 +921,11 @@
 		warnx("build_context failed: %d", (int)val);
 		break;
 	    }
-	   =20
-	    val =3D test_token(client, clientC, server, serverC);
+
+	    val =3D test_token(client, clientC, server, serverC, wrap_ext);
 	    if (val)
 		break;
-	   =20
+
 	    toast_resource(client, clientC);
 	    toast_resource(server, serverC);
 	    if (!delegCred) {
@@ -827,11 +939,11 @@
 	if (hCred)
 	    toast_resource(client, hCred);
     }
-   =20
+
     /*
      * Close all connections to clients
      */
-   =20
+
 out:
     printf("sending goodbye and waiting for log sockets\n");
     for (i =3D 0; i < num_clients; i++) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/gssmask/gssma=
sk.c
--- a/head/crypto/heimdal/appl/gssmask/gssmask.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/gssmask/gssmask.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,7 +32,7 @@
  */
=20
 #include "common.h"
-RCSID("$Id: gssmask.c 21229 2007-06-20 10:19:19Z lha $");
+RCSID("$Id$");
=20
 /*
  *
@@ -151,7 +151,7 @@
 {
     if (idx =3D=3D 0)
 	return NULL;
-   =20
+
     while (h) {
 	if (h->idx =3D=3D idx) {
 	    if (type =3D=3D h->type)
@@ -160,7 +160,7 @@
 	}
 	h =3D h->next;
     }
-    return NULL;   =20
+    return NULL;
 }
=20
=20
@@ -229,7 +229,7 @@
 		   "krb5_get_init_creds failed: %d", ret);
 	return convert_krb5_to_gsm(ret);
     }
-=09
+
     ret =3D krb5_cc_new_unique(context, "MEMORY", NULL, &id);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_initialize");
@@ -237,7 +237,7 @@
     ret =3D krb5_cc_initialize (context, id, cred.client);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_initialize");
-   =20
+
     ret =3D krb5_cc_store_cred (context, id, &cred);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_store_cred");
@@ -284,14 +284,14 @@
 HandleOP(GoodBye)
 {
     struct handle *h =3D c->handles;
-    int i =3D 0;
+    unsigned int i =3D 0;
=20
     while (h) {
 	h =3D h->next;
 	i++;
     }
=20
-    if (i !=3D 0)
+    if (i)
 	logmessage(c, __FILE__, __LINE__, 0,
 		   "Did not toast all resources: %d", i);
     return 1;
@@ -358,7 +358,7 @@
 	if (ctx)
 	    krb5_errx(context, 1, "initcreds, context not NULL, but first req");
     }
-=09
+
     if ((flags & GSS_C_DELEG_FLAG) !=3D 0)
 	logmessage(c, __FILE__, __LINE__, 0, "init_sec_context delegating");
     if ((flags & GSS_C_DCE_STYLE) !=3D 0)
@@ -370,7 +370,7 @@
 				    gss_target_name,
 				    oid,
 				    flags & 0x7f,
-				    0,=20
+				    0,
 				    NULL,
 				    input_token_ptr,
 				    NULL,
@@ -382,7 +382,7 @@
 	    del_handle(&c->handles, hContext);
 	new_context_id =3D 0;
 	logmessage(c, __FILE__, __LINE__, 0,
-		   "gss_init_sec_context returns code: %d/%d",=20
+		   "gss_init_sec_context returns code: %d/%d",
 		   maj_stat, min_stat);
     } else {
 	if (input_token.length =3D=3D 0)
@@ -461,7 +461,7 @@
 	if (hContext !=3D 0)
 	    del_handle(&c->handles, hContext);
 	logmessage(c, __FILE__, __LINE__, 0,
-		   "gss_accept_sec_context returns code: %d/%d",=20
+		   "gss_accept_sec_context returns code: %d/%d",
 		   maj_stat, min_stat);
 	new_context_id =3D 0;
     } else {
@@ -484,8 +484,8 @@
 	gss_release_cred(&min_stat, &deleg_cred);
 	deleg_hcred =3D 0;
     }
-	=20
-   =20
+
+
     gsm_error =3D convert_gss_to_gsm(maj_stat);
=20
     put32(c, new_context_id);
@@ -534,11 +534,11 @@
 	gsm_error =3D convert_krb5_to_gsm(ret);
 	goto out;
     }
-   =20
+
     ret =3D krb5_get_init_creds_opt_alloc (context, &opt);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");
-   =20
+
     krb5_get_init_creds_opt_set_pa_password(context, opt, password, NULL);
=20
     gsm_error =3D acquire_cred(c, principal, opt, &handle);
@@ -580,22 +580,22 @@
=20
     input_token.length =3D token.length;
     input_token.value =3D token.data;
-   =20
+
     maj_stat =3D gss_get_mic(&min_stat, ctx, 0, &input_token,
 			   &output_token);
     if (maj_stat !=3D GSS_S_COMPLETE)
 	errx(1, "gss_get_mic failed");
-   =20
+
     krb5_data_free(&token);
-   =20
+
     token.data =3D output_token.value;
     token.length =3D output_token.length;
-   =20
+
     put32(c, 0); /* XXX fix gsm_error */
     putdata(c, token);
-   =20
+
     gss_release_buffer(&min_stat, &output_token);
-   =20
+
     return 0;
 }
=20
@@ -621,7 +621,7 @@
=20
     msg_token.length =3D msg.length;
     msg_token.value =3D msg.data;
-   =20
+
     retdata(c, mic);
=20
     mic_token.length =3D mic.length;
@@ -631,12 +631,12 @@
 			      &mic_token, &qop);
     if (maj_stat !=3D GSS_S_COMPLETE)
 	errx(1, "gss_verify_mic failed");
-   =20
+
     krb5_data_free(&mic);
     krb5_data_free(&msg);
-   =20
+
     put32(c, 0); /* XXX fix gsm_error */
-   =20
+
     return 0;
 }
=20
@@ -653,7 +653,7 @@
     {
 	struct utsname ut;
 	if (uname(&ut) =3D=3D 0) {
-	    snprintf(name, sizeof(name), "%s-%s-%s",=20
+	    snprintf(name, sizeof(name), "%s-%s-%s",
 		     ut.sysname, ut.version, ut.machine);
 	}
     }
@@ -663,7 +663,7 @@
=20
     put32(c, GSSMAGGOTPROTOCOL);
     put32(c, cap);
-    putstring(c, str);=20
+    putstring(c, str);
     free(str);
=20
     return 0;
@@ -711,12 +711,12 @@
=20
     krb5_store_int32(c->logging, eLogSetMoniker);
     store_string(c->logging, c->moniker);
-   =20
+
     logmessage(c, __FILE__, __LINE__, 0, "logging turned on");
=20
     return 0;
 }
-   =20
+
=20
 static int
 HandleOP(ChangePassword)
@@ -751,22 +751,22 @@
=20
     input_token.length =3D token.length;
     input_token.value =3D token.data;
-   =20
+
     maj_stat =3D gss_wrap(&min_stat, ctx, flags, 0, &input_token,
 			&conf_state, &output_token);
     if (maj_stat !=3D GSS_S_COMPLETE)
 	errx(1, "gss_wrap failed");
-   =20
+
     krb5_data_free(&token);
-   =20
+
     token.data =3D output_token.value;
     token.length =3D output_token.length;
-   =20
+
     put32(c, 0); /* XXX fix gsm_error */
     putdata(c, token);
-   =20
+
     gss_release_buffer(&min_stat, &output_token);
-   =20
+
     return 0;
 }
=20
@@ -793,13 +793,13 @@
=20
     input_token.length =3D token.length;
     input_token.value =3D token.data;
-   =20
+
     maj_stat =3D gss_unwrap(&min_stat, ctx, &input_token,
 			  &output_token, &conf_state, &qop_state);
-   =20
+
     if (maj_stat !=3D GSS_S_COMPLETE)
 	errx(1, "gss_unwrap failed: %d/%d", maj_stat, min_stat);
-=09
+
     krb5_data_free(&token);
     if (maj_stat =3D=3D GSS_S_COMPLETE) {
 	token.data =3D output_token.value;
@@ -853,19 +853,180 @@
 {
     int32_t flags;
     krb5_data pfxdata;
+    char fn[] =3D "FILE:/tmp/pkcs12-creds-XXXXXXX";
+    krb5_principal principal =3D NULL;
+    int fd;
=20
     ret32(c, flags);
     retdata(c, pfxdata);
=20
-    /* get credentials */
+    fd =3D mkstemp(fn + 5);
+    if (fd < 0)
+	errx(1, "mkstemp");
=20
+    net_write(fd, pfxdata.data, pfxdata.length);
     krb5_data_free(&pfxdata);
+    close(fd);
+
+    if (principal)
+	krb5_free_principal(context, principal);
=20
     put32(c, -1); /* hResource */
     put32(c, GSMERR_NOT_SUPPORTED);
     return 0;
 }
=20
+static int
+HandleOP(WrapExt)
+{
+    OM_uint32 maj_stat, min_stat;
+    int32_t hContext, flags, bflags;
+    krb5_data token, header, trailer;
+    gss_ctx_id_t ctx;
+    unsigned char *p;
+    int conf_state, iov_len;
+    gss_iov_buffer_desc iov[6];
+
+    ret32(c, hContext);
+    ret32(c, flags);
+    ret32(c, bflags);
+    retdata(c, header);
+    retdata(c, token);
+    retdata(c, trailer);
+
+    ctx =3D find_handle(c->handles, hContext, handle_context);
+    if (ctx =3D=3D NULL)
+	errx(1, "wrap: reference to unknown context");
+
+    memset(&iov, 0, sizeof(iov));
+
+    iov_len =3D sizeof(iov)/sizeof(iov[0]);
+
+    if (bflags & WRAP_EXP_ONLY_HEADER)
+	iov_len -=3D 2; /* skip trailer and padding, aka dce-style */
+
+    iov[0].type =3D GSS_IOV_BUFFER_TYPE_HEADER | GSS_IOV_BUFFER_TYPE_FLAG_=
ALLOCATE;
+    if (header.length !=3D 0) {
+	iov[1].type =3D GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+	iov[1].buffer.length =3D header.length;
+	iov[1].buffer.value =3D header.data;
+    } else {
+	iov[1].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+    }
+    iov[2].type =3D GSS_IOV_BUFFER_TYPE_DATA;
+    iov[2].buffer.length =3D token.length;
+    iov[2].buffer.value =3D token.data;
+    if (trailer.length !=3D 0) {
+	iov[3].type =3D GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+	iov[3].buffer.length =3D trailer.length;
+	iov[3].buffer.value =3D trailer.data;
+    } else {
+	iov[3].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+    }
+    iov[4].type =3D GSS_IOV_BUFFER_TYPE_PADDING | GSS_IOV_BUFFER_TYPE_FLAG=
_ALLOCATE;
+    iov[5].type =3D GSS_IOV_BUFFER_TYPE_TRAILER | GSS_IOV_BUFFER_TYPE_FLAG=
_ALLOCATE;
+
+    maj_stat =3D gss_wrap_iov_length(&min_stat, ctx, flags, 0, &conf_state,
+				   iov, iov_len);
+    if (maj_stat !=3D GSS_S_COMPLETE)
+	errx(1, "gss_wrap_iov_length failed");
+
+    maj_stat =3D gss_wrap_iov(&min_stat, ctx, flags, 0, &conf_state,
+			    iov, iov_len);
+    if (maj_stat !=3D GSS_S_COMPLETE)
+	errx(1, "gss_wrap_iov failed");
+
+    krb5_data_free(&token);
+
+    token.length =3D iov[0].buffer.length + iov[2].buffer.length + iov[4].=
buffer.length + iov[5].buffer.length;
+    token.data =3D malloc(token.length);
+
+    p =3D token.data;
+    memcpy(p, iov[0].buffer.value, iov[0].buffer.length);
+    p +=3D iov[0].buffer.length;
+    memcpy(p, iov[2].buffer.value, iov[2].buffer.length);
+    p +=3D iov[2].buffer.length;
+    memcpy(p, iov[4].buffer.value, iov[4].buffer.length);
+    p +=3D iov[4].buffer.length;
+    memcpy(p, iov[5].buffer.value, iov[5].buffer.length);
+    p +=3D iov[5].buffer.length;
+
+    gss_release_iov_buffer(NULL, iov, iov_len);
+
+    put32(c, 0); /* XXX fix gsm_error */
+    putdata(c, token);
+
+    free(token.data);
+
+    return 0;
+}
+
+
+static int
+HandleOP(UnwrapExt)
+{
+    OM_uint32 maj_stat, min_stat;
+    int32_t hContext, flags, bflags;
+    krb5_data token, header, trailer;
+    gss_ctx_id_t ctx;
+    gss_iov_buffer_desc iov[3];
+    int conf_state, iov_len;
+    gss_qop_t qop_state;
+
+    ret32(c, hContext);
+    ret32(c, flags);
+    ret32(c, bflags);
+    retdata(c, header);
+    retdata(c, token);
+    retdata(c, trailer);
+
+    iov_len =3D sizeof(iov)/sizeof(iov[0]);
+
+    if (bflags & WRAP_EXP_ONLY_HEADER)
+	iov_len -=3D 1; /* skip trailer and padding, aka dce-style */
+
+    ctx =3D find_handle(c->handles, hContext, handle_context);
+    if (ctx =3D=3D NULL)
+	errx(1, "unwrap: reference to unknown context");
+
+    if (header.length !=3D 0) {
+	iov[0].type =3D GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+	iov[0].buffer.length =3D header.length;
+	iov[0].buffer.value =3D header.data;
+    } else {
+	iov[0].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+    }
+    iov[1].type =3D GSS_IOV_BUFFER_TYPE_DATA;
+    iov[1].buffer.length =3D token.length;
+    iov[1].buffer.value =3D token.data;
+
+    if (trailer.length !=3D 0) {
+	iov[2].type =3D GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+	iov[2].buffer.length =3D trailer.length;
+	iov[2].buffer.value =3D trailer.data;
+    } else {
+	iov[2].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+    }
+
+    maj_stat =3D gss_unwrap_iov(&min_stat, ctx, &conf_state, &qop_state,
+			      iov, iov_len);
+
+    if (maj_stat !=3D GSS_S_COMPLETE)
+	errx(1, "gss_unwrap failed: %d/%d", maj_stat, min_stat);
+
+    if (maj_stat =3D=3D GSS_S_COMPLETE) {
+	token.data =3D iov[1].buffer.value;
+	token.length =3D iov[1].buffer.length;
+    } else {
+	token.data =3D NULL;
+	token.length =3D 0;
+    }
+    put32(c, 0); /* XXX fix gsm_error */
+    putdata(c, token);
+
+    return 0;
+}
+
 /*
  *
  */
@@ -899,7 +1060,9 @@
     S(ConnectLoggingService2),
     S(GetMoniker),
     S(CallExtension),
-    S(AcquirePKInitCreds)
+    S(AcquirePKInitCreds),
+    S(WrapExt),
+    S(UnwrapExt),
 };
=20
 #undef S
@@ -937,16 +1100,16 @@
     {
 	c->salen =3D sizeof(c->sa);
 	getpeername(fd, (struct sockaddr *)&c->sa, &c->salen);
-=09
-	getnameinfo((struct sockaddr *)&c->sa, c->salen,=20
-		    c->servername, sizeof(c->servername),=20
+
+	getnameinfo((struct sockaddr *)&c->sa, c->salen,
+		    c->servername, sizeof(c->servername),
 		    NULL, 0, NI_NUMERICHOST);
     }
=20
     c->sock =3D krb5_storage_from_fd(fd);
     if (c->sock =3D=3D NULL)
 	errx(1, "krb5_storage_from_fd");
-   =20
+
     close(fd);
=20
     return c;
@@ -987,7 +1150,7 @@
 	}
=20
 	logmessage(c, __FILE__, __LINE__, 0,
-		   "---> Got op %s from server %s",=20
+		   "---> Got op %s from server %s",
 		   handler->name, c->servername);
=20
 	if ((handler->func)(handler->op, c))
@@ -1072,11 +1235,11 @@
 	    err(1, "error opening %s", lf);
     }
=20
-    mini_inetd(htons(port));
+    mini_inetd(htons(port), NULL);
     fprintf(logfile, "connected\n");
=20
     {
-	struct client *c;=20
+	struct client *c;
=20
 	c =3D create_client(0, port, moniker_str);
 	/* close(0); */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/gssmask/proto=
col.h
--- a/head/crypto/heimdal/appl/gssmask/protocol.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/gssmask/protocol.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,7 +32,7 @@
  */
=20
 /*
- * $Id: protocol.h 18352 2006-10-08 13:53:28Z lha $
+ * $Id$
  */
=20
 /* missing from tests:
@@ -63,9 +63,9 @@
  *   int32: message OP (enum gssMaggotProtocol)
  *   ...
  *
- * return:   -- on error=20
+ * return:   -- on error
  *    int32: not support (GSMERR_NOT_SUPPORTED)
- *=20
+ *
  * return:   -- on existing message OP
  *    int32: support (GSMERR_OK) -- only sent for extensions
  *    ...
@@ -75,28 +75,28 @@
=20
 enum gssMaggotOp {
     eGetVersionInfo	=3D 0,
-    /*=20
+    /*
      * input:
      *   none
      * return:
-     *   int32: last version handled=20
+     *   int32: last version handled
      */
     eGoodBye,
-    /*=20
+    /*
      * input:
      *   none
      * return:
      *   close socket
      */
     eInitContext,
-    /*=20
+    /*
      * input:
      *   int32: hContext
      *   int32: hCred
      *   int32: Flags
      *      the lowest 0x7f flags maps directly to GSS-API flags
-     *      DELEGATE		0x001=20
-     *      MUTUAL_AUTH		0x002=20
+     *      DELEGATE		0x001
+     *      MUTUAL_AUTH		0x002
      *      REPLAY_DETECT	0x004
      *      SEQUENCE_DETECT	0x008
      *      CONFIDENTIALITY	0x010
@@ -115,7 +115,7 @@
      *   length-encoded: output token
      */
     eAcceptContext,
-    /*=20
+    /*
      * input:
      *   int32: hContext
      *   int32: Flags		-- unused ?
@@ -153,7 +153,7 @@
     /*
      * input:
      *   int32: hContext
-     *   int32: flags		-- unused
+     *   int32: flags
      *   int32: seqno		-- unused
      *   length-encode: plaintext
      * return:
@@ -164,7 +164,7 @@
     /*
      * input:
      *   int32: hContext
-     *   int32: flags		-- unused
+     *   int32: flags
      *   int32: seqno		-- unused
      *   length-encode: ciphertext
      * return:
@@ -177,7 +177,7 @@
     /*
      * input:
      *   int32: hContext
-     *   int32: flags		-- unused
+     *   int32: flags
      *   int32: seqno		-- unused
      *   length-encode: message
      *   length-encode: signature
@@ -229,7 +229,7 @@
      * return1:
      *   int16: log port number
      *   int32: master log prototocol version (0)
-     *=20
+     *
      * wait for master to connect on the master log socket
      *
      * return2:
@@ -259,9 +259,40 @@
      *   int32: gsm status val (GSMERR_NOT_SUPPORTED)
      */
     /* here ended version 7 of the protocol */
+    eWrapExt,
+    /*
+     * input:
+     *   int32: hContext
+     *   int32: flags
+     *   int32: bflags
+     *   length-encode: protocol header
+     *   length-encode: plaintext
+     *   length-encode: protocol trailer
+     * return:
+     *   int32: gsm status val
+     *   length-encode: ciphertext
+     */
+    eUnwrapExt,
+    /*
+     * input:
+     *   int32: hContext
+     *   int32: flags
+     *   int32: bflags
+     *   length-encode: protocol header
+     *   length-encode: ciphertext
+     *   length-encode: protocol trailer
+     * return:
+     *   int32: gsm status val
+     *   length-encode: plaintext
+     */
+    /* here ended version 8 of the protocol */
+
     eLastProtocolMessage
 };
=20
+/* bflags */
+#define WRAP_EXP_ONLY_HEADER 1
+
 enum gssMaggotLogOp{
   eLogInfo =3D 0,
 	/*
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/kf/Makefile.am
--- a/head/crypto/heimdal/appl/kf/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/kf/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -17,4 +17,4 @@
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/kf/Makefile.in
--- a/head/crypto/heimdal/appl/kf/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/kf/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -46,7 +48,7 @@
 subdir =3D appl/kf
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -61,7 +63,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -75,9 +77,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -85,16 +90,15 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" \
 	"$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS) $(libexec_PROGRAMS)
 am_kf_OBJECTS =3D kf.$(OBJEXT)
 kf_OBJECTS =3D $(am_kf_OBJECTS)
@@ -109,9 +113,9 @@
 kfd_DEPENDENCIES =3D $(top_builddir)/lib/krb5/libkrb5.la \
 	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
 	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -123,6 +127,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(kf_SOURCES) $(kfd_SOURCES)
 DIST_SOURCES =3D $(kf_SOURCES) $(kfd_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
@@ -133,49 +158,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -199,10 +233,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -219,6 +254,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -234,31 +271,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -273,10 +324,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -317,29 +370,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 man_MANS =3D kf.1 kfd.8
 kf_SOURCES =3D kf.c kf_locl.h
@@ -349,23 +407,23 @@
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/kf/M=
akefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/kf/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/kf/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/kf/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -383,62 +441,93 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 kf$(EXEEXT): $(kf_OBJECTS) $(kf_DEPENDENCIES)=20
 	@rm -f kf$(EXEEXT)
 	$(LINK) $(kf_OBJECTS) $(kf_LDADD) $(LIBS)
@@ -452,160 +541,178 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kf.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kfd.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
-install-man8: $(man8_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -621,13 +728,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -662,6 +773,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -672,6 +784,7 @@
 	clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -682,6 +795,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -689,26 +804,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -729,11 +853,10 @@
 	uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1 uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libexecPROGRAMS \
@@ -822,6 +945,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -907,7 +1033,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -920,6 +1046,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/kf/kf.1
--- a/head/crypto/heimdal/appl/kf/kf.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/kf/kf.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2000 - 2001 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2000 - 2001 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: kf.1 11986 2003-04-11 12:43:57Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd July  2, 2000
 .Dt KF 1
@@ -41,20 +41,20 @@
 .Nm
 .Oo
 .Fl p Ar port |
-.Fl -port Ns =3D Ns Ar port
+.Fl Fl port Ns =3D Ns Ar port
 .Oc
 .Oo
 .Fl l Ar login |
-.Fl -login Ns =3D Ns Ar login
+.Fl Fl login Ns =3D Ns Ar login
 .Oc
 .Oo
 .Fl c Ar ccache |
-.Fl -ccache Ns =3D Ns Ar ccache
+.Fl Fl ccache Ns =3D Ns Ar ccache
 .Oc
 .Op Fl F | -forwardable
 .Op Fl G | -no-forwardable
 .Op Fl h | -help
-.Op Fl -version
+.Op Fl Fl version
 .Ar host ...
 .Sh DESCRIPTION
 The
@@ -65,17 +65,17 @@
 .Bl -tag -width indent
 .It Xo
 .Fl p Ar port ,
-.Fl -port Ns =3D Ns Ar port
+.Fl Fl port Ns =3D Ns Ar port
 .Xc
 port to connect to
 .It Xo
 .Fl l Ar login ,
-.Fl -login Ns =3D Ns Ar login
+.Fl Fl login Ns =3D Ns Ar login
 .Xc
 remote login name
 .It Xo
 .Fl c Ar ccache ,
-.Fl -ccache Ns =3D Ns Ar ccache
+.Fl Fl ccache Ns =3D Ns Ar ccache
 .Xc
 remote cred cache
 .It Fl F , -forwardable
@@ -83,7 +83,7 @@
 .It Fl G , -no-forwardable
 do not forward forwardable credentials
 .It Fl h , -help
-.It Fl -version
+.It Fl Fl version
 .El
 .Pp
 .Nm
@@ -94,7 +94,7 @@
 .Nm
 to work you will need to acquire your initial ticket with forwardable
 flag, i.e.
-.Nm kinit Fl -forwardable .
+.Nm kinit Fl Fl forwardable .
 .Pp
 .Nm telnet
 is able to forward tickets by itself.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/kf/kf.c
--- a/head/crypto/heimdal/appl/kf/kf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/kf/kf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997 - 2000, 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000, 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kf_locl.h"
-RCSID("$Id: kf.c 11400 2002-09-05 15:00:03Z joda $");
+RCSID("$Id$");
=20
 krb5_context context;
 static int help_flag;
@@ -72,16 +72,16 @@
     int status;
=20
     setprogname (argv[0]);
-=20
+
     status =3D krb5_init_context (context);
     if (status)
 	errx(1, "krb5_init_context failed: %d", status);
-=20
+
     forwardable =3D krb5_config_get_bool (*context, NULL,
 					"libdefaults",
 					"forwardable",
-					NULL);=20
-=20
+					NULL);
+
     if (getarg (args, num_args, *argc, argv, &optind))
 	usage(1, args, num_args);
=20
@@ -91,7 +91,7 @@
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     if(port_str) {
 	struct servent *s =3D roken_getservbyname(port_str, "tcp");
 	if(s)
@@ -108,7 +108,7 @@
=20
     if (port =3D=3D 0)
 	port =3D krb5_getportbyname (*context, KF_PORT_NAME, "tcp", KF_PORT_NUM);
-  =20
+
     if(*argc - optind < 1)
         usage(1, args, num_args);
     *argc =3D optind;
@@ -146,6 +146,7 @@
 					     auth_context,
 					     &sock);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_auth_con_setaddr");
 	return 1;
     }
@@ -156,6 +157,7 @@
 				      KRB5_NT_SRV_HST,
 				      &server);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_sname_to_principal");
 	return 1;
     }
@@ -174,6 +176,7 @@
 			    NULL,
 			    NULL);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn(context, status, "krb5_sendauth");
 	return 1;
     }
@@ -185,6 +188,7 @@
     data_send.length =3D strlen(remote_name) + 1;
     status =3D krb5_write_priv_message(context, auth_context, &sock, &data=
_send);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_write_message");
 	return 1;
     }
@@ -192,6 +196,7 @@
     data_send.length =3D strlen(ccache_name)+1;
     status =3D krb5_write_priv_message(context, auth_context, &sock, &data=
_send);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_write_message");
 	return 1;
     }
@@ -200,18 +205,20 @@
=20
     status =3D krb5_cc_default (context, &ccache);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_cc_default");
 	return 1;
     }
=20
     status =3D krb5_cc_get_principal (context, ccache, &principal);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_cc_get_principal");
 	return 1;
     }
=20
     creds.client =3D principal;
-   =20
+
     status =3D krb5_make_principal (context,
 				  &creds.server,
 				  principal->realm,
@@ -220,6 +227,7 @@
 				  NULL);
=20
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_make_principal");
 	return 1;
     }
@@ -238,6 +246,7 @@
 				       &creds,
 				       &data);
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_get_forwarded_creds");
 	return 1;
     }
@@ -245,13 +254,15 @@
     status =3D krb5_write_priv_message(context, auth_context, &sock, &data=
);
=20
     if (status) {
+	krb5_auth_con_free(context, auth_context);
 	krb5_warn (context, status, "krb5_mk_priv");
 	return 1;
     }
-   =20
+
     krb5_data_free (&data);
=20
     status =3D krb5_read_priv_message(context, auth_context, &sock, &data);
+    krb5_auth_con_free(context, auth_context);
     if (status) {
 	krb5_warn (context, status, "krb5_mk_priv");
 	return 1;
@@ -270,7 +281,7 @@
 }
=20
 static int
-doit (const char *hostname, int port, const char *service,=20
+doit (const char *hostname, int port, const char *service,
       char *message, size_t len)
 {
     struct addrinfo *ai, *a;
@@ -313,7 +324,7 @@
 {
     int argcc,port,i;
     int ret=3D0;
-=20
+
     argcc =3D argc;
     port =3D client_setup(&context, &argcc, argv);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/kf/kf_locl.h
--- a/head/crypto/heimdal/appl/kf/kf_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/kf/kf_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 1999, 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999, 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: kf_locl.h 11376 2002-09-04 20:29:04Z joda $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/kf/kfd.8
--- a/head/crypto/heimdal/appl/kf/kfd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/kf/kfd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2000 - 2002 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2000 - 2002 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: kfd.8 11648 2003-02-16 21:10:32Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd July  2, 2000
 .Dt KFD 8
@@ -41,15 +41,15 @@
 .Nm
 .Oo
 .Fl p Ar port |
-.Fl -port Ns =3D Ns Ar port
+.Fl Fl port Ns =3D Ns Ar port
 .Oc
 .Op Fl i | -inetd
 .Oo
 .Fl R Ar regpag |
-.Fl -regpag Ns =3D Ns Ar regpag
+.Fl Fl regpag Ns =3D Ns Ar regpag
 .Oc
 .Op Fl h | -help
-.Op Fl -version
+.Op Fl Fl version
 .Sh DESCRIPTION
 This is the daemon for
 .Xr kf 1 .
@@ -57,14 +57,14 @@
 .Bl -tag -width indent
 .It Xo
 .Fl p Ar port ,
-.Fl -port Ns =3D Ns Ar port
+.Fl Fl port Ns =3D Ns Ar port
 .Xc
 port to listen to
 .It Fl i , -inetd
 not started from inetd
 .It Xo
 .Fl R Ar regpag ,
-.Fl -regpag=3D Ns Ar regpag
+.Fl Fl regpag=3D Ns Ar regpag
 .Xc
 path to regpag binary
 .El
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/kf/kfd.c
--- a/head/crypto/heimdal/appl/kf/kfd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/kf/kfd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kf_locl.h"
-RCSID("$Id: kfd.c 15246 2005-05-27 13:47:20Z lha $");
+RCSID("$Id$");
=20
 krb5_context context;
 char krb5_tkfile[MAXPATHLEN];
@@ -76,7 +76,7 @@
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     if(port_str){
 	struct servent *s =3D roken_getservbyname(port_str, "tcp");
 	if(s)
@@ -96,7 +96,7 @@
=20
     if(argv[local_argc] !=3D NULL)
         usage(1, args, num_args);
-   =20
+
     return port;
 }
=20
@@ -189,7 +189,7 @@
 				   &sock, &remotename);
     if (status)
 	krb5_err(context, 1, status, "krb5_read_message");
-    status=3Dkrb5_read_priv_message (context, auth_context,=20
+    status=3Dkrb5_read_priv_message (context, auth_context,
 				   &sock, &tk_file);
     if (status)
 	krb5_err(context, 1, status, "krb5_read_message");
@@ -274,14 +274,17 @@
=20
     data.data =3D ret_string;
     data.length =3D strlen(ret_string) + 1;
-    return krb5_write_priv_message(context, auth_context, &sock, &data);
+    status =3D krb5_write_priv_message(context, auth_context, &sock, &data=
);
+    krb5_auth_con_free(context, auth_context);
+
+    return status;
 }
=20
 static int
 doit (int port, const char *service)
 {
     if (do_inetd)
-	mini_inetd(port);
+	mini_inetd(port, NULL);
     return proto (STDIN_FILENO, service);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/ChangeL=
og
--- a/head/crypto/heimdal/appl/login/ChangeLog	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/login/ChangeLog	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,24 +1,35 @@
-2006-12-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
+	* utmp_login.c: Reorder to avoid prototype.
+
+	* login_locl.h: If cygwin doesnt have WTMPX_FILE, it uses wtmp for
+	wtmpx http://www.cygwin.com/ml/cygwin/2006-12/msg00630.html
+=09
+2008-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* utmp_login.c: Remove utmp warning on mac os x
+
+2006-12-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
 	* limits_conf.c: Clear errno before calling the strtol
-	functions. From Paul Stoeber to OpenBSD by Ray Lai and Bj=F6rn
+	functions. From Paul Stoeber to OpenBSD by Ray Lai and Bj=C3=B6rn
 	Sandell.
=20
 	* limits_conf.c: Report to syslog strings that start with NUL;
-	prevents negative index array access. Ray Lai of OpenBSD via Bj=F6rn
+	prevents negative index array access. Ray Lai of OpenBSD via Bj=C3=B6rn
 	Sandell.
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: Add man_MANS to EXTRA_DIST
=20
-2006-09-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* read_string.c: try to not call signaction for signal 0 and use
 	NSIG if it exists to determin how many signals there exists, also,
 	only restore those signalhandlers that we got out.
 =09
-2006-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* login_locl.h: Include "loginpaths.h"
 =09
@@ -28,7 +39,7 @@
=20
 	* login.c: log successful logins
 =09
-2005-08-08  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-08-08  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* login.c (do_login): only do krb4_get_afs_tokens if we have done
 	v4 authentication or done a 5to4 conversion of tickets. This is to
@@ -66,11 +77,11 @@
 	* login.c: use krb5_appdefault_boolean instead of
 	krb5_config_get_bool
=20
-2003-09-03  Love H=F6rnquist =C5strand <lha at it.su.se>
+2003-09-03  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* login.c (krb5_to4): set client princ of the mcred
 =09
-2003-07-07  Love H=F6rnquist =C5strand <lha at it.su.se>
+2003-07-07  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* login.c (krb5_to4): use krb5_cc_clear_mcred
 =09
@@ -84,7 +95,7 @@
=20
 	* login.access.5: login.access manual page
=20
-2003-03-18  Love H=F6rnquist =C5strand <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* login.c: also need pag_set
 	* login.c: if there is kerberos 5, call krb5_afslog\*
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/Makefil=
e.am
--- a/head/crypto/heimdal/appl/login/Makefile.am	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/login/Makefile.am	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,9 +1,7 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_krb4)
-
 man_MANS =3D login.1 login.access.5
=20
 bin_PROGRAMS =3D login
@@ -14,7 +12,7 @@
 		login.c				\
 		login_access.c			\
 		login_locl.h			\
-		login_protos.h			\
+		login-protos.h			\
 		loginpaths.h			\
 		limits_conf.c			\
 		osfc2.c				\
@@ -28,16 +26,15 @@
 LDADD =3D $(LIB_otp) \
 	$(LIB_kafs) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken) \
 	$(LIB_security) \
 	$(DBLIB)
=20
-$(srcdir)/login_protos.h:
-	cd $(srcdir); perl ../../cf/make-proto.pl -o login_protos.h -q -P comment=
 $(login_SOURCES) || rm -f login_protos.h
+$(srcdir)/login-protos.h:
+	cd $(srcdir); perl ../../cf/make-proto.pl -o login-protos.h -q -P comment=
 $(login_SOURCES) || rm -f login-protos.h
=20
-$(login_OBJECTS): $(srcdir)/login_protos.h
+$(login_OBJECTS): $(srcdir)/login-protos.h
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/Makefil=
e.in
--- a/head/crypto/heimdal/appl/login/Makefile.in	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/login/Makefile.in	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/login
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,15 +89,15 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" \
 	"$(DESTDIR)$(man5dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS)
 am_login_OBJECTS =3D conf.$(OBJEXT) env.$(OBJEXT) login.$(OBJEXT) \
 	login_access.$(OBJEXT) limits_conf.$(OBJEXT) osfc2.$(OBJEXT) \
@@ -105,12 +110,11 @@
 	$(am__DEPENDENCIES_1)
 login_DEPENDENCIES =3D $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2) \
 	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -122,6 +126,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(login_SOURCES)
 DIST_SOURCES =3D $(login_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 man5dir =3D $(mandir)/man5
 MANS =3D $(man_MANS)
@@ -132,49 +157,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -198,10 +232,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -218,6 +253,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -233,31 +270,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -272,10 +323,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -316,30 +369,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 man_MANS =3D login.1 login.access.5
 login_SOURCES =3D \
@@ -348,7 +405,7 @@
 		login.c				\
 		login_access.c			\
 		login_locl.h			\
-		login_protos.h			\
+		login-protos.h			\
 		loginpaths.h			\
 		limits_conf.c			\
 		osfc2.c				\
@@ -362,30 +419,29 @@
 LDADD =3D $(LIB_otp) \
 	$(LIB_kafs) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken) \
 	$(LIB_security) \
 	$(DBLIB)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/logi=
n/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/login/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/login/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/login/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -403,34 +459,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 login$(EXEEXT): $(login_OBJECTS) $(login_DEPENDENCIES)=20
 	@rm -f login$(EXEEXT)
 	$(LINK) $(login_OBJECTS) $(login_LDADD) $(LIBS)
@@ -441,160 +513,188 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/conf.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/env.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/limits_conf.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/login.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/login_access.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/osfc2.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/read_string.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/shadow.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/stty_default.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/tty.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/utmp_login.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/utmpx_login.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
-install-man5: $(man5_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
+install-man5: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man5dir)" || $(MKDIR_P) "$(DESTDIR)$(man5dir)"
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man5:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man5dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man5dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -610,13 +710,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -651,6 +755,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -660,6 +765,7 @@
 clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -670,6 +776,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -677,26 +785,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1 install-man5
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -716,11 +833,10 @@
 uninstall-am: uninstall-binPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1 uninstall-man5
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libtool ctags \
@@ -807,6 +923,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -892,7 +1011,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -906,10 +1025,11 @@
 	  fi ; \
 	done
=20
-$(srcdir)/login_protos.h:
-	cd $(srcdir); perl ../../cf/make-proto.pl -o login_protos.h -q -P comment=
 $(login_SOURCES) || rm -f login_protos.h
+$(srcdir)/login-protos.h:
+	cd $(srcdir); perl ../../cf/make-proto.pl -o login-protos.h -q -P comment=
 $(login_SOURCES) || rm -f login-protos.h
=20
-$(login_OBJECTS): $(srcdir)/login_protos.h
+$(login_OBJECTS): $(srcdir)/login-protos.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/conf.c
--- a/head/crypto/heimdal/appl/login/conf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/login/conf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,7 +32,7 @@
=20
 #include "login_locl.h"
=20
-RCSID("$Id: conf.c 8302 2000-05-29 16:52:24Z assar $");
+RCSID("$Id$");
=20
 static char *confbuf;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/env.c
--- a/head/crypto/heimdal/appl/login/env.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/login/env.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "login_locl.h"
-RCSID("$Id: env.c 8476 2000-06-28 12:27:38Z joda $");
+RCSID("$Id$");
=20
 /*
  * the environment we will send to execle and the shell.
@@ -59,16 +59,21 @@
     if(str =3D=3D NULL)
 	errx(1, "Out of memory!");
     for(i =3D 0; i < num_env; i++)
-	if(strncmp(env[i], var, strlen(var)) =3D=3D 0 &&=20
+	if(strncmp(env[i], var, strlen(var)) =3D=3D 0 &&
 	   env[i][strlen(var)] =3D=3D '=3D'){
 	    free(env[i]);
 	    env[i] =3D str;
 	    return;
 	}
-   =20
+
     extend_env(str);
 }
=20
+#if !HAVE_DECL_ENVIRON
+extern char **environ;
+#endif
+
+
 void
 copy_env(void)
 {
@@ -77,22 +82,24 @@
 	extend_env(*p);
 }
=20
-int
+void
 login_read_env(const char *file)
 {
     char **newenv;
     char *p;
     int i, j;
-   =20
+
     newenv =3D NULL;
     i =3D read_environment(file, &newenv);
     for (j =3D 0; j < i; j++) {
 	p =3D strchr(newenv[j], '=3D');
+	if (p =3D=3D NULL)
+	    errx(1, "%s: missing =3D in string %s",
+		 file, newenv[j]);
 	*p++ =3D 0;
 	add_env(newenv[j], p);
 	*--p =3D '=3D';
 	free(newenv[j]);
     }
     free(newenv);
-    return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/limits_=
conf.c
--- a/head/crypto/heimdal/appl/login/limits_conf.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/login/limits_conf.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "login_locl.h"
=20
-RCSID("$Id: limits_conf.c 19215 2006-12-04 23:41:18Z lha $");
+RCSID("$Id$");
=20
 #include <errno.h>
 #include <limits.h>
@@ -91,7 +91,7 @@
 /* this function reads limits.conf files similar to pam_limits
    unimplemented features include:
    	% maxlogins
-	"-" no limits,=20
+	"-" no limits,
 	priorities etc that are not set via setrlimit
    XXX uses static storage, and clobbers getgr*
 */
@@ -131,7 +131,7 @@
 	    int c;
 	    while((c =3D fgetc(f)) !=3D EOF) {
 		eof =3D 0;
-		if(c =3D=3D '\n')=20
+		if(c =3D=3D '\n')
 		    break;
 	    }
 	    if(!eof) {
@@ -192,12 +192,12 @@
 		continue;
 	    l->has_limit =3D level;
 	}
-=09
+
 	/* XXX unclear: if you soft to more than default hard, should
            we set hard to soft? this code doesn't. */
 	if(strcasecmp(args[1], "soft") =3D=3D 0 || strcmp(args[1], "-") =3D=3D 0)
 	    l->limit.rlim_cur =3D value;
-	if(strcasecmp(args[1], "hard") =3D=3D 0 || strcmp(args[1], "-") =3D=3D 0)=20
+	if(strcasecmp(args[1], "hard") =3D=3D 0 || strcmp(args[1], "-") =3D=3D 0)
 	    l->limit.rlim_max =3D value;
     }
     fclose(f);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/login.1
--- a/head/crypto/heimdal/appl/login/login.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/login/login.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,11 @@
-.\" $Id: login.1 14891 2005-04-22 15:49:25Z joda $
-.\"=20
+.\" $Id$
+.\"
 .Dd April 22, 2005
 .Dt LOGIN 1
 .Os HEIMDAL
 .Sh NAME
 .Nm login
-.Nd
-authenticate a user and start new session
+.Nd authenticate a user and start new session
 .Sh SYNOPSIS
 .Nm
 .Op Fl fp
@@ -14,8 +13,8 @@
 .Op Fl h Ar hostname
 .Ar [username]
 .Sh DESCRIPTION
-This manual page documents  the=20
-.Nm login=20
+This manual page documents  the
+.Nm login
 program distributed with the Heimdal Kerberos 5 implementation, it may
 differ in important ways from your system version.
 .Pp
@@ -23,7 +22,7 @@
 .Nm login
 programs logs users into the system. It is intended to be run by
 system daemons like
-.Xr getty 8=20
+.Xr getty 8
 or
 .Xr telnetd 8 .
 If you are already logged in, but want to change to another user, you
@@ -33,16 +32,16 @@
 A username can be given on the command line, else one will be prompted
 for.
 .Pp
-A password is required to login, unless the=20
+A password is required to login, unless the
 .Fl f
 option is given (indicating that the calling program has already done
 proper authentication). With
 .Fl f
-the user will be logged in without further questions.=20
+the user will be logged in without further questions.
 .Pp
 For password authentication Kerberos 5, Kerberos 4 (if compiled in),
 OTP (if compiled in) and local
-.No ( Pa /etc/passwd )=20
+.No ( Pa /etc/passwd )
 passwords are supported. OTP will be used if the the user is
 registered to use it, and
 .Nm login
@@ -71,7 +70,7 @@
 and
 .Dv TZ
 variables are preserved. It could be a security risk to pass random
-variables to=20
+variables to
 .Nm login
 or the user shell, so the calling daemon should make sure it only
 passes
@@ -91,12 +90,12 @@
 the tty to the user, setting up signals, setting the group list, and
 user and group id. Also various machine specific tasks are performed.
 .Pp
-Next=20
+Next
 .Nm login
-changes to the users home directory, or if that fails, to=20
+changes to the users home directory, or if that fails, to
 .Pa / .
 The environment is setup, by adding some required variables (such as
-.Dv PATH ) ,=20
+.Dv PATH ) ,
 and also authentication related ones (such as
 .Dv KRB5CCNAME ) .
 If an environment file exists
@@ -108,31 +107,31 @@
 printed to the terminal.
 .Pp
 If a login time command is configured, it is executed. A logout time
-command can also be configured, which makes=20
+command can also be configured, which makes
 .Nm login
 fork, and wait for the user shell to exit, and then run the command.
 This can be used to clean up user credentials.
 .Pp
 Finally, the user's shell is executed. If the user logging in is root,
-and root's login shell does not exist, a default shell (usually=20
+and root's login shell does not exist, a default shell (usually
 .Pa /bin/sh )
 is also tried before giving up.
 .Sh ENVIRONMENT
-These environment variables are set by login (not including ones set by=20
+These environment variables are set by login (not including ones set by
 .Pa /etc/environment ) :
 .Pp
 .Bl -tag -compact -width USERXXLOGNAME
 .It Dv PATH
 the default system path
 .It Dv HOME
-the user's home directory (or possibly=20
+the user's home directory (or possibly
 .Pa / )
 .It Dv USER , Dv LOGNAME
 both set to the username
 .It Dv SHELL
 the user's shell
 .It Dv TERM , Dv TZ
-set to whatever is passed to=20
+set to whatever is passed to
 .Nm login
 .It Dv KRB5CCNAME
 if the password is verified via Kerberos 5, this will point to the
@@ -145,7 +144,7 @@
 .Bl -tag -compact -width Ds
 .It Pa /etc/environment
 Contains a set of environment variables that should be set in addition
-to the ones above. It should contain sh-style assignments like=20
+to the ones above. It should contain sh-style assignments like
 .Dq VARIABLE=3Dvalue .
 Note that they are not parsed the way a shell would. No variable
 expansion is performed, and all strings are literal, and quotation
@@ -161,7 +160,7 @@
 BAR=3D FOO=3D'this is a string'
 .Ed
 .It Pa /etc/login.access
-See=20
+See
 .Xr login.access 5 .
 .It Pa /etc/login.conf
 This is a termcap style configuration file, that contains various
@@ -205,14 +204,14 @@
 last time you logged in, if you have mail, and system message files.
 This version of
 .Nm login
-does not, so there is no reason for=20
+does not, so there is no reason for
 .Pa .hushlogin
 files or similar. We feel that these tasks are best left to the user's
-shell, but the=20
+shell, but the
 .Li login_program
 facility allows for a shell independent solution, if that is desired.
 .Sh EXAMPLES
-A=20
+A
 .Pa login.conf
 file could look like:
 .Bd -literal -offset indent
@@ -225,8 +224,8 @@
 .Pa limits.conf
 file consists of a table with four whitespace separated fields. First
 field is a username or a groupname (prefixed with
-.Sq @ ) ,=20
-or=20
+.Sq @ ) ,
+or
 .Sq * .
 Second field is
 .Sq soft ,
@@ -235,11 +234,11 @@
 .Sq -
 (the last meaning both soft and hard).
 Third field is a limit name (such as
-.Sq cpu=20
-or=20
+.Sq cpu
+or
 .Sq core ) .
 Last field is the limit value (a number or
-.Sq -=20
+.Sq -
 for unlimited). In the case of data sizes, the value is in kilobytes,
 and cputime is in minutes.
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/login.a=
ccess.5
--- a/head/crypto/heimdal/appl/login/login.access.5	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/login/login.access.5	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,12 +1,11 @@
-.\" $Id: login.access.5 11902 2003-03-24 15:49:30Z joda $
-.\"=20
+.\" $Id$
+.\"
 .Dd March 21, 2003
 .Dt LOGIN.ACCESS 5
 .Os HEIMDAL
 .Sh NAME
 .Nm login.access
-.Nd
-login access control table
+.Nd login access control table
 .Sh DESCRIPTION
 The
 .Nm login.access
@@ -14,7 +13,7 @@
 allowed to login.
 .Pp
 At login, the
-.Pa /etc/login.access=20
+.Pa /etc/login.access
 file is checked for the first entry that matches a specific user/host
 or user/tty combination. That entry can either allow or deny login
 access to that user.
@@ -52,5 +51,5 @@
 .Sh AUTHORS
 The
 .Fn login_access
-function was written by=20
+function was written by
 Wietse Venema. This manual page was written for Heimdal.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/login.c
--- a/head/crypto/heimdal/appl/login/login.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/login/login.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "login_locl.h"
@@ -42,7 +42,7 @@
 #include <crypt.h>
 #endif
=20
-RCSID("$Id: login.c 16498 2006-01-09 16:26:25Z joda $");
+RCSID("$Id$");
=20
 static int login_timeout =3D 60;
=20
@@ -100,7 +100,7 @@
 		execle(prog, argv0, NULL, env);
 		err(1, "exec %s", prog);
 	    }
-	} else if(ret < 0)=20
+	} else if(ret < 0)
 	    err(1, "waitpid");
     }
 }
@@ -110,7 +110,7 @@
 {
     char *sh;
     const char *p;
-   =20
+
     extend_env(NULL);
     if(start_login_process() < 0)
 	warn("login process");
@@ -125,7 +125,7 @@
 	errx(1, "Out of memory");
     execle(shell, sh, NULL, env);
     if(fallback){
-	warnx("Can't exec %s, trying %s",=20
+	warnx("Can't exec %s, trying %s",
 	      shell, _PATH_BSHELL);
 	execle(_PATH_BSHELL, "-sh", NULL, env);
 	err(1, "%s", _PATH_BSHELL);
@@ -133,11 +133,7 @@
     err(1, "%s", shell);
 }
=20
-static enum { NONE =3D 0, AUTH_KRB4 =3D 1, AUTH_KRB5 =3D 2, AUTH_OTP =3D 3=
 } auth;
-
-#ifdef KRB4
-static krb5_boolean get_v4_tgt =3D FALSE;
-#endif
+static enum { NONE =3D 0, AUTH_KRB5 =3D 2, AUTH_OTP =3D 3 } auth;
=20
 #ifdef OTP
 static OtpContext otp_ctx;
@@ -165,88 +161,21 @@
     ret =3D krb5_parse_name(context, pwd->pw_name, &princ);
     if(ret)
 	return 1;
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &id);
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
     if(ret) {
 	krb5_free_principal(context, princ);
 	return 1;
     }
     ret =3D krb5_verify_user_lrealm(context,
-				  princ,=20
+				  princ,
 				  id,
-				  password,=20
+				  password,
 				  1,
 				  NULL);
     krb5_free_principal(context, princ);
     return ret;
 }
=20
-#ifdef KRB4
-static krb5_error_code
-krb5_to4 (krb5_ccache id)
-{
-    krb5_error_code ret;
-    krb5_principal princ;
-
-    ret =3D krb5_cc_get_principal(context, id, &princ);
-    if(ret =3D=3D 0) {
-	krb5_appdefault_boolean(context, "login",=20
-				krb5_principal_get_realm(context, princ),=20
-				"krb4_get_tickets", FALSE, &get_v4_tgt);
-	krb5_free_principal(context, princ);
-    } else {
-	krb5_realm realm =3D NULL;
-	krb5_get_default_realm(context, &realm);
-	krb5_appdefault_boolean(context, "login",=20
-				realm,=20
-				"krb4_get_tickets", FALSE, &get_v4_tgt);
-	free(realm);
-    }
-
-    if (get_v4_tgt) {
-        CREDENTIALS c;
-        krb5_creds mcred, cred;
-        char krb4tkfile[MAXPATHLEN];
-	krb5_error_code ret;
-	krb5_principal princ;
-
-	krb5_cc_clear_mcred(&mcred);
-
-	ret =3D krb5_cc_get_principal (context, id, &princ);
-	if (ret)
-	    return ret;
-
-	ret =3D krb5_make_principal(context, &mcred.server,
-				  princ->realm,
-				  "krbtgt",
-				  princ->realm,
-				  NULL);
-	if (ret) {
-	    krb5_free_principal(context, princ);
-	    return ret;
-	}
-	mcred.client =3D princ;
-
-	ret =3D krb5_cc_retrieve_cred(context, id, 0, &mcred, &cred);
-	if(ret =3D=3D 0) {
-	    ret =3D krb524_convert_creds_kdc_ccache(context, id, &cred, &c);
-	    if(ret =3D=3D 0) {
-		snprintf(krb4tkfile,sizeof(krb4tkfile),"%s%d",TKT_ROOT,
-			 getuid());
-		krb_set_tkt_string(krb4tkfile);
-		tf_setup(&c, c.pname, c.pinst);
-	    }
-	    memset(&c, 0, sizeof(c));
-	    krb5_free_cred_contents(context, &cred);
-	}
-	if (ret !=3D 0)
-	    get_v4_tgt =3D FALSE;
-	krb5_free_principal(context, mcred.server);
-	krb5_free_principal(context, mcred.client);
-    }
-    return 0;
-}
-#endif /* KRB4 */
-
 static int
 krb5_start_session (const struct passwd *pwd)
 {
@@ -254,7 +183,7 @@
     char residual[64];
=20
     /* copy credentials to file cache */
-    snprintf(residual, sizeof(residual), "FILE:/tmp/krb5cc_%u",=20
+    snprintf(residual, sizeof(residual), "FILE:/tmp/krb5cc_%u",
 	     (unsigned)pwd->pw_uid);
     krb5_cc_resolve(context, residual, &id2);
     ret =3D krb5_cc_copy_cache(context, id, id2);
@@ -264,9 +193,6 @@
 	krb5_cc_destroy (context, id2);
 	return ret;
     }
-#ifdef KRB4
-    krb5_to4 (id2);
-#endif
     krb5_cc_close(context, id2);
     krb5_cc_destroy(context, id);
     return 0;
@@ -289,7 +215,7 @@
 	return;
=20
     ret =3D krb5_cc_default(context, &id2);
-=20
+
     if (ret =3D=3D 0) {
 	pw_dir =3D pwd->pw_dir;
=20
@@ -309,63 +235,6 @@
=20
 #endif /* KRB5 */
=20
-#ifdef KRB4
-
-static int
-krb4_verify(struct passwd *pwd, const char *password)
-{
-    char lrealm[REALM_SZ];
-    int ret;
-    char ticket_file[MaxPathLen];
-
-    ret =3D krb_get_lrealm (lrealm, 1);
-    if (ret)
-	return 1;
-
-    snprintf (ticket_file, sizeof(ticket_file),
-	      "%s%u_%u",
-	      TKT_ROOT, (unsigned)pwd->pw_uid, (unsigned)getpid());
-
-    krb_set_tkt_string (ticket_file);
-
-    ret =3D krb_verify_user (pwd->pw_name, "", lrealm, (char *)password,
-			   KRB_VERIFY_SECURE_FAIL, NULL);
-    if (ret)
-	return 1;
-
-    if (chown (ticket_file, pwd->pw_uid, pwd->pw_gid) < 0) {
-	dest_tkt();
-	return 1;
-    }
-=09
-    add_env ("KRBTKFILE", ticket_file);
-    return 0;
-}
-
-static void
-krb4_get_afs_tokens (const struct passwd *pwd)
-{
-    char cell[64];
-    char *pw_dir;
-
-    if (!k_hasafs ())
-	return;
-
-    pw_dir =3D pwd->pw_dir;
-
-    if (!pag_set) {
-	k_setpag();
-	pag_set =3D 1;
-    }
-
-    if(k_afs_cell_of_file(pw_dir, cell, sizeof(cell)) =3D=3D 0)
-	krb_afslog_uid_home (cell, NULL, pwd->pw_uid, pwd->pw_dir);
-
-    krb_afslog_uid_home (NULL, NULL, pwd->pw_uid, pwd->pw_dir);
-}
-
-#endif /* KRB4 */
-
 static int f_flag;
 static int p_flag;
 #if 0
@@ -436,7 +305,7 @@
     fclose(f);
 }
=20
-/*=20
+/*
  * Actually log in the user.  `pwd' contains all the relevant
  * information about the user.  `ttyn' is the complete name of the tty
  * and `tty' the short name.
@@ -456,7 +325,7 @@
=20
     if(!rootlogin)
 	checknologin();
-   =20
+
 #ifdef HAVE_GETSPNAM
     sp =3D getspnam(pwd->pw_name);
 #endif
@@ -496,7 +365,7 @@
=20
 	read_limits_conf(file, pwd);
     }
-	   =20
+
 #ifdef HAVE_SETPCRED
     if (setpcred (pwd->pw_name, NULL) =3D=3D -1)
 	warn("setpcred(%s)", pwd->pw_name);
@@ -523,7 +392,7 @@
=20
     /* make sure signals are set to default actions, apparently some
        OS:es like to ignore SIGINT, which is not very convenient */
-   =20
+
     for (i =3D 1; i < NSIG; ++i)
 	signal(i, SIG_DFL);
=20
@@ -600,29 +469,12 @@
     if (auth =3D=3D AUTH_KRB5) {
 	krb5_start_session (pwd);
     }
-#ifdef KRB4
-    else if (auth =3D=3D 0) {
-	krb5_error_code ret;
-	krb5_ccache id;
-
-	ret =3D krb5_cc_default (context, &id);
-	if (ret =3D=3D 0) {
-	    krb5_to4 (id);
-	    krb5_cc_close (context, id);
-	}
-    }
-#endif /* KRB4 */
=20
     krb5_get_afs_tokens (pwd);
=20
     krb5_finish ();
 #endif /* KRB5 */
=20
-#ifdef KRB4
-    if (auth =3D=3D AUTH_KRB4 || get_v4_tgt)
-	krb4_get_afs_tokens (pwd);
-#endif /* KRB4 */
-
     add_env("PATH", _PATH_DEFPATH);
=20
     {
@@ -682,12 +534,6 @@
 	return 0;
     }
 #endif
-#ifdef KRB4
-    if (krb4_verify (pwd, password) =3D=3D 0) {
-	auth =3D AUTH_KRB4;
-	return 0;
-    }
-#endif
 #ifdef OTP
     if (otp_verify (pwd, password) =3D=3D 0) {
        auth =3D AUTH_OTP;
@@ -726,7 +572,7 @@
=20
     int ask =3D 1;
     struct sigaction sa;
-   =20
+
     setprogname(argv[0]);
=20
 #ifdef KRB5
@@ -753,7 +599,7 @@
 	print_version (NULL);
 	return 0;
     }
-=09
+
     if (geteuid() !=3D 0)
 	errx(1, "only root may use login, use su");
=20
@@ -841,7 +687,7 @@
                   sig_handler(0);
             }
          }
-=09
+
 	if(pwd =3D=3D NULL){
 	    fprintf(stderr, "Login incorrect.\n");
 	    ask =3D 1;
@@ -862,7 +708,7 @@
 	    tty =3D ttyn + strlen(_PATH_DEV);
 	else
 	    tty =3D ttyn;
-   =20
+
 	if (login_access (pwd, remote_host ? remote_host : tty) =3D=3D 0) {
 	    fprintf(stderr, "Permission denied\n");
 	    if (remote_host)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/login_a=
ccess.c
--- a/head/crypto/heimdal/appl/login/login_access.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/login/login_access.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -25,7 +25,7 @@
=20
 #include "login_locl.h"
=20
-RCSID("$Id: login_access.c 10020 2001-06-04 14:10:19Z assar $");
+RCSID("$Id$");
=20
  /* Delimiters for fields and for lists of users, ttys or hosts. */
=20
@@ -101,13 +101,13 @@
 		|| !(users =3D strtok_r(NULL, fs, &foo))
 		|| !(froms =3D strtok_r(NULL, fs, &foo))
 		|| strtok_r(NULL, fs, &foo)) {
-		syslog(LOG_ERR, "%s: line %d: bad field count",=20
+		syslog(LOG_ERR, "%s: line %d: bad field count",
 		       _PATH_LOGACCESS,
 		       lineno);
 		continue;
 	    }
 	    if (perm[0] !=3D '+' && perm[0] !=3D '-') {
-		syslog(LOG_ERR, "%s: line %d: bad first field",=20
+		syslog(LOG_ERR, "%s: line %d: bad first field",
 		       _PATH_LOGACCESS,
 		       lineno);
 		continue;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/login_l=
ocl.h
--- a/head/crypto/heimdal/appl/login/login_locl.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/login/login_locl.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: login_locl.h 17302 2006-04-27 09:17:01Z lha $ */
+/* $Id$ */
=20
 #ifndef __LOGIN_LOCL_H__
 #define __LOGIN_LOCL_H__
@@ -84,9 +84,6 @@
 #ifdef HAVE_RPCSVC_YPCLNT_H
 #include <rpcsvc/ypclnt.h>
 #endif
-#ifdef KRB4
-#include <krb.h>
-#endif
 #ifdef KRB5
 #include <krb5.h>
 #endif
@@ -126,6 +123,14 @@
 #endif
 #endif
=20
+/* if cygwin doesnt have WTMPX_FILE, it uses wtmp for wtmpx
+ * http://www.cygwin.com/ml/cygwin/2006-12/msg00630.html */
+#ifdef __CYGWIN__
+#ifndef WTMPX_FILE
+#define WTMPX_FILE WTMP_FILE
+#endif
+#endif
+
 #ifndef _PATH_LOGACCESS
 #define _PATH_LOGACCESS SYSCONFDIR "/login.access"
 #endif /* _PATH_LOGACCESS */
@@ -145,6 +150,6 @@
 extern char **env;
 extern int num_env;
=20
-#include "login_protos.h"
+#include "login-protos.h"
=20
 #endif /* __LOGIN_LOCL_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/loginpa=
ths.h
--- a/head/crypto/heimdal/appl/login/loginpaths.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/login/loginpaths.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: loginpaths.h 17299 2006-04-27 09:14:20Z lha $ */
+/* $Id$ */
=20
 #ifndef __LOGIN_PATH_H
 #define __LOGIN_PATH_H
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/osfc2.c
--- a/head/crypto/heimdal/appl/login/osfc2.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/login/osfc2.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "login_locl.h"
-RCSID("$Id: osfc2.c 9704 2001-02-20 01:44:56Z assar $");
+RCSID("$Id$");
=20
 int
 do_osfc2_magic(uid_t uid)
@@ -40,15 +40,15 @@
 #ifdef HAVE_OSFC2
     struct es_passwd *epw;
     char *argv[2];
-   =20
+
     /* fake */
     argv[0] =3D (char*)getprogname();
     argv[1] =3D NULL;
     set_auth_parameters(1, argv);
-   =20
+
     epw =3D getespwuid(uid);
     if(epw =3D=3D NULL) {
-	syslog(LOG_AUTHPRIV|LOG_NOTICE,=20
+	syslog(LOG_AUTHPRIV|LOG_NOTICE,
 	       "getespwuid failed for %d", uid);
 	printf("Sorry.\n");
 	return 1;
@@ -59,17 +59,17 @@
        any other kind of serious C2 mumbo-jumbo. We do,
        however, call setluid, since failing to do so is not
        very good (take my word for it). */
-   =20
+
     if(!epw->uflg->fg_uid) {
-	syslog(LOG_AUTHPRIV|LOG_NOTICE,=20
+	syslog(LOG_AUTHPRIV|LOG_NOTICE,
 	       "attempted login by %s (has no uid)", epw->ufld->fd_name);
 	printf("Sorry.\n");
 	return 1;
     }
     setluid(epw->ufld->fd_uid);
     if(getluid() !=3D epw->ufld->fd_uid) {
-	syslog(LOG_AUTHPRIV|LOG_NOTICE,=20
-	       "failed to set LUID for %s (%d)",=20
+	syslog(LOG_AUTHPRIV|LOG_NOTICE,
+	       "failed to set LUID for %s (%d)",
 	       epw->ufld->fd_name, epw->ufld->fd_uid);
 	printf("Sorry.\n");
 	return 1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/read_st=
ring.c
--- a/head/crypto/heimdal/appl/login/read_string.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/login/read_string.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "login_locl.h"
=20
-RCSID("$Id: read_string.c 18156 2006-09-22 15:42:39Z lha $");
+RCSID("$Id$");
=20
 static sig_atomic_t intr_flag;
=20
@@ -69,13 +69,13 @@
     sigemptyset(&sa.sa_mask);
     sa.sa_flags =3D 0;
     for(i =3D 1; i < sizeof(sigs) / sizeof(sigs[0]); i++)
-	if (i !=3D SIGALRM)=20
+	if (i !=3D SIGALRM)
 	    if (sigaction(i, &sa, &sigs[i]) =3D=3D 0)
 		oksigs[i] =3D 1;
=20
     if((tty =3D fopen("/dev/tty", "r")) =3D=3D NULL)
 	tty =3D stdin;
-      =20
+
     fprintf(stderr, "%s", prompt);
     fflush(stderr);
=20
@@ -103,19 +103,19 @@
     if(of)
 	p--;
     *p =3D 0;
-   =20
+
     if(echo =3D=3D 0){
 	printf("\n");
 	tcsetattr(fileno(tty), TCSANOW, &t_old);
     }
-   =20
+
     if(tty !=3D stdin)
 	fclose(tty);
=20
     for(i =3D 1; i < sizeof(sigs) / sizeof(sigs[0]); i++)
 	if (oksigs[i])
 	    sigaction(i, &sigs[i], NULL);
-   =20
+
     if(ret)
 	return -3;
     if(intr_flag)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/shadow.c
--- a/head/crypto/heimdal/appl/login/shadow.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/login/shadow.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "login_locl.h"
=20
-RCSID("$Id: shadow.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
 #ifdef HAVE_SHADOW_H
=20
@@ -60,13 +60,13 @@
     }
 }
=20
-void=20
+void
 check_shadow(const struct passwd *pw, const struct spwd *sp)
 {
   long today;
=20
   today =3D time(0)/(24L * 60 * 60);
- =20
+
   if (sp =3D=3D NULL)
       return;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/stty_de=
fault.c
--- a/head/crypto/heimdal/appl/login/stty_default.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/login/stty_default.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,7 +33,7 @@
=20
 #include "login_locl.h"
=20
-RCSID("$Id: stty_default.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
 #include <termios.h>
=20
@@ -95,6 +95,6 @@
     termios.c_cc[VEOF] =3D Ctl('D');
=20
     termios.c_cc[VSUSP] =3D Ctl('Z');
-   =20
+
     tcsetattr(0, TCSANOW, &termios);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/tty.c
--- a/head/crypto/heimdal/appl/login/tty.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/login/tty.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,7 +33,7 @@
=20
 #include "login_locl.h"
=20
-RCSID("$Id: tty.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
 /*
  * Clean the tty name.  Return a pointer to the cleaned version.
@@ -61,7 +61,7 @@
 make_id (char *tty)
 {
   char *res =3D tty;
- =20
+
   if (strncmp (res, "pts/", 4) =3D=3D 0)
     res +=3D 4;
   if (strncmp (res, "tty", 3) =3D=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/utmp_lo=
gin.c
--- a/head/crypto/heimdal/appl/login/utmp_login.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/login/utmp_login.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,7 +33,7 @@
=20
 #include "login_locl.h"
=20
-RCSID("$Id: utmp_login.c 9661 2001-02-08 16:08:47Z assar $");
+RCSID("$Id$");
=20
 /* try to put something useful from hostname into dst, dst_sz:
  * full name, first component or address */
@@ -77,8 +77,12 @@
     }
 }
=20
+/* update utmp and wtmp - the BSD way */
+
+#if !defined(HAVE_UTMPX_H) || (defined(WTMP_FILE) && !defined(WTMPX_FILE))
+
 void
-prepare_utmp (struct utmp *utmp, char *tty,=20
+prepare_utmp (struct utmp *utmp, char *tty,
 	      const char *username, const char *hostname)
 {
     char *ttyx =3D clean_ttyname (tty);
@@ -117,16 +121,15 @@
     strncpy(utmp->ut_id, make_id(ttyx), sizeof(utmp->ut_id));
 # endif
 }
+#endif
=20
 #ifdef HAVE_UTMPX_H
 void utmp_login(char *tty, const char *username, const char *hostname)
-{=20
+{
     return;
 }
 #else
=20
-/* update utmp and wtmp - the BSD way */
-
 void utmp_login(char *tty, const char *username, const char *hostname)
 {
     struct utmp utmp;
@@ -159,4 +162,5 @@
 	close(fd);
     }
 }
+
 #endif /* !HAVE_UTMPX_H */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/login/utmpx_l=
ogin.c
--- a/head/crypto/heimdal/appl/login/utmpx_login.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/appl/login/utmpx_login.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -18,7 +18,7 @@
=20
 #include "login_locl.h"
=20
-RCSID("$Id: utmpx_login.c 10020 2001-06-04 14:10:19Z assar $");
+RCSID("$Id$");
=20
 /* utmpx_login - update utmp and wtmp after login */
=20
@@ -51,7 +51,7 @@
 #ifdef WTMPX_FILE
     updwtmpx(WTMPX_FILE, ut);
 #elif defined(WTMP_FILE)
-    {
+    { /* XXX should be removed, just drop wtmp support */
 	struct utmp utmp;
 	int fd;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/ChangeLog
--- a/head/crypto/heimdal/appl/push/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/push/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-2005-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* push.c: catch when snprint needs a larger buffer
=20
@@ -10,7 +10,7 @@
=20
 	* push.c: fixed one incorrect fprintf to stderr
=20
-2003-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* push.c: add names of pop states, add some more debugging and use
 	fprintf(stderr) for all dbg stmts.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/Makefile=
.am
--- a/head/crypto/heimdal/appl/push/Makefile.am	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/push/Makefile.am	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,8 +1,8 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_krb4) $(INCLUDE_hesiod)
+AM_CPPFLAGS +=3D $(INCLUDE_hesiod)
=20
 bin_SCRIPTS		=3D pfrom
=20
@@ -18,10 +18,9 @@
=20
 CLEANFILES =3D pfrom
=20
-EXTRA_DIST =3D pfrom.in $(man_MANS)
+EXTRA_DIST =3D NTMakefile pfrom.in $(man_MANS)
=20
 LDADD =3D $(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_roken) \
 	$(LIB_hesiod)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/Makefile=
.in
--- a/head/crypto/heimdal/appl/push/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/push/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,17 +15,18 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -46,7 +48,7 @@
 subdir =3D appl/push
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -61,7 +63,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -75,9 +77,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -85,28 +90,47 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(bindir)" \
 	"$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)"
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(libexec_PROGRAMS)
 am_push_OBJECTS =3D push.$(OBJEXT)
 push_OBJECTS =3D $(am_push_OBJECTS)
 push_LDADD =3D $(LDADD)
 am__DEPENDENCIES_1 =3D
 push_DEPENDENCIES =3D $(LIB_krb5) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-binSCRIPT_INSTALL =3D $(INSTALL_SCRIPT)
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 SCRIPTS =3D $(bin_SCRIPTS)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -128,49 +152,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -194,10 +227,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -214,6 +248,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -229,31 +265,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -268,10 +318,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -312,38 +364,41 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4) $(INCLUDE_hesiod)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_hesiod)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 bin_SCRIPTS =3D pfrom
 push_SOURCES =3D push.c push_locl.h
 man_MANS =3D push.8 pfrom.1
 CLEANFILES =3D pfrom
-EXTRA_DIST =3D pfrom.in $(man_MANS)
+EXTRA_DIST =3D NTMakefile pfrom.in $(man_MANS)
 LDADD =3D $(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_roken) \
 	$(LIB_hesiod)
@@ -351,19 +406,19 @@
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/push=
/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/push/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/push/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/push/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -381,56 +436,87 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 push$(EXEEXT): $(push_OBJECTS) $(push_DEPENDENCIES)=20
 	@rm -f push$(EXEEXT)
 	$(LINK) $(push_OBJECTS) $(push_LDADD) $(LIBS)
 install-binSCRIPTS: $(bin_SCRIPTS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_SCRIPTS)'; for p in $$list; do \
+	@list=3D'$(bin_SCRIPTS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  if test -f $$d$$p; then \
-	    f=3D`echo "$$p" | sed 's|^.*/||;$(transform)'`; \
-	    echo " $(binSCRIPT_INSTALL) '$$d$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	    $(binSCRIPT_INSTALL) "$$d$$p" "$(DESTDIR)$(bindir)/$$f"; \
-	  else :; fi; \
-	done
+	  if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n' \
+	    -e 'h;s|.*|.|' \
+	    -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1; } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) { files[d] =3D files[d] " " $$1; \
+	      if (++n[d] =3D=3D $(am__install_max)) { \
+		print "f", d, files[d]; n[d] =3D 0; files[d] =3D "" } } \
+	    else { print "f", d "/" $$4, $$1 } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	     if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	     test -z "$$files" || { \
+	       echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \
+	       $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
+	     } \
+	; done
=20
 uninstall-binSCRIPTS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_SCRIPTS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's|^.*/||;$(transform)'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	       sed -e 's,.*/,,;$(transform)'`; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
@@ -438,160 +524,177 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/push.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
-install-man8: $(man8_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -607,13 +710,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -649,6 +756,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -659,6 +767,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -669,6 +778,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -676,26 +787,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binSCRIPTS install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -716,11 +836,10 @@
 	uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1 uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libexecPROGRAMS clean-libtool ctags \
@@ -808,6 +927,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -893,7 +1015,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -910,6 +1032,7 @@
 pfrom: pfrom.in
 	sed -e "s!%libexecdir%!$(libexecdir)!" $(srcdir)/pfrom.in > $@
 	chmod +x $@
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/pfrom.1
--- a/head/crypto/heimdal/appl/push/pfrom.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/push/pfrom.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2000 - 2002 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2000 - 2002 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: pfrom.1 11648 2003-02-16 21:10:32Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd March 4, 2000
 .Dt PFROM 1
@@ -39,13 +39,13 @@
 .Nd "fetch a list of the current mail via POP"
 .Sh SYNOPSIS
 .Nm
-.Op Fl 4 | Fl -krb4
-.Op Fl 5 | Fl -krb5
-.Op Fl v | Fl -verbose
+.Op Fl 4 | Fl Fl krb4
+.Op Fl 5 | Fl Fl krb5
+.Op Fl v | Fl Fl verbose
 .Op Fl c | -count
-.Op Fl -header
+.Op Fl Fl header
 .Oo Fl p Ar port-spec  \*(Ba Xo
-.Fl -port=3D Ns Ar port-spec
+.Fl Fl port=3D Ns Ar port-spec
 .Xc
 .Oc
 .Sh DESCRIPTION
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/pfrom.in
--- a/head/crypto/heimdal/appl/push/pfrom.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/push/pfrom.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #!/bin/sh
-# $Id: pfrom.in 5248 1998-11-24 13:25:47Z assar $
+# $Id$
 libexecdir=3D%libexecdir%
 PATH=3D$libexecdir:$PATH
 export PATH
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/push.8
--- a/head/crypto/heimdal/appl/push/push.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/push/push.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $Id: push.8 11176 2002-08-20 17:07:29Z joda $
+.\" $Id$
 .\"
 .Dd May 31, 1998
 .Dt PUSH 8
@@ -8,16 +8,15 @@
 .Nd fetch mail via POP
 .Sh SYNOPSIS
 .Nm
-.Op Fl 4 | Fl -krb4
-.Op Fl 5 | Fl -krb5
-.Op Fl v | Fl -verbose
-.Op Fl f | Fl -fork
+.Op Fl 5 | Fl Fl krb5
+.Op Fl v | Fl Fl verbose
+.Op Fl f | Fl Fl fork
 .Op Fl l | -leave
-.Op Fl -from
+.Op Fl Fl from
 .Op Fl c | -count
-.Op Fl -headers Ns =3D Ns Ar headers
+.Op Fl Fl headers Ns =3D Ns Ar headers
 .Oo Fl p Ar port-spec  \*(Ba Xo
-.Fl -port Ns =3D Ns Ar port-spec
+.Fl Fl port Ns =3D Ns Ar port-spec
 .Xc
 .Oc
 .Ar po-box
@@ -51,41 +50,36 @@
 Supported options:
 .Bl -tag -width Ds
 .It Xo
-.Fl 4 ,
-.Fl -krb4
-.Xc
-use Kerberos 4 (if compiled with support for Kerberos 4)
-.It Xo
 .Fl 5 ,
-.Fl -krb5
+.Fl Fl krb5
 .Xc
 use Kerberos 5 (if compiled with support for Kerberos 5)
 .It Xo
 .Fl f ,
-.Fl -fork
+.Fl Fl fork
 .Xc
 fork before starting to delete messages
 .It Xo
 .Fl l ,
-.Fl -leave
+.Fl Fl leave
 .Xc
 don't delete fetched mail
 .It Xo
-.Fl -from
+.Fl Fl from
 .Xc
 behave like from.
 .It Xo
 .Fl c ,
-.Fl -count
+.Fl Fl count
 .Xc
 first print how many messages and bytes there are.
 .It Xo
-.Fl -headers Ns =3D Ns Ar headers
+.Fl Fl headers Ns =3D Ns Ar headers
 .Xc
 a list of comma-separated headers that should get printed.
 .It Xo
 .Fl p Ar port-spec ,
-.Fl -port Ns =3D Ns Ar port-spec
+.Fl Fl port Ns =3D Ns Ar port-spec
 .Xc
 use this port instead of the default
 .Ql kpop
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/push.c
--- a/head/crypto/heimdal/appl/push/push.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/push/push.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,44 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "push_locl.h"
-RCSID("$Id: push.c 14850 2005-04-19 18:00:17Z lha $");
+RCSID("$Id$");
=20
-#ifdef KRB4
-static int use_v4 =3D -1;
+#if defined(_AIX) && defined(STAT)
+/*
+ * AIX defines STAT to 1 in sys/dir.h
+ */
+#  undef STAT
 #endif
=20
 #ifdef KRB5
@@ -54,10 +57,6 @@
 static char *header_str;
=20
 struct getargs args[] =3D {
-#ifdef KRB4
-    { "krb4",	'4', arg_flag,		&use_v4,	"Use Kerberos V4",
-      NULL },
-#endif   =20
 #ifdef KRB5
     { "krb5",	'5', arg_flag,		&use_v5,	"Use Kerberos V5",
       NULL },
@@ -134,12 +133,12 @@
     return s;
 }
=20
-typedef enum { INIT =3D 0, GREET, USER, PASS, STAT, RETR, TOP,=20
+typedef enum { INIT =3D 0, GREET, USER, PASS, STAT, RETR, TOP,
 	       DELE, XDELE, QUIT} pop_state;
=20
 static char *pop_state_string[] =3D {
     "INIT", "GREET", "USER", "PASS", "STAT", "RETR", "TOP",
-    "DELE", "XDELE", "QUIT"=20
+    "DELE", "XDELE", "QUIT"
 };
=20
 #define PUSH_BUFSIZ 65536
@@ -169,20 +168,20 @@
 static void
 write_state_add (struct write_state *w, void *v, size_t len)
 {
-    if(w->niovecs =3D=3D w->allociovecs) {			=09
-	if(w->niovecs =3D=3D w->maxiovecs) {			=09
-	    if(writev (w->fd, w->iovecs, w->niovecs) < 0)	=09
-		err(1, "writev");			=09
-	    w->niovecs =3D 0;				=09
-	} else {					=09
-	    w->allociovecs =3D min(w->allociovecs + STEP, w->maxiovecs);=09
-	    w->iovecs =3D erealloc (w->iovecs,			=09
-				  w->allociovecs * sizeof(*w->iovecs));=09
-	}						=09
-    }							=09
-    w->iovecs[w->niovecs].iov_base =3D v;			=09
-    w->iovecs[w->niovecs].iov_len  =3D len;			=09
-    ++w->niovecs;						=09
+    if(w->niovecs =3D=3D w->allociovecs) {
+	if(w->niovecs =3D=3D w->maxiovecs) {
+	    if(writev (w->fd, w->iovecs, w->niovecs) < 0)
+		err(1, "writev");
+	    w->niovecs =3D 0;
+	} else {
+	    w->allociovecs =3D min(w->allociovecs + STEP, w->maxiovecs);
+	    w->iovecs =3D erealloc (w->iovecs,
+				  w->allociovecs * sizeof(*w->iovecs));
+	}
+    }
+    w->iovecs[w->niovecs].iov_base =3D v;
+    w->iovecs[w->niovecs].iov_len  =3D len;
+    ++w->niovecs;
 }
=20
 static void
@@ -219,7 +218,7 @@
     size_t in_len =3D 0;
     char *in_ptr;
     pop_state state =3D INIT;
-    unsigned count, bytes;
+    unsigned count =3D 0, bytes;
     unsigned asked_for =3D 0, retrieved =3D 0, asked_deleted =3D 0, delete=
d =3D 0;
     unsigned sent_xdele =3D 0;
     int out_fd;
@@ -227,7 +226,7 @@
     size_t from_line_length;
     time_t now;
     struct write_state write_state;
-    int numheaders =3D 1;
+    unsigned int numheaders =3D 1;
     char **headers =3D NULL;
     int i;
     char *tmp =3D NULL;
@@ -296,7 +295,7 @@
 	if (verbose > 1)
 	    fprintf (stderr, "state: %s count: %d asked_for: %d "
 		     "retrieved: %d asked_deleted: %d\n",
-		     pop_state_string[state],=20
+		     pop_state_string[state],
 		     count, asked_for, retrieved, asked_deleted);
=20
 	if (((state =3D=3D STAT || state =3D=3D RETR || state =3D=3D TOP)
@@ -311,12 +310,12 @@
 	    else
 		err (1, "select");
 	}
-=09
+
 	if (FD_ISSET(s, &readset)) {
 	    char *beg, *p;
 	    size_t rem;
 	    int blank_line =3D 0;
-	   =20
+
 	    if(in_len >=3D in_buf_size) {
 		char *tmp =3D erealloc(in_buf, in_buf_size + PUSH_BUFSIZ + 1);
 		in_ptr =3D tmp + (in_ptr - in_buf);
@@ -329,11 +328,11 @@
 		err (1, "read");
 	    else if (ret =3D=3D 0)
 		errx (1, "EOF during read");
-	   =20
+
 	    in_len +=3D ret;
 	    in_ptr +=3D ret;
 	    *in_ptr =3D '\0';
-	   =20
+
 	    beg =3D in_buf;
 	    rem =3D in_len;
 	    while(rem > 1
@@ -406,7 +405,7 @@
 			    ++copy;
 		    }
 		    *p =3D '\n';
-		    if(blank_line &&=20
+		    if(blank_line &&
 		       strncmp(copy, "From ", min(p - copy + 1, 5)) =3D=3D 0)
 			write_state_add(&write_state, ">", 1);
 		    write_state_add(&write_state, copy, p - copy + 1);
@@ -419,7 +418,7 @@
 			    write_state_add(&write_state,
 					    from_line, from_line_length);
 			blank_line =3D 0;
-			if (do_from)=20
+			if (do_from)
 			    state =3D TOP;
 			else
 			    state =3D RETR;
@@ -565,48 +564,6 @@
 }
 #endif
=20
-#ifdef KRB4
-static int
-do_v4 (const char *host,
-       int port,
-       const char *user,
-       const char *filename,
-       const char *header_str,
-       int leavep,
-       int verbose,
-       int forkp)
-{
-    KTEXT_ST ticket;
-    MSG_DAT msg_data;
-    CREDENTIALS cred;
-    des_key_schedule sched;
-    int s;
-    int ret;
-
-    s =3D do_connect (host, port, 1);
-    if (s < 0)
-	return 1;
-    ret =3D krb_sendauth(0,
-		       s,
-		       &ticket,=20
-		       "pop",
-		       (char *)host,
-		       krb_realmofhost(host),
-		       getpid(),
-		       &msg_data,
-		       &cred,
-		       sched,
-		       NULL,
-		       NULL,
-		       "KPOPV0.1");
-    if(ret) {
-	warnx("krb_sendauth: %s", krb_get_err_text(ret));
-	return 1;
-    }
-    return doit (s, host, user, filename, header_str, leavep, verbose, for=
kp);
-}
-#endif /* KRB4 */
-
 #ifdef HESIOD
=20
 #ifdef HESIOD_INTERFACES
@@ -763,13 +720,6 @@
     argc -=3D optind;
     argv +=3D optind;
=20
-#if defined(KRB4) && defined(KRB5)
-    if(use_v4 =3D=3D -1 && use_v5 =3D=3D 1)
-	use_v4 =3D 0;
-    if(use_v5 =3D=3D -1 && use_v4 =3D=3D 1)
-	use_v5 =3D 0;
-#endif   =20
-
     if (do_help)
 	usage (0);
=20
@@ -777,7 +727,7 @@
 	print_version(NULL);
 	return 0;
     }
-=09
+
     if (do_from && header_str =3D=3D NULL)
 	header_str =3D "From:";
     else if (header_str !=3D NULL)
@@ -818,10 +768,8 @@
     if (port =3D=3D 0) {
 #ifdef KRB5
 	port =3D krb5_getportbyname (context, "kpop", "tcp", 1109);
-#elif defined(KRB4)
-	port =3D k_getportbyname ("kpop", "tcp", htons(1109));
 #else
-#error must define KRB4 or KRB5
+#error must define KRB5
 #endif
     }
=20
@@ -833,12 +781,5 @@
 		     do_leave, verbose_level, do_fork);
     }
 #endif
-
-#ifdef KRB4
-    if (ret && use_v4) {
-	ret =3D do_v4 (host, port, user, filename, header_str,
-		     do_leave, verbose_level, do_fork);
-    }
-#endif /* KRB4 */
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/push/push_loc=
l.h
--- a/head/crypto/heimdal/appl/push/push_locl.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/push/push_locl.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997, 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: push_locl.h 7463 1999-12-02 16:58:55Z joda $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
@@ -92,7 +92,3 @@
 #ifdef KRB5
 #include <krb5.h>
 #endif
-
-#ifdef KRB4
-#include <krb.h>
-#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/ChangeLog
--- a/head/crypto/heimdal/appl/rcp/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rcp/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,17 @@
-2007-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-04-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Sync with NetBSD rcp, add v6 parsing support and no setuid code
+	at all.
+
+2007-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add missing files, from Buchan Milne.
=20
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: more files
 =09
-2006-08-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c: Check return values from setuid, prompted by MIT
 	advisory.  Thanks to Tom Yu at MIT, and Michael Calmer and Marcus
@@ -20,16 +25,16 @@
 	advisory.  Thanks to Tom Yu at MIT, and Michael Calmer and Marcus
 	Meissner at SUSE.  Either of CVE-2006-3083 or CVE-2006-3084.
 =09
-2005-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rcp.c: Check return value from asprintf instead of string !=3D
-	NULL since it undefined behavior on Linux. From Bj=F6rn Sandell
+	NULL since it undefined behavior on Linux. From Bj=C3=B6rn Sandell
 =09
-2005-08-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c: Explicit typecast to avoid signess warning.
 =09
-2005-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rcp_locl.h: undef _PATH_RSH to make sure our version is used
 =09
@@ -38,11 +43,11 @@
 	* rcp.c: MODEMASK is defined in sys/vnode.h on Solaris, so undef
 	it before we define our own.
=20
-2005-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rcp_locl.h: use BINDIR instead of "/usr/bin/ with _PATH_RSH
=20
-2005-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c: use unsigned char * to make sure its not negative when
 	passing it to is* functions
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/Makefile.=
am
--- a/head/crypto/heimdal/appl/rcp/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/rcp/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 22281 2007-12-13 20:35:52Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -10,6 +10,6 @@
=20
 man_MANS =3D rcp.1
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
=20
 LDADD =3D $(LIB_roken)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/Makefile.=
in
--- a/head/crypto/heimdal/appl/rcp/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/rcp/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22281 2007-12-13 20:35:52Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/rcp
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,23 +89,23 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS)
 am_rcp_OBJECTS =3D rcp.$(OBJEXT) util.$(OBJEXT)
 rcp_OBJECTS =3D $(am_rcp_OBJECTS)
 rcp_LDADD =3D $(LDADD)
 am__DEPENDENCIES_1 =3D
 rcp_DEPENDENCIES =3D $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -112,6 +117,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(rcp_SOURCES)
 DIST_SOURCES =3D $(rcp_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -121,49 +147,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -187,10 +222,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -207,6 +243,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -222,31 +260,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -261,10 +313,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -305,51 +359,55 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_krb4)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 rcp_SOURCES =3D rcp.c util.c rcp_locl.h extern.h
 man_MANS =3D rcp.1
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 LDADD =3D $(LIB_roken)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/rcp/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/rcp/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/rcp/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/rcp/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -367,34 +425,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 rcp$(EXEEXT): $(rcp_OBJECTS) $(rcp_DEPENDENCIES)=20
 	@rm -f rcp$(EXEEXT)
 	$(LINK) $(rcp_OBJECTS) $(rcp_LDADD) $(LIBS)
@@ -405,115 +479,140 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rcp.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/util.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -529,13 +628,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -570,6 +673,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -579,6 +683,7 @@
 clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -589,6 +694,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -596,26 +703,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -635,11 +751,10 @@
 uninstall-am: uninstall-binPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libtool ctags \
@@ -726,6 +841,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -811,7 +929,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -824,6 +942,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/extern.h
--- a/head/crypto/heimdal/appl/rcp/extern.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rcp/extern.h	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)extern.h	8.1 (Berkeley) 5/31/93
- * $FreeBSD$
+ * $FreeBSD: head/crypto/heimdal/appl/rcp/extern.h 233294 2012-03-22 08:48=
:42Z stas $
  */
=20
 typedef struct {
@@ -43,9 +43,10 @@
=20
 BUF	*allocbuf (BUF *, int, int);
 char	*colon (char *);
+char    *unbracket(char *);
 void	 lostconn (int);
 void	 nospace (void);
 int	 okname (char *);
 void	 run_err (const char *, ...);
-int	 susystem (char *, int);
+int	 susystem (char *);
 void	 verifydir (char *);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/rcp.1
--- a/head/crypto/heimdal/appl/rcp/rcp.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rcp/rcp.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,11 @@
-.\" $Id: rcp.1 12025 2003-04-16 12:20:43Z joda $
+.\" $Id$
 .\"
 .Dd April 16, 2003
 .Dt RCP 1
 .Os HEIMDAL
 .Sh NAME
 .Nm rcp
-.Nd
-copy file to and from remote machines
+.Nd copy file to and from remote machines
 .Sh SYNOPSIS
 .Nm rcp
 .Op Fl 45FKpxz
@@ -18,7 +17,7 @@
 .Ar file... directory
 .Sh DESCRIPTION
 .Nm rcp
-copies files between machines. Each file argument is either a remote file =
name of the form=20
+copies files between machines. Each file argument is either a remote file =
name of the form
 .Dq rname at rhost:path
 or a local file (containing no colon or with a slash before the first
 colon).
@@ -26,11 +25,11 @@
 Supported options:
 .Bl -tag -width Ds
 .It Xo
-.Fl 4 ,=20
-.Fl 5 ,=20
-.Fl K ,=20
-.Fl F ,=20
-.Fl x ,=20
+.Fl 4 ,
+.Fl 5 ,
+.Fl K ,
+.Fl F ,
+.Fl x ,
 .Fl z
 .Xc
 These options are passed on to
@@ -38,7 +37,7 @@
 .It Fl P Ar port
 This will pass the option
 .Fl p Ar port
-to=20
+to
 .Xr rsh 1 .
 .It Fl p
 Preserve file permissions.
@@ -59,7 +58,7 @@
 .\".Sh SEE ALSO
 .\".Sh STANDARDS
 .Sh HISTORY
-The=20
+The
 .Nm rcp
 utility first appeared in 4.2BSD. This version is derived from
 4.3BSD-Reno.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/rcp.c
--- a/head/crypto/heimdal/appl/rcp/rcp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rcp/rcp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -10,11 +10,7 @@
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *	This product includes software developed by the University of
- *	California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -105,7 +101,7 @@
 	    print_version (NULL);
 	    return 0;
 	}
-	   =20
+
 	iamremote =3D (fflag || tflag);
=20
 	argc -=3D optind;
@@ -118,16 +114,12 @@
 	remout =3D STDOUT_FILENO;
=20
 	if (fflag) {			/* Follow "protocol", send data. */
-		response();
-		if (setuid(userid) < 0)
-			errx(1, "setuid failed");
+		(void)response();
 		source(argc, argv);
 		exit(errs);
 	}
=20
 	if (tflag) {			/* Receive data. */
-		if (setuid(userid) < 0)
-			errx(1, "setuid failed");
 		sink(argc, argv);
 		exit(errs);
 	}
@@ -140,7 +132,7 @@
 	remin =3D remout =3D -1;
 	/* Command to be executed on remote system using "rsh". */
 	snprintf(cmd, sizeof(cmd),
-		 "rcp%s%s%s", iamrecursive ? " -r" : "",=20
+		 "rcp%s%s%s", iamrecursive ? " -r" : "",
 		 pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
=20
 	signal(SIGPIPE, lostconn);
@@ -165,7 +157,7 @@
 	if (*targ =3D=3D 0)
 		targ =3D ".";
=20
-	if ((thost =3D strchr(argv[argc - 1], '@'))) {
+	if ((thost =3D strchr(argv[argc - 1], '@')) !=3D NULL) {
 		/* user at host */
 		*thost++ =3D 0;
 		tuser =3D argv[argc - 1];
@@ -177,6 +169,7 @@
 		thost =3D argv[argc - 1];
 		tuser =3D NULL;
 	}
+	thost =3D unbracket(thost);
=20
 	for (i =3D 0; i < argc - 1; i++) {
 		src =3D colon(argv[i]);
@@ -188,6 +181,7 @@
 			host =3D strchr(argv[i], '@');
 			if (host) {
 				*host++ =3D '\0';
+				host =3D unbracket(host);
 				suser =3D argv[i];
 				if (*suser =3D=3D '\0')
 					suser =3D pwd->pw_name;
@@ -195,21 +189,22 @@
 					continue;
 				ret =3D asprintf(&bp,
 				    "%s%s %s -l %s -n %s %s '%s%s%s:%s'",
-					 _PATH_RSH, eflag ? " -e" : "",=20
+					 _PATH_RSH, eflag ? " -e" : "",
 					 host, suser, cmd, src,
 				    tuser ? tuser : "", tuser ? "@" : "",
 				    thost, targ);
 			} else {
+				host =3D unbracket(argv[i]);
 				ret =3D asprintf(&bp,
 					 "exec %s%s %s -n %s %s '%s%s%s:%s'",
-					 _PATH_RSH, eflag ? " -e" : "",=20
-					 argv[i], cmd, src,
+					 _PATH_RSH, eflag ? " -e" : "",
+					 host, cmd, src,
 					 tuser ? tuser : "", tuser ? "@" : "",
 					 thost, targ);
 			}
 			if (ret =3D=3D -1)
 				err (1, "malloc");
-			susystem(bp, userid);
+			susystem(bp);
 			free(bp);
 		} else {			/* local to remote */
 			if (remin =3D=3D -1) {
@@ -223,8 +218,6 @@
 				if (response() < 0)
 					exit(1);
 				free(bp);
-				if (setuid(userid) < 0)
-					errx(1, "setuid failed");
 			}
 			source(1, argv+i);
 		}
@@ -246,7 +239,7 @@
 			    argv[i], argv[argc - 1]);
 			if (ret =3D=3D -1)
 				err (1, "malloc");
-			if (susystem(bp, userid))
+			if (susystem(bp))
 				++errs;
 			free(bp);
 			continue;
@@ -275,8 +268,6 @@
 		}
 		free(bp);
 		sink(1, argv + argc - 1);
-		if (seteuid(0) < 0)
-			exit(1);
 		close(remin);
 		remin =3D remout =3D -1;
 	}
@@ -289,7 +280,8 @@
 	static BUF buffer;
 	BUF *bp;
 	off_t i;
-	int amt, fd, haderr, indx, result;
+	off_t amt;
+	int fd, haderr, indx, result;
 	char *last, *name, buf[BUFSIZ];
=20
 	for (indx =3D 0; indx < argc; ++indx) {
@@ -300,16 +292,10 @@
 syserr:			run_err("%s: %s", name, strerror(errno));
 			goto next;
 		}
-		switch (stb.st_mode & S_IFMT) {
-		case S_IFREG:
-			break;
-		case S_IFDIR:
-			if (iamrecursive) {
-				rsource(name, &stb);
-				goto next;
-			}
-			/* FALLTHROUGH */
-		default:
+		if (S_ISDIR(stb.st_mode) && iamrecursive) {
+			rsource(name, &stb);
+			goto next;
+		} else if (!S_ISREG(stb.st_mode)) {
 			run_err("%s: not a regular file", name);
 			goto next;
 		}
@@ -332,7 +318,7 @@
 #undef MODEMASK
 #define	MODEMASK	(S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)
 		snprintf(buf, sizeof(buf), "C%04o %lu %s\n",
-			 stb.st_mode & MODEMASK,
+			 (unsigned int)(stb.st_mode & MODEMASK),
 			 (unsigned long)stb.st_size,
 			 last);
 		write(remout, buf, strlen(buf));
@@ -349,14 +335,14 @@
 			if (i + amt > stb.st_size)
 				amt =3D stb.st_size - i;
 			if (!haderr) {
-				result =3D read(fd, bp->buf, amt);
+			        result =3D read(fd, bp->buf, (size_t)amt);
 				if (result !=3D amt)
 					haderr =3D result >=3D 0 ? EIO : errno;
 			}
 			if (haderr)
 				write(remout, bp->buf, amt);
 			else {
-				result =3D write(remout, bp->buf, amt);
+			        result =3D write(remout, bp->buf, (size_t)amt);
 				if (result !=3D amt)
 					haderr =3D result >=3D 0 ? EIO : errno;
 			}
@@ -398,13 +384,14 @@
 		}
 	}
 	snprintf(path, sizeof(path),
-	    "D%04o %d %s\n", statp->st_mode & MODEMASK, 0, last);
+		 "D%04o %d %s\n",
+		 (unsigned int)(statp->st_mode & MODEMASK), 0, last);
 	write(remout, path, strlen(path));
 	if (response() < 0) {
 		closedir(dirp);
 		return;
 	}
-	while ((dp =3D readdir(dirp))) {
+	while ((dp =3D readdir(dirp)) !=3D NULL) {
 		if (dp->d_ino =3D=3D 0)
 			continue;
 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
@@ -600,7 +587,7 @@
 			if (count =3D=3D bp->cnt) {
 				/* Keep reading so we stay sync'd up. */
 				if (wrerr =3D=3D NO) {
-					j =3D write(ofd, bp->buf, count);
+					j =3D write(ofd, bp->buf, (size_t)count);
 					if (j !=3D count) {
 						wrerr =3D YES;
 						wrerrno =3D j >=3D 0 ? EIO : errno;
@@ -611,7 +598,7 @@
 			}
 		}
 		if (count !=3D 0 && wrerr =3D=3D NO &&
-		    (j =3D write(ofd, bp->buf, count)) !=3D count) {
+		    (j =3D write(ofd, bp->buf, (size_t)count)) !=3D count) {
 			wrerr =3D YES;
 			wrerrno =3D j >=3D 0 ? EIO : errno;
 		}
@@ -723,7 +710,7 @@
  * If it cannot create necessary pipes it exits with error message.
  */
=20
-int=20
+int
 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
 {
 	int pin[2], pout[2], reserved[2];
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/rcp_locl.h
--- a/head/crypto/heimdal/appl/rcp/rcp_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rcp/rcp_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: rcp_locl.h 15285 2005-05-29 18:24:43Z lha $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rcp/util.c
--- a/head/crypto/heimdal/appl/rcp/util.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rcp/util.c	Tue Apr 17 11:51:51 2012 +0300
@@ -37,13 +37,13 @@
 static char sccsid[] =3D "@(#)util.c	8.2 (Berkeley) 4/2/94";
 #endif
 static const char rcsid[] =3D
-  "$FreeBSD$";
+  "$FreeBSD: head/crypto/heimdal/appl/rcp/util.c 233294 2012-03-22 08:48:4=
2Z stas $";
 #endif /* not lint */
 #endif
=20
 #include "rcp_locl.h"
=20
-RCSID("$Id: util.c 17878 2006-08-08 21:43:58Z lha $");
+RCSID("$Id$");
=20
 char *
 colon(cp)
@@ -61,6 +61,21 @@
 	return (0);
 }
=20
+char *
+unbracket(char *cp)
+{
+	char *ep;
+
+	if (*cp =3D=3D '[') {
+		ep =3D cp + (strlen(cp) - 1);
+		if (*ep =3D=3D ']') {
+			*ep =3D '\0';
+			++cp;
+		}
+	}
+	return (cp);
+}
+
 void
 verifydir(cp)
 	char *cp;
@@ -98,8 +113,7 @@
 }
=20
 int
-susystem(s, userid)
-	int userid;
+susystem(s)
 	char *s;
 {
 	void (*istat)(int), (*qstat)(int);
@@ -112,8 +126,6 @@
 		return (127);
=20
 	case 0:
-		if (setuid(userid) < 0)
-			_exit(127);
 		execl(_PATH_BSHELL, "sh", "-c", s, NULL);
 		_exit(127);
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/ChangeLog
--- a/head/crypto/heimdal/appl/rsh/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rsh/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,27 +1,27 @@
-2007-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rsh.c: Fix pointer vs strict alias rules.
=20
 	* rshd.c: Fix pointer vs strict alias rules.
=20
-2007-01-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* rshd.c: Declare iruserok if needed, based on bug report from
 	David Love.
 =09
-2006-11-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* rsh_locl.h: Forward decl.
 =09
-2006-10-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rsh_locl.h: Include "crypto-headers.h".
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add man_MANS to EXTRA_DIST
 =09
-2006-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: rshd_SOURCES +=3D add limits_conf.c
=20
@@ -38,30 +38,30 @@
=20
 	* rshd.c (krb5_start_session): syslog failures to store cred cache
 =09
-2005-12-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rshd.c (doit): move creation of users ticket file to later to
 	avoid seteuid/setuid dance. this breaks DCE, so remove support for
 	it completely.
 =09
-2005-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rshd.c: Check return value from asprintf instead of string !=3D
-	NULL since it undefined behavior on Linux. From Bj=F6rn Sandell
+	NULL since it undefined behavior on Linux. From Bj=C3=B6rn Sandell
=20
 	* rsh.c: Check return value from asprintf instead of string !=3D
-	NULL since it undefined behavior on Linux. From Bj=F6rn Sandell
+	NULL since it undefined behavior on Linux. From Bj=C3=B6rn Sandell
=20
-2005-06-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rshd.c: init some important variables and check that they are
 	set checking authentication, all to please gcc
=20
-2005-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rshd.c: case uid_t to unsigned long in printf format
 =09
-2005-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rsh_locl.h: Use larger buffer for recving data to be compatible
 	with older versions of heimdal (0.4 branch specificly)
@@ -69,11 +69,11 @@
 	* rshd.c: Use larger buffer for recving data to be compatible with
 	older versions of heimdal (0.4 branch specificly)
=20
-2005-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rshd.c: use snprintf to format tkfile
 =09
-2005-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rsh.c: use strlcat
=20
@@ -81,7 +81,7 @@
=20
 	* rsh_locl.h: forward declaration for private structures
=20
-2005-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rsh.c: cast size_t to unsigned long
=20
@@ -119,7 +119,7 @@
=20
 	* rshd.c: -P also with KRB5
 =09
-2003-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rsh.1: replace > with \*[Gt]
 =09
@@ -138,7 +138,7 @@
=20
 	* rsh.c (loop): only check errsock if it's valid
=20
-2003-03-18  Love  Love H=F6rnquist =C5strand <lha at it.su.se>
+2003-03-18  Love  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* rshd.c: do krb5_afslog when compling with afs support
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/Makefile.=
am
--- a/head/crypto/heimdal/appl/rsh/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/rsh/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,8 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_krb4) -I$(srcdir)/../login
+AM_CPPFLAGS +=3D -I$(srcdir)/../login $(INCLUDE_hcrypto)
=20
 bin_PROGRAMS =3D rsh
=20
@@ -22,8 +22,7 @@
=20
 LDADD =3D $(LIB_kafs) \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/Makefile.=
in
--- a/head/crypto/heimdal/appl/rsh/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/appl/rsh/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -46,7 +48,7 @@
 subdir =3D appl/rsh
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -61,7 +63,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -75,9 +77,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -85,16 +90,15 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" \
 	"$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS) $(libexec_PROGRAMS)
 am_rsh_OBJECTS =3D rsh.$(OBJEXT) common.$(OBJEXT)
 rsh_OBJECTS =3D $(am_rsh_OBJECTS)
@@ -103,18 +107,16 @@
 am__DEPENDENCIES_2 =3D $(top_builddir)/lib/kafs/libkafs.la \
 	$(am__DEPENDENCIES_1)
 rsh_DEPENDENCIES =3D $(am__DEPENDENCIES_2) $(LIB_krb5) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
 am_rshd_OBJECTS =3D rshd.$(OBJEXT) common.$(OBJEXT) \
 	login_access.$(OBJEXT) limits_conf.$(OBJEXT)
 rshd_OBJECTS =3D $(am_rshd_OBJECTS)
 rshd_LDADD =3D $(LDADD)
 rshd_DEPENDENCIES =3D $(am__DEPENDENCIES_2) $(LIB_krb5) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -126,6 +128,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(rsh_SOURCES) $(rshd_SOURCES)
 DIST_SOURCES =3D $(rsh_SOURCES) $(rshd_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
@@ -136,49 +159,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -202,10 +234,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -222,6 +255,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -237,31 +272,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -276,10 +325,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -320,57 +371,61 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4) -I$(srcdir)/../login
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I$(srcdir)/../login \
+	$(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 man_MANS =3D rsh.1 rshd.8
 rsh_SOURCES =3D rsh.c common.c rsh_locl.h
 rshd_SOURCES =3D rshd.c common.c login_access.c limits_conf.c rsh_locl.h
 LDADD =3D $(LIB_kafs) \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/rsh/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/rsh/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/rsh/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/rsh/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -388,62 +443,93 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 rsh$(EXEEXT): $(rsh_OBJECTS) $(rsh_DEPENDENCIES)=20
 	@rm -f rsh$(EXEEXT)
 	$(LINK) $(rsh_OBJECTS) $(rsh_LDADD) $(LIBS)
@@ -457,160 +543,181 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/common.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/limits_conf.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/login_access.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rsh.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rshd.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
-install-man8: $(man8_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -626,13 +733,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -667,6 +778,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -677,6 +789,7 @@
 	clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -687,6 +800,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -694,26 +809,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -734,11 +858,10 @@
 	uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1 uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libexecPROGRAMS \
@@ -827,6 +950,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -912,7 +1038,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -931,6 +1057,7 @@
=20
 limits_conf.c:
 	$(LN_S) $(srcdir)/../login/limits_conf.c .
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/common.c
--- a/head/crypto/heimdal/appl/rsh/common.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rsh/common.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "rsh_locl.h"
-RCSID("$Id: common.c 17450 2006-05-05 11:11:43Z lha $");
+RCSID("$Id$");
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
=20
 #ifdef KRB5
 int key_usage =3D 1026;
@@ -74,11 +74,6 @@
 do_read (int fd, void *buf, size_t sz, void *ivec)
 {
     if (do_encrypt) {
-#ifdef KRB4
-	if (auth_method =3D=3D AUTH_KRB4) {
-	    return des_enc_read (fd, buf, sz, schedule, &iv);
-	} else
-#endif /* KRB4 */
 #ifdef KRB5
         if(auth_method =3D=3D AUTH_KRB5) {
 	    krb5_error_code ret;
@@ -102,13 +97,15 @@
 	    if (edata =3D=3D NULL)
 		errx (1, "malloc: cannot allocate %u bytes", outer_len);
 	    ret =3D krb5_net_read (context, &fd, edata, outer_len);
-	    if (ret <=3D 0)
+	    if (ret <=3D 0) {
+		free(edata);
 		return ret;
+	    }
=20
-	    status =3D krb5_decrypt_ivec(context, crypto, key_usage,=20
+	    status =3D krb5_decrypt_ivec(context, crypto, key_usage,
 				       edata, outer_len, &data, ivec);
 	    free (edata);
-	   =20
+
 	    if (status)
 		krb5_err (context, 1, status, "decrypting data");
 	    if(ivec !=3D NULL) {
@@ -134,11 +131,6 @@
 do_write (int fd, void *buf, size_t sz, void *ivec)
 {
     if (do_encrypt) {
-#ifdef KRB4
-	if(auth_method =3D=3D AUTH_KRB4) {
-	    return des_enc_write (fd, buf, sz, schedule, &iv);
-	} else
-#endif /* KRB4 */
 #ifdef KRB5
 	if(auth_method =3D=3D AUTH_KRB5) {
 	    krb5_error_code status;
@@ -177,4 +169,4 @@
     } else
 	return write (fd, buf, sz);
 }
-#endif /* KRB4 || KRB5 */
+#endif /* KRB5 */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/limits_co=
nf.c
--- a/head/crypto/heimdal/appl/rsh/limits_conf.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/rsh/limits_conf.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "login_locl.h"
=20
-RCSID("$Id: limits_conf.c 19215 2006-12-04 23:41:18Z lha $");
+RCSID("$Id$");
=20
 #include <errno.h>
 #include <limits.h>
@@ -91,7 +91,7 @@
 /* this function reads limits.conf files similar to pam_limits
    unimplemented features include:
    	% maxlogins
-	"-" no limits,=20
+	"-" no limits,
 	priorities etc that are not set via setrlimit
    XXX uses static storage, and clobbers getgr*
 */
@@ -131,7 +131,7 @@
 	    int c;
 	    while((c =3D fgetc(f)) !=3D EOF) {
 		eof =3D 0;
-		if(c =3D=3D '\n')=20
+		if(c =3D=3D '\n')
 		    break;
 	    }
 	    if(!eof) {
@@ -192,12 +192,12 @@
 		continue;
 	    l->has_limit =3D level;
 	}
-=09
+
 	/* XXX unclear: if you soft to more than default hard, should
            we set hard to soft? this code doesn't. */
 	if(strcasecmp(args[1], "soft") =3D=3D 0 || strcmp(args[1], "-") =3D=3D 0)
 	    l->limit.rlim_cur =3D value;
-	if(strcasecmp(args[1], "hard") =3D=3D 0 || strcmp(args[1], "-") =3D=3D 0)=20
+	if(strcasecmp(args[1], "hard") =3D=3D 0 || strcmp(args[1], "-") =3D=3D 0)
 	    l->limit.rlim_max =3D value;
     }
     fclose(f);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/login_acc=
ess.c
--- a/head/crypto/heimdal/appl/rsh/login_access.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/rsh/login_access.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -25,7 +25,7 @@
=20
 #include "login_locl.h"
=20
-RCSID("$Id: login_access.c 10020 2001-06-04 14:10:19Z assar $");
+RCSID("$Id$");
=20
  /* Delimiters for fields and for lists of users, ttys or hosts. */
=20
@@ -101,13 +101,13 @@
 		|| !(users =3D strtok_r(NULL, fs, &foo))
 		|| !(froms =3D strtok_r(NULL, fs, &foo))
 		|| strtok_r(NULL, fs, &foo)) {
-		syslog(LOG_ERR, "%s: line %d: bad field count",=20
+		syslog(LOG_ERR, "%s: line %d: bad field count",
 		       _PATH_LOGACCESS,
 		       lineno);
 		continue;
 	    }
 	    if (perm[0] !=3D '+' && perm[0] !=3D '-') {
-		syslog(LOG_ERR, "%s: line %d: bad first field",=20
+		syslog(LOG_ERR, "%s: line %d: bad first field",
 		       _PATH_LOGACCESS,
 		       lineno);
 		continue;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/rsh.1
--- a/head/crypto/heimdal/appl/rsh/rsh.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rsh/rsh.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,42 @@
-.\" Copyright (c) 2002 - 2003 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2002 - 2003 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\"	$Id: rsh.1 13394 2004-02-20 12:21:42Z joda $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\"	$Id$
 .\"
 .Dd February 20, 2004
 .Dt RSH 1
 .Os HEIMDAL
 .Sh NAME
 .Nm rsh
-.Nd
-remote shell
+.Nd remote shell
 .Sh SYNOPSIS
 .Nm
 .Op Fl 45FGKdefnuxz
@@ -63,7 +62,7 @@
 .Bl -tag -width Ds
 .It Xo
 .Fl 4 ,
-.Fl -krb4
+.Fl Fl krb4
 .Xc
 The
 .Fl 4
@@ -72,7 +71,7 @@
 explicit control is desired.
 .It Xo
 .Fl 5 ,
-.Fl -krb5
+.Fl Fl krb5
 .Xc
 The
 .Fl 5
@@ -81,7 +80,7 @@
 option.
 .It Xo
 .Fl K ,
-.Fl -broken
+.Fl Fl broken
 .Xc
 The
 .Fl K
@@ -90,7 +89,7 @@
 good this is.
 .It Xo
 .Fl n ,
-.Fl -no-input
+.Fl Fl no-input
 .Xc
 The
 .Fl n
@@ -105,13 +104,13 @@
 socket debugging.
 .It Xo
 .Fl e ,
-.Fl -no-stderr
+.Fl Fl no-stderr
 .Xc
 Don't use a separate socket for the stderr stream. This can be
 necessary if rsh-ing through a NAT bridge.
 .It Xo
 .Fl x ,
-.Fl -encrypt
+.Fl Fl encrypt
 .Xc
 The
 .Fl x
@@ -127,12 +126,12 @@
 This is the default, and is mainly useful if encryption has been
 enabled by default, for instance in the
 .Li appdefaults
-section of=20
+section of
 .Pa /etc/krb5.conf
 when using Kerberos 5.
 .It Xo
 .Fl f ,
-.Fl -forward
+.Fl Fl forward
 .Xc
 Forward Kerberos 5 credentials to the remote host.
 Also settable via
@@ -141,16 +140,16 @@
 .Xr krb5.conf ) .
 .It Xo
 .Fl F ,
-.Fl -forwardable
+.Fl Fl forwardable
 .Xc
-Make the forwarded credentials re-forwardable.=20
+Make the forwarded credentials re-forwardable.
 Also settable via
 .Li appdefaults
 (see
 .Xr krb5.conf ) .
 .It Xo
 .Fl l Ar string ,
-.Fl -user=3D Ns Ar string
+.Fl Fl user=3D Ns Ar string
 .Xc
 By default the remote username is the same as the local. The
 .Fl l
@@ -159,16 +158,16 @@
 format allow the remote name to be specified.
 .It Xo
 .Fl n ,
-.Fl -no-input
+.Fl Fl no-input
 .Xc
-Direct input from=20
+Direct input from
 .Pa /dev/null
 (see the
 .Sx BUGS
 section).
 .It Xo
 .Fl p Ar number-or-service ,
-.Fl -port=3D Ns Ar number-or-service
+.Fl Fl port=3D Ns Ar number-or-service
 .Xc
 Connect to this port instead of the default (which is 514 when using
 old port based authentication, 544 for Kerberos 5 and non-encrypted
@@ -177,13 +176,13 @@
 .Pa /etc/services ) .
 .It Xo
 .Fl P Ar N|O|1|2 ,
-.Fl -protocol=3D Ns Ar N|O|1|2
+.Fl Fl protocol=3D Ns Ar N|O|1|2
 .Xc
 Specifies the protocol version to use with Kerberos 5.
 .Ar N
 and
 .Ar 2
-select protocol version 2, while=20
+select protocol version 2, while
 .Ar O
 and
 .Ar 1
@@ -193,20 +192,20 @@
 will try both.  This behaviour may change in the future.
 .It Xo
 .Fl u ,
-.Fl -unique
+.Fl Fl unique
 .Xc
 Make sure the remote credentials cache is unique, that is, don't reuse
 any existing cache. Mutually exclusive to
 .Fl U .
 .It Xo
 .Fl U Pa string ,
-.Fl -tkfile=3D Ns Pa string
+.Fl Fl tkfile=3D Ns Pa string
 .Xc
 Name of the remote credentials cache. Mutually exclusive to
 .Fl u .
 .It Xo
 .Fl x ,
-.Fl -encrypt
+.Fl Fl encrypt
 .Xc
 The
 .Fl x
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/rsh.c
--- a/head/crypto/heimdal/appl/rsh/rsh.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rsh/rsh.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "rsh_locl.h"
-RCSID("$Id: rsh.c 21516 2007-07-12 12:47:23Z lha $");
+RCSID("$Id$");
=20
 enum auth_method auth_method;
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 int do_encrypt       =3D -1;
 #endif
 #ifdef KRB5
@@ -48,19 +48,12 @@
 krb5_keyblock *keyblock;
 krb5_crypto crypto;
 #endif
-#ifdef KRB4
-des_key_schedule schedule;
-des_cblock iv;
-#endif
 int sock_debug	     =3D 0;
=20
-#ifdef KRB4
-static int use_v4 =3D -1;
-#endif
 #ifdef KRB5
 static int use_v5 =3D -1;
 #endif
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 static int use_only_broken =3D 0;
 #else
 static int use_only_broken =3D 1;
@@ -95,7 +88,7 @@
=20
     if (s >=3D FD_SETSIZE || (errsock !=3D -1 && errsock >=3D FD_SETSIZE))
 	errx (1, "fd too large");
-   =20
+
     FD_ZERO(&real_readset);
     FD_SET(s, &real_readset);
     if (errsock !=3D -1) {
@@ -156,50 +149,6 @@
     }
 }
=20
-#ifdef KRB4
-static int
-send_krb4_auth(int s,
-	       struct sockaddr *thisaddr,
-	       struct sockaddr *thataddr,
-	       const char *hostname,
-	       const char *remote_user,
-	       const char *local_user,
-	       size_t cmd_len,
-	       const char *cmd)
-{
-    KTEXT_ST text;
-    CREDENTIALS cred;
-    MSG_DAT msg;
-    int status;
-    size_t len;
-
-    /* the normal default for krb4 should be to disable encryption */
-    status =3D krb_sendauth ((do_encrypt =3D=3D 1) ? KOPT_DO_MUTUAL : 0,
-			   s, &text, "rcmd",
-			   (char *)hostname, krb_realmofhost (hostname),
-			   getpid(), &msg, &cred, schedule,
-			   (struct sockaddr_in *)thisaddr,
-			   (struct sockaddr_in *)thataddr,
-			   KCMD_OLD_VERSION);
-    if (status !=3D KSUCCESS) {
-	warnx("%s: %s", hostname, krb_get_err_text(status));
-	return 1;
-    }
-    memcpy (iv, cred.session, sizeof(iv));
-
-    len =3D strlen(remote_user) + 1;
-    if (net_write (s, remote_user, len) !=3D len) {
-	warn("write");
-	return 1;
-    }
-    if (net_write (s, cmd, cmd_len) !=3D cmd_len) {
-	warn("write");
-	return 1;
-    }
-    return 0;
-}
-#endif /* KRB4 */
-
 #ifdef KRB5
 /*
  * Send forward information on `s' for host `hostname', them being
@@ -236,17 +185,16 @@
     }
=20
     creds.client =3D principal;
-   =20
-    ret =3D krb5_build_principal (context,
-				&creds.server,
-				strlen(principal->realm),
-				principal->realm,
-				"krbtgt",
-				principal->realm,
-				NULL);
+
+    ret =3D krb5_make_principal(context,
+			      &creds.server,
+			      principal->realm,
+			      "krbtgt",
+			      principal->realm,
+			      NULL);
=20
     if (ret) {
-	warnx ("could not forward creds: krb5_build_principal: %s",
+	warnx ("could not forward creds: krb5_make_principal: %s",
 	       krb5_get_err_text (context, ret));
 	return 1;
     }
@@ -313,10 +261,10 @@
     }
=20
     if(do_encrypt =3D=3D -1) {
-	krb5_appdefault_boolean(context, NULL,=20
-				krb5_principal_get_realm(context, server),=20
-				"encrypt",=20
-				FALSE,=20
+	krb5_appdefault_boolean(context, NULL,
+				krb5_principal_get_realm(context, server),
+				"encrypt",
+				FALSE,
 				&do_encrypt);
     }
=20
@@ -349,7 +297,7 @@
     default:
 	abort();
     }
-=09
+
     status =3D krb5_sendauth (context,
 			    &auth_context,
 			    &s,
@@ -369,19 +317,19 @@
 	krb5_const_realm realm =3D krb5_principal_get_realm(context, server);
 	if (do_forwardable =3D=3D -1)
 	    krb5_appdefault_boolean(context, NULL, realm,
-				    "forwardable", FALSE,=20
+				    "forwardable", FALSE,
 				    &do_forwardable);
 	if (do_forward =3D=3D -1)
 	    krb5_appdefault_boolean(context, NULL, realm,
-				    "forward", FALSE,=20
+				    "forward", FALSE,
 				    &do_forward);
     }
-   =20
+
     krb5_free_principal(context, server);
     krb5_data_free(&cksum_data);
=20
     if (status) {
-	if(status =3D=3D KRB5_SENDAUTH_REJECTED &&=20
+	if(status =3D=3D KRB5_SENDAUTH_REJECTED &&
 	   protocol_version =3D=3D 2 && protocol_version_str =3D=3D NULL)
 	    sendauth_version_error =3D 1;
 	else
@@ -593,7 +541,7 @@
 		     cmd_len, cmd)) {
 	close (errsock2);
 	return 1;
-    }=20
+    }
=20
     ret =3D net_read (s, &reply, 1);
     if (ret < 0) {
@@ -625,7 +573,7 @@
 		       (void *)&one, sizeof(one)) < 0)
 	    warn("setsockopt stderr");
     }
-   =20
+
     return rsh_loop (s, errsock2);
 }
=20
@@ -666,11 +614,11 @@
     const char *as =3D NULL;
=20
     if(sa->sa_family =3D=3D AF_INET)
-	as =3D inet_ntop (sa->sa_family, &((struct sockaddr_in*)sa)->sin_addr,=20
+	as =3D inet_ntop (sa->sa_family, &((struct sockaddr_in*)sa)->sin_addr,
 			addr_str, sizeof(addr_str));
 #ifdef HAVE_INET6
     else if(sa->sa_family =3D=3D AF_INET6)
-	as =3D inet_ntop (sa->sa_family, &((struct sockaddr_in6*)sa)->sin6_addr,=20
+	as =3D inet_ntop (sa->sa_family, &((struct sockaddr_in6*)sa)->sin6_addr,
 			addr_str, sizeof(addr_str));
 #endif
     if(as =3D=3D NULL)
@@ -697,7 +645,7 @@
=20
     if (connect (priv_socket1, ai->ai_addr, ai->ai_addrlen) < 0) {
 	int save_errno =3D errno;
-=09
+
 	close(priv_socket1);
 	close(priv_socket2);
=20
@@ -754,7 +702,7 @@
     }
 }
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 static int
 doit (const char *hostname,
       struct addrinfo *ai,
@@ -778,12 +726,12 @@
 	int errsock;
=20
 	s =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
-	if (s < 0)=20
+	if (s < 0)
 	    continue;
 	socketfailed =3D 0;
 	if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
 	    char addr[128];
-	    if(getnameinfo(a->ai_addr, a->ai_addrlen,=20
+	    if(getnameinfo(a->ai_addr, a->ai_addrlen,
 			   addr, sizeof(addr), NULL, 0, NI_NUMERICHOST) =3D=3D 0)
 		warn ("connect(%s [%s])", hostname, addr);
 	    else
@@ -820,7 +768,7 @@
 	    freeaddrinfo (eai);
 	} else
 	    errsock =3D -1;
-   =20
+
 	ret =3D proto (s, errsock,
 		     hostname,
 		     local_user, remote_user,
@@ -832,12 +780,9 @@
 	warnx ("failed to contact %s", hostname);
     return -1;
 }
-#endif /* KRB4 || KRB5 */
+#endif /* KRB5 */
=20
 struct getargs args[] =3D {
-#ifdef KRB4
-    { "krb4",	'4', arg_flag,		&use_v4,	"Use Kerberos V4" },
-#endif
 #ifdef KRB5
     { "krb5",	'5', arg_flag,		&use_v5,	"Use Kerberos V5" },
     { "forward", 'f', arg_flag,		&do_forward,	"Forward credentials [krb5]"=
},
@@ -848,11 +793,11 @@
       "Use unique remote credentials cache [krb5]" },
     { "tkfile", 'U', arg_string,  &unique_tkfile,
       "Specifies remote credentials cache [krb5]" },
-    { "protocol", 'P', arg_string,      &protocol_version_str,=20
+    { "protocol", 'P', arg_string,      &protocol_version_str,
       "Protocol version [krb5]", "protocol" },
 #endif
     { "broken", 'K', arg_flag,		&use_only_broken, "Use only priv port" },
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
     { "encrypt", 'x', arg_flag,		&do_encrypt,	"Encrypt connection" },
     { NULL, 	'z', arg_negative_flag,      &do_encrypt,
       "Don't encrypt connection", NULL },
@@ -909,14 +854,14 @@
     uid =3D getuid ();
     if (setuid (uid) || (uid !=3D 0 && setuid(0) =3D=3D 0))
 	err (1, "setuid");
-   =20
+
     setprogname (argv[0]);
=20
     if (argc >=3D 2 && argv[1][0] !=3D '-') {
 	host =3D argv[host_index =3D 1];
 	argindex =3D 1;
     }
-   =20
+
     if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
 		&argindex))
 	usage (1);
@@ -940,7 +885,7 @@
 	    int v;
 	    v =3D strtol(protocol_version_str, &end, 0);
 	    if(*end !=3D '\0' || (v !=3D 1 && v !=3D 2)) {
-		errx(1, "unknown protocol version \"%s\"",=20
+		errx(1, "unknown protocol version \"%s\"",
 		     protocol_version_str);
 	    }
 	    protocol_version =3D v;
@@ -962,17 +907,7 @@
=20
 #endif
=20
-#if defined(KRB4) && defined(KRB5)
-    if(use_v4 =3D=3D -1 && use_v5 =3D=3D 1)
-	use_v4 =3D 0;
-    if(use_v5 =3D=3D -1 && use_v4 =3D=3D 1)
-	use_v5 =3D 0;
-#endif   =20
-
     if (use_only_broken) {
-#ifdef KRB4
-	use_v4 =3D 0;
-#endif
 #ifdef KRB5
 	use_v5 =3D 0;
 #endif
@@ -984,7 +919,7 @@
 	use_broken =3D 0;
     }
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
     if (do_encrypt =3D=3D 1 && use_only_broken)
 	errx (1, "encryption not supported with old style authentication");
 #endif
@@ -1013,7 +948,7 @@
 	else
 	    host =3D argv[host_index =3D argindex++];
     }
-   =20
+
     if((tmp =3D strchr(host, '@')) !=3D NULL) {
 	*tmp++ =3D '\0';
 	user =3D host;
@@ -1036,7 +971,7 @@
 	user =3D local_user;
=20
     cmd_len =3D construct_command(&cmd, argc - argindex, argv + argindex);
-   =20
+
     /*
      * Try all different authentication methods
      */
@@ -1061,7 +996,7 @@
       again:
 	ret =3D doit (host, ai, user, local_user, cmd, cmd_len,
 		    send_krb5_auth);
-	if(ret !=3D 0 && sendauth_version_error &&=20
+	if(ret !=3D 0 && sendauth_version_error &&
 	   protocol_version =3D=3D 2) {
 	    protocol_version =3D 1;
 	    goto again;
@@ -1069,33 +1004,6 @@
 	freeaddrinfo(ai);
     }
 #endif
-#ifdef KRB4
-    if (ret && use_v4) {
-	memset (&hints, 0, sizeof(hints));
-	hints.ai_socktype =3D SOCK_STREAM;
-	hints.ai_protocol =3D IPPROTO_TCP;
-
-	if(port_str =3D=3D NULL) {
-	    if(do_encrypt) {
-		error =3D getaddrinfo(host, "ekshell", &hints, &ai);
-		if(error =3D=3D EAI_NONAME)
-		    error =3D getaddrinfo(host, "545", &hints, &ai);
-	    } else {
-		error =3D getaddrinfo(host, "kshell", &hints, &ai);
-		if(error =3D=3D EAI_NONAME)
-		    error =3D getaddrinfo(host, "544", &hints, &ai);
-	    }
-	} else
-	    error =3D getaddrinfo(host, port_str, &hints, &ai);
-
-	if(error)
-	    errx (1, "getaddrinfo: %s", gai_strerror(error));
-	auth_method =3D AUTH_KRB4;
-	ret =3D doit (host, ai, user, local_user, cmd, cmd_len,
-		    send_krb4_auth);
-	freeaddrinfo(ai);
-    }
-#endif
     if (ret && use_broken) {
 	memset (&hints, 0, sizeof(hints));
 	hints.ai_socktype =3D SOCK_STREAM;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/rsh_locl.h
--- a/head/crypto/heimdal/appl/rsh/rsh_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rsh/rsh_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: rsh_locl.h 21553 2007-07-15 09:04:52Z lha $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
@@ -96,22 +96,23 @@
 #include <err.h>
 #include <roken.h>
 #include <getarg.h>
-#ifdef KRB4
-#include <krb.h>
-#include <prot.h>
-#endif
 #ifdef KRB5
 #include <krb5.h>
 /* XXX */
+struct hx509_certs_data;
 struct krb5_pk_identity;
 struct krb5_pk_cert;
 struct ContentInfo;
+struct AlgorithmIdentifier;
 struct _krb5_krb_auth_data;
 struct krb5_dh_moduli;
+struct _krb5_key_data;
+struct _krb5_encryption_type;
+struct _krb5_key_type;
 #include "crypto-headers.h"
 #include <krb5-private.h> /* for _krb5_{get,put}_int */
 #endif
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 #include <kafs.h>
 #endif
=20
@@ -129,7 +130,7 @@
  *
  */
=20
-enum auth_method { AUTH_KRB4, AUTH_KRB5, AUTH_BROKEN };
+enum auth_method { AUTH_KRB5, AUTH_BROKEN };
=20
 extern enum auth_method auth_method;
 extern int do_encrypt;
@@ -142,10 +143,6 @@
 extern void *ivec_out[2];
 void init_ivecs(int, int);
 #endif
-#ifdef KRB4
-extern des_key_schedule schedule;
-extern des_cblock iv;
-#endif
=20
 #define KCMD_OLD_VERSION "KCMDV0.1"
 #define KCMD_NEW_VERSION "KCMDV0.2"
@@ -160,7 +157,7 @@
=20
 #define PATH_RSH BINDIR "/rsh"
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 ssize_t do_read (int, void*, size_t, void*);
 ssize_t do_write (int, void*, size_t, void*);
 #else
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/rshd.8
--- a/head/crypto/heimdal/appl/rsh/rshd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rsh/rshd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,42 @@
-.\" Copyright (c) 2001 - 2006 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2001 - 2006 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: rshd.8 16764 2006-02-27 10:07:04Z joda $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd November 22, 2002
 .Dt RSHD 8
 .Os HEIMDAL
 .Sh NAME
 .Nm rshd
-.Nd
-remote shell server
+.Nd remote shell server
 .Sh SYNOPSIS
 .Nm
 .Op Fl aiklnvxPL
@@ -52,14 +51,14 @@
 .Bl -tag -width Ds
 .It Xo
 .Fl n ,
-.Fl -no-keepalive
+.Fl Fl no-keepalive
 .Xc
 Disables keep-alive messages.
 Keep-alives are packets sent at certain intervals to make sure that the
 client is still there, even when it doesn't send any data.
 .It Xo
 .Fl k ,
-.Fl -kerberos
+.Fl Fl kerberos
 .Xc
 Assume that clients connecting to this server will use some form of
 Kerberos authentication. See the
@@ -69,7 +68,7 @@
 configuration.
 .It Xo
 .Fl x ,
-.Fl -encrypt
+.Fl Fl encrypt
 .Xc
 For Kerberos 4 this means that the connections are encrypted. Kerberos
 5 can negotiate encryption even without this option, but if it's
@@ -79,14 +78,14 @@
 .Fl k .
 .\".It Xo
 .\".Fl l ,
-.\".Fl -no-rhosts
+.\".Fl Fl no-rhosts
 .\".Xc
 .\"When using old port-based authentication, the user's
 .\".Pa .rhosts
 .\"files are normally checked. This option disables this.
 .It Xo
 .Fl v ,
-.Fl -vacuous
+.Fl Fl vacuous
 .Xc
 If the connecting client does not use any Kerberised authentication,
 print a message that complains about this fact, and exit. This is
@@ -104,7 +103,7 @@
 peculiar environments, such as some batch systems.
 .It Xo
 .Fl i ,
-.Fl -no-inetd
+.Fl Fl no-inetd
 .Xc
 The
 .Fl i
@@ -115,7 +114,7 @@
 This is mostly useful for debugging.
 .It Xo
 .Fl p Ar port ,
-.Fl -port=3D Ns Ar port
+.Fl Fl port=3D Ns Ar port
 .Xc
 Port to use with
 .Fl i .
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/rsh/rshd.c
--- a/head/crypto/heimdal/appl/rsh/rshd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/rsh/rshd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "rsh_locl.h"
 #include "login_locl.h"
-RCSID("$Id: rshd.c 21515 2007-07-12 12:47:07Z lha $");
+RCSID("$Id$");
=20
 int
 login_access( struct passwd *user, char *from);
@@ -52,11 +52,6 @@
 krb5_crypto crypto;
 #endif
=20
-#ifdef KRB4
-des_key_schedule schedule;
-des_cblock iv;
-#endif
-
 #ifdef KRB5
 krb5_ccache ccache, ccache2;
 int kerberos_status =3D 0;
@@ -71,7 +66,6 @@
 static char *port_str;
 static int do_rhosts =3D 1;
 static int do_kerberos =3D 0;
-#define DO_KRB4 2
 #define DO_KRB5 4
 static int do_vacuous =3D 0;
 static int do_log =3D 1;
@@ -113,7 +107,7 @@
     len =3D min(len, sizeof(buf) - 1);
     va_end(args);
     if(what !=3D NULL)
-	syslog (LOG_ERR, "%s: %m: %s", what, buf + 1);
+	syslog (LOG_ERR, "%s: %s: %s", what, strerror(errno), buf + 1);
     else
 	syslog (LOG_ERR, "%s", buf + 1);
     net_write (sock, buf, len + 1);
@@ -129,7 +123,7 @@
 	fatal(s, NULL, "%s too long", expl);
     while(p < str + sz) {
 	if(net_read(s, p, 1) !=3D 1)
-	    syslog_and_die("read: %m");
+	    syslog_and_die("read: %s", strerror(errno));
 	if(*p =3D=3D '\0')
 	    return str;
 	p++;
@@ -146,7 +140,7 @@
 	       char **cmd)
 {
     struct passwd *pwd;
-   =20
+
     *client_username =3D read_str (s, USERNAME_SZ, "local username");
     *server_username =3D read_str (s, USERNAME_SZ, "remote username");
     *cmd =3D read_str (s, ARG_MAX + 1, "command");
@@ -159,72 +153,8 @@
     return 0;
 }
=20
-#ifdef KRB4
+#ifdef KRB5
 static int
-recv_krb4_auth (int s, u_char *buf,
-		struct sockaddr *thisaddr,
-		struct sockaddr *thataddr,
-		char **client_username,
-		char **server_username,
-		char **cmd)
-{
-    int status;
-    int32_t options;
-    KTEXT_ST ticket;
-    AUTH_DAT auth;
-    char instance[INST_SZ + 1];
-    char version[KRB_SENDAUTH_VLEN + 1];
-
-    if (memcmp (buf, KRB_SENDAUTH_VERS, 4) !=3D 0)
-	return -1;
-    if (net_read (s, buf + 4, KRB_SENDAUTH_VLEN - 4) !=3D
-	KRB_SENDAUTH_VLEN - 4)
-	syslog_and_die ("reading auth info: %m");
-    if (memcmp (buf, KRB_SENDAUTH_VERS, KRB_SENDAUTH_VLEN) !=3D 0)
-	syslog_and_die("unrecognized auth protocol: %.8s", buf);
-
-    options =3D KOPT_IGNORE_PROTOCOL;
-    if (do_encrypt)
-	options |=3D KOPT_DO_MUTUAL;
-    k_getsockinst (s, instance, sizeof(instance));
-    status =3D krb_recvauth (options,
-			   s,
-			   &ticket,
-			   "rcmd",
-			   instance,
-			   (struct sockaddr_in *)thataddr,
-			   (struct sockaddr_in *)thisaddr,
-			   &auth,
-			   "",
-			   schedule,
-			   version);
-    if (status !=3D KSUCCESS)
-	syslog_and_die ("recvauth: %s", krb_get_err_text(status));
-    if (strncmp (version, KCMD_OLD_VERSION, KRB_SENDAUTH_VLEN) !=3D 0)
-	syslog_and_die ("bad version: %s", version);
-
-    *server_username =3D read_str (s, USERNAME_SZ, "remote username");
-    if (kuserok (&auth, *server_username) !=3D 0)
-	fatal (s, NULL, "Permission denied.");
-    *cmd =3D read_str (s, ARG_MAX + 1, "command");
-
-    syslog(LOG_INFO|LOG_AUTH,
-	   "kerberos v4 shell from %s on %s as %s, cmd '%.80s'",
-	   krb_unparse_name_long(auth.pname, auth.pinst, auth.prealm),
-
-	   inet_ntoa(((struct sockaddr_in *)thataddr)->sin_addr),
-	   *server_username,
-	   *cmd);
-
-    memcpy (iv, auth.session, sizeof(iv));
-
-    return 0;
-}
-
-#endif /* KRB4 */
-
-#ifdef KRB5
-static int=20
 save_krb5_creds (int s,
                  krb5_auth_context auth_context,
                  krb5_principal client)
@@ -232,7 +162,7 @@
 {
     int ret;
     krb5_data remote_cred;
-=20
+
     krb5_data_zero (&remote_cred);
     ret=3D krb5_read_message (context, (void *)&s, &remote_cred);
     if (ret) {
@@ -241,13 +171,13 @@
     }
     if (remote_cred.length =3D=3D 0)
 	return 0;
-=20
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &ccache);
+
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &ccache=
);
     if (ret) {
 	krb5_data_free(&remote_cred);
 	return 0;
     }
- =20
+
     krb5_cc_initialize(context,ccache,client);
     ret =3D krb5_rd_cred2(context, auth_context, ccache, &remote_cred);
     if(ret !=3D 0)
@@ -268,8 +198,8 @@
     ret =3D krb5_cc_resolve (context, tkfile, &ccache2);
     if (ret) {
 	estr =3D krb5_get_error_string(context);
-	syslog(LOG_WARNING, "resolve cred cache %s: %s",=20
-	       tkfile,=20
+	syslog(LOG_WARNING, "resolve cred cache %s: %s",
+	       tkfile,
 	       estr ? estr : krb5_get_err_text(context, ret));
 	free(estr);
 	krb5_cc_destroy(context, ccache);
@@ -279,7 +209,7 @@
     ret =3D krb5_cc_copy_cache (context, ccache, ccache2);
     if (ret) {
 	estr =3D krb5_get_error_string(context);
-	syslog(LOG_WARNING, "storing credentials: %s",=20
+	syslog(LOG_WARNING, "storing credentials: %s",
 	       estr ? estr : krb5_get_err_text(context, ret));
 	free(estr);
 	krb5_cc_destroy(context, ccache);
@@ -328,13 +258,13 @@
     if (memcmp (buf, "\x00\x00\x00\x13", 4) !=3D 0)
 	return -1;
     len =3D (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | (buf[3]);
-=09
+
     if (net_read(s, buf, len) !=3D len)
-	syslog_and_die ("reading auth info: %m");
+	syslog_and_die ("reading auth info: %s", strerror(errno));
     if (len !=3D sizeof(KRB5_SENDAUTH_VERSION)
 	|| memcmp (buf, KRB5_SENDAUTH_VERSION, len) !=3D 0)
 	syslog_and_die ("bad sendauth version: %.8s", buf);
-   =20
+
     status =3D krb5_sock_to_principal (context,
 				     s,
 				     "host",
@@ -363,7 +293,7 @@
     *client_username =3D read_str (s, ARG_MAX + 1, "local username");
=20
     if(protocol_version =3D=3D 2) {
-	status =3D krb5_auth_con_getremotesubkey(context, auth_context,=20
+	status =3D krb5_auth_con_getremotesubkey(context, auth_context,
 					       &keyblock);
 	if(status !=3D 0 || keyblock =3D=3D NULL)
 	    syslog_and_die("failed to get remote subkey");
@@ -378,10 +308,10 @@
=20
     status =3D krb5_crypto_init(context, keyblock, 0, &crypto);
     if(status)
-	syslog_and_die("krb5_crypto_init: %s",=20
+	syslog_and_die("krb5_crypto_init: %s",
 		       krb5_get_err_text(context, status));
=20
-   =20
+
     cksum_data.length =3D asprintf (&str,
 				  "%u:%s%s",
 				  ntohs(socket_get_port (thisaddr)),
@@ -391,9 +321,9 @@
 	syslog_and_die ("asprintf: out of memory");
     cksum_data.data =3D str;
=20
-    status =3D krb5_verify_authenticator_checksum(context,=20
+    status =3D krb5_verify_authenticator_checksum(context,
 						auth_context,
-						cksum_data.data,=20
+						cksum_data.data,
 						cksum_data.length);
=20
     if (status)
@@ -464,7 +394,9 @@
 		   *cmd);
 	    free (name);
 	}
-    }	  =20
+    }
+
+    krb5_auth_con_free(context, auth_context);
=20
     return 0;
 }
@@ -508,12 +440,12 @@
 	    if (errno =3D=3D EINTR)
 		continue;
 	    else
-		syslog_and_die ("select: %m");
+		syslog_and_die ("select: %s", strerror(errno));
 	}
 	if (FD_ISSET(from0, &readset)) {
 	    ret =3D do_read (from0, buf, RSHD_BUFSIZ, ivec_in[0]);
 	    if (ret < 0)
-		syslog_and_die ("read: %m");
+		syslog_and_die ("read: %s", strerror(errno));
 	    else if (ret =3D=3D 0) {
 		close (from0);
 		close (to0);
@@ -524,7 +456,7 @@
 	if (FD_ISSET(from1, &readset)) {
 	    ret =3D read (from1, buf, RSH_BUFSIZ);
 	    if (ret < 0)
-		syslog_and_die ("read: %m");
+		syslog_and_die ("read: %s", strerror(errno));
 	    else if (ret =3D=3D 0) {
 		close (from1);
 		close (to1);
@@ -537,7 +469,7 @@
 	if (FD_ISSET(from2, &readset)) {
 	    ret =3D read (from2, buf, RSH_BUFSIZ);
 	    if (ret < 0)
-		syslog_and_die ("read: %m");
+		syslog_and_die ("read: %s", strerror(errno));
 	    else if (ret =3D=3D 0) {
 		close (from2);
 		close (to2);
@@ -683,10 +615,10 @@
=20
     thisaddr_len =3D sizeof(thisaddr_ss);
     if (getsockname (s, thisaddr, &thisaddr_len) < 0)
-	syslog_and_die("getsockname: %m");
+	syslog_and_die("getsockname: %s", strerror(errno));
     thataddr_len =3D sizeof(thataddr_ss);
     if (getpeername (s, thataddr, &thataddr_len) < 0)
-	syslog_and_die ("getpeername: %m");
+	syslog_and_die ("getpeername: %s", strerror(errno));
=20
     /* check for V4MAPPED addresses? */
=20
@@ -697,7 +629,7 @@
     port =3D 0;
     for(;;) {
 	if (net_read (s, p, 1) !=3D 1)
-	    syslog_and_die ("reading port number: %m");
+	    syslog_and_die ("reading port number: %s", strerror(errno));
 	if (*p =3D=3D '\0')
 	    break;
 	else if (isdigit(*p))
@@ -712,7 +644,7 @@
     if (port) {
 	int priv_port =3D IPPORT_RESERVED - 1;
=20
-	/*=20
+	/*
 	 * There's no reason to require a ``privileged'' port number
 	 * here, but for some reason the brain dead rsh clients
 	 * do... :-(
@@ -732,28 +664,19 @@
 	else
 	    errsock =3D socket (erraddr->sa_family, SOCK_STREAM, 0);
 	if (errsock < 0)
-	    syslog_and_die ("socket: %m");
+	    syslog_and_die ("socket: %s", strerror(errno));
 	if (connect (errsock,
 		     erraddr,
 		     socket_sockaddr_size (erraddr)) < 0) {
-	    syslog (LOG_WARNING, "connect: %m");
+	    syslog (LOG_WARNING, "connect: %s", strerror(errno));
 	    close (errsock);
 	}
     }
-   =20
+
     if(do_kerberos) {
 	if (net_read (s, buf, 4) !=3D 4)
-	    syslog_and_die ("reading auth info: %m");
-   =20
-#ifdef KRB4
-	if ((do_kerberos & DO_KRB4) &&=20
-	    recv_krb4_auth (s, buf, thisaddr, thataddr,
-			    &client_user,
-			    &server_user,
-			    &cmd) =3D=3D 0)
-	    auth_method =3D AUTH_KRB4;
-	else
-#endif /* KRB4 */
+	    syslog_and_die ("reading auth info: %s", strerror(errno));
+
 #ifdef KRB5
 	    if((do_kerberos & DO_KRB5) &&
 	       recv_krb5_auth (s, buf, thisaddr, thataddr,
@@ -811,26 +734,26 @@
     {
 	struct spwd *sp;
 	long    today;
-   =20
+
 	sp =3D getspnam(server_user);
 	if (sp !=3D NULL) {
 	    today =3D time(0)/(24L * 60 * 60);
-	    if (sp->sp_expire > 0)=20
-		if (today > sp->sp_expire)=20
+	    if (sp->sp_expire > 0)
+		if (today > sp->sp_expire)
 		    fatal(s, NULL, "Account has expired.");
 	}
     }
 #endif
-   =20
+
=20
 #ifdef HAVE_SETLOGIN
     if (setlogin(pwd->pw_name) < 0)
-	syslog(LOG_ERR, "setlogin() failed: %m");
+	syslog(LOG_ERR, "setlogin() failed: %s", strerror(errno));
 #endif
=20
 #ifdef HAVE_SETPCRED
     if (setpcred (pwd->pw_name, NULL) =3D=3D -1)
-	syslog(LOG_ERR, "setpcred() failure: %m");
+	syslog(LOG_ERR, "setpcred() failure: %s", strerror(errno));
 #endif /* HAVE_SETPCRED */
=20
     /* Apply limits if not root */
@@ -863,7 +786,7 @@
 #ifdef KRB5
     {
 	int fd;
-=20
+
 	if (!do_unique_tkfile)
 	    snprintf(tkfile,sizeof(tkfile),"FILE:/tmp/krb5cc_%lu",
 		     (unsigned long)pwd->pw_uid);
@@ -873,7 +796,7 @@
 	    close(fd);
 	    unlink(tkfile+5);
 	}
-=20
+
 	if (kerberos_status)
 	    krb5_start_session();
     }
@@ -888,19 +811,13 @@
 	    fatal (s, "net_write", "write failed");
     }
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
     if(k_hasafs()) {
 	char cell[64];
=20
 	if(do_newpag)
 	    k_setpag();
-#ifdef KRB4
-	if (k_afs_cell_of_file (pwd->pw_dir, cell, sizeof(cell)) =3D=3D 0)
-	    krb_afslog_uid_home (cell, NULL, pwd->pw_uid, pwd->pw_dir);
-	krb_afslog_uid_home(NULL, NULL, pwd->pw_uid, pwd->pw_dir);
-#endif
=20
-#ifdef KRB5
 	/* XXX */
        if (kerberos_status) {
 	   krb5_ccache ccache;
@@ -916,9 +833,8 @@
 	       krb5_cc_close (context, ccache);
 	   }
        }
+    }
 #endif /* KRB5 */
-    }
-#endif /* KRB5 || KRB4 */
     execle (pwd->pw_shell, pwd->pw_shell, "-c", cmd, NULL, env);
     err(1, "exec %s", pwd->pw_shell);
 }
@@ -928,7 +844,7 @@
     { "keepalive",	'n',	arg_negative_flag,	&do_keepalive },
     { "inetd",		'i',	arg_negative_flag,	&do_inetd,
       "Not started from inetd" },
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
     { "kerberos",	'k',	arg_flag,	&do_kerberos,
       "Implement kerberised services" },
     { "encrypt",	'x',	arg_flag,		&do_encrypt,
@@ -940,7 +856,7 @@
       "port" },
     { "vacuous",	'v',	arg_flag, &do_vacuous,
       "Don't accept non-kerberised connections" },
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
     { NULL,		'P',	arg_negative_flag, &do_newpag,
       "Don't put process in new PAG" },
 #endif
@@ -985,12 +901,12 @@
 	exit(0);
     }
=20
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
     if (do_encrypt)
 	do_kerberos =3D 1;
=20
     if(do_kerberos)
-	do_kerberos =3D DO_KRB4 | DO_KRB5;
+	do_kerberos =3D DO_KRB5;
 #endif
=20
 #ifdef KRB5
@@ -1002,19 +918,19 @@
 	int error;
 	struct addrinfo *ai =3D NULL, hints;
 	char portstr[NI_MAXSERV];
-=09
+
 	memset (&hints, 0, sizeof(hints));
 	hints.ai_flags    =3D AI_PASSIVE;
 	hints.ai_socktype =3D SOCK_STREAM;
 	hints.ai_family   =3D PF_UNSPEC;
-=09
+
 	if(port_str !=3D NULL) {
 	    error =3D getaddrinfo (NULL, port_str, &hints, &ai);
 	    if (error)
 		errx (1, "getaddrinfo: %s", gai_strerror (error));
 	}
 	if (ai =3D=3D NULL) {
-#if defined(KRB4) || defined(KRB5)
+#if defined(KRB5)
 	    if (do_kerberos) {
 		if (do_encrypt) {
 		    error =3D getaddrinfo(NULL, "ekshell", &hints, &ai);
@@ -1022,7 +938,7 @@
 			snprintf(portstr, sizeof(portstr), "%d", 545);
 			error =3D getaddrinfo(NULL, portstr, &hints, &ai);
 		    }
-		    if(error)=20
+		    if(error)
 			errx (1, "getaddrinfo: %s", gai_strerror (error));
 		} else {
 		    error =3D getaddrinfo(NULL, "kshell", &hints, &ai);
@@ -1030,7 +946,7 @@
 			snprintf(portstr, sizeof(portstr), "%d", 544);
 			error =3D getaddrinfo(NULL, portstr, &hints, &ai);
 		    }
-		    if(error)=20
+		    if(error)
 			errx (1, "getaddrinfo: %s", gai_strerror (error));
 		}
 	    } else
@@ -1041,18 +957,18 @@
 			snprintf(portstr, sizeof(portstr), "%d", 514);
 			error =3D getaddrinfo(NULL, portstr, &hints, &ai);
 		    }
-		    if(error)=20
+		    if(error)
 			errx (1, "getaddrinfo: %s", gai_strerror (error));
 		}
 	}
-	mini_inetd_addrinfo (ai);
+	mini_inetd_addrinfo (ai, NULL);
 	freeaddrinfo(ai);
     }
=20
     if (do_keepalive &&
 	setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on,
 		   sizeof(on)) < 0)
-	syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
+	syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %s", strerror(errno));
=20
     /* set SO_LINGER? */
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/su/ChangeLog
--- a/head/crypto/heimdal/appl/su/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/su/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,24 @@
-2007-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-07-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Makefile.am: no krb4
+
+	* su.c: Drop kerberos 4 support.
+
+2007-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* su.c: read environment from _PATH_ETC_ENVIRONMENT
=20
 	* supaths.c: paths
=20
-2007-08-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* su.c: Check all local realms when su-ing, from Magnus Holmberg.
=20
-2007-06-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* su.c: If not root and not setuid, print warning.
=20
-2006-01-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* su.c (group_member_p): rename from group_member to avoid name
 	pollution from glibc headers. Fixed based on report from David Love.
@@ -21,16 +27,16 @@
=20
 	* su.c: fix reversed logic when deciding to print tty or not
 =09
-2005-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* su.c: Check return value from asprintf instead of string !=3D NULL
-	since it undefined behavior on Linux. From Bj=F6rn Sandell
+	since it undefined behavior on Linux. From Bj=C3=B6rn Sandell
 =09
 2005-05-10  Dave Love  <fx at gnu.org>
=20
 	* su.c: Include <crypt.h>.
=20
-2003-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* su.c: s/des_read_pw_string/UI_UTIL_read_pw_string/
 =09
@@ -39,7 +45,7 @@
 	* su.c: remove accidentally committed code that prints the command
 	being executed
=20
-2003-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* su.c (krb5_start_session): krb5_afslog doesn't depend on KRB4
 	any more
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/su/Makefile.am
--- a/head/crypto/heimdal/appl/su/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/su/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,4 @@
-# $Id: Makefile.am 21986 2007-10-19 05:22:57Z lha $
-# $FreeBSD$
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -12,9 +11,8 @@
=20
 LDADD =3D $(LIB_kafs) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/su/Makefile.in
--- a/head/crypto/heimdal/appl/su/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/su/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 21986 2007-10-19 05:22:57Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/su
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,14 +89,14 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS)
 am_su_OBJECTS =3D su.$(OBJEXT)
 su_OBJECTS =3D $(am_su_OBJECTS)
@@ -101,11 +106,10 @@
 	$(am__DEPENDENCIES_1)
 su_DEPENDENCIES =3D $(am__DEPENDENCIES_2) \
 	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -117,6 +121,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(su_SOURCES)
 DIST_SOURCES =3D $(su_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -126,49 +151,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -192,10 +226,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -212,6 +247,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -227,31 +264,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -266,10 +317,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -310,58 +363,61 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4) $(INCLUDE_hcrypto)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_krb4) $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 bin_SUIDS =3D su
 su_SOURCES =3D su.c supaths.h
 man_MANS =3D su.1
 LDADD =3D $(LIB_kafs) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/su/M=
akefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/su/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/su/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/su/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -379,34 +435,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 su$(EXEEXT): $(su_OBJECTS) $(su_DEPENDENCIES)=20
 	@rm -f su$(EXEEXT)
 	$(LINK) $(su_OBJECTS) $(su_LDADD) $(LIBS)
@@ -417,115 +489,139 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/su.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -541,13 +637,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -582,6 +682,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -591,6 +692,7 @@
 clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -601,6 +703,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -608,26 +712,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -647,11 +760,10 @@
 uninstall-am: uninstall-binPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libtool ctags \
@@ -738,6 +850,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -823,7 +938,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -836,6 +951,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/su/su.1
--- a/head/crypto/heimdal/appl/su/su.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/su/su.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2003 - 2006 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2003 - 2006 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: su.1 16528 2006-01-12 16:25:01Z joda $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd January 12, 2006
 .Dt SU 1
@@ -39,16 +39,16 @@
 .Nd substitute user identity
 .Sh SYNOPSIS
 .Nm su
-.Op Fl K | Fl -no-kerberos
+.Op Fl K | Fl Fl no-kerberos
 .Op Fl f
-.Op Fl l | Fl -full
+.Op Fl l | Fl Fl full
 .Op Fl m
 .Oo Fl i Ar instance \*(Ba Xo
-.Fl -instance=3D Ns Ar instance
+.Fl Fl instance=3D Ns Ar instance
 .Xc
 .Oc
 .Oo Fl c Ar command \*(Ba Xo
-.Fl -command=3D Ns Ar command
+.Fl Fl command=3D Ns Ar command
 .Xc
 .Oc
 .Op Ar login Op Ar "shell arguments"
@@ -59,25 +59,25 @@
 .Pa .k5login
 in the target user id's home directory
 .Pp
-A special case exists where=20
+A special case exists where
 .Ql root Ap s
 .Pa ~/.k5login
 needs to contain an entry for:
 .Ql user Ns / Ns Ao instance Ac Ns @ Ns REALM
 for
 .Nm su
-to succed (where=20
+to succed (where
 .Aq instance
 is
 .Ql root
-unless changed with=20
+unless changed with
 .Fl i ) .
 .Pp
 In the absence of either an entry for current user in said file or
-other problems like missing=20
+other problems like missing
 .Ql host/hostname at REALM
 keys in the system's
-keytab, or user typing the wrong password,=20
+keytab, or user typing the wrong password,
 .Nm su
 will fall back to traditional
 .Pa /etc/passwd
@@ -86,7 +86,7 @@
 When using
 .Pa /etc/passwd
 authentication,
-.Nm su=20
+.Nm su
 allows
 .Ql root
 access only to members of the group
@@ -100,24 +100,24 @@
 .Bl -item -width Ds
 .It
 .Fl K ,
-.Fl -no-kerberos
+.Fl Fl no-kerberos
 don't use Kerberos.
 .It
 .Fl f
 don't read .cshrc.
 .It
 .Fl l ,
-.Fl -full
+.Fl Fl full
 simulate full login.
 .It
 .Fl m
 leave environment unmodified.
 .It
 .Fl i Ar instance ,
-.Fl -instance=3D Ns Ar instance
+.Fl Fl instance=3D Ns Ar instance
 root instance to use.
 .It
 .Fl c Ar command ,
-.Fl -command=3D Ns Ar command
+.Fl Fl command=3D Ns Ar command
 command to execute.
 .El
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/su/su.c
--- a/head/crypto/heimdal/appl/su/su.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/su/su.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -30,13 +30,9 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
=20
-/*
- * $FreeBSD$
- */
-
 #include <config.h>
=20
-RCSID("$Id: su.c 21988 2007-10-19 05:36:54Z lha $");
+RCSID("$Id$");
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -61,9 +57,6 @@
 #ifdef KRB5
 #include <krb5.h>
 #endif
-#ifdef KRB4
-#include <krb.h>
-#endif
 #include <kafs.h>
 #include <err.h>
 #include <roken.h>
@@ -71,6 +64,10 @@
=20
 #include "supaths.h"
=20
+#if !HAVE_DECL_ENVIRON
+extern char **environ;
+#endif
+
 int kerberos_flag =3D 1;
 int csh_f_flag;
 int full_login;
@@ -141,26 +138,6 @@
     return info;
 }
=20
-#if defined(KRB4) || defined(KRB5)
-static void
-set_tkfile()
-{
-#ifndef TKT_ROOT
-#define TKT_ROOT "/tmp/tkt"
-#endif
-    int fd;
-    if(*tkfile !=3D '\0')
-	return;
-    snprintf(tkfile, sizeof(tkfile), "%s_XXXXXX", TKT_ROOT);
-    fd =3D mkstemp(tkfile);
-    if(fd >=3D 0)
-	close(fd);
-#ifdef KRB4
-    krb_set_tkt_string(tkfile);
-#endif
-}
-#endif
-
 #ifdef KRB5
 static krb5_context context;
 static krb5_ccache ccache;
@@ -175,7 +152,7 @@
     krb5_realm *realms, *r;
     char *login_name =3D NULL;
     int user_ok =3D 0;
-=09
+
 #if defined(HAVE_GETLOGIN) && !defined(POSIX_GETLOGIN)
     login_name =3D getlogin();
 #endif
@@ -186,35 +163,35 @@
 #endif
 	return 1;
     }
-=09
+
     ret =3D krb5_get_default_realms(context, &realms);
-    if (ret)=20
+    if (ret)
 	return 1;
=20
     /* Check all local realms */
     for (r =3D realms; *r !=3D NULL && !user_ok; r++) {
-      =20
-	if (login_name =3D=3D NULL || strcmp (login_name, "root") =3D=3D 0)=20
+
+	if (login_name =3D=3D NULL || strcmp (login_name, "root") =3D=3D 0)
 	    login_name =3D login_info->pw_name;
 	if (strcmp (su_info->pw_name, "root") =3D=3D 0)
-	    ret =3D krb5_make_principal(context, &p, *r,=20
+	    ret =3D krb5_make_principal(context, &p, *r,
 				      login_name,
 				      kerberos_instance,
 				      NULL);
 	else
-	    ret =3D krb5_make_principal(context, &p, *r,=20
+	    ret =3D krb5_make_principal(context, &p, *r,
 				      su_info->pw_name,
 				      NULL);
 	if (ret) {
 	    krb5_free_host_realm(context, realms);
 	    return 1;
 	}
-=09
+
 	/* if we are su-ing too root, check with krb5_kuserok */
 	if (su_info->pw_uid =3D=3D 0 && !krb5_kuserok(context, p, su_info->pw_nam=
e))
 	    continue;
-      =20
-	ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &ccache);
+
+	ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &ccache);
 	if(ret) {
 	    krb5_free_host_realm(context, realms);
 	    krb5_free_principal (context, p);
@@ -253,109 +230,40 @@
     char *cc_name;
     int ret;
=20
-    ret =3D krb5_cc_gen_new(context, &krb5_fcc_ops, &ccache2);
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_file, NULL, &ccache2);
     if (ret) {
 	krb5_cc_destroy(context, ccache);
 	return 1;
     }
=20
     ret =3D krb5_cc_copy_cache(context, ccache, ccache2);
+    if (ret) {
+	krb5_cc_destroy(context, ccache);
+	krb5_cc_destroy(context, ccache2);
+	return 1;
+    }
=20
     ret =3D asprintf(&cc_name, "%s:%s", krb5_cc_get_type(context, ccache2),
 		   krb5_cc_get_name(context, ccache2));
-    if (ret =3D=3D -1)
+    if (ret =3D=3D -1) {
+	krb5_cc_destroy(context, ccache);
+	krb5_cc_destroy(context, ccache2);
 	errx(1, "malloc - out of memory");
+    }
     esetenv("KRB5CCNAME", cc_name, 1);
=20
-    /* we want to export this even if we don't directly support KRB4 */
-    set_tkfile();
-    esetenv("KRBTKFILE", tkfile, 1);
-           =20
     /* convert creds? */
     if(k_hasafs()) {
 	if (k_setpag() =3D=3D 0)
 	    krb5_afslog(context, ccache2, NULL, NULL);
     }
-           =20
+
     krb5_cc_close(context, ccache2);
     krb5_cc_destroy(context, ccache);
     return 0;
 }
 #endif
=20
-#ifdef KRB4
-
-static int
-krb_verify(const struct passwd *login_info,
-	   const struct passwd *su_info,
-	   const char *kerberos_instance)
-{
-    int ret;
-    char *login_name =3D NULL;
-    char *name, *instance, realm[REALM_SZ];
-=09
-#if defined(HAVE_GETLOGIN) && !defined(POSIX_GETLOGIN)
-    login_name =3D getlogin();
-#endif
-
-    ret =3D krb_get_lrealm(realm, 1);
-=09
-    if (login_name =3D=3D NULL || strcmp (login_name, "root") =3D=3D 0)=20
-	login_name =3D login_info->pw_name;
-    if (strcmp (su_info->pw_name, "root") =3D=3D 0) {
-	name =3D login_name;
-	instance =3D (char*)kerberos_instance;
-    } else {
-	name =3D su_info->pw_name;
-	instance =3D "";
-    }
-
-    if(su_info->pw_uid !=3D 0 ||=20
-       krb_kuserok(name, instance, realm, su_info->pw_name) =3D=3D 0) {
-	char password[128];
-	char *prompt;
-	ret =3D asprintf (&prompt,=20
-		  "%s's Password: ",
-		  krb_unparse_name_long (name, instance, realm));
-	if (ret =3D=3D -1)
-	    return (1);
-	if (UI_UTIL_read_pw_string (password, sizeof (password), prompt, 0)) {
-	    memset (password, 0, sizeof (password));
-	    free(prompt);
-	    return (1);
-	}
-	free(prompt);
-	if (strlen(password) =3D=3D 0)
-	    return (1);		/* Empty passwords are not allowed */
-	set_tkfile();
-	setuid(geteuid()); /* need to run as root here */
-	ret =3D krb_verify_user(name, instance, realm, password,=20
-			      KRB_VERIFY_SECURE, NULL);
-	memset(password, 0, sizeof(password));
-=09
-	if(ret) {
-	    warnx("%s", krb_get_err_text(ret));
-	    return 1;
-	}
-	chown (tkt_string(), su_info->pw_uid, su_info->pw_gid);
-	return 0;
-    }
-    return 1;
-}
-
-
-static int
-krb_start_session(void)
-{
-    esetenv("KRBTKFILE", tkfile, 1);
-           =20
-    /* convert creds? */
-    if(k_hasafs() && k_setpag() =3D=3D 0)
-	krb_afslog(NULL, NULL);
-           =20
-    return 0;
-}
-#endif
=20
 #define GROUP_MEMBER		0
 #define GROUP_MISSING		1
@@ -429,7 +337,6 @@
     char *shell;
=20
     int ok =3D 0;
-    int kerberos_error=3D1;
=20
     setprogname (argv[0]);
=20
@@ -441,7 +348,7 @@
 	 full_login =3D 1;
 	 break;
       }
-=09
+
     if(help_flag)
 	usage(0);
     if(version_flag) {
@@ -454,7 +361,7 @@
 	su_user =3D argv[optind++];
=20
     if (!issuid() && getuid() !=3D 0)
-	warnx("Not setuid and you are root, expect this to fail");
+	warnx("Not setuid and you are not root, expect this to fail");
=20
     pwd =3D k_getpwnam(su_user);
     if(pwd =3D=3D NULL)
@@ -466,7 +373,7 @@
     su_info =3D dup_info(pwd);
     if (su_info =3D=3D NULL)
 	errx (1, "malloc: out of memory");
-   =20
+
 	pwd =3D getpwuid(getuid());
     if(pwd =3D=3D NULL)
 	errx(1, "who are you?");
@@ -479,18 +386,13 @@
 	shell =3D su_info->pw_shell;
     if(shell =3D=3D NULL || *shell =3D=3D '\0')
 	shell =3D _PATH_BSHELL;
-   =20
+
=20
 #ifdef KRB5
     if(kerberos_flag && ok =3D=3D 0 &&
-      (kerberos_error=3Dkrb5_verify(login_info, su_info, kerberos_instance=
)) =3D=3D 0)
+       krb5_verify(login_info, su_info, kerberos_instance) =3D=3D 0)
 	ok =3D 5;
 #endif
-#ifdef KRB4
-    if(kerberos_flag && ok =3D=3D 0 &&
-       (kerberos_error =3D krb_verify(login_info, su_info, kerberos_instan=
ce)) =3D=3D 0)
-	ok =3D 4;
-#endif
=20
     if(ok =3D=3D 0 && login_info->pw_uid && verify_unix(login_info, su_inf=
o) !=3D 0) {
 	printf("Sorry!\n");
@@ -500,24 +402,24 @@
 #ifdef HAVE_GETSPNAM
    {  struct spwd *sp;
       long    today;
-   =20
+
     sp =3D getspnam(su_info->pw_name);
     if (sp !=3D NULL) {
 	today =3D time(0)/(24L * 60 * 60);
 	if (sp->sp_expire > 0) {
 	    if (today >=3D sp->sp_expire) {
-		if (login_info->pw_uid)=20
+		if (login_info->pw_uid)
 		    errx(1,"Your account has expired.");
 		else
 		    printf("Your account has expired.");
             }
-            else if (sp->sp_expire - today < 14)=20
+            else if (sp->sp_expire - today < 14)
                 printf("Your account will expire in %d days.\n",
 		       (int)(sp->sp_expire - today));
-	}=20
+	}
 	if (sp->sp_max > 0) {
 	    if (today >=3D sp->sp_lstchg + sp->sp_max) {
-		if (login_info->pw_uid)   =20
+		if (login_info->pw_uid)
 		    errx(1,"Your password has expired. Choose a new one.");
 		else
 		    printf("Your password has expired. Choose a new one.");
@@ -551,6 +453,8 @@
=20
 	    for (j =3D 0; j < i; j++) {
 		char *p =3D strchr(newenv[j], '=3D');
+		if (p =3D=3D NULL)
+		    errx(1, "enviroment '%s' missing '=3D'", newenv[j]);
 		*p++ =3D 0;
 		esetenv (newenv[j], p, 1);
 	    }
@@ -594,15 +498,15 @@
 	if (cmd) {
 	   args[i++] =3D "-c";
 	   args[i++] =3D cmd;
-	} =20
-	  =20
+	}
+
 	if (csh_f_flag)
 	    args[i++] =3D "-f";
=20
 	for (argv +=3D optind; *argv; ++argv)
 	   args[i++] =3D *argv;
 	args[i] =3D NULL;
-=09
+
 	if(setgid(su_info->pw_gid) < 0)
 	    err(1, "setgid");
 	if (initgroups (su_info->pw_name, su_info->pw_gid) < 0)
@@ -615,12 +519,8 @@
         if (ok =3D=3D 5)
            krb5_start_session();
 #endif
-#ifdef KRB4
-	if (ok =3D=3D 4)
-	    krb_start_session();
-#endif
-	execv(shell, args);
+	execve(shell, args, environ);
     }
-   =20
+
     exit(1);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/su/supaths.h
--- a/head/crypto/heimdal/appl/su/supaths.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/su/supaths.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /* $Id$ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/Change=
Log
--- a/head/crypto/heimdal/appl/telnet/ChangeLog	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/telnet/ChangeLog	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,20 +1,47 @@
-2007-12-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* libtelnet/enc_des.c: Use RAND_bytes() + DES_is_weak_key() to
+	generate random DES key. Introdunce random by feeding the des
+	session key into the random pool when the keys is recived instead
+	of encrypt the random key with the kerberos key.
+=09
+	This avoid depenency on DES_new_random_key() that doesn't exists
+	in OpenSSL.
+
+2008-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* libtelnet/enc_des.c: No need to call
+	DES_init_random_number_generator, hcrypto is sane now.
+
+	* libtelnet/enc_des.c: Use DES_new_random_key().
+
+2008-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* telnetd/sys_term.c: Really, mac os uses wtmpx (or asl).
+
+2008-03-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* telnetd/sys_term.c: Dont need to set this as the controlling PTY
+	on steams sockets, don't abort on failure. From Harald Barth and
+	Ian Delahorne.
+
+2007-12-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/sys_term.c: Use strlcpy instead of strncpy, thanks to
 	Antoine Brodin.
 =09
-2007-07-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/telnetd.c (usage): use exit_code, add --version and
 	--help.
=20
 	* telnetd/telnetd.c: Add --help, reported by David Love.
=20
-2007-07-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/main.c: Catch --help, reported by David Love.
 =09
-2007-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/sys_term.c: GLIBC made the choice that ut_tv should be
 	shared between 32 and 64 bit platforms so now we can no longer use
@@ -22,7 +49,7 @@
 	pointer (gettimeofday for example) since ut_tv is now not a struct
 	timeval but rather a struct { int32_t tv_sec; int32_t tv_usec; };
=20
-2006-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/telnet_locl.h: Include roken.h before the local
 	headerfiles.
@@ -36,13 +63,13 @@
 	* telnetd/telnetd.h: includes some STREAMSPTY header here to avoid
 	ioctl vs socket_wrapper horror.
 =09
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/Makefile.am: more files
 =09
 	* telnetd/Makefile.am: more files
 =09
-2006-09-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* telnetd/telnetd.8: Add documentation for -e, require encryption.
=20
@@ -54,50 +81,50 @@
 	* telnetd/state.c: If encryption is required, don't allow it to be
 	turned off.
 =09
-2006-09-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* libtelnet/kerberos5.c (kerberos5_forward): use KDCOptions2int on
 	flags before passing them to krb5_get_forwarded_creds.
 =09
-2006-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Rename u_intXX_t to uintXX_t
=20
-2006-03-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* libtelnet/encrypt.c: Spelling.
=20
-2005-12-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* telnetd/telnetd.c: Initialize the slc mapping table before its
 	used.  Based on bug report from Russell Sanford
 	<rrs at clyde.dcccd.edu>
 =09
-2005-11-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* telnet/telnet.c: Spelling in comments, from Dave Love
 	<fx at gnu.org>
 =09
-2005-10-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* libtelnet/kerberos5.c (Data): Use right variable. From Tomas
 	Olsson
 =09
-2005-10-22  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-10-22  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* telnet/commands.c: Check return value from asprintf instead of
-	string !=3D NULL since it undefined behavior on Linux. From Bj=F6rn
+	string !=3D NULL since it undefined behavior on Linux. From Bj=C3=B6rn
 	Sandell
=20
 	* libtelnet/kerberos5.c: Check return value from asprintf instead
-	of string !=3D NULL since it undefined behavior on Linux. From Bj=F6rn
+	of string !=3D NULL since it undefined behavior on Linux. From Bj=C3=B6rn
 	Sandell
=20
 	* libtelnet/kerberos.c: Check return value from asprintf instead
-	of string !=3D NULL since it undefined behavior on Linux. From Bj=F6rn
+	of string !=3D NULL since it undefined behavior on Linux. From Bj=C3=B6rn
 	Sandell
 =09
-2005-08-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/telnetd.c: Fix printing of /etc/issue{,.net}.
 =09
@@ -115,7 +142,7 @@
 	* libtelnet/kerberos.c: Do not assume that des_key_schedule is an
 	array.
=20
-2005-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* libtelnet/kerberos5.c: case uid_t to unsigned long in printf
 	format
@@ -123,7 +150,7 @@
 	* telnetd/sys_term.c (set_termbuf): use {} around if to make else
 	unambiguous
=20
-2005-05-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/sys_term.c (start_login): put utmpx code into a new
 	scope to avoid pre c99 problems.
@@ -153,33 +180,33 @@
=20
 	* telnetd/sys_term.c (getpty): Declare p.
=20
-2005-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/telnetd.c: use strlcpy
 =09
-2005-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/global.c, telnetd/state.c, telnetd/telnetd.c,
 	telentd/ext.h: remove another strcpy
=20
-2005-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/sys_term.c: rewrite getpty to make use openpty when its
 	found, save the slave fd so that cleanopen can use it if its
 	available
=20
-2005-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/sys_term.c: clean_ttyname might be unused, mark it so
 	with __attribute__
 =09
-2005-04-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/sys_term.c: use NULL as last argument to execl, not 0
=20
 	* telnet/commands.c: use NULL as last argument to execl, not 0
 =09
-2005-03-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/telnet.c: From FreeBSD:
 =09
@@ -205,20 +232,20 @@
 	These fixes are based in part on patches Submitted by: Solar
 	Designer <solar at openwall.com>
=20
-2005-03-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/telnetd.c: remove setting of DES_check_key, all code
 	uses DES_set_key_checked
=20
 	* libtelnet/enc_des.c: use DES_set_key_checked
 =09
-2005-01-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/telnet.c: cast argument to toupper to unsigned char
=20
 	* telnet/commands.c: cast argument to is* to unsigned char
=20
-2004-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/network.c: make network rings larger From: MAAAAA MOOOR
 	<huaraz at btinternet.com>
@@ -229,19 +256,19 @@
 	* libtelnet/kerberos5.c (Data): allocate the data needed to be
 	send From: MAAAAA MOOOR <huaraz at btinternet.com>
 =09
-2004-04-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/main.c: make encrypt, forwardable, forward use appdefault
 	(that also searches libdefaults), prompted by Thomas Nystrom
 	<thn at saeab.se>
 =09
-2004-03-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/telnetd.c: call setprogname to make libvers happy
=20
 	* telnet/main.c: call setprogname to make libvers happy
=20
-2003-09-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/externs.h: export Scheduler and scheduler_lockout_tty
 =09
@@ -251,13 +278,13 @@
 	* telnet/authenc.c (telnet_spin): if Scheduler() returns failure
 	(-1) propagate to higher level
=20
-2003-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnetd/telnetd.c: use new DES_ api
 =09
 	* libtelnet/enc_des.c: use new DES_ api
 =09
-2003-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* telnet/telnet.1: replace <,> with \*[Lt],\*[Gt]
 =09
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/Makefi=
le.am
--- a/head/crypto/heimdal/appl/telnet/Makefile.am	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/telnet/Makefile.am	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 5652 1999-03-20 13:58:20Z joda $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -8,4 +8,4 @@
 	$(mkinstalldirs) $(distdir)/arpa
 	$(INSTALL_DATA) $(srcdir)/arpa/telnet.h $(distdir)/arpa
=20
-EXTRA_DIST =3D README.ORIG telnet.state
+EXTRA_DIST =3D NTMakefile README.ORIG telnet.state
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/Makefi=
le.in
--- a/head/crypto/heimdal/appl/telnet/Makefile.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/telnet/Makefile.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 5652 1999-03-20 13:58:20Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D appl/telnet
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 RECURSIVE_TARGETS =3D all-recursive check-recursive dvi-recursive \
@@ -101,57 +105,94 @@
 	ps-recursive uninstall-recursive
 RECURSIVE_CLEAN_TARGETS =3D mostlyclean-recursive clean-recursive	\
   distclean-recursive maintainer-clean-recursive
+AM_RECURSIVE_TARGETS =3D $(RECURSIVE_TARGETS:-recursive=3D) \
+	$(RECURSIVE_CLEAN_TARGETS:-recursive=3D) tags TAGS ctags CTAGS \
+	distdir
 ETAGS =3D etags
 CTAGS =3D ctags
 DIST_SUBDIRS =3D $(SUBDIRS)
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+am__relativize =3D \
+  dir0=3D`pwd`; \
+  sed_first=3D's,^\([^/]*\)/.*$$,\1,'; \
+  sed_rest=3D's,^[^/]*/*,,'; \
+  sed_last=3D's,^.*/\([^/]*\)$$,\1,'; \
+  sed_butlast=3D's,/*[^/]*$$,,'; \
+  while test -n "$$dir1"; do \
+    first=3D`echo "$$dir1" | sed -e "$$sed_first"`; \
+    if test "$$first" !=3D "."; then \
+      if test "$$first" =3D ".."; then \
+        dir2=3D`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
+        dir0=3D`echo "$$dir0" | sed -e "$$sed_butlast"`; \
+      else \
+        first2=3D`echo "$$dir2" | sed -e "$$sed_first"`; \
+        if test "$$first2" =3D "$$first"; then \
+          dir2=3D`echo "$$dir2" | sed -e "$$sed_rest"`; \
+        else \
+          dir2=3D"../$$dir2"; \
+        fi; \
+        dir0=3D"$$dir0"/"$$first"; \
+      fi; \
+    fi; \
+    dir1=3D`echo "$$dir1" | sed -e "$$sed_rest"`; \
+  done; \
+  reldir=3D"$$dir2"
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -175,10 +216,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -195,6 +237,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -210,31 +254,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -249,10 +307,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -293,48 +353,53 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 SUBDIRS =3D libtelnet telnet telnetd
-EXTRA_DIST =3D README.ORIG telnet.state
+EXTRA_DIST =3D NTMakefile README.ORIG telnet.state
 all: all-recursive
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/teln=
et/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/telnet/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/telnet/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/telnet/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -352,6 +417,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -366,7 +432,7 @@
 #     (which will cause the Makefiles to be regenerated when you run `make=
');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -383,7 +449,7 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done; \
 	if test "$$dot_seen" =3D "no"; then \
@@ -391,7 +457,7 @@
 	fi; test -z "$$fail"
=20
 $(RECURSIVE_CLEAN_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -417,16 +483,16 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done && test -z "$$fail"
 tags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags);=
 \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 tags); \
 	done
 ctags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags)=
; \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 ctags); \
 	done
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
@@ -434,14 +500,14 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
 	  include_option=3D--etags-include; \
@@ -453,39 +519,43 @@
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test ! -f $$subdir/TAGS || \
-	      tags=3D"$$tags $$include_option=3D$$here/$$subdir/TAGS"; \
+	      set "$$@" "$$include_option=3D$$here/$$subdir/TAGS"; \
 	  fi; \
 	done; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -506,29 +576,44 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
-	list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test -d "$(distdir)/$$subdir" \
 	    || $(MKDIR_P) "$(distdir)/$$subdir" \
 	    || exit 1; \
-	    distdir=3D`$(am__cd) $(distdir) && pwd`; \
-	    top_distdir=3D`$(am__cd) $(top_distdir) && pwd`; \
-	    (cd $$subdir && \
+	  fi; \
+	done
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" =3D .; then :; else \
+	    dir1=3D$$subdir; dir2=3D"$(distdir)/$$subdir"; \
+	    $(am__relativize); \
+	    new_distdir=3D$$reldir; \
+	    dir1=3D$$subdir; dir2=3D"$(top_distdir)"; \
+	    $(am__relativize); \
+	    new_top_distdir=3D$$reldir; \
+	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir=3D"$$new_t=
op_distdir" distdir=3D"$$new_distdir" \\"; \
+	    echo "     am__remove_distdir=3D: am__skip_length_check=3D: am__skip_=
mode_fix=3D: distdir)"; \
+	    ($(am__cd) $$subdir && \
 	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir=3D"$$top_distdir" \
-	        distdir=3D"$$distdir/$$subdir" \
+	        top_distdir=3D"$$new_top_distdir" \
+	        distdir=3D"$$new_distdir" \
 		am__remove_distdir=3D: \
 		am__skip_length_check=3D: \
+		am__skip_mode_fix=3D: \
 	        distdir) \
 	      || exit 1; \
 	  fi; \
@@ -562,6 +647,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -580,6 +666,8 @@
=20
 html: html-recursive
=20
+html-am:
+
 info: info-recursive
=20
 info-am:
@@ -587,23 +675,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-recursive
=20
-install-dvi: install-dvi-recursive
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-recursive
=20
+install-html-am:
+
 install-info: install-info-recursive
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-recursive
=20
+install-pdf-am:
+
 install-ps: install-ps-recursive
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-recursive
@@ -625,9 +721,9 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \
-	install-data-am install-exec-am install-strip uninstall-am
+.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) check-am \
+	ctags-recursive install-am install-data-am install-exec-am \
+	install-strip tags-recursive uninstall-am
=20
 .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
 	all all-am all-local check check-am check-local clean \
@@ -713,6 +809,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -798,7 +897,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -815,6 +914,7 @@
 dist-hook:
 	$(mkinstalldirs) $(distdir)/arpa
 	$(INSTALL_DATA) $(srcdir)/arpa/telnet.h $(distdir)/arpa
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/Makefile.am
--- a/head/crypto/heimdal/appl/telnet/libtelnet/Makefile.am	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/Makefile.am	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,8 +1,8 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D -I$(srcdir)/.. $(INCLUDE_krb4) $(INCLUDE_hcrypto)
+AM_CPPFLAGS +=3D -I$(srcdir)/.. $(INCLUDE_hcrypto)
=20
 noinst_LIBRARIES =3D libtelnet.a
=20
@@ -15,10 +15,9 @@
 	encrypt.c	\
 	encrypt.h	\
 	genget.c	\
-	kerberos.c	\
 	kerberos5.c	\
 	misc-proto.h	\
 	misc.c		\
 	misc.h
=20
-EXTRA_DIST =3D krb4encpwd.c rsaencpwd.c spx.c
+EXTRA_DIST =3D NTMakefile rsaencpwd.c spx.c
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/Makefile.in
--- a/head/crypto/heimdal/appl/telnet/libtelnet/Makefile.in	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/Makefile.in	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -44,7 +46,7 @@
 subdir =3D appl/telnet/libtelnet
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -59,7 +61,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -73,9 +75,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -83,23 +88,24 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 LIBRARIES =3D $(noinst_LIBRARIES)
 ARFLAGS =3D cru
 libtelnet_a_AR =3D $(AR) $(ARFLAGS)
 libtelnet_a_LIBADD =3D
 am_libtelnet_a_OBJECTS =3D auth.$(OBJEXT) enc_des.$(OBJEXT) \
-	encrypt.$(OBJEXT) genget.$(OBJEXT) kerberos.$(OBJEXT) \
-	kerberos5.$(OBJEXT) misc.$(OBJEXT)
+	encrypt.$(OBJEXT) genget.$(OBJEXT) kerberos5.$(OBJEXT) \
+	misc.$(OBJEXT)
 libtelnet_a_OBJECTS =3D $(am_libtelnet_a_OBJECTS)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -118,49 +124,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -184,10 +199,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -204,6 +220,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -219,31 +237,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -258,10 +290,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -302,30 +336,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	-I$(srcdir)/.. $(INCLUDE_krb4) $(INCLUDE_hcrypto)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I$(srcdir)/.. $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 noinst_LIBRARIES =3D libtelnet.a
 libtelnet_a_SOURCES =3D \
@@ -337,29 +375,28 @@
 	encrypt.c	\
 	encrypt.h	\
 	genget.c	\
-	kerberos.c	\
 	kerberos5.c	\
 	misc-proto.h	\
 	misc.c		\
 	misc.h
=20
-EXTRA_DIST =3D krb4encpwd.c rsaencpwd.c spx.c
+EXTRA_DIST =3D NTMakefile rsaencpwd.c spx.c
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/teln=
et/libtelnet/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/telnet/libtelnet/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/telnet/libtelnet/Ma=
kefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/telnet/libtelnet/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -377,6 +414,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 clean-noinstLIBRARIES:
 	-test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES)
@@ -391,14 +429,33 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/auth.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/enc_des.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/encrypt.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/genget.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kerberos5.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/misc.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -411,45 +468,49 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -470,13 +531,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -508,6 +573,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -518,6 +584,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -528,6 +595,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -535,26 +604,35 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -574,9 +652,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libtool clean-noinstLIBRARIES ctags \
@@ -661,6 +738,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -746,7 +826,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -759,6 +839,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/auth-proto.h
--- a/head/crypto/heimdal/appl/telnet/libtelnet/auth-proto.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/auth-proto.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -40,7 +40,7 @@
  * to require a specific license from the United States Government.
  * It is the responsibility of any person or organization contemplating
  * export to obtain such a license before exporting.
- *=20
+ *
  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
  * distribute this software and its documentation for any purpose and
  * without fee is hereby granted, provided that the above copyright
@@ -53,7 +53,7 @@
  * or implied warranty.
  */
=20
-/* $Id: auth-proto.h 11288 2002-08-28 20:56:14Z joda $ */
+/* $Id$ */
=20
 #ifdef AUTHENTICATION
 Authenticator *findauthenticator (int, int);
@@ -61,7 +61,7 @@
 int auth_wait (char *, size_t);
 void auth_disable_name (char *);
 void auth_finished (Authenticator *, int);
-void auth_gen_printsub (unsigned char *, int, unsigned char *, int);
+void auth_gen_printsub (unsigned char *, size_t, unsigned char *, size_t);
 void auth_init (const char *, int);
 void auth_is (unsigned char *, int);
 void auth_name(unsigned char*, int);
@@ -69,7 +69,7 @@
 void auth_request (void);
 void auth_send (unsigned char *, int);
 void auth_send_retry (void);
-void auth_printsub(unsigned char*, int, unsigned char*, int);
+void auth_printsub(unsigned char*, size_t, unsigned char*, size_t);
 int getauthmask(char *type, int *maskp);
 int auth_enable(char *type);
 int auth_disable(char *type);
@@ -78,8 +78,6 @@
 int auth_status(void);
 int auth_sendname(unsigned char *cp, int len);
 void auth_debug(int mode);
-void auth_gen_printsub(unsigned char *data, int cnt,
-		       unsigned char *buf, int buflen);
=20
 #ifdef UNSAFE
 int unsafe_init (Authenticator *, int);
@@ -87,7 +85,7 @@
 void unsafe_is (Authenticator *, unsigned char *, int);
 void unsafe_reply (Authenticator *, unsigned char *, int);
 int unsafe_status (Authenticator *, char *, int);
-void unsafe_printsub (unsigned char *, int, unsigned char *, int);
+void unsafe_printsub (unsigned char *, size_t, unsigned char *, size_t);
 #endif
=20
 #ifdef SRA
@@ -96,18 +94,7 @@
 void sra_is (Authenticator *, unsigned char *, int);
 void sra_reply (Authenticator *, unsigned char *, int);
 int sra_status (Authenticator *, char *, int);
-void sra_printsub (unsigned char *, int, unsigned char *, int);
-#endif
-
-#ifdef	KRB4
-int kerberos4_init (Authenticator *, int);
-int kerberos4_send_mutual (Authenticator *);
-int kerberos4_send_oneway (Authenticator *);
-void kerberos4_is (Authenticator *, unsigned char *, int);
-void kerberos4_reply (Authenticator *, unsigned char *, int);
-int kerberos4_status (Authenticator *, char *, size_t, int);
-void kerberos4_printsub (unsigned char *, int, unsigned char *, int);
-int kerberos4_forward(Authenticator *ap, void *);
+void sra_printsub (unsigned char *, size_t, unsigned char *, size_t);
 #endif
=20
 #ifdef	KRB5
@@ -117,7 +104,7 @@
 void kerberos5_is (Authenticator *, unsigned char *, int);
 void kerberos5_reply (Authenticator *, unsigned char *, int);
 int kerberos5_status (Authenticator *, char *, size_t, int);
-void kerberos5_printsub (unsigned char *, int, unsigned char *, int);
+void kerberos5_printsub (unsigned char *, size_t, unsigned char *, size_t);
 int kerberos5_set_forward(int);
 int kerberos5_set_forwardable(int);
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/auth.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/auth.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/auth.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -53,7 +53,7 @@
=20
 #include <config.h>
=20
-RCSID("$Id: auth.c 10809 2002-01-18 12:58:49Z joda $");
+RCSID("$Id$");
=20
 #if	defined(AUTHENTICATION)
 #include <stdio.h>
@@ -81,15 +81,6 @@
=20
 #define	typemask(x)		(1<<((x)-1))
=20
-#ifdef	KRB4_ENCPWD
-extern krb4encpwd_init();
-extern krb4encpwd_send();
-extern krb4encpwd_is();
-extern krb4encpwd_reply();
-extern krb4encpwd_status();
-extern krb4encpwd_printsub();
-#endif
-
 #ifdef	RSA_ENCPWD
 extern rsaencpwd_init();
 extern rsaencpwd_send();
@@ -166,31 +157,6 @@
       kerberos5_status,
       kerberos5_printsub },
 #endif
-#ifdef	KRB4
-    { AUTHTYPE_KERBEROS_V4, AUTH_WHO_CLIENT|AUTH_HOW_MUTUAL,
-      kerberos4_init,
-      kerberos4_send_mutual,
-      kerberos4_is,
-      kerberos4_reply,
-      kerberos4_status,
-      kerberos4_printsub },
-    { AUTHTYPE_KERBEROS_V4, AUTH_WHO_CLIENT|AUTH_HOW_ONE_WAY,
-      kerberos4_init,
-      kerberos4_send_oneway,
-      kerberos4_is,
-      kerberos4_reply,
-      kerberos4_status,
-      kerberos4_printsub },
-#endif
-#ifdef	KRB4_ENCPWD
-    { AUTHTYPE_KRB4_ENCPWD, AUTH_WHO_CLIENT|AUTH_HOW_MUTUAL,
-      krb4encpwd_init,
-      krb4encpwd_send,
-      krb4encpwd_is,
-      krb4encpwd_reply,
-      krb4encpwd_status,
-      krb4encpwd_printsub },
-#endif
 #ifdef	RSA_ENCPWD
     { AUTHTYPE_RSA_ENCPWD, AUTH_WHO_CLIENT|AUTH_HOW_ONE_WAY,
       rsaencpwd_init,
@@ -627,7 +593,8 @@
 }
=20
 void
-auth_printsub(unsigned char *data, int cnt, unsigned char *buf, int buflen)
+auth_printsub(unsigned char *data, size_t cnt,
+	      unsigned char *buf, size_t buflen)
 {
     Authenticator *ap;
=20
@@ -638,7 +605,8 @@
 }
=20
 void
-auth_gen_printsub(unsigned char *data, int cnt, unsigned char *buf, int bu=
flen)
+auth_gen_printsub(unsigned char *data, size_t cnt,
+		  unsigned char *buf, size_t buflen)
 {
     unsigned char *cp;
     unsigned char tbuf[16];
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/auth.h
--- a/head/crypto/heimdal/appl/telnet/libtelnet/auth.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/auth.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -53,7 +53,7 @@
  * or implied warranty.
  */
=20
-/* $Id: auth.h 5027 1998-06-09 19:25:40Z joda $ */
+/* $Id$ */
=20
 #ifndef	__AUTH__
 #define	__AUTH__
@@ -72,7 +72,7 @@
 	void	(*is) (struct XauthP *, unsigned char *, int);
 	void	(*reply) (struct XauthP *, unsigned char *, int);
 	int	(*status) (struct XauthP *, char *, size_t, int);
-	void	(*printsub) (unsigned char *, int, unsigned char *, int);
+	void	(*printsub) (unsigned char *, size_t, unsigned char *, size_t);
 } Authenticator;
=20
 #include "auth-proto.h"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/enc-proto.h
--- a/head/crypto/heimdal/appl/telnet/libtelnet/enc-proto.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/enc-proto.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -55,7 +55,7 @@
  * or implied warranty.
  */
=20
-/* $Id: enc-proto.h 10809 2002-01-18 12:58:49Z joda $ */
+/* $Id$ */
=20
 #if	defined(ENCRYPTION)
 Encryptions *findencryption (int);
@@ -81,12 +81,12 @@
 void encrypt_display(void);
 void encrypt_enc_keyid(unsigned char*, int);
 void encrypt_end(void);
-void encrypt_gen_printsub(unsigned char*, int, unsigned char*, int);
+void encrypt_gen_printsub(unsigned char*, size_t, unsigned char*, size_t);
 void encrypt_init(const char*, int);
 void encrypt_is(unsigned char*, int);
 void encrypt_list_types(void);
 void encrypt_not(void);
-void encrypt_printsub(unsigned char*, int, unsigned char*, int);
+void encrypt_printsub(unsigned char*, size_t, unsigned char*, size_t);
 void encrypt_reply(unsigned char*, int);
 void encrypt_request_end(void);
 void encrypt_request_start(unsigned char*, int);
@@ -118,7 +118,7 @@
 int cfb64_reply (unsigned char *, int);
 void cfb64_session (Session_Key *, int);
 int cfb64_keyid (int, unsigned char *, int *);
-void cfb64_printsub (unsigned char *, int, unsigned char *, int);
+void cfb64_printsub (unsigned char *, size_t, unsigned char *, size_t);
=20
 void ofb64_encrypt (unsigned char *, int);
 int ofb64_decrypt (int);
@@ -128,6 +128,6 @@
 int ofb64_reply (unsigned char *, int);
 void ofb64_session (Session_Key *, int);
 int ofb64_keyid (int, unsigned char *, int *);
-void ofb64_printsub (unsigned char *, int, unsigned char *, int);
+void ofb64_printsub (unsigned char *, size_t, unsigned char *, size_t);
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/enc_des.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/enc_des.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/enc_des.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include <config.h>
=20
-RCSID("$Id: enc_des.c 14681 2005-03-23 16:19:31Z lha $");
+RCSID("$Id$");
=20
 #if	defined(AUTHENTICATION) && defined(ENCRYPTION) && defined(DES_ENCRYPTI=
ON)
 #include <arpa/telnet.h>
@@ -83,7 +83,6 @@
 	int need_start;
 	int state[2];
 	int keyid[2];
-	int once;
 	struct stinfo streams[2];
 };
=20
@@ -124,8 +123,8 @@
 static void fb64_session (Session_Key *, int, struct fb *);
 void fb64_stream_key (DES_cblock, struct stinfo *);
 int fb64_keyid (int, unsigned char *, int *, struct fb *);
-void fb64_printsub(unsigned char *, int ,
-		   unsigned char *, int , char *);
+void fb64_printsub(unsigned char *, size_t ,
+		   unsigned char *, size_t , char *);
=20
 void cfb64_init(int server)
 {
@@ -210,22 +209,13 @@
 		/*
 		 * Create a random feed and send it over.
 		 */
-#ifndef OLD_DES_RANDOM_KEY
-		DES_random_key(&fbp->temp_feed);
-#else
-		/*
-		 * From des_cryp.man "If the des_check_key flag is non-zero,
-		 *  des_set_key will check that the key passed is
-		 *  of odd parity and is not a week or semi-weak key."
-		 */
 		do {
-			DES_random_key(fbp->temp_feed);
-			DES_set_odd_parity(fbp->temp_feed);
-		} while (DES_is_weak_key(fbp->temp_feed));
-#endif
-		DES_ecb_encrypt(&fbp->temp_feed,
-				&fbp->temp_feed,
-				&fbp->krbdes_sched, 1);
+		    if (RAND_bytes(fbp->temp_feed,
+				   sizeof(*fbp->temp_feed)) !=3D 1)
+			abort();
+		    DES_set_odd_parity(&fbp->temp_feed);
+		} while(DES_is_weak_key(&fbp->temp_feed));
+
 		p =3D fbp->fb_feed + 3;
 		*p++ =3D ENCRYPT_IS;
 		p++;
@@ -405,18 +395,13 @@
 	fb64_stream_key(fbp->krbdes_key, &fbp->streams[DIR_ENCRYPT-1]);
 	fb64_stream_key(fbp->krbdes_key, &fbp->streams[DIR_DECRYPT-1]);
=20
-	if (fbp->once =3D=3D 0) {
-#if !defined(OLD_DES_RANDOM_KEY) && !defined(HAVE_OPENSSL)
-		DES_init_random_number_generator(&fbp->krbdes_key);
-#endif
-		fbp->once =3D 1;
-	}
+	RAND_seed(key->data, key->length);
+
 	DES_set_key_checked((DES_cblock *)&fbp->krbdes_key,
 			    &fbp->krbdes_sched);
 	/*
-	 * Now look to see if krbdes_start() was was waiting for
-	 * the key to show up.  If so, go ahead an call it now
-	 * that we have the key.
+	 * Now look to see if krbdes_start() was waiting for the key to
+	 * show up.  If so, go ahead an call it now that we have the key.
 	 */
 	if (fbp->need_start) {
 		fbp->need_start =3D 0;
@@ -456,8 +441,8 @@
 	return(fbp->state[dir-1] =3D state);
 }
=20
-void fb64_printsub(unsigned char *data, int cnt,=20
-		   unsigned char *buf, int buflen, char *type)
+void fb64_printsub(unsigned char *data, size_t cnt,
+		   unsigned char *buf, size_t buflen, char *type)
 {
 	char lbuf[32];
 	int i;
@@ -497,14 +482,14 @@
 	}
 }
=20
-void cfb64_printsub(unsigned char *data, int cnt,=20
-		    unsigned char *buf, int buflen)
+void cfb64_printsub(unsigned char *data, size_t cnt,
+		    unsigned char *buf, size_t buflen)
 {
 	fb64_printsub(data, cnt, buf, buflen, "CFB64");
 }
=20
-void ofb64_printsub(unsigned char *data, int cnt,
-		    unsigned char *buf, int buflen)
+void ofb64_printsub(unsigned char *data, size_t cnt,
+		    unsigned char *buf, size_t buflen)
 {
 	fb64_printsub(data, cnt, buf, buflen, "OFB64");
 }
@@ -540,7 +525,7 @@
  *  INPUT --(--------->(+)+---> DATA
  *          |             |
  *	    +-------------+
- *        =20
+ *
  *
  * Given:
  *	iV: Initial vector, 64 bits (8 bytes) long.
@@ -596,7 +581,7 @@
 		DES_ecb_encrypt(&stp->str_output,&b, &stp->str_sched, 1);
 		memcpy(stp->str_feed, b, sizeof(DES_cblock));
 		stp->str_index =3D 1;	/* Next time will be 1 */
-		index =3D 0;		/* But now use 0 */=20
+		index =3D 0;		/* But now use 0 */
 	}
=20
 	/* On decryption we store (data) which is cypher. */
@@ -665,7 +650,7 @@
 		DES_ecb_encrypt(&stp->str_feed,&b,&stp->str_sched, 1);
 		memcpy(stp->str_feed, b, sizeof(DES_cblock));
 		stp->str_index =3D 1;	/* Next time will be 1 */
-		index =3D 0;		/* But now use 0 */=20
+		index =3D 0;		/* But now use 0 */
 	}
=20
 	return(data ^ stp->str_feed[index]);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/encrypt.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/encrypt.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/encrypt.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -54,16 +54,13 @@
=20
 #include <config.h>
=20
-RCSID("$Id: encrypt.c 16802 2006-03-23 19:36:31Z lha $");
+RCSID("$Id$");
=20
 #if	defined(ENCRYPTION)
=20
 #define	ENCRYPT_NAMES
 #include <arpa/telnet.h>
=20
-#include "encrypt.h"
-#include "misc.h"
-
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -72,6 +69,9 @@
 #include <socks.h>
 #endif
=20
+#include "encrypt.h"
+#include "misc.h"
+
=20
 /*
  * These functions pointers point to the current routines
@@ -108,7 +108,7 @@
      static Encryptions encryptions[] =3D {
 #if	defined(DES_ENCRYPTION)
 	 { "DES_CFB64",	ENCTYPE_DES_CFB64,
-	   cfb64_encrypt,=09
+	   cfb64_encrypt,
 	   cfb64_decrypt,
 	   cfb64_init,
 	   cfb64_start,
@@ -118,7 +118,7 @@
 	   cfb64_keyid,
 	   cfb64_printsub },
 	 { "DES_OFB64",	ENCTYPE_DES_OFB64,
-	   ofb64_encrypt,=09
+	   ofb64_encrypt,
 	   ofb64_decrypt,
 	   ofb64_init,
 	   ofb64_start,
@@ -388,7 +388,7 @@
 	       ENCTYPE_NAME(encrypt_mode));
     else
 	printf("Currently not encrypting output\r\n");
-=09
+
     if (decrypt_input)
 	printf("Currently decrypting input with %s\r\n",
 	       ENCTYPE_NAME(decrypt_mode));
@@ -411,7 +411,7 @@
 	       ENCTYPE_NAME(encrypt_mode));
     } else
 	printf("Currently not encrypting output\r\n");
-=09
+
     if (decrypt_input) {
 	printf("Currently decrypting input with %s\r\n",
 	       ENCTYPE_NAME(decrypt_mode));
@@ -714,7 +714,7 @@
  * Called when ENCRYPT REQUEST-START is received.  If we receive
  * this before a type is picked, then that indicates that the
  * other side wants us to start encrypting data as soon as we
- * can.=20
+ * can.
  */
 void
 encrypt_request_start(unsigned char *data, int cnt)
@@ -737,7 +737,7 @@
     int ret =3D 0;
=20
     if (len > MAXKEYLEN)
-        len =3D MAXKEYLEN;
+	len =3D MAXKEYLEN;
=20
     if (!(ep =3D (*kp->getcrypt)(*kp->modep))) {
 	if (len =3D=3D 0)
@@ -844,7 +844,7 @@
 	i =3D (*ep->start)(DIR_ENCRYPT, Server);
 	if (encrypt_debug_mode) {
 	    printf(">>>%s: Encrypt start: %s (%d) %s\r\n",
-		   Name,=20
+		   Name,
 		   (i < 0) ? "failed" :
 		   "initial negotiation in progress",
 		   i, ENCTYPE_NAME(type));
@@ -968,8 +968,8 @@
     encrypt_debug_mode =3D mode;
 }
=20
-void encrypt_gen_printsub(unsigned char *data, int cnt,=20
-			  unsigned char *buf, int buflen)
+void encrypt_gen_printsub(unsigned char *data, size_t cnt,
+			  unsigned char *buf, size_t buflen)
 {
     char tbuf[16], *cp;
=20
@@ -989,7 +989,8 @@
 }
=20
 void
-encrypt_printsub(unsigned char *data, int cnt, unsigned char *buf, int buf=
len)
+encrypt_printsub(unsigned char *data, size_t cnt,
+		 unsigned char *buf, size_t buflen)
 {
     Encryptions *ep;
     int type =3D data[1];
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/encrypt.h
--- a/head/crypto/heimdal/appl/telnet/libtelnet/encrypt.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/encrypt.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -55,7 +55,7 @@
  * or implied warranty.
  */
=20
-/* $Id: encrypt.h 11444 2002-09-10 20:03:49Z joda $ */
+/* $Id$ */
=20
 #ifndef	__ENCRYPT__
 #define	__ENCRYPT__
@@ -85,7 +85,7 @@
 	int	(*reply) (unsigned char *, int);
 	void	(*session) (Session_Key *, int);
 	int	(*keyid) (int, unsigned char *, int *);
-	void	(*printsub) (unsigned char *, int, unsigned char *, int);
+	void	(*printsub) (unsigned char *, size_t, unsigned char *, size_t);
 } Encryptions;
=20
 #define	SK_DES		1	/* Matched Kerberos v5 KEYTYPE_DES */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/genget.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/genget.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/genget.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -32,11 +32,14 @@
  */
=20
 #include <config.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#include <ctype.h>
 #include "misc-proto.h"
=20
-RCSID("$Id: genget.c 10646 2001-09-03 05:54:18Z assar $");
+RCSID("$Id$");
=20
-#include <ctype.h>
=20
 #define	LOWER(x) (isupper(x) ? tolower(x) : (x))
 /*
@@ -72,7 +75,7 @@
 genget(char *name, char **table, int stlen)
      /* name to match */
      /* name entry in table */
-	   	     =20
+
 {
     char **c, **found;
     int n;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/kerberos5.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/kerberos5.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/kerberos5.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -53,7 +53,7 @@
=20
 #include <config.h>
=20
-RCSID("$Id: kerberos5.c 22071 2007-11-14 20:04:50Z lha $");
+RCSID("$Id$");
=20
 #ifdef	KRB5
=20
@@ -132,10 +132,10 @@
     p0 =3D malloc(len);
     if (p0 =3D=3D NULL)
 	return 0;
-   =20
+
     memcpy(p0, str_data, sizeof(str_data));
     p =3D p0 + sizeof(str_data);
-=09
+
     if (auth_debug_mode) {
 	printf("%s:%d: [%d] (%d)",
 	       str_data[3] =3D=3D TELQUAL_IS ? ">>>IS" : ">>>REPLY",
@@ -199,14 +199,14 @@
     int ap_opts;
     krb5_data cksum_data;
     char ap_msg[2];
-   =20
+
     if (!UserNameRequested) {
 	if (auth_debug_mode) {
 	    printf("Kerberos V5: no user name supplied\r\n");
 	}
 	return(0);
     }
-   =20
+
     ret =3D krb5_cc_default(context, &ccache);
     if (ret) {
 	if (auth_debug_mode) {
@@ -215,14 +215,14 @@
 	}
 	return 0;
     }
-=09
+
     if ((ap->way & AUTH_HOW_MASK) =3D=3D AUTH_HOW_MUTUAL)
 	ap_opts =3D AP_OPTS_MUTUAL_REQUIRED;
     else
 	ap_opts =3D 0;
=20
     ap_opts |=3D AP_OPTS_USE_SUBKEY;
-   =20
+
     ret =3D krb5_auth_con_init (context, &auth_context);
     if (ret) {
 	if (auth_debug_mode) {
@@ -244,7 +244,7 @@
 	return(0);
     }
=20
-    krb5_auth_con_setkeytype (context, auth_context, KEYTYPE_DES);
+    krb5_auth_con_setkeytype (context, auth_context, KRB5_ENCTYPE_DES_CBC_=
CRC);
=20
     ap_msg[0] =3D ap->type;
     ap_msg[1] =3D ap->way;
@@ -282,7 +282,7 @@
 	}
 	printf("[ Trying %s (%s)... ]\r\n", name, sname);
 	ret =3D krb5_mk_req_exact(context, &auth_context, ap_opts,
-				service,=20
+				service,
 				&cksum_data, ccache, &auth);
 	krb5_free_principal (context, service);
=20
@@ -395,7 +395,7 @@
=20
 	ret =3D krb5_rd_req(context,
 			  &auth_context,
-			  &auth,=20
+			  &auth,
 			  server,
 			  NULL,
 			  NULL,
@@ -418,16 +418,16 @@
 		free (errbuf);
 	    return;
 	}
-=09
+
 	{
 	    char ap_msg[2];
-	   =20
+
 	    ap_msg[0] =3D ap->type;
 	    ap_msg[1] =3D ap->way;
-	   =20
+
 	    ret =3D krb5_verify_authenticator_checksum(context,
 						     auth_context,
-						     ap_msg,=20
+						     ap_msg,
 						     sizeof(ap_msg));
=20
 	    if (ret) {
@@ -435,7 +435,7 @@
 		char *errbuf;
 		int ret2;
=20
-		ret2 =3D asprintf(&errbuf, "Bad checksum: %s",=20
+		ret2 =3D asprintf(&errbuf, "Bad checksum: %s",
 				krb5_get_err_text(context, ret));
 		if (ret2 !=3D -1)
 		    errbuf2 =3D errbuf;
@@ -489,6 +489,7 @@
 		log_message("Kerberos V5: "
 			    "krb5_mk_rep failed (%s)",
 			    krb5_get_err_text(context, ret));
+		krb5_free_keyblock(context, key_block);
 		return;
 	    }
 	    Data(ap, KRB_RESPONSE, outbuf.data, outbuf.length);
@@ -501,7 +502,7 @@
 					     UserNameRequested)) {
 	    Data(ap, KRB_ACCEPT, name, name ? -1 : 0);
 	    log_message("%s accepted as user %s from %s",
-			name ? name : "<unknown>",=20
+			name ? name : "<unknown>",
 			UserNameRequested ? UserNameRequested : "<unknown>",
 			RemoteHostName ? RemoteHostName : "<unknown>");
=20
@@ -521,7 +522,7 @@
 	    char *msg;
=20
 	    ret =3D asprintf (&msg, "user `%s' is not authorized to "
-			    "login as `%s'",=20
+			    "login as `%s'",
 			    name ? name : "<unknown>",
 			    UserNameRequested ? UserNameRequested : "<nobody>");
 	    if (ret !=3D -1)
@@ -530,12 +531,12 @@
 	    if (ret !=3D -1)
 		free(msg);
 	    auth_finished (ap, AUTH_REJECT);
-	    krb5_free_keyblock_contents(context, key_block);
+	    krb5_free_keyblock(context, key_block);
 	    break;
 	}
 	auth_finished(ap, AUTH_USER);
-	krb5_free_keyblock_contents(context, key_block);
-=09
+	krb5_free_keyblock(context, key_block);
+
 	break;
     case KRB_FORWARD: {
 	struct passwd *pwd;
@@ -627,7 +628,7 @@
 	krb5_error_code ret;
 	Session_Key skey;
 	krb5_keyblock *keyblock;
-=09
+
 	if ((ap->way & AUTH_HOW_MASK) =3D=3D AUTH_HOW_MUTUAL &&
 	    !mutual_complete) {
 	    printf("[ Kerberos V5 accepted you, but didn't provide mutual authent=
ication! ]\r\n");
@@ -638,7 +639,7 @@
 	    printf("[ Kerberos V5 accepts you as ``%.*s'' ]\r\n", cnt, data);
 	else
 	    printf("[ Kerberos V5 accepts you ]\r\n");
-	     =20
+
 	ret =3D krb5_auth_con_getlocalsubkey (context,
 					    auth_context,
 					    &keyblock);
@@ -652,12 +653,12 @@
 	    auth_send_retry();
 	    return;
 	}
-	     =20
+
 	skey.type =3D SK_DES;
 	skey.length =3D 8;
 	skey.data =3D keyblock->keyvalue.data;
 	encrypt_session_key(&skey, 0);
-	krb5_free_keyblock_contents (context, keyblock);
+	krb5_free_keyblock (context, keyblock);
 	auth_finished(ap, AUTH_USER);
 	if (forward_flags & OPTS_FORWARD_CREDS)
 	    kerberos5_forward(ap);
@@ -669,7 +670,7 @@
 	  krb5_ap_rep_enc_part *reply;
 	  krb5_data inbuf;
 	  krb5_error_code ret;
-	   =20
+
 	  inbuf.length =3D cnt;
 	  inbuf.data =3D (char *)data;
=20
@@ -722,7 +723,8 @@
 #define	ADDC(buf, len, c)	if ((len) > 0) {*(buf)++ =3D (c); --(len);}
=20
 void
-kerberos5_printsub(unsigned char *data, int cnt, unsigned char *buf, int b=
uflen)
+kerberos5_printsub(unsigned char *data, size_t cnt,
+		   unsigned char *buf, size_t buflen)
 {
     int i;
=20
@@ -810,14 +812,13 @@
     memset (&creds, 0, sizeof(creds));
=20
     creds.client =3D principal;
-   =20
-    ret =3D krb5_build_principal (context,
-				&creds.server,
-				strlen(principal->realm),
-				principal->realm,
-				"krbtgt",
-				principal->realm,
-				NULL);
+
+    ret =3D krb5_make_principal(context,
+			      &creds.server,
+			      principal->realm,
+			      "krbtgt",
+			      principal->realm,
+			      NULL);
=20
     if (ret) {
 	if (auth_debug_mode)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/misc-proto.h
--- a/head/crypto/heimdal/appl/telnet/libtelnet/misc-proto.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/misc-proto.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -53,7 +53,7 @@
  * or implied warranty.
  */
=20
-/* $Id: misc-proto.h 9187 2000-11-15 23:00:21Z assar $ */
+/* $Id$ */
=20
 #ifndef	__MISC_PROTO__
 #define	__MISC_PROTO__
@@ -75,5 +75,5 @@
 int telnet_spin (void);
 char *telnet_getenv (const char *);
 char *telnet_gets (char *, char *, int, int);
-void printsub(int direction, unsigned char *pointer, int length);
+void printsub(int direction, unsigned char *pointer, size_t);
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/misc.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/misc.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/misc.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -33,7 +33,7 @@
=20
 #include <config.h>
=20
-RCSID("$Id: misc.c 7822 2000-01-25 23:24:58Z assar $");
+RCSID("$Id$");
=20
 #include <stdio.h>
 #include <stdlib.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/rsaencpwd.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/rsaencpwd.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/rsaencpwd.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include <config.h>
=20
-RCSID("$Id: rsaencpwd.c 22071 2007-11-14 20:04:50Z lha $");
+RCSID("$Id$");
=20
 #ifdef	RSA_ENCPWD
 /*
@@ -403,11 +403,10 @@
 #define	ADDC(buf, len, c)	if ((len) > 0) {*(buf)++ =3D (c); --(len);}
=20
 	void
-rsaencpwd_printsub(data, cnt, buf, buflen)
-	unsigned char *data, *buf;
-	int cnt, buflen;
+rsaencpwd_printsub(unsigned char *data, size_t cnt,
+		   unsigned char * buf, size_t buflen)
 {
-	int i;
+	size_t i;
=20
 	buf[buflen-1] =3D '\0';		/* make sure it's NULL terminated */
 	buflen -=3D 1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/libtel=
net/spx.c
--- a/head/crypto/heimdal/appl/telnet/libtelnet/spx.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/appl/telnet/libtelnet/spx.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -33,7 +33,7 @@
=20
 #include <config.h>
=20
-RCSID("$Id: spx.c 22071 2007-11-14 20:04:50Z lha $");
+RCSID("$Id$");
=20
 #ifdef	SPX
 /*
@@ -237,7 +237,9 @@
 					&output_name_buffer,
 					&output_name_type);
=20
-	printf("target is '%s'\n", output_name_buffer.value); fflush(stdout);
+	printf("target is '%.*s'\n", (int)output_name_buffer.length,
+					(char*)output_name_buffer.value);
+	fflush(stdout);
=20
 	major_status =3D gss_release_buffer(&status, &output_name_buffer);
=20
@@ -290,7 +292,8 @@
 				GSS_C_NULL_OID,
 				&msg_ctx,
 				&status_string);
-	  printf("%s\n", status_string.value);
+	  printf("%.*s\n", (int)status_string.length,
+				(char*)status_string.value);
 	  return(0);
 	}
=20
@@ -457,8 +460,9 @@
 					GSS_C_NULL_OID,
 					&msg_ctx,
 					&status_string);
-		    printf("[ SPX mutual response fails ... '%s' ]\r\n",
-			 status_string.value);
+		    printf("[ SPX mutual response fails ... '%.*s' ]\r\n",
+			 (int)status_string.length,
+			 (char*)status_string.value);
 		    auth_send_retry();
 		    return;
 		  }
@@ -526,11 +530,10 @@
 #define	ADDC(buf, len, c)	if ((len) > 0) {*(buf)++ =3D (c); --(len);}
=20
 	void
-spx_printsub(data, cnt, buf, buflen)
-	unsigned char *data, *buf;
-	int cnt, buflen;
+spx_printsub(unsigned char *data, size_t cnt,
+	     unsigned char *buf, size_t buflen)
 {
-	int i;
+	size_t i;
=20
 	buf[buflen-1] =3D '\0';		/* make sure it's NULL terminated */
 	buflen -=3D 1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/Makefile.am
--- a/head/crypto/heimdal/appl/telnet/telnet/Makefile.am	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/Makefile.am	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,8 +1,8 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D -I$(srcdir)/.. $(INCLUDE_krb4) $(INCLUDE_hcrypto)
+AM_CPPFLAGS +=3D -I$(srcdir)/.. $(INCLUDE_hcrypto)
=20
 bin_PROGRAMS =3D telnet
=20
@@ -16,10 +16,9 @@
=20
 LDADD =3D ../libtelnet/libtelnet.a \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_tgetent) \
 	$(LIB_kdfs) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/Makefile.in
--- a/head/crypto/heimdal/appl/telnet/telnet/Makefile.in	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/Makefile.in	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/telnet/telnet
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,14 +89,14 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS)
 am_telnet_OBJECTS =3D authenc.$(OBJEXT) commands.$(OBJEXT) \
 	main.$(OBJEXT) network.$(OBJEXT) ring.$(OBJEXT) \
@@ -101,11 +106,11 @@
 telnet_LDADD =3D $(LDADD)
 am__DEPENDENCIES_1 =3D
 telnet_DEPENDENCIES =3D ../libtelnet/libtelnet.a $(LIB_krb5) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(LIB_kdfs) $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) $(LIB_kdfs) \
+	$(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -117,6 +122,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(telnet_SOURCES)
 DIST_SOURCES =3D $(telnet_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -126,49 +152,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -192,10 +227,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -212,6 +248,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -227,31 +265,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -266,10 +318,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -310,30 +364,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	-I$(srcdir)/.. $(INCLUDE_krb4) $(INCLUDE_hcrypto)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I$(srcdir)/.. $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 CHECK_LOCAL =3D=20
 telnet_SOURCES =3D authenc.c commands.c main.c network.c ring.c \
@@ -343,29 +401,28 @@
 man_MANS =3D telnet.1
 LDADD =3D ../libtelnet/libtelnet.a \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_tgetent) \
 	$(LIB_kdfs) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/teln=
et/telnet/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/telnet/telnet/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/telnet/telnet/Makef=
ile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/telnet/telnet/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -383,34 +440,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 telnet$(EXEEXT): $(telnet_OBJECTS) $(telnet_DEPENDENCIES)=20
 	@rm -f telnet$(EXEEXT)
 	$(LINK) $(telnet_OBJECTS) $(telnet_LDADD) $(LIBS)
@@ -421,115 +494,147 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/authenc.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/commands.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/main.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/network.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ring.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/sys_bsd.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/telnet.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/terminal.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/utilities.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -545,13 +650,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -586,6 +695,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -595,6 +705,7 @@
 clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -605,6 +716,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -612,26 +725,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -651,11 +773,10 @@
 uninstall-am: uninstall-binPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libtool ctags \
@@ -742,6 +863,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -827,7 +951,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -840,6 +964,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/authenc.c
--- a/head/crypto/heimdal/appl/telnet/telnet/authenc.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/authenc.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: authenc.c 12921 2003-09-25 15:45:51Z lha $");
+RCSID("$Id$");
=20
 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
 int
@@ -68,7 +68,7 @@
     if (Scheduler(0) =3D=3D -1)
 	ret =3D 1;
     scheduler_lockout_tty =3D 0;
-   =20
+
     return ret;
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/commands.c
--- a/head/crypto/heimdal/appl/telnet/telnet/commands.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/commands.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: commands.c 16224 2005-10-22 17:17:44Z lha $");
+RCSID("$Id$");
=20
 #if	defined(IPPROTO_IP) && defined(IP_TOS)
 int tos =3D -1;
@@ -453,20 +453,6 @@
     return 1;
 }
=20
-#if defined(KRB4) && defined(HAVE_KRB_DISABLE_DEBUG)
-#include <krb.h>
-
-static int
-togkrbdebug(void)
-{
-    if(krb_debug)
-	krb_enable_debug();
-    else
-	krb_disable_debug();
-    return 1;
-}
-#endif
-
 static int
 togcrlf()
 {
@@ -688,13 +674,6 @@
 	    togdebug,
 		&debug,
 		    "turn on socket level debugging" },
-#if defined(KRB4) && defined(HAVE_KRB_DISABLE_DEBUG)
-    { "krb_debug",
-      "kerberos 4 debugging",
-      togkrbdebug,
-      &krb_debug,
-      "turn on kerberos 4 debugging" },
-#endif
     { "netdata",
 	"printing of hexadecimal network data (debugging)",
 	    0,
@@ -1351,7 +1330,7 @@
 	/* reset options */
 	tninit();
     }
-    if ((argc !=3D 2) || (strcmp(argv[1], "fromquit") !=3D 0))=20
+    if ((argc !=3D 2) || (strcmp(argv[1], "fromquit") !=3D 0))
 	longjmp(toplevel, 1);
     return 0;	/* NOTREACHED */
 }
@@ -1553,8 +1532,8 @@
 	return(NULL);
 }
=20
-#ifdef IRIX4
-#define environ _environ
+#if !HAVE_DECL_ENVIRON
+extern char **environ;
 #endif
=20
 void
@@ -1619,7 +1598,7 @@
 	 * USER with the value from LOGNAME.  By default, we
 	 * don't export the USER variable.
 	 */
-	if ((env_find((unsigned char*)"USER") =3D=3D NULL) &&=20
+	if ((env_find((unsigned char*)"USER") =3D=3D NULL) &&
 	    (ep =3D env_find((unsigned char*)"LOGNAME"))) {
 		env_define((unsigned char *)"USER", ep->value);
 		env_unexport((unsigned char *)"USER");
@@ -2202,7 +2181,7 @@
 			     addrstr, sizeof(addrstr),
 			     NULL, 0, NI_NUMERICHOST) !=3D 0)
 		strlcpy (addrstr, "unknown address", sizeof(addrstr));
-			    =20
+
 	    printf("Trying %s...\r\n", addrstr);
=20
 	    net =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/externs.h
--- a/head/crypto/heimdal/appl/telnet/telnet/externs.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/externs.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -33,7 +33,7 @@
  *	@(#)externs.h	8.3 (Berkeley) 5/30/95
  */
=20
-/* $Id: externs.h 21734 2007-07-31 01:55:45Z lha $ */
+/* $Id$ */
=20
 #ifndef	BSD
 # define BSD 43
@@ -291,7 +291,6 @@
=20
 void     Dump (char, unsigned char *, int);
 void     printoption (char *, int, int);
-void     printsub (int, unsigned char *, int);
 void     sendnaws (void);
 void     setconnmode (int);
 void     setcommandmode (void);
@@ -360,7 +359,7 @@
 void Dump(char direction, unsigned char *buffer, int length);
 void printoption(char *direction, int cmd, int option);
 void optionstatus(void);
-void printsub(int direction, unsigned char *pointer, int length);
+void printsub(int direction, unsigned char *pointer, size_t length);
 void EmptyTerminal(void);
 void SetForExit(void);
 void Exit(int returnCode);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/main.c
--- a/head/crypto/heimdal/appl/telnet/telnet/main.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/main.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -38,7 +38,7 @@
 };
=20
 #include "telnet_locl.h"
-RCSID("$Id: main.c 21731 2007-07-30 20:01:26Z lha $");
+RCSID("$Id$");
=20
 #if KRB5
 #define FORWARD
@@ -138,12 +138,12 @@
 	    kerberos5_set_forwardable(1);
 #endif
 #ifdef  ENCRYPTION
-    krb5_appdefault_boolean(context, NULL,=20
+    krb5_appdefault_boolean(context, NULL,
 			    NULL, "encrypt",
 			    0, &ret_val);
     if (ret_val) {
           encrypt_auto(1);
-          decrypt_auto(1);=20
+          decrypt_auto(1);
 	  wantencryption =3D 1;
           EncryptVerbose(1);
         }
@@ -153,11 +153,6 @@
 }
 #endif
=20
-#if defined(AUTHENTICATION) && defined(KRB4)
-extern char *dest_realm, dst_realm_buf[];
-extern int dst_realm_sz;
-#endif
-
 int
 main(int argc, char **argv)
 {
@@ -169,7 +164,7 @@
 #ifdef KRB5
 	krb5_init();
 #endif
-=09
+
 	tninit();		/* Clear out things */
=20
 	TerminalSaveState();
@@ -183,10 +178,10 @@
=20
 	rlogin =3D (strncmp(prompt, "rlog", 4) =3D=3D 0) ? '~' : _POSIX_VDISABLE;
=20
-	/*=20
+	/*
 	 * if AUTHENTICATION and ENCRYPTION is set autologin will be
 	 * se to true after the getopt switch; unless the -K option is
-	 * passed=20
+	 * passed
 	 */
 	autologin =3D -1;
=20
@@ -280,17 +275,10 @@
 #endif
 			break;
 		case 'k':
-#if defined(AUTHENTICATION) && defined(KRB4)
-		    {
-			dest_realm =3D dst_realm_buf;
-			strlcpy(dest_realm, optarg, dst_realm_sz);
-		    }
-#else
-			fprintf(stderr,
-			   "%s: Warning: -k ignored, no Kerberos V4 support.\n",
-								prompt);
-#endif
-			break;
+		    fprintf(stderr,
+			    "%s: Warning: -k ignored, no Kerberos V4 support.\n",
+			    prompt);
+		    break;
 		case 'l':
 		  if(autologin =3D=3D 0){
 		    fprintf(stderr, "%s: Warning: -K ignored\n", prompt);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/network.c
--- a/head/crypto/heimdal/appl/telnet/telnet/network.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/network.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: network.c 13941 2004-06-20 17:01:28Z lha $");
+RCSID("$Id$");
=20
 Ring		netoring, netiring;
 size_t		netobufsize =3D 64*1024;
@@ -47,7 +47,7 @@
 init_network(void)
 {
     void *obuf, *ibuf;
-   =20
+
     if ((obuf =3D malloc(netobufsize)) =3D=3D NULL)
 	exit(1);
     if ((ibuf =3D malloc(netibufsize)) =3D=3D NULL)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/ring.c
--- a/head/crypto/heimdal/appl/telnet/telnet/ring.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/ring.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: ring.c 7853 2000-02-06 05:15:47Z assar $");
+RCSID("$Id$");
=20
 /*
  * This defines a structure for a ring buffer.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/ring.h
--- a/head/crypto/heimdal/appl/telnet/telnet/ring.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/ring.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -33,7 +33,7 @@
  *	@(#)ring.h	8.1 (Berkeley) 6/6/93
  */
=20
-/* $Id: ring.h 7853 2000-02-06 05:15:47Z assar $ */
+/* $Id$ */
=20
 /*
  * This defines a structure for a ring buffer.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/sys_bsd.c
--- a/head/crypto/heimdal/appl/telnet/telnet/sys_bsd.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/sys_bsd.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: sys_bsd.c 10941 2002-04-18 16:18:43Z joda $");
+RCSID("$Id$");
=20
 /*
  * The following routines try to encapsulate what is system dependent
@@ -608,11 +608,11 @@
 int
 TerminalWindowSize(long *rows, long *cols)
 {
-    struct winsize ws;
+    int irows, icols;
=20
-    if (get_window_size (STDIN_FILENO, &ws) =3D=3D 0) {
-	*rows =3D ws.ws_row;
-	*cols =3D ws.ws_col;
+    if (get_window_size(STDIN_FILENO, &irows, &icols) =3D=3D 0) {
+	*rows =3D irows;
+	*cols =3D icols;
 	return 1;
     } else
 	return 0;
@@ -641,7 +641,7 @@
 #ifdef SIGINFO
 static RETSIGTYPE ayt(int);
 #endif
- =20
+
=20
     /* ARGSUSED */
 static RETSIGTYPE
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/telnet.c
--- a/head/crypto/heimdal/appl/telnet/telnet/telnet.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/telnet.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: telnet.c 16285 2005-11-03 18:38:57Z lha $");
+RCSID("$Id$");
=20
 #define	strip(x) (eight ? (x) : ((x) & 0x7f))
=20
@@ -1631,7 +1631,7 @@
 		telrcv_state =3D TS_IAC;
 		break;
 	    }
-		    /*=20
+		    /*
 		     * The 'crmod' hack (see following) is needed
 		     * since we can't set CRMOD on output only.
 		     * Machines like MULTICS like to send \r without
@@ -2036,7 +2036,7 @@
 my_telnet(char *user)
 {
     int printed_encrypt =3D 0;
-   =20
+
     sys_telnet_init();
=20
 #if	defined(AUTHENTICATION) || defined(ENCRYPTION)
@@ -2079,7 +2079,7 @@
     /*
      * Note: we assume a tie to the authentication option here.  This
      * is necessary so that authentication fails, we don't spin
-     * forever.=20
+     * forever.
      */
     if (telnetport && wantencryption) {
 	time_t timeout =3D time(0) + 60;
@@ -2116,7 +2116,7 @@
 		    printed_encrypt =3D 1;
 		    printf("Waiting for encryption to be negotiated...\n");
 		    /*
-		     * Turn on MODE_TRAPSIG and then turn off localchars=20
+		     * Turn on MODE_TRAPSIG and then turn off localchars
 		     * so that ^C will cause telnet to exit.
 		     */
 		    TerminalNewMode(getconnmode()|MODE_TRAPSIG);
@@ -2130,7 +2130,7 @@
 		    printf("\nServer disconnected.\n");
 		    Exit(1);
 	    }
-	=09
+
 	}
 	if (printed_encrypt) {
 		printf("Encryption negotiated.\n");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/telnet_locl.h
--- a/head/crypto/heimdal/appl/telnet/telnet/telnet_locl.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/telnet_locl.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: telnet_locl.h 18776 2006-10-21 19:14:13Z lha $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/terminal.c
--- a/head/crypto/heimdal/appl/telnet/telnet/terminal.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/terminal.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: terminal.c 9733 2001-03-06 20:10:14Z assar $");
+RCSID("$Id$");
=20
 Ring		ttyoring, ttyiring;
 unsigned char	ttyobuf[2*BUFSIZ], ttyibuf[BUFSIZ];
@@ -195,7 +195,7 @@
     newmode =3D getconnmode()|(force?MODE_FORCE:0);
=20
     TerminalNewMode(newmode);
-   =20
+
 #ifdef  ENCRYPTION
     if ((newmode & (MODE_ECHO|MODE_EDIT)) =3D=3D MODE_EDIT) {
 	if (my_want_state_is_will(TELOPT_ENCRYPT)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
/utilities.c
--- a/head/crypto/heimdal/appl/telnet/telnet/utilities.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnet/utilities.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -37,7 +37,7 @@
=20
 #include "telnet_locl.h"
=20
-RCSID("$Id: utilities.c 10587 2001-08-29 00:45:23Z assar $");
+RCSID("$Id$");
=20
 FILE	*NetTrace =3D 0;		/* Not in bss, since needs to stay */
 int	prettydump;
@@ -248,8 +248,20 @@
=20
 }
=20
+static void __attribute__((format (printf, 3, 4)))
+qprintf(int quote, FILE *f, const char *fmt, ...)
+
+{
+    va_list va;
+    if (quote)
+	fprintf(f, "\" ");
+    va_start(va, fmt);
+    vfprintf(f, fmt, va);
+    va_end(va);
+}
+
 void
-printsub(int direction, unsigned char *pointer, int length)
+printsub(int direction, unsigned char *pointer, size_t length)
 {
     int i;
     unsigned char buf[512];
@@ -295,7 +307,9 @@
 	    fprintf(NetTrace, "TERMINAL-TYPE ");
 	    switch (pointer[1]) {
 	    case TELQUAL_IS:
-		fprintf(NetTrace, "IS \"%.*s\"", length-2, (char *)pointer+2);
+		fprintf(NetTrace, "IS \"%.*s\"",
+			(int)(length-2),
+			(char *)pointer+2);
 		break;
 	    case TELQUAL_SEND:
 		fprintf(NetTrace, "SEND");
@@ -315,7 +329,7 @@
 	    switch (pointer[1]) {
 	    case TELQUAL_IS:
 		fprintf(NetTrace, " IS ");
-		fprintf(NetTrace, "%.*s", length-2, (char *)pointer+2);
+		fprintf(NetTrace, "%.*s", (int)(length-2), (char *)pointer+2);
 		break;
 	    default:
 		if (pointer[1] =3D=3D 1)
@@ -696,7 +710,7 @@
 	    fprintf(NetTrace, "X-DISPLAY-LOCATION ");
 	    switch (pointer[1]) {
 	    case TELQUAL_IS:
-		fprintf(NetTrace, "IS \"%.*s\"", length-2, (char *)pointer+2);
+		fprintf(NetTrace, "IS \"%.*s\"", (int)(length-2), (char *)pointer+2);
 		break;
 	    case TELQUAL_SEND:
 		fprintf(NetTrace, "SEND");
@@ -726,57 +740,44 @@
 		fprintf(NetTrace, "INFO ");
 	    env_common:
 		{
-		    int noquote =3D 2;
+		    int quote =3D 0;
 		    for (i =3D 2; i < length; i++ ) {
 			switch (pointer[i]) {
-			case NEW_ENV_VALUE:
-#ifdef OLD_ENVIRON
-		     /*	case NEW_ENV_OVAR: */
-			    if (pointer[0] =3D=3D TELOPT_OLD_ENVIRON) {
-				    fprintf(NetTrace, "\" VAR " + noquote);
-			    } else
-#endif /* OLD_ENVIRON */
-				fprintf(NetTrace, "\" VALUE " + noquote);
-			    noquote =3D 2;
+			case NEW_ENV_VAR:
+			    qprintf(quote, NetTrace, "VAR ");
+			    quote =3D 0;
 			    break;
=20
-			case NEW_ENV_VAR:
-#ifdef OLD_ENVIRON
-		     /* case OLD_ENV_VALUE: */
-			    if (pointer[0] =3D=3D TELOPT_OLD_ENVIRON) {
-				    fprintf(NetTrace, "\" VALUE " + noquote);
-			    } else
-#endif /* OLD_ENVIRON */
-				fprintf(NetTrace, "\" VAR " + noquote);
-			    noquote =3D 2;
+			case NEW_ENV_VALUE:
+			    qprintf(quote, NetTrace, "VALUE");
+			    quote =3D 0;
 			    break;
=20
 			case ENV_ESC:
-			    fprintf(NetTrace, "\" ESC " + noquote);
-			    noquote =3D 2;
+			    qprintf(quote, NetTrace, "ESC ");
+			    quote =3D 0;
 			    break;
=20
 			case ENV_USERVAR:
-			    fprintf(NetTrace, "\" USERVAR " + noquote);
-			    noquote =3D 2;
+			    qprintf(quote, NetTrace, "USERVAR ");
+			    quote =3D 0;
 			    break;
=20
 			default:
 			    if (isprint(pointer[i]) && pointer[i] !=3D '"') {
-				if (noquote) {
+				if (!quote) {
 				    putc('"', NetTrace);
-				    noquote =3D 0;
+				    quote =3D 1;
 				}
 				putc(pointer[i], NetTrace);
 			    } else {
-				fprintf(NetTrace, "\" %03o " + noquote,
-							pointer[i]);
-				noquote =3D 2;
+				qprintf(quote, NetTrace, "%03o ", pointer[i]);
+				quote =3D 0;
 			    }
 			    break;
 			}
 		    }
-		    if (!noquote)
+		    if (quote)
 			putc('"', NetTrace);
 		    break;
 		}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/Makefile.am
--- a/head/crypto/heimdal/appl/telnet/telnetd/Makefile.am	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/Makefile.am	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,8 +1,8 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D -I$(srcdir)/.. $(INCLUDE_krb4) $(INCLUDE_hcrypto)
+AM_CPPFLAGS +=3D -I$(srcdir)/.. $(INCLUDE_hcrypto)
=20
 libexec_PROGRAMS =3D telnetd
=20
@@ -16,7 +16,6 @@
 LDADD =3D \
 	../libtelnet/libtelnet.a \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_tgetent) \
 	$(LIB_logwtmp) \
@@ -25,4 +24,4 @@
 	$(LIB_kdfs) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/Makefile.in
--- a/head/crypto/heimdal/appl/telnet/telnetd/Makefile.in	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/Makefile.in	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D appl/telnet/telnetd
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,14 +89,14 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(man8dir)"
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(libexec_PROGRAMS)
 am_telnetd_OBJECTS =3D telnetd.$(OBJEXT) state.$(OBJEXT) \
 	termstat.$(OBJEXT) slc.$(OBJEXT) sys_term.$(OBJEXT) \
@@ -102,11 +107,10 @@
 telnetd_DEPENDENCIES =3D ../libtelnet/libtelnet.a $(LIB_krb5) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) $(LIB_kdfs) \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(am__DEPENDENCIES_1) $(LIB_kdfs) $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -118,6 +122,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(telnetd_SOURCES)
 DIST_SOURCES =3D $(telnetd_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -127,49 +152,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -193,10 +227,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -213,6 +248,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -228,31 +265,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -267,10 +318,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -311,30 +364,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	-I$(srcdir)/.. $(INCLUDE_krb4) $(INCLUDE_hcrypto)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I$(srcdir)/.. $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 CHECK_LOCAL =3D=20
 telnetd_SOURCES =3D telnetd.c state.c termstat.c slc.c sys_term.c \
@@ -344,7 +401,6 @@
 LDADD =3D \
 	../libtelnet/libtelnet.a \
 	$(LIB_krb5) \
-	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(LIB_tgetent) \
 	$(LIB_logwtmp) \
@@ -353,23 +409,23 @@
 	$(LIB_kdfs) \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/teln=
et/telnetd/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/telnet/telnetd/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/telnet/telnetd/Make=
file'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/telnet/telnetd/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -387,34 +443,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 telnetd$(EXEEXT): $(telnetd_OBJECTS) $(telnetd_DEPENDENCIES)=20
 	@rm -f telnetd$(EXEEXT)
 	$(LINK) $(telnetd_OBJECTS) $(telnetd_LDADD) $(LIBS)
@@ -425,115 +497,146 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/authenc.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/global.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/slc.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/state.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/sys_term.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/telnetd.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/termstat.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/utility.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man8: $(man8_MANS) $(man_MANS)
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -549,13 +652,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -590,6 +697,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -600,6 +708,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -610,6 +719,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -617,26 +728,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -656,11 +776,10 @@
 uninstall-am: uninstall-libexecPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libexecPROGRAMS clean-libtool ctags \
@@ -747,6 +866,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -832,7 +954,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -845,6 +967,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/authenc.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/authenc.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/authenc.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnetd.h"
=20
-RCSID("$Id: authenc.c 9200 2000-11-15 23:20:43Z assar $");
+RCSID("$Id$");
=20
 #ifdef AUTHENTICATION
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/defs.h
--- a/head/crypto/heimdal/appl/telnet/telnetd/defs.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/defs.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -57,11 +57,11 @@
 #ifndef TIOCPKT_FLUSHWRITE
 #define TIOCPKT_FLUSHWRITE      0x02
 #endif
-=20
+
 #ifndef TIOCPKT_NOSTOP
 #define TIOCPKT_NOSTOP  0x10
 #endif
-=20
+
 #ifndef TIOCPKT_DOSTOP
 #define TIOCPKT_DOSTOP  0x20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/ext.h
--- a/head/crypto/heimdal/appl/telnet/telnetd/ext.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/ext.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -33,7 +33,7 @@
  *	@(#)ext.h	8.2 (Berkeley) 12/15/93
  */
=20
-/* $Id: ext.h 15841 2005-08-08 13:34:26Z lha $ */
+/* $Id$ */
=20
 #ifndef __EXT_H__
 #define __EXT_H__
@@ -147,8 +147,8 @@
 void putchr (int cc);
 void putf (char *cp, char *where);
 void printoption (char *fmt, int option);
-void printsub (int direction, unsigned char *pointer, int length);
-void printdata (char *tag, char *ptr, int cnt);
+void printsub (int direction, unsigned char *pointer, size_t length);
+void printdata (char *tag, char *ptr, size_t cnt);
 int login_tty(int t);
=20
 #ifdef ENCRYPTION
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/global.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/global.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/global.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -36,7 +36,7 @@
=20
 #include "telnetd.h"
=20
-RCSID("$Id: global.c 14939 2005-04-24 20:59:35Z lha $");
+RCSID("$Id$");
=20
 /*
  * Telnet server variable declarations
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/slc.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/slc.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/slc.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnetd.h"
=20
-RCSID("$Id: slc.c 1695 1997-05-11 06:30:05Z assar $");
+RCSID("$Id$");
=20
 /*
  * get_slc_defaults
@@ -44,14 +44,14 @@
 get_slc_defaults(void)
 {
     int i;
-   =20
+
     init_termbuf();
-   =20
+
     for (i =3D 1; i <=3D NSLC; i++) {
 	slctab[i].defset.flag =3D
 	    spcset(i, &slctab[i].defset.val, &slctab[i].sptr);
 	slctab[i].current.flag =3D SLC_NOSUPPORT;
 	slctab[i].current.val =3D 0;
     }
-   =20
+
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/state.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/state.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/state.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnetd.h"
=20
-RCSID("$Id: state.c 18110 2006-09-19 08:25:20Z lha $");
+RCSID("$Id$");
=20
 unsigned char	doopt[] =3D { IAC, DO, '%', 'c', 0 };
 unsigned char	dont[] =3D { IAC, DONT, '%', 'c', 0 };
@@ -506,7 +506,7 @@
 		changeok++;
 		break;
 #endif
-		=09
+
 	    default:
 		break;
 	    }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/sys_term.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/sys_term.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/sys_term.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnetd.h"
=20
-RCSID("$Id: sys_term.c 22390 2007-12-31 10:12:48Z lha $");
+RCSID("$Id$");
=20
 #if defined(_CRAY) || (defined(__hpux) && !defined(HAVE_UTMPX_H))
 # define PARENT_DOES_UTMP
@@ -67,6 +67,11 @@
 #endif
 #endif
=20
+/* really, mac os uses wtmpx (or asl) */
+#ifdef __APPLE__
+#undef _PATH_WTMP
+#endif
+
 #if !defined(WTMP_FILE) && defined(_PATH_WTMP)
 #define WTMP_FILE _PATH_WTMP
 #endif
@@ -159,6 +164,8 @@
 # ifdef  STREAMSPTY
      static int ttyfd =3D -1;
      int really_stream =3D 0;
+# else
+#define really_stream 0
 # endif
=20
      const char *new_login =3D _PATH_LOGIN;
@@ -379,12 +386,12 @@
 	return master;
     }
 #endif
-   =20
+
 #ifdef	STREAMSPTY
     {
-	char *clone[] =3D { "/dev/ptc", "/dev/ptmx", "/dev/ptm",=20
+	char *clone[] =3D { "/dev/ptc", "/dev/ptmx", "/dev/ptm",
 			  "/dev/ptym/clone", 0 };
-=09
+
 	char **q;
 	int p;
 	for(q=3Dclone; *q; q++){
@@ -408,7 +415,7 @@
 	int p;
 	char *cp, *p1, *p2;
 	int i;
-=09
+
 #ifndef	__hpux
 	snprintf(line, sizeof(Xline), "/dev/ptyXX");
 	p1 =3D &line[8];
@@ -418,11 +425,11 @@
 	p1 =3D &line[13];
 	p2 =3D &line[14];
 #endif
-=09
-=09
+
+
 	for (cp =3D "pqrstuvwxyzPQRST"; *cp; cp++) {
 	    struct stat stb;
-	   =20
+
 	    *p1 =3D *cp;
 	    *p2 =3D '0';
 	    /*
@@ -439,7 +446,7 @@
 #if SunOS =3D=3D 40
 		    int dummy;
 #endif
-		   =20
+
 #ifndef	__hpux
 		    line[5] =3D 't';
 #else
@@ -467,7 +474,7 @@
 	extern lowpty, highpty;
 	struct stat sb;
 	int p;
-=09
+
 	for (*ptynum =3D lowpty; *ptynum <=3D highpty; (*ptynum)++) {
 	    snprintf(myline, sizeof(myline), "/dev/pty/%03d", *ptynum);
 	    p =3D open(myline, 2);
@@ -748,7 +755,7 @@
     static struct str_list sl;
     int n;
     int i;
- =20
+
     if(!flag){
 	n =3D ioctl(fd, I_LIST, 0);
 	if(n < 0){
@@ -764,7 +771,7 @@
 	}
 	flag =3D 1;
     }
- =20
+
     for(i=3D0; i<sl.sl_nmods; i++)
 	if(!strcmp(sl.sl_modlist[i].l_name, module))
 	    return 1;
@@ -787,7 +794,7 @@
     }
     /* p points to null or to an already pushed module, now push all
        modules before this one */
- =20
+
     for(p--; p >=3D modules; p--){
 	err =3D ioctl(fd, I_PUSH, *p);
 	if(err < 0 && errno !=3D EINVAL)
@@ -849,7 +856,7 @@
=20
 #ifdef  STREAMSPTY
     ttyfd =3D t;
-	 =20
+
=20
     /*
      * Not all systems have (or need) modules ttcompat and pckt so
@@ -869,7 +876,7 @@
 	       pushed (via autopush, for instance).
=20
 	       */
-	    =20
+
 	    char *ttymodules[] =3D { "ttcompat", "ldterm", "ptem", NULL };
 	    char *ptymodules[] =3D { "pckt", NULL };
=20
@@ -1008,8 +1015,10 @@
=20
 int login_tty(int t)
 {
+    /* Dont need to set this as the controlling PTY on steams sockets,
+     * don't abort on failure. */
 # if defined(TIOCSCTTY) && !defined(__hpux)
-    if (ioctl(t, TIOCSCTTY, (char *)0) < 0)
+    if (ioctl(t, TIOCSCTTY, (char *)0) < 0 && !really_stream)
 	fatalperror(net, "ioctl(sctty)");
 #  ifdef _CRAY
     /*
@@ -1081,7 +1090,7 @@
 make_id (char *tty)
 {
   char *res =3D tty;
- =20
+
   if (strncmp (res, "pts/", 4) =3D=3D 0)
     res +=3D 4;
   if (strncmp (res, "tty", 3) =3D=3D 0)
@@ -1177,7 +1186,9 @@
 }
=20
 char	*envinit[3];
+#if !HAVE_DECL_ENVIRON
 extern char **environ;
+#endif
=20
 void
 init_env(void)
@@ -1223,7 +1234,7 @@
=20
     char **cpp, **cpp2;
     const char **p;
- =20
+
     for (cpp2 =3D cpp =3D environ; *cpp; cpp++) {
 	int reject_it =3D 0;
=20
@@ -1271,18 +1282,18 @@
     encrypt_output =3D NULL;
     decrypt_input =3D NULL;
 #endif
-   =20
+
 #ifdef HAVE_UTMPX_H
     {
 	int pid =3D getpid();
 	struct utmpx utmpx;
 	struct timeval tv;
 	char *clean_tty;
-=09
+
 	/*
 	 * Create utmp entry for child
 	 */
-=09
+
 	clean_tty =3D clean_ttyname(line);
 	memset(&utmpx, 0, sizeof(utmpx));
 	strncpy(utmpx.ut_user,  ".telnet", sizeof(utmpx.ut_user));
@@ -1291,9 +1302,9 @@
 	strncpy(utmpx.ut_id, make_id(clean_tty), sizeof(utmpx.ut_id));
 #endif
 	utmpx.ut_pid =3D pid;
-=09
+
 	utmpx.ut_type =3D LOGIN_PROCESS;
-=09
+
 	gettimeofday (&tv, NULL);
 	utmpx.ut_tv.tv_sec =3D tv.tv_sec;
 	utmpx.ut_tv.tv_usec =3D tv.tv_usec;
@@ -1304,7 +1315,7 @@
 #endif
=20
     scrub_env();
-=09
+
     /*
      * -h : pass on name of host.
      *		WARNING:  -h is accepted by login if and only if
@@ -1314,7 +1325,7 @@
      * -f : force this login, he has already been authenticated
      */
=20
-    /* init argv structure */=20
+    /* init argv structure */
     argv.size=3D0;
     argv.argc=3D0;
     argv.argv=3Dmalloc(0); /*so we can call realloc later */
@@ -1322,7 +1333,7 @@
     addarg(&argv, "-h");
     addarg(&argv, host);
     addarg(&argv, "-p");
-    if(name[0])
+    if(name && name[0])
 	user =3D name;
     else
 	user =3D getenv("USER");
@@ -1339,8 +1350,8 @@
 	    addarg(&argv, "-a");
 	    addarg(&argv, "otp");
 	}
-	if(log_unauth)=20
-	    syslog(LOG_INFO, "unauthenticated access from %s (%s)",=20
+	if(log_unauth)
+	    syslog(LOG_INFO, "unauthenticated access from %s (%s)",
 		   host, user ? user : "unknown user");
     }
     if (auth_level >=3D 0 && autologin =3D=3D AUTH_VALID)
@@ -1433,7 +1444,7 @@
 #elif defined(__osf__) /* XXX */
 	utxp->ut_exit.ut_termination =3D 0;
 	utxp->ut_exit.ut_exit =3D 0;
-#else=09
+#else
 	utxp->ut_exit.e_termination =3D 0;
 	utxp->ut_exit.e_exit =3D 0;
 #endif
@@ -1585,7 +1596,7 @@
     int t;
     int child_status; /* status of child process as returned by waitpid */
     int flags =3D WNOHANG|WUNTRACED;
-   =20
+
     /*
      * 1: Pick up the zombie, if we are being called
      *    as the signal handler.
@@ -1613,7 +1624,7 @@
     }
     incleanup =3D 1;
     sigsetmask(t);
-   =20
+
     t =3D cleantmp(&wtmp);
     setutent();	/* just to make sure */
 #endif /* CRAY */
@@ -1641,7 +1652,7 @@
 #endif
 #else
     char *p;
-   =20
+
     p =3D line + sizeof("/dev/") - 1;
     if (logout(p))
 	logwtmp(p, "", "");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/telnetd.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/telnetd.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/telnetd.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnetd.h"
=20
-RCSID("$Id: telnetd.c 21748 2007-07-31 18:57:20Z lha $");
+RCSID("$Id$");
=20
 #ifdef _SC_CRAY_SECURE_SYS
 #include <sys/sysv.h>
@@ -338,7 +338,7 @@
 	case 'L':
 	    new_login =3D optarg;
 	    break;
-		=09
+
 	default:
 	    fprintf(stderr, "telnetd: %c: unknown option\n", ch);
 	    /* FALLTHROUGH */
@@ -370,7 +370,7 @@
 	    port =3D k_getportbyname("telnet", "tcp", htons(23));
 #endif
 	}
-	mini_inetd (port);
+	mini_inetd (port, NULL);
     } else if (argc > 0) {
 	usage(1);
 	/* NOT REACHED */
@@ -389,7 +389,7 @@
=20
 	memset(&dv, 0, sizeof(dv));
=20
-	if (getsysv(&sysv, sizeof(struct sysv)) !=3D 0)=20
+	if (getsysv(&sysv, sizeof(struct sysv)) !=3D 0)
 	    fatalperror(net, "getsysv");
=20
 	/*
@@ -400,7 +400,7 @@
 	if ((getsockopt(0, SOL_SOCKET, SO_SECURITY,
 			(void *)&ss, &szss) < 0) ||
 	    (getsockopt(0, SOL_SOCKET, SO_SEC_MULTI,
-			(void *)&sock_multi, &szi) < 0))=20
+			(void *)&sock_multi, &szi) < 0))
 	    fatalperror(net, "getsockopt");
 	else {
 	    dv.dv_actlvl =3D ss.ss_actlabel.lt_level;
@@ -724,7 +724,7 @@
     error =3D getnameinfo_verified (who, who_len,
 				  remote_host_name,
 				  sizeof(remote_host_name),
-				  NULL, 0,=20
+				  NULL, 0,
 				  registerd_host_only ? NI_NAMEREQD : 0);
     if (error)
 	fatal(net, "Couldn't resolve your address into a host name.\r\n\
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/telnetd.h
--- a/head/crypto/heimdal/appl/telnet/telnetd/telnetd.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/telnetd.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -189,10 +189,6 @@
 struct hostent  *gethostbyname(const char *);
 #endif
=20
-#ifdef KRB4
-#include <krb.h>
-#endif
-
 #ifdef AUTHENTICATION
 #include <libtelnet/auth.h>
 #include <libtelnet/misc.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/termstat.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/termstat.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/termstat.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -33,7 +33,7 @@
=20
 #include "telnetd.h"
=20
-RCSID("$Id: termstat.c 10587 2001-08-29 00:45:23Z assar $");
+RCSID("$Id$");
=20
 /*
  * local variables
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/telnet/telnet=
d/utility.c
--- a/head/crypto/heimdal/appl/telnet/telnetd/utility.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/appl/telnet/telnetd/utility.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -34,7 +34,7 @@
 #define PRINTOPTIONS
 #include "telnetd.h"
=20
-RCSID("$Id: utility.c 15844 2005-08-08 13:36:16Z lha $");
+RCSID("$Id$");
=20
 /*
  * utility functions performing io related tasks
@@ -116,7 +116,7 @@
     int n;
=20
     if ((n =3D pfrontp - pbackp) > 0) {
-	DIAG((TD_REPORT | TD_PTYDATA), {=20
+	DIAG((TD_REPORT | TD_PTYDATA), {
 	    output_data("td: ptyflush %d chars\r\n", n);
 	});
 	DIAG(TD_PTYDATA, printdata("pd", pbackp, n));
@@ -367,7 +367,7 @@
 fatalperror_errno(int f, const char *msg, int error)
 {
     char buf[BUFSIZ];
-   =20
+
     snprintf(buf, sizeof(buf), "%s: %s", msg, strerror(error));
     fatal(f, buf);
 }
@@ -445,10 +445,10 @@
     char db[100];
=20
     /* if we don't have uname, set these to sensible values */
-    char *sysname =3D "Unix",=20
-	*machine =3D "",=20
+    char *sysname =3D "Unix",
+	*machine =3D "",
 	*release =3D "",
-	*version =3D "";=20
+	*version =3D "";
=20
 #ifdef HAVE_UNAME
     uname(&name);
@@ -532,7 +532,7 @@
 }
=20
 void
-printsub(int direction, unsigned char *pointer, int length)
+printsub(int direction, unsigned char *pointer, size_t length)
         		          	/* '<' or '>' */
                  	         	/* where suboption data sits */
        			       		/* length of suboption data */
@@ -587,7 +587,7 @@
 	switch (pointer[1]) {
 	case TELQUAL_IS:
 	    output_data("IS \"%.*s\"",
-			length-2,
+			(int)(length-2),
 			(char *)pointer+2);
 	    break;
 	case TELQUAL_SEND:
@@ -606,7 +606,7 @@
 	}
 	switch (pointer[1]) {
 	case TELQUAL_IS:
-	    output_data(" IS %.*s", length-2, (char *)pointer+2);
+	    output_data(" IS %.*s", (int)(length-2), (char *)pointer+2);
 	    break;
 	default:
 	    if (pointer[1] =3D=3D 1)
@@ -884,7 +884,7 @@
 	switch (pointer[1]) {
 	case TELQUAL_IS:
 	    output_data("IS \"%.*s\"",
-			length-2,
+			(int)(length-2),
 			(char *)pointer+2);
 	    break;
 	case TELQUAL_SEND:
@@ -913,46 +913,53 @@
 	    output_data("INFO ");
 	env_common:
 	    {
-		int noquote =3D 2;
+		int quote =3D 0;
 		for (i =3D 2; i < length; i++ ) {
 		    switch (pointer[i]) {
 		    case NEW_ENV_VAR:
-			output_data("\" VAR " + noquote);
-			noquote =3D 2;
+			if (quote)
+			    output_data("\" ");
+			output_data("VAR ");
+			quote =3D 0;
 			break;
=20
 		    case NEW_ENV_VALUE:
-			output_data("\" VALUE " + noquote);
-			noquote =3D 2;
+			if (quote)
+			    output_data("\" ");
+			output_data("VALUE ");
+			quote =3D 0;
 			break;
=20
 		    case ENV_ESC:
-			output_data("\" ESC " + noquote);
-			noquote =3D 2;
+			if (quote)
+			    output_data("\" ");
+			output_data("ESC ");
+			quote =3D 0;
 			break;
=20
 		    case ENV_USERVAR:
-			output_data("\" USERVAR " + noquote);
-			noquote =3D 2;
+			if (quote)
+			    output_data("\" ");
+			output_data("USERVAR ");
+			quote =3D 0;
 			break;
=20
 		    default:
 			if (isprint(pointer[i]) && pointer[i] !=3D '"') {
-			    if (noquote) {
-				output_data ("\"");
-				noquote =3D 0;
+			    if (!quote) {
+				output_data("\"");
+				quote =3D 1;
 			    }
-			    output_data ("%c", pointer[i]);
+			    output_data("%c", pointer[i]);
 			} else {
-			    output_data("\" %03o " + noquote,
-					pointer[i]);
-			    noquote =3D 2;
+			    output_data("%03o ", pointer[i]);
+			    quote =3D 0;
 			}
 			break;
 		    }
 		}
-		if (!noquote)
-		    output_data ("\"");
+		if (quote)
+		    output_data("\"");
 		break;
 	    }
 	}
@@ -1019,7 +1026,7 @@
 	case TELQUAL_NAME:
 	    i =3D 2;
 	    output_data(" NAME \"%.*s\"",
-			length - 2,
+			(int)(length - 2),
 			pointer);
 	    break;
=20
@@ -1130,9 +1137,9 @@
  * Dump a data buffer in hex and ascii to the output data stream.
  */
 void
-printdata(char *tag, char *ptr, int cnt)
+printdata(char *tag, char *ptr, size_t cnt)
 {
-    int i;
+    size_t i;
     char xbuf[30];
=20
     while (cnt) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/Makefile=
.am
--- a/head/crypto/heimdal/appl/test/Makefile.am	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/test/Makefile.am	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -40,3 +40,5 @@
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
+
+EXTRA_DIST =3D NTMakefile
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/Makefile=
.in
--- a/head/crypto/heimdal/appl/test/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/test/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -48,7 +50,7 @@
 subdir =3D appl/test
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -63,7 +65,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -77,9 +79,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -87,12 +92,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 PROGRAMS =3D $(noinst_PROGRAMS)
 am_gssapi_client_OBJECTS =3D gssapi_client.$(OBJEXT) \
 	gss_common.$(OBJEXT) common.$(OBJEXT)
@@ -147,9 +153,9 @@
 uu_server_DEPENDENCIES =3D $(top_builddir)/lib/krb5/libkrb5.la \
 	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
 	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -176,49 +182,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -242,10 +257,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -262,6 +278,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -277,31 +295,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -316,10 +348,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -360,29 +394,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 tcp_client_SOURCES =3D tcp_client.c common.c test_locl.h
 tcp_server_SOURCES =3D tcp_server.c common.c test_locl.h
@@ -409,22 +448,23 @@
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
+EXTRA_DIST =3D NTMakefile
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps appl/test=
/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps appl/test/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign appl/test/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign appl/test/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -442,13 +482,16 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 gssapi_client$(EXEEXT): $(gssapi_client_OBJECTS) $(gssapi_client_DEPENDENC=
IES)=20
 	@rm -f gssapi_client$(EXEEXT)
 	$(LINK) $(gssapi_client_OBJECTS) $(gssapi_client_LDADD) $(LIBS)
@@ -483,14 +526,39 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/common.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gss_common.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gssapi_client.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gssapi_server.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/http_client.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/nt_gss_client.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/nt_gss_common.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/nt_gss_server.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/tcp_client.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/tcp_server.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/uu_client.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/uu_server.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -503,45 +571,49 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -562,13 +634,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -600,6 +676,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -610,6 +687,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -620,6 +698,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -627,26 +707,35 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -666,9 +755,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libtool clean-noinstPROGRAMS ctags \
@@ -753,6 +841,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -838,7 +929,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -851,6 +942,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/common.c
--- a/head/crypto/heimdal/appl/test/common.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/appl/test/common.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
=20
-RCSID("$Id: common.c 12796 2003-09-09 03:38:04Z lha $");
+RCSID("$Id$");
=20
 static int help_flag;
 static int version_flag;
@@ -43,12 +43,14 @@
 char *service =3D SERVICE;
 char *mech =3D "krb5";
 int fork_flag;
+char *password =3D NULL;
=20
 static struct getargs args[] =3D {
     { "port", 'p', arg_string, &port_str, "port to listen to", "port" },
     { "service", 's', arg_string, &service, "service to use", "service" },
     { "keytab", 'k', arg_string, &keytab_str, "keytab to use", "keytab" },
     { "mech", 'm', arg_string, &mech, "gssapi mech to use", "mech" },
+    { "password", 'P', arg_string, &password, "password to use", "password=
" },
     { "fork", 'f', arg_flag, &fork_flag, "do fork" },
     { "help", 'h', arg_flag, &help_flag },
     { "version", 0, arg_flag, &version_flag }
@@ -72,7 +74,7 @@
=20
=20
 static int
-common_setup(krb5_context *context, int *argc, char **argv,=20
+common_setup(krb5_context *context, int *argc, char **argv,
 	     void (*usage)(int, struct getargs*, int))
 {
     int port =3D 0;
@@ -84,7 +86,7 @@
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     if(port_str){
 	struct servent *s =3D roken_getservbyname(port_str, "tcp");
 	if(s)
@@ -101,7 +103,7 @@
=20
     if (port =3D=3D 0)
 	port =3D krb5_getportbyname (*context, PORT, "tcp", 4711);
-   =20
+
     return port;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/gss_comm=
on.c
--- a/head/crypto/heimdal/appl/test/gss_common.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/test/gss_common.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,42 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
+#include <gssapi/gssapi_spnego.h>
 #include "gss_common.h"
-RCSID("$Id: gss_common.c 19937 2007-01-16 21:56:01Z lha $");
+RCSID("$Id$");
=20
 void
 write_token (int sock, gss_buffer_t buf)
@@ -93,7 +95,7 @@
 				  GSS_C_NO_OID,
 				  &msg_ctx,
 				  &status_string);
-	fprintf (stderr, "%.*s\n", (int)status_string.length,=20
+	fprintf (stderr, "%.*s\n", (int)status_string.length,
 		 (char *)status_string.value);
 	gss_release_buffer (&new_stat, &status_string);
     } while (!GSS_ERROR(ret) && msg_ctx !=3D 0);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/gss_comm=
on.h
--- a/head/crypto/heimdal/appl/test/gss_common.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/test/gss_common.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: gss_common.h 14661 2005-03-19 03:13:14Z lha $ */
+/* $Id$ */
=20
 void write_token (int sock, gss_buffer_t buf);
 void read_token (int sock, gss_buffer_t buf);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/gssapi_c=
lient.c
--- a/head/crypto/heimdal/appl/test/gssapi_client.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/test/gssapi_client.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,40 +1,42 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
+#include <gssapi/gssapi_spnego.h>
 #include "gss_common.h"
-RCSID("$Id: gssapi_client.c 21521 2007-07-12 13:13:40Z lha $");
+RCSID("$Id$");
=20
 static int
 do_trans (int sock, gss_ctx_id_t context_hdl)
@@ -92,21 +94,23 @@
     return 0;
 }
=20
+extern char *password;
+
 static int
 proto (int sock, const char *hostname, const char *service)
 {
-    struct sockaddr_in remote, local;
+    struct sockaddr_storage remote, local;
     socklen_t addrlen;
=20
     int context_established =3D 0;
     gss_ctx_id_t context_hdl =3D GSS_C_NO_CONTEXT;
+    gss_cred_id_t cred =3D GSS_C_NO_CREDENTIAL;
     gss_buffer_desc real_input_token, real_output_token;
     gss_buffer_t input_token =3D &real_input_token,
 	output_token =3D &real_output_token;
     OM_uint32 maj_stat, min_stat;
     gss_name_t server;
     gss_buffer_desc name_token;
-    struct gss_channel_bindings_struct input_chan_bindings;
     u_char init_buf[4];
     u_char acct_buf[4];
     gss_OID mech_oid;
@@ -119,7 +123,7 @@
     if (str =3D=3D NULL)
 	errx(1, "malloc - out of memory");
     name_token.value =3D str;
-=09
+
     maj_stat =3D gss_import_name (&min_stat,
 				&name_token,
 				GSS_C_NT_HOSTBASED_SERVICE,
@@ -128,19 +132,42 @@
 	gss_err (1, min_stat,
 		 "Error importing name `%s@%s':\n", service, hostname);
=20
+    if (password) {
+        gss_buffer_desc pw;
+
+        pw.value =3D password;
+        pw.length =3D strlen(password);
+
+        maj_stat =3D gss_acquire_cred_with_password(&min_stat,
+						  GSS_C_NO_NAME,
+						  &pw,
+						  GSS_C_INDEFINITE,
+						  GSS_C_NO_OID_SET,
+						  GSS_C_INITIATE,
+						  &cred,
+						  NULL,
+						  NULL);
+        if (GSS_ERROR(maj_stat))
+            gss_err (1, min_stat,
+                     "Error acquiring default initiator credentials");
+    }
+
     addrlen =3D sizeof(local);
     if (getsockname (sock, (struct sockaddr *)&local, &addrlen) < 0
-	|| addrlen !=3D sizeof(local))
+	|| addrlen > sizeof(local))
 	err (1, "getsockname(%s)", hostname);
=20
     addrlen =3D sizeof(remote);
     if (getpeername (sock, (struct sockaddr *)&remote, &addrlen) < 0
-	|| addrlen !=3D sizeof(remote))
+	|| addrlen > sizeof(remote))
 	err (1, "getpeername(%s)", hostname);
=20
     input_token->length =3D 0;
     output_token->length =3D 0;
=20
+#if 0
+    struct gss_channel_bindings_struct input_chan_bindings;
+
     input_chan_bindings.initiator_addrtype =3D GSS_C_AF_INET;
     input_chan_bindings.initiator_address.length =3D 4;
     init_buf[0] =3D (local.sin_addr.s_addr >> 24) & 0xFF;
@@ -156,13 +183,12 @@
     acct_buf[2] =3D (remote.sin_addr.s_addr >>  8) & 0xFF;
     acct_buf[3] =3D (remote.sin_addr.s_addr >>  0) & 0xFF;
     input_chan_bindings.acceptor_address.value =3D acct_buf;
-   =20
-#if 0
+
     input_chan_bindings.application_data.value =3D emalloc(4);
     * (unsigned short*)input_chan_bindings.application_data.value =3D loca=
l.sin_port;
     * ((unsigned short *)input_chan_bindings.application_data.value + 1) =
=3D remote.sin_port;
     input_chan_bindings.application_data.length =3D 4;
-#else
+
     input_chan_bindings.application_data.length =3D 0;
     input_chan_bindings.application_data.value =3D NULL;
 #endif
@@ -170,14 +196,13 @@
     while(!context_established) {
 	maj_stat =3D
 	    gss_init_sec_context(&min_stat,
-				 GSS_C_NO_CREDENTIAL,
+				 cred,
 				 &context_hdl,
 				 server,
 				 mech_oid,
-				 GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG
-				 | GSS_C_DELEG_FLAG,
+				 GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG,
 				 0,
-				 &input_chan_bindings,
+				 NULL,
 				 input_token,
 				 NULL,
 				 output_token,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/gssapi_s=
erver.c
--- a/head/crypto/heimdal/appl/test/gssapi_server.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/test/gssapi_server.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,40 +1,42 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
+#include <gssapi/gssapi_spnego.h>
 #include "gss_common.h"
-RCSID("$Id: gssapi_server.c 14762 2005-04-10 14:47:41Z lha $");
+RCSID("$Id$");
=20
 static int
 process_it(int sock,
@@ -185,9 +187,9 @@
     input_chan_bindings.application_data.length =3D 0;
     input_chan_bindings.application_data.value =3D NULL;
 #endif
-   =20
+
     delegated_cred_handle =3D GSS_C_NO_CREDENTIAL;
-   =20
+
     do {
 	read_token (sock, input_token);
 	maj_stat =3D
@@ -214,7 +216,7 @@
 	    break;
 	}
     } while(maj_stat & GSS_S_CONTINUE_NEEDED);
-   =20
+
     p =3D (char *)mech_oid->elements;
     if (mech_oid->length =3D=3D GSS_KRB5_MECHANISM->length
 	&& memcmp(p, GSS_KRB5_MECHANISM->elements, mech_oid->length) =3D=3D 0)
@@ -298,6 +300,7 @@
     int sock, sock2;
     struct sockaddr_in my_addr;
     int one =3D 1;
+    int ret;
=20
     sock =3D socket (AF_INET, SOCK_STREAM, 0);
     if (sock < 0)
@@ -315,14 +318,17 @@
     if (bind (sock, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0)
 	err (1, "bind");
=20
-    if (listen (sock, 1) < 0)
-	err (1, "listen");
+    while (1) {
+        if (listen (sock, 1) < 0)
+	    err (1, "listen");
=20
-    sock2 =3D accept (sock, NULL, NULL);
-    if (sock2 < 0)
-	err (1, "accept");
+        sock2 =3D accept (sock, NULL, NULL);
+        if (sock2 < 0)
+	    err (1, "accept");
=20
-    return proto (sock2, service);
+        ret =3D proto (sock2, service);
+    }
+    return ret;
 }
=20
 int
@@ -332,3 +338,4 @@
     int port =3D server_setup(&context, argc, argv);
     return doit (port, service);
 }
+
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/http_cli=
ent.c
--- a/head/crypto/heimdal/appl/test/http_client.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/appl/test/http_client.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,42 +1,44 @@
 /*
- * Copyright (c) 2003 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
+#include <gssapi/gssapi_spnego.h>
 #include "gss_common.h"
 #include <base64.h>
=20
-RCSID("$Id: http_client.c 14861 2005-04-20 10:38:37Z lha $");
+RCSID("$Id$");
=20
 /*
  * A simplistic client implementing draft-brezak-spnego-http-04.txt
@@ -84,7 +86,7 @@
     ssize_t ret;
     va_list ap;
     char *str, *buf;
-   =20
+
     va_start(ap, fmt);
     vasprintf(&str, fmt, ap);
     va_end(ap);
@@ -186,7 +188,7 @@
=20
=20
 static int
-http_query(const char *host, const char *page,=20
+http_query(const char *host, const char *page,
 	   char **headers, int num_headers, struct http_req *req)
 {
     enum { RESPONSE, HEADER, BODY } state;
@@ -214,7 +216,7 @@
 	    break;
 	else if (ret < 0)
 	    err (1, "read: %lu", (unsigned long)ret);
-=09
+
 	in_buf[ret + in_len] =3D '\0';
=20
 	if (state =3D=3D HEADER || state =3D=3D RESPONSE) {
@@ -235,12 +237,16 @@
 		    in_ptr -=3D 2;
 		    break;
 		} else if (state =3D=3D RESPONSE) {
-		    req->response =3D strndup(in_buf, p - in_buf);
+		    req->response =3D emalloc(p - in_buf + 1);
+		    memcpy(req->response, in_buf, p - in_buf);
+		    req->response[p - in_buf] =3D '\0';
 		    state =3D HEADER;
 		} else {
 		    req->headers =3D realloc(req->headers,
 					   (req->num_headers + 1) * sizeof(req->headers[0]));
-		    req->headers[req->num_headers] =3D strndup(in_buf, p - in_buf);
+		    req->headers[req->num_headers] =3D emalloc(p - in_buf + 1);
+		    memcpy(req->headers[req->num_headers], in_buf, p - in_buf);
+		    req->headers[req->num_headers][p - in_buf] =3D '\0';
 		    if (req->headers[req->num_headers] =3D=3D NULL)
 			errx(1, "strdup");
 		    req->num_headers++;
@@ -332,7 +338,7 @@
 	print_body =3D 0;
=20
 	http_query(host, page, headers, num_headers, &req);
-	for (i =3D 0 ; i < num_headers; i++)=20
+	for (i =3D 0 ; i < num_headers; i++)
 	    free(headers[i]);
 	num_headers =3D 0;
=20
@@ -356,7 +362,7 @@
=20
 		if (verbose_flag)
 		    printf("Negotiate found\n");
-	=09
+
 		if (server =3D=3D GSS_C_NO_NAME) {
 		    char *name;
 		    asprintf(&name, "%s@%s", gss_service, host);
@@ -468,7 +474,7 @@
 		    base64_encode(output_token.value,
 				  output_token.length,
 				  &neg_token);
-		   =20
+
 		    asprintf(&headers[0], "Authorization: Negotiate %s",
 			     neg_token);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/nt_gss_c=
lient.c
--- a/head/crypto/heimdal/appl/test/nt_gss_client.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/test/nt_gss_client.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
 #include <gssapi.h>
 #include "nt_gss_common.h"
=20
-RCSID("$Id: nt_gss_client.c 21522 2007-07-12 13:15:04Z lha $");
+RCSID("$Id$");
=20
 /*
  * This program tries to act as a client for the sample in `Sample
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/nt_gss_c=
ommon.c
--- a/head/crypto/heimdal/appl/test/nt_gss_common.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/test/nt_gss_common.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
 #include <gssapi.h>
 #include "nt_gss_common.h"
=20
-RCSID("$Id: nt_gss_common.c 17450 2006-05-05 11:11:43Z lha $");
+RCSID("$Id$");
=20
 /*
  * These are functions that are needed to interoperate with the
@@ -43,7 +43,7 @@
  */
=20
 /*
- * Write the `gss_buffer_t' in `buf' onto the fd `sock', but remember that=20
+ * Write the `gss_buffer_t' in `buf' onto the fd `sock', but remember that
  * the length is written in little-endian-order.
  */
=20
@@ -107,7 +107,9 @@
 				  GSS_C_NO_OID,
 				  &msg_ctx,
 				  &status_string);
-	fprintf (stderr, "%s\n", (char *)status_string.value);
+	fprintf (stderr, "%.*s\n",
+		(int)status_string.length,
+		(char *)status_string.value);
 	gss_release_buffer (&new_stat, &status_string);
     } while (!GSS_ERROR(ret) && msg_ctx !=3D 0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/nt_gss_c=
ommon.h
--- a/head/crypto/heimdal/appl/test/nt_gss_common.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/test/nt_gss_common.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: nt_gss_common.h 7464 1999-12-02 17:05:13Z joda $ */
+/* $Id$ */
=20
 void nt_write_token (int sock, gss_buffer_t buf);
 void nt_read_token (int sock, gss_buffer_t buf);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/nt_gss_s=
erver.c
--- a/head/crypto/heimdal/appl/test/nt_gss_server.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/appl/test/nt_gss_server.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,42 +1,44 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-#include <gssapi.h>
+#include <gssapi/gssapi.h>
+#include <gssapi/gssapi_krb5.h>
+#include <gssapi/gssapi_spnego.h>
 #include <krb5.h>
 #include "nt_gss_common.h"
=20
-RCSID("$Id: nt_gss_server.c 12323 2003-05-21 15:15:34Z lha $");
+RCSID("$Id$");
=20
 /*
  * This program tries to act as a server for the sample in `Sample
@@ -115,21 +117,16 @@
     } while(maj_stat & GSS_S_CONTINUE_NEEDED);
=20
     if (auth_file !=3D NULL) {
-	int fd =3D open (auth_file, O_WRONLY | O_CREAT, 0666);
-#if 0
-	krb5_ticket *ticket;
-	krb5_data *data;
+	gss_buffer_desc data;
=20
-	ticket =3D context_hdl->ticket;
-	data =3D &ticket->ticket.authorization_data->val[0].ad_data;
-
-	if(fd < 0)
-	    err (1, "open %s", auth_file);
-	if (write (fd, data->data, data->length) !=3D data->length)
-	    errx (1, "write to %s failed", auth_file);
-#endif
-	if (close (fd))
-	    err (1, "close %s", auth_file);
+	maj_stat =3D gsskrb5_extract_authz_data_from_sec_context(&min_stat,
+							       context_hdl,
+							       KRB5_AUTHDATA_WIN2K_PAC,
+							       &data);
+	if (maj_stat =3D=3D GSS_S_COMPLETE) {
+	    rk_dumpdata(auth_file, data.value, data.length);
+	    gss_release_buffer(&min_stat, &data);
+	}
     }
=20
     maj_stat =3D gss_display_name (&min_stat,
@@ -196,7 +193,7 @@
 }
=20
 static int
-common_setup(krb5_context *context, int *argc, char **argv,=20
+common_setup(krb5_context *context, int *argc, char **argv,
 	     void (*usage)(int, struct getargs*, int))
 {
     int port =3D 0;
@@ -208,7 +205,7 @@
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     if(port_str){
 	struct servent *s =3D roken_getservbyname(port_str, "tcp");
 	if(s)
@@ -225,7 +222,7 @@
=20
     if (port =3D=3D 0)
 	port =3D krb5_getportbyname (*context, PORT, "tcp", 4711);
-   =20
+
     return port;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/tcp_clie=
nt.c
--- a/head/crypto/heimdal/appl/test/tcp_client.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/test/tcp_client.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-RCSID("$Id: tcp_client.c 17450 2006-05-05 11:11:43Z lha $");
+RCSID("$Id$");
=20
 krb5_context context;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/tcp_serv=
er.c
--- a/head/crypto/heimdal/appl/test/tcp_server.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/appl/test/tcp_server.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-RCSID("$Id: tcp_server.c 17954 2006-09-01 09:01:03Z lha $");
+RCSID("$Id$");
=20
 krb5_context context;
=20
@@ -110,7 +110,7 @@
 	krb5_errx (context, 1, "EOF in krb5_net_read");
     if (n < 0)
 	krb5_err (context, 1, errno, "krb5_net_read");
-   =20
+
     status =3D krb5_rd_safe (context,
 			   auth_context,
 			   &packet,
@@ -137,7 +137,7 @@
 	krb5_errx (context, 1, "EOF in krb5_net_read");
     if (n < 0)
 	krb5_err (context, 1, errno, "krb5_net_read");
-   =20
+
     status =3D krb5_rd_priv (context,
 			   auth_context,
 			   &packet,
@@ -155,7 +155,7 @@
 static int
 doit (int port, const char *service)
 {
-    mini_inetd (port);
+    mini_inetd (port, NULL);
=20
     return proto (STDIN_FILENO, service);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/test_loc=
l.h
--- a/head/crypto/heimdal/appl/test/test_locl.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/test/test_locl.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: test_locl.h 12797 2003-09-09 03:38:51Z lha $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/uu_clien=
t.c
--- a/head/crypto/heimdal/appl/test/uu_client.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/test/uu_client.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-RCSID("$Id: uu_client.c 14719 2005-04-03 19:53:32Z lha $");
+RCSID("$Id$");
=20
 krb5_context context;
=20
@@ -95,14 +95,14 @@
     if(status)
 	krb5_err(context, 1, status, "krb5_cc_get_principal");
     status =3D krb5_make_principal(context, &mcred.server,
-				 *krb5_princ_realm(context, client),=20
-				 "krbtgt",=20
-				 *krb5_princ_realm(context, client),
+				 krb5_principal_get_realm(context, client),
+				 "krbtgt",
+				 krb5_principal_get_realm(context, client),
 				 NULL);
     if(status)
 	krb5_err(context, 1, status, "krb5_make_principal");
     mcred.client =3D client;
-   =20
+
     status =3D krb5_cc_retrieve_cred(context, ccache, 0, &mcred, &cred);
     if(status)
 	krb5_err(context, 1, status, "krb5_cc_retrieve_cred");
@@ -128,13 +128,13 @@
     status =3D krb5_auth_con_setuserkey(context, auth_context, &cred.sessi=
on);
     if(status)
 	krb5_err(context, 1, status, "krb5_auth_con_setuserkey");
-   =20
-    status =3D krb5_recvauth(context, &auth_context, &sock,=20
+
+    status =3D krb5_recvauth(context, &auth_context, &sock,
 			   VERSION, client, 0, NULL, &ticket);
=20
     if (status)
 	krb5_err(context, 1, status, "krb5_recvauth");
-   =20
+
     if (ticket->ticket.authorization_data) {
 	AuthorizationData *authz;
 	int i;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/appl/test/uu_serve=
r.c
--- a/head/crypto/heimdal/appl/test/uu_server.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/appl/test/uu_server.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997 - 2000, 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000, 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "test_locl.h"
-RCSID("$Id: uu_server.c 20880 2007-06-04 16:55:00Z lha $");
+RCSID("$Id$");
=20
 krb5_context context;
=20
@@ -62,8 +62,7 @@
=20
     status =3D krb5_auth_con_init (context, &auth_context);
     if (status)
-	errx (1, "krb5_auth_con_init: %s",
-	      krb5_get_err_text(context, status));
+	krb5_err(context, 1, status, "krb5_auth_con_init");
=20
     local_addr.addr_type =3D AF_INET;
     local_addr.address.length =3D sizeof(local.sin_addr);
@@ -78,16 +77,19 @@
 				     &local_addr,
 				     &remote_addr);
     if (status)
-	errx (1, "krb5_auth_con_setaddr: %s",
-	      krb5_get_err_text(context, status));
+	krb5_err(context, 1, status, "krb5_auth_con_setaddr");
=20
     status =3D krb5_read_message(context, &sock, &client_name);
     if(status)
 	krb5_err(context, 1, status, "krb5_read_message");
-   =20
+
     memset(&in_creds, 0, sizeof(in_creds));
     status =3D krb5_cc_default(context, &ccache);
+    if(status)
+	krb5_err(context, 1, status, "krb5_cc_default");
     status =3D krb5_cc_get_principal(context, ccache, &in_creds.client);
+    if(status)
+	krb5_err(context, 1, status, "krb5_cc_get_principal");
=20
     status =3D krb5_read_message(context, &sock, &in_creds.second_ticket);
     if(status)
@@ -96,18 +98,20 @@
     status =3D krb5_parse_name(context, client_name.data, &in_creds.server=
);
     if(status)
 	krb5_err(context, 1, status, "krb5_parse_name");
-   =20
-    status =3D krb5_get_credentials(context, KRB5_GC_USER_USER, ccache,=20
+
+    status =3D krb5_get_credentials(context, KRB5_GC_USER_USER, ccache,
 				  &in_creds, &out_creds);
     if(status)
 	krb5_err(context, 1, status, "krb5_get_credentials");
=20
     status =3D krb5_cc_default(context, &ccache);
+    if(status)
+	krb5_err(context, 1, status, "krb5_cc_default");
=20
-    status =3D krb5_sendauth(context,=20
+    status =3D krb5_sendauth(context,
 			   &auth_context,
-			   &sock,=20
-			   VERSION,=20
+			   &sock,
+			   VERSION,
 			   in_creds.client,
 			   in_creds.server,
 			   AP_OPTS_USE_SESSION_KEY,
@@ -117,10 +121,10 @@
 			   NULL,
 			   NULL,
 			   NULL);
-			  =20
+
     if (status)
 	krb5_err(context, 1, status, "krb5_sendauth");
-   =20
+
     {
 	char *str;
 	krb5_unparse_name(context, in_creds.server, &str);
@@ -137,15 +141,14 @@
     status =3D krb5_read_message(context, &sock, &packet);
     if(status)
 	krb5_err(context, 1, status, "krb5_read_message");
-   =20
+
     status =3D krb5_rd_safe (context,
 			   auth_context,
 			   &packet,
 			   &data,
 			   NULL);
     if (status)
-	errx (1, "krb5_rd_safe: %s",
-	      krb5_get_err_text(context, status));
+	krb5_err(context, 1, status, "krb5_rd_safe");
=20
     printf ("safe packet: %.*s\n", (int)data.length,
 	    (char *)data.data);
@@ -153,15 +156,14 @@
     status =3D krb5_read_message(context, &sock, &packet);
     if(status)
 	krb5_err(context, 1, status, "krb5_read_message");
-   =20
+
     status =3D krb5_rd_priv (context,
 			   auth_context,
 			   &packet,
 			   &data,
 			   NULL);
     if (status)
-	errx (1, "krb5_rd_priv: %s",
-	      krb5_get_err_text(context, status));
+	krb5_err(context, 1, status, "krb5_rd_priv");
=20
     printf ("priv packet: %.*s\n", (int)data.length,
 	    (char *)data.data);
@@ -185,7 +187,7 @@
     my_addr.sin_port        =3D port;
     my_addr.sin_addr.s_addr =3D INADDR_ANY;
=20
-    if (setsockopt (sock, SOL_SOCKET, SO_REUSEADDR,=20
+    if (setsockopt (sock, SOL_SOCKET, SO_REUSEADDR,
 		    (void *)&one, sizeof(one)) < 0)
 	warn ("setsockopt SO_REUSEADDR");
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/autogen.sh
--- a/head/crypto/heimdal/autogen.sh	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/autogen.sh	Tue Apr 17 11:51:51 2012 +0300
@@ -3,3 +3,4 @@
 # object tree, but this will do if you have all parts of the required
 # tool-chain installed
 autoreconf -f -i || { echo "autoreconf failed: $?"; exit 1; }
+find . \( -name '*-private.h' -o -name '*-protos.h' \) -delete
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/compile
--- a/head/crypto/heimdal/compile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/compile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,10 @@
 #! /bin/sh
 # Wrapper for compilers which do not understand `-c -o'.
=20
-scriptversion=3D2005-05-14.22
+scriptversion=3D2009-10-06.20; # UTC
=20
-# Copyright (C) 1999, 2000, 2003, 2004, 2005 Free Software Foundation, Inc.
+# Copyright (C) 1999, 2000, 2003, 2004, 2005, 2009  Free Software
+# Foundation, Inc.
 # Written by Tom Tromey <tromey at cygnus.com>.
 #
 # This program is free software; you can redistribute it and/or modify
@@ -17,8 +18,7 @@
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301=
, USA.
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
=20
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
@@ -103,13 +103,13 @@
 fi
=20
 # Name of file we expect compiler to create.
-cofile=3D`echo "$cfile" | sed -e 's|^.*/||' -e 's/\.c$/.o/'`
+cofile=3D`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'`
=20
 # Create the lock directory.
-# Note: use `[/.-]' here to ensure that we don't use the same name
+# Note: use `[/\\:.-]' here to ensure that we don't use the same name
 # that we are using for the .o file.  Also, base the name on the expected
 # object file name, since that is what matters with a parallel build.
-lockdir=3D`echo "$cofile" | sed -e 's|[/.-]|_|g'`.d
+lockdir=3D`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d
 while true; do
   if mkdir "$lockdir" >/dev/null 2>&1; then
     break
@@ -124,9 +124,9 @@
 ret=3D$?
=20
 if test -f "$cofile"; then
-  mv "$cofile" "$ofile"
+  test "$cofile" =3D "$ofile" || mv "$cofile" "$ofile"
 elif test -f "${cofile}bj"; then
-  mv "${cofile}bj" "$ofile"
+  test "${cofile}bj" =3D "$ofile" || mv "${cofile}bj" "$ofile"
 fi
=20
 rmdir "$lockdir"
@@ -138,5 +138,6 @@
 # eval: (add-hook 'write-file-hooks 'time-stamp)
 # time-stamp-start: "scriptversion=3D"
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-end: "$"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
 # End:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/config.guess
--- a/head/crypto/heimdal/config.guess	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/config.guess	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
-#   Inc.
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
+#   Free Software Foundation, Inc.
=20
-timestamp=3D'2006-07-02'
+timestamp=3D'2009-11-20'
=20
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -27,16 +27,16 @@
 # the same distribution terms that you use for the rest of that program.
=20
=20
-# Originally written by Per Bothner <per at bothner.com>.
-# Please send patches to <config-patches at gnu.org>.  Submit a context
-# diff and a properly formatted ChangeLog entry.
+# Originally written by Per Bothner.  Please send patches (context
+# diff format) to <config-patches at gnu.org> and include a ChangeLog
+# entry.
 #
 # This script attempts to guess a canonical system name similar to
 # config.sub.  If it succeeds, it prints the system name on stdout, and
 # exits with 0.  Otherwise, it exits with 1.
 #
-# The plan is that this can be called by configure scripts if you
-# don't specify an explicit build system type.
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=3Dconfig.git;a=3Dblob_plain;f=3Dco=
nfig.guess;hb=3DHEAD
=20
 me=3D`echo "$0" | sed -e 's,.*/,,'`
=20
@@ -56,8 +56,8 @@
 GNU config.guess ($timestamp)
=20
 Originally written by Per Bothner.
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, =
2002, 2003, 2004, 2005
-Free Software Foundation, Inc.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
=20
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE=
."
@@ -161,6 +161,7 @@
 	    arm*) machine=3Darm-unknown ;;
 	    sh3el) machine=3Dshl-unknown ;;
 	    sh3eb) machine=3Dsh-unknown ;;
+	    sh5el) machine=3Dsh5le-unknown ;;
 	    *) machine=3D${UNAME_MACHINE_ARCH}-unknown ;;
 	esac
 	# The Operating System including object format, if it has switched
@@ -169,7 +170,7 @@
 	    arm*|i386|m68k|ns32k|sh3*|sparc|vax)
 		eval $set_cc_for_build
 		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
-			| grep __ELF__ >/dev/null
+			| grep -q __ELF__
 		then
 		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout=
).
 		    # Return netbsd for either.  FIX?
@@ -323,14 +324,33 @@
 	case `/usr/bin/uname -p` in
 	    sparc) echo sparc-icl-nx7; exit ;;
 	esac ;;
+    s390x:SunOS:*:*)
+	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*/=
/'`
+	exit ;;
     sun4H:SunOS:5.*:*)
 	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
 	exit ;;
     sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
 	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
 	exit ;;
-    i86pc:SunOS:5.*:*)
-	echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+	echo i386-pc-auroraux${UNAME_RELEASE}
+	exit ;;
+    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+	eval $set_cc_for_build
+	SUN_ARCH=3D"i386"
+	# If there is a compiler, see if it is configured for 64-bit objects.
+	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+	# This test works for both compilers.
+	if [ "$CC_FOR_BUILD" !=3D 'no_compiler_found' ]; then
+	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+		(CCOPTS=3D $CC_FOR_BUILD -E - 2>/dev/null) | \
+		grep IS_64BIT_ARCH >/dev/null
+	    then
+		SUN_ARCH=3D"x86_64"
+	    fi
+	fi
+	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
 	exit ;;
     sun4*:SunOS:6*:*)
 	# According to config.sub, this is the proper way to canonicalize
@@ -531,7 +551,7 @@
 		echo rs6000-ibm-aix3.2
 	fi
 	exit ;;
-    *:AIX:*:[45])
+    *:AIX:*:[456])
 	IBM_CPU_ID=3D`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk=
 '{ print $1 }'`
 	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; th=
en
 		IBM_ARCH=3Drs6000
@@ -639,7 +659,7 @@
 	    # =3D> hppa64-hp-hpux11.23
=20
 	    if echo __LP64__ | (CCOPTS=3D $CC_FOR_BUILD -E - 2>/dev/null) |
-		grep __LP64__ >/dev/null
+		grep -q __LP64__
 	    then
 		HP_ARCH=3D"hppa2.0w"
 	    else
@@ -780,7 +800,7 @@
     i*:CYGWIN*:*)
 	echo ${UNAME_MACHINE}-pc-cygwin
 	exit ;;
-    i*:MINGW*:*)
+    *:MINGW*:*)
 	echo ${UNAME_MACHINE}-pc-mingw32
 	exit ;;
     i*:windows32*:*)
@@ -790,15 +810,24 @@
     i*:PW*:*)
 	echo ${UNAME_MACHINE}-pc-pw32
 	exit ;;
-    x86:Interix*:[3456]*)
-	echo i586-pc-interix${UNAME_RELEASE}
-	exit ;;
-    EM64T:Interix*:[3456]*)
-	echo x86_64-unknown-interix${UNAME_RELEASE}
-	exit ;;
+    *:Interix*:*)
+    	case ${UNAME_MACHINE} in
+	    x86)
+		echo i586-pc-interix${UNAME_RELEASE}
+		exit ;;
+	    authenticamd | genuineintel | EM64T)
+		echo x86_64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	    IA64)
+		echo ia64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	esac ;;
     [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
 	echo i${UNAME_MACHINE}-pc-mks
 	exit ;;
+    8664:Windows_NT:*)
+	echo x86_64-pc-mks
+	exit ;;
     i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
 	# How do we know it's Interix rather than the generic POSIX subsystem?
 	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
@@ -828,8 +857,29 @@
     i*86:Minix:*:*)
 	echo ${UNAME_MACHINE}-pc-minix
 	exit ;;
+    alpha:Linux:*:*)
+	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+	  EV5)   UNAME_MACHINE=3Dalphaev5 ;;
+	  EV56)  UNAME_MACHINE=3Dalphaev56 ;;
+	  PCA56) UNAME_MACHINE=3Dalphapca56 ;;
+	  PCA57) UNAME_MACHINE=3Dalphapca56 ;;
+	  EV6)   UNAME_MACHINE=3Dalphaev6 ;;
+	  EV67)  UNAME_MACHINE=3Dalphaev67 ;;
+	  EV68*) UNAME_MACHINE=3Dalphaev68 ;;
+        esac
+	objdump --private-headers /bin/sh | grep -q ld.so.1
+	if test "$?" =3D 0 ; then LIBC=3D"libc1" ; else LIBC=3D"" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+	exit ;;
     arm*:Linux:*:*)
-	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	eval $set_cc_for_build
+	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+	    | grep -q __ARM_EABI__
+	then
+	    echo ${UNAME_MACHINE}-unknown-linux-gnu
+	else
+	    echo ${UNAME_MACHINE}-unknown-linux-gnueabi
+	fi
 	exit ;;
     avr32*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
@@ -843,6 +893,17 @@
     frv:Linux:*:*)
     	echo frv-unknown-linux-gnu
 	exit ;;
+    i*86:Linux:*:*)
+	LIBC=3Dgnu
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#ifdef __dietlibc__
+	LIBC=3Ddietlibc
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'`
+	echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
+	exit ;;
     ia64:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
 	exit ;;
@@ -852,74 +913,33 @@
     m68*:Linux:*:*)
 	echo ${UNAME_MACHINE}-unknown-linux-gnu
 	exit ;;
-    mips:Linux:*:*)
+    mips:Linux:*:* | mips64:Linux:*:*)
 	eval $set_cc_for_build
 	sed 's/^	//' << EOF >$dummy.c
 	#undef CPU
-	#undef mips
-	#undef mipsel
+	#undef ${UNAME_MACHINE}
+	#undef ${UNAME_MACHINE}el
 	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defin=
ed(MIPSEL)
-	CPU=3Dmipsel
+	CPU=3D${UNAME_MACHINE}el
 	#else
 	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defin=
ed(MIPSEB)
-	CPU=3Dmips
+	CPU=3D${UNAME_MACHINE}
 	#else
 	CPU=3D
 	#endif
 	#endif
 EOF
-	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
-	    /^CPU/{
-		s: ::g
-		p
-	    }'`"
-	test x"${CPU}" !=3D x && { echo "${CPU}-unknown-linux-gnu"; exit; }
-	;;
-    mips64:Linux:*:*)
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#undef CPU
-	#undef mips64
-	#undef mips64el
-	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defin=
ed(MIPSEL)
-	CPU=3Dmips64el
-	#else
-	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defin=
ed(MIPSEB)
-	CPU=3Dmips64
-	#else
-	CPU=3D
-	#endif
-	#endif
-EOF
-	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
-	    /^CPU/{
-		s: ::g
-		p
-	    }'`"
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
 	test x"${CPU}" !=3D x && { echo "${CPU}-unknown-linux-gnu"; exit; }
 	;;
     or32:Linux:*:*)
 	echo or32-unknown-linux-gnu
 	exit ;;
-    ppc:Linux:*:*)
-	echo powerpc-unknown-linux-gnu
+    padre:Linux:*:*)
+	echo sparc-unknown-linux-gnu
 	exit ;;
-    ppc64:Linux:*:*)
-	echo powerpc64-unknown-linux-gnu
-	exit ;;
-    alpha:Linux:*:*)
-	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
-	  EV5)   UNAME_MACHINE=3Dalphaev5 ;;
-	  EV56)  UNAME_MACHINE=3Dalphaev56 ;;
-	  PCA56) UNAME_MACHINE=3Dalphapca56 ;;
-	  PCA57) UNAME_MACHINE=3Dalphapca56 ;;
-	  EV6)   UNAME_MACHINE=3Dalphaev6 ;;
-	  EV67)  UNAME_MACHINE=3Dalphaev67 ;;
-	  EV68*) UNAME_MACHINE=3Dalphaev68 ;;
-        esac
-	objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
-	if test "$?" =3D 0 ; then LIBC=3D"libc1" ; else LIBC=3D"" ; fi
-	echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-gnu
 	exit ;;
     parisc:Linux:*:* | hppa:Linux:*:*)
 	# Look for CPU level
@@ -929,8 +949,11 @@
 	  *)    echo hppa-unknown-linux-gnu ;;
 	esac
 	exit ;;
-    parisc64:Linux:*:* | hppa64:Linux:*:*)
-	echo hppa64-unknown-linux-gnu
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-gnu
+	exit ;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-gnu
 	exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
 	echo ${UNAME_MACHINE}-ibm-linux
@@ -950,69 +973,9 @@
     x86_64:Linux:*:*)
 	echo x86_64-unknown-linux-gnu
 	exit ;;
-    i*86:Linux:*:*)
-	# The BFD linker knows what the default object file format is, so
-	# first see if it will tell us. cd to the root directory to prevent
-	# problems with other programs or directories called `ld' in the path.
-	# Set LC_ALL=3DC to ensure ld outputs messages in English.
-	ld_supported_targets=3D`cd /; LC_ALL=3DC ld --help 2>&1 \
-			 | sed -ne '/supported targets:/!d
-				    s/[ 	][ 	]*/ /g
-				    s/.*supported targets: *//
-				    s/ .*//
-				    p'`
-        case "$ld_supported_targets" in
-	  elf32-i386)
-		TENTATIVE=3D"${UNAME_MACHINE}-pc-linux-gnu"
-		;;
-	  a.out-i386-linux)
-		echo "${UNAME_MACHINE}-pc-linux-gnuaout"
-		exit ;;
-	  coff-i386)
-		echo "${UNAME_MACHINE}-pc-linux-gnucoff"
-		exit ;;
-	  "")
-		# Either a pre-BFD a.out linker (linux-gnuoldld) or
-		# one that does not give us useful --help.
-		echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
-		exit ;;
-	esac
-	# Determine whether the default compiler is a.out or elf
-	eval $set_cc_for_build
-	sed 's/^	//' << EOF >$dummy.c
-	#include <features.h>
-	#ifdef __ELF__
-	# ifdef __GLIBC__
-	#  if __GLIBC__ >=3D 2
-	LIBC=3Dgnu
-	#  else
-	LIBC=3Dgnulibc1
-	#  endif
-	# else
-	LIBC=3Dgnulibc1
-	# endif
-	#else
-	#if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) ||=
 defined(__SUNPRO_CC)
-	LIBC=3Dgnu
-	#else
-	LIBC=3Dgnuaout
-	#endif
-	#endif
-	#ifdef __dietlibc__
-	LIBC=3Ddietlibc
-	#endif
-EOF
-	eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n '
-	    /^LIBC/{
-		s: ::g
-		p
-	    }'`"
-	test x"${LIBC}" !=3D x && {
-		echo "${UNAME_MACHINE}-pc-linux-${LIBC}"
-		exit
-	}
-	test x"${TENTATIVE}" !=3D x && { echo "${TENTATIVE}"; exit; }
-	;;
+    xtensa*:Linux:*:*)
+    	echo ${UNAME_MACHINE}-unknown-linux-gnu
+	exit ;;
     i*86:DYNIX/ptx:4*:*)
 	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
 	# earlier versions are messed up and put the nodename in both
@@ -1041,7 +1004,7 @@
     i*86:syllable:*:*)
 	echo ${UNAME_MACHINE}-pc-syllable
 	exit ;;
-    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
 	echo i386-unknown-lynxos${UNAME_RELEASE}
 	exit ;;
     i*86:*DOS:*:*)
@@ -1085,8 +1048,11 @@
     pc:*:*:*)
 	# Left here for compatibility:
         # uname -m prints for DJGPP always 'pc', but it prints nothing abo=
ut
-        # the processor, so we play safe by assuming i386.
-	echo i386-pc-msdosdjgpp
+        # the processor, so we play safe by assuming i586.
+	# Note: whatever this is, it MUST be the same as what config.sub
+	# prints for the "djgpp" host, or else GDB configury will decide that
+	# this is a cross-build.
+	echo i586-pc-msdosdjgpp
         exit ;;
     Intel:Mach:3*:*)
 	echo i386-pc-mach3
@@ -1124,6 +1090,16 @@
     3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
         /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
           && { echo i486-ncr-sysv4; exit; } ;;
+    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+	OS_REL=3D'.3'
+	test -r /etc/.relid \
+	    && OS_REL=3D.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.re=
lid`
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	    && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
     m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
 	echo m68k-unknown-lynxos${UNAME_RELEASE}
 	exit ;;
@@ -1136,7 +1112,7 @@
     rs6000:LynxOS:2.*:*)
 	echo rs6000-unknown-lynxos${UNAME_RELEASE}
 	exit ;;
-    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:=
*)
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02=
]*:*)
 	echo powerpc-unknown-lynxos${UNAME_RELEASE}
 	exit ;;
     SM[BE]S:UNIX_SV:*:*)
@@ -1199,6 +1175,9 @@
     BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
 	echo i586-pc-beos
 	exit ;;
+    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
+	echo i586-pc-haiku
+	exit ;;
     SX-4:SUPER-UX:*:*)
 	echo sx4-nec-superux${UNAME_RELEASE}
 	exit ;;
@@ -1208,6 +1187,15 @@
     SX-6:SUPER-UX:*:*)
 	echo sx6-nec-superux${UNAME_RELEASE}
 	exit ;;
+    SX-7:SUPER-UX:*:*)
+	echo sx7-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8:SUPER-UX:*:*)
+	echo sx8-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8R:SUPER-UX:*:*)
+	echo sx8r-nec-superux${UNAME_RELEASE}
+	exit ;;
     Power*:Rhapsody:*:*)
 	echo powerpc-apple-rhapsody${UNAME_RELEASE}
 	exit ;;
@@ -1217,6 +1205,16 @@
     *:Darwin:*:*)
 	UNAME_PROCESSOR=3D`uname -p` || UNAME_PROCESSOR=3Dunknown
 	case $UNAME_PROCESSOR in
+	    i386)
+		eval $set_cc_for_build
+		if [ "$CC_FOR_BUILD" !=3D 'no_compiler_found' ]; then
+		  if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		      (CCOPTS=3D $CC_FOR_BUILD -E - 2>/dev/null) | \
+		      grep IS_64BIT_ARCH >/dev/null
+		  then
+		      UNAME_PROCESSOR=3D"x86_64"
+		  fi
+		fi ;;
 	    unknown) UNAME_PROCESSOR=3Dpowerpc ;;
 	esac
 	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
@@ -1298,6 +1296,9 @@
     i*86:rdos:*:*)
 	echo ${UNAME_MACHINE}-pc-rdos
 	exit ;;
+    i*86:AROS:*:*)
+	echo ${UNAME_MACHINE}-pc-aros
+	exit ;;
 esac
=20
 #echo '(No uname command or uname output not recognized.)' 1>&2
@@ -1458,9 +1459,9 @@
 the operating system you are using. It is advised that you
 download the most up to date version of the config scripts from
=20
-  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.=
guess
+  http://git.savannah.gnu.org/gitweb/?p=3Dconfig.git;a=3Dblob_plain;f=3Dco=
nfig.guess;hb=3DHEAD
 and
-  http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.=
sub
+  http://git.savannah.gnu.org/gitweb/?p=3Dconfig.git;a=3Dblob_plain;f=3Dco=
nfig.sub;hb=3DHEAD
=20
 If the version you run ($0) is already up to date, please
 send the following data and any information you think might be
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/config.sub
--- a/head/crypto/heimdal/config.sub	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/config.sub	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
 #! /bin/sh
 # Configuration validation subroutine script.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
-#   2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
-#   Inc.
+#   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
+#   Free Software Foundation, Inc.
=20
-timestamp=3D'2006-09-20'
+timestamp=3D'2009-11-20'
=20
 # This file is (in principle) common to ALL GNU software.
 # The presence of a machine in this file suggests that SOME GNU software
@@ -32,13 +32,16 @@
=20
=20
 # Please send patches to <config-patches at gnu.org>.  Submit a context
-# diff and a properly formatted ChangeLog entry.
+# diff and a properly formatted GNU ChangeLog entry.
 #
 # Configuration subroutine to validate and canonicalize a configuration ty=
pe.
 # Supply the specified configuration type as an argument.
 # If it is invalid, we print an error message on stderr and exit with code=
 1.
 # Otherwise, we print the canonical config type on stdout and succeed.
=20
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=3Dconfig.git;a=3Dblob_plain;f=3Dco=
nfig.sub;hb=3DHEAD
+
 # This file is supposed to be the same for all GNU packages
 # and recognize all the CPU types, system types and aliases
 # that are meaningful with *any* GNU software.
@@ -72,8 +75,8 @@
 version=3D"\
 GNU config.sub ($timestamp)
=20
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, =
2002, 2003, 2004, 2005
-Free Software Foundation, Inc.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
=20
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE=
."
@@ -122,6 +125,7 @@
 case $maybe_os in
   nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* |=
 \
   uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd=
*-gnu* | \
+  kopensolaris*-gnu* | \
   storm-chaos* | os2-emx* | rtmk-nova*)
     os=3D-$maybe_os
     basic_machine=3D`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
@@ -148,10 +152,13 @@
 	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
 	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
 	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
-	-apple | -axis | -knuth | -cray)
+	-apple | -axis | -knuth | -cray | -microblaze)
 		os=3D
 		basic_machine=3D$1
 		;;
+        -bluegene*)
+	        os=3D-cnk
+		;;
 	-sim | -cisco | -oki | -wec | -winbond)
 		os=3D
 		basic_machine=3D$1
@@ -245,17 +252,20 @@
 	| bfin \
 	| c4x | clipper \
 	| d10v | d30v | dlx | dsp16xx \
-	| fr30 | frv \
+	| fido | fr30 | frv \
 	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
 	| i370 | i860 | i960 | ia64 \
 	| ip2k | iq2000 \
+	| lm32 \
 	| m32c | m32r | m32rle | m68000 | m68k | m88k \
-	| maxq | mb | microblaze | mcore \
+	| maxq | mb | microblaze | mcore | mep | metag \
 	| mips | mipsbe | mipseb | mipsel | mipsle \
 	| mips16 \
 	| mips64 | mips64el \
+	| mips64octeon | mips64octeonel \
+	| mips64orion | mips64orionel \
+	| mips64r5900 | mips64r5900el \
 	| mips64vr | mips64vrel \
-	| mips64orion | mips64orionel \
 	| mips64vr4100 | mips64vr4100el \
 	| mips64vr4300 | mips64vr4300el \
 	| mips64vr5000 | mips64vr5000el \
@@ -268,6 +278,7 @@
 	| mipsisa64sr71k | mipsisa64sr71kel \
 	| mipstx39 | mipstx39el \
 	| mn10200 | mn10300 \
+	| moxie \
 	| mt \
 	| msp430 \
 	| nios | nios2 \
@@ -276,20 +287,22 @@
 	| pdp10 | pdp11 | pj | pjl \
 	| powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
 	| pyramid \
+	| rx \
 	| score \
-	| sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[=
1234]le | sh3ele \
+	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe =
| shle | sh[1234]le | sh3ele \
 	| sh64 | sh64le \
 	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite=
 \
 	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
 	| spu | strongarm \
 	| tahoe | thumb | tic4x | tic80 | tron \
+	| ubicom32 \
 	| v850 | v850e \
 	| we32k \
 	| x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \
-	| z8k)
+	| z8k | z80)
 		basic_machine=3D$basic_machine-unknown
 		;;
-	m6811 | m68hc11 | m6812 | m68hc12)
+	m6811 | m68hc11 | m6812 | m68hc12 | picochip)
 		# Motorola 68HC11/12.
 		basic_machine=3D$basic_machine-unknown
 		os=3D-none
@@ -324,19 +337,22 @@
 	| clipper-* | craynv-* | cydra-* \
 	| d10v-* | d30v-* | dlx-* \
 	| elxsi-* \
-	| f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \
+	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
 	| h8300-* | h8500-* \
 	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
 	| i*86-* | i860-* | i960-* | ia64-* \
 	| ip2k-* | iq2000-* \
+	| lm32-* \
 	| m32c-* | m32r-* | m32rle-* \
 	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
-	| m88110-* | m88k-* | maxq-* | mcore-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \
 	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
 	| mips16-* \
 	| mips64-* | mips64el-* \
+	| mips64octeon-* | mips64octeonel-* \
+	| mips64orion-* | mips64orionel-* \
+	| mips64r5900-* | mips64r5900el-* \
 	| mips64vr-* | mips64vrel-* \
-	| mips64orion-* | mips64orionel-* \
 	| mips64vr4100-* | mips64vr4100el-* \
 	| mips64vr4300-* | mips64vr4300el-* \
 	| mips64vr5000-* | mips64vr5000el-* \
@@ -357,21 +373,26 @@
 	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
 	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
 	| pyramid-* \
-	| romp-* | rs6000-* \
-	| sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-=
* \
+	| romp-* | rs6000-* | rx-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | =
sheb-* | shbe-* \
 	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
 	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-*=
 \
 	| sparclite-* \
 	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* |=
 sx?-* \
 	| tahoe-* | thumb-* \
-	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* | tile-* \
 	| tron-* \
+	| ubicom32-* \
 	| v850-* | v850e-* | vax-* \
 	| we32k-* \
 	| x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \
-	| xstormy16-* | xtensa-* \
+	| xstormy16-* | xtensa*-* \
 	| ymp-* \
-	| z8k-*)
+	| z8k-* | z80-*)
+		;;
+	# Recognize the basic CPU types without company name, with glob match.
+	xtensa*)
+		basic_machine=3D$basic_machine-unknown
 		;;
 	# Recognize the various machine names and aliases which stand
 	# for a CPU type and a company and sometimes even an OS.
@@ -435,6 +456,10 @@
 		basic_machine=3Dm68k-apollo
 		os=3D-bsd
 		;;
+	aros)
+		basic_machine=3Di386-pc
+		os=3D-aros
+		;;
 	aux)
 		basic_machine=3Dm68k-apple
 		os=3D-aux
@@ -443,10 +468,26 @@
 		basic_machine=3Dns32k-sequent
 		os=3D-dynix
 		;;
+	blackfin)
+		basic_machine=3Dbfin-unknown
+		os=3D-linux
+		;;
+	blackfin-*)
+		basic_machine=3Dbfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=3D-linux
+		;;
+	bluegene*)
+		basic_machine=3Dpowerpc-ibm
+		os=3D-cnk
+		;;
 	c90)
 		basic_machine=3Dc90-cray
 		os=3D-unicos
 		;;
+        cegcc)
+		basic_machine=3Darm-unknown
+		os=3D-cegcc
+		;;
 	convex-c1)
 		basic_machine=3Dc1-convex
 		os=3D-bsd
@@ -475,8 +516,8 @@
 		basic_machine=3Dcraynv-cray
 		os=3D-unicosmp
 		;;
-	cr16c)
-		basic_machine=3Dcr16c-unknown
+	cr16)
+		basic_machine=3Dcr16-unknown
 		os=3D-elf
 		;;
 	crds | unos)
@@ -514,6 +555,10 @@
 		basic_machine=3Dm88k-motorola
 		os=3D-sysv3
 		;;
+	dicos)
+		basic_machine=3Di686-pc
+		os=3D-dicos
+		;;
 	djgpp)
 		basic_machine=3Di586-pc
 		os=3D-msdosdjgpp
@@ -668,6 +713,14 @@
 		basic_machine=3Dm68k-isi
 		os=3D-sysv
 		;;
+	m68knommu)
+		basic_machine=3Dm68k-unknown
+		os=3D-linux
+		;;
+	m68knommu-*)
+		basic_machine=3Dm68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=3D-linux
+		;;
 	m88k-omron*)
 		basic_machine=3Dm88k-omron
 		;;
@@ -679,10 +732,17 @@
 		basic_machine=3Dns32k-utek
 		os=3D-sysv
 		;;
+        microblaze)
+		basic_machine=3Dmicroblaze-xilinx
+		;;
 	mingw32)
 		basic_machine=3Di386-pc
 		os=3D-mingw32
 		;;
+	mingw32ce)
+		basic_machine=3Darm-unknown
+		os=3D-mingw32ce
+		;;
 	miniframe)
 		basic_machine=3Dm68000-convergent
 		;;
@@ -809,6 +869,14 @@
 		basic_machine=3Di860-intel
 		os=3D-osf
 		;;
+	parisc)
+		basic_machine=3Dhppa-unknown
+		os=3D-linux
+		;;
+	parisc-*)
+		basic_machine=3Dhppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=3D-linux
+		;;
 	pbd)
 		basic_machine=3Dsparc-tti
 		;;
@@ -925,6 +993,9 @@
 		basic_machine=3Dsh-hitachi
 		os=3D-hms
 		;;
+	sh5el)
+		basic_machine=3Dsh5le-unknown
+		;;
 	sh64)
 		basic_machine=3Dsh64-unknown
 		;;
@@ -1014,6 +1085,10 @@
 		basic_machine=3Dtic6x-unknown
 		os=3D-coff
 		;;
+	tile*)
+		basic_machine=3Dtile-unknown
+		os=3D-linux-gnu
+		;;
 	tx39)
 		basic_machine=3Dmipstx39-unknown
 		;;
@@ -1089,6 +1164,10 @@
 		basic_machine=3Dz8k-unknown
 		os=3D-sim
 		;;
+	z80-*-coff)
+		basic_machine=3Dz80-unknown
+		os=3D-sim
+		;;
 	none)
 		basic_machine=3Dnone-none
 		os=3D-none
@@ -1127,7 +1206,7 @@
 	we32k)
 		basic_machine=3Dwe32k-att
 		;;
-	sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele)
+	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
 		basic_machine=3Dsh-unknown
 		;;
 	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
@@ -1177,6 +1256,9 @@
         # First match some system type aliases
         # that might get confused with valid system types.
 	# -solaris* is a basic system type, with this one exception.
+        -auroraux)
+	        os=3D-auroraux
+		;;
 	-solaris1 | -solaris1.*)
 		os=3D`echo $os | sed -e 's|solaris1|sunos4|'`
 		;;
@@ -1197,10 +1279,11 @@
 	# Each alternative MUST END IN A *, to match a version number.
 	# -sysv* is not here because it comes later, after sysvr4.
 	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
-	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
-	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
+	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos=
[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris=
* \
+	      | -sym* | -kopensolaris* \
 	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
-	      | -aos* \
+	      | -aos* | -aros* \
 	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
 	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
 	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
@@ -1209,7 +1292,7 @@
 	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
 	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
 	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
-	      | -chorusos* | -chorusrdb* \
+	      | -chorusos* | -chorusrdb* | -cegcc* \
 	      | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
 	      | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \
 	      | -uxpv* | -beos* | -mpeix* | -udk* \
@@ -1219,7 +1302,7 @@
 	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
 	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
 	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-	      | -skyos* | -haiku* | -rdos* | -toppers*)
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*)
 	# Remember, each alternative MUST END IN *, to match a version number.
 		;;
 	-qnx*)
@@ -1349,6 +1432,9 @@
 	-zvmoe)
 		os=3D-zvmoe
 		;;
+	-dicos*)
+		os=3D-dicos
+		;;
 	-none)
 		;;
 	*)
@@ -1414,6 +1500,9 @@
 	m68*-cisco)
 		os=3D-aout
 		;;
+        mep-*)
+		os=3D-elf
+		;;
 	mips*-cisco)
 		os=3D-elf
 		;;
@@ -1543,7 +1632,7 @@
 			-sunos*)
 				vendor=3Dsun
 				;;
-			-aix*)
+			-cnk*|-aix*)
 				vendor=3Dibm
 				;;
 			-beos*)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/configure
--- a/head/crypto/heimdal/configure	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/configure	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,427 @@
 #! /bin/sh
-# From configure.in Revision: 22513 .
+# From configure.ac Revision.
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.61 for Heimdal 1.1.
+# Generated by GNU Autoconf 2.65 for Heimdal 1.5.2.
 #
 # Report bugs to <heimdal-bugs at h5l.org>.
 #
+#
 # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
-# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation,
+# Inc.
+#
+#
 # This configure script is free software; the Free Software Foundation
 # gives unlimited permission to copy, distribute and modify it.
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
=20
 # Be more Bourne compatible
 DUALCASE=3D1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
   emulate sh
   NULLCMD=3D:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'=3D'"$@"'
   setopt NO_GLOB_SUBST
 else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-
-
-# PATH needs CR
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl=3D'
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo=3D'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\=
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=3D$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=3D$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" =3D "X$as_echo") 2>/dev/null; then
+  as_echo=3D'print -r --'
+  as_echo_n=3D'print -rn --'
+elif (test "X`printf %s $as_echo`" =3D "X$as_echo") 2>/dev/null; then
+  as_echo=3D'printf %s\n'
+  as_echo_n=3D'printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" =3D "X-n $as_ech=
o"; then
+    as_echo_body=3D'eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n=3D'/usr/ucb/echo -n'
+  else
+    as_echo_body=3D'eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body=3D'eval
+      arg=3D$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=3D`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n=3D'sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo=3D'sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" !=3D set; then
+  PATH_SEPARATOR=3D:
+  (PATH=3D'/bin;/bin'; FPATH=3D$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH=3D'/bin:/bin'; FPATH=3D$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=3D';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=3D" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in #((
+  *[\\/]* ) as_myself=3D$0 ;;
+  *) as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    test -r "$as_dir/$0" && as_myself=3D$as_dir/$0 && break
+  done
+IFS=3D$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" =3D x; then
+  as_myself=3D$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute =
file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} =3D xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1=3D'$ '
+PS2=3D'> '
+PS4=3D'+ '
+
+# NLS nuisances.
+LC_ALL=3DC
+export LC_ALL
+LANGUAGE=3DC
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test "x$CONFIG_SHELL" =3D x; then
+  as_bourne_compatible=3D"if test -n \"\${ZSH_VERSION+set}\" && (emulate s=
h) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=3D:
+  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'=3D'\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+"
+  as_required=3D"as_fn_return () { (exit \$1); }
+as_fn_success () { as_fn_return 0; }
+as_fn_failure () { as_fn_return 1; }
+as_fn_ret_success () { return 0; }
+as_fn_ret_failure () { return 1; }
+
+exitcode=3D0
+as_fn_success || { exitcode=3D1; echo as_fn_success failed.; }
+as_fn_failure && { exitcode=3D1; echo as_fn_failure succeeded.; }
+as_fn_ret_success || { exitcode=3D1; echo as_fn_ret_success failed.; }
+as_fn_ret_failure && { exitcode=3D1; echo as_fn_ret_failure succeeded.; }
+if ( set x; as_fn_ret_success y && test x =3D \"\$1\" ); then :
+
+else
+  exitcode=3D1; echo positional parameters were not saved.
+fi
+test x\$exitcode =3D x0 || exit 1"
+  as_suggested=3D"  as_lineno_1=3D";as_suggested=3D$as_suggested$LINENO;as=
_suggested=3D$as_suggested" as_lineno_1a=3D\$LINENO
+  as_lineno_2=3D";as_suggested=3D$as_suggested$LINENO;as_suggested=3D$as_s=
uggested" as_lineno_2a=3D\$LINENO
+  eval 'test \"x\$as_lineno_1'\$as_run'\" !=3D \"x\$as_lineno_2'\$as_run'\=
" &&
+  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" =3D \"x\$as_lineno_2'\$as=
_run'\"' || exit 1
+
+  test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || (
+    ECHO=3D'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\=
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\=
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+    ECHO=3D\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO
+    ECHO=3D\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO
+    PATH=3D/empty FPATH=3D/empty; export PATH FPATH
+    test \"X\`printf %s \$ECHO\`\" =3D \"X\$ECHO\" \\
+      || test \"X\`print -r -- \$ECHO\`\" =3D \"X\$ECHO\" ) || exit 1
+test \$(( 1 + 1 )) =3D 2 || exit 1"
+  if (eval "$as_required") 2>/dev/null; then :
+  as_have_required=3Dyes
+else
+  as_have_required=3Dno
+fi
+  if test x$as_have_required =3D xyes && (eval "$as_suggested") 2>/dev/nul=
l; then :
+
+else
+  as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+as_found=3Dfalse
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+  as_found=3D:
+  case $as_dir in #(
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     # Try only shells that exist, to save several forks.
+	     as_shell=3D$as_dir/$as_base
+	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=3Da "$as_s=
hell"; } 2>/dev/null; then :
+  CONFIG_SHELL=3D$as_shell as_have_required=3Dyes
+		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=3Da "$a=
s_shell"; } 2>/dev/null; then :
+  break 2
+fi
+fi
+	   done;;
+       esac
+  as_found=3Dfalse
+done
+$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=3Da "$SHE=
LL"; } 2>/dev/null; then :
+  CONFIG_SHELL=3D$SHELL as_have_required=3Dyes
+fi; }
+IFS=3D$as_save_IFS
+
+
+      if test "x$CONFIG_SHELL" !=3D x; then :
+  # We cannot yet assume a decent shell, so we have to provide a
+	# neutralization value for shells without unset; and this also
+	# works around shells that cannot unset nonexistent variables.
+	BASH_ENV=3D/dev/null
+	ENV=3D/dev/null
+	(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+	export CONFIG_SHELL
+	exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+    if test x$as_have_required =3D xno; then :
+  $as_echo "$0: This script requires a shell more modern than all"
+  $as_echo "$0: the shells that I found on your system."
+  if test x${ZSH_VERSION+set} =3D xset ; then
+    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
+  else
+    $as_echo "$0: Please tell bug-autoconf at gnu.org and
+$0: heimdal-bugs at h5l.org about your system, including any
+$0: error possibly output before this message. Then install
+$0: a modern shell, or manually run the script under such a
+$0: shell if you do have one."
+  fi
+  exit 1
+fi
+fi
+fi
+SHELL=3D${CONFIG_SHELL-/bin/sh}
+export SHELL
+# Unset more variables known to interfere with behavior of common tools.
+CLICOLOR_FORCE=3D GREP_OPTIONS=3D
+unset CLICOLOR_FORCE GREP_OPTIONS
+
+## --------------------- ##
+## M4sh Shell Functions. ##
+## --------------------- ##
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=3D; unset $1;}
+}
+as_unset=3Das_fn_unset
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=3D./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=3D
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=3D`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=3D$as_dir;;
+      esac
+      as_dirs=3D"'$as_qdir' $as_dirs"
+      as_dir=3D`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. =
Take
+# advantage of any shell optimizations that allow amortized linear growth =
over
+# repeated appends, instead of the typical quadratic growth present in nai=
ve
+# implementations.
+if (eval "as_var=3D1; as_var+=3D2; test x\$as_var =3D x12") 2>/dev/null; t=
hen :
+  eval 'as_fn_append ()
+  {
+    eval $1+=3D\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=3D\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The argum=
ents
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) =3D 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=3D$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=3D`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+# as_fn_error ERROR [LINENO LOG_FD]
+# ---------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit=
 the
+# script with status $?, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=3D$?; test $as_status -eq 0 && as_status=3D1
+  if test "$3"; then
+    as_lineno=3D${as_lineno-"$2"} as_lineno_stack=3Das_lineno_stack=3D$as_=
lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3
+  fi
+  $as_echo "$as_me: error: $1" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" =3D X001; then
+  as_expr=3Dexpr
+else
+  as_expr=3Dfalse
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" =3D "X/=
"; then
+  as_basename=3Dbasename
+else
+  as_basename=3Dfalse
+fi
+
+if (as_dir=3D`dirname -- /` && test "X$as_dir" =3D X/) >/dev/null 2>&1; th=
en
+  as_dirname=3Ddirname
+else
+  as_dirname=3Dfalse
+fi
+
+as_me=3D`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
 # Avoid depending upon Character Ranges.
 as_cr_letters=3D'abcdefghijklmnopqrstuvwxyz'
 as_cr_LETTERS=3D'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
@@ -40,404 +429,12 @@
 as_cr_digits=3D'0123456789'
 as_cr_alnum=3D$as_cr_Letters$as_cr_digits
=20
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" !=3D set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH=3D"/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=3D';'
-  else
-    PATH_SEPARATOR=3D:
-  fi
-  rm -f conf$$.sh
-fi
-
-# Support unset when possible.
-if ( (MAIL=3D60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=3Dunset
-else
-  as_unset=3Dfalse
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-as_nl=3D'
-'
-IFS=3D" ""	$as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-case $0 in
-  *[\\/]* ) as_myself=3D$0 ;;
-  *) as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  test -r "$as_dir/$0" && as_myself=3D$as_dir/$0 && break
-done
-IFS=3D$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" =3D x; then
-  as_myself=3D$0
-fi
-if test ! -f "$as_myself"; then
-  echo "$as_myself: error: cannot find myself; rerun with an absolute file=
 name" >&2
-  { (exit 1); exit 1; }
-fi
-
-# Work around bugs in pre-3.0 UWIN ksh.
-for as_var in ENV MAIL MAILPATH
-do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-done
-PS1=3D'$ '
-PS2=3D'> '
-PS4=3D'+ '
-
-# NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
-do
-  if (set +x; test -z "`(eval $as_var=3DC; export $as_var) 2>&1`"); then
-    eval $as_var=3DC; export $as_var
-  else
-    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-  fi
-done
-
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" =3D X001; then
-  as_expr=3Dexpr
-else
-  as_expr=3Dfalse
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" =3D "X/=
"; then
-  as_basename=3Dbasename
-else
-  as_basename=3Dfalse
-fi
-
-
-# Name of the executable.
-as_me=3D`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-
-# CDPATH.
-$as_unset CDPATH
-
-
-if test "x$CONFIG_SHELL" =3D x; then
-  if (eval ":") 2>/dev/null; then
-  as_have_required=3Dyes
-else
-  as_have_required=3Dno
-fi
-
-  if test $as_have_required =3D yes && 	 (eval ":
-(as_func_return () {
-  (exit \$1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=3D0
-if as_func_success; then
-  :
-else
-  exitcode=3D1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=3D1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=3D1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=3D1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x =3D \"\$1\" ); then
-  :
-else
-  exitcode=3D1
-  echo positional parameters were not saved.
-fi
-
-test \$exitcode =3D 0) || { (exit 1); exit 1; }
-
-(
-  as_lineno_1=3D\$LINENO
-  as_lineno_2=3D\$LINENO
-  test \"x\$as_lineno_1\" !=3D \"x\$as_lineno_2\" &&
-  test \"x\`expr \$as_lineno_1 + 1\`\" =3D \"x\$as_lineno_2\") || { (exit =
1); exit 1; }
-") 2> /dev/null; then
-  :
-else
-  as_candidate_shells=3D
-    as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  case $as_dir in
-	 /*)
-	   for as_base in sh bash ksh sh5; do
-	     as_candidate_shells=3D"$as_candidate_shells $as_dir/$as_base"
-	   done;;
-       esac
-done
-IFS=3D$as_save_IFS
-
-
-      for as_shell in $as_candidate_shells $SHELL; do
-	 # Try only shells that exist, to save several forks.
-	 if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
-		{ ("$as_shell") 2> /dev/null <<\_ASEOF
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=3D:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'=3D'"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-:
-_ASEOF
-}; then
-  CONFIG_SHELL=3D$as_shell
-	       as_have_required=3Dyes
-	       if { "$as_shell" 2> /dev/null <<\_ASEOF
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=3D:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'=3D'"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-:
-(as_func_return () {
-  (exit $1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=3D0
-if as_func_success; then
-  :
-else
-  exitcode=3D1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=3D1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=3D1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=3D1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x =3D "$1" ); then
-  :
-else
-  exitcode=3D1
-  echo positional parameters were not saved.
-fi
-
-test $exitcode =3D 0) || { (exit 1); exit 1; }
-
-(
-  as_lineno_1=3D$LINENO
-  as_lineno_2=3D$LINENO
-  test "x$as_lineno_1" !=3D "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" =3D "x$as_lineno_2") || { (exit 1); exit=
 1; }
-
-_ASEOF
-}; then
-  break
-fi
-
-fi
-
-      done
-
-      if test "x$CONFIG_SHELL" !=3D x; then
-  for as_var in BASH_ENV ENV
-        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-        done
-        export CONFIG_SHELL
-        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
-fi
-
-
-    if test $as_have_required =3D no; then
-  echo This script requires a shell more modern than all the
-      echo shells that I found on your system.  Please install a
-      echo modern shell, or manually run the script under such a
-      echo shell if you do have one.
-      { (exit 1); exit 1; }
-fi
-
-
-fi
-
-fi
-
-
-
-(eval "as_func_return () {
-  (exit \$1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=3D0
-if as_func_success; then
-  :
-else
-  exitcode=3D1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=3D1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=3D1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=3D1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x =3D \"\$1\" ); then
-  :
-else
-  exitcode=3D1
-  echo positional parameters were not saved.
-fi
-
-test \$exitcode =3D 0") || {
-  echo No shell found that supports shell functions.
-  echo Please tell autoconf at gnu.org about your system,
-  echo including any error possibly output before this
-  echo message
-}
-
-
-
-  as_lineno_1=3D$LINENO
-  as_lineno_2=3D$LINENO
-  test "x$as_lineno_1" !=3D "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" =3D "x$as_lineno_2" || {
-
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line after each line using $LINENO; the second 'sed'
-  # does the real work.  The second script uses 'N' to pair each
-  # line-number line with the line containing $LINENO, and appends
-  # trailing '-' during substitution so that $LINENO is not a special
-  # case at line end.
-  # (Raja R Harinath suggested sed '=3D', and Paul Eggert wrote the
-  # scripts with optimization help from Paolo Bonzini.  Blame Lee
-  # E. McMahon (1931-1989) for sed's syntax.  :-)
+
+  as_lineno_1=3D$LINENO as_lineno_1a=3D$LINENO
+  as_lineno_2=3D$LINENO as_lineno_2a=3D$LINENO
+  eval 'test "x$as_lineno_1'$as_run'" !=3D "x$as_lineno_2'$as_run'" &&
+  test "x`expr $as_lineno_1'$as_run' + 1`" =3D "x$as_lineno_2'$as_run'"' |=
| {
+  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
   sed -n '
     p
     /[$]LINENO/=3D
@@ -454,8 +451,7 @@
       s/-\n.*//
     ' >$as_me.lineno &&
   chmod +x "$as_me.lineno" ||
-    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX=
 shell" >&2
-   { (exit 1); exit 1; }; }
+    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a P=
OSIX shell" >&2; as_fn_exit 1; }
=20
   # Don't try to exec as it changes $[0], causing all sort of problems
   # (the dirname of $[0] is not the place where we might find the
@@ -465,49 +461,40 @@
   exit
 }
=20
-
-if (as_dir=3D`dirname -- /` && test "X$as_dir" =3D X/) >/dev/null 2>&1; th=
en
-  as_dirname=3Ddirname
-else
-  as_dirname=3Dfalse
-fi
-
 ECHO_C=3D ECHO_N=3D ECHO_T=3D
-case `echo -n x` in
+case `echo -n x` in #(((((
 -n*)
-  case `echo 'x\c'` in
+  case `echo 'xy\c'` in
   *c*) ECHO_T=3D'	';;	# ECHO_T is single tab character.
-  *)   ECHO_C=3D'\c';;
+  xy)  ECHO_C=3D'\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T=3D'	';;
   esac;;
 *)
   ECHO_N=3D'-n';;
 esac
=20
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" =3D X001; then
-  as_expr=3Dexpr
-else
-  as_expr=3Dfalse
-fi
-
 rm -f conf$$ conf$$.exe conf$$.file
 if test -d conf$$.dir; then
   rm -f conf$$.dir/conf$$.file
 else
   rm -f conf$$.dir
-  mkdir conf$$.dir
-fi
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=3D'ln -s'
-  # ... but there are two gotchas:
-  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-  # In both cases, we have to default to `cp -p'.
-  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=3D'ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executabl=
e.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s=3D'cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=3Dln
+  else
     as_ln_s=3D'cp -p'
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=3Dln
+  fi
 else
   as_ln_s=3D'cp -p'
 fi
@@ -515,7 +502,7 @@
 rmdir conf$$.dir 2>/dev/null
=20
 if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=3D:
+  as_mkdir_p=3D'mkdir -p "$as_dir"'
 else
   test -d ./-p && rmdir ./-p
   as_mkdir_p=3Dfalse
@@ -532,12 +519,12 @@
   as_test_x=3D'
     eval sh -c '\''
       if test -d "$1"; then
-        test -d "$1/.";
-      else
-	case $1 in
-        -*)set "./$1";;
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
 	esac;
-	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
 	???[sx]*):;;*)false;;esac;fi
     '\'' sh
   '
@@ -550,163 +537,11 @@
 # Sed expression to map a string onto a valid variable name.
 as_tr_sh=3D"eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
=20
-
-
-
-# Check that we are running under the correct shell.
 SHELL=3D${CONFIG_SHELL-/bin/sh}
=20
-case X$ECHO in
-X*--fallback-echo)
-  # Remove one level of quotation (which was required for Make).
-  ECHO=3D`echo "$ECHO" | sed 's,\\\\\$\\$0,'$0','`
-  ;;
-esac
-
-echo=3D${ECHO-echo}
-if test "X$1" =3D X--no-reexec; then
-  # Discard the --no-reexec flag, and continue.
-  shift
-elif test "X$1" =3D X--fallback-echo; then
-  # Avoid inline document here, it may be left over
-  :
-elif test "X`($echo '\t') 2>/dev/null`" =3D 'X\t' ; then
-  # Yippee, $echo works!
-  :
-else
-  # Restart under the correct shell.
-  exec $SHELL "$0" --no-reexec ${1+"$@"}
-fi
-
-if test "X$1" =3D X--fallback-echo; then
-  # used as fallback echo
-  shift
-  cat <<EOF
-$*
-EOF
-  exit 0
-fi
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-if test -z "$ECHO"; then
-if test "X${echo_test_string+set}" !=3D Xset; then
-# find a string as large as possible, as long as the shell can cope with it
-  for cmd in 'sed 50q "$0"' 'sed 20q "$0"' 'sed 10q "$0"' 'sed 2q "$0"' 'e=
cho test'; do
-    # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ...
-    if (echo_test_string=3D`eval $cmd`) 2>/dev/null &&
-       echo_test_string=3D`eval $cmd` &&
-       (test "X$echo_test_string" =3D "X$echo_test_string") 2>/dev/null
-    then
-      break
-    fi
-  done
-fi
-
-if test "X`($echo '\t') 2>/dev/null`" =3D 'X\t' &&
-   echo_testing_string=3D`($echo "$echo_test_string") 2>/dev/null` &&
-   test "X$echo_testing_string" =3D "X$echo_test_string"; then
-  :
-else
-  # The Solaris, AIX, and Digital Unix default echo programs unquote
-  # backslashes.  This makes it impossible to quote backslashes using
-  #   echo "$something" | sed 's/\\/\\\\/g'
-  #
-  # So, first we look for a working echo in the user's PATH.
-
-  lt_save_ifs=3D"$IFS"; IFS=3D$PATH_SEPARATOR
-  for dir in $PATH /usr/ucb; do
-    IFS=3D"$lt_save_ifs"
-    if (test -f $dir/echo || test -f $dir/echo$ac_exeext) &&
-       test "X`($dir/echo '\t') 2>/dev/null`" =3D 'X\t' &&
-       echo_testing_string=3D`($dir/echo "$echo_test_string") 2>/dev/null`=
 &&
-       test "X$echo_testing_string" =3D "X$echo_test_string"; then
-      echo=3D"$dir/echo"
-      break
-    fi
-  done
-  IFS=3D"$lt_save_ifs"
-
-  if test "X$echo" =3D Xecho; then
-    # We didn't find a better echo, so look for alternatives.
-    if test "X`(print -r '\t') 2>/dev/null`" =3D 'X\t' &&
-       echo_testing_string=3D`(print -r "$echo_test_string") 2>/dev/null` =
&&
-       test "X$echo_testing_string" =3D "X$echo_test_string"; then
-      # This shell has a builtin print -r that does the trick.
-      echo=3D'print -r'
-    elif (test -f /bin/ksh || test -f /bin/ksh$ac_exeext) &&
-	 test "X$CONFIG_SHELL" !=3D X/bin/ksh; then
-      # If we have ksh, try running configure again with it.
-      ORIGINAL_CONFIG_SHELL=3D${CONFIG_SHELL-/bin/sh}
-      export ORIGINAL_CONFIG_SHELL
-      CONFIG_SHELL=3D/bin/ksh
-      export CONFIG_SHELL
-      exec $CONFIG_SHELL "$0" --no-reexec ${1+"$@"}
-    else
-      # Try using printf.
-      echo=3D'printf %s\n'
-      if test "X`($echo '\t') 2>/dev/null`" =3D 'X\t' &&
-	 echo_testing_string=3D`($echo "$echo_test_string") 2>/dev/null` &&
-	 test "X$echo_testing_string" =3D "X$echo_test_string"; then
-	# Cool, printf works
-	:
-      elif echo_testing_string=3D`($ORIGINAL_CONFIG_SHELL "$0" --fallback-=
echo '\t') 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D 'X\t' &&
-	   echo_testing_string=3D`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo "$=
echo_test_string") 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D "X$echo_test_string"; then
-	CONFIG_SHELL=3D$ORIGINAL_CONFIG_SHELL
-	export CONFIG_SHELL
-	SHELL=3D"$CONFIG_SHELL"
-	export SHELL
-	echo=3D"$CONFIG_SHELL $0 --fallback-echo"
-      elif echo_testing_string=3D`($CONFIG_SHELL "$0" --fallback-echo '\t'=
) 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D 'X\t' &&
-	   echo_testing_string=3D`($CONFIG_SHELL "$0" --fallback-echo "$echo_test=
_string") 2>/dev/null` &&
-	   test "X$echo_testing_string" =3D "X$echo_test_string"; then
-	echo=3D"$CONFIG_SHELL $0 --fallback-echo"
-      else
-	# maybe with a smaller string...
-	prev=3D:
-
-	for cmd in 'echo test' 'sed 2q "$0"' 'sed 10q "$0"' 'sed 20q "$0"' 'sed 5=
0q "$0"'; do
-	  if (test "X$echo_test_string" =3D "X`eval $cmd`") 2>/dev/null
-	  then
-	    break
-	  fi
-	  prev=3D"$cmd"
-	done
-
-	if test "$prev" !=3D 'sed 50q "$0"'; then
-	  echo_test_string=3D`eval $prev`
-	  export echo_test_string
-	  exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "$0" ${1+"$@"}
-	else
-	  # Oops.  We lost completely, so just stick with echo.
-	  echo=3Decho
-	fi
-      fi
-    fi
-  fi
-fi
-fi
-
-# Copy echo and quote the copy suitably for passing to libtool from
-# the Makefile, instead of quoting the original, which is used later.
-ECHO=3D$echo
-if test "X$ECHO" =3D "X$CONFIG_SHELL $0 --fallback-echo"; then
-   ECHO=3D"$CONFIG_SHELL \\\$\$0 --fallback-echo"
-fi
-
-
-
-
-tagnames=3D${tagnames+${tagnames},}CXX
-
-tagnames=3D${tagnames+${tagnames},}F77
-
-exec 7<&0 </dev/null 6>&1
+
+test -n "$DJDIR" || exec 7<&0 </dev/null
+exec 6>&1
=20
 # Name of the host.
 # hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
@@ -724,17 +559,16 @@
 subdirs=3D
 MFLAGS=3D
 MAKEFLAGS=3D
-SHELL=3D${CONFIG_SHELL-/bin/sh}
=20
 # Identity of this package.
 PACKAGE_NAME=3D'Heimdal'
 PACKAGE_TARNAME=3D'heimdal'
-PACKAGE_VERSION=3D'1.1'
-PACKAGE_STRING=3D'Heimdal 1.1'
+PACKAGE_VERSION=3D'1.5.2'
+PACKAGE_STRING=3D'Heimdal 1.5.2'
 PACKAGE_BUGREPORT=3D'heimdal-bugs at h5l.org'
+PACKAGE_URL=3D''
=20
 ac_unique_file=3D"kuser/kinit.c"
-ac_default_prefix=3D/usr/heimdal
 # Factoring default headers for most tests.
 ac_includes_default=3D"\
 #include <stdio.h>
@@ -771,256 +605,380 @@
 # include <unistd.h>
 #endif"
=20
-ac_subst_vars=3D'SHELL
+ac_default_prefix=3D/usr/heimdal
+ac_header_list=3D
+enable_option_checking=3Dno
+ac_subst_vars=3D'am__EXEEXT_FALSE
+am__EXEEXT_TRUE
+LTLIBOBJS
+HEIMDAL_DOCUMENTATION_FALSE
+HEIMDAL_DOCUMENTATION_TRUE
+LIB_AUTH_SUBDIRS
+LIB_com_err_so
+LIB_com_err_a
+LIB_com_err
+DIR_com_err
+COM_ERR_FALSE
+COM_ERR_TRUE
+COMPILE_ET
+LIBEDIT_FALSE
+LIBEDIT_TRUE
+FRAMEWORK_SECURITY_FALSE
+FRAMEWORK_SECURITY_TRUE
+KCM_FALSE
+KCM_TRUE
+LIB_door_create
+LIB_getpwnam_r
+LIB_tgetent
+LIB_openpty
+LIB_logout
+LIB_logwtmp
+NEED_WRITEAUTH_FALSE
+NEED_WRITEAUTH_TRUE
+LIB_XauFileName
+LIB_XauReadAuth
+LIB_XauWriteAuth
+HAVE_X_FALSE
+HAVE_X_TRUE
+X_EXTRA_LIBS
+X_LIBS
+X_PRE_LIBS
+X_CFLAGS
+XMKMF
+LIB_hesiod
+INCLUDE_hesiod
+subdirs
+LIB_libedit
+INCLUDE_libedit
+LIB_readline
+INCLUDE_readline
+CATMANEXT
+CATMAN_FALSE
+CATMAN_TRUE
+CATMAN
+GROFF
+NROFF
+LIB_security
+have_gcd_FALSE
+have_gcd_TRUE
+LIB_dispatch_async_f
+OTP_FALSE
+OTP_TRUE
+LIB_otp
+LIBADD_roken
+INCLUDES_roken
+LIB_roken
+DIR_roken
+have_socket_wrapper_FALSE
+have_socket_wrapper_TRUE
+LIB_crypt
+have_fnmatch_h_FALSE
+have_fnmatch_h_TRUE
+LIB_gai_strerror
+LIB_freeaddrinfo
+LIB_getnameinfo
+LIB_getaddrinfo
+LIB_pidfile
+LIB_bswap32
+LIB_bswap16
+LIB_hstrerror
+LIB_setsockopt
+LIB_getsockopt
+have_cgetent_FALSE
+have_cgetent_TRUE
+have_glob_h_FALSE
+have_glob_h_TRUE
+LIBOBJS
+LIB_dn_expand
+LIB_dns_search
+LIB_res_ndestroy
+LIB_res_nsearch
+LIB_res_search
+LIB_gethostbyname2
+LIB_syslog
+LIB_gethostbyname
+LIB_socket
+have_vis_h_FALSE
+have_vis_h_TRUE
+have_search_h_FALSE
+have_search_h_TRUE
+have_ifaddrs_h_FALSE
+have_ifaddrs_h_TRUE
+have_err_h_FALSE
+have_err_h_TRUE
+WFLAGS_NOIMPLICITINT
+WFLAGS_NOUNUSED
+WFLAGS
+LIB_NDBM
+DBLIB
+HAVE_DBHEADER_FALSE
+HAVE_DBHEADER_TRUE
+HAVE_NDBM_FALSE
+HAVE_NDBM_TRUE
+HAVE_DB3_FALSE
+HAVE_DB3_TRUE
+HAVE_DB1_FALSE
+HAVE_DB1_TRUE
+LIB_dbm_firstkey
+LIB_dbopen
+LIB_db_create
+DBHEADER
+NO_AFS
+dpagaix_ldflags
+dpagaix_ldadd
+dpagaix_cflags
+DCE_FALSE
+DCE_TRUE
+PTHREAD_LIBADD
+PTHREAD_LDADD
+PTHREAD_CFLAGS
+LIB_hcrypto_appl
+LIB_hcrypto_so
+LIB_hcrypto_a
+LIB_hcrypto
+INCLUDE_hcrypto
+DIR_hcrypto
+HAVE_OPENSSL_FALSE
+HAVE_OPENSSL_TRUE
+LIB_kdb
+do_roken_rename_FALSE
+do_roken_rename_TRUE
+KRB5_FALSE
+KRB5_TRUE
+KRB4_FALSE
+KRB4_TRUE
+LIB_krb4
+INCLUDE_krb4
+DIR_hdbdir
+LIB_libintl
+INCLUDE_libintl
+have_scc_FALSE
+have_scc_TRUE
+SQLITE3_FALSE
+SQLITE3_TRUE
+LIB_sqlite3
+INCLUDE_sqlite3
+HAVE_CAPNG_FALSE
+HAVE_CAPNG_TRUE
+CAPNG_LIBS
+CAPNG_CFLAGS
+PKG_CONFIG
+PKINIT_FALSE
+PKINIT_TRUE
+OPENLDAP_MODULE_FALSE
+OPENLDAP_MODULE_TRUE
+LIB_openldap
+INCLUDE_openldap
+SLC_DEP
+SLC
+ASN1_COMPILE_DEP
+ASN1_COMPILE
+CROSS_COMPILE_FALSE
+CROSS_COMPILE_TRUE
+LDFLAGS_VERSION_SCRIPT
+versionscript_FALSE
+versionscript_TRUE
+VERSIONING
+ENABLE_SHARED_FALSE
+ENABLE_SHARED_TRUE
+LEXLIB
+LEX_OUTPUT_ROOT
+LEX
+YFLAGS
+YACC
+IRIX_FALSE
+IRIX_TRUE
+AIX_EXTRA_KAFS
+AIX_DYNAMIC_AFS_FALSE
+AIX_DYNAMIC_AFS_TRUE
+LIB_loadquery
+HAVE_DLOPEN_FALSE
+HAVE_DLOPEN_TRUE
+LIB_dlopen
+AIX4_FALSE
+AIX4_TRUE
+AIX_FALSE
+AIX_TRUE
+CANONICAL_HOST
+OTOOL64
+OTOOL
+LIPO
+NMEDIT
+DSYMUTIL
+MANIFEST_TOOL
+RANLIB
+ac_ct_AR
+AR
+DLLTOOL
+OBJDUMP
+LN_S
+NM
+ac_ct_DUMPBIN
+DUMPBIN
+LD
+FGREP
+EGREP
+GREP
+SED
+host_os
+host_vendor
+host_cpu
+host
+build_os
+build_vendor
+build_cpu
+build
+LIBTOOL
+CPP
+am__fastdepCC_FALSE
+am__fastdepCC_TRUE
+CCDEPMODE
+AMDEPBACKSLASH
+AMDEP_FALSE
+AMDEP_TRUE
+am__quote
+am__include
+DEPDIR
+OBJEXT
+EXEEXT
+ac_ct_CC
+CPPFLAGS
+LDFLAGS
+CFLAGS
+CC
+MAINT
+MAINTAINER_MODE_FALSE
+MAINTAINER_MODE_TRUE
+am__untar
+am__tar
+AMTAR
+am__leading_dot
+SET_MAKE
+AWK
+mkdir_p
+MKDIR_P
+INSTALL_STRIP_PROGRAM
+STRIP
+install_sh
+MAKEINFO
+AUTOHEADER
+AUTOMAKE
+AUTOCONF
+ACLOCAL
+VERSION
+PACKAGE
+CYGPATH_W
+am__isrc
+INSTALL_DATA
+INSTALL_SCRIPT
+INSTALL_PROGRAM
+target_alias
+host_alias
+build_alias
+LIBS
+ECHO_T
+ECHO_N
+ECHO_C
+DEFS
+mandir
+localedir
+libdir
+psdir
+pdfdir
+dvidir
+htmldir
+infodir
+docdir
+oldincludedir
+includedir
+localstatedir
+sharedstatedir
+sysconfdir
+datadir
+datarootdir
+libexecdir
+sbindir
+bindir
+program_transform_name
+prefix
+exec_prefix
+PACKAGE_URL
+PACKAGE_BUGREPORT
+PACKAGE_STRING
+PACKAGE_VERSION
+PACKAGE_TARNAME
+PACKAGE_NAME
 PATH_SEPARATOR
-PACKAGE_NAME
-PACKAGE_TARNAME
-PACKAGE_VERSION
-PACKAGE_STRING
-PACKAGE_BUGREPORT
-exec_prefix
-prefix
-program_transform_name
-bindir
-sbindir
-libexecdir
-datarootdir
-datadir
-sysconfdir
-sharedstatedir
-localstatedir
-includedir
-oldincludedir
-docdir
-infodir
-htmldir
-dvidir
-pdfdir
-psdir
-libdir
-localedir
-mandir
-DEFS
-ECHO_C
-ECHO_N
-ECHO_T
-LIBS
-build_alias
-host_alias
-target_alias
-INSTALL_PROGRAM
-INSTALL_SCRIPT
-INSTALL_DATA
-am__isrc
-CYGPATH_W
-PACKAGE
-VERSION
-ACLOCAL
-AUTOCONF
-AUTOMAKE
-AUTOHEADER
-MAKEINFO
-install_sh
-STRIP
-INSTALL_STRIP_PROGRAM
-mkdir_p
-AWK
-SET_MAKE
-am__leading_dot
-AMTAR
-am__tar
-am__untar
-MAINTAINER_MODE_TRUE
-MAINTAINER_MODE_FALSE
-MAINT
-CC
-CFLAGS
-LDFLAGS
-CPPFLAGS
-ac_ct_CC
-EXEEXT
-OBJEXT
-CPP
-build
-build_cpu
-build_vendor
-build_os
-host
-host_cpu
-host_vendor
-host_os
-CANONICAL_HOST
-YACC
-YFLAGS
-LEX
-LEX_OUTPUT_ROOT
-LEXLIB
-LN_S
-GREP
-EGREP
-ECHO
-AR
-RANLIB
-CXX
-CXXFLAGS
-ac_ct_CXX
-CXXCPP
-F77
-FFLAGS
-ac_ct_F77
-LIBTOOL
-ENABLE_SHARED_TRUE
-ENABLE_SHARED_FALSE
-VERSIONING
-versionscript_TRUE
-versionscript_FALSE
-LDFLAGS_VERSION_SCRIPT
-INCLUDE_openldap
-LIB_openldap
-OPENLDAP_MODULE_TRUE
-OPENLDAP_MODULE_FALSE
-PKINIT_TRUE
-PKINIT_FALSE
-DIR_hdbdir
-INCLUDE_krb4
-LIB_krb4
-KRB4_TRUE
-KRB4_FALSE
-KRB5_TRUE
-KRB5_FALSE
-do_roken_rename_TRUE
-do_roken_rename_FALSE
-LIB_kdb
-HAVE_OPENSSL_TRUE
-HAVE_OPENSSL_FALSE
-DIR_hcrypto
-INCLUDE_hcrypto
-LIB_hcrypto
-LIB_hcrypto_a
-LIB_hcrypto_so
-LIB_hcrypto_appl
-PTHREADS_CFLAGS
-PTHREADS_LIBS
-DCE_TRUE
-DCE_FALSE
-dpagaix_cflags
-dpagaix_ldadd
-dpagaix_ldflags
-LIB_db_create
-LIB_dbopen
-LIB_dbm_firstkey
-HAVE_DB1_TRUE
-HAVE_DB1_FALSE
-HAVE_DB3_TRUE
-HAVE_DB3_FALSE
-HAVE_NDBM_TRUE
-HAVE_NDBM_FALSE
-DBLIB
-LIB_NDBM
-WFLAGS
-WFLAGS_NOUNUSED
-WFLAGS_NOIMPLICITINT
-VOID_RETSIGTYPE
-have_err_h_TRUE
-have_err_h_FALSE
-have_ifaddrs_h_TRUE
-have_ifaddrs_h_FALSE
-have_vis_h_TRUE
-have_vis_h_FALSE
-LIB_socket
-LIB_gethostbyname
-LIB_syslog
-LIB_gethostbyname2
-LIB_res_search
-LIB_res_nsearch
-LIB_res_ndestroy
-LIB_dn_expand
-LIBOBJS
-have_glob_h_TRUE
-have_glob_h_FALSE
-have_cgetent_TRUE
-have_cgetent_FALSE
-LIB_getsockopt
-LIB_setsockopt
-LIB_hstrerror
-LIB_bswap16
-LIB_bswap32
-LIB_pidfile
-LIB_getaddrinfo
-LIB_getnameinfo
-LIB_freeaddrinfo
-LIB_gai_strerror
-have_fnmatch_h_TRUE
-have_fnmatch_h_FALSE
-LIB_crypt
-have_socket_wrapper_TRUE
-have_socket_wrapper_FALSE
-DIR_roken
-LIB_roken
-INCLUDES_roken
-LIBADD_roken
-LIB_otp
-OTP_TRUE
-OTP_FALSE
-LIB_security
-NROFF
-GROFF
-CATMAN
-CATMAN_TRUE
-CATMAN_FALSE
-CATMANEXT
-INCLUDE_readline
-LIB_readline
-INCLUDE_hesiod
-LIB_hesiod
-AIX_TRUE
-AIX_FALSE
-AIX4_TRUE
-AIX4_FALSE
-LIB_dlopen
-HAVE_DLOPEN_TRUE
-HAVE_DLOPEN_FALSE
-LIB_loadquery
-AIX_DYNAMIC_AFS_TRUE
-AIX_DYNAMIC_AFS_FALSE
-AIX_EXTRA_KAFS
-IRIX_TRUE
-IRIX_FALSE
-XMKMF
-X_CFLAGS
-X_PRE_LIBS
-X_LIBS
-X_EXTRA_LIBS
-HAVE_X_TRUE
-HAVE_X_FALSE
-LIB_XauWriteAuth
-LIB_XauReadAuth
-LIB_XauFileName
-NEED_WRITEAUTH_TRUE
-NEED_WRITEAUTH_FALSE
-LIB_logwtmp
-LIB_logout
-LIB_openpty
-LIB_tgetent
-LIB_getpwnam_r
-LIB_door_create
-KCM_TRUE
-KCM_FALSE
-FRAMEWORK_SECURITY_TRUE
-FRAMEWORK_SECURITY_FALSE
-LIB_el_init
-el_compat_TRUE
-el_compat_FALSE
-COMPILE_ET
-COM_ERR_TRUE
-COM_ERR_FALSE
-DIR_com_err
-LIB_com_err
-LIB_com_err_a
-LIB_com_err_so
-LIB_AUTH_SUBDIRS
-LTLIBOBJS'
+SHELL'
 ac_subst_files=3D''
+ac_user_opts=3D'
+enable_option_checking
+enable_maintainer_mode
+enable_dependency_tracking
+enable_shared
+enable_static
+with_pic
+enable_fast_install
+with_gnu_ld
+with_sysroot
+enable_libtool_lock
+enable_largefile
+enable_dynamic_afs
+with_mips_abi
+with_cross_tools
+with_openldap
+with_openldap_lib
+with_openldap_include
+with_openldap_config
+enable_hdb_openldap_module
+enable_pk_init
+enable_digest
+enable_kx509
+with_capng
+with_sqlite3
+with_sqlite3_lib
+with_sqlite3_include
+with_sqlite3_config
+enable_sqlite_cache
+with_libintl
+with_libintl_lib
+with_libintl_include
+with_libintl_config
+with_hdbdir
+with_openssl
+with_openssl_lib
+with_openssl_include
+enable_pthread_support
+enable_dce
+enable_afs_support
+with_berkeley_db
+with_berkeley_db_include
+enable_ndbm_db
+enable_developer
+with_ipv6
+enable_socket_wrapper
+enable_otp
+enable_osfc2
+enable_mmap
+enable_afs_string_to_key
+with_readline
+with_readline_lib
+with_readline_include
+with_readline_config
+with_libedit
+with_libedit_lib
+with_libedit_include
+with_libedit_config
+with_hesiod
+with_hesiod_lib
+with_hesiod_include
+with_hesiod_config
+enable_bigendian
+enable_littleendian
+with_x
+enable_kcm
+enable_heimdal_documentation
+'
       ac_precious_vars=3D'build_alias
 host_alias
 target_alias
@@ -1032,18 +990,17 @@
 CPP
 YACC
 YFLAGS
-CXX
-CXXFLAGS
-CCC
-CXXCPP
-F77
-FFLAGS
+PKG_CONFIG
+CAPNG_CFLAGS
+CAPNG_LIBS
 XMKMF'
-
+ac_subdirs_all=3D'lib/libedit'
=20
 # Initialize some variables set by options.
 ac_init_help=3D
 ac_init_version=3Dfalse
+ac_unrecognized_opts=3D
+ac_unrecognized_sep=3D
 # The variables have the same names as the options, with
 # dashes changed to underlines.
 cache_file=3D/dev/null
@@ -1142,13 +1099,20 @@
     datarootdir=3D$ac_optarg ;;
=20
   -disable-* | --disable-*)
-    ac_feature=3D`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+    ac_useropt=3D`expr "x$ac_option" : 'x-*disable-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=3D`echo $ac_feature | sed 's/[-.]/_/g'`
-    eval enable_$ac_feature=3Dno ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid feature name: $ac_useropt"
+    ac_useropt_orig=3D$ac_useropt
+    ac_useropt=3D`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts=3D"$ac_unrecognized_opts$ac_unrecognized_sep=
--disable-$ac_useropt_orig"
+	 ac_unrecognized_sep=3D', ';;
+    esac
+    eval enable_$ac_useropt=3Dno ;;
=20
   -docdir | --docdir | --docdi | --doc | --do)
     ac_prev=3Ddocdir ;;
@@ -1161,13 +1125,20 @@
     dvidir=3D$ac_optarg ;;
=20
   -enable-* | --enable-*)
-    ac_feature=3D`expr "x$ac_option" : 'x-*enable-\([^=3D]*\)'`
+    ac_useropt=3D`expr "x$ac_option" : 'x-*enable-\([^=3D]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=3D`echo $ac_feature | sed 's/[-.]/_/g'`
-    eval enable_$ac_feature=3D\$ac_optarg ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid feature name: $ac_useropt"
+    ac_useropt_orig=3D$ac_useropt
+    ac_useropt=3D`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts=3D"$ac_unrecognized_opts$ac_unrecognized_sep=
--enable-$ac_useropt_orig"
+	 ac_unrecognized_sep=3D', ';;
+    esac
+    eval enable_$ac_useropt=3D\$ac_optarg ;;
=20
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -1358,22 +1329,36 @@
     ac_init_version=3D: ;;
=20
   -with-* | --with-*)
-    ac_package=3D`expr "x$ac_option" : 'x-*with-\([^=3D]*\)'`
+    ac_useropt=3D`expr "x$ac_option" : 'x-*with-\([^=3D]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=3D`echo $ac_package | sed 's/[-.]/_/g'`
-    eval with_$ac_package=3D\$ac_optarg ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid package name: $ac_useropt"
+    ac_useropt_orig=3D$ac_useropt
+    ac_useropt=3D`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts=3D"$ac_unrecognized_opts$ac_unrecognized_sep=
--with-$ac_useropt_orig"
+	 ac_unrecognized_sep=3D', ';;
+    esac
+    eval with_$ac_useropt=3D\$ac_optarg ;;
=20
   -without-* | --without-*)
-    ac_package=3D`expr "x$ac_option" : 'x-*without-\(.*\)'`
+    ac_useropt=3D`expr "x$ac_option" : 'x-*without-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=3D`echo $ac_package | sed 's/[-.]/_/g'`
-    eval with_$ac_package=3Dno ;;
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid package name: $ac_useropt"
+    ac_useropt_orig=3D$ac_useropt
+    ac_useropt=3D`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts=3D"$ac_unrecognized_opts$ac_unrecognized_sep=
--without-$ac_useropt_orig"
+	 ac_unrecognized_sep=3D', ';;
+    esac
+    eval with_$ac_useropt=3Dno ;;
=20
   --x)
     # Obsolete; use --with-x.
@@ -1393,25 +1378,25 @@
   | --x-librar=3D* | --x-libra=3D* | --x-libr=3D* | --x-lib=3D* | --x-li=
=3D* | --x-l=3D*)
     x_libraries=3D$ac_optarg ;;
=20
-  -*) { echo "$as_me: error: unrecognized option: $ac_option
-Try \`$0 --help' for more information." >&2
-   { (exit 1); exit 1; }; }
+  -*) as_fn_error "unrecognized option: \`$ac_option'
+Try \`$0 --help' for more information."
     ;;
=20
   *=3D*)
     ac_envvar=3D`expr "x$ac_option" : 'x\([^=3D]*\)=3D'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
-   { (exit 1); exit 1; }; }
+    case $ac_envvar in #(
+      '' | [0-9]* | *[!_$as_cr_alnum]* )
+      as_fn_error "invalid variable name: \`$ac_envvar'" ;;
+    esac
     eval $ac_envvar=3D\$ac_optarg
     export $ac_envvar ;;
=20
   *)
     # FIXME: should be removed in autoconf 3.0.
-    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >=
&2
     expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
     : ${build_alias=3D$ac_option} ${host_alias=3D$ac_option} ${target_alia=
s=3D$ac_option}
     ;;
=20
@@ -1420,23 +1405,36 @@
=20
 if test -n "$ac_prev"; then
   ac_option=3D--`echo $ac_prev | sed 's/_/-/g'`
-  { echo "$as_me: error: missing argument to $ac_option" >&2
-   { (exit 1); exit 1; }; }
-fi
-
-# Be sure to have absolute directory names.
+  as_fn_error "missing argument to $ac_option"
+fi
+
+if test -n "$ac_unrecognized_opts"; then
+  case $enable_option_checking in
+    no) ;;
+    fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;;
+    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecogniz=
ed_opts" >&2 ;;
+  esac
+fi
+
+# Check all directory arguments for consistency.
 for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
 		datadir sysconfdir sharedstatedir localstatedir includedir \
 		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
 		libdir localedir mandir
 do
   eval ac_val=3D\$$ac_var
+  # Remove trailing slashes.
+  case $ac_val in
+    */ )
+      ac_val=3D`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
+      eval $ac_var=3D\$ac_val;;
+  esac
+  # Be sure to have absolute directory names.
   case $ac_val in
     [\\/$]* | ?:[\\/]* )  continue;;
     NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
   esac
-  { echo "$as_me: error: expected an absolute directory name for --$ac_var=
: $ac_val" >&2
-   { (exit 1); exit 1; }; }
+  as_fn_error "expected an absolute directory name for --$ac_var: $ac_val"
 done
=20
 # There might be people who depend on the old broken behavior: `$host'
@@ -1450,7 +1448,7 @@
 if test "x$host_alias" !=3D x; then
   if test "x$build_alias" =3D x; then
     cross_compiling=3Dmaybe
-    echo "$as_me: WARNING: If you wanted to set the --build type, don't us=
e --host.
+    $as_echo "$as_me: WARNING: If you wanted to set the --build type, don'=
t use --host.
     If a cross compiler is detected then cross compile mode will be used."=
 >&2
   elif test "x$build_alias" !=3D "x$host_alias"; then
     cross_compiling=3Dyes
@@ -1466,23 +1464,21 @@
 ac_pwd=3D`pwd` && test -n "$ac_pwd" &&
 ac_ls_di=3D`ls -di .` &&
 ac_pwd_ls_di=3D`cd "$ac_pwd" && ls -di .` ||
-  { echo "$as_me: error: Working directory cannot be determined" >&2
-   { (exit 1); exit 1; }; }
+  as_fn_error "working directory cannot be determined"
 test "X$ac_ls_di" =3D "X$ac_pwd_ls_di" ||
-  { echo "$as_me: error: pwd does not report name of working directory" >&2
-   { (exit 1); exit 1; }; }
+  as_fn_error "pwd does not report name of working directory"
=20
=20
 # Find the source files, if location was not specified.
 if test -z "$srcdir"; then
   ac_srcdir_defaulted=3Dyes
   # Try the directory containing this script, then the parent directory.
-  ac_confdir=3D`$as_dirname -- "$0" ||
-$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$0" : 'X\(//\)[^/]' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$0" |
+  ac_confdir=3D`$as_dirname -- "$as_myself" ||
+$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_myself" : 'X\(//\)[^/]' \| \
+	 X"$as_myself" : 'X\(//\)$' \| \
+	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_myself" |
     sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
 	    s//\1/
 	    q
@@ -1509,13 +1505,11 @@
 fi
 if test ! -r "$srcdir/$ac_unique_file"; then
   test "$ac_srcdir_defaulted" =3D yes && srcdir=3D"$ac_confdir or .."
-  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir"=
 >&2
-   { (exit 1); exit 1; }; }
+  as_fn_error "cannot find sources ($ac_unique_file) in $srcdir"
 fi
 ac_msg=3D"sources are in $srcdir, but \`cd $srcdir' does not work"
 ac_abs_confdir=3D`(
-	cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac=
_msg" >&2
-   { (exit 1); exit 1; }; }
+	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg"
 	pwd)`
 # When building in place, set srcdir=3D.
 if test "$ac_abs_confdir" =3D "$ac_pwd"; then
@@ -1541,7 +1535,7 @@
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures Heimdal 1.1 to adapt to many kinds of systems.
+\`configure' configures Heimdal 1.5.2 to adapt to many kinds of systems.
=20
 Usage: $0 [OPTION]... [VAR=3DVALUE]...
=20
@@ -1563,9 +1557,9 @@
=20
 Installation directories:
   --prefix=3DPREFIX         install architecture-independent files in PREF=
IX
-			  [$ac_default_prefix]
+                          [$ac_default_prefix]
   --exec-prefix=3DEPREFIX   install architecture-dependent files in EPREFIX
-			  [PREFIX]
+                          [PREFIX]
=20
 By default, \`make install' will install all the files in
 \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
@@ -1575,25 +1569,25 @@
 For better control, use the options below.
=20
 Fine tuning of the installation directories:
-  --bindir=3DDIR           user executables [EPREFIX/bin]
-  --sbindir=3DDIR          system admin executables [EPREFIX/sbin]
-  --libexecdir=3DDIR       program executables [EPREFIX/libexec]
-  --sysconfdir=3DDIR       read-only single-machine data [PREFIX/etc]
-  --sharedstatedir=3DDIR   modifiable architecture-independent data [PREFI=
X/com]
-  --localstatedir=3DDIR    modifiable single-machine data [PREFIX/var]
-  --libdir=3DDIR           object code libraries [EPREFIX/lib]
-  --includedir=3DDIR       C header files [PREFIX/include]
-  --oldincludedir=3DDIR    C header files for non-gcc [/usr/include]
-  --datarootdir=3DDIR      read-only arch.-independent data root [PREFIX/s=
hare]
-  --datadir=3DDIR          read-only architecture-independent data [DATARO=
OTDIR]
-  --infodir=3DDIR          info documentation [DATAROOTDIR/info]
-  --localedir=3DDIR        locale-dependent data [DATAROOTDIR/locale]
-  --mandir=3DDIR           man documentation [DATAROOTDIR/man]
-  --docdir=3DDIR           documentation root [DATAROOTDIR/doc/heimdal]
-  --htmldir=3DDIR          html documentation [DOCDIR]
-  --dvidir=3DDIR           dvi documentation [DOCDIR]
-  --pdfdir=3DDIR           pdf documentation [DOCDIR]
-  --psdir=3DDIR            ps documentation [DOCDIR]
+  --bindir=3DDIR            user executables [EPREFIX/bin]
+  --sbindir=3DDIR           system admin executables [EPREFIX/sbin]
+  --libexecdir=3DDIR        program executables [EPREFIX/libexec]
+  --sysconfdir=3DDIR        read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=3DDIR    modifiable architecture-independent data [PREF=
IX/com]
+  --localstatedir=3DDIR     modifiable single-machine data [PREFIX/var]
+  --libdir=3DDIR            object code libraries [EPREFIX/lib]
+  --includedir=3DDIR        C header files [PREFIX/include]
+  --oldincludedir=3DDIR     C header files for non-gcc [/usr/include]
+  --datarootdir=3DDIR       read-only arch.-independent data root [PREFIX/=
share]
+  --datadir=3DDIR           read-only architecture-independent data [DATAR=
OOTDIR]
+  --infodir=3DDIR           info documentation [DATAROOTDIR/info]
+  --localedir=3DDIR         locale-dependent data [DATAROOTDIR/locale]
+  --mandir=3DDIR            man documentation [DATAROOTDIR/man]
+  --docdir=3DDIR            documentation root [DATAROOTDIR/doc/heimdal]
+  --htmldir=3DDIR           html documentation [DOCDIR]
+  --dvidir=3DDIR            dvi documentation [DOCDIR]
+  --pdfdir=3DDIR            pdf documentation [DOCDIR]
+  --psdir=3DDIR             ps documentation [DOCDIR]
 _ACEOF
=20
   cat <<\_ACEOF
@@ -1615,30 +1609,36 @@
=20
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of Heimdal 1.1:";;
+     short | recursive ) echo "Configuration of Heimdal 1.5.2:";;
    esac
   cat <<\_ACEOF
=20
 Optional Features:
+  --disable-option-checking  ignore unrecognized --enable/--with options
   --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=
=3Dno)
   --enable-FEATURE[=3DARG]  include FEATURE [ARG=3Dyes]
   --enable-maintainer-mode  enable make rules and dependencies not useful
 			  (and sometimes confusing) to the casual installer
-  --disable-largefile     omit support for large files
+  --disable-dependency-tracking  speeds up one-time build
+  --enable-dependency-tracking   do not reject slow dependency extractors
   --enable-shared[=3DPKGS]  build shared libraries [default=3Dyes]
   --enable-static[=3DPKGS]  build static libraries [default=3Dyes]
   --enable-fast-install[=3DPKGS]
                           optimize for fast installation [default=3Dyes]
   --disable-libtool-lock  avoid locking (might break parallel builds)
+  --disable-largefile     omit support for large files
+  --disable-dynamic-afs   do not use loaded AFS library with AIX
   --enable-hdb-openldap-module
                           if you want support to build openldap hdb as sha=
red
                           object
   --disable-pk-init       if you want disable to PK-INIT support
+  --disable-digest        if you want disable to DIGEST support
+  --disable-kx509         if you want disable to kx509 support
+  --disable-sqlite-cache  if you want support for cache in sqlite
   --enable-pthread-support
                           if you want thread safe libraries
   --enable-dce            if you want support for DCE/DFS PAG's
   --disable-afs-support   if you don't want support for AFS
-  --disable-berkeley-db   if you don't want berkeley db
   --disable-ndbm-db       if you don't want ndbm db
   --enable-developer      enable developer warnings
   --enable-socket-wrapper use sambas socket-wrapper for testing
@@ -1649,30 +1649,48 @@
                           disable use of weak AFS string-to-key functions
   --enable-bigendian      the target is big endian
   --enable-littleendian   the target is little endian
-  --disable-dynamic-afs   do not use loaded AFS library with AIX
-  --enable-netinfo        enable netinfo for configuration lookup
   --enable-kcm            enable Kerberos Credentials Manager
+  --disable-heimdal-documentation
+                          if you want disable to heimdal documentation
=20
 Optional Packages:
   --with-PACKAGE[=3DARG]    use PACKAGE [ARG=3Dyes]
   --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=3Dno)
-  --with-mips-abi=3Dabi     ABI to use for IRIX (32, n32, or 64)
-  --with-gnu-ld           assume the C compiler uses GNU ld [default=3Dno]
   --with-pic              try to use only PIC/non-PIC objects [default=3Du=
se
                           both]
-  --with-tags[=3DTAGS]      include additional configurations [automatic]
+  --with-gnu-ld           assume the C compiler uses GNU ld [default=3Dno]
+  --with-sysroot=3DDIR Search for dependent libraries within DIR
+                        (or the compiler's sysroot if not specified).
+  --with-mips-abi=3Dabi     ABI to use for IRIX (32, n32, or 64)
+  --with-cross-tools=3Ddir  use cross tools in dir
   --with-openldap=3Ddir     use openldap in dir
   --with-openldap-lib=3Ddir use openldap libraries in dir
   --with-openldap-include=3Ddir
                           use openldap headers in dir
   --with-openldap-config=3Dpath
                           config program for openldap
+  --with-capng            use libcap-ng to drop KDC privileges [default=3D=
check]
+  --with-sqlite3=3Ddir      use sqlite3 in dir
+  --with-sqlite3-lib=3Ddir  use sqlite3 libraries in dir
+  --with-sqlite3-include=3Ddir
+                          use sqlite3 headers in dir
+  --with-sqlite3-config=3Dpath
+                          config program for sqlite3
+  --with-libintl=3Ddir      use libintl in dir
+  --with-libintl-lib=3Ddir  use libintl libraries in dir
+  --with-libintl-include=3Ddir
+                          use libintl headers in dir
+  --with-libintl-config=3Dpath
+                          config program for libintl
   --with-hdbdir           Default location for KDC database
                           [default=3D/var/heimdal]
   --with-openssl=3Ddir      use openssl in dir
   --with-openssl-lib=3Ddir  use openssl libraries in dir
   --with-openssl-include=3Ddir
                           use openssl headers in dir
+  --with-berkeley-db      enable support for berkeley db [default=3Dcheck]
+  --with-berkeley-db-include=3Ddir
+                          use berkeley-db headers in dir
   --without-ipv6          do not enable IPv6 support
   --with-readline=3Ddir     use readline in dir
   --with-readline-lib=3Ddir use readline libraries in dir
@@ -1680,6 +1698,12 @@
                           use readline headers in dir
   --with-readline-config=3Dpath
                           config program for readline
+  --with-libedit=3Ddir      use libedit in dir
+  --with-libedit-lib=3Ddir  use libedit libraries in dir
+  --with-libedit-include=3Ddir
+                          use libedit headers in dir
+  --with-libedit-config=3Dpath
+                          config program for libedit
   --with-hesiod=3Ddir       use hesiod in dir
   --with-hesiod-lib=3Ddir   use hesiod libraries in dir
   --with-hesiod-include=3Ddir
@@ -1694,7 +1718,7 @@
   LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
               nonstandard directory <lib dir>
   LIBS        libraries to pass to the linker, e.g. -l<library>
-  CPPFLAGS    C/C++/Objective C preprocessor flags, e.g. -I<include dir> if
+  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
               you have headers in a nonstandard directory <include dir>
   CPP         C preprocessor
   YACC        The `Yet Another C Compiler' implementation to use. Defaults=
 to
@@ -1702,11 +1726,10 @@
   YFLAGS      The list of arguments that will be passed by default to $YAC=
C.
               This script will default YFLAGS to the empty string to avoid=
 a
               default value of `-d' given by some make applications.
-  CXX         C++ compiler command
-  CXXFLAGS    C++ compiler flags
-  CXXCPP      C++ preprocessor
-  F77         Fortran 77 compiler command
-  FFLAGS      Fortran 77 compiler flags
+  PKG_CONFIG  path to pkg-config utility
+  CAPNG_CFLAGS
+              C compiler flags for CAPNG, overriding pkg-config
+  CAPNG_LIBS  linker flags for CAPNG, overriding pkg-config
   XMKMF       Path to xmkmf, Makefile generator for X Window System
=20
 Use these variables to override the choices made by `configure' or to help
@@ -1720,15 +1743,17 @@
 if test "$ac_init_help" =3D "recursive"; then
   # If there are subdirs, report their specific --help.
   for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" =3D x: && continue
-    test -d "$ac_dir" || continue
+    test -d "$ac_dir" ||
+      { cd "$srcdir" && ac_pwd=3D`pwd` && srcdir=3D. && test -d "$ac_dir";=
 } ||
+      continue
     ac_builddir=3D.
=20
 case "$ac_dir" in
 .) ac_dir_suffix=3D ac_top_builddir_sub=3D. ac_top_build_prefix=3D ;;
 *)
-  ac_dir_suffix=3D/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  ac_dir_suffix=3D/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
   # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=3D`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/=
,,'`
+  ac_top_builddir_sub=3D`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g=
;s|/||'`
   case $ac_top_builddir_sub in
   "") ac_top_builddir_sub=3D. ac_top_build_prefix=3D ;;
   *)  ac_top_build_prefix=3D$ac_top_builddir_sub/ ;;
@@ -1764,7 +1789,7 @@
       echo &&
       $SHELL "$ac_srcdir/configure" --help=3Drecursive
     else
-      echo "$as_me: WARNING: no configuration information is in $ac_dir" >=
&2
+      $as_echo "$as_me: WARNING: no configuration information is in $ac_di=
r" >&2
     fi || ac_status=3D$?
     cd "$ac_pwd" || { ac_status=3D$?; break; }
   done
@@ -1773,22 +1798,462 @@
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-Heimdal configure 1.1
-generated by GNU Autoconf 2.61
-
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
-2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+Heimdal configure 1.5.2
+generated by GNU Autoconf 2.65
+
+Copyright (C) 2009 Free Software Foundation, Inc.
 This configure script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it.
 _ACEOF
   exit
 fi
+
+## ------------------------ ##
+## Autoconf initialization. ##
+## ------------------------ ##
+
+# ac_fn_c_try_compile LINENO
+# --------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_compile ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try=3D"$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
+  *) ac_try_echo=3D$ac_try;;
+esac
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=3D$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=3D0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=3D1
+fi
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_compile
+
+# ac_fn_c_try_cpp LINENO
+# ----------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_cpp ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  if { { ac_try=3D"$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
+  *) ac_try_echo=3D$ac_try;;
+esac
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=3D$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=3D0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=3D1
+fi
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_cpp
+
+# ac_fn_c_try_link LINENO
+# -----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_link ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  rm -f conftest.$ac_objext conftest$ac_exeext
+  if { { ac_try=3D"$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
+  *) ac_try_echo=3D$ac_try;;
+esac
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>conftest.err
+  ac_status=3D$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" =3D yes ||
+	 $as_test_x conftest$ac_exeext
+       }; then :
+  ac_retval=3D0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=3D1
+fi
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
+  # interfere with the next link command; also delete a directory that is
+  # left behind by Apple's compiler.  We do this before executing the acti=
ons.
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_link
+
+# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists and can be compiled using the include files =
in
+# INCLUDES, setting the cache variable VAR accordingly.
+ac_fn_c_check_header_compile ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "$3=3Dyes"
+else
+  eval "$3=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=3D\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+
+} # ac_fn_c_check_header_compile
+
+# ac_fn_c_try_run LINENO
+# ----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
+# that executables *can* be run.
+ac_fn_c_try_run ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  if { { ac_try=3D"$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
+  *) ac_try_echo=3D$ac_try;;
+esac
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } && { ac_try=3D'./conftest$ac_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
+  *) ac_try_echo=3D$ac_try;;
+esac
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; }; then :
+  ac_retval=3D0
+else
+  $as_echo "$as_me: program exited with status $ac_status" >&5
+       $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_retval=3D$ac_status
+fi
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_run
+
+# ac_fn_c_check_func LINENO FUNC VAR
+# ----------------------------------
+# Tests whether FUNC exists, setting the cache variable VAR accordingly
+ac_fn_c_check_func ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+/* Define $2 to an innocuous variant, in case <limits.h> declares $2.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define $2 innocuous_$2
+
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char $2 (); below.
+    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+    <limits.h> exists even on freestanding compilers.  */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $2
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $2 ();
+/* The GNU C library defines this for functions which it implements
+    to always fail with ENOSYS.  Some functions are actually named
+    something starting with __ and the normal name is an alias.  */
+#if defined __stub_$2 || defined __stub___$2
+choke me
+#endif
+
+int
+main ()
+{
+return $2 ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$3=3Dyes"
+else
+  eval "$3=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+eval ac_res=3D\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+
+} # ac_fn_c_check_func
+
+# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists, giving a warning if it cannot be compiled u=
sing
+# the include files in INCLUDES and setting the cache variable VAR
+# accordingly.
+ac_fn_c_check_header_mongrel ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+fi
+eval ac_res=3D\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+else
+  # Is the header compilable?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
+$as_echo_n "checking $2 usability... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_header_compiler=3Dyes
+else
+  ac_header_compiler=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
+$as_echo "$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
+$as_echo_n "checking $2 presence... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <$2>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  ac_header_preproc=3Dyes
+else
+  ac_header_preproc=3Dno
+fi
+rm -f conftest.err conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
+$as_echo "$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
+  yes:no: )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the =
compiler, rejected by the preprocessor!" >&5
+$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the p=
reprocessor!" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with =
the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+    ;;
+  no:yes:* )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cann=
ot be compiled" >&5
+$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for mi=
ssing prerequisite headers?" >&5
+$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?=
" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf=
 documentation" >&5
+$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Pr=
esent But Cannot Be Compiled\"" >&5
+$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compile=
d\"" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with =
the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+( cat <<\_ASBOX
+## ----------------------------------- ##
+## Report this to heimdal-bugs at h5l.org ##
+## ----------------------------------- ##
+_ASBOX
+     ) | sed "s/^/$as_me: WARNING:     /" >&2
+    ;;
+esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  eval "$3=3D\$ac_header_compiler"
+fi
+eval ac_res=3D\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+fi
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+
+} # ac_fn_c_check_header_mongrel
+
+# ac_fn_c_check_type LINENO TYPE VAR INCLUDES
+# -------------------------------------------
+# Tests whether TYPE exists after having included INCLUDES, setting cache
+# variable VAR accordingly.
+ac_fn_c_check_type ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  eval "$3=3Dno"
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+int
+main ()
+{
+if (sizeof ($2))
+	 return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+int
+main ()
+{
+if (sizeof (($2)))
+	    return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  eval "$3=3Dyes"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=3D\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+
+} # ac_fn_c_check_type
+
+# ac_fn_c_check_header_preproc LINENO HEADER VAR
+# ----------------------------------------------
+# Tests whether HEADER is present, setting the cache variable VAR accordin=
gly.
+ac_fn_c_check_header_preproc ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <$2>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  eval "$3=3Dyes"
+else
+  eval "$3=3Dno"
+fi
+rm -f conftest.err conftest.$ac_ext
+fi
+eval ac_res=3D\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+
+} # ac_fn_c_check_header_preproc
 cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
=20
-It was created by Heimdal $as_me 1.1, which was
-generated by GNU Autoconf 2.61.  Invocation command line was
+It was created by Heimdal $as_me 1.5.2, which was
+generated by GNU Autoconf 2.65.  Invocation command line was
=20
   $ $0 $@
=20
@@ -1824,8 +2289,8 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  echo "PATH: $as_dir"
-done
+    $as_echo "PATH: $as_dir"
+  done
 IFS=3D$as_save_IFS
=20
 } >&5
@@ -1859,12 +2324,12 @@
     | -silent | --silent | --silen | --sile | --sil)
       continue ;;
     *\'*)
-      ac_arg=3D`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+      ac_arg=3D`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
     esac
     case $ac_pass in
-    1) ac_configure_args0=3D"$ac_configure_args0 '$ac_arg'" ;;
+    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
     2)
-      ac_configure_args1=3D"$ac_configure_args1 '$ac_arg'"
+      as_fn_append ac_configure_args1 " '$ac_arg'"
       if test $ac_must_keep_next =3D true; then
 	ac_must_keep_next=3Dfalse # Got value, back to normal.
       else
@@ -1880,13 +2345,13 @@
 	  -* ) ac_must_keep_next=3Dtrue ;;
 	esac
       fi
-      ac_configure_args=3D"$ac_configure_args '$ac_arg'"
-      ;;
-    esac
-  done
-done
-$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" !=3D set =
|| { ac_configure_args0=3D; export ac_configure_args0; }
-$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" !=3D set =
|| { ac_configure_args1=3D; export ac_configure_args1; }
+      as_fn_append ac_configure_args " '$ac_arg'"
+      ;;
+    esac
+  done
+done
+{ ac_configure_args0=3D; unset ac_configure_args0;}
+{ ac_configure_args1=3D; unset ac_configure_args1;}
=20
 # When interrupted or exit'd, cleanup temporary files, and complete
 # config.log.  We remove comments because anyway the quotes in there
@@ -1911,12 +2376,13 @@
     case $ac_val in #(
     *${as_nl}*)
       case $ac_var in #(
-      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var cont=
ains a newline." >&5
-echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache vari=
able $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;=
} ;;
       esac
       case $ac_var in #(
       _ | IFS | as_nl) ;; #(
-      *) $as_unset $ac_var ;;
+      BASH_ARGV | BASH_SOURCE) eval $ac_var=3D ;; #(
+      *) { eval $ac_var=3D; unset $ac_var;} ;;
       esac ;;
     esac
   done
@@ -1945,9 +2411,9 @@
     do
       eval ac_val=3D\$$ac_var
       case $ac_val in
-      *\'\''*) ac_val=3D`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''=
/g"`;;
+      *\'\''*) ac_val=3D`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\''=
'\''/g"`;;
       esac
-      echo "$ac_var=3D'\''$ac_val'\''"
+      $as_echo "$ac_var=3D'\''$ac_val'\''"
     done | sort
     echo
=20
@@ -1962,9 +2428,9 @@
       do
 	eval ac_val=3D\$$ac_var
 	case $ac_val in
-	*\'\''*) ac_val=3D`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	*\'\''*) ac_val=3D`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/=
g"`;;
 	esac
-	echo "$ac_var=3D'\''$ac_val'\''"
+	$as_echo "$ac_var=3D'\''$ac_val'\''"
       done | sort
       echo
     fi
@@ -1980,86 +2446,94 @@
       echo
     fi
     test "$ac_signal" !=3D 0 &&
-      echo "$as_me: caught signal $ac_signal"
-    echo "$as_me: exit $exit_status"
+      $as_echo "$as_me: caught signal $ac_signal"
+    $as_echo "$as_me: exit $exit_status"
   } >&5
   rm -f core *.core core.conftest.* &&
     rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
     exit $exit_status
 ' 0
 for ac_signal in 1 2 13 15; do
-  trap 'ac_signal=3D'$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+  trap 'ac_signal=3D'$ac_signal'; as_fn_exit 1' $ac_signal
 done
 ac_signal=3D0
=20
 # confdefs.h avoids OS command line length limits that DEFS can exceed.
 rm -f -r conftest* confdefs.h
=20
+$as_echo "/* confdefs.h */" > confdefs.h
+
 # Predefined preprocessor variables.
=20
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_NAME "$PACKAGE_NAME"
 _ACEOF
=20
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_TARNAME "$PACKAGE_TARNAME"
 _ACEOF
=20
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_VERSION "$PACKAGE_VERSION"
 _ACEOF
=20
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_STRING "$PACKAGE_STRING"
 _ACEOF
=20
-
 cat >>confdefs.h <<_ACEOF
 #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
 _ACEOF
=20
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_URL "$PACKAGE_URL"
+_ACEOF
+
=20
 # Let the site file select an alternate cache file if it wants to.
-# Prefer explicitly selected file to automatically selected ones.
+# Prefer an explicitly selected file to automatically selected ones.
+ac_site_file1=3DNONE
+ac_site_file2=3DNONE
 if test -n "$CONFIG_SITE"; then
-  set x "$CONFIG_SITE"
+  ac_site_file1=3D$CONFIG_SITE
 elif test "x$prefix" !=3D xNONE; then
-  set x "$prefix/share/config.site" "$prefix/etc/config.site"
-else
-  set x "$ac_default_prefix/share/config.site" \
-	"$ac_default_prefix/etc/config.site"
-fi
-shift
-for ac_site_file
-do
-  if test -r "$ac_site_file"; then
-    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
-echo "$as_me: loading site script $ac_site_file" >&6;}
+  ac_site_file1=3D$prefix/share/config.site
+  ac_site_file2=3D$prefix/etc/config.site
+else
+  ac_site_file1=3D$ac_default_prefix/share/config.site
+  ac_site_file2=3D$ac_default_prefix/etc/config.site
+fi
+for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+do
+  test "x$ac_site_file" =3D xNONE && continue
+  if test /dev/null !=3D "$ac_site_file" && test -r "$ac_site_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_=
file" >&5
+$as_echo "$as_me: loading site script $ac_site_file" >&6;}
     sed 's/^/| /' "$ac_site_file" >&5
     . "$ac_site_file"
   fi
 done
=20
 if test -r "$cache_file"; then
-  # Some versions of bash will fail to source /dev/null (special
-  # files actually), so we avoid doing that.
-  if test -f "$cache_file"; then
-    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
-echo "$as_me: loading cache $cache_file" >&6;}
+  # Some versions of bash will fail to source /dev/null (special files
+  # actually), so we avoid doing that.  DJGPP emulates it as a regular fil=
e.
+  if test /dev/null !=3D "$cache_file" && test -f "$cache_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+$as_echo "$as_me: loading cache $cache_file" >&6;}
     case $cache_file in
       [\\/]* | ?:[\\/]* ) . "$cache_file";;
       *)                      . "./$cache_file";;
     esac
   fi
 else
-  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
-echo "$as_me: creating cache $cache_file" >&6;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+$as_echo "$as_me: creating cache $cache_file" >&6;}
   >$cache_file
 fi
=20
+as_fn_append ac_header_list " stdlib.h"
+as_fn_append ac_header_list " unistd.h"
+as_fn_append ac_header_list " sys/param.h"
 # Check that the precious variables saved in the cache have kept the same
 # value.
 ac_cache_corrupted=3Dfalse
@@ -2070,68 +2544,56 @@
   eval ac_new_val=3D\$ac_env_${ac_var}_value
   case $ac_old_set,$ac_new_set in
     set,)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' =
in the previous run" >&5
-echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous =
run" >&2;}
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set t=
o \`$ac_old_val' in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previ=
ous run" >&2;}
       ac_cache_corrupted=3D: ;;
     ,set)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previou=
s run" >&5
-echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not s=
et in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
       ac_cache_corrupted=3D: ;;
     ,);;
     *)
       if test "x$ac_old_val" !=3D "x$ac_new_val"; then
-	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous =
run:" >&5
-echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
-	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
-echo "$as_me:   former value:  $ac_old_val" >&2;}
-	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
-echo "$as_me:   current value: $ac_new_val" >&2;}
-	ac_cache_corrupted=3D:
+	# differences in whitespace do not lead to failure.
+	ac_old_val_w=3D`echo x $ac_old_val`
+	ac_new_val_w=3D`echo x $ac_new_val`
+	if test "$ac_old_val_w" !=3D "$ac_new_val_w"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed =
since the previous run:" >&5
+$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >=
&2;}
+	  ac_cache_corrupted=3D:
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace c=
hanges in \`$ac_var' since the previous run:" >&5
+$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since=
 the previous run:" >&2;}
+	  eval $ac_var=3D\$ac_old_val
+	fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'"=
 >&5
+$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'"=
 >&5
+$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
       fi;;
   esac
   # Pass precious variables to config.status.
   if test "$ac_new_set" =3D set; then
     case $ac_new_val in
-    *\'*) ac_arg=3D$ac_var=3D`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"=
` ;;
+    *\'*) ac_arg=3D$ac_var=3D`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\'=
'/g"` ;;
     *) ac_arg=3D$ac_var=3D$ac_new_val ;;
     esac
     case " $ac_configure_args " in
       *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
-      *) ac_configure_args=3D"$ac_configure_args '$ac_arg'" ;;
+      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
     esac
   fi
 done
 if $ac_cache_corrupted; then
-  { echo "$as_me:$LINENO: error: changes in the environment can compromise=
 the build" >&5
-echo "$as_me: error: changes in the environment can compromise the build" =
>&2;}
-  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cach=
e_file' and start over" >&5
-echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and st=
art over" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environme=
nt can compromise the build" >&5
+$as_echo "$as_me: error: changes in the environment can compromise the bui=
ld" >&2;}
+  as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start ov=
er" "$LINENO" 5
+fi
+## -------------------- ##
+## Main body of script. ##
+## -------------------- ##
=20
 ac_ext=3Dc
 ac_cpp=3D'$CPP $CPPFLAGS'
@@ -2144,28 +2606,21 @@
 ac_config_headers=3D"$ac_config_headers include/config.h"
=20
=20
-am__api_version=3D'1.10'
+
+am__api_version=3D'1.11'
=20
 ac_aux_dir=3D
 for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
-  if test -f "$ac_dir/install-sh"; then
-    ac_aux_dir=3D$ac_dir
-    ac_install_sh=3D"$ac_aux_dir/install-sh -c"
-    break
-  elif test -f "$ac_dir/install.sh"; then
-    ac_aux_dir=3D$ac_dir
-    ac_install_sh=3D"$ac_aux_dir/install.sh -c"
-    break
-  elif test -f "$ac_dir/shtool"; then
-    ac_aux_dir=3D$ac_dir
-    ac_install_sh=3D"$ac_aux_dir/shtool install -c"
-    break
-  fi
+  for ac_t in install-sh install.sh shtool; do
+    if test -f "$ac_dir/$ac_t"; then
+      ac_aux_dir=3D$ac_dir
+      ac_install_sh=3D"$ac_aux_dir/$ac_t -c"
+      break 2
+    fi
+  done
 done
 if test -z "$ac_aux_dir"; then
-  { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in=
 \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5
-echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \=
"$srcdir/..\" \"$srcdir/../..\"" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "cannot find install-sh, install.sh, or shtool in \"$srcdir\=
" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5
 fi
=20
 # These three variables are undocumented and unsupported,
@@ -2190,22 +2645,23 @@
 # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
 # OS/2's system install, which has a completely different semantic
 # ./install, which can be erroneously created by make from ./install.sh.
-{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
-echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; }
+# Reject install programs that cannot install multiple files.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible ins=
tall" >&5
+$as_echo_n "checking for a BSD-compatible install... " >&6; }
 if test -z "$INSTALL"; then
-if test "${ac_cv_path_install+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test "${ac_cv_path_install+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  # Account for people who put trailing slashes in PATH elements.
-case $as_dir/ in
-  ./ | .// | /cC/* | \
+    # Account for people who put trailing slashes in PATH elements.
+case $as_dir/ in #((
+  ./ | .// | /[cC]/* | \
   /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
-  ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \
+  ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \
   /usr/ucb/* ) ;;
   *)
     # OSF1 and SCO ODT 3.0 have their own names for install.
@@ -2223,17 +2679,29 @@
 	    # program-specific install script used by HP pwplus--don't use.
 	    :
 	  else
-	    ac_cv_path_install=3D"$as_dir/$ac_prog$ac_exec_ext -c"
-	    break 3
+	    rm -rf conftest.one conftest.two conftest.dir
+	    echo one > conftest.one
+	    echo two > conftest.two
+	    mkdir conftest.dir
+	    if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`=
/conftest.dir" &&
+	      test -s conftest.one && test -s conftest.two &&
+	      test -s conftest.dir/conftest.one &&
+	      test -s conftest.dir/conftest.two
+	    then
+	      ac_cv_path_install=3D"$as_dir/$ac_prog$ac_exec_ext -c"
+	      break 3
+	    fi
 	  fi
 	fi
       done
     done
     ;;
 esac
-done
-IFS=3D$as_save_IFS
-
+
+  done
+IFS=3D$as_save_IFS
+
+rm -rf conftest.one conftest.two conftest.dir
=20
 fi
   if test "${ac_cv_path_install+set}" =3D set; then
@@ -2246,8 +2714,8 @@
     INSTALL=3D$ac_install_sh
   fi
 fi
-{ echo "$as_me:$LINENO: result: $INSTALL" >&5
-echo "${ECHO_T}$INSTALL" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5
+$as_echo "$INSTALL" >&6; }
=20
 # Use test -z because SunOS4 sh mishandles braces in ${var-val}.
 # It thinks the first close brace ends the variable substitution.
@@ -2257,21 +2725,34 @@
=20
 test -z "$INSTALL_DATA" && INSTALL_DATA=3D'${INSTALL} -m 644'
=20
-{ echo "$as_me:$LINENO: checking whether build environment is sane" >&5
-echo $ECHO_N "checking whether build environment is sane... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environmen=
t is sane" >&5
+$as_echo_n "checking whether build environment is sane... " >&6; }
 # Just in case
 sleep 1
 echo timestamp > conftest.file
+# Reject unsafe characters in $srcdir or the absolute working directory
+# name.  Accept space and tab only in the latter.
+am_lf=3D'
+'
+case `pwd` in
+  *[\\\"\#\$\&\'\`$am_lf]*)
+    as_fn_error "unsafe absolute working directory name" "$LINENO" 5;;
+esac
+case $srcdir in
+  *[\\\"\#\$\&\'\`$am_lf\ \	]*)
+    as_fn_error "unsafe srcdir value: \`$srcdir'" "$LINENO" 5;;
+esac
+
 # Do `set' in a subshell so we don't clobber the current shell's
 # arguments.  Must try -L first in case configure is actually a
 # symlink; some systems play weird games with the mod time of symlinks
 # (eg FreeBSD returns the mod time of the symlink's containing
 # directory).
 if (
-   set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null`
+   set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null`
    if test "$*" =3D "X"; then
       # -L didn't work.
-      set X `ls -t $srcdir/configure conftest.file`
+      set X `ls -t "$srcdir/configure" conftest.file`
    fi
    rm -f conftest.file
    if test "$*" !=3D "X $srcdir/configure conftest.file" \
@@ -2281,11 +2762,8 @@
       # if, for instance, CONFIG_SHELL is bash and it inherits a
       # broken ls alias from the environment.  This has actually
       # happened.  Such a system could not be considered "sane".
-      { { echo "$as_me:$LINENO: error: ls -t appears to fail.  Make sure t=
here is not a broken
-alias in your environment" >&5
-echo "$as_me: error: ls -t appears to fail.  Make sure there is not a brok=
en
-alias in your environment" >&2;}
-   { (exit 1); exit 1; }; }
+      as_fn_error "ls -t appears to fail.  Make sure there is not a broken
+alias in your environment" "$LINENO" 5
    fi
=20
    test "$2" =3D conftest.file
@@ -2294,52 +2772,162 @@
    # Ok.
    :
 else
-   { { echo "$as_me:$LINENO: error: newly created file is older than distr=
ibuted files!
-Check your system clock" >&5
-echo "$as_me: error: newly created file is older than distributed files!
-Check your system clock" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+   as_fn_error "newly created file is older than distributed files!
+Check your system clock" "$LINENO" 5
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 test "$program_prefix" !=3D NONE &&
   program_transform_name=3D"s&^&$program_prefix&;$program_transform_name"
 # Use a double $ so make ignores it.
 test "$program_suffix" !=3D NONE &&
   program_transform_name=3D"s&\$&$program_suffix&;$program_transform_name"
-# Double any \ or $.  echo might interpret backslashes.
+# Double any \ or $.
 # By default was `s,x,x', remove it if useless.
-cat <<\_ACEOF >conftest.sed
-s/[\\$]/&&/g;s/;s,x,x,$//
-_ACEOF
-program_transform_name=3D`echo $program_transform_name | sed -f conftest.s=
ed`
-rm -f conftest.sed
+ac_script=3D's/[\\$]/&&/g;s/;s,x,x,$//'
+program_transform_name=3D`$as_echo "$program_transform_name" | sed "$ac_sc=
ript"`
=20
 # expand $ac_aux_dir to an absolute path
 am_aux_dir=3D`cd $ac_aux_dir && pwd`
=20
-test x"${MISSING+set}" =3D xset || MISSING=3D"\${SHELL} $am_aux_dir/missin=
g"
+if test x"${MISSING+set}" !=3D xset; then
+  case $am_aux_dir in
+  *\ * | *\	*)
+    MISSING=3D"\${SHELL} \"$am_aux_dir/missing\"" ;;
+  *)
+    MISSING=3D"\${SHELL} $am_aux_dir/missing" ;;
+  esac
+fi
 # Use eval to expand $SHELL
 if eval "$MISSING --run true"; then
   am_missing_run=3D"$MISSING --run "
 else
   am_missing_run=3D
-  { echo "$as_me:$LINENO: WARNING: \`missing' script is too old or missing=
" >&5
-echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;}
-fi
-
-{ echo "$as_me:$LINENO: checking for a thread-safe mkdir -p" >&5
-echo $ECHO_N "checking for a thread-safe mkdir -p... $ECHO_C" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is t=
oo old or missing" >&5
+$as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;}
+fi
+
+if test x"${install_sh}" !=3D xset; then
+  case $am_aux_dir in
+  *\ * | *\	*)
+    install_sh=3D"\${SHELL} '$am_aux_dir/install-sh'" ;;
+  *)
+    install_sh=3D"\${SHELL} $am_aux_dir/install-sh"
+  esac
+fi
+
+# Installed binaries are usually stripped using `strip' when the user
+# run `make install-strip'.  However `strip' might not be the right
+# tool to use in cross-compilation environments, therefore Automake
+# will honor the `STRIP' environment variable to overrule this program.
+if test "$cross_compiling" !=3D no; then
+  if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}strip", so it can be a pro=
gram name with args.
+set dummy ${ac_tool_prefix}strip; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_STRIP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$STRIP"; then
+  ac_cv_prog_STRIP=3D"$STRIP" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_STRIP=3D"${ac_tool_prefix}strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+STRIP=3D$ac_cv_prog_STRIP
+if test -n "$STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5
+$as_echo "$STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_STRIP"; then
+  ac_ct_STRIP=3D$STRIP
+  # Extract the first word of "strip", so it can be a program name with ar=
gs.
+set dummy strip; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_STRIP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_STRIP"; then
+  ac_cv_prog_ac_ct_STRIP=3D"$ac_ct_STRIP" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_STRIP=3D"strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_STRIP=3D$ac_cv_prog_ac_ct_STRIP
+if test -n "$ac_ct_STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5
+$as_echo "$ac_ct_STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_STRIP" =3D x; then
+    STRIP=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    STRIP=3D$ac_ct_STRIP
+  fi
+else
+  STRIP=3D"$ac_cv_prog_STRIP"
+fi
+
+fi
+INSTALL_STRIP_PROGRAM=3D"\$(install_sh) -c -s"
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir =
-p" >&5
+$as_echo_n "checking for a thread-safe mkdir -p... " >&6; }
 if test -z "$MKDIR_P"; then
-  if test "${ac_cv_path_mkdir+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  if test "${ac_cv_path_mkdir+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
 for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_prog in mkdir gmkdir; do
+    for ac_prog in mkdir gmkdir; do
 	 for ac_exec_ext in '' $ac_executable_extensions; do
 	   { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_pr=
og$ac_exec_ext"; } || continue
 	   case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #(
@@ -2351,11 +2939,12 @@
 	   esac
 	 done
        done
-done
-IFS=3D$as_save_IFS
-
-fi
-
+  done
+IFS=3D$as_save_IFS
+
+fi
+
+  test -d ./--version && rmdir ./--version
   if test "${ac_cv_path_mkdir+set}" =3D set; then
     MKDIR_P=3D"$ac_cv_path_mkdir -p"
   else
@@ -2363,12 +2952,11 @@
     # value for MKDIR_P within a source directory, because that will
     # break other packages using the cache if that directory is
     # removed, or if the value is a relative name.
-    test -d ./--version && rmdir ./--version
     MKDIR_P=3D"$ac_install_sh -d"
   fi
 fi
-{ echo "$as_me:$LINENO: result: $MKDIR_P" >&5
-echo "${ECHO_T}$MKDIR_P" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5
+$as_echo "$MKDIR_P" >&6; }
=20
 mkdir_p=3D"$MKDIR_P"
 case $mkdir_p in
@@ -2380,10 +2968,10 @@
 do
   # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
 set dummy $ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_AWK+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_AWK+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$AWK"; then
   ac_cv_prog_AWK=3D"$AWK" # Let the user override the test.
@@ -2393,36 +2981,37 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_prog_AWK=3D"$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 fi
 fi
 AWK=3D$ac_cv_prog_AWK
 if test -n "$AWK"; then
-  { echo "$as_me:$LINENO: result: $AWK" >&5
-echo "${ECHO_T}$AWK" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5
+$as_echo "$AWK" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
   test -n "$AWK" && break
 done
=20
-{ echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5
-echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6;=
 }
-set x ${MAKE-make}; ac_make=3D`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_=
/g'`
-if { as_var=3Dac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}=
\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} set=
s \$(MAKE)" >&5
+$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
+set x ${MAKE-make}
+ac_make=3D`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if { as_var=3Dac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}=
\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
 else
   cat >conftest.make <<\_ACEOF
 SHELL =3D /bin/sh
@@ -2439,12 +3028,12 @@
 rm -f conftest.make
 fi
 if eval test \$ac_cv_prog_make_${ac_make}_set =3D yes; then
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
   SET_MAKE=3D
 else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
   SET_MAKE=3D"MAKE=3D${MAKE-make}"
 fi
=20
@@ -2463,9 +3052,7 @@
   am__isrc=3D' -I$(srcdir)'
   # test to see if srcdir already configured
   if test -f $srcdir/config.status; then
-    { { echo "$as_me:$LINENO: error: source directory already configured; =
run \"make distclean\" there first" >&5
-echo "$as_me: error: source directory already configured; run \"make distc=
lean\" there first" >&2;}
-   { (exit 1); exit 1; }; }
+    as_fn_error "source directory already configured; run \"make distclean=
\" there first" "$LINENO" 5
   fi
 fi
=20
@@ -2481,7 +3068,7 @@
=20
 # Define the identity of the package.
  PACKAGE=3D'heimdal'
- VERSION=3D'1.1'
+ VERSION=3D'1.5.2'
=20
=20
 cat >>confdefs.h <<_ACEOF
@@ -2509,112 +3096,6 @@
=20
 MAKEINFO=3D${MAKEINFO-"${am_missing_run}makeinfo"}
=20
-install_sh=3D${install_sh-"\$(SHELL) $am_aux_dir/install-sh"}
-
-# Installed binaries are usually stripped using `strip' when the user
-# run `make install-strip'.  However `strip' might not be the right
-# tool to use in cross-compilation environments, therefore Automake
-# will honor the `STRIP' environment variable to overrule this program.
-if test "$cross_compiling" !=3D no; then
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}strip", so it can be a pro=
gram name with args.
-set dummy ${ac_tool_prefix}strip; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_STRIP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP=3D"$STRIP" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_STRIP=3D"${ac_tool_prefix}strip"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-STRIP=3D$ac_cv_prog_STRIP
-if test -n "$STRIP"; then
-  { echo "$as_me:$LINENO: result: $STRIP" >&5
-echo "${ECHO_T}$STRIP" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_STRIP"; then
-  ac_ct_STRIP=3D$STRIP
-  # Extract the first word of "strip", so it can be a program name with ar=
gs.
-set dummy strip; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_STRIP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_STRIP"; then
-  ac_cv_prog_ac_ct_STRIP=3D"$ac_ct_STRIP" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_ac_ct_STRIP=3D"strip"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-ac_ct_STRIP=3D$ac_cv_prog_ac_ct_STRIP
-if test -n "$ac_ct_STRIP"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
-echo "${ECHO_T}$ac_ct_STRIP" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-  if test "x$ac_ct_STRIP" =3D x; then
-    STRIP=3D":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=3Dyes ;;
-esac
-    STRIP=3D$ac_ct_STRIP
-  fi
-else
-  STRIP=3D"$ac_cv_prog_STRIP"
-fi
-
-fi
-INSTALL_STRIP_PROGRAM=3D"\$(install_sh) -c -s"
-
 # We need awk for the "check" target.  The system "awk" is bad on
 # some platforms.
 # Always define AMTAR for backward compatibility.
@@ -2627,17 +3108,18 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking whether to enable maintainer-specific por=
tions of Makefiles" >&5
-echo $ECHO_N "checking whether to enable maintainer-specific portions of M=
akefiles... $ECHO_C" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable mainta=
iner-specific portions of Makefiles" >&5
+$as_echo_n "checking whether to enable maintainer-specific portions of Mak=
efiles... " >&6; }
     # Check whether --enable-maintainer-mode was given.
-if test "${enable_maintainer_mode+set}" =3D set; then
+if test "${enable_maintainer_mode+set}" =3D set; then :
   enableval=3D$enable_maintainer_mode; USE_MAINTAINER_MODE=3D$enableval
 else
   USE_MAINTAINER_MODE=3Dno
 fi
=20
-  { echo "$as_me:$LINENO: result: $USE_MAINTAINER_MODE" >&5
-echo "${ECHO_T}$USE_MAINTAINER_MODE" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $USE_MAINTAINER_MODE" >=
&5
+$as_echo "$USE_MAINTAINER_MODE" >&6; }
    if test $USE_MAINTAINER_MODE =3D yes; then
   MAINTAINER_MODE_TRUE=3D
   MAINTAINER_MODE_FALSE=3D'#'
@@ -2658,10 +3140,10 @@
 if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}gcc", so it can be a progr=
am name with args.
 set dummy ${ac_tool_prefix}gcc; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_CC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_CC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
   ac_cv_prog_CC=3D"$CC" # Let the user override the test.
@@ -2671,25 +3153,25 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_prog_CC=3D"${ac_tool_prefix}gcc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 fi
 fi
 CC=3D$ac_cv_prog_CC
 if test -n "$CC"; then
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -2698,10 +3180,10 @@
   ac_ct_CC=3D$CC
   # Extract the first word of "gcc", so it can be a program name with args.
 set dummy gcc; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_CC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC=3D"$ac_ct_CC" # Let the user override the test.
@@ -2711,25 +3193,25 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_CC=3D"gcc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 fi
 fi
 ac_ct_CC=3D$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
   if test "x$ac_ct_CC" =3D x; then
@@ -2737,12 +3219,8 @@
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
 ac_tool_warned=3Dyes ;;
 esac
     CC=3D$ac_ct_CC
@@ -2755,10 +3233,10 @@
           if test -n "$ac_tool_prefix"; then
     # Extract the first word of "${ac_tool_prefix}cc", so it can be a prog=
ram name with args.
 set dummy ${ac_tool_prefix}cc; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_CC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_CC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
   ac_cv_prog_CC=3D"$CC" # Let the user override the test.
@@ -2768,25 +3246,25 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_prog_CC=3D"${ac_tool_prefix}cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 fi
 fi
 CC=3D$ac_cv_prog_CC
 if test -n "$CC"; then
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -2795,10 +3273,10 @@
 if test -z "$CC"; then
   # Extract the first word of "cc", so it can be a program name with args.
 set dummy cc; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_CC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_CC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
   ac_cv_prog_CC=3D"$CC" # Let the user override the test.
@@ -2809,18 +3287,18 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     if test "$as_dir/$ac_word$ac_exec_ext" =3D "/usr/ucb/cc"; then
        ac_prog_rejected=3Dyes
        continue
      fi
     ac_cv_prog_CC=3D"cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 if test $ac_prog_rejected =3D yes; then
@@ -2839,11 +3317,11 @@
 fi
 CC=3D$ac_cv_prog_CC
 if test -n "$CC"; then
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -2854,10 +3332,10 @@
   do
     # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a =
program name with args.
 set dummy $ac_tool_prefix$ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_CC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_CC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
   ac_cv_prog_CC=3D"$CC" # Let the user override the test.
@@ -2867,25 +3345,25 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_prog_CC=3D"$ac_tool_prefix$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 fi
 fi
 CC=3D$ac_cv_prog_CC
 if test -n "$CC"; then
-  { echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -2898,10 +3376,10 @@
 do
   # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
 set dummy $ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_CC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC=3D"$ac_ct_CC" # Let the user override the test.
@@ -2911,25 +3389,25 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_CC=3D"$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 fi
 fi
 ac_ct_CC=3D$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -2941,12 +3419,8 @@
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
 ac_tool_warned=3Dyes ;;
 esac
     CC=3D$ac_ct_CC
@@ -2956,98 +3430,80 @@
 fi
=20
=20
-test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler=
 found in \$PATH
-See \`config.log' for more details." >&5
-echo "$as_me: error: no acceptable C compiler found in \$PATH
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$a=
c_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "no acceptable C compiler found in \$PATH
+See \`config.log' for more details." "$LINENO" 5; }
=20
 # Provide some information about the compiler.
-echo "$as_me:$LINENO: checking for C compiler version" >&5
-ac_compiler=3D`set X $ac_compile; echo $2`
-{ (ac_try=3D"$ac_compiler --version >&5"
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=3D$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try=3D"$ac_compiler $ac_option >&5"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler --version >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-{ (ac_try=3D"$ac_compiler -v >&5"
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=3D$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }
+done
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=3D$ac_clean_files
+ac_clean_files=3D"$ac_clean_files a.out a.out.dSYM a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler w=
orks" >&5
+$as_echo_n "checking whether the C compiler works... " >&6; }
+ac_link_default=3D`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+
+# The possible output files:
+ac_files=3D"a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
+
+ac_rmfiles=3D
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    * ) ac_rmfiles=3D"$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { { ac_try=3D"$ac_link_default"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -v >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-{ (ac_try=3D"$ac_compiler -V >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -V >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-ac_clean_files_save=3D$ac_clean_files
-ac_clean_files=3D"$ac_clean_files a.out a.exe b.out"
-# Try to create an executable without -o first, disregard a.out.
-# It will help us diagnose broken compilers, and finding out an intuition
-# of exeext.
-{ echo "$as_me:$LINENO: checking for C compiler default output file name" =
>&5
-echo $ECHO_N "checking for C compiler default output file name... $ECHO_C"=
 >&6; }
-ac_link_default=3D`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-#
-# List of possible output files, starting from the most likely.
-# The algorithm is not robust to junk in `.', hence go to wildcards (a.*)
-# only as a last resort.  b.out is created by i960 compilers.
-ac_files=3D'a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.o=
ut'
-#
-# The IRIX 6 linker writes into existing files which may not be
-# executable, retaining their permissions.  Remove them first so a
-# subsequent execution test works.
-ac_rmfiles=3D
-for ac_file in $ac_files
-do
-  case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf | *.o | *.obj ) ;;
-    * ) ac_rmfiles=3D"$ac_rmfiles $ac_file";;
-  esac
-done
-rm -f $ac_rmfiles
-
-if { (ac_try=3D"$ac_link_default"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_link_default") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then :
   # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
 # So ignore a value of `no', otherwise this would lead to `EXEEXT =3D no'
 # in a Makefile.  We should not override ac_cv_exeext if it was cached,
@@ -3057,14 +3513,14 @@
 do
   test -f "$ac_file" || continue
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf | *.o | *.obj )
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf | *.dSYM | *.o | *.obj )
 	;;
     [ab].out )
 	# We found the default executable, but exeext=3D'' is most
 	# certainly right.
 	break;;
     *.* )
-        if test "${ac_cv_exeext+set}" =3D set && test "$ac_cv_exeext" !=3D=
 no;
+	if test "${ac_cv_exeext+set}" =3D set && test "$ac_cv_exeext" !=3D no;
 	then :; else
 	   ac_cv_exeext=3D`expr "$ac_file" : '[^.]*\(\..*\)'`
 	fi
@@ -3083,78 +3539,42 @@
 else
   ac_file=3D''
 fi
-
-{ echo "$as_me:$LINENO: result: $ac_file" >&5
-echo "${ECHO_T}$ac_file" >&6; }
-if test -z "$ac_file"; then
-  echo "$as_me: failed program was:" >&5
+if test -z "$ac_file"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+$as_echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
=20
-{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
-See \`config.log' for more details." >&5
-echo "$as_me: error: C compiler cannot create executables
-See \`config.log' for more details." >&2;}
-   { (exit 77); exit 77; }; }
-fi
-
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+{ as_fn_set_status 77
+as_fn_error "C compiler cannot create executables
+See \`config.log' for more details." "$LINENO" 5; }; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default o=
utput file name" >&5
+$as_echo_n "checking for C compiler default output file name... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+$as_echo "$ac_file" >&6; }
 ac_exeext=3D$ac_cv_exeext
=20
-# Check that the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5
-echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; }
-# FIXME: These cross compiler hacks should be removed for Autoconf 3.0
-# If not cross compiling, check that we can run a simple program.
-if test "$cross_compiling" !=3D yes; then
-  if { ac_try=3D'./$ac_file'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
-    cross_compiling=3Dno
-  else
-    if test "$cross_compiling" =3D maybe; then
-	cross_compiling=3Dyes
-    else
-	{ { echo "$as_me:$LINENO: error: cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-  fi
-fi
-{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-
-rm -f a.out a.exe conftest$ac_cv_exeext b.out
+rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
 ac_clean_files=3D$ac_clean_files_save
-# Check that the compiler produces executables we can run.  If not, either
-# the compiler is broken, or we cross compile.
-{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
-echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; }
-{ echo "$as_me:$LINENO: result: $cross_compiling" >&5
-echo "${ECHO_T}$cross_compiling" >&6; }
-
-{ echo "$as_me:$LINENO: checking for suffix of executables" >&5
-echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; }
-if { (ac_try=3D"$ac_link"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executable=
s" >&5
+$as_echo_n "checking for suffix of executables... " >&6; }
+if { { ac_try=3D"$ac_link"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_link") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then :
   # If both `conftest.exe' and `conftest' are `present' (well, observable)
 # catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
 # work properly (i.e., refer to `conftest.exe'), while it won't with
@@ -3162,93 +3582,141 @@
 for ac_file in conftest.exe conftest conftest.*; do
   test -f "$ac_file" || continue
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf | *.o | *.obj ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf | *.dSYM | *.o | *.obj ) ;;
     *.* ) ac_cv_exeext=3D`expr "$ac_file" : '[^.]*\(\..*\)'`
 	  break;;
     * ) break;;
   esac
 done
 else
-  { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: c=
annot compile and link
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute suffix of executables: cannot compile =
and link
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-rm -f conftest$ac_cv_exeext
-{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
-echo "${ECHO_T}$ac_cv_exeext" >&6; }
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." "$LINENO" 5; }
+fi
+rm -f conftest conftest$ac_cv_exeext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+$as_echo "$ac_cv_exeext" >&6; }
=20
 rm -f conftest.$ac_ext
 EXEEXT=3D$ac_cv_exeext
 ac_exeext=3D$EXEEXT
-{ echo "$as_me:$LINENO: checking for suffix of object files" >&5
-echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; }
-if test "${ac_cv_objext+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.o conftest.obj
-if { (ac_try=3D"$ac_compile"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+int
+main ()
+{
+FILE *f =3D fopen ("conftest.out", "w");
+ return ferror (f) || fclose (f) !=3D 0;
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files=3D"$ac_clean_files conftest.out"
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross com=
piling" >&5
+$as_echo_n "checking whether we are cross compiling... " >&6; }
+if test "$cross_compiling" !=3D yes; then
+  { { ac_try=3D"$ac_link"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }
+  if { ac_try=3D'./conftest$ac_cv_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
+  *) ac_try_echo=3D$ac_try;;
+esac
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; }; then
+    cross_compiling=3Dno
+  else
+    if test "$cross_compiling" =3D maybe; then
+	cross_compiling=3Dyes
+    else
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." "$LINENO" 5; }
+    fi
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+$as_echo "$cross_compiling" >&6; }
+
+rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
+ac_clean_files=3D$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object fil=
es" >&5
+$as_echo_n "checking for suffix of object files... " >&6; }
+if test "${ac_cv_objext+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { { ac_try=3D"$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
+  *) ac_try_echo=3D$ac_try;;
+esac
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_compile") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then :
   for ac_file in conftest.o conftest.obj conftest.*; do
   test -f "$ac_file" || continue;
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.=
map | *.inf | *.dSYM ) ;;
     *) ac_cv_objext=3D`expr "$ac_file" : '.*\.\(.*\)'`
        break;;
   esac
 done
 else
-  echo "$as_me: failed program was:" >&5
+  $as_echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
=20
-{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: ca=
nnot compile
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot compute suffix of object files: cannot compile
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." "$LINENO" 5; }
+fi
 rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
-echo "${ECHO_T}$ac_cv_objext" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+$as_echo "$ac_cv_objext" >&6; }
 OBJEXT=3D$ac_cv_objext
 ac_objext=3D$OBJEXT
-{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" =
>&5
-echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C"=
 >&6; }
-if test "${ac_cv_c_compiler_gnu+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the=
 GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if test "${ac_cv_c_compiler_gnu+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -3262,177 +3730,87 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_compiler_gnu=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_compiler_gnu=3Dno
-fi
-
+  ac_compiler_gnu=3Dno
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_cv_c_compiler_gnu=3D$ac_compiler_gnu
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; }
-GCC=3D`test $ac_compiler_gnu =3D yes && echo yes`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu =3D yes; then
+  GCC=3Dyes
+else
+  GCC=3D
+fi
 ac_test_CFLAGS=3D${CFLAGS+set}
 ac_save_CFLAGS=3D$CFLAGS
-{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
-echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; }
-if test "${ac_cv_prog_cc_g+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" =
>&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if test "${ac_cv_prog_cc_g+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_save_c_werror_flag=3D$ac_c_werror_flag
    ac_c_werror_flag=3Dyes
    ac_cv_prog_cc_g=3Dno
    CFLAGS=3D"-g"
-   cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_prog_cc_g=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	CFLAGS=3D""
-      cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_c_werror_flag=3D$ac_save_c_werror_flag
+  CFLAGS=3D""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=3D$ac_save_c_werror_flag
 	 CFLAGS=3D"-g"
-	 cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_prog_cc_g=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
    ac_c_werror_flag=3D$ac_save_c_werror_flag
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
 if test "$ac_test_CFLAGS" =3D set; then
   CFLAGS=3D$ac_save_CFLAGS
 elif test $ac_cv_prog_cc_g =3D yes; then
@@ -3448,18 +3826,14 @@
     CFLAGS=3D
   fi
 fi
-{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5
-echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; }
-if test "${ac_cv_prog_cc_c89+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept=
 ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if test "${ac_cv_prog_cc_c89+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_cv_prog_cc_c89=3Dno
 ac_save_CC=3D$CC
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdarg.h>
 #include <stdio.h>
@@ -3516,31 +3890,9 @@
 	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
 do
   CC=3D"$ac_save_CC $ac_arg"
-  rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+  if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_prog_cc_c89=3D$ac_arg
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
+fi
 rm -f core conftest.err conftest.$ac_objext
   test "x$ac_cv_prog_cc_c89" !=3D "xno" && break
 done
@@ -3551,41 +3903,228 @@
 # AC_CACHE_VAL
 case "x$ac_cv_prog_cc_c89" in
   x)
-    { echo "$as_me:$LINENO: result: none needed" >&5
-echo "${ECHO_T}none needed" >&6; } ;;
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
   xno)
-    { echo "$as_me:$LINENO: result: unsupported" >&5
-echo "${ECHO_T}unsupported" >&6; } ;;
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
   *)
     CC=3D"$CC $ac_cv_prog_cc_c89"
-    { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;;
-esac
-
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >=
&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" !=3D xno; then :
+
+fi
=20
 ac_ext=3Dc
 ac_cpp=3D'$CPP $CPPFLAGS'
 ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
 ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
+DEPDIR=3D"${am__leading_dot}deps"
+
+ac_config_commands=3D"$ac_config_commands depfiles"
+
+
+am_make=3D${MAKE-make}
+cat > confinc << 'END'
+am__doit:
+	@echo this is the am__doit target
+.PHONY: am__doit
+END
+# If we don't find an include directive, just comment out the code.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include use=
d by $am_make" >&5
+$as_echo_n "checking for style of include used by $am_make... " >&6; }
+am__include=3D"#"
+am__quote=3D
+_am_result=3Dnone
+# First try GNU make style include.
+echo "include confinc" > confmf
+# Ignore all kinds of additional output from `make'.
+case `$am_make -s -f confmf 2> /dev/null` in #(
+*the\ am__doit\ target*)
+  am__include=3Dinclude
+  am__quote=3D
+  _am_result=3DGNU
+  ;;
+esac
+# Now try BSD make style include.
+if test "$am__include" =3D "#"; then
+   echo '.include "confinc"' > confmf
+   case `$am_make -s -f confmf 2> /dev/null` in #(
+   *the\ am__doit\ target*)
+     am__include=3D.include
+     am__quote=3D"\""
+     _am_result=3DBSD
+     ;;
+   esac
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5
+$as_echo "$_am_result" >&6; }
+rm -f confinc confmf
+
+# Check whether --enable-dependency-tracking was given.
+if test "${enable_dependency_tracking+set}" =3D set; then :
+  enableval=3D$enable_dependency_tracking;
+fi
+
+if test "x$enable_dependency_tracking" !=3D xno; then
+  am_depcomp=3D"$ac_aux_dir/depcomp"
+  AMDEPBACKSLASH=3D'\'
+fi
+ if test "x$enable_dependency_tracking" !=3D xno; then
+  AMDEP_TRUE=3D
+  AMDEP_FALSE=3D'#'
+else
+  AMDEP_TRUE=3D'#'
+  AMDEP_FALSE=3D
+fi
+
+
+
+depcc=3D"$CC"   am_compiler_list=3D
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $dep=
cc" >&5
+$as_echo_n "checking dependency style of $depcc... " >&6; }
+if test "${am_cv_CC_dependencies_compiler_type+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then
+  # We make a subdir and do the tests there.  Otherwise we can end up
+  # making bogus files that we don't know about and never remove.  For
+  # instance it was reported that on HP-UX the gcc test will end up
+  # making a dummy file named `D' -- because `-MD' means `put the output
+  # in D'.
+  mkdir conftest.dir
+  # Copy depcomp to subdir because otherwise we won't find it if we're
+  # using a relative directory.
+  cp "$am_depcomp" conftest.dir
+  cd conftest.dir
+  # We will build objects and dependencies in a subdirectory because
+  # it helps to detect inapplicable dependency modes.  For instance
+  # both Tru64's cc and ICC support -MD to output dependencies as a
+  # side effect of compilation, but ICC will put the dependencies in
+  # the current directory while Tru64 will put them in the object
+  # directory.
+  mkdir sub
+
+  am_cv_CC_dependencies_compiler_type=3Dnone
+  if test "$am_compiler_list" =3D ""; then
+     am_compiler_list=3D`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp`
+  fi
+  am__universal=3Dfalse
+  case " $depcc " in #(
+     *\ -arch\ *\ -arch\ *) am__universal=3Dtrue ;;
+     esac
+
+  for depmode in $am_compiler_list; do
+    # Setup a source with many dependencies, because some compilers
+    # like to wrap large dependency lists on column 80 (with \), and
+    # we should not choose a depcomp mode which is confused by this.
+    #
+    # We need to recreate these files for each test, as the compiler may
+    # overwrite some of them when testing with obscure command lines.
+    # This happens at least with the AIX C compiler.
+    : > sub/conftest.c
+    for i in 1 2 3 4 5 6; do
+      echo '#include "conftst'$i'.h"' >> sub/conftest.c
+      # Using `: > sub/conftst$i.h' creates only sub/conftst1.h with
+      # Solaris 8's {/usr,}/bin/sh.
+      touch sub/conftst$i.h
+    done
+    echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf
+
+    # We check with `-c' and `-o' for the sake of the "dashmstdout"
+    # mode.  It turns out that the SunPro C++ compiler does not properly
+    # handle `-M -o', and we need to detect this.  Also, some Intel
+    # versions had trouble with output in subdirs
+    am__obj=3Dsub/conftest.${OBJEXT-o}
+    am__minus_obj=3D"-o $am__obj"
+    case $depmode in
+    gcc)
+      # This depmode causes a compiler race in universal mode.
+      test "$am__universal" =3D false || continue
+      ;;
+    nosideeffect)
+      # after this tag, mechanisms are not by side-effect, so they'll
+      # only be used when explicitly requested
+      if test "x$enable_dependency_tracking" =3D xyes; then
+	continue
+      else
+	break
+      fi
+      ;;
+    msvisualcpp | msvcmsys)
+      # This compiler won't grok `-c -o', but also, the minuso test has
+      # not run yet.  These depmodes are late enough in the game, and
+      # so weak that their functioning should not be impacted.
+      am__obj=3Dconftest.${OBJEXT-o}
+      am__minus_obj=3D
+      ;;
+    none) break ;;
+    esac
+    if depmode=3D$depmode \
+       source=3Dsub/conftest.c object=3D$am__obj \
+       depfile=3Dsub/conftest.Po tmpdepfile=3Dsub/conftest.TPo \
+       $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \
+         >/dev/null 2>conftest.err &&
+       grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
+       grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
+       grep $am__obj sub/conftest.Po > /dev/null 2>&1 &&
+       ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
+      # icc doesn't choke on unknown options, it will just issue warnings
+      # or remarks (even with -Werror).  So we grep stderr for any message
+      # that says an option was ignored or not supported.
+      # When given -MP, icc 7.0 and 7.1 complain thusly:
+      #   icc: Command line warning: ignoring option '-M'; no argument req=
uired
+      # The diagnosis changed in icc 8.0:
+      #   icc: Command line remark: option '-MP' not supported
+      if (grep 'ignoring option' conftest.err ||
+          grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
+        am_cv_CC_dependencies_compiler_type=3D$depmode
+        break
+      fi
+    fi
+  done
+
+  cd ..
+  rm -rf conftest.dir
+else
+  am_cv_CC_dependencies_compiler_type=3Dnone
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_co=
mpiler_type" >&5
+$as_echo "$am_cv_CC_dependencies_compiler_type" >&6; }
+CCDEPMODE=3Ddepmode=3D$am_cv_CC_dependencies_compiler_type
+
+ if
+  test "x$enable_dependency_tracking" !=3D xno \
+  && test "$am_cv_CC_dependencies_compiler_type" =3D gcc3; then
+  am__fastdepCC_TRUE=3D
+  am__fastdepCC_FALSE=3D'#'
+else
+  am__fastdepCC_TRUE=3D'#'
+  am__fastdepCC_FALSE=3D
+fi
+
=20
 if test "x$CC" !=3D xcc; then
-  { echo "$as_me:$LINENO: checking whether $CC and cc understand -c and -o=
 together" >&5
-echo $ECHO_N "checking whether $CC and cc understand -c and -o together...=
 $ECHO_C" >&6; }
-else
-  { echo "$as_me:$LINENO: checking whether cc understands -c and -o togeth=
er" >&5
-echo $ECHO_N "checking whether cc understands -c and -o together... $ECHO_=
C" >&6; }
-fi
-set dummy $CC; ac_cc=3D`echo $2 |
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC and cc und=
erstand -c and -o together" >&5
+$as_echo_n "checking whether $CC and cc understand -c and -o together... "=
 >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cc understands=
 -c and -o together" >&5
+$as_echo_n "checking whether cc understands -c and -o together... " >&6; }
+fi
+set dummy $CC; ac_cc=3D`$as_echo "$2" |
 		      sed 's/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/'`
-if { as_var=3Dac_cv_prog_cc_${ac_cc}_c_o; eval "test \"\${$as_var+set}\" =
=3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+if { as_var=3Dac_cv_prog_cc_${ac_cc}_c_o; eval "test \"\${$as_var+set}\" =
=3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -3601,58 +4140,63 @@
 # existing .o file with -o, though they will create one.
 ac_try=3D'$CC -c conftest.$ac_ext -o conftest2.$ac_objext >&5'
 rm -f conftest2.*
-if { (case "(($ac_try" in
+if { { case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_try") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } &&
-   test -f conftest2.$ac_objext && { (case "(($ac_try" in
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } &&
+   test -f conftest2.$ac_objext && { { case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_try") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); };
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; };
 then
   eval ac_cv_prog_cc_${ac_cc}_c_o=3Dyes
   if test "x$CC" !=3D xcc; then
     # Test first that cc exists at all.
     if { ac_try=3D'cc -c conftest.$ac_ext >&5'
-  { (case "(($ac_try" in
+  { { case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_try") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; }; then
       ac_try=3D'cc -c conftest.$ac_ext -o conftest2.$ac_objext >&5'
       rm -f conftest2.*
-      if { (case "(($ac_try" in
+      if { { case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_try") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } &&
-	 test -f conftest2.$ac_objext && { (case "(($ac_try" in
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } &&
+	 test -f conftest2.$ac_objext && { { case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
   (eval "$ac_try") 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); };
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; };
       then
 	# cc works too.
 	:
@@ -3669,23 +4213,22 @@
=20
 fi
 if eval test \$ac_cv_prog_cc_${ac_cc}_c_o =3D yes; then
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-
-cat >>confdefs.h <<\_ACEOF
-#define NO_MINUS_C_MINUS_O 1
-_ACEOF
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+
+$as_echo "#define NO_MINUS_C_MINUS_O 1" >>confdefs.h
=20
 fi
=20
 # FIXME: we rely on the cache variable name because
 # there is no other way.
 set dummy $CC
-ac_cc=3D`echo $2 | sed 's/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/'`
-if eval "test \"`echo '$ac_cv_prog_cc_'${ac_cc}_c_o`\" !=3D yes"; then
+am_cc=3D`echo $2 | sed 's/[^a-zA-Z0-9_]/_/g;s/^[0-9]/_/'`
+eval am_t=3D\$ac_cv_prog_cc_${am_cc}_c_o
+if test "$am_t" !=3D yes; then
    # Losing compiler, so override with the script.
    # FIXME: It is wrong to rewrite CC.
    # But if we don't then we get into trouble of one sort or another.
@@ -3700,15 +4243,15 @@
 ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
 ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
-{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
-echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preproc=
essor" >&5
+$as_echo_n "checking how to run the C preprocessor... " >&6; }
 # On Suns, sometimes $CPP names a directory.
 if test -n "$CPP" && test -d "$CPP"; then
   CPP=3D
 fi
 if test -z "$CPP"; then
-  if test "${ac_cv_prog_CPP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  if test "${ac_cv_prog_CPP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
       # Double quotes because CPP needs to be expanded
     for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
@@ -3722,11 +4265,7 @@
   # <limits.h> exists even on freestanding compilers.
   # On the NeXT, cc -E runs the code through the compiler's parser,
   # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef __STDC__
 # include <limits.h>
@@ -3735,76 +4274,34 @@
 #endif
 		     Syntax error
 _ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
   # Broken: fails on valid input.
 continue
 fi
-
 rm -f conftest.err conftest.$ac_ext
=20
   # OK, works on sane cases.  Now check whether nonexistent headers
   # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+if ac_fn_c_try_cpp "$LINENO"; then :
   # Broken: success on invalid input.
 continue
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
   # Passes both tests.
 ac_preproc_ok=3D:
 break
 fi
-
 rm -f conftest.err conftest.$ac_ext
=20
 done
 # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
 rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
+if $ac_preproc_ok; then :
   break
 fi
=20
@@ -3816,8 +4313,8 @@
 else
   ac_cv_prog_CPP=3D$CPP
 fi
-{ echo "$as_me:$LINENO: result: $CPP" >&5
-echo "${ECHO_T}$CPP" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+$as_echo "$CPP" >&6; }
 ac_preproc_ok=3Dfalse
 for ac_c_preproc_warn_flag in '' yes
 do
@@ -3827,11 +4324,7 @@
   # <limits.h> exists even on freestanding compilers.
   # On the NeXT, cc -E runs the code through the compiler's parser,
   # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef __STDC__
 # include <limits.h>
@@ -3840,83 +4333,40 @@
 #endif
 		     Syntax error
 _ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
   # Broken: fails on valid input.
 continue
 fi
-
 rm -f conftest.err conftest.$ac_ext
=20
   # OK, works on sane cases.  Now check whether nonexistent headers
   # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+if ac_fn_c_try_cpp "$LINENO"; then :
   # Broken: success on invalid input.
 continue
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
   # Passes both tests.
 ac_preproc_ok=3D:
 break
 fi
-
 rm -f conftest.err conftest.$ac_ext
=20
 done
 # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
 rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
-  :
-else
-  { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity ch=
eck
-See \`config.log' for more details." >&5
-echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
+if $ac_preproc_ok; then :
+
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." "$LINENO" 5; }
 fi
=20
 ac_ext=3Dc
@@ -3925,43 +4375,54 @@
 ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
 ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
=20
-
-
-
-test "$sysconfdir" =3D '${prefix}/etc' && sysconfdir=3D'/etc'
-test "$localstatedir" =3D '${prefix}/var' && localstatedir=3D'/var/heimdal'
+case `pwd` in
+  *\ * | *\	*)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cop=
e well with whitespace in \`pwd\`" >&5
+$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \=
`pwd\`" >&2;} ;;
+esac
+
+
+
+macro_version=3D'2.4'
+macro_revision=3D'1.3293'
+
+
+
+
+
+
+
+
+
+
+
+
+
+ltmain=3D"$ac_aux_dir/ltmain.sh"
=20
 # Make sure we can run config.sub.
 $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
-  { { echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.su=
b" >&5
-echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;}
-   { (exit 1); exit 1; }; }
-
-{ echo "$as_me:$LINENO: checking build system type" >&5
-echo $ECHO_N "checking build system type... $ECHO_C" >&6; }
-if test "${ac_cv_build+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  as_fn_error "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
+$as_echo_n "checking build system type... " >&6; }
+if test "${ac_cv_build+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_build_alias=3D$build_alias
 test "x$ac_build_alias" =3D x &&
   ac_build_alias=3D`$SHELL "$ac_aux_dir/config.guess"`
 test "x$ac_build_alias" =3D x &&
-  { { echo "$as_me:$LINENO: error: cannot guess build type; you must speci=
fy one" >&5
-echo "$as_me: error: cannot guess build type; you must specify one" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "cannot guess build type; you must specify one" "$LINENO" 5
 ac_cv_build=3D`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
-  { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build=
_alias failed" >&5
-echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed"=
 >&2;}
-   { (exit 1); exit 1; }; }
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_build" >&5
-echo "${ECHO_T}$ac_cv_build" >&6; }
+  as_fn_error "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LIN=
ENO" 5
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
+$as_echo "$ac_cv_build" >&6; }
 case $ac_cv_build in
 *-*-*) ;;
-*) { { echo "$as_me:$LINENO: error: invalid value of canonical build" >&5
-echo "$as_me: error: invalid value of canonical build" >&2;}
-   { (exit 1); exit 1; }; };;
+*) as_fn_error "invalid value of canonical build" "$LINENO" 5;;
 esac
 build=3D$ac_cv_build
 ac_save_IFS=3D$IFS; IFS=3D'-'
@@ -3977,28 +4438,24 @@
 case $build_os in *\ *) build_os=3D`echo "$build_os" | sed 's/ /-/g'`;; es=
ac
=20
=20
-{ echo "$as_me:$LINENO: checking host system type" >&5
-echo $ECHO_N "checking host system type... $ECHO_C" >&6; }
-if test "${ac_cv_host+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
+$as_echo_n "checking host system type... " >&6; }
+if test "${ac_cv_host+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test "x$host_alias" =3D x; then
   ac_cv_host=3D$ac_cv_build
 else
   ac_cv_host=3D`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
-    { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_a=
lias failed" >&5
-echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2=
;}
-   { (exit 1); exit 1; }; }
-fi
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_host" >&5
-echo "${ECHO_T}$ac_cv_host" >&6; }
+    as_fn_error "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINEN=
O" 5
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
+$as_echo "$ac_cv_host" >&6; }
 case $ac_cv_host in
 *-*-*) ;;
-*) { { echo "$as_me:$LINENO: error: invalid value of canonical host" >&5
-echo "$as_me: error: invalid value of canonical host" >&2;}
-   { (exit 1); exit 1; }; };;
+*) as_fn_error "invalid value of canonical host" "$LINENO" 5;;
 esac
 host=3D$ac_cv_host
 ac_save_IFS=3D$IFS; IFS=3D'-'
@@ -4014,1126 +4471,191 @@
 case $host_os in *\ *) host_os=3D`echo "$host_os" | sed 's/ /-/g'`;; esac
=20
=20
-CANONICAL_HOST=3D$host
-
-
-
-
-
-
-	{ echo "$as_me:$LINENO: autobuild project... ${PACKAGE_NAME:-$PACKAGE}" >=
&5
-echo "$as_me: autobuild project... ${PACKAGE_NAME:-$PACKAGE}" >&6;}
-	{ echo "$as_me:$LINENO: autobuild revision... ${PACKAGE_VERSION:-$VERSION=
}" >&5
-echo "$as_me: autobuild revision... ${PACKAGE_VERSION:-$VERSION}" >&6;}
-	hostname=3D`hostname`
-	if test "$hostname"; then
-	   { echo "$as_me:$LINENO: autobuild hostname... $hostname" >&5
-echo "$as_me: autobuild hostname... $hostname" >&6;}
-	fi
-
-	date=3D`date +%Y%m%d-%H%M%S`
-	if test "$?" !=3D 0; then
-	   date=3D`date`
-	fi
-	if test "$date"; then
-	   { echo "$as_me:$LINENO: autobuild timestamp... $date" >&5
-echo "$as_me: autobuild timestamp... $date" >&6;}
-	fi
-
-
-
-# Check whether --enable-largefile was given.
-if test "${enable_largefile+set}" =3D set; then
-  enableval=3D$enable_largefile;
-fi
-
-if test "$enable_largefile" !=3D no; then
-
-  { echo "$as_me:$LINENO: checking for special C compiler options needed f=
or large files" >&5
-echo $ECHO_N "checking for special C compiler options needed for large fil=
es... $ECHO_C" >&6; }
-if test "${ac_cv_sys_largefile_CC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_cv_sys_largefile_CC=3Dno
-     if test "$GCC" !=3D yes; then
-       ac_save_CC=3D$CC
-       while :; do
-	 # IRIX 6.2 and later do not support large files by default,
-	 # so use the C compiler's -n32 option if that helps.
-	 cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
-		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-	 rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext
-	 CC=3D"$CC -n32"
-	 rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_sys_largefile_CC=3D' -n32'; break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext
-	 break
-       done
-       CC=3D$ac_save_CC
-       rm -f conftest.$ac_ext
-    fi
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sys_largefile_CC" >&5
-echo "${ECHO_T}$ac_cv_sys_largefile_CC" >&6; }
-  if test "$ac_cv_sys_largefile_CC" !=3D no; then
-    CC=3D$CC$ac_cv_sys_largefile_CC
-  fi
-
-  { echo "$as_me:$LINENO: checking for _FILE_OFFSET_BITS value needed for =
large files" >&5
-echo $ECHO_N "checking for _FILE_OFFSET_BITS value needed for large files.=
.. $ECHO_C" >&6; }
-if test "${ac_cv_sys_file_offset_bits+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  while :; do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
-		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_sys_file_offset_bits=3Dno; break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#define _FILE_OFFSET_BITS 64
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
-		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_sys_file_offset_bits=3D64; break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_cv_sys_file_offset_bits=3Dunknown
-  break
-done
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sys_file_offset_bits" >&5
-echo "${ECHO_T}$ac_cv_sys_file_offset_bits" >&6; }
-case $ac_cv_sys_file_offset_bits in #(
-  no | unknown) ;;
-  *)
-cat >>confdefs.h <<_ACEOF
-#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits
-_ACEOF
-;;
-esac
-rm -f conftest*
-  if test $ac_cv_sys_file_offset_bits =3D unknown; then
-    { echo "$as_me:$LINENO: checking for _LARGE_FILES value needed for lar=
ge files" >&5
-echo $ECHO_N "checking for _LARGE_FILES value needed for large files... $E=
CHO_C" >&6; }
-if test "${ac_cv_sys_large_files+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  while :; do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
-		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_sys_large_files=3Dno; break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#define _LARGE_FILES 1
-#include <sys/types.h>
- /* Check that off_t can represent 2**63 - 1 correctly.
-    We can't simply define LARGE_OFF_T to be 9223372036854775807,
-    since some C++ compilers masquerading as C compilers
-    incorrectly reject 9223372036854775807.  */
-#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
-  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
-		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
-		      ? 1 : -1];
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_sys_large_files=3D1; break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_cv_sys_large_files=3Dunknown
-  break
-done
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sys_large_files" >&5
-echo "${ECHO_T}$ac_cv_sys_large_files" >&6; }
-case $ac_cv_sys_large_files in #(
-  no | unknown) ;;
-  *)
-cat >>confdefs.h <<_ACEOF
-#define _LARGE_FILES $ac_cv_sys_large_files
-_ACEOF
-;;
-esac
-rm -f conftest*
-  fi
-fi
-
-
-if test "$enable_largefile" !=3D no -a "$ac_cv_sys_large_files" !=3D no; t=
hen
-	CPPFLAGS=3D"$CPPFLAGS -D_LARGE_FILES=3D$ac_cv_sys_large_files"
-fi
-if test "$enable_largefile" !=3D no -a "$ac_cv_sys_file_offset_bits" !=3D =
no; then
-	CPPFLAGS=3D"$CPPFLAGS -D_FILE_OFFSET_BITS=3D$ac_cv_sys_file_offset_bits"
-fi
-
-
-
-cat >>confdefs.h <<\_ACEOF
-#define _GNU_SOURCE 1
-_ACEOF
-
-
-
-
-
-for ac_prog in 'bison -y' byacc
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
-set dummy $ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_YACC+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$YACC"; then
-  ac_cv_prog_YACC=3D"$YACC" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_YACC=3D"$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-YACC=3D$ac_cv_prog_YACC
-if test -n "$YACC"; then
-  { echo "$as_me:$LINENO: result: $YACC" >&5
-echo "${ECHO_T}$YACC" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-  test -n "$YACC" && break
-done
-test -n "$YACC" || YACC=3D"yacc"
-
-for ac_prog in flex lex
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
-set dummy $ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_LEX+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$LEX"; then
-  ac_cv_prog_LEX=3D"$LEX" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_LEX=3D"$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-LEX=3D$ac_cv_prog_LEX
-if test -n "$LEX"; then
-  { echo "$as_me:$LINENO: result: $LEX" >&5
-echo "${ECHO_T}$LEX" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-  test -n "$LEX" && break
-done
-test -n "$LEX" || LEX=3D":"
-
-if test "x$LEX" !=3D "x:"; then
-  cat >conftest.l <<_ACEOF
-%%
-a { ECHO; }
-b { REJECT; }
-c { yymore (); }
-d { yyless (1); }
-e { yyless (input () !=3D 0); }
-f { unput (yytext[0]); }
-. { BEGIN INITIAL; }
-%%
-#ifdef YYTEXT_POINTER
-extern char *yytext;
-#endif
-int
-main (void)
-{
-  return ! yylex () + ! yywrap ();
-}
-_ACEOF
-{ (ac_try=3D"$LEX conftest.l"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$LEX conftest.l") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-{ echo "$as_me:$LINENO: checking lex output file root" >&5
-echo $ECHO_N "checking lex output file root... $ECHO_C" >&6; }
-if test "${ac_cv_prog_lex_root+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-if test -f lex.yy.c; then
-  ac_cv_prog_lex_root=3Dlex.yy
-elif test -f lexyy.c; then
-  ac_cv_prog_lex_root=3Dlexyy
-else
-  { { echo "$as_me:$LINENO: error: cannot find output from $LEX; giving up=
" >&5
-echo "$as_me: error: cannot find output from $LEX; giving up" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_lex_root" >&5
-echo "${ECHO_T}$ac_cv_prog_lex_root" >&6; }
-LEX_OUTPUT_ROOT=3D$ac_cv_prog_lex_root
-
-if test -z "${LEXLIB+set}"; then
-  { echo "$as_me:$LINENO: checking lex library" >&5
-echo $ECHO_N "checking lex library... $ECHO_C" >&6; }
-if test "${ac_cv_lib_lex+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-    ac_save_LIBS=3D$LIBS
-    ac_cv_lib_lex=3D'none needed'
-    for ac_lib in '' -lfl -ll; do
-      LIBS=3D"$ac_lib $ac_save_LIBS"
-      cat >conftest.$ac_ext <<_ACEOF
-`cat $LEX_OUTPUT_ROOT.c`
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_lex=3D$ac_lib
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-      test "$ac_cv_lib_lex" !=3D 'none needed' && break
+# Backslashify metacharacters that are still active within
+# double-quoted strings.
+sed_quote_subst=3D's/\(["`$\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst=3D's/\(["`\\]\)/\\\1/g'
+
+# Sed substitution to delay expansion of an escaped shell variable in a
+# double_quote_subst'ed string.
+delay_variable_subst=3D's/\\\\\\\\\\\$/\\\\\\$/g'
+
+# Sed substitution to delay expansion of an escaped single quote.
+delay_single_quote_subst=3D's/'\''/'\'\\\\\\\'\''/g'
+
+# Sed substitution to avoid accidental globbing in evaled expressions
+no_glob_subst=3D's/\*/\\\*/g'
+
+ECHO=3D'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\=
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+ECHO=3D$ECHO$ECHO$ECHO$ECHO$ECHO
+ECHO=3D$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5
+$as_echo_n "checking how to print strings... " >&6; }
+# Test print first, because it will be a builtin if present.
+if test "X`( print -r -- -n ) 2>/dev/null`" =3D X-n && \
+   test "X`print -r -- $ECHO 2>/dev/null`" =3D "X$ECHO"; then
+  ECHO=3D'print -r --'
+elif test "X`printf %s $ECHO 2>/dev/null`" =3D "X$ECHO"; then
+  ECHO=3D'printf %s\n'
+else
+  # Use this function as a fallback that always works.
+  func_fallback_echo ()
+  {
+    eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+  }
+  ECHO=3D'func_fallback_echo'
+fi
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO ""
+}
+
+case "$ECHO" in
+  printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5
+$as_echo "printf" >&6; } ;;
+  print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5
+$as_echo "print -r" >&6; } ;;
+  *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5
+$as_echo "cat" >&6; } ;;
+esac
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not =
truncate output" >&5
+$as_echo_n "checking for a sed that does not truncate output... " >&6; }
+if test "${ac_cv_path_SED+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+            ac_script=3Ds/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbb=
bbbbbbbbbbbbbbbbbbbbb/
+     for ac_i in 1 2 3 4 5 6 7; do
+       ac_script=3D"$ac_script$as_nl$ac_script"
+     done
+     echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed
+     { ac_script=3D; unset ac_script;}
+     if test -z "$SED"; then
+  ac_path_SED_found=3Dfalse
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_prog in sed gsed; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_SED=3D"$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_SED" && $as_test_x "$ac_path_SED"; } || continue
+# Check for GNU ac_path_SED and select it if it is found.
+  # Check for GNU $ac_path_SED
+case `"$ac_path_SED" --version 2>&1` in
+*GNU*)
+  ac_cv_path_SED=3D"$ac_path_SED" ac_path_SED_found=3D:;;
+*)
+  ac_count=3D0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo '' >> "conftest.nl"
+    "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/=
null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=3D$as_val
+    if test $ac_count -gt ${ac_path_SED_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_SED=3D"$ac_path_SED"
+      ac_path_SED_max=3D$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_SED_found && break 3
     done
-    LIBS=3D$ac_save_LIBS
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_lex" >&5
-echo "${ECHO_T}$ac_cv_lib_lex" >&6; }
-  test "$ac_cv_lib_lex" !=3D 'none needed' && LEXLIB=3D$ac_cv_lib_lex
-fi
-
-
-{ echo "$as_me:$LINENO: checking whether yytext is a pointer" >&5
-echo $ECHO_N "checking whether yytext is a pointer... $ECHO_C" >&6; }
-if test "${ac_cv_prog_lex_yytext_pointer+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  # POSIX says lex can declare yytext either as a pointer or an array; the
-# default is implementation-dependent.  Figure out which it is, since
-# not all implementations provide the %pointer and %array declarations.
-ac_cv_prog_lex_yytext_pointer=3Dno
-ac_save_LIBS=3D$LIBS
-LIBS=3D"$LEXLIB $ac_save_LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-#define YYTEXT_POINTER 1
-`cat $LEX_OUTPUT_ROOT.c`
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_prog_lex_yytext_pointer=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=3D$ac_save_LIBS
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_lex_yytext_pointer" >&5
-echo "${ECHO_T}$ac_cv_prog_lex_yytext_pointer" >&6; }
-if test $ac_cv_prog_lex_yytext_pointer =3D yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define YYTEXT_POINTER 1
-_ACEOF
-
-fi
-rm -f conftest.l $LEX_OUTPUT_ROOT.c
-
-fi
-if test "$LEX" =3D :; then
-  LEX=3D${am_missing_run}flex
-fi
-for ac_prog in gawk mawk nawk awk
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
-set dummy $ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_AWK+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$AWK"; then
-  ac_cv_prog_AWK=3D"$AWK" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_AWK=3D"$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-AWK=3D$ac_cv_prog_AWK
-if test -n "$AWK"; then
-  { echo "$as_me:$LINENO: result: $AWK" >&5
-echo "${ECHO_T}$AWK" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-  test -n "$AWK" && break
-done
-
-{ echo "$as_me:$LINENO: checking for ln -s or something else" >&5
-echo $ECHO_N "checking for ln -s or something else... $ECHO_C" >&6; }
-if test "${ac_cv_prog_LN_S+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  rm -f conftestdata
-if ln -s X conftestdata 2>/dev/null
-then
-  rm -f conftestdata
-  ac_cv_prog_LN_S=3D"ln -s"
-else
-  touch conftestdata1
-  if ln conftestdata1 conftestdata2; then
-    rm -f conftestdata*
-    ac_cv_prog_LN_S=3Dln
-  else
-    ac_cv_prog_LN_S=3Dcp
-  fi
-fi
-fi
-LN_S=3D"$ac_cv_prog_LN_S"
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_LN_S" >&5
-echo "${ECHO_T}$ac_cv_prog_LN_S" >&6; }
-
-
-
-
-# Check whether --with-mips_abi was given.
-if test "${with_mips_abi+set}" =3D set; then
-  withval=3D$with_mips_abi;
-fi
-
-
-case "$host_os" in
-irix*)
-with_mips_abi=3D"${with_mips_abi:-yes}"
-if test -n "$GCC"; then
-
-# GCC < 2.8 only supports the O32 ABI. GCC >=3D 2.8 has a flag to select
-# which ABI to use, but only supports (as of 2.8.1) the N32 and 64 ABIs.
-#
-# Default to N32, but if GCC doesn't grok -mabi=3Dn32, we assume an old
-# GCC and revert back to O32. The same goes if O32 is asked for - old
-# GCCs doesn't like the -mabi option, and new GCCs can't output O32.
-#
-# Don't you just love *all* the different SGI ABIs?
-
-case "${with_mips_abi}" in
-        32|o32) abi=3D'-mabi=3D32';  abilibdirext=3D''     ;;
-       n32|yes) abi=3D'-mabi=3Dn32'; abilibdirext=3D'32'  ;;
-        64) abi=3D'-mabi=3D64';  abilibdirext=3D'64'   ;;
-	no) abi=3D''; abilibdirext=3D'';;
-         *) { { echo "$as_me:$LINENO: error: \"Invalid ABI specified\"" >&5
-echo "$as_me: error: \"Invalid ABI specified\"" >&2;}
-   { (exit 1); exit 1; }; } ;;
-esac
-if test -n "$abi" ; then
-ac_foo=3Dkrb_cv_gcc_`echo $abi | tr =3D- __`
-{ echo "$as_me:$LINENO: checking if $CC supports the $abi option" >&5
-echo $ECHO_N "checking if $CC supports the $abi option... $ECHO_C" >&6; }
-if { as_var=3D$ac_foo; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-save_CFLAGS=3D"$CFLAGS"
-CFLAGS=3D"$CFLAGS $abi"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-int x;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval $ac_foo=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval $ac_foo=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_extCFLAGS=3D"$sav=
e_CFLAGS"
-
-fi
-
-ac_res=3D`eval echo \\\$$ac_foo`
-{ echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test $ac_res =3D no; then
-# Try to figure out why that failed...
-case $abi in
-	-mabi=3D32)
-	save_CFLAGS=3D"$CFLAGS"
-	CFLAGS=3D"$CFLAGS -mabi=3Dn32"
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-int x;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_res=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_res=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext	CLAGS=3D"$sav=
e_CFLAGS"
-	if test $ac_res =3D yes; then
-		# New GCC
-		{ { echo "$as_me:$LINENO: error: $CC does not support the $with_mips_abi=
 ABI" >&5
-echo "$as_me: error: $CC does not support the $with_mips_abi ABI" >&2;}
-   { (exit 1); exit 1; }; }
-	fi
-	# Old GCC
-	abi=3D''
-	abilibdirext=3D''
-	;;
-	-mabi=3Dn32|-mabi=3D64)
-		if test $with_mips_abi =3D yes; then
-			# Old GCC, default to O32
-			abi=3D''
-			abilibdirext=3D''
-		else
-			# Some broken GCC
-			{ { echo "$as_me:$LINENO: error: $CC does not support the $with_mips_ab=
i ABI" >&5
-echo "$as_me: error: $CC does not support the $with_mips_abi ABI" >&2;}
-   { (exit 1); exit 1; }; }
-		fi
-	;;
-esac
-fi #if test $ac_res =3D no; then
-fi #if test -n "$abi" ; then
-else
-case "${with_mips_abi}" in
-        32|o32) abi=3D'-32'; abilibdirext=3D''     ;;
-       n32|yes) abi=3D'-n32'; abilibdirext=3D'32'  ;;
-        64) abi=3D'-64'; abilibdirext=3D'64'   ;;
-	no) abi=3D''; abilibdirext=3D'';;
-         *) { { echo "$as_me:$LINENO: error: \"Invalid ABI specified\"" >&5
-echo "$as_me: error: \"Invalid ABI specified\"" >&2;}
-   { (exit 1); exit 1; }; } ;;
-esac
-fi #if test -n "$GCC"; then
-;;
-esac
-
-CC=3D"$CC $abi"
-libdir=3D"$libdir$abilibdirext"
-
-
-{ echo "$as_me:$LINENO: checking for __attribute__" >&5
-echo $ECHO_N "checking for __attribute__... $ECHO_C" >&6; }
-if test "${ac_cv___attribute__+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdlib.h>
-static void foo(void) __attribute__ ((noreturn));
-
-static void
-foo(void)
-{
-  exit(1);
-}
-
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv___attribute__=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv___attribute__=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-
-if test "$ac_cv___attribute__" =3D "yes"; then
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE___ATTRIBUTE__ 1
-_ACEOF
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv___attribute__" >&5
-echo "${ECHO_T}$ac_cv___attribute__" >&6; }
-
-
-# Check whether --enable-shared was given.
-if test "${enable_shared+set}" =3D set; then
-  enableval=3D$enable_shared; p=3D${PACKAGE-default}
-    case $enableval in
-    yes) enable_shared=3Dyes ;;
-    no) enable_shared=3Dno ;;
-    *)
-      enable_shared=3Dno
-      # Look at the argument we got.  We use all the common list separator=
s.
-      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS=3D"$lt_save_ifs"
-	if test "X$pkg" =3D "X$p"; then
-	  enable_shared=3Dyes
-	fi
-      done
-      IFS=3D"$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_shared=3Dyes
-fi
-
-
-# Check whether --enable-static was given.
-if test "${enable_static+set}" =3D set; then
-  enableval=3D$enable_static; p=3D${PACKAGE-default}
-    case $enableval in
-    yes) enable_static=3Dyes ;;
-    no) enable_static=3Dno ;;
-    *)
-     enable_static=3Dno
-      # Look at the argument we got.  We use all the common list separator=
s.
-      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS=3D"$lt_save_ifs"
-	if test "X$pkg" =3D "X$p"; then
-	  enable_static=3Dyes
-	fi
-      done
-      IFS=3D"$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_static=3Dyes
-fi
-
-
-# Check whether --enable-fast-install was given.
-if test "${enable_fast_install+set}" =3D set; then
-  enableval=3D$enable_fast_install; p=3D${PACKAGE-default}
-    case $enableval in
-    yes) enable_fast_install=3Dyes ;;
-    no) enable_fast_install=3Dno ;;
-    *)
-      enable_fast_install=3Dno
-      # Look at the argument we got.  We use all the common list separator=
s.
-      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-      for pkg in $enableval; do
-	IFS=3D"$lt_save_ifs"
-	if test "X$pkg" =3D "X$p"; then
-	  enable_fast_install=3Dyes
-	fi
-      done
-      IFS=3D"$lt_save_ifs"
-      ;;
-    esac
-else
-  enable_fast_install=3Dyes
-fi
-
-
-{ echo "$as_me:$LINENO: checking for a sed that does not truncate output" =
>&5
-echo $ECHO_N "checking for a sed that does not truncate output... $ECHO_C"=
 >&6; }
-if test "${lt_cv_path_SED+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  # Loop through the user's path and test for sed and gsed.
-# Then use that list of sed's as ones to test for truncation.
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for lt_ac_prog in sed gsed; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then
-        lt_ac_sed_list=3D"$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext"
-      fi
-    done
-  done
-done
-lt_ac_max=3D0
-lt_ac_count=3D0
-# Add /usr/xpg4/bin/sed as it is typically found on Solaris
-# along with /bin/sed that truncates output.
-for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do
-  test ! -f $lt_ac_sed && continue
-  cat /dev/null > conftest.in
-  lt_ac_count=3D0
-  echo $ECHO_N "0123456789$ECHO_C" >conftest.in
-  # Check for GNU sed and select it if it is found.
-  if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then
-    lt_cv_path_SED=3D$lt_ac_sed
-    break
-  fi
-  while true; do
-    cat conftest.in conftest.in >conftest.tmp
-    mv conftest.tmp conftest.in
-    cp conftest.in conftest.nl
-    echo >>conftest.nl
-    $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break
-    cmp -s conftest.out conftest.nl || break
-    # 10000 chars as input seems more than enough
-    test $lt_ac_count -gt 10 && break
-    lt_ac_count=3D`expr $lt_ac_count + 1`
-    if test $lt_ac_count -gt $lt_ac_max; then
-      lt_ac_max=3D$lt_ac_count
-      lt_cv_path_SED=3D$lt_ac_sed
-    fi
-  done
-done
-
-fi
-
-SED=3D$lt_cv_path_SED
-{ echo "$as_me:$LINENO: result: $SED" >&5
-echo "${ECHO_T}$SED" >&6; }
-
-{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" =
>&5
-echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C"=
 >&6; }
-if test "${ac_cv_path_GREP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  # Extract the first word of "grep ggrep" to use in msg output
-if test -z "$GREP"; then
-set dummy grep ggrep; ac_prog_name=3D$2
-if test "${ac_cv_path_GREP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
+  done
+  done
+IFS=3D$as_save_IFS
+  if test -z "$ac_cv_path_SED"; then
+    as_fn_error "no acceptable sed could be found in \$PATH" "$LINENO" 5
+  fi
+else
+  ac_cv_path_SED=3D$SED
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5
+$as_echo "$ac_cv_path_SED" >&6; }
+ SED=3D"$ac_cv_path_SED"
+  rm -f conftest.sed
+
+test -z "$SED" && SED=3Dsed
+Xsed=3D"$SED -e 1s/^X//"
+
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles lo=
ng lines and -e" >&5
+$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
+if test "${ac_cv_path_GREP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$GREP"; then
   ac_path_GREP_found=3Dfalse
-# Loop through the user's path and test for each of PROGNAME-LIST
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
 for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_prog in grep ggrep; do
-  for ac_exec_ext in '' $ac_executable_extensions; do
-    ac_path_GREP=3D"$as_dir/$ac_prog$ac_exec_ext"
-    { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue
-    # Check for GNU ac_path_GREP and select it if it is found.
+    for ac_prog in grep ggrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_GREP=3D"$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || contin=
ue
+# Check for GNU ac_path_GREP and select it if it is found.
   # Check for GNU $ac_path_GREP
 case `"$ac_path_GREP" --version 2>&1` in
 *GNU*)
   ac_cv_path_GREP=3D"$ac_path_GREP" ac_path_GREP_found=3D:;;
 *)
   ac_count=3D0
-  echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
+  $as_echo_n 0123456789 >"conftest.in"
   while :
   do
     cat "conftest.in" "conftest.in" >"conftest.tmp"
     mv "conftest.tmp" "conftest.in"
     cp "conftest.in" "conftest.nl"
-    echo 'GREP' >> "conftest.nl"
+    $as_echo 'GREP' >> "conftest.nl"
     "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"con=
ftest.out" 2>/dev/null || break
     diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    ac_count=3D`expr $ac_count + 1`
+    as_fn_arith $ac_count + 1 && ac_count=3D$as_val
     if test $ac_count -gt ${ac_path_GREP_max-0}; then
       # Best one so far, save it but keep looking for a better one
       ac_cv_path_GREP=3D"$ac_path_GREP"
@@ -5145,77 +4667,61 @@
   rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
 esac
=20
-
-    $ac_path_GREP_found && break 3
-  done
-done
-
-done
-IFS=3D$as_save_IFS
-
-
-fi
-
-GREP=3D"$ac_cv_path_GREP"
-if test -z "$GREP"; then
-  { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be fo=
und in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
-echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$P=
ATH_SEPARATOR/usr/xpg4/bin" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
+      $ac_path_GREP_found && break 3
+    done
+  done
+  done
+IFS=3D$as_save_IFS
+  if test -z "$ac_cv_path_GREP"; then
+    as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR=
/usr/xpg4/bin" "$LINENO" 5
+  fi
 else
   ac_cv_path_GREP=3D$GREP
 fi
=20
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5
-echo "${ECHO_T}$ac_cv_path_GREP" >&6; }
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
+$as_echo "$ac_cv_path_GREP" >&6; }
  GREP=3D"$ac_cv_path_GREP"
=20
=20
-{ echo "$as_me:$LINENO: checking for egrep" >&5
-echo $ECHO_N "checking for egrep... $ECHO_C" >&6; }
-if test "${ac_cv_path_EGREP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
+$as_echo_n "checking for egrep... " >&6; }
+if test "${ac_cv_path_EGREP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
    then ac_cv_path_EGREP=3D"$GREP -E"
    else
-     # Extract the first word of "egrep" to use in msg output
-if test -z "$EGREP"; then
-set dummy egrep; ac_prog_name=3D$2
-if test "${ac_cv_path_EGREP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
+     if test -z "$EGREP"; then
   ac_path_EGREP_found=3Dfalse
-# Loop through the user's path and test for each of PROGNAME-LIST
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
 for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_prog in egrep; do
-  for ac_exec_ext in '' $ac_executable_extensions; do
-    ac_path_EGREP=3D"$as_dir/$ac_prog$ac_exec_ext"
-    { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || contin=
ue
-    # Check for GNU ac_path_EGREP and select it if it is found.
+    for ac_prog in egrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_EGREP=3D"$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || cont=
inue
+# Check for GNU ac_path_EGREP and select it if it is found.
   # Check for GNU $ac_path_EGREP
 case `"$ac_path_EGREP" --version 2>&1` in
 *GNU*)
   ac_cv_path_EGREP=3D"$ac_path_EGREP" ac_path_EGREP_found=3D:;;
 *)
   ac_count=3D0
-  echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
+  $as_echo_n 0123456789 >"conftest.in"
   while :
   do
     cat "conftest.in" "conftest.in" >"conftest.tmp"
     mv "conftest.tmp" "conftest.in"
     cp "conftest.in" "conftest.nl"
-    echo 'EGREP' >> "conftest.nl"
+    $as_echo 'EGREP' >> "conftest.nl"
     "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null =
|| break
     diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    ac_count=3D`expr $ac_count + 1`
+    as_fn_arith $ac_count + 1 && ac_count=3D$as_val
     if test $ac_count -gt ${ac_path_EGREP_max-0}; then
       # Best one so far, save it but keep looking for a better one
       ac_cv_path_EGREP=3D"$ac_path_EGREP"
@@ -5227,39 +4733,114 @@
   rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
 esac
=20
-
-    $ac_path_EGREP_found && break 3
-  done
-done
-
-done
-IFS=3D$as_save_IFS
-
-
-fi
-
-EGREP=3D"$ac_cv_path_EGREP"
-if test -z "$EGREP"; then
-  { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be fo=
und in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
-echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$P=
ATH_SEPARATOR/usr/xpg4/bin" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
+      $ac_path_EGREP_found && break 3
+    done
+  done
+  done
+IFS=3D$as_save_IFS
+  if test -z "$ac_cv_path_EGREP"; then
+    as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATO=
R/usr/xpg4/bin" "$LINENO" 5
+  fi
 else
   ac_cv_path_EGREP=3D$EGREP
 fi
=20
-
    fi
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5
-echo "${ECHO_T}$ac_cv_path_EGREP" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
+$as_echo "$ac_cv_path_EGREP" >&6; }
  EGREP=3D"$ac_cv_path_EGREP"
=20
=20
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5
+$as_echo_n "checking for fgrep... " >&6; }
+if test "${ac_cv_path_FGREP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1
+   then ac_cv_path_FGREP=3D"$GREP -F"
+   else
+     if test -z "$FGREP"; then
+  ac_path_FGREP_found=3Dfalse
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_prog in fgrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_FGREP=3D"$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_FGREP" && $as_test_x "$ac_path_FGREP"; } || cont=
inue
+# Check for GNU ac_path_FGREP and select it if it is found.
+  # Check for GNU $ac_path_FGREP
+case `"$ac_path_FGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_FGREP=3D"$ac_path_FGREP" ac_path_FGREP_found=3D:;;
+*)
+  ac_count=3D0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'FGREP' >> "conftest.nl"
+    "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || =
break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=3D$as_val
+    if test $ac_count -gt ${ac_path_FGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_FGREP=3D"$ac_path_FGREP"
+      ac_path_FGREP_max=3D$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_FGREP_found && break 3
+    done
+  done
+  done
+IFS=3D$as_save_IFS
+  if test -z "$ac_cv_path_FGREP"; then
+    as_fn_error "no acceptable fgrep could be found in $PATH$PATH_SEPARATO=
R/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_FGREP=3D$FGREP
+fi
+
+   fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5
+$as_echo "$ac_cv_path_FGREP" >&6; }
+ FGREP=3D"$ac_cv_path_FGREP"
+
+
+test -z "$GREP" && GREP=3Dgrep
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
=20
 # Check whether --with-gnu-ld was given.
-if test "${with_gnu_ld+set}" =3D set; then
+if test "${with_gnu_ld+set}" =3D set; then :
   withval=3D$with_gnu_ld; test "$withval" =3D no || with_gnu_ld=3Dyes
 else
   with_gnu_ld=3Dno
@@ -5268,8 +4849,8 @@
 ac_prog=3Dld
 if test "$GCC" =3D yes; then
   # Check if gcc -print-prog-name=3Dld gives a path.
-  { echo "$as_me:$LINENO: checking for ld used by $CC" >&5
-echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5
+$as_echo_n "checking for ld used by $CC... " >&6; }
   case $host in
   *-*-mingw*)
     # gcc leaves a trailing carriage return which upsets mingw
@@ -5282,9 +4863,9 @@
     [\\/]* | ?:[\\/]*)
       re_direlt=3D'/[^/][^/]*/\.\./'
       # Canonicalize the pathname of ld
-      ac_prog=3D`echo $ac_prog| $SED 's%\\\\%/%g'`
-      while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=3D`echo $ac_prog| $SED "s%$re_direlt%/%"`
+      ac_prog=3D`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'`
+      while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do
+	ac_prog=3D`$ECHO $ac_prog| $SED "s%$re_direlt%/%"`
       done
       test -z "$LD" && LD=3D"$ac_prog"
       ;;
@@ -5298,14 +4879,14 @@
     ;;
   esac
 elif test "$with_gnu_ld" =3D yes; then
-  { echo "$as_me:$LINENO: checking for GNU ld" >&5
-echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; }
-else
-  { echo "$as_me:$LINENO: checking for non-GNU ld" >&5
-echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6; }
-fi
-if test "${lt_cv_path_LD+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
+$as_echo_n "checking for GNU ld... " >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5
+$as_echo_n "checking for non-GNU ld... " >&6; }
+fi
+if test "${lt_cv_path_LD+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -z "$LD"; then
   lt_save_ifs=3D"$IFS"; IFS=3D$PATH_SEPARATOR
@@ -5335,19 +4916,17 @@
=20
 LD=3D"$lt_cv_path_LD"
 if test -n "$LD"; then
-  { echo "$as_me:$LINENO: result: $LD" >&5
-echo "${ECHO_T}$LD" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found i=
n \$PATH" >&5
-echo "$as_me: error: no acceptable ld found in \$PATH" >&2;}
-   { (exit 1); exit 1; }; }
-{ echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
-echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6; }
-if test "${lt_cv_prog_gnu_ld+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
+$as_echo "$LD" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+test -z "$LD" && as_fn_error "no acceptable ld found in \$PATH" "$LINENO" 5
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is G=
NU ld" >&5
+$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; }
+if test "${lt_cv_prog_gnu_ld+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   # I'd rather use --version here, but apparently some GNU lds only accept=
 -v.
 case `$LD -v 2>&1 </dev/null` in
@@ -5359,40 +4938,22 @@
   ;;
 esac
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
-echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5
+$as_echo "$lt_cv_prog_gnu_ld" >&6; }
 with_gnu_ld=3D$lt_cv_prog_gnu_ld
=20
=20
-{ echo "$as_me:$LINENO: checking for $LD option to reload object files" >&5
-echo $ECHO_N "checking for $LD option to reload object files... $ECHO_C" >=
&6; }
-if test "${lt_cv_ld_reload_flag+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_cv_ld_reload_flag=3D'-r'
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_ld_reload_flag" >&5
-echo "${ECHO_T}$lt_cv_ld_reload_flag" >&6; }
-reload_flag=3D$lt_cv_ld_reload_flag
-case $reload_flag in
-"" | " "*) ;;
-*) reload_flag=3D" $reload_flag" ;;
-esac
-reload_cmds=3D'$LD$reload_flag -o $output$reload_objs'
-case $host_os in
-  darwin*)
-    if test "$GCC" =3D yes; then
-      reload_cmds=3D'$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_o=
bjs'
-    else
-      reload_cmds=3D'$LD$reload_flag -o $output$reload_objs'
-    fi
-    ;;
-esac
-
-{ echo "$as_me:$LINENO: checking for BSD-compatible nm" >&5
-echo $ECHO_N "checking for BSD-compatible nm... $ECHO_C" >&6; }
-if test "${lt_cv_path_NM+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatibl=
e name lister (nm)" >&5
+$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; }
+if test "${lt_cv_path_NM+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$NM"; then
   # Let the user override the test.
@@ -5435,28 +4996,589 @@
     done
     IFS=3D"$lt_save_ifs"
   done
-  test -z "$lt_cv_path_NM" && lt_cv_path_NM=3Dnm
-fi
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_path_NM" >&5
-echo "${ECHO_T}$lt_cv_path_NM" >&6; }
-NM=3D"$lt_cv_path_NM"
-
-{ echo "$as_me:$LINENO: checking whether ln -s works" >&5
-echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6; }
+  : ${lt_cv_path_NM=3Dno}
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5
+$as_echo "$lt_cv_path_NM" >&6; }
+if test "$lt_cv_path_NM" !=3D "no"; then
+  NM=3D"$lt_cv_path_NM"
+else
+  # Didn't find any BSD compatible name lister, look for dumpbin.
+  if test -n "$DUMPBIN"; then :
+    # Let the user override the test.
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in dumpbin "link -dump"
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a =
program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_DUMPBIN+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$DUMPBIN"; then
+  ac_cv_prog_DUMPBIN=3D"$DUMPBIN" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_DUMPBIN=3D"$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+DUMPBIN=3D$ac_cv_prog_DUMPBIN
+if test -n "$DUMPBIN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5
+$as_echo "$DUMPBIN" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$DUMPBIN" && break
+  done
+fi
+if test -z "$DUMPBIN"; then
+  ac_ct_DUMPBIN=3D$DUMPBIN
+  for ac_prog in dumpbin "link -dump"
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
+set dummy $ac_prog; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_DUMPBIN+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_DUMPBIN"; then
+  ac_cv_prog_ac_ct_DUMPBIN=3D"$ac_ct_DUMPBIN" # Let the user override the =
test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_DUMPBIN=3D"$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_DUMPBIN=3D$ac_cv_prog_ac_ct_DUMPBIN
+if test -n "$ac_ct_DUMPBIN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5
+$as_echo "$ac_ct_DUMPBIN" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_DUMPBIN" && break
+done
+
+  if test "x$ac_ct_DUMPBIN" =3D x; then
+    DUMPBIN=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    DUMPBIN=3D$ac_ct_DUMPBIN
+  fi
+fi
+
+    case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in
+    *COFF*)
+      DUMPBIN=3D"$DUMPBIN -symbols"
+      ;;
+    *)
+      DUMPBIN=3D:
+      ;;
+    esac
+  fi
+
+  if test "$DUMPBIN" !=3D ":"; then
+    NM=3D"$DUMPBIN"
+  fi
+fi
+test -z "$NM" && NM=3Dnm
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) in=
terface" >&5
+$as_echo_n "checking the name lister ($NM) interface... " >&6; }
+if test "${lt_cv_nm_interface+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_nm_interface=3D"BSD nm"
+  echo "int some_variable =3D 0;" > conftest.$ac_ext
+  (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5)
+  (eval "$ac_compile" 2>conftest.err)
+  cat conftest.err >&5
+  (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5)
+  (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
+  cat conftest.err >&5
+  (eval echo "\"\$as_me:$LINENO: output\"" >&5)
+  cat conftest.out >&5
+  if $GREP 'External.*some_variable' conftest.out > /dev/null; then
+    lt_cv_nm_interface=3D"MS dumpbin"
+  fi
+  rm -f conftest*
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5
+$as_echo "$lt_cv_nm_interface" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5
+$as_echo_n "checking whether ln -s works... " >&6; }
 LN_S=3D$as_ln_s
 if test "$LN_S" =3D "ln -s"; then
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no, using $LN_S" >&5
-echo "${ECHO_T}no, using $LN_S" >&6; }
-fi
-
-{ echo "$as_me:$LINENO: checking how to recognise dependent libraries" >&5
-echo $ECHO_N "checking how to recognise dependent libraries... $ECHO_C" >&=
6; }
-if test "${lt_cv_deplibs_check_method+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5
+$as_echo "no, using $LN_S" >&6; }
+fi
+
+# find the maximum length of command line arguments
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of co=
mmand line arguments" >&5
+$as_echo_n "checking the maximum length of command line arguments... " >&6=
; }
+if test "${lt_cv_sys_max_cmd_len+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+    i=3D0
+  teststring=3D"ABCD"
+
+  case $build_os in
+  msdosdjgpp*)
+    # On DJGPP, this test can blow up pretty badly due to problems in libc
+    # (any single argument exceeding 2000 bytes causes a buffer overrun
+    # during glob expansion).  Even if it were fixed, the result of this
+    # check would be larger than it should be.
+    lt_cv_sys_max_cmd_len=3D12288;    # 12K is about right
+    ;;
+
+  gnu*)
+    # Under GNU Hurd, this test is not required because there is
+    # no limit to the length of command line arguments.
+    # Libtool will interpret -1 as no limit whatsoever
+    lt_cv_sys_max_cmd_len=3D-1;
+    ;;
+
+  cygwin* | mingw* | cegcc*)
+    # On Win9x/ME, this test blows up -- it succeeds, but takes
+    # about 5 minutes as the teststring grows exponentially.
+    # Worse, since 9x/ME are not pre-emptively multitasking,
+    # you end up with a "frozen" computer, even though with patience
+    # the test eventually succeeds (with a max line length of 256k).
+    # Instead, let's just punt: use the minimum linelength reported by
+    # all of the supported platforms: 8192 (on NT/2K/XP).
+    lt_cv_sys_max_cmd_len=3D8192;
+    ;;
+
+  mint*)
+    # On MiNT this can take a long time and run out of memory.
+    lt_cv_sys_max_cmd_len=3D8192;
+    ;;
+
+  amigaos*)
+    # On AmigaOS with pdksh, this test takes hours, literally.
+    # So we just punt and use a minimum line length of 8192.
+    lt_cv_sys_max_cmd_len=3D8192;
+    ;;
+
+  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
+    # This has been around since 386BSD, at least.  Likely further.
+    if test -x /sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=3D`/sbin/sysctl -n kern.argmax`
+    elif test -x /usr/sbin/sysctl; then
+      lt_cv_sys_max_cmd_len=3D`/usr/sbin/sysctl -n kern.argmax`
+    else
+      lt_cv_sys_max_cmd_len=3D65536	# usable default for all BSDs
+    fi
+    # And add a safety zone
+    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \/ 4`
+    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \* 3`
+    ;;
+
+  interix*)
+    # We know the value 262144 and hardcode it with a safety zone (like BS=
D)
+    lt_cv_sys_max_cmd_len=3D196608
+    ;;
+
+  osf*)
+    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running conf=
igure
+    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
+    # nice to cause kernel panics so lets avoid the loop below.
+    # First set a reasonable default.
+    lt_cv_sys_max_cmd_len=3D16384
+    #
+    if test -x /sbin/sysconfig; then
+      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
+        *1*) lt_cv_sys_max_cmd_len=3D-1 ;;
+      esac
+    fi
+    ;;
+  sco3.2v5*)
+    lt_cv_sys_max_cmd_len=3D102400
+    ;;
+  sysv5* | sco5v6* | sysv4.2uw2*)
+    kargmax=3D`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
+    if test -n "$kargmax"; then
+      lt_cv_sys_max_cmd_len=3D`echo $kargmax | sed 's/.*[	 ]//'`
+    else
+      lt_cv_sys_max_cmd_len=3D32768
+    fi
+    ;;
+  *)
+    lt_cv_sys_max_cmd_len=3D`(getconf ARG_MAX) 2> /dev/null`
+    if test -n "$lt_cv_sys_max_cmd_len"; then
+      lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \/ 4`
+      lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \* 3`
+    else
+      # Make teststring a little bigger before we do anything with it.
+      # a 1K string should be a reasonable start.
+      for i in 1 2 3 4 5 6 7 8 ; do
+        teststring=3D$teststring$teststring
+      done
+      SHELL=3D${SHELL-${CONFIG_SHELL-/bin/sh}}
+      # If test is not a shell built-in, we'll probably end up computing a
+      # maximum length that is only half of the actual maximum length, but
+      # we can't tell.
+      while { test "X"`func_fallback_echo "$teststring$teststring" 2>/dev/=
null` \
+	         =3D "X$teststring$teststring"; } >/dev/null 2>&1 &&
+	      test $i !=3D 17 # 1/2 MB should be enough
+      do
+        i=3D`expr $i + 1`
+        teststring=3D$teststring$teststring
+      done
+      # Only check the string length outside the loop.
+      lt_cv_sys_max_cmd_len=3D`expr "X$teststring" : ".*" 2>&1`
+      teststring=3D
+      # Add a significant safety factor because C++ compilers can tack on
+      # massive amounts of additional arguments before passing them to the
+      # linker.  It appears as though 1/2 is a usable value.
+      lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \/ 2`
+    fi
+    ;;
+  esac
+
+fi
+
+if test -n $lt_cv_sys_max_cmd_len ; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len"=
 >&5
+$as_echo "$lt_cv_sys_max_cmd_len" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5
+$as_echo "none" >&6; }
+fi
+max_cmd_len=3D$lt_cv_sys_max_cmd_len
+
+
+
+
+
+
+: ${CP=3D"cp -f"}
+: ${MV=3D"mv -f"}
+: ${RM=3D"rm -f"}
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell unders=
tands some XSI constructs" >&5
+$as_echo_n "checking whether the shell understands some XSI constructs... =
" >&6; }
+# Try some XSI features
+xsi_shell=3Dno
+( _lt_dummy=3D"a/b/c"
+  test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt=
_dummy"}, \
+      =3D c,a/b,b/c, \
+    && eval 'test $(( 1 + 1 )) -eq 2 \
+    && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \
+  && xsi_shell=3Dyes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5
+$as_echo "$xsi_shell" >&6; }
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell unders=
tands \"+=3D\"" >&5
+$as_echo_n "checking whether the shell understands \"+=3D\"... " >&6; }
+lt_shell_append=3Dno
+( foo=3Dbar; set foo baz; eval "$1+=3D\$2" && test "$foo" =3D barbaz ) \
+    >/dev/null 2>&1 \
+  && lt_shell_append=3Dyes
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5
+$as_echo "$lt_shell_append" >&6; }
+
+
+if ( (MAIL=3D60; unset MAIL) || exit) >/dev/null 2>&1; then
+  lt_unset=3Dunset
+else
+  lt_unset=3Dfalse
+fi
+
+
+
+
+
+# test EBCDIC or ASCII
+case `echo X|tr X '\101'` in
+ A) # ASCII based system
+    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
+  lt_SP2NL=3D'tr \040 \012'
+  lt_NL2SP=3D'tr \015\012 \040\040'
+  ;;
+ *) # EBCDIC based system
+  lt_SP2NL=3D'tr \100 \n'
+  lt_NL2SP=3D'tr \r\n \100\100'
+  ;;
+esac
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build fi=
le names to $host format" >&5
+$as_echo_n "checking how to convert $build file names to $host format... "=
 >&6; }
+if test "${lt_cv_to_host_file_cmd+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=3Dfunc_convert_file_msys_to_w32
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=3Dfunc_convert_file_cygwin_to_w32
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=3Dfunc_convert_file_nix_to_w32
+        ;;
+    esac
+    ;;
+  *-*-cygwin* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_host_file_cmd=3Dfunc_convert_file_msys_to_cygwin
+        ;;
+      *-*-cygwin* )
+        lt_cv_to_host_file_cmd=3Dfunc_convert_file_noop
+        ;;
+      * ) # otherwise, assume *nix
+        lt_cv_to_host_file_cmd=3Dfunc_convert_file_nix_to_cygwin
+        ;;
+    esac
+    ;;
+  * ) # unhandled hosts (and "normal" native builds)
+    lt_cv_to_host_file_cmd=3Dfunc_convert_file_noop
+    ;;
+esac
+
+fi
+
+to_host_file_cmd=3D$lt_cv_to_host_file_cmd
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" =
>&5
+$as_echo "$lt_cv_to_host_file_cmd" >&6; }
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build fi=
le names to toolchain format" >&5
+$as_echo_n "checking how to convert $build file names to toolchain format.=
.. " >&6; }
+if test "${lt_cv_to_tool_file_cmd+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  #assume ordinary cross tools, or native build.
+lt_cv_to_tool_file_cmd=3Dfunc_convert_file_noop
+case $host in
+  *-*-mingw* )
+    case $build in
+      *-*-mingw* ) # actually msys
+        lt_cv_to_tool_file_cmd=3Dfunc_convert_file_msys_to_w32
+        ;;
+    esac
+    ;;
+esac
+
+fi
+
+to_tool_file_cmd=3D$lt_cv_to_tool_file_cmd
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" =
>&5
+$as_echo "$lt_cv_to_tool_file_cmd" >&6; }
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload=
 object files" >&5
+$as_echo_n "checking for $LD option to reload object files... " >&6; }
+if test "${lt_cv_ld_reload_flag+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_ld_reload_flag=3D'-r'
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5
+$as_echo "$lt_cv_ld_reload_flag" >&6; }
+reload_flag=3D$lt_cv_ld_reload_flag
+case $reload_flag in
+"" | " "*) ;;
+*) reload_flag=3D" $reload_flag" ;;
+esac
+reload_cmds=3D'$LD$reload_flag -o $output$reload_objs'
+case $host_os in
+  cygwin* | mingw* | pw32* | cegcc*)
+    if test "$GCC" !=3D yes; then
+      reload_cmds=3Dfalse
+    fi
+    ;;
+  darwin*)
+    if test "$GCC" =3D yes; then
+      reload_cmds=3D'$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_o=
bjs'
+    else
+      reload_cmds=3D'$LD$reload_flag -o $output$reload_objs'
+    fi
+    ;;
+esac
+
+
+
+
+
+
+
+
+
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}objdump", so it can be a p=
rogram name with args.
+set dummy ${ac_tool_prefix}objdump; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_OBJDUMP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$OBJDUMP"; then
+  ac_cv_prog_OBJDUMP=3D"$OBJDUMP" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_OBJDUMP=3D"${ac_tool_prefix}objdump"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+OBJDUMP=3D$ac_cv_prog_OBJDUMP
+if test -n "$OBJDUMP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5
+$as_echo "$OBJDUMP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_OBJDUMP"; then
+  ac_ct_OBJDUMP=3D$OBJDUMP
+  # Extract the first word of "objdump", so it can be a program name with =
args.
+set dummy objdump; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_OBJDUMP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_OBJDUMP"; then
+  ac_cv_prog_ac_ct_OBJDUMP=3D"$ac_ct_OBJDUMP" # Let the user override the =
test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_OBJDUMP=3D"objdump"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_OBJDUMP=3D$ac_cv_prog_ac_ct_OBJDUMP
+if test -n "$ac_ct_OBJDUMP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5
+$as_echo "$ac_ct_OBJDUMP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_OBJDUMP" =3D x; then
+    OBJDUMP=3D"false"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    OBJDUMP=3D$ac_ct_OBJDUMP
+  fi
+else
+  OBJDUMP=3D"$ac_cv_prog_OBJDUMP"
+fi
+
+test -z "$OBJDUMP" && OBJDUMP=3Dobjdump
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize depende=
nt libraries" >&5
+$as_echo_n "checking how to recognize dependent libraries... " >&6; }
+if test "${lt_cv_deplibs_check_method+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   lt_cv_file_magic_cmd=3D'$MAGIC_CMD'
 lt_cv_file_magic_test_file=3D
@@ -5473,7 +5595,7 @@
 # whether `pass_all' will *always* work, you probably want this one.
=20
 case $host_os in
-aix4* | aix5*)
+aix[4-9]*)
   lt_cv_deplibs_check_method=3Dpass_all
   ;;
=20
@@ -5495,8 +5617,22 @@
=20
 mingw* | pw32*)
   # Base MSYS/MinGW do not provide the 'file' command needed by
-  # func_win32_libid shell function, so use a weaker test based on 'objdum=
p'.
-  lt_cv_deplibs_check_method=3D'file_magic file format pei*-i386(.*archite=
cture: i386)?'
+  # func_win32_libid shell function, so use a weaker test based on 'objdum=
p',
+  # unless we find 'file', for example because we are cross-compiling.
+  # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin.
+  if ( test "$lt_cv_nm_interface" =3D "BSD nm" && file / ) >/dev/null 2>&1=
; then
+    lt_cv_deplibs_check_method=3D'file_magic ^x86 archive import|^x86 DLL'
+    lt_cv_file_magic_cmd=3D'func_win32_libid'
+  else
+    # Keep this pattern in sync with the one in func_win32_libid.
+    lt_cv_deplibs_check_method=3D'file_magic file format (pei*-i386(.*arch=
itecture: i386)?|pe-arm-wince|pe-x86-64)'
+    lt_cv_file_magic_cmd=3D'$OBJDUMP -f'
+  fi
+  ;;
+
+cegcc*)
+  # use the weaker test based on 'objdump'. See mingw*.
+  lt_cv_deplibs_check_method=3D'file_magic file format pe-arm-.*little(.*a=
rchitecture: arm)?'
   lt_cv_file_magic_cmd=3D'$OBJDUMP -f'
   ;;
=20
@@ -5504,8 +5640,8 @@
   lt_cv_deplibs_check_method=3Dpass_all
   ;;
=20
-freebsd* | kfreebsd*-gnu | dragonfly*)
-  if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+freebsd* | dragonfly*)
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
     case $host_cpu in
     i*86 )
       # Not sure whether the presence of OpenBSD here was a mistake.
@@ -5524,6 +5660,10 @@
   lt_cv_deplibs_check_method=3Dpass_all
   ;;
=20
+haiku*)
+  lt_cv_deplibs_check_method=3Dpass_all
+  ;;
+
 hpux10.20* | hpux11*)
   lt_cv_file_magic_cmd=3D/usr/bin/file
   case $host_cpu in
@@ -5532,17 +5672,17 @@
     lt_cv_file_magic_test_file=3D/usr/lib/hpux32/libc.so
     ;;
   hppa*64*)
-    lt_cv_deplibs_check_method=3D'file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0=
-9]) shared object file - PA-RISC [0-9].[0-9]'
+    lt_cv_deplibs_check_method=3D'file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9=
][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'
     lt_cv_file_magic_test_file=3D/usr/lib/pa20_64/libc.sl
     ;;
   *)
-    lt_cv_deplibs_check_method=3D'file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9=
].[0-9]) shared library'
+    lt_cv_deplibs_check_method=3D'file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9=
]\.[0-9]) shared library'
     lt_cv_file_magic_test_file=3D/usr/lib/libc.sl
     ;;
   esac
   ;;
=20
-interix3*)
+interix[3-9]*)
   # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here
   lt_cv_deplibs_check_method=3D'match_pattern /lib[^/]+(\.so|\.a)$'
   ;;
@@ -5558,12 +5698,12 @@
   ;;
=20
 # This must be Linux ELF.
-linux*)
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
   lt_cv_deplibs_check_method=3Dpass_all
   ;;
=20
 netbsd*)
-  if echo __ELF__ | $CC -E - | grep __ELF__ > /dev/null; then
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then
     lt_cv_deplibs_check_method=3D'match_pattern /lib[^/]+(\.so\.[0-9]+\.[0=
-9]+|_pic\.a)$'
   else
     lt_cv_deplibs_check_method=3D'match_pattern /lib[^/]+(\.so|_pic\.a)$'
@@ -5576,12 +5716,12 @@
   lt_cv_file_magic_test_file=3D/usr/lib/libnls.so
   ;;
=20
-nto-qnx*)
-  lt_cv_deplibs_check_method=3Dunknown
+*nto* | *qnx*)
+  lt_cv_deplibs_check_method=3Dpass_all
   ;;
=20
 openbsd*)
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os=
-$host_cpu" =3D "openbsd2.8-powerpc"; then
     lt_cv_deplibs_check_method=3D'match_pattern /lib[^/]+(\.so\.[0-9]+\.[0=
-9]+|\.so|_pic\.a)$'
   else
     lt_cv_deplibs_check_method=3D'match_pattern /lib[^/]+(\.so\.[0-9]+\.[0=
-9]+|_pic\.a)$'
@@ -5592,10 +5732,18 @@
   lt_cv_deplibs_check_method=3Dpass_all
   ;;
=20
+rdos*)
+  lt_cv_deplibs_check_method=3Dpass_all
+  ;;
+
 solaris*)
   lt_cv_deplibs_check_method=3Dpass_all
   ;;
=20
+sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+  lt_cv_deplibs_check_method=3Dpass_all
+  ;;
+
 sysv4 | sysv4.3*)
   case $host_vendor in
   motorola)
@@ -5623,19 +5771,627 @@
   esac
   ;;
=20
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
+tpf*)
   lt_cv_deplibs_check_method=3Dpass_all
   ;;
 esac
=20
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_deplibs_check_method" >&5
-echo "${ECHO_T}$lt_cv_deplibs_check_method" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_meth=
od" >&5
+$as_echo "$lt_cv_deplibs_check_method" >&6; }
+
+file_magic_glob=3D
+want_nocaseglob=3Dno
+if test "$build" =3D "$host"; then
+  case $host_os in
+  mingw* | pw32*)
+    if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then
+      want_nocaseglob=3Dyes
+    else
+      file_magic_glob=3D`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvV=
wWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"`
+    fi
+    ;;
+  esac
+fi
+
 file_magic_cmd=3D$lt_cv_file_magic_cmd
 deplibs_check_method=3D$lt_cv_deplibs_check_method
 test -z "$deplibs_check_method" && deplibs_check_method=3Dunknown
=20
=20
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a p=
rogram name with args.
+set dummy ${ac_tool_prefix}dlltool; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_DLLTOOL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$DLLTOOL"; then
+  ac_cv_prog_DLLTOOL=3D"$DLLTOOL" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_DLLTOOL=3D"${ac_tool_prefix}dlltool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+DLLTOOL=3D$ac_cv_prog_DLLTOOL
+if test -n "$DLLTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5
+$as_echo "$DLLTOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_DLLTOOL"; then
+  ac_ct_DLLTOOL=3D$DLLTOOL
+  # Extract the first word of "dlltool", so it can be a program name with =
args.
+set dummy dlltool; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_DLLTOOL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_DLLTOOL"; then
+  ac_cv_prog_ac_ct_DLLTOOL=3D"$ac_ct_DLLTOOL" # Let the user override the =
test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_DLLTOOL=3D"dlltool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_DLLTOOL=3D$ac_cv_prog_ac_ct_DLLTOOL
+if test -n "$ac_ct_DLLTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5
+$as_echo "$ac_ct_DLLTOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_DLLTOOL" =3D x; then
+    DLLTOOL=3D"false"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    DLLTOOL=3D$ac_ct_DLLTOOL
+  fi
+else
+  DLLTOOL=3D"$ac_cv_prog_DLLTOOL"
+fi
+
+test -z "$DLLTOOL" && DLLTOOL=3Ddlltool
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime=
 and link libraries" >&5
+$as_echo_n "checking how to associate runtime and link libraries... " >&6;=
 }
+if test "${lt_cv_sharedlib_from_linklib_cmd+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_sharedlib_from_linklib_cmd=3D'unknown'
+
+case $host_os in
+cygwin* | mingw* | pw32* | cegcc*)
+  # two different shell functions defined in ltmain.sh
+  # decide which to use based on capabilities of $DLLTOOL
+  case `$DLLTOOL --help 2>&1` in
+  *--identify-strict*)
+    lt_cv_sharedlib_from_linklib_cmd=3Dfunc_cygming_dll_for_implib
+    ;;
+  *)
+    lt_cv_sharedlib_from_linklib_cmd=3Dfunc_cygming_dll_for_implib_fallback
+    ;;
+  esac
+  ;;
+*)
+  # fallback: assume linklib IS sharedlib
+  lt_cv_sharedlib_from_linklib_cmd=3D"$ECHO"
+  ;;
+esac
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_lin=
klib_cmd" >&5
+$as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; }
+sharedlib_from_linklib_cmd=3D$lt_cv_sharedlib_from_linklib_cmd
+test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=3D$ECHO
+
+
+
+
+
+
+
+
+if test -n "$ac_tool_prefix"; then
+  for ac_prog in ar
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a =
program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_AR+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$AR"; then
+  ac_cv_prog_AR=3D"$AR" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_AR=3D"$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+AR=3D$ac_cv_prog_AR
+if test -n "$AR"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
+$as_echo "$AR" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$AR" && break
+  done
+fi
+if test -z "$AR"; then
+  ac_ct_AR=3D$AR
+  for ac_prog in ar
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
+set dummy $ac_prog; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_AR+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_AR"; then
+  ac_cv_prog_ac_ct_AR=3D"$ac_ct_AR" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_AR=3D"$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_AR=3D$ac_cv_prog_ac_ct_AR
+if test -n "$ac_ct_AR"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
+$as_echo "$ac_ct_AR" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_AR" && break
+done
+
+  if test "x$ac_ct_AR" =3D x; then
+    AR=3D"false"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    AR=3D$ac_ct_AR
+  fi
+fi
+
+: ${AR=3Dar}
+: ${AR_FLAGS=3Dcru}
+
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE suppo=
rt" >&5
+$as_echo_n "checking for archiver @FILE support... " >&6; }
+if test "${lt_cv_ar_at_file+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_ar_at_file=3Dno
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  echo conftest.$ac_objext > conftest.lst
+      lt_ar_try=3D'$AR $AR_FLAGS libconftest.a @conftest.lst >&5'
+      { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } =
>&5
+  (eval $lt_ar_try) 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }
+      if test "$ac_status" -eq 0; then
+	# Ensure the archiver fails upon bogus file names.
+	rm -f conftest.$ac_objext libconftest.a
+	{ { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5
+  (eval $lt_ar_try) 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }
+	if test "$ac_status" -ne 0; then
+          lt_cv_ar_at_file=3D@
+        fi
+      fi
+      rm -f conftest.* libconftest.a
+
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5
+$as_echo "$lt_cv_ar_at_file" >&6; }
+
+if test "x$lt_cv_ar_at_file" =3D xno; then
+  archiver_list_spec=3D
+else
+  archiver_list_spec=3D$lt_cv_ar_at_file
+fi
+
+
+
+
+
+
+
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}strip", so it can be a pro=
gram name with args.
+set dummy ${ac_tool_prefix}strip; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_STRIP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$STRIP"; then
+  ac_cv_prog_STRIP=3D"$STRIP" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_STRIP=3D"${ac_tool_prefix}strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+STRIP=3D$ac_cv_prog_STRIP
+if test -n "$STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5
+$as_echo "$STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_STRIP"; then
+  ac_ct_STRIP=3D$STRIP
+  # Extract the first word of "strip", so it can be a program name with ar=
gs.
+set dummy strip; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_STRIP+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_STRIP"; then
+  ac_cv_prog_ac_ct_STRIP=3D"$ac_ct_STRIP" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_STRIP=3D"strip"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_STRIP=3D$ac_cv_prog_ac_ct_STRIP
+if test -n "$ac_ct_STRIP"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5
+$as_echo "$ac_ct_STRIP" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_STRIP" =3D x; then
+    STRIP=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    STRIP=3D$ac_ct_STRIP
+  fi
+else
+  STRIP=3D"$ac_cv_prog_STRIP"
+fi
+
+test -z "$STRIP" && STRIP=3D:
+
+
+
+
+
+
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a pr=
ogram name with args.
+set dummy ${ac_tool_prefix}ranlib; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_RANLIB+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$RANLIB"; then
+  ac_cv_prog_RANLIB=3D"$RANLIB" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_RANLIB=3D"${ac_tool_prefix}ranlib"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+RANLIB=3D$ac_cv_prog_RANLIB
+if test -n "$RANLIB"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
+$as_echo "$RANLIB" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_RANLIB"; then
+  ac_ct_RANLIB=3D$RANLIB
+  # Extract the first word of "ranlib", so it can be a program name with a=
rgs.
+set dummy ranlib; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_RANLIB+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_RANLIB"; then
+  ac_cv_prog_ac_ct_RANLIB=3D"$ac_ct_RANLIB" # Let the user override the te=
st.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_RANLIB=3D"ranlib"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_RANLIB=3D$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
+$as_echo "$ac_ct_RANLIB" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_RANLIB" =3D x; then
+    RANLIB=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    RANLIB=3D$ac_ct_RANLIB
+  fi
+else
+  RANLIB=3D"$ac_cv_prog_RANLIB"
+fi
+
+test -z "$RANLIB" && RANLIB=3D:
+
+
+
+
+
+
+# Determine commands to create old-style static archives.
+old_archive_cmds=3D'$AR $AR_FLAGS $oldlib$oldobjs'
+old_postinstall_cmds=3D'chmod 644 $oldlib'
+old_postuninstall_cmds=3D
+
+if test -n "$RANLIB"; then
+  case $host_os in
+  openbsd*)
+    old_postinstall_cmds=3D"$old_postinstall_cmds~\$RANLIB -t \$oldlib"
+    ;;
+  *)
+    old_postinstall_cmds=3D"$old_postinstall_cmds~\$RANLIB \$oldlib"
+    ;;
+  esac
+  old_archive_cmds=3D"$old_archive_cmds~\$RANLIB \$oldlib"
+fi
+
+case $host_os in
+  darwin*)
+    lock_old_archive_extraction=3Dyes ;;
+  *)
+    lock_old_archive_extraction=3Dno ;;
+esac
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 # If no C compiler was specified, use CC.
 LTCC=3D${LTCC-"$CC"}
=20
@@ -5645,8 +6401,320 @@
 # Allow CC to be a program name with arguments.
 compiler=3D$CC
=20
+
+# Check for command to grab the raw symbol name followed by C symbol from =
nm.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM out=
put from $compiler object" >&5
+$as_echo_n "checking command to parse $NM output from $compiler object... =
" >&6; }
+if test "${lt_cv_sys_global_symbol_pipe+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+# These are sane defaults that work on at least a few old systems.
+# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
+
+# Character class describing NM global symbol codes.
+symcode=3D'[BCDEGRST]'
+
+# Regexp to match symbols that can be accessed directly from C.
+sympat=3D'\([_A-Za-z][_A-Za-z0-9]*\)'
+
+# Define system-specific variables.
+case $host_os in
+aix*)
+  symcode=3D'[BCDT]'
+  ;;
+cygwin* | mingw* | pw32* | cegcc*)
+  symcode=3D'[ABCDGISTW]'
+  ;;
+hpux*)
+  if test "$host_cpu" =3D ia64; then
+    symcode=3D'[ABCDEGRST]'
+  fi
+  ;;
+irix* | nonstopux*)
+  symcode=3D'[BCDEGRST]'
+  ;;
+osf*)
+  symcode=3D'[BCDEGQRST]'
+  ;;
+solaris*)
+  symcode=3D'[BDRT]'
+  ;;
+sco3.2v5*)
+  symcode=3D'[DT]'
+  ;;
+sysv4.2uw2*)
+  symcode=3D'[DT]'
+  ;;
+sysv5* | sco5v6* | unixware* | OpenUNIX*)
+  symcode=3D'[ABDT]'
+  ;;
+sysv4)
+  symcode=3D'[DFNSTU]'
+  ;;
+esac
+
+# If we're using GNU nm, then use its standard symbol codes.
+case `$NM -V 2>&1` in
+*GNU* | *'with BFD'*)
+  symcode=3D'[ABCDGIRSTW]' ;;
+esac
+
+# Transform an extracted symbol line into a proper C declaration.
+# Some systems (esp. on ia64) link data and code symbols differently,
+# so use this general approach.
+lt_cv_sys_global_symbol_to_cdecl=3D"sed -n -e 's/^T .* \(.*\)$/extern int =
\1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
+
+# Transform an extracted symbol line into symbol name and symbol address
+lt_cv_sys_global_symbol_to_c_name_address=3D"sed -n -e 's/^: \([^ ]*\)[ ]*=
$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\=
"\2\", (void *) \&\2},/p'"
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix=3D"sed -n -e 's/^: \(=
[^ ]*\)[ ]*$/  {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(li=
b[^ ]*\)$/  {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\=
)$/  {\"lib\2\", (void *) \&\2},/p'"
+
+# Handle CRLF in mingw tool chain
+opt_cr=3D
+case $build_os in
+mingw*)
+  opt_cr=3D`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp
+  ;;
+esac
+
+# Try without a prefix underscore, then with it.
+for ac_symprfx in "" "_"; do
+
+  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbo=
l.
+  symxfrm=3D"\\1 $ac_symprfx\\2 \\2"
+
+  # Write the raw and C identifiers.
+  if test "$lt_cv_nm_interface" =3D "MS dumpbin"; then
+    # Fake it for dumpbin and say T for any non-static function
+    # and D for any global variable.
+    # Also find C++ and __fastcall symbols from MSVC++,
+    # which start with @ or ?.
+    lt_cv_sys_global_symbol_pipe=3D"$AWK '"\
+"     {last_section=3Dsection; section=3D\$ 3};"\
+"     /Section length .*#relocs.*(pick any)/{hide[last_section]=3D1};"\
+"     \$ 0!~/External *\|/{next};"\
+"     / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\
+"     {if(hide[section]) next};"\
+"     {f=3D0}; \$ 0~/\(\).*\|/{f=3D1}; {printf f ? \"T \" : \"D \"};"\
+"     {split(\$ 0, a, /\||\r/); split(a[2], s)};"\
+"     s[1]~/^[@?]/{print s[1], s[1]; next};"\
+"     s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx)=
)}"\
+"     ' prfx=3D^$ac_symprfx"
+  else
+    lt_cv_sys_global_symbol_pipe=3D"sed -n -e 's/^.*[	 ]\($symcode$symcode=
*\)[	 ][	 ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
+  fi
+  lt_cv_sys_global_symbol_pipe=3D"$lt_cv_sys_global_symbol_pipe | sed '/ _=
_gnu_lto/d'"
+
+  # Check to see that the pipe works correctly.
+  pipe_works=3Dno
+
+  rm -f conftest*
+  cat > conftest.$ac_ext <<_LT_EOF
+#ifdef __cplusplus
+extern "C" {
+#endif
+char nm_test_var;
+void nm_test_func(void);
+void nm_test_func(void){}
+#ifdef __cplusplus
+}
+#endif
+int main(){nm_test_var=3D'a';nm_test_func();return(0);}
+_LT_EOF
+
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } =
>&5
+  (eval $ac_compile) 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then
+    # Now try to grab the symbols.
+    nlist=3Dconftest.nm
+    if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac=
_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5
+  (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nli=
st) 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } && test -s "$nlist"; then
+      # Try sorting and uniquifying the output.
+      if sort "$nlist" | uniq > "$nlist"T; then
+	mv -f "$nlist"T "$nlist"
+      else
+	rm -f "$nlist"T
+      fi
+
+      # Make sure that we snagged all the symbols we need.
+      if $GREP ' nm_test_var$' "$nlist" >/dev/null; then
+	if $GREP ' nm_test_func$' "$nlist" >/dev/null; then
+	  cat <<_LT_EOF > conftest.$ac_ext
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tes=
ts.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  =
*/
+# define LT_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
+#else
+# define LT_DLSYM_CONST const
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+_LT_EOF
+	  # Now generate the symbol file.
+	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >>=
 conftest.$ac_ext'
+
+	  cat <<_LT_EOF >> conftest.$ac_ext
+
+/* The mapping between symbol names and symbols.  */
+LT_DLSYM_CONST struct {
+  const char *name;
+  void       *address;
+}
+lt__PROGRAM__LTX_preloaded_symbols[] =3D
+{
+  { "@PROGRAM@", (void *) 0 },
+_LT_EOF
+	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (void *) \&\2},/" =
< "$nlist" | $GREP -v main >> conftest.$ac_ext
+	  cat <<\_LT_EOF >> conftest.$ac_ext
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt__PROGRAM__LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+_LT_EOF
+	  # Now try linking the two files.
+	  mv conftest.$ac_objext conftstm.$ac_objext
+	  lt_globsym_save_LIBS=3D$LIBS
+	  lt_globsym_save_CFLAGS=3D$CFLAGS
+	  LIBS=3D"conftstm.$ac_objext"
+	  CFLAGS=3D"$CFLAGS$lt_prog_compiler_no_builtin_flag"
+	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
+  (eval $ac_link) 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } && test -s conftest${ac_exeext}; then
+	    pipe_works=3Dyes
+	  fi
+	  LIBS=3D$lt_globsym_save_LIBS
+	  CFLAGS=3D$lt_globsym_save_CFLAGS
+	else
+	  echo "cannot find nm_test_func in $nlist" >&5
+	fi
+      else
+	echo "cannot find nm_test_var in $nlist" >&5
+      fi
+    else
+      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5
+    fi
+  else
+    echo "$progname: failed program was:" >&5
+    cat conftest.$ac_ext >&5
+  fi
+  rm -rf conftest* conftst*
+
+  # Do not use the global_symbol_pipe unless it works.
+  if test "$pipe_works" =3D yes; then
+    break
+  else
+    lt_cv_sys_global_symbol_pipe=3D
+  fi
+done
+
+fi
+
+if test -z "$lt_cv_sys_global_symbol_pipe"; then
+  lt_cv_sys_global_symbol_to_cdecl=3D
+fi
+if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl=
"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5
+$as_echo "failed" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5
+$as_echo "ok" >&6; }
+fi
+
+# Response file support.
+if test "$lt_cv_nm_interface" =3D "MS dumpbin"; then
+  nm_file_list_spec=3D'@'
+elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then
+  nm_file_list_spec=3D'@'
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5
+$as_echo_n "checking for sysroot... " >&6; }
+
+# Check whether --with-sysroot was given.
+if test "${with_sysroot+set}" =3D set; then :
+  withval=3D$with_sysroot;
+else
+  with_sysroot=3Dno
+fi
+
+
+lt_sysroot=3D
+case ${with_sysroot} in #(
+ yes)
+   if test "$GCC" =3D yes; then
+     lt_sysroot=3D`$CC --print-sysroot 2>/dev/null`
+   fi
+   ;; #(
+ /*)
+   lt_sysroot=3D`echo "$with_sysroot" | sed -e "$sed_quote_subst"`
+   ;; #(
+ no|'')
+   ;; #(
+ *)
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5
+$as_echo "${with_sysroot}" >&6; }
+   as_fn_error "The sysroot must be an absolute path." "$LINENO" 5
+   ;;
+esac
+
+ { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5
+$as_echo "${lt_sysroot:-no}" >&6; }
+
+
+
+
+
 # Check whether --enable-libtool-lock was given.
-if test "${enable_libtool_lock+set}" =3D set; then
+if test "${enable_libtool_lock+set}" =3D set; then :
   enableval=3D$enable_libtool_lock;
 fi
=20
@@ -5658,100 +6726,107 @@
 ia64-*-hpux*)
   # Find out which ABI we are using.
   echo 'int i;' > conftest.$ac_ext
-  if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } =
>&5
   (eval $ac_compile) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then
     case `/usr/bin/file conftest.$ac_objext` in
-    *ELF-32*)
-      HPUX_IA64_MODE=3D"32"
-      ;;
-    *ELF-64*)
-      HPUX_IA64_MODE=3D"64"
-      ;;
+      *ELF-32*)
+	HPUX_IA64_MODE=3D"32"
+	;;
+      *ELF-64*)
+	HPUX_IA64_MODE=3D"64"
+	;;
     esac
   fi
   rm -rf conftest*
   ;;
 *-*-irix6*)
   # Find out which ABI we are using.
-  echo '#line 5679 "configure"' > conftest.$ac_ext
-  if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  echo '#line '$LINENO' "configure"' > conftest.$ac_ext
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } =
>&5
   (eval $ac_compile) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
-   if test "$lt_cv_prog_gnu_ld" =3D yes; then
-    case `/usr/bin/file conftest.$ac_objext` in
-    *32-bit*)
-      LD=3D"${LD-ld} -melf32bsmip"
-      ;;
-    *N32*)
-      LD=3D"${LD-ld} -melf32bmipn32"
-      ;;
-    *64-bit*)
-      LD=3D"${LD-ld} -melf64bmip"
-      ;;
-    esac
-   else
-    case `/usr/bin/file conftest.$ac_objext` in
-    *32-bit*)
-      LD=3D"${LD-ld} -32"
-      ;;
-    *N32*)
-      LD=3D"${LD-ld} -n32"
-      ;;
-    *64-bit*)
-      LD=3D"${LD-ld} -64"
-      ;;
-    esac
-   fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then
+    if test "$lt_cv_prog_gnu_ld" =3D yes; then
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD=3D"${LD-ld} -melf32bsmip"
+	  ;;
+	*N32*)
+	  LD=3D"${LD-ld} -melf32bmipn32"
+	  ;;
+	*64-bit*)
+	  LD=3D"${LD-ld} -melf64bmip"
+	;;
+      esac
+    else
+      case `/usr/bin/file conftest.$ac_objext` in
+	*32-bit*)
+	  LD=3D"${LD-ld} -32"
+	  ;;
+	*N32*)
+	  LD=3D"${LD-ld} -n32"
+	  ;;
+	*64-bit*)
+	  LD=3D"${LD-ld} -64"
+	  ;;
+      esac
+    fi
   fi
   rm -rf conftest*
   ;;
=20
-x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*|s390*-*linux*|sparc*-*linux*)
+x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \
+s390*-*linux*|s390*-*tpf*|sparc*-*linux*)
   # Find out which ABI we are using.
   echo 'int i;' > conftest.$ac_ext
-  if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } =
>&5
   (eval $ac_compile) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then
     case `/usr/bin/file conftest.o` in
-    *32-bit*)
-      case $host in
-        x86_64-*linux*)
-          LD=3D"${LD-ld} -m elf_i386"
-          ;;
-        ppc64-*linux*|powerpc64-*linux*)
-          LD=3D"${LD-ld} -m elf32ppclinux"
-          ;;
-        s390x-*linux*)
-          LD=3D"${LD-ld} -m elf_s390"
-          ;;
-        sparc64-*linux*)
-          LD=3D"${LD-ld} -m elf32_sparc"
-          ;;
-      esac
-      ;;
-    *64-bit*)
-      case $host in
-        x86_64-*linux*)
-          LD=3D"${LD-ld} -m elf_x86_64"
-          ;;
-        ppc*-*linux*|powerpc*-*linux*)
-          LD=3D"${LD-ld} -m elf64ppc"
-          ;;
-        s390*-*linux*)
-          LD=3D"${LD-ld} -m elf64_s390"
-          ;;
-        sparc*-*linux*)
-          LD=3D"${LD-ld} -m elf64_sparc"
-          ;;
-      esac
-      ;;
+      *32-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD=3D"${LD-ld} -m elf_i386_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD=3D"${LD-ld} -m elf_i386"
+	    ;;
+	  ppc64-*linux*|powerpc64-*linux*)
+	    LD=3D"${LD-ld} -m elf32ppclinux"
+	    ;;
+	  s390x-*linux*)
+	    LD=3D"${LD-ld} -m elf_s390"
+	    ;;
+	  sparc64-*linux*)
+	    LD=3D"${LD-ld} -m elf32_sparc"
+	    ;;
+	esac
+	;;
+      *64-bit*)
+	case $host in
+	  x86_64-*kfreebsd*-gnu)
+	    LD=3D"${LD-ld} -m elf_x86_64_fbsd"
+	    ;;
+	  x86_64-*linux*)
+	    LD=3D"${LD-ld} -m elf_x86_64"
+	    ;;
+	  ppc*-*linux*|powerpc*-*linux*)
+	    LD=3D"${LD-ld} -m elf64ppc"
+	    ;;
+	  s390*-*linux*|s390*-*tpf*)
+	    LD=3D"${LD-ld} -m elf64_s390"
+	    ;;
+	  sparc*-*linux*)
+	    LD=3D"${LD-ld} -m elf64_sparc"
+	    ;;
+	esac
+	;;
     esac
   fi
   rm -rf conftest*
@@ -5761,10 +6836,10 @@
   # On SCO OpenServer 5, we need -belf to get full-featured binaries.
   SAVE_CFLAGS=3D"$CFLAGS"
   CFLAGS=3D"$CFLAGS -belf"
-  { echo "$as_me:$LINENO: checking whether the C compiler needs -belf" >&5
-echo $ECHO_N "checking whether the C compiler needs -belf... $ECHO_C" >&6;=
 }
-if test "${lt_cv_cc_needs_belf+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler=
 needs -belf" >&5
+$as_echo_n "checking whether the C compiler needs -belf... " >&6; }
+if test "${lt_cv_cc_needs_belf+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_ext=3Dc
 ac_cpp=3D'$CPP $CPPFLAGS'
@@ -5772,49 +6847,24 @@
 ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
 ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
=20
-     cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
   lt_cv_cc_needs_belf=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	lt_cv_cc_needs_belf=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  lt_cv_cc_needs_belf=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
      ac_ext=3Dc
 ac_cpp=3D'$CPP $CPPFLAGS'
 ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -5822,8 +6872,8 @@
 ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
=20
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_cc_needs_belf" >&5
-echo "${ECHO_T}$lt_cv_cc_needs_belf" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5
+$as_echo "$lt_cv_cc_needs_belf" >&6; }
   if test x"$lt_cv_cc_needs_belf" !=3D x"yes"; then
     # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf
     CFLAGS=3D"$SAVE_CFLAGS"
@@ -5832,40 +6882,771 @@
 sparc*-*solaris*)
   # Find out which ABI we are using.
   echo 'int i;' > conftest.$ac_ext
-  if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } =
>&5
   (eval $ac_compile) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then
     case `/usr/bin/file conftest.o` in
     *64-bit*)
       case $lt_cv_prog_gnu_ld in
       yes*) LD=3D"${LD-ld} -m elf64_sparc" ;;
-      *)    LD=3D"${LD-ld} -64" ;;
+      *)
+	if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then
+	  LD=3D"${LD-ld} -64"
+	fi
+	;;
       esac
       ;;
     esac
   fi
   rm -rf conftest*
   ;;
-
-
 esac
=20
 need_locks=3D"$enable_libtool_lock"
=20
-
-
-{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5
-echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; }
-if test "${ac_cv_header_stdc+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}mt", so it can be a progra=
m name with args.
+set dummy ${ac_tool_prefix}mt; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_MANIFEST_TOOL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$MANIFEST_TOOL"; then
+  ac_cv_prog_MANIFEST_TOOL=3D"$MANIFEST_TOOL" # Let the user override the =
test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_MANIFEST_TOOL=3D"${ac_tool_prefix}mt"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+MANIFEST_TOOL=3D$ac_cv_prog_MANIFEST_TOOL
+if test -n "$MANIFEST_TOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5
+$as_echo "$MANIFEST_TOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_MANIFEST_TOOL"; then
+  ac_ct_MANIFEST_TOOL=3D$MANIFEST_TOOL
+  # Extract the first word of "mt", so it can be a program name with args.
+set dummy mt; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_MANIFEST_TOOL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_MANIFEST_TOOL"; then
+  ac_cv_prog_ac_ct_MANIFEST_TOOL=3D"$ac_ct_MANIFEST_TOOL" # Let the user o=
verride the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_MANIFEST_TOOL=3D"mt"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_MANIFEST_TOOL=3D$ac_cv_prog_ac_ct_MANIFEST_TOOL
+if test -n "$ac_ct_MANIFEST_TOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >=
&5
+$as_echo "$ac_ct_MANIFEST_TOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_MANIFEST_TOOL" =3D x; then
+    MANIFEST_TOOL=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    MANIFEST_TOOL=3D$ac_ct_MANIFEST_TOOL
+  fi
+else
+  MANIFEST_TOOL=3D"$ac_cv_prog_MANIFEST_TOOL"
+fi
+
+test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=3Dmt
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a m=
anifest tool" >&5
+$as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; }
+if test "${lt_cv_path_mainfest_tool+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_path_mainfest_tool=3Dno
+  echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5
+  $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out
+  cat conftest.err >&5
+  if $GREP 'Manifest Tool' conftest.out > /dev/null; then
+    lt_cv_path_mainfest_tool=3Dyes
+  fi
+  rm -f conftest*
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool=
" >&5
+$as_echo "$lt_cv_path_mainfest_tool" >&6; }
+if test "x$lt_cv_path_mainfest_tool" !=3D xyes; then
+  MANIFEST_TOOL=3D:
+fi
+
+
+
+
+
+
+  case $host_os in
+    rhapsody* | darwin*)
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a =
program name with args.
+set dummy ${ac_tool_prefix}dsymutil; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_DSYMUTIL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$DSYMUTIL"; then
+  ac_cv_prog_DSYMUTIL=3D"$DSYMUTIL" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_DSYMUTIL=3D"${ac_tool_prefix}dsymutil"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+DSYMUTIL=3D$ac_cv_prog_DSYMUTIL
+if test -n "$DSYMUTIL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5
+$as_echo "$DSYMUTIL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_DSYMUTIL"; then
+  ac_ct_DSYMUTIL=3D$DSYMUTIL
+  # Extract the first word of "dsymutil", so it can be a program name with=
 args.
+set dummy dsymutil; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_DSYMUTIL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_DSYMUTIL"; then
+  ac_cv_prog_ac_ct_DSYMUTIL=3D"$ac_ct_DSYMUTIL" # Let the user override th=
e test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_DSYMUTIL=3D"dsymutil"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_DSYMUTIL=3D$ac_cv_prog_ac_ct_DSYMUTIL
+if test -n "$ac_ct_DSYMUTIL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5
+$as_echo "$ac_ct_DSYMUTIL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_DSYMUTIL" =3D x; then
+    DSYMUTIL=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    DSYMUTIL=3D$ac_ct_DSYMUTIL
+  fi
+else
+  DSYMUTIL=3D"$ac_cv_prog_DSYMUTIL"
+fi
+
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a pr=
ogram name with args.
+set dummy ${ac_tool_prefix}nmedit; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_NMEDIT+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$NMEDIT"; then
+  ac_cv_prog_NMEDIT=3D"$NMEDIT" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_NMEDIT=3D"${ac_tool_prefix}nmedit"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+NMEDIT=3D$ac_cv_prog_NMEDIT
+if test -n "$NMEDIT"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5
+$as_echo "$NMEDIT" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_NMEDIT"; then
+  ac_ct_NMEDIT=3D$NMEDIT
+  # Extract the first word of "nmedit", so it can be a program name with a=
rgs.
+set dummy nmedit; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_NMEDIT+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_NMEDIT"; then
+  ac_cv_prog_ac_ct_NMEDIT=3D"$ac_ct_NMEDIT" # Let the user override the te=
st.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_NMEDIT=3D"nmedit"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_NMEDIT=3D$ac_cv_prog_ac_ct_NMEDIT
+if test -n "$ac_ct_NMEDIT"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5
+$as_echo "$ac_ct_NMEDIT" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_NMEDIT" =3D x; then
+    NMEDIT=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    NMEDIT=3D$ac_ct_NMEDIT
+  fi
+else
+  NMEDIT=3D"$ac_cv_prog_NMEDIT"
+fi
+
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}lipo", so it can be a prog=
ram name with args.
+set dummy ${ac_tool_prefix}lipo; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_LIPO+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$LIPO"; then
+  ac_cv_prog_LIPO=3D"$LIPO" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_LIPO=3D"${ac_tool_prefix}lipo"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+LIPO=3D$ac_cv_prog_LIPO
+if test -n "$LIPO"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5
+$as_echo "$LIPO" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_LIPO"; then
+  ac_ct_LIPO=3D$LIPO
+  # Extract the first word of "lipo", so it can be a program name with arg=
s.
+set dummy lipo; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_LIPO+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_LIPO"; then
+  ac_cv_prog_ac_ct_LIPO=3D"$ac_ct_LIPO" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_LIPO=3D"lipo"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_LIPO=3D$ac_cv_prog_ac_ct_LIPO
+if test -n "$ac_ct_LIPO"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5
+$as_echo "$ac_ct_LIPO" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_LIPO" =3D x; then
+    LIPO=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    LIPO=3D$ac_ct_LIPO
+  fi
+else
+  LIPO=3D"$ac_cv_prog_LIPO"
+fi
+
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}otool", so it can be a pro=
gram name with args.
+set dummy ${ac_tool_prefix}otool; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_OTOOL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$OTOOL"; then
+  ac_cv_prog_OTOOL=3D"$OTOOL" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_OTOOL=3D"${ac_tool_prefix}otool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+OTOOL=3D$ac_cv_prog_OTOOL
+if test -n "$OTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5
+$as_echo "$OTOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_OTOOL"; then
+  ac_ct_OTOOL=3D$OTOOL
+  # Extract the first word of "otool", so it can be a program name with ar=
gs.
+set dummy otool; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_OTOOL+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_OTOOL"; then
+  ac_cv_prog_ac_ct_OTOOL=3D"$ac_ct_OTOOL" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_OTOOL=3D"otool"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_OTOOL=3D$ac_cv_prog_ac_ct_OTOOL
+if test -n "$ac_ct_OTOOL"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5
+$as_echo "$ac_ct_OTOOL" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_OTOOL" =3D x; then
+    OTOOL=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    OTOOL=3D$ac_ct_OTOOL
+  fi
+else
+  OTOOL=3D"$ac_cv_prog_OTOOL"
+fi
+
+    if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}otool64", so it can be a p=
rogram name with args.
+set dummy ${ac_tool_prefix}otool64; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_OTOOL64+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$OTOOL64"; then
+  ac_cv_prog_OTOOL64=3D"$OTOOL64" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_OTOOL64=3D"${ac_tool_prefix}otool64"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+OTOOL64=3D$ac_cv_prog_OTOOL64
+if test -n "$OTOOL64"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5
+$as_echo "$OTOOL64" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_OTOOL64"; then
+  ac_ct_OTOOL64=3D$OTOOL64
+  # Extract the first word of "otool64", so it can be a program name with =
args.
+set dummy otool64; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_OTOOL64+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_OTOOL64"; then
+  ac_cv_prog_ac_ct_OTOOL64=3D"$ac_ct_OTOOL64" # Let the user override the =
test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_OTOOL64=3D"otool64"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+ac_ct_OTOOL64=3D$ac_cv_prog_ac_ct_OTOOL64
+if test -n "$ac_ct_OTOOL64"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5
+$as_echo "$ac_ct_OTOOL64" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_OTOOL64" =3D x; then
+    OTOOL64=3D":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    OTOOL64=3D$ac_ct_OTOOL64
+  fi
+else
+  OTOOL64=3D"$ac_cv_prog_OTOOL64"
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module l=
inker flag" >&5
+$as_echo_n "checking for -single_module linker flag... " >&6; }
+if test "${lt_cv_apple_cc_single_mod+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_apple_cc_single_mod=3Dno
+      if test -z "${LT_MULTI_MODULE}"; then
+	# By default we will add the -single_module flag. You can override
+	# by either setting the environment variable LT_MULTI_MODULE
+	# non-empty at configure time, or by adding -multi_module to the
+	# link flags.
+	rm -rf libconftest.dylib*
+	echo "int foo(void){return 1;}" > conftest.c
+	echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+-dynamiclib -Wl,-single_module conftest.c" >&5
+	$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \
+	  -dynamiclib -Wl,-single_module conftest.c 2>conftest.err
+        _lt_result=3D$?
+	if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_resul=
t =3D 0; then
+	  lt_cv_apple_cc_single_mod=3Dyes
+	else
+	  cat conftest.err >&5
+	fi
+	rm -rf libconftest.dylib*
+	rm -f conftest.*
+      fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mo=
d" >&5
+$as_echo "$lt_cv_apple_cc_single_mod" >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbol=
s_list linker flag" >&5
+$as_echo_n "checking for -exported_symbols_list linker flag... " >&6; }
+if test "${lt_cv_ld_exported_symbols_list+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_ld_exported_symbols_list=3Dno
+      save_LDFLAGS=3D$LDFLAGS
+      echo "_main" > conftest.sym
+      LDFLAGS=3D"$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  lt_cv_ld_exported_symbols_list=3Dyes
+else
+  lt_cv_ld_exported_symbols_list=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	LDFLAGS=3D"$save_LDFLAGS"
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbol=
s_list" >&5
+$as_echo "$lt_cv_ld_exported_symbols_list" >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load link=
er flag" >&5
+$as_echo_n "checking for -force_load linker flag... " >&6; }
+if test "${lt_cv_ld_force_load+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_ld_force_load=3Dno
+      cat > conftest.c << _LT_EOF
+int forced_loaded() { return 2;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5
+      $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5
+      echo "$AR cru libconftest.a conftest.o" >&5
+      $AR cru libconftest.a conftest.o 2>&5
+      echo "$RANLIB libconftest.a" >&5
+      $RANLIB libconftest.a 2>&5
+      cat > conftest.c << _LT_EOF
+int main() { return 0;}
+_LT_EOF
+      echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_loa=
d,./libconftest.a" >&5
+      $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./li=
bconftest.a 2>conftest.err
+      _lt_result=3D$?
+      if test -f conftest && test ! -s conftest.err && test $_lt_result =
=3D 0 && $GREP forced_load conftest 2>&1 >/dev/null; then
+	lt_cv_ld_force_load=3Dyes
+      else
+	cat conftest.err >&5
+      fi
+        rm -f conftest.err libconftest.a conftest conftest.c
+        rm -rf conftest.dSYM
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5
+$as_echo "$lt_cv_ld_force_load" >&6; }
+    case $host_os in
+    rhapsody* | darwin1.[012])
+      _lt_dar_allow_undefined=3D'${wl}-undefined ${wl}suppress' ;;
+    darwin1.*)
+      _lt_dar_allow_undefined=3D'${wl}-flat_namespace ${wl}-undefined ${wl=
}suppress' ;;
+    darwin*) # darwin 5.x on
+      # if running on 10.5 or later, the deployment target defaults
+      # to the OS version, if on x86, and 10.4, the deployment
+      # target defaults to 10.4. Don't you love it?
+      case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in
+	10.0,*86*-darwin8*|10.0,*-darwin[91]*)
+	  _lt_dar_allow_undefined=3D'${wl}-undefined ${wl}dynamic_lookup' ;;
+	10.[012]*)
+	  _lt_dar_allow_undefined=3D'${wl}-flat_namespace ${wl}-undefined ${wl}su=
ppress' ;;
+	10.*)
+	  _lt_dar_allow_undefined=3D'${wl}-undefined ${wl}dynamic_lookup' ;;
+      esac
+    ;;
+  esac
+    if test "$lt_cv_apple_cc_single_mod" =3D "yes"; then
+      _lt_dar_single_mod=3D'$single_module'
+    fi
+    if test "$lt_cv_ld_exported_symbols_list" =3D "yes"; then
+      _lt_dar_export_syms=3D' ${wl}-exported_symbols_list,$output_objdir/$=
{libname}-symbols.expsym'
+    else
+      _lt_dar_export_syms=3D'~$NMEDIT -s $output_objdir/${libname}-symbols=
.expsym ${lib}'
+    fi
+    if test "$DSYMUTIL" !=3D ":" && test "$lt_cv_ld_force_load" =3D "no"; =
then
+      _lt_dsymutil=3D'~$DSYMUTIL $lib || :'
+    else
+      _lt_dsymutil=3D
+    fi
+    ;;
+  esac
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files"=
 >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if test "${ac_cv_header_stdc+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdlib.h>
 #include <stdarg.h>
@@ -5880,47 +7661,23 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_header_stdc=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_header_stdc=3Dno
-fi
-
+  ac_cv_header_stdc=3Dno
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
=20
 if test $ac_cv_header_stdc =3D yes; then
   # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <string.h>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then
-  :
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
 else
   ac_cv_header_stdc=3Dno
 fi
@@ -5930,18 +7687,14 @@
=20
 if test $ac_cv_header_stdc =3D yes; then
   # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdlib.h>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then
-  :
+  $EGREP "free" >/dev/null 2>&1; then :
+
 else
   ac_cv_header_stdc=3Dno
 fi
@@ -5951,14 +7704,10 @@
=20
 if test $ac_cv_header_stdc =3D yes; then
   # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" =3D yes; then
+  if test "$cross_compiling" =3D yes; then :
   :
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <ctype.h>
 #include <stdlib.h>
@@ -5985,1464 +7734,236 @@
   return 0;
 }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
-else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_header_stdc=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
-echo "${ECHO_T}$ac_cv_header_stdc" >&6; }
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
 if test $ac_cv_header_stdc =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define STDC_HEADERS 1
-_ACEOF
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
=20
 fi
=20
 # On IRIX 5.3, sys/types and inttypes.h are conflicting.
-
-
-
-
-
-
-
-
-
 for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings=
.h \
 		  inttypes.h stdint.h unistd.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default
+"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in dlfcn.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-ac_ext=3Dcpp
-ac_cpp=3D'$CXXCPP $CPPFLAGS'
-ac_compile=3D'$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftes=
t.$ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_cxx_compiler_gnu
-if test -z "$CXX"; then
-  if test -n "$CCC"; then
-    CXX=3D$CCC
-  else
-    if test -n "$ac_tool_prefix"; then
-  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a =
program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_CXX+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$CXX"; then
-  ac_cv_prog_CXX=3D"$CXX" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_CXX=3D"$ac_tool_prefix$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-CXX=3D$ac_cv_prog_CXX
-if test -n "$CXX"; then
-  { echo "$as_me:$LINENO: result: $CXX" >&5
-echo "${ECHO_T}$CXX" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-    test -n "$CXX" && break
-  done
-fi
-if test -z "$CXX"; then
-  ac_ct_CXX=3D$CXX
-  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
-set dummy $ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_CXX+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_CXX"; then
-  ac_cv_prog_ac_ct_CXX=3D"$ac_ct_CXX" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_ac_ct_CXX=3D"$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-ac_ct_CXX=3D$ac_cv_prog_ac_ct_CXX
-if test -n "$ac_ct_CXX"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
-echo "${ECHO_T}$ac_ct_CXX" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-  test -n "$ac_ct_CXX" && break
-done
-
-  if test "x$ac_ct_CXX" =3D x; then
-    CXX=3D"g++"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=3Dyes ;;
-esac
-    CXX=3D$ac_ct_CXX
-  fi
-fi
-
-  fi
-fi
-# Provide some information about the compiler.
-echo "$as_me:$LINENO: checking for C++ compiler version" >&5
-ac_compiler=3D`set X $ac_compile; echo $2`
-{ (ac_try=3D"$ac_compiler --version >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler --version >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-{ (ac_try=3D"$ac_compiler -v >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -v >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-{ (ac_try=3D"$ac_compiler -V >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -V >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-
-{ echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler=
" >&5
-echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_=
C" >&6; }
-if test "${ac_cv_cxx_compiler_gnu+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-#ifndef __GNUC__
-       choke me
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_compiler_gnu=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_compiler_gnu=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_cxx_compiler_gnu=3D$ac_compiler_gnu
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6; }
-GXX=3D`test $ac_compiler_gnu =3D yes && echo yes`
-ac_test_CXXFLAGS=3D${CXXFLAGS+set}
-ac_save_CXXFLAGS=3D$CXXFLAGS
-{ echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
-echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6; }
-if test "${ac_cv_prog_cxx_g+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_save_cxx_werror_flag=3D$ac_cxx_werror_flag
-   ac_cxx_werror_flag=3Dyes
-   ac_cv_prog_cxx_g=3Dno
-   CXXFLAGS=3D"-g"
-   cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_prog_cxx_g=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	CXXFLAGS=3D""
-      cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cxx_werror_flag=3D$ac_save_cxx_werror_flag
-	 CXXFLAGS=3D"-g"
-	 cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_prog_cxx_g=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-   ac_cxx_werror_flag=3D$ac_save_cxx_werror_flag
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6; }
-if test "$ac_test_CXXFLAGS" =3D set; then
-  CXXFLAGS=3D$ac_save_CXXFLAGS
-elif test $ac_cv_prog_cxx_g =3D yes; then
-  if test "$GXX" =3D yes; then
-    CXXFLAGS=3D"-g -O2"
-  else
-    CXXFLAGS=3D"-g"
-  fi
-else
-  if test "$GXX" =3D yes; then
-    CXXFLAGS=3D"-O2"
-  else
-    CXXFLAGS=3D
-  fi
-fi
-ac_ext=3Dcpp
-ac_cpp=3D'$CXXCPP $CPPFLAGS'
-ac_compile=3D'$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftes=
t.$ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_cxx_compiler_gnu
-
-
-
-if test -n "$CXX" && ( test "X$CXX" !=3D "Xno" &&
-    ( (test "X$CXX" =3D "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-    (test "X$CXX" !=3D "Xg++"))) ; then
-  ac_ext=3Dcpp
-ac_cpp=3D'$CXXCPP $CPPFLAGS'
-ac_compile=3D'$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftes=
t.$ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_cxx_compiler_gnu
-{ echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5
-echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6; }
-if test -z "$CXXCPP"; then
-  if test "${ac_cv_prog_CXXCPP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-      # Double quotes because CXXCPP needs to be expanded
-    for CXXCPP in "$CXX -E" "/lib/cpp"
-    do
-      ac_preproc_ok=3Dfalse
-for ac_cxx_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Broken: fails on valid input.
-continue
-fi
-
-rm -f conftest.err conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  # Broken: success on invalid input.
-continue
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Passes both tests.
-ac_preproc_ok=3D:
-break
-fi
-
-rm -f conftest.err conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
-  break
-fi
-
-    done
-    ac_cv_prog_CXXCPP=3D$CXXCPP
-
-fi
-  CXXCPP=3D$ac_cv_prog_CXXCPP
-else
-  ac_cv_prog_CXXCPP=3D$CXXCPP
-fi
-{ echo "$as_me:$LINENO: result: $CXXCPP" >&5
-echo "${ECHO_T}$CXXCPP" >&6; }
-ac_preproc_ok=3Dfalse
-for ac_cxx_preproc_warn_flag in '' yes
-do
-  # Use a header file that comes with gcc, so configuring glibc
-  # with a fresh cross-compiler works.
-  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-  # <limits.h> exists even on freestanding compilers.
-  # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp. "Syntax error" is here to catch this case.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-		     Syntax error
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Broken: fails on valid input.
-continue
-fi
-
-rm -f conftest.err conftest.$ac_ext
-
-  # OK, works on sane cases.  Now check whether nonexistent headers
-  # can be detected and how.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <ac_nonexistent.h>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  # Broken: success on invalid input.
-continue
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  # Passes both tests.
-ac_preproc_ok=3D:
-break
-fi
-
-rm -f conftest.err conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then
-  :
-else
-  { { echo "$as_me:$LINENO: error: C++ preprocessor \"$CXXCPP\" fails sani=
ty check
-See \`config.log' for more details." >&5
-echo "$as_me: error: C++ preprocessor \"$CXXCPP\" fails sanity check
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-ac_ext=3Dcpp
-ac_cpp=3D'$CXXCPP $CPPFLAGS'
-ac_compile=3D'$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftes=
t.$ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_cxx_compiler_gnu
-
-fi
-
-
-ac_ext=3Df
-ac_compile=3D'$F77 -c $FFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $L=
IBS >&5'
-ac_compiler_gnu=3D$ac_cv_f77_compiler_gnu
-if test -n "$ac_tool_prefix"; then
-  for ac_prog in g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 xlf90 f90 pgf=
90 pghpf epcf90 gfortran g95 xlf95 f95 fort ifort ifc efc pgf95 lf95 ftn
-  do
-    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a =
program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_F77+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$F77"; then
-  ac_cv_prog_F77=3D"$F77" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_F77=3D"$ac_tool_prefix$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-F77=3D$ac_cv_prog_F77
-if test -n "$F77"; then
-  { echo "$as_me:$LINENO: result: $F77" >&5
-echo "${ECHO_T}$F77" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-    test -n "$F77" && break
-  done
-fi
-if test -z "$F77"; then
-  ac_ct_F77=3D$F77
-  for ac_prog in g77 xlf f77 frt pgf77 cf77 fort77 fl32 af77 xlf90 f90 pgf=
90 pghpf epcf90 gfortran g95 xlf95 f95 fort ifort ifc efc pgf95 lf95 ftn
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
-set dummy $ac_prog; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_F77+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_F77"; then
-  ac_cv_prog_ac_ct_F77=3D"$ac_ct_F77" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_ac_ct_F77=3D"$ac_prog"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-ac_ct_F77=3D$ac_cv_prog_ac_ct_F77
-if test -n "$ac_ct_F77"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_F77" >&5
-echo "${ECHO_T}$ac_ct_F77" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-  test -n "$ac_ct_F77" && break
-done
-
-  if test "x$ac_ct_F77" =3D x; then
-    F77=3D""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=3Dyes ;;
-esac
-    F77=3D$ac_ct_F77
-  fi
-fi
-
-
-# Provide some information about the compiler.
-echo "$as_me:$LINENO: checking for Fortran 77 compiler version" >&5
-ac_compiler=3D`set X $ac_compile; echo $2`
-{ (ac_try=3D"$ac_compiler --version >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler --version >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-{ (ac_try=3D"$ac_compiler -v >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -v >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-{ (ac_try=3D"$ac_compiler -V >&5"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compiler -V >&5") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-rm -f a.out
-
-# If we don't use `.F' as extension, the preprocessor is not run on the
-# input file.  (Note that this only needs to work for GNU compilers.)
-ac_save_ext=3D$ac_ext
-ac_ext=3DF
-{ echo "$as_me:$LINENO: checking whether we are using the GNU Fortran 77 c=
ompiler" >&5
-echo $ECHO_N "checking whether we are using the GNU Fortran 77 compiler...=
 $ECHO_C" >&6; }
-if test "${ac_cv_f77_compiler_gnu+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-      program main
-#ifndef __GNUC__
-       choke me
-#endif
-
-      end
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_compiler_gnu=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_compiler_gnu=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_f77_compiler_gnu=3D$ac_compiler_gnu
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_f77_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_f77_compiler_gnu" >&6; }
-ac_ext=3D$ac_save_ext
-ac_test_FFLAGS=3D${FFLAGS+set}
-ac_save_FFLAGS=3D$FFLAGS
-FFLAGS=3D
-{ echo "$as_me:$LINENO: checking whether $F77 accepts -g" >&5
-echo $ECHO_N "checking whether $F77 accepts -g... $ECHO_C" >&6; }
-if test "${ac_cv_prog_f77_g+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  FFLAGS=3D-g
-cat >conftest.$ac_ext <<_ACEOF
-      program main
-
-      end
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_prog_f77_g=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_prog_f77_g=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_prog_f77_g" >&5
-echo "${ECHO_T}$ac_cv_prog_f77_g" >&6; }
-if test "$ac_test_FFLAGS" =3D set; then
-  FFLAGS=3D$ac_save_FFLAGS
-elif test $ac_cv_prog_f77_g =3D yes; then
-  if test "x$ac_cv_f77_compiler_gnu" =3D xyes; then
-    FFLAGS=3D"-g -O2"
-  else
-    FFLAGS=3D"-g"
-  fi
-else
-  if test "x$ac_cv_f77_compiler_gnu" =3D xyes; then
-    FFLAGS=3D"-O2"
-  else
-    FFLAGS=3D
-  fi
-fi
-
-G77=3D`test $ac_compiler_gnu =3D yes && echo yes`
-ac_ext=3Dc
-ac_cpp=3D'$CPP $CPPFLAGS'
-ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
-
-
-
-# Autoconf 2.13's AC_OBJEXT and AC_EXEEXT macros only works for C compiler=
s!
-
-# find the maximum length of command line arguments
-{ echo "$as_me:$LINENO: checking the maximum length of command line argume=
nts" >&5
-echo $ECHO_N "checking the maximum length of command line arguments... $EC=
HO_C" >&6; }
-if test "${lt_cv_sys_max_cmd_len+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-    i=3D0
-  teststring=3D"ABCD"
-
-  case $build_os in
-  msdosdjgpp*)
-    # On DJGPP, this test can blow up pretty badly due to problems in libc
-    # (any single argument exceeding 2000 bytes causes a buffer overrun
-    # during glob expansion).  Even if it were fixed, the result of this
-    # check would be larger than it should be.
-    lt_cv_sys_max_cmd_len=3D12288;    # 12K is about right
-    ;;
-
-  gnu*)
-    # Under GNU Hurd, this test is not required because there is
-    # no limit to the length of command line arguments.
-    # Libtool will interpret -1 as no limit whatsoever
-    lt_cv_sys_max_cmd_len=3D-1;
-    ;;
-
-  cygwin* | mingw*)
-    # On Win9x/ME, this test blows up -- it succeeds, but takes
-    # about 5 minutes as the teststring grows exponentially.
-    # Worse, since 9x/ME are not pre-emptively multitasking,
-    # you end up with a "frozen" computer, even though with patience
-    # the test eventually succeeds (with a max line length of 256k).
-    # Instead, let's just punt: use the minimum linelength reported by
-    # all of the supported platforms: 8192 (on NT/2K/XP).
-    lt_cv_sys_max_cmd_len=3D8192;
-    ;;
-
-  amigaos*)
-    # On AmigaOS with pdksh, this test takes hours, literally.
-    # So we just punt and use a minimum line length of 8192.
-    lt_cv_sys_max_cmd_len=3D8192;
-    ;;
-
-  netbsd* | freebsd* | openbsd* | darwin* | dragonfly*)
-    # This has been around since 386BSD, at least.  Likely further.
-    if test -x /sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=3D`/sbin/sysctl -n kern.argmax`
-    elif test -x /usr/sbin/sysctl; then
-      lt_cv_sys_max_cmd_len=3D`/usr/sbin/sysctl -n kern.argmax`
-    else
-      lt_cv_sys_max_cmd_len=3D65536	# usable default for all BSDs
-    fi
-    # And add a safety zone
-    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \/ 4`
-    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \* 3`
-    ;;
-
-  interix*)
-    # We know the value 262144 and hardcode it with a safety zone (like BS=
D)
-    lt_cv_sys_max_cmd_len=3D196608
-    ;;
-
-  osf*)
-    # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running conf=
igure
-    # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not
-    # nice to cause kernel panics so lets avoid the loop below.
-    # First set a reasonable default.
-    lt_cv_sys_max_cmd_len=3D16384
-    #
-    if test -x /sbin/sysconfig; then
-      case `/sbin/sysconfig -q proc exec_disable_arg_limit` in
-        *1*) lt_cv_sys_max_cmd_len=3D-1 ;;
-      esac
-    fi
-    ;;
-  sco3.2v5*)
-    lt_cv_sys_max_cmd_len=3D102400
-    ;;
-  sysv5* | sco5v6* | sysv4.2uw2*)
-    kargmax=3D`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null`
-    if test -n "$kargmax"; then
-      lt_cv_sys_max_cmd_len=3D`echo $kargmax | sed 's/.*[ 	]//'`
-    else
-      lt_cv_sys_max_cmd_len=3D32768
-    fi
-    ;;
-  *)
-    # If test is not a shell built-in, we'll probably end up computing a
-    # maximum length that is only half of the actual maximum length, but
-    # we can't tell.
-    SHELL=3D${SHELL-${CONFIG_SHELL-/bin/sh}}
-    while (test "X"`$SHELL $0 --fallback-echo "X$teststring" 2>/dev/null` \
-	       =3D "XX$teststring") >/dev/null 2>&1 &&
-	    new_result=3D`expr "X$teststring" : ".*" 2>&1` &&
-	    lt_cv_sys_max_cmd_len=3D$new_result &&
-	    test $i !=3D 17 # 1/2 MB should be enough
-    do
-      i=3D`expr $i + 1`
-      teststring=3D$teststring$teststring
-    done
-    teststring=3D
-    # Add a significant safety factor because C++ compilers can tack on ma=
ssive
-    # amounts of additional arguments before passing them to the linker.
-    # It appears as though 1/2 is a usable value.
-    lt_cv_sys_max_cmd_len=3D`expr $lt_cv_sys_max_cmd_len \/ 2`
-    ;;
-  esac
-
-fi
-
-if test -n $lt_cv_sys_max_cmd_len ; then
-  { echo "$as_me:$LINENO: result: $lt_cv_sys_max_cmd_len" >&5
-echo "${ECHO_T}$lt_cv_sys_max_cmd_len" >&6; }
-else
-  { echo "$as_me:$LINENO: result: none" >&5
-echo "${ECHO_T}none" >&6; }
-fi
-
-
-
-
-# Check for command to grab the raw symbol name followed by C symbol from =
nm.
-{ echo "$as_me:$LINENO: checking command to parse $NM output from $compile=
r object" >&5
-echo $ECHO_N "checking command to parse $NM output from $compiler object..=
. $ECHO_C" >&6; }
-if test "${lt_cv_sys_global_symbol_pipe+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-# These are sane defaults that work on at least a few old systems.
-# [They come from Ultrix.  What could be older than Ultrix?!! ;)]
-
-# Character class describing NM global symbol codes.
-symcode=3D'[BCDEGRST]'
-
-# Regexp to match symbols that can be accessed directly from C.
-sympat=3D'\([_A-Za-z][_A-Za-z0-9]*\)'
-
-# Transform an extracted symbol line into a proper C declaration
-lt_cv_sys_global_symbol_to_cdecl=3D"sed -n -e 's/^. .* \(.*\)$/extern int =
\1;/p'"
-
-# Transform an extracted symbol line into symbol name and symbol address
-lt_cv_sys_global_symbol_to_c_name_address=3D"sed -n -e 's/^: \([^ ]*\) $/ =
 {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode \([^ ]*\) \([^ ]*\)$/  {\"\2\=
", (lt_ptr) \&\2},/p'"
-
-# Define system-specific variables.
-case $host_os in
-aix*)
-  symcode=3D'[BCDT]'
-  ;;
-cygwin* | mingw* | pw32*)
-  symcode=3D'[ABCDGISTW]'
-  ;;
-hpux*) # Its linker distinguishes data from code symbols
-  if test "$host_cpu" =3D ia64; then
-    symcode=3D'[ABCDEGRST]'
-  fi
-  lt_cv_sys_global_symbol_to_cdecl=3D"sed -n -e 's/^T .* \(.*\)$/extern in=
t \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-  lt_cv_sys_global_symbol_to_c_name_address=3D"sed -n -e 's/^: \([^ ]*\) $=
/  {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {\"=
\2\", (lt_ptr) \&\2},/p'"
-  ;;
-linux*)
-  if test "$host_cpu" =3D ia64; then
-    symcode=3D'[ABCDGIRSTW]'
-    lt_cv_sys_global_symbol_to_cdecl=3D"sed -n -e 's/^T .* \(.*\)$/extern =
int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'"
-    lt_cv_sys_global_symbol_to_c_name_address=3D"sed -n -e 's/^: \([^ ]*\)=
 $/  {\\\"\1\\\", (lt_ptr) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/  {=
\"\2\", (lt_ptr) \&\2},/p'"
-  fi
-  ;;
-irix* | nonstopux*)
-  symcode=3D'[BCDEGRST]'
-  ;;
-osf*)
-  symcode=3D'[BCDEGQRST]'
-  ;;
-solaris*)
-  symcode=3D'[BDRT]'
-  ;;
-sco3.2v5*)
-  symcode=3D'[DT]'
-  ;;
-sysv4.2uw2*)
-  symcode=3D'[DT]'
-  ;;
-sysv5* | sco5v6* | unixware* | OpenUNIX*)
-  symcode=3D'[ABDT]'
-  ;;
-sysv4)
-  symcode=3D'[DFNSTU]'
-  ;;
-esac
-
-# Handle CRLF in mingw tool chain
-opt_cr=3D
-case $build_os in
-mingw*)
-  opt_cr=3D`echo 'x\{0,1\}' | tr x '\015'` # option cr in regexp
-  ;;
-esac
-
-# If we're using GNU nm, then use its standard symbol codes.
-case `$NM -V 2>&1` in
-*GNU* | *'with BFD'*)
-  symcode=3D'[ABCDGIRSTW]' ;;
-esac
-
-# Try without a prefix undercore, then with it.
-for ac_symprfx in "" "_"; do
-
-  # Transform symcode, sympat, and symprfx into a raw symbol and a C symbo=
l.
-  symxfrm=3D"\\1 $ac_symprfx\\2 \\2"
-
-  # Write the raw and C identifiers.
-  lt_cv_sys_global_symbol_pipe=3D"sed -n -e 's/^.*[ 	]\($symcode$symcode*\=
)[ 	][ 	]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'"
-
-  # Check to see that the pipe works correctly.
-  pipe_works=3Dno
-
-  rm -f conftest*
-  cat > conftest.$ac_ext <<EOF
-#ifdef __cplusplus
-extern "C" {
-#endif
-char nm_test_var;
-void nm_test_func(){}
-#ifdef __cplusplus
-}
-#endif
-int main(){nm_test_var=3D'a';nm_test_func();return(0);}
-EOF
-
-  if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
-    # Now try to grab the symbols.
-    nlist=3Dconftest.nm
-    if { (eval echo "$as_me:$LINENO: \"$NM conftest.$ac_objext \| $lt_cv_s=
ys_global_symbol_pipe \> $nlist\"") >&5
-  (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist=
) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && test -s "$nlist"; then
-      # Try sorting and uniquifying the output.
-      if sort "$nlist" | uniq > "$nlist"T; then
-	mv -f "$nlist"T "$nlist"
-      else
-	rm -f "$nlist"T
-      fi
-
-      # Make sure that we snagged all the symbols we need.
-      if grep ' nm_test_var$' "$nlist" >/dev/null; then
-	if grep ' nm_test_func$' "$nlist" >/dev/null; then
-	  cat <<EOF > conftest.$ac_ext
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-EOF
-	  # Now generate the symbol file.
-	  eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | grep -v main >> =
conftest.$ac_ext'
-
-	  cat <<EOF >> conftest.$ac_ext
-#if defined (__STDC__) && __STDC__
-# define lt_ptr_t void *
-#else
-# define lt_ptr_t char *
-# define const
-#endif
-
-/* The mapping between symbol names and symbols. */
-const struct {
-  const char *name;
-  lt_ptr_t address;
-}
-lt_preloaded_symbols[] =3D
-{
-EOF
-	  $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/  {\"\2\", (lt_ptr_t) \&\2},/=
" < "$nlist" | grep -v main >> conftest.$ac_ext
-	  cat <<\EOF >> conftest.$ac_ext
-  {0, (lt_ptr_t) 0}
-};
-
-#ifdef __cplusplus
-}
-#endif
-EOF
-	  # Now try linking the two files.
-	  mv conftest.$ac_objext conftstm.$ac_objext
-	  lt_save_LIBS=3D"$LIBS"
-	  lt_save_CFLAGS=3D"$CFLAGS"
-	  LIBS=3D"conftstm.$ac_objext"
-	  CFLAGS=3D"$CFLAGS$lt_prog_compiler_no_builtin_flag"
-	  if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && test -s conftest${ac_exeext}; then
-	    pipe_works=3Dyes
-	  fi
-	  LIBS=3D"$lt_save_LIBS"
-	  CFLAGS=3D"$lt_save_CFLAGS"
-	else
-	  echo "cannot find nm_test_func in $nlist" >&5
-	fi
-      else
-	echo "cannot find nm_test_var in $nlist" >&5
-      fi
-    else
-      echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5
-    fi
-  else
-    echo "$progname: failed program was:" >&5
-    cat conftest.$ac_ext >&5
-  fi
-  rm -f conftest* conftst*
-
-  # Do not use the global_symbol_pipe unless it works.
-  if test "$pipe_works" =3D yes; then
-    break
-  else
-    lt_cv_sys_global_symbol_pipe=3D
-  fi
-done
-
-fi
-
-if test -z "$lt_cv_sys_global_symbol_pipe"; then
-  lt_cv_sys_global_symbol_to_cdecl=3D
-fi
-if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl=
"; then
-  { echo "$as_me:$LINENO: result: failed" >&5
-echo "${ECHO_T}failed" >&6; }
-else
-  { echo "$as_me:$LINENO: result: ok" >&5
-echo "${ECHO_T}ok" >&6; }
-fi
-
-{ echo "$as_me:$LINENO: checking for objdir" >&5
-echo $ECHO_N "checking for objdir... $ECHO_C" >&6; }
-if test "${lt_cv_objdir+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+do :
+  ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" =
"$ac_includes_default
+"
+if test "x$ac_cv_header_dlfcn_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DLFCN_H 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+# Set options
+
+
+
+        enable_dlopen=3Dno
+
+
+  enable_win32_dll=3Dno
+
+
+            # Check whether --enable-shared was given.
+if test "${enable_shared+set}" =3D set; then :
+  enableval=3D$enable_shared; p=3D${PACKAGE-default}
+    case $enableval in
+    yes) enable_shared=3Dyes ;;
+    no) enable_shared=3Dno ;;
+    *)
+      enable_shared=3Dno
+      # Look at the argument we got.  We use all the common list separator=
s.
+      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS=3D"$lt_save_ifs"
+	if test "X$pkg" =3D "X$p"; then
+	  enable_shared=3Dyes
+	fi
+      done
+      IFS=3D"$lt_save_ifs"
+      ;;
+    esac
+else
+  enable_shared=3Dyes
+fi
+
+
+
+
+
+
+
+
+
+  # Check whether --enable-static was given.
+if test "${enable_static+set}" =3D set; then :
+  enableval=3D$enable_static; p=3D${PACKAGE-default}
+    case $enableval in
+    yes) enable_static=3Dyes ;;
+    no) enable_static=3Dno ;;
+    *)
+     enable_static=3Dno
+      # Look at the argument we got.  We use all the common list separator=
s.
+      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS=3D"$lt_save_ifs"
+	if test "X$pkg" =3D "X$p"; then
+	  enable_static=3Dyes
+	fi
+      done
+      IFS=3D"$lt_save_ifs"
+      ;;
+    esac
+else
+  enable_static=3Dyes
+fi
+
+
+
+
+
+
+
+
+
+
+# Check whether --with-pic was given.
+if test "${with_pic+set}" =3D set; then :
+  withval=3D$with_pic; pic_mode=3D"$withval"
+else
+  pic_mode=3Ddefault
+fi
+
+
+test -z "$pic_mode" && pic_mode=3Ddefault
+
+
+
+
+
+
+
+  # Check whether --enable-fast-install was given.
+if test "${enable_fast_install+set}" =3D set; then :
+  enableval=3D$enable_fast_install; p=3D${PACKAGE-default}
+    case $enableval in
+    yes) enable_fast_install=3Dyes ;;
+    no) enable_fast_install=3Dno ;;
+    *)
+      enable_fast_install=3Dno
+      # Look at the argument we got.  We use all the common list separator=
s.
+      lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
+      for pkg in $enableval; do
+	IFS=3D"$lt_save_ifs"
+	if test "X$pkg" =3D "X$p"; then
+	  enable_fast_install=3Dyes
+	fi
+      done
+      IFS=3D"$lt_save_ifs"
+      ;;
+    esac
+else
+  enable_fast_install=3Dyes
+fi
+
+
+
+
+
+
+
+
+
+
+
+# This can be used to rebuild libtool when needed
+LIBTOOL_DEPS=3D"$ltmain"
+
+# Always use our own libtool.
+LIBTOOL=3D'$(SHELL) $(top_builddir)/libtool'
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+test -z "$LN_S" && LN_S=3D"ln -s"
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+if test -n "${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5
+$as_echo_n "checking for objdir... " >&6; }
+if test "${lt_cv_objdir+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   rm -f .libs 2>/dev/null
 mkdir .libs 2>/dev/null
@@ -7454,14 +7975,21 @@
 fi
 rmdir .libs 2>/dev/null
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_objdir" >&5
-echo "${ECHO_T}$lt_cv_objdir" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5
+$as_echo "$lt_cv_objdir" >&6; }
 objdir=3D$lt_cv_objdir
=20
=20
=20
=20
=20
+cat >>confdefs.h <<_ACEOF
+#define LT_OBJDIR "$lt_cv_objdir/"
+_ACEOF
+
+
+
+
 case $host_os in
 aix3*)
   # AIX sometimes has problems with the GCC collect2 program.  For some
@@ -7474,362 +8002,26 @@
   ;;
 esac
=20
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed=3D'sed -e 1s/^X//'
-sed_quote_subst=3D's/\([\\"\\`$\\\\]\)/\\\1/g'
-
-# Same as above, but do not quote variable references.
-double_quote_subst=3D's/\([\\"\\`\\\\]\)/\\\1/g'
-
-# Sed substitution to delay expansion of an escaped shell variable in a
-# double_quote_subst'ed string.
-delay_variable_subst=3D's/\\\\\\\\\\\$/\\\\\\$/g'
-
-# Sed substitution to avoid accidental globbing in evaled expressions
-no_glob_subst=3D's/\*/\\\*/g'
-
-# Constants:
-rm=3D"rm -f"
-
 # Global variables:
-default_ofile=3Dlibtool
+ofile=3Dlibtool
 can_build_shared=3Dyes
=20
 # All known linkers require a `.a' archive for static linking (except MSVC,
 # which needs '.lib').
 libext=3Da
-ltmain=3D"$ac_aux_dir/ltmain.sh"
-ofile=3D"$default_ofile"
+
 with_gnu_ld=3D"$lt_cv_prog_gnu_ld"
=20
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ar", so it can be a progra=
m name with args.
-set dummy ${ac_tool_prefix}ar; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_AR+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$AR"; then
-  ac_cv_prog_AR=3D"$AR" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_AR=3D"${ac_tool_prefix}ar"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-AR=3D$ac_cv_prog_AR
-if test -n "$AR"; then
-  { echo "$as_me:$LINENO: result: $AR" >&5
-echo "${ECHO_T}$AR" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_AR"; then
-  ac_ct_AR=3D$AR
-  # Extract the first word of "ar", so it can be a program name with args.
-set dummy ar; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_AR+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_AR"; then
-  ac_cv_prog_ac_ct_AR=3D"$ac_ct_AR" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_ac_ct_AR=3D"ar"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-ac_ct_AR=3D$ac_cv_prog_ac_ct_AR
-if test -n "$ac_ct_AR"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_AR" >&5
-echo "${ECHO_T}$ac_ct_AR" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-  if test "x$ac_ct_AR" =3D x; then
-    AR=3D"false"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=3Dyes ;;
-esac
-    AR=3D$ac_ct_AR
-  fi
-else
-  AR=3D"$ac_cv_prog_AR"
-fi
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a pr=
ogram name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_RANLIB+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$RANLIB"; then
-  ac_cv_prog_RANLIB=3D"$RANLIB" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_RANLIB=3D"${ac_tool_prefix}ranlib"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-RANLIB=3D$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  { echo "$as_me:$LINENO: result: $RANLIB" >&5
-echo "${ECHO_T}$RANLIB" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_RANLIB"; then
-  ac_ct_RANLIB=3D$RANLIB
-  # Extract the first word of "ranlib", so it can be a program name with a=
rgs.
-set dummy ranlib; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_RANLIB+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_RANLIB"; then
-  ac_cv_prog_ac_ct_RANLIB=3D"$ac_ct_RANLIB" # Let the user override the te=
st.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_ac_ct_RANLIB=3D"ranlib"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-ac_ct_RANLIB=3D$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
-echo "${ECHO_T}$ac_ct_RANLIB" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-  if test "x$ac_ct_RANLIB" =3D x; then
-    RANLIB=3D":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=3Dyes ;;
-esac
-    RANLIB=3D$ac_ct_RANLIB
-  fi
-else
-  RANLIB=3D"$ac_cv_prog_RANLIB"
-fi
-
-if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}strip", so it can be a pro=
gram name with args.
-set dummy ${ac_tool_prefix}strip; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_STRIP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$STRIP"; then
-  ac_cv_prog_STRIP=3D"$STRIP" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_STRIP=3D"${ac_tool_prefix}strip"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-STRIP=3D$ac_cv_prog_STRIP
-if test -n "$STRIP"; then
-  { echo "$as_me:$LINENO: result: $STRIP" >&5
-echo "${ECHO_T}$STRIP" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_STRIP"; then
-  ac_ct_STRIP=3D$STRIP
-  # Extract the first word of "strip", so it can be a program name with ar=
gs.
-set dummy strip; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_ac_ct_STRIP+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_STRIP"; then
-  ac_cv_prog_ac_ct_STRIP=3D"$ac_ct_STRIP" # Let the user override the test.
-else
-as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
-    ac_cv_prog_ac_ct_STRIP=3D"strip"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=3D$as_save_IFS
-
-fi
-fi
-ac_ct_STRIP=3D$ac_cv_prog_ac_ct_STRIP
-if test -n "$ac_ct_STRIP"; then
-  { echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
-echo "${ECHO_T}$ac_ct_STRIP" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-  if test "x$ac_ct_STRIP" =3D x; then
-    STRIP=3D":"
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect c=
ross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&5
-echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
-whose name does not start with the host triplet.  If you think this
-configuration is useful to you, please write to autoconf at gnu.org." >&2;}
-ac_tool_warned=3Dyes ;;
-esac
-    STRIP=3D$ac_ct_STRIP
-  fi
-else
-  STRIP=3D"$ac_cv_prog_STRIP"
-fi
-
-
 old_CC=3D"$CC"
 old_CFLAGS=3D"$CFLAGS"
=20
 # Set sane defaults for various variables
-test -z "$AR" && AR=3Dar
-test -z "$AR_FLAGS" && AR_FLAGS=3Dcru
-test -z "$AS" && AS=3Das
 test -z "$CC" && CC=3Dcc
 test -z "$LTCC" && LTCC=3D$CC
 test -z "$LTCFLAGS" && LTCFLAGS=3D$CFLAGS
-test -z "$DLLTOOL" && DLLTOOL=3Ddlltool
 test -z "$LD" && LD=3Dld
-test -z "$LN_S" && LN_S=3D"ln -s"
-test -z "$MAGIC_CMD" && MAGIC_CMD=3Dfile
-test -z "$NM" && NM=3Dnm
-test -z "$SED" && SED=3Dsed
-test -z "$OBJDUMP" && OBJDUMP=3Dobjdump
-test -z "$RANLIB" && RANLIB=3D:
-test -z "$STRIP" && STRIP=3D:
 test -z "$ac_objext" && ac_objext=3Do
=20
-# Determine commands to create old-style static archives.
-old_archive_cmds=3D'$AR $AR_FLAGS $oldlib$oldobjs$old_deplibs'
-old_postinstall_cmds=3D'chmod 644 $oldlib'
-old_postuninstall_cmds=3D
-
-if test -n "$RANLIB"; then
-  case $host_os in
-  openbsd*)
-    old_postinstall_cmds=3D"$old_postinstall_cmds~\$RANLIB -t \$oldlib"
-    ;;
-  *)
-    old_postinstall_cmds=3D"$old_postinstall_cmds~\$RANLIB \$oldlib"
-    ;;
-  esac
-  old_archive_cmds=3D"$old_archive_cmds~\$RANLIB \$oldlib"
-fi
-
 for cc_temp in $compiler""; do
   case $cc_temp in
     compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
@@ -7838,17 +8030,18 @@
     *) break;;
   esac
 done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
+cc_basename=3D`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"`
=20
=20
 # Only perform the check for file, if the check method requires it
+test -z "$MAGIC_CMD" && MAGIC_CMD=3Dfile
 case $deplibs_check_method in
 file_magic*)
   if test "$file_magic_cmd" =3D '$MAGIC_CMD'; then
-    { echo "$as_me:$LINENO: checking for ${ac_tool_prefix}file" >&5
-echo $ECHO_N "checking for ${ac_tool_prefix}file... $ECHO_C" >&6; }
-if test "${lt_cv_path_MAGIC_CMD+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix=
}file" >&5
+$as_echo_n "checking for ${ac_tool_prefix}file... " >&6; }
+if test "${lt_cv_path_MAGIC_CMD+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   case $MAGIC_CMD in
 [\\/*] |  ?:[\\/]*)
@@ -7872,7 +8065,7 @@
 	    $EGREP "$file_magic_regex" > /dev/null; then
 	    :
 	  else
-	    cat <<EOF 1>&2
+	    cat <<_LT_EOF 1>&2
=20
 *** Warning: the command libtool uses to detect shared libraries,
 *** $file_magic_cmd, produces output that libtool cannot recognize.
@@ -7883,7 +8076,7 @@
 *** may want to report the problem to your system manager and/or to
 *** bug-libtool at gnu.org
=20
-EOF
+_LT_EOF
 	  fi ;;
 	esac
       fi
@@ -7898,19 +8091,23 @@
=20
 MAGIC_CMD=3D"$lt_cv_path_MAGIC_CMD"
 if test -n "$MAGIC_CMD"; then
-  { echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
-echo "${ECHO_T}$MAGIC_CMD" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
+$as_echo "$MAGIC_CMD" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+
+
=20
 if test -z "$lt_cv_path_MAGIC_CMD"; then
   if test -n "$ac_tool_prefix"; then
-    { echo "$as_me:$LINENO: checking for file" >&5
-echo $ECHO_N "checking for file... $ECHO_C" >&6; }
-if test "${lt_cv_path_MAGIC_CMD+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5
+$as_echo_n "checking for file... " >&6; }
+if test "${lt_cv_path_MAGIC_CMD+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   case $MAGIC_CMD in
 [\\/*] |  ?:[\\/]*)
@@ -7934,7 +8131,7 @@
 	    $EGREP "$file_magic_regex" > /dev/null; then
 	    :
 	  else
-	    cat <<EOF 1>&2
+	    cat <<_LT_EOF 1>&2
=20
 *** Warning: the command libtool uses to detect shared libraries,
 *** $file_magic_cmd, produces output that libtool cannot recognize.
@@ -7945,7 +8142,7 @@
 *** may want to report the problem to your system manager and/or to
 *** bug-libtool at gnu.org
=20
-EOF
+_LT_EOF
 	  fi ;;
 	esac
       fi
@@ -7960,12 +8157,13 @@
=20
 MAGIC_CMD=3D"$lt_cv_path_MAGIC_CMD"
 if test -n "$MAGIC_CMD"; then
-  { echo "$as_me:$LINENO: result: $MAGIC_CMD" >&5
-echo "${ECHO_T}$MAGIC_CMD" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5
+$as_echo "$MAGIC_CMD" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
=20
   else
     MAGIC_CMD=3D:
@@ -7976,28 +8174,8 @@
   ;;
 esac
=20
-enable_dlopen=3Dno
-enable_win32_dll=3Dno
-
-# Check whether --enable-libtool-lock was given.
-if test "${enable_libtool_lock+set}" =3D set; then
-  enableval=3D$enable_libtool_lock;
-fi
-
-test "x$enable_libtool_lock" !=3D xno && enable_libtool_lock=3Dyes
-
-
-# Check whether --with-pic was given.
-if test "${with_pic+set}" =3D set; then
-  withval=3D$with_pic; pic_mode=3D"$withval"
-else
-  pic_mode=3Ddefault
-fi
-
-test -z "$pic_mode" && pic_mode=3Ddefault
-
 # Use C for the default configuration in the libtool script
-tagname=3D
+
 lt_save_CC=3D"$CC"
 ac_ext=3Dc
 ac_cpp=3D'$CPP $CPPFLAGS'
@@ -8014,10 +8192,15 @@
 objext=3D$objext
=20
 # Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"int some_variable =3D 0;\n"
+lt_simple_compile_test_code=3D"int some_variable =3D 0;"
=20
 # Code to be used in simple link tests
-lt_simple_link_test_code=3D'int main(){return(0);}\n'
+lt_simple_link_test_code=3D'int main(){return(0);}'
+
+
+
+
+
=20
=20
 # If no C compiler was specified, use CC.
@@ -8029,36 +8212,48 @@
 # Allow CC to be a program name with arguments.
 compiler=3D$CC
=20
+# Save the default compiler, since it gets overwritten when the other
+# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP.
+compiler_DEFAULT=3D$CC
=20
 # save warnings/boilerplate of simple test code
 ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
+echo "$lt_simple_compile_test_code" >conftest.$ac_ext
 eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
 _lt_compiler_boilerplate=3D`cat conftest.err`
-$rm conftest*
+$RM conftest*
=20
 ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
+echo "$lt_simple_link_test_code" >conftest.$ac_ext
 eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
 _lt_linker_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-
+$RM -r conftest*
+
+
+## CAVEAT EMPTOR:
+## There is no encapsulation within the following macros, do not change
+## the running order or otherwise move them around unless you know exactly
+## what you are doing...
+if test -n "$compiler"; then
=20
 lt_prog_compiler_no_builtin_flag=3D
=20
 if test "$GCC" =3D yes; then
-  lt_prog_compiler_no_builtin_flag=3D' -fno-builtin'
-
-
-{ echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exce=
ptions" >&5
-echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... =
$ECHO_C" >&6; }
-if test "${lt_cv_prog_compiler_rtti_exceptions+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  case $cc_basename in
+  nvcc*)
+    lt_prog_compiler_no_builtin_flag=3D' -Xcompiler -fno-builtin' ;;
+  *)
+    lt_prog_compiler_no_builtin_flag=3D' -fno-builtin' ;;
+  esac
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports =
-fno-rtti -fno-exceptions" >&5
+$as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " =
>&6; }
+if test "${lt_cv_prog_compiler_rtti_exceptions+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   lt_cv_prog_compiler_rtti_exceptions=3Dno
-  ac_outfile=3Dconftest.$ac_objext
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+   ac_outfile=3Dconftest.$ac_objext
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
    lt_compiler_flag=3D"-fno-rtti -fno-exceptions"
    # Insert the option either (1) after the last *FLAGS variable, or
    # (2) before a word containing "conftest.", or (3) at the end.
@@ -8069,25 +8264,25 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:8072: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=3D$?
    cat conftest.err >&5
-   echo "$as_me:8076: \$? =3D $ac_status" >&5
+   echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
      $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
      if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/nul=
l; then
        lt_cv_prog_compiler_rtti_exceptions=3Dyes
      fi
    fi
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6; }
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti=
_exceptions" >&5
+$as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; }
=20
 if test x"$lt_cv_prog_compiler_rtti_exceptions" =3D xyes; then
     lt_prog_compiler_no_builtin_flag=3D"$lt_prog_compiler_no_builtin_flag =
-fno-rtti -fno-exceptions"
@@ -8097,12 +8292,15 @@
=20
 fi
=20
-lt_prog_compiler_wl=3D
+
+
+
+
+
+  lt_prog_compiler_wl=3D
 lt_prog_compiler_pic=3D
 lt_prog_compiler_static=3D
=20
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6=
; }
=20
   if test "$GCC" =3D yes; then
     lt_prog_compiler_wl=3D'-Wl,'
@@ -8118,19 +8316,29 @@
       ;;
=20
     amigaos*)
-      # FIXME: we need at least 68020 code to build shared libraries, but
-      # adding the `-m68020' flag to GCC prevents building anything better,
-      # like `-m68040'.
-      lt_prog_compiler_pic=3D'-m68020 -resident32 -malways-restore-a4'
-      ;;
-
-    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            lt_prog_compiler_pic=3D'-fPIC'
+        ;;
+      m68k)
+            # FIXME: we need at least 68020 code to build shared libraries=
, but
+            # adding the `-m68020' flag to GCC prevents building anything =
better,
+            # like `-m68040'.
+            lt_prog_compiler_pic=3D'-m68020 -resident32 -malways-restore-a=
4'
+        ;;
+      esac
+      ;;
+
+    beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
       # PIC is the default for these OSes.
       ;;
=20
-    mingw* | pw32* | os2*)
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
       # This hack is so that the source file can tell whether it is being
       # built for inclusion in a dll (and should export symbols for exampl=
e).
+      # Although the cygwin gcc ignores -fPIC, still need this for old-sty=
le
+      # (--disable-auto-import) libraries
       lt_prog_compiler_pic=3D'-DDLL_EXPORT'
       ;;
=20
@@ -8140,7 +8348,27 @@
       lt_prog_compiler_pic=3D'-fno-common'
       ;;
=20
-    interix3*)
+    haiku*)
+      # PIC is the default for Haiku.
+      # The "-static" flag exists, but is broken.
+      lt_prog_compiler_static=3D
+      ;;
+
+    hpux*)
+      # PIC is the default for 64-bit PA HP-UX, but not for 32-bit
+      # PA HP-UX.  On IA64 HP-UX, PIC is the default but the pic flag
+      # sets the default TLS model and affects inlining.
+      case $host_cpu in
+      hppa*64*)
+	# +Z the default
+	;;
+      *)
+	lt_prog_compiler_pic=3D'-fPIC'
+	;;
+      esac
+      ;;
+
+    interix[3-9]*)
       # Interix 3.x gcc -fpic/-fPIC options generate broken code.
       # Instead, we relocate shared libraries at runtime.
       ;;
@@ -8152,29 +8380,29 @@
       enable_shared=3Dno
       ;;
=20
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      lt_prog_compiler_pic=3D'-fPIC -shared'
+      ;;
+
     sysv4*MP*)
       if test -d /usr/nec; then
 	lt_prog_compiler_pic=3D-Kconform_pic
       fi
       ;;
=20
-    hpux*)
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic=3D'-fPIC'
-	;;
-      esac
-      ;;
-
     *)
       lt_prog_compiler_pic=3D'-fPIC'
       ;;
     esac
+
+    case $cc_basename in
+    nvcc*) # Cuda Compiler Driver 2.2
+      lt_prog_compiler_wl=3D'-Xlinker '
+      lt_prog_compiler_pic=3D'-Xcompiler -fPIC'
+      ;;
+    esac
   else
     # PORTME Check for flag to pass linker flags through the system compil=
er.
     case $host_os in
@@ -8187,18 +8415,8 @@
 	lt_prog_compiler_static=3D'-bnso -bI:/lib/syscalls.exp'
       fi
       ;;
-      darwin*)
-        # PIC is the default on this platform
-        # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
-         xlc*)
-         lt_prog_compiler_pic=3D'-qnocommon'
-         lt_prog_compiler_wl=3D'-Wl,'
-         ;;
-       esac
-       ;;
-
-    mingw* | pw32* | os2*)
+
+    mingw* | cygwin* | pw32* | os2* | cegcc*)
       # This hack is so that the source file can tell whether it is being
       # built for inclusion in a dll (and should export symbols for exampl=
e).
       lt_prog_compiler_pic=3D'-DDLL_EXPORT'
@@ -8226,19 +8444,34 @@
       lt_prog_compiler_static=3D'-non_shared'
       ;;
=20
-    newsos6)
-      lt_prog_compiler_pic=3D'-KPIC'
-      lt_prog_compiler_static=3D'-Bstatic'
-      ;;
-
-    linux*)
+    linux* | k*bsd*-gnu | kopensolaris*-gnu)
       case $cc_basename in
-      icc* | ecc*)
+      # old Intel for x86_64 which still supported -KPIC.
+      ecc*)
 	lt_prog_compiler_wl=3D'-Wl,'
 	lt_prog_compiler_pic=3D'-KPIC'
 	lt_prog_compiler_static=3D'-static'
         ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
+      # icc used to be incompatible with GCC.
+      # ICC 10 doesn't accept -KPIC any more.
+      icc* | ifort*)
+	lt_prog_compiler_wl=3D'-Wl,'
+	lt_prog_compiler_pic=3D'-fPIC'
+	lt_prog_compiler_static=3D'-static'
+        ;;
+      # Lahey Fortran 8.1.
+      lf95*)
+	lt_prog_compiler_wl=3D'-Wl,'
+	lt_prog_compiler_pic=3D'--shared'
+	lt_prog_compiler_static=3D'--static'
+	;;
+      nagfor*)
+	# NAG Fortran compiler
+	lt_prog_compiler_wl=3D'-Wl,-Wl,,'
+	lt_prog_compiler_pic=3D'-PIC'
+	lt_prog_compiler_static=3D'-Bstatic'
+	;;
+      pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*)
         # Portland Group compilers (*not* the Pentium gcc compiler,
 	# which looks to be a dead project)
 	lt_prog_compiler_wl=3D'-Wl,'
@@ -8250,20 +8483,57 @@
         # All Alpha code is PIC.
         lt_prog_compiler_static=3D'-non_shared'
         ;;
+      xl* | bgxl* | bgf* | mpixl*)
+	# IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene
+	lt_prog_compiler_wl=3D'-Wl,'
+	lt_prog_compiler_pic=3D'-qpic'
+	lt_prog_compiler_static=3D'-qstaticlink'
+	;;
+      *)
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ F* | *Sun*Fortran*)
+	  # Sun Fortran 8.3 passes all unrecognized flags to the linker
+	  lt_prog_compiler_pic=3D'-KPIC'
+	  lt_prog_compiler_static=3D'-Bstatic'
+	  lt_prog_compiler_wl=3D''
+	  ;;
+	*Sun\ C*)
+	  # Sun C 5.9
+	  lt_prog_compiler_pic=3D'-KPIC'
+	  lt_prog_compiler_static=3D'-Bstatic'
+	  lt_prog_compiler_wl=3D'-Wl,'
+	  ;;
+	esac
+	;;
       esac
       ;;
=20
+    newsos6)
+      lt_prog_compiler_pic=3D'-KPIC'
+      lt_prog_compiler_static=3D'-Bstatic'
+      ;;
+
+    *nto* | *qnx*)
+      # QNX uses GNU C++, but need to define -shared option too, otherwise
+      # it will coredump.
+      lt_prog_compiler_pic=3D'-fPIC -shared'
+      ;;
+
     osf3* | osf4* | osf5*)
       lt_prog_compiler_wl=3D'-Wl,'
       # All OSF/1 code is PIC.
       lt_prog_compiler_static=3D'-non_shared'
       ;;
=20
+    rdos*)
+      lt_prog_compiler_static=3D'-non_shared'
+      ;;
+
     solaris*)
       lt_prog_compiler_pic=3D'-KPIC'
       lt_prog_compiler_static=3D'-Bstatic'
       case $cc_basename in
-      f77* | f90* | f95*)
+      f77* | f90* | f95* | sunf77* | sunf90* | sunf95*)
 	lt_prog_compiler_wl=3D'-Qoption ld ';;
       *)
 	lt_prog_compiler_wl=3D'-Wl,';;
@@ -8311,22 +8581,39 @@
     esac
   fi
=20
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic" >&6; }
+case $host_os in
+  # For platforms which do not support PIC, -DPIC is meaningless:
+  *djgpp*)
+    lt_prog_compiler_pic=3D
+    ;;
+  *)
+    lt_prog_compiler_pic=3D"$lt_prog_compiler_pic -DPIC"
+    ;;
+esac
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to =
produce PIC" >&5
+$as_echo_n "checking for $compiler option to produce PIC... " >&6; }
+if test "${lt_cv_prog_compiler_pic+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_pic=3D$lt_prog_compiler_pic
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic"=
 >&5
+$as_echo "$lt_cv_prog_compiler_pic" >&6; }
+lt_prog_compiler_pic=3D$lt_cv_prog_compiler_pic
=20
 #
 # Check to make sure the PIC flag actually works.
 #
 if test -n "$lt_prog_compiler_pic"; then
-
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_p=
ic works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic works..=
. $ECHO_C" >&6; }
-if test "${lt_prog_compiler_pic_works+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_pic_works=3Dno
-  ac_outfile=3Dconftest.$ac_objext
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag =
$lt_prog_compiler_pic works" >&5
+$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... =
" >&6; }
+if test "${lt_cv_prog_compiler_pic_works+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_pic_works=3Dno
+   ac_outfile=3Dconftest.$ac_objext
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
    lt_compiler_flag=3D"$lt_prog_compiler_pic -DPIC"
    # Insert the option either (1) after the last *FLAGS variable, or
    # (2) before a word containing "conftest.", or (3) at the end.
@@ -8337,27 +8624,27 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:8340: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>conftest.err)
    ac_status=3D$?
    cat conftest.err >&5
-   echo "$as_me:8344: \$? =3D $ac_status" >&5
+   echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
    if (exit $ac_status) && test -s "$ac_outfile"; then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp
      $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
      if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/nul=
l; then
-       lt_prog_compiler_pic_works=3Dyes
+       lt_cv_prog_compiler_pic_works=3Dyes
      fi
    fi
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works" >&6; }
-
-if test x"$lt_prog_compiler_pic_works" =3D xyes; then
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_=
works" >&5
+$as_echo "$lt_cv_prog_compiler_pic_works" >&6; }
+
+if test x"$lt_cv_prog_compiler_pic_works" =3D xyes; then
     case $lt_prog_compiler_pic in
      "" | " "*) ;;
      *) lt_prog_compiler_pic=3D" $lt_prog_compiler_pic" ;;
@@ -8368,69 +8655,75 @@
 fi
=20
 fi
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    lt_prog_compiler_pic=3D
-    ;;
-  *)
-    lt_prog_compiler_pic=3D"$lt_prog_compiler_pic -DPIC"
-    ;;
-esac
+
+
+
+
+
+
+
+
+
+
=20
 #
 # Check to make sure the static flag actually works.
 #
 wl=3D$lt_prog_compiler_wl eval lt_tmp_static_flag=3D\"$lt_prog_compiler_st=
atic\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_f=
lag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works.=
.. $ECHO_C" >&6; }
-if test "${lt_prog_compiler_static_works+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works=3Dno
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag=
 $lt_tmp_static_flag works" >&5
+$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works...=
 " >&6; }
+if test "${lt_cv_prog_compiler_static_works+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_static_works=3Dno
    save_LDFLAGS=3D"$LDFLAGS"
    LDFLAGS=3D"$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
    if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
      # The linker can only warn and ignore the option if not recognized
      # So say no if there are warnings
      if test -s conftest.err; then
        # Append any errors to the config.log.
        cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
        $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
        if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works=3Dyes
+         lt_cv_prog_compiler_static_works=3Dyes
        fi
      else
-       lt_prog_compiler_static_works=3Dyes
+       lt_cv_prog_compiler_static_works=3Dyes
      fi
    fi
-   $rm conftest*
+   $RM -r conftest*
    LDFLAGS=3D"$save_LDFLAGS"
=20
 fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works" >&6; }
-
-if test x"$lt_prog_compiler_static_works" =3D xyes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_stat=
ic_works" >&5
+$as_echo "$lt_cv_prog_compiler_static_works" >&6; }
+
+if test x"$lt_cv_prog_compiler_static_works" =3D xyes; then
     :
 else
     lt_prog_compiler_static=3D
 fi
=20
=20
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_obje=
xt" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECH=
O_C" >&6; }
-if test "${lt_cv_prog_compiler_c_o+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports =
-c -o file.$ac_objext" >&5
+$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6;=
 }
+if test "${lt_cv_prog_compiler_c_o+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   lt_cv_prog_compiler_c_o=3Dno
-   $rm -r conftest 2>/dev/null
+   $RM -r conftest 2>/dev/null
    mkdir conftest
    cd conftest
    mkdir out
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
=20
    lt_compiler_flag=3D"-o out/conftest2.$ac_objext"
    # Insert the option either (1) after the last *FLAGS variable, or
@@ -8441,83 +8734,148 @@
    -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
    -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
    -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:8444: $lt_compile\"" >&5)
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
    (eval "$lt_compile" 2>out/conftest.err)
    ac_status=3D$?
    cat out/conftest.err >&5
-   echo "$as_me:8448: \$? =3D $ac_status" >&5
+   echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
    if (exit $ac_status) && test -s out/conftest2.$ac_objext
    then
      # The compiler can only warn and ignore the option if not recognized
      # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.=
exp
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
      $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
      if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.e=
r2 >/dev/null; then
        lt_cv_prog_compiler_c_o=3Dyes
      fi
    fi
    chmod u+w . 2>&5
-   $rm conftest*
+   $RM conftest*
    # SGI C++ compiler will create directory out/ii_files/ for
    # template instantiation
-   test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
-   $rm out/* && rmdir out
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
    cd ..
-   rmdir conftest
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o" >&6; }
+   $RM -r conftest
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o"=
 >&5
+$as_echo "$lt_cv_prog_compiler_c_o" >&6; }
+
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports =
-c -o file.$ac_objext" >&5
+$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6;=
 }
+if test "${lt_cv_prog_compiler_c_o+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler_c_o=3Dno
+   $RM -r conftest 2>/dev/null
+   mkdir conftest
+   cd conftest
+   mkdir out
+   echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+   lt_compiler_flag=3D"-o out/conftest2.$ac_objext"
+   # Insert the option either (1) after the last *FLAGS variable, or
+   # (2) before a word containing "conftest.", or (3) at the end.
+   # Note that $ac_compile itself does not contain backslashes and begins
+   # with a dollar sign (not a hyphen), so the echo should work correctly.
+   lt_compile=3D`echo "$ac_compile" | $SED \
+   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
+   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
+   -e 's:$: $lt_compiler_flag:'`
+   (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5)
+   (eval "$lt_compile" 2>out/conftest.err)
+   ac_status=3D$?
+   cat out/conftest.err >&5
+   echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
+   if (exit $ac_status) && test -s out/conftest2.$ac_objext
+   then
+     # The compiler can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp
+     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
+     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.e=
r2 >/dev/null; then
+       lt_cv_prog_compiler_c_o=3Dyes
+     fi
+   fi
+   chmod u+w . 2>&5
+   $RM conftest*
+   # SGI C++ compiler will create directory out/ii_files/ for
+   # template instantiation
+   test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files
+   $RM out/* && rmdir out
+   cd ..
+   $RM -r conftest
+   $RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o"=
 >&5
+$as_echo "$lt_cv_prog_compiler_c_o" >&6; }
+
+
=20
=20
 hard_links=3D"nottested"
 if test "$lt_cv_prog_compiler_c_o" =3D no && test "$need_locks" !=3D no; t=
hen
   # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with ha=
rd links" >&5
+$as_echo_n "checking if we can lock with hard links... " >&6; }
   hard_links=3Dyes
-  $rm conftest*
+  $RM conftest*
   ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
   touch conftest.a
   ln conftest.a conftest.b 2>&5 || hard_links=3Dno
   ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5
+$as_echo "$hard_links" >&6; }
   if test "$hard_links" =3D no; then
-    { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so =
\`make -j' may be unsafe" >&5
-echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may=
 be unsafe" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not supp=
ort \`-c -o', so \`make -j' may be unsafe" >&5
+$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j'=
 may be unsafe" >&2;}
     need_locks=3Dwarn
   fi
 else
   need_locks=3Dno
 fi
=20
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) suppor=
ts shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared =
libraries... $ECHO_C" >&6; }
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler =
linker ($LD) supports shared libraries" >&5
+$as_echo_n "checking whether the $compiler linker ($LD) supports shared li=
braries... " >&6; }
=20
   runpath_var=3D
   allow_undefined_flag=3D
-  enable_shared_with_static_runtimes=3Dno
+  always_export_symbols=3Dno
   archive_cmds=3D
   archive_expsym_cmds=3D
-  old_archive_From_new_cmds=3D
-  old_archive_from_expsyms_cmds=3D
+  compiler_needs_object=3Dno
+  enable_shared_with_static_runtimes=3Dno
   export_dynamic_flag_spec=3D
-  whole_archive_flag_spec=3D
-  thread_safe_flag_spec=3D
+  export_symbols_cmds=3D'$NM $libobjs $convenience | $global_symbol_pipe |=
 $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  hardcode_automatic=3Dno
+  hardcode_direct=3Dno
+  hardcode_direct_absolute=3Dno
   hardcode_libdir_flag_spec=3D
   hardcode_libdir_flag_spec_ld=3D
   hardcode_libdir_separator=3D
-  hardcode_direct=3Dno
   hardcode_minus_L=3Dno
   hardcode_shlibpath_var=3Dunsupported
+  inherit_rpath=3Dno
   link_all_deplibs=3Dunknown
-  hardcode_automatic=3Dno
   module_cmds=3D
   module_expsym_cmds=3D
-  always_export_symbols=3Dno
-  export_symbols_cmds=3D'$NM $libobjs $convenience | $global_symbol_pipe |=
 $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
+  old_archive_from_new_cmds=3D
+  old_archive_from_expsyms_cmds=3D
+  thread_safe_flag_spec=3D
+  whole_archive_flag_spec=3D
   # include_expsyms should be a list of space-separated symbols to be *alw=
ays*
   # included in the symbol list
   include_expsyms=3D
@@ -8525,26 +8883,17 @@
   # it will be wrapped by ` (' and `)$', so one must not match beginning or
   # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `=
bc',
   # as well as any symbol that contains `d'.
-  exclude_expsyms=3D"_GLOBAL_OFFSET_TABLE_"
+  exclude_expsyms=3D'_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'
   # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
   # platforms (ab)use it in PIC code, but their linkers get confused if
   # the symbol is explicitly referenced.  Since portable code cannot
   # rely on this symbol name, it's probably fine to never include it in
   # preloaded symbol tables.
+  # Exclude shared library initialization/finalization symbols.
   extract_expsyms_cmds=3D
-  # Just being paranoid about ensuring that cc_basename is set.
-  for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
=20
   case $host_os in
-  cygwin* | mingw* | pw32*)
+  cygwin* | mingw* | pw32* | cegcc*)
     # FIXME: the MSVC++ port hasn't been tested in a loooong time
     # When not using gcc, we currently assume that we are using
     # Microsoft Visual C++.
@@ -8562,7 +8911,33 @@
   esac
=20
   ld_shlibs=3Dyes
+
+  # On some targets, GNU ld is compatible enough with the native linker
+  # that we're better off using the native interface for both.
+  lt_use_gnu_ld_interface=3Dno
   if test "$with_gnu_ld" =3D yes; then
+    case $host_os in
+      aix*)
+	# The AIX port of GNU ld has always aspired to compatibility
+	# with the native linker.  However, as the warning in the GNU ld
+	# block says, versions before 2.19.5* couldn't really create working
+	# shared libraries, regardless of the interface used.
+	case `$LD -v 2>&1` in
+	  *\ \(GNU\ Binutils\)\ 2.19.5*) ;;
+	  *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;;
+	  *\ \(GNU\ Binutils\)\ [3-9]*) ;;
+	  *)
+	    lt_use_gnu_ld_interface=3Dyes
+	    ;;
+	esac
+	;;
+      *)
+	lt_use_gnu_ld_interface=3Dyes
+	;;
+    esac
+  fi
+
+  if test "$lt_use_gnu_ld_interface" =3D yes; then
     # If archive_cmds runs LD, not CC, wlarc should be empty
     wlarc=3D'${wl}'
=20
@@ -8570,16 +8945,17 @@
     # are reset later if shared libraries are not supported. Putting them
     # here allows them to be overridden if necessary.
     runpath_var=3DLD_RUN_PATH
-    hardcode_libdir_flag_spec=3D'${wl}--rpath ${wl}$libdir'
+    hardcode_libdir_flag_spec=3D'${wl}-rpath ${wl}$libdir'
     export_dynamic_flag_spec=3D'${wl}--export-dynamic'
     # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	whole_archive_flag_spec=3D"$wlarc"'--whole-archive$convenience '"$wlarc"'=
--no-whole-archive'
-      else
-  	whole_archive_flag_spec=3D
+    if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then
+      whole_archive_flag_spec=3D"$wlarc"'--whole-archive$convenience '"$wl=
arc"'--no-whole-archive'
+    else
+      whole_archive_flag_spec=3D
     fi
     supports_anon_versioning=3Dno
-    case `$LD -v 2>/dev/null` in
+    case `$LD -v 2>&1` in
+      *GNU\ gold*) supports_anon_versioning=3Dyes ;;
       *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
       *\ 2.11.93.0.2\ *) supports_anon_versioning=3Dyes ;; # RH7.3 ...
       *\ 2.11.92.0.12\ *) supports_anon_versioning=3Dyes ;; # Mandrake 8.2=
 ...
@@ -8589,38 +8965,40 @@
=20
     # See if GNU ld supports shared libraries.
     case $host_os in
-    aix3* | aix4* | aix5*)
+    aix[3-9]*)
       # On AIX/PPC, the GNU linker is very broken
       if test "$host_cpu" !=3D ia64; then
 	ld_shlibs=3Dno
-	cat <<EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.9.1, is reported
+	cat <<_LT_EOF 1>&2
+
+*** Warning: the GNU linker, at least up to release 2.19, is reported
 *** to be unable to reliably create shared libraries on AIX.
 *** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to modify your PATH
-*** so that a non-GNU linker is found, and then restart.
-
-EOF
+*** really care for shared libraries, you may want to install binutils
+*** 2.20 or above, or modify your PATH so that a non-GNU linker is found.
+*** You will then need to restart the configuration process.
+
+_LT_EOF
       fi
       ;;
=20
     amigaos*)
-      archive_cmds=3D'$rm $output_objdir/a2ixlibrary.data~$echo "#define N=
AME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1=
" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $out=
put_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_o=
bjdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output=
_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec=3D'-L$libdir'
-      hardcode_minus_L=3Dyes
-
-      # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
-      # that the semantics of dynamic libraries on AmigaOS, at least up
-      # to version 4, is to share data among multiple programs linked
-      # with the same dynamic library.  Since this doesn't match the
-      # behavior of shared libraries on other platforms, we can't use
-      # them.
-      ld_shlibs=3Dno
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname -o $lib'
+            archive_expsym_cmds=3D''
+        ;;
+      m68k)
+            archive_cmds=3D'$RM $output_objdir/a2ixlibrary.data~$ECHO "#de=
fine NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRAR=
Y_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >=
> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $ou=
tput_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $=
output_objdir && a2ixlibrary -32)'
+            hardcode_libdir_flag_spec=3D'-L$libdir'
+            hardcode_minus_L=3Dyes
+        ;;
+      esac
       ;;
=20
     beos*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null;=
 then
 	allow_undefined_flag=3Dunsupported
 	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
 	# support --undefined.  This deserves some investigation.  FIXME
@@ -8630,16 +9008,18 @@
       fi
       ;;
=20
-    cygwin* | mingw* | pw32*)
-      # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
+    cygwin* | mingw* | pw32* | cegcc*)
+      # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless,
       # as there is no search path for DLLs.
       hardcode_libdir_flag_spec=3D'-L$libdir'
+      export_dynamic_flag_spec=3D'${wl}--export-all-symbols'
       allow_undefined_flag=3Dunsupported
       always_export_symbols=3Dno
       enable_shared_with_static_runtimes=3Dyes
-      export_symbols_cmds=3D'$NM $libobjs $convenience | $global_symbol_pi=
pe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[A=
ITW] /s/.* //'\'' | sort | uniq > $export_symbols'
-
-      if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
+      export_symbols_cmds=3D'$NM $libobjs $convenience | $global_symbol_pi=
pe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^=
 ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $ex=
port_symbols'
+      exclude_expsyms=3D'[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]=
+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'
+
+      if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then
         archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags -o $=
output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -=
Xlinker $lib'
 	# If the export-symbols file already is a .def file (1st line
 	# is EXPORTS), use it as is; otherwise, prepend...
@@ -8655,7 +9035,12 @@
       fi
       ;;
=20
-    interix3*)
+    haiku*)
+      archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-=
soname $wl$soname -o $lib'
+      link_all_deplibs=3Dyes
+      ;;
+
+    interix[3-9]*)
       hardcode_direct=3Dno
       hardcode_shlibpath_var=3Dno
       hardcode_libdir_flag_spec=3D'${wl}-rpath,$libdir'
@@ -8670,51 +9055,95 @@
       archive_expsym_cmds=3D'sed "s,^,_," $export_symbols >$output_objdir/=
$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl=
}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}-=
-image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
       ;;
=20
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	tmp_addflag=3D
+    gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu)
+      tmp_diet=3Dno
+      if test "$host_os" =3D linux-dietlibc; then
+	case $cc_basename in
+	  diet\ *) tmp_diet=3Dyes;;	# linux-dietlibc with static linking (!diet-d=
yn)
+	esac
+      fi
+      if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null=
 \
+	 && test "$tmp_diet" =3D no
+      then
+	tmp_addflag=3D' $pic_flag'
+	tmp_sharedflag=3D'-shared'
 	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec=3D'${wl}--whole-archive`for conv in $convenienc=
e\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$conv\=
"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+        pgcc*)				# Portland Group C compiler
+	  whole_archive_flag_spec=3D'${wl}--whole-archive`for conv in $convenienc=
e\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$conv\=
"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
 	  tmp_addflag=3D' $pic_flag'
 	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec=3D'${wl}--whole-archive`for conv in $convenienc=
e\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$conv\=
"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
+	pgf77* | pgf90* | pgf95* | pgfortran*)
+					# Portland Group f77 and f90 compilers
+	  whole_archive_flag_spec=3D'${wl}--whole-archive`for conv in $convenienc=
e\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$conv\=
"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
 	  tmp_addflag=3D' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
+	ecc*,ia64* | icc*,ia64*)	# Intel C compiler on ia64
 	  tmp_addflag=3D' -i_dynamic' ;;
 	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
 	  tmp_addflag=3D' -i_dynamic -nofor_main' ;;
 	ifc* | ifort*)			# Intel Fortran compiler
 	  tmp_addflag=3D' -nofor_main' ;;
+	lf95*)				# Lahey Fortran 8.1
+	  whole_archive_flag_spec=3D
+	  tmp_sharedflag=3D'--shared' ;;
+	xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf be=
low)
+	  tmp_sharedflag=3D'-qmkshrobj'
+	  tmp_addflag=3D ;;
+	nvcc*)	# Cuda Compiler Driver 2.2
+	  whole_archive_flag_spec=3D'${wl}--whole-archive`for conv in $convenienc=
e\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$conv\=
"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive'
+	  compiler_needs_object=3Dyes
+	  ;;
 	esac
-	archive_cmds=3D'$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_f=
lags ${wl}-soname $wl$soname -o $lib'
-
-	if test $supports_anon_versioning =3D yes; then
-	  archive_expsym_cmds=3D'$echo "{ global:" > $output_objdir/$libname.ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.=
ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-son=
ame $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $li=
b'
-	fi
-      else
-	ld_shlibs=3Dno
+	case `$CC -V 2>&1 | sed 5q` in
+	*Sun\ C*)			# Sun C 5.9
+	  whole_archive_flag_spec=3D'${wl}--whole-archive`new_convenience=3D; for=
 conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=3D\"$new=
_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-w=
hole-archive'
+	  compiler_needs_object=3Dyes
+	  tmp_sharedflag=3D'-G' ;;
+	*Sun\ F*)			# Sun Fortran 8.3
+	  tmp_sharedflag=3D'-G' ;;
+	esac
+	archive_cmds=3D'$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $=
compiler_flags ${wl}-soname $wl$soname -o $lib'
+
+        if test "x$supports_anon_versioning" =3D xyes; then
+          archive_expsym_cmds=3D'echo "{ global:" > $output_objdir/$libnam=
e.ver~
+	    cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libna=
me.ver~
+	    echo "local: *; };" >> $output_objdir/$libname.ver~
+	    $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_fla=
gs ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libnam=
e.ver -o $lib'
+        fi
+
+	case $cc_basename in
+	xlf* | bgf* | bgxlf* | mpixlf*)
+	  # IBM XL Fortran 10.1 on PPC cannot create shared libs itself
+	  whole_archive_flag_spec=3D'--whole-archive$convenience --no-whole-archi=
ve'
+	  hardcode_libdir_flag_spec=3D
+	  hardcode_libdir_flag_spec_ld=3D'-rpath $libdir'
+	  archive_cmds=3D'$LD -shared $libobjs $deplibs $linker_flags -soname $so=
name -o $lib'
+	  if test "x$supports_anon_versioning" =3D xyes; then
+	    archive_expsym_cmds=3D'echo "{ global:" > $output_objdir/$libname.ver~
+	      cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$lib=
name.ver~
+	      echo "local: *; };" >> $output_objdir/$libname.ver~
+	      $LD -shared $libobjs $deplibs $linker_flags -soname $soname -versio=
n-script $output_objdir/$libname.ver -o $lib'
+	  fi
+	  ;;
+	esac
+      else
+        ld_shlibs=3Dno
       fi
       ;;
=20
     netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
 	archive_cmds=3D'$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib'
 	wlarc=3D
       else
-	archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-sonam=
e $wl$soname -o $lib'
-	archive_expsym_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl=
}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+	archive_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $=
{wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_=
flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols =
-o $lib'
       fi
       ;;
=20
     solaris*)
-      if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
+      if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then
 	ld_shlibs=3Dno
-	cat <<EOF 1>&2
+	cat <<_LT_EOF 1>&2
=20
 *** Warning: The releases 2.8.* of the GNU linker cannot reliably
 *** create shared libraries on Solaris systems.  Therefore, libtool
@@ -8723,10 +9152,10 @@
 *** your PATH or compiler configuration so that the native linker is
 *** used, and then restart.
=20
-EOF
-      elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null=
; then
-	archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-sonam=
e $wl$soname -o $lib'
-	archive_expsym_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl=
}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+_LT_EOF
+      elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/nul=
l; then
+	archive_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $=
{wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_=
flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols =
-o $lib'
       else
 	ld_shlibs=3Dno
       fi
@@ -8748,10 +9177,14 @@
 _LT_EOF
 	;;
 	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec=3D'`test -z "$SCOABSPATH" && echo ${wl}-rpa=
th,$libdir`'
-	    archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    archive_expsym_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-file=
,$export_symbols -o $lib'
+	  # For security reasons, it is highly recommended that you always
+	  # use absolute paths for naming shared libraries, and exclude the
+	  # DT_RUNPATH tag from executables and libraries.  But doing so
+	  # requires that you compile everything twice, which is a pain.
+	  if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; th=
en
+	    hardcode_libdir_flag_spec=3D'${wl}-rpath ${wl}$libdir'
+	    archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname $wl$soname -o $lib'
+	    archive_expsym_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $li=
b'
 	  else
 	    ld_shlibs=3Dno
 	  fi
@@ -8767,9 +9200,9 @@
       ;;
=20
     *)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-sonam=
e $wl$soname -o $lib'
-	archive_expsym_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl=
}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib'
+      if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null;=
 then
+	archive_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $=
{wl}-soname $wl$soname -o $lib'
+	archive_expsym_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_=
flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols =
-o $lib'
       else
 	ld_shlibs=3Dno
       fi
@@ -8799,7 +9232,7 @@
       fi
       ;;
=20
-    aix4* | aix5*)
+    aix[4-9]*)
       if test "$host_cpu" =3D ia64; then
 	# On IA64, the linker does run time linking by default, so we don't
 	# have to do anything special.
@@ -8809,22 +9242,24 @@
       else
 	# If we're using GNU nm, then we don't want the "-C" option.
 	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
-	  export_symbols_cmds=3D'$NM -Bpg $libobjs $convenience | awk '\''{ if ((=
(\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (substr(\$3,1,=
1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+	# Also, AIX nm treats weak defined symbols like other global
+	# defined symbols, whereas GNU nm marks them as "W".
+	if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then
+	  export_symbols_cmds=3D'$NM -Bpg $libobjs $convenience | awk '\''{ if ((=
(\$ 2 =3D=3D "T") || (\$ 2 =3D=3D "D") || (\$ 2 =3D=3D "B") || (\$ 2 =3D=3D=
 "W")) && (substr(\$ 3,1,1) !=3D ".")) { print \$ 3 } }'\'' | sort -u > $ex=
port_symbols'
 	else
-	  export_symbols_cmds=3D'$NM -BCpg $libobjs $convenience | awk '\''{ if (=
((\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (substr(\$3,1=
,1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
+	  export_symbols_cmds=3D'$NM -BCpg $libobjs $convenience | awk '\''{ if (=
((\$ 2 =3D=3D "T") || (\$ 2 =3D=3D "D") || (\$ 2 =3D=3D "B")) && (substr(\$=
 3,1,1) !=3D ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols'
 	fi
 	aix_use_runtimelinking=3Dno
=20
 	# Test if we are trying to use run time linking or normal
 	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
 	# need to do runtime linking.
-	case $host_os in aix4.[23]|aix4.[23].*|aix5*)
+	case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*)
 	  for ld_flag in $LDFLAGS; do
-  	  if (test $ld_flag =3D "-brtl" || test $ld_flag =3D "-Wl,-brtl"); then
-  	    aix_use_runtimelinking=3Dyes
-  	    break
-  	  fi
+	  if (test $ld_flag =3D "-brtl" || test $ld_flag =3D "-Wl,-brtl"); then
+	    aix_use_runtimelinking=3Dyes
+	    break
+	  fi
 	  done
 	  ;;
 	esac
@@ -8841,28 +9276,30 @@
=20
       archive_cmds=3D''
       hardcode_direct=3Dyes
+      hardcode_direct_absolute=3Dyes
       hardcode_libdir_separator=3D':'
       link_all_deplibs=3Dyes
+      file_list_spec=3D'${wl}-f,'
=20
       if test "$GCC" =3D yes; then
 	case $host_os in aix4.[012]|aix4.[012].*)
 	# We only want to do this on AIX 4.2 and lower, the check
 	# below for broken collect2 doesn't work under 4.3+
 	  collect2name=3D`${CC} -print-prog-name=3Dcollect2`
-	  if test -f "$collect2name" && \
-  	   strings "$collect2name" | grep resolve_lib_name >/dev/null
+	  if test -f "$collect2name" &&
+	   strings "$collect2name" | $GREP resolve_lib_name >/dev/null
 	  then
-  	  # We have reworked collect2
-  	  hardcode_direct=3Dyes
+	  # We have reworked collect2
+	  :
 	  else
-  	  # We have old collect2
-  	  hardcode_direct=3Dunsupported
-  	  # It fails to find uninstalled libraries when the uninstalled
-  	  # path is not listed in the libpath.  Setting hardcode_minus_L
-  	  # to unsupported forces relinking
-  	  hardcode_minus_L=3Dyes
-  	  hardcode_libdir_flag_spec=3D'-L$libdir'
-  	  hardcode_libdir_separator=3D
+	  # We have old collect2
+	  hardcode_direct=3Dunsupported
+	  # It fails to find uninstalled libraries when the uninstalled
+	  # path is not listed in the libpath.  Setting hardcode_minus_L
+	  # to unsupported forces relinking
+	  hardcode_minus_L=3Dyes
+	  hardcode_libdir_flag_spec=3D'-L$libdir'
+	  hardcode_libdir_separator=3D
 	  fi
 	  ;;
 	esac
@@ -8873,8 +9310,8 @@
       else
 	# not using gcc
 	if test "$host_cpu" =3D ia64; then
-  	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-  	# chokes on -Wl,-G. The following line is correct:
+	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
+	# chokes on -Wl,-G. The following line is correct:
 	  shared_flag=3D'-G'
 	else
 	  if test "$aix_use_runtimelinking" =3D yes; then
@@ -8885,6 +9322,7 @@
 	fi
       fi
=20
+      export_dynamic_flag_spec=3D'${wl}-bexpall'
       # It seems that -bexpall does not export symbols beginning with
       # underscore (_), so it is better to generate a list of symbols to e=
xport.
       always_export_symbols=3Dyes
@@ -8892,123 +9330,116 @@
 	# Warning - without using the other runtime loading flags (-brtl),
 	# -berok will link without error, but may produce a broken library.
 	allow_undefined_flag=3D'-berok'
-       # Determine the default libpath from the value encoded in an empty =
executable.
-       cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-
-       hardcode_libdir_flag_spec=3D'${wl}-blibpath:$libdir:'"$aix_libpath"
-	archive_expsym_cmds=3D"\$CC"' -o $output_objdir/$soname $libobjs $deplibs=
 '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag=
}" !=3D "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}=
$exp_sym_flag:\$export_symbols $shared_flag"
-       else
+        # Determine the default libpath from the value encoded in an
+        # empty executable.
+        if test "${lt_cv_aix_libpath+set}" =3D set; then
+  aix_libpath=3D$lt_cv_aix_libpath
+else
+  if test "${lt_cv_aix_libpath_+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+
+  lt_aix_libpath_sed=3D'
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }'
+  lt_cv_aix_libpath_=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -=
e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_=3D`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED=
 -n -e "$lt_aix_libpath_sed"`
+  fi
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_=3D"/usr/lib:/lib"
+  fi
+
+fi
+
+  aix_libpath=3D$lt_cv_aix_libpath_
+fi
+
+        hardcode_libdir_flag_spec=3D'${wl}-blibpath:$libdir:'"$aix_libpath"
+        archive_expsym_cmds=3D'$CC -o $output_objdir/$soname $libobjs $dep=
libs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_=
flag}" !=3D "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :;=
 fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
+      else
 	if test "$host_cpu" =3D ia64; then
 	  hardcode_libdir_flag_spec=3D'${wl}-R $libdir:/usr/lib:/lib'
 	  allow_undefined_flag=3D"-z nodefs"
 	  archive_expsym_cmds=3D"\$CC $shared_flag"' -o $output_objdir/$soname $l=
ibobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undef=
ined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
 	else
-	 # Determine the default libpath from the value encoded in an empty execu=
table.
-	 cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
+	 # Determine the default libpath from the value encoded in an
+	 # empty executable.
+	 if test "${lt_cv_aix_libpath+set}" =3D set; then
+  aix_libpath=3D$lt_cv_aix_libpath
+else
+  if test "${lt_cv_aix_libpath_+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+
+  lt_aix_libpath_sed=3D'
+      /Import File Strings/,/^$/ {
+	  /^0/ {
+	      s/^0  *\([^ ]*\) *$/\1/
+	      p
+	  }
+      }'
+  lt_cv_aix_libpath_=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -=
e "$lt_aix_libpath_sed"`
+  # Check for a 64-bit object if we didn't find anything.
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_=3D`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED=
 -n -e "$lt_aix_libpath_sed"`
+  fi
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+  if test -z "$lt_cv_aix_libpath_"; then
+    lt_cv_aix_libpath_=3D"/usr/lib:/lib"
+  fi
+
+fi
+
+  aix_libpath=3D$lt_cv_aix_libpath_
+fi
=20
 	 hardcode_libdir_flag_spec=3D'${wl}-blibpath:$libdir:'"$aix_libpath"
 	  # Warning - without using the other run time loading flags,
 	  # -berok will link without error, but may produce a broken library.
 	  no_undefined_flag=3D' ${wl}-bernotok'
 	  allow_undefined_flag=3D' ${wl}-berok'
-	  # Exported symbols can be pulled into shared objects from archives
-	  whole_archive_flag_spec=3D'$convenience'
+	  if test "$with_gnu_ld" =3D yes; then
+	    # We only use this code for GNU lds that support --whole-archive.
+	    whole_archive_flag_spec=3D'${wl}--whole-archive$convenience ${wl}--no=
-whole-archive'
+	  else
+	    # Exported symbols can be pulled into shared objects from archives
+	    whole_archive_flag_spec=3D'$convenience'
+	  fi
 	  archive_cmds_need_lc=3Dyes
 	  # This is similar to how AIX traditionally builds its shared libraries.
 	  archive_expsym_cmds=3D"\$CC $shared_flag"' -o $output_objdir/$soname $l=
ibobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${al=
low_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output=
_objdir/$soname'
@@ -9017,86 +9448,117 @@
       ;;
=20
     amigaos*)
-      archive_cmds=3D'$rm $output_objdir/a2ixlibrary.data~$echo "#define N=
AME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_ID 1=
" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> $out=
put_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $output_o=
bjdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output=
_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec=3D'-L$libdir'
-      hardcode_minus_L=3Dyes
-      # see comment about different semantics on the GNU ld section
-      ld_shlibs=3Dno
+      case $host_cpu in
+      powerpc)
+            # see comment about AmigaOS4 .so support
+            archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname -o $lib'
+            archive_expsym_cmds=3D''
+        ;;
+      m68k)
+            archive_cmds=3D'$RM $output_objdir/a2ixlibrary.data~$ECHO "#de=
fine NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRAR=
Y_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >=
> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $ou=
tput_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $=
output_objdir && a2ixlibrary -32)'
+            hardcode_libdir_flag_spec=3D'-L$libdir'
+            hardcode_minus_L=3Dyes
+        ;;
+      esac
       ;;
=20
     bsdi[45]*)
       export_dynamic_flag_spec=3D-rdynamic
       ;;
=20
-    cygwin* | mingw* | pw32*)
+    cygwin* | mingw* | pw32* | cegcc*)
       # When not using gcc, we currently assume that we are using
       # Microsoft Visual C++.
       # hardcode_libdir_flag_spec is actually meaningless, as there is
       # no search path for DLLs.
-      hardcode_libdir_flag_spec=3D' '
-      allow_undefined_flag=3Dunsupported
-      # Tell ltmain to make .lib files, not .a files.
-      libext=3Dlib
-      # Tell ltmain to make .dll files, not .so files.
-      shrext_cmds=3D".dll"
-      # FIXME: Setting linknames here is a bad hack.
-      archive_cmds=3D'$CC -o $lib $libobjs $compiler_flags `echo "$deplibs=
" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=3D'
-      # The linker will automatically build a .lib file if we build a DLL.
-      old_archive_From_new_cmds=3D'true'
-      # FIXME: Should let the user specify the lib program.
-      old_archive_cmds=3D'lib /OUT:$oldlib$oldobjs$old_deplibs'
-      fix_srcfile_path=3D'`cygpath -w "$srcfile"`'
-      enable_shared_with_static_runtimes=3Dyes
+      case $cc_basename in
+      cl*)
+	# Native MSVC
+	hardcode_libdir_flag_spec=3D' '
+	allow_undefined_flag=3Dunsupported
+	always_export_symbols=3Dyes
+	file_list_spec=3D'@'
+	# Tell ltmain to make .lib files, not .a files.
+	libext=3Dlib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=3D".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	archive_cmds=3D'$CC -o $output_objdir/$soname $libobjs $compiler_flags $d=
eplibs -Wl,-dll~linknames=3D'
+	archive_expsym_cmds=3D'if test "x`$SED 1q $export_symbols`" =3D xEXPORTS;=
 then
+	    sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!=
p' < $export_symbols > $output_objdir/$soname.exp;
+	  else
+	    sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_sy=
mbols > $output_objdir/$soname.exp;
+	  fi~
+	  $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$=
tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libnam=
e.dll.lib"~
+	  linknames=3D'
+	# The linker will not automatically build a static lib if we build a DLL.
+	# _LT_TAGVAR(old_archive_from_new_cmds, )=3D'true'
+	enable_shared_with_static_runtimes=3Dyes
+	export_symbols_cmds=3D'$NM $libobjs $convenience | $global_symbol_pipe | =
$SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AI=
TW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols'
+	# Don't use ranlib
+	old_postinstall_cmds=3D'chmod 644 $oldlib'
+	postlink_cmds=3D'lt_outputfile=3D"@OUTPUT@"~
+	  lt_tool_outputfile=3D"@TOOL_OUTPUT@"~
+	  case $lt_outputfile in
+	    *.exe|*.EXE) ;;
+	    *)
+	      lt_outputfile=3D"$lt_outputfile.exe"
+	      lt_tool_outputfile=3D"$lt_tool_outputfile.exe"
+	      ;;
+	  esac~
+	  if test "$MANIFEST_TOOL" !=3D ":" && test -f "$lt_outputfile.manifest";=
 then
+	    $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresour=
ce:"$lt_tool_outputfile" || exit 1;
+	    $RM "$lt_outputfile.manifest";
+	  fi'
+	;;
+      *)
+	# Assume MSVC wrapper
+	hardcode_libdir_flag_spec=3D' '
+	allow_undefined_flag=3Dunsupported
+	# Tell ltmain to make .lib files, not .a files.
+	libext=3Dlib
+	# Tell ltmain to make .dll files, not .so files.
+	shrext_cmds=3D".dll"
+	# FIXME: Setting linknames here is a bad hack.
+	archive_cmds=3D'$CC -o $lib $libobjs $compiler_flags `func_echo_all "$dep=
libs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=3D'
+	# The linker will automatically build a .lib file if we build a DLL.
+	old_archive_from_new_cmds=3D'true'
+	# FIXME: Should let the user specify the lib program.
+	old_archive_cmds=3D'lib -OUT:$oldlib$oldobjs$old_deplibs'
+	enable_shared_with_static_runtimes=3Dyes
+	;;
+      esac
       ;;
=20
     darwin* | rhapsody*)
-      case $host_os in
-        rhapsody* | darwin1.[012])
-         allow_undefined_flag=3D'${wl}-undefined ${wl}suppress'
-         ;;
-       *) # Darwin 1.3 on
-         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
-           allow_undefined_flag=3D'${wl}-flat_namespace ${wl}-undefined ${=
wl}suppress'
-         else
-           case ${MACOSX_DEPLOYMENT_TARGET} in
-             10.[012])
-               allow_undefined_flag=3D'${wl}-flat_namespace ${wl}-undefine=
d ${wl}suppress'
-               ;;
-             10.*)
-               allow_undefined_flag=3D'${wl}-undefined ${wl}dynamic_lookup'
-               ;;
-           esac
-         fi
-         ;;
-      esac
-      archive_cmds_need_lc=3Dno
-      hardcode_direct=3Dno
-      hardcode_automatic=3Dyes
-      hardcode_shlibpath_var=3Dunsupported
-      whole_archive_flag_spec=3D''
-      link_all_deplibs=3Dyes
-    if test "$GCC" =3D yes ; then
-    	output_verbose_link_cmd=3D'echo'
-        archive_cmds=3D'$CC -dynamiclib $allow_undefined_flag -o $lib $lib=
objs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
-      module_cmds=3D'$CC $allow_undefined_flag -o $lib -bundle $libobjs $d=
eplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doe=
sn't exist in older darwin lds
-      archive_expsym_cmds=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(.=
.*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC =
-dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_flags=
 -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${libname=
}-symbols.expsym ${lib}'
-      module_expsym_cmds=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^\(..=
*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$CC $=
allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~nmed=
it -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    else
-      case $cc_basename in
-        xlc*)
-         output_verbose_link_cmd=3D'echo'
-         archive_cmds=3D'$CC -qmkshrobj $allow_undefined_flag -o $lib $lib=
objs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$soname`=
 $verstring'
-         module_cmds=3D'$CC $allow_undefined_flag -o $lib -bundle $libobjs=
 $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it=
 doesn't exist in older darwin lds
-         archive_expsym_cmds=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^=
\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$=
CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_fla=
gs ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_objd=
ir/${libname}-symbols.expsym ${lib}'
-          module_expsym_cmds=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^=
\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$=
CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~=
nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          ;;
-       *)
-         ld_shlibs=3Dno
-          ;;
-      esac
-    fi
+
+
+  archive_cmds_need_lc=3Dno
+  hardcode_direct=3Dno
+  hardcode_automatic=3Dyes
+  hardcode_shlibpath_var=3Dunsupported
+  if test "$lt_cv_ld_force_load" =3D "yes"; then
+    whole_archive_flag_spec=3D'`for conv in $convenience\"\"; do test  -n =
\"$conv\" && new_convenience=3D\"$new_convenience ${wl}-force_load,$conv\";=
 done; func_echo_all \"$new_convenience\"`'
+  else
+    whole_archive_flag_spec=3D''
+  fi
+  link_all_deplibs=3Dyes
+  allow_undefined_flag=3D"$_lt_dar_allow_undefined"
+  case $cc_basename in
+     ifort*) _lt_dar_can_shared=3Dyes ;;
+     *) _lt_dar_can_shared=3D$GCC ;;
+  esac
+  if test "$_lt_dar_can_shared" =3D "yes"; then
+    output_verbose_link_cmd=3Dfunc_echo_all
+    archive_cmds=3D"\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib=
objs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring =
$_lt_dar_single_mod${_lt_dsymutil}"
+    module_cmds=3D"\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs =
\$deplibs \$compiler_flags${_lt_dsymutil}"
+    archive_expsym_cmds=3D"sed 's,^,_,' < \$export_symbols > \$output_objd=
ir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$=
lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$v=
erstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}"
+    module_expsym_cmds=3D"sed -e 's,^,_,' < \$export_symbols > \$output_ob=
jdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundl=
e \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}"
+
+  else
+  ld_shlibs=3Dno
+  fi
+
       ;;
=20
     dgux*)
@@ -9129,8 +9591,8 @@
       ;;
=20
     # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | kfreebsd*-gnu | dragonfly*)
-      archive_cmds=3D'$CC -shared -o $lib $libobjs $deplibs $compiler_flag=
s'
+    freebsd* | dragonfly*)
+      archive_cmds=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $com=
piler_flags'
       hardcode_libdir_flag_spec=3D'-R$libdir'
       hardcode_direct=3Dyes
       hardcode_shlibpath_var=3Dno
@@ -9138,9 +9600,9 @@
=20
     hpux9*)
       if test "$GCC" =3D yes; then
-	archive_cmds=3D'$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl=
}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flag=
s~test $output_objdir/$soname =3D $lib || mv $output_objdir/$soname $lib'
-      else
-	archive_cmds=3D'$rm $output_objdir/$soname~$LD -b +b $install_libdir -o $=
output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$=
soname =3D $lib || mv $output_objdir/$soname $lib'
+	archive_cmds=3D'$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b =
${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_=
flags~test $output_objdir/$soname =3D $lib || mv $output_objdir/$soname $li=
b'
+      else
+	archive_cmds=3D'$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $=
output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$=
soname =3D $lib || mv $output_objdir/$soname $lib'
       fi
       hardcode_libdir_flag_spec=3D'${wl}+b ${wl}$libdir'
       hardcode_libdir_separator=3D:
@@ -9153,18 +9615,18 @@
       ;;
=20
     hpux10*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
-	archive_cmds=3D'$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$inst=
all_libdir -o $lib $libobjs $deplibs $compiler_flags'
+      if test "$GCC" =3D yes && test "$with_gnu_ld" =3D no; then
+	archive_cmds=3D'$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$=
install_libdir -o $lib $libobjs $deplibs $compiler_flags'
       else
 	archive_cmds=3D'$LD -b +h $soname +b $install_libdir -o $lib $libobjs $de=
plibs $linker_flags'
       fi
       if test "$with_gnu_ld" =3D no; then
 	hardcode_libdir_flag_spec=3D'${wl}+b ${wl}$libdir'
+	hardcode_libdir_flag_spec_ld=3D'+b $libdir'
 	hardcode_libdir_separator=3D:
-
 	hardcode_direct=3Dyes
+	hardcode_direct_absolute=3Dyes
 	export_dynamic_flag_spec=3D'${wl}-E'
-
 	# hardcode_minus_L: Not really in the search PATH,
 	# but as the default location of the library.
 	hardcode_minus_L=3Dyes
@@ -9172,16 +9634,16 @@
       ;;
=20
     hpux11*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
+      if test "$GCC" =3D yes && test "$with_gnu_ld" =3D no; then
 	case $host_cpu in
 	hppa*64*)
 	  archive_cmds=3D'$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $depl=
ibs $compiler_flags'
 	  ;;
 	ia64*)
-	  archive_cmds=3D'$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -=
o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds=3D'$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefa=
ultrpath -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
-	  archive_cmds=3D'$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$in=
stall_libdir -o $lib $libobjs $deplibs $compiler_flags'
+	  archive_cmds=3D'$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl=
}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
 	  ;;
 	esac
       else
@@ -9193,7 +9655,46 @@
 	  archive_cmds=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $li=
b $libobjs $deplibs $compiler_flags'
 	  ;;
 	*)
-	  archive_cmds=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdi=
r -o $lib $libobjs $deplibs $compiler_flags'
+
+	  # Older versions of the 11.00 compiler do not understand -b yet
+	  # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does)
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b=
" >&5
+$as_echo_n "checking if $CC understands -b... " >&6; }
+if test "${lt_cv_prog_compiler__b+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_prog_compiler__b=3Dno
+   save_LDFLAGS=3D"$LDFLAGS"
+   LDFLAGS=3D"$LDFLAGS -b"
+   echo "$lt_simple_link_test_code" > conftest.$ac_ext
+   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
+     # The linker can only warn and ignore the option if not recognized
+     # So say no if there are warnings
+     if test -s conftest.err; then
+       # Append any errors to the config.log.
+       cat conftest.err 1>&5
+       $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp
+       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
+       if diff conftest.exp conftest.er2 >/dev/null; then
+         lt_cv_prog_compiler__b=3Dyes
+       fi
+     else
+       lt_cv_prog_compiler__b=3Dyes
+     fi
+   fi
+   $RM -r conftest*
+   LDFLAGS=3D"$save_LDFLAGS"
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" =
>&5
+$as_echo "$lt_cv_prog_compiler__b" >&6; }
+
+if test x"$lt_cv_prog_compiler__b" =3D xyes; then
+    archive_cmds=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libd=
ir -o $lib $libobjs $deplibs $compiler_flags'
+else
+    archive_cmds=3D'$LD -b +h $soname +b $install_libdir -o $lib $libobjs =
$deplibs $linker_flags'
+fi
+
 	  ;;
 	esac
       fi
@@ -9203,12 +9704,12 @@
=20
 	case $host_cpu in
 	hppa*64*|ia64*)
-	  hardcode_libdir_flag_spec_ld=3D'+b $libdir'
 	  hardcode_direct=3Dno
 	  hardcode_shlibpath_var=3Dno
 	  ;;
 	*)
 	  hardcode_direct=3Dyes
+	  hardcode_direct_absolute=3Dyes
 	  export_dynamic_flag_spec=3D'${wl}-E'
=20
 	  # hardcode_minus_L: Not really in the search PATH,
@@ -9221,18 +9722,49 @@
=20
     irix5* | irix6* | nonstopux*)
       if test "$GCC" =3D yes; then
-	archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-sonam=
e ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstr=
ing` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	archive_cmds=3D'$LD -shared $libobjs $deplibs $linker_flags -soname $sona=
me `test -n "$verstring" && echo -set_version $verstring` -update_registry =
${output_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec_ld=3D'-rpath $libdir'
-      fi
+	archive_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $=
{wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_=
version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_lo=
cations -o $lib'
+	# Try to use the -exported_symbol ld option, if it does not
+	# work, assume that -exports_file does not work either and
+	# implicitly export all symbols.
+	# This should be the same for all languages, so no per-tag cache variable.
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os li=
nker accepts -exported_symbol" >&5
+$as_echo_n "checking whether the $host_os linker accepts -exported_symbol.=
.. " >&6; }
+if test "${lt_cv_irix_exported_symbol+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  save_LDFLAGS=3D"$LDFLAGS"
+	   LDFLAGS=3D"$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-updat=
e_registry ${wl}/dev/null"
+	   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+int foo (void) { return 0; }
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  lt_cv_irix_exported_symbol=3Dyes
+else
+  lt_cv_irix_exported_symbol=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+           LDFLAGS=3D"$save_LDFLAGS"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symb=
ol" >&5
+$as_echo "$lt_cv_irix_exported_symbol" >&6; }
+	if test "$lt_cv_irix_exported_symbol" =3D yes; then
+          archive_expsym_cmds=3D'$CC -shared $pic_flag $libobjs $deplibs $=
compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo=
_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${outp=
ut_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib'
+	fi
+      else
+	archive_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags -soname $so=
name `test -n "$verstring" && func_echo_all "-set_version $verstring"` -upd=
ate_registry ${output_objdir}/so_locations -o $lib'
+	archive_expsym_cmds=3D'$CC -shared $libobjs $deplibs $compiler_flags -son=
ame $soname `test -n "$verstring" && func_echo_all "-set_version $verstring=
"` -update_registry ${output_objdir}/so_locations -exports_file $export_sym=
bols -o $lib'
+      fi
+      archive_cmds_need_lc=3D'no'
       hardcode_libdir_flag_spec=3D'${wl}-rpath ${wl}$libdir'
       hardcode_libdir_separator=3D:
+      inherit_rpath=3Dyes
       link_all_deplibs=3Dyes
       ;;
=20
     netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+      if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
 	archive_cmds=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' =
 # a.out
       else
 	archive_cmds=3D'$LD -shared -o $lib $libobjs $deplibs $linker_flags'     =
 # ELF
@@ -9250,25 +9782,33 @@
       hardcode_shlibpath_var=3Dno
       ;;
=20
+    *nto* | *qnx*)
+      ;;
+
     openbsd*)
-      hardcode_direct=3Dyes
-      hardcode_shlibpath_var=3Dno
-      if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host=
_os-$host_cpu" =3D "openbsd2.8-powerpc"; then
-	archive_cmds=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler=
_flags'
-	archive_expsym_cmds=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $c=
ompiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	hardcode_libdir_flag_spec=3D'${wl}-rpath,$libdir'
-	export_dynamic_flag_spec=3D'${wl}-E'
-      else
-       case $host_os in
-	 openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
-	   archive_cmds=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linker_flag=
s'
-	   hardcode_libdir_flag_spec=3D'-R$libdir'
-	   ;;
-	 *)
-	   archive_cmds=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $compi=
ler_flags'
-	   hardcode_libdir_flag_spec=3D'${wl}-rpath,$libdir'
-	   ;;
-       esac
+      if test -f /usr/libexec/ld.so; then
+	hardcode_direct=3Dyes
+	hardcode_shlibpath_var=3Dno
+	hardcode_direct_absolute=3Dyes
+	if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
+	  archive_cmds=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $compil=
er_flags'
+	  archive_expsym_cmds=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs =
$compiler_flags ${wl}-retain-symbols-file,$export_symbols'
+	  hardcode_libdir_flag_spec=3D'${wl}-rpath,$libdir'
+	  export_dynamic_flag_spec=3D'${wl}-E'
+	else
+	  case $host_os in
+	   openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
+	     archive_cmds=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linker_fl=
ags'
+	     hardcode_libdir_flag_spec=3D'-R$libdir'
+	     ;;
+	   *)
+	     archive_cmds=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $com=
piler_flags'
+	     hardcode_libdir_flag_spec=3D'${wl}-rpath,$libdir'
+	     ;;
+	  esac
+	fi
+      else
+	ld_shlibs=3Dno
       fi
       ;;
=20
@@ -9276,18 +9816,19 @@
       hardcode_libdir_flag_spec=3D'-L$libdir'
       hardcode_minus_L=3Dyes
       allow_undefined_flag=3Dunsupported
-      archive_cmds=3D'$echo "LIBRARY $libname INITINSTANCE" > $output_objd=
ir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$libname=
.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED" >>=
 $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.def~e=
mxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $l=
ibobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      old_archive_From_new_cmds=3D'emximp -o $output_objdir/$libname.a $ou=
tput_objdir/$libname.def'
+      archive_cmds=3D'$ECHO "LIBRARY $libname INITINSTANCE" > $output_objd=
ir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname=
.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $=
output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxe=
xp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libo=
bjs $deplibs $compiler_flags $output_objdir/$libname.def'
+      old_archive_from_new_cmds=3D'emximp -o $output_objdir/$libname.a $ou=
tput_objdir/$libname.def'
       ;;
=20
     osf3*)
       if test "$GCC" =3D yes; then
 	allow_undefined_flag=3D' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs $com=
piler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-s=
et_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_=
locations -o $lib'
+	archive_cmds=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs $com=
piler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_al=
l "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_=
objdir}/so_locations -o $lib'
       else
 	allow_undefined_flag=3D' -expect_unresolved \*'
-	archive_cmds=3D'$LD -shared${allow_undefined_flag} $libobjs $deplibs $lin=
ker_flags -soname $soname `test -n "$verstring" && echo -set_version $verst=
ring` -update_registry ${output_objdir}/so_locations -o $lib'
-      fi
+	archive_cmds=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs $com=
piler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_ve=
rsion $verstring"` -update_registry ${output_objdir}/so_locations -o $lib'
+      fi
+      archive_cmds_need_lc=3D'no'
       hardcode_libdir_flag_spec=3D'${wl}-rpath ${wl}$libdir'
       hardcode_libdir_separator=3D:
       ;;
@@ -9295,49 +9836,59 @@
     osf4* | osf5*)	# as osf3* with the addition of -msym flag
       if test "$GCC" =3D yes; then
 	allow_undefined_flag=3D' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs $com=
piler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && e=
cho ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_=
objdir}/so_locations -o $lib'
+	archive_cmds=3D'$CC -shared${allow_undefined_flag} $pic_flag $libobjs $de=
plibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verst=
ring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_re=
gistry ${wl}${output_objdir}/so_locations -o $lib'
 	hardcode_libdir_flag_spec=3D'${wl}-rpath ${wl}$libdir'
       else
 	allow_undefined_flag=3D' -expect_unresolved \*'
-	archive_cmds=3D'$LD -shared${allow_undefined_flag} $libobjs $deplibs $lin=
ker_flags -msym -soname $soname `test -n "$verstring" && echo -set_version =
$verstring` -update_registry ${output_objdir}/so_locations -o $lib'
-	archive_expsym_cmds=3D'for i in `cat $export_symbols`; do printf "%s %s\\=
n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs=
 $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verst=
ring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
+	archive_cmds=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs $com=
piler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-=
set_version $verstring"` -update_registry ${output_objdir}/so_locations -o =
$lib'
+	archive_expsym_cmds=3D'for i in `cat $export_symbols`; do printf "%s %s\\=
n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $li=
b.exp~
+	$CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_fl=
ags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_=
version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib=
~$RM $lib.exp'
=20
 	# Both c and cxx compiler support -rpath directly
 	hardcode_libdir_flag_spec=3D'-rpath $libdir'
       fi
+      archive_cmds_need_lc=3D'no'
       hardcode_libdir_separator=3D:
       ;;
=20
     solaris*)
-      no_undefined_flag=3D' -z text'
+      no_undefined_flag=3D' -z defs'
       if test "$GCC" =3D yes; then
 	wlarc=3D'${wl}'
-	archive_cmds=3D'$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $deplib=
s $compiler_flags'
-	archive_expsym_cmds=3D'$echo "{ global:" > $lib.exp~cat $export_symbols |=
 $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs=
 $deplibs $compiler_flags~$rm $lib.exp'
-      else
-	wlarc=3D''
-	archive_cmds=3D'$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs=
 $deplibs $linker_flags'
-	archive_expsym_cmds=3D'$echo "{ global:" > $lib.exp~cat $export_symbols |=
 $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-  	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $=
deplibs $linker_flags~$rm $lib.exp'
+	archive_cmds=3D'$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$son=
ame -o $lib $libobjs $deplibs $compiler_flags'
+	archive_expsym_cmds=3D'echo "{ global:" > $lib.exp~cat $export_symbols | =
$SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h $=
{wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp'
+      else
+	case `$CC -V 2>&1` in
+	*"Compilers 5.0"*)
+	  wlarc=3D''
+	  archive_cmds=3D'$LD -G${allow_undefined_flag} -h $soname -o $lib $libob=
js $deplibs $linker_flags'
+	  archive_expsym_cmds=3D'echo "{ global:" > $lib.exp~cat $export_symbols =
| $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $=
deplibs $linker_flags~$RM $lib.exp'
+	  ;;
+	*)
+	  wlarc=3D'${wl}'
+	  archive_cmds=3D'$CC -G${allow_undefined_flag} -h $soname -o $lib $libob=
js $deplibs $compiler_flags'
+	  archive_expsym_cmds=3D'echo "{ global:" > $lib.exp~cat $export_symbols =
| $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~
+	  $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $=
deplibs $compiler_flags~$RM $lib.exp'
+	  ;;
+	esac
       fi
       hardcode_libdir_flag_spec=3D'-R$libdir'
       hardcode_shlibpath_var=3Dno
       case $host_os in
       solaris2.[0-5] | solaris2.[0-5].*) ;;
       *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  whole_archive_flag_spec=3D'-z allextract$convenience -z defaultextract=
' ;;
- 	*)
- 	  whole_archive_flag_spec=3D'${wl}-z ${wl}allextract`for conv in $conven=
ience\"\"; do test -n \"$conv\" && new_convenience=3D\"$new_convenience,$co=
nv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
- 	esac ;;
+	# The compiler driver will combine and reorder linker options,
+	# but understands `-z linker_flag'.  GCC discards it without `$wl',
+	# but is careful enough not to reorder.
+	# Supported since Solaris 2.6 (maybe 2.5.1?)
+	if test "$GCC" =3D yes; then
+	  whole_archive_flag_spec=3D'${wl}-z ${wl}allextract$convenience ${wl}-z =
${wl}defaultextract'
+	else
+	  whole_archive_flag_spec=3D'-z allextract$convenience -z defaultextract'
+	fi
+	;;
       esac
       link_all_deplibs=3Dyes
       ;;
@@ -9394,7 +9945,7 @@
       fi
       ;;
=20
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
+    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* |=
 sco3.2v5.0.[024]*)
       no_undefined_flag=3D'${wl}-z,text'
       archive_cmds_need_lc=3Dno
       hardcode_shlibpath_var=3Dno
@@ -9420,18 +9971,18 @@
       allow_undefined_flag=3D'${wl}-z,nodefs'
       archive_cmds_need_lc=3Dno
       hardcode_shlibpath_var=3Dno
-      hardcode_libdir_flag_spec=3D'`test -z "$SCOABSPATH" && echo ${wl}-R,=
$libdir`'
+      hardcode_libdir_flag_spec=3D'${wl}-R,$libdir'
       hardcode_libdir_separator=3D':'
       link_all_deplibs=3Dyes
       export_dynamic_flag_spec=3D'${wl}-Bexport'
       runpath_var=3D'LD_RUN_PATH'
=20
       if test "$GCC" =3D yes; then
-	archive_cmds=3D'$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$so=
name -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,=
\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compil=
er_flags'
-      else
-	archive_cmds=3D'$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$soname =
-o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\${SC=
OABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compiler_fl=
ags'
+	archive_cmds=3D'$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $co=
mpiler_flags'
+	archive_expsym_cmds=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,=
$soname -o $lib $libobjs $deplibs $compiler_flags'
+      else
+	archive_cmds=3D'$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compile=
r_flags'
+	archive_expsym_cmds=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$sona=
me -o $lib $libobjs $deplibs $compiler_flags'
       fi
       ;;
=20
@@ -9445,12 +9996,36 @@
       ld_shlibs=3Dno
       ;;
     esac
-  fi
-
-{ echo "$as_me:$LINENO: result: $ld_shlibs" >&5
-echo "${ECHO_T}$ld_shlibs" >&6; }
+
+    if test x$host_vendor =3D xsni; then
+      case $host in
+      sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*)
+	export_dynamic_flag_spec=3D'${wl}-Blargedynsym'
+	;;
+      esac
+    fi
+  fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5
+$as_echo "$ld_shlibs" >&6; }
 test "$ld_shlibs" =3D no && can_build_shared=3Dno
=20
+with_gnu_ld=3D$with_gnu_ld
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 #
 # Do we need to explicitly link libc?
 #
@@ -9468,54 +10043,281 @@
       # Test whether the compiler implicitly links with -lc since on some
       # systems, -lgcc has to come before -lc. If gcc already passes -lc
       # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly li=
nked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO=
_C" >&6; }
-      $rm conftest*
-      printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-      if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should=
 be explicitly linked in" >&5
+$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; }
+if test "${lt_cv_archive_cmds_need_lc+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  $RM conftest*
+	echo "$lt_simple_compile_test_code" > conftest.$ac_ext
+
+	if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >=
&5
   (eval $ac_compile) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } 2>conftest.err; then
-        soname=3Dconftest
-        lib=3Dconftest
-        libobjs=3Dconftest.$ac_objext
-        deplibs=3D
-        wl=3D$lt_prog_compiler_wl
-	pic_flag=3D$lt_prog_compiler_pic
-        compiler_flags=3D-v
-        linker_flags=3D-v
-        verstring=3D
-        output_objdir=3D.
-        libname=3Dconftest
-        lt_save_allow_undefined_flag=3D$allow_undefined_flag
-        allow_undefined_flag=3D
-        if { (eval echo "$as_me:$LINENO: \"$archive_cmds 2\>\&1 \| grep \"=
 -lc \" \>/dev/null 2\>\&1\"") >&5
-  (eval $archive_cmds 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-        then
-	  archive_cmds_need_lc=3Dno
-        else
-	  archive_cmds_need_lc=3Dyes
-        fi
-        allow_undefined_flag=3D$lt_save_allow_undefined_flag
-      else
-        cat conftest.err 1>&5
-      fi
-      $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc" >&5
-echo "${ECHO_T}$archive_cmds_need_lc" >&6; }
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } 2>conftest.err; then
+	  soname=3Dconftest
+	  lib=3Dconftest
+	  libobjs=3Dconftest.$ac_objext
+	  deplibs=3D
+	  wl=3D$lt_prog_compiler_wl
+	  pic_flag=3D$lt_prog_compiler_pic
+	  compiler_flags=3D-v
+	  linker_flags=3D-v
+	  verstring=3D
+	  output_objdir=3D.
+	  libname=3Dconftest
+	  lt_save_allow_undefined_flag=3D$allow_undefined_flag
+	  allow_undefined_flag=3D
+	  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>=
\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5
+  (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }
+	  then
+	    lt_cv_archive_cmds_need_lc=3Dno
+	  else
+	    lt_cv_archive_cmds_need_lc=3Dyes
+	  fi
+	  allow_undefined_flag=3D$lt_save_allow_undefined_flag
+	else
+	  cat conftest.err 1>&5
+	fi
+	$RM conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_=
lc" >&5
+$as_echo "$lt_cv_archive_cmds_need_lc" >&6; }
+      archive_cmds_need_lc=3D$lt_cv_archive_cmds_need_lc
+      ;;
+    esac
+  fi
+  ;;
+esac
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker charact=
eristics" >&5
+$as_echo_n "checking dynamic linker characteristics... " >&6; }
+
+if test "$GCC" =3D yes; then
+  case $host_os in
+    darwin*) lt_awk_arg=3D"/^libraries:/,/LR/" ;;
+    *) lt_awk_arg=3D"/^libraries:/" ;;
+  esac
+  case $host_os in
+    mingw* | cegcc*) lt_sed_strip_eq=3D"s,=3D\([A-Za-z]:\),\1,g" ;;
+    *) lt_sed_strip_eq=3D"s,=3D/,/,g" ;;
+  esac
+  lt_search_path_spec=3D`$CC -print-search-dirs | awk $lt_awk_arg | $SED -=
e "s/^libraries://" -e $lt_sed_strip_eq`
+  case $lt_search_path_spec in
+  *\;*)
+    # if the path contains ";" then we assume it to be the separator
+    # otherwise default to the standard path separator (i.e. ":") - it is
+    # assumed that no part of a normal pathname contains ";" but that shou=
ld
+    # okay in the real world where ";" in dirpaths is itself problematic.
+    lt_search_path_spec=3D`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'`
+    ;;
+  *)
+    lt_search_path_spec=3D`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SE=
PARATOR/ /g"`
+    ;;
+  esac
+  # Ok, now we have the path, separated by spaces, we can step through it
+  # and add multilib dir if necessary.
+  lt_tmp_lt_search_path_spec=3D
+  lt_multi_os_dir=3D`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-direct=
ory 2>/dev/null`
+  for lt_sys_path in $lt_search_path_spec; do
+    if test -d "$lt_sys_path/$lt_multi_os_dir"; then
+      lt_tmp_lt_search_path_spec=3D"$lt_tmp_lt_search_path_spec $lt_sys_pa=
th/$lt_multi_os_dir"
+    else
+      test -d "$lt_sys_path" && \
+	lt_tmp_lt_search_path_spec=3D"$lt_tmp_lt_search_path_spec $lt_sys_path"
+    fi
+  done
+  lt_search_path_spec=3D`$ECHO "$lt_tmp_lt_search_path_spec" | awk '
+BEGIN {RS=3D" "; FS=3D"/|\n";} {
+  lt_foo=3D"";
+  lt_count=3D0;
+  for (lt_i =3D NF; lt_i > 0; lt_i--) {
+    if ($lt_i !=3D "" && $lt_i !=3D ".") {
+      if ($lt_i =3D=3D "..") {
+        lt_count++;
+      } else {
+        if (lt_count =3D=3D 0) {
+          lt_foo=3D"/" $lt_i lt_foo;
+        } else {
+          lt_count--;
+        }
+      }
+    }
+  }
+  if (lt_foo !=3D "") { lt_freq[lt_foo]++; }
+  if (lt_freq[lt_foo] =3D=3D 1) { print lt_foo; }
+}'`
+  # AWK program above erroneously prepends '/' to C:/dos/paths
+  # for these hosts.
+  case $host_os in
+    mingw* | cegcc*) lt_search_path_spec=3D`$ECHO "$lt_search_path_spec" |\
+      $SED 's,/\([A-Za-z]:\),\1,g'` ;;
+  esac
+  sys_lib_search_path_spec=3D`$ECHO "$lt_search_path_spec" | $lt_NL2SP`
+else
+  sys_lib_search_path_spec=3D"/lib /usr/lib /usr/local/lib"
+fi
 library_names_spec=3D
 libname_spec=3D'lib$name'
 soname_spec=3D
@@ -9529,20 +10331,6 @@
 version_type=3Dnone
 dynamic_linker=3D"$host_os ld.so"
 sys_lib_dlsearch_path_spec=3D"/lib /usr/lib"
-if test "$GCC" =3D yes; then
-  sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^libraries:" =
| $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-  if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that shou=
ld
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED -e=
 's/;/ /g'`
-  else
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED  -=
e "s/$PATH_SEPARATOR/ /g"`
-  fi
-else
-  sys_lib_search_path_spec=3D"/lib /usr/lib /usr/local/lib"
-fi
 need_lib_prefix=3Dunknown
 hardcode_into_libs=3Dno
=20
@@ -9560,7 +10348,7 @@
   soname_spec=3D'${libname}${release}${shared_ext}$major'
   ;;
=20
-aix4* | aix5*)
+aix[4-9]*)
   version_type=3Dlinux
   need_lib_prefix=3Dno
   need_version=3Dno
@@ -9579,7 +10367,7 @@
       aix4 | aix4.[01] | aix4.[01].*)
       if { echo '#if __GNUC__ > 2 || (__GNUC__ =3D=3D 2 && __GNUC_MINOR__ =
>=3D 97)'
 	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
+	   echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then
 	:
       else
 	can_build_shared=3Dno
@@ -9605,9 +10393,18 @@
   ;;
=20
 amigaos*)
-  library_names_spec=3D'$libname.ixlibrary $libname.a'
-  # Create ${libname}_ixlibrary.a entries in /sys/libs.
-  finish_eval=3D'for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libna=
me=3D`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; te=
st $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib =
${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a =
|| exit 1; done'
+  case $host_cpu in
+  powerpc)
+    # Since July 2007 AmigaOS4 officially supports .so libraries.
+    # When compiling the executable, add -use-dynld -Lsobjs: to the compil=
eline.
+    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
+    ;;
+  m68k)
+    library_names_spec=3D'$libname.ixlibrary $libname.a'
+    # Create ${libname}_ixlibrary.a entries in /sys/libs.
+    finish_eval=3D'for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do lib=
name=3D`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''=
`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S =
$lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibra=
ry.a || exit 1; done'
+    ;;
+  esac
   ;;
=20
 beos*)
@@ -9630,61 +10427,112 @@
   # libtool to hard-code these into programs
   ;;
=20
-cygwin* | mingw* | pw32*)
+cygwin* | mingw* | pw32* | cegcc*)
   version_type=3Dwindows
   shrext_cmds=3D".dll"
   need_version=3Dno
   need_lib_prefix=3Dno
=20
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32*)
+  case $GCC,$cc_basename in
+  yes,*)
+    # gcc
     library_names_spec=3D'$libname.dll.a'
     # DLL is installed to $(libdir)/../bin by postinstall_cmds
     postinstall_cmds=3D'base_file=3D`basename \${file}`~
-      dlpath=3D`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dl=
name'\''`~
+      dlpath=3D`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$d=
lname'\''`~
       dldir=3D$destdir/`dirname \$dlpath`~
       test -d \$dldir || mkdir -p \$dldir~
       $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
+      chmod a+x \$dldir/$dlname~
+      if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then
+        eval '\''$striplib \$dldir/$dlname'\'' || exit \$?;
+      fi'
     postuninstall_cmds=3D'dldll=3D`$SHELL 2>&1 -c '\''. $file; echo \$dlna=
me'\''`~
       dlpath=3D$dir/\$dldll~
-       $rm \$dlpath'
+       $RM \$dlpath'
     shlibpath_overrides_runpath=3Dyes
=20
     case $host_os in
     cygwin*)
       # Cygwin DLLs use 'cyg' prefix rather than 'lib'
       soname_spec=3D'`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${relea=
se} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D"/usr/lib /lib/w32api /lib /usr/local/lib"
-      ;;
-    mingw*)
+
+      sys_lib_search_path_spec=3D"$sys_lib_search_path_spec /usr/lib/w32ap=
i"
+      ;;
+    mingw* | cegcc*)
       # MinGW DLLs use traditional 'lib' prefix
       soname_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${ve=
rsuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^librarie=
s:" | $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-      if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null;=
 then
-        # It is most probably a Windows format PATH printed by
-        # mingw gcc, but we are running on Cygwin. Gcc prints its search
-        # path with ; separators, and with drive letters. We can handle the
-        # drive letters (cygwin fileutils understands them), so leave them,
-        # especially as we might pass files found there to a mingw objdump,
-        # which wouldn't understand a cygwinified path. Ahh.
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D  -e "s/$PATH_SEPARATOR/ /g"`
-      fi
       ;;
     pw32*)
       # pw32 DLLs use 'pw' prefix rather than 'lib'
       library_names_spec=3D'`echo ${libname} | sed -e 's/^lib/pw/'``echo $=
{release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
       ;;
     esac
+    dynamic_linker=3D'Win32 ld.exe'
+    ;;
+
+  *,cl*)
+    # Native MSVC
+    libname_spec=3D'$name'
+    soname_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${vers=
uffix}${shared_ext}'
+    library_names_spec=3D'${libname}.dll.lib'
+
+    case $build_os in
+    mingw*)
+      sys_lib_search_path_spec=3D
+      lt_save_ifs=3D$IFS
+      IFS=3D';'
+      for lt_path in $LIB
+      do
+        IFS=3D$lt_save_ifs
+        # Let DOS variable expansion print the short 8.3 style file name.
+        lt_path=3D`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") d=
o @echo %~si"`
+        sys_lib_search_path_spec=3D"$sys_lib_search_path_spec $lt_path"
+      done
+      IFS=3D$lt_save_ifs
+      # Convert to MSYS style.
+      sys_lib_search_path_spec=3D`$ECHO "$sys_lib_search_path_spec" | sed =
-e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'`
+      ;;
+    cygwin*)
+      # Convert to unix form, then to dos form, then back to unix form
+      # but this time dos style (no spaces!) so that the unix form looks
+      # like /cygdrive/c/PROGRA~1:/cygdr...
+      sys_lib_search_path_spec=3D`cygpath --path --unix "$LIB"`
+      sys_lib_search_path_spec=3D`cygpath --path --dos "$sys_lib_search_pa=
th_spec" 2>/dev/null`
+      sys_lib_search_path_spec=3D`cygpath --path --unix "$sys_lib_search_p=
ath_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"`
+      ;;
+    *)
+      sys_lib_search_path_spec=3D"$LIB"
+      if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/nul=
l; then
+        # It is most probably a Windows format PATH.
+        sys_lib_search_path_spec=3D`$ECHO "$sys_lib_search_path_spec" | $S=
ED -e 's/;/ /g'`
+      else
+        sys_lib_search_path_spec=3D`$ECHO "$sys_lib_search_path_spec" | $S=
ED -e "s/$PATH_SEPARATOR/ /g"`
+      fi
+      # FIXME: find the short name or the path components, as spaces are
+      # common. (e.g. "Program Files" -> "PROGRA~1")
+      ;;
+    esac
+
+    # DLL is installed to $(libdir)/../bin by postinstall_cmds
+    postinstall_cmds=3D'base_file=3D`basename \${file}`~
+      dlpath=3D`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$d=
lname'\''`~
+      dldir=3D$destdir/`dirname \$dlpath`~
+      test -d \$dldir || mkdir -p \$dldir~
+      $install_prog $dir/$dlname \$dldir/$dlname'
+    postuninstall_cmds=3D'dldll=3D`$SHELL 2>&1 -c '\''. $file; echo \$dlna=
me'\''`~
+      dlpath=3D$dir/\$dldll~
+       $RM \$dlpath'
+    shlibpath_overrides_runpath=3Dyes
+    dynamic_linker=3D'Win32 link.exe'
     ;;
=20
   *)
+    # Assume MSVC wrapper
     library_names_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'=
`${versuffix}${shared_ext} $libname.lib'
-    ;;
-  esac
-  dynamic_linker=3D'Win32 ld.exe'
+    dynamic_linker=3D'Win32 ld.exe'
+    ;;
+  esac
   # FIXME: first we should search . and the directory the executable is in
   shlibpath_var=3DPATH
   ;;
@@ -9694,17 +10542,13 @@
   version_type=3Ddarwin
   need_lib_prefix=3Dno
   need_version=3Dno
-  library_names_spec=3D'${libname}${release}${major}$shared_ext ${libname}=
$shared_ext ${libname}${release}${versuffix}$shared_ext'
+  library_names_spec=3D'${libname}${release}${major}$shared_ext ${libname}=
$shared_ext'
   soname_spec=3D'${libname}${release}${major}$shared_ext'
   shlibpath_overrides_runpath=3Dyes
   shlibpath_var=3DDYLD_LIBRARY_PATH
   shrext_cmds=3D'`test .$module =3D .yes && echo .so || echo .dylib`'
-  # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
-  if test "$GCC" =3D yes; then
-    sys_lib_search_path_spec=3D`$CC -print-search-dirs | tr "\n" "$PATH_SE=
PARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^librar=
ies:" | sed -e "s/^libraries://" -e "s,=3D/,/,g" -e "s,$PATH_SEPARATOR, ,g"=
 -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
-  else
-    sys_lib_search_path_spec=3D'/lib /usr/lib /usr/local/lib'
-  fi
+
+  sys_lib_search_path_spec=3D"$sys_lib_search_path_spec /usr/local/lib"
   sys_lib_dlsearch_path_spec=3D'/usr/local/lib /lib /usr/lib'
   ;;
=20
@@ -9721,18 +10565,6 @@
   dynamic_linker=3Dno
   ;;
=20
-kfreebsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
 freebsd* | dragonfly*)
   # DragonFly does not have aout.  When/if they implement a new
   # versioning mechanism, adjust this.
@@ -9770,7 +10602,7 @@
     shlibpath_overrides_runpath=3Dno
     hardcode_into_libs=3Dyes
     ;;
-  freebsd*) # from 4.6 on
+  *) # from 4.6 on, and DragonFly
     shlibpath_overrides_runpath=3Dyes
     hardcode_into_libs=3Dyes
     ;;
@@ -9787,6 +10619,19 @@
   hardcode_into_libs=3Dyes
   ;;
=20
+haiku*)
+  version_type=3Dlinux
+  need_lib_prefix=3Dno
+  need_version=3Dno
+  dynamic_linker=3D"$host_os runtime_loader"
+  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}${major} ${libname}${shared_ext}'
+  soname_spec=3D'${libname}${release}${shared_ext}$major'
+  shlibpath_var=3DLIBRARY_PATH
+  shlibpath_overrides_runpath=3Dyes
+  sys_lib_dlsearch_path_spec=3D'/boot/home/config/lib /boot/common/lib /bo=
ot/system/lib'
+  hardcode_into_libs=3Dyes
+  ;;
+
 hpux9* | hpux10* | hpux11*)
   # Give a soname corresponding to the major version so that dld.sl refuse=
s to
   # link against other versions.
@@ -9809,18 +10654,18 @@
     fi
     sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
     ;;
-   hppa*64*)
-     shrext_cmds=3D'.sl'
-     hardcode_into_libs=3Dyes
-     dynamic_linker=3D"$host_os dld.sl"
-     shlibpath_var=3DLD_LIBRARY_PATH # How should we handle SHLIB_PATH
-     shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-     library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${l=
ibname}${release}${shared_ext}$major $libname${shared_ext}'
-     soname_spec=3D'${libname}${release}${shared_ext}$major'
-     sys_lib_search_path_spec=3D"/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-     sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-     ;;
-   *)
+  hppa*64*)
+    shrext_cmds=3D'.sl'
+    hardcode_into_libs=3Dyes
+    dynamic_linker=3D"$host_os dld.sl"
+    shlibpath_var=3DLD_LIBRARY_PATH # How should we handle SHLIB_PATH
+    shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
+    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
+    soname_spec=3D'${libname}${release}${shared_ext}$major'
+    sys_lib_search_path_spec=3D"/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
+    sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
+    ;;
+  *)
     shrext_cmds=3D'.sl'
     dynamic_linker=3D"$host_os dld.sl"
     shlibpath_var=3DSHLIB_PATH
@@ -9829,11 +10674,13 @@
     soname_spec=3D'${libname}${release}${shared_ext}$major'
     ;;
   esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
+  # HP-UX runs *really* slowly unless shared libraries are mode 555, ...
   postinstall_cmds=3D'chmod 555 $lib'
-  ;;
-
-interix3*)
+  # or fails outright, so override atomically:
+  install_override_mode=3D555
+  ;;
+
+interix[3-9]*)
   version_type=3Dlinux
   need_lib_prefix=3Dno
   need_version=3Dno
@@ -9888,7 +10735,7 @@
   ;;
=20
 # This must be Linux ELF.
-linux*)
+linux* | k*bsd*-gnu | kopensolaris*-gnu)
   version_type=3Dlinux
   need_lib_prefix=3Dno
   need_version=3Dno
@@ -9897,6 +10744,41 @@
   finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -n $libdir'
   shlibpath_var=3DLD_LIBRARY_PATH
   shlibpath_overrides_runpath=3Dno
+
+  # Some binutils ld are patched to set DT_RUNPATH
+  if test "${lt_cv_shlibpath_overrides_runpath+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  lt_cv_shlibpath_overrides_runpath=3Dno
+    save_LDFLAGS=3D$LDFLAGS
+    save_libdir=3D$libdir
+    eval "libdir=3D/foo; wl=3D\"$lt_prog_compiler_wl\"; \
+	 LDFLAGS=3D\"\$LDFLAGS $hardcode_libdir_flag_spec\""
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  if  ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdi=
r" >/dev/null; then :
+  lt_cv_shlibpath_overrides_runpath=3Dyes
+fi
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+    LDFLAGS=3D$save_LDFLAGS
+    libdir=3D$save_libdir
+
+fi
+
+  shlibpath_overrides_runpath=3D$lt_cv_shlibpath_overrides_runpath
+
   # This implies no fast_install, which is unacceptable.
   # Some rework will be needed to allow for fast_install
   # before this can be enabled.
@@ -9904,7 +10786,7 @@
=20
   # Append ld.so.conf contents to the search path
   if test -f /etc/ld.so.conf; then
-    lt_ld_extra=3D`awk '/^include / { system(sprintf("cd /etc; cat %s", \$=
2)); skip =3D 1; } { if (!skip) print \$0; skip =3D 0; }' < /etc/ld.so.conf=
 | $SED -e 's/#.*//;s/[:,	]/ /g;s/=3D[^=3D]*$//;s/=3D[^=3D ]* / /g;/^$/d' |=
 tr '\n' ' '`
+    lt_ld_extra=3D`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/d=
ev/null", \$2)); skip =3D 1; } { if (!skip) print \$0; skip =3D 0; }' < /et=
c/ld.so.conf | $SED -e 's/#.*//;/^[	 ]*hwcap[	 ]/d;s/[:,	]/ /g;s/=3D[^=3D]*=
$//;s/=3D[^=3D ]* / /g;s/"//g;/^$/d' | tr '\n' ' '`
     sys_lib_dlsearch_path_spec=3D"/lib /usr/lib $lt_ld_extra"
   fi
=20
@@ -9917,23 +10799,11 @@
   dynamic_linker=3D'GNU/Linux ld.so'
   ;;
=20
-knetbsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
 netbsd*)
   version_type=3Dsunos
   need_lib_prefix=3Dno
   need_version=3Dno
-  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
+  if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then
     library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${shared_ext}$versuffix'
     finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
     dynamic_linker=3D'NetBSD (a.out) ld.so'
@@ -9954,14 +10824,16 @@
   shlibpath_overrides_runpath=3Dyes
   ;;
=20
-nto-qnx*)
-  version_type=3Dlinux
+*nto* | *qnx*)
+  version_type=3Dqnx
   need_lib_prefix=3Dno
   need_version=3Dno
   library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
   soname_spec=3D'${libname}${release}${shared_ext}$major'
   shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
+  shlibpath_overrides_runpath=3Dno
+  hardcode_into_libs=3Dyes
+  dynamic_linker=3D'ldqnx.so'
   ;;
=20
 openbsd*)
@@ -9970,13 +10842,13 @@
   need_lib_prefix=3Dno
   # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
   case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=3Dyes ;;
-    *)                         need_version=3Dno  ;;
+    openbsd3.3 | openbsd3.3.*)	need_version=3Dyes ;;
+    *)				need_version=3Dno  ;;
   esac
   library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
   finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
   shlibpath_var=3DLD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
+  if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os=
-$host_cpu" =3D "openbsd2.8-powerpc"; then
     case $host_os in
       openbsd2.[89] | openbsd2.[89].*)
 	shlibpath_overrides_runpath=3Dno
@@ -10010,6 +10882,10 @@
   sys_lib_dlsearch_path_spec=3D"$sys_lib_search_path_spec"
   ;;
=20
+rdos*)
+  dynamic_linker=3Dno
+  ;;
+
 solaris*)
   version_type=3Dlinux
   need_lib_prefix=3Dno
@@ -10044,7 +10920,6 @@
     sni)
       shlibpath_overrides_runpath=3Dno
       need_lib_prefix=3Dno
-      export_dynamic_flag_spec=3D'${wl}-Blargedynsym'
       runpath_var=3DLD_RUN_PATH
       ;;
     siemens)
@@ -10075,13 +10950,12 @@
   library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext} $libname${shared_ext}'
   soname_spec=3D'${libname}${release}${shared_ext}$major'
   shlibpath_var=3DLD_LIBRARY_PATH
+  shlibpath_overrides_runpath=3Dyes
   hardcode_into_libs=3Dyes
   if test "$with_gnu_ld" =3D yes; then
     sys_lib_search_path_spec=3D'/usr/local/lib /usr/gnu/lib /usr/ccs/lib /=
usr/lib /lib'
-    shlibpath_overrides_runpath=3Dno
   else
     sys_lib_search_path_spec=3D'/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=3Dyes
     case $host_os in
       sco3.2v5*)
         sys_lib_search_path_spec=3D"$sys_lib_search_path_spec /lib"
@@ -10091,6 +10965,17 @@
   sys_lib_dlsearch_path_spec=3D'/usr/lib'
   ;;
=20
+tpf*)
+  # TPF is a cross-target only.  Preferred cross-host =3D GNU/Linux.
+  version_type=3Dlinux
+  need_lib_prefix=3Dno
+  need_version=3Dno
+  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
+  shlibpath_var=3DLD_LIBRARY_PATH
+  shlibpath_overrides_runpath=3Dno
+  hardcode_into_libs=3Dyes
+  ;;
+
 uts4*)
   version_type=3Dlinux
   library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
@@ -10102,8 +10987,8 @@
   dynamic_linker=3Dno
   ;;
 esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5
+$as_echo "$dynamic_linker" >&6; }
 test "$dynamic_linker" =3D no && can_build_shared=3Dno
=20
 variables_saved_for_relink=3D"PATH $shlibpath_var $runpath_var"
@@ -10111,19 +10996,117 @@
   variables_saved_for_relink=3D"$variables_saved_for_relink GCC_EXEC_PREFI=
X COMPILER_PATH LIBRARY_PATH"
 fi
=20
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into progra=
ms" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECH=
O_C" >&6; }
+if test "${lt_cv_sys_lib_search_path_spec+set}" =3D set; then
+  sys_lib_search_path_spec=3D"$lt_cv_sys_lib_search_path_spec"
+fi
+if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" =3D set; then
+  sys_lib_dlsearch_path_spec=3D"$lt_cv_sys_lib_dlsearch_path_spec"
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode librar=
y paths into programs" >&5
+$as_echo_n "checking how to hardcode library paths into programs... " >&6;=
 }
 hardcode_action=3D
-if test -n "$hardcode_libdir_flag_spec" || \
-   test -n "$runpath_var" || \
+if test -n "$hardcode_libdir_flag_spec" ||
+   test -n "$runpath_var" ||
    test "X$hardcode_automatic" =3D "Xyes" ; then
=20
-  # We can hardcode non-existant directories.
+  # We can hardcode non-existent directories.
   if test "$hardcode_direct" !=3D no &&
      # If the only mechanism to avoid hardcoding is shlibpath_var, we
      # have to relink, otherwise we might link with an installed library
      # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, )" !=3D no &&
+     ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" !=3D no &&
      test "$hardcode_minus_L" !=3D no; then
     # Linking always hardcodes the temporary library directory.
     hardcode_action=3Drelink
@@ -10136,10 +11119,11 @@
   # directories.
   hardcode_action=3Dunsupported
 fi
-{ echo "$as_me:$LINENO: result: $hardcode_action" >&5
-echo "${ECHO_T}$hardcode_action" >&6; }
-
-if test "$hardcode_action" =3D relink; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5
+$as_echo "$hardcode_action" >&6; }
+
+if test "$hardcode_action" =3D relink ||
+   test "$inherit_rpath" =3D yes; then
   # Fast installation is not supported
   enable_fast_install=3Dno
 elif test "$shlibpath_overrides_runpath" =3D yes ||
@@ -10148,36 +11132,12 @@
   enable_fast_install=3Dneedless
 fi
=20
-striplib=3D
-old_striplib=3D
-{ echo "$as_me:$LINENO: checking whether stripping libraries is possible" =
>&5
-echo $ECHO_N "checking whether stripping libraries is possible... $ECHO_C"=
 >&6; }
-if test -n "$STRIP" && $STRIP -V 2>&1 | grep "GNU strip" >/dev/null; then
-  test -z "$old_striplib" && old_striplib=3D"$STRIP --strip-debug"
-  test -z "$striplib" && striplib=3D"$STRIP --strip-unneeded"
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-else
-# FIXME - insert some real tests, host_os isn't really good enough
-  case $host_os in
-   darwin*)
-       if test -n "$STRIP" ; then
-         striplib=3D"$STRIP -x"
-         { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-       else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-       ;;
-   *)
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-    ;;
-  esac
-fi
-
-if test "x$enable_dlopen" !=3D xyes; then
+
+
+
+
+
+  if test "x$enable_dlopen" !=3D xyes; then
   enable_dlopen=3Dunknown
   enable_dlopen_self=3Dunknown
   enable_dlopen_self_static=3Dunknown
@@ -10192,30 +11152,26 @@
     lt_cv_dlopen_self=3Dyes
     ;;
=20
-  mingw* | pw32*)
+  mingw* | pw32* | cegcc*)
     lt_cv_dlopen=3D"LoadLibrary"
     lt_cv_dlopen_libs=3D
-   ;;
+    ;;
=20
   cygwin*)
     lt_cv_dlopen=3D"dlopen"
     lt_cv_dlopen_libs=3D
-   ;;
+    ;;
=20
   darwin*)
   # if libdl is installed we need to link against it
-    { echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
-echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; }
-if test "${ac_cv_lib_dl_dlopen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" =
>&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if test "${ac_cv_lib_dl_dlopen+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
 LIBS=3D"-ldl  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -10233,39 +11189,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_lib_dl_dlopen=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_dl_dlopen=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_lib_dl_dlopen=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
-echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; }
-if test $ac_cv_lib_dl_dlopen =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
+$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
+if test "x$ac_cv_lib_dl_dlopen" =3D x""yes; then :
   lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-ldl"
 else
=20
@@ -10275,36 +11210,22 @@
=20
 fi
=20
-   ;;
+    ;;
=20
   *)
-    { echo "$as_me:$LINENO: checking for shl_load" >&5
-echo $ECHO_N "checking for shl_load... $ECHO_C" >&6; }
-if test "${ac_cv_func_shl_load+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define shl_load to an innocuous variant, in case <limits.h> declares sh=
l_load.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define shl_load innocuous_shl_load
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char shl_load (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef shl_load
+    ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load"
+if test "x$ac_cv_func_shl_load" =3D x""yes; then :
+  lt_cv_dlopen=3D"shl_load"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld"=
 >&5
+$as_echo_n "checking for shl_load in -ldld... " >&6; }
+if test "${ac_cv_lib_dld_shl_load+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=3D$LIBS
+LIBS=3D"-ldld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
@@ -10313,13 +11234,6 @@
 extern "C"
 #endif
 char shl_load ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_shl_load || defined __stub___shl_load
-choke me
-#endif
-
 int
 main ()
 {
@@ -10328,52 +11242,32 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_shl_load=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_shl_load=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_shl_load" >&5
-echo "${ECHO_T}$ac_cv_func_shl_load" >&6; }
-if test $ac_cv_func_shl_load =3D yes; then
-  lt_cv_dlopen=3D"shl_load"
-else
-  { echo "$as_me:$LINENO: checking for shl_load in -ldld" >&5
-echo $ECHO_N "checking for shl_load in -ldld... $ECHO_C" >&6; }
-if test "${ac_cv_lib_dld_shl_load+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dld_shl_load=3Dyes
+else
+  ac_cv_lib_dld_shl_load=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=3D$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" =
>&5
+$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
+if test "x$ac_cv_lib_dld_shl_load" =3D x""yes; then :
+  lt_cv_dlopen=3D"shl_load" lt_cv_dlopen_libs=3D"-ldld"
+else
+  ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
+if test "x$ac_cv_func_dlopen" =3D x""yes; then :
+  lt_cv_dlopen=3D"dlopen"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if test "${ac_cv_lib_dl_dlopen+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-ldld  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS=3D"-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -10382,77 +11276,38 @@
 #ifdef __cplusplus
 extern "C"
 #endif
-char shl_load ();
-int
-main ()
-{
-return shl_load ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_dld_shl_load=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_dld_shl_load=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_dlopen=3Dyes
+else
+  ac_cv_lib_dl_dlopen=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_shl_load" >&5
-echo "${ECHO_T}$ac_cv_lib_dld_shl_load" >&6; }
-if test $ac_cv_lib_dld_shl_load =3D yes; then
-  lt_cv_dlopen=3D"shl_load" lt_cv_dlopen_libs=3D"-dld"
-else
-  { echo "$as_me:$LINENO: checking for dlopen" >&5
-echo $ECHO_N "checking for dlopen... $ECHO_C" >&6; }
-if test "${ac_cv_func_dlopen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define dlopen to an innocuous variant, in case <limits.h> declares dlop=
en.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define dlopen innocuous_dlopen
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char dlopen (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef dlopen
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
+$as_echo "$ac_cv_lib_dl_dlopen" >&6; }
+if test "x$ac_cv_lib_dl_dlopen" =3D x""yes; then :
+  lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-ldl"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" =
>&5
+$as_echo_n "checking for dlopen in -lsvld... " >&6; }
+if test "${ac_cv_lib_svld_dlopen+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=3D$LIBS
+LIBS=3D"-lsvld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
@@ -10461,13 +11316,6 @@
 extern "C"
 #endif
 char dlopen ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_dlopen || defined __stub___dlopen
-choke me
-#endif
-
 int
 main ()
 {
@@ -10476,52 +11324,28 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_dlopen=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_dlopen=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_dlopen" >&5
-echo "${ECHO_T}$ac_cv_func_dlopen" >&6; }
-if test $ac_cv_func_dlopen =3D yes; then
-  lt_cv_dlopen=3D"dlopen"
-else
-  { echo "$as_me:$LINENO: checking for dlopen in -ldl" >&5
-echo $ECHO_N "checking for dlopen in -ldl... $ECHO_C" >&6; }
-if test "${ac_cv_lib_dl_dlopen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_svld_dlopen=3Dyes
+else
+  ac_cv_lib_svld_dlopen=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=3D$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >=
&5
+$as_echo "$ac_cv_lib_svld_dlopen" >&6; }
+if test "x$ac_cv_lib_svld_dlopen" =3D x""yes; then :
+  lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-lsvld"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld"=
 >&5
+$as_echo_n "checking for dld_link in -ldld... " >&6; }
+if test "${ac_cv_lib_dld_dld_link+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-ldl  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS=3D"-ldld  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -10530,177 +11354,28 @@
 #ifdef __cplusplus
 extern "C"
 #endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_dl_dlopen=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_dl_dlopen=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+char dld_link ();
+int
+main ()
+{
+return dld_link ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dld_dld_link=3Dyes
+else
+  ac_cv_lib_dld_dld_link=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dl_dlopen" >&5
-echo "${ECHO_T}$ac_cv_lib_dl_dlopen" >&6; }
-if test $ac_cv_lib_dl_dlopen =3D yes; then
-  lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-ldl"
-else
-  { echo "$as_me:$LINENO: checking for dlopen in -lsvld" >&5
-echo $ECHO_N "checking for dlopen in -lsvld... $ECHO_C" >&6; }
-if test "${ac_cv_lib_svld_dlopen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-lsvld  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlopen ();
-int
-main ()
-{
-return dlopen ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_svld_dlopen=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_svld_dlopen=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=3D$ac_check_lib_save_LIBS
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_svld_dlopen" >&5
-echo "${ECHO_T}$ac_cv_lib_svld_dlopen" >&6; }
-if test $ac_cv_lib_svld_dlopen =3D yes; then
-  lt_cv_dlopen=3D"dlopen" lt_cv_dlopen_libs=3D"-lsvld"
-else
-  { echo "$as_me:$LINENO: checking for dld_link in -ldld" >&5
-echo $ECHO_N "checking for dld_link in -ldld... $ECHO_C" >&6; }
-if test "${ac_cv_lib_dld_dld_link+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-ldld  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dld_link ();
-int
-main ()
-{
-return dld_link ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_dld_dld_link=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_dld_dld_link=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=3D$ac_check_lib_save_LIBS
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dld_dld_link" >&5
-echo "${ECHO_T}$ac_cv_lib_dld_dld_link" >&6; }
-if test $ac_cv_lib_dld_dld_link =3D yes; then
-  lt_cv_dlopen=3D"dld_link" lt_cv_dlopen_libs=3D"-dld"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" =
>&5
+$as_echo "$ac_cv_lib_dld_dld_link" >&6; }
+if test "x$ac_cv_lib_dld_dld_link" =3D x""yes; then :
+  lt_cv_dlopen=3D"dld_link" lt_cv_dlopen_libs=3D"-ldld"
 fi
=20
=20
@@ -10738,18 +11413,18 @@
     save_LIBS=3D"$LIBS"
     LIBS=3D"$lt_cv_dlopen_libs $LIBS"
=20
-    { echo "$as_me:$LINENO: checking whether a program can dlopen itself" =
>&5
-echo $ECHO_N "checking whether a program can dlopen itself... $ECHO_C" >&6=
; }
-if test "${lt_cv_dlopen_self+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program ca=
n dlopen itself" >&5
+$as_echo_n "checking whether a program can dlopen itself... " >&6; }
+if test "${lt_cv_dlopen_self+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   	  if test "$cross_compiling" =3D yes; then :
   lt_cv_dlopen_self=3Dcross
 else
   lt_dlunknown=3D0; lt_dlno_uscore=3D1; lt_dlneed_uscore=3D2
   lt_status=3D$lt_dlunknown
-  cat > conftest.$ac_ext <<EOF
-#line 10752 "configure"
+  cat > conftest.$ac_ext <<_LT_EOF
+#line $LINENO "configure"
 #include "confdefs.h"
=20
 #if HAVE_DLFCN_H
@@ -10790,11 +11465,13 @@
 #  endif
 #endif
=20
-#ifdef __cplusplus
-extern "C" void exit (int);
-#endif
-
-void fnord() { int i=3D42;}
+/* When -fvisbility=3Dhidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ =3D=3D 3) && (__GNUC_MINOR__ >=3D 3))=
 || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
 int main ()
 {
   void *self =3D dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
@@ -10803,20 +11480,24 @@
   if (self)
     {
       if (dlsym (self,"fnord"))       status =3D $lt_dlno_uscore;
-      else if (dlsym( self,"_fnord")) status =3D $lt_dlneed_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status =3D $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
       /* dlclose (self); */
     }
   else
     puts (dlerror ());
=20
-    exit (status);
-}
-EOF
-  if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  return status;
+}
+_LT_EOF
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
   (eval $ac_link) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } && test -s conftest${ac_exeext} 2>/dev/null; th=
en
     (./conftest; exit; ) >&5 2>/dev/null
     lt_status=3D$?
     case x$lt_status in
@@ -10833,23 +11514,23 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_dlopen_self" >&5
-echo "${ECHO_T}$lt_cv_dlopen_self" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5
+$as_echo "$lt_cv_dlopen_self" >&6; }
=20
     if test "x$lt_cv_dlopen_self" =3D xyes; then
       wl=3D$lt_prog_compiler_wl eval LDFLAGS=3D\"\$LDFLAGS $lt_prog_compil=
er_static\"
-      { echo "$as_me:$LINENO: checking whether a statically linked program=
 can dlopen itself" >&5
-echo $ECHO_N "checking whether a statically linked program can dlopen itse=
lf... $ECHO_C" >&6; }
-if test "${lt_cv_dlopen_self_static+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statical=
ly linked program can dlopen itself" >&5
+$as_echo_n "checking whether a statically linked program can dlopen itself=
... " >&6; }
+if test "${lt_cv_dlopen_self_static+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   	  if test "$cross_compiling" =3D yes; then :
   lt_cv_dlopen_self_static=3Dcross
 else
   lt_dlunknown=3D0; lt_dlno_uscore=3D1; lt_dlneed_uscore=3D2
   lt_status=3D$lt_dlunknown
-  cat > conftest.$ac_ext <<EOF
-#line 10852 "configure"
+  cat > conftest.$ac_ext <<_LT_EOF
+#line $LINENO "configure"
 #include "confdefs.h"
=20
 #if HAVE_DLFCN_H
@@ -10890,11 +11571,13 @@
 #  endif
 #endif
=20
-#ifdef __cplusplus
-extern "C" void exit (int);
-#endif
-
-void fnord() { int i=3D42;}
+/* When -fvisbility=3Dhidden is used, assume the code has been annotated
+   correspondingly for the symbols needed.  */
+#if defined(__GNUC__) && (((__GNUC__ =3D=3D 3) && (__GNUC_MINOR__ >=3D 3))=
 || (__GNUC__ > 3))
+int fnord () __attribute__((visibility("default")));
+#endif
+
+int fnord () { return 42; }
 int main ()
 {
   void *self =3D dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW);
@@ -10903,20 +11586,24 @@
   if (self)
     {
       if (dlsym (self,"fnord"))       status =3D $lt_dlno_uscore;
-      else if (dlsym( self,"_fnord")) status =3D $lt_dlneed_uscore;
+      else
+        {
+	  if (dlsym( self,"_fnord"))  status =3D $lt_dlneed_uscore;
+          else puts (dlerror ());
+	}
       /* dlclose (self); */
     }
   else
     puts (dlerror ());
=20
-    exit (status);
-}
-EOF
-  if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
+  return status;
+}
+_LT_EOF
+  if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5
   (eval $ac_link) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && test -s conftest${ac_exeext} 2>/dev/null; then
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; } && test -s conftest${ac_exeext} 2>/dev/null; th=
en
     (./conftest; exit; ) >&5 2>/dev/null
     lt_status=3D$?
     case x$lt_status in
@@ -10933,8 +11620,8 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: result: $lt_cv_dlopen_self_static" >&5
-echo "${ECHO_T}$lt_cv_dlopen_self_static" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static=
" >&5
+$as_echo "$lt_cv_dlopen_self_static" >&6; }
     fi
=20
     CPPFLAGS=3D"$save_CPPFLAGS"
@@ -10955,524 +11642,103 @@
 fi
=20
=20
-# Report which library types will actually be built
-{ echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
-echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&=
6; }
-{ echo "$as_me:$LINENO: result: $can_build_shared" >&5
-echo "${ECHO_T}$can_build_shared" >&6; }
-
-{ echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
-echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6; }
-test "$can_build_shared" =3D "no" && enable_shared=3Dno
-
-# On AIX, shared libraries and static libraries use the same namespace, and
-# are all built from PIC.
-case $host_os in
-aix3*)
-  test "$enable_shared" =3D yes && enable_static=3Dno
-  if test -n "$RANLIB"; then
-    archive_cmds=3D"$archive_cmds~\$RANLIB \$lib"
-    postinstall_cmds=3D'$RANLIB $lib'
-  fi
-  ;;
-
-aix4* | aix5*)
-  if test "$host_cpu" !=3D ia64 && test "$aix_use_runtimelinking" =3D no ;=
 then
-    test "$enable_shared" =3D yes && enable_static=3Dno
-  fi
-    ;;
-esac
-{ echo "$as_me:$LINENO: result: $enable_shared" >&5
-echo "${ECHO_T}$enable_shared" >&6; }
-
-{ echo "$as_me:$LINENO: checking whether to build static libraries" >&5
-echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6; }
-# Make sure either enable_shared or enable_static is yes.
-test "$enable_shared" =3D yes || enable_static=3Dyes
-{ echo "$as_me:$LINENO: result: $enable_static" >&5
-echo "${ECHO_T}$enable_static" >&6; }
-
-# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our comm=
ands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTC=
FLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    compiler \
-    CC \
-    LD \
-    lt_prog_compiler_wl \
-    lt_prog_compiler_pic \
-    lt_prog_compiler_static \
-    lt_prog_compiler_no_builtin_flag \
-    export_dynamic_flag_spec \
-    thread_safe_flag_spec \
-    whole_archive_flag_spec \
-    enable_shared_with_static_runtimes \
-    old_archive_cmds \
-    old_archive_from_new_cmds \
-    predep_objects \
-    postdep_objects \
-    predeps \
-    postdeps \
-    compiler_lib_search_path \
-    archive_cmds \
-    archive_expsym_cmds \
-    postinstall_cmds \
-    postuninstall_cmds \
-    old_archive_from_expsyms_cmds \
-    allow_undefined_flag \
-    no_undefined_flag \
-    export_symbols_cmds \
-    hardcode_libdir_flag_spec \
-    hardcode_libdir_flag_spec_ld \
-    hardcode_libdir_separator \
-    hardcode_automatic \
-    module_cmds \
-    module_expsym_cmds \
-    lt_cv_prog_compiler_c_o \
-    exclude_expsyms \
-    include_expsyms; do
-
-    case $var in
-    old_archive_cmds | \
-    old_archive_from_new_cmds | \
-    archive_cmds | \
-    archive_expsym_cmds | \
-    module_cmds | \
-    module_expsym_cmds | \
-    old_archive_from_expsyms_cmds | \
-    export_symbols_cmds | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quot=
e_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
-      ;;
-    *)
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_s=
ubst\"\`\\\""
-      ;;
-    esac
-  done
-
-  case $lt_echo in
-  *'\$0 --fallback-echo"')
-    lt_echo=3D`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$=
/$0 --fallback-echo"/'`
-    ;;
-  esac
-
-cfgfile=3D"${ofile}T"
-  trap "$rm \"$cfgfile\"; exit 1" 1 2 15
-  $rm -f "$cfgfile"
-  { echo "$as_me:$LINENO: creating $ofile" >&5
-echo "$as_me: creating $ofile" >&6;}
-
-  cat <<__EOF__ >> "$cfgfile"
-#! $SHELL
-
-# `$echo "$cfgfile" | sed 's%^.*/%%'` - Provide generalized library-buildi=
ng support services.
-# Generated automatically by $PROGRAM (GNU $PACKAGE $VERSION$TIMESTAMP)
-# NOTE: Changes made to this file will be lost: look at ltmain.sh.
-#
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
-# Free Software Foundation, Inc.
-#
-# This file is part of GNU Libtool:
-# Originally by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301=
, USA.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# A sed program that does not truncate output.
-SED=3D$lt_SED
-
-# Sed that helps us avoid accidentally triggering echo(1) options like -n.
-Xsed=3D"$SED -e 1s/^X//"
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-# The names of the tagged configurations supported by this script.
-available_tags=3D
-
-# ### BEGIN LIBTOOL CONFIG
-
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed=
 1q`:
-
-# Shell to use when invoking shell scripts.
-SHELL=3D$lt_SHELL
-
-# Whether or not to build shared libraries.
-build_libtool_libs=3D$enable_shared
-
-# Whether or not to build static libraries.
-build_old_libs=3D$enable_static
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=3D$archive_cmds_need_lc
-
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=3D$enable_shared_with_static_runti=
mes
-
-# Whether or not to optimize for fast installation.
-fast_install=3D$enable_fast_install
-
-# The host system.
-host_alias=3D$host_alias
-host=3D$host
-host_os=3D$host_os
-
-# The build system.
-build_alias=3D$build_alias
-build=3D$build
-build_os=3D$build_os
-
-# An echo program that does not interpret backslashes.
-echo=3D$lt_echo
-
-# The archiver.
-AR=3D$lt_AR
-AR_FLAGS=3D$lt_AR_FLAGS
-
-# A C compiler.
-LTCC=3D$lt_LTCC
-
-# LTCC compiler flags.
-LTCFLAGS=3D$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=3D$lt_compiler
-
-# Is the compiler the GNU C compiler?
-with_gcc=3D$GCC
-
-# An ERE matcher.
-EGREP=3D$lt_EGREP
-
-# The linker used to build libraries.
-LD=3D$lt_LD
-
-# Whether we need hard or soft links.
-LN_S=3D$lt_LN_S
-
-# A BSD-compatible nm program.
-NM=3D$lt_NM
-
-# A symbol stripping program
-STRIP=3D$lt_STRIP
-
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=3D$MAGIC_CMD
-
-# Used on cygwin: DLL creation program.
-DLLTOOL=3D"$DLLTOOL"
-
-# Used on cygwin: object dumper.
-OBJDUMP=3D"$OBJDUMP"
-
-# Used on cygwin: assembler.
-AS=3D"$AS"
-
-# The name of the directory that contains temporary libtool files.
-objdir=3D$objdir
-
-# How to create reloadable object files.
-reload_flag=3D$lt_reload_flag
-reload_cmds=3D$lt_reload_cmds
-
-# How to pass a linker flag through the compiler.
-wl=3D$lt_lt_prog_compiler_wl
-
-# Object file suffix (normally "o").
-objext=3D"$ac_objext"
-
-# Old archive suffix (normally "a").
-libext=3D"$libext"
-
-# Shared library suffix (normally ".so").
-shrext_cmds=3D'$shrext_cmds'
-
-# Executable file suffix (normally "").
-exeext=3D"$exeext"
-
-# Additional compiler flags for building library objects.
-pic_flag=3D$lt_lt_prog_compiler_pic
-pic_mode=3D$pic_mode
-
-# What is the maximum length of a command?
-max_cmd_len=3D$lt_cv_sys_max_cmd_len
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=3D$lt_lt_cv_prog_compiler_c_o
-
-# Must we lock files when doing compilation?
-need_locks=3D$lt_need_locks
-
-# Do we need the lib prefix for modules?
-need_lib_prefix=3D$need_lib_prefix
-
-# Do we need a version for libraries?
-need_version=3D$need_version
-
-# Whether dlopen is supported.
-dlopen_support=3D$enable_dlopen
-
-# Whether dlopen of programs is supported.
-dlopen_self=3D$enable_dlopen_self
-
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=3D$enable_dlopen_self_static
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=3D$lt_lt_prog_compiler_static
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=3D$lt_lt_prog_compiler_no_builtin_flag
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=3D$lt_export_dynamic_flag_spec
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=3D$lt_whole_archive_flag_spec
-
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=3D$lt_thread_safe_flag_spec
-
-# Library versioning type.
-version_type=3D$version_type
-
-# Format of library name prefix.
-libname_spec=3D$lt_libname_spec
-
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=3D$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=3D$lt_soname_spec
-
-# Commands used to build and install an old-style archive.
-RANLIB=3D$lt_RANLIB
-old_archive_cmds=3D$lt_old_archive_cmds
-old_postinstall_cmds=3D$lt_old_postinstall_cmds
-old_postuninstall_cmds=3D$lt_old_postuninstall_cmds
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=3D$lt_old_archive_from_new_cmds
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=3D$lt_old_archive_from_expsyms_cmds
-
-# Commands used to build and install a shared archive.
-archive_cmds=3D$lt_archive_cmds
-archive_expsym_cmds=3D$lt_archive_expsym_cmds
-postinstall_cmds=3D$lt_postinstall_cmds
-postuninstall_cmds=3D$lt_postuninstall_cmds
-
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=3D$lt_module_cmds
-module_expsym_cmds=3D$lt_module_expsym_cmds
-
-# Commands to strip libraries.
-old_striplib=3D$lt_old_striplib
-striplib=3D$lt_striplib
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=3D$lt_predep_objects
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=3D$lt_postdep_objects
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=3D$lt_predeps
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=3D$lt_postdeps
-
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=3D$lt_compiler_lib_search_path
-
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=3D$lt_deplibs_check_method
-
-# Command to use when deplibs_check_method =3D=3D file_magic.
-file_magic_cmd=3D$lt_file_magic_cmd
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=3D$lt_allow_undefined_flag
-
-# Flag that forces no undefined symbols.
-no_undefined_flag=3D$lt_no_undefined_flag
-
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=3D$lt_finish_cmds
-
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=3D$lt_finish_eval
-
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=3D$lt_lt_cv_sys_global_symbol_pipe
-
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=3D$lt_lt_cv_sys_global_symbol_to_cdecl
-
-# Transform the output of nm in a C name address pair
-global_symbol_to_c_name_address=3D$lt_lt_cv_sys_global_symbol_to_c_name_ad=
dress
-
-# This is the shared library runtime path variable.
-runpath_var=3D$runpath_var
-
-# This is the shared library path variable.
-shlibpath_var=3D$shlibpath_var
-
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=3D$shlibpath_overrides_runpath
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=3D$hardcode_action
-
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=3D$hardcode_into_libs
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist.
-hardcode_libdir_flag_spec=3D$lt_hardcode_libdir_flag_spec
-
-# If ld is used when linking, flag to hardcode \$libdir into
-# a binary during linking. This must work even if \$libdir does
-# not exist.
-hardcode_libdir_flag_spec_ld=3D$lt_hardcode_libdir_flag_spec_ld
-
-# Whether we need a single -rpath flag with a separated argument.
-hardcode_libdir_separator=3D$lt_hardcode_libdir_separator
-
-# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DI=
R into the
-# resulting binary.
-hardcode_direct=3D$hardcode_direct
-
-# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
-# resulting binary.
-hardcode_minus_L=3D$hardcode_minus_L
-
-# Set to yes if using SHLIBPATH_VAR=3DDIR during linking hardcodes DIR into
-# the resulting binary.
-hardcode_shlibpath_var=3D$hardcode_shlibpath_var
-
-# Set to yes if building a shared library automatically hardcodes DIR into=
 the library
-# and all subsequent libraries and executables linked against it.
-hardcode_automatic=3D$hardcode_automatic
-
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at relink time.
-variables_saved_for_relink=3D"$variables_saved_for_relink"
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=3D$link_all_deplibs
-
-# Compile-time system search path for libraries
-sys_lib_search_path_spec=3D$lt_sys_lib_search_path_spec
-
-# Run-time system search path for libraries
-sys_lib_dlsearch_path_spec=3D$lt_sys_lib_dlsearch_path_spec
-
-# Fix the shell variable \$srcfile for the compiler.
-fix_srcfile_path=3D"$fix_srcfile_path"
-
-# Set to yes if exported symbols are required.
-always_export_symbols=3D$always_export_symbols
-
-# The commands to list exported symbols.
-export_symbols_cmds=3D$lt_export_symbols_cmds
-
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=3D$lt_extract_expsyms_cmds
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=3D$lt_exclude_expsyms
-
-# Symbols that must always be exported.
-include_expsyms=3D$lt_include_expsyms
-
-# ### END LIBTOOL CONFIG
-
-__EOF__
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+striplib=3D
+old_striplib=3D
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping librar=
ies is possible" >&5
+$as_echo_n "checking whether stripping libraries is possible... " >&6; }
+if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then
+  test -z "$old_striplib" && old_striplib=3D"$STRIP --strip-debug"
+  test -z "$striplib" && striplib=3D"$STRIP --strip-unneeded"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+# FIXME - insert some real tests, host_os isn't really good enough
+  case $host_os in
+  darwin*)
+    if test -n "$STRIP" ; then
+      striplib=3D"$STRIP -x"
+      old_striplib=3D"$STRIP -S"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+    fi
+    ;;
+  *)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+    ;;
+  esac
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+  # Report which library types will actually be built
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports sh=
ared libraries" >&5
+$as_echo_n "checking if libtool supports shared libraries... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5
+$as_echo "$can_build_shared" >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build share=
d libraries" >&5
+$as_echo_n "checking whether to build shared libraries... " >&6; }
+  test "$can_build_shared" =3D "no" && enable_shared=3Dno
+
+  # On AIX, shared libraries and static libraries use the same namespace, =
and
+  # are all built from PIC.
   case $host_os in
   aix3*)
-    cat <<\EOF >> "$cfgfile"
-
-# AIX sometimes has problems with the GCC collect2 program.  For some
-# reason, if we set the COLLECT_NAMES environment variable, the problems
-# vanish in a puff of smoke.
-if test "X${COLLECT_NAMES+set}" !=3D Xset; then
-  COLLECT_NAMES=3D
-  export COLLECT_NAMES
-fi
-EOF
-    ;;
-  esac
-
-  # We use sed instead of cat because bash on DJGPP gets confused if
-  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
-  # text mode, it properly converts lines to CR/LF.  This bash problem
-  # is reportedly fixed, but why not run on old versions too?
-  sed '$q' "$ltmain" >> "$cfgfile" || (rm -f "$cfgfile"; exit 1)
-
-  mv -f "$cfgfile" "$ofile" || \
-    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
-  chmod +x "$ofile"
-
-else
-  # If there is no Makefile yet, we rely on a make rule to execute
-  # `config.status --recheck' to rerun these tests and create the
-  # libtool script then.
-  ltmain_in=3D`echo $ltmain | sed -e 's/\.sh$/.in/'`
-  if test -f "$ltmain_in"; then
-    test -f Makefile && make "$ltmain"
-  fi
-fi
-
-
+    test "$enable_shared" =3D yes && enable_static=3Dno
+    if test -n "$RANLIB"; then
+      archive_cmds=3D"$archive_cmds~\$RANLIB \$lib"
+      postinstall_cmds=3D'$RANLIB $lib'
+    fi
+    ;;
+
+  aix[4-9]*)
+    if test "$host_cpu" !=3D ia64 && test "$aix_use_runtimelinking" =3D no=
 ; then
+      test "$enable_shared" =3D yes && enable_static=3Dno
+    fi
+    ;;
+  esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5
+$as_echo "$enable_shared" >&6; }
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build stati=
c libraries" >&5
+$as_echo_n "checking whether to build static libraries... " >&6; }
+  # Make sure either enable_shared or enable_static is yes.
+  test "$enable_shared" =3D yes || enable_static=3Dyes
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5
+$as_echo "$enable_static" >&6; }
+
+
+
+
+fi
 ac_ext=3Dc
 ac_cpp=3D'$CPP $CPPFLAGS'
 ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -11482,8715 +11748,996 @@
 CC=3D"$lt_save_CC"
=20
=20
-# Check whether --with-tags was given.
-if test "${with_tags+set}" =3D set; then
-  withval=3D$with_tags; tagnames=3D"$withval"
-fi
-
-
-if test -f "$ltmain" && test -n "$tagnames"; then
-  if test ! -f "${ofile}"; then
-    { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not exist"=
 >&5
-echo "$as_me: WARNING: output file \`$ofile' does not exist" >&2;}
-  fi
-
-  if test -z "$LTCC"; then
-    eval "`$SHELL ${ofile} --config | grep '^LTCC=3D'`"
-    if test -z "$LTCC"; then
-      { echo "$as_me:$LINENO: WARNING: output file \`$ofile' does not look=
 like a libtool script" >&5
-echo "$as_me: WARNING: output file \`$ofile' does not look like a libtool =
script" >&2;}
-    else
-      { echo "$as_me:$LINENO: WARNING: using \`LTCC=3D$LTCC', extracted fr=
om \`$ofile'" >&5
-echo "$as_me: WARNING: using \`LTCC=3D$LTCC', extracted from \`$ofile'" >&=
2;}
-    fi
-  fi
-  if test -z "$LTCFLAGS"; then
-    eval "`$SHELL ${ofile} --config | grep '^LTCFLAGS=3D'`"
-  fi
-
-  # Extract list of available tagged configurations in $ofile.
-  # Note that this assumes the entire list is on one line.
-  available_tags=3D`grep "^available_tags=3D" "${ofile}" | $SED -e 's/avai=
lable_tags=3D\(.*$\)/\1/' -e 's/\"//g'`
-
-  lt_save_ifs=3D"$IFS"; IFS=3D"${IFS}$PATH_SEPARATOR,"
-  for tagname in $tagnames; do
-    IFS=3D"$lt_save_ifs"
-    # Check whether tagname contains only valid characters
-    case `$echo "X$tagname" | $Xsed -e 's:[-_ABCDEFGHIJKLMNOPQRSTUVWXYZabc=
defghijklmnopqrstuvwxyz1234567890,/]::g'` in
-    "") ;;
-    *)  { { echo "$as_me:$LINENO: error: invalid tag name: $tagname" >&5
-echo "$as_me: error: invalid tag name: $tagname" >&2;}
-   { (exit 1); exit 1; }; }
-	;;
-    esac
-
-    if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "${ofile}" > /d=
ev/null
-    then
-      { { echo "$as_me:$LINENO: error: tag name \"$tagname\" already exist=
s" >&5
-echo "$as_me: error: tag name \"$tagname\" already exists" >&2;}
-   { (exit 1); exit 1; }; }
-    fi
-
-    # Update the list of available tags.
-    if test -n "$tagname"; then
-      echo appending configuration tag \"$tagname\" to $ofile
-
-      case $tagname in
-      CXX)
-	if test -n "$CXX" && ( test "X$CXX" !=3D "Xno" &&
-	    ( (test "X$CXX" =3D "Xg++" && `g++ -v >/dev/null 2>&1` ) ||
-	    (test "X$CXX" !=3D "Xg++"))) ; then
-	  ac_ext=3Dcpp
-ac_cpp=3D'$CXXCPP $CPPFLAGS'
-ac_compile=3D'$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftes=
t.$ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_cxx_compiler_gnu
-
-
-
-
-archive_cmds_need_lc_CXX=3Dno
-allow_undefined_flag_CXX=3D
-always_export_symbols_CXX=3Dno
-archive_expsym_cmds_CXX=3D
-export_dynamic_flag_spec_CXX=3D
-hardcode_direct_CXX=3Dno
-hardcode_libdir_flag_spec_CXX=3D
-hardcode_libdir_flag_spec_ld_CXX=3D
-hardcode_libdir_separator_CXX=3D
-hardcode_minus_L_CXX=3Dno
-hardcode_shlibpath_var_CXX=3Dunsupported
-hardcode_automatic_CXX=3Dno
-module_cmds_CXX=3D
-module_expsym_cmds_CXX=3D
-link_all_deplibs_CXX=3Dunknown
-old_archive_cmds_CXX=3D$old_archive_cmds
-no_undefined_flag_CXX=3D
-whole_archive_flag_spec_CXX=3D
-enable_shared_with_static_runtimes_CXX=3Dno
-
-# Dependencies to place before and after the object being linked:
-predep_objects_CXX=3D
-postdep_objects_CXX=3D
-predeps_CXX=3D
-postdeps_CXX=3D
-compiler_lib_search_path_CXX=3D
-
-# Source file extension for C++ test sources.
-ac_ext=3Dcpp
-
-# Object file extension for compiled C++ test sources.
-objext=3Do
-objext_CXX=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"int some_variable =3D 0;\n"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D'int main(int, char *[]) { return(0); }\n'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-
-# If no C compiler was specified, use CC.
-LTCC=3D${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=3D${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=3D$CC
-
-
-# save warnings/boilerplate of simple test code
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D$CC
-lt_save_LD=3D$LD
-lt_save_GCC=3D$GCC
-GCC=3D$GXX
-lt_save_with_gnu_ld=3D$with_gnu_ld
-lt_save_path_LD=3D$lt_cv_path_LD
-if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then
-  lt_cv_prog_gnu_ld=3D$lt_cv_prog_gnu_ldcxx
-else
-  $as_unset lt_cv_prog_gnu_ld
-fi
-if test -n "${lt_cv_path_LDCXX+set}"; then
-  lt_cv_path_LD=3D$lt_cv_path_LDCXX
-else
-  $as_unset lt_cv_path_LD
-fi
-test -z "${LDCXX+set}" || LD=3D$LDCXX
-CC=3D${CXX-"c++"}
-compiler=3D$CC
-compiler_CXX=3D$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
-
-
-# We don't want -fno-exception wen compiling C++ code, so set the
-# no_builtin_flag separately
-if test "$GXX" =3D yes; then
-  lt_prog_compiler_no_builtin_flag_CXX=3D' -fno-builtin'
-else
-  lt_prog_compiler_no_builtin_flag_CXX=3D
-fi
-
-if test "$GXX" =3D yes; then
-  # Set up default GNU C++ configuration
-
-
-# Check whether --with-gnu-ld was given.
-if test "${with_gnu_ld+set}" =3D set; then
-  withval=3D$with_gnu_ld; test "$withval" =3D no || with_gnu_ld=3Dyes
-else
-  with_gnu_ld=3Dno
-fi
-
-ac_prog=3Dld
-if test "$GCC" =3D yes; then
-  # Check if gcc -print-prog-name=3Dld gives a path.
-  { echo "$as_me:$LINENO: checking for ld used by $CC" >&5
-echo $ECHO_N "checking for ld used by $CC... $ECHO_C" >&6; }
-  case $host in
-  *-*-mingw*)
-    # gcc leaves a trailing carriage return which upsets mingw
-    ac_prog=3D`($CC -print-prog-name=3Dld) 2>&5 | tr -d '\015'` ;;
+
+
+
+
+
+
+
+
+
+
+
+        ac_config_commands=3D"$ac_config_commands libtool"
+
+
+
+
+# Only expand once:
+
+
+
+
+
+test "$sysconfdir" =3D '${prefix}/etc' && sysconfdir=3D'/etc'
+test "$localstatedir" =3D '${prefix}/var' && localstatedir=3D'/var/heimdal'
+
+
+CANONICAL_HOST=3D$host
+
+
+# Check whether --enable-largefile was given.
+if test "${enable_largefile+set}" =3D set; then :
+  enableval=3D$enable_largefile;
+fi
+
+if test "$enable_largefile" !=3D no; then
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler=
 options needed for large files" >&5
+$as_echo_n "checking for special C compiler options needed for large files=
... " >&6; }
+if test "${ac_cv_sys_largefile_CC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_sys_largefile_CC=3Dno
+     if test "$GCC" !=3D yes; then
+       ac_save_CC=3D$CC
+       while :; do
+	 # IRIX 6.2 and later do not support large files by default,
+	 # so use the C compiler's -n32 option if that helps.
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
+		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+	 if ac_fn_c_try_compile "$LINENO"; then :
+  break
+fi
+rm -f core conftest.err conftest.$ac_objext
+	 CC=3D"$CC -n32"
+	 if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_largefile_CC=3D' -n32'; break
+fi
+rm -f core conftest.err conftest.$ac_objext
+	 break
+       done
+       CC=3D$ac_save_CC
+       rm -f conftest.$ac_ext
+    fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" =
>&5
+$as_echo "$ac_cv_sys_largefile_CC" >&6; }
+  if test "$ac_cv_sys_largefile_CC" !=3D no; then
+    CC=3D$CC$ac_cv_sys_largefile_CC
+  fi
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS =
value needed for large files" >&5
+$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files...=
 " >&6; }
+if test "${ac_cv_sys_file_offset_bits+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  while :; do
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
+		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_file_offset_bits=3Dno; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#define _FILE_OFFSET_BITS 64
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
+		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_file_offset_bits=3D64; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_cv_sys_file_offset_bits=3Dunknown
+  break
+done
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bi=
ts" >&5
+$as_echo "$ac_cv_sys_file_offset_bits" >&6; }
+case $ac_cv_sys_file_offset_bits in #(
+  no | unknown) ;;
   *)
-    ac_prog=3D`($CC -print-prog-name=3Dld) 2>&5` ;;
-  esac
-  case $ac_prog in
-    # Accept absolute paths.
-    [\\/]* | ?:[\\/]*)
-      re_direlt=3D'/[^/][^/]*/\.\./'
-      # Canonicalize the pathname of ld
-      ac_prog=3D`echo $ac_prog| $SED 's%\\\\%/%g'`
-      while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
-	ac_prog=3D`echo $ac_prog| $SED "s%$re_direlt%/%"`
-      done
-      test -z "$LD" && LD=3D"$ac_prog"
-      ;;
-  "")
-    # If it fails, then pretend we aren't using GCC.
-    ac_prog=3Dld
-    ;;
+cat >>confdefs.h <<_ACEOF
+#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits
+_ACEOF
+;;
+esac
+rm -rf conftest*
+  if test $ac_cv_sys_file_offset_bits =3D unknown; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES val=
ue needed for large files" >&5
+$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&=
6; }
+if test "${ac_cv_sys_large_files+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  while :; do
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
+		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_large_files=3Dno; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#define _LARGE_FILES 1
+#include <sys/types.h>
+ /* Check that off_t can represent 2**63 - 1 correctly.
+    We can't simply define LARGE_OFF_T to be 9223372036854775807,
+    since some C++ compilers masquerading as C compilers
+    incorrectly reject 9223372036854775807.  */
+#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
+  int off_t_is_large[(LARGE_OFF_T % 2147483629 =3D=3D 721
+		       && LARGE_OFF_T % 2147483647 =3D=3D 1)
+		      ? 1 : -1];
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_sys_large_files=3D1; break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  ac_cv_sys_large_files=3Dunknown
+  break
+done
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >=
&5
+$as_echo "$ac_cv_sys_large_files" >&6; }
+case $ac_cv_sys_large_files in #(
+  no | unknown) ;;
   *)
-    # If it is relative, then search for the first ld in PATH.
-    with_gnu_ld=3Dunknown
-    ;;
-  esac
-elif test "$with_gnu_ld" =3D yes; then
-  { echo "$as_me:$LINENO: checking for GNU ld" >&5
-echo $ECHO_N "checking for GNU ld... $ECHO_C" >&6; }
-else
-  { echo "$as_me:$LINENO: checking for non-GNU ld" >&5
-echo $ECHO_N "checking for non-GNU ld... $ECHO_C" >&6; }
-fi
-if test "${lt_cv_path_LD+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -z "$LD"; then
-  lt_save_ifs=3D"$IFS"; IFS=3D$PATH_SEPARATOR
-  for ac_dir in $PATH; do
-    IFS=3D"$lt_save_ifs"
-    test -z "$ac_dir" && ac_dir=3D.
-    if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext";=
 then
-      lt_cv_path_LD=3D"$ac_dir/$ac_prog"
-      # Check to see if the program is GNU ld.  I'd rather use --version,
-      # but apparently some variants of GNU ld only accept -v.
-      # Break only if it was the GNU/non-GNU ld that we prefer.
-      case `"$lt_cv_path_LD" -v 2>&1 </dev/null` in
-      *GNU* | *'with BFD'*)
-	test "$with_gnu_ld" !=3D no && break
-	;;
-      *)
-	test "$with_gnu_ld" !=3D yes && break
-	;;
-      esac
-    fi
-  done
-  IFS=3D"$lt_save_ifs"
-else
-  lt_cv_path_LD=3D"$LD" # Let the user override the test with a path.
-fi
-fi
-
-LD=3D"$lt_cv_path_LD"
-if test -n "$LD"; then
-  { echo "$as_me:$LINENO: result: $LD" >&5
-echo "${ECHO_T}$LD" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-test -z "$LD" && { { echo "$as_me:$LINENO: error: no acceptable ld found i=
n \$PATH" >&5
-echo "$as_me: error: no acceptable ld found in \$PATH" >&2;}
-   { (exit 1); exit 1; }; }
-{ echo "$as_me:$LINENO: checking if the linker ($LD) is GNU ld" >&5
-echo $ECHO_N "checking if the linker ($LD) is GNU ld... $ECHO_C" >&6; }
-if test "${lt_cv_prog_gnu_ld+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  # I'd rather use --version here, but apparently some GNU lds only accept=
 -v.
-case `$LD -v 2>&1 </dev/null` in
-*GNU* | *'with BFD'*)
-  lt_cv_prog_gnu_ld=3Dyes
-  ;;
-*)
-  lt_cv_prog_gnu_ld=3Dno
-  ;;
-esac
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_gnu_ld" >&5
-echo "${ECHO_T}$lt_cv_prog_gnu_ld" >&6; }
-with_gnu_ld=3D$lt_cv_prog_gnu_ld
-
-
-
-  # Check if GNU C++ uses GNU ld as the underlying linker, since the
-  # archiving commands below assume that GNU ld is being used.
-  if test "$with_gnu_ld" =3D yes; then
-    archive_cmds_CXX=3D'$CC -shared -nostdlib $predep_objects $libobjs $de=
plibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-    archive_expsym_cmds_CXX=3D'$CC -shared -nostdlib $predep_objects $libo=
bjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}=
-retain-symbols-file $wl$export_symbols -o $lib'
-
-    hardcode_libdir_flag_spec_CXX=3D'${wl}--rpath ${wl}$libdir'
-    export_dynamic_flag_spec_CXX=3D'${wl}--export-dynamic'
-
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to
-    #     investigate it a little bit more. (MM)
-    wlarc=3D'${wl}'
-
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if eval "`$CC -print-prog-name=3Dld` --help 2>&1" | \
-	grep 'no-whole-archive' > /dev/null; then
-      whole_archive_flag_spec_CXX=3D"$wlarc"'--whole-archive$convenience '=
"$wlarc"'--no-whole-archive'
-    else
-      whole_archive_flag_spec_CXX=3D
-    fi
-  else
-    with_gnu_ld=3Dno
-    wlarc=3D
-
-    # A generic and very simple default shared library creation
-    # command for GNU C++ for the case where it uses the native
-    # linker, instead of GNU ld.  If possible, this setting should
-    # overridden to take advantage of the native linker features on
-    # the platform it is being used on.
-    archive_cmds_CXX=3D'$CC -shared -nostdlib $predep_objects $libobjs $de=
plibs $postdep_objects $compiler_flags -o $lib'
-  fi
-
-  # Commands to make compiler produce verbose output that lists
-  # what "hidden" libraries, object files and flags are used when
-  # linking a shared library.
-  output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&1 =
| grep "\-L"'
-
-else
-  GXX=3Dno
-  with_gnu_ld=3Dno
-  wlarc=3D
-fi
-
-# PORTME: fill in a description of your system's C++ link characteristics
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) suppor=
ts shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared =
libraries... $ECHO_C" >&6; }
-ld_shlibs_CXX=3Dyes
-case $host_os in
-  aix3*)
-    # FIXME: insert proper C++ library support
-    ld_shlibs_CXX=3Dno
-    ;;
-  aix4* | aix5*)
-    if test "$host_cpu" =3D ia64; then
-      # On IA64, the linker does run time linking by default, so we don't
-      # have to do anything special.
-      aix_use_runtimelinking=3Dno
-      exp_sym_flag=3D'-Bexport'
-      no_entry_flag=3D""
-    else
-      aix_use_runtimelinking=3Dno
-
-      # Test if we are trying to use run time linking or normal
-      # AIX style linking. If -brtl is somewhere in LDFLAGS, we
-      # need to do runtime linking.
-      case $host_os in aix4.[23]|aix4.[23].*|aix5*)
-	for ld_flag in $LDFLAGS; do
-	  case $ld_flag in
-	  *-brtl*)
-	    aix_use_runtimelinking=3Dyes
-	    break
-	    ;;
-	  esac
-	done
-	;;
-      esac
-
-      exp_sym_flag=3D'-bexport'
-      no_entry_flag=3D'-bnoentry'
-    fi
-
-    # When large executables or shared objects are built, AIX ld can
-    # have problems creating the table of contents.  If linking a library
-    # or program results in "error TOC overflow" add -mminimal-toc to
-    # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-    # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-    archive_cmds_CXX=3D''
-    hardcode_direct_CXX=3Dyes
-    hardcode_libdir_separator_CXX=3D':'
-    link_all_deplibs_CXX=3Dyes
-
-    if test "$GXX" =3D yes; then
-      case $host_os in aix4.[012]|aix4.[012].*)
-      # We only want to do this on AIX 4.2 and lower, the check
-      # below for broken collect2 doesn't work under 4.3+
-	collect2name=3D`${CC} -print-prog-name=3Dcollect2`
-	if test -f "$collect2name" && \
-	   strings "$collect2name" | grep resolve_lib_name >/dev/null
-	then
-	  # We have reworked collect2
-	  hardcode_direct_CXX=3Dyes
+cat >>confdefs.h <<_ACEOF
+#define _LARGE_FILES $ac_cv_sys_large_files
+_ACEOF
+;;
+esac
+rm -rf conftest*
+  fi
+fi
+
+
+if test "$enable_largefile" !=3D no -a "$ac_cv_sys_large_files" !=3D no; t=
hen
+	CPPFLAGS=3D"$CPPFLAGS -D_LARGE_FILES=3D$ac_cv_sys_large_files"
+fi
+if test "$enable_largefile" !=3D no -a "$ac_cv_sys_file_offset_bits" !=3D =
no; then
+	CPPFLAGS=3D"$CPPFLAGS -D_FILE_OFFSET_BITS=3D$ac_cv_sys_file_offset_bits"
+fi
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen" >&5
+$as_echo_n "checking for dlopen... " >&6; }
+if test "${ac_cv_funclib_dlopen+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+if eval "test \"\$ac_cv_func_dlopen\" !=3D yes" ; then
+	ac_save_LIBS=3D"$LIBS"
+	for ac_lib in "" dl; do
+		case "$ac_lib" in
+		"") ;;
+		yes) ac_lib=3D"" ;;
+		no) continue ;;
+		-l*) ;;
+		*) ac_lib=3D"-l$ac_lib" ;;
+		esac
+		LIBS=3D" $ac_lib  $ac_save_LIBS"
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#ifdef HAVE_DLFCN_H
+#include <dlfcn.h>
+#endif
+int
+main ()
+{
+dlopen(0,0)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "if test -n \"$ac_lib\";then ac_cv_funclib_dlopen=3D$ac_lib; else a=
c_cv_funclib_dlopen=3Dyes; fi";break
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	done
+	eval "ac_cv_funclib_dlopen=3D\${ac_cv_funclib_dlopen-no}"
+	LIBS=3D"$ac_save_LIBS"
+fi
+
+fi
+
+
+eval "ac_res=3D\$ac_cv_funclib_dlopen"
+
+if false; then
+	for ac_func in dlopen
+do :
+  ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
+if test "x$ac_cv_func_dlopen" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DLOPEN 1
+_ACEOF
+
+fi
+done
+
+fi
+# dlopen
+eval "ac_tr_func=3DHAVE_`echo dlopen | tr abcdefghijklmnopqrstuvwxyz ABCDE=
FGHIJKLMNOPQRSTUVWXYZ`"
+eval "ac_tr_lib=3DHAVE_LIB`echo $ac_res | sed -e 's/-l//' | tr abcdefghijk=
lmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
+eval "LIB_dlopen=3D$ac_res"
+
+case "$ac_res" in
+	yes)
+	eval "ac_cv_func_dlopen=3Dyes"
+	eval "LIB_dlopen=3D"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+	;;
+	no)
+	eval "ac_cv_func_dlopen=3Dno"
+	eval "LIB_dlopen=3D"
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+	;;
+	*)
+	eval "ac_cv_func_dlopen=3Dyes"
+	eval "ac_cv_lib_`echo "$ac_res" | sed 's/-l//'`=3Dyes"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_lib 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+	 if test "$ac_cv_funclib_dlopen" !=3D no; then
+  HAVE_DLOPEN_TRUE=3D
+  HAVE_DLOPEN_FALSE=3D'#'
+else
+  HAVE_DLOPEN_TRUE=3D'#'
+  HAVE_DLOPEN_FALSE=3D
+fi
+
+
+
+
+aix=3Dno
+case "$host" in
+*-*-aix3*)
+	aix=3D3
+	;;
+*-*-aix[4-9]*)
+	aix=3D4
+	;;
+esac
+
+ if test "$aix" !=3D no; then
+  AIX_TRUE=3D
+  AIX_FALSE=3D'#'
+else
+  AIX_TRUE=3D'#'
+  AIX_FALSE=3D
+fi
+ if test "$aix" =3D 4; then
+  AIX4_TRUE=3D
+  AIX4_FALSE=3D'#'
+else
+  AIX4_TRUE=3D'#'
+  AIX4_FALSE=3D
+fi
+
+# Check whether --enable-dynamic-afs was given.
+if test "${enable_dynamic_afs+set}" =3D set; then :
+  enableval=3D$enable_dynamic_afs;
+fi
+
+
+if test "$aix" !=3D no; then
+
+
+$as_echo "#define NEED_QSORT 1" >>confdefs.h
+
+
+	if test "$enable_dynamic_afs" !=3D no; then
+
+		if test "$ac_cv_func_dlopen" =3D no; then
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for loadquery" >&5
+$as_echo_n "checking for loadquery... " >&6; }
+if test "${ac_cv_funclib_loadquery+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+if eval "test \"\$ac_cv_func_loadquery\" !=3D yes" ; then
+	ac_save_LIBS=3D"$LIBS"
+	for ac_lib in "" ld; do
+		case "$ac_lib" in
+		"") ;;
+		yes) ac_lib=3D"" ;;
+		no) continue ;;
+		-l*) ;;
+		*) ac_lib=3D"-l$ac_lib" ;;
+		esac
+		LIBS=3D" $ac_lib  $ac_save_LIBS"
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+loadquery()
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "if test -n \"$ac_lib\";then ac_cv_funclib_loadquery=3D$ac_lib; els=
e ac_cv_funclib_loadquery=3Dyes; fi";break
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	done
+	eval "ac_cv_funclib_loadquery=3D\${ac_cv_funclib_loadquery-no}"
+	LIBS=3D"$ac_save_LIBS"
+fi
+
+fi
+
+
+eval "ac_res=3D\$ac_cv_funclib_loadquery"
+
+if false; then
+	for ac_func in loadquery
+do :
+  ac_fn_c_check_func "$LINENO" "loadquery" "ac_cv_func_loadquery"
+if test "x$ac_cv_func_loadquery" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LOADQUERY 1
+_ACEOF
+
+fi
+done
+
+fi
+# loadquery
+eval "ac_tr_func=3DHAVE_`echo loadquery | tr abcdefghijklmnopqrstuvwxyz AB=
CDEFGHIJKLMNOPQRSTUVWXYZ`"
+eval "ac_tr_lib=3DHAVE_LIB`echo $ac_res | sed -e 's/-l//' | tr abcdefghijk=
lmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
+eval "LIB_loadquery=3D$ac_res"
+
+case "$ac_res" in
+	yes)
+	eval "ac_cv_func_loadquery=3Dyes"
+	eval "LIB_loadquery=3D"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+	;;
+	no)
+	eval "ac_cv_func_loadquery=3Dno"
+	eval "LIB_loadquery=3D"
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+	;;
+	*)
+	eval "ac_cv_func_loadquery=3Dyes"
+	eval "ac_cv_lib_`echo "$ac_res" | sed 's/-l//'`=3Dyes"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_lib 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+		fi
+		if test "$ac_cv_func_dlopen" !=3D no; then
+			AIX_EXTRA_KAFS=3D'$(LIB_dlopen)'
+		elif test "$ac_cv_func_loadquery" !=3D no; then
+			AIX_EXTRA_KAFS=3D'$(LIB_loadquery)'
+		else
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: not using dynloaded AFS librar=
y" >&5
+$as_echo "$as_me: not using dynloaded AFS library" >&6;}
+			AIX_EXTRA_KAFS=3D
+			enable_dynamic_afs=3Dno
+		fi
 	else
-	  # We have old collect2
-	  hardcode_direct_CXX=3Dunsupported
-	  # It fails to find uninstalled libraries when the uninstalled
-	  # path is not listed in the libpath.  Setting hardcode_minus_L
-	  # to unsupported forces relinking
-	  hardcode_minus_L_CXX=3Dyes
-	  hardcode_libdir_flag_spec_CXX=3D'-L$libdir'
-	  hardcode_libdir_separator_CXX=3D
-	fi
-	;;
-      esac
-      shared_flag=3D'-shared'
-      if test "$aix_use_runtimelinking" =3D yes; then
-	shared_flag=3D"$shared_flag "'${wl}-G'
-      fi
-    else
-      # not using gcc
-      if test "$host_cpu" =3D ia64; then
-	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-	# chokes on -Wl,-G. The following line is correct:
-	shared_flag=3D'-G'
-      else
-	if test "$aix_use_runtimelinking" =3D yes; then
-	  shared_flag=3D'${wl}-G'
-	else
-	  shared_flag=3D'${wl}-bM:SRE'
-	fi
-      fi
-    fi
-
-    # It seems that -bexpall does not export symbols beginning with
-    # underscore (_), so it is better to generate a list of symbols to exp=
ort.
-    always_export_symbols_CXX=3Dyes
-    if test "$aix_use_runtimelinking" =3D yes; then
-      # Warning - without using the other runtime loading flags (-brtl),
-      # -berok will link without error, but may produce a broken library.
-      allow_undefined_flag_CXX=3D'-berok'
-      # Determine the default libpath from the value encoded in an empty e=
xecutable.
-      cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
+		AIX_EXTRA_KAFS=3D
+	fi
+fi
+
+ if test "$enable_dynamic_afs" !=3D no; then
+  AIX_DYNAMIC_AFS_TRUE=3D
+  AIX_DYNAMIC_AFS_FALSE=3D'#'
+else
+  AIX_DYNAMIC_AFS_TRUE=3D'#'
+  AIX_DYNAMIC_AFS_FALSE=3D
+fi
+
+if test "$aix" !=3D no; then
+
+$as_echo "#define _ALL_SOURCE 1" >>confdefs.h
+
+fi
+
+
+
+
+
+irix=3Dno
+case "$host" in
+*-*-irix*)
+	irix=3Dyes
+	;;
+esac
+ if test "$irix" !=3D no; then
+  IRIX_TRUE=3D
+  IRIX_FALSE=3D'#'
+else
+  IRIX_TRUE=3D'#'
+  IRIX_FALSE=3D
+fi
+
+
+
+sunos=3Dno
+case "$host" in
+*-*-solaris2.7)
+	sunos=3D57
+	;;
+*-*-solaris2.[89] | *-*-solaris2.1[0-9])
+	sunos=3D58
+	;;
+*-*-solaris2*)
+	sunos=3D50
+	;;
+esac
+if test "$sunos" !=3D no; then
+
+cat >>confdefs.h <<_ACEOF
+#define SunOS $sunos
+_ACEOF
+
+fi
+
+
+
+$as_echo "#define _GNU_SOURCE 1" >>confdefs.h
+
+
+
+
+
+for ac_prog in 'bison -y' byacc
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
+set dummy $ac_prog; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_YACC+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$YACC"; then
+  ac_cv_prog_YACC=3D"$YACC" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_YACC=3D"$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+YACC=3D$ac_cv_prog_YACC
+if test -n "$YACC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $YACC" >&5
+$as_echo "$YACC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$YACC" && break
+done
+test -n "$YACC" || YACC=3D"yacc"
+
+for ac_prog in flex lex
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
+set dummy $ac_prog; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_LEX+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$LEX"; then
+  ac_cv_prog_LEX=3D"$LEX" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_LEX=3D"$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+LEX=3D$ac_cv_prog_LEX
+if test -n "$LEX"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LEX" >&5
+$as_echo "$LEX" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$LEX" && break
+done
+test -n "$LEX" || LEX=3D":"
+
+if test "x$LEX" !=3D "x:"; then
+  cat >conftest.l <<_ACEOF
+%%
+a { ECHO; }
+b { REJECT; }
+c { yymore (); }
+d { yyless (1); }
+e { yyless (input () !=3D 0); }
+f { unput (yytext[0]); }
+. { BEGIN INITIAL; }
+%%
+#ifdef YYTEXT_POINTER
+extern char *yytext;
+#endif
+int
+main (void)
+{
+  return ! yylex () + ! yywrap ();
+}
+_ACEOF
+{ { ac_try=3D"$LEX conftest.l"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
   *) ac_try_echo=3D$ac_try;;
 esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-
-      hardcode_libdir_flag_spec_CXX=3D'${wl}-blibpath:$libdir:'"$aix_libpa=
th"
-
-      archive_expsym_cmds_CXX=3D"\$CC"' -o $output_objdir/$soname $libobjs=
 $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undef=
ined_flag}" !=3D "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi`=
 '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag"
-     else
-      if test "$host_cpu" =3D ia64; then
-	hardcode_libdir_flag_spec_CXX=3D'${wl}-R $libdir:/usr/lib:/lib'
-	allow_undefined_flag_CXX=3D"-z nodefs"
-	archive_expsym_cmds_CXX=3D"\$CC $shared_flag"' -o $output_objdir/$soname =
$libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_und=
efined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-      else
-	# Determine the default libpath from the value encoded in an empty execut=
able.
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_cxx_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-
-	hardcode_libdir_flag_spec_CXX=3D'${wl}-blibpath:$libdir:'"$aix_libpath"
-	# Warning - without using the other run time loading flags,
-	# -berok will link without error, but may produce a broken library.
-	no_undefined_flag_CXX=3D' ${wl}-bernotok'
-	allow_undefined_flag_CXX=3D' ${wl}-berok'
-	# Exported symbols can be pulled into shared objects from archives
-	whole_archive_flag_spec_CXX=3D'$convenience'
-	archive_cmds_need_lc_CXX=3Dyes
-	# This is similar to how AIX traditionally builds its shared libraries.
-	archive_expsym_cmds_CXX=3D"\$CC $shared_flag"' -o $output_objdir/$soname =
$libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${=
allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $outp=
ut_objdir/$soname'
-      fi
-    fi
-    ;;
-
-  beos*)
-    if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; th=
en
-      allow_undefined_flag_CXX=3Dunsupported
-      # Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-      # support --undefined.  This deserves some investigation.  FIXME
-      archive_cmds_CXX=3D'$CC -nostart $libobjs $deplibs $compiler_flags $=
{wl}-soname $wl$soname -o $lib'
-    else
-      ld_shlibs_CXX=3Dno
-    fi
-    ;;
-
-  chorus*)
-    case $cc_basename in
-      *)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-    esac
-    ;;
-
-  cygwin* | mingw* | pw32*)
-    # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningles=
s,
-    # as there is no search path for DLLs.
-    hardcode_libdir_flag_spec_CXX=3D'-L$libdir'
-    allow_undefined_flag_CXX=3Dunsupported
-    always_export_symbols_CXX=3Dno
-    enable_shared_with_static_runtimes_CXX=3Dyes
-
-    if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-      archive_cmds_CXX=3D'$CC -shared -nostdlib $predep_objects $libobjs $=
deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--e=
nable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-      # If the export-symbols file already is a .def file (1st line
-      # is EXPORTS), use it as is; otherwise, prepend...
-      archive_expsym_cmds_CXX=3D'if test "x`$SED 1q $export_symbols`" =3D =
xEXPORTS; then
-	cp $export_symbols $output_objdir/$soname.def;
-      else
-	echo EXPORTS > $output_objdir/$soname.def;
-	cat $export_symbols >> $output_objdir/$soname.def;
-      fi~
-      $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $li=
bobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $=
{wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib'
-    else
-      ld_shlibs_CXX=3Dno
-    fi
-  ;;
-      darwin* | rhapsody*)
-        case $host_os in
-        rhapsody* | darwin1.[012])
-         allow_undefined_flag_CXX=3D'${wl}-undefined ${wl}suppress'
-         ;;
-       *) # Darwin 1.3 on
-         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
-           allow_undefined_flag_CXX=3D'${wl}-flat_namespace ${wl}-undefine=
d ${wl}suppress'
-         else
-           case ${MACOSX_DEPLOYMENT_TARGET} in
-             10.[012])
-               allow_undefined_flag_CXX=3D'${wl}-flat_namespace ${wl}-unde=
fined ${wl}suppress'
-               ;;
-             10.*)
-               allow_undefined_flag_CXX=3D'${wl}-undefined ${wl}dynamic_lo=
okup'
-               ;;
-           esac
-         fi
-         ;;
-        esac
-      archive_cmds_need_lc_CXX=3Dno
-      hardcode_direct_CXX=3Dno
-      hardcode_automatic_CXX=3Dyes
-      hardcode_shlibpath_var_CXX=3Dunsupported
-      whole_archive_flag_spec_CXX=3D''
-      link_all_deplibs_CXX=3Dyes
-
-    if test "$GXX" =3D yes ; then
-      lt_int_apple_cc_single_mod=3Dno
-      output_verbose_link_cmd=3D'echo'
-      if $CC -dumpspecs 2>&1 | $EGREP 'single_module' >/dev/null ; then
-       lt_int_apple_cc_single_mod=3Dyes
-      fi
-      if test "X$lt_int_apple_cc_single_mod" =3D Xyes ; then
-       archive_cmds_CXX=3D'$CC -dynamiclib -single_module $allow_undefined=
_flag -o $lib $libobjs $deplibs $compiler_flags -install_name $rpath/$sonam=
e $verstring'
-      else
-          archive_cmds_CXX=3D'$CC -r -keep_private_externs -nostdlib -o ${=
lib}-master.o $libobjs~$CC -dynamiclib $allow_undefined_flag -o $lib ${lib}=
-master.o $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
-        fi
-        module_cmds_CXX=3D'$CC $allow_undefined_flag -o $lib -bundle $libo=
bjs $deplibs$compiler_flags'
-        # Don't fix this by using the ld -exported_symbols_list flag, it d=
oesn't exist in older darwin lds
-          if test "X$lt_int_apple_cc_single_mod" =3D Xyes ; then
-            archive_expsym_cmds_CXX=3D'sed -e "s,#.*,," -e "s,^[    ]*,," =
-e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.e=
xpsym~$CC -dynamiclib -single_module $allow_undefined_flag -o $lib $libobjs=
 $deplibs $compiler_flags -install_name $rpath/$soname $verstring~nmedit -s=
 $output_objdir/${libname}-symbols.expsym ${lib}'
-          else
-            archive_expsym_cmds_CXX=3D'sed -e "s,#.*,," -e "s,^[    ]*,," =
-e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.e=
xpsym~$CC -r -keep_private_externs -nostdlib -o ${lib}-master.o $libobjs~$C=
C -dynamiclib $allow_undefined_flag -o $lib ${lib}-master.o $deplibs $compi=
ler_flags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/=
${libname}-symbols.expsym ${lib}'
-          fi
-            module_expsym_cmds_CXX=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -=
e "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.ex=
psym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_=
flags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-      else
-      case $cc_basename in
-        xlc*)
-         output_verbose_link_cmd=3D'echo'
-          archive_cmds_CXX=3D'$CC -qmkshrobj ${wl}-single_module $allow_un=
defined_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-install_name $=
{wl}`echo $rpath/$soname` $verstring'
-          module_cmds_CXX=3D'$CC $allow_undefined_flag -o $lib -bundle $li=
bobjs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it=
 doesn't exist in older darwin lds
-          archive_expsym_cmds_CXX=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e=
 "s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.exp=
sym~$CC -qmkshrobj ${wl}-single_module $allow_undefined_flag -o $lib $libob=
js $deplibs $compiler_flags ${wl}-install_name ${wl}$rpath/$soname $verstri=
ng~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          module_expsym_cmds_CXX=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e =
"s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.exps=
ym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_fl=
ags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          ;;
-       *)
-         ld_shlibs_CXX=3Dno
-          ;;
-      esac
-      fi
-        ;;
-
-  dgux*)
-    case $cc_basename in
-      ec++*)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      ghcx*)
-	# Green Hills C++ Compiler
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-    esac
-    ;;
-  freebsd[12]*)
-    # C++ shared libraries reported to be fairly broken before switch to E=
LF
-    ld_shlibs_CXX=3Dno
-    ;;
-  freebsd-elf*)
-    archive_cmds_need_lc_CXX=3Dno
-    ;;
-  freebsd* | kfreebsd*-gnu | dragonfly*)
-    # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF
-    # conventions
-    ld_shlibs_CXX=3Dyes
-    ;;
-  gnu*)
-    ;;
-  hpux9*)
-    hardcode_libdir_flag_spec_CXX=3D'${wl}+b ${wl}$libdir'
-    hardcode_libdir_separator_CXX=3D:
-    export_dynamic_flag_spec_CXX=3D'${wl}-E'
-    hardcode_direct_CXX=3Dyes
-    hardcode_minus_L_CXX=3Dyes # Not in the search PATH,
-				# but as the default
-				# location of the library.
-
-    case $cc_basename in
-    CC*)
-      # FIXME: insert proper C++ library support
-      ld_shlibs_CXX=3Dno
-      ;;
-    aCC*)
-      archive_cmds_CXX=3D'$rm $output_objdir/$soname~$CC -b ${wl}+b ${wl}$=
install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs =
$postdep_objects $compiler_flags~test $output_objdir/$soname =3D $lib || mv=
 $output_objdir/$soname $lib'
-      # Commands to make compiler produce verbose output that lists
-      # what "hidden" libraries, object files and flags are used when
-      # linking a shared library.
-      #
-      # There doesn't appear to be a way to prevent this compiler from
-      # explicitly linking system object files so we need to strip them
-      # from the output so that they don't get included in the library
-      # dependencies.
-      output_verbose_link_cmd=3D'templist=3D`($CC -b $CFLAGS -v conftest.$=
objext 2>&1) | grep "[-]L"`; list=3D""; for z in $templist; do case $z in c=
onftest.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z";;esa=
c; done; echo $list'
-      ;;
-    *)
-      if test "$GXX" =3D yes; then
-        archive_cmds_CXX=3D'$rm $output_objdir/$soname~$CC -shared -nostdl=
ib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_obj=
ects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir=
/$soname =3D $lib || mv $output_objdir/$soname $lib'
-      else
-        # FIXME: insert proper C++ library support
-        ld_shlibs_CXX=3Dno
-      fi
-      ;;
-    esac
-    ;;
-  hpux10*|hpux11*)
-    if test $with_gnu_ld =3D no; then
-      hardcode_libdir_flag_spec_CXX=3D'${wl}+b ${wl}$libdir'
-      hardcode_libdir_separator_CXX=3D:
-
-      case $host_cpu in
-      hppa*64*|ia64*)
-	hardcode_libdir_flag_spec_ld_CXX=3D'+b $libdir'
-        ;;
-      *)
-	export_dynamic_flag_spec_CXX=3D'${wl}-E'
-        ;;
-      esac
-    fi
-    case $host_cpu in
-    hppa*64*|ia64*)
-      hardcode_direct_CXX=3Dno
-      hardcode_shlibpath_var_CXX=3Dno
-      ;;
-    *)
-      hardcode_direct_CXX=3Dyes
-      hardcode_minus_L_CXX=3Dyes # Not in the search PATH,
-					      # but as the default
-					      # location of the library.
-      ;;
-    esac
-
-    case $cc_basename in
-      CC*)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      aCC*)
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_CXX=3D'$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects=
 $libobjs $deplibs $postdep_objects $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_CXX=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o=
 $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds_CXX=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_l=
ibdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_=
flags'
-	  ;;
-	esac
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`($CC -b $CFLAGS -v conftest.$objex=
t 2>&1) | grep "\-L"`; list=3D""; for z in $templist; do case $z in conftes=
t.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z";;esac; don=
e; echo $list'
-	;;
-      *)
-	if test "$GXX" =3D yes; then
-	  if test $with_gnu_ld =3D no; then
-	    case $host_cpu in
-	    hppa*64*)
-	      archive_cmds_CXX=3D'$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$sonam=
e -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flag=
s'
-	      ;;
-	    ia64*)
-	      archive_cmds_CXX=3D'$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$sonam=
e ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_o=
bjects $compiler_flags'
-	      ;;
-	    *)
-	      archive_cmds_CXX=3D'$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$sonam=
e ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $p=
ostdep_objects $compiler_flags'
-	      ;;
-	    esac
-	  fi
-	else
-	  # FIXME: insert proper C++ library support
-	  ld_shlibs_CXX=3Dno
-	fi
-	;;
-    esac
-    ;;
-  interix3*)
-    hardcode_direct_CXX=3Dno
-    hardcode_shlibpath_var_CXX=3Dno
-    hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath,$libdir'
-    export_dynamic_flag_spec_CXX=3D'${wl}-E'
-    # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc.
-    # Instead, shared libraries are loaded at an image base (0x10000000 by
-    # default) and relocated if they conflict, which is a slow very memory
-    # consuming and fragmenting process.  To avoid this, we pick a random,
-    # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link
-    # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-    archive_cmds_CXX=3D'$CC -shared $pic_flag $libobjs $deplibs $compiler_=
flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 26=
2144 + 1342177280` -o $lib'
-    archive_expsym_cmds_CXX=3D'sed "s,^,_," $export_symbols >$output_objdi=
r/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${=
wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl=
}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib'
-    ;;
-  irix5* | irix6*)
-    case $cc_basename in
-      CC*)
-	# SGI C++
-	archive_cmds_CXX=3D'$CC -shared -all -multigot $predep_objects $libobjs $=
deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstri=
ng" && echo -set_version $verstring` -update_registry ${output_objdir}/so_l=
ocations -o $lib'
-
-	# Archives containing C++ object files must be created using
-	# "CC -ar", where "CC" is the IRIX C++ compiler.  This is
-	# necessary to make sure instantiated templates are included
-	# in the archive.
-	old_archive_cmds_CXX=3D'$CC -ar -WR,-u -o $oldlib $oldobjs'
-	;;
-      *)
-	if test "$GXX" =3D yes; then
-	  if test "$with_gnu_ld" =3D no; then
-	    archive_cmds_CXX=3D'$CC -shared -nostdlib $predep_objects $libobjs $d=
eplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n =
"$verstring" && echo ${wl}-set_version ${wl}$verstring` ${wl}-update_regist=
ry ${wl}${output_objdir}/so_locations -o $lib'
-	  else
-	    archive_cmds_CXX=3D'$CC -shared -nostdlib $predep_objects $libobjs $d=
eplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n =
"$verstring" && echo ${wl}-set_version ${wl}$verstring` -o $lib'
-	  fi
-	fi
-	link_all_deplibs_CXX=3Dyes
-	;;
-    esac
-    hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath ${wl}$libdir'
-    hardcode_libdir_separator_CXX=3D:
-    ;;
-  linux*)
-    case $cc_basename in
-      KCC*)
-	# Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	# KCC will only create a shared library if the output file
-	# ends with ".so" (or ".sl" for HP-UX), so rename the library
-	# to its proper name (with version) after linking.
-	archive_cmds_CXX=3D'tempext=3D`echo $shared_ext | $SED -e '\''s/\([^()0-9=
A-Za-z{}]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $SED -e "s/\${tempext}\..=
*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_=
flags --soname $soname -o \$templib; mv \$templib $lib'
-	archive_expsym_cmds_CXX=3D'tempext=3D`echo $shared_ext | $SED -e '\''s/\(=
[^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $SED -e "s/\${temp=
ext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $co=
mpiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$expor=
t_symbols; mv \$templib $lib'
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC $CFLAGS -v conftest.$objext -o=
 libconftest$shared_ext 2>&1 | grep "ld"`; rm -f libconftest$shared_ext; li=
st=3D""; for z in $templist; do case $z in conftest.$objext) list=3D"$list =
$z";; *.$objext);; *) list=3D"$list $z";;esac; done; echo $list'
-
-	hardcode_libdir_flag_spec_CXX=3D'${wl}--rpath,$libdir'
-	export_dynamic_flag_spec_CXX=3D'${wl}--export-dynamic'
-
-	# Archives containing C++ object files must be created using
-	# "CC -Bstatic", where "CC" is the KAI C++ compiler.
-	old_archive_cmds_CXX=3D'$CC -Bstatic -o $oldlib $oldobjs'
-	;;
-      icpc*)
-	# Intel C++
-	with_gnu_ld=3Dyes
-	# version 8.0 and above of icpc choke on multiply defined symbols
-	# if we add $predep_objects and $postdep_objects, however 7.1 and
-	# earlier do not add the objects themselves.
-	case `$CC -V 2>&1` in
-	*"Version 7."*)
-  	  archive_cmds_CXX=3D'$CC -shared $predep_objects $libobjs $deplibs $po=
stdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-  	  archive_expsym_cmds_CXX=3D'$CC -shared $predep_objects $libobjs $depl=
ibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-s=
ymbols-file $wl$export_symbols -o $lib'
-	  ;;
-	*)  # Version 8.0 or newer
-	  tmp_idyn=3D
-	  case $host_cpu in
-	    ia64*) tmp_idyn=3D' -i_dynamic';;
-	  esac
-  	  archive_cmds_CXX=3D'$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compi=
ler_flags ${wl}-soname $wl$soname -o $lib'
-	  archive_expsym_cmds_CXX=3D'$CC -shared'"$tmp_idyn"' $libobjs $deplibs $=
compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export=
_symbols -o $lib'
-	  ;;
-	esac
-	archive_cmds_need_lc_CXX=3Dno
-	hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath,$libdir'
-	export_dynamic_flag_spec_CXX=3D'${wl}--export-dynamic'
-	whole_archive_flag_spec_CXX=3D'${wl}--whole-archive$convenience ${wl}--no=
-whole-archive'
-	;;
-      pgCC*)
-        # Portland Group C++ compiler
-	archive_cmds_CXX=3D'$CC -shared $pic_flag $predep_objects $libobjs $depli=
bs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib'
-  	archive_expsym_cmds_CXX=3D'$CC -shared $pic_flag $predep_objects $libob=
js $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl=
}-retain-symbols-file ${wl}$export_symbols -o $lib'
-
-	hardcode_libdir_flag_spec_CXX=3D'${wl}--rpath ${wl}$libdir'
-	export_dynamic_flag_spec_CXX=3D'${wl}--export-dynamic'
-	whole_archive_flag_spec_CXX=3D'${wl}--whole-archive`for conv in $convenie=
nce\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$con=
v\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-        ;;
-      cxx*)
-	# Compaq C++
-	archive_cmds_CXX=3D'$CC -shared $predep_objects $libobjs $deplibs $postde=
p_objects $compiler_flags ${wl}-soname $wl$soname -o $lib'
-	archive_expsym_cmds_CXX=3D'$CC -shared $predep_objects $libobjs $deplibs =
$postdep_objects $compiler_flags ${wl}-soname $wl$soname  -o $lib ${wl}-ret=
ain-symbols-file $wl$export_symbols'
-
-	runpath_var=3DLD_RUN_PATH
-	hardcode_libdir_flag_spec_CXX=3D'-rpath $libdir'
-	hardcode_libdir_separator_CXX=3D:
-
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC -shared $CFLAGS -v conftest.$o=
bjext 2>&1 | grep "ld"`; templist=3D`echo $templist | $SED "s/\(^.*ld.*\)\(=
 .*ld .*$\)/\1/"`; list=3D""; for z in $templist; do case $z in conftest.$o=
bjext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z";;esac; done; e=
cho $list'
-	;;
-    esac
-    ;;
-  lynxos*)
-    # FIXME: insert proper C++ library support
-    ld_shlibs_CXX=3Dno
-    ;;
-  m88k*)
-    # FIXME: insert proper C++ library support
-    ld_shlibs_CXX=3Dno
-    ;;
-  mvs*)
-    case $cc_basename in
-      cxx*)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-    esac
-    ;;
-  netbsd*)
-    if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-      archive_cmds_CXX=3D'$LD -Bshareable  -o $lib $predep_objects $libobj=
s $deplibs $postdep_objects $linker_flags'
-      wlarc=3D
-      hardcode_libdir_flag_spec_CXX=3D'-R$libdir'
-      hardcode_direct_CXX=3Dyes
-      hardcode_shlibpath_var_CXX=3Dno
-    fi
-    # Workaround some broken pre-1.5 toolchains
-    output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&=
1 | grep conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"'
-    ;;
-  openbsd2*)
-    # C++ shared libraries are fairly broken
-    ld_shlibs_CXX=3Dno
-    ;;
-  openbsd*)
-    hardcode_direct_CXX=3Dyes
-    hardcode_shlibpath_var_CXX=3Dno
-    archive_cmds_CXX=3D'$CC -shared $pic_flag $predep_objects $libobjs $de=
plibs $postdep_objects $compiler_flags -o $lib'
-    hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath,$libdir'
-    if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_o=
s-$host_cpu" =3D "openbsd2.8-powerpc"; then
-      archive_expsym_cmds_CXX=3D'$CC -shared $pic_flag $predep_objects $li=
bobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$=
export_symbols -o $lib'
-      export_dynamic_flag_spec_CXX=3D'${wl}-E'
-      whole_archive_flag_spec_CXX=3D"$wlarc"'--whole-archive$convenience '=
"$wlarc"'--no-whole-archive'
-    fi
-    output_verbose_link_cmd=3D'echo'
-    ;;
-  osf3*)
-    case $cc_basename in
-      KCC*)
-	# Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	# KCC will only create a shared library if the output file
-	# ends with ".so" (or ".sl" for HP-UX), so rename the library
-	# to its proper name (with version) after linking.
-	archive_cmds_CXX=3D'tempext=3D`echo $shared_ext | $SED -e '\''s/\([^()0-9=
A-Za-z{}]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $SED -e "s/\${tempext}\..=
*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_=
flags --soname $soname -o \$templib; mv \$templib $lib'
-
-	hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath,$libdir'
-	hardcode_libdir_separator_CXX=3D:
-
-	# Archives containing C++ object files must be created using
-	# "CC -Bstatic", where "CC" is the KAI C++ compiler.
-	old_archive_cmds_CXX=3D'$CC -Bstatic -o $oldlib $oldobjs'
-
-	;;
-      RCC*)
-	# Rational C++ 2.4.1
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      cxx*)
-	allow_undefined_flag_CXX=3D' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_CXX=3D'$CC -shared${allow_undefined_flag} $predep_objects $l=
ibobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test=
 -n "$verstring" && echo ${wl}-set_version $verstring` -update_registry ${o=
utput_objdir}/so_locations -o $lib'
-
-	hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath ${wl}$libdir'
-	hardcode_libdir_separator_CXX=3D:
-
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC -shared $CFLAGS -v conftest.$o=
bjext 2>&1 | grep "ld" | grep -v "ld:"`; templist=3D`echo $templist | $SED =
"s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=3D""; for z in $templist; do case $z=
 in conftest.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z"=
;;esac; done; echo $list'
-	;;
-      *)
-	if test "$GXX" =3D yes && test "$with_gnu_ld" =3D no; then
-	  allow_undefined_flag_CXX=3D' ${wl}-expect_unresolved ${wl}\*'
-	  archive_cmds_CXX=3D'$CC -shared -nostdlib ${allow_undefined_flag} $pred=
ep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname =
${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$verstrin=
g` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-
-	  hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath ${wl}$libdir'
-	  hardcode_libdir_separator_CXX=3D:
-
-	  # Commands to make compiler produce verbose output that lists
-	  # what "hidden" libraries, object files and flags are used when
-	  # linking a shared library.
-	  output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&1=
 | grep "\-L"'
-
-	else
-	  # FIXME: insert proper C++ library support
-	  ld_shlibs_CXX=3Dno
-	fi
-	;;
-    esac
-    ;;
-  osf4* | osf5*)
-    case $cc_basename in
-      KCC*)
-	# Kuck and Associates, Inc. (KAI) C++ Compiler
-
-	# KCC will only create a shared library if the output file
-	# ends with ".so" (or ".sl" for HP-UX), so rename the library
-	# to its proper name (with version) after linking.
-	archive_cmds_CXX=3D'tempext=3D`echo $shared_ext | $SED -e '\''s/\([^()0-9=
A-Za-z{}]\)/\\\\\1/g'\''`; templib=3D`echo $lib | $SED -e "s/\${tempext}\..=
*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_=
flags --soname $soname -o \$templib; mv \$templib $lib'
-
-	hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath,$libdir'
-	hardcode_libdir_separator_CXX=3D:
-
-	# Archives containing C++ object files must be created using
-	# the KAI C++ compiler.
-	old_archive_cmds_CXX=3D'$CC -o $oldlib $oldobjs'
-	;;
-      RCC*)
-	# Rational C++ 2.4.1
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      cxx*)
-	allow_undefined_flag_CXX=3D' -expect_unresolved \*'
-	archive_cmds_CXX=3D'$CC -shared${allow_undefined_flag} $predep_objects $l=
ibobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `tes=
t -n "$verstring" && echo -set_version $verstring` -update_registry ${outpu=
t_objdir}/so_locations -o $lib'
-	archive_expsym_cmds_CXX=3D'for i in `cat $export_symbols`; do printf "%s =
%s\\n" -exported_symbol "\$i" >> $lib.exp; done~
-	  echo "-hidden">> $lib.exp~
-	  $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $pos=
tdep_objects $compiler_flags -msym -soname $soname -Wl,-input -Wl,$lib.exp =
 `test -n "$verstring" && echo -set_version	$verstring` -update_registry ${=
output_objdir}/so_locations -o $lib~
-	  $rm $lib.exp'
-
-	hardcode_libdir_flag_spec_CXX=3D'-rpath $libdir'
-	hardcode_libdir_separator_CXX=3D:
-
-	# Commands to make compiler produce verbose output that lists
-	# what "hidden" libraries, object files and flags are used when
-	# linking a shared library.
-	#
-	# There doesn't appear to be a way to prevent this compiler from
-	# explicitly linking system object files so we need to strip them
-	# from the output so that they don't get included in the library
-	# dependencies.
-	output_verbose_link_cmd=3D'templist=3D`$CC -shared $CFLAGS -v conftest.$o=
bjext 2>&1 | grep "ld" | grep -v "ld:"`; templist=3D`echo $templist | $SED =
"s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=3D""; for z in $templist; do case $z=
 in conftest.$objext) list=3D"$list $z";; *.$objext);; *) list=3D"$list $z"=
;;esac; done; echo $list'
-	;;
-      *)
-	if test "$GXX" =3D yes && test "$with_gnu_ld" =3D no; then
-	  allow_undefined_flag_CXX=3D' ${wl}-expect_unresolved ${wl}\*'
-	 archive_cmds_CXX=3D'$CC -shared -nostdlib ${allow_undefined_flag} $prede=
p_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${w=
l}-soname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl=
}$verstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $l=
ib'
-
-	  hardcode_libdir_flag_spec_CXX=3D'${wl}-rpath ${wl}$libdir'
-	  hardcode_libdir_separator_CXX=3D:
-
-	  # Commands to make compiler produce verbose output that lists
-	  # what "hidden" libraries, object files and flags are used when
-	  # linking a shared library.
-	  output_verbose_link_cmd=3D'$CC -shared $CFLAGS -v conftest.$objext 2>&1=
 | grep "\-L"'
-
-	else
-	  # FIXME: insert proper C++ library support
-	  ld_shlibs_CXX=3Dno
-	fi
-	;;
-    esac
-    ;;
-  psos*)
-    # FIXME: insert proper C++ library support
-    ld_shlibs_CXX=3Dno
-    ;;
-  sunos4*)
-    case $cc_basename in
-      CC*)
-	# Sun C++ 4.x
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      lcc*)
-	# Lucid
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-    esac
-    ;;
-  solaris*)
-    case $cc_basename in
-      CC*)
-	# Sun C++ 4.2, 5.x and Centerline C++
-        archive_cmds_need_lc_CXX=3Dyes
-	no_undefined_flag_CXX=3D' -zdefs'
-	archive_cmds_CXX=3D'$CC -G${allow_undefined_flag}  -h$soname -o $lib $pre=
dep_objects $libobjs $deplibs $postdep_objects $compiler_flags'
-	archive_expsym_cmds_CXX=3D'$echo "{ global:" > $lib.exp~cat $export_symbo=
ls | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-	$CC -G${allow_undefined_flag}  ${wl}-M ${wl}$lib.exp -h$soname -o $lib $p=
redep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$rm $lib.e=
xp'
-
-	hardcode_libdir_flag_spec_CXX=3D'-R$libdir'
-	hardcode_shlibpath_var_CXX=3Dno
-	case $host_os in
-	  solaris2.[0-5] | solaris2.[0-5].*) ;;
-	  *)
-	    # The C++ compiler is used as linker so we must use $wl
-	    # flag to pass the commands to the underlying system
-	    # linker. We must also pass each convience library through
-	    # to the system linker between allextract/defaultextract.
-	    # The C++ compiler will combine linker options so we
-	    # cannot just pass the convience library names through
-	    # without $wl.
-	    # Supported since Solaris 2.6 (maybe 2.5.1?)
-	    whole_archive_flag_spec_CXX=3D'${wl}-z ${wl}allextract`for conv in $c=
onvenience\"\"; do test -n \"$conv\" && new_convenience=3D\"$new_convenienc=
e,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract'
-	    ;;
-	esac
-	link_all_deplibs_CXX=3Dyes
-
-	output_verbose_link_cmd=3D'echo'
-
-	# Archives containing C++ object files must be created using
-	# "CC -xar", where "CC" is the Sun C++ compiler.  This is
-	# necessary to make sure instantiated templates are included
-	# in the archive.
-	old_archive_cmds_CXX=3D'$CC -xar -o $oldlib $oldobjs'
-	;;
-      gcx*)
-	# Green Hills C++ Compiler
-	archive_cmds_CXX=3D'$CC -shared $predep_objects $libobjs $deplibs $postde=
p_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-
-	# The C++ compiler must be used to create the archive.
-	old_archive_cmds_CXX=3D'$CC $LDFLAGS -archive -o $oldlib $oldobjs'
-	;;
-      *)
-	# GNU C++ compiler with Solaris linker
-	if test "$GXX" =3D yes && test "$with_gnu_ld" =3D no; then
-	  no_undefined_flag_CXX=3D' ${wl}-z ${wl}defs'
-	  if $CC --version | grep -v '^2\.7' > /dev/null; then
-	    archive_cmds_CXX=3D'$CC -shared -nostdlib $LDFLAGS $predep_objects $l=
ibobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-	    archive_expsym_cmds_CXX=3D'$echo "{ global:" > $lib.exp~cat $export_s=
ymbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.e=
xp~
-		$CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libob=
js $deplibs $postdep_objects $compiler_flags~$rm $lib.exp'
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    output_verbose_link_cmd=3D"$CC -shared $CFLAGS -v conftest.$objext 2>=
&1 | grep \"\-L\""
-	  else
-	    # g++ 2.7 appears to require `-G' NOT `-shared' on this
-	    # platform.
-	    archive_cmds_CXX=3D'$CC -G -nostdlib $LDFLAGS $predep_objects $libobj=
s $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib'
-	    archive_expsym_cmds_CXX=3D'$echo "{ global:" > $lib.exp~cat $export_s=
ymbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.e=
xp~
-		$CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $d=
eplibs $postdep_objects $compiler_flags~$rm $lib.exp'
-
-	    # Commands to make compiler produce verbose output that lists
-	    # what "hidden" libraries, object files and flags are used when
-	    # linking a shared library.
-	    output_verbose_link_cmd=3D"$CC -G $CFLAGS -v conftest.$objext 2>&1 | =
grep \"\-L\""
-	  fi
-
-	  hardcode_libdir_flag_spec_CXX=3D'${wl}-R $wl$libdir'
-	fi
-	;;
-    esac
-    ;;
-  sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | s=
co3.2v5.0.[024]*)
-    no_undefined_flag_CXX=3D'${wl}-z,text'
-    archive_cmds_need_lc_CXX=3Dno
-    hardcode_shlibpath_var_CXX=3Dno
-    runpath_var=3D'LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	archive_cmds_CXX=3D'$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $com=
piler_flags'
-	archive_expsym_cmds_CXX=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$=
soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-      *)
-	archive_cmds_CXX=3D'$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs=
 $compiler_flags'
-	archive_expsym_cmds_CXX=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl=
}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-	;;
-    esac
-    ;;
-  sysv5* | sco3.2v5* | sco5v6*)
-    # Note: We can NOT use -z defs as we might desire, because we do not
-    # link with -lc, and that would cause any symbols used from libc to
-    # always be unresolved, which means just about no library would
-    # ever link correctly.  If we're not using GNU ld we use -z text
-    # though, which does catch some bad symbols but isn't as heavy-handed
-    # as -z defs.
-    # For security reasons, it is highly recommended that you always
-    # use absolute paths for naming shared libraries, and exclude the
-    # DT_RUNPATH tag from executables and libraries.  But doing so
-    # requires that you compile everything twice, which is a pain.
-    # So that behaviour is only enabled if SCOABSPATH is set to a
-    # non-empty value in the environment.  Most likely only useful for
-    # creating official distributions of packages.
-    # This is a hack until libtool officially supports absolute path
-    # names for shared libraries.
-    no_undefined_flag_CXX=3D'${wl}-z,text'
-    allow_undefined_flag_CXX=3D'${wl}-z,nodefs'
-    archive_cmds_need_lc_CXX=3Dno
-    hardcode_shlibpath_var_CXX=3Dno
-    hardcode_libdir_flag_spec_CXX=3D'`test -z "$SCOABSPATH" && echo ${wl}-=
R,$libdir`'
-    hardcode_libdir_separator_CXX=3D':'
-    link_all_deplibs_CXX=3Dyes
-    export_dynamic_flag_spec_CXX=3D'${wl}-Bexport'
-    runpath_var=3D'LD_RUN_PATH'
-
-    case $cc_basename in
-      CC*)
-	archive_cmds_CXX=3D'$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$son=
ame -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_CXX=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\=
${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compile=
r_flags'
-	;;
-      *)
-	archive_cmds_CXX=3D'$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/=
}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_CXX=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl=
}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $co=
mpiler_flags'
-	;;
-    esac
-    ;;
-  tandem*)
-    case $cc_basename in
-      NCC*)
-	# NonStop-UX NCC 3.20
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-      *)
-	# FIXME: insert proper C++ library support
-	ld_shlibs_CXX=3Dno
-	;;
-    esac
-    ;;
-  vxworks*)
-    # FIXME: insert proper C++ library support
-    ld_shlibs_CXX=3Dno
-    ;;
-  *)
-    # FIXME: insert proper C++ library support
-    ld_shlibs_CXX=3Dno
-    ;;
-esac
-{ echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
-echo "${ECHO_T}$ld_shlibs_CXX" >&6; }
-test "$ld_shlibs_CXX" =3D no && can_build_shared=3Dno
-
-GCC_CXX=3D"$GXX"
-LD_CXX=3D"$LD"
-
-
-cat > conftest.$ac_ext <<EOF
-class Foo
-{
-public:
-  Foo (void) { a =3D 0; }
-private:
-  int a;
-};
-EOF
-
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; then
-  # Parse the compiler output and extract the necessary
-  # objects, libraries and library flags.
-
-  # Sentinel used to keep track of whether or not we are before
-  # the conftest object file.
-  pre_test_object_deps_done=3Dno
-
-  # The `*' in the case matches for architectures that use `case' in
-  # $output_verbose_cmd can trigger glob expansion during the loop
-  # eval without this substitution.
-  output_verbose_link_cmd=3D`$echo "X$output_verbose_link_cmd" | $Xsed -e =
"$no_glob_subst"`
-
-  for p in `eval $output_verbose_link_cmd`; do
-    case $p in
-
-    -L* | -R* | -l*)
-       # Some compilers place space between "-{L,R}" and the path.
-       # Remove the space.
-       if test $p =3D "-L" \
-	  || test $p =3D "-R"; then
-	 prev=3D$p
-	 continue
-       else
-	 prev=3D
-       fi
-
-       if test "$pre_test_object_deps_done" =3D no; then
-	 case $p in
-	 -L* | -R*)
-	   # Internal compiler library paths should come after those
-	   # provided the user.  The postdeps already come after the
-	   # user supplied libs so there is no need to process them.
-	   if test -z "$compiler_lib_search_path_CXX"; then
-	     compiler_lib_search_path_CXX=3D"${prev}${p}"
-	   else
-	     compiler_lib_search_path_CXX=3D"${compiler_lib_search_path_CXX} ${pr=
ev}${p}"
-	   fi
-	   ;;
-	 # The "-l" case would never come before the object being
-	 # linked, so don't bother handling this case.
-	 esac
-       else
-	 if test -z "$postdeps_CXX"; then
-	   postdeps_CXX=3D"${prev}${p}"
-	 else
-	   postdeps_CXX=3D"${postdeps_CXX} ${prev}${p}"
-	 fi
-       fi
-       ;;
-
-    *.$objext)
-       # This assumes that the test object file only shows up
-       # once in the compiler output.
-       if test "$p" =3D "conftest.$objext"; then
-	 pre_test_object_deps_done=3Dyes
-	 continue
-       fi
-
-       if test "$pre_test_object_deps_done" =3D no; then
-	 if test -z "$predep_objects_CXX"; then
-	   predep_objects_CXX=3D"$p"
-	 else
-	   predep_objects_CXX=3D"$predep_objects_CXX $p"
-	 fi
-       else
-	 if test -z "$postdep_objects_CXX"; then
-	   postdep_objects_CXX=3D"$p"
-	 else
-	   postdep_objects_CXX=3D"$postdep_objects_CXX $p"
-	 fi
-       fi
-       ;;
-
-    *) ;; # Ignore the rest.
-
-    esac
-  done
-
-  # Clean up.
-  rm -f a.out a.exe
-else
-  echo "libtool.m4: error: problem compiling CXX test program"
-fi
-
-$rm -f confest.$objext
-
-# PORTME: override above test on systems where it is broken
-case $host_os in
-interix3*)
-  # Interix 3.5 installs completely hosed .la files for C++, so rather than
-  # hack all around it, let's just trust "g++" to DTRT.
-  predep_objects_CXX=3D
-  postdep_objects_CXX=3D
-  postdeps_CXX=3D
-  ;;
-
-solaris*)
-  case $cc_basename in
-  CC*)
-    # Adding this requires a known-good setup of shared libraries for
-    # Sun compiler versions before 5.6, else PIC objects from an old
-    # archive will be linked into the output, leading to subtle bugs.
-    postdeps_CXX=3D'-lCstd -lCrun'
-    ;;
-  esac
-  ;;
-esac
-
-
-case " $postdeps_CXX " in
-*" -lc "*) archive_cmds_need_lc_CXX=3Dno ;;
-esac
-
-lt_prog_compiler_wl_CXX=3D
-lt_prog_compiler_pic_CXX=3D
-lt_prog_compiler_static_CXX=3D
-
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6=
; }
-
-  # C++ specific cases for pic, static, wl, etc.
-  if test "$GXX" =3D yes; then
-    lt_prog_compiler_wl_CXX=3D'-Wl,'
-    lt_prog_compiler_static_CXX=3D'-static'
-
-    case $host_os in
-    aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static_CXX=3D'-Bstatic'
-      fi
-      ;;
-    amigaos*)
-      # FIXME: we need at least 68020 code to build shared libraries, but
-      # adding the `-m68020' flag to GCC prevents building anything better,
-      # like `-m68040'.
-      lt_prog_compiler_pic_CXX=3D'-m68020 -resident32 -malways-restore-a4'
-      ;;
-    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-    mingw* | os2* | pw32*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      lt_prog_compiler_pic_CXX=3D'-DDLL_EXPORT'
-      ;;
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      lt_prog_compiler_pic_CXX=3D'-fno-common'
-      ;;
-    *djgpp*)
-      # DJGPP does not support shared libraries at all
-      lt_prog_compiler_pic_CXX=3D
-      ;;
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	lt_prog_compiler_pic_CXX=3D-Kconform_pic
-      fi
-      ;;
-    hpux*)
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	;;
-      *)
-	lt_prog_compiler_pic_CXX=3D'-fPIC'
-	;;
-      esac
-      ;;
-    *)
-      lt_prog_compiler_pic_CXX=3D'-fPIC'
-      ;;
-    esac
-  else
-    case $host_os in
-      aix4* | aix5*)
-	# All AIX code is PIC.
-	if test "$host_cpu" =3D ia64; then
-	  # AIX 5 now supports IA64 processor
-	  lt_prog_compiler_static_CXX=3D'-Bstatic'
-	else
-	  lt_prog_compiler_static_CXX=3D'-bnso -bI:/lib/syscalls.exp'
-	fi
-	;;
-      chorus*)
-	case $cc_basename in
-	cxch68*)
-	  # Green Hills C++ Compiler
-	  # _LT_AC_TAGVAR(lt_prog_compiler_static, CXX)=3D"--no_auto_instantiatio=
n -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/=
CC/libC.a $MVME_DIR/lib/classix/libcx.s.a"
-	  ;;
-	esac
-	;;
-       darwin*)
-         # PIC is the default on this platform
-         # Common symbols not allowed in MH_DYLIB files
-         case $cc_basename in
-           xlc*)
-           lt_prog_compiler_pic_CXX=3D'-qnocommon'
-           lt_prog_compiler_wl_CXX=3D'-Wl,'
-           ;;
-         esac
-       ;;
-      dgux*)
-	case $cc_basename in
-	  ec++*)
-	    lt_prog_compiler_pic_CXX=3D'-KPIC'
-	    ;;
-	  ghcx*)
-	    # Green Hills C++ Compiler
-	    lt_prog_compiler_pic_CXX=3D'-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      freebsd* | kfreebsd*-gnu | dragonfly*)
-	# FreeBSD uses GNU C++
-	;;
-      hpux9* | hpux10* | hpux11*)
-	case $cc_basename in
-	  CC*)
-	    lt_prog_compiler_wl_CXX=3D'-Wl,'
-	    lt_prog_compiler_static_CXX=3D'${wl}-a ${wl}archive'
-	    if test "$host_cpu" !=3D ia64; then
-	      lt_prog_compiler_pic_CXX=3D'+Z'
-	    fi
-	    ;;
-	  aCC*)
-	    lt_prog_compiler_wl_CXX=3D'-Wl,'
-	    lt_prog_compiler_static_CXX=3D'${wl}-a ${wl}archive'
-	    case $host_cpu in
-	    hppa*64*|ia64*)
-	      # +Z the default
-	      ;;
-	    *)
-	      lt_prog_compiler_pic_CXX=3D'+Z'
-	      ;;
-	    esac
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      interix*)
-	# This is c89, which is MS Visual C++ (no shared libs)
-	# Anyone wants to do a port?
-	;;
-      irix5* | irix6* | nonstopux*)
-	case $cc_basename in
-	  CC*)
-	    lt_prog_compiler_wl_CXX=3D'-Wl,'
-	    lt_prog_compiler_static_CXX=3D'-non_shared'
-	    # CC pic flag -KPIC is the default.
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      linux*)
-	case $cc_basename in
-	  KCC*)
-	    # KAI C++ Compiler
-	    lt_prog_compiler_wl_CXX=3D'--backend -Wl,'
-	    lt_prog_compiler_pic_CXX=3D'-fPIC'
-	    ;;
-	  icpc* | ecpc*)
-	    # Intel C++
-	    lt_prog_compiler_wl_CXX=3D'-Wl,'
-	    lt_prog_compiler_pic_CXX=3D'-KPIC'
-	    lt_prog_compiler_static_CXX=3D'-static'
-	    ;;
-	  pgCC*)
-	    # Portland Group C++ compiler.
-	    lt_prog_compiler_wl_CXX=3D'-Wl,'
-	    lt_prog_compiler_pic_CXX=3D'-fpic'
-	    lt_prog_compiler_static_CXX=3D'-Bstatic'
-	    ;;
-	  cxx*)
-	    # Compaq C++
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    lt_prog_compiler_pic_CXX=3D
-	    lt_prog_compiler_static_CXX=3D'-non_shared'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      lynxos*)
-	;;
-      m88k*)
-	;;
-      mvs*)
-	case $cc_basename in
-	  cxx*)
-	    lt_prog_compiler_pic_CXX=3D'-W c,exportall'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      netbsd*)
-	;;
-      osf3* | osf4* | osf5*)
-	case $cc_basename in
-	  KCC*)
-	    lt_prog_compiler_wl_CXX=3D'--backend -Wl,'
-	    ;;
-	  RCC*)
-	    # Rational C++ 2.4.1
-	    lt_prog_compiler_pic_CXX=3D'-pic'
-	    ;;
-	  cxx*)
-	    # Digital/Compaq C++
-	    lt_prog_compiler_wl_CXX=3D'-Wl,'
-	    # Make sure the PIC flag is empty.  It appears that all Alpha
-	    # Linux and Compaq Tru64 Unix objects are PIC.
-	    lt_prog_compiler_pic_CXX=3D
-	    lt_prog_compiler_static_CXX=3D'-non_shared'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      psos*)
-	;;
-      solaris*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.2, 5.x and Centerline C++
-	    lt_prog_compiler_pic_CXX=3D'-KPIC'
-	    lt_prog_compiler_static_CXX=3D'-Bstatic'
-	    lt_prog_compiler_wl_CXX=3D'-Qoption ld '
-	    ;;
-	  gcx*)
-	    # Green Hills C++ Compiler
-	    lt_prog_compiler_pic_CXX=3D'-PIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sunos4*)
-	case $cc_basename in
-	  CC*)
-	    # Sun C++ 4.x
-	    lt_prog_compiler_pic_CXX=3D'-pic'
-	    lt_prog_compiler_static_CXX=3D'-Bstatic'
-	    ;;
-	  lcc*)
-	    # Lucid
-	    lt_prog_compiler_pic_CXX=3D'-pic'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      tandem*)
-	case $cc_basename in
-	  NCC*)
-	    # NonStop-UX NCC 3.20
-	    lt_prog_compiler_pic_CXX=3D'-KPIC'
-	    ;;
-	  *)
-	    ;;
-	esac
-	;;
-      sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-	case $cc_basename in
-	  CC*)
-	    lt_prog_compiler_wl_CXX=3D'-Wl,'
-	    lt_prog_compiler_pic_CXX=3D'-KPIC'
-	    lt_prog_compiler_static_CXX=3D'-Bstatic'
-	    ;;
-	esac
-	;;
-      vxworks*)
-	;;
-      *)
-	lt_prog_compiler_can_build_shared_CXX=3Dno
-	;;
-    esac
-  fi
-
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_CXX" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_CXX" >&6; }
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$lt_prog_compiler_pic_CXX"; then
-
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_p=
ic_CXX works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX wor=
ks... $ECHO_C" >&6; }
-if test "${lt_prog_compiler_pic_works_CXX+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_pic_works_CXX=3Dno
-  ac_outfile=3Dconftest.$ac_objext
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag=3D"$lt_prog_compiler_pic_CXX -DPIC"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:13188: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=3D$?
-   cat conftest.err >&5
-   echo "$as_me:13192: \$? =3D $ac_status" >&5
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/nul=
l; then
-       lt_prog_compiler_pic_works_CXX=3Dyes
-     fi
-   fi
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_CXX" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works_CXX" >&6; }
-
-if test x"$lt_prog_compiler_pic_works_CXX" =3D xyes; then
-    case $lt_prog_compiler_pic_CXX in
-     "" | " "*) ;;
-     *) lt_prog_compiler_pic_CXX=3D" $lt_prog_compiler_pic_CXX" ;;
-     esac
-else
-    lt_prog_compiler_pic_CXX=3D
-     lt_prog_compiler_can_build_shared_CXX=3Dno
-fi
-
-fi
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    lt_prog_compiler_pic_CXX=3D
-    ;;
-  *)
-    lt_prog_compiler_pic_CXX=3D"$lt_prog_compiler_pic_CXX -DPIC"
-    ;;
-esac
-
-#
-# Check to make sure the static flag actually works.
-#
-wl=3D$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=3D\"$lt_prog_compile=
r_static_CXX\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_f=
lag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works.=
.. $ECHO_C" >&6; }
-if test "${lt_prog_compiler_static_works_CXX+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works_CXX=3Dno
-   save_LDFLAGS=3D"$LDFLAGS"
-   LDFLAGS=3D"$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works_CXX=3Dyes
-       fi
-     else
-       lt_prog_compiler_static_works_CXX=3Dyes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS=3D"$save_LDFLAGS"
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_CXX" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_CXX" >&6; }
-
-if test x"$lt_prog_compiler_static_works_CXX" =3D xyes; then
-    :
-else
-    lt_prog_compiler_static_CXX=3D
-fi
-
-
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_obje=
xt" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECH=
O_C" >&6; }
-if test "${lt_cv_prog_compiler_c_o_CXX+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_cv_prog_compiler_c_o_CXX=3Dno
-   $rm -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag=3D"-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:13292: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=3D$?
-   cat out/conftest.err >&5
-   echo "$as_me:13296: \$? =3D $ac_status" >&5
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.=
exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.e=
r2 >/dev/null; then
-       lt_cv_prog_compiler_c_o_CXX=3Dyes
-     fi
-   fi
-   chmod u+w . 2>&5
-   $rm conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
-   $rm out/* && rmdir out
-   cd ..
-   rmdir conftest
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_CXX" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o_CXX" >&6; }
-
-
-hard_links=3D"nottested"
-if test "$lt_cv_prog_compiler_c_o_CXX" =3D no && test "$need_locks" !=3D n=
o; then
-  # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
-  hard_links=3Dyes
-  $rm conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=3Dno
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
-  if test "$hard_links" =3D no; then
-    { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so =
\`make -j' may be unsafe" >&5
-echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may=
 be unsafe" >&2;}
-    need_locks=3Dwarn
-  fi
-else
-  need_locks=3Dno
-fi
-
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) suppor=
ts shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared =
libraries... $ECHO_C" >&6; }
-
-  export_symbols_cmds_CXX=3D'$NM $libobjs $convenience | $global_symbol_pi=
pe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  case $host_os in
-  aix4* | aix5*)
-    # If we're using GNU nm, then we don't want the "-C" option.
-    # -C means demangle to AIX nm, but means don't demangle with GNU nm
-    if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
-      export_symbols_cmds_CXX=3D'$NM -Bpg $libobjs $convenience | awk '\''=
{ if (((\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (substr=
(\$3,1,1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-    else
-      export_symbols_cmds_CXX=3D'$NM -BCpg $libobjs $convenience | awk '\'=
'{ if (((\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (subst=
r(\$3,1,1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-    fi
-    ;;
-  pw32*)
-    export_symbols_cmds_CXX=3D"$ltdll_cmds"
-  ;;
-  cygwin* | mingw*)
-    export_symbols_cmds_CXX=3D'$NM $libobjs $convenience | $global_symbol_=
pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/;/^.* __nm__/s/^.* __=
nm__\([^ ]*\) [^ ]*/\1 DATA/;/^I /d;/^[AITW] /s/.* //'\'' | sort | uniq > $=
export_symbols'
-  ;;
-  *)
-    export_symbols_cmds_CXX=3D'$NM $libobjs $convenience | $global_symbol_=
pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  ;;
-  esac
-
-{ echo "$as_me:$LINENO: result: $ld_shlibs_CXX" >&5
-echo "${ECHO_T}$ld_shlibs_CXX" >&6; }
-test "$ld_shlibs_CXX" =3D no && can_build_shared=3Dno
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$archive_cmds_need_lc_CXX" in
-x|xyes)
-  # Assume -lc should be added
-  archive_cmds_need_lc_CXX=3Dyes
-
-  if test "$enable_shared" =3D yes && test "$GCC" =3D yes; then
-    case $archive_cmds_CXX in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly li=
nked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO=
_C" >&6; }
-      $rm conftest*
-      printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-      if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } 2>conftest.err; then
-        soname=3Dconftest
-        lib=3Dconftest
-        libobjs=3Dconftest.$ac_objext
-        deplibs=3D
-        wl=3D$lt_prog_compiler_wl_CXX
-	pic_flag=3D$lt_prog_compiler_pic_CXX
-        compiler_flags=3D-v
-        linker_flags=3D-v
-        verstring=3D
-        output_objdir=3D.
-        libname=3Dconftest
-        lt_save_allow_undefined_flag=3D$allow_undefined_flag_CXX
-        allow_undefined_flag_CXX=3D
-        if { (eval echo "$as_me:$LINENO: \"$archive_cmds_CXX 2\>\&1 \| gre=
p \" -lc \" \>/dev/null 2\>\&1\"") >&5
-  (eval $archive_cmds_CXX 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-        then
-	  archive_cmds_need_lc_CXX=3Dno
-        else
-	  archive_cmds_need_lc_CXX=3Dyes
-        fi
-        allow_undefined_flag_CXX=3D$lt_save_allow_undefined_flag
-      else
-        cat conftest.err 1>&5
-      fi
-      $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_CXX" >&5
-echo "${ECHO_T}$archive_cmds_need_lc_CXX" >&6; }
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
-library_names_spec=3D
-libname_spec=3D'lib$name'
-soname_spec=3D
-shrext_cmds=3D".so"
-postinstall_cmds=3D
-postuninstall_cmds=3D
-finish_cmds=3D
-finish_eval=3D
-shlibpath_var=3D
-shlibpath_overrides_runpath=3Dunknown
-version_type=3Dnone
-dynamic_linker=3D"$host_os ld.so"
-sys_lib_dlsearch_path_spec=3D"/lib /usr/lib"
-if test "$GCC" =3D yes; then
-  sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^libraries:" =
| $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-  if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that shou=
ld
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED -e=
 's/;/ /g'`
-  else
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED  -=
e "s/$PATH_SEPARATOR/ /g"`
-  fi
-else
-  sys_lib_search_path_spec=3D"/lib /usr/lib /usr/local/lib"
-fi
-need_lib_prefix=3Dunknown
-hardcode_into_libs=3Dno
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=3Dunknown
-
-case $host_os in
-aix3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $libna=
me.a'
-  shlibpath_var=3DLIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the n=
ame.
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  ;;
-
-aix4* | aix5*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  hardcode_into_libs=3Dyes
-  if test "$host_cpu" =3D ia64; then
-    # AIX 5 supports IA64
-    library_names_spec=3D'${libname}${release}${shared_ext}$major ${libnam=
e}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[01] | aix4.[01].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ =3D=3D 2 && __GNUC_MINOR__ =
>=3D 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
-	:
-      else
-	can_build_shared=3Dno
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not h=
ardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" =3D yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec=3D'${libname}${release}.a $libname.a'
-      soname_spec=3D'${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=3DLIBPATH
-  fi
-  ;;
-
-amigaos*)
-  library_names_spec=3D'$libname.ixlibrary $libname.a'
-  # Create ${libname}_ixlibrary.a entries in /sys/libs.
-  finish_eval=3D'for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libna=
me=3D`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; te=
st $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib =
${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a =
|| exit 1; done'
-  ;;
-
-beos*)
-  library_names_spec=3D'${libname}${shared_ext}'
-  dynamic_linker=3D"$host_os ld.so"
-  shlibpath_var=3DLIBRARY_PATH
-  ;;
-
-bsdi[45]*)
-  version_type=3Dlinux
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/shlib /usr/lib /usr/X11/lib /usr/contrib/li=
b /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec=3D"/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32*)
-  version_type=3Dwindows
-  shrext_cmds=3D".dll"
-  need_version=3Dno
-  need_lib_prefix=3Dno
-
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32*)
-    library_names_spec=3D'$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds=3D'base_file=3D`basename \${file}`~
-      dlpath=3D`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dl=
name'\''`~
-      dldir=3D$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
-    postuninstall_cmds=3D'dldll=3D`$SHELL 2>&1 -c '\''. $file; echo \$dlna=
me'\''`~
-      dlpath=3D$dir/\$dldll~
-       $rm \$dlpath'
-    shlibpath_overrides_runpath=3Dyes
-
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec=3D'`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${relea=
se} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D"/usr/lib /lib/w32api /lib /usr/local/lib"
-      ;;
-    mingw*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${ve=
rsuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^librarie=
s:" | $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-      if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null;=
 then
-        # It is most probably a Windows format PATH printed by
-        # mingw gcc, but we are running on Cygwin. Gcc prints its search
-        # path with ; separators, and with drive letters. We can handle the
-        # drive letters (cygwin fileutils understands them), so leave them,
-        # especially as we might pass files found there to a mingw objdump,
-        # which wouldn't understand a cygwinified path. Ahh.
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D  -e "s/$PATH_SEPARATOR/ /g"`
-      fi
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec=3D'`echo ${libname} | sed -e 's/^lib/pw/'``echo $=
{release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    ;;
-
-  *)
-    library_names_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'=
`${versuffix}${shared_ext} $libname.lib'
-    ;;
-  esac
-  dynamic_linker=3D'Win32 ld.exe'
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=3DPATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker=3D"$host_os dyld"
-  version_type=3Ddarwin
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${major}$shared_ext ${libname}=
$shared_ext ${libname}${release}${versuffix}$shared_ext'
-  soname_spec=3D'${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=3Dyes
-  shlibpath_var=3DDYLD_LIBRARY_PATH
-  shrext_cmds=3D'`test .$module =3D .yes && echo .so || echo .dylib`'
-  # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
-  if test "$GCC" =3D yes; then
-    sys_lib_search_path_spec=3D`$CC -print-search-dirs | tr "\n" "$PATH_SE=
PARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^librar=
ies:" | sed -e "s/^libraries://" -e "s,=3D/,/,g" -e "s,$PATH_SEPARATOR, ,g"=
 -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
-  else
-    sys_lib_search_path_spec=3D'/lib /usr/lib /usr/local/lib'
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-freebsd1*)
-  dynamic_linker=3Dno
-  ;;
-
-kfreebsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=3D`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[123]*) objformat=3Daout ;;
-    *) objformat=3Delf ;;
-    esac
-  fi
-  version_type=3Dfreebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=3Dno
-      need_lib_prefix=3Dno
-      ;;
-    freebsd-*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $l=
ibname${shared_ext}$versuffix'
-      need_version=3Dyes
-      ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_os in
-  freebsd2*)
-    shlibpath_overrides_runpath=3Dyes
-    ;;
-  freebsd3.[01]* | freebsdelf3.[01]*)
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=3Dno
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  esac
-  ;;
-
-gnu*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuse=
s to
-  # link against other versions.
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  case $host_cpu in
-  ia64*)
-    shrext_cmds=3D'.so'
-    hardcode_into_libs=3Dyes
-    dynamic_linker=3D"$host_os dld.so"
-    shlibpath_var=3DLD_LIBRARY_PATH
-    shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" =3D X32; then
-      sys_lib_search_path_spec=3D"/usr/lib/hpux32 /usr/local/lib/hpux32 /u=
sr/local/lib"
-    else
-      sys_lib_search_path_spec=3D"/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-    ;;
-   hppa*64*)
-     shrext_cmds=3D'.sl'
-     hardcode_into_libs=3Dyes
-     dynamic_linker=3D"$host_os dld.sl"
-     shlibpath_var=3DLD_LIBRARY_PATH # How should we handle SHLIB_PATH
-     shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-     library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${l=
ibname}${release}${shared_ext}$major $libname${shared_ext}'
-     soname_spec=3D'${libname}${release}${shared_ext}$major'
-     sys_lib_search_path_spec=3D"/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-     sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-     ;;
-   *)
-    shrext_cmds=3D'.sl'
-    dynamic_linker=3D"$host_os dld.sl"
-    shlibpath_var=3DSHLIB_PATH
-    shlibpath_overrides_runpath=3Dno # +s is required to enable SHLIB_PATH
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
-  postinstall_cmds=3D'chmod 555 $lib'
-  ;;
-
-interix3*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  dynamic_linker=3D'Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=3Dnonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" =3D yes; then
-		version_type=3Dlinux
-	else
-		version_type=3Dirix
-	fi ;;
-  esac
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libnam=
e${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff=3D shlibsuff=3D
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff=3D shlibsuff=3D libmagic=3D32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=3D32 shlibsuff=3DN32 libmagic=3DN32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=3D64 shlibsuff=3D64 libmagic=3D64-bit;;
-    *) libsuff=3D shlibsuff=3D libmagic=3Dnever-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=3Dno
-  sys_lib_search_path_spec=3D"/usr/lib${libsuff} /lib${libsuff} /usr/local=
/lib${libsuff}"
-  sys_lib_dlsearch_path_spec=3D"/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=3Dyes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=3Dno
-  ;;
-
-# This must be Linux ELF.
-linux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=3Dyes
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=3D`awk '/^include / { system(sprintf("cd /etc; cat %s", \$=
2)); skip =3D 1; } { if (!skip) print \$0; skip =3D 0; }' < /etc/ld.so.conf=
 | $SED -e 's/#.*//;s/[:,	]/ /g;s/=3D[^=3D]*$//;s/=3D[^=3D ]* / /g;/^$/d' |=
 tr '\n' ' '`
-    sys_lib_dlsearch_path_spec=3D"/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker=3D'GNU/Linux ld.so'
-  ;;
-
-knetbsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-netbsd*)
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${shared_ext}$versuffix'
-    finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker=3D'NetBSD (a.out) ld.so'
-  else
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    dynamic_linker=3D'NetBSD ld.elf_so'
-  fi
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  ;;
-
-newsos6)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-nto-qnx*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-openbsd*)
-  version_type=3Dsunos
-  sys_lib_dlsearch_path_spec=3D"/usr/lib"
-  need_lib_prefix=3Dno
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=3Dyes ;;
-    *)                         need_version=3Dno  ;;
-  esac
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=3Dno
-	;;
-      *)
-	shlibpath_overrides_runpath=3Dyes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=3Dyes
-  fi
-  ;;
-
-os2*)
-  libname_spec=3D'$name'
-  shrext_cmds=3D".dll"
-  need_lib_prefix=3Dno
-  library_names_spec=3D'$libname${shared_ext} $libname.a'
-  dynamic_linker=3D'OS/2 ld.exe'
-  shlibpath_var=3DLIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=3Dosf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /=
usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec=3D"$sys_lib_search_path_spec"
-  ;;
-
-solaris*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  # ldd complains unless libraries are executable
-  postinstall_cmds=3D'chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=3Dsunos
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    need_lib_prefix=3Dno
-  fi
-  need_version=3Dyes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=3Dno
-      need_lib_prefix=3Dno
-      export_dynamic_flag_spec=3D'${wl}-Blargedynsym'
-      runpath_var=3DLD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=3Dno
-      ;;
-    motorola)
-      need_lib_prefix=3Dno
-      need_version=3Dno
-      shlibpath_overrides_runpath=3Dno
-      sys_lib_search_path_spec=3D'/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=3Dlinux
-    library_names_spec=3D'$libname${shared_ext}.$versuffix $libname${share=
d_ext}.$major $libname${shared_ext}'
-    soname_spec=3D'$libname${shared_ext}.$major'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=3Dfreebsd-elf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    sys_lib_search_path_spec=3D'/usr/local/lib /usr/gnu/lib /usr/ccs/lib /=
usr/lib /lib'
-    shlibpath_overrides_runpath=3Dno
-  else
-    sys_lib_search_path_spec=3D'/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=3Dyes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec=3D"$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/lib'
-  ;;
-
-uts4*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=3Dno
-  ;;
-esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
-test "$dynamic_linker" =3D no && can_build_shared=3Dno
-
-variables_saved_for_relink=3D"PATH $shlibpath_var $runpath_var"
-if test "$GCC" =3D yes; then
-  variables_saved_for_relink=3D"$variables_saved_for_relink GCC_EXEC_PREFI=
X COMPILER_PATH LIBRARY_PATH"
-fi
-
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into progra=
ms" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECH=
O_C" >&6; }
-hardcode_action_CXX=3D
-if test -n "$hardcode_libdir_flag_spec_CXX" || \
-   test -n "$runpath_var_CXX" || \
-   test "X$hardcode_automatic_CXX" =3D "Xyes" ; then
-
-  # We can hardcode non-existant directories.
-  if test "$hardcode_direct_CXX" !=3D no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, CXX)" !=3D no &&
-     test "$hardcode_minus_L_CXX" !=3D no; then
-    # Linking always hardcodes the temporary library directory.
-    hardcode_action_CXX=3Drelink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    hardcode_action_CXX=3Dimmediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  hardcode_action_CXX=3Dunsupported
-fi
-{ echo "$as_me:$LINENO: result: $hardcode_action_CXX" >&5
-echo "${ECHO_T}$hardcode_action_CXX" >&6; }
-
-if test "$hardcode_action_CXX" =3D relink; then
-  # Fast installation is not supported
-  enable_fast_install=3Dno
-elif test "$shlibpath_overrides_runpath" =3D yes ||
-     test "$enable_shared" =3D no; then
-  # Fast installation is not necessary
-  enable_fast_install=3Dneedless
-fi
-
-
-# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our comm=
ands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTC=
FLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    compiler_CXX \
-    CC_CXX \
-    LD_CXX \
-    lt_prog_compiler_wl_CXX \
-    lt_prog_compiler_pic_CXX \
-    lt_prog_compiler_static_CXX \
-    lt_prog_compiler_no_builtin_flag_CXX \
-    export_dynamic_flag_spec_CXX \
-    thread_safe_flag_spec_CXX \
-    whole_archive_flag_spec_CXX \
-    enable_shared_with_static_runtimes_CXX \
-    old_archive_cmds_CXX \
-    old_archive_from_new_cmds_CXX \
-    predep_objects_CXX \
-    postdep_objects_CXX \
-    predeps_CXX \
-    postdeps_CXX \
-    compiler_lib_search_path_CXX \
-    archive_cmds_CXX \
-    archive_expsym_cmds_CXX \
-    postinstall_cmds_CXX \
-    postuninstall_cmds_CXX \
-    old_archive_from_expsyms_cmds_CXX \
-    allow_undefined_flag_CXX \
-    no_undefined_flag_CXX \
-    export_symbols_cmds_CXX \
-    hardcode_libdir_flag_spec_CXX \
-    hardcode_libdir_flag_spec_ld_CXX \
-    hardcode_libdir_separator_CXX \
-    hardcode_automatic_CXX \
-    module_cmds_CXX \
-    module_expsym_cmds_CXX \
-    lt_cv_prog_compiler_c_o_CXX \
-    exclude_expsyms_CXX \
-    include_expsyms_CXX; do
-
-    case $var in
-    old_archive_cmds_CXX | \
-    old_archive_from_new_cmds_CXX | \
-    archive_cmds_CXX | \
-    archive_expsym_cmds_CXX | \
-    module_cmds_CXX | \
-    module_expsym_cmds_CXX | \
-    old_archive_from_expsyms_cmds_CXX | \
-    export_symbols_cmds_CXX | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quot=
e_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
-      ;;
-    *)
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_s=
ubst\"\`\\\""
-      ;;
-    esac
-  done
-
-  case $lt_echo in
-  *'\$0 --fallback-echo"')
-    lt_echo=3D`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$=
/$0 --fallback-echo"/'`
-    ;;
-  esac
-
-cfgfile=3D"$ofile"
-
-  cat <<__EOF__ >> "$cfgfile"
-# ### BEGIN LIBTOOL TAG CONFIG: $tagname
-
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed=
 1q`:
-
-# Shell to use when invoking shell scripts.
-SHELL=3D$lt_SHELL
-
-# Whether or not to build shared libraries.
-build_libtool_libs=3D$enable_shared
-
-# Whether or not to build static libraries.
-build_old_libs=3D$enable_static
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=3D$archive_cmds_need_lc_CXX
-
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=3D$enable_shared_with_static_runti=
mes_CXX
-
-# Whether or not to optimize for fast installation.
-fast_install=3D$enable_fast_install
-
-# The host system.
-host_alias=3D$host_alias
-host=3D$host
-host_os=3D$host_os
-
-# The build system.
-build_alias=3D$build_alias
-build=3D$build
-build_os=3D$build_os
-
-# An echo program that does not interpret backslashes.
-echo=3D$lt_echo
-
-# The archiver.
-AR=3D$lt_AR
-AR_FLAGS=3D$lt_AR_FLAGS
-
-# A C compiler.
-LTCC=3D$lt_LTCC
-
-# LTCC compiler flags.
-LTCFLAGS=3D$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=3D$lt_compiler_CXX
-
-# Is the compiler the GNU C compiler?
-with_gcc=3D$GCC_CXX
-
-# An ERE matcher.
-EGREP=3D$lt_EGREP
-
-# The linker used to build libraries.
-LD=3D$lt_LD_CXX
-
-# Whether we need hard or soft links.
-LN_S=3D$lt_LN_S
-
-# A BSD-compatible nm program.
-NM=3D$lt_NM
-
-# A symbol stripping program
-STRIP=3D$lt_STRIP
-
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=3D$MAGIC_CMD
-
-# Used on cygwin: DLL creation program.
-DLLTOOL=3D"$DLLTOOL"
-
-# Used on cygwin: object dumper.
-OBJDUMP=3D"$OBJDUMP"
-
-# Used on cygwin: assembler.
-AS=3D"$AS"
-
-# The name of the directory that contains temporary libtool files.
-objdir=3D$objdir
-
-# How to create reloadable object files.
-reload_flag=3D$lt_reload_flag
-reload_cmds=3D$lt_reload_cmds
-
-# How to pass a linker flag through the compiler.
-wl=3D$lt_lt_prog_compiler_wl_CXX
-
-# Object file suffix (normally "o").
-objext=3D"$ac_objext"
-
-# Old archive suffix (normally "a").
-libext=3D"$libext"
-
-# Shared library suffix (normally ".so").
-shrext_cmds=3D'$shrext_cmds'
-
-# Executable file suffix (normally "").
-exeext=3D"$exeext"
-
-# Additional compiler flags for building library objects.
-pic_flag=3D$lt_lt_prog_compiler_pic_CXX
-pic_mode=3D$pic_mode
-
-# What is the maximum length of a command?
-max_cmd_len=3D$lt_cv_sys_max_cmd_len
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=3D$lt_lt_cv_prog_compiler_c_o_CXX
-
-# Must we lock files when doing compilation?
-need_locks=3D$lt_need_locks
-
-# Do we need the lib prefix for modules?
-need_lib_prefix=3D$need_lib_prefix
-
-# Do we need a version for libraries?
-need_version=3D$need_version
-
-# Whether dlopen is supported.
-dlopen_support=3D$enable_dlopen
-
-# Whether dlopen of programs is supported.
-dlopen_self=3D$enable_dlopen_self
-
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=3D$enable_dlopen_self_static
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=3D$lt_lt_prog_compiler_static_CXX
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=3D$lt_lt_prog_compiler_no_builtin_flag_CXX
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=3D$lt_export_dynamic_flag_spec_CXX
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=3D$lt_whole_archive_flag_spec_CXX
-
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=3D$lt_thread_safe_flag_spec_CXX
-
-# Library versioning type.
-version_type=3D$version_type
-
-# Format of library name prefix.
-libname_spec=3D$lt_libname_spec
-
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=3D$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=3D$lt_soname_spec
-
-# Commands used to build and install an old-style archive.
-RANLIB=3D$lt_RANLIB
-old_archive_cmds=3D$lt_old_archive_cmds_CXX
-old_postinstall_cmds=3D$lt_old_postinstall_cmds
-old_postuninstall_cmds=3D$lt_old_postuninstall_cmds
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=3D$lt_old_archive_from_new_cmds_CXX
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=3D$lt_old_archive_from_expsyms_cmds_CXX
-
-# Commands used to build and install a shared archive.
-archive_cmds=3D$lt_archive_cmds_CXX
-archive_expsym_cmds=3D$lt_archive_expsym_cmds_CXX
-postinstall_cmds=3D$lt_postinstall_cmds
-postuninstall_cmds=3D$lt_postuninstall_cmds
-
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=3D$lt_module_cmds_CXX
-module_expsym_cmds=3D$lt_module_expsym_cmds_CXX
-
-# Commands to strip libraries.
-old_striplib=3D$lt_old_striplib
-striplib=3D$lt_striplib
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=3D$lt_predep_objects_CXX
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=3D$lt_postdep_objects_CXX
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=3D$lt_predeps_CXX
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=3D$lt_postdeps_CXX
-
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=3D$lt_compiler_lib_search_path_CXX
-
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=3D$lt_deplibs_check_method
-
-# Command to use when deplibs_check_method =3D=3D file_magic.
-file_magic_cmd=3D$lt_file_magic_cmd
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=3D$lt_allow_undefined_flag_CXX
-
-# Flag that forces no undefined symbols.
-no_undefined_flag=3D$lt_no_undefined_flag_CXX
-
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=3D$lt_finish_cmds
-
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=3D$lt_finish_eval
-
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=3D$lt_lt_cv_sys_global_symbol_pipe
-
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=3D$lt_lt_cv_sys_global_symbol_to_cdecl
-
-# Transform the output of nm in a C name address pair
-global_symbol_to_c_name_address=3D$lt_lt_cv_sys_global_symbol_to_c_name_ad=
dress
-
-# This is the shared library runtime path variable.
-runpath_var=3D$runpath_var
-
-# This is the shared library path variable.
-shlibpath_var=3D$shlibpath_var
-
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=3D$shlibpath_overrides_runpath
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=3D$hardcode_action_CXX
-
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=3D$hardcode_into_libs
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist.
-hardcode_libdir_flag_spec=3D$lt_hardcode_libdir_flag_spec_CXX
-
-# If ld is used when linking, flag to hardcode \$libdir into
-# a binary during linking. This must work even if \$libdir does
-# not exist.
-hardcode_libdir_flag_spec_ld=3D$lt_hardcode_libdir_flag_spec_ld_CXX
-
-# Whether we need a single -rpath flag with a separated argument.
-hardcode_libdir_separator=3D$lt_hardcode_libdir_separator_CXX
-
-# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DI=
R into the
-# resulting binary.
-hardcode_direct=3D$hardcode_direct_CXX
-
-# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
-# resulting binary.
-hardcode_minus_L=3D$hardcode_minus_L_CXX
-
-# Set to yes if using SHLIBPATH_VAR=3DDIR during linking hardcodes DIR into
-# the resulting binary.
-hardcode_shlibpath_var=3D$hardcode_shlibpath_var_CXX
-
-# Set to yes if building a shared library automatically hardcodes DIR into=
 the library
-# and all subsequent libraries and executables linked against it.
-hardcode_automatic=3D$hardcode_automatic_CXX
-
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at relink time.
-variables_saved_for_relink=3D"$variables_saved_for_relink"
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=3D$link_all_deplibs_CXX
-
-# Compile-time system search path for libraries
-sys_lib_search_path_spec=3D$lt_sys_lib_search_path_spec
-
-# Run-time system search path for libraries
-sys_lib_dlsearch_path_spec=3D$lt_sys_lib_dlsearch_path_spec
-
-# Fix the shell variable \$srcfile for the compiler.
-fix_srcfile_path=3D"$fix_srcfile_path_CXX"
-
-# Set to yes if exported symbols are required.
-always_export_symbols=3D$always_export_symbols_CXX
-
-# The commands to list exported symbols.
-export_symbols_cmds=3D$lt_export_symbols_cmds_CXX
-
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=3D$lt_extract_expsyms_cmds
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=3D$lt_exclude_expsyms_CXX
-
-# Symbols that must always be exported.
-include_expsyms=3D$lt_include_expsyms_CXX
-
-# ### END LIBTOOL TAG CONFIG: $tagname
-
-__EOF__
-
-
-else
-  # If there is no Makefile yet, we rely on a make rule to execute
-  # `config.status --recheck' to rerun these tests and create the
-  # libtool script then.
-  ltmain_in=3D`echo $ltmain | sed -e 's/\.sh$/.in/'`
-  if test -f "$ltmain_in"; then
-    test -f Makefile && make "$ltmain"
-  fi
-fi
-
-
-ac_ext=3Dc
-ac_cpp=3D'$CPP $CPPFLAGS'
-ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
-
-CC=3D$lt_save_CC
-LDCXX=3D$LD
-LD=3D$lt_save_LD
-GCC=3D$lt_save_GCC
-with_gnu_ldcxx=3D$with_gnu_ld
-with_gnu_ld=3D$lt_save_with_gnu_ld
-lt_cv_path_LDCXX=3D$lt_cv_path_LD
-lt_cv_path_LD=3D$lt_save_path_LD
-lt_cv_prog_gnu_ldcxx=3D$lt_cv_prog_gnu_ld
-lt_cv_prog_gnu_ld=3D$lt_save_with_gnu_ld
-
-	else
-	  tagname=3D""
-	fi
-	;;
-
-      F77)
-	if test -n "$F77" && test "X$F77" !=3D "Xno"; then
-
-ac_ext=3Df
-ac_compile=3D'$F77 -c $FFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $L=
IBS >&5'
-ac_compiler_gnu=3D$ac_cv_f77_compiler_gnu
-
-
-archive_cmds_need_lc_F77=3Dno
-allow_undefined_flag_F77=3D
-always_export_symbols_F77=3Dno
-archive_expsym_cmds_F77=3D
-export_dynamic_flag_spec_F77=3D
-hardcode_direct_F77=3Dno
-hardcode_libdir_flag_spec_F77=3D
-hardcode_libdir_flag_spec_ld_F77=3D
-hardcode_libdir_separator_F77=3D
-hardcode_minus_L_F77=3Dno
-hardcode_automatic_F77=3Dno
-module_cmds_F77=3D
-module_expsym_cmds_F77=3D
-link_all_deplibs_F77=3Dunknown
-old_archive_cmds_F77=3D$old_archive_cmds
-no_undefined_flag_F77=3D
-whole_archive_flag_spec_F77=3D
-enable_shared_with_static_runtimes_F77=3Dno
-
-# Source file extension for f77 test sources.
-ac_ext=3Df
-
-# Object file extension for compiled f77 test sources.
-objext=3Do
-objext_F77=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"      subroutine t\n      return\n      end=
\n"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D"      program t\n      end\n"
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-
-# If no C compiler was specified, use CC.
-LTCC=3D${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=3D${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=3D$CC
-
-
-# save warnings/boilerplate of simple test code
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D"$CC"
-CC=3D${F77-"f77"}
-compiler=3D$CC
-compiler_F77=3D$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
-
-
-{ echo "$as_me:$LINENO: checking if libtool supports shared libraries" >&5
-echo $ECHO_N "checking if libtool supports shared libraries... $ECHO_C" >&=
6; }
-{ echo "$as_me:$LINENO: result: $can_build_shared" >&5
-echo "${ECHO_T}$can_build_shared" >&6; }
-
-{ echo "$as_me:$LINENO: checking whether to build shared libraries" >&5
-echo $ECHO_N "checking whether to build shared libraries... $ECHO_C" >&6; }
-test "$can_build_shared" =3D "no" && enable_shared=3Dno
-
-# On AIX, shared libraries and static libraries use the same namespace, and
-# are all built from PIC.
-case $host_os in
-aix3*)
-  test "$enable_shared" =3D yes && enable_static=3Dno
-  if test -n "$RANLIB"; then
-    archive_cmds=3D"$archive_cmds~\$RANLIB \$lib"
-    postinstall_cmds=3D'$RANLIB $lib'
-  fi
-  ;;
-aix4* | aix5*)
-  if test "$host_cpu" !=3D ia64 && test "$aix_use_runtimelinking" =3D no ;=
 then
-    test "$enable_shared" =3D yes && enable_static=3Dno
-  fi
-  ;;
-esac
-{ echo "$as_me:$LINENO: result: $enable_shared" >&5
-echo "${ECHO_T}$enable_shared" >&6; }
-
-{ echo "$as_me:$LINENO: checking whether to build static libraries" >&5
-echo $ECHO_N "checking whether to build static libraries... $ECHO_C" >&6; }
-# Make sure either enable_shared or enable_static is yes.
-test "$enable_shared" =3D yes || enable_static=3Dyes
-{ echo "$as_me:$LINENO: result: $enable_static" >&5
-echo "${ECHO_T}$enable_static" >&6; }
-
-GCC_F77=3D"$G77"
-LD_F77=3D"$LD"
-
-lt_prog_compiler_wl_F77=3D
-lt_prog_compiler_pic_F77=3D
-lt_prog_compiler_static_F77=3D
-
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6=
; }
-
-  if test "$GCC" =3D yes; then
-    lt_prog_compiler_wl_F77=3D'-Wl,'
-    lt_prog_compiler_static_F77=3D'-static'
-
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static_F77=3D'-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      # FIXME: we need at least 68020 code to build shared libraries, but
-      # adding the `-m68020' flag to GCC prevents building anything better,
-      # like `-m68040'.
-      lt_prog_compiler_pic_F77=3D'-m68020 -resident32 -malways-restore-a4'
-      ;;
-
-    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      lt_prog_compiler_pic_F77=3D'-DDLL_EXPORT'
-      ;;
-
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      lt_prog_compiler_pic_F77=3D'-fno-common'
-      ;;
-
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared librar=
ies
-      # on systems that don't support them.
-      lt_prog_compiler_can_build_shared_F77=3Dno
-      enable_shared=3Dno
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	lt_prog_compiler_pic_F77=3D-Kconform_pic
-      fi
-      ;;
-
-    hpux*)
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic_F77=3D'-fPIC'
-	;;
-      esac
-      ;;
-
-    *)
-      lt_prog_compiler_pic_F77=3D'-fPIC'
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compil=
er.
-    case $host_os in
-    aix*)
-      lt_prog_compiler_wl_F77=3D'-Wl,'
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static_F77=3D'-Bstatic'
-      else
-	lt_prog_compiler_static_F77=3D'-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-      darwin*)
-        # PIC is the default on this platform
-        # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
-         xlc*)
-         lt_prog_compiler_pic_F77=3D'-qnocommon'
-         lt_prog_compiler_wl_F77=3D'-Wl,'
-         ;;
-       esac
-       ;;
-
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      lt_prog_compiler_pic_F77=3D'-DDLL_EXPORT'
-      ;;
-
-    hpux9* | hpux10* | hpux11*)
-      lt_prog_compiler_wl_F77=3D'-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic_F77=3D'+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bund=
led CC?
-      lt_prog_compiler_static_F77=3D'${wl}-a ${wl}archive'
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      lt_prog_compiler_wl_F77=3D'-Wl,'
-      # PIC (with -KPIC) is the default.
-      lt_prog_compiler_static_F77=3D'-non_shared'
-      ;;
-
-    newsos6)
-      lt_prog_compiler_pic_F77=3D'-KPIC'
-      lt_prog_compiler_static_F77=3D'-Bstatic'
-      ;;
-
-    linux*)
-      case $cc_basename in
-      icc* | ecc*)
-	lt_prog_compiler_wl_F77=3D'-Wl,'
-	lt_prog_compiler_pic_F77=3D'-KPIC'
-	lt_prog_compiler_static_F77=3D'-static'
-        ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	lt_prog_compiler_wl_F77=3D'-Wl,'
-	lt_prog_compiler_pic_F77=3D'-fpic'
-	lt_prog_compiler_static_F77=3D'-Bstatic'
-        ;;
-      ccc*)
-        lt_prog_compiler_wl_F77=3D'-Wl,'
-        # All Alpha code is PIC.
-        lt_prog_compiler_static_F77=3D'-non_shared'
-        ;;
-      esac
-      ;;
-
-    osf3* | osf4* | osf5*)
-      lt_prog_compiler_wl_F77=3D'-Wl,'
-      # All OSF/1 code is PIC.
-      lt_prog_compiler_static_F77=3D'-non_shared'
-      ;;
-
-    solaris*)
-      lt_prog_compiler_pic_F77=3D'-KPIC'
-      lt_prog_compiler_static_F77=3D'-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	lt_prog_compiler_wl_F77=3D'-Qoption ld ';;
-      *)
-	lt_prog_compiler_wl_F77=3D'-Wl,';;
-      esac
-      ;;
-
-    sunos4*)
-      lt_prog_compiler_wl_F77=3D'-Qoption ld '
-      lt_prog_compiler_pic_F77=3D'-PIC'
-      lt_prog_compiler_static_F77=3D'-Bstatic'
-      ;;
-
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      lt_prog_compiler_wl_F77=3D'-Wl,'
-      lt_prog_compiler_pic_F77=3D'-KPIC'
-      lt_prog_compiler_static_F77=3D'-Bstatic'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	lt_prog_compiler_pic_F77=3D'-Kconform_pic'
-	lt_prog_compiler_static_F77=3D'-Bstatic'
-      fi
-      ;;
-
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      lt_prog_compiler_wl_F77=3D'-Wl,'
-      lt_prog_compiler_pic_F77=3D'-KPIC'
-      lt_prog_compiler_static_F77=3D'-Bstatic'
-      ;;
-
-    unicos*)
-      lt_prog_compiler_wl_F77=3D'-Wl,'
-      lt_prog_compiler_can_build_shared_F77=3Dno
-      ;;
-
-    uts4*)
-      lt_prog_compiler_pic_F77=3D'-pic'
-      lt_prog_compiler_static_F77=3D'-Bstatic'
-      ;;
-
-    *)
-      lt_prog_compiler_can_build_shared_F77=3Dno
-      ;;
-    esac
-  fi
-
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_F77" >&6; }
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$lt_prog_compiler_pic_F77"; then
-
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_p=
ic_F77 works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_F77 wor=
ks... $ECHO_C" >&6; }
-if test "${lt_prog_compiler_pic_works_F77+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_pic_works_F77=3Dno
-  ac_outfile=3Dconftest.$ac_objext
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag=3D"$lt_prog_compiler_pic_F77"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:14862: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=3D$?
-   cat conftest.err >&5
-   echo "$as_me:14866: \$? =3D $ac_status" >&5
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/nul=
l; then
-       lt_prog_compiler_pic_works_F77=3Dyes
-     fi
-   fi
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works_F77" >&6; }
-
-if test x"$lt_prog_compiler_pic_works_F77" =3D xyes; then
-    case $lt_prog_compiler_pic_F77 in
-     "" | " "*) ;;
-     *) lt_prog_compiler_pic_F77=3D" $lt_prog_compiler_pic_F77" ;;
-     esac
-else
-    lt_prog_compiler_pic_F77=3D
-     lt_prog_compiler_can_build_shared_F77=3Dno
-fi
-
-fi
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    lt_prog_compiler_pic_F77=3D
-    ;;
-  *)
-    lt_prog_compiler_pic_F77=3D"$lt_prog_compiler_pic_F77"
-    ;;
-esac
-
-#
-# Check to make sure the static flag actually works.
-#
-wl=3D$lt_prog_compiler_wl_F77 eval lt_tmp_static_flag=3D\"$lt_prog_compile=
r_static_F77\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_f=
lag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works.=
.. $ECHO_C" >&6; }
-if test "${lt_prog_compiler_static_works_F77+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works_F77=3Dno
-   save_LDFLAGS=3D"$LDFLAGS"
-   LDFLAGS=3D"$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works_F77=3Dyes
-       fi
-     else
-       lt_prog_compiler_static_works_F77=3Dyes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS=3D"$save_LDFLAGS"
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_F77" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_F77" >&6; }
-
-if test x"$lt_prog_compiler_static_works_F77" =3D xyes; then
-    :
-else
-    lt_prog_compiler_static_F77=3D
-fi
-
-
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_obje=
xt" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECH=
O_C" >&6; }
-if test "${lt_cv_prog_compiler_c_o_F77+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_cv_prog_compiler_c_o_F77=3Dno
-   $rm -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag=3D"-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:14966: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=3D$?
-   cat out/conftest.err >&5
-   echo "$as_me:14970: \$? =3D $ac_status" >&5
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.=
exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.e=
r2 >/dev/null; then
-       lt_cv_prog_compiler_c_o_F77=3Dyes
-     fi
-   fi
-   chmod u+w . 2>&5
-   $rm conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
-   $rm out/* && rmdir out
-   cd ..
-   rmdir conftest
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_F77" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o_F77" >&6; }
-
-
-hard_links=3D"nottested"
-if test "$lt_cv_prog_compiler_c_o_F77" =3D no && test "$need_locks" !=3D n=
o; then
-  # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
-  hard_links=3Dyes
-  $rm conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=3Dno
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
-  if test "$hard_links" =3D no; then
-    { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so =
\`make -j' may be unsafe" >&5
-echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may=
 be unsafe" >&2;}
-    need_locks=3Dwarn
-  fi
-else
-  need_locks=3Dno
-fi
-
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) suppor=
ts shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared =
libraries... $ECHO_C" >&6; }
-
-  runpath_var=3D
-  allow_undefined_flag_F77=3D
-  enable_shared_with_static_runtimes_F77=3Dno
-  archive_cmds_F77=3D
-  archive_expsym_cmds_F77=3D
-  old_archive_From_new_cmds_F77=3D
-  old_archive_from_expsyms_cmds_F77=3D
-  export_dynamic_flag_spec_F77=3D
-  whole_archive_flag_spec_F77=3D
-  thread_safe_flag_spec_F77=3D
-  hardcode_libdir_flag_spec_F77=3D
-  hardcode_libdir_flag_spec_ld_F77=3D
-  hardcode_libdir_separator_F77=3D
-  hardcode_direct_F77=3Dno
-  hardcode_minus_L_F77=3Dno
-  hardcode_shlibpath_var_F77=3Dunsupported
-  link_all_deplibs_F77=3Dunknown
-  hardcode_automatic_F77=3Dno
-  module_cmds_F77=3D
-  module_expsym_cmds_F77=3D
-  always_export_symbols_F77=3Dno
-  export_symbols_cmds_F77=3D'$NM $libobjs $convenience | $global_symbol_pi=
pe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  # include_expsyms should be a list of space-separated symbols to be *alw=
ays*
-  # included in the symbol list
-  include_expsyms_F77=3D
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `=
bc',
-  # as well as any symbol that contains `d'.
-  exclude_expsyms_F77=3D"_GLOBAL_OFFSET_TABLE_"
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  extract_expsyms_cmds=3D
-  # Just being paranoid about ensuring that cc_basename is set.
-  for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
-
-  case $host_os in
-  cygwin* | mingw* | pw32*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" !=3D yes; then
-      with_gnu_ld=3Dno
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (=3D MSVC++)
-    with_gnu_ld=3Dyes
-    ;;
-  openbsd*)
-    with_gnu_ld=3Dno
-    ;;
-  esac
-
-  ld_shlibs_F77=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc=3D'${wl}'
-
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=3DLD_RUN_PATH
-    hardcode_libdir_flag_spec_F77=3D'${wl}--rpath ${wl}$libdir'
-    export_dynamic_flag_spec_F77=3D'${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	whole_archive_flag_spec_F77=3D"$wlarc"'--whole-archive$convenience '"$wla=
rc"'--no-whole-archive'
-      else
-  	whole_archive_flag_spec_F77=3D
-    fi
-    supports_anon_versioning=3Dno
-    case `$LD -v 2>/dev/null` in
-      *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=3Dyes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=3Dyes ;; # Mandrake 8.2=
 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=3Dyes ;;
-    esac
-
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix3* | aix4* | aix5*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" !=3D ia64; then
-	ld_shlibs_F77=3Dno
-	cat <<EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.9.1, is reported
-*** to be unable to reliably create shared libraries on AIX.
-*** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to modify your PATH
-*** so that a non-GNU linker is found, and then restart.
-
-EOF
-      fi
-      ;;
-
-    amigaos*)
-      archive_cmds_F77=3D'$rm $output_objdir/a2ixlibrary.data~$echo "#defi=
ne NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_=
ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> =
$output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $outp=
ut_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $ou=
tput_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-      hardcode_minus_L_F77=3Dyes
-
-      # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
-      # that the semantics of dynamic libraries on AmigaOS, at least up
-      # to version 4, is to share data among multiple programs linked
-      # with the same dynamic library.  Since this doesn't match the
-      # behavior of shared libraries on other platforms, we can't use
-      # them.
-      ld_shlibs_F77=3Dno
-      ;;
-
-    beos*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	allow_undefined_flag_F77=3Dunsupported
-	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	archive_cmds_F77=3D'$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-=
soname $wl$soname -o $lib'
-      else
-	ld_shlibs_F77=3Dno
-      fi
-      ;;
-
-    cygwin* | mingw* | pw32*)
-      # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, F77) is actually meaningl=
ess,
-      # as there is no search path for DLLs.
-      hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-      allow_undefined_flag_F77=3Dunsupported
-      always_export_symbols_F77=3Dno
-      enable_shared_with_static_runtimes_F77=3Dyes
-      export_symbols_cmds_F77=3D'$NM $libobjs $convenience | $global_symbo=
l_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''=
/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
-
-      if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-        archive_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags =
-o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-impl=
ib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	archive_expsym_cmds_F77=3D'if test "x`$SED 1q $export_symbols`" =3D xEXPO=
RTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags =
-o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-impl=
ib -Xlinker $lib'
-      else
-	ld_shlibs_F77=3Dno
-      fi
-      ;;
-
-    interix3*)
-      hardcode_direct_F77=3Dno
-      hardcode_shlibpath_var_F77=3Dno
-      hardcode_libdir_flag_spec_F77=3D'${wl}-rpath,$libdir'
-      export_dynamic_flag_spec_F77=3D'${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gc=
c.
-      # Instead, shared libraries are loaded at an image base (0x10000000 =
by
-      # default) and relocated if they conflict, which is a slow very memo=
ry
-      # consuming and fragmenting process.  To avoid this, we pick a rando=
m,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at li=
nk
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      archive_cmds_F77=3D'$CC -shared $pic_flag $libobjs $deplibs $compile=
r_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* =
262144 + 1342177280` -o $lib'
-      archive_expsym_cmds_F77=3D'sed "s,^,_," $export_symbols >$output_obj=
dir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags =
${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${=
wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $l=
ib'
-      ;;
-
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	tmp_addflag=3D
-	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec_F77=3D'${wl}--whole-archive`for conv in $conven=
ience\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$c=
onv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=3D' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec_F77=3D'${wl}--whole-archive`for conv in $conven=
ience\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$c=
onv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=3D' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
-	  tmp_addflag=3D' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=3D' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=3D' -nofor_main' ;;
-	esac
-	archive_cmds_F77=3D'$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compil=
er_flags ${wl}-soname $wl$soname -o $lib'
-
-	if test $supports_anon_versioning =3D yes; then
-	  archive_expsym_cmds_F77=3D'$echo "{ global:" > $output_objdir/$libname.=
ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.=
ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-son=
ame $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $li=
b'
-	fi
-      else
-	ld_shlibs_F77=3Dno
-      fi
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	archive_cmds_F77=3D'$LD -Bshareable $libobjs $deplibs $linker_flags -o $l=
ib'
-	wlarc=3D
-      else
-	archive_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname $wl$soname -o $lib'
-	archive_expsym_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $li=
b'
-      fi
-      ;;
-
-    solaris*)
-      if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
-	ld_shlibs_F77=3Dno
-	cat <<EOF 1>&2
-
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-EOF
-      elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null=
; then
-	archive_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname $wl$soname -o $lib'
-	archive_expsym_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $li=
b'
-      else
-	ld_shlibs_F77=3Dno
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
-	ld_shlibs_F77=3Dno
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec_F77=3D'`test -z "$SCOABSPATH" && echo ${wl}=
-rpath,$libdir`'
-	    archive_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags ${w=
l}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    archive_expsym_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_fl=
ags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-=
file,$export_symbols -o $lib'
-	  else
-	    ld_shlibs_F77=3Dno
-	  fi
-	;;
-      esac
-      ;;
-
-    sunos4*)
-      archive_cmds_F77=3D'$LD -assert pure-text -Bshareable -o $lib $libob=
js $deplibs $linker_flags'
-      wlarc=3D
-      hardcode_direct_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    *)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	archive_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname $wl$soname -o $lib'
-	archive_expsym_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $li=
b'
-      else
-	ld_shlibs_F77=3Dno
-      fi
-      ;;
-    esac
-
-    if test "$ld_shlibs_F77" =3D no; then
-      runpath_var=3D
-      hardcode_libdir_flag_spec_F77=3D
-      export_dynamic_flag_spec_F77=3D
-      whole_archive_flag_spec_F77=3D
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
-    case $host_os in
-    aix3*)
-      allow_undefined_flag_F77=3Dunsupported
-      always_export_symbols_F77=3Dyes
-      archive_expsym_cmds_F77=3D'$LD -o $output_objdir/$soname $libobjs $d=
eplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS =
$lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      hardcode_minus_L_F77=3Dyes
-      if test "$GCC" =3D yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	hardcode_direct_F77=3Dunsupported
-      fi
-      ;;
-
-    aix4* | aix5*)
-      if test "$host_cpu" =3D ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=3Dno
-	exp_sym_flag=3D'-Bexport'
-	no_entry_flag=3D""
-      else
-	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
-	  export_symbols_cmds_F77=3D'$NM -Bpg $libobjs $convenience | awk '\''{ i=
f (((\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (substr(\$=
3,1,1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-	else
-	  export_symbols_cmds_F77=3D'$NM -BCpg $libobjs $convenience | awk '\''{ =
if (((\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (substr(\=
$3,1,1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-	fi
-	aix_use_runtimelinking=3Dno
-
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[23]|aix4.[23].*|aix5*)
-	  for ld_flag in $LDFLAGS; do
-  	  if (test $ld_flag =3D "-brtl" || test $ld_flag =3D "-Wl,-brtl"); then
-  	    aix_use_runtimelinking=3Dyes
-  	    break
-  	  fi
-	  done
-	  ;;
-	esac
-
-	exp_sym_flag=3D'-bexport'
-	no_entry_flag=3D'-bnoentry'
-      fi
-
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-      archive_cmds_F77=3D''
-      hardcode_direct_F77=3Dyes
-      hardcode_libdir_separator_F77=3D':'
-      link_all_deplibs_F77=3Dyes
-
-      if test "$GCC" =3D yes; then
-	case $host_os in aix4.[012]|aix4.[012].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=3D`${CC} -print-prog-name=3Dcollect2`
-	  if test -f "$collect2name" && \
-  	   strings "$collect2name" | grep resolve_lib_name >/dev/null
-	  then
-  	  # We have reworked collect2
-  	  hardcode_direct_F77=3Dyes
-	  else
-  	  # We have old collect2
-  	  hardcode_direct_F77=3Dunsupported
-  	  # It fails to find uninstalled libraries when the uninstalled
-  	  # path is not listed in the libpath.  Setting hardcode_minus_L
-  	  # to unsupported forces relinking
-  	  hardcode_minus_L_F77=3Dyes
-  	  hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-  	  hardcode_libdir_separator_F77=3D
-	  fi
-	  ;;
-	esac
-	shared_flag=3D'-shared'
-	if test "$aix_use_runtimelinking" =3D yes; then
-	  shared_flag=3D"$shared_flag "'${wl}-G'
-	fi
-      else
-	# not using gcc
-	if test "$host_cpu" =3D ia64; then
-  	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-  	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag=3D'-G'
-	else
-	  if test "$aix_use_runtimelinking" =3D yes; then
-	    shared_flag=3D'${wl}-G'
-	  else
-	    shared_flag=3D'${wl}-bM:SRE'
-	  fi
-	fi
-      fi
-
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to e=
xport.
-      always_export_symbols_F77=3Dyes
-      if test "$aix_use_runtimelinking" =3D yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	allow_undefined_flag_F77=3D'-berok'
-       # Determine the default libpath from the value encoded in an empty =
executable.
-       cat >conftest.$ac_ext <<_ACEOF
-      program main
-
-      end
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-
-       hardcode_libdir_flag_spec_F77=3D'${wl}-blibpath:$libdir:'"$aix_libp=
ath"
-	archive_expsym_cmds_F77=3D"\$CC"' -o $output_objdir/$soname $libobjs $dep=
libs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_=
flag}" !=3D "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\$=
{wl}$exp_sym_flag:\$export_symbols $shared_flag"
-       else
-	if test "$host_cpu" =3D ia64; then
-	  hardcode_libdir_flag_spec_F77=3D'${wl}-R $libdir:/usr/lib:/lib'
-	  allow_undefined_flag_F77=3D"-z nodefs"
-	  archive_expsym_cmds_F77=3D"\$CC $shared_flag"' -o $output_objdir/$sonam=
e $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_u=
ndefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an empty execu=
table.
-	 cat >conftest.$ac_ext <<_ACEOF
-      program main
-
-      end
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_f77_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-
-	 hardcode_libdir_flag_spec_F77=3D'${wl}-blibpath:$libdir:'"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  no_undefined_flag_F77=3D' ${wl}-bernotok'
-	  allow_undefined_flag_F77=3D' ${wl}-berok'
-	  # Exported symbols can be pulled into shared objects from archives
-	  whole_archive_flag_spec_F77=3D'$convenience'
-	  archive_cmds_need_lc_F77=3Dyes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  archive_expsym_cmds_F77=3D"\$CC $shared_flag"' -o $output_objdir/$sonam=
e $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols=
${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $ou=
tput_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      archive_cmds_F77=3D'$rm $output_objdir/a2ixlibrary.data~$echo "#defi=
ne NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_=
ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> =
$output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $outp=
ut_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $ou=
tput_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-      hardcode_minus_L_F77=3Dyes
-      # see comment about different semantics on the GNU ld section
-      ld_shlibs_F77=3Dno
-      ;;
-
-    bsdi[45]*)
-      export_dynamic_flag_spec_F77=3D-rdynamic
-      ;;
-
-    cygwin* | mingw* | pw32*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # hardcode_libdir_flag_spec is actually meaningless, as there is
-      # no search path for DLLs.
-      hardcode_libdir_flag_spec_F77=3D' '
-      allow_undefined_flag_F77=3Dunsupported
-      # Tell ltmain to make .lib files, not .a files.
-      libext=3Dlib
-      # Tell ltmain to make .dll files, not .so files.
-      shrext_cmds=3D".dll"
-      # FIXME: Setting linknames here is a bad hack.
-      archive_cmds_F77=3D'$CC -o $lib $libobjs $compiler_flags `echo "$dep=
libs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=3D'
-      # The linker will automatically build a .lib file if we build a DLL.
-      old_archive_From_new_cmds_F77=3D'true'
-      # FIXME: Should let the user specify the lib program.
-      old_archive_cmds_F77=3D'lib /OUT:$oldlib$oldobjs$old_deplibs'
-      fix_srcfile_path_F77=3D'`cygpath -w "$srcfile"`'
-      enable_shared_with_static_runtimes_F77=3Dyes
-      ;;
-
-    darwin* | rhapsody*)
-      case $host_os in
-        rhapsody* | darwin1.[012])
-         allow_undefined_flag_F77=3D'${wl}-undefined ${wl}suppress'
-         ;;
-       *) # Darwin 1.3 on
-         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
-           allow_undefined_flag_F77=3D'${wl}-flat_namespace ${wl}-undefine=
d ${wl}suppress'
-         else
-           case ${MACOSX_DEPLOYMENT_TARGET} in
-             10.[012])
-               allow_undefined_flag_F77=3D'${wl}-flat_namespace ${wl}-unde=
fined ${wl}suppress'
-               ;;
-             10.*)
-               allow_undefined_flag_F77=3D'${wl}-undefined ${wl}dynamic_lo=
okup'
-               ;;
-           esac
-         fi
-         ;;
-      esac
-      archive_cmds_need_lc_F77=3Dno
-      hardcode_direct_F77=3Dno
-      hardcode_automatic_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dunsupported
-      whole_archive_flag_spec_F77=3D''
-      link_all_deplibs_F77=3Dyes
-    if test "$GCC" =3D yes ; then
-    	output_verbose_link_cmd=3D'echo'
-        archive_cmds_F77=3D'$CC -dynamiclib $allow_undefined_flag -o $lib =
$libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
-      module_cmds_F77=3D'$CC $allow_undefined_flag -o $lib -bundle $libobj=
s $deplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doe=
sn't exist in older darwin lds
-      archive_expsym_cmds_F77=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,=
^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~=
$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_f=
lags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${lib=
name}-symbols.expsym ${lib}'
-      module_expsym_cmds_F77=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^=
\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$=
CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~=
nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    else
-      case $cc_basename in
-        xlc*)
-         output_verbose_link_cmd=3D'echo'
-         archive_cmds_F77=3D'$CC -qmkshrobj $allow_undefined_flag -o $lib =
$libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$son=
ame` $verstring'
-         module_cmds_F77=3D'$CC $allow_undefined_flag -o $lib -bundle $lib=
objs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it=
 doesn't exist in older darwin lds
-         archive_expsym_cmds_F77=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e =
"s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.exps=
ym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler=
_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_=
objdir/${libname}-symbols.expsym ${lib}'
-          module_expsym_cmds_F77=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e =
"s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.exps=
ym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_fl=
ags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          ;;
-       *)
-         ld_shlibs_F77=3Dno
-          ;;
-      esac
-    fi
-      ;;
-
-    dgux*)
-      archive_cmds_F77=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    freebsd1*)
-      ld_shlibs_F77=3Dno
-      ;;
-
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ construct=
or
-    # support.  Future versions do this automatically, but an explicit c++=
rt0.o
-    # does not break anything, and helps significantly (at the cost of a l=
ittle
-    # extra space).
-    freebsd2.2*)
-      archive_cmds_F77=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linke=
r_flags /usr/lib/c++rt0.o'
-      hardcode_libdir_flag_spec_F77=3D'-R$libdir'
-      hardcode_direct_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
-      archive_cmds_F77=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linke=
r_flags'
-      hardcode_direct_F77=3Dyes
-      hardcode_minus_L_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | kfreebsd*-gnu | dragonfly*)
-      archive_cmds_F77=3D'$CC -shared -o $lib $libobjs $deplibs $compiler_=
flags'
-      hardcode_libdir_flag_spec_F77=3D'-R$libdir'
-      hardcode_direct_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    hpux9*)
-      if test "$GCC" =3D yes; then
-	archive_cmds_F77=3D'$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b =
${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_=
flags~test $output_objdir/$soname =3D $lib || mv $output_objdir/$soname $li=
b'
-      else
-	archive_cmds_F77=3D'$rm $output_objdir/$soname~$LD -b +b $install_libdir =
-o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objd=
ir/$soname =3D $lib || mv $output_objdir/$soname $lib'
-      fi
-      hardcode_libdir_flag_spec_F77=3D'${wl}+b ${wl}$libdir'
-      hardcode_libdir_separator_F77=3D:
-      hardcode_direct_F77=3Dyes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      hardcode_minus_L_F77=3Dyes
-      export_dynamic_flag_spec_F77=3D'${wl}-E'
-      ;;
-
-    hpux10*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
-	archive_cmds_F77=3D'$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$=
install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_F77=3D'$LD -b +h $soname +b $install_libdir -o $lib $libobjs=
 $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" =3D no; then
-	hardcode_libdir_flag_spec_F77=3D'${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_F77=3D:
-
-	hardcode_direct_F77=3Dyes
-	export_dynamic_flag_spec_F77=3D'${wl}-E'
-
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	hardcode_minus_L_F77=3Dyes
-      fi
-      ;;
-
-    hpux11*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_F77=3D'$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $=
deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_F77=3D'$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpa=
th -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds_F77=3D'$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl=
}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_F77=3D'$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $depli=
bs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_F77=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o=
 $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds_F77=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_l=
ibdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" =3D no; then
-	hardcode_libdir_flag_spec_F77=3D'${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_F77=3D:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  hardcode_libdir_flag_spec_ld_F77=3D'+b $libdir'
-	  hardcode_direct_F77=3Dno
-	  hardcode_shlibpath_var_F77=3Dno
-	  ;;
-	*)
-	  hardcode_direct_F77=3Dyes
-	  export_dynamic_flag_spec_F77=3D'${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  hardcode_minus_L_F77=3Dyes
-	  ;;
-	esac
-      fi
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      if test "$GCC" =3D yes; then
-	archive_cmds_F77=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$ve=
rstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	archive_cmds_F77=3D'$LD -shared $libobjs $deplibs $linker_flags -soname $=
soname `test -n "$verstring" && echo -set_version $verstring` -update_regis=
try ${output_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec_ld_F77=3D'-rpath $libdir'
-      fi
-      hardcode_libdir_flag_spec_F77=3D'${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_F77=3D:
-      link_all_deplibs_F77=3Dyes
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	archive_cmds_F77=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linker_fla=
gs'  # a.out
-      else
-	archive_cmds_F77=3D'$LD -shared -o $lib $libobjs $deplibs $linker_flags' =
     # ELF
-      fi
-      hardcode_libdir_flag_spec_F77=3D'-R$libdir'
-      hardcode_direct_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    newsos6)
-      archive_cmds_F77=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_direct_F77=3Dyes
-      hardcode_libdir_flag_spec_F77=3D'${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_F77=3D:
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    openbsd*)
-      hardcode_direct_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dno
-      if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host=
_os-$host_cpu" =3D "openbsd2.8-powerpc"; then
-	archive_cmds_F77=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $comp=
iler_flags'
-	archive_expsym_cmds_F77=3D'$CC -shared $pic_flag -o $lib $libobjs $deplib=
s $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	hardcode_libdir_flag_spec_F77=3D'${wl}-rpath,$libdir'
-	export_dynamic_flag_spec_F77=3D'${wl}-E'
-      else
-       case $host_os in
-	 openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
-	   archive_cmds_F77=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linker_=
flags'
-	   hardcode_libdir_flag_spec_F77=3D'-R$libdir'
-	   ;;
-	 *)
-	   archive_cmds_F77=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $c=
ompiler_flags'
-	   hardcode_libdir_flag_spec_F77=3D'${wl}-rpath,$libdir'
-	   ;;
-       esac
-      fi
-      ;;
-
-    os2*)
-      hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-      hardcode_minus_L_F77=3Dyes
-      allow_undefined_flag_F77=3Dunsupported
-      archive_cmds_F77=3D'$echo "LIBRARY $libname INITINSTANCE" > $output_=
objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$lib=
name.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED=
" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.d=
ef~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $li=
b $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      old_archive_From_new_cmds_F77=3D'emximp -o $output_objdir/$libname.a=
 $output_objdir/$libname.def'
-      ;;
-
-    osf3*)
-      if test "$GCC" =3D yes; then
-	allow_undefined_flag_F77=3D' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_F77=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs =
$compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${w=
l}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}=
/so_locations -o $lib'
-      else
-	allow_undefined_flag_F77=3D' -expect_unresolved \*'
-	archive_cmds_F77=3D'$LD -shared${allow_undefined_flag} $libobjs $deplibs =
$linker_flags -soname $soname `test -n "$verstring" && echo -set_version $v=
erstring` -update_registry ${output_objdir}/so_locations -o $lib'
-      fi
-      hardcode_libdir_flag_spec_F77=3D'${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_F77=3D:
-      ;;
-
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" =3D yes; then
-	allow_undefined_flag_F77=3D' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_F77=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs =
$compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" =
&& echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${out=
put_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec_F77=3D'${wl}-rpath ${wl}$libdir'
-      else
-	allow_undefined_flag_F77=3D' -expect_unresolved \*'
-	archive_cmds_F77=3D'$LD -shared${allow_undefined_flag} $libobjs $deplibs =
$linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_vers=
ion $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
-	archive_expsym_cmds_F77=3D'for i in `cat $export_symbols`; do printf "%s =
%s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs=
 $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verst=
ring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
-
-	# Both c and cxx compiler support -rpath directly
-	hardcode_libdir_flag_spec_F77=3D'-rpath $libdir'
-      fi
-      hardcode_libdir_separator_F77=3D:
-      ;;
-
-    solaris*)
-      no_undefined_flag_F77=3D' -z text'
-      if test "$GCC" =3D yes; then
-	wlarc=3D'${wl}'
-	archive_cmds_F77=3D'$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $de=
plibs $compiler_flags'
-	archive_expsym_cmds_F77=3D'$echo "{ global:" > $lib.exp~cat $export_symbo=
ls | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs=
 $deplibs $compiler_flags~$rm $lib.exp'
-      else
-	wlarc=3D''
-	archive_cmds_F77=3D'$LD -G${allow_undefined_flag} -h $soname -o $lib $lib=
objs $deplibs $linker_flags'
-	archive_expsym_cmds_F77=3D'$echo "{ global:" > $lib.exp~cat $export_symbo=
ls | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-  	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $=
deplibs $linker_flags~$rm $lib.exp'
-      fi
-      hardcode_libdir_flag_spec_F77=3D'-R$libdir'
-      hardcode_shlibpath_var_F77=3Dno
-      case $host_os in
-      solaris2.[0-5] | solaris2.[0-5].*) ;;
-      *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  whole_archive_flag_spec_F77=3D'-z allextract$convenience -z defaultext=
ract' ;;
- 	*)
- 	  whole_archive_flag_spec_F77=3D'${wl}-z ${wl}allextract`for conv in $co=
nvenience\"\"; do test -n \"$conv\" && new_convenience=3D\"$new_convenience=
,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
- 	esac ;;
-      esac
-      link_all_deplibs_F77=3Dyes
-      ;;
-
-    sunos4*)
-      if test "x$host_vendor" =3D xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	archive_cmds_F77=3D'$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $com=
piler_flags'
-      else
-	archive_cmds_F77=3D'$LD -assert pure-text -Bstatic -o $lib $libobjs $depl=
ibs $linker_flags'
-      fi
-      hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-      hardcode_direct_F77=3Dyes
-      hardcode_minus_L_F77=3Dyes
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    sysv4)
-      case $host_vendor in
-	sni)
-	  archive_cmds_F77=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $linker=
_flags'
-	  hardcode_direct_F77=3Dyes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  archive_cmds_F77=3D'$LD -G -o $lib $libobjs $deplibs $linker_flags'
-	  reload_cmds_F77=3D'$CC -r -o $output$reload_objs'
-	  hardcode_direct_F77=3Dno
-        ;;
-	motorola)
-	  archive_cmds_F77=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $linker=
_flags'
-	  hardcode_direct_F77=3Dno #Motorola manual says yes, but my tests say th=
ey lie
-	;;
-      esac
-      runpath_var=3D'LD_RUN_PATH'
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    sysv4.3*)
-      archive_cmds_F77=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_shlibpath_var_F77=3Dno
-      export_dynamic_flag_spec_F77=3D'-Bexport'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	archive_cmds_F77=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $linker_f=
lags'
-	hardcode_shlibpath_var_F77=3Dno
-	runpath_var=3DLD_RUN_PATH
-	hardcode_runpath_var=3Dyes
-	ld_shlibs_F77=3Dyes
-      fi
-      ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
-      no_undefined_flag_F77=3D'${wl}-z,text'
-      archive_cmds_need_lc_F77=3Dno
-      hardcode_shlibpath_var_F77=3Dno
-      runpath_var=3D'LD_RUN_PATH'
-
-      if test "$GCC" =3D yes; then
-	archive_cmds_F77=3D'$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs=
 $compiler_flags'
-	archive_expsym_cmds_F77=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl=
}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_F77=3D'$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $com=
piler_flags'
-	archive_expsym_cmds_F77=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$=
soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      no_undefined_flag_F77=3D'${wl}-z,text'
-      allow_undefined_flag_F77=3D'${wl}-z,nodefs'
-      archive_cmds_need_lc_F77=3Dno
-      hardcode_shlibpath_var_F77=3Dno
-      hardcode_libdir_flag_spec_F77=3D'`test -z "$SCOABSPATH" && echo ${wl=
}-R,$libdir`'
-      hardcode_libdir_separator_F77=3D':'
-      link_all_deplibs_F77=3Dyes
-      export_dynamic_flag_spec_F77=3D'${wl}-Bexport'
-      runpath_var=3D'LD_RUN_PATH'
-
-      if test "$GCC" =3D yes; then
-	archive_cmds_F77=3D'$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/=
}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl=
}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $co=
mpiler_flags'
-      else
-	archive_cmds_F77=3D'$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$son=
ame -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_F77=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\=
${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compile=
r_flags'
-      fi
-      ;;
-
-    uts4*)
-      archive_cmds_F77=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_libdir_flag_spec_F77=3D'-L$libdir'
-      hardcode_shlibpath_var_F77=3Dno
-      ;;
-
-    *)
-      ld_shlibs_F77=3Dno
-      ;;
-    esac
-  fi
-
-{ echo "$as_me:$LINENO: result: $ld_shlibs_F77" >&5
-echo "${ECHO_T}$ld_shlibs_F77" >&6; }
-test "$ld_shlibs_F77" =3D no && can_build_shared=3Dno
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$archive_cmds_need_lc_F77" in
-x|xyes)
-  # Assume -lc should be added
-  archive_cmds_need_lc_F77=3Dyes
-
-  if test "$enable_shared" =3D yes && test "$GCC" =3D yes; then
-    case $archive_cmds_F77 in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly li=
nked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO=
_C" >&6; }
-      $rm conftest*
-      printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-      if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } 2>conftest.err; then
-        soname=3Dconftest
-        lib=3Dconftest
-        libobjs=3Dconftest.$ac_objext
-        deplibs=3D
-        wl=3D$lt_prog_compiler_wl_F77
-	pic_flag=3D$lt_prog_compiler_pic_F77
-        compiler_flags=3D-v
-        linker_flags=3D-v
-        verstring=3D
-        output_objdir=3D.
-        libname=3Dconftest
-        lt_save_allow_undefined_flag=3D$allow_undefined_flag_F77
-        allow_undefined_flag_F77=3D
-        if { (eval echo "$as_me:$LINENO: \"$archive_cmds_F77 2\>\&1 \| gre=
p \" -lc \" \>/dev/null 2\>\&1\"") >&5
-  (eval $archive_cmds_F77 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-        then
-	  archive_cmds_need_lc_F77=3Dno
-        else
-	  archive_cmds_need_lc_F77=3Dyes
-        fi
-        allow_undefined_flag_F77=3D$lt_save_allow_undefined_flag
-      else
-        cat conftest.err 1>&5
-      fi
-      $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_F77" >&5
-echo "${ECHO_T}$archive_cmds_need_lc_F77" >&6; }
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
-library_names_spec=3D
-libname_spec=3D'lib$name'
-soname_spec=3D
-shrext_cmds=3D".so"
-postinstall_cmds=3D
-postuninstall_cmds=3D
-finish_cmds=3D
-finish_eval=3D
-shlibpath_var=3D
-shlibpath_overrides_runpath=3Dunknown
-version_type=3Dnone
-dynamic_linker=3D"$host_os ld.so"
-sys_lib_dlsearch_path_spec=3D"/lib /usr/lib"
-if test "$GCC" =3D yes; then
-  sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^libraries:" =
| $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-  if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that shou=
ld
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED -e=
 's/;/ /g'`
-  else
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED  -=
e "s/$PATH_SEPARATOR/ /g"`
-  fi
-else
-  sys_lib_search_path_spec=3D"/lib /usr/lib /usr/local/lib"
-fi
-need_lib_prefix=3Dunknown
-hardcode_into_libs=3Dno
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=3Dunknown
-
-case $host_os in
-aix3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $libna=
me.a'
-  shlibpath_var=3DLIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the n=
ame.
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  ;;
-
-aix4* | aix5*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  hardcode_into_libs=3Dyes
-  if test "$host_cpu" =3D ia64; then
-    # AIX 5 supports IA64
-    library_names_spec=3D'${libname}${release}${shared_ext}$major ${libnam=
e}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[01] | aix4.[01].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ =3D=3D 2 && __GNUC_MINOR__ =
>=3D 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
-	:
-      else
-	can_build_shared=3Dno
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not h=
ardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" =3D yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec=3D'${libname}${release}.a $libname.a'
-      soname_spec=3D'${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=3DLIBPATH
-  fi
-  ;;
-
-amigaos*)
-  library_names_spec=3D'$libname.ixlibrary $libname.a'
-  # Create ${libname}_ixlibrary.a entries in /sys/libs.
-  finish_eval=3D'for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libna=
me=3D`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; te=
st $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib =
${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a =
|| exit 1; done'
-  ;;
-
-beos*)
-  library_names_spec=3D'${libname}${shared_ext}'
-  dynamic_linker=3D"$host_os ld.so"
-  shlibpath_var=3DLIBRARY_PATH
-  ;;
-
-bsdi[45]*)
-  version_type=3Dlinux
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/shlib /usr/lib /usr/X11/lib /usr/contrib/li=
b /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec=3D"/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32*)
-  version_type=3Dwindows
-  shrext_cmds=3D".dll"
-  need_version=3Dno
-  need_lib_prefix=3Dno
-
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32*)
-    library_names_spec=3D'$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds=3D'base_file=3D`basename \${file}`~
-      dlpath=3D`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dl=
name'\''`~
-      dldir=3D$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
-    postuninstall_cmds=3D'dldll=3D`$SHELL 2>&1 -c '\''. $file; echo \$dlna=
me'\''`~
-      dlpath=3D$dir/\$dldll~
-       $rm \$dlpath'
-    shlibpath_overrides_runpath=3Dyes
-
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec=3D'`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${relea=
se} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D"/usr/lib /lib/w32api /lib /usr/local/lib"
-      ;;
-    mingw*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${ve=
rsuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^librarie=
s:" | $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-      if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null;=
 then
-        # It is most probably a Windows format PATH printed by
-        # mingw gcc, but we are running on Cygwin. Gcc prints its search
-        # path with ; separators, and with drive letters. We can handle the
-        # drive letters (cygwin fileutils understands them), so leave them,
-        # especially as we might pass files found there to a mingw objdump,
-        # which wouldn't understand a cygwinified path. Ahh.
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D  -e "s/$PATH_SEPARATOR/ /g"`
-      fi
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec=3D'`echo ${libname} | sed -e 's/^lib/pw/'``echo $=
{release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    ;;
-
-  *)
-    library_names_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'=
`${versuffix}${shared_ext} $libname.lib'
-    ;;
-  esac
-  dynamic_linker=3D'Win32 ld.exe'
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=3DPATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker=3D"$host_os dyld"
-  version_type=3Ddarwin
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${major}$shared_ext ${libname}=
$shared_ext ${libname}${release}${versuffix}$shared_ext'
-  soname_spec=3D'${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=3Dyes
-  shlibpath_var=3DDYLD_LIBRARY_PATH
-  shrext_cmds=3D'`test .$module =3D .yes && echo .so || echo .dylib`'
-  # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
-  if test "$GCC" =3D yes; then
-    sys_lib_search_path_spec=3D`$CC -print-search-dirs | tr "\n" "$PATH_SE=
PARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^librar=
ies:" | sed -e "s/^libraries://" -e "s,=3D/,/,g" -e "s,$PATH_SEPARATOR, ,g"=
 -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
-  else
-    sys_lib_search_path_spec=3D'/lib /usr/lib /usr/local/lib'
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-freebsd1*)
-  dynamic_linker=3Dno
-  ;;
-
-kfreebsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=3D`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[123]*) objformat=3Daout ;;
-    *) objformat=3Delf ;;
-    esac
-  fi
-  version_type=3Dfreebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=3Dno
-      need_lib_prefix=3Dno
-      ;;
-    freebsd-*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $l=
ibname${shared_ext}$versuffix'
-      need_version=3Dyes
-      ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_os in
-  freebsd2*)
-    shlibpath_overrides_runpath=3Dyes
-    ;;
-  freebsd3.[01]* | freebsdelf3.[01]*)
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=3Dno
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  esac
-  ;;
-
-gnu*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuse=
s to
-  # link against other versions.
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  case $host_cpu in
-  ia64*)
-    shrext_cmds=3D'.so'
-    hardcode_into_libs=3Dyes
-    dynamic_linker=3D"$host_os dld.so"
-    shlibpath_var=3DLD_LIBRARY_PATH
-    shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" =3D X32; then
-      sys_lib_search_path_spec=3D"/usr/lib/hpux32 /usr/local/lib/hpux32 /u=
sr/local/lib"
-    else
-      sys_lib_search_path_spec=3D"/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-    ;;
-   hppa*64*)
-     shrext_cmds=3D'.sl'
-     hardcode_into_libs=3Dyes
-     dynamic_linker=3D"$host_os dld.sl"
-     shlibpath_var=3DLD_LIBRARY_PATH # How should we handle SHLIB_PATH
-     shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-     library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${l=
ibname}${release}${shared_ext}$major $libname${shared_ext}'
-     soname_spec=3D'${libname}${release}${shared_ext}$major'
-     sys_lib_search_path_spec=3D"/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-     sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-     ;;
-   *)
-    shrext_cmds=3D'.sl'
-    dynamic_linker=3D"$host_os dld.sl"
-    shlibpath_var=3DSHLIB_PATH
-    shlibpath_overrides_runpath=3Dno # +s is required to enable SHLIB_PATH
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
-  postinstall_cmds=3D'chmod 555 $lib'
-  ;;
-
-interix3*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  dynamic_linker=3D'Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=3Dnonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" =3D yes; then
-		version_type=3Dlinux
-	else
-		version_type=3Dirix
-	fi ;;
-  esac
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libnam=
e${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff=3D shlibsuff=3D
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff=3D shlibsuff=3D libmagic=3D32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=3D32 shlibsuff=3DN32 libmagic=3DN32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=3D64 shlibsuff=3D64 libmagic=3D64-bit;;
-    *) libsuff=3D shlibsuff=3D libmagic=3Dnever-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=3Dno
-  sys_lib_search_path_spec=3D"/usr/lib${libsuff} /lib${libsuff} /usr/local=
/lib${libsuff}"
-  sys_lib_dlsearch_path_spec=3D"/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=3Dyes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=3Dno
-  ;;
-
-# This must be Linux ELF.
-linux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=3Dyes
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=3D`awk '/^include / { system(sprintf("cd /etc; cat %s", \$=
2)); skip =3D 1; } { if (!skip) print \$0; skip =3D 0; }' < /etc/ld.so.conf=
 | $SED -e 's/#.*//;s/[:,	]/ /g;s/=3D[^=3D]*$//;s/=3D[^=3D ]* / /g;/^$/d' |=
 tr '\n' ' '`
-    sys_lib_dlsearch_path_spec=3D"/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker=3D'GNU/Linux ld.so'
-  ;;
-
-knetbsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-netbsd*)
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${shared_ext}$versuffix'
-    finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker=3D'NetBSD (a.out) ld.so'
-  else
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    dynamic_linker=3D'NetBSD ld.elf_so'
-  fi
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  ;;
-
-newsos6)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-nto-qnx*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-openbsd*)
-  version_type=3Dsunos
-  sys_lib_dlsearch_path_spec=3D"/usr/lib"
-  need_lib_prefix=3Dno
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=3Dyes ;;
-    *)                         need_version=3Dno  ;;
-  esac
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=3Dno
-	;;
-      *)
-	shlibpath_overrides_runpath=3Dyes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=3Dyes
-  fi
-  ;;
-
-os2*)
-  libname_spec=3D'$name'
-  shrext_cmds=3D".dll"
-  need_lib_prefix=3Dno
-  library_names_spec=3D'$libname${shared_ext} $libname.a'
-  dynamic_linker=3D'OS/2 ld.exe'
-  shlibpath_var=3DLIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=3Dosf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /=
usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec=3D"$sys_lib_search_path_spec"
-  ;;
-
-solaris*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  # ldd complains unless libraries are executable
-  postinstall_cmds=3D'chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=3Dsunos
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    need_lib_prefix=3Dno
-  fi
-  need_version=3Dyes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=3Dno
-      need_lib_prefix=3Dno
-      export_dynamic_flag_spec=3D'${wl}-Blargedynsym'
-      runpath_var=3DLD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=3Dno
-      ;;
-    motorola)
-      need_lib_prefix=3Dno
-      need_version=3Dno
-      shlibpath_overrides_runpath=3Dno
-      sys_lib_search_path_spec=3D'/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=3Dlinux
-    library_names_spec=3D'$libname${shared_ext}.$versuffix $libname${share=
d_ext}.$major $libname${shared_ext}'
-    soname_spec=3D'$libname${shared_ext}.$major'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=3Dfreebsd-elf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    sys_lib_search_path_spec=3D'/usr/local/lib /usr/gnu/lib /usr/ccs/lib /=
usr/lib /lib'
-    shlibpath_overrides_runpath=3Dno
-  else
-    sys_lib_search_path_spec=3D'/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=3Dyes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec=3D"$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/lib'
-  ;;
-
-uts4*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=3Dno
-  ;;
-esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
-test "$dynamic_linker" =3D no && can_build_shared=3Dno
-
-variables_saved_for_relink=3D"PATH $shlibpath_var $runpath_var"
-if test "$GCC" =3D yes; then
-  variables_saved_for_relink=3D"$variables_saved_for_relink GCC_EXEC_PREFI=
X COMPILER_PATH LIBRARY_PATH"
-fi
-
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into progra=
ms" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECH=
O_C" >&6; }
-hardcode_action_F77=3D
-if test -n "$hardcode_libdir_flag_spec_F77" || \
-   test -n "$runpath_var_F77" || \
-   test "X$hardcode_automatic_F77" =3D "Xyes" ; then
-
-  # We can hardcode non-existant directories.
-  if test "$hardcode_direct_F77" !=3D no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, F77)" !=3D no &&
-     test "$hardcode_minus_L_F77" !=3D no; then
-    # Linking always hardcodes the temporary library directory.
-    hardcode_action_F77=3Drelink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    hardcode_action_F77=3Dimmediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  hardcode_action_F77=3Dunsupported
-fi
-{ echo "$as_me:$LINENO: result: $hardcode_action_F77" >&5
-echo "${ECHO_T}$hardcode_action_F77" >&6; }
-
-if test "$hardcode_action_F77" =3D relink; then
-  # Fast installation is not supported
-  enable_fast_install=3Dno
-elif test "$shlibpath_overrides_runpath" =3D yes ||
-     test "$enable_shared" =3D no; then
-  # Fast installation is not necessary
-  enable_fast_install=3Dneedless
-fi
-
-
-# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our comm=
ands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTC=
FLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    compiler_F77 \
-    CC_F77 \
-    LD_F77 \
-    lt_prog_compiler_wl_F77 \
-    lt_prog_compiler_pic_F77 \
-    lt_prog_compiler_static_F77 \
-    lt_prog_compiler_no_builtin_flag_F77 \
-    export_dynamic_flag_spec_F77 \
-    thread_safe_flag_spec_F77 \
-    whole_archive_flag_spec_F77 \
-    enable_shared_with_static_runtimes_F77 \
-    old_archive_cmds_F77 \
-    old_archive_from_new_cmds_F77 \
-    predep_objects_F77 \
-    postdep_objects_F77 \
-    predeps_F77 \
-    postdeps_F77 \
-    compiler_lib_search_path_F77 \
-    archive_cmds_F77 \
-    archive_expsym_cmds_F77 \
-    postinstall_cmds_F77 \
-    postuninstall_cmds_F77 \
-    old_archive_from_expsyms_cmds_F77 \
-    allow_undefined_flag_F77 \
-    no_undefined_flag_F77 \
-    export_symbols_cmds_F77 \
-    hardcode_libdir_flag_spec_F77 \
-    hardcode_libdir_flag_spec_ld_F77 \
-    hardcode_libdir_separator_F77 \
-    hardcode_automatic_F77 \
-    module_cmds_F77 \
-    module_expsym_cmds_F77 \
-    lt_cv_prog_compiler_c_o_F77 \
-    exclude_expsyms_F77 \
-    include_expsyms_F77; do
-
-    case $var in
-    old_archive_cmds_F77 | \
-    old_archive_from_new_cmds_F77 | \
-    archive_cmds_F77 | \
-    archive_expsym_cmds_F77 | \
-    module_cmds_F77 | \
-    module_expsym_cmds_F77 | \
-    old_archive_from_expsyms_cmds_F77 | \
-    export_symbols_cmds_F77 | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quot=
e_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
-      ;;
-    *)
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_s=
ubst\"\`\\\""
-      ;;
-    esac
-  done
-
-  case $lt_echo in
-  *'\$0 --fallback-echo"')
-    lt_echo=3D`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$=
/$0 --fallback-echo"/'`
-    ;;
-  esac
-
-cfgfile=3D"$ofile"
-
-  cat <<__EOF__ >> "$cfgfile"
-# ### BEGIN LIBTOOL TAG CONFIG: $tagname
-
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed=
 1q`:
-
-# Shell to use when invoking shell scripts.
-SHELL=3D$lt_SHELL
-
-# Whether or not to build shared libraries.
-build_libtool_libs=3D$enable_shared
-
-# Whether or not to build static libraries.
-build_old_libs=3D$enable_static
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=3D$archive_cmds_need_lc_F77
-
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=3D$enable_shared_with_static_runti=
mes_F77
-
-# Whether or not to optimize for fast installation.
-fast_install=3D$enable_fast_install
-
-# The host system.
-host_alias=3D$host_alias
-host=3D$host
-host_os=3D$host_os
-
-# The build system.
-build_alias=3D$build_alias
-build=3D$build
-build_os=3D$build_os
-
-# An echo program that does not interpret backslashes.
-echo=3D$lt_echo
-
-# The archiver.
-AR=3D$lt_AR
-AR_FLAGS=3D$lt_AR_FLAGS
-
-# A C compiler.
-LTCC=3D$lt_LTCC
-
-# LTCC compiler flags.
-LTCFLAGS=3D$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=3D$lt_compiler_F77
-
-# Is the compiler the GNU C compiler?
-with_gcc=3D$GCC_F77
-
-# An ERE matcher.
-EGREP=3D$lt_EGREP
-
-# The linker used to build libraries.
-LD=3D$lt_LD_F77
-
-# Whether we need hard or soft links.
-LN_S=3D$lt_LN_S
-
-# A BSD-compatible nm program.
-NM=3D$lt_NM
-
-# A symbol stripping program
-STRIP=3D$lt_STRIP
-
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=3D$MAGIC_CMD
-
-# Used on cygwin: DLL creation program.
-DLLTOOL=3D"$DLLTOOL"
-
-# Used on cygwin: object dumper.
-OBJDUMP=3D"$OBJDUMP"
-
-# Used on cygwin: assembler.
-AS=3D"$AS"
-
-# The name of the directory that contains temporary libtool files.
-objdir=3D$objdir
-
-# How to create reloadable object files.
-reload_flag=3D$lt_reload_flag
-reload_cmds=3D$lt_reload_cmds
-
-# How to pass a linker flag through the compiler.
-wl=3D$lt_lt_prog_compiler_wl_F77
-
-# Object file suffix (normally "o").
-objext=3D"$ac_objext"
-
-# Old archive suffix (normally "a").
-libext=3D"$libext"
-
-# Shared library suffix (normally ".so").
-shrext_cmds=3D'$shrext_cmds'
-
-# Executable file suffix (normally "").
-exeext=3D"$exeext"
-
-# Additional compiler flags for building library objects.
-pic_flag=3D$lt_lt_prog_compiler_pic_F77
-pic_mode=3D$pic_mode
-
-# What is the maximum length of a command?
-max_cmd_len=3D$lt_cv_sys_max_cmd_len
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=3D$lt_lt_cv_prog_compiler_c_o_F77
-
-# Must we lock files when doing compilation?
-need_locks=3D$lt_need_locks
-
-# Do we need the lib prefix for modules?
-need_lib_prefix=3D$need_lib_prefix
-
-# Do we need a version for libraries?
-need_version=3D$need_version
-
-# Whether dlopen is supported.
-dlopen_support=3D$enable_dlopen
-
-# Whether dlopen of programs is supported.
-dlopen_self=3D$enable_dlopen_self
-
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=3D$enable_dlopen_self_static
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=3D$lt_lt_prog_compiler_static_F77
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=3D$lt_lt_prog_compiler_no_builtin_flag_F77
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=3D$lt_export_dynamic_flag_spec_F77
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=3D$lt_whole_archive_flag_spec_F77
-
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=3D$lt_thread_safe_flag_spec_F77
-
-# Library versioning type.
-version_type=3D$version_type
-
-# Format of library name prefix.
-libname_spec=3D$lt_libname_spec
-
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=3D$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=3D$lt_soname_spec
-
-# Commands used to build and install an old-style archive.
-RANLIB=3D$lt_RANLIB
-old_archive_cmds=3D$lt_old_archive_cmds_F77
-old_postinstall_cmds=3D$lt_old_postinstall_cmds
-old_postuninstall_cmds=3D$lt_old_postuninstall_cmds
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=3D$lt_old_archive_from_new_cmds_F77
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=3D$lt_old_archive_from_expsyms_cmds_F77
-
-# Commands used to build and install a shared archive.
-archive_cmds=3D$lt_archive_cmds_F77
-archive_expsym_cmds=3D$lt_archive_expsym_cmds_F77
-postinstall_cmds=3D$lt_postinstall_cmds
-postuninstall_cmds=3D$lt_postuninstall_cmds
-
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=3D$lt_module_cmds_F77
-module_expsym_cmds=3D$lt_module_expsym_cmds_F77
-
-# Commands to strip libraries.
-old_striplib=3D$lt_old_striplib
-striplib=3D$lt_striplib
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=3D$lt_predep_objects_F77
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=3D$lt_postdep_objects_F77
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=3D$lt_predeps_F77
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=3D$lt_postdeps_F77
-
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=3D$lt_compiler_lib_search_path_F77
-
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=3D$lt_deplibs_check_method
-
-# Command to use when deplibs_check_method =3D=3D file_magic.
-file_magic_cmd=3D$lt_file_magic_cmd
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=3D$lt_allow_undefined_flag_F77
-
-# Flag that forces no undefined symbols.
-no_undefined_flag=3D$lt_no_undefined_flag_F77
-
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=3D$lt_finish_cmds
-
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=3D$lt_finish_eval
-
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=3D$lt_lt_cv_sys_global_symbol_pipe
-
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=3D$lt_lt_cv_sys_global_symbol_to_cdecl
-
-# Transform the output of nm in a C name address pair
-global_symbol_to_c_name_address=3D$lt_lt_cv_sys_global_symbol_to_c_name_ad=
dress
-
-# This is the shared library runtime path variable.
-runpath_var=3D$runpath_var
-
-# This is the shared library path variable.
-shlibpath_var=3D$shlibpath_var
-
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=3D$shlibpath_overrides_runpath
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=3D$hardcode_action_F77
-
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=3D$hardcode_into_libs
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist.
-hardcode_libdir_flag_spec=3D$lt_hardcode_libdir_flag_spec_F77
-
-# If ld is used when linking, flag to hardcode \$libdir into
-# a binary during linking. This must work even if \$libdir does
-# not exist.
-hardcode_libdir_flag_spec_ld=3D$lt_hardcode_libdir_flag_spec_ld_F77
-
-# Whether we need a single -rpath flag with a separated argument.
-hardcode_libdir_separator=3D$lt_hardcode_libdir_separator_F77
-
-# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DI=
R into the
-# resulting binary.
-hardcode_direct=3D$hardcode_direct_F77
-
-# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
-# resulting binary.
-hardcode_minus_L=3D$hardcode_minus_L_F77
-
-# Set to yes if using SHLIBPATH_VAR=3DDIR during linking hardcodes DIR into
-# the resulting binary.
-hardcode_shlibpath_var=3D$hardcode_shlibpath_var_F77
-
-# Set to yes if building a shared library automatically hardcodes DIR into=
 the library
-# and all subsequent libraries and executables linked against it.
-hardcode_automatic=3D$hardcode_automatic_F77
-
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at relink time.
-variables_saved_for_relink=3D"$variables_saved_for_relink"
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=3D$link_all_deplibs_F77
-
-# Compile-time system search path for libraries
-sys_lib_search_path_spec=3D$lt_sys_lib_search_path_spec
-
-# Run-time system search path for libraries
-sys_lib_dlsearch_path_spec=3D$lt_sys_lib_dlsearch_path_spec
-
-# Fix the shell variable \$srcfile for the compiler.
-fix_srcfile_path=3D"$fix_srcfile_path_F77"
-
-# Set to yes if exported symbols are required.
-always_export_symbols=3D$always_export_symbols_F77
-
-# The commands to list exported symbols.
-export_symbols_cmds=3D$lt_export_symbols_cmds_F77
-
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=3D$lt_extract_expsyms_cmds
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=3D$lt_exclude_expsyms_F77
-
-# Symbols that must always be exported.
-include_expsyms=3D$lt_include_expsyms_F77
-
-# ### END LIBTOOL TAG CONFIG: $tagname
-
-__EOF__
-
-
-else
-  # If there is no Makefile yet, we rely on a make rule to execute
-  # `config.status --recheck' to rerun these tests and create the
-  # libtool script then.
-  ltmain_in=3D`echo $ltmain | sed -e 's/\.sh$/.in/'`
-  if test -f "$ltmain_in"; then
-    test -f Makefile && make "$ltmain"
-  fi
-fi
-
-
-ac_ext=3Dc
-ac_cpp=3D'$CPP $CPPFLAGS'
-ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
-
-CC=3D"$lt_save_CC"
-
-	else
-	  tagname=3D""
-	fi
-	;;
-
-      GCJ)
-	if test -n "$GCJ" && test "X$GCJ" !=3D "Xno"; then
-
-
-# Source file extension for Java test sources.
-ac_ext=3Djava
-
-# Object file extension for compiled Java test sources.
-objext=3Do
-objext_GCJ=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D"class foo {}\n"
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D'public class conftest { public static void mai=
n(String[] argv) {}; }\n'
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-
-# If no C compiler was specified, use CC.
-LTCC=3D${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=3D${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=3D$CC
-
-
-# save warnings/boilerplate of simple test code
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D"$CC"
-CC=3D${GCJ-"gcj"}
-compiler=3D$CC
-compiler_GCJ=3D$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
-
-
-# GCJ did not exist at the time GCC didn't implicitly link libc in.
-archive_cmds_need_lc_GCJ=3Dno
-
-old_archive_cmds_GCJ=3D$old_archive_cmds
-
-
-lt_prog_compiler_no_builtin_flag_GCJ=3D
-
-if test "$GCC" =3D yes; then
-  lt_prog_compiler_no_builtin_flag_GCJ=3D' -fno-builtin'
-
-
-{ echo "$as_me:$LINENO: checking if $compiler supports -fno-rtti -fno-exce=
ptions" >&5
-echo $ECHO_N "checking if $compiler supports -fno-rtti -fno-exceptions... =
$ECHO_C" >&6; }
-if test "${lt_cv_prog_compiler_rtti_exceptions+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_cv_prog_compiler_rtti_exceptions=3Dno
-  ac_outfile=3Dconftest.$ac_objext
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag=3D"-fno-rtti -fno-exceptions"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:17164: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=3D$?
-   cat conftest.err >&5
-   echo "$as_me:17168: \$? =3D $ac_status" >&5
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/nul=
l; then
-       lt_cv_prog_compiler_rtti_exceptions=3Dyes
-     fi
-   fi
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_rtti_exceptions" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_rtti_exceptions" >&6; }
-
-if test x"$lt_cv_prog_compiler_rtti_exceptions" =3D xyes; then
-    lt_prog_compiler_no_builtin_flag_GCJ=3D"$lt_prog_compiler_no_builtin_f=
lag_GCJ -fno-rtti -fno-exceptions"
-else
-    :
-fi
-
-fi
-
-lt_prog_compiler_wl_GCJ=3D
-lt_prog_compiler_pic_GCJ=3D
-lt_prog_compiler_static_GCJ=3D
-
-{ echo "$as_me:$LINENO: checking for $compiler option to produce PIC" >&5
-echo $ECHO_N "checking for $compiler option to produce PIC... $ECHO_C" >&6=
; }
-
-  if test "$GCC" =3D yes; then
-    lt_prog_compiler_wl_GCJ=3D'-Wl,'
-    lt_prog_compiler_static_GCJ=3D'-static'
-
-    case $host_os in
-      aix*)
-      # All AIX code is PIC.
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      fi
-      ;;
-
-    amigaos*)
-      # FIXME: we need at least 68020 code to build shared libraries, but
-      # adding the `-m68020' flag to GCC prevents building anything better,
-      # like `-m68040'.
-      lt_prog_compiler_pic_GCJ=3D'-m68020 -resident32 -malways-restore-a4'
-      ;;
-
-    beos* | cygwin* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*)
-      # PIC is the default for these OSes.
-      ;;
-
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      lt_prog_compiler_pic_GCJ=3D'-DDLL_EXPORT'
-      ;;
-
-    darwin* | rhapsody*)
-      # PIC is the default on this platform
-      # Common symbols not allowed in MH_DYLIB files
-      lt_prog_compiler_pic_GCJ=3D'-fno-common'
-      ;;
-
-    interix3*)
-      # Interix 3.x gcc -fpic/-fPIC options generate broken code.
-      # Instead, we relocate shared libraries at runtime.
-      ;;
-
-    msdosdjgpp*)
-      # Just because we use GCC doesn't mean we suddenly get shared librar=
ies
-      # on systems that don't support them.
-      lt_prog_compiler_can_build_shared_GCJ=3Dno
-      enable_shared=3Dno
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	lt_prog_compiler_pic_GCJ=3D-Kconform_pic
-      fi
-      ;;
-
-    hpux*)
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic_GCJ=3D'-fPIC'
-	;;
-      esac
-      ;;
-
-    *)
-      lt_prog_compiler_pic_GCJ=3D'-fPIC'
-      ;;
-    esac
-  else
-    # PORTME Check for flag to pass linker flags through the system compil=
er.
-    case $host_os in
-    aix*)
-      lt_prog_compiler_wl_GCJ=3D'-Wl,'
-      if test "$host_cpu" =3D ia64; then
-	# AIX 5 now supports IA64 processor
-	lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      else
-	lt_prog_compiler_static_GCJ=3D'-bnso -bI:/lib/syscalls.exp'
-      fi
-      ;;
-      darwin*)
-        # PIC is the default on this platform
-        # Common symbols not allowed in MH_DYLIB files
-       case $cc_basename in
-         xlc*)
-         lt_prog_compiler_pic_GCJ=3D'-qnocommon'
-         lt_prog_compiler_wl_GCJ=3D'-Wl,'
-         ;;
-       esac
-       ;;
-
-    mingw* | pw32* | os2*)
-      # This hack is so that the source file can tell whether it is being
-      # built for inclusion in a dll (and should export symbols for exampl=
e).
-      lt_prog_compiler_pic_GCJ=3D'-DDLL_EXPORT'
-      ;;
-
-    hpux9* | hpux10* | hpux11*)
-      lt_prog_compiler_wl_GCJ=3D'-Wl,'
-      # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but
-      # not for PA HP-UX.
-      case $host_cpu in
-      hppa*64*|ia64*)
-	# +Z the default
-	;;
-      *)
-	lt_prog_compiler_pic_GCJ=3D'+Z'
-	;;
-      esac
-      # Is there a better lt_prog_compiler_static that works with the bund=
led CC?
-      lt_prog_compiler_static_GCJ=3D'${wl}-a ${wl}archive'
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      lt_prog_compiler_wl_GCJ=3D'-Wl,'
-      # PIC (with -KPIC) is the default.
-      lt_prog_compiler_static_GCJ=3D'-non_shared'
-      ;;
-
-    newsos6)
-      lt_prog_compiler_pic_GCJ=3D'-KPIC'
-      lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      ;;
-
-    linux*)
-      case $cc_basename in
-      icc* | ecc*)
-	lt_prog_compiler_wl_GCJ=3D'-Wl,'
-	lt_prog_compiler_pic_GCJ=3D'-KPIC'
-	lt_prog_compiler_static_GCJ=3D'-static'
-        ;;
-      pgcc* | pgf77* | pgf90* | pgf95*)
-        # Portland Group compilers (*not* the Pentium gcc compiler,
-	# which looks to be a dead project)
-	lt_prog_compiler_wl_GCJ=3D'-Wl,'
-	lt_prog_compiler_pic_GCJ=3D'-fpic'
-	lt_prog_compiler_static_GCJ=3D'-Bstatic'
-        ;;
-      ccc*)
-        lt_prog_compiler_wl_GCJ=3D'-Wl,'
-        # All Alpha code is PIC.
-        lt_prog_compiler_static_GCJ=3D'-non_shared'
-        ;;
-      esac
-      ;;
-
-    osf3* | osf4* | osf5*)
-      lt_prog_compiler_wl_GCJ=3D'-Wl,'
-      # All OSF/1 code is PIC.
-      lt_prog_compiler_static_GCJ=3D'-non_shared'
-      ;;
-
-    solaris*)
-      lt_prog_compiler_pic_GCJ=3D'-KPIC'
-      lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      case $cc_basename in
-      f77* | f90* | f95*)
-	lt_prog_compiler_wl_GCJ=3D'-Qoption ld ';;
-      *)
-	lt_prog_compiler_wl_GCJ=3D'-Wl,';;
-      esac
-      ;;
-
-    sunos4*)
-      lt_prog_compiler_wl_GCJ=3D'-Qoption ld '
-      lt_prog_compiler_pic_GCJ=3D'-PIC'
-      lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      ;;
-
-    sysv4 | sysv4.2uw2* | sysv4.3*)
-      lt_prog_compiler_wl_GCJ=3D'-Wl,'
-      lt_prog_compiler_pic_GCJ=3D'-KPIC'
-      lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec ;then
-	lt_prog_compiler_pic_GCJ=3D'-Kconform_pic'
-	lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      fi
-      ;;
-
-    sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*)
-      lt_prog_compiler_wl_GCJ=3D'-Wl,'
-      lt_prog_compiler_pic_GCJ=3D'-KPIC'
-      lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      ;;
-
-    unicos*)
-      lt_prog_compiler_wl_GCJ=3D'-Wl,'
-      lt_prog_compiler_can_build_shared_GCJ=3Dno
-      ;;
-
-    uts4*)
-      lt_prog_compiler_pic_GCJ=3D'-pic'
-      lt_prog_compiler_static_GCJ=3D'-Bstatic'
-      ;;
-
-    *)
-      lt_prog_compiler_can_build_shared_GCJ=3Dno
-      ;;
-    esac
-  fi
-
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_GCJ" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_GCJ" >&6; }
-
-#
-# Check to make sure the PIC flag actually works.
-#
-if test -n "$lt_prog_compiler_pic_GCJ"; then
-
-{ echo "$as_me:$LINENO: checking if $compiler PIC flag $lt_prog_compiler_p=
ic_GCJ works" >&5
-echo $ECHO_N "checking if $compiler PIC flag $lt_prog_compiler_pic_GCJ wor=
ks... $ECHO_C" >&6; }
-if test "${lt_prog_compiler_pic_works_GCJ+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_pic_works_GCJ=3Dno
-  ac_outfile=3Dconftest.$ac_objext
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-   lt_compiler_flag=3D"$lt_prog_compiler_pic_GCJ"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   # The option is referenced via a variable to avoid confusing sed.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:17432: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>conftest.err)
-   ac_status=3D$?
-   cat conftest.err >&5
-   echo "$as_me:17436: \$? =3D $ac_status" >&5
-   if (exit $ac_status) && test -s "$ac_outfile"; then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings other than the usual output.
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
-     $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-     if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/nul=
l; then
-       lt_prog_compiler_pic_works_GCJ=3Dyes
-     fi
-   fi
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_pic_works_GCJ" >&5
-echo "${ECHO_T}$lt_prog_compiler_pic_works_GCJ" >&6; }
-
-if test x"$lt_prog_compiler_pic_works_GCJ" =3D xyes; then
-    case $lt_prog_compiler_pic_GCJ in
-     "" | " "*) ;;
-     *) lt_prog_compiler_pic_GCJ=3D" $lt_prog_compiler_pic_GCJ" ;;
-     esac
-else
-    lt_prog_compiler_pic_GCJ=3D
-     lt_prog_compiler_can_build_shared_GCJ=3Dno
-fi
-
-fi
-case $host_os in
-  # For platforms which do not support PIC, -DPIC is meaningless:
-  *djgpp*)
-    lt_prog_compiler_pic_GCJ=3D
-    ;;
-  *)
-    lt_prog_compiler_pic_GCJ=3D"$lt_prog_compiler_pic_GCJ"
-    ;;
-esac
-
-#
-# Check to make sure the static flag actually works.
-#
-wl=3D$lt_prog_compiler_wl_GCJ eval lt_tmp_static_flag=3D\"$lt_prog_compile=
r_static_GCJ\"
-{ echo "$as_me:$LINENO: checking if $compiler static flag $lt_tmp_static_f=
lag works" >&5
-echo $ECHO_N "checking if $compiler static flag $lt_tmp_static_flag works.=
.. $ECHO_C" >&6; }
-if test "${lt_prog_compiler_static_works_GCJ+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_prog_compiler_static_works_GCJ=3Dno
-   save_LDFLAGS=3D"$LDFLAGS"
-   LDFLAGS=3D"$LDFLAGS $lt_tmp_static_flag"
-   printf "$lt_simple_link_test_code" > conftest.$ac_ext
-   if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
-     # The linker can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     if test -s conftest.err; then
-       # Append any errors to the config.log.
-       cat conftest.err 1>&5
-       $echo "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp
-       $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
-       if diff conftest.exp conftest.er2 >/dev/null; then
-         lt_prog_compiler_static_works_GCJ=3Dyes
-       fi
-     else
-       lt_prog_compiler_static_works_GCJ=3Dyes
-     fi
-   fi
-   $rm conftest*
-   LDFLAGS=3D"$save_LDFLAGS"
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_prog_compiler_static_works_GCJ" >&5
-echo "${ECHO_T}$lt_prog_compiler_static_works_GCJ" >&6; }
-
-if test x"$lt_prog_compiler_static_works_GCJ" =3D xyes; then
-    :
-else
-    lt_prog_compiler_static_GCJ=3D
-fi
-
-
-{ echo "$as_me:$LINENO: checking if $compiler supports -c -o file.$ac_obje=
xt" >&5
-echo $ECHO_N "checking if $compiler supports -c -o file.$ac_objext... $ECH=
O_C" >&6; }
-if test "${lt_cv_prog_compiler_c_o_GCJ+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  lt_cv_prog_compiler_c_o_GCJ=3Dno
-   $rm -r conftest 2>/dev/null
-   mkdir conftest
-   cd conftest
-   mkdir out
-   printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-   lt_compiler_flag=3D"-o out/conftest2.$ac_objext"
-   # Insert the option either (1) after the last *FLAGS variable, or
-   # (2) before a word containing "conftest.", or (3) at the end.
-   # Note that $ac_compile itself does not contain backslashes and begins
-   # with a dollar sign (not a hyphen), so the echo should work correctly.
-   lt_compile=3D`echo "$ac_compile" | $SED \
-   -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
-   -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
-   -e 's:$: $lt_compiler_flag:'`
-   (eval echo "\"\$as_me:17536: $lt_compile\"" >&5)
-   (eval "$lt_compile" 2>out/conftest.err)
-   ac_status=3D$?
-   cat out/conftest.err >&5
-   echo "$as_me:17540: \$? =3D $ac_status" >&5
-   if (exit $ac_status) && test -s out/conftest2.$ac_objext
-   then
-     # The compiler can only warn and ignore the option if not recognized
-     # So say no if there are warnings
-     $echo "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.=
exp
-     $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
-     if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.e=
r2 >/dev/null; then
-       lt_cv_prog_compiler_c_o_GCJ=3Dyes
-     fi
-   fi
-   chmod u+w . 2>&5
-   $rm conftest*
-   # SGI C++ compiler will create directory out/ii_files/ for
-   # template instantiation
-   test -d out/ii_files && $rm out/ii_files/* && rmdir out/ii_files
-   $rm out/* && rmdir out
-   cd ..
-   rmdir conftest
-   $rm conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $lt_cv_prog_compiler_c_o_GCJ" >&5
-echo "${ECHO_T}$lt_cv_prog_compiler_c_o_GCJ" >&6; }
-
-
-hard_links=3D"nottested"
-if test "$lt_cv_prog_compiler_c_o_GCJ" =3D no && test "$need_locks" !=3D n=
o; then
-  # do not overwrite the value of need_locks provided by the user
-  { echo "$as_me:$LINENO: checking if we can lock with hard links" >&5
-echo $ECHO_N "checking if we can lock with hard links... $ECHO_C" >&6; }
-  hard_links=3Dyes
-  $rm conftest*
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  touch conftest.a
-  ln conftest.a conftest.b 2>&5 || hard_links=3Dno
-  ln conftest.a conftest.b 2>/dev/null && hard_links=3Dno
-  { echo "$as_me:$LINENO: result: $hard_links" >&5
-echo "${ECHO_T}$hard_links" >&6; }
-  if test "$hard_links" =3D no; then
-    { echo "$as_me:$LINENO: WARNING: \`$CC' does not support \`-c -o', so =
\`make -j' may be unsafe" >&5
-echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may=
 be unsafe" >&2;}
-    need_locks=3Dwarn
-  fi
-else
-  need_locks=3Dno
-fi
-
-{ echo "$as_me:$LINENO: checking whether the $compiler linker ($LD) suppor=
ts shared libraries" >&5
-echo $ECHO_N "checking whether the $compiler linker ($LD) supports shared =
libraries... $ECHO_C" >&6; }
-
-  runpath_var=3D
-  allow_undefined_flag_GCJ=3D
-  enable_shared_with_static_runtimes_GCJ=3Dno
-  archive_cmds_GCJ=3D
-  archive_expsym_cmds_GCJ=3D
-  old_archive_From_new_cmds_GCJ=3D
-  old_archive_from_expsyms_cmds_GCJ=3D
-  export_dynamic_flag_spec_GCJ=3D
-  whole_archive_flag_spec_GCJ=3D
-  thread_safe_flag_spec_GCJ=3D
-  hardcode_libdir_flag_spec_GCJ=3D
-  hardcode_libdir_flag_spec_ld_GCJ=3D
-  hardcode_libdir_separator_GCJ=3D
-  hardcode_direct_GCJ=3Dno
-  hardcode_minus_L_GCJ=3Dno
-  hardcode_shlibpath_var_GCJ=3Dunsupported
-  link_all_deplibs_GCJ=3Dunknown
-  hardcode_automatic_GCJ=3Dno
-  module_cmds_GCJ=3D
-  module_expsym_cmds_GCJ=3D
-  always_export_symbols_GCJ=3Dno
-  export_symbols_cmds_GCJ=3D'$NM $libobjs $convenience | $global_symbol_pi=
pe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols'
-  # include_expsyms should be a list of space-separated symbols to be *alw=
ays*
-  # included in the symbol list
-  include_expsyms_GCJ=3D
-  # exclude_expsyms can be an extended regexp of symbols to exclude
-  # it will be wrapped by ` (' and `)$', so one must not match beginning or
-  # end of line.  Example: `a|bc|.*d.*' will exclude the symbols `a' and `=
bc',
-  # as well as any symbol that contains `d'.
-  exclude_expsyms_GCJ=3D"_GLOBAL_OFFSET_TABLE_"
-  # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out
-  # platforms (ab)use it in PIC code, but their linkers get confused if
-  # the symbol is explicitly referenced.  Since portable code cannot
-  # rely on this symbol name, it's probably fine to never include it in
-  # preloaded symbol tables.
-  extract_expsyms_cmds=3D
-  # Just being paranoid about ensuring that cc_basename is set.
-  for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
-
-  case $host_os in
-  cygwin* | mingw* | pw32*)
-    # FIXME: the MSVC++ port hasn't been tested in a loooong time
-    # When not using gcc, we currently assume that we are using
-    # Microsoft Visual C++.
-    if test "$GCC" !=3D yes; then
-      with_gnu_ld=3Dno
-    fi
-    ;;
-  interix*)
-    # we just hope/assume this is gcc and not c89 (=3D MSVC++)
-    with_gnu_ld=3Dyes
-    ;;
-  openbsd*)
-    with_gnu_ld=3Dno
-    ;;
-  esac
-
-  ld_shlibs_GCJ=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    # If archive_cmds runs LD, not CC, wlarc should be empty
-    wlarc=3D'${wl}'
-
-    # Set some defaults for GNU ld with shared library support. These
-    # are reset later if shared libraries are not supported. Putting them
-    # here allows them to be overridden if necessary.
-    runpath_var=3DLD_RUN_PATH
-    hardcode_libdir_flag_spec_GCJ=3D'${wl}--rpath ${wl}$libdir'
-    export_dynamic_flag_spec_GCJ=3D'${wl}--export-dynamic'
-    # ancient GNU ld didn't support --whole-archive et. al.
-    if $LD --help 2>&1 | grep 'no-whole-archive' > /dev/null; then
-	whole_archive_flag_spec_GCJ=3D"$wlarc"'--whole-archive$convenience '"$wla=
rc"'--no-whole-archive'
-      else
-  	whole_archive_flag_spec_GCJ=3D
-    fi
-    supports_anon_versioning=3Dno
-    case `$LD -v 2>/dev/null` in
-      *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11
-      *\ 2.11.93.0.2\ *) supports_anon_versioning=3Dyes ;; # RH7.3 ...
-      *\ 2.11.92.0.12\ *) supports_anon_versioning=3Dyes ;; # Mandrake 8.2=
 ...
-      *\ 2.11.*) ;; # other 2.11 versions
-      *) supports_anon_versioning=3Dyes ;;
-    esac
-
-    # See if GNU ld supports shared libraries.
-    case $host_os in
-    aix3* | aix4* | aix5*)
-      # On AIX/PPC, the GNU linker is very broken
-      if test "$host_cpu" !=3D ia64; then
-	ld_shlibs_GCJ=3Dno
-	cat <<EOF 1>&2
-
-*** Warning: the GNU linker, at least up to release 2.9.1, is reported
-*** to be unable to reliably create shared libraries on AIX.
-*** Therefore, libtool is disabling shared libraries support.  If you
-*** really care for shared libraries, you may want to modify your PATH
-*** so that a non-GNU linker is found, and then restart.
-
-EOF
-      fi
-      ;;
-
-    amigaos*)
-      archive_cmds_GCJ=3D'$rm $output_objdir/a2ixlibrary.data~$echo "#defi=
ne NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_=
ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> =
$output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $outp=
ut_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $ou=
tput_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-      hardcode_minus_L_GCJ=3Dyes
-
-      # Samuel A. Falvo II <kc5tja at dolphin.openprojects.net> reports
-      # that the semantics of dynamic libraries on AmigaOS, at least up
-      # to version 4, is to share data among multiple programs linked
-      # with the same dynamic library.  Since this doesn't match the
-      # behavior of shared libraries on other platforms, we can't use
-      # them.
-      ld_shlibs_GCJ=3Dno
-      ;;
-
-    beos*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	allow_undefined_flag_GCJ=3Dunsupported
-	# Joseph Beckenbach <jrb3 at best.com> says some releases of gcc
-	# support --undefined.  This deserves some investigation.  FIXME
-	archive_cmds_GCJ=3D'$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-=
soname $wl$soname -o $lib'
-      else
-	ld_shlibs_GCJ=3Dno
-      fi
-      ;;
-
-    cygwin* | mingw* | pw32*)
-      # _LT_AC_TAGVAR(hardcode_libdir_flag_spec, GCJ) is actually meaningl=
ess,
-      # as there is no search path for DLLs.
-      hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-      allow_undefined_flag_GCJ=3Dunsupported
-      always_export_symbols_GCJ=3Dno
-      enable_shared_with_static_runtimes_GCJ=3Dyes
-      export_symbols_cmds_GCJ=3D'$NM $libobjs $convenience | $global_symbo=
l_pipe | $SED -e '\''/^[BCDGRS] /s/.* \([^ ]*\)/\1 DATA/'\'' | $SED -e '\''=
/^[AITW] /s/.* //'\'' | sort | uniq > $export_symbols'
-
-      if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then
-        archive_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags =
-o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-impl=
ib -Xlinker $lib'
-	# If the export-symbols file already is a .def file (1st line
-	# is EXPORTS), use it as is; otherwise, prepend...
-	archive_expsym_cmds_GCJ=3D'if test "x`$SED 1q $export_symbols`" =3D xEXPO=
RTS; then
-	  cp $export_symbols $output_objdir/$soname.def;
-	else
-	  echo EXPORTS > $output_objdir/$soname.def;
-	  cat $export_symbols >> $output_objdir/$soname.def;
-	fi~
-	$CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags =
-o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-impl=
ib -Xlinker $lib'
-      else
-	ld_shlibs_GCJ=3Dno
-      fi
-      ;;
-
-    interix3*)
-      hardcode_direct_GCJ=3Dno
-      hardcode_shlibpath_var_GCJ=3Dno
-      hardcode_libdir_flag_spec_GCJ=3D'${wl}-rpath,$libdir'
-      export_dynamic_flag_spec_GCJ=3D'${wl}-E'
-      # Hack: On Interix 3.x, we cannot compile PIC because of a broken gc=
c.
-      # Instead, shared libraries are loaded at an image base (0x10000000 =
by
-      # default) and relocated if they conflict, which is a slow very memo=
ry
-      # consuming and fragmenting process.  To avoid this, we pick a rando=
m,
-      # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at li=
nk
-      # time.  Moving up from 0x10000000 also allows more sbrk(2) space.
-      archive_cmds_GCJ=3D'$CC -shared $pic_flag $libobjs $deplibs $compile=
r_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* =
262144 + 1342177280` -o $lib'
-      archive_expsym_cmds_GCJ=3D'sed "s,^,_," $export_symbols >$output_obj=
dir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags =
${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${=
wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $l=
ib'
-      ;;
-
-    linux*)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	tmp_addflag=3D
-	case $cc_basename,$host_cpu in
-	pgcc*)				# Portland Group C compiler
-	  whole_archive_flag_spec_GCJ=3D'${wl}--whole-archive`for conv in $conven=
ience\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$c=
onv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=3D' $pic_flag'
-	  ;;
-	pgf77* | pgf90* | pgf95*)	# Portland Group f77 and f90 compilers
-	  whole_archive_flag_spec_GCJ=3D'${wl}--whole-archive`for conv in $conven=
ience\"\"; do test  -n \"$conv\" && new_convenience=3D\"$new_convenience,$c=
onv\"; done; $echo \"$new_convenience\"` ${wl}--no-whole-archive'
-	  tmp_addflag=3D' $pic_flag -Mnomain' ;;
-	ecc*,ia64* | icc*,ia64*)		# Intel C compiler on ia64
-	  tmp_addflag=3D' -i_dynamic' ;;
-	efc*,ia64* | ifort*,ia64*)	# Intel Fortran compiler on ia64
-	  tmp_addflag=3D' -i_dynamic -nofor_main' ;;
-	ifc* | ifort*)			# Intel Fortran compiler
-	  tmp_addflag=3D' -nofor_main' ;;
-	esac
-	archive_cmds_GCJ=3D'$CC -shared'"$tmp_addflag"' $libobjs $deplibs $compil=
er_flags ${wl}-soname $wl$soname -o $lib'
-
-	if test $supports_anon_versioning =3D yes; then
-	  archive_expsym_cmds_GCJ=3D'$echo "{ global:" > $output_objdir/$libname.=
ver~
-  cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.=
ver~
-  $echo "local: *; };" >> $output_objdir/$libname.ver~
-	  $CC -shared'"$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-son=
ame $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $li=
b'
-	fi
-      else
-	ld_shlibs_GCJ=3Dno
-      fi
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	archive_cmds_GCJ=3D'$LD -Bshareable $libobjs $deplibs $linker_flags -o $l=
ib'
-	wlarc=3D
-      else
-	archive_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname $wl$soname -o $lib'
-	archive_expsym_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $li=
b'
-      fi
-      ;;
-
-    solaris*)
-      if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then
-	ld_shlibs_GCJ=3Dno
-	cat <<EOF 1>&2
-
-*** Warning: The releases 2.8.* of the GNU linker cannot reliably
-*** create shared libraries on Solaris systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.9.1 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-EOF
-      elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null=
; then
-	archive_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname $wl$soname -o $lib'
-	archive_expsym_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $li=
b'
-      else
-	ld_shlibs_GCJ=3Dno
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*)
-      case `$LD -v 2>&1` in
-        *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*)
-	ld_shlibs_GCJ=3Dno
-	cat <<_LT_EOF 1>&2
-
-*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not
-*** reliably create shared libraries on SCO systems.  Therefore, libtool
-*** is disabling shared libraries support.  We urge you to upgrade GNU
-*** binutils to release 2.16.91.0.3 or newer.  Another option is to modify
-*** your PATH or compiler configuration so that the native linker is
-*** used, and then restart.
-
-_LT_EOF
-	;;
-	*)
-	  if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then
-	    hardcode_libdir_flag_spec_GCJ=3D'`test -z "$SCOABSPATH" && echo ${wl}=
-rpath,$libdir`'
-	    archive_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags ${w=
l}-soname,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib'
-	    archive_expsym_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_fl=
ags ${wl}-soname,\${SCOABSPATH:+${install_libdir}/}$soname,-retain-symbols-=
file,$export_symbols -o $lib'
-	  else
-	    ld_shlibs_GCJ=3Dno
-	  fi
-	;;
-      esac
-      ;;
-
-    sunos4*)
-      archive_cmds_GCJ=3D'$LD -assert pure-text -Bshareable -o $lib $libob=
js $deplibs $linker_flags'
-      wlarc=3D
-      hardcode_direct_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    *)
-      if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; =
then
-	archive_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname $wl$soname -o $lib'
-	archive_expsym_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags =
${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $li=
b'
-      else
-	ld_shlibs_GCJ=3Dno
-      fi
-      ;;
-    esac
-
-    if test "$ld_shlibs_GCJ" =3D no; then
-      runpath_var=3D
-      hardcode_libdir_flag_spec_GCJ=3D
-      export_dynamic_flag_spec_GCJ=3D
-      whole_archive_flag_spec_GCJ=3D
-    fi
-  else
-    # PORTME fill in a description of your system's linker (not GNU ld)
-    case $host_os in
-    aix3*)
-      allow_undefined_flag_GCJ=3Dunsupported
-      always_export_symbols_GCJ=3Dyes
-      archive_expsym_cmds_GCJ=3D'$LD -o $output_objdir/$soname $libobjs $d=
eplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS =
$lib $output_objdir/$soname'
-      # Note: this linker hardcodes the directories in LIBPATH if there
-      # are no directories specified by -L.
-      hardcode_minus_L_GCJ=3Dyes
-      if test "$GCC" =3D yes && test -z "$lt_prog_compiler_static"; then
-	# Neither direct hardcoding nor static linking is supported with a
-	# broken collect2.
-	hardcode_direct_GCJ=3Dunsupported
-      fi
-      ;;
-
-    aix4* | aix5*)
-      if test "$host_cpu" =3D ia64; then
-	# On IA64, the linker does run time linking by default, so we don't
-	# have to do anything special.
-	aix_use_runtimelinking=3Dno
-	exp_sym_flag=3D'-Bexport'
-	no_entry_flag=3D""
-      else
-	# If we're using GNU nm, then we don't want the "-C" option.
-	# -C means demangle to AIX nm, but means don't demangle with GNU nm
-	if $NM -V 2>&1 | grep 'GNU' > /dev/null; then
-	  export_symbols_cmds_GCJ=3D'$NM -Bpg $libobjs $convenience | awk '\''{ i=
f (((\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (substr(\$=
3,1,1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-	else
-	  export_symbols_cmds_GCJ=3D'$NM -BCpg $libobjs $convenience | awk '\''{ =
if (((\$2 =3D=3D "T") || (\$2 =3D=3D "D") || (\$2 =3D=3D "B")) && (substr(\=
$3,1,1) !=3D ".")) { print \$3 } }'\'' | sort -u > $export_symbols'
-	fi
-	aix_use_runtimelinking=3Dno
-
-	# Test if we are trying to use run time linking or normal
-	# AIX style linking. If -brtl is somewhere in LDFLAGS, we
-	# need to do runtime linking.
-	case $host_os in aix4.[23]|aix4.[23].*|aix5*)
-	  for ld_flag in $LDFLAGS; do
-  	  if (test $ld_flag =3D "-brtl" || test $ld_flag =3D "-Wl,-brtl"); then
-  	    aix_use_runtimelinking=3Dyes
-  	    break
-  	  fi
-	  done
-	  ;;
-	esac
-
-	exp_sym_flag=3D'-bexport'
-	no_entry_flag=3D'-bnoentry'
-      fi
-
-      # When large executables or shared objects are built, AIX ld can
-      # have problems creating the table of contents.  If linking a library
-      # or program results in "error TOC overflow" add -mminimal-toc to
-      # CXXFLAGS/CFLAGS for g++/gcc.  In the cases where that is not
-      # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS.
-
-      archive_cmds_GCJ=3D''
-      hardcode_direct_GCJ=3Dyes
-      hardcode_libdir_separator_GCJ=3D':'
-      link_all_deplibs_GCJ=3Dyes
-
-      if test "$GCC" =3D yes; then
-	case $host_os in aix4.[012]|aix4.[012].*)
-	# We only want to do this on AIX 4.2 and lower, the check
-	# below for broken collect2 doesn't work under 4.3+
-	  collect2name=3D`${CC} -print-prog-name=3Dcollect2`
-	  if test -f "$collect2name" && \
-  	   strings "$collect2name" | grep resolve_lib_name >/dev/null
-	  then
-  	  # We have reworked collect2
-  	  hardcode_direct_GCJ=3Dyes
-	  else
-  	  # We have old collect2
-  	  hardcode_direct_GCJ=3Dunsupported
-  	  # It fails to find uninstalled libraries when the uninstalled
-  	  # path is not listed in the libpath.  Setting hardcode_minus_L
-  	  # to unsupported forces relinking
-  	  hardcode_minus_L_GCJ=3Dyes
-  	  hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-  	  hardcode_libdir_separator_GCJ=3D
-	  fi
-	  ;;
-	esac
-	shared_flag=3D'-shared'
-	if test "$aix_use_runtimelinking" =3D yes; then
-	  shared_flag=3D"$shared_flag "'${wl}-G'
-	fi
-      else
-	# not using gcc
-	if test "$host_cpu" =3D ia64; then
-  	# VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release
-  	# chokes on -Wl,-G. The following line is correct:
-	  shared_flag=3D'-G'
-	else
-	  if test "$aix_use_runtimelinking" =3D yes; then
-	    shared_flag=3D'${wl}-G'
-	  else
-	    shared_flag=3D'${wl}-bM:SRE'
-	  fi
-	fi
-      fi
-
-      # It seems that -bexpall does not export symbols beginning with
-      # underscore (_), so it is better to generate a list of symbols to e=
xport.
-      always_export_symbols_GCJ=3Dyes
-      if test "$aix_use_runtimelinking" =3D yes; then
-	# Warning - without using the other runtime loading flags (-brtl),
-	# -berok will link without error, but may produce a broken library.
-	allow_undefined_flag_GCJ=3D'-berok'
-       # Determine the default libpath from the value encoded in an empty =
executable.
-       cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-
-       hardcode_libdir_flag_spec_GCJ=3D'${wl}-blibpath:$libdir:'"$aix_libp=
ath"
-	archive_expsym_cmds_GCJ=3D"\$CC"' -o $output_objdir/$soname $libobjs $dep=
libs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_=
flag}" !=3D "x"; then echo "${wl}${allow_undefined_flag}"; else :; fi` '"\$=
{wl}$exp_sym_flag:\$export_symbols $shared_flag"
-       else
-	if test "$host_cpu" =3D ia64; then
-	  hardcode_libdir_flag_spec_GCJ=3D'${wl}-R $libdir:/usr/lib:/lib'
-	  allow_undefined_flag_GCJ=3D"-z nodefs"
-	  archive_expsym_cmds_GCJ=3D"\$CC $shared_flag"' -o $output_objdir/$sonam=
e $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_u=
ndefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols"
-	else
-	 # Determine the default libpath from the value encoded in an empty execu=
table.
-	 cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-
-aix_libpath=3D`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e '/Impor=
t File Strings/,/^$/ { /^0/ { s/^0  *\(.*\)$/\1/; p; }
-}'`
-# Check for a 64-bit object if we didn't find anything.
-if test -z "$aix_libpath"; then aix_libpath=3D`dump -HX64 conftest$ac_exee=
xt 2>/dev/null | $SED -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0  *\(.=
*\)$/\1/; p; }
-}'`; fi
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test -z "$aix_libpath"; then aix_libpath=3D"/usr/lib:/lib"; fi
-
-	 hardcode_libdir_flag_spec_GCJ=3D'${wl}-blibpath:$libdir:'"$aix_libpath"
-	  # Warning - without using the other run time loading flags,
-	  # -berok will link without error, but may produce a broken library.
-	  no_undefined_flag_GCJ=3D' ${wl}-bernotok'
-	  allow_undefined_flag_GCJ=3D' ${wl}-berok'
-	  # Exported symbols can be pulled into shared objects from archives
-	  whole_archive_flag_spec_GCJ=3D'$convenience'
-	  archive_cmds_need_lc_GCJ=3Dyes
-	  # This is similar to how AIX traditionally builds its shared libraries.
-	  archive_expsym_cmds_GCJ=3D"\$CC $shared_flag"' -o $output_objdir/$sonam=
e $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols=
${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $ou=
tput_objdir/$soname'
-	fi
-      fi
-      ;;
-
-    amigaos*)
-      archive_cmds_GCJ=3D'$rm $output_objdir/a2ixlibrary.data~$echo "#defi=
ne NAME $libname" > $output_objdir/a2ixlibrary.data~$echo "#define LIBRARY_=
ID 1" >> $output_objdir/a2ixlibrary.data~$echo "#define VERSION $major" >> =
$output_objdir/a2ixlibrary.data~$echo "#define REVISION $revision" >> $outp=
ut_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $ou=
tput_objdir && a2ixlibrary -32)'
-      hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-      hardcode_minus_L_GCJ=3Dyes
-      # see comment about different semantics on the GNU ld section
-      ld_shlibs_GCJ=3Dno
-      ;;
-
-    bsdi[45]*)
-      export_dynamic_flag_spec_GCJ=3D-rdynamic
-      ;;
-
-    cygwin* | mingw* | pw32*)
-      # When not using gcc, we currently assume that we are using
-      # Microsoft Visual C++.
-      # hardcode_libdir_flag_spec is actually meaningless, as there is
-      # no search path for DLLs.
-      hardcode_libdir_flag_spec_GCJ=3D' '
-      allow_undefined_flag_GCJ=3Dunsupported
-      # Tell ltmain to make .lib files, not .a files.
-      libext=3Dlib
-      # Tell ltmain to make .dll files, not .so files.
-      shrext_cmds=3D".dll"
-      # FIXME: Setting linknames here is a bad hack.
-      archive_cmds_GCJ=3D'$CC -o $lib $libobjs $compiler_flags `echo "$dep=
libs" | $SED -e '\''s/ -lc$//'\''` -link -dll~linknames=3D'
-      # The linker will automatically build a .lib file if we build a DLL.
-      old_archive_From_new_cmds_GCJ=3D'true'
-      # FIXME: Should let the user specify the lib program.
-      old_archive_cmds_GCJ=3D'lib /OUT:$oldlib$oldobjs$old_deplibs'
-      fix_srcfile_path_GCJ=3D'`cygpath -w "$srcfile"`'
-      enable_shared_with_static_runtimes_GCJ=3Dyes
-      ;;
-
-    darwin* | rhapsody*)
-      case $host_os in
-        rhapsody* | darwin1.[012])
-         allow_undefined_flag_GCJ=3D'${wl}-undefined ${wl}suppress'
-         ;;
-       *) # Darwin 1.3 on
-         if test -z ${MACOSX_DEPLOYMENT_TARGET} ; then
-           allow_undefined_flag_GCJ=3D'${wl}-flat_namespace ${wl}-undefine=
d ${wl}suppress'
-         else
-           case ${MACOSX_DEPLOYMENT_TARGET} in
-             10.[012])
-               allow_undefined_flag_GCJ=3D'${wl}-flat_namespace ${wl}-unde=
fined ${wl}suppress'
-               ;;
-             10.*)
-               allow_undefined_flag_GCJ=3D'${wl}-undefined ${wl}dynamic_lo=
okup'
-               ;;
-           esac
-         fi
-         ;;
-      esac
-      archive_cmds_need_lc_GCJ=3Dno
-      hardcode_direct_GCJ=3Dno
-      hardcode_automatic_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dunsupported
-      whole_archive_flag_spec_GCJ=3D''
-      link_all_deplibs_GCJ=3Dyes
-    if test "$GCC" =3D yes ; then
-    	output_verbose_link_cmd=3D'echo'
-        archive_cmds_GCJ=3D'$CC -dynamiclib $allow_undefined_flag -o $lib =
$libobjs $deplibs $compiler_flags -install_name $rpath/$soname $verstring'
-      module_cmds_GCJ=3D'$CC $allow_undefined_flag -o $lib -bundle $libobj=
s $deplibs$compiler_flags'
-      # Don't fix this by using the ld -exported_symbols_list flag, it doe=
sn't exist in older darwin lds
-      archive_expsym_cmds_GCJ=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,=
^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~=
$CC -dynamiclib $allow_undefined_flag -o $lib $libobjs $deplibs $compiler_f=
lags -install_name $rpath/$soname $verstring~nmedit -s $output_objdir/${lib=
name}-symbols.expsym ${lib}'
-      module_expsym_cmds_GCJ=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e "s,^=
\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.expsym~$=
CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_flags~=
nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-    else
-      case $cc_basename in
-        xlc*)
-         output_verbose_link_cmd=3D'echo'
-         archive_cmds_GCJ=3D'$CC -qmkshrobj $allow_undefined_flag -o $lib =
$libobjs $deplibs $compiler_flags ${wl}-install_name ${wl}`echo $rpath/$son=
ame` $verstring'
-         module_cmds_GCJ=3D'$CC $allow_undefined_flag -o $lib -bundle $lib=
objs $deplibs$compiler_flags'
-          # Don't fix this by using the ld -exported_symbols_list flag, it=
 doesn't exist in older darwin lds
-         archive_expsym_cmds_GCJ=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e =
"s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.exps=
ym~$CC -qmkshrobj $allow_undefined_flag -o $lib $libobjs $deplibs $compiler=
_flags ${wl}-install_name ${wl}$rpath/$soname $verstring~nmedit -s $output_=
objdir/${libname}-symbols.expsym ${lib}'
-          module_expsym_cmds_GCJ=3D'sed -e "s,#.*,," -e "s,^[    ]*,," -e =
"s,^\(..*\),_&," < $export_symbols > $output_objdir/${libname}-symbols.exps=
ym~$CC $allow_undefined_flag  -o $lib -bundle $libobjs $deplibs$compiler_fl=
ags~nmedit -s $output_objdir/${libname}-symbols.expsym ${lib}'
-          ;;
-       *)
-         ld_shlibs_GCJ=3Dno
-          ;;
-      esac
-    fi
-      ;;
-
-    dgux*)
-      archive_cmds_GCJ=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    freebsd1*)
-      ld_shlibs_GCJ=3Dno
-      ;;
-
-    # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ construct=
or
-    # support.  Future versions do this automatically, but an explicit c++=
rt0.o
-    # does not break anything, and helps significantly (at the cost of a l=
ittle
-    # extra space).
-    freebsd2.2*)
-      archive_cmds_GCJ=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linke=
r_flags /usr/lib/c++rt0.o'
-      hardcode_libdir_flag_spec_GCJ=3D'-R$libdir'
-      hardcode_direct_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    # Unfortunately, older versions of FreeBSD 2 do not have this feature.
-    freebsd2*)
-      archive_cmds_GCJ=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linke=
r_flags'
-      hardcode_direct_GCJ=3Dyes
-      hardcode_minus_L_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    # FreeBSD 3 and greater uses gcc -shared to do shared libraries.
-    freebsd* | kfreebsd*-gnu | dragonfly*)
-      archive_cmds_GCJ=3D'$CC -shared -o $lib $libobjs $deplibs $compiler_=
flags'
-      hardcode_libdir_flag_spec_GCJ=3D'-R$libdir'
-      hardcode_direct_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    hpux9*)
-      if test "$GCC" =3D yes; then
-	archive_cmds_GCJ=3D'$rm $output_objdir/$soname~$CC -shared -fPIC ${wl}+b =
${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_=
flags~test $output_objdir/$soname =3D $lib || mv $output_objdir/$soname $li=
b'
-      else
-	archive_cmds_GCJ=3D'$rm $output_objdir/$soname~$LD -b +b $install_libdir =
-o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objd=
ir/$soname =3D $lib || mv $output_objdir/$soname $lib'
-      fi
-      hardcode_libdir_flag_spec_GCJ=3D'${wl}+b ${wl}$libdir'
-      hardcode_libdir_separator_GCJ=3D:
-      hardcode_direct_GCJ=3Dyes
-
-      # hardcode_minus_L: Not really in the search PATH,
-      # but as the default location of the library.
-      hardcode_minus_L_GCJ=3Dyes
-      export_dynamic_flag_spec_GCJ=3D'${wl}-E'
-      ;;
-
-    hpux10*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
-	archive_cmds_GCJ=3D'$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$=
install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_GCJ=3D'$LD -b +h $soname +b $install_libdir -o $lib $libobjs=
 $deplibs $linker_flags'
-      fi
-      if test "$with_gnu_ld" =3D no; then
-	hardcode_libdir_flag_spec_GCJ=3D'${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_GCJ=3D:
-
-	hardcode_direct_GCJ=3Dyes
-	export_dynamic_flag_spec_GCJ=3D'${wl}-E'
-
-	# hardcode_minus_L: Not really in the search PATH,
-	# but as the default location of the library.
-	hardcode_minus_L_GCJ=3Dyes
-      fi
-      ;;
-
-    hpux11*)
-      if test "$GCC" =3D yes -a "$with_gnu_ld" =3D no; then
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_GCJ=3D'$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $=
deplibs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_GCJ=3D'$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpa=
th -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds_GCJ=3D'$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl=
}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      else
-	case $host_cpu in
-	hppa*64*)
-	  archive_cmds_GCJ=3D'$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $depli=
bs $compiler_flags'
-	  ;;
-	ia64*)
-	  archive_cmds_GCJ=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o=
 $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	*)
-	  archive_cmds_GCJ=3D'$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_l=
ibdir -o $lib $libobjs $deplibs $compiler_flags'
-	  ;;
-	esac
-      fi
-      if test "$with_gnu_ld" =3D no; then
-	hardcode_libdir_flag_spec_GCJ=3D'${wl}+b ${wl}$libdir'
-	hardcode_libdir_separator_GCJ=3D:
-
-	case $host_cpu in
-	hppa*64*|ia64*)
-	  hardcode_libdir_flag_spec_ld_GCJ=3D'+b $libdir'
-	  hardcode_direct_GCJ=3Dno
-	  hardcode_shlibpath_var_GCJ=3Dno
-	  ;;
-	*)
-	  hardcode_direct_GCJ=3Dyes
-	  export_dynamic_flag_spec_GCJ=3D'${wl}-E'
-
-	  # hardcode_minus_L: Not really in the search PATH,
-	  # but as the default location of the library.
-	  hardcode_minus_L_GCJ=3Dyes
-	  ;;
-	esac
-      fi
-      ;;
-
-    irix5* | irix6* | nonstopux*)
-      if test "$GCC" =3D yes; then
-	archive_cmds_GCJ=3D'$CC -shared $libobjs $deplibs $compiler_flags ${wl}-s=
oname ${wl}$soname `test -n "$verstring" && echo ${wl}-set_version ${wl}$ve=
rstring` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib'
-      else
-	archive_cmds_GCJ=3D'$LD -shared $libobjs $deplibs $linker_flags -soname $=
soname `test -n "$verstring" && echo -set_version $verstring` -update_regis=
try ${output_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec_ld_GCJ=3D'-rpath $libdir'
-      fi
-      hardcode_libdir_flag_spec_GCJ=3D'${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_GCJ=3D:
-      link_all_deplibs_GCJ=3Dyes
-      ;;
-
-    netbsd*)
-      if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-	archive_cmds_GCJ=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linker_fla=
gs'  # a.out
-      else
-	archive_cmds_GCJ=3D'$LD -shared -o $lib $libobjs $deplibs $linker_flags' =
     # ELF
-      fi
-      hardcode_libdir_flag_spec_GCJ=3D'-R$libdir'
-      hardcode_direct_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    newsos6)
-      archive_cmds_GCJ=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_direct_GCJ=3Dyes
-      hardcode_libdir_flag_spec_GCJ=3D'${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_GCJ=3D:
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    openbsd*)
-      hardcode_direct_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dno
-      if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host=
_os-$host_cpu" =3D "openbsd2.8-powerpc"; then
-	archive_cmds_GCJ=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $comp=
iler_flags'
-	archive_expsym_cmds_GCJ=3D'$CC -shared $pic_flag -o $lib $libobjs $deplib=
s $compiler_flags ${wl}-retain-symbols-file,$export_symbols'
-	hardcode_libdir_flag_spec_GCJ=3D'${wl}-rpath,$libdir'
-	export_dynamic_flag_spec_GCJ=3D'${wl}-E'
-      else
-       case $host_os in
-	 openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*)
-	   archive_cmds_GCJ=3D'$LD -Bshareable -o $lib $libobjs $deplibs $linker_=
flags'
-	   hardcode_libdir_flag_spec_GCJ=3D'-R$libdir'
-	   ;;
-	 *)
-	   archive_cmds_GCJ=3D'$CC -shared $pic_flag -o $lib $libobjs $deplibs $c=
ompiler_flags'
-	   hardcode_libdir_flag_spec_GCJ=3D'${wl}-rpath,$libdir'
-	   ;;
-       esac
-      fi
-      ;;
-
-    os2*)
-      hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-      hardcode_minus_L_GCJ=3Dyes
-      allow_undefined_flag_GCJ=3Dunsupported
-      archive_cmds_GCJ=3D'$echo "LIBRARY $libname INITINSTANCE" > $output_=
objdir/$libname.def~$echo "DESCRIPTION \"$libname\"" >> $output_objdir/$lib=
name.def~$echo DATA >> $output_objdir/$libname.def~$echo " SINGLE NONSHARED=
" >> $output_objdir/$libname.def~$echo EXPORTS >> $output_objdir/$libname.d=
ef~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $li=
b $libobjs $deplibs $compiler_flags $output_objdir/$libname.def'
-      old_archive_From_new_cmds_GCJ=3D'emximp -o $output_objdir/$libname.a=
 $output_objdir/$libname.def'
-      ;;
-
-    osf3*)
-      if test "$GCC" =3D yes; then
-	allow_undefined_flag_GCJ=3D' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_GCJ=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs =
$compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && echo ${w=
l}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${output_objdir}=
/so_locations -o $lib'
-      else
-	allow_undefined_flag_GCJ=3D' -expect_unresolved \*'
-	archive_cmds_GCJ=3D'$LD -shared${allow_undefined_flag} $libobjs $deplibs =
$linker_flags -soname $soname `test -n "$verstring" && echo -set_version $v=
erstring` -update_registry ${output_objdir}/so_locations -o $lib'
-      fi
-      hardcode_libdir_flag_spec_GCJ=3D'${wl}-rpath ${wl}$libdir'
-      hardcode_libdir_separator_GCJ=3D:
-      ;;
-
-    osf4* | osf5*)	# as osf3* with the addition of -msym flag
-      if test "$GCC" =3D yes; then
-	allow_undefined_flag_GCJ=3D' ${wl}-expect_unresolved ${wl}\*'
-	archive_cmds_GCJ=3D'$CC -shared${allow_undefined_flag} $libobjs $deplibs =
$compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" =
&& echo ${wl}-set_version ${wl}$verstring` ${wl}-update_registry ${wl}${out=
put_objdir}/so_locations -o $lib'
-	hardcode_libdir_flag_spec_GCJ=3D'${wl}-rpath ${wl}$libdir'
-      else
-	allow_undefined_flag_GCJ=3D' -expect_unresolved \*'
-	archive_cmds_GCJ=3D'$LD -shared${allow_undefined_flag} $libobjs $deplibs =
$linker_flags -msym -soname $soname `test -n "$verstring" && echo -set_vers=
ion $verstring` -update_registry ${output_objdir}/so_locations -o $lib'
-	archive_expsym_cmds_GCJ=3D'for i in `cat $export_symbols`; do printf "%s =
%s\\n" -exported_symbol "\$i" >> $lib.exp; done; echo "-hidden">> $lib.exp~
-	$LD -shared${allow_undefined_flag} -input $lib.exp $linker_flags $libobjs=
 $deplibs -soname $soname `test -n "$verstring" && echo -set_version $verst=
ring` -update_registry ${output_objdir}/so_locations -o $lib~$rm $lib.exp'
-
-	# Both c and cxx compiler support -rpath directly
-	hardcode_libdir_flag_spec_GCJ=3D'-rpath $libdir'
-      fi
-      hardcode_libdir_separator_GCJ=3D:
-      ;;
-
-    solaris*)
-      no_undefined_flag_GCJ=3D' -z text'
-      if test "$GCC" =3D yes; then
-	wlarc=3D'${wl}'
-	archive_cmds_GCJ=3D'$CC -shared ${wl}-h ${wl}$soname -o $lib $libobjs $de=
plibs $compiler_flags'
-	archive_expsym_cmds_GCJ=3D'$echo "{ global:" > $lib.exp~cat $export_symbo=
ls | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-	  $CC -shared ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs=
 $deplibs $compiler_flags~$rm $lib.exp'
-      else
-	wlarc=3D''
-	archive_cmds_GCJ=3D'$LD -G${allow_undefined_flag} -h $soname -o $lib $lib=
objs $deplibs $linker_flags'
-	archive_expsym_cmds_GCJ=3D'$echo "{ global:" > $lib.exp~cat $export_symbo=
ls | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~$echo "local: *; };" >> $lib.exp~
-  	$LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $=
deplibs $linker_flags~$rm $lib.exp'
-      fi
-      hardcode_libdir_flag_spec_GCJ=3D'-R$libdir'
-      hardcode_shlibpath_var_GCJ=3Dno
-      case $host_os in
-      solaris2.[0-5] | solaris2.[0-5].*) ;;
-      *)
- 	# The compiler driver will combine linker options so we
- 	# cannot just pass the convience library names through
- 	# without $wl, iff we do not link with $LD.
- 	# Luckily, gcc supports the same syntax we need for Sun Studio.
- 	# Supported since Solaris 2.6 (maybe 2.5.1?)
- 	case $wlarc in
- 	'')
- 	  whole_archive_flag_spec_GCJ=3D'-z allextract$convenience -z defaultext=
ract' ;;
- 	*)
- 	  whole_archive_flag_spec_GCJ=3D'${wl}-z ${wl}allextract`for conv in $co=
nvenience\"\"; do test -n \"$conv\" && new_convenience=3D\"$new_convenience=
,$conv\"; done; $echo \"$new_convenience\"` ${wl}-z ${wl}defaultextract' ;;
- 	esac ;;
-      esac
-      link_all_deplibs_GCJ=3Dyes
-      ;;
-
-    sunos4*)
-      if test "x$host_vendor" =3D xsequent; then
-	# Use $CC to link under sequent, because it throws in some extra .o
-	# files that make .init and .fini sections work.
-	archive_cmds_GCJ=3D'$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $com=
piler_flags'
-      else
-	archive_cmds_GCJ=3D'$LD -assert pure-text -Bstatic -o $lib $libobjs $depl=
ibs $linker_flags'
-      fi
-      hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-      hardcode_direct_GCJ=3Dyes
-      hardcode_minus_L_GCJ=3Dyes
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    sysv4)
-      case $host_vendor in
-	sni)
-	  archive_cmds_GCJ=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $linker=
_flags'
-	  hardcode_direct_GCJ=3Dyes # is this really true???
-	;;
-	siemens)
-	  ## LD is ld it makes a PLAMLIB
-	  ## CC just makes a GrossModule.
-	  archive_cmds_GCJ=3D'$LD -G -o $lib $libobjs $deplibs $linker_flags'
-	  reload_cmds_GCJ=3D'$CC -r -o $output$reload_objs'
-	  hardcode_direct_GCJ=3Dno
-        ;;
-	motorola)
-	  archive_cmds_GCJ=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $linker=
_flags'
-	  hardcode_direct_GCJ=3Dno #Motorola manual says yes, but my tests say th=
ey lie
-	;;
-      esac
-      runpath_var=3D'LD_RUN_PATH'
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    sysv4.3*)
-      archive_cmds_GCJ=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_shlibpath_var_GCJ=3Dno
-      export_dynamic_flag_spec_GCJ=3D'-Bexport'
-      ;;
-
-    sysv4*MP*)
-      if test -d /usr/nec; then
-	archive_cmds_GCJ=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $linker_f=
lags'
-	hardcode_shlibpath_var_GCJ=3Dno
-	runpath_var=3DLD_RUN_PATH
-	hardcode_runpath_var=3Dyes
-	ld_shlibs_GCJ=3Dyes
-      fi
-      ;;
-
-    sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*)
-      no_undefined_flag_GCJ=3D'${wl}-z,text'
-      archive_cmds_need_lc_GCJ=3Dno
-      hardcode_shlibpath_var_GCJ=3Dno
-      runpath_var=3D'LD_RUN_PATH'
-
-      if test "$GCC" =3D yes; then
-	archive_cmds_GCJ=3D'$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs=
 $compiler_flags'
-	archive_expsym_cmds_GCJ=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl=
}-h,$soname -o $lib $libobjs $deplibs $compiler_flags'
-      else
-	archive_cmds_GCJ=3D'$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $com=
piler_flags'
-	archive_expsym_cmds_GCJ=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$=
soname -o $lib $libobjs $deplibs $compiler_flags'
-      fi
-      ;;
-
-    sysv5* | sco3.2v5* | sco5v6*)
-      # Note: We can NOT use -z defs as we might desire, because we do not
-      # link with -lc, and that would cause any symbols used from libc to
-      # always be unresolved, which means just about no library would
-      # ever link correctly.  If we're not using GNU ld we use -z text
-      # though, which does catch some bad symbols but isn't as heavy-handed
-      # as -z defs.
-      no_undefined_flag_GCJ=3D'${wl}-z,text'
-      allow_undefined_flag_GCJ=3D'${wl}-z,nodefs'
-      archive_cmds_need_lc_GCJ=3Dno
-      hardcode_shlibpath_var_GCJ=3Dno
-      hardcode_libdir_flag_spec_GCJ=3D'`test -z "$SCOABSPATH" && echo ${wl=
}-R,$libdir`'
-      hardcode_libdir_separator_GCJ=3D':'
-      link_all_deplibs_GCJ=3Dyes
-      export_dynamic_flag_spec_GCJ=3D'${wl}-Bexport'
-      runpath_var=3D'LD_RUN_PATH'
-
-      if test "$GCC" =3D yes; then
-	archive_cmds_GCJ=3D'$CC -shared ${wl}-h,\${SCOABSPATH:+${install_libdir}/=
}$soname -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_GCJ=3D'$CC -shared ${wl}-Bexport:$export_symbols ${wl=
}-h,\${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $co=
mpiler_flags'
-      else
-	archive_cmds_GCJ=3D'$CC -G ${wl}-h,\${SCOABSPATH:+${install_libdir}/}$son=
ame -o $lib $libobjs $deplibs $compiler_flags'
-	archive_expsym_cmds_GCJ=3D'$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,\=
${SCOABSPATH:+${install_libdir}/}$soname -o $lib $libobjs $deplibs $compile=
r_flags'
-      fi
-      ;;
-
-    uts4*)
-      archive_cmds_GCJ=3D'$LD -G -h $soname -o $lib $libobjs $deplibs $lin=
ker_flags'
-      hardcode_libdir_flag_spec_GCJ=3D'-L$libdir'
-      hardcode_shlibpath_var_GCJ=3Dno
-      ;;
-
-    *)
-      ld_shlibs_GCJ=3Dno
-      ;;
-    esac
-  fi
-
-{ echo "$as_me:$LINENO: result: $ld_shlibs_GCJ" >&5
-echo "${ECHO_T}$ld_shlibs_GCJ" >&6; }
-test "$ld_shlibs_GCJ" =3D no && can_build_shared=3Dno
-
-#
-# Do we need to explicitly link libc?
-#
-case "x$archive_cmds_need_lc_GCJ" in
-x|xyes)
-  # Assume -lc should be added
-  archive_cmds_need_lc_GCJ=3Dyes
-
-  if test "$enable_shared" =3D yes && test "$GCC" =3D yes; then
-    case $archive_cmds_GCJ in
-    *'~'*)
-      # FIXME: we may have to deal with multi-command sequences.
-      ;;
-    '$CC '*)
-      # Test whether the compiler implicitly links with -lc since on some
-      # systems, -lgcc has to come before -lc. If gcc already passes -lc
-      # to ld, don't add -lc before -lgcc.
-      { echo "$as_me:$LINENO: checking whether -lc should be explicitly li=
nked in" >&5
-echo $ECHO_N "checking whether -lc should be explicitly linked in... $ECHO=
_C" >&6; }
-      $rm conftest*
-      printf "$lt_simple_compile_test_code" > conftest.$ac_ext
-
-      if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } 2>conftest.err; then
-        soname=3Dconftest
-        lib=3Dconftest
-        libobjs=3Dconftest.$ac_objext
-        deplibs=3D
-        wl=3D$lt_prog_compiler_wl_GCJ
-	pic_flag=3D$lt_prog_compiler_pic_GCJ
-        compiler_flags=3D-v
-        linker_flags=3D-v
-        verstring=3D
-        output_objdir=3D.
-        libname=3Dconftest
-        lt_save_allow_undefined_flag=3D$allow_undefined_flag_GCJ
-        allow_undefined_flag_GCJ=3D
-        if { (eval echo "$as_me:$LINENO: \"$archive_cmds_GCJ 2\>\&1 \| gre=
p \" -lc \" \>/dev/null 2\>\&1\"") >&5
-  (eval $archive_cmds_GCJ 2\>\&1 \| grep \" -lc \" \>/dev/null 2\>\&1) 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }
-        then
-	  archive_cmds_need_lc_GCJ=3Dno
-        else
-	  archive_cmds_need_lc_GCJ=3Dyes
-        fi
-        allow_undefined_flag_GCJ=3D$lt_save_allow_undefined_flag
-      else
-        cat conftest.err 1>&5
-      fi
-      $rm conftest*
-      { echo "$as_me:$LINENO: result: $archive_cmds_need_lc_GCJ" >&5
-echo "${ECHO_T}$archive_cmds_need_lc_GCJ" >&6; }
-      ;;
-    esac
-  fi
-  ;;
-esac
-
-{ echo "$as_me:$LINENO: checking dynamic linker characteristics" >&5
-echo $ECHO_N "checking dynamic linker characteristics... $ECHO_C" >&6; }
-library_names_spec=3D
-libname_spec=3D'lib$name'
-soname_spec=3D
-shrext_cmds=3D".so"
-postinstall_cmds=3D
-postuninstall_cmds=3D
-finish_cmds=3D
-finish_eval=3D
-shlibpath_var=3D
-shlibpath_overrides_runpath=3Dunknown
-version_type=3Dnone
-dynamic_linker=3D"$host_os ld.so"
-sys_lib_dlsearch_path_spec=3D"/lib /usr/lib"
-if test "$GCC" =3D yes; then
-  sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^libraries:" =
| $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-  if echo "$sys_lib_search_path_spec" | grep ';' >/dev/null ; then
-    # if the path contains ";" then we assume it to be the separator
-    # otherwise default to the standard path separator (i.e. ":") - it is
-    # assumed that no part of a normal pathname contains ";" but that shou=
ld
-    # okay in the real world where ";" in dirpaths is itself problematic.
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED -e=
 's/;/ /g'`
-  else
-    sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SED  -=
e "s/$PATH_SEPARATOR/ /g"`
-  fi
-else
-  sys_lib_search_path_spec=3D"/lib /usr/lib /usr/local/lib"
-fi
-need_lib_prefix=3Dunknown
-hardcode_into_libs=3Dno
-
-# when you set need_version to no, make sure it does not cause -set_version
-# flags to be left without arguments
-need_version=3Dunknown
-
-case $host_os in
-aix3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $libna=
me.a'
-  shlibpath_var=3DLIBPATH
-
-  # AIX 3 has no versioning support, so we append a major version to the n=
ame.
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  ;;
-
-aix4* | aix5*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  hardcode_into_libs=3Dyes
-  if test "$host_cpu" =3D ia64; then
-    # AIX 5 supports IA64
-    library_names_spec=3D'${libname}${release}${shared_ext}$major ${libnam=
e}${release}${shared_ext}$versuffix $libname${shared_ext}'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  else
-    # With GCC up to 2.95.x, collect2 would create an import file
-    # for dependence libraries.  The import file would start with
-    # the line `#! .'.  This would cause the generated library to
-    # depend on `.', always an invalid library.  This was fixed in
-    # development snapshots of GCC prior to 3.0.
-    case $host_os in
-      aix4 | aix4.[01] | aix4.[01].*)
-      if { echo '#if __GNUC__ > 2 || (__GNUC__ =3D=3D 2 && __GNUC_MINOR__ =
>=3D 97)'
-	   echo ' yes '
-	   echo '#endif'; } | ${CC} -E - | grep yes > /dev/null; then
-	:
-      else
-	can_build_shared=3Dno
-      fi
-      ;;
-    esac
-    # AIX (on Power*) has no versioning support, so currently we can not h=
ardcode correct
-    # soname into executable. Probably we can add versioning support to
-    # collect2, so additional links can be useful in future.
-    if test "$aix_use_runtimelinking" =3D yes; then
-      # If using run time linking (on AIX 4.2 or later) use lib<name>.so
-      # instead of lib<name>.a to let people know that these are not
-      # typical AIX shared libraries.
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext}$major $libname${shared_ext}'
-    else
-      # We preserve .a as extension for shared libraries through AIX4.2
-      # and later when we are not doing run time linking.
-      library_names_spec=3D'${libname}${release}.a $libname.a'
-      soname_spec=3D'${libname}${release}${shared_ext}$major'
-    fi
-    shlibpath_var=3DLIBPATH
-  fi
-  ;;
-
-amigaos*)
-  library_names_spec=3D'$libname.ixlibrary $libname.a'
-  # Create ${libname}_ixlibrary.a entries in /sys/libs.
-  finish_eval=3D'for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libna=
me=3D`$echo "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; te=
st $rm /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib =
${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a =
|| exit 1; done'
-  ;;
-
-beos*)
-  library_names_spec=3D'${libname}${shared_ext}'
-  dynamic_linker=3D"$host_os ld.so"
-  shlibpath_var=3DLIBRARY_PATH
-  ;;
-
-bsdi[45]*)
-  version_type=3Dlinux
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/shlib /usr/lib /usr/X11/lib /usr/contrib/li=
b /lib /usr/local/lib"
-  sys_lib_dlsearch_path_spec=3D"/shlib /usr/lib /usr/local/lib"
-  # the default ld.so.conf also contains /usr/contrib/lib and
-  # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow
-  # libtool to hard-code these into programs
-  ;;
-
-cygwin* | mingw* | pw32*)
-  version_type=3Dwindows
-  shrext_cmds=3D".dll"
-  need_version=3Dno
-  need_lib_prefix=3Dno
-
-  case $GCC,$host_os in
-  yes,cygwin* | yes,mingw* | yes,pw32*)
-    library_names_spec=3D'$libname.dll.a'
-    # DLL is installed to $(libdir)/../bin by postinstall_cmds
-    postinstall_cmds=3D'base_file=3D`basename \${file}`~
-      dlpath=3D`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i;echo \$dl=
name'\''`~
-      dldir=3D$destdir/`dirname \$dlpath`~
-      test -d \$dldir || mkdir -p \$dldir~
-      $install_prog $dir/$dlname \$dldir/$dlname~
-      chmod a+x \$dldir/$dlname'
-    postuninstall_cmds=3D'dldll=3D`$SHELL 2>&1 -c '\''. $file; echo \$dlna=
me'\''`~
-      dlpath=3D$dir/\$dldll~
-       $rm \$dlpath'
-    shlibpath_overrides_runpath=3Dyes
-
-    case $host_os in
-    cygwin*)
-      # Cygwin DLLs use 'cyg' prefix rather than 'lib'
-      soname_spec=3D'`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${relea=
se} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D"/usr/lib /lib/w32api /lib /usr/local/lib"
-      ;;
-    mingw*)
-      # MinGW DLLs use traditional 'lib' prefix
-      soname_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${ve=
rsuffix}${shared_ext}'
-      sys_lib_search_path_spec=3D`$CC -print-search-dirs | grep "^librarie=
s:" | $SED -e "s/^libraries://" -e "s,=3D/,/,g"`
-      if echo "$sys_lib_search_path_spec" | grep ';[c-zC-Z]:/' >/dev/null;=
 then
-        # It is most probably a Windows format PATH printed by
-        # mingw gcc, but we are running on Cygwin. Gcc prints its search
-        # path with ; separators, and with drive letters. We can handle the
-        # drive letters (cygwin fileutils understands them), so leave them,
-        # especially as we might pass files found there to a mingw objdump,
-        # which wouldn't understand a cygwinified path. Ahh.
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D -e 's/;/ /g'`
-      else
-        sys_lib_search_path_spec=3D`echo "$sys_lib_search_path_spec" | $SE=
D  -e "s/$PATH_SEPARATOR/ /g"`
-      fi
-      ;;
-    pw32*)
-      # pw32 DLLs use 'pw' prefix rather than 'lib'
-      library_names_spec=3D'`echo ${libname} | sed -e 's/^lib/pw/'``echo $=
{release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}'
-      ;;
-    esac
-    ;;
-
-  *)
-    library_names_spec=3D'${libname}`echo ${release} | $SED -e 's/[.]/-/g'=
`${versuffix}${shared_ext} $libname.lib'
-    ;;
-  esac
-  dynamic_linker=3D'Win32 ld.exe'
-  # FIXME: first we should search . and the directory the executable is in
-  shlibpath_var=3DPATH
-  ;;
-
-darwin* | rhapsody*)
-  dynamic_linker=3D"$host_os dyld"
-  version_type=3Ddarwin
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${major}$shared_ext ${libname}=
$shared_ext ${libname}${release}${versuffix}$shared_ext'
-  soname_spec=3D'${libname}${release}${major}$shared_ext'
-  shlibpath_overrides_runpath=3Dyes
-  shlibpath_var=3DDYLD_LIBRARY_PATH
-  shrext_cmds=3D'`test .$module =3D .yes && echo .so || echo .dylib`'
-  # Apple's gcc prints 'gcc -print-search-dirs' doesn't operate the same.
-  if test "$GCC" =3D yes; then
-    sys_lib_search_path_spec=3D`$CC -print-search-dirs | tr "\n" "$PATH_SE=
PARATOR" | sed -e 's/libraries:/@libraries:/' | tr "@" "\n" | grep "^librar=
ies:" | sed -e "s/^libraries://" -e "s,=3D/,/,g" -e "s,$PATH_SEPARATOR, ,g"=
 -e "s,.*,& /lib /usr/lib /usr/local/lib,g"`
-  else
-    sys_lib_search_path_spec=3D'/lib /usr/lib /usr/local/lib'
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/local/lib /lib /usr/lib'
-  ;;
-
-dgux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname$shared_ext'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-freebsd1*)
-  dynamic_linker=3Dno
-  ;;
-
-kfreebsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-freebsd* | dragonfly*)
-  # DragonFly does not have aout.  When/if they implement a new
-  # versioning mechanism, adjust this.
-  if test -x /usr/bin/objformat; then
-    objformat=3D`/usr/bin/objformat`
-  else
-    case $host_os in
-    freebsd[123]*) objformat=3Daout ;;
-    *) objformat=3Delf ;;
-    esac
-  fi
-  version_type=3Dfreebsd-$objformat
-  case $version_type in
-    freebsd-elf*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${=
libname}${release}${shared_ext} $libname${shared_ext}'
-      need_version=3Dno
-      need_lib_prefix=3Dno
-      ;;
-    freebsd-*)
-      library_names_spec=3D'${libname}${release}${shared_ext}$versuffix $l=
ibname${shared_ext}$versuffix'
-      need_version=3Dyes
-      ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_os in
-  freebsd2*)
-    shlibpath_overrides_runpath=3Dyes
-    ;;
-  freebsd3.[01]* | freebsdelf3.[01]*)
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd3.[2-9]* | freebsdelf3.[2-9]* | \
-  freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1)
-    shlibpath_overrides_runpath=3Dno
-    hardcode_into_libs=3Dyes
-    ;;
-  freebsd*) # from 4.6 on
-    shlibpath_overrides_runpath=3Dyes
-    hardcode_into_libs=3Dyes
-    ;;
-  esac
-  ;;
-
-gnu*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}${major} ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  ;;
-
-hpux9* | hpux10* | hpux11*)
-  # Give a soname corresponding to the major version so that dld.sl refuse=
s to
-  # link against other versions.
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  case $host_cpu in
-  ia64*)
-    shrext_cmds=3D'.so'
-    hardcode_into_libs=3Dyes
-    dynamic_linker=3D"$host_os dld.so"
-    shlibpath_var=3DLD_LIBRARY_PATH
-    shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    if test "X$HPUX_IA64_MODE" =3D X32; then
-      sys_lib_search_path_spec=3D"/usr/lib/hpux32 /usr/local/lib/hpux32 /u=
sr/local/lib"
-    else
-      sys_lib_search_path_spec=3D"/usr/lib/hpux64 /usr/local/lib/hpux64"
-    fi
-    sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-    ;;
-   hppa*64*)
-     shrext_cmds=3D'.sl'
-     hardcode_into_libs=3Dyes
-     dynamic_linker=3D"$host_os dld.sl"
-     shlibpath_var=3DLD_LIBRARY_PATH # How should we handle SHLIB_PATH
-     shlibpath_overrides_runpath=3Dyes # Unless +noenvvar is specified.
-     library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${l=
ibname}${release}${shared_ext}$major $libname${shared_ext}'
-     soname_spec=3D'${libname}${release}${shared_ext}$major'
-     sys_lib_search_path_spec=3D"/usr/lib/pa20_64 /usr/ccs/lib/pa20_64"
-     sys_lib_dlsearch_path_spec=3D$sys_lib_search_path_spec
-     ;;
-   *)
-    shrext_cmds=3D'.sl'
-    dynamic_linker=3D"$host_os dld.sl"
-    shlibpath_var=3DSHLIB_PATH
-    shlibpath_overrides_runpath=3Dno # +s is required to enable SHLIB_PATH
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major $libname${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    ;;
-  esac
-  # HP-UX runs *really* slowly unless shared libraries are mode 555.
-  postinstall_cmds=3D'chmod 555 $lib'
-  ;;
-
-interix3*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  dynamic_linker=3D'Interix 3.x ld.so.1 (PE, like ELF)'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  ;;
-
-irix5* | irix6* | nonstopux*)
-  case $host_os in
-    nonstopux*) version_type=3Dnonstopux ;;
-    *)
-	if test "$lt_cv_prog_gnu_ld" =3D yes; then
-		version_type=3Dlinux
-	else
-		version_type=3Dirix
-	fi ;;
-  esac
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libnam=
e${shared_ext}'
-  case $host_os in
-  irix5* | nonstopux*)
-    libsuff=3D shlibsuff=3D
-    ;;
-  *)
-    case $LD in # libtool.m4 will add one of these switches to LD
-    *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ")
-      libsuff=3D shlibsuff=3D libmagic=3D32-bit;;
-    *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ")
-      libsuff=3D32 shlibsuff=3DN32 libmagic=3DN32;;
-    *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ")
-      libsuff=3D64 shlibsuff=3D64 libmagic=3D64-bit;;
-    *) libsuff=3D shlibsuff=3D libmagic=3Dnever-match;;
-    esac
-    ;;
-  esac
-  shlibpath_var=3DLD_LIBRARY${shlibsuff}_PATH
-  shlibpath_overrides_runpath=3Dno
-  sys_lib_search_path_spec=3D"/usr/lib${libsuff} /lib${libsuff} /usr/local=
/lib${libsuff}"
-  sys_lib_dlsearch_path_spec=3D"/usr/lib${libsuff} /lib${libsuff}"
-  hardcode_into_libs=3Dyes
-  ;;
-
-# No shared lib support for Linux oldld, aout, or coff.
-linux*oldld* | linux*aout* | linux*coff*)
-  dynamic_linker=3Dno
-  ;;
-
-# This must be Linux ELF.
-linux*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -n $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  # This implies no fast_install, which is unacceptable.
-  # Some rework will be needed to allow for fast_install
-  # before this can be enabled.
-  hardcode_into_libs=3Dyes
-
-  # Append ld.so.conf contents to the search path
-  if test -f /etc/ld.so.conf; then
-    lt_ld_extra=3D`awk '/^include / { system(sprintf("cd /etc; cat %s", \$=
2)); skip =3D 1; } { if (!skip) print \$0; skip =3D 0; }' < /etc/ld.so.conf=
 | $SED -e 's/#.*//;s/[:,	]/ /g;s/=3D[^=3D]*$//;s/=3D[^=3D ]* / /g;/^$/d' |=
 tr '\n' ' '`
-    sys_lib_dlsearch_path_spec=3D"/lib /usr/lib $lt_ld_extra"
-  fi
-
-  # We used to test for /lib/ld.so.1 and disable shared libraries on
-  # powerpc, because MkLinux only supported shared libraries with the
-  # GNU dynamic linker.  Since this was broken with cross compilers,
-  # most powerpc-linux boxes support dynamic linking these days and
-  # people can always --disable-shared, the test was removed, and we
-  # assume the GNU/Linux dynamic linker is in use.
-  dynamic_linker=3D'GNU/Linux ld.so'
-  ;;
-
-knetbsd*-gnu)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major ${libname}${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dno
-  hardcode_into_libs=3Dyes
-  dynamic_linker=3D'GNU ld.so'
-  ;;
-
-netbsd*)
-  version_type=3Dsunos
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  if echo __ELF__ | $CC -E - | grep __ELF__ >/dev/null; then
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${shared_ext}$versuffix'
-    finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-    dynamic_linker=3D'NetBSD (a.out) ld.so'
-  else
-    library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${li=
bname}${release}${shared_ext}$major ${libname}${shared_ext}'
-    soname_spec=3D'${libname}${release}${shared_ext}$major'
-    dynamic_linker=3D'NetBSD ld.elf_so'
-  fi
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  ;;
-
-newsos6)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-nto-qnx*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  ;;
-
-openbsd*)
-  version_type=3Dsunos
-  sys_lib_dlsearch_path_spec=3D"/usr/lib"
-  need_lib_prefix=3Dno
-  # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs.
-  case $host_os in
-    openbsd3.3 | openbsd3.3.*) need_version=3Dyes ;;
-    *)                         need_version=3Dno  ;;
-  esac
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/sbin" ldconfig -m $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-=
$host_cpu" =3D "openbsd2.8-powerpc"; then
-    case $host_os in
-      openbsd2.[89] | openbsd2.[89].*)
-	shlibpath_overrides_runpath=3Dno
-	;;
-      *)
-	shlibpath_overrides_runpath=3Dyes
-	;;
-      esac
-  else
-    shlibpath_overrides_runpath=3Dyes
-  fi
-  ;;
-
-os2*)
-  libname_spec=3D'$name'
-  shrext_cmds=3D".dll"
-  need_lib_prefix=3Dno
-  library_names_spec=3D'$libname${shared_ext} $libname.a'
-  dynamic_linker=3D'OS/2 ld.exe'
-  shlibpath_var=3DLIBPATH
-  ;;
-
-osf3* | osf4* | osf5*)
-  version_type=3Dosf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  sys_lib_search_path_spec=3D"/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /=
usr/lib /usr/local/lib /var/shlib"
-  sys_lib_dlsearch_path_spec=3D"$sys_lib_search_path_spec"
-  ;;
-
-solaris*)
-  version_type=3Dlinux
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  hardcode_into_libs=3Dyes
-  # ldd complains unless libraries are executable
-  postinstall_cmds=3D'chmod +x $lib'
-  ;;
-
-sunos4*)
-  version_type=3Dsunos
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${shared_ext}$versuffix'
-  finish_cmds=3D'PATH=3D"\$PATH:/usr/etc" ldconfig $libdir'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  shlibpath_overrides_runpath=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    need_lib_prefix=3Dno
-  fi
-  need_version=3Dyes
-  ;;
-
-sysv4 | sysv4.3*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  case $host_vendor in
-    sni)
-      shlibpath_overrides_runpath=3Dno
-      need_lib_prefix=3Dno
-      export_dynamic_flag_spec=3D'${wl}-Blargedynsym'
-      runpath_var=3DLD_RUN_PATH
-      ;;
-    siemens)
-      need_lib_prefix=3Dno
-      ;;
-    motorola)
-      need_lib_prefix=3Dno
-      need_version=3Dno
-      shlibpath_overrides_runpath=3Dno
-      sys_lib_search_path_spec=3D'/lib /usr/lib /usr/ccs/lib'
-      ;;
-  esac
-  ;;
-
-sysv4*MP*)
-  if test -d /usr/nec ;then
-    version_type=3Dlinux
-    library_names_spec=3D'$libname${shared_ext}.$versuffix $libname${share=
d_ext}.$major $libname${shared_ext}'
-    soname_spec=3D'$libname${shared_ext}.$major'
-    shlibpath_var=3DLD_LIBRARY_PATH
-  fi
-  ;;
-
-sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*)
-  version_type=3Dfreebsd-elf
-  need_lib_prefix=3Dno
-  need_version=3Dno
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext} $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  hardcode_into_libs=3Dyes
-  if test "$with_gnu_ld" =3D yes; then
-    sys_lib_search_path_spec=3D'/usr/local/lib /usr/gnu/lib /usr/ccs/lib /=
usr/lib /lib'
-    shlibpath_overrides_runpath=3Dno
-  else
-    sys_lib_search_path_spec=3D'/usr/ccs/lib /usr/lib'
-    shlibpath_overrides_runpath=3Dyes
-    case $host_os in
-      sco3.2v5*)
-        sys_lib_search_path_spec=3D"$sys_lib_search_path_spec /lib"
-	;;
-    esac
-  fi
-  sys_lib_dlsearch_path_spec=3D'/usr/lib'
-  ;;
-
-uts4*)
-  version_type=3Dlinux
-  library_names_spec=3D'${libname}${release}${shared_ext}$versuffix ${libn=
ame}${release}${shared_ext}$major $libname${shared_ext}'
-  soname_spec=3D'${libname}${release}${shared_ext}$major'
-  shlibpath_var=3DLD_LIBRARY_PATH
-  ;;
-
-*)
-  dynamic_linker=3Dno
-  ;;
-esac
-{ echo "$as_me:$LINENO: result: $dynamic_linker" >&5
-echo "${ECHO_T}$dynamic_linker" >&6; }
-test "$dynamic_linker" =3D no && can_build_shared=3Dno
-
-variables_saved_for_relink=3D"PATH $shlibpath_var $runpath_var"
-if test "$GCC" =3D yes; then
-  variables_saved_for_relink=3D"$variables_saved_for_relink GCC_EXEC_PREFI=
X COMPILER_PATH LIBRARY_PATH"
-fi
-
-{ echo "$as_me:$LINENO: checking how to hardcode library paths into progra=
ms" >&5
-echo $ECHO_N "checking how to hardcode library paths into programs... $ECH=
O_C" >&6; }
-hardcode_action_GCJ=3D
-if test -n "$hardcode_libdir_flag_spec_GCJ" || \
-   test -n "$runpath_var_GCJ" || \
-   test "X$hardcode_automatic_GCJ" =3D "Xyes" ; then
-
-  # We can hardcode non-existant directories.
-  if test "$hardcode_direct_GCJ" !=3D no &&
-     # If the only mechanism to avoid hardcoding is shlibpath_var, we
-     # have to relink, otherwise we might link with an installed library
-     # when we should be linking with a yet-to-be-installed one
-     ## test "$_LT_AC_TAGVAR(hardcode_shlibpath_var, GCJ)" !=3D no &&
-     test "$hardcode_minus_L_GCJ" !=3D no; then
-    # Linking always hardcodes the temporary library directory.
-    hardcode_action_GCJ=3Drelink
-  else
-    # We can link without hardcoding, and we can hardcode nonexisting dirs.
-    hardcode_action_GCJ=3Dimmediate
-  fi
-else
-  # We cannot hardcode anything, or else we can only hardcode existing
-  # directories.
-  hardcode_action_GCJ=3Dunsupported
-fi
-{ echo "$as_me:$LINENO: result: $hardcode_action_GCJ" >&5
-echo "${ECHO_T}$hardcode_action_GCJ" >&6; }
-
-if test "$hardcode_action_GCJ" =3D relink; then
-  # Fast installation is not supported
-  enable_fast_install=3Dno
-elif test "$shlibpath_overrides_runpath" =3D yes ||
-     test "$enable_shared" =3D no; then
-  # Fast installation is not necessary
-  enable_fast_install=3Dneedless
-fi
-
-
-# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our comm=
ands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTC=
FLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    compiler_GCJ \
-    CC_GCJ \
-    LD_GCJ \
-    lt_prog_compiler_wl_GCJ \
-    lt_prog_compiler_pic_GCJ \
-    lt_prog_compiler_static_GCJ \
-    lt_prog_compiler_no_builtin_flag_GCJ \
-    export_dynamic_flag_spec_GCJ \
-    thread_safe_flag_spec_GCJ \
-    whole_archive_flag_spec_GCJ \
-    enable_shared_with_static_runtimes_GCJ \
-    old_archive_cmds_GCJ \
-    old_archive_from_new_cmds_GCJ \
-    predep_objects_GCJ \
-    postdep_objects_GCJ \
-    predeps_GCJ \
-    postdeps_GCJ \
-    compiler_lib_search_path_GCJ \
-    archive_cmds_GCJ \
-    archive_expsym_cmds_GCJ \
-    postinstall_cmds_GCJ \
-    postuninstall_cmds_GCJ \
-    old_archive_from_expsyms_cmds_GCJ \
-    allow_undefined_flag_GCJ \
-    no_undefined_flag_GCJ \
-    export_symbols_cmds_GCJ \
-    hardcode_libdir_flag_spec_GCJ \
-    hardcode_libdir_flag_spec_ld_GCJ \
-    hardcode_libdir_separator_GCJ \
-    hardcode_automatic_GCJ \
-    module_cmds_GCJ \
-    module_expsym_cmds_GCJ \
-    lt_cv_prog_compiler_c_o_GCJ \
-    exclude_expsyms_GCJ \
-    include_expsyms_GCJ; do
-
-    case $var in
-    old_archive_cmds_GCJ | \
-    old_archive_from_new_cmds_GCJ | \
-    archive_cmds_GCJ | \
-    archive_expsym_cmds_GCJ | \
-    module_cmds_GCJ | \
-    module_expsym_cmds_GCJ | \
-    old_archive_from_expsyms_cmds_GCJ | \
-    export_symbols_cmds_GCJ | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quot=
e_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
-      ;;
-    *)
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_s=
ubst\"\`\\\""
-      ;;
-    esac
-  done
-
-  case $lt_echo in
-  *'\$0 --fallback-echo"')
-    lt_echo=3D`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$=
/$0 --fallback-echo"/'`
-    ;;
-  esac
-
-cfgfile=3D"$ofile"
-
-  cat <<__EOF__ >> "$cfgfile"
-# ### BEGIN LIBTOOL TAG CONFIG: $tagname
-
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed=
 1q`:
-
-# Shell to use when invoking shell scripts.
-SHELL=3D$lt_SHELL
-
-# Whether or not to build shared libraries.
-build_libtool_libs=3D$enable_shared
-
-# Whether or not to build static libraries.
-build_old_libs=3D$enable_static
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=3D$archive_cmds_need_lc_GCJ
-
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=3D$enable_shared_with_static_runti=
mes_GCJ
-
-# Whether or not to optimize for fast installation.
-fast_install=3D$enable_fast_install
-
-# The host system.
-host_alias=3D$host_alias
-host=3D$host
-host_os=3D$host_os
-
-# The build system.
-build_alias=3D$build_alias
-build=3D$build
-build_os=3D$build_os
-
-# An echo program that does not interpret backslashes.
-echo=3D$lt_echo
-
-# The archiver.
-AR=3D$lt_AR
-AR_FLAGS=3D$lt_AR_FLAGS
-
-# A C compiler.
-LTCC=3D$lt_LTCC
-
-# LTCC compiler flags.
-LTCFLAGS=3D$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=3D$lt_compiler_GCJ
-
-# Is the compiler the GNU C compiler?
-with_gcc=3D$GCC_GCJ
-
-# An ERE matcher.
-EGREP=3D$lt_EGREP
-
-# The linker used to build libraries.
-LD=3D$lt_LD_GCJ
-
-# Whether we need hard or soft links.
-LN_S=3D$lt_LN_S
-
-# A BSD-compatible nm program.
-NM=3D$lt_NM
-
-# A symbol stripping program
-STRIP=3D$lt_STRIP
-
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=3D$MAGIC_CMD
-
-# Used on cygwin: DLL creation program.
-DLLTOOL=3D"$DLLTOOL"
-
-# Used on cygwin: object dumper.
-OBJDUMP=3D"$OBJDUMP"
-
-# Used on cygwin: assembler.
-AS=3D"$AS"
-
-# The name of the directory that contains temporary libtool files.
-objdir=3D$objdir
-
-# How to create reloadable object files.
-reload_flag=3D$lt_reload_flag
-reload_cmds=3D$lt_reload_cmds
-
-# How to pass a linker flag through the compiler.
-wl=3D$lt_lt_prog_compiler_wl_GCJ
-
-# Object file suffix (normally "o").
-objext=3D"$ac_objext"
-
-# Old archive suffix (normally "a").
-libext=3D"$libext"
-
-# Shared library suffix (normally ".so").
-shrext_cmds=3D'$shrext_cmds'
-
-# Executable file suffix (normally "").
-exeext=3D"$exeext"
-
-# Additional compiler flags for building library objects.
-pic_flag=3D$lt_lt_prog_compiler_pic_GCJ
-pic_mode=3D$pic_mode
-
-# What is the maximum length of a command?
-max_cmd_len=3D$lt_cv_sys_max_cmd_len
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=3D$lt_lt_cv_prog_compiler_c_o_GCJ
-
-# Must we lock files when doing compilation?
-need_locks=3D$lt_need_locks
-
-# Do we need the lib prefix for modules?
-need_lib_prefix=3D$need_lib_prefix
-
-# Do we need a version for libraries?
-need_version=3D$need_version
-
-# Whether dlopen is supported.
-dlopen_support=3D$enable_dlopen
-
-# Whether dlopen of programs is supported.
-dlopen_self=3D$enable_dlopen_self
-
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=3D$enable_dlopen_self_static
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=3D$lt_lt_prog_compiler_static_GCJ
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=3D$lt_lt_prog_compiler_no_builtin_flag_GCJ
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=3D$lt_export_dynamic_flag_spec_GCJ
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=3D$lt_whole_archive_flag_spec_GCJ
-
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=3D$lt_thread_safe_flag_spec_GCJ
-
-# Library versioning type.
-version_type=3D$version_type
-
-# Format of library name prefix.
-libname_spec=3D$lt_libname_spec
-
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=3D$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=3D$lt_soname_spec
-
-# Commands used to build and install an old-style archive.
-RANLIB=3D$lt_RANLIB
-old_archive_cmds=3D$lt_old_archive_cmds_GCJ
-old_postinstall_cmds=3D$lt_old_postinstall_cmds
-old_postuninstall_cmds=3D$lt_old_postuninstall_cmds
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=3D$lt_old_archive_from_new_cmds_GCJ
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=3D$lt_old_archive_from_expsyms_cmds_GCJ
-
-# Commands used to build and install a shared archive.
-archive_cmds=3D$lt_archive_cmds_GCJ
-archive_expsym_cmds=3D$lt_archive_expsym_cmds_GCJ
-postinstall_cmds=3D$lt_postinstall_cmds
-postuninstall_cmds=3D$lt_postuninstall_cmds
-
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=3D$lt_module_cmds_GCJ
-module_expsym_cmds=3D$lt_module_expsym_cmds_GCJ
-
-# Commands to strip libraries.
-old_striplib=3D$lt_old_striplib
-striplib=3D$lt_striplib
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=3D$lt_predep_objects_GCJ
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=3D$lt_postdep_objects_GCJ
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=3D$lt_predeps_GCJ
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=3D$lt_postdeps_GCJ
-
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=3D$lt_compiler_lib_search_path_GCJ
-
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=3D$lt_deplibs_check_method
-
-# Command to use when deplibs_check_method =3D=3D file_magic.
-file_magic_cmd=3D$lt_file_magic_cmd
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=3D$lt_allow_undefined_flag_GCJ
-
-# Flag that forces no undefined symbols.
-no_undefined_flag=3D$lt_no_undefined_flag_GCJ
-
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=3D$lt_finish_cmds
-
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=3D$lt_finish_eval
-
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=3D$lt_lt_cv_sys_global_symbol_pipe
-
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=3D$lt_lt_cv_sys_global_symbol_to_cdecl
-
-# Transform the output of nm in a C name address pair
-global_symbol_to_c_name_address=3D$lt_lt_cv_sys_global_symbol_to_c_name_ad=
dress
-
-# This is the shared library runtime path variable.
-runpath_var=3D$runpath_var
-
-# This is the shared library path variable.
-shlibpath_var=3D$shlibpath_var
-
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=3D$shlibpath_overrides_runpath
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=3D$hardcode_action_GCJ
-
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=3D$hardcode_into_libs
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist.
-hardcode_libdir_flag_spec=3D$lt_hardcode_libdir_flag_spec_GCJ
-
-# If ld is used when linking, flag to hardcode \$libdir into
-# a binary during linking. This must work even if \$libdir does
-# not exist.
-hardcode_libdir_flag_spec_ld=3D$lt_hardcode_libdir_flag_spec_ld_GCJ
-
-# Whether we need a single -rpath flag with a separated argument.
-hardcode_libdir_separator=3D$lt_hardcode_libdir_separator_GCJ
-
-# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DI=
R into the
-# resulting binary.
-hardcode_direct=3D$hardcode_direct_GCJ
-
-# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
-# resulting binary.
-hardcode_minus_L=3D$hardcode_minus_L_GCJ
-
-# Set to yes if using SHLIBPATH_VAR=3DDIR during linking hardcodes DIR into
-# the resulting binary.
-hardcode_shlibpath_var=3D$hardcode_shlibpath_var_GCJ
-
-# Set to yes if building a shared library automatically hardcodes DIR into=
 the library
-# and all subsequent libraries and executables linked against it.
-hardcode_automatic=3D$hardcode_automatic_GCJ
-
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at relink time.
-variables_saved_for_relink=3D"$variables_saved_for_relink"
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=3D$link_all_deplibs_GCJ
-
-# Compile-time system search path for libraries
-sys_lib_search_path_spec=3D$lt_sys_lib_search_path_spec
-
-# Run-time system search path for libraries
-sys_lib_dlsearch_path_spec=3D$lt_sys_lib_dlsearch_path_spec
-
-# Fix the shell variable \$srcfile for the compiler.
-fix_srcfile_path=3D"$fix_srcfile_path_GCJ"
-
-# Set to yes if exported symbols are required.
-always_export_symbols=3D$always_export_symbols_GCJ
-
-# The commands to list exported symbols.
-export_symbols_cmds=3D$lt_export_symbols_cmds_GCJ
-
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=3D$lt_extract_expsyms_cmds
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=3D$lt_exclude_expsyms_GCJ
-
-# Symbols that must always be exported.
-include_expsyms=3D$lt_include_expsyms_GCJ
-
-# ### END LIBTOOL TAG CONFIG: $tagname
-
-__EOF__
-
-
-else
-  # If there is no Makefile yet, we rely on a make rule to execute
-  # `config.status --recheck' to rerun these tests and create the
-  # libtool script then.
-  ltmain_in=3D`echo $ltmain | sed -e 's/\.sh$/.in/'`
-  if test -f "$ltmain_in"; then
-    test -f Makefile && make "$ltmain"
-  fi
-fi
-
-
-ac_ext=3Dc
-ac_cpp=3D'$CPP $CPPFLAGS'
-ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
-
-CC=3D"$lt_save_CC"
-
-	else
-	  tagname=3D""
-	fi
-	;;
-
-      RC)
-
-
-# Source file extension for RC test sources.
-ac_ext=3Drc
-
-# Object file extension for compiled RC test sources.
-objext=3Do
-objext_RC=3D$objext
-
-# Code to be used in simple compile tests
-lt_simple_compile_test_code=3D'sample MENU { MENUITEM "&Soup", 100, CHECKE=
D }\n'
-
-# Code to be used in simple link tests
-lt_simple_link_test_code=3D"$lt_simple_compile_test_code"
-
-# ltmain only uses $CC for tagged configurations so make sure $CC is set.
-
-# If no C compiler was specified, use CC.
-LTCC=3D${LTCC-"$CC"}
-
-# If no C compiler flags were specified, use CFLAGS.
-LTCFLAGS=3D${LTCFLAGS-"$CFLAGS"}
-
-# Allow CC to be a program name with arguments.
-compiler=3D$CC
-
-
-# save warnings/boilerplate of simple test code
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_compile_test_code" >conftest.$ac_ext
-eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_compiler_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-ac_outfile=3Dconftest.$ac_objext
-printf "$lt_simple_link_test_code" >conftest.$ac_ext
-eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err
-_lt_linker_boilerplate=3D`cat conftest.err`
-$rm conftest*
-
-
-# Allow CC to be a program name with arguments.
-lt_save_CC=3D"$CC"
-CC=3D${RC-"windres"}
-compiler=3D$CC
-compiler_RC=3D$CC
-for cc_temp in $compiler""; do
-  case $cc_temp in
-    compile | *[\\/]compile | ccache | *[\\/]ccache ) ;;
-    distcc | *[\\/]distcc | purify | *[\\/]purify ) ;;
-    \-*) ;;
-    *) break;;
-  esac
-done
-cc_basename=3D`$echo "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%=
%"`
-
-lt_cv_prog_compiler_c_o_RC=3Dyes
-
-# The else clause should only fire when bootstrapping the
-# libtool distribution, otherwise you forgot to ship ltmain.sh
-# with your package, and you will get complaints that there are
-# no rules to generate ltmain.sh.
-if test -f "$ltmain"; then
-  # See if we are running on zsh, and set the options which allow our comm=
ands through
-  # without removal of \ escapes.
-  if test -n "${ZSH_VERSION+set}" ; then
-    setopt NO_GLOB_SUBST
-  fi
-  # Now quote all the things that may contain metacharacters while being
-  # careful not to overquote the AC_SUBSTed values.  We take copies of the
-  # variables and quote the copies for generation of the libtool script.
-  for var in echo old_CC old_CFLAGS AR AR_FLAGS EGREP RANLIB LN_S LTCC LTC=
FLAGS NM \
-    SED SHELL STRIP \
-    libname_spec library_names_spec soname_spec extract_expsyms_cmds \
-    old_striplib striplib file_magic_cmd finish_cmds finish_eval \
-    deplibs_check_method reload_flag reload_cmds need_locks \
-    lt_cv_sys_global_symbol_pipe lt_cv_sys_global_symbol_to_cdecl \
-    lt_cv_sys_global_symbol_to_c_name_address \
-    sys_lib_search_path_spec sys_lib_dlsearch_path_spec \
-    old_postinstall_cmds old_postuninstall_cmds \
-    compiler_RC \
-    CC_RC \
-    LD_RC \
-    lt_prog_compiler_wl_RC \
-    lt_prog_compiler_pic_RC \
-    lt_prog_compiler_static_RC \
-    lt_prog_compiler_no_builtin_flag_RC \
-    export_dynamic_flag_spec_RC \
-    thread_safe_flag_spec_RC \
-    whole_archive_flag_spec_RC \
-    enable_shared_with_static_runtimes_RC \
-    old_archive_cmds_RC \
-    old_archive_from_new_cmds_RC \
-    predep_objects_RC \
-    postdep_objects_RC \
-    predeps_RC \
-    postdeps_RC \
-    compiler_lib_search_path_RC \
-    archive_cmds_RC \
-    archive_expsym_cmds_RC \
-    postinstall_cmds_RC \
-    postuninstall_cmds_RC \
-    old_archive_from_expsyms_cmds_RC \
-    allow_undefined_flag_RC \
-    no_undefined_flag_RC \
-    export_symbols_cmds_RC \
-    hardcode_libdir_flag_spec_RC \
-    hardcode_libdir_flag_spec_ld_RC \
-    hardcode_libdir_separator_RC \
-    hardcode_automatic_RC \
-    module_cmds_RC \
-    module_expsym_cmds_RC \
-    lt_cv_prog_compiler_c_o_RC \
-    exclude_expsyms_RC \
-    include_expsyms_RC; do
-
-    case $var in
-    old_archive_cmds_RC | \
-    old_archive_from_new_cmds_RC | \
-    archive_cmds_RC | \
-    archive_expsym_cmds_RC | \
-    module_cmds_RC | \
-    module_expsym_cmds_RC | \
-    old_archive_from_expsyms_cmds_RC | \
-    export_symbols_cmds_RC | \
-    extract_expsyms_cmds | reload_cmds | finish_cmds | \
-    postinstall_cmds | postuninstall_cmds | \
-    old_postinstall_cmds | old_postuninstall_cmds | \
-    sys_lib_search_path_spec | sys_lib_dlsearch_path_spec)
-      # Double-quote double-evaled strings.
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$double_quot=
e_subst\" -e \"\$sed_quote_subst\" -e \"\$delay_variable_subst\"\`\\\""
-      ;;
-    *)
-      eval "lt_$var=3D\\\"\`\$echo \"X\$$var\" | \$Xsed -e \"\$sed_quote_s=
ubst\"\`\\\""
-      ;;
-    esac
-  done
-
-  case $lt_echo in
-  *'\$0 --fallback-echo"')
-    lt_echo=3D`$echo "X$lt_echo" | $Xsed -e 's/\\\\\\\$0 --fallback-echo"$=
/$0 --fallback-echo"/'`
-    ;;
-  esac
-
-cfgfile=3D"$ofile"
-
-  cat <<__EOF__ >> "$cfgfile"
-# ### BEGIN LIBTOOL TAG CONFIG: $tagname
-
-# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed=
 1q`:
-
-# Shell to use when invoking shell scripts.
-SHELL=3D$lt_SHELL
-
-# Whether or not to build shared libraries.
-build_libtool_libs=3D$enable_shared
-
-# Whether or not to build static libraries.
-build_old_libs=3D$enable_static
-
-# Whether or not to add -lc for building shared libraries.
-build_libtool_need_lc=3D$archive_cmds_need_lc_RC
-
-# Whether or not to disallow shared libs when runtime libs are static
-allow_libtool_libs_with_static_runtimes=3D$enable_shared_with_static_runti=
mes_RC
-
-# Whether or not to optimize for fast installation.
-fast_install=3D$enable_fast_install
-
-# The host system.
-host_alias=3D$host_alias
-host=3D$host
-host_os=3D$host_os
-
-# The build system.
-build_alias=3D$build_alias
-build=3D$build
-build_os=3D$build_os
-
-# An echo program that does not interpret backslashes.
-echo=3D$lt_echo
-
-# The archiver.
-AR=3D$lt_AR
-AR_FLAGS=3D$lt_AR_FLAGS
-
-# A C compiler.
-LTCC=3D$lt_LTCC
-
-# LTCC compiler flags.
-LTCFLAGS=3D$lt_LTCFLAGS
-
-# A language-specific compiler.
-CC=3D$lt_compiler_RC
-
-# Is the compiler the GNU C compiler?
-with_gcc=3D$GCC_RC
-
-# An ERE matcher.
-EGREP=3D$lt_EGREP
-
-# The linker used to build libraries.
-LD=3D$lt_LD_RC
-
-# Whether we need hard or soft links.
-LN_S=3D$lt_LN_S
-
-# A BSD-compatible nm program.
-NM=3D$lt_NM
-
-# A symbol stripping program
-STRIP=3D$lt_STRIP
-
-# Used to examine libraries when file_magic_cmd begins "file"
-MAGIC_CMD=3D$MAGIC_CMD
-
-# Used on cygwin: DLL creation program.
-DLLTOOL=3D"$DLLTOOL"
-
-# Used on cygwin: object dumper.
-OBJDUMP=3D"$OBJDUMP"
-
-# Used on cygwin: assembler.
-AS=3D"$AS"
-
-# The name of the directory that contains temporary libtool files.
-objdir=3D$objdir
-
-# How to create reloadable object files.
-reload_flag=3D$lt_reload_flag
-reload_cmds=3D$lt_reload_cmds
-
-# How to pass a linker flag through the compiler.
-wl=3D$lt_lt_prog_compiler_wl_RC
-
-# Object file suffix (normally "o").
-objext=3D"$ac_objext"
-
-# Old archive suffix (normally "a").
-libext=3D"$libext"
-
-# Shared library suffix (normally ".so").
-shrext_cmds=3D'$shrext_cmds'
-
-# Executable file suffix (normally "").
-exeext=3D"$exeext"
-
-# Additional compiler flags for building library objects.
-pic_flag=3D$lt_lt_prog_compiler_pic_RC
-pic_mode=3D$pic_mode
-
-# What is the maximum length of a command?
-max_cmd_len=3D$lt_cv_sys_max_cmd_len
-
-# Does compiler simultaneously support -c and -o options?
-compiler_c_o=3D$lt_lt_cv_prog_compiler_c_o_RC
-
-# Must we lock files when doing compilation?
-need_locks=3D$lt_need_locks
-
-# Do we need the lib prefix for modules?
-need_lib_prefix=3D$need_lib_prefix
-
-# Do we need a version for libraries?
-need_version=3D$need_version
-
-# Whether dlopen is supported.
-dlopen_support=3D$enable_dlopen
-
-# Whether dlopen of programs is supported.
-dlopen_self=3D$enable_dlopen_self
-
-# Whether dlopen of statically linked programs is supported.
-dlopen_self_static=3D$enable_dlopen_self_static
-
-# Compiler flag to prevent dynamic linking.
-link_static_flag=3D$lt_lt_prog_compiler_static_RC
-
-# Compiler flag to turn off builtin functions.
-no_builtin_flag=3D$lt_lt_prog_compiler_no_builtin_flag_RC
-
-# Compiler flag to allow reflexive dlopens.
-export_dynamic_flag_spec=3D$lt_export_dynamic_flag_spec_RC
-
-# Compiler flag to generate shared objects directly from archives.
-whole_archive_flag_spec=3D$lt_whole_archive_flag_spec_RC
-
-# Compiler flag to generate thread-safe objects.
-thread_safe_flag_spec=3D$lt_thread_safe_flag_spec_RC
-
-# Library versioning type.
-version_type=3D$version_type
-
-# Format of library name prefix.
-libname_spec=3D$lt_libname_spec
-
-# List of archive names.  First name is the real one, the rest are links.
-# The last name is the one that the linker finds with -lNAME.
-library_names_spec=3D$lt_library_names_spec
-
-# The coded name of the library, if different from the real name.
-soname_spec=3D$lt_soname_spec
-
-# Commands used to build and install an old-style archive.
-RANLIB=3D$lt_RANLIB
-old_archive_cmds=3D$lt_old_archive_cmds_RC
-old_postinstall_cmds=3D$lt_old_postinstall_cmds
-old_postuninstall_cmds=3D$lt_old_postuninstall_cmds
-
-# Create an old-style archive from a shared archive.
-old_archive_from_new_cmds=3D$lt_old_archive_from_new_cmds_RC
-
-# Create a temporary old-style archive to link instead of a shared archive.
-old_archive_from_expsyms_cmds=3D$lt_old_archive_from_expsyms_cmds_RC
-
-# Commands used to build and install a shared archive.
-archive_cmds=3D$lt_archive_cmds_RC
-archive_expsym_cmds=3D$lt_archive_expsym_cmds_RC
-postinstall_cmds=3D$lt_postinstall_cmds
-postuninstall_cmds=3D$lt_postuninstall_cmds
-
-# Commands used to build a loadable module (assumed same as above if empty)
-module_cmds=3D$lt_module_cmds_RC
-module_expsym_cmds=3D$lt_module_expsym_cmds_RC
-
-# Commands to strip libraries.
-old_striplib=3D$lt_old_striplib
-striplib=3D$lt_striplib
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predep_objects=3D$lt_predep_objects_RC
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdep_objects=3D$lt_postdep_objects_RC
-
-# Dependencies to place before the objects being linked to create a
-# shared library.
-predeps=3D$lt_predeps_RC
-
-# Dependencies to place after the objects being linked to create a
-# shared library.
-postdeps=3D$lt_postdeps_RC
-
-# The library search path used internally by the compiler when linking
-# a shared library.
-compiler_lib_search_path=3D$lt_compiler_lib_search_path_RC
-
-# Method to check whether dependent libraries are shared objects.
-deplibs_check_method=3D$lt_deplibs_check_method
-
-# Command to use when deplibs_check_method =3D=3D file_magic.
-file_magic_cmd=3D$lt_file_magic_cmd
-
-# Flag that allows shared libraries with undefined symbols to be built.
-allow_undefined_flag=3D$lt_allow_undefined_flag_RC
-
-# Flag that forces no undefined symbols.
-no_undefined_flag=3D$lt_no_undefined_flag_RC
-
-# Commands used to finish a libtool library installation in a directory.
-finish_cmds=3D$lt_finish_cmds
-
-# Same as above, but a single script fragment to be evaled but not shown.
-finish_eval=3D$lt_finish_eval
-
-# Take the output of nm and produce a listing of raw symbols and C names.
-global_symbol_pipe=3D$lt_lt_cv_sys_global_symbol_pipe
-
-# Transform the output of nm in a proper C declaration
-global_symbol_to_cdecl=3D$lt_lt_cv_sys_global_symbol_to_cdecl
-
-# Transform the output of nm in a C name address pair
-global_symbol_to_c_name_address=3D$lt_lt_cv_sys_global_symbol_to_c_name_ad=
dress
-
-# This is the shared library runtime path variable.
-runpath_var=3D$runpath_var
-
-# This is the shared library path variable.
-shlibpath_var=3D$shlibpath_var
-
-# Is shlibpath searched before the hard-coded library search path?
-shlibpath_overrides_runpath=3D$shlibpath_overrides_runpath
-
-# How to hardcode a shared library path into an executable.
-hardcode_action=3D$hardcode_action_RC
-
-# Whether we should hardcode library paths into libraries.
-hardcode_into_libs=3D$hardcode_into_libs
-
-# Flag to hardcode \$libdir into a binary during linking.
-# This must work even if \$libdir does not exist.
-hardcode_libdir_flag_spec=3D$lt_hardcode_libdir_flag_spec_RC
-
-# If ld is used when linking, flag to hardcode \$libdir into
-# a binary during linking. This must work even if \$libdir does
-# not exist.
-hardcode_libdir_flag_spec_ld=3D$lt_hardcode_libdir_flag_spec_ld_RC
-
-# Whether we need a single -rpath flag with a separated argument.
-hardcode_libdir_separator=3D$lt_hardcode_libdir_separator_RC
-
-# Set to yes if using DIR/libNAME${shared_ext} during linking hardcodes DI=
R into the
-# resulting binary.
-hardcode_direct=3D$hardcode_direct_RC
-
-# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
-# resulting binary.
-hardcode_minus_L=3D$hardcode_minus_L_RC
-
-# Set to yes if using SHLIBPATH_VAR=3DDIR during linking hardcodes DIR into
-# the resulting binary.
-hardcode_shlibpath_var=3D$hardcode_shlibpath_var_RC
-
-# Set to yes if building a shared library automatically hardcodes DIR into=
 the library
-# and all subsequent libraries and executables linked against it.
-hardcode_automatic=3D$hardcode_automatic_RC
-
-# Variables whose values should be saved in libtool wrapper scripts and
-# restored at relink time.
-variables_saved_for_relink=3D"$variables_saved_for_relink"
-
-# Whether libtool must link a program against all its dependency libraries.
-link_all_deplibs=3D$link_all_deplibs_RC
-
-# Compile-time system search path for libraries
-sys_lib_search_path_spec=3D$lt_sys_lib_search_path_spec
-
-# Run-time system search path for libraries
-sys_lib_dlsearch_path_spec=3D$lt_sys_lib_dlsearch_path_spec
-
-# Fix the shell variable \$srcfile for the compiler.
-fix_srcfile_path=3D"$fix_srcfile_path_RC"
-
-# Set to yes if exported symbols are required.
-always_export_symbols=3D$always_export_symbols_RC
-
-# The commands to list exported symbols.
-export_symbols_cmds=3D$lt_export_symbols_cmds_RC
-
-# The commands to extract the exported symbol list from a shared archive.
-extract_expsyms_cmds=3D$lt_extract_expsyms_cmds
-
-# Symbols that should not be listed in the preloaded symbols.
-exclude_expsyms=3D$lt_exclude_expsyms_RC
-
-# Symbols that must always be exported.
-include_expsyms=3D$lt_include_expsyms_RC
-
-# ### END LIBTOOL TAG CONFIG: $tagname
-
-__EOF__
-
-
-else
-  # If there is no Makefile yet, we rely on a make rule to execute
-  # `config.status --recheck' to rerun these tests and create the
-  # libtool script then.
-  ltmain_in=3D`echo $ltmain | sed -e 's/\.sh$/.in/'`
-  if test -f "$ltmain_in"; then
-    test -f Makefile && make "$ltmain"
-  fi
-fi
-
-
-ac_ext=3Dc
-ac_cpp=3D'$CPP $CPPFLAGS'
-ac_compile=3D'$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link=3D'$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$=
ac_ext $LIBS >&5'
-ac_compiler_gnu=3D$ac_cv_c_compiler_gnu
-
-CC=3D"$lt_save_CC"
-
-	;;
-
-      *)
-	{ { echo "$as_me:$LINENO: error: Unsupported tag name: $tagname" >&5
-echo "$as_me: error: Unsupported tag name: $tagname" >&2;}
-   { (exit 1); exit 1; }; }
-	;;
-      esac
-
-      # Append the new tag name to the list of available tags.
-      if test -n "$tagname" ; then
-      available_tags=3D"$available_tags $tagname"
-    fi
-    fi
-  done
-  IFS=3D"$lt_save_ifs"
-
-  # Now substitute the updated list of available tags.
-  if eval "sed -e 's/^available_tags=3D.*\$/available_tags=3D\"$available_=
tags\"/' \"$ofile\" > \"${ofile}T\""; then
-    mv "${ofile}T" "$ofile"
-    chmod +x "$ofile"
-  else
-    rm -f "${ofile}T"
-    { { echo "$as_me:$LINENO: error: unable to update list of available ta=
gged configurations." >&5
-echo "$as_me: error: unable to update list of available tagged configurati=
ons." >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-fi
-
-
-
-# This can be used to rebuild libtool when needed
-LIBTOOL_DEPS=3D"$ac_aux_dir/ltmain.sh"
-
-# Always use our own libtool.
-LIBTOOL=3D'$(SHELL) $(top_builddir)/libtool'
-
-# Prevent multiple expansion
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+eval ac_try_echo=3D"\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$LEX conftest.l") 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking lex output file root" >&5
+$as_echo_n "checking lex output file root... " >&6; }
+if test "${ac_cv_prog_lex_root+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+if test -f lex.yy.c; then
+  ac_cv_prog_lex_root=3Dlex.yy
+elif test -f lexyy.c; then
+  ac_cv_prog_lex_root=3Dlexyy
+else
+  as_fn_error "cannot find output from $LEX; giving up" "$LINENO" 5
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_lex_root" >&5
+$as_echo "$ac_cv_prog_lex_root" >&6; }
+LEX_OUTPUT_ROOT=3D$ac_cv_prog_lex_root
+
+if test -z "${LEXLIB+set}"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking lex library" >&5
+$as_echo_n "checking lex library... " >&6; }
+if test "${ac_cv_lib_lex+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    ac_save_LIBS=3D$LIBS
+    ac_cv_lib_lex=3D'none needed'
+    for ac_lib in '' -lfl -ll; do
+      LIBS=3D"$ac_lib $ac_save_LIBS"
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+`cat $LEX_OUTPUT_ROOT.c`
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_lex=3D$ac_lib
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+      test "$ac_cv_lib_lex" !=3D 'none needed' && break
+    done
+    LIBS=3D$ac_save_LIBS
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_lex" >&5
+$as_echo "$ac_cv_lib_lex" >&6; }
+  test "$ac_cv_lib_lex" !=3D 'none needed' && LEXLIB=3D$ac_cv_lib_lex
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether yytext is a poin=
ter" >&5
+$as_echo_n "checking whether yytext is a pointer... " >&6; }
+if test "${ac_cv_prog_lex_yytext_pointer+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  # POSIX says lex can declare yytext either as a pointer or an array; the
+# default is implementation-dependent.  Figure out which it is, since
+# not all implementations provide the %pointer and %array declarations.
+ac_cv_prog_lex_yytext_pointer=3Dno
+ac_save_LIBS=3D$LIBS
+LIBS=3D"$LEXLIB $ac_save_LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#define YYTEXT_POINTER 1
+`cat $LEX_OUTPUT_ROOT.c`
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_prog_lex_yytext_pointer=3Dyes
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=3D$ac_save_LIBS
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_lex_yytext_po=
inter" >&5
+$as_echo "$ac_cv_prog_lex_yytext_pointer" >&6; }
+if test $ac_cv_prog_lex_yytext_pointer =3D yes; then
+
+$as_echo "#define YYTEXT_POINTER 1" >>confdefs.h
+
+fi
+rm -f conftest.l $LEX_OUTPUT_ROOT.c
+
+fi
+if test "$LEX" =3D :; then
+  LEX=3D${am_missing_run}flex
+fi
+for ac_prog in gawk mawk nawk awk
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with=
 args.
+set dummy $ac_prog; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_AWK+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$AWK"; then
+  ac_cv_prog_AWK=3D"$AWK" # Let the user override the test.
+else
+as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_prog_AWK=3D"$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+fi
+fi
+AWK=3D$ac_cv_prog_AWK
+if test -n "$AWK"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5
+$as_echo "$AWK" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$AWK" && break
+done
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ln -s or something e=
lse" >&5
+$as_echo_n "checking for ln -s or something else... " >&6; }
+if test "${ac_cv_prog_LN_S+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  rm -f conftestdata
+if ln -s X conftestdata 2>/dev/null
+then
+  rm -f conftestdata
+  ac_cv_prog_LN_S=3D"ln -s"
+else
+  touch conftestdata1
+  if ln conftestdata1 conftestdata2; then
+    rm -f conftestdata*
+    ac_cv_prog_LN_S=3Dln
+  else
+    ac_cv_prog_LN_S=3Dcp
+  fi
+fi
+fi
+LN_S=3D"$ac_cv_prog_LN_S"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_LN_S" >&5
+$as_echo "$ac_cv_prog_LN_S" >&6; }
+
+
+
+
+# Check whether --with-mips_abi was given.
+if test "${with_mips_abi+set}" =3D set; then :
+  withval=3D$with_mips_abi;
+fi
+
+
+case "$host_os" in
+irix*)
+with_mips_abi=3D"${with_mips_abi:-yes}"
+if test -n "$GCC"; then
+
+# GCC < 2.8 only supports the O32 ABI. GCC >=3D 2.8 has a flag to select
+# which ABI to use, but only supports (as of 2.8.1) the N32 and 64 ABIs.
+#
+# Default to N32, but if GCC doesn't grok -mabi=3Dn32, we assume an old
+# GCC and revert back to O32. The same goes if O32 is asked for - old
+# GCCs doesn't like the -mabi option, and new GCCs can't output O32.
+#
+# Don't you just love *all* the different SGI ABIs?
+
+case "${with_mips_abi}" in
+        32|o32) abi=3D'-mabi=3D32';  abilibdirext=3D''     ;;
+       n32|yes) abi=3D'-mabi=3Dn32'; abilibdirext=3D'32'  ;;
+        64) abi=3D'-mabi=3D64';  abilibdirext=3D'64'   ;;
+	no) abi=3D''; abilibdirext=3D'';;
+         *) as_fn_error "\"Invalid ABI specified\"" "$LINENO" 5 ;;
+esac
+if test -n "$abi" ; then
+ac_foo=3Dkrb_cv_gcc_`echo $abi | tr =3D- __`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC supports the $abi=
 option" >&5
+$as_echo_n "checking if $CC supports the $abi option... " >&6; }
+if { as_var=3D$ac_foo; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+
+save_CFLAGS=3D"$CFLAGS"
+CFLAGS=3D"$CFLAGS $abi"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+int x;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval $ac_foo=3Dyes
+else
+  eval $ac_foo=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_extCFLAGS=3D"$sav=
e_CFLAGS"
+
+fi
+
+ac_res=3D`eval echo \\\$$ac_foo`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if test $ac_res =3D no; then
+# Try to figure out why that failed...
+case $abi in
+	-mabi=3D32)
+	save_CFLAGS=3D"$CFLAGS"
+	CFLAGS=3D"$CFLAGS -mabi=3Dn32"
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+int x;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_res=3Dyes
+else
+  ac_res=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext	CLAGS=3D"$sav=
e_CFLAGS"
+	if test $ac_res =3D yes; then
+		# New GCC
+		as_fn_error "$CC does not support the $with_mips_abi ABI" "$LINENO" 5
+	fi
+	# Old GCC
+	abi=3D''
+	abilibdirext=3D''
+	;;
+	-mabi=3Dn32|-mabi=3D64)
+		if test $with_mips_abi =3D yes; then
+			# Old GCC, default to O32
+			abi=3D''
+			abilibdirext=3D''
+		else
+			# Some broken GCC
+			as_fn_error "$CC does not support the $with_mips_abi ABI" "$LINENO" 5
+		fi
+	;;
+esac
+fi #if test $ac_res =3D no; then
+fi #if test -n "$abi" ; then
+else
+case "${with_mips_abi}" in
+        32|o32) abi=3D'-32'; abilibdirext=3D''     ;;
+       n32|yes) abi=3D'-n32'; abilibdirext=3D'32'  ;;
+        64) abi=3D'-64'; abilibdirext=3D'64'   ;;
+	no) abi=3D''; abilibdirext=3D'';;
+         *) as_fn_error "\"Invalid ABI specified\"" "$LINENO" 5 ;;
+esac
+fi #if test -n "$GCC"; then
+;;
+esac
+
+CC=3D"$CC $abi"
+libdir=3D"$libdir$abilibdirext"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for __attribute__" >&5
+$as_echo_n "checking for __attribute__... " >&6; }
+if test "${ac_cv___attribute__+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+static void foo(void) __attribute__ ((noreturn));
+
+static void
+foo(void)
+{
+  exit(1);
+}
+
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv___attribute__=3Dyes
+else
+  ac_cv___attribute__=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+if test "$ac_cv___attribute__" =3D "yes"; then
+
+$as_echo "#define HAVE___ATTRIBUTE__ 1" >>confdefs.h
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv___attribute__" >&5
+$as_echo "$ac_cv___attribute__" >&6; }
=20
=20
=20
@@ -20205,10 +12752,10 @@
 fi
=20
=20
-{ echo "$as_me:$LINENO: checking for ld --version-script" >&5
-echo $ECHO_N "checking for ld --version-script... $ECHO_C" >&6; }
-if test "${rk_cv_version_script+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld --version-script"=
 >&5
+$as_echo_n "checking for ld --version-script... " >&6; }
+if test "${rk_cv_version_script+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
   rk_cv_version_script=3Dno
@@ -20225,22 +12772,26 @@
 int gss_init_creds(int foo) { return 0; }
 EOF
=20
-  if { ac_try=3D'${CC-cc} $CFLAGS $LDFLAGS -shared
-                               -o conftest.so conftest.c
-                               -Wl,--version-script,conftest.map'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
+  if { ac_try=3D'${CC-cc} -c $CFLAGS -fPIC conftest.c'
+  { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5
   (eval $ac_try) 2>&5
   ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; };
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; }  &&
+     { ac_try=3D'${CC-cc} -shared -Wl,--version-script,conftest.map $CFLAG=
S $LDFLAGS -o libconftestlib.so conftest.o'
+  { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5
+  (eval $ac_try) 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; };
   then
     rk_cv_version_script=3Dyes
   fi
-rm -f conftest*
-
-fi
-{ echo "$as_me:$LINENO: result: $rk_cv_version_script" >&5
-echo "${ECHO_T}$rk_cv_version_script" >&6; }
+rm -rf conftest* libconftest* .libs
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $rk_cv_version_script" >&5
+$as_echo "$rk_cv_version_script" >&6; }
=20
 if test $rk_cv_version_script =3D yes ; then
   doversioning=3Dyes
@@ -20265,18 +12816,68 @@
=20
=20
=20
+
+ if test "${cross_compiling}" =3D yes; then
+  CROSS_COMPILE_TRUE=3D
+  CROSS_COMPILE_FALSE=3D'#'
+else
+  CROSS_COMPILE_TRUE=3D'#'
+  CROSS_COMPILE_FALSE=3D
+fi
+
+
+
+# Check whether --with-cross-tools was given.
+if test "${with_cross_tools+set}" =3D set; then :
+  withval=3D$with_cross_tools; if test "$withval" =3D "yes"; then
+		as_fn_error "Need path to cross tools" "$LINENO" 5
+	fi
+	with_cross_tools=3D"${with_cross_tools}/"
+
+fi
+
+
+if test "${cross_compiling}" !=3D yes ; then
+
+   ASN1_COMPILE=3D"\$(top_builddir)/lib/asn1/asn1_compile\$(EXEEXT)"
+   SLC=3D"\$(top_builddir)/lib/sl/slc"
+
+   ASN1_COMPILE_DEP=3D"\$(ASN1_COMPILE)"
+   SLC_DEP=3D"\$(SLC)"
+else
+   ASN1_COMPILE=3D"${with_cross_tools}asn1_compile"
+   SLC=3D"${with_cross_tools}slc"
+
+   ASN1_COMPILE_DEP=3D
+   SLC_DEP=3D
+
+   ac_cv_prog_COMPILE_ET=3D${with_cross_tools}compile_et
+
+fi
+
+
+
+
+
+
+
+
+
+$as_echo "#define HEIM_WEAK_CRYPTO 1" >>confdefs.h
+
+
+
+
 # Check whether --with-openldap was given.
-if test "${with_openldap+set}" =3D set; then
+if test "${with_openldap+set}" =3D set; then :
   withval=3D$with_openldap;
 fi
=20
=20
 # Check whether --with-openldap-lib was given.
-if test "${with_openldap_lib+set}" =3D set; then
+if test "${with_openldap_lib+set}" =3D set; then :
   withval=3D$with_openldap_lib; if test "$withval" =3D "yes" -o "$withval"=
 =3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-openldap-lib" >&5
-echo "$as_me: error: No argument for --with-openldap-lib" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-openldap-lib" "$LINENO" 5
 elif test "X$with_openldap" =3D "X"; then
   with_openldap=3Dyes
 fi
@@ -20284,11 +12885,9 @@
=20
=20
 # Check whether --with-openldap-include was given.
-if test "${with_openldap_include+set}" =3D set; then
+if test "${with_openldap_include+set}" =3D set; then :
   withval=3D$with_openldap_include; if test "$withval" =3D "yes" -o "$with=
val" =3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-openldap-include=
" >&5
-echo "$as_me: error: No argument for --with-openldap-include" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-openldap-include" "$LINENO" 5
 elif test "X$with_openldap" =3D "X"; then
   with_openldap=3Dyes
 fi
@@ -20296,15 +12895,15 @@
=20
=20
 # Check whether --with-openldap-config was given.
-if test "${with_openldap_config+set}" =3D set; then
+if test "${with_openldap_config+set}" =3D set; then :
   withval=3D$with_openldap_config;
 fi
=20
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for openldap" >&5
-echo $ECHO_N "checking for openldap... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for openldap" >&5
+$as_echo_n "checking for openldap... " >&6; }
=20
 case "$with_openldap" in
 yes|"") d=3D'' ;;
@@ -20368,11 +12967,8 @@
 	if test "$openldap_cflags" -a "$openldap_libs"; then
 		CFLAGS=3D"$openldap_cflags $save_CFLAGS"
 		LIBS=3D"$openldap_libs $save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <lber.h>
 #include <ldap.h>
@@ -20384,49 +12980,23 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
=20
 			INCLUDE_openldap=3D"$openldap_cflags"
 			LIB_openldap=3D"$openldap_libs"
-			{ echo "$as_me:$LINENO: result: from $with_openldap_config" >&5
-echo "${ECHO_T}from $with_openldap_config" >&6; }
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: from $with_openldap_co=
nfig" >&5
+$as_echo "from $with_openldap_config" >&6; }
 			found=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	fi
 	if test "$found" =3D no; then
 		ires=3D lres=3D
 		for i in $header_dirs; do
 			CFLAGS=3D"-I$i $save_CFLAGS"
-			cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <lber.h>
 #include <ldap.h>
@@ -20438,40 +13008,14 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ires=3D$i;break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 		done
 		for i in $lib_dirs; do
 			LIBS=3D"-L$i -lldap -llber  $save_LIBS"
-			cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <lber.h>
 #include <ldap.h>
@@ -20483,41 +13027,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   lres=3D$i;break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 		done
 		if test "$ires" -a "$lres" -a "$with_openldap" !=3D "no"; then
 			INCLUDE_openldap=3D"-I$ires"
 			LIB_openldap=3D"-L$lres -lldap -llber "
 			found=3Dyes
-			{ echo "$as_me:$LINENO: result: headers $ires, libraries $lres" >&5
-echo "${ECHO_T}headers $ires, libraries $lres" >&6; }
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: headers $ires, librari=
es $lres" >&5
+$as_echo "headers $ires, libraries $lres" >&6; }
 		fi
 	fi
 	CFLAGS=3D"$save_CFLAGS"
@@ -20535,8 +13056,8 @@
 	with_openldap=3Dno
 	INCLUDE_openldap=3D
 	LIB_openldap=3D
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -20544,15 +13065,13 @@
=20
=20
 # Check whether --enable-hdb-openldap-module was given.
-if test "${enable_hdb_openldap_module+set}" =3D set; then
+if test "${enable_hdb_openldap_module+set}" =3D set; then :
   enableval=3D$enable_hdb_openldap_module;
 fi
=20
 if test "$enable_hdb_openldap_module" =3D yes -a "$with_openldap" =3D yes;=
 then
=20
-cat >>confdefs.h <<\_ACEOF
-#define OPENLDAP_MODULE 1
-_ACEOF
+$as_echo "#define OPENLDAP_MODULE 1" >>confdefs.h
=20
 fi
  if test "$enable_hdb_openldap_module" =3D yes -a "$with_openldap" =3D yes=
; then
@@ -20564,16 +13083,15 @@
 fi
=20
=20
+
 # Check whether --enable-pk-init was given.
-if test "${enable_pk_init+set}" =3D set; then
+if test "${enable_pk_init+set}" =3D set; then :
   enableval=3D$enable_pk_init;
 fi
=20
 if test "$enable_pk_init" !=3D no ;then
=20
-cat >>confdefs.h <<\_ACEOF
-#define PKINIT 1
-_ACEOF
+$as_echo "#define PKINIT 1" >>confdefs.h
=20
 fi
  if test "$enable_pk_init" !=3D no; then
@@ -20585,10 +13103,683 @@
 fi
=20
=20
+# Check whether --enable-digest was given.
+if test "${enable_digest+set}" =3D set; then :
+  enableval=3D$enable_digest;
+fi
+
+if test "$enable_digest" !=3D no ;then
+
+$as_echo "#define DIGEST 1" >>confdefs.h
+
+fi
+
+# Check whether --enable-kx509 was given.
+if test "${enable_kx509+set}" =3D set; then :
+  enableval=3D$enable_kx509;
+fi
+
+if test "$enable_kx509" !=3D no ;then
+
+$as_echo "#define KX509 1" >>confdefs.h
+
+fi
+
+
+
+if test "x$ac_cv_env_PKG_CONFIG_set" !=3D "xset"; then
+	if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be =
a program name with args.
+set dummy ${ac_tool_prefix}pkg-config; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_path_PKG_CONFIG+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $PKG_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PKG_CONFIG=3D"$PKG_CONFIG" # Let the user override the test w=
ith a path.
+  ;;
+  *)
+  as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_path_PKG_CONFIG=3D"$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+  ;;
+esac
+fi
+PKG_CONFIG=3D$ac_cv_path_PKG_CONFIG
+if test -n "$PKG_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5
+$as_echo "$PKG_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_path_PKG_CONFIG"; then
+  ac_pt_PKG_CONFIG=3D$PKG_CONFIG
+  # Extract the first word of "pkg-config", so it can be a program name wi=
th args.
+set dummy pkg-config; ac_word=3D$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $ac_pt_PKG_CONFIG in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_ac_pt_PKG_CONFIG=3D"$ac_pt_PKG_CONFIG" # Let the user overrid=
e the test with a path.
+  ;;
+  *)
+  as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
+    ac_cv_path_ac_pt_PKG_CONFIG=3D"$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=3D$as_save_IFS
+
+  ;;
+esac
+fi
+ac_pt_PKG_CONFIG=3D$ac_cv_path_ac_pt_PKG_CONFIG
+if test -n "$ac_pt_PKG_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5
+$as_echo "$ac_pt_PKG_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_pt_PKG_CONFIG" =3D x; then
+    PKG_CONFIG=3D""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not pr=
efixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triple=
t" >&2;}
+ac_tool_warned=3Dyes ;;
+esac
+    PKG_CONFIG=3D$ac_pt_PKG_CONFIG
+  fi
+else
+  PKG_CONFIG=3D"$ac_cv_path_PKG_CONFIG"
+fi
+
+fi
+if test -n "$PKG_CONFIG"; then
+	_pkg_min_version=3D0.9.0
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least =
version $_pkg_min_version" >&5
+$as_echo_n "checking pkg-config is at least version $_pkg_min_version... "=
 >&6; }
+	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
+		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+	else
+		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+		PKG_CONFIG=3D""
+	fi
+
+fi
+
+
+# Check whether --with-capng was given.
+if test "${with_capng+set}" =3D set; then :
+  withval=3D$with_capng;
+else
+  with_capng=3Dcheck
+fi
+
+if test "$with_capng" !=3D "no"; then
+
+pkg_failed=3Dno
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for CAPNG" >&5
+$as_echo_n "checking for CAPNG... " >&6; }
+
+if test -n "$PKG_CONFIG"; then
+    if test -n "$CAPNG_CFLAGS"; then
+        pkg_cv_CAPNG_CFLAGS=3D"$CAPNG_CFLAGS"
+    else
+        if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --pri=
nt-errors \"libcap-ng >=3D 0.4.0\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "libcap-ng >=3D 0.4.0") 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then
+  pkg_cv_CAPNG_CFLAGS=3D`$PKG_CONFIG --cflags "libcap-ng >=3D 0.4.0" 2>/de=
v/null`
+else
+  pkg_failed=3Dyes
+fi
+    fi
+else
+	pkg_failed=3Duntried
+fi
+if test -n "$PKG_CONFIG"; then
+    if test -n "$CAPNG_LIBS"; then
+        pkg_cv_CAPNG_LIBS=3D"$CAPNG_LIBS"
+    else
+        if test -n "$PKG_CONFIG" && \
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --pri=
nt-errors \"libcap-ng >=3D 0.4.0\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "libcap-ng >=3D 0.4.0") 2>&5
+  ac_status=3D$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? =3D $ac_status" >&5
+  test $ac_status =3D 0; }; then
+  pkg_cv_CAPNG_LIBS=3D`$PKG_CONFIG --libs "libcap-ng >=3D 0.4.0" 2>/dev/nu=
ll`
+else
+  pkg_failed=3Dyes
+fi
+    fi
+else
+	pkg_failed=3Duntried
+fi
+
+
+
+if test $pkg_failed =3D yes; then
+
+if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
+        _pkg_short_errors_supported=3Dyes
+else
+        _pkg_short_errors_supported=3Dno
+fi
+        if test $_pkg_short_errors_supported =3D yes; then
+	        CAPNG_PKG_ERRORS=3D`$PKG_CONFIG --short-errors --errors-to-stdout=
 --print-errors "libcap-ng >=3D 0.4.0"`
+        else
+	        CAPNG_PKG_ERRORS=3D`$PKG_CONFIG --errors-to-stdout --print-errors=
 "libcap-ng >=3D 0.4.0"`
+        fi
+	# Put the nasty error message in config.log where it belongs
+	echo "$CAPNG_PKG_ERRORS" >&5
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+                with_capng=3Dno
+elif test $pkg_failed =3D untried; then
+	with_capng=3Dno
+else
+	CAPNG_CFLAGS=3D$pkg_cv_CAPNG_CFLAGS
+	CAPNG_LIBS=3D$pkg_cv_CAPNG_LIBS
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+	with_capng=3Dyes
+fi
+fi
+if test "$with_capng" =3D "yes"; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_CAPNG 1
+_ACEOF
+
+fi
+ if test "$with_capng" !=3D "no"; then
+  HAVE_CAPNG_TRUE=3D
+  HAVE_CAPNG_FALSE=3D'#'
+else
+  HAVE_CAPNG_TRUE=3D'#'
+  HAVE_CAPNG_FALSE=3D
+fi
+
+
+
+
+
+
+# Check whether --with-sqlite3 was given.
+if test "${with_sqlite3+set}" =3D set; then :
+  withval=3D$with_sqlite3;
+fi
+
+
+# Check whether --with-sqlite3-lib was given.
+if test "${with_sqlite3_lib+set}" =3D set; then :
+  withval=3D$with_sqlite3_lib; if test "$withval" =3D "yes" -o "$withval" =
=3D "no"; then
+  as_fn_error "No argument for --with-sqlite3-lib" "$LINENO" 5
+elif test "X$with_sqlite3" =3D "X"; then
+  with_sqlite3=3Dyes
+fi
+fi
+
+
+# Check whether --with-sqlite3-include was given.
+if test "${with_sqlite3_include+set}" =3D set; then :
+  withval=3D$with_sqlite3_include; if test "$withval" =3D "yes" -o "$withv=
al" =3D "no"; then
+  as_fn_error "No argument for --with-sqlite3-include" "$LINENO" 5
+elif test "X$with_sqlite3" =3D "X"; then
+  with_sqlite3=3Dyes
+fi
+fi
+
+
+# Check whether --with-sqlite3-config was given.
+if test "${with_sqlite3_config+set}" =3D set; then :
+  withval=3D$with_sqlite3_config;
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sqlite3" >&5
+$as_echo_n "checking for sqlite3... " >&6; }
+
+case "$with_sqlite3" in
+yes|"") d=3D'' ;;
+no)	d=3D ;;
+*)	d=3D"$with_sqlite3" ;;
+esac
+
+header_dirs=3D
+lib_dirs=3D
+for i in $d; do
+	if test "$with_sqlite3_include" =3D ""; then
+		if test -d "$i/include/sqlite3"; then
+			header_dirs=3D"$header_dirs $i/include/sqlite3"
+		fi
+		if test -d "$i/include"; then
+			header_dirs=3D"$header_dirs $i/include"
+		fi
+	fi
+	if test "$with_sqlite3_lib" =3D ""; then
+		if test -d "$i/lib$abilibdirext"; then
+			lib_dirs=3D"$lib_dirs $i/lib$abilibdirext"
+		fi
+	fi
+done
+
+if test "$with_sqlite3_include"; then
+	header_dirs=3D"$with_sqlite3_include $header_dirs"
+fi
+if test "$with_sqlite3_lib"; then
+	lib_dirs=3D"$with_sqlite3_lib $lib_dirs"
+fi
+
+if test "$with_sqlite3_config" =3D ""; then
+	with_sqlite3_config=3D''
+fi
+
+sqlite3_cflags=3D
+sqlite3_libs=3D
+
+case "$with_sqlite3_config" in
+yes|no|""|"")
+	if test -f $with_sqlite3/bin/ ; then
+		with_sqlite3_config=3D$with_sqlite3/bin/
+	fi
+	;;
+esac
+
+case "$with_sqlite3_config" in
+yes|no|"")
+	;;
+*)
+	sqlite3_cflags=3D"`$with_sqlite3_config --cflags 2>&1`"
+	sqlite3_libs=3D"`$with_sqlite3_config --libs 2>&1`"
+	;;
+esac
+
+found=3Dno
+if test "$with_sqlite3" !=3D no; then
+	save_CFLAGS=3D"$CFLAGS"
+	save_LIBS=3D"$LIBS"
+	if test "$sqlite3_cflags" -a "$sqlite3_libs"; then
+		CFLAGS=3D"$sqlite3_cflags $save_CFLAGS"
+		LIBS=3D"$sqlite3_libs $save_LIBS"
+
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sqlite3.h>
+#ifndef SQLITE_OPEN_CREATE
+#error "old version"
+#endif
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+
+			INCLUDE_sqlite3=3D"$sqlite3_cflags"
+			LIB_sqlite3=3D"$sqlite3_libs"
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: from $with_sqlite3_con=
fig" >&5
+$as_echo "from $with_sqlite3_config" >&6; }
+			found=3Dyes
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	fi
+	if test "$found" =3D no; then
+		ires=3D lres=3D
+		for i in $header_dirs; do
+			CFLAGS=3D"-I$i $save_CFLAGS"
+
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sqlite3.h>
+#ifndef SQLITE_OPEN_CREATE
+#error "old version"
+#endif
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ires=3D$i;break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+		done
+		for i in $lib_dirs; do
+			LIBS=3D"-L$i -lsqlite3  $save_LIBS"
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sqlite3.h>
+#ifndef SQLITE_OPEN_CREATE
+#error "old version"
+#endif
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  lres=3D$i;break
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+		done
+		if test "$ires" -a "$lres" -a "$with_sqlite3" !=3D "no"; then
+			INCLUDE_sqlite3=3D"-I$ires"
+			LIB_sqlite3=3D"-L$lres -lsqlite3 "
+			found=3Dyes
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: headers $ires, librari=
es $lres" >&5
+$as_echo "headers $ires, libraries $lres" >&6; }
+		fi
+	fi
+	CFLAGS=3D"$save_CFLAGS"
+	LIBS=3D"$save_LIBS"
+fi
+
+if test "$found" =3D yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define SQLITE3 1
+_ACEOF
+
+	with_sqlite3=3Dyes
+else
+	with_sqlite3=3Dno
+	INCLUDE_sqlite3=3D
+	LIB_sqlite3=3D
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+
+
+
+if test "X$with_sqlite3" !=3D Xyes ; then
+   INCLUDE_sqlite3=3D"-I\$(top_srcdir)/lib/sqlite"
+   LIB_sqlite3=3D"\$(top_builddir)/lib/sqlite/libheimsqlite.la"
+fi
+ if test "X$with_sqlite3" =3D Xyes; then
+  SQLITE3_TRUE=3D
+  SQLITE3_FALSE=3D'#'
+else
+  SQLITE3_TRUE=3D'#'
+  SQLITE3_FALSE=3D
+fi
+
+
+
+$as_echo "#define HAVE_SQLITE3 1" >>confdefs.h
+
+
+# Check whether --enable-sqlite-cache was given.
+if test "${enable_sqlite_cache+set}" =3D set; then :
+  enableval=3D$enable_sqlite_cache;
+fi
+
+if test "$enable_sqlite_cache" !=3D no; then
+
+$as_echo "#define HAVE_SCC 1" >>confdefs.h
+
+fi
+ if test "$enable_sqlite_cache" !=3D no; then
+  have_scc_TRUE=3D
+  have_scc_FALSE=3D'#'
+else
+  have_scc_TRUE=3D'#'
+  have_scc_FALSE=3D
+fi
+
+
+
+
+
+# Check whether --with-libintl was given.
+if test "${with_libintl+set}" =3D set; then :
+  withval=3D$with_libintl;
+fi
+
+
+# Check whether --with-libintl-lib was given.
+if test "${with_libintl_lib+set}" =3D set; then :
+  withval=3D$with_libintl_lib; if test "$withval" =3D "yes" -o "$withval" =
=3D "no"; then
+  as_fn_error "No argument for --with-libintl-lib" "$LINENO" 5
+elif test "X$with_libintl" =3D "X"; then
+  with_libintl=3Dyes
+fi
+fi
+
+
+# Check whether --with-libintl-include was given.
+if test "${with_libintl_include+set}" =3D set; then :
+  withval=3D$with_libintl_include; if test "$withval" =3D "yes" -o "$withv=
al" =3D "no"; then
+  as_fn_error "No argument for --with-libintl-include" "$LINENO" 5
+elif test "X$with_libintl" =3D "X"; then
+  with_libintl=3Dyes
+fi
+fi
+
+
+# Check whether --with-libintl-config was given.
+if test "${with_libintl_config+set}" =3D set; then :
+  withval=3D$with_libintl_config;
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for libintl" >&5
+$as_echo_n "checking for libintl... " >&6; }
+
+case "$with_libintl" in
+yes|"") d=3D'' ;;
+no)	d=3D ;;
+*)	d=3D"$with_libintl" ;;
+esac
+
+header_dirs=3D
+lib_dirs=3D
+for i in $d; do
+	if test "$with_libintl_include" =3D ""; then
+		if test -d "$i/include/libintl"; then
+			header_dirs=3D"$header_dirs $i/include/libintl"
+		fi
+		if test -d "$i/include"; then
+			header_dirs=3D"$header_dirs $i/include"
+		fi
+	fi
+	if test "$with_libintl_lib" =3D ""; then
+		if test -d "$i/lib$abilibdirext"; then
+			lib_dirs=3D"$lib_dirs $i/lib$abilibdirext"
+		fi
+	fi
+done
+
+if test "$with_libintl_include"; then
+	header_dirs=3D"$with_libintl_include $header_dirs"
+fi
+if test "$with_libintl_lib"; then
+	lib_dirs=3D"$with_libintl_lib $lib_dirs"
+fi
+
+if test "$with_libintl_config" =3D ""; then
+	with_libintl_config=3D''
+fi
+
+libintl_cflags=3D
+libintl_libs=3D
+
+case "$with_libintl_config" in
+yes|no|""|"")
+	if test -f $with_libintl/bin/ ; then
+		with_libintl_config=3D$with_libintl/bin/
+	fi
+	;;
+esac
+
+case "$with_libintl_config" in
+yes|no|"")
+	;;
+*)
+	libintl_cflags=3D"`$with_libintl_config --cflags 2>&1`"
+	libintl_libs=3D"`$with_libintl_config --libs 2>&1`"
+	;;
+esac
+
+found=3Dno
+if test "$with_libintl" !=3D no; then
+	save_CFLAGS=3D"$CFLAGS"
+	save_LIBS=3D"$LIBS"
+	if test "$libintl_cflags" -a "$libintl_libs"; then
+		CFLAGS=3D"$libintl_cflags $save_CFLAGS"
+		LIBS=3D"$libintl_libs $save_LIBS"
+
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <libintl.h>
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+
+			INCLUDE_libintl=3D"$libintl_cflags"
+			LIB_libintl=3D"$libintl_libs"
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: from $with_libintl_con=
fig" >&5
+$as_echo "from $with_libintl_config" >&6; }
+			found=3Dyes
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	fi
+	if test "$found" =3D no; then
+		ires=3D lres=3D
+		for i in $header_dirs; do
+			CFLAGS=3D"-I$i $save_CFLAGS"
+
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <libintl.h>
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ires=3D$i;break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+		done
+		for i in $lib_dirs; do
+			LIBS=3D"-L$i -lintl  $save_LIBS"
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <libintl.h>
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  lres=3D$i;break
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+		done
+		if test "$ires" -a "$lres" -a "$with_libintl" !=3D "no"; then
+			INCLUDE_libintl=3D"-I$ires"
+			LIB_libintl=3D"-L$lres -lintl "
+			found=3Dyes
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: headers $ires, librari=
es $lres" >&5
+$as_echo "headers $ires, libraries $lres" >&6; }
+		fi
+	fi
+	CFLAGS=3D"$save_CFLAGS"
+	LIBS=3D"$save_LIBS"
+fi
+
+if test "$found" =3D yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define LIBINTL 1
+_ACEOF
+
+	with_libintl=3Dyes
+else
+	with_libintl=3Dno
+	INCLUDE_libintl=3D
+	LIB_libintl=3D
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+
+
=20
=20
 # Check whether --with-hdbdir was given.
-if test "${with_hdbdir+set}" =3D set; then
+if test "${with_hdbdir+set}" =3D set; then :
   withval=3D$with_hdbdir;
 else
   with_hdbdir=3D/var/heimdal
@@ -20628,27 +13819,27 @@
=20
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define KRB5 1
-_ACEOF
+$as_echo "#define SUPPORT_INETD 1" >>confdefs.h
+
+
+
+$as_echo "#define KRB5 1" >>confdefs.h
=20
=20
 crypto_lib=3Dunknown
=20
=20
 # Check whether --with-openssl was given.
-if test "${with_openssl+set}" =3D set; then
+if test "${with_openssl+set}" =3D set; then :
   withval=3D$with_openssl;
 fi
=20
=20
=20
 # Check whether --with-openssl-lib was given.
-if test "${with_openssl_lib+set}" =3D set; then
+if test "${with_openssl_lib+set}" =3D set; then :
   withval=3D$with_openssl_lib; if test "$withval" =3D "yes" -o "$withval" =
=3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-openssl-lib" >&5
-echo "$as_me: error: No argument for --with-openssl-lib" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-openssl-lib" "$LINENO" 5
 elif test "X$with_openssl" =3D "X"; then
   with_openssl=3Dyes
 fi
@@ -20657,11 +13848,9 @@
=20
=20
 # Check whether --with-openssl-include was given.
-if test "${with_openssl_include+set}" =3D set; then
+if test "${with_openssl_include+set}" =3D set; then :
   withval=3D$with_openssl_include; if test "$withval" =3D "yes" -o "$withv=
al" =3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-openssl-include"=
 >&5
-echo "$as_me: error: No argument for --with-openssl-include" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-openssl-include" "$LINENO" 5
 elif test "X$with_openssl" =3D "X"; then
   with_openssl=3Dyes
 fi
@@ -20684,8 +13873,8 @@
=20
 DIR_hcrypto=3D
=20
-{ echo "$as_me:$LINENO: checking for crypto library" >&5
-echo $ECHO_N "checking for crypto library... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for crypto library" >&5
+$as_echo_n "checking for crypto library... " >&6; }
=20
 openssl=3Dno
=20
@@ -20707,11 +13896,7 @@
 		for j in $cdirs; do
 			for k in $clibs; do
 				LIBS=3D"$j $k $save_LIBS"
-				cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+				cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 		#undef KRB5 /* makes md4.h et al unhappy */
@@ -20726,6 +13911,7 @@
 		#include <openssl/des.h>
 		#include <openssl/rc4.h>
 		#include <openssl/aes.h>
+		#include <openssl/ec.h>
 		#include <openssl/engine.h>
 		#include <openssl/ui.h>
 		#include <openssl/rand.h>
@@ -20749,19 +13935,20 @@
 {
=20
 		void *schedule =3D 0;
-		MD4_CTX md4;
-		MD5_CTX md5;
-		SHA_CTX sha1;
-		SHA256_CTX sha256;
-
-		MD4_Init(&md4);
-		MD5_Init(&md5);
-		SHA1_Init(&sha1);
-		SHA256_Init(&sha256);
+		EVP_MD_CTX mdctx;
+
+		EVP_md4();
+		EVP_md5();
+		EVP_sha1();
+		EVP_sha256();
+
+		EVP_MD_CTX_init(&mdctx);
+		EVP_DigestInit_ex(&mdctx, EVP_sha1(), (ENGINE *)0);
 		EVP_CIPHER_iv_length(((EVP_CIPHER*)0));
+		UI_UTIL_read_pw_string(0,0,0,0);
+		RAND_status();
 		#ifdef HAVE_OPENSSL
-		RAND_status();
-		UI_UTIL_read_pw_string(0,0,0,0);
+		EC_KEY_new();
 		#endif
=20
 		OpenSSL_add_all_algorithms();
@@ -20772,45 +13959,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   openssl=3Dyes ires=3D"$i" lres=3D"$j $k"; break 3
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 			done
 		done
 		CFLAGS=3D"$i $save_CFLAGS"
 		for j in $cdirs; do
 			for k in $clibs; do
 				LIBS=3D"$j $k $save_LIBS"
-				cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+				cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 		#undef KRB5 /* makes md4.h et al unhappy */
@@ -20825,6 +13985,7 @@
 		#include <openssl/des.h>
 		#include <openssl/rc4.h>
 		#include <openssl/aes.h>
+		#include <openssl/ec.h>
 		#include <openssl/engine.h>
 		#include <openssl/ui.h>
 		#include <openssl/rand.h>
@@ -20848,19 +14009,20 @@
 {
=20
 		void *schedule =3D 0;
-		MD4_CTX md4;
-		MD5_CTX md5;
-		SHA_CTX sha1;
-		SHA256_CTX sha256;
-
-		MD4_Init(&md4);
-		MD5_Init(&md5);
-		SHA1_Init(&sha1);
-		SHA256_Init(&sha256);
+		EVP_MD_CTX mdctx;
+
+		EVP_md4();
+		EVP_md5();
+		EVP_sha1();
+		EVP_sha256();
+
+		EVP_MD_CTX_init(&mdctx);
+		EVP_DigestInit_ex(&mdctx, EVP_sha1(), (ENGINE *)0);
 		EVP_CIPHER_iv_length(((EVP_CIPHER*)0));
+		UI_UTIL_read_pw_string(0,0,0,0);
+		RAND_status();
 		#ifdef HAVE_OPENSSL
-		RAND_status();
-		UI_UTIL_read_pw_string(0,0,0,0);
+		EC_KEY_new();
 		#endif
=20
 		OpenSSL_add_all_algorithms();
@@ -20871,34 +14033,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   openssl=3Dno ires=3D"$i" lres=3D"$j $k"; break 3
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 			done
 		done
 	done
@@ -20909,8 +14048,8 @@
 		INCLUDE_hcrypto=3D"$ires"
 		LIB_hcrypto=3D"$lres"
 		crypto_lib=3Dkrb4
-		{ echo "$as_me:$LINENO: result: same as krb4" >&5
-echo "${ECHO_T}same as krb4" >&6; }
+		{ $as_echo "$as_me:${as_lineno-$LINENO}: result: same as krb4" >&5
+$as_echo "same as krb4" >&6; }
 		LIB_hcrypto_a=3D'$(LIB_hcrypto)'
 		LIB_hcrypto_so=3D'$(LIB_hcrypto)'
 		LIB_hcrypto_appl=3D'$(LIB_hcrypto)'
@@ -20936,11 +14075,7 @@
 		LIB_hcrypto_so=3D"$LIB_hcrypto"
 		LIB_hcrypto_appl=3D"$LIB_hcrypto"
 		LIBS=3D"${LIBS} ${LIB_hcrypto}"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 		#undef KRB5 /* makes md4.h et al unhappy */
@@ -20955,6 +14090,7 @@
 		#include <openssl/des.h>
 		#include <openssl/rc4.h>
 		#include <openssl/aes.h>
+		#include <openssl/ec.h>
 		#include <openssl/engine.h>
 		#include <openssl/ui.h>
 		#include <openssl/rand.h>
@@ -20978,19 +14114,20 @@
 {
=20
 		void *schedule =3D 0;
-		MD4_CTX md4;
-		MD5_CTX md5;
-		SHA_CTX sha1;
-		SHA256_CTX sha256;
-
-		MD4_Init(&md4);
-		MD5_Init(&md5);
-		SHA1_Init(&sha1);
-		SHA256_Init(&sha256);
+		EVP_MD_CTX mdctx;
+
+		EVP_md4();
+		EVP_md5();
+		EVP_sha1();
+		EVP_sha256();
+
+		EVP_MD_CTX_init(&mdctx);
+		EVP_DigestInit_ex(&mdctx, EVP_sha1(), (ENGINE *)0);
 		EVP_CIPHER_iv_length(((EVP_CIPHER*)0));
+		UI_UTIL_read_pw_string(0,0,0,0);
+		RAND_status();
 		#ifdef HAVE_OPENSSL
-		RAND_status();
-		UI_UTIL_read_pw_string(0,0,0,0);
+		EC_KEY_new();
 		#endif
=20
 		OpenSSL_add_all_algorithms();
@@ -21001,38 +14138,15 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
=20
 			crypto_lib=3Dlibcrypto openssl=3Dyes
-			{ echo "$as_me:$LINENO: result: libcrypto" >&5
-echo "${ECHO_T}libcrypto" >&6; }
-
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: libcrypto" >&5
+$as_echo "libcrypto" >&6; }
+
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 		if test "$crypto_lib" =3D libcrypto ; then
 			break;
 		fi
@@ -21049,26 +14163,20 @@
   LIB_hcrypto_so=3D'$(top_builddir)/lib/hcrypto/.libs/libhcrypto.so'
   LIB_hcrypto_appl=3D"-lhcrypto"
=20
-  { echo "$as_me:$LINENO: result: included libhcrypto" >&5
-echo "${ECHO_T}included libhcrypto" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: included libhcrypto" >&5
+$as_echo "included libhcrypto" >&6; }
=20
 fi
=20
 if test "$with_krb4" !=3D no -a "$crypto_lib" !=3D krb4; then
-	{ { echo "$as_me:$LINENO: error: the crypto library used by krb4 lacks fe=
atures
+	as_fn_error "the crypto library used by krb4 lacks features
 required by Kerberos 5; to continue, you need to install a newer
-Kerberos 4 or configure --without-krb4" >&5
-echo "$as_me: error: the crypto library used by krb4 lacks features
-required by Kerberos 5; to continue, you need to install a newer
-Kerberos 4 or configure --without-krb4" >&2;}
-   { (exit 1); exit 1; }; }
+Kerberos 4 or configure --without-krb4" "$LINENO" 5
 fi
=20
 if test "$openssl" =3D "yes"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_OPENSSL 1
-_ACEOF
+$as_echo "#define HAVE_OPENSSL 1" >>confdefs.h
=20
 fi
  if test "$openssl" =3D yes; then
@@ -21088,11 +14196,11 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking if compiling threadsafe libraries" >&5
-echo $ECHO_N "checking if compiling threadsafe libraries... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiling threadsafe =
libraries" >&5
+$as_echo_n "checking if compiling threadsafe libraries... " >&6; }
=20
 # Check whether --enable-pthread-support was given.
-if test "${enable_pthread_support+set}" =3D set; then
+if test "${enable_pthread_support+set}" =3D set; then :
   enableval=3D$enable_pthread_support;
 else
   enable_pthread_support=3Dmaybe
@@ -21103,35 +14211,51 @@
 *-*-solaris2*)
 	native_pthread_support=3Dyes
 	if test "$GCC" =3D yes; then
-		PTHREADS_CFLAGS=3D-pthreads
-		PTHREADS_LIBS=3D-pthreads
+		PTHREAD_CFLAGS=3D-pthreads
+		PTHREAD_LIBADD=3D-pthreads
 	else
-		PTHREADS_CFLAGS=3D-mt
-		PTHREADS_LIBS=3D-mt
-	fi
-	;;
-*-*-netbsd*)
+		PTHREAD_CFLAGS=3D-mt
+		PTHREAD_LDADD=3D-mt
+		PTHREAD_LIBADD=3D-mt
+	fi
+	;;
+*-*-netbsd[12]*)
 	native_pthread_support=3D"if running netbsd 1.6T or newer"
-		PTHREADS_LIBS=3D""
-	;;
-*-*-freebsd5*)
+		PTHREAD_LIBADD=3D"-lpthread"
+	;;
+*-*-netbsd[3456789]*)
+	native_pthread_support=3D"netbsd 3 uses explict pthread"
+		PTHREAD_LIBADD=3D"-lpthread"
+	;;
+*-*-freebsd[56789]*)
 	native_pthread_support=3Dyes
+	PTHREAD_LIBADD=3D"-pthread"
+	;;
+*-*-openbsd*)
+	native_pthread_support=3Dyes
+	PTHREAD_CFLAGS=3D-pthread
+	PTHREAD_LIBADD=3D-pthread
 	;;
 *-*-linux* | *-*-linux-gnu)
 	case `uname -r` in
-	2.*)
+	2.*|3.*)
 		native_pthread_support=3Dyes
-		PTHREADS_CFLAGS=3D-pthread
-		PTHREADS_LIBS=3D-pthread
+		PTHREAD_CFLAGS=3D-pthread
+		PTHREAD_LIBADD=3D-pthread
 		;;
 	esac
 	;;
+*-*-kfreebsd*-gnu*)
+	native_pthread_support=3Dyes
+	PTHREAD_CFLAGS=3D-pthread
+	PTHREAD_LIBADD=3D-pthread
+	;;
 *-*-aix*)
 	        	native_pthread_support=3Dno
 	;;
 mips-sgi-irix6.[5-9])  # maybe works for earlier versions too
 	native_pthread_support=3Dyes
-	PTHREADS_LIBS=3D"-lpthread"
+	PTHREAD_LIBADD=3D"-lpthread"
 	;;
 *-*-darwin*)
 	native_pthread_support=3Dyes
@@ -21147,33 +14271,30 @@
=20
 if test "$enable_pthread_support" !=3D no; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define ENABLE_PTHREAD_SUPPORT 1
-_ACEOF
-
-            LIBS=3D"$PTHREADS_LIBS $LIBS"
-else
-  PTHREADS_CFLAGS=3D""
-  PTHREADS_LIBS=3D""
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: result: $enable_pthread_support" >&5
-echo "${ECHO_T}$enable_pthread_support" >&6; }
+$as_echo "#define ENABLE_PTHREAD_SUPPORT 1" >>confdefs.h
+
+            LIBS=3D"$PTHREAD_LIBADD $LIBS"
+else
+  PTHREAD_CFLAGS=3D""
+  PTHREAD_LIBADD=3D""
+fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_pthread_support" =
>&5
+$as_echo "$enable_pthread_support" >&6; }
=20
=20
 # Check whether --enable-dce was given.
-if test "${enable_dce+set}" =3D set; then
+if test "${enable_dce+set}" =3D set; then :
   enableval=3D$enable_dce;
 fi
=20
 if test "$enable_dce" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define DCE 1
-_ACEOF
+$as_echo "#define DCE 1" >>confdefs.h
=20
 fi
  if test "$enable_dce" =3D yes; then
@@ -21200,28 +14321,39 @@
=20
=20
 # Check whether --enable-afs-support was given.
-if test "${enable_afs_support+set}" =3D set; then
+if test "${enable_afs_support+set}" =3D set; then :
   enableval=3D$enable_afs_support;
 fi
=20
 if test "$enable_afs_support" =3D no; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NO_AFS 1
-_ACEOF
-
-fi
-
-
-# Check whether --enable-berkeley-db was given.
-if test "${enable_berkeley_db+set}" =3D set; then
-  enableval=3D$enable_berkeley_db;
-
+$as_echo "#define NO_AFS 1" >>confdefs.h
+
+	NO_AFS=3D"1"
+fi
+
+
+
+# Check whether --with-berkeley-db was given.
+if test "${with_berkeley_db+set}" =3D set; then :
+  withval=3D$with_berkeley_db;
+else
+  with_berkeley_db=3Dcheck
+fi
+
+
+dbheader=3D""
+
+# Check whether --with-berkeley-db-include was given.
+if test "${with_berkeley_db_include+set}" =3D set; then :
+  withval=3D$with_berkeley_db_include; dbheader=3D$withval
+else
+  with_berkeley_db_include=3Dcheck
 fi
=20
=20
 # Check whether --enable-ndbm-db was given.
-if test "${enable_ndbm_db+set}" =3D set; then
+if test "${enable_ndbm_db+set}" =3D set; then :
   enableval=3D$enable_ndbm_db;
=20
 fi
@@ -21230,192 +14362,87 @@
 have_ndbm=3Dno
 db_type=3Dunknown
=20
-if test "$enable_berkeley_db" !=3D no; then
-
-
-
-
-
-for ac_header in 				\
-	db4/db.h				\
-	db3/db.h				\
-	db.h					\
-	db_185.h				\
-
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for db_create" >&5
-echo $ECHO_N "checking for db_create... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_db_create+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if test "x$with_berkeley_db" !=3D xno; then :
+  if test "x$with_berkeley_db_include" !=3D xcheck; then :
+  for ac_header in "$dbheader/db.h"
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+ DBHEADER=3D$dbheader
+
+
+$as_echo "#define HAVE_DBHEADER 1" >>confdefs.h
+
+
+else
+  if test "x$with_berkeley_db_include" !=3D xcheck; then
+		     { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >=
&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "--with-berkeley-db-include was given but include test failed
+See \`config.log' for more details." "$LINENO" 5; }
+		    fi
+
+fi
+
+done
+
+else
+  for ac_header in 					\
+	           db5/db.h				\
+	           db4/db.h				\
+	           db3/db.h				\
+	           db.h					\
+
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for db_create" >&5
+$as_echo_n "checking for db_create... " >&6; }
+if test "${ac_cv_funclib_db_create+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_db_create\" !=3D yes" ; then
 	ac_save_LIBS=3D"$LIBS"
-	for ac_lib in "" db4 db3 db; do
-		case "$ac_lib" in
-		"") ;;
-		yes) ac_lib=3D"" ;;
-		no) continue ;;
-		-l*) ;;
-		*) ac_lib=3D"-l$ac_lib" ;;
-		esac
-		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+	for ac_lib in "" $dbheader db5 db4 db3 db; do
+		case "$ac_lib" in
+		"") ;;
+		yes) ac_lib=3D"" ;;
+		no) continue ;;
+		-l*) ;;
+		*) ac_lib=3D"-l$ac_lib" ;;
+		esac
+		LIBS=3D" $ac_lib  $ac_save_LIBS"
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
   #include <stdio.h>
-  #ifdef HAVE_DB4_DB_H
+  #ifdef HAVE_DBHEADER
+  #include <$dbheader/db.h>
+  #elif HAVE_DB5_DB_H
+  #include <db5/db.h>
+  #elif HAVE_DB4_DB_H
   #include <db4/db.h>
   #elif defined(HAVE_DB3_DB_H)
   #include <db3/db.h>
@@ -21431,34 +14458,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_db_create=3D$ac_lib; els=
e ac_cv_funclib_db_create=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_db_create=3D\${ac_cv_funclib_db_create-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -21470,95 +14474,12 @@
 eval "ac_res=3D\$ac_cv_funclib_db_create"
=20
 if false; then
-
-for ac_func in db_create
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in db_create
+do :
+  ac_fn_c_check_func "$LINENO" "db_create" "ac_cv_func_db_create"
+if test "x$ac_cv_func_db_create" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DB_CREATE 1
 _ACEOF
=20
 fi
@@ -21578,14 +14499,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_db_create=3Dno"
 	eval "LIB_db_create=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_db_create=3Dyes"
@@ -21598,8 +14519,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -21613,20 +14534,18 @@
       DBLIB=3D""
     fi
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_DB3 1
-_ACEOF
-
-  else
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for dbopen" >&5
-echo $ECHO_N "checking for dbopen... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_dbopen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define HAVE_DB3 1" >>confdefs.h
+
+  fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dbopen" >&5
+$as_echo_n "checking for dbopen... " >&6; }
+if test "${ac_cv_funclib_dbopen+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_dbopen\" !=3D yes" ; then
@@ -21640,23 +14559,17 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-    #include <stdio.h>
-    #if defined(HAVE_DB2_DB_H)
-    #include <db2/db.h>
-    #elif defined(HAVE_DB_185_H)
-    #include <db_185.h>
-    #elif defined(HAVE_DB_H)
-    #include <db.h>
-    #else
-    #error no db.h
-    #endif
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+  #include <stdio.h>
+  #if defined(HAVE_DB2_DB_H)
+  #include <db2/db.h>
+  #elif defined(HAVE_DB_H)
+  #include <db.h>
+  #else
+  #error no db.h
+  #endif
=20
 int
 main ()
@@ -21666,34 +14579,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_dbopen=3D$ac_lib; else a=
c_cv_funclib_dbopen=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_dbopen=3D\${ac_cv_funclib_dbopen-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -21705,95 +14595,12 @@
 eval "ac_res=3D\$ac_cv_funclib_dbopen"
=20
 if false; then
-
-for ac_func in dbopen
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in dbopen
+do :
+  ac_fn_c_check_func "$LINENO" "dbopen" "ac_cv_func_dbopen"
+if test "x$ac_cv_func_dbopen" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DBOPEN 1
 _ACEOF
=20
 fi
@@ -21813,14 +14620,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_dbopen=3Dno"
 	eval "LIB_dbopen=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_dbopen=3Dyes"
@@ -21833,36 +14640,33 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-    if test "$ac_cv_func_dbopen" =3D "yes"; then
-      db_type=3Ddb1
-      if test "$ac_cv_funclib_dbopen" !=3D "yes"; then
-        DBLIB=3D"$ac_cv_funclib_dbopen"
-      else
-        DBLIB=3D""
-      fi
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_DB1 1
-_ACEOF
-
-    fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+  if test "$ac_cv_func_dbopen" =3D "yes"; then
+    db_type=3Ddb1
+    if test "$ac_cv_funclib_dbopen" !=3D "yes"; then
+      DBLIB=3D"$ac_cv_funclib_dbopen"
+    else
+      DBLIB=3D""
+    fi
+
+$as_echo "#define HAVE_DB1 1" >>confdefs.h
+
   fi
=20
=20
   if test "$ac_cv_func_dbm_firstkey" !=3D yes; then
=20
=20
-{ echo "$as_me:$LINENO: checking for dbm_firstkey" >&5
-echo $ECHO_N "checking for dbm_firstkey... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_dbm_firstkey+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dbm_firstkey" >&5
+$as_echo_n "checking for dbm_firstkey... " >&6; }
+if test "${ac_cv_funclib_dbm_firstkey+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_dbm_firstkey\" !=3D yes" ; then
@@ -21876,11 +14680,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
     #include <stdio.h>
@@ -21896,34 +14696,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_dbm_firstkey=3D$ac_lib; =
else ac_cv_funclib_dbm_firstkey=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_dbm_firstkey=3D\${ac_cv_funclib_dbm_firstkey-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -21935,95 +14712,12 @@
 eval "ac_res=3D\$ac_cv_funclib_dbm_firstkey"
=20
 if false; then
-
-for ac_func in dbm_firstkey
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in dbm_firstkey
+do :
+  ac_fn_c_check_func "$LINENO" "dbm_firstkey" "ac_cv_func_dbm_firstkey"
+if test "x$ac_cv_func_dbm_firstkey" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DBM_FIRSTKEY 1
 _ACEOF
=20
 fi
@@ -22043,14 +14737,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_dbm_firstkey=3Dno"
 	eval "LIB_dbm_firstkey=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_dbm_firstkey=3Dyes"
@@ -22063,8 +14757,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -22077,14 +14771,10 @@
         LIB_NDBM=3D""
       fi
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_DB_NDBM 1
-_ACEOF
-
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_NEW_DB 1
-_ACEOF
+$as_echo "#define HAVE_DB_NDBM 1" >>confdefs.h
+
+
+$as_echo "#define HAVE_NEW_DB 1" >>confdefs.h
=20
     else
       $as_unset ac_cv_func_dbm_firstkey
@@ -22092,169 +14782,38 @@
     fi
   fi
=20
-fi # berkeley db
+
+fi # fi berkeley db
=20
 if test "$enable_ndbm_db" !=3D "no"; then
=20
   if test "$db_type" =3D "unknown" -o "$ac_cv_func_dbm_firstkey" =3D ""; t=
hen
=20
-
-
-for ac_header in 				\
+    for ac_header in 				\
   	dbm.h					\
   	ndbm.h					\
=20
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for dbm_firstkey" >&5
-echo $ECHO_N "checking for dbm_firstkey... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_dbm_firstkey+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dbm_firstkey" >&5
+$as_echo_n "checking for dbm_firstkey... " >&6; }
+if test "${ac_cv_funclib_dbm_firstkey+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_dbm_firstkey\" !=3D yes" ; then
@@ -22268,11 +14827,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
     #include <stdio.h>
@@ -22291,34 +14846,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_dbm_firstkey=3D$ac_lib; =
else ac_cv_funclib_dbm_firstkey=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_dbm_firstkey=3D\${ac_cv_funclib_dbm_firstkey-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -22330,95 +14862,12 @@
 eval "ac_res=3D\$ac_cv_funclib_dbm_firstkey"
=20
 if false; then
-
-for ac_func in dbm_firstkey
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in dbm_firstkey
+do :
+  ac_fn_c_check_func "$LINENO" "dbm_firstkey" "ac_cv_func_dbm_firstkey"
+if test "x$ac_cv_func_dbm_firstkey" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DBM_FIRSTKEY 1
 _ACEOF
=20
 fi
@@ -22438,14 +14887,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_dbm_firstkey=3Dno"
 	eval "LIB_dbm_firstkey=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_dbm_firstkey=3Dyes"
@@ -22458,8 +14907,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -22472,9 +14921,7 @@
         LIB_NDBM=3D""
       fi
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_NDBM 1
-_ACEOF
+$as_echo "#define HAVE_NDBM 1" >>confdefs.h
       have_ndbm=3Dyes
       if test "$db_type" =3D "unknown"; then
         db_type=3Dndbm
@@ -22485,161 +14932,30 @@
       $as_unset ac_cv_func_dbm_firstkey
       $as_unset ac_cv_funclib_dbm_firstkey
=20
-
-for ac_header in 				\
+      for ac_header in 				\
   	  gdbm/ndbm.h				\
=20
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for dbm_firstkey" >&5
-echo $ECHO_N "checking for dbm_firstkey... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_dbm_firstkey+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dbm_firstkey" >&5
+$as_echo_n "checking for dbm_firstkey... " >&6; }
+if test "${ac_cv_funclib_dbm_firstkey+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_dbm_firstkey\" !=3D yes" ; then
@@ -22653,11 +14969,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
       #include <stdio.h>
@@ -22672,34 +14984,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_dbm_firstkey=3D$ac_lib; =
else ac_cv_funclib_dbm_firstkey=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_dbm_firstkey=3D\${ac_cv_funclib_dbm_firstkey-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -22711,95 +15000,12 @@
 eval "ac_res=3D\$ac_cv_funclib_dbm_firstkey"
=20
 if false; then
-
-for ac_func in dbm_firstkey
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in dbm_firstkey
+do :
+  ac_fn_c_check_func "$LINENO" "dbm_firstkey" "ac_cv_func_dbm_firstkey"
+if test "x$ac_cv_func_dbm_firstkey" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DBM_FIRSTKEY 1
 _ACEOF
=20
 fi
@@ -22819,14 +15025,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_dbm_firstkey=3Dno"
 	eval "LIB_dbm_firstkey=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_dbm_firstkey=3Dyes"
@@ -22839,8 +15045,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -22853,9 +15059,7 @@
   	LIB_NDBM=3D""
         fi
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_NDBM 1
-_ACEOF
+$as_echo "#define HAVE_NDBM 1" >>confdefs.h
         have_ndbm=3Dyes
         if test "$db_type" =3D "unknown"; then
   	db_type=3Dndbm
@@ -22867,20 +15071,13 @@
 fi # unknown
=20
 if test "$have_ndbm" =3D "yes"; then
-  { echo "$as_me:$LINENO: checking if ndbm is implemented with db" >&5
-echo $ECHO_N "checking if ndbm is implemented with db... $ECHO_C" >&6; }
-  if test "$cross_compiling" =3D yes; then
-  { { echo "$as_me:$LINENO: error: cannot run test program while cross com=
piling
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot run test program while cross compiling
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if ndbm is implemented=
 with db" >&5
+$as_echo_n "checking if ndbm is implemented with db... " >&6; }
+  if test "$cross_compiling" =3D yes; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no-cross" >&5
+$as_echo "no-cross" >&6; }
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <unistd.h>
@@ -22903,51 +15100,25 @@
   return 0;
 }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
=20
     if test -f conftest.db; then
-      { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_NEW_DB 1
-_ACEOF
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+
+$as_echo "#define HAVE_NEW_DB 1" >>confdefs.h
=20
     else
-      { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-    fi
-else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
+      { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+    fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
=20
 fi
=20
@@ -22972,6 +15143,13 @@
   HAVE_NDBM_TRUE=3D'#'
   HAVE_NDBM_FALSE=3D
 fi
+ if test "$dbheader" !=3D ""; then
+  HAVE_DBHEADER_TRUE=3D
+  HAVE_DBHEADER_FALSE=3D'#'
+else
+  HAVE_DBHEADER_TRUE=3D'#'
+  HAVE_DBHEADER_FALSE=3D
+fi
=20
 ## it's probably not correct to include LDFLAGS here, but we might
 ## need it, for now just add any possible -L
@@ -22986,19 +15164,14 @@
=20
=20
=20
-
-{ echo "$as_me:$LINENO: checking for inline" >&5
-echo $ECHO_N "checking for inline... $ECHO_C" >&6; }
-if test "${ac_cv_c_inline+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5
+$as_echo_n "checking for inline... " >&6; }
+if test "${ac_cv_c_inline+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_cv_c_inline=3Dno
 for ac_kw in inline __inline__ __inline; do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifndef __cplusplus
 typedef int foo_t;
@@ -23007,39 +15180,16 @@
 #endif
=20
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_c_inline=3D$ac_kw
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
   test "$ac_cv_c_inline" !=3D no && break
 done
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_c_inline" >&5
-echo "${ECHO_T}$ac_cv_c_inline" >&6; }
-
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5
+$as_echo "$ac_cv_c_inline" >&6; }
=20
 case $ac_cv_c_inline in
   inline | yes) ;;
@@ -23056,16 +15206,12 @@
     ;;
 esac
=20
-{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5
-echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; }
-if test "${ac_cv_c_const+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming=
 const" >&5
+$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
+if test "${ac_cv_c_const+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -23125,98 +15271,24 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_c_const=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_c_const=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5
-echo "${ECHO_T}$ac_cv_c_const" >&6; }
+  ac_cv_c_const=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5
+$as_echo "$ac_cv_c_const" >&6; }
 if test $ac_cv_c_const =3D no; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define const
-_ACEOF
-
-fi
-
-{ echo "$as_me:$LINENO: checking for size_t" >&5
-echo $ECHO_N "checking for size_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_size_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef size_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_size_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_size_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5
-echo "${ECHO_T}$ac_cv_type_size_t" >&6; }
-if test $ac_cv_type_size_t =3D yes; then
-  :
+$as_echo "#define const /**/" >>confdefs.h
+
+fi
+
+ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_de=
fault"
+if test "x$ac_cv_type_size_t" =3D x""yes; then :
+
 else
=20
 cat >>confdefs.h <<_ACEOF
@@ -23225,61 +15297,9 @@
=20
 fi
=20
-{ echo "$as_me:$LINENO: checking for pid_t" >&5
-echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_pid_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef pid_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_pid_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_pid_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5
-echo "${ECHO_T}$ac_cv_type_pid_t" >&6; }
-if test $ac_cv_type_pid_t =3D yes; then
-  :
+ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_defa=
ult"
+if test "x$ac_cv_type_pid_t" =3D x""yes; then :
+
 else
=20
 cat >>confdefs.h <<_ACEOF
@@ -23288,22 +15308,18 @@
=20
 fi
=20
-{ echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5
-echo $ECHO_N "checking for uid_t in sys/types.h... $ECHO_C" >&6; }
-if test "${ac_cv_type_uid_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h=
" >&5
+$as_echo_n "checking for uid_t in sys/types.h... " >&6; }
+if test "${ac_cv_type_uid_t+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "uid_t" >/dev/null 2>&1; then
+  $EGREP "uid_t" >/dev/null 2>&1; then :
   ac_cv_type_uid_t=3Dyes
 else
   ac_cv_type_uid_t=3Dno
@@ -23311,32 +15327,24 @@
 rm -f conftest*
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5
-echo "${ECHO_T}$ac_cv_type_uid_t" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5
+$as_echo "$ac_cv_type_uid_t" >&6; }
 if test $ac_cv_type_uid_t =3D no; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define uid_t int
-_ACEOF
-
-
-cat >>confdefs.h <<\_ACEOF
-#define gid_t int
-_ACEOF
-
-fi
-
-
-{ echo "$as_me:$LINENO: checking return type of signal handlers" >&5
-echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6; }
-if test "${ac_cv_type_signal+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define uid_t int" >>confdefs.h
+
+
+$as_echo "#define gid_t int" >>confdefs.h
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal ha=
ndlers" >&5
+$as_echo_n "checking return type of signal handlers... " >&6; }
+if test "${ac_cv_type_signal+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #include <signal.h>
@@ -23349,35 +15357,15 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_signal=3Dint
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_signal=3Dvoid
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5
-echo "${ECHO_T}$ac_cv_type_signal" >&6; }
+  ac_cv_type_signal=3Dvoid
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5
+$as_echo "$ac_cv_type_signal" >&6; }
=20
 cat >>confdefs.h <<_ACEOF
 #define RETSIGTYPE $ac_cv_type_signal
@@ -23386,25 +15374,18 @@
=20
 if test "$ac_cv_type_signal" =3D "void" ; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define VOID_RETSIGTYPE 1
-_ACEOF
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be=
 included" >&5
-echo $ECHO_N "checking whether time.h and sys/time.h may both be included.=
.. $ECHO_C" >&6; }
-if test "${ac_cv_header_time+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define VOID_RETSIGTYPE 1" >>confdefs.h
+
+fi
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/t=
ime.h may both be included" >&5
+$as_echo_n "checking whether time.h and sys/time.h may both be included...=
 " >&6; }
+if test "${ac_cv_header_time+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #include <sys/time.h>
@@ -23419,183 +15400,28 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_header_time=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_header_time=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5
-echo "${ECHO_T}$ac_cv_header_time" >&6; }
+  ac_cv_header_time=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5
+$as_echo "$ac_cv_header_time" >&6; }
 if test $ac_cv_header_time =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define TIME_WITH_SYS_TIME 1
-_ACEOF
-
-fi
-
+$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h
+
+fi
=20
=20
 for ac_header in standards.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+do :
+  ac_fn_c_check_header_mongrel "$LINENO" "standards.h" "ac_cv_header_stand=
ards_h" "$ac_includes_default"
+if test "x$ac_cv_header_standards_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_STANDARDS_H 1
 _ACEOF
=20
 fi
@@ -23606,16 +15432,12 @@
=20
 cv=3D`echo "$i" | sed 'y%./+-%__p_%'`
=20
-{ echo "$as_me:$LINENO: checking for $i" >&5
-echo $ECHO_N "checking for $i... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_header_$cv; eval "test \"\${$as_var+set}\" =3D set"; }=
; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $i" >&5
+$as_echo_n "checking for $i... " >&6; }
+if { as_var=3Dac_cv_header_$cv; eval "test \"\${$as_var+set}\" =3D set"; }=
; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_STANDARDS_H
@@ -23624,35 +15446,16 @@
 #include <$i>
=20
 _ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+if ac_fn_c_try_cpp "$LINENO"; then :
   eval "ac_cv_header_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
   eval "ac_cv_header_$cv=3Dno"
 fi
-
 rm -f conftest.err conftest.$ac_ext
 fi
-ac_res=3D`eval echo '${'ac_cv_header_$cv'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
+eval ac_res=3D\$ac_cv_header_$cv
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
 ac_res=3D`eval echo \\$ac_cv_header_$cv`
 if test "$ac_res" =3D yes; then
 	ac_tr_hdr=3DHAVE_`echo $i | sed 'y%abcdefghijklmnopqrstuvwxyz./-%ABCDEFGH=
IJKLMNOPQRSTUVWXYZ___%'`
@@ -23663,255 +15466,41 @@
 fi
 done
 if false;then
-
-
-for ac_header in netinet/ip.h netinet/tcp.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-fi
-
-
+	for ac_header in netinet/ip.h netinet/tcp.h
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+fi
=20
=20
 for ac_func in getlogin setlogin
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+do :
+  as_ac_var=3D`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+eval as_val=3D\$$as_ac_var
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
 _ACEOF
=20
 fi
 done
=20
 if test "$ac_cv_func_getlogin" =3D yes; then
-{ echo "$as_me:$LINENO: checking if getlogin is posix" >&5
-echo $ECHO_N "checking if getlogin is posix... $ECHO_C" >&6; }
-if test "${ac_cv_func_getlogin_posix+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getlogin is posix" >&5
+$as_echo_n "checking if getlogin is posix... " >&6; }
+if test "${ac_cv_func_getlogin_posix+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if test "$ac_cv_func_getlogin" =3D yes -a "$ac_cv_func_setlogin" =3D yes; =
then
@@ -23921,270 +15510,60 @@
 fi
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getlogin_posix" >&5
-echo "${ECHO_T}$ac_cv_func_getlogin_posix" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getlogin_posi=
x" >&5
+$as_echo "$ac_cv_func_getlogin_posix" >&6; }
 if test "$ac_cv_func_getlogin_posix" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define POSIX_GETLOGIN 1
-_ACEOF
-
-fi
-fi
-
-
-
-for ac_header in stdlib.h unistd.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
+$as_echo "#define POSIX_GETLOGIN 1" >>confdefs.h
+
+fi
+fi
+
+
+
+
+  for ac_header in $ac_header_list
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default
+"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+
=20
=20
 for ac_func in getpagesize
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-{ echo "$as_me:$LINENO: checking for working mmap" >&5
-echo $ECHO_N "checking for working mmap... $ECHO_C" >&6; }
-if test "${ac_cv_func_mmap_fixed_mapped+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test "$cross_compiling" =3D yes; then
+do :
+  ac_fn_c_check_func "$LINENO" "getpagesize" "ac_cv_func_getpagesize"
+if test "x$ac_cv_func_getpagesize" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETPAGESIZE 1
+_ACEOF
+
+fi
+done
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working mmap" >&5
+$as_echo_n "checking for working mmap... " >&6; }
+if test "${ac_cv_func_mmap_fixed_mapped+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "$cross_compiling" =3D yes; then :
   ac_cv_func_mmap_fixed_mapped=3Dno
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $ac_includes_default
 /* malloc might have been renamed as rpl_malloc. */
@@ -24221,11 +15600,6 @@
=20
 /* This mess was copied from the GNU getpagesize.h.  */
 #ifndef HAVE_GETPAGESIZE
-/* Assume that all systems that can run configure have sys/param.h.  */
-# ifndef HAVE_SYS_PARAM_H
-#  define HAVE_SYS_PARAM_H 1
-# endif
-
 # ifdef _SC_PAGESIZE
 #  define getpagesize() sysconf(_SC_PAGESIZE)
 # else /* no _SC_PAGESIZE */
@@ -24261,7 +15635,7 @@
 {
   char *data, *data2, *data3;
   int i, pagesize;
-  int fd;
+  int fd, fd2;
=20
   pagesize =3D getpagesize ();
=20
@@ -24274,27 +15648,41 @@
   umask (0);
   fd =3D creat ("conftest.mmap", 0600);
   if (fd < 0)
-    return 1;
+    return 2;
   if (write (fd, data, pagesize) !=3D pagesize)
-    return 1;
+    return 3;
   close (fd);
=20
+  /* Next, check that the tail of a page is zero-filled.  File must have
+     non-zero length, otherwise we risk SIGBUS for entire page.  */
+  fd2 =3D open ("conftest.txt", O_RDWR | O_CREAT | O_TRUNC, 0600);
+  if (fd2 < 0)
+    return 4;
+  data2 =3D "";
+  if (write (fd2, data2, 1) !=3D 1)
+    return 5;
+  data2 =3D mmap (0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd2, 0L=
);
+  if (data2 =3D=3D MAP_FAILED)
+    return 6;
+  for (i =3D 0; i < pagesize; ++i)
+    if (*(data2 + i))
+      return 7;
+  close (fd2);
+  if (munmap (data2, pagesize))
+    return 8;
+
   /* Next, try to mmap the file at a fixed address which already has
      something else allocated at it.  If we can, also make sure that
      we see the same garbage.  */
   fd =3D open ("conftest.mmap", O_RDWR);
   if (fd < 0)
-    return 1;
-  data2 =3D (char *) malloc (2 * pagesize);
-  if (!data2)
-    return 1;
-  data2 +=3D (pagesize - ((long int) data2 & (pagesize - 1))) & (pagesize =
- 1);
+    return 9;
   if (data2 !=3D mmap (data2, pagesize, PROT_READ | PROT_WRITE,
 		     MAP_PRIVATE | MAP_FIXED, fd, 0L))
-    return 1;
+    return 10;
   for (i =3D 0; i < pagesize; ++i)
     if (*(data + i) !=3D *(data2 + i))
-      return 1;
+      return 11;
=20
   /* Finally, make sure that changes to the mapped area do not
      percolate back to the file as seen by read().  (This is a bug on
@@ -24303,77 +15691,47 @@
     *(data2 + i) =3D *(data2 + i) + 1;
   data3 =3D (char *) malloc (pagesize);
   if (!data3)
-    return 1;
+    return 12;
   if (read (fd, data3, pagesize) !=3D pagesize)
-    return 1;
+    return 13;
   for (i =3D 0; i < pagesize; ++i)
     if (*(data + i) !=3D *(data3 + i))
-      return 1;
+      return 14;
   close (fd);
   return 0;
 }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   ac_cv_func_mmap_fixed_mapped=3Dyes
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_mmap_fixed_mapped=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap_fixed_mapped" >&5
-echo "${ECHO_T}$ac_cv_func_mmap_fixed_mapped" >&6; }
+  ac_cv_func_mmap_fixed_mapped=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_mmap_fixed_ma=
pped" >&5
+$as_echo "$ac_cv_func_mmap_fixed_mapped" >&6; }
 if test $ac_cv_func_mmap_fixed_mapped =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_MMAP 1
-_ACEOF
-
-fi
-rm -f conftest.mmap
-
-
-{ echo "$as_me:$LINENO: checking if realloc if broken" >&5
-echo $ECHO_N "checking if realloc if broken... $ECHO_C" >&6; }
-if test "${ac_cv_func_realloc_broken+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define HAVE_MMAP 1" >>confdefs.h
+
+fi
+rm -f conftest.mmap conftest.txt
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if realloc if broken" >&5
+$as_echo_n "checking if realloc if broken... " >&6; }
+if test "${ac_cv_func_realloc_broken+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 ac_cv_func_realloc_broken=3Dno
-if test "$cross_compiling" =3D yes; then
+if test "$cross_compiling" =3D yes; then :
   :
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stddef.h>
@@ -24385,51 +15743,24 @@
 }
=20
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   :
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_realloc_broken=3Dyes
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_realloc_broken" >&5
-echo "${ECHO_T}$ac_cv_func_realloc_broken" >&6; }
+  ac_cv_func_realloc_broken=3Dyes
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_realloc_broke=
n" >&5
+$as_echo "$ac_cv_func_realloc_broken" >&6; }
 if test "$ac_cv_func_realloc_broken" =3D yes ; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define BROKEN_REALLOC 1
-_ACEOF
-
-fi
-
+$as_echo "#define BROKEN_REALLOC 1" >>confdefs.h
+
+fi
=20
=20
=20
@@ -24449,13 +15780,17 @@
=20
=20
=20
+$as_echo "#define rk_PATH_DELIM '/'" >>confdefs.h
+
+
+
=20
=20
=20
=20
=20
 # Check whether --enable-developer was given.
-if test "${enable_developer+set}" =3D set; then
+if test "${enable_developer+set}" =3D set; then :
   enableval=3D$enable_developer;
 fi
=20
@@ -24471,6 +15806,7 @@
   #   -Wcast-align doesn't work well on alpha osf/1
   #   -Wmissing-prototypes -Wpointer-arith -Wbad-function-cast
   #   -Wmissing-declarations -Wnested-externs
+  #   -Wstrict-overflow=3D5
   WFLAGS=3D"-Wall -Wmissing-prototypes -Wpointer-arith -Wbad-function-cast=
 -Wmissing-declarations -Wnested-externs $dwflags"
   WFLAGS_NOUNUSED=3D"-Wno-unused"
   WFLAGS_NOIMPLICITINT=3D"-Wno-implicit-int"
@@ -24484,16 +15820,12 @@
=20
=20
 cv=3D`echo "ssize_t" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for ssize_t" >&5
-echo $ECHO_N "checking for ssize_t... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ssize_t" >&5
+$as_echo_n "checking for ssize_t... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -24510,93 +15842,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo ssize_t | sed 'y%abcdefghijklmnopqrstuvwxyz./- %A=
BCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for ssize_t" >&5
-echo $ECHO_N "checking for ssize_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_ssize_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef ssize_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_ssize_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_ssize_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_ssize_t" >&5
-echo "${ECHO_T}$ac_cv_type_ssize_t" >&6; }
-if test $ac_cv_type_ssize_t =3D yes; then
+	ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes=
_default"
+if test "x$ac_cv_type_ssize_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SSIZE_T 1
@@ -24618,16 +15878,12 @@
=20
=20
 cv=3D`echo "long long" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for long long" >&5
-echo $ECHO_N "checking for long long... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long long" >&5
+$as_echo_n "checking for long long... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -24644,93 +15900,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo long long | sed 'y%abcdefghijklmnopqrstuvwxyz./- =
%ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for long long" >&5
-echo $ECHO_N "checking for long long... $ECHO_C" >&6; }
-if test "${ac_cv_type_long_long+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef long long ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_long_long=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_long_long=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5
-echo "${ECHO_T}$ac_cv_type_long_long" >&6; }
-if test $ac_cv_type_long_long =3D yes; then
+	ac_fn_c_check_type "$LINENO" "long long" "ac_cv_type_long_long" "$ac_incl=
udes_default"
+if test "x$ac_cv_type_long_long" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_LONG_LONG 1
@@ -24753,45 +15937,6 @@
=20
=20
=20
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
 for ac_header in \
 	arpa/inet.h				\
 	config.h				\
@@ -24811,6 +15956,7 @@
 	poll.h					\
 	pwd.h					\
 	rpcsvc/ypclnt.h				\
+	search.h				\
 	shadow.h				\
 	stdint.h				\
 	sys/bswap.h				\
@@ -24828,148 +15974,20 @@
 	sys/wait.h				\
 	syslog.h				\
 	termios.h				\
+	winsock2.h				\
+	ws2tcpip.h				\
 	unistd.h				\
 	userconf.h				\
 	usersec.h				\
 	util.h					\
=20
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
 _ACEOF
=20
 fi
@@ -24980,16 +15998,12 @@
=20
=20
 cv=3D`echo "uintptr_t" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for uintptr_t" >&5
-echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uintptr_t" >&5
+$as_echo_n "checking for uintptr_t... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -25008,93 +16022,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo uintptr_t | sed 'y%abcdefghijklmnopqrstuvwxyz./- =
%ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for uintptr_t" >&5
-echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_uintptr_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef uintptr_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_uintptr_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_uintptr_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_uintptr_t" >&5
-echo "${ECHO_T}$ac_cv_type_uintptr_t" >&6; }
-if test $ac_cv_type_uintptr_t =3D yes; then
+	ac_fn_c_check_type "$LINENO" "uintptr_t" "ac_cv_type_uintptr_t" "$ac_incl=
udes_default"
+if test "x$ac_cv_type_uintptr_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_UINTPTR_T 1
@@ -25112,276 +16054,83 @@
 fi
=20
=20
-
 for ac_header in vis.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+do :
+  ac_fn_c_check_header_compile "$LINENO" "vis.h" "ac_cv_header_vis_h" "
 #include <vis.h>
 #ifndef VIS_SP
 #error invis
 #endif
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_vis_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_VIS_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in netdb.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+do :
+  ac_fn_c_check_header_compile "$LINENO" "netdb.h" "ac_cv_header_netdb_h" =
"$ac_includes_default
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+"
+if test "x$ac_cv_header_netdb_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_NETDB_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in sys/socket.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+do :
+  ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_=
socket_h" "$ac_includes_default
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+"
+if test "x$ac_cv_header_sys_socket_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SYS_SOCKET_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in net/if.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "net/if.h" "ac_cv_header_net_if_h=
" "$ac_includes_default
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
 #if HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_net_if_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_NET_IF_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in netinet6/in6_var.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "netinet6/in6_var.h" "ac_cv_heade=
r_netinet6_in6_var_h" "$ac_includes_default
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
@@ -25392,168 +16141,46 @@
 #include <netinet6/in6.h>
 #endif
=20
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_netinet6_in6_var_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_NETINET6_IN6_VAR_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in sys/sysctl.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "sys/sysctl.h" "ac_cv_header_sys_=
sysctl_h" "$ac_includes_default
 #ifdef HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
=20
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_sys_sysctl_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SYS_SYSCTL_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in sys/proc.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "sys/proc.h" "ac_cv_header_sys_pr=
oc_h" "$ac_includes_default
 #ifdef HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
=20
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+"
+if test "x$ac_cv_header_sys_proc_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SYS_PROC_H 1
 _ACEOF
=20
 fi
@@ -25579,6 +16206,14 @@
   have_ifaddrs_h_FALSE=3D
 fi
=20
+ if test "$ac_cv_header_search_h" =3D yes; then
+  have_search_h_TRUE=3D
+  have_search_h_FALSE=3D'#'
+else
+  have_search_h_TRUE=3D'#'
+  have_search_h_FALSE=3D
+fi
+
  if test "$ac_cv_header_vis_h" =3D yes; then
   have_vis_h_TRUE=3D
   have_vis_h_FALSE=3D'#'
@@ -25593,10 +16228,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for socket" >&5
-echo $ECHO_N "checking for socket... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_socket+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket" >&5
+$as_echo_n "checking for socket... " >&6; }
+if test "${ac_cv_funclib_socket+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_socket\" !=3D yes" ; then
@@ -25610,11 +16245,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -25625,34 +16256,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_socket=3D$ac_lib; else a=
c_cv_funclib_socket=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_socket=3D\${ac_cv_funclib_socket-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -25664,95 +16272,12 @@
 eval "ac_res=3D\$ac_cv_funclib_socket"
=20
 if false; then
-
-for ac_func in socket
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in socket
+do :
+  ac_fn_c_check_func "$LINENO" "socket" "ac_cv_func_socket"
+if test "x$ac_cv_func_socket" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SOCKET 1
 _ACEOF
=20
 fi
@@ -25772,14 +16297,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_socket=3Dno"
 	eval "LIB_socket=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_socket=3Dyes"
@@ -25792,8 +16317,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -25806,10 +16331,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for gethostbyname" >&5
-echo $ECHO_N "checking for gethostbyname... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_gethostbyname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname" >&5
+$as_echo_n "checking for gethostbyname... " >&6; }
+if test "${ac_cv_funclib_gethostbyname+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_gethostbyname\" !=3D yes" ; then
@@ -25823,11 +16348,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -25838,34 +16359,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_gethostbyname=3D$ac_lib;=
 else ac_cv_funclib_gethostbyname=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_gethostbyname=3D\${ac_cv_funclib_gethostbyname-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -25877,95 +16375,12 @@
 eval "ac_res=3D\$ac_cv_funclib_gethostbyname"
=20
 if false; then
-
-for ac_func in gethostbyname
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in gethostbyname
+do :
+  ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname"
+if test "x$ac_cv_func_gethostbyname" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETHOSTBYNAME 1
 _ACEOF
=20
 fi
@@ -25985,14 +16400,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_gethostbyname=3Dno"
 	eval "LIB_gethostbyname=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_gethostbyname=3Dyes"
@@ -26005,8 +16420,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -26019,10 +16434,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for syslog" >&5
-echo $ECHO_N "checking for syslog... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_syslog+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for syslog" >&5
+$as_echo_n "checking for syslog... " >&6; }
+if test "${ac_cv_funclib_syslog+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_syslog\" !=3D yes" ; then
@@ -26036,11 +16451,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -26051,34 +16462,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_syslog=3D$ac_lib; else a=
c_cv_funclib_syslog=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_syslog=3D\${ac_cv_funclib_syslog-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -26090,95 +16478,12 @@
 eval "ac_res=3D\$ac_cv_funclib_syslog"
=20
 if false; then
-
-for ac_func in syslog
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in syslog
+do :
+  ac_fn_c_check_func "$LINENO" "syslog" "ac_cv_func_syslog"
+if test "x$ac_cv_func_syslog" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SYSLOG 1
 _ACEOF
=20
 fi
@@ -26198,14 +16503,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_syslog=3Dno"
 	eval "LIB_syslog=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_syslog=3Dyes"
@@ -26218,8 +16523,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -26232,30 +16537,28 @@
=20
=20
 # Check whether --with-ipv6 was given.
-if test "${with_ipv6+set}" =3D set; then
+if test "${with_ipv6+set}" =3D set; then :
   withval=3D$with_ipv6;
-if test "$withval" =3D "no"; then
-	ac_cv_lib_ipv6=3Dno
-fi
+        ac_cv_lib_ipv6=3D"$withval"
+
 fi
=20
 save_CFLAGS=3D"${CFLAGS}"
-{ echo "$as_me:$LINENO: checking for IPv6 stack type" >&5
-echo $ECHO_N "checking for IPv6 stack type... $ECHO_C" >&6; }
-if test "${v6type+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  v6type=3Dunknown
-v6lib=3Dnone
-
-for i in v6d toshiba kame inria zeta linux; do
-	case $i in
-	v6d)
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+
+if test "X$ac_cv_lib_ipv6" !=3D "Xno"; then
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for IPv6 stack type" >&5
+$as_echo_n "checking for IPv6 stack type... " >&6; }
+if test "${rk_cv_v6type+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  	v6type=3Dunknown
+	v6lib=3Dnone
+
+	for i in v6d toshiba kame inria zeta linux; do
+		case $i in
+		v6d)
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include </usr/local/v6/include/sys/types.h>
@@ -26264,20 +16567,16 @@
 #endif
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "yes" >/dev/null 2>&1; then
+  $EGREP "yes" >/dev/null 2>&1; then :
   v6type=3D$i; v6lib=3Dv6;
-			v6libdir=3D/usr/local/v6/lib;
-			CFLAGS=3D"-I/usr/local/v6/include $CFLAGS"
+				v6libdir=3D/usr/local/v6/lib;
+				CFLAGS=3D"-I/usr/local/v6/include $CFLAGS"
 fi
 rm -f conftest*
=20
-		;;
-	toshiba)
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			;;
+		toshiba)
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/param.h>
@@ -26286,20 +16585,16 @@
 #endif
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "yes" >/dev/null 2>&1; then
+  $EGREP "yes" >/dev/null 2>&1; then :
   v6type=3D$i; v6lib=3Dinet6;
-			v6libdir=3D/usr/local/v6/lib;
-			CFLAGS=3D"-DINET6 $CFLAGS"
+				v6libdir=3D/usr/local/v6/lib;
+				CFLAGS=3D"-DINET6 $CFLAGS"
 fi
 rm -f conftest*
=20
-		;;
-	kame)
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			;;
+		kame)
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <netinet/in.h>
@@ -26308,20 +16603,16 @@
 #endif
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "yes" >/dev/null 2>&1; then
+  $EGREP "yes" >/dev/null 2>&1; then :
   v6type=3D$i; v6lib=3Dinet6;
-			v6libdir=3D/usr/local/v6/lib;
-			CFLAGS=3D"-DINET6 $CFLAGS"
+				v6libdir=3D/usr/local/v6/lib;
+				CFLAGS=3D"-DINET6 $CFLAGS"
 fi
 rm -f conftest*
=20
-		;;
-	inria)
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			;;
+		inria)
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <netinet/in.h>
@@ -26330,18 +16621,14 @@
 #endif
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "yes" >/dev/null 2>&1; then
+  $EGREP "yes" >/dev/null 2>&1; then :
   v6type=3D$i; CFLAGS=3D"-DINET6 $CFLAGS"
 fi
 rm -f conftest*
=20
-		;;
-	zeta)
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			;;
+		zeta)
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/param.h>
@@ -26350,52 +16637,47 @@
 #endif
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "yes" >/dev/null 2>&1; then
+  $EGREP "yes" >/dev/null 2>&1; then :
   v6type=3D$i; v6lib=3Dinet6;
-			v6libdir=3D/usr/local/v6/lib;
-			CFLAGS=3D"-DINET6 $CFLAGS"
+				v6libdir=3D/usr/local/v6/lib;
+				CFLAGS=3D"-DINET6 $CFLAGS"
 fi
 rm -f conftest*
=20
-		;;
-	linux)
-		if test -d /usr/inet6; then
-			v6type=3D$i
-			v6lib=3Dinet6
-			v6libdir=3D/usr/inet6
-			CFLAGS=3D"-DINET6 $CFLAGS"
-		fi
-		;;
-	esac
-	if test "$v6type" !=3D "unknown"; then
-		break
-	fi
-done
-
-if test "$v6lib" !=3D "none"; then
-	for dir in $v6libdir /usr/local/v6/lib /usr/local/lib; do
-		if test -d $dir -a -f $dir/lib$v6lib.a; then
-			LIBS=3D"-L$dir -l$v6lib $LIBS"
+			;;
+		linux)
+			if test -d /usr/inet6; then
+				v6type=3D$i
+				v6lib=3Dinet6
+				v6libdir=3D/usr/inet6
+				CFLAGS=3D"-DINET6 $CFLAGS"
+			fi
+			;;
+		esac
+		if test "$v6type" !=3D "unknown"; then
 			break
 		fi
 	done
-fi
-
-fi
-{ echo "$as_me:$LINENO: result: $v6type" >&5
-echo "${ECHO_T}$v6type" >&6; }
-
-{ echo "$as_me:$LINENO: checking for IPv6" >&5
-echo $ECHO_N "checking for IPv6... $ECHO_C" >&6; }
-if test "${ac_cv_lib_ipv6+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+
+	if test "$v6lib" !=3D "none"; then
+		for dir in $v6libdir /usr/local/v6/lib /usr/local/lib; do
+			if test -d $dir -a -f $dir/lib$v6lib.a; then
+				LIBS=3D"-L$dir -l$v6lib $LIBS"
+				break
+			fi
+		done
+	fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $rk_cv_v6type" >&5
+$as_echo "$rk_cv_v6type" >&6; }
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for IPv6" >&5
+$as_echo_n "checking for IPv6... " >&6; }
+if test "${rk_cv_lib_ipv6+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -26429,42 +16711,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_lib_ipv6=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_ipv6=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_ipv6" >&5
-echo "${ECHO_T}$ac_cv_lib_ipv6" >&6; }
+  ac_cv_lib_ipv6=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $rk_cv_lib_ipv6" >&5
+$as_echo "$rk_cv_lib_ipv6" >&6; }
+fi
+
 if test "$ac_cv_lib_ipv6" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_IPV6 1
-_ACEOF
+$as_echo "#define HAVE_IPV6 1" >>confdefs.h
=20
 else
   CFLAGS=3D"${save_CFLAGS}"
@@ -26472,17 +16733,13 @@
=20
 ## test for AIX missing in6addr_loopback
 if test "$ac_cv_lib_ipv6" =3D yes; then
-	{ echo "$as_me:$LINENO: checking for in6addr_loopback" >&5
-echo $ECHO_N "checking for in6addr_loopback... $ECHO_C" >&6; }
-if test "${ac_cv_var_in6addr_loopback+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for in6addr_loopback" >=
&5
+$as_echo_n "checking for in6addr_loopback... " >&6; }
+if test "${rk_cv_var_in6addr_loopback+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -26508,55 +16765,32 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_in6addr_loopback=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_in6addr_loopback=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_var_in6addr_loopback" >&5
-echo "${ECHO_T}$ac_cv_var_in6addr_loopback" >&6; }
+  ac_cv_var_in6addr_loopback=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $rk_cv_var_in6addr_loopba=
ck" >&5
+$as_echo "$rk_cv_var_in6addr_loopback" >&6; }
 	if test "$ac_cv_var_in6addr_loopback" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_IN6ADDR_LOOPBACK 1
-_ACEOF
-
-	fi
-fi
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for gethostbyname2" >&5
-echo $ECHO_N "checking for gethostbyname2... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_gethostbyname2+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define HAVE_IN6ADDR_LOOPBACK 1" >>confdefs.h
+
+	fi
+fi
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname2" >&5
+$as_echo_n "checking for gethostbyname2... " >&6; }
+if test "${ac_cv_funclib_gethostbyname2+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_gethostbyname2\" !=3D yes" ; then
@@ -26570,11 +16804,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -26585,34 +16815,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_gethostbyname2=3D$ac_lib=
; else ac_cv_funclib_gethostbyname2=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_gethostbyname2=3D\${ac_cv_funclib_gethostbyname2-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -26624,95 +16831,12 @@
 eval "ac_res=3D\$ac_cv_funclib_gethostbyname2"
=20
 if false; then
-
-for ac_func in gethostbyname2
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in gethostbyname2
+do :
+  ac_fn_c_check_func "$LINENO" "gethostbyname2" "ac_cv_func_gethostbyname2"
+if test "x$ac_cv_func_gethostbyname2" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETHOSTBYNAME2 1
 _ACEOF
=20
 fi
@@ -26732,14 +16856,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_gethostbyname2=3Dno"
 	eval "LIB_gethostbyname2=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_gethostbyname2=3Dyes"
@@ -26752,8 +16876,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -26765,168 +16889,24 @@
=20
=20
=20
-
-for ac_header in arpa/nameser.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+for ac_header in arpa/nameser.h dns.h
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in resolv.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "resolv.h" "ac_cv_header_resolv_h=
" "$ac_includes_default
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
@@ -26937,57 +16917,25 @@
 #include <arpa/nameser.h>
 #endif
=20
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for res_search" >&5
-echo $ECHO_N "checking for res_search... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_res_search+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+"
+if test "x$ac_cv_header_resolv_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_RESOLV_H 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for res_search" >&5
+$as_echo_n "checking for res_search... " >&6; }
+if test "${ac_cv_funclib_res_search+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_res_search\" !=3D yes" ; then
@@ -27001,11 +16949,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stdio.h>
@@ -27030,34 +16974,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_res_search=3D$ac_lib; el=
se ac_cv_funclib_res_search=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_res_search=3D\${ac_cv_funclib_res_search-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -27069,95 +16990,12 @@
 eval "ac_res=3D\$ac_cv_funclib_res_search"
=20
 if false; then
-
-for ac_func in res_search
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in res_search
+do :
+  ac_fn_c_check_func "$LINENO" "res_search" "ac_cv_func_res_search"
+if test "x$ac_cv_func_res_search" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_RES_SEARCH 1
 _ACEOF
=20
 fi
@@ -27177,14 +17015,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_res_search=3Dno"
 	eval "LIB_res_search=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_res_search=3Dyes"
@@ -27197,8 +17035,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -27212,10 +17050,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for res_nsearch" >&5
-echo $ECHO_N "checking for res_nsearch... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_res_nsearch+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for res_nsearch" >&5
+$as_echo_n "checking for res_nsearch... " >&6; }
+if test "${ac_cv_funclib_res_nsearch+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_res_nsearch\" !=3D yes" ; then
@@ -27229,11 +17067,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stdio.h>
@@ -27258,34 +17092,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_res_nsearch=3D$ac_lib; e=
lse ac_cv_funclib_res_nsearch=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_res_nsearch=3D\${ac_cv_funclib_res_nsearch-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -27297,95 +17108,12 @@
 eval "ac_res=3D\$ac_cv_funclib_res_nsearch"
=20
 if false; then
-
-for ac_func in res_nsearch
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in res_nsearch
+do :
+  ac_fn_c_check_func "$LINENO" "res_nsearch" "ac_cv_func_res_nsearch"
+if test "x$ac_cv_func_res_nsearch" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_RES_NSEARCH 1
 _ACEOF
=20
 fi
@@ -27405,14 +17133,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_res_nsearch=3Dno"
 	eval "LIB_res_nsearch=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_res_nsearch=3Dyes"
@@ -27425,8 +17153,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -27440,10 +17168,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for res_ndestroy" >&5
-echo $ECHO_N "checking for res_ndestroy... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_res_ndestroy+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for res_ndestroy" >&5
+$as_echo_n "checking for res_ndestroy... " >&6; }
+if test "${ac_cv_funclib_res_ndestroy+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_res_ndestroy\" !=3D yes" ; then
@@ -27457,11 +17185,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stdio.h>
@@ -27486,34 +17210,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_res_ndestroy=3D$ac_lib; =
else ac_cv_funclib_res_ndestroy=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_res_ndestroy=3D\${ac_cv_funclib_res_ndestroy-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -27525,95 +17226,12 @@
 eval "ac_res=3D\$ac_cv_funclib_res_ndestroy"
=20
 if false; then
-
-for ac_func in res_ndestroy
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in res_ndestroy
+do :
+  ac_fn_c_check_func "$LINENO" "res_ndestroy" "ac_cv_func_res_ndestroy"
+if test "x$ac_cv_func_res_ndestroy" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_RES_NDESTROY 1
 _ACEOF
=20
 fi
@@ -27633,14 +17251,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_res_ndestroy=3Dno"
 	eval "LIB_res_ndestroy=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_res_ndestroy=3Dyes"
@@ -27653,8 +17271,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -27667,11 +17285,115 @@
=20
=20
=20
-
-{ echo "$as_me:$LINENO: checking for dn_expand" >&5
-echo $ECHO_N "checking for dn_expand... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_dn_expand+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dns_search" >&5
+$as_echo_n "checking for dns_search... " >&6; }
+if test "${ac_cv_funclib_dns_search+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+if eval "test \"\$ac_cv_func_dns_search\" !=3D yes" ; then
+	ac_save_LIBS=3D"$LIBS"
+	for ac_lib in "" ; do
+		case "$ac_lib" in
+		"") ;;
+		yes) ac_lib=3D"" ;;
+		no) continue ;;
+		-l*) ;;
+		*) ac_lib=3D"-l$ac_lib" ;;
+		esac
+		LIBS=3D" $ac_lib  $ac_save_LIBS"
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#ifdef HAVE_DNS_H
+#include <dns.h>
+#endif
+
+int
+main ()
+{
+dns_search(0,0,0,0,0,0,0,0)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "if test -n \"$ac_lib\";then ac_cv_funclib_dns_search=3D$ac_lib; el=
se ac_cv_funclib_dns_search=3Dyes; fi";break
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	done
+	eval "ac_cv_funclib_dns_search=3D\${ac_cv_funclib_dns_search-no}"
+	LIBS=3D"$ac_save_LIBS"
+fi
+
+fi
+
+
+eval "ac_res=3D\$ac_cv_funclib_dns_search"
+
+if false; then
+	for ac_func in dns_search
+do :
+  ac_fn_c_check_func "$LINENO" "dns_search" "ac_cv_func_dns_search"
+if test "x$ac_cv_func_dns_search" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DNS_SEARCH 1
+_ACEOF
+
+fi
+done
+
+fi
+# dns_search
+eval "ac_tr_func=3DHAVE_`echo dns_search | tr abcdefghijklmnopqrstuvwxyz A=
BCDEFGHIJKLMNOPQRSTUVWXYZ`"
+eval "ac_tr_lib=3DHAVE_LIB`echo $ac_res | sed -e 's/-l//' | tr abcdefghijk=
lmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
+eval "LIB_dns_search=3D$ac_res"
+
+case "$ac_res" in
+	yes)
+	eval "ac_cv_func_dns_search=3Dyes"
+	eval "LIB_dns_search=3D"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+	;;
+	no)
+	eval "ac_cv_func_dns_search=3Dno"
+	eval "LIB_dns_search=3D"
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+	;;
+	*)
+	eval "ac_cv_func_dns_search=3Dyes"
+	eval "ac_cv_lib_`echo "$ac_res" | sed 's/-l//'`=3Dyes"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_lib 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dn_expand" >&5
+$as_echo_n "checking for dn_expand... " >&6; }
+if test "${ac_cv_funclib_dn_expand+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_dn_expand\" !=3D yes" ; then
@@ -27685,11 +17407,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stdio.h>
@@ -27714,34 +17432,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_dn_expand=3D$ac_lib; els=
e ac_cv_funclib_dn_expand=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_dn_expand=3D\${ac_cv_funclib_dn_expand-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -27753,95 +17448,12 @@
 eval "ac_res=3D\$ac_cv_funclib_dn_expand"
=20
 if false; then
-
-for ac_func in dn_expand
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in dn_expand
+do :
+  ac_fn_c_check_func "$LINENO" "dn_expand" "ac_cv_func_dn_expand"
+if test "x$ac_cv_func_dn_expand" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DN_EXPAND 1
 _ACEOF
=20
 fi
@@ -27861,14 +17473,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_dn_expand=3Dno"
 	eval "LIB_dn_expand=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_dn_expand=3Dyes"
@@ -27881,8 +17493,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -27893,18 +17505,14 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for _res" >&5
-echo $ECHO_N "checking for _res... $ECHO_C" >&6; }
-if test "${ac_cv_var__res+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for _res" >&5
+$as_echo_n "checking for _res... " >&6; }
+if test "${ac_cv_var__res+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
 #ifdef HAVE_SYS_TYPES_H
@@ -27928,41 +17536,29 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var__res=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var__res=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var__res=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 if test "$ac_cv_var__res" !=3D yes ; then
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_NAMESER_H
+#include <arpa/nameser.h>
+#endif
+#ifdef HAVE_RESOLV_H
+#include <resolv.h>
+#endif
 extern int _res;
 int foo(void) { return _res; }
 int
@@ -27973,59 +17569,66 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var__res=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var__res=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var__res=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 fi
=20
 ac_foo=3D`eval echo \\$ac_cv_var__res`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE__RES 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: checking whether _res is declared" >&5
-echo $ECHO_N "checking whether _res is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl__res+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdio.h>
+
+# ac_fn_c_check_decl LINENO SYMBOL VAR
+# ------------------------------------
+# Tests whether SYMBOL is declared, setting cache variable VAR accordingly.
+ac_fn_c_check_decl ()
+{
+  as_lineno=3D${as_lineno-"$1"} as_lineno_stack=3Das_lineno_stack=3D$as_li=
neno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $2 is declared=
" >&5
+$as_echo_n "checking whether $2 is declared... " >&6; }
+if { as_var=3D$3; eval "test \"\${$as_var+set}\" =3D set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+int
+main ()
+{
+#ifndef $2
+  (void) $2;
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "$3=3Dyes"
+else
+  eval "$3=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=3D\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" =3D x && { as_lineno=3D;=
 unset as_lineno;}
+
+} # ac_fn_c_check_decl
+ac_fn_c_check_decl "$LINENO" "_res" "ac_cv_have_decl__res" "#include <stdi=
o.h>
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
@@ -28038,83 +17641,33 @@
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
-
-int
-main ()
-{
-#ifndef _res
-  (void) _res;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl__res=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl__res=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl__res" >&5
-echo "${ECHO_T}$ac_cv_have_decl__res" >&6; }
-if test $ac_cv_have_decl__res =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL__RES 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL__RES 0
-_ACEOF
-
-
-fi
-
-
-fi
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for working snprintf" >&5
-echo $ECHO_N "checking for working snprintf... $ECHO_C" >&6; }
-if test "${ac_cv_func_snprintf_working+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+"
+if test "x$ac_cv_have_decl__res" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL__RES $ac_have_decl
+_ACEOF
+
+fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working snprintf" >&5
+$as_echo_n "checking for working snprintf... " >&6; }
+if test "${ac_cv_func_snprintf_working+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_cv_func_snprintf_working=3Dyes
-if test "$cross_compiling" =3D yes; then
+if test "$cross_compiling" =3D yes; then :
   :
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stdio.h>
@@ -28126,42 +17679,18 @@
 	return strcmp(foo, "1") || snprintf(NULL, 0, "%d", 12) !=3D 2;
 }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   :
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_snprintf_working=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_snprintf_working" >&5
-echo "${ECHO_T}$ac_cv_func_snprintf_working" >&6; }
+  ac_cv_func_snprintf_working=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_snprintf_work=
ing" >&5
+$as_echo "$ac_cv_func_snprintf_working" >&6; }
=20
 if test "$ac_cv_func_snprintf_working" =3D yes; then
=20
@@ -28173,16 +17702,12 @@
 if test "$ac_cv_func_snprintf_working" =3D yes; then
=20
 if test "$ac_cv_func_snprintf+set" !=3D set -o "$ac_cv_func_snprintf" =3D =
yes; then
-{ echo "$as_me:$LINENO: checking if snprintf needs a prototype" >&5
-echo $ECHO_N "checking if snprintf needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_snprintf_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if snprintf needs a prot=
otype" >&5
+$as_echo_n "checking if snprintf needs a prototype... " >&6; }
+if test "${ac_cv_func_snprintf_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
 struct foo { int foo; } xx;
@@ -28195,61 +17720,35 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_snprintf_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_snprintf_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_snprintf_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_snprintf_noproto" >&6; }
+  eval "ac_cv_func_snprintf_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_snprintf_nopr=
oto" >&5
+$as_echo "$ac_cv_func_snprintf_noproto" >&6; }
 if test "$ac_cv_func_snprintf_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_SNPRINTF_PROTO 1
-_ACEOF
-
-fi
-fi
-
-fi
-
-
-{ echo "$as_me:$LINENO: checking for working vsnprintf" >&5
-echo $ECHO_N "checking for working vsnprintf... $ECHO_C" >&6; }
-if test "${ac_cv_func_vsnprintf_working+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define NEED_SNPRINTF_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working vsnprintf" >=
&5
+$as_echo_n "checking for working vsnprintf... " >&6; }
+if test "${ac_cv_func_vsnprintf_working+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_cv_func_vsnprintf_working=3Dyes
-if test "$cross_compiling" =3D yes; then
+if test "$cross_compiling" =3D yes; then :
   :
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stdio.h>
@@ -28281,42 +17780,18 @@
 	return foo(0, "12") || bar(0, 2, "12");
 }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   :
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_vsnprintf_working=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vsnprintf_working" >&5
-echo "${ECHO_T}$ac_cv_func_vsnprintf_working" >&6; }
+  ac_cv_func_vsnprintf_working=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vsnprintf_wor=
king" >&5
+$as_echo "$ac_cv_func_vsnprintf_working" >&6; }
=20
 if test "$ac_cv_func_vsnprintf_working" =3D yes; then
=20
@@ -28328,16 +17803,12 @@
 if test "$ac_cv_func_vsnprintf_working" =3D yes; then
=20
 if test "$ac_cv_func_vsnprintf+set" !=3D set -o "$ac_cv_func_vsnprintf" =
=3D yes; then
-{ echo "$as_me:$LINENO: checking if vsnprintf needs a prototype" >&5
-echo $ECHO_N "checking if vsnprintf needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_vsnprintf_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if vsnprintf needs a pro=
totype" >&5
+$as_echo_n "checking if vsnprintf needs a prototype... " >&6; }
+if test "${ac_cv_func_vsnprintf_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
 struct foo { int foo; } xx;
@@ -28350,59 +17821,33 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_vsnprintf_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_vsnprintf_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vsnprintf_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_vsnprintf_noproto" >&6; }
+  eval "ac_cv_func_vsnprintf_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vsnprintf_nop=
roto" >&5
+$as_echo "$ac_cv_func_vsnprintf_noproto" >&6; }
 if test "$ac_cv_func_vsnprintf_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_VSNPRINTF_PROTO 1
-_ACEOF
-
-fi
-fi
-
-fi
-
-
-
-{ echo "$as_me:$LINENO: checking for working glob" >&5
-echo $ECHO_N "checking for working glob... $ECHO_C" >&6; }
-if test "${ac_cv_func_glob_working+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define NEED_VSNPRINTF_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+fi
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working glob" >&5
+$as_echo_n "checking for working glob... " >&6; }
+if test "${ac_cv_func_glob_working+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_cv_func_glob_working=3Dyes
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <stdio.h>
@@ -28424,58 +17869,31 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   :
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_glob_working=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_glob_working" >&5
-echo "${ECHO_T}$ac_cv_func_glob_working" >&6; }
+  ac_cv_func_glob_working=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_glob_working"=
 >&5
+$as_echo "$ac_cv_func_glob_working" >&6; }
=20
 if test "$ac_cv_func_glob_working" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_GLOB 1
-_ACEOF
+$as_echo "#define HAVE_GLOB 1" >>confdefs.h
=20
 fi
 if test "$ac_cv_func_glob_working" =3D yes; then
=20
 if test "$ac_cv_func_glob+set" !=3D set -o "$ac_cv_func_glob" =3D yes; then
-{ echo "$as_me:$LINENO: checking if glob needs a prototype" >&5
-echo $ECHO_N "checking if glob needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_glob_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if glob needs a prototyp=
e" >&5
+$as_echo_n "checking if glob needs a prototype... " >&6; }
+if test "${ac_cv_func_glob_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
 #include <glob.h>
@@ -28489,40 +17907,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_glob_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_glob_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_glob_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_glob_noproto" >&6; }
+  eval "ac_cv_func_glob_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_glob_noproto"=
 >&5
+$as_echo "$ac_cv_func_glob_noproto" >&6; }
 if test "$ac_cv_func_glob_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_GLOB_PROTO 1
-_ACEOF
+$as_echo "#define NEED_GLOB_PROTO 1" >>confdefs.h
=20
 fi
 fi
@@ -28547,33 +17943,6 @@
=20
=20
=20
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
 for ac_func in 				\
 	asnprintf				\
 	asprintf				\
@@ -28583,113 +17952,35 @@
 	getprogname				\
 	getrlimit				\
 	getspnam				\
-	initstate				\
 	issetugid				\
 	on_exit					\
 	poll					\
 	random					\
 	setprogname				\
-	setstate				\
 	strsvis					\
+	strsvisx				\
 	strunvis				\
 	strvis					\
 	strvisx					\
 	svis					\
 	sysconf					\
 	sysctl					\
+	tdelete					\
+	tfind					\
+	twalk					\
 	uname					\
 	unvis					\
 	vasnprintf				\
 	vasprintf				\
 	vis					\
=20
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+do :
+  as_ac_var=3D`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+eval as_val=3D\$$as_ac_var
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
 _ACEOF
=20
 fi
@@ -28720,10 +18011,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for getsockopt" >&5
-echo $ECHO_N "checking for getsockopt... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_getsockopt+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getsockopt" >&5
+$as_echo_n "checking for getsockopt... " >&6; }
+if test "${ac_cv_funclib_getsockopt+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_getsockopt\" !=3D yes" ; then
@@ -28737,11 +18028,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -28757,34 +18044,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_getsockopt=3D$ac_lib; el=
se ac_cv_funclib_getsockopt=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_getsockopt=3D\${ac_cv_funclib_getsockopt-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -28796,95 +18060,12 @@
 eval "ac_res=3D\$ac_cv_funclib_getsockopt"
=20
 if false; then
-
-for ac_func in getsockopt
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in getsockopt
+do :
+  ac_fn_c_check_func "$LINENO" "getsockopt" "ac_cv_func_getsockopt"
+if test "x$ac_cv_func_getsockopt" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETSOCKOPT 1
 _ACEOF
=20
 fi
@@ -28904,14 +18085,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_getsockopt=3Dno"
 	eval "LIB_getsockopt=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_getsockopt=3Dyes"
@@ -28924,19 +18105,19 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for setsockopt" >&5
-echo $ECHO_N "checking for setsockopt... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_setsockopt+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for setsockopt" >&5
+$as_echo_n "checking for setsockopt... " >&6; }
+if test "${ac_cv_funclib_setsockopt+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_setsockopt\" !=3D yes" ; then
@@ -28950,11 +18131,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -28970,34 +18147,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_setsockopt=3D$ac_lib; el=
se ac_cv_funclib_setsockopt=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_setsockopt=3D\${ac_cv_funclib_setsockopt-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -29009,95 +18163,12 @@
 eval "ac_res=3D\$ac_cv_funclib_setsockopt"
=20
 if false; then
-
-for ac_func in setsockopt
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in setsockopt
+do :
+  ac_fn_c_check_func "$LINENO" "setsockopt" "ac_cv_func_setsockopt"
+if test "x$ac_cv_func_setsockopt" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SETSOCKOPT 1
 _ACEOF
=20
 fi
@@ -29117,14 +18188,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_setsockopt=3Dno"
 	eval "LIB_setsockopt=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_setsockopt=3Dyes"
@@ -29137,21 +18208,21 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for hstrerror" >&5
-echo $ECHO_N "checking for hstrerror... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_hstrerror+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for hstrerror" >&5
+$as_echo_n "checking for hstrerror... " >&6; }
+if test "${ac_cv_funclib_hstrerror+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_hstrerror\" !=3D yes" ; then
@@ -29165,11 +18236,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
@@ -29182,34 +18249,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_hstrerror=3D$ac_lib; els=
e ac_cv_funclib_hstrerror=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_hstrerror=3D\${ac_cv_funclib_hstrerror-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -29221,95 +18265,12 @@
 eval "ac_res=3D\$ac_cv_funclib_hstrerror"
=20
 if false; then
-
-for ac_func in hstrerror
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in hstrerror
+do :
+  ac_fn_c_check_func "$LINENO" "hstrerror" "ac_cv_func_hstrerror"
+if test "x$ac_cv_func_hstrerror" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_HSTRERROR 1
 _ACEOF
=20
 fi
@@ -29329,14 +18290,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_hstrerror=3Dno"
 	eval "LIB_hstrerror=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_hstrerror=3Dyes"
@@ -29349,8 +18310,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -29370,16 +18331,12 @@
=20
=20
 if test "$ac_cv_func_hstrerror+set" !=3D set -o "$ac_cv_func_hstrerror" =
=3D yes; then
-{ echo "$as_me:$LINENO: checking if hstrerror needs a prototype" >&5
-echo $ECHO_N "checking if hstrerror needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_hstrerror_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if hstrerror needs a pro=
totype" >&5
+$as_echo_n "checking if hstrerror needs a prototype... " >&6; }
+if test "${ac_cv_func_hstrerror_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_NETDB_H
@@ -29395,40 +18352,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_hstrerror_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_hstrerror_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_hstrerror_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_hstrerror_noproto" >&6; }
+  eval "ac_cv_func_hstrerror_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_hstrerror_nop=
roto" >&5
+$as_echo "$ac_cv_func_hstrerror_noproto" >&6; }
 if test "$ac_cv_func_hstrerror_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_HSTRERROR_PROTO 1
-_ACEOF
+$as_echo "#define NEED_HSTRERROR_PROTO 1" >>confdefs.h
=20
 fi
 fi
@@ -29436,16 +18371,12 @@
=20
=20
 if test "$ac_cv_func_asprintf+set" !=3D set -o "$ac_cv_func_asprintf" =3D =
yes; then
-{ echo "$as_me:$LINENO: checking if asprintf needs a prototype" >&5
-echo $ECHO_N "checking if asprintf needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_asprintf_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if asprintf needs a prot=
otype" >&5
+$as_echo_n "checking if asprintf needs a prototype... " >&6; }
+if test "${ac_cv_func_asprintf_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 	#include <stdio.h>
@@ -29460,55 +18391,29 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_asprintf_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_asprintf_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_asprintf_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_asprintf_noproto" >&6; }
+  eval "ac_cv_func_asprintf_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_asprintf_nopr=
oto" >&5
+$as_echo "$ac_cv_func_asprintf_noproto" >&6; }
 if test "$ac_cv_func_asprintf_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_ASPRINTF_PROTO 1
-_ACEOF
+$as_echo "#define NEED_ASPRINTF_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
 if test "$ac_cv_func_vasprintf+set" !=3D set -o "$ac_cv_func_vasprintf" =
=3D yes; then
-{ echo "$as_me:$LINENO: checking if vasprintf needs a prototype" >&5
-echo $ECHO_N "checking if vasprintf needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_vasprintf_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if vasprintf needs a pro=
totype" >&5
+$as_echo_n "checking if vasprintf needs a prototype... " >&6; }
+if test "${ac_cv_func_vasprintf_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 	#include <stdio.h>
@@ -29523,55 +18428,29 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_vasprintf_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_vasprintf_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vasprintf_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_vasprintf_noproto" >&6; }
+  eval "ac_cv_func_vasprintf_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vasprintf_nop=
roto" >&5
+$as_echo "$ac_cv_func_vasprintf_noproto" >&6; }
 if test "$ac_cv_func_vasprintf_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_VASPRINTF_PROTO 1
-_ACEOF
+$as_echo "#define NEED_VASPRINTF_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
 if test "$ac_cv_func_asnprintf+set" !=3D set -o "$ac_cv_func_asnprintf" =
=3D yes; then
-{ echo "$as_me:$LINENO: checking if asnprintf needs a prototype" >&5
-echo $ECHO_N "checking if asnprintf needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_asnprintf_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if asnprintf needs a pro=
totype" >&5
+$as_echo_n "checking if asnprintf needs a prototype... " >&6; }
+if test "${ac_cv_func_asnprintf_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 	#include <stdio.h>
@@ -29586,55 +18465,29 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_asnprintf_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_asnprintf_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_asnprintf_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_asnprintf_noproto" >&6; }
+  eval "ac_cv_func_asnprintf_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_asnprintf_nop=
roto" >&5
+$as_echo "$ac_cv_func_asnprintf_noproto" >&6; }
 if test "$ac_cv_func_asnprintf_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_ASNPRINTF_PROTO 1
-_ACEOF
+$as_echo "#define NEED_ASNPRINTF_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
 if test "$ac_cv_func_vasnprintf+set" !=3D set -o "$ac_cv_func_vasnprintf" =
=3D yes; then
-{ echo "$as_me:$LINENO: checking if vasnprintf needs a prototype" >&5
-echo $ECHO_N "checking if vasnprintf needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_vasnprintf_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if vasnprintf needs a pr=
ototype" >&5
+$as_echo_n "checking if vasnprintf needs a prototype... " >&6; }
+if test "${ac_cv_func_vasnprintf_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 	#include <stdio.h>
@@ -29649,52 +18502,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_vasnprintf_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_vasnprintf_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vasnprintf_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_vasnprintf_noproto" >&6; }
+  eval "ac_cv_func_vasnprintf_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vasnprintf_no=
proto" >&5
+$as_echo "$ac_cv_func_vasnprintf_noproto" >&6; }
 if test "$ac_cv_func_vasnprintf_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_VASNPRINTF_PROTO 1
-_ACEOF
-
-fi
-fi
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for bswap16" >&5
-echo $ECHO_N "checking for bswap16... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_bswap16+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define NEED_VASNPRINTF_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for bswap16" >&5
+$as_echo_n "checking for bswap16... " >&6; }
+if test "${ac_cv_funclib_bswap16+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_bswap16\" !=3D yes" ; then
@@ -29708,12 +18539,11 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
 #ifdef HAVE_SYS_BSWAP_H
 #include <sys/bswap.h>
 #endif
@@ -29725,34 +18555,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_bswap16=3D$ac_lib; else =
ac_cv_funclib_bswap16=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_bswap16=3D\${ac_cv_funclib_bswap16-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -29764,95 +18571,12 @@
 eval "ac_res=3D\$ac_cv_funclib_bswap16"
=20
 if false; then
-
-for ac_func in bswap16
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in bswap16
+do :
+  ac_fn_c_check_func "$LINENO" "bswap16" "ac_cv_func_bswap16"
+if test "x$ac_cv_func_bswap16" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_BSWAP16 1
 _ACEOF
=20
 fi
@@ -29872,14 +18596,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_bswap16=3Dno"
 	eval "LIB_bswap16=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_bswap16=3Dyes"
@@ -29892,20 +18616,20 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for bswap32" >&5
-echo $ECHO_N "checking for bswap32... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_bswap32+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for bswap32" >&5
+$as_echo_n "checking for bswap32... " >&6; }
+if test "${ac_cv_funclib_bswap32+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_bswap32\" !=3D yes" ; then
@@ -29919,12 +18643,11 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
 #ifdef HAVE_SYS_BSWAP_H
 #include <sys/bswap.h>
 #endif
@@ -29936,34 +18659,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_bswap32=3D$ac_lib; else =
ac_cv_funclib_bswap32=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_bswap32=3D\${ac_cv_funclib_bswap32-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -29975,95 +18675,12 @@
 eval "ac_res=3D\$ac_cv_funclib_bswap32"
=20
 if false; then
-
-for ac_func in bswap32
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in bswap32
+do :
+  ac_fn_c_check_func "$LINENO" "bswap32" "ac_cv_func_bswap32"
+if test "x$ac_cv_func_bswap32" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_BSWAP32 1
 _ACEOF
=20
 fi
@@ -30083,14 +18700,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_bswap32=3Dno"
 	eval "LIB_bswap32=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_bswap32=3Dyes"
@@ -30103,20 +18720,20 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for pidfile" >&5
-echo $ECHO_N "checking for pidfile... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_pidfile+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pidfile" >&5
+$as_echo_n "checking for pidfile... " >&6; }
+if test "${ac_cv_funclib_pidfile+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_pidfile\" !=3D yes" ; then
@@ -30130,11 +18747,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_UTIL_H
 #include <util.h>
@@ -30147,34 +18760,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_pidfile=3D$ac_lib; else =
ac_cv_funclib_pidfile=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_pidfile=3D\${ac_cv_funclib_pidfile-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -30186,95 +18776,12 @@
 eval "ac_res=3D\$ac_cv_funclib_pidfile"
=20
 if false; then
-
-for ac_func in pidfile
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in pidfile
+do :
+  ac_fn_c_check_func "$LINENO" "pidfile" "ac_cv_func_pidfile"
+if test "x$ac_cv_func_pidfile" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_PIDFILE 1
 _ACEOF
=20
 fi
@@ -30294,14 +18801,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_pidfile=3Dno"
 	eval "LIB_pidfile=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_pidfile=3Dyes"
@@ -30314,21 +18821,21 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for getaddrinfo" >&5
-echo $ECHO_N "checking for getaddrinfo... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_getaddrinfo+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getaddrinfo" >&5
+$as_echo_n "checking for getaddrinfo... " >&6; }
+if test "${ac_cv_funclib_getaddrinfo+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_getaddrinfo\" !=3D yes" ; then
@@ -30342,15 +18849,14 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -30359,34 +18865,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_getaddrinfo=3D$ac_lib; e=
lse ac_cv_funclib_getaddrinfo=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_getaddrinfo=3D\${ac_cv_funclib_getaddrinfo-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -30398,95 +18881,12 @@
 eval "ac_res=3D\$ac_cv_funclib_getaddrinfo"
=20
 if false; then
-
-for ac_func in getaddrinfo
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in getaddrinfo
+do :
+  ac_fn_c_check_func "$LINENO" "getaddrinfo" "ac_cv_func_getaddrinfo"
+if test "x$ac_cv_func_getaddrinfo" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETADDRINFO 1
 _ACEOF
=20
 fi
@@ -30506,14 +18906,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_getaddrinfo=3Dno"
 	eval "LIB_getaddrinfo=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_getaddrinfo=3Dyes"
@@ -30526,8 +18926,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -30550,10 +18950,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for getnameinfo" >&5
-echo $ECHO_N "checking for getnameinfo... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_getnameinfo+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getnameinfo" >&5
+$as_echo_n "checking for getnameinfo... " >&6; }
+if test "${ac_cv_funclib_getnameinfo+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_getnameinfo\" !=3D yes" ; then
@@ -30567,15 +18967,14 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -30584,34 +18983,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_getnameinfo=3D$ac_lib; e=
lse ac_cv_funclib_getnameinfo=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_getnameinfo=3D\${ac_cv_funclib_getnameinfo-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -30623,95 +18999,12 @@
 eval "ac_res=3D\$ac_cv_funclib_getnameinfo"
=20
 if false; then
-
-for ac_func in getnameinfo
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in getnameinfo
+do :
+  ac_fn_c_check_func "$LINENO" "getnameinfo" "ac_cv_func_getnameinfo"
+if test "x$ac_cv_func_getnameinfo" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETNAMEINFO 1
 _ACEOF
=20
 fi
@@ -30731,14 +19024,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_getnameinfo=3Dno"
 	eval "LIB_getnameinfo=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_getnameinfo=3Dyes"
@@ -30751,8 +19044,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -30775,10 +19068,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for freeaddrinfo" >&5
-echo $ECHO_N "checking for freeaddrinfo... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_freeaddrinfo+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for freeaddrinfo" >&5
+$as_echo_n "checking for freeaddrinfo... " >&6; }
+if test "${ac_cv_funclib_freeaddrinfo+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_freeaddrinfo\" !=3D yes" ; then
@@ -30792,15 +19085,14 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -30809,34 +19101,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_freeaddrinfo=3D$ac_lib; =
else ac_cv_funclib_freeaddrinfo=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_freeaddrinfo=3D\${ac_cv_funclib_freeaddrinfo-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -30848,95 +19117,12 @@
 eval "ac_res=3D\$ac_cv_funclib_freeaddrinfo"
=20
 if false; then
-
-for ac_func in freeaddrinfo
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in freeaddrinfo
+do :
+  ac_fn_c_check_func "$LINENO" "freeaddrinfo" "ac_cv_func_freeaddrinfo"
+if test "x$ac_cv_func_freeaddrinfo" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_FREEADDRINFO 1
 _ACEOF
=20
 fi
@@ -30956,14 +19142,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_freeaddrinfo=3Dno"
 	eval "LIB_freeaddrinfo=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_freeaddrinfo=3Dyes"
@@ -30976,8 +19162,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -31000,10 +19186,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for gai_strerror" >&5
-echo $ECHO_N "checking for gai_strerror... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_gai_strerror+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for gai_strerror" >&5
+$as_echo_n "checking for gai_strerror... " >&6; }
+if test "${ac_cv_funclib_gai_strerror+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_gai_strerror\" !=3D yes" ; then
@@ -31017,15 +19203,14 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -31034,34 +19219,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_gai_strerror=3D$ac_lib; =
else ac_cv_funclib_gai_strerror=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_gai_strerror=3D\${ac_cv_funclib_gai_strerror-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -31073,95 +19235,12 @@
 eval "ac_res=3D\$ac_cv_funclib_gai_strerror"
=20
 if false; then
-
-for ac_func in gai_strerror
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in gai_strerror
+do :
+  ac_fn_c_check_func "$LINENO" "gai_strerror" "ac_cv_func_gai_strerror"
+if test "x$ac_cv_func_gai_strerror" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GAI_STRERROR 1
 _ACEOF
=20
 fi
@@ -31181,14 +19260,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_gai_strerror=3Dno"
 	eval "LIB_gai_strerror=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_gai_strerror=3Dyes"
@@ -31201,8 +19280,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -31221,88 +19300,33 @@
 fi
=20
=20
-{ echo "$as_me:$LINENO: checking for chown" >&5
-echo $ECHO_N "checking for chown... $ECHO_C" >&6; }
-if test "${ac_cv_func_chown+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define chown to an innocuous variant, in case <limits.h> declares chown.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define chown innocuous_chown
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char chown (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef chown
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char chown ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_chown || defined __stub___chown
-choke me
-#endif
-
-int
-main ()
-{
-return chown ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_chown=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_chown=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_chown" >&5
-echo "${ECHO_T}$ac_cv_func_chown" >&6; }
-if test $ac_cv_func_chown =3D yes; then
+case "$host_os" in
+	darwin*)
+		;;
+	*)
+
+$as_echo "#define SUPPORT_DETACH 1" >>confdefs.h
+
+		ac_fn_c_check_func "$LINENO" "daemon" "ac_cv_func_daemon"
+if test "x$ac_cv_func_daemon" =3D x""yes; then :
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DAEMON 1
+_ACEOF
+
+else
+  case " $LIBOBJS " in
+  *" daemon.$ac_objext "* ) ;;
+  *) LIBOBJS=3D"$LIBOBJS daemon.$ac_objext"
+ ;;
+esac
+
+fi
+ ;;
+esac
+
+ac_fn_c_check_func "$LINENO" "chown" "ac_cv_func_chown"
+if test "x$ac_cv_func_chown" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_CHOWN 1
@@ -31316,88 +19340,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for copyhostent" >&5
-echo $ECHO_N "checking for copyhostent... $ECHO_C" >&6; }
-if test "${ac_cv_func_copyhostent+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define copyhostent to an innocuous variant, in case <limits.h> declares=
 copyhostent.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define copyhostent innocuous_copyhostent
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char copyhostent (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef copyhostent
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char copyhostent ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_copyhostent || defined __stub___copyhostent
-choke me
-#endif
-
-int
-main ()
-{
-return copyhostent ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_copyhostent=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_copyhostent=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_copyhostent" >&5
-echo "${ECHO_T}$ac_cv_func_copyhostent" >&6; }
-if test $ac_cv_func_copyhostent =3D yes; then
+ac_fn_c_check_func "$LINENO" "copyhostent" "ac_cv_func_copyhostent"
+if test "x$ac_cv_func_copyhostent" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_COPYHOSTENT 1
@@ -31411,88 +19355,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for closefrom" >&5
-echo $ECHO_N "checking for closefrom... $ECHO_C" >&6; }
-if test "${ac_cv_func_closefrom+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define closefrom to an innocuous variant, in case <limits.h> declares c=
losefrom.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define closefrom innocuous_closefrom
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char closefrom (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef closefrom
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char closefrom ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_closefrom || defined __stub___closefrom
-choke me
-#endif
-
-int
-main ()
-{
-return closefrom ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_closefrom=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_closefrom=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_closefrom" >&5
-echo "${ECHO_T}$ac_cv_func_closefrom" >&6; }
-if test $ac_cv_func_closefrom =3D yes; then
+ac_fn_c_check_func "$LINENO" "closefrom" "ac_cv_func_closefrom"
+if test "x$ac_cv_func_closefrom" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_CLOSEFROM 1
@@ -31506,183 +19370,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for daemon" >&5
-echo $ECHO_N "checking for daemon... $ECHO_C" >&6; }
-if test "${ac_cv_func_daemon+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define daemon to an innocuous variant, in case <limits.h> declares daem=
on.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define daemon innocuous_daemon
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char daemon (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef daemon
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char daemon ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_daemon || defined __stub___daemon
-choke me
-#endif
-
-int
-main ()
-{
-return daemon ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_daemon=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_daemon=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_daemon" >&5
-echo "${ECHO_T}$ac_cv_func_daemon" >&6; }
-if test $ac_cv_func_daemon =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DAEMON 1
-_ACEOF
-
-else
-  case " $LIBOBJS " in
-  *" daemon.$ac_objext "* ) ;;
-  *) LIBOBJS=3D"$LIBOBJS daemon.$ac_objext"
- ;;
-esac
-
-fi
-{ echo "$as_me:$LINENO: checking for ecalloc" >&5
-echo $ECHO_N "checking for ecalloc... $ECHO_C" >&6; }
-if test "${ac_cv_func_ecalloc+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define ecalloc to an innocuous variant, in case <limits.h> declares eca=
lloc.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define ecalloc innocuous_ecalloc
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char ecalloc (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef ecalloc
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char ecalloc ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_ecalloc || defined __stub___ecalloc
-choke me
-#endif
-
-int
-main ()
-{
-return ecalloc ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_ecalloc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_ecalloc=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_ecalloc" >&5
-echo "${ECHO_T}$ac_cv_func_ecalloc" >&6; }
-if test $ac_cv_func_ecalloc =3D yes; then
+ac_fn_c_check_func "$LINENO" "ecalloc" "ac_cv_func_ecalloc"
+if test "x$ac_cv_func_ecalloc" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_ECALLOC 1
@@ -31696,88 +19385,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for emalloc" >&5
-echo $ECHO_N "checking for emalloc... $ECHO_C" >&6; }
-if test "${ac_cv_func_emalloc+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define emalloc to an innocuous variant, in case <limits.h> declares ema=
lloc.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define emalloc innocuous_emalloc
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char emalloc (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef emalloc
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char emalloc ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_emalloc || defined __stub___emalloc
-choke me
-#endif
-
-int
-main ()
-{
-return emalloc ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_emalloc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_emalloc=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_emalloc" >&5
-echo "${ECHO_T}$ac_cv_func_emalloc" >&6; }
-if test $ac_cv_func_emalloc =3D yes; then
+ac_fn_c_check_func "$LINENO" "emalloc" "ac_cv_func_emalloc"
+if test "x$ac_cv_func_emalloc" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_EMALLOC 1
@@ -31791,88 +19400,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for erealloc" >&5
-echo $ECHO_N "checking for erealloc... $ECHO_C" >&6; }
-if test "${ac_cv_func_erealloc+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define erealloc to an innocuous variant, in case <limits.h> declares er=
ealloc.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define erealloc innocuous_erealloc
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char erealloc (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef erealloc
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char erealloc ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_erealloc || defined __stub___erealloc
-choke me
-#endif
-
-int
-main ()
-{
-return erealloc ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_erealloc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_erealloc=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_erealloc" >&5
-echo "${ECHO_T}$ac_cv_func_erealloc" >&6; }
-if test $ac_cv_func_erealloc =3D yes; then
+ac_fn_c_check_func "$LINENO" "erealloc" "ac_cv_func_erealloc"
+if test "x$ac_cv_func_erealloc" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_EREALLOC 1
@@ -31886,88 +19415,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for estrdup" >&5
-echo $ECHO_N "checking for estrdup... $ECHO_C" >&6; }
-if test "${ac_cv_func_estrdup+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define estrdup to an innocuous variant, in case <limits.h> declares est=
rdup.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define estrdup innocuous_estrdup
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char estrdup (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef estrdup
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char estrdup ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_estrdup || defined __stub___estrdup
-choke me
-#endif
-
-int
-main ()
-{
-return estrdup ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_estrdup=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_estrdup=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_estrdup" >&5
-echo "${ECHO_T}$ac_cv_func_estrdup" >&6; }
-if test $ac_cv_func_estrdup =3D yes; then
+ac_fn_c_check_func "$LINENO" "estrdup" "ac_cv_func_estrdup"
+if test "x$ac_cv_func_estrdup" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_ESTRDUP 1
@@ -31981,88 +19430,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for err" >&5
-echo $ECHO_N "checking for err... $ECHO_C" >&6; }
-if test "${ac_cv_func_err+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define err to an innocuous variant, in case <limits.h> declares err.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define err innocuous_err
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char err (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef err
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char err ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_err || defined __stub___err
-choke me
-#endif
-
-int
-main ()
-{
-return err ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_err=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_err=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_err" >&5
-echo "${ECHO_T}$ac_cv_func_err" >&6; }
-if test $ac_cv_func_err =3D yes; then
+ac_fn_c_check_func "$LINENO" "err" "ac_cv_func_err"
+if test "x$ac_cv_func_err" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_ERR 1
@@ -32076,88 +19445,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for errx" >&5
-echo $ECHO_N "checking for errx... $ECHO_C" >&6; }
-if test "${ac_cv_func_errx+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define errx to an innocuous variant, in case <limits.h> declares errx.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define errx innocuous_errx
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char errx (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef errx
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char errx ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_errx || defined __stub___errx
-choke me
-#endif
-
-int
-main ()
-{
-return errx ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_errx=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_errx=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_errx" >&5
-echo "${ECHO_T}$ac_cv_func_errx" >&6; }
-if test $ac_cv_func_errx =3D yes; then
+ac_fn_c_check_func "$LINENO" "errx" "ac_cv_func_errx"
+if test "x$ac_cv_func_errx" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_ERRX 1
@@ -32171,88 +19460,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for fchown" >&5
-echo $ECHO_N "checking for fchown... $ECHO_C" >&6; }
-if test "${ac_cv_func_fchown+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define fchown to an innocuous variant, in case <limits.h> declares fcho=
wn.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define fchown innocuous_fchown
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char fchown (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef fchown
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char fchown ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_fchown || defined __stub___fchown
-choke me
-#endif
-
-int
-main ()
-{
-return fchown ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_fchown=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_fchown=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_fchown" >&5
-echo "${ECHO_T}$ac_cv_func_fchown" >&6; }
-if test $ac_cv_func_fchown =3D yes; then
+ac_fn_c_check_func "$LINENO" "fchown" "ac_cv_func_fchown"
+if test "x$ac_cv_func_fchown" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_FCHOWN 1
@@ -32266,88 +19475,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for flock" >&5
-echo $ECHO_N "checking for flock... $ECHO_C" >&6; }
-if test "${ac_cv_func_flock+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define flock to an innocuous variant, in case <limits.h> declares flock.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define flock innocuous_flock
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char flock (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef flock
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char flock ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_flock || defined __stub___flock
-choke me
-#endif
-
-int
-main ()
-{
-return flock ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_flock=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_flock=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_flock" >&5
-echo "${ECHO_T}$ac_cv_func_flock" >&6; }
-if test $ac_cv_func_flock =3D yes; then
+ac_fn_c_check_func "$LINENO" "flock" "ac_cv_func_flock"
+if test "x$ac_cv_func_flock" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_FLOCK 1
@@ -32361,88 +19490,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for fnmatch" >&5
-echo $ECHO_N "checking for fnmatch... $ECHO_C" >&6; }
-if test "${ac_cv_func_fnmatch+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define fnmatch to an innocuous variant, in case <limits.h> declares fnm=
atch.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define fnmatch innocuous_fnmatch
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char fnmatch (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef fnmatch
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char fnmatch ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_fnmatch || defined __stub___fnmatch
-choke me
-#endif
-
-int
-main ()
-{
-return fnmatch ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_fnmatch=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_fnmatch=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_fnmatch" >&5
-echo "${ECHO_T}$ac_cv_func_fnmatch" >&6; }
-if test $ac_cv_func_fnmatch =3D yes; then
+ac_fn_c_check_func "$LINENO" "fnmatch" "ac_cv_func_fnmatch"
+if test "x$ac_cv_func_fnmatch" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_FNMATCH 1
@@ -32456,88 +19505,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for freehostent" >&5
-echo $ECHO_N "checking for freehostent... $ECHO_C" >&6; }
-if test "${ac_cv_func_freehostent+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define freehostent to an innocuous variant, in case <limits.h> declares=
 freehostent.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define freehostent innocuous_freehostent
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char freehostent (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef freehostent
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char freehostent ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_freehostent || defined __stub___freehostent
-choke me
-#endif
-
-int
-main ()
-{
-return freehostent ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_freehostent=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_freehostent=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_freehostent" >&5
-echo "${ECHO_T}$ac_cv_func_freehostent" >&6; }
-if test $ac_cv_func_freehostent =3D yes; then
+ac_fn_c_check_func "$LINENO" "freehostent" "ac_cv_func_freehostent"
+if test "x$ac_cv_func_freehostent" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_FREEHOSTENT 1
@@ -32551,88 +19520,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getcwd" >&5
-echo $ECHO_N "checking for getcwd... $ECHO_C" >&6; }
-if test "${ac_cv_func_getcwd+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getcwd to an innocuous variant, in case <limits.h> declares getc=
wd.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getcwd innocuous_getcwd
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getcwd (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getcwd
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getcwd ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getcwd || defined __stub___getcwd
-choke me
-#endif
-
-int
-main ()
-{
-return getcwd ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getcwd=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getcwd=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getcwd" >&5
-echo "${ECHO_T}$ac_cv_func_getcwd" >&6; }
-if test $ac_cv_func_getcwd =3D yes; then
+ac_fn_c_check_func "$LINENO" "getcwd" "ac_cv_func_getcwd"
+if test "x$ac_cv_func_getcwd" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETCWD 1
@@ -32646,88 +19535,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getdtablesize" >&5
-echo $ECHO_N "checking for getdtablesize... $ECHO_C" >&6; }
-if test "${ac_cv_func_getdtablesize+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getdtablesize to an innocuous variant, in case <limits.h> declar=
es getdtablesize.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getdtablesize innocuous_getdtablesize
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getdtablesize (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getdtablesize
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getdtablesize ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getdtablesize || defined __stub___getdtablesize
-choke me
-#endif
-
-int
-main ()
-{
-return getdtablesize ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getdtablesize=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getdtablesize=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getdtablesize" >&5
-echo "${ECHO_T}$ac_cv_func_getdtablesize" >&6; }
-if test $ac_cv_func_getdtablesize =3D yes; then
+ac_fn_c_check_func "$LINENO" "getdtablesize" "ac_cv_func_getdtablesize"
+if test "x$ac_cv_func_getdtablesize" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETDTABLESIZE 1
@@ -32741,88 +19550,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getegid" >&5
-echo $ECHO_N "checking for getegid... $ECHO_C" >&6; }
-if test "${ac_cv_func_getegid+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getegid to an innocuous variant, in case <limits.h> declares get=
egid.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getegid innocuous_getegid
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getegid (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getegid
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getegid ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getegid || defined __stub___getegid
-choke me
-#endif
-
-int
-main ()
-{
-return getegid ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getegid=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getegid=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getegid" >&5
-echo "${ECHO_T}$ac_cv_func_getegid" >&6; }
-if test $ac_cv_func_getegid =3D yes; then
+ac_fn_c_check_func "$LINENO" "getegid" "ac_cv_func_getegid"
+if test "x$ac_cv_func_getegid" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETEGID 1
@@ -32836,88 +19565,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for geteuid" >&5
-echo $ECHO_N "checking for geteuid... $ECHO_C" >&6; }
-if test "${ac_cv_func_geteuid+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define geteuid to an innocuous variant, in case <limits.h> declares get=
euid.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define geteuid innocuous_geteuid
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char geteuid (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef geteuid
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char geteuid ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_geteuid || defined __stub___geteuid
-choke me
-#endif
-
-int
-main ()
-{
-return geteuid ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_geteuid=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_geteuid=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_geteuid" >&5
-echo "${ECHO_T}$ac_cv_func_geteuid" >&6; }
-if test $ac_cv_func_geteuid =3D yes; then
+ac_fn_c_check_func "$LINENO" "geteuid" "ac_cv_func_geteuid"
+if test "x$ac_cv_func_geteuid" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETEUID 1
@@ -32931,88 +19580,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getgid" >&5
-echo $ECHO_N "checking for getgid... $ECHO_C" >&6; }
-if test "${ac_cv_func_getgid+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getgid to an innocuous variant, in case <limits.h> declares getg=
id.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getgid innocuous_getgid
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getgid (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getgid
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getgid ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getgid || defined __stub___getgid
-choke me
-#endif
-
-int
-main ()
-{
-return getgid ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getgid=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getgid=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getgid" >&5
-echo "${ECHO_T}$ac_cv_func_getgid" >&6; }
-if test $ac_cv_func_getgid =3D yes; then
+ac_fn_c_check_func "$LINENO" "getgid" "ac_cv_func_getgid"
+if test "x$ac_cv_func_getgid" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETGID 1
@@ -33026,88 +19595,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for gethostname" >&5
-echo $ECHO_N "checking for gethostname... $ECHO_C" >&6; }
-if test "${ac_cv_func_gethostname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define gethostname to an innocuous variant, in case <limits.h> declares=
 gethostname.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define gethostname innocuous_gethostname
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char gethostname (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef gethostname
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gethostname ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_gethostname || defined __stub___gethostname
-choke me
-#endif
-
-int
-main ()
-{
-return gethostname ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_gethostname=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_gethostname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostname" >&5
-echo "${ECHO_T}$ac_cv_func_gethostname" >&6; }
-if test $ac_cv_func_gethostname =3D yes; then
+ac_fn_c_check_func "$LINENO" "gethostname" "ac_cv_func_gethostname"
+if test "x$ac_cv_func_gethostname" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETHOSTNAME 1
@@ -33121,88 +19610,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getifaddrs" >&5
-echo $ECHO_N "checking for getifaddrs... $ECHO_C" >&6; }
-if test "${ac_cv_func_getifaddrs+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getifaddrs to an innocuous variant, in case <limits.h> declares =
getifaddrs.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getifaddrs innocuous_getifaddrs
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getifaddrs (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getifaddrs
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getifaddrs ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getifaddrs || defined __stub___getifaddrs
-choke me
-#endif
-
-int
-main ()
-{
-return getifaddrs ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getifaddrs=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getifaddrs=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getifaddrs" >&5
-echo "${ECHO_T}$ac_cv_func_getifaddrs" >&6; }
-if test $ac_cv_func_getifaddrs =3D yes; then
+ac_fn_c_check_func "$LINENO" "getifaddrs" "ac_cv_func_getifaddrs"
+if test "x$ac_cv_func_getifaddrs" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETIFADDRS 1
@@ -33216,88 +19625,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getipnodebyaddr" >&5
-echo $ECHO_N "checking for getipnodebyaddr... $ECHO_C" >&6; }
-if test "${ac_cv_func_getipnodebyaddr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getipnodebyaddr to an innocuous variant, in case <limits.h> decl=
ares getipnodebyaddr.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getipnodebyaddr innocuous_getipnodebyaddr
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getipnodebyaddr (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getipnodebyaddr
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getipnodebyaddr ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getipnodebyaddr || defined __stub___getipnodebyaddr
-choke me
-#endif
-
-int
-main ()
-{
-return getipnodebyaddr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getipnodebyaddr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getipnodebyaddr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getipnodebyaddr" >&5
-echo "${ECHO_T}$ac_cv_func_getipnodebyaddr" >&6; }
-if test $ac_cv_func_getipnodebyaddr =3D yes; then
+ac_fn_c_check_func "$LINENO" "getipnodebyaddr" "ac_cv_func_getipnodebyaddr"
+if test "x$ac_cv_func_getipnodebyaddr" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETIPNODEBYADDR 1
@@ -33311,88 +19640,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getipnodebyname" >&5
-echo $ECHO_N "checking for getipnodebyname... $ECHO_C" >&6; }
-if test "${ac_cv_func_getipnodebyname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getipnodebyname to an innocuous variant, in case <limits.h> decl=
ares getipnodebyname.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getipnodebyname innocuous_getipnodebyname
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getipnodebyname (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getipnodebyname
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getipnodebyname ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getipnodebyname || defined __stub___getipnodebyname
-choke me
-#endif
-
-int
-main ()
-{
-return getipnodebyname ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getipnodebyname=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getipnodebyname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getipnodebyname" >&5
-echo "${ECHO_T}$ac_cv_func_getipnodebyname" >&6; }
-if test $ac_cv_func_getipnodebyname =3D yes; then
+ac_fn_c_check_func "$LINENO" "getipnodebyname" "ac_cv_func_getipnodebyname"
+if test "x$ac_cv_func_getipnodebyname" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETIPNODEBYNAME 1
@@ -33406,88 +19655,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getopt" >&5
-echo $ECHO_N "checking for getopt... $ECHO_C" >&6; }
-if test "${ac_cv_func_getopt+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getopt to an innocuous variant, in case <limits.h> declares geto=
pt.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getopt innocuous_getopt
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getopt (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getopt
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getopt ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getopt || defined __stub___getopt
-choke me
-#endif
-
-int
-main ()
-{
-return getopt ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getopt=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getopt=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getopt" >&5
-echo "${ECHO_T}$ac_cv_func_getopt" >&6; }
-if test $ac_cv_func_getopt =3D yes; then
+ac_fn_c_check_func "$LINENO" "getopt" "ac_cv_func_getopt"
+if test "x$ac_cv_func_getopt" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETOPT 1
@@ -33501,88 +19670,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for gettimeofday" >&5
-echo $ECHO_N "checking for gettimeofday... $ECHO_C" >&6; }
-if test "${ac_cv_func_gettimeofday+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define gettimeofday to an innocuous variant, in case <limits.h> declare=
s gettimeofday.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define gettimeofday innocuous_gettimeofday
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char gettimeofday (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef gettimeofday
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gettimeofday ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_gettimeofday || defined __stub___gettimeofday
-choke me
-#endif
-
-int
-main ()
-{
-return gettimeofday ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_gettimeofday=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_gettimeofday=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_gettimeofday" >&5
-echo "${ECHO_T}$ac_cv_func_gettimeofday" >&6; }
-if test $ac_cv_func_gettimeofday =3D yes; then
+ac_fn_c_check_func "$LINENO" "gettimeofday" "ac_cv_func_gettimeofday"
+if test "x$ac_cv_func_gettimeofday" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETTIMEOFDAY 1
@@ -33596,88 +19685,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getuid" >&5
-echo $ECHO_N "checking for getuid... $ECHO_C" >&6; }
-if test "${ac_cv_func_getuid+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getuid to an innocuous variant, in case <limits.h> declares getu=
id.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getuid innocuous_getuid
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getuid (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getuid
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getuid ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getuid || defined __stub___getuid
-choke me
-#endif
-
-int
-main ()
-{
-return getuid ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getuid=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getuid=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getuid" >&5
-echo "${ECHO_T}$ac_cv_func_getuid" >&6; }
-if test $ac_cv_func_getuid =3D yes; then
+ac_fn_c_check_func "$LINENO" "getuid" "ac_cv_func_getuid"
+if test "x$ac_cv_func_getuid" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETUID 1
@@ -33691,88 +19700,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for getusershell" >&5
-echo $ECHO_N "checking for getusershell... $ECHO_C" >&6; }
-if test "${ac_cv_func_getusershell+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getusershell to an innocuous variant, in case <limits.h> declare=
s getusershell.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getusershell innocuous_getusershell
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getusershell (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getusershell
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getusershell ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getusershell || defined __stub___getusershell
-choke me
-#endif
-
-int
-main ()
-{
-return getusershell ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getusershell=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getusershell=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getusershell" >&5
-echo "${ECHO_T}$ac_cv_func_getusershell" >&6; }
-if test $ac_cv_func_getusershell =3D yes; then
+ac_fn_c_check_func "$LINENO" "getusershell" "ac_cv_func_getusershell"
+if test "x$ac_cv_func_getusershell" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_GETUSERSHELL 1
@@ -33786,88 +19715,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for initgroups" >&5
-echo $ECHO_N "checking for initgroups... $ECHO_C" >&6; }
-if test "${ac_cv_func_initgroups+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define initgroups to an innocuous variant, in case <limits.h> declares =
initgroups.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define initgroups innocuous_initgroups
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char initgroups (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef initgroups
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char initgroups ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_initgroups || defined __stub___initgroups
-choke me
-#endif
-
-int
-main ()
-{
-return initgroups ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_initgroups=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_initgroups=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_initgroups" >&5
-echo "${ECHO_T}$ac_cv_func_initgroups" >&6; }
-if test $ac_cv_func_initgroups =3D yes; then
+ac_fn_c_check_func "$LINENO" "initgroups" "ac_cv_func_initgroups"
+if test "x$ac_cv_func_initgroups" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_INITGROUPS 1
@@ -33881,88 +19730,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for innetgr" >&5
-echo $ECHO_N "checking for innetgr... $ECHO_C" >&6; }
-if test "${ac_cv_func_innetgr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define innetgr to an innocuous variant, in case <limits.h> declares inn=
etgr.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define innetgr innocuous_innetgr
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char innetgr (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef innetgr
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char innetgr ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_innetgr || defined __stub___innetgr
-choke me
-#endif
-
-int
-main ()
-{
-return innetgr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_innetgr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_innetgr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_innetgr" >&5
-echo "${ECHO_T}$ac_cv_func_innetgr" >&6; }
-if test $ac_cv_func_innetgr =3D yes; then
+ac_fn_c_check_func "$LINENO" "innetgr" "ac_cv_func_innetgr"
+if test "x$ac_cv_func_innetgr" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_INNETGR 1
@@ -33976,88 +19745,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for iruserok" >&5
-echo $ECHO_N "checking for iruserok... $ECHO_C" >&6; }
-if test "${ac_cv_func_iruserok+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define iruserok to an innocuous variant, in case <limits.h> declares ir=
userok.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define iruserok innocuous_iruserok
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char iruserok (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef iruserok
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char iruserok ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_iruserok || defined __stub___iruserok
-choke me
-#endif
-
-int
-main ()
-{
-return iruserok ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_iruserok=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_iruserok=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_iruserok" >&5
-echo "${ECHO_T}$ac_cv_func_iruserok" >&6; }
-if test $ac_cv_func_iruserok =3D yes; then
+ac_fn_c_check_func "$LINENO" "iruserok" "ac_cv_func_iruserok"
+if test "x$ac_cv_func_iruserok" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_IRUSEROK 1
@@ -34071,88 +19760,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for localtime_r" >&5
-echo $ECHO_N "checking for localtime_r... $ECHO_C" >&6; }
-if test "${ac_cv_func_localtime_r+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define localtime_r to an innocuous variant, in case <limits.h> declares=
 localtime_r.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define localtime_r innocuous_localtime_r
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char localtime_r (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef localtime_r
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char localtime_r ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_localtime_r || defined __stub___localtime_r
-choke me
-#endif
-
-int
-main ()
-{
-return localtime_r ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_localtime_r=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_localtime_r=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_localtime_r" >&5
-echo "${ECHO_T}$ac_cv_func_localtime_r" >&6; }
-if test $ac_cv_func_localtime_r =3D yes; then
+ac_fn_c_check_func "$LINENO" "localtime_r" "ac_cv_func_localtime_r"
+if test "x$ac_cv_func_localtime_r" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_LOCALTIME_R 1
@@ -34166,88 +19775,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for lstat" >&5
-echo $ECHO_N "checking for lstat... $ECHO_C" >&6; }
-if test "${ac_cv_func_lstat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define lstat to an innocuous variant, in case <limits.h> declares lstat.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define lstat innocuous_lstat
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char lstat (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef lstat
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char lstat ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_lstat || defined __stub___lstat
-choke me
-#endif
-
-int
-main ()
-{
-return lstat ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_lstat=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_lstat=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_lstat" >&5
-echo "${ECHO_T}$ac_cv_func_lstat" >&6; }
-if test $ac_cv_func_lstat =3D yes; then
+ac_fn_c_check_func "$LINENO" "lstat" "ac_cv_func_lstat"
+if test "x$ac_cv_func_lstat" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_LSTAT 1
@@ -34261,88 +19790,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for memmove" >&5
-echo $ECHO_N "checking for memmove... $ECHO_C" >&6; }
-if test "${ac_cv_func_memmove+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define memmove to an innocuous variant, in case <limits.h> declares mem=
move.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define memmove innocuous_memmove
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char memmove (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef memmove
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char memmove ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_memmove || defined __stub___memmove
-choke me
-#endif
-
-int
-main ()
-{
-return memmove ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_memmove=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_memmove=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_memmove" >&5
-echo "${ECHO_T}$ac_cv_func_memmove" >&6; }
-if test $ac_cv_func_memmove =3D yes; then
+ac_fn_c_check_func "$LINENO" "memmove" "ac_cv_func_memmove"
+if test "x$ac_cv_func_memmove" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_MEMMOVE 1
@@ -34356,88 +19805,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for mkstemp" >&5
-echo $ECHO_N "checking for mkstemp... $ECHO_C" >&6; }
-if test "${ac_cv_func_mkstemp+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define mkstemp to an innocuous variant, in case <limits.h> declares mks=
temp.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define mkstemp innocuous_mkstemp
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char mkstemp (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef mkstemp
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char mkstemp ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_mkstemp || defined __stub___mkstemp
-choke me
-#endif
-
-int
-main ()
-{
-return mkstemp ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_mkstemp=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_mkstemp=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_mkstemp" >&5
-echo "${ECHO_T}$ac_cv_func_mkstemp" >&6; }
-if test $ac_cv_func_mkstemp =3D yes; then
+ac_fn_c_check_func "$LINENO" "mkstemp" "ac_cv_func_mkstemp"
+if test "x$ac_cv_func_mkstemp" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_MKSTEMP 1
@@ -34451,88 +19820,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for putenv" >&5
-echo $ECHO_N "checking for putenv... $ECHO_C" >&6; }
-if test "${ac_cv_func_putenv+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define putenv to an innocuous variant, in case <limits.h> declares pute=
nv.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define putenv innocuous_putenv
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char putenv (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef putenv
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char putenv ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_putenv || defined __stub___putenv
-choke me
-#endif
-
-int
-main ()
-{
-return putenv ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_putenv=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_putenv=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_putenv" >&5
-echo "${ECHO_T}$ac_cv_func_putenv" >&6; }
-if test $ac_cv_func_putenv =3D yes; then
+ac_fn_c_check_func "$LINENO" "putenv" "ac_cv_func_putenv"
+if test "x$ac_cv_func_putenv" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_PUTENV 1
@@ -34546,88 +19835,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for rcmd" >&5
-echo $ECHO_N "checking for rcmd... $ECHO_C" >&6; }
-if test "${ac_cv_func_rcmd+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define rcmd to an innocuous variant, in case <limits.h> declares rcmd.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define rcmd innocuous_rcmd
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char rcmd (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef rcmd
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char rcmd ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_rcmd || defined __stub___rcmd
-choke me
-#endif
-
-int
-main ()
-{
-return rcmd ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_rcmd=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_rcmd=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_rcmd" >&5
-echo "${ECHO_T}$ac_cv_func_rcmd" >&6; }
-if test $ac_cv_func_rcmd =3D yes; then
+ac_fn_c_check_func "$LINENO" "rcmd" "ac_cv_func_rcmd"
+if test "x$ac_cv_func_rcmd" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_RCMD 1
@@ -34641,88 +19850,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for readv" >&5
-echo $ECHO_N "checking for readv... $ECHO_C" >&6; }
-if test "${ac_cv_func_readv+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define readv to an innocuous variant, in case <limits.h> declares readv.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define readv innocuous_readv
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char readv (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef readv
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char readv ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_readv || defined __stub___readv
-choke me
-#endif
-
-int
-main ()
-{
-return readv ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_readv=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_readv=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_readv" >&5
-echo "${ECHO_T}$ac_cv_func_readv" >&6; }
-if test $ac_cv_func_readv =3D yes; then
+ac_fn_c_check_func "$LINENO" "readv" "ac_cv_func_readv"
+if test "x$ac_cv_func_readv" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_READV 1
@@ -34736,88 +19865,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for recvmsg" >&5
-echo $ECHO_N "checking for recvmsg... $ECHO_C" >&6; }
-if test "${ac_cv_func_recvmsg+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define recvmsg to an innocuous variant, in case <limits.h> declares rec=
vmsg.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define recvmsg innocuous_recvmsg
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char recvmsg (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef recvmsg
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char recvmsg ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_recvmsg || defined __stub___recvmsg
-choke me
-#endif
-
-int
-main ()
-{
-return recvmsg ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_recvmsg=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_recvmsg=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_recvmsg" >&5
-echo "${ECHO_T}$ac_cv_func_recvmsg" >&6; }
-if test $ac_cv_func_recvmsg =3D yes; then
+ac_fn_c_check_func "$LINENO" "recvmsg" "ac_cv_func_recvmsg"
+if test "x$ac_cv_func_recvmsg" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_RECVMSG 1
@@ -34831,88 +19880,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for sendmsg" >&5
-echo $ECHO_N "checking for sendmsg... $ECHO_C" >&6; }
-if test "${ac_cv_func_sendmsg+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define sendmsg to an innocuous variant, in case <limits.h> declares sen=
dmsg.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define sendmsg innocuous_sendmsg
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char sendmsg (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef sendmsg
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char sendmsg ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_sendmsg || defined __stub___sendmsg
-choke me
-#endif
-
-int
-main ()
-{
-return sendmsg ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_sendmsg=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_sendmsg=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_sendmsg" >&5
-echo "${ECHO_T}$ac_cv_func_sendmsg" >&6; }
-if test $ac_cv_func_sendmsg =3D yes; then
+ac_fn_c_check_func "$LINENO" "sendmsg" "ac_cv_func_sendmsg"
+if test "x$ac_cv_func_sendmsg" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SENDMSG 1
@@ -34926,88 +19895,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for setegid" >&5
-echo $ECHO_N "checking for setegid... $ECHO_C" >&6; }
-if test "${ac_cv_func_setegid+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define setegid to an innocuous variant, in case <limits.h> declares set=
egid.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define setegid innocuous_setegid
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char setegid (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef setegid
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char setegid ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_setegid || defined __stub___setegid
-choke me
-#endif
-
-int
-main ()
-{
-return setegid ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_setegid=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_setegid=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_setegid" >&5
-echo "${ECHO_T}$ac_cv_func_setegid" >&6; }
-if test $ac_cv_func_setegid =3D yes; then
+ac_fn_c_check_func "$LINENO" "setegid" "ac_cv_func_setegid"
+if test "x$ac_cv_func_setegid" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SETEGID 1
@@ -35021,88 +19910,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for setenv" >&5
-echo $ECHO_N "checking for setenv... $ECHO_C" >&6; }
-if test "${ac_cv_func_setenv+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define setenv to an innocuous variant, in case <limits.h> declares sete=
nv.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define setenv innocuous_setenv
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char setenv (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef setenv
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char setenv ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_setenv || defined __stub___setenv
-choke me
-#endif
-
-int
-main ()
-{
-return setenv ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_setenv=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_setenv=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_setenv" >&5
-echo "${ECHO_T}$ac_cv_func_setenv" >&6; }
-if test $ac_cv_func_setenv =3D yes; then
+ac_fn_c_check_func "$LINENO" "setenv" "ac_cv_func_setenv"
+if test "x$ac_cv_func_setenv" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SETENV 1
@@ -35116,88 +19925,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for seteuid" >&5
-echo $ECHO_N "checking for seteuid... $ECHO_C" >&6; }
-if test "${ac_cv_func_seteuid+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define seteuid to an innocuous variant, in case <limits.h> declares set=
euid.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define seteuid innocuous_seteuid
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char seteuid (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef seteuid
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char seteuid ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_seteuid || defined __stub___seteuid
-choke me
-#endif
-
-int
-main ()
-{
-return seteuid ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_seteuid=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_seteuid=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_seteuid" >&5
-echo "${ECHO_T}$ac_cv_func_seteuid" >&6; }
-if test $ac_cv_func_seteuid =3D yes; then
+ac_fn_c_check_func "$LINENO" "seteuid" "ac_cv_func_seteuid"
+if test "x$ac_cv_func_seteuid" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SETEUID 1
@@ -35211,88 +19940,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strcasecmp" >&5
-echo $ECHO_N "checking for strcasecmp... $ECHO_C" >&6; }
-if test "${ac_cv_func_strcasecmp+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strcasecmp to an innocuous variant, in case <limits.h> declares =
strcasecmp.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strcasecmp innocuous_strcasecmp
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strcasecmp (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strcasecmp
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strcasecmp ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strcasecmp || defined __stub___strcasecmp
-choke me
-#endif
-
-int
-main ()
-{
-return strcasecmp ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strcasecmp=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strcasecmp=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strcasecmp" >&5
-echo "${ECHO_T}$ac_cv_func_strcasecmp" >&6; }
-if test $ac_cv_func_strcasecmp =3D yes; then
+ac_fn_c_check_func "$LINENO" "strcasecmp" "ac_cv_func_strcasecmp"
+if test "x$ac_cv_func_strcasecmp" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRCASECMP 1
@@ -35306,88 +19955,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strdup" >&5
-echo $ECHO_N "checking for strdup... $ECHO_C" >&6; }
-if test "${ac_cv_func_strdup+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strdup to an innocuous variant, in case <limits.h> declares strd=
up.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strdup innocuous_strdup
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strdup (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strdup
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strdup ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strdup || defined __stub___strdup
-choke me
-#endif
-
-int
-main ()
-{
-return strdup ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strdup=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strdup=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strdup" >&5
-echo "${ECHO_T}$ac_cv_func_strdup" >&6; }
-if test $ac_cv_func_strdup =3D yes; then
+ac_fn_c_check_func "$LINENO" "strdup" "ac_cv_func_strdup"
+if test "x$ac_cv_func_strdup" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRDUP 1
@@ -35401,88 +19970,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strerror" >&5
-echo $ECHO_N "checking for strerror... $ECHO_C" >&6; }
-if test "${ac_cv_func_strerror+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strerror to an innocuous variant, in case <limits.h> declares st=
rerror.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strerror innocuous_strerror
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strerror (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strerror
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strerror ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strerror || defined __stub___strerror
-choke me
-#endif
-
-int
-main ()
-{
-return strerror ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strerror=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strerror=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strerror" >&5
-echo "${ECHO_T}$ac_cv_func_strerror" >&6; }
-if test $ac_cv_func_strerror =3D yes; then
+ac_fn_c_check_func "$LINENO" "strerror" "ac_cv_func_strerror"
+if test "x$ac_cv_func_strerror" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRERROR 1
@@ -35496,88 +19985,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strftime" >&5
-echo $ECHO_N "checking for strftime... $ECHO_C" >&6; }
-if test "${ac_cv_func_strftime+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strftime to an innocuous variant, in case <limits.h> declares st=
rftime.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strftime innocuous_strftime
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strftime (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strftime
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strftime ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strftime || defined __stub___strftime
-choke me
-#endif
-
-int
-main ()
-{
-return strftime ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strftime=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strftime=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strftime" >&5
-echo "${ECHO_T}$ac_cv_func_strftime" >&6; }
-if test $ac_cv_func_strftime =3D yes; then
+ac_fn_c_check_func "$LINENO" "strftime" "ac_cv_func_strftime"
+if test "x$ac_cv_func_strftime" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRFTIME 1
@@ -35591,88 +20000,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strlcat" >&5
-echo $ECHO_N "checking for strlcat... $ECHO_C" >&6; }
-if test "${ac_cv_func_strlcat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strlcat to an innocuous variant, in case <limits.h> declares str=
lcat.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strlcat innocuous_strlcat
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strlcat (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strlcat
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strlcat ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strlcat || defined __stub___strlcat
-choke me
-#endif
-
-int
-main ()
-{
-return strlcat ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strlcat=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strlcat=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strlcat" >&5
-echo "${ECHO_T}$ac_cv_func_strlcat" >&6; }
-if test $ac_cv_func_strlcat =3D yes; then
+ac_fn_c_check_func "$LINENO" "strlcat" "ac_cv_func_strlcat"
+if test "x$ac_cv_func_strlcat" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRLCAT 1
@@ -35686,88 +20015,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strlcpy" >&5
-echo $ECHO_N "checking for strlcpy... $ECHO_C" >&6; }
-if test "${ac_cv_func_strlcpy+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strlcpy to an innocuous variant, in case <limits.h> declares str=
lcpy.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strlcpy innocuous_strlcpy
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strlcpy (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strlcpy
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strlcpy ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strlcpy || defined __stub___strlcpy
-choke me
-#endif
-
-int
-main ()
-{
-return strlcpy ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strlcpy=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strlcpy=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strlcpy" >&5
-echo "${ECHO_T}$ac_cv_func_strlcpy" >&6; }
-if test $ac_cv_func_strlcpy =3D yes; then
+ac_fn_c_check_func "$LINENO" "strlcpy" "ac_cv_func_strlcpy"
+if test "x$ac_cv_func_strlcpy" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRLCPY 1
@@ -35781,88 +20030,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strlwr" >&5
-echo $ECHO_N "checking for strlwr... $ECHO_C" >&6; }
-if test "${ac_cv_func_strlwr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strlwr to an innocuous variant, in case <limits.h> declares strl=
wr.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strlwr innocuous_strlwr
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strlwr (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strlwr
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strlwr ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strlwr || defined __stub___strlwr
-choke me
-#endif
-
-int
-main ()
-{
-return strlwr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strlwr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strlwr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strlwr" >&5
-echo "${ECHO_T}$ac_cv_func_strlwr" >&6; }
-if test $ac_cv_func_strlwr =3D yes; then
+ac_fn_c_check_func "$LINENO" "strlwr" "ac_cv_func_strlwr"
+if test "x$ac_cv_func_strlwr" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRLWR 1
@@ -35876,88 +20045,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strncasecmp" >&5
-echo $ECHO_N "checking for strncasecmp... $ECHO_C" >&6; }
-if test "${ac_cv_func_strncasecmp+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strncasecmp to an innocuous variant, in case <limits.h> declares=
 strncasecmp.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strncasecmp innocuous_strncasecmp
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strncasecmp (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strncasecmp
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strncasecmp ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strncasecmp || defined __stub___strncasecmp
-choke me
-#endif
-
-int
-main ()
-{
-return strncasecmp ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strncasecmp=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strncasecmp=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strncasecmp" >&5
-echo "${ECHO_T}$ac_cv_func_strncasecmp" >&6; }
-if test $ac_cv_func_strncasecmp =3D yes; then
+ac_fn_c_check_func "$LINENO" "strncasecmp" "ac_cv_func_strncasecmp"
+if test "x$ac_cv_func_strncasecmp" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRNCASECMP 1
@@ -35971,88 +20060,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strndup" >&5
-echo $ECHO_N "checking for strndup... $ECHO_C" >&6; }
-if test "${ac_cv_func_strndup+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strndup to an innocuous variant, in case <limits.h> declares str=
ndup.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strndup innocuous_strndup
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strndup (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strndup
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strndup ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strndup || defined __stub___strndup
-choke me
-#endif
-
-int
-main ()
-{
-return strndup ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strndup=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strndup=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strndup" >&5
-echo "${ECHO_T}$ac_cv_func_strndup" >&6; }
-if test $ac_cv_func_strndup =3D yes; then
+ac_fn_c_check_func "$LINENO" "strndup" "ac_cv_func_strndup"
+if test "x$ac_cv_func_strndup" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRNDUP 1
@@ -36066,88 +20075,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strnlen" >&5
-echo $ECHO_N "checking for strnlen... $ECHO_C" >&6; }
-if test "${ac_cv_func_strnlen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strnlen to an innocuous variant, in case <limits.h> declares str=
nlen.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strnlen innocuous_strnlen
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strnlen (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strnlen
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strnlen ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strnlen || defined __stub___strnlen
-choke me
-#endif
-
-int
-main ()
-{
-return strnlen ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strnlen=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strnlen=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strnlen" >&5
-echo "${ECHO_T}$ac_cv_func_strnlen" >&6; }
-if test $ac_cv_func_strnlen =3D yes; then
+ac_fn_c_check_func "$LINENO" "strnlen" "ac_cv_func_strnlen"
+if test "x$ac_cv_func_strnlen" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRNLEN 1
@@ -36161,88 +20090,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strptime" >&5
-echo $ECHO_N "checking for strptime... $ECHO_C" >&6; }
-if test "${ac_cv_func_strptime+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strptime to an innocuous variant, in case <limits.h> declares st=
rptime.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strptime innocuous_strptime
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strptime (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strptime
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strptime ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strptime || defined __stub___strptime
-choke me
-#endif
-
-int
-main ()
-{
-return strptime ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strptime=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strptime=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strptime" >&5
-echo "${ECHO_T}$ac_cv_func_strptime" >&6; }
-if test $ac_cv_func_strptime =3D yes; then
+ac_fn_c_check_func "$LINENO" "strptime" "ac_cv_func_strptime"
+if test "x$ac_cv_func_strptime" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRPTIME 1
@@ -36256,88 +20105,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strsep" >&5
-echo $ECHO_N "checking for strsep... $ECHO_C" >&6; }
-if test "${ac_cv_func_strsep+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strsep to an innocuous variant, in case <limits.h> declares strs=
ep.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strsep innocuous_strsep
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strsep (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strsep
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strsep ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strsep || defined __stub___strsep
-choke me
-#endif
-
-int
-main ()
-{
-return strsep ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strsep=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strsep=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strsep" >&5
-echo "${ECHO_T}$ac_cv_func_strsep" >&6; }
-if test $ac_cv_func_strsep =3D yes; then
+ac_fn_c_check_func "$LINENO" "strsep" "ac_cv_func_strsep"
+if test "x$ac_cv_func_strsep" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRSEP 1
@@ -36351,88 +20120,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strsep_copy" >&5
-echo $ECHO_N "checking for strsep_copy... $ECHO_C" >&6; }
-if test "${ac_cv_func_strsep_copy+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strsep_copy to an innocuous variant, in case <limits.h> declares=
 strsep_copy.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strsep_copy innocuous_strsep_copy
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strsep_copy (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strsep_copy
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strsep_copy ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strsep_copy || defined __stub___strsep_copy
-choke me
-#endif
-
-int
-main ()
-{
-return strsep_copy ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strsep_copy=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strsep_copy=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strsep_copy" >&5
-echo "${ECHO_T}$ac_cv_func_strsep_copy" >&6; }
-if test $ac_cv_func_strsep_copy =3D yes; then
+ac_fn_c_check_func "$LINENO" "strsep_copy" "ac_cv_func_strsep_copy"
+if test "x$ac_cv_func_strsep_copy" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRSEP_COPY 1
@@ -36446,88 +20135,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strtok_r" >&5
-echo $ECHO_N "checking for strtok_r... $ECHO_C" >&6; }
-if test "${ac_cv_func_strtok_r+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strtok_r to an innocuous variant, in case <limits.h> declares st=
rtok_r.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strtok_r innocuous_strtok_r
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strtok_r (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strtok_r
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strtok_r ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strtok_r || defined __stub___strtok_r
-choke me
-#endif
-
-int
-main ()
-{
-return strtok_r ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strtok_r=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strtok_r=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strtok_r" >&5
-echo "${ECHO_T}$ac_cv_func_strtok_r" >&6; }
-if test $ac_cv_func_strtok_r =3D yes; then
+ac_fn_c_check_func "$LINENO" "strtok_r" "ac_cv_func_strtok_r"
+if test "x$ac_cv_func_strtok_r" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRTOK_R 1
@@ -36541,88 +20150,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for strupr" >&5
-echo $ECHO_N "checking for strupr... $ECHO_C" >&6; }
-if test "${ac_cv_func_strupr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define strupr to an innocuous variant, in case <limits.h> declares stru=
pr.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define strupr innocuous_strupr
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char strupr (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef strupr
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char strupr ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_strupr || defined __stub___strupr
-choke me
-#endif
-
-int
-main ()
-{
-return strupr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_strupr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_strupr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strupr" >&5
-echo "${ECHO_T}$ac_cv_func_strupr" >&6; }
-if test $ac_cv_func_strupr =3D yes; then
+ac_fn_c_check_func "$LINENO" "strupr" "ac_cv_func_strupr"
+if test "x$ac_cv_func_strupr" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRUPR 1
@@ -36636,88 +20165,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for swab" >&5
-echo $ECHO_N "checking for swab... $ECHO_C" >&6; }
-if test "${ac_cv_func_swab+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define swab to an innocuous variant, in case <limits.h> declares swab.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define swab innocuous_swab
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char swab (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef swab
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char swab ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_swab || defined __stub___swab
-choke me
-#endif
-
-int
-main ()
-{
-return swab ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_swab=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_swab=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_swab" >&5
-echo "${ECHO_T}$ac_cv_func_swab" >&6; }
-if test $ac_cv_func_swab =3D yes; then
+ac_fn_c_check_func "$LINENO" "swab" "ac_cv_func_swab"
+if test "x$ac_cv_func_swab" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SWAB 1
@@ -36731,88 +20180,23 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for timegm" >&5
-echo $ECHO_N "checking for timegm... $ECHO_C" >&6; }
-if test "${ac_cv_func_timegm+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define timegm to an innocuous variant, in case <limits.h> declares time=
gm.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define timegm innocuous_timegm
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char timegm (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef timegm
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char timegm ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_timegm || defined __stub___timegm
-choke me
-#endif
-
-int
-main ()
-{
-return timegm ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_timegm=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_timegm=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_timegm" >&5
-echo "${ECHO_T}$ac_cv_func_timegm" >&6; }
-if test $ac_cv_func_timegm =3D yes; then
+ac_fn_c_check_func "$LINENO" "tsearch" "ac_cv_func_tsearch"
+if test "x$ac_cv_func_tsearch" =3D x""yes; then :
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_TSEARCH 1
+_ACEOF
+
+else
+  case " $LIBOBJS " in
+  *" tsearch.$ac_objext "* ) ;;
+  *) LIBOBJS=3D"$LIBOBJS tsearch.$ac_objext"
+ ;;
+esac
+
+fi
+ac_fn_c_check_func "$LINENO" "timegm" "ac_cv_func_timegm"
+if test "x$ac_cv_func_timegm" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_TIMEGM 1
@@ -36826,88 +20210,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for unsetenv" >&5
-echo $ECHO_N "checking for unsetenv... $ECHO_C" >&6; }
-if test "${ac_cv_func_unsetenv+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define unsetenv to an innocuous variant, in case <limits.h> declares un=
setenv.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define unsetenv innocuous_unsetenv
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char unsetenv (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef unsetenv
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char unsetenv ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_unsetenv || defined __stub___unsetenv
-choke me
-#endif
-
-int
-main ()
-{
-return unsetenv ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_unsetenv=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_unsetenv=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_unsetenv" >&5
-echo "${ECHO_T}$ac_cv_func_unsetenv" >&6; }
-if test $ac_cv_func_unsetenv =3D yes; then
+ac_fn_c_check_func "$LINENO" "unsetenv" "ac_cv_func_unsetenv"
+if test "x$ac_cv_func_unsetenv" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_UNSETENV 1
@@ -36921,88 +20225,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for verr" >&5
-echo $ECHO_N "checking for verr... $ECHO_C" >&6; }
-if test "${ac_cv_func_verr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define verr to an innocuous variant, in case <limits.h> declares verr.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define verr innocuous_verr
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char verr (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef verr
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char verr ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_verr || defined __stub___verr
-choke me
-#endif
-
-int
-main ()
-{
-return verr ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_verr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_verr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_verr" >&5
-echo "${ECHO_T}$ac_cv_func_verr" >&6; }
-if test $ac_cv_func_verr =3D yes; then
+ac_fn_c_check_func "$LINENO" "verr" "ac_cv_func_verr"
+if test "x$ac_cv_func_verr" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_VERR 1
@@ -37016,88 +20240,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for verrx" >&5
-echo $ECHO_N "checking for verrx... $ECHO_C" >&6; }
-if test "${ac_cv_func_verrx+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define verrx to an innocuous variant, in case <limits.h> declares verrx.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define verrx innocuous_verrx
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char verrx (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef verrx
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char verrx ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_verrx || defined __stub___verrx
-choke me
-#endif
-
-int
-main ()
-{
-return verrx ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_verrx=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_verrx=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_verrx" >&5
-echo "${ECHO_T}$ac_cv_func_verrx" >&6; }
-if test $ac_cv_func_verrx =3D yes; then
+ac_fn_c_check_func "$LINENO" "verrx" "ac_cv_func_verrx"
+if test "x$ac_cv_func_verrx" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_VERRX 1
@@ -37111,88 +20255,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for vsyslog" >&5
-echo $ECHO_N "checking for vsyslog... $ECHO_C" >&6; }
-if test "${ac_cv_func_vsyslog+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define vsyslog to an innocuous variant, in case <limits.h> declares vsy=
slog.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define vsyslog innocuous_vsyslog
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char vsyslog (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef vsyslog
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char vsyslog ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_vsyslog || defined __stub___vsyslog
-choke me
-#endif
-
-int
-main ()
-{
-return vsyslog ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_vsyslog=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_vsyslog=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vsyslog" >&5
-echo "${ECHO_T}$ac_cv_func_vsyslog" >&6; }
-if test $ac_cv_func_vsyslog =3D yes; then
+ac_fn_c_check_func "$LINENO" "vsyslog" "ac_cv_func_vsyslog"
+if test "x$ac_cv_func_vsyslog" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_VSYSLOG 1
@@ -37206,88 +20270,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for vwarn" >&5
-echo $ECHO_N "checking for vwarn... $ECHO_C" >&6; }
-if test "${ac_cv_func_vwarn+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define vwarn to an innocuous variant, in case <limits.h> declares vwarn.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define vwarn innocuous_vwarn
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char vwarn (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef vwarn
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char vwarn ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_vwarn || defined __stub___vwarn
-choke me
-#endif
-
-int
-main ()
-{
-return vwarn ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_vwarn=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_vwarn=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vwarn" >&5
-echo "${ECHO_T}$ac_cv_func_vwarn" >&6; }
-if test $ac_cv_func_vwarn =3D yes; then
+ac_fn_c_check_func "$LINENO" "vwarn" "ac_cv_func_vwarn"
+if test "x$ac_cv_func_vwarn" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_VWARN 1
@@ -37301,88 +20285,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for vwarnx" >&5
-echo $ECHO_N "checking for vwarnx... $ECHO_C" >&6; }
-if test "${ac_cv_func_vwarnx+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define vwarnx to an innocuous variant, in case <limits.h> declares vwar=
nx.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define vwarnx innocuous_vwarnx
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char vwarnx (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef vwarnx
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char vwarnx ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_vwarnx || defined __stub___vwarnx
-choke me
-#endif
-
-int
-main ()
-{
-return vwarnx ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_vwarnx=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_vwarnx=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vwarnx" >&5
-echo "${ECHO_T}$ac_cv_func_vwarnx" >&6; }
-if test $ac_cv_func_vwarnx =3D yes; then
+ac_fn_c_check_func "$LINENO" "vwarnx" "ac_cv_func_vwarnx"
+if test "x$ac_cv_func_vwarnx" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_VWARNX 1
@@ -37396,88 +20300,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for warn" >&5
-echo $ECHO_N "checking for warn... $ECHO_C" >&6; }
-if test "${ac_cv_func_warn+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define warn to an innocuous variant, in case <limits.h> declares warn.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define warn innocuous_warn
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char warn (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef warn
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char warn ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_warn || defined __stub___warn
-choke me
-#endif
-
-int
-main ()
-{
-return warn ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_warn=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_warn=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_warn" >&5
-echo "${ECHO_T}$ac_cv_func_warn" >&6; }
-if test $ac_cv_func_warn =3D yes; then
+ac_fn_c_check_func "$LINENO" "warn" "ac_cv_func_warn"
+if test "x$ac_cv_func_warn" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_WARN 1
@@ -37491,88 +20315,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for warnx" >&5
-echo $ECHO_N "checking for warnx... $ECHO_C" >&6; }
-if test "${ac_cv_func_warnx+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define warnx to an innocuous variant, in case <limits.h> declares warnx.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define warnx innocuous_warnx
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char warnx (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef warnx
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char warnx ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_warnx || defined __stub___warnx
-choke me
-#endif
-
-int
-main ()
-{
-return warnx ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_warnx=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_warnx=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_warnx" >&5
-echo "${ECHO_T}$ac_cv_func_warnx" >&6; }
-if test $ac_cv_func_warnx =3D yes; then
+ac_fn_c_check_func "$LINENO" "warnx" "ac_cv_func_warnx"
+if test "x$ac_cv_func_warnx" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_WARNX 1
@@ -37586,88 +20330,8 @@
 esac
=20
 fi
-{ echo "$as_me:$LINENO: checking for writev" >&5
-echo $ECHO_N "checking for writev... $ECHO_C" >&6; }
-if test "${ac_cv_func_writev+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define writev to an innocuous variant, in case <limits.h> declares writ=
ev.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define writev innocuous_writev
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char writev (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef writev
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char writev ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_writev || defined __stub___writev
-choke me
-#endif
-
-int
-main ()
-{
-return writev ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_writev=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_writev=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_writev" >&5
-echo "${ECHO_T}$ac_cv_func_writev" >&6; }
-if test $ac_cv_func_writev =3D yes; then
+ac_fn_c_check_func "$LINENO" "writev" "ac_cv_func_writev"
+if test "x$ac_cv_func_writev" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_WRITEV 1
@@ -37694,16 +20358,12 @@
=20
=20
 if test "$ac_cv_func_strndup+set" !=3D set -o "$ac_cv_func_strndup" =3D ye=
s; then
-{ echo "$as_me:$LINENO: checking if strndup needs a prototype" >&5
-echo $ECHO_N "checking if strndup needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_strndup_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strndup needs a proto=
type" >&5
+$as_echo_n "checking if strndup needs a prototype... " >&6; }
+if test "${ac_cv_func_strndup_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <string.h>
 struct foo { int foo; } xx;
@@ -37716,55 +20376,29 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_strndup_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_strndup_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strndup_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_strndup_noproto" >&6; }
+  eval "ac_cv_func_strndup_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strndup_nopro=
to" >&5
+$as_echo "$ac_cv_func_strndup_noproto" >&6; }
 if test "$ac_cv_func_strndup_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_STRNDUP_PROTO 1
-_ACEOF
+$as_echo "#define NEED_STRNDUP_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
 if test "$ac_cv_func_strsep+set" !=3D set -o "$ac_cv_func_strsep" =3D yes;=
 then
-{ echo "$as_me:$LINENO: checking if strsep needs a prototype" >&5
-echo $ECHO_N "checking if strsep needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_strsep_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strsep needs a protot=
ype" >&5
+$as_echo_n "checking if strsep needs a prototype... " >&6; }
+if test "${ac_cv_func_strsep_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <string.h>
 struct foo { int foo; } xx;
@@ -37777,55 +20411,29 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_strsep_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_strsep_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strsep_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_strsep_noproto" >&6; }
+  eval "ac_cv_func_strsep_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strsep_noprot=
o" >&5
+$as_echo "$ac_cv_func_strsep_noproto" >&6; }
 if test "$ac_cv_func_strsep_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_STRSEP_PROTO 1
-_ACEOF
+$as_echo "#define NEED_STRSEP_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
 if test "$ac_cv_func_strtok_r+set" !=3D set -o "$ac_cv_func_strtok_r" =3D =
yes; then
-{ echo "$as_me:$LINENO: checking if strtok_r needs a prototype" >&5
-echo $ECHO_N "checking if strtok_r needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_strtok_r_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strtok_r needs a prot=
otype" >&5
+$as_echo_n "checking if strtok_r needs a prototype... " >&6; }
+if test "${ac_cv_func_strtok_r_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <string.h>
 struct foo { int foo; } xx;
@@ -37838,40 +20446,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_strtok_r_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_strtok_r_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strtok_r_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_strtok_r_noproto" >&6; }
+  eval "ac_cv_func_strtok_r_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strtok_r_nopr=
oto" >&5
+$as_echo "$ac_cv_func_strtok_r_noproto" >&6; }
 if test "$ac_cv_func_strtok_r_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_STRTOK_R_PROTO 1
-_ACEOF
+$as_echo "#define NEED_STRTOK_R_PROTO 1" >>confdefs.h
=20
 fi
 fi
@@ -37879,16 +20465,12 @@
=20
=20
 if test "$ac_cv_func_strsvis+set" !=3D set -o "$ac_cv_func_strsvis" =3D ye=
s; then
-{ echo "$as_me:$LINENO: checking if strsvis needs a prototype" >&5
-echo $ECHO_N "checking if strsvis needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_strsvis_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strsvis needs a proto=
type" >&5
+$as_echo_n "checking if strsvis needs a prototype... " >&6; }
+if test "${ac_cv_func_strsvis_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_VIS_H
 #include <vis.h>
@@ -37903,375 +20485,256 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_strsvis_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_strsvis_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strsvis_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_strsvis_noproto" >&6; }
+  eval "ac_cv_func_strsvis_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strsvis_nopro=
to" >&5
+$as_echo "$ac_cv_func_strsvis_noproto" >&6; }
 if test "$ac_cv_func_strsvis_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_STRSVIS_PROTO 1
-_ACEOF
-
-fi
-fi
-
-if test "$ac_cv_func_strunvis+set" !=3D set -o "$ac_cv_func_strunvis" =3D =
yes; then
-{ echo "$as_me:$LINENO: checking if strunvis needs a prototype" >&5
-echo $ECHO_N "checking if strunvis needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_strunvis_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define NEED_STRSVIS_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+if test "$ac_cv_func_strsvisx+set" !=3D set -o "$ac_cv_func_strsvisx" =3D =
yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strsvisx needs a prot=
otype" >&5
+$as_echo_n "checking if strsvisx needs a prototype... " >&6; }
+if test "${ac_cv_func_strsvisx_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_VIS_H
 #include <vis.h>
 #endif
 struct foo { int foo; } xx;
-extern int strunvis (struct foo*);
-int
-main ()
-{
-strunvis(&xx)
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "ac_cv_func_strunvis_noproto=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_strunvis_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strunvis_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_strunvis_noproto" >&6; }
-if test "$ac_cv_func_strunvis_noproto" =3D yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define NEED_STRUNVIS_PROTO 1
-_ACEOF
-
-fi
-fi
-
-if test "$ac_cv_func_strvis+set" !=3D set -o "$ac_cv_func_strvis" =3D yes;=
 then
-{ echo "$as_me:$LINENO: checking if strvis needs a prototype" >&5
-echo $ECHO_N "checking if strvis needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_strvis_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+extern int strsvisx (struct foo*);
+int
+main ()
+{
+strsvisx(&xx)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "ac_cv_func_strsvisx_noproto=3Dyes"
+else
+  eval "ac_cv_func_strsvisx_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strsvisx_nopr=
oto" >&5
+$as_echo "$ac_cv_func_strsvisx_noproto" >&6; }
+if test "$ac_cv_func_strsvisx_noproto" =3D yes; then
+
+$as_echo "#define NEED_STRSVISX_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+if test "$ac_cv_func_strunvis+set" !=3D set -o "$ac_cv_func_strunvis" =3D =
yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strunvis needs a prot=
otype" >&5
+$as_echo_n "checking if strunvis needs a prototype... " >&6; }
+if test "${ac_cv_func_strunvis_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_VIS_H
 #include <vis.h>
 #endif
 struct foo { int foo; } xx;
-extern int strvis (struct foo*);
-int
-main ()
-{
-strvis(&xx)
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "ac_cv_func_strvis_noproto=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_strvis_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strvis_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_strvis_noproto" >&6; }
-if test "$ac_cv_func_strvis_noproto" =3D yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define NEED_STRVIS_PROTO 1
-_ACEOF
-
-fi
-fi
-
-if test "$ac_cv_func_strvisx+set" !=3D set -o "$ac_cv_func_strvisx" =3D ye=
s; then
-{ echo "$as_me:$LINENO: checking if strvisx needs a prototype" >&5
-echo $ECHO_N "checking if strvisx needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_strvisx_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+extern int strunvis (struct foo*);
+int
+main ()
+{
+strunvis(&xx)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "ac_cv_func_strunvis_noproto=3Dyes"
+else
+  eval "ac_cv_func_strunvis_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strunvis_nopr=
oto" >&5
+$as_echo "$ac_cv_func_strunvis_noproto" >&6; }
+if test "$ac_cv_func_strunvis_noproto" =3D yes; then
+
+$as_echo "#define NEED_STRUNVIS_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+if test "$ac_cv_func_strvis+set" !=3D set -o "$ac_cv_func_strvis" =3D yes;=
 then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strvis needs a protot=
ype" >&5
+$as_echo_n "checking if strvis needs a prototype... " >&6; }
+if test "${ac_cv_func_strvis_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_VIS_H
 #include <vis.h>
 #endif
 struct foo { int foo; } xx;
-extern int strvisx (struct foo*);
-int
-main ()
-{
-strvisx(&xx)
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "ac_cv_func_strvisx_noproto=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_strvisx_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_strvisx_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_strvisx_noproto" >&6; }
-if test "$ac_cv_func_strvisx_noproto" =3D yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define NEED_STRVISX_PROTO 1
-_ACEOF
-
-fi
-fi
-
-if test "$ac_cv_func_svis+set" !=3D set -o "$ac_cv_func_svis" =3D yes; then
-{ echo "$as_me:$LINENO: checking if svis needs a prototype" >&5
-echo $ECHO_N "checking if svis needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_svis_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+extern int strvis (struct foo*);
+int
+main ()
+{
+strvis(&xx)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "ac_cv_func_strvis_noproto=3Dyes"
+else
+  eval "ac_cv_func_strvis_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strvis_noprot=
o" >&5
+$as_echo "$ac_cv_func_strvis_noproto" >&6; }
+if test "$ac_cv_func_strvis_noproto" =3D yes; then
+
+$as_echo "#define NEED_STRVIS_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+if test "$ac_cv_func_strvisx+set" !=3D set -o "$ac_cv_func_strvisx" =3D ye=
s; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strvisx needs a proto=
type" >&5
+$as_echo_n "checking if strvisx needs a prototype... " >&6; }
+if test "${ac_cv_func_strvisx_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_VIS_H
 #include <vis.h>
 #endif
 struct foo { int foo; } xx;
-extern int svis (struct foo*);
-int
-main ()
-{
-svis(&xx)
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "ac_cv_func_svis_noproto=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_svis_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_svis_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_svis_noproto" >&6; }
-if test "$ac_cv_func_svis_noproto" =3D yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define NEED_SVIS_PROTO 1
-_ACEOF
-
-fi
-fi
-
-if test "$ac_cv_func_unvis+set" !=3D set -o "$ac_cv_func_unvis" =3D yes; t=
hen
-{ echo "$as_me:$LINENO: checking if unvis needs a prototype" >&5
-echo $ECHO_N "checking if unvis needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_unvis_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+extern int strvisx (struct foo*);
+int
+main ()
+{
+strvisx(&xx)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "ac_cv_func_strvisx_noproto=3Dyes"
+else
+  eval "ac_cv_func_strvisx_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strvisx_nopro=
to" >&5
+$as_echo "$ac_cv_func_strvisx_noproto" >&6; }
+if test "$ac_cv_func_strvisx_noproto" =3D yes; then
+
+$as_echo "#define NEED_STRVISX_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+if test "$ac_cv_func_svis+set" !=3D set -o "$ac_cv_func_svis" =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if svis needs a prototyp=
e" >&5
+$as_echo_n "checking if svis needs a prototype... " >&6; }
+if test "${ac_cv_func_svis_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_VIS_H
 #include <vis.h>
 #endif
 struct foo { int foo; } xx;
-extern int unvis (struct foo*);
-int
-main ()
-{
-unvis(&xx)
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "ac_cv_func_unvis_noproto=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_unvis_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_unvis_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_unvis_noproto" >&6; }
-if test "$ac_cv_func_unvis_noproto" =3D yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define NEED_UNVIS_PROTO 1
-_ACEOF
-
-fi
-fi
-
-if test "$ac_cv_func_vis+set" !=3D set -o "$ac_cv_func_vis" =3D yes; then
-{ echo "$as_me:$LINENO: checking if vis needs a prototype" >&5
-echo $ECHO_N "checking if vis needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_vis_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+extern int svis (struct foo*);
+int
+main ()
+{
+svis(&xx)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "ac_cv_func_svis_noproto=3Dyes"
+else
+  eval "ac_cv_func_svis_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_svis_noproto"=
 >&5
+$as_echo "$ac_cv_func_svis_noproto" >&6; }
+if test "$ac_cv_func_svis_noproto" =3D yes; then
+
+$as_echo "#define NEED_SVIS_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+if test "$ac_cv_func_unvis+set" !=3D set -o "$ac_cv_func_unvis" =3D yes; t=
hen
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if unvis needs a prototy=
pe" >&5
+$as_echo_n "checking if unvis needs a prototype... " >&6; }
+if test "${ac_cv_func_unvis_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_VIS_H
 #include <vis.h>
 #endif
 struct foo { int foo; } xx;
+extern int unvis (struct foo*);
+int
+main ()
+{
+unvis(&xx)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "ac_cv_func_unvis_noproto=3Dyes"
+else
+  eval "ac_cv_func_unvis_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_unvis_noproto=
" >&5
+$as_echo "$ac_cv_func_unvis_noproto" >&6; }
+if test "$ac_cv_func_unvis_noproto" =3D yes; then
+
+$as_echo "#define NEED_UNVIS_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+if test "$ac_cv_func_vis+set" !=3D set -o "$ac_cv_func_vis" =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if vis needs a prototype=
" >&5
+$as_echo_n "checking if vis needs a prototype... " >&6; }
+if test "${ac_cv_func_vis_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef HAVE_VIS_H
+#include <vis.h>
+#endif
+struct foo { int foo; } xx;
 extern int vis (struct foo*);
 int
 main ()
@@ -38281,55 +20744,106 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_vis_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_vis_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_vis_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_vis_noproto" >&6; }
+  eval "ac_cv_func_vis_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vis_noproto" =
>&5
+$as_echo "$ac_cv_func_vis_noproto" >&6; }
 if test "$ac_cv_func_vis_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_VIS_PROTO 1
-_ACEOF
-
-fi
-fi
-
-
-{ echo "$as_me:$LINENO: checking for inet_aton" >&5
-echo $ECHO_N "checking for inet_aton... $ECHO_C" >&6; }
-if test "${ac_cv_func_inet_aton+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define NEED_VIS_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking checking for dirfd" >&5
+$as_echo_n "checking checking for dirfd... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+#ifdef HAVE_DIRENT_H
+#include <dirent.h>
+#endif
+
+int
+main ()
+{
+DIR *d =3D 0; dirfd(d);
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_rk_have_dirfd=3Dyes
+else
+  ac_rk_have_dirfd=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+if test "$ac_rk_have_dirfd" =3D "yes" ; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DIRFD 1
+_ACEOF
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_rk_have_dirfd" >&5
+$as_echo "$ac_rk_have_dirfd" >&6; }
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dd_fd in DIR" >&5
+$as_echo_n "checking for dd_fd in DIR... " >&6; }
+if test "${ac_cv_type_dir_dd_fd+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+#ifdef HAVE_DIRENT_H
+#include <dirent.h>
+#endif
+int
+main ()
+{
+DIR x; memset(&x, 0, sizeof(x)); x.dd_fd
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_dir_dd_fd=3Dyes
+else
+  ac_cv_type_dir_dd_fd=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_dir_dd_fd" >&5
+$as_echo "$ac_cv_type_dir_dd_fd" >&6; }
+if test "$ac_cv_type_dir_dd_fd" =3D yes; then
+
+
+$as_echo "#define HAVE_DIR_DD_FD 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_aton" >&5
+$as_echo_n "checking for inet_aton... " >&6; }
+if test "${ac_cv_func_inet_aton+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -38360,34 +20874,13 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "ac_cv_func_inet_aton=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_inet_aton=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  eval "ac_cv_func_inet_aton=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 if eval "test \"\${ac_cv_func_inet_aton}\" =3D yes"; then
@@ -38396,11 +20889,11 @@
 #define HAVE_INET_ATON 1
 _ACEOF
=20
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
   case " $LIBOBJS " in
   *" inet_aton.$ac_objext "* ) ;;
   *) LIBOBJS=3D"$LIBOBJS inet_aton.$ac_objext"
@@ -38409,16 +20902,12 @@
=20
 fi
=20
-{ echo "$as_me:$LINENO: checking for inet_ntop" >&5
-echo $ECHO_N "checking for inet_ntop... $ECHO_C" >&6; }
-if test "${ac_cv_func_inet_ntop+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_ntop" >&5
+$as_echo_n "checking for inet_ntop... " >&6; }
+if test "${ac_cv_func_inet_ntop+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -38449,34 +20938,13 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "ac_cv_func_inet_ntop=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_inet_ntop=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  eval "ac_cv_func_inet_ntop=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 if eval "test \"\${ac_cv_func_inet_ntop}\" =3D yes"; then
@@ -38485,11 +20953,11 @@
 #define HAVE_INET_NTOP 1
 _ACEOF
=20
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
   case " $LIBOBJS " in
   *" inet_ntop.$ac_objext "* ) ;;
   *) LIBOBJS=3D"$LIBOBJS inet_ntop.$ac_objext"
@@ -38498,16 +20966,12 @@
=20
 fi
=20
-{ echo "$as_me:$LINENO: checking for inet_pton" >&5
-echo $ECHO_N "checking for inet_pton... $ECHO_C" >&6; }
-if test "${ac_cv_func_inet_pton+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_pton" >&5
+$as_echo_n "checking for inet_pton... " >&6; }
+if test "${ac_cv_func_inet_pton+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -38538,34 +21002,13 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "ac_cv_func_inet_pton=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_inet_pton=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  eval "ac_cv_func_inet_pton=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 if eval "test \"\${ac_cv_func_inet_pton}\" =3D yes"; then
@@ -38574,11 +21017,11 @@
 #define HAVE_INET_PTON 1
 _ACEOF
=20
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
   case " $LIBOBJS " in
   *" inet_pton.$ac_objext "* ) ;;
   *) LIBOBJS=3D"$LIBOBJS inet_pton.$ac_objext"
@@ -38589,17 +21032,13 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for sa_len in struct sockaddr" >&5
-echo $ECHO_N "checking for sa_len in struct sockaddr... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_sockaddr_sa_len+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sa_len in struct soc=
kaddr" >&5
+$as_echo_n "checking for sa_len in struct sockaddr... " >&6; }
+if test "${ac_cv_type_struct_sockaddr_sa_len+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #include <sys/socket.h>
@@ -38611,42 +21050,20 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_sockaddr_sa_len=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_sockaddr_sa_len=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_sockaddr_sa_len" >&5
-echo "${ECHO_T}$ac_cv_type_struct_sockaddr_sa_len" >&6; }
+  ac_cv_type_struct_sockaddr_sa_len=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_sockad=
dr_sa_len" >&5
+$as_echo "$ac_cv_type_struct_sockaddr_sa_len" >&6; }
 if test "$ac_cv_type_struct_sockaddr_sa_len" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_SOCKADDR_SA_LEN 1
-_ACEOF
+$as_echo "#define HAVE_STRUCT_SOCKADDR_SA_LEN 1" >>confdefs.h
=20
=20
 fi
@@ -38655,23 +21072,15 @@
=20
 if test "$ac_cv_func_getaddrinfo" =3D "yes"; then
=20
-{ echo "$as_me:$LINENO: checking if getaddrinfo handles numeric services" =
>&5
-echo $ECHO_N "checking if getaddrinfo handles numeric services... $ECHO_C"=
 >&6; }
-if test "${ac_cv_func_getaddrinfo_numserv+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test "$cross_compiling" =3D yes; then
-  { { echo "$as_me:$LINENO: error: cannot run test program while cross com=
piling
-See \`config.log' for more details." >&5
-echo "$as_me: error: cannot run test program while cross compiling
-See \`config.log' for more details." >&2;}
-   { (exit 1); exit 1; }; }
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getaddrinfo handles n=
umeric services" >&5
+$as_echo_n "checking if getaddrinfo handles numeric services... " >&6; }
+if test "${ac_cv_func_getaddrinfo_numserv+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "$cross_compiling" =3D yes; then :
+  ac_cv_func_getaddrinfo_numserv=3Dyes
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
 #include <sys/types.h>
@@ -38694,42 +21103,18 @@
 }
=20
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   ac_cv_func_getaddrinfo_numserv=3Dyes
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_getaddrinfo_numserv=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getaddrinfo_numserv" >&5
-echo "${ECHO_T}$ac_cv_func_getaddrinfo_numserv" >&6; }
+  ac_cv_func_getaddrinfo_numserv=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getaddrinfo_n=
umserv" >&5
+$as_echo "$ac_cv_func_getaddrinfo_numserv" >&6; }
   if test "$ac_cv_func_getaddrinfo_numserv" =3D no; then
 	case " $LIBOBJS " in
   *" getaddrinfo.$ac_objext "* ) ;;
@@ -38748,16 +21133,12 @@
=20
=20
 if test "$ac_cv_func_setenv+set" !=3D set -o "$ac_cv_func_setenv" =3D yes;=
 then
-{ echo "$as_me:$LINENO: checking if setenv needs a prototype" >&5
-echo $ECHO_N "checking if setenv needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_setenv_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if setenv needs a protot=
ype" >&5
+$as_echo_n "checking if setenv needs a prototype... " >&6; }
+if test "${ac_cv_func_setenv_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdlib.h>
 struct foo { int foo; } xx;
@@ -38770,56 +21151,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_setenv_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_setenv_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_setenv_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_setenv_noproto" >&6; }
+  eval "ac_cv_func_setenv_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_setenv_noprot=
o" >&5
+$as_echo "$ac_cv_func_setenv_noproto" >&6; }
 if test "$ac_cv_func_setenv_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_SETENV_PROTO 1
-_ACEOF
+$as_echo "#define NEED_SETENV_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
=20
 if test "$ac_cv_func_unsetenv+set" !=3D set -o "$ac_cv_func_unsetenv" =3D =
yes; then
-{ echo "$as_me:$LINENO: checking if unsetenv needs a prototype" >&5
-echo $ECHO_N "checking if unsetenv needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_unsetenv_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if unsetenv needs a prot=
otype" >&5
+$as_echo_n "checking if unsetenv needs a prototype... " >&6; }
+if test "${ac_cv_func_unsetenv_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdlib.h>
 struct foo { int foo; } xx;
@@ -38832,56 +21187,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_unsetenv_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_unsetenv_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_unsetenv_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_unsetenv_noproto" >&6; }
+  eval "ac_cv_func_unsetenv_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_unsetenv_nopr=
oto" >&5
+$as_echo "$ac_cv_func_unsetenv_noproto" >&6; }
 if test "$ac_cv_func_unsetenv_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_UNSETENV_PROTO 1
-_ACEOF
+$as_echo "#define NEED_UNSETENV_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
=20
 if test "$ac_cv_func_gethostname+set" !=3D set -o "$ac_cv_func_gethostname=
" =3D yes; then
-{ echo "$as_me:$LINENO: checking if gethostname needs a prototype" >&5
-echo $ECHO_N "checking if gethostname needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_gethostname_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if gethostname needs a p=
rototype" >&5
+$as_echo_n "checking if gethostname needs a prototype... " >&6; }
+if test "${ac_cv_func_gethostname_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <unistd.h>
 struct foo { int foo; } xx;
@@ -38894,56 +21223,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_gethostname_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_gethostname_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostname_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_gethostname_noproto" >&6; }
+  eval "ac_cv_func_gethostname_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_gethostname_n=
oproto" >&5
+$as_echo "$ac_cv_func_gethostname_noproto" >&6; }
 if test "$ac_cv_func_gethostname_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_GETHOSTNAME_PROTO 1
-_ACEOF
+$as_echo "#define NEED_GETHOSTNAME_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
=20
 if test "$ac_cv_func_mkstemp+set" !=3D set -o "$ac_cv_func_mkstemp" =3D ye=
s; then
-{ echo "$as_me:$LINENO: checking if mkstemp needs a prototype" >&5
-echo $ECHO_N "checking if mkstemp needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_mkstemp_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if mkstemp needs a proto=
type" >&5
+$as_echo_n "checking if mkstemp needs a prototype... " >&6; }
+if test "${ac_cv_func_mkstemp_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <unistd.h>
 struct foo { int foo; } xx;
@@ -38956,56 +21259,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_mkstemp_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_mkstemp_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_mkstemp_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_mkstemp_noproto" >&6; }
+  eval "ac_cv_func_mkstemp_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_mkstemp_nopro=
to" >&5
+$as_echo "$ac_cv_func_mkstemp_noproto" >&6; }
 if test "$ac_cv_func_mkstemp_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_MKSTEMP_PROTO 1
-_ACEOF
+$as_echo "#define NEED_MKSTEMP_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
=20
 if test "$ac_cv_func_getusershell+set" !=3D set -o "$ac_cv_func_getusershe=
ll" =3D yes; then
-{ echo "$as_me:$LINENO: checking if getusershell needs a prototype" >&5
-echo $ECHO_N "checking if getusershell needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_getusershell_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getusershell needs a =
prototype" >&5
+$as_echo_n "checking if getusershell needs a prototype... " >&6; }
+if test "${ac_cv_func_getusershell_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <unistd.h>
 struct foo { int foo; } xx;
@@ -39018,56 +21295,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_getusershell_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_getusershell_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getusershell_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_getusershell_noproto" >&6; }
+  eval "ac_cv_func_getusershell_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getusershell_=
noproto" >&5
+$as_echo "$ac_cv_func_getusershell_noproto" >&6; }
 if test "$ac_cv_func_getusershell_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_GETUSERSHELL_PROTO 1
-_ACEOF
+$as_echo "#define NEED_GETUSERSHELL_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
=20
 if test "$ac_cv_func_daemon+set" !=3D set -o "$ac_cv_func_daemon" =3D yes;=
 then
-{ echo "$as_me:$LINENO: checking if daemon needs a prototype" >&5
-echo $ECHO_N "checking if daemon needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_daemon_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if daemon needs a protot=
ype" >&5
+$as_echo_n "checking if daemon needs a prototype... " >&6; }
+if test "${ac_cv_func_daemon_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <unistd.h>
 struct foo { int foo; } xx;
@@ -39080,56 +21331,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_daemon_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_daemon_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_daemon_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_daemon_noproto" >&6; }
+  eval "ac_cv_func_daemon_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_daemon_noprot=
o" >&5
+$as_echo "$ac_cv_func_daemon_noproto" >&6; }
 if test "$ac_cv_func_daemon_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_DAEMON_PROTO 1
-_ACEOF
+$as_echo "#define NEED_DAEMON_PROTO 1" >>confdefs.h
=20
 fi
 fi
=20
=20
 if test "$ac_cv_func_iruserok+set" !=3D set -o "$ac_cv_func_iruserok" =3D =
yes; then
-{ echo "$as_me:$LINENO: checking if iruserok needs a prototype" >&5
-echo $ECHO_N "checking if iruserok needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_iruserok_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if iruserok needs a prot=
otype" >&5
+$as_echo_n "checking if iruserok needs a prototype... " >&6; }
+if test "${ac_cv_func_iruserok_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -39160,40 +21385,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_iruserok_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_iruserok_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_iruserok_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_iruserok_noproto" >&6; }
+  eval "ac_cv_func_iruserok_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_iruserok_nopr=
oto" >&5
+$as_echo "$ac_cv_func_iruserok_noproto" >&6; }
 if test "$ac_cv_func_iruserok_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_IRUSEROK_PROTO 1
-_ACEOF
+$as_echo "#define NEED_IRUSEROK_PROTO 1" >>confdefs.h
=20
 fi
 fi
@@ -39201,16 +21404,12 @@
=20
=20
 if test "$ac_cv_func_inet_aton+set" !=3D set -o "$ac_cv_func_inet_aton" =
=3D yes; then
-{ echo "$as_me:$LINENO: checking if inet_aton needs a prototype" >&5
-echo $ECHO_N "checking if inet_aton needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_inet_aton_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if inet_aton needs a pro=
totype" >&5
+$as_echo_n "checking if inet_aton needs a prototype... " >&6; }
+if test "${ac_cv_func_inet_aton_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -39235,52 +21434,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_inet_aton_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_inet_aton_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_inet_aton_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_inet_aton_noproto" >&6; }
+  eval "ac_cv_func_inet_aton_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_inet_aton_nop=
roto" >&5
+$as_echo "$ac_cv_func_inet_aton_noproto" >&6; }
 if test "$ac_cv_func_inet_aton_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_INET_ATON_PROTO 1
-_ACEOF
-
-fi
-fi
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for crypt" >&5
-echo $ECHO_N "checking for crypt... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_crypt+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define NEED_INET_ATON_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for crypt" >&5
+$as_echo_n "checking for crypt... " >&6; }
+if test "${ac_cv_funclib_crypt+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_crypt\" !=3D yes" ; then
@@ -39294,11 +21471,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -39309,34 +21482,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_crypt=3D$ac_lib; else ac=
_cv_funclib_crypt=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_crypt=3D\${ac_cv_funclib_crypt-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -39348,95 +21498,12 @@
 eval "ac_res=3D\$ac_cv_funclib_crypt"
=20
 if false; then
-
-for ac_func in crypt
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in crypt
+do :
+  ac_fn_c_check_func "$LINENO" "crypt" "ac_cv_func_crypt"
+if test "x$ac_cv_func_crypt" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_CRYPT 1
 _ACEOF
=20
 fi
@@ -39456,14 +21523,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_crypt=3Dno"
 	eval "LIB_crypt=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_crypt=3Dyes"
@@ -39476,26 +21543,71 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking if gethostbyname is compatible with syste=
m prototype" >&5
-echo $ECHO_N "checking if gethostbyname is compatible with system prototyp=
e... $ECHO_C" >&6; }
-if test "${ac_cv_func_gethostbyname_proto_compat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if strerror_r is compati=
ble with system prototype" >&5
+$as_echo_n "checking if strerror_r is compatible with system prototype... =
" >&6; }
+if test "${ac_cv_func_strerror_r_proto_compat+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <stdio.h>
+#include <string.h>
+
+int
+main ()
+{
+int strerror_r(int, char *, size_t)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "ac_cv_func_strerror_r_proto_compat=3Dyes"
+else
+  eval "ac_cv_func_strerror_r_proto_compat=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strerror_r_pr=
oto_compat" >&5
+$as_echo "$ac_cv_func_strerror_r_proto_compat" >&6; }
+
+if test "$ac_cv_func_strerror_r_proto_compat" =3D yes; then
+
+$as_echo "#define STRERROR_R_PROTO_COMPATIBLE 1" >>confdefs.h
+
+fi
+
+
+
+ac_fn_c_check_func "$LINENO" "strerror_r" "ac_cv_func_strerror_r"
+if test "x$ac_cv_func_strerror_r" =3D x""yes; then :
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_STRERROR_R 1
+_ACEOF
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if gethostbyname is comp=
atible with system prototype" >&5
+$as_echo_n "checking if gethostbyname is compatible with system prototype.=
.. " >&6; }
+if test "${ac_cv_func_gethostbyname_proto_compat+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -39522,57 +21634,31 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_gethostbyname_proto_compat=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_gethostbyname_proto_compat=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname_proto_compat" >&5
-echo "${ECHO_T}$ac_cv_func_gethostbyname_proto_compat" >&6; }
+  eval "ac_cv_func_gethostbyname_proto_compat=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_gethostbyname=
_proto_compat" >&5
+$as_echo "$ac_cv_func_gethostbyname_proto_compat" >&6; }
=20
 if test "$ac_cv_func_gethostbyname_proto_compat" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define GETHOSTBYNAME_PROTO_COMPATIBLE 1
-_ACEOF
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking if gethostbyaddr is compatible with syste=
m prototype" >&5
-echo $ECHO_N "checking if gethostbyaddr is compatible with system prototyp=
e... $ECHO_C" >&6; }
-if test "${ac_cv_func_gethostbyaddr_proto_compat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define GETHOSTBYNAME_PROTO_COMPATIBLE 1" >>confdefs.h
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if gethostbyaddr is comp=
atible with system prototype" >&5
+$as_echo_n "checking if gethostbyaddr is compatible with system prototype.=
.. " >&6; }
+if test "${ac_cv_func_gethostbyaddr_proto_compat+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -39599,57 +21685,31 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_gethostbyaddr_proto_compat=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_gethostbyaddr_proto_compat=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyaddr_proto_compat" >&5
-echo "${ECHO_T}$ac_cv_func_gethostbyaddr_proto_compat" >&6; }
+  eval "ac_cv_func_gethostbyaddr_proto_compat=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_gethostbyaddr=
_proto_compat" >&5
+$as_echo "$ac_cv_func_gethostbyaddr_proto_compat" >&6; }
=20
 if test "$ac_cv_func_gethostbyaddr_proto_compat" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define GETHOSTBYADDR_PROTO_COMPATIBLE 1
-_ACEOF
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking if getservbyname is compatible with syste=
m prototype" >&5
-echo $ECHO_N "checking if getservbyname is compatible with system prototyp=
e... $ECHO_C" >&6; }
-if test "${ac_cv_func_getservbyname_proto_compat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define GETHOSTBYADDR_PROTO_COMPATIBLE 1" >>confdefs.h
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getservbyname is comp=
atible with system prototype" >&5
+$as_echo_n "checking if getservbyname is compatible with system prototype.=
.. " >&6; }
+if test "${ac_cv_func_getservbyname_proto_compat+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -39676,57 +21736,31 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_getservbyname_proto_compat=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_getservbyname_proto_compat=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getservbyname_proto_compat" >&5
-echo "${ECHO_T}$ac_cv_func_getservbyname_proto_compat" >&6; }
+  eval "ac_cv_func_getservbyname_proto_compat=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getservbyname=
_proto_compat" >&5
+$as_echo "$ac_cv_func_getservbyname_proto_compat" >&6; }
=20
 if test "$ac_cv_func_getservbyname_proto_compat" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define GETSERVBYNAME_PROTO_COMPATIBLE 1
-_ACEOF
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking if getsockname is compatible with system =
prototype" >&5
-echo $ECHO_N "checking if getsockname is compatible with system prototype.=
.. $ECHO_C" >&6; }
-if test "${ac_cv_func_getsockname_proto_compat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define GETSERVBYNAME_PROTO_COMPATIBLE 1" >>confdefs.h
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getsockname is compat=
ible with system prototype" >&5
+$as_echo_n "checking if getsockname is compatible with system prototype...=
 " >&6; }
+if test "${ac_cv_func_getsockname_proto_compat+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYS_TYPES_H
@@ -39744,57 +21778,31 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_getsockname_proto_compat=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_getsockname_proto_compat=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getsockname_proto_compat" >&5
-echo "${ECHO_T}$ac_cv_func_getsockname_proto_compat" >&6; }
+  eval "ac_cv_func_getsockname_proto_compat=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getsockname_p=
roto_compat" >&5
+$as_echo "$ac_cv_func_getsockname_proto_compat" >&6; }
=20
 if test "$ac_cv_func_getsockname_proto_compat" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define GETSOCKNAME_PROTO_COMPATIBLE 1
-_ACEOF
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking if openlog is compatible with system prot=
otype" >&5
-echo $ECHO_N "checking if openlog is compatible with system prototype... $=
ECHO_C" >&6; }
-if test "${ac_cv_func_openlog_proto_compat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define GETSOCKNAME_PROTO_COMPATIBLE 1" >>confdefs.h
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if openlog is compatible=
 with system prototype" >&5
+$as_echo_n "checking if openlog is compatible with system prototype... " >=
&6; }
+if test "${ac_cv_func_openlog_proto_compat+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_SYSLOG_H
@@ -39809,41 +21817,19 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_openlog_proto_compat=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_openlog_proto_compat=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_openlog_proto_compat" >&5
-echo "${ECHO_T}$ac_cv_func_openlog_proto_compat" >&6; }
+  eval "ac_cv_func_openlog_proto_compat=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_openlog_proto=
_compat" >&5
+$as_echo "$ac_cv_func_openlog_proto_compat" >&6; }
=20
 if test "$ac_cv_func_openlog_proto_compat" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define OPENLOG_PROTO_COMPATIBLE 1
-_ACEOF
+$as_echo "#define OPENLOG_PROTO_COMPATIBLE 1" >>confdefs.h
=20
 fi
=20
@@ -39851,16 +21837,12 @@
=20
=20
 if test "$ac_cv_func_crypt+set" !=3D set -o "$ac_cv_func_crypt" =3D yes; t=
hen
-{ echo "$as_me:$LINENO: checking if crypt needs a prototype" >&5
-echo $ECHO_N "checking if crypt needs a prototype... $ECHO_C" >&6; }
-if test "${ac_cv_func_crypt_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if crypt needs a prototy=
pe" >&5
+$as_echo_n "checking if crypt needs a prototype... " >&6; }
+if test "${ac_cv_func_crypt_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_CRYPT_H
@@ -39880,59 +21862,33 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_crypt_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_crypt_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_crypt_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_crypt_noproto" >&6; }
+  eval "ac_cv_func_crypt_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_crypt_noproto=
" >&5
+$as_echo "$ac_cv_func_crypt_noproto" >&6; }
 if test "$ac_cv_func_crypt_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_CRYPT_PROTO 1
-_ACEOF
-
-fi
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for h_errno" >&5
-echo $ECHO_N "checking for h_errno... $ECHO_C" >&6; }
-if test "${ac_cv_var_h_errno+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define NEED_CRYPT_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for h_errno" >&5
+$as_echo_n "checking for h_errno... " >&6; }
+if test "${ac_cv_var_h_errno+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -39940,6 +21896,10 @@
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+
 	void * foo(void) { return &h_errno; }
 int
 main ()
@@ -39949,41 +21909,26 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_h_errno=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_h_errno=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_h_errno=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 if test "$ac_cv_var_h_errno" !=3D yes ; then
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+
 extern int h_errno;
 int foo(void) { return h_errno; }
 int
@@ -39994,141 +21939,66 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_h_errno=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_h_errno=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_h_errno=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 fi
=20
 ac_foo=3D`eval echo \\$ac_cv_var_h_errno`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_H_ERRNO 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: checking whether h_errno is declared" >&5
-echo $ECHO_N "checking whether h_errno is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_h_errno+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef HAVE_SYS_TYPES_H
+	ac_fn_c_check_decl "$LINENO" "h_errno" "ac_cv_have_decl_h_errno" "#ifdef =
HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
-
-int
-main ()
-{
-#ifndef h_errno
-  (void) h_errno;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_h_errno=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_h_errno=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_h_errno" >&5
-echo "${ECHO_T}$ac_cv_have_decl_h_errno" >&6; }
-if test $ac_cv_have_decl_h_errno =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_H_ERRNO 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_H_ERRNO 0
-_ACEOF
-
-
-fi
-
-
-fi
-
-
-
-{ echo "$as_me:$LINENO: checking for h_errlist" >&5
-echo $ECHO_N "checking for h_errlist... $ECHO_C" >&6; }
-if test "${ac_cv_var_h_errlist+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+
+"
+if test "x$ac_cv_have_decl_h_errno" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_H_ERRNO $ac_have_decl
+_ACEOF
+
+fi
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for h_errlist" >&5
+$as_echo_n "checking for h_errlist... " >&6; }
+if test "${ac_cv_var_h_errlist+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 	void * foo(void) { return &h_errlist; }
 int
 main ()
@@ -40138,41 +22008,22 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_h_errlist=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_h_errlist=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_h_errlist=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 if test "$ac_cv_var_h_errlist" !=3D yes ; then
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 extern int h_errlist;
 int foo(void) { return h_errlist; }
 int
@@ -40183,182 +22034,87 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_h_errlist=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_h_errlist=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_h_errlist=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 fi
=20
 ac_foo=3D`eval echo \\$ac_cv_var_h_errlist`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_H_ERRLIST 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: checking whether h_errlist is declared" >&5
-echo $ECHO_N "checking whether h_errlist is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_h_errlist+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+	ac_fn_c_check_decl "$LINENO" "h_errlist" "ac_cv_have_decl_h_errlist" "#if=
def HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+"
+if test "x$ac_cv_have_decl_h_errlist" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_H_ERRLIST $ac_have_decl
+_ACEOF
+
+fi
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for h_nerr" >&5
+$as_echo_n "checking for h_nerr... " >&6; }
+if test "${ac_cv_var_h_nerr+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
-
-int
-main ()
-{
-#ifndef h_errlist
-  (void) h_errlist;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_h_errlist=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_h_errlist=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_h_errlist" >&5
-echo "${ECHO_T}$ac_cv_have_decl_h_errlist" >&6; }
-if test $ac_cv_have_decl_h_errlist =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_H_ERRLIST 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_H_ERRLIST 0
-_ACEOF
-
-
-fi
-
-
-fi
-
-
-
-{ echo "$as_me:$LINENO: checking for h_nerr" >&5
-echo $ECHO_N "checking for h_nerr... $ECHO_C" >&6; }
-if test "${ac_cv_var_h_nerr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+	void * foo(void) { return &h_nerr; }
+int
+main ()
+{
+foo()
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_var_h_nerr=3Dyes
+else
+  ac_cv_var_h_nerr=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+if test "$ac_cv_var_h_nerr" !=3D yes ; then
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_NETDB_H
 #include <netdb.h>
 #endif
-	void * foo(void) { return &h_nerr; }
-int
-main ()
-{
-foo()
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_var_h_nerr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_h_nerr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-if test "$ac_cv_var_h_nerr" !=3D yes ; then
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 extern int h_nerr;
 int foo(void) { return h_nerr; }
 int
@@ -40369,134 +22125,55 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_h_nerr=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_h_nerr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_h_nerr=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 fi
=20
 ac_foo=3D`eval echo \\$ac_cv_var_h_nerr`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_H_NERR 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: checking whether h_nerr is declared" >&5
-echo $ECHO_N "checking whether h_nerr is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_h_nerr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef HAVE_NETDB_H
+	ac_fn_c_check_decl "$LINENO" "h_nerr" "ac_cv_have_decl_h_nerr" "#ifdef HA=
VE_NETDB_H
 #include <netdb.h>
 #endif
-
-int
-main ()
-{
-#ifndef h_nerr
-  (void) h_nerr;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_h_nerr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_h_nerr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_h_nerr" >&5
-echo "${ECHO_T}$ac_cv_have_decl_h_nerr" >&6; }
-if test $ac_cv_have_decl_h_nerr =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_H_NERR 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_H_NERR 0
-_ACEOF
-
-
-fi
-
-
-fi
-
-
-
-{ echo "$as_me:$LINENO: checking for __progname" >&5
-echo $ECHO_N "checking for __progname... $ECHO_C" >&6; }
-if test "${ac_cv_var___progname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
+"
+if test "x$ac_cv_have_decl_h_nerr" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_H_NERR $ac_have_decl
+_ACEOF
+
+fi
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for __progname" >&5
+$as_echo_n "checking for __progname... " >&6; }
+if test "${ac_cv_var___progname+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifdef HAVE_ERR_H
 #include <err.h>
@@ -40510,41 +22187,19 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var___progname=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var___progname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var___progname=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 if test "$ac_cv_var___progname" !=3D yes ; then
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef HAVE_ERR_H
+#include <err.h>
+#endif
 extern int __progname;
 int foo(void) { return __progname; }
 int
@@ -40555,488 +22210,130 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var___progname=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var___progname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var___progname=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 fi
=20
 ac_foo=3D`eval echo \\$ac_cv_var___progname`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE___PROGNAME 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: checking whether __progname is declared" >&5
-echo $ECHO_N "checking whether __progname is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl___progname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#ifdef HAVE_ERR_H
+	ac_fn_c_check_decl "$LINENO" "__progname" "ac_cv_have_decl___progname" "#=
ifdef HAVE_ERR_H
 #include <err.h>
 #endif
-
-int
-main ()
-{
-#ifndef __progname
-  (void) __progname;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl___progname=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl___progname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl___progname" >&5
-echo "${ECHO_T}$ac_cv_have_decl___progname" >&6; }
-if test $ac_cv_have_decl___progname =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL___PROGNAME 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL___PROGNAME 0
-_ACEOF
-
-
-fi
-
-
-fi
-
-
-{ echo "$as_me:$LINENO: checking whether optarg is declared" >&5
-echo $ECHO_N "checking whether optarg is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_optarg+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-#ifndef optarg
-  (void) optarg;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_optarg=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_optarg=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_optarg" >&5
-echo "${ECHO_T}$ac_cv_have_decl_optarg" >&6; }
-if test $ac_cv_have_decl_optarg =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTARG 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTARG 0
-_ACEOF
-
-
+"
+if test "x$ac_cv_have_decl___progname" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL___PROGNAME $ac_have_decl
+_ACEOF
+
+fi
+
+
+ac_fn_c_check_decl "$LINENO" "optarg" "ac_cv_have_decl_optarg" "
 #include <stdlib.h>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-fi
-{ echo "$as_me:$LINENO: checking whether optind is declared" >&5
-echo $ECHO_N "checking whether optind is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_optind+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-#ifndef optind
-  (void) optind;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_optind=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_optind=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_optind" >&5
-echo "${ECHO_T}$ac_cv_have_decl_optind" >&6; }
-if test $ac_cv_have_decl_optind =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTIND 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTIND 0
-_ACEOF
-
-
+"
+if test "x$ac_cv_have_decl_optarg" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_OPTARG $ac_have_decl
+_ACEOF
+ac_fn_c_check_decl "$LINENO" "optind" "ac_cv_have_decl_optind" "
 #include <stdlib.h>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-fi
-{ echo "$as_me:$LINENO: checking whether opterr is declared" >&5
-echo $ECHO_N "checking whether opterr is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_opterr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-#ifndef opterr
-  (void) opterr;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_opterr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_opterr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_opterr" >&5
-echo "${ECHO_T}$ac_cv_have_decl_opterr" >&6; }
-if test $ac_cv_have_decl_opterr =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTERR 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTERR 0
-_ACEOF
-
-
+"
+if test "x$ac_cv_have_decl_optind" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_OPTIND $ac_have_decl
+_ACEOF
+ac_fn_c_check_decl "$LINENO" "opterr" "ac_cv_have_decl_opterr" "
 #include <stdlib.h>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-fi
-{ echo "$as_me:$LINENO: checking whether optopt is declared" >&5
-echo $ECHO_N "checking whether optopt is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_optopt+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-#ifndef optopt
-  (void) optopt;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_optopt=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_optopt=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_optopt" >&5
-echo "${ECHO_T}$ac_cv_have_decl_optopt" >&6; }
-if test $ac_cv_have_decl_optopt =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTOPT 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_OPTOPT 0
-_ACEOF
-
-
+"
+if test "x$ac_cv_have_decl_opterr" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_OPTERR $ac_have_decl
+_ACEOF
+ac_fn_c_check_decl "$LINENO" "optopt" "ac_cv_have_decl_optopt" "
 #include <stdlib.h>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-fi
-{ echo "$as_me:$LINENO: checking whether environ is declared" >&5
-echo $ECHO_N "checking whether environ is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_environ+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-int
-main ()
-{
-#ifndef environ
-  (void) environ;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_environ=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_environ=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_environ" >&5
-echo "${ECHO_T}$ac_cv_have_decl_environ" >&6; }
-if test $ac_cv_have_decl_environ =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_ENVIRON 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_ENVIRON 0
-_ACEOF
-
-
+"
+if test "x$ac_cv_have_decl_optopt" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_OPTOPT $ac_have_decl
+_ACEOF
+ac_fn_c_check_decl "$LINENO" "environ" "ac_cv_have_decl_environ" "
 #include <stdlib.h>
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
-fi
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for tm_gmtoff in struct tm" >&5
-echo $ECHO_N "checking for tm_gmtoff in struct tm... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_tm_tm_gmtoff+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+"
+if test "x$ac_cv_have_decl_environ" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_ENVIRON $ac_have_decl
+_ACEOF
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tm_gmtoff in struct =
tm" >&5
+$as_echo_n "checking for tm_gmtoff in struct tm... " >&6; }
+if test "${ac_cv_type_struct_tm_tm_gmtoff+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <time.h>
 int
@@ -41047,60 +22344,34 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_tm_tm_gmtoff=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_tm_tm_gmtoff=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_tm_tm_gmtoff" >&5
-echo "${ECHO_T}$ac_cv_type_struct_tm_tm_gmtoff" >&6; }
+  ac_cv_type_struct_tm_tm_gmtoff=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_tm_tm_=
gmtoff" >&5
+$as_echo "$ac_cv_type_struct_tm_tm_gmtoff" >&6; }
 if test "$ac_cv_type_struct_tm_tm_gmtoff" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_TM_TM_GMTOFF 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for tm_zone in struct tm" >&5
-echo $ECHO_N "checking for tm_zone in struct tm... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_tm_tm_zone+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_TM_TM_GMTOFF 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tm_zone in struct tm=
" >&5
+$as_echo_n "checking for tm_zone in struct tm... " >&6; }
+if test "${ac_cv_type_struct_tm_tm_zone+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <time.h>
 int
@@ -41111,62 +22382,36 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_tm_tm_zone=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_tm_tm_zone=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_tm_tm_zone" >&5
-echo "${ECHO_T}$ac_cv_type_struct_tm_tm_zone" >&6; }
+  ac_cv_type_struct_tm_tm_zone=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_tm_tm_=
zone" >&5
+$as_echo "$ac_cv_type_struct_tm_tm_zone" >&6; }
 if test "$ac_cv_type_struct_tm_tm_zone" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_TM_TM_ZONE 1
-_ACEOF
-
-
-fi
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for timezone" >&5
-echo $ECHO_N "checking for timezone... $ECHO_C" >&6; }
-if test "${ac_cv_var_timezone+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_TM_TM_ZONE 1" >>confdefs.h
+
+
+fi
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for timezone" >&5
+$as_echo_n "checking for timezone... " >&6; }
+if test "${ac_cv_var_timezone+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <time.h>
 	void * foo(void) { return &timezone; }
@@ -41178,41 +22423,17 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_timezone=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_timezone=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_timezone=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 if test "$ac_cv_var_timezone" !=3D yes ; then
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <time.h>
 extern int timezone;
 int foo(void) { return timezone; }
 int
@@ -41223,131 +22444,49 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_timezone=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_timezone=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_timezone=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 fi
=20
 ac_foo=3D`eval echo \\$ac_cv_var_timezone`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_TIMEZONE 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: checking whether timezone is declared" >&5
-echo $ECHO_N "checking whether timezone is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_timezone+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <time.h>
-
-int
-main ()
-{
-#ifndef timezone
-  (void) timezone;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_timezone=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_timezone=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_timezone" >&5
-echo "${ECHO_T}$ac_cv_have_decl_timezone" >&6; }
-if test $ac_cv_have_decl_timezone =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_TIMEZONE 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_TIMEZONE 0
-_ACEOF
-
-
-fi
-
-
-fi
-
-
-{ echo "$as_me:$LINENO: checking for altzone" >&5
-echo $ECHO_N "checking for altzone... $ECHO_C" >&6; }
-if test "${ac_cv_var_altzone+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+	ac_fn_c_check_decl "$LINENO" "timezone" "ac_cv_have_decl_timezone" "#incl=
ude <time.h>
+"
+if test "x$ac_cv_have_decl_timezone" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_TIMEZONE $ac_have_decl
+_ACEOF
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for altzone" >&5
+$as_echo_n "checking for altzone... " >&6; }
+if test "${ac_cv_var_altzone+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <time.h>
 	void * foo(void) { return &altzone; }
@@ -41359,41 +22498,17 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_altzone=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_altzone=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_altzone=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 if test "$ac_cv_var_altzone" !=3D yes ; then
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <time.h>
 extern int altzone;
 int foo(void) { return altzone; }
 int
@@ -41404,115 +22519,37 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_var_altzone=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_var_altzone=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_var_altzone=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi
=20
 fi
=20
 ac_foo=3D`eval echo \\$ac_cv_var_altzone`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_ALTZONE 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: checking whether altzone is declared" >&5
-echo $ECHO_N "checking whether altzone is declared... $ECHO_C" >&6; }
-if test "${ac_cv_have_decl_altzone+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <time.h>
-
-int
-main ()
-{
-#ifndef altzone
-  (void) altzone;
-#endif
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_have_decl_altzone=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_have_decl_altzone=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_have_decl_altzone" >&5
-echo "${ECHO_T}$ac_cv_have_decl_altzone" >&6; }
-if test $ac_cv_have_decl_altzone =3D yes; then
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_ALTZONE 1
-_ACEOF
-
-
-else
-  cat >>confdefs.h <<_ACEOF
-#define HAVE_DECL_ALTZONE 0
-_ACEOF
-
-
-fi
-
+	ac_fn_c_check_decl "$LINENO" "altzone" "ac_cv_have_decl_altzone" "#includ=
e <time.h>
+"
+if test "x$ac_cv_have_decl_altzone" =3D x""yes; then :
+  ac_have_decl=3D1
+else
+  ac_have_decl=3D0
+fi
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_DECL_ALTZONE $ac_have_decl
+_ACEOF
=20
 fi
=20
@@ -41520,16 +22557,12 @@
=20
=20
 cv=3D`echo "sa_family_t" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for sa_family_t" >&5
-echo $ECHO_N "checking for sa_family_t... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sa_family_t" >&5
+$as_echo_n "checking for sa_family_t... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -41539,7 +22572,12 @@
 #endif
=20
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -41548,93 +22586,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo sa_family_t | sed 'y%abcdefghijklmnopqrstuvwxyz./=
- %ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for sa_family_t" >&5
-echo $ECHO_N "checking for sa_family_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_sa_family_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef sa_family_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_sa_family_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_sa_family_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_sa_family_t" >&5
-echo "${ECHO_T}$ac_cv_type_sa_family_t" >&6; }
-if test $ac_cv_type_sa_family_t =3D yes; then
+	ac_fn_c_check_type "$LINENO" "sa_family_t" "ac_cv_type_sa_family_t" "$ac_=
includes_default"
+if test "x$ac_cv_type_sa_family_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SA_FAMILY_T 1
@@ -41654,16 +22620,12 @@
=20
=20
 cv=3D`echo "socklen_t" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for socklen_t" >&5
-echo $ECHO_N "checking for socklen_t... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socklen_t" >&5
+$as_echo_n "checking for socklen_t... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -41673,7 +22635,12 @@
 #endif
=20
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -41682,93 +22649,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo socklen_t | sed 'y%abcdefghijklmnopqrstuvwxyz./- =
%ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for socklen_t" >&5
-echo $ECHO_N "checking for socklen_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_socklen_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef socklen_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_socklen_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_socklen_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_socklen_t" >&5
-echo "${ECHO_T}$ac_cv_type_socklen_t" >&6; }
-if test $ac_cv_type_socklen_t =3D yes; then
+	ac_fn_c_check_type "$LINENO" "socklen_t" "ac_cv_type_socklen_t" "$ac_incl=
udes_default"
+if test "x$ac_cv_type_socklen_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_SOCKLEN_T 1
@@ -41788,16 +22683,12 @@
=20
=20
 cv=3D`echo "struct sockaddr" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for struct sockaddr" >&5
-echo $ECHO_N "checking for struct sockaddr... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct sockaddr" >&5
+$as_echo_n "checking for struct sockaddr... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -41807,7 +22698,12 @@
 #endif
=20
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -41816,93 +22712,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo struct sockaddr | sed 'y%abcdefghijklmnopqrstuvwx=
yz./- %ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for struct sockaddr" >&5
-echo $ECHO_N "checking for struct sockaddr... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_sockaddr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef struct sockaddr ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_struct_sockaddr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_sockaddr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_sockaddr" >&5
-echo "${ECHO_T}$ac_cv_type_struct_sockaddr" >&6; }
-if test $ac_cv_type_struct_sockaddr =3D yes; then
+	ac_fn_c_check_type "$LINENO" "struct sockaddr" "ac_cv_type_struct_sockadd=
r" "$ac_includes_default"
+if test "x$ac_cv_type_struct_sockaddr" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRUCT_SOCKADDR 1
@@ -41922,16 +22746,12 @@
=20
=20
 cv=3D`echo "struct sockaddr_storage" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for struct sockaddr_storage" >&5
-echo $ECHO_N "checking for struct sockaddr_storage... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct sockaddr_stor=
age" >&5
+$as_echo_n "checking for struct sockaddr_storage... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -41941,7 +22761,12 @@
 #endif
=20
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -41950,93 +22775,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo struct sockaddr_storage | sed 'y%abcdefghijklmnop=
qrstuvwxyz./- %ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for struct sockaddr_storage" >&5
-echo $ECHO_N "checking for struct sockaddr_storage... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_sockaddr_storage+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef struct sockaddr_storage ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_struct_sockaddr_storage=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_sockaddr_storage=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_sockaddr_storage" >&5
-echo "${ECHO_T}$ac_cv_type_struct_sockaddr_storage" >&6; }
-if test $ac_cv_type_struct_sockaddr_storage =3D yes; then
+	ac_fn_c_check_type "$LINENO" "struct sockaddr_storage" "ac_cv_type_struct=
_sockaddr_storage" "$ac_includes_default"
+if test "x$ac_cv_type_struct_sockaddr_storage" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRUCT_SOCKADDR_STORAGE 1
@@ -42056,16 +22809,12 @@
=20
=20
 cv=3D`echo "struct addrinfo" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for struct addrinfo" >&5
-echo $ECHO_N "checking for struct addrinfo... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct addrinfo" >&5
+$as_echo_n "checking for struct addrinfo... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -42075,7 +22824,12 @@
 #endif
=20
 #include <sys/types.h>
+#ifdef HAVE_NETDB_H
 #include <netdb.h>
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -42084,93 +22838,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo struct addrinfo | sed 'y%abcdefghijklmnopqrstuvwx=
yz./- %ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for struct addrinfo" >&5
-echo $ECHO_N "checking for struct addrinfo... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_addrinfo+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef struct addrinfo ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_struct_addrinfo=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_addrinfo=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_addrinfo" >&5
-echo "${ECHO_T}$ac_cv_type_struct_addrinfo" >&6; }
-if test $ac_cv_type_struct_addrinfo =3D yes; then
+	ac_fn_c_check_type "$LINENO" "struct addrinfo" "ac_cv_type_struct_addrinf=
o" "$ac_includes_default"
+if test "x$ac_cv_type_struct_addrinfo" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRUCT_ADDRINFO 1
@@ -42190,16 +22872,12 @@
=20
=20
 cv=3D`echo "struct ifaddrs" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for struct ifaddrs" >&5
-echo $ECHO_N "checking for struct ifaddrs... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct ifaddrs" >&5
+$as_echo_n "checking for struct ifaddrs... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -42216,93 +22894,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo struct ifaddrs | sed 'y%abcdefghijklmnopqrstuvwxy=
z./- %ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for struct ifaddrs" >&5
-echo $ECHO_N "checking for struct ifaddrs... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_ifaddrs+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef struct ifaddrs ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_struct_ifaddrs=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_ifaddrs=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_ifaddrs" >&5
-echo "${ECHO_T}$ac_cv_type_struct_ifaddrs" >&6; }
-if test $ac_cv_type_struct_ifaddrs =3D yes; then
+	ac_fn_c_check_type "$LINENO" "struct ifaddrs" "ac_cv_type_struct_ifaddrs"=
 "$ac_includes_default"
+if test "x$ac_cv_type_struct_ifaddrs" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRUCT_IFADDRS 1
@@ -42322,16 +22928,12 @@
=20
=20
 cv=3D`echo "struct iovec" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for struct iovec" >&5
-echo $ECHO_N "checking for struct iovec... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct iovec" >&5
+$as_echo_n "checking for struct iovec... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -42351,93 +22953,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo struct iovec | sed 'y%abcdefghijklmnopqrstuvwxyz.=
/- %ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for struct iovec" >&5
-echo $ECHO_N "checking for struct iovec... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_iovec+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef struct iovec ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_struct_iovec=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_iovec=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_iovec" >&5
-echo "${ECHO_T}$ac_cv_type_struct_iovec" >&6; }
-if test $ac_cv_type_struct_iovec =3D yes; then
+	ac_fn_c_check_type "$LINENO" "struct iovec" "ac_cv_type_struct_iovec" "$a=
c_includes_default"
+if test "x$ac_cv_type_struct_iovec" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRUCT_IOVEC 1
@@ -42457,16 +22987,12 @@
=20
=20
 cv=3D`echo "struct msghdr" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for struct msghdr" >&5
-echo $ECHO_N "checking for struct msghdr... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct msghdr" >&5
+$as_echo_n "checking for struct msghdr... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -42476,8 +23002,12 @@
 #endif
=20
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
-
+#endif
+#ifdef HAVE_WS2TCPIP_H
+#include <ws2tcpip.h>
+#endif
 int
 main ()
 {
@@ -42486,93 +23016,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo struct msghdr | sed 'y%abcdefghijklmnopqrstuvwxyz=
./- %ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for struct msghdr" >&5
-echo $ECHO_N "checking for struct msghdr... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_msghdr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef struct msghdr ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_struct_msghdr=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_msghdr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_msghdr" >&5
-echo "${ECHO_T}$ac_cv_type_struct_msghdr" >&6; }
-if test $ac_cv_type_struct_msghdr =3D yes; then
+	ac_fn_c_check_type "$LINENO" "struct msghdr" "ac_cv_type_struct_msghdr" "=
$ac_includes_default"
+if test "x$ac_cv_type_struct_msghdr" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_STRUCT_MSGHDR 1
@@ -42592,25 +23050,21 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for struct winsize" >&5
-echo $ECHO_N "checking for struct winsize... $ECHO_C" >&6; }
-if test "${ac_cv_struct_winsize+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct winsize" >&5
+$as_echo_n "checking for struct winsize... " >&6; }
+if test "${ac_cv_struct_winsize+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 ac_cv_struct_winsize=3Dno
 for i in sys/termios.h sys/ioctl.h; do
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <$i>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "struct[ 	]*winsize" >/dev/null 2>&1; then
+  $EGREP "struct[ 	]*winsize" >/dev/null 2>&1; then :
   ac_cv_struct_winsize=3Dyes; break
 fi
 rm -f conftest*
@@ -42620,47 +23074,33 @@
=20
 if test "$ac_cv_struct_winsize" =3D "yes"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_WINSIZE 1
-_ACEOF
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_struct_winsize" >&5
-echo "${ECHO_T}$ac_cv_struct_winsize" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_WINSIZE 1" >>confdefs.h
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_winsize" >&5
+$as_echo "$ac_cv_struct_winsize" >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <termios.h>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "ws_xpixel" >/dev/null 2>&1; then
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_WS_XPIXEL 1
-_ACEOF
+  $EGREP "ws_xpixel" >/dev/null 2>&1; then :
+
+$as_echo "#define HAVE_WS_XPIXEL 1" >>confdefs.h
=20
 fi
 rm -f conftest*
=20
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <termios.h>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "ws_ypixel" >/dev/null 2>&1; then
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_WS_YPIXEL 1
-_ACEOF
+  $EGREP "ws_ypixel" >/dev/null 2>&1; then :
+
+$as_echo "#define HAVE_WS_YPIXEL 1" >>confdefs.h
=20
 fi
 rm -f conftest*
@@ -42669,17 +23109,13 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for struct spwd" >&5
-echo $ECHO_N "checking for struct spwd... $ECHO_C" >&6; }
-if test "${ac_cv_struct_spwd+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct spwd" >&5
+$as_echo_n "checking for struct spwd... " >&6; }
+if test "${ac_cv_struct_spwd+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <pwd.h>
@@ -42694,43 +23130,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_struct_spwd=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_struct_spwd=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-
-{ echo "$as_me:$LINENO: result: $ac_cv_struct_spwd" >&5
-echo "${ECHO_T}$ac_cv_struct_spwd" >&6; }
+  ac_cv_struct_spwd=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_spwd" >&5
+$as_echo "$ac_cv_struct_spwd" >&6; }
=20
 if test "$ac_cv_struct_spwd" =3D "yes"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_SPWD 1
-_ACEOF
+$as_echo "#define HAVE_STRUCT_SPWD 1" >>confdefs.h
=20
 fi
=20
@@ -42742,7 +23156,7 @@
=20
=20
 # Check whether --enable-socket-wrapper was given.
-if test "${enable_socket_wrapper+set}" =3D set; then
+if test "${enable_socket_wrapper+set}" =3D set; then :
   enableval=3D$enable_socket_wrapper;
 fi
=20
@@ -42757,9 +23171,7 @@
=20
 if test "x$enable_socket_wrapper" =3D xyes ; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define SOCKET_WRAPPER_REPLACE 1
-_ACEOF
+$as_echo "#define SOCKET_WRAPPER_REPLACE 1" >>confdefs.h
=20
 fi
=20
@@ -42774,14 +23186,12 @@
=20
=20
 # Check whether --enable-otp was given.
-if test "${enable_otp+set}" =3D set; then
+if test "${enable_otp+set}" =3D set; then :
   enableval=3D$enable_otp;
 fi
=20
 if test "$enable_otp" =3D yes -a "$db_type" =3D unknown; then
-	{ { echo "$as_me:$LINENO: error: OTP requires a NDBM/DB compatible librar=
y" >&5
-echo "$as_me: error: OTP requires a NDBM/DB compatible library" >&2;}
-   { (exit 1); exit 1; }; }
+	as_fn_error "OTP requires a NDBM/DB compatible library" "$LINENO" 5
 fi
 if test "$enable_otp" !=3D no; then
 	if test "$db_type" !=3D unknown; then
@@ -42792,17 +23202,15 @@
 fi
 if test "$enable_otp" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define OTP 1
-_ACEOF
+$as_echo "#define OTP 1" >>confdefs.h
=20
 	LIB_otp=3D'$(top_builddir)/lib/otp/libotp.la'
=20
 fi
-{ echo "$as_me:$LINENO: checking whether to enable OTP library" >&5
-echo $ECHO_N "checking whether to enable OTP library... $ECHO_C" >&6; }
-{ echo "$as_me:$LINENO: result: $enable_otp" >&5
-echo "${ECHO_T}$enable_otp" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable OTP li=
brary" >&5
+$as_echo_n "checking whether to enable OTP library... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_otp" >&5
+$as_echo "$enable_otp" >&6; }
  if test "$enable_otp" =3D yes; then
   OTP_TRUE=3D
   OTP_FALSE=3D'#'
@@ -42813,17 +23221,151 @@
=20
=20
=20
+
+for ac_header in dispatch/dispatch.h
+do :
+  ac_fn_c_check_header_mongrel "$LINENO" "dispatch/dispatch.h" "ac_cv_head=
er_dispatch_dispatch_h" "$ac_includes_default"
+if test "x$ac_cv_header_dispatch_dispatch_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DISPATCH_DISPATCH_H 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dispatch_async_f" >&5
+$as_echo_n "checking for dispatch_async_f... " >&6; }
+if test "${ac_cv_funclib_dispatch_async_f+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+if eval "test \"\$ac_cv_func_dispatch_async_f\" !=3D yes" ; then
+	ac_save_LIBS=3D"$LIBS"
+	for ac_lib in "" dispatch; do
+		case "$ac_lib" in
+		"") ;;
+		yes) ac_lib=3D"" ;;
+		no) continue ;;
+		-l*) ;;
+		*) ac_lib=3D"-l$ac_lib" ;;
+		esac
+		LIBS=3D" $ac_lib  $ac_save_LIBS"
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef HAVE_DISPATCH_DISPATCH_H
+#include <dispatch/dispatch.h>
+#endif
+int
+main ()
+{
+dispatch_async_f(0,0,0)
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "if test -n \"$ac_lib\";then ac_cv_funclib_dispatch_async_f=3D$ac_l=
ib; else ac_cv_funclib_dispatch_async_f=3Dyes; fi";break
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	done
+	eval "ac_cv_funclib_dispatch_async_f=3D\${ac_cv_funclib_dispatch_async_f-=
no}"
+	LIBS=3D"$ac_save_LIBS"
+fi
+
+fi
+
+
+eval "ac_res=3D\$ac_cv_funclib_dispatch_async_f"
+
+if false; then
+	for ac_func in dispatch_async_f
+do :
+  ac_fn_c_check_func "$LINENO" "dispatch_async_f" "ac_cv_func_dispatch_asy=
nc_f"
+if test "x$ac_cv_func_dispatch_async_f" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DISPATCH_ASYNC_F 1
+_ACEOF
+
+fi
+done
+
+fi
+# dispatch_async_f
+eval "ac_tr_func=3DHAVE_`echo dispatch_async_f | tr abcdefghijklmnopqrstuv=
wxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
+eval "ac_tr_lib=3DHAVE_LIB`echo $ac_res | sed -e 's/-l//' | tr abcdefghijk=
lmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
+eval "LIB_dispatch_async_f=3D$ac_res"
+
+case "$ac_res" in
+	yes)
+	eval "ac_cv_func_dispatch_async_f=3Dyes"
+	eval "LIB_dispatch_async_f=3D"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+	;;
+	no)
+	eval "ac_cv_func_dispatch_async_f=3Dno"
+	eval "LIB_dispatch_async_f=3D"
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+	;;
+	*)
+	eval "ac_cv_func_dispatch_async_f=3Dyes"
+	eval "ac_cv_lib_`echo "$ac_res" | sed 's/-l//'`=3Dyes"
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_func 1
+_ACEOF
+
+	cat >>confdefs.h <<_ACEOF
+#define $ac_tr_lib 1
+_ACEOF
+
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+if test "$ac_cv_func_dispatch_async_f" =3D yes ; then
+
+$as_echo "#define HAVE_GCD 1" >>confdefs.h
+
+    libdispatch=3Dyes
+else
+    libdispatch=3Dno
+fi
+
+ if test "$libdispatch" =3D yes; then
+  have_gcd_TRUE=3D
+  have_gcd_FALSE=3D'#'
+else
+  have_gcd_TRUE=3D'#'
+  have_gcd_FALSE=3D
+fi
+
+
+
+
+
 # Check whether --enable-osfc2 was given.
-if test "${enable_osfc2+set}" =3D set; then
+if test "${enable_osfc2+set}" =3D set; then :
   enableval=3D$enable_osfc2;
 fi
=20
 LIB_security=3D
 if test "$enable_osfc2" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_OSFC2 1
-_ACEOF
+$as_echo "#define HAVE_OSFC2 1" >>confdefs.h
=20
 	LIB_security=3D-lsecurity
 fi
@@ -42831,20 +23373,18 @@
=20
=20
 # Check whether --enable-mmap was given.
-if test "${enable_mmap+set}" =3D set; then
+if test "${enable_mmap+set}" =3D set; then :
   enableval=3D$enable_mmap;
 fi
=20
 if test "$enable_mmap" =3D "no"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NO_MMAP 1
-_ACEOF
+$as_echo "#define NO_MMAP 1" >>confdefs.h
=20
 fi
=20
 # Check whether --enable-afs-string-to-key was given.
-if test "${enable_afs_string_to_key+set}" =3D set; then
+if test "${enable_afs_string_to_key+set}" =3D set; then :
   enableval=3D$enable_afs_string_to_key;
 else
   enable_afs_string_to_key=3Dyes
@@ -42853,19 +23393,17 @@
=20
 if test "$enable_afs_string_to_key" =3D "yes"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define ENABLE_AFS_STRING_TO_KEY 1
-_ACEOF
+$as_echo "#define ENABLE_AFS_STRING_TO_KEY 1" >>confdefs.h
=20
 fi
=20
=20
 # Extract the first word of "nroff", so it can be a program name with args.
 set dummy nroff; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_path_NROFF+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_path_NROFF+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   case $NROFF in
   [\\/]* | ?:[\\/]*)
@@ -42877,14 +23415,14 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_path_NROFF=3D"$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
   ;;
@@ -42892,20 +23430,20 @@
 fi
 NROFF=3D$ac_cv_path_NROFF
 if test -n "$NROFF"; then
-  { echo "$as_me:$LINENO: result: $NROFF" >&5
-echo "${ECHO_T}$NROFF" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NROFF" >&5
+$as_echo "$NROFF" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
 # Extract the first word of "groff", so it can be a program name with args.
 set dummy groff; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_path_GROFF+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_path_GROFF+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   case $GROFF in
   [\\/]* | ?:[\\/]*)
@@ -42917,14 +23455,14 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_path_GROFF=3D"$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
   ;;
@@ -42932,26 +23470,25 @@
 fi
 GROFF=3D$ac_cv_path_GROFF
 if test -n "$GROFF"; then
-  { echo "$as_me:$LINENO: result: $GROFF" >&5
-echo "${ECHO_T}$GROFF" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-{ echo "$as_me:$LINENO: checking how to format man pages" >&5
-echo $ECHO_N "checking how to format man pages... $ECHO_C" >&6; }
-if test "${ac_cv_sys_man_format+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $GROFF" >&5
+$as_echo "$GROFF" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to format man pages"=
 >&5
+$as_echo_n "checking how to format man pages... " >&6; }
+if test "${ac_cv_sys_man_format+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   cat > conftest.1 << END
 .Dd January 1, 1970
 .Dt CONFTEST 1
 .Sh NAME
 .Nm conftest
-.Nd
-foobar
+.Nd foobar
 END
=20
 if test "$NROFF" ; then
@@ -42977,8 +23514,8 @@
 fi
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sys_man_format" >&5
-echo "${ECHO_T}$ac_cv_sys_man_format" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_man_format" >&5
+$as_echo "$ac_cv_sys_man_format" >&6; }
 if test "$ac_cv_sys_man_format"; then
 	CATMAN=3D"$ac_cv_sys_man_format"
=20
@@ -42991,10 +23528,10 @@
   CATMAN_FALSE=3D
 fi
=20
-{ echo "$as_me:$LINENO: checking extension of pre-formatted manual pages" =
>&5
-echo $ECHO_N "checking extension of pre-formatted manual pages... $ECHO_C"=
 >&6; }
-if test "${ac_cv_sys_catman_ext+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking extension of pre-formatt=
ed manual pages" >&5
+$as_echo_n "checking extension of pre-formatted manual pages... " >&6; }
+if test "${ac_cv_sys_catman_ext+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if grep _suffix /etc/man.conf > /dev/null 2>&1; then
 	ac_cv_sys_catman_ext=3D0
@@ -43003,8 +23540,8 @@
 fi
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_sys_catman_ext" >&5
-echo "${ECHO_T}$ac_cv_sys_catman_ext" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_catman_ext" >&5
+$as_echo "$ac_cv_sys_catman_ext" >&6; }
 if test "$ac_cv_sys_catman_ext" =3D number; then
 	CATMANEXT=3D'$$section'
 else
@@ -43016,17 +23553,15 @@
=20
=20
 # Check whether --with-readline was given.
-if test "${with_readline+set}" =3D set; then
+if test "${with_readline+set}" =3D set; then :
   withval=3D$with_readline;
 fi
=20
=20
 # Check whether --with-readline-lib was given.
-if test "${with_readline_lib+set}" =3D set; then
+if test "${with_readline_lib+set}" =3D set; then :
   withval=3D$with_readline_lib; if test "$withval" =3D "yes" -o "$withval"=
 =3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-readline-lib" >&5
-echo "$as_me: error: No argument for --with-readline-lib" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-readline-lib" "$LINENO" 5
 elif test "X$with_readline" =3D "X"; then
   with_readline=3Dyes
 fi
@@ -43034,11 +23569,9 @@
=20
=20
 # Check whether --with-readline-include was given.
-if test "${with_readline_include+set}" =3D set; then
+if test "${with_readline_include+set}" =3D set; then :
   withval=3D$with_readline_include; if test "$withval" =3D "yes" -o "$with=
val" =3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-readline-include=
" >&5
-echo "$as_me: error: No argument for --with-readline-include" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-readline-include" "$LINENO" 5
 elif test "X$with_readline" =3D "X"; then
   with_readline=3Dyes
 fi
@@ -43046,15 +23579,15 @@
=20
=20
 # Check whether --with-readline-config was given.
-if test "${with_readline_config+set}" =3D set; then
+if test "${with_readline_config+set}" =3D set; then :
   withval=3D$with_readline_config;
 fi
=20
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for readline" >&5
-echo $ECHO_N "checking for readline... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for readline" >&5
+$as_echo_n "checking for readline... " >&6; }
=20
 case "$with_readline" in
 yes|"") d=3D'' ;;
@@ -43118,156 +23651,119 @@
 	if test "$readline_cflags" -a "$readline_libs"; then
 		CFLAGS=3D"$readline_cflags $save_CFLAGS"
 		LIBS=3D"$readline_libs $save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		for ac_header in readline.h readline/readline.h
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
- #include <readline.h>
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+#if defined(HAVE_READLINE_READLINE_H)
+#include <readline/readline.h>
+#elif defined(HAVE_READLINE_H)
+#include <readline.h>
+#endif
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
=20
 			INCLUDE_readline=3D"$readline_cflags"
 			LIB_readline=3D"$readline_libs"
-			{ echo "$as_me:$LINENO: result: from $with_readline_config" >&5
-echo "${ECHO_T}from $with_readline_config" >&6; }
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: from $with_readline_co=
nfig" >&5
+$as_echo "from $with_readline_config" >&6; }
 			found=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	fi
 	if test "$found" =3D no; then
 		ires=3D lres=3D
 		for i in $header_dirs; do
 			CFLAGS=3D"-I$i $save_CFLAGS"
-			cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			for ac_header in readline.h readline/readline.h
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
- #include <readline.h>
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+#if defined(HAVE_READLINE_READLINE_H)
+#include <readline/readline.h>
+#elif defined(HAVE_READLINE_H)
+#include <readline.h>
+#endif
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
   ires=3D$i;break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 		done
 		for i in $lib_dirs; do
 			LIBS=3D"-L$i -lreadline  $save_LIBS"
-			cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
- #include <readline.h>
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+#if defined(HAVE_READLINE_READLINE_H)
+#include <readline/readline.h>
+#elif defined(HAVE_READLINE_H)
+#include <readline.h>
+#endif
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
   lres=3D$i;break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 		done
 		if test "$ires" -a "$lres" -a "$with_readline" !=3D "no"; then
 			INCLUDE_readline=3D"-I$ires"
 			LIB_readline=3D"-L$lres -lreadline "
 			found=3Dyes
-			{ echo "$as_me:$LINENO: result: headers $ires, libraries $lres" >&5
-echo "${ECHO_T}headers $ires, libraries $lres" >&6; }
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: headers $ires, librari=
es $lres" >&5
+$as_echo "headers $ires, libraries $lres" >&6; }
 		fi
 	fi
 	CFLAGS=3D"$save_CFLAGS"
@@ -43285,28 +23781,270 @@
 	with_readline=3Dno
 	INCLUDE_readline=3D
 	LIB_readline=3D
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+
+
+
+
+
+# Check whether --with-libedit was given.
+if test "${with_libedit+set}" =3D set; then :
+  withval=3D$with_libedit;
+fi
+
+
+# Check whether --with-libedit-lib was given.
+if test "${with_libedit_lib+set}" =3D set; then :
+  withval=3D$with_libedit_lib; if test "$withval" =3D "yes" -o "$withval" =
=3D "no"; then
+  as_fn_error "No argument for --with-libedit-lib" "$LINENO" 5
+elif test "X$with_libedit" =3D "X"; then
+  with_libedit=3Dyes
+fi
+fi
+
+
+# Check whether --with-libedit-include was given.
+if test "${with_libedit_include+set}" =3D set; then :
+  withval=3D$with_libedit_include; if test "$withval" =3D "yes" -o "$withv=
al" =3D "no"; then
+  as_fn_error "No argument for --with-libedit-include" "$LINENO" 5
+elif test "X$with_libedit" =3D "X"; then
+  with_libedit=3Dyes
+fi
+fi
+
+
+# Check whether --with-libedit-config was given.
+if test "${with_libedit_config+set}" =3D set; then :
+  withval=3D$with_libedit_config;
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for libedit" >&5
+$as_echo_n "checking for libedit... " >&6; }
+
+case "$with_libedit" in
+yes|"") d=3D'' ;;
+no)	d=3D ;;
+*)	d=3D"$with_libedit" ;;
+esac
+
+header_dirs=3D
+lib_dirs=3D
+for i in $d; do
+	if test "$with_libedit_include" =3D ""; then
+		if test -d "$i/include/libedit"; then
+			header_dirs=3D"$header_dirs $i/include/libedit"
+		fi
+		if test -d "$i/include"; then
+			header_dirs=3D"$header_dirs $i/include"
+		fi
+	fi
+	if test "$with_libedit_lib" =3D ""; then
+		if test -d "$i/lib$abilibdirext"; then
+			lib_dirs=3D"$lib_dirs $i/lib$abilibdirext"
+		fi
+	fi
+done
+
+if test "$with_libedit_include"; then
+	header_dirs=3D"$with_libedit_include $header_dirs"
+fi
+if test "$with_libedit_lib"; then
+	lib_dirs=3D"$with_libedit_lib $lib_dirs"
+fi
+
+if test "$with_libedit_config" =3D ""; then
+	with_libedit_config=3D''
+fi
+
+libedit_cflags=3D
+libedit_libs=3D
+
+case "$with_libedit_config" in
+yes|no|""|"")
+	if test -f $with_libedit/bin/ ; then
+		with_libedit_config=3D$with_libedit/bin/
+	fi
+	;;
+esac
+
+case "$with_libedit_config" in
+yes|no|"")
+	;;
+*)
+	libedit_cflags=3D"`$with_libedit_config --cflags 2>&1`"
+	libedit_libs=3D"`$with_libedit_config --libs 2>&1`"
+	;;
+esac
+
+found=3Dno
+if test "$with_libedit" !=3D no; then
+	save_CFLAGS=3D"$CFLAGS"
+	save_LIBS=3D"$LIBS"
+	if test "$libedit_cflags" -a "$libedit_libs"; then
+		CFLAGS=3D"$libedit_cflags $save_CFLAGS"
+		LIBS=3D"$libedit_libs $save_LIBS"
+		for ac_header in readline.h readline/readline.h
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+#if defined(HAVE_READLINE_READLINE_H)
+#include <readline/readline.h>
+#elif defined(HAVE_READLINE_H)
+#include <readline.h>
+#endif
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+
+			INCLUDE_libedit=3D"$libedit_cflags"
+			LIB_libedit=3D"$libedit_libs"
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: from $with_libedit_con=
fig" >&5
+$as_echo "from $with_libedit_config" >&6; }
+			found=3Dyes
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+	fi
+	if test "$found" =3D no; then
+		ires=3D lres=3D
+		for i in $header_dirs; do
+			CFLAGS=3D"-I$i $save_CFLAGS"
+			for ac_header in readline.h readline/readline.h
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+#if defined(HAVE_READLINE_READLINE_H)
+#include <readline/readline.h>
+#elif defined(HAVE_READLINE_H)
+#include <readline.h>
+#endif
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ires=3D$i;break
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+		done
+		for i in $lib_dirs; do
+			LIBS=3D"-L$i -ledit  $save_LIBS"
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+#if defined(HAVE_READLINE_READLINE_H)
+#include <readline/readline.h>
+#elif defined(HAVE_READLINE_H)
+#include <readline.h>
+#endif
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  lres=3D$i;break
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+		done
+		if test "$ires" -a "$lres" -a "$with_libedit" !=3D "no"; then
+			INCLUDE_libedit=3D"-I$ires"
+			LIB_libedit=3D"-L$lres -ledit "
+			found=3Dyes
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: headers $ires, librari=
es $lres" >&5
+$as_echo "headers $ires, libraries $lres" >&6; }
+		fi
+	fi
+	CFLAGS=3D"$save_CFLAGS"
+	LIBS=3D"$save_LIBS"
+fi
+
+if test "$found" =3D yes; then
+
+cat >>confdefs.h <<_ACEOF
+#define LIBEDIT 1
+_ACEOF
+
+	with_libedit=3Dyes
+else
+	with_libedit=3Dno
+	INCLUDE_libedit=3D
+	LIB_libedit=3D
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+
+
+
+
+
+subdirs=3D"$subdirs lib/libedit"
=20
=20
=20
=20
 # Check whether --with-hesiod was given.
-if test "${with_hesiod+set}" =3D set; then
+if test "${with_hesiod+set}" =3D set; then :
   withval=3D$with_hesiod;
 fi
=20
=20
 # Check whether --with-hesiod-lib was given.
-if test "${with_hesiod_lib+set}" =3D set; then
+if test "${with_hesiod_lib+set}" =3D set; then :
   withval=3D$with_hesiod_lib; if test "$withval" =3D "yes" -o "$withval" =
=3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-hesiod-lib" >&5
-echo "$as_me: error: No argument for --with-hesiod-lib" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-hesiod-lib" "$LINENO" 5
 elif test "X$with_hesiod" =3D "X"; then
   with_hesiod=3Dyes
 fi
@@ -43314,11 +24052,9 @@
=20
=20
 # Check whether --with-hesiod-include was given.
-if test "${with_hesiod_include+set}" =3D set; then
+if test "${with_hesiod_include+set}" =3D set; then :
   withval=3D$with_hesiod_include; if test "$withval" =3D "yes" -o "$withva=
l" =3D "no"; then
-  { { echo "$as_me:$LINENO: error: No argument for --with-hesiod-include" =
>&5
-echo "$as_me: error: No argument for --with-hesiod-include" >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "No argument for --with-hesiod-include" "$LINENO" 5
 elif test "X$with_hesiod" =3D "X"; then
   with_hesiod=3Dyes
 fi
@@ -43326,15 +24062,15 @@
=20
=20
 # Check whether --with-hesiod-config was given.
-if test "${with_hesiod_config+set}" =3D set; then
+if test "${with_hesiod_config+set}" =3D set; then :
   withval=3D$with_hesiod_config;
 fi
=20
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for hesiod" >&5
-echo $ECHO_N "checking for hesiod... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for hesiod" >&5
+$as_echo_n "checking for hesiod... " >&6; }
=20
 case "$with_hesiod" in
 yes|"") d=3D'' ;;
@@ -43398,11 +24134,8 @@
 	if test "$hesiod_cflags" -a "$hesiod_libs"; then
 		CFLAGS=3D"$hesiod_cflags $save_CFLAGS"
 		LIBS=3D"$hesiod_libs $save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <hesiod.h>
 int
@@ -43413,49 +24146,23 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
=20
 			INCLUDE_hesiod=3D"$hesiod_cflags"
 			LIB_hesiod=3D"$hesiod_libs"
-			{ echo "$as_me:$LINENO: result: from $with_hesiod_config" >&5
-echo "${ECHO_T}from $with_hesiod_config" >&6; }
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: from $with_hesiod_conf=
ig" >&5
+$as_echo "from $with_hesiod_config" >&6; }
 			found=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	fi
 	if test "$found" =3D no; then
 		ires=3D lres=3D
 		for i in $header_dirs; do
 			CFLAGS=3D"-I$i $save_CFLAGS"
-			cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <hesiod.h>
 int
@@ -43466,40 +24173,14 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ires=3D$i;break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 		done
 		for i in $lib_dirs; do
 			LIBS=3D"-L$i -lhesiod  $save_LIBS"
-			cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+			cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <hesiod.h>
 int
@@ -43510,41 +24191,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   lres=3D$i;break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 		done
 		if test "$ires" -a "$lres" -a "$with_hesiod" !=3D "no"; then
 			INCLUDE_hesiod=3D"-I$ires"
 			LIB_hesiod=3D"-L$lres -lhesiod "
 			found=3Dyes
-			{ echo "$as_me:$LINENO: result: headers $ires, libraries $lres" >&5
-echo "${ECHO_T}headers $ires, libraries $lres" >&6; }
+			{ $as_echo "$as_me:${as_lineno-$LINENO}: result: headers $ires, librari=
es $lres" >&5
+$as_echo "headers $ires, libraries $lres" >&6; }
 		fi
 	fi
 	CFLAGS=3D"$save_CFLAGS"
@@ -43562,8 +24220,8 @@
 	with_hesiod=3Dno
 	INCLUDE_hesiod=3D
 	LIB_hesiod=3D
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -43572,25 +24230,21 @@
=20
=20
 # Check whether --enable-bigendian was given.
-if test "${enable_bigendian+set}" =3D set; then
+if test "${enable_bigendian+set}" =3D set; then :
   enableval=3D$enable_bigendian; krb_cv_c_bigendian=3Dyes
 fi
=20
 # Check whether --enable-littleendian was given.
-if test "${enable_littleendian+set}" =3D set; then
+if test "${enable_littleendian+set}" =3D set; then :
   enableval=3D$enable_littleendian; krb_cv_c_bigendian=3Dno
 fi
=20
-{ echo "$as_me:$LINENO: checking whether byte order is known at compile ti=
me" >&5
-echo $ECHO_N "checking whether byte order is known at compile time... $ECH=
O_C" >&6; }
-if test "${krb_cv_c_bigendian_compile+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte order is kn=
own at compile time" >&5
+$as_echo_n "checking whether byte order is known at compile time... " >&6;=
 }
+if test "${krb_cv_c_bigendian_compile+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -43599,47 +24253,23 @@
  bogus endian macros
 #endif
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   krb_cv_c_bigendian_compile=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	krb_cv_c_bigendian_compile=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $krb_cv_c_bigendian_compile" >&5
-echo "${ECHO_T}$krb_cv_c_bigendian_compile" >&6; }
-{ echo "$as_me:$LINENO: checking whether byte ordering is bigendian" >&5
-echo $ECHO_N "checking whether byte ordering is bigendian... $ECHO_C" >&6;=
 }
-if test "${krb_cv_c_bigendian+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  krb_cv_c_bigendian_compile=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $krb_cv_c_bigendian_compi=
le" >&5
+$as_echo "$krb_cv_c_bigendian_compile" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is=
 bigendian" >&5
+$as_echo_n "checking whether byte ordering is bigendian... " >&6; }
+if test "${krb_cv_c_bigendian+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
   if test "$krb_cv_c_bigendian_compile" =3D "yes"; then
-    cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -43648,43 +24278,17 @@
   not big endian
 #endif
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   krb_cv_c_bigendian=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	krb_cv_c_bigendian=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  else
-    if test "$cross_compiling" =3D yes; then
-  { { echo "$as_me:$LINENO: error: specify either --enable-bigendian or --=
enable-littleendian" >&5
-echo "$as_me: error: specify either --enable-bigendian or --enable-littlee=
ndian" >&2;}
-   { (exit 1); exit 1; }; }
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  krb_cv_c_bigendian=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  else
+    if test "$cross_compiling" =3D yes; then :
+  as_fn_error "specify either --enable-bigendian or --enable-littleendian"=
 "$LINENO" 5
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 main (int argc, char **argv) {
       /* Are we little or big endian?  From Harbison&Steele.  */
@@ -43697,71 +24301,38 @@
     exit (u.c[sizeof (long) - 1] =3D=3D 1);
   }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   krb_cv_c_bigendian=3Dno
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-krb_cv_c_bigendian=3Dyes
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-  fi
-
-fi
-{ echo "$as_me:$LINENO: result: $krb_cv_c_bigendian" >&5
-echo "${ECHO_T}$krb_cv_c_bigendian" >&6; }
+  krb_cv_c_bigendian=3Dyes
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+  fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $krb_cv_c_bigendian" >&5
+$as_echo "$krb_cv_c_bigendian" >&6; }
 if test "$krb_cv_c_bigendian" =3D "yes"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define WORDS_BIGENDIAN 1
-_ACEOF
+$as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h
 fi
 if test "$krb_cv_c_bigendian_compile" =3D "yes"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define ENDIANESS_IN_SYS_PARAM_H 1
-_ACEOF
-fi
-
-
-
-{ echo "$as_me:$LINENO: checking for inline" >&5
-echo $ECHO_N "checking for inline... $ECHO_C" >&6; }
-if test "${ac_cv_c_inline+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+$as_echo "#define ENDIANESS_IN_SYS_PARAM_H 1" >>confdefs.h
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5
+$as_echo_n "checking for inline... " >&6; }
+if test "${ac_cv_c_inline+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_cv_c_inline=3Dno
 for ac_kw in inline __inline__ __inline; do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #ifndef __cplusplus
 typedef int foo_t;
@@ -43770,39 +24341,16 @@
 #endif
=20
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_c_inline=3D$ac_kw
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
   test "$ac_cv_c_inline" !=3D no && break
 done
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_c_inline" >&5
-echo "${ECHO_T}$ac_cv_c_inline" >&6; }
-
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5
+$as_echo "$ac_cv_c_inline" >&6; }
=20
 case $ac_cv_c_inline in
   inline | yes) ;;
@@ -43820,559 +24368,12 @@
 esac
=20
=20
-
-
-
-
-{ echo "$as_me:$LINENO: checking for dlopen" >&5
-echo $ECHO_N "checking for dlopen... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_dlopen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-if eval "test \"\$ac_cv_func_dlopen\" !=3D yes" ; then
-	ac_save_LIBS=3D"$LIBS"
-	for ac_lib in "" dl; do
-		case "$ac_lib" in
-		"") ;;
-		yes) ac_lib=3D"" ;;
-		no) continue ;;
-		-l*) ;;
-		*) ac_lib=3D"-l$ac_lib" ;;
-		esac
-		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-#ifdef HAVE_DLFCN_H
-#include <dlfcn.h>
-#endif
-int
-main ()
-{
-dlopen(0,0)
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "if test -n \"$ac_lib\";then ac_cv_funclib_dlopen=3D$ac_lib; else a=
c_cv_funclib_dlopen=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-	done
-	eval "ac_cv_funclib_dlopen=3D\${ac_cv_funclib_dlopen-no}"
-	LIBS=3D"$ac_save_LIBS"
-fi
-
-fi
-
-
-eval "ac_res=3D\$ac_cv_funclib_dlopen"
-
-if false; then
-
-for ac_func in dlopen
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-fi
-# dlopen
-eval "ac_tr_func=3DHAVE_`echo dlopen | tr abcdefghijklmnopqrstuvwxyz ABCDE=
FGHIJKLMNOPQRSTUVWXYZ`"
-eval "ac_tr_lib=3DHAVE_LIB`echo $ac_res | sed -e 's/-l//' | tr abcdefghijk=
lmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
-eval "LIB_dlopen=3D$ac_res"
-
-case "$ac_res" in
-	yes)
-	eval "ac_cv_func_dlopen=3Dyes"
-	eval "LIB_dlopen=3D"
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_func 1
-_ACEOF
-
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-	;;
-	no)
-	eval "ac_cv_func_dlopen=3Dno"
-	eval "LIB_dlopen=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-	;;
-	*)
-	eval "ac_cv_func_dlopen=3Dyes"
-	eval "ac_cv_lib_`echo "$ac_res" | sed 's/-l//'`=3Dyes"
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_func 1
-_ACEOF
-
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_lib 1
-_ACEOF
-
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-	 if test "$ac_cv_funclib_dlopen" !=3D no; then
-  HAVE_DLOPEN_TRUE=3D
-  HAVE_DLOPEN_FALSE=3D'#'
-else
-  HAVE_DLOPEN_TRUE=3D'#'
-  HAVE_DLOPEN_FALSE=3D
-fi
-
-
-
-
-aix=3Dno
-case "$host" in
-*-*-aix3*)
-	aix=3D3
-	;;
-*-*-aix4*|*-*-aix5*)
-	aix=3D4
-	;;
-esac
-
- if test "$aix" !=3D no; then
-  AIX_TRUE=3D
-  AIX_FALSE=3D'#'
-else
-  AIX_TRUE=3D'#'
-  AIX_FALSE=3D
-fi
- if test "$aix" =3D 4; then
-  AIX4_TRUE=3D
-  AIX4_FALSE=3D'#'
-else
-  AIX4_TRUE=3D'#'
-  AIX4_FALSE=3D
-fi
-
-
-
-# Check whether --enable-dynamic-afs was given.
-if test "${enable_dynamic_afs+set}" =3D set; then
-  enableval=3D$enable_dynamic_afs;
-fi
-
-
-if test "$aix" !=3D no; then
-	if test "$enable_dynamic_afs" !=3D no; then
-
-		if test "$ac_cv_func_dlopen" =3D no; then
-
-
-
-{ echo "$as_me:$LINENO: checking for loadquery" >&5
-echo $ECHO_N "checking for loadquery... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_loadquery+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-if eval "test \"\$ac_cv_func_loadquery\" !=3D yes" ; then
-	ac_save_LIBS=3D"$LIBS"
-	for ac_lib in "" ld; do
-		case "$ac_lib" in
-		"") ;;
-		yes) ac_lib=3D"" ;;
-		no) continue ;;
-		-l*) ;;
-		*) ac_lib=3D"-l$ac_lib" ;;
-		esac
-		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-loadquery()
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "if test -n \"$ac_lib\";then ac_cv_funclib_loadquery=3D$ac_lib; els=
e ac_cv_funclib_loadquery=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-	done
-	eval "ac_cv_funclib_loadquery=3D\${ac_cv_funclib_loadquery-no}"
-	LIBS=3D"$ac_save_LIBS"
-fi
-
-fi
-
-
-eval "ac_res=3D\$ac_cv_funclib_loadquery"
-
-if false; then
-
-for ac_func in loadquery
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-fi
-# loadquery
-eval "ac_tr_func=3DHAVE_`echo loadquery | tr abcdefghijklmnopqrstuvwxyz AB=
CDEFGHIJKLMNOPQRSTUVWXYZ`"
-eval "ac_tr_lib=3DHAVE_LIB`echo $ac_res | sed -e 's/-l//' | tr abcdefghijk=
lmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
-eval "LIB_loadquery=3D$ac_res"
-
-case "$ac_res" in
-	yes)
-	eval "ac_cv_func_loadquery=3Dyes"
-	eval "LIB_loadquery=3D"
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_func 1
-_ACEOF
-
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-	;;
-	no)
-	eval "ac_cv_func_loadquery=3Dno"
-	eval "LIB_loadquery=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-	;;
-	*)
-	eval "ac_cv_func_loadquery=3Dyes"
-	eval "ac_cv_lib_`echo "$ac_res" | sed 's/-l//'`=3Dyes"
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_func 1
-_ACEOF
-
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_lib 1
-_ACEOF
-
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-		fi
-		if test "$ac_cv_func_dlopen" !=3D no; then
-			AIX_EXTRA_KAFS=3D'$(LIB_dlopen)'
-		elif test "$ac_cv_func_loadquery" !=3D no; then
-			AIX_EXTRA_KAFS=3D'$(LIB_loadquery)'
-		else
-			{ echo "$as_me:$LINENO: not using dynloaded AFS library" >&5
-echo "$as_me: not using dynloaded AFS library" >&6;}
-			AIX_EXTRA_KAFS=3D
-			enable_dynamic_afs=3Dno
-		fi
-	else
-		AIX_EXTRA_KAFS=3D
-	fi
-fi
-
- if test "$enable_dynamic_afs" !=3D no; then
-  AIX_DYNAMIC_AFS_TRUE=3D
-  AIX_DYNAMIC_AFS_FALSE=3D'#'
-else
-  AIX_DYNAMIC_AFS_TRUE=3D'#'
-  AIX_DYNAMIC_AFS_FALSE=3D
-fi
-
-
-
-
-
-
-irix=3Dno
-case "$host" in
-*-*-irix4*)
-
-cat >>confdefs.h <<\_ACEOF
-#define IRIX4 1
-_ACEOF
-
-	irix=3Dyes
-	;;
-*-*-irix*)
-	irix=3Dyes
-	;;
-esac
- if test "$irix" !=3D no; then
-  IRIX_TRUE=3D
-  IRIX_FALSE=3D'#'
-else
-  IRIX_TRUE=3D'#'
-  IRIX_FALSE=3D
-fi
-
-
-
-
-
-sunos=3Dno
-case "$host" in
-*-*-sunos4*)
-	sunos=3D40
-	;;
-*-*-solaris2.7)
-	sunos=3D57
-	;;
-*-*-solaris2.[89] | *-*-solaris2.10)
-	sunos=3D58
-	;;
-*-*-solaris2*)
-	sunos=3D50
-	;;
-esac
-if test "$sunos" !=3D no; then
-
-cat >>confdefs.h <<_ACEOF
-#define SunOS $sunos
-_ACEOF
-
-fi
-
-
-{ echo "$as_me:$LINENO: checking for X" >&5
-echo $ECHO_N "checking for X... $ECHO_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for X" >&5
+$as_echo_n "checking for X... " >&6; }
=20
=20
 # Check whether --with-x was given.
-if test "${with_x+set}" =3D set; then
+if test "${with_x+set}" =3D set; then :
   withval=3D$with_x;
 fi
=20
@@ -44382,11 +24383,9 @@
   have_x=3Ddisabled
 else
   case $x_includes,$x_libraries in #(
-    *\'*) { { echo "$as_me:$LINENO: error: Cannot use X directory names co=
ntaining '" >&5
-echo "$as_me: error: Cannot use X directory names containing '" >&2;}
-   { (exit 1); exit 1; }; };; #(
-    *,NONE | NONE,*) if test "${ac_cv_have_x+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+    *\'*) as_fn_error "cannot use X directory names containing '" "$LINENO=
" 5;; #(
+    *,NONE | NONE,*) if test "${ac_cv_have_x+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   # One or both of the vars are not set, and there is no cached value.
 ac_x_includes=3Dno ac_x_libraries=3Dno
@@ -44407,7 +24406,7 @@
       eval "ac_im_$ac_var=3D\`\${MAKE-make} $ac_var 2>/dev/null | sed -n '=
s/^$ac_var=3D//p'\`"
     done
     # Open Windows xmkmf reportedly sets LIBDIR instead of USRLIBDIR.
-    for ac_extension in a so sl; do
+    for ac_extension in a so sl dylib la dll; do
       if test ! -f "$ac_im_usrlibdir/libX11.$ac_extension" &&
 	 test -f "$ac_im_libdir/libX11.$ac_extension"; then
 	ac_im_usrlibdir=3D$ac_im_libdir; break
@@ -44421,7 +24420,7 @@
 	*) test -f "$ac_im_incroot/X11/Xos.h" && ac_x_includes=3D$ac_im_incroot;;
     esac
     case $ac_im_usrlibdir in
-	/usr/lib | /lib) ;;
+	/usr/lib | /usr/lib64 | /lib | /lib64) ;;
 	*) test -d "$ac_im_usrlibdir" && ac_x_libraries=3D$ac_im_usrlibdir ;;
     esac
   fi
@@ -44433,21 +24432,25 @@
 # Check X11 before X11Rn because it is often a symlink to the current rele=
ase.
 ac_x_header_dirs=3D'
 /usr/X11/include
+/usr/X11R7/include
 /usr/X11R6/include
 /usr/X11R5/include
 /usr/X11R4/include
=20
 /usr/include/X11
+/usr/include/X11R7
 /usr/include/X11R6
 /usr/include/X11R5
 /usr/include/X11R4
=20
 /usr/local/X11/include
+/usr/local/X11R7/include
 /usr/local/X11R6/include
 /usr/local/X11R5/include
 /usr/local/X11R4/include
=20
 /usr/local/include/X11
+/usr/local/include/X11R7
 /usr/local/include/X11R6
 /usr/local/include/X11R5
 /usr/local/include/X11R4
@@ -44469,36 +24472,14 @@
 if test "$ac_x_includes" =3D no; then
   # Guess where to find include files, by looking for Xlib.h.
   # First, try using that file with no special directory specified.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <X11/Xlib.h>
 _ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
+if ac_fn_c_try_cpp "$LINENO"; then :
   # We can compile using X headers with no special include directory.
 ac_x_includes=3D
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
   for ac_dir in $ac_x_header_dirs; do
   if test -r "$ac_dir/X11/Xlib.h"; then
     ac_x_includes=3D$ac_dir
@@ -44506,7 +24487,6 @@
   fi
 done
 fi
-
 rm -f conftest.err conftest.$ac_ext
 fi # $ac_x_includes =3D no
=20
@@ -44516,11 +24496,7 @@
   # Don't add to $LIBS permanently.
   ac_save_LIBS=3D$LIBS
   LIBS=3D"-lX11 $LIBS"
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <X11/Xlib.h>
 int
@@ -44531,36 +24507,16 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   LIBS=3D$ac_save_LIBS
 # We can link X programs with no special library path.
 ac_x_libraries=3D
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	LIBS=3D$ac_save_LIBS
-for ac_dir in `echo "$ac_x_includes $ac_x_header_dirs" | sed s/include/lib=
/g`
+  LIBS=3D$ac_save_LIBS
+for ac_dir in `$as_echo "$ac_x_includes $ac_x_header_dirs" | sed s/include=
/lib/g`
 do
   # Don't even attempt the hair of trying to link an X program!
-  for ac_extension in a so sl; do
+  for ac_extension in a so sl dylib la dll; do
     if test -r "$ac_dir/libX11.$ac_extension"; then
       ac_x_libraries=3D$ac_dir
       break 2
@@ -44568,9 +24524,8 @@
   done
 done
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 fi # $ac_x_libraries =3D no
=20
 case $ac_x_includes,$ac_x_libraries in #(
@@ -44591,8 +24546,8 @@
 fi # $with_x !=3D no
=20
 if test "$have_x" !=3D yes; then
-  { echo "$as_me:$LINENO: result: $have_x" >&5
-echo "${ECHO_T}$have_x" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_x" >&5
+$as_echo "$have_x" >&6; }
   no_x=3Dyes
 else
   # If each of the values was on the command line, it overrides each guess.
@@ -44602,17 +24557,15 @@
   ac_cv_have_x=3D"have_x=3Dyes\
 	ac_x_includes=3D'$x_includes'\
 	ac_x_libraries=3D'$x_libraries'"
-  { echo "$as_me:$LINENO: result: libraries $x_libraries, headers $x_inclu=
des" >&5
-echo "${ECHO_T}libraries $x_libraries, headers $x_includes" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $x_libraries,=
 headers $x_includes" >&5
+$as_echo "libraries $x_libraries, headers $x_includes" >&6; }
 fi
=20
=20
 if test "$no_x" =3D yes; then
   # Not all programs may use this symbol, but it does not hurt to define i=
t.
=20
-cat >>confdefs.h <<\_ACEOF
-#define X_DISPLAY_MISSING 1
-_ACEOF
+$as_echo "#define X_DISPLAY_MISSING 1" >>confdefs.h
=20
   X_CFLAGS=3D X_PRE_LIBS=3D X_LIBS=3D X_EXTRA_LIBS=3D
 else
@@ -44625,102 +24578,52 @@
     X_LIBS=3D"$X_LIBS -L$x_libraries"
     # For Solaris; some versions of Sun CC require a space after -R and
     # others require no space.  Words are not sufficient . . . .
-    { echo "$as_me:$LINENO: checking whether -R must be followed by a spac=
e" >&5
-echo $ECHO_N "checking whether -R must be followed by a space... $ECHO_C" =
>&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -R must be f=
ollowed by a space" >&5
+$as_echo_n "checking whether -R must be followed by a space... " >&6; }
     ac_xsave_LIBS=3D$LIBS; LIBS=3D"$LIBS -R$x_libraries"
     ac_xsave_c_werror_flag=3D$ac_c_werror_flag
     ac_c_werror_flag=3Dyes
-    cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
        X_LIBS=3D"$X_LIBS -R$x_libraries"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	LIBS=3D"$ac_xsave_LIBS -R $x_libraries"
-       cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+  LIBS=3D"$ac_xsave_LIBS -R $x_libraries"
+       cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	  X_LIBS=3D"$X_LIBS -R $x_libraries"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	{ echo "$as_me:$LINENO: result: neither works" >&5
-echo "${ECHO_T}neither works" >&6; }
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: neither works" >&5
+$as_echo "neither works" >&6; }
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
     ac_c_werror_flag=3D$ac_xsave_c_werror_flag
     LIBS=3D$ac_xsave_LIBS
   fi
@@ -44736,11 +24639,7 @@
     # libraries were built with DECnet support.  And Karl Berry says
     # the Alpha needs dnet_stub (dnet does not exist).
     ac_xsave_LIBS=3D"$LIBS"; LIBS=3D"$LIBS $X_LIBS -lX11"
-    cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -44758,41 +24657,17 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	{ echo "$as_me:$LINENO: checking for dnet_ntoa in -ldnet" >&5
-echo $ECHO_N "checking for dnet_ntoa in -ldnet... $ECHO_C" >&6; }
-if test "${ac_cv_lib_dnet_dnet_ntoa+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if ac_fn_c_try_link "$LINENO"; then :
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dnet_ntoa in -ldne=
t" >&5
+$as_echo_n "checking for dnet_ntoa in -ldnet... " >&6; }
+if test "${ac_cv_lib_dnet_dnet_ntoa+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
 LIBS=3D"-ldnet  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -44810,55 +24685,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_lib_dnet_dnet_ntoa=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_dnet_dnet_ntoa=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_lib_dnet_dnet_ntoa=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dnet_dnet_ntoa" >&5
-echo "${ECHO_T}$ac_cv_lib_dnet_dnet_ntoa" >&6; }
-if test $ac_cv_lib_dnet_dnet_ntoa =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dnet_dnet_ntoa=
" >&5
+$as_echo "$ac_cv_lib_dnet_dnet_ntoa" >&6; }
+if test "x$ac_cv_lib_dnet_dnet_ntoa" =3D x""yes; then :
   X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -ldnet"
 fi
=20
     if test $ac_cv_lib_dnet_dnet_ntoa =3D no; then
-      { echo "$as_me:$LINENO: checking for dnet_ntoa in -ldnet_stub" >&5
-echo $ECHO_N "checking for dnet_ntoa in -ldnet_stub... $ECHO_C" >&6; }
-if test "${ac_cv_lib_dnet_stub_dnet_ntoa+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dnet_ntoa in -=
ldnet_stub" >&5
+$as_echo_n "checking for dnet_ntoa in -ldnet_stub... " >&6; }
+if test "${ac_cv_lib_dnet_stub_dnet_ntoa+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
 LIBS=3D"-ldnet_stub  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -44876,47 +24726,25 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_lib_dnet_stub_dnet_ntoa=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_dnet_stub_dnet_ntoa=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_lib_dnet_stub_dnet_ntoa=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_dnet_stub_dnet_ntoa" >&5
-echo "${ECHO_T}$ac_cv_lib_dnet_stub_dnet_ntoa" >&6; }
-if test $ac_cv_lib_dnet_stub_dnet_ntoa =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dnet_stub_dnet=
_ntoa" >&5
+$as_echo "$ac_cv_lib_dnet_stub_dnet_ntoa" >&6; }
+if test "x$ac_cv_lib_dnet_stub_dnet_ntoa" =3D x""yes; then :
   X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -ldnet_stub"
 fi
=20
     fi
 fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
     LIBS=3D"$ac_xsave_LIBS"
=20
     # msh at cis.ufl.edu says -lnsl (and -lsocket) are needed for his 386/AT,
@@ -44927,33 +24755,21 @@
     # on Irix 5.2, according to T.E. Dickey.
     # The functions gethostbyname, getservbyname, and inet_addr are
     # in -lbsd on LynxOS 3.0.1/i386, according to Lars Hecking.
-    { echo "$as_me:$LINENO: checking for gethostbyname" >&5
-echo $ECHO_N "checking for gethostbyname... $ECHO_C" >&6; }
-if test "${ac_cv_func_gethostbyname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define gethostbyname to an innocuous variant, in case <limits.h> declar=
es gethostbyname.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define gethostbyname innocuous_gethostbyname
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char gethostbyname (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef gethostbyname
+    ac_fn_c_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname"
+if test "x$ac_cv_func_gethostbyname" =3D x""yes; then :
+
+fi
+
+    if test $ac_cv_func_gethostbyname =3D no; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname =
in -lnsl" >&5
+$as_echo_n "checking for gethostbyname in -lnsl... " >&6; }
+if test "${ac_cv_lib_nsl_gethostbyname+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=3D$LIBS
+LIBS=3D"-lnsl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
@@ -44962,13 +24778,6 @@
 extern "C"
 #endif
 char gethostbyname ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_gethostbyname || defined __stub___gethostbyname
-choke me
-#endif
-
 int
 main ()
 {
@@ -44977,51 +24786,30 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_gethostbyname=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_gethostbyname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_gethostbyname" >&5
-echo "${ECHO_T}$ac_cv_func_gethostbyname" >&6; }
-
-    if test $ac_cv_func_gethostbyname =3D no; then
-      { echo "$as_me:$LINENO: checking for gethostbyname in -lnsl" >&5
-echo $ECHO_N "checking for gethostbyname in -lnsl... $ECHO_C" >&6; }
-if test "${ac_cv_lib_nsl_gethostbyname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_nsl_gethostbyname=3Dyes
+else
+  ac_cv_lib_nsl_gethostbyname=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=3D$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_gethostbyn=
ame" >&5
+$as_echo "$ac_cv_lib_nsl_gethostbyname" >&6; }
+if test "x$ac_cv_lib_nsl_gethostbyname" =3D x""yes; then :
+  X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -lnsl"
+fi
+
+      if test $ac_cv_lib_nsl_gethostbyname =3D no; then
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -l=
bsd" >&5
+$as_echo_n "checking for gethostbyname in -lbsd... " >&6; }
+if test "${ac_cv_lib_bsd_gethostbyname+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-lnsl  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS=3D"-lbsd  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -45039,105 +24827,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_nsl_gethostbyname=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_nsl_gethostbyname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_bsd_gethostbyname=3Dyes
+else
+  ac_cv_lib_bsd_gethostbyname=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_nsl_gethostbyname" >&5
-echo "${ECHO_T}$ac_cv_lib_nsl_gethostbyname" >&6; }
-if test $ac_cv_lib_nsl_gethostbyname =3D yes; then
-  X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -lnsl"
-fi
-
-      if test $ac_cv_lib_nsl_gethostbyname =3D no; then
-	{ echo "$as_me:$LINENO: checking for gethostbyname in -lbsd" >&5
-echo $ECHO_N "checking for gethostbyname in -lbsd... $ECHO_C" >&6; }
-if test "${ac_cv_lib_bsd_gethostbyname+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-lbsd  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char gethostbyname ();
-int
-main ()
-{
-return gethostbyname ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_bsd_gethostbyname=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_bsd_gethostbyname=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=3D$ac_check_lib_save_LIBS
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_bsd_gethostbyname" >&5
-echo "${ECHO_T}$ac_cv_lib_bsd_gethostbyname" >&6; }
-if test $ac_cv_lib_bsd_gethostbyname =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_gethostbyn=
ame" >&5
+$as_echo "$ac_cv_lib_bsd_gethostbyname" >&6; }
+if test "x$ac_cv_lib_bsd_gethostbyname" =3D x""yes; then :
   X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -lbsd"
 fi
=20
@@ -45151,33 +24852,21 @@
     # variants that don't use the name server (or something).  -lsocket
     # must be given before -lnsl if both are needed.  We assume that
     # if connect needs -lnsl, so does gethostbyname.
-    { echo "$as_me:$LINENO: checking for connect" >&5
-echo $ECHO_N "checking for connect... $ECHO_C" >&6; }
-if test "${ac_cv_func_connect+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define connect to an innocuous variant, in case <limits.h> declares con=
nect.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define connect innocuous_connect
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char connect (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef connect
+    ac_fn_c_check_func "$LINENO" "connect" "ac_cv_func_connect"
+if test "x$ac_cv_func_connect" =3D x""yes; then :
+
+fi
+
+    if test $ac_cv_func_connect =3D no; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for connect in -ls=
ocket" >&5
+$as_echo_n "checking for connect in -lsocket... " >&6; }
+if test "${ac_cv_lib_socket_connect+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=3D$LIBS
+LIBS=3D"-lsocket $X_EXTRA_LIBS $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
@@ -45186,13 +24875,6 @@
 extern "C"
 #endif
 char connect ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_connect || defined __stub___connect
-choke me
-#endif
-
 int
 main ()
 {
@@ -45201,51 +24883,38 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_connect=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_connect=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_connect" >&5
-echo "${ECHO_T}$ac_cv_func_connect" >&6; }
-
-    if test $ac_cv_func_connect =3D no; then
-      { echo "$as_me:$LINENO: checking for connect in -lsocket" >&5
-echo $ECHO_N "checking for connect in -lsocket... $ECHO_C" >&6; }
-if test "${ac_cv_lib_socket_connect+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_socket_connect=3Dyes
+else
+  ac_cv_lib_socket_connect=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=3D$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_connect=
" >&5
+$as_echo "$ac_cv_lib_socket_connect" >&6; }
+if test "x$ac_cv_lib_socket_connect" =3D x""yes; then :
+  X_EXTRA_LIBS=3D"-lsocket $X_EXTRA_LIBS"
+fi
+
+    fi
+
+    # Guillermo Gomez says -lposix is necessary on A/UX.
+    ac_fn_c_check_func "$LINENO" "remove" "ac_cv_func_remove"
+if test "x$ac_cv_func_remove" =3D x""yes; then :
+
+fi
+
+    if test $ac_cv_func_remove =3D no; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for remove in -lpo=
six" >&5
+$as_echo_n "checking for remove in -lposix... " >&6; }
+if test "${ac_cv_lib_posix_remove+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-lsocket $X_EXTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+LIBS=3D"-lposix  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -45254,81 +24923,48 @@
 #ifdef __cplusplus
 extern "C"
 #endif
-char connect ();
-int
-main ()
-{
-return connect ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_socket_connect=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_socket_connect=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+char remove ();
+int
+main ()
+{
+return remove ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_posix_remove=3Dyes
+else
+  ac_cv_lib_posix_remove=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_socket_connect" >&5
-echo "${ECHO_T}$ac_cv_lib_socket_connect" >&6; }
-if test $ac_cv_lib_socket_connect =3D yes; then
-  X_EXTRA_LIBS=3D"-lsocket $X_EXTRA_LIBS"
-fi
-
-    fi
-
-    # Guillermo Gomez says -lposix is necessary on A/UX.
-    { echo "$as_me:$LINENO: checking for remove" >&5
-echo $ECHO_N "checking for remove... $ECHO_C" >&6; }
-if test "${ac_cv_func_remove+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define remove to an innocuous variant, in case <limits.h> declares remo=
ve.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define remove innocuous_remove
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char remove (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef remove
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_posix_remove" =
>&5
+$as_echo "$ac_cv_lib_posix_remove" >&6; }
+if test "x$ac_cv_lib_posix_remove" =3D x""yes; then :
+  X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -lposix"
+fi
+
+    fi
+
+    # BSDI BSD/OS 2.1 needs -lipc for XOpenDisplay.
+    ac_fn_c_check_func "$LINENO" "shmat" "ac_cv_func_shmat"
+if test "x$ac_cv_func_shmat" =3D x""yes; then :
+
+fi
+
+    if test $ac_cv_func_shmat =3D no; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shmat in -lipc=
" >&5
+$as_echo_n "checking for shmat in -lipc... " >&6; }
+if test "${ac_cv_lib_ipc_shmat+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=3D$LIBS
+LIBS=3D"-lipc  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
@@ -45336,268 +24972,27 @@
 #ifdef __cplusplus
 extern "C"
 #endif
-char remove ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_remove || defined __stub___remove
-choke me
-#endif
-
-int
-main ()
-{
-return remove ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_remove=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_remove=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_remove" >&5
-echo "${ECHO_T}$ac_cv_func_remove" >&6; }
-
-    if test $ac_cv_func_remove =3D no; then
-      { echo "$as_me:$LINENO: checking for remove in -lposix" >&5
-echo $ECHO_N "checking for remove in -lposix... $ECHO_C" >&6; }
-if test "${ac_cv_lib_posix_remove+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-lposix  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char remove ();
-int
-main ()
-{
-return remove ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_posix_remove=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_posix_remove=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+char shmat ();
+int
+main ()
+{
+return shmat ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_ipc_shmat=3Dyes
+else
+  ac_cv_lib_ipc_shmat=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_posix_remove" >&5
-echo "${ECHO_T}$ac_cv_lib_posix_remove" >&6; }
-if test $ac_cv_lib_posix_remove =3D yes; then
-  X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -lposix"
-fi
-
-    fi
-
-    # BSDI BSD/OS 2.1 needs -lipc for XOpenDisplay.
-    { echo "$as_me:$LINENO: checking for shmat" >&5
-echo $ECHO_N "checking for shmat... $ECHO_C" >&6; }
-if test "${ac_cv_func_shmat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define shmat to an innocuous variant, in case <limits.h> declares shmat.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define shmat innocuous_shmat
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char shmat (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef shmat
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char shmat ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_shmat || defined __stub___shmat
-choke me
-#endif
-
-int
-main ()
-{
-return shmat ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_shmat=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_shmat=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_shmat" >&5
-echo "${ECHO_T}$ac_cv_func_shmat" >&6; }
-
-    if test $ac_cv_func_shmat =3D no; then
-      { echo "$as_me:$LINENO: checking for shmat in -lipc" >&5
-echo $ECHO_N "checking for shmat in -lipc... $ECHO_C" >&6; }
-if test "${ac_cv_lib_ipc_shmat+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  ac_check_lib_save_LIBS=3D$LIBS
-LIBS=3D"-lipc  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char shmat ();
-int
-main ()
-{
-return shmat ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_lib_ipc_shmat=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_ipc_shmat=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-LIBS=3D$ac_check_lib_save_LIBS
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_ipc_shmat" >&5
-echo "${ECHO_T}$ac_cv_lib_ipc_shmat" >&6; }
-if test $ac_cv_lib_ipc_shmat =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ipc_shmat" >&5
+$as_echo "$ac_cv_lib_ipc_shmat" >&6; }
+if test "x$ac_cv_lib_ipc_shmat" =3D x""yes; then :
   X_EXTRA_LIBS=3D"$X_EXTRA_LIBS -lipc"
 fi
=20
@@ -45613,18 +25008,14 @@
   # These have to be linked with before -lX11, unlike the other
   # libraries we check for below, so use a different variable.
   # John Interrante, Karl Berry
-  { echo "$as_me:$LINENO: checking for IceConnectionNumber in -lICE" >&5
-echo $ECHO_N "checking for IceConnectionNumber in -lICE... $ECHO_C" >&6; }
-if test "${ac_cv_lib_ICE_IceConnectionNumber+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for IceConnectionNumbe=
r in -lICE" >&5
+$as_echo_n "checking for IceConnectionNumber in -lICE... " >&6; }
+if test "${ac_cv_lib_ICE_IceConnectionNumber+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_check_lib_save_LIBS=3D$LIBS
 LIBS=3D"-lICE $X_EXTRA_LIBS $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 /* Override any GCC internal prototype to avoid an error.
@@ -45642,39 +25033,18 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   ac_cv_lib_ICE_IceConnectionNumber=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_lib_ICE_IceConnectionNumber=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+  ac_cv_lib_ICE_IceConnectionNumber=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 LIBS=3D$ac_check_lib_save_LIBS
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_lib_ICE_IceConnectionNumber" >&5
-echo "${ECHO_T}$ac_cv_lib_ICE_IceConnectionNumber" >&6; }
-if test $ac_cv_lib_ICE_IceConnectionNumber =3D yes; then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ICE_IceConnect=
ionNumber" >&5
+$as_echo "$ac_cv_lib_ICE_IceConnectionNumber" >&6; }
+if test "x$ac_cv_lib_ICE_IceConnectionNumber" =3D x""yes; then :
   X_PRE_LIBS=3D"$X_PRE_LIBS -lSM -lICE"
 fi
=20
@@ -45686,10 +25056,10 @@
 # try to figure out if we need any additional ld flags, like -R
 # and yes, the autoconf X test is utterly broken
 if test "$no_x" !=3D yes; then
-	{ echo "$as_me:$LINENO: checking for special X linker flags" >&5
-echo $ECHO_N "checking for special X linker flags... $ECHO_C" >&6; }
-if test "${krb_cv_sys_x_libs_rpath+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for special X linker fl=
ags" >&5
+$as_echo_n "checking for special X linker flags... " >&6; }
+if test "${krb_cv_sys_x_libs_rpath+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 	ac_save_libs=3D"$LIBS"
@@ -45714,10 +25084,11 @@
 			done
 		fi
 		LIBS=3D"$ac_save_libs $foo $X_PRE_LIBS -lX11 $X_EXTRA_LIBS"
-		if test "$cross_compiling" =3D yes; then
+		if test "$cross_compiling" =3D yes; then :
   krb_cv_sys_x_libs_rpath=3D"" ; krb_cv_sys_x_libs=3D"" ; break
 else
-  cat >conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
=20
 		#include <X11/Xlib.h>
 		foo(void)
@@ -45730,46 +25101,22 @@
 		}
=20
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   krb_cv_sys_x_libs_rpath=3D"$rflag"; krb_cv_sys_x_libs=3D"$foo"; break
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-:
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
+  :
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
=20
 	done
 	LIBS=3D"$ac_save_libs"
 	CFLAGS=3D"$ac_save_cflags"
=20
 fi
-{ echo "$as_me:$LINENO: result: $krb_cv_sys_x_libs_rpath" >&5
-echo "${ECHO_T}$krb_cv_sys_x_libs_rpath" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $krb_cv_sys_x_libs_rpath"=
 >&5
+$as_echo "$krb_cv_sys_x_libs_rpath" >&6; }
 	X_LIBS=3D"$krb_cv_sys_x_libs"
 fi
=20
@@ -45799,10 +25146,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for XauWriteAuth" >&5
-echo $ECHO_N "checking for XauWriteAuth... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_XauWriteAuth+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for XauWriteAuth" >&5
+$as_echo_n "checking for XauWriteAuth... " >&6; }
+if test "${ac_cv_funclib_XauWriteAuth+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_XauWriteAuth\" !=3D yes" ; then
@@ -45816,11 +25163,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <X11/Xauth.h>
 int
@@ -45831,34 +25174,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_XauWriteAuth=3D$ac_lib; =
else ac_cv_funclib_XauWriteAuth=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_XauWriteAuth=3D\${ac_cv_funclib_XauWriteAuth-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -45870,95 +25190,12 @@
 eval "ac_res=3D\$ac_cv_funclib_XauWriteAuth"
=20
 if false; then
-
-for ac_func in XauWriteAuth
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in XauWriteAuth
+do :
+  ac_fn_c_check_func "$LINENO" "XauWriteAuth" "ac_cv_func_XauWriteAuth"
+if test "x$ac_cv_func_XauWriteAuth" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_XAUWRITEAUTH 1
 _ACEOF
=20
 fi
@@ -45978,14 +25215,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_XauWriteAuth=3Dno"
 	eval "LIB_XauWriteAuth=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_XauWriteAuth=3Dyes"
@@ -45998,8 +25235,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -46009,10 +25246,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for XauReadAuth" >&5
-echo $ECHO_N "checking for XauReadAuth... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_XauReadAuth+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for XauReadAuth" >&5
+$as_echo_n "checking for XauReadAuth... " >&6; }
+if test "${ac_cv_funclib_XauReadAuth+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_XauReadAuth\" !=3D yes" ; then
@@ -46026,11 +25263,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <X11/Xauth.h>
 int
@@ -46041,34 +25274,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_XauReadAuth=3D$ac_lib; e=
lse ac_cv_funclib_XauReadAuth=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_XauReadAuth=3D\${ac_cv_funclib_XauReadAuth-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -46080,95 +25290,12 @@
 eval "ac_res=3D\$ac_cv_funclib_XauReadAuth"
=20
 if false; then
-
-for ac_func in XauReadAuth
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in XauReadAuth
+do :
+  ac_fn_c_check_func "$LINENO" "XauReadAuth" "ac_cv_func_XauReadAuth"
+if test "x$ac_cv_func_XauReadAuth" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_XAUREADAUTH 1
 _ACEOF
=20
 fi
@@ -46188,14 +25315,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_XauReadAuth=3Dno"
 	eval "LIB_XauReadAuth=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_XauReadAuth=3Dyes"
@@ -46208,8 +25335,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -46218,10 +25345,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for XauFileName" >&5
-echo $ECHO_N "checking for XauFileName... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_XauFileName+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for XauFileName" >&5
+$as_echo_n "checking for XauFileName... " >&6; }
+if test "${ac_cv_funclib_XauFileName+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_XauFileName\" !=3D yes" ; then
@@ -46235,11 +25362,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <X11/Xauth.h>
 int
@@ -46250,34 +25373,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_XauFileName=3D$ac_lib; e=
lse ac_cv_funclib_XauFileName=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_XauFileName=3D\${ac_cv_funclib_XauFileName-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -46289,95 +25389,12 @@
 eval "ac_res=3D\$ac_cv_funclib_XauFileName"
=20
 if false; then
-
-for ac_func in XauFileName
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in XauFileName
+do :
+  ac_fn_c_check_func "$LINENO" "XauFileName" "ac_cv_func_XauFileName"
+if test "x$ac_cv_func_XauFileName" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_XAUFILENAME 1
 _ACEOF
=20
 fi
@@ -46397,14 +25414,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_XauFileName=3Dno"
 	eval "LIB_XauFileName=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_XauFileName=3Dyes"
@@ -46417,8 +25434,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -46472,16 +25489,12 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5
-echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; }
-if test "${ac_cv_c_const+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming=
 const" >&5
+$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
+if test "${ac_cv_c_const+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -46541,98 +25554,24 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_c_const=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_c_const=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5
-echo "${ECHO_T}$ac_cv_c_const" >&6; }
+  ac_cv_c_const=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5
+$as_echo "$ac_cv_c_const" >&6; }
 if test $ac_cv_c_const =3D no; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define const
-_ACEOF
-
-fi
-
-{ echo "$as_me:$LINENO: checking for off_t" >&5
-echo $ECHO_N "checking for off_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_off_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef off_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_off_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_off_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5
-echo "${ECHO_T}$ac_cv_type_off_t" >&6; }
-if test $ac_cv_type_off_t =3D yes; then
-  :
+$as_echo "#define const /**/" >>confdefs.h
+
+fi
+
+ac_fn_c_check_type "$LINENO" "off_t" "ac_cv_type_off_t" "$ac_includes_defa=
ult"
+if test "x$ac_cv_type_off_t" =3D x""yes; then :
+
 else
=20
 cat >>confdefs.h <<_ACEOF
@@ -46641,16 +25580,12 @@
=20
 fi
=20
-{ echo "$as_me:$LINENO: checking for mode_t" >&5
-echo $ECHO_N "checking for mode_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_mode_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for mode_t" >&5
+$as_echo_n "checking for mode_t... " >&6; }
+if test "${ac_cv_type_mode_t+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #if STDC_HEADERS
@@ -46660,7 +25595,7 @@
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "mode_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
+  $EGREP "mode_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then :
   ac_cv_type_mode_t=3Dyes
 else
   ac_cv_type_mode_t=3Dno
@@ -46668,26 +25603,20 @@
 rm -f conftest*
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5
-echo "${ECHO_T}$ac_cv_type_mode_t" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_mode_t" >&5
+$as_echo "$ac_cv_type_mode_t" >&6; }
 if test $ac_cv_type_mode_t =3D no; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define mode_t unsigned short
-_ACEOF
-
-fi
-
-{ echo "$as_me:$LINENO: checking for sig_atomic_t" >&5
-echo $ECHO_N "checking for sig_atomic_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_sig_atomic_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define mode_t unsigned short" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sig_atomic_t" >&5
+$as_echo_n "checking for sig_atomic_t... " >&6; }
+if test "${ac_cv_type_sig_atomic_t+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #if STDC_HEADERS
@@ -46697,7 +25626,7 @@
 #include <signal.h>
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "sig_atomic_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then
+  $EGREP "sig_atomic_t[^a-zA-Z_0-9]" >/dev/null 2>&1; then :
   ac_cv_type_sig_atomic_t=3Dyes
 else
   ac_cv_type_sig_atomic_t=3Dno
@@ -46705,29 +25634,23 @@
 rm -f conftest*
=20
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_sig_atomic_t" >&5
-echo "${ECHO_T}$ac_cv_type_sig_atomic_t" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_sig_atomic_t"=
 >&5
+$as_echo "$ac_cv_type_sig_atomic_t" >&6; }
 if test $ac_cv_type_sig_atomic_t =3D no; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define sig_atomic_t int
-_ACEOF
+$as_echo "#define sig_atomic_t int" >>confdefs.h
=20
 fi
=20
=20
=20
 cv=3D`echo "long long" | sed 'y%./+- %__p__%'`
-{ echo "$as_me:$LINENO: checking for long long" >&5
-echo $ECHO_N "checking for long long... $ECHO_C" >&6; }
-if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for long long" >&5
+$as_echo_n "checking for long long... " >&6; }
+if { as_var=3Dac_cv_type_$cv; eval "test \"\${$as_var+set}\" =3D set"; }; =
then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #include <sys/types.h>
@@ -46744,93 +25667,21 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_type_$cv=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_type_$cv=3Dno"
-fi
-
+  eval "ac_cv_type_$cv=3Dno"
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 ac_foo=3D`eval echo \\$ac_cv_type_$cv`
-{ echo "$as_me:$LINENO: result: $ac_foo" >&5
-echo "${ECHO_T}$ac_foo" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_foo" >&5
+$as_echo "$ac_foo" >&6; }
 if test "$ac_foo" =3D yes; then
   ac_tr_hdr=3DHAVE_`echo long long | sed 'y%abcdefghijklmnopqrstuvwxyz./- =
%ABCDEFGHIJKLMNOPQRSTUVWXYZ____%'`
 if false; then
-	{ echo "$as_me:$LINENO: checking for long long" >&5
-echo $ECHO_N "checking for long long... $ECHO_C" >&6; }
-if test "${ac_cv_type_long_long+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-typedef long long ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_long_long=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_long_long=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_long_long" >&5
-echo "${ECHO_T}$ac_cv_type_long_long" >&6; }
-if test $ac_cv_type_long_long =3D yes; then
+	ac_fn_c_check_type "$LINENO" "long long" "ac_cv_type_long_long" "$ac_incl=
udes_default"
+if test "x$ac_cv_type_long_long" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_LONG_LONG 1
@@ -46847,16 +25698,12 @@
=20
 fi
=20
-{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be=
 included" >&5
-echo $ECHO_N "checking whether time.h and sys/time.h may both be included.=
.. $ECHO_C" >&6; }
-if test "${ac_cv_header_time+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/t=
ime.h may both be included" >&5
+$as_echo_n "checking whether time.h and sys/time.h may both be included...=
 " >&6; }
+if test "${ac_cv_header_time+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #include <sys/time.h>
@@ -46871,53 +25718,27 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_header_time=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_header_time=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5
-echo "${ECHO_T}$ac_cv_header_time" >&6; }
+  ac_cv_header_time=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5
+$as_echo "$ac_cv_header_time" >&6; }
 if test $ac_cv_header_time =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define TIME_WITH_SYS_TIME 1
-_ACEOF
-
-fi
-
-{ echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or tim=
e.h" >&5
-echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $EC=
HO_C" >&6; }
-if test "${ac_cv_struct_tm+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether struct tm is in =
sys/time.h or time.h" >&5
+$as_echo_n "checking whether struct tm is in sys/time.h or time.h... " >&6=
; }
+if test "${ac_cv_struct_tm+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #include <time.h>
@@ -46927,59 +25748,33 @@
 {
 struct tm tm;
 				     int *p =3D &tm.tm_sec;
- 				     return !p;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+				     return !p;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_struct_tm=3Dtime.h
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_struct_tm=3Dsys/time.h
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5
-echo "${ECHO_T}$ac_cv_struct_tm" >&6; }
+  ac_cv_struct_tm=3Dsys/time.h
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_struct_tm" >&5
+$as_echo "$ac_cv_struct_tm" >&6; }
 if test $ac_cv_struct_tm =3D sys/time.h; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define TM_IN_SYS_TIME 1
-_ACEOF
-
-fi
-
-
-{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5
-echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; }
-if test "${ac_cv_header_stdc+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files"=
 >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if test "${ac_cv_header_stdc+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdlib.h>
 #include <stdarg.h>
@@ -46994,47 +25789,23 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_header_stdc=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_header_stdc=3Dno
-fi
-
+  ac_cv_header_stdc=3Dno
+fi
 rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
=20
 if test $ac_cv_header_stdc =3D yes; then
   # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <string.h>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then
-  :
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
 else
   ac_cv_header_stdc=3Dno
 fi
@@ -47044,18 +25815,14 @@
=20
 if test $ac_cv_header_stdc =3D yes; then
   # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdlib.h>
=20
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then
-  :
+  $EGREP "free" >/dev/null 2>&1; then :
+
 else
   ac_cv_header_stdc=3Dno
 fi
@@ -47065,14 +25832,10 @@
=20
 if test $ac_cv_header_stdc =3D yes; then
   # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" =3D yes; then
+  if test "$cross_compiling" =3D yes; then :
   :
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <ctype.h>
 #include <stdlib.h>
@@ -47099,111 +25862,36 @@
   return 0;
 }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
-else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_header_stdc=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
-echo "${ECHO_T}$ac_cv_header_stdc" >&6; }
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
 if test $ac_cv_header_stdc =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define STDC_HEADERS 1
-_ACEOF
-
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
=20
=20
 for ac_header in \
+	CommonCrypto/CommonDigest.h		\
+	CommonCrypto/CommonCryptor.h		\
 	arpa/ftp.h				\
 	arpa/telnet.h				\
 	bind/bitypes.h				\
 	bsdsetjmp.h				\
 	curses.h				\
 	dlfcn.h					\
+	execinfo.h				\
 	fnmatch.h				\
 	inttypes.h				\
 	io.h					\
@@ -47212,7 +25900,6 @@
 	maillock.h				\
 	netgroup.h				\
 	netinet/in6_machtypes.h			\
-	netinfo/ni.h				\
 	pthread.h				\
 	pty.h					\
 	sac.h					\
@@ -47241,6 +25928,7 @@
 	sys/times.h				\
 	sys/types.h				\
 	sys/un.h				\
+	locale.h				\
 	termcap.h				\
 	termio.h				\
 	termios.h				\
@@ -47251,548 +25939,153 @@
 	utmp.h					\
 	utmpx.h					\
=20
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in term.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  eval "$as_ac_Header=3Dno"
-fi
-
-rm -f conftest.err conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+do :
+  ac_fn_c_check_header_preproc "$LINENO" "term.h" "ac_cv_header_term_h"
+if test "x$ac_cv_header_term_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_TERM_H 1
+_ACEOF
+
+fi
+
+done
+
+
+for ac_header in asl.h
+do :
+  ac_fn_c_check_header_compile "$LINENO" "asl.h" "ac_cv_header_asl_h" "
+#include <asl.h>
+#ifndef ASL_STRING_EMERG
+#error ASL_STRING_EMERG missing
+#endif
+"
+if test "x$ac_cv_header_asl_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_ASL_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in net/if.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "net/if.h" "ac_cv_header_net_if_h=
" "$ac_includes_default
 #if HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_net_if_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_NET_IF_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in sys/ptyvar.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "sys/ptyvar.h" "ac_cv_header_sys_=
ptyvar_h" "$ac_includes_default
 #if HAVE_SYS_TTY_H
 #include <sys/tty.h>
 #endif
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_sys_ptyvar_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SYS_PTYVAR_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in sys/strtty.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "sys/strtty.h" "ac_cv_header_sys_=
strtty_h" "$ac_includes_default
 #if HAVE_TERMIOS_H
 #include <termios.h>
 #endif
 #if HAVE_SYS_STREAM_H
 #include <sys/stream.h>
 #endif
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_sys_strtty_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SYS_STRTTY_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in sys/ucred.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "sys/ucred.h" "ac_cv_header_sys_u=
cred_h" "$ac_includes_default
 #if HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
 #if HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
+"
+if test "x$ac_cv_header_sys_ucred_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SYS_UCRED_H 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_header in security/pam_modules.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
+do :
+  ac_fn_c_check_header_compile "$LINENO" "security/pam_modules.h" "ac_cv_h=
eader_security_pam_modules_h" "$ac_includes_default
 #include <security/pam_appl.h>
=20
-
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  eval "$as_ac_Header=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_Header=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
-# Check whether --enable-netinfo was given.
-if test "${enable_netinfo+set}" =3D set; then
-  enableval=3D$enable_netinfo;
-fi
-
-
-if test "$ac_cv_header_netinfo_ni_h" =3D yes -a "$enable_netinfo" =3D yes;=
 then
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_NETINFO 1
-_ACEOF
-
-fi
-
-
-
-
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for logwtmp" >&5
-echo $ECHO_N "checking for logwtmp... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_logwtmp+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+"
+if test "x$ac_cv_header_security_pam_modules_h" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_SECURITY_PAM_MODULES_H 1
+_ACEOF
+
+fi
+
+done
+
+
+
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for logwtmp" >&5
+$as_echo_n "checking for logwtmp... " >&6; }
+if test "${ac_cv_funclib_logwtmp+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_logwtmp\" !=3D yes" ; then
@@ -47806,11 +26099,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_UTIL_H
@@ -47825,34 +26114,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_logwtmp=3D$ac_lib; else =
ac_cv_funclib_logwtmp=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_logwtmp=3D\${ac_cv_funclib_logwtmp-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -47864,95 +26130,12 @@
 eval "ac_res=3D\$ac_cv_funclib_logwtmp"
=20
 if false; then
-
-for ac_func in logwtmp
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in logwtmp
+do :
+  ac_fn_c_check_func "$LINENO" "logwtmp" "ac_cv_func_logwtmp"
+if test "x$ac_cv_func_logwtmp" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LOGWTMP 1
 _ACEOF
=20
 fi
@@ -47972,14 +26155,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_logwtmp=3Dno"
 	eval "LIB_logwtmp=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_logwtmp=3Dyes"
@@ -47992,19 +26175,19 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for logout" >&5
-echo $ECHO_N "checking for logout... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_logout+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for logout" >&5
+$as_echo_n "checking for logout... " >&6; }
+if test "${ac_cv_funclib_logout+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_logout\" !=3D yes" ; then
@@ -48018,11 +26201,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_UTIL_H
@@ -48037,34 +26216,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_logout=3D$ac_lib; else a=
c_cv_funclib_logout=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_logout=3D\${ac_cv_funclib_logout-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -48076,95 +26232,12 @@
 eval "ac_res=3D\$ac_cv_funclib_logout"
=20
 if false; then
-
-for ac_func in logout
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in logout
+do :
+  ac_fn_c_check_func "$LINENO" "logout" "ac_cv_func_logout"
+if test "x$ac_cv_func_logout" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LOGOUT 1
 _ACEOF
=20
 fi
@@ -48184,14 +26257,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_logout=3Dno"
 	eval "LIB_logout=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_logout=3Dyes"
@@ -48204,19 +26277,19 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for openpty" >&5
-echo $ECHO_N "checking for openpty... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_openpty+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for openpty" >&5
+$as_echo_n "checking for openpty... " >&6; }
+if test "${ac_cv_funclib_openpty+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_openpty\" !=3D yes" ; then
@@ -48230,11 +26303,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_UTIL_H
@@ -48249,34 +26318,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_openpty=3D$ac_lib; else =
ac_cv_funclib_openpty=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_openpty=3D\${ac_cv_funclib_openpty-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -48288,95 +26334,12 @@
 eval "ac_res=3D\$ac_cv_funclib_openpty"
=20
 if false; then
-
-for ac_func in openpty
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in openpty
+do :
+  ac_fn_c_check_func "$LINENO" "openpty" "ac_cv_func_openpty"
+if test "x$ac_cv_func_openpty" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_OPENPTY 1
 _ACEOF
=20
 fi
@@ -48396,14 +26359,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_openpty=3Dno"
 	eval "LIB_openpty=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_openpty=3Dyes"
@@ -48416,20 +26379,20 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for tgetent" >&5
-echo $ECHO_N "checking for tgetent... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_tgetent+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for tgetent" >&5
+$as_echo_n "checking for tgetent... " >&6; }
+if test "${ac_cv_funclib_tgetent+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_tgetent\" !=3D yes" ; then
@@ -48443,11 +26406,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #ifdef HAVE_TERMCAP_H
@@ -48465,34 +26424,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_tgetent=3D$ac_lib; else =
ac_cv_funclib_tgetent=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_tgetent=3D\${ac_cv_funclib_tgetent-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -48504,95 +26440,12 @@
 eval "ac_res=3D\$ac_cv_funclib_tgetent"
=20
 if false; then
-
-for ac_func in tgetent
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in tgetent
+do :
+  ac_fn_c_check_func "$LINENO" "tgetent" "ac_cv_func_tgetent"
+if test "x$ac_cv_func_tgetent" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_TGETENT 1
 _ACEOF
=20
 fi
@@ -48612,14 +26465,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_tgetent=3Dno"
 	eval "LIB_tgetent=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_tgetent=3Dyes"
@@ -48632,40 +26485,10 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
+	;;
+esac
=20
=20
=20
@@ -48674,6 +26497,7 @@
 	_getpty					\
 	_scrsize				\
 	arc4random				\
+	backtrace				\
 	fcntl					\
 	getpeereid				\
 	getpeerucred				\
@@ -48702,352 +26526,70 @@
 	vhangup					\
 	yp_get_default_domain			\
=20
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-
-
-
-for ac_header in stdlib.h unistd.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
+do :
+  as_ac_var=3D`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+eval as_val=3D\$$as_ac_var
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking checking for __sync_add_=
and_fetch" >&5
+$as_echo_n "checking checking for __sync_add_and_fetch... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+int
+main ()
+{
+unsigned int foo; __sync_add_and_fetch(&foo, 1);
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_rk_have___sync_add_and_fetch=3Dyes
+else
+  ac_rk_have___sync_add_and_fetch=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+if test "$ac_rk_have___sync_add_and_fetch" =3D "yes" ; then
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE___SYNC_ADD_AND_FETCH 1
+_ACEOF
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_rk_have___sync_add_an=
d_fetch" >&5
+$as_echo "$ac_rk_have___sync_add_and_fetch" >&6; }
=20
=20
 for ac_func in getpagesize
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-{ echo "$as_me:$LINENO: checking for working mmap" >&5
-echo $ECHO_N "checking for working mmap... $ECHO_C" >&6; }
-if test "${ac_cv_func_mmap_fixed_mapped+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test "$cross_compiling" =3D yes; then
+do :
+  ac_fn_c_check_func "$LINENO" "getpagesize" "ac_cv_func_getpagesize"
+if test "x$ac_cv_func_getpagesize" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETPAGESIZE 1
+_ACEOF
+
+fi
+done
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working mmap" >&5
+$as_echo_n "checking for working mmap... " >&6; }
+if test "${ac_cv_func_mmap_fixed_mapped+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "$cross_compiling" =3D yes; then :
   ac_cv_func_mmap_fixed_mapped=3Dno
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $ac_includes_default
 /* malloc might have been renamed as rpl_malloc. */
@@ -49084,11 +26626,6 @@
=20
 /* This mess was copied from the GNU getpagesize.h.  */
 #ifndef HAVE_GETPAGESIZE
-/* Assume that all systems that can run configure have sys/param.h.  */
-# ifndef HAVE_SYS_PARAM_H
-#  define HAVE_SYS_PARAM_H 1
-# endif
-
 # ifdef _SC_PAGESIZE
 #  define getpagesize() sysconf(_SC_PAGESIZE)
 # else /* no _SC_PAGESIZE */
@@ -49124,7 +26661,7 @@
 {
   char *data, *data2, *data3;
   int i, pagesize;
-  int fd;
+  int fd, fd2;
=20
   pagesize =3D getpagesize ();
=20
@@ -49137,27 +26674,41 @@
   umask (0);
   fd =3D creat ("conftest.mmap", 0600);
   if (fd < 0)
-    return 1;
+    return 2;
   if (write (fd, data, pagesize) !=3D pagesize)
-    return 1;
+    return 3;
   close (fd);
=20
+  /* Next, check that the tail of a page is zero-filled.  File must have
+     non-zero length, otherwise we risk SIGBUS for entire page.  */
+  fd2 =3D open ("conftest.txt", O_RDWR | O_CREAT | O_TRUNC, 0600);
+  if (fd2 < 0)
+    return 4;
+  data2 =3D "";
+  if (write (fd2, data2, 1) !=3D 1)
+    return 5;
+  data2 =3D mmap (0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd2, 0L=
);
+  if (data2 =3D=3D MAP_FAILED)
+    return 6;
+  for (i =3D 0; i < pagesize; ++i)
+    if (*(data2 + i))
+      return 7;
+  close (fd2);
+  if (munmap (data2, pagesize))
+    return 8;
+
   /* Next, try to mmap the file at a fixed address which already has
      something else allocated at it.  If we can, also make sure that
      we see the same garbage.  */
   fd =3D open ("conftest.mmap", O_RDWR);
   if (fd < 0)
-    return 1;
-  data2 =3D (char *) malloc (2 * pagesize);
-  if (!data2)
-    return 1;
-  data2 +=3D (pagesize - ((long int) data2 & (pagesize - 1))) & (pagesize =
- 1);
+    return 9;
   if (data2 !=3D mmap (data2, pagesize, PROT_READ | PROT_WRITE,
 		     MAP_PRIVATE | MAP_FIXED, fd, 0L))
-    return 1;
+    return 10;
   for (i =3D 0; i < pagesize; ++i)
     if (*(data + i) !=3D *(data2 + i))
-      return 1;
+      return 11;
=20
   /* Finally, make sure that changes to the mapped area do not
      percolate back to the file as seen by read().  (This is a bug on
@@ -49166,316 +26717,76 @@
     *(data2 + i) =3D *(data2 + i) + 1;
   data3 =3D (char *) malloc (pagesize);
   if (!data3)
-    return 1;
+    return 12;
   if (read (fd, data3, pagesize) !=3D pagesize)
-    return 1;
+    return 13;
   for (i =3D 0; i < pagesize; ++i)
     if (*(data + i) !=3D *(data3 + i))
-      return 1;
+      return 14;
   close (fd);
   return 0;
 }
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   ac_cv_func_mmap_fixed_mapped=3Dyes
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_mmap_fixed_mapped=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_mmap_fixed_mapped" >&5
-echo "${ECHO_T}$ac_cv_func_mmap_fixed_mapped" >&6; }
+  ac_cv_func_mmap_fixed_mapped=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_mmap_fixed_ma=
pped" >&5
+$as_echo "$ac_cv_func_mmap_fixed_mapped" >&6; }
 if test $ac_cv_func_mmap_fixed_mapped =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_MMAP 1
-_ACEOF
-
-fi
-rm -f conftest.mmap
-
-
+$as_echo "#define HAVE_MMAP 1" >>confdefs.h
+
+fi
+rm -f conftest.mmap conftest.txt
=20
=20
=20
=20
 for ac_header in capability.h sys/capability.h
-do
-as_ac_Header=3D`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  { echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
-echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_includes_default
-#include <$ac_header>
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_header_compiler=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_header_compiler=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
-echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <$ac_header>
-_ACEOF
-if { (ac_try=3D"$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } >/dev/null && {
-	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       }; then
-  ac_header_preproc=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-  ac_header_preproc=3Dno
-fi
-
-rm -f conftest.err conftest.$ac_ext
-{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
-  yes:no: )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler,=
 rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by t=
he preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compi=
ler's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" =
>&2;}
-    ac_header_preproc=3Dyes
-    ;;
-  no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be com=
piled" >&5
-echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing pre=
requisite headers?" >&5
-echo "$as_me: WARNING: $ac_header:     check for missing prerequisite head=
ers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf document=
ation" >&5
-echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But=
 Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Com=
piled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the prepr=
ocessor's result" >&5
-echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's resu=
lt" >&2;}
-    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compil=
er will take precedence" >&5
-echo "$as_me: WARNING: $ac_header: in the future, the compiler will take p=
recedence" >&2;}
-    ( cat <<\_ASBOX
-## ----------------------------------- ##
-## Report this to heimdal-bugs at h5l.org ##
-## ----------------------------------- ##
-_ASBOX
-     ) | sed "s/^/$as_me: WARNING:     /" >&2
-    ;;
-esac
-{ echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_Header; eval "test \"\${$as_var+set}\" =3D set"; }; t=
hen
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  eval "$as_ac_Header=3D\$ac_header_preproc"
-fi
-ac_res=3D`eval echo '${'$as_ac_Header'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-
-fi
-if test `eval echo '${'$as_ac_Header'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
+do :
+  as_ac_Header=3D`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_i=
ncludes_default"
+eval as_val=3D\$$as_ac_Header
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
=20
=20
 for ac_func in sgi_getcapabilitybyname cap_set_proc
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for getpwnam_r" >&5
-echo $ECHO_N "checking for getpwnam_r... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_getpwnam_r+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+do :
+  as_ac_var=3D`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+eval as_val=3D\$$as_ac_var
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for getpwnam_r" >&5
+$as_echo_n "checking for getpwnam_r... " >&6; }
+if test "${ac_cv_funclib_getpwnam_r+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_getpwnam_r\" !=3D yes" ; then
@@ -49489,11 +26800,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -49504,34 +26811,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_getpwnam_r=3D$ac_lib; el=
se ac_cv_funclib_getpwnam_r=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_getpwnam_r=3D\${ac_cv_funclib_getpwnam_r-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -49543,95 +26827,12 @@
 eval "ac_res=3D\$ac_cv_funclib_getpwnam_r"
=20
 if false; then
-
-for ac_func in getpwnam_r
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in getpwnam_r
+do :
+  ac_fn_c_check_func "$LINENO" "getpwnam_r" "ac_cv_func_getpwnam_r"
+if test "x$ac_cv_func_getpwnam_r" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_GETPWNAM_R 1
 _ACEOF
=20
 fi
@@ -49651,14 +26852,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_getpwnam_r=3Dno"
 	eval "LIB_getpwnam_r=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_getpwnam_r=3Dyes"
@@ -49671,28 +26872,24 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
=20
 if test "$ac_cv_func_getpwnam_r" =3D yes; then
-	{ echo "$as_me:$LINENO: checking if getpwnam_r is posix" >&5
-echo $ECHO_N "checking if getpwnam_r is posix... $ECHO_C" >&6; }
-if test "${ac_cv_func_getpwnam_r_posix+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getpwnam_r is posix"=
 >&5
+$as_echo_n "checking if getpwnam_r is posix... " >&6; }
+if test "${ac_cv_func_getpwnam_r_posix+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   ac_libs=3D"$LIBS"
 	LIBS=3D"$LIBS $LIB_getpwnam_r"
-	if test "$cross_compiling" =3D yes; then
+	if test "$cross_compiling" =3D yes; then :
   :
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 #define _POSIX_PTHREAD_SEMANTICS
@@ -49700,52 +26897,65 @@
 int main(int argc, char **argv)
 {
 	struct passwd pw, *pwd;
-	return getpwnam_r("", &pw, NULL, 0, &pwd) < 0;
-}
-
-_ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+	return getpwnam_r("", &pw, 0, 0, &pwd) < 0;
+}
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
   ac_cv_func_getpwnam_r_posix=3Dyes
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_getpwnam_r_posix=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
+  ac_cv_func_getpwnam_r_posix=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
=20
 LIBS=3D"$ac_libs"
 fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getpwnam_r_posix" >&5
-echo "${ECHO_T}$ac_cv_func_getpwnam_r_posix" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getpwnam_r_po=
six" >&5
+$as_echo "$ac_cv_func_getpwnam_r_posix" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if _POSIX_PTHREAD_SEMAN=
TICS is needed" >&5
+$as_echo_n "checking if _POSIX_PTHREAD_SEMANTICS is needed... " >&6; }
+if test "${ac_cv_func_getpwnam_r_posix_def+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_libs=3D"$LIBS"
+	LIBS=3D"$LIBS $LIB_getpwnam_r"
+	if test "$cross_compiling" =3D yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <pwd.h>
+int main(int argc, char **argv)
+{
+	struct passwd pw, *pwd;
+	return getpwnam_r("", &pw, 0, 0, &pwd) < 0;
+}
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  ac_cv_func_getpwnam_r_posix_def=3Dno
+else
+  ac_cv_func_getpwnam_r_posix_def=3Dyes
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+LIBS=3D"$ac_libs"
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getpwnam_r_po=
six_def" >&5
+$as_echo "$ac_cv_func_getpwnam_r_posix_def" >&6; }
 if test "$ac_cv_func_getpwnam_r_posix" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define POSIX_GETPWNAM_R 1
-_ACEOF
+$as_echo "#define POSIX_GETPWNAM_R 1" >>confdefs.h
+
+fi
+if test "$ac_cv_func_getpwnam_r_posix" =3D yes -a "$ac_cv_func_getpwnam_r_=
posix_def" =3D yes; then
+
+$as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
=20
 fi
 fi
@@ -49757,10 +26967,10 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for door_create" >&5
-echo $ECHO_N "checking for door_create... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_door_create+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for door_create" >&5
+$as_echo_n "checking for door_create... " >&6; }
+if test "${ac_cv_funclib_door_create+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if eval "test \"\$ac_cv_func_door_create\" !=3D yes" ; then
@@ -49774,11 +26984,7 @@
 		*) ac_lib=3D"-l$ac_lib" ;;
 		esac
 		LIBS=3D" $ac_lib  $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 int
@@ -49789,34 +26995,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   eval "if test -n \"$ac_lib\";then ac_cv_funclib_door_create=3D$ac_lib; e=
lse ac_cv_funclib_door_create=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	done
 	eval "ac_cv_funclib_door_create=3D\${ac_cv_funclib_door_create-no}"
 	LIBS=3D"$ac_save_LIBS"
@@ -49828,95 +27011,12 @@
 eval "ac_res=3D\$ac_cv_funclib_door_create"
=20
 if false; then
-
-for ac_func in door_create
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
+	for ac_func in door_create
+do :
+  ac_fn_c_check_func "$LINENO" "door_create" "ac_cv_func_door_create"
+if test "x$ac_cv_func_door_create" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_DOOR_CREATE 1
 _ACEOF
=20
 fi
@@ -49936,14 +27036,14 @@
 #define $ac_tr_func 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
 	;;
 	no)
 	eval "ac_cv_func_door_create=3Dno"
 	eval "LIB_door_create=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 	;;
 	*)
 	eval "ac_cv_func_door_create=3Dyes"
@@ -49956,8 +27056,8 @@
 #define $ac_tr_lib 1
 _ACEOF
=20
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes, in $ac_res" >&5
+$as_echo "yes, in $ac_res" >&6; }
 	;;
 esac
=20
@@ -49966,7 +27066,7 @@
 fi
=20
 # Check whether --enable-kcm was given.
-if test "${enable_kcm+set}" =3D set; then
+if test "${enable_kcm+set}" =3D set; then :
   enableval=3D$enable_kcm;
 else
   enable_kcm=3Dyes
@@ -49980,9 +27080,7 @@
 fi
 if test "$enable_kcm" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_KCM 1
-_ACEOF
+$as_echo "#define HAVE_KCM 1" >>confdefs.h
=20
 fi
  if test "$enable_kcm" =3D yes; then
@@ -49996,117 +27094,31 @@
=20
=20
=20
-
-
 for ac_func in getudbnam setlim
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_addr in struct utmp" >&5
-echo $ECHO_N "checking for ut_addr in struct utmp... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmp_ut_addr+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+do :
+  as_ac_var=3D`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+eval as_val=3D\$$as_ac_var
+   if test "x$as_val" =3D x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_addr in struct ut=
mp" >&5
+$as_echo_n "checking for ut_addr in struct utmp... " >&6; }
+if test "${ac_cv_type_struct_utmp_ut_addr+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmp.h>
 int
@@ -50117,60 +27129,34 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmp_ut_addr=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmp_ut_addr=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmp_ut_addr" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmp_ut_addr" >&6; }
+  ac_cv_type_struct_utmp_ut_addr=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmp_u=
t_addr" >&5
+$as_echo "$ac_cv_type_struct_utmp_ut_addr" >&6; }
 if test "$ac_cv_type_struct_utmp_ut_addr" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMP_UT_ADDR 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_host in struct utmp" >&5
-echo $ECHO_N "checking for ut_host in struct utmp... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmp_ut_host+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_UTMP_UT_ADDR 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_host in struct ut=
mp" >&5
+$as_echo_n "checking for ut_host in struct utmp... " >&6; }
+if test "${ac_cv_type_struct_utmp_ut_host+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmp.h>
 int
@@ -50181,60 +27167,34 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmp_ut_host=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmp_ut_host=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmp_ut_host" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmp_ut_host" >&6; }
+  ac_cv_type_struct_utmp_ut_host=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmp_u=
t_host" >&5
+$as_echo "$ac_cv_type_struct_utmp_ut_host" >&6; }
 if test "$ac_cv_type_struct_utmp_ut_host" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMP_UT_HOST 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_id in struct utmp" >&5
-echo $ECHO_N "checking for ut_id in struct utmp... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmp_ut_id+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_UTMP_UT_HOST 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_id in struct utmp=
" >&5
+$as_echo_n "checking for ut_id in struct utmp... " >&6; }
+if test "${ac_cv_type_struct_utmp_ut_id+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmp.h>
 int
@@ -50245,60 +27205,34 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmp_ut_id=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmp_ut_id=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmp_ut_id" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmp_ut_id" >&6; }
+  ac_cv_type_struct_utmp_ut_id=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmp_u=
t_id" >&5
+$as_echo "$ac_cv_type_struct_utmp_ut_id" >&6; }
 if test "$ac_cv_type_struct_utmp_ut_id" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMP_UT_ID 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_pid in struct utmp" >&5
-echo $ECHO_N "checking for ut_pid in struct utmp... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmp_ut_pid+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_UTMP_UT_ID 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_pid in struct utm=
p" >&5
+$as_echo_n "checking for ut_pid in struct utmp... " >&6; }
+if test "${ac_cv_type_struct_utmp_ut_pid+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmp.h>
 int
@@ -50309,60 +27243,34 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmp_ut_pid=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmp_ut_pid=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmp_ut_pid" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmp_ut_pid" >&6; }
+  ac_cv_type_struct_utmp_ut_pid=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmp_u=
t_pid" >&5
+$as_echo "$ac_cv_type_struct_utmp_ut_pid" >&6; }
 if test "$ac_cv_type_struct_utmp_ut_pid" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMP_UT_PID 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_type in struct utmp" >&5
-echo $ECHO_N "checking for ut_type in struct utmp... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmp_ut_type+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_UTMP_UT_PID 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_type in struct ut=
mp" >&5
+$as_echo_n "checking for ut_type in struct utmp... " >&6; }
+if test "${ac_cv_type_struct_utmp_ut_type+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmp.h>
 int
@@ -50373,60 +27281,34 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmp_ut_type=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmp_ut_type=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmp_ut_type" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmp_ut_type" >&6; }
+  ac_cv_type_struct_utmp_ut_type=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmp_u=
t_type" >&5
+$as_echo "$ac_cv_type_struct_utmp_ut_type" >&6; }
 if test "$ac_cv_type_struct_utmp_ut_type" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMP_UT_TYPE 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_user in struct utmp" >&5
-echo $ECHO_N "checking for ut_user in struct utmp... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmp_ut_user+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_UTMP_UT_TYPE 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_user in struct ut=
mp" >&5
+$as_echo_n "checking for ut_user in struct utmp... " >&6; }
+if test "${ac_cv_type_struct_utmp_ut_user+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmp.h>
 int
@@ -50437,124 +27319,338 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmp_ut_user=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmp_ut_user=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmp_ut_user" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmp_ut_user" >&6; }
+  ac_cv_type_struct_utmp_ut_user=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmp_u=
t_user" >&5
+$as_echo "$ac_cv_type_struct_utmp_ut_user" >&6; }
 if test "$ac_cv_type_struct_utmp_ut_user" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMP_UT_USER 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_exit in struct utmpx" >&5
-echo $ECHO_N "checking for ut_exit in struct utmpx... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmpx_ut_exit+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_UTMP_UT_USER 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_host in struct ut=
mpx" >&5
+$as_echo_n "checking for ut_host in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_host+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmpx.h>
 int
 main ()
 {
+struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_host
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_struct_utmpx_ut_host=3Dyes
+else
+  ac_cv_type_struct_utmpx_ut_host=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_host" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_host" >&6; }
+if test "$ac_cv_type_struct_utmpx_ut_host" =3D yes; then
+
+
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_HOST 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_id in struct utmp=
x" >&5
+$as_echo_n "checking for ut_id in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_id+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <utmpx.h>
+int
+main ()
+{
+struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_id
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_struct_utmpx_ut_id=3Dyes
+else
+  ac_cv_type_struct_utmpx_ut_id=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_id" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_id" >&6; }
+if test "$ac_cv_type_struct_utmpx_ut_id" =3D yes; then
+
+
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_ID 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_line in struct ut=
mpx" >&5
+$as_echo_n "checking for ut_line in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_line+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <utmpx.h>
+int
+main ()
+{
+struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_line
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_struct_utmpx_ut_line=3Dyes
+else
+  ac_cv_type_struct_utmpx_ut_line=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_line" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_line" >&6; }
+if test "$ac_cv_type_struct_utmpx_ut_line" =3D yes; then
+
+
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_LINE 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_pid in struct utm=
px" >&5
+$as_echo_n "checking for ut_pid in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_pid+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <utmpx.h>
+int
+main ()
+{
+struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_pid
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_struct_utmpx_ut_pid=3Dyes
+else
+  ac_cv_type_struct_utmpx_ut_pid=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_pid" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_pid" >&6; }
+if test "$ac_cv_type_struct_utmpx_ut_pid" =3D yes; then
+
+
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_PID 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_tv in struct utmp=
x" >&5
+$as_echo_n "checking for ut_tv in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_tv+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <utmpx.h>
+int
+main ()
+{
+struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_tv
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_struct_utmpx_ut_tv=3Dyes
+else
+  ac_cv_type_struct_utmpx_ut_tv=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_tv" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_tv" >&6; }
+if test "$ac_cv_type_struct_utmpx_ut_tv" =3D yes; then
+
+
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_TV 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_type in struct ut=
mpx" >&5
+$as_echo_n "checking for ut_type in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_type+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <utmpx.h>
+int
+main ()
+{
+struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_type
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_struct_utmpx_ut_type=3Dyes
+else
+  ac_cv_type_struct_utmpx_ut_type=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_type" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_type" >&6; }
+if test "$ac_cv_type_struct_utmpx_ut_type" =3D yes; then
+
+
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_TYPE 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_user in struct ut=
mpx" >&5
+$as_echo_n "checking for ut_user in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_user+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <utmpx.h>
+int
+main ()
+{
+struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_user
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_struct_utmpx_ut_user=3Dyes
+else
+  ac_cv_type_struct_utmpx_ut_user=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_user" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_user" >&6; }
+if test "$ac_cv_type_struct_utmpx_ut_user" =3D yes; then
+
+
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_USER 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_exit in struct ut=
mpx" >&5
+$as_echo_n "checking for ut_exit in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_exit+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <utmpx.h>
+int
+main ()
+{
 struct utmpx x; memset(&x, 0, sizeof(x)); x.ut_exit
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmpx_ut_exit=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmpx_ut_exit=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmpx_ut_exit" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmpx_ut_exit" >&6; }
+  ac_cv_type_struct_utmpx_ut_exit=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_exit" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_exit" >&6; }
 if test "$ac_cv_type_struct_utmpx_ut_exit" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMPX_UT_EXIT 1
-_ACEOF
-
-
-fi
-
-
-
-
-{ echo "$as_me:$LINENO: checking for ut_syslen in struct utmpx" >&5
-echo $ECHO_N "checking for ut_syslen in struct utmpx... $ECHO_C" >&6; }
-if test "${ac_cv_type_struct_utmpx_ut_syslen+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_EXIT 1" >>confdefs.h
+
+
+fi
+
+
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_syslen in struct =
utmpx" >&5
+$as_echo_n "checking for ut_syslen in struct utmpx... " >&6; }
+if test "${ac_cv_type_struct_utmpx_ut_syslen+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <utmpx.h>
 int
@@ -50565,60 +27661,27 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   ac_cv_type_struct_utmpx_ut_syslen=3Dyes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_struct_utmpx_ut_syslen=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_struct_utmpx_ut_syslen" >&5
-echo "${ECHO_T}$ac_cv_type_struct_utmpx_ut_syslen" >&6; }
+  ac_cv_type_struct_utmpx_ut_syslen=3Dno
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_struct_utmpx_=
ut_syslen" >&5
+$as_echo "$ac_cv_type_struct_utmpx_ut_syslen" >&6; }
 if test "$ac_cv_type_struct_utmpx_ut_syslen" =3D yes; then
=20
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_STRUCT_UTMPX_UT_SYSLEN 1
-_ACEOF
-
-
-fi
-
-
-
-{ echo "$as_me:$LINENO: checking for int8_t" >&5
-echo $ECHO_N "checking for int8_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_int8_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+$as_echo "#define HAVE_STRUCT_UTMPX_UT_SYSLEN 1" >>confdefs.h
+
+
+fi
+
+
+
+ac_fn_c_check_type "$LINENO" "int8_t" "ac_cv_type_int8_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -50635,49 +27698,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef int8_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_int8_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_int8_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_int8_t" >&5
-echo "${ECHO_T}$ac_cv_type_int8_t" >&6; }
-if test $ac_cv_type_int8_t =3D yes; then
+"
+if test "x$ac_cv_type_int8_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_INT8_T 1
@@ -50685,18 +27707,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for int16_t" >&5
-echo $ECHO_N "checking for int16_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_int16_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "int16_t" "ac_cv_type_int16_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -50713,49 +27724,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef int16_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_int16_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_int16_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_int16_t" >&5
-echo "${ECHO_T}$ac_cv_type_int16_t" >&6; }
-if test $ac_cv_type_int16_t =3D yes; then
+"
+if test "x$ac_cv_type_int16_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_INT16_T 1
@@ -50763,18 +27733,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for int32_t" >&5
-echo $ECHO_N "checking for int32_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_int32_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "int32_t" "ac_cv_type_int32_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -50791,49 +27750,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef int32_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_int32_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_int32_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_int32_t" >&5
-echo "${ECHO_T}$ac_cv_type_int32_t" >&6; }
-if test $ac_cv_type_int32_t =3D yes; then
+"
+if test "x$ac_cv_type_int32_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_INT32_T 1
@@ -50841,18 +27759,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for int64_t" >&5
-echo $ECHO_N "checking for int64_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_int64_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "int64_t" "ac_cv_type_int64_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -50869,49 +27776,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef int64_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_int64_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_int64_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_int64_t" >&5
-echo "${ECHO_T}$ac_cv_type_int64_t" >&6; }
-if test $ac_cv_type_int64_t =3D yes; then
+"
+if test "x$ac_cv_type_int64_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_INT64_T 1
@@ -50919,18 +27785,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for u_int8_t" >&5
-echo $ECHO_N "checking for u_int8_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_u_int8_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "u_int8_t" "ac_cv_type_u_int8_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -50947,49 +27802,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef u_int8_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_u_int8_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_u_int8_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_u_int8_t" >&5
-echo "${ECHO_T}$ac_cv_type_u_int8_t" >&6; }
-if test $ac_cv_type_u_int8_t =3D yes; then
+"
+if test "x$ac_cv_type_u_int8_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_U_INT8_T 1
@@ -50997,18 +27811,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for u_int16_t" >&5
-echo $ECHO_N "checking for u_int16_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_u_int16_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "u_int16_t" "ac_cv_type_u_int16_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -51025,49 +27828,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef u_int16_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_u_int16_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_u_int16_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_u_int16_t" >&5
-echo "${ECHO_T}$ac_cv_type_u_int16_t" >&6; }
-if test $ac_cv_type_u_int16_t =3D yes; then
+"
+if test "x$ac_cv_type_u_int16_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_U_INT16_T 1
@@ -51075,18 +27837,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for u_int32_t" >&5
-echo $ECHO_N "checking for u_int32_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_u_int32_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "u_int32_t" "ac_cv_type_u_int32_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -51103,49 +27854,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef u_int32_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_u_int32_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_u_int32_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_u_int32_t" >&5
-echo "${ECHO_T}$ac_cv_type_u_int32_t" >&6; }
-if test $ac_cv_type_u_int32_t =3D yes; then
+"
+if test "x$ac_cv_type_u_int32_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_U_INT32_T 1
@@ -51153,18 +27863,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for u_int64_t" >&5
-echo $ECHO_N "checking for u_int64_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_u_int64_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "u_int64_t" "ac_cv_type_u_int64_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -51181,49 +27880,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef u_int64_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_u_int64_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_u_int64_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_u_int64_t" >&5
-echo "${ECHO_T}$ac_cv_type_u_int64_t" >&6; }
-if test $ac_cv_type_u_int64_t =3D yes; then
+"
+if test "x$ac_cv_type_u_int64_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_U_INT64_T 1
@@ -51231,18 +27889,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for uint8_t" >&5
-echo $ECHO_N "checking for uint8_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_uint8_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "uint8_t" "ac_cv_type_uint8_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -51259,49 +27906,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef uint8_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_uint8_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_uint8_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_uint8_t" >&5
-echo "${ECHO_T}$ac_cv_type_uint8_t" >&6; }
-if test $ac_cv_type_uint8_t =3D yes; then
+"
+if test "x$ac_cv_type_uint8_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_UINT8_T 1
@@ -51309,18 +27915,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for uint16_t" >&5
-echo $ECHO_N "checking for uint16_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_uint16_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "uint16_t" "ac_cv_type_uint16_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -51337,49 +27932,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef uint16_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_uint16_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_uint16_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_uint16_t" >&5
-echo "${ECHO_T}$ac_cv_type_uint16_t" >&6; }
-if test $ac_cv_type_uint16_t =3D yes; then
+"
+if test "x$ac_cv_type_uint16_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_UINT16_T 1
@@ -51387,18 +27941,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for uint32_t" >&5
-echo $ECHO_N "checking for uint32_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_uint32_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "uint32_t" "ac_cv_type_uint32_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -51415,49 +27958,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef uint32_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_uint32_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_uint32_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_uint32_t" >&5
-echo "${ECHO_T}$ac_cv_type_uint32_t" >&6; }
-if test $ac_cv_type_uint32_t =3D yes; then
+"
+if test "x$ac_cv_type_uint32_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_UINT32_T 1
@@ -51465,18 +27967,7 @@
=20
=20
 fi
-{ echo "$as_me:$LINENO: checking for uint64_t" >&5
-echo $ECHO_N "checking for uint64_t... $ECHO_C" >&6; }
-if test "${ac_cv_type_uint64_t+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
+ac_fn_c_check_type "$LINENO" "uint64_t" "ac_cv_type_uint64_t" "
 #ifdef HAVE_INTTYPES_H
 #include <inttypes.h>
 #endif
@@ -51493,49 +27984,8 @@
 #include <netinet/in6_machtypes.h>
 #endif
=20
-
-typedef uint64_t ac__type_new_;
-int
-main ()
-{
-if ((ac__type_new_ *) 0)
-  return 0;
-if (sizeof (ac__type_new_))
-  return 0;
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_type_uint64_t=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_type_uint64_t=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_type_uint64_t" >&5
-echo "${ECHO_T}$ac_cv_type_uint64_t" >&6; }
-if test $ac_cv_type_uint64_t =3D yes; then
+"
+if test "x$ac_cv_type_uint64_t" =3D x""yes; then :
=20
 cat >>confdefs.h <<_ACEOF
 #define HAVE_UINT64_T 1
@@ -51547,20 +27997,16 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking for framework security" >&5
-echo $ECHO_N "checking for framework security... $ECHO_C" >&6; }
-if test "${rk_cv_framework_security+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for framework security" =
>&5
+$as_echo_n "checking for framework security... " >&6; }
+if test "${rk_cv_framework_security+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
=20
 if test "$rk_cv_framework_security" !=3D yes; then
 	ac_save_LIBS=3D"$LIBS"
 	LIBS=3D"$ac_save_LIBS -framework Security -framework CoreFoundation"
-	cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+	cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <Security/Security.h>
=20
@@ -51575,34 +28021,11 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+if ac_fn_c_try_link "$LINENO"; then :
   rk_cv_framework_security=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
 	LIBS=3D"$ac_save_LIBS"
 fi
=20
@@ -51611,15 +28034,13 @@
=20
 if test "$rk_cv_framework_security" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_FRAMEWORK_SECURITY 1
-_ACEOF
-
-   { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-else
-   { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+$as_echo "#define HAVE_FRAMEWORK_SECURITY 1" >>confdefs.h
+
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+else
+   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
  if test "$rk_cv_framework_security" =3D yes; then
   FRAMEWORK_SECURITY_TRUE=3D
@@ -51633,16 +28054,12 @@
 if test "$rk_cv_framework_security" =3D yes; then
=20
 if test "$ac_cv_func_SecKeyGetCSPHandle+set" !=3D set -o "$ac_cv_func_SecK=
eyGetCSPHandle" =3D yes; then
-{ echo "$as_me:$LINENO: checking if SecKeyGetCSPHandle needs a prototype" =
>&5
-echo $ECHO_N "checking if SecKeyGetCSPHandle needs a prototype... $ECHO_C"=
 >&6; }
-if test "${ac_cv_func_SecKeyGetCSPHandle_noproto+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if SecKeyGetCSPHandle ne=
eds a prototype" >&5
+$as_echo_n "checking if SecKeyGetCSPHandle needs a prototype... " >&6; }
+if test "${ac_cv_func_SecKeyGetCSPHandle_noproto+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <Security/Security.h>
 struct foo { int foo; } xx;
@@ -51655,371 +28072,68 @@
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
+if ac_fn_c_try_compile "$LINENO"; then :
   eval "ac_cv_func_SecKeyGetCSPHandle_noproto=3Dyes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "ac_cv_func_SecKeyGetCSPHandle_noproto=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_SecKeyGetCSPHandle_noproto" >&5
-echo "${ECHO_T}$ac_cv_func_SecKeyGetCSPHandle_noproto" >&6; }
+  eval "ac_cv_func_SecKeyGetCSPHandle_noproto=3Dno"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_SecKeyGetCSPH=
andle_noproto" >&5
+$as_echo "$ac_cv_func_SecKeyGetCSPHandle_noproto" >&6; }
 if test "$ac_cv_func_SecKeyGetCSPHandle_noproto" =3D yes; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define NEED_SECKEYGETCSPHANDLE_PROTO 1
-_ACEOF
-
-fi
-fi
-
-fi
-
-
-
-
-
-
-
-{ echo "$as_me:$LINENO: checking for el_init" >&5
-echo $ECHO_N "checking for el_init... $ECHO_C" >&6; }
-if test "${ac_cv_funclib_el_init+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-if eval "test \"\$ac_cv_func_el_init\" !=3D yes" ; then
-	ac_save_LIBS=3D"$LIBS"
-	for ac_lib in "" edit; do
-		case "$ac_lib" in
-		"") ;;
-		yes) ac_lib=3D"" ;;
-		no) continue ;;
-		-l*) ;;
-		*) ac_lib=3D"-l$ac_lib" ;;
-		esac
-		LIBS=3D" $ac_lib $LIB_tgetent $ac_save_LIBS"
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-
-int
-main ()
-{
-el_init()
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "if test -n \"$ac_lib\";then ac_cv_funclib_el_init=3D$ac_lib; else =
ac_cv_funclib_el_init=3Dyes; fi";break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-	done
-	eval "ac_cv_funclib_el_init=3D\${ac_cv_funclib_el_init-no}"
-	LIBS=3D"$ac_save_LIBS"
-fi
-
-fi
-
-
-eval "ac_res=3D\$ac_cv_funclib_el_init"
-
-if false; then
-
-for ac_func in el_init
-do
-as_ac_var=3D`echo "ac_cv_func_$ac_func" | $as_tr_sh`
-{ echo "$as_me:$LINENO: checking for $ac_func" >&5
-echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
-if { as_var=3D$as_ac_var; eval "test \"\${$as_var+set}\" =3D set"; }; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define $ac_func to an innocuous variant, in case <limits.h> declares $a=
c_func.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define $ac_func innocuous_$ac_func
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $ac_func
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $ac_func ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_$ac_func || defined __stub___$ac_func
-choke me
-#endif
-
-int
-main ()
-{
-return $ac_func ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  eval "$as_ac_var=3Dyes"
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	eval "$as_ac_var=3Dno"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-ac_res=3D`eval echo '${'$as_ac_var'}'`
-	       { echo "$as_me:$LINENO: result: $ac_res" >&5
-echo "${ECHO_T}$ac_res" >&6; }
-if test `eval echo '${'$as_ac_var'}'` =3D yes; then
-  cat >>confdefs.h <<_ACEOF
-#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-done
-
-fi
-# el_init
-eval "ac_tr_func=3DHAVE_`echo el_init | tr abcdefghijklmnopqrstuvwxyz ABCD=
EFGHIJKLMNOPQRSTUVWXYZ`"
-eval "ac_tr_lib=3DHAVE_LIB`echo $ac_res | sed -e 's/-l//' | tr abcdefghijk=
lmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ`"
-eval "LIB_el_init=3D$ac_res"
-
-case "$ac_res" in
-	yes)
-	eval "ac_cv_func_el_init=3Dyes"
-	eval "LIB_el_init=3D"
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_func 1
-_ACEOF
-
-	{ echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
-	;;
-	no)
-	eval "ac_cv_func_el_init=3Dno"
-	eval "LIB_el_init=3D"
-	{ echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-	;;
-	*)
-	eval "ac_cv_func_el_init=3Dyes"
-	eval "ac_cv_lib_`echo "$ac_res" | sed 's/-l//'`=3Dyes"
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_func 1
-_ACEOF
-
-	cat >>confdefs.h <<_ACEOF
-#define $ac_tr_lib 1
-_ACEOF
-
-	{ echo "$as_me:$LINENO: result: yes, in $ac_res" >&5
-echo "${ECHO_T}yes, in $ac_res" >&6; }
-	;;
-esac
-
-
-if test "$ac_cv_func_el_init" =3D yes ; then
-	{ echo "$as_me:$LINENO: checking for four argument el_init" >&5
-echo $ECHO_N "checking for four argument el_init... $ECHO_C" >&6; }
-if test "${ac_cv_func_el_init_four+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-
-		cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdio.h>
-			#include <histedit.h>
-int
-main ()
-{
-el_init("", NULL, NULL, NULL);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (ac_try=3D"$ac_compile"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_compile") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then
-  ac_cv_func_el_init_four=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_el_init_four=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_el_init_four" >&5
-echo "${ECHO_T}$ac_cv_func_el_init_four" >&6; }
-	if test "$ac_cv_func_el_init_four" =3D yes; then
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_FOUR_VALUED_EL_INIT 1
-_ACEOF
-
-	fi
-fi
+$as_echo "#define NEED_SECKEYGETCSPHANDLE_PROTO 1" >>confdefs.h
+
+fi
+fi
+
+fi
+
+
+
+
=20
=20
 ac_foo=3Dno
+build_editline=3Dno
 if test "$with_readline" =3D yes; then
 	:
+elif test "$with_libedit" =3D yes; then
+   	LIB_readline=3D"${LIB_libedit}"
 elif test "$ac_cv_func_readline" =3D yes; then
 	:
-elif test "$ac_cv_func_el_init" =3D yes; then
-	ac_foo=3Dyes
-	LIB_readline=3D"\$(top_builddir)/lib/editline/libel_compat.la \$(LIB_el_i=
nit) \$(LIB_tgetent)"
-else
-	LIB_readline=3D"\$(top_builddir)/lib/editline/libeditline.la \$(LIB_tgete=
nt)"
-fi
- if test "$ac_foo" =3D yes; then
-  el_compat_TRUE=3D
-  el_compat_FALSE=3D'#'
-else
-  el_compat_TRUE=3D'#'
-  el_compat_FALSE=3D
-fi
-
-
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_READLINE 1
-_ACEOF
-
-
-
-
-
-cat >>confdefs.h <<\_ACEOF
-#define AUTHENTICATION 1
-_ACEOF
-
-cat >>confdefs.h <<\_ACEOF
-#define ENCRYPTION 1
-_ACEOF
-
-cat >>confdefs.h <<\_ACEOF
-#define DES_ENCRYPTION 1
-_ACEOF
-
-cat >>confdefs.h <<\_ACEOF
-#define DIAGNOSTICS 1
-_ACEOF
-
-cat >>confdefs.h <<\_ACEOF
-#define OLD_ENVIRON 1
-_ACEOF
-if false; then
-
-cat >>confdefs.h <<\_ACEOF
-#define ENV_HACK 1
-_ACEOF
+else
+	build_libedit=3Dyes
+	LIB_readline=3D"\$(top_builddir)/lib/libedit/src/libheimedit.la \$(LIB_tg=
etent)"
+fi
+ if test "$build_libedit" =3D yes; then
+  LIBEDIT_TRUE=3D
+  LIBEDIT_FALSE=3D'#'
+else
+  LIBEDIT_TRUE=3D'#'
+  LIBEDIT_FALSE=3D
+fi
+
+
+$as_echo "#define HAVE_READLINE 1" >>confdefs.h
+
+
+
+
+
+$as_echo "#define AUTHENTICATION 1" >>confdefs.h
+
+$as_echo "#define ENCRYPTION 1" >>confdefs.h
+
+$as_echo "#define DES_ENCRYPTION 1" >>confdefs.h
+
+$as_echo "#define DIAGNOSTICS 1" >>confdefs.h
+
+$as_echo "#define OLD_ENVIRON 1" >>confdefs.h
+if false; then
+
+$as_echo "#define ENV_HACK 1" >>confdefs.h
=20
 fi
=20
@@ -52032,102 +28146,21 @@
 *-*-aix3*|*-*-sunos4*|*-*-osf*|*-*-hpux1[01]*)
 	;;
 *)
-	{ echo "$as_me:$LINENO: checking for getmsg" >&5
-echo $ECHO_N "checking for getmsg... $ECHO_C" >&6; }
-if test "${ac_cv_func_getmsg+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-/* Define getmsg to an innocuous variant, in case <limits.h> declares getm=
sg.
-   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
-#define getmsg innocuous_getmsg
-
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char getmsg (); below.
-    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
-    <limits.h> exists even on freestanding compilers.  */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef getmsg
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char getmsg ();
-/* The GNU C library defines this for functions which it implements
-    to always fail with ENOSYS.  Some functions are actually named
-    something starting with __ and the normal name is an alias.  */
-#if defined __stub_getmsg || defined __stub___getmsg
-choke me
-#endif
-
-int
-main ()
-{
-return getmsg ();
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
-  ac_cv_func_getmsg=3Dyes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	ac_cv_func_getmsg=3Dno
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getmsg" >&5
-echo "${ECHO_T}$ac_cv_func_getmsg" >&6; }
+	ac_fn_c_check_func "$LINENO" "getmsg" "ac_cv_func_getmsg"
+if test "x$ac_cv_func_getmsg" =3D x""yes; then :
+
+fi
=20
 	if test "$ac_cv_func_getmsg" =3D "yes"; then
-		{ echo "$as_me:$LINENO: checking if getmsg works" >&5
-echo $ECHO_N "checking if getmsg works... $ECHO_C" >&6; }
-if test "${ac_cv_func_getmsg_works+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test "$cross_compiling" =3D yes; then
+		{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getmsg works" >&5
+$as_echo_n "checking if getmsg works... " >&6; }
+if test "${ac_cv_func_getmsg_works+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "$cross_compiling" =3D yes; then :
   ac_cv_func_getmsg_works=3Dno
 else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
=20
 			#include <stdio.h>
@@ -52143,58 +28176,29 @@
 			}
=20
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   ac_cv_func_getmsg_works=3Dyes
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-ac_cv_func_getmsg_works=3Dno
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: $ac_cv_func_getmsg_works" >&5
-echo "${ECHO_T}$ac_cv_func_getmsg_works" >&6; }
+  ac_cv_func_getmsg_works=3Dno
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getmsg_works"=
 >&5
+$as_echo "$ac_cv_func_getmsg_works" >&6; }
 		if test "$ac_cv_func_getmsg_works" =3D "yes"; then
=20
-cat >>confdefs.h <<\_ACEOF
-#define HAVE_GETMSG 1
-_ACEOF
-
-
-cat >>confdefs.h <<\_ACEOF
-#define STREAMSPTY 1
-_ACEOF
-
-		fi
-	fi
-	;;
-esac
-
+$as_echo "#define HAVE_GETMSG 1" >>confdefs.h
+
+
+$as_echo "#define STREAMSPTY 1" >>confdefs.h
+
+		fi
+	fi
+	;;
+esac
=20
=20
=20
@@ -52203,10 +28207,10 @@
=20
 # Extract the first word of "compile_et", so it can be a program name with=
 args.
 set dummy compile_et; ac_word=3D$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_prog_COMPILE_ET+set}" =3D set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_COMPILE_ET+set}" =3D set; then :
+  $as_echo_n "(cached) " >&6
 else
   if test -n "$COMPILE_ET"; then
   ac_cv_prog_COMPILE_ET=3D"$COMPILE_ET" # Let the user override the test.
@@ -52216,25 +28220,25 @@
 do
   IFS=3D$as_save_IFS
   test -z "$as_dir" && as_dir=3D.
-  for ac_exec_ext in '' $ac_executable_extensions; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
   if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_w=
ord$ac_exec_ext"; }; then
     ac_cv_prog_COMPILE_ET=3D"compile_et"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_=
ext" >&5
+    break 2
+  fi
+done
+  done
 IFS=3D$as_save_IFS
=20
 fi
 fi
 COMPILE_ET=3D$ac_cv_prog_COMPILE_ET
 if test -n "$COMPILE_ET"; then
-  { echo "$as_me:$LINENO: result: $COMPILE_ET" >&5
-echo "${ECHO_T}$COMPILE_ET" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $COMPILE_ET" >&5
+$as_echo "$COMPILE_ET" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
=20
=20
@@ -52244,8 +28248,8 @@
 krb_cv_compile_et_cross=3Dno
 if test "${COMPILE_ET}" =3D "compile_et"; then
=20
-{ echo "$as_me:$LINENO: checking whether compile_et has the features we ne=
ed" >&5
-echo $ECHO_N "checking whether compile_et has the features we need... $ECH=
O_C" >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compile_et has t=
he features we need" >&5
+$as_echo_n "checking whether compile_et has the features we need... " >&6;=
 }
 cat > conftest_et.et <<'EOF'
 error_table test conf
 prefix CONFTEST
@@ -52260,10 +28264,11 @@
   if test -d "/usr/include/et"; then
     CPPFLAGS=3D"-I/usr/include/et ${CPPFLAGS}"
   fi
-    if test "$cross_compiling" =3D yes; then
+    if test "$cross_compiling" =3D yes; then :
   krb_cv_compile_et=3D"yes" krb_cv_compile_et_cross=3Dyes
 else
-  cat >conftest.$ac_ext <<_ACEOF
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
=20
 #include <com_err.h>
 #include <string.h>
@@ -52275,66 +28280,38 @@
 return (CONFTEST_CODE2 - CONFTEST_CODE1) !=3D 127;}
=20
 _ACEOF
-rm -f conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && { ac_try=3D'./conftest$ac_exeext'
-  { (case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_try") 2>&5
-  ac_status=3D$?
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); }; }; then
+if ac_fn_c_try_run "$LINENO"; then :
   krb_cv_compile_et=3D"yes"
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-( exit $ac_status )
-CPPFLAGS=3D"${save_CPPFLAGS}"
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conft=
est.$ac_objext conftest.$ac_ext
-fi
-
-
-fi
-{ echo "$as_me:$LINENO: result: ${krb_cv_compile_et}" >&5
-echo "${ECHO_T}${krb_cv_compile_et}" >&6; }
+  CPPFLAGS=3D"${save_CPPFLAGS}"
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: ${krb_cv_compile_et}" >&5
+$as_echo "${krb_cv_compile_et}" >&6; }
 if test "${krb_cv_compile_et}" =3D "yes" -a "${krb_cv_compile_et_cross}" =
=3D no; then
-  { echo "$as_me:$LINENO: checking for if com_err generates a initialize_c=
onf_error_table_r" >&5
-echo $ECHO_N "checking for if com_err generates a initialize_conf_error_ta=
ble_r... $ECHO_C" >&6; }
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for if com_err generat=
es a initialize_conf_error_table_r" >&5
+$as_echo_n "checking for if com_err generates a initialize_conf_error_tabl=
e_r... " >&6; }
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include "conftest_et.h"
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "initialize_conf_error_table_r.*struct et_list" >/dev/null 2>&1; =
then
+  $EGREP "initialize_conf_error_table_r.*struct et_list" >/dev/null 2>&1; =
then :
   krb_cv_com_err_need_r=3D"ok"
 fi
 rm -f conftest*
=20
   if test X"$krb_cv_com_err_need_r" =3D X ; then
-    { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
     krb_cv_compile_et=3Dno
   else
-    { echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6; }
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
   fi
 fi
 rm -fr conftest*
@@ -52345,13 +28322,9 @@
 elif test "${krb_cv_compile_et}" =3D "yes"; then
     krb_cv_save_LIBS=3D"${LIBS}"
   LIBS=3D"${LIBS} -lcom_err"
-  { echo "$as_me:$LINENO: checking for com_err" >&5
-echo $ECHO_N "checking for com_err... $ECHO_C" >&6; }
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for com_err" >&5
+$as_echo_n "checking for com_err... " >&6; }
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <com_err.h>
 int
@@ -52361,41 +28334,21 @@
     const char *p;
     p =3D error_message(0);
     initialize_error_table_r(0,0,0,0);
-
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (ac_try=3D"$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=3D\$ac_try;;
-  *) ac_try_echo=3D$ac_try;;
-esac
-eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
-  (eval "$ac_link") 2>conftest.er1
-  ac_status=3D$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? =3D $ac_status" >&5
-  (exit $ac_status); } && {
-	 test -z "$ac_c_werror_flag" ||
-	 test ! -s conftest.err
-       } && test -s conftest$ac_exeext &&
-       $as_test_x conftest$ac_exeext; then
+    com_right_r(0, 0, 0, 0);
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
   krb_cv_com_err=3D"yes"
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-	krb_cv_com_err=3D"no"; CPPFLAGS=3D"${save_CPPFLAGS}"
-fi
-
-rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
-      conftest$ac_exeext conftest.$ac_ext
-  { echo "$as_me:$LINENO: result: ${krb_cv_com_err}" >&5
-echo "${ECHO_T}${krb_cv_com_err}" >&6; }
+  krb_cv_com_err=3D"no"; CPPFLAGS=3D"${save_CPPFLAGS}"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${krb_cv_com_err}" >&5
+$as_echo "${krb_cv_com_err}" >&6; }
   LIBS=3D"${krb_cv_save_LIBS}"
 else
     krb_cv_com_err=3D"no"
@@ -52406,16 +28359,18 @@
     LIB_com_err=3D"-lcom_err"
     LIB_com_err_a=3D""
     LIB_com_err_so=3D""
-    { echo "$as_me:$LINENO: Using the already-installed com_err" >&5
-echo "$as_me: Using the already-installed com_err" >&6;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Using the already-installed c=
om_err" >&5
+$as_echo "$as_me: Using the already-installed com_err" >&6;}
+    COMPILE_ET=3D"${ac_cv_prog_COMPILE_ET}"
     localcomerr=3Dno
 elif test "${krb_cv_com_err}" =3D "cross"; then
     DIR_com_err=3D"com_err"
     LIB_com_err=3D"\$(top_builddir)/lib/com_err/libcom_err.la"
     LIB_com_err_a=3D"\$(top_builddir)/lib/com_err/.libs/libcom_err.a"
     LIB_com_err_so=3D"\$(top_builddir)/lib/com_err/.libs/libcom_err.so"
-    { echo "$as_me:$LINENO: Using our own com_err with toolchain compile_e=
t" >&5
-echo "$as_me: Using our own com_err with toolchain compile_et" >&6;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Using our own com_err with to=
olchain compile_et" >&5
+$as_echo "$as_me: Using our own com_err with toolchain compile_et" >&6;}
+    COMPILE_ET=3D"${ac_cv_prog_COMPILE_ET}"
     localcomerr=3Dyes
 else
     COMPILE_ET=3D"\$(top_builddir)/lib/com_err/compile_et"
@@ -52423,8 +28378,8 @@
     LIB_com_err=3D"\$(top_builddir)/lib/com_err/libcom_err.la"
     LIB_com_err_a=3D"\$(top_builddir)/lib/com_err/.libs/libcom_err.a"
     LIB_com_err_so=3D"\$(top_builddir)/lib/com_err/.libs/libcom_err.so"
-    { echo "$as_me:$LINENO: Using our own com_err" >&5
-echo "$as_me: Using our own com_err" >&6;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Using our own com_err" >&5
+$as_echo "$as_me: Using our own com_err" >&6;}
     localcomerr=3Dyes
 fi
  if test "$localcomerr" =3D yes; then
@@ -52442,8 +28397,9 @@
=20
=20
=20
-{ echo "$as_me:$LINENO: checking which authentication modules should be bu=
ilt" >&5
-echo $ECHO_N "checking which authentication modules should be built... $EC=
HO_C" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking which authentication mod=
ules should be built" >&5
+$as_echo_n "checking which authentication modules should be built... " >&6=
; }
=20
 z=3D'sia afskauthlib'
 LIB_AUTH_SUBDIRS=3D
@@ -52474,11 +28430,11 @@
 esac
 done
 if test "$LIB_AUTH_SUBDIRS"; then
-	{ echo "$as_me:$LINENO: result: $LIB_AUTH_SUBDIRS" >&5
-echo "${ECHO_T}$LIB_AUTH_SUBDIRS" >&6; }
-else
-	{ echo "$as_me:$LINENO: result: none" >&5
-echo "${ECHO_T}none" >&6; }
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIB_AUTH_SUBDIRS" >&5
+$as_echo "$LIB_AUTH_SUBDIRS" >&6; }
+else
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5
+$as_echo "none" >&6; }
 fi
=20
=20
@@ -52560,7 +28516,7 @@
=20
=20
 # Check whether --enable-developer was given.
-if test "${enable_developer+set}" =3D set; then
+if test "${enable_developer+set}" =3D set; then :
   enableval=3D$enable_developer;
 fi
=20
@@ -52576,6 +28532,7 @@
   #   -Wcast-align doesn't work well on alpha osf/1
   #   -Wmissing-prototypes -Wpointer-arith -Wbad-function-cast
   #   -Wmissing-declarations -Wnested-externs
+  #   -Wstrict-overflow=3D5
   WFLAGS=3D"-Wall -Wmissing-prototypes -Wpointer-arith -Wbad-function-cast=
 -Wmissing-declarations -Wnested-externs $dwflags"
   WFLAGS_NOUNUSED=3D"-Wno-unused"
   WFLAGS_NOIMPLICITINT=3D"-Wno-implicit-int"
@@ -52586,7 +28543,22 @@
=20
=20
=20
-ac_config_files=3D"$ac_config_files Makefile etc/Makefile include/Makefile=
 include/gssapi/Makefile include/hcrypto/Makefile include/kadm5/Makefile li=
b/Makefile lib/45/Makefile lib/auth/Makefile lib/auth/afskauthlib/Makefile =
lib/auth/pam/Makefile lib/auth/sia/Makefile lib/asn1/Makefile lib/com_err/M=
akefile lib/hcrypto/Makefile lib/editline/Makefile lib/hx509/Makefile lib/g=
ssapi/Makefile lib/ntlm/Makefile lib/hdb/Makefile lib/kadm5/Makefile lib/ka=
fs/Makefile lib/kdfs/Makefile lib/krb5/Makefile lib/otp/Makefile lib/roken/=
Makefile lib/sl/Makefile lib/vers/Makefile kuser/Makefile kpasswd/Makefile =
kadmin/Makefile admin/Makefile kcm/Makefile kdc/Makefile appl/Makefile appl=
/afsutil/Makefile appl/ftp/Makefile appl/ftp/common/Makefile appl/ftp/ftp/M=
akefile appl/ftp/ftpd/Makefile appl/gssmask/Makefile appl/kx/Makefile appl/=
login/Makefile appl/otp/Makefile appl/popper/Makefile appl/push/Makefile ap=
pl/rsh/Makefile appl/rcp/Makefile appl/su/Makefile appl/xnlock/Makefile app=
l/telnet/Makefile appl/telnet/libtelnet/Makefile appl/telnet/telnet/Makefil=
e appl/telnet/telnetd/Makefile appl/test/Makefile appl/kf/Makefile appl/dce=
utils/Makefile tests/Makefile tests/can/Makefile tests/db/Makefile tests/kd=
c/Makefile tests/ldap/Makefile tests/gss/Makefile tests/java/Makefile tests=
/plugin/Makefile packages/Makefile packages/mac/Makefile packages/debian/Ma=
kefile doc/Makefile tools/Makefile"
+
+# Check whether --enable-heimdal-documentation was given.
+if test "${enable_heimdal_documentation+set}" =3D set; then :
+  enableval=3D$enable_heimdal_documentation;
+fi
+
+ if test "$enable_heimdal_documentation" !=3D no; then
+  HEIMDAL_DOCUMENTATION_TRUE=3D
+  HEIMDAL_DOCUMENTATION_FALSE=3D'#'
+else
+  HEIMDAL_DOCUMENTATION_TRUE=3D'#'
+  HEIMDAL_DOCUMENTATION_FALSE=3D
+fi
+
+
+ac_config_files=3D"$ac_config_files Makefile etc/Makefile include/Makefile=
 include/gssapi/Makefile include/hcrypto/Makefile include/kadm5/Makefile li=
b/Makefile base/Makefile lib/asn1/Makefile lib/com_err/Makefile lib/hcrypto=
/Makefile lib/hx509/Makefile lib/gssapi/Makefile lib/ntlm/Makefile lib/hdb/=
Makefile lib/ipc/Makefile lib/kadm5/Makefile lib/kafs/Makefile lib/kdfs/Mak=
efile lib/krb5/Makefile lib/otp/Makefile lib/roken/Makefile lib/sl/Makefile=
 lib/sqlite/Makefile lib/vers/Makefile lib/wind/Makefile po/Makefile kuser/=
Makefile kpasswd/Makefile kadmin/Makefile admin/Makefile kcm/Makefile kdc/M=
akefile appl/Makefile appl/afsutil/Makefile appl/ftp/Makefile appl/ftp/comm=
on/Makefile appl/ftp/ftp/Makefile appl/ftp/ftpd/Makefile appl/gssmask/Makef=
ile appl/kx/Makefile appl/login/Makefile appl/otp/Makefile appl/popper/Make=
file appl/push/Makefile appl/rsh/Makefile appl/rcp/Makefile appl/su/Makefil=
e appl/xnlock/Makefile appl/telnet/Makefile appl/telnet/libtelnet/Makefile =
appl/telnet/telnet/Makefile appl/telnet/telnetd/Makefile appl/test/Makefile=
 appl/kf/Makefile appl/dceutils/Makefile tests/Makefile tests/bin/Makefile =
tests/can/Makefile tests/db/Makefile tests/kdc/Makefile tests/ldap/Makefile=
 tests/gss/Makefile tests/java/Makefile tests/plugin/Makefile packages/Make=
file packages/mac/Makefile doc/Makefile tools/Makefile"
=20
=20
 cat >confcache <<\_ACEOF
@@ -52616,12 +28588,13 @@
     case $ac_val in #(
     *${as_nl}*)
       case $ac_var in #(
-      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var cont=
ains a newline." >&5
-echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache vari=
able $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;=
} ;;
       esac
       case $ac_var in #(
       _ | IFS | as_nl) ;; #(
-      *) $as_unset $ac_var ;;
+      BASH_ARGV | BASH_SOURCE) eval $ac_var=3D ;; #(
+      *) { eval $ac_var=3D; unset $ac_var;} ;;
       esac ;;
     esac
   done
@@ -52629,8 +28602,8 @@
   (set) 2>&1 |
     case $as_nl`(ac_space=3D' '; set) 2>&1` in #(
     *${as_nl}ac_space=3D\ *)
-      # `set' does not quote correctly, so add quotes (double-quote
-      # substitution turns \\\\ into \\, and sed turns \\ into \).
+      # `set' does not quote correctly, so add quotes: double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \.
       sed -n \
 	"s/'/'\\\\''/g;
 	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=3D\\(.*\\)/\\1=3D'\\2'/p"
@@ -52653,12 +28626,12 @@
 if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
   if test -w "$cache_file"; then
     test "x$cache_file" !=3D "x/dev/null" &&
-      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
-echo "$as_me: updating cache $cache_file" >&6;}
+      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file"=
 >&5
+$as_echo "$as_me: updating cache $cache_file" >&6;}
     cat confcache >$cache_file
   else
-    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
-echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache=
 $cache_file" >&5
+$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
   fi
 fi
 rm -f confcache
@@ -52674,255 +28647,206 @@
 for ac_i in : $LIBOBJS; do test "x$ac_i" =3D x: && continue
   # 1. Remove the extension, and $U if already installed.
   ac_script=3D's/\$U\././;s/\.o$//;s/\.obj$//'
-  ac_i=3D`echo "$ac_i" | sed "$ac_script"`
+  ac_i=3D`$as_echo "$ac_i" | sed "$ac_script"`
   # 2. Prepend LIBOBJDIR.  When used with automake>=3D1.10 LIBOBJDIR
   #    will be set to the directory where LIBOBJS objects are built.
-  ac_libobjs=3D"$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
-  ac_ltlibobjs=3D"$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
+  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
 done
 LIBOBJS=3D$ac_libobjs
=20
 LTLIBOBJS=3D$ac_ltlibobjs
=20
=20
+ if test -n "$EXEEXT"; then
+  am__EXEEXT_TRUE=3D
+  am__EXEEXT_FALSE=3D'#'
+else
+  am__EXEEXT_TRUE=3D'#'
+  am__EXEEXT_FALSE=3D
+fi
+
 if test -z "${MAINTAINER_MODE_TRUE}" && test -z "${MAINTAINER_MODE_FALSE}"=
; then
-  { { echo "$as_me:$LINENO: error: conditional \"MAINTAINER_MODE\" was nev=
er defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"MAINTAINER_MODE\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"MAINTAINER_MODE\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then
+  as_fn_error "conditional \"AMDEP\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; th=
en
+  as_fn_error "conditional \"am__fastdepCC\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${AIX_TRUE}" && test -z "${AIX_FALSE}"; then
+  as_fn_error "conditional \"AIX\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${AIX4_TRUE}" && test -z "${AIX4_FALSE}"; then
+  as_fn_error "conditional \"AIX4\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${HAVE_DLOPEN_TRUE}" && test -z "${HAVE_DLOPEN_FALSE}"; then
+  as_fn_error "conditional \"HAVE_DLOPEN\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${AIX_DYNAMIC_AFS_TRUE}" && test -z "${AIX_DYNAMIC_AFS_FALSE}"=
; then
+  as_fn_error "conditional \"AIX_DYNAMIC_AFS\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${IRIX_TRUE}" && test -z "${IRIX_FALSE}"; then
+  as_fn_error "conditional \"IRIX\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${ENABLE_SHARED_TRUE}" && test -z "${ENABLE_SHARED_FALSE}"; th=
en
-  { { echo "$as_me:$LINENO: error: conditional \"ENABLE_SHARED\" was never=
 defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"ENABLE_SHARED\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"ENABLE_SHARED\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${versionscript_TRUE}" && test -z "${versionscript_FALSE}"; th=
en
-  { { echo "$as_me:$LINENO: error: conditional \"versionscript\" was never=
 defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"versionscript\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"versionscript\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${CROSS_COMPILE_TRUE}" && test -z "${CROSS_COMPILE_FALSE}"; th=
en
+  as_fn_error "conditional \"CROSS_COMPILE\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${OPENLDAP_MODULE_TRUE}" && test -z "${OPENLDAP_MODULE_FALSE}"=
; then
-  { { echo "$as_me:$LINENO: error: conditional \"OPENLDAP_MODULE\" was nev=
er defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"OPENLDAP_MODULE\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"OPENLDAP_MODULE\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${PKINIT_TRUE}" && test -z "${PKINIT_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"PKINIT\" was never define=
d.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"PKINIT\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"PKINIT\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${HAVE_CAPNG_TRUE}" && test -z "${HAVE_CAPNG_FALSE}"; then
+  as_fn_error "conditional \"HAVE_CAPNG\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${SQLITE3_TRUE}" && test -z "${SQLITE3_FALSE}"; then
+  as_fn_error "conditional \"SQLITE3\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${have_scc_TRUE}" && test -z "${have_scc_FALSE}"; then
+  as_fn_error "conditional \"have_scc\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${KRB4_TRUE}" && test -z "${KRB4_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"KRB4\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"KRB4\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"KRB4\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${KRB5_TRUE}" && test -z "${KRB5_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"KRB5\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"KRB5\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"KRB5\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${do_roken_rename_TRUE}" && test -z "${do_roken_rename_FALSE}"=
; then
-  { { echo "$as_me:$LINENO: error: conditional \"do_roken_rename\" was nev=
er defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"do_roken_rename\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"do_roken_rename\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${HAVE_OPENSSL_TRUE}" && test -z "${HAVE_OPENSSL_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"HAVE_OPENSSL\" was never =
defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"HAVE_OPENSSL\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"HAVE_OPENSSL\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${DCE_TRUE}" && test -z "${DCE_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"DCE\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"DCE\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"DCE\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${HAVE_DB1_TRUE}" && test -z "${HAVE_DB1_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"HAVE_DB1\" was never defi=
ned.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"HAVE_DB1\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"HAVE_DB1\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${HAVE_DB3_TRUE}" && test -z "${HAVE_DB3_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"HAVE_DB3\" was never defi=
ned.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"HAVE_DB3\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"HAVE_DB3\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${HAVE_NDBM_TRUE}" && test -z "${HAVE_NDBM_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"HAVE_NDBM\" was never def=
ined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"HAVE_NDBM\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"HAVE_NDBM\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${HAVE_DBHEADER_TRUE}" && test -z "${HAVE_DBHEADER_FALSE}"; th=
en
+  as_fn_error "conditional \"HAVE_DBHEADER\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${have_err_h_TRUE}" && test -z "${have_err_h_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"have_err_h\" was never de=
fined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"have_err_h\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"have_err_h\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${have_ifaddrs_h_TRUE}" && test -z "${have_ifaddrs_h_FALSE}"; =
then
-  { { echo "$as_me:$LINENO: error: conditional \"have_ifaddrs_h\" was neve=
r defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"have_ifaddrs_h\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"have_ifaddrs_h\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${have_search_h_TRUE}" && test -z "${have_search_h_FALSE}"; th=
en
+  as_fn_error "conditional \"have_search_h\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${have_vis_h_TRUE}" && test -z "${have_vis_h_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"have_vis_h\" was never de=
fined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"have_vis_h\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"have_vis_h\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${have_glob_h_TRUE}" && test -z "${have_glob_h_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"have_glob_h\" was never d=
efined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"have_glob_h\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"have_glob_h\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${have_cgetent_TRUE}" && test -z "${have_cgetent_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"have_cgetent\" was never =
defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"have_cgetent\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"have_cgetent\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${have_fnmatch_h_TRUE}" && test -z "${have_fnmatch_h_FALSE}"; =
then
-  { { echo "$as_me:$LINENO: error: conditional \"have_fnmatch_h\" was neve=
r defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"have_fnmatch_h\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"have_fnmatch_h\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${have_socket_wrapper_TRUE}" && test -z "${have_socket_wrapper=
_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"have_socket_wrapper\" was=
 never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"have_socket_wrapper\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"have_socket_wrapper\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${OTP_TRUE}" && test -z "${OTP_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"OTP\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"OTP\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"OTP\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${have_gcd_TRUE}" && test -z "${have_gcd_FALSE}"; then
+  as_fn_error "conditional \"have_gcd\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${CATMAN_TRUE}" && test -z "${CATMAN_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"CATMAN\" was never define=
d.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"CATMAN\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-if test -z "${AIX_TRUE}" && test -z "${AIX_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"AIX\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"AIX\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-if test -z "${AIX4_TRUE}" && test -z "${AIX4_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"AIX4\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"AIX4\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-if test -z "${HAVE_DLOPEN_TRUE}" && test -z "${HAVE_DLOPEN_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"HAVE_DLOPEN\" was never d=
efined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"HAVE_DLOPEN\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-if test -z "${AIX_DYNAMIC_AFS_TRUE}" && test -z "${AIX_DYNAMIC_AFS_FALSE}"=
; then
-  { { echo "$as_me:$LINENO: error: conditional \"AIX_DYNAMIC_AFS\" was nev=
er defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"AIX_DYNAMIC_AFS\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-if test -z "${IRIX_TRUE}" && test -z "${IRIX_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"IRIX\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"IRIX\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"CATMAN\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${HAVE_X_TRUE}" && test -z "${HAVE_X_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"HAVE_X\" was never define=
d.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"HAVE_X\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"HAVE_X\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${NEED_WRITEAUTH_TRUE}" && test -z "${NEED_WRITEAUTH_FALSE}"; =
then
-  { { echo "$as_me:$LINENO: error: conditional \"NEED_WRITEAUTH\" was neve=
r defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"NEED_WRITEAUTH\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"NEED_WRITEAUTH\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${KCM_TRUE}" && test -z "${KCM_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"KCM\" was never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"KCM\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"KCM\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${FRAMEWORK_SECURITY_TRUE}" && test -z "${FRAMEWORK_SECURITY_F=
ALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"FRAMEWORK_SECURITY\" was =
never defined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"FRAMEWORK_SECURITY\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
-fi
-if test -z "${el_compat_TRUE}" && test -z "${el_compat_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"el_compat\" was never def=
ined.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"el_compat\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"FRAMEWORK_SECURITY\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${LIBEDIT_TRUE}" && test -z "${LIBEDIT_FALSE}"; then
+  as_fn_error "conditional \"LIBEDIT\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
 if test -z "${COM_ERR_TRUE}" && test -z "${COM_ERR_FALSE}"; then
-  { { echo "$as_me:$LINENO: error: conditional \"COM_ERR\" was never defin=
ed.
-Usually this means the macro was only invoked conditionally." >&5
-echo "$as_me: error: conditional \"COM_ERR\" was never defined.
-Usually this means the macro was only invoked conditionally." >&2;}
-   { (exit 1); exit 1; }; }
+  as_fn_error "conditional \"COM_ERR\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
+fi
+if test -z "${HEIMDAL_DOCUMENTATION_TRUE}" && test -z "${HEIMDAL_DOCUMENTA=
TION_FALSE}"; then
+  as_fn_error "conditional \"HEIMDAL_DOCUMENTATION\" was never defined.
+Usually this means the macro was only invoked conditionally." "$LINENO" 5
 fi
=20
 : ${CONFIG_STATUS=3D./config.status}
+ac_write_fail=3D0
 ac_clean_files_save=3D$ac_clean_files
 ac_clean_files=3D"$ac_clean_files $CONFIG_STATUS"
-{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
-echo "$as_me: creating $CONFIG_STATUS" >&6;}
-cat >$CONFIG_STATUS <<_ACEOF
+{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+as_write_fail=3D0
+cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=3D1
 #! $SHELL
 # Generated by $as_me.
 # Run this file to recreate the current configuration.
@@ -52932,34 +28856,252 @@
 debug=3Dfalse
 ac_cs_recheck=3Dfalse
 ac_cs_silent=3Dfalse
+
 SHELL=3D\${CONFIG_SHELL-$SHELL}
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
+export SHELL
+_ASEOF
+cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=3D1
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
=20
 # Be more Bourne compatible
 DUALCASE=3D1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
   emulate sh
   NULLCMD=3D:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'=3D'"$@"'
   setopt NO_GLOB_SUBST
 else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-
-
-# PATH needs CR
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl=3D'
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo=3D'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\=
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=3D$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=3D$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" =3D "X$as_echo") 2>/dev/null; then
+  as_echo=3D'print -r --'
+  as_echo_n=3D'print -rn --'
+elif (test "X`printf %s $as_echo`" =3D "X$as_echo") 2>/dev/null; then
+  as_echo=3D'printf %s\n'
+  as_echo_n=3D'printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" =3D "X-n $as_ech=
o"; then
+    as_echo_body=3D'eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n=3D'/usr/ucb/echo -n'
+  else
+    as_echo_body=3D'eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body=3D'eval
+      arg=3D$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=3D`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n=3D'sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo=3D'sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" !=3D set; then
+  PATH_SEPARATOR=3D:
+  (PATH=3D'/bin;/bin'; FPATH=3D$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH=3D'/bin:/bin'; FPATH=3D$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=3D';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=3D" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in #((
+  *[\\/]* ) as_myself=3D$0 ;;
+  *) as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=3D$as_save_IFS
+  test -z "$as_dir" && as_dir=3D.
+    test -r "$as_dir/$0" && as_myself=3D$as_dir/$0 && break
+  done
+IFS=3D$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" =3D x; then
+  as_myself=3D$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute =
file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} =3D xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1=3D'$ '
+PS2=3D'> '
+PS4=3D'+ '
+
+# NLS nuisances.
+LC_ALL=3DC
+export LC_ALL
+LANGUAGE=3DC
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+
+# as_fn_error ERROR [LINENO LOG_FD]
+# ---------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit=
 the
+# script with status $?, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=3D$?; test $as_status -eq 0 && as_status=3D1
+  if test "$3"; then
+    as_lineno=3D${as_lineno-"$2"} as_lineno_stack=3Das_lineno_stack=3D$as_=
lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3
+  fi
+  $as_echo "$as_me: error: $1" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=3D; unset $1;}
+}
+as_unset=3Das_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. =
Take
+# advantage of any shell optimizations that allow amortized linear growth =
over
+# repeated appends, instead of the typical quadratic growth present in nai=
ve
+# implementations.
+if (eval "as_var=3D1; as_var+=3D2; test x\$as_var =3D x12") 2>/dev/null; t=
hen :
+  eval 'as_fn_append ()
+  {
+    eval $1+=3D\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=3D\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The argum=
ents
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) =3D 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=3D$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=3D`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" =3D X001; then
+  as_expr=3Dexpr
+else
+  as_expr=3Dfalse
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" =3D "X/=
"; then
+  as_basename=3Dbasename
+else
+  as_basename=3Dfalse
+fi
+
+if (as_dir=3D`dirname -- /` && test "X$as_dir" =3D X/) >/dev/null 2>&1; th=
en
+  as_dirname=3Ddirname
+else
+  as_dirname=3Dfalse
+fi
+
+as_me=3D`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
 # Avoid depending upon Character Ranges.
 as_cr_letters=3D'abcdefghijklmnopqrstuvwxyz'
 as_cr_LETTERS=3D'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
@@ -52967,214 +29109,96 @@
 as_cr_digits=3D'0123456789'
 as_cr_alnum=3D$as_cr_Letters$as_cr_digits
=20
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" !=3D set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH=3D"/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=3D';'
-  else
-    PATH_SEPARATOR=3D:
-  fi
-  rm -f conf$$.sh
-fi
-
-# Support unset when possible.
-if ( (MAIL=3D60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=3Dunset
-else
-  as_unset=3Dfalse
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-as_nl=3D'
-'
-IFS=3D" ""	$as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-case $0 in
-  *[\\/]* ) as_myself=3D$0 ;;
-  *) as_save_IFS=3D$IFS; IFS=3D$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=3D$as_save_IFS
-  test -z "$as_dir" && as_dir=3D.
-  test -r "$as_dir/$0" && as_myself=3D$as_dir/$0 && break
-done
-IFS=3D$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" =3D x; then
-  as_myself=3D$0
-fi
-if test ! -f "$as_myself"; then
-  echo "$as_myself: error: cannot find myself; rerun with an absolute file=
 name" >&2
-  { (exit 1); exit 1; }
-fi
-
-# Work around bugs in pre-3.0 UWIN ksh.
-for as_var in ENV MAIL MAILPATH
-do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-done
-PS1=3D'$ '
-PS2=3D'> '
-PS4=3D'+ '
-
-# NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
-do
-  if (set +x; test -z "`(eval $as_var=3DC; export $as_var) 2>&1`"); then
-    eval $as_var=3DC; export $as_var
-  else
-    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-  fi
-done
-
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" =3D X001; then
-  as_expr=3Dexpr
-else
-  as_expr=3Dfalse
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" =3D "X/=
"; then
-  as_basename=3Dbasename
-else
-  as_basename=3Dfalse
-fi
-
-
-# Name of the executable.
-as_me=3D`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-
-# CDPATH.
-$as_unset CDPATH
-
-
-
-  as_lineno_1=3D$LINENO
-  as_lineno_2=3D$LINENO
-  test "x$as_lineno_1" !=3D "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" =3D "x$as_lineno_2" || {
-
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line after each line using $LINENO; the second 'sed'
-  # does the real work.  The second script uses 'N' to pair each
-  # line-number line with the line containing $LINENO, and appends
-  # trailing '-' during substitution so that $LINENO is not a special
-  # case at line end.
-  # (Raja R Harinath suggested sed '=3D', and Paul Eggert wrote the
-  # scripts with optimization help from Paolo Bonzini.  Blame Lee
-  # E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=3D
-  ' <$as_myself |
-    sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
-      N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
-      t loop
-      s/-\n.*//
-    ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
-    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX=
 shell" >&2
-   { (exit 1); exit 1; }; }
-
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensitive to this).
-  . "./$as_me.lineno"
-  # Exit status is that of the last command.
-  exit
-}
-
-
-if (as_dir=3D`dirname -- /` && test "X$as_dir" =3D X/) >/dev/null 2>&1; th=
en
-  as_dirname=3Ddirname
-else
-  as_dirname=3Dfalse
-fi
-
 ECHO_C=3D ECHO_N=3D ECHO_T=3D
-case `echo -n x` in
+case `echo -n x` in #(((((
 -n*)
-  case `echo 'x\c'` in
+  case `echo 'xy\c'` in
   *c*) ECHO_T=3D'	';;	# ECHO_T is single tab character.
-  *)   ECHO_C=3D'\c';;
+  xy)  ECHO_C=3D'\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T=3D'	';;
   esac;;
 *)
   ECHO_N=3D'-n';;
 esac
=20
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" =3D X001; then
-  as_expr=3Dexpr
-else
-  as_expr=3Dfalse
-fi
-
 rm -f conf$$ conf$$.exe conf$$.file
 if test -d conf$$.dir; then
   rm -f conf$$.dir/conf$$.file
 else
   rm -f conf$$.dir
-  mkdir conf$$.dir
-fi
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=3D'ln -s'
-  # ... but there are two gotchas:
-  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-  # In both cases, we have to default to `cp -p'.
-  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=3D'ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executabl=
e.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s=3D'cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=3Dln
+  else
     as_ln_s=3D'cp -p'
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=3Dln
+  fi
 else
   as_ln_s=3D'cp -p'
 fi
 rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
 rmdir conf$$.dir 2>/dev/null
=20
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=3D./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=3D
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=3D`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=3D$as_dir;;
+      esac
+      as_dirs=3D"'$as_qdir' $as_dirs"
+      as_dir=3D`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
 if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=3D:
+  as_mkdir_p=3D'mkdir -p "$as_dir"'
 else
   test -d ./-p && rmdir ./-p
   as_mkdir_p=3Dfalse
@@ -53191,12 +29215,12 @@
   as_test_x=3D'
     eval sh -c '\''
       if test -d "$1"; then
-        test -d "$1/.";
-      else
-	case $1 in
-        -*)set "./$1";;
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
 	esac;
-	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
 	???[sx]*):;;*)false;;esac;fi
     '\'' sh
   '
@@ -53211,13 +29235,19 @@
=20
=20
 exec 6>&1
-
-# Save the log message, to keep $[0] and so on meaningful, and to
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+_ASEOF
+test $as_write_fail =3D 0 && chmod +x $CONFIG_STATUS || ac_write_fail=3D1
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
+# Save the log message, to keep $0 and so on meaningful, and to
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log=3D"
-This file was extended by Heimdal $as_me 1.1, which was
-generated by GNU Autoconf 2.61.  Invocation command line was
+This file was extended by Heimdal $as_me 1.5.2, which was
+generated by GNU Autoconf 2.65.  Invocation command line was
=20
   CONFIG_FILES    =3D $CONFIG_FILES
   CONFIG_HEADERS  =3D $CONFIG_HEADERS
@@ -53230,29 +29260,42 @@
=20
 _ACEOF
=20
-cat >>$CONFIG_STATUS <<_ACEOF
+case $ac_config_files in *"
+"*) set x $ac_config_files; shift; ac_config_files=3D$*;;
+esac
+
+case $ac_config_headers in *"
+"*) set x $ac_config_headers; shift; ac_config_headers=3D$*;;
+esac
+
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
 # Files that config.status was made for.
 config_files=3D"$ac_config_files"
 config_headers=3D"$ac_config_headers"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
+config_commands=3D"$ac_config_commands"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
 ac_cs_usage=3D"\
-\`$as_me' instantiates files from templates according to the
-current configuration.
-
-Usage: $0 [OPTIONS] [FILE]...
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
+
+Usage: $0 [OPTION]... [TAG]...
=20
   -h, --help       print this help, then exit
   -V, --version    print version number and configuration settings, then e=
xit
-  -q, --quiet      do not print progress messages
+      --config     print configuration, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
   -d, --debug      don't remove temporary files
       --recheck    update $as_me by reconfiguring in the same conditions
-  --file=3DFILE[:TEMPLATE]
-		   instantiate the configuration file FILE
-  --header=3DFILE[:TEMPLATE]
-		   instantiate the configuration header FILE
+      --file=3DFILE[:TEMPLATE]
+                   instantiate the configuration file FILE
+      --header=3DFILE[:TEMPLATE]
+                   instantiate the configuration header FILE
=20
 Configuration files:
 $config_files
@@ -53260,16 +29303,20 @@
 Configuration headers:
 $config_headers
=20
-Report bugs to <bug-autoconf at gnu.org>."
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
+Configuration commands:
+$config_commands
+
+Report bugs to <heimdal-bugs at h5l.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
+ac_cs_config=3D"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]=
/\\\\&/g'`"
 ac_cs_version=3D"\\
-Heimdal config.status 1.1
-configured by $0, generated by GNU Autoconf 2.61,
-  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\=
\\\&/g'`\\"
-
-Copyright (C) 2006 Free Software Foundation, Inc.
+Heimdal config.status 1.5.2
+configured by $0, generated by GNU Autoconf 2.65,
+  with options \\"\$ac_cs_config\\"
+
+Copyright (C) 2009 Free Software Foundation, Inc.
 This config.status script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it."
=20
@@ -53277,11 +29324,12 @@
 srcdir=3D'$srcdir'
 INSTALL=3D'$INSTALL'
 MKDIR_P=3D'$MKDIR_P'
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-# If no file are specified by the user, then we need to provide default
-# value.  By we need to know if files were specified by the user.
+AWK=3D'$AWK'
+test -n "\$AWK" || AWK=3Dawk
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
+# The default lists apply if the user does not specify any file.
 ac_need_defaults=3D:
 while test $# !=3D 0
 do
@@ -53303,34 +29351,40 @@
   -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
     ac_cs_recheck=3D: ;;
   --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    echo "$ac_cs_version"; exit ;;
+    $as_echo "$ac_cs_version"; exit ;;
+  --config | --confi | --conf | --con | --co | --c )
+    $as_echo "$ac_cs_config"; exit ;;
   --debug | --debu | --deb | --de | --d | -d )
     debug=3D: ;;
   --file | --fil | --fi | --f )
     $ac_shift
-    CONFIG_FILES=3D"$CONFIG_FILES $ac_optarg"
+    case $ac_optarg in
+    *\'*) ac_optarg=3D`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
     ac_need_defaults=3Dfalse;;
   --header | --heade | --head | --hea )
     $ac_shift
-    CONFIG_HEADERS=3D"$CONFIG_HEADERS $ac_optarg"
+    case $ac_optarg in
+    *\'*) ac_optarg=3D`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
     ac_need_defaults=3Dfalse;;
   --he | --h)
     # Conflict between --help and --header
-    { echo "$as_me: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&2
-   { (exit 1); exit 1; }; };;
+    as_fn_error "ambiguous option: \`$1'
+Try \`$0 --help' for more information.";;
   --help | --hel | -h )
-    echo "$ac_cs_usage"; exit ;;
+    $as_echo "$ac_cs_usage"; exit ;;
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil | --si | --s)
     ac_cs_silent=3D: ;;
=20
   # This is an error.
-  -*) { echo "$as_me: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&2
-   { (exit 1); exit 1; }; } ;;
-
-  *) ac_config_targets=3D"$ac_config_targets $1"
+  -*) as_fn_error "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
+
+  *) as_fn_append ac_config_targets " $1"
      ac_need_defaults=3Dfalse ;;
=20
   esac
@@ -53345,36 +29399,322 @@
 fi
=20
 _ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
 if \$ac_cs_recheck; then
-  echo "running CONFIG_SHELL=3D$SHELL $SHELL $0 "$ac_configure_args \$ac_c=
onfigure_extra_args " --no-create --no-recursion" >&6
-  CONFIG_SHELL=3D$SHELL
+  set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-cr=
eate --no-recursion
+  shift
+  \$as_echo "running CONFIG_SHELL=3D$SHELL \$*" >&6
+  CONFIG_SHELL=3D'$SHELL'
   export CONFIG_SHELL
-  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create=
 --no-recursion
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
+  exec "\$@"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
 exec 5>>config.log
 {
   echo
   sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
 ## Running $as_me. ##
 _ASBOX
-  echo "$ac_log"
+  $as_echo "$ac_log"
 } >&5
=20
 _ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
+#
+# INIT-COMMANDS
+#
+AMDEP_TRUE=3D"$AMDEP_TRUE" ac_aux_dir=3D"$ac_aux_dir"
+
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+sed_quote_subst=3D'$sed_quote_subst'
+double_quote_subst=3D'$double_quote_subst'
+delay_variable_subst=3D'$delay_variable_subst'
+macro_version=3D'`$ECHO "$macro_version" | $SED "$delay_single_quote_subst=
"`'
+macro_revision=3D'`$ECHO "$macro_revision" | $SED "$delay_single_quote_sub=
st"`'
+enable_shared=3D'`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst=
"`'
+enable_static=3D'`$ECHO "$enable_static" | $SED "$delay_single_quote_subst=
"`'
+pic_mode=3D'`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`'
+enable_fast_install=3D'`$ECHO "$enable_fast_install" | $SED "$delay_single=
_quote_subst"`'
+SHELL=3D'`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`'
+ECHO=3D'`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`'
+host_alias=3D'`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`'
+host=3D'`$ECHO "$host" | $SED "$delay_single_quote_subst"`'
+host_os=3D'`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`'
+build_alias=3D'`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`'
+build=3D'`$ECHO "$build" | $SED "$delay_single_quote_subst"`'
+build_os=3D'`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`'
+SED=3D'`$ECHO "$SED" | $SED "$delay_single_quote_subst"`'
+Xsed=3D'`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`'
+GREP=3D'`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`'
+EGREP=3D'`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`'
+FGREP=3D'`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`'
+LD=3D'`$ECHO "$LD" | $SED "$delay_single_quote_subst"`'
+NM=3D'`$ECHO "$NM" | $SED "$delay_single_quote_subst"`'
+LN_S=3D'`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`'
+max_cmd_len=3D'`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`'
+ac_objext=3D'`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`'
+exeext=3D'`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`'
+lt_unset=3D'`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`'
+lt_SP2NL=3D'`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`'
+lt_NL2SP=3D'`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`'
+lt_cv_to_host_file_cmd=3D'`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_=
single_quote_subst"`'
+lt_cv_to_tool_file_cmd=3D'`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_=
single_quote_subst"`'
+reload_flag=3D'`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`'
+reload_cmds=3D'`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`'
+OBJDUMP=3D'`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`'
+deplibs_check_method=3D'`$ECHO "$deplibs_check_method" | $SED "$delay_sing=
le_quote_subst"`'
+file_magic_cmd=3D'`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_sub=
st"`'
+file_magic_glob=3D'`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_s=
ubst"`'
+want_nocaseglob=3D'`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_s=
ubst"`'
+DLLTOOL=3D'`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`'
+sharedlib_from_linklib_cmd=3D'`$ECHO "$sharedlib_from_linklib_cmd" | $SED =
"$delay_single_quote_subst"`'
+AR=3D'`$ECHO "$AR" | $SED "$delay_single_quote_subst"`'
+AR_FLAGS=3D'`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`'
+archiver_list_spec=3D'`$ECHO "$archiver_list_spec" | $SED "$delay_single_q=
uote_subst"`'
+STRIP=3D'`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`'
+RANLIB=3D'`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`'
+old_postinstall_cmds=3D'`$ECHO "$old_postinstall_cmds" | $SED "$delay_sing=
le_quote_subst"`'
+old_postuninstall_cmds=3D'`$ECHO "$old_postuninstall_cmds" | $SED "$delay_=
single_quote_subst"`'
+old_archive_cmds=3D'`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote=
_subst"`'
+lock_old_archive_extraction=3D'`$ECHO "$lock_old_archive_extraction" | $SE=
D "$delay_single_quote_subst"`'
+CC=3D'`$ECHO "$CC" | $SED "$delay_single_quote_subst"`'
+CFLAGS=3D'`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`'
+compiler=3D'`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`'
+GCC=3D'`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_pipe=3D'`$ECHO "$lt_cv_sys_global_symbol_pipe" | $=
SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_to_cdecl=3D'`$ECHO "$lt_cv_sys_global_symbol_to_cd=
ecl" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_to_c_name_address=3D'`$ECHO "$lt_cv_sys_global_sym=
bol_to_c_name_address" | $SED "$delay_single_quote_subst"`'
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix=3D'`$ECHO "$lt_cv_sys=
_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_su=
bst"`'
+nm_file_list_spec=3D'`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quo=
te_subst"`'
+lt_sysroot=3D'`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`'
+objdir=3D'`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`'
+MAGIC_CMD=3D'`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_no_builtin_flag=3D'`$ECHO "$lt_prog_compiler_no_builtin_f=
lag" | $SED "$delay_single_quote_subst"`'
+lt_prog_compiler_pic=3D'`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_sing=
le_quote_subst"`'
+lt_prog_compiler_wl=3D'`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single=
_quote_subst"`'
+lt_prog_compiler_static=3D'`$ECHO "$lt_prog_compiler_static" | $SED "$dela=
y_single_quote_subst"`'
+lt_cv_prog_compiler_c_o=3D'`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$dela=
y_single_quote_subst"`'
+need_locks=3D'`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`'
+MANIFEST_TOOL=3D'`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst=
"`'
+DSYMUTIL=3D'`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`'
+NMEDIT=3D'`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`'
+LIPO=3D'`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`'
+OTOOL=3D'`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`'
+OTOOL64=3D'`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`'
+libext=3D'`$ECHO "$libext" | $SED "$delay_single_quote_subst"`'
+shrext_cmds=3D'`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`'
+extract_expsyms_cmds=3D'`$ECHO "$extract_expsyms_cmds" | $SED "$delay_sing=
le_quote_subst"`'
+archive_cmds_need_lc=3D'`$ECHO "$archive_cmds_need_lc" | $SED "$delay_sing=
le_quote_subst"`'
+enable_shared_with_static_runtimes=3D'`$ECHO "$enable_shared_with_static_r=
untimes" | $SED "$delay_single_quote_subst"`'
+export_dynamic_flag_spec=3D'`$ECHO "$export_dynamic_flag_spec" | $SED "$de=
lay_single_quote_subst"`'
+whole_archive_flag_spec=3D'`$ECHO "$whole_archive_flag_spec" | $SED "$dela=
y_single_quote_subst"`'
+compiler_needs_object=3D'`$ECHO "$compiler_needs_object" | $SED "$delay_si=
ngle_quote_subst"`'
+old_archive_from_new_cmds=3D'`$ECHO "$old_archive_from_new_cmds" | $SED "$=
delay_single_quote_subst"`'
+old_archive_from_expsyms_cmds=3D'`$ECHO "$old_archive_from_expsyms_cmds" |=
 $SED "$delay_single_quote_subst"`'
+archive_cmds=3D'`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`'
+archive_expsym_cmds=3D'`$ECHO "$archive_expsym_cmds" | $SED "$delay_single=
_quote_subst"`'
+module_cmds=3D'`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`'
+module_expsym_cmds=3D'`$ECHO "$module_expsym_cmds" | $SED "$delay_single_q=
uote_subst"`'
+with_gnu_ld=3D'`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`'
+allow_undefined_flag=3D'`$ECHO "$allow_undefined_flag" | $SED "$delay_sing=
le_quote_subst"`'
+no_undefined_flag=3D'`$ECHO "$no_undefined_flag" | $SED "$delay_single_quo=
te_subst"`'
+hardcode_libdir_flag_spec=3D'`$ECHO "$hardcode_libdir_flag_spec" | $SED "$=
delay_single_quote_subst"`'
+hardcode_libdir_flag_spec_ld=3D'`$ECHO "$hardcode_libdir_flag_spec_ld" | $=
SED "$delay_single_quote_subst"`'
+hardcode_libdir_separator=3D'`$ECHO "$hardcode_libdir_separator" | $SED "$=
delay_single_quote_subst"`'
+hardcode_direct=3D'`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_s=
ubst"`'
+hardcode_direct_absolute=3D'`$ECHO "$hardcode_direct_absolute" | $SED "$de=
lay_single_quote_subst"`'
+hardcode_minus_L=3D'`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote=
_subst"`'
+hardcode_shlibpath_var=3D'`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_=
single_quote_subst"`'
+hardcode_automatic=3D'`$ECHO "$hardcode_automatic" | $SED "$delay_single_q=
uote_subst"`'
+inherit_rpath=3D'`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst=
"`'
+link_all_deplibs=3D'`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote=
_subst"`'
+always_export_symbols=3D'`$ECHO "$always_export_symbols" | $SED "$delay_si=
ngle_quote_subst"`'
+export_symbols_cmds=3D'`$ECHO "$export_symbols_cmds" | $SED "$delay_single=
_quote_subst"`'
+exclude_expsyms=3D'`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_s=
ubst"`'
+include_expsyms=3D'`$ECHO "$include_expsyms" | $SED "$delay_single_quote_s=
ubst"`'
+prelink_cmds=3D'`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`'
+postlink_cmds=3D'`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst=
"`'
+file_list_spec=3D'`$ECHO "$file_list_spec" | $SED "$delay_single_quote_sub=
st"`'
+variables_saved_for_relink=3D'`$ECHO "$variables_saved_for_relink" | $SED =
"$delay_single_quote_subst"`'
+need_lib_prefix=3D'`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_s=
ubst"`'
+need_version=3D'`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`'
+version_type=3D'`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`'
+runpath_var=3D'`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`'
+shlibpath_var=3D'`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst=
"`'
+shlibpath_overrides_runpath=3D'`$ECHO "$shlibpath_overrides_runpath" | $SE=
D "$delay_single_quote_subst"`'
+libname_spec=3D'`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`'
+library_names_spec=3D'`$ECHO "$library_names_spec" | $SED "$delay_single_q=
uote_subst"`'
+soname_spec=3D'`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`'
+install_override_mode=3D'`$ECHO "$install_override_mode" | $SED "$delay_si=
ngle_quote_subst"`'
+postinstall_cmds=3D'`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote=
_subst"`'
+postuninstall_cmds=3D'`$ECHO "$postuninstall_cmds" | $SED "$delay_single_q=
uote_subst"`'
+finish_cmds=3D'`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`'
+finish_eval=3D'`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`'
+hardcode_into_libs=3D'`$ECHO "$hardcode_into_libs" | $SED "$delay_single_q=
uote_subst"`'
+sys_lib_search_path_spec=3D'`$ECHO "$sys_lib_search_path_spec" | $SED "$de=
lay_single_quote_subst"`'
+sys_lib_dlsearch_path_spec=3D'`$ECHO "$sys_lib_dlsearch_path_spec" | $SED =
"$delay_single_quote_subst"`'
+hardcode_action=3D'`$ECHO "$hardcode_action" | $SED "$delay_single_quote_s=
ubst"`'
+enable_dlopen=3D'`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst=
"`'
+enable_dlopen_self=3D'`$ECHO "$enable_dlopen_self" | $SED "$delay_single_q=
uote_subst"`'
+enable_dlopen_self_static=3D'`$ECHO "$enable_dlopen_self_static" | $SED "$=
delay_single_quote_subst"`'
+old_striplib=3D'`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`'
+striplib=3D'`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`'
+
+LTCC=3D'$LTCC'
+LTCFLAGS=3D'$LTCFLAGS'
+compiler=3D'$compiler_DEFAULT'
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
+
+# Quote evaled strings.
+for var in SHELL \
+ECHO \
+SED \
+GREP \
+EGREP \
+FGREP \
+LD \
+NM \
+LN_S \
+lt_SP2NL \
+lt_NL2SP \
+reload_flag \
+OBJDUMP \
+deplibs_check_method \
+file_magic_cmd \
+file_magic_glob \
+want_nocaseglob \
+DLLTOOL \
+sharedlib_from_linklib_cmd \
+AR \
+AR_FLAGS \
+archiver_list_spec \
+STRIP \
+RANLIB \
+CC \
+CFLAGS \
+compiler \
+lt_cv_sys_global_symbol_pipe \
+lt_cv_sys_global_symbol_to_cdecl \
+lt_cv_sys_global_symbol_to_c_name_address \
+lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \
+nm_file_list_spec \
+lt_prog_compiler_no_builtin_flag \
+lt_prog_compiler_pic \
+lt_prog_compiler_wl \
+lt_prog_compiler_static \
+lt_cv_prog_compiler_c_o \
+need_locks \
+MANIFEST_TOOL \
+DSYMUTIL \
+NMEDIT \
+LIPO \
+OTOOL \
+OTOOL64 \
+shrext_cmds \
+export_dynamic_flag_spec \
+whole_archive_flag_spec \
+compiler_needs_object \
+with_gnu_ld \
+allow_undefined_flag \
+no_undefined_flag \
+hardcode_libdir_flag_spec \
+hardcode_libdir_flag_spec_ld \
+hardcode_libdir_separator \
+exclude_expsyms \
+include_expsyms \
+file_list_spec \
+variables_saved_for_relink \
+libname_spec \
+library_names_spec \
+soname_spec \
+install_override_mode \
+finish_eval \
+old_striplib \
+striplib; do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[\\\\\\\`\\"\\\$]*)
+      eval "lt_\$var=3D\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\=
\$sed_quote_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=3D\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+# Double-quote double-evaled strings.
+for var in reload_cmds \
+old_postinstall_cmds \
+old_postuninstall_cmds \
+old_archive_cmds \
+extract_expsyms_cmds \
+old_archive_from_new_cmds \
+old_archive_from_expsyms_cmds \
+archive_cmds \
+archive_expsym_cmds \
+module_cmds \
+module_expsym_cmds \
+export_symbols_cmds \
+prelink_cmds \
+postlink_cmds \
+postinstall_cmds \
+postuninstall_cmds \
+finish_cmds \
+sys_lib_search_path_spec \
+sys_lib_dlsearch_path_spec; do
+    case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in
+    *[\\\\\\\`\\"\\\$]*)
+      eval "lt_\$var=3D\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\=
"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_var=
iable_subst\\"\\\`\\\\\\""
+      ;;
+    *)
+      eval "lt_\$var=3D\\\\\\"\\\$\$var\\\\\\""
+      ;;
+    esac
+done
+
+ac_aux_dir=3D'$ac_aux_dir'
+xsi_shell=3D'$xsi_shell'
+lt_shell_append=3D'$lt_shell_append'
+
+# See if we are running on zsh, and set the options which allow our
+# commands through without removal of \ escapes INIT.
+if test -n "\${ZSH_VERSION+set}" ; then
+   setopt NO_GLOB_SUBST
+fi
+
+
+    PACKAGE=3D'$PACKAGE'
+    VERSION=3D'$VERSION'
+    TIMESTAMP=3D'$TIMESTAMP'
+    RM=3D'$RM'
+    ofile=3D'$ofile'
+
+
+
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
=20
 # Handling of arguments.
 for ac_config_target in $ac_config_targets
 do
   case $ac_config_target in
     "include/config.h") CONFIG_HEADERS=3D"$CONFIG_HEADERS include/config.h=
" ;;
+    "depfiles") CONFIG_COMMANDS=3D"$CONFIG_COMMANDS depfiles" ;;
+    "libtool") CONFIG_COMMANDS=3D"$CONFIG_COMMANDS libtool" ;;
     "Makefile") CONFIG_FILES=3D"$CONFIG_FILES Makefile" ;;
     "etc/Makefile") CONFIG_FILES=3D"$CONFIG_FILES etc/Makefile" ;;
     "include/Makefile") CONFIG_FILES=3D"$CONFIG_FILES include/Makefile" ;;
@@ -53382,19 +29722,15 @@
     "include/hcrypto/Makefile") CONFIG_FILES=3D"$CONFIG_FILES include/hcry=
pto/Makefile" ;;
     "include/kadm5/Makefile") CONFIG_FILES=3D"$CONFIG_FILES include/kadm5/=
Makefile" ;;
     "lib/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/Makefile" ;;
-    "lib/45/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/45/Makefile" ;;
-    "lib/auth/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/auth/Makefile" =
;;
-    "lib/auth/afskauthlib/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/aut=
h/afskauthlib/Makefile" ;;
-    "lib/auth/pam/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/auth/pam/Ma=
kefile" ;;
-    "lib/auth/sia/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/auth/sia/Ma=
kefile" ;;
+    "base/Makefile") CONFIG_FILES=3D"$CONFIG_FILES base/Makefile" ;;
     "lib/asn1/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/asn1/Makefile" =
;;
     "lib/com_err/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/com_err/Make=
file" ;;
     "lib/hcrypto/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/hcrypto/Make=
file" ;;
-    "lib/editline/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/editline/Ma=
kefile" ;;
     "lib/hx509/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/hx509/Makefile=
" ;;
     "lib/gssapi/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/gssapi/Makefi=
le" ;;
     "lib/ntlm/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/ntlm/Makefile" =
;;
     "lib/hdb/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/hdb/Makefile" ;;
+    "lib/ipc/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/ipc/Makefile" ;;
     "lib/kadm5/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/kadm5/Makefile=
" ;;
     "lib/kafs/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/kafs/Makefile" =
;;
     "lib/kdfs/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/kdfs/Makefile" =
;;
@@ -53402,7 +29738,10 @@
     "lib/otp/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/otp/Makefile" ;;
     "lib/roken/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/roken/Makefile=
" ;;
     "lib/sl/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/sl/Makefile" ;;
+    "lib/sqlite/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/sqlite/Makefi=
le" ;;
     "lib/vers/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/vers/Makefile" =
;;
+    "lib/wind/Makefile") CONFIG_FILES=3D"$CONFIG_FILES lib/wind/Makefile" =
;;
+    "po/Makefile") CONFIG_FILES=3D"$CONFIG_FILES po/Makefile" ;;
     "kuser/Makefile") CONFIG_FILES=3D"$CONFIG_FILES kuser/Makefile" ;;
     "kpasswd/Makefile") CONFIG_FILES=3D"$CONFIG_FILES kpasswd/Makefile" ;;
     "kadmin/Makefile") CONFIG_FILES=3D"$CONFIG_FILES kadmin/Makefile" ;;
@@ -53433,6 +29772,7 @@
     "appl/kf/Makefile") CONFIG_FILES=3D"$CONFIG_FILES appl/kf/Makefile" ;;
     "appl/dceutils/Makefile") CONFIG_FILES=3D"$CONFIG_FILES appl/dceutils/=
Makefile" ;;
     "tests/Makefile") CONFIG_FILES=3D"$CONFIG_FILES tests/Makefile" ;;
+    "tests/bin/Makefile") CONFIG_FILES=3D"$CONFIG_FILES tests/bin/Makefile=
" ;;
     "tests/can/Makefile") CONFIG_FILES=3D"$CONFIG_FILES tests/can/Makefile=
" ;;
     "tests/db/Makefile") CONFIG_FILES=3D"$CONFIG_FILES tests/db/Makefile" =
;;
     "tests/kdc/Makefile") CONFIG_FILES=3D"$CONFIG_FILES tests/kdc/Makefile=
" ;;
@@ -53442,13 +29782,10 @@
     "tests/plugin/Makefile") CONFIG_FILES=3D"$CONFIG_FILES tests/plugin/Ma=
kefile" ;;
     "packages/Makefile") CONFIG_FILES=3D"$CONFIG_FILES packages/Makefile" =
;;
     "packages/mac/Makefile") CONFIG_FILES=3D"$CONFIG_FILES packages/mac/Ma=
kefile" ;;
-    "packages/debian/Makefile") CONFIG_FILES=3D"$CONFIG_FILES packages/deb=
ian/Makefile" ;;
     "doc/Makefile") CONFIG_FILES=3D"$CONFIG_FILES doc/Makefile" ;;
     "tools/Makefile") CONFIG_FILES=3D"$CONFIG_FILES tools/Makefile" ;;
=20
-  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target"=
 >&5
-echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
-   { (exit 1); exit 1; }; };;
+  *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
   esac
 done
=20
@@ -53460,6 +29797,7 @@
 if $ac_need_defaults; then
   test "${CONFIG_FILES+set}" =3D set || CONFIG_FILES=3D$config_files
   test "${CONFIG_HEADERS+set}" =3D set || CONFIG_HEADERS=3D$config_headers
+  test "${CONFIG_COMMANDS+set}" =3D set || CONFIG_COMMANDS=3D$config_comma=
nds
 fi
=20
 # Have a temporary directory for convenience.  Make it in the build tree
@@ -53474,7 +29812,7 @@
   trap 'exit_status=3D$?
   { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_s=
tatus
 ' 0
-  trap '{ (exit 1); exit 1; }' 1 2 13 15
+  trap 'as_fn_exit 1' 1 2 13 15
 }
 # Create a (secure) tmp directory for tmp files.
=20
@@ -53485,397 +29823,139 @@
 {
   tmp=3D./conf$$-$RANDOM
   (umask 077 && mkdir "$tmp")
-} ||
-{
-   echo "$me: cannot create a temporary directory in ." >&2
-   { (exit 1); exit 1; }
-}
-
-#
-# Set up the sed scripts for CONFIG_FILES section.
-#
-
-# No need to generate the scripts if there are no CONFIG_FILES.
-# This happens for instance when ./config.status config.h
+} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5
+
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
 if test -n "$CONFIG_FILES"; then
=20
-_ACEOF
-
-
-
+
+ac_cr=3D`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" =3D x; then
+  eval ac_cr=3D\$\'\\r\'
+fi
+ac_cs_awk_cr=3D`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" =3D "a${ac_cr}b"; then
+  ac_cs_awk_cr=3D'\r'
+else
+  ac_cs_awk_cr=3D$ac_cr
+fi
+
+echo 'BEGIN {' >"$tmp/subs1.awk" &&
+_ACEOF
+
+
+{
+  echo "cat >conf$$subs.awk <<_ACEOF" &&
+  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
+  echo "_ACEOF"
+} >conf$$subs.sh ||
+  as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5
+ac_delim_num=3D`echo "$ac_subst_vars" | grep -c '$'`
 ac_delim=3D'%!_!# '
 for ac_last_try in false false false false false :; do
-  cat >conf$$subs.sed <<_ACEOF
-SHELL!$SHELL$ac_delim
-PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
-PACKAGE_NAME!$PACKAGE_NAME$ac_delim
-PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
-PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
-PACKAGE_STRING!$PACKAGE_STRING$ac_delim
-PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
-exec_prefix!$exec_prefix$ac_delim
-prefix!$prefix$ac_delim
-program_transform_name!$program_transform_name$ac_delim
-bindir!$bindir$ac_delim
-sbindir!$sbindir$ac_delim
-libexecdir!$libexecdir$ac_delim
-datarootdir!$datarootdir$ac_delim
-datadir!$datadir$ac_delim
-sysconfdir!$sysconfdir$ac_delim
-sharedstatedir!$sharedstatedir$ac_delim
-localstatedir!$localstatedir$ac_delim
-includedir!$includedir$ac_delim
-oldincludedir!$oldincludedir$ac_delim
-docdir!$docdir$ac_delim
-infodir!$infodir$ac_delim
-htmldir!$htmldir$ac_delim
-dvidir!$dvidir$ac_delim
-pdfdir!$pdfdir$ac_delim
-psdir!$psdir$ac_delim
-libdir!$libdir$ac_delim
-localedir!$localedir$ac_delim
-mandir!$mandir$ac_delim
-DEFS!$DEFS$ac_delim
-ECHO_C!$ECHO_C$ac_delim
-ECHO_N!$ECHO_N$ac_delim
-ECHO_T!$ECHO_T$ac_delim
-LIBS!$LIBS$ac_delim
-build_alias!$build_alias$ac_delim
-host_alias!$host_alias$ac_delim
-target_alias!$target_alias$ac_delim
-INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim
-INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim
-INSTALL_DATA!$INSTALL_DATA$ac_delim
-am__isrc!$am__isrc$ac_delim
-CYGPATH_W!$CYGPATH_W$ac_delim
-PACKAGE!$PACKAGE$ac_delim
-VERSION!$VERSION$ac_delim
-ACLOCAL!$ACLOCAL$ac_delim
-AUTOCONF!$AUTOCONF$ac_delim
-AUTOMAKE!$AUTOMAKE$ac_delim
-AUTOHEADER!$AUTOHEADER$ac_delim
-MAKEINFO!$MAKEINFO$ac_delim
-install_sh!$install_sh$ac_delim
-STRIP!$STRIP$ac_delim
-INSTALL_STRIP_PROGRAM!$INSTALL_STRIP_PROGRAM$ac_delim
-mkdir_p!$mkdir_p$ac_delim
-AWK!$AWK$ac_delim
-SET_MAKE!$SET_MAKE$ac_delim
-am__leading_dot!$am__leading_dot$ac_delim
-AMTAR!$AMTAR$ac_delim
-am__tar!$am__tar$ac_delim
-am__untar!$am__untar$ac_delim
-MAINTAINER_MODE_TRUE!$MAINTAINER_MODE_TRUE$ac_delim
-MAINTAINER_MODE_FALSE!$MAINTAINER_MODE_FALSE$ac_delim
-MAINT!$MAINT$ac_delim
-CC!$CC$ac_delim
-CFLAGS!$CFLAGS$ac_delim
-LDFLAGS!$LDFLAGS$ac_delim
-CPPFLAGS!$CPPFLAGS$ac_delim
-ac_ct_CC!$ac_ct_CC$ac_delim
-EXEEXT!$EXEEXT$ac_delim
-OBJEXT!$OBJEXT$ac_delim
-CPP!$CPP$ac_delim
-build!$build$ac_delim
-build_cpu!$build_cpu$ac_delim
-build_vendor!$build_vendor$ac_delim
-build_os!$build_os$ac_delim
-host!$host$ac_delim
-host_cpu!$host_cpu$ac_delim
-host_vendor!$host_vendor$ac_delim
-host_os!$host_os$ac_delim
-CANONICAL_HOST!$CANONICAL_HOST$ac_delim
-YACC!$YACC$ac_delim
-YFLAGS!$YFLAGS$ac_delim
-LEX!$LEX$ac_delim
-LEX_OUTPUT_ROOT!$LEX_OUTPUT_ROOT$ac_delim
-LEXLIB!$LEXLIB$ac_delim
-LN_S!$LN_S$ac_delim
-GREP!$GREP$ac_delim
-EGREP!$EGREP$ac_delim
-ECHO!$ECHO$ac_delim
-AR!$AR$ac_delim
-RANLIB!$RANLIB$ac_delim
-CXX!$CXX$ac_delim
-CXXFLAGS!$CXXFLAGS$ac_delim
-ac_ct_CXX!$ac_ct_CXX$ac_delim
-CXXCPP!$CXXCPP$ac_delim
-F77!$F77$ac_delim
-FFLAGS!$FFLAGS$ac_delim
-ac_ct_F77!$ac_ct_F77$ac_delim
-_ACEOF
-
-  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` =3D 97=
; then
+  . ./conf$$subs.sh ||
+    as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5
+
+  ac_delim_n=3D`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
+  if test $ac_delim_n =3D $ac_delim_num; then
     break
   elif $ac_last_try; then
-    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
-echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
-   { (exit 1); exit 1; }; }
+    as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5
   else
     ac_delim=3D"$ac_delim!$ac_delim _$ac_delim!! "
   fi
 done
-
-ac_eof=3D`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
-if test -n "$ac_eof"; then
-  ac_eof=3D`echo "$ac_eof" | sort -nru | sed 1q`
-  ac_eof=3D`expr $ac_eof + 1`
-fi
-
-cat >>$CONFIG_STATUS <<_ACEOF
-cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-_ACEOF
-sed '
-s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
-s/^/s,@/; s/!/@,|#_!!_#|/
-:n
-t n
-s/'"$ac_delim"'$/,g/; t
-s/$/\\/; p
-N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
-' >>$CONFIG_STATUS <conf$$subs.sed
-rm -f conf$$subs.sed
-cat >>$CONFIG_STATUS <<_ACEOF
-CEOF$ac_eof
-_ACEOF
-
-
-ac_delim=3D'%!_!# '
-for ac_last_try in false false false false false :; do
-  cat >conf$$subs.sed <<_ACEOF
-LIBTOOL!$LIBTOOL$ac_delim
-ENABLE_SHARED_TRUE!$ENABLE_SHARED_TRUE$ac_delim
-ENABLE_SHARED_FALSE!$ENABLE_SHARED_FALSE$ac_delim
-VERSIONING!$VERSIONING$ac_delim
-versionscript_TRUE!$versionscript_TRUE$ac_delim
-versionscript_FALSE!$versionscript_FALSE$ac_delim
-LDFLAGS_VERSION_SCRIPT!$LDFLAGS_VERSION_SCRIPT$ac_delim
-INCLUDE_openldap!$INCLUDE_openldap$ac_delim
-LIB_openldap!$LIB_openldap$ac_delim
-OPENLDAP_MODULE_TRUE!$OPENLDAP_MODULE_TRUE$ac_delim
-OPENLDAP_MODULE_FALSE!$OPENLDAP_MODULE_FALSE$ac_delim
-PKINIT_TRUE!$PKINIT_TRUE$ac_delim
-PKINIT_FALSE!$PKINIT_FALSE$ac_delim
-DIR_hdbdir!$DIR_hdbdir$ac_delim
-INCLUDE_krb4!$INCLUDE_krb4$ac_delim
-LIB_krb4!$LIB_krb4$ac_delim
-KRB4_TRUE!$KRB4_TRUE$ac_delim
-KRB4_FALSE!$KRB4_FALSE$ac_delim
-KRB5_TRUE!$KRB5_TRUE$ac_delim
-KRB5_FALSE!$KRB5_FALSE$ac_delim
-do_roken_rename_TRUE!$do_roken_rename_TRUE$ac_delim
-do_roken_rename_FALSE!$do_roken_rename_FALSE$ac_delim
-LIB_kdb!$LIB_kdb$ac_delim
-HAVE_OPENSSL_TRUE!$HAVE_OPENSSL_TRUE$ac_delim
-HAVE_OPENSSL_FALSE!$HAVE_OPENSSL_FALSE$ac_delim
-DIR_hcrypto!$DIR_hcrypto$ac_delim
-INCLUDE_hcrypto!$INCLUDE_hcrypto$ac_delim
-LIB_hcrypto!$LIB_hcrypto$ac_delim
-LIB_hcrypto_a!$LIB_hcrypto_a$ac_delim
-LIB_hcrypto_so!$LIB_hcrypto_so$ac_delim
-LIB_hcrypto_appl!$LIB_hcrypto_appl$ac_delim
-PTHREADS_CFLAGS!$PTHREADS_CFLAGS$ac_delim
-PTHREADS_LIBS!$PTHREADS_LIBS$ac_delim
-DCE_TRUE!$DCE_TRUE$ac_delim
-DCE_FALSE!$DCE_FALSE$ac_delim
-dpagaix_cflags!$dpagaix_cflags$ac_delim
-dpagaix_ldadd!$dpagaix_ldadd$ac_delim
-dpagaix_ldflags!$dpagaix_ldflags$ac_delim
-LIB_db_create!$LIB_db_create$ac_delim
-LIB_dbopen!$LIB_dbopen$ac_delim
-LIB_dbm_firstkey!$LIB_dbm_firstkey$ac_delim
-HAVE_DB1_TRUE!$HAVE_DB1_TRUE$ac_delim
-HAVE_DB1_FALSE!$HAVE_DB1_FALSE$ac_delim
-HAVE_DB3_TRUE!$HAVE_DB3_TRUE$ac_delim
-HAVE_DB3_FALSE!$HAVE_DB3_FALSE$ac_delim
-HAVE_NDBM_TRUE!$HAVE_NDBM_TRUE$ac_delim
-HAVE_NDBM_FALSE!$HAVE_NDBM_FALSE$ac_delim
-DBLIB!$DBLIB$ac_delim
-LIB_NDBM!$LIB_NDBM$ac_delim
-WFLAGS!$WFLAGS$ac_delim
-WFLAGS_NOUNUSED!$WFLAGS_NOUNUSED$ac_delim
-WFLAGS_NOIMPLICITINT!$WFLAGS_NOIMPLICITINT$ac_delim
-VOID_RETSIGTYPE!$VOID_RETSIGTYPE$ac_delim
-have_err_h_TRUE!$have_err_h_TRUE$ac_delim
-have_err_h_FALSE!$have_err_h_FALSE$ac_delim
-have_ifaddrs_h_TRUE!$have_ifaddrs_h_TRUE$ac_delim
-have_ifaddrs_h_FALSE!$have_ifaddrs_h_FALSE$ac_delim
-have_vis_h_TRUE!$have_vis_h_TRUE$ac_delim
-have_vis_h_FALSE!$have_vis_h_FALSE$ac_delim
-LIB_socket!$LIB_socket$ac_delim
-LIB_gethostbyname!$LIB_gethostbyname$ac_delim
-LIB_syslog!$LIB_syslog$ac_delim
-LIB_gethostbyname2!$LIB_gethostbyname2$ac_delim
-LIB_res_search!$LIB_res_search$ac_delim
-LIB_res_nsearch!$LIB_res_nsearch$ac_delim
-LIB_res_ndestroy!$LIB_res_ndestroy$ac_delim
-LIB_dn_expand!$LIB_dn_expand$ac_delim
-LIBOBJS!$LIBOBJS$ac_delim
-have_glob_h_TRUE!$have_glob_h_TRUE$ac_delim
-have_glob_h_FALSE!$have_glob_h_FALSE$ac_delim
-have_cgetent_TRUE!$have_cgetent_TRUE$ac_delim
-have_cgetent_FALSE!$have_cgetent_FALSE$ac_delim
-LIB_getsockopt!$LIB_getsockopt$ac_delim
-LIB_setsockopt!$LIB_setsockopt$ac_delim
-LIB_hstrerror!$LIB_hstrerror$ac_delim
-LIB_bswap16!$LIB_bswap16$ac_delim
-LIB_bswap32!$LIB_bswap32$ac_delim
-LIB_pidfile!$LIB_pidfile$ac_delim
-LIB_getaddrinfo!$LIB_getaddrinfo$ac_delim
-LIB_getnameinfo!$LIB_getnameinfo$ac_delim
-LIB_freeaddrinfo!$LIB_freeaddrinfo$ac_delim
-LIB_gai_strerror!$LIB_gai_strerror$ac_delim
-have_fnmatch_h_TRUE!$have_fnmatch_h_TRUE$ac_delim
-have_fnmatch_h_FALSE!$have_fnmatch_h_FALSE$ac_delim
-LIB_crypt!$LIB_crypt$ac_delim
-have_socket_wrapper_TRUE!$have_socket_wrapper_TRUE$ac_delim
-have_socket_wrapper_FALSE!$have_socket_wrapper_FALSE$ac_delim
-DIR_roken!$DIR_roken$ac_delim
-LIB_roken!$LIB_roken$ac_delim
-INCLUDES_roken!$INCLUDES_roken$ac_delim
-LIBADD_roken!$LIBADD_roken$ac_delim
-LIB_otp!$LIB_otp$ac_delim
-OTP_TRUE!$OTP_TRUE$ac_delim
-OTP_FALSE!$OTP_FALSE$ac_delim
-LIB_security!$LIB_security$ac_delim
-NROFF!$NROFF$ac_delim
-GROFF!$GROFF$ac_delim
-_ACEOF
-
-  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` =3D 97=
; then
-    break
-  elif $ac_last_try; then
-    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
-echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
-   { (exit 1); exit 1; }; }
-  else
-    ac_delim=3D"$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-
-ac_eof=3D`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
-if test -n "$ac_eof"; then
-  ac_eof=3D`echo "$ac_eof" | sort -nru | sed 1q`
-  ac_eof=3D`expr $ac_eof + 1`
-fi
-
-cat >>$CONFIG_STATUS <<_ACEOF
-cat >"\$tmp/subs-2.sed" <<\CEOF$ac_eof
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-_ACEOF
-sed '
-s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
-s/^/s,@/; s/!/@,|#_!!_#|/
-:n
-t n
-s/'"$ac_delim"'$/,g/; t
-s/$/\\/; p
-N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
-' >>$CONFIG_STATUS <conf$$subs.sed
-rm -f conf$$subs.sed
-cat >>$CONFIG_STATUS <<_ACEOF
-CEOF$ac_eof
-_ACEOF
-
-
-ac_delim=3D'%!_!# '
-for ac_last_try in false false false false false :; do
-  cat >conf$$subs.sed <<_ACEOF
-CATMAN!$CATMAN$ac_delim
-CATMAN_TRUE!$CATMAN_TRUE$ac_delim
-CATMAN_FALSE!$CATMAN_FALSE$ac_delim
-CATMANEXT!$CATMANEXT$ac_delim
-INCLUDE_readline!$INCLUDE_readline$ac_delim
-LIB_readline!$LIB_readline$ac_delim
-INCLUDE_hesiod!$INCLUDE_hesiod$ac_delim
-LIB_hesiod!$LIB_hesiod$ac_delim
-AIX_TRUE!$AIX_TRUE$ac_delim
-AIX_FALSE!$AIX_FALSE$ac_delim
-AIX4_TRUE!$AIX4_TRUE$ac_delim
-AIX4_FALSE!$AIX4_FALSE$ac_delim
-LIB_dlopen!$LIB_dlopen$ac_delim
-HAVE_DLOPEN_TRUE!$HAVE_DLOPEN_TRUE$ac_delim
-HAVE_DLOPEN_FALSE!$HAVE_DLOPEN_FALSE$ac_delim
-LIB_loadquery!$LIB_loadquery$ac_delim
-AIX_DYNAMIC_AFS_TRUE!$AIX_DYNAMIC_AFS_TRUE$ac_delim
-AIX_DYNAMIC_AFS_FALSE!$AIX_DYNAMIC_AFS_FALSE$ac_delim
-AIX_EXTRA_KAFS!$AIX_EXTRA_KAFS$ac_delim
-IRIX_TRUE!$IRIX_TRUE$ac_delim
-IRIX_FALSE!$IRIX_FALSE$ac_delim
-XMKMF!$XMKMF$ac_delim
-X_CFLAGS!$X_CFLAGS$ac_delim
-X_PRE_LIBS!$X_PRE_LIBS$ac_delim
-X_LIBS!$X_LIBS$ac_delim
-X_EXTRA_LIBS!$X_EXTRA_LIBS$ac_delim
-HAVE_X_TRUE!$HAVE_X_TRUE$ac_delim
-HAVE_X_FALSE!$HAVE_X_FALSE$ac_delim
-LIB_XauWriteAuth!$LIB_XauWriteAuth$ac_delim
-LIB_XauReadAuth!$LIB_XauReadAuth$ac_delim
-LIB_XauFileName!$LIB_XauFileName$ac_delim
-NEED_WRITEAUTH_TRUE!$NEED_WRITEAUTH_TRUE$ac_delim
-NEED_WRITEAUTH_FALSE!$NEED_WRITEAUTH_FALSE$ac_delim
-LIB_logwtmp!$LIB_logwtmp$ac_delim
-LIB_logout!$LIB_logout$ac_delim
-LIB_openpty!$LIB_openpty$ac_delim
-LIB_tgetent!$LIB_tgetent$ac_delim
-LIB_getpwnam_r!$LIB_getpwnam_r$ac_delim
-LIB_door_create!$LIB_door_create$ac_delim
-KCM_TRUE!$KCM_TRUE$ac_delim
-KCM_FALSE!$KCM_FALSE$ac_delim
-FRAMEWORK_SECURITY_TRUE!$FRAMEWORK_SECURITY_TRUE$ac_delim
-FRAMEWORK_SECURITY_FALSE!$FRAMEWORK_SECURITY_FALSE$ac_delim
-LIB_el_init!$LIB_el_init$ac_delim
-el_compat_TRUE!$el_compat_TRUE$ac_delim
-el_compat_FALSE!$el_compat_FALSE$ac_delim
-COMPILE_ET!$COMPILE_ET$ac_delim
-COM_ERR_TRUE!$COM_ERR_TRUE$ac_delim
-COM_ERR_FALSE!$COM_ERR_FALSE$ac_delim
-DIR_com_err!$DIR_com_err$ac_delim
-LIB_com_err!$LIB_com_err$ac_delim
-LIB_com_err_a!$LIB_com_err_a$ac_delim
-LIB_com_err_so!$LIB_com_err_so$ac_delim
-LIB_AUTH_SUBDIRS!$LIB_AUTH_SUBDIRS$ac_delim
-LTLIBOBJS!$LTLIBOBJS$ac_delim
-_ACEOF
-
-  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` =3D 55=
; then
-    break
-  elif $ac_last_try; then
-    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
-echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
-   { (exit 1); exit 1; }; }
-  else
-    ac_delim=3D"$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-
-ac_eof=3D`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
-if test -n "$ac_eof"; then
-  ac_eof=3D`echo "$ac_eof" | sort -nru | sed 1q`
-  ac_eof=3D`expr $ac_eof + 1`
-fi
-
-cat >>$CONFIG_STATUS <<_ACEOF
-cat >"\$tmp/subs-3.sed" <<\CEOF$ac_eof
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
-_ACEOF
-sed '
-s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
-s/^/s,@/; s/!/@,|#_!!_#|/
-:n
-t n
-s/'"$ac_delim"'$/,g/; t
-s/$/\\/; p
-N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
-' >>$CONFIG_STATUS <conf$$subs.sed
-rm -f conf$$subs.sed
-cat >>$CONFIG_STATUS <<_ACEOF
-:end
-s/|#_!!_#|//g
-CEOF$ac_eof
-_ACEOF
-
+rm -f conf$$subs.sh
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
+cat >>"\$tmp/subs1.awk" <<\\_ACAWK &&
+_ACEOF
+sed -n '
+h
+s/^/S["/; s/!.*/"]=3D/
+p
+g
+s/^[^!]*!//
+:repl
+t repl
+s/'"$ac_delim"'$//
+t delim
+:nl
+h
+s/\(.\{148\}\)..*/\1/
+t more1
+s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
+p
+n
+b repl
+:more1
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t nl
+:delim
+h
+s/\(.\{148\}\)..*/\1/
+t more2
+s/["\\]/\\&/g; s/^/"/; s/$/"/
+p
+b
+:more2
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t delim
+' <conf$$subs.awk | sed '
+/^[^""]/{
+  N
+  s/\n//
+}
+' >>$CONFIG_STATUS || ac_write_fail=3D1
+rm -f conf$$subs.awk
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
+_ACAWK
+cat >>"\$tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] =3D 1
+  FS =3D "=07"
+
+}
+{
+  line =3D $ 0
+  nfields =3D split(line, field, "@")
+  substed =3D 0
+  len =3D length(field[1])
+  for (i =3D 2; i < nfields; i++) {
+    key =3D field[i]
+    keylen =3D length(key)
+    if (S_is_set[key]) {
+      value =3D S[key]
+      line =3D substr(line, 1, len) "" value "" substr(line, len + keylen =
+ 3)
+      len +=3D length(value) + length(field[++i])
+      substed =3D 1
+    } else
+      len +=3D 1 + keylen
+  }
+
+  print line
+}
+
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \
+  || as_fn_error "could not setup config files machinery" "$LINENO" 5
+_ACEOF
=20
 # VPATH may cause trouble with some makes, so we remove $(srcdir),
 # ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
@@ -53892,20 +29972,128 @@
 }'
 fi
=20
-cat >>$CONFIG_STATUS <<\_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
 fi # test -n "$CONFIG_FILES"
=20
-
-for ac_tag in  :F $CONFIG_FILES  :H $CONFIG_HEADERS
+# Set up the scripts for CONFIG_HEADERS section.
+# No need to generate them if there are no CONFIG_HEADERS.
+# This happens for instance with `./config.status Makefile'.
+if test -n "$CONFIG_HEADERS"; then
+cat >"$tmp/defines.awk" <<\_ACAWK ||
+BEGIN {
+_ACEOF
+
+# Transform confdefs.h into an awk script `defines.awk', embedded as
+# here-document in config.status, that substitutes the proper values into
+# config.h.in to produce config.h.
+
+# Create a delimiter string that does not exist in confdefs.h, to ease
+# handling of long lines.
+ac_delim=3D'%!_!# '
+for ac_last_try in false false :; do
+  ac_t=3D`sed -n "/$ac_delim/p" confdefs.h`
+  if test -z "$ac_t"; then
+    break
+  elif $ac_last_try; then
+    as_fn_error "could not make $CONFIG_HEADERS" "$LINENO" 5
+  else
+    ac_delim=3D"$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+
+# For the awk script, D is an array of macro values keyed by name,
+# likewise P contains macro parameters if any.  Preserve backslash
+# newline sequences.
+
+ac_word_re=3D[_$as_cr_Letters][_$as_cr_alnum]*
+sed -n '
+s/.\{148\}/&'"$ac_delim"'/g
+t rset
+:rset
+s/^[	 ]*#[	 ]*define[	 ][	 ]*/ /
+t def
+d
+:def
+s/\\$//
+t bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]=3D"\2"\
+D["\1"]=3D" \3"/p
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=3D" \2"/p
+d
+:bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]=3D"\2"\
+D["\1"]=3D" \3\\\\\\n"\\/p
+t cont
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=3D" \2\\\\\\n"\\/p
+t cont
+d
+:cont
+n
+s/.\{148\}/&'"$ac_delim"'/g
+t clear
+:clear
+s/\\$//
+t bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/"/p
+d
+:bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
+b cont
+' <confdefs.h | sed '
+s/'"$ac_delim"'/"\\\
+"/g' >>$CONFIG_STATUS || ac_write_fail=3D1
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
+  for (key in D) D_is_set[key] =3D 1
+  FS =3D "=07"
+}
+/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
+  line =3D \$ 0
+  split(line, arg, " ")
+  if (arg[1] =3D=3D "#") {
+    defundef =3D arg[2]
+    mac1 =3D arg[3]
+  } else {
+    defundef =3D substr(arg[1], 2)
+    mac1 =3D arg[2]
+  }
+  split(mac1, mac2, "(") #)
+  macro =3D mac2[1]
+  prefix =3D substr(line, 1, index(line, defundef) - 1)
+  if (D_is_set[macro]) {
+    # Preserve the white space surrounding the "#".
+    print prefix "define", macro P[macro] D[macro]
+    next
+  } else {
+    # Replace #undef with comments.  This is necessary, for example,
+    # in the case of _POSIX_SOURCE, which is predefined and required
+    # on some systems where configure will not decide to define it.
+    if (defundef =3D=3D "undef") {
+      print "/*", prefix defundef, macro, "*/"
+      next
+    }
+  }
+}
+{ print }
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
+  as_fn_error "could not setup config headers machinery" "$LINENO" 5
+fi # test -n "$CONFIG_HEADERS"
+
+
+eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    :C $CONFIG_COMMANDS"
+shift
+for ac_tag
 do
   case $ac_tag in
   :[FHLC]) ac_mode=3D$ac_tag; continue;;
   esac
   case $ac_mode$ac_tag in
   :[FHL]*:*);;
-  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
-echo "$as_me: error: Invalid tag $ac_tag." >&2;}
-   { (exit 1); exit 1; }; };;
+  :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;;
   :[FH]-) ac_tag=3D-:-;;
   :[FH]*) ac_tag=3D$ac_tag:$ac_tag.in;;
   esac
@@ -53933,26 +30121,34 @@
 	   [\\/$]*) false;;
 	   *) test -f "$srcdir/$ac_f" && ac_f=3D"$srcdir/$ac_f";;
 	   esac ||
-	   { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
-echo "$as_me: error: cannot find input file: $ac_f" >&2;}
-   { (exit 1); exit 1; }; };;
+	   as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;;
       esac
-      ac_file_inputs=3D"$ac_file_inputs $ac_f"
+      case $ac_f in *\'*) ac_f=3D`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/=
g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
     done
=20
     # Let's still pretend it is `configure' which instantiates (i.e., don't
     # use $as_me), people would be surprised to read:
     #    /* config.h.  Generated by config.status.  */
-    configure_input=3D"Generated from "`IFS=3D:
-	  echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+    configure_input=3D'Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
     if test x"$ac_file" !=3D x-; then
       configure_input=3D"$ac_file.  $configure_input"
-      { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-    fi
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement stri=
ngs.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=3D`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=3D$configure_input;;
+    esac
=20
     case $ac_tag in
-    *:-:* | *:-) cat >"$tmp/stdin";;
+    *:-:* | *:-) cat >"$tmp/stdin" \
+      || as_fn_error "could not create $ac_file" "$LINENO" 5 ;;
     esac
     ;;
   esac
@@ -53962,7 +30158,7 @@
 	 X"$ac_file" : 'X\(//\)[^/]' \| \
 	 X"$ac_file" : 'X\(//\)$' \| \
 	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$ac_file" |
+$as_echo X"$ac_file" |
     sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
 	    s//\1/
 	    q
@@ -53980,55 +30176,15 @@
 	    q
 	  }
 	  s/.*/./; q'`
-  { as_dir=3D"$ac_dir"
-  case $as_dir in #(
-  -*) as_dir=3D./$as_dir;;
-  esac
-  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
-    as_dirs=3D
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=3D`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
-      *) as_qdir=3D$as_dir;;
-      esac
-      as_dirs=3D"'$as_qdir' $as_dirs"
-      as_dir=3D`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_dir" : 'X\(//\)[^/]' \| \
-	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create=
 directory $as_dir" >&5
-echo "$as_me: error: cannot create directory $as_dir" >&2;}
-   { (exit 1); exit 1; }; }; }
+  as_dir=3D"$ac_dir"; as_fn_mkdir_p
   ac_builddir=3D.
=20
 case "$ac_dir" in
 .) ac_dir_suffix=3D ac_top_builddir_sub=3D. ac_top_build_prefix=3D ;;
 *)
-  ac_dir_suffix=3D/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  ac_dir_suffix=3D/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
   # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=3D`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/=
,,'`
+  ac_top_builddir_sub=3D`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g=
;s|/||'`
   case $ac_top_builddir_sub in
   "") ac_top_builddir_sub=3D. ac_top_build_prefix=3D ;;
   *)  ac_top_build_prefix=3D$ac_top_builddir_sub/ ;;
@@ -54073,12 +30229,12 @@
   esac
 _ACEOF
=20
-cat >>$CONFIG_STATUS <<\_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
 # If the template does not know about datarootdir, expand it.
 # FIXME: This hack should be removed a few years after 2.60.
 ac_datarootdir_hack=3D; ac_datarootdir_seen=3D
-
-case `sed -n '/datarootdir/ {
+ac_sed_dataroot=3D'
+/datarootdir/ {
   p
   q
 }
@@ -54086,36 +30242,37 @@
 /@docdir@/p
 /@infodir@/p
 /@localedir@/p
-/@mandir@/p
-' $ac_file_inputs` in
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
 *datarootdir*) ac_datarootdir_seen=3Dyes;;
 *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --d=
atarootdir setting" >&5
-echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir s=
etting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems =
to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootd=
ir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
   ac_datarootdir_hack=3D'
   s&@datadir@&$datadir&g
   s&@docdir@&$docdir&g
   s&@infodir@&$infodir&g
   s&@localedir@&$localedir&g
   s&@mandir@&$mandir&g
-    s&\\\${datarootdir}&$datarootdir&g' ;;
+  s&\\\${datarootdir}&$datarootdir&g' ;;
 esac
 _ACEOF
=20
 # Neutralize VPATH when `$srcdir' =3D `.'.
 # Shell code in configure.ac might set extrasub.
 # FIXME: do we really want to maintain this feature?
-cat >>$CONFIG_STATUS <<_ACEOF
-  sed "$ac_vpsub
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=3D1
+ac_sed_extra=3D"$ac_vpsub
 $extrasub
 _ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=3D1
 :t
 /@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s&@configure_input@&$configure_input&;t t
+s|@configure_input@|$ac_sed_conf_input|;t t
 s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
 s&@srcdir@&$ac_srcdir&;t t
 s&@abs_srcdir@&$ac_abs_srcdir&;t t
 s&@top_srcdir@&$ac_top_srcdir&;t t
@@ -54126,135 +30283,65 @@
 s&@INSTALL@&$ac_INSTALL&;t t
 s&@MKDIR_P@&$ac_MKDIR_P&;t t
 $ac_datarootdir_hack
-" $ac_file_inputs | sed -f "$tmp/subs-1.sed" | sed -f "$tmp/subs-2.sed" | =
sed -f "$tmp/subs-3.sed" >$tmp/out
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$=
tmp/out \
+  || as_fn_error "could not create $ac_file" "$LINENO" 5
=20
 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
   { ac_out=3D`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; =
} &&
   { ac_out=3D`sed -n '/^[	 ]*datarootdir[	 ]*:*=3D/p' "$tmp/out"`; test -z=
 "$ac_out"; } &&
-  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the va=
riable \`datarootdir'
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a re=
ference to the variable \`datarootdir'
 which seems to be undefined.  Please make sure it is defined." >&5
-echo "$as_me: WARNING: $ac_file contains a reference to the variable \`dat=
arootdir'
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \=
`datarootdir'
 which seems to be undefined.  Please make sure it is defined." >&2;}
=20
   rm -f "$tmp/stdin"
   case $ac_file in
-  -) cat "$tmp/out"; rm -f "$tmp/out";;
-  *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
-  esac
+  -) cat "$tmp/out" && rm -f "$tmp/out";;
+  *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error "could not create $ac_file" "$LINENO" 5
  ;;
   :H)
   #
   # CONFIG_HEADER
   #
-_ACEOF
-
-# Transform confdefs.h into a sed script `conftest.defines', that
-# substitutes the proper values into config.h.in to produce config.h.
-rm -f conftest.defines conftest.tail
-# First, append a space to every undef/define line, to ease matching.
-echo 's/$/ /' >conftest.defines
-# Then, protect against being on the right side of a sed subst, or in
-# an unquoted here document, in config.status.  If some macros were
-# called several times there might be several #defines for the same
-# symbol, which is useless.  But do not sort them, since the last
-# AC_DEFINE must be honored.
-ac_word_re=3D[_$as_cr_Letters][_$as_cr_alnum]*
-# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", whe=
re
-# NAME is the cpp macro being defined, VALUE is the value it is being give=
n.
-# PARAMS is the parameter list in the macro definition--in most cases, it's
-# just an empty string.
-ac_dA=3D's,^\\([	 #]*\\)[^	 ]*\\([	 ]*'
-ac_dB=3D'\\)[	 (].*,\\1define\\2'
-ac_dC=3D' '
-ac_dD=3D' ,'
-
-uniq confdefs.h |
-  sed -n '
-	t rset
-	:rset
-	s/^[	 ]*#[	 ]*define[	 ][	 ]*//
-	t ok
-	d
-	:ok
-	s/[\\&,]/\\&/g
-	s/^\('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"=
${ac_dC}"'\3'"$ac_dD"'/p
-	s/^\('"$ac_word_re"'\)[	 ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"=
'/p
-  ' >>conftest.defines
-
-# Remove the space that was appended to ease matching.
-# Then replace #undef with comments.  This is necessary, for
-# example, in the case of _POSIX_SOURCE, which is predefined and required
-# on some systems where configure will not decide to define it.
-# (The regexp can be short, since the line contains either #define or #und=
ef.)
-echo 's/ $//
-s,^[	 #]*u.*,/* & */,' >>conftest.defines
-
-# Break up conftest.defines:
-ac_max_sed_lines=3D50
-
-# First sed command is:	 sed -f defines.sed $ac_file_inputs >"$tmp/out1"
-# Second one is:	 sed -f defines.sed "$tmp/out1" >"$tmp/out2"
-# Third one will be:	 sed -f defines.sed "$tmp/out2" >"$tmp/out1"
-# et cetera.
-ac_in=3D'$ac_file_inputs'
-ac_out=3D'"$tmp/out1"'
-ac_nxt=3D'"$tmp/out2"'
-
-while :
-do
-  # Write a here document:
-    cat >>$CONFIG_STATUS <<_ACEOF
-    # First, check the format of the line:
-    cat >"\$tmp/defines.sed" <<\\CEOF
-/^[	 ]*#[	 ]*undef[	 ][	 ]*$ac_word_re[	 ]*\$/b def
-/^[	 ]*#[	 ]*define[	 ][	 ]*$ac_word_re[(	 ]/b def
-b
-:def
-_ACEOF
-  sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS
-  echo 'CEOF
-    sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS
-  ac_in=3D$ac_out; ac_out=3D$ac_nxt; ac_nxt=3D$ac_in
-  sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail
-  grep . conftest.tail >/dev/null || break
-  rm -f conftest.defines
-  mv conftest.tail conftest.defines
-done
-rm -f conftest.defines conftest.tail
-
-echo "ac_result=3D$ac_in" >>$CONFIG_STATUS
-cat >>$CONFIG_STATUS <<\_ACEOF
   if test x"$ac_file" !=3D x-; then
-    echo "/* $configure_input  */" >"$tmp/config.h"
-    cat "$ac_result" >>"$tmp/config.h"
-    if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then
-      { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
-echo "$as_me: $ac_file is unchanged" >&6;}
+    {
+      $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs"
+    } >"$tmp/config.h" \
+      || as_fn_error "could not create $ac_file" "$LINENO" 5
+    if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
+$as_echo "$as_me: $ac_file is unchanged" >&6;}
     else
-      rm -f $ac_file
-      mv "$tmp/config.h" $ac_file
-    fi
-  else
-    echo "/* $configure_input  */"
-    cat "$ac_result"
-  fi
-  rm -f "$tmp/out12"
-# Compute $ac_file's index in $config_headers.
+      rm -f "$ac_file"
+      mv "$tmp/config.h" "$ac_file" \
+	|| as_fn_error "could not create $ac_file" "$LINENO" 5
+    fi
+  else
+    $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \
+      || as_fn_error "could not create -" "$LINENO" 5
+  fi
+# Compute "$ac_file"'s index in $config_headers.
+_am_arg=3D"$ac_file"
 _am_stamp_count=3D1
 for _am_header in $config_headers :; do
   case $_am_header in
-    $ac_file | $ac_file:* )
+    $_am_arg | $_am_arg:* )
       break ;;
     * )
       _am_stamp_count=3D`expr $_am_stamp_count + 1` ;;
   esac
 done
-echo "timestamp for $ac_file" >`$as_dirname -- $ac_file ||
-$as_expr X$ac_file : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X$ac_file : 'X\(//\)[^/]' \| \
-	 X$ac_file : 'X\(//\)$' \| \
-	 X$ac_file : 'X\(/\)' \| . 2>/dev/null ||
-echo X$ac_file |
+echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" ||
+$as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$_am_arg" : 'X\(//\)[^/]' \| \
+	 X"$_am_arg" : 'X\(//\)$' \| \
+	 X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$_am_arg" |
     sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
 	    s//\1/
 	    q
@@ -54274,17 +30361,751 @@
 	  s/.*/./; q'`/stamp-h$_am_stamp_count
  ;;
=20
-
-  esac
-
+  :C)  { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file command=
s" >&5
+$as_echo "$as_me: executing $ac_file commands" >&6;}
+ ;;
+  esac
+
+
+  case $ac_file$ac_mode in
+    "depfiles":C) test x"$AMDEP_TRUE" !=3D x"" || {
+  # Autoconf 2.62 quotes --file arguments for eval, but not when files
+  # are listed without --file.  Let's play safe and only enable the eval
+  # if we detect the quoting.
+  case $CONFIG_FILES in
+  *\'*) eval set x "$CONFIG_FILES" ;;
+  *)   set x $CONFIG_FILES ;;
+  esac
+  shift
+  for mf
+  do
+    # Strip MF so we end up with the name of the file.
+    mf=3D`echo "$mf" | sed -e 's/:.*$//'`
+    # Check whether this is an Automake generated Makefile or not.
+    # We used to match only the files named `Makefile.in', but
+    # some people rename them; so instead we look at the file content.
+    # Grep'ing the first line is not enough: some people post-process
+    # each Makefile.in and add a new line on top of each file to say so.
+    # Grep'ing the whole file is not good either: AIX grep has a line
+    # limit of 2048, but all sed's we know have understand at least 4000.
+    if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/nul=
l 2>&1; then
+      dirpart=3D`$as_dirname -- "$mf" ||
+$as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$mf" : 'X\(//\)[^/]' \| \
+	 X"$mf" : 'X\(//\)$' \| \
+	 X"$mf" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$mf" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+    else
+      continue
+    fi
+    # Extract the definition of DEPDIR, am__include, and am__quote
+    # from the Makefile without running `make'.
+    DEPDIR=3D`sed -n 's/^DEPDIR =3D //p' < "$mf"`
+    test -z "$DEPDIR" && continue
+    am__include=3D`sed -n 's/^am__include =3D //p' < "$mf"`
+    test -z "am__include" && continue
+    am__quote=3D`sed -n 's/^am__quote =3D //p' < "$mf"`
+    # When using ansi2knr, U may be empty or an underscore; expand it
+    U=3D`sed -n 's/^U =3D //p' < "$mf"`
+    # Find all dependency output files, they are included files with
+    # $(DEPDIR) in their names.  We invoke sed twice because it is the
+    # simplest approach to changing $(DEPDIR) to its actual value in the
+    # expansion.
+    for file in `sed -n "
+      s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf"=
 | \
+	 sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
+      # Make sure the directory exists.
+      test -f "$dirpart/$file" && continue
+      fdir=3D`$as_dirname -- "$file" ||
+$as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$file" : 'X\(//\)[^/]' \| \
+	 X"$file" : 'X\(//\)$' \| \
+	 X"$file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      as_dir=3D$dirpart/$fdir; as_fn_mkdir_p
+      # echo "creating $dirpart/$file"
+      echo '# dummy' > "$dirpart/$file"
+    done
+  done
+}
+ ;;
+    "libtool":C)
+
+    # See if we are running on zsh, and set the options which allow our
+    # commands through without removal of \ escapes.
+    if test -n "${ZSH_VERSION+set}" ; then
+      setopt NO_GLOB_SUBST
+    fi
+
+    cfgfile=3D"${ofile}T"
+    trap "$RM \"$cfgfile\"; exit 1" 1 2 15
+    $RM "$cfgfile"
+
+    cat <<_LT_EOF >> "$cfgfile"
+#! $SHELL
+
+# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building=
 support services.
+# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION
+# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed=
 1q`:
+# NOTE: Changes made to this file will be lost: look at ltmain.sh.
+#
+#   Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005,
+#                 2006, 2007, 2008, 2009, 2010 Free Software Foundation,
+#                 Inc.
+#   Written by Gordon Matzigkeit, 1996
+#
+#   This file is part of GNU Libtool.
+#
+# GNU Libtool is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of
+# the License, or (at your option) any later version.
+#
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html, or
+# obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+
+# The names of the tagged configurations supported by this script.
+available_tags=3D""
+
+# ### BEGIN LIBTOOL CONFIG
+
+# Which release of libtool.m4 was used?
+macro_version=3D$macro_version
+macro_revision=3D$macro_revision
+
+# Whether or not to build shared libraries.
+build_libtool_libs=3D$enable_shared
+
+# Whether or not to build static libraries.
+build_old_libs=3D$enable_static
+
+# What type of objects to build.
+pic_mode=3D$pic_mode
+
+# Whether or not to optimize for fast installation.
+fast_install=3D$enable_fast_install
+
+# Shell to use when invoking shell scripts.
+SHELL=3D$lt_SHELL
+
+# An echo program that protects backslashes.
+ECHO=3D$lt_ECHO
+
+# The host system.
+host_alias=3D$host_alias
+host=3D$host
+host_os=3D$host_os
+
+# The build system.
+build_alias=3D$build_alias
+build=3D$build
+build_os=3D$build_os
+
+# A sed program that does not truncate output.
+SED=3D$lt_SED
+
+# Sed that helps us avoid accidentally triggering echo(1) options like -n.
+Xsed=3D"\$SED -e 1s/^X//"
+
+# A grep program that handles long lines.
+GREP=3D$lt_GREP
+
+# An ERE matcher.
+EGREP=3D$lt_EGREP
+
+# A literal string matcher.
+FGREP=3D$lt_FGREP
+
+# A BSD- or MS-compatible name lister.
+NM=3D$lt_NM
+
+# Whether we need soft or hard links.
+LN_S=3D$lt_LN_S
+
+# What is the maximum length of a command?
+max_cmd_len=3D$max_cmd_len
+
+# Object file suffix (normally "o").
+objext=3D$ac_objext
+
+# Executable file suffix (normally "").
+exeext=3D$exeext
+
+# whether the shell understands "unset".
+lt_unset=3D$lt_unset
+
+# turn spaces into newlines.
+SP2NL=3D$lt_lt_SP2NL
+
+# turn newlines into spaces.
+NL2SP=3D$lt_lt_NL2SP
+
+# convert \$build file names to \$host format.
+to_host_file_cmd=3D$lt_cv_to_host_file_cmd
+
+# convert \$build files to toolchain format.
+to_tool_file_cmd=3D$lt_cv_to_tool_file_cmd
+
+# An object symbol dumper.
+OBJDUMP=3D$lt_OBJDUMP
+
+# Method to check whether dependent libraries are shared objects.
+deplibs_check_method=3D$lt_deplibs_check_method
+
+# Command to use when deplibs_check_method =3D "file_magic".
+file_magic_cmd=3D$lt_file_magic_cmd
+
+# How to find potential files when deplibs_check_method =3D "file_magic".
+file_magic_glob=3D$lt_file_magic_glob
+
+# Find potential files using nocaseglob when deplibs_check_method =3D "fil=
e_magic".
+want_nocaseglob=3D$lt_want_nocaseglob
+
+# DLL creation program.
+DLLTOOL=3D$lt_DLLTOOL
+
+# Command to associate shared and link libraries.
+sharedlib_from_linklib_cmd=3D$lt_sharedlib_from_linklib_cmd
+
+# The archiver.
+AR=3D$lt_AR
+
+# Flags to create an archive.
+AR_FLAGS=3D$lt_AR_FLAGS
+
+# How to feed a file listing to the archiver.
+archiver_list_spec=3D$lt_archiver_list_spec
+
+# A symbol stripping program.
+STRIP=3D$lt_STRIP
+
+# Commands used to install an old-style archive.
+RANLIB=3D$lt_RANLIB
+old_postinstall_cmds=3D$lt_old_postinstall_cmds
+old_postuninstall_cmds=3D$lt_old_postuninstall_cmds
+
+# Whether to use a lock for old archive extraction.
+lock_old_archive_extraction=3D$lock_old_archive_extraction
+
+# A C compiler.
+LTCC=3D$lt_CC
+
+# LTCC compiler flags.
+LTCFLAGS=3D$lt_CFLAGS
+
+# Take the output of nm and produce a listing of raw symbols and C names.
+global_symbol_pipe=3D$lt_lt_cv_sys_global_symbol_pipe
+
+# Transform the output of nm in a proper C declaration.
+global_symbol_to_cdecl=3D$lt_lt_cv_sys_global_symbol_to_cdecl
+
+# Transform the output of nm in a C name address pair.
+global_symbol_to_c_name_address=3D$lt_lt_cv_sys_global_symbol_to_c_name_ad=
dress
+
+# Transform the output of nm in a C name address pair when lib prefix is n=
eeded.
+global_symbol_to_c_name_address_lib_prefix=3D$lt_lt_cv_sys_global_symbol_t=
o_c_name_address_lib_prefix
+
+# Specify filename containing input files for \$NM.
+nm_file_list_spec=3D$lt_nm_file_list_spec
+
+# The root where to search for dependent libraries,and in which our librar=
ies should be installed.
+lt_sysroot=3D$lt_sysroot
+
+# The name of the directory that contains temporary libtool files.
+objdir=3D$objdir
+
+# Used to examine libraries when file_magic_cmd begins with "file".
+MAGIC_CMD=3D$MAGIC_CMD
+
+# Must we lock files when doing compilation?
+need_locks=3D$lt_need_locks
+
+# Manifest tool.
+MANIFEST_TOOL=3D$lt_MANIFEST_TOOL
+
+# Tool to manipulate archived DWARF debug symbol files on Mac OS X.
+DSYMUTIL=3D$lt_DSYMUTIL
+
+# Tool to change global to local symbols on Mac OS X.
+NMEDIT=3D$lt_NMEDIT
+
+# Tool to manipulate fat objects and archives on Mac OS X.
+LIPO=3D$lt_LIPO
+
+# ldd/readelf like tool for Mach-O binaries on Mac OS X.
+OTOOL=3D$lt_OTOOL
+
+# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4.
+OTOOL64=3D$lt_OTOOL64
+
+# Old archive suffix (normally "a").
+libext=3D$libext
+
+# Shared library suffix (normally ".so").
+shrext_cmds=3D$lt_shrext_cmds
+
+# The commands to extract the exported symbol list from a shared archive.
+extract_expsyms_cmds=3D$lt_extract_expsyms_cmds
+
+# Variables whose values should be saved in libtool wrapper scripts and
+# restored at link time.
+variables_saved_for_relink=3D$lt_variables_saved_for_relink
+
+# Do we need the "lib" prefix for modules?
+need_lib_prefix=3D$need_lib_prefix
+
+# Do we need a version for libraries?
+need_version=3D$need_version
+
+# Library versioning type.
+version_type=3D$version_type
+
+# Shared library runtime path variable.
+runpath_var=3D$runpath_var
+
+# Shared library path variable.
+shlibpath_var=3D$shlibpath_var
+
+# Is shlibpath searched before the hard-coded library search path?
+shlibpath_overrides_runpath=3D$shlibpath_overrides_runpath
+
+# Format of library name prefix.
+libname_spec=3D$lt_libname_spec
+
+# List of archive names.  First name is the real one, the rest are links.
+# The last name is the one that the linker finds with -lNAME
+library_names_spec=3D$lt_library_names_spec
+
+# The coded name of the library, if different from the real name.
+soname_spec=3D$lt_soname_spec
+
+# Permission mode override for installation of shared libraries.
+install_override_mode=3D$lt_install_override_mode
+
+# Command to use after installation of a shared archive.
+postinstall_cmds=3D$lt_postinstall_cmds
+
+# Command to use after uninstallation of a shared archive.
+postuninstall_cmds=3D$lt_postuninstall_cmds
+
+# Commands used to finish a libtool library installation in a directory.
+finish_cmds=3D$lt_finish_cmds
+
+# As "finish_cmds", except a single script fragment to be evaled but
+# not shown.
+finish_eval=3D$lt_finish_eval
+
+# Whether we should hardcode library paths into libraries.
+hardcode_into_libs=3D$hardcode_into_libs
+
+# Compile-time system search path for libraries.
+sys_lib_search_path_spec=3D$lt_sys_lib_search_path_spec
+
+# Run-time system search path for libraries.
+sys_lib_dlsearch_path_spec=3D$lt_sys_lib_dlsearch_path_spec
+
+# Whether dlopen is supported.
+dlopen_support=3D$enable_dlopen
+
+# Whether dlopen of programs is supported.
+dlopen_self=3D$enable_dlopen_self
+
+# Whether dlopen of statically linked programs is supported.
+dlopen_self_static=3D$enable_dlopen_self_static
+
+# Commands to strip libraries.
+old_striplib=3D$lt_old_striplib
+striplib=3D$lt_striplib
+
+
+# The linker used to build libraries.
+LD=3D$lt_LD
+
+# How to create reloadable object files.
+reload_flag=3D$lt_reload_flag
+reload_cmds=3D$lt_reload_cmds
+
+# Commands used to build an old-style archive.
+old_archive_cmds=3D$lt_old_archive_cmds
+
+# A language specific compiler.
+CC=3D$lt_compiler
+
+# Is the compiler the GNU compiler?
+with_gcc=3D$GCC
+
+# Compiler flag to turn off builtin functions.
+no_builtin_flag=3D$lt_lt_prog_compiler_no_builtin_flag
+
+# Additional compiler flags for building library objects.
+pic_flag=3D$lt_lt_prog_compiler_pic
+
+# How to pass a linker flag through the compiler.
+wl=3D$lt_lt_prog_compiler_wl
+
+# Compiler flag to prevent dynamic linking.
+link_static_flag=3D$lt_lt_prog_compiler_static
+
+# Does compiler simultaneously support -c and -o options?
+compiler_c_o=3D$lt_lt_cv_prog_compiler_c_o
+
+# Whether or not to add -lc for building shared libraries.
+build_libtool_need_lc=3D$archive_cmds_need_lc
+
+# Whether or not to disallow shared libs when runtime libs are static.
+allow_libtool_libs_with_static_runtimes=3D$enable_shared_with_static_runti=
mes
+
+# Compiler flag to allow reflexive dlopens.
+export_dynamic_flag_spec=3D$lt_export_dynamic_flag_spec
+
+# Compiler flag to generate shared objects directly from archives.
+whole_archive_flag_spec=3D$lt_whole_archive_flag_spec
+
+# Whether the compiler copes with passing no objects directly.
+compiler_needs_object=3D$lt_compiler_needs_object
+
+# Create an old-style archive from a shared archive.
+old_archive_from_new_cmds=3D$lt_old_archive_from_new_cmds
+
+# Create a temporary old-style archive to link instead of a shared archive.
+old_archive_from_expsyms_cmds=3D$lt_old_archive_from_expsyms_cmds
+
+# Commands used to build a shared archive.
+archive_cmds=3D$lt_archive_cmds
+archive_expsym_cmds=3D$lt_archive_expsym_cmds
+
+# Commands used to build a loadable module if different from building
+# a shared archive.
+module_cmds=3D$lt_module_cmds
+module_expsym_cmds=3D$lt_module_expsym_cmds
+
+# Whether we are building with GNU ld or not.
+with_gnu_ld=3D$lt_with_gnu_ld
+
+# Flag that allows shared libraries with undefined symbols to be built.
+allow_undefined_flag=3D$lt_allow_undefined_flag
+
+# Flag that enforces no undefined symbols.
+no_undefined_flag=3D$lt_no_undefined_flag
+
+# Flag to hardcode \$libdir into a binary during linking.
+# This must work even if \$libdir does not exist
+hardcode_libdir_flag_spec=3D$lt_hardcode_libdir_flag_spec
+
+# If ld is used when linking, flag to hardcode \$libdir into a binary
+# during linking.  This must work even if \$libdir does not exist.
+hardcode_libdir_flag_spec_ld=3D$lt_hardcode_libdir_flag_spec_ld
+
+# Whether we need a single "-rpath" flag with a separated argument.
+hardcode_libdir_separator=3D$lt_hardcode_libdir_separator
+
+# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# DIR into the resulting binary.
+hardcode_direct=3D$hardcode_direct
+
+# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes
+# DIR into the resulting binary and the resulting library dependency is
+# "absolute",i.e impossible to change by setting \${shlibpath_var} if the
+# library is relocated.
+hardcode_direct_absolute=3D$hardcode_direct_absolute
+
+# Set to "yes" if using the -LDIR flag during linking hardcodes DIR
+# into the resulting binary.
+hardcode_minus_L=3D$hardcode_minus_L
+
+# Set to "yes" if using SHLIBPATH_VAR=3DDIR during linking hardcodes DIR
+# into the resulting binary.
+hardcode_shlibpath_var=3D$hardcode_shlibpath_var
+
+# Set to "yes" if building a shared library automatically hardcodes DIR
+# into the library and all subsequent libraries and executables linked
+# against it.
+hardcode_automatic=3D$hardcode_automatic
+
+# Set to yes if linker adds runtime paths of dependent libraries
+# to runtime path list.
+inherit_rpath=3D$inherit_rpath
+
+# Whether libtool must link a program against all its dependency libraries.
+link_all_deplibs=3D$link_all_deplibs
+
+# Set to "yes" if exported symbols are required.
+always_export_symbols=3D$always_export_symbols
+
+# The commands to list exported symbols.
+export_symbols_cmds=3D$lt_export_symbols_cmds
+
+# Symbols that should not be listed in the preloaded symbols.
+exclude_expsyms=3D$lt_exclude_expsyms
+
+# Symbols that must always be exported.
+include_expsyms=3D$lt_include_expsyms
+
+# Commands necessary for linking programs (against libraries) with templat=
es.
+prelink_cmds=3D$lt_prelink_cmds
+
+# Commands necessary for finishing linking programs.
+postlink_cmds=3D$lt_postlink_cmds
+
+# Specify filename containing input files.
+file_list_spec=3D$lt_file_list_spec
+
+# How to hardcode a shared library path into an executable.
+hardcode_action=3D$hardcode_action
+
+# ### END LIBTOOL CONFIG
+
+_LT_EOF
+
+  case $host_os in
+  aix3*)
+    cat <<\_LT_EOF >> "$cfgfile"
+# AIX sometimes has problems with the GCC collect2 program.  For some
+# reason, if we set the COLLECT_NAMES environment variable, the problems
+# vanish in a puff of smoke.
+if test "X${COLLECT_NAMES+set}" !=3D Xset; then
+  COLLECT_NAMES=3D
+  export COLLECT_NAMES
+fi
+_LT_EOF
+    ;;
+  esac
+
+
+ltmain=3D"$ac_aux_dir/ltmain.sh"
+
+
+  # We use sed instead of cat because bash on DJGPP gets confused if
+  # if finds mixed CR/LF and LF-only lines.  Since sed operates in
+  # text mode, it properly converts lines to CR/LF.  This bash problem
+  # is reportedly fixed, but why not run on old versions too?
+  sed '$q' "$ltmain" >> "$cfgfile" \
+     || (rm -f "$cfgfile"; exit 1)
+
+  if test x"$xsi_shell" =3D xyes; then
+  sed -e '/^func_dirname ()$/,/^} # func_dirname /c\
+func_dirname ()\
+{\
+\    case ${1} in\
+\      */*) func_dirname_result=3D"${1%/*}${2}" ;;\
+\      *  ) func_dirname_result=3D"${3}" ;;\
+\    esac\
+} # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_basename ()$/,/^} # func_basename /c\
+func_basename ()\
+{\
+\    func_basename_result=3D"${1##*/}"\
+} # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp=
 \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename=
 /c\
+func_dirname_and_basename ()\
+{\
+\    case ${1} in\
+\      */*) func_dirname_result=3D"${1%/*}${2}" ;;\
+\      *  ) func_dirname_result=3D"${3}" ;;\
+\    esac\
+\    func_basename_result=3D"${1##*/}"\
+} # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > =
$cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_stripname ()$/,/^} # func_stripname /c\
+func_stripname ()\
+{\
+\    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\
+\    # positional parameters, so assign one to ordinary parameter first.\
+\    func_stripname_result=3D${3}\
+\    func_stripname_result=3D${func_stripname_result#"${1}"}\
+\    func_stripname_result=3D${func_stripname_result%"${2}"}\
+} # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tm=
p \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\
+func_split_long_opt ()\
+{\
+\    func_split_long_opt_name=3D${1%%=3D*}\
+\    func_split_long_opt_arg=3D${1#*=3D}\
+} # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfi=
le.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\
+func_split_short_opt ()\
+{\
+\    func_split_short_opt_arg=3D${1#??}\
+\    func_split_short_opt_name=3D${1%"$func_split_short_opt_arg"}\
+} # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgf=
ile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\
+func_lo2o ()\
+{\
+\    case ${1} in\
+\      *.lo) func_lo2o_result=3D${1%.lo}.${objext} ;;\
+\      *)    func_lo2o_result=3D${1} ;;\
+\    esac\
+} # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_xform ()$/,/^} # func_xform /c\
+func_xform ()\
+{\
+    func_xform_result=3D${1%.*}.lo\
+} # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_arith ()$/,/^} # func_arith /c\
+func_arith ()\
+{\
+    func_arith_result=3D$(( $* ))\
+} # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_len ()$/,/^} # func_len /c\
+func_len ()\
+{\
+    func_len_result=3D${#1}\
+} # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+fi
+
+if test x"$lt_shell_append" =3D xyes; then
+  sed -e '/^func_append ()$/,/^} # func_append /c\
+func_append ()\
+{\
+    eval "${1}+=3D\\${2}"\
+} # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\
+func_append_quoted ()\
+{\
+\    func_quote_for_eval "${2}"\
+\    eval "${1}+=3D\\\\ \\$func_quote_for_eval_result"\
+} # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfil=
e.tmp \
+  && mv -f "$cfgfile.tmp" "$cfgfile" \
+    || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfil=
e.tmp")
+test 0 -eq $? || _lt_function_replace_fail=3D:
+
+
+  # Save a `func_append' function call where possible by direct use of '+=
=3D'
+  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+=3D"%g' $cfgfile > $cfgfi=
le.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgf=
ile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=3D:
+else
+  # Save a `func_append' function call even when '+=3D' is not available
+  sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1=3D"$\1%g' $cfgfile > $cfg=
file.tmp \
+    && mv -f "$cfgfile.tmp" "$cfgfile" \
+      || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgf=
ile.tmp")
+  test 0 -eq $? || _lt_function_replace_fail=3D:
+fi
+
+if test x"$_lt_function_replace_fail" =3D x":"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute e=
xtended shell functions in $ofile" >&5
+$as_echo "$as_me: WARNING: Unable to substitute extended shell functions i=
n $ofile" >&2;}
+fi
+
+
+   mv -f "$cfgfile" "$ofile" ||
+    (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile")
+  chmod +x "$ofile"
+
+ ;;
+
+  esac
 done # for ac_tag
=20
=20
-{ (exit 0); exit 0; }
-_ACEOF
-chmod +x $CONFIG_STATUS
+as_fn_exit 0
+_ACEOF
 ac_clean_files=3D$ac_clean_files_save
=20
+test $ac_write_fail =3D 0 ||
+  as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5
+
=20
 # configure is writing to config.log, and then calls config.status.
 # config.status does its own redirection, appending to config.log.
@@ -54304,14 +31125,166 @@
   exec 5>>config.log
   # Use ||, not &&, to avoid exiting from the if with $? =3D 1, which
   # would make configure fail if this is the last instruction.
-  $ac_cs_success || { (exit 1); exit 1; }
+  $ac_cs_success || as_fn_exit $?
+fi
+
+#
+# CONFIG_SUBDIRS section.
+#
+if test "$no_recursion" !=3D yes; then
+
+  # Remove --cache-file, --srcdir, and --disable-option-checking arguments
+  # so they do not pile up.
+  ac_sub_configure_args=3D
+  ac_prev=3D
+  eval "set x $ac_configure_args"
+  shift
+  for ac_arg
+  do
+    if test -n "$ac_prev"; then
+      ac_prev=3D
+      continue
+    fi
+    case $ac_arg in
+    -cache-file | --cache-file | --cache-fil | --cache-fi \
+    | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+      ac_prev=3Dcache_file ;;
+    -cache-file=3D* | --cache-file=3D* | --cache-fil=3D* | --cache-fi=3D* \
+    | --cache-f=3D* | --cache-=3D* | --cache=3D* | --cach=3D* | --cac=3D* =
| --ca=3D* \
+    | --c=3D*)
+      ;;
+    --config-cache | -C)
+      ;;
+    -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+      ac_prev=3Dsrcdir ;;
+    -srcdir=3D* | --srcdir=3D* | --srcdi=3D* | --srcd=3D* | --src=3D* | --=
sr=3D*)
+      ;;
+    -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+      ac_prev=3Dprefix ;;
+    -prefix=3D* | --prefix=3D* | --prefi=3D* | --pref=3D* | --pre=3D* | --=
pr=3D* | --p=3D*)
+      ;;
+    --disable-option-checking)
+      ;;
+    *)
+      case $ac_arg in
+      *\'*) ac_arg=3D`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+      esac
+      as_fn_append ac_sub_configure_args " '$ac_arg'" ;;
+    esac
+  done
+
+  # Always prepend --prefix to ensure using the same prefix
+  # in subdir configurations.
+  ac_arg=3D"--prefix=3D$prefix"
+  case $ac_arg in
+  *\'*) ac_arg=3D`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+  esac
+  ac_sub_configure_args=3D"'$ac_arg' $ac_sub_configure_args"
+
+  # Pass --silent
+  if test "$silent" =3D yes; then
+    ac_sub_configure_args=3D"--silent $ac_sub_configure_args"
+  fi
+
+  # Always prepend --disable-option-checking to silence warnings, since
+  # different subdirs can have different --enable and --with options.
+  ac_sub_configure_args=3D"--disable-option-checking $ac_sub_configure_arg=
s"
+
+  ac_popdir=3D`pwd`
+  for ac_dir in : $subdirs; do test "x$ac_dir" =3D x: && continue
+
+    # Do not complain, so a configure script can configure whichever
+    # parts of a large source tree are present.
+    test -d "$srcdir/$ac_dir" || continue
+
+    ac_msg=3D"=3D=3D=3D configuring in $ac_dir (`pwd`/$ac_dir)"
+    $as_echo "$as_me:${as_lineno-$LINENO}: $ac_msg" >&5
+    $as_echo "$ac_msg" >&6
+    as_dir=3D"$ac_dir"; as_fn_mkdir_p
+    ac_builddir=3D.
+
+case "$ac_dir" in
+.) ac_dir_suffix=3D ac_top_builddir_sub=3D. ac_top_build_prefix=3D ;;
+*)
+  ac_dir_suffix=3D/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=3D`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g=
;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=3D. ac_top_build_prefix=3D ;;
+  *)  ac_top_build_prefix=3D$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=3D$ac_pwd
+ac_abs_builddir=3D$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=3D$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=3D.
+    ac_top_srcdir=3D$ac_top_builddir_sub
+    ac_abs_top_srcdir=3D$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=3D$srcdir$ac_dir_suffix;
+    ac_top_srcdir=3D$srcdir
+    ac_abs_top_srcdir=3D$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=3D$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=3D$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=3D$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=3D$ac_abs_top_srcdir$ac_dir_suffix
+
+
+    cd "$ac_dir"
+
+    # Check for guested configure; otherwise get Cygnus style configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      ac_sub_configure=3D$ac_srcdir/configure.gnu
+    elif test -f "$ac_srcdir/configure"; then
+      ac_sub_configure=3D$ac_srcdir/configure
+    elif test -f "$ac_srcdir/configure.in"; then
+      # This should be Cygnus configure.
+      ac_sub_configure=3D$ac_aux_dir/configure
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: no configuration i=
nformation is in $ac_dir" >&5
+$as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2=
;}
+      ac_sub_configure=3D
+    fi
+
+    # The recursion is here.
+    if test -n "$ac_sub_configure"; then
+      # Make the cache file name correct relative to the subdirectory.
+      case $cache_file in
+      [\\/]* | ?:[\\/]* ) ac_sub_cache_file=3D$cache_file ;;
+      *) # Relative name.
+	ac_sub_cache_file=3D$ac_top_build_prefix$cache_file ;;
+      esac
+
+      { $as_echo "$as_me:${as_lineno-$LINENO}: running $SHELL $ac_sub_conf=
igure $ac_sub_configure_args --cache-file=3D$ac_sub_cache_file --srcdir=3D$=
ac_srcdir" >&5
+$as_echo "$as_me: running $SHELL $ac_sub_configure $ac_sub_configure_args =
--cache-file=3D$ac_sub_cache_file --srcdir=3D$ac_srcdir" >&6;}
+      # The eval makes quoting arguments work.
+      eval "\$SHELL \"\$ac_sub_configure\" $ac_sub_configure_args \
+	   --cache-file=3D\"\$ac_sub_cache_file\" --srcdir=3D\"\$ac_srcdir\"" ||
+	as_fn_error "$ac_sub_configure failed for $ac_dir" "$LINENO" 5
+    fi
+
+    cd "$ac_popdir"
+  done
+fi
+if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" !=3D =
no; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: =
$ac_unrecognized_opts" >&5
+$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&=
2;}
 fi
=20
=20
=20
 cat > include/newversion.h.in <<EOF
-const char *heimdal_long_version =3D "@(#)\$Version: $PACKAGE_STRING by @U=
SER@ on @HOST@ ($host) @DATE@ \$";
-const char *heimdal_version =3D "Heimdal 1.1";
+#ifndef VERSION_HIDDEN
+#define VERSION_HIDDEN
+#endif
+VERSION_HIDDEN const char *heimdal_long_version =3D "@(#)\$Version: $PACKA=
GE_STRING by @USER@ on @HOST@ ($host) @DATE@ \$";
+VERSION_HIDDEN const char *heimdal_version =3D "Heimdal 1.5.2";
 EOF
=20
 if test -f include/version.h && cmp -s include/newversion.h.in include/ver=
sion.h.in; then
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/Makefile.am
--- a/head/crypto/heimdal/doc/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-# $Id: Makefile.am 22284 2007-12-13 20:39:37Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
 AUTOMAKE_OPTIONS =3D no-texinfo.tex
=20
-MAKEINFOFLAGS =3D --no-split --css-include=3D$(srcdir)/heimdal.css
+MAKEINFOFLAGS =3D --css-include=3D$(srcdir)/heimdal.css
=20
 TEXI2DVI =3D true # ARGH, make distcheck can't be disabled to not build dv=
ifiles
=20
@@ -14,6 +14,26 @@
 	-e 's,[@]objdir[@],.,g' \
 	-e 's,[@]PACKAGE_VERSION[@],$(PACKAGE_VERSION),g'
=20
+hcrypto.dxy: hcrypto.din Makefile
+	$(dxy_subst) < $(srcdir)/hcrypto.din > hcrypto.dxy.tmp
+	chmod +x hcrypto.dxy.tmp
+	mv hcrypto.dxy.tmp hcrypto.dxy
+
+hdb.dxy: hdb.din Makefile
+	$(dxy_subst) < $(srcdir)/hdb.din > hdb.dxy.tmp
+	chmod +x hdb.dxy.tmp
+	mv hdb.dxy.tmp hdb.dxy
+
+hx509.dxy: hx509.din Makefile
+	$(dxy_subst) < $(srcdir)/hx509.din > hx509.dxy.tmp
+	chmod +x hx509.dxy.tmp
+	mv hx509.dxy.tmp hx509.dxy
+
+gssapi.dxy: gssapi.din Makefile
+	$(dxy_subst) < $(srcdir)/gssapi.din > gssapi.dxy.tmp
+	chmod +x gssapi.dxy.tmp
+	mv gssapi.dxy.tmp gssapi.dxy
+
 krb5.dxy: krb5.din Makefile
 	$(dxy_subst) < $(srcdir)/krb5.din > krb5.dxy.tmp
 	chmod +x krb5.dxy.tmp
@@ -24,16 +44,10 @@
 	chmod +x ntlm.dxy.tmp
 	mv ntlm.dxy.tmp ntlm.dxy
=20
-hx509.dxy: hx509.din Makefile
-	$(dxy_subst) < $(srcdir)/hx509.din > hx509.dxy.tmp
-	chmod +x hx509.dxy.tmp
-	mv hx509.dxy.tmp hx509.dxy
-
-hcrypto.dxy: hcrypto.din Makefile
-	$(dxy_subst) < $(srcdir)/hcrypto.din > hcrypto.dxy.tmp
-	chmod +x hcrypto.dxy.tmp
-	mv hcrypto.dxy.tmp hcrypto.dxy
-
+wind.dxy: wind.din Makefile
+	$(dxy_subst) < $(srcdir)/wind.din > wind.dxy.tmp
+	chmod +x wind.dxy.tmp
+	mv wind.dxy.tmp wind.dxy
=20
 texi_subst =3D sed -e 's,[@]dbdir[@],$(localstatedir),g' \
 	-e 's,[@]PACKAGE_VERSION[@],$(PACKAGE_VERSION),g'
@@ -43,15 +57,51 @@
 	chmod +x vars.texi.tmp
 	mv vars.texi.tmp vars.texi
=20
-doxygen: krb5.dxy ntlm.dxy hx509.dxy hcrypto.dxy
-	doxygen krb5.dxy
-	doxygen ntlm.dxy
-	doxygen hx509.dxy
-	doxygen hcrypto.dxy
+PROJECTS =3D hcrypto hdb hx509 gssapi krb5 ntlm wind=20
+
+doxyout doxygen: hdb.dxy hx509.dxy hcrypto.dxy gssapi.dxy krb5.dxy ntlm.dx=
y wind.dxy
+	@find $(srcdir)/doxyout -type d ! -perm -200 -exec chmod u+w {} ';' ; \
+	rm -rf $(srcdir)/doxyout ; \
+	mkdir $(srcdir)/doxyout ; \
+	for a in $(PROJECTS) ; do \
+		echo $$a ; \
+		doxygen $$a.dxy; \
+		(cd $(srcdir)/doxyout && find $$a/man -type f > $$a/manpages ) ; \
+	done
+
+install-data-hook: install-doxygen-manpage
+uninstall-hook: uninstall-doxygen-manpage
+dist-hook: doxygen
+
+install-doxygen-manpage:
+	for a in $(PROJECTS) ; do \
+		f=3D"$(srcdir)/doxyout/$$a/manpages" ; \
+		test -f $$f || continue ; \
+		echo "install $$a manual pages $$(wc -l < $$f)" ; \
+		while read x ; do \
+			section=3D`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \
+			$(mkinstalldirs) "$(DESTDIR)$(mandir)/man$$section" ; \
+			$(INSTALL_DATA) $(srcdir)/doxyout/$$x "$(DESTDIR)$(mandir)/man$$section=
" ; \
+		done < $$f ; \
+	done ; exit 0
+
+uninstall-doxygen-manpage:
+	@for a in $(PROJECTS) ; do \
+		f=3D"$(srcdir)/doxyout/$$a/manpages" ; \
+		test -f $$f || continue ; \
+		echo "removing $$a manual pages" ; \
+		while read x ; do \
+			section=3D`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \
+			base=3D`basename $$x` ; \
+			rm "$(DESTDIR)$(mandir)/man$$section/$$base" ; \
+		done < $$f ; \
+	done
+
=20
 heimdal_TEXINFOS =3D \
 	ack.texi \
 	apps.texi \
+	copyright.texi \
 	heimdal.texi \
 	install.texi \
 	intro.texi \
@@ -65,21 +115,30 @@
 	win2k.texi
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	doxyout \
+	footer.html \
+	gssapi.din \
+	hdb.din \
+	hcrypto.din \
+	header.html \
+	heimdal.css \
+	hx509.din \
 	krb5.din \
 	ntlm.din \
-	hx509.din \
-	hcrypto.din \
-	heimdal.css \
 	init-creds \
 	latin1.tex \
 	layman.asc \
 	doxytmpl.dxy \
+	wind.din \
 	vars.tin
=20
 CLEANFILES =3D \
+	hcrypto.dxy* \
+	hx509.dxy* \
+	hdb.dxy* \
+	gssapi.dxy* \
 	krb5.dxy* \
 	ntlm.dxy* \
-	hx509.dxy* \
-	hcrypto.dxy* \
+	wind.dxy* \
 	vars.texi*
-
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/Makefile.in
--- a/head/crypto/heimdal/doc/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22284 2007-12-13 20:39:37Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D doc
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 INFO_DEPS =3D $(srcdir)/heimdal.info $(srcdir)/hx509.info
@@ -109,55 +113,79 @@
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -181,10 +209,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -201,6 +230,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -216,31 +247,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -255,10 +300,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -299,32 +346,37 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 AUTOMAKE_OPTIONS =3D no-texinfo.tex
-MAKEINFOFLAGS =3D --no-split --css-include=3D$(srcdir)/heimdal.css
+MAKEINFOFLAGS =3D --css-include=3D$(srcdir)/heimdal.css
 TEXI2DVI =3D true # ARGH, make distcheck can't be disabled to not build dv=
ifiles
 info_TEXINFOS =3D heimdal.texi hx509.texi
 dxy_subst =3D sed -e 's,[@]srcdir[@],$(srcdir),g' \
@@ -334,9 +386,11 @@
 texi_subst =3D sed -e 's,[@]dbdir[@],$(localstatedir),g' \
 	-e 's,[@]PACKAGE_VERSION[@],$(PACKAGE_VERSION),g'
=20
+PROJECTS =3D hcrypto hdb hx509 gssapi krb5 ntlm wind=20
 heimdal_TEXINFOS =3D \
 	ack.texi \
 	apps.texi \
+	copyright.texi \
 	heimdal.texi \
 	install.texi \
 	intro.texi \
@@ -350,40 +404,50 @@
 	win2k.texi
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	doxyout \
+	footer.html \
+	gssapi.din \
+	hdb.din \
+	hcrypto.din \
+	header.html \
+	heimdal.css \
+	hx509.din \
 	krb5.din \
 	ntlm.din \
-	hx509.din \
-	hcrypto.din \
-	heimdal.css \
 	init-creds \
 	latin1.tex \
 	layman.asc \
 	doxytmpl.dxy \
+	wind.din \
 	vars.tin
=20
 CLEANFILES =3D \
+	hcrypto.dxy* \
+	hx509.dxy* \
+	hdb.dxy* \
+	gssapi.dxy* \
 	krb5.dxy* \
 	ntlm.dxy* \
-	hx509.dxy* \
-	hcrypto.dxy* \
+	wind.dxy* \
 	vars.texi*
=20
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .dvi .html =
.info .pdf .ps .texi
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .dvi .h=
tml .info .pdf .ps .texi
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps doc/Makef=
ile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps doc/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign doc/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -401,6 +465,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -410,7 +475,7 @@
=20
 .texi.info:
 	restore=3D: && backupdir=3D"$(am__leading_dot)am$$$$" && \
-	am__cwd=3D`pwd` && cd $(srcdir) && \
+	am__cwd=3D`pwd` && $(am__cd) $(srcdir) && \
 	rm -rf $$backupdir && mkdir $$backupdir && \
 	if ($(MAKEINFO) --version) >/dev/null 2>&1; then \
 	  for f in $@ $@-[0-9] $@-[0-9][0-9] $(@:.info=3D).i[0-9] $(@:.info=3D).i=
[0-9][0-9]; do \
@@ -422,10 +487,10 @@
 	 -o $@ $<; \
 	then \
 	  rc=3D0; \
-	  cd $(srcdir); \
+	  $(am__cd) $(srcdir); \
 	else \
 	  rc=3D$$?; \
-	  cd $(srcdir) && \
+	  $(am__cd) $(srcdir) && \
 	  $$restore $$backupdir/* `echo "./$@" | sed 's|[^/]*$$||'`; \
 	fi; \
 	rm -rf $$backupdir; exit $$rc
@@ -467,16 +532,18 @@
=20
 uninstall-dvi-am:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(DVIS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
+	@list=3D'$(DVIS)'; test -n "$(dvidir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
 	  echo " rm -f '$(DESTDIR)$(dvidir)/$$f'"; \
 	  rm -f "$(DESTDIR)$(dvidir)/$$f"; \
 	done
=20
 uninstall-html-am:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(HTMLS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
+	@list=3D'$(HTMLS)'; test -n "$(htmldir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
 	  echo " rm -rf '$(DESTDIR)$(htmldir)/$$f'"; \
 	  rm -rf "$(DESTDIR)$(htmldir)/$$f"; \
 	done
@@ -490,7 +557,8 @@
 	  for file in $$list; do \
 	    relfile=3D`echo "$$file" | sed 's|^.*/||'`; \
 	    echo " install-info --info-dir=3D'$(DESTDIR)$(infodir)' --remove '$(D=
ESTDIR)$(infodir)/$$relfile'"; \
-	    install-info --info-dir=3D"$(DESTDIR)$(infodir)" --remove "$(DESTDIR)=
$(infodir)/$$relfile"; \
+	    if install-info --info-dir=3D"$(DESTDIR)$(infodir)" --remove "$(DESTD=
IR)$(infodir)/$$relfile"; \
+	    then :; else test ! -f "$(DESTDIR)$(infodir)/$$relfile" || exit 1; fi=
; \
 	  done; \
 	else :; fi
 	@$(NORMAL_UNINSTALL)
@@ -506,16 +574,18 @@
=20
 uninstall-pdf-am:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(PDFS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
+	@list=3D'$(PDFS)'; test -n "$(pdfdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
 	  echo " rm -f '$(DESTDIR)$(pdfdir)/$$f'"; \
 	  rm -f "$(DESTDIR)$(pdfdir)/$$f"; \
 	done
=20
 uninstall-ps-am:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(PSS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
+	@list=3D'$(PSS)'; test -n "$(psdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
 	  echo " rm -f '$(DESTDIR)$(psdir)/$$f'"; \
 	  rm -f "$(DESTDIR)$(psdir)/$$f"; \
 	done
@@ -532,20 +602,25 @@
 	  for file in $$d/$$base $$d/$$base-[0-9] $$d/$$base-[0-9][0-9] $$d/$$bas=
e_i[0-9] $$d/$$base_i[0-9][0-9]; do \
 	    if test -f $$file; then \
 	      relfile=3D`expr "$$file" : "$$d/\(.*\)"`; \
-	      test -f $(distdir)/$$relfile || \
-		cp -p $$file $(distdir)/$$relfile; \
+	      test -f "$(distdir)/$$relfile" || \
+		cp -p $$file "$(distdir)/$$relfile"; \
 	    else :; fi; \
 	  done; \
 	done
=20
 mostlyclean-aminfo:
-	-rm -rf heimdal.aux heimdal.cp heimdal.cps heimdal.fn heimdal.fns heimdal=
.ky \
-	  heimdal.kys heimdal.log heimdal.pg heimdal.tmp heimdal.toc \
-	  heimdal.tp heimdal.tps heimdal.vr heimdal.vrs heimdal.dvi \
-	  heimdal.pdf heimdal.ps heimdal.html hx509.aux hx509.cp \
-	  hx509.cps hx509.fn hx509.fns hx509.ky hx509.kys hx509.log \
-	  hx509.pg hx509.tmp hx509.toc hx509.tp hx509.tps hx509.vr \
-	  hx509.vrs hx509.dvi hx509.pdf hx509.ps hx509.html
+	-rm -rf heimdal.aux heimdal.cp heimdal.cps heimdal.fn heimdal.fns \
+	  heimdal.ky heimdal.kys heimdal.log heimdal.pg heimdal.tmp \
+	  heimdal.toc heimdal.tp heimdal.tps heimdal.vr heimdal.vrs \
+	  hx509.aux hx509.cp hx509.cps hx509.fn hx509.fns hx509.ky \
+	  hx509.kys hx509.log hx509.pg hx509.tmp hx509.toc hx509.tp \
+	  hx509.tps hx509.vr hx509.vrs
+
+clean-aminfo:
+	-test -z "heimdal.dvi heimdal.pdf heimdal.ps heimdal.html hx509.dvi hx509=
.pdf \
+	  hx509.ps hx509.html" \
+	|| rm -rf heimdal.dvi heimdal.pdf heimdal.ps heimdal.html hx509.dvi hx509=
.pdf \
+	  hx509.ps hx509.html
=20
 maintainer-clean-aminfo:
 	@list=3D'$(INFO_DEPS)'; for i in $$list; do \
@@ -576,13 +651,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -618,13 +697,14 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
 	@echo "it deletes files that may require special tools to rebuild."
 clean: clean-am
=20
-clean-am: clean-generic clean-libtool mostlyclean-am
+clean-am: clean-aminfo clean-generic clean-libtool mostlyclean-am
=20
 distclean: distclean-am
 	-rm -f Makefile
@@ -645,47 +725,53 @@
 install-data-am: install-info-am
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
-
 install-dvi: install-dvi-am
=20
 install-dvi-am: $(DVIS)
 	@$(NORMAL_INSTALL)
 	test -z "$(dvidir)" || $(MKDIR_P) "$(DESTDIR)$(dvidir)"
-	@list=3D'$(DVIS)'; for p in $$list; do \
+	@list=3D'$(DVIS)'; test -n "$(dvidir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(INSTALL_DATA) '$$d$$p' '$(DESTDIR)$(dvidir)/$$f'"; \
-	  $(INSTALL_DATA) "$$d$$p" "$(DESTDIR)$(dvidir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(dvidir)'"; \
+	  $(INSTALL_DATA) $$files "$(DESTDIR)$(dvidir)" || exit $$?; \
 	done
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
 install-html-am: $(HTMLS)
 	@$(NORMAL_INSTALL)
 	test -z "$(htmldir)" || $(MKDIR_P) "$(DESTDIR)$(htmldir)"
-	@list=3D'$(HTMLS)'; for p in $$list; do \
+	@list=3D'$(HTMLS)'; list2=3D; test -n "$(htmldir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p" || test -d "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi=
; \
-	  f=3D$(am__strip_dir) \
+	  $(am__strip_dir) \
 	  if test -d "$$d$$p"; then \
 	    echo " $(MKDIR_P) '$(DESTDIR)$(htmldir)/$$f'"; \
 	    $(MKDIR_P) "$(DESTDIR)$(htmldir)/$$f" || exit 1; \
 	    echo " $(INSTALL_DATA) '$$d$$p'/* '$(DESTDIR)$(htmldir)/$$f'"; \
-	    $(INSTALL_DATA) "$$d$$p"/* "$(DESTDIR)$(htmldir)/$$f"; \
+	    $(INSTALL_DATA) "$$d$$p"/* "$(DESTDIR)$(htmldir)/$$f" || exit $$?; \
 	  else \
-	    echo " $(INSTALL_DATA) '$$d$$p' '$(DESTDIR)$(htmldir)/$$f'"; \
-	    $(INSTALL_DATA) "$$d$$p" "$(DESTDIR)$(htmldir)/$$f"; \
+	    list2=3D"$$list2 $$d$$p"; \
 	  fi; \
-	done
+	done; \
+	test -z "$$list2" || { echo "$$list2" | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmldir)'"; \
+	  $(INSTALL_DATA) $$files "$(DESTDIR)$(htmldir)" || exit $$?; \
+	done; }
 install-info: install-info-am
=20
 install-info-am: $(INFO_DEPS)
 	@$(NORMAL_INSTALL)
 	test -z "$(infodir)" || $(MKDIR_P) "$(DESTDIR)$(infodir)"
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`; \
-	list=3D'$(INFO_DEPS)'; \
+	list=3D'$(INFO_DEPS)'; test -n "$(infodir)" || list=3D; \
 	for file in $$list; do \
 	  case $$file in \
 	    $(srcdir)/*) file=3D`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
@@ -693,18 +779,19 @@
 	  if test -f $$file; then d=3D.; else d=3D$(srcdir); fi; \
 	  file_i=3D`echo "$$file" | sed 's|\.info$$||;s|$$|.i|'`; \
 	  for ifile in $$d/$$file $$d/$$file-[0-9] $$d/$$file-[0-9][0-9] \
-                       $$d/$$file_i[0-9] $$d/$$file_i[0-9][0-9] ; do \
+	               $$d/$$file_i[0-9] $$d/$$file_i[0-9][0-9] ; do \
 	    if test -f $$ifile; then \
-	      relfile=3D`echo "$$ifile" | sed 's|^.*/||'`; \
-	      echo " $(INSTALL_DATA) '$$ifile' '$(DESTDIR)$(infodir)/$$relfile'";=
 \
-	      $(INSTALL_DATA) "$$ifile" "$(DESTDIR)$(infodir)/$$relfile"; \
+	      echo "$$ifile"; \
 	    else : ; fi; \
 	  done; \
-	done
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(infodir)'"; \
+	  $(INSTALL_DATA) $$files "$(DESTDIR)$(infodir)" || exit $$?; done
 	@$(POST_INSTALL)
 	@if (install-info --version && \
 	     install-info --version 2>&1 | sed 1q | grep -i -v debian) >/dev/null=
 2>&1; then \
-	  list=3D'$(INFO_DEPS)'; \
+	  list=3D'$(INFO_DEPS)'; test -n "$(infodir)" || list=3D; \
 	  for file in $$list; do \
 	    relfile=3D`echo "$$file" | sed 's|^.*/||'`; \
 	    echo " install-info --info-dir=3D'$(DESTDIR)$(infodir)' '$(DESTDIR)$(=
infodir)/$$relfile'";\
@@ -718,23 +805,27 @@
 install-pdf-am: $(PDFS)
 	@$(NORMAL_INSTALL)
 	test -z "$(pdfdir)" || $(MKDIR_P) "$(DESTDIR)$(pdfdir)"
-	@list=3D'$(PDFS)'; for p in $$list; do \
+	@list=3D'$(PDFS)'; test -n "$(pdfdir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(INSTALL_DATA) '$$d$$p' '$(DESTDIR)$(pdfdir)/$$f'"; \
-	  $(INSTALL_DATA) "$$d$$p" "$(DESTDIR)$(pdfdir)/$$f"; \
-	done
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pdfdir)'"; \
+	  $(INSTALL_DATA) $$files "$(DESTDIR)$(pdfdir)" || exit $$?; done
 install-ps: install-ps-am
=20
 install-ps-am: $(PSS)
 	@$(NORMAL_INSTALL)
 	test -z "$(psdir)" || $(MKDIR_P) "$(DESTDIR)$(psdir)"
-	@list=3D'$(PSS)'; for p in $$list; do \
+	@list=3D'$(PSS)'; test -n "$(psdir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(INSTALL_DATA) '$$d$$p' '$(DESTDIR)$(psdir)/$$f'"; \
-	  $(INSTALL_DATA) "$$d$$p" "$(DESTDIR)$(psdir)/$$f"; \
-	done
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(psdir)'"; \
+	  $(INSTALL_DATA) $$files "$(DESTDIR)$(psdir)" || exit $$?; done
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
@@ -759,20 +850,19 @@
 	uninstall-pdf-am uninstall-ps-am
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: all all-am all-local check check-am check-local clean \
-	clean-generic clean-libtool dist-hook dist-info distclean \
-	distclean-generic distclean-libtool distdir dvi dvi-am html \
-	html-am info info-am install install-am install-data \
-	install-data-am install-data-hook install-dvi install-dvi-am \
-	install-exec install-exec-am install-exec-hook install-html \
-	install-html-am install-info install-info-am install-man \
-	install-pdf install-pdf-am install-ps install-ps-am \
-	install-strip installcheck installcheck-am installdirs \
-	maintainer-clean maintainer-clean-aminfo \
+	clean-aminfo clean-generic clean-libtool dist-hook dist-info \
+	distclean distclean-generic distclean-libtool distdir dvi \
+	dvi-am html html-am info info-am install install-am \
+	install-data install-data-am install-data-hook install-dvi \
+	install-dvi-am install-exec install-exec-am install-exec-hook \
+	install-html install-html-am install-info install-info-am \
+	install-man install-pdf install-pdf-am install-ps \
+	install-ps-am install-strip installcheck installcheck-am \
+	installdirs maintainer-clean maintainer-clean-aminfo \
 	maintainer-clean-generic mostlyclean mostlyclean-aminfo \
 	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
 	uninstall uninstall-am uninstall-dvi-am uninstall-hook \
@@ -848,6 +938,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -933,7 +1026,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -947,6 +1040,26 @@
 	  fi ; \
 	done
=20
+hcrypto.dxy: hcrypto.din Makefile
+	$(dxy_subst) < $(srcdir)/hcrypto.din > hcrypto.dxy.tmp
+	chmod +x hcrypto.dxy.tmp
+	mv hcrypto.dxy.tmp hcrypto.dxy
+
+hdb.dxy: hdb.din Makefile
+	$(dxy_subst) < $(srcdir)/hdb.din > hdb.dxy.tmp
+	chmod +x hdb.dxy.tmp
+	mv hdb.dxy.tmp hdb.dxy
+
+hx509.dxy: hx509.din Makefile
+	$(dxy_subst) < $(srcdir)/hx509.din > hx509.dxy.tmp
+	chmod +x hx509.dxy.tmp
+	mv hx509.dxy.tmp hx509.dxy
+
+gssapi.dxy: gssapi.din Makefile
+	$(dxy_subst) < $(srcdir)/gssapi.din > gssapi.dxy.tmp
+	chmod +x gssapi.dxy.tmp
+	mv gssapi.dxy.tmp gssapi.dxy
+
 krb5.dxy: krb5.din Makefile
 	$(dxy_subst) < $(srcdir)/krb5.din > krb5.dxy.tmp
 	chmod +x krb5.dxy.tmp
@@ -957,26 +1070,54 @@
 	chmod +x ntlm.dxy.tmp
 	mv ntlm.dxy.tmp ntlm.dxy
=20
-hx509.dxy: hx509.din Makefile
-	$(dxy_subst) < $(srcdir)/hx509.din > hx509.dxy.tmp
-	chmod +x hx509.dxy.tmp
-	mv hx509.dxy.tmp hx509.dxy
-
-hcrypto.dxy: hcrypto.din Makefile
-	$(dxy_subst) < $(srcdir)/hcrypto.din > hcrypto.dxy.tmp
-	chmod +x hcrypto.dxy.tmp
-	mv hcrypto.dxy.tmp hcrypto.dxy
+wind.dxy: wind.din Makefile
+	$(dxy_subst) < $(srcdir)/wind.din > wind.dxy.tmp
+	chmod +x wind.dxy.tmp
+	mv wind.dxy.tmp wind.dxy
=20
 vars.texi: vars.tin Makefile
 	$(texi_subst) < $(srcdir)/vars.tin > vars.texi.tmp
 	chmod +x vars.texi.tmp
 	mv vars.texi.tmp vars.texi
=20
-doxygen: krb5.dxy ntlm.dxy hx509.dxy hcrypto.dxy
-	doxygen krb5.dxy
-	doxygen ntlm.dxy
-	doxygen hx509.dxy
-	doxygen hcrypto.dxy
+doxyout doxygen: hdb.dxy hx509.dxy hcrypto.dxy gssapi.dxy krb5.dxy ntlm.dx=
y wind.dxy
+	@find $(srcdir)/doxyout -type d ! -perm -200 -exec chmod u+w {} ';' ; \
+	rm -rf $(srcdir)/doxyout ; \
+	mkdir $(srcdir)/doxyout ; \
+	for a in $(PROJECTS) ; do \
+		echo $$a ; \
+		doxygen $$a.dxy; \
+		(cd $(srcdir)/doxyout && find $$a/man -type f > $$a/manpages ) ; \
+	done
+
+install-data-hook: install-doxygen-manpage
+uninstall-hook: uninstall-doxygen-manpage
+dist-hook: doxygen
+
+install-doxygen-manpage:
+	for a in $(PROJECTS) ; do \
+		f=3D"$(srcdir)/doxyout/$$a/manpages" ; \
+		test -f $$f || continue ; \
+		echo "install $$a manual pages $$(wc -l < $$f)" ; \
+		while read x ; do \
+			section=3D`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \
+			$(mkinstalldirs) "$(DESTDIR)$(mandir)/man$$section" ; \
+			$(INSTALL_DATA) $(srcdir)/doxyout/$$x "$(DESTDIR)$(mandir)/man$$section=
" ; \
+		done < $$f ; \
+	done ; exit 0
+
+uninstall-doxygen-manpage:
+	@for a in $(PROJECTS) ; do \
+		f=3D"$(srcdir)/doxyout/$$a/manpages" ; \
+		test -f $$f || continue ; \
+		echo "removing $$a manual pages" ; \
+		while read x ; do \
+			section=3D`echo "$$x" | sed 's/.*\.\([0-9]\)/\1/'` ; \
+			base=3D`basename $$x` ; \
+			rm "$(DESTDIR)$(mandir)/man$$section/$$base" ; \
+		done < $$f ; \
+	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/ack.texi
--- a/head/crypto/heimdal/doc/ack.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/ack.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
- at c $Id: ack.texi 21228 2007-06-20 10:18:03Z lha $
+ at c $Id$
=20
- at node  Acknowledgments, , Migration, Top
+ at node  Acknowledgments, Copyrights and Licenses, Migration, Top
 @comment  node-name,  next,  previous,  up
 @appendix Acknowledgments
=20
@@ -36,36 +36,88 @@
=20
 Bugfixes, documentation, encouragement, and code has been contributed by:
 @table @asis
- at item Alexander Bostr=F6m
- at item Andreaw Bartlett
- at item Bj=F6rn Sandell
+ at item Alexander Bostr=C3=B6m
+ at item Allan McRae
+ at item Andrew Bartlett
+ at item Andrew Cobaugh
+ at item Andrew Tridge
+ at item Anton Lundin
+ at item Asanka Herath
+ at item Bj=C3=B6rn Gr=C3=B6nvall
+ at item Bj=C3=B6rn Sandell
+ at item Bj=C3=B6rn Schl=C3=B6gl
 @item Brandon S. Allbery KF8NH
 @item Brian A May
+ at item Buck Huppmann
+ at item Cacdric Schieli
 @item Chaskiel M Grundman
+ at item Christos Zoulas
 @item Cizzi Storm
 @item Daniel Kouril
 @item David Love
+ at item David Markey
+ at item David R Boldt
 @item Derrick J Brashear
+ at item Donald Norwood
 @item Douglas E Engert
 @item Frank van der Linden
+ at item Gabor Gombas
+ at item Guido G=C3=BCnther
+ at item Guillaume Rousse
+ at item Harald Barth
+ at item Ingo Schwarze
+ at item Jacques A. Vidrine
+ at item Jaideep Padhye
+ at item Jan Rekorajski
 @item Jason McIntyre
- at item Johan Ihr=E9n
+ at item Jeffrey Altman
+ at item Jelmer Vernooij
+ at item Joerg Pulz
+ at item Johan Danielsson
+ at item Johan Gadsj=C3=B6
+ at item Johan Ihr=C3=A9n
+ at item John Center
 @item Jun-ichiro itojun Hagino
+ at item KAMADA Ken'ichi
+ at item Kamen Mazdrashki
+ at item Karolin Seeger
 @item Ken Hornstein
+ at item Love H=C3=B6rnquist =C3=85strand
+ at item Luke Howard
 @item Magnus Ahltorp
+ at item Magnus Holmberg
 @item Marc Horowitz
 @item Mario Strasser
 @item Mark Eichin
+ at item Martin von Gagern
+ at item Matthias Dieter Walln=C3=B6fer
+ at item Matthieu Patou
 @item Mattias Amnefelt
 @item Michael B Allen
 @item Michael Fromberger
 @item Michal Vocu
+ at item Milosz Kmieciak
 @item Miroslav Ruda
+ at item Mustafa A. Hashmi
+ at item Nicolas Williams
+ at item Patrik Lundin
 @item Petr Holub
 @item Phil Fisher
 @item Rafal Malinowski
+ at item Ragnar Sundblad
+ at item Rainer Toebbicke
 @item Richard Nyberg
- at item =C5ke Sandgren=20
+ at item Roland C. Dowdeswell
+ at item Roman Divacky
+ at item Russ Allbery
+ at item Sho Hosoda, =E7=B4=B0=E7=94=B0 =E5=B0=86
+ at item Simon Wilkinson
+ at item Stefan Metzmacher
+ at item Ted Percival
+ at item Tom Payerle
+ at item Victor Guerra
+ at item Zeqing Xia
+ at item =C3=85ke Sandgren=20
 @item and we hope that those not mentioned here will forgive us.
 @end table
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/apps.texi
--- a/head/crypto/heimdal/doc/apps.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/apps.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
- at c $Id: apps.texi 22071 2007-11-14 20:04:50Z lha $
+ at c $Id$
=20
 @node Applications, Things in search for a better place, Setting up a real=
m, Top
=20
@@ -174,6 +174,32 @@
 @url{http://www.openafs.org/} and Arla
 @url{http://www.stacken.kth.se/projekt/arla/}.
=20
+ at subsection kafs and afslog
+ at cindex afslog
+
+ at manpage{afslog,1} will obtains AFS tokens for a number of cells. What cel=
ls to get
+tokens for can either be specified as an explicit list, as file paths to
+get tokens for, or be left unspecified, in which case will use whatever
+magic @manpage{kafs,3} decides upon.
+
+If not told what cell to get credentials for, @manpage{kafs,3} will
+search for the files ThisCell and TheseCells in the locations
+specified in @manpage{kafs,3} and try to get tokens for these cells
+and the cells specified in $HOME/.TheseCells.
+
+More usefully it will look at and ~/.TheseCells in your home directory
+and for each line which is a cell get afs token for these cells.
+
+The TheseCells file defines the the cells to which applications on the
+local client machine should try to aquire tokens for. It must reside in
+the directories searched by @manpage{kafs,3} on every AFS client machine.
+
+The file is in ASCII format and contains one character string, the cell
+name, per line. Cell names are case sensitive, but most cell names
+are lower case.
+
+See manpage for @manpage{kafs,3} for search locations of ThisCell and Thes=
eCells.
+
 @subsection How to get a KeyFile
=20
 @file{ktutil -k AFSKEYFILE:KeyFile get afs@@MY.REALM}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/doxytmpl.dxy
--- a/head/crypto/heimdal/doc/doxytmpl.dxy	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/doxytmpl.dxy	Tue Apr 17 11:51:51 2012 +0300
@@ -112,7 +112,6 @@
 EXCLUDE_SYMLINKS       =3D NO
 EXCLUDE_PATTERNS       =3D */.svn
 EXCLUDE_SYMBOLS        =3D=20
-EXAMPLE_PATH           =3D=20
 EXAMPLE_PATTERNS       =3D *
 EXAMPLE_RECURSIVE      =3D NO
 IMAGE_PATH             =3D=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/hcrypto.din
--- a/head/crypto/heimdal/doc/hcrypto.din	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/hcrypto.din	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,9 @@
=20
 PROJECT_NAME           =3D "Heimdal crypto library"
 PROJECT_NUMBER         =3D @PACKAGE_VERSION@
-OUTPUT_DIRECTORY       =3D @objdir@/hcrypto
+OUTPUT_DIRECTORY       =3D @srcdir@/doxyout/hcrypto
 INPUT                  =3D @srcdir@/../lib/hcrypto
+EXAMPLE_PATH	       =3D @srcdir@/../lib/hcrypto
=20
 WARN_IF_UNDOCUMENTED   =3D YES
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/heimdal.texi
--- a/head/crypto/heimdal/doc/heimdal.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/heimdal.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 \input texinfo @c -*- texinfo -*-
 @c %**start of header
- at c $Id: heimdal.texi 22191 2007-12-06 17:26:30Z lha $
+ at c $Id$
 @setfilename heimdal.info
 @settitle HEIMDAL
 @iftex
@@ -16,7 +16,6 @@
=20
 @include vars.texi
=20
- at set UPDATED $Date: 2007-12-06 09:26:30 -0800 (Tor, 06 Dec 2007) $
 @set VERSION @value{PACKAGE_VERSION}
 @set EDITION 1.0
=20
@@ -32,227 +31,11 @@
 @title Heimdal
 @subtitle Kerberos 5 from KTH
 @subtitle Edition @value{EDITION}, for version @value{VERSION}
- at subtitle 2007
+ at subtitle 2008
 @author Johan Danielsson
- at author Love H=F6rnquist =C5strand
+ at author Love H=C3=B6rnquist =C3=85strand
 @author Assar Westerlund
- at author last updated @value{UPDATED}
=20
- at def@copynext{@vskip 20pt plus 1fil at penalty-1000}
- at def@copyrightstart{}
- at def@copyrightend{}
- at page
- at copyrightstart
-Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan=20
-(Royal Institute of Technology, Stockholm, Sweden).
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-
-3. Neither the name of the Institute nor the names of its contributors
-   may be used to endorse or promote products derived from this software
-   without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGE.
-
- at copynext
-
-Copyright (C) 1990 by the Massachusetts Institute of Technology
-
-Export of this software from the United States of America may
-require a specific license from the United States Government.
-It is the responsibility of any person or organization contemplating
-export to obtain such a license before exporting.
-
-WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
-distribute this software and its documentation for any purpose and
-without fee is hereby granted, provided that the above copyright
-notice appear in all copies and that both that copyright notice and
-this permission notice appear in supporting documentation, and that
-the name of M.I.T. not be used in advertising or publicity pertaining
-to distribution of the software without specific, written prior
-permission.  M.I.T. makes no representations about the suitability of
-this software for any purpose.  It is provided "as is" without express
-or implied warranty.
-
- at copynext
-
-Copyright (c) 1988, 1990, 1993
-     The Regents of the University of California.  All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-
-3. Neither the name of the University nor the names of its contributors
-   may be used to endorse or promote products derived from this software
-   without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGE.
-
- at copynext
-
-Copyright 1992 Simmule Turner and Rich Salz.  All rights reserved.=20
-
-This software is not subject to any license of the American Telephone=20
-and Telegraph Company or of the Regents of the University of California.=20
-
-Permission is granted to anyone to use this software for any purpose on
-any computer system, and to alter it and redistribute it freely, subject
-to the following restrictions:
-
-1. The authors are not responsible for the consequences of use of this
-   software, no matter how awful, even if they arise from flaws in it.
-
-2. The origin of this software must not be misrepresented, either by
-   explicit claim or by omission.  Since few users ever read sources,
-   credits must appear in the documentation.
-
-3. Altered versions must be plainly marked as such, and must not be
-   misrepresented as being the original software.  Since few users
-   ever read sources, credits must appear in the documentation.
-
-4. This notice may not be removed or altered.
-
- at copynext
-
-IMath is Copyright 2002-2005 Michael J. Fromberger
-You may use it subject to the following Licensing Terms:
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
- at copynext
-
-Copyright (c) 2005 Doug Rabson
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGE.
-
- at copynext
-
-Copyright (c) 2005 Marko Kreen
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
-       notice, this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright
-       notice, this list of conditions and the following disclaimer in the
-       documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED.	IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGE.
-
- at copynext
-
-Copyright (c) 2006,2007
-NTT (Nippon Telegraph and Telephone Corporation) . All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
-  notice, this list of conditions and the following disclaimer as
-  the first lines of this file unmodified.
-2. Redistributions in binary form must reproduce the above copyright
-  notice, this list of conditions and the following disclaimer in the
-  documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY NTT ``AS IS'' AND ANY EXPRESS OR
-IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-IN NO EVENT SHALL NTT BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
- at copyrightend
 @end titlepage
=20
 @macro manpage{man, section}
@@ -276,8 +59,7 @@
 @top Heimdal
 @end ifnottex
=20
-This manual is last updated @value{UPDATED} for version
- at value{VERSION} of Heimdal.
+This manual for version @value{VERSION} of Heimdal.
=20
 @menu
 * Introduction::               =20
@@ -287,10 +69,11 @@
 * Applications::               =20
 * Things in search for a better place:: =20
 * Kerberos 4 issues::          =20
-* Windows 2000 compatability:: =20
+* Windows compatibility:: =20
 * Programming with Kerberos::  =20
 * Migration::                  =20
 * Acknowledgments::            =20
+* Copyrights and Licenses::
=20
 @detailmenu
  --- The Detailed Node Listing ---
@@ -301,13 +84,13 @@
 * Creating the database::      =20
 * Modifying the database::     =20
 * keytabs::                    =20
-* Serving Kerberos 4/524/kaserver:: =20
 * Remote administration::      =20
 * Password changing::          =20
 * Testing clients and servers:: =20
 * Slave Servers::              =20
 * Incremental propagation::    =20
 * Encryption types and salting::                    =20
+* Credential cache server - KCM::
 * Cross realm::                =20
 * Transit policy::             =20
 * Setting up DNS::             =20
@@ -329,26 +112,19 @@
=20
 * Principal conversion issues:: =20
 * Converting a version 4 database:: =20
-* kaserver::                   =20
=20
-Windows 2000 compatability
+Windows compatibility
=20
-* Configuring Windows 2000 to use a Heimdal KDC:: =20
-* Inter-Realm keys (trust) between Windows 2000 and a Heimdal KDC:: =20
+* Configuring Windows to use a Heimdal KDC:: =20
+* Inter-Realm keys (trust) between Windows and a Heimdal KDC:: =20
 * Create account mappings::    =20
 * Encryption types::           =20
 * Authorisation data::         =20
 * Quirks of Windows 2000 KDC:: =20
-* Useful links when reading about the Windows 2000:: =20
+* Useful links when reading about the Windows:: =20
=20
 Programming with Kerberos
=20
-* Kerberos 5 API Overview::    =20
-* Walkthrough of a sample Kerberos 5 client:: =20
-* Validating a password in a server application:: =20
-* API differences to MIT Kerberos:: =20
-* File formats::
-
 @end detailmenu
 @end menu
=20
@@ -363,6 +139,7 @@
 @include programming.texi
 @include migration.texi
 @include ack.texi
+ at include copyright.texi
=20
 @c @shortcontents
 @contents
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/hx509.din
--- a/head/crypto/heimdal/doc/hx509.din	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/hx509.din	Tue Apr 17 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
=20
 PROJECT_NAME           =3D Heimdal x509 library
 PROJECT_NUMBER         =3D @PACKAGE_VERSION@
-OUTPUT_DIRECTORY       =3D @objdir@/hx509
+OUTPUT_DIRECTORY       =3D @srcdir@/doxyout/hx509
 INPUT                  =3D @srcdir@/../lib/hx509
=20
 WARN_IF_UNDOCUMENTED   =3D YES
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/hx509.texi
--- a/head/crypto/heimdal/doc/hx509.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/hx509.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 \input texinfo @c -*- texinfo -*-
 @c %**start of header
- at c $Id: hx509.texi 22071 2007-11-14 20:04:50Z lha $
+ at c $Id$
 @setfilename hx509.info
 @settitle HX509
 @iftex
@@ -14,14 +14,15 @@
 @syncodeindex pg cp
 @c %**end of header
=20
- at set UPDATED $Date: 2007-11-14 12:04:50 -0800 (Ons, 14 Nov 2007) $
- at set VERSION 1.0
+ at include vars.texi
+
+ at set VERSION @value{PACKAGE_VERSION}
 @set EDITION 1.0
=20
 @ifinfo
 @dircategory Security
 @direntry
-* hx509: (hx509).           The X.509 distribution from KTH
+* hx509: (hx509).               The X.509 distribution from KTH
 @end direntry
 @end ifinfo
=20
@@ -30,16 +31,15 @@
 @title HX509
 @subtitle X.509 distribution from KTH
 @subtitle Edition @value{EDITION}, for version @value{VERSION}
- at subtitle 2007
- at author Love H=F6rnquist =C5strand
- at author last updated @value{UPDATED}
+ at subtitle 2008
+ at author Love H=C3=B6rnquist =C3=85strand
=20
- at def@copynext{@vskip 20pt plus 1fil at penalty-1000}
+ at def@copynext{@vskip 20pt plus 1fil}
 @def at copyrightstart{}
 @def at copyrightend{}
 @page
 @copyrightstart
-Copyright (c) 1994-2007 Kungliga Tekniska H=F6gskolan
+Copyright (c) 1994-2008 Kungliga Tekniska H=C3=B6gskolan
 (Royal Institute of Technology, Stockholm, Sweden).
 All rights reserved.
=20
@@ -72,26 +72,6 @@
=20
 @copynext
=20
-Copyright (C) 1990 by the Massachusetts Institute of Technology
-
-Export of this software from the United States of America may
-require a specific license from the United States Government.
-It is the responsibility of any person or organization contemplating
-export to obtain such a license before exporting.
-
-WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
-distribute this software and its documentation for any purpose and
-without fee is hereby granted, provided that the above copyright
-notice appear in all copies and that both that copyright notice and
-this permission notice appear in supporting documentation, and that
-the name of M.I.T. not be used in advertising or publicity pertaining
-to distribution of the software without specific, written prior
-permission.  M.I.T. makes no representations about the suitability of
-this software for any purpose.  It is provided "as is" without express
-or implied warranty.
-
- at copynext
-
 Copyright (c) 1988, 1990, 1993
      The Regents of the University of California.  All rights reserved.
=20
@@ -194,14 +174,15 @@
 @top Heimdal
 @end ifnottex
=20
-This manual is last updated @value{UPDATED} for version
- at value{VERSION} of hx509.
+This manual is for version @value{VERSION} of hx509.
=20
 @menu
 * Introduction::
 * What is X.509 ?::
 * Setting up a CA::
 * CMS signing and encryption::
+* Certificate matching::
+* Software PKCS 11 module::
=20
 @detailmenu
  --- The Detailed Node Listing ---
@@ -222,38 +203,69 @@
=20
 * CMS background::
=20
+Certificate matching
+
+* Matching syntax::
+
+Software PKCS 11 module
+
+* How to use the PKCS11 module::
+
 @end detailmenu
 @end menu
=20
 @node Introduction, What is X.509 ?, Top, Top
 @chapter Introduction
=20
-hx509 is a somewhat complete X.509 stack that can handle CMS messages
-(crypto system used in S/MIME and Kerberos PK-INIT) and basic
-certificate processing tasks, path construction, path validation, OCSP
-and CRL validation, PKCS10 message construction, CMS Encrypted (shared
-secret encrypted), CMS SignedData (certificate signed), and CMS
-EnvelopedData (certificate encrypted).
+The goals of a PKI infrastructure (as defined in=20
+<a href=3D"http://www.ietf.org/rfc/rfc3280.txt">RFC 3280</a>) is to meet=20
+ at emph{the needs of deterministic, automated identification, authentication=
, access control, and authorization}.
=20
-hx509 can use PKCS11 tokens, PKCS12 files, PEM files, DER encoded files.
+
+The administrator should be aware of certain terminologies as explained by=
 the aforementioned
+RFC before attemping to put in place a PKI infrastructure. Briefly, these =
are:=20
+
+ at itemize @bullet
+ at item CA
+Certificate Authority
+ at item RA
+Registration Authority, i.e., an optional system to which a CA delegates c=
ertain management functions.
+ at item CRL Issuer
+An optional system to which a CA delegates the publication of certificate =
revocation lists.
+ at item Repository
+A system or collection of distributed systems that stores certificates and=
 CRLs=20
+and serves as a means of distributing these certificates and CRLs to end e=
ntities
+ at end itemize
+
+hx509 (Heimdal x509 support) is a near complete X.509 stack that can
+handle CMS messages (crypto system used in S/MIME and Kerberos PK-INIT)
+and basic certificate processing tasks, path construction, path
+validation, OCSP and CRL validation, PKCS10 message construction, CMS
+Encrypted (shared secret encrypted), CMS SignedData (certificate
+signed), and CMS EnvelopedData (certificate encrypted).
+
+hx509 can use PKCS11 tokens, PKCS12 files, PEM files, and/or DER encoded
+files.
=20
 @node What is X.509 ?, Setting up a CA, Introduction, Top
 @chapter What is X.509, PKIX, PKCS7 and CMS ?=20
=20
-X.509 is from the beginning created by CCITT (later ITU) for the X.500
-directory service. But today when people are talking about X.509 they
-are commonly referring to IETF's PKIX Certificate and CRL Profile of the
-X.509 v3 certificate standard, as specified in RFC 3280.
+X.509 was created by CCITT (later ITU) for the X.500 directory
+service. Today, X.509 discussions and implementations commonly reference
+the IETF's PKIX Certificate and CRL Profile of the X.509 v3 certificate
+standard, as specified in RFC 3280.
=20
-ITU continues to develop the X.509 standard together in a complicated
-dance with IETF.
+ITU continues to develop the X.509 standard together with the IETF in a=20
+rather complicated dance.
=20
-X.509 is public key based security system that have associated data
-stored within a so called certificate. From the beginning X.509 was a
-strict hierarchical system with one root. This didn't not work so over
-time X.509 got support for multiple policy roots, bridges, and mesh
-solutions. You can even use it as a peer to peer system, but this is not
-very common.
+X.509 is a public key based security system that has associated data
+stored within a so called certificate. Initially, X.509 was a strict
+hierarchical system with one root. However, ever evolving requiments and
+technology advancements saw the inclusion of multiple policy roots,
+bridges and mesh solutions.
+
+x.509 can also be used as a peer to peer system, though often seen as a
+common scenario.
=20
 @section Type of certificates
=20
@@ -263,36 +275,36 @@
=20
 @item Trust anchors
=20
-Trust anchors are strictly not certificate, but commonly stored in
-certificate since they are easier to handle then. Trust anchor are the
-keys that you trust to validate other certificate. This is done by
-building a path from the certificate you wan to validate to to any of
-the trust anchors you have.
+Trust anchors are strictly not certificates, but commonly stored in a
+certificate format as they become easier to manage. Trust anchors are
+the keys that an end entity would trust to validate other certificates.
+This is done by building a path from the certificate you want to
+validate to to any of the trust anchors you have.
=20
 @item End Entity (EE) certificates
=20
-End entity certificates is the most common type of certificate. End
-entity certificates can't issue certificate them-self and is used to
-authenticate and authorize user and services.
+End entity certificates are the most common types of certificates. End
+entity certificates cannot issue (sign) certificate themselves and are gen=
erally
+used to authenticate and authorize users and services.
=20
 @item Certification Authority (CA) certificates
=20
-Certificate authority are certificates that have the right to issue
-other certificate, they may be End entity certificates or Certificate
-Authority certificates. There is no limit to how many certificates a CA
+Certificate authority certificates have the right to issue additional
+certificates (be it sub-ordinate CA certificates to build an trust anchors
+or end entity certificates). There is no limit to how many certificates a =
CA
 may issue, but there might other restrictions, like the maximum path
 depth.
=20
 @item Proxy certificates
=20
-Remember that End Entity can't issue certificates by them own, it's not
-really true. There there is an extension called proxy certificates,
-defined in RFC3820, that allows certificates to be issued by end entity
-certificates. The service that receives the proxy certificates must have
-explicitly turned on support for proxy certificates, so their use is
-somewhat limited.
+Remember the statement "End Entity certificates cannot issue
+certificates"?  Well that statement is not entirely true. There is an
+extension called proxy certificates defined in RFC3820, that allows
+certificates to be issued by end entity certificates. The service that
+receives the proxy certificates must have explicitly turned on support
+for proxy certificates, so their use is somewhat limited.
=20
-Proxy certificates can be limited by policy stored in the certificate to
+Proxy certificates can be limited by policies stored in the certificate to
 what they can be used for. This allows users to delegate the proxy
 certificate to services (by sending over the certificate and private
 key) so the service can access services on behalf of the user.
@@ -302,59 +314,52 @@
 much, so the user creates a proxy certificate with the policy that it
 can only be used to access files related to this print job, creates the
 print job description and send both the description and proxy
-certificate with key over to print service. Later at night will the
-print service, without the help of the user, access the files for the
-the print job using the proxy certificate and print the job. Because of
-the policy (limitation) in the proxy certificate, it can't be used for
-any other purposes.
+certificate with key over to print service. Later at night when the
+print service initializes (without any user intervention), access to the f=
iles=20
+for the print job is granted via the proxy certificate. As a result of (in=
-place)=20
+policy limitations, the certificate cannot be used for any other purposes.
=20
 @end itemize
=20
 @section Building a path
=20
-Before validating a path the path must be constructed. Given a
-certificate (EE, CA, Proxy, or any other type), the path construction
-algorithm will try to find a path to one of the trust anchors.
+Before validating a certificate path (or chain), the path needs to be
+constructed.  Given a certificate (EE, CA, Proxy, or any other type),
+the path construction algorithm will try to find a path to one of the
+trust anchors.
=20
-It start with looking at whom issued the certificate, by name or Key
-Identifier, and tries to find that certificate while at the same time
-evaluates the policy.
+The process starts by looking at the issuing CA of the certificate, by
+Name or Key Identifier, and tries to find that certificate while at the
+same time evaluting any policies in-place.
=20
 @node Setting up a CA, Creating a CA certificate, What is X.509 ?, Top
 @chapter Setting up a CA
=20
-Do not let this chapter scare you off, it's just to give you an idea how
-to complicated setting up a CA can be. If you are just playing around,
-skip all this and go to the next chapter, @pxref{Creating a CA
-certificate}.
+Do not let information overload scare you off! If you are simply testing
+or getting started with a PKI infrastructure, skip all this and go to
+the next chapter (see: @pxref{Creating a CA certificate}).
=20
 Creating a CA certificate should be more the just creating a
-certificate, there is the policy of the CA. If it's just you and your
-friend that is playing around then it probably doesn't matter what the
-policy is. But then it comes to trust in an organisation, it will
-probably matter more whom your users and sysadmins will find it
-acceptable to trust.
+certificate, CA's should define a policy. Again, if you are simply
+testing a PKI, policies do not matter so much. However, when it comes to
+trust in an organisation, it will probably matter more whom your users
+and sysadmins will find it acceptable to trust.
=20
-At the same time, try to keep thing simple, it's not very hard to run a
-Certificate authority and the process to get new certificates should
-simple.
+At the same time, try to keep things simple, it's not very hard to run a
+Certificate authority and the process to get new certificates should be si=
mple.
=20
-Fill all this in later.
+You may find it helpful to answer the following policy questions for
+your organization at a later stage:
=20
-How do you trust your CA.
-
-What is the CA responsibility.
-
-Review of CA activity.
-
-How much process should it be to issue certificate.
-
-Who is allowed to issue certificates.
-
-Who is allowed to requests certificates.
-
-How to handle certificate revocation, issuing CRLs and maintain OCSP
-services.
+ at itemize @bullet
+ at item How do you trust your CA.
+ at item What is the CA responsibility.
+ at item Review of CA activity.
+ at item How much process should it be to issue certificate.
+ at item Who is allowed to issue certificates.
+ at item Who is allowed to requests certificates.
+ at item How to handle certificate revocation, issuing CRLs and maintain OCSP=
 services.
+ at end itemize
=20
 @node Creating a CA certificate, Issuing certificates, Setting up a CA, Top
 @section Creating a CA certificate
@@ -365,10 +370,10 @@
 @subsection Lifetime CA certificate
=20
 You probably want to create a CA certificate with a long lifetime, 10
-years at the shortest. This because you don't want to push out the
-certificate (as a trust anchor) to all you users once again when the old
-one just expired. A trust anchor can't really expire, but not all
-software works that way.
+years at the very minimum. This is because you don't want to push out the
+certificate (as a trust anchor) to all you users again when the old
+CA certificate expires. Although a trust anchor can't really expire, not a=
ll
+software works in accordance with published standards.
=20
 Keep in mind the security requirements might be different 10-20 years
 into the future. For example, SHA1 is going to be withdrawn in 2010, so
@@ -377,7 +382,7 @@
=20
 @subsection Create a CA certificate
=20
-This command below will create a CA certificate in the file ca.pem.
+This command below can be used to generate a self-signed CA certificate.
=20
 @example
 hxtool issue-certificate \
@@ -389,14 +394,14 @@
     --certificate=3D"FILE:ca.pem"
 @end example
=20
- at subsection Extending lifetime of a CA certificate
+ at subsection Extending the lifetime of a CA certificate
=20
 You just realised that your CA certificate is going to expire soon and
-that you need replace it with something else, the easiest way to do that
-is to extend the lifetime of your CA certificate.
+that you need replace it with a new CA. The easiest way to do that
+is to extend the lifetime of your existing CA certificate.
=20
-The example below will extend the CA certificate 10 years into the
-future. You should compare this new certificate if it contains all the
+The example below will extend the CA certificate's lifetime by 10 years.=20
+You should compare this new certificate if it contains all the
 special tweaks as the old certificate had.
=20
 @example
@@ -412,7 +417,7 @@
=20
 @subsection Subordinate CA
=20
-This example create a new subordinate certificate authority.
+This example below creates a new subordinate certificate authority.
=20
 @example
 hxtool issue-certificate \
@@ -428,17 +433,34 @@
 @section Issuing certificates
=20
 First you'll create a CA certificate, after that you have to deal with
-your users and servers and issue certificate to them.
+your users and servers and issue certificates to them.
=20
-CA can generate the key for the user.
+ at c I think this section needs a bit of clarity. Can I add a separate
+ at c section which explains CSRs as well?
=20
-Can receive PKCS10 certificate requests from the users. PKCS10 is a
-request for a certificate. The user can specified what DN the user wants
-and what public key. To prove the user have the key, the whole request
-is signed by the private key of the user.
+
+ at itemize @bullet
+
+ at item Do all the work themself
+
+Generate the key for the user. This has the problme that the the CA
+knows the private key of the user. For a paranoid user this might leave
+feeling of disconfort.
+
+ at item Have the user do part of the work
+
+Receive PKCS10 certificate requests fromusers. PKCS10 is a request for a
+certificate.  The user may specify what DN they want as well as provide
+a certificate signing request (CSR).  To prove the user have the key,
+the whole request is signed by the private key of the user.
+
+ at end itemize
=20
 @subsection Name space management
=20
+ at c The explanation given below is slightly unclear. I will re-read the
+ at c RFC and document accordingly
+
 What people might want to see.
=20
 Re-issue certificates just because people moved within the organization.
@@ -449,22 +471,43 @@
=20
 @subsection Certificate Revocation, CRL and OCSP
=20
-Sonetimes people loose smartcard or computers and certificates have to
-be make not valid any more, this is called revoking certificates. There
-are two main protocols for doing this Certificate Revocations Lists
-(CRL) and Online Certificate Status Protocol (OCSP).
+Certificates that a CA issues may need to be revoked at some stage. As
+an example, an employee leaves the organization and does not bother
+handing in his smart card (or even if the smart card is handed back --
+the certificate on it must no longer be acceptable to services; the
+employee has left).
=20
-If you know that the certificate is destroyed then there is no need to
-revoke the certificate because it can not be used by someone else.
+You may also want to revoke a certificate for a service which is no
+longer being offered on your network. Overlooking these scenarios can
+lead to security holes which will quickly become a nightmare to deal
+with.
=20
-The main reason you as a CA administrator have to deal with CRLs however
-will be that some software require there to be CRLs. Example of this is
-Windows, so you have to deal with this somehow.
+There are two primary protocols for dealing with certificate
+revokation. Namely:
+
+ at itemize @bullet
+ at item Certificate Revocation List (CRL)
+ at item Online Certificate Status Protocol (OCSP)
+ at end itemize
+
+If however the certificate in qeustion has been destroyed, there is no
+need to revoke the certificate because it can not be used by someone
+else. This matter since for each certificate you add to CRL, the
+download time and processing time for clients are longer.
+
+CRLs and OCSP responders however greatly help manage compatible services
+which may authenticate and authorize users (or services) on an on-going
+basis. As an example, VPN connectivity established via certificates for
+connecting clients would require your VPN software to make use of a CRL
+or an OCSP service to ensure revoked certificates belonging to former
+clients are not allowed access to (formerly subscribed) network
+services.
+
=20
 @node Issuing CRLs, Application requirements, Issuing certificates, Top
 @section Issuing CRLs
=20
-Create an empty CRL with not certificates revoked. Default expiration
+Create an empty CRL with no certificates revoked. Default expiration
 value is one year from now.
=20
 @example
@@ -488,7 +531,7 @@
 @node Application requirements, CMS signing and encryption, Issuing CRLs, =
Top
 @section Application requirements
=20
-Application have different requirements on certificates. This section
+Application place different requirements on certificates. This section
 tries to expand what they are and how to use hxtool to generate
 certificates for those services.
=20
@@ -521,14 +564,14 @@
 RFC2822, section 3.4.1 and it should be an ``addr-spec''.
=20
 There are two ways to specifify email address in certificates. The old
-ways is in the subject distinguished name, this should not be used. The
+way is in the subject distinguished name, @emph{this should not be used}. =
The
 new way is using a Subject Alternative Name (SAN).
=20
-But even though email address is stored in certificates, they don't need
-to, email reader programs are required to accept certificates that
-doesn't have either of the two methods of storing email in certificates.
-In that case, they try to protect the user by printing the name of the
-certificate instead.
+Even though the email address is stored in certificates, they don't need
+to be, email reader programs are required to accept certificates that
+doesn't have either of the two methods of storing email in certificates
+-- in which case, the email client will try to protect the user by
+printing the name of the certificate instead.
=20
 S/MIME certificate can be used in another special way. They can be
 issued with a NULL subject distinguished name plus the email in SAN,
@@ -561,26 +604,51 @@
=20
 @subsection PK-INIT
=20
-How to create a certificate for a KDC.
+A PK-INIT infrastructure allows users and services to pick up kerberos
+credentials (tickets) based on their certificate. This, for example,
+allows users to authenticate to their desktops using smartcards while
+acquiring kerberos tickets in the process.
+
+As an example, an office network which offers centrally controlled
+desktop logins, mail, messaging (xmpp) and openafs would give users
+single sign-on facilities via smartcard based logins.  Once the kerberos
+ticket has been acquired, all kerberized services would immediately
+become accessible based on deployed security policies.
+
+Let's go over the process of initializing a demo PK-INIT framework:
=20
 @example
 hxtool issue-certificate \
-    --type=3D"pkinit-kdc" \
-    --pk-init-principal=3D"krbtgt/TEST.H5L.SE@@TEST.H5L.SE" \
-    --hostname kerberos.test.h5l.se \
-    --hostname pal.test.h5l.se \
-    ...
+        --type=3D"pkinit-kdc" \
+        --pk-init-principal=3D"krbtgt/TEST.H5L.SE@@TEST.H5L.SE" \
+        --hostname=3Dkerberos.test.h5l.se \
+        --ca-certificate=3D"FILE:ca.pem,ca.key" \
+        --generate-key=3Drsa \
+        --certificate=3D"FILE:kdc.pem" \
+        --subject=3D"cn=3Dkdc"
 @end example
=20
 How to create a certificate for a user.
=20
 @example
 hxtool issue-certificate \
-    --type=3D"pkinit-client" \
-    --pk-init-principal=3D"user@@TEST.H5L.SE" \
-    ...
+        --type=3D"pkinit-client" \
+        --pk-init-principal=3D"user@@TEST.H5L.SE" \
+        --ca-certificate=3D"FILE:ca.pem,ca.key" \
+        --generate-key=3Drsa \
+        --subject=3D"cn=3DTest User" \
+        --certificate=3D"FILE:user.pem"
 @end example
=20
+The --type field can be specified multiple times. The same certificate
+can hence house extensions for both pkinit-client as well as S/MIME.
+
+To use the PKCS11 module, please see the section:
+ at pxref{How to use the PKCS11 module}.
+
+More about how to configure the KDC, see the documentation in the
+Heimdal manual to set up the KDC.
+
 @subsection XMPP/Jabber
=20
 The jabber server certificate should have a dNSname that is the same as
@@ -623,10 +691,66 @@
 S/MIME (secure email) and Kerberos PK-INIT. It's an extended version of
 the RSA, Inc standard PKCS7.
=20
- at node CMS background, , CMS signing and encryption, Top
+ at node CMS background, Certificate matching, CMS signing and encryption, Top
 @section CMS background
=20
=20
+ at node Certificate matching, Matching syntax, CMS background, Top
+ at chapter Certificate matching
+
+To match certificates hx509 have a special query language to match
+certifictes in queries and ACLs.
+
+ at node Matching syntax, Software PKCS 11 module, Certificate matching, Top
+ at section Matching syntax
+
+This is the language definitions somewhat slopply descriped:
+
+ at example
+
+expr =3D TRUE,=20
+     FALSE,
+     ! expr,
+     expr AND expr,
+     expr OR expr,
+     ( expr )
+     compare
+
+compare =3D
+     word =3D=3D word,
+     word !=3D word,
+     word IN ( word [, word ...])
+     word IN %@{variable.subvariable@}
+
+word =3D
+     STRING,
+     %@{variable@}
+
+ at end example
+
+ at node Software PKCS 11 module, How to use the PKCS11 module, Matching synt=
ax, Top
+ at chapter Software PKCS 11 module
+
+PKCS11 is a standard created by RSA, Inc to support hardware and
+software encryption modules. It can be used by smartcard to expose the
+crypto primitives inside without exposing the crypto keys.
+
+Hx509 includes a software implementation of PKCS11 that runs within the
+memory space of the process and thus exposes the keys to the
+application.
+
+ at node How to use the PKCS11 module, , Software PKCS 11 module, Top
+ at section How to use the PKCS11 module
+
+ at example
+$ cat > ~/.soft-pkcs11.rc <<EOF
+mycert	cert	User certificate	FILE:/Users/lha/Private/pkinit.pem
+app-fatal	true
+EOF
+$ kinit -C PKCS11:/usr/heimdal/lib/hx509.so lha@@EXAMPLE.ORG
+ at end example
+
+
 @c @shortcontents
 @contents
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/install.texi
--- a/head/crypto/heimdal/doc/install.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/install.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,107 +1,12 @@
- at c $Id: install.texi 16768 2006-02-27 12:26:49Z joda $
-
 @node Building and Installing, Setting up a realm, What is Kerberos?, Top
 @comment  node-name,  next,  previous,  up
 @chapter Building and Installing
=20
-Heimdal uses GNU Autoconf to configure for specific hosts, and GNU
-Automake to manage makefiles. If this is new to you, the short
-instruction is to run the @code{configure} script in the top level
-directory, and when that finishes @code{make}.
+Build and install instructions are located here:
=20
-If you want to build the distribution in a different directory from the
-source directory, you will need a make that implements VPATH correctly,
-such as GNU make.
+ at url{http://www.h5l.org/compile.html}
=20
-You will need to build the distribution:
+Prebuilt packages is located here:
=20
- at itemize @bullet
- at item
-A compiler that supports a ``loose'' ANSI C mode, such as @code{gcc}.
- at item
-lex or flex
- at item
-awk
- at item
-yacc or bison
- at item
-a socket library
- at item
-NDBM or Berkeley DB for building the server side.
- at end itemize
+ at url{http://www.h5l.org/binaries.html}
=20
-When everything is built, you can install by doing @kbd{make
-install}. The default location for installation is @file{/usr/heimdal},
-but this can be changed by running @code{configure} with
- at samp{--prefix=3D/some/other/place}.
-
-If you need to change the default behaviour, configure understands the
-following options:
-
- at table @asis
- at item @kbd{--without-berkeley-db}
-DB is preferred before NDBM, but if you for some reason want to use NDBM
-instead, you can use this option.
-
- at item @kbd{--with-krb4=3D at file{dir}}
-Gives the location of Kerberos 4 libraries and headers. This enables
-Kerberos 4 support in the applications (telnet, rsh, popper, etc) and
-the KDC. It is automatically found if present under
- at file{/usr/athena}.  If you keep libraries and headers in different
-places, you can instead give the path to each with the
- at kbd{--with-krb4-lib=3D at file{dir}}, and
- at kbd{--with-krb4-include=3D at file{dir}} options.
-
-You will need a fairly recent version of our Kerberos 4 distribution for
- at code{rshd} and @code{popper} to support version 4 clients.
-
- at item @kbd{--enable-dce}
-Enables support for getting DCE credentials and tokens.  See the README
-files in @file{appl/dceutils} for more information.
-
- at item @kbd{--disable-otp}
-By default some of the application programs will build with support for
-one-time passwords (OTP).  Use this option to disable that support.
-
- at item @kbd{--enable-osfc2}
-Enable some C2 support for OSF/Digital Unix/Tru64.  Use this option if
-you are running your OSF operating system in C2 mode.
-
- at item @kbd{--with-readline=3D at file{dir}}
-Gives the path for the GNU Readline library, which will be used in some
-programs. If no readline library is found, the (simpler) editline
-library will be used instead.
-
- at item @kbd{--with-hesiod=3D at file{dir}}
-Enables hesiod support in push.
-
- at item @kbd{--enable-netinfo}
-Add support for using netinfo to lookup configuration information.
-Probably only useful (and working) on NextStep/Mac OS X.
-
- at item @kbd{--without-ipv6}
-Disable the IPv6 support.
-
- at item @kbd{--with-openldap}
-Compile Heimdal with support for storing the database in LDAP.  Requires
-OpenLDAP @url{http://www.openldap.org}.  See
- at url{http://www.padl.com/Research/Heimdal.html} for more information.
-
- at item @kbd{--enable-bigendian}
- at item @kbd{--enable-littleendian}
-Normally, the build process will figure out by itself if the machine is
-big or little endian.  It might fail in some cases when
-cross-compiling.  If it does fail to figure it out, use the relevant of
-these two options.
-
- at item @kbd{--with-mips-abi=3D at var{abi}}
-On Irix there are three different ABIs that can be used (@samp{32},
- at samp{n32}, or @samp{64}).  This option allows you to override the
-automatic selection.
-
- at item @kbd{--disable-mmap}
-Do not use the mmap system call.  Normally, configure detects if there
-is a working mmap and it is only used if there is one.  Only try this
-option if it fails to work anyhow.
-
- at end table
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/intro.texi
--- a/head/crypto/heimdal/doc/intro.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/intro.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
- at c $Id: intro.texi 22509 2008-01-23 18:28:01Z lha $
+ at c $Id$
=20
 @node Introduction, What is Kerberos?, Top, Top
 @c @node Introduction, What is Kerberos?, Top, Top
@@ -57,8 +57,7 @@
 @item
 some simple test programs
 @item
-a KDC that supports most things; optionally, it may also support
-Kerberos V4 and kaserver,
+a KDC that supports most things,
 @item
 simple programs for distributing databases between a KDC master and
 slaves
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/kerberos4.texi
--- a/head/crypto/heimdal/doc/kerberos4.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/kerberos4.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,19 +1,16 @@
- at c $Id: kerberos4.texi 16370 2005-12-12 12:11:51Z lha $
+ at c $Id$
=20
- at node Kerberos 4 issues, Windows 2000 compatability, Things in search for =
a better place, Top
+ at node Kerberos 4 issues, Windows compatibility, Things in search for a bet=
ter place, Top
 @comment  node-name,  next,  previous,  up
 @chapter Kerberos 4 issues
=20
-The KDC has built-in version 4 support. It is not enabled by default,
-see setup how to set it up.
+Kerberos 4 KDC and KA server have been moved.
=20
-The KDC will also have kaserver emulation and be able to handle
-AFS-clients that use @code{klog}.
+For more about AFS, see the section @xref{AFS}.
=20
 @menu
 * Principal conversion issues:: =20
 * Converting a version 4 database:: =20
-* kaserver::
 @end menu
=20
 @node Principal conversion issues, Converting a version 4 database, Kerber=
os 4 issues, Kerberos 4 issues
@@ -57,7 +54,7 @@
 @code{krb5_425_conv_principal_ext} to convert principals when handling
 to version 4 requests.
=20
- at node Converting a version 4 database, kaserver , Principal conversion iss=
ues, Kerberos 4 issues
+ at node Converting a version 4 database, , Principal conversion issues, Kerb=
eros 4 issues
 @section Converting a version 4 database
=20
 If you want to convert an existing version 4 database, the principal
@@ -174,53 +171,3 @@
 hprop -n --source=3Dkrb4-db -d /var/kerberos/principal --master-key=3D/.m =
| hpropd -n
 @end example
=20
- at section Version 4 Kadmin
-
- at samp{kadmind} can act as a version 4 kadmind, and you can do most
-operations, but with some restrictions (since the version 4 kadmin
-protocol is, lets say, very ad hoc.) One example is that it only passes
-des keys when creating principals and changing passwords (modern kpasswd
-clients do send the password, so it's possible to to password quality
-checks). Because of this you can only create principals with des keys,
-and you can't set any flags or do any other fancy stuff.
-
-To get this to work, you have to add another entry to inetd (since
-version 4 uses port 751, not 749).
-
- at emph{And then there are a many more things you can do; more on this in
-a later version of this manual. Until then, UTSL.}
-
- at node kaserver, , Converting a version 4 database, Kerberos 4 issues
- at section kaserver
-
- at subsection kaserver emulation
-
-The Heimdal kdc can emulate a kaserver. The kaserver is a Kerberos 4
-server with pre-authentication using Rx as the on-wire protocol. The kdc
-contains a minimalistic Rx implementation.
-
-There are three parts of the kaserver; KAA (Authentication), KAT (Ticket
-Granting), and KAM (Maintenance). The KAA interface and KAT interface
-both passes over DES encrypted data-blobs (just like the
-Kerberos-protocol) and thus do not need any other protection.  The KAM
-interface uses @code{rxkad} (Kerberos authentication layer for Rx) for
-security and data protection, and is used for example for changing
-passwords.  This part is not implemented in the kdc.
-
-Another difference between the ka-protocol and the Kerberos 4 protocol
-is that the pass-phrase is salted with the cellname in the @code{string to
-key} function in the ka-protocol, while in the Kerberos 4 protocol there
-is no salting of the password at all. To make sure AFS-compatible keys
-are added to each principals when they are created or their password are
-changed, @samp{afs3-salt} should be added to
- at samp{[kadmin]default_keys}.
-
- at subsection Transarc AFS Windows client
-
-The Transarc Windows client uses Kerberos 4 to obtain tokens, and thus
-does not need a kaserver. The Windows client assumes that the Kerberos
-server is on the same machine as the AFS-database server. If you do not
-like to do that you can add a small program that runs on the database
-servers that forward all kerberos requests to the real kerberos
-server. A program that does this is @code{krb-forward}
-(@url{ftp://ftp.stacken.kth.se/pub/projekts/krb-forward}).
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/krb5.din
--- a/head/crypto/heimdal/doc/krb5.din	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/krb5.din	Tue Apr 17 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
=20
 PROJECT_NAME           =3D Heimdal Kerberos 5 library
 PROJECT_NUMBER         =3D @PACKAGE_VERSION@
-OUTPUT_DIRECTORY       =3D @objdir@/krb5
+OUTPUT_DIRECTORY       =3D @srcdir@/doxyout/krb5
 INPUT                  =3D @srcdir@/../lib/krb5
=20
 WARN_IF_UNDOCUMENTED   =3D NO
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/migration.texi
--- a/head/crypto/heimdal/doc/migration.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/migration.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,18 @@
- at c $Id: migration.texi 9718 2001-02-24 05:09:24Z assar $
+ at c $Id$
=20
 @node Migration, Acknowledgments, Programming with Kerberos, Top
 @chapter Migration
=20
+ at section Migration from MIT Kerberos to Heimdal
+
+hpropd can read MIT Kerberos dump, the format is the same as used in
+mit-kerberos 1.0b7, and to dump that format use the following command:
+ at samp{kdb5_util dump -b7}.
+
+To load the MIT Kerberos dump file, use the following command:
+
+ at samp{/usr/heimdal/libexec/hprop --database=3Ddump-file --master-key=3D/va=
r/db/krb5kdc/mit_stash --source=3Dmit-dump --decrypt --stdout | /usr/heimda=
l/libexec/hpropd --stdin}
+
 @section General issues
=20
 When migrating from a Kerberos 4 KDC.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/misc.texi
--- a/head/crypto/heimdal/doc/misc.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/misc.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
- at c $Id: misc.texi 12197 2003-05-04 13:32:37Z lha $
+ at c $Id$
=20
 @node Things in search for a better place, Kerberos 4 issues, Applications=
, Top
 @chapter Things in search for a better place
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/ntlm.din
--- a/head/crypto/heimdal/doc/ntlm.din	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/ntlm.din	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,9 @@
=20
 PROJECT_NAME           =3D Heimdal ntlm library
 PROJECT_NUMBER         =3D @PACKAGE_VERSION@
-OUTPUT_DIRECTORY       =3D @objdir@/ntlm
+OUTPUT_DIRECTORY       =3D @srcdir@/doxyout/ntlm
 INPUT                  =3D @srcdir@/../lib/ntlm
+EXAMPLE_PATH	       =3D @srcdir@/../lib/ntlm
=20
 WARN_IF_UNDOCUMENTED   =3D YES
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/programming.te=
xi
--- a/head/crypto/heimdal/doc/programming.texi	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/doc/programming.texi	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,642 +1,7 @@
- at c $Id: programming.texi 22071 2007-11-14 20:04:50Z lha $
+ at c $Id$
=20
- at node Programming with Kerberos, Migration, Windows 2000 compatability, Top
+ at node Programming with Kerberos, Migration, Windows compatibility, Top
 @chapter Programming with Kerberos
=20
-First you need to know how the Kerberos model works, go read the
-introduction text (@pxref{What is Kerberos?}).
-
- at menu
-* Kerberos 5 API Overview::    =20
-* Walkthrough of a sample Kerberos 5 client:: =20
-* Validating a password in a server application:: =20
-* API differences to MIT Kerberos:: =20
-* File formats::
- at end menu
-
- at node Kerberos 5 API Overview, Walkthrough of a sample Kerberos 5 client, =
Programming with Kerberos, Programming with Kerberos
- at section Kerberos 5 API Overview
-
-All functions are documented in manual pages.  This section tries to
-give an overview of the major components used in Kerberos library, and
-point to where to look for a specific function.
-
- at subsection Kerberos context
-
-A kerberos context (@code{krb5_context}) holds all per thread state. All g=
lobal variables that
-are context specific are stored in this structure, including default
-encryption types, credential cache (for example, a ticket file), and defau=
lt realms.
-
-See the manual pages for @manpage{krb5_context,3} and
- at manpage{krb5_init_context,3}.
-
- at subsection Kerberos authentication context
-
-Kerberos authentication context (@code{krb5_auth_context}) holds all
-context related to an authenticated connection, in a similar way to the
-kerberos context that holds the context for the thread or process.
-
-The @code{krb5_auth_context} is used by various functions that are
-directly related to authentication between the server/client. Example of
-data that this structure contains are various flags, addresses of client
-and server, port numbers, keyblocks (and subkeys), sequence numbers,
-replay cache, and checksum types.
-
-See the manual page for @manpage{krb5_auth_context,3}.
-
- at subsection Kerberos principal
-
-The Kerberos principal is the structure that identifies a user or
-service in Kerberos. The structure that holds the principal is the
- at code{krb5_principal}. There are function to extract the realm and
-elements of the principal, but most applications have no reason to
-inspect the content of the structure.
-
-The are several ways to create a principal (with different degree of
-portability), and one way to free it.
-
-See manual page for @manpage{krb5_principal,3} for more information
-about the functions.
-
- at subsection Credential cache
-
-A credential cache holds the tickets for a user. A given user can have
-several credential caches, one for each realm where the user have the
-initial tickets (the first krbtgt).
-
-The credential cache data can be stored internally in different way, each =
of them for
-different proposes.  File credential (FILE) caches and processes based
-(KCM) caches are for permanent storage. While memory caches (MEMORY)
-are local caches to the local process.
-
-Caches are opened with @manpage{krb5_cc_resolve,3} or created with
- at manpage{krb5_cc_gen_unique,3}.
-
-If the cache needs to be opened again (using
- at manpage{krb5_cc_resolve,3}) @manpage{krb5_cc_close,3} will close the
-handle, but not the remove the cache. @manpage{krb5_cc_destroy,3} will
-zero out the cache, remove the cache so it can no longer be
-referenced.
-
-See also manual page for @manpage{krb5_ccache,3}
-
- at subsection Kerberos errors
-
-Kerberos errors are based on the com_err library.  All error codes are
-32-bit signed numbers, the first 24 bits define what subsystem the
-error originates from, and last 8 bits are 255 error codes within the
-library.  Each error code have fixed string associated with it.  For
-example, the error-code -1765328383 have the symbolic name
-KRB5KDC_ERR_NAME_EXP, and associated error string ``Client's entry in
-database has expired''.
-
-This is a great improvement compared to just getting one of the unix
-error-codes back.  However, Heimdal have an extention to pass back
-customised errors messages.  Instead of getting ``Key table entry not
-found'', the user might back ``failed to find
-host/host.example.com@@EXAMLE.COM(kvno 3) in keytab /etc/krb5.keytab
-(des-cbc-crc)''.  This improves the chance that the user find the
-cause of the error so you should use the customised error message
-whenever it's available.
-
-See also manual page for @manpage{krb5_get_error_string,3} and
- at manpage{krb5_get_err_text,3}.
-
- at subsection Keytab management
-
-A keytab is a storage for locally stored keys. Heimdal includes keytab
-support for Kerberos 5 keytabs, Kerberos 4 srvtab, AFS-KeyFile's,
-and for storing keys in memory.
-
-Keytabs are used for servers and long-running services.
-
-See also manual page for @manpage{krb5_keytab,3}
-
- at subsection Kerberos crypto
-
-Heimdal includes a implementation of the Kerberos crypto framework,
-all crypto operations.
-
-See also manual page for @manpage{krb5_crypto_init,3},
- at manpage{krb5_keyblock,3}, @manpage{krb5_create_checksum,3},=20
-and @manpage{krb5_encrypt,3}.
-
- at node Walkthrough of a sample Kerberos 5 client, Validating a password in =
a server application, Kerberos 5 API Overview, Programming with Kerberos
- at section Walkthrough of a sample Kerberos 5 client
-
-This example contains parts of a sample TCP Kerberos 5 clients, if you
-want a real working client, please look in @file{appl/test} directory in
-the Heimdal distribution.
-
-All Kerberos error-codes that are returned from kerberos functions in
-this program are passed to @code{krb5_err}, that will print a
-descriptive text of the error code and exit. Graphical programs can
-convert error-code to a human readable error-string with the
- at manpage{krb5_get_err_text,3} function.
-
-Note that you should not use any Kerberos function before
- at code{krb5_init_context()} have completed successfully. That is the
-reason @code{err()} is used when @code{krb5_init_context()} fails.
-
-First the client needs to call @code{krb5_init_context} to initialise
-the Kerberos 5 library. This is only needed once per thread
-in the program. If the function returns a non-zero value it indicates
-that either the Kerberos implementation is failing or it's disabled on
-this host.
-
- at example
-#include <krb5.h>
-
-int
-main(int argc, char **argv)
-@{
-        krb5_context context;
-
-        if (krb5_context(&context))
-                errx (1, "krb5_context");
- at end example
-
-Now the client wants to connect to the host at the other end. The
-preferred way of doing this is using @manpage{getaddrinfo,3} (for
-operating system that have this function implemented), since getaddrinfo
-is neutral to the address type and can use any protocol that is available.
-
- at example
-        struct addrinfo *ai, *a;
-        struct addrinfo hints;
-        int error;
-
-        memset (&hints, 0, sizeof(hints));
-        hints.ai_socktype =3D SOCK_STREAM;
-        hints.ai_protocol =3D IPPROTO_TCP;
-
-        error =3D getaddrinfo (hostname, "pop3", &hints, &ai);
-        if (error)
-                errx (1, "%s: %s", hostname, gai_strerror(error));
-
-        for (a =3D ai; a !=3D NULL; a =3D a->ai_next) @{
-                int s;
-
-                s =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol=
);
-                if (s < 0)
-                        continue;
-                if (connect (s, a->ai_addr, a->ai_addrlen) < 0) @{
-                        warn ("connect(%s)", hostname);
-                            close (s);
-                            continue;
-                @}
-                freeaddrinfo (ai);
-                ai =3D NULL;
-        @}
-        if (ai) @{
-                    freeaddrinfo (ai);
-                    errx ("failed to contact %s", hostname);
-        @}
- at end example
-
-Before authenticating, an authentication context needs to be
-created. This context keeps all information for one (to be) authenticated
-connection (see @manpage{krb5_auth_context,3}).
-
- at example
-        status =3D krb5_auth_con_init (context, &auth_context);
-        if (status)
-                krb5_err (context, 1, status, "krb5_auth_con_init");
- at end example
-
-For setting the address in the authentication there is a help function
- at code{krb5_auth_con_setaddrs_from_fd} that does everything that is needed
-when given a connected file descriptor to the socket.
-
- at example
-        status =3D krb5_auth_con_setaddrs_from_fd (context,
-                                                 auth_context,
-                                                 &sock);
-        if (status)
-                krb5_err (context, 1, status,=20
-                          "krb5_auth_con_setaddrs_from_fd");
- at end example
-
-The next step is to build a server principal for the service we want
-to connect to. (See also @manpage{krb5_sname_to_principal,3}.)
-
- at example
-        status =3D krb5_sname_to_principal (context,
-                                          hostname,
-                                          service,
-                                          KRB5_NT_SRV_HST,
-                                          &server);
-        if (status)
-                krb5_err (context, 1, status, "krb5_sname_to_principal");
- at end example
-
-The client principal is not passed to @manpage{krb5_sendauth,3}
-function, this causes the @code{krb5_sendauth} function to try to figure it
-out itself.
-
-The server program is using the function @manpage{krb5_recvauth,3} to
-receive the Kerberos 5 authenticator.
-
-In this case, mutual authentication will be tried. That means that the ser=
ver
-will authenticate to the client. Using mutual authentication
-is good since it enables the user to verify that they are talking to the
-right server (a server that knows the key).
-
-If you are using a non-blocking socket you will need to do all work of
- at code{krb5_sendauth} yourself. Basically you need to send over the
-authenticator from @manpage{krb5_mk_req,3} and, in case of mutual
-authentication, verifying the result from the server with
- at manpage{krb5_rd_rep,3}.
-
- at example
-        status =3D krb5_sendauth (context,
-                                &auth_context,
-                                &sock,
-                                VERSION,
-                                NULL,
-                                server,
-                                AP_OPTS_MUTUAL_REQUIRED,
-                                NULL,
-                                NULL,
-                                NULL,
-                                NULL,
-                                NULL,
-                                NULL);
-        if (status)
-                krb5_err (context, 1, status, "krb5_sendauth");
- at end example
-
-Once authentication has been performed, it is time to send some
-data. First we create a krb5_data structure, then we sign it with
- at manpage{krb5_mk_safe,3} using the @code{auth_context} that contains the
-session-key that was exchanged in the
- at manpage{krb5_sendauth,3}/@manpage{krb5_recvauth,3} authentication
-sequence.
-
- at example
-        data.data   =3D "hej";
-        data.length =3D 3;
-
-        krb5_data_zero (&packet);
-
-        status =3D krb5_mk_safe (context,
-                               auth_context,
-                               &data,
-                               &packet,
-                               NULL);
-        if (status)
-                krb5_err (context, 1, status, "krb5_mk_safe");
- at end example
-
-And send it over the network.
-
- at example
-        len =3D packet.length;
-        net_len =3D htonl(len);
-
-        if (krb5_net_write (context, &sock, &net_len, 4) !=3D 4)
-                err (1, "krb5_net_write");
-        if (krb5_net_write (context, &sock, packet.data, len) !=3D len)
-                err (1, "krb5_net_write");
- at end example
-
-To send encrypted (and signed) data @manpage{krb5_mk_priv,3} should be
-used instead. @manpage{krb5_mk_priv,3} works the same way as
- at manpage{krb5_mk_safe,3}, with the exception that it encrypts the data
-in addition to signing it.
-
- at example
-        data.data   =3D "hemligt";
-        data.length =3D 7;
-
-        krb5_data_free (&packet);
-
-        status =3D krb5_mk_priv (context,
-                               auth_context,
-                               &data,
-                               &packet,
-                               NULL);
-        if (status)
-                krb5_err (context, 1, status, "krb5_mk_priv");
- at end example
-
-And send it over the network.
-
- at example
-        len =3D packet.length;
-        net_len =3D htonl(len);
-
-        if (krb5_net_write (context, &sock, &net_len, 4) !=3D 4)
-                err (1, "krb5_net_write");
-        if (krb5_net_write (context, &sock, packet.data, len) !=3D len)
-                err (1, "krb5_net_write");
-
- at end example
-
-The server is using @manpage{krb5_rd_safe,3} and
- at manpage{krb5_rd_priv,3} to verify the signature and decrypt the packet.
-
- at node Validating a password in a server application, API differences to MI=
T Kerberos, Walkthrough of a sample Kerberos 5 client, Programming with Ker=
beros
- at section Validating a password in an application
-
-See the manual page for @manpage{krb5_verify_user,3}.
-
- at node API differences to MIT Kerberos, File formats, Validating a password=
 in a server application, Programming with Kerberos
- at section API differences to MIT Kerberos
-
-This section is somewhat disorganised, but so far there is no overall
-structure to the differences, though some of the have their root in
-that Heimdal uses an ASN.1 compiler and MIT doesn't.
-
- at subsection Principal and realms
-
-Heimdal stores the realm as a @code{krb5_realm}, that is a @code{char *}.
-MIT Kerberos uses a @code{krb5_data} to store a realm.
-
-In Heimdal @code{krb5_principal} doesn't contain the component
- at code{name_type}; it's instead stored in component
- at code{name.name_type}. To get and set the nametype in Heimdal, use
- at manpage{krb5_principal_get_type,3} and
- at manpage{krb5_principal_set_type,3}.
-
-For more information about principal and realms, see
- at manpage{krb5_principal,3}.
-
- at subsection Error messages
-
-To get the error string, Heimdal uses
- at manpage{krb5_get_error_string,3} or, if @code{NULL} is returned,
- at manpage{krb5_get_err_text,3}. This is to return custom error messages
-(like ``Can't find host/datan.example.com@@EXAMPLE.COM in
-/etc/krb5.conf.'' instead of a ``Key table entry not found'' that
- at manpage{error_message,3} returns.
-
-Heimdal uses a threadsafe(r) version of the com_err interface; the
-global @code{com_err} table isn't initialised.  Then
- at manpage{error_message,3} returns quite a boring error string (just
-the error code itself).
-
-
- at c @node Why you should use GSS-API for new applications, Walkthrough of a=
 sample GSS-API client, Validating a password in a server application, Prog=
ramming with Kerberos
- at c @section Why you should use GSS-API for new applications
- at c=20
- at c SSPI, bah, bah, microsoft, bah, bah, almost GSS-API.
- at c=20
- at c It would also be possible for other mechanisms then Kerberos, but that
- at c doesn't exist any other GSS-API implementations today.
- at c=20
- at c @node Walkthrough of a sample GSS-API client, , Why you should use GSS-=
API for new applications, Programming with Kerberos
- at c @section Walkthrough of a sample GSS-API client
- at c=20
- at c Write about how gssapi_clent.c works.
-
- at node File formats,  , API differences to MIT Kerberos, Programming with K=
erberos
- at section File formats
-
-This section documents the diffrent file formats that are used in
-Heimdal and other Kerberos implementations.
-
- at subsection keytab
-
-The keytab binary format is not a standard format. The format has
-evolved and may continue to. It is however understood by several
-Kerberos implementations including Heimdal, MIT, Sun's Java ktab and
-are created by the ktpass.exe utility from Windows. So it has
-established itself as the defacto format for storing Kerberos keys.
-
-The following C-like structure definitions illustrate the MIT keytab
-file format. All values are in network byte order. All text is ASCII.
-
- at example
-  keytab @{
-      uint16_t file_format_version;                    /* 0x502 */
-      keytab_entry entries[*];
-  @};
-
-  keytab_entry @{
-      int32_t size;
-      uint16_t num_components;   /* subtract 1 if version 0x501 */
-      counted_octet_string realm;
-      counted_octet_string components[num_components];
-      uint32_t name_type;       /* not present if version 0x501 */
-      uint32_t timestamp;
-      uint8_t vno8;
-      keyblock key;
-      uint32_t vno; /* only present if >=3D 4 bytes left in entry */
-  @};
-
-  counted_octet_string @{
-      uint16_t length;
-      uint8_t data[length];
-  @};
-
-  keyblock @{
-      uint16_t type;
-      counted_octet_string;
-  @};
- at end example
-
-All numbers are stored in network byteorder (big endian) format.
-
-The keytab file format begins with the 16 bit file_format_version which
-at the time this document was authored is 0x502. The format of older
-keytabs is described at the end of this document.
-
-The file_format_version is immediately followed by an array of
-keytab_entry structures which are prefixed with a 32 bit size indicating
-the number of bytes that follow in the entry. Note that the size should be
-evaluated as signed. This is because a negative value indicates that the
-entry is in fact empty (e.g. it has been deleted) and that the negative
-value of that negative value (which is of course a positive value) is
-the offset to the next keytab_entry. Based on these size values alone
-the entire keytab file can be traversed.
-
-The size is followed by a 16 bit num_components field indicating the
-number of counted_octet_string components in the components array.
-
-The num_components field is followed by a counted_octet_string
-representing the realm of the principal.
-
-A counted_octet_string is simply an array of bytes prefixed with a 16
-bit length. For the realm and name components, the counted_octet_string
-bytes are ASCII encoded text with no zero terminator.
-
-Following the realm is the components array that represents the name of
-the principal. The text of these components may be joined with slashs
-to construct the typical SPN representation. For example, the service
-principal HTTP/www.foo.net@@FOO.NET would consist of name components
-"HTTP" followed by "www.foo.net".
-
-Following the components array is the 32 bit name_type (e.g. 1 is
-KRB5_NT_PRINCIPAL, 2 is KRB5_NT_SRV_INST, 5 is KRB5_NT_UID, etc). In
-practice the name_type is almost certainly 1 meaning KRB5_NT_PRINCIPAL.
-
-The 32 bit timestamp indicates the time the key was established for that
-principal. The value represents the number of seconds since Jan 1, 1970.
-
-The 8 bit vno8 field is the version number of the key. This value is
-overridden by the 32 bit vno field if it is present. The vno8 field is
-filled with the lower 8 bits of the 32 bit protocol kvno field.
-
-The keyblock structure consists of a 16 bit value indicating the
-encryption type and is a counted_octet_string containing the key.  The
-encryption type is the same as the Kerberos standard (e.g. 3 is
-des-cbc-md5, 23 is arcfour-hmac-md5, etc).
-
-The last field of the keytab_entry structure is optional. If the size of
-the keytab_entry indicates that there are at least 4 bytes remaining,
-a 32 bit value representing the key version number is present. This
-value supersedes the 8 bit vno8 value preceeding the keyblock.
-
-Older keytabs with a file_format_version of 0x501 are different in
-three ways:
-
- at table @asis
- at item All integers are in host byte order [1].
- at item The num_components field is 1 too large (i.e. after decoding, decrem=
ent by 1).
- at item The 32 bit name_type field is not present.
- at end table
-
-[1] The file_format_version field should really be treated as two
-separate 8 bit quantities representing the major and minor version
-number respectively.
-
- at subsection Heimdal database dump file
-
-Format of the Heimdal text dump file as of Heimdal 0.6.3:
-
-Each line in the dump file is one entry in the database.
-
-Each field of a line is separated by one or more spaces, with the
-exception of fields consisting of principals containing spaces, where
-space can be quoted with \ and \ is quoted by \.
-
-Fields and their types are:
-
- at example
-	Quoted princial (quote character is \) [string]
-	Keys [keys]
-	Created by [event]
-	Modified by [event optional]
-	Valid start time [time optional]
-	Valid end time [time optional]
-	Password end valid time [time optional]
-	Max lifetime of ticket [time optional]
-	Max renew time of ticket [integer optional]
-	Flags [hdb flags]
-	Generation number [generation optional]
-	Extensions [extentions optional]
- at end example
-
-Fields following these silently are ignored.
-
-All optional fields will be skipped if they fail to parse (or comprise
-the optional field marker of "-", w/o quotes).
-
-Example:
-
- at example
-fred@@EXAMPLE.COM 27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba3737=
33d26ca59ba6c789666f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a9338811=
78c744f4232172dcd774c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b1=
3eb795d76f3a80717d469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e=
16d8078bf60c781da90f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:- 2002=
0415130120:admin@@EXAMPLE.COM 20041221112428:fred@@EXAMPLE.COM - - - 86400 =
604800 126 20020415130120:793707:28 -
- at end example
-
-Encoding of types are as follows:
-
- at table @asis
- at item keys
-
- at example
-kvno:[masterkvno:keytype:keydata:salt]@{zero or more separated by :@}
- at end example
-
-kvno is the key version number.
-
-keydata is hex-encoded
-
-masterkvno is the kvno of the database master key.  If this field is
-empty, the kadmin load and merge operations will encrypt the key data
-with the master key if there is one.  Otherwise the key data will be
-imported asis.
-
-salt is encoded as "-" (no/default salt) or
-
- at example
-salt-type /
-salt-type / "string"
-salt-type / hex-encoded-data
- at end example
-
-keytype is the protocol enctype number; see enum ENCTYPE in
-include/krb5_asn1.h for values.
-
-Example:
- at example
-27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba373733d26ca59ba6c78966=
6f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a933881178c744f4232172dcd7=
74c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b13eb795d76f3a80717d=
469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e16d8078bf60c781da9=
0f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:-
- at end example
-
-
- at example
-kvno=3D27,@{key: masterkvno=3D1,keytype=3Ddes3-cbc-sha1,keydata=3D..., def=
ault salt@}...
- at end example
-
- at item time
-=09
-Format of the time is: YYYYmmddHHMMSS, corresponding to strftime
-format "%Y%m%d%k%M%S".
-
-Time is expressed in UTC.
-
-Time can be optional (using -), when the time 0 is used.
-
-Example:
-
- at example
-20041221112428
- at end example
-
- at item event
-
- at example
-	time:principal
- at end example
-
-time is as given in format time
-
-principal is a string.  Not quoting it may not work in earlier
-versions of Heimdal.
-
-Example:
- at example
-20041221112428:bloggs@@EXAMPLE.COM
- at end example
-
- at item hdb flags
-
-Integer encoding of HDB flags, see HDBFlags in lib/hdb/hdb.asn1. Each
-bit in the integer is the same as the bit in the specification.
-
- at item generation:
-
- at example
-time:usec:gen
- at end example
-
-
-usec is a the microsecond, integer.
-gen is generation number, integer.
-
-The generation can be defaulted (using '-') or the empty string
-
- at item extensions:
-
- at example
-first-hex-encoded-HDB-Extension[:second-...]
- at end example
-
-HDB-extension is encoded the DER encoded HDB-Extension from
-lib/hdb/hdb.asn1. Consumers HDB extensions should be aware that
-unknown entires needs to be preserved even thought the ASN.1 data
-content might be unknown. There is a critical flag in the data to show
-to the KDC that the entry MUST be understod if the entry is to be
-used.
-
- at end table
+See the Kerberos 5 API introduction and documentation on the Heimdal
+webpage.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/setup.texi
--- a/head/crypto/heimdal/doc/setup.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/setup.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
- at c $Id: setup.texi 22191 2007-12-06 17:26:30Z lha $
+ at c $Id$
=20
 @node Setting up a realm, Applications, Building and Installing, Top
=20
@@ -17,19 +17,20 @@
 * Modifying the database::
 * Checking the setup::
 * keytabs::
-* Serving Kerberos 4/524/kaserver::
 * Remote administration::
 * Password changing::
 * Testing clients and servers::
 * Slave Servers::
 * Incremental propagation::
 * Encryption types and salting::
+* Credential cache server - KCM::
 * Cross realm::
 * Transit policy::
 * Setting up DNS::
 * Using LDAP to store the database::
 * Providing Kerberos credentials to servers and programs::
 * Setting up PK-INIT::
+* Debugging Kerberos problems::
 @end menu
=20
 @node  Configuration file, Creating the database, Setting up a realm, Sett=
ing up a realm
@@ -92,6 +93,8 @@
         MY.REALM =3D @{
                 kdc =3D my.kdc my.slave.kdc
                 kdc =3D my.third.kdc
+                kdc =3D 130.237.237.17
+                kdc =3D [2001:6b0:1:ea::100]:88
         @}
 [domain_realm]
         .my.domain =3D MY.REALM
@@ -103,6 +106,14 @@
 SRV-record for your realm, or your Kerberos server has DNS CNAME
 @samp{kerberos.my.realm}, you can omit the @samp{realms} section too.
=20
+ at cindex KRB5_CONFIG
+If you want to use a different configuration file then the default you
+can point a file with the enviroment variable @samp{KRB5_CONFIG}.
+
+ at example
+env KRB5_CONFIG=3D$HOME/etc/krb5.conf kinit user@@REALM
+ at end example
+
 @node Creating the database, Modifying the database, Configuration file, S=
etting up a realm
 @section Creating the database
=20
@@ -267,14 +278,14 @@
 database check by run by the following command :
=20
 @example
-kadmin check REALM.EXAMPLE.ORG
+kadmin -l check REALM.EXAMPLE.ORG
 @end example
=20
- at node keytabs, Serving Kerberos 4/524/kaserver, Checking the setup, Settin=
g up a realm
+ at node keytabs, Remote administration, Checking the setup, Setting up a rea=
lm
 @section keytabs
=20
 To extract a service ticket from the database and put it in a keytab, you
-need to first create the principal in the database with @samp{ank}
+need to first create the principal in the database with @samp{add}
 (using the @kbd{--random-key} flag to get a random key) and then
 extract it with @samp{ext_keytab}.
=20
@@ -293,59 +304,7 @@
      1   des3-cbc-sha1    host/my.host.name@@MY.REALM
 @end example
=20
- at node Serving Kerberos 4/524/kaserver, Remote administration, keytabs, Set=
ting up a realm
- at section Serving Kerberos 4/524/kaserver
-
-Heimdal can be configured to support 524, Kerberos 4 or kaserver. All
-these services are turned off by default. Kerberos 4 is always
-supported by the KDC, but the Kerberos 4 client support also depends
-on Kerberos 4 support having been included at compile-time, using
- at kbd{--with-krb4=3Ddir}.
-
- at subsection 524
-
-524 is a service that allows the KDC to convert Kerberos 5 tickets to
-Kerberos 4 tickets for backward compatibility. See also Using 2b
-tokens with AFS in @xref{Things in search for a better place}.
-
-524 can be turned on by adding this to the configuration file
-
- at example
-[kdc]
-	enable-524 =3D yes
- at end example
-
- at subsection Kerberos 4
-
-Kerberos 4 is the predecessor to to Kerberos 5. It only supports
-single DES at . You should only enable Kerberos 4 support if you have
-needs for compatibility with an installed base of Kerberos 4
-clients/servers.
-
-Kerberos 4 can be turned on by adding this to the configuration file
-
- at example
-[kdc]
-	enable-kerberos4 =3D yes
- at end example
-
- at subsection kaserver
-
-Kaserver is a Kerberos 4 that is used in AFS at .  The protocol has some
-extra features over plain Kerberos 4, but like Kerberos 4, only uses
-single DES at .
-
-You should only enable Kaserver support if you have needs for
-compatibility with an installed base of AFS machines.
-
-Kaserver can be turned on by adding this to the configuration file
-
- at example
-[kdc]
-	enable-kaserver =3D yes
- at end example
-
- at node Remote administration, Password changing, Serving Kerberos 4/524/kas=
erver, Setting up a realm
+ at node Remote administration, Password changing, keytabs, Setting up a realm
 @section Remote administration
=20
 The administration server, @command{kadmind}, can be started by
@@ -403,7 +362,17 @@
 It is not run from @command{inetd}.
=20
 You might need to add @samp{kpasswd} to your @file{/etc/services} as
- at samp{464/udp}.
+ at samp{464/udp}.  If your realm is not setup to use DNS, you might also
+need to add a @samp{kpasswd_server} entry to the realm configuration
+in @file{/etc/krb5.conf} on client machines:
+
+ at example
+[realms]
+        MY.REALM =3D @{
+                kdc =3D my.kdc my.slave.kdc
+                kpasswd_server =3D my.kdc
+        @}
+ at end example
=20
 @subsection Password quality assurance
=20
@@ -419,16 +388,18 @@
=20
 @example
 [password_quality]
-	policies =3D external-check builtin:minimum-length module:policyname
+	policies =3D external-check builtin:minimum-length modulename:policyname
 	external_program =3D /bin/false
 	policy_libraries =3D @var{library1.so} @var{library2.so}
 @end example
=20
 In @samp{[password_quality]policies} the module name is optional if
 the policy name is unique in all modules (members of
- at samp{policy_libraries}).
+ at samp{policy_libraries}).  All built-in policies can be qualified with
+a module name of @samp{builtin} to unambiguously specify the built-in
+policy and not a policy by the same name from a loaded module.
=20
-The built-in polices are
+The built-in policies are
=20
 @itemize @bullet
=20
@@ -488,7 +459,7 @@
 performed is that the password is at least six characters long.
=20
 To check the password policy settings, use the command
- at command{password-quality} in @command{kadmin} program. The password
+ at command{verify-password-quality} in @command{kadmin} program. The password
 verification is only performed locally, on the client.  It may be
 convenient to set the environment variable @samp{KRB5_CONFIG} to point
 to a test version of @file{krb5.conf} while you're testing the
@@ -555,7 +526,7 @@
 @node Incremental propagation, Encryption types and salting, Slave Servers=
, Setting up a realm
 @section Incremental propagation
=20
-There is also a newer, and still somewhat experimental, mechanism for
+There is also a newer mechanism for
 doing incremental propagation in Heimdal.  Instead of sending the whole
 database regularly, it sends the changes as they happen on the master to
 the slaves.  The master keeps track of all the changes by assigning a
@@ -572,6 +543,14 @@
 or the whole database in a @samp{TELLYOUEVERYTHING} message.  There is
 also a keep-alive protocol that makes sure all slaves are up and running.
=20
+In addition on listening on the network to get connection from new
+slaves, the ipropd-master also listens on a status unix
+socket. kadmind and kpasswdd both open that socket when a transation
+is done and written a notification to the socket. That cause
+ipropd-master to check for new version in the log file. As a fallback in
+case a notification is lost by the unix socket, the log file is
+checked after 30 seconds of no event.
+
 @subsection Configuring incremental propagation
=20
 The program that runs on the master is @command{ipropd-master} and all
@@ -596,6 +575,11 @@
 master# /usr/heimdal/sbin/ktutil get iprop/`hostname`
 @end example
=20
+ at example
+slave# /usr/heimdal/sbin/ktutil get iprop/`hostname`
+ at end example
+
+
 The next step is to start the @command{ipropd-master} process on the master
 server.  The @command{ipropd-master} listens on the UNIX domain socket
 @file{/var/heimdal/signal} to know when changes have been made to the
@@ -612,7 +596,7 @@
 To manage the iprop log file you should use the @command{iprop-log}
 command. With it you can dump, truncate and replay the logfile.
=20
- at node Encryption types and salting, Cross realm, Incremental propagation, =
Setting up a realm
+ at node Encryption types and salting, Credential cache server - KCM, Increme=
ntal propagation, Setting up a realm
 @section Encryption types and salting
 @cindex Salting
 @cindex Encryption types
@@ -673,7 +657,76 @@
=20
 @end itemize
=20
- at node Cross realm, Transit policy, Encryption types and salting, Setting u=
p a realm
+ at node Credential cache server - KCM, Cross realm, Encryption types and sal=
ting, Setting up a realm
+ at section Credential cache server - KCM
+ at cindex KCM
+ at cindex Credential cache server
+
+When KCM running is easy for users to switch between different
+kerberos principals using @file{kswitch} or built in support in
+application, like OpenSSH's GSSAPIClientIdentity.
+
+Other advantages are that there is the long term credentials are not
+written to disk and on reboot the credential is removed when kcm
+process stopps running.
+
+Configure the system startup script to start the kcm process,
+ at file{/usr/heimdal/libexec/kcm} and then configure the system to use kcm i=
n @file{krb5.conf}.
+
+ at example
+[libdefaults]
+	default_cc_type =3D KCM
+ at end example
+
+Now when you run @command{kinit} it doesn't overwrite your existing
+credentials but rather just add them to the set of
+credentials. @command{klist -l} lists the credentials and the star
+marks the default credential.
+
+ at example
+$ kinit lha@@KTH.SE
+lha@@KTH.SE's Password:=20
+$ klist -l
+  Name         Cache name               Expires        =20
+lha@@KTH.SE   0                        Nov 22 23:09:40   *
+lha@@SU.SE    Initial default ccache   Nov 22 14:14:24  =20
+ at end example
+
+When switching between credentials you can use @command{kswitch}.
+
+ at example
+$ kswitch -i
+     Principal
+1    lha@@KTH.SE
+2    lha@@SU.SE
+Select number: 2
+ at end example
+
+After switching, a new set of credentials are used as default.
+
+ at example
+$ klist -l
+  Name         Cache name               Expires        =20
+lha@@SU.SE    Initial default ccache   Nov 22 14:14:24   *
+lha@@KTH.SE   0                        Nov 22 23:09:40  =20
+ at end example
+
+Som applications, like openssh with Simon Wilkinsons patch applied,
+support specifiying that credential to use.  The example below will
+login to the host computer.kth.se using lha@@KTH.SE (not the current
+default credential).
+
+ at example
+$ ssh \
+   -o GSSAPIAuthentication=3Dyes \
+   -o GSSAPIKeyExchange=3Dyes \
+   -o GSSAPIClientIdentity=3Dlha@@KTH.SE \
+   computer.kth.se
+ at end example
+
+
+
+ at node Cross realm, Transit policy, Credential cache server - KCM, Setting =
up a realm
 @section Cross realm
 @cindex Cross realm
=20
@@ -740,17 +793,36 @@
 @section Transit policy
 @cindex Transit policy
=20
-If you want to use cross realm authentication through an intermediate
-realm, it must be explicitly allowed by either the KDCs or the server
-receiving the request. This is done in @file{krb5.conf} in the
+Under some circumstances, you may not wish to set up direct
+cross-realm trust with every realm to which you wish to authenticate
+or from which you wish to accept authentications. Kerberos supports
+multi-hop cross-realm trust where a client principal in realm A
+authenticates to a service in realm C through a realm B with which
+both A and C have cross-realm trust relationships. In this situation,
+A and C need not set up cross-realm principals between each other.
+
+If you want to use cross-realm authentication through an intermediate
+realm, it must be explicitly allowed by either the KDCs for the realm
+to which the client is authenticating (in this case, realm C), or the
+server receiving the request. This is done in @file{krb5.conf} in the
 @code{[capaths]} section.
=20
+In addition, the client in realm A need to be configured to know how
+to reach realm C via realm B. This can be done either on the client or
+via KDC configuration in the KDC for realm A.
+
+ at subsection Allowing cross-realm transits
+
 When the ticket transits through a realm to another realm, the
 destination realm adds its peer to the "transited-realms" field in the
-ticket. The field is unordered, since there is no way to know if
-know if one of the transited-realms changed the order of the list.
+ticket. The field is unordered, since there is no way to know if know
+if one of the transited-realms changed the order of the list. For the
+authentication to be accepted by the final destination realm, all of
+the transited realms must be listed as trusted in the @code{[capaths]}
+configuration, either in the KDC for the destination realm or on the
+server receiving the authentication.
=20
-The syntax for @code{[capaths]} section:
+The syntax for @code{[capaths]} section is:
=20
 @example
 [capaths]
@@ -759,11 +831,15 @@
         @}
 @end example
=20
-The realm @code{STACKEN.KTH.SE} allows clients from @code{SU.SE} and
- at code{DSV.SU.SE} to cross it. Since @code{STACKEN.KTH.SE} only has
-direct cross realm setup with @code{KTH.SE}, and @code{DSV.SU.SE} only
-has direct cross realm setup with @code{SU.SE} they need to use both
- at code{SU.SE} and @code{KTH.SE} as transit realms.
+In the following example, the realm @code{STACKEN.KTH.SE} only has
+direct cross-realm set up with @code{KTH.SE}.  @code{KTH.SE} has
+direct cross-realm set up with @code{STACKEN.KTH.SE} and @code{SU.SE}.
+ at code{DSV.SU.SE} only has direct cross-realm set up with @code{SU.SE}.
+The goal is to allow principals in the @code{DSV.SU.SE} or
+ at code{SU.SE} realms to authenticate to services in
+ at code{STACKEN.KTH.SE}.  This is done with the following
+ at code{[capaths]} entry on either the server accepting authentication
+or on the KDC for @code{STACKEN.KTH.SE}.
=20
 @example
 [capaths]
@@ -773,17 +849,100 @@
 	DSV.SU.SE =3D @{
                     STACKEN.KTH.SE =3D SU.SE KTH.SE
 	@}
+ at end example
=20
- at end example
+The first entry allows cross-realm authentication from clients in
+ at code{SU.SE} transiting through @code{KTH.SE} to
+ at code{STACKEN.KTH.SE}.  The second entry allows cross-realm
+authentication from clients in @code{DSV.SU.SE} transiting through
+both @code{SU.SE} and @code{KTH.SE} to @code{STACKEN.KTH.SE}.
+
+Be careful of which realm goes where; it's easy to put realms in the
+wrong place.  The block is tagged with the client realm (the realm of
+the principal authenticating), and the realm before the equal sign is
+the final destination realm: the realm to which the client is
+authenticating.  After the equal sign go all the realms that the
+client transits through.
=20
 The order of the @code{PERMITTED-CROSS-REALMS} is not important when
 doing transit cross realm verification.
=20
-However, the order is important when the @code{[capaths]} section is used
-to figure out the intermediate realm to go to when doing multi-realm
-transit. When figuring out the next realm, the first realm of the list
-of @code{PERMITTED-CROSS-REALMS} is chosen. This is done in both the
-client kerberos library and the KDC.
+ at subsection Configuring client cross-realm transits
+
+The @code{[capaths]} section is also used for another purpose: to tell
+clients which realm to transit through to reach a realm with which
+their local realm does not have cross-realm trust.  This can be done
+by either putting a @code{[capaths]} entry in the configuration of the
+client or by putting the entry in the configuration of the KDC for the
+client's local realm.  In the latter case, the KDC will then hand back
+a referral to the client when the client requests a cross-realm ticket
+to the destination realm, telling the client to try to go through an
+intermediate realm.
+
+For client configuration, the order of @code{PERMITTED-CROSS-REALMS}
+is significant, since only the first realm in this section (after the
+equal sign) is used by the client.
+
+For example, again consider the @code{[capaths]} entry above for the
+case of a client in the @code{SU.SE} realm, and assume that the client
+or the @code{SU.SE} KDC has that @code{[capaths]} entry.  If the
+client attempts to authenticate to a service in the
+ at code{STACKEN.KTH.SE} realm, that entry says to first authenticate
+cross-realm to the @code{KTH.SE} realm (the first realm listed in the
+ at code{PERMITTED-CROSS-REALMS} section), and then from there to
+ at code{STACKEN.KTH.SE}.
+
+Each entry in @code{[capaths]} can only give the next hop, since only
+the first realm in @code{PERMITTED-CROSS-REALMS} is used.  If, for
+instance, a client in @code{DSV.SU.SE} had a @code{[capaths]}
+configuration as above but without the first block for @code{SU.SE},
+they would not be able to reach @code{STACKEN.KTH.SE}.  They would get
+as far as @code{SU.SE} based on the @code{DSV.SU.SE} entry in
+ at code{[capaths]} and then attempt to go directly from there to
+ at code{STACKEN.KTH.SE} and get stuck (unless, of course, the
+ at code{SU.SE} KDC had the additional entry required to tell the client
+to go through @code{KTH.SE}).
+
+ at subsection Active Directory forest example
+
+One common place where a @code{[capaths]} configuration is desirable
+is with Windows Active Directory forests.  One common Active Directory
+configuration is to have one top-level Active Directory realm but then
+divide systems, services, and users into child realms (perhaps based
+on organizational unit).  One generally establishes cross-realm trust
+only with the top-level realm, and then uses transit policy to permit
+authentications to and from the child realms.
+
+For example, suppose an organization has a Heimdal realm
+ at code{EXAMPLE.COM}, a Windows Active Directory realm
+ at code{WIN.EXAMPLE.COM}, and then child Active Directory realms
+ at code{ENGR.WIN.EXAMPLE.COM} and @code{SALES.WIN.EXAMPLE.COM}.  The
+goal is to allow users in any of these realms to authenticate to
+services in any of these realms.  The @code{EXAMPLE.COM} KDC (and
+possibly client) configuration should therefore contain a
+ at code{[capaths]} section as follows:
+
+ at example
+[capaths]
+	ENGR.WIN.EXAMPLE.COM =3D @{
+		EXAMPLE.COM =3D WIN.EXAMPLE.COM
+	@}
+	SALES.WIN.EXAMPLE.COM =3D @{
+		EXAMPLE.COM =3D WIN.EXAMPLE.COM
+	@}
+	EXAMPLE.COM =3D @{
+		ENGR.WIN.EXAMPLE.COM =3D WIN.EXAMPLE.COM
+		SALES.WIN.EXAMPLE.COM =3D WIN.EXAMPLE.COM
+	@}
+ at end example
+
+The first two blocks allow clients in the @code{ENGR.WIN.EXAMPLE.COM}
+and @code{SALES.WIN.EXAMPLE.COM} realms to authenticate to services in
+the @code{EXAMPLE.COM} realm.  The third block tells the client (or
+tells the KDC to tell the client via referrals) to transit through
+ at code{WIN.EXAMPLE.COM} to reach these realms.  Both sides of the
+configuration are needed for bi-directional transited cross-realm
+authentication.
=20
 @c To test the cross realm configuration, use:
 @c    kmumble transit-check client server transit-realms ...
@@ -863,6 +1022,8 @@
 secure fashion. A knowledge of LDAP, Kerberos, and C is necessary to
 install this backend. The HDB schema was devised by Leif Johansson.
=20
+This assumes, OpenLDAP 2.3 or later.
+
 Requirements:
=20
 @itemize @bullet
@@ -880,9 +1041,7 @@
 see option --hdb-openldap-module to configure.
=20
 @item
-OpenLDAP 2.0.x. Configure OpenLDAP with @kbd{--enable-local} to enable the
-local transport. (A patch to support SASL EXTERNAL authentication is
-necessary in order to use OpenLDAP 2.1.x.)
+Configure OpenLDAP with @kbd{--enable-local} to enable the local transport.
=20
 @item
 Add the hdb schema to the LDAP server, it's included in the source-tree
@@ -901,7 +1060,7 @@
         by dn.exact=3D"uid=3Dheimdal,dc=3Dservices,dc=3Dexample,dc=3Dcom" =
write
         ...
=20
-sasl-regexp "uidNumber=3D0\\\+gidNumber=3D.*,cn=3Dpeercred,cn=3Dexternal,c=
n=3Dauth"
+authz-regexp "gidNumber=3D.*\\\+uidNumber=3D0,cn=3Dpeercred,cn=3Dexternal,=
cn=3Dauth''
 	"uid=3Dheimdal,dc=3Dservices,dc=3Dexample,dc=3Dcom"
=20
 @end example
@@ -970,7 +1129,7 @@
 kadmin> init EXAMPLE.COM
 Realm max ticket life [unlimited]:
 Realm max renewable ticket life [unlimited]:
-kadmin> ank lukeh
+kadmin> add lukeh
 Max ticket life [1 day]:
 Max renewable life [1 week]:
 Principal expiration time [never]:
@@ -1004,6 +1163,14 @@
=20
 @end itemize
=20
+ at subsection smbk5pwd overlay
+
+The smbk5pwd overlay, updates the krb5Key and krb5KeyVersionNumber
+appropriately when it receives an LDAP Password change Extended
+Operation:
+
+ at url{http://www.openldap.org/devel/cvsweb.cgi/contrib/slapd-modules/smbk5p=
wd/README?hideattic=3D1&sortbydate=3D0}
+
 @subsection Troubleshooting guide
=20
 @url{https://sec.miljovern.no/bin/view/Info/TroubleshootingGuide}
@@ -1073,21 +1240,22 @@
 @end example
=20
=20
- at node Setting up PK-INIT, , Providing Kerberos credentials to servers and =
programs, Setting up a realm
+ at node Setting up PK-INIT, Debugging Kerberos problems, Providing Kerberos =
credentials to servers and programs, Setting up a realm
 @section Setting up PK-INIT
=20
-PK-INIT is levering the existing PKI infrastructure to use
-certificates to get the initial ticket, that is usually the krbtgt.
+PK-INIT leverages an existing PKI (public key infrastructure), using
+certificates to get the initial ticket (usually the krbtgt
+ticket-granting ticket).
=20
-To use PK-INIT you must first have a PKI, so if you don't have one,
-it is time to create it. Note that you should read the whole chapter
-of the document to see the requirements on the CA software.
+To use PK-INIT you must first have a PKI. If you don't have one, it is
+time to create it. You should first read the whole chapter of the
+document to see the requirements imposed on the CA software.
=20
-There needs to exist a mapping between the certificate and what
-principals that certificate is allowed to use. There are several ways
-to do this. The administrator can use a configuration file, storing
-the principal in the SubjectAltName extension of the certificate, or store=
 the
-mapping in the principals entry in the kerberos database.
+A mapping between the PKI certificate and what principals that
+certificate is allowed to use must exist. There are several ways to do
+this. The administrator can use a configuration file, store the
+principal in the SubjectAltName extension of the certificate, or store
+the mapping in the principals entry in the kerberos database.
=20
 @section Certificates
=20
@@ -1097,27 +1265,28 @@
=20
 @subsection KDC certificate
=20
-The certificate for the KDC have serveral requirements.
+The certificate for the KDC has serveral requirements.
=20
-First the certificate should have an Extended Key Usage (EKU)
-id-pkkdcekuoid (1.3.6.1.5.2.3.5) set. Second there must be a
-subjectAltName otherName using oid id-pkinit-san (1.3.6.1.5.2.2) in
+First, the certificate should have an Extended Key Usage (EKU)
+id-pkkdcekuoid (1.3.6.1.5.2.3.5) set. Second, there must be a
+subjectAltName otherName using OID id-pkinit-san (1.3.6.1.5.2.2) in
 the type field and a DER encoded KRB5PrincipalName that matches the
-name of the TGS of the target realm.
+name of the TGS of the target realm.  Also, if the certificate has a
+nameConstraints extention with a Generalname with dNSName or iPAdress,
+it must match the hostname or adress of the KDC.
=20
-Both of these two requirements are not required by the standard to be
-checked by the client if it have external information what the
-certificate the KDC is supposed to be used. So it's in the interest of
-minimum amount of configuration on the clients they should be included.
+The client is not required by the standard to check the server
+certificate for this information if the client has external
+information confirming which certificate the KDC is supposed to be
+using. However, adding this information to the KDC certificate removes
+the need to specially configure the client to recognize the KDC
+certificate.
=20
 Remember that if the client would accept any certificate as the KDC's
 certificate, the client could be fooled into trusting something that
 isn't a KDC and thus expose the user to giving away information (like
-password or other private information) that it is supposed to secret.
-
-Also, if the certificate has a nameConstraints extention with a
-Generalname with dNSName or iPAdress it must match the hostname or
-adress of the KDC.
+a password or other private information) that it is supposed to keep
+secret.
=20
 @subsection Client certificate
=20
@@ -1128,14 +1297,23 @@
 certificate and thus delegate responsibility to do the mapping between
 certificates and principals to the CA.
=20
+This behavior is controlled by KDC configuration option:
+
+ at example
+[kdc]
+	pkinit_principal_in_certificate =3D yes
+ at end example
+
 @subsubsection Using KRB5PrincipalName in id-pkinit-san
=20
-OtherName extention in the GeneralName is used to do the
-mapping between certifiate and principal in the certifiate or storing
-the krbtgt principal in the KDC certificate.
+The OtherName extention in the GeneralName is used to do the mapping
+between certificate and principal.  For the KDC certificate, this
+stores the krbtgt principal name for that KDC.  For the client
+certificate, this stores the principal for which that certificate is
+allowed to get tickets.
=20
 The principal is stored in a SubjectAltName in the certificate using
-OtherName. The oid in the type is id-pkinit-san.
+OtherName. The OID in the type is id-pkinit-san.
=20
 @example
 id-pkinit-san OBJECT IDENTIFIER ::=3D @{ iso (1) org (3) dod (6)
@@ -1152,32 +1330,32 @@
 @}
 @end example
=20
-where Realm and PrincipalName is defined by the Kerberos ASN.1 specificati=
on.
+where Realm and PrincipalName is defined by the Kerberos ASN.1
+specification.
=20
 @section Naming certificate using hx509
=20
 hx509 is the X.509 software used in Heimdal to handle
-certificates. hx509 uses different syntaxes to specify the different
-formats the certificates are stored in and what formats they exist in.
+certificates. hx509 supports several different syntaxes for specifying
+certificate files or formats. Several formats may be used:  PEM,
+certificates embedded in PKCS#12 files, certificates embedded in
+PKCS#11 devices, and raw DER encoded certificates.
=20
-There are several formats that can be used, PEM, embedded into PKCS12
-files, embedded into PKCS11 devices and raw DER encoded certificates.
-Below is a list of types to use.
-
+Those formats may be specified as follows:
=20
 @table @asis
=20
 @item DIR:
=20
-DIR is reading all certificates in a directory that is DER or PEM
-formatted.
+DIR specifies a directory which contains certificates in the DER or
+PEM format.
=20
 The main feature of DIR is that the directory is read on demand when
-iterating over certificates, that way applictions can for some cases
-avoid to store all certificates in memory. It's very useful for tests
-that iterate over larger amount of certificates.
+iterating over certificates. This allows applications, in some
+situations, to avoid having to store all certificates in memory.  It's
+very useful for tests that iterate over large numbers of certificates.
=20
-Syntax is:
+The syntax is:
=20
 @example
 DIR:/path/to/der/files
@@ -1185,15 +1363,16 @@
=20
 @item FILE:
=20
-FILE: is used to have the lib pick up a certificate chain and a
-private key. The file can be either a PEM (openssl) file or a raw DER
-encoded certificate. If it's a PEM file it can contain several keys and
+FILE: specifies a file that contains a certificate or private key.
+The file can be either a PEM (openssl) file or a raw DER encoded
+certificate. If it's a PEM file, it can contain several keys and
 certificates and the code will try to match the private key and
-certificate together.
+certificate together. Multiple files may be specified, separated by
+commas.
=20
-Its useful to have one PEM file that contains all the trust anchors.
+It's useful to have one PEM file that contains all the trust anchors.
=20
-Syntax is:
+The syntax is:
=20
 @example
 FILE:certificate.pem,private-key.key,other-cert.pem,....
@@ -1201,11 +1380,12 @@
=20
 @item PKCS11:
=20
-PKCS11: is used to handle smartcards via PKCS11 drivers, for example
-soft-token, opensc, or muscle. The default is to use all slots on the
-device/token.
+PKCS11: is used to handle smartcards via PKCS#11 drivers, such as
+soft-token, opensc, or muscle. The argument specifies a shared object
+that implements the PKCS#11 API. The default is to use all slots on
+the device/token.
=20
-Syntax is:
+The syntax is:
=20
 @example
 PKCS11:shared-object.so
@@ -1213,10 +1393,10 @@
=20
 @item PKCS12:
=20
-PKCS12: is used to handle PKCS12 files. PKCS12 files commonly have the
-extension pfx or p12.
+PKCS12: is used to handle PKCS#12 files. PKCS#12 files commonly have
+the extension pfx or p12.
=20
-Syntax is:
+The syntax is:
=20
 @example
 PKCS12:/path/to/file.pfx
@@ -1227,8 +1407,8 @@
 @section Configure the Kerberos software
=20
 First configure the client's trust anchors and what parameters to
-verify, see subsection below how to do that. Now you can use kinit to
-get yourself tickets. One example how that can look like is:
+verify. See the subsections below for how to do that. Then, you can
+use kinit to get yourself tickets. For example:
=20
 @example
 $ kinit -C FILE:$HOME/.certs/lha.crt,$HOME/.certs/lha.key lha@@EXAMPLE.ORG
@@ -1241,10 +1421,10 @@
 Apr 20 02:08:08  Apr 20 12:08:08  krbtgt/EXAMPLE.ORG@@EXAMPLE.ORG
 @end example
=20
-Using PKCS11 it can look like this instead:
+Using PKCS#11 it can look like this instead:
=20
 @example
-$ kinit -C PKCS11:/tmp/pkcs11/lib/soft-pkcs11.so lha@@EXAMPLE.ORG
+$ kinit -C PKCS11:/usr/heimdal/lib/hx509.so lha@@EXAMPLE.ORG
 PIN code for SoftToken (slot):
 $ klist
 Credentials cache: API:4
@@ -1254,8 +1434,7 @@
 Mar 26 23:40:10  Mar 27 09:40:10  krbtgt/EXAMPLE.ORG@@EXAMPLE.ORG
 @end example
=20
-
-Write about the kdc.
+TODO: Write about the KDC.
=20
 @section Configure the client
=20
@@ -1282,8 +1461,9 @@
 	pkinit_anchors =3D FILE:/path/to/trust-anchors.pem
 	pkinit_pool =3D PKCS12:/path/to/useful-intermediate-certs.pfx
 	pkinit_pool =3D FILE:/path/to/other-useful-intermediate-certs.pem
-	pkinit_allow_proxy_certificate =3D false
+	pkinit_allow_proxy_certificate =3D no
 	pkinit_win2k_require_binding =3D yes
+	pkinit_principal_in_certificate =3D no
 @end example
=20
 @subsection Using pki-mapping file
@@ -1303,10 +1483,11 @@
=20
 @subsection Generate certificates
=20
-First you need to generate a CA certificate, change the --subject to
-something appropriate, the CA certificate will be valid for 10 years.
+First, you need to generate a CA certificate. This example creates a
+CA certificate that will be valid for 10 years.
=20
-You need to change --subject in the command below.
+You need to change --subject in the command below to something
+appropriate for your site.
=20
 @example
 hxtool issue-certificate \
@@ -1322,7 +1503,8 @@
 type ``pkinit-kdc'' and set the PK-INIT specifial SubjectAltName to the
 name of the krbtgt of the realm.
=20
-You need to change --subject and --pk-init-principal in the command below.
+You need to change --subject and --pk-init-principal in the command
+below to something appropriate for your site.
=20
 @example
 hxtool issue-certificate \
@@ -1334,12 +1516,14 @@
     --certificate=3D"FILE:kdc.pem"
 @end example
=20
-The users also needs to have a certificate, so generate a certificate
-of the type ``pkinit-client''. The client doesn't need to have the PK-INIT
-SubjectAltName set, you can have the Subject DN in the ACL file
-(pki-mapping) instead.
+The users also needs to have certificates. For your first client,
+generate a certificate of type ``pkinit-client''. The client doesn't
+need to have the PK-INIT SubjectAltName set; you can have the Subject
+DN in the ACL file (pki-mapping) instead.
=20
-You need to change --subject and --pk-init-principal in the command below.
+You need to change --subject and --pk-init-principal in the command
+below to something appropriate for your site. You can omit
+--pk-init-principal if you're going to use the ACL file instead.
=20
 @example
 hxtool issue-certificate \
@@ -1353,9 +1537,10 @@
=20
 @subsection Validate the certificate
=20
-hxtool also contains a tool that will validate certificates according to
-rules from the PKIX document. These checks are not complete, but a good te=
st
-to check if you got all of the basic bits right in your certificates.
+hxtool also contains a tool that will validate certificates according
+to rules from the PKIX document. These checks are not complete, but
+they provide a good test of whether you got all of the basic bits
+right in your certificates.
=20
 @example
 hxtool validate FILE:user.pem
@@ -1368,7 +1553,7 @@
=20
 @subsection Using OpenSSL to create certificates with krb5PrincipalName
=20
-To make OpenSSL create certificates with krb5PrincipalName use
+To make OpenSSL create certificates with krb5PrincipalName, use an
 @file{openssl.cnf} as described below. To see a complete example of
 creating client and KDC certificates, see the test-data generation
 script @file{lib/hx509/data/gen-req.sh} in the source-tree. The
@@ -1395,7 +1580,7 @@
=20
 @end example
=20
-Command usage
+Command usage:
=20
 @example
 openssl x509 -extensions user_certificate
@@ -1425,9 +1610,9 @@
 windows uses pre-standard format and this can't be autodetected.
=20
 The pkinit_win2k_require_binding option requires the reply for the KDC
-to be of the new, secure, type that binds the request to reply. Before
-clients should fake the reply from the KDC. To use this option you
-have to apply a fix from Microsoft.
+to be of the new, secure, type that binds the request to
+reply. Before, clients could fake the reply from the KDC. To use this
+option you have to apply a fix from Microsoft.
=20
 @example
 [realms]
@@ -1440,16 +1625,32 @@
 @subsection Certificates
=20
 The client certificates need to have the extended keyusage ``Microsoft
-Smartcardlogin'' (openssl have the oid shortname msSmartcardLogin).
+Smartcardlogin'' (openssl has the OID shortname msSmartcardLogin).
=20
 See Microsoft Knowledge Base Article - 281245 ``Guidelines for Enabling
 Smart Card Logon with Third-Party Certification Authorities'' for a
-more extensive description of how set setup an external CA to it
-includes all information that will make a Windows KDC happy.
+more extensive description of how set setup an external CA so that it
+includes all the information required to make a Windows KDC happy.
=20
 @subsection Configure Windows 2000 CA
=20
-To enable Microsoft Smartcardlogin> for certificates in your Windows
-2000 CA, you want to look at Microsoft Knowledge Base Article -
-313274 ``HOW TO: Configure a Certification Authority to Issue
-Smart Card Certificates in Windows''.
+To enable Microsoft Smartcardlogin for certificates in your Windows
+2000 CA, you want to look at Microsoft Knowledge Base Article - 313274
+``HOW TO: Configure a Certification Authority to Issue Smart Card
+Certificates in Windows''.
+
+ at node Debugging Kerberos problems, , Setting up PK-INIT, Setting up a realm
+ at section Debugging Kerberos problems
+
+To debug Kerberos client and server problems you can enable debug
+traceing by adding the following to @file{/etc/krb5,conf}. Note that the
+trace logging is sparse at the moment, but will continue to improve.
+
+ at example
+[logging]
+        libkrb5 =3D 0-/SYSLOG:
+ at end example
+
+
+
+
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/vars.texi
--- a/head/crypto/heimdal/doc/vars.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/vars.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -4,4 +4,4 @@
 @c
=20
 @set dbdir /var/heimdal
- at set PACKAGE_VERSION 1.1
+ at set PACKAGE_VERSION 1.5.2
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/whatis.texi
--- a/head/crypto/heimdal/doc/whatis.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/whatis.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
- at c $Id: whatis.texi 16769 2006-02-27 12:26:50Z joda $
+ at c $Id$
=20
 @node What is Kerberos?, Building and Installing, Introduction, Top
 @chapter What is Kerberos?
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/doc/win2k.texi
--- a/head/crypto/heimdal/doc/win2k.texi	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/doc/win2k.texi	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,36 @@
- at c $Id: win2k.texi 21991 2007-10-19 13:28:07Z lha $
+ at c $Id$
=20
- at node Windows 2000 compatability, Programming with Kerberos, Kerberos 4 is=
sues, Top
+
+ at node Windows compatibility, Programming with Kerberos, Kerberos 4 issues,=
 Top
 @comment  node-name,  next,  previous,  up
- at chapter Windows 2000 compatability
+ at chapter Windows compatibility
=20
-Windows 2000 (formerly known as Windows NT 5) from Microsoft implements
-Kerberos 5.  Their implementation, however, has some quirks,
-peculiarities, and bugs.  This chapter is a short summary of the things
-that we have found out while trying to test Heimdal against Windows
-2000.  Another big problem with the Kerberos implementation in Windows
-2000 is that the available documentation is more focused on getting
+Microsoft Windows, starting from version 2000 (formerly known as Windows N=
T 5), implements Kerberos 5. Their implementation, however, has some quirks,
+peculiarities, and bugs. This chapter is a short summary of the compatibil=
ity
+issues between Heimdal and various Windows versions.
+
+The big problem with the Kerberos implementation in Windows
+is that the available documentation is more focused on getting
 things to work rather than how they work, and not that useful in figuring
-out how things really work.
-
-This information should apply to Heimdal @value{VERSION} and Windows
-2000 Professional.  It's of course subject to change all the time and
+out how things really work. It's of course subject to change all the time =
and
 mostly consists of our not so inspired guesses.  Hopefully it's still
 somewhat useful.
=20
 @menu
-* Configuring Windows 2000 to use a Heimdal KDC:: =20
-* Inter-Realm keys (trust) between Windows 2000 and a Heimdal KDC:: =20
+* Configuring Windows to use a Heimdal KDC:: =20
+* Inter-Realm keys (trust) between Windows and a Heimdal KDC:: =20
 * Create account mappings::    =20
 * Encryption types::           =20
 * Authorisation data::         =20
 * Quirks of Windows 2000 KDC:: =20
-* Useful links when reading about the Windows 2000:: =20
+* Useful links when reading about the Windows:: =20
 @end menu
=20
- at node Configuring Windows 2000 to use a Heimdal KDC, Inter-Realm keys (tru=
st) between Windows 2000 and a Heimdal KDC, Windows 2000 compatability, Win=
dows 2000 compatability
+ at node Configuring Windows to use a Heimdal KDC, Inter-Realm keys (trust) b=
etween Windows and a Heimdal KDC, Windows compatibility, Windows compatibil=
ity
 @comment node-name, next, precious, up
- at section Configuring Windows 2000 to use a Heimdal KDC
+ at section Configuring Windows to use a Heimdal KDC
=20
-You need the command line program called @command{ksetup.exe} which is ava=
ilable
-in the file @file{SUPPORT/TOOLS/SUPPORT.CAB} on the Windows 2000 Professio=
nal
-CD-ROM. This program is used to configure the Kerberos settings on a
-Workstation.
+You need the command line program called @command{ksetup.exe}. This progra=
m comes with the Windows Support Tools, available from either the installat=
ion CD-ROM (@file{SUPPORT/TOOLS/SUPPORT.CAB}), or from Microsoft web site. =
Starting from Windows 2008, it is already installed. This program is used t=
o configure the Kerberos settings on a Workstation.
=20
 @command{Ksetup} store the domain information under the registry key:
 @code{HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\Kerberos\Dom=
ains}.
@@ -88,13 +83,13 @@
 for example @samp{nisse} to the principal @samp{nisse@@MY.REALM}.
 (This is most likely what you want.)
=20
- at node Inter-Realm keys (trust) between Windows 2000 and a Heimdal KDC, Cre=
ate account mappings, Configuring Windows 2000 to use a Heimdal KDC, Window=
s 2000 compatability
+ at node Inter-Realm keys (trust) between Windows and a Heimdal KDC, Create a=
ccount mappings, Configuring Windows to use a Heimdal KDC, Windows compatib=
ility
 @comment node-name, next, precious, up
- at section Inter-Realm keys (trust) between Windows 2000 and a Heimdal KDC
+ at section Inter-Realm keys (trust) between Windows and a Heimdal KDC
=20
 See also the Step-by-Step guide from Microsoft, referenced below.
=20
-Install Windows 2000, and create a new controller (Active Directory
+Install Windows, and create a new controller (Active Directory
 Server) for the domain.
=20
 By default the trust will be non-transitive. This means that only users
@@ -102,8 +97,8 @@
 to transitive by using the @command{netdom.exe} tool. @command{netdom.exe}=20
 can also be used to add the trust between two realms.
=20
-You need to tell Windows 2000 on what hosts to find the KDCs for the
-non-Windows realm with @command{ksetup}, see @xref{Configuring Windows 2000
+You need to tell Windows on what hosts to find the KDCs for the
+non-Windows realm with @command{ksetup}, see @xref{Configuring Windows=20
 to use a Heimdal KDC}.
=20
 This needs to be done on all computers that want enable cross-realm
@@ -127,33 +122,37 @@
 netdom trust NT.REALM.EXAMPLE.COM /Domain:EXAMPLE.COM /add /realm /passwor=
dt:TrustPassword
 @end example
=20
-You also need to add the inter-realm keys to the Heimdal KDC. Make sure
-you have matching encryption types (DES, Arcfour and AES in case of Longho=
rn)
+You also need to add the inter-realm keys to the Heimdal KDC. But take
+care to the encryption types and salting used for those keys. There should=
 be
+no encryption type stronger than the one configured on Windows side for th=
is
+relationship, itself limited to the ones supported by this specific versio=
n of
+Windows, nor any Kerberos 4 salted hashes, as Windows does not seem to
+understand them. Otherwise, the trust will not works.
=20
-Another issue is salting.  Since Windows 2000 does not seem to
-understand Kerberos 4 salted hashes you might need to turn off anything
-similar to the following if you have it, at least while adding the
-principals that are going to share keys with Windows 2000.
+Here are the version-specific needed information:
+ at enumerate
+ at item Windows 2000: maximum encryption type is DES
+ at item Windows 2003: maximum encryption type is DES
+ at item Windows 2003RC2: maximum encryption type is RC4, relationship defaul=
ts to DES
+ at item Windows 2008: maximum encryption type is AES, relationship defaults =
to RC4
+ at end enumerate
+
+For Windows 2003RC2, to change the trust encryption type, you have to use =
the
+ at command{ktpass}, from the Windows 2003 Resource kit *service pack2*, avai=
lable
+from Microsoft web site.
=20
 @example
-[kadmin]
-        default_keys =3D v5 v4
+C:> ktpass /MITRealmName UNIX.EXAMPLE.COM /TrustEncryp RC4=20
 @end example
=20
-So remove v4 from default keys.
-
-What you probably want to use is this:
+For Windows 2008, the same operation can be done with the @command{ksetup}=
, installed by default.
=20
 @example
-[kadmin]
-        default_keys =3D des-cbc-crc:pw-salt arcfour-hmac-md5:pw-salt
+C:> ksetup /SetEncTypeAttre EXAMPLE.COM AES256-SHA1=20
 @end example
=20
- at c XXX check this
- at c It is definitely not supported in base 2003.  I haven't been able to
- at c get SP1 installed here, but it is supposed to work in that.
-
-Once that is also done, you can add the required inter-realm keys:
+Once the relationship is correctly configured, you can add the required
+inter-realm keys, using heimdal default encryption types:
=20
 @example
 kadmin add krbtgt/NT.REALM.EXAMPLE.COM@@EXAMPLE.COM
@@ -162,11 +161,20 @@
=20
 Use the same passwords for both keys.
=20
+And if needed, to remove unsupported encryptions, such as the following on=
es for a Windows 2003RC2 server.
+
+ at example
+kadmin del_enctype krbtgt/REALM.EXAMPLE.COM@@NT.EXAMPLE.COM aes256-cts-hma=
c-sha1-96
+kadmin del_enctype krbtgt/REALM.EXAMPLE.COM@@NT.EXAMPLE.COM des3-cbc-sha1
+kadmin del_enctype krbtgt/NT.EXAMPLE.COM@@EXAMPLE.COM aes256-cts-hmac-sha1=
-96
+kadmin del_enctype krbtgt/NT.EXAMPLE.COM@@EXAMPLE.COM des3-cbc-sha1
+ at end example
+
 Do not forget to reboot before trying the new realm-trust (after
 running @command{ksetup}). It looks like it might work, but packets are
 never sent to the non-Windows KDC.
=20
- at node Create account mappings, Encryption types, Inter-Realm keys (trust) =
between Windows 2000 and a Heimdal KDC, Windows 2000 compatability
+ at node Create account mappings, Encryption types, Inter-Realm keys (trust) =
between Windows and a Heimdal KDC, Windows compatibility
 @comment node-name, next, precious, up
 @section Create account mappings
=20
@@ -183,7 +191,7 @@
 the Active Directory LDAP catalog. When you create users by script you
 can add this entry instead.
=20
- at node Encryption types, Authorisation data, Create account mappings, Windo=
ws 2000 compatability
+ at node Encryption types, Authorisation data, Create account mappings, Windo=
ws compatibility
 @comment  node-name,  next,  previous,  up
 @section Encryption types
=20
@@ -195,7 +203,7 @@
 only have MD4 passwords and will need a password change to get a DES
 key.
=20
- at node Authorisation data, Quirks of Windows 2000 KDC, Encryption types, Wi=
ndows 2000 compatability
+ at node Authorisation data, Quirks of Windows 2000 KDC, Encryption types, Wi=
ndows compatibility
 @comment  node-name,  next,  previous,  up
 @section Authorisation data
=20
@@ -223,7 +231,7 @@
 analysing the data.
 @end enumerate
=20
- at node Quirks of Windows 2000 KDC, Useful links when reading about the Wind=
ows 2000, Authorisation data, Windows 2000 compatability
+ at node Quirks of Windows 2000 KDC, Useful links when reading about the Wind=
ows, Authorisation data, Windows compatibility
 @comment  node-name,  next,  previous,  up
 @section Quirks of Windows 2000 KDC
=20
@@ -255,9 +263,9 @@
 These configuration options will make sure that no checksums of the
 unsupported types are generated.
=20
- at node Useful links when reading about the Windows 2000,  , Quirks of Windo=
ws 2000 KDC, Windows 2000 compatability
+ at node Useful links when reading about the Windows,  , Quirks of Windows 20=
00 KDC, Windows compatibility
 @comment  node-name,  next,  previous,  up
- at section Useful links when reading about the Windows 2000
+ at section Useful links when reading about the Windows
=20
 See also our paper presented at the 2001 Usenix Annual Technical
 Conference, available in the proceedings or at
@@ -272,7 +280,7 @@
 @uref{http://www.microsoft.com/technet/prodtechnol/windows2000serv/howto/k=
erbstep.mspx}.
 Kerberos GSS-API (in Windows-eze SSPI), Windows as a client in a
 non-Windows KDC realm, adding unix clients to a Windows 2000 KDC, and
-adding cross-realm trust (@pxref{Inter-Realm keys (trust) between Windows =
2000
+adding cross-realm trust (@pxref{Inter-Realm keys (trust) between Windows
 and a Heimdal KDC}).
=20
 @item Windows 2000 Kerberos Authentication:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/etc/Makefile.am
--- a/head/crypto/heimdal/etc/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/etc/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
-# $Id: Makefile.am 20565 2007-04-27 13:52:30Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-EXTRA_DIST =3D services.append
+EXTRA_DIST =3D NTMakefile services.append
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/etc/Makefile.in
--- a/head/crypto/heimdal/etc/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/etc/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20565 2007-04-27 13:52:30Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D etc
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
@@ -97,49 +101,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -163,10 +176,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -183,6 +197,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -198,31 +214,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -237,10 +267,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -281,47 +313,52 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
-EXTRA_DIST =3D services.append
+EXTRA_DIST =3D NTMakefile services.append
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps etc/Makef=
ile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps etc/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign etc/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign etc/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -339,6 +376,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -368,13 +406,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -406,6 +448,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -424,6 +467,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -431,23 +476,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
@@ -469,9 +522,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: all all-am all-local check check-am check-local clean \
 	clean-generic clean-libtool dist-hook distclean \
@@ -555,6 +607,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -640,7 +695,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -653,6 +708,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/etc/services.append
--- a/head/crypto/heimdal/etc/services.append	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/etc/services.append	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #
-# $Id: services.append 10452 2001-08-08 15:48:37Z assar $
+# $Id$
 #
 # Kerberos services
 #
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/Makefile.am
--- a/head/crypto/heimdal/include/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/include/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,85 +1,105 @@
-# $Id: Makefile.am 22396 2008-01-01 19:35:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
 SUBDIRS =3D kadm5 hcrypto gssapi
=20
-noinst_PROGRAMS =3D bits make_crypto
+noinst_PROGRAMS =3D bits
 CHECK_LOCAL =3D no-check-local
=20
 AM_CPPFLAGS +=3D -DHOST=3D\"$(CANONICAL_HOST)\"
=20
 nodist_include_HEADERS =3D krb5-types.h
-nodist_noinst_HEADERS =3D crypto-headers.h
+
+noinst_HEADERS =3D heim_threads.h crypto-headers.h
+
+EXTRA_DIST =3D NTMakefile krb5-types.cross
+
+if !CROSS_COMPILE
=20
 krb5-types.h: bits$(EXEEXT)
 	./bits$(EXEEXT) krb5-types.h
=20
-crypto-headers.h: make_crypto$(EXEEXT)
-	./make_crypto$(EXEEXT) crypto-headers.h
+else
+
+krb5-types.h: krb5-types.cross
+	cp $(srcdir)/krb5-types.cross krb5-types.h
+
+endif
=20
 CLEANFILES =3D			\
-	cms_asn1.h 		\
-	der-protos.h 		\
-	digest_asn1.h 		\
-	hdb-protos.h		\
-	heim_asn1.h		\
-	heim_threads.h		\
-	hex.h			\
-	hx509-protos.h		\
-	hx509.h			\
-	hx509_err.h		\
-	kx509_asn1.h		\
-	kx509_err.h		\
-	k524_err.h		\
-	kdc-protos.h		\
-	kdc.h			\
-	krb5_asn1.h		\
-	krb5_ccapi.h		\
-	parse_bytes.h		\
-	pkcs12_asn1.h		\
-	pkcs8_asn1.h		\
-	pkcs9_asn1.h		\
-	pkinit_asn1.h		\
-	rfc2459_asn1.h		\
-	rtbl.h			\
-	test-mem.h		\
-	vers.h			\
-	vis.h			\
 	asn1.h			\
+	asn1-common.h		\
+	asn1-template.h		\
 	asn1_err.h		\
 	base64.h		\
+	cms_asn1.h 		\
+	crmf_asn1.h		\
 	com_err.h		\
 	com_right.h		\
-	crypto-headers.h	\
+	ccache_plugin.h		\
+	der-protos.h 		\
+	der-private.h 		\
 	der.h			\
+	digest_asn1.h 		\
 	editline.h		\
 	err.h			\
 	getarg.h		\
 	glob.h			\
 	gssapi.h		\
+	hdb-protos.h		\
 	hdb.h			\
 	hdb_asn1.h		\
 	hdb_err.h		\
+	heim-ipc.h		\
+	heim_asn1.h		\
 	heim_err.h		\
+	heimbase.h		\
+	heimntlm-protos.h	\
 	heimntlm.h		\
-	heimntlm-protos.h	\
+	hex.h			\
+	hx509-protos.h		\
+	hx509.h			\
+	hx509_err.h		\
+	k524_err.h		\
 	kafs.h			\
-	krb_err.h		\
+	kdc-protos.h		\
+	kdc.h			\
+	krb5-private.h		\
 	krb5-protos.h		\
-	krb5-private.h		\
 	krb5-types.h		\
 	krb5.h			\
+	krb5_asn1.h		\
+	krb5_ccapi.h		\
 	krb5_err.h		\
+	krb_err.h		\
+	kx509_asn1.h		\
+	kx509_err.h		\
+	locate_plugin.h		\
+	ntlm_err.h		\
+	ocsp_asn1.h		\
 	otp.h			\
+	parse_bytes.h		\
 	parse_time.h		\
 	parse_units.h		\
+	pkcs10_asn1.h		\
+	pkcs12_asn1.h		\
+	pkcs8_asn1.h		\
+	pkcs9_asn1.h		\
+	pkinit_asn1.h		\
 	resolve.h		\
+	rfc2459_asn1.h		\
 	roken-common.h		\
 	roken.h			\
+	rtbl.h			\
+	send_to_kdc_plugin.h	\
 	sl.h			\
+	test-mem.h		\
+	vers.h			\
+	vis.h			\
+	wind.h			\
+	wind_err.h		\
 	windc_plugin.h		\
-	locate_plugin.h		\
 	xdbm.h
=20
 DISTCLEANFILES =3D 	\
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/Makefile.in
--- a/head/crypto/heimdal/include/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/include/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,17 +15,18 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22396 2008-01-01 19:35:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -39,14 +41,15 @@
 POST_UNINSTALL =3D :
 build_triplet =3D @build@
 host_triplet =3D @host@
-DIST_COMMON =3D $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
-	$(srcdir)/config.h.in $(top_srcdir)/Makefile.am.common \
+DIST_COMMON =3D $(noinst_HEADERS) $(srcdir)/Makefile.am \
+	$(srcdir)/Makefile.in $(srcdir)/config.h.in \
+	$(top_srcdir)/Makefile.am.common \
 	$(top_srcdir)/cf/Makefile.am.common
-noinst_PROGRAMS =3D bits$(EXEEXT) make_crypto$(EXEEXT)
+noinst_PROGRAMS =3D bits$(EXEEXT)
 subdir =3D include
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -61,7 +64,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -75,9 +78,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -85,22 +91,20 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 PROGRAMS =3D $(noinst_PROGRAMS)
 bits_SOURCES =3D bits.c
 bits_OBJECTS =3D bits.$(OBJEXT)
 bits_LDADD =3D $(LDADD)
-make_crypto_SOURCES =3D make_crypto.c
-make_crypto_OBJECTS =3D make_crypto.$(OBJEXT)
-make_crypto_LDADD =3D $(LDADD)
-DEFAULT_INCLUDES =3D -I. at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -110,8 +114,8 @@
 LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
-SOURCES =3D bits.c make_crypto.c
-DIST_SOURCES =3D bits.c make_crypto.c
+SOURCES =3D bits.c
+DIST_SOURCES =3D bits.c
 RECURSIVE_TARGETS =3D all-recursive check-recursive dvi-recursive \
 	html-recursive info-recursive install-data-recursive \
 	install-dvi-recursive install-exec-recursive \
@@ -124,63 +128,114 @@
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(includedir)"
-nodist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-HEADERS =3D $(nodist_include_HEADERS) $(nodist_noinst_HEADERS)
+HEADERS =3D $(nodist_include_HEADERS) $(noinst_HEADERS)
 RECURSIVE_CLEAN_TARGETS =3D mostlyclean-recursive clean-recursive	\
   distclean-recursive maintainer-clean-recursive
+AM_RECURSIVE_TARGETS =3D $(RECURSIVE_TARGETS:-recursive=3D) \
+	$(RECURSIVE_CLEAN_TARGETS:-recursive=3D) tags TAGS ctags CTAGS \
+	distdir
 ETAGS =3D etags
 CTAGS =3D ctags
 DIST_SUBDIRS =3D $(SUBDIRS)
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+am__relativize =3D \
+  dir0=3D`pwd`; \
+  sed_first=3D's,^\([^/]*\)/.*$$,\1,'; \
+  sed_rest=3D's,^[^/]*/*,,'; \
+  sed_last=3D's,^.*/\([^/]*\)$$,\1,'; \
+  sed_butlast=3D's,/*[^/]*$$,,'; \
+  while test -n "$$dir1"; do \
+    first=3D`echo "$$dir1" | sed -e "$$sed_first"`; \
+    if test "$$first" !=3D "."; then \
+      if test "$$first" =3D ".."; then \
+        dir2=3D`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
+        dir0=3D`echo "$$dir0" | sed -e "$$sed_butlast"`; \
+      else \
+        first2=3D`echo "$$dir2" | sed -e "$$sed_first"`; \
+        if test "$$first2" =3D "$$first"; then \
+          dir2=3D`echo "$$dir2" | sed -e "$$sed_rest"`; \
+        else \
+          dir2=3D"../$$dir2"; \
+        fi; \
+        dir0=3D"$$dir0"/"$$first"; \
+      fi; \
+    fi; \
+    dir1=3D`echo "$$dir1" | sed -e "$$sed_rest"`; \
+  done; \
+  reldir=3D"$$dir2"
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -204,10 +259,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -224,6 +280,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -239,31 +297,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -278,10 +350,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -322,97 +396,113 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	-DHOST=3D\"$(CANONICAL_HOST)\"
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -DHOST=3D\"$(CANONICAL_HOST)\"
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 SUBDIRS =3D kadm5 hcrypto gssapi
 CHECK_LOCAL =3D no-check-local
 nodist_include_HEADERS =3D krb5-types.h
-nodist_noinst_HEADERS =3D crypto-headers.h
+noinst_HEADERS =3D heim_threads.h crypto-headers.h
+EXTRA_DIST =3D NTMakefile krb5-types.cross
 CLEANFILES =3D \
-	cms_asn1.h 		\
-	der-protos.h 		\
-	digest_asn1.h 		\
-	hdb-protos.h		\
-	heim_asn1.h		\
-	heim_threads.h		\
-	hex.h			\
-	hx509-protos.h		\
-	hx509.h			\
-	hx509_err.h		\
-	kx509_asn1.h		\
-	kx509_err.h		\
-	k524_err.h		\
-	kdc-protos.h		\
-	kdc.h			\
-	krb5_asn1.h		\
-	krb5_ccapi.h		\
-	parse_bytes.h		\
-	pkcs12_asn1.h		\
-	pkcs8_asn1.h		\
-	pkcs9_asn1.h		\
-	pkinit_asn1.h		\
-	rfc2459_asn1.h		\
-	rtbl.h			\
-	test-mem.h		\
-	vers.h			\
-	vis.h			\
 	asn1.h			\
+	asn1-common.h		\
+	asn1-template.h		\
 	asn1_err.h		\
 	base64.h		\
+	cms_asn1.h 		\
+	crmf_asn1.h		\
 	com_err.h		\
 	com_right.h		\
-	crypto-headers.h	\
+	ccache_plugin.h		\
+	der-protos.h 		\
+	der-private.h 		\
 	der.h			\
+	digest_asn1.h 		\
 	editline.h		\
 	err.h			\
 	getarg.h		\
 	glob.h			\
 	gssapi.h		\
+	hdb-protos.h		\
 	hdb.h			\
 	hdb_asn1.h		\
 	hdb_err.h		\
+	heim-ipc.h		\
+	heim_asn1.h		\
 	heim_err.h		\
+	heimbase.h		\
+	heimntlm-protos.h	\
 	heimntlm.h		\
-	heimntlm-protos.h	\
+	hex.h			\
+	hx509-protos.h		\
+	hx509.h			\
+	hx509_err.h		\
+	k524_err.h		\
 	kafs.h			\
-	krb_err.h		\
+	kdc-protos.h		\
+	kdc.h			\
+	krb5-private.h		\
 	krb5-protos.h		\
-	krb5-private.h		\
 	krb5-types.h		\
 	krb5.h			\
+	krb5_asn1.h		\
+	krb5_ccapi.h		\
 	krb5_err.h		\
+	krb_err.h		\
+	kx509_asn1.h		\
+	kx509_err.h		\
+	locate_plugin.h		\
+	ntlm_err.h		\
+	ocsp_asn1.h		\
 	otp.h			\
+	parse_bytes.h		\
 	parse_time.h		\
 	parse_units.h		\
+	pkcs10_asn1.h		\
+	pkcs12_asn1.h		\
+	pkcs8_asn1.h		\
+	pkcs9_asn1.h		\
+	pkinit_asn1.h		\
 	resolve.h		\
+	rfc2459_asn1.h		\
 	roken-common.h		\
 	roken.h			\
+	rtbl.h			\
+	send_to_kdc_plugin.h	\
 	sl.h			\
+	test-mem.h		\
+	vers.h			\
+	vis.h			\
+	wind.h			\
+	wind_err.h		\
 	windc_plugin.h		\
-	locate_plugin.h		\
 	xdbm.h
=20
 DISTCLEANFILES =3D \
@@ -423,19 +513,19 @@
 	$(MAKE) $(AM_MAKEFLAGS) all-recursive
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps include/M=
akefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps include/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign include/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign include/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -453,6 +543,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 config.h: stamp-h1
 	@if test ! -f $@; then \
@@ -464,7 +555,7 @@
 	@rm -f stamp-h1
 	cd $(top_builddir) && $(SHELL) ./config.status include/config.h
 $(srcdir)/config.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)=20
-	cd $(top_srcdir) && $(AUTOHEADER)
+	($(am__cd) $(top_srcdir) && $(AUTOHEADER))
 	rm -f stamp-h1
 	touch $@
=20
@@ -472,17 +563,16 @@
 	-rm -f config.h stamp-h1
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 bits$(EXEEXT): $(bits_OBJECTS) $(bits_DEPENDENCIES)=20
 	@rm -f bits$(EXEEXT)
 	$(LINK) $(bits_OBJECTS) $(bits_LDADD) $(LIBS)
-make_crypto$(EXEEXT): $(make_crypto_OBJECTS) $(make_crypto_DEPENDENCIES)=20
-	@rm -f make_crypto$(EXEEXT)
-	$(LINK) $(make_crypto_OBJECTS) $(make_crypto_LDADD) $(LIBS)
=20
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
@@ -490,14 +580,28 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/bits.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -507,20 +611,23 @@
 install-nodist_includeHEADERS: $(nodist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedi=
r)/$$f'"; \
-	  $(nodist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"=
; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 # This directory's subdirectories are mostly independent; you can cd
 # into them and run `make' without going through this Makefile.
@@ -529,7 +636,7 @@
 #     (which will cause the Makefiles to be regenerated when you run `make=
');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -546,7 +653,7 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done; \
 	if test "$$dot_seen" =3D "no"; then \
@@ -554,7 +661,7 @@
 	fi; test -z "$$fail"
=20
 $(RECURSIVE_CLEAN_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -580,16 +687,16 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done && test -z "$$fail"
 tags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags);=
 \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 tags); \
 	done
 ctags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags)=
; \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 ctags); \
 	done
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
@@ -597,14 +704,14 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES=
) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
 	  include_option=3D--etags-include; \
@@ -616,39 +723,43 @@
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test ! -f $$subdir/TAGS || \
-	      tags=3D"$$tags $$include_option=3D$$here/$$subdir/TAGS"; \
+	      set "$$@" "$$include_option=3D$$here/$$subdir/TAGS"; \
 	  fi; \
 	done; \
 	list=3D'$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS: ctags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCI=
ES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -669,29 +780,44 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
-	list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test -d "$(distdir)/$$subdir" \
 	    || $(MKDIR_P) "$(distdir)/$$subdir" \
 	    || exit 1; \
-	    distdir=3D`$(am__cd) $(distdir) && pwd`; \
-	    top_distdir=3D`$(am__cd) $(top_distdir) && pwd`; \
-	    (cd $$subdir && \
+	  fi; \
+	done
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" =3D .; then :; else \
+	    dir1=3D$$subdir; dir2=3D"$(distdir)/$$subdir"; \
+	    $(am__relativize); \
+	    new_distdir=3D$$reldir; \
+	    dir1=3D$$subdir; dir2=3D"$(top_distdir)"; \
+	    $(am__relativize); \
+	    new_top_distdir=3D$$reldir; \
+	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir=3D"$$new_t=
op_distdir" distdir=3D"$$new_distdir" \\"; \
+	    echo "     am__remove_distdir=3D: am__skip_length_check=3D: am__skip_=
mode_fix=3D: distdir)"; \
+	    ($(am__cd) $$subdir && \
 	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir=3D"$$top_distdir" \
-	        distdir=3D"$$distdir/$$subdir" \
+	        top_distdir=3D"$$new_top_distdir" \
+	        distdir=3D"$$new_distdir" \
 		am__remove_distdir=3D: \
 		am__skip_length_check=3D: \
+		am__skip_mode_fix=3D: \
 	        distdir) \
 	      || exit 1; \
 	  fi; \
@@ -729,6 +855,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
 	-test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES)
=20
 maintainer-clean-generic:
@@ -740,6 +867,7 @@
 	mostlyclean-am
=20
 distclean: distclean-recursive
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-hdr distclean-tags
@@ -750,6 +878,8 @@
=20
 html: html-recursive
=20
+html-am:
+
 info: info-recursive
=20
 info-am:
@@ -757,26 +887,35 @@
 install-data-am: install-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-recursive
=20
-install-dvi: install-dvi-recursive
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-recursive
=20
+install-html-am:
+
 install-info: install-info-recursive
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-recursive
=20
+install-pdf-am:
+
 install-ps: install-ps-recursive
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-recursive
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -796,9 +935,9 @@
 uninstall-am: uninstall-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \
-	install-data-am install-exec-am install-strip uninstall-am
+.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) all check-am \
+	ctags-recursive install-am install-data-am install-exec-am \
+	install-strip tags-recursive uninstall-am
=20
 .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
 	all all-am all-local check check-am check-local clean \
@@ -887,6 +1026,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -972,7 +1114,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -986,11 +1128,12 @@
 	  fi ; \
 	done
=20
-krb5-types.h: bits$(EXEEXT)
-	./bits$(EXEEXT) krb5-types.h
+ at CROSS_COMPILE_FALSE@krb5-types.h: bits$(EXEEXT)
+ at CROSS_COMPILE_FALSE@	./bits$(EXEEXT) krb5-types.h
=20
-crypto-headers.h: make_crypto$(EXEEXT)
-	./make_crypto$(EXEEXT) crypto-headers.h
+ at CROSS_COMPILE_TRUE@krb5-types.h: krb5-types.cross
+ at CROSS_COMPILE_TRUE@	cp $(srcdir)/krb5-types.cross krb5-types.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/bits.c
--- a/head/crypto/heimdal/include/bits.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/include/bits.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,50 @@
 /*
- * Copyright (c) 1997-2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: bits.c 18703 2006-10-20 20:33:58Z lha $");
+RCSID("$Id$");
 #endif
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <ctype.h>
+#ifdef WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
=20
 #define BITSIZE(TYPE)						\
 {								\
@@ -46,7 +52,7 @@
     char tmp[128], tmp2[128];					\
     while(x){ x <<=3D 1; b++; if(x < zero) pre=3D""; }		\
     if(b >=3D len){						\
-        int tabs;						\
+        size_t tabs;						\
 	sprintf(tmp, "%sint%d_t" , pre, len);			\
 	sprintf(tmp2, "typedef %s %s;", #TYPE, tmp);		\
 	tabs =3D 5 - strlen(tmp2) / 8;				\
@@ -113,7 +119,7 @@
     FILE *f;
     int flag;
     const char *fn, *hb;
-   =20
+
     if (argc > 1 && strcmp(argv[1], "--version") =3D=3D 0) {
 	printf("some version");
 	return 0;
@@ -136,8 +142,8 @@
 	f =3D fopen(argv[1], "w");
     }
     fprintf(f, "/* %s -- this file was generated for %s by\n", fn, HOST);
-    fprintf(f, "   %*s    %s */\n\n", (int)strlen(fn), "",=20
-	    "$Id: bits.c 18703 2006-10-20 20:33:58Z lha $");
+    fprintf(f, "   %*s    %s */\n\n", (int)strlen(fn), "",
+	    "$Id$");
     fprintf(f, "#ifndef %s\n", hb);
     fprintf(f, "#define %s\n", hb);
     fprintf(f, "\n");
@@ -157,7 +163,12 @@
     fprintf(f, "#include <netinet/in6_machtypes.h>\n");
 #endif
 #ifdef HAVE_SOCKLEN_T
+#ifndef WIN32
     fprintf(f, "#include <sys/socket.h>\n");
+#else
+    fprintf(f, "#include <winsock2.h>\n");
+    fprintf(f, "#include <ws2tcpip.h>\n");
+#endif
 #endif
     fprintf(f, "\n");
=20
@@ -234,7 +245,53 @@
     fprintf(f, "typedef int krb5_ssize_t;\n");
 #endif
     fprintf(f, "\n");
+
+#if defined(_WIN32)
+    fprintf(f, "typedef SOCKET krb5_socket_t;\n");
+#else
+    fprintf(f, "typedef int krb5_socket_t;\n");
+#endif
+    fprintf(f, "\n");
+
 #endif /* KRB5 */
+
+    fprintf(f, "#ifndef HEIMDAL_DEPRECATED\n");
+    fprintf(f, "#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ =3D=
=3D 3) && (__GNUC_MINOR__ >=3D 1 )))\n");
+    fprintf(f, "#define HEIMDAL_DEPRECATED __attribute__((deprecated))\n");
+    fprintf(f, "#elif defined(_MSC_VER) && (_MSC_VER>1200)\n");
+    fprintf(f, "#define HEIMDAL_DEPRECATED __declspec(deprecated)\n");
+    fprintf(f, "#else\n");
+    fprintf(f, "#define HEIMDAL_DEPRECATED\n");
+    fprintf(f, "#endif\n");
+    fprintf(f, "#endif\n");
+
+    fprintf(f, "#ifndef HEIMDAL_PRINTF_ATTRIBUTE\n");
+    fprintf(f, "#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ =3D=
=3D 3) && (__GNUC_MINOR__ >=3D 1 )))\n");
+    fprintf(f, "#define HEIMDAL_PRINTF_ATTRIBUTE(x) __attribute__((format =
x))\n");
+    fprintf(f, "#else\n");
+    fprintf(f, "#define HEIMDAL_PRINTF_ATTRIBUTE(x)\n");
+    fprintf(f, "#endif\n");
+    fprintf(f, "#endif\n");
+
+    fprintf(f, "#ifndef HEIMDAL_NORETURN_ATTRIBUTE\n");
+    fprintf(f, "#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ =3D=
=3D 3) && (__GNUC_MINOR__ >=3D 1 )))\n");
+    fprintf(f, "#define HEIMDAL_NORETURN_ATTRIBUTE __attribute__((noreturn=
))\n");
+    fprintf(f, "#else\n");
+    fprintf(f, "#define HEIMDAL_NORETURN_ATTRIBUTE\n");
+    fprintf(f, "#endif\n");
+    fprintf(f, "#endif\n");
+
+    fprintf(f, "#ifndef HEIMDAL_UNUSED_ATTRIBUTE\n");
+    fprintf(f, "#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ =3D=
=3D 3) && (__GNUC_MINOR__ >=3D 1 )))\n");
+    fprintf(f, "#define HEIMDAL_UNUSED_ATTRIBUTE __attribute__((unused))\n=
");
+    fprintf(f, "#else\n");
+    fprintf(f, "#define HEIMDAL_UNUSED_ATTRIBUTE\n");
+    fprintf(f, "#endif\n");
+    fprintf(f, "#endif\n");
+
     fprintf(f, "#endif /* %s */\n", hb);
+
+    if (f !=3D stdout)
+	fclose(f);
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/config.h.in
--- a/head/crypto/heimdal/include/config.h.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/include/config.h.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* include/config.h.in.  Generated from configure.in by autoheader.  */
+/* include/config.h.in.  Generated from configure.ac by autoheader.  */
=20
 #ifndef RCSID
 #define RCSID(msg) \
@@ -12,22 +12,45 @@
=20
=20
 #ifdef BUILD_KRB5_LIB
-#ifndef KRB5_LIB_FUNCTION
+#ifndef KRB5_LIB
 #ifdef _WIN32_
-#define KRB5_LIB_FUNCTION _export _stdcall
+#define KRB5_LIB_FUNCTION __declspec(dllexport)
+#define KRB5_LIB_CALL __stdcall
+#define KRB5_LIB_VARIABLE __declspec(dllexport)
 #else
 #define KRB5_LIB_FUNCTION
+#define KRB5_LIB_CALL
+#define KRB5_LIB_VARIABLE
 #endif
 #endif
 #endif
=20
=20
 #ifdef BUILD_ROKEN_LIB
-#ifndef ROKEN_LIB_FUNCTION
+#ifndef ROKEN_LIB
 #ifdef _WIN32_
-#define ROKEN_LIB_FUNCTION _export _stdcall
+#define ROKEN_LIB_FUNCTION __declspec(dllexport)
+#define ROKEN_LIB_CALL __stdcall
+#define ROKEN_LIB_VARIABLE __declspec(dllexport)
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#define ROKEN_LIB_VARIABLE
+#endif
+#endif
+#endif
+
+
+#ifdef BUILD_GSSAPI_LIB
+#ifndef GSSAPI_LIB
+#ifdef _WIN32_
+#define GSSAPI_LIB_FUNCTION __declspec(dllexport)
+#define GSSAPI_LIB_CALL __stdcall
+#define GSSAPI_LIB_VARIABLE __declspec(dllexport)
+#else
+#define GSSAPI_LIB_FUNCTION
+#define GSSAPI_LIB_CALL
+#define GSSAPI_LIB_VARIABLE
 #endif
 #endif
 #endif
@@ -51,6 +74,9 @@
 /* Define this to enable diagnostics in telnet. */
 #undef DIAGNOSTICS
=20
+/* Define to enable DIGEST. */
+#undef DIGEST
+
 /* Define if want to use the weak AFS string to key functions. */
 #undef ENABLE_AFS_STRING_TO_KEY
=20
@@ -100,6 +126,9 @@
 /* Define to 1 if you have the <arpa/telnet.h> header file. */
 #undef HAVE_ARPA_TELNET_H
=20
+/* Define to 1 if you have the <asl.h> header file. */
+#undef HAVE_ASL_H
+
 /* Define to 1 if you have the `asnprintf' function. */
 #undef HAVE_ASNPRINTF
=20
@@ -109,6 +138,9 @@
 /* Define to 1 if you have the `atexit' function. */
 #undef HAVE_ATEXIT
=20
+/* Define to 1 if you have the `backtrace' function. */
+#undef HAVE_BACKTRACE
+
 /* Define to 1 if you have the <bind/bitypes.h> header file. */
 #undef HAVE_BIND_BITYPES_H
=20
@@ -124,6 +156,9 @@
 /* Define to 1 if you have the <capability.h> header file. */
 #undef HAVE_CAPABILITY_H
=20
+/* whether capng is available for privilege reduction */
+#undef HAVE_CAPNG
+
 /* Define to 1 if you have the `cap_set_proc' function. */
 #undef HAVE_CAP_SET_PROC
=20
@@ -136,6 +171,12 @@
 /* Define if you have the function `closefrom'. */
 #undef HAVE_CLOSEFROM
=20
+/* Define to 1 if you have the <CommonCrypto/CommonCryptor.h> header file.=
 */
+#undef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H
+
+/* Define to 1 if you have the <CommonCrypto/CommonDigest.h> header file. =
*/
+#undef HAVE_COMMONCRYPTO_COMMONDIGEST_H
+
 /* Define to 1 if you have the <config.h> header file. */
 #undef HAVE_CONFIG_H
=20
@@ -157,7 +198,7 @@
 /* define if you have a berkeley db1/2 library */
 #undef HAVE_DB1
=20
-/* define if you have a berkeley db3/4 library */
+/* define if you have a berkeley db3/4/5 library */
 #undef HAVE_DB3
=20
 /* Define to 1 if you have the <db3/db.h> header file. */
@@ -166,6 +207,12 @@
 /* Define to 1 if you have the <db4/db.h> header file. */
 #undef HAVE_DB4_DB_H
=20
+/* Define to 1 if you have the <db5/db.h> header file. */
+#undef HAVE_DB5_DB_H
+
+/* Define if you have user supplied header location */
+#undef HAVE_DBHEADER
+
 /* Define to 1 if you have the `dbm_firstkey' function. */
 #undef HAVE_DBM_FIRSTKEY
=20
@@ -175,9 +222,6 @@
 /* Define to 1 if you have the `dbopen' function. */
 #undef HAVE_DBOPEN
=20
-/* Define to 1 if you have the <db_185.h> header file. */
-#undef HAVE_DB_185_H
-
 /* Define to 1 if you have the `db_create' function. */
 #undef HAVE_DB_CREATE
=20
@@ -238,12 +282,30 @@
 /* Define to 1 if you have the <dirent.h> header file. */
 #undef HAVE_DIRENT_H
=20
+/* have a dirfd function/macro */
+#undef HAVE_DIRFD
+
+/* Define if DIR has field dd_fd. */
+#undef HAVE_DIR_DD_FD
+
+/* Define to 1 if you have the `dispatch_async_f' function. */
+#undef HAVE_DISPATCH_ASYNC_F
+
+/* Define to 1 if you have the <dispatch/dispatch.h> header file. */
+#undef HAVE_DISPATCH_DISPATCH_H
+
 /* Define to 1 if you have the <dlfcn.h> header file. */
 #undef HAVE_DLFCN_H
=20
 /* Define to 1 if you have the `dlopen' function. */
 #undef HAVE_DLOPEN
=20
+/* Define to 1 if you have the <dns.h> header file. */
+#undef HAVE_DNS_H
+
+/* Define to 1 if you have the `dns_search' function. */
+#undef HAVE_DNS_SEARCH
+
 /* Define to 1 if you have the `dn_expand' function. */
 #undef HAVE_DN_EXPAND
=20
@@ -253,9 +315,6 @@
 /* Define if you have the function `ecalloc'. */
 #undef HAVE_ECALLOC
=20
-/* Define to 1 if you have the `el_init' function. */
-#undef HAVE_EL_INIT
-
 /* Define if you have the function `emalloc'. */
 #undef HAVE_EMALLOC
=20
@@ -277,6 +336,9 @@
 /* Define if you have the function `estrdup'. */
 #undef HAVE_ESTRDUP
=20
+/* Define to 1 if you have the <execinfo.h> header file. */
+#undef HAVE_EXECINFO_H
+
 /* Define if you have the function `fchown'. */
 #undef HAVE_FCHOWN
=20
@@ -295,9 +357,6 @@
 /* Define to 1 if you have the <fnmatch.h> header file. */
 #undef HAVE_FNMATCH_H
=20
-/* Define if el_init takes four arguments. */
-#undef HAVE_FOUR_VALUED_EL_INIT
-
 /* Have -framework Security */
 #undef HAVE_FRAMEWORK_SECURITY
=20
@@ -310,6 +369,9 @@
 /* Define to 1 if you have the `gai_strerror' function. */
 #undef HAVE_GAI_STRERROR
=20
+/* Define if os support gcd. */
+#undef HAVE_GCD
+
 /* Define to 1 if you have the <gdbm/ndbm.h> header file. */
 #undef HAVE_GDBM_NDBM_H
=20
@@ -440,9 +502,6 @@
 /* Define if you have the function `initgroups'. */
 #undef HAVE_INITGROUPS
=20
-/* Define to 1 if you have the `initstate' function. */
-#undef HAVE_INITSTATE
-
 /* Define if you have the function `innetgr'. */
 #undef HAVE_INNETGR
=20
@@ -485,6 +544,9 @@
 /* Define to 1 if you have the `loadquery' function. */
 #undef HAVE_LOADQUERY
=20
+/* Define to 1 if you have the <locale.h> header file. */
+#undef HAVE_LOCALE_H
+
 /* Define if you have the function `localtime_r'. */
 #undef HAVE_LOCALTIME_R
=20
@@ -554,12 +616,6 @@
 /* Define to 1 if you have the <netinet/tcp.h> header file. */
 #undef HAVE_NETINET_TCP_H
=20
-/* Define if you want to use Netinfo instead of krb5.conf. */
-#undef HAVE_NETINFO
-
-/* Define to 1 if you have the <netinfo/ni.h> header file. */
-#undef HAVE_NETINFO_NI_H
-
 /* Define to 1 if you have the <net/if.h> header file. */
 #undef HAVE_NET_IF_H
=20
@@ -617,6 +673,13 @@
 /* Define if you have a readline compatible library. */
 #undef HAVE_READLINE
=20
+/* Define to 1 if you have the
+   <[readline.h])[][]_AH_CHECK_HEADER([readline/readline.h]> header file. =
*/
+#undef HAVE_READLINE_H
+
+/* Define to 1 if you have the <readline/readline.h > header file. */
+#undef HAVE_READLINE_READLINE_H_
+
 /* Define if you have the function `readv'. */
 #undef HAVE_READV
=20
@@ -647,6 +710,12 @@
 /* Define to 1 if the system has the type `sa_family_t'. */
 #undef HAVE_SA_FAMILY_T
=20
+/* Define if you want support for cache in sqlite. */
+#undef HAVE_SCC
+
+/* Define to 1 if you have the <search.h> header file. */
+#undef HAVE_SEARCH_H
+
 /* Define to 1 if you have the <security/pam_modules.h> header file. */
 #undef HAVE_SECURITY_PAM_MODULES_H
=20
@@ -704,9 +773,6 @@
 /* Define to 1 if you have the `setsockopt' function. */
 #undef HAVE_SETSOCKOPT
=20
-/* Define to 1 if you have the `setstate' function. */
-#undef HAVE_SETSTATE
-
 /* Define to 1 if you have the `setutent' function. */
 #undef HAVE_SETUTENT
=20
@@ -737,6 +803,9 @@
 /* Define to 1 if the system has the type `socklen_t'. */
 #undef HAVE_SOCKLEN_T
=20
+/* Define if you want support for sqlite in Heimdal. */
+#undef HAVE_SQLITE3
+
 /* Define to 1 if the system has the type `ssize_t'. */
 #undef HAVE_SSIZE_T
=20
@@ -758,6 +827,9 @@
 /* Define if you have the function `strerror'. */
 #undef HAVE_STRERROR
=20
+/* Define if you have the function strerror_r. */
+#undef HAVE_STRERROR_R
+
 /* Define if you have the function `strftime'. */
 #undef HAVE_STRFTIME
=20
@@ -803,6 +875,9 @@
 /* Define to 1 if you have the `strsvis' function. */
 #undef HAVE_STRSVIS
=20
+/* Define to 1 if you have the `strsvisx' function. */
+#undef HAVE_STRSVISX
+
 /* Define if you have the function `strtok_r'. */
 #undef HAVE_STRTOK_R
=20
@@ -839,9 +914,30 @@
 /* Define if struct utmpx has field ut_exit. */
 #undef HAVE_STRUCT_UTMPX_UT_EXIT
=20
+/* Define if struct utmpx has field ut_host. */
+#undef HAVE_STRUCT_UTMPX_UT_HOST
+
+/* Define if struct utmpx has field ut_id. */
+#undef HAVE_STRUCT_UTMPX_UT_ID
+
+/* Define if struct utmpx has field ut_line. */
+#undef HAVE_STRUCT_UTMPX_UT_LINE
+
+/* Define if struct utmpx has field ut_pid. */
+#undef HAVE_STRUCT_UTMPX_UT_PID
+
 /* Define if struct utmpx has field ut_syslen. */
 #undef HAVE_STRUCT_UTMPX_UT_SYSLEN
=20
+/* Define if struct utmpx has field ut_tv. */
+#undef HAVE_STRUCT_UTMPX_UT_TV
+
+/* Define if struct utmpx has field ut_type. */
+#undef HAVE_STRUCT_UTMPX_UT_TYPE
+
+/* Define if struct utmpx has field ut_user. */
+#undef HAVE_STRUCT_UTMPX_UT_USER
+
 /* Define if struct utmp has field ut_addr. */
 #undef HAVE_STRUCT_UTMP_UT_ADDR
=20
@@ -1001,6 +1097,9 @@
 /* Define to 1 if you have the <sys/wait.h> header file. */
 #undef HAVE_SYS_WAIT_H
=20
+/* Define to 1 if you have the `tdelete' function. */
+#undef HAVE_TDELETE
+
 /* Define to 1 if you have the <termcap.h> header file. */
 #undef HAVE_TERMCAP_H
=20
@@ -1013,6 +1112,9 @@
 /* Define to 1 if you have the <term.h> header file. */
 #undef HAVE_TERM_H
=20
+/* Define to 1 if you have the `tfind' function. */
+#undef HAVE_TFIND
+
 /* Define to 1 if you have the `tgetent' function. */
 #undef HAVE_TGETENT
=20
@@ -1028,12 +1130,18 @@
 /* Define to 1 if you have the <tmpdir.h> header file. */
 #undef HAVE_TMPDIR_H
=20
+/* Define if you have the function `tsearch'. */
+#undef HAVE_TSEARCH
+
 /* Define to 1 if you have the `ttyname' function. */
 #undef HAVE_TTYNAME
=20
 /* Define to 1 if you have the `ttyslot' function. */
 #undef HAVE_TTYSLOT
=20
+/* Define to 1 if you have the `twalk' function. */
+#undef HAVE_TWALK
+
 /* Define to 1 if you have the <udb.h> header file. */
 #undef HAVE_UDB_H
=20
@@ -1136,9 +1244,15 @@
 /* Define if you have the function `warnx'. */
 #undef HAVE_WARNX
=20
+/* Define to 1 if you have the <winsock2.h> header file. */
+#undef HAVE_WINSOCK2_H
+
 /* Define if you have the function `writev'. */
 #undef HAVE_WRITEV
=20
+/* Define to 1 if you have the <ws2tcpip.h> header file. */
+#undef HAVE_WS2TCPIP_H
+
 /* define if struct winsize has ws_xpixel */
 #undef HAVE_WS_XPIXEL
=20
@@ -1172,24 +1286,40 @@
 /* Define if you have the `__progname' variable. */
 #undef HAVE___PROGNAME
=20
+/* have __sync_add_and_fetch */
+#undef HAVE___SYNC_ADD_AND_FETCH
+
+/* Define if you want support for weak crypto */
+#undef HEIM_WEAK_CRYPTO
+
 /* Define if you have the hesiod package. */
 #undef HESIOD
=20
-/* Define if you are running IRIX 4. */
-#undef IRIX4
-
 /* Enable Kerberos 5 support in applications. */
 #undef KRB5
=20
+/* Define to enable kx509. */
+#undef KX509
+
 /* path to lib */
 #undef LIBDIR
=20
+/* Define if you have the libedit package. */
+#undef LIBEDIT
+
 /* path to libexec */
 #undef LIBEXECDIR
=20
+/* Define if you have the libintl package. */
+#undef LIBINTL
+
 /* path to localstate */
 #undef LOCALSTATEDIR
=20
+/* Define to the sub-directory in which libtool stores uninstalled librari=
es.
+   */
+#undef LT_OBJDIR
+
 /* define if the system is missing a prototype for asnprintf() */
 #undef NEED_ASNPRINTF_PROTO
=20
@@ -1223,6 +1353,9 @@
 /* define if the system is missing a prototype for mkstemp() */
 #undef NEED_MKSTEMP_PROTO
=20
+/* if your qsort is not a stable sort */
+#undef NEED_QSORT
+
 /* define if the system is missing a prototype for SecKeyGetCSPHandle() */
 #undef NEED_SECKEYGETCSPHANDLE_PROTO
=20
@@ -1238,6 +1371,9 @@
 /* define if the system is missing a prototype for strsep() */
 #undef NEED_STRSEP_PROTO
=20
+/* define if the system is missing a prototype for strsvisx() */
+#undef NEED_STRSVISX_PROTO
+
 /* define if the system is missing a prototype for strsvis() */
 #undef NEED_STRSVIS_PROTO
=20
@@ -1314,6 +1450,9 @@
 /* Define to the one symbol short name of this package. */
 #undef PACKAGE_TARNAME
=20
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
 /* Define to the version of this package. */
 #undef PACKAGE_VERSION
=20
@@ -1338,12 +1477,25 @@
 /* Define if you want to use samba socket wrappers. */
 #undef SOCKET_WRAPPER_REPLACE
=20
+/* Define if you have the sqlite3 package. */
+#undef SQLITE3
+
 /* Define to 1 if you have the ANSI C header files. */
 #undef STDC_HEADERS
=20
 /* Define if you have streams ptys. */
 #undef STREAMSPTY
=20
+/* define if prototype of strerror_r is compatible with int strerror_r(int,
+   char *, size_t) */
+#undef STRERROR_R_PROTO_COMPATIBLE
+
+/* Define if os support want to detach is daemonens. */
+#undef SUPPORT_DETACH
+
+/* Enable use of inetd style startup. */
+#undef SUPPORT_INETD
+
 /* path to sysconf */
 #undef SYSCONFDIR
=20
@@ -1372,6 +1524,9 @@
    `char[]'. */
 #undef YYTEXT_POINTER
=20
+/* Required for functional/sane headers on AIX */
+#undef _ALL_SOURCE
+
 /* Number of bits in a file offset, on hosts where this is settable. */
 #undef _FILE_OFFSET_BITS
=20
@@ -1381,6 +1536,9 @@
 /* Define for large files, on AIX-style hosts. */
 #undef _LARGE_FILES
=20
+/* Define to get POSIX getpwnam_r in some systems. */
+#undef _POSIX_PTHREAD_SEMANTICS
+
 /* Define to empty if `const' does not conform to ANSI C. */
 #undef const
=20
@@ -1402,6 +1560,9 @@
 /* Define to `int' if <sys/types.h> does not define. */
 #undef pid_t
=20
+/* Path name delimiter */
+#undef rk_PATH_DELIM
+
 /* Define this to what the type sig_atomic_t should be. */
 #undef sig_atomic_t
=20
@@ -1411,6 +1572,18 @@
 /* Define to `int' if <sys/types.h> doesn't define. */
 #undef uid_t
=20
+#if _AIX
+/* XXX this is gross, but kills about a gazillion warnings */
+struct ether_addr;
+struct sockaddr;
+struct sockaddr_dl;
+struct sockaddr_in;
+#endif
+
+#ifdef __APPLE__
+#include <AvailabilityMacros.h>
+#endif
+
 #ifdef ROKEN_RENAME
 #include "roken_rename.h"
 #endif
@@ -1426,7 +1599,7 @@
 #endif
=20
=20
-#if ENDIANESS_IN_SYS_PARAM_H
+#ifdef ENDIANESS_IN_SYS_PARAM_H
 #  include <sys/types.h>
 #  include <sys/param.h>
 #  if BYTE_ORDER =3D=3D BIG_ENDIAN
@@ -1435,27 +1608,8 @@
 #endif
=20
=20
-#if _AIX
-#define _ALL_SOURCE
-/* XXX this is gross, but kills about a gazillion warnings */
-struct ether_addr;
-struct sockaddr;
-struct sockaddr_dl;
-struct sockaddr_in;
-#endif
=20
=20
-/* IRIX 4 braindamage */
-#if IRIX =3D=3D 4 && !defined(__STDC__)
-#define __STDC__ 0
-#endif
-
-
-
-#if defined(ENCRYPTION) && !defined(AUTHENTICATION)
-#define AUTHENTICATION 1
-#endif
-
 /* Set this to the default system lead string for telnetd=20
  * can contain %-escapes: %s=3Dsysname, %m=3Dmachine, %r=3Dos-release
  * %v=3Dos-version, %t=3Dtty, %h=3Dhostname, %d=3Ddate and time
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/gssapi/Mak=
efile.am
--- a/head/crypto/heimdal/include/gssapi/Makefile.am	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/include/gssapi/Makefile.am	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,6 +1,7 @@
-# $Id: Makefile.am 18701 2006-10-20 20:32:01Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-CLEANFILES =3D gssapi.h gssapi_krb5.h gssapi_spnego.h
+CLEANFILES =3D gssapi.h gssapi_krb5.h gssapi_spnego.h gssapi_ntlm.h gssapi=
_oid.h
=20
+EXTRA_DIST =3D NTMakefile
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/gssapi/Mak=
efile.in
--- a/head/crypto/heimdal/include/gssapi/Makefile.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/include/gssapi/Makefile.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 18701 2006-10-20 20:32:01Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D include/gssapi
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
@@ -97,49 +101,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -163,10 +176,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -183,6 +197,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -198,31 +214,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -237,10 +267,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -281,47 +313,53 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
-CLEANFILES =3D gssapi.h gssapi_krb5.h gssapi_spnego.h
+CLEANFILES =3D gssapi.h gssapi_krb5.h gssapi_spnego.h gssapi_ntlm.h gssapi=
_oid.h
+EXTRA_DIST =3D NTMakefile
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps include/g=
ssapi/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps include/gssapi/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign include/gssapi/Makefile'=
; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign include/gssapi/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -339,6 +377,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -368,13 +407,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -407,6 +450,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -425,6 +469,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -432,23 +478,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
@@ -470,9 +524,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: all all-am all-local check check-am check-local clean \
 	clean-generic clean-libtool dist-hook distclean \
@@ -556,6 +609,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -641,7 +697,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -654,6 +710,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/hcrypto/Ma=
kefile.am
--- a/head/crypto/heimdal/include/hcrypto/Makefile.am	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/include/hcrypto/Makefile.am	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 16553 2006-01-13 13:43:32Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -8,8 +8,13 @@
 	des.h		\
 	dh.h		\
 	dsa.h		\
+	ec.h		\
+	ecdsa.h		\
+	ecdh.h		\
 	engine.h	\
 	evp.h		\
+	evp-hcrypto.h	\
+	evp-cc.h	\
 	hmac.h		\
 	md2.h		\
 	md4.h		\
@@ -21,3 +26,5 @@
 	rsa.h		\
 	sha.h		\
 	ui.h
+
+EXTRA_DIST =3D NTMakefile
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/hcrypto/Ma=
kefile.in
--- a/head/crypto/heimdal/include/hcrypto/Makefile.in	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/include/hcrypto/Makefile.in	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 16553 2006-01-13 13:43:32Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D include/hcrypto
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
@@ -97,49 +101,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -163,10 +176,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -183,6 +197,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -198,31 +214,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -237,10 +267,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -281,29 +313,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 CLEANFILES =3D \
 	aes.h		\
@@ -311,8 +348,13 @@
 	des.h		\
 	dh.h		\
 	dsa.h		\
+	ec.h		\
+	ecdsa.h		\
+	ecdh.h		\
 	engine.h	\
 	evp.h		\
+	evp-hcrypto.h	\
+	evp-cc.h	\
 	hmac.h		\
 	md2.h		\
 	md4.h		\
@@ -325,22 +367,23 @@
 	sha.h		\
 	ui.h
=20
+EXTRA_DIST =3D NTMakefile
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps include/h=
crypto/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps include/hcrypto/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign include/hcrypto/Makefile=
'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign include/hcrypto/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -358,6 +401,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -387,13 +431,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -426,6 +474,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -444,6 +493,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -451,23 +502,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
@@ -489,9 +548,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: all all-am all-local check check-am check-local clean \
 	clean-generic clean-libtool dist-hook distclean \
@@ -575,6 +633,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -660,7 +721,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -673,6 +734,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/kadm5/Make=
file.am
--- a/head/crypto/heimdal/include/kadm5/Makefile.am	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/include/kadm5/Makefile.am	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,8 @@
-# $Id: Makefile.am 18696 2006-10-20 20:25:13Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-CLEANFILES =3D admin.h kadm5_err.h private.h kadm5-private.h kadm5-protos.h
+CLEANFILES =3D admin.h kadm5_err.h private.h
+CLEANFILES +=3D kadm5-private.h kadm5-protos.h kadm5-pwcheck.h
+
+EXTRA_DIST =3D NTMakefile
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/include/kadm5/Make=
file.in
--- a/head/crypto/heimdal/include/kadm5/Makefile.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/include/kadm5/Makefile.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 18696 2006-10-20 20:25:13Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D include/kadm5
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
@@ -97,49 +101,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -163,10 +176,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -183,6 +197,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -198,31 +214,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -237,10 +267,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -281,47 +313,54 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
-CLEANFILES =3D admin.h kadm5_err.h private.h kadm5-private.h kadm5-protos.h
+CLEANFILES =3D admin.h kadm5_err.h private.h kadm5-private.h \
+	kadm5-protos.h kadm5-pwcheck.h
+EXTRA_DIST =3D NTMakefile
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps include/k=
adm5/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps include/kadm5/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign include/kadm5/Makefile';=
 \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign include/kadm5/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -339,6 +378,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -368,13 +408,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -407,6 +451,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -425,6 +470,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -432,23 +479,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
@@ -470,9 +525,8 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: all all-am all-local check check-am check-local clean \
 	clean-generic clean-libtool dist-hook distclean \
@@ -556,6 +610,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -641,7 +698,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -654,6 +711,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/install-sh
--- a/head/crypto/heimdal/install-sh	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/install-sh	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #!/bin/sh
 # install - install a program, script, or datafile
=20
-scriptversion=3D2006-10-14.15
+scriptversion=3D2009-04-28.21; # UTC
=20
 # This originates from X11R5 (mit/util/scripts/install.sh), which was
 # later released in X11R6 (xc/config/util/install.sh) with the
@@ -48,7 +48,7 @@
 # set DOITPROG to echo to test this script
=20
 # Don't use :- since 4.3BSD and earlier shells don't like it.
-doit=3D"${DOITPROG-}"
+doit=3D${DOITPROG-}
 if test -z "$doit"; then
   doit_exec=3Dexec
 else
@@ -58,34 +58,49 @@
 # Put in absolute file names if you don't have them in your path;
 # or use environment vars.
=20
-mvprog=3D"${MVPROG-mv}"
-cpprog=3D"${CPPROG-cp}"
-chmodprog=3D"${CHMODPROG-chmod}"
-chownprog=3D"${CHOWNPROG-chown}"
-chgrpprog=3D"${CHGRPPROG-chgrp}"
-stripprog=3D"${STRIPPROG-strip}"
-rmprog=3D"${RMPROG-rm}"
-mkdirprog=3D"${MKDIRPROG-mkdir}"
+chgrpprog=3D${CHGRPPROG-chgrp}
+chmodprog=3D${CHMODPROG-chmod}
+chownprog=3D${CHOWNPROG-chown}
+cmpprog=3D${CMPPROG-cmp}
+cpprog=3D${CPPROG-cp}
+mkdirprog=3D${MKDIRPROG-mkdir}
+mvprog=3D${MVPROG-mv}
+rmprog=3D${RMPROG-rm}
+stripprog=3D${STRIPPROG-strip}
=20
-posix_glob=3D
+posix_glob=3D'?'
+initialize_posix_glob=3D'
+  test "$posix_glob" !=3D "?" || {
+    if (set -f) 2>/dev/null; then
+      posix_glob=3D
+    else
+      posix_glob=3D:
+    fi
+  }
+'
+
 posix_mkdir=3D
=20
 # Desired mode of installed file.
 mode=3D0755
=20
+chgrpcmd=3D
 chmodcmd=3D$chmodprog
 chowncmd=3D
-chgrpcmd=3D
+mvcmd=3D$mvprog
+rmcmd=3D"$rmprog -f"
 stripcmd=3D
-rmcmd=3D"$rmprog -f"
-mvcmd=3D"$mvprog"
+
 src=3D
 dst=3D
 dir_arg=3D
-dstarg=3D
+dst_arg=3D
+
+copy_on_change=3Dfalse
 no_target_directory=3D
=20
-usage=3D"Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+usage=3D"\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
    or: $0 [OPTION]... SRCFILES... DIRECTORY
    or: $0 [OPTION]... -t DIRECTORY SRCFILES...
    or: $0 [OPTION]... -d DIRECTORIES...
@@ -95,65 +110,55 @@
 In the 4th, create DIRECTORIES.
=20
 Options:
--c         (ignored)
--d         create directories instead of installing files.
--g GROUP   $chgrpprog installed files to GROUP.
--m MODE    $chmodprog installed files to MODE.
--o USER    $chownprog installed files to USER.
--s         $stripprog installed files.
--t DIRECTORY  install into DIRECTORY.
--T         report an error if DSTFILE is a directory.
---help     display this help and exit.
---version  display version info and exit.
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modifica=
tion time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
=20
 Environment variables override the default commands:
-  CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
 "
=20
 while test $# -ne 0; do
   case $1 in
-    -c) shift
-        continue;;
+    -c) ;;
=20
-    -d) dir_arg=3Dtrue
-        shift
-        continue;;
+    -C) copy_on_change=3Dtrue;;
+
+    -d) dir_arg=3Dtrue;;
=20
     -g) chgrpcmd=3D"$chgrpprog $2"
-        shift
-        shift
-        continue;;
+	shift;;
=20
     --help) echo "$usage"; exit $?;;
=20
     -m) mode=3D$2
-        shift
-        shift
 	case $mode in
 	  *' '* | *'	'* | *'
 '*	  | *'*'* | *'?'* | *'['*)
 	    echo "$0: invalid mode: $mode" >&2
 	    exit 1;;
 	esac
-        continue;;
+	shift;;
=20
     -o) chowncmd=3D"$chownprog $2"
-        shift
-        shift
-        continue;;
+	shift;;
=20
-    -s) stripcmd=3D$stripprog
-        shift
-        continue;;
+    -s) stripcmd=3D$stripprog;;
=20
-    -t) dstarg=3D$2
-	shift
-	shift
-	continue;;
+    -t) dst_arg=3D$2
+	shift;;
=20
-    -T) no_target_directory=3Dtrue
-	shift
-	continue;;
+    -T) no_target_directory=3Dtrue;;
=20
     --version) echo "$0 $scriptversion"; exit $?;;
=20
@@ -165,21 +170,22 @@
=20
     *)  break;;
   esac
+  shift
 done
=20
-if test $# -ne 0 && test -z "$dir_arg$dstarg"; then
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
   # When -d is used, all remaining arguments are directories to create.
   # When -t is used, the destination is already specified.
   # Otherwise, the last argument is the destination.  Remove it from $@.
   for arg
   do
-    if test -n "$dstarg"; then
+    if test -n "$dst_arg"; then
       # $@ is not empty: it contains at least $arg.
-      set fnord "$@" "$dstarg"
+      set fnord "$@" "$dst_arg"
       shift # fnord
     fi
     shift # arg
-    dstarg=3D$arg
+    dst_arg=3D$arg
   done
 fi
=20
@@ -224,7 +230,7 @@
 do
   # Protect names starting with `-'.
   case $src in
-    -*) src=3D./$src ;;
+    -*) src=3D./$src;;
   esac
=20
   if test -n "$dir_arg"; then
@@ -242,22 +248,22 @@
       exit 1
     fi
=20
-    if test -z "$dstarg"; then
+    if test -z "$dst_arg"; then
       echo "$0: no destination specified." >&2
       exit 1
     fi
=20
-    dst=3D$dstarg
+    dst=3D$dst_arg
     # Protect names starting with `-'.
     case $dst in
-      -*) dst=3D./$dst ;;
+      -*) dst=3D./$dst;;
     esac
=20
     # If destination is a directory, append the input filename; won't work
     # if double slashes aren't ignored.
     if test -d "$dst"; then
       if test -n "$no_target_directory"; then
-	echo "$0: $dstarg: Is a directory" >&2
+	echo "$0: $dst_arg: Is a directory" >&2
 	exit 1
       fi
       dstdir=3D$dst
@@ -378,26 +384,19 @@
       # directory the slow way, step by step, checking for races as we go.
=20
       case $dstdir in
-	/*) prefix=3D/ ;;
-	-*) prefix=3D./ ;;
-	*)  prefix=3D ;;
+	/*) prefix=3D'/';;
+	-*) prefix=3D'./';;
+	*)  prefix=3D'';;
       esac
=20
-      case $posix_glob in
-        '')
-	  if (set -f) 2>/dev/null; then
-	    posix_glob=3Dtrue
-	  else
-	    posix_glob=3Dfalse
-	  fi ;;
-      esac
+      eval "$initialize_posix_glob"
=20
       oIFS=3D$IFS
       IFS=3D/
-      $posix_glob && set -f
+      $posix_glob set -f
       set fnord $dstdir
       shift
-      $posix_glob && set +f
+      $posix_glob set +f
       IFS=3D$oIFS
=20
       prefixes=3D
@@ -459,41 +458,54 @@
     # ignore errors from any of these, just make sure not to ignore
     # errors from the above "$doit $cpprog $src $dsttmp" command.
     #
-    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \
-      && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \
-      && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \
-      && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
=20
-    # Now rename the file to the real destination.
-    { $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null \
-      || {
-	   # The rename failed, perhaps because mv can't rename something else
-	   # to itself, or perhaps because mv is so ancient that it does not
-	   # support -f.
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=3D`LC_ALL=3DC ls -dlL "$dst"	2>/dev/null` &&
+       new=3D`LC_ALL=3DC ls -dlL "$dsttmp"	2>/dev/null` &&
=20
-	   # Now remove or move aside any old file at destination location.
-	   # We try this two ways since rm can't unlink itself on some
-	   # systems and the destination file might be busy for other
-	   # reasons.  In this case, the final cleanup might fail but the new
-	   # file should still install successfully.
-	   {
-	     if test -f "$dst"; then
-	       $doit $rmcmd -f "$dst" 2>/dev/null \
-	       || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null \
-		     && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }; }\
-	       || {
-		 echo "$0: cannot unlink or rename $dst" >&2
-		 (exit 1); exit 1
-	       }
-	     else
-	       :
-	     fi
-	   } &&
+       eval "$initialize_posix_glob" &&
+       $posix_glob set -f &&
+       set X $old && old=3D:$2:$4:$5:$6 &&
+       set X $new && new=3D:$2:$4:$5:$6 &&
+       $posix_glob set +f &&
=20
-	   # Now rename the file to the real destination.
-	   $doit $mvcmd "$dsttmp" "$dst"
-	 }
-    } || exit 1
+       test "$old" =3D "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+	# Now remove or move aside any old file at destination location.
+	# We try this two ways since rm can't unlink itself on some
+	# systems and the destination file might be busy for other
+	# reasons.  In this case, the final cleanup might fail but the new
+	# file should still install successfully.
+	{
+	  test ! -f "$dst" ||
+	  $doit $rmcmd -f "$dst" 2>/dev/null ||
+	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+	  } ||
+	  { echo "$0: cannot unlink or rename $dst" >&2
+	    (exit 1); exit 1
+	  }
+	} &&
+
+	# Now rename the file to the real destination.
+	$doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
=20
     trap '' 0
   fi
@@ -503,5 +515,6 @@
 # eval: (add-hook 'write-file-hooks 'time-stamp)
 # time-stamp-start: "scriptversion=3D"
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-end: "$"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
 # End:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/ChangeLog
--- a/head/crypto/heimdal/kadmin/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,20 +1,24 @@
-2007-12-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* kadm_conn.c: Use unsigned where appropriate.
+
+2007-12-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.c: Use hdb_db_dir().
=20
 	* kadmind.c: Use hdb_db_dir().
=20
-2007-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c: Clear error string, just to be sure.
=20
-2007-05-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin-commands.in: modify --pkinit-acl
=20
 	* mod.c: add pk-init command
 =09
-2007-02-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-02-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.8: document kadmin add_enctype functionallity.
=20
@@ -25,7 +29,7 @@
 	* add_enctype.c: Add support for adding a random key enctype to a
 	principal.
 =09
-2007-02-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-02-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mod.c: add setting and displaying aliases
=20
@@ -33,7 +37,7 @@
=20
 	* kadmin-commands.in: add setting and displaying aliases
=20
-2006-12-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c: Make str2time_t parser more robust.
=20
@@ -41,51 +45,51 @@
=20
 	* test_util.c: Test str2time_t parser.
 =09
-2006-12-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* add-random-users.c: Use strcspn to remove \n from fgets
-	result. Prompted by change by Ray Lai of OpenBSD via Bj=F6rn
+	result. Prompted by change by Ray Lai of OpenBSD via Bj=C3=B6rn
 	Sandell.
 =09
-2006-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mod.c: Try to not leak memory.
=20
 	* check.c: Try to not leak memory.
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: split build files into dist_ and noinst_ SOURCES
 =09
-2006-08-28  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-08-28  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* kadmin.c (help): use sl_slc_help().
 =09
-2006-08-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c: Add KRB5_KDB_ALLOW_DIGEST
 =09
-2006-07-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* get.c (format_field): optionally print issuer and anchor.
 =09
-2006-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* check.c: Check if afs at REALM and afs/cellname at REALM both exists.
 =09
-2006-06-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c (kdb_attrs): Add KRB5_KDB_ALLOW_KERBEROS4
 =09
-2006-06-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mod.c (do_mod_entry): Add setting 1 delegation entry
 =09
-2006-06-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* server.c: Less shadowing.
 =09
-2006-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: kadmin_SOURCES +=3D add check.c
=20
@@ -98,32 +102,32 @@
 	* check.c: Check database for strange configurations on default
 	principals.
 =09
-2006-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* server.c (kadm_get_privs): one less "pointer targets in passing
 	argument differ in signedness" warning.
 =09
-2006-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* dump-format.txt: Moved to info documentation.
=20
 	* Rename u_intXX_t to uintXX_t
 =09
-2006-05-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.8: spelling, update .Dd
 =09
-2006-04-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* add-random-users.c: Catch empty file case. From Tobias
 	Stoeckmann.
 =09
-2006-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* random_password.c (generate_password): memory leak in error
 	condition case From Coverity NetBSD CID#1887
 =09
-2006-02-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cpw.c (cpw_entry): make sure ret have a defined value
=20
@@ -132,7 +136,7 @@
 	* mod.c: Return error code so that toplevel function can catch
 	them.
 =09
-2006-01-25  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-01-25  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* cpw.c (cpw_entry): return 1 on failure.
=20
@@ -148,26 +152,26 @@
 	* util.c (foreach_principal): If any of calls to `func' failes,
 	the first error is returned when all principals are processed.
 =09
-2005-12-01  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-12-01  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* kadmin-commands.in: Add ank as an alias to add, it lost in
-	transition to slc, from M=E5ns Nilsson.
+	transition to slc, from M=C3=A5ns Nilsson.
 =09
-2005-09-14  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-09-14  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* dump-format.txt: Add extensions, fill in missing fields.
=20
-2005-09-08  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-09-08  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* init.c (create_random_entry): create principal with random
 	password even though its disabled. From Andrew Bartlet
 	<abartlet at samba.org>
 =09
-2005-09-01  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-09-01  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadm_conn.c: Use socket_set_reuseaddr and socket_set_ipv6only.
 =09
-2005-08-11  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-08-11  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* get.c: Remove structure that is never used (sneaked in the large
 	TL_DATA patch).
@@ -188,7 +192,7 @@
 	options and fix a dependency bug (keys needed principal to print
 	the salting).
 =09
-2005-07-08  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-07-08  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* lower amount of shadow and const warnings
=20
@@ -196,14 +200,14 @@
=20
 	* dump-format.txt: Clarify, spelling and add examples.
 =09
-2005-05-30  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-05-30  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c (kdb_attrs): add ok-as-delegate
=20
 	* get.c (getit): init data.mask to 0.  Problem found by Andrew
 	Bartlett <abartlet at samba.org>
=20
-2005-05-09  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-05-09  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.c (main): catch -2 as EOF
=20
@@ -215,12 +219,12 @@
=20
 	* kadmin.c (help): Don't use non-constant initializer for `fake'.
=20
-2005-04-20  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-04-20  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c (foreach_principal): initialize ret to make sure it have
 	a value
=20
-2005-04-04  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-04-04  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmind.c: add verifier libraries with
 	kadm5_add_passwd_quality_verifier
@@ -231,50 +235,50 @@
 	* load.c: max-life and max-renew is of unsigned int in asn1
 	compiler, use that for the parser too
=20
-2005-03-26  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-03-26  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.8: List of attributes, from James F.  Hranicky
 	<jfh at cise.ufl.edu>
=20
-2005-01-19  Love H=F6rquist =C5strand  <lha at it.su.se>
+2005-01-19  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* dump.c (dump): handle errors
=20
-2005-01-08 Love H=F6rquist =C5strand <lha at it.su.se>
+2005-01-08 Love H=C3=B6rquist =C3=85strand <lha at it.su.se>
=20
 	* dump-format.txt: text dump format
=20
-2004-12-08  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-12-08  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmind.8: use keeps around options, from OpenBSD
 =09
 	* kadmin.8: use keeps around options, "improve" spelling, from
 	openbsd
=20
-2004-11-01  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-11-01  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* get.c (getit): always free columns
 =09
 	* ank.c (add_one_principal): catch error from
 	UI_UTIL_read_pw_string
=20
-2004-10-31  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-10-31  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* del_enctype.c (del_enctype): fix off-by-one error in del_enctype
 	From: <ragge at ludd.luth.se>
 =09
-2004-08-13  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-08-13  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* get.c: print keytypes on long format
 =09
-2004-07-06  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-07-06  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* get.c (format_field): allow mod_name to be optional
 =09
 	* ext.c (do_ext_keytab): if there isn't any keydata, try using
 	kadm5_randkey_principal
=20
-2004-07-02  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-07-02  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* load.c: make merge/load work again
 =09
@@ -282,7 +286,7 @@
 =09
 	* ank.c: fix slc lossage
 =09
-2004-06-28  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-06-28  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.c: use kadm5_ad_init_with_password_ctx
 =09
@@ -303,11 +307,11 @@
 =09
 	* kadmin: convert to use slc; also add stash subcommand
=20
-2004-06-15  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-06-15  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.c (main): keytab mode requires principal name
 =09
-2004-06-12  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-06-12  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmind.c: drop keyfile, not used, found by
 	Elrond <elrond at samba-tng.org>
@@ -315,7 +319,7 @@
 	* kadmin.c: if keyfile is set, pass in to libkadm5 bug pointed out
 	by Elrond <elrond at samba-tng.org>
 =09
-2004-05-31  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-05-31  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.c: add --ad flag, XXX rewrite the init kadm5 interface
 =09
@@ -328,7 +332,7 @@
 	* util.c (str2time_t): fix end-of-day logic, from Duncan
 	McEwan/Mark Davies.
=20
-2004-04-29  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-04-29  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* version4.c (handle_v4): make sure length is longer then 2,
 	Pointed out by Evgeny Demidov <demidov at gleg.net>
@@ -342,7 +346,7 @@
 	* mod.c: allow wildcarding principals, and make parameters a work
 	same as if prompted
 =09
-2004-03-08  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-03-08  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.8: document password-quality
 =09
@@ -354,40 +358,40 @@
 =09
 	* pw_quality.c: test run the password quality function
 =09
-2004-03-07  Love H=F6rquist =C5strand  <lha at it.su.se>
+2004-03-07  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* ank.c (add_one_principal): even though the principal is disabled
 	(creation of random key/keydata), create it with a random password
 =09
-2003-12-07  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-12-07  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* init.c (create_random_entry): print error message on failure
 =09
 	* ank.c (add_one_principal): pass right argument to
 	kadm5_free_principal_ent From Panasas, Inc
 =09
-2003-11-18  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-11-18  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmind.c (main): move opening the logfile to after reading
 	kdc.conf move the loading of hdb keytab ops closer to where its
 	used From: Jeffrey Hutzelman <jhutz at cmu.edu>
 =09
-2003-10-04  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-10-04  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c (str2time_t): allow whitespace between date and time
 	From: Bob Beck <beck at cvs.openbsd.org> and adharw at yahoo.com
 =09
-2003-09-03  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-09-03  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* ank.c: s/des_read_pw_string/UI_UTIL_read_pw_string/
 =09
 	* cpw.c: s/des_read_pw_string/UI_UTIL_read_pw_string/
 =09
-2003-08-21  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-08-21  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* get.c (print_entry_terse): handle error when unparsing name
 =09
-2003-08-18  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-08-18  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmind.c (main): use krb5_prepend_config_files_default, now all
 	options in kdc.conf is parsed, not just [kdc]key-file=3D
@@ -395,16 +399,16 @@
 	* kadmin.c (main): use krb5_prepend_config_files_default, now all
 	options in kdc.conf is parsed, not just [kdc]key-file=3D
 =09
-2003-04-14  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-04-14  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* util.c: cast argument to tolower to unsigned char, from
 	Christian Biere <christianbiere at gmx.de> via NetBSD
 =09
-2003-04-06  Love H=F6rquist =C5strand <lha at it.su.se>
+2003-04-06  Love H=C3=B6rquist =C3=85strand <lha at it.su.se>
=20
 	* kadmind.8: s/kerberos/Kerberos/
 =09
-2003-03-31  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-03-31  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmin.8: initialises -> initializes, from Perry E. Metzger"
 	<perry at piermont.com>
@@ -412,13 +416,13 @@
 	* kadmin.c: principal, not pricipal. From Thomas Klausner
 	<wiz at netbsd.org>
=20
-2003-02-04  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-02-04  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* kadmind.8: spelling, from jmc <jmc at prioris.mini.pw.edu.pl>
 =09
 	* kadmin.8: spelling, from jmc <jmc at prioris.mini.pw.edu.pl>
 =09
-2003-01-29  Love H=F6rquist =C5strand  <lha at it.su.se>
+2003-01-29  Love H=C3=B6rquist =C3=85strand  <lha at it.su.se>
=20
 	* server.c (kadmind_dispatch): kadm_chpass: require the password
 	to pass the password quality check in case the user changes the
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/Makefile.am
--- a/head/crypto/heimdal/kadmin/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,15 +1,13 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_readline) $(INCLUDE_hcrypto) -I$(srcdir)/../lib=
/krb5
+AM_CPPFLAGS +=3D $(INCLUDE_libintl) $(INCLUDE_readline) $(INCLUDE_hcrypto)=
 -I$(srcdir)/../lib/krb5 -I$(top_builddir)/include/gssapi
=20
 sbin_PROGRAMS =3D kadmin
=20
 libexec_PROGRAMS =3D kadmind
=20
-SLC =3D $(top_builddir)/lib/sl/slc
-
 man_MANS =3D kadmin.8 kadmind.8
=20
 noinst_PROGRAMS =3D add_random_users
@@ -47,10 +45,10 @@
 	$(SLC) $(srcdir)/kadmin-commands.in
=20
 kadmind_SOURCES =3D				\
+	rpc.c					\
+	server.c				\
 	kadmind.c				\
-	server.c				\
 	kadmin_locl.h				\
-	$(version4_c)				\
 	kadm_conn.c
=20
 add_random_users_SOURCES =3D add-random-users.c
@@ -63,7 +61,6 @@
=20
 LDADD_common =3D \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
@@ -71,6 +68,7 @@
 	$(DBLIB)
=20
 kadmind_LDADD =3D $(top_builddir)/lib/kadm5/libkadm5srv.la \
+	../lib/gssapi/libgssapi.la \
 	$(LDADD_common) \
 	$(LIB_pidfile) \
 	$(LIB_dlopen)
@@ -91,4 +89,9 @@
=20
 test_util_LDADD =3D $(kadmin_LDADD)
=20
-EXTRA_DIST =3D $(man_MANS) kadmin-commands.in
+EXTRA_DIST =3D \
+	NTMakefile \
+	kadmin-version.rc \
+	kadmind-version.rc \
+	$(man_MANS) \
+	kadmin-commands.in
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/Makefile.in
--- a/head/crypto/heimdal/kadmin/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -49,7 +51,7 @@
 subdir =3D kadmin
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -64,7 +66,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -78,9 +80,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -88,25 +93,24 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__EXEEXT_1 =3D test_util$(EXEEXT)
 am__installdirs =3D "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(sbindir)" \
 	"$(DESTDIR)$(man8dir)"
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-sbinPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(libexec_PROGRAMS) $(noinst_PROGRAMS) $(sbin_PROGRAMS)
 am_add_random_users_OBJECTS =3D add-random-users.$(OBJEXT)
 add_random_users_OBJECTS =3D $(am_add_random_users_OBJECTS)
 am__DEPENDENCIES_1 =3D
 am__DEPENDENCIES_2 =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
 add_random_users_DEPENDENCIES =3D  \
 	$(top_builddir)/lib/kadm5/libkadm5clnt.la \
 	$(top_builddir)/lib/kadm5/libkadm5srv.la $(am__DEPENDENCIES_2) \
@@ -123,12 +127,12 @@
 	$(top_builddir)/lib/kadm5/libkadm5srv.la \
 	$(top_builddir)/lib/sl/libsl.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1)
-am_kadmind_OBJECTS =3D kadmind.$(OBJEXT) server.$(OBJEXT) \
+am_kadmind_OBJECTS =3D rpc.$(OBJEXT) server.$(OBJEXT) kadmind.$(OBJEXT) \
 	kadm_conn.$(OBJEXT)
 kadmind_OBJECTS =3D $(am_kadmind_OBJECTS)
 kadmind_DEPENDENCIES =3D $(top_builddir)/lib/kadm5/libkadm5srv.la \
-	$(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
+	../lib/gssapi/libgssapi.la $(am__DEPENDENCIES_2) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
 am_test_util_OBJECTS =3D test_util.$(OBJEXT) util.$(OBJEXT)
 test_util_OBJECTS =3D $(am_test_util_OBJECTS)
 am__DEPENDENCIES_3 =3D $(top_builddir)/lib/kadm5/libkadm5clnt.la \
@@ -136,9 +140,9 @@
 	$(top_builddir)/lib/sl/libsl.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1)
 test_util_DEPENDENCIES =3D $(am__DEPENDENCIES_3)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -153,58 +157,90 @@
 	$(test_util_SOURCES)
 DIST_SOURCES =3D $(add_random_users_SOURCES) $(dist_kadmin_SOURCES) \
 	$(kadmind_SOURCES) $(test_util_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -228,10 +264,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -248,6 +285,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -263,31 +302,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -302,10 +355,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -346,32 +401,37 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_readline) $(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_libintl) $(INCLUDE_readline) \
+	$(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5 \
+	-I$(top_builddir)/include/gssapi
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
-SLC =3D $(top_builddir)/lib/sl/slc
 man_MANS =3D kadmin.8 kadmind.8
 dist_kadmin_SOURCES =3D \
 	ank.c					\
@@ -400,17 +460,16 @@
=20
 CLEANFILES =3D kadmin-commands.h kadmin-commands.c
 kadmind_SOURCES =3D \
+	rpc.c					\
+	server.c				\
 	kadmind.c				\
-	server.c				\
 	kadmin_locl.h				\
-	$(version4_c)				\
 	kadm_conn.c
=20
 add_random_users_SOURCES =3D add-random-users.c
 test_util_SOURCES =3D test_util.c util.c
 LDADD_common =3D \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
@@ -418,6 +477,7 @@
 	$(DBLIB)
=20
 kadmind_LDADD =3D $(top_builddir)/lib/kadm5/libkadm5srv.la \
+	../lib/gssapi/libgssapi.la \
 	$(LDADD_common) \
 	$(LIB_pidfile) \
 	$(LIB_dlopen)
@@ -437,23 +497,29 @@
 	$(LIB_dlopen)
=20
 test_util_LDADD =3D $(kadmin_LDADD)
-EXTRA_DIST =3D $(man_MANS) kadmin-commands.in
+EXTRA_DIST =3D \
+	NTMakefile \
+	kadmin-version.rc \
+	kadmind-version.rc \
+	$(man_MANS) \
+	kadmin-commands.in
+
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps kadmin/Ma=
kefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps kadmin/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign kadmin/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign kadmin/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -471,76 +537,111 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-sbinPROGRAMS: $(sbin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(sbindir)" || $(MKDIR_P) "$(DESTDIR)$(sbindir)"
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRA=
MS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRAMS_INST=
ALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$d=
ir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || =
exit $$?; \
+	    } \
+	; done
=20
 uninstall-sbinPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(sbindir)/$$f"; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(sbindir)" && rm -f $$files
=20
 clean-sbinPROGRAMS:
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 add_random_users$(EXEEXT): $(add_random_users_OBJECTS) $(add_random_users_=
DEPENDENCIES)=20
 	@rm -f add_random_users$(EXEEXT)
 	$(LINK) $(add_random_users_OBJECTS) $(add_random_users_LDADD) $(LIBS)
@@ -560,118 +661,154 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/add-random-users.Po at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/add_enctype.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ank.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/check.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/cpw.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/del.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/del_enctype.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dump.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ext.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/get.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/init.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kadm_conn.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kadmin-commands.Po at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kadmin.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kadmind.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/load.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/mod.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pw_quality.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/random_password.Po at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rename.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rpc.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/server.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/stash.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_util.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/util.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man8: $(man8_MANS) $(man_MANS)
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -680,49 +817,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -733,15 +884,32 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -757,13 +925,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -800,6 +972,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -811,6 +984,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -821,6 +995,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -828,26 +1004,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libexecPROGRAMS install-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -868,11 +1053,10 @@
 	uninstall-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
 	check-local clean clean-checkPROGRAMS clean-generic \
@@ -961,6 +1145,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1046,7 +1233,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1064,6 +1251,7 @@
=20
 kadmin-commands.c kadmin-commands.h: kadmin-commands.in
 	$(SLC) $(srcdir)/kadmin-commands.in
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/add-random-=
users.c
--- a/head/crypto/heimdal/kadmin/add-random-users.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/kadmin/add-random-users.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 2000 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
=20
-RCSID("$Id: add-random-users.c 19213 2006-12-04 23:36:36Z lha $");
-
 #define WORDS_FILENAME "/usr/share/dict/words"
=20
 #define NUSERS 1000
@@ -74,6 +72,7 @@
     if (n =3D=3D 0)
 	errx(1, "%s is an empty file, no words to try", filename);
     *ret_w =3D w;
+    fclose(f);
     return n;
 }
=20
@@ -119,17 +118,17 @@
     ret =3D krb5_init_context(&context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
-    ret =3D kadm5_s_init_with_password_ctx(context,=20
+    ret =3D kadm5_s_init_with_password_ctx(context,
 					 KADM5_ADMIN_SERVICE,
 					 NULL,
 					 KADM5_ADMIN_SERVICE,
-					 NULL, 0, 0,=20
+					 NULL, 0, 0,
 					 &kadm_handle);
     if(ret)
 	krb5_err(context, 1, ret, "kadm5_init_with_password");
=20
     nwords =3D read_words (filename, &words);
-   =20
+
     for (i =3D 0; i < n; ++i)
 	add_user (context, kadm_handle, nwords, words);
     kadm5_destroy(kadm_handle);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/add_enctype=
.c
--- a/head/crypto/heimdal/kadmin/add_enctype.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/kadmin/add_enctype.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1999-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: add_enctype.c 20287 2007-02-22 03:12:30Z lha $");
-
 /*
  * del_enctype principal enctypes...
  */
@@ -102,6 +100,7 @@
 	    if (etypes[j] =3D=3D key->key_data_type[0]) {
 		krb5_warnx(context, "enctype %d already exists",
 			   (int)etypes[j]);
+		free(new_key_data);
 		goto out;
 	    }
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/ank.c
--- a/head/crypto/heimdal/kadmin/ank.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/ank.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,61 +1,59 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: ank.c 16658 2006-01-25 12:29:46Z lha $");
-
 /*
  * fetch the default principal corresponding to `princ'
  */
=20
 static krb5_error_code
-get_default (kadm5_server_context *context,
+get_default (kadm5_server_context *contextp,
 	     krb5_principal princ,
 	     kadm5_principal_ent_t default_ent)
 {
     krb5_error_code ret;
     krb5_principal def_principal;
-    krb5_realm *realm =3D krb5_princ_realm(context->context, princ);
+    krb5_const_realm realm =3D krb5_principal_get_realm(contextp->context,=
 princ);
=20
-    ret =3D krb5_make_principal (context->context, &def_principal,
-			       *realm, "default", NULL);
+    ret =3D krb5_make_principal (contextp->context, &def_principal,
+			       realm, "default", NULL);
     if (ret)
 	return ret;
-    ret =3D kadm5_get_principal (context, def_principal, default_ent,
+    ret =3D kadm5_get_principal (contextp, def_principal, default_ent,
 			       KADM5_PRINCIPAL_NORMAL_MASK);
-    krb5_free_principal (context->context, def_principal);
+    krb5_free_principal (contextp->context, def_principal);
     return ret;
 }
=20
@@ -68,7 +66,7 @@
 add_one_principal (const char *name,
 		   int rand_key,
 		   int rand_password,
-		   int use_defaults,=20
+		   int use_defaults,
 		   char *password,
 		   krb5_key_data *key_data,
 		   const char *max_ticket_life,
@@ -95,7 +93,7 @@
     mask |=3D KADM5_PRINCIPAL;
=20
     ret =3D set_entry(context, &princ, &mask,
-		    max_ticket_life, max_renewable_life,=20
+		    max_ticket_life, max_renewable_life,
 		    expiration, pw_expiration, attributes);
     if (ret)
 	goto out;
@@ -110,7 +108,7 @@
 	    KADM5_PRINC_EXPIRE_TIME | KADM5_PW_EXPIRATION;
     }
=20
-    if(use_defaults)=20
+    if(use_defaults)
 	set_defaults(&princ, &mask, default_ent, default_mask);
     else
 	if(edit_entry(&princ, &mask, default_ent, default_mask))
@@ -133,13 +131,13 @@
 	ret =3D UI_UTIL_read_pw_string (pwbuf, sizeof(pwbuf), prompt, 1);
 	free (prompt);
 	if (ret) {
-	    krb5_set_error_string(context, "failed to verify password");
 	    ret =3D KRB5_LIBOS_BADPWDMATCH;
+	    krb5_set_error_message(context, ret, "failed to verify password");
 	    goto out;
 	}
 	password =3D pwbuf;
     }
-   =20
+
     ret =3D kadm5_create_principal(kadm_handle, &princ, mask, password);
     if(ret) {
 	krb5_warn(context, ret, "kadm5_create_principal");
@@ -148,7 +146,7 @@
     if(rand_key) {
 	krb5_keyblock *new_keys;
 	int n_keys, i;
-	ret =3D kadm5_randkey_principal(kadm_handle, princ_ent,=20
+	ret =3D kadm5_randkey_principal(kadm_handle, princ_ent,
 				      &new_keys, &n_keys);
 	if(ret){
 	    krb5_warn(context, ret, "kadm5_randkey_principal");
@@ -158,11 +156,11 @@
 	    krb5_free_keyblock_contents(context, &new_keys[i]);
 	if (n_keys > 0)
 	    free(new_keys);
-	kadm5_get_principal(kadm_handle, princ_ent, &princ,=20
+	kadm5_get_principal(kadm_handle, princ_ent, &princ,
 			    KADM5_PRINCIPAL | KADM5_KVNO | KADM5_ATTRIBUTES);
 	princ.attributes &=3D (~KRB5_KDB_DISALLOW_ALL_TIX);
 	princ.kvno =3D 1;
-	kadm5_modify_principal(kadm_handle, &princ,=20
+	kadm5_modify_principal(kadm_handle, &princ,
 			       KADM5_ATTRIBUTES | KADM5_KVNO);
 	kadm5_free_principal_ent(kadm_handle, &princ);
     } else if (key_data) {
@@ -171,7 +169,7 @@
 	if (ret) {
 	    krb5_warn(context, ret, "kadm5_chpass_principal_with_key");
 	}
-	kadm5_get_principal(kadm_handle, princ_ent, &princ,=20
+	kadm5_get_principal(kadm_handle, princ_ent, &princ,
 			    KADM5_PRINCIPAL | KADM5_ATTRIBUTES);
 	princ.attributes &=3D (~KRB5_KDB_DISALLOW_ALL_TIX);
 	kadm5_modify_principal(kadm_handle, &princ, KADM5_ATTRIBUTES);
@@ -234,7 +232,7 @@
 	const char *error;
=20
 	if (parse_des_key (opt->key_string, key_data, &error)) {
-	    fprintf (stderr, "failed parsing key \"%s\": %s\n",=20
+	    fprintf (stderr, "failed parsing key \"%s\": %s\n",
 		     opt->key_string, error);
 	    return 1;
 	}
@@ -242,10 +240,10 @@
     }
=20
     for(i =3D 0; i < argc; i++) {
-	ret =3D add_one_principal (argv[i],=20
-				 opt->random_key_flag,=20
+	ret =3D add_one_principal (argv[i],
+				 opt->random_key_flag,
 				 opt->random_password_flag,
-				 opt->use_defaults_flag,=20
+				 opt->use_defaults_flag,
 				 opt->password_string,
 				 kdp,
 				 opt->max_ticket_life_string,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/check.c
--- a/head/crypto/heimdal/kadmin/check.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/check.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /*
@@ -38,8 +38,6 @@
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: check.c 20962 2007-06-07 05:09:24Z lha $");
-
 static int
 get_check_entry(const char *name, kadm5_principal_ent_rec *ent)
 {
@@ -69,7 +67,7 @@
     kadm5_principal_ent_rec princ;
     char *name;
     int i;
-   =20
+
     ret =3D krb5_unparse_name(context, principal, &name);
     if (ret)
 	return 1;
@@ -85,10 +83,10 @@
=20
     for (i =3D 0; i < princ.n_key_data; i++) {
 	size_t keysize;
-	ret =3D krb5_enctype_keysize(context,=20
+	ret =3D krb5_enctype_keysize(context,
 				   princ.key_data[i].key_data_type[0],
 				   &keysize);
-	if (ret =3D=3D 0 && keysize !=3D princ.key_data[i].key_data_length[0]) {
+	if (ret =3D=3D 0 && keysize !=3D (size_t)princ.key_data[i].key_data_lengt=
h[0]) {
 	    krb5_warnx(context,
 		       "Principal %s enctype %d, wrong length: %lu\n",
 		       name, princ.key_data[i].key_data_type[0],
@@ -142,7 +140,7 @@
 	free(p);
 	goto fail;
     }
-    free(p);   =20
+    free(p);
=20
     kadm5_free_principal_ent(kadm_handle, &ent);
=20
@@ -187,13 +185,12 @@
     kadm5_free_principal_ent(kadm_handle, &ent);
=20
     /*
-     * Check for duplicate afs keys=20
+     * Check for duplicate afs keys
      */
=20
     p2 =3D strdup(realm);
     if (p2 =3D=3D NULL) {
 	krb5_warn(context, errno, "malloc");
-	free(p);
 	goto fail;
     }
     strlwr(p2);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/cpw.c
--- a/head/crypto/heimdal/kadmin/cpw.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/cpw.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: cpw.c 16755 2006-02-18 23:30:32Z lha $");
-
 struct cpw_entry_data {
     int random_key;
     int random_password;
@@ -120,7 +118,7 @@
 do_cpw_entry(krb5_principal principal, void *data)
 {
     struct cpw_entry_data *e =3D data;
-   =20
+
     if (e->random_key)
 	return set_random_key (principal);
     else if (e->random_password)
@@ -160,12 +158,12 @@
 		"--random-key, --random-password, --password, --key\n");
 	return 1;
     }
-=09
+
     if (opt->key_string) {
 	const char *error;
=20
 	if (parse_des_key (opt->key_string, key_data, &error)) {
-	    fprintf (stderr, "failed parsing key \"%s\": %s\n",=20
+	    fprintf (stderr, "failed parsing key \"%s\": %s\n",
 		     opt->key_string, error);
 	    return 1;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/del.c
--- a/head/crypto/heimdal/kadmin/del.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/del.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: del.c 16754 2006-02-18 23:29:43Z lha $");
-
 static int
 do_del_entry(krb5_principal principal, void *data)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/del_enctype=
.c
--- a/head/crypto/heimdal/kadmin/del_enctype.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/kadmin/del_enctype.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1999-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: del_enctype.c 16658 2006-01-25 12:29:46Z lha $");
-
 /*
  * del_enctype principal enctypes...
  */
@@ -84,7 +82,7 @@
     }
=20
     new_key_data   =3D malloc(princ.n_key_data * sizeof(*new_key_data));
-    if (new_key_data =3D=3D NULL) {
+    if (new_key_data =3D=3D NULL && princ.n_key_data !=3D 0) {
 	krb5_warnx (context, "out of memory");
 	goto out;
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/dump.c
--- a/head/crypto/heimdal/kadmin/dump.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/dump.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,40 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
 #include <kadm5/private.h>
=20
-RCSID("$Id: dump.c 14518 2005-01-19 17:09:56Z lha $");
-
 extern int local_flag;
=20
 int
@@ -45,7 +43,7 @@
     krb5_error_code ret;
     FILE *f;
     HDB *db =3D NULL;
-   =20
+
     if(!local_flag) {
 	krb5_warnx(context, "dump is only available in local (-l) mode");
 	return 0;
@@ -57,7 +55,7 @@
 	f =3D stdout;
     else
 	f =3D fopen(argv[0], "w");
-   =20
+
     if(f =3D=3D NULL) {
 	krb5_warn(context, errno, "open: %s", argv[0]);
 	goto out;
@@ -68,7 +66,7 @@
 	goto out;
     }
=20
-    hdb_foreach(context, db, opt->decrypt_flag ? HDB_F_DECRYPT : 0,=20
+    hdb_foreach(context, db, opt->decrypt_flag ? HDB_F_DECRYPT : 0,
 		hdb_print_entry, f);
=20
     db->hdb_close(context, db);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/ext.c
--- a/head/crypto/heimdal/kadmin/ext.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/ext.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: ext.c 16658 2006-01-25 12:29:46Z lha $");
-
 struct ext_keytab_data {
     krb5_keytab keytab;
 };
@@ -49,8 +47,8 @@
     krb5_keytab_entry *keys =3D NULL;
     krb5_keyblock *k =3D NULL;
     int i, n_k;
-   =20
-    ret =3D kadm5_get_principal(kadm_handle, principal, &princ,=20
+
+    ret =3D kadm5_get_principal(kadm_handle, principal, &princ,
 			      KADM5_PRINCIPAL|KADM5_KVNO|KADM5_KEY_DATA);
     if(ret)
 	return ret;
@@ -59,7 +57,7 @@
 	keys =3D malloc(sizeof(*keys) * princ.n_key_data);
 	if (keys =3D=3D NULL) {
 	    kadm5_free_principal_ent(kadm_handle, &princ);
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    return ENOMEM;
 	}
 	for (i =3D 0; i < princ.n_key_data; i++) {
@@ -83,7 +81,7 @@
 	keys =3D malloc(sizeof(*keys) * n_k);
 	if (keys =3D=3D NULL) {
 	    kadm5_free_principal_ent(kadm_handle, &princ);
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    return ENOMEM;
 	}
 	for (i =3D 0; i < n_k; i++) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/get.c
--- a/head/crypto/heimdal/kadmin/get.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/get.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
@@ -36,8 +36,6 @@
 #include <parse_units.h>
 #include <rtbl.h>
=20
-RCSID("$Id: get.c 21745 2007-07-31 16:11:25Z lha $");
-
 static struct field_name {
     const char *fieldname;
     unsigned int fieldvalue;
@@ -100,7 +98,7 @@
     data->mask |=3D ff->fieldvalue;
     data->extra_mask |=3D ff->extra_mask;
     if(data->table !=3D NULL)
-	rtbl_add_column_by_id(data->table, ff->fieldvalue,=20
+	rtbl_add_column_by_id(data->table, ff->fieldvalue,
 			      header ? header : ff->default_header, ff->flags);
     return 0;
 }
@@ -112,9 +110,9 @@
 static int
 cmp_salt (const krb5_salt *salt, const krb5_key_data *k)
 {
-    if (salt->salttype !=3D k->key_data_type[1])
+    if (salt->salttype !=3D (size_t)k->key_data_type[1])
 	return 1;
-    if (salt->saltvalue.length !=3D k->key_data_length[1])
+    if (salt->saltvalue.length !=3D (size_t)k->key_data_length[1])
 	return 1;
     return memcmp (salt->saltvalue.data, k->key_data_contents[1],
 		   salt->saltvalue.length);
@@ -159,7 +157,7 @@
 }
=20
 static void
-format_field(kadm5_principal_ent_t princ, unsigned int field,=20
+format_field(kadm5_principal_ent_t princ, unsigned int field,
 	     unsigned int subfield, char *buf, size_t buf_len, int condensed)
 {
     switch(field) {
@@ -169,27 +167,27 @@
 	else
 	    krb5_unparse_name_fixed(context, princ->principal, buf, buf_len);
 	break;
-   =20
+
     case KADM5_PRINC_EXPIRE_TIME:
 	time_t2str(princ->princ_expire_time, buf, buf_len, !condensed);
 	break;
-	   =20
+
     case KADM5_PW_EXPIRATION:
 	time_t2str(princ->pw_expiration, buf, buf_len, !condensed);
 	break;
-	   =20
+
     case KADM5_LAST_PWD_CHANGE:
 	time_t2str(princ->last_pwd_change, buf, buf_len, !condensed);
 	break;
-	   =20
+
     case KADM5_MAX_LIFE:
 	deltat2str(princ->max_life, buf, buf_len);
 	break;
-	   =20
+
     case KADM5_MAX_RLIFE:
 	deltat2str(princ->max_renewable_life, buf, buf_len);
 	break;
-	   =20
+
     case KADM5_MOD_TIME:
 	time_t2str(princ->mod_date, buf, buf_len, !condensed);
 	break;
@@ -209,7 +207,8 @@
 	snprintf(buf, buf_len, "%d", princ->kvno);
 	break;
     case KADM5_MKVNO:
-	snprintf(buf, buf_len, "%d", princ->mkvno);
+	/* XXX libkadm5srv decrypts the keys, so mkvno is always 0. */
+	strlcpy(buf, "unknown", buf_len);
 	break;
     case KADM5_LAST_SUCCESS:
 	time_t2str(princ->last_success, buf, buf_len, !condensed);
@@ -246,7 +245,7 @@
 	krb5_tl_data *tl;
=20
 	for (tl =3D princ->tl_data; tl !=3D NULL; tl =3D tl->tl_data_next)
-	    if (tl->tl_data_type =3D=3D subfield)
+	    if ((unsigned)tl->tl_data_type =3D=3D subfield)
 		break;
 	if (tl =3D=3D NULL) {
 	    strlcpy(buf, "", buf_len);
@@ -262,7 +261,8 @@
 	case KRB5_TL_PKINIT_ACL: {
 	    HDB_Ext_PKINIT_acl acl;
 	    size_t size;
-	    int i, ret;
+	    int ret;
+	    size_t i;
=20
 	    ret =3D decode_HDB_Ext_PKINIT_acl(tl->tl_data_contents,
 					    tl->tl_data_length,
@@ -294,7 +294,8 @@
 	case KRB5_TL_ALIASES: {
 	    HDB_Ext_Aliases alias;
 	    size_t size;
-	    int i, ret;
+	    int ret;
+	    size_t i;
=20
 	    ret =3D decode_HDB_Ext_Aliases(tl->tl_data_contents,
 					 tl->tl_data_length,
@@ -310,7 +311,7 @@
 		ret =3D krb5_unparse_name(context, &alias.aliases.val[i], &p);
 		if (ret)
 		    break;
-		if (i < 0)
+		if (i > 0)
 		    strlcat(buf, " ", buf_len);
 		strlcat(buf, p, buf_len);
 		free(p);
@@ -335,7 +336,7 @@
 {
     char buf[1024];
     struct field_info *f;
-   =20
+
     for(f =3D data->chead; f !=3D NULL; f =3D f->next) {
 	format_field(princ, f->ff->fieldvalue, f->ff->subvalue, buf, sizeof(buf),=
 1);
 	rtbl_add_column_entry_by_id(data->table, f->ff->fieldvalue, buf);
@@ -348,7 +349,7 @@
     char buf[1024];
     struct field_info *f;
     int width =3D 0;
-   =20
+
     for(f =3D data->chead; f !=3D NULL; f =3D f->next) {
 	int w =3D strlen(f->header ? f->header : f->ff->def_longheader);
 	if(w > width)
@@ -367,9 +368,9 @@
     kadm5_principal_ent_rec princ;
     krb5_error_code ret;
     struct get_entry_data *e =3D data;
-   =20
+
     memset(&princ, 0, sizeof(princ));
-    ret =3D kadm5_get_principal(kadm_handle, principal,=20
+    ret =3D kadm5_get_principal(kadm_handle, principal,
 			      &princ,
 			      e->mask | e->extra_mask);
     if(ret)
@@ -420,9 +421,35 @@
     return 0;
 }
=20
+static int
+do_list_entry(krb5_principal principal, void *data)
+{
+    char buf[1024];
+    krb5_error_code ret;
+
+    ret =3D krb5_unparse_name_fixed_short(context, principal, buf, sizeof(=
buf));
+    if (ret !=3D 0)
+        return ret;
+    printf("%s\n", buf);
+    return 0;
+}
+
+static int
+listit(const char *funcname, int argc, char **argv)
+{
+    int i;
+    krb5_error_code ret, saved_ret =3D 0;
+
+    for (i =3D 0; i < argc; i++) {
+	ret =3D foreach_principal(argv[i], do_list_entry, funcname, NULL);
+        if (saved_ret =3D=3D 0 && ret !=3D 0)
+            saved_ret =3D ret;
+    }
+    return saved_ret !=3D 0;
+}
+
 #define DEFAULT_COLUMNS_SHORT "principal,princ_expire_time,pw_expiration,l=
ast_pwd_change,max_life,max_rlife"
 #define DEFAULT_COLUMNS_LONG "principal,princ_expire_time,pw_expiration,la=
st_pwd_change,max_life,max_rlife,kvno,mkvno,last_success,last_failed,fail_a=
uth_count,mod_time,mod_name,attributes,keytypes,pkinit-acl,aliases"
-#define DEFAULT_COLUMNS_TERSE "principal=3D"
=20
 static int
 getit(struct get_options *opt, const char *name, int argc, char **argv)
@@ -430,7 +457,7 @@
     int i;
     krb5_error_code ret;
     struct get_entry_data data;
-   =20
+
     if(opt->long_flag =3D=3D -1 && (opt->short_flag =3D=3D 1 || opt->terse=
_flag =3D=3D 1))
 	opt->long_flag =3D 0;
     if(opt->short_flag =3D=3D -1 && (opt->long_flag =3D=3D 1 || opt->terse=
_flag =3D=3D 1))
@@ -440,13 +467,16 @@
     if(opt->long_flag =3D=3D 0 && opt->short_flag =3D=3D 0 && opt->terse_f=
lag =3D=3D 0)
 	opt->short_flag =3D 1;
=20
+    if (opt->terse_flag)
+        return listit(name, argc, argv);
+
     data.table =3D NULL;
     data.chead =3D NULL;
     data.ctail =3D &data.chead;
     data.mask =3D 0;
     data.extra_mask =3D 0;
=20
-    if(opt->short_flag || opt->terse_flag) {
+    if(opt->short_flag) {
 	data.table =3D rtbl_create();
 	rtbl_set_separator(data.table, "  ");
 	data.format =3D print_entry_short;
@@ -455,24 +485,20 @@
     if(opt->column_info_string =3D=3D NULL) {
 	if(opt->long_flag)
 	    ret =3D setup_columns(&data, DEFAULT_COLUMNS_LONG);
-	else if(opt->short_flag)
+	else
 	    ret =3D setup_columns(&data, DEFAULT_COLUMNS_SHORT);
-	else {
-	    ret =3D setup_columns(&data, DEFAULT_COLUMNS_TERSE);
-	    rtbl_set_flags(data.table, RTBL_HEADER_STYLE_NONE);
-	}
     } else
 	ret =3D setup_columns(&data, opt->column_info_string);
-=09
+
     if(ret !=3D 0) {
 	if(data.table !=3D NULL)
 	    rtbl_destroy(data.table);
 	return 0;
     }
-   =20
+
     for(i =3D 0; i < argc; i++)
-	ret =3D foreach_principal(argv[i], do_get_entry, "get", &data);
-   =20
+	ret =3D foreach_principal(argv[i], do_get_entry, name, &data);
+
     if(data.table !=3D NULL) {
 	rtbl_format(data.table, stdout);
 	rtbl_destroy(data.table);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/init.c
--- a/head/crypto/heimdal/kadmin/init.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/init.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
 #include <kadm5/private.h>
=20
-RCSID("$Id: init.c 17447 2006-05-05 10:52:01Z lha $");
-
 static kadm5_ret_t
 create_random_entry(krb5_principal princ,
 		    unsigned max_life,
@@ -78,22 +78,22 @@
     /* Create the entry with a random password */
     ret =3D kadm5_create_principal(kadm_handle, &ent, mask, password);
     if(ret) {
-	krb5_warn(context, ret, "create_random_entry(%s): randkey failed",=20
+	krb5_warn(context, ret, "create_random_entry(%s): randkey failed",
 		  name);
 	goto out;
     }
-   =20
+
     /* Replace the string2key based keys with real random bytes */
     ret =3D kadm5_randkey_principal(kadm_handle, princ, &keys, &n_keys);
     if(ret) {
-	krb5_warn(context, ret, "create_random_entry*%s): randkey failed",
+	krb5_warn(context, ret, "create_random_entry(%s): randkey failed",
 		  name);
 	goto out;
     }
     for(i =3D 0; i < n_keys; i++)
 	krb5_free_keyblock_contents(context, &keys[i]);
     free(keys);
-    ret =3D kadm5_get_principal(kadm_handle, princ, &ent,=20
+    ret =3D kadm5_get_principal(kadm_handle, princ, &ent,
 			      KADM5_PRINCIPAL | KADM5_ATTRIBUTES);
     if(ret) {
 	krb5_warn(context, ret, "create_random_entry(%s): "
@@ -102,7 +102,7 @@
     }
     ent.attributes &=3D (~KRB5_KDB_DISALLOW_ALL_TIX);
     ent.kvno =3D 1;
-    ret =3D kadm5_modify_principal(kadm_handle, &ent,=20
+    ret =3D kadm5_modify_principal(kadm_handle, &ent,
 				 KADM5_ATTRIBUTES|KADM5_KVNO);
     kadm5_free_principal_ent (kadm_handle, &ent);
     if(ret) {
@@ -123,23 +123,23 @@
     kadm5_ret_t ret;
     int i;
     HDB *db;
-    krb5_deltat max_life, max_rlife;
+    krb5_deltat max_life =3D 0, max_rlife =3D 0;
=20
-    if(!local_flag) {
+    if (!local_flag) {
 	krb5_warnx(context, "init is only available in local (-l) mode");
 	return 0;
     }
=20
     if (opt->realm_max_ticket_life_string) {
 	if (str2deltat (opt->realm_max_ticket_life_string, &max_life) !=3D 0) {
-	    krb5_warnx (context, "unable to parse \"%s\"",=20
+	    krb5_warnx (context, "unable to parse \"%s\"",
 			opt->realm_max_ticket_life_string);
 	    return 0;
 	}
     }
     if (opt->realm_max_renewable_life_string) {
 	if (str2deltat (opt->realm_max_renewable_life_string, &max_rlife) !=3D 0)=
 {
-	    krb5_warnx (context, "unable to parse \"%s\"",=20
+	    krb5_warnx (context, "unable to parse \"%s\"",
 			opt->realm_max_renewable_life_string);
 	    return 0;
 	}
@@ -157,15 +157,9 @@
 	krb5_principal princ;
 	const char *realm =3D argv[i];
=20
-	/* Create `krbtgt/REALM' */
-	ret =3D krb5_make_principal(context, &princ, realm,
-				  KRB5_TGS_NAME, realm, NULL);
-	if(ret)
-	    return 0;
 	if (opt->realm_max_ticket_life_string =3D=3D NULL) {
 	    max_life =3D 0;
 	    if(edit_deltat ("Realm max ticket life", &max_life, NULL, 0)) {
-		krb5_free_principal(context, princ);
 		return 0;
 	    }
 	}
@@ -173,15 +167,24 @@
 	    max_rlife =3D 0;
 	    if(edit_deltat("Realm max renewable ticket life", &max_rlife,
 			   NULL, 0)) {
-		krb5_free_principal(context, princ);
 		return 0;
 	    }
 	}
+
+	/* Create `krbtgt/REALM' */
+	ret =3D krb5_make_principal(context, &princ, realm,
+				  KRB5_TGS_NAME, realm, NULL);
+	if(ret)
+	    return 0;
+
 	create_random_entry(princ, max_life, max_rlife, 0);
 	krb5_free_principal(context, princ);
=20
+	if (opt->bare_flag)
+	    continue;
+
 	/* Create `kadmin/changepw' */
-	krb5_make_principal(context, &princ, realm,=20
+	krb5_make_principal(context, &princ, realm,
 			    "kadmin", "changepw", NULL);
 	/*
 	 * The Windows XP (at least) password changing protocol
@@ -189,7 +192,7 @@
 	 * renewable, forwardable' and so fails if we disallow
 	 * forwardable here.
 	 */
-	create_random_entry(princ, 5*60, 5*60,=20
+	create_random_entry(princ, 5*60, 5*60,
 			    KRB5_KDB_DISALLOW_TGT_BASED|
 			    KRB5_KDB_PWCHANGE_SERVICE|
 			    KRB5_KDB_DISALLOW_POSTDATED|
@@ -199,7 +202,7 @@
 	krb5_free_principal(context, princ);
=20
 	/* Create `kadmin/admin' */
-	krb5_make_principal(context, &princ, realm,=20
+	krb5_make_principal(context, &princ, realm,
 			    "kadmin", "admin", NULL);
 	create_random_entry(princ, 60*60, 60*60, KRB5_KDB_REQUIRES_PRE_AUTH);
 	krb5_free_principal(context, princ);
@@ -221,6 +224,14 @@
 			    KRB5_KDB_DISALLOW_TGT_BASED);
 	krb5_free_principal(context, princ);
=20
+	/* Create `WELLKNOWN/ANONYMOUS' for anonymous as-req */
+	krb5_make_principal(context, &princ, realm,
+			    KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME, NULL);
+	create_random_entry(princ, 60*60, 60*60,
+			    KRB5_KDB_REQUIRES_PRE_AUTH);
+	krb5_free_principal(context, princ);
+
+
 	/* Create `default' */
 	{
 	    kadm5_principal_ent_rec ent;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/kadm_conn.c
--- a/head/crypto/heimdal/kadmin/kadm_conn.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/kadm_conn.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2000 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
@@ -36,8 +36,6 @@
 #include <sys/wait.h>
 #endif
=20
-RCSID("$Id: kadm_conn.c 16007 2005-09-01 18:49:57Z lha $");
-
 struct kadm_port {
     char *port;
     unsigned short def_port;
@@ -45,16 +43,16 @@
 } *kadm_ports;
=20
 static void
-add_kadm_port(krb5_context context, const char *service, unsigned int port)
+add_kadm_port(krb5_context contextp, const char *service, unsigned int por=
t)
 {
     struct kadm_port *p;
     p =3D malloc(sizeof(*p));
     if(p =3D=3D NULL) {
-	krb5_warnx(context, "failed to allocate %lu bytes\n",=20
+	krb5_warnx(contextp, "failed to allocate %lu bytes\n",
 		   (unsigned long)sizeof(*p));
 	return;
     }
-   =20
+
     p->port =3D strdup(service);
     p->def_port =3D port;
=20
@@ -63,9 +61,9 @@
 }
=20
 static void
-add_standard_ports (krb5_context context)
+add_standard_ports (krb5_context contextp)
 {
-    add_kadm_port(context, "kerberos-adm", 749);
+    add_kadm_port(contextp, "kerberos-adm", 749);
 }
=20
 /*
@@ -75,15 +73,15 @@
  */
=20
 void
-parse_ports(krb5_context context, const char *str)
+parse_ports(krb5_context contextp, const char *str)
 {
     char p[128];
=20
     while(strsep_copy(&str, " \t", p, sizeof(p)) !=3D -1) {
 	if(strcmp(p, "+") =3D=3D 0)
-	    add_standard_ports(context);
+	    add_standard_ports(contextp);
 	else
-	    add_kadm_port(context, p, 0);
+	    add_kadm_port(contextp, p, 0);
     }
 }
=20
@@ -94,7 +92,12 @@
 sigchld(int sig)
 {
     int status;
-    waitpid(-1, &status, 0);
+    /*
+     * waitpid() is async safe. will return -1 or 0 on no more zombie
+     * children
+     */
+    while ((waitpid(-1, &status, WNOHANG)) > 0)
+	;
     SIGRETURN(0);
 }
=20
@@ -117,68 +120,73 @@
 }
=20
 static int
-spawn_child(krb5_context context, int *socks, int num_socks, int this_sock)
+spawn_child(krb5_context contextp, int *socks,
+	    unsigned int num_socks, int this_sock)
 {
-    int e, i;
+    int e;
+    size_t i;
     struct sockaddr_storage __ss;
     struct sockaddr *sa =3D (struct sockaddr *)&__ss;
     socklen_t sa_size =3D sizeof(__ss);
-    int s;
+    krb5_socket_t s;
     pid_t pid;
     krb5_address addr;
     char buf[128];
     size_t buf_len;
=20
     s =3D accept(socks[this_sock], sa, &sa_size);
-    if(s < 0) {
-	krb5_warn(context, errno, "accept");
+    if(rk_IS_BAD_SOCKET(s)) {
+	krb5_warn(contextp, rk_SOCK_ERRNO, "accept");
 	return 1;
     }
-    e =3D krb5_sockaddr2address(context, sa, &addr);
+    e =3D krb5_sockaddr2address(contextp, sa, &addr);
     if(e)
-	krb5_warn(context, e, "krb5_sockaddr2address");
+	krb5_warn(contextp, e, "krb5_sockaddr2address");
     else {
-	e =3D krb5_print_address (&addr, buf, sizeof(buf),=20
+	e =3D krb5_print_address (&addr, buf, sizeof(buf),
 				&buf_len);
-	if(e)=20
-	    krb5_warn(context, e, "krb5_print_address");
+	if(e)
+	    krb5_warn(contextp, e, "krb5_print_address");
 	else
-	    krb5_warnx(context, "connection from %s", buf);
-	krb5_free_address(context, &addr);
+	    krb5_warnx(contextp, "connection from %s", buf);
+	krb5_free_address(contextp, &addr);
     }
-   =20
+
     pid =3D fork();
     if(pid =3D=3D 0) {
 	for(i =3D 0; i < num_socks; i++)
-	    close(socks[i]);
+	    rk_closesocket(socks[i]);
 	dup2(s, STDIN_FILENO);
 	dup2(s, STDOUT_FILENO);
 	if(s !=3D STDIN_FILENO && s !=3D STDOUT_FILENO)
-	    close(s);
+	    rk_closesocket(s);
 	return 0;
     } else {
-	close(s);
+	rk_closesocket(s);
     }
     return 1;
 }
=20
-static int
-wait_for_connection(krb5_context context,
-		    int *socks, int num_socks)
+static void
+wait_for_connection(krb5_context contextp,
+		    krb5_socket_t *socks, unsigned int num_socks)
 {
-    int i, e;
+    unsigned int i;
+    int e;
     fd_set orig_read_set, read_set;
-    int max_fd =3D -1;
-   =20
+    int status, max_fd =3D -1;
+
     FD_ZERO(&orig_read_set);
-   =20
+
     for(i =3D 0; i < num_socks; i++) {
+#ifdef FD_SETSIZE
 	if (socks[i] >=3D FD_SETSIZE)
 	    errx (1, "fd too large");
+#endif
 	FD_SET(socks[i], &orig_read_set);
 	max_fd =3D max(max_fd, socks[i]);
     }
-   =20
+
     pgrp =3D getpid();
=20
     if(setpgid(0, pgrp) < 0)
@@ -191,41 +199,43 @@
     while (term_flag =3D=3D 0) {
 	read_set =3D orig_read_set;
 	e =3D select(max_fd + 1, &read_set, NULL, NULL, NULL);
-	if(e < 0) {
-	    if(errno !=3D EINTR)
-		krb5_warn(context, errno, "select");
+	if(rk_IS_SOCKET_ERROR(e)) {
+	    if(rk_SOCK_ERRNO !=3D EINTR)
+		krb5_warn(contextp, rk_SOCK_ERRNO, "select");
 	} else if(e =3D=3D 0)
-	    krb5_warnx(context, "select returned 0");
+	    krb5_warnx(contextp, "select returned 0");
 	else {
 	    for(i =3D 0; i < num_socks; i++) {
 		if(FD_ISSET(socks[i], &read_set))
-		    if(spawn_child(context, socks, num_socks, i) =3D=3D 0)
-			return 0;
+		    if(spawn_child(contextp, socks, num_socks, i) =3D=3D 0)
+			return;
 	    }
 	}
     }
     signal(SIGCHLD, SIG_IGN);
-    while(1) {
-	int status;
-	pid_t pid;
-	pid =3D waitpid(-1, &status, 0);
-	if(pid =3D=3D -1 && errno =3D=3D ECHILD)
-	    break;
-    }
+
+    while ((waitpid(-1, &status, WNOHANG)) > 0)
+	;
+
     exit(0);
 }
=20
=20
-int
-start_server(krb5_context context)
+void
+start_server(krb5_context contextp, const char *port_str)
 {
     int e;
     struct kadm_port *p;
=20
-    int *socks =3D NULL, *tmp;
-    int num_socks =3D 0;
+    krb5_socket_t *socks =3D NULL, *tmp;
+    unsigned int num_socks =3D 0;
     int i;
=20
+    if (port_str =3D=3D NULL)
+	port_str =3D "+";
+
+    parse_ports(contextp, port_str);
+
     for(p =3D kadm_ports; p; p =3D p->next) {
 	struct addrinfo hints, *ai, *ap;
 	char portstr[32];
@@ -240,38 +250,38 @@
 	}
=20
 	if(e) {
-	    krb5_warn(context, krb5_eai_to_heim_errno(e, errno),
+	    krb5_warn(contextp, krb5_eai_to_heim_errno(e, errno),
 		      "%s", portstr);
 	    continue;
 	}
 	i =3D 0;
-	for(ap =3D ai; ap; ap =3D ap->ai_next)=20
+	for(ap =3D ai; ap; ap =3D ap->ai_next)
 	    i++;
 	tmp =3D realloc(socks, (num_socks + i) * sizeof(*socks));
 	if(tmp =3D=3D NULL) {
-	    krb5_warnx(context, "failed to reallocate %lu bytes",=20
+	    krb5_warnx(contextp, "failed to reallocate %lu bytes",
 		       (unsigned long)(num_socks + i) * sizeof(*socks));
 	    continue;
 	}
 	socks =3D tmp;
 	for(ap =3D ai; ap; ap =3D ap->ai_next) {
-	    int s =3D socket(ap->ai_family, ap->ai_socktype, ap->ai_protocol);
-	    if(s < 0) {
-		krb5_warn(context, errno, "socket");
+	    krb5_socket_t s =3D socket(ap->ai_family, ap->ai_socktype, ap->ai_pro=
tocol);
+	    if(rk_IS_BAD_SOCKET(s)) {
+		krb5_warn(contextp, rk_SOCK_ERRNO, "socket");
 		continue;
 	    }
=20
 	    socket_set_reuseaddr(s, 1);
 	    socket_set_ipv6only(s, 1);
=20
-	    if (bind (s, ap->ai_addr, ap->ai_addrlen) < 0) {
-		krb5_warn(context, errno, "bind");
-		close(s);
+	    if (rk_IS_SOCKET_ERROR(bind (s, ap->ai_addr, ap->ai_addrlen))) {
+		krb5_warn(contextp, rk_SOCK_ERRNO, "bind");
+		rk_closesocket(s);
 		continue;
 	    }
-	    if (listen (s, SOMAXCONN) < 0) {
-		krb5_warn(context, errno, "listen");
-		close(s);
+	    if (rk_IS_SOCKET_ERROR(listen (s, SOMAXCONN))) {
+		krb5_warn(contextp, rk_SOCK_ERRNO, "listen");
+		rk_closesocket(s);
 		continue;
 	    }
 	    socks[num_socks++] =3D s;
@@ -279,6 +289,7 @@
 	freeaddrinfo (ai);
     }
     if(num_socks =3D=3D 0)
-	krb5_errx(context, 1, "no sockets to listen to - exiting");
-    return wait_for_connection(context, socks, num_socks);
+	krb5_errx(contextp, 1, "no sockets to listen to - exiting");
+
+    wait_for_connection(contextp, socks, num_socks);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/kadmin-comm=
ands.in
--- a/head/crypto/heimdal/kadmin/kadmin-commands.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/kadmin/kadmin-commands.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).=20
  * All rights reserved.=20
  *
@@ -30,7 +30,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
  * SUCH DAMAGE.=20
  */
-/* $Id: kadmin-commands.in 21969 2007-10-18 18:51:11Z lha $ */
+/* $Id$ */
=20
 command =3D {
 	name =3D "stash"
@@ -55,6 +55,11 @@
 		help =3D "just convert keyfile to new format"
 	}
 	option =3D {
+		long =3D "random-password"
+		type =3D "flag"
+		help =3D "use a random password (and print the password to stdout)"
+	}
+	option =3D {
 		long =3D "master-key-fd"
 		type =3D "integer"
 		argument =3D "fd"
@@ -89,6 +94,11 @@
 		type =3D "string"
 		help =3D "realm max renewable lifetime"
 	}
+	option =3D {
+		long =3D "bare"
+		type =3D "flag"
+		help =3D "only create krbtgt for realm"
+	}
 	argument =3D "realm..."
 	min_args =3D "1"
 	help =3D "Initializes the default principals for a realm. Creates the dat=
abase\nif necessary. Local (-l) mode only."
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/kadmin.8
--- a/head/crypto/heimdal/kadmin/kadmin.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/kadmin.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2000 - 2007 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2000 - 2007 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: kadmin.8 21739 2007-07-31 15:55:32Z lha $
+.\" $Id$
 .\"
 .Dd Feb  22, 2007
 .Dt KADMIN 8
@@ -40,37 +40,16 @@
 .Sh SYNOPSIS
 .Nm
 .Bk -words
-.Oo Fl p Ar string \*(Ba Xo
-.Fl -principal=3D Ns Ar string
-.Xc
-.Oc
-.Oo Fl K Ar string \*(Ba Xo
-.Fl -keytab=3D Ns Ar string
-.Xc
-.Oc
-.Oo Fl c Ar file \*(Ba Xo
-.Fl -config-file=3D Ns Ar file
-.Xc
-.Oc
-.Oo Fl k Ar file \*(Ba Xo
-.Fl -key-file=3D Ns Ar file
-.Xc
-.Oc
-.Oo Fl r Ar realm \*(Ba Xo
-.Fl -realm=3D Ns Ar realm
-.Xc
-.Oc
-.Oo Fl a Ar host \*(Ba Xo
-.Fl -admin-server=3D Ns Ar host
-.Xc
-.Oc
-.Oo Fl s Ar port number \*(Ba Xo
-.Fl -server-port=3D Ns Ar port number
-.Xc
-.Oc
-.Op Fl l | Fl -local
-.Op Fl h | Fl -help
-.Op Fl v | Fl -version
+.Op Fl p Ar string \*(Ba Fl Fl principal=3D Ns Ar string
+.Op Fl K Ar string \*(Ba Fl Fl keytab=3D Ns Ar string
+.Op Fl c Ar file \*(Ba Fl Fl config-file=3D Ns Ar file
+.Op Fl k Ar file \*(Ba Fl Fl key-file=3D Ns Ar file
+.Op Fl r Ar realm \*(Ba Fl Fl realm=3D Ns Ar realm
+.Op Fl a Ar host \*(Ba Fl Fl admin-server=3D Ns Ar host
+.Op Fl s Ar port number \*(Ba Fl Fl server-port=3D Ns Ar port number
+.Op Fl l | Fl Fl local
+.Op Fl h | Fl Fl help
+.Op Fl v | Fl Fl version
 .Op Ar command
 .Ek
 .Sh DESCRIPTION
@@ -84,45 +63,21 @@
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl p Ar string ,
-.Fl -principal=3D Ns Ar string
-.Xc
+.It Fl p Ar string , Fl Fl principal=3D Ns Ar string
 principal to authenticate as
-.It Xo
-.Fl K Ar string ,
-.Fl -keytab=3D Ns Ar string
-.Xc
+.It Fl K Ar string , Fl Fl keytab=3D Ns Ar string
 keytab for authentication principal
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 location of config file
-.It Xo
-.Fl k Ar file ,
-.Fl -key-file=3D Ns Ar file
-.Xc
+.It Fl k Ar file , Fl Fl key-file=3D Ns Ar file
 location of master key file
-.It Xo
-.Fl r Ar realm ,
-.Fl -realm=3D Ns Ar realm
-.Xc
+.It Fl r Ar realm , Fl Fl realm=3D Ns Ar realm
 realm to use
-.It Xo
-.Fl a Ar host ,
-.Fl -admin-server=3D Ns Ar host
-.Xc
+.It Fl a Ar host , Fl Fl admin-server=3D Ns Ar host
 server to contact
-.It Xo
-.Fl s Ar port number ,
-.Fl -server-port=3D Ns Ar port number
-.Xc
+.It Fl s Ar port number , Fl Fl server-port=3D Ns Ar port number
 port to use
-.It Xo
-.Fl l ,
-.Fl -local
-.Xc
+.It Fl l , Fl Fl local
 local admin mode
 .El
 .Pp
@@ -144,29 +99,25 @@
 Commands include:
 .\" not using a list here, since groff apparently gets confused
 .\" with nested Xo/Xc
-.Bd -ragged -offset indent
+.Pp
 .Nm add
-.Op Fl r | Fl -random-key
-.Op Fl -random-password
-.Oo Fl p Ar string \*(Ba Xo
-.Fl -password=3D Ns Ar string
-.Xc
-.Oc
-.Op Fl -key=3D Ns Ar string
-.Op Fl -max-ticket-life=3D Ns Ar lifetime
-.Op Fl -max-renewable-life=3D Ns Ar lifetime
-.Op Fl -attributes=3D Ns Ar attributes
-.Op Fl -expiration-time=3D Ns Ar time
-.Op Fl -pw-expiration-time=3D Ns Ar time
+.Op Fl r | Fl Fl random-key
+.Op Fl Fl random-password
+.Op Fl p Ar string \*(Ba Fl Fl password=3D Ns Ar string
+.Op Fl Fl key=3D Ns Ar string
+.Op Fl Fl max-ticket-life=3D Ns Ar lifetime
+.Op Fl Fl max-renewable-life=3D Ns Ar lifetime
+.Op Fl Fl attributes=3D Ns Ar attributes
+.Op Fl Fl expiration-time=3D Ns Ar time
+.Op Fl Fl pw-expiration-time=3D Ns Ar time
 .Ar principal...
-.Pp
 .Bd -ragged -offset indent
 Adds a new principal to the database. The options not passed on the
 command line will be promped for.
 .Ed
 .Pp
 .Nm add_enctype
-.Op Fl r | Fl -random-key
+.Op Fl r | Fl Fl random-key
 .Ar principal enctypes...
 .Pp
 .Bd -ragged -offset indent
@@ -176,14 +127,12 @@
 .Pp
 .Nm delete
 .Ar principal...
-.Pp
 .Bd -ragged -offset indent
 Removes a principal.
 .Ed
 .Pp
 .Nm del_enctype
 .Ar principal enctypes...
-.Pp
 .Bd -ragged -offset indent
 Removes some enctypes from a principal; this can be useful if the
 service belonging to the principal is known to not handle certain
@@ -192,22 +141,20 @@
 .Pp
 .Nm ext_keytab
 .Oo Fl k Ar string \*(Ba Xo
-.Fl -keytab=3D Ns Ar string
+.Fl Fl keytab=3D Ns Ar string
 .Xc
 .Oc
 .Ar principal...
-.Pp
 .Bd -ragged -offset indent
 Creates a keytab with the keys of the specified principals.
 .Ed
 .Pp
 .Nm get
-.Op Fl l | Fl -long
-.Op Fl s | Fl -short
-.Op Fl t | Fl -terse
-.Op Fl o Ar string | Fl -column-info=3D Ns Ar string
+.Op Fl l | Fl Fl long
+.Op Fl s | Fl Fl short
+.Op Fl t | Fl Fl terse
+.Op Fl o Ar string | Fl Fl column-info=3D Ns Ar string
 .Ar principal...
-.Pp
 .Bd -ragged -offset indent
 Lists the matching principals, short prints the result as a table,
 while long format produces a more verbose output. Which columns to
@@ -245,16 +192,15 @@
 .Pp
 .Nm modify
 .Oo Fl a Ar attributes \*(Ba Xo
-.Fl -attributes=3D Ns Ar attributes
+.Fl Fl attributes=3D Ns Ar attributes
 .Xc
 .Oc
-.Op Fl -max-ticket-life=3D Ns Ar lifetime
-.Op Fl -max-renewable-life=3D Ns Ar lifetime
-.Op Fl -expiration-time=3D Ns Ar time
-.Op Fl -pw-expiration-time=3D Ns Ar time
-.Op Fl -kvno=3D Ns Ar number
+.Op Fl Fl max-ticket-life=3D Ns Ar lifetime
+.Op Fl Fl max-renewable-life=3D Ns Ar lifetime
+.Op Fl Fl expiration-time=3D Ns Ar time
+.Op Fl Fl pw-expiration-time=3D Ns Ar time
+.Op Fl Fl kvno=3D Ns Ar number
 .Ar principal...
-.Pp
 .Bd -ragged -offset indent
 Modifies certain attributes of a principal. If run without command
 line options, you will be prompted. With command line options, it will
@@ -276,21 +222,20 @@
 .Li disallow-forwardable ,
 .Li disallow-postdated
 .Pp
-Attributes may be negated with a "-", e.g.,=20
-.Pp=20
+Attributes may be negated with a "-", e.g.,
+.Pp
 kadmin -l modify -a -disallow-proxiable user
 .Ed
 .Pp
 .Nm passwd
-.Op Fl r | Fl -random-key
-.Op Fl -random-password
+.Op Fl r | Fl Fl random-key
+.Op Fl Fl random-password
 .Oo Fl p Ar string \*(Ba Xo
-.Fl -password=3D Ns Ar string
+.Fl Fl password=3D Ns Ar string
 .Xc
 .Oc
-.Op Fl -key=3D Ns Ar string
+.Op Fl Fl key=3D Ns Ar string
 .Ar principal...
-.Pp
 .Bd -ragged -offset indent
 Changes the password of an existing principal.
 .Ed
@@ -298,7 +243,6 @@
 .Nm password-quality
 .Ar principal
 .Ar password
-.Pp
 .Bd -ragged -offset indent
 Run the password quality check function locally.
 You can run this on the host that is configured to run the kadmind
@@ -308,7 +252,6 @@
 .Ed
 .Pp
 .Nm privileges
-.Pp
 .Bd -ragged -offset indent
 Lists the operations you are allowed to perform. These include
 .Li add ,
@@ -324,7 +267,6 @@
 .Pp
 .Nm rename
 .Ar from to
-.Pp
 .Bd -ragged -offset indent
 Renames a principal. This is normally transparent, but since keys are
 salted with the principal name, they will have a non-standard salt,
@@ -340,28 +282,24 @@
 no realm is given, the default realm is used.
 .Ed
 .Pp
-.Ed
+When running in local mode, the following commands can also be used:
 .Pp
-When running in local mode, the following commands can also be used:
-.Bd -ragged -offset indent
 .Nm dump
-.Op Fl d | Fl -decrypt
+.Op Fl d | Fl Fl decrypt
 .Op Ar dump-file
-.Pp
 .Bd -ragged -offset indent
 Writes the database in
 .Dq human readable
 form to the specified file, or standard out. If the database is
 encrypted, the dump will also have encrypted keys, unless
-.Fl -decrypt
+.Fl Fl decrypt
 is used.
 .Ed
 .Pp
 .Nm init
-.Op Fl -realm-max-ticket-life=3D Ns Ar string
-.Op Fl -realm-max-renewable-life=3D Ns Ar string
+.Op Fl Fl realm-max-ticket-life=3D Ns Ar string
+.Op Fl Fl realm-max-renewable-life=3D Ns Ar string
 .Ar realm
-.Pp
 .Bd -ragged -offset indent
 Initializes the Kerberos database with entries for a new realm. It's
 possible to have more than one realm served by one server.
@@ -369,7 +307,6 @@
 .Pp
 .Nm load
 .Ar file
-.Pp
 .Bd -ragged -offset indent
 Reads a previously dumped database, and re-creates that database from
 scratch.
@@ -377,7 +314,6 @@
 .Pp
 .Nm merge
 .Ar file
-.Pp
 .Bd -ragged -offset indent
 Similar to
 .Nm load
@@ -386,21 +322,18 @@
 .Pp
 .Nm stash
 .Oo Fl e Ar enctype \*(Ba Xo
-.Fl -enctype=3D Ns Ar enctype
+.Fl Fl enctype=3D Ns Ar enctype
 .Xc
 .Oc
 .Oo Fl k Ar keyfile \*(Ba Xo
-.Fl -key-file=3D Ns Ar keyfile
+.Fl Fl key-file=3D Ns Ar keyfile
 .Xc
 .Oc
-.Op Fl -convert-file
-.Op Fl -master-key-fd=3D Ns Ar fd
-.Pp
+.Op Fl Fl convert-file
+.Op Fl Fl master-key-fd=3D Ns Ar fd
 .Bd -ragged -offset indent
 Writes the Kerberos master key to a file used by the KDC.
 .Ed
-.Pp
-.Ed
 .\".Sh ENVIRONMENT
 .\".Sh FILES
 .\".Sh EXAMPLES
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/kadmin.c
--- a/head/crypto/heimdal/kadmin/kadmin.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/kadmin.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,40 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
 #include <sl.h>
=20
-RCSID("$Id: kadmin.c 22253 2007-12-09 06:00:00Z lha $");
-
 static char *config_file;
 static char *keyfile;
 int local_flag;
@@ -54,41 +52,42 @@
=20
 static struct getargs args[] =3D {
     {	"principal", 	'p',	arg_string,	&client_name,
-	"principal to authenticate as" },
+	"principal to authenticate as", NULL },
     {   "keytab",	'K',	arg_string,	&keytab,
-   	"keytab for authentication principal" },
-    {=20
-	"config-file",	'c',	arg_string,	&config_file,=20
-	"location of config file",	"file"=20
+   	"keytab for authentication principal", NULL },
+    {
+	"config-file",	'c',	arg_string,	&config_file,
+	"location of config file",	"file"
     },
     {
-	"key-file",	'k',	arg_string, &keyfile,=20
+	"key-file",	'k',	arg_string, &keyfile,
 	"location of master key file", "file"
     },
-    {=09
-	"realm",	'r',	arg_string,   &realm,=20
-	"realm to use", "realm"=20
+    {
+	"realm",	'r',	arg_string,   &realm,
+	"realm to use", "realm"
     },
-    {=09
-	"admin-server",	'a',	arg_string,   &admin_server,=20
-	"server to contact", "host"=20
+    {
+	"admin-server",	'a',	arg_string,   &admin_server,
+	"server to contact", "host"
     },
-    {=09
-	"server-port",	's',	arg_integer,   &server_port,=20
-	"port to use", "port number"=20
+    {
+	"server-port",	's',	arg_integer,   &server_port,
+	"port to use", "port number"
     },
-    {	"ad", 		0, arg_flag, &ad_flag, "active directory admin mode" },
+    {	"ad", 		0, arg_flag, &ad_flag, "active directory admin mode",
+	NULL },
 #ifdef HAVE_DLOPEN
-    { "check-library", 0, arg_string, &check_library,=20
+    { "check-library", 0, arg_string, &check_library,
       "library to load password check function from", "library" },
     { "check-function", 0, arg_string, &check_function,
       "password check function to load", "function" },
     { "policy-libraries", 0, arg_strings, &policy_libraries,
       "password check function to load", "function" },
 #endif
-    {	"local", 'l', arg_flag, &local_flag, "local admin mode" },
-    {	"help",		'h',	arg_flag,   &help_flag },
-    {	"version",	'v',	arg_flag,   &version_flag }
+    {	"local", 'l', arg_flag, &local_flag, "local admin mode", NULL },
+    {	"help",		'h',	arg_flag,   &help_flag, NULL, NULL },
+    {	"version",	'v',	arg_flag,   &version_flag, NULL, NULL }
 };
=20
 static int num_args =3D sizeof(args) / sizeof(args[0]);
@@ -126,13 +125,16 @@
     uint32_t privs;
     char str[128];
     kadm5_ret_t ret;
-   =20
+
     ret =3D kadm5_get_privs(kadm_handle, &privs);
     if(ret)
 	krb5_warn(context, ret, "kadm5_get_privs");
     else{
 	ret =3D_kadm5_privs_to_string(privs, str, sizeof(str));
-	printf("%s\n", str);
+	if (ret =3D=3D 0)
+	    printf("%s\n", str);
+	else
+	    printf("privs: 0x%x\n", (unsigned int)privs);
     }
     return 0;
 }
@@ -151,7 +153,7 @@
     ret =3D krb5_init_context(&context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
-   =20
+
     if(getarg(args, num_args, argc, argv, &optidx))
 	usage(1);
=20
@@ -175,12 +177,12 @@
     ret =3D krb5_prepend_config_files_default(config_file, &files);
     if (ret)
 	krb5_err(context, 1, ret, "getting configuration files");
-   =20
+
     ret =3D krb5_set_config_files(context, files);
     krb5_free_config_files(files);
-    if(ret)=20
+    if(ret)
 	krb5_err(context, 1, ret, "reading configuration files");
-   =20
+
     memset(&conf, 0, sizeof(conf));
     if(realm) {
 	krb5_set_default_realm(context, realm); /* XXX should be fixed
@@ -207,11 +209,11 @@
     if(local_flag) {
 	int i;
=20
-	kadm5_setup_passwd_quality_check (context,=20
+	kadm5_setup_passwd_quality_check (context,
 					  check_library, check_function);
-=09
+
 	for (i =3D 0; i < policy_libraries.num_strings; i++) {
-	    ret =3D kadm5_add_passwd_quality_verifier(context,=20
+	    ret =3D kadm5_add_passwd_quality_verifier(context,
 						    policy_libraries.strings[i]);
 	    if (ret)
 		krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
@@ -219,12 +221,12 @@
 	ret =3D kadm5_add_passwd_quality_verifier(context, NULL);
 	if (ret)
 	    krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
-=09
-	ret =3D kadm5_s_init_with_password_ctx(context,=20
+
+	ret =3D kadm5_s_init_with_password_ctx(context,
 					     KADM5_ADMIN_SERVICE,
 					     NULL,
 					     KADM5_ADMIN_SERVICE,
-					     &conf, 0, 0,=20
+					     &conf, 0, 0,
 					     &kadm_handle);
     } else if (ad_flag) {
 	if (client_name =3D=3D NULL)
@@ -245,13 +247,13 @@
                                          &conf, 0, 0,
                                          &kadm_handle);
     } else
-	ret =3D kadm5_c_init_with_password_ctx(context,=20
+	ret =3D kadm5_c_init_with_password_ctx(context,
 					     client_name,
 					     NULL,
 					     KADM5_ADMIN_SERVICE,
-					     &conf, 0, 0,=20
+					     &conf, 0, 0,
 					     &kadm_handle);
-   =20
+
     if(ret)
 	krb5_err(context, 1, ret, "kadm5_init_with_password");
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/kadmin_locl=
.h
--- a/head/crypto/heimdal/kadmin/kadmin_locl.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/kadmin/kadmin_locl.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,47 +1,45 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/*=20
- * $Id: kadmin_locl.h 17580 2006-05-13 21:28:56Z lha $
- * $FreeBSD$
+/*
+ * $Id$
  */
=20
 #ifndef __ADMIN_LOCL_H__
 #define __ADMIN_LOCL_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -128,16 +126,11 @@
 	      const char *, const char *, const char *,
 	      const char *, const char *);
 int
-foreach_principal(const char *, int (*)(krb5_principal, void*),=20
+foreach_principal(const char *, int (*)(krb5_principal, void*),
 		  const char *, void *);
=20
 int parse_des_key (const char *, krb5_key_data *, const char **);
=20
-/* server.c */
-
-krb5_error_code
-kadmind_loop (krb5_context, krb5_auth_context, krb5_keytab, int);
-
 /* random_password.c */
=20
 void
@@ -148,11 +141,17 @@
 extern sig_atomic_t term_flag, doing_useful_work;
=20
 void parse_ports(krb5_context, const char*);
-int start_server(krb5_context);
+void start_server(krb5_context, const char*);
=20
 /* server.c */
=20
 krb5_error_code
-kadmind_loop (krb5_context, krb5_auth_context, krb5_keytab, int);
+kadmind_loop (krb5_context, krb5_keytab, int);
+
+/* rpc.c */
+
+int
+handle_mit(krb5_context, void *, size_t, int);
+
=20
 #endif /* __ADMIN_LOCL_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/kadmind.8
--- a/head/crypto/heimdal/kadmin/kadmind.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/kadmind.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2002 - 2004 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2002 - 2004 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: kadmind.8 14370 2004-12-08 17:20:21Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd December  8, 2004
 .Dt KADMIND 8
@@ -41,21 +41,21 @@
 .Nm
 .Bk -words
 .Oo Fl c Ar file \*(Ba Xo
-.Fl -config-file=3D Ns Ar file
+.Fl Fl config-file=3D Ns Ar file
 .Xc
 .Oc
 .Oo Fl k Ar file \*(Ba Xo
-.Fl -key-file=3D Ns Ar file
+.Fl Fl key-file=3D Ns Ar file
 .Xc
 .Oc
-.Op Fl -keytab=3D Ns Ar keytab
+.Op Fl Fl keytab=3D Ns Ar keytab
 .Oo Fl r Ar realm \*(Ba Xo
-.Fl -realm=3D Ns Ar realm
+.Fl Fl realm=3D Ns Ar realm
 .Xc
 .Oc
-.Op Fl d | Fl -debug
+.Op Fl d | Fl Fl debug
 .Oo Fl p Ar port \*(Ba Xo
-.Fl -ports=3D Ns Ar port
+.Fl Fl ports=3D Ns Ar port
 .Xc
 .Oc
 .Ek
@@ -67,7 +67,7 @@
 .Xr inetd 8 ,
 otherwise it behaves as a daemon, forking processes for each new
 connection. The
-.Fl -debug
+.Fl Fl debug
 option causes
 .Nm
 to accept exactly one connection, which is useful for debugging.
@@ -76,8 +76,7 @@
 .Xr kpasswdd 8
 daemon is responsible for the Kerberos 5 password changing protocol
 (used by
-.Xr kpasswd 1 )
-.
+.Xr kpasswd 1 ) .
 .Pp
 This daemon should only be run on the master server, and not on any
 slaves.
@@ -118,34 +117,17 @@
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 location of config file
-.It Xo
-.Fl k Ar file ,
-.Fl -key-file=3D Ns Ar file
-.Xc
+.It Fl k Ar file , Fl Fl key-file=3D Ns Ar file
 location of master key file
-.It Xo
-.Fl -keytab=3D Ns Ar keytab
-.Xc
+.It Fl Fl keytab=3D Ns Ar keytab
 what keytab to use
-.It Xo
-.Fl r Ar realm ,
-.Fl -realm=3D Ns Ar realm
-.Xc
+.It Fl r Ar realm , Fl Fl realm=3D Ns Ar realm
 realm to use
-.It Xo
-.Fl d ,
-.Fl -debug
-.Xc
+.It Fl d , Fl Fl debug
 enable debugging
-.It Xo
-.Fl p Ar port ,
-.Fl -ports=3D Ns Ar port
-.Xc
+.It Fl p Ar port , Fl Fl ports=3D Ns Ar port
 ports to listen to. By default, if run as a daemon, it listens to port
 749, but you can add any number of ports with this option. The port
 string is a whitespace separated list of port specifications, with the
@@ -162,7 +144,7 @@
 to listen to port 4711 in addition to any
 compiled in defaults:
 .Pp
-.D1 Nm Fl -ports Ns Li "=3D\*[q]+ 4711\*[q] &"
+.D1 Nm Fl Fl ports Ns Li "=3D\*[q]+ 4711\*[q] &"
 .Pp
 This acl file will grant Joe all rights, and allow Mallory to view and
 add host principals.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/kadmind.c
--- a/head/crypto/heimdal/kadmin/kadmind.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/kadmind.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,45 +1,44 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
=20
-RCSID("$Id: kadmind.c 22250 2007-12-09 05:57:31Z lha $");
-
 static char *check_library  =3D NULL;
 static char *check_function =3D NULL;
 static getarg_strings policy_libraries =3D { 0, NULL };
 static char *config_file;
-static char *keytab_str =3D "HDB:";
+static char sHDB[] =3D "HDB:";
+static char *keytab_str =3D sHDB;
 static int help_flag;
 static int version_flag;
 static int debug_flag;
@@ -47,32 +46,32 @@
 char *realm;
=20
 static struct getargs args[] =3D {
-    {=20
-	"config-file",	'c',	arg_string,	&config_file,=20
-	"location of config file",	"file"=20
+    {
+	"config-file",	'c',	arg_string,	&config_file,
+	"location of config file",	"file"
     },
     {
 	"keytab",	0,	arg_string, &keytab_str,
 	"what keytab to use", "keytab"
     },
-    {	"realm",	'r',	arg_string,   &realm,=20
-	"realm to use", "realm"=20
+    {	"realm",	'r',	arg_string,   &realm,
+	"realm to use", "realm"
     },
 #ifdef HAVE_DLOPEN
-    { "check-library", 0, arg_string, &check_library,=20
+    { "check-library", 0, arg_string, &check_library,
       "library to load password check function from", "library" },
     { "check-function", 0, arg_string, &check_function,
       "password check function to load", "function" },
     { "policy-libraries", 0, arg_strings, &policy_libraries,
       "password check function to load", "function" },
 #endif
-    {	"debug",	'd',	arg_flag,   &debug_flag,=20
-	"enable debugging"=20
+    {	"debug",	'd',	arg_flag,   &debug_flag,
+	"enable debugging", NULL
     },
-    {	"ports",	'p',	arg_string, &port_str,=20
+    {	"ports",	'p',	arg_string, &port_str,
 	"ports to listen to", "port" },
-    {	"help",		'h',	arg_flag,   &help_flag },
-    {	"version",	'v',	arg_flag,   &version_flag }
+    {	"help",		'h',	arg_flag,   &help_flag, NULL, NULL },
+    {	"version",	'v',	arg_flag,   &version_flag, NULL, NULL }
 };
=20
 static int num_args =3D sizeof(args) / sizeof(args[0]);
@@ -92,9 +91,10 @@
     krb5_error_code ret;
     char **files;
     int optidx =3D 0;
-    int e, i;
+    int i;
     krb5_log_facility *logfacility;
     krb5_keytab keytab;
+    krb5_socket_t sfd =3D rk_INVALID_SOCKET;
=20
     setprogname(argv[0]);
=20
@@ -102,8 +102,10 @@
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
=20
-    while((e =3D getarg(args, num_args, argc, argv, &optidx)))
+    if (getarg(args, num_args, argc, argv, &optidx)) {
 	warnx("error at argument `%s'", argv[optidx]);
+	usage(1);
+    }
=20
     if (help_flag)
 	usage (0);
@@ -121,16 +123,16 @@
 	if (config_file =3D=3D NULL)
 	    errx(1, "out of memory");
     }
-   =20
+
     ret =3D krb5_prepend_config_files_default(config_file, &files);
     if (ret)
 	krb5_err(context, 1, ret, "getting configuration files");
-   =20
+
     ret =3D krb5_set_config_files(context, files);
     krb5_free_config_files(files);
-    if(ret)=20
+    if(ret)
 	krb5_err(context, 1, ret, "reading configuration files");
-   =20
+
     ret =3D krb5_openlog(context, "kadmind", &logfacility);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_openlog");
@@ -149,7 +151,7 @@
     kadm5_setup_passwd_quality_check (context, check_library, check_functi=
on);
=20
     for (i =3D 0; i < policy_libraries.num_strings; i++) {
-	ret =3D kadm5_add_passwd_quality_verifier(context,=20
+	ret =3D kadm5_add_passwd_quality_verifier(context,
 						policy_libraries.strings[i]);
 	if (ret)
 	    krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
@@ -158,30 +160,42 @@
     if (ret)
 	krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
=20
-    {
-	int fd =3D 0;
+    if(debug_flag) {
+	int debug_port;
+
+	if(port_str =3D=3D NULL)
+	    debug_port =3D krb5_getportbyname (context, "kerberos-adm",
+					     "tcp", 749);
+	else
+	    debug_port =3D htons(atoi(port_str));
+	mini_inetd(debug_port, &sfd);
+    } else {
+#ifdef _WIN32
+	pidfile(NULL);
+	start_server(context, port_str);
+#else
 	struct sockaddr_storage __ss;
 	struct sockaddr *sa =3D (struct sockaddr *)&__ss;
 	socklen_t sa_size =3D sizeof(__ss);
-	krb5_auth_context ac =3D NULL;
-	int debug_port;
=20
-	if(debug_flag) {
-	    if(port_str =3D=3D NULL)
-		debug_port =3D krb5_getportbyname (context, "kerberos-adm",=20
-						 "tcp", 749);
-	    else
-		debug_port =3D htons(atoi(port_str));
-	    mini_inetd(debug_port);
-	} else if(roken_getsockname(STDIN_FILENO, sa, &sa_size) < 0 &&=20
-		   errno =3D=3D ENOTSOCK) {
-	    parse_ports(context, port_str ? port_str : "+");
+	/*
+	 * Check if we are running inside inetd or not, if not, start
+	 * our own server.
+	 */
+
+	if(roken_getsockname(STDIN_FILENO, sa, &sa_size) < 0 &&
+	   rk_SOCK_ERRNO =3D=3D ENOTSOCK) {
 	    pidfile(NULL);
-	    start_server(context);
+	    start_server(context, port_str);
 	}
-	if(realm)
-	    krb5_set_default_realm(context, realm); /* XXX */
-	kadmind_loop(context, ac, keytab, fd);
+#endif /* _WIN32 */
+	sfd =3D STDIN_FILENO;
     }
+
+    if(realm)
+	krb5_set_default_realm(context, realm); /* XXX */
+
+    kadmind_loop(context, keytab, sfd);
+
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/load.c
--- a/head/crypto/heimdal/kadmin/load.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/load.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,40 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
 #include <kadm5/private.h>
=20
-RCSID("$Id: load.c 16658 2006-01-25 12:29:46Z lha $");
-
 struct entry {
     char *principal;
     char *key;
@@ -55,7 +53,7 @@
 static char *
 skip_next(char *p)
 {
-    while(*p && !isspace((unsigned char)*p))=20
+    while(*p && !isspace((unsigned char)*p))
 	p++;
     *p++ =3D 0;
     while(*p && isspace((unsigned char)*p))
@@ -78,7 +76,7 @@
=20
     if(strcmp(s, "-") =3D=3D 0)
 	return 0;
-    if(sscanf(s, "%04d%02d%02d%02d%02d%02d",=20
+    if(sscanf(s, "%04d%02d%02d%02d%02d%02d",
 	      &year, &month, &date, &hour, &minute, &second) !=3D 6)
 	return -1;
     tm.tm_year  =3D year - 1900;
@@ -155,8 +153,8 @@
     krb5_error_code ret;
     int tmp;
     char *p;
-    int i;
-   =20
+    size_t i;
+
     p =3D strsep(&str, ":");
     if (sscanf(p, "%d", &tmp) !=3D 1)
 	return 1;
@@ -164,7 +162,7 @@
     p =3D strsep(&str, ":");
     while(p){
 	Key *key;
-	key =3D realloc(ent->keys.val,=20
+	key =3D realloc(ent->keys.val,
 		      (ent->keys.len + 1) * sizeof(*ent->keys.val));
 	if(key =3D=3D NULL)
 	    krb5_errx (context, 1, "realloc: out of memory");
@@ -203,11 +201,11 @@
 	    p++;
 	    p_len =3D strlen(p);
=20
-	    key->salt =3D malloc(sizeof(*key->salt));
+	    key->salt =3D calloc(1, sizeof(*key->salt));
 	    if (key->salt =3D=3D NULL)
 		krb5_errx (context, 1, "malloc: out of memory");
 	    key->salt->type =3D type;
-	=09
+
 	    if (p_len) {
 		if(*p =3D=3D '\"') {
 		    ret =3D krb5_data_copy(&key->salt->salt, p + 1, p_len - 2);
@@ -333,8 +331,10 @@
 	d =3D malloc(len);
=20
 	len =3D hex_decode(p, d, len);
-	if (len < 0)
+	if (len < 0) {
+	    free(d);
 	    return -1;
+	}
=20
 	ret =3D decode_HDB_extension(d, len, &ext, NULL);
 	free(d);
@@ -395,7 +395,6 @@
     line =3D 0;
     ret =3D 0;
     while(fgets(s, sizeof(s), f) !=3D NULL) {
-	ret =3D 0;
 	line++;
=20
 	p =3D s;
@@ -412,7 +411,7 @@
 	    }
 	}
 	p =3D skip_next(p);
-=09
+
 	e.key =3D p;
 	p =3D skip_next(p);
=20
@@ -444,26 +443,25 @@
 	p =3D skip_next(p);
=20
 	e.extensions =3D p;
-	p =3D skip_next(p);
+	skip_next(p);
=20
 	memset(&ent, 0, sizeof(ent));
 	ret =3D krb5_parse_name(context, e.principal, &ent.entry.principal);
 	if(ret) {
-	    fprintf(stderr, "%s:%d:%s (%s)\n",=20
-		    filename,=20
-		    line,
-		    krb5_get_err_text(context, ret),
-		    e.principal);
+	    const char *msg =3D krb5_get_error_message(context, ret);
+	    fprintf(stderr, "%s:%d:%s (%s)\n",
+		    filename, line, msg, e.principal);
+	    krb5_free_error_message(context, msg);
 	    continue;
 	}
-=09
+
 	if (parse_keys(&ent.entry, e.key)) {
 	    fprintf (stderr, "%s:%d:error parsing keys (%s)\n",
 		     filename, line, e.key);
 	    hdb_free_entry (context, &ent);
 	    continue;
 	}
-=09
+
 	if (parse_event(&ent.entry.created_by, e.created) =3D=3D -1) {
 	    fprintf (stderr, "%s:%d:error parsing created event (%s)\n",
 		     filename, line, e.created);
@@ -555,13 +553,13 @@
=20
     return doit(argv[0], mergep);
 }
-=20
+
 int
 load(void *opt, int argc, char **argv)
 {
     return loadit(0, "load", argc, argv);
 }
-=20
+
 int
 merge(void *opt, int argc, char **argv)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/mod.c
--- a/head/crypto/heimdal/kadmin/mod.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/mod.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: mod.c 21968 2007-10-18 18:50:33Z lha $");
-
 static void
 add_tl(kadm5_principal_ent_rec *princ, int type, krb5_data *data)
 {
@@ -46,7 +44,7 @@
     tl->tl_data_type =3D KRB5_TL_EXTENSION;
     tl->tl_data_length =3D data->length;
     tl->tl_data_contents =3D data->data;
-   =20
+
     princ->n_tl_data++;
     ptl =3D &princ->tl_data;
     while (*ptl !=3D NULL)
@@ -57,15 +55,15 @@
 }
=20
 static void
-add_constrained_delegation(krb5_context context,
+add_constrained_delegation(krb5_context contextp,
 			   kadm5_principal_ent_rec *princ,
 			   struct getarg_strings *strings)
 {
     krb5_error_code ret;
     HDB_extension ext;
     krb5_data buf;
-    size_t size;
-	   =20
+    size_t size =3D 0;
+
     memset(&ext, 0, sizeof(ext));
     ext.mandatory =3D FALSE;
     ext.data.element =3D choice_HDB_extension_data_allowed_to_delegate_to;
@@ -77,15 +75,19 @@
 	krb5_principal p;
 	int i;
=20
-	ext.data.u.allowed_to_delegate_to.val =3D=20
-	    calloc(strings->num_strings,=20
+	ext.data.u.allowed_to_delegate_to.val =3D
+	    calloc(strings->num_strings,
 		   sizeof(ext.data.u.allowed_to_delegate_to.val[0]));
 	ext.data.u.allowed_to_delegate_to.len =3D strings->num_strings;
-=09
+
 	for (i =3D 0; i < strings->num_strings; i++) {
-	    ret =3D krb5_parse_name(context, strings->strings[i], &p);
+	    ret =3D krb5_parse_name(contextp, strings->strings[i], &p);
+	    if (ret)
+		abort();
 	    ret =3D copy_Principal(p, &ext.data.u.allowed_to_delegate_to.val[i]);
-	    krb5_free_principal(context, p);
+	    if (ret)
+		abort();
+	    krb5_free_principal(contextp, p);
 	}
     }
=20
@@ -101,16 +103,16 @@
 }
=20
 static void
-add_aliases(krb5_context context, kadm5_principal_ent_rec *princ,
+add_aliases(krb5_context contextp, kadm5_principal_ent_rec *princ,
 	    struct getarg_strings *strings)
 {
     krb5_error_code ret;
     HDB_extension ext;
     krb5_data buf;
     krb5_principal p;
-    size_t size;
+    size_t size =3D 0;
     int i;
-   =20
+
     memset(&ext, 0, sizeof(ext));
     ext.mandatory =3D FALSE;
     ext.data.element =3D choice_HDB_extension_data_aliases;
@@ -120,15 +122,15 @@
 	ext.data.u.aliases.aliases.val =3D NULL;
 	ext.data.u.aliases.aliases.len =3D 0;
     } else {
-	ext.data.u.aliases.aliases.val =3D=20
-	    calloc(strings->num_strings,=20
+	ext.data.u.aliases.aliases.val =3D
+	    calloc(strings->num_strings,
 		   sizeof(ext.data.u.aliases.aliases.val[0]));
 	ext.data.u.aliases.aliases.len =3D strings->num_strings;
-=09
+
 	for (i =3D 0; i < strings->num_strings; i++) {
-	    ret =3D krb5_parse_name(context, strings->strings[i], &p);
+	    ret =3D krb5_parse_name(contextp, strings->strings[i], &p);
 	    ret =3D copy_Principal(p, &ext.data.u.aliases.aliases.val[i]);
-	    krb5_free_principal(context, p);
+	    krb5_free_principal(contextp, p);
 	}
     }
=20
@@ -139,20 +141,20 @@
 	abort();
     if (buf.length !=3D size)
 	abort();
-   =20
+
     add_tl(princ, KRB5_TL_EXTENSION, &buf);
 }
=20
 static void
-add_pkinit_acl(krb5_context context, kadm5_principal_ent_rec *princ,
+add_pkinit_acl(krb5_context contextp, kadm5_principal_ent_rec *princ,
 	       struct getarg_strings *strings)
 {
     krb5_error_code ret;
     HDB_extension ext;
     krb5_data buf;
-    size_t size;
+    size_t size =3D 0;
     int i;
-   =20
+
     memset(&ext, 0, sizeof(ext));
     ext.mandatory =3D FALSE;
     ext.data.element =3D choice_HDB_extension_data_pkinit_acl;
@@ -162,11 +164,11 @@
 	ext.data.u.pkinit_acl.val =3D NULL;
 	ext.data.u.pkinit_acl.len =3D 0;
     } else {
-	ext.data.u.pkinit_acl.val =3D=20
-	    calloc(strings->num_strings,=20
+	ext.data.u.pkinit_acl.val =3D
+	    calloc(strings->num_strings,
 		   sizeof(ext.data.u.pkinit_acl.val[0]));
 	ext.data.u.pkinit_acl.len =3D strings->num_strings;
-=09
+
 	for (i =3D 0; i < strings->num_strings; i++) {
 	    ext.data.u.pkinit_acl.val[i].subject =3D estrdup(strings->strings[i]);
 	}
@@ -179,7 +181,7 @@
 	abort();
     if (buf.length !=3D size)
 	abort();
-   =20
+
     add_tl(princ, KRB5_TL_EXTENSION, &buf);
 }
=20
@@ -190,17 +192,17 @@
     kadm5_principal_ent_rec princ;
     int mask =3D 0;
     struct modify_options *e =3D data;
-   =20
+
     memset (&princ, 0, sizeof(princ));
     ret =3D kadm5_get_principal(kadm_handle, principal, &princ,
-			      KADM5_PRINCIPAL | KADM5_ATTRIBUTES |=20
+			      KADM5_PRINCIPAL | KADM5_ATTRIBUTES |
 			      KADM5_MAX_LIFE | KADM5_MAX_RLIFE |
 			      KADM5_PRINC_EXPIRE_TIME |
 			      KADM5_PW_EXPIRATION);
-    if(ret)=20
+    if(ret)
 	return ret;
=20
-    if(e->max_ticket_life_string ||=20
+    if(e->max_ticket_life_string ||
        e->max_renewable_life_string ||
        e->expiration_time_string ||
        e->pw_expiration_time_string ||
@@ -209,11 +211,11 @@
        e->constrained_delegation_strings.num_strings ||
        e->alias_strings.num_strings ||
        e->pkinit_acl_strings.num_strings) {
-	ret =3D set_entry(context, &princ, &mask,=20
-			e->max_ticket_life_string,=20
-			e->max_renewable_life_string,=20
-			e->expiration_time_string,=20
-			e->pw_expiration_time_string,=20
+	ret =3D set_entry(context, &princ, &mask,
+			e->max_ticket_life_string,
+			e->max_renewable_life_string,
+			e->expiration_time_string,
+			e->pw_expiration_time_string,
 			e->attributes_string);
 	if(e->kvno_integer !=3D -1) {
 	    princ.kvno =3D e->kvno_integer;
@@ -240,7 +242,7 @@
 	if(ret)
 	    krb5_warn(context, ret, "kadm5_modify_principal");
     }
-   =20
+
     kadm5_free_principal_ent(kadm_handle, &princ);
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/pw_quality.c
--- a/head/crypto/heimdal/kadmin/pw_quality.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/pw_quality.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2003-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: pw_quality.c 14026 2004-07-05 11:41:22Z joda $");
-
 int
 password_quality(void *opt, int argc, char **argv)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/random_pass=
word.c
--- a/head/crypto/heimdal/kadmin/random_password.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/kadmin/random_password.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,45 +1,43 @@
 /*
- * Copyright (c) 1998, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
=20
-RCSID("$Id: random_password.c 21745 2007-07-31 16:11:25Z lha $");
-
 /* This file defines some a function that generates a random password,
    that can be used when creating a large amount of principals (such
    as for a batch of students). Since this is a political matter, you
    should think about how secure generated passwords has to be.
-  =20
+
    Both methods defined here will give you at least 55 bits of
    entropy.
    */
@@ -65,9 +63,9 @@
     }
 #else
     char *pass;
-    generate_password(&pass, 3,=20
-		      "abcdefghijklmnopqrstuvwxyz", 7,=20
-		      "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 2,=20
+    generate_password(&pass, 3,
+		      "abcdefghijklmnopqrstuvwxyz", 7,
+		      "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 2,
 		      "@$%&*()-+=3D:,/<>1234567890", 1);
     strlcpy(pw, pass, len);
     memset(pass, 0, strlen(pass));
@@ -104,11 +102,11 @@
    |   | ---- * |   /    |
    |   | Ni!    |  /___  |
     i=3D1          \  i=3D1  /
-  =20
+
     Since it uses the RND function above, neither the size of each
     class, nor the total length of the generated password should be
     larger than 127 (without fixing RND).
-  =20
+
    */
 static void
 generate_password(char **pw, int num_classes, ...)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/rename.c
--- a/head/crypto/heimdal/kadmin/rename.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/rename.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: rename.c 17007 2006-04-07 13:11:24Z lha $");
-
 int
 rename_entry(void *opt, int argc, char **argv)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/server.c
--- a/head/crypto/heimdal/kadmin/server.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/server.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,50 +1,48 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include <krb5-private.h>
=20
-RCSID("$Id: server.c 17611 2006-06-02 22:10:21Z lha $");
-
 static kadm5_ret_t
-kadmind_dispatch(void *kadm_handle, krb5_boolean initial,
+kadmind_dispatch(void *kadm_handlep, krb5_boolean initial,
 		 krb5_data *in, krb5_data *out)
 {
     kadm5_ret_t ret;
     int32_t cmd, mask, tmp;
-    kadm5_server_context *context =3D kadm_handle;
+    kadm5_server_context *contextp =3D kadm_handlep;
     char client[128], name[128], name2[128];
-    char *op =3D "";
+    const char *op =3D "";
     krb5_principal princ, princ2;
     kadm5_principal_ent_rec ent;
     char *password, *expression;
@@ -53,11 +51,13 @@
     char **princs;
     int n_princs;
     krb5_storage *sp;
-   =20
-    krb5_unparse_name_fixed(context->context, context->caller,=20
+
+    krb5_unparse_name_fixed(contextp->context, contextp->caller,
 			    client, sizeof(client));
-   =20
+
     sp =3D krb5_storage_from_data(in);
+    if (sp =3D=3D NULL)
+	krb5_errx(contextp->context, 1, "out of memory");
=20
     krb5_ret_int32(sp, &cmd);
     switch(cmd){
@@ -68,25 +68,26 @@
 	    goto fail;
 	ret =3D krb5_ret_int32(sp, &mask);
 	if(ret){
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
-	krb5_unparse_name_fixed(context->context, princ, name, sizeof(name));
-	krb5_warnx(context->context, "%s: %s %s", client, op, name);
-	ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_GET, princ);
+	mask |=3D KADM5_PRINCIPAL;
+	krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name));
+	krb5_warnx(contextp->context, "%s: %s %s", client, op, name);
+	ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_GET, princ);
 	if(ret){
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
-	ret =3D kadm5_get_principal(kadm_handle, princ, &ent, mask);
+	ret =3D kadm5_get_principal(kadm_handlep, princ, &ent, mask);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, ret);
 	if(ret =3D=3D 0){
 	    kadm5_store_principal_ent(sp, &ent);
-	    kadm5_free_principal_ent(kadm_handle, &ent);
+	    kadm5_free_principal_ent(kadm_handlep, &ent);
 	}
-	krb5_free_principal(context->context, princ);
+	krb5_free_principal(contextp->context, princ);
 	break;
     }
     case kadm_delete:{
@@ -94,15 +95,15 @@
 	ret =3D krb5_ret_principal(sp, &princ);
 	if(ret)
 	    goto fail;
-	krb5_unparse_name_fixed(context->context, princ, name, sizeof(name));
-	krb5_warnx(context->context, "%s: %s %s", client, op, name);
-	ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_DELETE, princ);
+	krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name));
+	krb5_warnx(contextp->context, "%s: %s %s", client, op, name);
+	ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_DELETE, princ);
 	if(ret){
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
-	ret =3D kadm5_delete_principal(kadm_handle, princ);
-	krb5_free_principal(context->context, princ);
+	ret =3D kadm5_delete_principal(kadm_handlep, princ);
+	krb5_free_principal(contextp->context, princ);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, ret);
@@ -115,28 +116,28 @@
 	    goto fail;
 	ret =3D krb5_ret_int32(sp, &mask);
 	if(ret){
-	    kadm5_free_principal_ent(context->context, &ent);
+	    kadm5_free_principal_ent(contextp->context, &ent);
 	    goto fail;
 	}
 	ret =3D krb5_ret_string(sp, &password);
 	if(ret){
-	    kadm5_free_principal_ent(context->context, &ent);
+	    kadm5_free_principal_ent(contextp->context, &ent);
 	    goto fail;
 	}
-	krb5_unparse_name_fixed(context->context, ent.principal,=20
+	krb5_unparse_name_fixed(contextp->context, ent.principal,
 				name, sizeof(name));
-	krb5_warnx(context->context, "%s: %s %s", client, op, name);
-	ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_ADD,
+	krb5_warnx(contextp->context, "%s: %s %s", client, op, name);
+	ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_ADD,
 					  ent.principal);
 	if(ret){
-	    kadm5_free_principal_ent(context->context, &ent);
+	    kadm5_free_principal_ent(contextp->context, &ent);
 	    memset(password, 0, strlen(password));
 	    free(password);
 	    goto fail;
 	}
-	ret =3D kadm5_create_principal(kadm_handle, &ent,=20
+	ret =3D kadm5_create_principal(kadm_handlep, &ent,
 				     mask, password);
-	kadm5_free_principal_ent(kadm_handle, &ent);
+	kadm5_free_principal_ent(kadm_handlep, &ent);
 	memset(password, 0, strlen(password));
 	free(password);
 	krb5_storage_free(sp);
@@ -151,20 +152,20 @@
 	    goto fail;
 	ret =3D krb5_ret_int32(sp, &mask);
 	if(ret){
-	    kadm5_free_principal_ent(context, &ent);
+	    kadm5_free_principal_ent(contextp, &ent);
 	    goto fail;
 	}
-	krb5_unparse_name_fixed(context->context, ent.principal,=20
+	krb5_unparse_name_fixed(contextp->context, ent.principal,
 				name, sizeof(name));
-	krb5_warnx(context->context, "%s: %s %s", client, op, name);
-	ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_MODIFY,
+	krb5_warnx(contextp->context, "%s: %s %s", client, op, name);
+	ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_MODIFY,
 					  ent.principal);
 	if(ret){
-	    kadm5_free_principal_ent(context, &ent);
+	    kadm5_free_principal_ent(contextp, &ent);
 	    goto fail;
 	}
-	ret =3D kadm5_modify_principal(kadm_handle, &ent, mask);
-	kadm5_free_principal_ent(kadm_handle, &ent);
+	ret =3D kadm5_modify_principal(kadm_handlep, &ent, mask);
+	kadm5_free_principal_ent(kadm_handlep, &ent);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, ret);
@@ -177,27 +178,27 @@
 	    goto fail;
 	ret =3D krb5_ret_principal(sp, &princ2);
 	if(ret){
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
-	krb5_unparse_name_fixed(context->context, princ, name, sizeof(name));
-	krb5_unparse_name_fixed(context->context, princ2, name2, sizeof(name2));
-	krb5_warnx(context->context, "%s: %s %s -> %s",=20
+	krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name));
+	krb5_unparse_name_fixed(contextp->context, princ2, name2, sizeof(name2));
+	krb5_warnx(contextp->context, "%s: %s %s -> %s",
 		   client, op, name, name2);
-	ret =3D _kadm5_acl_check_permission(context,=20
+	ret =3D _kadm5_acl_check_permission(contextp,
 					  KADM5_PRIV_ADD,
 					  princ2)
-	    || _kadm5_acl_check_permission(context,=20
+	    || _kadm5_acl_check_permission(contextp,
 					   KADM5_PRIV_DELETE,
 					   princ);
 	if(ret){
-	    krb5_free_principal(context->context, princ);
-	    krb5_free_principal(context->context, princ2);
+	    krb5_free_principal(contextp->context, princ);
+	    krb5_free_principal(contextp->context, princ2);
 	    goto fail;
 	}
-	ret =3D kadm5_rename_principal(kadm_handle, princ, princ2);
-	krb5_free_principal(context->context, princ);
-	krb5_free_principal(context->context, princ2);
+	ret =3D kadm5_rename_principal(kadm_handlep, princ, princ2);
+	krb5_free_principal(contextp->context, princ);
+	krb5_free_principal(contextp->context, princ2);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, ret);
@@ -210,23 +211,26 @@
 	    goto fail;
 	ret =3D krb5_ret_string(sp, &password);
 	if(ret){
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
-	krb5_unparse_name_fixed(context->context, princ, name, sizeof(name));
-	krb5_warnx(context->context, "%s: %s %s", client, op, name);
+	krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name));
+	krb5_warnx(contextp->context, "%s: %s %s", client, op, name);
=20
 	/*
 	 * The change is allowed if at least one of:
-
-	 * a) it's for the principal him/herself and this was an
+	 *
+	 * a) allowed by sysadmin
+	 * b) it's for the principal him/herself and this was an
 	 *    initial ticket, but then, check with the password quality
 	 *    function.
-	 * b) the user is on the CPW ACL.
+	 * c) the user is on the CPW ACL.
 	 */
=20
-	if (initial
-	    && krb5_principal_compare (context->context, context->caller,
+	if (krb5_config_get_bool_default(contextp->context, NULL, TRUE,
+					 "kadmin", "allow_self_change_password", NULL)
+	    && initial
+	    && krb5_principal_compare (contextp->context, contextp->caller,
 				       princ))
 	{
 	    krb5_data pwd_data;
@@ -235,23 +239,23 @@
 	    pwd_data.data =3D password;
 	    pwd_data.length =3D strlen(password);
=20
-	    pwd_reason =3D kadm5_check_password_quality (context->context,
+	    pwd_reason =3D kadm5_check_password_quality (contextp->context,
 						       princ, &pwd_data);
 	    if (pwd_reason !=3D NULL)
 		ret =3D KADM5_PASS_Q_DICT;
 	    else
 		ret =3D 0;
 	} else
-	    ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_CPW, princ);
+	    ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_CPW, princ);
=20
 	if(ret) {
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    memset(password, 0, strlen(password));
 	    free(password);
 	    goto fail;
 	}
-	ret =3D kadm5_chpass_principal(kadm_handle, princ, password);
-	krb5_free_principal(context->context, princ);
+	ret =3D kadm5_chpass_principal(kadm_handlep, princ, password);
+	krb5_free_principal(contextp->context, princ);
 	memset(password, 0, strlen(password));
 	free(password);
 	krb5_storage_free(sp);
@@ -270,21 +274,21 @@
 	    goto fail;
 	ret =3D krb5_ret_int32(sp, &n_key_data);
 	if (ret) {
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
 	/* n_key_data will be squeezed into an int16_t below. */
 	if (n_key_data < 0 || n_key_data >=3D 1 << 16 ||
-	    n_key_data > UINT_MAX/sizeof(*key_data)) {
+	    (size_t)n_key_data > UINT_MAX/sizeof(*key_data)) {
 	    ret =3D ERANGE;
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
=20
 	key_data =3D malloc (n_key_data * sizeof(*key_data));
-	if (key_data =3D=3D NULL) {
+	if (key_data =3D=3D NULL && n_key_data !=3D 0) {
 	    ret =3D ENOMEM;
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
=20
@@ -293,38 +297,38 @@
 	    if (ret) {
 		int16_t dummy =3D i;
=20
-		kadm5_free_key_data (context, &dummy, key_data);
+		kadm5_free_key_data (contextp, &dummy, key_data);
 		free (key_data);
-		krb5_free_principal(context->context, princ);
+		krb5_free_principal(contextp->context, princ);
 		goto fail;
 	    }
 	}
=20
-	krb5_unparse_name_fixed(context->context, princ, name, sizeof(name));
-	krb5_warnx(context->context, "%s: %s %s", client, op, name);
+	krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name));
+	krb5_warnx(contextp->context, "%s: %s %s", client, op, name);
=20
 	/*
 	 * The change is only allowed if the user is on the CPW ACL,
 	 * this it to force password quality check on the user.
 	 */
=20
-	ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_CPW, princ);
+	ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_CPW, princ);
 	if(ret) {
 	    int16_t dummy =3D n_key_data;
=20
-	    kadm5_free_key_data (context, &dummy, key_data);
+	    kadm5_free_key_data (contextp, &dummy, key_data);
 	    free (key_data);
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
-	ret =3D kadm5_chpass_principal_with_key(kadm_handle, princ,
+	ret =3D kadm5_chpass_principal_with_key(kadm_handlep, princ,
 					      n_key_data, key_data);
 	{
 	    int16_t dummy =3D n_key_data;
-	    kadm5_free_key_data (context, &dummy, key_data);
+	    kadm5_free_key_data (contextp, &dummy, key_data);
 	}
 	free (key_data);
-	krb5_free_principal(context->context, princ);
+	krb5_free_principal(contextp->context, princ);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, ret);
@@ -335,8 +339,8 @@
 	ret =3D krb5_ret_principal(sp, &princ);
 	if(ret)
 	    goto fail;
-	krb5_unparse_name_fixed(context->context, princ, name, sizeof(name));
-	krb5_warnx(context->context, "%s: %s %s", client, op, name);
+	krb5_unparse_name_fixed(contextp->context, princ, name, sizeof(name));
+	krb5_warnx(contextp->context, "%s: %s %s", client, op, name);
 	/*
 	 * The change is allowed if at least one of:
 	 * a) it's for the principal him/herself and this was an initial ticket
@@ -344,19 +348,19 @@
 	 */
=20
 	if (initial
-	    && krb5_principal_compare (context->context, context->caller,
+	    && krb5_principal_compare (contextp->context, contextp->caller,
 				       princ))
 	    ret =3D 0;
 	else
-	    ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_CPW, princ);
+	    ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_CPW, princ);
=20
 	if(ret) {
-	    krb5_free_principal(context->context, princ);
+	    krb5_free_principal(contextp->context, princ);
 	    goto fail;
 	}
-	ret =3D kadm5_randkey_principal(kadm_handle, princ,=20
+	ret =3D kadm5_randkey_principal(kadm_handlep, princ,
 				      &new_keys, &n_keys);
-	krb5_free_principal(context->context, princ);
+	krb5_free_principal(contextp->context, princ);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, ret);
@@ -365,14 +369,15 @@
 	    krb5_store_int32(sp, n_keys);
 	    for(i =3D 0; i < n_keys; i++){
 		krb5_store_keyblock(sp, new_keys[i]);
-		krb5_free_keyblock_contents(context->context, &new_keys[i]);
+		krb5_free_keyblock_contents(contextp->context, &new_keys[i]);
 	    }
+	    free(new_keys);
 	}
 	break;
     }
     case kadm_get_privs:{
 	uint32_t privs;
-	ret =3D kadm5_get_privs(kadm_handle, &privs);
+	ret =3D kadm5_get_privs(kadm_handlep, &privs);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, ret);
@@ -391,14 +396,14 @@
 		goto fail;
 	}else
 	    expression =3D NULL;
-	krb5_warnx(context->context, "%s: %s %s", client, op,
+	krb5_warnx(contextp->context, "%s: %s %s", client, op,
 		   expression ? expression : "*");
-	ret =3D _kadm5_acl_check_permission(context, KADM5_PRIV_LIST, NULL);
+	ret =3D _kadm5_acl_check_permission(contextp, KADM5_PRIV_LIST, NULL);
 	if(ret){
 	    free(expression);
 	    goto fail;
 	}
-	ret =3D kadm5_get_principals(kadm_handle, expression, &princs, &n_princs);
+	ret =3D kadm5_get_principals(kadm_handlep, expression, &princs, &n_princs=
);
 	free(expression);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
@@ -408,12 +413,12 @@
 	    krb5_store_int32(sp, n_princs);
 	    for(i =3D 0; i < n_princs; i++)
 		krb5_store_string(sp, princs[i]);
-	    kadm5_free_name_list(kadm_handle, princs, &n_princs);
+	    kadm5_free_name_list(kadm_handlep, princs, &n_princs);
 	}
 	break;
     }
     default:
-	krb5_warnx(context->context, "%s: UNKNOWN OP %d", client, cmd);
+	krb5_warnx(contextp->context, "%s: UNKNOWN OP %d", client, cmd);
 	krb5_storage_free(sp);
 	sp =3D krb5_storage_emem();
 	krb5_store_int32(sp, KADM5_FAILURE);
@@ -423,7 +428,7 @@
     krb5_storage_free(sp);
     return 0;
 fail:
-    krb5_warn(context->context, ret, "%s", op);
+    krb5_warn(contextp->context, ret, "%s", op);
     krb5_storage_seek(sp, 0, SEEK_SET);
     krb5_store_int32(sp, ret);
     krb5_storage_to_data(sp, out);
@@ -432,11 +437,11 @@
 }
=20
 static void
-v5_loop (krb5_context context,
+v5_loop (krb5_context contextp,
 	 krb5_auth_context ac,
 	 krb5_boolean initial,
-	 void *kadm_handle,
-	 int fd)
+	 void *kadm_handlep,
+	 krb5_socket_t fd)
 {
     krb5_error_code ret;
     krb5_data in, out;
@@ -445,17 +450,17 @@
 	doing_useful_work =3D 0;
 	if(term_flag)
 	    exit(0);
-	ret =3D krb5_read_priv_message(context, ac, &fd, &in);
+	ret =3D krb5_read_priv_message(contextp, ac, &fd, &in);
 	if(ret =3D=3D HEIM_ERR_EOF)
 	    exit(0);
 	if(ret)
-	    krb5_err(context, 1, ret, "krb5_read_priv_message");
+	    krb5_err(contextp, 1, ret, "krb5_read_priv_message");
 	doing_useful_work =3D 1;
-	kadmind_dispatch(kadm_handle, initial, &in, &out);
+	kadmind_dispatch(kadm_handlep, initial, &in, &out);
 	krb5_data_free(&in);
-	ret =3D krb5_write_priv_message(context, ac, &fd, &out);
+	ret =3D krb5_write_priv_message(contextp, ac, &fd, &out);
 	if(ret)
-	    krb5_err(context, 1, ret, "krb5_write_priv_message");
+	    krb5_err(contextp, 1, ret, "krb5_write_priv_message");
     }
 }
=20
@@ -465,55 +470,41 @@
     unsigned minor;
     if(sscanf(appl_version, "KADM0.%u", &minor) !=3D 1)
 	return 0;
-    *(unsigned*)data =3D minor;
+    /*XXX*/
+    *(unsigned*)(intptr_t)data =3D minor;
     return 1;
 }
=20
 static void
-handle_v5(krb5_context context,
-	  krb5_auth_context ac,
+handle_v5(krb5_context contextp,
 	  krb5_keytab keytab,
-	  int len,
-	  int fd)
+	  krb5_socket_t fd)
 {
     krb5_error_code ret;
-    u_char version[sizeof(KRB5_SENDAUTH_VERSION)];
     krb5_ticket *ticket;
     char *server_name;
     char *client;
-    void *kadm_handle;
-    ssize_t n;
+    void *kadm_handlep;
     krb5_boolean initial;
+    krb5_auth_context ac =3D NULL;
=20
     unsigned kadm_version;
     kadm5_config_params realm_params;
=20
-    if (len !=3D sizeof(KRB5_SENDAUTH_VERSION))
-	krb5_errx(context, 1, "bad sendauth len %d", len);
-    n =3D krb5_net_read(context, &fd, version, len);
-    if (n < 0)
-	krb5_err (context, 1, errno, "reading sendauth version");
-    if (n =3D=3D 0)
-	krb5_errx (context, 1, "EOF reading sendauth version");
-    if(memcmp(version, KRB5_SENDAUTH_VERSION, len) !=3D 0)
-	krb5_errx(context, 1, "bad sendauth version %.8s", version);
-=09
-    ret =3D krb5_recvauth_match_version(context, &ac, &fd,=20
+    ret =3D krb5_recvauth_match_version(contextp, &ac, &fd,
 				      match_appl_version, &kadm_version,
-				      NULL, KRB5_RECVAUTH_IGNORE_VERSION,=20
+				      NULL, KRB5_RECVAUTH_IGNORE_VERSION,
 				      keytab, &ticket);
-    if(ret =3D=3D KRB5_KT_NOTFOUND)
-	krb5_errx(context, 1, "krb5_recvauth: key not found");
-    if(ret)
-	krb5_err(context, 1, ret, "krb5_recvauth");
+    if (ret)
+	krb5_err(contextp, 1, ret, "krb5_recvauth");
=20
-    ret =3D krb5_unparse_name (context, ticket->server, &server_name);
+    ret =3D krb5_unparse_name (contextp, ticket->server, &server_name);
     if (ret)
-	krb5_err (context, 1, ret, "krb5_unparse_name");
+	krb5_err (contextp, 1, ret, "krb5_unparse_name");
=20
     if (strncmp (server_name, KADM5_ADMIN_SERVICE,
 		 strlen(KADM5_ADMIN_SERVICE)) !=3D 0)
-	krb5_errx (context, 1, "ticket for strange principal (%s)",
+	krb5_errx (contextp, 1, "ticket for strange principal (%s)",
 		   server_name);
=20
     free (server_name);
@@ -522,56 +513,62 @@
=20
     if(kadm_version =3D=3D 1) {
 	krb5_data params;
-	ret =3D krb5_read_priv_message(context, ac, &fd, &params);
+	ret =3D krb5_read_priv_message(contextp, ac, &fd, &params);
 	if(ret)
-	    krb5_err(context, 1, ret, "krb5_read_priv_message");
-	_kadm5_unmarshal_params(context, &params, &realm_params);
+	    krb5_err(contextp, 1, ret, "krb5_read_priv_message");
+	_kadm5_unmarshal_params(contextp, &params, &realm_params);
     }
=20
     initial =3D ticket->ticket.flags.initial;
-    ret =3D krb5_unparse_name(context, ticket->client, &client);
+    ret =3D krb5_unparse_name(contextp, ticket->client, &client);
     if (ret)
-	krb5_err (context, 1, ret, "krb5_unparse_name");
-    krb5_free_ticket (context, ticket);
-    ret =3D kadm5_init_with_password_ctx(context,=20
-				       client,=20
-				       NULL,
-				       KADM5_ADMIN_SERVICE,
-				       &realm_params,=20
-				       0, 0,=20
-				       &kadm_handle);
+	krb5_err (contextp, 1, ret, "krb5_unparse_name");
+    krb5_free_ticket (contextp, ticket);
+    ret =3D kadm5_s_init_with_password_ctx(contextp,
+					 client,
+					 NULL,
+					 KADM5_ADMIN_SERVICE,
+					 &realm_params,
+					 0, 0,
+					 &kadm_handlep);
     if(ret)
-	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");
-    v5_loop (context, ac, initial, kadm_handle, fd);
+	krb5_err (contextp, 1, ret, "kadm5_init_with_password_ctx");
+    v5_loop (contextp, ac, initial, kadm_handlep, fd);
 }
=20
 krb5_error_code
-kadmind_loop(krb5_context context,
-	     krb5_auth_context ac,
-	     krb5_keytab keytab,=20
-	     int fd)
+kadmind_loop(krb5_context contextp,
+	     krb5_keytab keytab,
+	     krb5_socket_t sock)
 {
-    unsigned char tmp[4];
+    u_char buf[sizeof(KRB5_SENDAUTH_VERSION) + 4];
     ssize_t n;
     unsigned long len;
=20
-    n =3D krb5_net_read(context, &fd, tmp, 4);
+    n =3D krb5_net_read(contextp, &sock, buf, 4);
     if(n =3D=3D 0)
 	exit(0);
     if(n < 0)
-	krb5_err(context, 1, errno, "read");
-    _krb5_get_int(tmp, &len, 4);
-    /* this v4 test could probably also go away */
-    if(len > 0xffff && (len & 0xffff) =3D=3D ('K' << 8) + 'A') {
-	unsigned char v4reply[] =3D {=20
-	    0x00, 0x0c,=20
-	    'K', 'Y', 'O', 'U', 'L', 'O', 'S', 'E',=20
-	    0x95, 0xb7, 0xa7, 0x08 /* KADM_BAD_VER */
-	};
-	krb5_net_write(context, &fd, v4reply, sizeof(v4reply));
-	krb5_errx(context, 1, "packet appears to be version 4");
-    } else {
-	handle_v5(context, ac, keytab, len, fd);
-    }
+	krb5_err(contextp, 1, errno, "read");
+    _krb5_get_int(buf, &len, 4);
+
+    if (len =3D=3D sizeof(KRB5_SENDAUTH_VERSION)) {
+
+	n =3D krb5_net_read(contextp, &sock, buf + 4, len);
+	if (n < 0)
+	    krb5_err (contextp, 1, errno, "reading sendauth version");
+	if (n =3D=3D 0)
+	    krb5_errx (contextp, 1, "EOF reading sendauth version");
+
+	if(memcmp(buf + 4, KRB5_SENDAUTH_VERSION, len) =3D=3D 0) {
+	    handle_v5(contextp, keytab, sock);
+	    return 0;
+	}
+	len +=3D 4;
+    } else
+	len =3D 4;
+
+    handle_mit(contextp, buf, len, sock);
+
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/stash.c
--- a/head/crypto/heimdal/kadmin/stash.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/stash.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include "kadmin-commands.h"
=20
-RCSID("$Id: stash.c 22251 2007-12-09 05:58:43Z lha $");
-
 extern int local_flag;
=20
 int
@@ -45,7 +45,7 @@
     krb5_error_code ret;
     krb5_enctype enctype;
     hdb_master_key mkey;
-   =20
+
     if(!local_flag) {
 	krb5_warnx(context, "stash is only available in local (-l) mode");
 	return 0;
@@ -65,14 +65,14 @@
=20
     ret =3D hdb_read_master_key(context, opt->key_file_string, &mkey);
     if(ret && ret !=3D ENOENT) {
-	krb5_warn(context, ret, "reading master key from %s",=20
+	krb5_warn(context, ret, "reading master key from %s",
 		  opt->key_file_string);
 	return 0;
     }
=20
     if (opt->convert_file_flag) {
 	if (ret)
-	    krb5_warn(context, ret, "reading master key from %s",=20
+	    krb5_warn(context, ret, "reading master key from %s",
 		      opt->key_file_string);
 	return 0;
     } else {
@@ -87,10 +87,15 @@
 	    n =3D read(opt->master_key_fd_integer, buf, sizeof(buf));
 	    if(n =3D=3D 0)
 		krb5_warnx(context, "end of file reading passphrase");
-	    else if(n < 0)
+	    else if(n < 0) {
 		krb5_warn(context, errno, "reading passphrase");
+		n =3D 0;
+	    }
 	    buf[n] =3D '\0';
 	    buf[strcspn(buf, "\r\n")] =3D '\0';
+	} else if (opt->random_password_flag) {
+	    random_password (buf, sizeof(buf));
+	    printf("Using random master stash password: %s\n", buf);
 	} else {
 	    if(UI_UTIL_read_pw_string(buf, sizeof(buf), "Master key: ", 1)) {
 		hdb_free_master_key(context, mkey);
@@ -101,7 +106,7 @@
 	ret =3D hdb_add_master_key(context, &key, &mkey);
 	krb5_free_keyblock_contents(context, &key);
     }
-   =20
+
     {
 	char *new, *old;
 	asprintf(&old, "%s.old", opt->key_file_string);
@@ -110,7 +115,7 @@
 	    ret =3D ENOMEM;
 	    goto out;
 	}
-	   =20
+
 	if(unlink(new) < 0 && errno !=3D ENOENT) {
 	    ret =3D errno;
 	    goto out;
@@ -121,12 +126,18 @@
 	    unlink(new);
 	else {
 	    unlink(old);
+#ifndef NO_POSIX_LINKS
 	    if(link(opt->key_file_string, old) < 0 && errno !=3D ENOENT) {
 		ret =3D errno;
 		unlink(new);
-	    } else if(rename(new, opt->key_file_string) < 0) {
-		ret =3D errno;
+	    } else {
+#endif
+		if(rename(new, opt->key_file_string) < 0) {
+		    ret =3D errno;
+		}
+#ifndef NO_POSIX_LINKS
 	    }
+#endif
 	}
     out:
 	free(old);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/test_util.c
--- a/head/crypto/heimdal/kadmin/test_util.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/test_util.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,8 +32,6 @@
=20
 #include "kadmin_locl.h"
=20
-RCSID("$Id: test_util.c 19486 2006-12-22 17:25:59Z lha $");
-
 krb5_context context;
 void *kadm_handle;
=20
@@ -60,13 +58,13 @@
 	if (ret !=3D ts[i].ret) {
 	    printf("%d: %d is wrong ret\n", i, ret);
 	    errors++;
-	}=20
+	}
 	else if (t !=3D ts[i].t) {
 	    printf("%d: %d is wrong time\n", i, (int)t);
 	    errors++;
 	}
     }
-   =20
+
     return errors;
 }
=20
@@ -89,4 +87,4 @@
=20
     return ret;
 }
-   =20
+
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kadmin/util.c
--- a/head/crypto/heimdal/kadmin/util.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kadmin/util.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadmin_locl.h"
 #include <parse_units.h>
=20
-RCSID("$Id: util.c 21745 2007-07-31 16:11:25Z lha $");
-
 /*
  * util.c - functions for parsing, unparsing, and editing different
  * types of data used in kadmin.
@@ -45,7 +43,7 @@
 get_response(const char *prompt, const char *def, char *buf, size_t len);
=20
 /*
- * attributes=20
+ * attributes
  */
=20
 struct units kdb_attrs[] =3D {
@@ -67,7 +65,7 @@
     { "disallow-tgt-based",	KRB5_KDB_DISALLOW_TGT_BASED },
     { "disallow-forwardable",	KRB5_KDB_DISALLOW_FORWARDABLE },
     { "disallow-postdated",	KRB5_KDB_DISALLOW_POSTDATED },
-    { NULL }
+    { NULL, 0 }
 };
=20
 /*
@@ -155,7 +153,7 @@
 /*
  * Convert the time `t' to a string representation in `str' (of max
  * size `len').  If include_time also include time, otherwise just
- * date. =20
+ * date.
  */
=20
 void
@@ -184,6 +182,18 @@
     memset (&tm, 0, sizeof (tm));
     memset (&tm2, 0, sizeof (tm2));
=20
+    while(isspace((unsigned char)*str))
+	str++;
+
+    if (str[0] =3D=3D '+') {
+	str++;
+	*t =3D parse_time(str, "month");
+	if (*t < 0)
+	    return -1;
+	*t +=3D time(NULL);
+	return 0;
+    }
+
     if(strcasecmp(str, "never") =3D=3D 0) {
 	*t =3D 0;
 	return 0;
@@ -233,7 +243,7 @@
 	if(mask)
 	    *mask |=3D bit;
 	return 0;
-    }=20
+    }
     if(*resp !=3D '?')
 	fprintf (stderr, "Unable to parse time \"%s\"\n", resp);
     fprintf (stderr, "Print date on format YYYY-mm-dd [hh:mm:ss]\n");
@@ -393,7 +403,7 @@
     if(edit_deltat ("Max ticket life", &ent->max_life, mask,
 		    KADM5_MAX_LIFE) !=3D 0)
 	return 1;
-   =20
+
     if(edit_deltat ("Max renewable life", &ent->max_renewable_life, mask,
 		    KADM5_MAX_RLIFE) !=3D 0)
 	return 1;
@@ -420,7 +430,7 @@
  */
=20
 int
-set_entry(krb5_context context,
+set_entry(krb5_context contextp,
 	  kadm5_principal_ent_t ent,
 	  int *mask,
 	  const char *max_ticket_life,
@@ -430,38 +440,38 @@
 	  const char *attributes)
 {
     if (max_ticket_life !=3D NULL) {
-	if (parse_deltat (max_ticket_life, &ent->max_life,=20
+	if (parse_deltat (max_ticket_life, &ent->max_life,
 			  mask, KADM5_MAX_LIFE)) {
-	    krb5_warnx (context, "unable to parse `%s'", max_ticket_life);
+	    krb5_warnx (contextp, "unable to parse `%s'", max_ticket_life);
 	    return 1;
 	}
     }
     if (max_renewable_life !=3D NULL) {
-	if (parse_deltat (max_renewable_life, &ent->max_renewable_life,=20
+	if (parse_deltat (max_renewable_life, &ent->max_renewable_life,
 			  mask, KADM5_MAX_RLIFE)) {
-	    krb5_warnx (context, "unable to parse `%s'", max_renewable_life);
+	    krb5_warnx (contextp, "unable to parse `%s'", max_renewable_life);
 	    return 1;
 	}
     }
=20
     if (expiration) {
-	if (parse_timet (expiration, &ent->princ_expire_time,=20
+	if (parse_timet (expiration, &ent->princ_expire_time,
 			mask, KADM5_PRINC_EXPIRE_TIME)) {
-	    krb5_warnx (context, "unable to parse `%s'", expiration);
+	    krb5_warnx (contextp, "unable to parse `%s'", expiration);
 	    return 1;
 	}
     }
     if (pw_expiration) {
-	if (parse_timet (pw_expiration, &ent->pw_expiration,=20
+	if (parse_timet (pw_expiration, &ent->pw_expiration,
 			 mask, KADM5_PW_EXPIRATION)) {
-	    krb5_warnx (context, "unable to parse `%s'", pw_expiration);
+	    krb5_warnx (contextp, "unable to parse `%s'", pw_expiration);
 	    return 1;
 	}
     }
     if (attributes !=3D NULL) {
-	if (parse_attributes (attributes, &ent->attributes,=20
+	if (parse_attributes (attributes, &ent->attributes,
 			      mask, KADM5_ATTRIBUTES)) {
-	    krb5_warnx (context, "unable to parse `%s'", attributes);
+	    krb5_warnx (contextp, "unable to parse `%s'", attributes);
 	    return 1;
 	}
     }
@@ -485,7 +495,7 @@
 	}
 	if(*p =3D=3D '\\')
 	    quote++;
-	else if(strchr("[]*?", *p) !=3D NULL)=20
+	else if(strchr("[]*?", *p) !=3D NULL)
 	    return 1;
     }
     return 0;
@@ -497,13 +507,13 @@
  * processed.
  */
 int
-foreach_principal(const char *exp_str,=20
-		  int (*func)(krb5_principal, void*),=20
+foreach_principal(const char *exp_str,
+		  int (*func)(krb5_principal, void*),
 		  const char *funcname,
 		  void *data)
 {
-    char **princs;
-    int num_princs;
+    char **princs =3D NULL;
+    int num_princs =3D 0;
     int i;
     krb5_error_code saved_ret =3D 0, ret =3D 0;
     krb5_principal princ_ent;
@@ -522,7 +532,7 @@
 	if(princs =3D=3D NULL)
 	    return ENOMEM;
 	princs[0] =3D strdup(exp_str);
-	if(princs[0] =3D=3D NULL){=20
+	if(princs[0] =3D=3D NULL){
 	    free(princs);
 	    return ENOMEM;
 	}
@@ -538,7 +548,7 @@
 	}
 	ret =3D (*func)(princ_ent, data);
 	if(ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    krb5_warn(context, ret, "%s %s", funcname, princs[i]);
 	    if (saved_ret =3D=3D 0)
 		saved_ret =3D ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/Makefile.am
--- a/head/crypto/heimdal/kcm/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,8 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_krb4) $(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
+AM_CPPFLAGS +=3D $(INCLUDE_libintl) $(INCLUDE_krb4) $(INCLUDE_hcrypto) -I$=
(srcdir)/../lib/krb5
=20
 libexec_PROGRAMS =3D kcm
=20
@@ -13,32 +13,33 @@
 	client.c	\
 	config.c	\
 	connect.c	\
-	cursor.c	\
 	events.c	\
 	glue.c		\
 	headers.h	\
 	kcm_locl.h	\
-	kcm_protos.h	\
+	kcm-protos.h	\
 	log.c		\
 	main.c		\
 	protocol.c	\
+	sessions.c	\
 	renew.c
=20
-$(srcdir)/kcm_protos.h:
-	cd $(srcdir); perl ../cf/make-proto.pl -o kcm_protos.h -q -P comment $(kc=
m_SOURCES) || rm -f kcm_protos.h
+$(srcdir)/kcm-protos.h:
+	cd $(srcdir); perl ../cf/make-proto.pl -o kcm-protos.h -q -P comment $(kc=
m_SOURCES) || rm -f kcm-protos.h
=20
-$(kcm_OBJECTS): $(srcdir)/kcm_protos.h
+$(kcm_OBJECTS): $(srcdir)/kcm-protos.h
=20
 man_MANS =3D kcm.8
=20
 LDADD =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ntlm/libheimntlm.la \
+	$(top_builddir)/lib/ipc/libheim-ipcs.la \
 	$(LIB_roken) \
 	$(LIB_door_create) \
 	$(LIB_pidfile)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/Makefile.in
--- a/head/crypto/heimdal/kcm/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D kcm
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,30 +89,31 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(man8dir)"
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(libexec_PROGRAMS)
 am_kcm_OBJECTS =3D acl.$(OBJEXT) acquire.$(OBJEXT) cache.$(OBJEXT) \
 	client.$(OBJEXT) config.$(OBJEXT) connect.$(OBJEXT) \
-	cursor.$(OBJEXT) events.$(OBJEXT) glue.$(OBJEXT) log.$(OBJEXT) \
-	main.$(OBJEXT) protocol.$(OBJEXT) renew.$(OBJEXT)
+	events.$(OBJEXT) glue.$(OBJEXT) log.$(OBJEXT) main.$(OBJEXT) \
+	protocol.$(OBJEXT) sessions.$(OBJEXT) renew.$(OBJEXT)
 kcm_OBJECTS =3D $(am_kcm_OBJECTS)
 kcm_LDADD =3D $(LDADD)
 am__DEPENDENCIES_1 =3D
 kcm_DEPENDENCIES =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ntlm/libheimntlm.la \
+	$(top_builddir)/lib/ipc/libheim-ipcs.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -119,6 +125,27 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(kcm_SOURCES)
 DIST_SOURCES =3D $(kcm_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
 ETAGS =3D etags
@@ -128,49 +155,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -194,10 +230,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -214,6 +251,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -229,31 +268,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -268,10 +321,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -312,30 +367,35 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4) $(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_libintl) $(INCLUDE_krb4) \
+	$(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 kcm_SOURCES =3D \
 	acl.c		\
@@ -344,45 +404,46 @@
 	client.c	\
 	config.c	\
 	connect.c	\
-	cursor.c	\
 	events.c	\
 	glue.c		\
 	headers.h	\
 	kcm_locl.h	\
-	kcm_protos.h	\
+	kcm-protos.h	\
 	log.c		\
 	main.c		\
 	protocol.c	\
+	sessions.c	\
 	renew.c
=20
 man_MANS =3D kcm.8
 LDADD =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_krb4) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ntlm/libheimntlm.la \
+	$(top_builddir)/lib/ipc/libheim-ipcs.la \
 	$(LIB_roken) \
 	$(LIB_door_create) \
 	$(LIB_pidfile)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps kcm/Makef=
ile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps kcm/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign kcm/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign kcm/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -400,34 +461,50 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 kcm$(EXEEXT): $(kcm_OBJECTS) $(kcm_DEPENDENCIES)=20
 	@rm -f kcm$(EXEEXT)
 	$(LINK) $(kcm_OBJECTS) $(kcm_LDADD) $(LIBS)
@@ -438,115 +515,151 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/acl.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/acquire.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/cache.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/client.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/config.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/connect.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/events.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/glue.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/log.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/main.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/protocol.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/renew.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/sessions.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man8: $(man8_MANS) $(man_MANS)
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -562,13 +675,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -603,6 +720,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -613,6 +731,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -623,6 +742,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -630,26 +751,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -669,11 +799,10 @@
 uninstall-am: uninstall-libexecPROGRAMS uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libexecPROGRAMS clean-libtool ctags \
@@ -760,6 +889,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -845,7 +977,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -859,10 +991,11 @@
 	  fi ; \
 	done
=20
-$(srcdir)/kcm_protos.h:
-	cd $(srcdir); perl ../cf/make-proto.pl -o kcm_protos.h -q -P comment $(kc=
m_SOURCES) || rm -f kcm_protos.h
+$(srcdir)/kcm-protos.h:
+	cd $(srcdir); perl ../cf/make-proto.pl -o kcm-protos.h -q -P comment $(kc=
m_SOURCES) || rm -f kcm-protos.h
=20
-$(kcm_OBJECTS): $(srcdir)/kcm_protos.h
+$(kcm_OBJECTS): $(srcdir)/kcm-protos.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/acl.c
--- a/head/crypto/heimdal/kcm/acl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/acl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -32,8 +34,6 @@
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: acl.c 20472 2007-04-20 10:43:25Z lha $");
-
 krb5_error_code
 kcm_access(krb5_context context,
 	   kcm_client *client,
@@ -57,6 +57,9 @@
     case KCM_OP_CHMOD:
     case KCM_OP_GET_INITIAL_TICKET:
     case KCM_OP_GET_TICKET:
+    case KCM_OP_MOVE_CACHE:
+    case KCM_OP_SET_DEFAULT_CACHE:
+    case KCM_OP_SET_KDC_OFFSET:
 	write_p =3D 1;
 	read_p =3D 0;
 	break;
@@ -66,52 +69,70 @@
     case KCM_OP_GEN_NEW:
     case KCM_OP_RETRIEVE:
     case KCM_OP_GET_PRINCIPAL:
-    case KCM_OP_GET_FIRST:
-    case KCM_OP_GET_NEXT:
-    case KCM_OP_END_GET:
-    case KCM_OP_MAX:
+    case KCM_OP_GET_CRED_UUID_LIST:
+    case KCM_OP_GET_CRED_BY_UUID:
+    case KCM_OP_GET_CACHE_UUID_LIST:
+    case KCM_OP_GET_CACHE_BY_UUID:
+    case KCM_OP_GET_DEFAULT_CACHE:
+    case KCM_OP_GET_KDC_OFFSET:
 	write_p =3D 0;
 	read_p =3D 1;
 	break;
+    default:
+	ret =3D KRB5_FCC_PERM;
+	goto out;
     }
=20
     if (ccache->flags & KCM_FLAGS_OWNER_IS_SYSTEM) {
 	/* System caches cannot be reinitialized or destroyed by users */
 	if (opcode =3D=3D KCM_OP_INITIALIZE ||
 	    opcode =3D=3D KCM_OP_DESTROY ||
-	    opcode =3D=3D KCM_OP_REMOVE_CRED) {
+	    opcode =3D=3D KCM_OP_REMOVE_CRED ||
+	    opcode =3D=3D KCM_OP_MOVE_CACHE) {
 	    ret =3D KRB5_FCC_PERM;
 	    goto out;
 	}
=20
 	/* Let root always read system caches */
-	if (client->uid =3D=3D 0) {
+	if (CLIENT_IS_ROOT(client)) {
 	    ret =3D 0;
 	    goto out;
 	}
     }
=20
-    mask =3D 0;
+    /* start out with "other" mask */
+    mask =3D S_IROTH|S_IWOTH;
=20
-    /* Root may do whatever they like */
-    if (client->uid =3D=3D ccache->uid || CLIENT_IS_ROOT(client)) {
+    /* root can do anything */
+    if (CLIENT_IS_ROOT(client)) {
 	if (read_p)
-	    mask |=3D S_IRUSR;
+	    mask |=3D S_IRUSR|S_IRGRP|S_IROTH;
 	if (write_p)
-	    mask |=3D S_IWUSR;
-    } else if (client->gid =3D=3D ccache->gid || CLIENT_IS_ROOT(client)) {
-	if (read_p)
-	    mask |=3D S_IRGRP;
-	if (write_p)
-	    mask |=3D S_IWGRP;
-    } else {
+	    mask |=3D S_IWUSR|S_IWGRP|S_IWOTH;
+    }
+    /* same session same as owner */
+    if (kcm_is_same_session(client, ccache->uid, ccache->session)) {
 	if (read_p)
 	    mask |=3D S_IROTH;
 	if (write_p)
 	    mask |=3D S_IWOTH;
     }
+    /* owner */
+    if (client->uid =3D=3D ccache->uid) {
+	if (read_p)
+	    mask |=3D S_IRUSR;
+	if (write_p)
+	    mask |=3D S_IWUSR;
+    }
+    /* group */
+    if (client->gid =3D=3D ccache->gid) {
+	if (read_p)
+	    mask |=3D S_IRGRP;
+	if (write_p)
+	    mask |=3D S_IWGRP;
+    }
=20
-    ret =3D ((ccache->mode & mask) =3D=3D mask) ? 0 : KRB5_FCC_PERM;
+    ret =3D (ccache->mode & mask) ? 0 : KRB5_FCC_PERM;
=20
 out:
     if (ret) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/acquire.c
--- a/head/crypto/heimdal/kcm/acquire.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/acquire.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,11 +32,6 @@
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: acquire.c 22118 2007-12-03 21:44:00Z lha $");
-
-static krb5_error_code
-change_pw_and_update_keytab(krb5_context context, kcm_ccache ccache);
-
 /*
  * Get a new ticket using a keytab/cached key and swap it into
  * an existing redentials cache
@@ -50,10 +45,9 @@
     krb5_error_code ret =3D 0;
     krb5_creds cred;
     krb5_const_realm realm;
-    krb5_get_init_creds_opt opt;
+    krb5_get_init_creds_opt *opt =3D NULL;
     krb5_ccache_data ccdata;
     char *in_tkt_service =3D NULL;
-    int done =3D 0;
=20
     memset(&cred, 0, sizeof(cred));
=20
@@ -73,7 +67,7 @@
 		ccache->name);
 	return KRB5_FCC_INTERNAL;
     }
-=09
+
     HEIMDAL_MUTEX_lock(&ccache->mutex);
=20
     /* Fake up an internal ccache */
@@ -91,12 +85,14 @@
=20
     realm =3D krb5_principal_get_realm(context, ccache->client);
=20
-    krb5_get_init_creds_opt_init(&opt);
-    krb5_get_init_creds_opt_set_default_flags(context, "kcm", realm, &opt);
+    ret =3D krb5_get_init_creds_opt_alloc(context, &opt);
+    if (ret)
+	goto out;
+    krb5_get_init_creds_opt_set_default_flags(context, "kcm", realm, opt);
     if (ccache->tkt_life !=3D 0)
-	krb5_get_init_creds_opt_set_tkt_life(&opt, ccache->tkt_life);
+	krb5_get_init_creds_opt_set_tkt_life(opt, ccache->tkt_life);
     if (ccache->renew_life !=3D 0)
-	krb5_get_init_creds_opt_set_renew_life(&opt, ccache->renew_life);
+	krb5_get_init_creds_opt_set_renew_life(opt, ccache->renew_life);
=20
     if (ccache->flags & KCM_FLAGS_USE_CACHED_KEY) {
 	ret =3D krb5_get_init_creds_keyblock(context,
@@ -105,34 +101,16 @@
 					   &ccache->key.keyblock,
 					   0,
 					   in_tkt_service,
-					   &opt);
+					   opt);
     } else {
 	/* loosely based on lib/krb5/init_creds_pw.c */
-	while (!done) {
-	    ret =3D krb5_get_init_creds_keytab(context,
-					     &cred,
-					     ccache->client,
-					     ccache->key.keytab,
-					     0,
-					     in_tkt_service,
-					     &opt);
-	    switch (ret) {
-	    case KRB5KDC_ERR_KEY_EXPIRED:
-		if (in_tkt_service !=3D NULL &&
-		    strcmp(in_tkt_service, "kadmin/changepw") =3D=3D 0) {
-		    goto out;
-		}
-
-		ret =3D change_pw_and_update_keytab(context, ccache);
-		if (ret)
-		    goto out;
-		break;
-	    case 0:
-	    default:
-		done =3D 1;
-		break;
-	    }
-	}
+	ret =3D krb5_get_init_creds_keytab(context,
+					 &cred,
+					 ccache->client,
+					 ccache->key.keytab,
+					 0,
+					 in_tkt_service,
+					 opt);
     }
=20
     if (ret) {
@@ -158,374 +136,10 @@
     }
=20
 out:
+    if (opt)
+	krb5_get_init_creds_opt_free(context, opt);
+
     HEIMDAL_MUTEX_unlock(&ccache->mutex);
=20
     return ret;
 }
-
-static krb5_error_code
-change_pw(krb5_context context,
-	  kcm_ccache ccache,
-	  char *cpn,
-	  char *newpw)
-{
-    krb5_error_code ret;
-    krb5_creds cpw_cred;
-    int result_code;
-    krb5_data result_code_string;
-    krb5_data result_string;
-    krb5_get_init_creds_opt options;
-
-    memset(&cpw_cred, 0, sizeof(cpw_cred));
-
-    krb5_get_init_creds_opt_init(&options);
-    krb5_get_init_creds_opt_set_tkt_life(&options, 60);
-    krb5_get_init_creds_opt_set_forwardable(&options, FALSE);
-    krb5_get_init_creds_opt_set_proxiable(&options, FALSE);
-
-    krb5_data_zero(&result_code_string);
-    krb5_data_zero(&result_string);
-
-    ret =3D krb5_get_init_creds_keytab(context,
-				     &cpw_cred,
-				     ccache->client,
-				     ccache->key.keytab,
-				     0,
-				     "kadmin/changepw",
-				     &options);
-    if (ret) {
-	kcm_log(0, "Failed to acquire password change credentials "
-		"for principal %s: %s",=20
-		cpn, krb5_get_err_text(context, ret));
-	goto out;
-    }
-
-    ret =3D krb5_set_password(context,
-			    &cpw_cred,
-			    newpw,
-			    ccache->client,
-			    &result_code,
-			    &result_code_string,
-			    &result_string);
-    if (ret) {
-	kcm_log(0, "Failed to change password for principal %s: %s",
-		cpn, krb5_get_err_text(context, ret));
-	goto out;
-    }
-
-    if (result_code) {
-	kcm_log(0, "Failed to change password for principal %s: %.*s",
-		cpn,
-		(int)result_string.length,
-		result_string.length > 0 ? (char *)result_string.data : "");
-	goto out;
-    }
-
-out:
-    krb5_data_free(&result_string);
-    krb5_data_free(&result_code_string);
-    krb5_free_cred_contents(context, &cpw_cred);
-
-    return ret;
-}
-
-struct kcm_keyseed_data {
-    krb5_salt salt;
-    const char *password;
-};
-
-static krb5_error_code
-kcm_password_key_proc(krb5_context context,
-		      krb5_enctype etype,
-		      krb5_salt salt,
-		      krb5_const_pointer keyseed,
-		      krb5_keyblock **key)
-{
-    krb5_error_code ret;
-    struct kcm_keyseed_data *s =3D (struct kcm_keyseed_data *)keyseed;
-
-    /* we may be called multiple times */
-    krb5_free_salt(context, s->salt);
-    krb5_data_zero(&s->salt.saltvalue);
-
-    /* stash the salt */
-    s->salt.salttype =3D salt.salttype;
-
-    ret =3D krb5_data_copy(&s->salt.saltvalue,
-		         salt.saltvalue.data,
-			 salt.saltvalue.length);
-    if (ret)
-	return ret;
-
-    *key =3D (krb5_keyblock *)malloc(sizeof(**key));
-    if (*key =3D=3D NULL) {
-	return ENOMEM;
-    }
-
-    ret =3D krb5_string_to_key_salt(context, etype, s->password,
-				  s->salt, *key);
-    if (ret) {
-	free(*key);
-	*key =3D NULL;
-    }
-
-    return ret;
-}
-
-static krb5_error_code
-get_salt_and_kvno(krb5_context context,
-		  kcm_ccache ccache,
-		  krb5_enctype *etypes,
-		  char *cpn,
-		  char *newpw,
-		  krb5_salt *salt,
-		  unsigned *kvno)
-{
-    krb5_error_code ret;
-    krb5_creds creds;
-    krb5_ccache_data ccdata;
-    krb5_flags options =3D 0;
-    krb5_kdc_rep reply;
-    struct kcm_keyseed_data s;
-
-    memset(&creds, 0, sizeof(creds));
-    memset(&reply, 0, sizeof(reply));
-
-    s.password =3D NULL;
-    s.salt.salttype =3D (int)ETYPE_NULL;
-    krb5_data_zero(&s.salt.saltvalue);
-
-    *kvno =3D 0;
-    kcm_internal_ccache(context, ccache, &ccdata);
-    s.password =3D newpw;
-
-    /* Do an AS-REQ to determine salt and key version number */
-    ret =3D krb5_copy_principal(context, ccache->client, &creds.client);
-    if (ret)
-	return ret;
-
-    /* Yes, get a ticket to ourselves */
-    ret =3D krb5_copy_principal(context, ccache->client, &creds.server);
-    if (ret) {
-	krb5_free_principal(context, creds.client);
-	return ret;
-    }
-=09
-    ret =3D krb5_get_in_tkt(context,
-			  options,
-			  NULL,
-			  etypes,
-			  NULL,
-			  kcm_password_key_proc,
-			  &s,
-			  NULL,
-			  NULL,
-			  &creds,
-			  &ccdata,
-			  &reply);
-    if (ret) {
-	kcm_log(0, "Failed to get self ticket for principal %s: %s",
-		cpn, krb5_get_err_text(context, ret));
-	krb5_free_salt(context, s.salt);
-    } else {
-	*salt =3D s.salt; /* retrieve stashed salt */
-	if (reply.kdc_rep.enc_part.kvno !=3D NULL)
-	    *kvno =3D *(reply.kdc_rep.enc_part.kvno);
-    }
-    /* ccache may have been modified but it will get trashed anyway */
-
-    krb5_free_cred_contents(context, &creds);
-    krb5_free_kdc_rep(context, &reply);
-
-    return ret;
-}
-
-static krb5_error_code
-update_keytab_entry(krb5_context context,
-		    kcm_ccache ccache,
-		    krb5_enctype etype,
-		    char *cpn,
-		    char *spn,
-		    char *newpw,
-		    krb5_salt salt,
-		    unsigned kvno)
-{
-    krb5_error_code ret;
-    krb5_keytab_entry entry;
-    krb5_data pw;
-
-    memset(&entry, 0, sizeof(entry));
-
-    pw.data =3D (char *)newpw;
-    pw.length =3D strlen(newpw);
-
-    ret =3D krb5_string_to_key_data_salt(context, etype, pw,
-				       salt, &entry.keyblock);
-    if (ret) {
-	kcm_log(0, "String to key conversion failed for principal %s "
-		"and etype %d: %s",
-		cpn, etype, krb5_get_err_text(context, ret));=20
-	return ret;
-    }
-
-    if (spn =3D=3D NULL) {
-	ret =3D krb5_copy_principal(context, ccache->client,
-				  &entry.principal);
-	if (ret) {
-	    kcm_log(0, "Failed to copy principal name %s: %s",
-		    cpn, krb5_get_err_text(context, ret));
-	    return ret;
-	}
-    } else {
-	ret =3D krb5_parse_name(context, spn, &entry.principal);
-	if (ret) {
-	    kcm_log(0, "Failed to parse SPN alias %s: %s",
-		    spn, krb5_get_err_text(context, ret));
-	    return ret;
-	}
-    }
-
-    entry.vno =3D kvno;
-    entry.timestamp =3D time(NULL);
-
-    ret =3D krb5_kt_add_entry(context, ccache->key.keytab, &entry);
-    if (ret) {
-	kcm_log(0, "Failed to update keytab for principal %s "
-		"and etype %d: %s",
-		cpn, etype, krb5_get_err_text(context, ret));
-    }
-
-    krb5_kt_free_entry(context, &entry);
-
-    return ret;=20
-}
-
-static krb5_error_code
-update_keytab_entries(krb5_context context,
-		      kcm_ccache ccache,
-		      krb5_enctype *etypes,
-		      char *cpn,
-		      char *spn,
-		      char *newpw,
-		      krb5_salt salt,
-		      unsigned kvno)
-{
-    krb5_error_code ret =3D 0;
-    int i;
-
-    for (i =3D 0; etypes[i] !=3D ETYPE_NULL; i++) {
-	ret =3D update_keytab_entry(context, ccache, etypes[i],
-				  cpn, spn, newpw, salt, kvno);
-	if (ret)
-	    break;
-    }
-
-    return ret;
-}
-
-static void
-generate_random_pw(krb5_context context,
-		   char *buf,
-		   size_t bufsiz)
-{
-    unsigned char x[512], *p;
-    size_t i;
-
-    memset(x, 0, sizeof(x));
-    krb5_generate_random_block(x, sizeof(x));
-    p =3D x;
-
-    for (i =3D 0; i < bufsiz; i++) {
-	while (isprint(*p) =3D=3D 0)
-	    p++;
-
-	if (p - x >=3D sizeof(x)) {
-	    krb5_generate_random_block(x, sizeof(x));
-	    p =3D x;
-	}
-	buf[i] =3D (char)*p++;
-    }
-    buf[bufsiz - 1] =3D '\0';
-    memset(x, 0, sizeof(x));
-}
-
-static krb5_error_code
-change_pw_and_update_keytab(krb5_context context,
-			    kcm_ccache ccache)
-{
-    char newpw[121];
-    krb5_error_code ret;
-    unsigned kvno;
-    krb5_salt salt;
-    krb5_enctype *etypes =3D NULL;
-    int i;
-    char *cpn =3D NULL;
-    char **spns =3D NULL;
-
-    krb5_data_zero(&salt.saltvalue);
-
-    ret =3D krb5_unparse_name(context, ccache->client, &cpn);
-    if (ret) {
-	kcm_log(0, "Failed to unparse name: %s",
-		krb5_get_err_text(context, ret));
-	goto out;
-    }
-
-    ret =3D krb5_get_default_in_tkt_etypes(context, &etypes);
-    if (ret) {
-	kcm_log(0, "Failed to determine default encryption types: %s",
-		krb5_get_err_text(context, ret));
-	goto out;
-    }
-
-    /* Generate a random password (there is no set keys protocol) */
-    generate_random_pw(context, newpw, sizeof(newpw));
-
-    /* Change it */
-    ret =3D change_pw(context, ccache, cpn, newpw);
-    if (ret)
-	goto out;
-
-    /* Do an AS-REQ to determine salt and key version number */
-    ret =3D get_salt_and_kvno(context, ccache, etypes, cpn, newpw,
-			    &salt, &kvno);
-    if (ret) {
-	kcm_log(0, "Failed to determine salting principal for principal %s: %s",
-		cpn, krb5_get_err_text(context, ret));
-	goto out;
-    }
-
-    /* Add canonical name */
-    ret =3D update_keytab_entries(context, ccache, etypes, cpn,
-				NULL, newpw, salt, kvno);
-    if (ret)
-	goto out;
-
-    /* Add SPN aliases, if any */
-    spns =3D krb5_config_get_strings(context, NULL, "kcm",
-				   "system_ccache", "spn_aliases", NULL);
-    if (spns !=3D NULL) {
-	for (i =3D 0; spns[i] !=3D NULL; i++) {
-	    ret =3D update_keytab_entries(context, ccache, etypes, cpn,
-					spns[i], newpw, salt, kvno);
-	    if (ret)
-		goto out;
-	}
-    }
-
-    kcm_log(0, "Changed expired password for principal %s in cache %s",
-	    cpn, ccache->name);
-
-out:
-    if (cpn !=3D NULL)
-	free(cpn);
-    if (spns !=3D NULL)
-	krb5_config_free_strings(spns);
-    if (etypes !=3D NULL)
-	free(etypes);
-    krb5_free_salt(context, salt);
-    memset(newpw, 0, sizeof(newpw));
-
-    return ret;
-}
-
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/cache.c
--- a/head/crypto/heimdal/kcm/cache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/cache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -32,11 +34,9 @@
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: cache.c 14566 2005-02-06 01:22:49Z lukeh $");
-
-static HEIMDAL_MUTEX ccache_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
-static kcm_ccache_data *ccache_head =3D NULL;
-static unsigned int ccache_nextid =3D 0;=20
+HEIMDAL_MUTEX ccache_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
+kcm_ccache_data *ccache_head =3D NULL;
+static unsigned int ccache_nextid =3D 0;
=20
 char *kcm_ccache_nextid(pid_t pid, uid_t uid, gid_t gid)
 {
@@ -47,15 +47,15 @@
     n =3D ++ccache_nextid;
     HEIMDAL_MUTEX_unlock(&ccache_mutex);
=20
-    asprintf(&name, "%d:%u", uid, n);
+    asprintf(&name, "%ld:%u", (long)uid, n);
=20
     return name;
 }
=20
-static krb5_error_code
-kcm_ccache_resolve_internal(krb5_context context,
-			    const char *name,
-			    kcm_ccache *ccache)
+krb5_error_code
+kcm_ccache_resolve(krb5_context context,
+		   const char *name,
+		   kcm_ccache *ccache)
 {
     kcm_ccache p;
     krb5_error_code ret;
@@ -85,6 +85,66 @@
     return ret;
 }
=20
+krb5_error_code
+kcm_ccache_resolve_by_uuid(krb5_context context,
+			   kcmuuid_t uuid,
+			   kcm_ccache *ccache)
+{
+    kcm_ccache p;
+    krb5_error_code ret;
+
+    *ccache =3D NULL;
+
+    ret =3D KRB5_FCC_NOFILE;
+
+    HEIMDAL_MUTEX_lock(&ccache_mutex);
+
+    for (p =3D ccache_head; p !=3D NULL; p =3D p->next) {
+	if ((p->flags & KCM_FLAGS_VALID) =3D=3D 0)
+	    continue;
+	if (memcmp(p->uuid, uuid, sizeof(uuid)) =3D=3D 0) {
+	    ret =3D 0;
+	    break;
+	}
+    }
+
+    if (ret =3D=3D 0) {
+	kcm_retain_ccache(context, p);
+	*ccache =3D p;
+    }
+
+    HEIMDAL_MUTEX_unlock(&ccache_mutex);
+
+    return ret;
+}
+
+krb5_error_code
+kcm_ccache_get_uuids(krb5_context context, kcm_client *client, kcm_operati=
on opcode, krb5_storage *sp)
+{
+    krb5_error_code ret;
+    kcm_ccache p;
+
+    ret =3D KRB5_FCC_NOFILE;
+
+    HEIMDAL_MUTEX_lock(&ccache_mutex);
+
+    for (p =3D ccache_head; p !=3D NULL; p =3D p->next) {
+	if ((p->flags & KCM_FLAGS_VALID) =3D=3D 0)
+	    continue;
+	ret =3D kcm_access(context, client, opcode, p);
+	if (ret) {
+	    ret =3D 0;
+	    continue;
+	}
+	krb5_storage_write(sp, p->uuid, sizeof(p->uuid));
+    }
+
+    HEIMDAL_MUTEX_unlock(&ccache_mutex);
+
+    return ret;
+}
+
+
 krb5_error_code kcm_debug_ccache(krb5_context context)
 {
     kcm_ccache p;
@@ -108,7 +168,7 @@
 	    krb5_unparse_name(context, p->client, &cpn);
 	if (p->server !=3D NULL)
 	    krb5_unparse_name(context, p->server, &spn);
-=09
+
 	kcm_log(7, "cache %08x: name %s refcnt %d flags %04x mode %04o "
 		"uid %d gid %d client %s server %s ncreds %d",
 		p, p->name, p->refcnt, p->flags, p->mode, p->uid, p->gid,
@@ -125,10 +185,48 @@
     return 0;
 }
=20
-static krb5_error_code
-kcm_ccache_destroy_internal(krb5_context context, const char *name)
+static void
+kcm_free_ccache_data_internal(krb5_context context,
+			      kcm_ccache_data *cache)
 {
-    kcm_ccache *p;
+    KCM_ASSERT_VALID(cache);
+
+    if (cache->name !=3D NULL) {
+	free(cache->name);
+	cache->name =3D NULL;
+    }
+
+    if (cache->flags & KCM_FLAGS_USE_KEYTAB) {
+	krb5_kt_close(context, cache->key.keytab);
+	cache->key.keytab =3D NULL;
+    } else if (cache->flags & KCM_FLAGS_USE_CACHED_KEY) {
+	krb5_free_keyblock_contents(context, &cache->key.keyblock);
+	krb5_keyblock_zero(&cache->key.keyblock);
+    }
+
+    cache->flags =3D 0;
+    cache->mode =3D 0;
+    cache->uid =3D -1;
+    cache->gid =3D -1;
+    cache->session =3D -1;
+
+    kcm_zero_ccache_data_internal(context, cache);
+
+    cache->tkt_life =3D 0;
+    cache->renew_life =3D 0;
+
+    cache->next =3D NULL;
+    cache->refcnt =3D 0;
+
+    HEIMDAL_MUTEX_unlock(&cache->mutex);
+    HEIMDAL_MUTEX_destroy(&cache->mutex);
+}
+
+
+krb5_error_code
+kcm_ccache_destroy(krb5_context context, const char *name)
+{
+    kcm_ccache *p, ccache;
     krb5_error_code ret;
=20
     ret =3D KRB5_FCC_NOFILE;
@@ -142,11 +240,18 @@
 	    break;
 	}
     }
-
     if (ret)
 	goto out;
=20
-    kcm_release_ccache(context, p);
+    if ((*p)->refcnt !=3D 1) {
+	ret =3D EAGAIN;
+	goto out;
+    }
+
+    ccache =3D *p;
+    *p =3D (*p)->next;
+    kcm_free_ccache_data_internal(context, ccache);
+    free(ccache);
=20
 out:
     HEIMDAL_MUTEX_unlock(&ccache_mutex);
@@ -182,28 +287,20 @@
 	goto out;
=20
     /*
-     * Then try and find an empty slot
-     * XXX we need to recycle slots for this to actually do anything
+     * Create an enpty slot for us.
      */
     if (slot =3D=3D NULL) {
-	for (; p !=3D NULL; p =3D p->next) {
-	    if ((p->flags & KCM_FLAGS_VALID) =3D=3D 0) {
-		slot =3D p;
-		break;
-	    }
+	slot =3D (kcm_ccache_data *)malloc(sizeof(*slot));
+	if (slot =3D=3D NULL) {
+	    ret =3D KRB5_CC_NOMEM;
+	    goto out;
 	}
+	slot->next =3D ccache_head;
+	HEIMDAL_MUTEX_init(&slot->mutex);
+	new_slot =3D 1;
+    }
=20
-	if (slot =3D=3D NULL) {
-	    slot =3D (kcm_ccache_data *)malloc(sizeof(*slot));
-	    if (slot =3D=3D NULL) {
-		ret =3D KRB5_CC_NOMEM;
-		goto out;
-	    }
-	    slot->next =3D ccache_head;
-	    HEIMDAL_MUTEX_init(&slot->mutex);
-	    new_slot =3D 1;
-	}
-    }
+    RAND_bytes(slot->uuid, sizeof(slot->uuid));
=20
     slot->name =3D strdup(name);
     if (slot->name =3D=3D NULL) {
@@ -219,8 +316,6 @@
     slot->client =3D NULL;
     slot->server =3D NULL;
     slot->creds =3D NULL;
-    slot->n_cursor =3D 0;
-    slot->cursors =3D NULL;
     slot->key.keytab =3D NULL;
     slot->tkt_life =3D 0;
     slot->renew_life =3D 0;
@@ -247,7 +342,6 @@
 				 kcm_ccache ccache)
 {
     struct kcm_creds *k;
-    struct kcm_cursor *c;
=20
     k =3D ccache->creds;
     while (k !=3D NULL) {
@@ -260,20 +354,6 @@
     }
     ccache->creds =3D NULL;
=20
-    /* remove anything that would have pointed into the creds too */
-
-    ccache->n_cursor =3D 0;
-
-    c =3D ccache->cursors;
-    while (c !=3D NULL) {
-	struct kcm_cursor *old;
-
-	old =3D c;
-	c =3D c->next;
-	free(old);
-    }
-    ccache->cursors =3D NULL;
-
     return 0;
 }
=20
@@ -326,44 +406,6 @@
     return ret;
 }
=20
-static krb5_error_code
-kcm_free_ccache_data_internal(krb5_context context,
-			      kcm_ccache_data *cache)
-{
-    KCM_ASSERT_VALID(cache);
-
-    if (cache->name !=3D NULL) {
-	free(cache->name);
-	cache->name =3D NULL;
-    }
-
-    if (cache->flags & KCM_FLAGS_USE_KEYTAB) {
-	krb5_kt_close(context, cache->key.keytab);
-	cache->key.keytab =3D NULL;
-    } else if (cache->flags & KCM_FLAGS_USE_CACHED_KEY) {
-	krb5_free_keyblock_contents(context, &cache->key.keyblock);
-	krb5_keyblock_zero(&cache->key.keyblock);
-    }
-
-    cache->flags =3D 0;
-    cache->mode =3D 0;
-    cache->uid =3D -1;
-    cache->gid =3D -1;
-
-    kcm_zero_ccache_data_internal(context, cache);
-
-    cache->tkt_life =3D 0;
-    cache->renew_life =3D 0;
-
-    cache->next =3D NULL;
-    cache->refcnt =3D 0;
-
-    HEIMDAL_MUTEX_unlock(&cache->mutex);
-    HEIMDAL_MUTEX_destroy(&cache->mutex);
-
-    return 0;
-}
-
 krb5_error_code
 kcm_retain_ccache(krb5_context context,
 		  kcm_ccache ccache)
@@ -378,26 +420,21 @@
 }
=20
 krb5_error_code
-kcm_release_ccache(krb5_context context,
-		   kcm_ccache *ccache)
+kcm_release_ccache(krb5_context context, kcm_ccache c)
 {
-    kcm_ccache c =3D *ccache;
     krb5_error_code ret =3D 0;
=20
     KCM_ASSERT_VALID(c);
=20
     HEIMDAL_MUTEX_lock(&c->mutex);
     if (c->refcnt =3D=3D 1) {
-	ret =3D kcm_free_ccache_data_internal(context, c);
-	if (ret =3D=3D 0)
-	    free(c);
+	kcm_free_ccache_data_internal(context, c);
+	free(c);
     } else {
 	c->refcnt--;
 	HEIMDAL_MUTEX_unlock(&c->mutex);
     }
=20
-    *ccache =3D NULL;
-
     return ret;
 }
=20
@@ -442,38 +479,15 @@
 }
=20
 krb5_error_code
-kcm_ccache_resolve(krb5_context context,
-		   const char *name,
-		   kcm_ccache *ccache)
-{
-    krb5_error_code ret;
-
-    ret =3D kcm_ccache_resolve_internal(context, name, ccache);
-
-    return ret;
-}
-
-krb5_error_code
-kcm_ccache_destroy(krb5_context context,
-		   const char *name)
-{
-    krb5_error_code ret;
-
-    ret =3D kcm_ccache_destroy_internal(context, name);
-
-    return ret;
-}
-
-krb5_error_code
 kcm_ccache_destroy_if_empty(krb5_context context,
 			    kcm_ccache ccache)
 {
     krb5_error_code ret;
=20
     KCM_ASSERT_VALID(ccache);
-   =20
+
     if (ccache->creds =3D=3D NULL) {
-	ret =3D kcm_ccache_destroy_internal(context, ccache->name);
+	ret =3D kcm_ccache_destroy(context, ccache->name);
     } else
 	ret =3D 0;
=20
@@ -490,7 +504,7 @@
     krb5_creds *tmp;
=20
     KCM_ASSERT_VALID(ccache);
-   =20
+
     HEIMDAL_MUTEX_lock(&ccache->mutex);
     ret =3D kcm_ccache_store_cred_internal(context, ccache, creds, copy, &=
tmp);
     HEIMDAL_MUTEX_unlock(&ccache->mutex);
@@ -498,6 +512,22 @@
     return ret;
 }
=20
+struct kcm_creds *
+kcm_ccache_find_cred_uuid(krb5_context context,
+			  kcm_ccache ccache,
+			  kcmuuid_t uuid)
+{
+    struct kcm_creds *c;
+
+    for (c =3D ccache->creds; c !=3D NULL; c =3D c->next)
+	if (memcmp(c->uuid, uuid, sizeof(c->uuid)) =3D=3D 0)
+	    return c;
+
+    return NULL;
+}
+
+
+
 krb5_error_code
 kcm_ccache_store_cred_internal(krb5_context context,
 			       kcm_ccache ccache,
@@ -511,10 +541,11 @@
     for (c =3D &ccache->creds; *c !=3D NULL; c =3D &(*c)->next)
 	;
=20
-    *c =3D (struct kcm_creds *)malloc(sizeof(struct kcm_creds));
-    if (*c =3D=3D NULL) {
+    *c =3D (struct kcm_creds *)calloc(1, sizeof(**c));
+    if (*c =3D=3D NULL)
 	return KRB5_CC_NOMEM;
-    }
+
+    RAND_bytes((*c)->uuid, sizeof((*c)->uuid));
=20
     *credp =3D &(*c)->cred;
=20
@@ -529,25 +560,9 @@
 	ret =3D 0;
     }
=20
-    (*c)->next =3D NULL;
-
     return ret;
 }
=20
-static void
-remove_cred(krb5_context context,
-	    struct kcm_creds **c)
-{
-    struct kcm_creds *cred;
-
-    cred =3D *c;
-
-    *c =3D cred->next;
-
-    krb5_free_cred_contents(context, &cred->cred);
-    free(cred);
-}
-
 krb5_error_code
 kcm_ccache_remove_cred_internal(krb5_context context,
 				kcm_ccache ccache,
@@ -561,8 +576,14 @@
=20
     for (c =3D &ccache->creds; *c !=3D NULL; c =3D &(*c)->next) {
 	if (krb5_compare_creds(context, whichfields, mcreds, &(*c)->cred)) {
-	    remove_cred(context, c);
+	    struct kcm_creds *cred =3D *c;
+
+	    *c =3D cred->next;
+	    krb5_free_cred_contents(context, &cred->cred);
+	    free(cred);
 	    ret =3D 0;
+	    if (*c =3D=3D NULL)
+		break;
 	}
     }
=20
@@ -626,7 +647,7 @@
     krb5_error_code ret;
=20
     KCM_ASSERT_VALID(ccache);
-   =20
+
     HEIMDAL_MUTEX_lock(&ccache->mutex);
     ret =3D kcm_ccache_retrieve_cred_internal(context, ccache,
 					    whichfields, mcreds, credp);
@@ -634,3 +655,21 @@
=20
     return ret;
 }
+
+char *
+kcm_ccache_first_name(kcm_client *client)
+{
+    kcm_ccache p;
+    char *name =3D NULL;
+
+    HEIMDAL_MUTEX_lock(&ccache_mutex);
+
+    for (p =3D ccache_head; p !=3D NULL; p =3D p->next) {
+	if (kcm_is_same_session(client, p->uid, p->session))
+	    break;
+    }
+    if (p)
+	name =3D strdup(p->name);
+    HEIMDAL_MUTEX_unlock(&ccache_mutex);
+    return name;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/client.c
--- a/head/crypto/heimdal/kcm/client.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/client.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -33,8 +35,6 @@
 #include "kcm_locl.h"
 #include <pwd.h>
=20
-RCSID("$Id: client.c 20487 2007-04-21 06:25:06Z lha $");
-
 krb5_error_code
 kcm_ccache_resolve_client(krb5_context context,
 			  kcm_client *client,
@@ -54,7 +54,7 @@
     ret =3D kcm_access(context, client, opcode, *ccache);
     if (ret) {
 	ret =3D KRB5_FCC_NOFILE; /* don't disclose */
-	kcm_release_ccache(context, ccache);
+	kcm_release_ccache(context, *ccache);
     }
=20
     return ret;
@@ -76,19 +76,12 @@
     }
=20
     ret =3D kcm_access(context, client, KCM_OP_DESTROY, ccache);
-    if (ret) {
-	kcm_release_ccache(context, &ccache);
+    kcm_cleanup_events(context, ccache);
+    kcm_release_ccache(context, ccache);
+    if (ret)
 	return ret;
-    }
=20
-    ret =3D kcm_ccache_destroy(context, ccache->name);
-    if (ret =3D=3D 0) {
-	/* don't leave any events dangling */
-	kcm_cleanup_events(context, ccache);
-    }
-
-    kcm_release_ccache(context, &ccache);
-    return ret;
+    return kcm_ccache_destroy(context, name);
 }
=20
 krb5_error_code
@@ -121,7 +114,7 @@
 	if (bad && !CLIENT_IS_ROOT(client))
 	    return KRB5_CC_BADNAME;
     }
-=09
+
     ret =3D kcm_ccache_resolve(context, name, &ccache);
     if (ret =3D=3D 0) {
 	if ((ccache->uid !=3D client->uid ||
@@ -142,12 +135,13 @@
 	/* bind to current client */
 	ccache->uid =3D client->uid;
 	ccache->gid =3D client->gid;
+	ccache->session =3D client->session;
     } else {
 	ret =3D kcm_zero_ccache_data(context, ccache);
 	if (ret) {
 	    kcm_log(1, "Failed to empty cache %s: %s",
 		    name, krb5_get_err_text(context, ret));
-	    kcm_release_ccache(context, &ccache);
+	    kcm_release_ccache(context, ccache);
 	    return ret;
 	}
 	kcm_cleanup_events(context, ccache);
@@ -155,12 +149,12 @@
=20
     ret =3D kcm_access(context, client, KCM_OP_INITIALIZE, ccache);
     if (ret) {
-	kcm_release_ccache(context, &ccache);
+	kcm_release_ccache(context, ccache);
 	kcm_ccache_destroy(context, name);
 	return ret;
     }
=20
-    /*=20
+    /*
      * Finally, if the user is root and the cache was created under
      * another user's name, chown the cache to that user and their
      * default gid.
@@ -178,7 +172,7 @@
 	    }
 	}
     }
-   =20
+
     *ccache_p =3D ccache;
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/config.c
--- a/head/crypto/heimdal/kcm/config.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/config.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -34,8 +36,6 @@
 #include <getarg.h>
 #include <parse_bytes.h>
=20
-RCSID("$Id: config.c 15296 2005-05-30 10:17:43Z lha $");
-
 static const char *config_file;	/* location of kcm config file */
=20
 size_t max_request =3D 0;		/* maximal size of a request */
@@ -44,8 +44,10 @@
=20
 static char *max_request_str;	/* `max_request' as a string */
=20
+#ifdef SUPPORT_DETACH
 int detach_from_console =3D -1;
 #define DETACH_IS_DEFAULT FALSE
+#endif
=20
 static const char *system_cache_name =3D NULL;
 static const char *system_keytab =3D NULL;
@@ -58,44 +60,51 @@
 static const char *renew_life =3D NULL;
 static const char *ticket_life =3D NULL;
=20
-int disallow_getting_krbtgt =3D -1;
+int launchd_flag =3D 0;
+int disallow_getting_krbtgt =3D 0;
 int name_constraints =3D -1;
=20
 static int help_flag;
 static int version_flag;
=20
 static struct getargs args[] =3D {
-    {=20
-	"cache-name",	0,	arg_string,	&system_cache_name,=20
-	"system cache name", "cachename"=20
+    {
+	"cache-name",	0,	arg_string,	&system_cache_name,
+	"system cache name", "cachename"
     },
-    {=20
-	"config-file",	'c',	arg_string,	&config_file,=20
-	"location of config file",	"file"=20
+    {
+	"config-file",	'c',	arg_string,	&config_file,
+	"location of config file",	"file"
     },
-    {=20
-	"group",	'g',	arg_string,	&system_group,=20
-	"system cache group",	"group"=20
+    {
+	"group",	'g',	arg_string,	&system_group,
+	"system cache group",	"group"
     },
-    {=20
-	"max-request",	0,	arg_string, &max_request,=20
+    {
+	"max-request",	0,	arg_string, &max_request,
 	"max size for a kcm-request", "size"
     },
+    {
+	"launchd",	0,	arg_flag, &launchd_flag,
+	"when in use by launchd"
+    },
+#ifdef SUPPORT_DETACH
 #if DETACH_IS_DEFAULT
     {
-	"detach",       'D',      arg_negative_flag, &detach_from_console,=20
+	"detach",       'D',      arg_negative_flag, &detach_from_console,
 	"don't detach from console"
     },
 #else
     {
-	"detach",       0 ,      arg_flag, &detach_from_console,=20
+	"detach",       0 ,      arg_flag, &detach_from_console,
 	"detach from console"
     },
 #endif
+#endif
     {	"help",		'h',	arg_flag,   &help_flag },
-    {=20
-	"system-principal",	'k',	arg_string,	&system_principal,=20
-	"system principal name",	"principal"=20
+    {
+	"system-principal",	'k',	arg_string,	&system_principal,
+	"system principal name",	"principal"
     },
     {
 	"lifetime",	'l', arg_string, &ticket_life,
@@ -131,13 +140,13 @@
 	"server",		'S', arg_string, &system_server,
     	"server to get system ticket for", "principal"
     },
-    {=20
-	"keytab",	't',	arg_string,	&system_keytab,=20
-	"system keytab name",	"keytab"=20
+    {
+	"keytab",	't',	arg_string,	&system_keytab,
+	"system keytab name",	"keytab"
     },
-    {=20
-	"user",		'u',	arg_string,	&system_user,=20
-	"system cache owner",	"user"=20
+    {
+	"user",		'u',	arg_string,	&system_user,
+	"system cache owner",	"user"
     },
     {	"version",	'v',	arg_flag,   &version_flag }
 };
@@ -236,7 +245,7 @@
=20
     ret =3D krb5_parse_name(kcm_context, system_principal, &ccache->client=
);
     if (ret) {
-	kcm_release_ccache(kcm_context, &ccache);
+	kcm_release_ccache(kcm_context, ccache);
 	return ret;
     }
=20
@@ -246,7 +255,7 @@
     if (system_server !=3D NULL) {
 	ret =3D krb5_parse_name(kcm_context, system_server, &ccache->server);
 	if (ret) {
-	    kcm_release_ccache(kcm_context, &ccache);
+	    kcm_release_ccache(kcm_context, ccache);
 	    return ret;
 	}
     }
@@ -260,7 +269,7 @@
 	ret =3D krb5_kt_default(kcm_context, &ccache->key.keytab);
     }
     if (ret) {
-	kcm_release_ccache(kcm_context, &ccache);
+	kcm_release_ccache(kcm_context, ccache);
 	return ret;
     }
=20
@@ -273,7 +282,7 @@
     if (renew_life !=3D NULL) {
 	ccache->renew_life =3D parse_time(renew_life, "s");
 	if (ccache->renew_life < 0) {
-	    kcm_release_ccache(kcm_context, &ccache);
+	    kcm_release_ccache(kcm_context, ccache);
 	    return EINVAL;
 	}
     }
@@ -284,7 +293,7 @@
     if (ticket_life !=3D NULL) {
 	ccache->tkt_life =3D parse_time(ticket_life, "s");
 	if (ccache->tkt_life < 0) {
-	    kcm_release_ccache(kcm_context, &ccache);
+	    kcm_release_ccache(kcm_context, ccache);
 	    return EINVAL;
 	}
     }
@@ -310,7 +319,7 @@
     /* enqueue default actions for credentials cache */
     ret =3D kcm_ccache_enqueue_default(kcm_context, ccache, NULL);
=20
-    kcm_release_ccache(kcm_context, &ccache); /* retained by event queue */
+    kcm_release_ccache(kcm_context, ccache); /* retained by event queue */
=20
     return ret;
 }
@@ -321,7 +330,7 @@
     krb5_error_code ret;
     int optind =3D 0;
     const char *p;
-   =20
+
     while(getarg(args, num_args, argc, argv, &optind))
 	warnx("error at argument `%s'", argv[optind]);
=20
@@ -338,7 +347,7 @@
=20
     if (argc !=3D 0)
 	usage(1);
-   =20
+
     {
 	char **files;
=20
@@ -348,10 +357,10 @@
 	ret =3D krb5_prepend_config_files_default(config_file, &files);
 	if (ret)
 	    krb5_err(kcm_context, 1, ret, "getting configuration files");
-	   =20
+
 	ret =3D krb5_set_config_files(kcm_context, files);
 	krb5_free_config_files(files);
-	if(ret)=20
+	if(ret)
 	    krb5_err(kcm_context, 1, ret, "reading configuration files");
     }
=20
@@ -378,11 +387,13 @@
 	    krb5_err(kcm_context, 1, ret, "initializing system ccache");
     }
=20
-    if(detach_from_console =3D=3D -1)=20
+#ifdef SUPPORT_DETACH
+    if(detach_from_console =3D=3D -1)
 	detach_from_console =3D krb5_config_get_bool_default(kcm_context, NULL,
 							   DETACH_IS_DEFAULT,
 							   "kcm",
 							   "detach", NULL);
+#endif
     kcm_openlog();
     if(max_request =3D=3D 0)
 	max_request =3D 64 * 1024;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/connect.c
--- a/head/crypto/heimdal/kcm/connect.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/connect.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,688 +1,84 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: connect.c 16314 2005-11-29 19:03:50Z lha $");
+void
+kcm_service(void *ctx, const heim_idata *req,
+	    const heim_icred cred,
+	    heim_ipc_complete complete,
+	    heim_sipc_call cctx)
+{
+    kcm_client peercred;
+    krb5_error_code ret;
+    krb5_data request, rep;
+    unsigned char *buf;
+    size_t len;
=20
-struct descr {
-    int s;
-    int type;
-    char *path;
-    unsigned char *buf;
-    size_t size;
-    size_t len;
-    time_t timeout;
-    struct sockaddr_storage __ss;
-    struct sockaddr *sa;
-    socklen_t sock_len;
-    kcm_client peercred;
-};
+    krb5_data_zero(&rep);
=20
-static void
-init_descr(struct descr *d)
-{
-    memset(d, 0, sizeof(*d));
-    d->sa =3D (struct sockaddr *)&d->__ss;
-    d->s =3D -1;
-}
+    peercred.uid =3D heim_ipc_cred_get_uid(cred);
+    peercred.gid =3D heim_ipc_cred_get_gid(cred);
+    peercred.pid =3D heim_ipc_cred_get_pid(cred);
+    peercred.session =3D heim_ipc_cred_get_session(cred);
=20
-/*
- * re-initialize all `n' ->sa in `d'.
- */
-
-static void
-reinit_descrs (struct descr *d, int n)
-{
-    int i;
-
-    for (i =3D 0; i < n; ++i)
-	d[i].sa =3D (struct sockaddr *)&d[i].__ss;
-}
-
-/*
- * Update peer credentials from socket.
- *
- * SCM_CREDS can only be updated the first time there is read data to
- * read from the filedescriptor, so if we read do it before this
- * point, the cred data might not be is not there yet.
- */
-
-static int
-update_client_creds(int s, kcm_client *peer)
-{
-#ifdef GETPEERUCRED
-    /* Solaris 10 */
-    {
-	ucred_t *peercred;
-=09
-	if (getpeerucred(s, &peercred) !=3D 0) {
-	    peer->uid =3D ucred_geteuid(peercred);
-	    peer->gid =3D ucred_getegid(peercred);
-	    peer->pid =3D 0;
-	    ucred_free(peercred);
-	    return 0;
-	}
-    }=20
-#endif
-#ifdef GETPEEREID
-    /* FreeBSD, OpenBSD */
-    {
-	uid_t uid;
-	gid_t gid;
-
-	if (getpeereid(s, &uid, &gid) =3D=3D 0) {
-	    peer->uid =3D uid;
-	    peer->gid =3D gid;
-	    peer->pid =3D 0;
-	    return 0;
-	}
-    }
-#endif
-#ifdef SO_PEERCRED
-    /* Linux */
-    {
-	struct ucred pc;
-	socklen_t pclen =3D sizeof(pc);
-
-	if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, (void *)&pc, &pclen) =3D=3D 0)=
 {
-	    peer->uid =3D pc.uid;
-	    peer->gid =3D pc.gid;
-	    peer->pid =3D pc.pid;
-	    return 0;
-	}
-    }
-#endif
-#if defined(LOCAL_PEERCRED) && defined(XUCRED_VERSION)
-    {
-	struct xucred peercred;
-	socklen_t peercredlen =3D sizeof(peercred);
-
-	if (getsockopt(s, LOCAL_PEERCRED, 1,
-		       (void *)&peercred, &peercredlen) =3D=3D 0
-	    && peercred.cr_version =3D=3D XUCRED_VERSION)
-	{
-	    peer->uid =3D peercred.cr_uid;
-	    peer->gid =3D peercred.cr_gid;
-	    peer->pid =3D 0;
-	    return 0;
-	}
-    }
-#endif
-#if defined(SOCKCREDSIZE) && defined(SCM_CREDS)
-    /* NetBSD */
-    if (peer->uid =3D=3D -1) {
-	struct msghdr msg;
-	socklen_t crmsgsize;
-	void *crmsg;
-	struct cmsghdr *cmp;
-	struct sockcred *sc;
-=09
-	memset(&msg, 0, sizeof(msg));
-	crmsgsize =3D CMSG_SPACE(SOCKCREDSIZE(CMGROUP_MAX));
-	if (crmsgsize =3D=3D 0)
-	    return 1 ;
-
-	crmsg =3D malloc(crmsgsize);
-	if (crmsg =3D=3D NULL)
-	    goto failed_scm_creds;
-
-	memset(crmsg, 0, crmsgsize);
-=09
-	msg.msg_control =3D crmsg;
-	msg.msg_controllen =3D crmsgsize;
-=09
-	if (recvmsg(s, &msg, 0) < 0) {
-	    free(crmsg);
-	    goto failed_scm_creds;
-	}=09
-=09
-	if (msg.msg_controllen =3D=3D 0 || (msg.msg_flags & MSG_CTRUNC) !=3D 0) {
-	    free(crmsg);
-	    goto failed_scm_creds;
-	}=09
-=09
-	cmp =3D CMSG_FIRSTHDR(&msg);
-	if (cmp->cmsg_level !=3D SOL_SOCKET || cmp->cmsg_type !=3D SCM_CREDS) {
-	    free(crmsg);
-	    goto failed_scm_creds;
-	}=09
-=09
-	sc =3D (struct sockcred *)(void *)CMSG_DATA(cmp);
-=09
-	peer->uid =3D sc->sc_euid;
-	peer->gid =3D sc->sc_egid;
-	peer->pid =3D 0;
-=09
-	free(crmsg);
-	return 0;
-    } else {
-	/* we already got the cred, just return it */
-	return 0;
-    }
- failed_scm_creds:
-#endif
-    krb5_warn(kcm_context, errno, "failed to determine peer identity");
-    return 1;
-}
-
-
-/*
- * Create the socket (family, type, port) in `d'
- */
-
-static void=20
-init_socket(struct descr *d)
-{
-    struct sockaddr_un un;
-    struct sockaddr *sa =3D (struct sockaddr *)&un;
-    krb5_socklen_t sa_size =3D sizeof(un);
-
-    init_descr (d);
-
-    un.sun_family =3D AF_UNIX;
-
-    if (socket_path !=3D NULL)
-	d->path =3D socket_path;
-    else
-	d->path =3D _PATH_KCM_SOCKET;
-
-    strlcpy(un.sun_path, d->path, sizeof(un.sun_path));
-
-    d->s =3D socket(AF_UNIX, SOCK_STREAM, 0);
-    if (d->s < 0){
-	krb5_warn(kcm_context, errno, "socket(%d, %d, 0)", AF_UNIX, SOCK_STREAM);
-	d->s =3D -1;
-	return;
-    }
-#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_REUSEADD=
R)
-    {
-	int one =3D 1;
-	setsockopt(d->s, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
-    }
-#endif
-#ifdef LOCAL_CREDS
-    {
-	int one =3D 1;
-	setsockopt(d->s, 0, LOCAL_CREDS, (void *)&one, sizeof(one));
-    }
-#endif
-
-    d->type =3D SOCK_STREAM;
-
-    unlink(d->path);
-
-    if (bind(d->s, sa, sa_size) < 0) {
-	krb5_warn(kcm_context, errno, "bind %s", un.sun_path);
-	close(d->s);
-	d->s =3D -1;
+    if (req->length < 4) {
+	kcm_log(1, "malformed request from process %d (too short)",
+		peercred.pid);
+	(*complete)(cctx, EINVAL, NULL);
 	return;
     }
=20
-    if (listen(d->s, SOMAXCONN) < 0) {
-	krb5_warn(kcm_context, errno, "listen %s", un.sun_path);
-	close(d->s);
-	d->s =3D -1;
-	return;
-    }
-
-    chmod(d->path, 0777);
-
-    return;
-}
-
-/*
- * Allocate descriptors for all the sockets that we should listen on
- * and return the number of them.
- */
-
-static int
-init_sockets(struct descr **desc)
-{
-    struct descr *d;
-    size_t num =3D 0;
-
-    d =3D (struct descr *)malloc(sizeof(*d));
-    if (d =3D=3D NULL) {
-	krb5_errx(kcm_context, 1, "malloc failed");
-    }
-
-    init_socket(d);
-    if (d->s !=3D -1) {
-	kcm_log(5, "listening on domain socket %s", d->path);
-	num++;
-    }
-
-    reinit_descrs (d, num);
-    *desc =3D d;
-
-    return num;
-}
-
-/*
- * handle the request in `buf, len', from `addr' (or `from' as a string),
- * sending a reply in `reply'.
- */
-
-static int
-process_request(unsigned char *buf,=20
-		size_t len,=20
-		krb5_data *reply,
-		kcm_client *client)
-{
-    krb5_data request;
-  =20
-    if (len < 4) {
-	kcm_log(1, "malformed request from process %d (too short)",=20
-		client->pid);
-	return -1;
-    }
+    buf =3D req->data;
+    len =3D req->length;
=20
     if (buf[0] !=3D KCM_PROTOCOL_VERSION_MAJOR ||
 	buf[1] !=3D KCM_PROTOCOL_VERSION_MINOR) {
 	kcm_log(1, "incorrect protocol version %d.%d from process %d",
-		buf[0], buf[1], client->pid);
-	return -1;
+		buf[0], buf[1], peercred.pid);
+	(*complete)(cctx, EINVAL, NULL);
+	return;
     }
=20
-    buf +=3D 2;
-    len -=3D 2;
+    request.data =3D buf + 2;
+    request.length =3D len - 2;
=20
     /* buf is now pointing at opcode */
=20
-    request.data =3D buf;
-    request.length =3D len;
+    ret =3D kcm_dispatch(kcm_context, &peercred, &request, &rep);
=20
-    return kcm_dispatch(kcm_context, client, &request, reply);
+    (*complete)(cctx, ret, &rep);
+    krb5_data_free(&rep);
 }
-
-/*
- * Handle the request in `buf, len' to socket `d'
- */
-
-static void
-do_request(void *buf, size_t len, struct descr *d)
-{
-    krb5_error_code ret;
-    krb5_data reply;
-
-    reply.length =3D 0;
-
-    ret =3D process_request(buf, len, &reply, &d->peercred);
-    if (reply.length !=3D 0) {
-	unsigned char len[4];
-	struct msghdr msghdr;
-	struct iovec iov[2];
-
-	kcm_log(5, "sending %lu bytes to process %d",=20
-		(unsigned long)reply.length,
-		(int)d->peercred.pid);
-
-	memset (&msghdr, 0, sizeof(msghdr));
-	msghdr.msg_name       =3D NULL;
-	msghdr.msg_namelen    =3D 0;
-	msghdr.msg_iov        =3D iov;
-	msghdr.msg_iovlen     =3D sizeof(iov)/sizeof(*iov);
-#if 0
-	msghdr.msg_control    =3D NULL;
-	msghdr.msg_controllen =3D 0;
-#endif
-
-	len[0] =3D (reply.length >> 24) & 0xff;
-	len[1] =3D (reply.length >> 16) & 0xff;
-	len[2] =3D (reply.length >> 8) & 0xff;
-	len[3] =3D reply.length & 0xff;
-
-	iov[0].iov_base       =3D (void*)len;
-	iov[0].iov_len        =3D 4;
-	iov[1].iov_base       =3D reply.data;
-	iov[1].iov_len        =3D reply.length;
-
-	if (sendmsg (d->s, &msghdr, 0) < 0) {
-	    kcm_log (0, "sendmsg(%d): %d %s", (int)d->peercred.pid,
-		     errno, strerror(errno));
-	    krb5_data_free(&reply);
-	    return;
-	}
-
-	krb5_data_free(&reply);
-    }
-
-    if (ret) {
-	kcm_log(0, "Failed processing %lu byte request from process %d",=20
-		(unsigned long)len, d->peercred.pid);
-    }
-}
-
-static void
-clear_descr(struct descr *d)
-{
-    if(d->buf)
-	memset(d->buf, 0, d->size);
-    d->len =3D 0;
-    if(d->s !=3D -1)
-	close(d->s);
-    d->s =3D -1;
-}
-
-#define STREAM_TIMEOUT 4
-
-/*
- * accept a new stream connection on `d[parent]' and store it in `d[child]'
- */
-
-static void
-add_new_stream (struct descr *d, int parent, int child)
-{
-    int s;
-
-    if (child =3D=3D -1)
-	return;
-
-    d[child].peercred.pid =3D -1;
-    d[child].peercred.uid =3D -1;
-    d[child].peercred.gid =3D -1;
-
-    d[child].sock_len =3D sizeof(d[child].__ss);
-    s =3D accept(d[parent].s, d[child].sa, &d[child].sock_len);
-    if(s < 0) {
-	krb5_warn(kcm_context, errno, "accept");
-	return;
-    }
-
-    if (s >=3D FD_SETSIZE) {
-	krb5_warnx(kcm_context, "socket FD too large");
-	close (s);
-	return;
-    }
-
-    d[child].s =3D s;
-    d[child].timeout =3D time(NULL) + STREAM_TIMEOUT;
-    d[child].type =3D SOCK_STREAM;
-}
-
-/*
- * Grow `d' to handle at least `n'.
- * Return !=3D 0 if fails
- */
-
-static int
-grow_descr (struct descr *d, size_t n)
-{
-    if (d->size - d->len < n) {
-	unsigned char *tmp;
-	size_t grow;
-
-	grow =3D max(1024, d->len + n);
-	if (d->size + grow > max_request) {
-	    kcm_log(0, "Request exceeds max request size (%lu bytes).",
-		    (unsigned long)d->size + grow);
-	    clear_descr(d);
-	    return -1;
-	}
-	tmp =3D realloc (d->buf, d->size + grow);
-	if (tmp =3D=3D NULL) {
-	    kcm_log(0, "Failed to re-allocate %lu bytes.",
-		    (unsigned long)d->size + grow);
-	    clear_descr(d);
-	    return -1;
-	}
-	d->size +=3D grow;
-	d->buf =3D tmp;
-    }
-    return 0;
-}
-
-/*
- * Handle incoming data to the stream socket in `d[index]'
- */
-
-static void
-handle_stream(struct descr *d, int index, int min_free)
-{
-    unsigned char buf[1024];
-    int n;
-    int ret =3D 0;
-
-    if (d[index].timeout =3D=3D 0) {
-	add_new_stream (d, index, min_free);
-	return;
-    }
-
-    if (update_client_creds(d[index].s, &d[index].peercred)) {
-	krb5_warnx(kcm_context, "failed to update peer identity");
-	clear_descr(d + index);
-	return;
-    }
-
-    if (d[index].peercred.uid =3D=3D -1) {
-	krb5_warnx(kcm_context, "failed to determine peer identity");
-	clear_descr (d + index);
-	return;
-    }
-
-    n =3D recvfrom(d[index].s, buf, sizeof(buf), 0, NULL, NULL);
-    if (n < 0) {
-	krb5_warn(kcm_context, errno, "recvfrom");
-	return;
-    } else if (n =3D=3D 0) {
-	krb5_warnx(kcm_context, "connection closed before end of data "
-		   "after %lu bytes from process %ld",
-		   (unsigned long) d[index].len, (long) d[index].peercred.pid);
-	clear_descr (d + index);
-	return;
-    }
-    if (grow_descr (&d[index], n))
-	return;
-    memcpy(d[index].buf + d[index].len, buf, n);
-    d[index].len +=3D n;
-    if (d[index].len > 4) {
-	krb5_storage *sp;
-	int32_t len;
-
-	sp =3D krb5_storage_from_mem(d[index].buf, d[index].len);
-	if (sp =3D=3D NULL) {
-	    kcm_log (0, "krb5_storage_from_mem failed");
-	    ret =3D -1;
-	} else {
-	    krb5_ret_int32(sp, &len);
-	    krb5_storage_free(sp);
-	    if (d[index].len - 4 >=3D len) {
-		memmove(d[index].buf, d[index].buf + 4, d[index].len - 4);
-		ret =3D 1;
-	    } else
-		ret =3D 0;
-	}
-    }
-    if (ret < 0)
-	return;
-    else if (ret =3D=3D 1) {
-	do_request(d[index].buf, d[index].len, &d[index]);
-	clear_descr(d + index);
-    }
-}
-
-#ifdef HAVE_DOOR_CREATE
-
-static void
-kcm_door_server(void  *cookie, char *argp, size_t arg_size,
-		door_desc_t *dp, uint_t n_desc)
-{
-    kcm_client peercred;
-    door_cred_t cred;
-    krb5_error_code ret;
-    krb5_data reply;
-    size_t length;
-    char *p;
-
-    reply.length =3D 0;
-
-    p =3D NULL;
-    length =3D 0;
-
-    if (door_cred(&cred) !=3D 0) {
-	kcm_log(0, "door_cred failed with %s", strerror(errno));
-	goto out;
-    }
-
-    peercred.uid =3D cred.dc_euid;
-    peercred.gid =3D cred.dc_egid;
-    peercred.pid =3D cred.dc_pid;
-
-    ret =3D process_request((unsigned char*)argp, arg_size, &reply, &peerc=
red);
-    if (reply.length !=3D 0) {
-	p =3D alloca(reply.length); /* XXX don't use alloca */
-	if (p) {
-	    memcpy(p, reply.data, reply.length);
-	    length =3D reply.length;
-	}
-	krb5_data_free(&reply);
-    }
-
- out:
-    door_return(p, length, NULL, 0);
-}
-
-static void
-kcm_setup_door(void)
-{
-    int fd, ret;
-    char *path;
-
-    fd =3D door_create(kcm_door_server, NULL, 0);
-    if (fd < 0)
-	krb5_err(kcm_context, 1, errno, "Failed to create door");
-
-    if (door_path !=3D NULL)
-	path =3D door_path;
-    else
-	path =3D _PATH_KCM_DOOR;
-
-    unlink(path);
-    ret =3D open(path, O_RDWR | O_CREAT, 0666);
-    if (ret < 0)
-	krb5_err(kcm_context, 1, errno, "Failed to create/open door");
-    close(ret);
-
-    ret =3D fattach(fd, path);
-    if (ret < 0)
-	krb5_err(kcm_context, 1, errno, "Failed to attach door");
-
-}
-#endif /* HAVE_DOOR_CREATE */
-
-
-void
-kcm_loop(void)
-{
-    struct descr *d;
-    int ndescr;
-
-#ifdef HAVE_DOOR_CREATE
-    kcm_setup_door();
-#endif
-
-    ndescr =3D init_sockets(&d);
-    if (ndescr <=3D 0) {
-	krb5_warnx(kcm_context, "No sockets!");
-#ifndef HAVE_DOOR_CREATE
-	exit(1);
-#endif
-    }
-    while (exit_flag =3D=3D 0){
-	struct timeval tmout;
-	fd_set fds;
-	int min_free =3D -1;
-	int max_fd =3D 0;
-	int i;
-
-	FD_ZERO(&fds);
-	for(i =3D 0; i < ndescr; i++) {
-	    if (d[i].s >=3D 0){
-		if(d[i].type =3D=3D SOCK_STREAM &&=20
-		   d[i].timeout && d[i].timeout < time(NULL)) {
-		    kcm_log(1, "Stream connection from %d expired after %lu bytes",
-			    d[i].peercred.pid, (unsigned long)d[i].len);
-		    clear_descr(&d[i]);
-		    continue;
-		}
-		if (max_fd < d[i].s)
-		    max_fd =3D d[i].s;
-		if (max_fd >=3D FD_SETSIZE)
-		    krb5_errx(kcm_context, 1, "fd too large");
-		FD_SET(d[i].s, &fds);
-	    } else if (min_free < 0 || i < min_free)
-		min_free =3D i;
-	}
-	if (min_free =3D=3D -1) {
-	    struct descr *tmp;
-	    tmp =3D realloc(d, (ndescr + 4) * sizeof(*d));
-	    if(tmp =3D=3D NULL)
-		krb5_warnx(kcm_context, "No memory");
-	    else {
-		d =3D tmp;
-		reinit_descrs (d, ndescr);
-		memset(d + ndescr, 0, 4 * sizeof(*d));
-		for(i =3D ndescr; i < ndescr + 4; i++)
-		    init_descr (&d[i]);
-		min_free =3D ndescr;
-		ndescr +=3D 4;
-	    }
-	}
-
-	tmout.tv_sec =3D STREAM_TIMEOUT;
-	tmout.tv_usec =3D 0;
-	switch (select(max_fd + 1, &fds, 0, 0, &tmout)){
-	case 0:
-	    kcm_run_events(kcm_context, time(NULL));
-	    break;
-	case -1:
-	    if (errno !=3D EINTR)
-		krb5_warn(kcm_context, errno, "select");
-	    break;
-	default:
-	    for(i =3D 0; i < ndescr; i++) {
-		if(d[i].s >=3D 0 && FD_ISSET(d[i].s, &fds)) {
-		    if (d[i].type =3D=3D SOCK_STREAM)
-			handle_stream(d, i, min_free);
-		}
-	    }
-	    kcm_run_events(kcm_context, time(NULL));
-	    break;
-	}
-    }
-    if (d->path !=3D NULL)
-	unlink(d->path);
-    free(d);
-}
-
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/events.c
--- a/head/crypto/heimdal/kcm/events.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/events.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: events.c 15294 2005-05-30 01:43:23Z lukeh $");
+RCSID("$Id$");
=20
 /* thread-safe in case we multi-thread later */
 static HEIMDAL_MUTEX events_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
@@ -161,7 +161,7 @@
     (*e)->fire_count =3D 0;
     (*e)->expire_time =3D 0;
     (*e)->backoff_time =3D 0;
-    kcm_release_ccache(context, &(*e)->ccache);
+    kcm_release_ccache(context, (*e)->ccache);
     (*e)->next =3D NULL;
     free(*e);
=20
@@ -206,7 +206,7 @@
     krb5_error_code ret =3D 0;
     kcm_ccache ccache =3D event->ccache;
=20
-    event->fire_time =3D 0;=20
+    event->fire_time =3D 0;
     event->expire_time =3D 0;
     event->backoff_time =3D KCM_EVENT_DEFAULT_BACKOFF_TIME;
=20
@@ -353,7 +353,7 @@
     event->fire_count++;
=20
     if (ret) {
-	/* Reschedule failed event for another time */=20
+	/* Reschedule failed event for another time */
 	event->fire_time +=3D event->backoff_time;
 	if (event->backoff_time < KCM_EVENT_MAX_BACKOFF_TIME)
 	    event->backoff_time *=3D 2;
@@ -394,8 +394,7 @@
 }
=20
 krb5_error_code
-kcm_run_events(krb5_context context,
-	       time_t now)
+kcm_run_events(krb5_context context, time_t now)
 {
     krb5_error_code ret;
     kcm_event **e;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/glue.c
--- a/head/crypto/heimdal/kcm/glue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/glue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: glue.c 14566 2005-02-06 01:22:49Z lukeh $");
+RCSID("$Id$");
=20
 /*
  * Server-side loopback glue for credentials cache operations; this
@@ -247,6 +247,7 @@
 }
=20
 static const krb5_cc_ops krb5_kcmss_ops =3D {
+    KRB5_CC_OPS_VERSION,
     "KCM",
     kcmss_get_name,
     kcmss_resolve,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/headers.h
--- a/head/crypto/heimdal/kcm/headers.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/headers.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,9 +33,9 @@
 #ifndef __HEADERS_H__
 #define __HEADERS_H__
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-#endif
+
 #include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -70,20 +70,21 @@
 #ifdef HAVE_LIBUTIL_H
 #include <libutil.h>
 #endif
-#ifdef HAVE_GETPEERUCRED
-#include <ucred.h>
-#endif
-#ifdef HAVE_DOOR_CREATE
-#include <door.h>
-#include <alloca.h>
-#endif
+#include <ctype.h>
 #include <err.h>
 #include <roken.h>
 #include <getarg.h>
 #include <base64.h>
 #include <parse_units.h>
+#include <parse_time.h>
+
+
 #include <krb5.h>
-#include <krb5_locl.h>
+#include <heim_threads.h>
+
+#include <heim-ipc.h>
+
+#include "crypto-headers.h"
=20
 #endif /* __HEADERS_H__ */
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/kcm.8
--- a/head/crypto/heimdal/kcm/kcm.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/kcm.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,96 +1,95 @@
-.\" Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
 .\"
-.\" $Id: kcm.8 15497 2005-06-20 13:32:44Z lha $
+.\" $Id$
 .\"
 .Dd May 29, 2005
 .Dt KCM 8
 .Os Heimdal
 .Sh NAME
 .Nm kcm
-.Nd
-is a process based credential cache for Kerberos tickets.
+.Nd process-based credential cache for Kerberos tickets.
 .Sh SYNOPSIS
 .Nm
-.Op Fl -cache-name=3D Ns Ar cachename
+.Op Fl Fl cache-name=3D Ns Ar cachename
 .Oo Fl c Ar file \*(Ba Xo
-.Fl -config-file=3D Ns Ar file
+.Fl Fl config-file=3D Ns Ar file
 .Xc
 .Oc
 .Oo Fl g Ar group \*(Ba Xo
-.Fl -group=3D Ns Ar group
+.Fl Fl group=3D Ns Ar group
 .Xc
 .Oc
-.Op Fl -max-request=3D Ns Ar size
-.Op Fl -disallow-getting-krbtgt
-.Op Fl -detach
-.Op Fl h | Fl -help
+.Op Fl Fl max-request=3D Ns Ar size
+.Op Fl Fl disallow-getting-krbtgt
+.Op Fl Fl detach
+.Op Fl h | Fl Fl help
 .Oo Fl k Ar principal \*(Ba Xo
-.Fl -system-principal=3D Ns Ar principal
+.Fl Fl system-principal=3D Ns Ar principal
 .Xc
 .Oc
 .Oo Fl l Ar time \*(Ba Xo
-.Fl -lifetime=3D Ns Ar time
+.Fl Fl lifetime=3D Ns Ar time
 .Xc
 .Oc
 .Oo Fl m Ar mode \*(Ba Xo
-.Fl -mode=3D Ns Ar mode
+.Fl Fl mode=3D Ns Ar mode
 .Xc
 .Oc
-.Op Fl n | Fl -no-name-constraints
+.Op Fl n | Fl Fl no-name-constraints
 .Oo Fl r Ar time \*(Ba Xo
-.Fl -renewable-life=3D Ns Ar time
+.Fl Fl renewable-life=3D Ns Ar time
 .Xc
 .Oc
 .Oo Fl s Ar path \*(Ba Xo
-.Fl -socket-path=3D Ns Ar path
+.Fl Fl socket-path=3D Ns Ar path
 .Xc
 .Oc
 .Oo Xo
-.Fl -door-path=3D Ns Ar path
+.Fl Fl door-path=3D Ns Ar path
 .Xc
 .Oc
 .Oo Fl S Ar principal \*(Ba Xo
-.Fl -server=3D Ns Ar principal
+.Fl Fl server=3D Ns Ar principal
 .Xc
 .Oc
 .Oo Fl t Ar keytab \*(Ba Xo
-.Fl -keytab=3D Ns Ar keytab
+.Fl Fl keytab=3D Ns Ar keytab
 .Xc
 .Oc
 .Oo Fl u Ar user \*(Ba Xo
-.Fl -user=3D Ns Ar user
+.Fl Fl user=3D Ns Ar user
 .Xc
 .Oc
-.Op Fl v | Fl -version
+.Op Fl v | Fl Fl version
 .Sh DESCRIPTION
 .Nm
 is a process based credential cache.
@@ -123,95 +122,46 @@
 daemon can also keep a SYSTEM credential that server processes can
 use to access services.  One example of usage might be an nss_ldap
 module that quickly needs to get credentials and doesn't want to renew
-the ticket itself.=20
+the ticket itself.
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl -cache-name=3D Ns Ar cachename
-.Xc
+.It Fl Fl cache-name=3D Ns Ar cachename
 system cache name
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 location of config file
-.It Xo
-.Fl g Ar group ,
-.Fl -group=3D Ns Ar group
-.Xc
+.It Fl g Ar group , Fl Fl group=3D Ns Ar group
 system cache group
-.It Xo
-.Fl -max-request=3D Ns Ar size
-.Xc
+.It Fl Fl max-request=3D Ns Ar size
 max size for a kcm-request
-.It Xo
-.Fl -disallow-getting-krbtgt
-.Xc
+.It Fl Fl disallow-getting-krbtgt
 disallow extracting any krbtgt from the
 .Nm kcm
 daemon.
-.It Xo
-.Fl -detach
-.Xc
+.It Fl Fl detach
 detach from console
-.It Xo
-.Fl h ,
-.Fl -help
-.Xc
-.It Xo
-.Fl k Ar principal ,
-.Fl -system-principal=3D Ns Ar principal
-.Xc
+.It Fl h , Fl Fl help
+.It Fl k Ar principal , Fl Fl system-principal=3D Ns Ar principal
 system principal name
-.It Xo
-.Fl l Ar time ,
-.Fl -lifetime=3D Ns Ar time
-.Xc
+.It Fl l Ar time , Fl Fl lifetime=3D Ns Ar time
 lifetime of system tickets
-.It Xo
-.Fl m Ar mode ,
-.Fl -mode=3D Ns Ar mode
-.Xc
+.It Fl m Ar mode , Fl Fl mode=3D Ns Ar mode
 octal mode of system cache
-.It Xo
-.Fl n ,
-.Fl -no-name-constraints
-.Xc
+.It Fl n , Fl Fl no-name-constraints
 disable credentials cache name constraints
-.It Xo
-.Fl r Ar time ,
-.Fl -renewable-life=3D Ns Ar time
-.Xc
+.It Fl r Ar time , Fl Fl renewable-life=3D Ns Ar time
 renewable lifetime of system tickets
-.It Xo
-.Fl s Ar path ,
-.Fl -socket-path=3D Ns Ar path
-.Xc
+.It Fl s Ar path , Fl Fl socket-path=3D Ns Ar path
 path to kcm domain socket
-.It Xo
-.Fl -door-path=3D Ns Ar path
-.Xc
+.It Fl Fl door-path=3D Ns Ar path
 path to kcm door socket
-.It Xo
-.Fl S Ar principal ,
-.Fl -server=3D Ns Ar principal
-.Xc
+.It Fl S Ar principal , Fl Fl server=3D Ns Ar principal
 server to get system ticket for
-.It Xo
-.Fl t Ar keytab ,
-.Fl -keytab=3D Ns Ar keytab
-.Xc
+.It Fl t Ar keytab , Fl Fl keytab=3D Ns Ar keytab
 system keytab name
-.It Xo
-.Fl u Ar user ,
-.Fl -user=3D Ns Ar user
-.Xc
+.It Fl u Ar user , Fl Fl user=3D Ns Ar user
 system cache owner
-.It Xo
-.Fl v ,
-.Fl -version
-.Xc
+.It Fl v , Fl Fl version
 .El
 .\".Sh ENVIRONMENT
 .\".Sh FILES
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/kcm_locl.h
--- a/head/crypto/heimdal/kcm/kcm_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/kcm_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -30,8 +32,8 @@
  * SUCH DAMAGE.
  */
=20
-/*=20
- * $Id: kcm_locl.h 20470 2007-04-20 10:41:11Z lha $=20
+/*
+ * $Id$
  */
=20
 #ifndef __KCM_LOCL_H__
@@ -65,30 +67,36 @@
 struct kcm_ccache_data;
 struct kcm_creds;
=20
-typedef struct kcm_cursor {
-    pid_t pid;
-    uint32_t key;
-    struct kcm_creds *credp;		/* pointer to next credential */=20
-    struct kcm_cursor *next;
-} kcm_cursor;
+struct kcm_default_cache {
+    uid_t uid;
+    pid_t session; /* really au_asid_t */
+    char *name;
+    struct kcm_default_cache *next;
+};
+
+extern struct kcm_default_cache *default_caches;
+
+struct kcm_creds {
+    kcmuuid_t uuid;
+    krb5_creds cred;
+    struct kcm_creds *next;
+};
=20
 typedef struct kcm_ccache_data {
     char *name;
+    kcmuuid_t uuid;
     unsigned refcnt;
     uint16_t flags;
     uint16_t mode;
     uid_t uid;
     gid_t gid;
+    pid_t session; /* really au_asid_t */
     krb5_principal client; /* primary client principal */
     krb5_principal server; /* primary server principal (TGS if NULL) */
-    struct kcm_creds {
-	krb5_creds cred; /* XXX would be useful for have ACLs on creds */
-	struct kcm_creds *next;
-    } *creds;
-    uint32_t n_cursor;
-    kcm_cursor *cursors;
+    struct kcm_creds *creds;
     krb5_deltat tkt_life;
     krb5_deltat renew_life;
+    int32_t kdc_offset;
     union {
 	krb5_keytab keytab;
 	krb5_keyblock keyblock;
@@ -138,6 +146,7 @@
     pid_t pid;
     uid_t uid;
     gid_t gid;
+    pid_t session;
 } kcm_client;
=20
 #define CLIENT_IS_ROOT(client) ((client)->uid =3D=3D 0)
@@ -160,14 +169,20 @@
 extern size_t max_request;
 extern sig_atomic_t exit_flag;
 extern int name_constraints;
+#ifdef SUPPORT_DETACH
 extern int detach_from_console;
+#endif
+extern int launchd_flag;
 extern int disallow_getting_krbtgt;
=20
 #if 0
 extern const krb5_cc_ops krb5_kcmss_ops;
 #endif
=20
-#include <kcm_protos.h>
+void	kcm_service(void *, const heim_idata *, const heim_icred,
+		    heim_ipc_complete, heim_sipc_call);
+
+#include <kcm-protos.h>
=20
 #endif /* __KCM_LOCL_H__ */
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/log.c
--- a/head/crypto/heimdal/kcm/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: log.c 14566 2005-02-06 01:22:49Z lukeh $");
+RCSID("$Id$");
=20
 static krb5_log_facility *logf;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/main.c
--- a/head/crypto/heimdal/kcm/main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,46 @@
 /*
- * Copyright (c) 1997-2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: main.c 15298 2005-05-30 10:58:14Z lha $");
+RCSID("$Id$");
=20
 sig_atomic_t exit_flag =3D 0;
=20
 krb5_context kcm_context =3D NULL;
=20
+const char *service_name =3D "org.h5l.kcm";
+
 static RETSIGTYPE
 sigterm(int sig)
 {
@@ -70,7 +72,7 @@
     }
=20
     kcm_configure(argc, argv);
-   =20
+
 #ifdef HAVE_SIGACTION
     {
 	struct sigaction sa;
@@ -98,10 +100,22 @@
     signal(SIGUSR2, sigusr2);
     signal(SIGPIPE, SIG_IGN);
 #endif
+#ifdef SUPPORT_DETACH
     if (detach_from_console)
 	daemon(0, 0);
+#endif
     pidfile(NULL);
-    kcm_loop();
+
+    if (launchd_flag) {
+	heim_sipc mach;
+	heim_sipc_launchd_mach_init(service_name, kcm_service, NULL, &mach);
+    } else {
+	heim_sipc un;
+	heim_sipc_service_unix(service_name, kcm_service, NULL, &un);
+    }
+
+    heim_ipc_main();
+
     krb5_free_context(kcm_context);
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/protocol.c
--- a/head/crypto/heimdal/kcm/protocol.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/protocol.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -31,8 +33,22 @@
  */
=20
 #include "kcm_locl.h"
+#include <heimntlm.h>
=20
-RCSID("$Id: protocol.c 22112 2007-12-03 19:34:33Z lha $");
+static void
+kcm_drop_default_cache(krb5_context context, kcm_client *client, char *nam=
e);
+
+
+int
+kcm_is_same_session(kcm_client *client, uid_t uid, pid_t session)
+{
+#if 0 /* XXX pppd is running in diffrent session the user */
+    if (session !=3D -1)
+	return (client->session =3D=3D session);
+    else
+#endif
+	return  (client->uid =3D=3D uid);
+}
=20
 static krb5_error_code
 kcm_op_noop(krb5_context context,
@@ -43,7 +59,7 @@
 {
     KCM_LOG_REQUEST(context, client, opcode);
=20
-    return 0;=09
+    return 0;
 }
=20
 /*
@@ -80,19 +96,19 @@
=20
     ret =3D krb5_store_stringz(response, ccache->name);
     if (ret) {
-	kcm_release_ccache(context, &ccache);
+	kcm_release_ccache(context, ccache);
 	free(name);
 	return ret;
     }
=20
     free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
     return 0;
 }
=20
 /*
  * Request:
- *=09
+ *
  * Response:
  *	NameZ
  */
@@ -123,9 +139,9 @@
  * Request:
  *	NameZ
  *	Principal
- *=09
+ *
  * Response:
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_initialize(krb5_context context,
@@ -181,7 +197,7 @@
     ret =3D kcm_enqueue_event_relative(context, &event);
 #endif
=20
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return ret;
 }
@@ -189,9 +205,9 @@
 /*
  * Request:
  *	NameZ
- *=09
+ *
  * Response:
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_destroy(krb5_context context,
@@ -210,6 +226,8 @@
     KCM_LOG_REQUEST_NAME(context, client, opcode, name);
=20
     ret =3D kcm_ccache_destroy_client(context, client, name);
+    if (ret =3D=3D 0)
+	kcm_drop_default_cache(context, client, name);
=20
     free(name);
=20
@@ -220,9 +238,9 @@
  * Request:
  *	NameZ
  *	Creds
- *=09
+ *
  * Response:
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_store(krb5_context context,
@@ -260,14 +278,14 @@
     if (ret) {
 	free(name);
 	krb5_free_cred_contents(context, &creds);
-	kcm_release_ccache(context, &ccache);
+	kcm_release_ccache(context, ccache);
 	return ret;
     }
=20
     kcm_ccache_enqueue_default(context, ccache, &creds);
=20
     free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return 0;
 }
@@ -280,7 +298,7 @@
  *
  * Response:
  *	Creds
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_retrieve(krb5_context context,
@@ -334,7 +352,8 @@
=20
     ret =3D kcm_ccache_retrieve_cred(context, ccache, flags,
 				   &mcreds, &credp);
-    if (ret && ((flags & KRB5_GC_CACHED) =3D=3D 0)) {
+    if (ret && ((flags & KRB5_GC_CACHED) =3D=3D 0) &&
+	!krb5_is_config_principal(context, mcreds.server)) {
 	krb5_ccache_data ccdata;
=20
 	/* try and acquire */
@@ -357,7 +376,7 @@
=20
     free(name);
     krb5_free_cred_contents(context, &mcreds);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     if (free_creds)
 	krb5_free_cred_contents(context, credp);
@@ -402,7 +421,7 @@
 	ret =3D krb5_store_principal(response, ccache->client);
=20
     free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return 0;
 }
@@ -412,19 +431,19 @@
  *	NameZ
  *
  * Response:
- *	Cursor
- *=09
+ *	UUIDs
+ *
  */
 static krb5_error_code
-kcm_op_get_first(krb5_context context,
-		 kcm_client *client,
-		 kcm_operation opcode,
-		 krb5_storage *request,
-		 krb5_storage *response)
+kcm_op_get_cred_uuid_list(krb5_context context,
+			  kcm_client *client,
+			  kcm_operation opcode,
+			  krb5_storage *request,
+			  krb5_storage *response)
 {
+    struct kcm_creds *creds;
     krb5_error_code ret;
     kcm_ccache ccache;
-    uint32_t cursor;
     char *name;
=20
     ret =3D krb5_ret_stringz(request, &name);
@@ -435,22 +454,20 @@
=20
     ret =3D kcm_ccache_resolve_client(context, client, opcode,
 				    name, &ccache);
-    if (ret) {
-	free(name);
+    free(name);
+    if (ret)
 	return ret;
+
+    for (creds =3D ccache->creds ; creds ; creds =3D creds->next) {
+	ssize_t sret;
+	sret =3D krb5_storage_write(response, &creds->uuid, sizeof(creds->uuid));
+	if (sret !=3D sizeof(creds->uuid)) {
+	    ret =3D ENOMEM;
+	    break;
+	}
     }
=20
-    ret =3D kcm_cursor_new(context, client->pid, ccache, &cursor);
-    if (ret) {
-	kcm_release_ccache(context, &ccache);
-	free(name);
-	return ret;
-    }
-
-    ret =3D krb5_store_int32(response, cursor);
-
-    free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return ret;
 }
@@ -464,17 +481,18 @@
  *	Creds
  */
 static krb5_error_code
-kcm_op_get_next(krb5_context context,
-		kcm_client *client,
-		kcm_operation opcode,
-		krb5_storage *request,
-		krb5_storage *response)
+kcm_op_get_cred_by_uuid(krb5_context context,
+			kcm_client *client,
+			kcm_operation opcode,
+			krb5_storage *request,
+			krb5_storage *response)
 {
     krb5_error_code ret;
     kcm_ccache ccache;
     char *name;
-    uint32_t cursor;
-    kcm_cursor *c;
+    struct kcm_creds *c;
+    kcmuuid_t uuid;
+    ssize_t sret;
=20
     ret =3D krb5_ret_stringz(request, &name);
     if (ret)
@@ -482,84 +500,30 @@
=20
     KCM_LOG_REQUEST_NAME(context, client, opcode, name);
=20
-    ret =3D krb5_ret_uint32(request, &cursor);
-    if (ret) {
-	free(name);
+    ret =3D kcm_ccache_resolve_client(context, client, opcode,
+				    name, &ccache);
+    free(name);
+    if (ret)
 	return ret;
+
+    sret =3D krb5_storage_read(request, &uuid, sizeof(uuid));
+    if (sret !=3D sizeof(uuid)) {
+	kcm_release_ccache(context, ccache);
+	krb5_clear_error_message(context);
+	return KRB5_CC_IO;
     }
=20
-    ret =3D kcm_ccache_resolve_client(context, client, opcode,
-				    name, &ccache);
-    if (ret) {
-	free(name);
-	return ret;
-    }
-
-    ret =3D kcm_cursor_find(context, client->pid, ccache, cursor, &c);
-    if (ret) {
-	kcm_release_ccache(context, &ccache);
-	free(name);
-	return ret;
+    c =3D kcm_ccache_find_cred_uuid(context, ccache, uuid);
+    if (c =3D=3D NULL) {
+	kcm_release_ccache(context, ccache);
+	return KRB5_CC_END;
     }
=20
     HEIMDAL_MUTEX_lock(&ccache->mutex);
-    if (c->credp =3D=3D NULL) {
-	ret =3D KRB5_CC_END;
-    } else {
-	ret =3D krb5_store_creds(response, &c->credp->cred);
-	c->credp =3D c->credp->next;
-    }
+    ret =3D krb5_store_creds(response, &c->cred);
     HEIMDAL_MUTEX_unlock(&ccache->mutex);
=20
-    free(name);
-    kcm_release_ccache(context, &ccache);
-
-    return ret;
-}
-
-/*
- * Request:
- *	NameZ
- *	Cursor
- *
- * Response:
- *=09
- */
-static krb5_error_code
-kcm_op_end_get(krb5_context context,
-	       kcm_client *client,
-	       kcm_operation opcode,
-	       krb5_storage *request,
-	       krb5_storage *response)
-{
-    krb5_error_code ret;
-    kcm_ccache ccache;
-    uint32_t cursor;
-    char *name;
-
-    ret =3D krb5_ret_stringz(request, &name);
-    if (ret)
-	return ret;
-
-    KCM_LOG_REQUEST_NAME(context, client, opcode, name);
-
-    ret =3D krb5_ret_uint32(request, &cursor);
-    if (ret) {
-	free(name);
-	return ret;
-    }
-
-    ret =3D kcm_ccache_resolve_client(context, client, opcode,
-				    name, &ccache);
-    if (ret) {
-	free(name);
-	return ret;
-    }
-
-    ret =3D kcm_cursor_delete(context, client->pid, ccache, cursor);
-
-    free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return ret;
 }
@@ -571,7 +535,7 @@
  *	MatchCreds
  *
  * Response:
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_remove_cred(krb5_context context,
@@ -618,7 +582,7 @@
=20
     free(name);
     krb5_free_cred_contents(context, &mcreds);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return ret;
 }
@@ -629,7 +593,7 @@
  *	Flags
  *
  * Response:
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_set_flags(krb5_context context,
@@ -664,7 +628,7 @@
=20
     /* we don't really support any flags yet */
     free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return 0;
 }
@@ -676,7 +640,7 @@
  *	GID
  *
  * Response:
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_chown(krb5_context context,
@@ -719,7 +683,7 @@
     ret =3D kcm_chown(context, client, ccache, uid, gid);
=20
     free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return ret;
 }
@@ -730,7 +694,7 @@
  *	Mode
  *
  * Response:
- *=09
+ *
  */
 static krb5_error_code
 kcm_op_chmod(krb5_context context,
@@ -766,7 +730,7 @@
     ret =3D kcm_chmod(context, client, ccache, mode);
=20
     free(name);
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return ret;
 }
@@ -863,7 +827,7 @@
 	krb5_free_keyblock(context, &key);
     }
=20
-    kcm_release_ccache(context, &ccache);
+    kcm_release_ccache(context, ccache);
=20
     return ret;
 }
@@ -926,7 +890,7 @@
 	free(name);
 	return ret;
     }
-=20
+
     HEIMDAL_MUTEX_lock(&ccache->mutex);
=20
     /* Fake up an internal ccache */
@@ -942,14 +906,796 @@
=20
     HEIMDAL_MUTEX_unlock(&ccache->mutex);
=20
+    krb5_free_principal(context, server);
+
     if (ret =3D=3D 0)
 	krb5_free_cred_contents(context, out);
=20
+    kcm_release_ccache(context, ccache);
     free(name);
=20
     return ret;
 }
=20
+/*
+ * Request:
+ *	OldNameZ
+ *	NewNameZ
+ *
+ * Repsonse:
+ *
+ */
+static krb5_error_code
+kcm_op_move_cache(krb5_context context,
+		  kcm_client *client,
+		  kcm_operation opcode,
+		  krb5_storage *request,
+		  krb5_storage *response)
+{
+    krb5_error_code ret;
+    kcm_ccache oldid, newid;
+    char *oldname, *newname;
+
+    ret =3D krb5_ret_stringz(request, &oldname);
+    if (ret)
+	return ret;
+
+    KCM_LOG_REQUEST_NAME(context, client, opcode, oldname);
+
+    ret =3D krb5_ret_stringz(request, &newname);
+    if (ret) {
+	free(oldname);
+	return ret;
+    }
+
+    /* move to ourself is simple, done! */
+    if (strcmp(oldname, newname) =3D=3D 0) {
+	free(oldname);
+	free(newname);
+	return 0;
+    }
+
+    ret =3D kcm_ccache_resolve_client(context, client, opcode, oldname, &o=
ldid);
+    if (ret) {
+	free(oldname);
+	free(newname);
+	return ret;
+    }
+
+    /* Check if new credential cache exists, if not create one. */
+    ret =3D kcm_ccache_resolve_client(context, client, opcode, newname, &n=
ewid);
+    if (ret =3D=3D KRB5_FCC_NOFILE)
+	ret =3D kcm_ccache_new_client(context, client, newname, &newid);
+    free(newname);
+
+    if (ret) {
+	free(oldname);
+	kcm_release_ccache(context, oldid);
+	return ret;
+    }
+
+    HEIMDAL_MUTEX_lock(&oldid->mutex);
+    HEIMDAL_MUTEX_lock(&newid->mutex);
+
+    /* move content */
+    {
+	kcm_ccache_data tmp;
+
+#define MOVE(n,o,f) { tmp.f =3D n->f ; n->f =3D o->f; o->f =3D tmp.f; }
+
+	MOVE(newid, oldid, flags);
+	MOVE(newid, oldid, client);
+	MOVE(newid, oldid, server);
+	MOVE(newid, oldid, creds);
+	MOVE(newid, oldid, tkt_life);
+	MOVE(newid, oldid, renew_life);
+	MOVE(newid, oldid, key);
+	MOVE(newid, oldid, kdc_offset);
+#undef MOVE
+    }
+
+    HEIMDAL_MUTEX_unlock(&oldid->mutex);
+    HEIMDAL_MUTEX_unlock(&newid->mutex);
+
+    kcm_release_ccache(context, oldid);
+    kcm_release_ccache(context, newid);
+
+    ret =3D kcm_ccache_destroy_client(context, client, oldname);
+    if (ret =3D=3D 0)
+	kcm_drop_default_cache(context, client, oldname);
+
+    free(oldname);
+
+    return ret;
+}
+
+static krb5_error_code
+kcm_op_get_cache_uuid_list(krb5_context context,
+			   kcm_client *client,
+			   kcm_operation opcode,
+			   krb5_storage *request,
+			   krb5_storage *response)
+{
+    KCM_LOG_REQUEST(context, client, opcode);
+
+    return kcm_ccache_get_uuids(context, client, opcode, response);
+}
+
+static krb5_error_code
+kcm_op_get_cache_by_uuid(krb5_context context,
+			 kcm_client *client,
+			 kcm_operation opcode,
+			 krb5_storage *request,
+			 krb5_storage *response)
+{
+    krb5_error_code ret;
+    kcmuuid_t uuid;
+    ssize_t sret;
+    kcm_ccache cache;
+
+    KCM_LOG_REQUEST(context, client, opcode);
+
+    sret =3D krb5_storage_read(request, &uuid, sizeof(uuid));
+    if (sret !=3D sizeof(uuid)) {
+	krb5_clear_error_message(context);
+	return KRB5_CC_IO;
+    }
+
+    ret =3D kcm_ccache_resolve_by_uuid(context, uuid, &cache);
+    if (ret)
+	return ret;
+
+    ret =3D kcm_access(context, client, opcode, cache);
+    if (ret)
+	ret =3D KRB5_FCC_NOFILE;
+
+    if (ret =3D=3D 0)
+	ret =3D krb5_store_stringz(response, cache->name);
+
+    kcm_release_ccache(context, cache);
+
+    return ret;
+}
+
+struct kcm_default_cache *default_caches;
+
+static krb5_error_code
+kcm_op_get_default_cache(krb5_context context,
+			 kcm_client *client,
+			 kcm_operation opcode,
+			 krb5_storage *request,
+			 krb5_storage *response)
+{
+    struct kcm_default_cache *c;
+    krb5_error_code ret;
+    const char *name =3D NULL;
+    char *n =3D NULL;
+
+    KCM_LOG_REQUEST(context, client, opcode);
+
+    for (c =3D default_caches; c !=3D NULL; c =3D c->next) {
+	if (kcm_is_same_session(client, c->uid, c->session)) {
+	    name =3D c->name;
+	    break;
+	}
+    }
+    if (name =3D=3D NULL)
+	name =3D n =3D kcm_ccache_first_name(client);
+
+    if (name =3D=3D NULL) {
+	asprintf(&n, "%d", (int)client->uid);
+	name =3D n;
+    }
+    if (name =3D=3D NULL)
+	return ENOMEM;
+    ret =3D krb5_store_stringz(response, name);
+    if (n)
+	free(n);
+    return ret;
+}
+
+static void
+kcm_drop_default_cache(krb5_context context, kcm_client *client, char *nam=
e)
+{
+    struct kcm_default_cache **c;
+
+    for (c =3D &default_caches; *c !=3D NULL; c =3D &(*c)->next) {
+	if (!kcm_is_same_session(client, (*c)->uid, (*c)->session))
+	    continue;
+	if (strcmp((*c)->name, name) =3D=3D 0) {
+	    struct kcm_default_cache *h =3D *c;
+	    *c =3D (*c)->next;
+	    free(h->name);
+	    free(h);
+	    break;
+	}
+    }
+}
+
+static krb5_error_code
+kcm_op_set_default_cache(krb5_context context,
+			 kcm_client *client,
+			 kcm_operation opcode,
+			 krb5_storage *request,
+			 krb5_storage *response)
+{
+    struct kcm_default_cache *c;
+    krb5_error_code ret;
+    char *name;
+
+    ret =3D krb5_ret_stringz(request, &name);
+    if (ret)
+	return ret;
+
+    KCM_LOG_REQUEST_NAME(context, client, opcode, name);
+
+    for (c =3D default_caches; c !=3D NULL; c =3D c->next) {
+	if (kcm_is_same_session(client, c->uid, c->session))
+	    break;
+    }
+    if (c =3D=3D NULL) {
+	c =3D malloc(sizeof(*c));
+	if (c =3D=3D NULL)
+	    return ENOMEM;
+	c->session =3D client->session;
+	c->uid =3D client->uid;
+	c->name =3D strdup(name);
+
+	c->next =3D default_caches;
+	default_caches =3D c;
+    } else {
+	free(c->name);
+	c->name =3D strdup(name);
+    }
+
+    return 0;
+}
+
+static krb5_error_code
+kcm_op_get_kdc_offset(krb5_context context,
+		      kcm_client *client,
+		      kcm_operation opcode,
+		      krb5_storage *request,
+		      krb5_storage *response)
+{
+    krb5_error_code ret;
+    kcm_ccache ccache;
+    char *name;
+
+    ret =3D krb5_ret_stringz(request, &name);
+    if (ret)
+	return ret;
+
+    KCM_LOG_REQUEST_NAME(context, client, opcode, name);
+
+    ret =3D kcm_ccache_resolve_client(context, client, opcode, name, &ccac=
he);
+    free(name);
+    if (ret)
+	return ret;
+
+    HEIMDAL_MUTEX_lock(&ccache->mutex);
+    ret =3D krb5_store_int32(response, ccache->kdc_offset);
+    HEIMDAL_MUTEX_unlock(&ccache->mutex);
+
+    kcm_release_ccache(context, ccache);
+
+    return ret;
+}
+
+static krb5_error_code
+kcm_op_set_kdc_offset(krb5_context context,
+		      kcm_client *client,
+		      kcm_operation opcode,
+		      krb5_storage *request,
+		      krb5_storage *response)
+{
+    krb5_error_code ret;
+    kcm_ccache ccache;
+    int32_t offset;
+    char *name;
+
+    ret =3D krb5_ret_stringz(request, &name);
+    if (ret)
+	return ret;
+
+    KCM_LOG_REQUEST_NAME(context, client, opcode, name);
+
+    ret =3D krb5_ret_int32(request, &offset);
+    if (ret) {
+	free(name);
+	return ret;
+    }
+
+    ret =3D kcm_ccache_resolve_client(context, client, opcode, name, &ccac=
he);
+    free(name);
+    if (ret)
+	return ret;
+
+    HEIMDAL_MUTEX_lock(&ccache->mutex);
+    ccache->kdc_offset =3D offset;
+    HEIMDAL_MUTEX_unlock(&ccache->mutex);
+
+    kcm_release_ccache(context, ccache);
+
+    return ret;
+}
+
+struct kcm_ntlm_cred {
+    kcmuuid_t uuid;
+    char *user;
+    char *domain;
+    krb5_data nthash;
+    uid_t uid;
+    pid_t session;
+    struct kcm_ntlm_cred *next;
+};
+
+static struct kcm_ntlm_cred *ntlm_head;
+
+static void
+free_cred(struct kcm_ntlm_cred *cred)
+{
+    free(cred->user);
+    free(cred->domain);
+    krb5_data_free(&cred->nthash);
+    free(cred);
+}
+
+
+/*
+ * name
+ * domain
+ * ntlm hash
+ *
+ * Reply:
+ *   uuid
+ */
+
+static struct kcm_ntlm_cred *
+find_ntlm_cred(const char *user, const char *domain, kcm_client *client)
+{
+    struct kcm_ntlm_cred *c;
+
+    for (c =3D ntlm_head; c !=3D NULL; c =3D c->next)
+	if ((user[0] =3D=3D '\0' || strcmp(user, c->user) =3D=3D 0) &&
+	    (domain =3D=3D NULL || strcmp(domain, c->domain) =3D=3D 0) &&
+	    kcm_is_same_session(client, c->uid, c->session))
+	    return c;
+
+    return NULL;
+}
+
+static krb5_error_code
+kcm_op_add_ntlm_cred(krb5_context context,
+		     kcm_client *client,
+		     kcm_operation opcode,
+		     krb5_storage *request,
+		     krb5_storage *response)
+{
+    struct kcm_ntlm_cred *cred, *c;
+    krb5_error_code ret;
+
+    cred =3D calloc(1, sizeof(*cred));
+    if (cred =3D=3D NULL)
+	return ENOMEM;
+
+    RAND_bytes(cred->uuid, sizeof(cred->uuid));
+
+    ret =3D krb5_ret_stringz(request, &cred->user);
+    if (ret)
+	goto error;
+
+    ret =3D krb5_ret_stringz(request, &cred->domain);
+    if (ret)
+	goto error;
+
+    ret =3D krb5_ret_data(request, &cred->nthash);
+    if (ret)
+	goto error;
+
+    /* search for dups */
+    c =3D find_ntlm_cred(cred->user, cred->domain, client);
+    if (c) {
+	krb5_data hash =3D c->nthash;
+	c->nthash =3D cred->nthash;
+	cred->nthash =3D hash;
+	free_cred(cred);
+	cred =3D c;
+    } else {
+	cred->next =3D ntlm_head;
+	ntlm_head =3D cred;
+    }
+
+    cred->uid =3D client->uid;
+    cred->session =3D client->session;
+
+    /* write response */
+    (void)krb5_storage_write(response, &cred->uuid, sizeof(cred->uuid));
+
+    return 0;
+
+ error:
+    free_cred(cred);
+
+    return ret;
+}
+
+/*
+ * { "HAVE_NTLM_CRED",		NULL },
+ *
+ * input:
+ *  name
+ *  domain
+ */
+
+static krb5_error_code
+kcm_op_have_ntlm_cred(krb5_context context,
+		     kcm_client *client,
+		     kcm_operation opcode,
+		     krb5_storage *request,
+		     krb5_storage *response)
+{
+    struct kcm_ntlm_cred *c;
+    char *user =3D NULL, *domain =3D NULL;
+    krb5_error_code ret;
+
+    ret =3D krb5_ret_stringz(request, &user);
+    if (ret)
+	goto error;
+
+    ret =3D krb5_ret_stringz(request, &domain);
+    if (ret)
+	goto error;
+
+    if (domain[0] =3D=3D '\0') {
+	free(domain);
+	domain =3D NULL;
+    }
+
+    c =3D find_ntlm_cred(user, domain, client);
+    if (c =3D=3D NULL)
+	ret =3D ENOENT;
+
+ error:
+    free(user);
+    if (domain)
+	free(domain);
+
+    return ret;
+}
+
+/*
+ * { "DEL_NTLM_CRED",		NULL },
+ *
+ * input:
+ *  name
+ *  domain
+ */
+
+static krb5_error_code
+kcm_op_del_ntlm_cred(krb5_context context,
+		     kcm_client *client,
+		     kcm_operation opcode,
+		     krb5_storage *request,
+		     krb5_storage *response)
+{
+    struct kcm_ntlm_cred **cp, *c;
+    char *user =3D NULL, *domain =3D NULL;
+    krb5_error_code ret;
+
+    ret =3D krb5_ret_stringz(request, &user);
+    if (ret)
+	goto error;
+
+    ret =3D krb5_ret_stringz(request, &domain);
+    if (ret)
+	goto error;
+
+    for (cp =3D &ntlm_head; *cp !=3D NULL; cp =3D &(*cp)->next) {
+	if (strcmp(user, (*cp)->user) =3D=3D 0 && strcmp(domain, (*cp)->domain) =
=3D=3D 0 &&
+	    kcm_is_same_session(client, (*cp)->uid, (*cp)->session))
+	{
+	    c =3D *cp;
+	    *cp =3D c->next;
+
+	    free_cred(c);
+	    break;
+	}
+    }
+
+ error:
+    free(user);
+    free(domain);
+
+    return ret;
+}
+
+/*
+ * { "DO_NTLM_AUTH",		NULL },
+ *
+ * input:
+ *  name:string
+ *  domain:string
+ *  type2:data
+ *
+ * reply:
+ *  type3:data
+ *  flags:int32
+ *  session-key:data
+ */
+
+#define NTLM_FLAG_SESSIONKEY 1
+#define NTLM_FLAG_NTLM2_SESSION 2
+#define NTLM_FLAG_KEYEX 4
+
+static krb5_error_code
+kcm_op_do_ntlm(krb5_context context,
+	       kcm_client *client,
+	       kcm_operation opcode,
+	       krb5_storage *request,
+	       krb5_storage *response)
+{
+    struct kcm_ntlm_cred *c;
+    struct ntlm_type2 type2;
+    struct ntlm_type3 type3;
+    char *user =3D NULL, *domain =3D NULL;
+    struct ntlm_buf ndata, sessionkey;
+    krb5_data data;
+    krb5_error_code ret;
+    uint32_t flags =3D 0;
+
+    memset(&type2, 0, sizeof(type2));
+    memset(&type3, 0, sizeof(type3));
+    sessionkey.data =3D NULL;
+    sessionkey.length =3D 0;
+
+    ret =3D krb5_ret_stringz(request, &user);
+    if (ret)
+	goto error;
+
+    ret =3D krb5_ret_stringz(request, &domain);
+    if (ret)
+	goto error;
+
+    if (domain[0] =3D=3D '\0') {
+	free(domain);
+	domain =3D NULL;
+    }
+
+    c =3D find_ntlm_cred(user, domain, client);
+    if (c =3D=3D NULL) {
+	ret =3D EINVAL;
+	goto error;
+    }
+
+    ret =3D krb5_ret_data(request, &data);
+    if (ret)
+	goto error;
+
+    ndata.data =3D data.data;
+    ndata.length =3D data.length;
+
+    ret =3D heim_ntlm_decode_type2(&ndata, &type2);
+    krb5_data_free(&data);
+    if (ret)
+	goto error;
+
+    if (domain && strcmp(domain, type2.targetname) =3D=3D 0) {
+	ret =3D EINVAL;
+	goto error;
+    }
+
+    type3.username =3D c->user;
+    type3.flags =3D type2.flags;
+    type3.targetname =3D type2.targetname;
+    type3.ws =3D rk_UNCONST("workstation");
+
+    /*
+     * NTLM Version 1 if no targetinfo buffer.
+     */
+
+    if (1 || type2.targetinfo.length =3D=3D 0) {
+	struct ntlm_buf sessionkey;
+
+	if (type2.flags & NTLM_NEG_NTLM2_SESSION) {
+	    unsigned char nonce[8];
+
+	    if (RAND_bytes(nonce, sizeof(nonce)) !=3D 1) {
+		ret =3D EINVAL;
+		goto error;
+	    }
+
+	    ret =3D heim_ntlm_calculate_ntlm2_sess(nonce,
+						 type2.challenge,
+						 c->nthash.data,
+						 &type3.lm,
+						 &type3.ntlm);
+	} else {
+	    ret =3D heim_ntlm_calculate_ntlm1(c->nthash.data,
+					    c->nthash.length,
+					    type2.challenge,
+					    &type3.ntlm);
+
+	}
+	if (ret)
+	    goto error;
+
+	ret =3D heim_ntlm_build_ntlm1_master(c->nthash.data,
+					   c->nthash.length,
+					   &sessionkey,
+					   &type3.sessionkey);
+	if (ret) {
+	    if (type3.lm.data)
+		free(type3.lm.data);
+	    if (type3.ntlm.data)
+		free(type3.ntlm.data);
+	    goto error;
+	}
+
+	free(sessionkey.data);
+	if (ret) {
+	    if (type3.lm.data)
+		free(type3.lm.data);
+	    if (type3.ntlm.data)
+		free(type3.ntlm.data);
+	    goto error;
+	}
+	flags |=3D NTLM_FLAG_SESSIONKEY;
+#if 0
+    } else {
+	struct ntlm_buf sessionkey;
+	unsigned char ntlmv2[16];
+	struct ntlm_targetinfo ti;
+
+	/* verify infotarget */
+
+	ret =3D heim_ntlm_decode_targetinfo(&type2.targetinfo, 1, &ti);
+	if(ret) {
+	    _gss_ntlm_delete_sec_context(minor_status,
+					 context_handle, NULL);
+	    *minor_status =3D ret;
+	    return GSS_S_FAILURE;
+	}
+
+	if (ti.domainname && strcmp(ti.domainname, name->domain) !=3D 0) {
+	    _gss_ntlm_delete_sec_context(minor_status,
+					 context_handle, NULL);
+	    *minor_status =3D EINVAL;
+	    return GSS_S_FAILURE;
+	}
+
+	ret =3D heim_ntlm_calculate_ntlm2(ctx->client->key.data,
+					ctx->client->key.length,
+					type3.username,
+					name->domain,
+					type2.challenge,
+					&type2.targetinfo,
+					ntlmv2,
+					&type3.ntlm);
+	if (ret) {
+	    _gss_ntlm_delete_sec_context(minor_status,
+					 context_handle, NULL);
+	    *minor_status =3D ret;
+	    return GSS_S_FAILURE;
+	}
+
+	ret =3D heim_ntlm_build_ntlm1_master(ntlmv2, sizeof(ntlmv2),
+					   &sessionkey,
+					   &type3.sessionkey);
+	memset(ntlmv2, 0, sizeof(ntlmv2));
+	if (ret) {
+	    _gss_ntlm_delete_sec_context(minor_status,
+					 context_handle, NULL);
+	    *minor_status =3D ret;
+	    return GSS_S_FAILURE;
+	}
+
+	flags |=3D NTLM_FLAG_NTLM2_SESSION |
+	         NTLM_FLAG_SESSION;
+
+	if (type3.flags & NTLM_NEG_KEYEX)
+	    flags |=3D NTLM_FLAG_KEYEX;
+
+	ret =3D krb5_data_copy(&ctx->sessionkey,
+			     sessionkey.data, sessionkey.length);
+	free(sessionkey.data);
+	if (ret) {
+	    _gss_ntlm_delete_sec_context(minor_status,
+					 context_handle, NULL);
+	    *minor_status =3D ret;
+	    return GSS_S_FAILURE;
+	}
+#endif
+    }
+
+#if 0
+    if (flags & NTLM_FLAG_NTLM2_SESSION) {
+	_gss_ntlm_set_key(&ctx->u.v2.send, 0, (ctx->flags & NTLM_NEG_KEYEX),
+			  ctx->sessionkey.data,
+			  ctx->sessionkey.length);
+	_gss_ntlm_set_key(&ctx->u.v2.recv, 1, (ctx->flags & NTLM_NEG_KEYEX),
+			  ctx->sessionkey.data,
+			  ctx->sessionkey.length);
+    } else {
+	flags |=3D NTLM_FLAG_SESSION;
+	RC4_set_key(&ctx->u.v1.crypto_recv.key,
+		    ctx->sessionkey.length,
+		    ctx->sessionkey.data);
+	RC4_set_key(&ctx->u.v1.crypto_send.key,
+		    ctx->sessionkey.length,
+		    ctx->sessionkey.data);
+    }
+#endif
+
+    ret =3D heim_ntlm_encode_type3(&type3, &ndata);
+    if (ret)
+	goto error;
+
+    data.data =3D ndata.data;
+    data.length =3D ndata.length;
+    ret =3D krb5_store_data(response, data);
+    heim_ntlm_free_buf(&ndata);
+    if (ret) goto error;
+
+    ret =3D krb5_store_int32(response, flags);
+    if (ret) goto error;
+
+    data.data =3D sessionkey.data;
+    data.length =3D sessionkey.length;
+
+    ret =3D krb5_store_data(response, data);
+    if (ret) goto error;
+
+ error:
+    free(type3.username);
+    heim_ntlm_free_type2(&type2);
+    free(user);
+    if (domain)
+	free(domain);
+
+    return ret;
+}
+
+
+/*
+ * { "GET_NTLM_UUID_LIST",	NULL }
+ *
+ * reply:
+ *   1 user domain
+ *   0 [ end of list ]
+ */
+
+static krb5_error_code
+kcm_op_get_ntlm_user_list(krb5_context context,
+			  kcm_client *client,
+			  kcm_operation opcode,
+			  krb5_storage *request,
+			  krb5_storage *response)
+{
+    struct kcm_ntlm_cred *c;
+    krb5_error_code ret;
+
+    for (c =3D ntlm_head; c !=3D NULL; c =3D c->next) {
+	if (!kcm_is_same_session(client, c->uid, c->session))
+	    continue;
+
+	ret =3D krb5_store_uint32(response, 1);
+	if (ret)
+	    return ret;
+	ret =3D krb5_store_stringz(response, c->user);
+	if (ret)
+	    return ret;
+	ret =3D krb5_store_stringz(response, c->domain);
+	if (ret)
+	    return ret;
+    }
+    return krb5_store_uint32(response, 0);
+}
+
+/*
+ *
+ */
+
 static struct kcm_op kcm_ops[] =3D {
     { "NOOP", 			kcm_op_noop },
     { "GET_NAME",		kcm_op_get_name },
@@ -960,19 +1706,31 @@
     { "STORE",			kcm_op_store },
     { "RETRIEVE",		kcm_op_retrieve },
     { "GET_PRINCIPAL",		kcm_op_get_principal },
-    { "GET_FIRST",		kcm_op_get_first },
-    { "GET_NEXT",		kcm_op_get_next },
-    { "END_GET",		kcm_op_end_get },
+    { "GET_CRED_UUID_LIST",	kcm_op_get_cred_uuid_list },
+    { "GET_CRED_BY_UUID",	kcm_op_get_cred_by_uuid },
     { "REMOVE_CRED",		kcm_op_remove_cred },
     { "SET_FLAGS",		kcm_op_set_flags },
     { "CHOWN",			kcm_op_chown },
     { "CHMOD",			kcm_op_chmod },
     { "GET_INITIAL_TICKET",	kcm_op_get_initial_ticket },
-    { "GET_TICKET",		kcm_op_get_ticket }
+    { "GET_TICKET",		kcm_op_get_ticket },
+    { "MOVE_CACHE",		kcm_op_move_cache },
+    { "GET_CACHE_UUID_LIST",	kcm_op_get_cache_uuid_list },
+    { "GET_CACHE_BY_UUID",	kcm_op_get_cache_by_uuid },
+    { "GET_DEFAULT_CACHE",      kcm_op_get_default_cache },
+    { "SET_DEFAULT_CACHE",      kcm_op_set_default_cache },
+    { "GET_KDC_OFFSET",      	kcm_op_get_kdc_offset },
+    { "SET_KDC_OFFSET",      	kcm_op_set_kdc_offset },
+    { "ADD_NTLM_CRED",		kcm_op_add_ntlm_cred },
+    { "HAVE_USER_CRED",		kcm_op_have_ntlm_cred },
+    { "DEL_NTLM_CRED",		kcm_op_del_ntlm_cred },
+    { "DO_NTLM_AUTH",		kcm_op_do_ntlm },
+    { "GET_NTLM_USER_LIST",	kcm_op_get_ntlm_user_list }
 };
=20
=20
-const char *kcm_op2string(kcm_operation opcode)
+const char *
+kcm_op2string(kcm_operation opcode)
 {
     if (opcode >=3D sizeof(kcm_ops)/sizeof(kcm_ops[0]))
 	return "Unknown operation";
@@ -1024,6 +1782,12 @@
 	goto out;
     }
     method =3D kcm_ops[opcode].method;
+    if (method =3D=3D NULL) {
+	kcm_log(0, "Process %d: operation code %s not implemented",
+		client->pid, kcm_op2string(opcode));
+	ret =3D KRB5_FCC_INTERNAL;
+	goto out;
+    }
=20
     /* seek past place for status code */
     krb5_storage_seek(resp_sp, 4, SEEK_SET);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kcm/renew.c
--- a/head/crypto/heimdal/kcm/renew.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kcm/renew.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
=20
 #include "kcm_locl.h"
=20
-RCSID("$Id: renew.c 14566 2005-02-06 01:22:49Z lukeh $");
+RCSID("$Id$");
=20
 krb5_error_code
 kcm_ccache_refresh(krb5_context context,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/Makefile.am
--- a/head/crypto/heimdal/kdc/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,8 @@
-# $Id: Makefile.am 22489 2008-01-21 11:49:06Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_krb4) $(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
+AM_CPPFLAGS +=3D $(INCLUDE_libintl) $(INCLUDE_krb4) $(INCLUDE_hcrypto) -I$=
(srcdir)/../lib/krb5
=20
 lib_LTLIBRARIES =3D libkdc.la
=20
@@ -10,21 +10,25 @@
=20
 sbin_PROGRAMS =3D kstash
=20
-libexec_PROGRAMS =3D hprop hpropd kdc
+libexec_PROGRAMS =3D hprop hpropd kdc digest-service
=20
 noinst_PROGRAMS =3D kdc-replay
=20
 man_MANS =3D kdc.8 kstash.8 hprop.8 hpropd.8 string2key.8
=20
-hprop_SOURCES =3D hprop.c mit_dump.c v4_dump.c hprop.h kadb.h=20
+hprop_SOURCES =3D hprop.c mit_dump.c hprop.h
 hpropd_SOURCES =3D hpropd.c hprop.h
=20
 kstash_SOURCES =3D kstash.c headers.h
=20
 string2key_SOURCES =3D string2key.c headers.h
=20
+digest_service_SOURCES =3D \
+	digest-service.c
+
 kdc_SOURCES =3D connect.c	\
 	config.c	\
+	announce.c	\
 	main.c
=20
 libkdc_la_SOURCES =3D 		\
@@ -39,9 +43,6 @@
 	pkinit.c		\
 	log.c			\
 	misc.c			\
-	524.c			\
-	kerberos4.c		\
-	kaserver.c		\
 	kx509.c			\
 	process.c		\
 	windc.c			\
@@ -66,7 +67,6 @@
=20
 hprop_LDADD =3D \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_kdb) $(LIB_krb4) \
 	$(LIB_hcrypto) \
@@ -76,7 +76,6 @@
=20
 hpropd_LDADD =3D \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_kdb) $(LIB_krb4) \
 	$(LIB_hcrypto) \
@@ -91,7 +90,6 @@
 libkdc_la_LIBADD =3D \
 	$(LIB_pkinit) \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_kdb) $(LIB_krb4) \
 	$(top_builddir)/lib/ntlm/libheimntlm.la \
@@ -101,7 +99,6 @@
 	$(DBLIB)=20
=20
 LDADD =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_krb4) \
 	$(LIB_hcrypto) \
@@ -109,14 +106,34 @@
 	$(LIB_roken) \
 	$(DBLIB)
=20
-kdc_LDADD =3D libkdc.la $(LDADD) $(LIB_pidfile)
-kdc_replay_LDADD =3D $(kdc_LDADD)
+kdc_LDADD =3D libkdc.la $(LDADD) $(LIB_pidfile) $(CAPNG_LIBS)
+
+if FRAMEWORK_SECURITY
+kdc_LDFLAGS =3D -framework SystemConfiguration -framework CoreFoundation
+endif
+kdc_CFLAGS =3D $(CAPNG_CFLAGS)
+
+digest_service_LDADD =3D \
+	libkdc.la \
+	$(top_builddir)/lib/ntlm/libheimntlm.la \
+	$(top_builddir)/lib/ipc/libheim-ipcs.la \
+	$(LDADD) $(LIB_pidfile)
+kdc_replay_LDADD =3D libkdc.la $(LDADD) $(LIB_pidfile)
=20
 include_HEADERS =3D kdc.h kdc-protos.h
=20
+
 krb5dir =3D $(includedir)/krb5
 krb5_HEADERS =3D windc_plugin.h
=20
 build_HEADERZ =3D $(krb5_HEADERS) # XXX
=20
-EXTRA_DIST =3D $(man_MANS) version-script.map
+EXTRA_DIST =3D \
+	hprop-version.rc \
+	hpropd-version.rc \
+	kdc-version.rc \
+	kstash-version.rc \
+	libkdc-version.rc \
+	string2key-version.rc \
+	libkdc-exports.def \
+	NTMakefile $(man_MANS) version-script.map
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/Makefile.in
--- a/head/crypto/heimdal/kdc/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22489 2008-01-21 11:49:06Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,13 +47,14 @@
 	$(top_srcdir)/cf/Makefile.am.common
 bin_PROGRAMS =3D string2key$(EXEEXT)
 sbin_PROGRAMS =3D kstash$(EXEEXT)
-libexec_PROGRAMS =3D hprop$(EXEEXT) hpropd$(EXEEXT) kdc$(EXEEXT)
+libexec_PROGRAMS =3D hprop$(EXEEXT) hpropd$(EXEEXT) kdc$(EXEEXT) \
+	digest-service$(EXEEXT)
 noinst_PROGRAMS =3D kdc-replay$(EXEEXT)
 @versionscript_TRUE at am__append_1 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
 subdir =3D kdc
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -66,7 +69,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -80,9 +83,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -90,91 +96,108 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \
 	"$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(sbindir)" \
 	"$(DESTDIR)$(man8dir)" "$(DESTDIR)$(includedir)" \
 	"$(DESTDIR)$(krb5dir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
 am__DEPENDENCIES_1 =3D
 libkdc_la_DEPENDENCIES =3D $(LIB_pkinit) \
-	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/hdb/libhdb.la \
 	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(top_builddir)/lib/ntlm/libheimntlm.la \
 	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
 am_libkdc_la_OBJECTS =3D default_config.lo set_dbinfo.lo digest.lo \
-	kerberos5.lo krb5tgs.lo pkinit.lo log.lo misc.lo 524.lo \
-	kerberos4.lo kaserver.lo kx509.lo process.lo windc.lo
+	kerberos5.lo krb5tgs.lo pkinit.lo log.lo misc.lo kx509.lo \
+	process.lo windc.lo
 libkdc_la_OBJECTS =3D $(am_libkdc_la_OBJECTS)
 libkdc_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libkdc_la_LDFLAGS) $(LDFLAGS) -o $@
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-sbinPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS) $(libexec_PROGRAMS) $(noinst_PROGRAMS) \
 	$(sbin_PROGRAMS)
-am_hprop_OBJECTS =3D hprop.$(OBJEXT) mit_dump.$(OBJEXT) \
-	v4_dump.$(OBJEXT)
+am_digest_service_OBJECTS =3D digest-service.$(OBJEXT)
+digest_service_OBJECTS =3D $(am_digest_service_OBJECTS)
+am__DEPENDENCIES_2 =3D $(top_builddir)/lib/hdb/libhdb.la \
+	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+digest_service_DEPENDENCIES =3D libkdc.la \
+	$(top_builddir)/lib/ntlm/libheimntlm.la \
+	$(top_builddir)/lib/ipc/libheim-ipcs.la $(am__DEPENDENCIES_2) \
+	$(am__DEPENDENCIES_1)
+am_hprop_OBJECTS =3D hprop.$(OBJEXT) mit_dump.$(OBJEXT)
 hprop_OBJECTS =3D $(am_hprop_OBJECTS)
 hprop_DEPENDENCIES =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la \
+	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
 am_hpropd_OBJECTS =3D hpropd.$(OBJEXT)
 hpropd_OBJECTS =3D $(am_hpropd_OBJECTS)
 hpropd_DEPENDENCIES =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-am_kdc_OBJECTS =3D connect.$(OBJEXT) config.$(OBJEXT) main.$(OBJEXT)
-kdc_OBJECTS =3D $(am_kdc_OBJECTS)
-am__DEPENDENCIES_2 =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la \
+	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
 	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
+am_kdc_OBJECTS =3D kdc-connect.$(OBJEXT) kdc-config.$(OBJEXT) \
+	kdc-announce.$(OBJEXT) kdc-main.$(OBJEXT)
+kdc_OBJECTS =3D $(am_kdc_OBJECTS)
 kdc_DEPENDENCIES =3D libkdc.la $(am__DEPENDENCIES_2) \
-	$(am__DEPENDENCIES_1)
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+kdc_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
+	--mode=3Dlink $(CCLD) $(kdc_CFLAGS) $(CFLAGS) $(kdc_LDFLAGS) \
+	$(LDFLAGS) -o $@
 kdc_replay_SOURCES =3D kdc-replay.c
 kdc_replay_OBJECTS =3D kdc-replay.$(OBJEXT)
-am__DEPENDENCIES_3 =3D libkdc.la $(am__DEPENDENCIES_2) \
+kdc_replay_DEPENDENCIES =3D libkdc.la $(am__DEPENDENCIES_2) \
 	$(am__DEPENDENCIES_1)
-kdc_replay_DEPENDENCIES =3D $(am__DEPENDENCIES_3)
 am_kstash_OBJECTS =3D kstash.$(OBJEXT)
 kstash_OBJECTS =3D $(am_kstash_OBJECTS)
 kstash_LDADD =3D $(LDADD)
 kstash_DEPENDENCIES =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
 am_string2key_OBJECTS =3D string2key.$(OBJEXT)
 string2key_OBJECTS =3D $(am_string2key_OBJECTS)
 string2key_LDADD =3D $(LDADD)
 string2key_DEPENDENCIES =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/krb5/libkrb5.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -184,16 +207,14 @@
 LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
-SOURCES =3D $(libkdc_la_SOURCES) $(hprop_SOURCES) $(hpropd_SOURCES) \
-	$(kdc_SOURCES) kdc-replay.c $(kstash_SOURCES) \
-	$(string2key_SOURCES)
-DIST_SOURCES =3D $(libkdc_la_SOURCES) $(hprop_SOURCES) $(hpropd_SOURCES) \
-	$(kdc_SOURCES) kdc-replay.c $(kstash_SOURCES) \
-	$(string2key_SOURCES)
+SOURCES =3D $(libkdc_la_SOURCES) $(digest_service_SOURCES) \
+	$(hprop_SOURCES) $(hpropd_SOURCES) $(kdc_SOURCES) kdc-replay.c \
+	$(kstash_SOURCES) $(string2key_SOURCES)
+DIST_SOURCES =3D $(libkdc_la_SOURCES) $(digest_service_SOURCES) \
+	$(hprop_SOURCES) $(hpropd_SOURCES) $(kdc_SOURCES) kdc-replay.c \
+	$(kstash_SOURCES) $(string2key_SOURCES)
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
-includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-krb5HEADERS_INSTALL =3D $(INSTALL_HEADER)
 HEADERS =3D $(include_HEADERS) $(krb5_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
@@ -202,49 +223,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -268,10 +298,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -288,6 +319,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -303,31 +336,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -342,10 +389,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -386,39 +435,48 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4) $(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_libintl) $(INCLUDE_krb4) \
+	$(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 lib_LTLIBRARIES =3D libkdc.la
 man_MANS =3D kdc.8 kstash.8 hprop.8 hpropd.8 string2key.8
-hprop_SOURCES =3D hprop.c mit_dump.c v4_dump.c hprop.h kadb.h=20
+hprop_SOURCES =3D hprop.c mit_dump.c hprop.h
 hpropd_SOURCES =3D hpropd.c hprop.h
 kstash_SOURCES =3D kstash.c headers.h
 string2key_SOURCES =3D string2key.c headers.h
+digest_service_SOURCES =3D \
+	digest-service.c
+
 kdc_SOURCES =3D connect.c	\
 	config.c	\
+	announce.c	\
 	main.c
=20
 libkdc_la_SOURCES =3D \
@@ -433,9 +491,6 @@
 	pkinit.c		\
 	log.c			\
 	misc.c			\
-	524.c			\
-	kerberos4.c		\
-	kaserver.c		\
 	kx509.c			\
 	process.c		\
 	windc.c			\
@@ -444,7 +499,6 @@
 libkdc_la_LDFLAGS =3D -version-info 2:0:0 $(am__append_1)
 hprop_LDADD =3D \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_kdb) $(LIB_krb4) \
 	$(LIB_hcrypto) \
@@ -454,7 +508,6 @@
=20
 hpropd_LDADD =3D \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_kdb) $(LIB_krb4) \
 	$(LIB_hcrypto) \
@@ -466,7 +519,6 @@
 libkdc_la_LIBADD =3D \
 	$(LIB_pkinit) \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_kdb) $(LIB_krb4) \
 	$(top_builddir)/lib/ntlm/libheimntlm.la \
@@ -476,7 +528,6 @@
 	$(DBLIB)=20
=20
 LDADD =3D $(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_krb4) \
 	$(LIB_hcrypto) \
@@ -484,29 +535,46 @@
 	$(LIB_roken) \
 	$(DBLIB)
=20
-kdc_LDADD =3D libkdc.la $(LDADD) $(LIB_pidfile)
-kdc_replay_LDADD =3D $(kdc_LDADD)
+kdc_LDADD =3D libkdc.la $(LDADD) $(LIB_pidfile) $(CAPNG_LIBS)
+ at FRAMEWORK_SECURITY_TRUE@kdc_LDFLAGS =3D -framework SystemConfiguration -f=
ramework CoreFoundation
+kdc_CFLAGS =3D $(CAPNG_CFLAGS)
+digest_service_LDADD =3D \
+	libkdc.la \
+	$(top_builddir)/lib/ntlm/libheimntlm.la \
+	$(top_builddir)/lib/ipc/libheim-ipcs.la \
+	$(LDADD) $(LIB_pidfile)
+
+kdc_replay_LDADD =3D libkdc.la $(LDADD) $(LIB_pidfile)
 include_HEADERS =3D kdc.h kdc-protos.h
 krb5dir =3D $(includedir)/krb5
 krb5_HEADERS =3D windc_plugin.h
 build_HEADERZ =3D $(krb5_HEADERS) # XXX
-EXTRA_DIST =3D $(man_MANS) version-script.map
+EXTRA_DIST =3D \
+	hprop-version.rc \
+	hpropd-version.rc \
+	kdc-version.rc \
+	kstash-version.rc \
+	libkdc-version.rc \
+	string2key-version.rc \
+	libkdc-exports.def \
+	NTMakefile $(man_MANS) version-script.map
+
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps kdc/Makef=
ile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps kdc/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign kdc/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign kdc/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -524,23 +592,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -556,94 +629,144 @@
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-sbinPROGRAMS: $(sbin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(sbindir)" || $(MKDIR_P) "$(DESTDIR)$(sbindir)"
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRA=
MS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRAMS_INST=
ALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$d=
ir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || =
exit $$?; \
+	    } \
+	; done
=20
 uninstall-sbinPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(sbindir)/$$f"; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(sbindir)" && rm -f $$files
=20
 clean-sbinPROGRAMS:
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
+digest-service$(EXEEXT): $(digest_service_OBJECTS) $(digest_service_DEPEND=
ENCIES)=20
+	@rm -f digest-service$(EXEEXT)
+	$(LINK) $(digest_service_OBJECTS) $(digest_service_LDADD) $(LIBS)
 hprop$(EXEEXT): $(hprop_OBJECTS) $(hprop_DEPENDENCIES)=20
 	@rm -f hprop$(EXEEXT)
 	$(LINK) $(hprop_OBJECTS) $(hprop_LDADD) $(LIBS)
@@ -652,7 +775,7 @@
 	$(LINK) $(hpropd_OBJECTS) $(hpropd_LDADD) $(LIBS)
 kdc$(EXEEXT): $(kdc_OBJECTS) $(kdc_DEPENDENCIES)=20
 	@rm -f kdc$(EXEEXT)
-	$(LINK) $(kdc_OBJECTS) $(kdc_LDADD) $(LIBS)
+	$(kdc_LINK) $(kdc_OBJECTS) $(kdc_LDADD) $(LIBS)
 kdc-replay$(EXEEXT): $(kdc_replay_OBJECTS) $(kdc_replay_DEPENDENCIES)=20
 	@rm -f kdc-replay$(EXEEXT)
 	$(LINK) $(kdc_replay_OBJECTS) $(kdc_replay_LDADD) $(LIBS)
@@ -669,149 +792,256 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/default_config.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/digest-service.Po at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/digest.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hprop.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hpropd.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdc-announce.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdc-config.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdc-connect.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdc-main.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdc-replay.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kerberos5.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/krb5tgs.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kstash.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kx509.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/log.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/misc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/mit_dump.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/pkinit.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/process.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/set_dbinfo.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/string2key.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/windc.Plo at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
+
+kdc-connect.o: connect.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-connect.o -MD -MP -MF $=
(DEPDIR)/kdc-connect.Tpo -c -o kdc-connect.o `test -f 'connect.c' || echo '=
$(srcdir)/'`connect.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-connect.Tpo $(DEPDIR)/kdc-con=
nect.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'connect.c' object=3D'kdc-conne=
ct.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-connect.o `test -f '=
connect.c' || echo '$(srcdir)/'`connect.c
+
+kdc-connect.obj: connect.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-connect.obj -MD -MP -MF=
 $(DEPDIR)/kdc-connect.Tpo -c -o kdc-connect.obj `if test -f 'connect.c'; t=
hen $(CYGPATH_W) 'connect.c'; else $(CYGPATH_W) '$(srcdir)/connect.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-connect.Tpo $(DEPDIR)/kdc-con=
nect.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'connect.c' object=3D'kdc-conne=
ct.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-connect.obj `if test=
 -f 'connect.c'; then $(CYGPATH_W) 'connect.c'; else $(CYGPATH_W) '$(srcdir=
)/connect.c'; fi`
+
+kdc-config.o: config.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-config.o -MD -MP -MF $(=
DEPDIR)/kdc-config.Tpo -c -o kdc-config.o `test -f 'config.c' || echo '$(sr=
cdir)/'`config.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-config.Tpo $(DEPDIR)/kdc-conf=
ig.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'config.c' object=3D'kdc-config=
.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-config.o `test -f 'c=
onfig.c' || echo '$(srcdir)/'`config.c
+
+kdc-config.obj: config.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-config.obj -MD -MP -MF =
$(DEPDIR)/kdc-config.Tpo -c -o kdc-config.obj `if test -f 'config.c'; then =
$(CYGPATH_W) 'config.c'; else $(CYGPATH_W) '$(srcdir)/config.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-config.Tpo $(DEPDIR)/kdc-conf=
ig.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'config.c' object=3D'kdc-config=
.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-config.obj `if test =
-f 'config.c'; then $(CYGPATH_W) 'config.c'; else $(CYGPATH_W) '$(srcdir)/c=
onfig.c'; fi`
+
+kdc-announce.o: announce.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-announce.o -MD -MP -MF =
$(DEPDIR)/kdc-announce.Tpo -c -o kdc-announce.o `test -f 'announce.c' || ec=
ho '$(srcdir)/'`announce.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-announce.Tpo $(DEPDIR)/kdc-an=
nounce.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'announce.c' object=3D'kdc-anno=
unce.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-announce.o `test -f =
'announce.c' || echo '$(srcdir)/'`announce.c
+
+kdc-announce.obj: announce.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-announce.obj -MD -MP -M=
F $(DEPDIR)/kdc-announce.Tpo -c -o kdc-announce.obj `if test -f 'announce.c=
'; then $(CYGPATH_W) 'announce.c'; else $(CYGPATH_W) '$(srcdir)/announce.c'=
; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-announce.Tpo $(DEPDIR)/kdc-an=
nounce.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'announce.c' object=3D'kdc-anno=
unce.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-announce.obj `if tes=
t -f 'announce.c'; then $(CYGPATH_W) 'announce.c'; else $(CYGPATH_W) '$(src=
dir)/announce.c'; fi`
+
+kdc-main.o: main.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-main.o -MD -MP -MF $(DE=
PDIR)/kdc-main.Tpo -c -o kdc-main.o `test -f 'main.c' || echo '$(srcdir)/'`=
main.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-main.Tpo $(DEPDIR)/kdc-main.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'main.c' object=3D'kdc-main.o' =
libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-main.o `test -f 'mai=
n.c' || echo '$(srcdir)/'`main.c
+
+kdc-main.obj: main.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -MT kdc-main.obj -MD -MP -MF $(=
DEPDIR)/kdc-main.Tpo -c -o kdc-main.obj `if test -f 'main.c'; then $(CYGPAT=
H_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/kdc-main.Tpo $(DEPDIR)/kdc-main.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'main.c' object=3D'kdc-main.obj=
' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(kdc_CFLAGS) $(CFLAGS) -c -o kdc-main.obj `if test -f=
 'main.c'; then $(CYGPATH_W) 'main.c'; else $(CYGPATH_W) '$(srcdir)/main.c'=
; fi`
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man8: $(man8_MANS) $(man_MANS)
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
 install-includeHEADERS: $(include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'=
"; \
-	  $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-krb5HEADERS: $(krb5_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(krb5dir)" || $(MKDIR_P) "$(DESTDIR)$(krb5dir)"
-	@list=3D'$(krb5_HEADERS)'; for p in $$list; do \
+	@list=3D'$(krb5_HEADERS)'; test -n "$(krb5dir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(krb5HEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(krb5dir)/$$f'"; \
-	  $(krb5HEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(krb5dir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(krb5dir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(krb5dir)" || exit $$?; \
 	done
=20
 uninstall-krb5HEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(krb5_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(krb5dir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(krb5dir)/$$f"; \
-	done
+	@list=3D'$(krb5_HEADERS)'; test -n "$(krb5dir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(krb5dir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(krb5dir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -827,13 +1057,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -871,6 +1105,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -882,6 +1117,7 @@
 	clean-sbinPROGRAMS mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -892,6 +1128,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -900,27 +1138,36 @@
 	install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libLTLIBRARIES \
 	install-libexecPROGRAMS install-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -942,11 +1189,10 @@
 	uninstall-libexecPROGRAMS uninstall-man uninstall-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libLTLIBRARIES \
@@ -1039,6 +1285,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1124,7 +1373,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1146,6 +1395,7 @@
=20
 $(srcdir)/kdc-private.h:
 	cd $(srcdir) && perl ../cf/make-proto.pl -q -P comment -p kdc-private.h $=
(libkdc_la_SOURCES) || rm -f kdc-private.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/config.c
--- a/head/crypto/heimdal/kdc/config.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/config.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,42 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * All rights reserved.=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
 #include <getarg.h>
 #include <parse_bytes.h>
=20
-RCSID("$Id: config.c 22248 2007-12-08 23:52:12Z lha $");
-
 struct dbinfo {
     char *realm;
     char *dbname;
@@ -51,10 +50,6 @@
 static char *max_request_str;	/* `max_request' as a string */
=20
 static int disable_des =3D -1;
-static int enable_v4 =3D -1;
-static int enable_kaserver =3D -1;
-static int enable_524 =3D -1;
-static int enable_v4_cross_realm =3D -1;
=20
 static int builtin_hdb_flag;
 static int help_flag;
@@ -62,62 +57,55 @@
=20
 static struct getarg_strings addresses_str;	/* addresses to listen on */
=20
-static char *v4_realm;
+char *runas_string;
+char *chroot_string;
+
=20
 static struct getargs args[] =3D {
-    {=20
-	"config-file",	'c',	arg_string,	&config_file,=20
-	"location of config file",	"file"=20
+    {
+	"config-file",	'c',	arg_string,	&config_file,
+	"location of config file",	"file"
     },
-    {=20
-	"require-preauth",	'p',	arg_negative_flag, &require_preauth,=20
-	"don't require pa-data in as-reqs"
+    {
+	"require-preauth",	'p',	arg_negative_flag, &require_preauth,
+	"don't require pa-data in as-reqs", NULL
     },
-    {=20
-	"max-request",	0,	arg_string, &max_request,=20
+    {
+	"max-request",	0,	arg_string, &max_request_str,
 	"max size for a kdc-request", "size"
     },
-    { "enable-http", 'H', arg_flag, &enable_http, "turn on HTTP support" },
-    {	"524",		0, 	arg_negative_flag, &enable_524,
-	"don't respond to 524 requests"=20
-    },
-    {
-	"kaserver", 'K', arg_flag,   &enable_kaserver,
-	"enable kaserver support"
-    },
-    {	"kerberos4",	0, 	arg_flag, &enable_v4,
-	"respond to kerberos 4 requests"=20
-    },
-    {=20
-	"v4-realm",	'r',	arg_string, &v4_realm,=20
-	"realm to serve v4-requests for"
-    },
-    {	"kerberos4-cross-realm",	0, 	arg_flag,
-	&enable_v4_cross_realm,
-	"respond to kerberos 4 requests from foreign realms"=20
-    },
-    {	"ports",	'P', 	arg_string, &port_str,
+    { "enable-http", 'H', arg_flag, &enable_http, "turn on HTTP support",
+   	 NULL },
+    {	"ports",	'P', 	arg_string, rk_UNCONST(&port_str),
 	"ports to listen to", "portspec"
     },
+#ifdef SUPPORT_DETACH
 #if DETACH_IS_DEFAULT
     {
-	"detach",       'D',      arg_negative_flag, &detach_from_console,=20
-	"don't detach from console"
+	"detach",       'D',      arg_negative_flag, &detach_from_console,
+	"don't detach from console", NULL
     },
 #else
     {
-	"detach",       0 ,      arg_flag, &detach_from_console,=20
-	"detach from console"
+	"detach",       0 ,      arg_flag, &detach_from_console,
+	"detach from console", NULL
     },
 #endif
+#endif
     {	"addresses",	0,	arg_strings, &addresses_str,
 	"addresses to listen on", "list of addresses" },
     {	"disable-des",	0,	arg_flag, &disable_des,
-	"disable DES" },
+	"disable DES", NULL },
     {	"builtin-hdb",	0,	arg_flag,   &builtin_hdb_flag,
-	"list builtin hdb backends"},
-    {	"help",		'h',	arg_flag,   &help_flag },
-    {	"version",	'v',	arg_flag,   &version_flag }
+	"list builtin hdb backends", NULL},
+    {   "runas-user",	0,	arg_string, &runas_string,
+	"run as this user when connected to network", NULL
+    },
+    {   "chroot",	0,	arg_string, &chroot_string,
+	"chroot directory to run in", NULL
+    },
+    {	"help",		'h',	arg_flag,   &help_flag, NULL, NULL },
+    {	"version",	'v',	arg_flag,   &version_flag, NULL, NULL }
 };
=20
 static int num_args =3D sizeof(args) / sizeof(args[0]);
@@ -152,7 +140,7 @@
     krb5_error_code ret;
     int optidx =3D 0;
     const char *p;
-   =20
+
     while(getarg(args, num_args, argc, argv, &optidx))
 	warnx("error at argument `%s'", argv[optidx]);
=20
@@ -179,7 +167,7 @@
=20
     if (argc !=3D 0)
 	usage(1);
-   =20
+
     {
 	char **files;
=20
@@ -192,10 +180,10 @@
 	ret =3D krb5_prepend_config_files_default(config_file, &files);
 	if (ret)
 	    krb5_err(context, 1, ret, "getting configuration files");
-	   =20
+
 	ret =3D krb5_set_config_files(context, files);
 	krb5_free_config_files(files);
-	if(ret)=20
+	if(ret)
 	    krb5_err(context, 1, ret, "reading configuration files");
     }
=20
@@ -203,25 +191,25 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_kdc_default_config");
=20
-    kdc_openlog(context, config);
+    kdc_openlog(context, "kdc", config);
=20
     ret =3D krb5_kdc_set_dbinfo(context, config);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_kdc_set_dbinfo");
=20
     if(max_request_str)
-	max_request =3D parse_bytes(max_request_str, NULL);
+	max_request_tcp =3D max_request_udp =3D parse_bytes(max_request_str, NULL=
);
=20
-    if(max_request =3D=3D 0){
+    if(max_request_tcp =3D=3D 0){
 	p =3D krb5_config_get_string (context,
 				    NULL,
 				    "kdc",
 				    "max-request",
 				    NULL);
 	if(p)
-	    max_request =3D parse_bytes(p, NULL);
+	    max_request_tcp =3D max_request_udp =3D parse_bytes(p, NULL);
     }
-   =20
+
     if(require_preauth !=3D -1)
 	config->require_preauth =3D require_preauth;
=20
@@ -250,53 +238,39 @@
 	}
     }
=20
-    if(enable_v4 !=3D -1)
-	config->enable_v4 =3D enable_v4;
-
-    if(enable_v4_cross_realm !=3D -1)
-	config->enable_v4_cross_realm =3D enable_v4_cross_realm;
-
-    if(enable_524 !=3D -1)
-	config->enable_524 =3D enable_524;
-
     if(enable_http =3D=3D -1)
-	enable_http =3D krb5_config_get_bool(context, NULL, "kdc",=20
+	enable_http =3D krb5_config_get_bool(context, NULL, "kdc",
 					   "enable-http", NULL);
=20
     if(request_log =3D=3D NULL)
-	request_log =3D krb5_config_get_string(context, NULL,=20
-					     "kdc",=20
-					     "kdc-request-log",=20
+	request_log =3D krb5_config_get_string(context, NULL,
+					     "kdc",
+					     "kdc-request-log",
 					     NULL);
=20
-    if (krb5_config_get_string(context, NULL, "kdc",=20
+    if (krb5_config_get_string(context, NULL, "kdc",
 			       "enforce-transited-policy", NULL))
 	krb5_errx(context, 1, "enforce-transited-policy deprecated, "
 		  "use [kdc]transited-policy instead");
=20
-    if (enable_kaserver !=3D -1)
-	config->enable_kaserver =3D enable_kaserver;
-
-    if(detach_from_console =3D=3D -1)=20
-	detach_from_console =3D krb5_config_get_bool_default(context, NULL,=20
+#ifdef SUPPORT_DETACH
+    if(detach_from_console =3D=3D -1)
+	detach_from_console =3D krb5_config_get_bool_default(context, NULL,
 							   DETACH_IS_DEFAULT,
 							   "kdc",
 							   "detach", NULL);
+#endif /* SUPPORT_DETACH */
=20
-    if(max_request =3D=3D 0)
-	max_request =3D 64 * 1024;
+    if(max_request_tcp =3D=3D 0)
+	max_request_tcp =3D 64 * 1024;
+    if(max_request_udp =3D=3D 0)
+	max_request_udp =3D 64 * 1024;
=20
     if (port_str =3D=3D NULL)
 	port_str =3D "+";
=20
-    if (v4_realm)
-	config->v4_realm =3D v4_realm;
-
-    if(config->v4_realm =3D=3D NULL && (config->enable_kaserver || config-=
>enable_v4))
-	krb5_errx(context, 1, "Kerberos 4 enabled but no realm configured");
-
     if(disable_des =3D=3D -1)
-	disable_des =3D krb5_config_get_bool_default(context, NULL,=20
+	disable_des =3D krb5_config_get_bool_default(context, NULL,
 						   FALSE,
 						   "kdc",
 						   "disable-des", NULL);
@@ -307,16 +281,11 @@
 	krb5_enctype_disable(context, ETYPE_DES_CBC_NONE);
 	krb5_enctype_disable(context, ETYPE_DES_CFB64_NONE);
 	krb5_enctype_disable(context, ETYPE_DES_PCBC_NONE);
-
-	kdc_log(context, config,=20
-		0, "DES was disabled, turned off Kerberos V4, 524 "
-		"and kaserver");
-	config->enable_v4 =3D 0;
-	config->enable_524 =3D 0;
-	config->enable_kaserver =3D 0;
     }
=20
     krb5_kdc_windc_init(context);
=20
+    krb5_kdc_pkinit_config(context, config);
+
     return config;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/connect.c
--- a/head/crypto/heimdal/kdc/connect.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/connect.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: connect.c 22434 2008-01-14 09:21:37Z lha $");
-
 /* Should we enable the HTTP hack? */
 int enable_http =3D -1;
=20
@@ -46,7 +44,8 @@
=20
 krb5_addresses explicit_addresses;
=20
-size_t max_request;		/* maximal size of a request */
+size_t max_request_udp;
+size_t max_request_tcp;
=20
 /*
  * a tuple describing on what to listen
@@ -61,18 +60,18 @@
 /* the current ones */
=20
 static struct port_desc *ports;
-static int num_ports;
+static size_t num_ports;
=20
 /*
  * add `family, port, protocol' to the list with duplicate suppresion.
  */
=20
 static void
-add_port(krb5_context context,=20
+add_port(krb5_context context,
 	 int family, int port, const char *protocol)
 {
     int type;
-    int i;
+    size_t i;
=20
     if(strcmp(protocol, "udp") =3D=3D 0)
 	type =3D SOCK_DGRAM;
@@ -101,7 +100,7 @@
  */
=20
 static void
-add_port_service(krb5_context context,=20
+add_port_service(krb5_context context,
 		 int family, const char *service, int port,
 		 const char *protocol)
 {
@@ -115,7 +114,7 @@
  */
=20
 static void
-add_port_string (krb5_context context,=20
+add_port_string (krb5_context context,
 		 int family, const char *str, const char *protocol)
 {
     struct servent *sp;
@@ -139,7 +138,7 @@
  */
=20
 static void
-add_standard_ports (krb5_context context, 		=20
+add_standard_ports (krb5_context context,
 		    krb5_kdc_configuration *config,
 		    int family)
 {
@@ -149,16 +148,6 @@
     add_port_service(context, family, "kerberos-sec", 88, "tcp");
     if(enable_http)
 	add_port_service(context, family, "http", 80, "tcp");
-    if(config->enable_524) {
-	add_port_service(context, family, "krb524", 4444, "udp");
-	add_port_service(context, family, "krb524", 4444, "tcp");
-    }
-    if(config->enable_v4) {
-	add_port_service(context, family, "kerberos-iv", 750, "udp");
-	add_port_service(context, family, "kerberos-iv", 750, "tcp");
-    }
-    if (config->enable_kaserver)
-	add_port_service(context, family, "afs3-kaserver", 7004, "udp");
     if(config->enable_kx509) {
 	add_port_service(context, family, "kca_service", 9878, "udp");
 	add_port_service(context, family, "kca_service", 9878, "tcp");
@@ -173,7 +162,7 @@
  */
=20
 static void
-parse_ports(krb5_context context, 		=20
+parse_ports(krb5_context context,
 	    krb5_kdc_configuration *config,
 	    const char *str)
 {
@@ -205,7 +194,7 @@
 		add_port_string(context, AF_INET, p, "tcp");
 	    }
 	}
-	   =20
+
 	p =3D strtok_r(NULL, " \t", &pos);
     }
     free (str_copy);
@@ -216,7 +205,7 @@
  */
=20
 struct descr {
-    int s;
+    krb5_socket_t s;
     int type;
     int port;
     unsigned char *buf;
@@ -234,7 +223,7 @@
 {
     memset(d, 0, sizeof(*d));
     d->sa =3D (struct sockaddr *)&d->__ss;
-    d->s =3D -1;
+    d->s =3D rk_INVALID_SOCKET;
 }
=20
 /*
@@ -254,8 +243,8 @@
  * Create the socket (family, type, port) in `d'
  */
=20
-static void=20
-init_socket(krb5_context context,=20
+static void
+init_socket(krb5_context context,
 	    krb5_kdc_configuration *config,
 	    struct descr *d, krb5_address *a, int family, int type, int port)
 {
@@ -269,8 +258,8 @@
     ret =3D krb5_addr2sockaddr (context, a, sa, &sa_size, port);
     if (ret) {
 	krb5_warn(context, ret, "krb5_addr2sockaddr");
-	close(d->s);
-	d->s =3D -1;
+	rk_closesocket(d->s);
+	d->s =3D rk_INVALID_SOCKET;
 	return;
     }
=20
@@ -278,9 +267,9 @@
 	return;
=20
     d->s =3D socket(family, type, 0);
-    if(d->s < 0){
+    if(rk_IS_BAD_SOCKET(d->s)){
 	krb5_warn(context, errno, "socket(%d, %d, 0)", family, type);
-	d->s =3D -1;
+	d->s =3D rk_INVALID_SOCKET;
 	return;
     }
 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_REUSEADD=
R)
@@ -292,24 +281,24 @@
     d->type =3D type;
     d->port =3D port;
=20
-    if(bind(d->s, sa, sa_size) < 0){
+    if(rk_IS_SOCKET_ERROR(bind(d->s, sa, sa_size))){
 	char a_str[256];
 	size_t len;
=20
 	krb5_print_address (a, a_str, sizeof(a_str), &len);
 	krb5_warn(context, errno, "bind %s/%d", a_str, ntohs(port));
-	close(d->s);
-	d->s =3D -1;
+	rk_closesocket(d->s);
+	d->s =3D rk_INVALID_SOCKET;
 	return;
     }
-    if(type =3D=3D SOCK_STREAM && listen(d->s, SOMAXCONN) < 0){
+    if(type =3D=3D SOCK_STREAM && rk_IS_SOCKET_ERROR(listen(d->s, SOMAXCON=
N))){
 	char a_str[256];
 	size_t len;
=20
 	krb5_print_address (a, a_str, sizeof(a_str), &len);
 	krb5_warn(context, errno, "listen %s/%d", a_str, ntohs(port));
-	close(d->s);
-	d->s =3D -1;
+	rk_closesocket(d->s);
+	d->s =3D rk_INVALID_SOCKET;
 	return;
     }
 }
@@ -320,12 +309,12 @@
  */
=20
 static int
-init_sockets(krb5_context context,=20
+init_sockets(krb5_context context,
 	     krb5_kdc_configuration *config,
 	     struct descr **desc)
 {
     krb5_error_code ret;
-    int i, j;
+    size_t i, j;
     struct descr *d;
     int num =3D 0;
     krb5_addresses addresses;
@@ -347,7 +336,7 @@
 	for (j =3D 0; j < addresses.len; ++j) {
 	    init_socket(context, config, &d[num], &addresses.val[j],
 			ports[i].family, ports[i].type, ports[i].port);
-	    if(d[num].s !=3D -1){
+	    if(d[num].s !=3D rk_INVALID_SOCKET){
 		char a_str[80];
 		size_t len;
=20
@@ -356,7 +345,7 @@
=20
 		kdc_log(context, config, 5, "listening on %s port %u/%s",
 			a_str,
-			ntohs(ports[i].port),=20
+			ntohs(ports[i].port),
 			(ports[i].type =3D=3D SOCK_STREAM) ? "tcp" : "udp");
 		/* XXX */
 		num++;
@@ -388,7 +377,7 @@
 }
=20
 static void
-addr_to_string(krb5_context context, 		=20
+addr_to_string(krb5_context context,
 	       struct sockaddr *addr, size_t addr_len, char *str, size_t len)
 {
     krb5_address a;
@@ -407,7 +396,7 @@
  */
=20
 static void
-send_reply(krb5_context context,=20
+send_reply(krb5_context context,
 	   krb5_kdc_configuration *config,
 	   krb5_boolean prependlength,
 	   struct descr *d,
@@ -422,15 +411,16 @@
 	l[1] =3D (reply->length >> 16) & 0xff;
 	l[2] =3D (reply->length >> 8) & 0xff;
 	l[3] =3D reply->length & 0xff;
-	if(sendto(d->s, l, sizeof(l), 0, d->sa, d->sock_len) < 0) {
-	    kdc_log (context, config,=20
-		     0, "sendto(%s): %s", d->addr_string, strerror(errno));
+	if(rk_IS_SOCKET_ERROR(sendto(d->s, l, sizeof(l), 0, d->sa, d->sock_len)))=
 {
+	    kdc_log (context, config,
+		     0, "sendto(%s): %s", d->addr_string,
+		     strerror(rk_SOCK_ERRNO));
 	    return;
 	}
     }
-    if(sendto(d->s, reply->data, reply->length, 0, d->sa, d->sock_len) < 0=
) {
-	kdc_log (context, config,=20
-		 0, "sendto(%s): %s", d->addr_string, strerror(errno));
+    if(rk_IS_SOCKET_ERROR(sendto(d->s, reply->data, reply->length, 0, d->s=
a, d->sock_len))) {
+	kdc_log (context, config, 0, "sendto(%s): %s", d->addr_string,
+		 strerror(rk_SOCK_ERRNO));
 	return;
     }
 }
@@ -440,7 +430,7 @@
  */
=20
 static void
-do_request(krb5_context context,=20
+do_request(krb5_context context,
 	   krb5_kdc_configuration *config,
 	   void *buf, size_t len, krb5_boolean prependlength,
 	   struct descr *d)
@@ -452,7 +442,7 @@
     krb5_kdc_update_time(NULL);
=20
     krb5_data_zero(&reply);
-    ret =3D krb5_kdc_process_request(context, config,=20
+    ret =3D krb5_kdc_process_request(context, config,
 				   buf, len, &reply, &prependlength,
 				   d->addr_string, d->sa,
 				   datagram_reply);
@@ -463,8 +453,8 @@
 	krb5_data_free(&reply);
     }
     if(ret)
-	kdc_log(context, config, 0,=20
-		"Failed processing %lu byte request from %s",=20
+	kdc_log(context, config, 0,
+		"Failed processing %lu byte request from %s",
 		(unsigned long)len, d->addr_string);
 }
=20
@@ -473,27 +463,45 @@
  */
=20
 static void
-handle_udp(krb5_context context,=20
+handle_udp(krb5_context context,
 	   krb5_kdc_configuration *config,
 	   struct descr *d)
 {
     unsigned char *buf;
-    int n;
+    ssize_t n;
=20
-    buf =3D malloc(max_request);
+    buf =3D malloc(max_request_udp);
     if(buf =3D=3D NULL){
-	kdc_log(context, config, 0, "Failed to allocate %lu bytes", (unsigned lon=
g)max_request);
+	kdc_log(context, config, 0, "Failed to allocate %lu bytes", (unsigned lon=
g)max_request_udp);
 	return;
     }
=20
     d->sock_len =3D sizeof(d->__ss);
-    n =3D recvfrom(d->s, buf, max_request, 0, d->sa, &d->sock_len);
-    if(n < 0)
-	krb5_warn(context, errno, "recvfrom");
+    n =3D recvfrom(d->s, buf, max_request_udp, 0, d->sa, &d->sock_len);
+    if(rk_IS_SOCKET_ERROR(n))
+	krb5_warn(context, rk_SOCK_ERRNO, "recvfrom");
     else {
 	addr_to_string (context, d->sa, d->sock_len,
 			d->addr_string, sizeof(d->addr_string));
-	do_request(context, config, buf, n, FALSE, d);
+	if ((size_t)n =3D=3D max_request_udp) {
+	    krb5_data data;
+	    krb5_warn(context, errno,
+		      "recvfrom: truncated packet from %s, asking for TCP",
+		      d->addr_string);
+	    krb5_mk_error(context,
+			  KRB5KRB_ERR_RESPONSE_TOO_BIG,
+			  NULL,
+			  NULL,
+			  NULL,
+			  NULL,
+			  NULL,
+			  NULL,
+			  &data);
+	    send_reply(context, config, FALSE, d, &data);
+	    krb5_data_free(&data);
+	} else {
+	    do_request(context, config, buf, n, FALSE, d);
+	}
     }
     free (buf);
 }
@@ -504,9 +512,9 @@
     if(d->buf)
 	memset(d->buf, 0, d->size);
     d->len =3D 0;
-    if(d->s !=3D -1)
-	close(d->s);
-    d->s =3D -1;
+    if(d->s !=3D rk_INVALID_SOCKET)
+	rk_closesocket(d->s);
+    d->s =3D rk_INVALID_SOCKET;
 }
=20
=20
@@ -536,32 +544,34 @@
  */
=20
 static void
-add_new_tcp (krb5_context context,=20
+add_new_tcp (krb5_context context,
 	     krb5_kdc_configuration *config,
 	     struct descr *d, int parent, int child)
 {
-    int s;
+    krb5_socket_t s;
=20
     if (child =3D=3D -1)
 	return;
=20
     d[child].sock_len =3D sizeof(d[child].__ss);
     s =3D accept(d[parent].s, d[child].sa, &d[child].sock_len);
-    if(s < 0) {
-	krb5_warn(context, errno, "accept");
+    if(rk_IS_BAD_SOCKET(s)) {
+	krb5_warn(context, rk_SOCK_ERRNO, "accept");
 	return;
     }
-	   =20
+
+#ifdef FD_SETSIZE
     if (s >=3D FD_SETSIZE) {
 	krb5_warnx(context, "socket FD too large");
-	close (s);
+	rk_closesocket (s);
 	return;
     }
+#endif
=20
     d[child].s =3D s;
     d[child].timeout =3D time(NULL) + TCP_TIMEOUT;
     d[child].type =3D SOCK_STREAM;
-    addr_to_string (context,=20
+    addr_to_string (context,
 		    d[child].sa, d[child].sock_len,
 		    d[child].addr_string, sizeof(d[child].addr_string));
 }
@@ -572,16 +582,16 @@
  */
=20
 static int
-grow_descr (krb5_context context,=20
+grow_descr (krb5_context context,
 	    krb5_kdc_configuration *config,
 	    struct descr *d, size_t n)
 {
     if (d->size - d->len < n) {
 	unsigned char *tmp;
-	size_t grow;=20
+	size_t grow;
=20
 	grow =3D max(1024, d->len + n);
-	if (d->size + grow > max_request) {
+	if (d->size + grow > max_request_tcp) {
 	    kdc_log(context, config, 0, "Request exceeds max request size (%lu by=
tes).",
 		    (unsigned long)d->size + grow);
 	    clear_descr(d);
@@ -606,7 +616,7 @@
  */
=20
 static int
-handle_vanilla_tcp (krb5_context context,=20
+handle_vanilla_tcp (krb5_context context,
 		    krb5_kdc_configuration *config,
 		    struct descr *d)
 {
@@ -634,7 +644,7 @@
  */
=20
 static int
-handle_http_tcp (krb5_context context,=20
+handle_http_tcp (krb5_context context,
 		 krb5_kdc_configuration *config,
 		 struct descr *d)
 {
@@ -645,24 +655,26 @@
=20
     s =3D (char *)d->buf;
=20
+    /* If its a multi line query, truncate off the first line */
     p =3D strstr(s, "\r\n");
-    if (p =3D=3D NULL) {
-	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_str=
ing);
-	return -1;
-    }
-    *p =3D 0;
+    if (p)
+	*p =3D 0;
=20
     p =3D NULL;
     t =3D strtok_r(s, " \t", &p);
     if (t =3D=3D NULL) {
-	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_str=
ing);
+	kdc_log(context, config, 0,
+		"Missing HTTP operand (GET) request from %s", d->addr_string);
 	return -1;
     }
+
     t =3D strtok_r(NULL, " \t", &p);
     if(t =3D=3D NULL) {
-	kdc_log(context, config, 0, "Malformed HTTP request from %s", d->addr_str=
ing);
+	kdc_log(context, config, 0,
+		"Missing HTTP GET data in request from %s", d->addr_string);
 	return -1;
     }
+
     data =3D malloc(strlen(t));
     if (data =3D=3D NULL) {
 	kdc_log(context, config, 0, "Failed to allocate %lu bytes",
@@ -685,7 +697,7 @@
     }
     len =3D base64_decode(t, data);
     if(len <=3D 0){
-	const char *msg =3D=20
+	const char *msg =3D
 	    " 404 Not found\r\n"
 	    "Server: Heimdal/" VERSION "\r\n"
 	    "Cache-Control: no-cache\r\n"
@@ -699,37 +711,41 @@
 	kdc_log(context, config, 0, "HTTP request from %s is non KDC request", d-=
>addr_string);
 	kdc_log(context, config, 5, "HTTP request: %s", t);
 	free(data);
-	if (write(d->s, proto, strlen(proto)) < 0) {
-	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",=20
-		    d->addr_string, strerror(errno));
+	if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
+	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
+		    d->addr_string, strerror(rk_SOCK_ERRNO));
 	    return -1;
 	}
-	if (write(d->s, msg, strlen(msg)) < 0) {
-	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",=20
-		    d->addr_string, strerror(errno));
+	if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
+	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
+		    d->addr_string, strerror(rk_SOCK_ERRNO));
 	    return -1;
 	}
 	return -1;
     }
     {
-	const char *msg =3D=20
+	const char *msg =3D
 	    " 200 OK\r\n"
 	    "Server: Heimdal/" VERSION "\r\n"
 	    "Cache-Control: no-cache\r\n"
 	    "Pragma: no-cache\r\n"
 	    "Content-type: application/octet-stream\r\n"
 	    "Content-transfer-encoding: binary\r\n\r\n";
-	if (write(d->s, proto, strlen(proto)) < 0) {
-	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",=20
-		    d->addr_string, strerror(errno));
+	if (rk_IS_SOCKET_ERROR(send(d->s, proto, strlen(proto), 0))) {
+	    free(data);
+	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
+		    d->addr_string, strerror(rk_SOCK_ERRNO));
 	    return -1;
 	}
-	if (write(d->s, msg, strlen(msg)) < 0) {
-	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",=20
-		    d->addr_string, strerror(errno));
+	if (rk_IS_SOCKET_ERROR(send(d->s, msg, strlen(msg), 0))) {
+	    free(data);
+	    kdc_log(context, config, 0, "HTTP write failed: %s: %s",
+		    d->addr_string, strerror(rk_SOCK_ERRNO));
 	    return -1;
 	}
     }
+    if ((size_t)len > d->len)
+        len =3D d->len;
     memcpy(d->buf, data, len);
     d->len =3D len;
     free(data);
@@ -741,7 +757,7 @@
  */
=20
 static void
-handle_tcp(krb5_context context,=20
+handle_tcp(krb5_context context,
 	   krb5_kdc_configuration *config,
 	   struct descr *d, int idx, int min_free)
 {
@@ -755,15 +771,15 @@
     }
=20
     n =3D recvfrom(d[idx].s, buf, sizeof(buf), 0, NULL, NULL);
-    if(n < 0){
-	krb5_warn(context, errno, "recvfrom failed from %s to %s/%d",
-		  d[idx].addr_string, descr_type(d + idx),=20
+    if(rk_IS_SOCKET_ERROR(n)){
+	krb5_warn(context, rk_SOCK_ERRNO, "recvfrom failed from %s to %s/%d",
+		  d[idx].addr_string, descr_type(d + idx),
 		  ntohs(d[idx].port));
 	return;
     } else if (n =3D=3D 0) {
 	krb5_warnx(context, "connection closed before end of data after %lu "
-		   "bytes from %s to %s/%d", (unsigned long)d[idx].len,=20
-		   d[idx].addr_string, descr_type(d + idx),=20
+		   "bytes from %s to %s/%d", (unsigned long)d[idx].len,
+		   d[idx].addr_string, descr_type(d + idx),
 		   ntohs(d[idx].port));
 	clear_descr (d + idx);
 	return;
@@ -776,16 +792,20 @@
 	ret =3D handle_vanilla_tcp (context, config, &d[idx]);
     } else if(enable_http &&
 	      d[idx].len >=3D 4 &&
-	      strncmp((char *)d[idx].buf, "GET ", 4) =3D=3D 0 &&=20
+	      strncmp((char *)d[idx].buf, "GET ", 4) =3D=3D 0 &&
 	      strncmp((char *)d[idx].buf + d[idx].len - 4,
 		      "\r\n\r\n", 4) =3D=3D 0) {
+
+        /* remove the trailing \r\n\r\n so the string is NUL terminated */
+        d[idx].buf[d[idx].len - 4] =3D '\0';
+
 	ret =3D handle_http_tcp (context, config, &d[idx]);
 	if (ret < 0)
 	    clear_descr (d + idx);
     } else if (d[idx].len > 4) {
-	kdc_log (context, config,=20
+	kdc_log (context, config,
 		 0, "TCP data of strange type from %s to %s/%d",
-		 d[idx].addr_string, descr_type(d + idx),=20
+		 d[idx].addr_string, descr_type(d + idx),
 		 ntohs(d[idx].port));
 	if (d[idx].buf[0] & 0x80) {
 	    krb5_data reply;
@@ -812,18 +832,18 @@
     if (ret < 0)
 	return;
     else if (ret =3D=3D 1) {
-	do_request(context, config,=20
+	do_request(context, config,
 		   d[idx].buf, d[idx].len, TRUE, &d[idx]);
 	clear_descr(d + idx);
     }
 }
=20
 void
-loop(krb5_context context,=20
+loop(krb5_context context,
      krb5_kdc_configuration *config)
 {
     struct descr *d;
-    int ndescr;
+    unsigned int ndescr;
=20
     ndescr =3D init_sockets(context, config, &d);
     if(ndescr <=3D 0)
@@ -834,25 +854,29 @@
 	fd_set fds;
 	int min_free =3D -1;
 	int max_fd =3D 0;
-	int i;
+	size_t i;
=20
 	FD_ZERO(&fds);
 	for(i =3D 0; i < ndescr; i++) {
-	    if(d[i].s >=3D 0){
-		if(d[i].type =3D=3D SOCK_STREAM &&=20
+	    if(!rk_IS_BAD_SOCKET(d[i].s)){
+		if(d[i].type =3D=3D SOCK_STREAM &&
 		   d[i].timeout && d[i].timeout < time(NULL)) {
-		    kdc_log(context, config, 1,=20
+		    kdc_log(context, config, 1,
 			    "TCP-connection from %s expired after %lu bytes",
 			    d[i].addr_string, (unsigned long)d[i].len);
 		    clear_descr(&d[i]);
 		    continue;
 		}
+#ifndef NO_LIMIT_FD_SETSIZE
 		if(max_fd < d[i].s)
 		    max_fd =3D d[i].s;
+#ifdef FD_SETSIZE
 		if (max_fd >=3D FD_SETSIZE)
 		    krb5_errx(context, 1, "fd too large");
+#endif
+#endif
 		FD_SET(d[i].s, &fds);
-	    } else if(min_free < 0 || i < min_free)
+	    } else if(min_free < 0 || i < (size_t)min_free)
 		min_free =3D i;
 	}
 	if(min_free =3D=3D -1){
@@ -870,7 +894,7 @@
 		ndescr +=3D 4;
 	    }
 	}
-   =20
+
 	tmout.tv_sec =3D TCP_TIMEOUT;
 	tmout.tv_usec =3D 0;
 	switch(select(max_fd + 1, &fds, 0, 0, &tmout)){
@@ -878,11 +902,11 @@
 	    break;
 	case -1:
 	    if (errno !=3D EINTR)
-		krb5_warn(context, errno, "select");
+		krb5_warn(context, rk_SOCK_ERRNO, "select");
 	    break;
 	default:
 	    for(i =3D 0; i < ndescr; i++)
-		if(d[i].s >=3D 0 && FD_ISSET(d[i].s, &fds)) {
+		if(!rk_IS_BAD_SOCKET(d[i].s) && FD_ISSET(d[i].s, &fds)) {
 		    if(d[i].type =3D=3D SOCK_DGRAM)
 			handle_udp(context, config, &d[i]);
 		    else if(d[i].type =3D=3D SOCK_STREAM)
@@ -890,8 +914,11 @@
 		}
 	}
     }
-    if(exit_flag =3D=3D SIGXCPU)
+    if (0);
+#ifdef SIGXCPU
+    else if(exit_flag =3D=3D SIGXCPU)
 	kdc_log(context, config, 0, "CPU time limit exceeded");
+#endif
     else if(exit_flag =3D=3D SIGINT || exit_flag =3D=3D SIGTERM)
 	kdc_log(context, config, 0, "Terminated");
     else
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/default_config=
.c
--- a/head/crypto/heimdal/kdc/default_config.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/kdc/default_config.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,43 +1,42 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * All rights reserved.=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
 #include <getarg.h>
 #include <parse_bytes.h>
=20
-RCSID("$Id: default_config.c 21405 2007-07-04 10:35:45Z lha $");
-
 krb5_error_code
 krb5_kdc_get_config(krb5_context context, krb5_kdc_configuration **config)
 {
@@ -45,21 +44,21 @@
=20
     c =3D calloc(1, sizeof(*c));
     if (c =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
=20
     c->require_preauth =3D TRUE;
     c->kdc_warn_pwexpire =3D 0;
     c->encode_as_rep_as_tgs_rep =3D FALSE;
+    c->tgt_use_strongest_session_key =3D FALSE;
+    c->preauth_use_strongest_session_key =3D FALSE;
+    c->svc_use_strongest_session_key =3D FALSE;
+    c->use_strongest_server_key =3D TRUE;
     c->check_ticket_addresses =3D TRUE;
     c->allow_null_ticket_addresses =3D TRUE;
     c->allow_anonymous =3D FALSE;
     c->trpolicy =3D TRPOLICY_ALWAYS_CHECK;
-    c->enable_v4 =3D FALSE;
-    c->enable_kaserver =3D FALSE;
-    c->enable_524 =3D FALSE;
-    c->enable_v4_cross_realm =3D FALSE;
     c->enable_pkinit =3D FALSE;
     c->pkinit_princ_in_cert =3D TRUE;
     c->pkinit_require_binding =3D TRUE;
@@ -68,32 +67,20 @@
     c->logf =3D NULL;
=20
     c->require_preauth =3D
-	krb5_config_get_bool_default(context, NULL,=20
+	krb5_config_get_bool_default(context, NULL,
 				     c->require_preauth,
 				     "kdc", "require-preauth", NULL);
-    c->enable_v4 =3D=20
-	krb5_config_get_bool_default(context, NULL,=20
-				     c->enable_v4,=20
-				     "kdc", "enable-kerberos4", NULL);
-    c->enable_v4_cross_realm =3D
+#ifdef DIGEST
+    c->enable_digest =3D
 	krb5_config_get_bool_default(context, NULL,
-				     c->enable_v4_cross_realm,=20
-				     "kdc",
-				     "enable-kerberos4-cross-realm", NULL);
-    c->enable_524 =3D
-	krb5_config_get_bool_default(context, NULL,=20
-				     c->enable_v4,=20
-				     "kdc", "enable-524", NULL);
-    c->enable_digest =3D=20
-	krb5_config_get_bool_default(context, NULL,=20
 				     FALSE,
 				     "kdc", "enable-digest", NULL);
=20
     {
 	const char *digests;
=20
-	digests =3D krb5_config_get_string(context, NULL,=20
-					 "kdc",=20
+	digests =3D krb5_config_get_string(context, NULL,
+					 "kdc",
 					 "digests_allowed", NULL);
 	if (digests =3D=3D NULL)
 	    digests =3D "ntlm-v2";
@@ -110,18 +97,20 @@
 	    c->enable_digest =3D 0;
 	}
     }
+#endif
=20
-    c->enable_kx509 =3D=20
-	krb5_config_get_bool_default(context, NULL,=20
-				     FALSE,=20
+#ifdef KX509
+    c->enable_kx509 =3D
+	krb5_config_get_bool_default(context, NULL,
+				     FALSE,
 				     "kdc", "enable-kx509", NULL);
=20
     if (c->enable_kx509) {
 	c->kx509_template =3D
-	    krb5_config_get_string(context, NULL,=20
+	    krb5_config_get_string(context, NULL,
 				   "kdc", "kx509_template", NULL);
 	c->kx509_ca =3D
-	    krb5_config_get_string(context, NULL,=20
+	    krb5_config_get_string(context, NULL,
 				   "kdc", "kx509_ca", NULL);
 	if (c->kx509_ca =3D=3D NULL || c->kx509_template =3D=3D NULL) {
 	    kdc_log(context, c, 0,
@@ -129,27 +118,49 @@
 	    c->enable_kx509 =3D FALSE;
 	}
     }
+#endif
=20
-    c->check_ticket_addresses =3D=20
-	krb5_config_get_bool_default(context, NULL,=20
-				     c->check_ticket_addresses,=20
-				     "kdc",=20
+    c->tgt_use_strongest_session_key =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->tgt_use_strongest_session_key,
+				     "kdc",
+				     "tgt-use-strongest-session-key", NULL);
+    c->preauth_use_strongest_session_key =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->preauth_use_strongest_session_key,
+				     "kdc",
+				     "preauth-use-strongest-session-key", NULL);
+    c->svc_use_strongest_session_key =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->svc_use_strongest_session_key,
+				     "kdc",
+				     "svc-use-strongest-session-key", NULL);
+    c->use_strongest_server_key =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->use_strongest_server_key,
+				     "kdc",
+				     "use-strongest-server-key", NULL);
+
+    c->check_ticket_addresses =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->check_ticket_addresses,
+				     "kdc",
 				     "check-ticket-addresses", NULL);
-    c->allow_null_ticket_addresses =3D=20
-	krb5_config_get_bool_default(context, NULL,=20
-				     c->allow_null_ticket_addresses,=20
-				     "kdc",=20
+    c->allow_null_ticket_addresses =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->allow_null_ticket_addresses,
+				     "kdc",
 				     "allow-null-ticket-addresses", NULL);
=20
-    c->allow_anonymous =3D=20
-	krb5_config_get_bool_default(context, NULL,=20
+    c->allow_anonymous =3D
+	krb5_config_get_bool_default(context, NULL,
 				     c->allow_anonymous,
-				     "kdc",=20
+				     "kdc",
 				     "allow-anonymous", NULL);
=20
     c->max_datagram_reply_length =3D
-	krb5_config_get_int_default(context,=20
-				    NULL,=20
+	krb5_config_get_int_default(context,
+				    NULL,
 				    1400,
 				    "kdc",
 				    "max-kdc-datagram-reply-length",
@@ -158,8 +169,8 @@
     {
 	const char *trpolicy_str;
=20
-	trpolicy_str =3D=20
-	    krb5_config_get_string_default(context, NULL, "DEFAULT", "kdc",=20
+	trpolicy_str =3D
+	    krb5_config_get_string_default(context, NULL, "DEFAULT", "kdc",
 					   "transited-policy", NULL);
 	if(strcasecmp(trpolicy_str, "always-check") =3D=3D 0) {
 	    c->trpolicy =3D TRPOLICY_ALWAYS_CHECK;
@@ -167,119 +178,110 @@
 	    c->trpolicy =3D TRPOLICY_ALLOW_PER_PRINCIPAL;
 	} else if(strcasecmp(trpolicy_str, "always-honour-request") =3D=3D 0) {
 	    c->trpolicy =3D TRPOLICY_ALWAYS_HONOUR_REQUEST;
-	} else if(strcasecmp(trpolicy_str, "DEFAULT") =3D=3D 0) {=20
+	} else if(strcasecmp(trpolicy_str, "DEFAULT") =3D=3D 0) {
 	    /* default */
 	} else {
 	    kdc_log(context, c, 0,
 		    "unknown transited-policy: %s, "
-		    "reverting to default (always-check)",=20
+		    "reverting to default (always-check)",
 		    trpolicy_str);
 	}
     }
=20
-    {
-	const char *p;
-	p =3D krb5_config_get_string (context, NULL,=20
-				    "kdc",
-				    "v4-realm",
-				    NULL);
-	if(p !=3D NULL) {
-	    c->v4_realm =3D strdup(p);
-	    if (c->v4_realm =3D=3D NULL)
-		krb5_errx(context, 1, "out of memory");
-	} else {
-	    c->v4_realm =3D NULL;
-	}
-    }
+    c->encode_as_rep_as_tgs_rep =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->encode_as_rep_as_tgs_rep,
+				     "kdc",
+				     "encode_as_rep_as_tgs_rep", NULL);
=20
-    c->enable_kaserver =3D=20
-	krb5_config_get_bool_default(context,=20
-				     NULL,=20
-				     c->enable_kaserver,
-				     "kdc", "enable-kaserver", NULL);
-
-
-    c->encode_as_rep_as_tgs_rep =3D
-	krb5_config_get_bool_default(context, NULL,=20
-				     c->encode_as_rep_as_tgs_rep,=20
-				     "kdc",=20
-				     "encode_as_rep_as_tgs_rep", NULL);
-   =20
     c->kdc_warn_pwexpire =3D
 	krb5_config_get_time_default (context, NULL,
 				      c->kdc_warn_pwexpire,
 				      "kdc", "kdc_warn_pwexpire", NULL);
=20
=20
-#ifdef PKINIT
-    c->enable_pkinit =3D=20
-	krb5_config_get_bool_default(context,=20
-				     NULL,=20
+    c->enable_pkinit =3D
+	krb5_config_get_bool_default(context,
+				     NULL,
 				     c->enable_pkinit,
 				     "kdc",
 				     "enable-pkinit",
 				     NULL);
-    if (c->enable_pkinit) {
-	const char *user_id, *anchors, *ocsp_file;
-	char **pool_list, **revoke_list;
=20
-	user_id =3D=20
-	    krb5_config_get_string(context, NULL,
-				   "kdc", "pkinit_identity", NULL);
-	if (user_id =3D=3D NULL)
-	    krb5_errx(context, 1, "pkinit enabled but no identity");
=20
-	anchors =3D krb5_config_get_string(context, NULL,
-					 "kdc", "pkinit_anchors", NULL);
-	if (anchors =3D=3D NULL)
-	    krb5_errx(context, 1, "pkinit enabled but no X509 anchors");
-
-	pool_list =3D
-	    krb5_config_get_strings(context, NULL,
-				    "kdc", "pkinit_pool", NULL);
-
-	revoke_list =3D
-	    krb5_config_get_strings(context, NULL,
-				    "kdc", "pkinit_revoke", NULL);
-
-	ocsp_file =3D=20
-	    krb5_config_get_string(context, NULL,
-				   "kdc", "pkinit_kdc_ocsp", NULL);
-	if (ocsp_file) {
-	    c->pkinit_kdc_ocsp_file =3D strdup(ocsp_file);
-	    if (c->pkinit_kdc_ocsp_file =3D=3D NULL)
-		krb5_errx(context, 1, "out of memory");
-	}
-
-	_kdc_pk_initialize(context, c, user_id, anchors,=20
-			   pool_list, revoke_list);
-
-	krb5_config_free_strings(pool_list);
-	krb5_config_free_strings(revoke_list);
-
-	c->pkinit_princ_in_cert =3D=20
-	    krb5_config_get_bool_default(context, NULL,
-					 c->pkinit_princ_in_cert,
-					 "kdc",
-					 "pkinit_principal_in_certificate",
-					 NULL);
-
-	c->pkinit_require_binding =3D=20
-	    krb5_config_get_bool_default(context, NULL,
-					 c->pkinit_require_binding,
-					 "kdc",
-					 "pkinit_win2k_require_binding",
-					 NULL);
-    }
-
+    c->pkinit_kdc_identity =3D
+	krb5_config_get_string(context, NULL,
+			       "kdc", "pkinit_identity", NULL);
+    c->pkinit_kdc_anchors =3D
+	krb5_config_get_string(context, NULL,
+			       "kdc", "pkinit_anchors", NULL);
+    c->pkinit_kdc_cert_pool =3D
+	krb5_config_get_strings(context, NULL,
+				"kdc", "pkinit_pool", NULL);
+    c->pkinit_kdc_revoke =3D
+	krb5_config_get_strings(context, NULL,
+				"kdc", "pkinit_revoke", NULL);
+    c->pkinit_kdc_ocsp_file =3D
+	krb5_config_get_string(context, NULL,
+			       "kdc", "pkinit_kdc_ocsp", NULL);
+    c->pkinit_kdc_friendly_name =3D
+	krb5_config_get_string(context, NULL,
+			       "kdc", "pkinit_kdc_friendly_name", NULL);
+    c->pkinit_princ_in_cert =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->pkinit_princ_in_cert,
+				     "kdc",
+				     "pkinit_principal_in_certificate",
+				     NULL);
+    c->pkinit_require_binding =3D
+	krb5_config_get_bool_default(context, NULL,
+				     c->pkinit_require_binding,
+				     "kdc",
+				     "pkinit_win2k_require_binding",
+				     NULL);
     c->pkinit_dh_min_bits =3D
-	krb5_config_get_int_default(context, NULL,=20
+	krb5_config_get_int_default(context, NULL,
 				    0,
 				    "kdc", "pkinit_dh_min_bits", NULL);
=20
-#endif
-
     *config =3D c;
=20
     return 0;
 }
+
+krb5_error_code
+krb5_kdc_pkinit_config(krb5_context context, krb5_kdc_configuration *confi=
g)
+{
+#ifdef PKINIT
+#ifdef __APPLE__
+    config->enable_pkinit =3D 1;
+
+    if (config->pkinit_kdc_identity =3D=3D NULL) {
+	if (config->pkinit_kdc_friendly_name =3D=3D NULL)
+	    config->pkinit_kdc_friendly_name =3D
+		strdup("O=3DSystem Identity,CN=3Dcom.apple.kerberos.kdc");
+	config->pkinit_kdc_identity =3D strdup("KEYCHAIN:");
+    }
+    if (config->pkinit_kdc_anchors =3D=3D NULL)
+	config->pkinit_kdc_anchors =3D strdup("KEYCHAIN:");
+
+#endif /* __APPLE__ */
+
+    if (config->enable_pkinit) {
+	if (config->pkinit_kdc_identity =3D=3D NULL)
+	    krb5_errx(context, 1, "pkinit enabled but no identity");
+
+	if (config->pkinit_kdc_anchors =3D=3D NULL)
+	    krb5_errx(context, 1, "pkinit enabled but no X509 anchors");
+
+	krb5_kdc_pk_initialize(context, config,
+			       config->pkinit_kdc_identity,
+			       config->pkinit_kdc_anchors,
+			       config->pkinit_kdc_cert_pool,
+			       config->pkinit_kdc_revoke);
+
+    }
+
+    return 0;
+#endif /* PKINIT */
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/digest.c
--- a/head/crypto/heimdal/kdc/digest.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/digest.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
 #include <hex.h>
=20
-RCSID("$Id: digest.c 22374 2007-12-28 18:36:52Z lha $");
+#ifdef DIGEST
=20
 #define MS_CHAP_V2	0x20
 #define CHAP_MD5	0x10
@@ -44,13 +44,13 @@
 #define NTLM_V1		0x01
=20
 const struct units _kdc_digestunits[] =3D {
-	{"ms-chap-v2",		1U << 5},
-	{"chap-md5",		1U << 4},
-	{"digest-md5",		1U << 3},
-	{"ntlm-v2",		1U << 2},
-	{"ntlm-v1-session",	1U << 1},
-	{"ntlm-v1",		1U << 0},
-	{NULL,	0}
+    {"ms-chap-v2",		1U << 5},
+    {"chap-md5",		1U << 4},
+    {"digest-md5",		1U << 3},
+    {"ntlm-v2",		1U << 2},
+    {"ntlm-v1-session",	1U << 1},
+    {"ntlm-v1",		1U << 0},
+    {NULL,	0}
 };
=20
=20
@@ -63,7 +63,7 @@
     krb5_error_code ret;
     krb5_enctype enctype;
     Key *key;
-   =20
+
     ret =3D _kdc_get_preferred_key(context,
 				 config,
 				 server,
@@ -115,17 +115,17 @@
     ti.domainname =3D targetname;
     p =3D client->entry.principal;
     str =3D krb5_principal_get_comp_string(context, p, 0);
-    if (str !=3D NULL &&=20
-	(strcmp("host", str) =3D=3D 0 ||=20
+    if (str !=3D NULL &&
+	(strcmp("host", str) =3D=3D 0 ||
 	 strcmp("ftp", str) =3D=3D 0 ||
 	 strcmp("imap", str) =3D=3D 0 ||
 	 strcmp("pop", str) =3D=3D 0 ||
 	 strcmp("smtp", str)))
-    {
-	str =3D krb5_principal_get_comp_string(context, p, 1);
-	ti.dnsservername =3D rk_UNCONST(str);
-    }
-   =20
+	{
+	    str =3D krb5_principal_get_comp_string(context, p, 1);
+	    ti.dnsservername =3D rk_UNCONST(str);
+	}
+
     ret =3D heim_ntlm_encode_targetinfo(&ti, 1, &d);
     if (ret)
 	return ret;
@@ -177,7 +177,7 @@
 	return ret;
=20
     ret =3D _kdc_db_fetch(context, config, clientprincipal,
-			HDB_F_GET_CLIENT, &db, &user);
+			HDB_F_GET_CLIENT, NULL, &db, &user);
     krb5_free_principal(context, clientprincipal);
     if (ret)
 	return ret;
@@ -186,7 +186,7 @@
     if (ret || password =3D=3D NULL) {
 	if (ret =3D=3D 0) {
 	    ret =3D EINVAL;
-	    krb5_set_error_string(context, "password missing");
+	    krb5_set_error_message(context, ret, "password missing");
 	}
 	memset(user, 0, sizeof(*user));
     }
@@ -199,9 +199,9 @@
  */
=20
 krb5_error_code
-_kdc_do_digest(krb5_context context,=20
+_kdc_do_digest(krb5_context context,
 	       krb5_kdc_configuration *config,
-	       const DigestREQ *req, krb5_data *reply,
+	       const struct DigestREQ *req, krb5_data *reply,
 	       const char *from, struct sockaddr *addr)
 {
     krb5_error_code ret =3D 0;
@@ -223,7 +223,7 @@
     krb5_data serverNonce;
=20
     if(!config->enable_digest) {
-	kdc_log(context, config, 0,=20
+	kdc_log(context, config, 0,
 		"Rejected digest request (disabled) from %s", from);
 	return KRB5KDC_ERR_POLICY;
     }
@@ -234,6 +234,7 @@
     memset(&ireq, 0, sizeof(ireq));
     memset(&r, 0, sizeof(r));
     memset(&rep, 0, sizeof(rep));
+    memset(&res, 0, sizeof(res));
=20
     kdc_log(context, config, 0, "Digest request from %s", from);
=20
@@ -243,7 +244,7 @@
 	goto out;
     }
=20
-    ret =3D krb5_rd_req(context,=20
+    ret =3D krb5_rd_req(context,
 		      &ac,
 		      &req->apReq,
 		      NULL,
@@ -256,14 +257,14 @@
     /* check the server principal in the ticket matches digest/R at R */
     {
 	krb5_principal principal =3D NULL;
-	const char *p, *r;
+	const char *p, *rr;
=20
 	ret =3D krb5_ticket_get_server(context, ticket, &principal);
 	if (ret)
 	    goto out;
=20
 	ret =3D EINVAL;
-	krb5_set_error_string(context, "Wrong digest server principal used");
+	krb5_set_error_message(context, ret, "Wrong digest server principal used"=
);
 	p =3D krb5_principal_get_comp_string(context, principal, 0);
 	if (p =3D=3D NULL) {
 	    krb5_free_principal(context, principal);
@@ -279,19 +280,19 @@
 	    krb5_free_principal(context, principal);
 	    goto out;
 	}
-	r =3D krb5_principal_get_realm(context, principal);
-	if (r =3D=3D NULL) {
+	rr =3D krb5_principal_get_realm(context, principal);
+	if (rr =3D=3D NULL) {
 	    krb5_free_principal(context, principal);
 	    goto out;
 	}
-	if (strcmp(p, r) !=3D 0) {
+	if (strcmp(p, rr) !=3D 0) {
 	    krb5_free_principal(context, principal);
 	    goto out;
 	}
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
=20
 	ret =3D _kdc_db_fetch(context, config, principal,
-			    HDB_F_GET_SERVER, NULL, &server);
+			    HDB_F_GET_SERVER, NULL, NULL, &server);
 	if (ret)
 	    goto out;
=20
@@ -313,19 +314,19 @@
 	}
=20
 	ret =3D _kdc_db_fetch(context, config, principal,
-			    HDB_F_GET_CLIENT, NULL, &client);
+			    HDB_F_GET_CLIENT, NULL, NULL, &client);
 	krb5_free_principal(context, principal);
 	if (ret)
 	    goto out;
=20
 	if (client->entry.flags.allow_digest =3D=3D 0) {
-	    kdc_log(context, config, 0,=20
+	    kdc_log(context, config, 0,
 		    "Client %s tried to use digest "
-		    "but is not allowed to",=20
+		    "but is not allowed to",
 		    client_name);
-	    krb5_set_error_string(context,=20
-				  "Client is not permitted to use digest");
 	    ret =3D KRB5KDC_ERR_POLICY;
+	    krb5_set_error_message(context, ret,
+				   "Client is not permitted to use digest");
 	    goto out;
 	}
     }
@@ -338,8 +339,8 @@
 	if (ret)
 	    goto out;
 	if (key =3D=3D NULL) {
-	    krb5_set_error_string(context, "digest: remote subkey not found");
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret, "digest: remote subkey not found=
");
 	    goto out;
 	}
=20
@@ -355,15 +356,15 @@
     crypto =3D NULL;
     if (ret)
 	goto out;
-	  =20
+
     ret =3D decode_DigestReqInner(buf.data, buf.length, &ireq, NULL);
     krb5_data_free(&buf);
     if (ret) {
-	krb5_set_error_string(context, "Failed to decode digest inner request");
+	krb5_set_error_message(context, ret, "Failed to decode digest inner reque=
st");
 	goto out;
     }
=20
-    kdc_log(context, config, 0, "Valid digest request from %s (%s)",=20
+    kdc_log(context, config, 0, "Valid digest request from %s (%s)",
 	    client_name, from);
=20
     /*
@@ -386,20 +387,20 @@
=20
 	hex_encode(server_nonce, sizeof(server_nonce), &r.u.initReply.nonce);
 	if (r.u.initReply.nonce =3D=3D NULL) {
-	    krb5_set_error_string(context, "Failed to decode server nonce");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "Failed to decode server nonce");
 	    goto out;
 	}
=20
 	sp =3D krb5_storage_emem();
 	if (sp =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "out of memory");
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	ret =3D krb5_store_stringz(sp, ireq.u.init.type);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
@@ -410,34 +411,34 @@
 		     ireq.u.init.channel->cb_type,
 		     ireq.u.init.channel->cb_binding);
 	    if (s =3D=3D NULL) {
-		krb5_set_error_string(context, "Failed to allocate "
-				      "channel binding");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret,
+				       "Failed to allocate channel binding");
 		goto out;
 	    }
 	    free(r.u.initReply.nonce);
 	    r.u.initReply.nonce =3D s;
 	}
-=09
+
 	ret =3D krb5_store_stringz(sp, r.u.initReply.nonce);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
 	if (strcasecmp(ireq.u.init.type, "CHAP") =3D=3D 0) {
-	    r.u.initReply.identifier =3D=20
+	    r.u.initReply.identifier =3D
 		malloc(sizeof(*r.u.initReply.identifier));
 	    if (r.u.initReply.identifier =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
=20
 	    asprintf(r.u.initReply.identifier, "%02X", identifier & 0xff);
 	    if (*r.u.initReply.identifier =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
=20
@@ -447,14 +448,14 @@
 	if (ireq.u.init.hostname) {
 	    ret =3D krb5_store_stringz(sp, *ireq.u.init.hostname);
 	    if (ret) {
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		goto out;
 	    }
 	}
=20
 	ret =3D krb5_storage_to_data(sp, &buf);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
@@ -474,12 +475,12 @@
 	krb5_data_free(&buf);
 	if (ret)
 	    goto out;
-=09
+
 	ASN1_MALLOC_ENCODE(Checksum, buf.data, buf.length, &res, &size, ret);
 	free_Checksum(&res);
 	if (ret) {
-	    krb5_set_error_string(context, "Failed to encode "
-				  "checksum in digest request");
+	    krb5_set_error_message(context, ret, "Failed to encode "
+				   "checksum in digest request");
 	    goto out;
 	}
 	if (size !=3D buf.length)
@@ -487,8 +488,9 @@
=20
 	hex_encode(buf.data, buf.length, &r.u.initReply.opaque);
 	free(buf.data);
+	krb5_data_zero(&buf);
 	if (r.u.initReply.opaque =3D=3D NULL) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    ret =3D ENOMEM;
 	    goto out;
 	}
@@ -502,12 +504,12 @@
 	sp =3D krb5_storage_emem();
 	if (sp =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "out of memory");
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	ret =3D krb5_store_stringz(sp, ireq.u.digestRequest.type);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
@@ -516,7 +518,7 @@
 	if (ireq.u.digestRequest.hostname) {
 	    ret =3D krb5_store_stringz(sp, *ireq.u.digestRequest.hostname);
 	    if (ret) {
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		goto out;
 	    }
 	}
@@ -524,52 +526,54 @@
 	buf.length =3D strlen(ireq.u.digestRequest.opaque);
 	buf.data =3D malloc(buf.length);
 	if (buf.data =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
=20
 	ret =3D hex_decode(ireq.u.digestRequest.opaque, buf.data, buf.length);
 	if (ret <=3D 0) {
-	    krb5_set_error_string(context, "Failed to decode opaque");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "Failed to decode opaque");
 	    goto out;
 	}
 	buf.length =3D ret;
=20
 	ret =3D decode_Checksum(buf.data, buf.length, &res, NULL);
 	free(buf.data);
+	krb5_data_zero(&buf);
 	if (ret) {
-	    krb5_set_error_string(context, "Failed to decode digest Checksum");
+	    krb5_set_error_message(context, ret,
+				   "Failed to decode digest Checksum");
 	    goto out;
 	}
-=09
+
 	ret =3D krb5_storage_to_data(sp, &buf);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
 	serverNonce.length =3D strlen(ireq.u.digestRequest.serverNonce);
 	serverNonce.data =3D malloc(serverNonce.length);
 	if (serverNonce.data =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
-	   =20
+
 	/*
 	 * CHAP does the checksum of the raw nonce, but do it for all
 	 * types, since we need to check the timestamp.
 	 */
 	{
 	    ssize_t ssize;
-	   =20
-	    ssize =3D hex_decode(ireq.u.digestRequest.serverNonce,=20
+
+	    ssize =3D hex_decode(ireq.u.digestRequest.serverNonce,
 			       serverNonce.data, serverNonce.length);
 	    if (ssize <=3D 0) {
-		krb5_set_error_string(context, "Failed to decode serverNonce");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "Failed to decode serverNonce");
 		goto out;
 	    }
 	    serverNonce.length =3D ssize;
@@ -579,9 +583,11 @@
 	if (ret)
 	    goto out;
=20
-	ret =3D krb5_verify_checksum(context, crypto,=20
+	ret =3D krb5_verify_checksum(context, crypto,
 				   KRB5_KU_DIGEST_OPAQUE,
 				   buf.data, buf.length, &res);
+	free_Checksum(&res);
+	krb5_data_free(&buf);
 	krb5_crypto_destroy(context, crypto);
 	crypto =3D NULL;
 	if (ret)
@@ -591,26 +597,26 @@
 	{
 	    unsigned char *p =3D serverNonce.data;
 	    uint32_t t;
-	   =20
+
 	    if (serverNonce.length < 4) {
-		krb5_set_error_string(context, "server nonce too short");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret, "server nonce too short");
 		goto out;
 	    }
 	    t =3D p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
=20
 	    if (abs((kdc_time & 0xffffffff) - t) > context->max_skew) {
-		krb5_set_error_string(context, "time screw in server nonce ");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret, "time screw in server nonce ");
 		goto out;
 	    }
 	}
=20
 	if (strcasecmp(ireq.u.digestRequest.type, "CHAP") =3D=3D 0) {
-	    MD5_CTX ctx;
+	    EVP_MD_CTX *ctx;
 	    unsigned char md[MD5_DIGEST_LENGTH];
 	    char *mdx;
-	    char id;
+	    char idx;
=20
 	    if ((config->digests_allowed & CHAP_MD5) =3D=3D 0) {
 		kdc_log(context, config, 0, "Digest CHAP MD5 not allowed");
@@ -618,33 +624,37 @@
 	    }
=20
 	    if (ireq.u.digestRequest.identifier =3D=3D NULL) {
-		krb5_set_error_string(context, "Identifier missing "
-				      "from CHAP request");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret, "Identifier missing "
+				       "from CHAP request");
 		goto out;
 	    }
-	   =20
-	    if (hex_decode(*ireq.u.digestRequest.identifier, &id, 1) !=3D 1) {
-		krb5_set_error_string(context, "failed to decode identifier");
+
+	    if (hex_decode(*ireq.u.digestRequest.identifier, &idx, 1) !=3D 1) {
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret, "failed to decode identifier");
 		goto out;
 	    }
-	   =20
-	    ret =3D get_password_entry(context, config,=20
+
+	    ret =3D get_password_entry(context, config,
 				     ireq.u.digestRequest.username,
 				     &password);
 	    if (ret)
 		goto out;
=20
-	    MD5_Init(&ctx);
-	    MD5_Update(&ctx, &id, 1);
-	    MD5_Update(&ctx, password, strlen(password));
-	    MD5_Update(&ctx, serverNonce.data, serverNonce.length);
-	    MD5_Final(md, &ctx);
+	    ctx =3D EVP_MD_CTX_create();
+
+	    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+	    EVP_DigestUpdate(ctx, &idx, 1);
+	    EVP_DigestUpdate(ctx, password, strlen(password));
+	    EVP_DigestUpdate(ctx, serverNonce.data, serverNonce.length);
+	    EVP_DigestFinal_ex(ctx, md, NULL);
+
+	    EVP_MD_CTX_destroy(ctx);
=20
 	    hex_encode(md, sizeof(md), &mdx);
 	    if (mdx =3D=3D NULL) {
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		ret =3D ENOMEM;
 		goto out;
 	    }
@@ -656,14 +666,14 @@
 	    if (ret =3D=3D 0) {
 		r.u.response.success =3D TRUE;
 	    } else {
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"CHAP reply mismatch for %s",
 			ireq.u.digestRequest.username);
 		r.u.response.success =3D FALSE;
 	    }
=20
 	} else if (strcasecmp(ireq.u.digestRequest.type, "SASL-DIGEST-MD5") =3D=
=3D 0) {
-	    MD5_CTX ctx;
+	    EVP_MD_CTX *ctx;
 	    unsigned char md[MD5_DIGEST_LENGTH];
 	    char *mdx;
 	    char *A1, *A2;
@@ -673,97 +683,104 @@
 		goto out;
 	    }
=20
-	    if (ireq.u.digestRequest.nonceCount =3D=3D NULL)=20
+	    if (ireq.u.digestRequest.nonceCount =3D=3D NULL)
 		goto out;
-	    if (ireq.u.digestRequest.clientNonce =3D=3D NULL)=20
+	    if (ireq.u.digestRequest.clientNonce =3D=3D NULL)
 		goto out;
-	    if (ireq.u.digestRequest.qop =3D=3D NULL)=20
+	    if (ireq.u.digestRequest.qop =3D=3D NULL)
 		goto out;
-	    if (ireq.u.digestRequest.realm =3D=3D NULL)=20
+	    if (ireq.u.digestRequest.realm =3D=3D NULL)
 		goto out;
-	   =20
-	    ret =3D get_password_entry(context, config,=20
+
+	    ret =3D get_password_entry(context, config,
 				     ireq.u.digestRequest.username,
 				     &password);
 	    if (ret)
 		goto failed;
=20
-	    MD5_Init(&ctx);
-	    MD5_Update(&ctx, ireq.u.digestRequest.username,
+	    ctx =3D EVP_MD_CTX_create();
+
+	    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+	    EVP_DigestUpdate(ctx, ireq.u.digestRequest.username,
 		       strlen(ireq.u.digestRequest.username));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, *ireq.u.digestRequest.realm,
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, *ireq.u.digestRequest.realm,
 		       strlen(*ireq.u.digestRequest.realm));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, password, strlen(password));
-	    MD5_Final(md, &ctx);
-	   =20
-	    MD5_Init(&ctx);
-	    MD5_Update(&ctx, md, sizeof(md));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, ireq.u.digestRequest.serverNonce,
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, password, strlen(password));
+	    EVP_DigestFinal_ex(ctx, md, NULL);
+
+	    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+	    EVP_DigestUpdate(ctx, md, sizeof(md));
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, ireq.u.digestRequest.serverNonce,
 		       strlen(ireq.u.digestRequest.serverNonce));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, *ireq.u.digestRequest.nonceCount,
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, *ireq.u.digestRequest.nonceCount,
 		       strlen(*ireq.u.digestRequest.nonceCount));
 	    if (ireq.u.digestRequest.authid) {
-		MD5_Update(&ctx, ":", 1);
-		MD5_Update(&ctx, *ireq.u.digestRequest.authid,
+		EVP_DigestUpdate(ctx, ":", 1);
+		EVP_DigestUpdate(ctx, *ireq.u.digestRequest.authid,
 			   strlen(*ireq.u.digestRequest.authid));
 	    }
-	    MD5_Final(md, &ctx);
+	    EVP_DigestFinal_ex(ctx, md, NULL);
 	    hex_encode(md, sizeof(md), &A1);
 	    if (A1 =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
+		EVP_MD_CTX_destroy(ctx);
 		goto failed;
 	    }
-	   =20
-	    MD5_Init(&ctx);
-	    MD5_Update(&ctx, "AUTHENTICATE:", sizeof("AUTHENTICATE:") - 1);
-	    MD5_Update(&ctx, *ireq.u.digestRequest.uri,
+
+	    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+	    EVP_DigestUpdate(ctx,
+			     "AUTHENTICATE:", sizeof("AUTHENTICATE:") - 1);
+	    EVP_DigestUpdate(ctx, *ireq.u.digestRequest.uri,
 		       strlen(*ireq.u.digestRequest.uri));
-=09
+
 	    /* conf|int */
 	    if (strcmp(ireq.u.digestRequest.digest, "clear") !=3D 0) {
 		static char conf_zeros[] =3D ":00000000000000000000000000000000";
-		MD5_Update(&ctx, conf_zeros, sizeof(conf_zeros) - 1);
+		EVP_DigestUpdate(ctx, conf_zeros, sizeof(conf_zeros) - 1);
 	    }
-	   =20
-	    MD5_Final(md, &ctx);
+
+	    EVP_DigestFinal_ex(ctx, md, NULL);
+
 	    hex_encode(md, sizeof(md), &A2);
 	    if (A2 =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		free(A1);
 		goto failed;
 	    }
=20
-	    MD5_Init(&ctx);
-	    MD5_Update(&ctx, A1, strlen(A2));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, ireq.u.digestRequest.serverNonce,
+	    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+	    EVP_DigestUpdate(ctx, A1, strlen(A2));
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, ireq.u.digestRequest.serverNonce,
 		       strlen(ireq.u.digestRequest.serverNonce));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, *ireq.u.digestRequest.nonceCount,
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, *ireq.u.digestRequest.nonceCount,
 		       strlen(*ireq.u.digestRequest.nonceCount));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, *ireq.u.digestRequest.clientNonce,
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, *ireq.u.digestRequest.clientNonce,
 		       strlen(*ireq.u.digestRequest.clientNonce));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, *ireq.u.digestRequest.qop,
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, *ireq.u.digestRequest.qop,
 		       strlen(*ireq.u.digestRequest.qop));
-	    MD5_Update(&ctx, ":", 1);
-	    MD5_Update(&ctx, A2, strlen(A2));
+	    EVP_DigestUpdate(ctx, ":", 1);
+	    EVP_DigestUpdate(ctx, A2, strlen(A2));
=20
-	    MD5_Final(md, &ctx);
+	    EVP_DigestFinal_ex(ctx, md, NULL);
+
+	    EVP_MD_CTX_destroy(ctx);
=20
 	    free(A1);
 	    free(A2);
=20
 	    hex_encode(md, sizeof(md), &mdx);
 	    if (mdx =3D=3D NULL) {
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		ret =3D ENOMEM;
 		goto out;
 	    }
@@ -774,7 +791,7 @@
 	    if (ret =3D=3D 0) {
 		r.u.response.success =3D TRUE;
 	    } else {
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"DIGEST-MD5 reply mismatch for %s",
 			ireq.u.digestRequest.username);
 		r.u.response.success =3D FALSE;
@@ -787,7 +804,7 @@
 	    const char *username;
 	    struct ntlm_buf answer;
 	    Key *key =3D NULL;
-	    SHA_CTX ctx;
+	    EVP_MD_CTX *ctp;
=20
 	    if ((config->digests_allowed & MS_CHAP_V2) =3D=3D 0) {
 		kdc_log(context, config, 0, "MS-CHAP-V2 not allowed");
@@ -795,15 +812,15 @@
 	    }
=20
 	    if (ireq.u.digestRequest.clientNonce =3D=3D NULL)  {
-		krb5_set_error_string(context,=20
-				      "MS-CHAP-V2 clientNonce missing");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       "MS-CHAP-V2 clientNonce missing");
 		goto failed;
-	    }	   =20
+	    }
 	    if (serverNonce.length !=3D 16) {
-		krb5_set_error_string(context,=20
-				      "MS-CHAP-V2 serverNonce wrong length");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       "MS-CHAP-V2 serverNonce wrong length");
 		goto failed;
 	    }
=20
@@ -814,56 +831,64 @@
 	    else
 		username++;
=20
+	    ctp =3D EVP_MD_CTX_create();
+
 	    /* ChallangeHash */
-	    SHA1_Init(&ctx);
+	    EVP_DigestInit_ex(ctp, EVP_sha1(), NULL);
 	    {
 		ssize_t ssize;
 		krb5_data clientNonce;
-	=09
+
 		clientNonce.length =3D strlen(*ireq.u.digestRequest.clientNonce);
 		clientNonce.data =3D malloc(clientNonce.length);
 		if (clientNonce.data =3D=3D NULL) {
 		    ret =3D ENOMEM;
-		    krb5_set_error_string(context, "out of memory");
+		    krb5_set_error_message(context, ret,
+					   "malloc: out of memory");
+		    EVP_MD_CTX_destroy(ctp);
 		    goto out;
 		}
=20
-		ssize =3D hex_decode(*ireq.u.digestRequest.clientNonce,=20
+		ssize =3D hex_decode(*ireq.u.digestRequest.clientNonce,
 				   clientNonce.data, clientNonce.length);
 		if (ssize !=3D 16) {
-		    krb5_set_error_string(context,=20
-					  "Failed to decode clientNonce");
 		    ret =3D ENOMEM;
+		    krb5_set_error_message(context, ret,
+					   "Failed to decode clientNonce");
+		    EVP_MD_CTX_destroy(ctp);
 		    goto out;
 		}
-		SHA1_Update(&ctx, clientNonce.data, ssize);
+		EVP_DigestUpdate(ctp, clientNonce.data, ssize);
 		free(clientNonce.data);
 	    }
-	    SHA1_Update(&ctx, serverNonce.data, serverNonce.length);
-	    SHA1_Update(&ctx, username, strlen(username));
-	    SHA1_Final(challange, &ctx);
+	    EVP_DigestUpdate(ctp, serverNonce.data, serverNonce.length);
+	    EVP_DigestUpdate(ctp, username, strlen(username));
+
+	    EVP_DigestFinal_ex(ctp, challange, NULL);
+
+	    EVP_MD_CTX_destroy(ctp);
=20
 	    /* NtPasswordHash */
 	    ret =3D krb5_parse_name(context, username, &clientprincipal);
 	    if (ret)
 		goto failed;
-	   =20
+
 	    ret =3D _kdc_db_fetch(context, config, clientprincipal,
-				HDB_F_GET_CLIENT, NULL, &user);
+				HDB_F_GET_CLIENT, NULL, NULL, &user);
 	    krb5_free_principal(context, clientprincipal);
 	    if (ret) {
-		krb5_set_error_string(context,=20
-				      "MS-CHAP-V2 user %s not in database",
-				      username);
+		krb5_set_error_message(context, ret,
+				       "MS-CHAP-V2 user %s not in database",
+				       username);
 		goto failed;
 	    }
=20
-	    ret =3D hdb_enctype2key(context, &user->entry,=20
+	    ret =3D hdb_enctype2key(context, &user->entry,
 				  ETYPE_ARCFOUR_HMAC_MD5, &key);
 	    if (ret) {
-		krb5_set_error_string(context,=20
-				      "MS-CHAP-V2 missing arcfour key %s",
-				      username);
+		krb5_set_error_message(context, ret,
+				       "MS-CHAP-V2 missing arcfour key %s",
+				       username);
 		goto failed;
 	    }
=20
@@ -872,14 +897,14 @@
 					    key->key.keyvalue.length,
 					    challange, &answer);
 	    if (ret) {
-		krb5_set_error_string(context, "NTLM missing arcfour key");
+		krb5_set_error_message(context, ret, "NTLM missing arcfour key");
 		goto failed;
 	    }
-	   =20
+
 	    hex_encode(answer.data, answer.length, &mdx);
 	    if (mdx =3D=3D NULL) {
 		free(answer.data);
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		ret =3D ENOMEM;
 		goto out;
 	    }
@@ -889,7 +914,7 @@
 	    if (ret =3D=3D 0) {
 		r.u.response.success =3D TRUE;
 	    } else {
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"MS-CHAP-V2 hash mismatch for %s",
 			ireq.u.digestRequest.username);
 		r.u.response.success =3D FALSE;
@@ -898,34 +923,39 @@
=20
 	    if (r.u.response.success) {
 		unsigned char hashhash[MD4_DIGEST_LENGTH];
+		EVP_MD_CTX *ctxp;
+
+		ctxp =3D EVP_MD_CTX_create();
=20
 		/* hashhash */
 		{
-		    MD4_CTX hctx;
-
-		    MD4_Init(&hctx);
-		    MD4_Update(&hctx, key->key.keyvalue.data,=20
-			       key->key.keyvalue.length);
-		    MD4_Final(hashhash, &hctx);
+		    EVP_DigestInit_ex(ctxp, EVP_md4(), NULL);
+		    EVP_DigestUpdate(ctxp,
+				     key->key.keyvalue.data,
+				     key->key.keyvalue.length);
+		    EVP_DigestFinal_ex(ctxp, hashhash, NULL);
 		}
=20
 		/* GenerateAuthenticatorResponse */
-		SHA1_Init(&ctx);
-		SHA1_Update(&ctx, hashhash, sizeof(hashhash));
-		SHA1_Update(&ctx, answer.data, answer.length);
-		SHA1_Update(&ctx, ms_chap_v2_magic1,sizeof(ms_chap_v2_magic1));
-		SHA1_Final(md, &ctx);
+		EVP_DigestInit_ex(ctxp, EVP_sha1(), NULL);
+		EVP_DigestUpdate(ctxp, hashhash, sizeof(hashhash));
+		EVP_DigestUpdate(ctxp, answer.data, answer.length);
+		EVP_DigestUpdate(ctxp, ms_chap_v2_magic1,
+				 sizeof(ms_chap_v2_magic1));
+		EVP_DigestFinal_ex(ctxp, md, NULL);
=20
-		SHA1_Init(&ctx);
-		SHA1_Update(&ctx, md, sizeof(md));
-		SHA1_Update(&ctx, challange, 8);
-		SHA1_Update(&ctx, ms_chap_v2_magic2, sizeof(ms_chap_v2_magic2));
-		SHA1_Final(md, &ctx);
+		EVP_DigestInit_ex(ctxp, EVP_sha1(), NULL);
+		EVP_DigestUpdate(ctxp, md, sizeof(md));
+		EVP_DigestUpdate(ctxp, challange, 8);
+		EVP_DigestUpdate(ctxp, ms_chap_v2_magic2,
+				 sizeof(ms_chap_v2_magic2));
+		EVP_DigestFinal_ex(ctxp, md, NULL);
=20
 		r.u.response.rsp =3D calloc(1, sizeof(*r.u.response.rsp));
 		if (r.u.response.rsp =3D=3D NULL) {
 		    free(answer.data);
-		    krb5_clear_error_string(context);
+		    krb5_clear_error_message(context);
+		    EVP_MD_CTX_destroy(ctxp);
 		    ret =3D ENOMEM;
 		    goto out;
 		}
@@ -933,42 +963,46 @@
 		hex_encode(md, sizeof(md), r.u.response.rsp);
 		if (r.u.response.rsp =3D=3D NULL) {
 		    free(answer.data);
-		    krb5_clear_error_string(context);
+		    krb5_clear_error_message(context);
+		    EVP_MD_CTX_destroy(ctxp);
 		    ret =3D ENOMEM;
 		    goto out;
 		}
=20
 		/* get_master, rfc 3079 3.4 */
-		SHA1_Init(&ctx);
-		SHA1_Update(&ctx, hashhash, 16); /* md4(hash) */
-		SHA1_Update(&ctx, answer.data, answer.length);
-		SHA1_Update(&ctx, ms_rfc3079_magic1, sizeof(ms_rfc3079_magic1));
-		SHA1_Final(md, &ctx);
+		EVP_DigestInit_ex(ctxp, EVP_sha1(), NULL);
+		EVP_DigestUpdate(ctxp, hashhash, 16);
+		EVP_DigestUpdate(ctxp, answer.data, answer.length);
+		EVP_DigestUpdate(ctxp, ms_rfc3079_magic1,
+				 sizeof(ms_rfc3079_magic1));
+		EVP_DigestFinal_ex(ctxp, md, NULL);
=20
 		free(answer.data);
=20
-		r.u.response.session_key =3D=20
+		EVP_MD_CTX_destroy(ctxp);
+
+		r.u.response.session_key =3D
 		    calloc(1, sizeof(*r.u.response.session_key));
 		if (r.u.response.session_key =3D=3D NULL) {
-		    krb5_clear_error_string(context);
+		    krb5_clear_error_message(context);
 		    ret =3D ENOMEM;
 		    goto out;
 		}
=20
 		ret =3D krb5_data_copy(r.u.response.session_key, md, 16);
 		if (ret) {
-		    krb5_clear_error_string(context);
+		    krb5_clear_error_message(context);
 		    goto out;
 		}
 	    }
=20
 	} else {
 	    r.element =3D choice_DigestRepInner_error;
-	    asprintf(&r.u.error.reason, "Unsupported digest type %s",=20
+	    asprintf(&r.u.error.reason, "Unsupported digest type %s",
 		     ireq.u.digestRequest.type);
 	    if (r.u.error.reason =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
 	    r.u.error.code =3D EINVAL;
@@ -1002,7 +1036,7 @@
 	    goto failed;
 	}
=20
-	r.u.ntlmInitReply.flags |=3D=20
+	r.u.ntlmInitReply.flags |=3D
 	    NTLM_NEG_TARGET |
 	    NTLM_TARGET_DOMAIN |
 	    NTLM_ENC_128;
@@ -1018,32 +1052,32 @@
=20
 #undef ALL
=20
-	r.u.ntlmInitReply.targetname =3D=20
+	r.u.ntlmInitReply.targetname =3D
 	    get_ntlm_targetname(context, client);
 	if (r.u.ntlmInitReply.targetname =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	r.u.ntlmInitReply.challange.data =3D malloc(8);
 	if (r.u.ntlmInitReply.challange.data =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	r.u.ntlmInitReply.challange.length =3D 8;
 	if (RAND_bytes(r.u.ntlmInitReply.challange.data,
-		       r.u.ntlmInitReply.challange.length) !=3D 1)=20
-	{
-	    krb5_set_error_string(context, "out of random error");
-	    ret =3D ENOMEM;
-	    goto out;
-	}
+		       r.u.ntlmInitReply.challange.length) !=3D 1)
+	    {
+		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "out of random error");
+		goto out;
+	    }
 	/* XXX fix targetinfo */
 	ALLOC(r.u.ntlmInitReply.targetinfo);
 	if (r.u.ntlmInitReply.targetinfo =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
=20
@@ -1052,37 +1086,37 @@
 			      client,
 			      r.u.ntlmInitReply.targetinfo);
 	if (ret) {
-	    krb5_set_error_string(context, "out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
=20
-	/*=20
+	/*
 	 * Save data encryted in opaque for the second part of the
 	 * ntlm authentication
 	 */
 	sp =3D krb5_storage_emem();
 	if (sp =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "out of memory");
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
-=09
+
 	ret =3D krb5_storage_write(sp, r.u.ntlmInitReply.challange.data, 8);
 	if (ret !=3D 8) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "storage write challange");
+	    krb5_set_error_message(context, ret, "storage write challange");
 	    goto out;
 	}
 	ret =3D krb5_store_uint32(sp, r.u.ntlmInitReply.flags);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
 	ret =3D krb5_storage_to_data(sp, &buf);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
@@ -1109,7 +1143,7 @@
 	uint32_t flags;
 	Key *key =3D NULL;
 	int version;
-	   =20
+
 	r.element =3D choice_DigestRepInner_ntlmResponse;
 	r.u.ntlmResponse.success =3D 0;
 	r.u.ntlmResponse.flags =3D 0;
@@ -1124,11 +1158,11 @@
 	    goto failed;
=20
 	ret =3D _kdc_db_fetch(context, config, clientprincipal,
-			    HDB_F_GET_CLIENT, NULL, &user);
+			    HDB_F_GET_CLIENT, NULL, NULL, &user);
 	krb5_free_principal(context, clientprincipal);
 	if (ret) {
-	    krb5_set_error_string(context, "NTLM user %s not in database",
-				  ireq.u.ntlmRequest.username);
+	    krb5_set_error_message(context, ret, "NTLM user %s not in database",
+				   ireq.u.ntlmRequest.username);
 	    goto failed;
 	}
=20
@@ -1142,7 +1176,7 @@
 	krb5_crypto_destroy(context, crypto);
 	crypto =3D NULL;
 	if (ret) {
-	    kdc_log(context, config, 0,=20
+	    kdc_log(context, config, 0,
 		    "Failed to decrypt nonce from %s", from);
 	    goto failed;
 	}
@@ -1150,33 +1184,35 @@
 	sp =3D krb5_storage_from_data(&buf);
 	if (sp =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "out of memory");
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
-=09
+
 	ret =3D krb5_storage_read(sp, challange, sizeof(challange));
 	if (ret !=3D sizeof(challange)) {
-	    krb5_set_error_string(context, "NTLM storage read challange");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "NTLM storage read challange");
 	    goto out;
 	}
 	ret =3D krb5_ret_uint32(sp, &flags);
 	if (ret) {
-	    krb5_set_error_string(context, "NTLM storage read flags");
+	    krb5_set_error_message(context, ret, "NTLM storage read flags");
 	    goto out;
 	}
+	krb5_storage_free(sp);
+	sp =3D NULL;
 	krb5_data_free(&buf);
=20
 	if ((flags & NTLM_NEG_NTLM) =3D=3D 0) {
 	    ret =3D EINVAL;
-	    krb5_set_error_string(context, "NTLM not negotiated");
+	    krb5_set_error_message(context, ret, "NTLM not negotiated");
 	    goto out;
 	}
=20
-	ret =3D hdb_enctype2key(context, &user->entry,=20
+	ret =3D hdb_enctype2key(context, &user->entry,
 			      ETYPE_ARCFOUR_HMAC_MD5, &key);
 	if (ret) {
-	    krb5_set_error_string(context, "NTLM missing arcfour key");
+	    krb5_set_error_message(context, ret, "NTLM missing arcfour key");
 	    goto out;
 	}
=20
@@ -1194,8 +1230,8 @@
=20
 	    targetname =3D get_ntlm_targetname(context, client);
 	    if (targetname =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
=20
@@ -1213,7 +1249,7 @@
 					 sessionkey);
 	    free(targetname);
 	    if (ret) {
-		krb5_set_error_string(context, "NTLM v2 verify failed");
+		krb5_set_error_message(context, ret, "NTLM v2 verify failed");
 		goto failed;
 	    }
=20
@@ -1229,8 +1265,8 @@
=20
 	    if (flags & NTLM_NEG_NTLM2_SESSION) {
 		unsigned char sessionhash[MD5_DIGEST_LENGTH];
-		MD5_CTX md5ctx;
-	=09
+		EVP_MD_CTX *ctx;
+
 		if ((config->digests_allowed & NTLM_V1_SESSION) =3D=3D 0) {
 		    kdc_log(context, config, 0, "NTLM v1-session not allowed");
 		    ret =3D EINVAL;
@@ -1238,91 +1274,105 @@
 		}
=20
 		if (ireq.u.ntlmRequest.lm.length !=3D 24) {
-		    krb5_set_error_string(context, "LM hash have wrong length "
-					  "for NTLM session key");
 		    ret =3D EINVAL;
+		    krb5_set_error_message(context, ret, "LM hash have wrong length "
+					   "for NTLM session key");
 		    goto failed;
 		}
-	=09
-		MD5_Init(&md5ctx);
-		MD5_Update(&md5ctx, challange, sizeof(challange));
-		MD5_Update(&md5ctx, ireq.u.ntlmRequest.lm.data, 8);
-		MD5_Final(sessionhash, &md5ctx);
+
+		ctx =3D EVP_MD_CTX_create();
+
+		EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+
+		EVP_DigestUpdate(ctx, challange, sizeof(challange));
+		EVP_DigestUpdate(ctx, ireq.u.ntlmRequest.lm.data, 8);
+		EVP_DigestFinal_ex(ctx, sessionhash, NULL);
 		memcpy(challange, sessionhash, sizeof(challange));
+
+		EVP_MD_CTX_destroy(ctx);
+
 	    } else {
 		if ((config->digests_allowed & NTLM_V1) =3D=3D 0) {
 		    kdc_log(context, config, 0, "NTLM v1 not allowed");
 		    goto failed;
 		}
 	    }
-	   =20
+
 	    ret =3D heim_ntlm_calculate_ntlm1(key->key.keyvalue.data,
 					    key->key.keyvalue.length,
 					    challange, &answer);
 	    if (ret) {
-		krb5_set_error_string(context, "NTLM missing arcfour key");
+		krb5_set_error_message(context, ret, "NTLM missing arcfour key");
 		goto failed;
 	    }
-	   =20
+
 	    if (ireq.u.ntlmRequest.ntlm.length !=3D answer.length ||
 		memcmp(ireq.u.ntlmRequest.ntlm.data, answer.data, answer.length) !=3D 0)
-	    {
-		free(answer.data);
-		ret =3D EINVAL;
-		krb5_set_error_string(context, "NTLM hash mismatch");
-		goto failed;
-	    }
+		{
+		    free(answer.data);
+		    ret =3D EINVAL;
+		    krb5_set_error_message(context, ret, "NTLM hash mismatch");
+		    goto failed;
+		}
 	    free(answer.data);
=20
 	    {
-		MD4_CTX ctx;
+		EVP_MD_CTX *ctx;
=20
-		MD4_Init(&ctx);
-		MD4_Update(&ctx,=20
-			   key->key.keyvalue.data, key->key.keyvalue.length);
-		MD4_Final(sessionkey, &ctx);
+		ctx =3D EVP_MD_CTX_create();
+
+		EVP_DigestInit_ex(ctx, EVP_md4(), NULL);
+		EVP_DigestUpdate(ctx,
+				 key->key.keyvalue.data,
+				 key->key.keyvalue.length);
+		EVP_DigestFinal_ex(ctx, sessionkey, NULL);
+
+		EVP_MD_CTX_destroy(ctx);
 	    }
 	}
=20
 	if (ireq.u.ntlmRequest.sessionkey) {
 	    unsigned char masterkey[MD4_DIGEST_LENGTH];
-	    RC4_KEY rc4;
+	    EVP_CIPHER_CTX rc4;
 	    size_t len;
-	   =20
+
 	    if ((flags & NTLM_NEG_KEYEX) =3D=3D 0) {
-		krb5_set_error_string(context,
-				      "NTLM client failed to neg key "
-				      "exchange but still sent key");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       "NTLM client failed to neg key "
+				       "exchange but still sent key");
 		goto failed;
 	    }
-	   =20
+
 	    len =3D ireq.u.ntlmRequest.sessionkey->length;
 	    if (len !=3D sizeof(masterkey)){
-		krb5_set_error_string(context,
-				      "NTLM master key wrong length: %lu",
-				      (unsigned long)len);
+		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       "NTLM master key wrong length: %lu",
+				       (unsigned long)len);
 		goto failed;
 	    }
-	   =20
-	    RC4_set_key(&rc4, sizeof(sessionkey), sessionkey);
-	   =20
-	    RC4(&rc4, sizeof(masterkey),
-		ireq.u.ntlmRequest.sessionkey->data,=20
-		masterkey);
-	    memset(&rc4, 0, sizeof(rc4));
-	   =20
-	    r.u.ntlmResponse.sessionkey =3D=20
+
+
+	    EVP_CIPHER_CTX_init(&rc4);
+	    EVP_CipherInit_ex(&rc4, EVP_rc4(), NULL, sessionkey, NULL, 1);
+	    EVP_Cipher(&rc4,
+		       masterkey, ireq.u.ntlmRequest.sessionkey->data,
+		       sizeof(masterkey));
+	    EVP_CIPHER_CTX_cleanup(&rc4);
+
+	    r.u.ntlmResponse.sessionkey =3D
 		malloc(sizeof(*r.u.ntlmResponse.sessionkey));
 	    if (r.u.ntlmResponse.sessionkey =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
+		ret =3D EINVAL;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
-	   =20
+
 	    ret =3D krb5_data_copy(r.u.ntlmResponse.sessionkey,
 				 masterkey, sizeof(masterkey));
 	    if (ret) {
-		krb5_set_error_string(context, "out of memory");
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
 	}
@@ -1354,26 +1404,26 @@
 	break;
=20
     default: {
-	char *s;
-	krb5_set_error_string(context, "unknown operation to digest");
+	const char *s;
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret, "unknown operation to digest");
=20
-    failed:
+	failed:
=20
 	s =3D krb5_get_error_message(context, ret);
 	if (s =3D=3D NULL) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
-=09
+
 	kdc_log(context, config, 0, "Digest failed with: %s", s);
=20
 	r.element =3D choice_DigestRepInner_error;
 	r.u.error.reason =3D strdup("unknown error");
-	krb5_free_error_string(context, s);
+	krb5_free_error_message(context, s);
 	if (r.u.error.reason =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	r.u.error.code =3D EINVAL;
@@ -1383,7 +1433,7 @@
=20
     ASN1_MALLOC_ENCODE(DigestRepInner, buf.data, buf.length, &r, &size, re=
t);
     if (ret) {
-	krb5_set_error_string(context, "Failed to encode inner digest reply");
+	krb5_set_error_message(context, ret, "Failed to encode inner digest reply=
");
 	goto out;
     }
     if (size !=3D buf.length)
@@ -1408,20 +1458,20 @@
 	    goto out;
     }
=20
-    ret =3D krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_DIGEST_ENC=
RYPT,=20
+    ret =3D krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_DIGEST_ENC=
RYPT,
 				     buf.data, buf.length, 0,
 				     &rep.innerRep);
-   =20
+
     ASN1_MALLOC_ENCODE(DigestREP, reply->data, reply->length, &rep, &size,=
 ret);
     if (ret) {
-	krb5_set_error_string(context, "Failed to encode digest reply");
+	krb5_set_error_message(context, ret, "Failed to encode digest reply");
 	goto out;
     }
     if (size !=3D reply->length)
 	krb5_abortx(context, "ASN1 internal error");
=20
-   =20
-out:
+
+ out:
     if (ac)
 	krb5_auth_con_free(context, ac);
     if (ret)
@@ -1448,9 +1498,12 @@
 	free (client_name);
     krb5_data_free(&buf);
     krb5_data_free(&serverNonce);
+    free_Checksum(&res);
     free_DigestREP(&rep);
     free_DigestRepInner(&r);
     free_DigestReqInner(&ireq);
=20
     return ret;
 }
+
+#endif /* DIGEST */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/headers.h
--- a/head/crypto/heimdal/kdc/headers.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/headers.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,47 +1,45 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/*=20
- * $Id: headers.h 19658 2007-01-04 00:15:34Z lha $=20
- * $FreeBSD$=20
+/*
+ * $Id$
  */
=20
 #ifndef __HEADERS_H__
 #define __HEADERS_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #include <limits.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -92,17 +90,24 @@
 #include <parse_units.h>
 #include <krb5.h>
 #include <krb5_locl.h>
+#ifdef DIGEST
 #include <digest_asn1.h>
+#endif
+#ifdef KX509
 #include <kx509_asn1.h>
+#endif
 #include <hdb.h>
 #include <hdb_err.h>
 #include <der.h>
=20
+#ifndef NO_NTLM
 #include <heimntlm.h>
+#endif
+#include <kdc.h>
 #include <windc_plugin.h>
=20
 #undef ALLOC
-#define ALLOC(X) ((X) =3D malloc(sizeof(*(X))))
+#define ALLOC(X) ((X) =3D calloc(1, sizeof(*(X))))
 #undef ALLOC_SEQ
 #define ALLOC_SEQ(X, N) do { (X)->len =3D (N); \
 (X)->val =3D calloc((X)->len, sizeof(*(X)->val)); } while(0)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/hprop.8
--- a/head/crypto/heimdal/kdc/hprop.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/hprop.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2000 - 2004 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2000 - 2004 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: hprop.8 20456 2007-04-19 20:29:42Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd December  8, 2004
 .Dt HPROP 8
@@ -41,37 +41,36 @@
 .Nm
 .Bk -words
 .Oo Fl m Ar file \*(Ba Xo
-.Fl -master-key=3D Ns Pa file
+.Fl Fl master-key=3D Ns Pa file
 .Xc
 .Oc
 .Oo Fl d Ar file \*(Ba Xo
-.Fl -database=3D Ns Pa file
+.Fl Fl database=3D Ns Pa file
 .Xc
 .Oc
-.Op Fl -source=3D Ns Ar heimdal|mit-dump|krb4-dump|kaserver
+.Op Fl Fl source=3D Ns Ar heimdal|mit-dump
 .Oo Fl r Ar string \*(Ba Xo
-.Fl -v4-realm=3D Ns Ar string
+.Fl Fl v4-realm=3D Ns Ar string
 .Xc
 .Oc
 .Oo Fl c Ar cell \*(Ba Xo
-.Fl -cell=3D Ns Ar cell
+.Fl Fl cell=3D Ns Ar cell
 .Xc
 .Oc
-.Op Fl S | Fl -kaspecials
 .Oo Fl k Ar keytab \*(Ba Xo
-.Fl -keytab=3D Ns Ar keytab
+.Fl Fl keytab=3D Ns Ar keytab
 .Xc
 .Oc
 .Oo Fl R Ar string \*(Ba Xo
-.Fl -v5-realm=3D Ns Ar string
+.Fl Fl v5-realm=3D Ns Ar string
 .Xc
 .Oc
-.Op Fl D | Fl -decrypt
-.Op Fl E | Fl -encrypt
-.Op Fl n | Fl -stdout
-.Op Fl v | Fl -verbose
-.Op Fl -version
-.Op Fl h | Fl -help
+.Op Fl D | Fl Fl decrypt
+.Op Fl E | Fl Fl encrypt
+.Op Fl n | Fl Fl stdout
+.Op Fl v | Fl Fl verbose
+.Op Fl Fl version
+.Op Fl h | Fl Fl help
 .Op Ar host Ns Op : Ns Ar port
 .Ar ...
 .Ek
@@ -90,101 +89,42 @@
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl m Ar file ,
-.Fl -master-key=3D Ns Pa file
-.Xc
+.It Fl m Ar file , Fl Fl master-key=3D Ns Pa file
 Where to find the master key to encrypt or decrypt keys with.
-.It Xo
-.Fl d Ar file ,
-.Fl -database=3D Ns Pa file
-.Xc
+.It Fl d Ar file , Fl Fl database=3D Ns Pa file
 The database to be propagated.
-.It Xo
-.Fl -source=3D Ns Ar heimdal|mit-dump|krb4-dump|kaserver
-.Xc
+.It Fl Fl source=3D Ns Ar heimdal|mit-dump|krb4-dump|kaserver
 Specifies the type of the source database. Alternatives include:
 .Pp
-.Bl -tag -width krb4-dump -compact -offset indent
+.Bl -tag -width mit-dump -compact -offset indent
 .It heimdal
 a Heimdal database
 .It mit-dump
 a MIT Kerberos 5 dump file
-.It krb4-dump
-a Kerberos 4 dump file
-.It kaserver
-an AFS kaserver database
 .El
-.It Xo
-.Fl k Ar keytab ,
-.Fl -keytab=3D Ns Ar keytab
-.Xc
++.It Fl k Ar keytab , Fl Fl keytab=3D Ns Ar keytab
 The keytab to use for fetching the key to be used for authenticating
 to the propagation daemon(s). The key
-.Pa kadmin/hprop
+.Pa hprop/hostname
 is used from this keytab.  The default is to fetch the key from the
 KDC database.
-.It Xo
-.Fl R Ar string ,
-.Fl -v5-realm=3D Ns Ar string
-.Xc
+.It Fl R Ar string , Fl Fl v5-realm=3D Ns Ar string
 Local realm override.
-.It Xo
-.Fl D ,
-.Fl -decrypt
-.Xc
+.It Fl D , Fl Fl decrypt
 The encryption keys in the database can either be in clear, or
 encrypted with a master key. This option transmits the database with
 unencrypted keys.
-.It Xo
-.Fl E ,
-.Fl -encrypt
-.Xc
+.It Fl E , Fl Fl encrypt
 This option transmits the database with encrypted keys.
-.It Xo
-.Fl n ,
-.Fl -stdout
-.Xc
+.It Fl n , Fl Fl stdout
 Dump the database on stdout, in a format that can be fed to hpropd.
 .El
-.Pp
-The following options are only valid if
-.Nm hprop
-is compiled with support for Kerberos 4 (kaserver).
-.Bl -tag -width Ds
-.It Xo
-.Fl r Ar string ,
-.Fl -v4-realm=3D Ns Ar string
-.Xc
-v4 realm to use.
-.It Xo
-.Fl c Ar cell ,
-.Fl -cell=3D Ns Ar cell
-.Xc
-The AFS cell name, used if reading a kaserver database.
-.It Xo
-.Fl S ,
-.Fl -kaspecials
-.Xc
-Also dump the principals marked as special in the kaserver database.
-.It Xo
-.Fl K ,
-.Fl -ka-db
-.Xc
-Deprecated, identical to
-.Sq --source=3Dkaserver .
-.El
 .Sh EXAMPLES
 The following will propagate a database to another machine (which
 should run
-.Xr hpropd 8 ):
+.Xr hpropd 8 ) :
 .Bd -literal -offset indent
 $ hprop slave-1 slave-2
 .Ed
-.Pp
-Convert a Kerberos 4 dump-file for use with a Heimdal KDC:
-.Bd -literal -offset indent
-$ hprop -n --source=3Dkrb4-dump -d /var/kerberos/principal.dump --master-k=
ey=3D/.k | hpropd -n
-.Ed
 .Sh SEE ALSO
 .Xr hpropd 8
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/hprop.c
--- a/head/crypto/heimdal/kdc/hprop.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/hprop.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
+#define KRB5_DEPRECATED /* uses v4 functions that will die */
+
 #include "hprop.h"
=20
-RCSID("$Id: hprop.c 21745 2007-07-31 16:11:25Z lha $");
-
 static int version_flag;
 static int help_flag;
 static const char *ktname =3D HPROP_KEYTAB;
@@ -48,12 +48,6 @@
=20
 static char *source_type;
=20
-static char *afs_cell;
-static char *v4_realm;
-
-static int kaspecials_flag;
-static int ka_use_null_salt;
-
 static char *local_realm=3DNULL;
=20
 static int
@@ -72,7 +66,7 @@
 	warnx ("%s: %s", hostname, gai_strerror(error));
 	return -1;
     }
-   =20
+
     for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
 	int s;
=20
@@ -112,7 +106,7 @@
 	    krb5_warn(context, ret, "hdb_unseal_keys_mkey");
 	    return ret;
 	}
-    }=09
+    }
=20
     ret =3D hdb_entry2value(context, &entry->entry, &data);
     if(ret) {
@@ -123,310 +117,29 @@
     if(to_stdout)
 	ret =3D krb5_write_message(context, &pd->sock, &data);
     else
-	ret =3D krb5_write_priv_message(context, pd->auth_context,=20
+	ret =3D krb5_write_priv_message(context, pd->auth_context,
 				      &pd->sock, &data);
     krb5_data_free(&data);
     return ret;
 }
=20
-int
-v4_prop(void *arg, struct v4_principal *p)
-{
-    struct prop_data *pd =3D arg;
-    hdb_entry_ex ent;
-    krb5_error_code ret;
-
-    memset(&ent, 0, sizeof(ent));
-
-    ret =3D krb5_425_conv_principal(pd->context, p->name, p->instance, v4_=
realm,
-				  &ent.entry.principal);
-    if(ret) {
-	krb5_warn(pd->context, ret,
-		  "krb5_425_conv_principal %s.%s@%s",
-		  p->name, p->instance, v4_realm);
-	return 0;
-    }
-
-    if(verbose_flag) {
-	char *s;
-	krb5_unparse_name_short(pd->context, ent.entry.principal, &s);
-	krb5_warnx(pd->context, "%s.%s -> %s", p->name, p->instance, s);
-	free(s);
-    }
-
-    ent.entry.kvno =3D p->kvno;
-    ent.entry.keys.len =3D 3;
-    ent.entry.keys.val =3D malloc(ent.entry.keys.len * sizeof(*ent.entry.k=
eys.val));
-    if (ent.entry.keys.val =3D=3D NULL)
-	krb5_errx(pd->context, ENOMEM, "malloc");
-    if(p->mkvno !=3D -1) {
-	ent.entry.keys.val[0].mkvno =3D malloc (sizeof(*ent.entry.keys.val[0].mkv=
no));
-	if (ent.entry.keys.val[0].mkvno =3D=3D NULL)
-	    krb5_errx(pd->context, ENOMEM, "malloc");
-	*(ent.entry.keys.val[0].mkvno) =3D p->mkvno;
-    } else
-	ent.entry.keys.val[0].mkvno =3D NULL;
-    ent.entry.keys.val[0].salt =3D calloc(1, sizeof(*ent.entry.keys.val[0]=
.salt));
-    if (ent.entry.keys.val[0].salt =3D=3D NULL)
-	krb5_errx(pd->context, ENOMEM, "calloc");
-    ent.entry.keys.val[0].salt->type =3D KRB5_PADATA_PW_SALT;
-    ent.entry.keys.val[0].key.keytype =3D ETYPE_DES_CBC_MD5;
-    krb5_data_alloc(&ent.entry.keys.val[0].key.keyvalue, DES_KEY_SZ);
-    memcpy(ent.entry.keys.val[0].key.keyvalue.data, p->key, 8);
-
-    copy_Key(&ent.entry.keys.val[0], &ent.entry.keys.val[1]);
-    ent.entry.keys.val[1].key.keytype =3D ETYPE_DES_CBC_MD4;
-    copy_Key(&ent.entry.keys.val[0], &ent.entry.keys.val[2]);
-    ent.entry.keys.val[2].key.keytype =3D ETYPE_DES_CBC_CRC;
-
-    {
-	int life =3D _krb5_krb_life_to_time(0, p->max_life);
-	if(life =3D=3D NEVERDATE){
-	    ent.entry.max_life =3D NULL;
-	} else {
-	    /* clean up lifetime a bit */
-	    if(life > 86400)
-		life =3D (life + 86399) / 86400 * 86400;
-	    else if(life > 3600)
-		life =3D (life + 3599) / 3600 * 3600;
-	    ALLOC(ent.entry.max_life);
-	    *ent.entry.max_life =3D life;
-	}
-    }
-
-    ALLOC(ent.entry.valid_end);
-    *ent.entry.valid_end =3D p->exp_date;
-
-    ret =3D krb5_make_principal(pd->context, &ent.entry.created_by.princip=
al,
-			      v4_realm,
-			      "kadmin",
-			      "hprop",
-			      NULL);
-    if(ret){
-	krb5_warn(pd->context, ret, "krb5_make_principal");
-	ret =3D 0;
-	goto out;
-    }
-    ent.entry.created_by.time =3D time(NULL);
-    ALLOC(ent.entry.modified_by);
-    ret =3D krb5_425_conv_principal(pd->context, p->mod_name, p->mod_insta=
nce,=20
-				  v4_realm, &ent.entry.modified_by->principal);
-    if(ret){
-	krb5_warn(pd->context, ret, "%s.%s@%s", p->name, p->instance, v4_realm);
-	ent.entry.modified_by->principal =3D NULL;
-	ret =3D 0;
-	goto out;
-    }
-    ent.entry.modified_by->time =3D p->mod_date;
-
-    ent.entry.flags.forwardable =3D 1;
-    ent.entry.flags.renewable =3D 1;
-    ent.entry.flags.proxiable =3D 1;
-    ent.entry.flags.postdate =3D 1;
-    ent.entry.flags.client =3D 1;
-    ent.entry.flags.server =3D 1;
-   =20
-    /* special case password changing service */
-    if(strcmp(p->name, "changepw") =3D=3D 0 &&=20
-       strcmp(p->instance, "kerberos") =3D=3D 0) {
-	ent.entry.flags.forwardable =3D 0;
-	ent.entry.flags.renewable =3D 0;
-	ent.entry.flags.proxiable =3D 0;
-	ent.entry.flags.postdate =3D 0;
-	ent.entry.flags.initial =3D 1;
-	ent.entry.flags.change_pw =3D 1;
-    }
-
-    ret =3D v5_prop(pd->context, NULL, &ent, pd);
-
-    if (strcmp (p->name, "krbtgt") =3D=3D 0
-	&& strcmp (v4_realm, p->instance) !=3D 0) {
-	krb5_free_principal (pd->context, ent.entry.principal);
-	ret =3D krb5_425_conv_principal (pd->context, p->name,
-				       v4_realm, p->instance,
-				       &ent.entry.principal);
-	if (ret =3D=3D 0)
-	    ret =3D v5_prop (pd->context, NULL, &ent, pd);
-    }
-
-  out:
-    hdb_free_entry(pd->context, &ent);
-    return ret;
-}
-
-#include "kadb.h"
-
-/* read a `ka_entry' from `fd' at offset `pos' */
-static void
-read_block(krb5_context context, int fd, int32_t pos, void *buf, size_t le=
n)
-{
-    krb5_error_code ret;
-#ifdef HAVE_PREAD
-    if((ret =3D pread(fd, buf, len, 64 + pos)) < 0)
-	krb5_err(context, 1, errno, "pread(%u)", 64 + pos);
-#else
-    if(lseek(fd, 64 + pos, SEEK_SET) =3D=3D (off_t)-1)
-	krb5_err(context, 1, errno, "lseek(%u)", 64 + pos);
-    ret =3D read(fd, buf, len);
-    if(ret < 0)
-	krb5_err(context, 1, errno, "read(%lu)", (unsigned long)len);
-#endif
-    if(ret !=3D len)
-	krb5_errx(context, 1, "read(%lu) =3D %u", (unsigned long)len, ret);
-}
-
-static int
-ka_convert(struct prop_data *pd, int fd, struct ka_entry *ent)
-{
-    int32_t flags =3D ntohl(ent->flags);
-    krb5_error_code ret;
-    hdb_entry_ex hdb;
-
-    if(!kaspecials_flag
-       && (flags & KAFNORMAL) =3D=3D 0) /* remove special entries */
-	return 0;
-    memset(&hdb, 0, sizeof(hdb));
-    ret =3D krb5_425_conv_principal(pd->context, ent->name, ent->instance,=20
-				  v4_realm, &hdb.entry.principal);
-    if(ret) {
-	krb5_warn(pd->context, ret,
-		  "krb5_425_conv_principal (%s.%s@%s)",
-		  ent->name, ent->instance, v4_realm);
-	return 0;
-    }
-    hdb.entry.kvno =3D ntohl(ent->kvno);
-    hdb.entry.keys.len =3D 3;
-    hdb.entry.keys.val =3D=20
-	malloc(hdb.entry.keys.len * sizeof(*hdb.entry.keys.val));
-    if (hdb.entry.keys.val =3D=3D NULL)
-	krb5_errx(pd->context, ENOMEM, "malloc");
-    hdb.entry.keys.val[0].mkvno =3D NULL;
-    hdb.entry.keys.val[0].salt =3D calloc(1, sizeof(*hdb.entry.keys.val[0]=
.salt));
-    if (hdb.entry.keys.val[0].salt =3D=3D NULL)
-	krb5_errx(pd->context, ENOMEM, "calloc");
-    if (ka_use_null_salt) {
-	hdb.entry.keys.val[0].salt->type =3D hdb_pw_salt;
-	hdb.entry.keys.val[0].salt->salt.data =3D NULL;
-	hdb.entry.keys.val[0].salt->salt.length =3D 0;
-    } else {
-	hdb.entry.keys.val[0].salt->type =3D hdb_afs3_salt;
-	hdb.entry.keys.val[0].salt->salt.data =3D strdup(afs_cell);
-	if (hdb.entry.keys.val[0].salt->salt.data =3D=3D NULL)
-	    krb5_errx(pd->context, ENOMEM, "strdup");
-	hdb.entry.keys.val[0].salt->salt.length =3D strlen(afs_cell);
-    }
-   =20
-    hdb.entry.keys.val[0].key.keytype =3D ETYPE_DES_CBC_MD5;
-    krb5_data_copy(&hdb.entry.keys.val[0].key.keyvalue,
-		   ent->key,
-		   sizeof(ent->key));
-    copy_Key(&hdb.entry.keys.val[0], &hdb.entry.keys.val[1]);
-    hdb.entry.keys.val[1].key.keytype =3D ETYPE_DES_CBC_MD4;
-    copy_Key(&hdb.entry.keys.val[0], &hdb.entry.keys.val[2]);
-    hdb.entry.keys.val[2].key.keytype =3D ETYPE_DES_CBC_CRC;
-
-    ALLOC(hdb.entry.max_life);
-    *hdb.entry.max_life =3D ntohl(ent->max_life);
-
-    if(ntohl(ent->valid_end) !=3D NEVERDATE && ntohl(ent->valid_end) !=3D =
0xffffffff) {
-	ALLOC(hdb.entry.valid_end);
-	*hdb.entry.valid_end =3D ntohl(ent->valid_end);
-    }
-   =20
-    if (ntohl(ent->pw_change) !=3D NEVERDATE &&=20
-	ent->pw_expire !=3D 255 &&
-	ent->pw_expire !=3D 0) {
-	ALLOC(hdb.entry.pw_end);
-	*hdb.entry.pw_end =3D ntohl(ent->pw_change)
-	    + 24 * 60 * 60 * ent->pw_expire;
-    }
-
-    ret =3D krb5_make_principal(pd->context, &hdb.entry.created_by.princip=
al,
-			      v4_realm,
-			      "kadmin",
-			      "hprop",
-			      NULL);
-    hdb.entry.created_by.time =3D time(NULL);
-
-    if(ent->mod_ptr){
-	struct ka_entry mod;
-	ALLOC(hdb.entry.modified_by);
-	read_block(pd->context, fd, ntohl(ent->mod_ptr), &mod, sizeof(mod));
-=09
-	krb5_425_conv_principal(pd->context, mod.name, mod.instance, v4_realm,=20
-				&hdb.entry.modified_by->principal);
-	hdb.entry.modified_by->time =3D ntohl(ent->mod_time);
-	memset(&mod, 0, sizeof(mod));
-    }
-
-    hdb.entry.flags.forwardable =3D 1;
-    hdb.entry.flags.renewable =3D 1;
-    hdb.entry.flags.proxiable =3D 1;
-    hdb.entry.flags.postdate =3D 1;
-    /* XXX - AFS 3.4a creates krbtgt.REALMOFCELL as NOTGS+NOSEAL */
-    if (strcmp(ent->name, "krbtgt") =3D=3D 0 &&
-	(flags & (KAFNOTGS|KAFNOSEAL)) =3D=3D (KAFNOTGS|KAFNOSEAL))
-	flags &=3D ~(KAFNOTGS|KAFNOSEAL);
-
-    hdb.entry.flags.client =3D (flags & KAFNOTGS) =3D=3D 0;
-    hdb.entry.flags.server =3D (flags & KAFNOSEAL) =3D=3D 0;
-
-    ret =3D v5_prop(pd->context, NULL, &hdb, pd);
-    hdb_free_entry(pd->context, &hdb);
-    return ret;
-}
-
-static int
-ka_dump(struct prop_data *pd, const char *file)
-{
-    struct ka_header header;
-    int i;
-    int fd =3D open(file, O_RDONLY);
-
-    if(fd < 0)
-	krb5_err(pd->context, 1, errno, "open(%s)", file);
-    read_block(pd->context, fd, 0, &header, sizeof(header));
-    if(header.version1 !=3D header.version2)
-	krb5_errx(pd->context, 1, "Version mismatch in header: %ld/%ld",
-		  (long)ntohl(header.version1), (long)ntohl(header.version2));
-    if(ntohl(header.version1) !=3D 5)
-	krb5_errx(pd->context, 1, "Unknown database version %ld (expected 5)",=20
-		  (long)ntohl(header.version1));
-    for(i =3D 0; i < ntohl(header.hashsize); i++){
-	int32_t pos =3D ntohl(header.hash[i]);
-	while(pos){
-	    struct ka_entry ent;
-	    read_block(pd->context, fd, pos, &ent, sizeof(ent));
-	    ka_convert(pd, fd, &ent);
-	    pos =3D ntohl(ent.next);
-	}
-    }
-    return 0;
-}
-
-
-
 struct getargs args[] =3D {
     { "master-key", 'm', arg_string, &mkeyfile, "v5 master key file", "fil=
e" },
-    { "database", 'd',	arg_string, &database, "database", "file" },
-    { "source",   0,	arg_string, &source_type, "type of database to read",=20
+    { "database", 'd',	arg_string, rk_UNCONST(&database), "database", "fil=
e" },
+    { "source",   0,	arg_string, &source_type, "type of database to read",
       "heimdal"
       "|mit-dump"
-      "|krb4-dump"
-      "|kaserver"
     },
-     =20
-    { "v4-realm", 'r',  arg_string, &v4_realm, "v4 realm to use" },
-    { "cell",	  'c',  arg_string, &afs_cell, "name of AFS cell" },
-    { "kaspecials", 'S', arg_flag,   &kaspecials_flag, "dump KASPECIAL key=
s"},
-    { "keytab",   'k',	arg_string, &ktname, "keytab to use for authenticat=
ion", "keytab" },
-    { "v5-realm", 'R',  arg_string, &local_realm, "v5 realm to use" },
-    { "decrypt",  'D',  arg_flag,   &decrypt_flag,   "decrypt keys" },
-    { "encrypt",  'E',  arg_flag,   &encrypt_flag,   "encrypt keys" },
-    { "stdout",	  'n',  arg_flag,   &to_stdout, "dump to stdout" },
-    { "verbose",  'v',	arg_flag, &verbose_flag },
-    { "version",   0,	arg_flag, &version_flag },
-    { "help",     'h',	arg_flag, &help_flag }
+
+    { "keytab",   'k',	arg_string, rk_UNCONST(&ktname),
+      "keytab to use for authentication", "keytab" },
+    { "v5-realm", 'R',  arg_string, &local_realm, "v5 realm to use", NULL =
},
+    { "decrypt",  'D',  arg_flag,   &decrypt_flag,   "decrypt keys", NULL =
},
+    { "encrypt",  'E',  arg_flag,   &encrypt_flag,   "encrypt keys", NULL =
},
+    { "stdout",	  'n',  arg_flag,   &to_stdout, "dump to stdout", NULL },
+    { "verbose",  'v',	arg_flag, &verbose_flag, NULL, NULL },
+    { "version",   0,	arg_flag, &version_flag, NULL, NULL },
+    { "help",     'h',	arg_flag, &help_flag, NULL, NULL }
 };
=20
 static int num_args =3D sizeof(args) / sizeof(args[0]);
@@ -447,14 +160,14 @@
     krb5_get_init_creds_opt *init_opts;
     krb5_preauthtype preauth =3D KRB5_PADATA_ENC_TIMESTAMP;
     krb5_creds creds;
-   =20
+
     ret =3D krb5_kt_register(context, &hdb_kt_ops);
     if(ret) krb5_err(context, 1, ret, "krb5_kt_register");
=20
     ret =3D krb5_kt_resolve(context, ktname, &keytab);
     if(ret) krb5_err(context, 1, ret, "krb5_kt_resolve");
-   =20
-    ret =3D krb5_make_principal(context, &client, NULL,=20
+
+    ret =3D krb5_make_principal(context, &client, NULL,
 			      "kadmin", HPROP_NAME, NULL);
     if(ret) krb5_err(context, 1, ret, "krb5_make_principal");
=20
@@ -466,12 +179,12 @@
     if(ret) krb5_err(context, 1, ret, "krb5_get_init_creds");
=20
     krb5_get_init_creds_opt_free(context, init_opts);
-   =20
+
     ret =3D krb5_kt_close(context, keytab);
     if(ret) krb5_err(context, 1, ret, "krb5_kt_close");
-   =20
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, cache);
-    if(ret) krb5_err(context, 1, ret, "krb5_cc_gen_new");
+
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, cache);
+    if(ret) krb5_err(context, 1, ret, "krb5_cc_new_unique");
=20
     ret =3D krb5_cc_initialize(context, *cache, client);
     if(ret) krb5_err(context, 1, ret, "krb5_cc_initialize");
@@ -486,27 +199,21 @@
=20
 enum hprop_source {
     HPROP_HEIMDAL =3D 1,
-    HPROP_KRB4_DUMP,
-    HPROP_KASERVER,
     HPROP_MIT_DUMP
 };
=20
-#define IS_TYPE_V4(X) ((X) =3D=3D HPROP_KRB4_DUMP || (X) =3D=3D HPROP_KASE=
RVER)
-
 struct {
     int type;
     const char *name;
 } types[] =3D {
     { HPROP_HEIMDAL,	"heimdal" },
-    { HPROP_KRB4_DUMP,	"krb4-dump" },
-    { HPROP_KASERVER, 	"kaserver" },
     { HPROP_MIT_DUMP,	"mit-dump" }
 };
=20
 static int
 parse_source_type(const char *s)
 {
-    int i;
+    size_t i;
     for(i =3D 0; i < sizeof(types) / sizeof(types[0]); i++) {
 	if(strstr(types[i].name, s) =3D=3D types[i].name)
 	    return types[i].type;
@@ -524,22 +231,10 @@
     int ret;
=20
     switch(type) {
-    case HPROP_KRB4_DUMP:
-	ret =3D v4_prop_dump(pd, database_name);
-	if(ret)
-	    krb5_warnx(context, "v4_prop_dump: %s",=20
-		       krb5_get_err_text(context, ret));
-	break;
-    case HPROP_KASERVER:
-	ret =3D ka_dump(pd, database_name);
-	if(ret)
-	    krb5_warn(context, ret, "ka_dump");
-	break;
     case HPROP_MIT_DUMP:
 	ret =3D mit_prop_dump(pd, database_name);
 	if (ret)
-	    krb5_warnx(context, "mit_prop_dump: %s",
-		      krb5_get_err_text(context, ret));
+	    krb5_warn(context, ret, "mit_prop_dump");
 	break;
     case HPROP_HEIMDAL:
 	ret =3D hdb_foreach(context, db, HDB_F_DECRYPT, v5_prop, pd);
@@ -563,7 +258,7 @@
     pd.context      =3D context;
     pd.auth_context =3D NULL;
     pd.sock         =3D STDOUT_FILENO;
-=09
+
     ret =3D iterate (context, database_name, db, type, &pd);
     if (ret)
 	krb5_errx(context, 1, "iterate failure");
@@ -577,7 +272,7 @@
=20
 static int
 propagate_database (krb5_context context, int type,
-		    const char *database_name,=20
+		    const char *database_name,
 		    HDB *db, krb5_ccache ccache,
 		    int optidx, int argc, char **argv)
 {
@@ -596,8 +291,8 @@
=20
 	port =3D strchr(host, ':');
 	if(port =3D=3D NULL) {
-	    snprintf(portstr, sizeof(portstr), "%u",=20
-		     ntohs(krb5_getportbyname (context, "hprop", "tcp",=20
+	    snprintf(portstr, sizeof(portstr), "%u",
+		     ntohs(krb5_getportbyname (context, "hprop", "tcp",
 					       HPROP_PORT)));
 	    port =3D portstr;
 	} else
@@ -622,11 +317,10 @@
         if (local_realm) {
             krb5_realm my_realm;
             krb5_get_default_realm(context,&my_realm);
+            krb5_principal_set_realm(context,server,my_realm);
+	    krb5_xfree(my_realm);
+        }
=20
-	    free (*krb5_princ_realm(context, server));
-            krb5_princ_set_realm(context,server,&my_realm);
-        }
-   =20
 	auth_context =3D NULL;
 	ret =3D krb5_sendauth(context,
 			    &auth_context,
@@ -650,7 +344,7 @@
 	    close(fd);
 	    goto next_host;
 	}
-=09
+
 	pd.context      =3D context;
 	pd.auth_context =3D auth_context;
 	pd.sock         =3D fd;
@@ -677,7 +371,7 @@
 	    goto next_host;
 	} else
 	    krb5_data_free (&data);
-=09
+
     next_host:
 	krb5_auth_con_free(context, auth_context);
 	close(fd);
@@ -705,7 +399,7 @@
=20
     if(help_flag)
 	usage(0);
-   =20
+
     if(version_flag){
 	print_version(NULL);
 	exit(0);
@@ -715,25 +409,16 @@
     if(ret)
 	exit(1);
=20
+    /* We may be reading an old database encrypted with a DES master key. =
*/
+    ret =3D krb5_allow_weak_crypto(context, 1);
+    if(ret)
+        krb5_err(context, 1, ret, "krb5_allow_weak_crypto");
+
     if(local_realm)
 	krb5_set_default_realm(context, local_realm);
=20
-    if(v4_realm =3D=3D NULL) {
-	ret =3D krb5_get_default_realm(context, &v4_realm);
-	if(ret)
-	    krb5_err(context, 1, ret, "krb5_get_default_realm");
-    }
-
-    if(afs_cell =3D=3D NULL) {
-	afs_cell =3D strdup(v4_realm);
-	if(afs_cell =3D=3D NULL)
-	    krb5_errx(context, 1, "out of memory");
-	strlwr(afs_cell);
-    }
-
-
     if(encrypt_flag && decrypt_flag)
-	krb5_errx(context, 1,=20
+	krb5_errx(context, 1,
 		  "only one of `--encrypt' and `--decrypt' is meaningful");
=20
     if(source_type !=3D NULL) {
@@ -745,7 +430,7 @@
=20
     if(!to_stdout)
 	get_creds(context, &ccache);
-   =20
+
     if(decrypt_flag || encrypt_flag) {
 	ret =3D hdb_read_master_key(context, mkeyfile, &mkey5);
 	if(ret && ret !=3D ENOENT)
@@ -753,26 +438,8 @@
 	if(ret)
 	    krb5_errx(context, 1, "No master key file found");
     }
-   =20
-    if (IS_TYPE_V4(type) && v4_realm =3D=3D NULL)
-	krb5_errx(context, 1, "Its a Kerberos 4 database "
-		  "but no realm configured");
=20
     switch(type) {
-    case HPROP_KASERVER:
-	if (database =3D=3D NULL)
-	    database =3D DEFAULT_DATABASE;
-	ka_use_null_salt =3D krb5_config_get_bool_default(context, NULL, FALSE,=20
-							"hprop",=20
-							"afs_uses_null_salt",=20
-							NULL);
-
-	break;
-    case HPROP_KRB4_DUMP:
-	if (database =3D=3D NULL)
-	    krb5_errx(context, 1, "no dump file specified");
-=09
-	break;
     case HPROP_MIT_DUMP:
 	if (database =3D=3D NULL)
 	    krb5_errx(context, 1, "no dump file specified");
@@ -793,12 +460,12 @@
     if (to_stdout)
 	exit_code =3D dump_database (context, type, database, db);
     else
-	exit_code =3D propagate_database (context, type, database,=20
+	exit_code =3D propagate_database (context, type, database,
 					db, ccache, optidx, argc, argv);
=20
     if(ccache !=3D NULL)
 	krb5_cc_destroy(context, ccache);
-=09
+
     if(db !=3D NULL)
 	(*db->hdb_destroy)(context, db);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/hprop.h
--- a/head/crypto/heimdal/kdc/hprop.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/hprop.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: hprop.h 16378 2005-12-12 12:40:12Z lha $ */
+/* $Id$ */
=20
 #ifndef __HPROP_H__
 #define __HPROP_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/hpropd.8
--- a/head/crypto/heimdal/kdc/hpropd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/hpropd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 1997, 2000 - 2003 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1997, 2000 - 2003 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: hpropd.8 14381 2004-12-10 09:44:05Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd August 27, 1997
 .Dt HPROPD 8
@@ -41,17 +41,17 @@
 .Nm
 .Bk -words
 .Oo Fl d Ar file \*(Ba Xo
-.Fl -database=3D Ns Ar file
+.Fl Fl database=3D Ns Ar file
 .Xc
 .Oc
-.Op Fl n | Fl -stdin
-.Op Fl -print
-.Op Fl i | Fl -no-inetd
+.Op Fl n | Fl Fl stdin
+.Op Fl Fl print
+.Op Fl i | Fl Fl no-inetd
 .Oo Fl k Ar keytab \*(Ba Xo
-.Fl -keytab=3D Ns Ar keytab
+.Fl Fl keytab=3D Ns Ar keytab
 .Xc
 .Oc
-.Op Fl 4 | Fl -v4dump
+.Op Fl 4 | Fl Fl v4dump
 .Ek
 .Sh DESCRIPTION
 .Nm
@@ -73,34 +73,17 @@
 .Pp
 Options supported:
 .Bl -tag -width Ds
-.It Xo
-.Fl d Ar file ,
-.Fl -database=3D Ns Ar file
-.Xc
+.It Fl d Ar file , Fl Fl database=3D Ns Ar file
 database
-.It Xo
-.Fl n ,
-.Fl -stdin
-.Xc
+.It Fl n , Fl Fl stdin
 read from stdin
-.It Xo
-.Fl -print
-.Xc
+.It Fl Fl print
 print dump to stdout
-.It Xo
-.Fl i ,
-.Fl -no-inetd
-.Xc
+.It Fl i , Fl Fl no-inetd
 not started from inetd
-.It Xo
-.Fl k Ar keytab ,
-.Fl -keytab=3D Ns Ar keytab
-.Xc
+.It Fl k Ar keytab , Fl Fl keytab=3D Ns Ar keytab
 keytab to use for authentication
-.It Xo
-.Fl 4 ,
-.Fl -v4dump
-.Xc
+.It Fl 4 , Fl Fl v4dump
 create v4 type DB
 .El
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/hpropd.c
--- a/head/crypto/heimdal/kdc/hpropd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/hpropd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hprop.h"
=20
-RCSID("$Id: hpropd.c 22245 2007-12-08 23:48:52Z lha $");
-
 static int inetd_flag =3D -1;
 static int help_flag;
 static int version_flag;
@@ -45,18 +43,21 @@
 static char *ktname =3D NULL;
=20
 struct getargs args[] =3D {
-    { "database", 'd', arg_string, &database, "database", "file" },
-    { "stdin",    'n', arg_flag, &from_stdin, "read from stdin" },
-    { "print",	    0, arg_flag, &print_dump, "print dump to stdout" },
+    { "database", 'd', arg_string, rk_UNCONST(&database), "database", "fil=
e" },
+    { "stdin",    'n', arg_flag, &from_stdin, "read from stdin", NULL },
+    { "print",	    0, arg_flag, &print_dump, "print dump to stdout", NULL =
},
+#ifdef SUPPORT_INETD
     { "inetd",	   'i',	arg_negative_flag,	&inetd_flag,
-      "Not started from inetd" },
+      "Not started from inetd", NULL },
+#endif
     { "keytab",   'k',	arg_string, &ktname,	"keytab to use for authenticat=
ion", "keytab" },
-    { "realm",   'r',	arg_string, &local_realm, "realm to use" },
+    { "realm",   'r',	arg_string, &local_realm, "realm to use", NULL },
     { "version",    0, arg_flag, &version_flag, NULL, NULL },
     { "help",    'h',  arg_flag, &help_flag, NULL, NULL}
 };
=20
 static int num_args =3D sizeof(args) / sizeof(args[0]);
+static char unparseable_name[] =3D "unparseable name";
=20
 static void
 usage(int ret)
@@ -74,8 +75,8 @@
     krb5_principal c1, c2;
     krb5_authenticator authent;
     krb5_keytab keytab;
-    int fd;
-    HDB *db;
+    krb5_socket_t sock =3D rk_INVALID_SOCKET;
+    HDB *db =3D NULL;
     int optidx =3D 0;
     char *tmp_db;
     krb5_log_facility *fac;
@@ -89,22 +90,22 @@
=20
     ret =3D krb5_openlog(context, "hpropd", &fac);
     if(ret)
-	;
+	errx(1, "krb5_openlog");
     krb5_set_warn_dest(context, fac);
- =20
+
     if(getarg(args, num_args, argc, argv, &optidx))
 	usage(1);
=20
     if(local_realm !=3D NULL)
 	krb5_set_default_realm(context, local_realm);
-   =20
+
     if(help_flag)
 	usage(0);
     if(version_flag) {
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     argc -=3D optidx;
     argv +=3D optidx;
=20
@@ -114,9 +115,9 @@
     if (database =3D=3D NULL)
 	database =3D hdb_default_db(context);
=20
-    if(from_stdin)
-	fd =3D STDIN_FILENO;
-    else {
+    if(from_stdin) {
+	sock =3D STDIN_FILENO;
+    } else {
 	struct sockaddr_storage ss;
 	struct sockaddr *sa =3D (struct sockaddr *)&ss;
 	socklen_t sin_len =3D sizeof(ss);
@@ -124,19 +125,24 @@
 	krb5_ticket *ticket;
 	char *server;
=20
-	fd =3D STDIN_FILENO;
+	sock =3D STDIN_FILENO;
+#ifdef SUPPORT_INETD
 	if (inetd_flag =3D=3D -1) {
-	    if (getpeername (fd, sa, &sin_len) < 0)
+	    if (getpeername (sock, sa, &sin_len) < 0) {
 		inetd_flag =3D 0;
-	    else
+	    } else {
 		inetd_flag =3D 1;
+	    }
 	}
+#else
+	inetd_flag =3D 0;
+#endif
 	if (!inetd_flag) {
 	    mini_inetd (krb5_getportbyname (context, "hprop", "tcp",
-					    HPROP_PORT));
+					    HPROP_PORT), &sock);
 	}
 	sin_len =3D sizeof(ss);
-	if(getpeername(fd, sa, &sin_len) < 0)
+	if(getpeername(sock, sa, &sin_len) < 0)
 	    krb5_err(context, 1, errno, "getpeername");
=20
 	if (inet_ntop(sa->sa_family,
@@ -147,7 +153,7 @@
 		     sizeof(addr_name));
=20
 	krb5_log(context, fac, 0, "Connection from %s", addr_name);
-   =20
+
 	ret =3D krb5_kt_register(context, &hdb_kt_ops);
 	if(ret)
 	    krb5_err(context, 1, ret, "krb5_kt_register");
@@ -162,11 +168,11 @@
 		krb5_err (context, 1, ret, "krb5_kt_default");
 	}
=20
-	ret =3D krb5_recvauth(context, &ac, &fd, HPROP_VERSION, NULL,
+	ret =3D krb5_recvauth(context, &ac, &sock, HPROP_VERSION, NULL,
 			    0, keytab, &ticket);
 	if(ret)
 	    krb5_err(context, 1, ret, "krb5_recvauth");
-=09
+
 	ret =3D krb5_unparse_name(context, ticket->server, &server);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_unparse_name");
@@ -179,17 +185,17 @@
 	ret =3D krb5_auth_con_getauthenticator(context, ac, &authent);
 	if(ret)
 	    krb5_err(context, 1, ret, "krb5_auth_con_getauthenticator");
-=09
+
 	ret =3D krb5_make_principal(context, &c1, NULL, "kadmin", "hprop", NULL);
 	if(ret)
 	    krb5_err(context, 1, ret, "krb5_make_principal");
-	_krb5_principalname2krb5_principal(context, &c2,=20
+	_krb5_principalname2krb5_principal(context, &c2,
 					   authent->cname, authent->crealm);
 	if(!krb5_principal_compare(context, c1, c2)) {
 	    char *s;
 	    ret =3D krb5_unparse_name(context, c2, &s);
 	    if (ret)
-		s =3D "unparseable name";
+		s =3D unparseable_name;
 	    krb5_errx(context, 1, "Unauthorized connection from %s", s);
 	}
 	krb5_free_principal(context, c1);
@@ -199,7 +205,7 @@
 	if(ret)
 	    krb5_err(context, 1, ret, "krb5_kt_close");
     }
-   =20
+
     if(!print_dump) {
 	asprintf(&tmp_db, "%s~", database);
=20
@@ -217,11 +223,11 @@
 	hdb_entry_ex entry;
=20
 	if(from_stdin) {
-	    ret =3D krb5_read_message(context, &fd, &data);
+	    ret =3D krb5_read_message(context, &sock, &data);
 	    if(ret !=3D 0 && ret !=3D HEIM_ERR_EOF)
 		krb5_err(context, 1, ret, "krb5_read_message");
 	} else {
-	    ret =3D krb5_read_priv_message(context, ac, &fd, &data);
+	    ret =3D krb5_read_priv_message(context, ac, &sock, &data);
 	    if(ret)
 		krb5_err(context, 1, ret, "krb5_read_priv_message");
 	}
@@ -230,15 +236,15 @@
 	    if(!from_stdin) {
 		data.data =3D NULL;
 		data.length =3D 0;
-		krb5_write_priv_message(context, ac, &fd, &data);
+		krb5_write_priv_message(context, ac, &sock, &data);
 	    }
 	    if(!print_dump) {
+		ret =3D db->hdb_close(context, db);
+		if(ret)
+		    krb5_err(context, 1, ret, "db_close");
 		ret =3D db->hdb_rename(context, db, database);
 		if(ret)
 		    krb5_err(context, 1, ret, "db_rename");
-		ret =3D db->hdb_close(context, db);
-		if(ret)
-		    krb5_err(context, 1, ret, "db_close");
 	    }
 	    break;
 	}
@@ -255,10 +261,10 @@
 		char *s;
 		ret =3D krb5_unparse_name(context, entry.entry.principal, &s);
 		if (ret)
-		    s =3D strdup("unparseable name");
+		    s =3D strdup(unparseable_name);
 		krb5_warnx(context, "Entry exists: %s", s);
 		free(s);
-	    } else if(ret)=20
+	    } else if(ret)
 		krb5_err(context, 1, ret, "db_store");
 	    else
 		nprincs++;
@@ -267,5 +273,9 @@
     }
     if (!print_dump)
 	krb5_log(context, fac, 0, "Received %d principals", nprincs);
+
+    if (inetd_flag =3D=3D 0)
+	rk_closesocket(sock);
+
     exit(0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kdc-private.h
--- a/head/crypto/heimdal/kdc/kdc-private.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kdc-private.h	Tue Apr 17 11:51:51 2012 +0300
@@ -10,15 +10,16 @@
 	krb5_kdc_configuration */*config*/,
 	hdb_entry_ex */*krbtgt*/,
 	krb5_enctype /*enctype*/,
+	krb5_principal /*client*/,
 	krb5_const_principal /*server*/,
-	KRB5SignedPathPrincipals */*principals*/,
+	krb5_principals /*principals*/,
 	EncTicketPart */*tkt*/);
=20
 krb5_error_code
 _kdc_add_inital_verified_cas (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
-	pk_client_params */*params*/,
+	pk_client_params */*cp*/,
 	EncTicketPart */*tkt*/);
=20
 krb5_error_code
@@ -32,6 +33,17 @@
 	struct sockaddr */*from_addr*/,
 	int /*datagram_reply*/);
=20
+krb5_error_code
+_kdc_check_access (
+	krb5_context /*context*/,
+	krb5_kdc_configuration */*config*/,
+	hdb_entry_ex */*client_ex*/,
+	const char */*client_name*/,
+	hdb_entry_ex */*server_ex*/,
+	const char */*server_name*/,
+	KDC_REQ */*req*/,
+	krb5_data */*e_data*/);
+
 krb5_boolean
 _kdc_check_addresses (
 	krb5_context /*context*/,
@@ -40,82 +52,34 @@
 	const struct sockaddr */*from*/);
=20
 krb5_error_code
-_kdc_check_flags (
-	krb5_context /*context*/,
-	krb5_kdc_configuration */*config*/,
-	hdb_entry_ex */*client_ex*/,
-	const char */*client_name*/,
-	hdb_entry_ex */*server_ex*/,
-	const char */*server_name*/,
-	krb5_boolean /*is_as_req*/);
-
-krb5_error_code
 _kdc_db_fetch (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
 	krb5_const_principal /*principal*/,
 	unsigned /*flags*/,
+	krb5uint32 */*kvno_ptr*/,
 	HDB **/*db*/,
 	hdb_entry_ex **/*h*/);
=20
 krb5_error_code
-_kdc_db_fetch4 (
+_kdc_do_digest (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
-	const char */*name*/,
-	const char */*instance*/,
-	const char */*realm*/,
-	unsigned /*flags*/,
-	hdb_entry_ex **/*ent*/);
-
-krb5_error_code
-_kdc_do_524 (
-	krb5_context /*context*/,
-	krb5_kdc_configuration */*config*/,
-	const Ticket */*t*/,
+	const struct DigestREQ */*req*/,
 	krb5_data */*reply*/,
 	const char */*from*/,
 	struct sockaddr */*addr*/);
=20
 krb5_error_code
-_kdc_do_digest (
+_kdc_do_kx509 (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
-	const DigestREQ */*req*/,
+	const struct Kx509Request */*req*/,
 	krb5_data */*reply*/,
 	const char */*from*/,
 	struct sockaddr */*addr*/);
=20
 krb5_error_code
-_kdc_do_kaserver (
-	krb5_context /*context*/,
-	krb5_kdc_configuration */*config*/,
-	unsigned char */*buf*/,
-	size_t /*len*/,
-	krb5_data */*reply*/,
-	const char */*from*/,
-	struct sockaddr_in */*addr*/);
-
-krb5_error_code
-_kdc_do_kx509 (
-	krb5_context /*context*/,
-	krb5_kdc_configuration */*config*/,
-	const Kx509Request */*req*/,
-	krb5_data */*reply*/,
-	const char */*from*/,
-	struct sockaddr */*addr*/);
-
-krb5_error_code
-_kdc_do_version4 (
-	krb5_context /*context*/,
-	krb5_kdc_configuration */*config*/,
-	unsigned char */*buf*/,
-	size_t /*len*/,
-	krb5_data */*reply*/,
-	const char */*from*/,
-	struct sockaddr_in */*addr*/);
-
-krb5_error_code
 _kdc_encode_reply (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
@@ -126,28 +90,21 @@
 	int /*skvno*/,
 	const EncryptionKey */*skey*/,
 	int /*ckvno*/,
-	const EncryptionKey */*ckey*/,
+	const EncryptionKey */*reply_key*/,
+	int /*rk_is_subkey*/,
 	const char **/*e_text*/,
 	krb5_data */*reply*/);
=20
 krb5_error_code
-_kdc_encode_v4_ticket (
-	krb5_context /*context*/,
-	krb5_kdc_configuration */*config*/,
-	void */*buf*/,
-	size_t /*len*/,
-	const EncTicketPart */*et*/,
-	const PrincipalName */*service*/,
-	size_t */*size*/);
-
-krb5_error_code
 _kdc_find_etype (
 	krb5_context /*context*/,
-	const hdb_entry_ex */*princ*/,
+	krb5_boolean /*use_strongest_session_key*/,
+	krb5_boolean /*is_preauth*/,
+	hdb_entry_ex */*princ*/,
 	krb5_enctype */*etypes*/,
 	unsigned /*len*/,
-	Key **/*ret_key*/,
-	krb5_enctype */*ret_etype*/);
+	krb5_enctype */*ret_enctype*/,
+	Key **/*ret_key*/);
=20
 const PA_DATA*
 _kdc_find_padata (
@@ -164,14 +121,6 @@
 	hdb_entry_ex */*ent*/);
=20
 krb5_error_code
-_kdc_get_des_key (
-	krb5_context /*context*/,
-	hdb_entry_ex */*principal*/,
-	krb5_boolean /*is_server*/,
-	krb5_boolean /*prefer_afs_key*/,
-	Key **/*ret_key*/);
-
-krb5_error_code
 _kdc_get_preferred_key (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
@@ -180,6 +129,16 @@
 	krb5_enctype */*enctype*/,
 	Key **/*key*/);
=20
+krb5_boolean
+_kdc_is_anonymous (
+	krb5_context /*context*/,
+	krb5_principal /*principal*/);
+
+krb5_boolean
+_kdc_is_weak_exception (
+	krb5_principal /*principal*/,
+	krb5_enctype /*etype*/);
+
 void
 _kdc_log_timestamp (
 	krb5_context /*context*/,
@@ -193,11 +152,6 @@
 krb5_error_code
 _kdc_make_anonymous_principalname (PrincipalName */*pn*/);
=20
-int
-_kdc_maybe_version4 (
-	unsigned char */*buf*/,
-	int /*len*/);
-
 krb5_error_code
 _kdc_pac_generate (
 	krb5_context /*context*/,
@@ -208,41 +162,38 @@
 _kdc_pac_verify (
 	krb5_context /*context*/,
 	const krb5_principal /*client_principal*/,
+	const krb5_principal /*delegated_proxy_principal*/,
 	hdb_entry_ex */*client*/,
 	hdb_entry_ex */*server*/,
-	krb5_pac */*pac*/);
+	hdb_entry_ex */*krbtgt*/,
+	krb5_pac */*pac*/,
+	int */*verified*/);
=20
 krb5_error_code
 _kdc_pk_check_client (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
-	const hdb_entry_ex */*client*/,
-	pk_client_params */*client_params*/,
+	HDB */*clientdb*/,
+	hdb_entry_ex */*client*/,
+	pk_client_params */*cp*/,
 	char **/*subject_name*/);
=20
 void
 _kdc_pk_free_client_param (
 	krb5_context /*context*/,
-	pk_client_params */*client_params*/);
-
-krb5_error_code
-_kdc_pk_initialize (
-	krb5_context /*context*/,
-	krb5_kdc_configuration */*config*/,
-	const char */*user_id*/,
-	const char */*anchors*/,
-	char **/*pool*/,
-	char **/*revoke_list*/);
+	pk_client_params */*cp*/);
=20
 krb5_error_code
 _kdc_pk_mk_pa_reply (
 	krb5_context /*context*/,
 	krb5_kdc_configuration */*config*/,
-	pk_client_params */*client_params*/,
+	pk_client_params */*cp*/,
 	const hdb_entry_ex */*client*/,
+	krb5_enctype /*sessionetype*/,
 	const KDC_REQ */*req*/,
 	const krb5_data */*req_buffer*/,
 	krb5_keyblock **/*reply_key*/,
+	krb5_keyblock */*sessionkey*/,
 	METHOD_DATA */*md*/);
=20
 krb5_error_code
@@ -251,6 +202,7 @@
 	krb5_kdc_configuration */*config*/,
 	const KDC_REQ */*req*/,
 	const PA_DATA */*pa*/,
+	hdb_entry_ex */*client*/,
 	pk_client_params **/*ret_params*/);
=20
 krb5_error_code
@@ -274,13 +226,7 @@
 _kdc_try_kx509_request (
 	void */*ptr*/,
 	size_t /*len*/,
-	Kx509Request */*req*/,
+	struct Kx509Request */*req*/,
 	size_t */*size*/);
=20
-krb5_error_code
-_kdc_windc_client_access (
-	krb5_context /*context*/,
-	struct hdb_entry_ex */*client*/,
-	KDC_REQ */*req*/);
-
 #endif /* __kdc_private_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kdc-protos.h
--- a/head/crypto/heimdal/kdc/kdc-protos.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kdc-protos.h	Tue Apr 17 11:51:51 2012 +0300
@@ -8,6 +8,16 @@
 extern "C" {
 #endif
=20
+krb5_error_code
+kdc_check_flags (
+	krb5_context /*context*/,
+	krb5_kdc_configuration */*config*/,
+	hdb_entry_ex */*client_ex*/,
+	const char */*client_name*/,
+	hdb_entry_ex */*server_ex*/,
+	const char */*server_name*/,
+	krb5_boolean /*is_as_req*/);
+
 void
 kdc_log (
 	krb5_context /*context*/,
@@ -35,6 +45,7 @@
 void
 kdc_openlog (
 	krb5_context /*context*/,
+	const char */*service*/,
 	krb5_kdc_configuration */*config*/);
=20
 krb5_error_code
@@ -42,6 +53,20 @@
 	krb5_context /*context*/,
 	krb5_kdc_configuration **/*config*/);
=20
+krb5_error_code
+krb5_kdc_pk_initialize (
+	krb5_context /*context*/,
+	krb5_kdc_configuration */*config*/,
+	const char */*user_id*/,
+	const char */*anchors*/,
+	char **/*pool*/,
+	char **/*revoke_list*/);
+
+krb5_error_code
+krb5_kdc_pkinit_config (
+	krb5_context /*context*/,
+	krb5_kdc_configuration */*config*/);
+
 int
 krb5_kdc_process_krb5_request (
 	krb5_context /*context*/,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kdc-replay.c
--- a/head/crypto/heimdal/kdc/kdc-replay.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kdc-replay.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: kdc-replay.c 21945 2007-10-03 21:52:24Z lha $");
-
 static int version_flag;
 static int help_flag;
=20
@@ -62,13 +60,13 @@
     int fd, optidx =3D 0;
=20
     setprogname(argv[0]);
-   =20
+
     if(getarg(args, num_args, argc, argv, &optidx))
 	usage(1);
=20
     if(help_flag)
 	usage(0);
-   =20
+
     if(version_flag){
 	print_version(NULL);
 	exit(0);
@@ -82,12 +80,29 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_kdc_default_config");
=20
-    kdc_openlog(context, config);
+    kdc_openlog(context, "kdc-replay", config);
=20
     ret =3D krb5_kdc_set_dbinfo(context, config);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_kdc_set_dbinfo");
=20
+#ifdef PKINIT
+    if (config->enable_pkinit) {
+	if (config->pkinit_kdc_identity =3D=3D NULL)
+	    krb5_errx(context, 1, "pkinit enabled but no identity");
+
+	if (config->pkinit_kdc_anchors =3D=3D NULL)
+	    krb5_errx(context, 1, "pkinit enabled but no X509 anchors");
+
+	krb5_kdc_pk_initialize(context, config,
+			       config->pkinit_kdc_identity,
+			       config->pkinit_kdc_anchors,
+			       config->pkinit_kdc_cert_pool,
+			       config->pkinit_kdc_revoke);
+
+    }
+#endif /* PKINIT */
+
     if (argc !=3D 2)
 	errx(1, "argc !=3D 2");
=20
@@ -145,7 +160,7 @@
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_print_address");
=20
-	printf("processing request from %s, %lu bytes\n",=20
+	printf("processing request from %s, %lu bytes\n",
 	       astr, (unsigned long)d.length);
=20
 	r.length =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kdc.8
--- a/head/crypto/heimdal/kdc/kdc.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kdc.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2003 - 2004 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2003 - 2004 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
 .\"
-.\" $Id: kdc.8 18419 2006-10-12 10:05:57Z lha $
+.\" $Id$
 .\"
 .Dd August 24, 2006
 .Dt KDC 8
@@ -41,27 +41,26 @@
 .Nm
 .Bk -words
 .Oo Fl c Ar file \*(Ba Xo
-.Fl -config-file=3D Ns Ar file
+.Fl Fl config-file=3D Ns Ar file
 .Xc
 .Oc
-.Op Fl p | Fl -no-require-preauth
-.Op Fl -max-request=3D Ns Ar size
-.Op Fl H | Fl -enable-http
-.Op Fl -no-524
-.Op Fl -kerberos4
-.Op Fl -kerberos4-cross-realm
+.Op Fl p | Fl Fl no-require-preauth
+.Op Fl Fl max-request=3D Ns Ar size
+.Op Fl H | Fl Fl enable-http
+.Op Fl Fl no-524
+.Op Fl Fl kerberos4
+.Op Fl Fl kerberos4-cross-realm
 .Oo Fl r Ar string \*(Ba Xo
-.Fl -v4-realm=3D Ns Ar string
+.Fl Fl v4-realm=3D Ns Ar string
 .Xc
 .Oc
-.Op Fl K | Fl -kaserver
 .Oo Fl P Ar portspec \*(Ba Xo
-.Fl -ports=3D Ns Ar portspec
+.Fl Fl ports=3D Ns Ar portspec
 .Xc
 .Oc
-.Op Fl -detach
-.Op Fl -disable-DES
-.Op Fl -addresses=3D Ns Ar list of addresses
+.Op Fl Fl detach
+.Op Fl Fl disable-des
+.Op Fl Fl addresses=3D Ns Ar list of addresses
 .Ek
 .Sh DESCRIPTION
 .Nm
@@ -72,17 +71,11 @@
 .Pp
 Options supported:
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 Specifies the location of the config file, the default is
 .Pa /var/heimdal/kdc.conf .
 This is the only value that can't be specified in the config file.
-.It Xo
-.Fl p ,
-.Fl -no-require-preauth
-.Xc
+.It Fl p , Fl Fl no-require-preauth
 Turn off the requirement for pre-autentication in the initial AS-REQ
 for all principals.
 The use of pre-authentication makes it more difficult to do offline
@@ -95,34 +88,20 @@
 The default is to require pre-authentication.
 Adding the require-preauth per principal is a more flexible way of
 handling this.
-.It Xo
-.Fl -max-request=3D Ns Ar size
-.Xc
+.It Fl Fl max-request=3D Ns Ar size
 Gives an upper limit on the size of the requests that the kdc is
 willing to handle.
-.It Xo
-.Fl H ,
-.Fl -enable-http
-.Xc
+.It Fl H , Fl Fl enable-http
 Makes the kdc listen on port 80 and handle requests encapsulated in HTTP.
-.It Xo
-.Fl -no-524
-.Xc
+.It Fl Fl no-524
 don't respond to 524 requests
-.It Xo
-.Fl -kerberos4
-.Xc
+.It Fl Fl kerberos4
 respond to Kerberos 4 requests
-.It Xo
-.Fl -kerberos4-cross-realm
-.Xc
+.It Fl Fl kerberos4-cross-realm
 respond to Kerberos 4 requests from foreign realms.
 This is a known security hole and should not be enabled unless you
 understand the consequences and are willing to live with them.
-.It Xo
-.Fl r Ar string ,
-.Fl -v4-realm=3D Ns Ar string
-.Xc
+.It Fl r Ar string , Fl Fl v4-realm=3D Ns Ar string
 What realm this server should act as when dealing with version 4
 requests.
 The database can contain any number of realms, but since the version 4
@@ -130,29 +109,21 @@
 specified.
 The default is whatever is returned by
 .Fn krb_get_lrealm .
-This option is only availabe if the KDC has been compiled with version
+This option is only available if the KDC has been compiled with version
 4 support.
-.It Xo
-.Fl K ,
-.Fl -kaserver
-.Xc
-Enable kaserver emulation (in case it's compiled in).
-.It Xo
-.Fl P Ar portspec ,
-.Fl -ports=3D Ns Ar portspec
-.Xc
+.It Fl P Ar portspec , Fl Fl ports=3D Ns Ar portspec
 Specifies the set of ports the KDC should listen on.
 It is given as a
 white-space separated list of services or port numbers.
-.It Fl -addresses=3D Ns Ar list of addresses
+.It Fl Fl addresses=3D Ns Ar list of addresses
 The list of addresses to listen for requests on.
 By default, the kdc will listen on all the locally configured
 addresses.
 If only a subset is desired, or the automatic detection fails, this
 option might be used.
-.It Fl -detach
+.It Fl Fl detach
 detach from pty and run as a daemon.
-.It Fl -disable-DES
+.It Fl Fl disable-des
 disable add des encryption types, makes the kdc not use them.
 .El
 .Pp
@@ -163,13 +134,13 @@
 The entity used for logging is
 .Nm kdc .
 .Sh CONFIGURATION FILE
-The configuration file has the same syntax as=20
+The configuration file has the same syntax as
 .Xr krb5.conf 5 ,
-but will be read before=20
+but will be read before
 .Pa /etc/krb5.conf ,
 so it may override settings found there.
 Options specific to the KDC only are found in the
-.Dq [kdc]=20
+.Dq [kdc]
 section.
 All the command-line options can preferably be added in the
 configuration file.
@@ -179,7 +150,7 @@
 .Dl require-preauth =3D no
 .Pp
 (in fact you can specify the option as
-.Fl -require-preauth=3Dno ) .
+.Fl Fl require-preauth=3Dno ) .
 .Pp
 And there are some configuration options which do not have
 command-line equivalents:
@@ -198,11 +169,8 @@
 .It Li max-kdc-datagram-reply-length =3D Va number
 Maximum packet size the UDP rely that the KDC will transmit, instead
 the KDC sends back a reply telling the client to use TCP instead.
-.It Li transited-policy =3D Xo
-.Li always-check \*(Ba
-.Li allow-per-principal |
-.Li always-honour-request
-.Xc
+.It Li transited-policy =3D Li always-check \*(Ba \
+Li allow-per-principal | Li always-honour-request
 This controls how KDC requests with the
 .Li disable-transited-check
 flag are handled. It can be one of:
@@ -227,7 +195,7 @@
 sending out warning messages.
 .El
 .Pp
-The configuration file is only read when the=20
+The configuration file is only read when the
 .Nm
 is started.
 If changes made to the configuration file are to take effect, the
@@ -252,7 +220,7 @@
 socket, and make sure your clients use TCP to connect.
 For instance, this will listen to IPv4 TCP port 88 only:
 .Bd -literal -offset indent
-kdc --addresses=3D0.0.0.0 --ports=3D"88/tcp"=20
+kdc --addresses=3D0.0.0.0 --ports=3D"88/tcp"
 .Ed
 .Pp
 There should be a way to specify protocol, port, and address triplets,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kdc.h
--- a/head/crypto/heimdal/kdc/kdc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kdc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,51 +1,52 @@
 /*
- * Copyright (c) 1997-2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
+ * Copyright (c) 1997-2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  *
  * Copyright (c) 2005 Andrew Bartlett <abartlet at samba.org>
- *=20
- * All rights reserved.=20
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/*=20
- * $Id: kdc.h 21287 2007-06-25 14:09:03Z lha $=20
+/*
+ * $Id$
  */
=20
 #ifndef __KDC_H__
 #define __KDC_H__
=20
+#include <hdb.h>
 #include <krb5.h>
=20
 enum krb5_kdc_trpolicy {
     TRPOLICY_ALWAYS_CHECK,
-    TRPOLICY_ALLOW_PER_PRINCIPAL,=20
+    TRPOLICY_ALLOW_PER_PRINCIPAL,
     TRPOLICY_ALWAYS_HONOUR_REQUEST
 };
=20
@@ -57,26 +58,28 @@
     int num_db;
=20
     krb5_boolean encode_as_rep_as_tgs_rep; /* bug compatibility */
-=09
+
+    krb5_boolean tgt_use_strongest_session_key;
+    krb5_boolean preauth_use_strongest_session_key;
+    krb5_boolean svc_use_strongest_session_key;
+    krb5_boolean use_strongest_server_key;
+
     krb5_boolean check_ticket_addresses;
     krb5_boolean allow_null_ticket_addresses;
     krb5_boolean allow_anonymous;
     enum krb5_kdc_trpolicy trpolicy;
=20
-    char *v4_realm;
-    krb5_boolean enable_v4;
-    krb5_boolean enable_v4_cross_realm;
-    krb5_boolean enable_v4_per_principal;
-
-    krb5_boolean enable_kaserver;
-
-    krb5_boolean enable_524;
-
     krb5_boolean enable_pkinit;
     krb5_boolean pkinit_princ_in_cert;
-    char *pkinit_kdc_ocsp_file;
+    const char *pkinit_kdc_identity;
+    const char *pkinit_kdc_anchors;
+    const char *pkinit_kdc_friendly_name;
+    const char *pkinit_kdc_ocsp_file;
+    char **pkinit_kdc_cert_pool;
+    char **pkinit_kdc_revoke;
     int pkinit_dh_min_bits;
     int pkinit_require_binding;
+    int pkinit_allow_proxy_certs;
=20
     krb5_log_facility *logf;
=20
@@ -91,6 +94,20 @@
=20
 } krb5_kdc_configuration;
=20
+struct krb5_kdc_service {
+    unsigned int flags;
+#define KS_KRB5		1
+#define KS_NO_LENGTH	2
+    krb5_error_code (*process)(krb5_context context,
+			       krb5_kdc_configuration *config,
+			       krb5_data *req_buffer,
+			       krb5_data *reply,
+			       const char *from,
+			       struct sockaddr *addr,
+			       int datagram_reply,
+			       int *claim);
+};
+
 #include <kdc-protos.h>
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kdc_locl.h
--- a/head/crypto/heimdal/kdc/kdc_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kdc_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,60 +1,65 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/*=20
- * $Id: kdc_locl.h 22247 2007-12-08 23:49:41Z lha $=20
+/*
+ * $Id$
  */
=20
 #ifndef __KDC_LOCL_H__
 #define __KDC_LOCL_H__
=20
 #include "headers.h"
-#include "kdc.h"
=20
 typedef struct pk_client_params pk_client_params;
+struct DigestREQ;
+struct Kx509Request;
 #include <kdc-private.h>
=20
 extern sig_atomic_t exit_flag;
-extern size_t max_request;
+extern size_t max_request_udp;
+extern size_t max_request_tcp;
 extern const char *request_log;
 extern const char *port_str;
 extern krb5_addresses explicit_addresses;
=20
 extern int enable_http;
=20
+#ifdef SUPPORT_DETACH
+
 #define DETACH_IS_DEFAULT FALSE
=20
 extern int detach_from_console;
+#endif
=20
 extern const struct units _kdc_digestunits[];
=20
@@ -63,10 +68,17 @@
 extern struct timeval _kdc_now;
 #define kdc_time (_kdc_now.tv_sec)
=20
+extern char *runas_string;
+extern char *chroot_string;
+
 void
 loop(krb5_context context, krb5_kdc_configuration *config);
=20
 krb5_kdc_configuration *
 configure(krb5_context context, int argc, char **argv);
=20
+#ifdef __APPLE__
+void bonjour_announce(krb5_context, krb5_kdc_configuration *);
+#endif
+
 #endif /* __KDC_LOCL_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kerberos5.c
--- a/head/crypto/heimdal/kdc/kerberos5.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kerberos5.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: kerberos5.c 22071 2007-11-14 20:04:50Z lha $");
-
 #define MAX_TIME ((time_t)((1U << 31) - 1))
=20
 void
@@ -60,13 +58,13 @@
 }
=20
 static void
-set_salt_padata (METHOD_DATA *md, Salt *salt)
+set_salt_padata(METHOD_DATA *md, Salt *salt)
 {
     if (salt) {
-	realloc_method_data(md);
-	md->val[md->len - 1].padata_type =3D salt->type;
-	der_copy_octet_string(&salt->salt,
-			      &md->val[md->len - 1].padata_value);
+       realloc_method_data(md);
+       md->val[md->len - 1].padata_type =3D salt->type;
+       der_copy_octet_string(&salt->salt,
+                             &md->val[md->len - 1].padata_value);
     }
 }
=20
@@ -76,15 +74,33 @@
     if (req->padata =3D=3D NULL)
 	return NULL;
=20
-    while(*start < req->padata->len){
+    while((size_t)*start < req->padata->len){
 	(*start)++;
-	if(req->padata->val[*start - 1].padata_type =3D=3D type)
+	if(req->padata->val[*start - 1].padata_type =3D=3D (unsigned)type)
 	    return &req->padata->val[*start - 1];
     }
     return NULL;
 }
=20
 /*
+ * This is a hack to allow predefined weak services, like afs to
+ * still use weak types
+ */
+
+krb5_boolean
+_kdc_is_weak_exception(krb5_principal principal, krb5_enctype etype)
+{
+    if (principal->name.name_string.len > 0 &&
+	strcmp(principal->name.name_string.val[0], "afs") =3D=3D 0 &&
+	(etype =3D=3D ETYPE_DES_CBC_CRC
+	 || etype =3D=3D ETYPE_DES_CBC_MD4
+	 || etype =3D=3D ETYPE_DES_CBC_MD5))
+	return TRUE;
+    return FALSE;
+}
+
+
+/*
  * Detect if `key' is the using the the precomputed `default_salt'.
  */
=20
@@ -107,36 +123,103 @@
  */
=20
 krb5_error_code
-_kdc_find_etype(krb5_context context, const hdb_entry_ex *princ,
-		krb5_enctype *etypes, unsigned len,=20
-		Key **ret_key, krb5_enctype *ret_etype)
+_kdc_find_etype(krb5_context context, krb5_boolean use_strongest_session_k=
ey,
+		krb5_boolean is_preauth, hdb_entry_ex *princ,
+		krb5_enctype *etypes, unsigned len,
+		krb5_enctype *ret_enctype, Key **ret_key)
 {
+    krb5_error_code ret;
+    krb5_salt def_salt;
+    krb5_enctype enctype =3D ETYPE_NULL;
+    Key *key;
     int i;
-    krb5_error_code ret =3D KRB5KDC_ERR_ETYPE_NOSUPP;
-    krb5_salt def_salt;
=20
-    krb5_get_pw_salt (context, princ->entry.principal, &def_salt);
+    /* We'll want to avoid keys with v4 salted keys in the pre-auth case..=
. */
+    ret =3D krb5_get_pw_salt(context, princ->entry.principal, &def_salt);
+    if (ret)
+	return ret;
=20
-    for(i =3D 0; ret !=3D 0 && i < len ; i++) {
-	Key *key =3D NULL;
+    ret =3D KRB5KDC_ERR_ETYPE_NOSUPP;
=20
-	if (krb5_enctype_valid(context, etypes[i]) !=3D 0)
-	    continue;
+    if (use_strongest_session_key) {
+	const krb5_enctype *p;
+	krb5_enctype clientbest =3D ETYPE_NULL;
+	int j;
=20
-	while (hdb_next_enctype2key(context, &princ->entry, etypes[i], &key) =3D=
=3D 0) {
-	    if (key->key.keyvalue.length =3D=3D 0) {
-		ret =3D KRB5KDC_ERR_NULL_KEY;
+	/*
+	 * Pick the strongest key that the KDC, target service, and
+	 * client all support, using the local cryptosystem enctype
+	 * list in strongest-to-weakest order to drive the search.
+	 *
+	 * This is not what RFC4120 says to do, but it encourages
+	 * adoption of stronger enctypes.  This doesn't play well with
+	 * clients that have multiple Kerberos client implementations
+	 * available with different supported enctype lists.
+	 */
+
+	/* drive the search with local supported enctypes list */
+	p =3D krb5_kerberos_enctypes(context);
+	for (i =3D 0; p[i] !=3D ETYPE_NULL && enctype =3D=3D ETYPE_NULL; i++) {
+	    if (krb5_enctype_valid(context, p[i]) !=3D 0)
 		continue;
+
+	    /* check that the client supports it too */
+	    for (j =3D 0; j < len && enctype =3D=3D ETYPE_NULL; j++) {
+		if (p[i] !=3D etypes[j])
+		    continue;
+		/* save best of union of { client, crypto system } */
+		if (clientbest =3D=3D ETYPE_NULL)
+		    clientbest =3D p[i];
+		/* check target princ support */
+		ret =3D hdb_enctype2key(context, &princ->entry, p[i], &key);
+		if (ret)
+		    continue;
+		if (is_preauth && !is_default_salt_p(&def_salt, key))
+		    continue;
+		enctype =3D p[i];
 	    }
-	    *ret_key   =3D key;
-	    *ret_etype =3D etypes[i];
-	    ret =3D 0;
-	    if (is_default_salt_p(&def_salt, key)) {
-		krb5_free_salt (context, def_salt);
-		return ret;
+	}
+	if (clientbest !=3D ETYPE_NULL && enctype =3D=3D ETYPE_NULL)
+	    enctype =3D clientbest;
+	else if (enctype =3D=3D ETYPE_NULL)
+	    ret =3D KRB5KDC_ERR_ETYPE_NOSUPP;
+	if (ret =3D=3D 0 && ret_enctype !=3D NULL)
+	    *ret_enctype =3D enctype;
+	if (ret =3D=3D 0 && ret_key !=3D NULL)
+	    *ret_key =3D key;
+    } else {
+	/*
+	 * Pick the first key from the client's enctype list that is
+	 * supported by the cryptosystem and by the given principal.
+	 *
+	 * RFC4120 says we SHOULD pick the first _strong_ key from the
+	 * client's list... not the first key...  If the admin disallows
+	 * weak enctypes in krb5.conf and selects this key selection
+	 * algorithm, then we get exactly what RFC4120 says.
+	 */
+	for(key =3D NULL, i =3D 0; ret !=3D 0 && i < len; i++, key =3D NULL) {
+
+	    if (krb5_enctype_valid(context, etypes[i]) !=3D 0 &&
+		!_kdc_is_weak_exception(princ->entry.principal, etypes[i]))
+		continue;
+
+	    while (hdb_next_enctype2key(context, &princ->entry, etypes[i], &key) =
=3D=3D 0) {
+		if (key->key.keyvalue.length =3D=3D 0) {
+		    ret =3D KRB5KDC_ERR_NULL_KEY;
+		    continue;
+		}
+		if (ret_key !=3D NULL)
+		    *ret_key =3D key;
+		if (ret_enctype !=3D NULL)
+		    *ret_enctype =3D etypes[i];
+		ret =3D 0;
+		if (is_preauth && is_default_salt_p(&def_salt, key))
+		    goto out;
 	    }
 	}
     }
+
+out:
     krb5_free_salt (context, def_salt);
     return ret;
 }
@@ -159,44 +242,44 @@
 }
=20
 void
-_kdc_log_timestamp(krb5_context context,=20
+_kdc_log_timestamp(krb5_context context,
 		   krb5_kdc_configuration *config,
 		   const char *type,
-		   KerberosTime authtime, KerberosTime *starttime,=20
+		   KerberosTime authtime, KerberosTime *starttime,
 		   KerberosTime endtime, KerberosTime *renew_till)
 {
-    char authtime_str[100], starttime_str[100],=20
+    char authtime_str[100], starttime_str[100],
 	endtime_str[100], renewtime_str[100];
-   =20
-    krb5_format_time(context, authtime,=20
-		     authtime_str, sizeof(authtime_str), TRUE);=20
+
+    krb5_format_time(context, authtime,
+		     authtime_str, sizeof(authtime_str), TRUE);
     if (starttime)
-	krb5_format_time(context, *starttime,=20
-			 starttime_str, sizeof(starttime_str), TRUE);=20
+	krb5_format_time(context, *starttime,
+			 starttime_str, sizeof(starttime_str), TRUE);
     else
 	strlcpy(starttime_str, "unset", sizeof(starttime_str));
-    krb5_format_time(context, endtime,=20
-		     endtime_str, sizeof(endtime_str), TRUE);=20
+    krb5_format_time(context, endtime,
+		     endtime_str, sizeof(endtime_str), TRUE);
     if (renew_till)
-	krb5_format_time(context, *renew_till,=20
-			 renewtime_str, sizeof(renewtime_str), TRUE);=20
+	krb5_format_time(context, *renew_till,
+			 renewtime_str, sizeof(renewtime_str), TRUE);
     else
 	strlcpy(renewtime_str, "unset", sizeof(renewtime_str));
-   =20
+
     kdc_log(context, config, 5,
 	    "%s authtime: %s starttime: %s endtime: %s renew till: %s",
 	    type, authtime_str, starttime_str, endtime_str, renewtime_str);
 }
=20
 static void
-log_patypes(krb5_context context,=20
+log_patypes(krb5_context context,
 	    krb5_kdc_configuration *config,
 	    METHOD_DATA *padata)
 {
     struct rk_strpool *p =3D NULL;
     char *str;
-    int i;
-	   =20
+    size_t i;
+
     for (i =3D 0; i < padata->len; i++) {
 	switch(padata->val[i].padata_type) {
 	case KRB5_PADATA_PK_AS_REQ:
@@ -224,7 +307,7 @@
     }
     if (p =3D=3D NULL)
 	p =3D rk_strpoolprintf(p, "none");
-=09
+
     str =3D rk_strpoolcollect(p);
     kdc_log(context, config, 0, "Client sent patypes: %s", str);
     free(str);
@@ -238,23 +321,25 @@
 krb5_error_code
 _kdc_encode_reply(krb5_context context,
 		  krb5_kdc_configuration *config,
-		  KDC_REP *rep, const EncTicketPart *et, EncKDCRepPart *ek,=20
-		  krb5_enctype etype,=20
+		  KDC_REP *rep, const EncTicketPart *et, EncKDCRepPart *ek,
+		  krb5_enctype etype,
 		  int skvno, const EncryptionKey *skey,
-		  int ckvno, const EncryptionKey *ckey,
+		  int ckvno, const EncryptionKey *reply_key,
+		  int rk_is_subkey,
 		  const char **e_text,
 		  krb5_data *reply)
 {
     unsigned char *buf;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     krb5_error_code ret;
     krb5_crypto crypto;
=20
     ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size, et, &len, ret);
     if(ret) {
-	kdc_log(context, config, 0, "Failed to encode ticket: %s",=20
-		krb5_get_err_text(context, ret));
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "Failed to encode ticket: %s", msg);
+	krb5_free_error_message(context, msg);
 	return ret;
     }
     if(buf_size !=3D len) {
@@ -266,13 +351,15 @@
=20
     ret =3D krb5_crypto_init(context, skey, etype, &crypto);
     if (ret) {
+        const char *msg;
 	free(buf);
-	kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-		krb5_get_err_text(context, ret));
+	msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+	krb5_free_error_message(context, msg);
 	return ret;
     }
=20
-    ret =3D krb5_encrypt_EncryptedData(context,=20
+    ret =3D krb5_encrypt_EncryptedData(context,
 				     crypto,
 				     KRB5_KU_TICKET,
 				     buf,
@@ -282,18 +369,20 @@
     free(buf);
     krb5_crypto_destroy(context, crypto);
     if(ret) {
-	kdc_log(context, config, 0, "Failed to encrypt data: %s",
-		krb5_get_err_text(context, ret));
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "Failed to encrypt data: %s", msg);
+	krb5_free_error_message(context, msg);
 	return ret;
     }
-   =20
+
     if(rep->msg_type =3D=3D krb_as_rep && !config->encode_as_rep_as_tgs_re=
p)
 	ASN1_MALLOC_ENCODE(EncASRepPart, buf, buf_size, ek, &len, ret);
     else
 	ASN1_MALLOC_ENCODE(EncTGSRepPart, buf, buf_size, ek, &len, ret);
     if(ret) {
-	kdc_log(context, config, 0, "Failed to encode KDC-REP: %s",=20
-		krb5_get_err_text(context, ret));
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "Failed to encode KDC-REP: %s", msg);
+	krb5_free_error_message(context, msg);
 	return ret;
     }
     if(buf_size !=3D len) {
@@ -302,11 +391,12 @@
 	*e_text =3D "KDC internal error";
 	return KRB5KRB_ERR_GENERIC;
     }
-    ret =3D krb5_crypto_init(context, ckey, 0, &crypto);
+    ret =3D krb5_crypto_init(context, reply_key, 0, &crypto);
     if (ret) {
+	const char *msg =3D krb5_get_error_message(context, ret);
 	free(buf);
-	kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-		krb5_get_err_text(context, ret));
+	kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+	krb5_free_error_message(context, msg);
 	return ret;
     }
     if(rep->msg_type =3D=3D krb_as_rep) {
@@ -322,7 +412,7 @@
     } else {
 	krb5_encrypt_EncryptedData(context,
 				   crypto,
-				   KRB5_KU_TGS_REP_ENC_PART_SESSION,
+				   rk_is_subkey ? KRB5_KU_TGS_REP_ENC_PART_SUB_KEY : KRB5_KU_TGS_REP_E=
NC_PART_SESSION,
 				   buf,
 				   len,
 				   ckvno,
@@ -332,8 +422,9 @@
     }
     krb5_crypto_destroy(context, crypto);
     if(ret) {
-	kdc_log(context, config, 0, "Failed to encode KDC-REP: %s",=20
-		krb5_get_err_text(context, ret));
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "Failed to encode KDC-REP: %s", msg);
+	krb5_free_error_message(context, msg);
 	return ret;
     }
     if(buf_size !=3D len) {
@@ -362,7 +453,7 @@
     case ETYPE_DES3_CBC_SHA1:
     case ETYPE_ARCFOUR_HMAC_MD5:
     case ETYPE_ARCFOUR_HMAC_MD5_56:
-    /*=20
+    /*
      * The following three is "old" windows enctypes and is needed for
      * windows 2000 hosts.
      */
@@ -375,18 +466,6 @@
     }
 }
=20
-static int
-only_older_enctype_p(const KDC_REQ *req)
-{
-    int i;
-
-    for(i =3D 0; i < req->req_body.etype.len; i++) {
-	if (!older_enctype(req->req_body.etype.val[i]))
-	    return 0;
-    }
-    return 1;
-}
-
 /*
  *
  */
@@ -404,7 +483,7 @@
 	else if(key->salt->type =3D=3D hdb_afs3_salt)
 	    *ent->salttype =3D 2;
 	else {
-	    kdc_log(context, config, 0, "unknown salt-type: %d",=20
+	    kdc_log(context, config, 0, "unknown salt-type: %d",
 		    key->salt->type);
 	    return KRB5KRB_ERR_GENERIC;
 	}
@@ -417,7 +496,7 @@
 	ALLOC(ent->salttype);
 	*ent->salttype =3D key->salt->type;
 #else
-	/*=20
+	/*
 	 * We shouldn't sent salttype since it is incompatible with the
 	 * specification and it breaks windows clients.  The afs
 	 * salting problem is solved by using KRB5-PADATA-AFS3-SALT
@@ -440,74 +519,25 @@
 }
=20
 static krb5_error_code
-get_pa_etype_info(krb5_context context,=20
+get_pa_etype_info(krb5_context context,
 		  krb5_kdc_configuration *config,
-		  METHOD_DATA *md, hdb_entry *client,=20
-		  ENCTYPE *etypes, unsigned int etypes_len)
+		  METHOD_DATA *md, Key *ckey)
 {
     krb5_error_code ret =3D 0;
-    int i, j;
-    unsigned int n =3D 0;
     ETYPE_INFO pa;
     unsigned char *buf;
     size_t len;
-   =20
=20
-    pa.len =3D client->keys.len;
-    if(pa.len > UINT_MAX/sizeof(*pa.val))
-	return ERANGE;
-    pa.val =3D malloc(pa.len * sizeof(*pa.val));
+
+    pa.len =3D 1;
+    pa.val =3D calloc(1, sizeof(pa.val[0]));
     if(pa.val =3D=3D NULL)
 	return ENOMEM;
-    memset(pa.val, 0, pa.len * sizeof(*pa.val));
=20
-    for(i =3D 0; i < client->keys.len; i++) {
-	for (j =3D 0; j < n; j++)
-	    if (pa.val[j].etype =3D=3D client->keys.val[i].key.keytype)
-		goto skip1;
-	for(j =3D 0; j < etypes_len; j++) {
-	    if(client->keys.val[i].key.keytype =3D=3D etypes[j]) {
- 		if (krb5_enctype_valid(context, etypes[j]) !=3D 0)
- 		    continue;
-		if (!older_enctype(etypes[j]))
- 		    continue;
-		if (n >=3D pa.len)
-		    krb5_abortx(context, "internal error: n >=3D p.len");
-		if((ret =3D make_etype_info_entry(context,=20
-						&pa.val[n++],=20
-						&client->keys.val[i])) !=3D 0) {
-		    free_ETYPE_INFO(&pa);
-		    return ret;
-		}
-		break;
-	    }
-	}
-    skip1:;
-    }
-    for(i =3D 0; i < client->keys.len; i++) {
-	/* already added? */
-	for(j =3D 0; j < etypes_len; j++) {
-	    if(client->keys.val[i].key.keytype =3D=3D etypes[j])
-		goto skip2;
-	}
-	if (krb5_enctype_valid(context, client->keys.val[i].key.keytype) !=3D 0)
-	    continue;
-	if (!older_enctype(etypes[j]))
-	    continue;
-	if (n >=3D pa.len)
-	    krb5_abortx(context, "internal error: n >=3D p.len");
-	if((ret =3D make_etype_info_entry(context,=20
-					&pa.val[n++],=20
-					&client->keys.val[i])) !=3D 0) {
-	    free_ETYPE_INFO(&pa);
-	    return ret;
-	}
-    skip2:;
-    }
-   =20
-    if(n < pa.len) {
-	/* stripped out dups, newer enctypes, and not valid enctypes */
- 	pa.len =3D n;
+    ret =3D make_etype_info_entry(context, &pa.val[0], ckey);
+    if (ret) {
+	free_ETYPE_INFO(&pa);
+	return ret;
     }
=20
     ASN1_MALLOC_ENCODE(ETYPE_INFO, buf, len, &pa, &len, ret);
@@ -565,8 +595,8 @@
 	    ent->s2kparams =3D NULL;
 	    return ENOMEM;
 	}
-	_krb5_put_int(ent->s2kparams->data,=20
-		      _krb5_AES_string_to_default_iterator,=20
+	_krb5_put_int(ent->s2kparams->data,
+		      _krb5_AES_string_to_default_iterator,
 		      ent->s2kparams->length);
 	break;
     case ETYPE_DES_CBC_CRC:
@@ -584,7 +614,7 @@
 		ent->s2kparams =3D NULL;
 		return ENOMEM;
 	    }
-	    _krb5_put_int(ent->s2kparams->data,=20
+	    _krb5_put_int(ent->s2kparams->data,
 			  1,
 			  ent->s2kparams->length);
 	}
@@ -602,68 +632,24 @@
  */
=20
 static krb5_error_code
-get_pa_etype_info2(krb5_context context,=20
+get_pa_etype_info2(krb5_context context,
 		   krb5_kdc_configuration *config,
-		   METHOD_DATA *md, hdb_entry *client,=20
-		   ENCTYPE *etypes, unsigned int etypes_len)
+		   METHOD_DATA *md, Key *ckey)
 {
     krb5_error_code ret =3D 0;
-    int i, j;
-    unsigned int n =3D 0;
     ETYPE_INFO2 pa;
     unsigned char *buf;
     size_t len;
=20
-    pa.len =3D client->keys.len;
-    if(pa.len > UINT_MAX/sizeof(*pa.val))
-	return ERANGE;
-    pa.val =3D malloc(pa.len * sizeof(*pa.val));
+    pa.len =3D 1;
+    pa.val =3D calloc(1, sizeof(pa.val[0]));
     if(pa.val =3D=3D NULL)
 	return ENOMEM;
-    memset(pa.val, 0, pa.len * sizeof(*pa.val));
=20
-    for(i =3D 0; i < client->keys.len; i++) {
-	for (j =3D 0; j < n; j++)
-	    if (pa.val[j].etype =3D=3D client->keys.val[i].key.keytype)
-		goto skip1;
-	for(j =3D 0; j < etypes_len; j++) {
-	    if(client->keys.val[i].key.keytype =3D=3D etypes[j]) {
-		if (krb5_enctype_valid(context, etypes[j]) !=3D 0)
-		    continue;
-		if (n >=3D pa.len)
-		    krb5_abortx(context, "internal error: n >=3D p.len");
-		if((ret =3D make_etype_info2_entry(&pa.val[n++],=20
-						 &client->keys.val[i])) !=3D 0) {
-		    free_ETYPE_INFO2(&pa);
-		    return ret;
-		}
-		break;
-	    }
-	}
-    skip1:;
-    }
-    /* send enctypes that the client doesn't know about too */
-    for(i =3D 0; i < client->keys.len; i++) {
-	/* already added? */
-	for(j =3D 0; j < etypes_len; j++) {
-	    if(client->keys.val[i].key.keytype =3D=3D etypes[j])
-		goto skip2;
-	}
-	if (krb5_enctype_valid(context, client->keys.val[i].key.keytype) !=3D 0)
-	    continue;
-	if (n >=3D pa.len)
-	    krb5_abortx(context, "internal error: n >=3D p.len");
-	if((ret =3D make_etype_info2_entry(&pa.val[n++],
-					 &client->keys.val[i])) !=3D 0) {
-	    free_ETYPE_INFO2(&pa);
-	    return ret;
-	}
-      skip2:;
-    }
-   =20
-    if(n < pa.len) {
-	/* stripped out dups, and not valid enctypes */
- 	pa.len =3D n;
+    ret =3D make_etype_info2_entry(&pa.val[0], ckey);
+    if (ret) {
+	free_ETYPE_INFO2(&pa);
+	return ret;
     }
=20
     ASN1_MALLOC_ENCODE(ETYPE_INFO2, buf, len, &pa, &len, ret);
@@ -693,10 +679,12 @@
 	   const KDC_REQ_BODY *b)
 {
     krb5_error_code ret;
-    struct rk_strpool *p =3D NULL;
+    struct rk_strpool *p;
     char *str;
-    int i;
-   =20
+    size_t i;
+
+    p =3D rk_strpoolprintf(NULL, "%s", "Client supported enctypes: ");
+
     for (i =3D 0; i < b->etype.len; i++) {
 	ret =3D krb5_enctype_to_string(context, b->etype.val[i], &str);
 	if (ret =3D=3D 0) {
@@ -713,10 +701,6 @@
     }
     if (p =3D=3D NULL)
 	p =3D rk_strpoolprintf(p, "no encryption types");
-   =20
-    str =3D rk_strpoolcollect(p);
-    kdc_log(context, config, 0, "Client supported enctypes: %s", str);
-    free(str);
=20
     {
 	char *cet;
@@ -726,21 +710,26 @@
 	if(ret =3D=3D 0) {
 	    ret =3D krb5_enctype_to_string(context, setype, &set);
 	    if (ret =3D=3D 0) {
-		kdc_log(context, config, 5, "Using %s/%s", cet, set);
+		p =3D rk_strpoolprintf(p, ", using %s/%s", cet, set);
 		free(set);
 	    }
 	    free(cet);
 	}
 	if (ret !=3D 0)
-	    kdc_log(context, config, 5, "Using e-types %d/%d", cetype, setype);
+	    p =3D rk_strpoolprintf(p, ", using enctypes %d/%d",
+				 cetype, setype);
     }
-   =20
+
+    str =3D rk_strpoolcollect(p);
+    kdc_log(context, config, 0, "%s", str);
+    free(str);
+
     {
 	char fixedstr[128];
-	unparse_flags(KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(),=20
+	unparse_flags(KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(),
 		      fixedstr, sizeof(fixedstr));
 	if(*fixedstr)
-	    kdc_log(context, config, 2, "Requested flags: %s", fixedstr);
+	    kdc_log(context, config, 0, "Requested flags: %s", fixedstr);
     }
 }
=20
@@ -751,65 +740,76 @@
  */
=20
 krb5_error_code
-_kdc_check_flags(krb5_context context,=20
-		 krb5_kdc_configuration *config,
-		 hdb_entry_ex *client_ex, const char *client_name,
-		 hdb_entry_ex *server_ex, const char *server_name,
-		 krb5_boolean is_as_req)
+kdc_check_flags(krb5_context context,
+		krb5_kdc_configuration *config,
+		hdb_entry_ex *client_ex, const char *client_name,
+		hdb_entry_ex *server_ex, const char *server_name,
+		krb5_boolean is_as_req)
 {
     if(client_ex !=3D NULL) {
 	hdb_entry *client =3D &client_ex->entry;
=20
 	/* check client */
+	if (client->flags.locked_out) {
+	    kdc_log(context, config, 0,
+		    "Client (%s) is locked out", client_name);
+	    return KRB5KDC_ERR_POLICY;
+	}
+
 	if (client->flags.invalid) {
-	    kdc_log(context, config, 0,=20
+	    kdc_log(context, config, 0,
 		    "Client (%s) has invalid bit set", client_name);
 	    return KRB5KDC_ERR_POLICY;
 	}
-=09
+
 	if(!client->flags.client){
 	    kdc_log(context, config, 0,
 		    "Principal may not act as client -- %s", client_name);
 	    return KRB5KDC_ERR_POLICY;
 	}
-=09
+
 	if (client->valid_start && *client->valid_start > kdc_time) {
 	    char starttime_str[100];
-	    krb5_format_time(context, *client->valid_start,=20
-			     starttime_str, sizeof(starttime_str), TRUE);=20
+	    krb5_format_time(context, *client->valid_start,
+			     starttime_str, sizeof(starttime_str), TRUE);
 	    kdc_log(context, config, 0,
-		    "Client not yet valid until %s -- %s",=20
+		    "Client not yet valid until %s -- %s",
 		    starttime_str, client_name);
 	    return KRB5KDC_ERR_CLIENT_NOTYET;
 	}
-=09
+
 	if (client->valid_end && *client->valid_end < kdc_time) {
 	    char endtime_str[100];
-	    krb5_format_time(context, *client->valid_end,=20
-			     endtime_str, sizeof(endtime_str), TRUE);=20
+	    krb5_format_time(context, *client->valid_end,
+			     endtime_str, sizeof(endtime_str), TRUE);
 	    kdc_log(context, config, 0,
 		    "Client expired at %s -- %s",
 		    endtime_str, client_name);
 	    return KRB5KDC_ERR_NAME_EXP;
 	}
-=09
-	if (client->pw_end && *client->pw_end < kdc_time=20
+
+	if (client->pw_end && *client->pw_end < kdc_time
 	    && (server_ex =3D=3D NULL || !server_ex->entry.flags.change_pw)) {
 	    char pwend_str[100];
-	    krb5_format_time(context, *client->pw_end,=20
-			     pwend_str, sizeof(pwend_str), TRUE);=20
+	    krb5_format_time(context, *client->pw_end,
+			     pwend_str, sizeof(pwend_str), TRUE);
 	    kdc_log(context, config, 0,
-		    "Client's key has expired at %s -- %s",=20
+		    "Client's key has expired at %s -- %s",
 		    pwend_str, client_name);
 	    return KRB5KDC_ERR_KEY_EXPIRED;
 	}
     }
=20
     /* check server */
-   =20
+
     if (server_ex !=3D NULL) {
 	hdb_entry *server =3D &server_ex->entry;
=20
+	if (server->flags.locked_out) {
+	    kdc_log(context, config, 0,
+		    "Client server locked out -- %s", server_name);
+	    return KRB5KDC_ERR_POLICY;
+	}
 	if (server->flags.invalid) {
 	    kdc_log(context, config, 0,
 		    "Server has invalid flag set -- %s", server_name);
@@ -830,8 +830,8 @@
=20
 	if (server->valid_start && *server->valid_start > kdc_time) {
 	    char starttime_str[100];
-	    krb5_format_time(context, *server->valid_start,=20
-			     starttime_str, sizeof(starttime_str), TRUE);=20
+	    krb5_format_time(context, *server->valid_start,
+			     starttime_str, sizeof(starttime_str), TRUE);
 	    kdc_log(context, config, 0,
 		    "Server not yet valid until %s -- %s",
 		    starttime_str, server_name);
@@ -840,20 +840,20 @@
=20
 	if (server->valid_end && *server->valid_end < kdc_time) {
 	    char endtime_str[100];
-	    krb5_format_time(context, *server->valid_end,=20
-			     endtime_str, sizeof(endtime_str), TRUE);=20
+	    krb5_format_time(context, *server->valid_end,
+			     endtime_str, sizeof(endtime_str), TRUE);
 	    kdc_log(context, config, 0,
-		    "Server expired at %s -- %s",=20
+		    "Server expired at %s -- %s",
 		    endtime_str, server_name);
 	    return KRB5KDC_ERR_SERVICE_EXP;
 	}
=20
 	if (server->pw_end && *server->pw_end < kdc_time) {
 	    char pwend_str[100];
-	    krb5_format_time(context, *server->pw_end,=20
-			     pwend_str, sizeof(pwend_str), TRUE);=20
+	    krb5_format_time(context, *server->pw_end,
+			     pwend_str, sizeof(pwend_str), TRUE);
 	    kdc_log(context, config, 0,
-		    "Server's key has expired at -- %s",=20
+		    "Server's key has expired at -- %s",
 		    pwend_str, server_name);
 	    return KRB5KDC_ERR_KEY_EXPIRED;
 	}
@@ -868,7 +868,7 @@
  */
=20
 krb5_boolean
-_kdc_check_addresses(krb5_context context,       =20
+_kdc_check_addresses(krb5_context context,
 		     krb5_kdc_configuration *config,
 		     HostAddresses *addresses, const struct sockaddr *from)
 {
@@ -876,14 +876,14 @@
     krb5_address addr;
     krb5_boolean result;
     krb5_boolean only_netbios =3D TRUE;
-    int i;
-   =20
+    size_t i;
+
     if(config->check_ticket_addresses =3D=3D 0)
 	return TRUE;
=20
     if(addresses =3D=3D NULL)
 	return config->allow_null_ticket_addresses;
-   =20
+
     for (i =3D 0; i < addresses->len; ++i) {
 	if (addresses->val[i].addr_type !=3D KRB5_ADDRESS_NETBIOS) {
 	    only_netbios =3D FALSE;
@@ -919,7 +919,7 @@
     PA_PAC_REQUEST pacreq;
     const PA_DATA *pa;
     int i =3D 0;
-   =20
+
     pa =3D _kdc_find_padata(req, &i, KRB5_PADATA_PA_PAC_REQUEST);
     if (pa =3D=3D NULL)
 	return TRUE;
@@ -937,15 +937,26 @@
     return TRUE;
 }
=20
+krb5_boolean
+_kdc_is_anonymous(krb5_context context, krb5_principal principal)
+{
+    if (principal->name.name_type !=3D KRB5_NT_WELLKNOWN ||
+	principal->name.name_string.len !=3D 2 ||
+	strcmp(principal->name.name_string.val[0], KRB5_WELLKNOWN_NAME) !=3D 0 ||
+	strcmp(principal->name.name_string.val[1], KRB5_ANON_NAME) !=3D 0)
+	return 0;
+    return 1;
+}
+
 /*
  *
  */
=20
 krb5_error_code
-_kdc_as_rep(krb5_context context,=20
+_kdc_as_rep(krb5_context context,
 	    krb5_kdc_configuration *config,
-	    KDC_REQ *req,=20
-	    const krb5_data *req_buffer,=20
+	    KDC_REQ *req,
+	    const krb5_data *req_buffer,
 	    krb5_data *reply,
 	    const char *from,
 	    struct sockaddr *from_addr,
@@ -955,7 +966,8 @@
     AS_REP rep;
     KDCOptions f =3D b->kdc_options;
     hdb_entry_ex *client =3D NULL, *server =3D NULL;
-    krb5_enctype cetype, setype, sessionetype;
+    HDB *clientdb;
+    krb5_enctype setype, sessionetype;
     krb5_data e_data;
     EncTicketPart et;
     EncKDCRepPart ek;
@@ -965,15 +977,20 @@
     const char *e_text =3D NULL;
     krb5_crypto crypto;
     Key *ckey, *skey;
-    EncryptionKey *reply_key;
-    int flags =3D 0;
+    EncryptionKey *reply_key =3D NULL, session_key;
+    int flags =3D HDB_F_FOR_AS_REQ;
 #ifdef PKINIT
     pk_client_params *pkp =3D NULL;
 #endif
=20
     memset(&rep, 0, sizeof(rep));
+    memset(&session_key, 0, sizeof(session_key));
     krb5_data_zero(&e_data);
=20
+    ALLOC(rep.padata);
+    rep.padata->len =3D 0;
+    rep.padata->val =3D NULL;
+
     if (f.canonicalize)
 	flags |=3D HDB_F_CANON;
=20
@@ -989,37 +1006,21 @@
 	    ret =3D krb5_unparse_name(context, server_princ, &server_name);
     }
     if (ret) {
-	kdc_log(context, config, 0,=20
+	kdc_log(context, config, 0,
 		"AS-REQ malformed server name from %s", from);
 	goto out;
     }
-   =20
     if(b->cname =3D=3D NULL){
 	ret =3D KRB5KRB_ERR_GENERIC;
 	e_text =3D "No client in request";
     } else {
+	ret =3D _krb5_principalname2krb5_principal (context,
+						  &client_princ,
+						  *(b->cname),
+						  b->realm);
+	if (ret)
+	    goto out;
=20
-	if (b->cname->name_type =3D=3D KRB5_NT_ENTERPRISE_PRINCIPAL) {
-	    if (b->cname->name_string.len !=3D 1) {
-		kdc_log(context, config, 0,
-			"AS-REQ malformed canon request from %s, "
-			"enterprise name with %d name components",=20
-			from, b->cname->name_string.len);
-		ret =3D KRB5_PARSE_MALFORMED;
-		goto out;
-	    }
-	    ret =3D krb5_parse_name(context, b->cname->name_string.val[0],
-				  &client_princ);
-	    if (ret)
-		goto out;
-	} else {
-	    ret =3D _krb5_principalname2krb5_principal (context,
-						      &client_princ,
-						      *(b->cname),
-						      b->realm);
-	    if (ret)
-		goto out;
-	}
 	ret =3D krb5_unparse_name(context, client_princ, &client_name);
     }
     if (ret) {
@@ -1028,42 +1029,95 @@
 	goto out;
     }
=20
-    kdc_log(context, config, 0, "AS-REQ %s from %s for %s",=20
+    kdc_log(context, config, 0, "AS-REQ %s from %s for %s",
 	    client_name, from, server_name);
=20
-    ret =3D _kdc_db_fetch(context, config, client_princ,=20
-			HDB_F_GET_CLIENT | flags, NULL, &client);
-    if(ret){
-	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", client_name,
-		krb5_get_err_text(context, ret));
+    /*
+     *
+     */
+
+    if (_kdc_is_anonymous(context, client_princ)) {
+	if (!b->kdc_options.request_anonymous) {
+	    kdc_log(context, config, 0, "Anonymous ticket w/o anonymous flag");
+	    ret =3D KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
+	    goto out;
+	}
+    } else if (b->kdc_options.request_anonymous) {
+	kdc_log(context, config, 0,
+		"Request for a anonymous ticket with non "
+		"anonymous client name: %s", client_name);
 	ret =3D KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
 	goto out;
     }
=20
+    /*
+     *
+     */
+
+    ret =3D _kdc_db_fetch(context, config, client_princ,
+			HDB_F_GET_CLIENT | flags, NULL,
+			&clientdb, &client);
+    if(ret =3D=3D HDB_ERR_NOT_FOUND_HERE) {
+	kdc_log(context, config, 5, "client %s does not have secrets at this KDC,=
 need to proxy", client_name);
+	goto out;
+    } else if(ret){
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", client_name, msg);
+	krb5_free_error_message(context, msg);
+	ret =3D KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
+	goto out;
+    }
     ret =3D _kdc_db_fetch(context, config, server_princ,
-			HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
-			NULL, &server);
-    if(ret){
-	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", server_name,
-		krb5_get_err_text(context, ret));
+			HDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags,
+			NULL, NULL, &server);
+    if(ret =3D=3D HDB_ERR_NOT_FOUND_HERE) {
+	kdc_log(context, config, 5, "target %s does not have secrets at this KDC,=
 need to proxy", server_name);
+	goto out;
+    } else if(ret){
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "UNKNOWN -- %s: %s", server_name, msg);
+	krb5_free_error_message(context, msg);
 	ret =3D KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
 	goto out;
     }
=20
-    ret =3D _kdc_windc_client_access(context, client, req);
-    if(ret)
-	goto out;
-
-    ret =3D _kdc_check_flags(context, config,=20
-			   client, client_name,
-			   server, server_name,
-			   TRUE);
-    if(ret)
-	goto out;
-
     memset(&et, 0, sizeof(et));
     memset(&ek, 0, sizeof(ek));
=20
+    /*
+     * Select a session enctype from the list of the crypto system
+     * supported enctypes that is supported by the client and is one of
+     * the enctype of the enctype of the service (likely krbtgt).
+     *
+     * The latter is used as a hint of what enctypes all KDC support,
+     * to make sure a newer version of KDC won't generate a session
+     * enctype that an older version of a KDC in the same realm can't
+     * decrypt.
+     */
+    ret =3D _kdc_find_etype(context,
+			  krb5_principal_is_krbtgt(context, server_princ) ?
+			  config->tgt_use_strongest_session_key :
+			  config->svc_use_strongest_session_key, FALSE,
+			  client, b->etype.val, b->etype.len, &sessionetype,
+			  NULL);
+    if (ret) {
+	kdc_log(context, config, 0,
+		"Client (%s) from %s has no common enctypes with KDC "
+		"to use for the session key",
+		client_name, from);
+	goto out;
+    }
+    /*
+     * But if the KDC admin is paranoid and doesn't want to have "not
+     * the best" enctypes on the krbtgt, lets save the best pick from
+     * the client list and hope that that will work for any other
+     * KDCs.
+     */
+
+    /*
+     * Pre-auth processing
+     */
+
     if(req->padata){
 	int i;
 	const PA_DATA *pa;
@@ -1072,27 +1126,25 @@
 	log_patypes(context, config, req->padata);
=20
 #ifdef PKINIT
-	kdc_log(context, config, 5,=20
+	kdc_log(context, config, 5,
 		"Looking for PKINIT pa-data -- %s", client_name);
=20
 	e_text =3D "No PKINIT PA found";
=20
 	i =3D 0;
-	if ((pa =3D _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ)))
-	    ;
+	pa =3D _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ);
 	if (pa =3D=3D NULL) {
 	    i =3D 0;
-	    if((pa =3D _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ_WIN)))
-		;
+	    pa =3D _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ_WIN);
 	}
 	if (pa) {
 	    char *client_cert =3D NULL;
=20
-	    ret =3D _kdc_pk_rd_padata(context, config, req, pa, &pkp);
+	    ret =3D _kdc_pk_rd_padata(context, config, req, pa, client, &pkp);
 	    if (ret) {
 		ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
-		kdc_log(context, config, 5,=20
-			"Failed to decode PKINIT PA-DATA -- %s",=20
+		kdc_log(context, config, 5,
+			"Failed to decode PKINIT PA-DATA -- %s",
 			client_name);
 		goto ts_enc;
 	    }
@@ -1101,6 +1153,7 @@
=20
 	    ret =3D _kdc_pk_check_client(context,
 				       config,
+				       clientdb,
 				       client,
 				       pkp,
 				       &client_cert);
@@ -1113,10 +1166,11 @@
 		pkp =3D NULL;
 		goto out;
 	    }
+
 	    found_pa =3D 1;
 	    et.flags.pre_authent =3D 1;
 	    kdc_log(context, config, 0,
-		    "PKINIT pre-authentication succeeded -- %s using %s",=20
+		    "PKINIT pre-authentication succeeded -- %s using %s",
 		    client_name, client_cert);
 	    free(client_cert);
 	    if (pkp)
@@ -1124,7 +1178,7 @@
 	}
     ts_enc:
 #endif
-	kdc_log(context, config, 5, "Looking for ENC-TS pa-data -- %s",=20
+	kdc_log(context, config, 5, "Looking for ENC-TS pa-data -- %s",
 		client_name);
=20
 	i =3D 0;
@@ -1136,21 +1190,27 @@
 	    EncryptedData enc_data;
 	    Key *pa_key;
 	    char *str;
-	   =20
+
 	    found_pa =3D 1;
-	   =20
+
+	    if (b->kdc_options.request_anonymous) {
+		ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
+		kdc_log(context, config, 0, "ENC-TS doesn't support anon");
+		goto out;
+	    }
+
 	    ret =3D decode_EncryptedData(pa->padata_value.data,
 				       pa->padata_value.length,
 				       &enc_data,
 				       &len);
 	    if (ret) {
 		ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
-		kdc_log(context, config, 5, "Failed to decode PA-DATA -- %s",=20
+		kdc_log(context, config, 5, "Failed to decode PA-DATA -- %s",
 			client_name);
 		goto out;
 	    }
-	   =20
-	    ret =3D hdb_enctype2key(context, &client->entry,=20
+
+	    ret =3D hdb_enctype2key(context, &client->entry,
 				  enc_data.etype, &pa_key);
 	    if(ret){
 		char *estr;
@@ -1159,24 +1219,25 @@
 		if(krb5_enctype_to_string(context, enc_data.etype, &estr))
 		    estr =3D NULL;
 		if(estr =3D=3D NULL)
-		    kdc_log(context, config, 5,=20
-			    "No client key matching pa-data (%d) -- %s",=20
+		    kdc_log(context, config, 5,
+			    "No client key matching pa-data (%d) -- %s",
 			    enc_data.etype, client_name);
 		else
 		    kdc_log(context, config, 5,
-			    "No client key matching pa-data (%s) -- %s",=20
+			    "No client key matching pa-data (%s) -- %s",
 			    estr, client_name);
 		free(estr);
-		   =20
 		free_EncryptedData(&enc_data);
+
 		continue;
 	    }
=20
 	try_next_key:
 	    ret =3D krb5_crypto_init(context, &pa_key->key, 0, &crypto);
 	    if (ret) {
-		kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-			krb5_get_err_text(context, ret));
+		const char *msg =3D krb5_get_error_message(context, ret);
+		kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+		krb5_free_error_message(context, msg);
 		free_EncryptedData(&enc_data);
 		continue;
 	    }
@@ -1187,26 +1248,36 @@
 					      &enc_data,
 					      &ts_data);
 	    krb5_crypto_destroy(context, crypto);
+	    /*
+	     * Since the user might have several keys with the same
+	     * enctype but with diffrent salting, we need to try all
+	     * the keys with the same enctype.
+	     */
 	    if(ret){
 		krb5_error_code ret2;
-		ret2 =3D krb5_enctype_to_string(context,=20
+		const char *msg =3D krb5_get_error_message(context, ret);
+
+		ret2 =3D krb5_enctype_to_string(context,
 					      pa_key->key.keytype, &str);
 		if (ret2)
 		    str =3D NULL;
-		kdc_log(context, config, 5,=20
+		kdc_log(context, config, 5,
 			"Failed to decrypt PA-DATA -- %s "
 			"(enctype %s) error %s",
-			client_name,
-			str ? str : "unknown enctype",=20
-			krb5_get_err_text(context, ret));
+			client_name, str ? str : "unknown enctype", msg);
+		krb5_free_error_message(context, msg);
 		free(str);
=20
-		if(hdb_next_enctype2key(context, &client->entry,=20
+		if(hdb_next_enctype2key(context, &client->entry,
 					enc_data.etype, &pa_key) =3D=3D 0)
 		    goto try_next_key;
 		e_text =3D "Failed to decrypt PA-DATA";
=20
 		free_EncryptedData(&enc_data);
+
+		if (clientdb->hdb_auth_status)
+		    (clientdb->hdb_auth_status)(context, clientdb, client, HDB_AUTH_WRON=
G_PASSWORD);
+
 		ret =3D KRB5KDC_ERR_PREAUTH_FAILED;
 		continue;
 	    }
@@ -1219,7 +1290,7 @@
 	    if(ret){
 		e_text =3D "Failed to decode PA-ENC-TS-ENC";
 		ret =3D KRB5KDC_ERR_PREAUTH_FAILED;
-		kdc_log(context, config,=20
+		kdc_log(context, config,
 			5, "Failed to decode PA-ENC-TS_ENC -- %s",
 			client_name);
 		continue;
@@ -1227,41 +1298,39 @@
 	    free_PA_ENC_TS_ENC(&p);
 	    if (abs(kdc_time - p.patimestamp) > context->max_skew) {
 		char client_time[100];
-	=09
-		krb5_format_time(context, p.patimestamp,=20
-				 client_time, sizeof(client_time), TRUE);=20
+
+		krb5_format_time(context, p.patimestamp,
+				 client_time, sizeof(client_time), TRUE);
=20
  		ret =3D KRB5KRB_AP_ERR_SKEW;
  		kdc_log(context, config, 0,
 			"Too large time skew, "
-			"client time %s is out by %u > %u seconds -- %s",=20
-			client_time,=20
-			(unsigned)abs(kdc_time - p.patimestamp),=20
+			"client time %s is out by %u > %u seconds -- %s",
+			client_time,
+			(unsigned)abs(kdc_time - p.patimestamp),
 			context->max_skew,
 			client_name);
-#if 0
-		/* This code is from samba, needs testing */
-		/*=20
-		 * the following is needed to make windows clients
-		 * to retry using the timestamp in the error message
-		 *
-		 * this is maybe a bug in windows to not trying when e_text
-		 * is present...
+
+		/*
+		 * The following is needed to make windows clients to
+		 * retry using the timestamp in the error message, if
+		 * there is a e_text, they become unhappy.
 		 */
 		e_text =3D NULL;
-#else
-		e_text =3D "Too large time skew";
-#endif
 		goto out;
 	    }
 	    et.flags.pre_authent =3D 1;
=20
-	    ret =3D krb5_enctype_to_string(context,pa_key->key.keytype, &str);
+	    set_salt_padata(rep.padata, pa_key->salt);
+
+	    reply_key =3D &pa_key->key;
+
+	    ret =3D krb5_enctype_to_string(context, pa_key->key.keytype, &str);
 	    if (ret)
 		str =3D NULL;
=20
 	    kdc_log(context, config, 2,
-		    "ENC-TS Pre-authentication succeeded -- %s using %s",=20
+		    "ENC-TS Pre-authentication succeeded -- %s using %s",
 		    client_name, str ? str : "unknown enctype");
 	    free(str);
 	    break;
@@ -1279,6 +1348,7 @@
 	    goto out;
 	}
     }else if (config->require_preauth
+	      || b->kdc_options.request_anonymous /* hack to force anon */
 	      || client->entry.flags.require_preauth
 	      || server->entry.flags.require_preauth) {
 	METHOD_DATA method_data;
@@ -1286,11 +1356,15 @@
 	unsigned char *buf;
 	size_t len;
=20
-    use_pa:=20
+    use_pa:
 	method_data.len =3D 0;
 	method_data.val =3D NULL;
=20
 	ret =3D realloc_method_data(&method_data);
+	if (ret) {
+	    free_METHOD_DATA(&method_data);
+	    goto out;
+	}
 	pa =3D &method_data.val[method_data.len-1];
 	pa->padata_type		=3D KRB5_PADATA_ENC_TIMESTAMP;
 	pa->padata_value.length	=3D 0;
@@ -1298,36 +1372,62 @@
=20
 #ifdef PKINIT
 	ret =3D realloc_method_data(&method_data);
+	if (ret) {
+	    free_METHOD_DATA(&method_data);
+	    goto out;
+	}
 	pa =3D &method_data.val[method_data.len-1];
 	pa->padata_type		=3D KRB5_PADATA_PK_AS_REQ;
 	pa->padata_value.length	=3D 0;
 	pa->padata_value.data	=3D NULL;
=20
 	ret =3D realloc_method_data(&method_data);
+	if (ret) {
+	    free_METHOD_DATA(&method_data);
+	    goto out;
+	}
 	pa =3D &method_data.val[method_data.len-1];
 	pa->padata_type		=3D KRB5_PADATA_PK_AS_REQ_WIN;
 	pa->padata_value.length	=3D 0;
 	pa->padata_value.data	=3D NULL;
 #endif
=20
-	/*=20
-	 * RFC4120 requires:=20
-	 * - If the client only knows about old enctypes, then send
-	 *   both info replies (we send 'info' first in the list).
-	 * - If the client is 'modern', because it knows about 'new'
-	 *   enctype types, then only send the 'info2' reply.
+	/*
+	 * If there is a client key, send ETYPE_INFO{,2}
 	 */
+	ret =3D _kdc_find_etype(context,
+			      config->preauth_use_strongest_session_key, TRUE,
+			      client, b->etype.val, b->etype.len, NULL, &ckey);
+	if (ret =3D=3D 0) {
=20
-	/* XXX check ret */
-	if (only_older_enctype_p(req))
-	    ret =3D get_pa_etype_info(context, config,
-				    &method_data, &client->entry,=20
-				    b->etype.val, b->etype.len);=20
-	/* XXX check ret */
-	ret =3D get_pa_etype_info2(context, config, &method_data,=20
-				 &client->entry, b->etype.val, b->etype.len);
+	    /*
+	     * RFC4120 requires:
+	     * - If the client only knows about old enctypes, then send
+	     *   both info replies (we send 'info' first in the list).
+	     * - If the client is 'modern', because it knows about 'new'
+	     *   enctype types, then only send the 'info2' reply.
+	     *
+	     * Before we send the full list of etype-info data, we pick
+	     * the client key we would have used anyway below, just pick
+	     * that instead.
+	     */
=20
-=09
+	    if (older_enctype(ckey->key.keytype)) {
+		ret =3D get_pa_etype_info(context, config,
+					&method_data, ckey);
+		if (ret) {
+		    free_METHOD_DATA(&method_data);
+		    goto out;
+		}
+	    }
+	    ret =3D get_pa_etype_info2(context, config,
+				     &method_data, ckey);
+	    if (ret) {
+		free_METHOD_DATA(&method_data);
+		goto out;
+	    }
+	}
+
 	ASN1_MALLOC_ENCODE(METHOD_DATA, buf, len, &method_data, &len, ret);
 	free_METHOD_DATA(&method_data);
=20
@@ -1342,103 +1442,54 @@
 		client_name);
 	goto out;
     }
-   =20
+
+    if (clientdb->hdb_auth_status)
+	(clientdb->hdb_auth_status)(context, clientdb, client,
+				    HDB_AUTH_SUCCESS);
+
     /*
-     * Find the client key (for preauth ENC-TS verification and reply
-     * encryption).  Then the best encryption type for the KDC and
-     * last the best session key that shared between the client and
-     * KDC runtime enctypes.
+     * Verify flags after the user been required to prove its identity
+     * with in a preauth mech.
      */
=20
-    ret =3D _kdc_find_etype(context, client, b->etype.val, b->etype.len,
-			  &ckey, &cetype);
-    if (ret) {
-	kdc_log(context, config, 0,=20
-		"Client (%s) has no support for etypes", client_name);
+    ret =3D _kdc_check_access(context, config, client, client_name,
+			    server, server_name,
+			    req, &e_data);
+    if(ret)
 	goto out;
-    }
-=09
+
+    /*
+     * Selelct the best encryption type for the KDC with out regard to
+     * the client since the client never needs to read that data.
+     */
+
     ret =3D _kdc_get_preferred_key(context, config,
 				 server, server_name,
 				 &setype, &skey);
     if(ret)
 	goto out;
=20
-    /*=20
-     * Select a session enctype from the list of the crypto systems
-     * supported enctype, is supported by the client and is one of the
-     * enctype of the enctype of the krbtgt.
-     *
-     * The later is used as a hint what enctype all KDC are supporting
-     * to make sure a newer version of KDC wont generate a session
-     * enctype that and older version of a KDC in the same realm can't
-     * decrypt.
-     *
-     * But if the KDC admin is paranoid and doesn't want to have "no
-     * the best" enctypes on the krbtgt, lets save the best pick from
-     * the client list and hope that that will work for any other
-     * KDCs.
-     */
-    {
-	const krb5_enctype *p;
-	krb5_enctype clientbest =3D ETYPE_NULL;
-	int i, j;
-
-	p =3D krb5_kerberos_enctypes(context);
-
-	sessionetype =3D ETYPE_NULL;
-
-	for (i =3D 0; p[i] !=3D ETYPE_NULL && sessionetype =3D=3D ETYPE_NULL; i++=
) {
-	    if (krb5_enctype_valid(context, p[i]) !=3D 0)
-		continue;
-
-	    for (j =3D 0; j < b->etype.len && sessionetype =3D=3D ETYPE_NULL; j++=
) {
-		Key *dummy;
-		/* check with client */
-		if (p[i] !=3D b->etype.val[j])
-		    continue;=20
-		/* save best of union of { client, crypto system } */
-		if (clientbest =3D=3D ETYPE_NULL)
-		    clientbest =3D p[i];
-		/* check with krbtgt */
-		ret =3D hdb_enctype2key(context, &server->entry, p[i], &dummy);
-		if (ret)=20
-		    continue;
-		sessionetype =3D p[i];
-	    }
-	}
-	/* if krbtgt had no shared keys with client, pick clients best */
-	if (clientbest !=3D ETYPE_NULL && sessionetype =3D=3D ETYPE_NULL) {
-	    sessionetype =3D clientbest;
-	} else if (sessionetype =3D=3D ETYPE_NULL) {
-	    kdc_log(context, config, 0,
-		    "Client (%s) from %s has no common enctypes with KDC"
-		    "to use for the session key",=20
-		    client_name, from);=20
-	    goto out;
-	}
-    }
-
-    log_as_req(context, config, cetype, setype, b);
-
     if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey
        || (f.request_anonymous && !config->allow_anonymous)) {
 	ret =3D KRB5KDC_ERR_BADOPTION;
+	e_text =3D "Bad KDC options";
 	kdc_log(context, config, 0, "Bad KDC options -- %s", client_name);
 	goto out;
     }
-   =20
+
     rep.pvno =3D 5;
     rep.msg_type =3D krb_as_rep;
-    copy_Realm(&client->entry.principal->realm, &rep.crealm);
-    if (f.request_anonymous)
-	_kdc_make_anonymous_principalname (&rep.cname);
-    else
-	_krb5_principal2principalname(&rep.cname,=20
-				      client->entry.principal);
+
+    ret =3D copy_Realm(&client->entry.principal->realm, &rep.crealm);
+    if (ret)
+	goto out;
+    ret =3D _krb5_principal2principalname(&rep.cname, client->entry.princi=
pal);
+    if (ret)
+	goto out;
+
     rep.ticket.tkt_vno =3D 5;
     copy_Realm(&server->entry.principal->realm, &rep.ticket.realm);
-    _krb5_principal2principalname(&rep.ticket.sname,=20
+    _krb5_principal2principalname(&rep.ticket.sname,
 				  server->entry.principal);
     /* java 1.6 expects the name to be the same type, lets allow that
      * uncomplicated name-types. */
@@ -1451,6 +1502,7 @@
     if(client->entry.flags.forwardable && server->entry.flags.forwardable)
 	et.flags.forwardable =3D f.forwardable;
     else if (f.forwardable) {
+	e_text =3D "Ticket may not be forwardable";
 	ret =3D KRB5KDC_ERR_POLICY;
 	kdc_log(context, config, 0,
 		"Ticket may not be forwardable -- %s", client_name);
@@ -1459,14 +1511,16 @@
     if(client->entry.flags.proxiable && server->entry.flags.proxiable)
 	et.flags.proxiable =3D f.proxiable;
     else if (f.proxiable) {
+	e_text =3D "Ticket may not be proxiable";
 	ret =3D KRB5KDC_ERR_POLICY;
-	kdc_log(context, config, 0,=20
+	kdc_log(context, config, 0,
 		"Ticket may not be proxiable -- %s", client_name);
 	goto out;
     }
     if(client->entry.flags.postdate && server->entry.flags.postdate)
 	et.flags.may_postdate =3D f.allow_postdate;
     else if (f.allow_postdate){
+	e_text =3D "Ticket may not be postdate";
 	ret =3D KRB5KDC_ERR_POLICY;
 	kdc_log(context, config, 0,
 		"Ticket may not be postdatable -- %s", client_name);
@@ -1475,24 +1529,26 @@
=20
     /* check for valid set of addresses */
     if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {
+	e_text =3D "Bad address list in requested";
 	ret =3D KRB5KRB_AP_ERR_BADADDR;
 	kdc_log(context, config, 0,
 		"Bad address list requested -- %s", client_name);
 	goto out;
     }
=20
-    ret =3D krb5_generate_random_keyblock(context, sessionetype, &et.key);
+    ret =3D copy_PrincipalName(&rep.cname, &et.cname);
     if (ret)
 	goto out;
-    copy_PrincipalName(&rep.cname, &et.cname);
-    copy_Realm(&rep.crealm, &et.crealm);
-   =20
+    ret =3D copy_Realm(&rep.crealm, &et.crealm);
+    if (ret)
+	goto out;
+
     {
 	time_t start;
 	time_t t;
-=09
+
 	start =3D et.authtime =3D kdc_time;
-   =20
+
 	if(f.postdated && req->req_body.from){
 	    ALLOC(et.starttime);
 	    start =3D *et.starttime =3D *req->req_body.from;
@@ -1540,16 +1596,14 @@
=20
     if (f.request_anonymous)
 	et.flags.anonymous =3D 1;
-   =20
+
     if(b->addresses){
 	ALLOC(et.caddr);
 	copy_HostAddresses(b->addresses, et.caddr);
     }
-   =20
+
     et.transited.tr_type =3D DOMAIN_X500_COMPRESS;
-    krb5_data_zero(&et.transited.contents);=20
-    =20
-    copy_EncryptionKey(&et.key, &ek.key);
+    krb5_data_zero(&et.transited.contents);
=20
     /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded
      * as 0 and as 0x80 (meaning indefinite length) apart, and is thus
@@ -1588,7 +1642,7 @@
 	ALLOC(ek.key_expiration);
 	if (client->entry.valid_end) {
 	    if (client->entry.pw_end)
-		*ek.key_expiration =3D min(*client->entry.valid_end,=20
+		*ek.key_expiration =3D min(*client->entry.valid_end,
 					 *client->entry.pw_end);
 	    else
 		*ek.key_expiration =3D *client->entry.valid_end;
@@ -1614,16 +1668,12 @@
 	copy_HostAddresses(et.caddr, ek.caddr);
     }
=20
-    ALLOC(rep.padata);
-    rep.padata->len =3D 0;
-    rep.padata->val =3D NULL;
-
-    reply_key =3D &ckey->key;
 #if PKINIT
     if (pkp) {
-	ret =3D _kdc_pk_mk_pa_reply(context, config, pkp, client,=20
-				  req, req_buffer,=20
-				  &reply_key, rep.padata);
+        e_text =3D "Failed to build PK-INIT reply";
+	ret =3D _kdc_pk_mk_pa_reply(context, config, pkp, client,
+				  sessionetype, req, req_buffer,
+				  &reply_key, &et.key, rep.padata);
 	if (ret)
 	    goto out;
 	ret =3D _kdc_add_inital_verified_cas(context,
@@ -1632,51 +1682,65 @@
 					   &et);
 	if (ret)
 	    goto out;
+
+    } else
+#endif
+    {
+	ret =3D krb5_generate_random_keyblock(context, sessionetype, &et.key);
+	if (ret)
+	    goto out;
     }
-#endif
=20
-    set_salt_padata (rep.padata, ckey->salt);
+    if (reply_key =3D=3D NULL) {
+	e_text =3D "Client have no reply key";
+	ret =3D KRB5KDC_ERR_CLIENT_NOTYET;
+	goto out;
+    }
+
+    ret =3D copy_EncryptionKey(&et.key, &ek.key);
+    if (ret)
+	goto out;
=20
     /* Add signing of alias referral */
     if (f.canonicalize) {
 	PA_ClientCanonicalized canon;
 	krb5_data data;
 	PA_DATA pa;
-	krb5_crypto crypto;
-	size_t len;
+	krb5_crypto cryptox;
+	size_t len =3D 0;
=20
 	memset(&canon, 0, sizeof(canon));
=20
 	canon.names.requested_name =3D *b->cname;
-	canon.names.real_name =3D client->entry.principal->name;
+	canon.names.mapped_name =3D client->entry.principal->name;
=20
 	ASN1_MALLOC_ENCODE(PA_ClientCanonicalizedNames, data.data, data.length,
 			   &canon.names, &len, ret);
-	if (ret)=20
+	if (ret)
 	    goto out;
 	if (data.length !=3D len)
 	    krb5_abortx(context, "internal asn.1 error");
=20
 	/* sign using "returned session key" */
-	ret =3D krb5_crypto_init(context, &et.key, 0, &crypto);
+	ret =3D krb5_crypto_init(context, &et.key, 0, &cryptox);
 	if (ret) {
 	    free(data.data);
 	    goto out;
 	}
=20
-	ret =3D krb5_create_checksum(context, crypto,=20
+	ret =3D krb5_create_checksum(context, cryptox,
 				   KRB5_KU_CANONICALIZED_NAMES, 0,
 				   data.data, data.length,
 				   &canon.canon_checksum);
 	free(data.data);
-	krb5_crypto_destroy(context, crypto);
+	krb5_crypto_destroy(context, cryptox);
 	if (ret)
 	    goto out;
-	 =20
+
 	ASN1_MALLOC_ENCODE(PA_ClientCanonicalized, data.data, data.length,
 			   &canon, &len, ret);
 	free_Checksum(&canon.canon_checksum);
-	if (ret)=20
+	if (ret)
 	    goto out;
 	if (data.length !=3D len)
 	    krb5_abortx(context, "internal asn.1 error");
@@ -1701,19 +1765,19 @@
=20
 	ret =3D _kdc_pac_generate(context, client, &p);
 	if (ret) {
-	    kdc_log(context, config, 0, "PAC generation failed for -- %s",=20
+	    kdc_log(context, config, 0, "PAC generation failed for -- %s",
 		    client_name);
 	    goto out;
 	}
 	if (p !=3D NULL) {
 	    ret =3D _krb5_pac_sign(context, p, et.authtime,
 				 client->entry.principal,
-				 &skey->key, /* Server key */=20
+				 &skey->key, /* Server key */
 				 &skey->key, /* FIXME: should be krbtgt key */
 				 &data);
 	    krb5_pac_free(context, p);
 	    if (ret) {
-		kdc_log(context, config, 0, "PAC signing failed for -- %s",=20
+		kdc_log(context, config, 0, "PAC signing failed for -- %s",
 			client_name);
 		goto out;
 	    }
@@ -1727,7 +1791,7 @@
 	}
     }
=20
-    _kdc_log_timestamp(context, config, "AS-REQ", et.authtime, et.starttim=
e,=20
+    _kdc_log_timestamp(context, config, "AS-REQ", et.authtime, et.starttim=
e,
 		       et.endtime, et.renew_till);
=20
     /* do this as the last thing since this signs the EncTicketPart */
@@ -1735,16 +1799,19 @@
 				  config,
 				  server,
 				  setype,
+				  client->entry.principal,
 				  NULL,
 				  NULL,
 				  &et);
     if (ret)
 	goto out;
=20
-    ret =3D _kdc_encode_reply(context, config,=20
-			    &rep, &et, &ek, setype, server->entry.kvno,=20
-			    &skey->key, client->entry.kvno,=20
-			    reply_key, &e_text, reply);
+    log_as_req(context, config, reply_key->keytype, setype, b);
+
+    ret =3D _kdc_encode_reply(context, config,
+			    &rep, &et, &ek, setype, server->entry.kvno,
+			    &skey->key, client->entry.kvno,
+			    reply_key, 0, &e_text, reply);
     free_EncTicketPart(&et);
     free_EncKDCRepPart(&ek);
     if (ret)
@@ -1759,7 +1826,7 @@
=20
 out:
     free_AS_REP(&rep);
-    if(ret){
+    if(ret !=3D 0 && ret !=3D HDB_ERR_NOT_FOUND_HERE){
 	krb5_mk_error(context,
 		      ret,
 		      e_text,
@@ -1791,8 +1858,8 @@
 }
=20
 /*
- * Add the AuthorizationData `data=B4 of `type=B4 to the last element in
- * the sequence of authorization_data in `tkt=B4 wrapped in an IF_RELEVANT
+ * Add the AuthorizationData `data=C2=B4 of `type=C2=B4 to the last elemen=
t in
+ * the sequence of authorization_data in `tkt=C2=B4 wrapped in an IF_RELEV=
ANT
  */
=20
 krb5_error_code
@@ -1802,16 +1869,16 @@
 			    const krb5_data *data)
 {
     krb5_error_code ret;
-    size_t size;
+    size_t size =3D 0;
=20
     if (tkt->authorization_data =3D=3D NULL) {
 	tkt->authorization_data =3D calloc(1, sizeof(*tkt->authorization_data));
 	if (tkt->authorization_data =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
+	    krb5_set_error_message(context, ENOMEM, "out of memory");
 	    return ENOMEM;
 	}
     }
-=09
+
     /* add the entry to the last element */
     {
 	AuthorizationData ad =3D { 0, NULL };
@@ -1822,28 +1889,28 @@
=20
 	ret =3D add_AuthorizationData(&ad, &ade);
 	if (ret) {
-	    krb5_set_error_string(context, "add AuthorizationData failed");
+	    krb5_set_error_message(context, ret, "add AuthorizationData failed");
 	    return ret;
 	}
=20
 	ade.ad_type =3D KRB5_AUTHDATA_IF_RELEVANT;
=20
-	ASN1_MALLOC_ENCODE(AuthorizationData,=20
-			   ade.ad_data.data, ade.ad_data.length,=20
+	ASN1_MALLOC_ENCODE(AuthorizationData,
+			   ade.ad_data.data, ade.ad_data.length,
 			   &ad, &size, ret);
 	free_AuthorizationData(&ad);
 	if (ret) {
-	    krb5_set_error_string(context, "ASN.1 encode of "
-				  "AuthorizationData failed");
+	    krb5_set_error_message(context, ret, "ASN.1 encode of "
+				   "AuthorizationData failed");
 	    return ret;
 	}
 	if (ade.ad_data.length !=3D size)
 	    krb5_abortx(context, "internal asn.1 encoder error");
-=09
+
 	ret =3D add_AuthorizationData(tkt->authorization_data, &ade);
 	der_free_octet_string(&ade.ad_data);
 	if (ret) {
-	    krb5_set_error_string(context, "add AuthorizationData failed");
+	    krb5_set_error_message(context, ret, "add AuthorizationData failed");
 	    return ret;
 	}
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/krb5tgs.c
--- a/head/crypto/heimdal/kdc/krb5tgs.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/krb5tgs.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,45 +1,43 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: krb5tgs.c 22071 2007-11-14 20:04:50Z lha $");
-
 /*
  * return the realm of a krbtgt-ticket or NULL
  */
=20
-static Realm=20
+static Realm
 get_krbtgt_realm(const PrincipalName *p)
 {
     if(p->name_string.len =3D=3D 2
@@ -66,7 +64,7 @@
     AuthorizationData child;
     krb5_error_code ret;
     int pos;
-=09
+
     if (ad =3D=3D NULL || ad->len =3D=3D 0)
 	return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
=20
@@ -80,8 +78,8 @@
 				   &child,
 				   NULL);
     if (ret) {
-	krb5_set_error_string(context, "Failed to decode "
-			      "IF_RELEVANT with %d", ret);
+	krb5_set_error_message(context, ret, "Failed to decode "
+			       "IF_RELEVANT with %d", ret);
 	return ret;
     }
=20
@@ -106,28 +104,31 @@
 			krb5_kdc_configuration *config,
 			hdb_entry_ex *krbtgt,
 			krb5_enctype enctype,
+			krb5_principal client,
 			krb5_const_principal server,
-			KRB5SignedPathPrincipals *principals,
+			krb5_principals principals,
 			EncTicketPart *tkt)
 {
     krb5_error_code ret;
     KRB5SignedPath sp;
     krb5_data data;
     krb5_crypto crypto =3D NULL;
-    size_t size;
+    size_t size =3D 0;
=20
     if (server && principals) {
-	ret =3D add_KRB5SignedPathPrincipals(principals, server);
+	ret =3D add_Principals(principals, server);
 	if (ret)
 	    return ret;
     }
=20
     {
 	KRB5SignedPathData spd;
-=09
-	spd.encticket =3D *tkt;
+
+	spd.client =3D client;
+	spd.authtime =3D tkt->authtime;
 	spd.delegated =3D principals;
-=09
+	spd.method_data =3D NULL;
+
 	ASN1_MALLOC_ENCODE(KRB5SignedPathData, data.data, data.length,
 			   &spd, &size, ret);
 	if (ret)
@@ -153,6 +154,7 @@
=20
     sp.etype =3D enctype;
     sp.delegated =3D principals;
+    sp.method_data =3D NULL;
=20
     ret =3D krb5_create_checksum(context, crypto, KRB5_KU_KRB5SIGNEDPATH, =
0,
 			       data.data, data.length, &sp.cksum);
@@ -168,7 +170,7 @@
     if (data.length !=3D size)
 	krb5_abortx(context, "internal asn.1 encoder error");
=20
-   =20
+
     /*
      * Add IF-RELEVANT(KRB5SignedPath) to the last slot in
      * authorization data field.
@@ -185,39 +187,36 @@
 check_KRB5SignedPath(krb5_context context,
 		     krb5_kdc_configuration *config,
 		     hdb_entry_ex *krbtgt,
+		     krb5_principal cp,
 		     EncTicketPart *tkt,
-		     KRB5SignedPathPrincipals **delegated,
-		     int require_signedpath)
+		     krb5_principals *delegated,
+		     int *signedpath)
 {
     krb5_error_code ret;
     krb5_data data;
     krb5_crypto crypto =3D NULL;
=20
-    *delegated =3D NULL;
+    if (delegated)
+	*delegated =3D NULL;
=20
     ret =3D find_KRB5SignedPath(context, tkt->authorization_data, &data);
     if (ret =3D=3D 0) {
 	KRB5SignedPathData spd;
 	KRB5SignedPath sp;
-	AuthorizationData *ad;
-	size_t size;
+	size_t size =3D 0;
=20
 	ret =3D decode_KRB5SignedPath(data.data, data.length, &sp, NULL);
 	krb5_data_free(&data);
 	if (ret)
 	    return ret;
=20
-	spd.encticket =3D *tkt;
-	/* the KRB5SignedPath is the last entry */
-	ad =3D spd.encticket.authorization_data;
-	if (--ad->len =3D=3D 0)
-	    spd.encticket.authorization_data =3D NULL;
+	spd.client =3D cp;
+	spd.authtime =3D tkt->authtime;
 	spd.delegated =3D sp.delegated;
+	spd.method_data =3D sp.method_data;
=20
 	ASN1_MALLOC_ENCODE(KRB5SignedPathData, data.data, data.length,
 			   &spd, &size, ret);
-	ad->len++;
-	spd.encticket.authorization_data =3D ad;
 	if (ret) {
 	    free_KRB5SignedPath(&sp);
 	    return ret;
@@ -236,17 +235,19 @@
 		return ret;
 	    }
 	}
-	ret =3D krb5_verify_checksum(context, crypto, KRB5_KU_KRB5SIGNEDPATH,=20
-				   data.data, data.length,=20
+	ret =3D krb5_verify_checksum(context, crypto, KRB5_KU_KRB5SIGNEDPATH,
+				   data.data, data.length,
 				   &sp.cksum);
 	krb5_crypto_destroy(context, crypto);
 	free(data.data);
 	if (ret) {
 	    free_KRB5SignedPath(&sp);
-	    return ret;
+	    kdc_log(context, config, 5,
+		    "KRB5SignedPath not signed correctly, not marking as signed");
+	    return 0;
 	}
=20
-	if (sp.delegated) {
+	if (delegated && sp.delegated) {
=20
 	    *delegated =3D malloc(sizeof(*sp.delegated));
 	    if (*delegated =3D=3D NULL) {
@@ -254,7 +255,7 @@
 		return ENOMEM;
 	    }
=20
-	    ret =3D copy_KRB5SignedPathPrincipals(*delegated, sp.delegated);
+	    ret =3D copy_Principals(*delegated, sp.delegated);
 	    if (ret) {
 		free_KRB5SignedPath(&sp);
 		free(*delegated);
@@ -263,10 +264,8 @@
 	    }
 	}
 	free_KRB5SignedPath(&sp);
-=09
-    } else {
-	if (require_signedpath)
-	    return KRB5KDC_ERR_BADOPTION;
+
+	*signedpath =3D 1;
     }
=20
     return 0;
@@ -280,13 +279,17 @@
 check_PAC(krb5_context context,
 	  krb5_kdc_configuration *config,
 	  const krb5_principal client_principal,
+	  const krb5_principal delegated_proxy_principal,
 	  hdb_entry_ex *client,
 	  hdb_entry_ex *server,
-	  const EncryptionKey *server_key,
-	  const EncryptionKey *krbtgt_key,
+	  hdb_entry_ex *krbtgt,
+	  const EncryptionKey *server_check_key,
+	  const EncryptionKey *krbtgt_check_key,
+	  const EncryptionKey *server_sign_key,
+	  const EncryptionKey *krbtgt_sign_key,
 	  EncTicketPart *tkt,
 	  krb5_data *rspac,
-	  int *require_signedpath)
+	  int *signedpath)
 {
     AuthorizationData *ad =3D tkt->authorization_data;
     unsigned i, j;
@@ -306,13 +309,14 @@
 				       &child,
 				       NULL);
 	if (ret) {
-	    krb5_set_error_string(context, "Failed to decode "
-				  "IF_RELEVANT with %d", ret);
+	    krb5_set_error_message(context, ret, "Failed to decode "
+				   "IF_RELEVANT with %d", ret);
 	    return ret;
 	}
 	for (j =3D 0; j < child.len; j++) {
=20
 	    if (child.val[j].ad_type =3D=3D KRB5_AUTHDATA_WIN2K_PAC) {
+		int signed_pac =3D 0;
 		krb5_pac pac;
=20
 		/* Found PAC */
@@ -324,26 +328,34 @@
 		if (ret)
 		    return ret;
=20
-		ret =3D krb5_pac_verify(context, pac, tkt->authtime,=20
+		ret =3D krb5_pac_verify(context, pac, tkt->authtime,
 				      client_principal,
-				      krbtgt_key, NULL);
+				      server_check_key, krbtgt_check_key);
 		if (ret) {
 		    krb5_pac_free(context, pac);
 		    return ret;
 		}
=20
-		ret =3D _kdc_pac_verify(context, client_principal,=20
-				      client, server, &pac);
+		ret =3D _kdc_pac_verify(context, client_principal,
+				      delegated_proxy_principal,
+				      client, server, krbtgt, &pac, &signed_pac);
 		if (ret) {
 		    krb5_pac_free(context, pac);
 		    return ret;
 		}
-		*require_signedpath =3D 0;
=20
-		ret =3D _krb5_pac_sign(context, pac, tkt->authtime,
-				     client_principal,
-				     server_key, krbtgt_key, rspac);
-
+		/*
+		 * Only re-sign PAC if we could verify it with the PAC
+		 * function. The no-verify case happens when we get in
+		 * a PAC from cross realm from a Windows domain and
+		 * that there is no PAC verification function.
+		 */
+		if (signed_pac) {
+		    *signedpath =3D 1;
+		    ret =3D _krb5_pac_sign(context, pac, tkt->authtime,
+					 client_principal,
+					 server_sign_key, krbtgt_sign_key, rspac);
+		}
 		krb5_pac_free(context, pac);
=20
 		return ret;
@@ -359,12 +371,12 @@
  */
=20
 static krb5_error_code
-check_tgs_flags(krb5_context context,       =20
+check_tgs_flags(krb5_context context,
 		krb5_kdc_configuration *config,
 		KDC_REQ_BODY *b, const EncTicketPart *tgt, EncTicketPart *et)
 {
     KDCOptions f =3D b->kdc_options;
-=09
+
     if(f.validate){
 	if(!tgt->flags.invalid || tgt->starttime =3D=3D NULL){
 	    kdc_log(context, config, 0,
@@ -379,7 +391,7 @@
 	/* XXX  tkt =3D tgt */
 	et->flags.invalid =3D 0;
     }else if(tgt->flags.invalid){
-	kdc_log(context, config, 0,=20
+	kdc_log(context, config, 0,
 		"Ticket-granting ticket has INVALID flag set");
 	return KRB5KRB_AP_ERR_TKT_INVALID;
     }
@@ -403,7 +415,7 @@
     }
     if(tgt->flags.forwarded)
 	et->flags.forwarded =3D 1;
-=09
+
     if(f.proxiable){
 	if(!tgt->flags.proxiable){
 	    kdc_log(context, config, 0,
@@ -448,7 +460,7 @@
     }
=20
     if(f.renewable){
-	if(!tgt->flags.renewable){
+	if(!tgt->flags.renewable || tgt->renew_till =3D=3D NULL){
 	    kdc_log(context, config, 0,
 		    "Bad request for renewable ticket");
 	    return KRB5KDC_ERR_BADOPTION;
@@ -473,8 +485,8 @@
 	et->endtime =3D *et->starttime + old_life;
 	if (et->renew_till !=3D NULL)
 	    et->endtime =3D min(*et->renew_till, et->endtime);
-    }	   =20
-   =20
+    }
+
 #if 0
     /* checks for excess flags */
     if(f.request_anonymous && !config->allow_anonymous){
@@ -487,34 +499,90 @@
 }
=20
 /*
- *
+ * Determine if constrained delegation is allowed from this client to this=
 server
  */
=20
 static krb5_error_code
-check_constrained_delegation(krb5_context context,=20
+check_constrained_delegation(krb5_context context,
 			     krb5_kdc_configuration *config,
+			     HDB *clientdb,
 			     hdb_entry_ex *client,
-			     krb5_const_principal server)
+			     hdb_entry_ex *server,
+			     krb5_const_principal target)
 {
     const HDB_Ext_Constrained_delegation_acl *acl;
     krb5_error_code ret;
-    int i;
+    size_t i;
=20
-    ret =3D hdb_entry_get_ConstrainedDelegACL(&client->entry, &acl);
-    if (ret) {
-	krb5_clear_error_string(context);
+    /*
+     * constrained_delegation (S4U2Proxy) only works within
+     * the same realm. We use the already canonicalized version
+     * of the principals here, while "target" is the principal
+     * provided by the client.
+     */
+    if(!krb5_realm_compare(context, client->entry.principal, server->entry=
.principal)) {
+	ret =3D KRB5KDC_ERR_BADOPTION;
+	kdc_log(context, config, 0,
+	    "Bad request for constrained delegation");
 	return ret;
     }
=20
-    if (acl) {
-	for (i =3D 0; i < acl->len; i++) {
-	    if (krb5_principal_compare(context, server, &acl->val[i]) =3D=3D TRUE)
-		return 0;
+    if (clientdb->hdb_check_constrained_delegation) {
+	ret =3D clientdb->hdb_check_constrained_delegation(context, clientdb, cli=
ent, target);
+	if (ret =3D=3D 0)
+	    return 0;
+    } else {
+	/* if client delegates to itself, that ok */
+	if (krb5_principal_compare(context, client->entry.principal, server->entr=
y.principal) =3D=3D TRUE)
+	    return 0;
+
+	ret =3D hdb_entry_get_ConstrainedDelegACL(&client->entry, &acl);
+	if (ret) {
+	    krb5_clear_error_message(context);
+	    return ret;
 	}
+
+	if (acl) {
+	    for (i =3D 0; i < acl->len; i++) {
+		if (krb5_principal_compare(context, target, &acl->val[i]) =3D=3D TRUE)
+		    return 0;
+	    }
+	}
+	ret =3D KRB5KDC_ERR_BADOPTION;
     }
     kdc_log(context, config, 0,
 	    "Bad request for constrained delegation");
-    return KRB5KDC_ERR_BADOPTION;
+    return ret;
+}
+
+/*
+ * Determine if s4u2self is allowed from this client to this server
+ *
+ * For example, regardless of the principal being impersonated, if the
+ * 'client' and 'server' are the same, then it's safe.
+ */
+
+static krb5_error_code
+check_s4u2self(krb5_context context,
+	       krb5_kdc_configuration *config,
+	       HDB *clientdb,
+	       hdb_entry_ex *client,
+	       krb5_const_principal server)
+{
+    krb5_error_code ret;
+
+    /* if client does a s4u2self to itself, that ok */
+    if (krb5_principal_compare(context, client->entry.principal, server) =
=3D=3D TRUE)
+	return 0;
+
+    if (clientdb->hdb_check_s4u2self) {
+	ret =3D clientdb->hdb_check_s4u2self(context, clientdb, client, server);
+	if (ret =3D=3D 0)
+	    return 0;
+    } else {
+	ret =3D KRB5KDC_ERR_BADOPTION;
+    }
+    return ret;
 }
=20
 /*
@@ -522,7 +590,7 @@
  */
=20
 static krb5_error_code
-verify_flags (krb5_context context,=20
+verify_flags (krb5_context context,
 	      krb5_kdc_configuration *config,
 	      const EncTicketPart *et,
 	      const char *pstr)
@@ -543,19 +611,19 @@
  */
=20
 static krb5_error_code
-fix_transited_encoding(krb5_context context,=20
+fix_transited_encoding(krb5_context context,
 		       krb5_kdc_configuration *config,
 		       krb5_boolean check_policy,
-		       const TransitedEncoding *tr,=20
-		       EncTicketPart *et,=20
-		       const char *client_realm,=20
-		       const char *server_realm,=20
+		       const TransitedEncoding *tr,
+		       EncTicketPart *et,
+		       const char *client_realm,
+		       const char *server_realm,
 		       const char *tgt_realm)
 {
     krb5_error_code ret =3D 0;
     char **realms, **tmp;
-    int num_realms;
-    int i;
+    unsigned int num_realms;
+    size_t i;
=20
     switch (tr->tr_type) {
     case DOMAIN_X500_COMPRESS:
@@ -576,9 +644,9 @@
 	return KRB5KDC_ERR_TRTYPE_NOSUPP;
     }
=20
-    ret =3D krb5_domain_x500_decode(context,=20
+    ret =3D krb5_domain_x500_decode(context,
 				  tr->contents,
-				  &realms,=20
+				  &realms,
 				  &num_realms,
 				  client_realm,
 				  server_realm);
@@ -589,7 +657,7 @@
     }
     if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm))=
 {
 	/* not us, so add the previous realm to transited set */
-	if (num_realms < 0 || num_realms + 1 > UINT_MAX/sizeof(*realms)) {
+	if (num_realms + 1 > UINT_MAX/sizeof(*realms)) {
 	    ret =3D ERANGE;
 	    goto free_realms;
 	}
@@ -607,7 +675,7 @@
 	num_realms++;
     }
     if(num_realms =3D=3D 0) {
-	if(strcmp(client_realm, server_realm))=20
+	if(strcmp(client_realm, server_realm))
 	    kdc_log(context, config, 0,
 		    "cross-realm %s -> %s", client_realm, server_realm);
     } else {
@@ -630,11 +698,11 @@
 	}
     }
     if(check_policy) {
-	ret =3D krb5_check_transited(context, client_realm,=20
-				   server_realm,=20
+	ret =3D krb5_check_transited(context, client_realm,
+				   server_realm,
 				   realms, num_realms, NULL);
 	if(ret) {
-	    krb5_warn(context, ret, "cross-realm %s -> %s",=20
+	    krb5_warn(context, ret, "cross-realm %s -> %s",
 		      client_realm, server_realm);
 	    goto free_realms;
 	}
@@ -653,23 +721,27 @@
=20
=20
 static krb5_error_code
-tgs_make_reply(krb5_context context,=20
+tgs_make_reply(krb5_context context,
 	       krb5_kdc_configuration *config,
-	       KDC_REQ_BODY *b,=20
+	       KDC_REQ_BODY *b,
 	       krb5_const_principal tgt_name,
-	       const EncTicketPart *tgt,=20
+	       const EncTicketPart *tgt,
+	       const krb5_keyblock *replykey,
+	       int rk_is_subkey,
 	       const EncryptionKey *serverkey,
 	       const krb5_keyblock *sessionkey,
 	       krb5_kvno kvno,
 	       AuthorizationData *auth_data,
-	       hdb_entry_ex *server,=20
-	       const char *server_name,=20
-	       hdb_entry_ex *client,=20
-	       krb5_principal client_principal,=20
+	       hdb_entry_ex *server,
+	       krb5_principal server_principal,
+	       const char *server_name,
+	       hdb_entry_ex *client,
+	       krb5_principal client_principal,
 	       hdb_entry_ex *krbtgt,
 	       krb5_enctype krbtgt_etype,
-	       KRB5SignedPathPrincipals *spp,
+	       krb5_principals spp,
 	       const krb5_data *rspac,
+	       const METHOD_DATA *enc_pa_data,
 	       const char **e_text,
 	       krb5_data *reply)
 {
@@ -678,11 +750,12 @@
     EncTicketPart et;
     KDCOptions f =3D b->kdc_options;
     krb5_error_code ret;
-   =20
+    int is_weak =3D 0;
+
     memset(&rep, 0, sizeof(rep));
     memset(&et, 0, sizeof(et));
     memset(&ek, 0, sizeof(ek));
-   =20
+
     rep.pvno =3D 5;
     rep.msg_type =3D krb_tgs_rep;
=20
@@ -691,7 +764,7 @@
     et.endtime =3D min(tgt->endtime, *b->till);
     ALLOC(et.starttime);
     *et.starttime =3D kdc_time;
-   =20
+
     ret =3D check_tgs_flags(context, config, b, tgt, &et);
     if(ret)
 	goto out;
@@ -715,23 +788,22 @@
 #define PRINCIPAL_FORCE_TRANSITED_CHECK(P)		0
 #define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P)	0
=20
-    ret =3D fix_transited_encoding(context, config,=20
+    ret =3D fix_transited_encoding(context, config,
 				 !f.disable_transited_check ||
 				 GLOBAL_FORCE_TRANSITED_CHECK ||
 				 PRINCIPAL_FORCE_TRANSITED_CHECK(server) ||
-				 !((GLOBAL_ALLOW_PER_PRINCIPAL &&=20
+				 !((GLOBAL_ALLOW_PER_PRINCIPAL &&
 				    PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) ||
 				   GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK),
 				 &tgt->transited, &et,
-				 *krb5_princ_realm(context, client_principal),
-				 *krb5_princ_realm(context, server->entry.principal),
-				 *krb5_princ_realm(context, krbtgt->entry.principal));
+				 krb5_principal_get_realm(context, client_principal),
+				 krb5_principal_get_realm(context, server->entry.principal),
+				 krb5_principal_get_realm(context, krbtgt->entry.principal));
     if(ret)
 	goto out;
=20
-    copy_Realm(krb5_princ_realm(context, server->entry.principal),=20
-	       &rep.ticket.realm);
-    _krb5_principal2principalname(&rep.ticket.sname, server->entry.princip=
al);
+    copy_Realm(&server_principal->realm, &rep.ticket.realm);
+    _krb5_principal2principalname(&rep.ticket.sname, server_principal);
     copy_Realm(&tgt_name->realm, &rep.crealm);
 /*
     if (f.request_anonymous)
@@ -754,8 +826,10 @@
 	    life =3D min(life, *server->entry.max_life);
 	et.endtime =3D *et.starttime + life;
     }
-    if(f.renewable_ok && tgt->flags.renewable &&=20
-       et.renew_till =3D=3D NULL && et.endtime < *b->till){
+    if(f.renewable_ok && tgt->flags.renewable &&
+       et.renew_till =3D=3D NULL && et.endtime < *b->till &&
+       tgt->renew_till !=3D NULL)
+    {
 	et.flags.renewable =3D 1;
 	ALLOC(et.renew_till);
 	*et.renew_till =3D *b->till;
@@ -769,13 +843,13 @@
 	    renew =3D min(renew, *server->entry.max_renew);
 	*et.renew_till =3D et.authtime + renew;
     }
-	   =20
+
     if(et.renew_till){
 	*et.renew_till =3D min(*et.renew_till, *tgt->renew_till);
 	*et.starttime =3D min(*et.starttime, *et.renew_till);
 	et.endtime =3D min(et.endtime, *et.renew_till);
     }
-   =20
+
     *et.starttime =3D min(*et.starttime, et.endtime);
=20
     if(*et.starttime =3D=3D et.endtime){
@@ -787,22 +861,43 @@
 	et.renew_till =3D NULL;
 	et.flags.renewable =3D 0;
     }
-   =20
+
     et.flags.pre_authent =3D tgt->flags.pre_authent;
     et.flags.hw_authent  =3D tgt->flags.hw_authent;
     et.flags.anonymous   =3D tgt->flags.anonymous;
     et.flags.ok_as_delegate =3D server->entry.flags.ok_as_delegate;
-	   =20
-    if (auth_data) {
-	/* XXX Check enc-authorization-data */
-	et.authorization_data =3D calloc(1, sizeof(*et.authorization_data));
-	if (et.authorization_data =3D=3D NULL) {
-	    ret =3D ENOMEM;
-	    goto out;
-	}
-	ret =3D copy_AuthorizationData(auth_data, et.authorization_data);
+
+    if(rspac->length) {
+	/*
+	 * No not need to filter out the any PAC from the
+	 * auth_data since it's signed by the KDC.
+	 */
+	ret =3D _kdc_tkt_add_if_relevant_ad(context, &et,
+					  KRB5_AUTHDATA_WIN2K_PAC, rspac);
 	if (ret)
 	    goto out;
+    }
+
+    if (auth_data) {
+	unsigned int i =3D 0;
+
+	/* XXX check authdata */
+
+	if (et.authorization_data =3D=3D NULL) {
+	    et.authorization_data =3D calloc(1, sizeof(*et.authorization_data));
+	    if (et.authorization_data =3D=3D NULL) {
+		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
+		goto out;
+	    }
+	}
+	for(i =3D 0; i < auth_data->len ; i++) {
+	    ret =3D add_AuthorizationData(et.authorization_data, &auth_data->val[=
i]);
+	    if (ret) {
+		krb5_set_error_message(context, ret, "malloc: out of memory");
+		goto out;
+	    }
+	}
=20
 	/* Filter out type KRB5SignedPath */
 	ret =3D find_KRB5SignedPath(context, et.authorization_data, NULL);
@@ -819,24 +914,12 @@
 	}
     }
=20
-    if(rspac->length) {
-	/*
-	 * No not need to filter out the any PAC from the
-	 * auth_data since it's signed by the KDC.
-	 */
-	ret =3D _kdc_tkt_add_if_relevant_ad(context, &et,
-					  KRB5_AUTHDATA_WIN2K_PAC,
-					  rspac);
-	if (ret)
-	    goto out;
-    }
-
     ret =3D krb5_copy_keyblock_contents(context, sessionkey, &et.key);
     if (ret)
 	goto out;
-    et.crealm =3D tgt->crealm;
+    et.crealm =3D tgt_name->realm;
     et.cname =3D tgt_name->name;
-	   =20
+
     ek.key =3D et.key;
     /* MIT must have at least one last_req */
     ek.last_req.len =3D 1;
@@ -853,8 +936,8 @@
     ek.renew_till =3D et.renew_till;
     ek.srealm =3D rep.ticket.realm;
     ek.sname =3D rep.ticket.sname;
-   =20
-    _kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.startti=
me,=20
+
+    _kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.startti=
me,
 		       et.endtime, et.renew_till);
=20
     /* Don't sign cross realm tickets, they can't be checked anyway */
@@ -866,6 +949,7 @@
 					  config,
 					  krbtgt,
 					  krbtgt_etype,
+					  client_principal,
 					  NULL,
 					  spp,
 					  &et);
@@ -874,6 +958,25 @@
 	}
     }
=20
+    if (enc_pa_data->len) {
+	rep.padata =3D calloc(1, sizeof(*rep.padata));
+	if (rep.padata =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+	ret =3D copy_METHOD_DATA(enc_pa_data, rep.padata);
+	if (ret)
+	    goto out;
+    }
+
+    if (krb5_enctype_valid(context, et.key.keytype) !=3D 0
+	&& _kdc_is_weak_exception(server->entry.principal, et.key.keytype))
+    {
+	krb5_enctype_enable(context, et.key.keytype);
+	is_weak =3D 1;
+    }
+
+
     /* It is somewhat unclear where the etype in the following
        encryption should come from. What we have is a session
        key in the passed tgt, and a list of preferred etypes
@@ -884,10 +987,14 @@
        CAST session key. Should the DES3 etype be added to the
        etype list, even if we don't want a session key with
        DES3? */
-    ret =3D _kdc_encode_reply(context, config,=20
+    ret =3D _kdc_encode_reply(context, config,
 			    &rep, &et, &ek, et.key.keytype,
-			    kvno,=20
-			    serverkey, 0, &tgt->key, e_text, reply);
+			    kvno,
+			    serverkey, 0, replykey, rk_is_subkey,
+			    e_text, reply);
+    if (is_weak)
+	krb5_enctype_disable(context, et.key.keytype);
+
 out:
     free_TGS_REP(&rep);
     free_TransitedEncoding(&et.transited);
@@ -906,20 +1013,20 @@
 }
=20
 static krb5_error_code
-tgs_check_authenticator(krb5_context context,=20
+tgs_check_authenticator(krb5_context context,
 			krb5_kdc_configuration *config,
 	                krb5_auth_context ac,
-			KDC_REQ_BODY *b,=20
+			KDC_REQ_BODY *b,
 			const char **e_text,
 			krb5_keyblock *key)
 {
     krb5_authenticator auth;
-    size_t len;
+    size_t len =3D 0;
     unsigned char *buf;
     size_t buf_size;
     krb5_error_code ret;
     krb5_crypto crypto;
-   =20
+
     krb5_auth_con_getauthenticator(context, ac, &auth);
     if(auth->cksum =3D=3D NULL){
 	kdc_log(context, config, 0, "No authenticator in request");
@@ -936,17 +1043,18 @@
 	||
 #endif
  !krb5_checksum_is_collision_proof(context, auth->cksum->cksumtype)) {
-	kdc_log(context, config, 0, "Bad checksum type in authenticator: %d",=20
+	kdc_log(context, config, 0, "Bad checksum type in authenticator: %d",
 		auth->cksum->cksumtype);
 	ret =3D  KRB5KRB_AP_ERR_INAPP_CKSUM;
 	goto out;
     }
-	=09
+
     /* XXX should not re-encode this */
     ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, b, &len, ret);
     if(ret){
-	kdc_log(context, config, 0, "Failed to encode KDC-REQ-BODY: %s",=20
-		krb5_get_err_text(context, ret));
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "Failed to encode KDC-REQ-BODY: %s", msg);
+	krb5_free_error_message(context, msg);
 	goto out;
     }
     if(buf_size !=3D len) {
@@ -958,23 +1066,25 @@
     }
     ret =3D krb5_crypto_init(context, key, 0, &crypto);
     if (ret) {
+	const char *msg =3D krb5_get_error_message(context, ret);
 	free(buf);
-	kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-		krb5_get_err_text(context, ret));
+	kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+	krb5_free_error_message(context, msg);
 	goto out;
     }
     ret =3D krb5_verify_checksum(context,
 			       crypto,
 			       KRB5_KU_TGS_REQ_AUTH_CKSUM,
-			       buf,=20
+			       buf,
 			       len,
 			       auth->cksum);
     free(buf);
     krb5_crypto_destroy(context, crypto);
     if(ret){
+	const char *msg =3D krb5_get_error_message(context, ret);
 	kdc_log(context, config, 0,
-		"Failed to verify authenticator checksum: %s",=20
-		krb5_get_err_text(context, ret));
+		"Failed to verify authenticator checksum: %s", msg);
+	krb5_free_error_message(context, msg);
     }
 out:
     free_Authenticator(auth);
@@ -991,27 +1101,38 @@
 {
     const char *new_realm =3D krb5_config_get_string(context,
 						   NULL,
-						   "capaths",=20
+						   "capaths",
 						   crealm,
 						   srealm,
 						   NULL);
     return new_realm;
 }
-	   =20
+
=20
 static krb5_boolean
-need_referral(krb5_context context, krb5_principal server, krb5_realm **re=
alms)
+need_referral(krb5_context context, krb5_kdc_configuration *config,
+	      const KDCOptions * const options, krb5_principal server,
+	      krb5_realm **realms)
 {
-    if(server->name.name_type !=3D KRB5_NT_SRV_INST ||
-       server->name.name_string.len !=3D 2)
+    const char *name;
+
+    if(!options->canonicalize && server->name.name_type !=3D KRB5_NT_SRV_I=
NST)
 	return FALSE;
-=20
-    return _krb5_get_host_realm_int(context, server->name.name_string.val[=
1],
-				    FALSE, realms) =3D=3D 0;
+
+    if (server->name.name_string.len =3D=3D 1)
+	name =3D server->name.name_string.val[0];
+    else if (server->name.name_string.len > 1)
+	name =3D server->name.name_string.val[1];
+    else
+	return FALSE;
+
+    kdc_log(context, config, 0, "Searching referral for %s", name);
+
+    return _krb5_get_host_realm_int(context, name, FALSE, realms) =3D=3D 0;
 }
=20
 static krb5_error_code
-tgs_parse_request(krb5_context context,=20
+tgs_parse_request(krb5_context context,
 		  krb5_kdc_configuration *config,
 		  KDC_REQ_BODY *b,
 		  const PA_DATA *tgs_req,
@@ -1023,8 +1144,11 @@
 		  const struct sockaddr *from_addr,
 		  time_t **csec,
 		  int **cusec,
-		  AuthorizationData **auth_data)
+		  AuthorizationData **auth_data,
+		  krb5_keyblock **replykey,
+		  int *rk_is_subkey)
 {
+    static char failed[] =3D "<unparse_name failed>";
     krb5_ap_req ap_req;
     krb5_error_code ret;
     krb5_principal princ;
@@ -1033,16 +1157,20 @@
     krb5_flags verify_ap_req_flags;
     krb5_crypto crypto;
     Key *tkey;
+    krb5_keyblock *subkey =3D NULL;
+    unsigned usage;
=20
     *auth_data =3D NULL;
     *csec  =3D NULL;
     *cusec =3D NULL;
+    *replykey =3D NULL;
=20
     memset(&ap_req, 0, sizeof(ap_req));
     ret =3D krb5_decode_ap_req(context, &tgs_req->padata_value, &ap_req);
     if(ret){
-	kdc_log(context, config, 0, "Failed to decode AP-REQ: %s",=20
-		krb5_get_err_text(context, ret));
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "Failed to decode AP-REQ: %s", msg);
+	krb5_free_error_message(context, msg);
 	goto out;
     }
=20
@@ -1052,39 +1180,51 @@
 	ret =3D KRB5KDC_ERR_POLICY; /* ? */
 	goto out;
     }
-   =20
+
     _krb5_principalname2krb5_principal(context,
 				       &princ,
 				       ap_req.ticket.sname,
 				       ap_req.ticket.realm);
-   =20
-    ret =3D _kdc_db_fetch(context, config, princ, HDB_F_GET_KRBTGT, NULL, =
krbtgt);
=20
-    if(ret) {
+    ret =3D _kdc_db_fetch(context, config, princ, HDB_F_GET_KRBTGT, ap_req=
.ticket.enc_part.kvno, NULL, krbtgt);
+
+    if(ret =3D=3D HDB_ERR_NOT_FOUND_HERE) {
 	char *p;
 	ret =3D krb5_unparse_name(context, princ, &p);
 	if (ret !=3D 0)
-	    p =3D "<unparse_name failed>";
+	    p =3D failed;
+	krb5_free_principal(context, princ);
+	kdc_log(context, config, 5, "Ticket-granting ticket account %s does not h=
ave secrets at this KDC, need to proxy", p);
+	if (ret =3D=3D 0)
+	    free(p);
+	ret =3D HDB_ERR_NOT_FOUND_HERE;
+	goto out;
+    } else if(ret){
+	const char *msg =3D krb5_get_error_message(context, ret);
+	char *p;
+	ret =3D krb5_unparse_name(context, princ, &p);
+	if (ret !=3D 0)
+	    p =3D failed;
 	krb5_free_principal(context, princ);
 	kdc_log(context, config, 0,
-		"Ticket-granting ticket not found in database: %s: %s",
-		p, krb5_get_err_text(context, ret));
+		"Ticket-granting ticket not found in database: %s", msg);
+	krb5_free_error_message(context, msg);
 	if (ret =3D=3D 0)
 	    free(p);
 	ret =3D KRB5KRB_AP_ERR_NOT_US;
 	goto out;
     }
-   =20
-    if(ap_req.ticket.enc_part.kvno &&=20
+
+    if(ap_req.ticket.enc_part.kvno &&
        *ap_req.ticket.enc_part.kvno !=3D (*krbtgt)->entry.kvno){
 	char *p;
=20
 	ret =3D krb5_unparse_name (context, princ, &p);
 	krb5_free_principal(context, princ);
 	if (ret !=3D 0)
-	    p =3D "<unparse_name failed>";
+	    p =3D failed;
 	kdc_log(context, config, 0,
-		"Ticket kvno =3D %d, DB kvno =3D %d (%s)",=20
+		"Ticket kvno =3D %d, DB kvno =3D %d (%s)",
 		*ap_req.ticket.enc_part.kvno,
 		(*krbtgt)->entry.kvno,
 		p);
@@ -1096,7 +1236,7 @@
=20
     *krbtgt_etype =3D ap_req.ticket.enc_part.etype;
=20
-    ret =3D hdb_enctype2key(context, &(*krbtgt)->entry,=20
+    ret =3D hdb_enctype2key(context, &(*krbtgt)->entry,
 			  ap_req.ticket.enc_part.etype, &tkey);
     if(ret){
 	char *str =3D NULL, *p =3D NULL;
@@ -1112,7 +1252,7 @@
 	ret =3D KRB5KRB_AP_ERR_BADKEYVER;
 	goto out;
     }
-   =20
+
     if (b->kdc_options.validate)
 	verify_ap_req_flags =3D KRB5_VERIFY_AP_REQ_IGNORE_INVALID;
     else
@@ -1127,11 +1267,12 @@
 			      &ap_req_options,
 			      ticket,
 			      KRB5_KU_TGS_REQ_AUTH);
-			    =20
+
     krb5_free_principal(context, princ);
     if(ret) {
-	kdc_log(context, config, 0, "Failed to verify AP-REQ: %s",=20
-		krb5_get_err_text(context, ret));
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0, "Failed to verify AP-REQ: %s", msg);
+	krb5_free_error_message(context, msg);
 	goto out;
     }
=20
@@ -1158,49 +1299,56 @@
 	}
     }
=20
-    ret =3D tgs_check_authenticator(context, config,=20
+    ret =3D tgs_check_authenticator(context, config,
 				  ac, b, e_text, &(*ticket)->ticket.key);
     if (ret) {
 	krb5_auth_con_free(context, ac);
 	goto out;
     }
=20
+    usage =3D KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY;
+    *rk_is_subkey =3D 1;
+
+    ret =3D krb5_auth_con_getremotesubkey(context, ac, &subkey);
+    if(ret){
+	const char *msg =3D krb5_get_error_message(context, ret);
+	krb5_auth_con_free(context, ac);
+	kdc_log(context, config, 0, "Failed to get remote subkey: %s", msg);
+	krb5_free_error_message(context, msg);
+	goto out;
+    }
+    if(subkey =3D=3D NULL){
+	usage =3D KRB5_KU_TGS_REQ_AUTH_DAT_SESSION;
+	*rk_is_subkey =3D 0;
+
+	ret =3D krb5_auth_con_getkey(context, ac, &subkey);
+	if(ret) {
+	    const char *msg =3D krb5_get_error_message(context, ret);
+	    krb5_auth_con_free(context, ac);
+	    kdc_log(context, config, 0, "Failed to get session key: %s", msg);
+	    krb5_free_error_message(context, msg);
+	    goto out;
+	}
+    }
+    if(subkey =3D=3D NULL){
+	krb5_auth_con_free(context, ac);
+	kdc_log(context, config, 0,
+		"Failed to get key for enc-authorization-data");
+	ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
+	goto out;
+    }
+
+    *replykey =3D subkey;
+
     if (b->enc_authorization_data) {
-	unsigned usage =3D KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY;
-	krb5_keyblock *subkey;
 	krb5_data ad;
=20
-	ret =3D krb5_auth_con_getremotesubkey(context,
-					    ac,
-					    &subkey);
-	if(ret){
-	    krb5_auth_con_free(context, ac);
-	    kdc_log(context, config, 0, "Failed to get remote subkey: %s",=20
-		    krb5_get_err_text(context, ret));
-	    goto out;
-	}
-	if(subkey =3D=3D NULL){
-	    usage =3D KRB5_KU_TGS_REQ_AUTH_DAT_SESSION;
-	    ret =3D krb5_auth_con_getkey(context, ac, &subkey);
-	    if(ret) {
-		krb5_auth_con_free(context, ac);
-		kdc_log(context, config, 0, "Failed to get session key: %s",=20
-			krb5_get_err_text(context, ret));
-		goto out;
-	    }
-	}
-	if(subkey =3D=3D NULL){
-	    krb5_auth_con_free(context, ac);
-	    kdc_log(context, config, 0,
-		    "Failed to get key for enc-authorization-data");
-	    ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
-	    goto out;
-	}
 	ret =3D krb5_crypto_init(context, subkey, 0, &crypto);
 	if (ret) {
+	    const char *msg =3D krb5_get_error_message(context, ret);
 	    krb5_auth_con_free(context, ac);
-	    kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-		    krb5_get_err_text(context, ret));
+	    kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+	    krb5_free_error_message(context, msg);
 	    goto out;
 	}
 	ret =3D krb5_decrypt_EncryptedData (context,
@@ -1211,12 +1359,11 @@
 	krb5_crypto_destroy(context, crypto);
 	if(ret){
 	    krb5_auth_con_free(context, ac);
-	    kdc_log(context, config, 0,=20
+	    kdc_log(context, config, 0,
 		    "Failed to decrypt enc-authorization-data");
 	    ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
 	    goto out;
 	}
-	krb5_free_keyblock(context, subkey);
 	ALLOC(*auth_data);
 	if (*auth_data =3D=3D NULL) {
 	    krb5_auth_con_free(context, ac);
@@ -1235,62 +1382,154 @@
     }
=20
     krb5_auth_con_free(context, ac);
-   =20
+
 out:
     free_AP_REQ(&ap_req);
-   =20
+
     return ret;
 }
=20
 static krb5_error_code
-tgs_build_reply(krb5_context context,=20
+build_server_referral(krb5_context context,
+		      krb5_kdc_configuration *config,
+		      krb5_crypto session,
+		      krb5_const_realm referred_realm,
+		      const PrincipalName *true_principal_name,
+		      const PrincipalName *requested_principal,
+		      krb5_data *outdata)
+{
+    PA_ServerReferralData ref;
+    krb5_error_code ret;
+    EncryptedData ed;
+    krb5_data data;
+    size_t size =3D 0;
+
+    memset(&ref, 0, sizeof(ref));
+
+    if (referred_realm) {
+	ALLOC(ref.referred_realm);
+	if (ref.referred_realm =3D=3D NULL)
+	    goto eout;
+	*ref.referred_realm =3D strdup(referred_realm);
+	if (*ref.referred_realm =3D=3D NULL)
+	    goto eout;
+    }
+    if (true_principal_name) {
+	ALLOC(ref.true_principal_name);
+	if (ref.true_principal_name =3D=3D NULL)
+	    goto eout;
+	ret =3D copy_PrincipalName(true_principal_name, ref.true_principal_name);
+	if (ret)
+	    goto eout;
+    }
+    if (requested_principal) {
+	ALLOC(ref.requested_principal_name);
+	if (ref.requested_principal_name =3D=3D NULL)
+	    goto eout;
+	ret =3D copy_PrincipalName(requested_principal,
+				 ref.requested_principal_name);
+	if (ret)
+	    goto eout;
+    }
+
+    ASN1_MALLOC_ENCODE(PA_ServerReferralData,
+		       data.data, data.length,
+		       &ref, &size, ret);
+    free_PA_ServerReferralData(&ref);
+    if (ret)
+	return ret;
+    if (data.length !=3D size)
+	krb5_abortx(context, "internal asn.1 encoder error");
+
+    ret =3D krb5_encrypt_EncryptedData(context, session,
+				     KRB5_KU_PA_SERVER_REFERRAL,
+				     data.data, data.length,
+				     0 /* kvno */, &ed);
+    free(data.data);
+    if (ret)
+	return ret;
+
+    ASN1_MALLOC_ENCODE(EncryptedData,
+		       outdata->data, outdata->length,
+		       &ed, &size, ret);
+    free_EncryptedData(&ed);
+    if (ret)
+	return ret;
+    if (outdata->length !=3D size)
+	krb5_abortx(context, "internal asn.1 encoder error");
+
+    return 0;
+eout:
+    free_PA_ServerReferralData(&ref);
+    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+    return ENOMEM;
+}
+
+static krb5_error_code
+tgs_build_reply(krb5_context context,
 		krb5_kdc_configuration *config,
-		KDC_REQ *req,=20
+		KDC_REQ *req,
 		KDC_REQ_BODY *b,
 		hdb_entry_ex *krbtgt,
 		krb5_enctype krbtgt_etype,
+		const krb5_keyblock *replykey,
+		int rk_is_subkey,
 		krb5_ticket *ticket,
 		krb5_data *reply,
 		const char *from,
 		const char **e_text,
-		AuthorizationData *auth_data,
-		const struct sockaddr *from_addr,
-		int datagram_reply)
+		AuthorizationData **auth_data,
+		const struct sockaddr *from_addr)
 {
     krb5_error_code ret;
-    krb5_principal cp =3D NULL, sp =3D NULL;
-    krb5_principal client_principal =3D NULL;
-    char *spn =3D NULL, *cpn =3D NULL;
-    hdb_entry_ex *server =3D NULL, *client =3D NULL;
+    krb5_principal cp =3D NULL, sp =3D NULL, rsp =3D NULL, tp =3D NULL, dp=
 =3D NULL;
+    krb5_principal krbtgt_principal =3D NULL;
+    char *spn =3D NULL, *cpn =3D NULL, *tpn =3D NULL, *dpn =3D NULL;
+    hdb_entry_ex *server =3D NULL, *client =3D NULL, *s4u2self_impersonate=
d_client =3D NULL;
+    HDB *clientdb, *s4u2self_impersonated_clientdb;
+    krb5_realm ref_realm =3D NULL;
     EncTicketPart *tgt =3D &ticket->ticket;
-    KRB5SignedPathPrincipals *spp =3D NULL;
+    krb5_principals spp =3D NULL;
     const EncryptionKey *ekey;
     krb5_keyblock sessionkey;
     krb5_kvno kvno;
     krb5_data rspac;
-    int cross_realm =3D 0;
+
+    hdb_entry_ex *krbtgt_out =3D NULL;
+
+    METHOD_DATA enc_pa_data;
=20
     PrincipalName *s;
     Realm r;
     int nloop =3D 0;
     EncTicketPart adtkt;
     char opt_str[128];
-    int require_signedpath =3D 0;
+    int signedpath =3D 0;
+
+    Key *tkey_check;
+    Key *tkey_sign;
+    int flags =3D HDB_F_FOR_TGS_REQ;
=20
     memset(&sessionkey, 0, sizeof(sessionkey));
     memset(&adtkt, 0, sizeof(adtkt));
     krb5_data_zero(&rspac);
+    memset(&enc_pa_data, 0, sizeof(enc_pa_data));
=20
     s =3D b->sname;
     r =3D b->realm;
=20
+    /*=20
+     * Always to do CANON, see comment below about returned server princip=
al (rsp).
+     */
+    flags |=3D HDB_F_CANON;
+
     if(b->kdc_options.enc_tkt_in_skey){
 	Ticket *t;
 	hdb_entry_ex *uu;
 	krb5_principal p;
 	Key *uukey;
-	   =20
-	if(b->additional_tickets =3D=3D NULL ||=20
+
+	if(b->additional_tickets =3D=3D NULL ||
 	   b->additional_tickets->len =3D=3D 0){
 	    ret =3D KRB5KDC_ERR_BADOPTION; /* ? */
 	    kdc_log(context, config, 0,
@@ -1305,8 +1544,8 @@
 	    goto out;
 	}
 	_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);
-	ret =3D _kdc_db_fetch(context, config, p,=20
-			    HDB_F_GET_CLIENT|HDB_F_GET_SERVER,=20
+	ret =3D _kdc_db_fetch(context, config, p,
+			    HDB_F_GET_KRBTGT, t->enc_part.kvno,
 			    NULL, &uu);
 	krb5_free_principal(context, p);
 	if(ret){
@@ -1314,7 +1553,7 @@
 		ret =3D KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
 	    goto out;
 	}
-	ret =3D hdb_enctype2key(context, &uu->entry,=20
+	ret =3D hdb_enctype2key(context, &uu->entry,
 			      t->enc_part.etype, &uukey);
 	if(ret){
 	    _kdc_free_ent(context, uu);
@@ -1335,7 +1574,7 @@
     }
=20
     _krb5_principalname2krb5_principal(context, &sp, *s, r);
-    ret =3D krb5_unparse_name(context, sp, &spn);=09
+    ret =3D krb5_unparse_name(context, sp, &spn);
     if (ret)
 	goto out;
     _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crea=
lm);
@@ -1347,7 +1586,7 @@
 		   opt_str, sizeof(opt_str));
     if(*opt_str)
 	kdc_log(context, config, 0,
-		"TGS-REQ %s from %s for %s [%s]",=20
+		"TGS-REQ %s from %s for %s [%s]",
 		cpn, from, spn, opt_str);
     else
 	kdc_log(context, config, 0,
@@ -1358,10 +1597,14 @@
      */
=20
 server_lookup:
-    ret =3D _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER, NULL, &se=
rver);
+    ret =3D _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | flags,
+			NULL, NULL, &server);
=20
-    if(ret){
-	const char *new_rlm;
+    if(ret =3D=3D HDB_ERR_NOT_FOUND_HERE) {
+	kdc_log(context, config, 5, "target %s does not have secrets at this KDC,=
 need to proxy", sp);
+	goto out;
+    } else if(ret){
+	const char *new_rlm, *msg;
 	Realm req_rlm;
 	krb5_realm *realms;
=20
@@ -1370,20 +1613,23 @@
 		new_rlm =3D find_rpath(context, tgt->crealm, req_rlm);
 		if(new_rlm) {
 		    kdc_log(context, config, 5, "krbtgt for realm %s "
-			    "not found, trying %s",=20
+			    "not found, trying %s",
 			    req_rlm, new_rlm);
 		    krb5_free_principal(context, sp);
 		    free(spn);
-		    krb5_make_principal(context, &sp, r,=20
+		    krb5_make_principal(context, &sp, r,
 					KRB5_TGS_NAME, new_rlm, NULL);
-		    ret =3D krb5_unparse_name(context, sp, &spn);=09
+		    ret =3D krb5_unparse_name(context, sp, &spn);
 		    if (ret)
 			goto out;
-		    auth_data =3D NULL; /* ms don't handle AD in referals */
+
+		    if (ref_realm)
+			free(ref_realm);
+		    ref_realm =3D strdup(new_rlm);
 		    goto server_lookup;
 		}
 	    }
-	} else if(need_referral(context, sp, &realms)) {
+	} else if(need_referral(context, config, &b->kdc_options, sp, &realms)) {
 	    if (strcmp(realms[0], sp->realm) !=3D 0) {
 		kdc_log(context, config, 5,
 			"Returning a referral to realm %s for "
@@ -1396,23 +1642,169 @@
 		ret =3D krb5_unparse_name(context, sp, &spn);
 		if (ret)
 		    goto out;
+
+		if (ref_realm)
+		    free(ref_realm);
+		ref_realm =3D strdup(realms[0]);
+
 		krb5_free_host_realm(context, realms);
-		auth_data =3D NULL; /* ms don't handle AD in referals */
 		goto server_lookup;
 	    }
 	    krb5_free_host_realm(context, realms);
 	}
+	msg =3D krb5_get_error_message(context, ret);
 	kdc_log(context, config, 0,
-		"Server not found in database: %s: %s", spn,
-		krb5_get_err_text(context, ret));
+		"Server not found in database: %s: %s", spn, msg);
+	krb5_free_error_message(context, msg);
 	if (ret =3D=3D HDB_ERR_NOENTRY)
 	    ret =3D KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
 	goto out;
     }
=20
-    ret =3D _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT, NULL, &cl=
ient);
+    /* the name returned to the client depend on what was asked for,
+     * return canonical name if kdc_options.canonicalize was set, the
+     * client wants the true name of the principal, if not it just
+     * wants the name its asked for.
+     */
+
+    if (b->kdc_options.canonicalize)
+	rsp =3D server->entry.principal;
+    else
+	rsp =3D sp;
+
+
+    /*
+     * Select enctype, return key and kvno.
+     */
+
+    {
+	krb5_enctype etype;
+
+	if(b->kdc_options.enc_tkt_in_skey) {
+	    size_t i;
+	    ekey =3D &adtkt.key;
+	    for(i =3D 0; i < b->etype.len; i++)
+		if (b->etype.val[i] =3D=3D adtkt.key.keytype)
+		    break;
+	    if(i =3D=3D b->etype.len) {
+		kdc_log(context, config, 0,
+			"Addition ticket have not matching etypes");
+		krb5_clear_error_message(context);
+		ret =3D KRB5KDC_ERR_ETYPE_NOSUPP;
+		goto out;
+	    }
+	    etype =3D b->etype.val[i];
+	    kvno =3D 0;
+	} else {
+	    Key *skey;
+
+	    ret =3D _kdc_find_etype(context,
+				  krb5_principal_is_krbtgt(context, sp) ?
+				  config->tgt_use_strongest_session_key :
+				  config->svc_use_strongest_session_key, FALSE,
+				  server, b->etype.val, b->etype.len, NULL,
+				  &skey);
+	    if(ret) {
+		kdc_log(context, config, 0,
+			"Server (%s) has no support for etypes", spn);
+		goto out;
+	    }
+	    ekey =3D &skey->key;
+	    etype =3D skey->key.keytype;
+	    kvno =3D server->entry.kvno;
+	}
+
+	ret =3D krb5_generate_random_keyblock(context, etype, &sessionkey);
+	if (ret)
+	    goto out;
+    }
+
+    /*
+     * Check that service is in the same realm as the krbtgt. If it's
+     * not the same, it's someone that is using a uni-directional trust
+     * backward.
+     */
+
+    /*
+     * Validate authoriation data
+     */
+
+    ret =3D hdb_enctype2key(context, &krbtgt->entry,
+			  krbtgt_etype, &tkey_check);
     if(ret) {
-	const char *krbtgt_realm;=20
+	kdc_log(context, config, 0,
+		    "Failed to find key for krbtgt PAC check");
+	goto out;
+    }
+
+    /* Now refetch the primary krbtgt, and get the current kvno (the
+     * sign check may have been on an old kvno, and the server may
+     * have been an incoming trust) */
+    ret =3D krb5_make_principal(context, &krbtgt_principal,
+			      krb5_principal_get_comp_string(context,
+							     krbtgt->entry.principal,
+							     1),
+			      KRB5_TGS_NAME,
+			      krb5_principal_get_comp_string(context,
+							     krbtgt->entry.principal,
+							     1), NULL);
+    if(ret) {
+	kdc_log(context, config, 0,
+		    "Failed to generate krbtgt principal");
+	goto out;
+    }
+
+    ret =3D _kdc_db_fetch(context, config, krbtgt_principal, HDB_F_GET_KRB=
TGT, NULL, NULL, &krbtgt_out);
+    krb5_free_principal(context, krbtgt_principal);
+    if (ret) {
+	krb5_error_code ret2;
+	char *ktpn, *ktpn2;
+	ret =3D krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);
+	ret2 =3D krb5_unparse_name(context, krbtgt_principal, &ktpn2);
+	kdc_log(context, config, 0,
+		"Request with wrong krbtgt: %s, %s not found in our database",
+		(ret =3D=3D 0) ? ktpn : "<unknown>", (ret2 =3D=3D 0) ? ktpn2 : "<unknown=
>");
+	if(ret =3D=3D 0)
+	    free(ktpn);
+	if(ret2 =3D=3D 0)
+	    free(ktpn2);
+	ret =3D KRB5KRB_AP_ERR_NOT_US;
+	goto out;
+    }
+
+    /* The first realm is the realm of the service, the second is
+     * krbtgt/<this>/@REALM component of the krbtgt DN the request was
+     * encrypted to.  The redirection via the krbtgt_out entry allows
+     * the DB to possibly correct the case of the realm (Samba4 does
+     * this) before the strcmp() */
+    if (strcmp(krb5_principal_get_realm(context, server->entry.principal),
+	       krb5_principal_get_realm(context, krbtgt_out->entry.principal)) !=
=3D 0) {
+	char *ktpn;
+	ret =3D krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);
+	kdc_log(context, config, 0,
+		"Request with wrong krbtgt: %s",
+		(ret =3D=3D 0) ? ktpn : "<unknown>");
+	if(ret =3D=3D 0)
+	    free(ktpn);
+	ret =3D KRB5KRB_AP_ERR_NOT_US;
+    }
+
+    ret =3D hdb_enctype2key(context, &krbtgt_out->entry,
+			  krbtgt_etype, &tkey_sign);
+    if(ret) {
+	kdc_log(context, config, 0,
+		    "Failed to find key for krbtgt PAC signature");
+	goto out;
+    }
+
+    ret =3D _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,
+			NULL, &clientdb, &client);
+    if(ret =3D=3D HDB_ERR_NOT_FOUND_HERE) {
+	/* This is OK, we are just trying to find out if they have
+	 * been disabled or deleted in the meantime, missing secrets
+	 * is OK */
+    } else if(ret){
+	const char *krbtgt_realm, *msg;
=20
 	/*
 	 * If the client belongs to the same realm as our krbtgt, it
@@ -1420,9 +1812,7 @@
 	 *
 	 */
=20
-	krbtgt_realm =3D=20
-	    krb5_principal_get_comp_string(context,=20
-					   krbtgt->entry.principal, 1);
+	krbtgt_realm =3D krb5_principal_get_realm(context, krbtgt_out->entry.prin=
cipal);
=20
 	if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) =3D=3D 0) {
 	    if (ret =3D=3D HDB_ERR_NOENTRY)
@@ -1431,53 +1821,63 @@
 		    cpn);
 	    goto out;
 	}
-=09
-	kdc_log(context, config, 1, "Client not found in database: %s: %s",
-		cpn, krb5_get_err_text(context, ret));
=20
-	cross_realm =3D 1;
+	msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 1, "Client not found in database: %s", msg);
+	krb5_free_error_message(context, msg);
     }
-   =20
-    /*
-     * Check that service is in the same realm as the krbtgt. If it's
-     * not the same, it's someone that is using a uni-directional trust
-     * backward.
-     */
-   =20
-    if (strcmp(krb5_principal_get_realm(context, sp),
-	       krb5_principal_get_comp_string(context,=20
-					      krbtgt->entry.principal,=20
-					      1)) !=3D 0) {
-	char *tpn;
-	ret =3D krb5_unparse_name(context, krbtgt->entry.principal, &tpn);
+
+    ret =3D check_PAC(context, config, cp, NULL,
+		    client, server, krbtgt,
+		    &tkey_check->key, &tkey_check->key,
+		    ekey, &tkey_sign->key,
+		    tgt, &rspac, &signedpath);
+    if (ret) {
+	const char *msg =3D krb5_get_error_message(context, ret);
 	kdc_log(context, config, 0,
-		"Request with wrong krbtgt: %s",
-		(ret =3D=3D 0) ? tpn : "<unknown>");
-	if(ret =3D=3D 0)
-	    free(tpn);
-	ret =3D KRB5KRB_AP_ERR_NOT_US;
+		"Verify PAC failed for %s (%s) from %s with %s",
+		spn, cpn, from, msg);
+	krb5_free_error_message(context, msg);
+	goto out;
+    }
+
+    /* also check the krbtgt for signature */
+    ret =3D check_KRB5SignedPath(context,
+			       config,
+			       krbtgt,
+			       cp,
+			       tgt,
+			       &spp,
+			       &signedpath);
+    if (ret) {
+	const char *msg =3D krb5_get_error_message(context, ret);
+	kdc_log(context, config, 0,
+		"KRB5SignedPath check failed for %s (%s) from %s with %s",
+		spn, cpn, from, msg);
+	krb5_free_error_message(context, msg);
 	goto out;
     }
=20
     /*
-     *
+     * Process request
      */
=20
-    client_principal =3D cp;
+    /* by default the tgt principal matches the client principal */
+    tp =3D cp;
+    tpn =3D cpn;
=20
     if (client) {
 	const PA_DATA *sdata;
 	int i =3D 0;
=20
-	sdata =3D _kdc_find_padata(req, &i, KRB5_PADATA_S4U2SELF);
+	sdata =3D _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);
 	if (sdata) {
 	    krb5_crypto crypto;
 	    krb5_data datack;
 	    PA_S4U2Self self;
-	    char *selfcpn =3D NULL;
 	    const char *str;
=20
-	    ret =3D decode_PA_S4U2Self(sdata->padata_value.data,=20
+	    ret =3D decode_PA_S4U2Self(sdata->padata_value.data,
 				     sdata->padata_value.length,
 				     &self, NULL);
 	    if (ret) {
@@ -1491,52 +1891,97 @@
=20
 	    ret =3D krb5_crypto_init(context, &tgt->key, 0, &crypto);
 	    if (ret) {
+		const char *msg =3D krb5_get_error_message(context, ret);
 		free_PA_S4U2Self(&self);
 		krb5_data_free(&datack);
-		kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-			krb5_get_err_text(context, ret));
+		kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+		krb5_free_error_message(context, msg);
 		goto out;
 	    }
=20
 	    ret =3D krb5_verify_checksum(context,
 				       crypto,
 				       KRB5_KU_OTHER_CKSUM,
-				       datack.data,=20
-				       datack.length,=20
+				       datack.data,
+				       datack.length,
 				       &self.cksum);
 	    krb5_data_free(&datack);
 	    krb5_crypto_destroy(context, crypto);
 	    if (ret) {
+		const char *msg =3D krb5_get_error_message(context, ret);
 		free_PA_S4U2Self(&self);
-		kdc_log(context, config, 0,=20
-			"krb5_verify_checksum failed for S4U2Self: %s",
-			krb5_get_err_text(context, ret));
+		kdc_log(context, config, 0,
+			"krb5_verify_checksum failed for S4U2Self: %s", msg);
+		krb5_free_error_message(context, msg);
 		goto out;
 	    }
=20
 	    ret =3D _krb5_principalname2krb5_principal(context,
-						     &client_principal,
+						     &tp,
 						     self.name,
 						     self.realm);
 	    free_PA_S4U2Self(&self);
 	    if (ret)
 		goto out;
=20
-	    ret =3D krb5_unparse_name(context, client_principal, &selfcpn);=09
+	    ret =3D krb5_unparse_name(context, tp, &tpn);
 	    if (ret)
 		goto out;
=20
+	    /* If we were about to put a PAC into the ticket, we better fix it to=
 be the right PAC */
+	    if(rspac.data) {
+		krb5_pac p =3D NULL;
+		krb5_data_free(&rspac);
+		ret =3D _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,
+				    NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_clie=
nt);
+		if (ret) {
+		    const char *msg;
+
+		    /*
+		     * If the client belongs to the same realm as our krbtgt, it
+		     * should exist in the local database.
+		     *
+		     */
+
+		    if (ret =3D=3D HDB_ERR_NOENTRY)
+			ret =3D KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
+		    msg =3D krb5_get_error_message(context, ret);
+		    kdc_log(context, config, 1,
+			    "S2U4Self principal to impersonate %s not found in database: %s",
+			    tpn, msg);
+		    krb5_free_error_message(context, msg);
+		    goto out;
+		}
+		ret =3D _kdc_pac_generate(context, s4u2self_impersonated_client, &p);
+		if (ret) {
+		    kdc_log(context, config, 0, "PAC generation failed for -- %s",
+			    tpn);
+		    goto out;
+		}
+		if (p !=3D NULL) {
+		    ret =3D _krb5_pac_sign(context, p, ticket->ticket.authtime,
+					 s4u2self_impersonated_client->entry.principal,
+					 ekey, &tkey_sign->key,
+					 &rspac);
+		    krb5_pac_free(context, p);
+		    if (ret) {
+			kdc_log(context, config, 0, "PAC signing failed for -- %s",
+				tpn);
+			goto out;
+		    }
+		}
+	    }
+
 	    /*
 	     * Check that service doing the impersonating is
 	     * requesting a ticket to it-self.
 	     */
-	    if (krb5_principal_compare(context, cp, sp) !=3D TRUE) {
+	    ret =3D check_s4u2self(context, config, clientdb, client, sp);
+	    if (ret) {
 		kdc_log(context, config, 0, "S4U2Self: %s is not allowed "
-			"to impersonate some other user "
+			"to impersonate to service "
 			"(tried for user %s to service %s)",
-			cpn, selfcpn, spn);
-		free(selfcpn);
-		ret =3D KRB5KDC_ERR_BADOPTION; /* ? */
+			cpn, tpn, spn);
 		goto out;
 	    }
=20
@@ -1552,8 +1997,7 @@
 		str =3D "";
 	    }
 	    kdc_log(context, config, 0, "s4u2self %s impersonating %s to "
-		    "service %s %s", cpn, selfcpn, spn, str);
-	    free(selfcpn);
+		    "service %s %s", cpn, tpn, spn, str);
 	}
     }
=20
@@ -1566,13 +2010,25 @@
 	&& b->additional_tickets->len !=3D 0
 	&& b->kdc_options.enc_tkt_in_skey =3D=3D 0)
     {
+	int ad_signedpath =3D 0;
 	Key *clientkey;
 	Ticket *t;
-	char *str;
+
+	/*
+	 * Require that the KDC have issued the service's krbtgt (not
+	 * self-issued ticket with kimpersonate(1).
+	 */
+	if (!signedpath) {
+	    ret =3D KRB5KDC_ERR_BADOPTION;
+	    kdc_log(context, config, 0,
+		    "Constrained delegation done on service ticket %s/%s",
+		    cpn, spn);
+	    goto out;
+	}
=20
 	t =3D &b->additional_tickets->val[0];
=20
-	ret =3D hdb_enctype2key(context, &client->entry,=20
+	ret =3D hdb_enctype2key(context, &client->entry,
 			      t->enc_part.etype, &clientkey);
 	if(ret){
 	    ret =3D KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
@@ -1583,90 +2039,127 @@
 	if (ret) {
 	    kdc_log(context, config, 0,
 		    "failed to decrypt ticket for "
-		    "constrained delegation from %s to %s ", spn, cpn);
-	    goto out;
-	}
-
-	/* check that ticket is valid */
-
-	if (adtkt.flags.forwardable =3D=3D 0) {
-	    kdc_log(context, config, 0,
-		    "Missing forwardable flag on ticket for "
-		    "constrained delegation from %s to %s ", spn, cpn);
-	    ret =3D KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
-	    goto out;
-	}
-
-	ret =3D check_constrained_delegation(context, config, client, sp);
-	if (ret) {
-	    kdc_log(context, config, 0,
-		    "constrained delegation from %s to %s not allowed",=20
-		    spn, cpn);
+		    "constrained delegation from %s to %s ", cpn, spn);
 	    goto out;
 	}
=20
 	ret =3D _krb5_principalname2krb5_principal(context,
-						 &client_principal,
+						 &tp,
 						 adtkt.cname,
 						 adtkt.crealm);
 	if (ret)
 	    goto out;
=20
-	ret =3D krb5_unparse_name(context, client_principal, &str);
+	ret =3D krb5_unparse_name(context, tp, &tpn);
 	if (ret)
 	    goto out;
=20
-	ret =3D verify_flags(context, config, &adtkt, str);
+	ret =3D _krb5_principalname2krb5_principal(context,
+						 &dp,
+						 t->sname,
+						 t->realm);
+	if (ret)
+	    goto out;
+
+	ret =3D krb5_unparse_name(context, dp, &dpn);
+	if (ret)
+	    goto out;
+
+	/* check that ticket is valid */
+	if (adtkt.flags.forwardable =3D=3D 0) {
+	    kdc_log(context, config, 0,
+		    "Missing forwardable flag on ticket for "
+		    "constrained delegation from %s (%s) as %s to %s ",
+		    cpn, dpn, tpn, spn);
+	    ret =3D KRB5KDC_ERR_BADOPTION;
+	    goto out;
+	}
+
+	ret =3D check_constrained_delegation(context, config, clientdb,
+					   client, server, sp);
 	if (ret) {
-	    free(str);
+	    kdc_log(context, config, 0,
+		    "constrained delegation from %s (%s) as %s to %s not allowed",
+		    cpn, dpn, tpn, spn);
+	    goto out;
+	}
+
+	ret =3D verify_flags(context, config, &adtkt, tpn);
+	if (ret) {
+	    goto out;
+	}
+
+	krb5_data_free(&rspac);
+
+	/*
+	 * generate the PAC for the user.
+	 *
+	 * TODO: pass in t->sname and t->realm and build
+	 * a S4U_DELEGATION_INFO blob to the PAC.
+	 */
+	ret =3D check_PAC(context, config, tp, dp,
+			client, server, krbtgt,
+			&clientkey->key, &tkey_check->key,
+			ekey, &tkey_sign->key,
+			&adtkt, &rspac, &ad_signedpath);
+	if (ret) {
+	    const char *msg =3D krb5_get_error_message(context, ret);
+	    kdc_log(context, config, 0,
+		    "Verify delegated PAC failed to %s for client"
+		    "%s (%s) as %s from %s with %s",
+		    spn, cpn, dpn, tpn, from, msg);
+	    krb5_free_error_message(context, msg);
 	    goto out;
 	}
=20
 	/*
-	 * Check KRB5SignedPath in authorization data and add new entry to
-	 * make sure servers can't fake a ticket to us.
+	 * Check that the KDC issued the user's ticket.
 	 */
-
 	ret =3D check_KRB5SignedPath(context,
 				   config,
 				   krbtgt,
+				   cp,
 				   &adtkt,
-				   &spp,
-				   1);
+				   NULL,
+				   &ad_signedpath);
 	if (ret) {
+	    const char *msg =3D krb5_get_error_message(context, ret);
 	    kdc_log(context, config, 0,
 		    "KRB5SignedPath check from service %s failed "
-		    "for delegation to %s for client %s "
+		    "for delegation to %s for client %s (%s)"
 		    "from %s failed with %s",
-		    spn, str, cpn, from, krb5_get_err_text(context, ret));
-	    free(str);
+		    spn, tpn, dpn, cpn, from, msg);
+	    krb5_free_error_message(context, msg);
+	    goto out;
+	}
+
+	if (!ad_signedpath) {
+	    ret =3D KRB5KDC_ERR_BADOPTION;
+	    kdc_log(context, config, 0,
+		    "Ticket not signed with PAC nor SignedPath service %s failed "
+		    "for delegation to %s for client %s (%s)"
+		    "from %s",
+		    spn, tpn, dpn, cpn, from);
 	    goto out;
 	}
=20
 	kdc_log(context, config, 0, "constrained delegation for %s "
-		"from %s to %s", str, cpn, spn);
-	free(str);
-
-	/*=20
-	 * Also require that the KDC have issue the service's krbtgt
-	 * used to do the request.=20
-	 */
-	require_signedpath =3D 1;
+		"from %s (%s) to %s", tpn, cpn, dpn, spn);
     }
=20
     /*
      * Check flags
      */
=20
-    ret =3D _kdc_check_flags(context, config,=20
-			   client, cpn,
-			   server, spn,
-			   FALSE);
+    ret =3D kdc_check_flags(context, config,
+			  client, cpn,
+			  server, spn,
+			  FALSE);
     if(ret)
 	goto out;
=20
-    if((b->kdc_options.validate || b->kdc_options.renew) &&=20
-       !krb5_principal_compare(context,=20
+    if((b->kdc_options.validate || b->kdc_options.renew) &&
+       !krb5_principal_compare(context,
 			       krbtgt->entry.principal,
 			       server->entry.principal)){
 	kdc_log(context, config, 0, "Inconsistent request.");
@@ -1680,123 +2173,99 @@
 	kdc_log(context, config, 0, "Request from wrong address");
 	goto out;
     }
-=09
+
     /*
-     * Select enctype, return key and kvno.
+     * If this is an referral, add server referral data to the
+     * auth_data reply .
      */
+    if (ref_realm) {
+	PA_DATA pa;
+	krb5_crypto crypto;
=20
-    {
-	krb5_enctype etype;
+	kdc_log(context, config, 0,
+		"Adding server referral to %s", ref_realm);
=20
-	if(b->kdc_options.enc_tkt_in_skey) {
-	    int i;
-	    ekey =3D &adtkt.key;
-	    for(i =3D 0; i < b->etype.len; i++)
-		if (b->etype.val[i] =3D=3D adtkt.key.keytype)
-		    break;
-	    if(i =3D=3D b->etype.len) {
-		krb5_clear_error_string(context);
-		return KRB5KDC_ERR_ETYPE_NOSUPP;
-	    }
-	    etype =3D b->etype.val[i];
-	    kvno =3D 0;
-	} else {
-	    Key *skey;
-	   =20
-	    ret =3D _kdc_find_etype(context, server, b->etype.val, b->etype.len,
-				  &skey, &etype);
-	    if(ret) {
-		kdc_log(context, config, 0,=20
-			"Server (%s) has no support for etypes", spp);
-		return ret;
-	    }
-	    ekey =3D &skey->key;
-	    kvno =3D server->entry.kvno;
-	}
-=09
-	ret =3D krb5_generate_random_keyblock(context, etype, &sessionkey);
+	ret =3D krb5_crypto_init(context, &sessionkey, 0, &crypto);
 	if (ret)
 	    goto out;
-    }
=20
-    /* check PAC if not cross realm and if there is one */
-    if (!cross_realm) {
-	Key *tkey;
-
-	ret =3D hdb_enctype2key(context, &krbtgt->entry,=20
-			      krbtgt_etype, &tkey);
-	if(ret) {
+	ret =3D build_server_referral(context, config, crypto, ref_realm,
+				    NULL, s, &pa.padata_value);
+	krb5_crypto_destroy(context, crypto);
+	if (ret) {
 	    kdc_log(context, config, 0,
-		    "Failed to find key for krbtgt PAC check");
+		    "Failed building server referral");
 	    goto out;
 	}
+	pa.padata_type =3D KRB5_PADATA_SERVER_REFERRAL;
=20
-	ret =3D check_PAC(context, config, client_principal,=20
-			client, server, ekey, &tkey->key,
-			tgt, &rspac, &require_signedpath);
+	ret =3D add_METHOD_DATA(&enc_pa_data, &pa);
+	krb5_data_free(&pa.padata_value);
 	if (ret) {
 	    kdc_log(context, config, 0,
-		    "Verify PAC failed for %s (%s) from %s with %s",
-		    spn, cpn, from, krb5_get_err_text(context, ret));
+		    "Add server referral METHOD-DATA failed");
 	    goto out;
 	}
     }
=20
-    /* also check the krbtgt for signature */
-    ret =3D check_KRB5SignedPath(context,
-			       config,
-			       krbtgt,
-			       tgt,
-			       &spp,
-			       require_signedpath);
-    if (ret) {
-	kdc_log(context, config, 0,
-		"KRB5SignedPath check failed for %s (%s) from %s with %s",
-		spn, cpn, from, krb5_get_err_text(context, ret));
-	goto out;
-    }
-
     /*
      *
      */
=20
     ret =3D tgs_make_reply(context,
-			 config,=20
-			 b,=20
-			 client_principal,
-			 tgt,=20
+			 config,
+			 b,
+			 tp,
+			 tgt,
+			 replykey,
+			 rk_is_subkey,
 			 ekey,
 			 &sessionkey,
 			 kvno,
-			 auth_data,
-			 server,=20
+			 *auth_data,
+			 server,
+			 rsp,
 			 spn,
-			 client,=20
-			 cp,=20
-			 krbtgt,=20
+			 client,
+			 cp,
+			 krbtgt_out,
 			 krbtgt_etype,
 			 spp,
 			 &rspac,
+			 &enc_pa_data,
 			 e_text,
 			 reply);
-=09
+
 out:
+    if (tpn !=3D cpn)
+	    free(tpn);
     free(spn);
     free(cpn);
-	   =20
+    if (dpn)
+	free(dpn);
+
     krb5_data_free(&rspac);
     krb5_free_keyblock_contents(context, &sessionkey);
+    if(krbtgt_out)
+	_kdc_free_ent(context, krbtgt_out);
     if(server)
 	_kdc_free_ent(context, server);
     if(client)
 	_kdc_free_ent(context, client);
+    if(s4u2self_impersonated_client)
+	_kdc_free_ent(context, s4u2self_impersonated_client);
=20
-    if (client_principal && client_principal !=3D cp)
-	krb5_free_principal(context, client_principal);
+    if (tp && tp !=3D cp)
+	krb5_free_principal(context, tp);
     if (cp)
 	krb5_free_principal(context, cp);
+    if (dp)
+	krb5_free_principal(context, dp);
     if (sp)
 	krb5_free_principal(context, sp);
+    if (ref_realm)
+	free(ref_realm);
+    free_METHOD_DATA(&enc_pa_data);
=20
     free_EncTicketPart(&adtkt);
=20
@@ -1808,9 +2277,9 @@
  */
=20
 krb5_error_code
-_kdc_tgs_rep(krb5_context context,=20
+_kdc_tgs_rep(krb5_context context,
 	     krb5_kdc_configuration *config,
-	     KDC_REQ *req,=20
+	     KDC_REQ *req,
 	     krb5_data *data,
 	     const char *from,
 	     struct sockaddr *from_addr,
@@ -1826,6 +2295,8 @@
     const char *e_text =3D NULL;
     krb5_enctype krbtgt_etype =3D ETYPE_NULL;
=20
+    krb5_keyblock *replykey =3D NULL;
+    int rk_is_subkey =3D 0;
     time_t *csec =3D NULL;
     int *cusec =3D NULL;
=20
@@ -1835,17 +2306,17 @@
 		"TGS-REQ from %s without PA-DATA", from);
 	goto out;
     }
-   =20
+
     tgs_req =3D _kdc_find_padata(req, &i, KRB5_PADATA_TGS_REQ);
=20
     if(tgs_req =3D=3D NULL){
 	ret =3D KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
-=09
-	kdc_log(context, config, 0,=20
+
+	kdc_log(context, config, 0,
 		"TGS-REQ from %s without PA-TGS-REQ", from);
 	goto out;
     }
-    ret =3D tgs_parse_request(context, config,=20
+    ret =3D tgs_parse_request(context, config,
 			    &req->req_body, tgs_req,
 			    &krbtgt,
 			    &krbtgt_etype,
@@ -1853,9 +2324,15 @@
 			    &e_text,
 			    from, from_addr,
 			    &csec, &cusec,
-			    &auth_data);
+			    &auth_data,
+			    &replykey,
+			    &rk_is_subkey);
+    if (ret =3D=3D HDB_ERR_NOT_FOUND_HERE) {
+	/* kdc_log() is called in tgs_parse_request() */
+	goto out;
+    }
     if (ret) {
-	kdc_log(context, config, 0,=20
+	kdc_log(context, config, 0,
 		"Failed parsing TGS-REQ from %s", from);
 	goto out;
     }
@@ -1866,15 +2343,16 @@
 			  &req->req_body,
 			  krbtgt,
 			  krbtgt_etype,
+			  replykey,
+			  rk_is_subkey,
 			  ticket,
 			  data,
 			  from,
 			  &e_text,
-			  auth_data,
-			  from_addr,
-			  datagram_reply);
+			  &auth_data,
+			  from_addr);
     if (ret) {
-	kdc_log(context, config, 0,=20
+	kdc_log(context, config, 0,
 		"Failed building TGS-REP to %s", from);
 	goto out;
     }
@@ -1887,7 +2365,9 @@
     }
=20
 out:
-    if(ret && data->data =3D=3D NULL){
+    if (replykey)
+	krb5_free_keyblock(context, replykey);
+    if(ret && ret !=3D HDB_ERR_NOT_FOUND_HERE && data->data =3D=3D NULL){
 	krb5_mk_error(context,
 		      ret,
 		      NULL,
@@ -1897,6 +2377,7 @@
 		      csec,
 		      cusec,
 		      data);
+	ret =3D 0;
     }
     free(csec);
     free(cusec);
@@ -1910,5 +2391,5 @@
 	free(auth_data);
     }
=20
-    return 0;
+    return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kstash.8
--- a/head/crypto/heimdal/kdc/kstash.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kstash.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
 .\"
-.\" $Id: kstash.8 20316 2007-04-11 11:53:20Z lha $
+.\" $Id$
 .\"
 .Dd April 10, 2007
 .Dt KSTASH 8
@@ -41,19 +41,19 @@
 .Nm
 .Bk -words
 .Oo Fl e Ar string \*(Ba Xo
-.Fl -enctype=3D Ns Ar string
+.Fl Fl enctype=3D Ns Ar string
 .Xc
 .Oc
 .Oo Fl k Ar file \*(Ba Xo
-.Fl -key-file=3D Ns Ar file
+.Fl Fl key-file=3D Ns Ar file
 .Xc
 .Oc
-.Op Fl -convert-file
-.Op Fl -random-key
-.Op Fl -master-key-fd=3D Ns Ar fd
-.Op Fl -random-key
-.Op Fl h | Fl -help
-.Op Fl -version
+.Op Fl Fl convert-file
+.Op Fl Fl random-key
+.Op Fl Fl master-key-fd=3D Ns Ar fd
+.Op Fl Fl random-key
+.Op Fl h | Fl Fl help
+.Op Fl Fl version
 .Ek
 .Sh DESCRIPTION
 .Nm
@@ -62,28 +62,16 @@
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl e Ar string ,
-.Fl -enctype=3D Ns Ar string
-.Xc
+.It Fl e Ar string , Fl Fl enctype=3D Ns Ar string
 the encryption type to use, defaults to DES3-CBC-SHA1.
-.It Xo
-.Fl k Ar file ,
-.Fl -key-file=3D Ns Ar file
-.Xc
+.It Fl k Ar file , Fl Fl key-file=3D Ns Ar file
 the name of the master key file.
-.It Xo
-.Fl -convert-file
-.Xc
+.It Fl Fl convert-file
 don't ask for a new master key, just read an old master key file, and
 write it back in the new keyfile format.
-.It Xo
-.Fl -random-key
-.Xc
+.It Fl Fl random-key
 generate a random master key.
-.It Xo
-.Fl -master-key-fd=3D Ns Ar fd
-.Xc
+.It Fl Fl master-key-fd=3D Ns Ar fd
 filedescriptor to read passphrase from, if not specified the
 passphrase will be read from the terminal.
 .El
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kstash.c
--- a/head/crypto/heimdal/kdc/kstash.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kstash.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "headers.h"
=20
-RCSID("$Id: kstash.c 22244 2007-12-08 23:47:42Z lha $");
-
 krb5_context context;
=20
 static char *keyfile;
@@ -48,15 +46,17 @@
 static const char *enctype_str =3D "des3-cbc-sha1";
=20
 static struct getargs args[] =3D {
-    { "enctype", 'e', arg_string, &enctype_str, "encryption type" },
+    { "enctype", 'e', arg_string, rk_UNCONST(&enctype_str), "encryption ty=
pe",
+	NULL },
     { "key-file", 'k', arg_string, &keyfile, "master key file", "file" },
-    { "convert-file", 0, arg_flag, &convert_flag,=20
-      "just convert keyfile to new format" },
-    { "master-key-fd", 0, arg_integer, &master_key_fd,=20
+    { "convert-file", 0, arg_flag, &convert_flag,
+      "just convert keyfile to new format", NULL },
+    { "master-key-fd", 0, arg_integer, &master_key_fd,
       "filedescriptor to read passphrase from", "fd" },
-    { "random-key", 0, arg_flag, &random_key_flag, "generate a random mast=
er key" },
-    { "help", 'h', arg_flag, &help_flag },
-    { "version", 0, arg_flag, &version_flag }
+    { "random-key", 0, arg_flag, &random_key_flag,
+	"generate a random master key", NULL },
+    { "help", 'h', arg_flag, &help_flag, NULL, NULL },
+    { "version", 0, arg_flag, &version_flag, NULL, NULL }
 };
=20
 int num_args =3D sizeof(args) / sizeof(args[0]);
@@ -66,11 +66,11 @@
 {
     char buf[1024];
     krb5_error_code ret;
-   =20
+
     krb5_enctype enctype;
=20
     hdb_master_key mkey;
-   =20
+
     krb5_program_setup(&context, argc, argv, args, num_args, NULL);
=20
     if(help_flag)
@@ -118,7 +118,7 @@
 		    krb5_err(context, 1, errno, "failed to read passphrase");
 		buf[n] =3D '\0';
 		buf[strcspn(buf, "\r\n")] =3D '\0';
-	=09
+
 	    } else {
 		if(UI_UTIL_read_pw_string(buf, sizeof(buf), "Master key: ", 1))
 		    exit(1);
@@ -126,11 +126,11 @@
 	    krb5_string_to_key_salt(context, enctype, buf, salt, &key);
 	}
 	ret =3D hdb_add_master_key(context, &key, &mkey);
-=09
+
 	krb5_free_keyblock_contents(context, &key);
=20
     }
-   =20
+
     {
 	char *new, *old;
 	asprintf(&old, "%s.old", keyfile);
@@ -144,13 +144,19 @@
 	if(ret)
 	    unlink(new);
 	else {
+#ifndef NO_POSIX_LINKS
 	    unlink(old);
 	    if(link(keyfile, old) < 0 && errno !=3D ENOENT) {
 		ret =3D errno;
 		unlink(new);
-	    } else if(rename(new, keyfile) < 0) {
-		ret =3D errno;
+	    } else {
+#endif
+		if(rename(new, keyfile) < 0) {
+		    ret =3D errno;
+		}
+#ifndef NO_POSIX_LINKS
 	    }
+#endif
 	}
     out:
 	free(old);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/kx509.c
--- a/head/crypto/heimdal/kdc/kx509.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/kx509.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
@@ -36,14 +36,14 @@
 #include <rfc2459_asn1.h>
 #include <hx509.h>
=20
-RCSID("$Id: kx509.c 21607 2007-07-17 07:04:52Z lha $");
+#ifdef KX509
=20
 /*
  *
  */
=20
 krb5_error_code
-_kdc_try_kx509_request(void *ptr, size_t len, Kx509Request *req, size_t *s=
ize)
+_kdc_try_kx509_request(void *ptr, size_t len, struct Kx509Request *req, si=
ze_t *size)
 {
     if (len < 4)
 	return -1;
@@ -59,22 +59,23 @@
 static const unsigned char version_2_0[4] =3D {0 , 0, 2, 0};
=20
 static krb5_error_code
-verify_req_hash(krb5_context context,=20
+verify_req_hash(krb5_context context,
 		const Kx509Request *req,
 		krb5_keyblock *key)
 {
     unsigned char digest[SHA_DIGEST_LENGTH];
     HMAC_CTX ctx;
-   =20
+
     if (req->pk_hash.length !=3D sizeof(digest)) {
-	krb5_set_error_string(context, "pk-hash have wrong length: %lu",
-			      (unsigned long)req->pk_hash.length);
+	krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
+			       "pk-hash have wrong length: %lu",
+			       (unsigned long)req->pk_hash.length);
 	return KRB5KDC_ERR_PREAUTH_FAILED;
     }
=20
     HMAC_CTX_init(&ctx);
-    HMAC_Init_ex(&ctx,=20
-		 key->keyvalue.data, key->keyvalue.length,=20
+    HMAC_Init_ex(&ctx,
+		 key->keyvalue.data, key->keyvalue.length,
 		 EVP_sha1(), NULL);
     if (sizeof(digest) !=3D HMAC_size(&ctx))
 	krb5_abortx(context, "runtime error, hmac buffer wrong size in kx509");
@@ -84,7 +85,8 @@
     HMAC_CTX_cleanup(&ctx);
=20
     if (memcmp(req->pk_hash.data, digest, sizeof(digest)) !=3D 0) {
-	krb5_set_error_string(context, "pk-hash is not correct");
+	krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
+			       "pk-hash is not correct");
 	return KRB5KDC_ERR_PREAUTH_FAILED;
     }
     return 0;
@@ -95,18 +97,17 @@
 		     krb5_keyblock *key,
 		     Kx509Response *rep)
 {
+    krb5_error_code ret;
     HMAC_CTX ctx;
-   =20
+
     HMAC_CTX_init(&ctx);
=20
-    HMAC_Init_ex(&ctx,=20
-		 key->keyvalue.data, key->keyvalue.length,=20
+    HMAC_Init_ex(&ctx, key->keyvalue.data, key->keyvalue.length,
 		 EVP_sha1(), NULL);
-    rep->hash->length =3D HMAC_size(&ctx);
-    rep->hash->data =3D malloc(rep->hash->length);
-    if (rep->hash->data =3D=3D NULL) {
+    ret =3D krb5_data_alloc(rep->hash, HMAC_size(&ctx));
+    if (ret) {
 	HMAC_CTX_cleanup(&ctx);
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
=20
@@ -131,18 +132,17 @@
 }
=20
 /*
- * Build a certifate for `principal=B4 that will expire at `endtime=B4.
+ * Build a certifate for `principal=C2=B4 that will expire at `endtime=C2=
=B4.
  */
=20
 static krb5_error_code
-build_certificate(krb5_context context,=20
+build_certificate(krb5_context context,
 		  krb5_kdc_configuration *config,
 		  const krb5_data *key,
 		  time_t endtime,
 		  krb5_principal principal,
 		  krb5_data *certificate)
 {
-    hx509_context hxctx =3D NULL;
     hx509_ca_tbs tbs =3D NULL;
     hx509_env env =3D NULL;
     hx509_cert cert =3D NULL;
@@ -154,15 +154,7 @@
 	return EINVAL;
     }
=20
-    ret =3D hx509_context_init(&hxctx);
-    if (ret)
-	goto out;
-
-    ret =3D hx509_env_init(hxctx, &env);
-    if (ret)
-	goto out;
-
-    ret =3D hx509_env_add(hxctx, env, "principal-name",=20
+    ret =3D hx509_env_add(context->hx509ctx, &env, "principal-name",
 			krb5_principal_get_comp_string(context, principal, 0));
     if (ret)
 	goto out;
@@ -171,14 +163,14 @@
 	hx509_certs certs;
 	hx509_query *q;
=20
-	ret =3D hx509_certs_init(hxctx, config->kx509_ca, 0,
+	ret =3D hx509_certs_init(context->hx509ctx, config->kx509_ca, 0,
 			       NULL, &certs);
 	if (ret) {
 	    kdc_log(context, config, 0, "Failed to load CA %s",
 		    config->kx509_ca);
 	    goto out;
 	}
-	ret =3D hx509_query_alloc(hxctx, &q);
+	ret =3D hx509_query_alloc(context->hx509ctx, &q);
 	if (ret) {
 	    hx509_certs_free(&certs);
 	    goto out;
@@ -187,8 +179,8 @@
 	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
 	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_KEYCERTSIGN);
=20
-	ret =3D hx509_certs_find(hxctx, certs, q, &signer);
-	hx509_query_free(hxctx, q);
+	ret =3D hx509_certs_find(context->hx509ctx, certs, q, &signer);
+	hx509_query_free(context->hx509ctx, q);
 	hx509_certs_free(&certs);
 	if (ret) {
 	    kdc_log(context, config, 0, "Failed to find a CA in %s",
@@ -197,7 +189,7 @@
 	}
     }
=20
-    ret =3D hx509_ca_tbs_init(hxctx, &tbs);
+    ret =3D hx509_ca_tbs_init(context->hx509ctx, &tbs);
     if (ret)
 	goto out;
=20
@@ -210,14 +202,14 @@
 	spki.subjectPublicKey.data =3D key->data;
 	spki.subjectPublicKey.length =3D key->length * 8;
=20
-	ret =3D der_copy_oid(oid_id_pkcs1_rsaEncryption(),=20
+	ret =3D der_copy_oid(&asn1_oid_id_pkcs1_rsaEncryption,
 			   &spki.algorithm.algorithm);
=20
 	any.data =3D "\x05\x00";
 	any.length =3D 2;
 	spki.algorithm.parameters =3D &any;
=20
-	ret =3D hx509_ca_tbs_set_spki(hxctx, tbs, &spki);
+	ret =3D hx509_ca_tbs_set_spki(context->hx509ctx, tbs, &spki);
 	der_free_oid(&spki.algorithm.algorithm);
 	if (ret)
 	    goto out;
@@ -227,21 +219,21 @@
 	hx509_certs certs;
 	hx509_cert template;
=20
-	ret =3D hx509_certs_init(hxctx, config->kx509_template, 0,
+	ret =3D hx509_certs_init(context->hx509ctx, config->kx509_template, 0,
 			       NULL, &certs);
 	if (ret) {
 	    kdc_log(context, config, 0, "Failed to load template %s",
 		    config->kx509_template);
 	    goto out;
 	}
-	ret =3D hx509_get_one_cert(hxctx, certs, &template);
+	ret =3D hx509_get_one_cert(context->hx509ctx, certs, &template);
 	hx509_certs_free(&certs);
 	if (ret) {
 	    kdc_log(context, config, 0, "Failed to find template in %s",
 		    config->kx509_template);
 	    goto out;
 	}
-	ret =3D hx509_ca_tbs_set_template(hxctx, tbs,=20
+	ret =3D hx509_ca_tbs_set_template(context->hx509ctx, tbs,
 					HX509_CA_TEMPLATE_SUBJECT|
 					HX509_CA_TEMPLATE_KU|
 					HX509_CA_TEMPLATE_EKU,
@@ -251,24 +243,22 @@
 	    goto out;
     }
=20
-    hx509_ca_tbs_set_notAfter(hxctx, tbs, endtime);
+    hx509_ca_tbs_set_notAfter(context->hx509ctx, tbs, endtime);
=20
-    hx509_ca_tbs_subject_expand(hxctx, tbs, env);
+    hx509_ca_tbs_subject_expand(context->hx509ctx, tbs, env);
     hx509_env_free(&env);
=20
-    ret =3D hx509_ca_sign(hxctx, tbs, signer, &cert);
+    ret =3D hx509_ca_sign(context->hx509ctx, tbs, signer, &cert);
     hx509_cert_free(signer);
     if (ret)
 	goto out;
=20
     hx509_ca_tbs_free(&tbs);
=20
-    ret =3D hx509_cert_binary(hxctx, cert, certificate);
+    ret =3D hx509_cert_binary(context->hx509ctx, cert, certificate);
     hx509_cert_free(cert);
     if (ret)
 	goto out;
-		     =20
-    hx509_context_free(&hxctx);
=20
     return 0;
 out:
@@ -278,9 +268,7 @@
 	hx509_ca_tbs_free(&tbs);
     if (signer)
 	hx509_cert_free(signer);
-    if (hxctx)
-	hx509_context_free(&hxctx);
-    krb5_set_error_string(context, "cert creation failed");
+    krb5_set_error_message(context, ret, "cert creation failed");
     return ret;
 }
=20
@@ -289,9 +277,9 @@
  */
=20
 krb5_error_code
-_kdc_do_kx509(krb5_context context,=20
+_kdc_do_kx509(krb5_context context,
 	      krb5_kdc_configuration *config,
-	      const Kx509Request *req, krb5_data *reply,
+	      const struct Kx509Request *req, krb5_data *reply,
 	      const char *from, struct sockaddr *addr)
 {
     krb5_error_code ret;
@@ -309,7 +297,7 @@
     memset(&rep, 0, sizeof(rep));
=20
     if(!config->enable_kx509) {
-	kdc_log(context, config, 0,=20
+	kdc_log(context, config, 0,
 		"Rejected kx509 request (disabled) from %s", from);
 	return KRB5KDC_ERR_POLICY;
     }
@@ -322,7 +310,7 @@
 	goto out;
     }
=20
-    ret =3D krb5_rd_req(context,=20
+    ret =3D krb5_rd_req(context,
 		      &ac,
 		      &req->authenticator,
 		      NULL,
@@ -339,7 +327,7 @@
     ret =3D krb5_unparse_name(context, cprincipal, &cname);
     if (ret)
 	goto out;
-   =20
+
     /* verify server principal */
=20
     ret =3D krb5_sname_to_principal(context, NULL, "kca_service",
@@ -357,20 +345,36 @@
 	ret =3D krb5_principal_compare(context, sprincipal, principal);
 	krb5_free_principal(context, principal);
 	if (ret !=3D TRUE) {
+	    char *expected, *used;
+
+	    ret =3D krb5_unparse_name(context, sprincipal, &expected);
+	    if (ret)
+		goto out;
+	    ret =3D krb5_unparse_name(context, principal, &used);
+	    if (ret) {
+		krb5_xfree(expected);
+		goto out;
+	    }
+
 	    ret =3D KRB5KDC_ERR_SERVER_NOMATCH;
-	    krb5_set_error_string(context,=20
-				  "User %s used wrong Kx509 service principal",
-				  cname);
+	    krb5_set_error_message(context, ret,
+				   "User %s used wrong Kx509 service "
+				   "principal, expected: %s, used %s",
+				   cname, expected, used);
+	    krb5_xfree(expected);
+	    krb5_xfree(used);
 	    goto out;
 	}
     }
-   =20
+
     ret =3D krb5_auth_con_getkey(context, ac, &key);
-    if (ret || key =3D=3D NULL) {
-	krb5_set_error_string(context, "Kx509 can't get session key");
+    if (ret =3D=3D 0 && key =3D=3D NULL)
+	ret =3D KRB5KDC_ERR_NULL_KEY;
+    if (ret) {
+	krb5_set_error_message(context, ret, "Kx509 can't get session key");
 	goto out;
     }
-   =20
+
     ret =3D verify_req_hash(context, req, key);
     if (ret)
 	goto out;
@@ -385,8 +389,10 @@
 	if (ret)
 	    goto out;
 	free_RSAPublicKey(&key);
-	if (size !=3D req->pk_key.length)
-	    ;
+	if (size !=3D req->pk_key.length) {
+	    ret =3D ASN1_EXTRA_DATA;
+	    goto out;
+	}
     }
=20
     ALLOC(rep.certificate);
@@ -398,7 +404,7 @@
 	goto out;
     krb5_data_zero(rep.hash);
=20
-    ret =3D build_certificate(context, config, &req->pk_key,=20
+    ret =3D build_certificate(context, config, &req->pk_key,
 			    krb5_ticket_get_endtime(context, ticket),
 			    cprincipal, rep.certificate);
     if (ret)
@@ -418,7 +424,7 @@
 	ASN1_MALLOC_ENCODE(Kx509Response, data.data, data.length, &rep,
 			   &size, ret);
 	if (ret) {
-	    krb5_set_error_string(context, "Failed to encode kx509 reply");
+	    krb5_set_error_message(context, ret, "Failed to encode kx509 reply");
 	    goto out;
 	}
 	if (size !=3D data.length)
@@ -458,3 +464,5 @@
=20
     return 0;
 }
+
+#endif /* KX509 */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/log.c
--- a/head/crypto/heimdal/kdc/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,63 +1,67 @@
 /*
- * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
-RCSID("$Id: log.c 22254 2007-12-09 06:01:05Z lha $");
=20
 void
-kdc_openlog(krb5_context context,=20
+kdc_openlog(krb5_context context,
+	    const char *service,
 	    krb5_kdc_configuration *config)
 {
     char **s =3D NULL, **p;
     krb5_initlog(context, "kdc", &config->logf);
-    s =3D krb5_config_get_strings(context, NULL, "kdc", "logging", NULL);
+    s =3D krb5_config_get_strings(context, NULL, service, "logging", NULL);
     if(s =3D=3D NULL)
-	s =3D krb5_config_get_strings(context, NULL, "logging", "kdc", NULL);
+	s =3D krb5_config_get_strings(context, NULL, "logging", service, NULL);
     if(s){
 	for(p =3D s; *p; p++)
 	    krb5_addlog_dest(context, config->logf, *p);
 	krb5_config_free_strings(s);
     }else {
-	char *s;
-	asprintf(&s, "0-1/FILE:%s/%s", hdb_db_dir(context), KDC_LOG_FILE);
-	krb5_addlog_dest(context, config->logf, s);
-	free(s);
+	char *ss;
+	if (asprintf(&ss, "0-1/FILE:%s/%s", hdb_db_dir(context),
+	    KDC_LOG_FILE) < 0)
+	    err(1, NULL);
+	krb5_addlog_dest(context, config->logf, ss);
+	free(ss);
     }
     krb5_set_warn_dest(context, config->logf);
 }
=20
 char*
-kdc_log_msg_va(krb5_context context,=20
+kdc_log_msg_va(krb5_context context,
 	       krb5_kdc_configuration *config,
 	       int level, const char *fmt, va_list ap)
 {
@@ -67,7 +71,7 @@
 }
=20
 char*
-kdc_log_msg(krb5_context context,=20
+kdc_log_msg(krb5_context context,
 	    krb5_kdc_configuration *config,
 	    int level, const char *fmt, ...)
 {
@@ -80,7 +84,7 @@
 }
=20
 void
-kdc_log(krb5_context context,=20
+kdc_log(krb5_context context,
 	krb5_kdc_configuration *config,
 	int level, const char *fmt, ...)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/main.c
--- a/head/crypto/heimdal/kdc/main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,36 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
@@ -36,11 +38,15 @@
 #include <util.h>
 #endif
=20
-RCSID("$Id: main.c 20454 2007-04-19 20:21:51Z lha $");
+#ifdef HAVE_CAPNG
+#include <cap-ng.h>
+#endif
=20
 sig_atomic_t exit_flag =3D 0;
=20
+#ifdef SUPPORT_DETACH
 int detach_from_console =3D -1;
+#endif
=20
 static RETSIGTYPE
 sigterm(int sig)
@@ -48,6 +54,54 @@
     exit_flag =3D sig;
 }
=20
+/*
+ * Allow dropping root bit, since heimdal reopens the database all the
+ * time the database needs to be owned by the user you are switched
+ * too. A better solution is to split the kdc in to more processes and
+ * run the network facing part with very low privilege.
+ */
+
+static void
+switch_environment(void)
+{
+#ifdef HAVE_GETEUID
+    if ((runas_string || chroot_string) && geteuid() !=3D 0)
+	errx(1, "no running as root, can't switch user/chroot");
+
+    if (chroot_string && chroot(chroot_string) !=3D 0)
+	errx(1, "chroot(%s)", "chroot_string failed");
+
+    if (runas_string) {
+	struct passwd *pw;
+
+	pw =3D getpwnam(runas_string);
+	if (pw =3D=3D NULL)
+	    errx(1, "unknown user %s", runas_string);
+
+	if (initgroups(pw->pw_name, pw->pw_gid) < 0)
+	    err(1, "initgroups failed");
+
+#ifndef HAVE_CAPNG
+	if (setgid(pw->pw_gid) < 0)
+	    err(1, "setgid(%s) failed", runas_string);
+
+	if (setuid(pw->pw_uid) < 0)
+	    err(1, "setuid(%s)", runas_string);
+#else
+	capng_clear (CAPNG_EFFECTIVE | CAPNG_PERMITTED);
+	if (capng_updatev (CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED,
+	                   CAP_NET_BIND_SERVICE, CAP_SETPCAP, -1) < 0)
+	    err(1, "capng_updateev");
+
+	if (capng_change_id(pw->pw_uid, pw->pw_gid,
+	                    CAPNG_CLEAR_BOUNDING) < 0)
+	    err(1, "capng_change_id(%s)", runas_string);
+#endif
+    }
+#endif
+}
+
+
 int
 main(int argc, char **argv)
 {
@@ -56,7 +110,7 @@
     krb5_kdc_configuration *config;
=20
     setprogname(argv[0]);
-   =20
+
     ret =3D krb5_init_context(&context);
     if (ret =3D=3D KRB5_CONFIG_BADFORMAT)
 	errx (1, "krb5_init_context failed to parse configuration file");
@@ -79,20 +133,36 @@
=20
 	sigaction(SIGINT, &sa, NULL);
 	sigaction(SIGTERM, &sa, NULL);
+#ifdef SIGXCPU
 	sigaction(SIGXCPU, &sa, NULL);
+#endif
=20
 	sa.sa_handler =3D SIG_IGN;
+#ifdef SIGPIPE
 	sigaction(SIGPIPE, &sa, NULL);
+#endif
     }
 #else
     signal(SIGINT, sigterm);
     signal(SIGTERM, sigterm);
+#ifdef SIGXCPU
     signal(SIGXCPU, sigterm);
+#endif
+#ifdef SIGPIPE
     signal(SIGPIPE, SIG_IGN);
 #endif
+#endif
+#ifdef SUPPORT_DETACH
     if (detach_from_console)
 	daemon(0, 0);
+#endif
+#ifdef __APPLE__
+    bonjour_announce(context, config);
+#endif
     pidfile(NULL);
+
+    switch_environment();
+
     loop(context, config);
     krb5_free_context(context);
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/misc.c
--- a/head/crypto/heimdal/kdc/misc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/misc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: misc.c 21106 2007-06-18 10:18:11Z lha $");
-
 struct timeval _kdc_now;
=20
 krb5_error_code
@@ -42,31 +40,66 @@
 	      krb5_kdc_configuration *config,
 	      krb5_const_principal principal,
 	      unsigned flags,
+	      krb5uint32 *kvno_ptr,
 	      HDB **db,
 	      hdb_entry_ex **h)
 {
     hdb_entry_ex *ent;
-    krb5_error_code ret;
+    krb5_error_code ret =3D HDB_ERR_NOENTRY;
     int i;
+    unsigned kvno =3D 0;
+
+    if (kvno_ptr) {
+	    kvno =3D *kvno_ptr;
+	    flags |=3D HDB_F_KVNO_SPECIFIED;
+    }
=20
     ent =3D calloc (1, sizeof (*ent));
     if (ent =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
=20
     for(i =3D 0; i < config->num_db; i++) {
+	krb5_principal enterprise_principal =3D NULL;
+	if (!(config->db[i]->hdb_capability_flags & HDB_CAP_F_HANDLE_ENTERPRISE_P=
RINCIPAL)
+	    && principal->name.name_type =3D=3D KRB5_NT_ENTERPRISE_PRINCIPAL) {
+	    if (principal->name.name_string.len !=3D 1) {
+		ret =3D KRB5_PARSE_MALFORMED;
+		krb5_set_error_message(context, ret,
+				       "malformed request: "
+				       "enterprise name with %d name components",
+				       principal->name.name_string.len);
+		free(ent);
+		return ret;
+	    }
+	    ret =3D krb5_parse_name(context, principal->name.name_string.val[0],
+				  &enterprise_principal);
+	    if (ret) {
+		free(ent);
+		return ret;
+	    }
+
+	    principal =3D enterprise_principal;
+	}
+
 	ret =3D config->db[i]->hdb_open(context, config->db[i], O_RDONLY, 0);
 	if (ret) {
-	    kdc_log(context, config, 0, "Failed to open database: %s",=20
-		    krb5_get_err_text(context, ret));
+	    const char *msg =3D krb5_get_error_message(context, ret);
+	    kdc_log(context, config, 0, "Failed to open database: %s", msg);
+	    krb5_free_error_message(context, msg);
 	    continue;
 	}
-	ret =3D config->db[i]->hdb_fetch(context,=20
-				       config->db[i],
-				       principal,
-				       flags | HDB_F_DECRYPT,
-				       ent);
+
+	ret =3D config->db[i]->hdb_fetch_kvno(context,
+					    config->db[i],
+					    principal,
+					    flags | HDB_F_DECRYPT,
+					    kvno,
+					    ent);
+
+	krb5_free_principal(context, enterprise_principal);
+
 	config->db[i]->hdb_close(context, config->db[i]);
 	if(ret =3D=3D 0) {
 	    if (db)
@@ -76,8 +109,9 @@
 	}
     }
     free(ent);
-    krb5_set_error_string(context, "no such entry found in hdb");
-    return  HDB_ERR_NOENTRY;
+    krb5_set_error_message(context, ret,
+			   "no such entry found in hdb");
+    return ret;
 }
=20
 void
@@ -100,23 +134,41 @@
 		       krb5_enctype *enctype,
 		       Key **key)
 {
-    const krb5_enctype *p;
     krb5_error_code ret;
     int i;
=20
-    p =3D krb5_kerberos_enctypes(context);
+    if (config->use_strongest_server_key) {
+	const krb5_enctype *p =3D krb5_kerberos_enctypes(context);
=20
-    for (i =3D 0; p[i] !=3D ETYPE_NULL; i++) {
-	if (krb5_enctype_valid(context, p[i]) !=3D 0)
-	    continue;
-	ret =3D hdb_enctype2key(context, &h->entry, p[i], key);
-	if (ret =3D=3D 0) {
-	    *enctype =3D p[i];
+	for (i =3D 0; p[i] !=3D ETYPE_NULL; i++) {
+	    if (krb5_enctype_valid(context, p[i]) !=3D 0)
+		continue;
+	    ret =3D hdb_enctype2key(context, &h->entry, p[i], key);
+	    if (ret !=3D 0)
+		continue;
+	    if (enctype !=3D NULL)
+		*enctype =3D p[i];
+	    return 0;
+	}
+    } else {
+	*key =3D NULL;
+
+	for (i =3D 0; i < h->entry.keys.len; i++) {
+	    if (krb5_enctype_valid(context, h->entry.keys.val[i].key.keytype)
+		!=3D 0)
+		continue;
+	    ret =3D hdb_enctype2key(context, &h->entry,
+		h->entry.keys.val[i].key.keytype, key);
+	    if (ret !=3D 0)
+		continue;
+	    if (enctype !=3D NULL)
+		*enctype =3D (*key)->key.keytype;
 	    return 0;
 	}
     }
=20
-    krb5_set_error_string(context, "No valid kerberos key found for %s", n=
ame);
-    return EINVAL;
+    krb5_set_error_message(context, EINVAL,
+			   "No valid kerberos key found for %s", name);
+    return EINVAL; /* XXX */
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/mit_dump.c
--- a/head/crypto/heimdal/kdc/mit_dump.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/mit_dump.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,8 +33,6 @@
=20
 #include "hprop.h"
=20
-RCSID("$Id: mit_dump.c 21745 2007-07-31 16:11:25Z lha $");
-
 /*
 can have any number of princ stanzas.
 format is as follows (only \n indicates newlines)
@@ -42,13 +40,13 @@
 %d\t (strlen of principal e.g. shadow/foo at ANDREW.CMU.EDU)
 %d\t (number of tl_data)
 %d\t (number of key data, e.g. how many keys for this user)
-%d\t (extra data length)=20
+%d\t (extra data length)
 %s\t (principal name)
 %d\t (attributes)
 %d\t (max lifetime, seconds)
 %d\t (max renewable life, seconds)
 %d\t (expiration, seconds since epoch or 2145830400 for never)
-%d\t (password expiration, seconds, 0 for never)=20
+%d\t (password expiration, seconds, 0 for never)
 %d\t (last successful auth, seconds since epoch)
 %d\t (last failed auth, per above)
 %d\t (failed auth count)
@@ -67,7 +65,7 @@
       %02x (key data contents[element n])
     except if key_data length is 0
       %d (always -1)
-    \t   =20
+    \t
 foreach extra data length 0 to length - 1
   %02x (extra data part)
 unless no extra data
@@ -79,7 +77,7 @@
 static int
 hex_to_octet_string(const char *ptr, krb5_data *data)
 {
-    int i;
+    size_t i;
     unsigned int v;
     for(i =3D 0; i < data->length; i++) {
 	if(sscanf(ptr + 2 * i, "%02x", &v) !=3D 1)
@@ -137,7 +135,7 @@
     /* DUP_SKEY */
     flags->invalid =3D	       !!(attr & KRB5_KDB_DISALLOW_ALL_TIX);
     flags->require_preauth =3D   !!(attr & KRB5_KDB_REQUIRES_PRE_AUTH);
-    /* HW_AUTH */
+    flags->require_hwauth =3D    !!(attr & KRB5_KDB_REQUIRES_HW_AUTH);
     flags->server =3D		!(attr & KRB5_KDB_DISALLOW_SVR);
     flags->change_pw =3D 	       !!(attr & KRB5_KDB_PWCHANGE_SERVICE);
     flags->client =3D	        1; /* XXX */
@@ -167,9 +165,9 @@
     case KRB5_KDB_SALTTYPE_NOREALM:
     {
 	size_t len;
-	int i;
+	size_t i;
 	char *p;
-	   =20
+
 	len =3D 0;
 	for (i =3D 0; i < ent->principal->name.name_string.len; ++i)
 	    len +=3D strlen(ent->principal->name.name_string.val[i]);
@@ -189,8 +187,8 @@
     }
     case KRB5_KDB_SALTTYPE_ONLYREALM:
 	krb5_data_free(&salt->salt);
-	ret =3D krb5_data_copy(&salt->salt,=20
-			     ent->principal->realm,=20
+	ret =3D krb5_data_copy(&salt->salt,
+			     ent->principal->realm,
 			     strlen(ent->principal->realm));
 	if(ret)
 	    return ret;
@@ -201,8 +199,8 @@
 	break;
     case KRB5_KDB_SALTTYPE_AFS3:
 	krb5_data_free(&salt->salt);
-	ret =3D krb5_data_copy(&salt->salt,=20
-		       ent->principal->realm,=20
+	ret =3D krb5_data_copy(&salt->salt,
+		       ent->principal->realm,
 		       strlen(ent->principal->realm));
 	if(ret)
 	    return ret;
@@ -228,7 +226,7 @@
     f =3D fopen(file, "r");
     if(f =3D=3D NULL)
 	return errno;
-   =20
+
     while(fgets(line, sizeof(line), f)) {
 	char *p =3D line, *q;
=20
@@ -236,7 +234,7 @@
=20
 	int num_tl_data;
 	int num_key_data;
-	int extra_data_length;
+	int high_kvno;
 	int attributes;
=20
 	int tmp;
@@ -257,8 +255,11 @@
 	    q =3D nexttoken(&p); /* x.0 */
 	    if(sscanf(q, "%d", &major) !=3D 1)
 		errx(1, "line %d: unknown version", lineno);
-	    if(major !=3D 4)
-		errx(1, "unknown dump file format, got %d, expected 4", major);
+	    if(major !=3D 4 && major !=3D 5 && major !=3D 6)
+		errx(1, "unknown dump file format, got %d, expected 4-6",
+		     major);
+	    continue;
+	} else if(strcmp(q, "policy") =3D=3D 0) {
 	    continue;
 	} else if(strcmp(q, "princ") !=3D 0) {
 	    warnx("line %d: not a principal", lineno);
@@ -269,10 +270,10 @@
 	    warnx("line %d: bad base length %d !=3D 38", lineno, tmp);
 	    continue;
 	}
-	q =3D nexttoken(&p); /* length of principal */
+	nexttoken(&p); /* length of principal */
 	num_tl_data =3D getint(&p); /* number of tl-data */
 	num_key_data =3D getint(&p); /* number of key-data */
-	extra_data_length =3D getint(&p);  /* length of extra data */
+	getint(&p);  /* length of extra data */
 	q =3D nexttoken(&p); /* principal name */
 	krb5_parse_name(pd->context, q, &ent.entry.principal);
 	attributes =3D getint(&p); /* attributes */
@@ -297,9 +298,9 @@
 	    ALLOC(ent.entry.pw_end);
 	    *ent.entry.pw_end =3D tmp;
 	}
-	q =3D nexttoken(&p); /* last auth */
-	q =3D nexttoken(&p); /* last failed auth */
-	q =3D nexttoken(&p); /* fail auth count */
+	nexttoken(&p); /* last auth */
+	nexttoken(&p); /* last failed auth */
+	nexttoken(&p); /* fail auth count */
 	for(i =3D 0; i < num_tl_data; i++) {
 	    unsigned long val;
 	    int tl_type, tl_length;
@@ -312,6 +313,20 @@
 #define mit_KRB5_TL_LAST_PWD_CHANGE	1
 #define mit_KRB5_TL_MOD_PRINC		2
 	    switch(tl_type) {
+	    case mit_KRB5_TL_LAST_PWD_CHANGE:
+		buf =3D malloc(tl_length);
+		if (buf =3D=3D NULL)
+		    errx(ENOMEM, "malloc");
+		getdata(&p, buf, tl_length); /* data itself */
+		val =3D buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
+		free(buf);
+		ALLOC(ent.entry.extensions);
+		ALLOC_SEQ(ent.entry.extensions, 1);
+		ent.entry.extensions->val[0].mandatory =3D 0;
+		ent.entry.extensions->val[0].data.element
+		    =3D choice_HDB_extension_data_last_pw_change;
+		ent.entry.extensions->val[0].data.u.last_pw_change =3D val;
+		break;
 	    case mit_KRB5_TL_MOD_PRINC:
 		buf =3D malloc(tl_length);
 		if (buf =3D=3D NULL)
@@ -319,6 +334,9 @@
 		getdata(&p, buf, tl_length); /* data itself */
 		val =3D buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
 		ret =3D krb5_parse_name(pd->context, (char *)buf + 4, &princ);
+		if (ret)
+		    krb5_err(pd->context, 1, ret,
+			     "parse_name: %s", (char *)buf + 4);
 		free(buf);
 		ALLOC(ent.entry.modified_by);
 		ent.entry.modified_by->time =3D val;
@@ -330,14 +348,40 @@
 	    }
 	}
 	ALLOC_SEQ(&ent.entry.keys, num_key_data);
+	high_kvno =3D -1;
 	for(i =3D 0; i < num_key_data; i++) {
 	    int key_versions;
+	    int kvno;
 	    key_versions =3D getint(&p); /* key data version */
-	    ent.entry.kvno =3D getint(&p); /* XXX kvno */
-	   =20
+	    kvno =3D getint(&p);
+
+	    /*
+	     * An MIT dump file may contain multiple sets of keys with
+	     * different kvnos.  Since the Heimdal database can only represent
+	     * one kvno per principal, we only want the highest set.  Assume
+	     * that set will be given first, and discard all keys with lower
+	     * kvnos.
+	     */
+	    if (kvno > high_kvno && high_kvno !=3D -1)
+		errx(1, "line %d: high kvno keys given after low kvno keys",
+		     lineno);
+	    else if (kvno < high_kvno) {
+		nexttoken(&p); /* key type */
+		nexttoken(&p); /* key length */
+		nexttoken(&p); /* key */
+		if (key_versions > 1) {
+		    nexttoken(&p); /* salt type */
+		    nexttoken(&p); /* salt length */
+		    nexttoken(&p); /* salt */
+		}
+		ent.entry.keys.len--;
+		continue;
+	    }
+	    ent.entry.kvno =3D kvno;
+	    high_kvno =3D kvno;
 	    ALLOC(ent.entry.keys.val[i].mkvno);
-	    *ent.entry.keys.val[i].mkvno =3D 0;
-	   =20
+	    *ent.entry.keys.val[i].mkvno =3D 1;
+
 	    /* key version 0 -- actual key */
 	    ent.entry.keys.val[i].key.keytype =3D getint(&p); /* key type */
 	    tmp =3D getint(&p); /* key length */
@@ -360,12 +404,12 @@
 		} else {
 		    ent.entry.keys.val[i].salt->salt.length =3D 0;
 		    ent.entry.keys.val[i].salt->salt.data =3D NULL;
-		    tmp =3D getint(&p);	/* -1, if no data. */
+		    getint(&p);	/* -1, if no data. */
 		}
 		fix_salt(pd->context, &ent.entry, i);
 	    }
 	}
-	q =3D nexttoken(&p); /* extra data */
+	nexttoken(&p); /* extra data */
 	v5_prop(pd->context, NULL, &ent, arg);
     }
     fclose(f);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/pkinit.c
--- a/head/crypto/heimdal/kdc/pkinit.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/pkinit.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 2003 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: pkinit.c 22243 2007-12-08 23:39:30Z lha $");
-
 #ifdef PKINIT
=20
 #include <heim_asn1.h>
@@ -45,31 +45,28 @@
 #include <hx509.h>
 #include "crypto-headers.h"
=20
-/* XXX copied from lib/krb5/pkinit.c */
-struct krb5_pk_identity {
-    hx509_context hx509ctx;
-    hx509_verify_ctx verify_ctx;
-    hx509_certs certs;
-    hx509_certs anchors;
-    hx509_certs certpool;
-    hx509_revoke_ctx revoke;
-};
-
-enum pkinit_type {
-    PKINIT_COMPAT_WIN2K =3D 1,
-    PKINIT_COMPAT_27 =3D 3
-};
-
 struct pk_client_params {
-    enum pkinit_type type;
-    BIGNUM *dh_public_key;
+    enum krb5_pk_type type;
+    enum { USE_RSA, USE_DH, USE_ECDH } keyex;
+    union {
+	struct {
+	    BIGNUM *public_key;
+	    DH *key;
+	} dh;
+#ifdef HAVE_OPENSSL
+	struct {
+	    EC_KEY *public_key;
+	    EC_KEY *key;
+	} ecdh;
+#endif
+    } u;
     hx509_cert cert;
     unsigned nonce;
-    DH *dh;
     EncryptionKey reply_key;
     char *dh_group_name;
     hx509_peer_info peer;
     hx509_certs client_anchors;
+    hx509_verify_ctx verify_ctx;
 };
=20
 struct pk_principal_mapping {
@@ -105,7 +102,7 @@
=20
     /* XXX cusec */
     if (a->ctime =3D=3D 0 || abs(a->ctime - now) > context->max_skew) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return KRB5KRB_AP_ERR_SKEW;
     }
     return 0;
@@ -119,7 +116,7 @@
     u_char *buf =3D NULL;
     size_t buf_size;
     krb5_error_code ret;
-    size_t len;
+    size_t len =3D 0;
     krb5_timestamp now;
     Checksum checksum;
=20
@@ -127,13 +124,13 @@
=20
     /* XXX cusec */
     if (a->ctime =3D=3D 0 || abs(a->ctime - now) > context->max_skew) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return KRB5KRB_AP_ERR_SKEW;
     }
=20
     ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, &req->req_body, &len, =
ret);
     if (ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
     if (buf_size !=3D len)
@@ -148,18 +145,18 @@
 			       &checksum);
     free(buf);
     if (ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
-=09
+
     if (a->paChecksum =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	ret =3D KRB5_KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
 	goto out;
     }
=20
     if (der_heim_octet_string_cmp(a->paChecksum, &checksum.checksum) !=3D =
0) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	ret =3D KRB5KRB_ERR_GENERIC;
     }
=20
@@ -170,29 +167,43 @@
 }
=20
 void
-_kdc_pk_free_client_param(krb5_context context,=20
-			  pk_client_params *client_params)
+_kdc_pk_free_client_param(krb5_context context, pk_client_params *cp)
 {
-    if (client_params->cert)
-	hx509_cert_free(client_params->cert);
-    if (client_params->dh)
-	DH_free(client_params->dh);
-    if (client_params->dh_public_key)
-	BN_free(client_params->dh_public_key);
-    krb5_free_keyblock_contents(context, &client_params->reply_key);
-    if (client_params->dh_group_name)
-	free(client_params->dh_group_name);
-    if (client_params->peer)
-	hx509_peer_info_free(client_params->peer);
-    if (client_params->client_anchors)
-	hx509_certs_free(&client_params->client_anchors);
-    memset(client_params, 0, sizeof(*client_params));
-    free(client_params);
+    if (cp =3D=3D NULL)
+        return;
+    if (cp->cert)
+	hx509_cert_free(cp->cert);
+    if (cp->verify_ctx)
+	hx509_verify_destroy_ctx(cp->verify_ctx);
+    if (cp->keyex =3D=3D USE_DH) {
+	if (cp->u.dh.key)
+	    DH_free(cp->u.dh.key);
+	if (cp->u.dh.public_key)
+	    BN_free(cp->u.dh.public_key);
+    }
+#ifdef HAVE_OPENSSL
+    if (cp->keyex =3D=3D USE_ECDH) {
+	if (cp->u.ecdh.key)
+	    EC_KEY_free(cp->u.ecdh.key);
+	if (cp->u.ecdh.public_key)
+	    EC_KEY_free(cp->u.ecdh.public_key);
+    }
+#endif
+    krb5_free_keyblock_contents(context, &cp->reply_key);
+    if (cp->dh_group_name)
+	free(cp->dh_group_name);
+    if (cp->peer)
+	hx509_peer_info_free(cp->peer);
+    if (cp->client_anchors)
+	hx509_certs_free(&cp->client_anchors);
+    memset(cp, 0, sizeof(*cp));
+    free(cp);
 }
=20
 static krb5_error_code
-generate_dh_keyblock(krb5_context context, pk_client_params *client_params,
-                     krb5_enctype enctype, krb5_keyblock *reply_key)
+generate_dh_keyblock(krb5_context context,
+		     pk_client_params *client_params,
+                     krb5_enctype enctype)
 {
     unsigned char *dh_gen_key =3D NULL;
     krb5_keyblock key;
@@ -201,36 +212,84 @@
=20
     memset(&key, 0, sizeof(key));
=20
-    if (!DH_generate_key(client_params->dh)) {
-	krb5_set_error_string(context, "Can't generate Diffie-Hellman keys");
+    if (client_params->keyex =3D=3D USE_DH) {
+
+	if (client_params->u.dh.public_key =3D=3D NULL) {
+	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret, "public_key");
+	    goto out;
+	}
+
+	if (!DH_generate_key(client_params->u.dh.key)) {
+	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   "Can't generate Diffie-Hellman keys");
+	    goto out;
+	}
+
+	size =3D DH_size(client_params->u.dh.key);
+
+	dh_gen_key =3D malloc(size);
+	if (dh_gen_key =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
+	    goto out;
+	}
+
+	dh_gen_keylen =3D DH_compute_key(dh_gen_key,client_params->u.dh.public_ke=
y, client_params->u.dh.key);
+	if (dh_gen_keylen =3D=3D (size_t)-1) {
+	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   "Can't compute Diffie-Hellman key");
+	    goto out;
+	}
+	if (dh_gen_keylen < size) {
+	    size -=3D dh_gen_keylen;
+	    memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen);
+	    memset(dh_gen_key, 0, size);
+	}
+
+	ret =3D 0;
+#ifdef HAVE_OPENSSL
+    } else if (client_params->keyex =3D=3D USE_ECDH) {
+
+	if (client_params->u.ecdh.public_key =3D=3D NULL) {
+	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret, "public_key");
+	    goto out;
+	}
+
+	client_params->u.ecdh.key =3D EC_KEY_new();
+	if (client_params->u.ecdh.key =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+	EC_KEY_set_group(client_params->u.ecdh.key,
+			 EC_KEY_get0_group(client_params->u.ecdh.public_key));
+
+	if (EC_KEY_generate_key(client_params->u.ecdh.key) !=3D 1) {
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+
+	size =3D (EC_GROUP_get_degree(EC_KEY_get0_group(client_params->u.ecdh.key=
)) + 7) / 8;
+	dh_gen_key =3D malloc(size);
+	if (dh_gen_key =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
+	    goto out;
+	}
+
+	dh_gen_keylen =3D ECDH_compute_key(dh_gen_key, size,
+					 EC_KEY_get0_public_key(client_params->u.ecdh.public_key),
+					 client_params->u.ecdh.key, NULL);
+
+#endif /* HAVE_OPENSSL */
+    } else {
 	ret =3D KRB5KRB_ERR_GENERIC;
-	goto out;
-    }
-    if (client_params->dh_public_key =3D=3D NULL) {
-	krb5_set_error_string(context, "dh_public_key");
-	ret =3D KRB5KRB_ERR_GENERIC;
-	goto out;
-    }
-
-    dh_gen_keylen =3D DH_size(client_params->dh);
-    size =3D BN_num_bytes(client_params->dh->p);
-    if (size < dh_gen_keylen)
-	size =3D dh_gen_keylen;
-
-    dh_gen_key =3D malloc(size);
-    if (dh_gen_key =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	ret =3D ENOMEM;
-	goto out;
-    }
-    memset(dh_gen_key, 0, size - dh_gen_keylen);
-
-    dh_gen_keylen =3D DH_compute_key(dh_gen_key + (size - dh_gen_keylen),
-				   client_params->dh_public_key,
-				   client_params->dh);
-    if (dh_gen_keylen =3D=3D -1) {
-	krb5_set_error_string(context, "Can't compute Diffie-Hellman key");
-	ret =3D KRB5KRB_ERR_GENERIC;
+	krb5_set_error_message(context, ret,
+			       "Diffie-Hellman not selected keys");
 	goto out;
     }
=20
@@ -238,7 +297,7 @@
 				   enctype,
 				   dh_gen_key, dh_gen_keylen,
 				   NULL, NULL,
-				   reply_key);
+				   &client_params->reply_key);
=20
  out:
     if (dh_gen_key)
@@ -256,7 +315,8 @@
=20
     bn =3D BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
     if (bn =3D=3D NULL) {
-	krb5_set_error_string(context, "PKINIT: parsing BN failed %s", field);
+	krb5_set_error_message(context, KRB5_BADMSGTYPE,
+			       "PKINIT: parsing BN failed %s", field);
 	return NULL;
     }
     BN_set_negative(bn, f->negative);
@@ -275,14 +335,17 @@
=20
     memset(&dhparam, 0, sizeof(dhparam));
=20
-    if (der_heim_oid_cmp(&dh_key_info->algorithm.algorithm, oid_id_dhpubli=
cnumber())) {
-	krb5_set_error_string(context,
-			      "PKINIT invalid oid in clientPublicValue");
-	return KRB5_BADMSGTYPE;
+    if ((dh_key_info->subjectPublicKey.length % 8) !=3D 0) {
+	ret =3D KRB5_BADMSGTYPE;
+	krb5_set_error_message(context, ret,
+			       "PKINIT: subjectPublicKey not aligned "
+			       "to 8 bit boundary");
+	goto out;
     }
=20
     if (dh_key_info->algorithm.parameters =3D=3D NULL) {
-	krb5_set_error_string(context, "PKINIT missing algorithm parameter "
+	krb5_set_error_message(context, KRB5_BADMSGTYPE,
+			       "PKINIT missing algorithm parameter "
 			      "in clientPublicValue");
 	return KRB5_BADMSGTYPE;
     }
@@ -292,20 +355,12 @@
 				  &dhparam,
 				  NULL);
     if (ret) {
-	krb5_set_error_string(context, "Can't decode algorithm "
-			      "parameters in clientPublicValue");
+	krb5_set_error_message(context, ret, "Can't decode algorithm "
+			       "parameters in clientPublicValue");
 	goto out;
     }
=20
-    if ((dh_key_info->subjectPublicKey.length % 8) !=3D 0) {
-	ret =3D KRB5_BADMSGTYPE;
-	krb5_set_error_string(context, "PKINIT: subjectPublicKey not aligned "
-			      "to 8 bit boundary");
-	goto out;
-    }
-
-
-    ret =3D _krb5_dh_group_ok(context, config->pkinit_dh_min_bits,=20
+    ret =3D _krb5_dh_group_ok(context, config->pkinit_dh_min_bits,
 			    &dhparam.p, &dhparam.g, &dhparam.q, moduli,
 			    &client_params->dh_group_name);
     if (ret) {
@@ -315,8 +370,8 @@
=20
     dh =3D DH_new();
     if (dh =3D=3D NULL) {
-	krb5_set_error_string(context, "Cannot create DH structure");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, "Cannot create DH structure");
 	goto out;
     }
     ret =3D KRB5_BADMSGTYPE;
@@ -339,22 +394,24 @@
 				 &glue,
 				 &size);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    return ret;
 	}
=20
-	client_params->dh_public_key =3D integer_to_BN(context,
-						     "subjectPublicKey",
-						     &glue);
+	client_params->u.dh.public_key =3D integer_to_BN(context,
+						       "subjectPublicKey",
+						       &glue);
 	der_free_heim_integer(&glue);
-	if (client_params->dh_public_key =3D=3D NULL)
+	if (client_params->u.dh.public_key =3D=3D NULL) {
+	    ret =3D KRB5_BADMSGTYPE;
 	    goto out;
+	}
     }
=20
-    client_params->dh =3D dh;
+    client_params->u.dh.key =3D dh;
     dh =3D NULL;
     ret =3D 0;
-   =20
+
  out:
     if (dh)
 	DH_free(dh);
@@ -362,60 +419,182 @@
     return ret;
 }
=20
+#ifdef HAVE_OPENSSL
+
+static krb5_error_code
+get_ecdh_param(krb5_context context,
+	       krb5_kdc_configuration *config,
+	       SubjectPublicKeyInfo *dh_key_info,
+	       pk_client_params *client_params)
+{
+    ECParameters ecp;
+    EC_KEY *public =3D NULL;
+    krb5_error_code ret;
+    const unsigned char *p;
+    size_t len;
+    int nid;
+
+    if (dh_key_info->algorithm.parameters =3D=3D NULL) {
+	krb5_set_error_message(context, KRB5_BADMSGTYPE,
+			       "PKINIT missing algorithm parameter "
+			       "in clientPublicValue");
+	return KRB5_BADMSGTYPE;
+    }
+
+    memset(&ecp, 0, sizeof(ecp));
+
+    ret =3D decode_ECParameters(dh_key_info->algorithm.parameters->data,
+			      dh_key_info->algorithm.parameters->length, &ecp, &len);
+    if (ret)
+	goto out;
+
+    if (ecp.element !=3D choice_ECParameters_namedCurve) {
+	ret =3D KRB5_BADMSGTYPE;
+	goto out;
+    }
+
+    if (der_heim_oid_cmp(&ecp.u.namedCurve, &asn1_oid_id_ec_group_secp256r=
1) =3D=3D 0)
+	nid =3D NID_X9_62_prime256v1;
+    else {
+	ret =3D KRB5_BADMSGTYPE;
+	goto out;
+    }
+
+    /* XXX verify group is ok */
+
+    public =3D EC_KEY_new_by_curve_name(nid);
+
+    p =3D dh_key_info->subjectPublicKey.data;
+    len =3D dh_key_info->subjectPublicKey.length / 8;
+    if (o2i_ECPublicKey(&public, &p, len) =3D=3D NULL) {
+	ret =3D KRB5_BADMSGTYPE;
+	krb5_set_error_message(context, ret,
+			       "PKINIT failed to decode ECDH key");
+	goto out;
+    }
+    client_params->u.ecdh.public_key =3D public;
+    public =3D NULL;
+
+ out:
+    if (public)
+	EC_KEY_free(public);
+    free_ECParameters(&ecp);
+    return ret;
+}
+
+#endif /* HAVE_OPENSSL */
+
 krb5_error_code
 _kdc_pk_rd_padata(krb5_context context,
 		  krb5_kdc_configuration *config,
 		  const KDC_REQ *req,
 		  const PA_DATA *pa,
+		  hdb_entry_ex *client,
 		  pk_client_params **ret_params)
 {
-    pk_client_params *client_params;
+    pk_client_params *cp;
     krb5_error_code ret;
     heim_oid eContentType =3D { 0, NULL }, contentInfoOid =3D { 0, NULL };
     krb5_data eContent =3D { 0, NULL };
     krb5_data signed_content =3D { 0, NULL };
     const char *type =3D "unknown type";
+    hx509_certs trust_anchors;
     int have_data =3D 0;
+    const HDB_Ext_PKINIT_cert *pc;
=20
     *ret_params =3D NULL;
-   =20
+
     if (!config->enable_pkinit) {
 	kdc_log(context, config, 0, "PK-INIT request but PK-INIT not enabled");
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return 0;
     }
=20
-    hx509_verify_set_time(kdc_identity->verify_ctx, _kdc_now.tv_sec);
-
-    client_params =3D calloc(1, sizeof(*client_params));
-    if (client_params =3D=3D NULL) {
-	krb5_clear_error_string(context);
+    cp =3D calloc(1, sizeof(*cp));
+    if (cp =3D=3D NULL) {
+	krb5_clear_error_message(context);
 	ret =3D ENOMEM;
 	goto out;
     }
=20
+    ret =3D hx509_certs_init(context->hx509ctx,
+			   "MEMORY:trust-anchors",
+			   0, NULL, &trust_anchors);
+    if (ret) {
+	krb5_set_error_message(context, ret, "failed to create trust anchors");
+	goto out;
+    }
+
+    ret =3D hx509_certs_merge(context->hx509ctx, trust_anchors,
+			    kdc_identity->anchors);
+    if (ret) {
+	hx509_certs_free(&trust_anchors);
+	krb5_set_error_message(context, ret, "failed to create verify context");
+	goto out;
+    }
+
+    /* Add any registered certificates for this client as trust anchors */
+    ret =3D hdb_entry_get_pkinit_cert(&client->entry, &pc);
+    if (ret =3D=3D 0 && pc !=3D NULL) {
+	hx509_cert cert;
+	unsigned int i;
+
+	for (i =3D 0; i < pc->len; i++) {
+	    ret =3D hx509_cert_init_data(context->hx509ctx,
+				       pc->val[i].cert.data,
+				       pc->val[i].cert.length,
+				       &cert);
+	    if (ret)
+		continue;
+	    hx509_certs_add(context->hx509ctx, trust_anchors, cert);
+	    hx509_cert_free(cert);
+	}
+    }
+
+    ret =3D hx509_verify_init_ctx(context->hx509ctx, &cp->verify_ctx);
+    if (ret) {
+	hx509_certs_free(&trust_anchors);
+	krb5_set_error_message(context, ret, "failed to create verify context");
+	goto out;
+    }
+
+    hx509_verify_set_time(cp->verify_ctx, kdc_time);
+    hx509_verify_attach_anchors(cp->verify_ctx, trust_anchors);
+    hx509_certs_free(&trust_anchors);
+
+    if (config->pkinit_allow_proxy_certs)
+	hx509_verify_set_proxy_certificate(cp->verify_ctx, 1);
+
     if (pa->padata_type =3D=3D KRB5_PADATA_PK_AS_REQ_WIN) {
 	PA_PK_AS_REQ_Win2k r;
=20
 	type =3D "PK-INIT-Win2k";
=20
+	if (req->req_body.kdc_options.request_anonymous) {
+	    ret =3D KRB5_KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED;
+	    krb5_set_error_message(context, ret,
+				   "Anon not supported in RSA mode");
+	    goto out;
+	}
+
 	ret =3D decode_PA_PK_AS_REQ_Win2k(pa->padata_value.data,
 					pa->padata_value.length,
 					&r,
 					NULL);
 	if (ret) {
-	    krb5_set_error_string(context, "Can't decode "
-				  "PK-AS-REQ-Win2k: %d", ret);
+	    krb5_set_error_message(context, ret, "Can't decode "
+				   "PK-AS-REQ-Win2k: %d", ret);
 	    goto out;
 	}
-=09
+
 	ret =3D hx509_cms_unwrap_ContentInfo(&r.signed_auth_pack,
 					   &contentInfoOid,
 					   &signed_content,
 					   &have_data);
 	free_PA_PK_AS_REQ_Win2k(&r);
 	if (ret) {
-	    krb5_set_error_string(context, "Can't decode PK-AS-REQ: %d", ret);
+	    krb5_set_error_message(context, ret,
+				   "Can't unwrap ContentInfo(win): %d", ret);
 	    goto out;
 	}
=20
@@ -429,25 +608,35 @@
 				  &r,
 				  NULL);
 	if (ret) {
-	    krb5_set_error_string(context, "Can't decode PK-AS-REQ: %d", ret);
+	    krb5_set_error_message(context, ret,
+				   "Can't decode PK-AS-REQ: %d", ret);
 	    goto out;
 	}
-=09
+
 	/* XXX look at r.kdcPkId */
 	if (r.trustedCertifiers) {
 	    ExternalPrincipalIdentifiers *edi =3D r.trustedCertifiers;
-	    unsigned int i;
+	    unsigned int i, maxedi;
=20
-	    ret =3D hx509_certs_init(kdc_identity->hx509ctx,
+	    ret =3D hx509_certs_init(context->hx509ctx,
 				   "MEMORY:client-anchors",
 				   0, NULL,
-				   &client_params->client_anchors);
+				   &cp->client_anchors);
 	    if (ret) {
-		krb5_set_error_string(context, "Can't allocate client anchors: %d", ret);
+		krb5_set_error_message(context, ret,
+				       "Can't allocate client anchors: %d",
+				       ret);
 		goto out;
=20
 	    }
-	    for (i =3D 0; i < edi->len; i++) {
+	    /*
+	     * If the client sent more then 10 EDI, don't bother
+	     * looking more then 10 of performance reasons.
+	     */
+	    maxedi =3D edi->len;
+	    if (maxedi > 10)
+		maxedi =3D 10;
+	    for (i =3D 0; i < maxedi; i++) {
 		IssuerAndSerialNumber iasn;
 		hx509_query *q;
 		hx509_cert cert;
@@ -456,35 +645,37 @@
 		if (edi->val[i].issuerAndSerialNumber =3D=3D NULL)
 		    continue;
=20
-		ret =3D hx509_query_alloc(kdc_identity->hx509ctx, &q);
+		ret =3D hx509_query_alloc(context->hx509ctx, &q);
 		if (ret) {
-		    krb5_set_error_string(context,=20
+		    krb5_set_error_message(context, ret,
 					  "Failed to allocate hx509_query");
 		    goto out;
 		}
-	=09
+
 		ret =3D decode_IssuerAndSerialNumber(edi->val[i].issuerAndSerialNumber->=
data,
 						   edi->val[i].issuerAndSerialNumber->length,
 						   &iasn,
 						   &size);
 		if (ret) {
-		    hx509_query_free(kdc_identity->hx509ctx, q);
+		    hx509_query_free(context->hx509ctx, q);
 		    continue;
 		}
 		ret =3D hx509_query_match_issuer_serial(q, &iasn.issuer, &iasn.serialNum=
ber);
 		free_IssuerAndSerialNumber(&iasn);
-		if (ret)
+		if (ret) {
+		    hx509_query_free(context->hx509ctx, q);
 		    continue;
+		}
=20
-		ret =3D hx509_certs_find(kdc_identity->hx509ctx,
+		ret =3D hx509_certs_find(context->hx509ctx,
 				       kdc_identity->certs,
 				       q,
 				       &cert);
-		hx509_query_free(kdc_identity->hx509ctx, q);
+		hx509_query_free(context->hx509ctx, q);
 		if (ret)
 		    continue;
-		hx509_certs_add(kdc_identity->hx509ctx,=20
-				client_params->client_anchors, cert);
+		hx509_certs_add(context->hx509ctx,
+				cp->client_anchors, cert);
 		hx509_cert_free(cert);
 	    }
 	}
@@ -495,36 +686,42 @@
 					   &have_data);
 	free_PA_PK_AS_REQ(&r);
 	if (ret) {
-	    krb5_set_error_string(context, "Can't unwrap ContentInfo: %d", ret);
+	    krb5_set_error_message(context, ret,
+				   "Can't unwrap ContentInfo: %d", ret);
 	    goto out;
 	}
=20
-    } else {=20
-	krb5_clear_error_string(context);
+    } else {
+	krb5_clear_error_message(context);
 	ret =3D KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
 	goto out;
     }
=20
-    ret =3D der_heim_oid_cmp(&contentInfoOid, oid_id_pkcs7_signedData());
+    ret =3D der_heim_oid_cmp(&contentInfoOid, &asn1_oid_id_pkcs7_signedDat=
a);
     if (ret !=3D 0) {
-	krb5_set_error_string(context, "PK-AS-REQ-Win2k invalid content "
-			      "type oid");
 	ret =3D KRB5KRB_ERR_GENERIC;
+	krb5_set_error_message(context, ret,
+			       "PK-AS-REQ-Win2k invalid content type oid");
 	goto out;
     }
-=09
+
     if (!have_data) {
-	krb5_set_error_string(context,
+	ret =3D KRB5KRB_ERR_GENERIC;
+	krb5_set_error_message(context, ret,
 			      "PK-AS-REQ-Win2k no signed auth pack");
-	ret =3D KRB5KRB_ERR_GENERIC;
 	goto out;
     }
=20
     {
 	hx509_certs signer_certs;
+	int flags =3D HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH; /* BTMM */
=20
-	ret =3D hx509_cms_verify_signed(kdc_identity->hx509ctx,
-				      kdc_identity->verify_ctx,
+	if (req->req_body.kdc_options.request_anonymous)
+	    flags |=3D HX509_CMS_VS_ALLOW_ZERO_SIGNER;
+
+	ret =3D hx509_cms_verify_signed(context->hx509ctx,
+				      cp->verify_ctx,
+				      flags,
 				      signed_content.data,
 				      signed_content.length,
 				      NULL,
@@ -533,26 +730,28 @@
 				      &eContent,
 				      &signer_certs);
 	if (ret) {
-	    char *s =3D hx509_get_error_string(kdc_identity->hx509ctx, ret);
+	    char *s =3D hx509_get_error_string(context->hx509ctx, ret);
 	    krb5_warnx(context, "PKINIT: failed to verify signature: %s: %d",
 		       s, ret);
 	    free(s);
 	    goto out;
 	}
=20
-	ret =3D hx509_get_one_cert(kdc_identity->hx509ctx, signer_certs,
-				 &client_params->cert);
-	hx509_certs_free(&signer_certs);
+	if (signer_certs) {
+	    ret =3D hx509_get_one_cert(context->hx509ctx, signer_certs,
+				     &cp->cert);
+	    hx509_certs_free(&signer_certs);
+	}
 	if (ret)
 	    goto out;
     }
=20
     /* Signature is correct, now verify the signed message */
-    if (der_heim_oid_cmp(&eContentType, oid_id_pkcs7_data()) !=3D 0 &&
-	der_heim_oid_cmp(&eContentType, oid_id_pkauthdata()) !=3D 0)
+    if (der_heim_oid_cmp(&eContentType, &asn1_oid_id_pkcs7_data) !=3D 0 &&
+	der_heim_oid_cmp(&eContentType, &asn1_oid_id_pkauthdata) !=3D 0)
     {
-	krb5_set_error_string(context, "got wrong oid for pkauthdata");
 	ret =3D KRB5_BADMSGTYPE;
+	krb5_set_error_message(context, ret, "got wrong oid for pkauthdata");
 	goto out;
     }
=20
@@ -564,11 +763,12 @@
 				    &ap,
 				    NULL);
 	if (ret) {
-	    krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
+	    krb5_set_error_message(context, ret,
+				   "Can't decode AuthPack: %d", ret);
 	    goto out;
 	}
- =20
-	ret =3D pk_check_pkauthenticator_win2k(context,=20
+
+	ret =3D pk_check_pkauthenticator_win2k(context,
 					     &ap.pkAuthenticator,
 					     req);
 	if (ret) {
@@ -576,12 +776,13 @@
 	    goto out;
 	}
=20
-	client_params->type =3D PKINIT_COMPAT_WIN2K;
-	client_params->nonce =3D ap.pkAuthenticator.nonce;
+	cp->type =3D PKINIT_WIN2K;
+	cp->nonce =3D ap.pkAuthenticator.nonce;
=20
 	if (ap.clientPublicValue) {
-	    krb5_set_error_string(context, "DH not supported for windows");
 	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   "DH not supported for windows");
 	    goto out;
 	}
 	free_AuthPack_Win2k(&ap);
@@ -594,12 +795,22 @@
 			      &ap,
 			      NULL);
 	if (ret) {
-	    krb5_set_error_string(context, "can't decode AuthPack: %d", ret);
+	    krb5_set_error_message(context, ret,
+				   "Can't decode AuthPack: %d", ret);
 	    free_AuthPack(&ap);
 	    goto out;
 	}
- =20
-	ret =3D pk_check_pkauthenticator(context,=20
+
+	if (req->req_body.kdc_options.request_anonymous &&
+	    ap.clientPublicValue =3D=3D NULL) {
+	    free_AuthPack(&ap);
+	    ret =3D KRB5_KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED;
+	    krb5_set_error_message(context, ret,
+				   "Anon not supported in RSA mode");
+	    goto out;
+	}
+
+	ret =3D pk_check_pkauthenticator(context,
 				       &ap.pkAuthenticator,
 				       req);
 	if (ret) {
@@ -607,33 +818,55 @@
 	    goto out;
 	}
=20
-	client_params->type =3D PKINIT_COMPAT_27;
-	client_params->nonce =3D ap.pkAuthenticator.nonce;
+	cp->type =3D PKINIT_27;
+	cp->nonce =3D ap.pkAuthenticator.nonce;
=20
 	if (ap.clientPublicValue) {
-	    ret =3D get_dh_param(context, config,=20
-			       ap.clientPublicValue, client_params);
+	    if (der_heim_oid_cmp(&ap.clientPublicValue->algorithm.algorithm, &asn=
1_oid_id_dhpublicnumber) =3D=3D 0) {
+		cp->keyex =3D USE_DH;
+		ret =3D get_dh_param(context, config,
+				   ap.clientPublicValue, cp);
+#ifdef HAVE_OPENSSL
+	    } else if (der_heim_oid_cmp(&ap.clientPublicValue->algorithm.algorith=
m, &asn1_oid_id_ecPublicKey) =3D=3D 0) {
+		cp->keyex =3D USE_ECDH;
+		ret =3D get_ecdh_param(context, config,
+				     ap.clientPublicValue, cp);
+#endif /* HAVE_OPENSSL */
+	    } else {
+		ret =3D KRB5_BADMSGTYPE;
+		krb5_set_error_message(context, ret, "PKINIT unknown DH mechanism");
+	    }
 	    if (ret) {
 		free_AuthPack(&ap);
 		goto out;
 	    }
+	} else
+	    cp->keyex =3D USE_RSA;
+
+	ret =3D hx509_peer_info_alloc(context->hx509ctx,
+					&cp->peer);
+	if (ret) {
+	    free_AuthPack(&ap);
+	    goto out;
 	}
=20
 	if (ap.supportedCMSTypes) {
-	    ret =3D hx509_peer_info_alloc(kdc_identity->hx509ctx,
-					&client_params->peer);
-	    if (ret) {
-		free_AuthPack(&ap);
-		goto out;
-	    }
-	    ret =3D hx509_peer_info_set_cms_algs(kdc_identity->hx509ctx,
-					       client_params->peer,
+	    ret =3D hx509_peer_info_set_cms_algs(context->hx509ctx,
+					       cp->peer,
 					       ap.supportedCMSTypes->val,
 					       ap.supportedCMSTypes->len);
 	    if (ret) {
 		free_AuthPack(&ap);
 		goto out;
 	    }
+	} else {
+	    /* assume old client */
+	    hx509_peer_info_add_cms_alg(context->hx509ctx, cp->peer,
+					hx509_crypto_des_rsdi_ede3_cbc());
+	    hx509_peer_info_add_cms_alg(context->hx509ctx, cp->peer,
+					hx509_signature_rsa_with_sha1());
+	    hx509_peer_info_add_cms_alg(context->hx509ctx, cp->peer,
+					hx509_signature_sha1());
 	}
 	free_AuthPack(&ap);
     } else
@@ -650,10 +883,10 @@
     krb5_data_free(&eContent);
     der_free_oid(&eContentType);
     der_free_oid(&contentInfoOid);
-    if (ret)
-	_kdc_pk_free_client_param(context, client_params);
-    else
-	*ret_params =3D client_params;
+    if (ret) {
+        _kdc_pk_free_client_param(context, cp);
+    } else
+	*ret_params =3D cp;
     return ret;
 }
=20
@@ -667,7 +900,7 @@
     integer->length =3D BN_num_bytes(bn);
     integer->data =3D malloc(integer->length);
     if (integer->data =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ENOMEM;
     }
     BN_bn2bin(bn, integer->data);
@@ -678,58 +911,63 @@
 static krb5_error_code
 pk_mk_pa_reply_enckey(krb5_context context,
 		      krb5_kdc_configuration *config,
-		      pk_client_params *client_params,
+		      pk_client_params *cp,
 		      const KDC_REQ *req,
 		      const krb5_data *req_buffer,
 		      krb5_keyblock *reply_key,
-		      ContentInfo *content_info)
+		      ContentInfo *content_info,
+		      hx509_cert *kdc_cert)
 {
-    const heim_oid *envelopedAlg =3D NULL, *sdAlg =3D NULL;
+    const heim_oid *envelopedAlg =3D NULL, *sdAlg =3D NULL, *evAlg =3D NUL=
L;
     krb5_error_code ret;
     krb5_data buf, signed_data;
-    size_t size;
+    size_t size =3D 0;
     int do_win2k =3D 0;
=20
     krb5_data_zero(&buf);
     krb5_data_zero(&signed_data);
=20
+    *kdc_cert =3D NULL;
+
     /*
      * If the message client is a win2k-type but it send pa data
      * 09-binding it expects a IETF (checksum) reply so there can be
      * no replay attacks.
      */
=20
-    switch (client_params->type) {
-    case PKINIT_COMPAT_WIN2K: {
+    switch (cp->type) {
+    case PKINIT_WIN2K: {
 	int i =3D 0;
 	if (_kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_09_BINDING) =3D=3D NULL
 	    && config->pkinit_require_binding =3D=3D 0)
 	{
 	    do_win2k =3D 1;
 	}
+	sdAlg =3D &asn1_oid_id_pkcs7_data;
+	evAlg =3D &asn1_oid_id_pkcs7_data;
+	envelopedAlg =3D &asn1_oid_id_rsadsi_des_ede3_cbc;
 	break;
     }
-    case PKINIT_COMPAT_27:
+    case PKINIT_27:
+	sdAlg =3D &asn1_oid_id_pkrkeydata;
+	evAlg =3D &asn1_oid_id_pkcs7_signedData;
 	break;
     default:
 	krb5_abortx(context, "internal pkinit error");
-    }	   =20
+    }
=20
     if (do_win2k) {
 	ReplyKeyPack_Win2k kp;
 	memset(&kp, 0, sizeof(kp));
=20
-	envelopedAlg =3D oid_id_rsadsi_des_ede3_cbc();
-	sdAlg =3D oid_id_pkcs7_data();
-
 	ret =3D copy_EncryptionKey(reply_key, &kp.replyKey);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
-	kp.nonce =3D client_params->nonce;
-=09
-	ASN1_MALLOC_ENCODE(ReplyKeyPack_Win2k,=20
+	kp.nonce =3D cp->nonce;
+
+	ASN1_MALLOC_ENCODE(ReplyKeyPack_Win2k,
 			   buf.data, buf.length,
 			   &kp, &size,ret);
 	free_ReplyKeyPack_Win2k(&kp);
@@ -738,17 +976,15 @@
 	ReplyKeyPack kp;
 	memset(&kp, 0, sizeof(kp));
=20
-	sdAlg =3D oid_id_pkrkeydata();
-
 	ret =3D copy_EncryptionKey(reply_key, &kp.replyKey);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
 	ret =3D krb5_crypto_init(context, reply_key, 0, &ascrypto);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
@@ -756,21 +992,21 @@
 				   req_buffer->data, req_buffer->length,
 				   &kp.asChecksum);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
-			    =20
+
 	ret =3D krb5_crypto_destroy(context, ascrypto);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
 	ASN1_MALLOC_ENCODE(ReplyKeyPack, buf.data, buf.length, &kp, &size,ret);
 	free_ReplyKeyPack(&kp);
     }
     if (ret) {
-	krb5_set_error_string(context, "ASN.1 encoding of ReplyKeyPack "
-			      "failed (%d)", ret);
+	krb5_set_error_message(context, ret, "ASN.1 encoding of ReplyKeyPack "
+			       "failed (%d)", ret);
 	goto out;
     }
     if (buf.length !=3D size)
@@ -779,42 +1015,43 @@
     {
 	hx509_query *q;
 	hx509_cert cert;
-=09
-	ret =3D hx509_query_alloc(kdc_identity->hx509ctx, &q);
+
+	ret =3D hx509_query_alloc(context->hx509ctx, &q);
 	if (ret)
 	    goto out;
-=09
+
 	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
-	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
-=09
-	ret =3D hx509_certs_find(kdc_identity->hx509ctx,=20
-			       kdc_identity->certs,=20
-			       q,=20
+	if (config->pkinit_kdc_friendly_name)
+	    hx509_query_match_friendly_name(q, config->pkinit_kdc_friendly_name);
+
+	ret =3D hx509_certs_find(context->hx509ctx,
+			       kdc_identity->certs,
+			       q,
 			       &cert);
-	hx509_query_free(kdc_identity->hx509ctx, q);
+	hx509_query_free(context->hx509ctx, q);
 	if (ret)
 	    goto out;
-=09
-	ret =3D hx509_cms_create_signed_1(kdc_identity->hx509ctx,
+
+	ret =3D hx509_cms_create_signed_1(context->hx509ctx,
 					0,
 					sdAlg,
 					buf.data,
 					buf.length,
 					NULL,
 					cert,
-					client_params->peer,
-					client_params->client_anchors,
+					cp->peer,
+					cp->client_anchors,
 					kdc_identity->certpool,
 					&signed_data);
-	hx509_cert_free(cert);
+	*kdc_cert =3D cert;
     }
=20
     krb5_data_free(&buf);
-    if (ret)=20
+    if (ret)
 	goto out;
=20
-    if (client_params->type =3D=3D PKINIT_COMPAT_WIN2K) {
-	ret =3D hx509_cms_wrap_ContentInfo(oid_id_pkcs7_signedData(),
+    if (cp->type =3D=3D PKINIT_WIN2K) {
+	ret =3D hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData,
 					 &signed_data,
 					 &buf);
 	if (ret)
@@ -823,20 +1060,25 @@
 	signed_data =3D buf;
     }
=20
-    ret =3D hx509_cms_envelope_1(kdc_identity->hx509ctx,
-			       0,
-			       client_params->cert,
-			       signed_data.data, signed_data.length,=20
+    ret =3D hx509_cms_envelope_1(context->hx509ctx,
+			       HX509_CMS_EV_NO_KU_CHECK,
+			       cp->cert,
+			       signed_data.data, signed_data.length,
 			       envelopedAlg,
-			       oid_id_pkcs7_signedData(), &buf);
+			       evAlg, &buf);
     if (ret)
 	goto out;
-   =20
+
     ret =3D _krb5_pk_mk_ContentInfo(context,
 				  &buf,
-				  oid_id_pkcs7_envelopedData(),
+				  &asn1_oid_id_pkcs7_envelopedData,
 				  content_info);
 out:
+    if (ret && *kdc_cert) {
+        hx509_cert_free(*kdc_cert);
+	*kdc_cert =3D NULL;
+    }
+
     krb5_data_free(&buf);
     krb5_data_free(&signed_data);
     return ret;
@@ -848,9 +1090,8 @@
=20
 static krb5_error_code
 pk_mk_pa_reply_dh(krb5_context context,
-                  DH *kdc_dh,
-      		  pk_client_params *client_params,
-                  krb5_keyblock *reply_key,
+		  krb5_kdc_configuration *config,
+      		  pk_client_params *cp,
 		  ContentInfo *content_info,
 		  hx509_cert *kdc_cert)
 {
@@ -858,88 +1099,115 @@
     krb5_data signed_data, buf;
     ContentInfo contentinfo;
     krb5_error_code ret;
-    size_t size;
-    heim_integer i;
+    hx509_cert cert;
+    hx509_query *q;
+    size_t size =3D 0;
=20
     memset(&contentinfo, 0, sizeof(contentinfo));
     memset(&dh_info, 0, sizeof(dh_info));
+    krb5_data_zero(&signed_data);
     krb5_data_zero(&buf);
-    krb5_data_zero(&signed_data);
=20
     *kdc_cert =3D NULL;
=20
-    ret =3D BN_to_integer(context, kdc_dh->pub_key, &i);
-    if (ret)
-	return ret;
+    if (cp->keyex =3D=3D USE_DH) {
+	DH *kdc_dh =3D cp->u.dh.key;
+	heim_integer i;
=20
-    ASN1_MALLOC_ENCODE(DHPublicKey, buf.data, buf.length, &i, &size, ret);
-    if (ret) {
-	krb5_set_error_string(context, "ASN.1 encoding of "
-			      "DHPublicKey failed (%d)", ret);
-	krb5_clear_error_string(context);
-	return ret;
-    }
-    if (buf.length !=3D size)
-	krb5_abortx(context, "Internal ASN.1 encoder error");
+	ret =3D BN_to_integer(context, kdc_dh->pub_key, &i);
+	if (ret)
+	    return ret;
=20
-    dh_info.subjectPublicKey.length =3D buf.length * 8;
-    dh_info.subjectPublicKey.data =3D buf.data;
-   =20
-    dh_info.nonce =3D client_params->nonce;
+	ASN1_MALLOC_ENCODE(DHPublicKey, buf.data, buf.length, &i, &size, ret);
+	der_free_heim_integer(&i);
+	if (ret) {
+	    krb5_set_error_message(context, ret, "ASN.1 encoding of "
+				   "DHPublicKey failed (%d)", ret);
+	    return ret;
+	}
+	if (buf.length !=3D size)
+	    krb5_abortx(context, "Internal ASN.1 encoder error");
=20
-    ASN1_MALLOC_ENCODE(KDCDHKeyInfo, buf.data, buf.length, &dh_info, &size=
,=20
+	dh_info.subjectPublicKey.length =3D buf.length * 8;
+	dh_info.subjectPublicKey.data =3D buf.data;
+	krb5_data_zero(&buf);
+#ifdef HAVE_OPENSSL
+    } else if (cp->keyex =3D=3D USE_ECDH) {
+	unsigned char *p;
+	int len;
+
+	len =3D i2o_ECPublicKey(cp->u.ecdh.key, NULL);
+	if (len <=3D 0)
+	    abort();
+
+	p =3D malloc(len);
+	if (p =3D=3D NULL)
+	    abort();
+
+	dh_info.subjectPublicKey.length =3D len * 8;
+	dh_info.subjectPublicKey.data =3D p;
+
+	len =3D i2o_ECPublicKey(cp->u.ecdh.key, &p);
+	if (len <=3D 0)
+	    abort();
+#endif
+    } else
+	krb5_abortx(context, "no keyex selected ?");
+
+
+    dh_info.nonce =3D cp->nonce;
+
+    ASN1_MALLOC_ENCODE(KDCDHKeyInfo, buf.data, buf.length, &dh_info, &size,
 		       ret);
     if (ret) {
-	krb5_set_error_string(context, "ASN.1 encoding of "
-			      "KdcDHKeyInfo failed (%d)", ret);
+	krb5_set_error_message(context, ret, "ASN.1 encoding of "
+			       "KdcDHKeyInfo failed (%d)", ret);
 	goto out;
     }
     if (buf.length !=3D size)
 	krb5_abortx(context, "Internal ASN.1 encoder error");
=20
-    /*=20
+    /*
      * Create the SignedData structure and sign the KdcDHKeyInfo
      * filled in above
      */
=20
-    {
-	hx509_query *q;
-	hx509_cert cert;
-=09
-	ret =3D hx509_query_alloc(kdc_identity->hx509ctx, &q);
-	if (ret)
-	    goto out;
-=09
-	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
-	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
-=09
-	ret =3D hx509_certs_find(kdc_identity->hx509ctx,=20
-			       kdc_identity->certs,=20
-			       q,=20
-			       &cert);
-	hx509_query_free(kdc_identity->hx509ctx, q);
-	if (ret)
-	    goto out;
-=09
-	ret =3D hx509_cms_create_signed_1(kdc_identity->hx509ctx,
-					0,
-					oid_id_pkdhkeydata(),
-					buf.data,
-					buf.length,
-					NULL,
-					cert,
-					client_params->peer,
-					client_params->client_anchors,
-					kdc_identity->certpool,
-					&signed_data);
-	*kdc_cert =3D cert;
-    }
+    ret =3D hx509_query_alloc(context->hx509ctx, &q);
     if (ret)
 	goto out;
=20
+    hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+    if (config->pkinit_kdc_friendly_name)
+	hx509_query_match_friendly_name(q, config->pkinit_kdc_friendly_name);
+
+    ret =3D hx509_certs_find(context->hx509ctx,
+			   kdc_identity->certs,
+			   q,
+			   &cert);
+    hx509_query_free(context->hx509ctx, q);
+    if (ret)
+	goto out;
+
+    ret =3D hx509_cms_create_signed_1(context->hx509ctx,
+				    0,
+				    &asn1_oid_id_pkdhkeydata,
+				    buf.data,
+				    buf.length,
+				    NULL,
+				    cert,
+				    cp->peer,
+				    cp->client_anchors,
+				    kdc_identity->certpool,
+				    &signed_data);
+    if (ret) {
+	kdc_log(context, config, 0, "Failed signing the DH* reply: %d", ret);
+	goto out;
+    }
+    *kdc_cert =3D cert;
+
     ret =3D _krb5_pk_mk_ContentInfo(context,
 				  &signed_data,
-				  oid_id_pkcs7_signedData(),
+				  &asn1_oid_id_pkcs7_signedData,
 				  content_info);
     if (ret)
 	goto out;
@@ -964,23 +1232,25 @@
 krb5_error_code
 _kdc_pk_mk_pa_reply(krb5_context context,
 		    krb5_kdc_configuration *config,
-		    pk_client_params *client_params,
+		    pk_client_params *cp,
 		    const hdb_entry_ex *client,
+		    krb5_enctype sessionetype,
 		    const KDC_REQ *req,
 		    const krb5_data *req_buffer,
 		    krb5_keyblock **reply_key,
+		    krb5_keyblock *sessionkey,
 		    METHOD_DATA *md)
 {
     krb5_error_code ret;
-    void *buf;
-    size_t len, size;
+    void *buf =3D NULL;
+    size_t len =3D 0, size =3D 0;
     krb5_enctype enctype;
     int pa_type;
     hx509_cert kdc_cert =3D NULL;
-    int i;
+    size_t i;
=20
     if (!config->enable_pkinit) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return 0;
     }
=20
@@ -990,15 +1260,15 @@
 		break;
 	if (req->req_body.etype.len <=3D i) {
 	    ret =3D KRB5KRB_ERR_GENERIC;
-	    krb5_set_error_string(context,
-				  "No valid enctype available from client");
+	    krb5_set_error_message(context, ret,
+				   "No valid enctype available from client");
 	    goto out;
-	}=09
+	}
 	enctype =3D req->req_body.etype.val[i];
     } else
 	enctype =3D ETYPE_DES3_CBC_SHA1;
=20
-    if (client_params->type =3D=3D PKINIT_COMPAT_27) {
+    if (cp->type =3D=3D PKINIT_27) {
 	PA_PK_AS_REP rep;
 	const char *type, *other =3D "";
=20
@@ -1006,87 +1276,129 @@
=20
 	pa_type =3D KRB5_PADATA_PK_AS_REP;
=20
-	if (client_params->dh =3D=3D NULL) {
+	if (cp->keyex =3D=3D USE_RSA) {
 	    ContentInfo info;
=20
 	    type =3D "enckey";
=20
 	    rep.element =3D choice_PA_PK_AS_REP_encKeyPack;
=20
-	    ret =3D krb5_generate_random_keyblock(context, enctype,=20
-						&client_params->reply_key);
+	    ret =3D krb5_generate_random_keyblock(context, enctype,
+						&cp->reply_key);
 	    if (ret) {
 		free_PA_PK_AS_REP(&rep);
 		goto out;
 	    }
 	    ret =3D pk_mk_pa_reply_enckey(context,
 					config,
-					client_params,
+					cp,
 					req,
 					req_buffer,
-					&client_params->reply_key,
-					&info);
+					&cp->reply_key,
+					&info,
+					&kdc_cert);
 	    if (ret) {
 		free_PA_PK_AS_REP(&rep);
 		goto out;
 	    }
-	    ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data,=20
-			       rep.u.encKeyPack.length, &info, &size,=20
+	    ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data,
+			       rep.u.encKeyPack.length, &info, &size,
 			       ret);
 	    free_ContentInfo(&info);
 	    if (ret) {
-		krb5_set_error_string(context, "encoding of Key ContentInfo "
-				      "failed %d", ret);
+		krb5_set_error_message(context, ret, "encoding of Key ContentInfo "
+				       "failed %d", ret);
 		free_PA_PK_AS_REP(&rep);
 		goto out;
 	    }
 	    if (rep.u.encKeyPack.length !=3D size)
 		krb5_abortx(context, "Internal ASN.1 encoder error");
=20
+	    ret =3D krb5_generate_random_keyblock(context, sessionetype,
+						sessionkey);
+	    if (ret) {
+		free_PA_PK_AS_REP(&rep);
+		goto out;
+	    }
+
 	} else {
 	    ContentInfo info;
=20
-	    type =3D "dh";
-	    if (client_params->dh_group_name)
-		other =3D client_params->dh_group_name;
+	    switch (cp->keyex) {
+	    case USE_DH: type =3D "dh"; break;
+#ifdef HAVE_OPENSSL
+	    case USE_ECDH: type =3D "ecdh"; break;
+#endif
+	    default: krb5_abortx(context, "unknown keyex"); break;
+	    }
+
+	    if (cp->dh_group_name)
+		other =3D cp->dh_group_name;
=20
 	    rep.element =3D choice_PA_PK_AS_REP_dhInfo;
=20
-	    ret =3D generate_dh_keyblock(context, client_params, enctype,
-				       &client_params->reply_key);
+	    ret =3D generate_dh_keyblock(context, cp, enctype);
 	    if (ret)
 		return ret;
=20
-	    ret =3D pk_mk_pa_reply_dh(context, client_params->dh,
-				    client_params,=20
-				    &client_params->reply_key,
+	    ret =3D pk_mk_pa_reply_dh(context, config,
+				    cp,
 				    &info,
 				    &kdc_cert);
+	    if (ret) {
+		free_PA_PK_AS_REP(&rep);
+		krb5_set_error_message(context, ret,
+				       "create pa-reply-dh "
+				       "failed %d", ret);
+		goto out;
+	    }
=20
 	    ASN1_MALLOC_ENCODE(ContentInfo, rep.u.dhInfo.dhSignedData.data,
 			       rep.u.dhInfo.dhSignedData.length, &info, &size,
 			       ret);
 	    free_ContentInfo(&info);
 	    if (ret) {
-		krb5_set_error_string(context, "encoding of Key ContentInfo "
-				      "failed %d", ret);
+		krb5_set_error_message(context, ret,
+				       "encoding of Key ContentInfo "
+				       "failed %d", ret);
 		free_PA_PK_AS_REP(&rep);
 		goto out;
 	    }
 	    if (rep.u.encKeyPack.length !=3D size)
 		krb5_abortx(context, "Internal ASN.1 encoder error");
=20
-	}
-	if (ret) {
-	    free_PA_PK_AS_REP(&rep);
-	    goto out;
+	    /* XXX KRB-FX-CF2 */
+	    ret =3D krb5_generate_random_keyblock(context, sessionetype,
+						sessionkey);
+	    if (ret) {
+		free_PA_PK_AS_REP(&rep);
+		goto out;
+	    }
+
+	    /* XXX Add PA-PKINIT-KX */
+
 	}
=20
-	ASN1_MALLOC_ENCODE(PA_PK_AS_REP, buf, len, &rep, &size, ret);
+#define use_btmm_with_enckey 0
+	if (use_btmm_with_enckey && rep.element =3D=3D choice_PA_PK_AS_REP_encKey=
Pack) {
+	    PA_PK_AS_REP_BTMM btmm;
+	    heim_any any;
+
+	    any.data =3D rep.u.encKeyPack.data;
+	    any.length =3D rep.u.encKeyPack.length;
+
+	    btmm.dhSignedData =3D NULL;
+	    btmm.encKeyPack =3D &any;
+
+	    ASN1_MALLOC_ENCODE(PA_PK_AS_REP_BTMM, buf, len, &btmm, &size, ret);
+	} else {
+	    ASN1_MALLOC_ENCODE(PA_PK_AS_REP, buf, len, &rep, &size, ret);
+	}
+
 	free_PA_PK_AS_REP(&rep);
 	if (ret) {
-	    krb5_set_error_string(context, "encode PA-PK-AS-REP failed %d",
-				  ret);
+	    krb5_set_error_message(context, ret,
+				   "encode PA-PK-AS-REP failed %d", ret);
 	    goto out;
 	}
 	if (len !=3D size)
@@ -1094,44 +1406,46 @@
=20
 	kdc_log(context, config, 0, "PK-INIT using %s %s", type, other);
=20
-    } else if (client_params->type =3D=3D PKINIT_COMPAT_WIN2K) {
+    } else if (cp->type =3D=3D PKINIT_WIN2K) {
 	PA_PK_AS_REP_Win2k rep;
 	ContentInfo info;
=20
-	if (client_params->dh) {
-	    krb5_set_error_string(context, "Windows PK-INIT doesn't support DH");
+	if (cp->keyex !=3D USE_RSA) {
 	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   "Windows PK-INIT doesn't support DH");
 	    goto out;
 	}
=20
 	memset(&rep, 0, sizeof(rep));
=20
 	pa_type =3D KRB5_PADATA_PK_AS_REP_19;
-	rep.element =3D choice_PA_PK_AS_REP_encKeyPack;
+	rep.element =3D choice_PA_PK_AS_REP_Win2k_encKeyPack;
=20
-	ret =3D krb5_generate_random_keyblock(context, enctype,=20
-					    &client_params->reply_key);
+	ret =3D krb5_generate_random_keyblock(context, enctype,
+					    &cp->reply_key);
 	if (ret) {
 	    free_PA_PK_AS_REP_Win2k(&rep);
 	    goto out;
 	}
 	ret =3D pk_mk_pa_reply_enckey(context,
 				    config,
-				    client_params,
+				    cp,
 				    req,
 				    req_buffer,
-				    &client_params->reply_key,
-				    &info);
+				    &cp->reply_key,
+				    &info,
+				    &kdc_cert);
 	if (ret) {
 	    free_PA_PK_AS_REP_Win2k(&rep);
 	    goto out;
 	}
-	ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data,=20
-			   rep.u.encKeyPack.length, &info, &size,=20
+	ASN1_MALLOC_ENCODE(ContentInfo, rep.u.encKeyPack.data,
+			   rep.u.encKeyPack.length, &info, &size,
 			   ret);
 	free_ContentInfo(&info);
 	if (ret) {
-	    krb5_set_error_string(context, "encoding of Key ContentInfo "
+	    krb5_set_error_message(context, ret, "encoding of Key ContentInfo "
 				  "failed %d", ret);
 	    free_PA_PK_AS_REP_Win2k(&rep);
 	    goto out;
@@ -1142,20 +1456,28 @@
 	ASN1_MALLOC_ENCODE(PA_PK_AS_REP_Win2k, buf, len, &rep, &size, ret);
 	free_PA_PK_AS_REP_Win2k(&rep);
 	if (ret) {
-	    krb5_set_error_string(context,=20
+	    krb5_set_error_message(context, ret,
 				  "encode PA-PK-AS-REP-Win2k failed %d", ret);
 	    goto out;
 	}
 	if (len !=3D size)
 	    krb5_abortx(context, "Internal ASN.1 encoder error");
=20
+	ret =3D krb5_generate_random_keyblock(context, sessionetype,
+					    sessionkey);
+	if (ret) {
+	    free(buf);
+	    goto out;
+	}
+
     } else
 	krb5_abortx(context, "PK-INIT internal error");
=20
=20
     ret =3D krb5_padata_add(context, md, pa_type, buf, len);
     if (ret) {
-	krb5_set_error_string(context, "failed adding PA-PK-AS-REP %d", ret);
+	krb5_set_error_message(context, ret,
+			       "Failed adding PA-PK-AS-REP %d", ret);
 	free(buf);
 	goto out;
     }
@@ -1173,7 +1495,7 @@
=20
 	    fd =3D open(config->pkinit_kdc_ocsp_file, O_RDONLY);
 	    if (fd < 0) {
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"PK-INIT failed to open ocsp data file %d", errno);
 		goto out_ocsp;
 	    }
@@ -1181,15 +1503,15 @@
 	    if (ret) {
 		ret =3D errno;
 		close(fd);
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"PK-INIT failed to stat ocsp data %d", ret);
 		goto out_ocsp;
 	    }
-	   =20
+
 	    ret =3D krb5_data_alloc(&ocsp.data, sb.st_size);
 	    if (ret) {
 		close(fd);
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"PK-INIT failed to stat ocsp data %d", ret);
 		goto out_ocsp;
 	    }
@@ -1197,19 +1519,19 @@
 	    ret =3D read(fd, ocsp.data.data, sb.st_size);
 	    close(fd);
 	    if (ret !=3D sb.st_size) {
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"PK-INIT failed to read ocsp data %d", errno);
 		goto out_ocsp;
 	    }
=20
-	    ret =3D hx509_ocsp_verify(kdc_identity->hx509ctx,
+	    ret =3D hx509_ocsp_verify(context->hx509ctx,
 				    kdc_time,
 				    kdc_cert,
 				    0,
 				    ocsp.data.data, ocsp.data.length,
 				    &ocsp.expire);
 	    if (ret) {
-		kdc_log(context, config, 0,=20
+		kdc_log(context, config, 0,
 			"PK-INIT failed to verify ocsp data %d", ret);
 		krb5_data_free(&ocsp.data);
 		ocsp.expire =3D 0;
@@ -1225,12 +1547,12 @@
=20
 	if (ocsp.expire !=3D 0 && ocsp.expire > kdc_time) {
=20
-	    ret =3D krb5_padata_add(context, md,=20
+	    ret =3D krb5_padata_add(context, md,
 				  KRB5_PADATA_PA_PK_OCSP_RESPONSE,
 				  ocsp.data.data, ocsp.data.length);
 	    if (ret) {
-		krb5_set_error_string(context,=20
-				      "Failed adding OCSP response %d", ret);
+		krb5_set_error_message(context, ret,
+				       "Failed adding OCSP response %d", ret);
 		goto out;
 	    }
 	}
@@ -1241,25 +1563,26 @@
 	hx509_cert_free(kdc_cert);
=20
     if (ret =3D=3D 0)
-	*reply_key =3D &client_params->reply_key;
+	*reply_key =3D &cp->reply_key;
     return ret;
 }
=20
 static int
-match_rfc_san(krb5_context context,=20
+match_rfc_san(krb5_context context,
 	      krb5_kdc_configuration *config,
 	      hx509_context hx509ctx,
-	      hx509_cert client_cert,=20
+	      hx509_cert client_cert,
 	      krb5_const_principal match)
 {
     hx509_octet_string_list list;
-    int ret, i, found =3D 0;
+    int ret, found =3D 0;
+    size_t i;
=20
     memset(&list, 0 , sizeof(list));
=20
     ret =3D hx509_cert_find_subjectAltName_otherName(hx509ctx,
 						   client_cert,
-						   oid_id_pkinit_san(),
+						   &asn1_oid_id_pkinit_san,
 						   &list);
     if (ret)
 	goto out;
@@ -1269,13 +1592,14 @@
 	KRB5PrincipalName kn;
 	size_t size;
=20
-	ret =3D decode_KRB5PrincipalName(list.val[i].data,=20
+	ret =3D decode_KRB5PrincipalName(list.val[i].data,
 				       list.val[i].length,
 				       &kn, &size);
 	if (ret) {
+	    const char *msg =3D krb5_get_error_message(context, ret);
 	    kdc_log(context, config, 0,
-		    "Decoding kerberos name in certificate failed: %s",
-		    krb5_get_err_text(context, ret));
+		    "Decoding kerberos name in certificate failed: %s", msg);
+	    krb5_free_error_message(context, msg);
 	    break;
 	}
 	if (size !=3D list.val[i].length) {
@@ -1293,7 +1617,7 @@
     }
=20
 out:
-    hx509_free_octet_string_list(&list);   =20
+    hx509_free_octet_string_list(&list);
     if (ret)
 	return ret;
=20
@@ -1304,15 +1628,16 @@
 }
=20
 static int
-match_ms_upn_san(krb5_context context,=20
+match_ms_upn_san(krb5_context context,
 		 krb5_kdc_configuration *config,
 		 hx509_context hx509ctx,
-		 hx509_cert client_cert,=20
-		 krb5_const_principal match)
+		 hx509_cert client_cert,
+		 HDB *clientdb,
+		 hdb_entry_ex *client)
 {
     hx509_octet_string_list list;
     krb5_principal principal =3D NULL;
-    int ret, found =3D 0;
+    int ret;
     MS_UPN_SAN upn;
     size_t size;
=20
@@ -1320,7 +1645,7 @@
=20
     ret =3D hx509_cert_find_subjectAltName_otherName(hx509ctx,
 						   client_cert,
-						   oid_id_pkinit_ms_san(),
+						   &asn1_oid_id_pkinit_ms_san,
 						   &list);
     if (ret)
 	goto out;
@@ -1336,6 +1661,12 @@
 	kdc_log(context, config, 0, "Decode of MS-UPN-SAN failed");
 	goto out;
     }
+    if (size !=3D list.val[0].length) {
+	free_MS_UPN_SAN(&upn);
+	kdc_log(context, config, 0, "Trailing data in ");
+	ret =3D KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
+	goto out;
+    }
=20
     kdc_log(context, config, 0, "found MS UPN SAN: %s", upn);
=20
@@ -1346,42 +1677,51 @@
 	goto out;
     }
=20
-    /*=20
-     * This is very wrong, but will do for now, should really and a
-     * plugin to the windc layer to very this ACL.
-    */
-    strupr(principal->realm);
+    if (clientdb->hdb_check_pkinit_ms_upn_match) {
+	ret =3D clientdb->hdb_check_pkinit_ms_upn_match(context, clientdb, client=
, principal);
+    } else {
=20
-    if (krb5_principal_compare(context, principal, match) =3D=3D TRUE)
-	found =3D 1;
+	/*
+	 * This is very wrong, but will do for a fallback
+	 */
+	strupr(principal->realm);
+
+	if (krb5_principal_compare(context, principal, client->entry.principal) =
=3D=3D FALSE)
+	    ret =3D KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
+    }
=20
 out:
     if (principal)
 	krb5_free_principal(context, principal);
-    hx509_free_octet_string_list(&list);   =20
-    if (ret)
-	return ret;
+    hx509_free_octet_string_list(&list);
=20
-    if (!found)
-	return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
-
-    return 0;
+    return ret;
 }
=20
 krb5_error_code
 _kdc_pk_check_client(krb5_context context,
 		     krb5_kdc_configuration *config,
-		     const hdb_entry_ex *client,
-		     pk_client_params *client_params,
+		     HDB *clientdb,
+		     hdb_entry_ex *client,
+		     pk_client_params *cp,
 		     char **subject_name)
 {
     const HDB_Ext_PKINIT_acl *acl;
+    const HDB_Ext_PKINIT_cert *pc;
     krb5_error_code ret;
     hx509_name name;
-    int i;
+    size_t i;
=20
-    ret =3D hx509_cert_get_base_subject(kdc_identity->hx509ctx,
-				      client_params->cert,
+    if (cp->cert =3D=3D NULL) {
+
+	*subject_name =3D strdup("anonymous client client");
+	if (*subject_name =3D=3D NULL)
+	    return ENOMEM;
+	return 0;
+    }
+
+    ret =3D hx509_cert_get_base_subject(context->hx509ctx,
+				      cp->cert,
 				      &name);
     if (ret)
 	return ret;
@@ -1392,13 +1732,36 @@
 	return ret;
=20
     kdc_log(context, config, 0,
-	    "Trying to authorize PK-INIT subject DN %s",=20
+	    "Trying to authorize PK-INIT subject DN %s",
 	    *subject_name);
=20
+    ret =3D hdb_entry_get_pkinit_cert(&client->entry, &pc);
+    if (ret =3D=3D 0 && pc) {
+	hx509_cert cert;
+	size_t j;
+
+	for (j =3D 0; j < pc->len; j++) {
+	    ret =3D hx509_cert_init_data(context->hx509ctx,
+				       pc->val[j].cert.data,
+				       pc->val[j].cert.length,
+				       &cert);
+	    if (ret)
+		continue;
+	    ret =3D hx509_cert_cmp(cert, cp->cert);
+	    hx509_cert_free(cert);
+	    if (ret =3D=3D 0) {
+		kdc_log(context, config, 5,
+			"Found matching PK-INIT cert in hdb");
+		return 0;
+	    }
+	}
+    }
+
+
     if (config->pkinit_princ_in_cert) {
 	ret =3D match_rfc_san(context, config,
-			    kdc_identity->hx509ctx,
-			    client_params->cert,
+			    context->hx509ctx,
+			    cp->cert,
 			    client->entry.principal);
 	if (ret =3D=3D 0) {
 	    kdc_log(context, config, 5,
@@ -1406,9 +1769,10 @@
 	    return 0;
 	}
 	ret =3D match_ms_upn_san(context, config,
-			       kdc_identity->hx509ctx,
-			       client_params->cert,
-			       client->entry.principal);
+			       context->hx509ctx,
+			       cp->cert,
+			       clientdb,
+			       client);
 	if (ret =3D=3D 0) {
 	    kdc_log(context, config, 5,
 		    "Found matching MS UPN SAN in certificate");
@@ -1453,7 +1817,8 @@
 	return 0;
     }
=20
-    krb5_set_error_string(context,
+    ret =3D KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
+    krb5_set_error_message(context, ret,
 			  "PKINIT no matching principals for %s",
 			  *subject_name);
=20
@@ -1464,11 +1829,11 @@
     free(*subject_name);
     *subject_name =3D NULL;
=20
-    return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
+    return ret;
 }
=20
 static krb5_error_code
-add_principal_mapping(krb5_context context,=20
+add_principal_mapping(krb5_context context,
 		      const char *principal_name,
 		      const char * subject)
 {
@@ -1501,16 +1866,16 @@
 krb5_error_code
 _kdc_add_inital_verified_cas(krb5_context context,
 			     krb5_kdc_configuration *config,
-			     pk_client_params *params,
+			     pk_client_params *cp,
 			     EncTicketPart *tkt)
 {
     AD_INITIAL_VERIFIED_CAS cas;
     krb5_error_code ret;
     krb5_data data;
-    size_t size;
+    size_t size =3D 0;
=20
     memset(&cas, 0, sizeof(cas));
-   =20
+
     /* XXX add CAs to cas here */
=20
     ASN1_MALLOC_ENCODE(AD_INITIAL_VERIFIED_CAS, data.data, data.length,
@@ -1520,7 +1885,7 @@
     if (data.length !=3D size)
 	krb5_abortx(context, "internal asn.1 encoder error");
=20
-    ret =3D _kdc_tkt_add_if_relevant_ad(context, tkt,=20
+    ret =3D _kdc_tkt_add_if_relevant_ad(context, tkt,
 				      KRB5_AUTHDATA_INITIAL_VERIFIED_CAS,
 				      &data);
     krb5_data_free(&data);
@@ -1545,7 +1910,7 @@
=20
     while (fgets(buf, sizeof(buf), f) !=3D NULL) {
 	char *subject_name, *p;
-   =20
+
 	buf[strcspn(buf, "\n")] =3D '\0';
 	lineno++;
=20
@@ -1569,22 +1934,22 @@
 		      lineno, buf);
 	    continue;
 	}
-    }=20
+    }
=20
     fclose(f);
 }
-		  =20
+
 /*
  *
  */
=20
 krb5_error_code
-_kdc_pk_initialize(krb5_context context,
-		   krb5_kdc_configuration *config,
-		   const char *user_id,
-		   const char *anchors,
-		   char **pool,
-		   char **revoke_list)
+krb5_kdc_pk_initialize(krb5_context context,
+		       krb5_kdc_configuration *config,
+		       const char *user_id,
+		       const char *anchors,
+		       char **pool,
+		       char **revoke_list)
 {
     const char *file;
     char *fn =3D NULL;
@@ -1618,42 +1983,52 @@
     {
 	hx509_query *q;
 	hx509_cert cert;
-=09
-	ret =3D hx509_query_alloc(kdc_identity->hx509ctx, &q);
+
+	ret =3D hx509_query_alloc(context->hx509ctx, &q);
 	if (ret) {
 	    krb5_warnx(context, "PKINIT: out of memory");
 	    return ENOMEM;
 	}
-=09
+
 	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
-	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
-=09
-	ret =3D hx509_certs_find(kdc_identity->hx509ctx,
+	if (config->pkinit_kdc_friendly_name)
+	    hx509_query_match_friendly_name(q, config->pkinit_kdc_friendly_name);
+
+	ret =3D hx509_certs_find(context->hx509ctx,
 			       kdc_identity->certs,
 			       q,
 			       &cert);
-	hx509_query_free(kdc_identity->hx509ctx, q);
+	hx509_query_free(context->hx509ctx, q);
 	if (ret =3D=3D 0) {
-	    if (hx509_cert_check_eku(kdc_identity->hx509ctx, cert,
-				     oid_id_pkkdcekuoid(), 0))
-		krb5_warnx(context, "WARNING Found KDC certificate "
-			   "is missing the PK-INIT KDC EKU, this is bad for "
-			   "interoperability.");
+	    if (hx509_cert_check_eku(context->hx509ctx, cert,
+				     &asn1_oid_id_pkkdcekuoid, 0)) {
+		hx509_name name;
+		char *str;
+		ret =3D hx509_cert_get_subject(cert, &name);
+		if (ret =3D=3D 0) {
+		    hx509_name_to_string(name, &str);
+		    krb5_warnx(context, "WARNING Found KDC certificate (%s)"
+			       "is missing the PK-INIT KDC EKU, this is bad for "
+			       "interoperability.", str);
+		    hx509_name_free(&name);
+		    free(str);
+		}
+	    }
 	    hx509_cert_free(cert);
 	} else
 	    krb5_warnx(context, "PKINIT: failed to find a signing "
 		       "certifiate with a public key");
     }
=20
-    ret =3D krb5_config_get_bool_default(context,=20
-				       NULL,
-				       FALSE,
-				       "kdc",
-				       "pkinit_allow_proxy_certificate",
-				       NULL);
-    _krb5_pk_allow_proxy_certificate(kdc_identity, ret);
+    if (krb5_config_get_bool_default(context,
+				     NULL,
+				     FALSE,
+				     "kdc",
+				     "pkinit_allow_proxy_certificate",
+				     NULL))
+	config->pkinit_allow_proxy_certs =3D 1;
=20
-    file =3D krb5_config_get_string(context,=20
+    file =3D krb5_config_get_string(context,
 				  NULL,
 				  "kdc",
 				  "pkinit_mappings_file",
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/process.c
--- a/head/crypto/heimdal/kdc/process.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/process.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  *
- * All rights reserved.=20
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: process.c 20959 2007-06-07 04:46:06Z lha $");
-
 /*
  *
  */
@@ -49,66 +47,167 @@
 	_kdc_now =3D *tv;
 }
=20
+static krb5_error_code
+kdc_as_req(krb5_context context,
+	   krb5_kdc_configuration *config,
+	   krb5_data *req_buffer,
+	   krb5_data *reply,
+	   const char *from,
+	   struct sockaddr *addr,
+	   int datagram_reply,
+	   int *claim)
+{
+    krb5_error_code ret;
+    KDC_REQ req;
+    size_t len;
+
+    ret =3D decode_AS_REQ(req_buffer->data, req_buffer->length, &req, &len=
);
+    if (ret)
+	return ret;
+
+    *claim =3D 1;
+
+    ret =3D _kdc_as_rep(context, config, &req, req_buffer,
+		      reply, from, addr, datagram_reply);
+    free_AS_REQ(&req);
+    return ret;
+}
+
+
+static krb5_error_code
+kdc_tgs_req(krb5_context context,
+	    krb5_kdc_configuration *config,
+	    krb5_data *req_buffer,
+	    krb5_data *reply,
+	    const char *from,
+	    struct sockaddr *addr,
+	    int datagram_reply,
+	    int *claim)
+{
+    krb5_error_code ret;
+    KDC_REQ req;
+    size_t len;
+
+    ret =3D decode_TGS_REQ(req_buffer->data, req_buffer->length, &req, &le=
n);
+    if (ret)
+	return ret;
+
+    *claim =3D 1;
+
+    ret =3D _kdc_tgs_rep(context, config, &req, reply,
+		       from, addr, datagram_reply);
+    free_TGS_REQ(&req);
+    return ret;
+}
+
+#ifdef DIGEST
+
+static krb5_error_code
+kdc_digest(krb5_context context,
+	   krb5_kdc_configuration *config,
+	   krb5_data *req_buffer,
+	   krb5_data *reply,
+	   const char *from,
+	   struct sockaddr *addr,
+	   int datagram_reply,
+	   int *claim)
+{
+    DigestREQ digestreq;
+    krb5_error_code ret;
+    size_t len;
+
+    ret =3D decode_DigestREQ(req_buffer->data, req_buffer->length,
+			   &digestreq, &len);
+    if (ret)
+	return ret;
+
+    *claim =3D 1;
+
+    ret =3D _kdc_do_digest(context, config, &digestreq, reply, from, addr);
+    free_DigestREQ(&digestreq);
+    return ret;
+}
+
+#endif
+
+#ifdef KX509
+
+static krb5_error_code
+kdc_kx509(krb5_context context,
+	  krb5_kdc_configuration *config,
+	  krb5_data *req_buffer,
+	  krb5_data *reply,
+	  const char *from,
+	  struct sockaddr *addr,
+	  int datagram_reply,
+	  int *claim)
+{
+    Kx509Request kx509req;
+    krb5_error_code ret;
+    size_t len;
+
+    ret =3D _kdc_try_kx509_request(req_buffer->data, req_buffer->length,
+				 &kx509req, &len);
+    if (ret)
+	return ret;
+
+    *claim =3D 1;
+
+    ret =3D _kdc_do_kx509(context, config, &kx509req, reply, from, addr);
+    free_Kx509Request(&kx509req);
+    return ret;
+}
+
+#endif
+
+
+static struct krb5_kdc_service services[] =3D  {
+    { KS_KRB5,		kdc_as_req },
+    { KS_KRB5,		kdc_tgs_req },
+#ifdef DIGEST
+    { 0,		kdc_digest },
+#endif
+#ifdef KX509
+    { 0,		kdc_kx509 },
+#endif
+    { 0, NULL }
+};
+
 /*
  * handle the request in `buf, len', from `addr' (or `from' as a string),
  * sending a reply in `reply'.
  */
=20
 int
-krb5_kdc_process_request(krb5_context context,=20
+krb5_kdc_process_request(krb5_context context,
 			 krb5_kdc_configuration *config,
-			 unsigned char *buf,=20
-			 size_t len,=20
+			 unsigned char *buf,
+			 size_t len,
 			 krb5_data *reply,
 			 krb5_boolean *prependlength,
 			 const char *from,
 			 struct sockaddr *addr,
 			 int datagram_reply)
 {
-    KDC_REQ req;
-    Ticket ticket;
-    DigestREQ digestreq;
-    Kx509Request kx509req;
     krb5_error_code ret;
-    size_t i;
+    unsigned int i;
+    krb5_data req_buffer;
+    int claim =3D 0;
=20
-    if(decode_AS_REQ(buf, len, &req, &i) =3D=3D 0){
-	krb5_data req_buffer;
+    req_buffer.data =3D buf;
+    req_buffer.length =3D len;
=20
-	req_buffer.data =3D buf;
-	req_buffer.length =3D len;
+    for (i =3D 0; services[i].process !=3D NULL; i++) {
+	ret =3D (*services[i].process)(context, config, &req_buffer,
+				     reply, from, addr, datagram_reply,
+				     &claim);
+	if (claim) {
+	    if (services[i].flags & KS_NO_LENGTH)
+		*prependlength =3D 0;
+	    return ret;
+	}
+    }
=20
-	ret =3D _kdc_as_rep(context, config, &req, &req_buffer,=20
-			  reply, from, addr, datagram_reply);
-	free_AS_REQ(&req);
-	return ret;
-    }else if(decode_TGS_REQ(buf, len, &req, &i) =3D=3D 0){
-	ret =3D _kdc_tgs_rep(context, config, &req, reply, from, addr, datagram_r=
eply);
-	free_TGS_REQ(&req);
-	return ret;
-    }else if(decode_Ticket(buf, len, &ticket, &i) =3D=3D 0){
-	ret =3D _kdc_do_524(context, config, &ticket, reply, from, addr);
-	free_Ticket(&ticket);
-	return ret;
-    }else if(decode_DigestREQ(buf, len, &digestreq, &i) =3D=3D 0){
-	ret =3D _kdc_do_digest(context, config, &digestreq, reply, from, addr);
-	free_DigestREQ(&digestreq);
-	return ret;
-    } else if (_kdc_try_kx509_request(buf, len, &kx509req, &i) =3D=3D 0) {
-	ret =3D _kdc_do_kx509(context, config, &kx509req, reply, from, addr);
-	free_Kx509Request(&kx509req);
-	return ret;
-    } else if(_kdc_maybe_version4(buf, len)){
-	*prependlength =3D FALSE; /* elbitapmoc sdrawkcab XXX */
-	_kdc_do_version4(context, config, buf, len, reply, from,=20
-			 (struct sockaddr_in*)addr);
-	return 0;
-    } else if (config->enable_kaserver) {
-	ret =3D _kdc_do_kaserver(context, config, buf, len, reply, from,
-			       (struct sockaddr_in*)addr);
-	return ret;
-    }
-			 =20
     return -1;
 }
=20
@@ -120,34 +219,33 @@
  */
=20
 int
-krb5_kdc_process_krb5_request(krb5_context context,=20
+krb5_kdc_process_krb5_request(krb5_context context,
 			      krb5_kdc_configuration *config,
-			      unsigned char *buf,=20
-			      size_t len,=20
+			      unsigned char *buf,
+			      size_t len,
 			      krb5_data *reply,
 			      const char *from,
 			      struct sockaddr *addr,
 			      int datagram_reply)
 {
-    KDC_REQ req;
     krb5_error_code ret;
-    size_t i;
+    unsigned int i;
+    krb5_data req_buffer;
+    int claim =3D 0;
=20
-    if(decode_AS_REQ(buf, len, &req, &i) =3D=3D 0){
-	krb5_data req_buffer;
+    req_buffer.data =3D buf;
+    req_buffer.length =3D len;
=20
-	req_buffer.data =3D buf;
-	req_buffer.length =3D len;
+    for (i =3D 0; services[i].process !=3D NULL; i++) {
+	if ((services[i].flags & KS_KRB5) =3D=3D 0)
+	    continue;
+	ret =3D (*services[i].process)(context, config, &req_buffer,
+				     reply, from, addr, datagram_reply,
+				     &claim);
+	if (claim)
+	    return ret;
+    }
=20
-	ret =3D _kdc_as_rep(context, config, &req, &req_buffer,
-			  reply, from, addr, datagram_reply);
-	free_AS_REQ(&req);
-	return ret;
-    }else if(decode_TGS_REQ(buf, len, &req, &i) =3D=3D 0){
-	ret =3D _kdc_tgs_rep(context, config, &req, reply, from, addr, datagram_r=
eply);
-	free_TGS_REQ(&req);
-	return ret;
-    }
     return -1;
 }
=20
@@ -156,7 +254,7 @@
  */
=20
 int
-krb5_kdc_save_request(krb5_context context,=20
+krb5_kdc_save_request(krb5_context context,
 		      const char *fn,
 		      const unsigned char *buf,
 		      size_t len,
@@ -177,14 +275,15 @@
=20
     fd =3D open(fn, O_WRONLY|O_CREAT|O_APPEND, 0600);
     if (fd < 0) {
-	krb5_set_error_string(context, "Failed to open: %s", fn);
-	return errno;
+	int saved_errno =3D errno;
+	krb5_set_error_message(context, saved_errno, "Failed to open: %s", fn);
+	return saved_errno;
     }
-   =20
+
     sp =3D krb5_storage_from_fd(fd);
     close(fd);
     if (sp =3D=3D NULL) {
-	krb5_set_error_string(context, "Storage failed to open fd");
+	krb5_set_error_message(context, ENOMEM, "Storage failed to open fd");
 	return ENOMEM;
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/rx.h
--- a/head/crypto/heimdal/kdc/rx.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/rx.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: rx.h 17447 2006-05-05 10:52:01Z lha $ */
+/* $Id$ */
=20
 #ifndef __RX_H__
 #define __RX_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/set_dbinfo.c
--- a/head/crypto/heimdal/kdc/set_dbinfo.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/set_dbinfo.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,68 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * All rights reserved.=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: default_config.c 21296 2007-06-25 14:49:11Z lha $");
+static krb5_error_code
+add_db(krb5_context context, struct krb5_kdc_configuration *c,
+       const char *conf, const char *master_key)
+{
+    krb5_error_code ret;
+    void *ptr;
+
+    ptr =3D realloc(c->db, (c->num_db + 1) * sizeof(*c->db));
+    if (ptr =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	return ENOMEM;
+    }
+    c->db =3D ptr;
+
+    ret =3D hdb_create(context, &c->db[c->num_db], conf);
+    if(ret)
+	return ret;
+
+    c->num_db++;
+
+    if (master_key) {
+	ret =3D hdb_set_master_keyfile(context, c->db[c->num_db - 1], master_key);
+	if (ret)
+	    return ret;
+    }
+
+    return 0;
+}
=20
 krb5_error_code
 krb5_kdc_set_dbinfo(krb5_context context, struct krb5_kdc_configuration *c)
@@ -47,30 +75,15 @@
     ret =3D hdb_get_dbinfo(context, &info);
     if (ret)
 	return ret;
-   =20
+
     d =3D NULL;
     while ((d =3D hdb_dbinfo_get_next(info, d)) !=3D NULL) {
-	void *ptr;
-=09
-	ptr =3D realloc(c->db, (c->num_db + 1) * sizeof(*c->db));
-	if (ptr =3D=3D NULL) {
-	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "out of memory");
-	    goto out;
-	}
-	c->db =3D ptr;
-=09
-	ret =3D hdb_create(context, &c->db[c->num_db],=20
-			 hdb_dbinfo_get_dbname(context, d));
-	if(ret)
-	    goto out;
-=09
-	ret =3D hdb_set_master_keyfile(context, c->db[c->num_db],=20
-				     hdb_dbinfo_get_mkey_file(context, d));
+
+	ret =3D add_db(context, c,
+		     hdb_dbinfo_get_dbname(context, d),
+		     hdb_dbinfo_get_mkey_file(context, d));
 	if (ret)
 	    goto out;
-=09
-	c->num_db++;
=20
 	kdc_log(context, c, 0, "label: %s",
 		hdb_dbinfo_get_label(context, d));
@@ -91,7 +104,7 @@
     c->num_db =3D 0;
     free(c->db);
     c->db =3D NULL;
-=20
+
     hdb_free_dbinfo(context, &info);
=20
     return ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/string2key.8
--- a/head/crypto/heimdal/kdc/string2key.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/string2key.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2000 - 2002 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2000 - 2002 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: string2key.8 11648 2003-02-16 21:10:32Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd March  4, 2000
 .Dt STRING2KEY 8
@@ -39,23 +39,23 @@
 .Nd map a password into a key
 .Sh SYNOPSIS
 .Nm
-.Op Fl 5 | Fl -version5
-.Op Fl 4 | Fl -version4
-.Op Fl a | Fl -afs
+.Op Fl 5 | Fl Fl version5
+.Op Fl 4 | Fl Fl version4
+.Op Fl a | Fl Fl afs
 .Oo Fl c Ar cell \*(Ba Xo
-.Fl -cell=3D Ns Ar cell
+.Fl Fl cell=3D Ns Ar cell
 .Xc
 .Oc
 .Oo Fl w Ar password \*(Ba Xo
-.Fl -password=3D Ns Ar password
+.Fl Fl password=3D Ns Ar password
 .Xc
 .Oc
 .Oo Fl p Ar principal \*(Ba Xo
-.Fl -principal=3D Ns Ar principal
+.Fl Fl principal=3D Ns Ar principal
 .Xc
 .Oc
 .Oo Fl k Ar string \*(Ba Xo
-.Fl -keytype=3D Ns Ar string
+.Fl Fl keytype=3D Ns Ar string
 .Xc
 .Oc
 .Ar password
@@ -65,46 +65,21 @@
 This is useful when you want to handle the raw key instead of the password.
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl 5 ,
-.Fl -version5
-.Xc
+.It Fl 5 , Fl Fl version5
 Output Kerberos v5 string-to-key
-.It Xo
-.Fl 4 ,
-.Fl -version4
-.Xc
+.It Fl 4 , Fl Fl version4
 Output Kerberos v4 string-to-key
-.It Xo
-.Fl a ,
-.Fl -afs
-.Xc
+.It Fl a , Fl Fl afs
 Output AFS string-to-key
-.It Xo
-.Fl c Ar cell ,
-.Fl -cell=3D Ns Ar cell
-.Xc
+.It Fl c Ar cell , Fl Fl cell=3D Ns Ar cell
 AFS cell to use
-.It Xo
-.Fl w Ar password ,
-.Fl -password=3D Ns Ar password
-.Xc
+.It Fl w Ar password , Fl Fl password=3D Ns Ar password
 Password to use
-.It Xo
-.Fl p Ar principal ,
-.Fl -principal=3D Ns Ar principal
-.Xc
+.It Fl p Ar principal , Fl Fl principal=3D Ns Ar principal
 Kerberos v5 principal to use
-.It Xo
-.Fl k Ar string ,
-.Fl -keytype=3D Ns Ar string
-.Xc
+.It Fl k Ar string , Fl Fl keytype=3D Ns Ar string
 Keytype
-.It Xo
-.Fl -version
-.Xc
+.It Fl Fl version
 print version
-.It Xo
-.Fl -help
-.Xc
+.It Fl Fl help
 .El
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/string2key.c
--- a/head/crypto/heimdal/kdc/string2key.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/string2key.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "headers.h"
 #include <getarg.h>
=20
-RCSID("$Id: string2key.c 19213 2006-12-04 23:36:36Z lha $");
-
 int version5;
 int version4;
 int afs;
@@ -47,15 +45,17 @@
 int help;
=20
 struct getargs args[] =3D {
-    { "version5", '5', arg_flag,   &version5, "Output Kerberos v5 string-t=
o-key" },
-    { "version4", '4', arg_flag,   &version4, "Output Kerberos v4 string-t=
o-key" },
-    { "afs",      'a', arg_flag,   &afs, "Output AFS string-to-key" },
+    { "version5", '5', arg_flag,   &version5, "Output Kerberos v5 string-t=
o-key",
+	NULL },
+    { "version4", '4', arg_flag,   &version4, "Output Kerberos v4 string-t=
o-key",
+	NULL },
+    { "afs",      'a', arg_flag,   &afs, "Output AFS string-to-key", NULL =
},
     { "cell",     'c', arg_string, &cell, "AFS cell to use", "cell" },
     { "password", 'w', arg_string, &password, "Password to use", "password=
" },
     { "principal",'p', arg_string, &principal, "Kerberos v5 principal to u=
se", "principal" },
-    { "keytype",  'k', arg_string, &keytype_str, "Keytype" },
-    { "version",    0, arg_flag,   &version, "print version" },
-    { "help",       0, arg_flag,   &help, NULL }
+    { "keytype",  'k', arg_string, rk_UNCONST(&keytype_str), "Keytype", NU=
LL },
+    { "version",    0, arg_flag,   &version, "print version", NULL },
+    { "help",       0, arg_flag,   &help, NULL, NULL }
 };
=20
 int num_args =3D sizeof(args) / sizeof(args[0]);
@@ -68,14 +68,14 @@
 }
=20
 static void
-tokey(krb5_context context,=20
-      krb5_enctype enctype,=20
-      const char *pw,=20
-      krb5_salt salt,=20
+tokey(krb5_context context,
+      krb5_enctype enctype,
+      const char *pw,
+      krb5_salt salt,
       const char *label)
 {
     krb5_error_code ret;
-    int i;
+    size_t i;
     krb5_keyblock key;
     char *e;
=20
@@ -109,7 +109,7 @@
=20
     if(help)
 	usage(0);
-   =20
+
     if(version){
 	print_version (NULL);
 	return 0;
@@ -125,26 +125,9 @@
 	version5 =3D 1;
=20
     ret =3D krb5_string_to_enctype(context, keytype_str, &etype);
-    if(ret) {
-	krb5_keytype keytype;
-	int *etypes;
-	unsigned num;
-	char *str;
-	ret =3D krb5_string_to_keytype(context, keytype_str, &keytype);
-	if(ret)
-	    krb5_err(context, 1, ret, "%s", keytype_str);
-	ret =3D krb5_keytype_to_enctypes(context, keytype, &num, &etypes);
-	if(ret)
-	    krb5_err(context, 1, ret, "%s", keytype_str);
-	if(num =3D=3D 0)
-	    krb5_errx(context, 1, "there are no encryption types for that keytype=
");
-	etype =3D etypes[0];
-	krb5_enctype_to_string(context, etype, &str);
-	keytype_str =3D str;
-	if(num > 1 && version5)
-	    krb5_warnx(context, "ambiguous keytype, using %s", keytype_str);
-    }
-   =20
+    if(ret)
+	krb5_err(context, 1, ret, "krb5_string_to_enctype");
+
     if((etype !=3D ETYPE_DES_CBC_CRC &&
 	etype !=3D ETYPE_DES_CBC_MD4 &&
 	etype !=3D ETYPE_DES_CBC_MD5) &&
@@ -152,7 +135,7 @@
 	if(!version5) {
 	    etype =3D ETYPE_DES_CBC_CRC;
 	} else {
-	    krb5_errx(context, 1,=20
+	    krb5_errx(context, 1,
 		      "DES is the only valid keytype for AFS and Kerberos 4");
 	}
     }
@@ -178,7 +161,7 @@
 	    return 1;
 	password =3D buf;
     }
-=09
+
     if(version5){
 	krb5_parse_name(context, principal, &princ);
 	krb5_get_pw_salt(context, princ, &salt);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/version-script=
.map
--- a/head/crypto/heimdal/kdc/version-script.map	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/kdc/version-script.map	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-# $Id: version-script.map 21110 2007-06-18 10:52:20Z lha $
+# $Id$
=20
 HEIMDAL_KDC_1.0 {
 	global:
@@ -6,13 +6,20 @@
 		kdc_log_msg;
 		kdc_log_msg_va;
 		kdc_openlog;
+		kdc_check_flags;
 		krb5_kdc_windc_init;
 		krb5_kdc_get_config;
+		krb5_kdc_pkinit_config;
 		krb5_kdc_set_dbinfo;
 		krb5_kdc_process_krb5_request;
 		krb5_kdc_process_request;
 		krb5_kdc_save_request;
 		krb5_kdc_update_time;
+		krb5_kdc_pk_initialize;
+
+		# needed for digest-service
+		_kdc_db_fetch;
+		_kdc_free_ent;
 	local:
 		*;
 };
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/windc.c
--- a/head/crypto/heimdal/kdc/windc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/windc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kdc_locl.h"
=20
-RCSID("$Id: windc.c 20559 2007-04-24 16:00:07Z lha $");
-
 static krb5plugin_windc_ftable *windcft;
 static void *windcctx;
=20
@@ -55,15 +53,15 @@
     for (e =3D list; e !=3D NULL; e =3D _krb5_plugin_get_next(e)) {
=20
 	windcft =3D _krb5_plugin_get_symbol(e);
-	if (windcft->minor_version < KRB5_WINDC_PLUGING_MINOR)
+	if (windcft->minor_version < KRB5_WINDC_PLUGIN_MINOR)
 	    continue;
-=09
+
 	(*windcft->init)(context, &windcctx);
 	break;
     }
+    _krb5_plugin_free(list);
     if (e =3D=3D NULL) {
-	_krb5_plugin_free(list);
-	krb5_set_error_string(context, "Did not find any WINDC plugin");
+	krb5_set_error_message(context, ENOENT, "Did not find any WINDC plugin");
 	windcft =3D NULL;
 	return ENOENT;
     }
@@ -72,9 +70,9 @@
 }
=20
=20
-krb5_error_code=20
+krb5_error_code
 _kdc_pac_generate(krb5_context context,
-		  hdb_entry_ex *client,=20
+		  hdb_entry_ex *client,
 		  krb5_pac *pac)
 {
     *pac =3D NULL;
@@ -83,27 +81,47 @@
     return (windcft->pac_generate)(windcctx, context, client, pac);
 }
=20
-krb5_error_code=20
-_kdc_pac_verify(krb5_context context,=20
+krb5_error_code
+_kdc_pac_verify(krb5_context context,
 		const krb5_principal client_principal,
+		const krb5_principal delegated_proxy_principal,
 		hdb_entry_ex *client,
 		hdb_entry_ex *server,
-		krb5_pac *pac)
+		hdb_entry_ex *krbtgt,
+		krb5_pac *pac,
+		int *verified)
 {
-    if (windcft =3D=3D NULL) {
-	krb5_set_error_string(context, "Can't verify PAC, no function");
-	return EINVAL;
-    }
-    return (windcft->pac_verify)(windcctx, context,=20
-				 client_principal, client, server, pac);
+    krb5_error_code ret;
+
+    if (windcft =3D=3D NULL)
+	return 0;
+
+    ret =3D windcft->pac_verify(windcctx, context,
+			      client_principal,
+			      delegated_proxy_principal,
+			      client, server, krbtgt, pac);
+    if (ret =3D=3D 0)
+	*verified =3D 1;
+    return ret;
 }
=20
 krb5_error_code
-_kdc_windc_client_access(krb5_context context,
-			 struct hdb_entry_ex *client,
-			 KDC_REQ *req)
+_kdc_check_access(krb5_context context,
+		  krb5_kdc_configuration *config,
+		  hdb_entry_ex *client_ex, const char *client_name,
+		  hdb_entry_ex *server_ex, const char *server_name,
+		  KDC_REQ *req,
+		  krb5_data *e_data)
 {
     if (windcft =3D=3D NULL)
-	return 0;
-    return (windcft->client_access)(windcctx, context, client, req);
+	    return kdc_check_flags(context, config,
+				   client_ex, client_name,
+				   server_ex, server_name,
+				   req->msg_type =3D=3D krb_as_req);
+
+    return (windcft->client_access)(windcctx,
+				    context, config,
+				    client_ex, client_name,
+				    server_ex, server_name,
+				    req, e_data);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kdc/windc_plugin.h
--- a/head/crypto/heimdal/kdc/windc_plugin.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kdc/windc_plugin.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: windc_plugin.h 19798 2007-01-10 15:24:51Z lha $ */
+/* $Id$ */
=20
 #ifndef HEIMDAL_KRB5_PAC_PLUGIN_H
 #define HEIMDAL_KRB5_PAC_PLUGIN_H 1
@@ -51,23 +51,30 @@
=20
 struct hdb_entry_ex;
=20
-typedef krb5_error_code=20
+typedef krb5_error_code
 (*krb5plugin_windc_pac_generate)(void *, krb5_context,
 				 struct hdb_entry_ex *, krb5_pac *);
=20
-typedef krb5_error_code=20
+typedef krb5_error_code
 (*krb5plugin_windc_pac_verify)(void *, krb5_context,
-			       const krb5_principal,
-			       struct hdb_entry_ex *,=20
-			       struct hdb_entry_ex *,
+			       const krb5_principal, /* new ticket client */
+			       const krb5_principal, /* delegation proxy */
+			       struct hdb_entry_ex *,/* client */
+			       struct hdb_entry_ex *,/* server */
+			       struct hdb_entry_ex *,/* krbtgt */
 			       krb5_pac *);
=20
-typedef krb5_error_code=20
+typedef krb5_error_code
 (*krb5plugin_windc_client_access)(
-    void *, krb5_context, struct hdb_entry_ex *, KDC_REQ *);
+	void *, krb5_context,
+	krb5_kdc_configuration *config,
+	hdb_entry_ex *, const char *,
+	hdb_entry_ex *, const char *,
+	KDC_REQ *, krb5_data *);
=20
=20
-#define KRB5_WINDC_PLUGING_MINOR		2
+#define KRB5_WINDC_PLUGIN_MINOR			6
+#define KRB5_WINDC_PLUGING_MINOR KRB5_WINDC_PLUGIN_MINOR
=20
 typedef struct krb5plugin_windc_ftable {
     int			minor_version;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/Makefile.am
--- a/head/crypto/heimdal/kpasswd/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kpasswd/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -19,7 +19,6 @@
 kpasswdd_LDADD =3D \
 	$(top_builddir)/lib/kadm5/libkadm5srv.la \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(LDADD) \
 	$(LIB_pidfile) \
 	$(LIB_dlopen) \
@@ -30,4 +29,4 @@
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/Makefile.in
--- a/head/crypto/heimdal/kpasswd/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kpasswd/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -47,7 +49,7 @@
 subdir =3D kpasswd
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -62,7 +64,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -76,9 +78,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -86,16 +91,15 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" \
 	"$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS) $(libexec_PROGRAMS) $(noinst_PROGRAMS)
 am_kpasswd_OBJECTS =3D kpasswd.$(OBJEXT)
 kpasswd_OBJECTS =3D $(am_kpasswd_OBJECTS)
@@ -116,12 +120,12 @@
 	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
 	$(am__DEPENDENCIES_1)
 kpasswdd_DEPENDENCIES =3D $(top_builddir)/lib/kadm5/libkadm5srv.la \
-	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_2) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -134,6 +138,27 @@
 SOURCES =3D $(kpasswd_SOURCES) kpasswd-generator.c $(kpasswdd_SOURCES)
 DIST_SOURCES =3D $(kpasswd_SOURCES) kpasswd-generator.c \
 	$(kpasswdd_SOURCES)
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
@@ -144,49 +169,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -210,10 +244,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -230,6 +265,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -245,31 +282,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -284,10 +335,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -328,30 +381,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_hcrypto)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 man_MANS =3D kpasswd.1 kpasswdd.8
 kpasswd_SOURCES =3D kpasswd.c kpasswd_locl.h
@@ -359,7 +416,6 @@
 kpasswdd_LDADD =3D \
 	$(top_builddir)/lib/kadm5/libkadm5srv.la \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(LDADD) \
 	$(LIB_pidfile) \
 	$(LIB_dlopen) \
@@ -370,23 +426,23 @@
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS)
+EXTRA_DIST =3D NTMakefile $(man_MANS)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps kpasswd/M=
akefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps kpasswd/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign kpasswd/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign kpasswd/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -404,69 +460,102 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 kpasswd$(EXEEXT): $(kpasswd_OBJECTS) $(kpasswd_DEPENDENCIES)=20
 	@rm -f kpasswd$(EXEEXT)
 	$(LINK) $(kpasswd_OBJECTS) $(kpasswd_LDADD) $(LIBS)
@@ -483,160 +572,179 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kpasswd-generator.Po at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kpasswd.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kpasswdd.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
-install-man8: $(man8_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -652,13 +760,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -693,6 +805,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -703,6 +816,7 @@
 	clean-libtool clean-noinstPROGRAMS mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -713,6 +827,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -720,26 +836,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -760,11 +885,10 @@
 	uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1 uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libexecPROGRAMS \
@@ -853,6 +977,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -938,7 +1065,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -951,6 +1078,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/kpasswd-ge=
nerator.c
--- a/head/crypto/heimdal/kpasswd/kpasswd-generator.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/kpasswd/kpasswd-generator.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 2000 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kpasswd_locl.h"
=20
-RCSID("$Id: kpasswd-generator.c 19233 2006-12-06 08:04:05Z lha $");
+RCSID("$Id$");
=20
 static unsigned
 read_words (const char *filename, char ***ret_w)
@@ -58,6 +58,7 @@
     *ret_w =3D w;
     if (n =3D=3D 0)
 	errx(1, "%s is an empty file, no words to try", filename);
+    fclose(f);
     return n;
 }
=20
@@ -140,10 +141,14 @@
=20
 	krb5_free_principal (context, principal);
=20
-	ret =3D krb5_change_password (context, &cred, new_pwd,
-				    &result_code,
-				    &result_code_string,
-				    &result_string);
+
+	ret =3D krb5_set_password (context,
+				 &cred,
+				 new_pwd,
+				 NULL,
+				 &result_code,
+				 &result_code_string,
+				 &result_string);
 	if (ret)
 	    krb5_err (context, 1, ret, "krb5_change_password");
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/kpasswd.1
--- a/head/crypto/heimdal/kpasswd/kpasswd.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kpasswd/kpasswd.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 1997, 2000 - 2005 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1997, 2000 - 2005 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: kpasswd.1 14478 2005-01-05 16:08:58Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd January  5, 2005
 .Dt KPASSWD 1
@@ -39,9 +39,9 @@
 .Nd Kerberos 5 password changing program
 .Sh SYNOPSIS
 .Nm
-.Op Fl -admin-principal=3D Ns Ar principal
+.Op Fl Fl admin-principal=3D Ns Ar principal
 .Oo Fl c Ar cache \*(Ba Xo
-.Fl -cache=3D Ns Ar cache
+.Fl Fl cache=3D Ns Ar cache
 .Xc
 .Oc
 .Op Ar principal ...
@@ -58,7 +58,7 @@
 principal of the default credential cache will be used.
 .Pp
 If a credential cache is given, the
-.Fl -admin-principal
+.Fl Fl admin-principal
 flag is ignored and use the default name of the credential cache is
 used instead.
 .Sh DIAGNOSTICS
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/kpasswd.c
--- a/head/crypto/heimdal/kpasswd/kpasswd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kpasswd/kpasswd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kpasswd_locl.h"
-RCSID("$Id: kpasswd.c 19078 2006-11-20 18:12:41Z lha $");
+RCSID("$Id$");
=20
 static int version_flag;
 static int help_flag;
@@ -40,10 +40,11 @@
 static char *cred_cache_str;
=20
 static struct getargs args[] =3D {
-    { "admin-principal",	0,   arg_string, &admin_principal_str },
-    { "cache",			'c', arg_string, &cred_cache_str },
-    { "version", 		0,   arg_flag, &version_flag },
-    { "help",			0,   arg_flag, &help_flag }
+    { "admin-principal",	0,   arg_string, &admin_principal_str, NULL,
+   	 NULL },
+    { "cache",			'c', arg_string, &cred_cache_str, NULL, NULL },
+    { "version", 		0,   arg_flag, &version_flag, NULL, NULL },
+    { "help",			0,   arg_flag, &help_flag, NULL, NULL }
 };
=20
 static void
@@ -117,33 +118,32 @@
     krb5_error_code ret;
     krb5_context context;
     krb5_principal principal;
-    int optind =3D 0;
     krb5_get_init_creds_opt *opt;
     krb5_ccache id =3D NULL;
     int exit_value;
+    int optidx =3D 0;
=20
-    optind =3D krb5_program_setup(&context, argc, argv,
-				args, sizeof(args) / sizeof(args[0]), usage);
+    setprogname(argv[0]);
=20
+    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+	usage(1, args, sizeof(args) / sizeof(args[0]));
     if (help_flag)
-	usage (0, args, sizeof(args) / sizeof(args[0]));
-
-    if(version_flag){
-	print_version (NULL);
-	exit(0);
+	usage(0, args, sizeof(args) / sizeof(args[0]));
+    if (version_flag) {
+	print_version(NULL);
+	return 0;
     }
-
-    argc -=3D optind;
-    argv +=3D optind;
+    argc -=3D optidx;
+    argv +=3D optidx;
=20
     ret =3D krb5_init_context (&context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
- =20
+
     ret =3D krb5_get_init_creds_opt_alloc (context, &opt);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");
-   =20
+
     krb5_get_init_creds_opt_set_tkt_life (opt, 300);
     krb5_get_init_creds_opt_set_forwardable (opt, FALSE);
     krb5_get_init_creds_opt_set_proxiable (opt, FALSE);
@@ -153,9 +153,9 @@
 	if (ret)
 	    krb5_err (context, 1, ret, "krb5_cc_resolve");
     } else {
-	ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &id);
+	ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
 	if (ret)
-	    krb5_err (context, 1, ret, "krb5_cc_gen_new");
+	    krb5_err (context, 1, ret, "krb5_cc_new_unique");
     }
=20
     if (cred_cache_str =3D=3D NULL) {
@@ -198,18 +198,18 @@
 	default:
 	    krb5_err(context, 1, ret, "krb5_get_init_creds");
 	}
-=09
+
 	krb5_get_init_creds_opt_free(context, opt);
-=09
+
 	ret =3D krb5_cc_initialize(context, id, admin_principal);
 	krb5_free_principal(context, admin_principal);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_cc_initialize");
=20
-	ret =3D krb5_cc_store_cred(context, id, &cred);   =20
+	ret =3D krb5_cc_store_cred(context, id, &cred);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_cc_store_cred");
-=09
+
 	krb5_free_cred_contents (context, &cred);
     }
=20
@@ -243,5 +243,5 @@
     }
=20
     krb5_free_context (context);
-    return ret;
+    return exit_value;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/kpasswd_lo=
cl.h
--- a/head/crypto/heimdal/kpasswd/kpasswd_locl.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/kpasswd/kpasswd_locl.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: kpasswd_locl.h 11444 2002-09-10 20:03:49Z joda $ */
+/* $Id$ */
=20
 #ifndef __KPASSWD_LOCL_H__
 #define __KPASSWD_LOCL_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/kpasswdd.8
--- a/head/crypto/heimdal/kpasswd/kpasswdd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kpasswd/kpasswdd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,33 @@
-.\" $Id: kpasswdd.8 14481 2005-01-05 18:07:44Z lha $
+.\" Copyright (c) 1997, 2000 - 2005 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
+.\"
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
+.\"
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
 .\"
 .Dd April 19, 1999
 .Dt KPASSWDD 8
@@ -9,23 +38,23 @@
 .Sh SYNOPSIS
 .Nm
 .Bk -words
-.Op Fl -addresses=3D Ns Ar address
-.Op Fl -check-library=3D Ns Ar library
-.Op Fl -check-function=3D Ns Ar function
+.Op Fl Fl addresses=3D Ns Ar address
+.Op Fl Fl check-library=3D Ns Ar library
+.Op Fl Fl check-function=3D Ns Ar function
 .Oo Fl k Ar kspec \*(Ba Xo
-.Fl -keytab=3D Ns Ar kspec
+.Fl Fl keytab=3D Ns Ar kspec
 .Xc
 .Oc
 .Oo Fl r Ar realm \*(Ba Xo
-.Fl -realm=3D Ns Ar realm
+.Fl Fl realm=3D Ns Ar realm
 .Xc
 .Oc
 .Oo Fl p Ar string \*(Ba Xo
-.Fl -port=3D Ns Ar string
+.Fl Fl port=3D Ns Ar string
 .Xc
 .Oc
-.Op Fl -version
-.Op Fl -help
+.Op Fl Fl version
+.Op Fl Fl help
 .Ek
 .Sh DESCRIPTION
 .Nm
@@ -35,20 +64,14 @@
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl -addresses=3D Ns Ar address
-.Xc
+.It Fl Fl addresses=3D Ns Ar address
 For each till the argument is given, add the address to what kpasswdd
 should listen too.
-.It Xo
-.Fl -check-library=3D Ns Ar library
-.Xc
+.It Fl Fl check-library=3D Ns Ar library
 If your system has support for dynamic loading of shared libraries,
 you can use an external function to check password quality. This
 option specifies which library to load.
-.It Xo
-.Fl -check-function=3D Ns Ar function
-.Xc
+.It Fl Fl check-function=3D Ns Ar function
 This is the function to call in the loaded library. The function
 should look like this:
 .Pp
@@ -63,20 +86,11 @@
 is the new password. Note that the password (in
 .Fa password->data )
 is not zero terminated.
-.It Xo
-.Fl k Ar kspec ,
-.Fl -keytab=3D Ns Ar kspec
-.Xc
+.It Fl k Ar kspec , Fl Fl keytab=3D Ns Ar kspec
 Keytab to get authentication key from.
-.It Xo
-.Fl r Ar realm ,
-.Fl -realm=3D Ns Ar realm
-.Xc
+.It Fl r Ar realm , Fl Fl realm=3D Ns Ar realm
 Default realm.
-.It Xo
-.Fl p Ar string ,
-.Fl -port=3D Ns Ar string
-.Xc
+.It Fl p Ar string , Fl Fl port=3D Ns Ar string
 Port to listen on (default service kpasswd - 464).
 .El
 .Sh DIAGNOSTICS
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kpasswd/kpasswdd.c
--- a/head/crypto/heimdal/kpasswd/kpasswdd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kpasswd/kpasswdd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kpasswd_locl.h"
-RCSID("$Id: kpasswdd.c 22252 2007-12-09 05:59:34Z lha $");
+RCSID("$Id$");
=20
 #include <kadm5/admin.h>
 #ifdef HAVE_SYS_UN_H
@@ -244,14 +244,14 @@
     const char *pwd_reason;
     kadm5_config_params conf;
     void *kadm5_handle =3D NULL;
-    krb5_principal principal;
+    krb5_principal principal =3D NULL;
     krb5_data *pwd_data =3D NULL;
     char *tmp;
     ChangePasswdDataMS chpw;
=20
     memset (&conf, 0, sizeof(conf));
     memset(&chpw, 0, sizeof(chpw));
-   =20
+
     if (version =3D=3D KRB5_KPASSWD_VERS_CHANGEPW) {
 	ret =3D krb5_copy_data(context, in_data, &pwd_data);
 	if (ret) {
@@ -272,7 +272,7 @@
 			"malformed ChangePasswdData");
 	    return;
 	}
-=09
+
=20
 	ret =3D krb5_copy_data(context, &chpw.newpasswd, &pwd_data);
 	if (ret) {
@@ -284,7 +284,7 @@
=20
 	if (chpw.targname =3D=3D NULL && chpw.targrealm !=3D NULL) {
 	    krb5_warn (context, ret, "kadm5_init_with_password_ctx");
-	    reply_priv (auth_context, s, sa, sa_size,=20
+	    reply_priv (auth_context, s, sa, sa_size,
 			KRB5_KPASSWD_MALFORMED,
 			"targrealm but not targname");
 	    goto out;
@@ -299,10 +299,10 @@
 		ret =3D krb5_get_default_realm(context, &princ.realm);
=20
 		if (ret) {
-		    krb5_warnx (context,=20
+		    krb5_warnx (context,
 				"kadm5_init_with_password_ctx: "
 				"failed to allocate realm");
-		    reply_priv (auth_context, s, sa, sa_size,=20
+		    reply_priv (auth_context, s, sa, sa_size,
 				KRB5_KPASSWD_SOFTERROR,
 				"failed to allocate realm");
 		    goto out;
@@ -313,7 +313,7 @@
 		free(princ.realm);
 	    if (ret) {
 		krb5_warn(context, ret, "krb5_copy_principal");
-		reply_priv(auth_context, s, sa, sa_size,=20
+		reply_priv(auth_context, s, sa, sa_size,
 			   KRB5_KPASSWD_HARDERROR,
 			   "failed to allocate principal");
 		goto out;
@@ -322,7 +322,7 @@
 	    principal =3D admin_principal;
     } else {
 	krb5_warnx (context, "kadm5_init_with_password_ctx: unknown proto");
-	reply_priv (auth_context, s, sa, sa_size,=20
+	reply_priv (auth_context, s, sa, sa_size,
 		    KRB5_KPASSWD_HARDERROR,
 		    "Unknown protocol used");
 	return;
@@ -331,7 +331,7 @@
     ret =3D krb5_unparse_name (context, admin_principal, &admin);
     if (ret) {
 	krb5_warn (context, ret, "unparse_name failed");
-	reply_priv (auth_context, s, sa, sa_size,=20
+	reply_priv (auth_context, s, sa, sa_size,
 		    KRB5_KPASSWD_HARDERROR, "out of memory error");
 	goto out;
     }
@@ -339,11 +339,11 @@
     conf.realm =3D principal->realm;
     conf.mask |=3D KADM5_CONFIG_REALM;
=20
-    ret =3D kadm5_init_with_password_ctx(context,=20
+    ret =3D kadm5_init_with_password_ctx(context,
 				       admin,
 				       NULL,
 				       KADM5_ADMIN_SERVICE,
-				       &conf, 0, 0,=20
+				       &conf, 0, 0,
 				       &kadm5_handle);
     if (ret) {
 	krb5_warn (context, ret, "kadm5_init_with_password_ctx");
@@ -355,7 +355,7 @@
     ret =3D krb5_unparse_name(context, principal, &client);
     if (ret) {
 	krb5_warn (context, ret, "unparse_name failed");
-	reply_priv (auth_context, s, sa, sa_size,=20
+	reply_priv (auth_context, s, sa, sa_size,
 		    KRB5_KPASSWD_HARDERROR, "out of memory error");
 	goto out;
     }
@@ -366,25 +366,25 @@
=20
     if (krb5_principal_compare(context, admin_principal, principal) =3D=3D=
 TRUE) {
=20
-	pwd_reason =3D kadm5_check_password_quality (context, principal,=20
+	pwd_reason =3D kadm5_check_password_quality (context, principal,
 						   pwd_data);
 	if (pwd_reason !=3D NULL ) {
-	    krb5_warnx (context,=20
+	    krb5_warnx (context,
 			"%s didn't pass password quality check with error: %s",
 			client, pwd_reason);
-	    reply_priv (auth_context, s, sa, sa_size,=20
+	    reply_priv (auth_context, s, sa, sa_size,
 			KRB5_KPASSWD_SOFTERROR, pwd_reason);
 	    goto out;
 	}
 	krb5_warnx (context, "Changing password for %s", client);
     } else {
-	ret =3D _kadm5_acl_check_permission(kadm5_handle, KADM5_PRIV_CPW,=20
+	ret =3D _kadm5_acl_check_permission(kadm5_handle, KADM5_PRIV_CPW,
 					  principal);
 	if (ret) {
-	    krb5_warn (context, ret,=20
+	    krb5_warn (context, ret,
 		       "Check ACL failed for %s for changing %s password",
 		       admin, client);
-	    reply_priv (auth_context, s, sa, sa_size,=20
+	    reply_priv (auth_context, s, sa, sa_size,
 			KRB5_KPASSWD_HARDERROR, "permission denied");
 	    goto out;
 	}
@@ -405,17 +405,19 @@
     krb5_free_data (context, pwd_data);
     pwd_data =3D NULL;
     if (ret) {
-	char *str =3D krb5_get_error_message(context, ret);
+	const char *str =3D krb5_get_error_message(context, ret);
 	krb5_warnx(context, "kadm5_s_chpass_principal_cond: %s", str);
 	reply_priv (auth_context, s, sa, sa_size, KRB5_KPASSWD_SOFTERROR,
 		    str ? str : "Internal error");
-	krb5_free_error_string(context, str);
+	krb5_free_error_message(context, str);
 	goto out;
     }
     reply_priv (auth_context, s, sa, sa_size, KRB5_KPASSWD_SUCCESS,
 		"Password changed");
 out:
     free_ChangePasswdDataMS(&chpw);
+    if (principal !=3D admin_principal)
+	krb5_free_principal(context, principal);
     if (admin)
 	free(admin);
     if (client)
@@ -437,7 +439,8 @@
 	struct sockaddr *sa,
 	int sa_size,
 	u_char *msg,
-	size_t len)
+	size_t len,
+	krb5_address *client_addr)
 {
     krb5_error_code ret;
     uint16_t pkt_len, pkt_ver, ap_req_len;
@@ -445,13 +448,27 @@
     krb5_data krb_priv_data;
     krb5_realm *r;
=20
+    /*
+     * Only send an error reply if the request passes basic length
+     * verification.  Otherwise, kpasswdd would reply to every UDP packet,
+     * allowing an attacker to set up a ping-pong DoS attack via a spoofed=
 UDP
+     * packet with a source address of another UDP service that also repli=
es
+     * to every packet.
+     *
+     * Also suppress the error reply if ap_req_len is 0, which indicates
+     * either an invalid request or an error packet.  An error packet may =
be
+     * the result of a ping-pong attacker pointing us at another kpasswdd.
+     */
     pkt_len =3D (msg[0] << 8) | (msg[1]);
     pkt_ver =3D (msg[2] << 8) | (msg[3]);
     ap_req_len =3D (msg[4] << 8) | (msg[5]);
     if (pkt_len !=3D len) {
-	krb5_warnx (context, "Strange len: %ld !=3D %ld",=20
+	krb5_warnx (context, "Strange len: %ld !=3D %ld",
 		    (long)pkt_len, (long)len);
-	reply_error (NULL, s, sa, sa_size, 0, 1, "Bad request");
+	return 1;
+    }
+    if (ap_req_len =3D=3D 0) {
+	krb5_warnx (context, "Request is error packet (ap_req_len =3D=3D 0)");
 	return 1;
     }
     if (pkt_ver !=3D KRB5_KPASSWD_VERS_CHANGEPW &&
@@ -483,7 +500,7 @@
 	krb5_principal principal;
 	krb5_boolean same;
=20
-	ret =3D krb5_make_principal (context,=20
+	ret =3D krb5_make_principal (context,
 				   &principal,
 				   *r,
 				   "kadmin",
@@ -524,15 +541,30 @@
     krb_priv_data.data   =3D msg + 6 + ap_req_len;
     krb_priv_data.length =3D len - 6 - ap_req_len;
=20
+    /*
+     * Only enforce client addresses on on tickets with addresses.  If
+     * its addressless, we are guessing its behind NAT and really
+     * can't know this information.
+     */
+
+    if ((*ticket)->ticket.caddr && (*ticket)->ticket.caddr->len > 0) {
+	ret =3D krb5_auth_con_setaddrs (context, *auth_context,
+				      NULL, client_addr);
+	if (ret) {
+	    krb5_warn (context, ret, "krb5_auth_con_setaddr(this)");
+	    goto out;
+	}
+    }
+
     ret =3D krb5_rd_priv (context,
 			*auth_context,
 			&krb_priv_data,
 			out_data,
 			NULL);
-   =20
+
     if (ret) {
 	krb5_warn (context, ret, "krb5_rd_priv");
-	reply_error ((*ticket)->server->realm, s, sa, sa_size, ret, 3,=20
+	reply_error ((*ticket)->server->realm, s, sa, sa_size, ret, 3,
 		     "Bad request");
 	goto out;
     }
@@ -560,7 +592,7 @@
     krb5_address other_addr;
     uint16_t version;
=20
-
+    memset(&other_addr, 0, sizeof(other_addr));
     krb5_data_zero (&out_data);
=20
     ret =3D krb5_auth_con_init (context, &auth_context);
@@ -578,18 +610,27 @@
 	goto out;
     }
=20
-    ret =3D krb5_auth_con_setaddrs (context,
-				  auth_context,
-				  this_addr,
-				  &other_addr);
-    krb5_free_address (context, &other_addr);
+    ret =3D krb5_auth_con_setaddrs (context, auth_context, this_addr, NULL=
);
     if (ret) {
-	krb5_warn (context, ret, "krb5_auth_con_setaddr");
+	krb5_warn (context, ret, "krb5_auth_con_setaddr(this)");
 	goto out;
     }
=20
     if (verify (&auth_context, realms, keytab, &ticket, &out_data,
-		&version, s, sa, sa_size, msg, len) =3D=3D 0) {
+		&version, s, sa, sa_size, msg, len, &other_addr) =3D=3D 0)
+    {
+	/*
+	 * We always set the client_addr, to assume that the client
+	 * can ignore it if it choose to do so (just the server does
+	 * so for addressless tickets).
+	 */
+	ret =3D krb5_auth_con_setaddrs (context, auth_context,=20
+				      this_addr, &other_addr);
+	if (ret) {
+	    krb5_warn (context, ret, "krb5_auth_con_setaddr(other)");
+	    goto out;
+	}
+
 	change (auth_context,
 		ticket->client,
 		version,
@@ -601,8 +642,9 @@
     }
=20
 out:
-    krb5_data_free (&out_data);
-    krb5_auth_con_free (context, auth_context);
+    krb5_free_address(context, &other_addr);
+    krb5_data_free(&out_data);
+    krb5_auth_con_free(context, auth_context);
 }
=20
 static int
@@ -640,7 +682,7 @@
 	krb5_socklen_t sa_size =3D sizeof(__ss);
=20
 	krb5_addr2sockaddr (context, &addrs.val[i], sa, &sa_size, port);
-=09
+
 	sockets[i] =3D socket (sa->sa_family, SOCK_DGRAM, 0);
 	if (sockets[i] < 0)
 	    krb5_err (context, 1, errno, "socket");
@@ -664,11 +706,11 @@
 	krb5_errx (context, 1, "No sockets!");
=20
     while(exit_flag =3D=3D 0) {
-	int ret;
+	krb5_ssize_t retx;
 	fd_set fdset =3D real_fdset;
=20
-	ret =3D select (maxfd + 1, &fdset, NULL, NULL, NULL);
-	if (ret < 0) {
+	retx =3D select (maxfd + 1, &fdset, NULL, NULL, NULL);
+	if (retx < 0) {
 	    if (errno =3D=3D EINTR)
 		continue;
 	    else
@@ -679,9 +721,9 @@
 		u_char buf[BUFSIZ];
 		socklen_t addrlen =3D sizeof(__ss);
=20
-		ret =3D recvfrom (sockets[i], buf, sizeof(buf), 0,
+		retx =3D recvfrom(sockets[i], buf, sizeof(buf), 0,
 				sa, &addrlen);
-		if (ret < 0) {
+		if (retx < 0) {
 		    if(errno =3D=3D EINTR)
 			break;
 		    else
@@ -691,7 +733,7 @@
 		process (realms, keytab, sockets[i],
 			 &addrs.val[i],
 			 sa, addrlen,
-			 buf, ret);
+			 buf, retx);
 	    }
     }
=20
@@ -714,7 +756,8 @@
 static const char *check_library  =3D NULL;
 static const char *check_function =3D NULL;
 static getarg_strings policy_libraries =3D { 0, NULL };
-static char *keytab_str =3D "HDB:";
+static char sHDB[] =3D "HDB:";
+static char *keytab_str =3D sHDB;
 static char *realm_str;
 static int version_flag;
 static int help_flag;
@@ -723,7 +766,7 @@
=20
 struct getargs args[] =3D {
 #ifdef HAVE_DLOPEN
-    { "check-library", 0, arg_string, &check_library,=20
+    { "check-library", 0, arg_string, &check_library,
       "library to load password check function from", "library" },
     { "check-function", 0, arg_string, &check_function,
       "password check function to load", "function" },
@@ -732,27 +775,26 @@
 #endif
     { "addresses",	0,	arg_strings, &addresses_str,
       "addresses to listen on", "list of addresses" },
-    { "keytab", 'k', arg_string, &keytab_str,=20
+    { "keytab", 'k', arg_string, &keytab_str,
       "keytab to get authentication key from", "kspec" },
-    { "config-file", 'c', arg_string, &config_file },
+    { "config-file", 'c', arg_string, &config_file, NULL, NULL },
     { "realm", 'r', arg_string, &realm_str, "default realm", "realm" },
-    { "port",  'p', arg_string, &port_str, "port" },
-    { "version", 0, arg_flag, &version_flag },
-    { "help", 0, arg_flag, &help_flag }
+    { "port",  'p', arg_string, &port_str, "port", NULL },
+    { "version", 0, arg_flag, &version_flag, NULL, NULL },
+    { "help", 0, arg_flag, &help_flag, NULL, NULL }
 };
 int num_args =3D sizeof(args) / sizeof(args[0]);
=20
 int
 main (int argc, char **argv)
 {
-    int optind;
     krb5_keytab keytab;
     krb5_error_code ret;
     char **files;
     int port, i;
-   =20
-    optind =3D krb5_program_setup(&context, argc, argv, args, num_args, NU=
LL);
-   =20
+
+    krb5_program_setup(&context, argc, argv, args, num_args, NULL);
+
     if(help_flag)
 	krb5_std_usage(0, args, num_args);
     if(version_flag) {
@@ -777,7 +819,7 @@
=20
     if(realm_str)
 	krb5_set_default_realm(context, realm_str);
-   =20
+
     krb5_openlog (context, "kpasswdd", &log_facility);
     krb5_set_warn_dest(context, log_facility);
=20
@@ -804,11 +846,11 @@
     ret =3D krb5_kt_resolve(context, keytab_str, &keytab);
     if(ret)
 	krb5_err(context, 1, ret, "%s", keytab_str);
-   =20
+
     kadm5_setup_passwd_quality_check (context, check_library, check_functi=
on);
=20
     for (i =3D 0; i < policy_libraries.num_strings; i++) {
-	ret =3D kadm5_add_passwd_quality_verifier(context,=20
+	ret =3D kadm5_add_passwd_quality_verifier(context,
 						policy_libraries.strings[i]);
 	if (ret)
 	    krb5_err(context, 1, ret, "kadm5_add_passwd_quality_verifier");
@@ -821,10 +863,10 @@
     explicit_addresses.len =3D 0;
=20
     if (addresses_str.num_strings) {
-	int i;
+	int j;
=20
-	for (i =3D 0; i < addresses_str.num_strings; ++i)
-	    add_one_address (addresses_str.strings[i], i =3D=3D 0);
+	for (j =3D 0; j < addresses_str.num_strings; ++j)
+	    add_one_address (addresses_str.strings[j], j =3D=3D 0);
 	free_getarg_strings (&addresses_str);
     } else {
 	char **foo =3D krb5_config_get_strings (context, NULL,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/Makefile.am
--- a/head/crypto/heimdal/kuser/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,22 +1,24 @@
-# $Id: Makefile.am 22285 2007-12-13 20:40:57Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
+AM_CPPFLAGS +=3D $(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5 \
+	$(INCLUDE_libintl) \
+	-DHEIMDAL_LOCALEDIR=3D'"$(localedir)"'
=20
 man_MANS =3D \
 	kinit.1 \
 	klist.1 \
 	kdestroy.1 \
+	kswitch.1 \
+	kdigest.8 \
 	kgetcred.1 \
-	kimpersonate.1
+	kimpersonate.8
=20
-SLC =3D $(top_builddir)/lib/sl/slc
-
-bin_PROGRAMS =3D kinit klist kdestroy kgetcred
+bin_PROGRAMS =3D kinit kdestroy kgetcred kcc
 libexec_PROGRAMS =3D kdigest kimpersonate
=20
-noinst_PROGRAMS =3D kverify kdecode_ticket generate-requests copy_cred_cac=
he
+noinst_PROGRAMS =3D kverify kdecode_ticket generate-requests
=20
 kinit_LDADD =3D \
 	$(LIB_kafs) \
@@ -24,13 +26,22 @@
 	$(top_builddir)/lib/ntlm/libheimntlm.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(LIB_libintl) \
 	$(LIB_roken)
=20
 kdestroy_LDADD	=3D $(kinit_LDADD)
=20
-klist_LDADD	=3D $(kinit_LDADD)
+kimpersonate_LDADD =3D $(kinit_LDADD)
=20
-kimpersonate_LDADD =3D $(kinit_LDADD)
+kcc_LDADD =3D \
+	$(top_builddir)/lib/sl/libsl.la \
+	$(kinit_LDADD) \
+	$(LIB_readline)
+
+dist_kcc_SOURCES =3D kcc.c klist.c kswitch.c copy_cred_cache.c
+nodist_kcc_SOURCES =3D kcc-commands.c
+
+$(kcc_OBJECTS): kcc-commands.h
=20
 dist_kdigest_SOURCES =3D kdigest.c
 nodist_kdigest_SOURCES =3D kdigest-commands.c
@@ -45,20 +56,33 @@
=20
 $(kdigest_OBJECTS): kdigest-commands.h
=20
-CLEANFILES =3D kdigest-commands.h kdigest-commands.c
+CLEANFILES =3D \
+	kdigest-commands.h kdigest-commands.c \
+	kcc-commands.h kcc-commands.c
=20
 kdigest-commands.c kdigest-commands.h: kdigest-commands.in
 	$(SLC) $(srcdir)/kdigest-commands.in
=20
+kcc-commands.c kcc-commands.h: kcc-commands.in
+	$(SLC) $(srcdir)/kcc-commands.in
+
 LDADD =3D \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
+EXTRA_DIST =3D NTMakefile $(man_MANS) \
+	kcc-version.rc \
+	kdestroy-version.rc \
+	kdigest-version.rc \
+	kgetcred-version.rc \
+	kimpersonate-version.rc \
+	kinit-version.rc \
+	kuser_locl.h kcc-commands.in kdigest-commands.in copy_cred_cache.1
+
 # make sure install-exec-hook doesn't have any commands in Makefile.am.com=
mon
 install-exec-hook:
-	(cd $(DESTDIR)$(bindir) && rm -f kauth && $(LN_S) kinit kauth)
+	(cd $(DESTDIR)$(bindir) && rm -f klist && $(LN_S) kcc klist)
+	(cd $(DESTDIR)$(bindir) && rm -f kswitch && $(LN_S) kcc kswitch)
=20
-EXTRA_DIST =3D $(man_MANS) kuser_locl.h kdigest-commands.in copy_cred_cach=
e.1
-
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/Makefile.in
--- a/head/crypto/heimdal/kuser/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,16 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22285 2007-12-13 20:40:57Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -41,15 +43,15 @@
 DIST_COMMON =3D $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
 	$(top_srcdir)/Makefile.am.common \
 	$(top_srcdir)/cf/Makefile.am.common
-bin_PROGRAMS =3D kinit$(EXEEXT) klist$(EXEEXT) kdestroy$(EXEEXT) \
-	kgetcred$(EXEEXT)
+bin_PROGRAMS =3D kinit$(EXEEXT) kdestroy$(EXEEXT) kgetcred$(EXEEXT) \
+	kcc$(EXEEXT)
 libexec_PROGRAMS =3D kdigest$(EXEEXT) kimpersonate$(EXEEXT)
 noinst_PROGRAMS =3D kverify$(EXEEXT) kdecode_ticket$(EXEEXT) \
-	generate-requests$(EXEEXT) copy_cred_cache$(EXEEXT)
+	generate-requests$(EXEEXT)
 subdir =3D kuser
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -64,7 +66,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -78,9 +80,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -88,30 +93,36 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" \
-	"$(DESTDIR)$(man1dir)"
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
+	"$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)"
 PROGRAMS =3D $(bin_PROGRAMS) $(libexec_PROGRAMS) $(noinst_PROGRAMS)
-copy_cred_cache_SOURCES =3D copy_cred_cache.c
-copy_cred_cache_OBJECTS =3D copy_cred_cache.$(OBJEXT)
-copy_cred_cache_LDADD =3D $(LDADD)
-am__DEPENDENCIES_1 =3D
-copy_cred_cache_DEPENDENCIES =3D $(top_builddir)/lib/krb5/libkrb5.la \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
-	$(am__DEPENDENCIES_1)
 generate_requests_SOURCES =3D generate-requests.c
 generate_requests_OBJECTS =3D generate-requests.$(OBJEXT)
 generate_requests_LDADD =3D $(LDADD)
+am__DEPENDENCIES_1 =3D
 generate_requests_DEPENDENCIES =3D $(top_builddir)/lib/krb5/libkrb5.la \
 	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
 	$(am__DEPENDENCIES_1)
+dist_kcc_OBJECTS =3D kcc.$(OBJEXT) klist.$(OBJEXT) kswitch.$(OBJEXT) \
+	copy_cred_cache.$(OBJEXT)
+nodist_kcc_OBJECTS =3D kcc-commands.$(OBJEXT)
+kcc_OBJECTS =3D $(dist_kcc_OBJECTS) $(nodist_kcc_OBJECTS)
+am__DEPENDENCIES_2 =3D $(top_builddir)/lib/kafs/libkafs.la \
+	$(am__DEPENDENCIES_1)
+am__DEPENDENCIES_3 =3D $(am__DEPENDENCIES_2) \
+	$(top_builddir)/lib/krb5/libkrb5.la \
+	$(top_builddir)/lib/ntlm/libheimntlm.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
+kcc_DEPENDENCIES =3D $(top_builddir)/lib/sl/libsl.la \
+	$(am__DEPENDENCIES_3) $(am__DEPENDENCIES_1)
 kdecode_ticket_SOURCES =3D kdecode_ticket.c
 kdecode_ticket_OBJECTS =3D kdecode_ticket.$(OBJEXT)
 kdecode_ticket_LDADD =3D $(LDADD)
@@ -120,12 +131,6 @@
 	$(am__DEPENDENCIES_1)
 kdestroy_SOURCES =3D kdestroy.c
 kdestroy_OBJECTS =3D kdestroy.$(OBJEXT)
-am__DEPENDENCIES_2 =3D $(top_builddir)/lib/kafs/libkafs.la \
-	$(am__DEPENDENCIES_1)
-am__DEPENDENCIES_3 =3D $(am__DEPENDENCIES_2) \
-	$(top_builddir)/lib/krb5/libkrb5.la \
-	$(top_builddir)/lib/ntlm/libheimntlm.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
 kdestroy_DEPENDENCIES =3D $(am__DEPENDENCIES_3)
 dist_kdigest_OBJECTS =3D kdigest.$(OBJEXT)
 nodist_kdigest_OBJECTS =3D kdigest-commands.$(OBJEXT)
@@ -148,19 +153,17 @@
 kinit_DEPENDENCIES =3D $(am__DEPENDENCIES_2) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/ntlm/libheimntlm.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
-klist_SOURCES =3D klist.c
-klist_OBJECTS =3D klist.$(OBJEXT)
-klist_DEPENDENCIES =3D $(am__DEPENDENCIES_3)
+	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
 kverify_SOURCES =3D kverify.c
 kverify_OBJECTS =3D kverify.$(OBJEXT)
 kverify_LDADD =3D $(LDADD)
 kverify_DEPENDENCIES =3D $(top_builddir)/lib/krb5/libkrb5.la \
 	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
 	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -170,13 +173,36 @@
 LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
-SOURCES =3D copy_cred_cache.c generate-requests.c kdecode_ticket.c \
-	kdestroy.c $(dist_kdigest_SOURCES) $(nodist_kdigest_SOURCES) \
-	kgetcred.c kimpersonate.c kinit.c klist.c kverify.c
-DIST_SOURCES =3D copy_cred_cache.c generate-requests.c kdecode_ticket.c \
-	kdestroy.c $(dist_kdigest_SOURCES) kgetcred.c kimpersonate.c \
-	kinit.c klist.c kverify.c
+SOURCES =3D generate-requests.c $(dist_kcc_SOURCES) \
+	$(nodist_kcc_SOURCES) kdecode_ticket.c kdestroy.c \
+	$(dist_kdigest_SOURCES) $(nodist_kdigest_SOURCES) kgetcred.c \
+	kimpersonate.c kinit.c kverify.c
+DIST_SOURCES =3D generate-requests.c $(dist_kcc_SOURCES) \
+	kdecode_ticket.c kdestroy.c $(dist_kdigest_SOURCES) kgetcred.c \
+	kimpersonate.c kinit.c kverify.c
+am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
+am__vpath_adj =3D case $$p in \
+    $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
+    *) f=3D$$p;; \
+  esac;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 man1dir =3D $(mandir)/man1
+man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
 ETAGS =3D etags
 CTAGS =3D ctags
@@ -185,49 +211,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -251,10 +286,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -271,6 +307,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -286,31 +324,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -325,10 +377,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -369,50 +423,64 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_hcrypto) -I$(srcdir)/../lib/krb5
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_hcrypto) \
+	-I$(srcdir)/../lib/krb5 $(INCLUDE_libintl) \
+	-DHEIMDAL_LOCALEDIR=3D'"$(localedir)"'
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 man_MANS =3D \
 	kinit.1 \
 	klist.1 \
 	kdestroy.1 \
+	kswitch.1 \
+	kdigest.8 \
 	kgetcred.1 \
-	kimpersonate.1
+	kimpersonate.8
=20
-SLC =3D $(top_builddir)/lib/sl/slc
 kinit_LDADD =3D \
 	$(LIB_kafs) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/ntlm/libheimntlm.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(LIB_libintl) \
 	$(LIB_roken)
=20
 kdestroy_LDADD =3D $(kinit_LDADD)
-klist_LDADD =3D $(kinit_LDADD)
 kimpersonate_LDADD =3D $(kinit_LDADD)
+kcc_LDADD =3D \
+	$(top_builddir)/lib/sl/libsl.la \
+	$(kinit_LDADD) \
+	$(LIB_readline)
+
+dist_kcc_SOURCES =3D kcc.c klist.c kswitch.c copy_cred_cache.c
+nodist_kcc_SOURCES =3D kcc-commands.c
 dist_kdigest_SOURCES =3D kdigest.c
 nodist_kdigest_SOURCES =3D kdigest-commands.c
 kdigest_LDADD =3D \
@@ -423,30 +491,41 @@
 	$(top_builddir)/lib/sl/libsl.la \
 	$(LIB_roken)
=20
-CLEANFILES =3D kdigest-commands.h kdigest-commands.c
+CLEANFILES =3D \
+	kdigest-commands.h kdigest-commands.c \
+	kcc-commands.h kcc-commands.c
+
 LDADD =3D \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_roken)
=20
-EXTRA_DIST =3D $(man_MANS) kuser_locl.h kdigest-commands.in copy_cred_cach=
e.1
+EXTRA_DIST =3D NTMakefile $(man_MANS) \
+	kcc-version.rc \
+	kdestroy-version.rc \
+	kdigest-version.rc \
+	kgetcred-version.rc \
+	kimpersonate-version.rc \
+	kinit-version.rc \
+	kuser_locl.h kcc-commands.in kdigest-commands.in copy_cred_cache.1
+
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps kuser/Mak=
efile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps kuser/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign kuser/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign kuser/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -464,75 +543,108 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
-copy_cred_cache$(EXEEXT): $(copy_cred_cache_OBJECTS) $(copy_cred_cache_DEP=
ENDENCIES)=20
-	@rm -f copy_cred_cache$(EXEEXT)
-	$(LINK) $(copy_cred_cache_OBJECTS) $(copy_cred_cache_LDADD) $(LIBS)
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 generate-requests$(EXEEXT): $(generate_requests_OBJECTS) $(generate_reques=
ts_DEPENDENCIES)=20
 	@rm -f generate-requests$(EXEEXT)
 	$(LINK) $(generate_requests_OBJECTS) $(generate_requests_LDADD) $(LIBS)
+kcc$(EXEEXT): $(kcc_OBJECTS) $(kcc_DEPENDENCIES)=20
+	@rm -f kcc$(EXEEXT)
+	$(LINK) $(kcc_OBJECTS) $(kcc_LDADD) $(LIBS)
 kdecode_ticket$(EXEEXT): $(kdecode_ticket_OBJECTS) $(kdecode_ticket_DEPEND=
ENCIES)=20
 	@rm -f kdecode_ticket$(EXEEXT)
 	$(LINK) $(kdecode_ticket_OBJECTS) $(kdecode_ticket_LDADD) $(LIBS)
@@ -551,9 +663,6 @@
 kinit$(EXEEXT): $(kinit_OBJECTS) $(kinit_DEPENDENCIES)=20
 	@rm -f kinit$(EXEEXT)
 	$(LINK) $(kinit_OBJECTS) $(kinit_LDADD) $(LIBS)
-klist$(EXEEXT): $(klist_OBJECTS) $(klist_DEPENDENCIES)=20
-	@rm -f klist$(EXEEXT)
-	$(LINK) $(klist_OBJECTS) $(klist_LDADD) $(LIBS)
 kverify$(EXEEXT): $(kverify_OBJECTS) $(kverify_DEPENDENCIES)=20
 	@rm -f kverify$(EXEEXT)
 	$(LINK) $(kverify_OBJECTS) $(kverify_LDADD) $(LIBS)
@@ -564,115 +673,190 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/copy_cred_cache.Po at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/generate-requests.Po at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kcc-commands.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kcc.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdecode_ticket.Po at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdestroy.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdigest-commands.Po at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kdigest.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kgetcred.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kimpersonate.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kinit.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/klist.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kswitch.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kverify.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
+	@$(NORMAL_INSTALL)
+	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
+uninstall-man8:
+	@$(NORMAL_UNINSTALL)
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -688,13 +872,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -706,7 +894,7 @@
 check: check-am
 all-am: Makefile $(PROGRAMS) $(MANS) all-local
 installdirs:
-	for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(m=
an1dir)"; do \
+	for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(m=
an1dir)" "$(DESTDIR)$(man8dir)"; do \
 	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
 	done
 install: install-am
@@ -730,6 +918,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -740,6 +929,7 @@
 	clean-libtool clean-noinstPROGRAMS mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -750,6 +940,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -757,26 +949,35 @@
 install-data-am: install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libexecPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
+install-html: install-html-am
=20
-install-html: install-html-am
+install-html-am:
=20
 install-info: install-info-am
=20
-install-man: install-man1
+install-info-am:
+
+install-man: install-man1 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -797,11 +998,10 @@
 	uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
+uninstall-man: uninstall-man1 uninstall-man8
=20
-uninstall-man: uninstall-man1
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libexecPROGRAMS \
@@ -812,14 +1012,14 @@
 	install-data-am install-data-hook install-dvi install-dvi-am \
 	install-exec install-exec-am install-exec-hook install-html \
 	install-html-am install-info install-info-am \
-	install-libexecPROGRAMS install-man install-man1 install-pdf \
-	install-pdf-am install-ps install-ps-am install-strip \
-	installcheck installcheck-am installdirs maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-compile \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags uninstall uninstall-am uninstall-binPROGRAMS \
-	uninstall-hook uninstall-libexecPROGRAMS uninstall-man \
-	uninstall-man1
+	install-libexecPROGRAMS install-man install-man1 install-man8 \
+	install-pdf install-pdf-am install-ps install-ps-am \
+	install-strip installcheck installcheck-am installdirs \
+	maintainer-clean maintainer-clean-generic mostlyclean \
+	mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+	pdf pdf-am ps ps-am tags uninstall uninstall-am \
+	uninstall-binPROGRAMS uninstall-hook uninstall-libexecPROGRAMS \
+	uninstall-man uninstall-man1 uninstall-man8
=20
=20
 install-suid-programs:
@@ -890,6 +1090,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -975,7 +1178,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -989,14 +1192,21 @@
 	  fi ; \
 	done
=20
+$(kcc_OBJECTS): kcc-commands.h
+
 $(kdigest_OBJECTS): kdigest-commands.h
=20
 kdigest-commands.c kdigest-commands.h: kdigest-commands.in
 	$(SLC) $(srcdir)/kdigest-commands.in
=20
+kcc-commands.c kcc-commands.h: kcc-commands.in
+	$(SLC) $(srcdir)/kcc-commands.in
+
 # make sure install-exec-hook doesn't have any commands in Makefile.am.com=
mon
 install-exec-hook:
-	(cd $(DESTDIR)$(bindir) && rm -f kauth && $(LN_S) kinit kauth)
+	(cd $(DESTDIR)$(bindir) && rm -f klist && $(LN_S) kcc klist)
+	(cd $(DESTDIR)$(bindir) && rm -f kswitch && $(LN_S) kcc kswitch)
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/copy_cred_ca=
che.1
--- a/head/crypto/heimdal/kuser/copy_cred_cache.1	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/kuser/copy_cred_cache.1	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,23 +29,22 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: copy_cred_cache.1 13783 2004-04-25 16:03:45Z joda $
+.\" $Id$
 .\"
 .Dd April 24, 2004
 .Dt COPY_CRED_CACHE 1
 .Os HEIMDAL
 .Sh NAME
 .Nm copy_cred_cache
-.Nd
-copy credentials from one cache to another
+.Nd copy credentials from one cache to another
 .Sh SYNOPSIS
 .Nm
-.Op Fl -krbtgt-only
-.Op Fl -service=3D Ns Ar principal
-.Op Fl -enctype=3D Ns Ar enctype
-.Op Fl -flags=3D Ns Ar ticketflags
-.Op Fl -valid-for=3D Ns Ar time
-.Op Fl -fcache-version=3D Ns Ar integer
+.Op Fl Fl krbtgt-only
+.Op Fl Fl service=3D Ns Ar principal
+.Op Fl Fl enctype=3D Ns Ar enctype
+.Op Fl Fl flags=3D Ns Ar ticketflags
+.Op Fl Fl valid-for=3D Ns Ar time
+.Op Fl Fl fcache-version=3D Ns Ar integer
 .Op Aq Ar from-cache
 .Aq Ar to-cache
 .Sh DESCRIPTION
@@ -57,20 +56,20 @@
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Fl -krbtgt-only
+.It Fl Fl krbtgt-only
 Copies only krbtgt credentials for the client's realm. This is
 equivalent to
-.Fl -service=3D Ns Li krbtgt/ Ns Ao Ar CLIENTREALM Ac Ns Li @ Ns Ao Ar CLI=
ENTREALM Ac .
-.It Fl -service=3D Ns Ar principal
+.Fl Fl service=3D Ns Li krbtgt/ Ns Ao Ar CLIENTREALM Ac Ns Li @ Ns Ao Ar C=
LIENTREALM Ac .
+.It Fl Fl service=3D Ns Ar principal
 Copies only credentials matching this service principal.
-.It Fl -enctype=3D Ns Ar enctype
+.It Fl Fl enctype=3D Ns Ar enctype
 Copies only credentials a matching enctype.
-.It Fl -flags=3D Ns Ar ticketflags
+.It Fl Fl flags=3D Ns Ar ticketflags
 Copies only credentials with these ticket flags set.
-.It Fl -valid-for=3D Ns Ar time
+.It Fl Fl valid-for=3D Ns Ar time
 Copies only credentials that are valid for at least this long. This
 does not take renewable creds into account.
-.It Fl -fcache-version=3D Ns Ar integer
+.It Fl Fl fcache-version=3D Ns Ar integer
 The created cache, If a standard
 .Li FILE
 cache is created, it will have this file format version.
@@ -88,7 +87,7 @@
 .Sh DIAGNOSTICS
 The
 .Nm
-utility exits 0 on success, and \*[Gt]0 if an error occurs, or of no
+utility exits 0 on success, and \*[Gt]0 if an error occurs, or if no
 credentials where actually copied.
 .\".Sh SEE ALSO
 .\".Sh STANDARDS
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/copy_cred_ca=
che.c
--- a/head/crypto/heimdal/kuser/copy_cred_cache.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/kuser/copy_cred_cache.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
@@ -31,53 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
+#include "kuser_locl.h"
 #include <config.h>
-RCSID("$Id: copy_cred_cache.c 15542 2005-07-01 07:20:54Z lha $");
-#endif
-
-#include <stdlib.h>
-#include <krb5.h>
-#include <roken.h>
-#include <getarg.h>
 #include <parse_units.h>
 #include <parse_time.h>
-
-static int krbtgt_only_flag;
-static char *service_string;
-static char *enctype_string;
-static char *flags_string;
-static char *valid_string;
-static int fcache_version;
-static int help_flag;
-static int version_flag;
-
-static struct getargs args[] =3D {
-    { "krbtgt-only", 0, arg_flag, &krbtgt_only_flag,
-      "only copy local krbtgt" },
-    { "service", 0, arg_string, &service_string,
-      "limit to this service", "principal" },
-    { "enctype", 0, arg_string, &enctype_string,
-      "limit to this enctype", "enctype" },
-    { "flags", 0, arg_string, &flags_string,
-      "limit to these flags", "ticketflags" },
-    { "valid-for", 0, arg_string, &valid_string,=20
-      "limit to creds valid for at least this long", "time" },
-    { "fcache-version", 0, arg_integer, &fcache_version,
-      "file cache version to create" },
-    { "version", 0, arg_flag, &version_flag },
-    { "help", 'h', arg_flag, &help_flag }
-};
-
-static void
-usage(int ret)
-{
-    arg_printusage(args,
-		   sizeof(args) / sizeof(*args),
-		   NULL,
-		   "[from-cache] to-cache");
-    exit(ret);
-}
+#include "kcc-commands.h"
=20
 static int32_t
 bitswap32(int32_t b)
@@ -102,114 +60,104 @@
=20
     memset(&ff, 0, sizeof(ff));
     ff.proxy =3D 1;
-    if (parse_flags("proxy", asn1_TicketFlags_units(), 0) =3D=3D TicketFla=
gs2int(ff))
+    if ((size_t)parse_flags("proxy", asn1_TicketFlags_units(), 0) =3D=3D T=
icketFlags2int(ff))
 	ret_flags->i =3D flags;
     else
 	ret_flags->i =3D bitswap32(flags);
 }
=20
+struct ctx {
+    krb5_flags whichfields;
+    krb5_creds mcreds;
+};
+
+static krb5_boolean
+matchfunc(krb5_context context, void *ptr, const krb5_creds *creds)
+{
+    struct ctx *ctx =3D ptr;
+    if (krb5_compare_creds(context, ctx->whichfields, &ctx->mcreds, creds))
+	return TRUE;
+    return FALSE;
+}
+
 int
-main(int argc, char **argv)
+copy_cred_cache(struct copy_cred_cache_options *opt, int argc, char **argv)
 {
     krb5_error_code ret;
-    krb5_context context;
-    int optidx =3D 0;
     const char *from_name, *to_name;
     krb5_ccache from_ccache, to_ccache;
-    krb5_flags whichfields =3D 0;
-    krb5_creds mcreds;
     unsigned int matched;
+    struct ctx ctx;
=20
-    setprogname(argv[0]);
+    memset(&ctx, 0, sizeof(ctx));
=20
-    memset(&mcreds, 0, sizeof(mcreds));
-
-    if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
-	usage(1);
-
-    if (help_flag)
-	usage(0);
-
-    if (version_flag) {
-	print_version(NULL);
-	exit(0);
+    if (opt->service_string) {
+	ret =3D krb5_parse_name(kcc_context, opt->service_string, &ctx.mcreds.ser=
ver);
+	if (ret)
+	    krb5_err(kcc_context, 1, ret, "%s", opt->service_string);
     }
-    argc -=3D optidx;
-    argv +=3D optidx;
-
-    if (argc < 1 || argc > 2)
-	usage(1);
-
-    if (krb5_init_context(&context))
-	errx(1, "krb5_init_context failed");
-
-    if (service_string) {
-	ret =3D krb5_parse_name(context, service_string, &mcreds.server);
+    if (opt->enctype_string) {
+	krb5_enctype enctype;
+	ret =3D krb5_string_to_enctype(kcc_context, opt->enctype_string, &enctype=
);
 	if (ret)
-	    krb5_err(context, 1, ret, "%s", service_string);
+	    krb5_err(kcc_context, 1, ret, "%s", opt->enctype_string);
+	ctx.whichfields |=3D KRB5_TC_MATCH_KEYTYPE;
+	ctx.mcreds.session.keytype =3D enctype;
     }
-    if (enctype_string) {
-	krb5_enctype enctype;
-	ret =3D krb5_string_to_enctype(context, enctype_string, &enctype);
-	if (ret)
-	    krb5_err(context, 1, ret, "%s", enctype_string);
-	whichfields |=3D KRB5_TC_MATCH_KEYTYPE;
-	mcreds.session.keytype =3D enctype;
+    if (opt->flags_string) {
+	parse_ticket_flags(kcc_context, opt->flags_string, &ctx.mcreds.flags);
+	ctx.whichfields |=3D KRB5_TC_MATCH_FLAGS;
     }
-    if (flags_string) {
-	parse_ticket_flags(context, flags_string, &mcreds.flags);
-	whichfields |=3D KRB5_TC_MATCH_FLAGS;
+    if (opt->valid_for_string) {
+	time_t t =3D parse_time(opt->valid_for_string, "s");
+	if(t < 0)
+	    errx(1, "unknown time \"%s\"", opt->valid_for_string);
+	ctx.mcreds.times.endtime =3D time(NULL) + t;
+	ctx.whichfields |=3D KRB5_TC_MATCH_TIMES;
     }
-    if (valid_string) {
-	time_t t =3D parse_time(valid_string, "s");
-	if(t < 0)
-	    errx(1, "unknown time \"%s\"", valid_string);
-	mcreds.times.endtime =3D time(NULL) + t;
-	whichfields |=3D KRB5_TC_MATCH_TIMES;
-    }
-    if (fcache_version)
-	krb5_set_fcache_version(context, fcache_version);
+    if (opt->fcache_version_integer)
+	krb5_set_fcache_version(kcc_context, opt->fcache_version_integer);
=20
     if (argc =3D=3D 1) {
-	from_name =3D krb5_cc_default_name(context);
+	from_name =3D krb5_cc_default_name(kcc_context);
 	to_name =3D argv[0];
     } else {
 	from_name =3D argv[0];
 	to_name =3D argv[1];
     }
=20
-    ret =3D krb5_cc_resolve(context, from_name, &from_ccache);
+    ret =3D krb5_cc_resolve(kcc_context, from_name, &from_ccache);
     if (ret)
-	krb5_err(context, 1, ret, "%s", from_name);
+	krb5_err(kcc_context, 1, ret, "%s", from_name);
=20
-    if (krbtgt_only_flag) {
+    if (opt->krbtgt_only_flag) {
 	krb5_principal client;
-	ret =3D krb5_cc_get_principal(context, from_ccache, &client);
+	ret =3D krb5_cc_get_principal(kcc_context, from_ccache, &client);
 	if (ret)
-	    krb5_err(context, 1, ret, "getting default principal");
-	ret =3D krb5_make_principal(context, &mcreds.server,
-				  krb5_principal_get_realm(context, client),
+	    krb5_err(kcc_context, 1, ret, "getting default principal");
+	ret =3D krb5_make_principal(kcc_context, &ctx.mcreds.server,
+				  krb5_principal_get_realm(kcc_context, client),
 				  KRB5_TGS_NAME,
-				  krb5_principal_get_realm(context, client),
+				  krb5_principal_get_realm(kcc_context, client),
 				  NULL);
 	if (ret)
-	    krb5_err(context, 1, ret, "constructing krbtgt principal");
-	krb5_free_principal(context, client);
+	    krb5_err(kcc_context, 1, ret, "constructing krbtgt principal");
+	krb5_free_principal(kcc_context, client);
     }
-    ret =3D krb5_cc_resolve(context, to_name, &to_ccache);
+    ret =3D krb5_cc_resolve(kcc_context, to_name, &to_ccache);
     if (ret)
-	krb5_err(context, 1, ret, "%s", to_name);
+	krb5_err(kcc_context, 1, ret, "%s", to_name);
=20
-    ret =3D krb5_cc_copy_cache_match(context, from_ccache, to_ccache,
-				   whichfields, &mcreds, &matched);
+    ret =3D krb5_cc_copy_match_f(kcc_context, from_ccache, to_ccache,
+			       matchfunc, &ctx, &matched);
     if (ret)
-	krb5_err(context, 1, ret, "copying cred cache");
+	krb5_err(kcc_context, 1, ret, "copying cred cache");
=20
-    krb5_cc_close(context, from_ccache);
+    krb5_cc_close(kcc_context, from_ccache);
     if(matched =3D=3D 0)
-	krb5_cc_destroy(context, to_ccache);
+	krb5_cc_destroy(kcc_context, to_ccache);
     else
-	krb5_cc_close(context, to_ccache);
-    krb5_free_context(context);
+	krb5_cc_close(kcc_context, to_ccache);
+
     return matched =3D=3D 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/generate-req=
uests.c
--- a/head/crypto/heimdal/kuser/generate-requests.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/kuser/generate-requests.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,50 +1,38 @@
 /*
- * Copyright (c) 2000 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kuser_locl.h"
=20
-RCSID("$Id: generate-requests.c 19233 2006-12-06 08:04:05Z lha $");
-
-static krb5_error_code
-null_key_proc (krb5_context context,
-	       krb5_enctype type,
-	       krb5_salt salt,
-	       krb5_const_pointer keyseed,
-	       krb5_keyblock **key)
-{
-    return ENOTTY;
-}
-
 static unsigned
 read_words (const char *filename, char ***ret_w)
 {
@@ -68,12 +56,14 @@
     *ret_w =3D w;
     if (n =3D=3D 0)
 	errx(1, "%s is an empty file, no words to try", filename);
+    fclose(f);
     return n;
 }
=20
 static void
 generate_requests (const char *filename, unsigned nreq)
 {
+    krb5_principal client;
     krb5_context context;
     krb5_error_code ret;
     krb5_creds cred;
@@ -89,24 +79,18 @@
=20
     for (i =3D 0; i < nreq; ++i) {
 	char *name =3D words[rand() % nwords];
-	krb5_realm *client_realm;
=20
 	memset(&cred, 0, sizeof(cred));
=20
-	ret =3D krb5_parse_name (context, name, &cred.client);
+	ret =3D krb5_parse_name (context, name, &client);
 	if (ret)
 	    krb5_err (context, 1, ret, "krb5_parse_name %s", name);
-	client_realm =3D krb5_princ_realm (context, cred.client);
=20
-	ret =3D krb5_make_principal(context, &cred.server, *client_realm,
-				  KRB5_TGS_NAME, *client_realm, NULL);
+	ret =3D krb5_get_init_creds_password (context, &cred, client, "",
+					    NULL, NULL, 0, NULL, NULL);
 	if (ret)
-	    krb5_err (context, 1, ret, "krb5_make_principal");
-
-	ret =3D krb5_get_in_cred (context, 0, NULL, NULL, NULL, NULL,
-				null_key_proc, NULL, NULL, NULL,
-				&cred, NULL);
-	krb5_free_cred_contents (context, &cred);
+	    krb5_free_cred_contents (context, &cred);
+	krb5_free_principal(context, client);
     }
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kdecode_tick=
et.c
--- a/head/crypto/heimdal/kuser/kdecode_ticket.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/kuser/kdecode_ticket.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kuser_locl.h"
=20
-RCSID("$Id: kdecode_ticket.c 15541 2005-07-01 07:14:58Z lha $");
-
 static char *etype_str;
 static int version_flag;
 static int help_flag;
@@ -70,11 +68,12 @@
     krb5_crypto_destroy (context, crypto);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_decrypt_EncryptedData");
-    ret =3D krb5_decode_EncTicketPart (context, dec_data.data, dec_data.le=
ngth,
-				     &decr_part, &len);
+    ret =3D decode_EncTicketPart (dec_data.data, dec_data.length,
+				&decr_part, &len);
     krb5_data_free (&dec_data);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_decode_EncTicketPart");
+    free_EncTicketPart(&decr_part);
 }
=20
 struct getargs args[] =3D {
@@ -108,10 +107,10 @@
     ret =3D krb5_init_context (&context);
     if (ret)
 	errx(1, "krb5_init_context failed: %d", ret);
- =20
+
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kdestroy.1
--- a/head/crypto/heimdal/kuser/kdestroy.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kdestroy.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,56 +1,57 @@
-.\" Copyright (c) 1997, 1999, 2001, 2004, 2006 Kungliga Tekniska H=F6gskol=
an
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1997, 1999, 2001, 2004, 2006 Kungliga Tekniska H=C3=B6gs=
kolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: kdestroy.1 22071 2007-11-14 20:04:50Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd April 27, 2006
 .Dt KDESTROY 1
 .Os HEIMDAL
 .Sh NAME
 .Nm kdestroy
-.Nd remove one credental or destroy the current ticket file
+.Nd remove one credential or destroy the current ticket file
 .Sh SYNOPSIS
 .Nm
 .Bk -words
 .Op Fl c Ar cachefile
-.Op Fl -credential=3D Ns Ar principal
-.Op Fl -cache=3D Ns Ar cachefile
-.Op Fl -no-unlog
-.Op Fl -no-delete-v4
-.Op Fl -version
-.Op Fl -help
+.Op Fl Fl credential=3D Ns Ar principal
+.Op Fl Fl cache=3D Ns Ar cachefile
+.Op Fl A | Fl Fl all
+.Op Fl Fl no-unlog
+.Op Fl Fl no-delete-v4
+.Op Fl Fl version
+.Op Fl Fl help
 .Ek
 .Sh DESCRIPTION
 .Nm
-remove one or the current set of tickets.
+removes one credential or the current set of tickets.
 .Pp
 Supported options:
 .Bl -tag -width Ds
@@ -61,9 +62,12 @@
 .It Fl c Ar cachefile
 .It Fl cache=3D Ns Ar cachefile
 The cache file to remove.
-.It Fl -no-unlog
+.It Fl A
+.It Fl Fl all
+remove all credential caches.
+.It Fl Fl no-unlog
 Do not remove AFS tokens.
-.It Fl -no-delete-v4
+.It Fl Fl no-delete-v4
 Do not remove v4 tickets.
 .El
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kdestroy.c
--- a/head/crypto/heimdal/kuser/kdestroy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kdestroy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,52 +1,57 @@
 /*
- * Copyright (c) 1997 - 2000, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kuser_locl.h"
-RCSID("$Id: kdestroy.c 20458 2007-04-19 20:41:27Z lha $");
=20
 static const char *cache;
 static const char *credential;
 static int help_flag;
 static int version_flag;
+#ifndef NO_AFS
 static int unlog_flag =3D 1;
+#endif
 static int dest_tkt_flag =3D 1;
+static int all_flag =3D 0;
=20
 struct getargs args[] =3D {
-    { "credential",	0,   arg_string, &credential,
+    { "credential",	0,   arg_string, rk_UNCONST(&credential),
       "remove one credential", "principal" },
-    { "cache",		'c', arg_string, &cache, "cache to destroy", "cache" },
+    { "cache",		'c', arg_string, rk_UNCONST(&cache), "cache to destroy", "=
cache" },
+    { "all",		'A', arg_flag, &all_flag, "destroy all caches", NULL },
+#ifndef NO_AFS
     { "unlog",		0,   arg_negative_flag, &unlog_flag,
       "do not destroy tokens", NULL },
+#endif
     { "delete-v4",	0,   arg_negative_flag, &dest_tkt_flag,
       "do not destroy v4 tickets", NULL },
     { "version", 	0,   arg_flag, &version_flag, NULL, NULL },
@@ -75,15 +80,15 @@
=20
     if(getarg(args, num_args, argc, argv, &optidx))
 	usage(1);
- =20
+
     if (help_flag)
 	usage (0);
- =20
+
     if(version_flag){
 	print_version(NULL);
 	exit(0);
     }
- =20
+
     argc -=3D optidx;
     argv +=3D optidx;
=20
@@ -93,58 +98,75 @@
     ret =3D krb5_init_context (&context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
- =20
-    if(cache =3D=3D NULL) {
-	cache =3D krb5_cc_default_name(context);
-	if (cache =3D=3D NULL) {
-	    warnx ("krb5_cc_default_name: %s", krb5_get_err_text(context, ret));
-	    exit(1);
+
+    if (all_flag) {
+	krb5_cccol_cursor cursor;
+
+	ret =3D krb5_cccol_cursor_new (context, &cursor);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_cccol_cursor_new");
+
+	while (krb5_cccol_cursor_next (context, cursor, &ccache) =3D=3D 0 && ccac=
he !=3D NULL) {
+
+	    ret =3D krb5_cc_destroy (context, ccache);
+	    if (ret) {
+		krb5_warn(context, ret, "krb5_cc_destroy");
+		exit_val =3D 1;
+	    }
 	}
-    }
+	krb5_cccol_cursor_free(context, &cursor);
=20
-    ret =3D  krb5_cc_resolve(context,
-			   cache,=20
-			   &ccache);
-
-    if (ret =3D=3D 0) {
-	if (credential) {
-	    krb5_creds mcred;
-	   =20
-	    krb5_cc_clear_mcred(&mcred);
-
-	    ret =3D krb5_parse_name(context, credential, &mcred.server);
+    } else {
+	if(cache =3D=3D NULL) {
+	    ret =3D krb5_cc_default(context, &ccache);
 	    if (ret)
-		krb5_err(context, 1, ret,
-			 "Can't parse principal %s", credential);
-
-	    ret =3D krb5_cc_remove_cred(context, ccache, 0, &mcred);
+		krb5_err(context, 1, ret, "krb5_cc_default");
+	} else {
+	    ret =3D  krb5_cc_resolve(context,
+				   cache,
+				   &ccache);
 	    if (ret)
-		krb5_err(context, 1, ret,=20
-			 "Failed to remove principal %s", credential);
-
-	    krb5_cc_close(context, ccache);
-	    krb5_free_principal(context, mcred.server);
-	    krb5_free_context(context);
-	    return 0;
+		krb5_err(context, 1, ret, "krb5_cc_resolve");
 	}
=20
-	ret =3D krb5_cc_destroy (context, ccache);
-	if (ret) {
-	    warnx ("krb5_cc_destroy: %s", krb5_get_err_text(context, ret));
-	    exit_val =3D 1;
+	if (ret =3D=3D 0) {
+	    if (credential) {
+		krb5_creds mcred;
+
+		krb5_cc_clear_mcred(&mcred);
+
+		ret =3D krb5_parse_name(context, credential, &mcred.server);
+		if (ret)
+		    krb5_err(context, 1, ret,
+			     "Can't parse principal %s", credential);
+
+		ret =3D krb5_cc_remove_cred(context, ccache, 0, &mcred);
+		if (ret)
+		    krb5_err(context, 1, ret,
+			     "Failed to remove principal %s", credential);
+
+		krb5_cc_close(context, ccache);
+		krb5_free_principal(context, mcred.server);
+		krb5_free_context(context);
+		return 0;
+	    }
+
+	    ret =3D krb5_cc_destroy (context, ccache);
+	    if (ret) {
+		krb5_warn(context, ret, "krb5_cc_destroy");
+		exit_val =3D 1;
+	    }
 	}
-    } else {
-	warnx ("krb5_cc_resolve(%s): %s", cache,
-	       krb5_get_err_text(context, ret));
-	exit_val =3D 1;
     }
=20
     krb5_free_context (context);
=20
+#ifndef NO_AFS
     if (unlog_flag && k_hasafs ()) {
 	if (k_unlog ())
 	    exit_val =3D 1;
     }
+#endif
=20
     return exit_val;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kdigest-comm=
ands.in
--- a/head/crypto/heimdal/kuser/kdigest-commands.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/kuser/kdigest-commands.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).=20
  * All rights reserved.=20
  *
@@ -30,7 +30,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
  * SUCH DAMAGE.=20
  */
-/* $Id: kdigest-commands.in 22157 2007-12-04 20:03:29Z lha $ */
+/* $Id$ */
=20
 command =3D {
 	name =3D "digest-probe"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kdigest.c
--- a/head/crypto/heimdal/kuser/kdigest.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kdigest.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,40 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
+#define HC_DEPRECATED_CRYPTO
+
 #include "kuser_locl.h"
-RCSID("$Id: kdigest.c 22158 2007-12-04 20:04:01Z lha $");
+
 #include <kdigest-commands.h>
 #include <hex.h>
 #include <base64.h>
@@ -98,7 +100,7 @@
 	krb5_err(context, 1, ret, "krb5_digest_set_type");
=20
     if (opt->cb_type_string && opt->cb_value_string) {
-	ret =3D krb5_digest_set_server_cb(context, digest,=20
+	ret =3D krb5_digest_set_server_cb(context, digest,
 					opt->cb_type_string,
 					opt->cb_value_string);
 	if (ret)
@@ -112,7 +114,7 @@
 	krb5_err(context, 1, ret, "krb5_digest_init_request");
=20
     printf("type=3D%s\n", opt->type_string);
-    printf("server-nonce=3D%s\n",=20
+    printf("server-nonce=3D%s\n",
 	   krb5_digest_get_server_nonce(context, digest));
     {
 	const char *s =3D krb5_digest_get_identifier(context, digest);
@@ -121,11 +123,13 @@
     }
     printf("opaque=3D%s\n", krb5_digest_get_opaque(context, digest));
=20
+    krb5_digest_free(digest);
+
     return 0;
 }
=20
 int
-digest_server_request(struct digest_server_request_options *opt,=20
+digest_server_request(struct digest_server_request_options *opt,
 		      int argc, char **argv)
 {
     krb5_error_code ret;
@@ -150,7 +154,7 @@
 	if (opt->server_identifier_string =3D=3D NULL)
 	    errx(1, "server identifier missing");
=20
-	ret =3D krb5_digest_set_identifier(context, digest,=20
+	ret =3D krb5_digest_set_identifier(context, digest,
 					 opt->server_identifier_string);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_digest_set_type");
@@ -164,13 +168,13 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_digest_set_username");
=20
-    ret =3D krb5_digest_set_server_nonce(context, digest,=20
+    ret =3D krb5_digest_set_server_nonce(context, digest,
 				       opt->server_nonce_string);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_digest_set_server_nonce");
=20
     if(opt->client_nonce_string) {
-	ret =3D krb5_digest_set_client_nonce(context, digest,=20
+	ret =3D krb5_digest_set_client_nonce(context, digest,
 					   opt->client_nonce_string);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_digest_set_client_nonce");
@@ -181,7 +185,7 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_digest_set_opaque");
=20
-    ret =3D krb5_digest_set_responseData(context, digest,=20
+    ret =3D krb5_digest_set_responseData(context, digest,
 				       opt->client_response_string);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_digest_set_responseData");
@@ -213,6 +217,8 @@
 	free(key);
     }
=20
+    krb5_digest_free(digest);
+
     return 0;
 }
=20
@@ -221,15 +227,19 @@
 	    unsigned char server_identifier,
 	    const char *password)
 {
-    MD5_CTX ctx;
+    EVP_MD_CTX *ctx;
     unsigned char md[MD5_DIGEST_LENGTH];
     char *h;
=20
-    MD5_Init(&ctx);
-    MD5_Update(&ctx, &server_identifier, 1);
-    MD5_Update(&ctx, password, strlen(password));
-    MD5_Update(&ctx, server_nonce, snoncelen);
-    MD5_Final(md, &ctx);
+    ctx =3D EVP_MD_CTX_create();
+    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+
+    EVP_DigestUpdate(ctx, &server_identifier, 1);
+    EVP_DigestUpdate(ctx, password, strlen(password));
+    EVP_DigestUpdate(ctx, server_nonce, snoncelen);
+    EVP_DigestFinal_ex(ctx, md, NULL);
+
+    EVP_MD_CTX_destroy(ctx);
=20
     hex_encode(md, 16, &h);
=20
@@ -262,27 +272,31 @@
 		const char *username,
 		const char *password)
 {
-    SHA_CTX ctx;
-    MD4_CTX hctx;
-    unsigned char md[SHA_DIGEST_LENGTH], challange[SHA_DIGEST_LENGTH];
+    EVP_MD_CTX *hctx, *ctx;
+    unsigned char md[SHA_DIGEST_LENGTH], challenge[SHA_DIGEST_LENGTH];
     unsigned char hmd[MD4_DIGEST_LENGTH];
     struct ntlm_buf answer;
     int i, len, ret;
     char *h;
=20
-    SHA1_Init(&ctx);
-    SHA1_Update(&ctx, client_nonce, cnoncelen);
-    SHA1_Update(&ctx, server_nonce, snoncelen);
-    SHA1_Update(&ctx, username, strlen(username));
-    SHA1_Final(md, &ctx);
+    ctx =3D EVP_MD_CTX_create();
+    EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
=20
-    MD4_Init(&hctx);
+    EVP_DigestUpdate(ctx, client_nonce, cnoncelen);
+    EVP_DigestUpdate(ctx, server_nonce, snoncelen);
+    EVP_DigestUpdate(ctx, username, strlen(username));
+    EVP_DigestFinal_ex(ctx, md, NULL);
+
+
+    hctx =3D EVP_MD_CTX_create();
+    EVP_DigestInit_ex(hctx, EVP_md4(), NULL);
     len =3D strlen(password);
     for (i =3D 0; i < len; i++) {
-	MD4_Update(&hctx, &password[i], 1);
-	MD4_Update(&hctx, &password[len], 1);
-    }=09
-    MD4_Final(hmd, &hctx);
+	EVP_DigestUpdate(hctx, &password[i], 1);
+	EVP_DigestUpdate(hctx, &password[len], 1);
+    }
+    EVP_DigestFinal_ex(hctx, hmd, NULL);
+
=20
     /* ChallengeResponse */
     ret =3D heim_ntlm_calculate_ntlm1(hmd, sizeof(hmd), md, &answer);
@@ -294,51 +308,55 @@
     free(h);
=20
     /* PasswordHash */
-    MD4_Init(&hctx);
-    MD4_Update(&hctx, hmd, sizeof(hmd));
-    MD4_Final(hmd, &hctx);
+    EVP_DigestInit_ex(hctx, EVP_md4(), NULL);
+    EVP_DigestUpdate(hctx, hmd, sizeof(hmd));
+    EVP_DigestFinal_ex(hctx, hmd, NULL);
+
=20
     /* GenerateAuthenticatorResponse */
-    SHA1_Init(&ctx);
-    SHA1_Update(&ctx, hmd, sizeof(hmd));
-    SHA1_Update(&ctx, answer.data, answer.length);
-    SHA1_Update(&ctx, ms_chap_v2_magic1, sizeof(ms_chap_v2_magic1));
-    SHA1_Final(md, &ctx);
-   =20
+    EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+    EVP_DigestUpdate(ctx, hmd, sizeof(hmd));
+    EVP_DigestUpdate(ctx, answer.data, answer.length);
+    EVP_DigestUpdate(ctx, ms_chap_v2_magic1, sizeof(ms_chap_v2_magic1));
+    EVP_DigestFinal_ex(ctx, md, NULL);
+
     /* ChallengeHash */
-    SHA1_Init(&ctx);
-    SHA1_Update(&ctx, client_nonce, cnoncelen);
-    SHA1_Update(&ctx, server_nonce, snoncelen);
-    SHA1_Update(&ctx, username, strlen(username));
-    SHA1_Final(challange, &ctx);
+    EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+    EVP_DigestUpdate(ctx, client_nonce, cnoncelen);
+    EVP_DigestUpdate(ctx, server_nonce, snoncelen);
+    EVP_DigestUpdate(ctx, username, strlen(username));
+    EVP_DigestFinal_ex(ctx, challenge, NULL);
=20
-    SHA1_Init(&ctx);
-    SHA1_Update(&ctx, md, sizeof(md));
-    SHA1_Update(&ctx, challange, 8);
-    SHA1_Update(&ctx, ms_chap_v2_magic2, sizeof(ms_chap_v2_magic2));
-    SHA1_Final(md, &ctx);
+    EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+    EVP_DigestUpdate(ctx, md, sizeof(md));
+    EVP_DigestUpdate(ctx, challenge, 8);
+    EVP_DigestUpdate(ctx, ms_chap_v2_magic2, sizeof(ms_chap_v2_magic2));
+    EVP_DigestFinal_ex(ctx, md, NULL);
=20
     hex_encode(md, sizeof(md), &h);
     printf("AuthenticatorResponse=3D%s\n", h);
     free(h);
=20
     /* get_master, rfc 3079 3.4 */
-    SHA1_Init(&ctx);
-    SHA1_Update(&ctx, hmd, sizeof(hmd));
-    SHA1_Update(&ctx, answer.data, answer.length);
-    SHA1_Update(&ctx, ms_rfc3079_magic1, sizeof(ms_rfc3079_magic1));
-    SHA1_Final(md, &ctx);
+    EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+    EVP_DigestUpdate(ctx, hmd, sizeof(hmd));
+    EVP_DigestUpdate(ctx, answer.data, answer.length);
+    EVP_DigestUpdate(ctx, ms_rfc3079_magic1, sizeof(ms_rfc3079_magic1));
+    EVP_DigestFinal_ex(ctx, md, NULL);
=20
     free(answer.data);
=20
     hex_encode(md, 16, &h);
     printf("session-key=3D%s\n", h);
     free(h);
+
+    EVP_MD_CTX_destroy(hctx);
+    EVP_MD_CTX_destroy(ctx);
 }
=20
=20
 int
-digest_client_request(struct digest_client_request_options *opt,=20
+digest_client_request(struct digest_client_request_options *opt,
 		      int argc, char **argv)
 {
     char *server_nonce, *client_nonce =3D NULL, server_identifier;
@@ -358,7 +376,7 @@
 	errx(1, "server_nonce");
=20
     snoncelen =3D hex_decode(opt->server_nonce_string, server_nonce, snonc=
elen);
-    if (snoncelen <=3D 0)=20
+    if (snoncelen <=3D 0)
 	errx(1, "server nonce wrong");
=20
     if (opt->client_nonce_string) {
@@ -366,10 +384,10 @@
 	client_nonce =3D malloc(cnoncelen);
 	if (client_nonce =3D=3D NULL)
 	    errx(1, "client_nonce");
-=09
-	cnoncelen =3D hex_decode(opt->client_nonce_string,=20
+
+	cnoncelen =3D hex_decode(opt->client_nonce_string,
 			       client_nonce, cnoncelen);
-	if (cnoncelen <=3D 0)=20
+	if (cnoncelen <=3D 0)
 	    errx(1, "client nonce wrong");
     }
=20
@@ -385,7 +403,7 @@
 	if (opt->server_identifier_string =3D=3D NULL)
 	    errx(1, "server identifier missing");
=20
-	client_chap(server_nonce, snoncelen, server_identifier,=20
+	client_chap(server_nonce, snoncelen, server_identifier,
 		    opt->password_string);
=20
     } else if (strcasecmp(opt->type_string, "MS-CHAP-V2") =3D=3D 0) {
@@ -395,11 +413,13 @@
 	    errx(1, "client nonce missing");
=20
 	client_mschapv2(server_nonce, snoncelen,
-			client_nonce, cnoncelen,=20
+			client_nonce, cnoncelen,
 			opt->username_string,
 			opt->password_string);
     }
-=09
+    if (client_nonce)
+	free(client_nonce);
+    free(server_nonce);
=20
     return 0;
 }
@@ -413,9 +433,10 @@
     krb5_error_code ret;
     krb5_ntlm ntlm;
     struct ntlm_type2 type2;
-    krb5_data challange, opaque;
+    krb5_data challenge, opaque;
     struct ntlm_buf data;
     char *s;
+    static char zero2[] =3D "\x00\x00";
=20
     memset(&type2, 0, sizeof(type2));
=20
@@ -423,7 +444,7 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_ntlm_alloc");
=20
-    ret =3D krb5_ntlm_init_request(context,=20
+    ret =3D krb5_ntlm_init_request(context,
 				 ntlm,
 				 opt->kerberos_realm_string,
 				 id,
@@ -437,29 +458,29 @@
      *
      */
=20
-    ret =3D krb5_ntlm_init_get_challange(context, ntlm, &challange);
+    ret =3D krb5_ntlm_init_get_challange(context, ntlm, &challenge);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_ntlm_init_get_challange");
=20
-    if (challange.length !=3D sizeof(type2.challange))
-	krb5_errx(context, 1, "ntlm challange have wrong length");
-    memcpy(type2.challange, challange.data, sizeof(type2.challange));
-    krb5_data_free(&challange);
+    if (challenge.length !=3D sizeof(type2.challenge))
+	krb5_errx(context, 1, "ntlm challenge have wrong length");
+    memcpy(type2.challenge, challenge.data, sizeof(type2.challenge));
+    krb5_data_free(&challenge);
=20
     ret =3D krb5_ntlm_init_get_flags(context, ntlm, &type2.flags);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_ntlm_init_get_flags");
=20
     krb5_ntlm_init_get_targetname(context, ntlm, &type2.targetname);
-    type2.targetinfo.data =3D "\x00\x00";
+    type2.targetinfo.data =3D zero2;
     type2.targetinfo.length =3D 2;
-=09
+
     ret =3D heim_ntlm_encode_type2(&type2, &data);
     if (ret)
 	krb5_errx(context, 1, "heim_ntlm_encode_type2");
=20
     free(type2.targetname);
-=09
+
     /*
      *
      */
@@ -519,7 +540,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kgetcred.1
--- a/head/crypto/heimdal/kuser/kgetcred.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kgetcred.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 1999, 2001 - 2002 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1999, 2001 - 2002 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: kgetcred.1 14090 2004-08-05 18:49:47Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd March 12, 2004
 .Dt KGETCRED 1
@@ -39,18 +39,18 @@
 .Nd "get a ticket for a particular service"
 .Sh SYNOPSIS
 .Nm
-.Op Fl -canonicalize
+.Op Fl Fl canonicalize
 .Oo Fl c cache \*(Ba Xo
-.Fl -cache=3D Ns Ar cache
+.Fl Fl cache=3D Ns Ar cache
 .Xc
 .Oc
 .Oo Fl e Ar enctype \*(Ba Xo
-.Fl -enctype=3D Ns Ar enctype
+.Fl Fl enctype=3D Ns Ar enctype
 .Xc
 .Oc
-.Op Fl -no-transit-check
-.Op Fl -version
-.Op Fl -help
+.Op Fl Fl no-transit-check
+.Op Fl Fl version
+.Op Fl Fl help
 .Ar service
 .Sh DESCRIPTION
 .Nm
@@ -61,30 +61,16 @@
 .Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl -canonicalize
-.Xc
+.It Fl Fl canonicalize
 requests that the KDC canonicalize the principal.
-.It Xo
-.Fl c Ar cache ,
-.Fl -cache=3D Ns Ar cache
-.Xc
+.It Fl c Ar cache , Fl Fl cache=3D Ns Ar cache
 the credential cache to use.
-.It Xo
-.Fl e Ar enctype ,
-.Fl -enctype=3D Ns Ar enctype
-.Xc
+.It Fl e Ar enctype , Fl Fl enctype=3D Ns Ar enctype
 encryption type to use.
-.It Xo
-.Fl -no-transit-check
-.Xc
-requests that the KDC doesn't do trasnit checking.
-.It Xo
-.Fl -version
-.Xc
-.It Xo
-.Fl -help
-.Xc
+.It Fl Fl no-transit-check
+requests that the KDC doesn't do transit checking.
+.It Fl Fl version
+.It Fl Fl help
 .El
 .Sh SEE ALSO
 .Xr kinit 1 ,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kgetcred.c
--- a/head/crypto/heimdal/kuser/kgetcred.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kgetcred.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,46 +1,45 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kuser_locl.h"
=20
-RCSID("$Id: kgetcred.c 22276 2007-12-12 02:42:31Z lha $");
-
 static char *cache_str;
 static char *out_cache_str;
 static char *delegation_cred_str;
 static char *etype_str;
 static int transit_flag =3D 1;
 static int forwardable_flag;
+static int canonicalize_flag;
 static char *impersonate_str;
 static char *nametype_str;
 static int version_flag;
@@ -48,21 +47,23 @@
=20
 struct getargs args[] =3D {
     { "cache",		'c', arg_string, &cache_str,
-      "credential cache to use", "cache"},
+      NP_("credential cache to use", ""), "cache"},
     { "out-cache",	0,   arg_string, &out_cache_str,
-      "credential cache to store credential in", "cache"},
+      NP_("credential cache to store credential in", ""), "cache"},
     { "delegation-credential-cache",0,arg_string, &delegation_cred_str,
-      "where to find the ticket use for delegation", "cache"},
+      NP_("where to find the ticket use for delegation", ""), "cache"},
+    { "canonicalize",	0, arg_flag, &canonicalize_flag,
+      NP_("canonicalize the principal", ""), NULL },
     { "forwardable",	0, arg_flag, &forwardable_flag,
-      "forwardable ticket requested"},
-    { "transit-check",	0,   arg_negative_flag, &transit_flag },
+      NP_("forwardable ticket requested", ""), NULL},
+    { "transit-check",	0,   arg_negative_flag, &transit_flag, NULL, NULL },
     { "enctype",	'e', arg_string, &etype_str,
-      "encryption type to use", "enctype"},
+      NP_("encryption type to use", ""), "enctype"},
     { "impersonate",	0,   arg_string, &impersonate_str,
-      "client to impersonate", "principal"},
-    { "name-type",		0,   arg_string, &nametype_str },
-    { "version", 	0,   arg_flag, &version_flag },
-    { "help",		0,   arg_flag, &help_flag }
+      NP_("client to impersonate", ""), "principal"},
+    { "name-type",		0,   arg_string, &nametype_str, NULL, NULL },
+    { "version", 	0,   arg_flag, &version_flag, NULL, NULL },
+    { "help",		0,   arg_flag, &help_flag, NULL, NULL }
 };
=20
 static void
@@ -92,10 +93,10 @@
     ret =3D krb5_init_context (&context);
     if (ret)
 	errx(1, "krb5_init_context failed: %d", ret);
- =20
+
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -129,7 +130,8 @@
=20
 	ret =3D krb5_string_to_enctype(context, etype_str, &enctype);
 	if (ret)
-	    krb5_errx (context, 1, "unrecognized enctype: %s", etype_str);
+	    krb5_errx (context, 1, N_("unrecognized enctype: %s", ""),
+		       etype_str);
 	krb5_get_creds_opt_set_enctype(context, opt, enctype);
     }
=20
@@ -148,6 +150,8 @@
 	krb5_get_creds_opt_add_options(context, opt, KRB5_GC_FORWARDABLE);
     if (!transit_flag)
 	krb5_get_creds_opt_add_options(context, opt, KRB5_GC_NO_TRANSIT_CHECK);
+    if (canonicalize_flag)
+	krb5_get_creds_opt_add_options(context, opt, KRB5_GC_CANONICALIZE);
=20
     if (delegation_cred_str) {
 	krb5_ccache id;
@@ -169,7 +173,7 @@
=20
 	ret =3D decode_Ticket(c.ticket.data, c.ticket.length, &ticket, NULL);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    krb5_err (context, 1, ret, "decode_Ticket");
 	}
 	krb5_free_cred_contents(context, &c);
@@ -182,7 +186,7 @@
 	krb5_cc_close (context, id);
 	krb5_free_principal(context, mc.server);
=20
-	krb5_get_creds_opt_add_options(context, opt,=20
+	krb5_get_creds_opt_add_options(context, opt,
 				       KRB5_GC_CONSTRAINED_DELEGATION);
     }
=20
@@ -191,10 +195,13 @@
 	krb5_err (context, 1, ret, "krb5_parse_name %s", argv[0]);
=20
     if (nametype_str) {
-	ret =3D krb5_parse_nametype(context, nametype_str,
-				  &server->name.name_type);
+	int32_t nametype;
+
+	ret =3D krb5_parse_nametype(context, nametype_str, &nametype);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_parse_nametype");
+
+	server->name.name_type =3D (NAME_TYPE)nametype;
     }
=20
     ret =3D krb5_get_creds(context, opt, cache, server, &out);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kimpersonate=
.c
--- a/head/crypto/heimdal/kuser/kimpersonate.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/kuser/kimpersonate.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000 - 2007 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000 - 2007 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -32,7 +32,6 @@
  */
=20
 #include "kuser_locl.h"
-RCSID("$Id: kimpersonate.c 22117 2007-12-03 21:24:16Z lha $");
 #include <parse_units.h>
=20
 static char *client_principal_str =3D NULL;
@@ -45,19 +44,21 @@
 static char *ticket_flags_str =3D NULL;
 static TicketFlags ticket_flags;
 static char *keytab_file =3D NULL;
-static char *enc_type =3D "des-cbc-md5";
+static char *enctype_string =3D NULL;
 static int   expiration_time =3D 3600;
 static struct getarg_strings client_addresses;
 static int   version_flag =3D 0;
 static int   help_flag =3D 0;
 static int   use_krb5 =3D 1;
=20
+static const char *enc_type =3D "des-cbc-md5";
+
 /*
  *
  */
=20
 static void
-encode_ticket (krb5_context context,=20
+encode_ticket (krb5_context context,
 	       EncryptionKey *skey,
 	       krb5_enctype etype,
 	       int skvno,
@@ -68,24 +69,24 @@
     krb5_error_code ret;
     krb5_crypto crypto;
     EncryptedData enc_part;
-    EncTicketPart et;   =20
+    EncTicketPart et;
     Ticket ticket;
=20
     memset (&enc_part, 0, sizeof(enc_part));
     memset (&ticket, 0, sizeof(ticket));
-   =20
+
     /*
      * Set up `enc_part'
      */
=20
     et.flags =3D cred->flags.b;
     et.key =3D cred->session;
-    et.crealm =3D *krb5_princ_realm (context, cred->client);
+    et.crealm =3D cred->client->realm;
     copy_PrincipalName(&cred->client->name, &et.cname);
     {
 	krb5_data empty_string;
-=09
-	krb5_data_zero(&empty_string);=20
+
+	krb5_data_zero(&empty_string);
 	et.transited.tr_type =3D DOMAIN_X500_COMPRESS;
 	et.transited.contents =3D empty_string;
     }
@@ -104,14 +105,19 @@
     if (ret)
 	krb5_err(context, 1, ret, "EncTicketPart");
=20
-    krb5_crypto_init(context, skey, etype, &crypto);
-    krb5_encrypt_EncryptedData (context,=20
-				crypto,
-				KRB5_KU_TICKET,
-				buf,
-				len,
-				skvno,
-				&ticket.enc_part);
+    ret =3D krb5_crypto_init(context, skey, etype, &crypto);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_crypto_init");
+    ret =3D krb5_encrypt_EncryptedData (context,
+				      crypto,
+				      KRB5_KU_TICKET,
+				      buf,
+				      len,
+				      skvno,
+				      &ticket.enc_part);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_encrypt_EncryptedData");
+
     free(buf);
     krb5_crypto_destroy(context, crypto);
=20
@@ -120,14 +126,15 @@
      */
=20
     ticket.tkt_vno =3D 5;
-    ticket.realm =3D *krb5_princ_realm (context, cred->server);
+    ticket.realm =3D cred->server->realm;
     copy_PrincipalName(&cred->server->name, &ticket.sname);
-   =20
+
     ASN1_MALLOC_ENCODE(Ticket, buf, len, &ticket, &size, ret);
     if(ret)
 	krb5_err (context, 1, ret, "encode_Ticket");
=20
     krb5_data_copy(&cred->ticket, buf, len);
+    free(buf);
 }
=20
 /*
@@ -142,13 +149,13 @@
     krb5_creds cred;
     krb5_enctype etype;
     krb5_ccache ccache;
-   =20
+
     memset (&cred, 0, sizeof(cred));
-   =20
+
     ret =3D krb5_string_to_enctype (context, enc_type, &etype);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_string_to_enctype");
-    ret =3D krb5_kt_get_entry (context, kt, server_principal,=20
+    ret =3D krb5_kt_get_entry (context, kt, server_principal,
 			     0, etype, &entry);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_kt_get_entry");
@@ -162,27 +169,27 @@
     if (ret)
 	krb5_err (context, 1, ret, "krb5_copy_principal");
     ret =3D krb5_copy_principal (context, server_principal, &cred.server);
-    if (ret)=20
+    if (ret)
 	krb5_err (context, 1, ret, "krb5_copy_principal");
-    krb5_generate_random_keyblock(context, etype, &cred.session);   =20
+    krb5_generate_random_keyblock(context, etype, &cred.session);
=20
     cred.times.authtime =3D time(NULL);
     cred.times.starttime =3D time(NULL);
     cred.times.endtime =3D time(NULL) + expiration_time;
     cred.times.renew_till =3D 0;
-    krb5_data_zero(&cred.second_ticket);=20
+    krb5_data_zero(&cred.second_ticket);
=20
     ret =3D krb5_get_all_client_addrs (context, &cred.addresses);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_get_all_client_addrs");
     cred.flags.b =3D ticket_flags;
-   =20
-   =20
+
+
     /*
      * Encode encrypted part of ticket
      */
=20
-    encode_ticket (context, &entry.keyblock, etype, entry.vno, &cred);   =20
+    encode_ticket (context, &entry.keyblock, etype, entry.vno, &cred);
=20
     /*
      * Write to cc
@@ -201,14 +208,14 @@
     ret =3D krb5_cc_initialize (context, ccache, cred.client);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_initialize");
-   =20
+
     ret =3D krb5_cc_store_cred (context, ccache, &cred);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_store_cred");
=20
     krb5_free_cred_contents (context, &cred);
     krb5_cc_close (context, ccache);
-   =20
+
     return 0;
 }
=20
@@ -243,7 +250,7 @@
     if (ticket_flags_str) {
 	int ticket_flags_int;
=20
-	ticket_flags_int =3D parse_flags(ticket_flags_str,=20
+	ticket_flags_int =3D parse_flags(ticket_flags_str,
 				       asn1_TicketFlags_units(), 0);
 	if (ticket_flags_int <=3D 0) {
 	    krb5_warnx (context, "bad ticket flags: `%s'", ticket_flags_str);
@@ -262,22 +269,22 @@
 struct getargs args[] =3D {
     { "ccache", 0, arg_string, &ccache_str,
       "name of kerberos 5 credential cache", "cache-name"},
-    { "server", 's', arg_string, &server_principal_str,=20
-      "name of server principal" },
-    { "client", 'c', arg_string, &client_principal_str,=20
-      "name of client principal" },
+    { "server", 's', arg_string, &server_principal_str,
+      "name of server principal", NULL },
+    { "client", 'c', arg_string, &client_principal_str,
+      "name of client principal", NULL },
     { "keytab", 'k', arg_string, &keytab_file,
-      "name of keytab file" },
+      "name of keytab file", NULL },
     { "krb5", '5', arg_flag,	 &use_krb5,
-      "create a kerberos 5 ticket"},
+      "create a kerberos 5 ticket", NULL },
     { "expire-time", 'e', arg_integer, &expiration_time,
-      "lifetime of ticket in seconds" },
+      "lifetime of ticket in seconds", NULL },
     { "client-addresses", 'a', arg_strings, &client_addresses,
-      "addresses of client" },
-    { "enc-type", 't', arg_string, 	&enc_type,
-      "encryption type" },
+      "addresses of client", NULL },
+    { "enc-type", 't', arg_string, 	&enctype_string,
+      "encryption type", NULL },
     { "ticket-flags", 'f', arg_string,   &ticket_flags_str,
-      "ticket flags for krb5 ticket" },
+      "ticket flags for krb5 ticket", NULL },
     { "version", 0,  arg_flag,		&version_flag,	"Print version",
       NULL },
     { "help",	 0,  arg_flag,		&help_flag,	NULL,
@@ -297,7 +304,7 @@
 int
 main (int argc, char **argv)
 {
-    int optind =3D 0;
+    int optidx =3D 0;
     krb5_error_code ret;
     krb5_context context;
     krb5_keytab kt;
@@ -308,23 +315,26 @@
     if (ret)
 	errx(1, "krb5_init_context failed: %u", ret);
=20
-    if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
-		&optind))
-	usage (1);
+    if (getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+	usage(1);
=20
     if (help_flag)
-	usage (0);
+	usage(0);
=20
     if (version_flag) {
 	print_version(NULL);
 	return 0;
     }
=20
-    setup_env (context, &kt);
+    if (enctype_string)
+	enc_type =3D enctype_string;
+
+    setup_env(context, &kt);
=20
     if (use_krb5)
-	create_krb5_tickets (context, kt);
+	create_krb5_tickets(context, kt);
=20
-    krb5_kt_close (context, kt);
+    krb5_kt_close(context, kt);
+
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kinit.1
--- a/head/crypto/heimdal/kuser/kinit.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kinit.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,92 +1,90 @@
-.\" Copyright (c) 1998 - 2003, 2006 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1998 - 2003, 2006 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: kinit.1 17822 2006-07-10 14:46:58Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd April 25, 2006
 .Dt KINIT 1
 .Os HEIMDAL
 .Sh NAME
 .Nm kinit
-.Nm kauth
 .Nd acquire initial tickets
 .Sh SYNOPSIS
 .Nm kinit
-.Op Fl 4 | Fl -524init
-.Op Fl 9 | Fl -524convert
-.Op Fl -afslog
+.Op Fl Fl afslog
 .Oo Fl c Ar cachename \*(Ba Xo
-.Fl -cache=3D Ns Ar cachename
+.Fl Fl cache=3D Ns Ar cachename
 .Xc
 .Oc
-.Op Fl f | Fl -forwardable
+.Op Fl f | Fl Fl no-forwardable
 .Oo Fl t Ar keytabname \*(Ba Xo
-.Fl -keytab=3D Ns Ar keytabname
+.Fl Fl keytab=3D Ns Ar keytabname
 .Xc
 .Oc
 .Oo Fl l Ar time \*(Ba Xo
-.Fl -lifetime=3D Ns Ar time
+.Fl Fl lifetime=3D Ns Ar time
 .Xc
 .Oc
-.Op Fl p | Fl -proxiable
-.Op Fl R | Fl -renew
-.Op Fl -renewable
+.Op Fl p | Fl Fl proxiable
+.Op Fl R | Fl Fl renew
+.Op Fl Fl renewable
 .Oo Fl r Ar time \*(Ba Xo
-.Fl -renewable-life=3D Ns Ar time
+.Fl Fl renewable-life=3D Ns Ar time
 .Xc
 .Oc
 .Oo Fl S Ar principal \*(Ba Xo
-.Fl -server=3D Ns Ar principal
+.Fl Fl server=3D Ns Ar principal
 .Xc
 .Oc
 .Oo Fl s Ar time \*(Ba Xo
-.Fl -start-time=3D Ns Ar time
+.Fl Fl start-time=3D Ns Ar time
 .Xc
 .Oc
-.Op Fl k | Fl -use-keytab
-.Op Fl v | Fl -validate
+.Op Fl k | Fl Fl use-keytab
+.Op Fl v | Fl Fl validate
 .Oo Fl e Ar enctypes \*(Ba Xo
-.Fl -enctypes=3D Ns Ar enctypes
+.Fl Fl enctypes=3D Ns Ar enctypes
 .Xc
 .Oc
 .Oo Fl a Ar addresses \*(Ba Xo
-.Fl -extra-addresses=3D Ns Ar addresses
+.Fl Fl extra-addresses=3D Ns Ar addresses
 .Xc
 .Oc
-.Op Fl -password-file=3D Ns Ar filename
-.Op Fl -fcache-version=3D Ns Ar version-number
-.Op Fl A | Fl -no-addresses
-.Op Fl -anonymous
-.Op Fl -version
-.Op Fl -help
+.Op Fl Fl password-file=3D Ns Ar filename
+.Op Fl Fl fcache-version=3D Ns Ar version-number
+.Op Fl A | Fl Fl no-addresses
+.Op Fl Fl anonymous
+.Op Fl Fl enterprise
+.Op Fl Fl version
+.Op Fl Fl help
 .Op Ar principal Op Ar command
 .Sh DESCRIPTION
 .Nm
@@ -96,97 +94,53 @@
 name at the default realm), and acquire a ticket granting ticket that
 can later be used to obtain tickets for other services.
 .Pp
-If you have compiled
-.Nm kinit
-with Kerberos 4 support and you have a
-Kerberos 4 server,
-.Nm
-will detect this and get you Kerberos 4 tickets.
-.Pp
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar cachename
-.Fl -cache=3D Ns Ar cachename
-.Xc
+.It Fl c Ar cachename Fl Fl cache=3D Ns Ar cachename
 The credentials cache to put the acquired ticket in, if other than
 default.
-.It Xo
-.Fl f ,
-.Fl -forwardable
-.Xc
-Get ticket that can be forwarded to another host.
-.It Xo
-.Fl t Ar keytabname ,
-.Fl -keytab=3D Ns Ar keytabname
-.Xc
+.It Fl f Fl Fl no-forwardable
+Get ticket that can be forwarded to another host, or if the negative
+flags use, don't get a forwardable flag.
+.It Fl t Ar keytabname , Fl Fl keytab=3D Ns Ar keytabname
 Don't ask for a password, but instead get the key from the specified
 keytab.
-.It Xo
-.Fl l Ar time ,
-.Fl -lifetime=3D Ns Ar time
-.Xc
+.It Fl l Ar time , Fl Fl lifetime=3D Ns Ar time
 Specifies the lifetime of the ticket.
 The argument can either be in seconds, or a more human readable string
 like
 .Sq 1h .
-.It Xo
-.Fl p ,
-.Fl -proxiable
-.Xc
+.It Fl p , Fl Fl proxiable
 Request tickets with the proxiable flag set.
-.It Xo
-.Fl R ,
-.Fl -renew
-.Xc
+.It Fl R , Fl Fl renew
 Try to renew ticket.
 The ticket must have the
 .Sq renewable
 flag set, and must not be expired.
-.It Fl -renewable
+.It Fl Fl renewable
 The same as
-.Fl -renewable-life ,
+.Fl Fl renewable-life ,
 with an infinite time.
-.It Xo
-.Fl r Ar time ,
-.Fl -renewable-life=3D Ns Ar time
-.Xc
+.It Fl r Ar time , Fl Fl renewable-life=3D Ns Ar time
 The max renewable ticket life.
-.It Xo
-.Fl S Ar principal ,
-.Fl -server=3D Ns Ar principal
-.Xc
+.It Fl S Ar principal , Fl Fl server=3D Ns Ar principal
 Get a ticket for a service other than krbtgt/LOCAL.REALM.
-.It Xo
-.Fl s Ar time ,
-.Fl -start-time=3D Ns Ar time
-.Xc
+.It Fl s Ar time , Fl Fl start-time=3D Ns Ar time
 Obtain a ticket that starts to be valid
 .Ar time
 (which can really be a generic time specification, like
 .Sq 1h )
 seconds into the future.
-.It Xo
-.Fl k ,
-.Fl -use-keytab
-.Xc
+.It Fl k , Fl Fl use-keytab
 The same as
-.Fl -keytab ,
+.Fl Fl keytab ,
 but with the default keytab name (normally
 .Ar FILE:/etc/krb5.keytab ) .
-.It Xo
-.Fl v ,
-.Fl -validate
-.Xc
+.It Fl v , Fl Fl validate
 Try to validate an invalid ticket.
-.It Xo
-.Fl e ,
-.Fl -enctypes=3D Ns Ar enctypes
-.Xc
+.It Fl e , Fl Fl enctypes=3D Ns Ar enctypes
 Request tickets with this particular enctype.
-.It Xo
-.Fl -password-file=3D Ns Ar filename
-.Xc
+.It Fl Fl password-file=3D Ns Ar filename
 read the password from the first line of
 .Ar filename .
 If the
@@ -194,15 +148,10 @@
 is
 .Ar STDIN ,
 the password will be read from the standard input.
-.It Xo
-.Fl -fcache-version=3D Ns Ar version-number
-.Xc
+.It Fl Fl fcache-version=3D Ns Ar version-number
 Create a credentials cache of version
 .Ar version-number .
-.It Xo
-.Fl a ,
-.Fl -extra-addresses=3D Ns Ar enctypes
-.Xc
+.It Fl a , Fl Fl extra-addresses=3D Ns Ar enctypes
 Adds a set of addresses that will, in addition to the systems local
 addresses, be put in the ticket.
 This can be useful if all addresses a client can use can't be
@@ -212,36 +161,23 @@
 .Li libdefaults/extra_addresses
 in
 .Xr krb5.conf 5 .
-.It Xo
-.Fl A ,
-.Fl -no-addresses
-.Xc
+.It Fl A , Fl Fl no-addresses
 Request a ticket with no addresses.
-.It Xo
-.Fl -anonymous
-.Xc
+.It Fl Fl anonymous
 Request an anonymous ticket (which means that the ticket will be
 issued to an anonymous principal, typically
 .Dq anonymous at REALM ) .
-.El
-.Pp
-The following options are only available if
-.Nm
-has been compiled with support for Kerberos 4.
-.Bl -tag -width Ds
-.It Xo
-.Fl 4 ,
-.Fl -524init
-.Xc
-Try to convert the obtained Kerberos 5 krbtgt to a version 4
-compatible ticket.
-It will store this ticket in the default Kerberos 4 ticket file.
-.It Xo
-.Fl 9 ,
-.Fl -524convert
-.Xc
-only convert ticket to version 4
-.It Fl -afslog
+.It Fl Fl enterprise
+Parse principal as a enterprise (KRB5-NT-ENTERPRISE) name. Enterprise
+names are email like principals that are stored in the name part of
+the principal, and since there are two @ characters the parser needs
+to know that the first is not a realm.
+An example of an enterprise name is
+.Dq lha at e.kth.se@KTH.SE ,
+and this option is usually used with canonicalize so that the
+principal returned from the KDC will typically be the real principal
+name.
+.It Fl Fl afslog
 Gets AFS tickets, converts them to version 4 format, and stores them
 in the kernel.
 Only useful if you have AFS.
@@ -261,7 +197,7 @@
 If  a
 .Ar command
 is given,
-.Nm kinit
+.Nm
 will set up new credentials caches, and AFS PAG, and then run the given
 command.
 When it finishes the credentials will be removed.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kinit.c
--- a/head/crypto/heimdal/kuser/kinit.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kinit.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,47 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kuser_locl.h"
-RCSID("$Id: kinit.c 22116 2007-12-03 21:22:58Z lha $");
=20
-#include "krb5-v4compat.h"
+#ifdef __APPLE__
+#include <Security/Security.h>
+#endif
=20
+#ifndef NO_NTLM
 #include "heimntlm.h"
+#endif
=20
 int forwardable_flag	=3D -1;
 int proxiable_flag	=3D -1;
@@ -54,124 +59,153 @@
 char *server_str	=3D NULL;
 char *cred_cache	=3D NULL;
 char *start_str		=3D NULL;
+static int switch_cache_flags =3D 1;
 struct getarg_strings etype_str;
 int use_keytab		=3D 0;
 char *keytab_str	=3D NULL;
 int do_afslog		=3D -1;
-int get_v4_tgt		=3D -1;
-int convert_524		=3D 0;
 int fcache_version;
 char *password_file	=3D NULL;
 char *pk_user_id	=3D NULL;
+int pk_enterprise_flag =3D 0;
+struct hx509_certs_data *ent_user_id =3D NULL;
 char *pk_x509_anchors	=3D NULL;
 int pk_use_enckey	=3D 0;
 static int canonicalize_flag =3D 0;
+static int enterprise_flag =3D 0;
+static int ok_as_delegate_flag =3D 0;
+static int use_referrals_flag =3D 0;
+static int windows_flag =3D 0;
+#ifndef NO_NTLM
 static char *ntlm_domain;
+#endif
=20
-static char *krb4_cc_name;
=20
 static struct getargs args[] =3D {
-    /*=20
+    /*
      * used by MIT
      * a: ~A
      * V: verbose
      * F: ~f
      * P: ~p
      * C: v4 cache name?
-     * 5:=20
+     * 5:
+     *
+     * old flags
+     * 4:
+     * 9:
      */
-    { "524init", 	'4', arg_flag, &get_v4_tgt,
-      "obtain version 4 TGT" },
-
-    { "524convert", 	'9', arg_flag, &convert_524,
-      "only convert ticket to version 4" },
-
     { "afslog", 	0  , arg_flag, &do_afslog,
-      "obtain afs tokens"  },
+      NP_("obtain afs tokens", ""), NULL },
=20
     { "cache", 		'c', arg_string, &cred_cache,
-      "credentials cache", "cachename" },
+      NP_("credentials cache", ""), "cachename" },
=20
-    { "forwardable",	'f', arg_flag, &forwardable_flag,
-      "get forwardable tickets"},
+    { "forwardable",	0, arg_negative_flag, &forwardable_flag,
+      NP_("get tickets not forwardable", ""), NULL },
+
+    { NULL,		'f', arg_flag, &forwardable_flag,
+      NP_("get forwardable tickets", ""), NULL },
=20
     { "keytab",         't', arg_string, &keytab_str,
-      "keytab to use", "keytabname" },
+      NP_("keytab to use", ""), "keytabname" },
=20
     { "lifetime",	'l', arg_string, &lifetime,
-      "lifetime of tickets", "time"},
+      NP_("lifetime of tickets", ""), "time" },
=20
     { "proxiable",	'p', arg_flag, &proxiable_flag,
-      "get proxiable tickets" },
+      NP_("get proxiable tickets", ""), NULL },
=20
     { "renew",          'R', arg_flag, &renew_flag,
-      "renew TGT" },
+      NP_("renew TGT", ""), NULL },
=20
     { "renewable",	0,   arg_flag, &renewable_flag,
-      "get renewable tickets" },
+      NP_("get renewable tickets", ""), NULL },
=20
     { "renewable-life",	'r', arg_string, &renew_life,
-      "renewable lifetime of tickets", "time" },
+      NP_("renewable lifetime of tickets", ""), "time" },
=20
     { "server", 	'S', arg_string, &server_str,
-      "server to get ticket for", "principal" },
+      NP_("server to get ticket for", ""), "principal" },
=20
     { "start-time",	's', arg_string, &start_str,
-      "when ticket gets valid", "time" },
+      NP_("when ticket gets valid", ""), "time" },
=20
     { "use-keytab",     'k', arg_flag, &use_keytab,
-      "get key from keytab" },
+      NP_("get key from keytab", ""), NULL },
=20
     { "validate",	'v', arg_flag, &validate_flag,
-      "validate TGT" },
+      NP_("validate TGT", ""), NULL },
=20
     { "enctypes",	'e', arg_strings, &etype_str,
-      "encryption types to use", "enctypes" },
+      NP_("encryption types to use", ""), "enctypes" },
=20
     { "fcache-version", 0,   arg_integer, &fcache_version,
-      "file cache version to create" },
+      NP_("file cache version to create", ""), NULL },
=20
     { "addresses",	'A',   arg_negative_flag,	&addrs_flag,
-      "request a ticket with no addresses" },
+      NP_("request a ticket with no addresses", ""), NULL },
=20
     { "extra-addresses",'a', arg_strings,	&extra_addresses,
-      "include these extra addresses", "addresses" },
+      NP_("include these extra addresses", ""), "addresses" },
=20
     { "anonymous",	0,   arg_flag,	&anonymous_flag,
-      "request an anonymous ticket" },
+      NP_("request an anonymous ticket", ""), NULL },
=20
     { "request-pac",	0,   arg_flag,	&pac_flag,
-      "request a Windows PAC" },
+      NP_("request a Windows PAC", ""), NULL },
=20
     { "password-file",	0,   arg_string, &password_file,
-      "read the password from a file" },
+      NP_("read the password from a file", ""), NULL },
=20
     { "canonicalize",0,   arg_flag, &canonicalize_flag,
-      "canonicalize client principal" },
+      NP_("canonicalize client principal", ""), NULL },
+
+    { "enterprise",0,   arg_flag, &enterprise_flag,
+      NP_("parse principal as a KRB5-NT-ENTERPRISE name", ""), NULL },
 #ifdef PKINIT
+    { "pk-enterprise",	0,	arg_flag,	&pk_enterprise_flag,
+      NP_("use enterprise name from certificate", ""), NULL },
+
     { "pk-user",	'C',	arg_string,	&pk_user_id,
-      "principal's public/private/certificate identifier", "id" },
+      NP_("principal's public/private/certificate identifier", ""), "id" },
=20
     { "x509-anchors",	'D',  arg_string, &pk_x509_anchors,
-      "directory with CA certificates", "directory" },
+      NP_("directory with CA certificates", ""), "directory" },
=20
     { "pk-use-enckey",	0,  arg_flag, &pk_use_enckey,
-      "Use RSA encrypted reply (instead of DH)" },
+      NP_("Use RSA encrypted reply (instead of DH)", ""), NULL },
 #endif
+#ifndef NO_NTLM
     { "ntlm-domain",	0,  arg_string, &ntlm_domain,
-      "NTLM domain", "domain" },
+      NP_("NTLM domain", ""), "domain" },
+#endif
=20
-    { "version", 	0,   arg_flag, &version_flag },
-    { "help",		0,   arg_flag, &help_flag }
+    { "change-default",  0,  arg_negative_flag, &switch_cache_flags,
+      NP_("switch the default cache to the new credentials cache", ""), NU=
LL },
+
+    { "ok-as-delegate",	0,  arg_flag, &ok_as_delegate_flag,
+      NP_("honor ok-as-delegate on tickets", ""), NULL },
+
+    { "use-referrals",	0,  arg_flag, &use_referrals_flag,
+      NP_("only use referrals, no dns canalisation", ""), NULL },
+
+    { "windows",	0,  arg_flag, &windows_flag,
+      NP_("get windows behavior", ""), NULL },
+
+    { "version", 	0,   arg_flag, &version_flag, NULL, NULL },
+    { "help",		0,   arg_flag, &help_flag, NULL, NULL }
 };
=20
 static void
 usage (int ret)
 {
-    arg_printusage (args,
-		    sizeof(args)/sizeof(*args),
-		    NULL,
-		    "[principal [command]]");
+    arg_printusage_i18n (args,
+			 sizeof(args)/sizeof(*args),
+			 N_("Usage: ", ""),
+			 NULL,
+			 "[principal [command]]",
+			 getarg_i18n);
     exit (ret);
 }
=20
@@ -181,63 +215,20 @@
 	   const char *server,
 	   krb5_principal *princ)
 {
-    krb5_realm *client_realm;
+    krb5_const_realm realm;
     if(server)
 	return krb5_parse_name(context, server, princ);
=20
-    client_realm =3D krb5_princ_realm (context, client);
-    return krb5_make_principal(context, princ, *client_realm,
-			       KRB5_TGS_NAME, *client_realm, NULL);
-}
-
-static krb5_error_code
-do_524init(krb5_context context, krb5_ccache ccache,=20
-	   krb5_creds *creds, const char *server)
-{
-    krb5_error_code ret;
-
-    struct credentials c;
-    krb5_creds in_creds, *real_creds;
-
-    if(creds !=3D NULL)
-	real_creds =3D creds;
-    else {
-	krb5_principal client;
-	krb5_cc_get_principal(context, ccache, &client);
-	memset(&in_creds, 0, sizeof(in_creds));
-	ret =3D get_server(context, client, server, &in_creds.server);
-	if(ret) {
-	    krb5_free_principal(context, client);
-	    return ret;
-	}
-	in_creds.client =3D client;
-	ret =3D krb5_get_credentials(context, 0, ccache, &in_creds, &real_creds);
-	krb5_free_principal(context, client);
-	krb5_free_principal(context, in_creds.server);
-	if(ret)
-	    return ret;
-    }
-    ret =3D krb524_convert_creds_kdc_ccache(context, ccache, real_creds, &=
c);
-    if(ret)
-	krb5_warn(context, ret, "converting creds");
-    else {
-	krb5_error_code tret =3D _krb5_krb_tf_setup(context, &c, NULL, 0);
-	if(tret)
-	    krb5_warn(context, tret, "saving v4 creds");
-    }
-
-    if(creds =3D=3D NULL)
-	krb5_free_creds(context, real_creds);
-    memset(&c, 0, sizeof(c));
-
-    return ret;
+    realm =3D krb5_principal_get_realm(context, client);
+    return krb5_make_principal(context, princ, realm,
+			       KRB5_TGS_NAME, realm, NULL);
 }
=20
 static int
-renew_validate(krb5_context context,=20
+renew_validate(krb5_context context,
 	       int renew,
 	       int validate,
-	       krb5_ccache cache,=20
+	       krb5_ccache cache,
 	       const char *server,
 	       krb5_deltat life)
 {
@@ -259,8 +250,8 @@
     }
=20
     if (renew) {
-	/*=20
-	 * no need to check the error here, it's only to be=20
+	/*
+	 * no need to check the error here, it's only to be
 	 * friendly to the user
 	 */
 	krb5_get_credentials(context, KRB5_GC_CACHED, cache, &in, &out);
@@ -280,7 +271,7 @@
     else if (out)
 	flags.b.proxiable 	  =3D out->flags.b.proxiable;
=20
-    if (anonymous_flag !=3D -1)
+    if (anonymous_flag)
 	flags.b.request_anonymous =3D anonymous_flag;
     if(life)
 	in.times.endtime =3D time(NULL) + life;
@@ -312,10 +303,10 @@
=20
     if(ret =3D=3D 0 && server =3D=3D NULL) {
 	/* only do this if it's a general renew-my-tgt request */
-	if(get_v4_tgt)
-	    do_524init(context, cache, out, NULL);
+#ifndef NO_AFS
 	if(do_afslog && k_hasafs())
 	    krb5_afslog(context, cache, NULL, NULL);
+#endif
     }
=20
     krb5_free_creds (context, out);
@@ -328,41 +319,33 @@
     return ret;
 }
=20
+#ifndef NO_NTLM
+
 static krb5_error_code
-store_ntlmkey(krb5_context context, krb5_ccache id,=20
-	      const char *domain, krb5_const_principal client,
-	      struct ntlm_buf *buf)
+store_ntlmkey(krb5_context context, krb5_ccache id,
+	      const char *domain, struct ntlm_buf *buf)
 {
     krb5_error_code ret;
-    krb5_creds cred;
-   =20
-    memset(&cred, 0, sizeof(cred));
+    krb5_data data;
+    char *name;
=20
-    ret =3D krb5_make_principal(context, &cred.server,
-			      krb5_principal_get_realm(context, client),
-			      "@ntlm-key", domain, NULL);
-    if (ret)
-	goto out;
-    ret =3D krb5_copy_principal(context, client, &cred.client);
-    if (ret)
-	goto out;
-   =20
-    cred.times.authtime =3D time(NULL);
-    cred.times.endtime =3D time(NULL) + 3600 * 24 * 30; /* XXX */
-    cred.session.keytype =3D ENCTYPE_ARCFOUR_HMAC_MD5;
-    ret =3D krb5_data_copy(&cred.session.keyvalue, buf->data, buf->length);
-    if (ret)
-	goto out;
+    asprintf(&name, "ntlm-key-%s", domain);
+    if (name =3D=3D NULL) {
+	krb5_clear_error_message(context);
+	return ENOMEM;
+    }
=20
-    ret =3D krb5_cc_store_cred(context, id, &cred);
+    data.length =3D buf->length;
+    data.data =3D buf->data;
=20
-out:
-    krb5_free_cred_contents (context, &cred);
-    return 0;
+    ret =3D krb5_cc_set_config(context, id, NULL, name, &data);
+    free(name);
+    return ret;
 }
+#endif
=20
 static krb5_error_code
-get_new_tickets(krb5_context context,=20
+get_new_tickets(krb5_context context,
 		krb5_principal principal,
 		krb5_ccache ccache,
 		krb5_deltat ticket_life,
@@ -374,12 +357,13 @@
     char passwd[256];
     krb5_deltat start_time =3D 0;
     krb5_deltat renew =3D 0;
-    char *renewstr =3D NULL;
+    const char *renewstr =3D NULL;
     krb5_enctype *enctype =3D NULL;
+    krb5_ccache tempccache;
+#ifndef NO_NTLM
     struct ntlm_buf ntlmkey;
-    krb5_ccache tempccache;
-
     memset(&ntlmkey, 0, sizeof(ntlmkey));
+#endif
     passwd[0] =3D '\0';
=20
     if (password_file) {
@@ -394,20 +378,48 @@
 		      password_file);
=20
 	if (fgets(passwd, sizeof(passwd), f) =3D=3D NULL)
-	    krb5_errx(context, 1,=20
-		      "Failed to read password from file %s", password_file);
+	    krb5_errx(context, 1,
+		      N_("Failed to read password from file %s", ""),
+		      password_file);
 	if (f !=3D stdin)
 	    fclose(f);
 	passwd[strcspn(passwd, "\n")] =3D '\0';
     }
=20
+#ifdef __APPLE__
+    if (passwd[0] =3D=3D '\0') {
+	const char *realm;
+	OSStatus osret;
+	UInt32 length;
+	void *buffer;
+	char *name;
+
+	realm =3D krb5_principal_get_realm(context, principal);
+
+	ret =3D krb5_unparse_name_flags(context, principal,
+				      KRB5_PRINCIPAL_UNPARSE_NO_REALM, &name);
+	if (ret)
+	    goto nopassword;
+
+	osret =3D SecKeychainFindGenericPassword(NULL, strlen(realm), realm,
+					       strlen(name), name,
+					       &length, &buffer, NULL);
+	free(name);
+	if (osret =3D=3D noErr && length < sizeof(passwd) - 1) {
+	    memcpy(passwd, buffer, length);
+	    passwd[length] =3D '\0';
+	}
+    nopassword:
+	do { } while(0);
+    }
+#endif
=20
     memset(&cred, 0, sizeof(cred));
=20
     ret =3D krb5_get_init_creds_opt_alloc (context, &opt);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_get_init_creds_opt_alloc");
-   =20
+
     krb5_get_init_creds_opt_set_default_flags(context, "kinit",
 	krb5_principal_get_realm(context, principal), opt);
=20
@@ -415,30 +427,35 @@
 	krb5_get_init_creds_opt_set_forwardable (opt, forwardable_flag);
     if(proxiable_flag !=3D -1)
 	krb5_get_init_creds_opt_set_proxiable (opt, proxiable_flag);
-    if(anonymous_flag !=3D -1)
+    if(anonymous_flag)
 	krb5_get_init_creds_opt_set_anonymous (opt, anonymous_flag);
     if (pac_flag !=3D -1)
-	krb5_get_init_creds_opt_set_pac_request(context, opt,=20
+	krb5_get_init_creds_opt_set_pac_request(context, opt,
 						pac_flag ? TRUE : FALSE);
     if (canonicalize_flag)
 	krb5_get_init_creds_opt_set_canonicalize(context, opt, TRUE);
-    if (pk_user_id) {
+    if (pk_enterprise_flag || enterprise_flag || canonicalize_flag || wind=
ows_flag)
+	krb5_get_init_creds_opt_set_win2k(context, opt, TRUE);
+    if (pk_user_id || ent_user_id || anonymous_flag) {
 	ret =3D krb5_get_init_creds_opt_set_pkinit(context, opt,
 						 principal,
 						 pk_user_id,
 						 pk_x509_anchors,
 						 NULL,
 						 NULL,
-						 pk_use_enckey ? 2 : 0,
+						 pk_use_enckey ? 2 : 0 |
+						 anonymous_flag ? 4 : 0,
 						 krb5_prompter_posix,
 						 NULL,
 						 passwd);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_get_init_creds_opt_set_pkinit");
+	if (ent_user_id)
+	    krb5_get_init_creds_opt_set_pkinit_user_certs(context, opt, ent_user_=
id);
     }
=20
     if (addrs_flag !=3D -1)
-	krb5_get_init_creds_opt_set_addressless(context, opt,=20
+	krb5_get_init_creds_opt_set_addressless(context, opt,
 						addrs_flag ? FALSE : TRUE);
=20
     if (renew_life =3D=3D NULL && renewable_flag)
@@ -449,7 +466,7 @@
 	renew =3D parse_time (renewstr, "s");
 	if (renew < 0)
 	    errx (1, "unparsable time: %s", renewstr);
-=09
+
 	krb5_get_init_creds_opt_set_renew_life (opt, renew);
     }
=20
@@ -459,7 +476,7 @@
     if(start_str) {
 	int tmp =3D parse_time (start_str, "s");
 	if (tmp < 0)
-	    errx (1, "unparsable time: %s", start_str);
+	    errx (1, N_("unparsable time: %s", ""), start_str);
=20
 	start_time =3D tmp;
     }
@@ -471,13 +488,13 @@
 	if(enctype =3D=3D NULL)
 	    errx(1, "out of memory");
 	for(i =3D 0; i < etype_str.num_strings; i++) {
-	    ret =3D krb5_string_to_enctype(context,=20
-					 etype_str.strings[i],=20
+	    ret =3D krb5_string_to_enctype(context,
+					 etype_str.strings[i],
 					 &enctype[i]);
 	    if(ret)
 		errx(1, "unrecognized enctype: %s", etype_str.strings[i]);
 	}
-	krb5_get_init_creds_opt_set_etype_list(opt, enctype,=20
+	krb5_get_init_creds_opt_set_etype_list(opt, enctype,
 					       etype_str.num_strings);
     }
=20
@@ -497,7 +514,7 @@
 					  server_str,
 					  opt);
 	krb5_kt_close(context, kt);
-    } else if (pk_user_id) {
+    } else if (pk_user_id || ent_user_id || anonymous_flag) {
 	ret =3D krb5_get_init_creds_password (context,
 					    &cred,
 					    principal,
@@ -515,11 +532,11 @@
=20
 	if (passwd[0] =3D=3D '\0') {
 	    char *p, *prompt;
-	   =20
+
 	    krb5_unparse_name (context, principal, &p);
-	    asprintf (&prompt, "%s's Password: ", p);
+	    asprintf (&prompt, N_("%s's Password: ", ""), p);
 	    free (p);
-	   =20
+
 	    if (UI_UTIL_read_pw_string(passwd, sizeof(passwd)-1, prompt, 0)){
 		memset(passwd, 0, sizeof(passwd));
 		exit(1);
@@ -527,7 +544,7 @@
 	    free (prompt);
 	}
=20
-=09
+
 	ret =3D krb5_get_init_creds_password (context,
 					    &cred,
 					    principal,
@@ -539,8 +556,10 @@
 					    opt);
     }
     krb5_get_init_creds_opt_free(context, opt);
+#ifndef NO_NTLM
     if (ntlm_domain && passwd[0])
 	heim_ntlm_nt_key(passwd, &ntlmkey);
+#endif
     memset(passwd, 0, sizeof(passwd));
=20
     switch(ret){
@@ -551,10 +570,10 @@
     case KRB5KRB_AP_ERR_BAD_INTEGRITY:
     case KRB5KRB_AP_ERR_MODIFIED:
     case KRB5KDC_ERR_PREAUTH_FAILED:
-	krb5_errx(context, 1, "Password incorrect");
+	krb5_errx(context, 1, N_("Password incorrect", ""));
 	break;
     case KRB5KRB_AP_ERR_V4_REPLY:
-	krb5_errx(context, 1, "Looks like a Kerberos 4 reply");
+	krb5_errx(context, 1, N_("Looks like a Kerberos 4 reply", ""));
 	break;
     default:
 	krb5_err(context, 1, ret, "krb5_get_init_creds");
@@ -563,22 +582,23 @@
     if(ticket_life !=3D 0) {
 	if(abs(cred.times.endtime - cred.times.starttime - ticket_life) > 30) {
 	    char life[64];
-	    unparse_time_approx(cred.times.endtime - cred.times.starttime,=20
+	    unparse_time_approx(cred.times.endtime - cred.times.starttime,
 				life, sizeof(life));
-	    krb5_warnx(context, "NOTICE: ticket lifetime is %s", life);
+	    krb5_warnx(context, N_("NOTICE: ticket lifetime is %s", ""), life);
 	}
     }
     if(renew_life) {
 	if(abs(cred.times.renew_till - cred.times.starttime - renew) > 30) {
 	    char life[64];
-	    unparse_time_approx(cred.times.renew_till - cred.times.starttime,=20
+	    unparse_time_approx(cred.times.renew_till - cred.times.starttime,
 				life, sizeof(life));
-	    krb5_warnx(context, "NOTICE: ticket renewable lifetime is %s",=20
+	    krb5_warnx(context,
+		       N_("NOTICE: ticket renewable lifetime is %s", ""),
 		       life);
 	}
     }
=20
-    ret =3D krb5_cc_new_unique(context, krb5_cc_get_type(context, ccache),=20
+    ret =3D krb5_cc_new_unique(context, krb5_cc_get_type(context, ccache),
 			     NULL, &tempccache);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_new_unique");
@@ -586,7 +606,7 @@
     ret =3D krb5_cc_initialize (context, tempccache, cred.client);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_initialize");
-   =20
+
     ret =3D krb5_cc_store_cred (context, tempccache, &cred);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_store_cred");
@@ -597,8 +617,29 @@
     if (ret)
 	krb5_err (context, 1, ret, "krb5_cc_move");
=20
+    if (switch_cache_flags)
+	krb5_cc_switch(context, ccache);
+
+#ifndef NO_NTLM
     if (ntlm_domain && ntlmkey.data)
-	store_ntlmkey(context, ccache, ntlm_domain, principal, &ntlmkey);
+	store_ntlmkey(context, ccache, ntlm_domain, &ntlmkey);
+#endif
+
+    if (ok_as_delegate_flag || windows_flag || use_referrals_flag) {
+	unsigned char d =3D 0;
+	krb5_data data;
+
+	if (ok_as_delegate_flag || windows_flag)
+	    d |=3D 1;
+	if (use_referrals_flag || windows_flag)
+	    d |=3D 2;
+
+	data.length =3D 1;
+	data.data =3D &d;
+
+	krb5_cc_set_config(context, ccache, NULL, "realm-config", &data);
+    }
+
=20
     if (enctype)
 	free(enctype);
@@ -607,7 +648,7 @@
 }
=20
 static time_t
-ticket_lifetime(krb5_context context, krb5_ccache cache,=20
+ticket_lifetime(krb5_context context, krb5_ccache cache,
 		krb5_principal client, const char *server)
 {
     krb5_creds in_cred, *cred;
@@ -667,13 +708,13 @@
 	new_tickets =3D 1;
=20
     if (new_tickets)
-	get_new_tickets(ctx->context, ctx->principal,=20
+	get_new_tickets(ctx->context, ctx->principal,
 			ctx->ccache, ctx->ticket_life, 0);
=20
-    if(get_v4_tgt || convert_524)
-	do_524init(ctx->context, ctx->ccache, NULL, server_str);
+#ifndef NO_AFS
     if(do_afslog && k_hasafs())
 	krb5_afslog(ctx->context, ctx->ccache, NULL, NULL);
+#endif
=20
     expire =3D ticket_lifetime(ctx->context, ctx->ccache, ctx->principal,
 			     server_str) / 2;
@@ -692,16 +733,20 @@
     int parseflags =3D 0;
=20
     setprogname (argv[0]);
-   =20
+
+    setlocale (LC_ALL, "");
+    bindtextdomain ("heimdal_kuser", HEIMDAL_LOCALEDIR);
+    textdomain("heimdal_kuser");
+
     ret =3D krb5_init_context (&context);
     if (ret =3D=3D KRB5_CONFIG_BADFORMAT)
 	errx (1, "krb5_init_context failed to parse configuration file");
     else if (ret)
 	errx(1, "krb5_init_context failed: %d", ret);
- =20
+
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -713,17 +758,38 @@
     argc -=3D optidx;
     argv +=3D optidx;
=20
-    if (canonicalize_flag)
+    if (canonicalize_flag || enterprise_flag)
 	parseflags |=3D KRB5_PRINCIPAL_PARSE_ENTERPRISE;
=20
-    if (argv[0]) {
-	ret =3D krb5_parse_name_flags (context, argv[0], parseflags, &principal);
+    if (pk_enterprise_flag) {
+	ret =3D krb5_pk_enterprise_cert(context, pk_user_id,
+				      argv[0], &principal,
+				      &ent_user_id);
 	if (ret)
-	    krb5_err (context, 1, ret, "krb5_parse_name");
+	    krb5_err(context, 1, ret, "krb5_pk_enterprise_certs");
+
+	pk_user_id =3D NULL;
+
+    } else if (anonymous_flag) {
+
+	ret =3D krb5_make_principal(context, &principal, argv[0],
+				  KRB5_WELLKNOWN_NAME, KRB5_ANON_NAME,
+				  NULL);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_make_principal");
+	krb5_principal_set_type(context, principal, KRB5_NT_WELLKNOWN);
+
     } else {
-	ret =3D krb5_get_default_principal (context, &principal);
-	if (ret)
-	    krb5_err (context, 1, ret, "krb5_get_default_principal");
+	if (argv[0]) {
+	    ret =3D krb5_parse_name_flags (context, argv[0], parseflags,
+					 &principal);
+	    if (ret)
+		krb5_err (context, 1, ret, "krb5_parse_name");
+	} else {
+	    ret =3D krb5_get_default_principal (context, &principal);
+	    if (ret)
+		krb5_err (context, 1, ret, "krb5_get_default_principal");
+	}
     }
=20
     if(fcache_version)
@@ -734,68 +800,70 @@
 	krb5_appdefault_boolean(context, "kinit",
 				krb5_principal_get_realm(context, principal),
 				"renewable", FALSE, &renewable_flag);
-    if(get_v4_tgt =3D=3D -1)
-	krb5_appdefault_boolean(context, "kinit",=20
-				krb5_principal_get_realm(context, principal),=20
-				"krb4_get_tickets", FALSE, &get_v4_tgt);
     if(do_afslog =3D=3D -1)
-	krb5_appdefault_boolean(context, "kinit",=20
-				krb5_principal_get_realm(context, principal),=20
+	krb5_appdefault_boolean(context, "kinit",
+				krb5_principal_get_realm(context, principal),
 				"afslog", TRUE, &do_afslog);
=20
-    if(cred_cache)=20
+    if(cred_cache)
 	ret =3D krb5_cc_resolve(context, cred_cache, &ccache);
     else {
 	if(argc > 1) {
 	    char s[1024];
-	    ret =3D krb5_cc_gen_new(context, &krb5_fcc_ops, &ccache);
+	    ret =3D krb5_cc_new_unique(context, NULL, NULL, &ccache);
 	    if(ret)
 		krb5_err(context, 1, ret, "creating cred cache");
 	    snprintf(s, sizeof(s), "%s:%s",
 		     krb5_cc_get_type(context, ccache),
 		     krb5_cc_get_name(context, ccache));
 	    setenv("KRB5CCNAME", s, 1);
-	    if (get_v4_tgt) {
-		int fd;
-		if (asprintf(&krb4_cc_name, "%s_XXXXXX", TKT_ROOT) < 0)
-		    krb5_errx(context, 1, "out of memory");
-		if((fd =3D mkstemp(krb4_cc_name)) >=3D 0) {
-		    close(fd);
-		    setenv("KRBTKFILE", krb4_cc_name, 1);
-		} else {
-		    free(krb4_cc_name);
-		    krb4_cc_name =3D NULL;
+	} else {
+	    ret =3D krb5_cc_cache_match(context, principal, &ccache);
+	    if (ret) {
+		const char *type;
+		ret =3D krb5_cc_default (context, &ccache);
+		if (ret)
+		    krb5_err (context, 1, ret, N_("resolving credentials cache", ""));
+
+		/*
+		 * Check if the type support switching, and we do,
+		 * then do that instead over overwriting the current
+		 * default credential
+		 */
+		type =3D krb5_cc_get_type(context, ccache);
+		if (krb5_cc_support_switch(context, type)) {
+		    krb5_cc_close(context, ccache);
+		    ret =3D krb5_cc_new_unique(context, type, NULL, &ccache);
 		}
 	    }
-	} else {
-	    ret =3D krb5_cc_cache_match(context, principal, NULL, &ccache);
-	    if (ret)
-		ret =3D krb5_cc_default (context, &ccache);
 	}
     }
     if (ret)
-	krb5_err (context, 1, ret, "resolving credentials cache");
+	krb5_err (context, 1, ret, N_("resolving credentials cache", ""));
=20
+#ifndef NO_AFS
     if(argc > 1 && k_hasafs ())
 	k_setpag();
+#endif
=20
     if (lifetime) {
 	int tmp =3D parse_time (lifetime, "s");
 	if (tmp < 0)
-	    errx (1, "unparsable time: %s", lifetime);
+	    errx (1, N_("unparsable time: %s", ""), lifetime);
=20
 	ticket_life =3D tmp;
     }
=20
     if(addrs_flag =3D=3D 0 && extra_addresses.num_strings > 0)
-	krb5_errx(context, 1, "specifying both extra addresses and "
-		  "no addresses makes no sense");
+	krb5_errx(context, 1,
+		  N_("specifying both extra addresses and "
+		     "no addresses makes no sense", ""));
     {
 	int i;
 	krb5_addresses addresses;
 	memset(&addresses, 0, sizeof(addresses));
 	for(i =3D 0; i < extra_addresses.num_strings; i++) {
-	    ret =3D krb5_parse_address(context, extra_addresses.strings[i],=20
+	    ret =3D krb5_parse_address(context, extra_addresses.strings[i],
 				     &addresses);
 	    if (ret =3D=3D 0) {
 		krb5_add_extra_addresses(context, &addresses);
@@ -806,18 +874,17 @@
     }
=20
     if(renew_flag || validate_flag) {
-	ret =3D renew_validate(context, renew_flag, validate_flag,=20
+	ret =3D renew_validate(context, renew_flag, validate_flag,
 			     ccache, server_str, ticket_life);
 	exit(ret !=3D 0);
     }
=20
-    if(!convert_524)
-	get_new_tickets(context, principal, ccache, ticket_life, 1);
+    get_new_tickets(context, principal, ccache, ticket_life, 1);
=20
-    if(get_v4_tgt || convert_524)
-	do_524init(context, ccache, NULL, server_str);
+#ifndef NO_AFS
     if(do_afslog && k_hasafs())
 	krb5_afslog(context, ccache, NULL, NULL);
+#endif
     if(argc > 1) {
 	struct renew_ctx ctx;
 	time_t timeout;
@@ -829,19 +896,20 @@
 	ctx.principal =3D principal;
 	ctx.ticket_life =3D ticket_life;
=20
-	ret =3D simple_execvp_timed(argv[1], argv+1,=20
+	ret =3D simple_execvp_timed(argv[1], argv+1,
 				  renew_func, &ctx, timeout);
 #define EX_NOEXEC	126
 #define EX_NOTFOUND	127
 	if(ret =3D=3D EX_NOEXEC)
-	    krb5_warnx(context, "permission denied: %s", argv[1]);
+	    krb5_warnx(context, N_("permission denied: %s", ""), argv[1]);
 	else if(ret =3D=3D EX_NOTFOUND)
-	    krb5_warnx(context, "command not found: %s", argv[1]);
-=09
+	    krb5_warnx(context, N_("command not found: %s", ""), argv[1]);
+
 	krb5_cc_destroy(context, ccache);
-	_krb5_krb_dest_tkt(context, krb4_cc_name);
+#ifndef NO_AFS
 	if(k_hasafs())
 	    k_unlog();
+#endif
     } else {
 	krb5_cc_close (context, ccache);
 	ret =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/klist.1
--- a/head/crypto/heimdal/kuser/klist.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/klist.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2000 - 2005 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2000 - 2005 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: klist.1 20458 2007-04-19 20:41:27Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd October  6, 2005
 .Dt KLIST 1
@@ -41,17 +41,17 @@
 .Nm
 .Bk -words
 .Oo Fl c Ar cache \*(Ba Xo
-.Fl -cache=3D Ns Ar cache
+.Fl Fl cache=3D Ns Ar cache
 .Xc
 .Oc
-.Op Fl s | Fl t | Fl -test
-.Op Fl T | Fl -tokens
-.Op Fl 5 | Fl -v5
-.Op Fl v | Fl -verbose
-.Op Fl l | Fl -list-caches
+.Op Fl s | Fl t | Fl Fl test
+.Op Fl T | Fl Fl tokens
+.Op Fl 5 | Fl Fl v5
+.Op Fl v | Fl Fl verbose
+.Op Fl l | Fl Fl list-caches
 .Op Fl f
-.Op Fl -version
-.Op Fl -help
+.Op Fl Fl version
+.Op Fl Fl help
 .Ek
 .Sh DESCRIPTION
 .Nm
@@ -60,27 +60,14 @@
 .Pp
 Options supported:
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar cache ,
-.Fl -cache=3D Ns Ar cache
-.Xc
+.It Fl c Ar cache , Fl Fl cache=3D Ns Ar cache
 credential cache to list
-.It Xo
-.Fl s ,
-.Fl t ,
-.Fl -test
-.Xc
+.It Fl s , Fl t , Fl Fl test
 Test for there being an active and valid TGT for the local realm of
 the user in the credential cache.
-.It Xo
-.Fl T ,
-.Fl -tokens
-.Xc
+.It Fl T , Fl Fl tokens
 display AFS tokens
-.It Xo
-.Fl 5 ,
-.Fl -v5
-.Xc
+.It Fl 5 , Fl Fl v5
 display v5 cred cache (this is the default)
 .It Fl f
 Include ticket flags in short form, each character stands for a
@@ -111,12 +98,9 @@
 .El
 .Pp
 This information is also output with the
-.Fl -verbose
+.Fl Fl verbose
 option, but in a more verbose way.
-.It Xo
-.Fl v ,
-.Fl -verbose
-.Xc
+.It Fl v , Fl Fl verbose
 Verbose output. Include all possible information:
 .Bl -tag -width XXXX -offset indent
 .It Server
@@ -141,10 +125,7 @@
 .It Addresses
 the set of addresses from which this ticket is valid
 .El
-.It Xo
-.Fl l ,
-.Fl -list-caches
-.Xc
+.It Fl l , Fl Fl list-caches
 List the credential caches for the current users, not all cache types
 supports listing multiple caches.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/klist.c
--- a/head/crypto/heimdal/kuser/klist.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/klist.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,65 +1,77 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kuser_locl.h"
 #include "rtbl.h"
+#include "parse_units.h"
+#include "kcc-commands.h"
=20
-RCSID("$Id: klist.c 20516 2007-04-22 10:40:41Z lha $");
+static char*
+printable_time_internal(time_t t, int x)
+{
+    static char s[128];
+    char *p;
+
+    if ((p =3D ctime(&t)) =3D=3D NULL)
+	strlcpy(s, "?", sizeof(s));
+    else
+	strlcpy(s, p + 4, sizeof(s));
+    s[x] =3D 0;
+    return s;
+}
=20
 static char*
 printable_time(time_t t)
 {
-    static char s[128];
-    strlcpy(s, ctime(&t)+ 4, sizeof(s));
-    s[15] =3D 0;
-    return s;
+    return printable_time_internal(t, 20);
 }
=20
 static char*
 printable_time_long(time_t t)
 {
-    static char s[128];
-    strlcpy(s, ctime(&t)+ 4, sizeof(s));
-    s[20] =3D 0;
-    return s;
+    return printable_time_internal(t, 20);
 }
=20
-#define COL_ISSUED		"  Issued"
-#define COL_EXPIRES		"  Expires"
-#define COL_FLAGS		"Flags"
-#define COL_PRINCIPAL		"  Principal"
-#define COL_PRINCIPAL_KVNO	"  Principal (kvno)"
-#define COL_CACHENAME		"  Cache name"
+#define COL_ISSUED		NP_("  Issued","")
+#define COL_EXPIRES		NP_("  Expires", "")
+#define COL_FLAGS		NP_("Flags", "")
+#define COL_NAME		NP_("  Name", "")
+#define COL_PRINCIPAL		NP_("  Principal", "in klist output")
+#define COL_PRINCIPAL_KVNO	NP_("  Principal (kvno)", "in klist output")
+#define COL_CACHENAME		NP_("  Cache name", "name in klist output")
+#define COL_DEFCACHE		NP_("", "")
=20
 static void
 print_cred(krb5_context context, krb5_creds *cred, rtbl_t ct, int do_flags)
@@ -77,12 +89,12 @@
     else
 	rtbl_add_column_entry(ct, COL_ISSUED,
 			      printable_time(cred->times.authtime));
-   =20
+
     if(cred->times.endtime > sec)
 	rtbl_add_column_entry(ct, COL_EXPIRES,
 			      printable_time(cred->times.endtime));
     else
-	rtbl_add_column_entry(ct, COL_EXPIRES, ">>>Expired<<<");
+	rtbl_add_column_entry(ct, COL_EXPIRES, N_(">>>Expired<<<", ""));
     ret =3D krb5_unparse_name (context, cred->server, &str);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_unparse_name");
@@ -111,7 +123,7 @@
 	    *sp++ =3D 'A';
 	if(cred->flags.b.hw_authent)
 	    *sp++ =3D 'H';
-	*sp++ =3D '\0';
+	*sp =3D '\0';
 	rtbl_add_column_entry(ct, COL_FLAGS, s);
     }
     free(str);
@@ -120,10 +132,9 @@
 static void
 print_cred_verbose(krb5_context context, krb5_creds *cred)
 {
-    int j;
+    size_t j;
     char *str;
     krb5_error_code ret;
-    int first_flag;
     krb5_timestamp sec;
=20
     krb5_timeofday (context, &sec);
@@ -131,13 +142,13 @@
     ret =3D krb5_unparse_name(context, cred->server, &str);
     if(ret)
 	exit(1);
-    printf("Server: %s\n", str);
+    printf(N_("Server: %s\n", ""), str);
     free (str);
=20
     ret =3D krb5_unparse_name(context, cred->client, &str);
     if(ret)
 	exit(1);
-    printf("Client: %s\n", str);
+    printf(N_("Client: %s\n", ""), str);
     free (str);
=20
     {
@@ -147,71 +158,63 @@
=20
 	decode_Ticket(cred->ticket.data, cred->ticket.length, &t, &len);
 	ret =3D krb5_enctype_to_string(context, t.enc_part.etype, &s);
-	printf("Ticket etype: ");
+	printf(N_("Ticket etype: ", ""));
 	if (ret =3D=3D 0) {
 	    printf("%s", s);
 	    free(s);
 	} else {
-	    printf("unknown(%d)", t.enc_part.etype);
+	    printf(N_("unknown-enctype(%d)", ""), t.enc_part.etype);
 	}
 	if(t.enc_part.kvno)
-	    printf(", kvno %d", *t.enc_part.kvno);
+	    printf(N_(", kvno %d", ""), *t.enc_part.kvno);
 	printf("\n");
 	if(cred->session.keytype !=3D t.enc_part.etype) {
 	    ret =3D krb5_enctype_to_string(context, cred->session.keytype, &str);
 	    if(ret)
 		krb5_warn(context, ret, "session keytype");
 	    else {
-		printf("Session key: %s\n", str);
+		printf(N_("Session key: %s\n", "enctype"), str);
 		free(str);
 	    }
 	}
 	free_Ticket(&t);
-	printf("Ticket length: %lu\n", (unsigned long)cred->ticket.length);
+	printf(N_("Ticket length: %lu\n", ""),
+	       (unsigned long)cred->ticket.length);
     }
-    printf("Auth time:  %s\n", printable_time_long(cred->times.authtime));
+    printf(N_("Auth time:  %s\n", ""),
+	   printable_time_long(cred->times.authtime));
     if(cred->times.authtime !=3D cred->times.starttime)
-	printf("Start time: %s\n", printable_time_long(cred->times.starttime));
-    printf("End time:   %s", printable_time_long(cred->times.endtime));
+	printf(N_("Start time: %s\n", ""),
+	       printable_time_long(cred->times.starttime));
+    printf(N_("End time:   %s", ""),
+	   printable_time_long(cred->times.endtime));
     if(sec > cred->times.endtime)
-	printf(" (expired)");
+	printf(N_(" (expired)", ""));
     printf("\n");
     if(cred->flags.b.renewable)
-	printf("Renew till: %s\n",=20
+	printf(N_("Renew till: %s\n", ""),
 	       printable_time_long(cred->times.renew_till));
-    printf("Ticket flags: ");
-#define PRINT_FLAG2(f, s) if(cred->flags.b.f) { if(!first_flag) printf(", =
"); printf("%s", #s); first_flag =3D 0; }
-#define PRINT_FLAG(f) PRINT_FLAG2(f, f)
-    first_flag =3D 1;
-    PRINT_FLAG(forwardable);
-    PRINT_FLAG(forwarded);
-    PRINT_FLAG(proxiable);
-    PRINT_FLAG(proxy);
-    PRINT_FLAG2(may_postdate, may-postdate);
-    PRINT_FLAG(postdated);
-    PRINT_FLAG(invalid);
-    PRINT_FLAG(renewable);
-    PRINT_FLAG(initial);
-    PRINT_FLAG2(pre_authent, pre-authenticated);
-    PRINT_FLAG2(hw_authent, hw-authenticated);
-    PRINT_FLAG2(transited_policy_checked, transited-policy-checked);
-    PRINT_FLAG2(ok_as_delegate, ok-as-delegate);
-    PRINT_FLAG(anonymous);
-    printf("\n");
-    printf("Addresses: ");
+    {
+	char flags[1024];
+	unparse_flags(TicketFlags2int(cred->flags.b),
+		      asn1_TicketFlags_units(),
+		      flags, sizeof(flags));
+	printf(N_("Ticket flags: %s\n", ""), flags);
+    }
+    printf(N_("Addresses: ", ""));
     if (cred->addresses.len !=3D 0) {
 	for(j =3D 0; j < cred->addresses.len; j++){
 	    char buf[128];
 	    size_t len;
 	    if(j) printf(", ");
-	    ret =3D krb5_print_address(&cred->addresses.val[j],=20
+	    ret =3D krb5_print_address(&cred->addresses.val[j],
 				     buf, sizeof(buf), &len);
-	   =20
+
 	    if(ret =3D=3D 0)
 		printf("%s", buf);
 	}
     } else {
-	printf("addressless");
+	printf(N_("addressless", ""));
     }
     printf("\n\n");
 }
@@ -229,10 +232,10 @@
 	       int do_hidden)
 {
     krb5_error_code ret;
-    char *str;
+    char *str, *name;
     krb5_cc_cursor cursor;
     krb5_creds creds;
-    int32_t sec, usec;
+    krb5_deltat sec;
=20
     rtbl_t ct =3D NULL;
=20
@@ -240,20 +243,30 @@
     if (ret)
 	krb5_err (context, 1, ret, "krb5_unparse_name");
=20
-    printf ("%17s: %s:%s\n",=20
-	    "Credentials cache",
+    printf ("%17s: %s:%s\n",
+	    N_("Credentials cache", ""),
 	    krb5_cc_get_type(context, ccache),
 	    krb5_cc_get_name(context, ccache));
-    printf ("%17s: %s\n", "Principal", str);
+    printf ("%17s: %s\n", N_("Principal", ""), str);
+
+    ret =3D krb5_cc_get_friendly_name(context, ccache, &name);
+    if (ret =3D=3D 0) {
+	if (strcmp(name, str) !=3D 0)
+	    printf ("%17s: %s\n", N_("Friendly name", ""), name);
+	free(name);
+    }
     free (str);
-   =20
-    if(do_verbose)
-	printf ("%17s: %d\n", "Cache version",
+
+    if(do_verbose) {
+	printf ("%17s: %d\n", N_("Cache version", ""),
 		krb5_cc_get_version(context, ccache));
-   =20
-    krb5_get_kdc_sec_offset(context, &sec, &usec);
+    } else {
+        krb5_cc_set_flags(context, ccache, KRB5_TC_NOTICKET);
+    }
=20
-    if (do_verbose && sec !=3D 0) {
+    ret =3D krb5_cc_get_kdc_offset(context, ccache, &sec);
+
+    if (ret =3D=3D 0 && do_verbose && sec !=3D 0) {
 	char buf[BUFSIZ];
 	int val;
 	int sig;
@@ -264,10 +277,10 @@
 	    sig =3D -1;
 	    val =3D -val;
 	}
-=09
+
 	unparse_time (val, buf, sizeof(buf));
=20
-	printf ("%17s: %s%s\n", "KDC time offset",
+	printf ("%17s: %s%s\n", N_("KDC time offset", ""),
 		sig =3D=3D -1 ? "-" : "", buf);
     }
=20
@@ -290,9 +303,7 @@
 				     ccache,
 				     &cursor,
 				     &creds)) =3D=3D 0) {
-	const char *str;
-	str =3D krb5_principal_get_comp_string(context, creds.server, 0);
-	if (!do_hidden && str && str[0] =3D=3D '@') {
+	if (!do_hidden && krb5_is_config_principal(context, creds.server)) {
 	    ;
 	}else if(do_verbose){
 	    print_cred_verbose(context, &creds);
@@ -326,16 +337,15 @@
     krb5_error_code ret;
     krb5_creds pattern;
     krb5_creds creds;
-    krb5_realm *client_realm;
+    krb5_const_realm client_realm;
     int expired;
=20
     krb5_cc_clear_mcred(&pattern);
=20
-    client_realm =3D krb5_princ_realm (context, principal);
+    client_realm =3D krb5_principal_get_realm(context, principal);
=20
     ret =3D krb5_make_principal (context, &pattern.server,
-			       *client_realm, KRB5_TGS_NAME, *client_realm,
-			       NULL);
+			       client_realm, KRB5_TGS_NAME, client_realm, NULL);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_make_principal");
     pattern.client =3D principal;
@@ -362,6 +372,8 @@
  * Print a list of all AFS tokens
  */
=20
+#ifndef NO_AFS
+
 static void
 display_tokens(int do_verbose)
 {
@@ -414,53 +426,40 @@
 	    strlcpy (buf2, printable_time(ct.EndTimestamp),
 		     sizeof(buf2));
 	else
-	    strlcpy (buf2, ">>> Expired <<<", sizeof(buf2));
+	    strlcpy (buf2, N_(">>> Expired <<<", ""), sizeof(buf2));
=20
 	printf("%s  %s  ", buf1, buf2);
=20
 	if ((ct.EndTimestamp - ct.BeginTimestamp) & 1)
-	    printf("User's (AFS ID %d) tokens for %s", ct.ViceId, cell);
+	    printf(N_("User's (AFS ID %d) tokens for %s", ""), ct.ViceId, cell);
 	else
-	    printf("Tokens for %s", cell);
+	    printf(N_("Tokens for %s", ""), cell);
 	if (do_verbose)
 	    printf(" (%d)", ct.AuthHandle);
 	putchar('\n');
     }
 }
+#endif
=20
 /*
  * display the ccache in `cred_cache'
  */
=20
 static int
-display_v5_ccache (const char *cred_cache, int do_test, int do_verbose,=20
+display_v5_ccache (krb5_context context, krb5_ccache ccache,
+		   int do_test, int do_verbose,
 		   int do_flags, int do_hidden)
 {
     krb5_error_code ret;
-    krb5_context context;
-    krb5_ccache ccache;
     krb5_principal principal;
     int exit_status =3D 0;
=20
-    ret =3D krb5_init_context (&context);
-    if (ret)
-	errx (1, "krb5_init_context failed: %d", ret);
-
-    if(cred_cache) {
-	ret =3D krb5_cc_resolve(context, cred_cache, &ccache);
-	if (ret)
-	    krb5_err (context, 1, ret, "%s", cred_cache);
-    } else {
-	ret =3D krb5_cc_default (context, &ccache);
-	if (ret)
-	    krb5_err (context, 1, ret, "krb5_cc_resolve");
-    }
=20
     ret =3D krb5_cc_get_principal (context, ccache, &principal);
     if (ret) {
 	if(ret =3D=3D ENOENT) {
 	    if (!do_test)
-		krb5_warnx(context, "No ticket file: %s",
+		krb5_warnx(context, N_("No ticket file: %s", ""),
 			   krb5_cc_get_name(context, ccache));
 	    return 1;
 	} else
@@ -477,7 +476,7 @@
 	krb5_err (context, 1, ret, "krb5_cc_close");
=20
     krb5_free_principal (context, principal);
-    krb5_free_context (context);
+
     return exit_status;
 }
=20
@@ -486,17 +485,19 @@
  */
=20
 static int
-list_caches(void)
+list_caches(krb5_context context)
 {
     krb5_cc_cache_cursor cursor;
-    krb5_context context;
+    const char *cdef_name;
+    char *def_name;
     krb5_error_code ret;
     krb5_ccache id;
     rtbl_t ct;
-   =20
-    ret =3D krb5_init_context (&context);
-    if (ret)
-	errx (1, "krb5_init_context failed: %d", ret);
+
+    cdef_name =3D krb5_cc_default_name(context);
+    if (cdef_name =3D=3D NULL)
+	krb5_errx(context, 1, "krb5_cc_default_name");
+    def_name =3D strdup(cdef_name);
=20
     ret =3D krb5_cc_cache_get_first (context, NULL, &cursor);
     if (ret =3D=3D KRB5_CC_NOSUPP)
@@ -505,41 +506,61 @@
 	krb5_err (context, 1, ret, "krb5_cc_cache_get_first");
=20
     ct =3D rtbl_create();
-    rtbl_add_column(ct, COL_PRINCIPAL, 0);
+    rtbl_add_column(ct, COL_NAME, 0);
     rtbl_add_column(ct, COL_CACHENAME, 0);
     rtbl_add_column(ct, COL_EXPIRES, 0);
+    rtbl_add_column(ct, COL_DEFCACHE, 0);
     rtbl_set_prefix(ct, "   ");
-    rtbl_set_column_prefix(ct, COL_PRINCIPAL, "");
+    rtbl_set_column_prefix(ct, COL_NAME, "");
=20
-    while ((ret =3D krb5_cc_cache_next (context, cursor, &id)) =3D=3D 0) {
-	krb5_principal principal;
+    while (krb5_cc_cache_next (context, cursor, &id) =3D=3D 0) {
+	krb5_principal principal =3D NULL;
+	int expired =3D 0;
 	char *name;
+	time_t t;
=20
 	ret =3D krb5_cc_get_principal(context, id, &principal);
+	if (ret)
+	    continue;
+
+	expired =3D check_for_tgt (context, id, principal, &t);
+
+	ret =3D krb5_cc_get_friendly_name(context, id, &name);
 	if (ret =3D=3D 0) {
-	    time_t t;
-	    int expired =3D check_for_tgt (context, id, principal, &t);
+	    const char *str;
+	    char *fname;
+	    rtbl_add_column_entry(ct, COL_NAME, name);
+	    rtbl_add_column_entry(ct, COL_CACHENAME,
+				  krb5_cc_get_name(context, id));
+	    if (expired)
+		str =3D N_(">>> Expired <<<", "");
+	    else
+		str =3D printable_time(t);
+	    rtbl_add_column_entry(ct, COL_EXPIRES, str);
+	    free(name);
=20
-	    ret =3D krb5_unparse_name(context, principal, &name);
-	    if (ret =3D=3D 0) {
-		rtbl_add_column_entry(ct, COL_PRINCIPAL, name);
-		rtbl_add_column_entry(ct, COL_CACHENAME,
-				      krb5_cc_get_name(context, id));
-		rtbl_add_column_entry(ct, COL_EXPIRES,
-				      expired ? ">>> Expired <<<" :=20
-				      printable_time(t));
-		free(name);
-		krb5_free_principal(context, principal);
-	    }
+	    ret =3D krb5_cc_get_full_name(context, id, &fname);
+	    if (ret)
+		krb5_err (context, 1, ret, "krb5_cc_get_full_name");
+
+	    if (strcmp(fname, def_name) =3D=3D 0)
+		rtbl_add_column_entry(ct, COL_DEFCACHE, "*");
+	    else
+		rtbl_add_column_entry(ct, COL_DEFCACHE, "");
+
+	    krb5_xfree(fname);
 	}
 	krb5_cc_close(context, id);
+
+	krb5_free_principal(context, principal);
     }
=20
     krb5_cc_cache_end_seq_get(context, cursor);
=20
+    free(def_name);
     rtbl_format(ct, stdout);
     rtbl_destroy(ct);
-   =20
+
     return 0;
 }
=20
@@ -547,92 +568,68 @@
  *
  */
=20
-static int version_flag		=3D 0;
-static int help_flag		=3D 0;
-static int do_verbose		=3D 0;
-static int do_list_caches	=3D 0;
-static int do_test		=3D 0;
-static int do_tokens		=3D 0;
-static int do_v5		=3D 1;
-static char *cred_cache;
-static int do_flags	 	=3D 0;
-static int do_hidden	 	=3D 0;
-
-static struct getargs args[] =3D {
-    { NULL, 'f', arg_flag, &do_flags },
-    { "cache",			'c', arg_string, &cred_cache,
-      "credentials cache to list", "cache" },
-    { "test",			't', arg_flag, &do_test,
-      "test for having tickets", NULL },
-    { NULL,			's', arg_flag, &do_test },
-    { "tokens",			'T',   arg_flag, &do_tokens,
-      "display AFS tokens", NULL },
-    { "v5",			'5',	arg_flag, &do_v5,
-      "display v5 cred cache", NULL},
-    { "list-caches",		'l', arg_flag, &do_list_caches,
-      "verbose output", NULL },
-    { "verbose",		'v', arg_flag, &do_verbose,
-      "verbose output", NULL },
-    { "hidden",			0,   arg_flag, &do_hidden,
-      "display hidden credentials", NULL },
-    { NULL,			'a', arg_flag, &do_verbose },
-    { NULL,			'n', arg_flag, &do_verbose },
-    { "version", 		0,   arg_flag, &version_flag,=20
-      "print version", NULL },
-    { "help",			0,   arg_flag, &help_flag,=20
-      NULL, NULL}
-};
-
-static void
-usage (int ret)
+int
+klist(struct klist_options *opt, int argc, char **argv)
 {
-    arg_printusage (args,
-		    sizeof(args)/sizeof(*args),
-		    NULL,
-		    "");
-    exit (ret);
-}
-
-int
-main (int argc, char **argv)
-{
-    int optidx =3D 0;
+    krb5_error_code ret;
     int exit_status =3D 0;
=20
-    setprogname (argv[0]);
+    int do_verbose =3D
+	opt->verbose_flag ||
+	opt->a_flag ||
+	opt->n_flag;
+    int do_test =3D
+	opt->test_flag ||
+	opt->s_flag;
=20
-    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
-	usage(1);
-   =20
-    if (help_flag)
-	usage (0);
-
-    if(version_flag){
-	print_version(NULL);
-	exit(0);
-    }
-
-    argc -=3D optidx;
-    argv +=3D optidx;
-
-    if (argc !=3D 0)
-	usage (1);
-
-    if (do_list_caches) {
-	exit_status =3D list_caches();
+    if (opt->list_all_flag) {
+	exit_status =3D list_caches(kcc_context);
 	return exit_status;
     }
=20
-    if (do_v5)
-	exit_status =3D display_v5_ccache (cred_cache, do_test,=20
-					 do_verbose, do_flags, do_hidden);
+    if (opt->v5_flag) {
+	krb5_ccache id;
+
+	if (opt->all_content_flag) {
+	    krb5_cc_cache_cursor cursor;
+
+	    ret =3D krb5_cc_cache_get_first(kcc_context, NULL, &cursor);
+	    if (ret)
+		krb5_err(kcc_context, 1, ret, "krb5_cc_cache_get_first");
+
+
+	    while (krb5_cc_cache_next(kcc_context, cursor, &id) =3D=3D 0) {
+		exit_status |=3D display_v5_ccache(kcc_context, id, do_test,
+						 do_verbose, opt->flags_flag,
+						 opt->hidden_flag);
+		printf("\n\n");
+	    }
+	    krb5_cc_cache_end_seq_get(kcc_context, cursor);
+
+	} else {
+	    if(opt->cache_string) {
+		ret =3D krb5_cc_resolve(kcc_context, opt->cache_string, &id);
+		if (ret)
+		    krb5_err(kcc_context, 1, ret, "%s", opt->cache_string);
+	    } else {
+		ret =3D krb5_cc_default(kcc_context, &id);
+		if (ret)
+		    krb5_err(kcc_context, 1, ret, "krb5_cc_resolve");
+	    }
+	    exit_status =3D display_v5_ccache(kcc_context, id, do_test,
+					    do_verbose, opt->flags_flag,
+					    opt->hidden_flag);
+	}
+    }
=20
     if (!do_test) {
-	if (do_tokens && k_hasafs ()) {
-	    if (do_v5)
-		printf ("\n");
-	    display_tokens (do_verbose);
+#ifndef NO_AFS
+	if (opt->tokens_flag && k_hasafs()) {
+	    if (opt->v5_flag)
+		printf("\n");
+	    display_tokens(opt->verbose_flag);
 	}
+#endif
     }
=20
     return exit_status;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kuser_locl.h
--- a/head/crypto/heimdal/kuser/kuser_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kuser_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,42 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: kuser_locl.h 20458 2007-04-19 20:41:27Z lha $ */
+/* $Id$ */
=20
 #ifndef __KUSER_LOCL_H__
 #define __KUSER_LOCL_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -81,7 +79,30 @@
 #ifdef HAVE_SYS_IOCCOM_H
 #include <sys/ioccom.h>
 #endif
+#ifndef NO_AFS
 #include <kafs.h>
-#include "crypto-headers.h" /* for des_read_pw_string */
+#endif
+#include "crypto-headers.h" /* for UI_UTIL_read_pw_string */
+
+#include <rtbl.h>
+
+#ifdef HAVE_LOCALE_H
+#include <locale.h>
+#endif
+
+#ifdef LIBINTL
+#include <libintl.h>
+#define N_(x,y) gettext(x)
+#define NP_(x,y) (x)
+#define getarg_i18n gettext
+#else
+#define N_(x,y) (x)
+#define NP_(x,y) (x)
+#define getarg_i18n NULL
+#define bindtextdomain(package, localedir)
+#define textdomain(package)
+#endif
+
+extern krb5_context kcc_context;
=20
 #endif /* __KUSER_LOCL_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/kuser/kverify.c
--- a/head/crypto/heimdal/kuser/kverify.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/kuser/kverify.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2005, 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005, 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kuser_locl.h"
=20
-RCSID("$Id: kverify.c 19920 2007-01-15 23:21:32Z lha $");
-
 static int help_flag =3D 0;
 static int version_flag =3D 0;
=20
@@ -69,7 +67,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -77,7 +75,7 @@
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     argc -=3D optidx;
     argv +=3D optidx;
=20
@@ -94,11 +92,16 @@
 					      1);
=20
     krb5_verify_init_creds_opt_init (&verify_options);
-   =20
+
     if (argc) {
 	ret =3D krb5_parse_name(context, argv[0], &principal);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_parse_name: %s", argv[0]);
+    } else {
+	ret =3D krb5_get_default_principal(context, &principal);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_get_default_principal");
+
     }
=20
     ret =3D krb5_get_init_creds_password (context,
@@ -111,7 +114,7 @@
 					NULL,
 					get_options);
     if (ret)
-	errx (1, "krb5_get_init_creds: %s", krb5_get_err_text(context, ret));
+	krb5_err(context, 1, ret,  "krb5_get_init_creds");
=20
     ret =3D krb5_verify_init_creds (context,
 				  &cred,
@@ -120,8 +123,7 @@
 				  NULL,
 				  &verify_options);
     if (ret)
-	errx (1, "krb5_verify_init_creds: %s",
-	      krb5_get_err_text(context, ret));
+	krb5_err(context, 1, ret, "krb5_verify_init_creds");
     krb5_free_cred_contents (context, &cred);
     krb5_free_context (context);
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/Makefile.am
--- a/head/crypto/heimdal/lib/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,9 @@
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-if KRB4
-dir_45 =3D 45
+if LIBEDIT
+dir_editline =3D libedit
 endif
 if OTP
 dir_otp =3D otp
@@ -17,6 +17,29 @@
 if !HAVE_OPENSSL
 dir_hcrypto =3D hcrypto
 endif
+if !SQLITE3
+dir_sqlite =3D sqlite
+endif
=20
-SUBDIRS =3D roken vers editline $(dir_com_err) sl asn1 $(dir_hcrypto) hx50=
9 \
-	krb5 ntlm kafs gssapi hdb kadm5 auth $(dir_45) $(dir_otp) $(dir_dce)
+SUBDIRS =3D \
+	roken \
+	vers \
+	$(dir_editline) \
+	$(dir_com_err) \
+	sl \
+	wind \
+	asn1 \
+	$(dir_sqlite) \
+	$(dir_hcrypto) \
+	ipc \
+	hx509 \
+	krb5 \
+	ntlm \
+	kafs \
+	gssapi \
+	hdb \
+	kadm5 \
+	$(dir_otp) \
+	$(dir_dce)
+
+EXTRA_DIST =3D NTMakefile heimdal
\ No newline at end of file
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/Makefile.in
--- a/head/crypto/heimdal/lib/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,15 +15,16 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 20466 2007-04-20 08:29:05Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,7 +45,7 @@
 subdir =3D lib
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -58,7 +60,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -72,9 +74,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -82,14 +87,13 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-depcomp =3D
-am__depfiles_maybe =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 SOURCES =3D
 DIST_SOURCES =3D
 RECURSIVE_TARGETS =3D all-recursive check-recursive dvi-recursive \
@@ -101,58 +105,95 @@
 	ps-recursive uninstall-recursive
 RECURSIVE_CLEAN_TARGETS =3D mostlyclean-recursive clean-recursive	\
   distclean-recursive maintainer-clean-recursive
+AM_RECURSIVE_TARGETS =3D $(RECURSIVE_TARGETS:-recursive=3D) \
+	$(RECURSIVE_CLEAN_TARGETS:-recursive=3D) tags TAGS ctags CTAGS \
+	distdir
 ETAGS =3D etags
 CTAGS =3D ctags
-DIST_SUBDIRS =3D roken vers editline com_err sl asn1 hcrypto hx509 krb5 \
-	ntlm kafs gssapi hdb kadm5 auth 45 otp kdfs
+DIST_SUBDIRS =3D roken vers libedit com_err sl wind asn1 sqlite hcrypto \
+	ipc hx509 krb5 ntlm kafs gssapi hdb kadm5 otp kdfs
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
+am__relativize =3D \
+  dir0=3D`pwd`; \
+  sed_first=3D's,^\([^/]*\)/.*$$,\1,'; \
+  sed_rest=3D's,^[^/]*/*,,'; \
+  sed_last=3D's,^.*/\([^/]*\)$$,\1,'; \
+  sed_butlast=3D's,/*[^/]*$$,,'; \
+  while test -n "$$dir1"; do \
+    first=3D`echo "$$dir1" | sed -e "$$sed_first"`; \
+    if test "$$first" !=3D "."; then \
+      if test "$$first" =3D ".."; then \
+        dir2=3D`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
+        dir0=3D`echo "$$dir0" | sed -e "$$sed_butlast"`; \
+      else \
+        first2=3D`echo "$$dir2" | sed -e "$$sed_first"`; \
+        if test "$$first2" =3D "$$first"; then \
+          dir2=3D`echo "$$dir2" | sed -e "$$sed_rest"`; \
+        else \
+          dir2=3D"../$$dir2"; \
+        fi; \
+        dir0=3D"$$dir0"/"$$first"; \
+      fi; \
+    fi; \
+    dir1=3D`echo "$$dir1" | sed -e "$$sed_rest"`; \
+  done; \
+  reldir=3D"$$dir2"
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -176,10 +217,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -196,6 +238,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -211,31 +255,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -250,10 +308,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -294,54 +354,79 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
- at KRB4_TRUE@dir_45 =3D 45
+ at LIBEDIT_TRUE@dir_editline =3D libedit
 @OTP_TRUE at dir_otp =3D otp
 @DCE_TRUE at dir_dce =3D kdfs
 @COM_ERR_TRUE at dir_com_err =3D com_err
 @HAVE_OPENSSL_FALSE at dir_hcrypto =3D hcrypto
-SUBDIRS =3D roken vers editline $(dir_com_err) sl asn1 $(dir_hcrypto) hx50=
9 \
-	krb5 ntlm kafs gssapi hdb kadm5 auth $(dir_45) $(dir_otp) $(dir_dce)
+ at SQLITE3_FALSE@dir_sqlite =3D sqlite
+SUBDIRS =3D \
+	roken \
+	vers \
+	$(dir_editline) \
+	$(dir_com_err) \
+	sl \
+	wind \
+	asn1 \
+	$(dir_sqlite) \
+	$(dir_hcrypto) \
+	ipc \
+	hx509 \
+	krb5 \
+	ntlm \
+	kafs \
+	gssapi \
+	hdb \
+	kadm5 \
+	$(dir_otp) \
+	$(dir_dce)
=20
+EXTRA_DIST =3D NTMakefile heimdal
 all: all-recursive
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/Makef=
ile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -359,6 +444,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -373,7 +459,7 @@
 #     (which will cause the Makefiles to be regenerated when you run `make=
');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -390,7 +476,7 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done; \
 	if test "$$dot_seen" =3D "no"; then \
@@ -398,7 +484,7 @@
 	fi; test -z "$$fail"
=20
 $(RECURSIVE_CLEAN_TARGETS):
-	@failcom=3D'exit 1'; \
+	@fail=3D failcom=3D'exit 1'; \
 	for f in x $$MAKEFLAGS; do \
 	  case $$f in \
 	    *=3D* | --[!k]*);; \
@@ -424,16 +510,16 @@
 	  else \
 	    local_target=3D"$$target"; \
 	  fi; \
-	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
+	  ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
 	  || eval $$failcom; \
 	done && test -z "$$fail"
 tags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags);=
 \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 tags); \
 	done
 ctags-recursive:
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
-	  test "$$subdir" =3D . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags)=
; \
+	  test "$$subdir" =3D . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS)=
 ctags); \
 	done
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
@@ -441,14 +527,14 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS: tags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
 	  include_option=3D--etags-include; \
@@ -460,39 +546,43 @@
 	list=3D'$(SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test ! -f $$subdir/TAGS || \
-	      tags=3D"$$tags $$include_option=3D$$here/$$subdir/TAGS"; \
+	      set "$$@" "$$include_option=3D$$here/$$subdir/TAGS"; \
 	  fi; \
 	done; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS: ctags-recursive $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -513,29 +603,44 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
-	list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
 	  if test "$$subdir" =3D .; then :; else \
 	    test -d "$(distdir)/$$subdir" \
 	    || $(MKDIR_P) "$(distdir)/$$subdir" \
 	    || exit 1; \
-	    distdir=3D`$(am__cd) $(distdir) && pwd`; \
-	    top_distdir=3D`$(am__cd) $(top_distdir) && pwd`; \
-	    (cd $$subdir && \
+	  fi; \
+	done
+	@list=3D'$(DIST_SUBDIRS)'; for subdir in $$list; do \
+	  if test "$$subdir" =3D .; then :; else \
+	    dir1=3D$$subdir; dir2=3D"$(distdir)/$$subdir"; \
+	    $(am__relativize); \
+	    new_distdir=3D$$reldir; \
+	    dir1=3D$$subdir; dir2=3D"$(top_distdir)"; \
+	    $(am__relativize); \
+	    new_top_distdir=3D$$reldir; \
+	    echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir=3D"$$new_t=
op_distdir" distdir=3D"$$new_distdir" \\"; \
+	    echo "     am__remove_distdir=3D: am__skip_length_check=3D: am__skip_=
mode_fix=3D: distdir)"; \
+	    ($(am__cd) $$subdir && \
 	      $(MAKE) $(AM_MAKEFLAGS) \
-	        top_distdir=3D"$$top_distdir" \
-	        distdir=3D"$$distdir/$$subdir" \
+	        top_distdir=3D"$$new_top_distdir" \
+	        distdir=3D"$$new_distdir" \
 		am__remove_distdir=3D: \
 		am__skip_length_check=3D: \
+		am__skip_mode_fix=3D: \
 	        distdir) \
 	      || exit 1; \
 	  fi; \
@@ -569,6 +674,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -587,6 +693,8 @@
=20
 html: html-recursive
=20
+html-am:
+
 info: info-recursive
=20
 info-am:
@@ -594,23 +702,31 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-recursive
=20
-install-dvi: install-dvi-recursive
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-recursive
=20
+install-html-am:
+
 install-info: install-info-recursive
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-recursive
=20
+install-pdf-am:
+
 install-ps: install-ps-recursive
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-recursive
@@ -632,9 +748,9 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \
-	install-data-am install-exec-am install-strip uninstall-am
+.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) check-am \
+	ctags-recursive install-am install-data-am install-exec-am \
+	install-strip tags-recursive uninstall-am
=20
 .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
 	all all-am all-local check check-am check-local clean \
@@ -720,6 +836,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -805,7 +924,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -818,6 +937,7 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/ChangeLog
--- a/head/crypto/heimdal/lib/asn1/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,59 @@
-2008-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-04-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* pkinit.asn1: add id-pkinit-kdf
+
+	* pkinit.asn1: add PkinitSP80056AOtherInfo
+
+2008-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* gen.c: Use unsigned where appropriate.
+
+2008-03-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* k5.asn1: Match name in ClientCanonicalizedNames with -10
+
+	* k5.asn1: add referral-valid-until
+
+2008-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* asn1-common.h gen.c der.c gen_encode.c: add and use der_{malloc,free}
=20
-2007-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* libasn1.h: remove, not used.
=20
-2007-12-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add DigestTypes, add --seq to antoher type.
=20
 	* digest.asn1: Add supportedMechs request.
-=09
-2007-10-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2007-10-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* k5.asn1: Some "old" windows enctypes. From Andy Polyakov.
-=09
-2007-07-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2007-07-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Fold in pk-init-alg-agilty.
=20
 	* pkinit.asn1: Fold in pk-init-alg-agilty.
=20
-2007-07-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse.y: Passe object id is its part of the module defintion
 	statement.
=20
-2007-07-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-gen.c: test SEQ OF SIZE (...)
=20
 	* Makefile.am: Include more sizeof tests.
=20
-2007-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* try to avoid aliasing of pointers enum {} vs int
=20
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test.asn1: Test SIZE attribute for SEQ and OCTET STRING
=20
@@ -45,10 +61,10 @@
=20
 	* Makefile.am: New library version.
=20
-2007-07-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-
-	* rfc2459.asn1: Re-add size limits.=20
-=09
+2007-07-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* rfc2459.asn1: Re-add size limits.
+
 	* k5.asn1: Add size limits from RFC 4120.
=20
 	* gen_decode.c: Check range on SEQ OF and OCTET STRING.
@@ -57,17 +73,17 @@
=20
 	* parse.y: Parse size limitations to SEQ OF.
=20
-2007-06-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add AuthorityInfoAccessSyntax.
=20
 	* rfc2459.asn1: Add AuthorityInfoAccessSyntax.
=20
 	* rfc2459.asn1: Add authorityInfoAccess, rename proxyCertInfo.
-=09
+
 	* Makefile.am: Add authorityInfoAccess, rename proxyCertInfo.
=20
-2007-06-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_get.c (der_get_time): avoid using wrapping of octet_string
 	and realloc.
@@ -95,20 +111,20 @@
=20
 	* check-der.c: Test zero length integer.
=20
-2007-06-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: Init data to something.
=20
-2007-06-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* k5.asn1: Add KRB5-AUTHDATA-INITIAL-VERIFIED-CAS.
=20
-2007-06-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* pkinit.asn1: Make the pkinit nonce signed (like the kerberos
 	nonce).
=20
-2007-06-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: Free more memory.
=20
@@ -122,10 +138,10 @@
=20
 	* der_format.c (der_parse_hex_heim_integer): check length before
 	reading data.
-=09
+
 	* check-gen.c (test_authenticator): free memory
-=09
-2007-05-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2007-05-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add MS-UPN-SAN
=20
@@ -133,13 +149,13 @@
=20
 	* rfc2459.asn1: Do evil things to handle IMPLICIT encoded
 	structures.  Add id-ms-client-authentication.
-=09
-2007-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2007-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add asn1_id_ms_cert_enroll_domaincontroller.x
-=09
-2007-05-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-05-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* gen.c: Add struct units; as a forward declaration. Pointed out
 	by Marcus Watts.
=20
@@ -148,65 +164,65 @@
 	* Makefile.am: add U.S. Federal PKI Common Policy Framework
=20
 	* rfc2459.asn1: add U.S. Federal PKI Common Policy Framework
-=09
-2007-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2007-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_seq.c: Handle the case of resize to 0 and realloc that
 	returns NULL.
=20
 	* check-gen.c (check_seq): free seq.
-=09
-2007-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2007-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c (test_heim_oid_format_same): avoid leaking memory in
 	the non failure case too
-=09
-2007-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: remove extra ^Q
-=09
-2007-04-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-04-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* der_get.c: Allow trailing NULs. We allow this since MIT Kerberos
 	sends an strings in the NEED_PREAUTH case that includes a trailing
 	NUL.
-=09
-2007-02-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
-=09
+
+2007-02-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+
 	* Makefile.am: Add PA-ClientCanonicalized and friends.
=20
 	* k5.asn1: Add PA-ClientCanonicalized and friends.
-=09
-2007-02-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2007-02-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: Drop one over INT_MAX test-case.
-=09
-2007-02-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-02-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* pkinit.asn1: add id-pkinit-ms-eku
-=09
+
 	* pkinit.asn1: fill in more bits of id-pkinit-ms-san
-=09
-2007-02-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-02-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* digest.asn1: rename hash-a1 to session key
-=09
-2007-02-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-02-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* digest.asn1: Add elements to send in requestResponse to KDC and
 	get status of the request.
-=09
-2007-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-01-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: seq rules for CRLDistributionPoints
-=09
-2007-01-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-01-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: add CRLDistributionPoints and friends
-=09
-2007-01-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-01-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* check-der.c: check BMPstring oddlength more
=20
 	* check-der.c: Test for NUL char in string in GENERAL STRING.
@@ -215,24 +231,24 @@
 	ASN1_BAD_CHARACTER error-code if we find them.
=20
 	* asn1_err.et: Add BAD_CHARACTER error.
-=09
-2007-01-16  Love H=F6rnquist =C5strand <lha at it.su.se>
-=09
+
+2007-01-16  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
+
 	* Makefile.am: Add id-at-streetAddress.
=20
 	* rfc2459.asn1: Add id-at-streetAddress.
-=09
-2007-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2007-01-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* rfc2459.asn1: Add PKIXXmppAddr and id-pkix-on-xmppAddr.
-=09
-2006-12-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-12-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: Add id-pkix-kp oids.
=20
 	* rfc2459.asn1: Add id-pkix-kp oids.
-=09
-2006-12-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-12-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_encode.c: Named bit strings have this horrible, disgusting,
 	compress bits until they are no longer really there but stuff in
@@ -242,56 +258,56 @@
 	* check-gen.c: Check all other silly bitstring combinations.
=20
 	* Makefile.am: Add --sequence=3DExtensions to rfc2459.
-=09
-2006-12-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-12-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* kx509.asn1: Add kx509.
=20
 	* Makefile.am: Add kx509.
=20
 	* Add VisibleString parsing
=20
-2006-12-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add ntlm files.
=20
 	* digest.asn1: Add bits for handling NTLM.
-=09
-2006-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-12-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add pkix proxy cert policy lang oids
=20
 	* rfc2459.asn1: add pkix proxy cert policy lang oids
-=09
-2006-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-12-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* rfc2459.asn1: unbreak id-pe-proxyCertInfo
=20
 	* rfc2459.asn1: Add id-pkix-on-dnsSRV and related oids
=20
-2006-11-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+2006-11-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: Add explicit depenency to LIB_roken for libasn1.la,
 	make AIX happy.
-=09
-2006-11-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-11-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_format.c (der_print_heim_oid): oid with zero length is
 	invalid, fail to print.
-=09
-2006-11-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-11-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* der_format.c (der_print_heim_oid): use delim when printing.
-=09
-2006-11-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-11-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* k5.asn1: Make KRB5-PADATA-S4U2SELF pa type 129.
-=09
-2006-10-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-10-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* asn1_err.et: add EXTRA_DATA
-=09
-2006-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-gen.c: avoid leaking memory
=20
@@ -305,18 +321,18 @@
 	unaligned.
=20
 	* lex.l: add missing */
-=09
+
 	* lex.c: need %e for hpux lex
=20
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: remove dups from gen_files_test, add check-timegm.
-=09
+
 	* Makefile.am: include more test.asn1 built files
=20
 	* Makefile.am: More files, now for make check.
-=09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add missing files
=20
@@ -329,17 +345,17 @@
 	* timegm.c: make more strict
=20
 	* der_locl.h: Rename timegm to _der_timegm.
-=09
-2006-10-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-10-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* timegm.c: vJust fail if tm_mon is out of range for now XXXX this
 	is wrong.
-=09
-2006-10-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-10-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: extra depencies on der-protos.h
-=09
-2006-10-14 Love H=F6rnquist =C5strand <lha at it.su.se>
+
+2006-10-14 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* check-der.c: Prefix primitive types with der_.
=20
@@ -348,7 +364,7 @@
 	* heim_asn1.h: move prototype away from here.
=20
 	* der_format.c: Add der_parse_heim_oid
-=09
+
 	* gen_free.c: prefix primitive types with der_
=20
 	* der_copy.c: prefix primitive types with der_
@@ -368,7 +384,7 @@
 	* der_copy.c: rename copy_ to der_copy_
=20
 	* Makefile.am: Add der-protos.h to nodist_include_HEADERS.
-=09
+
 	* der.h: use newly built <der-protos.h>
=20
 	* Makefile.am: Generate der prototypes.
@@ -384,29 +400,29 @@
=20
 	* check-der.c: New der_print_heim_oid signature.  Test
 	der_parse_heim_oid
-=09
-2006-10-07  Love H=F6rnquist =C5strand <lha at it.su.se>
-=09
+
+2006-10-07  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
+
 	* lex.l: Grow an even larger output table size.
=20
 	* Makefile.am: split build files into dist_ and noinst_ SOURCES
-=09
-2006-10-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-10-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_seq.c: In generation of remove_TYPE: if you just removed the
 	last element, you must not memmove memory beyond the array.  From
 	Andrew Bartlett
-=09
-2006-10-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-10-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lex.l: Grow (%p, %a, %n) tables for Solaris 10 lex. From Harald
 	Barth.
-=09
-2006-09-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-09-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c (decode_type): drop unused variable realtype.
-=09
-2006-09-11  Love H=F6rnquist =C5strand <lha at it.su.se>
+
+2006-09-11  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* Makefile.am: Add KRB5SignedPath and friends.
=20
@@ -414,12 +430,12 @@
=20
 	* Makefile.am: Add new sequence generation for GeneralNames.
=20
-2006-09-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* CMS.asn1 (CMSVersion): rename versions from v0 to CMSVersion_v0,
 	...
-=09
-2006-09-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-09-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add TESTSeqOf for testing sequence generation code.
=20
@@ -446,23 +462,23 @@
 	TType". I'm tried of writing realloc(foo->data,
 	sizeof(foo->data[0]) + (foo->len + 1)); Only generated for those
 	type that is enabled by the command flag --sequence.
-=09
-2006-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* digest.asn1 (DigestRequest): add authid
=20
 	* digest.asn1: Comment describing on how to communicate the sasl
 	int/conf mode.
-=09
-2006-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* digest.asn1: Add some missing fields needed for digest.
-=09
-2006-08-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-08-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* digest.asn1: Tweak to make consisten and more easier to use.
-=09
-2006-07-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-07-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Remove CMS symmetric encryption support.  Add
 	DigestProtocol.
@@ -470,9 +486,9 @@
 	* digest.asn1: DigestProtocol
=20
 	* k5.asn1: Remove CMS symmetric encryption support.
-=09
-2006-06-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-06-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* check-der.c (check_fail_heim_integer): disable test
=20
 	* der_get.c (der_get_heim_integer): revert part of previous
@@ -485,58 +501,58 @@
=20
 	* check-der.c: Add one check for heim_int, add checking for oid
 	printing
-=09
-2006-06-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-06-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Impersonation support bits (and sort)
=20
 	* k5.asn1: Impersonation support bits.
-=09
-2006-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_format.c (der_parse_hex_heim_integer): avoid shadowing.
-=09
-2006-04-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: Add ExternalPrincipalIdentifiers, shared between
 	several elements.
=20
 	* pkinit.asn1: Add ExternalPrincipalIdentifiers, shared between
 	several elements.
-=09
-2006-04-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-04-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse.y: Add missing ;'s, found by bison on a SuSE 8.2 machine.
-=09
-2006-04-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add definitions from RFC 3820, Proxy Certificate
 	Profile.
=20
 	* rfc2459.asn1: Add definitions from RFC 3820, Proxy Certificate
 	Profile.
-=09
-2006-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rfc2459.asn1: Add id-Userid
=20
 	* Makefile.am: Add UID and email
=20
 	* pkcs9.asn1: Add id-pkcs9-emailAddress
-=09
+
 	* Makefile.am: Add attribute type oids from X520 and RFC 2247 DC
 	oid
=20
 	* rfc2459.asn1: Add attribute type oids from X520 and RFC 2247 DC
 	oid
-=09
-2006-04-21  Love H=F6rnquist =C5strand <lha at it.su.se>
+
+2006-04-21  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* Makefile.am: add sha-1 and sha-2
=20
 	* rfc2459.asn1: add sha-1 and sha-2
-=09
-2006-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add id-pkcs1-sha256WithRSAEncryption and friends
=20
@@ -544,50 +560,50 @@
=20
 	* CMS.asn1: Turn CMSRC2CBCParameter.rc2ParameterVersion into a
 	constrained integer
-=09
-2006-04-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-04-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hash.c (hashtabnew): check for NULL before setting structure.
 	Coverity, NetBSD CID#4
-=09
-2006-03-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-03-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: gen_files_rfc2459 +=3D asn1_ExtKeyUsage.x
-=09
+
 	* rfc2459.asn1: Add ExtKeyUsage.
=20
 	* gen.c (generate_header_of_codefile): remove unused variable.
-=09
-2006-03-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-03-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen.c: Put all the IMPORTed headers into the headerfile to avoid
 	hidden depencies.
-=09
-2006-03-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-03-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add id-pkinit-ms-san.
=20
 	* pkinit.asn1: Add id-pkinit-ms-san.
=20
 	* k5.asn1 (PADATA-TYPE): Add KRB5-PADATA-PA-PK-OCSP-RESPONSE
-=09
-2006-03-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-03-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add pkinit-san.
=20
 	* pkinit.asn1: Rename id-pksan to id-pkinit-san
-=09
-2006-03-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-03-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen.c (init_generate): Nothing in the generated files needs
 	timegm(), so no need to provide a prototype for it.
-=09
-2006-02-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-02-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* pkinit.asn1: paChecksum is now OPTIONAL so it can be upgraded to
 	something better then SHA1
-=09
-2006-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-01-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* extra.c: Stub-generator now generates alloc statements for
 	tagless ANY OPTIONAL, remove workaround.
@@ -595,25 +611,25 @@
 	* check-gen.c: check for "tagless ANY OPTIONAL"
=20
 	* test.asn1: check for "tagless ANY OPTIONAL"
-=09
-2006-01-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-01-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der.h: UniversalString and BMPString are both implemented.
=20
 	* der.h: Remove , after the last element of enum.
=20
 	* asn1_gen.c: Spelling.
-=09
-2006-01-20  Love H=F6rnquist =C5strand <lha at it.su.se>
-=09
+
+2006-01-20  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
+
 	* der_length.c (length_heim_integer): Try handle negative length
 	of integers better.
=20
 	* der_get.c (der_get_heim_integer): handle negative integers.
-=09
+
 	* check-der.c: check heim_integer.
-=09
-2006-01-18  Love H=F6rnquist =C5strand <lha at it.su.se>
+
+2006-01-18  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* Makefile.am: Its cRLReason, not cRLReasons
=20
@@ -630,8 +646,8 @@
=20
 	* der_cmp.c (heim_integer_cmp): make it work with negative
 	numbers.
-=09
-2006-01-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2006-01-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: check that der_parse_hex_heim_integer() handles odd
 	length numbers.
@@ -639,21 +655,21 @@
 	* der_format.c (der_parse_hex_heim_integer): make more resiliant
 	to errors, handle odd length numbers.
=20
-2006-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+2006-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: Add RSAPrivateKey
-=09
+
 	* rfc2459.asn1: Add RSAPrivateKey.
-=09
-2006-01-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2006-01-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* der_copy.c (copy_heim_integer): copy the negative flag
-=09
-2005-12-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-12-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse.y: Drop ExceptionSpec for now, its not used.
-=09
-2005-12-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-12-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test.asn1: Add test string for constraints.
=20
@@ -663,71 +679,71 @@
 	constructed types.
=20
 	* parse.y: Add support for parsing part of the Constraint-s
-=09
-2005-10-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
-=09
+
+2005-10-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
 	* Makefile.am: Add some X9.57 (DSA) oids, sort lines
=20
 	* rfc2459.asn1: Add some X9.57 (DSA) oids.
-=09
-2005-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Remove pk-init-19 support.
-=09
+
 	* pkinit.asn1: Fix comment
-=09
+
 	* check-der.c: Add tests for parse and print functions for
 	heim_integer.
=20
 	* Makefile.am: Add parse and print functions for heim_integer.
-=09
+
 	* der_format.c: Add parse and print functions for heim_integer.
=20
 	* der.h: Add parse and print functions for heim_integer.
-=09
-2005-09-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-09-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am (gen_files_rfc2459) +=3D asn1_DHPublicKey.x
-=09
+
 	* rfc2459.asn1: Add DHPublicKey, and INTEGER to for storing the DH
 	public key in the SubjectPublicKeyInfo.subjectPublicKey BIT
 	STRING.
-=09
-2005-09-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-09-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c: TSequenceOf/TSetOf: Increase the length of the
 	array after successful decoding the next element, so that the
 	array don't contain heap-data.
-=09
-2005-09-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-09-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: Avoid empty array initiators.
-=09
+
 	* pkcs8.asn1 (PKCS8PrivateKeyInfo): Inline SET OF to avoid
 	compiler "feature"
-=09
+
 	* check-common.c: Avoid signedness warnings.
-=09
+
 	* check-common.h: Makes bytes native platform signed to avoid
 	casting everywhere
-=09
+
 	* check-der.c: Don't depend on malloc(very-very-larger-value) will
 	fail.  Cast to unsigned long before printing size_t.
-=09
+
 	* check-gen.c: Don't depend on malloc(very-very-larger-value) will
 	fail.
-=09
+
 	* check-gen.c: Fix signedness warnings.
-=09
+
 	* lex.l: unput() have to hanppen in actions for flex 2.5.31, can
 	do them in user code sesction, so move up handle_comment and
 	handle_string into action, not much sharing was done anyway.
-=09
-2005-09-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-09-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c (test_one_int): len and len_len is size_t
=20
-2005-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_encode.c: Change name of oldret for each instance its used
 	to avoid shadow warning. From: Stefan Metzmacher
@@ -740,61 +756,61 @@
 	* gen_decode.c: Change name of oldret for each instance its used
 	to avoid shadow warning. From: Stefan Metzmacher
 	<metze at samba.org>.
-=09
+
 	* parse.y: Const poision yyerror.
=20
 	* gen.c: Const poision.
-=09
-2005-08-22 Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-08-22 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* k5.asn1: Add KRB5-PADATA-PK-AS-09-BINDING, client send
 	this (with an empty pa-data.padata-value) to tell the KDC that the
 	client support the binding the PA-REP to the AS-REQ packet. This
 	is to fix the problem lack of binding the AS-REQ to the PK-AS-REP
 	in pre PK-INIT-27. The nonce is replaced with a asCheckSum.
-=09
-2005-08-11 Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-08-11 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* canthandle.asn1: Allocation is done on CONTEXT tags.
=20
 	* asn1_gen.c: rename optind to optidx to avoid shadow warnings
=20
-2005-07-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rfc2459.asn1: add id-rsadsi-rc2-cbc
=20
 	* Makefile.am: add another oid for rc2
=20
-2005-07-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: Make variable initiation constant by moving them to
 	global context
=20
 	* check-gen.c: change to c89 comment
=20
-2005-07-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: remove duplicate asn1_CMSAttributes.x
=20
-2005-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* asn1_print.c: rename optind to optidx
=20
 	* Makefile.am: Update to pkinit-27
=20
 	* pkinit.asn1: Update to pkinit-27
-=09
-2005-07-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+
+2005-07-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: make it work for non c99 compilers too
-=09
+
 	* check-der.c: start testing BIT STRING
=20
 	* der_cmp.c (heim_bit_string_cmp): try handle corner cases better
-=09
+
 	* gen_free.c (free_type): free bignum integers
=20
-2005-07-23   Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-23   Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add PKCS12-OctetString
=20
@@ -807,24 +823,24 @@
=20
 	* CMS.asn1: handle IMPLICIT and share some common structures
=20
-2005-07-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rfc2459.asn1: Include enough workarounds that this even might
 	work.
=20
 	* check-gen.c: Two implicit tests, one with all structures inlined
-=09
+
 	* test.asn1: fix workaround for IMPLICIT CONS case
-=09
+
 	* canthandle.asn1: fix workaround for IMPLICIT CONS case
-=09
+
 	* asn1_print.c: hint that there are IMPLICIT content when we find
 	it
=20
 	* check-gen.c: Added #ifdef out test for IMPLICIT tagging.
=20
 	* Makefile.am: test several IMPLICIT tag level deep
-=09
+
 	* test.asn1: test several IMPLICIT tag level deep
=20
 	* test.asn1: tests for IMPLICIT
@@ -837,7 +853,7 @@
 	* rfc2459.asn1: some of the structure are in the IMPLICIT TAGS
 	module
=20
-2005-07-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* asn1_print.c: print size_t by casting to unsigned long and use
 	right printf format tags are unsigned integers
@@ -869,7 +885,7 @@
=20
 	* gen_decode.c (find_tag): Fix return in TType case.
=20
-2005-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_encode.c (TChoice): add () to make sure variable expression
 	is evaluated correctly
@@ -880,7 +896,7 @@
 	* k5.asn1: reapply 1.43 that got lost in the merge: rename pvno to
 	krb5-pvno
=20
-2005-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c (decode_type): TChoice: set the label
=20
@@ -931,7 +947,7 @@
 	Make sure that malloc(0) returning NULL is not treated as an
 	error.
=20
-2005-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-gen.c: test cases for CHOICE, its too liberal right now,
 	it don't fail hard on failure on after it successfully decoded the
@@ -958,7 +974,7 @@
 	* der.h: Add class/type/tag string<->num converter.
 	Prototypes/structures for new time bits.
=20
-2005-07-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_get.c (der_get_unsigned) check for length overflow
 	(der_get_integer) ditto
@@ -979,13 +995,13 @@
 	* check-common.c (map_alloc): make input buffer const
 	(generic_decode_fail): verify decoding failures
=20
-2005-07-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_encode.c: split up the printf for SET OF, also use the
 	generate name for the symbol in the SET OF, if not, the name might
 	contain non valid variable name characters (like -)
=20
-2005-07-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: move pkcs12 defines into their own namespace
=20
@@ -1004,7 +1020,7 @@
 	* gen_decode.c: use less context so lower indentention level, add
 	missing {} where needed
=20
-2005-07-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_copy.c: Use a global variable to keep track of if the 'goto
 	fail' was used, and use that to only generate the label if needed.
@@ -1017,7 +1033,7 @@
 	(missing EndOfContent tag) add (negative) indent flag to speed up
 	testing
=20
-2005-07-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* canthandle.asn1: Can't handle primitives in CHOICE
=20
@@ -1028,12 +1044,12 @@
 	* gen_decode.c: Check if malloc failes, rename "reallen" to
 	tagdatalen since that is what it is.
=20
-2005-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* prefix Der_class with ASN1_C_ to avoid problems with system
 	headerfiles that pollute the name space
=20
-2005-05-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* pkcs12.asn1: add PKCS12CertBag
=20
@@ -1047,16 +1063,16 @@
=20
 	* Makefile.am: add PKCS12Attributes
=20
-2005-05-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* canthandle.asn1: fix tags in example
=20
-2005-05-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* pkinit.asn1: Let the Windows nonce be an int32 (signed), if not
 	it will fail when using Windows PK-INIT.
=20
-2005-05-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add pkcs12-PBEParams
=20
@@ -1064,14 +1080,14 @@
=20
 	* parse.y: objid_element: exit when the condition fails
=20
-2005-04-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_glue.c: 1.8: switch the units variable to a
 	function. gcc-4.1 needs the size of the structure if its defined
 	as extern struct units foo_units[] an we don't want to include
 	<parse_units.h> in the generate headerfile
=20
-2005-03-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add the des-ede3-cbc oid that ansi x9.52 uses
=20
@@ -1081,23 +1097,23 @@
=20
 	* rfc2459.asn1: add oids now when the compiler can handle them
=20
-2005-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add pkcs9 files
=20
 	* pkcs9.asn1: add small number of oids from pkcs9
=20
-2005-03-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add a bunch of pkcs1/pkcs2/pkcs3/aes oids
=20
 	* rfc2459.asn1: add a bunch of pkcs1/pkcs2/pkcs3/aes oids
=20
-2005-03-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* k5.asn1: merge pa-numbers
=20
-2005-03-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add oid's
=20
@@ -1109,7 +1125,7 @@
=20
 	* CMS.asn1: add pkcs7 oids
=20
-2005-03-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen.c (generate_header_of_codefile): break out the header
 	section generation
@@ -1120,12 +1136,12 @@
=20
 	* parse.y: handle OBJECT IDENTIFIER as value construct
=20
-2005-02-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Preserve content of CHOICE element that is unknown if ellipsis
 	was used when defining the structure
=20
-2005-02-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse.y: use ANS1_TAILQ macros
=20
@@ -1134,43 +1150,43 @@
 	* asn1_queue.h: inline bsd sys/queue.h and rename TAILQ to
 	ASN1_TAILQ to avoid problems with name polluting headerfiles
=20
-2005-01-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen.c: pull in <krb5-types.h>
=20
-2005-01-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Add BMPString and UniversalString
=20
 	* k5.asn1 (EtypeList): make INTEGER constrained (use krb5int32)
=20
-2005-01-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rfc2459.asn1: add GeneralNames
=20
-2004-11-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen.c: use unsigned integer for len of SequenceOf/SetOf and
 	bitstring names
=20
-2004-11-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: switch to krb5int32 and krb5uint32
=20
 	* Unify that three integer types TInteger TUInteger and TBigInteger.
 	Start to use constrained integers where appropriate.
=20
-2004-10-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* CMS.asn1: remove no longer used commented out elements
=20
 	* gen_glue.c: make units structures const
=20
-2004-10-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lex.l: handle hex number with [a-fA-F] in them
=20
-2004-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_free.c: free _save for CHOICE too
=20
@@ -1187,7 +1203,7 @@
 	name is CMSIdentifier and add glue for that so we can share code
 	use Name and not heim_any
=20
-2004-10-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: drop AlgorithmIdentifierNonOpt add
 	{RC2CBC,}CBCParameter here where they belong
@@ -1199,7 +1215,7 @@
 	* rfc2459.asn1: stop using AlgorithmIdentifierNonOpt hint that we
 	really want to use Name and some MS stuff
=20
-2004-09-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* asn1_print.c: handle end of content, this is part BER support,
 	however, OCTET STRING need some tweeking too.
@@ -1244,7 +1260,7 @@
=20
 	* CMS.asn1: add EncryptedData
=20
-2004-08-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c (decode_type): if the entry is already optional
 	when parsing a tag and we allocate the structure, not pass down
@@ -1252,12 +1268,12 @@
 	allocate an entry. and we'll leak an entry. Bug from Luke Howard
 	<lukeh at padl.com>. While here, use calloc.
=20
-2004-04-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* k5.asn1: shift the last added etypes one step so rc2 doesn't
 	stomp on cram-md5
=20
-2004-04-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* k5.asn1: add ETYPE_AESNNN_CBC_NONE
=20
@@ -1266,17 +1282,17 @@
 	* k5.asn1: add CMS symmetrical parameters here, more nametypes
 	enctype rc2-cbc
=20
-2004-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c: free data on decode failure
=20
-2004-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add CBCParameter and RC2CBCParameter
=20
 	* CMS.asn1: add CBCParameter and RC2CBCParameter
=20
-2004-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-der.c: add simple test for oid's, used to trigger malloc
 	bugs in you have picky malloc (like valgrind/purify/third)
@@ -1285,7 +1301,7 @@
 	then 127 and allocate one extra element since first byte is split
 	to to elements.
=20
-2004-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* canthandle.asn1: one thing handled
=20
@@ -1295,7 +1311,7 @@
 	an unsigned, do the length counting here. ("unsigned" is zero
 	padded when most significate bit is set, length is not)
=20
-2004-04-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* canthandle.asn1: document by example what the encoder can't
 	handle right now
@@ -1344,7 +1360,7 @@
=20
 	* der.h: hide away more symbols, add more _cmp functions
=20
-2004-03-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add more pkix types make k5 use rfc150 bitstrings,
 	everything else use der bitstrings
@@ -1365,7 +1381,7 @@
=20
 	* rfc2459.asn1: add Certificates and KeyUsage
=20
-2004-02-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* pkinit.asn1: use Name from PKIX
=20
@@ -1398,7 +1414,7 @@
 	* gen_length.c: 1.14: (length_type): TSequenceOf: add up the size
 	of all the elements, don't use just the size of the last element.
=20
-2004-02-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rfc2459.asn1: include defintion of Name
=20
@@ -1410,7 +1426,7 @@
=20
 	* Makefile.am: align with pk-init-18, move contentinfo to cms
=20
-2004-02-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_get.c: rewrite previous commit
=20
@@ -1461,17 +1477,17 @@
 	* asn1-common.h: add signedness flag to heim_integer, add
 	ia5string and printablestring
=20
-2004-02-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rfc2459.asn1: use BIGINTEGER where appropriate
=20
 	* setchgpw2.asn1: spelling and add op-req again
=20
-2004-02-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: clean up better
=20
-2004-02-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c (decode_type): TTag, don't overshare the reallen
 	variable
@@ -1480,7 +1496,7 @@
=20
 	* gen.c: genereate log file name based on base name
=20
-2003-11-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: +=3D asn1_AlgorithmIdentifierNonOpt.x
=20
@@ -1491,7 +1507,7 @@
=20
 	* pkinit.asn1: don't import AlgorithmIdentifier
=20
-2003-11-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_put.c (der_put_bit_string): make it work somewhat better
 	(should really prune off all trailing zeros)
@@ -1501,7 +1517,7 @@
 	* der_length.c (length_bit_string): calculate right length for
 	bitstrings
=20
-2003-11-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_cmp.c (oid_cmp): compare the whole array, not just
 	length/sizeof(component)
@@ -1524,11 +1540,11 @@
=20
 	* asn1_print.c: check end of tag_names loop into APPL class tags
=20
-2003-11-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_put.c (der_put_generalized_time): check size, not *size
=20
-2003-11-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c (decode_type/TBitString): skip over
 	skipped-bits-in-last-octet octet
@@ -1536,7 +1552,7 @@
 	* gen_glue.c (generate_units): generate units in reverse order to
 	keep unparse_units happy
=20
-2003-11-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: generate all silly pkinit files
=20
@@ -1592,7 +1608,7 @@
=20
 	* pkinit.asn1: add KdcDHKeyInfo-Win2k
=20
-2003-11-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* der_copy.c (copy_oid): copy all components
=20
@@ -1612,29 +1628,29 @@
 	steping out in the void, parse SET, only go down CONTEXT of type
 	CONS (not PRIM)
=20
-2003-09-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_encode.c (TChoice, TSequence): code element in reverse
 	order...
=20
-2003-09-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen.c: store NULL's as int's for now
=20
 	* parse.y: remove dup of type def of UsefulType
=20
-2003-09-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c (decode_type): if malloc failes, return ENOMEM
=20
-2003-09-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse.y: kw_UTF8String is a token put tag around the OID
=20
 	* asn1_print.c (UT_Integer): when the integer is larger then int
 	can handle, just print BIG INT and its size
=20
-2003-09-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gen_decode.c (decode_type): TTag, try to generate prettier code
 	in the non optional case, also remember to update length
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/Makefile.=
am
--- a/head/crypto/heimdal/lib/asn1/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 22445 2008-01-14 21:23:36Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -7,456 +7,62 @@
 lib_LTLIBRARIES =3D libasn1.la
 libasn1_la_LDFLAGS =3D -version-info 8:0:0
=20
+noinst_LTLIBRARIES =3D libasn1base.la
+
+if versionscript
+libasn1_la_LDFLAGS +=3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.=
map
+endif
+
+
 libasn1_la_LIBADD =3D \
+	libasn1base.la \
 	@LIB_com_err@ \
 	$(LIBADD_roken)
=20
 BUILT_SOURCES =3D				\
 	$(gen_files_rfc2459:.x=3D.c)	\
 	$(gen_files_cms:.x=3D.c)		\
-	$(gen_files_k5:.x=3D.c)		\
+	$(gen_files_krb5:.x=3D.c)		\
 	$(gen_files_pkinit:.x=3D.c)	\
 	$(gen_files_pkcs8:.x=3D.c)	\
 	$(gen_files_pkcs9:.x=3D.c)	\
 	$(gen_files_pkcs12:.x=3D.c)	\
 	$(gen_files_digest:.x=3D.c)	\
-	$(gen_files_kx509:.x=3D.c)	\
-	asn1_err.h			\
-	asn1_err.c
+	$(gen_files_kx509:.x=3D.c)
=20
-gen_files_k5 =3D						\
-	asn1_AD_AND_OR.x				\
-	asn1_AD_IF_RELEVANT.x				\
-	asn1_AD_KDCIssued.x				\
-	asn1_AD_MANDATORY_FOR_KDC.x			\
-	asn1_AD_LoginAlias.x				\
-	asn1_APOptions.x				\
-	asn1_AP_REP.x					\
-	asn1_AP_REQ.x					\
-	asn1_AS_REP.x					\
-	asn1_AS_REQ.x					\
-	asn1_AUTHDATA_TYPE.x				\
-	asn1_Authenticator.x				\
-	asn1_AuthorizationData.x			\
-	asn1_AuthorizationDataElement.x			\
-	asn1_CKSUMTYPE.x				\
-	asn1_ChangePasswdDataMS.x			\
-	asn1_Checksum.x					\
-	asn1_ENCTYPE.x					\
-	asn1_ETYPE_INFO.x				\
-	asn1_ETYPE_INFO2.x				\
-	asn1_ETYPE_INFO2_ENTRY.x			\
-	asn1_ETYPE_INFO_ENTRY.x				\
-	asn1_EncAPRepPart.x				\
-	asn1_EncASRepPart.x				\
-	asn1_EncKDCRepPart.x				\
-	asn1_EncKrbCredPart.x				\
-	asn1_EncKrbPrivPart.x				\
-	asn1_EncTGSRepPart.x				\
-	asn1_EncTicketPart.x				\
-	asn1_EncryptedData.x				\
-	asn1_EncryptionKey.x				\
-	asn1_EtypeList.x				\
-	asn1_HostAddress.x				\
-	asn1_HostAddresses.x				\
-	asn1_KDCOptions.x				\
-	asn1_KDC_REP.x					\
-	asn1_KDC_REQ.x					\
-	asn1_KDC_REQ_BODY.x				\
-	asn1_KRB_CRED.x					\
-	asn1_KRB_ERROR.x				\
-	asn1_KRB_PRIV.x					\
-	asn1_KRB_SAFE.x					\
-	asn1_KRB_SAFE_BODY.x				\
-	asn1_KerberosString.x				\
-	asn1_KerberosTime.x				\
-	asn1_KrbCredInfo.x				\
-	asn1_LR_TYPE.x					\
-	asn1_LastReq.x					\
-	asn1_MESSAGE_TYPE.x				\
-	asn1_METHOD_DATA.x				\
-	asn1_NAME_TYPE.x				\
-	asn1_PADATA_TYPE.x				\
-	asn1_PA_DATA.x					\
-	asn1_PA_ENC_SAM_RESPONSE_ENC.x         		\
-	asn1_PA_ENC_TS_ENC.x				\
-	asn1_PA_PAC_REQUEST.x				\
-	asn1_PA_S4U2Self.x				\
-	asn1_PA_SAM_CHALLENGE_2.x               	\
-	asn1_PA_SAM_CHALLENGE_2_BODY.x 			\
-	asn1_PA_SAM_REDIRECT.x				\
-	asn1_PA_SAM_RESPONSE_2.x			\
-	asn1_PA_SAM_TYPE.x				\
-	asn1_PA_ClientCanonicalized.x			\
-	asn1_PA_ClientCanonicalizedNames.x		\
-	asn1_PA_SvrReferralData.x			\
-	asn1_PROV_SRV_LOCATION.x			\
-	asn1_Principal.x				\
-	asn1_PrincipalName.x				\
-	asn1_Realm.x					\
-	asn1_SAMFlags.x					\
-	asn1_TGS_REP.x					\
-	asn1_TGS_REQ.x					\
-	asn1_TYPED_DATA.x				\
-	asn1_Ticket.x					\
-	asn1_TicketFlags.x				\
-	asn1_TransitedEncoding.x			\
-	asn1_TypedData.x				\
-	asn1_krb5int32.x				\
-	asn1_krb5uint32.x				\
-	asn1_KRB5SignedPathData.x			\
-	asn1_KRB5SignedPathPrincipals.x			\
-	asn1_KRB5SignedPath.x
+gen_files_krb5 =3D asn1_krb5_asn1.x
+gen_files_cms =3D asn1_cms_asn1.x
+gen_files_rfc2459 =3D asn1_rfc2459_asn1.x
+gen_files_pkinit =3D asn1_pkinit_asn1.x
+gen_files_pkcs12 =3D asn1_pkcs12_asn1.x
+gen_files_pkcs8 =3D asn1_pkcs8_asn1.x
+gen_files_pkcs9 =3D asn1_pkcs9_asn1.x
+gen_files_test =3D asn1_test_asn1.x
+gen_files_digest =3D asn1_digest_asn1.x
+gen_files_kx509 =3D asn1_kx509_asn1.x
=20
-gen_files_cms =3D						\
-	asn1_CMSAttributes.x				\
-	asn1_CMSCBCParameter.x				\
-	asn1_CMSEncryptedData.x				\
-	asn1_CMSIdentifier.x				\
-	asn1_CMSRC2CBCParameter.x			\
-	asn1_CMSVersion.x				\
-	asn1_CertificateList.x				\
-	asn1_CertificateRevocationLists.x		\
-	asn1_CertificateSet.x				\
-	asn1_ContentEncryptionAlgorithmIdentifier.x	\
-	asn1_ContentInfo.x				\
-	asn1_ContentType.x				\
-	asn1_DigestAlgorithmIdentifier.x		\
-	asn1_DigestAlgorithmIdentifiers.x		\
-	asn1_EncapsulatedContentInfo.x			\
-	asn1_EncryptedContent.x				\
-	asn1_EncryptedContentInfo.x			\
-	asn1_EncryptedKey.x				\
-	asn1_EnvelopedData.x				\
-	asn1_IssuerAndSerialNumber.x			\
-	asn1_KeyEncryptionAlgorithmIdentifier.x		\
-	asn1_KeyTransRecipientInfo.x			\
-	asn1_MessageDigest.x				\
-	asn1_OriginatorInfo.x				\
-	asn1_RecipientIdentifier.x			\
-	asn1_RecipientInfo.x				\
-	asn1_RecipientInfos.x				\
-	asn1_SignatureAlgorithmIdentifier.x		\
-	asn1_SignatureValue.x				\
-	asn1_SignedData.x				\
-	asn1_SignerIdentifier.x				\
-	asn1_SignerInfo.x				\
-	asn1_SignerInfos.x				\
-	asn1_id_pkcs7.x					\
-	asn1_id_pkcs7_data.x				\
-	asn1_id_pkcs7_digestedData.x			\
-	asn1_id_pkcs7_encryptedData.x			\
-	asn1_id_pkcs7_envelopedData.x			\
-	asn1_id_pkcs7_signedAndEnvelopedData.x		\
-	asn1_id_pkcs7_signedData.x			\
-	asn1_UnprotectedAttributes.x
+noinst_PROGRAMS =3D asn1_gen
=20
-gen_files_rfc2459 =3D					\
-	asn1_Version.x					\
-	asn1_id_pkcs_1.x				\
-	asn1_id_pkcs1_rsaEncryption.x			\
-	asn1_id_pkcs1_md2WithRSAEncryption.x		\
-	asn1_id_pkcs1_md5WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha1WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha256WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha384WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha512WithRSAEncryption.x		\
-	asn1_id_heim_rsa_pkcs1_x509.x			\
-	asn1_id_pkcs_2.x				\
-	asn1_id_pkcs2_md2.x				\
-	asn1_id_pkcs2_md4.x				\
-	asn1_id_pkcs2_md5.x				\
-	asn1_id_rsa_digestAlgorithm.x			\
-	asn1_id_rsa_digest_md2.x			\
-	asn1_id_rsa_digest_md4.x			\
-	asn1_id_rsa_digest_md5.x			\
-	asn1_id_pkcs_3.x				\
-	asn1_id_pkcs3_rc2_cbc.x				\
-	asn1_id_pkcs3_rc4.x				\
-	asn1_id_pkcs3_des_ede3_cbc.x			\
-	asn1_id_rsadsi_encalg.x				\
-	asn1_id_rsadsi_rc2_cbc.x			\
-	asn1_id_rsadsi_des_ede3_cbc.x			\
-	asn1_id_secsig_sha_1.x				\
-	asn1_id_nistAlgorithm.x				\
-	asn1_id_nist_aes_algs.x				\
-	asn1_id_aes_128_cbc.x				\
-	asn1_id_aes_192_cbc.x				\
-	asn1_id_aes_256_cbc.x				\
-	asn1_id_nist_sha_algs.x				\
-	asn1_id_sha256.x				\
-	asn1_id_sha224.x				\
-	asn1_id_sha384.x				\
-	asn1_id_sha512.x				\
-	asn1_id_dhpublicnumber.x			\
-	asn1_id_x9_57.x					\
-	asn1_id_dsa.x					\
-	asn1_id_dsa_with_sha1.x				\
-	asn1_id_x520_at.x				\
-	asn1_id_at_commonName.x				\
-	asn1_id_at_surname.x				\
-	asn1_id_at_serialNumber.x			\
-	asn1_id_at_countryName.x			\
-	asn1_id_at_localityName.x			\
-	asn1_id_at_streetAddress.x			\
-	asn1_id_at_stateOrProvinceName.x		\
-	asn1_id_at_organizationName.x			\
-	asn1_id_at_organizationalUnitName.x		\
-	asn1_id_at_name.x				\
-	asn1_id_at_givenName.x				\
-	asn1_id_at_initials.x				\
-	asn1_id_at_generationQualifier.x		\
-	asn1_id_at_pseudonym.x				\
-	asn1_id_Userid.x				\
-	asn1_id_domainComponent.x			\
-	asn1_id_x509_ce.x				\
-	asn1_id_uspkicommon_card_id.x			\
-	asn1_id_uspkicommon_piv_interim.x		\
-	asn1_id_netscape.x				\
-	asn1_id_netscape_cert_comment.x			\
-	asn1_id_ms_cert_enroll_domaincontroller.x	\
-	asn1_id_ms_client_authentication.x		\
-	asn1_AlgorithmIdentifier.x			\
-	asn1_AttributeType.x				\
-	asn1_AttributeValue.x				\
-	asn1_TeletexStringx.x				\
-	asn1_DirectoryString.x				\
-	asn1_Attribute.x				\
-	asn1_AttributeTypeAndValue.x			\
-	asn1_AuthorityInfoAccessSyntax.x		\
-	asn1_AccessDescription.x			\
-	asn1_RelativeDistinguishedName.x		\
-	asn1_RDNSequence.x				\
-	asn1_Name.x					\
-	asn1_CertificateSerialNumber.x			\
-	asn1_Time.x					\
-	asn1_Validity.x					\
-	asn1_UniqueIdentifier.x				\
-	asn1_SubjectPublicKeyInfo.x			\
-	asn1_Extension.x				\
-	asn1_Extensions.x				\
-	asn1_TBSCertificate.x				\
-	asn1_Certificate.x				\
-	asn1_Certificates.x				\
-	asn1_ValidationParms.x				\
-	asn1_DomainParameters.x				\
-	asn1_DHPublicKey.x				\
-	asn1_OtherName.x				\
-	asn1_GeneralName.x				\
-	asn1_GeneralNames.x				\
-	asn1_id_x509_ce_keyUsage.x			\
-	asn1_KeyUsage.x					\
-	asn1_id_x509_ce_authorityKeyIdentifier.x	\
-	asn1_KeyIdentifier.x				\
-	asn1_AuthorityKeyIdentifier.x			\
-	asn1_id_x509_ce_subjectKeyIdentifier.x		\
-	asn1_SubjectKeyIdentifier.x			\
-	asn1_id_x509_ce_basicConstraints.x		\
-	asn1_BasicConstraints.x				\
-	asn1_id_x509_ce_nameConstraints.x		\
-	asn1_BaseDistance.x				\
-	asn1_GeneralSubtree.x				\
-	asn1_GeneralSubtrees.x				\
-	asn1_NameConstraints.x				\
-	asn1_id_x509_ce_privateKeyUsagePeriod.x		\
-	asn1_id_x509_ce_certificatePolicies.x		\
-	asn1_id_x509_ce_policyMappings.x		\
-	asn1_id_x509_ce_subjectAltName.x		\
-	asn1_id_x509_ce_issuerAltName.x			\
-	asn1_id_x509_ce_subjectDirectoryAttributes.x	\
-	asn1_id_x509_ce_policyConstraints.x		\
-	asn1_id_x509_ce_extKeyUsage.x			\
-	asn1_ExtKeyUsage.x				\
-	asn1_id_x509_ce_cRLDistributionPoints.x		\
-	asn1_id_x509_ce_deltaCRLIndicator.x		\
-	asn1_id_x509_ce_issuingDistributionPoint.x	\
-	asn1_id_x509_ce_holdInstructionCode.x		\
-	asn1_id_x509_ce_invalidityDate.x		\
-	asn1_id_x509_ce_certificateIssuer.x		\
-	asn1_id_x509_ce_inhibitAnyPolicy.x		\
-	asn1_DistributionPointReasonFlags.x		\
-	asn1_DistributionPointName.x			\
-	asn1_DistributionPoint.x			\
-	asn1_CRLDistributionPoints.x			\
-	asn1_DSASigValue.x				\
-	asn1_DSAPublicKey.x				\
-	asn1_DSAParams.x				\
-	asn1_RSAPublicKey.x				\
-	asn1_RSAPrivateKey.x				\
-	asn1_DigestInfo.x				\
-	asn1_TBSCRLCertList.x				\
-	asn1_CRLCertificateList.x			\
-	asn1_id_x509_ce_cRLNumber.x			\
-	asn1_id_x509_ce_freshestCRL.x			\
-	asn1_id_x509_ce_cRLReason.x			\
-	asn1_CRLReason.x				\
-	asn1_PKIXXmppAddr.x				\
-	asn1_id_pkix.x					\
-	asn1_id_pkix_on.x				\
-	asn1_id_pkix_on_dnsSRV.x			\
-	asn1_id_pkix_on_xmppAddr.x			\
-	asn1_id_pkix_kp.x				\
-	asn1_id_pkix_kp_serverAuth.x			\
-	asn1_id_pkix_kp_clientAuth.x			\
-	asn1_id_pkix_kp_emailProtection.x		\
-	asn1_id_pkix_kp_timeStamping.x			\
-	asn1_id_pkix_kp_OCSPSigning.x			\
-	asn1_id_pkix_pe.x				\
-	asn1_id_pkix_pe_authorityInfoAccess.x		\
-	asn1_id_pkix_pe_proxyCertInfo.x			\
-	asn1_id_pkix_ppl.x				\
-	asn1_id_pkix_ppl_anyLanguage.x			\
-	asn1_id_pkix_ppl_inheritAll.x			\
-	asn1_id_pkix_ppl_independent.x			\
-	asn1_ProxyPolicy.x				\
-	asn1_ProxyCertInfo.x=20
+libexec_heimdal_PROGRAMS =3D asn1_compile asn1_print
=20
-gen_files_pkinit =3D					\
-	asn1_id_pkinit.x				\
-	asn1_id_pkauthdata.x				\
-	asn1_id_pkdhkeydata.x				\
-	asn1_id_pkrkeydata.x				\
-	asn1_id_pkekuoid.x				\
-	asn1_id_pkkdcekuoid.x				\
-	asn1_id_pkinit_san.x				\
-	asn1_id_pkinit_ms_eku.x				\
-	asn1_id_pkinit_ms_san.x				\
-	asn1_MS_UPN_SAN.x				\
-	asn1_DHNonce.x					\
-	asn1_KDFAlgorithmId.x				\
-	asn1_TrustedCA.x				\
-	asn1_ExternalPrincipalIdentifier.x		\
-	asn1_ExternalPrincipalIdentifiers.x		\
-	asn1_PA_PK_AS_REQ.x				\
-	asn1_PKAuthenticator.x				\
-	asn1_AuthPack.x					\
-	asn1_TD_TRUSTED_CERTIFIERS.x			\
-	asn1_TD_INVALID_CERTIFICATES.x			\
-	asn1_KRB5PrincipalName.x			\
-	asn1_AD_INITIAL_VERIFIED_CAS.x			\
-	asn1_DHRepInfo.x				\
-	asn1_PA_PK_AS_REP.x				\
-	asn1_KDCDHKeyInfo.x				\
-	asn1_ReplyKeyPack.x				\
-	asn1_TD_DH_PARAMETERS.x				\
-	asn1_PKAuthenticator_Win2k.x			\
-	asn1_AuthPack_Win2k.x				\
-	asn1_TrustedCA_Win2k.x				\
-	asn1_PA_PK_AS_REQ_Win2k.x			\
-	asn1_PA_PK_AS_REP_Win2k.x			\
-	asn1_KDCDHKeyInfo_Win2k.x			\
-	asn1_ReplyKeyPack_Win2k.x			\
-	asn1_PkinitSuppPubInfo.x=20
-
-gen_files_pkcs12 =3D					\
-	asn1_id_pkcs_12.x				\
-	asn1_id_pkcs_12PbeIds.x				\
-	asn1_id_pbeWithSHAAnd128BitRC4.x		\
-	asn1_id_pbeWithSHAAnd40BitRC4.x			\
-	asn1_id_pbeWithSHAAnd3_KeyTripleDES_CBC.x	\
-	asn1_id_pbeWithSHAAnd2_KeyTripleDES_CBC.x	\
-	asn1_id_pbeWithSHAAnd128BitRC2_CBC.x		\
-	asn1_id_pbewithSHAAnd40BitRC2_CBC.x		\
-	asn1_id_pkcs12_bagtypes.x			\
-	asn1_id_pkcs12_keyBag.x				\
-	asn1_id_pkcs12_pkcs8ShroudedKeyBag.x		\
-	asn1_id_pkcs12_certBag.x			\
-	asn1_id_pkcs12_crlBag.x				\
-	asn1_id_pkcs12_secretBag.x			\
-	asn1_id_pkcs12_safeContentsBag.x		\
-	asn1_PKCS12_MacData.x				\
-	asn1_PKCS12_PFX.x				\
-	asn1_PKCS12_AuthenticatedSafe.x			\
-	asn1_PKCS12_CertBag.x				\
-	asn1_PKCS12_Attribute.x				\
-	asn1_PKCS12_Attributes.x			\
-	asn1_PKCS12_SafeBag.x				\
-	asn1_PKCS12_SafeContents.x			\
-	asn1_PKCS12_OctetString.x			\
-	asn1_PKCS12_PBEParams.x
-
-gen_files_pkcs8 =3D					\
-	asn1_PKCS8PrivateKeyAlgorithmIdentifier.x	\
-	asn1_PKCS8PrivateKey.x				\
-	asn1_PKCS8PrivateKeyInfo.x			\
-	asn1_PKCS8Attributes.x				\
-	asn1_PKCS8EncryptedPrivateKeyInfo.x		\
-	asn1_PKCS8EncryptedData.x
-
-gen_files_pkcs9 =3D					\
-	asn1_id_pkcs_9.x				\
-	asn1_id_pkcs9_contentType.x			\
-	asn1_id_pkcs9_emailAddress.x			\
-	asn1_id_pkcs9_messageDigest.x			\
-	asn1_id_pkcs9_signingTime.x			\
-	asn1_id_pkcs9_countersignature.x		\
-	asn1_id_pkcs_9_at_friendlyName.x		\
-	asn1_id_pkcs_9_at_localKeyId.x			\
-	asn1_id_pkcs_9_at_certTypes.x			\
-	asn1_id_pkcs_9_at_certTypes_x509.x		\
-	asn1_PKCS9_BMPString.x				\
-	asn1_PKCS9_friendlyName.x
-
-gen_files_test =3D					\
-	asn1_TESTAlloc.x				\
-	asn1_TESTAllocInner.x				\
-	asn1_TESTCONTAINING.x				\
-	asn1_TESTCONTAININGENCODEDBY.x			\
-	asn1_TESTCONTAININGENCODEDBY2.x			\
-	asn1_TESTChoice1.x				\
-	asn1_TESTChoice2.x				\
-	asn1_TESTDer.x					\
-	asn1_TESTENCODEDBY.x				\
-	asn1_TESTImplicit.x				\
-	asn1_TESTImplicit2.x				\
-	asn1_TESTInteger.x				\
-	asn1_TESTInteger2.x				\
-	asn1_TESTInteger3.x				\
-	asn1_TESTLargeTag.x				\
-	asn1_TESTSeq.x					\
-	asn1_TESTUSERCONSTRAINED.x			\
-	asn1_TESTSeqOf.x				\
-	asn1_TESTOSSize1.x				\
-	asn1_TESTSeqSizeOf1.x				\
-	asn1_TESTSeqSizeOf2.x				\
-	asn1_TESTSeqSizeOf3.x				\
-	asn1_TESTSeqSizeOf4.x
-
-gen_files_digest =3D					\
-	asn1_DigestError.x				\
-	asn1_DigestInit.x				\
-	asn1_DigestInitReply.x				\
-	asn1_DigestREP.x				\
-	asn1_DigestREQ.x				\
-	asn1_DigestRepInner.x				\
-	asn1_DigestReqInner.x				\
-	asn1_DigestRequest.x				\
-	asn1_DigestResponse.x				\
-	asn1_DigestTypes.x				\
-	asn1_NTLMInit.x					\
-	asn1_NTLMInitReply.x				\
-	asn1_NTLMRequest.x				\
-	asn1_NTLMResponse.x
-
-gen_files_kx509 =3D					\
-	asn1_Kx509Response.x				\
-	asn1_Kx509Request.x
-
-noinst_PROGRAMS =3D asn1_compile asn1_print asn1_gen
-
-TESTS =3D check-der check-gen check-timegm
+TESTS =3D check-der check-gen check-timegm check-ber check-template
 check_PROGRAMS =3D $(TESTS)
=20
 asn1_gen_SOURCES =3D asn1_gen.c
 asn1_print_SOURCES =3D asn1_print.c
 check_der_SOURCES =3D check-der.c check-common.c check-common.h
=20
+check_template_SOURCES =3D check-template.c check-common.c check-common.h
+nodist_check_template_SOURCES =3D $(gen_files_test:.x=3D.c)
+
 dist_check_gen_SOURCES =3D check-gen.c check-common.c check-common.h
 nodist_check_gen_SOURCES =3D $(gen_files_test:.x=3D.c)
=20
+build_HEADERZ =3D asn1-template.h
+
 asn1_compile_SOURCES =3D 				\
-	asn1-common.h				\
 	asn1_queue.h				\
+	asn1parse.y				\
 	der.h					\
 	gen.c					\
 	gen_copy.c				\
@@ -467,17 +73,17 @@
 	gen_length.c				\
 	gen_locl.h				\
 	gen_seq.c				\
+	gen_template.c				\
 	hash.c					\
 	hash.h					\
 	lex.l					\
 	lex.h					\
 	main.c					\
-	parse.y					\
+	asn1-template.h				\
 	symbol.c				\
 	symbol.h
=20
-dist_libasn1_la_SOURCES =3D			\
-	der-protos.h 				\
+dist_libasn1base_la_SOURCES =3D			\
 	der_locl.h 				\
 	der.c					\
 	der.h					\
@@ -490,27 +96,38 @@
 	der_format.c				\
 	heim_asn1.h				\
 	extra.c					\
+	template.c				\
 	timegm.c
=20
+nodist_libasn1base_la_SOURCES =3D 	\
+	asn1_err.h			\
+	asn1_err.c
+
 nodist_libasn1_la_SOURCES =3D $(BUILT_SOURCES)
=20
 asn1_compile_LDADD =3D \
 	$(LIB_roken) $(LEXLIB)
=20
 check_der_LDADD =3D \
+	libasn1base.la \
+	$(LIB_roken)
+
+check_template_LDADD =3D $(check_der_LDADD)
+asn1_print_LDADD =3D $(check_der_LDADD) $(LIB_com_err)
+asn1_gen_LDADD =3D $(check_der_LDADD)
+check_timegm_LDADD =3D $(check_der_LDADD)
+
+check_gen_LDADD =3D \
 	libasn1.la \
 	$(LIB_roken)
=20
-check_gen_LDADD =3D $(check_der_LDADD)
-asn1_print_LDADD =3D $(check_der_LDADD)
-asn1_gen_LDADD =3D $(check_der_LDADD)
-check_timegm_LDADD =3D $(check_der_LDADD)
+check_ber_LDADD =3D $(check_gen_LDADD)
=20
 CLEANFILES =3D \
 	$(BUILT_SOURCES) \
 	$(gen_files_rfc2459) \
 	$(gen_files_cms) \
-	$(gen_files_k5) \
+	$(gen_files_krb5) \
 	$(gen_files_pkinit) \
 	$(gen_files_pkcs8) \
 	$(gen_files_pkcs9) \
@@ -518,18 +135,20 @@
 	$(gen_files_digest) \
 	$(gen_files_kx509) \
 	$(gen_files_test) $(nodist_check_gen_SOURCES) \
-	rfc2459_asn1_files rfc2459_asn1.h \
-	cms_asn1_files cms_asn1.h \
-	krb5_asn1_files krb5_asn1.h \
-	pkinit_asn1_files pkinit_asn1.h \
-	pkcs8_asn1_files pkcs8_asn1.h \
-	pkcs9_asn1_files pkcs9_asn1.h \
-	pkcs12_asn1_files pkcs12_asn1.h \
-	digest_asn1_files digest_asn1.h \
-	kx509_asn1_files kx509_asn1.h \
-	test_asn1_files test_asn1.h
+	asn1_err.c asn1_err.h \
+	rfc2459_asn1_files rfc2459_asn1*.h* \
+	cms_asn1_files cms_asn1*.h* \
+	krb5_asn1_files krb5_asn1*.h* \
+	pkinit_asn1_files pkinit_asn1*.h* \
+	pkcs8_asn1_files pkcs8_asn1*.h* \
+	pkcs9_asn1_files pkcs9_asn1*.h* \
+	pkcs12_asn1_files pkcs12_asn1*.h* \
+	digest_asn1_files digest_asn1*.h* \
+	kx509_asn1_files kx509_asn1*.h* \
+	test_asn1_files test_asn1*.h*
=20
-dist_include_HEADERS =3D der.h heim_asn1.h der-protos.h
+dist_include_HEADERS =3D der.h heim_asn1.h der-protos.h der-private.h
+dist_include_HEADERS +=3D asn1-common.h
=20
 nodist_include_HEADERS =3D asn1_err.h
 nodist_include_HEADERS +=3D krb5_asn1.h
@@ -542,69 +161,94 @@
 nodist_include_HEADERS +=3D digest_asn1.h
 nodist_include_HEADERS +=3D kx509_asn1.h
=20
-$(asn1_compile_OBJECTS): parse.h parse.c $(srcdir)/der-protos.h
-$(libasn1_la_OBJECTS): krb5_asn1.h asn1_err.h $(srcdir)/der-protos.h
+priv_headers  =3D krb5_asn1-priv.h
+priv_headers +=3D pkinit_asn1-priv.h
+priv_headers +=3D cms_asn1-priv.h
+priv_headers +=3D rfc2459_asn1-priv.h
+priv_headers +=3D pkcs8_asn1-priv.h
+priv_headers +=3D pkcs9_asn1-priv.h
+priv_headers +=3D pkcs12_asn1-priv.h
+priv_headers +=3D digest_asn1-priv.h
+priv_headers +=3D kx509_asn1-priv.h
+priv_headers +=3D test_asn1.h test_asn1-priv.h
+
+
+
+$(asn1_compile_OBJECTS): asn1parse.h asn1parse.c $(srcdir)/der-protos.h $(=
srcdir)/der-private.h
+$(libasn1_la_OBJECTS): $(nodist_include_HEADERS) $(priv_headers) asn1_err.=
h $(srcdir)/der-protos.h $(srcdir)/der-private.h
+$(libasn1base_la_OBJECTS): asn1_err.h $(srcdir)/der-protos.h $(srcdir)/der=
-private.h
 $(check_gen_OBJECTS): test_asn1.h
+$(check_template_OBJECTS): test_asn1_files
 $(asn1_print_OBJECTS): krb5_asn1.h
=20
-parse.h: parse.c
+asn1parse.h: asn1parse.c
=20
-$(gen_files_k5) krb5_asn1.h: krb5_asn1_files
-$(gen_files_pkinit) pkinit_asn1.h: pkinit_asn1_files
-$(gen_files_pkcs8) pkcs8_asn1.h: pkcs8_asn1_files
-$(gen_files_pkcs9) pkcs9_asn1.h: pkcs9_asn1_files
-$(gen_files_pkcs12) pkcs12_asn1.h: pkcs12_asn1_files
-$(gen_files_digest) digest_asn1.h: digest_asn1_files
-$(gen_files_kx509) kx509_asn1.h: kx509_asn1_files
-$(gen_files_rfc2459) rfc2459_asn1.h: rfc2459_asn1_files
-$(gen_files_cms) cms_asn1.h: cms_asn1_files
-$(gen_files_test) test_asn1.h: test_asn1_files
+$(gen_files_krb5) krb5_asn1.hx krb5_asn1-priv.hx: krb5_asn1_files
+$(gen_files_pkinit) pkinit_asn1.hx pkinit_asn1-priv.hx: pkinit_asn1_files
+$(gen_files_pkcs8) pkcs8_asn1.hx pkcs8_asn1-priv.hx: pkcs8_asn1_files
+$(gen_files_pkcs9) pkcs9_asn1.hx pkcs9_asn1-priv.hx: pkcs9_asn1_files
+$(gen_files_pkcs12) pkcs12_asn1.hx pkcs12_asn1-priv.hx: pkcs12_asn1_files
+$(gen_files_digest) digest_asn1.hx digest_asn1-priv.hx: digest_asn1_files
+$(gen_files_kx509) kx509_asn1.hx kx509_asn1-priv.hx: kx509_asn1_files
+$(gen_files_rfc2459) rfc2459_asn1.hx rfc2459_asn1-priv.hx: rfc2459_asn1_fi=
les
+$(gen_files_cms) cms_asn1.hx cms_asn1-priv.hx: cms_asn1_files
+$(gen_files_test) test_asn1.hx test_asn1-priv.hx: test_asn1_files
=20
 rfc2459_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/rfc2459.asn1
-	./asn1_compile$(EXEEXT) --preserve-binary=3DTBSCertificate --preserve-bin=
ary=3DTBSCRLCertList --preserve-binary=3DName --sequence=3DGeneralNames --s=
equence=3DExtensions --sequence=3DCRLDistributionPoints $(srcdir)/rfc2459.a=
sn1 rfc2459_asn1 || (rm -f rfc2459_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file --preserve-binary=3DTBSCertificate --pres=
erve-binary=3DTBSCRLCertList --preserve-binary=3DName --sequence=3DGeneralN=
ames --sequence=3DExtensions --sequence=3DCRLDistributionPoints $(srcdir)/r=
fc2459.asn1 rfc2459_asn1 || (rm -f rfc2459_asn1_files ; exit 1)
=20
-cms_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/CMS.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/CMS.asn1 cms_asn1 || (rm -f cms_asn1_fi=
les ; exit 1)
+cms_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/cms.asn1 $(srcdir)/cms.opt
+	$(ASN1_COMPILE) --one-code-file --option-file=3D$(srcdir)/cms.opt $(srcdi=
r)/cms.asn1 cms_asn1 || (rm -f cms_asn1_files ; exit 1)
=20
-krb5_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/k5.asn1
-	./asn1_compile$(EXEEXT) --encode-rfc1510-bit-string --sequence=3DKRB5Sign=
edPathPrincipals --sequence=3DAuthorizationData --sequence=3DMETHOD-DATA --=
sequence=3DETYPE-INFO --sequence=3DETYPE-INFO2 $(srcdir)/k5.asn1 krb5_asn1 =
|| (rm -f krb5_asn1_files ; exit 1)
+krb5_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/krb5.asn1 $(srcdir)/krb5.=
opt
+	$(ASN1_COMPILE) --one-code-file --option-file=3D$(srcdir)/krb5.opt $(srcd=
ir)/krb5.asn1 krb5_asn1 || (rm -f krb5_asn1_files ; exit 1)
=20
 pkinit_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkinit.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkinit.asn1 pkinit_asn1 || (rm -f pkini=
t_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkinit.asn1 pkinit_asn1 || (rm =
-f pkinit_asn1_files ; exit 1)
=20
 pkcs8_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs8.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkcs8.asn1 pkcs8_asn1 || (rm -f pkcs8_a=
sn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkcs8.asn1 pkcs8_asn1 || (rm -f=
 pkcs8_asn1_files ; exit 1)
=20
 pkcs9_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs9.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkcs9.asn1 pkcs9_asn1 || (rm -f pkcs9_a=
sn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkcs9.asn1 pkcs9_asn1 || (rm -f=
 pkcs9_asn1_files ; exit 1)
=20
 pkcs12_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs12.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkcs12.asn1 pkcs12_asn1 || (rm -f pkcs1=
2_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkcs12.asn1 pkcs12_asn1 || (rm =
-f pkcs12_asn1_files ; exit 1)
=20
 digest_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/digest.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/digest.asn1 digest_asn1 || (rm -f diges=
t_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/digest.asn1 digest_asn1 || (rm =
-f digest_asn1_files ; exit 1)
=20
 kx509_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/kx509.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/kx509.asn1 kx509_asn1 || (rm -f kx509_a=
sn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/kx509.asn1 kx509_asn1 || (rm -f=
 kx509_asn1_files ; exit 1)
=20
 test_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/test.asn1
-	./asn1_compile$(EXEEXT) --sequence=3DTESTSeqOf $(srcdir)/test.asn1 test_a=
sn1 || (rm -f test_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file --sequence=3DTESTSeqOf $(srcdir)/test.asn=
1 test_asn1 || (rm -f test_asn1_files ; exit 1)
+
=20
 EXTRA_DIST =3D		\
+	NTMakefile	\
+	asn1_compile-version.rc \
+	libasn1-exports.def \
+	cms.asn1	\
+	cms.opt		\
 	asn1_err.et	\
 	canthandle.asn1	\
-	CMS.asn1	\
 	digest.asn1	\
-	k5.asn1		\
+	krb5.asn1	\
+	krb5.opt	\
 	kx509.asn1	\
-	test.asn1	\
-	setchgpw2.asn1	\
 	pkcs12.asn1	\
 	pkcs8.asn1	\
 	pkcs9.asn1	\
 	pkinit.asn1	\
 	rfc2459.asn1	\
-	test.gen
+	setchgpw2.asn1	\
+	test.asn1	\
+	test.gen	\
+	version-script.map
=20
 $(srcdir)/der-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o der-protos.h=
 $(dist_libasn1_la_SOURCES) || rm -f der-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o der-protos.h=
 $(dist_libasn1base_la_SOURCES) || rm -f der-protos.h
+
+$(srcdir)/der-private.h:
+	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p der-private.=
h $(dist_libasn1base_la_SOURCES) || rm -f der-private.h
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/Makefile.=
in
--- a/head/crypto/heimdal/lib/asn1/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22445 2008-01-14 21:23:36Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -42,16 +44,18 @@
 host_triplet =3D @host@
 DIST_COMMON =3D $(dist_include_HEADERS) $(srcdir)/Makefile.am \
 	$(srcdir)/Makefile.in $(top_srcdir)/Makefile.am.common \
-	$(top_srcdir)/cf/Makefile.am.common ChangeLog lex.c parse.c \
-	parse.h
-noinst_PROGRAMS =3D asn1_compile$(EXEEXT) asn1_print$(EXEEXT) \
-	asn1_gen$(EXEEXT)
-TESTS =3D check-der$(EXEEXT) check-gen$(EXEEXT) check-timegm$(EXEEXT)
+	$(top_srcdir)/cf/Makefile.am.common ChangeLog asn1parse.c \
+	asn1parse.h lex.c
+ at versionscript_TRUE@am__append_1 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
+noinst_PROGRAMS =3D asn1_gen$(EXEEXT)
+libexec_heimdal_PROGRAMS =3D asn1_compile$(EXEEXT) asn1_print$(EXEEXT)
+TESTS =3D check-der$(EXEEXT) check-gen$(EXEEXT) check-timegm$(EXEEXT) \
+	check-ber$(EXEEXT) check-template$(EXEEXT)
 check_PROGRAMS =3D $(am__EXEEXT_1)
 subdir =3D lib/asn1
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -66,7 +70,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -80,9 +84,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -90,281 +97,108 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
-am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" \
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
+am__installdirs =3D "$(DESTDIR)$(libdir)" \
+	"$(DESTDIR)$(libexec_heimdaldir)" "$(DESTDIR)$(includedir)" \
 	"$(DESTDIR)$(includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
-LTLIBRARIES =3D $(lib_LTLIBRARIES)
+LTLIBRARIES =3D $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES)
 am__DEPENDENCIES_1 =3D
-libasn1_la_DEPENDENCIES =3D $(am__DEPENDENCIES_1)
-dist_libasn1_la_OBJECTS =3D der.lo der_get.lo der_put.lo der_free.lo \
-	der_length.lo der_copy.lo der_cmp.lo der_format.lo extra.lo \
-	timegm.lo
-am__objects_1 =3D asn1_Version.lo asn1_id_pkcs_1.lo \
-	asn1_id_pkcs1_rsaEncryption.lo \
-	asn1_id_pkcs1_md2WithRSAEncryption.lo \
-	asn1_id_pkcs1_md5WithRSAEncryption.lo \
-	asn1_id_pkcs1_sha1WithRSAEncryption.lo \
-	asn1_id_pkcs1_sha256WithRSAEncryption.lo \
-	asn1_id_pkcs1_sha384WithRSAEncryption.lo \
-	asn1_id_pkcs1_sha512WithRSAEncryption.lo \
-	asn1_id_heim_rsa_pkcs1_x509.lo asn1_id_pkcs_2.lo \
-	asn1_id_pkcs2_md2.lo asn1_id_pkcs2_md4.lo asn1_id_pkcs2_md5.lo \
-	asn1_id_rsa_digestAlgorithm.lo asn1_id_rsa_digest_md2.lo \
-	asn1_id_rsa_digest_md4.lo asn1_id_rsa_digest_md5.lo \
-	asn1_id_pkcs_3.lo asn1_id_pkcs3_rc2_cbc.lo \
-	asn1_id_pkcs3_rc4.lo asn1_id_pkcs3_des_ede3_cbc.lo \
-	asn1_id_rsadsi_encalg.lo asn1_id_rsadsi_rc2_cbc.lo \
-	asn1_id_rsadsi_des_ede3_cbc.lo asn1_id_secsig_sha_1.lo \
-	asn1_id_nistAlgorithm.lo asn1_id_nist_aes_algs.lo \
-	asn1_id_aes_128_cbc.lo asn1_id_aes_192_cbc.lo \
-	asn1_id_aes_256_cbc.lo asn1_id_nist_sha_algs.lo \
-	asn1_id_sha256.lo asn1_id_sha224.lo asn1_id_sha384.lo \
-	asn1_id_sha512.lo asn1_id_dhpublicnumber.lo asn1_id_x9_57.lo \
-	asn1_id_dsa.lo asn1_id_dsa_with_sha1.lo asn1_id_x520_at.lo \
-	asn1_id_at_commonName.lo asn1_id_at_surname.lo \
-	asn1_id_at_serialNumber.lo asn1_id_at_countryName.lo \
-	asn1_id_at_localityName.lo asn1_id_at_streetAddress.lo \
-	asn1_id_at_stateOrProvinceName.lo \
-	asn1_id_at_organizationName.lo \
-	asn1_id_at_organizationalUnitName.lo asn1_id_at_name.lo \
-	asn1_id_at_givenName.lo asn1_id_at_initials.lo \
-	asn1_id_at_generationQualifier.lo asn1_id_at_pseudonym.lo \
-	asn1_id_Userid.lo asn1_id_domainComponent.lo \
-	asn1_id_x509_ce.lo asn1_id_uspkicommon_card_id.lo \
-	asn1_id_uspkicommon_piv_interim.lo asn1_id_netscape.lo \
-	asn1_id_netscape_cert_comment.lo \
-	asn1_id_ms_cert_enroll_domaincontroller.lo \
-	asn1_id_ms_client_authentication.lo \
-	asn1_AlgorithmIdentifier.lo asn1_AttributeType.lo \
-	asn1_AttributeValue.lo asn1_TeletexStringx.lo \
-	asn1_DirectoryString.lo asn1_Attribute.lo \
-	asn1_AttributeTypeAndValue.lo \
-	asn1_AuthorityInfoAccessSyntax.lo asn1_AccessDescription.lo \
-	asn1_RelativeDistinguishedName.lo asn1_RDNSequence.lo \
-	asn1_Name.lo asn1_CertificateSerialNumber.lo asn1_Time.lo \
-	asn1_Validity.lo asn1_UniqueIdentifier.lo \
-	asn1_SubjectPublicKeyInfo.lo asn1_Extension.lo \
-	asn1_Extensions.lo asn1_TBSCertificate.lo asn1_Certificate.lo \
-	asn1_Certificates.lo asn1_ValidationParms.lo \
-	asn1_DomainParameters.lo asn1_DHPublicKey.lo asn1_OtherName.lo \
-	asn1_GeneralName.lo asn1_GeneralNames.lo \
-	asn1_id_x509_ce_keyUsage.lo asn1_KeyUsage.lo \
-	asn1_id_x509_ce_authorityKeyIdentifier.lo \
-	asn1_KeyIdentifier.lo asn1_AuthorityKeyIdentifier.lo \
-	asn1_id_x509_ce_subjectKeyIdentifier.lo \
-	asn1_SubjectKeyIdentifier.lo \
-	asn1_id_x509_ce_basicConstraints.lo asn1_BasicConstraints.lo \
-	asn1_id_x509_ce_nameConstraints.lo asn1_BaseDistance.lo \
-	asn1_GeneralSubtree.lo asn1_GeneralSubtrees.lo \
-	asn1_NameConstraints.lo \
-	asn1_id_x509_ce_privateKeyUsagePeriod.lo \
-	asn1_id_x509_ce_certificatePolicies.lo \
-	asn1_id_x509_ce_policyMappings.lo \
-	asn1_id_x509_ce_subjectAltName.lo \
-	asn1_id_x509_ce_issuerAltName.lo \
-	asn1_id_x509_ce_subjectDirectoryAttributes.lo \
-	asn1_id_x509_ce_policyConstraints.lo \
-	asn1_id_x509_ce_extKeyUsage.lo asn1_ExtKeyUsage.lo \
-	asn1_id_x509_ce_cRLDistributionPoints.lo \
-	asn1_id_x509_ce_deltaCRLIndicator.lo \
-	asn1_id_x509_ce_issuingDistributionPoint.lo \
-	asn1_id_x509_ce_holdInstructionCode.lo \
-	asn1_id_x509_ce_invalidityDate.lo \
-	asn1_id_x509_ce_certificateIssuer.lo \
-	asn1_id_x509_ce_inhibitAnyPolicy.lo \
-	asn1_DistributionPointReasonFlags.lo \
-	asn1_DistributionPointName.lo asn1_DistributionPoint.lo \
-	asn1_CRLDistributionPoints.lo asn1_DSASigValue.lo \
-	asn1_DSAPublicKey.lo asn1_DSAParams.lo asn1_RSAPublicKey.lo \
-	asn1_RSAPrivateKey.lo asn1_DigestInfo.lo \
-	asn1_TBSCRLCertList.lo asn1_CRLCertificateList.lo \
-	asn1_id_x509_ce_cRLNumber.lo asn1_id_x509_ce_freshestCRL.lo \
-	asn1_id_x509_ce_cRLReason.lo asn1_CRLReason.lo \
-	asn1_PKIXXmppAddr.lo asn1_id_pkix.lo asn1_id_pkix_on.lo \
-	asn1_id_pkix_on_dnsSRV.lo asn1_id_pkix_on_xmppAddr.lo \
-	asn1_id_pkix_kp.lo asn1_id_pkix_kp_serverAuth.lo \
-	asn1_id_pkix_kp_clientAuth.lo \
-	asn1_id_pkix_kp_emailProtection.lo \
-	asn1_id_pkix_kp_timeStamping.lo asn1_id_pkix_kp_OCSPSigning.lo \
-	asn1_id_pkix_pe.lo asn1_id_pkix_pe_authorityInfoAccess.lo \
-	asn1_id_pkix_pe_proxyCertInfo.lo asn1_id_pkix_ppl.lo \
-	asn1_id_pkix_ppl_anyLanguage.lo asn1_id_pkix_ppl_inheritAll.lo \
-	asn1_id_pkix_ppl_independent.lo asn1_ProxyPolicy.lo \
-	asn1_ProxyCertInfo.lo
-am__objects_2 =3D asn1_CMSAttributes.lo asn1_CMSCBCParameter.lo \
-	asn1_CMSEncryptedData.lo asn1_CMSIdentifier.lo \
-	asn1_CMSRC2CBCParameter.lo asn1_CMSVersion.lo \
-	asn1_CertificateList.lo asn1_CertificateRevocationLists.lo \
-	asn1_CertificateSet.lo \
-	asn1_ContentEncryptionAlgorithmIdentifier.lo \
-	asn1_ContentInfo.lo asn1_ContentType.lo \
-	asn1_DigestAlgorithmIdentifier.lo \
-	asn1_DigestAlgorithmIdentifiers.lo \
-	asn1_EncapsulatedContentInfo.lo asn1_EncryptedContent.lo \
-	asn1_EncryptedContentInfo.lo asn1_EncryptedKey.lo \
-	asn1_EnvelopedData.lo asn1_IssuerAndSerialNumber.lo \
-	asn1_KeyEncryptionAlgorithmIdentifier.lo \
-	asn1_KeyTransRecipientInfo.lo asn1_MessageDigest.lo \
-	asn1_OriginatorInfo.lo asn1_RecipientIdentifier.lo \
-	asn1_RecipientInfo.lo asn1_RecipientInfos.lo \
-	asn1_SignatureAlgorithmIdentifier.lo asn1_SignatureValue.lo \
-	asn1_SignedData.lo asn1_SignerIdentifier.lo asn1_SignerInfo.lo \
-	asn1_SignerInfos.lo asn1_id_pkcs7.lo asn1_id_pkcs7_data.lo \
-	asn1_id_pkcs7_digestedData.lo asn1_id_pkcs7_encryptedData.lo \
-	asn1_id_pkcs7_envelopedData.lo \
-	asn1_id_pkcs7_signedAndEnvelopedData.lo \
-	asn1_id_pkcs7_signedData.lo asn1_UnprotectedAttributes.lo
-am__objects_3 =3D asn1_AD_AND_OR.lo asn1_AD_IF_RELEVANT.lo \
-	asn1_AD_KDCIssued.lo asn1_AD_MANDATORY_FOR_KDC.lo \
-	asn1_AD_LoginAlias.lo asn1_APOptions.lo asn1_AP_REP.lo \
-	asn1_AP_REQ.lo asn1_AS_REP.lo asn1_AS_REQ.lo \
-	asn1_AUTHDATA_TYPE.lo asn1_Authenticator.lo \
-	asn1_AuthorizationData.lo asn1_AuthorizationDataElement.lo \
-	asn1_CKSUMTYPE.lo asn1_ChangePasswdDataMS.lo asn1_Checksum.lo \
-	asn1_ENCTYPE.lo asn1_ETYPE_INFO.lo asn1_ETYPE_INFO2.lo \
-	asn1_ETYPE_INFO2_ENTRY.lo asn1_ETYPE_INFO_ENTRY.lo \
-	asn1_EncAPRepPart.lo asn1_EncASRepPart.lo \
-	asn1_EncKDCRepPart.lo asn1_EncKrbCredPart.lo \
-	asn1_EncKrbPrivPart.lo asn1_EncTGSRepPart.lo \
-	asn1_EncTicketPart.lo asn1_EncryptedData.lo \
-	asn1_EncryptionKey.lo asn1_EtypeList.lo asn1_HostAddress.lo \
-	asn1_HostAddresses.lo asn1_KDCOptions.lo asn1_KDC_REP.lo \
-	asn1_KDC_REQ.lo asn1_KDC_REQ_BODY.lo asn1_KRB_CRED.lo \
-	asn1_KRB_ERROR.lo asn1_KRB_PRIV.lo asn1_KRB_SAFE.lo \
-	asn1_KRB_SAFE_BODY.lo asn1_KerberosString.lo \
-	asn1_KerberosTime.lo asn1_KrbCredInfo.lo asn1_LR_TYPE.lo \
-	asn1_LastReq.lo asn1_MESSAGE_TYPE.lo asn1_METHOD_DATA.lo \
-	asn1_NAME_TYPE.lo asn1_PADATA_TYPE.lo asn1_PA_DATA.lo \
-	asn1_PA_ENC_SAM_RESPONSE_ENC.lo asn1_PA_ENC_TS_ENC.lo \
-	asn1_PA_PAC_REQUEST.lo asn1_PA_S4U2Self.lo \
-	asn1_PA_SAM_CHALLENGE_2.lo asn1_PA_SAM_CHALLENGE_2_BODY.lo \
-	asn1_PA_SAM_REDIRECT.lo asn1_PA_SAM_RESPONSE_2.lo \
-	asn1_PA_SAM_TYPE.lo asn1_PA_ClientCanonicalized.lo \
-	asn1_PA_ClientCanonicalizedNames.lo asn1_PA_SvrReferralData.lo \
-	asn1_PROV_SRV_LOCATION.lo asn1_Principal.lo \
-	asn1_PrincipalName.lo asn1_Realm.lo asn1_SAMFlags.lo \
-	asn1_TGS_REP.lo asn1_TGS_REQ.lo asn1_TYPED_DATA.lo \
-	asn1_Ticket.lo asn1_TicketFlags.lo asn1_TransitedEncoding.lo \
-	asn1_TypedData.lo asn1_krb5int32.lo asn1_krb5uint32.lo \
-	asn1_KRB5SignedPathData.lo asn1_KRB5SignedPathPrincipals.lo \
-	asn1_KRB5SignedPath.lo
-am__objects_4 =3D asn1_id_pkinit.lo asn1_id_pkauthdata.lo \
-	asn1_id_pkdhkeydata.lo asn1_id_pkrkeydata.lo \
-	asn1_id_pkekuoid.lo asn1_id_pkkdcekuoid.lo \
-	asn1_id_pkinit_san.lo asn1_id_pkinit_ms_eku.lo \
-	asn1_id_pkinit_ms_san.lo asn1_MS_UPN_SAN.lo asn1_DHNonce.lo \
-	asn1_KDFAlgorithmId.lo asn1_TrustedCA.lo \
-	asn1_ExternalPrincipalIdentifier.lo \
-	asn1_ExternalPrincipalIdentifiers.lo asn1_PA_PK_AS_REQ.lo \
-	asn1_PKAuthenticator.lo asn1_AuthPack.lo \
-	asn1_TD_TRUSTED_CERTIFIERS.lo asn1_TD_INVALID_CERTIFICATES.lo \
-	asn1_KRB5PrincipalName.lo asn1_AD_INITIAL_VERIFIED_CAS.lo \
-	asn1_DHRepInfo.lo asn1_PA_PK_AS_REP.lo asn1_KDCDHKeyInfo.lo \
-	asn1_ReplyKeyPack.lo asn1_TD_DH_PARAMETERS.lo \
-	asn1_PKAuthenticator_Win2k.lo asn1_AuthPack_Win2k.lo \
-	asn1_TrustedCA_Win2k.lo asn1_PA_PK_AS_REQ_Win2k.lo \
-	asn1_PA_PK_AS_REP_Win2k.lo asn1_KDCDHKeyInfo_Win2k.lo \
-	asn1_ReplyKeyPack_Win2k.lo asn1_PkinitSuppPubInfo.lo
-am__objects_5 =3D asn1_PKCS8PrivateKeyAlgorithmIdentifier.lo \
-	asn1_PKCS8PrivateKey.lo asn1_PKCS8PrivateKeyInfo.lo \
-	asn1_PKCS8Attributes.lo asn1_PKCS8EncryptedPrivateKeyInfo.lo \
-	asn1_PKCS8EncryptedData.lo
-am__objects_6 =3D asn1_id_pkcs_9.lo asn1_id_pkcs9_contentType.lo \
-	asn1_id_pkcs9_emailAddress.lo asn1_id_pkcs9_messageDigest.lo \
-	asn1_id_pkcs9_signingTime.lo asn1_id_pkcs9_countersignature.lo \
-	asn1_id_pkcs_9_at_friendlyName.lo \
-	asn1_id_pkcs_9_at_localKeyId.lo asn1_id_pkcs_9_at_certTypes.lo \
-	asn1_id_pkcs_9_at_certTypes_x509.lo asn1_PKCS9_BMPString.lo \
-	asn1_PKCS9_friendlyName.lo
-am__objects_7 =3D asn1_id_pkcs_12.lo asn1_id_pkcs_12PbeIds.lo \
-	asn1_id_pbeWithSHAAnd128BitRC4.lo \
-	asn1_id_pbeWithSHAAnd40BitRC4.lo \
-	asn1_id_pbeWithSHAAnd3_KeyTripleDES_CBC.lo \
-	asn1_id_pbeWithSHAAnd2_KeyTripleDES_CBC.lo \
-	asn1_id_pbeWithSHAAnd128BitRC2_CBC.lo \
-	asn1_id_pbewithSHAAnd40BitRC2_CBC.lo \
-	asn1_id_pkcs12_bagtypes.lo asn1_id_pkcs12_keyBag.lo \
-	asn1_id_pkcs12_pkcs8ShroudedKeyBag.lo \
-	asn1_id_pkcs12_certBag.lo asn1_id_pkcs12_crlBag.lo \
-	asn1_id_pkcs12_secretBag.lo asn1_id_pkcs12_safeContentsBag.lo \
-	asn1_PKCS12_MacData.lo asn1_PKCS12_PFX.lo \
-	asn1_PKCS12_AuthenticatedSafe.lo asn1_PKCS12_CertBag.lo \
-	asn1_PKCS12_Attribute.lo asn1_PKCS12_Attributes.lo \
-	asn1_PKCS12_SafeBag.lo asn1_PKCS12_SafeContents.lo \
-	asn1_PKCS12_OctetString.lo asn1_PKCS12_PBEParams.lo
-am__objects_8 =3D asn1_DigestError.lo asn1_DigestInit.lo \
-	asn1_DigestInitReply.lo asn1_DigestREP.lo asn1_DigestREQ.lo \
-	asn1_DigestRepInner.lo asn1_DigestReqInner.lo \
-	asn1_DigestRequest.lo asn1_DigestResponse.lo \
-	asn1_DigestTypes.lo asn1_NTLMInit.lo asn1_NTLMInitReply.lo \
-	asn1_NTLMRequest.lo asn1_NTLMResponse.lo
-am__objects_9 =3D asn1_Kx509Response.lo asn1_Kx509Request.lo
+libasn1_la_DEPENDENCIES =3D libasn1base.la $(am__DEPENDENCIES_1)
+am__objects_1 =3D asn1_rfc2459_asn1.lo
+am__objects_2 =3D asn1_cms_asn1.lo
+am__objects_3 =3D asn1_krb5_asn1.lo
+am__objects_4 =3D asn1_pkinit_asn1.lo
+am__objects_5 =3D asn1_pkcs8_asn1.lo
+am__objects_6 =3D asn1_pkcs9_asn1.lo
+am__objects_7 =3D asn1_pkcs12_asn1.lo
+am__objects_8 =3D asn1_digest_asn1.lo
+am__objects_9 =3D asn1_kx509_asn1.lo
 am__objects_10 =3D $(am__objects_1) $(am__objects_2) $(am__objects_3) \
 	$(am__objects_4) $(am__objects_5) $(am__objects_6) \
-	$(am__objects_7) $(am__objects_8) $(am__objects_9) asn1_err.lo
+	$(am__objects_7) $(am__objects_8) $(am__objects_9)
 nodist_libasn1_la_OBJECTS =3D $(am__objects_10)
-libasn1_la_OBJECTS =3D $(dist_libasn1_la_OBJECTS) \
-	$(nodist_libasn1_la_OBJECTS)
+libasn1_la_OBJECTS =3D $(nodist_libasn1_la_OBJECTS)
 libasn1_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libasn1_la_LDFLAGS) $(LDFLAGS) -o $@
+libasn1base_la_LIBADD =3D
+dist_libasn1base_la_OBJECTS =3D der.lo der_get.lo der_put.lo der_free.lo \
+	der_length.lo der_copy.lo der_cmp.lo der_format.lo extra.lo \
+	template.lo timegm.lo
+nodist_libasn1base_la_OBJECTS =3D asn1_err.lo
+libasn1base_la_OBJECTS =3D $(dist_libasn1base_la_OBJECTS) \
+	$(nodist_libasn1base_la_OBJECTS)
 am__EXEEXT_1 =3D check-der$(EXEEXT) check-gen$(EXEEXT) \
-	check-timegm$(EXEEXT)
-PROGRAMS =3D $(noinst_PROGRAMS)
-am_asn1_compile_OBJECTS =3D gen.$(OBJEXT) gen_copy.$(OBJEXT) \
-	gen_decode.$(OBJEXT) gen_encode.$(OBJEXT) gen_free.$(OBJEXT) \
-	gen_glue.$(OBJEXT) gen_length.$(OBJEXT) gen_seq.$(OBJEXT) \
-	hash.$(OBJEXT) lex.$(OBJEXT) main.$(OBJEXT) parse.$(OBJEXT) \
-	symbol.$(OBJEXT)
+	check-timegm$(EXEEXT) check-ber$(EXEEXT) \
+	check-template$(EXEEXT)
+PROGRAMS =3D $(libexec_heimdal_PROGRAMS) $(noinst_PROGRAMS)
+am_asn1_compile_OBJECTS =3D asn1parse.$(OBJEXT) gen.$(OBJEXT) \
+	gen_copy.$(OBJEXT) gen_decode.$(OBJEXT) gen_encode.$(OBJEXT) \
+	gen_free.$(OBJEXT) gen_glue.$(OBJEXT) gen_length.$(OBJEXT) \
+	gen_seq.$(OBJEXT) gen_template.$(OBJEXT) hash.$(OBJEXT) \
+	lex.$(OBJEXT) main.$(OBJEXT) symbol.$(OBJEXT)
 asn1_compile_OBJECTS =3D $(am_asn1_compile_OBJECTS)
 asn1_compile_DEPENDENCIES =3D $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
 am_asn1_gen_OBJECTS =3D asn1_gen.$(OBJEXT)
 asn1_gen_OBJECTS =3D $(am_asn1_gen_OBJECTS)
-am__DEPENDENCIES_2 =3D libasn1.la $(am__DEPENDENCIES_1)
+am__DEPENDENCIES_2 =3D libasn1base.la $(am__DEPENDENCIES_1)
 asn1_gen_DEPENDENCIES =3D $(am__DEPENDENCIES_2)
 am_asn1_print_OBJECTS =3D asn1_print.$(OBJEXT)
 asn1_print_OBJECTS =3D $(am_asn1_print_OBJECTS)
-asn1_print_DEPENDENCIES =3D $(am__DEPENDENCIES_2)
+asn1_print_DEPENDENCIES =3D $(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1)
+check_ber_SOURCES =3D check-ber.c
+check_ber_OBJECTS =3D check-ber.$(OBJEXT)
+am__DEPENDENCIES_3 =3D libasn1.la $(am__DEPENDENCIES_1)
+check_ber_DEPENDENCIES =3D $(am__DEPENDENCIES_3)
 am_check_der_OBJECTS =3D check-der.$(OBJEXT) check-common.$(OBJEXT)
 check_der_OBJECTS =3D $(am_check_der_OBJECTS)
-check_der_DEPENDENCIES =3D libasn1.la $(am__DEPENDENCIES_1)
+check_der_DEPENDENCIES =3D libasn1base.la $(am__DEPENDENCIES_1)
 dist_check_gen_OBJECTS =3D check-gen.$(OBJEXT) check-common.$(OBJEXT)
-am__objects_11 =3D asn1_TESTAlloc.$(OBJEXT) \
-	asn1_TESTAllocInner.$(OBJEXT) asn1_TESTCONTAINING.$(OBJEXT) \
-	asn1_TESTCONTAININGENCODEDBY.$(OBJEXT) \
-	asn1_TESTCONTAININGENCODEDBY2.$(OBJEXT) \
-	asn1_TESTChoice1.$(OBJEXT) asn1_TESTChoice2.$(OBJEXT) \
-	asn1_TESTDer.$(OBJEXT) asn1_TESTENCODEDBY.$(OBJEXT) \
-	asn1_TESTImplicit.$(OBJEXT) asn1_TESTImplicit2.$(OBJEXT) \
-	asn1_TESTInteger.$(OBJEXT) asn1_TESTInteger2.$(OBJEXT) \
-	asn1_TESTInteger3.$(OBJEXT) asn1_TESTLargeTag.$(OBJEXT) \
-	asn1_TESTSeq.$(OBJEXT) asn1_TESTUSERCONSTRAINED.$(OBJEXT) \
-	asn1_TESTSeqOf.$(OBJEXT) asn1_TESTOSSize1.$(OBJEXT) \
-	asn1_TESTSeqSizeOf1.$(OBJEXT) asn1_TESTSeqSizeOf2.$(OBJEXT) \
-	asn1_TESTSeqSizeOf3.$(OBJEXT) asn1_TESTSeqSizeOf4.$(OBJEXT)
+am__objects_11 =3D asn1_test_asn1.$(OBJEXT)
 nodist_check_gen_OBJECTS =3D $(am__objects_11)
 check_gen_OBJECTS =3D $(dist_check_gen_OBJECTS) \
 	$(nodist_check_gen_OBJECTS)
-check_gen_DEPENDENCIES =3D $(am__DEPENDENCIES_2)
+check_gen_DEPENDENCIES =3D libasn1.la $(am__DEPENDENCIES_1)
+am_check_template_OBJECTS =3D check-template.$(OBJEXT) \
+	check-common.$(OBJEXT)
+nodist_check_template_OBJECTS =3D $(am__objects_11)
+check_template_OBJECTS =3D $(am_check_template_OBJECTS) \
+	$(nodist_check_template_OBJECTS)
+check_template_DEPENDENCIES =3D $(am__DEPENDENCIES_2)
 check_timegm_SOURCES =3D check-timegm.c
 check_timegm_OBJECTS =3D check-timegm.$(OBJEXT)
 check_timegm_DEPENDENCIES =3D $(am__DEPENDENCIES_2)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -383,67 +217,78 @@
 YACCCOMPILE =3D $(YACC) $(YFLAGS) $(AM_YFLAGS)
 LTYACCCOMPILE =3D $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dcompile $(YACC) $(YFLAGS) $(AM_YFLAGS)
-SOURCES =3D $(dist_libasn1_la_SOURCES) $(nodist_libasn1_la_SOURCES) \
-	$(asn1_compile_SOURCES) $(asn1_gen_SOURCES) \
-	$(asn1_print_SOURCES) $(check_der_SOURCES) \
-	$(dist_check_gen_SOURCES) $(nodist_check_gen_SOURCES) \
-	check-timegm.c
-DIST_SOURCES =3D $(dist_libasn1_la_SOURCES) $(asn1_compile_SOURCES) \
-	$(asn1_gen_SOURCES) $(asn1_print_SOURCES) $(check_der_SOURCES) \
-	$(dist_check_gen_SOURCES) check-timegm.c
-dist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-nodist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
+SOURCES =3D $(nodist_libasn1_la_SOURCES) $(dist_libasn1base_la_SOURCES) \
+	$(nodist_libasn1base_la_SOURCES) $(asn1_compile_SOURCES) \
+	$(asn1_gen_SOURCES) $(asn1_print_SOURCES) check-ber.c \
+	$(check_der_SOURCES) $(dist_check_gen_SOURCES) \
+	$(nodist_check_gen_SOURCES) $(check_template_SOURCES) \
+	$(nodist_check_template_SOURCES) check-timegm.c
+DIST_SOURCES =3D $(dist_libasn1base_la_SOURCES) $(asn1_compile_SOURCES) \
+	$(asn1_gen_SOURCES) $(asn1_print_SOURCES) check-ber.c \
+	$(check_der_SOURCES) $(dist_check_gen_SOURCES) \
+	$(check_template_SOURCES) check-timegm.c
 HEADERS =3D $(dist_include_HEADERS) $(nodist_include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -467,10 +312,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -487,6 +333,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -502,31 +350,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -541,10 +403,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -585,475 +449,75 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 lib_LTLIBRARIES =3D libasn1.la
-libasn1_la_LDFLAGS =3D -version-info 8:0:0
+libasn1_la_LDFLAGS =3D -version-info 8:0:0 $(am__append_1)
+noinst_LTLIBRARIES =3D libasn1base.la
 libasn1_la_LIBADD =3D \
+	libasn1base.la \
 	@LIB_com_err@ \
 	$(LIBADD_roken)
=20
 BUILT_SOURCES =3D \
 	$(gen_files_rfc2459:.x=3D.c)	\
 	$(gen_files_cms:.x=3D.c)		\
-	$(gen_files_k5:.x=3D.c)		\
+	$(gen_files_krb5:.x=3D.c)		\
 	$(gen_files_pkinit:.x=3D.c)	\
 	$(gen_files_pkcs8:.x=3D.c)	\
 	$(gen_files_pkcs9:.x=3D.c)	\
 	$(gen_files_pkcs12:.x=3D.c)	\
 	$(gen_files_digest:.x=3D.c)	\
-	$(gen_files_kx509:.x=3D.c)	\
-	asn1_err.h			\
-	asn1_err.c
+	$(gen_files_kx509:.x=3D.c)
=20
-gen_files_k5 =3D \
-	asn1_AD_AND_OR.x				\
-	asn1_AD_IF_RELEVANT.x				\
-	asn1_AD_KDCIssued.x				\
-	asn1_AD_MANDATORY_FOR_KDC.x			\
-	asn1_AD_LoginAlias.x				\
-	asn1_APOptions.x				\
-	asn1_AP_REP.x					\
-	asn1_AP_REQ.x					\
-	asn1_AS_REP.x					\
-	asn1_AS_REQ.x					\
-	asn1_AUTHDATA_TYPE.x				\
-	asn1_Authenticator.x				\
-	asn1_AuthorizationData.x			\
-	asn1_AuthorizationDataElement.x			\
-	asn1_CKSUMTYPE.x				\
-	asn1_ChangePasswdDataMS.x			\
-	asn1_Checksum.x					\
-	asn1_ENCTYPE.x					\
-	asn1_ETYPE_INFO.x				\
-	asn1_ETYPE_INFO2.x				\
-	asn1_ETYPE_INFO2_ENTRY.x			\
-	asn1_ETYPE_INFO_ENTRY.x				\
-	asn1_EncAPRepPart.x				\
-	asn1_EncASRepPart.x				\
-	asn1_EncKDCRepPart.x				\
-	asn1_EncKrbCredPart.x				\
-	asn1_EncKrbPrivPart.x				\
-	asn1_EncTGSRepPart.x				\
-	asn1_EncTicketPart.x				\
-	asn1_EncryptedData.x				\
-	asn1_EncryptionKey.x				\
-	asn1_EtypeList.x				\
-	asn1_HostAddress.x				\
-	asn1_HostAddresses.x				\
-	asn1_KDCOptions.x				\
-	asn1_KDC_REP.x					\
-	asn1_KDC_REQ.x					\
-	asn1_KDC_REQ_BODY.x				\
-	asn1_KRB_CRED.x					\
-	asn1_KRB_ERROR.x				\
-	asn1_KRB_PRIV.x					\
-	asn1_KRB_SAFE.x					\
-	asn1_KRB_SAFE_BODY.x				\
-	asn1_KerberosString.x				\
-	asn1_KerberosTime.x				\
-	asn1_KrbCredInfo.x				\
-	asn1_LR_TYPE.x					\
-	asn1_LastReq.x					\
-	asn1_MESSAGE_TYPE.x				\
-	asn1_METHOD_DATA.x				\
-	asn1_NAME_TYPE.x				\
-	asn1_PADATA_TYPE.x				\
-	asn1_PA_DATA.x					\
-	asn1_PA_ENC_SAM_RESPONSE_ENC.x         		\
-	asn1_PA_ENC_TS_ENC.x				\
-	asn1_PA_PAC_REQUEST.x				\
-	asn1_PA_S4U2Self.x				\
-	asn1_PA_SAM_CHALLENGE_2.x               	\
-	asn1_PA_SAM_CHALLENGE_2_BODY.x 			\
-	asn1_PA_SAM_REDIRECT.x				\
-	asn1_PA_SAM_RESPONSE_2.x			\
-	asn1_PA_SAM_TYPE.x				\
-	asn1_PA_ClientCanonicalized.x			\
-	asn1_PA_ClientCanonicalizedNames.x		\
-	asn1_PA_SvrReferralData.x			\
-	asn1_PROV_SRV_LOCATION.x			\
-	asn1_Principal.x				\
-	asn1_PrincipalName.x				\
-	asn1_Realm.x					\
-	asn1_SAMFlags.x					\
-	asn1_TGS_REP.x					\
-	asn1_TGS_REQ.x					\
-	asn1_TYPED_DATA.x				\
-	asn1_Ticket.x					\
-	asn1_TicketFlags.x				\
-	asn1_TransitedEncoding.x			\
-	asn1_TypedData.x				\
-	asn1_krb5int32.x				\
-	asn1_krb5uint32.x				\
-	asn1_KRB5SignedPathData.x			\
-	asn1_KRB5SignedPathPrincipals.x			\
-	asn1_KRB5SignedPath.x
-
-gen_files_cms =3D \
-	asn1_CMSAttributes.x				\
-	asn1_CMSCBCParameter.x				\
-	asn1_CMSEncryptedData.x				\
-	asn1_CMSIdentifier.x				\
-	asn1_CMSRC2CBCParameter.x			\
-	asn1_CMSVersion.x				\
-	asn1_CertificateList.x				\
-	asn1_CertificateRevocationLists.x		\
-	asn1_CertificateSet.x				\
-	asn1_ContentEncryptionAlgorithmIdentifier.x	\
-	asn1_ContentInfo.x				\
-	asn1_ContentType.x				\
-	asn1_DigestAlgorithmIdentifier.x		\
-	asn1_DigestAlgorithmIdentifiers.x		\
-	asn1_EncapsulatedContentInfo.x			\
-	asn1_EncryptedContent.x				\
-	asn1_EncryptedContentInfo.x			\
-	asn1_EncryptedKey.x				\
-	asn1_EnvelopedData.x				\
-	asn1_IssuerAndSerialNumber.x			\
-	asn1_KeyEncryptionAlgorithmIdentifier.x		\
-	asn1_KeyTransRecipientInfo.x			\
-	asn1_MessageDigest.x				\
-	asn1_OriginatorInfo.x				\
-	asn1_RecipientIdentifier.x			\
-	asn1_RecipientInfo.x				\
-	asn1_RecipientInfos.x				\
-	asn1_SignatureAlgorithmIdentifier.x		\
-	asn1_SignatureValue.x				\
-	asn1_SignedData.x				\
-	asn1_SignerIdentifier.x				\
-	asn1_SignerInfo.x				\
-	asn1_SignerInfos.x				\
-	asn1_id_pkcs7.x					\
-	asn1_id_pkcs7_data.x				\
-	asn1_id_pkcs7_digestedData.x			\
-	asn1_id_pkcs7_encryptedData.x			\
-	asn1_id_pkcs7_envelopedData.x			\
-	asn1_id_pkcs7_signedAndEnvelopedData.x		\
-	asn1_id_pkcs7_signedData.x			\
-	asn1_UnprotectedAttributes.x
-
-gen_files_rfc2459 =3D \
-	asn1_Version.x					\
-	asn1_id_pkcs_1.x				\
-	asn1_id_pkcs1_rsaEncryption.x			\
-	asn1_id_pkcs1_md2WithRSAEncryption.x		\
-	asn1_id_pkcs1_md5WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha1WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha256WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha384WithRSAEncryption.x		\
-	asn1_id_pkcs1_sha512WithRSAEncryption.x		\
-	asn1_id_heim_rsa_pkcs1_x509.x			\
-	asn1_id_pkcs_2.x				\
-	asn1_id_pkcs2_md2.x				\
-	asn1_id_pkcs2_md4.x				\
-	asn1_id_pkcs2_md5.x				\
-	asn1_id_rsa_digestAlgorithm.x			\
-	asn1_id_rsa_digest_md2.x			\
-	asn1_id_rsa_digest_md4.x			\
-	asn1_id_rsa_digest_md5.x			\
-	asn1_id_pkcs_3.x				\
-	asn1_id_pkcs3_rc2_cbc.x				\
-	asn1_id_pkcs3_rc4.x				\
-	asn1_id_pkcs3_des_ede3_cbc.x			\
-	asn1_id_rsadsi_encalg.x				\
-	asn1_id_rsadsi_rc2_cbc.x			\
-	asn1_id_rsadsi_des_ede3_cbc.x			\
-	asn1_id_secsig_sha_1.x				\
-	asn1_id_nistAlgorithm.x				\
-	asn1_id_nist_aes_algs.x				\
-	asn1_id_aes_128_cbc.x				\
-	asn1_id_aes_192_cbc.x				\
-	asn1_id_aes_256_cbc.x				\
-	asn1_id_nist_sha_algs.x				\
-	asn1_id_sha256.x				\
-	asn1_id_sha224.x				\
-	asn1_id_sha384.x				\
-	asn1_id_sha512.x				\
-	asn1_id_dhpublicnumber.x			\
-	asn1_id_x9_57.x					\
-	asn1_id_dsa.x					\
-	asn1_id_dsa_with_sha1.x				\
-	asn1_id_x520_at.x				\
-	asn1_id_at_commonName.x				\
-	asn1_id_at_surname.x				\
-	asn1_id_at_serialNumber.x			\
-	asn1_id_at_countryName.x			\
-	asn1_id_at_localityName.x			\
-	asn1_id_at_streetAddress.x			\
-	asn1_id_at_stateOrProvinceName.x		\
-	asn1_id_at_organizationName.x			\
-	asn1_id_at_organizationalUnitName.x		\
-	asn1_id_at_name.x				\
-	asn1_id_at_givenName.x				\
-	asn1_id_at_initials.x				\
-	asn1_id_at_generationQualifier.x		\
-	asn1_id_at_pseudonym.x				\
-	asn1_id_Userid.x				\
-	asn1_id_domainComponent.x			\
-	asn1_id_x509_ce.x				\
-	asn1_id_uspkicommon_card_id.x			\
-	asn1_id_uspkicommon_piv_interim.x		\
-	asn1_id_netscape.x				\
-	asn1_id_netscape_cert_comment.x			\
-	asn1_id_ms_cert_enroll_domaincontroller.x	\
-	asn1_id_ms_client_authentication.x		\
-	asn1_AlgorithmIdentifier.x			\
-	asn1_AttributeType.x				\
-	asn1_AttributeValue.x				\
-	asn1_TeletexStringx.x				\
-	asn1_DirectoryString.x				\
-	asn1_Attribute.x				\
-	asn1_AttributeTypeAndValue.x			\
-	asn1_AuthorityInfoAccessSyntax.x		\
-	asn1_AccessDescription.x			\
-	asn1_RelativeDistinguishedName.x		\
-	asn1_RDNSequence.x				\
-	asn1_Name.x					\
-	asn1_CertificateSerialNumber.x			\
-	asn1_Time.x					\
-	asn1_Validity.x					\
-	asn1_UniqueIdentifier.x				\
-	asn1_SubjectPublicKeyInfo.x			\
-	asn1_Extension.x				\
-	asn1_Extensions.x				\
-	asn1_TBSCertificate.x				\
-	asn1_Certificate.x				\
-	asn1_Certificates.x				\
-	asn1_ValidationParms.x				\
-	asn1_DomainParameters.x				\
-	asn1_DHPublicKey.x				\
-	asn1_OtherName.x				\
-	asn1_GeneralName.x				\
-	asn1_GeneralNames.x				\
-	asn1_id_x509_ce_keyUsage.x			\
-	asn1_KeyUsage.x					\
-	asn1_id_x509_ce_authorityKeyIdentifier.x	\
-	asn1_KeyIdentifier.x				\
-	asn1_AuthorityKeyIdentifier.x			\
-	asn1_id_x509_ce_subjectKeyIdentifier.x		\
-	asn1_SubjectKeyIdentifier.x			\
-	asn1_id_x509_ce_basicConstraints.x		\
-	asn1_BasicConstraints.x				\
-	asn1_id_x509_ce_nameConstraints.x		\
-	asn1_BaseDistance.x				\
-	asn1_GeneralSubtree.x				\
-	asn1_GeneralSubtrees.x				\
-	asn1_NameConstraints.x				\
-	asn1_id_x509_ce_privateKeyUsagePeriod.x		\
-	asn1_id_x509_ce_certificatePolicies.x		\
-	asn1_id_x509_ce_policyMappings.x		\
-	asn1_id_x509_ce_subjectAltName.x		\
-	asn1_id_x509_ce_issuerAltName.x			\
-	asn1_id_x509_ce_subjectDirectoryAttributes.x	\
-	asn1_id_x509_ce_policyConstraints.x		\
-	asn1_id_x509_ce_extKeyUsage.x			\
-	asn1_ExtKeyUsage.x				\
-	asn1_id_x509_ce_cRLDistributionPoints.x		\
-	asn1_id_x509_ce_deltaCRLIndicator.x		\
-	asn1_id_x509_ce_issuingDistributionPoint.x	\
-	asn1_id_x509_ce_holdInstructionCode.x		\
-	asn1_id_x509_ce_invalidityDate.x		\
-	asn1_id_x509_ce_certificateIssuer.x		\
-	asn1_id_x509_ce_inhibitAnyPolicy.x		\
-	asn1_DistributionPointReasonFlags.x		\
-	asn1_DistributionPointName.x			\
-	asn1_DistributionPoint.x			\
-	asn1_CRLDistributionPoints.x			\
-	asn1_DSASigValue.x				\
-	asn1_DSAPublicKey.x				\
-	asn1_DSAParams.x				\
-	asn1_RSAPublicKey.x				\
-	asn1_RSAPrivateKey.x				\
-	asn1_DigestInfo.x				\
-	asn1_TBSCRLCertList.x				\
-	asn1_CRLCertificateList.x			\
-	asn1_id_x509_ce_cRLNumber.x			\
-	asn1_id_x509_ce_freshestCRL.x			\
-	asn1_id_x509_ce_cRLReason.x			\
-	asn1_CRLReason.x				\
-	asn1_PKIXXmppAddr.x				\
-	asn1_id_pkix.x					\
-	asn1_id_pkix_on.x				\
-	asn1_id_pkix_on_dnsSRV.x			\
-	asn1_id_pkix_on_xmppAddr.x			\
-	asn1_id_pkix_kp.x				\
-	asn1_id_pkix_kp_serverAuth.x			\
-	asn1_id_pkix_kp_clientAuth.x			\
-	asn1_id_pkix_kp_emailProtection.x		\
-	asn1_id_pkix_kp_timeStamping.x			\
-	asn1_id_pkix_kp_OCSPSigning.x			\
-	asn1_id_pkix_pe.x				\
-	asn1_id_pkix_pe_authorityInfoAccess.x		\
-	asn1_id_pkix_pe_proxyCertInfo.x			\
-	asn1_id_pkix_ppl.x				\
-	asn1_id_pkix_ppl_anyLanguage.x			\
-	asn1_id_pkix_ppl_inheritAll.x			\
-	asn1_id_pkix_ppl_independent.x			\
-	asn1_ProxyPolicy.x				\
-	asn1_ProxyCertInfo.x=20
-
-gen_files_pkinit =3D \
-	asn1_id_pkinit.x				\
-	asn1_id_pkauthdata.x				\
-	asn1_id_pkdhkeydata.x				\
-	asn1_id_pkrkeydata.x				\
-	asn1_id_pkekuoid.x				\
-	asn1_id_pkkdcekuoid.x				\
-	asn1_id_pkinit_san.x				\
-	asn1_id_pkinit_ms_eku.x				\
-	asn1_id_pkinit_ms_san.x				\
-	asn1_MS_UPN_SAN.x				\
-	asn1_DHNonce.x					\
-	asn1_KDFAlgorithmId.x				\
-	asn1_TrustedCA.x				\
-	asn1_ExternalPrincipalIdentifier.x		\
-	asn1_ExternalPrincipalIdentifiers.x		\
-	asn1_PA_PK_AS_REQ.x				\
-	asn1_PKAuthenticator.x				\
-	asn1_AuthPack.x					\
-	asn1_TD_TRUSTED_CERTIFIERS.x			\
-	asn1_TD_INVALID_CERTIFICATES.x			\
-	asn1_KRB5PrincipalName.x			\
-	asn1_AD_INITIAL_VERIFIED_CAS.x			\
-	asn1_DHRepInfo.x				\
-	asn1_PA_PK_AS_REP.x				\
-	asn1_KDCDHKeyInfo.x				\
-	asn1_ReplyKeyPack.x				\
-	asn1_TD_DH_PARAMETERS.x				\
-	asn1_PKAuthenticator_Win2k.x			\
-	asn1_AuthPack_Win2k.x				\
-	asn1_TrustedCA_Win2k.x				\
-	asn1_PA_PK_AS_REQ_Win2k.x			\
-	asn1_PA_PK_AS_REP_Win2k.x			\
-	asn1_KDCDHKeyInfo_Win2k.x			\
-	asn1_ReplyKeyPack_Win2k.x			\
-	asn1_PkinitSuppPubInfo.x=20
-
-gen_files_pkcs12 =3D \
-	asn1_id_pkcs_12.x				\
-	asn1_id_pkcs_12PbeIds.x				\
-	asn1_id_pbeWithSHAAnd128BitRC4.x		\
-	asn1_id_pbeWithSHAAnd40BitRC4.x			\
-	asn1_id_pbeWithSHAAnd3_KeyTripleDES_CBC.x	\
-	asn1_id_pbeWithSHAAnd2_KeyTripleDES_CBC.x	\
-	asn1_id_pbeWithSHAAnd128BitRC2_CBC.x		\
-	asn1_id_pbewithSHAAnd40BitRC2_CBC.x		\
-	asn1_id_pkcs12_bagtypes.x			\
-	asn1_id_pkcs12_keyBag.x				\
-	asn1_id_pkcs12_pkcs8ShroudedKeyBag.x		\
-	asn1_id_pkcs12_certBag.x			\
-	asn1_id_pkcs12_crlBag.x				\
-	asn1_id_pkcs12_secretBag.x			\
-	asn1_id_pkcs12_safeContentsBag.x		\
-	asn1_PKCS12_MacData.x				\
-	asn1_PKCS12_PFX.x				\
-	asn1_PKCS12_AuthenticatedSafe.x			\
-	asn1_PKCS12_CertBag.x				\
-	asn1_PKCS12_Attribute.x				\
-	asn1_PKCS12_Attributes.x			\
-	asn1_PKCS12_SafeBag.x				\
-	asn1_PKCS12_SafeContents.x			\
-	asn1_PKCS12_OctetString.x			\
-	asn1_PKCS12_PBEParams.x
-
-gen_files_pkcs8 =3D \
-	asn1_PKCS8PrivateKeyAlgorithmIdentifier.x	\
-	asn1_PKCS8PrivateKey.x				\
-	asn1_PKCS8PrivateKeyInfo.x			\
-	asn1_PKCS8Attributes.x				\
-	asn1_PKCS8EncryptedPrivateKeyInfo.x		\
-	asn1_PKCS8EncryptedData.x
-
-gen_files_pkcs9 =3D \
-	asn1_id_pkcs_9.x				\
-	asn1_id_pkcs9_contentType.x			\
-	asn1_id_pkcs9_emailAddress.x			\
-	asn1_id_pkcs9_messageDigest.x			\
-	asn1_id_pkcs9_signingTime.x			\
-	asn1_id_pkcs9_countersignature.x		\
-	asn1_id_pkcs_9_at_friendlyName.x		\
-	asn1_id_pkcs_9_at_localKeyId.x			\
-	asn1_id_pkcs_9_at_certTypes.x			\
-	asn1_id_pkcs_9_at_certTypes_x509.x		\
-	asn1_PKCS9_BMPString.x				\
-	asn1_PKCS9_friendlyName.x
-
-gen_files_test =3D \
-	asn1_TESTAlloc.x				\
-	asn1_TESTAllocInner.x				\
-	asn1_TESTCONTAINING.x				\
-	asn1_TESTCONTAININGENCODEDBY.x			\
-	asn1_TESTCONTAININGENCODEDBY2.x			\
-	asn1_TESTChoice1.x				\
-	asn1_TESTChoice2.x				\
-	asn1_TESTDer.x					\
-	asn1_TESTENCODEDBY.x				\
-	asn1_TESTImplicit.x				\
-	asn1_TESTImplicit2.x				\
-	asn1_TESTInteger.x				\
-	asn1_TESTInteger2.x				\
-	asn1_TESTInteger3.x				\
-	asn1_TESTLargeTag.x				\
-	asn1_TESTSeq.x					\
-	asn1_TESTUSERCONSTRAINED.x			\
-	asn1_TESTSeqOf.x				\
-	asn1_TESTOSSize1.x				\
-	asn1_TESTSeqSizeOf1.x				\
-	asn1_TESTSeqSizeOf2.x				\
-	asn1_TESTSeqSizeOf3.x				\
-	asn1_TESTSeqSizeOf4.x
-
-gen_files_digest =3D \
-	asn1_DigestError.x				\
-	asn1_DigestInit.x				\
-	asn1_DigestInitReply.x				\
-	asn1_DigestREP.x				\
-	asn1_DigestREQ.x				\
-	asn1_DigestRepInner.x				\
-	asn1_DigestReqInner.x				\
-	asn1_DigestRequest.x				\
-	asn1_DigestResponse.x				\
-	asn1_DigestTypes.x				\
-	asn1_NTLMInit.x					\
-	asn1_NTLMInitReply.x				\
-	asn1_NTLMRequest.x				\
-	asn1_NTLMResponse.x
-
-gen_files_kx509 =3D \
-	asn1_Kx509Response.x				\
-	asn1_Kx509Request.x
-
+gen_files_krb5 =3D asn1_krb5_asn1.x
+gen_files_cms =3D asn1_cms_asn1.x
+gen_files_rfc2459 =3D asn1_rfc2459_asn1.x
+gen_files_pkinit =3D asn1_pkinit_asn1.x
+gen_files_pkcs12 =3D asn1_pkcs12_asn1.x
+gen_files_pkcs8 =3D asn1_pkcs8_asn1.x
+gen_files_pkcs9 =3D asn1_pkcs9_asn1.x
+gen_files_test =3D asn1_test_asn1.x
+gen_files_digest =3D asn1_digest_asn1.x
+gen_files_kx509 =3D asn1_kx509_asn1.x
 asn1_gen_SOURCES =3D asn1_gen.c
 asn1_print_SOURCES =3D asn1_print.c
 check_der_SOURCES =3D check-der.c check-common.c check-common.h
+check_template_SOURCES =3D check-template.c check-common.c check-common.h
+nodist_check_template_SOURCES =3D $(gen_files_test:.x=3D.c)
 dist_check_gen_SOURCES =3D check-gen.c check-common.c check-common.h
 nodist_check_gen_SOURCES =3D $(gen_files_test:.x=3D.c)
+build_HEADERZ =3D asn1-template.h
 asn1_compile_SOURCES =3D \
-	asn1-common.h				\
 	asn1_queue.h				\
+	asn1parse.y				\
 	der.h					\
 	gen.c					\
 	gen_copy.c				\
@@ -1064,17 +528,17 @@
 	gen_length.c				\
 	gen_locl.h				\
 	gen_seq.c				\
+	gen_template.c				\
 	hash.c					\
 	hash.h					\
 	lex.l					\
 	lex.h					\
 	main.c					\
-	parse.y					\
+	asn1-template.h				\
 	symbol.c				\
 	symbol.h
=20
-dist_libasn1_la_SOURCES =3D \
-	der-protos.h 				\
+dist_libasn1base_la_SOURCES =3D \
 	der_locl.h 				\
 	der.c					\
 	der.h					\
@@ -1087,25 +551,35 @@
 	der_format.c				\
 	heim_asn1.h				\
 	extra.c					\
+	template.c				\
 	timegm.c
=20
+nodist_libasn1base_la_SOURCES =3D \
+	asn1_err.h			\
+	asn1_err.c
+
 nodist_libasn1_la_SOURCES =3D $(BUILT_SOURCES)
 asn1_compile_LDADD =3D \
 	$(LIB_roken) $(LEXLIB)
=20
 check_der_LDADD =3D \
+	libasn1base.la \
+	$(LIB_roken)
+
+check_template_LDADD =3D $(check_der_LDADD)
+asn1_print_LDADD =3D $(check_der_LDADD) $(LIB_com_err)
+asn1_gen_LDADD =3D $(check_der_LDADD)
+check_timegm_LDADD =3D $(check_der_LDADD)
+check_gen_LDADD =3D \
 	libasn1.la \
 	$(LIB_roken)
=20
-check_gen_LDADD =3D $(check_der_LDADD)
-asn1_print_LDADD =3D $(check_der_LDADD)
-asn1_gen_LDADD =3D $(check_der_LDADD)
-check_timegm_LDADD =3D $(check_der_LDADD)
+check_ber_LDADD =3D $(check_gen_LDADD)
 CLEANFILES =3D \
 	$(BUILT_SOURCES) \
 	$(gen_files_rfc2459) \
 	$(gen_files_cms) \
-	$(gen_files_k5) \
+	$(gen_files_krb5) \
 	$(gen_files_pkinit) \
 	$(gen_files_pkcs8) \
 	$(gen_files_pkcs9) \
@@ -1113,54 +587,66 @@
 	$(gen_files_digest) \
 	$(gen_files_kx509) \
 	$(gen_files_test) $(nodist_check_gen_SOURCES) \
-	rfc2459_asn1_files rfc2459_asn1.h \
-	cms_asn1_files cms_asn1.h \
-	krb5_asn1_files krb5_asn1.h \
-	pkinit_asn1_files pkinit_asn1.h \
-	pkcs8_asn1_files pkcs8_asn1.h \
-	pkcs9_asn1_files pkcs9_asn1.h \
-	pkcs12_asn1_files pkcs12_asn1.h \
-	digest_asn1_files digest_asn1.h \
-	kx509_asn1_files kx509_asn1.h \
-	test_asn1_files test_asn1.h
+	asn1_err.c asn1_err.h \
+	rfc2459_asn1_files rfc2459_asn1*.h* \
+	cms_asn1_files cms_asn1*.h* \
+	krb5_asn1_files krb5_asn1*.h* \
+	pkinit_asn1_files pkinit_asn1*.h* \
+	pkcs8_asn1_files pkcs8_asn1*.h* \
+	pkcs9_asn1_files pkcs9_asn1*.h* \
+	pkcs12_asn1_files pkcs12_asn1*.h* \
+	digest_asn1_files digest_asn1*.h* \
+	kx509_asn1_files kx509_asn1*.h* \
+	test_asn1_files test_asn1*.h*
=20
-dist_include_HEADERS =3D der.h heim_asn1.h der-protos.h
+dist_include_HEADERS =3D der.h heim_asn1.h der-protos.h der-private.h \
+	asn1-common.h
 nodist_include_HEADERS =3D asn1_err.h krb5_asn1.h pkinit_asn1.h \
 	cms_asn1.h rfc2459_asn1.h pkcs8_asn1.h pkcs9_asn1.h \
 	pkcs12_asn1.h digest_asn1.h kx509_asn1.h
+priv_headers =3D krb5_asn1-priv.h pkinit_asn1-priv.h cms_asn1-priv.h \
+	rfc2459_asn1-priv.h pkcs8_asn1-priv.h pkcs9_asn1-priv.h \
+	pkcs12_asn1-priv.h digest_asn1-priv.h kx509_asn1-priv.h \
+	test_asn1.h test_asn1-priv.h
 EXTRA_DIST =3D \
+	NTMakefile	\
+	asn1_compile-version.rc \
+	libasn1-exports.def \
+	cms.asn1	\
+	cms.opt		\
 	asn1_err.et	\
 	canthandle.asn1	\
-	CMS.asn1	\
 	digest.asn1	\
-	k5.asn1		\
+	krb5.asn1	\
+	krb5.opt	\
 	kx509.asn1	\
-	test.asn1	\
-	setchgpw2.asn1	\
 	pkcs12.asn1	\
 	pkcs8.asn1	\
 	pkcs9.asn1	\
 	pkinit.asn1	\
 	rfc2459.asn1	\
-	test.gen
+	setchgpw2.asn1	\
+	test.asn1	\
+	test.gen	\
+	version-script.map
=20
 all: $(BUILT_SOURCES)
 	$(MAKE) $(AM_MAKEFLAGS) all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .l .lo .o .=
obj .y
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .l .lo =
.o .obj .y
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/asn1/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/asn1/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/asn1/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/asn1/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -1178,23 +664,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -1205,22 +696,80 @@
 	  echo "rm -f \"$${dir}/so_locations\""; \
 	  rm -f "$${dir}/so_locations"; \
 	done
+
+clean-noinstLTLIBRARIES:
+	-test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+	@list=3D'$(noinst_LTLIBRARIES)'; for p in $$list; do \
+	  dir=3D"`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+	  test "$$dir" !=3D "$$p" || dir=3D.; \
+	  echo "rm -f \"$${dir}/so_locations\""; \
+	  rm -f "$${dir}/so_locations"; \
+	done
 libasn1.la: $(libasn1_la_OBJECTS) $(libasn1_la_DEPENDENCIES)=20
 	$(libasn1_la_LINK) -rpath $(libdir) $(libasn1_la_OBJECTS) $(libasn1_la_LI=
BADD) $(LIBS)
+libasn1base.la: $(libasn1base_la_OBJECTS) $(libasn1base_la_DEPENDENCIES)=20
+	$(LINK)  $(libasn1base_la_OBJECTS) $(libasn1base_la_LIBADD) $(LIBS)
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
+install-libexec_heimdalPROGRAMS: $(libexec_heimdal_PROGRAMS)
+	@$(NORMAL_INSTALL)
+	test -z "$(libexec_heimdaldir)" || $(MKDIR_P) "$(DESTDIR)$(libexec_heimda=
ldir)"
+	@list=3D'$(libexec_heimdal_PROGRAMS)'; test -n "$(libexec_heimdaldir)" ||=
 list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexec_hei=
mdaldir)$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexec_heimdaldir=
)$$dir" || exit $$?; \
+	    } \
+	; done
+
+uninstall-libexec_heimdalPROGRAMS:
+	@$(NORMAL_UNINSTALL)
+	@list=3D'$(libexec_heimdal_PROGRAMS)'; test -n "$(libexec_heimdaldir)" ||=
 list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexec_heimdaldir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexec_heimdaldir)" && rm -f $$files
+
+clean-libexec_heimdalPROGRAMS:
+	@list=3D'$(libexec_heimdal_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 asn1_compile$(EXEEXT): $(asn1_compile_OBJECTS) $(asn1_compile_DEPENDENCIES=
)=20
 	@rm -f asn1_compile$(EXEEXT)
 	$(LINK) $(asn1_compile_OBJECTS) $(asn1_compile_LDADD) $(LIBS)
@@ -1230,12 +779,18 @@
 asn1_print$(EXEEXT): $(asn1_print_OBJECTS) $(asn1_print_DEPENDENCIES)=20
 	@rm -f asn1_print$(EXEEXT)
 	$(LINK) $(asn1_print_OBJECTS) $(asn1_print_LDADD) $(LIBS)
+check-ber$(EXEEXT): $(check_ber_OBJECTS) $(check_ber_DEPENDENCIES)=20
+	@rm -f check-ber$(EXEEXT)
+	$(LINK) $(check_ber_OBJECTS) $(check_ber_LDADD) $(LIBS)
 check-der$(EXEEXT): $(check_der_OBJECTS) $(check_der_DEPENDENCIES)=20
 	@rm -f check-der$(EXEEXT)
 	$(LINK) $(check_der_OBJECTS) $(check_der_LDADD) $(LIBS)
 check-gen$(EXEEXT): $(check_gen_OBJECTS) $(check_gen_DEPENDENCIES)=20
 	@rm -f check-gen$(EXEEXT)
 	$(LINK) $(check_gen_OBJECTS) $(check_gen_LDADD) $(LIBS)
+check-template$(EXEEXT): $(check_template_OBJECTS) $(check_template_DEPEND=
ENCIES)=20
+	@rm -f check-template$(EXEEXT)
+	$(LINK) $(check_template_OBJECTS) $(check_template_LDADD) $(LIBS)
 check-timegm$(EXEEXT): $(check_timegm_OBJECTS) $(check_timegm_DEPENDENCIES=
)=20
 	@rm -f check-timegm$(EXEEXT)
 	$(LINK) $(check_timegm_OBJECTS) $(check_timegm_LDADD) $(LIBS)
@@ -1246,14 +801,71 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_cms_asn1.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_digest_asn1.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_err.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_gen.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_krb5_asn1.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_kx509_asn1.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_pkcs12_asn1.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_pkcs8_asn1.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_pkcs9_asn1.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_pkinit_asn1.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_print.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_rfc2459_asn1.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_test_asn1.Po at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1parse.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/check-ber.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/check-common.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/check-der.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/check-gen.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/check-template.Po at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/check-timegm.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der_cmp.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der_copy.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der_format.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der_free.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der_get.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der_length.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/der_put.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/extra.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_copy.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_decode.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_encode.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_free.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_glue.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_length.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_seq.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gen_template.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hash.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/lex.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/main.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/symbol.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/template.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/timegm.Plo at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 .l.c:
 	$(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMP=
ILE)
@@ -1269,90 +881,101 @@
 install-dist_includeHEADERS: $(dist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(dist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)=
/$$f'"; \
-	  $(dist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-dist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-nodist_includeHEADERS: $(nodist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedi=
r)/$$f'"; \
-	  $(nodist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"=
; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -1361,49 +984,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -1414,11 +1051,15 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
@@ -1438,13 +1079,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -1458,7 +1103,7 @@
 	$(MAKE) $(AM_MAKEFLAGS) check-am
 all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) all-local
 installdirs:
-	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(i=
ncludedir)"; do \
+	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(libexec_heimdaldir)" "$(DES=
TDIR)$(includedir)" "$(DESTDIR)$(includedir)"; do \
 	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
 	done
 install: $(BUILT_SOURCES)
@@ -1483,20 +1128,23 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
 	@echo "it deletes files that may require special tools to rebuild."
+	-rm -f asn1parse.c
+	-rm -f asn1parse.h
 	-rm -f lex.c
-	-rm -f parse.c
-	-rm -f parse.h
 	-test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES)
 clean: clean-am
=20
 clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \
-	clean-libtool clean-noinstPROGRAMS mostlyclean-am
+	clean-libexec_heimdalPROGRAMS clean-libtool \
+	clean-noinstLTLIBRARIES clean-noinstPROGRAMS mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -1507,6 +1155,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -1515,26 +1165,36 @@
 	install-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
-
 install-dvi: install-dvi-am
=20
-install-exec-am: install-libLTLIBRARIES
+install-dvi-am:
+
+install-exec-am: install-libLTLIBRARIES \
+	install-libexec_heimdalPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -1552,23 +1212,25 @@
 ps-am:
=20
 uninstall-am: uninstall-dist_includeHEADERS uninstall-libLTLIBRARIES \
+	uninstall-libexec_heimdalPROGRAMS \
 	uninstall-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: all check check-am install install-am install-data-am \
+	install-exec-am install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
 	check-local clean clean-checkPROGRAMS clean-generic \
-	clean-libLTLIBRARIES clean-libtool clean-noinstPROGRAMS ctags \
-	dist-hook distclean distclean-compile distclean-generic \
+	clean-libLTLIBRARIES clean-libexec_heimdalPROGRAMS \
+	clean-libtool clean-noinstLTLIBRARIES clean-noinstPROGRAMS \
+	ctags dist-hook distclean distclean-compile distclean-generic \
 	distclean-libtool distclean-tags distdir dvi dvi-am html \
 	html-am info info-am install install-am install-data \
 	install-data-am install-data-hook install-dist_includeHEADERS \
 	install-dvi install-dvi-am install-exec install-exec-am \
 	install-exec-hook install-html install-html-am install-info \
-	install-info-am install-libLTLIBRARIES install-man \
+	install-info-am install-libLTLIBRARIES \
+	install-libexec_heimdalPROGRAMS install-man \
 	install-nodist_includeHEADERS install-pdf install-pdf-am \
 	install-ps install-ps-am install-strip installcheck \
 	installcheck-am installdirs maintainer-clean \
@@ -1576,6 +1238,7 @@
 	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
 	tags uninstall uninstall-am uninstall-dist_includeHEADERS \
 	uninstall-hook uninstall-libLTLIBRARIES \
+	uninstall-libexec_heimdalPROGRAMS \
 	uninstall-nodist_includeHEADERS
=20
=20
@@ -1647,6 +1310,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1732,7 +1398,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1746,56 +1412,62 @@
 	  fi ; \
 	done
=20
-$(asn1_compile_OBJECTS): parse.h parse.c $(srcdir)/der-protos.h
-$(libasn1_la_OBJECTS): krb5_asn1.h asn1_err.h $(srcdir)/der-protos.h
+$(asn1_compile_OBJECTS): asn1parse.h asn1parse.c $(srcdir)/der-protos.h $(=
srcdir)/der-private.h
+$(libasn1_la_OBJECTS): $(nodist_include_HEADERS) $(priv_headers) asn1_err.=
h $(srcdir)/der-protos.h $(srcdir)/der-private.h
+$(libasn1base_la_OBJECTS): asn1_err.h $(srcdir)/der-protos.h $(srcdir)/der=
-private.h
 $(check_gen_OBJECTS): test_asn1.h
+$(check_template_OBJECTS): test_asn1_files
 $(asn1_print_OBJECTS): krb5_asn1.h
=20
-parse.h: parse.c
+asn1parse.h: asn1parse.c
=20
-$(gen_files_k5) krb5_asn1.h: krb5_asn1_files
-$(gen_files_pkinit) pkinit_asn1.h: pkinit_asn1_files
-$(gen_files_pkcs8) pkcs8_asn1.h: pkcs8_asn1_files
-$(gen_files_pkcs9) pkcs9_asn1.h: pkcs9_asn1_files
-$(gen_files_pkcs12) pkcs12_asn1.h: pkcs12_asn1_files
-$(gen_files_digest) digest_asn1.h: digest_asn1_files
-$(gen_files_kx509) kx509_asn1.h: kx509_asn1_files
-$(gen_files_rfc2459) rfc2459_asn1.h: rfc2459_asn1_files
-$(gen_files_cms) cms_asn1.h: cms_asn1_files
-$(gen_files_test) test_asn1.h: test_asn1_files
+$(gen_files_krb5) krb5_asn1.hx krb5_asn1-priv.hx: krb5_asn1_files
+$(gen_files_pkinit) pkinit_asn1.hx pkinit_asn1-priv.hx: pkinit_asn1_files
+$(gen_files_pkcs8) pkcs8_asn1.hx pkcs8_asn1-priv.hx: pkcs8_asn1_files
+$(gen_files_pkcs9) pkcs9_asn1.hx pkcs9_asn1-priv.hx: pkcs9_asn1_files
+$(gen_files_pkcs12) pkcs12_asn1.hx pkcs12_asn1-priv.hx: pkcs12_asn1_files
+$(gen_files_digest) digest_asn1.hx digest_asn1-priv.hx: digest_asn1_files
+$(gen_files_kx509) kx509_asn1.hx kx509_asn1-priv.hx: kx509_asn1_files
+$(gen_files_rfc2459) rfc2459_asn1.hx rfc2459_asn1-priv.hx: rfc2459_asn1_fi=
les
+$(gen_files_cms) cms_asn1.hx cms_asn1-priv.hx: cms_asn1_files
+$(gen_files_test) test_asn1.hx test_asn1-priv.hx: test_asn1_files
=20
 rfc2459_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/rfc2459.asn1
-	./asn1_compile$(EXEEXT) --preserve-binary=3DTBSCertificate --preserve-bin=
ary=3DTBSCRLCertList --preserve-binary=3DName --sequence=3DGeneralNames --s=
equence=3DExtensions --sequence=3DCRLDistributionPoints $(srcdir)/rfc2459.a=
sn1 rfc2459_asn1 || (rm -f rfc2459_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file --preserve-binary=3DTBSCertificate --pres=
erve-binary=3DTBSCRLCertList --preserve-binary=3DName --sequence=3DGeneralN=
ames --sequence=3DExtensions --sequence=3DCRLDistributionPoints $(srcdir)/r=
fc2459.asn1 rfc2459_asn1 || (rm -f rfc2459_asn1_files ; exit 1)
=20
-cms_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/CMS.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/CMS.asn1 cms_asn1 || (rm -f cms_asn1_fi=
les ; exit 1)
+cms_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/cms.asn1 $(srcdir)/cms.opt
+	$(ASN1_COMPILE) --one-code-file --option-file=3D$(srcdir)/cms.opt $(srcdi=
r)/cms.asn1 cms_asn1 || (rm -f cms_asn1_files ; exit 1)
=20
-krb5_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/k5.asn1
-	./asn1_compile$(EXEEXT) --encode-rfc1510-bit-string --sequence=3DKRB5Sign=
edPathPrincipals --sequence=3DAuthorizationData --sequence=3DMETHOD-DATA --=
sequence=3DETYPE-INFO --sequence=3DETYPE-INFO2 $(srcdir)/k5.asn1 krb5_asn1 =
|| (rm -f krb5_asn1_files ; exit 1)
+krb5_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/krb5.asn1 $(srcdir)/krb5.=
opt
+	$(ASN1_COMPILE) --one-code-file --option-file=3D$(srcdir)/krb5.opt $(srcd=
ir)/krb5.asn1 krb5_asn1 || (rm -f krb5_asn1_files ; exit 1)
=20
 pkinit_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkinit.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkinit.asn1 pkinit_asn1 || (rm -f pkini=
t_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkinit.asn1 pkinit_asn1 || (rm =
-f pkinit_asn1_files ; exit 1)
=20
 pkcs8_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs8.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkcs8.asn1 pkcs8_asn1 || (rm -f pkcs8_a=
sn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkcs8.asn1 pkcs8_asn1 || (rm -f=
 pkcs8_asn1_files ; exit 1)
=20
 pkcs9_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs9.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkcs9.asn1 pkcs9_asn1 || (rm -f pkcs9_a=
sn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkcs9.asn1 pkcs9_asn1 || (rm -f=
 pkcs9_asn1_files ; exit 1)
=20
 pkcs12_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/pkcs12.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/pkcs12.asn1 pkcs12_asn1 || (rm -f pkcs1=
2_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/pkcs12.asn1 pkcs12_asn1 || (rm =
-f pkcs12_asn1_files ; exit 1)
=20
 digest_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/digest.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/digest.asn1 digest_asn1 || (rm -f diges=
t_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/digest.asn1 digest_asn1 || (rm =
-f digest_asn1_files ; exit 1)
=20
 kx509_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/kx509.asn1
-	./asn1_compile$(EXEEXT) $(srcdir)/kx509.asn1 kx509_asn1 || (rm -f kx509_a=
sn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file $(srcdir)/kx509.asn1 kx509_asn1 || (rm -f=
 kx509_asn1_files ; exit 1)
=20
 test_asn1_files: asn1_compile$(EXEEXT) $(srcdir)/test.asn1
-	./asn1_compile$(EXEEXT) --sequence=3DTESTSeqOf $(srcdir)/test.asn1 test_a=
sn1 || (rm -f test_asn1_files ; exit 1)
+	$(ASN1_COMPILE) --one-code-file --sequence=3DTESTSeqOf $(srcdir)/test.asn=
1 test_asn1 || (rm -f test_asn1_files ; exit 1)
=20
 $(srcdir)/der-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o der-protos.h=
 $(dist_libasn1_la_SOURCES) || rm -f der-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o der-protos.h=
 $(dist_libasn1base_la_SOURCES) || rm -f der-protos.h
+
+$(srcdir)/der-private.h:
+	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p der-private.=
h $(dist_libasn1base_la_SOURCES) || rm -f der-private.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/asn1-comm=
on.h
--- a/head/crypto/heimdal/lib/asn1/asn1-common.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/asn1/asn1-common.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,7 +1,8 @@
-/* $Id: asn1-common.h 22429 2008-01-13 10:25:50Z lha $ */
+/* $Id$ */
=20
 #include <stddef.h>
 #include <time.h>
+#include <krb5-types.h>
=20
 #ifndef __asn1_common_definitions__
 #define __asn1_common_definitions__
@@ -19,8 +20,8 @@
=20
 typedef char *heim_general_string;
 typedef char *heim_utf8_string;
-typedef char *heim_printable_string;
-typedef char *heim_ia5_string;
+typedef struct heim_octet_string heim_printable_string;
+typedef struct heim_octet_string heim_ia5_string;
=20
 typedef struct heim_bmp_string {
     size_t length;
@@ -63,4 +64,16 @@
     }                                                          \
   } while (0)
=20
+#ifdef _WIN32
+#ifndef ASN1_LIB
+#define ASN1EXP  __declspec(dllimport)
+#else
+#define ASN1EXP
 #endif
+#define ASN1CALL __stdcall
+#else
+#define ASN1EXP
+#define ASN1CALL
+#endif
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/asn1_err.=
et
--- a/head/crypto/heimdal/lib/asn1/asn1_err.et	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/asn1_err.et	Tue Apr 17 11:51:51 2012 +03=
00
@@ -3,7 +3,7 @@
 #
 # This might look like a com_err file, but is not
 #
-id "$Id: asn1_err.et 21394 2007-07-02 10:14:43Z lha $"
+id "$Id$"
=20
 error_table asn1
 prefix ASN1
@@ -22,4 +22,8 @@
 error_code MIN_CONSTRAINT,	"ASN.1 too few elements"
 error_code MAX_CONSTRAINT,	"ASN.1 too many elements"
 error_code EXACT_CONSTRAINT,	"ASN.1 wrong number of elements"
+error_code INDEF_OVERRUN,   	"ASN.1 BER indefinte encoding overrun"
+error_code INDEF_UNDERRUN,   	"ASN.1 BER indefinte encoding underun"
+error_code GOT_BER,		"ASN.1 got BER encoded when expected DER"
+error_code INDEF_EXTRA_DATA,	"ASN.1 EoC tag contained data"
 end
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/asn1_gen.c
--- a/head/crypto/heimdal/lib/asn1/asn1_gen.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/asn1_gen.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
@@ -40,13 +40,13 @@
 #include <hex.h>
 #include <err.h>
=20
-RCSID("$Id: asn1_gen.c 16666 2006-01-30 15:06:03Z lha $");
+RCSID("$Id$");
=20
 static int
 doit(const char *fn)
 {
     char buf[2048];
-    char *fnout;
+    char *fnout =3D NULL;
     const char *bname;
     unsigned long line =3D 0;
     FILE *f, *fout;
@@ -62,8 +62,7 @@
     else
 	bname =3D fn;
=20
-    asprintf(&fnout, "%s.out", bname);
-    if (fnout =3D=3D NULL)
+    if (asprintf(&fnout, "%s.out", bname) < 0 || fnout =3D=3D NULL)
 	errx(1, "malloc");
=20
     fout =3D fopen(fnout, "w");
@@ -107,8 +106,8 @@
 	l =3D atoi(length);
=20
 	printf("line: %3lu offset: %3lu class: %d type: %d "
-	       "tag: %3d length: %3d %s\n",=20
-	       line, (unsigned long)offset, c, ty, ta, l,=20
+	       "tag: %3d length: %3d %s\n",
+	       line, (unsigned long)offset, c, ty, ta, l,
 	       data ? "<have data>" : "<no data>");
=20
 	ret =3D der_put_length_and_tag(p + sizeof(p) - 1, sizeof(p),
@@ -119,29 +118,29 @@
 				     &sz);
 	if (ret)
 	    errx(1, "der_put_length_and_tag: %d", ret);
-=09
+
 	if (fwrite(p + sizeof(p) - sz , sz, 1, fout) !=3D 1)
 	    err(1, "fwrite length/tag failed");
 	offset +=3D sz;
-=09
+
 	if (data) {
 	    size_t datalen;
-	   =20
+
 	    datalen =3D strlen(data) / 2;
 	    pdata =3D emalloc(sz);
-	   =20
+
 	    if (hex_decode(data, pdata, datalen) !=3D datalen)
 		errx(1, "failed to decode data");
-	   =20
+
 	    if (fwrite(pdata, datalen, 1, fout) !=3D 1)
 		err(1, "fwrite data failed");
 	    offset +=3D datalen;
-	   =20
+
 	    free(pdata);
 	}
     }
     printf("line: eof offset: %lu\n", (unsigned long)offset);
-   =20
+
     fclose(fout);
     fclose(f);
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/asn1_prin=
t.c
--- a/head/crypto/heimdal/lib/asn1/asn1_print.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/asn1_print.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,34 +1,36 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
@@ -39,9 +41,8 @@
 #include <err.h>
 #include <der.h>
=20
-RCSID("$Id: asn1_print.c 19539 2006-12-28 17:15:05Z lha $");
-
 static int indent_flag =3D 1;
+static int inner_flag =3D 0;
=20
 static unsigned long indefinite_form_loop;
 static unsigned long indefinite_form_loop_max =3D 10000;
@@ -151,13 +152,13 @@
=20
 		    ret =3D der_get_heim_integer(buf, length, &vali, NULL);
 		    if (ret)
-			errx (1, "der_get_heim_integer: %s",=20
+			errx (1, "der_get_heim_integer: %s",
 			      error_message (ret));
 		    ret =3D der_print_hex_heim_integer(&vali, &p);
 		    if (ret)
-			errx (1, "der_print_hex_heim_integer: %s",=20
+			errx (1, "der_print_hex_heim_integer: %s",
 			      error_message (ret));
-		    printf ("BIG NUM integer: length %lu %s\n",=20
+		    printf ("BIG NUM integer: length %lu %s\n",
 			    (unsigned long)length, p);
 		    free(p);
 		}
@@ -165,24 +166,70 @@
 	    }
 	    case UT_OctetString : {
 		heim_octet_string str;
-		int i;
-		unsigned char *uc;
+		size_t i;
=20
 		ret =3D der_get_octet_string (buf, length, &str, NULL);
 		if (ret)
 		    errx (1, "der_get_octet_string: %s", error_message (ret));
 		printf ("(length %lu), ", (unsigned long)length);
-		uc =3D (unsigned char *)str.data;
-		for (i =3D 0; i < min(16,length); ++i)
-		    printf ("%02x", uc[i]);
-		printf ("\n");
+
+		if (inner_flag) {
+		    Der_class class;
+		    Der_type type;
+		    unsigned int tag;
+
+		    ret =3D der_get_tag(str.data, str.length,
+				      &class, &type, &tag, &sz);
+		    if (ret || sz > str.length ||
+			type !=3D CONS || tag !=3D UT_Sequence)
+			goto just_an_octet_string;
+
+		    printf("{\n");
+		    loop (str.data, str.length, indent + 2);
+		    for (i =3D 0; i < indent; ++i)
+			printf (" ");
+		    printf ("}\n");
+
+		} else {
+		    unsigned char *uc;
+
+		just_an_octet_string:
+		    uc =3D (unsigned char *)str.data;
+		    for (i =3D 0; i < min(16,length); ++i)
+			printf ("%02x", uc[i]);
+		    printf ("\n");
+		}
 		free (str.data);
 		break;
 	    }
+	    case UT_IA5String :
+	    case UT_PrintableString : {
+		heim_printable_string str;
+		unsigned char *s;
+		size_t n;
+
+		memset(&str, 0, sizeof(str));
+
+		ret =3D der_get_printable_string (buf, length, &str, NULL);
+		if (ret)
+		    errx (1, "der_get_general_string: %s",
+			  error_message (ret));
+		s =3D str.data;
+		printf("\"");
+		for (n =3D 0; n < str.length; n++) {
+		    if (isprint((int)s[n]))
+			printf ("%c", s[n]);
+		    else
+			printf ("#%02x", s[n]);
+		}
+		printf("\"\n");
+		der_free_printable_string(&str);
+		break;
+	    }
 	    case UT_GeneralizedTime :
 	    case UT_GeneralString :
-	    case UT_PrintableString :
-	    case UT_VisibleString : {
+	    case UT_VisibleString :
+	    case UT_UTF8String : {
 		heim_general_string str;
=20
 		ret =3D der_get_general_string (buf, length, &str, NULL);
@@ -215,7 +262,7 @@
 		ret =3D der_get_integer (buf, length, &num, NULL);
 		if (ret)
 		    errx (1, "der_get_enum: %s", error_message (ret));
-	=09
+
 		printf("%u\n", num);
 		break;
 	    }
@@ -226,7 +273,7 @@
 	}
 	if (end_tag) {
 	    if (loop_length =3D=3D 0)
-		errx(1, "zero length INDEFINITE data ? indent =3D %d\n",=20
+		errx(1, "zero length INDEFINITE data ? indent =3D %d\n",
 		     indent / 2);
 	    if (loop_length < length)
 		length =3D loop_length;
@@ -261,7 +308,7 @@
     close (fd);
     ret =3D loop (buf, len, 0);
     free (buf);
-    return 0;
+    return ret;
 }
=20
=20
@@ -269,6 +316,7 @@
 static int help_flag;
 struct getargs args[] =3D {
     { "indent", 0, arg_negative_flag, &indent_flag },
+    { "inner", 0, arg_flag, &inner_flag, "try to parse inner structures of=
 OCTET STRING" },
     { "version", 0, arg_flag, &version_flag },
     { "help", 0, arg_flag, &help_flag }
 };
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/asn1_queu=
e.h
--- a/head/crypto/heimdal/lib/asn1/asn1_queue.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/asn1_queue.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 /*	$NetBSD: queue.h,v 1.38 2004/04/18 14:12:05 lukem Exp $	*/
-/*	$Id: asn1_queue.h 15617 2005-07-12 06:27:42Z lha $ */
+/*	$Id$ */
=20
 /*
  * Copyright (c) 1991, 1993
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/canthandl=
e.asn1
--- a/head/crypto/heimdal/lib/asn1/canthandle.asn1	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/asn1/canthandle.asn1	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,4 +1,4 @@
--- $Id: canthandle.asn1 22071 2007-11-14 20:04:50Z lha $ --
+-- $Id$ --
=20
 CANTHANDLE DEFINITIONS ::=3D BEGIN
=20
@@ -7,7 +7,7 @@
 -- Code the tag [2] but it should be primitive since KAKA3 is
 -- Workaround: use the INTEGER type directly
=20
-Kaka2  ::=3D SEQUENCE {=20
+Kaka2  ::=3D SEQUENCE {
         kaka2-1 [0] INTEGER
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/check-com=
mon.c
--- a/head/crypto/heimdal/lib/asn1/check-common.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/asn1/check-common.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,34 +1,36 @@
 /*
- * Copyright (c) 1999 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifdef HAVE_CONFIG_H
@@ -42,9 +44,10 @@
 #include <err.h>
 #include <roken.h>
=20
+#include "asn1-common.h"
 #include "check-common.h"
=20
-RCSID("$Id: check-common.c 18751 2006-10-21 14:49:13Z lha $");
+RCSID("$Id$");
=20
 struct map_page {
     void *start;
@@ -57,14 +60,14 @@
 /* #undef HAVE_MMAP */
=20
 void *
-map_alloc(enum map_type type, const void *buf,=20
+map_alloc(enum map_type type, const void *buf,
 	  size_t size, struct map_page **map)
 {
 #ifndef HAVE_MMAP
     unsigned char *p;
     size_t len =3D size + sizeof(long) * 2;
     int i;
-   =20
+
     *map =3D ecalloc(1, sizeof(**map));
=20
     p =3D emalloc(len);
@@ -136,18 +139,18 @@
 #ifndef HAVE_MMAP
     unsigned char *p =3D map->start;
     int i;
-   =20
+
     for (i =3D sizeof(long); i > 0; i--)
 	if (p[sizeof(long) - i] !=3D 0xff - i)
 	    errx(1, "%s: %s underrun %d\n", test_name, map_name, i);
     for (i =3D sizeof(long); i > 0; i--)
 	if (p[map->size - i] !=3D 0xff - i)
-	    errx(1, "%s: %s overrun %lu\n", test_name, map_name,=20
+	    errx(1, "%s: %s overrun %lu\n", test_name, map_name,
 		 (unsigned long)map->size - i);
     free(map->start);
 #else
     int ret;
-   =20
+
     ret =3D munmap (map->start, map->size);
     if (ret < 0)
 	err (1, "munmap");
@@ -176,7 +179,7 @@
 {
     int fd;
     char msg[] =3D "SIGSEGV i current test: ";
-   =20
+
     fd =3D open("/dev/stdout", O_WRONLY, 0600);
     if (fd >=3D 0) {
 	write(fd, msg, sizeof(msg));
@@ -193,11 +196,12 @@
 generic_test (const struct test_case *tests,
 	      unsigned ntests,
 	      size_t data_size,
-	      int (*encode)(unsigned char *, size_t, void *, size_t *),
-	      int (*length)(void *),
-	      int (*decode)(unsigned char *, size_t, void *, size_t *),
-	      int (*free_data)(void *),
-	      int (*cmp)(void *a, void *b))
+	      int (ASN1CALL *encode)(unsigned char *, size_t, void *, size_t *),
+	      int (ASN1CALL *length)(void *),
+	      int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *),
+	      int (ASN1CALL *free_data)(void *),
+	      int (*cmp)(void *a, void *b),
+	      int (ASN1CALL *copy)(const void *from, void *to))
 {
     unsigned char *buf, *buf2;
     int i;
@@ -205,16 +209,20 @@
     void *data;
     struct map_page *data_map, *buf_map, *buf2_map;
=20
+#ifdef HAVE_SIGACTION
     struct sigaction sa, osa;
+#endif
=20
     for (i =3D 0; i < ntests; ++i) {
 	int ret;
 	size_t sz, consumed_sz, length_sz, buf_sz;
+	void *to =3D NULL;
=20
 	current_test =3D tests[i].name;
=20
 	current_state =3D "init";
=20
+#ifdef HAVE_SIGACTION
 	sigemptyset (&sa.sa_mask);
 	sa.sa_flags =3D 0;
 #ifdef SA_RESETHAND
@@ -222,6 +230,7 @@
 #endif
 	sa.sa_handler =3D segv_handler;
 	sigaction (SIGSEGV, &sa, &osa);
+#endif
=20
 	data =3D map_alloc(OVERRUN, NULL, data_size, &data_map);
=20
@@ -237,8 +246,8 @@
 	    continue;
 	}
 	if (sz !=3D tests[i].byte_len) {
-	    printf ("encoding of %s has wrong len (%lu !=3D %lu)\n",
-		    tests[i].name,=20
+ 	    printf ("encoding of %s has wrong len (%lu !=3D %lu)\n",
+		    tests[i].name,
 		    (unsigned long)sz, (unsigned long)tests[i].byte_len);
 	    ++failures;
 	    continue;
@@ -261,6 +270,11 @@
 	    printf ("\nactual:  ");
 	    print_bytes (buf, sz);
 	    printf ("\n");
+#if 0
+	    rk_dumpdata("correct", tests[i].bytes, tests[i].byte_len);
+	    rk_dumpdata("actual", buf, sz);
+	    exit (1);
+#endif
 	    ++failures;
 	    continue;
 	}
@@ -276,7 +290,7 @@
 	}
 	if (sz !=3D consumed_sz) {
 	    printf ("different length decoding %s (%ld !=3D %ld)\n",
-		    tests[i].name,=20
+		    tests[i].name,
 		    (unsigned long)sz, (unsigned long)consumed_sz);
 	    ++failures;
 	    continue;
@@ -287,16 +301,42 @@
 	    ++failures;
 	    continue;
 	}
+
+	current_state =3D "copy";
+	if (copy) {
+	    to =3D emalloc(data_size);
+	    ret =3D (*copy)(data, to);
+	    if (ret !=3D 0) {
+		printf ("copy of %s failed %d\n", tests[i].name, ret);
+		++failures;
+		continue;
+	    }
+
+	    current_state =3D "cmp-copy";
+	    if ((*cmp)(data, to) !=3D 0) {
+		printf ("%s: copy comparison failed\n", tests[i].name);
+		++failures;
+		continue;
+	    }
+	}
+
 	current_state =3D "free";
-	if (free_data)
+	if (free_data) {
 	    (*free_data)(data);
+	    if (to) {
+		(*free_data)(to);
+		free(to);
+	    }
+	}
=20
 	current_state =3D "free";
 	map_free(buf_map, tests[i].name, "encode");
 	map_free(buf2_map, tests[i].name, "decode");
 	map_free(data_map, tests[i].name, "data");
=20
+#ifdef HAVE_SIGACTION
 	sigaction (SIGSEGV, &osa, NULL);
+#endif
     }
     current_state =3D "done";
     return failures;
@@ -304,7 +344,7 @@
=20
 /*
  * check for failures
- *=20
+ *
  * a test size (byte_len) of -1 means that the test tries to trigger a
  * integer overflow (and later a malloc of to little memory), just
  * allocate some memory and hope that is enough for that test.
@@ -314,7 +354,7 @@
 generic_decode_fail (const struct test_case *tests,
 		     unsigned ntests,
 		     size_t data_size,
-		     int (*decode)(unsigned char *, size_t, void *, size_t *))
+		     int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *))
 {
     unsigned char *buf;
     int i;
@@ -322,17 +362,20 @@
     void *data;
     struct map_page *data_map, *buf_map;
=20
+#ifdef HAVE_SIGACTION
     struct sigaction sa, osa;
+#endif
=20
     for (i =3D 0; i < ntests; ++i) {
 	int ret;
 	size_t sz;
 	const void *bytes;
-=09
+
 	current_test =3D tests[i].name;
=20
 	current_state =3D "init";
=20
+#ifdef HAVE_SIGACTION
 	sigemptyset (&sa.sa_mask);
 	sa.sa_flags =3D 0;
 #ifdef SA_RESETHAND
@@ -340,6 +383,7 @@
 #endif
 	sa.sa_handler =3D segv_handler;
 	sigaction (SIGSEGV, &sa, &osa);
+#endif
=20
 	data =3D map_alloc(OVERRUN, NULL, data_size, &data_map);
=20
@@ -350,7 +394,7 @@
 	    sz =3D 4096;
 	    bytes =3D NULL;
 	}
-	=09
+
 	buf =3D map_alloc(OVERRUN, bytes, sz, &buf_map);
=20
 	if (tests[i].byte_len =3D=3D -1)
@@ -369,7 +413,9 @@
 	    map_free(buf_map, tests[i].name, "encode");
 	map_free(data_map, tests[i].name, "data");
=20
+#ifdef HAVE_SIGACTION
 	sigaction (SIGSEGV, &osa, NULL);
+#endif
     }
     current_state =3D "done";
     return failures;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/check-com=
mon.h
--- a/head/crypto/heimdal/lib/asn1/check-common.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/asn1/check-common.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,34 +1,36 @@
 /*
- * Copyright (c) 1999 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 struct test_case {
@@ -38,26 +40,28 @@
     char *name;
 };
=20
-typedef int (*generic_encode)(unsigned char *, size_t, void *, size_t *);
-typedef int (*generic_length)(void *);
-typedef int (*generic_decode)(unsigned char *, size_t, void *, size_t *);
-typedef int (*generic_free)(void *);
+typedef int (ASN1CALL *generic_encode)(unsigned char *, size_t, void *, si=
ze_t *);
+typedef int (ASN1CALL *generic_length)(void *);
+typedef int (ASN1CALL *generic_decode)(unsigned char *, size_t, void *, si=
ze_t *);
+typedef int (ASN1CALL *generic_free)(void *);
+typedef int (ASN1CALL *generic_copy)(const void *, void *);
=20
 int
 generic_test (const struct test_case *tests,
 	      unsigned ntests,
 	      size_t data_size,
-	      int (*encode)(unsigned char *, size_t, void *, size_t *),
-	      int (*length)(void *),
-	      int (*decode)(unsigned char *, size_t, void *, size_t *),
-	      int (*free_data)(void *),
-	      int (*cmp)(void *a, void *b));
+	      int (ASN1CALL *encode)(unsigned char *, size_t, void *, size_t *),
+	      int (ASN1CALL *length)(void *),
+	      int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *),
+	      int (ASN1CALL *free_data)(void *),
+	      int (*cmp)(void *a, void *b),
+	      int (ASN1CALL *copy)(const void *a, void *b));
=20
 int
 generic_decode_fail(const struct test_case *tests,
 		    unsigned ntests,
 		    size_t data_size,
-		    int (*decode)(unsigned char *, size_t, void *, size_t *));
+		    int (ASN1CALL *decode)(unsigned char *, size_t, void *, size_t *));
=20
=20
 struct map_page;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/check-der=
.c
--- a/head/crypto/heimdal/lib/asn1/check-der.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/check-der.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,34 +1,36 @@
 /*
- * Copyright (c) 1999 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
@@ -41,7 +43,7 @@
=20
 #include "check-common.h"
=20
-RCSID("$Id: check-der.c 21359 2007-06-27 08:15:41Z lha $");
+RCSID("$Id$");
=20
 static int
 cmp_integer (void *a, void *b)
@@ -75,17 +77,19 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "integer %d", values[i]);
+	if (asprintf (&tests[i].name, "integer %d", values[i]) < 0)
+	    errx(1, "malloc");
 	if (tests[i].name =3D=3D NULL)
 	    errx(1, "malloc");
     }
=20
     ret =3D generic_test (tests, ntests, sizeof(int),
 			(generic_encode)der_put_integer,
-			 (generic_length) der_length_integer,
-			 (generic_decode)der_get_integer,
-			 (generic_free)NULL,
-			 cmp_integer);
+			(generic_length) der_length_integer,
+			(generic_decode)der_get_integer,
+			(generic_free)NULL,
+			cmp_integer,
+			NULL);
=20
     for (i =3D 0; i < ntests; ++i)
 	free (tests[i].name);
@@ -190,14 +194,15 @@
 	{NULL, 4, "\x7f\xff\xff\xff"}
     };
=20
-    unsigned int values[] =3D {0, 127, 128, 256, 512, 32768,=20
+    unsigned int values[] =3D {0, 127, 128, 256, 512, 32768,
 			     0x80000000, 0x7fffffff};
     int i, ret;
     int ntests =3D sizeof(tests) / sizeof(*tests);
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "unsigned %u", values[i]);
+	if (asprintf (&tests[i].name, "unsigned %u", values[i]) < 0)
+	    errx(1, "malloc");
 	if (tests[i].name =3D=3D NULL)
 	    errx(1, "malloc");
     }
@@ -207,8 +212,9 @@
 			(generic_length)der_length_unsigned,
 			(generic_decode)der_get_unsigned,
 			(generic_free)NULL,
-			cmp_unsigned);
-    for (i =3D 0; i < ntests; ++i)=20
+			cmp_unsigned,
+			NULL);
+    for (i =3D 0; i < ntests; ++i)
 	free (tests[i].name);
     return ret;
 }
@@ -237,7 +243,8 @@
     int ret;
=20
     tests[0].val =3D &s1;
-    asprintf (&tests[0].name, "a octet string");
+    if (asprintf (&tests[0].name, "a octet string") < 0)
+	errx(1, "malloc");
     if (tests[0].name =3D=3D NULL)
 	errx(1, "malloc");
=20
@@ -246,7 +253,8 @@
 			(generic_length)der_length_octet_string,
 			(generic_decode)der_get_octet_string,
 			(generic_free)der_free_octet_string,
-			cmp_octet_string);
+			cmp_octet_string,
+			NULL);
     free(tests[0].name);
     return ret;
 }
@@ -277,11 +285,13 @@
     int ret;
=20
     tests[0].val =3D &s1;
-    asprintf (&tests[0].name, "a bmp string");
+    if (asprintf (&tests[0].name, "a bmp string") < 0)
+	errx(1, "malloc");
     if (tests[0].name =3D=3D NULL)
 	errx(1, "malloc");
     tests[1].val =3D &s2;
-    asprintf (&tests[1].name, "second bmp string");
+    if (asprintf (&tests[1].name, "second bmp string") < 0)
+	errx(1, "malloc");
     if (tests[1].name =3D=3D NULL)
 	errx(1, "malloc");
=20
@@ -290,7 +300,8 @@
 			(generic_length)der_length_bmp_string,
 			(generic_decode)der_get_bmp_string,
 			(generic_free)der_free_bmp_string,
-			cmp_bmp_string);
+			cmp_bmp_string,
+			NULL);
     free(tests[0].name);
     free(tests[1].name);
     return ret;
@@ -322,11 +333,13 @@
     int ret;
=20
     tests[0].val =3D &s1;
-    asprintf (&tests[0].name, "a universal string");
+    if (asprintf (&tests[0].name, "a universal string") < 0)
+	errx(1, "malloc");
     if (tests[0].name =3D=3D NULL)
 	errx(1, "malloc");
     tests[1].val =3D &s2;
-    asprintf (&tests[1].name, "second universal string");
+    if (asprintf (&tests[1].name, "second universal string") < 0)
+	errx(1, "malloc");
     if (tests[1].name =3D=3D NULL)
 	errx(1, "malloc");
=20
@@ -335,7 +348,8 @@
 			(generic_length)der_length_universal_string,
 			(generic_decode)der_get_universal_string,
 			(generic_free)der_free_universal_string,
-			cmp_universal_string);
+			cmp_universal_string,
+			NULL);
     free(tests[0].name);
     free(tests[1].name);
     return ret;
@@ -361,7 +375,8 @@
     int ret, ntests =3D sizeof(tests) / sizeof(*tests);
=20
     tests[0].val =3D &s1;
-    asprintf (&tests[0].name, "the string \"%s\"", s1);
+    if (asprintf (&tests[0].name, "the string \"%s\"", s1) < 0)
+	errx(1, "malloc");
     if (tests[0].name =3D=3D NULL)
 	errx(1, "malloc");
=20
@@ -370,7 +385,8 @@
 			(generic_length)der_length_general_string,
 			(generic_decode)der_get_general_string,
 			(generic_free)der_free_general_string,
-			cmp_general_string);
+			cmp_general_string,
+			NULL);
     free(tests[0].name);
     return ret;
 }
@@ -397,7 +413,8 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "time %d", (int)values[i]);
+	if (asprintf (&tests[i].name, "time %d", (int)values[i]) < 0)
+	    errx(1, "malloc");
 	if (tests[i].name =3D=3D NULL)
 	    errx(1, "malloc");
     }
@@ -407,7 +424,8 @@
 			(generic_length)der_length_generalized_time,
 			(generic_decode)der_get_generalized_time,
 			(generic_free)NULL,
-			cmp_generalized_time);
+			cmp_generalized_time,
+			NULL);
     for (i =3D 0; i < ntests; ++i)
 	free(tests[i].name);
     return ret;
@@ -444,7 +462,8 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "oid %d", i);
+	if (asprintf (&tests[i].name, "oid %d", i) < 0)
+	    errx(1, "malloc");
 	if (tests[i].name =3D=3D NULL)
 	    errx(1, "malloc");
     }
@@ -454,7 +473,8 @@
 			(generic_length)der_length_oid,
 			(generic_decode)der_get_oid,
 			(generic_free)der_free_oid,
-			test_cmp_oid);
+			test_cmp_oid,
+			NULL);
     for (i =3D 0; i < ntests; ++i)
 	free(tests[i].name);
     return ret;
@@ -480,7 +500,8 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "bit_string %d", i);
+	if (asprintf (&tests[i].name, "bit_string %d", i) < 0)
+	    errx(1, "malloc");
 	if (tests[i].name =3D=3D NULL)
 	    errx(1, "malloc");
     }
@@ -490,7 +511,8 @@
 			(generic_length)der_length_bit_string,
 			(generic_decode)der_get_bit_string,
 			(generic_free)der_free_bit_string,
-			test_cmp_bit_string);
+			test_cmp_bit_string,
+			NULL);
     for (i =3D 0; i < ntests; ++i)
 	free(tests[i].name);
     return ret;
@@ -531,7 +553,8 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "heim_integer %d", i);
+	if (asprintf (&tests[i].name, "heim_integer %d", i) < 0)
+	    errx(1, "malloc");
 	if (tests[i].name =3D=3D NULL)
 	    errx(1, "malloc");
     }
@@ -541,8 +564,9 @@
 			(generic_length)der_length_heim_integer,
 			(generic_decode)der_get_heim_integer,
 			(generic_free)der_free_heim_integer,
-			test_cmp_heim_integer);
-    for (i =3D 0; i < ntests; ++i)=20
+			test_cmp_heim_integer,
+			NULL);
+    for (i =3D 0; i < ntests; ++i)
 	free (tests[i].name);
     if (ret)
 	return ret;
@@ -580,7 +604,8 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "heim_boolean %d", i);
+	if (asprintf (&tests[i].name, "heim_boolean %d", i) < 0)
+	    errx(1, "malloc");
 	if (tests[i].name =3D=3D NULL)
 	    errx(1, "malloc");
     }
@@ -590,8 +615,9 @@
 			(generic_length)der_length_boolean,
 			(generic_decode)der_get_boolean,
 			(generic_free)NULL,
-			test_cmp_boolean);
-    for (i =3D 0; i < ntests; ++i)=20
+			test_cmp_boolean,
+			NULL);
+    for (i =3D 0; i < ntests; ++i)
 	free (tests[i].name);
     if (ret)
 	return ret;
@@ -733,7 +759,7 @@
     struct test_case tests[] =3D {
 	{NULL, 0, "", "empty input data"},
 	{NULL, 2, "\x00\x80", "last byte continuation" },
-	{NULL, 11, "\x00\x81\x80\x80\x80\x80\x80\x80\x80\x80\x00",=20
+	{NULL, 11, "\x00\x81\x80\x80\x80\x80\x80\x80\x80\x80\x00",
 	"oid element overflow" }
     };
     int ntests =3D sizeof(tests) / sizeof(*tests);
@@ -808,7 +834,7 @@
 	"EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381"
 	"FFFFFFFF" "FFFFFFFF";
     heim_integer bni =3D {
-	128,=20
+	128,
 	"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xC9\x0F\xDA\xA2"
 	"\x21\x68\xC2\x34\xC4\xC6\x62\x8B\x80\xDC\x1C\xD1"
 	"\x29\x02\x4E\x08\x8A\x67\xCC\x74\x02\x0B\xBE\xA6"
@@ -916,7 +942,7 @@
 	{ 0, (const unsigned char *)"foo\0", 4, "foo", 4 },
 	{ 0, (const unsigned char *)"foo", 3, "foo", 3 }
     };
-   =20
+
     for (i =3D 0; i < sizeof(foo)/sizeof(foo[0]); i++) {
 	char *s;
 	size_t size;
@@ -1024,7 +1050,7 @@
 	int ok;
 	const char *ptr;
 	size_t len;
-    } tests[] =3D {=20
+    } tests[] =3D {
 	{ 1, "\x00", 1 },
 	{ 0, "\xff", 1 },
 	{ 0, "\xff\xff\xff\xff\xff\xff\xff\xff", 8 }
@@ -1036,7 +1062,7 @@
     size_t size;
=20
     for (i =3D 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
-	ret =3D der_get_tag((const unsigned char*)tests[i].ptr,=20
+	ret =3D der_get_tag((const unsigned char*)tests[i].ptr,
 			  tests[i].len, &cl, &ty, &tag, &size);
 	if (ret) {
 	    if (tests[i].ok)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/check-gen=
.c
--- a/head/crypto/heimdal/lib/asn1/check-gen.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/check-gen.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,34 +1,36 @@
 /*
- * Copyright (c) 1999 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifdef HAVE_CONFIG_H
@@ -49,7 +51,7 @@
=20
 #include "check-common.h"
=20
-RCSID("$Id: check-gen.c 21539 2007-07-14 16:12:04Z lha $");
+RCSID("$Id$");
=20
 static char *lha_principal[] =3D { "lha" };
 static char *lharoot_princ[] =3D { "lha", "root" };
@@ -67,6 +69,8 @@
 	do { if (strcmp((ac)->e, (bc)->e) !=3D 0) return 1; } while(0)
 #define COMPARE_INTEGER(ac,bc,e) \
 	do { if ((ac)->e !=3D (bc)->e) return 1; } while(0)
+#define COMPARE_OPT_INTEGER(ac,bc,e) \
+	do { if (*(ac)->e !=3D *(bc)->e) return 1; } while(0)
 #define COMPARE_MEM(ac,bc,e,len) \
 	do { if (memcmp((ac)->e, (bc)->e,len) !=3D 0) return 1; } while(0)
=20
@@ -92,7 +96,7 @@
 {
=20
     struct test_case tests[] =3D {
-	{ NULL, 29,=20
+	{ NULL, 29,
 	  "\x30\x1b\xa0\x10\x30\x0e\xa0\x03\x02\x01\x01\xa1\x07\x30\x05\x1b"
 	  "\x03\x6c\x68\x61\xa1\x07\x1b\x05\x53\x55\x2e\x53\x45"
 	},
@@ -101,7 +105,7 @@
 	  "\x03\x6c\x68\x61\x1b\x04\x72\x6f\x6f\x74\xa1\x07\x1b\x05\x53\x55"
 	  "\x2e\x53\x45"
 	},
-	{ NULL, 54,=20
+	{ NULL, 54,
 	  "\x30\x34\xa0\x26\x30\x24\xa0\x03\x02\x01\x03\xa1\x1d\x30\x1b\x1b"
 	  "\x04\x68\x6f\x73\x74\x1b\x13\x6e\x75\x74\x63\x72\x61\x63\x6b\x65"
 	  "\x72\x2e\x65\x2e\x6b\x74\x68\x2e\x73\x65\xa1\x0a\x1b\x08\x45\x2e"
@@ -110,7 +114,7 @@
     };
=20
=20
-    Principal values[] =3D {=20
+    Principal values[] =3D {
 	{ { KRB5_NT_PRINCIPAL, { 1, lha_principal } },  "SU.SE" },
 	{ { KRB5_NT_PRINCIPAL, { 2, lharoot_princ } },  "SU.SE" },
 	{ { KRB5_NT_SRV_HST, { 2, datan_princ } },  "E.KTH.SE" }
@@ -120,7 +124,10 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "Principal %d", i);
+	if (asprintf (&tests[i].name, "Principal %d", i) < 0)
+	    errx(1, "malloc");
+	if (tests[i].name =3D=3D NULL)
+	    errx(1, "malloc");
     }
=20
     ret =3D generic_test (tests, ntests, sizeof(Principal),
@@ -128,7 +135,8 @@
 			(generic_length)length_Principal,
 			(generic_decode)decode_Principal,
 			(generic_free)free_Principal,
-			cmp_principal);
+			cmp_principal,
+			NULL);
     for (i =3D 0; i < ntests; ++i)
 	free (tests[i].name);
=20
@@ -158,14 +166,14 @@
 test_authenticator (void)
 {
     struct test_case tests[] =3D {
-	{ NULL, 63,=20
+	{ NULL, 63,
 	  "\x62\x3d\x30\x3b\xa0\x03\x02\x01\x05\xa1\x0a\x1b\x08"
 	  "\x45\x2e\x4b\x54\x48\x2e\x53\x45\xa2\x10\x30\x0e\xa0"
 	  "\x03\x02\x01\x01\xa1\x07\x30\x05\x1b\x03\x6c\x68\x61"
 	  "\xa4\x03\x02\x01\x0a\xa5\x11\x18\x0f\x31\x39\x37\x30"
 	  "\x30\x31\x30\x31\x30\x30\x30\x31\x33\x39\x5a"
 	},
-	{ NULL, 67,=20
+	{ NULL, 67,
 	  "\x62\x41\x30\x3f\xa0\x03\x02\x01\x05\xa1\x07\x1b\x05"
 	  "\x53\x55\x2e\x53\x45\xa2\x16\x30\x14\xa0\x03\x02\x01"
 	  "\x01\xa1\x0d\x30\x0b\x1b\x03\x6c\x68\x61\x1b\x04\x72"
@@ -186,7 +194,10 @@
=20
     for (i =3D 0; i < ntests; ++i) {
 	tests[i].val =3D &values[i];
-	asprintf (&tests[i].name, "Authenticator %d", i);
+	if (asprintf (&tests[i].name, "Authenticator %d", i) < 0)
+	    errx(1, "malloc");
+	if (tests[i].name =3D=3D NULL)
+	    errx(1, "malloc");
     }
=20
     ret =3D generic_test (tests, ntests, sizeof(Authenticator),
@@ -194,7 +205,8 @@
 			(generic_length)length_Authenticator,
 			(generic_decode)decode_Authenticator,
 			(generic_free)free_Authenticator,
-			cmp_authenticator);
+			cmp_authenticator,
+			(generic_copy)copy_Authenticator);
     for (i =3D 0; i < ntests; ++i)
 	free(tests[i].name);
=20
@@ -249,7 +261,7 @@
 test_krb_error (void)
 {
     struct test_case tests[] =3D {
-	{ NULL, 127,=20
+	{ NULL, 127,
 	  "\x7e\x7d\x30\x7b\xa0\x03\x02\x01\x05\xa1\x03\x02\x01\x1e\xa4\x11"
 	  "\x18\x0f\x32\x30\x30\x33\x31\x31\x32\x34\x30\x30\x31\x31\x31\x39"
 	  "\x5a\xa5\x05\x02\x03\x04\xed\xa5\xa6\x03\x02\x01\x1f\xa7\x0d\x1b"
@@ -288,7 +300,8 @@
 			 (generic_length)length_KRB_ERROR,
 			 (generic_decode)decode_KRB_ERROR,
 			 (generic_free)free_KRB_ERROR,
-			 cmp_KRB_ERROR);
+			 cmp_KRB_ERROR,
+			 (generic_copy)copy_KRB_ERROR);
 }
=20
 static int
@@ -306,13 +319,13 @@
 test_Name (void)
 {
     struct test_case tests[] =3D {
-	{ NULL, 35,=20
+	{ NULL, 35,
 	  "\x30\x21\x31\x1f\x30\x0b\x06\x03\x55\x04\x03\x13\x04\x4c\x6f\x76"
 	  "\x65\x30\x10\x06\x03\x55\x04\x07\x13\x09\x53\x54\x4f\x43\x4b\x48"
 	  "\x4f\x4c\x4d",
 	  "Name CN=3DLove+L=3DSTOCKHOLM"
 	},
-	{ NULL, 35,=20
+	{ NULL, 35,
 	  "\x30\x21\x31\x1f\x30\x0b\x06\x03\x55\x04\x03\x13\x04\x4c\x6f\x76"
 	  "\x65\x30\x10\x06\x03\x55\x04\x07\x13\x09\x53\x54\x4f\x43\x4b\x48"
 	  "\x4f\x4c\x4d",
@@ -339,12 +352,14 @@
     atv1[0].type.length =3D sizeof(cmp_CN)/sizeof(cmp_CN[0]);
     atv1[0].type.components =3D cmp_CN;
     atv1[0].value.element =3D choice_DirectoryString_printableString;
-    atv1[0].value.u.printableString =3D "Love";
+    atv1[0].value.u.printableString.data =3D "Love";
+    atv1[0].value.u.printableString.length =3D 4;
=20
     atv1[1].type.length =3D sizeof(cmp_L)/sizeof(cmp_L[0]);
     atv1[1].type.components =3D cmp_L;
     atv1[1].value.element =3D choice_DirectoryString_printableString;
-    atv1[1].value.u.printableString =3D "STOCKHOLM";
+    atv1[1].value.u.printableString.data =3D "STOCKHOLM";
+    atv1[1].value.u.printableString.length =3D 9;
=20
     /* n2 */
     n2.element =3D choice_Name_rdnSequence;
@@ -356,12 +371,14 @@
     atv2[0].type.length =3D sizeof(cmp_L)/sizeof(cmp_L[0]);
     atv2[0].type.components =3D cmp_L;
     atv2[0].value.element =3D choice_DirectoryString_printableString;
-    atv2[0].value.u.printableString =3D "STOCKHOLM";
+    atv2[0].value.u.printableString.data =3D "STOCKHOLM";
+    atv2[0].value.u.printableString.length =3D 9;
=20
     atv2[1].type.length =3D sizeof(cmp_CN)/sizeof(cmp_CN[0]);
     atv2[1].type.components =3D cmp_CN;
     atv2[1].value.element =3D choice_DirectoryString_printableString;
-    atv2[1].value.u.printableString =3D "Love";
+    atv2[1].value.u.printableString.data =3D "Love";
+    atv2[1].value.u.printableString.length =3D 4;
=20
     /* */
     tests[0].val =3D &n1;
@@ -372,7 +389,8 @@
 			 (generic_length)length_Name,
 			 (generic_decode)decode_Name,
 			 (generic_free)free_Name,
-			 cmp_Name);
+			 cmp_Name,
+			 (generic_copy)copy_Name);
 }
=20
 static int
@@ -431,16 +449,234 @@
 			 (generic_length)length_KeyUsage,
 			 (generic_decode)decode_KeyUsage,
 			 (generic_free)free_KeyUsage,
-			 cmp_KeyUsage);
+			 cmp_KeyUsage,
+			 (generic_copy)copy_KeyUsage);
 }
=20
 static int
+cmp_TicketFlags (void *a, void *b)
+{
+    TicketFlags *aa =3D a;
+    TicketFlags *ab =3D b;
+
+    return TicketFlags2int(*aa) !=3D TicketFlags2int(*ab);
+}
+
+static int
+test_bit_string_rfc1510 (void)
+{
+    struct test_case tests[] =3D {
+	{ NULL, 7,
+	  "\x03\x05\x00\x80\x00\x00\x00",
+	  "TF bitstring 1"
+	},
+	{ NULL, 7,
+	  "\x03\x05\x00\x40\x20\x00\x00",
+	  "TF bitstring 2"
+	},
+	{ NULL, 7,
+	  "\x03\x05\x00\x00\x20\x00\x00",
+	  "TF bitstring 3"
+	},
+	{ NULL, 7,
+	  "\x03\x05\x00\x00\x00\x00\x00",
+	  "TF bitstring 4"
+	}
+    };
+
+    int ntests =3D sizeof(tests) / sizeof(*tests);
+    TicketFlags tf1, tf2, tf3, tf4;
+
+    memset(&tf1, 0, sizeof(tf1));
+    tf1.reserved =3D 1;
+    tests[0].val =3D &tf1;
+
+    memset(&tf2, 0, sizeof(tf2));
+    tf2.forwardable =3D 1;
+    tf2.pre_authent =3D 1;
+    tests[1].val =3D &tf2;
+
+    memset(&tf3, 0, sizeof(tf3));
+    tf3.pre_authent =3D 1;
+    tests[2].val =3D &tf3;
+
+    memset(&tf4, 0, sizeof(tf4));
+    tests[3].val =3D &tf4;
+
+
+    return generic_test (tests, ntests, sizeof(TicketFlags),
+			 (generic_encode)encode_TicketFlags,
+			 (generic_length)length_TicketFlags,
+			 (generic_decode)decode_TicketFlags,
+			 (generic_free)free_TicketFlags,
+			 cmp_TicketFlags,
+			 (generic_copy)copy_TicketFlags);
+}
+
+static int
+cmp_KerberosTime (void *a, void *b)
+{
+    KerberosTime *aa =3D a;
+    KerberosTime *ab =3D b;
+
+    return *aa !=3D *ab;
+}
+
+static int
+test_time (void)
+{
+    struct test_case tests[] =3D {
+	{ NULL,  17,
+	  "\x18\x0f\x31\x39\x37\x30\x30\x31\x30\x31\x30\x31\x31\x38\x33\x31"
+	  "\x5a",
+	  "time 1" },
+	{ NULL,  17,
+	  "\x18\x0f\x32\x30\x30\x39\x30\x35\x32\x34\x30\x32\x30\x32\x34\x30"
+	  "\x5a"
+	  "time 2" }
+    };
+
+    int ntests =3D sizeof(tests) / sizeof(*tests);
+    KerberosTime times[] =3D {
+	4711,
+	1243130560
+    };
+
+    tests[0].val =3D &times[0];
+    tests[1].val =3D &times[1];
+
+    return generic_test (tests, ntests, sizeof(KerberosTime),
+			 (generic_encode)encode_KerberosTime,
+			 (generic_length)length_KerberosTime,
+			 (generic_decode)decode_KerberosTime,
+			 (generic_free)free_KerberosTime,
+			 cmp_KerberosTime,
+			 (generic_copy)copy_KerberosTime);
+}
+
+struct {
+    const char *cert;
+    size_t len;
+} certs[] =3D {
+    {
+	"\x30\x82\x02\x6c\x30\x82\x01\xd5\xa0\x03\x02\x01\x02\x02\x09\x00"
+	"\x99\x32\xde\x61\x0e\x40\x19\x8a\x30\x0d\x06\x09\x2a\x86\x48\x86"
+	"\xf7\x0d\x01\x01\x05\x05\x00\x30\x2a\x31\x1b\x30\x19\x06\x03\x55"
+	"\x04\x03\x0c\x12\x68\x78\x35\x30\x39\x20\x54\x65\x73\x74\x20\x52"
+	"\x6f\x6f\x74\x20\x43\x41\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13"
+	"\x02\x53\x45\x30\x1e\x17\x0d\x30\x39\x30\x34\x32\x36\x32\x30\x32"
+	"\x39\x34\x30\x5a\x17\x0d\x31\x39\x30\x34\x32\x34\x32\x30\x32\x39"
+	"\x34\x30\x5a\x30\x2a\x31\x1b\x30\x19\x06\x03\x55\x04\x03\x0c\x12"
+	"\x68\x78\x35\x30\x39\x20\x54\x65\x73\x74\x20\x52\x6f\x6f\x74\x20"
+	"\x43\x41\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x53\x45\x30"
+	"\x81\x9f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05"
+	"\x00\x03\x81\x8d\x00\x30\x81\x89\x02\x81\x81\x00\xb9\xd3\x1b\x67"
+	"\x1c\xf7\x5e\x26\x81\x3b\x82\xff\x03\xa4\x43\xb5\xb2\x63\x0b\x89"
+	"\x58\x43\xfe\x3d\xe0\x38\x7d\x93\x74\xbb\xad\x21\xa4\x29\xd9\x34"
+	"\x79\xf3\x1c\x8c\x5a\xd6\xb0\xd7\x19\xea\xcc\xaf\xe0\xa8\x40\x02"
+	"\x1d\x91\xf1\xac\x36\xb0\xfb\x08\xbd\xcc\x9a\xe1\xb7\x6e\xee\x0a"
+	"\x69\xbf\x6d\x2b\xee\x20\x82\x61\x06\xf2\x18\xcc\x89\x11\x64\x7e"
+	"\xb2\xff\x47\xd1\x3b\x52\x73\xeb\x5a\xc0\x03\xa6\x4b\xc7\x40\x7e"
+	"\xbc\xe1\x0e\x65\x44\x3f\x40\x8b\x02\x82\x54\x04\xd9\xcc\x2c\x67"
+	"\x01\xb6\x16\x82\xd8\x33\x53\x17\xd7\xde\x8d\x5d\x02\x03\x01\x00"
+	"\x01\xa3\x81\x99\x30\x81\x96\x30\x1d\x06\x03\x55\x1d\x0e\x04\x16"
+	"\x04\x14\x6e\x48\x13\xdc\xbf\x8b\x95\x4c\x13\xf3\x1f\x97\x30\xdd"
+	"\x27\x96\x59\x9b\x0e\x68\x30\x5a\x06\x03\x55\x1d\x23\x04\x53\x30"
+	"\x51\x80\x14\x6e\x48\x13\xdc\xbf\x8b\x95\x4c\x13\xf3\x1f\x97\x30"
+	"\xdd\x27\x96\x59\x9b\x0e\x68\xa1\x2e\xa4\x2c\x30\x2a\x31\x1b\x30"
+	"\x19\x06\x03\x55\x04\x03\x0c\x12\x68\x78\x35\x30\x39\x20\x54\x65"
+	"\x73\x74\x20\x52\x6f\x6f\x74\x20\x43\x41\x31\x0b\x30\x09\x06\x03"
+	"\x55\x04\x06\x13\x02\x53\x45\x82\x09\x00\x99\x32\xde\x61\x0e\x40"
+	"\x19\x8a\x30\x0c\x06\x03\x55\x1d\x13\x04\x05\x30\x03\x01\x01\xff"
+	"\x30\x0b\x06\x03\x55\x1d\x0f\x04\x04\x03\x02\x01\xe6\x30\x0d\x06"
+	"\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x03\x81\x81\x00"
+	"\x52\x9b\xe4\x0e\xee\xc2\x5d\xb7\xf1\xba\x47\xe3\xfe\xaf\x3d\x51"
+	"\x10\xfd\xe8\x0d\x14\x58\x05\x36\xa7\xeb\xd8\x05\xe5\x27\x6f\x51"
+	"\xb8\xec\x90\xd9\x03\xe1\xbc\x9c\x93\x38\x21\x5c\xaf\x4e\x6c\x7b"
+	"\x6c\x65\xa9\x92\xcd\x94\xef\xa8\xae\x90\x12\x14\x78\x2d\xa3\x15"
+	"\xaa\x42\xf1\xd9\x44\x64\x2c\x3c\xc0\xbd\x3a\x48\xd8\x80\x45\x8b"
+	"\xd1\x79\x82\xe0\x0f\xdf\x08\x3c\x60\x21\x6f\x31\x47\x98\xae\x2f"
+	"\xcb\xb1\xa1\xb9\xc1\xa3\x71\x5e\x4a\xc2\x67\xdf\x66\x0a\x51\xb5"
+	"\xad\x60\x05\xdb\x02\xd4\x1a\xd2\xb9\x4e\x01\x08\x2b\xc3\x57\xaf",
+	624 },
+    {
+	"\x30\x82\x02\x54\x30\x82\x01\xbd\xa0\x03\x02\x01\x02\x02\x01\x08"
+	"\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30"
+	"\x2a\x31\x1b\x30\x19\x06\x03\x55\x04\x03\x0c\x12\x68\x78\x35\x30"
+	"\x39\x20\x54\x65\x73\x74\x20\x52\x6f\x6f\x74\x20\x43\x41\x31\x0b"
+	"\x30\x09\x06\x03\x55\x04\x06\x13\x02\x53\x45\x30\x1e\x17\x0d\x30"
+	"\x39\x30\x34\x32\x36\x32\x30\x32\x39\x34\x30\x5a\x17\x0d\x31\x39"
+	"\x30\x34\x32\x34\x32\x30\x32\x39\x34\x30\x5a\x30\x1b\x31\x0b\x30"
+	"\x09\x06\x03\x55\x04\x06\x13\x02\x53\x45\x31\x0c\x30\x0a\x06\x03"
+	"\x55\x04\x03\x0c\x03\x6b\x64\x63\x30\x81\x9f\x30\x0d\x06\x09\x2a"
+	"\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x81\x8d\x00\x30\x81"
+	"\x89\x02\x81\x81\x00\xd2\x41\x7a\xf8\x4b\x55\xb2\xaf\x11\xf9\x43"
+	"\x9b\x43\x81\x09\x3b\x9a\x94\xcf\x00\xf4\x85\x75\x92\xd7\x2a\xa5"
+	"\x11\xf1\xa8\x50\x6e\xc6\x84\x74\x24\x17\xda\x84\xc8\x03\x37\xb2"
+	"\x20\xf3\xba\xb5\x59\x36\x21\x4d\xab\x70\xe2\xc3\x09\x93\x68\x14"
+	"\x12\x79\xc5\xbb\x9e\x1b\x4a\xf0\xc6\x24\x59\x25\xc3\x1c\xa8\x70"
+	"\x66\x5b\x3e\x41\x8e\xe3\x25\x71\x9a\x94\xa0\x5b\x46\x91\x6f\xdd"
+	"\x58\x14\xec\x89\xe5\x8c\x96\xc5\x38\x60\xe4\xab\xf2\x75\xee\x6e"
+	"\x62\xfc\xe1\xbd\x03\x47\xff\xc4\xbe\x0f\xca\x70\x73\xe3\x74\x58"
+	"\x3a\x2f\x04\x2d\x39\x02\x03\x01\x00\x01\xa3\x81\x98\x30\x81\x95"
+	"\x30\x09\x06\x03\x55\x1d\x13\x04\x02\x30\x00\x30\x0b\x06\x03\x55"
+	"\x1d\x0f\x04\x04\x03\x02\x05\xe0\x30\x12\x06\x03\x55\x1d\x25\x04"
+	"\x0b\x30\x09\x06\x07\x2b\x06\x01\x05\x02\x03\x05\x30\x1d\x06\x03"
+	"\x55\x1d\x0e\x04\x16\x04\x14\x3a\xd3\x73\xff\xab\xdb\x7d\x8d\xc6"
+	"\x3a\xa2\x26\x3e\xae\x78\x95\x80\xc9\xe6\x31\x30\x48\x06\x03\x55"
+	"\x1d\x11\x04\x41\x30\x3f\xa0\x3d\x06\x06\x2b\x06\x01\x05\x02\x02"
+	"\xa0\x33\x30\x31\xa0\x0d\x1b\x0b\x54\x45\x53\x54\x2e\x48\x35\x4c"
+	"\x2e\x53\x45\xa1\x20\x30\x1e\xa0\x03\x02\x01\x01\xa1\x17\x30\x15"
+	"\x1b\x06\x6b\x72\x62\x74\x67\x74\x1b\x0b\x54\x45\x53\x54\x2e\x48"
+	"\x35\x4c\x2e\x53\x45\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01"
+	"\x01\x05\x05\x00\x03\x81\x81\x00\x83\xf4\x14\xa7\x6e\x59\xff\x80"
+	"\x64\xe7\xfa\xcf\x13\x80\x86\xe1\xed\x02\x38\xad\x96\x72\x25\xe5"
+	"\x06\x7a\x9a\xbc\x24\x74\xa9\x75\x55\xb2\x49\x80\x69\x45\x95\x4a"
+	"\x4c\x76\xa9\xe3\x4e\x49\xd3\xc2\x69\x5a\x95\x03\xeb\xba\x72\x23"
+	"\x9c\xfd\x3d\x8b\xc6\x07\x82\x3b\xf4\xf3\xef\x6c\x2e\x9e\x0b\xac"
+	"\x9e\x6c\xbb\x37\x4a\xa1\x9e\x73\xd1\xdc\x97\x61\xba\xfc\xd3\x49"
+	"\xa6\xc2\x4c\x55\x2e\x06\x37\x76\xb5\xef\x57\xe7\x57\x58\x8a\x71"
+	"\x63\xf3\xeb\xe7\x55\x68\x0d\xf6\x46\x4c\xfb\xf9\x43\xbb\x0c\x92"
+	"\x4f\x4e\x22\x7b\x63\xe8\x4f\x9c",
+	600
+    }
+};
+
+static int
+test_cert(void)
+{
+    Certificate c, c2;
+    size_t size;
+    size_t i;
+    int ret;
+
+    for (i =3D 0; i < sizeof(certs)/sizeof(certs[0]); i++) {
+
+	ret =3D decode_Certificate((unsigned char *)certs[i].cert,
+				 certs[i].len, &c, &size);
+	if (ret)
+	    return ret;
+
+	ret =3D copy_Certificate(&c, &c2);
+	free_Certificate(&c);
+	if (ret)
+	    return ret;
+
+	free_Certificate(&c2);
+    }
+
+    return 0;
+}
+
+
+static int
 cmp_TESTLargeTag (void *a, void *b)
 {
     TESTLargeTag *aa =3D a;
     TESTLargeTag *ab =3D b;
=20
     COMPARE_INTEGER(aa,ab,foo);
+    COMPARE_INTEGER(aa,ab,bar);
     return 0;
 }
=20
@@ -448,7 +684,7 @@
 test_large_tag (void)
 {
     struct test_case tests[] =3D {
-	{ NULL,  8,  "\x30\x06\xbf\x7f\x03\x02\x01\x01", "large tag 1" }
+	{ NULL,  15,  "\x30\x0d\xbf\x7f\x03\x02\x01\x01\xbf\x81\x00\x03\x02\x01\x=
02", "large tag 1" }
     };
=20
     int ntests =3D sizeof(tests) / sizeof(*tests);
@@ -456,6 +692,7 @@
=20
     memset(&lt1, 0, sizeof(lt1));
     lt1.foo =3D 1;
+    lt1.bar =3D 2;
=20
     tests[0].val =3D &lt1;
=20
@@ -464,7 +701,8 @@
 			 (generic_length)length_TESTLargeTag,
 			 (generic_decode)decode_TESTLargeTag,
 			 (generic_free)free_TESTLargeTag,
-			 cmp_TESTLargeTag);
+			 cmp_TESTLargeTag,
+			 (generic_copy)copy_TESTLargeTag);
 }
=20
 struct test_data {
@@ -490,9 +728,9 @@
 	{ 0, 5, 0, "\x02\xff\x7f\x02\x00"}
     };
     size_t sz;
-    krb5uint32 values[] =3D {0, 127, 128, 256, 512,
+    TESTuint32 values[] =3D {0, 127, 128, 256, 512,
 			 0, 127, 128, 256, 512 };
-    krb5uint32 u;
+    TESTuint32 u;
     int i, ret, failed =3D 0;
     void *buf;
=20
@@ -501,7 +739,7 @@
=20
 	buf =3D map_alloc(OVERRUN, td[i].data, td[i].len, &page);
=20
-	ret =3D decode_krb5uint32(buf, td[i].len, &u, &sz);
+	ret =3D decode_TESTuint32(buf, td[i].len, &u, &sz);
 	if (ret) {
 	    if (td[i].ok) {
 		printf("failed with tag len test %d\n", i);
@@ -560,7 +798,8 @@
 			 (generic_length)length_TESTChoice1,
 			 (generic_decode)decode_TESTChoice1,
 			 (generic_free)free_TESTChoice1,
-			 cmp_TESTChoice);
+			 cmp_TESTChoice,
+			 (generic_copy)copy_TESTChoice1);
=20
     memset(&c2_2, 0, sizeof(c2_2));
     c2_2.element =3D choice_TESTChoice2_asn1_ellipsis;
@@ -573,7 +812,8 @@
 			 (generic_length)length_TESTChoice2,
 			 (generic_decode)decode_TESTChoice2,
 			 (generic_free)free_TESTChoice2,
-			 cmp_TESTChoice);
+			 cmp_TESTChoice,
+			 (generic_copy)copy_TESTChoice2);
=20
     return ret;
 }
@@ -603,9 +843,9 @@
 test_implicit (void)
 {
     struct test_case tests[] =3D {
-	{ NULL,  16, =20
+	{ NULL,  16,
 	  "\x30\x0e\x80\x01\x00\xa1\x06\xbf"
-	  "\x7f\x03\x02\x01\x02\x82\x01\x03",=20
+	  "\x7f\x03\x02\x01\x02\x82\x01\x03",
 	  "implicit 1" }
     };
=20
@@ -623,7 +863,8 @@
 			 (generic_length)length_TESTImplicit,
 			 (generic_decode)decode_TESTImplicit,
 			 (generic_free)free_TESTImplicit,
-			 cmp_TESTImplicit);
+			 cmp_TESTImplicit,
+			 (generic_copy)copy_TESTImplicit);
=20
 #ifdef IMPLICIT_TAGGING_WORKS
     ret +=3D generic_test (tests, ntests, sizeof(TESTImplicit2),
@@ -631,7 +872,8 @@
 			 (generic_length)length_TESTImplicit2,
 			 (generic_decode)decode_TESTImplicit2,
 			 (generic_free)free_TESTImplicit2,
-			 cmp_TESTImplicit);
+			 cmp_TESTImplicit,
+			 NULL);
=20
 #endif /* IMPLICIT_TAGGING_WORKS */
     return ret;
@@ -679,14 +921,14 @@
 test_taglessalloc (void)
 {
     struct test_case tests[] =3D {
-	{ NULL,  14, =20
-	  "\x30\x0c\x30\x05\xa0\x03\x02\x01\x01\xa1\x03\x02\x01\x03",=20
+	{ NULL,  14,
+	  "\x30\x0c\x30\x05\xa0\x03\x02\x01\x01\xa1\x03\x02\x01\x03",
 	  "alloc 1" },
-	{ NULL,  7, =20
-	  "\x30\x05\xa1\x03\x02\x01\x03",=20
+	{ NULL,  7,
+	  "\x30\x05\xa1\x03\x02\x01\x03",
 	  "alloc 2" },
-	{ NULL,  10, =20
-	  "\x30\x08\xa1\x03\x02\x01\x04\x02\x01\x05",=20
+	{ NULL,  10,
+	  "\x30\x08\xa1\x03\x02\x01\x04\x02\x01\x05",
 	  "alloc 3" }
     };
=20
@@ -718,13 +960,95 @@
 			 (generic_length)length_TESTAlloc,
 			 (generic_decode)decode_TESTAlloc,
 			 (generic_free)free_TESTAlloc,
-			 cmp_TESTAlloc);
+			 cmp_TESTAlloc,
+			 (generic_copy)copy_TESTAlloc);
=20
     free(c1.tagless);
=20
     return ret;
 }
=20
+static int
+cmp_TESTOptional (void *a, void *b)
+{
+    TESTOptional *aa =3D a;
+    TESTOptional *ab =3D b;
+
+    IF_OPT_COMPARE(aa,ab,zero) {
+	COMPARE_OPT_INTEGER(aa,ab,zero);
+    }
+    IF_OPT_COMPARE(aa,ab,one) {
+	COMPARE_OPT_INTEGER(aa,ab,one);
+    }
+    return 0;
+}
+
+/*
+UNIV CONS Sequence 5
+  CONTEXT CONS 0 3
+    UNIV PRIM Integer 1 00
+
+UNIV CONS Sequence 5
+  CONTEXT CONS 1 3
+    UNIV PRIM Integer 1 03
+
+UNIV CONS Sequence 10
+  CONTEXT CONS 0 3
+    UNIV PRIM Integer 1 00
+  CONTEXT CONS 1 3
+    UNIV PRIM Integer 1 01
+
+*/
+
+static int
+test_optional (void)
+{
+    struct test_case tests[] =3D {
+	{ NULL,  2,
+	  "\x30\x00",
+	  "optional 0" },
+	{ NULL,  7,
+	  "\x30\x05\xa0\x03\x02\x01\x00",
+	  "optional 1" },
+	{ NULL,  7,
+	  "\x30\x05\xa1\x03\x02\x01\x01",
+	  "optional 2" },
+	{ NULL,  12,
+	  "\x30\x0a\xa0\x03\x02\x01\x00\xa1\x03\x02\x01\x01",
+	  "optional 3" }
+    };
+
+    int ret =3D 0, ntests =3D sizeof(tests) / sizeof(*tests);
+    TESTOptional c0, c1, c2, c3;
+    int zero =3D 0;
+    int one =3D 1;
+
+    c0.zero =3D NULL;
+    c0.one =3D NULL;
+    tests[0].val =3D &c0;
+
+    c1.zero =3D &zero;
+    c1.one =3D NULL;
+    tests[1].val =3D &c1;
+
+    c2.zero =3D NULL;
+    c2.one =3D &one;
+    tests[2].val =3D &c2;
+
+    c3.zero =3D &zero;
+    c3.one =3D &one;
+    tests[3].val =3D &c3;
+
+    ret +=3D generic_test (tests, ntests, sizeof(TESTOptional),
+			 (generic_encode)encode_TESTOptional,
+			 (generic_length)length_TESTOptional,
+			 (generic_decode)decode_TESTOptional,
+			 (generic_free)free_TESTOptional,
+			 cmp_TESTOptional,
+			 (generic_copy)copy_TESTOptional);
+
+    return ret;
+}
=20
 static int
 check_fail_largetag(void)
@@ -768,7 +1092,7 @@
 {
     struct test_case tests[] =3D {
 	{NULL, 0, "", "empty buffer"},
-	{NULL, 24,=20
+	{NULL, 24,
 	 "\x30\x16\xa0\x03\x02\x01\x01\xa1\x08\x30\x06\xbf\x7f\x03\x02\x01\x01"
 	 "\x02\x01\x01\xa2\x03\x02\x01\x01"
 	 "missing one byte from the end, internal length ok"},
@@ -776,7 +1100,7 @@
 	 "\x30\x18\xa0\x03\x02\x01\x01\xa1\x08\x30\x06\xbf\x7f\x03\x02\x01\x01"
 	 "\x02\x01\x01\xa2\x03\x02\x01\x01",
 	 "inner length one byte too long"},
-	{NULL, 24,=20
+	{NULL, 24,
 	 "\x30\x17\xa0\x03\x02\x01\x01\xa1\x08\x30\x06\xbf\x7f\x03\x02\x01"
 	 "\x01\x02\x01\x01\xa2\x03\x02\x01\x01",
 	 "correct buffer but missing one too short"}
@@ -793,10 +1117,10 @@
     struct test_case tests[] =3D {
 	{NULL, 6,
 	 "\xa1\x02\x02\x01\x01",
-	 "one too short"},
+	 "choice one too short"},
 	{NULL, 6,
 	 "\xa1\x03\x02\x02\x01",
-	 "one too short inner"}
+	 "choice one too short inner"}
     };
     int ntests =3D sizeof(tests) / sizeof(*tests);
=20
@@ -877,6 +1201,7 @@
 static int
 check_seq_of_size(void)
 {
+#if 0 /* template */
     TESTInteger integers[4] =3D { 1, 2, 3, 4 };
     int ret;
=20
@@ -894,7 +1219,7 @@
 	TESTSeqSizeOf2 ssof2ok1 =3D { 1, integers };
 	TESTSeqSizeOf2 ssof2ok2 =3D { 2, integers };
 	TESTSeqSizeOf2 ssof2f2 =3D { 3, integers };
-=09
+
 	test_seq_of(TESTSeqSizeOf2, 0, &ssof2f1);
 	test_seq_of(TESTSeqSizeOf2, 1, &ssof2ok1);
 	test_seq_of(TESTSeqSizeOf2, 1, &ssof2ok2);
@@ -904,7 +1229,7 @@
 	TESTSeqSizeOf3 ssof3f1 =3D { 0, NULL };
 	TESTSeqSizeOf3 ssof3ok1 =3D { 1, integers };
 	TESTSeqSizeOf3 ssof3ok2 =3D { 2, integers };
-=09
+
 	test_seq_of(TESTSeqSizeOf3, 0, &ssof3f1);
 	test_seq_of(TESTSeqSizeOf3, 1, &ssof3ok1);
 	test_seq_of(TESTSeqSizeOf3, 1, &ssof3ok2);
@@ -914,17 +1239,42 @@
 	TESTSeqSizeOf4 ssof4ok2 =3D { 1, integers };
 	TESTSeqSizeOf4 ssof4ok3 =3D { 2, integers };
 	TESTSeqSizeOf4 ssof4f1  =3D { 3, integers };
-=09
+
 	test_seq_of(TESTSeqSizeOf4, 1, &ssof4ok1);
-	test_seq_of(TESTSeqSizeOf4, 1, &ssof4ok2);=20
+	test_seq_of(TESTSeqSizeOf4, 1, &ssof4ok2);
 	test_seq_of(TESTSeqSizeOf4, 1, &ssof4ok3);
 	test_seq_of(TESTSeqSizeOf4, 0, &ssof4f1);
    }
-
+#endif
     return 0;
 }
=20
+static int
+check_TESTMechTypeList(void)
+{
+    TESTMechTypeList tl;
+    unsigned oid1[] =3D  { 1, 2, 840, 48018, 1, 2, 2};
+    unsigned oid2[] =3D  { 1, 2, 840, 113554, 1, 2, 2};
+    unsigned oid3[] =3D   { 1, 3, 6, 1, 4, 1, 311, 2, 2, 30};
+    unsigned oid4[] =3D   { 1, 3, 6, 1, 4, 1, 311, 2, 2, 10};
+    TESTMechType array[] =3D {{ 7, oid1 },
+                            { 7, oid2 },
+                            { 10, oid3 },
+                            { 10, oid4 }};
+    size_t size, len;
+    void *ptr;
+    int ret;
=20
+    tl.len =3D 4;
+    tl.val =3D array;
+
+    ASN1_MALLOC_ENCODE(TESTMechTypeList, ptr, len, &tl, &size, ret);
+    if (ret)
+	errx(1, "TESTMechTypeList: %d", ret);
+    if (len !=3D size)
+	abort();
+    return 0;
+}
=20
 int
 main(int argc, char **argv)
@@ -936,6 +1286,9 @@
     ret +=3D test_krb_error();
     ret +=3D test_Name();
     ret +=3D test_bit_string();
+    ret +=3D test_bit_string_rfc1510();
+    ret +=3D test_time();
+    ret +=3D test_cert();
=20
     ret +=3D check_tag_length();
     ret +=3D test_large_tag();
@@ -943,6 +1296,7 @@
=20
     ret +=3D test_implicit();
     ret +=3D test_taglessalloc();
+    ret +=3D test_optional();
=20
     ret +=3D check_fail_largetag();
     ret +=3D check_fail_sequence();
@@ -951,5 +1305,7 @@
     ret +=3D check_seq();
     ret +=3D check_seq_of_size();
=20
+    ret +=3D check_TESTMechTypeList();
+
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/check-tim=
egm.c
--- a/head/crypto/heimdal/lib/asn1/check-timegm.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/asn1/check-timegm.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include <der_locl.h>
=20
-RCSID("$Id: check-timegm.c 18610 2006-10-19 16:33:24Z lha $");
+RCSID("$Id$");
=20
 static int
 test_timegm(void)
@@ -58,6 +58,15 @@
     if (t !=3D -1)
 	ret +=3D 1;
=20
+    _der_gmtime(1159696980, &tm);
+    if (tm.tm_year !=3D 106 ||
+	tm.tm_mon !=3D 9 ||
+	tm.tm_mday !=3D 1 ||
+	tm.tm_hour !=3D 10 ||
+	tm.tm_min !=3D 3 ||
+	tm.tm_sec !=3D 0)
+      errx(1, "tmtime failes");
+
     return ret;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der-proto=
s.h
--- a/head/crypto/heimdal/lib/asn1/der-protos.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/der-protos.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -48,14 +48,24 @@
 	heim_general_string */*to*/);
=20
 int
+der_copy_generalized_time (
+	const time_t */*from*/,
+	time_t */*to*/);
+
+int
 der_copy_heim_integer (
 	const heim_integer */*from*/,
 	heim_integer */*to*/);
=20
 int
 der_copy_ia5_string (
-	const heim_printable_string */*from*/,
-	heim_printable_string */*to*/);
+	const heim_ia5_string */*from*/,
+	heim_ia5_string */*to*/);
+
+int
+der_copy_integer (
+	const int */*from*/,
+	int */*to*/);
=20
 int
 der_copy_octet_string (
@@ -78,6 +88,16 @@
 	heim_universal_string */*to*/);
=20
 int
+der_copy_unsigned (
+	const unsigned */*from*/,
+	unsigned */*to*/);
+
+int
+der_copy_utctime (
+	const time_t */*from*/,
+	time_t */*to*/);
+
+int
 der_copy_utf8string (
 	const heim_utf8_string */*from*/,
 	heim_utf8_string */*to*/);
@@ -97,12 +117,18 @@
 der_free_general_string (heim_general_string */*str*/);
=20
 void
+der_free_generalized_time (time_t */*t*/);
+
+void
 der_free_heim_integer (heim_integer */*k*/);
=20
 void
 der_free_ia5_string (heim_ia5_string */*str*/);
=20
 void
+der_free_integer (int */*i*/);
+
+void
 der_free_octet_string (heim_octet_string */*k*/);
=20
 void
@@ -115,6 +141,12 @@
 der_free_universal_string (heim_universal_string */*k*/);
=20
 void
+der_free_unsigned (unsigned */*u*/);
+
+void
+der_free_utctime (time_t */*t*/);
+
+void
 der_free_utf8string (heim_utf8_string */*str*/);
=20
 void
@@ -197,6 +229,13 @@
 	size_t */*size*/);
=20
 int
+der_get_octet_string_ber (
+	const unsigned char */*p*/,
+	size_t /*len*/,
+	heim_octet_string */*data*/,
+	size_t */*size*/);
+
+int
 der_get_oid (
 	const unsigned char */*p*/,
 	size_t /*len*/,
@@ -296,6 +335,11 @@
 	const heim_universal_string */*p*/,
 	const heim_universal_string */*q*/);
=20
+int
+der_ia5_string_cmp (
+	const heim_ia5_string */*p*/,
+	const heim_ia5_string */*q*/);
+
 size_t
 der_length_bit_string (const heim_bit_string */*k*/);
=20
@@ -336,6 +380,9 @@
 der_length_printable_string (const heim_printable_string */*data*/);
=20
 size_t
+der_length_tag (unsigned int /*tag*/);
+
+size_t
 der_length_universal_string (const heim_universal_string */*data*/);
=20
 size_t
@@ -360,11 +407,20 @@
 	size_t */*size*/);
=20
 int
+der_match_tag2 (
+	const unsigned char */*p*/,
+	size_t /*len*/,
+	Der_class /*class*/,
+	Der_type */*type*/,
+	unsigned int /*tag*/,
+	size_t */*size*/);
+
+int
 der_match_tag_and_length (
 	const unsigned char */*p*/,
 	size_t /*len*/,
 	Der_class /*class*/,
-	Der_type /*type*/,
+	Der_type */*type*/,
 	unsigned int /*tag*/,
 	size_t */*length_ret*/,
 	size_t */*size*/);
@@ -392,6 +448,11 @@
 	char **/*p*/);
=20
 int
+der_printable_string_cmp (
+	const heim_printable_string */*p*/,
+	const heim_printable_string */*q*/);
+
+int
 der_put_bit_string (
 	unsigned char */*p*/,
 	size_t /*len*/,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der.c
--- a/head/crypto/heimdal/lib/asn1/der.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
@@ -38,7 +38,7 @@
 #include <getarg.h>
 #include <err.h>
=20
-RCSID("$Id: der.c 22429 2008-01-13 10:25:50Z lha $");
+RCSID("$Id$");
=20
=20
 static const char *class_names[] =3D {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der.h
--- a/head/crypto/heimdal/lib/asn1/der.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: der.h 18437 2006-10-14 05:16:08Z lha $ */
+/* $Id$ */
=20
 #ifndef __DER_H__
 #define __DER_H__
@@ -52,7 +52,7 @@
 enum {
     UT_EndOfContent	=3D 0,
     UT_Boolean		=3D 1,
-    UT_Integer		=3D 2,=09
+    UT_Integer		=3D 2,
     UT_BitString	=3D 3,
     UT_OctetString	=3D 4,
     UT_Null		=3D 5,
@@ -94,6 +94,8 @@
     int bt_zone;
 } heim_ber_time_t;
=20
+struct asn1_template;
+
 #include <der-protos.h>
=20
 int _heim_fix_dce(size_t reallen, size_t *len);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_cmp.c
--- a/head/crypto/heimdal/lib/asn1/der_cmp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der_cmp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2003-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
@@ -38,13 +38,13 @@
 {
     if (p->length !=3D q->length)
 	return p->length - q->length;
-    return memcmp(p->components,=20
+    return memcmp(p->components,
 		  q->components,
 		  p->length * sizeof(*p->components));
 }
=20
 int
-der_heim_octet_string_cmp(const heim_octet_string *p,=20
+der_heim_octet_string_cmp(const heim_octet_string *p,
 			  const heim_octet_string *q)
 {
     if (p->length !=3D q->length)
@@ -53,6 +53,20 @@
 }
=20
 int
+der_printable_string_cmp(const heim_printable_string *p,
+			 const heim_printable_string *q)
+{
+    return der_heim_octet_string_cmp(p, q);
+}
+
+int
+der_ia5_string_cmp(const heim_ia5_string *p,
+		   const heim_ia5_string *q)
+{
+    return der_heim_octet_string_cmp(p, q);
+}
+
+int
 der_heim_bit_string_cmp(const heim_bit_string *p,
 			const heim_bit_string *q)
 {
@@ -93,7 +107,7 @@
 }
=20
 int
-der_heim_universal_string_cmp(const heim_universal_string *p,=20
+der_heim_universal_string_cmp(const heim_universal_string *p,
 			      const heim_universal_string *q)
 {
     if (p->length !=3D q->length)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_copy.c
--- a/head/crypto/heimdal/lib/asn1/der_copy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der_copy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,44 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
=20
-RCSID("$Id: der_copy.c 19539 2006-12-28 17:15:05Z lha $");
+RCSID("$Id$");
=20
 int
-der_copy_general_string (const heim_general_string *from,=20
+der_copy_general_string (const heim_general_string *from,
 			 heim_general_string *to)
 {
     *to =3D strdup(*from);
@@ -46,23 +48,57 @@
 }
=20
 int
+der_copy_integer (const int *from, int *to)
+{
+    *to =3D *from;
+    return 0;
+}
+
+int
+der_copy_unsigned (const unsigned *from, unsigned *to)
+{
+    *to =3D *from;
+    return 0;
+}
+
+int
+der_copy_generalized_time (const time_t *from, time_t *to)
+{
+    *to =3D *from;
+    return 0;
+}
+
+int
+der_copy_utctime (const time_t *from, time_t *to)
+{
+    *to =3D *from;
+    return 0;
+}
+
+int
 der_copy_utf8string (const heim_utf8_string *from, heim_utf8_string *to)
 {
     return der_copy_general_string(from, to);
 }
=20
 int
-der_copy_printable_string (const heim_printable_string *from,=20
+der_copy_printable_string (const heim_printable_string *from,
 		       heim_printable_string *to)
 {
-    return der_copy_general_string(from, to);
+    to->length =3D from->length;
+    to->data   =3D malloc(to->length + 1);
+    if(to->data =3D=3D NULL)
+	return ENOMEM;
+    memcpy(to->data, from->data, to->length);
+    ((char *)to->data)[to->length] =3D '\0';
+    return 0;
 }
=20
 int
-der_copy_ia5_string (const heim_printable_string *from,=20
-		     heim_printable_string *to)
+der_copy_ia5_string (const heim_ia5_string *from,
+		     heim_ia5_string *to)
 {
-    return der_copy_general_string(from, to);
+    return der_copy_printable_string(from, to);
 }
=20
 int
@@ -89,7 +125,7 @@
 }
=20
 int
-der_copy_visible_string (const heim_visible_string *from,=20
+der_copy_visible_string (const heim_visible_string *from,
 			 heim_visible_string *to)
 {
     return der_copy_general_string(from, to);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_forma=
t.c
--- a/head/crypto/heimdal/lib/asn1/der_format.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/der_format.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
 #include <hex.h>
=20
-RCSID("$Id: der_format.c 20861 2007-06-03 20:18:29Z lha $");
+RCSID("$Id$");
=20
 int
 der_parse_hex_heim_integer (const char *p, heim_integer *data)
@@ -56,7 +56,7 @@
 	data->length =3D 0;
 	return EINVAL;
     }
-   =20
+
     data->length =3D (len / 2) + 1;
     data->data =3D malloc(data->length);
     if (data->data =3D=3D NULL) {
@@ -108,7 +108,7 @@
 der_print_heim_oid (const heim_oid *oid, char delim, char **str)
 {
     struct rk_strpool *p =3D NULL;
-    int i;
+    size_t i;
=20
     if (oid->length =3D=3D 0)
 	return EINVAL;
@@ -144,8 +144,8 @@
=20
     s =3D strdup(str);
=20
-    for (w =3D strtok_r(s, sep, &brkt);=20
-	 w !=3D NULL;=20
+    for (w =3D strtok_r(s, sep, &brkt);
+	 w !=3D NULL;
 	 w =3D strtok_r(NULL, sep, &brkt)) {
=20
 	c =3D realloc(data->components,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_free.c
--- a/head/crypto/heimdal/lib/asn1/der_free.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der_free.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,41 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
=20
-RCSID("$Id: der_free.c 19539 2006-12-28 17:15:05Z lha $");
+RCSID("$Id$");
=20
 void
 der_free_general_string (heim_general_string *str)
@@ -43,6 +45,31 @@
 }
=20
 void
+der_free_integer (int *i)
+{
+    *i =3D 0;
+}
+
+void
+der_free_unsigned (unsigned *u)
+{
+    *u =3D 0;
+}
+
+void
+der_free_generalized_time(time_t *t)
+{
+    *t =3D 0;
+}
+
+void
+der_free_utctime(time_t *t)
+{
+    *t =3D 0;
+}
+
+
+void
 der_free_utf8string (heim_utf8_string *str)
 {
     free(*str);
@@ -52,15 +79,13 @@
 void
 der_free_printable_string (heim_printable_string *str)
 {
-    free(*str);
-    *str =3D NULL;
+    der_free_octet_string(str);
 }
=20
 void
 der_free_ia5_string (heim_ia5_string *str)
 {
-    free(*str);
-    *str =3D NULL;
+    der_free_octet_string(str);
 }
=20
 void
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_get.c
--- a/head/crypto/heimdal/lib/asn1/der_get.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der_get.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,39 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
=20
-RCSID("$Id: der_get.c 21369 2007-06-27 10:14:39Z lha $");
-
-#include <version.h>
-
-/*=20
+/*
  * All decoding functions take a pointer `p' to first position in
  * which to read, from the left, `len' which means the maximum number
  * of characters we are able to read, `ret' were the value will be
@@ -132,7 +128,7 @@
 }
=20
 int
-der_get_general_string (const unsigned char *p, size_t len,=20
+der_get_general_string (const unsigned char *p, size_t len,
 			heim_general_string *str, size_t *size)
 {
     const unsigned char *p1;
@@ -140,14 +136,14 @@
=20
     p1 =3D memchr(p, 0, len);
     if (p1 !=3D NULL) {
-	/*=20
+	/*
 	 * Allow trailing NULs. We allow this since MIT Kerberos sends
 	 * an strings in the NEED_PREAUTH case that includes a
 	 * trailing NUL.
 	 */
-	while (p1 - p < len && *p1 =3D=3D '\0')
+	while ((size_t)(p1 - p) < len && *p1 =3D=3D '\0')
 	    p1++;
-       if (p1 - p !=3D len)
+       if ((size_t)(p1 - p) !=3D len)
 	    return ASN1_BAD_CHARACTER;
     }
     if (len > len + 1)
@@ -164,28 +160,35 @@
 }
=20
 int
-der_get_utf8string (const unsigned char *p, size_t len,=20
+der_get_utf8string (const unsigned char *p, size_t len,
 		    heim_utf8_string *str, size_t *size)
 {
     return der_get_general_string(p, len, str, size);
 }
=20
 int
-der_get_printable_string (const unsigned char *p, size_t len,=20
-			  heim_printable_string *str, size_t *size)
+der_get_printable_string(const unsigned char *p, size_t len,
+			 heim_printable_string *str, size_t *size)
 {
-    return der_get_general_string(p, len, str, size);
+    str->length =3D len;
+    str->data =3D malloc(len + 1);
+    if (str->data =3D=3D NULL)
+	return ENOMEM;
+    memcpy(str->data, p, len);
+    ((char *)str->data)[len] =3D '\0';
+    if(size) *size =3D len;
+    return 0;
 }
=20
 int
-der_get_ia5_string (const unsigned char *p, size_t len,=20
-		    heim_ia5_string *str, size_t *size)
+der_get_ia5_string(const unsigned char *p, size_t len,
+		   heim_ia5_string *str, size_t *size)
 {
-    return der_get_general_string(p, len, str, size);
+    return der_get_printable_string(p, len, str, size);
 }
=20
 int
-der_get_bmp_string (const unsigned char *p, size_t len,=20
+der_get_bmp_string (const unsigned char *p, size_t len,
 		    heim_bmp_string *data, size_t *size)
 {
     size_t i;
@@ -202,6 +205,13 @@
     for (i =3D 0; i < data->length; i++) {
 	data->data[i] =3D (p[0] << 8) | p[1];
 	p +=3D 2;
+	/* check for NUL in the middle of the string */
+	if (data->data[i] =3D=3D 0 && i !=3D (data->length - 1)) {
+	    free(data->data);
+	    data->data =3D NULL;
+	    data->length =3D 0;
+	    return ASN1_BAD_CHARACTER;
+	}
     }
     if (size) *size =3D len;
=20
@@ -209,7 +219,7 @@
 }
=20
 int
-der_get_universal_string (const unsigned char *p, size_t len,=20
+der_get_universal_string (const unsigned char *p, size_t len,
 			  heim_universal_string *data, size_t *size)
 {
     size_t i;
@@ -226,20 +236,27 @@
     for (i =3D 0; i < data->length; i++) {
 	data->data[i] =3D (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
 	p +=3D 4;
+	/* check for NUL in the middle of the string */
+	if (data->data[i] =3D=3D 0 && i !=3D (data->length - 1)) {
+	    free(data->data);
+	    data->data =3D NULL;
+	    data->length =3D 0;
+	    return ASN1_BAD_CHARACTER;
+	}
     }
     if (size) *size =3D len;
     return 0;
 }
=20
 int
-der_get_visible_string (const unsigned char *p, size_t len,=20
+der_get_visible_string (const unsigned char *p, size_t len,
 			heim_visible_string *str, size_t *size)
 {
     return der_get_general_string(p, len, str, size);
 }
=20
 int
-der_get_octet_string (const unsigned char *p, size_t len,=20
+der_get_octet_string (const unsigned char *p, size_t len,
 		      heim_octet_string *data, size_t *size)
 {
     data->length =3D len;
@@ -252,7 +269,76 @@
 }
=20
 int
-der_get_heim_integer (const unsigned char *p, size_t len,=20
+der_get_octet_string_ber (const unsigned char *p, size_t len,
+			  heim_octet_string *data, size_t *size)
+{
+    int e;
+    Der_type type;
+    Der_class class;
+    unsigned int tag, depth =3D 0;
+    size_t l, datalen, oldlen =3D len;
+
+    data->length =3D 0;
+    data->data =3D NULL;
+
+    while (len) {
+	e =3D der_get_tag (p, len, &class, &type, &tag, &l);
+	if (e) goto out;
+	if (class !=3D ASN1_C_UNIV) {
+	    e =3D ASN1_BAD_ID;
+	    goto out;
+	}
+	if (type =3D=3D PRIM && tag =3D=3D UT_EndOfContent) {
+	    if (depth =3D=3D 0)
+		break;
+	    depth--;
+	}
+	if (tag !=3D UT_OctetString) {
+	    e =3D ASN1_BAD_ID;
+	    goto out;
+	}
+
+	p +=3D l;
+	len -=3D l;
+	e =3D der_get_length (p, len, &datalen, &l);
+	if (e) goto out;
+	p +=3D l;
+	len -=3D l;
+
+	if (datalen > len)
+	    return ASN1_OVERRUN;
+
+	if (type =3D=3D PRIM) {
+	    void *ptr;
+
+	    ptr =3D realloc(data->data, data->length + datalen);
+	    if (ptr =3D=3D NULL) {
+		e =3D ENOMEM;
+		goto out;
+	    }
+	    data->data =3D ptr;
+	    memcpy(((unsigned char *)data->data) + data->length, p, datalen);
+	    data->length +=3D datalen;
+	} else
+	    depth++;
+
+	p +=3D datalen;
+	len -=3D datalen;
+    }
+    if (depth !=3D 0)
+	return ASN1_INDEF_OVERRUN;
+    if(size) *size =3D oldlen - len;
+    return 0;
+ out:
+    free(data->data);
+    data->data =3D NULL;
+    data->length =3D 0;
+    return e;
+}
+
+
+int
+der_get_heim_integer (const unsigned char *p, size_t len,
 		      heim_integer *data, size_t *size)
 {
     data->length =3D 0;
@@ -338,7 +424,7 @@
 }
=20
 static int
-der_get_time (const unsigned char *p, size_t len,=20
+der_get_time (const unsigned char *p, size_t len,
 	      time_t *data, size_t *size)
 {
     char *times;
@@ -359,14 +445,14 @@
 }
=20
 int
-der_get_generalized_time (const unsigned char *p, size_t len,=20
+der_get_generalized_time (const unsigned char *p, size_t len,
 			  time_t *data, size_t *size)
 {
     return der_get_time(p, len, data, size);
 }
=20
 int
-der_get_utctime (const unsigned char *p, size_t len,=20
+der_get_utctime (const unsigned char *p, size_t len,
 			  time_t *data, size_t *size)
 {
     return der_get_time(p, len, data, size);
@@ -397,7 +483,7 @@
     ++p;
     for (n =3D 2; len > 0; ++n) {
 	unsigned u =3D 0, u1;
-=09
+
 	do {
 	    --len;
 	    u1 =3D u * 128 + (*p++ % 128);
@@ -457,15 +543,28 @@
 	       Der_class class, Der_type type,
 	       unsigned int tag, size_t *size)
 {
+    Der_type thistype;
+    int e;
+
+    e =3D der_match_tag2(p, len, class, &thistype, tag, size);
+    if (e) return e;
+    if (thistype !=3D type) return ASN1_BAD_ID;
+    return 0;
+}
+
+int
+der_match_tag2 (const unsigned char *p, size_t len,
+		Der_class class, Der_type *type,
+		unsigned int tag, size_t *size)
+{
     size_t l;
     Der_class thisclass;
-    Der_type thistype;
     unsigned int thistag;
     int e;
=20
-    e =3D der_get_tag (p, len, &thisclass, &thistype, &thistag, &l);
+    e =3D der_get_tag (p, len, &thisclass, type, &thistag, &l);
     if (e) return e;
-    if (class !=3D thisclass || type !=3D thistype)
+    if (class !=3D thisclass)
 	return ASN1_BAD_ID;
     if(tag > thistag)
 	return ASN1_MISPLACED_FIELD;
@@ -477,27 +576,26 @@
=20
 int
 der_match_tag_and_length (const unsigned char *p, size_t len,
-			  Der_class class, Der_type type, unsigned int tag,
+			  Der_class class, Der_type *type, unsigned int tag,
 			  size_t *length_ret, size_t *size)
 {
     size_t l, ret =3D 0;
     int e;
=20
-    e =3D der_match_tag (p, len, class, type, tag, &l);
+    e =3D der_match_tag2 (p, len, class, type, tag, &l);
     if (e) return e;
     p +=3D l;
     len -=3D l;
     ret +=3D l;
     e =3D der_get_length (p, len, length_ret, &l);
     if (e) return e;
-    p +=3D l;
-    len -=3D l;
-    ret +=3D l;
-    if(size) *size =3D ret;
+    if(size) *size =3D ret + l;
     return 0;
 }
=20
-/*=20
+
+
+/*
  * Old versions of DCE was based on a very early beta of the MIT code,
  * which used MAVROS for ASN.1 encoding. MAVROS had the interesting
  * feature that it encoded data in the forward direction, which has
@@ -507,7 +605,7 @@
  * to indefinite, BER style, lengths. The version of MAVROS used by
  * the DCE people could apparently generate correct X.509 DER encodings, a=
nd
  * did this by making space for the length after encoding, but
- * unfortunately this feature wasn't used with Kerberos.=20
+ * unfortunately this feature wasn't used with Kerberos.
  */
=20
 int
@@ -522,7 +620,7 @@
 }
=20
 int
-der_get_bit_string (const unsigned char *p, size_t len,=20
+der_get_bit_string (const unsigned char *p, size_t len,
 		    heim_bit_string *data, size_t *size)
 {
     if (len < 1)
@@ -539,8 +637,11 @@
     data->data =3D malloc(len - 1);
     if (data->data =3D=3D NULL && (len - 1) !=3D 0)
 	return ENOMEM;
-    memcpy (data->data, p + 1, len - 1);
-    data->length -=3D p[0];
+    /* copy data is there is data to copy */
+    if (len - 1 !=3D 0) {
+      memcpy (data->data, p + 1, len - 1);
+      data->length -=3D p[0];
+    }
     if(size) *size =3D len;
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_lengt=
h.c
--- a/head/crypto/heimdal/lib/asn1/der_length.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/der_length.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,46 +1,48 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
=20
-RCSID("$Id: der_length.c 19539 2006-12-28 17:15:05Z lha $");
+RCSID("$Id$");
=20
 size_t
 _heim_len_unsigned (unsigned val)
 {
     size_t ret =3D 0;
     int last_val_gt_128;
-   =20
+
     do {
 	++ret;
 	last_val_gt_128 =3D (val >=3D 128);
@@ -84,7 +86,7 @@
 len_oid (const heim_oid *oid)
 {
     size_t ret =3D 1;
-    int n;
+    size_t n;
=20
     for (n =3D 2; n < oid->length; ++n) {
 	unsigned u =3D oid->components[n];
@@ -113,6 +115,20 @@
 }
=20
 size_t
+der_length_tag(unsigned int tag)
+{
+    size_t len =3D 0;
+
+    if(tag <=3D 30)
+	return 1;
+    while(tag) {
+	tag /=3D 128;
+	len++;
+    }
+    return len + 1;
+}
+
+size_t
 der_length_integer (const int *data)
 {
     return _heim_len_int (*data);
@@ -145,13 +161,13 @@
 size_t
 der_length_printable_string (const heim_printable_string *data)
 {
-    return strlen(*data);
+    return data->length;
 }
=20
 size_t
 der_length_ia5_string (const heim_ia5_string *data)
 {
-    return strlen(*data);
+    return data->length;
 }
=20
 size_t
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_locl.h
--- a/head/crypto/heimdal/lib/asn1/der_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,44 @@
 /*
- * Copyright (c) 1997 - 2002, 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002, 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: der_locl.h 18608 2006-10-19 16:24:02Z lha $ */
+/* $Id$ */
=20
 #ifndef __DER_LOCL_H__
 #define __DER_LOCL_H__
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-#endif
+
 #include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -52,8 +52,11 @@
 #include <asn1-common.h>
 #include <asn1_err.h>
 #include <der.h>
+#include <der-private.h>
+#include "asn1-template.h"
=20
 time_t _der_timegm (struct tm *);
+struct tm * _der_gmtime(time_t t, struct tm *);
 size_t _heim_len_unsigned (unsigned);
 size_t _heim_len_int (int);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/der_put.c
--- a/head/crypto/heimdal/lib/asn1/der_put.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/der_put.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
=20
-RCSID("$Id: der_put.c 19539 2006-12-28 17:15:05Z lha $");
+RCSID("$Id$");
=20
 /*
  * All encoding functions take a pointer `p' to first position in
@@ -157,7 +157,7 @@
 }
=20
 int
-der_put_general_string (unsigned char *p, size_t len,=20
+der_put_general_string (unsigned char *p, size_t len,
 			const heim_general_string *str, size_t *size)
 {
     size_t slen =3D strlen(*str);
@@ -165,42 +165,40 @@
     if (len < slen)
 	return ASN1_OVERFLOW;
     p -=3D slen;
-    len -=3D slen;
     memcpy (p+1, *str, slen);
     *size =3D slen;
     return 0;
 }
=20
 int
-der_put_utf8string (unsigned char *p, size_t len,=20
+der_put_utf8string (unsigned char *p, size_t len,
 		    const heim_utf8_string *str, size_t *size)
 {
     return der_put_general_string(p, len, str, size);
 }
=20
 int
-der_put_printable_string (unsigned char *p, size_t len,=20
+der_put_printable_string (unsigned char *p, size_t len,
 			  const heim_printable_string *str, size_t *size)
 {
-    return der_put_general_string(p, len, str, size);
+    return der_put_octet_string(p, len, str, size);
 }
=20
 int
-der_put_ia5_string (unsigned char *p, size_t len,=20
+der_put_ia5_string (unsigned char *p, size_t len,
 		    const heim_ia5_string *str, size_t *size)
 {
-    return der_put_general_string(p, len, str, size);
+    return der_put_octet_string(p, len, str, size);
 }
=20
 int
-der_put_bmp_string (unsigned char *p, size_t len,=20
+der_put_bmp_string (unsigned char *p, size_t len,
 		    const heim_bmp_string *data, size_t *size)
 {
     size_t i;
     if (len / 2 < data->length)
 	return ASN1_OVERFLOW;
     p -=3D data->length * 2;
-    len -=3D data->length * 2;
     for (i =3D 0; i < data->length; i++) {
 	p[1] =3D (data->data[i] >> 8) & 0xff;
 	p[2] =3D data->data[i] & 0xff;
@@ -211,14 +209,13 @@
 }
=20
 int
-der_put_universal_string (unsigned char *p, size_t len,=20
+der_put_universal_string (unsigned char *p, size_t len,
 			  const heim_universal_string *data, size_t *size)
 {
     size_t i;
     if (len / 4 < data->length)
 	return ASN1_OVERFLOW;
     p -=3D data->length * 4;
-    len -=3D data->length * 4;
     for (i =3D 0; i < data->length; i++) {
 	p[1] =3D (data->data[i] >> 24) & 0xff;
 	p[2] =3D (data->data[i] >> 16) & 0xff;
@@ -231,27 +228,26 @@
 }
=20
 int
-der_put_visible_string (unsigned char *p, size_t len,=20
+der_put_visible_string (unsigned char *p, size_t len,
 			 const heim_visible_string *str, size_t *size)
 {
     return der_put_general_string(p, len, str, size);
 }
=20
 int
-der_put_octet_string (unsigned char *p, size_t len,=20
+der_put_octet_string (unsigned char *p, size_t len,
 		      const heim_octet_string *data, size_t *size)
 {
     if (len < data->length)
 	return ASN1_OVERFLOW;
     p -=3D data->length;
-    len -=3D data->length;
     memcpy (p+1, data->data, data->length);
     *size =3D data->length;
     return 0;
 }
=20
 int
-der_put_heim_integer (unsigned char *p, size_t len,=20
+der_put_heim_integer (unsigned char *p, size_t len,
 		     const heim_integer *data, size_t *size)
 {
     unsigned char *buf =3D data->data;
@@ -303,7 +299,7 @@
 }
=20
 int
-der_put_generalized_time (unsigned char *p, size_t len,=20
+der_put_generalized_time (unsigned char *p, size_t len,
 			  const time_t *data, size_t *size)
 {
     heim_octet_string k;
@@ -323,7 +319,7 @@
 }
=20
 int
-der_put_utctime (unsigned char *p, size_t len,=20
+der_put_utctime (unsigned char *p, size_t len,
 		 const time_t *data, size_t *size)
 {
     heim_octet_string k;
@@ -384,7 +380,7 @@
     } else {
 	size_t ret =3D 0;
 	unsigned int continuation =3D 0;
-=09
+
 	do {
 	    if (len < 1)
 		return ASN1_OVERFLOW;
@@ -405,7 +401,7 @@
=20
 int
 der_put_length_and_tag (unsigned char *p, size_t len, size_t len_val,
-			Der_class class, Der_type type,=20
+			Der_class class, Der_type type,
 			unsigned int tag, size_t *size)
 {
     size_t ret =3D 0;
@@ -421,8 +417,7 @@
     e =3D der_put_tag (p, len, class, type, tag, &l);
     if(e)
 	return e;
-    p -=3D l;
-    len -=3D l;
+
     ret +=3D l;
     *size =3D ret;
     return 0;
@@ -431,35 +426,36 @@
 int
 _heim_time2generalizedtime (time_t t, heim_octet_string *s, int gtimep)
 {
-     struct tm *tm;
+     struct tm tm;
      const size_t len =3D gtimep ? 15 : 13;
=20
      s->data =3D malloc(len + 1);
      if (s->data =3D=3D NULL)
 	 return ENOMEM;
      s->length =3D len;
-     tm =3D gmtime (&t);
+     if (_der_gmtime(t, &tm) =3D=3D NULL)
+	 return ASN1_BAD_TIMEFORMAT;
      if (gtimep)
-	 snprintf (s->data, len + 1, "%04d%02d%02d%02d%02d%02dZ",=20
-		   tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,=20
-		   tm->tm_hour, tm->tm_min, tm->tm_sec);
+	 snprintf (s->data, len + 1, "%04d%02d%02d%02d%02d%02dZ",
+		   tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
+		   tm.tm_hour, tm.tm_min, tm.tm_sec);
      else
-	 snprintf (s->data, len + 1, "%02d%02d%02d%02d%02d%02dZ",=20
-		   tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,=20
-		   tm->tm_hour, tm->tm_min, tm->tm_sec);
+	 snprintf (s->data, len + 1, "%02d%02d%02d%02d%02d%02dZ",
+		   tm.tm_year % 100, tm.tm_mon + 1, tm.tm_mday,
+		   tm.tm_hour, tm.tm_min, tm.tm_sec);
=20
      return 0;
 }
=20
 int
-der_put_bit_string (unsigned char *p, size_t len,=20
+der_put_bit_string (unsigned char *p, size_t len,
 		    const heim_bit_string *data, size_t *size)
 {
     size_t data_size =3D (data->length + 7) / 8;
     if (len < data_size + 1)
 	return ASN1_OVERFLOW;
     p -=3D data_size + 1;
-    len -=3D data_size + 1;
+
     memcpy (p+2, data->data, data_size);
     if (data->length && (data->length % 8) !=3D 0)
 	p[1] =3D 8 - (data->length % 8);
@@ -469,13 +465,13 @@
     return 0;
 }
=20
-int=20
+int
 _heim_der_set_sort(const void *a1, const void *a2)
 {
     const struct heim_octet_string *s1 =3D a1, *s2 =3D a2;
     int ret;
=20
-    ret =3D memcmp(s1->data, s2->data,=20
+    ret =3D memcmp(s1->data, s2->data,
 		 s1->length < s2->length ? s1->length : s2->length);
     if(ret)
 	return ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/digest.as=
n1
--- a/head/crypto/heimdal/lib/asn1/digest.asn1	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/digest.asn1	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
--- $Id: digest.asn1 22152 2007-12-04 19:59:18Z lha $
+-- $Id$
=20
 DIGEST DEFINITIONS ::=3D
 BEGIN
@@ -100,6 +100,21 @@
     tickets		[3] SEQUENCE OF OCTET STRING OPTIONAL
 }
=20
+NTLMRequest2 ::=3D SEQUENCE {
+    loginUserName	[0] UTF8String,
+    loginDomainName	[1] UTF8String,
+    flags		[2] INTEGER (0..4294967295),
+    lmchallenge		[3] OCTET STRING SIZE (8),
+    ntChallengeResponce [4] OCTET STRING,
+    lmChallengeResponce [5] OCTET STRING
+}
+
+NTLMReply ::=3D SEQUENCE {
+    success		[0] BOOLEAN,
+    flags		[1] INTEGER (0..4294967295),
+    sessionkey		[2] OCTET STRING OPTIONAL
+}
+
 DigestReqInner ::=3D CHOICE {
     init		[0] DigestInit,
     digestRequest	[1] DigestRequest,
@@ -139,7 +154,7 @@
 -- qop =3D=3D auth
 -- A2 =3D Method ":" digest-uri-value
 -- qop =3D=3D auth-int
--- A2 =3D Method ":" digest-uri-value ":" H(entity-body)=20
+-- A2 =3D Method ":" digest-uri-value ":" H(entity-body)
=20
 -- request-digest  =3D HEX(KD(HEX(H(A1)),
 --    unq(nonce-value) ":" nc-value ":" unq(cnonce-value) ":" unq(qop-valu=
e) ":" HEX(H(A2))))
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/extra.c
--- a/head/crypto/heimdal/lib/asn1/extra.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/extra.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,56 +1,52 @@
 /*
- * Copyright (c) 2003 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
 #include "heim_asn1.h"
=20
-RCSID("$Id: extra.c 16672 2006-01-31 09:44:54Z lha $");
+RCSID("$Id$");
=20
 int
-encode_heim_any(unsigned char *p, size_t len,=20
+encode_heim_any(unsigned char *p, size_t len,
 		const heim_any *data, size_t *size)
 {
-    if (data->length > len)
-	return ASN1_OVERFLOW;
-    p -=3D data->length;
-    len -=3D data->length;
-    memcpy (p+1, data->data, data->length);
-    *size =3D data->length;
-    return 0;
+    return der_put_octet_string (p, len, data, size);
 }
=20
 int
-decode_heim_any(const unsigned char *p, size_t len,=20
+decode_heim_any(const unsigned char *p, size_t len,
 		heim_any *data, size_t *size)
 {
     size_t len_len, length, l;
@@ -67,8 +63,14 @@
 	return ASN1_OVERFLOW;
     e =3D der_get_length(p + l, len - l, &length, &len_len);
     if (e) return e;
-    if (length + len_len + l > len)
-	return ASN1_OVERFLOW;
+    if (length =3D=3D ASN1_INDEFINITE) {
+        if (len < len_len + l)
+	    return ASN1_OVERFLOW;
+	length =3D len - (len_len + l);
+    } else {
+	if (len < length + len_len + l)
+	    return ASN1_OVERFLOW;
+    }
=20
     data->data =3D malloc(length + len_len + l);
     if (data->data =3D=3D NULL)
@@ -85,8 +87,7 @@
 void
 free_heim_any(heim_any *data)
 {
-    free(data->data);
-    data->data =3D NULL;
+    der_free_octet_string(data);
 }
=20
 size_t
@@ -98,58 +99,43 @@
 int
 copy_heim_any(const heim_any *from, heim_any *to)
 {
-    to->data =3D malloc(from->length);
-    if (to->data =3D=3D NULL && from->length !=3D 0)
-	return ENOMEM;
-    memcpy(to->data, from->data, from->length);
-    to->length =3D from->length;
-    return 0;
+    return der_copy_octet_string(from, to);
 }
=20
 int
-encode_heim_any_set(unsigned char *p, size_t len,=20
+encode_heim_any_set(unsigned char *p, size_t len,
 		    const heim_any_set *data, size_t *size)
 {
-    return encode_heim_any(p, len, data, size);
+    return der_put_octet_string (p, len, data, size);
 }
=20
-
 int
-decode_heim_any_set(const unsigned char *p, size_t len,=20
+decode_heim_any_set(const unsigned char *p, size_t len,
 		heim_any_set *data, size_t *size)
 {
-    memset(data, 0, sizeof(*data));
-    data->data =3D malloc(len);
-    if (data->data =3D=3D NULL && len !=3D 0)
-	return ENOMEM;
-    data->length =3D len;
-    memcpy(data->data, p, len);
-    if (size) *size =3D len;
-    return 0;
+    return der_get_octet_string(p, len, data, size);
 }
=20
 void
 free_heim_any_set(heim_any_set *data)
 {
-    free_heim_any(data);
+    der_free_octet_string(data);
 }
=20
 size_t
 length_heim_any_set(const heim_any *data)
 {
-    return length_heim_any(data);
+    return data->length;
 }
=20
 int
 copy_heim_any_set(const heim_any_set *from, heim_any_set *to)
 {
-    return copy_heim_any(from, to);
+    return der_copy_octet_string(from, to);
 }
=20
 int
 heim_any_cmp(const heim_any_set *p, const heim_any_set *q)
 {
-    if (p->length !=3D q->length)
-	return p->length - q->length;
-    return memcmp(p->data, q->data, p->length);
+    return der_heim_octet_string_cmp(p, q);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen.c
--- a/head/crypto/heimdal/lib/asn1/gen.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/gen.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,46 +1,48 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: gen.c 22429 2008-01-13 10:25:50Z lha $");
+RCSID("$Id$");
=20
-FILE *headerfile, *codefile, *logfile;
+FILE *privheaderfile, *headerfile, *codefile, *logfile, *templatefile;
=20
 #define STEM "asn1"
=20
 static const char *orig_filename;
-static char *header;
+static char *privheader, *header, *template;
 static const char *headerbase =3D STEM;
=20
 /*
@@ -66,6 +68,45 @@
     fprintf (headerfile, "#include <%s_asn1.h>\n", module);
 }
=20
+/*
+ * List of all exported symbols
+ */
+
+struct sexport {
+    const char *name;
+    int defined;
+    struct sexport *next;
+};
+
+static struct sexport *exports =3D NULL;
+
+void
+add_export (const char *name)
+{
+    struct sexport *tmp =3D emalloc (sizeof(*tmp));
+
+    tmp->name   =3D name;
+    tmp->next   =3D exports;
+    exports     =3D tmp;
+}
+
+int
+is_export(const char *name)
+{
+    struct sexport *tmp;
+
+    if (exports =3D=3D NULL) /* no export list, all exported */
+	return 1;
+
+    for (tmp =3D exports; tmp !=3D NULL; tmp =3D tmp->next) {
+	if (strcmp(tmp->name, name) =3D=3D 0) {
+	    tmp->defined =3D 1;
+	    return 1;
+	}
+    }
+    return 0;
+}
+
 const char *
 get_filename (void)
 {
@@ -75,7 +116,7 @@
 void
 init_generate (const char *filename, const char *base)
 {
-    char *fn;
+    char *fn =3D NULL;
=20
     orig_filename =3D filename;
     if (base !=3D NULL) {
@@ -83,20 +124,40 @@
 	if (headerbase =3D=3D NULL)
 	    errx(1, "strdup");
     }
-    asprintf(&header, "%s.h", headerbase);
-    if (header =3D=3D NULL)
+
+    /* public header file */
+    if (asprintf(&header, "%s.h", headerbase) < 0 || header =3D=3D NULL)
 	errx(1, "malloc");
-    headerfile =3D fopen (header, "w");
+    if (asprintf(&fn, "%s.hx", headerbase) < 0 || fn =3D=3D NULL)
+	errx(1, "malloc");
+    headerfile =3D fopen (fn, "w");
     if (headerfile =3D=3D NULL)
-	err (1, "open %s", header);
+	err (1, "open %s", fn);
+    free(fn);
+    fn =3D NULL;
+
+    /* private header file */
+    if (asprintf(&privheader, "%s-priv.h", headerbase) < 0 || privheader =
=3D=3D NULL)
+	errx(1, "malloc");
+    if (asprintf(&fn, "%s-priv.hx", headerbase) < 0 || fn =3D=3D NULL)
+	errx(1, "malloc");
+    privheaderfile =3D fopen (fn, "w");
+    if (privheaderfile =3D=3D NULL)
+	err (1, "open %s", fn);
+    free(fn);
+    fn =3D NULL;
+
+    /* template file */
+    if (asprintf(&template, "%s-template.c", headerbase) < 0 || template =
=3D=3D NULL)
+	errx(1, "malloc");
     fprintf (headerfile,
 	     "/* Generated from %s */\n"
 	     "/* Do not edit */\n\n",
 	     filename);
-    fprintf (headerfile,=20
+    fprintf (headerfile,
 	     "#ifndef __%s_h__\n"
 	     "#define __%s_h__\n\n", headerbase, headerbase);
-    fprintf (headerfile,=20
+    fprintf (headerfile,
 	     "#include <stddef.h>\n"
 	     "#include <time.h>\n\n");
     fprintf (headerfile,
@@ -120,10 +181,10 @@
 	     "typedef char *heim_utf8_string;\n\n"
 	     );
     fprintf (headerfile,
-	     "typedef char *heim_printable_string;\n\n"
+	     "typedef struct heim_octet_string heim_printable_string;\n\n"
 	     );
     fprintf (headerfile,
-	     "typedef char *heim_ia5_string;\n\n"
+	     "typedef struct heim_octet_string heim_ia5_string;\n\n"
 	     );
     fprintf (headerfile,
 	     "typedef struct heim_bmp_string {\n"
@@ -167,14 +228,55 @@
 	  "    }                                                          \\\n"
 	  "  } while (0)\n\n",
 	  headerfile);
+    fputs("#ifdef _WIN32\n"
+	  "#ifndef ASN1_LIB\n"
+	  "#define ASN1EXP  __declspec(dllimport)\n"
+	  "#else\n"
+	  "#define ASN1EXP\n"
+	  "#endif\n"
+	  "#define ASN1CALL __stdcall\n"
+	  "#else\n"
+	  "#define ASN1EXP\n"
+	  "#define ASN1CALL\n"
+	  "#endif\n",
+	  headerfile);
     fprintf (headerfile, "struct units;\n\n");
     fprintf (headerfile, "#endif\n\n");
-    asprintf(&fn, "%s_files", base);
-    if (fn =3D=3D NULL)
+    if (asprintf(&fn, "%s_files", base) < 0 || fn =3D=3D NULL)
 	errx(1, "malloc");
     logfile =3D fopen(fn, "w");
     if (logfile =3D=3D NULL)
 	err (1, "open %s", fn);
+
+    /* if one code file, write into the one codefile */
+    if (one_code_file)
+	return;
+
+    templatefile =3D fopen (template, "w");
+    if (templatefile =3D=3D NULL)
+	err (1, "open %s", template);
+
+    fprintf (templatefile,
+	     "/* Generated from %s */\n"
+	     "/* Do not edit */\n\n"
+	     "#include <stdio.h>\n"
+	     "#include <stdlib.h>\n"
+	     "#include <time.h>\n"
+	     "#include <string.h>\n"
+	     "#include <errno.h>\n"
+	     "#include <limits.h>\n"
+	     "#include <krb5-types.h>\n",
+	     filename);
+
+    fprintf (templatefile,
+	     "#include <%s>\n"
+	     "#include <%s>\n"
+	     "#include <der.h>\n"
+	     "#include <der-private.h>\n"
+	     "#include <asn1-template.h>\n",
+	     header, privheader);
+
+
 }
=20
 void
@@ -182,9 +284,15 @@
 {
     fprintf (headerfile, "#endif /* __%s_h__ */\n", headerbase);
=20
-    fclose (headerfile);
-    fprintf (logfile, "\n");
-    fclose (logfile);
+    if (headerfile)
+        fclose (headerfile);
+    if (privheaderfile)
+        fclose (privheaderfile);
+    if (templatefile)
+        fclose (templatefile);
+    if (logfile)
+        fprintf (logfile, "\n");
+        fclose (logfile);
 }
=20
 void
@@ -229,25 +337,26 @@
     }
 }
=20
-static void
+void
 generate_header_of_codefile(const char *name)
 {
-    char *filename;
+    char *filename =3D NULL;
=20
     if (codefile !=3D NULL)
 	abort();
=20
-    asprintf (&filename, "%s_%s.x", STEM, name);
-    if (filename =3D=3D NULL)
+    if (asprintf (&filename, "%s_%s.x", STEM, name) < 0 || filename =3D=3D=
 NULL)
 	errx(1, "malloc");
     codefile =3D fopen (filename, "w");
     if (codefile =3D=3D NULL)
 	err (1, "fopen %s", filename);
     fprintf(logfile, "%s ", filename);
     free(filename);
-    fprintf (codefile,=20
+    filename =3D NULL;
+    fprintf (codefile,
 	     "/* Generated from %s */\n"
 	     "/* Do not edit */\n\n"
+	     "#define  ASN1_LIB\n\n"
 	     "#include <stdio.h>\n"
 	     "#include <stdlib.h>\n"
 	     "#include <time.h>\n"
@@ -258,16 +367,19 @@
 	     orig_filename);
=20
     fprintf (codefile,
-	     "#include <%s.h>\n",
-	     headerbase);
+	     "#include <%s>\n"
+	     "#include <%s>\n",
+	     header, privheader);
     fprintf (codefile,
 	     "#include <asn1_err.h>\n"
 	     "#include <der.h>\n"
+	     "#include <der-private.h>\n"
+	     "#include <asn1-template.h>\n"
 	     "#include <parse_units.h>\n\n");
=20
 }
=20
-static void
+void
 close_codefile(void)
 {
     if (codefile =3D=3D NULL)
@@ -294,13 +406,20 @@
 	break;
     case objectidentifiervalue: {
 	struct objid *o, **list;
-	int i, len;
+	unsigned int i, len;
+	char *gen_upper;
=20
-	generate_header_of_codefile(s->gen_name);
+	if (!one_code_file)
+	    generate_header_of_codefile(s->gen_name);
=20
 	len =3D 0;
 	for (o =3D s->value->u.objectidentifiervalue; o !=3D NULL; o =3D o->next)
 	    len++;
+	if (len =3D=3D 0) {
+	    printf("s->gen_name: %s",s->gen_name);
+	    fflush(stdout);
+	    break;
+	}
 	list =3D emalloc(sizeof(*list) * len);
=20
 	i =3D 0;
@@ -308,34 +427,44 @@
 	    list[i++] =3D o;
=20
 	fprintf (headerfile, "/* OBJECT IDENTIFIER %s ::=3D { ", s->name);
-	for (i =3D len - 1 ; i >=3D 0; i--) {
-	    o =3D list[i];
+	for (i =3D len ; i > 0; i--) {
+	    o =3D list[i - 1];
 	    fprintf(headerfile, "%s(%d) ",
 		    o->label ? o->label : "label-less", o->value);
 	}
=20
-	fprintf (headerfile, "} */\n");
-	fprintf (headerfile, "const heim_oid *oid_%s(void);\n\n",
-		 s->gen_name);
-
 	fprintf (codefile, "static unsigned oid_%s_variable_num[%d] =3D  {",
 		 s->gen_name, len);
-	for (i =3D len - 1 ; i >=3D 0; i--) {
-	    fprintf(codefile, "%d%s ", list[i]->value, i > 0 ? "," : "");
+	for (i =3D len ; i > 0; i--) {
+	    fprintf(codefile, "%d%s ", list[i - 1]->value, i > 1 ? "," : "");
 	}
 	fprintf(codefile, "};\n");
=20
-	fprintf (codefile, "static const heim_oid oid_%s_variable =3D "
-		 "{ %d, oid_%s_variable_num };\n\n",=20
+	fprintf (codefile, "const heim_oid asn1_oid_%s =3D "
+		 "{ %d, oid_%s_variable_num };\n\n",
 		 s->gen_name, len, s->gen_name);
=20
-	fprintf (codefile, "const heim_oid *oid_%s(void)\n"
-		 "{\n"
-		 "return &oid_%s_variable;\n"
-		 "}\n\n",
-		 s->gen_name, s->gen_name);
+	free(list);
=20
-	close_codefile();
+	/* header file */
+
+	gen_upper =3D strdup(s->gen_name);
+	len =3D strlen(gen_upper);
+	for (i =3D 0; i < len; i++)
+	    gen_upper[i] =3D toupper((int)s->gen_name[i]);
+
+	fprintf (headerfile, "} */\n");
+	fprintf (headerfile,
+		 "extern ASN1EXP const heim_oid asn1_oid_%s;\n"
+		 "#define ASN1_OID_%s (&asn1_oid_%s)\n\n",
+		 s->gen_name,
+		 gen_upper,
+		 s->gen_name);
+
+	free(gen_upper);
+
+	if (!one_code_file)
+	    close_codefile();
=20
 	break;
     }
@@ -344,6 +473,33 @@
     }
 }
=20
+int
+is_primitive_type(int type)
+{
+    switch(type) {
+    case TInteger:
+    case TBoolean:
+    case TOctetString:
+    case TBitString:
+    case TEnumerated:
+    case TGeneralizedTime:
+    case TGeneralString:
+    case TTeletexString:
+    case TOID:
+    case TUTCTime:
+    case TUTF8String:
+    case TPrintableString:
+    case TIA5String:
+    case TBMPString:
+    case TUniversalString:
+    case TVisibleString:
+    case TNull:
+	return 1;
+    default:
+	return 0;
+    }
+}
+
 static void
 space(int level)
 {
@@ -391,7 +547,7 @@
             fprintf (headerfile, "INTEGER {\n");
 	    ASN1_TAILQ_FOREACH(m, t->members, members) {
                 space (level + 1);
-		fprintf(headerfile, "%s(%d)%s\n", m->gen_name, m->val,=20
+		fprintf(headerfile, "%s(%d)%s\n", m->gen_name, m->val,
 			last_member_p(m));
             }
 	    space(level);
@@ -415,7 +571,7 @@
 	    fprintf (headerfile, "ENUMERATED {\n");
 	ASN1_TAILQ_FOREACH(m, t->members, members) {
 	    space(level + 1);
-	    fprintf (headerfile, "%s(%d)%s\n", m->name, m->val,=20
+	    fprintf (headerfile, "%s(%d)%s\n", m->name, m->val,
 		     last_member_p(m));
 	}
 	space(level);
@@ -474,11 +630,14 @@
     case TGeneralString:
 	fprintf (headerfile, "GeneralString");
 	break;
+    case TTeletexString:
+	fprintf (headerfile, "TeletexString");
+	break;
     case TTag: {
-	const char *classnames[] =3D { "UNIVERSAL ", "APPLICATION ",=20
+	const char *classnames[] =3D { "UNIVERSAL ", "APPLICATION ",
 				     "" /* CONTEXT */, "PRIVATE " };
 	if(t->tag.tagclass !=3D ASN1_C_UNIV)
-	    fprintf (headerfile, "[%s%d] ",=20
+	    fprintf (headerfile, "[%s%d] ",
 		     classnames[t->tag.tagclass],
 		     t->tag.tagvalue);
 	if(t->tag.tagenv =3D=3D TE_IMPLICIT)
@@ -527,8 +686,25 @@
 }
=20
 static void
-define_type (int level, const char *name, Type *t, int typedefp, int prese=
rvep)
+getnewbasename(char **newbasename, int typedefp, const char *basename, con=
st char *name)
 {
+    if (typedefp)
+	*newbasename =3D strdup(name);
+    else {
+	if (name[0] =3D=3D '*')
+	    name++;
+	if (asprintf(newbasename, "%s_%s", basename, name) < 0)
+	    errx(1, "malloc");
+    }
+    if (*newbasename =3D=3D NULL)
+	err(1, "malloc");
+}
+
+static void
+define_type (int level, const char *name, const char *basename, Type *t, i=
nt typedefp, int preservep)
+{
+    char *newbasename =3D NULL;
+
     switch (t->type) {
     case TType:
 	space(level);
@@ -541,7 +717,7 @@
             fprintf (headerfile, "enum %s {\n", typedefp ? name : "");
 	    ASN1_TAILQ_FOREACH(m, t->members, members) {
                 space (level + 1);
-                fprintf(headerfile, "%s =3D %d%s\n", m->gen_name, m->val,=20
+                fprintf(headerfile, "%s =3D %d%s\n", m->gen_name, m->val,
                         last_member_p(m));
             }
             fprintf (headerfile, "} %s;\n", name);
@@ -554,7 +730,7 @@
 	} else if (t->range->min =3D=3D 0 && t->range->max =3D=3D INT_MAX) {
 	    fprintf (headerfile, "unsigned int %s;\n", name);
 	} else
-	    errx(1, "%s: unsupported range %d -> %d",=20
+	    errx(1, "%s: unsupported range %d -> %d",
 		 name, t->range->min, t->range->max);
 	break;
     case TBoolean:
@@ -576,19 +752,43 @@
 	i.constraint =3D NULL;
=20
 	space(level);
-	if(ASN1_TAILQ_EMPTY(t->members))=20
+	if(ASN1_TAILQ_EMPTY(t->members))
 	    fprintf (headerfile, "heim_bit_string %s;\n", name);
 	else {
-	    fprintf (headerfile, "struct %s {\n", typedefp ? name : "");
+	    int pos =3D 0;
+	    getnewbasename(&newbasename, typedefp, basename, name);
+
+	    fprintf (headerfile, "struct %s {\n", newbasename);
 	    ASN1_TAILQ_FOREACH(m, t->members, members) {
-		char *n;
-	=09
-		asprintf (&n, "%s:1", m->gen_name);
-		if (n =3D=3D NULL)
+		char *n =3D NULL;
+
+		/* pad unused */
+		while (pos < m->val) {
+		    if (asprintf (&n, "_unused%d:1", pos) < 0 || n =3D=3D NULL)
+			errx(1, "malloc");
+		    define_type (level + 1, n, newbasename, &i, FALSE, FALSE);
+		    free(n);
+		    pos++;
+		}
+
+		n =3D NULL;
+		if (asprintf (&n, "%s:1", m->gen_name) < 0 || n =3D=3D NULL)
 		    errx(1, "malloc");
-		define_type (level + 1, n, &i, FALSE, FALSE);
+		define_type (level + 1, n, newbasename, &i, FALSE, FALSE);
 		free (n);
+		n =3D NULL;
+		pos++;
 	    }
+	    /* pad to 32 elements */
+	    while (pos < 32) {
+		char *n =3D NULL;
+		if (asprintf (&n, "_unused%d:1", pos) < 0 || n =3D=3D NULL)
+		    errx(1, "malloc");
+		define_type (level + 1, n, newbasename, &i, FALSE, FALSE);
+		free(n);
+		pos++;
+	    }
+
 	    space(level);
 	    fprintf (headerfile, "} %s;\n\n", name);
 	}
@@ -615,8 +815,10 @@
     case TSequence: {
 	Member *m;
=20
+	getnewbasename(&newbasename, typedefp, basename, name);
+
 	space(level);
-	fprintf (headerfile, "struct %s {\n", typedefp ? name : "");
+	fprintf (headerfile, "struct %s {\n", newbasename);
 	if (t->type =3D=3D TSequence && preservep) {
 	    space(level + 1);
 	    fprintf(headerfile, "heim_octet_string _save;\n");
@@ -625,15 +827,14 @@
 	    if (m->ellipsis) {
 		;
 	    } else if (m->optional) {
-		char *n;
+		char *n =3D NULL;
=20
-		asprintf (&n, "*%s", m->gen_name);
-		if (n =3D=3D NULL)
+		if (asprintf (&n, "*%s", m->gen_name) < 0 || n =3D=3D NULL)
 		    errx(1, "malloc");
-		define_type (level + 1, n, m->type, FALSE, FALSE);
+		define_type (level + 1, n, newbasename, m->type, FALSE, FALSE);
 		free (n);
 	    } else
-		define_type (level + 1, m->gen_name, m->type, FALSE, FALSE);
+		define_type (level + 1, m->gen_name, newbasename, m->type, FALSE, FALSE);
 	}
 	space(level);
 	fprintf (headerfile, "} %s;\n", name);
@@ -644,15 +845,17 @@
 	Type i;
 	struct range range =3D { 0, INT_MAX };
=20
+	getnewbasename(&newbasename, typedefp, basename, name);
+
 	i.type =3D TInteger;
 	i.range =3D ⦥
 	i.members =3D NULL;
 	i.constraint =3D NULL;
=20
 	space(level);
-	fprintf (headerfile, "struct %s {\n", typedefp ? name : "");
-	define_type (level + 1, "len", &i, FALSE, FALSE);
-	define_type (level + 1, "*val", t->subtype, FALSE, FALSE);
+	fprintf (headerfile, "struct %s {\n", newbasename);
+	define_type (level + 1, "len", newbasename, &i, FALSE, FALSE);
+	define_type (level + 1, "*val", newbasename, t->subtype, FALSE, FALSE);
 	space(level);
 	fprintf (headerfile, "} %s;\n", name);
 	break;
@@ -665,15 +868,21 @@
 	space(level);
 	fprintf (headerfile, "heim_general_string %s;\n", name);
 	break;
+    case TTeletexString:
+	space(level);
+	fprintf (headerfile, "heim_general_string %s;\n", name);
+	break;
     case TTag:
-	define_type (level, name, t->subtype, typedefp, preservep);
+	define_type (level, name, basename, t->subtype, typedefp, preservep);
 	break;
     case TChoice: {
 	int first =3D 1;
 	Member *m;
=20
+	getnewbasename(&newbasename, typedefp, basename, name);
+
 	space(level);
-	fprintf (headerfile, "struct %s {\n", typedefp ? name : "");
+	fprintf (headerfile, "struct %s {\n", newbasename);
 	if (preservep) {
 	    space(level + 1);
 	    fprintf(headerfile, "heim_octet_string _save;\n");
@@ -683,7 +892,7 @@
 	m =3D have_ellipsis(t);
 	if (m) {
 	    space(level + 2);
-	    fprintf (headerfile, "%s =3D 0,\n", m->label);=20
+	    fprintf (headerfile, "%s =3D 0,\n", m->label);
 	    first =3D 0;
 	}
 	ASN1_TAILQ_FOREACH(m, t->members, members) {
@@ -691,8 +900,8 @@
 	    if (m->ellipsis)
 		fprintf (headerfile, "/* ... */\n");
 	    else
-		fprintf (headerfile, "%s%s%s\n", m->label,=20
-			 first ? " =3D 1" : "",=20
+		fprintf (headerfile, "%s%s%s\n", m->label,
+			 first ? " =3D 1" : "",
 			 last_member_p(m));
 	    first =3D 0;
 	}
@@ -705,15 +914,14 @@
 		space(level + 2);
 		fprintf(headerfile, "heim_octet_string asn1_ellipsis;\n");
 	    } else if (m->optional) {
-		char *n;
+		char *n =3D NULL;
=20
-		asprintf (&n, "*%s", m->gen_name);
-		if (n =3D=3D NULL)
+		if (asprintf (&n, "*%s", m->gen_name) < 0 || n =3D=3D NULL)
 		    errx(1, "malloc");
-		define_type (level + 2, n, m->type, FALSE, FALSE);
+		define_type (level + 2, n, newbasename, m->type, FALSE, FALSE);
 		free (n);
 	    } else
-		define_type (level + 2, m->gen_name, m->type, FALSE, FALSE);
+		define_type (level + 2, m->gen_name, newbasename, m->type, FALSE, FALSE);
 	}
 	space(level + 1);
 	fprintf (headerfile, "} u;\n");
@@ -760,6 +968,8 @@
     default:
 	abort ();
     }
+    if (newbasename)
+	free(newbasename);
 }
=20
 static void
@@ -773,25 +983,72 @@
     fprintf (headerfile, "\n*/\n\n");
=20
     fprintf (headerfile, "typedef ");
-    define_type (0, s->gen_name, s->type, TRUE, preservep);
+    define_type (0, s->gen_name, s->gen_name, s->type, TRUE, preservep);
=20
     fprintf (headerfile, "\n");
 }
=20
-
 void
 generate_type (const Symbol *s)
 {
-    generate_header_of_codefile(s->gen_name);
+    FILE *h;
+    const char * exp;
+
+    if (!one_code_file)
+	generate_header_of_codefile(s->gen_name);
=20
     generate_type_header (s);
-    generate_type_encode (s);
-    generate_type_decode (s);
-    generate_type_free (s);
-    generate_type_length (s);
-    generate_type_copy (s);
+
+    if (template_flag)
+	generate_template(s);
+
+    if (template_flag =3D=3D 0 || is_template_compat(s) =3D=3D 0) {
+	generate_type_encode (s);
+	generate_type_decode (s);
+	generate_type_free (s);
+	generate_type_length (s);
+	generate_type_copy (s);
+    }
     generate_type_seq (s);
     generate_glue (s->type, s->gen_name);
-    fprintf(headerfile, "\n\n");
-    close_codefile();
+
+    /* generate prototypes */
+
+    if (is_export(s->name)) {
+	h =3D headerfile;
+	exp =3D "ASN1EXP ";
+    } else {
+	h =3D privheaderfile;
+	exp =3D "";
+    }
+
+    fprintf (h,
+	     "%sint    ASN1CALL "
+	     "decode_%s(const unsigned char *, size_t, %s *, size_t *);\n",
+	     exp,
+	     s->gen_name, s->gen_name);
+    fprintf (h,
+	     "%sint    ASN1CALL "
+	     "encode_%s(unsigned char *, size_t, const %s *, size_t *);\n",
+	     exp,
+	     s->gen_name, s->gen_name);
+    fprintf (h,
+	     "%ssize_t ASN1CALL length_%s(const %s *);\n",
+	     exp,
+	     s->gen_name, s->gen_name);
+    fprintf (h,
+	     "%sint    ASN1CALL copy_%s  (const %s *, %s *);\n",
+	     exp,
+	     s->gen_name, s->gen_name, s->gen_name);
+    fprintf (h,
+	     "%svoid   ASN1CALL free_%s  (%s *);\n",
+	     exp,
+	     s->gen_name, s->gen_name);
+
+    fprintf(h, "\n\n");
+
+    if (!one_code_file) {
+	fprintf(codefile, "\n\n");
+	close_codefile();
+	}
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_copy.c
--- a/head/crypto/heimdal/lib/asn1/gen_copy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/gen_copy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,46 +1,46 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: gen_copy.c 19539 2006-12-28 17:15:05Z lha $");
+RCSID("$Id$");
=20
 static int used_fail;
=20
 static void
 copy_primitive (const char *typename, const char *from, const char *to)
 {
-    fprintf (codefile, "if(der_copy_%s(%s, %s)) goto fail;\n",=20
+    fprintf (codefile, "if(der_copy_%s(%s, %s)) goto fail;\n",
 	     typename, from, to);
     used_fail++;
 }
@@ -53,7 +53,7 @@
 #if 0
 	copy_type (from, to, t->symbol->type, preserve);
 #endif
-	fprintf (codefile, "if(copy_%s(%s, %s)) goto fail;\n",=20
+	fprintf (codefile, "if(copy_%s(%s, %s)) goto fail;\n",
 		 t->symbol->gen_name, from, to);
 	used_fail++;
 	break;
@@ -82,7 +82,7 @@
=20
 	if(t->members =3D=3D NULL)
 	    break;
-     =20
+
 	if ((t->type =3D=3D TSequence || t->type =3D=3D TChoice) && preserve) {
 	    fprintf(codefile,
 		    "{ int ret;\n"
@@ -110,14 +110,16 @@
 	    if(t->type =3D=3D TChoice)
 		fprintf(codefile, "case %s:\n", m->label);
=20
-	    asprintf (&fs, "%s(%s)->%s%s",
-		      m->optional ? "" : "&", from,=20
-		      t->type =3D=3D TChoice ? "u." : "", m->gen_name);
+	    if (asprintf (&fs, "%s(%s)->%s%s",
+			  m->optional ? "" : "&", from,
+			  t->type =3D=3D TChoice ? "u." : "", m->gen_name) < 0)
+		errx(1, "malloc");
 	    if (fs =3D=3D NULL)
 		errx(1, "malloc");
-	    asprintf (&ts, "%s(%s)->%s%s",
-		      m->optional ? "" : "&", to,=20
-		      t->type =3D=3D TChoice ? "u." : "", m->gen_name);
+	    if (asprintf (&ts, "%s(%s)->%s%s",
+			  m->optional ? "" : "&", to,
+			  t->type =3D=3D TChoice ? "u." : "", m->gen_name) < 0)
+		errx(1, "malloc");
 	    if (ts =3D=3D NULL)
 		errx(1, "malloc");
 	    if(m->optional){
@@ -145,31 +147,32 @@
 			"break;\n"
 			"}\n",
 			have_ellipsis->label,
-			from, have_ellipsis->gen_name,=20
+			from, have_ellipsis->gen_name,
 			to, have_ellipsis->gen_name);
 		used_fail++;
 	    }
-	    fprintf(codefile, "}\n");=09
+	    fprintf(codefile, "}\n");
 	}
 	break;
     }
     case TSetOf:
     case TSequenceOf: {
-	char *f;
-	char *T;
+	char *f =3D NULL, *T =3D NULL;
=20
 	fprintf (codefile, "if(((%s)->val =3D "
-		 "malloc((%s)->len * sizeof(*(%s)->val))) =3D=3D NULL && (%s)->len !=3D =
0)\n",=20
+		 "malloc((%s)->len * sizeof(*(%s)->val))) =3D=3D NULL && (%s)->len !=3D =
0)\n",
 		 to, from, to, from);
 	fprintf (codefile, "goto fail;\n");
 	used_fail++;
 	fprintf(codefile,
 		"for((%s)->len =3D 0; (%s)->len < (%s)->len; (%s)->len++){\n",
 		to, to, from, to);
-	asprintf(&f, "&(%s)->val[(%s)->len]", from, to);
+	if (asprintf(&f, "&(%s)->val[(%s)->len]", from, to) < 0)
+	    errx(1, "malloc");
 	if (f =3D=3D NULL)
 	    errx(1, "malloc");
-	asprintf(&T, "&(%s)->val[(%s)->len]", to, to);
+	if (asprintf(&T, "&(%s)->val[(%s)->len]", to, to) < 0)
+	    errx(1, "malloc");
 	if (T =3D=3D NULL)
 	    errx(1, "malloc");
 	copy_type(f, T, t->subtype, FALSE);
@@ -184,6 +187,9 @@
     case TGeneralString:
 	copy_primitive ("general_string", from, to);
 	break;
+    case TTeletexString:
+	copy_primitive ("general_string", from, to);
+	break;
     case TUTCTime:
 	fprintf(codefile, "*(%s) =3D *(%s);\n", to, from);
 	break;
@@ -225,11 +231,7 @@
=20
   used_fail =3D 0;
=20
-  fprintf (headerfile,
-	   "int    copy_%s  (const %s *, %s *);\n",
-	   s->gen_name, s->gen_name, s->gen_name);
-
-  fprintf (codefile, "int\n"
+  fprintf (codefile, "int ASN1CALL\n"
 	   "copy_%s(const %s *from, %s *to)\n"
 	   "{\n"
 	   "memset(to, 0, sizeof(*to));\n",
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_decod=
e.c
--- a/head/crypto/heimdal/lib/asn1/gen_decode.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/gen_decode.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
 #include "lex.h"
=20
-RCSID("$Id: gen_decode.c 21503 2007-07-12 11:57:19Z lha $");
+RCSID("$Id$");
=20
 static void
 decode_primitive (const char *typename, const char *name, const char *forw=
str)
@@ -56,32 +56,6 @@
 #endif
 }
=20
-static int
-is_primitive_type(int type)
-{
-    switch(type) {
-    case TInteger:
-    case TBoolean:
-    case TOctetString:
-    case TBitString:
-    case TEnumerated:
-    case TGeneralizedTime:
-    case TGeneralString:
-    case TOID:
-    case TUTCTime:
-    case TUTF8String:
-    case TPrintableString:
-    case TIA5String:
-    case TBMPString:
-    case TUniversalString:
-    case TVisibleString:
-    case TNull:
-	return 1;
-    default:
-	return 0;
-    }
-}
-
 static void
 find_tag (const Type *t,
 	  Der_class *cl, Der_type *ty, unsigned *tag)
@@ -97,19 +71,24 @@
 	*ty  =3D PRIM;
 	*tag =3D UT_Boolean;
 	break;
-    case TChoice:=20
+    case TChoice:
 	errx(1, "Cannot have recursive CHOICE");
     case TEnumerated:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D PRIM;
 	*tag =3D UT_Enumerated;
 	break;
-    case TGeneralString:=20
+    case TGeneralString:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D PRIM;
 	*tag =3D UT_GeneralString;
 	break;
-    case TGeneralizedTime:=20
+    case TTeletexString:
+	*cl  =3D ASN1_C_UNIV;
+	*ty  =3D PRIM;
+	*tag =3D UT_TeletexString;
+	break;
+    case TGeneralizedTime:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D PRIM;
 	*tag =3D UT_GeneralizedTime;
@@ -119,7 +98,7 @@
 	*ty  =3D PRIM;
 	*tag =3D UT_IA5String;
 	break;
-    case TInteger:=20
+    case TInteger:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D PRIM;
 	*tag =3D UT_Integer;
@@ -129,12 +108,12 @@
 	*ty  =3D PRIM;
 	*tag =3D UT_Null;
 	break;
-    case TOID:=20
+    case TOID:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D PRIM;
 	*tag =3D UT_OID;
 	break;
-    case TOctetString:=20
+    case TOctetString:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D PRIM;
 	*tag =3D UT_OctetString;
@@ -144,35 +123,35 @@
 	*ty  =3D PRIM;
 	*tag =3D UT_PrintableString;
 	break;
-    case TSequence:=20
+    case TSequence:
     case TSequenceOf:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D CONS;
 	*tag =3D UT_Sequence;
 	break;
-    case TSet:=20
+    case TSet:
     case TSetOf:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D CONS;
 	*tag =3D UT_Set;
 	break;
-    case TTag:=20
+    case TTag:
 	*cl  =3D t->tag.tagclass;
 	*ty  =3D is_primitive_type(t->subtype->type) ? PRIM : CONS;
 	*tag =3D t->tag.tagvalue;
 	break;
-    case TType:=20
+    case TType:
 	if ((t->symbol->stype =3D=3D Stype && t->symbol->type =3D=3D NULL)
 	    || t->symbol->stype =3D=3D SUndefined) {
-	    error_message("%s is imported or still undefined, "
-			  " can't generate tag checking data in CHOICE "
-			  "without this information",
-			  t->symbol->name);
+	    lex_error_message("%s is imported or still undefined, "
+			      " can't generate tag checking data in CHOICE "
+			      "without this information",
+			      t->symbol->name);
 	    exit(1);
 	}
 	find_tag(t->symbol->type, cl, ty, tag);
 	return;
-    case TUTCTime:=20
+    case TUTCTime:
 	*cl  =3D ASN1_C_UNIV;
 	*ty  =3D PRIM;
 	*tag =3D UT_UTCTime;
@@ -205,7 +184,7 @@
 static void
 range_check(const char *name,
 	    const char *length,
-	    const char *forwstr,=20
+	    const char *forwstr,
 	    struct range *r)
 {
     if (r->min =3D=3D r->max + 2 || r->min < r->max)
@@ -229,13 +208,14 @@
 }
=20
 static int
-decode_type (const char *name, const Type *t, int optional,=20
-	     const char *forwstr, const char *tmpstr)
+decode_type (const char *name, const Type *t, int optional,
+	     const char *forwstr, const char *tmpstr, const char *dertype,
+	     unsigned int depth)
 {
     switch (t->type) {
     case TType: {
 	if (optional)
-	    fprintf(codefile,=20
+	    fprintf(codefile,
 		    "%s =3D calloc(1, sizeof(*%s));\n"
 		    "if (%s =3D=3D NULL) %s;\n",
 		    name, name, name, forwstr);
@@ -279,7 +259,7 @@
 	} else if (t->range->min =3D=3D 0 && t->range->max =3D=3D INT_MAX) {
 	    decode_primitive ("unsigned", name, forwstr);
 	} else
-	    errx(1, "%s: unsupported range %d -> %d",=20
+	    errx(1, "%s: unsupported range %d -> %d",
 		 name, t->range->min, t->range->max);
 	break;
     case TBoolean:
@@ -289,7 +269,17 @@
 	decode_primitive ("enumerated", name, forwstr);
 	break;
     case TOctetString:
+	if (dertype) {
+	    fprintf(codefile,
+		    "if (%s =3D=3D CONS) {\n",
+		    dertype);
+	    decode_primitive("octet_string_ber", name, forwstr);
+	    fprintf(codefile,
+		    "} else {\n");
+	}
 	decode_primitive ("octet_string", name, forwstr);
+	if (dertype)
+	    fprintf(codefile, "}\n");
 	if (t->range)
 	    range_check(name, "length", forwstr, t->range);
 	break;
@@ -331,19 +321,19 @@
 	    break;
=20
 	ASN1_TAILQ_FOREACH(m, t->members, members) {
-	    char *s;
+	    char *s =3D NULL;
=20
 	    if (m->ellipsis)
 		continue;
=20
-	    asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&",
-		      name, m->gen_name);
-	    if (s =3D=3D NULL)
+	    if (asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&",
+			  name, m->gen_name) < 0 || s =3D=3D NULL)
 		errx(1, "malloc");
-	    decode_type (s, m->type, m->optional, forwstr, m->gen_name);
+	    decode_type (s, m->type, m->optional, forwstr, m->gen_name, NULL,
+		depth + 1);
 	    free (s);
 	}
-=09
+
 	break;
     }
     case TSet: {
@@ -356,7 +346,7 @@
 	fprintf(codefile, "{\n");
 	fprintf(codefile, "unsigned int members =3D 0;\n");
 	fprintf(codefile, "while(len > 0) {\n");
-	fprintf(codefile,=20
+	fprintf(codefile,
 		"Der_class class;\n"
 		"Der_type type;\n"
 		"int tag;\n"
@@ -374,22 +364,21 @@
 		    is_primitive_type(m->type->subtype->type) ? "PRIM" : "CONS",
 		    valuename(m->type->tag.tagclass, m->type->tag.tagvalue));
=20
-	    asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&", name, m->gen_name=
);
-	    if (s =3D=3D NULL)
+	    if (asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&", name, m->gen_=
name) < 0 || s =3D=3D NULL)
 		errx(1, "malloc");
 	    if(m->optional)
-		fprintf(codefile,=20
+		fprintf(codefile,
 			"%s =3D calloc(1, sizeof(*%s));\n"
 			"if (%s =3D=3D NULL) { e =3D ENOMEM; %s; }\n",
 			s, s, s, forwstr);
-	    decode_type (s, m->type, 0, forwstr, m->gen_name);
+	    decode_type (s, m->type, 0, forwstr, m->gen_name, NULL, depth + 1);
 	    free (s);
=20
 	    fprintf(codefile, "members |=3D (1 << %d);\n", memno);
 	    memno++;
 	    fprintf(codefile, "break;\n");
 	}
-	fprintf(codefile,=20
+	fprintf(codefile,
 		"default:\n"
 		"return ASN1_MISPLACED_FIELD;\n"
 		"break;\n");
@@ -399,8 +388,7 @@
 	ASN1_TAILQ_FOREACH(m, t->members, members) {
 	    char *s;
=20
-	    asprintf (&s, "%s->%s", name, m->gen_name);
-	    if (s =3D=3D NULL)
+	    if (asprintf (&s, "%s->%s", name, m->gen_name) < 0 || s =3D=3D NULL)
 		errx(1, "malloc");
 	    fprintf(codefile, "if((members & (1 << %d)) =3D=3D 0)\n", memno);
 	    if(m->optional)
@@ -417,8 +405,8 @@
     }
     case TSetOf:
     case TSequenceOf: {
-	char *n;
-	char *sname;
+	char *n =3D NULL;
+	char *sname =3D NULL;
=20
 	fprintf (codefile,
 		 "{\n"
@@ -449,17 +437,15 @@
 		 tmpstr, tmpstr, forwstr,
 		 tmpstr, tmpstr,
 		 tmpstr, name, tmpstr,
-		 tmpstr, forwstr,=20
+		 tmpstr, forwstr,
 		 name, tmpstr);
=20
-	asprintf (&n, "&(%s)->val[(%s)->len]", name, name);
-	if (n =3D=3D NULL)
+	if (asprintf (&n, "&(%s)->val[(%s)->len]", name, name) < 0 || n =3D=3D NU=
LL)
 	    errx(1, "malloc");
-	asprintf (&sname, "%s_s_of", tmpstr);
-	if (sname =3D=3D NULL)
+	if (asprintf (&sname, "%s_s_of", tmpstr) < 0 || sname =3D=3D NULL)
 	    errx(1, "malloc");
-	decode_type (n, t->subtype, 0, forwstr, sname);
-	fprintf (codefile,=20
+	decode_type (n, t->subtype, 0, forwstr, sname, NULL, depth + 1);
+	fprintf (codefile,
 		 "(%s)->len++;\n"
 		 "len =3D %s_origlen - ret;\n"
 		 "}\n"
@@ -479,24 +465,44 @@
     case TGeneralString:
 	decode_primitive ("general_string", name, forwstr);
 	break;
+    case TTeletexString:
+	decode_primitive ("general_string", name, forwstr);
+	break;
     case TTag:{
-    	char *tname;
+    	char *tname =3D NULL, *typestring =3D NULL;
+	char *ide =3D NULL;
=20
-	fprintf(codefile,=20
+	if (asprintf(&typestring, "%s_type", tmpstr) < 0 || typestring =3D=3D NUL=
L)
+	    errx(1, "malloc");
+
+	fprintf(codefile,
 		"{\n"
-		"size_t %s_datalen, %s_oldlen;\n",
-		tmpstr, tmpstr);
-	if(dce_fix)
-	    fprintf(codefile,=20
-		    "int dce_fix;\n");
-	fprintf(codefile, "e =3D der_match_tag_and_length(p, len, %s, %s, %s, "
+		"size_t %s_datalen, %s_oldlen;\n"
+		"Der_type %s;\n",
+		tmpstr, tmpstr, typestring);
+	if(support_ber)
+	    fprintf(codefile,
+		    "int is_indefinite%u;\n", depth);
+
+	fprintf(codefile, "e =3D der_match_tag_and_length(p, len, %s, &%s, %s, "
 		"&%s_datalen, &l);\n",
 		classname(t->tag.tagclass),
-		is_primitive_type(t->subtype->type) ? "PRIM" : "CONS",
+		typestring,
 		valuename(t->tag.tagclass, t->tag.tagvalue),
 		tmpstr);
+
+	/* XXX hardcode for now */
+	if (support_ber && t->subtype->type =3D=3D TOctetString) {
+	    ide =3D typestring;
+	} else {
+	    fprintf(codefile,
+		    "if (e =3D=3D 0 && %s !=3D %s) { e =3D ASN1_BAD_ID; }\n",
+		    typestring,
+		    is_primitive_type(t->subtype->type) ? "PRIM" : "CONS");
+	}
+
 	if(optional) {
-	    fprintf(codefile,=20
+	    fprintf(codefile,
 		    "if(e) {\n"
 		    "%s =3D NULL;\n"
 		    "} else {\n"
@@ -510,36 +516,45 @@
 		 "p +=3D l; len -=3D l; ret +=3D l;\n"
 		 "%s_oldlen =3D len;\n",
 		 tmpstr);
-	if(dce_fix)
+	if(support_ber)
 	    fprintf (codefile,
-		     "if((dce_fix =3D _heim_fix_dce(%s_datalen, &len)) < 0)\n"
-		     "{ e =3D ASN1_BAD_FORMAT; %s; }\n",
-		     tmpstr, forwstr);
+		     "if((is_indefinite%u =3D _heim_fix_dce(%s_datalen, &len)) < 0)\n"
+		     "{ e =3D ASN1_BAD_FORMAT; %s; }\n"
+		     "if (is_indefinite%u) { if (len < 2) { e =3D ASN1_OVERRUN; %s; } le=
n -=3D 2; }",
+		     depth, tmpstr, forwstr, depth, forwstr);
 	else
-	    fprintf(codefile,=20
+	    fprintf(codefile,
 		    "if (%s_datalen > len) { e =3D ASN1_OVERRUN; %s; }\n"
 		    "len =3D %s_datalen;\n", tmpstr, forwstr, tmpstr);
-	asprintf (&tname, "%s_Tag", tmpstr);
-	if (tname =3D=3D NULL)
+	if (asprintf (&tname, "%s_Tag", tmpstr) < 0 || tname =3D=3D NULL)
 	    errx(1, "malloc");
-	decode_type (name, t->subtype, 0, forwstr, tname);
-	if(dce_fix)
+	decode_type (name, t->subtype, 0, forwstr, tname, ide, depth + 1);
+	if(support_ber)
 	    fprintf(codefile,
-		    "if(dce_fix){\n"
-		    "e =3D der_match_tag_and_length (p, len, "
-		    "(Der_class)0,(Der_type)0, UT_EndOfContent, "
+		    "if(is_indefinite%u){\n"
+		    "len +=3D 2;\n"
+		    "e =3D der_match_tag_and_length(p, len, "
+		    "(Der_class)0, &%s, UT_EndOfContent, "
 		    "&%s_datalen, &l);\n"
-		    "if(e) %s;\np +=3D l; len -=3D l; ret +=3D l;\n"
-		    "} else \n", tmpstr, forwstr);
-	fprintf(codefile,=20
+		    "if(e) %s;\n"
+		    "p +=3D l; len -=3D l; ret +=3D l;\n"
+		    "if (%s !=3D (Der_type)0) { e =3D ASN1_BAD_ID; %s; }\n"
+		    "} else \n",
+		    depth,
+		    typestring,
+		    tmpstr,
+		    forwstr,
+		    typestring, forwstr);
+	fprintf(codefile,
 		"len =3D %s_oldlen - %s_datalen;\n",
 		tmpstr, tmpstr);
 	if(optional)
-	    fprintf(codefile,=20
+	    fprintf(codefile,
 		    "}\n");
-	fprintf(codefile,=20
+	fprintf(codefile,
 		"}\n");
 	free(tname);
+	free(typestring);
 	break;
     }
     case TChoice: {
@@ -551,11 +566,11 @@
=20
 	ASN1_TAILQ_FOREACH(m, t->members, members) {
 	    const Type *tt =3D m->type;
-	    char *s;
+	    char *s =3D NULL;
 	    Der_class cl;
 	    Der_type  ty;
 	    unsigned  tag;
-	   =20
+
 	    if (m->ellipsis) {
 		have_ellipsis =3D m;
 		continue;
@@ -569,11 +584,11 @@
 		    classname(cl),
 		    ty ? "CONS" : "PRIM",
 		    valuename(cl, tag));
-	    asprintf (&s, "%s(%s)->u.%s", m->optional ? "" : "&",
-		      name, m->gen_name);
-	    if (s =3D=3D NULL)
+	    if (asprintf (&s, "%s(%s)->u.%s", m->optional ? "" : "&",
+			  name, m->gen_name) < 0 || s =3D=3D NULL)
 		errx(1, "malloc");
-	    decode_type (s, m->type, m->optional, forwstr, m->gen_name);
+	    decode_type (s, m->type, m->optional, forwstr, m->gen_name, NULL,
+		depth + 1);
 	    fprintf(codefile,
 		    "(%s)->element =3D %s;\n",
 		    name, m->label);
@@ -594,11 +609,11 @@
 		    "(%s)->element =3D %s;\n"
 		    "p +=3D len;\n"
 		    "ret +=3D len;\n"
-		    "len -=3D len;\n"
+		    "len =3D 0;\n"
 		    "}\n",
 		    name, have_ellipsis->gen_name,
 		    name, have_ellipsis->gen_name,
-		    forwstr,=20
+		    forwstr,
 		    name, have_ellipsis->gen_name,
 		    name, have_ellipsis->gen_name,
 		    name, have_ellipsis->label);
@@ -650,14 +665,9 @@
 {
     int preserve =3D preserve_type(s->name) ? TRUE : FALSE;
=20
-    fprintf (headerfile,
-	     "int    "
-	     "decode_%s(const unsigned char *, size_t, %s *, size_t *);\n",
-	     s->gen_name, s->gen_name);
-
-    fprintf (codefile, "int\n"
-	     "decode_%s(const unsigned char *p,"
-	     " size_t len, %s *data, size_t *size)\n"
+    fprintf (codefile, "int ASN1CALL\n"
+	     "decode_%s(const unsigned char *p HEIMDAL_UNUSED_ATTRIBUTE,"
+	     " size_t len HEIMDAL_UNUSED_ATTRIBUTE, %s *data, size_t *size)\n"
 	     "{\n",
 	     s->gen_name, s->gen_name);
=20
@@ -668,6 +678,7 @@
     case TOID:
     case TGeneralizedTime:
     case TGeneralString:
+    case TTeletexString:
     case TUTF8String:
     case TPrintableString:
     case TIA5String:
@@ -687,15 +698,15 @@
     case TChoice:
 	fprintf (codefile,
 		 "size_t ret =3D 0;\n"
-		 "size_t l;\n"
-		 "int e;\n");
+		 "size_t l HEIMDAL_UNUSED_ATTRIBUTE;\n"
+		 "int e HEIMDAL_UNUSED_ATTRIBUTE;\n");
 	if (preserve)
 	    fprintf (codefile, "const unsigned char *begin =3D p;\n");
=20
 	fprintf (codefile, "\n");
 	fprintf (codefile, "memset(data, 0, sizeof(*data));\n"); /* hack to avoid=
 `unused variable' */
=20
-	decode_type ("data", s->type, 0, "goto fail", "Top");
+	decode_type ("data", s->type, 0, "goto fail", "Top", NULL, 1);
 	if (preserve)
 	    fprintf (codefile,
 		     "data->_save.data =3D calloc(1, ret);\n"
@@ -704,7 +715,7 @@
 		     "}\n"
 		     "data->_save.length =3D ret;\n"
 		     "memcpy(data->_save.data, begin, ret);\n");
-	fprintf (codefile,=20
+	fprintf (codefile,
 		 "if(size) *size =3D ret;\n"
 		 "return 0;\n");
 	fprintf (codefile,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_encod=
e.c
--- a/head/crypto/heimdal/lib/asn1/gen_encode.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/gen_encode.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: gen_encode.c 22429 2008-01-13 10:25:50Z lha $");
+RCSID("$Id$");
=20
 static void
 encode_primitive (const char *typename, const char *name)
@@ -60,7 +60,7 @@
 valuename(Der_class class, int value)
 {
     static char s[32];
-    struct {=20
+    struct {
 	int value;
 	const char *s;
     } *p, values[] =3D {
@@ -136,7 +136,7 @@
 	} else if (t->range->min =3D=3D 0 && t->range->max =3D=3D INT_MAX) {
 	    encode_primitive ("unsigned", name);
 	} else
-	    errx(1, "%s: unsupported range %d -> %d",=20
+	    errx(1, "%s: unsupported range %d -> %d",
 		 name, t->range->min, t->range->max);
 	constructed =3D 0;
 	break;
@@ -209,7 +209,7 @@
 	    }
 	    fprintf (codefile,
 		     "if((%s)->%s) {\n"
-		     "c |=3D 1<<%d;\n",=20
+		     "c |=3D 1<<%d;\n",
 		     name, m->gen_name, 7 - m->val % 8);
 	    fprintf (codefile,
 		     "}\n");
@@ -218,7 +218,7 @@
 	if (!rfc1510_bitstring)
 	    fprintf (codefile,
 		     "if (c !=3D 0 || bit_set) {\n");
-	fprintf (codefile,=20
+	fprintf (codefile,
 		 "if (len < 1) return ASN1_OVERFLOW;\n"
 		 "*p-- =3D c; len--; ret++;\n");
 	if (!rfc1510_bitstring)
@@ -235,7 +235,7 @@
 		     "}\n"
 		     "}\n");
=20
-	fprintf (codefile,=20
+	fprintf (codefile,
 		 "if (len < 1) return ASN1_OVERFLOW;\n"
 		 "*p-- =3D %s;\n"
 		 "len -=3D 1;\n"
@@ -257,15 +257,14 @@
=20
 	if (t->members =3D=3D NULL)
 	    break;
-=09
+
 	ASN1_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
-	    char *s;
+	    char *s =3D NULL;
=20
 	    if (m->ellipsis)
 		continue;
=20
-	    asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&", name, m->gen_name=
);
-	    if (s =3D=3D NULL)
+	    if (asprintf (&s, "%s(%s)->%s", m->optional ? "" : "&", name, m->gen_=
name) < 0 || s =3D=3D NULL)
 		errx(1, "malloc");
 	    fprintf(codefile, "/* %s */\n", m->name);
 	    if (m->optional)
@@ -275,7 +274,7 @@
 	    else if(m->defval)
 		gen_compare_defval(s + 1, m->defval);
 	    fprintf (codefile, "{\n");
-	    fprintf (codefile, "size_t %s_oldret =3D ret;\n", tmpstr);
+	    fprintf (codefile, "size_t %s_oldret HEIMDAL_UNUSED_ATTRIBUTE =3D ret=
;\n", tmpstr);
 	    fprintf (codefile, "ret =3D 0;\n");
 	    encode_type (s, m->type, m->gen_name);
 	    fprintf (codefile, "ret +=3D %s_oldret;\n", tmpstr);
@@ -289,8 +288,8 @@
 	fprintf(codefile,
 		"{\n"
 		"struct heim_octet_string *val;\n"
-		"size_t elen, totallen =3D 0;\n"
-		"int eret;\n");
+		"size_t elen =3D 0, totallen =3D 0;\n"
+		"int eret =3D 0;\n");
=20
 	fprintf(codefile,
 		"if ((%s)->len > UINT_MAX/sizeof(val[0]))\n"
@@ -303,7 +302,7 @@
 		name, name);
=20
 	fprintf(codefile,
-		"for(i =3D 0; i < (%s)->len; i++) {\n",
+		"for(i =3D 0; i < (int)(%s)->len; i++) {\n",
 		name);
=20
 	fprintf(codefile,
@@ -327,7 +326,7 @@
=20
 	fprintf(codefile,
 		"if (totallen > len) {\n"
-		"for (i =3D 0; i < (%s)->len; i++) {\n"
+		"for (i =3D 0; i < (int)(%s)->len; i++) {\n"
 		"free(val[i].data);\n"
 		"}\n"
 		"free(val);\n"
@@ -340,7 +339,7 @@
 		name);
=20
 	fprintf (codefile,
-		 "for(i =3D (%s)->len - 1; i >=3D 0; --i) {\n"
+		 "for(i =3D (int)(%s)->len - 1; i >=3D 0; --i) {\n"
 		 "p -=3D val[i].length;\n"
 		 "ret +=3D val[i].length;\n"
 		 "memcpy(p + 1, val[i].data, val[i].length);\n"
@@ -352,19 +351,17 @@
 	break;
     }
     case TSequenceOf: {
-	char *n;
-	char *sname;
+	char *sname =3D NULL;
+	char *n =3D NULL;
=20
 	fprintf (codefile,
-		 "for(i =3D (%s)->len - 1; i >=3D 0; --i) {\n"
+		 "for(i =3D (int)(%s)->len - 1; i >=3D 0; --i) {\n"
 		 "size_t %s_for_oldret =3D ret;\n"
 		 "ret =3D 0;\n",
 		 name, tmpstr);
-	asprintf (&n, "&(%s)->val[i]", name);
-	if (n =3D=3D NULL)
+	if (asprintf (&n, "&(%s)->val[i]", name) < 0 || n =3D=3D NULL)
 	    errx(1, "malloc");
-	asprintf (&sname, "%s_S_Of", tmpstr);
-	if (sname =3D=3D NULL)
+	if (asprintf (&sname, "%s_S_Of", tmpstr) < 0 || sname =3D=3D NULL)
 	    errx(1, "malloc");
 	encode_type (n, t->subtype, sname);
 	fprintf (codefile,
@@ -383,48 +380,49 @@
 	encode_primitive ("general_string", name);
 	constructed =3D 0;
 	break;
+    case TTeletexString:
+	encode_primitive ("general_string", name);
+	constructed =3D 0;
+	break;
     case TTag: {
-    	char *tname;
+    	char *tname =3D NULL;
 	int c;
-	asprintf (&tname, "%s_tag", tmpstr);
-	if (tname =3D=3D NULL)
-	    errx(1, "malloc");=09
+	if (asprintf (&tname, "%s_tag", tmpstr) < 0 || tname =3D=3D NULL)
+	    errx(1, "malloc");
 	c =3D encode_type (name, t->subtype, tname);
 	fprintf (codefile,
 		 "e =3D der_put_length_and_tag (p, len, ret, %s, %s, %s, &l);\n"
 		 "if (e) return e;\np -=3D l; len -=3D l; ret +=3D l;\n\n",
 		 classname(t->tag.tagclass),
-		 c ? "CONS" : "PRIM",=20
+		 c ? "CONS" : "PRIM",
 		 valuename(t->tag.tagclass, t->tag.tagvalue));
 	free (tname);
 	break;
     }
     case TChoice:{
 	Member *m, *have_ellipsis =3D NULL;
-	char *s;
+	char *s =3D NULL;
=20
 	if (t->members =3D=3D NULL)
 	    break;
=20
 	fprintf(codefile, "\n");
=20
-	asprintf (&s, "(%s)", name);
-	if (s =3D=3D NULL)
+	if (asprintf (&s, "(%s)", name) < 0 || s =3D=3D NULL)
 	    errx(1, "malloc");
 	fprintf(codefile, "switch(%s->element) {\n", s);
=20
 	ASN1_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
-	    char *s2;
+	    char *s2 =3D NULL;
=20
 	    if (m->ellipsis) {
 		have_ellipsis =3D m;
 		continue;
 	    }
=20
-	    fprintf (codefile, "case %s: {", m->label);=20
-	    asprintf(&s2, "%s(%s)->u.%s", m->optional ? "" : "&",=20
-		     s, m->gen_name);
-	    if (s2 =3D=3D NULL)
+	    fprintf (codefile, "case %s: {", m->label);
+	    if (asprintf(&s2, "%s(%s)->u.%s", m->optional ? "" : "&",
+			 s, m->gen_name) < 0 || s2 =3D=3D NULL)
 		errx(1, "malloc");
 	    if (m->optional)
 		fprintf (codefile, "if(%s) {\n", s2);
@@ -504,13 +502,8 @@
 void
 generate_type_encode (const Symbol *s)
 {
-    fprintf (headerfile,
-	     "int    "
-	     "encode_%s(unsigned char *, size_t, const %s *, size_t *);\n",
-	     s->gen_name, s->gen_name);
-
-    fprintf (codefile, "int\n"
-	     "encode_%s(unsigned char *p, size_t len,"
+    fprintf (codefile, "int ASN1CALL\n"
+	     "encode_%s(unsigned char *p HEIMDAL_UNUSED_ATTRIBUTE, size_t len HEI=
MDAL_UNUSED_ATTRIBUTE,"
 	     " const %s *data, size_t *size)\n"
 	     "{\n",
 	     s->gen_name, s->gen_name);
@@ -521,6 +514,7 @@
     case TOctetString:
     case TGeneralizedTime:
     case TGeneralString:
+    case TTeletexString:
     case TUTCTime:
     case TUTF8String:
     case TPrintableString:
@@ -540,11 +534,10 @@
     case TType:
     case TChoice:
 	fprintf (codefile,
-		 "size_t ret =3D 0;\n"
-		 "size_t l;\n"
-		 "int i, e;\n\n");
-	fprintf(codefile, "i =3D 0;\n"); /* hack to avoid `unused variable' */
-   =20
+		 "size_t ret HEIMDAL_UNUSED_ATTRIBUTE =3D 0;\n"
+		 "size_t l HEIMDAL_UNUSED_ATTRIBUTE;\n"
+		 "int i HEIMDAL_UNUSED_ATTRIBUTE, e HEIMDAL_UNUSED_ATTRIBUTE;\n\n");
+
 	encode_type("data", s->type, "Top");
=20
 	fprintf (codefile, "*size =3D ret;\n"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_free.c
--- a/head/crypto/heimdal/lib/asn1/gen_free.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/gen_free.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: gen_free.c 19539 2006-12-28 17:15:05Z lha $");
+RCSID("$Id$");
=20
 static void
 free_primitive (const char *typename, const char *name)
@@ -82,7 +82,7 @@
=20
 	if(t->type =3D=3D TChoice)
 	    fprintf(codefile, "switch((%s)->element) {\n", name);
-     =20
+
 	ASN1_TAILQ_FOREACH(m, t->members, members) {
 	    char *s;
=20
@@ -93,16 +93,15 @@
=20
 	    if(t->type =3D=3D TChoice)
 		fprintf(codefile, "case %s:\n", m->label);
-	    asprintf (&s, "%s(%s)->%s%s",
-		      m->optional ? "" : "&", name,=20
-		      t->type =3D=3D TChoice ? "u." : "", m->gen_name);
-	    if (s =3D=3D NULL)
+	    if (asprintf (&s, "%s(%s)->%s%s",
+			  m->optional ? "" : "&", name,
+			  t->type =3D=3D TChoice ? "u." : "", m->gen_name) < 0 || s =3D=3D NULL)
 		errx(1, "malloc");
 	    if(m->optional)
 		fprintf(codefile, "if(%s) {\n", s);
 	    free_type (s, m->type, FALSE);
 	    if(m->optional)
-		fprintf(codefile,=20
+		fprintf(codefile,
 			"free(%s);\n"
 			"%s =3D NULL;\n"
 			"}\n",s, s);
@@ -110,7 +109,7 @@
 	    if(t->type =3D=3D TChoice)
 		fprintf(codefile, "break;\n");
 	}
-=09
+
 	if(t->type =3D=3D TChoice) {
 	    if (have_ellipsis)
 		fprintf(codefile,
@@ -128,11 +127,10 @@
 	char *n;
=20
 	fprintf (codefile, "while((%s)->len){\n", name);
-	asprintf (&n, "&(%s)->val[(%s)->len-1]", name, name);
-	if (n =3D=3D NULL)
+	if (asprintf (&n, "&(%s)->val[(%s)->len-1]", name, name) < 0 || n =3D=3D =
NULL)
 	    errx(1, "malloc");
 	free_type(n, t->subtype, FALSE);
-	fprintf(codefile,=20
+	fprintf(codefile,
 		"(%s)->len--;\n"
 		"}\n",
 		name);
@@ -145,6 +143,9 @@
     case TGeneralString:
 	free_primitive ("general_string", name);
 	break;
+    case TTeletexString:
+	free_primitive ("general_string", name);
+	break;
     case TUTF8String:
 	free_primitive ("utf8string", name);
 	break;
@@ -177,18 +178,14 @@
 void
 generate_type_free (const Symbol *s)
 {
-  int preserve =3D preserve_type(s->name) ? TRUE : FALSE;
+    int preserve =3D preserve_type(s->name) ? TRUE : FALSE;
=20
-  fprintf (headerfile,
-	   "void   free_%s  (%s *);\n",
-	   s->gen_name, s->gen_name);
+    fprintf (codefile, "void ASN1CALL\n"
+	     "free_%s(%s *data)\n"
+	     "{\n",
+	     s->gen_name, s->gen_name);
=20
-  fprintf (codefile, "void\n"
-	   "free_%s(%s *data)\n"
-	   "{\n",
-	   s->gen_name, s->gen_name);
-
-  free_type ("data", s->type, preserve);
-  fprintf (codefile, "}\n\n");
+    free_type ("data", s->type, preserve);
+    fprintf (codefile, "}\n\n");
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_glue.c
--- a/head/crypto/heimdal/lib/asn1/gen_glue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/gen_glue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,41 @@
 /*
- * Copyright (c) 1997, 1999, 2000, 2003 - 2005 Kungliga Tekniska H=F6gskol=
an
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1999, 2000, 2003 - 2005 Kungliga Tekniska H=C3=B6gs=
kolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: gen_glue.c 15617 2005-07-12 06:27:42Z lha $");
+RCSID("$Id$");
=20
 static void
 generate_2int (const Type *t, const char *gen_name)
@@ -70,7 +72,8 @@
     fprintf (codefile,
 	     "%s int2%s(unsigned n)\n"
 	     "{\n"
-	     "\t%s flags;\n\n",
+	     "\t%s flags;\n\n"
+	     "\tmemset(&flags, 0, sizeof(flags));\n\n",
 	     gen_name, gen_name, gen_name);
=20
     if(t->members) {
@@ -92,9 +95,17 @@
 {
     Member *m;
=20
-    fprintf (headerfile,
-	     "const struct units * asn1_%s_units(void);",
-	     gen_name);
+    if (template_flag) {
+	fprintf (headerfile,
+		 "extern const struct units *asn1_%s_table_units;\n",
+		 gen_name);
+	fprintf (headerfile, "#define asn1_%s_units() (asn1_%s_table_units)\n",
+		 gen_name, gen_name);
+    } else {
+	fprintf (headerfile,
+		 "const struct units * asn1_%s_units(void);\n",
+		 gen_name);
+    }
=20
     fprintf (codefile,
 	     "static struct units %s_units[] =3D {\n",
@@ -103,7 +114,7 @@
     if(t->members) {
 	ASN1_TAILQ_FOREACH_REVERSE(m, t->members, memhead, members) {
 	    fprintf (codefile,
-		     "\t{\"%s\",\t1U << %d},\n", m->gen_name, m->val);
+		     "\t{\"%s\",\t1U << %d},\n", m->name, m->val);
 	}
     }
=20
@@ -111,11 +122,16 @@
 	     "\t{NULL,\t0}\n"
 	     "};\n\n");
=20
-    fprintf (codefile,
-	     "const struct units * asn1_%s_units(void){\n"
-	     "return %s_units;\n"
-	     "}\n\n",
-	     gen_name, gen_name);
+    if (template_flag)
+	fprintf (codefile,
+		 "const struct units * asn1_%s_table_units =3D %s_units;\n",
+		 gen_name, gen_name);
+    else
+	fprintf (codefile,
+		 "const struct units * asn1_%s_units(void){\n"
+		 "return %s_units;\n"
+		 "}\n\n",
+		 gen_name, gen_name);
=20
=20
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_lengt=
h.c
--- a/head/crypto/heimdal/lib/asn1/gen_length.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/gen_length.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: gen_length.c 21503 2007-07-12 11:57:19Z lha $");
+RCSID("$Id$");
=20
 static void
 length_primitive (const char *typename,
@@ -43,11 +43,12 @@
     fprintf (codefile, "%s +=3D der_length_%s(%s);\n", variable, typename,=
 name);
 }
=20
+/* XXX same as der_length_tag */
 static size_t
 length_tag(unsigned int tag)
 {
     size_t len =3D 0;
-   =20
+
     if(tag <=3D 30)
 	return 1;
     while(tag) {
@@ -59,7 +60,7 @@
=20
=20
 static int
-length_type (const char *name, const Type *t,=20
+length_type (const char *name, const Type *t,
 	     const char *variable, const char *tmpstr)
 {
     switch (t->type) {
@@ -86,7 +87,7 @@
 	} else if (t->range->min =3D=3D 0 && t->range->max =3D=3D INT_MAX) {
 	    length_primitive ("unsigned", name, variable);
 	} else
-	    errx(1, "%s: unsupported range %d -> %d",=20
+	    errx(1, "%s: unsupported range %d -> %d",
 		 name, t->range->min, t->range->max);
=20
 	break;
@@ -133,13 +134,13 @@
=20
 	if (t->members =3D=3D NULL)
 	    break;
-     =20
+
 	if(t->type =3D=3D TChoice)
 	    fprintf (codefile, "switch((%s)->element) {\n", name);
=20
 	ASN1_TAILQ_FOREACH(m, t->members, members) {
 	    char *s;
-	   =20
+
 	    if (m->ellipsis) {
 		have_ellipsis =3D m;
 		continue;
@@ -148,10 +149,9 @@
 	    if(t->type =3D=3D TChoice)
 		fprintf(codefile, "case %s:\n", m->label);
=20
-	    asprintf (&s, "%s(%s)->%s%s",
-		      m->optional ? "" : "&", name,=20
-		      t->type =3D=3D TChoice ? "u." : "", m->gen_name);
-	    if (s =3D=3D NULL)
+	    if (asprintf (&s, "%s(%s)->%s%s",
+			  m->optional ? "" : "&", name,
+			  t->type =3D=3D TChoice ? "u." : "", m->gen_name) < 0 || s =3D=3D NULL)
 		errx(1, "malloc");
 	    if (m->optional)
 		fprintf (codefile, "if(%s)", s);
@@ -182,24 +182,22 @@
     }
     case TSetOf:
     case TSequenceOf: {
-	char *n;
-	char *sname;
+	char *n =3D NULL;
+	char *sname =3D NULL;
=20
 	fprintf (codefile,
 		 "{\n"
-		 "int %s_oldret =3D %s;\n"
+		 "size_t %s_oldret =3D %s;\n"
 		 "int i;\n"
 		 "%s =3D 0;\n",
 		 tmpstr, variable, variable);
=20
 	fprintf (codefile, "for(i =3D (%s)->len - 1; i >=3D 0; --i){\n", name);
-	fprintf (codefile, "int %s_for_oldret =3D %s;\n"
+	fprintf (codefile, "size_t %s_for_oldret =3D %s;\n"
 		 "%s =3D 0;\n", tmpstr, variable, variable);
-	asprintf (&n, "&(%s)->val[i]", name);
-	if (n =3D=3D NULL)
+	if (asprintf (&n, "&(%s)->val[i]", name) < 0  || n =3D=3D NULL)
 	    errx(1, "malloc");
-	asprintf (&sname, "%s_S_Of", tmpstr);
-	if (sname =3D=3D NULL)
+	if (asprintf (&sname, "%s_S_Of", tmpstr) < 0 || sname =3D=3D NULL)
 	    errx(1, "malloc");
 	length_type(n, t->subtype, variable, sname);
 	fprintf (codefile, "%s +=3D %s_for_oldret;\n",
@@ -219,6 +217,9 @@
     case TGeneralString:
 	length_primitive ("general_string", name, variable);
 	break;
+    case TTeletexString:
+	length_primitive ("general_string", name, variable);
+	break;
     case TUTCTime:
 	length_primitive ("utctime", name, variable);
 	break;
@@ -244,12 +245,11 @@
 	fprintf (codefile, "/* NULL */\n");
 	break;
     case TTag:{
-    	char *tname;
-	asprintf(&tname, "%s_tag", tmpstr);
-	if (tname =3D=3D NULL)
+    	char *tname =3D NULL;
+	if (asprintf(&tname, "%s_tag", tmpstr) < 0 || tname =3D=3D NULL)
 	    errx(1, "malloc");
 	length_type (name, t->subtype, variable, tname);
-	fprintf (codefile, "ret +=3D %lu + der_length_len (ret);\n",=20
+	fprintf (codefile, "ret +=3D %lu + der_length_len (ret);\n",
 		 (unsigned long)length_tag(t->tag.tagvalue));
 	free(tname);
 	break;
@@ -266,17 +266,13 @@
 void
 generate_type_length (const Symbol *s)
 {
-    fprintf (headerfile,
-	     "size_t length_%s(const %s *);\n",
-	     s->gen_name, s->gen_name);
-   =20
     fprintf (codefile,
-	     "size_t\n"
+	     "size_t ASN1CALL\n"
 	     "length_%s(const %s *data)\n"
 	     "{\n"
 	     "size_t ret =3D 0;\n",
 	     s->gen_name, s->gen_name);
-   =20
+
     length_type ("data", s->type, "ret", "Top");
     fprintf (codefile, "return ret;\n}\n\n");
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_locl.h
--- a/head/crypto/heimdal/lib/asn1/gen_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/gen_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,43 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: gen_locl.h 18008 2006-09-05 12:29:18Z lha $ */
+/* $Id$ */
=20
 #ifndef __GEN_LOCL_H__
 #define __GEN_LOCL_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #include <assert.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -53,6 +52,7 @@
 #include "symbol.h"
 #include "asn1-common.h"
 #include "der.h"
+#include "der-private.h"
=20
 void generate_type (const Symbol *);
 void generate_constant (const Symbol *);
@@ -75,14 +75,27 @@
 const char *get_filename (void);
 void close_generate(void);
 void add_import(const char *);
+void add_export(const char *);
+int is_export(const char *);
 int yyparse(void);
+int is_primitive_type(int);
=20
 int preserve_type(const char *);
 int seq_type(const char *);
=20
-extern FILE *headerfile, *codefile, *logfile;
-extern int dce_fix;
+void generate_header_of_codefile(const char *);
+void close_codefile(void);
+
+int is_template_compat (const Symbol *);
+void generate_template(const Symbol *);
+void gen_template_import(const Symbol *);
+
+
+extern FILE *privheaderfile, *headerfile, *codefile, *logfile, *templatefi=
le;
+extern int support_ber;
+extern int template_flag;
 extern int rfc1510_bitstring;
+extern int one_code_file;
=20
 extern int error_flag;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/gen_seq.c
--- a/head/crypto/heimdal/lib/asn1/gen_seq.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/gen_seq.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: gen_seq.c 20561 2007-04-24 16:14:30Z lha $");
+RCSID("$Id$");
=20
 void
 generate_type_seq (const Symbol *s)
@@ -47,8 +47,8 @@
     while(type->type =3D=3D TTag)
 	type =3D type->subtype;
=20
-    if (type->type !=3D TSequenceOf) {
-	printf("%s not seq of %d\n", s->name, (int)type->type);
+    if (type->type !=3D TSequenceOf && type->type !=3D TSetOf) {
+	fprintf(stderr, "%s not seq of %d\n", s->name, (int)type->type);
 	return;
     }
=20
@@ -56,7 +56,7 @@
      * Require the subtype to be a type so we can name it and use
      * copy_/free_
      */
-   =20
+
     if (type->subtype->type !=3D TType) {
 	fprintf(stderr, "%s subtype is not a type, can't generate "
 	       "sequence code for this case: %d\n",
@@ -67,17 +67,17 @@
     subname =3D type->subtype->symbol->gen_name;
=20
     fprintf (headerfile,
-	     "int   add_%s  (%s *, const %s *);\n"
-	     "int   remove_%s  (%s *, unsigned int);\n",
+	     "ASN1EXP int   ASN1CALL add_%s  (%s *, const %s *);\n"
+	     "ASN1EXP int   ASN1CALL remove_%s  (%s *, unsigned int);\n",
 	     s->gen_name, s->gen_name, subname,
 	     s->gen_name, s->gen_name);
=20
-    fprintf (codefile, "int\n"
+    fprintf (codefile, "int ASN1CALL\n"
 	     "add_%s(%s *data, const %s *element)\n"
 	     "{\n",
 	     s->gen_name, s->gen_name, subname);
=20
-    fprintf (codefile,=20
+    fprintf (codefile,
 	     "int ret;\n"
 	     "void *ptr;\n"
 	     "\n"
@@ -92,13 +92,13 @@
 	     subname);
=20
     fprintf (codefile, "}\n\n");
-   =20
-    fprintf (codefile, "int\n"
+
+    fprintf (codefile, "int ASN1CALL\n"
 	     "remove_%s(%s *data, unsigned int element)\n"
 	     "{\n",
 	     s->gen_name, s->gen_name);
=20
-    fprintf (codefile,=20
+    fprintf (codefile,
 	     "void *ptr;\n"
 	     "\n"
 	     "if (data->len =3D=3D 0 || element >=3D data->len)\n"
@@ -108,7 +108,7 @@
 	     /* don't move if its the last element */
 	     "if (element < data->len)\n"
 	     "\tmemmove(&data->val[element], &data->val[element + 1], \n"
-	     "\t\tsizeof(data->val[0]) * data->len);\n"
+	     "\t\tsizeof(data->val[0]) * (data->len - element));\n"
 	     /* resize but don't care about failures since it doesn't matter */
 	     "ptr =3D realloc(data->val, data->len * sizeof(data->val[0]));\n"
 	     "if (ptr !=3D NULL || data->len =3D=3D 0) data->val =3D ptr;\n"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/hash.c
--- a/head/crypto/heimdal/lib/asn1/hash.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/hash.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /*
@@ -37,7 +37,7 @@
=20
 #include "gen_locl.h"
=20
-RCSID("$Id: hash.c 17016 2006-04-07 22:16:00Z lha $");
+RCSID("$Id$");
=20
 static Hashentry *_search(Hashtab * htab,	/* The hash table */
 			  void *ptr);	/* And key */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/hash.h
--- a/head/crypto/heimdal/lib/asn1/hash.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/hash.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /*
  * hash.h. Header file for hash table functions
  */
=20
-/* $Id: hash.h 7464 1999-12-02 17:05:13Z joda $ */
+/* $Id$ */
=20
 struct hashentry {		/* Entry in bucket */
      struct hashentry **prev;
@@ -56,7 +56,7 @@
=20
 /* prototypes */
=20
-Hashtab *hashtabnew(int sz,=20
+Hashtab *hashtabnew(int sz,
 		    int (*cmp)(void *, void *),
 		    unsigned (*hash)(void *));	/* Make new hash table */
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/heim_asn1=
.h
--- a/head/crypto/heimdal/lib/asn1/heim_asn1.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/heim_asn1.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2003-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifndef __HEIM_ANY_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/kx509.asn1
--- a/head/crypto/heimdal/lib/asn1/kx509.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/kx509.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,19 @@
--- $Id: kx509.asn1 19546 2006-12-28 21:05:23Z lha $
+-- $Id$
=20
 KX509 DEFINITIONS ::=3D
 BEGIN
=20
+KX509-ERROR-CODE ::=3D INTEGER {
+	KX509-STATUS-GOOD(0),
+	KX509-STATUS-CLIENT-BAD(1),
+	KX509-STATUS-CLIENT-FIX(2),
+	KX509-STATUS-CLIENT-TEMP(3),
+	KX509-STATUS-SERVER-BAD(4),
+	KX509-STATUS-SERVER-TEMP(5),
+        -- 6 is used internally in the umich client, avoid that
+	KX509-STATUS-SERVER-KEY(7)
+}
+
 Kx509Request ::=3D SEQUENCE {
 	authenticator OCTET STRING,
 	pk-hash OCTET STRING,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/lex.c
--- a/head/crypto/heimdal/lib/asn1/lex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/lex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -8,7 +8,7 @@
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
 #define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 33
+#define YY_FLEX_SUBMINOR_VERSION 35
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -30,7 +30,7 @@
=20
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
=20
-#if __STDC_VERSION__ >=3D 199901L
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >=3D 199901L
=20
 /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
  * if you want the limit (max/min) macros for int types.=20
@@ -93,11 +93,12 @@
=20
 #else	/* ! __cplusplus */
=20
-#if __STDC__
+/* C99 requires __STDC__ to be defined as 1. */
+#if defined (__STDC__)
=20
 #define YY_USE_CONST
=20
-#endif	/* __STDC__ */
+#endif	/* defined (__STDC__) */
 #endif	/* ! __cplusplus */
=20
 #ifdef YY_USE_CONST
@@ -151,7 +152,12 @@
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
=20
-extern int yyleng;
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef size_t yy_size_t;
+#endif
+
+extern yy_size_t yyleng;
=20
 extern FILE *yyin, *yyout;
=20
@@ -177,16 +183,6 @@
=20
 #define unput(c) yyunput( c, (yytext_ptr)  )
=20
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
-
-#ifndef YY_TYPEDEF_YY_SIZE_T
-#define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
-#endif
-
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
@@ -204,7 +200,7 @@
 	/* Number of characters read into yy_ch_buf, not including EOB
 	 * characters.
 	 */
-	int yy_n_chars;
+	yy_size_t yy_n_chars;
=20
 	/* Whether we "own" the buffer - i.e., we know we created it,
 	 * and can realloc() it to grow it, and should free() it to
@@ -274,8 +270,8 @@
=20
 /* yy_hold_char holds the character lost when yytext is formed. */
 static char yy_hold_char;
-static int yy_n_chars;		/* number of characters read into yy_ch_buf */
-int yyleng;
+static yy_size_t yy_n_chars;		/* number of characters read into yy_ch_buf =
*/
+yy_size_t yyleng;
=20
 /* Points to current character in buffer. */
 static char *yy_c_buf_p =3D (char *) 0;
@@ -303,7 +299,7 @@
=20
 YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size  );
 YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str  );
-YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len  );
+YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len  );
=20
 void *yyalloc (yy_size_t  );
 void *yyrealloc (void *,yy_size_t  );
@@ -794,39 +790,39 @@
 #line 1 "lex.l"
 #line 2 "lex.l"
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: lex.l 18738 2006-10-21 11:57:22Z lha $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
@@ -840,7 +836,7 @@
 #endif
 #undef ECHO
 #include "symbol.h"
-#include "parse.h"
+#include "asn1parse.h"
 #include "lex.h"
 #include "gen_locl.h"
=20
@@ -851,7 +847,7 @@
 static void unterminated(const char *, unsigned);
=20
 /* This is for broken old lexes (solaris 10 and hpux) */
-#line 855 "lex.c"
+#line 851 "lex.c"
=20
 #define INITIAL 0
=20
@@ -869,6 +865,35 @@
=20
 static int yy_init_globals (void );
=20
+/* Accessor methods to globals.
+   These are made visible to non-reentrant scanners for convenience. */
+
+int yylex_destroy (void );
+
+int yyget_debug (void );
+
+void yyset_debug (int debug_flag  );
+
+YY_EXTRA_TYPE yyget_extra (void );
+
+void yyset_extra (YY_EXTRA_TYPE user_defined  );
+
+FILE *yyget_in (void );
+
+void yyset_in  (FILE * in_str  );
+
+FILE *yyget_out (void );
+
+void yyset_out  (FILE * out_str  );
+
+yy_size_t yyget_leng (void );
+
+char *yyget_text (void );
+
+int yyget_lineno (void );
+
+void yyset_lineno (int line_number  );
+
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
  */
@@ -911,7 +936,7 @@
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#define ECHO fwrite( yytext, yyleng, 1, yyout )
 #endif
=20
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_=
NULL,
@@ -922,7 +947,7 @@
 	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
 		{ \
 		int c =3D '*'; \
-		size_t n; \
+		yy_size_t n; \
 		for ( n =3D 0; n < max_size && \
 			     (c =3D getc( yyin )) !=3D EOF && c !=3D '\n'; ++n ) \
 			buf[n] =3D (char) c; \
@@ -1006,7 +1031,7 @@
    =20
 #line 68 "lex.l"
=20
-#line 1010 "lex.c"
+#line 1035 "lex.c"
=20
 	if ( !(yy_init) )
 		{
@@ -1512,7 +1537,7 @@
 case 85:
 YY_RULE_SETUP
 #line 153 "lex.l"
-{=20
+{
 			    int c, start_lineno =3D lineno;
 			    int f =3D 0;
 			    while((c =3D input()) !=3D EOF) {
@@ -1535,7 +1560,7 @@
 case 86:
 YY_RULE_SETUP
 #line 172 "lex.l"
-{=20
+{
 			    int c, start_lineno =3D lineno;
 			    int level =3D 1;
 			    int seen_star =3D 0;
@@ -1562,7 +1587,7 @@
 					level++;
 					seen_star =3D seen_slash =3D 0;
 					continue;
-				    }=20
+				    }
 				    seen_star =3D 1;
 				    continue;
 				}
@@ -1579,14 +1604,14 @@
 case 87:
 YY_RULE_SETUP
 #line 212 "lex.l"
-{=20
+{
 			    int start_lineno =3D lineno;
 			    int c;
 			    char buf[1024];
 			    char *p =3D buf;
 			    int f =3D 0;
 			    int skip_ws =3D 0;
-			   =20
+
 			    while((c =3D input()) !=3D EOF) {
 				if(isspace(c) && skip_ws) {
 				    if(c =3D=3D '\n')
@@ -1594,7 +1619,7 @@
 				    continue;
 				}
 				skip_ws =3D 0;
-			=09
+
 				if(c =3D=3D '"') {
 				    if(f) {
 					*p++ =3D '"';
@@ -1621,7 +1646,7 @@
 			    *p++ =3D '\0';
 			    fprintf(stderr, "string -- %s\n", buf);
 			    yylval.name =3D estrdup(buf);
-			    return STRING;=20
+			    return STRING;
 			}
 	YY_BREAK
 case 88:
@@ -1630,8 +1655,8 @@
 { char *e, *y =3D yytext;
 			  yylval.constant =3D strtol((const char *)yytext,
 						   &e, 0);
-			  if(e =3D=3D y)=20
-			    error_message("malformed constant (%s)", yytext);=20
+			  if(e =3D=3D y)
+			    lex_error_message("malformed constant (%s)", yytext);
 			  else
 			    return NUMBER;
 			}
@@ -1668,14 +1693,14 @@
 case 94:
 YY_RULE_SETUP
 #line 273 "lex.l"
-{ error_message("Ignoring char(%c)\n", *yytext); }
+{ lex_error_message("Ignoring char(%c)\n", *yytext); }
 	YY_BREAK
 case 95:
 YY_RULE_SETUP
 #line 274 "lex.l"
 ECHO;
 	YY_BREAK
-#line 1679 "lex.c"
+#line 1704 "lex.c"
 case YY_STATE_EOF(INITIAL):
 	yyterminate();
=20
@@ -1861,7 +1886,7 @@
=20
 	else
 		{
-			int num_to_read =3D
+			yy_size_t num_to_read =3D
 			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
=20
 		while ( num_to_read <=3D 0 )
@@ -1875,7 +1900,7 @@
=20
 			if ( b->yy_is_our_buffer )
 				{
-				int new_size =3D b->yy_buf_size * 2;
+				yy_size_t new_size =3D b->yy_buf_size * 2;
=20
 				if ( new_size <=3D 0 )
 					b->yy_buf_size +=3D b->yy_buf_size / 8;
@@ -1930,6 +1955,14 @@
 	else
 		ret_val =3D EOB_ACT_CONTINUE_SCAN;
=20
+	if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALU=
E->yy_buf_size) {
+		/* Extend the array by 50%, plus the number we really need. */
+		yy_size_t new_size =3D (yy_n_chars) + number_to_move + ((yy_n_chars) >> =
1);
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf =3D (char *) yyrealloc((void *) YY_C=
URRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
+		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+	}
+
 	(yy_n_chars) +=3D number_to_move;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] =3D YY_END_OF_BUFFER_CH=
AR;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] =3D YY_END_OF_BUFFE=
R_CHAR;
@@ -2008,7 +2041,7 @@
 	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
 		{ /* need to shift things up to make room */
 		/* +2 for EOB chars. */
-		register int number_to_move =3D (yy_n_chars) + 2;
+		register yy_size_t number_to_move =3D (yy_n_chars) + 2;
 		register char *dest =3D &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
 					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
 		register char *source =3D
@@ -2057,7 +2090,7 @@
=20
 		else
 			{ /* need more input */
-			int offset =3D (yy_c_buf_p) - (yytext_ptr);
+			yy_size_t offset =3D (yy_c_buf_p) - (yytext_ptr);
 			++(yy_c_buf_p);
=20
 			switch ( yy_get_next_buffer(  ) )
@@ -2333,7 +2366,7 @@
  */
 static void yyensure_buffer_stack (void)
 {
-	int num_to_alloc;
+	yy_size_t num_to_alloc;
    =20
 	if (!(yy_buffer_stack)) {
=20
@@ -2345,7 +2378,9 @@
 		(yy_buffer_stack) =3D (struct yy_buffer_state**)yyalloc
 								(num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
-	=09
+		if ( ! (yy_buffer_stack) )
+			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
+								 =20
 		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_stat=
e*));
 			=09
 		(yy_buffer_stack_max) =3D num_to_alloc;
@@ -2363,6 +2398,8 @@
 								((yy_buffer_stack),
 								num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
+		if ( ! (yy_buffer_stack) )
+			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
=20
 		/* zero only the new slots.*/
 		memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(=
struct yy_buffer_state*));
@@ -2407,7 +2444,7 @@
=20
 /** Setup the input buffer state to scan a string. The next call to yylex(=
) will
  * scan from a @e copy of @a str.
- * @param str a NUL-terminated string to scan
+ * @param yystr a NUL-terminated string to scan
  *=20
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
@@ -2426,12 +2463,11 @@
  *=20
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len )
+YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, yy_size_t  _yybyte=
s_len )
 {
 	YY_BUFFER_STATE b;
 	char *buf;
-	yy_size_t n;
-	int i;
+	yy_size_t n, i;
    =20
 	/* Get memory for full buffer, including space for trailing EOB's. */
 	n =3D _yybytes_len + 2;
@@ -2513,7 +2549,7 @@
 /** Get the length of the current token.
  *=20
  */
-int yyget_leng  (void)
+yy_size_t yyget_leng  (void)
 {
         return yyleng;
 }
@@ -2667,14 +2703,14 @@
=20
 #ifndef yywrap /* XXX */
 int
-yywrap ()=20
+yywrap ()
 {
      return 1;
 }
 #endif
=20
 void
-error_message (const char *format, ...)
+lex_error_message (const char *format, ...)
 {
     va_list args;
=20
@@ -2688,6 +2724,6 @@
 static void
 unterminated(const char *type, unsigned start_lineno)
 {
-    error_message("unterminated %s, possibly started on line %d\n", type, =
start_lineno);
+    lex_error_message("unterminated %s, possibly started on line %d\n", ty=
pe, start_lineno);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/lex.h
--- a/head/crypto/heimdal/lib/asn1/lex.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/lex.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: lex.h 15617 2005-07-12 06:27:42Z lha $ */
+/* $Id$ */
=20
 #include <roken.h>
=20
-void error_message (const char *, ...)
+void lex_error_message (const char *, ...)
 __attribute__ ((format (printf, 1, 2)));
 extern int error_flag;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/lex.l
--- a/head/crypto/heimdal/lib/asn1/lex.l	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/lex.l	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 %{
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: lex.l 18738 2006-10-21 11:57:22Z lha $ */
+/* $Id$ */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
@@ -46,7 +46,7 @@
 #endif
 #undef ECHO
 #include "symbol.h"
-#include "parse.h"
+#include "asn1parse.h"
 #include "lex.h"
 #include "gen_locl.h"
=20
@@ -150,7 +150,7 @@
 "["			{ return *yytext; }
 "]"			{ return *yytext; }
 ::=3D			{ return EEQUAL; }
---			{=20
+--			{
 			    int c, start_lineno =3D lineno;
 			    int f =3D 0;
 			    while((c =3D input()) !=3D EOF) {
@@ -169,7 +169,7 @@
 			    if(c =3D=3D EOF)
 				unterminated("comment", start_lineno);
 			}
-\/\*			{=20
+\/\*			{
 			    int c, start_lineno =3D lineno;
 			    int level =3D 1;
 			    int seen_star =3D 0;
@@ -196,7 +196,7 @@
 					level++;
 					seen_star =3D seen_slash =3D 0;
 					continue;
-				    }=20
+				    }
 				    seen_star =3D 1;
 				    continue;
 				}
@@ -209,14 +209,14 @@
 			    if(c =3D=3D EOF)
 				unterminated("comment", start_lineno);
 			}
-"\""			{=20
+"\""			{
 			    int start_lineno =3D lineno;
 			    int c;
 			    char buf[1024];
 			    char *p =3D buf;
 			    int f =3D 0;
 			    int skip_ws =3D 0;
-			   =20
+
 			    while((c =3D input()) !=3D EOF) {
 				if(isspace(c) && skip_ws) {
 				    if(c =3D=3D '\n')
@@ -224,7 +224,7 @@
 				    continue;
 				}
 				skip_ws =3D 0;
-			=09
+
 				if(c =3D=3D '"') {
 				    if(f) {
 					*p++ =3D '"';
@@ -251,14 +251,14 @@
 			    *p++ =3D '\0';
 			    fprintf(stderr, "string -- %s\n", buf);
 			    yylval.name =3D estrdup(buf);
-			    return STRING;=20
+			    return STRING;
 			}
=20
 -?0x[0-9A-Fa-f]+|-?[0-9]+ { char *e, *y =3D yytext;
 			  yylval.constant =3D strtol((const char *)yytext,
 						   &e, 0);
-			  if(e =3D=3D y)=20
-			    error_message("malformed constant (%s)", yytext);=20
+			  if(e =3D=3D y)
+			    lex_error_message("malformed constant (%s)", yytext);
 			  else
 			    return NUMBER;
 			}
@@ -270,19 +270,19 @@
 \n			{ ++lineno; }
 \.\.\.			{ return ELLIPSIS; }
 \.\.			{ return RANGE; }
-.			{ error_message("Ignoring char(%c)\n", *yytext); }
+.			{ lex_error_message("Ignoring char(%c)\n", *yytext); }
 %%
=20
 #ifndef yywrap /* XXX */
 int
-yywrap ()=20
+yywrap ()
 {
      return 1;
 }
 #endif
=20
 void
-error_message (const char *format, ...)
+lex_error_message (const char *format, ...)
 {
     va_list args;
=20
@@ -296,5 +296,5 @@
 static void
 unterminated(const char *type, unsigned start_lineno)
 {
-    error_message("unterminated %s, possibly started on line %d\n", type, =
start_lineno);
+    lex_error_message("unterminated %s, possibly started on line %d\n", ty=
pe, start_lineno);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/main.c
--- a/head/crypto/heimdal/lib/asn1/main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "gen_locl.h"
 #include <getarg.h>
 #include "lex.h"
=20
-RCSID("$Id: main.c 20858 2007-06-03 18:56:41Z lha $");
+RCSID("$Id$");
=20
 extern FILE *yyin;
=20
@@ -62,15 +62,22 @@
     return 0;
 }
=20
-int dce_fix;
+int support_ber;
+int template_flag;
 int rfc1510_bitstring;
+int one_code_file;
+char *option_file;
 int version_flag;
 int help_flag;
 struct getargs args[] =3D {
+    { "template", 0, arg_flag, &template_flag },
     { "encode-rfc1510-bit-string", 0, arg_flag, &rfc1510_bitstring },
-    { "decode-dce-ber", 0, arg_flag, &dce_fix },
+    { "decode-dce-ber", 0, arg_flag, &support_ber },
+    { "support-ber", 0, arg_flag, &support_ber },
     { "preserve-binary", 0, arg_strings, &preserve },
     { "sequence", 0, arg_strings, &seq },
+    { "one-code-file", 0, arg_flag, &one_code_file },
+    { "option-file", 0, arg_string, &option_file },
     { "version", 0, arg_flag, &version_flag },
     { "help", 0, arg_flag, &help_flag }
 };
@@ -92,6 +99,8 @@
     const char *file;
     const char *name =3D NULL;
     int optidx =3D 0;
+    char **arg =3D NULL;
+    size_t len =3D 0, i;
=20
     setprogname(argv[0]);
     if(getarg(args, num_args, argc, argv, &optidx))
@@ -121,7 +130,62 @@
 	    name =3D argv[optidx + 1];
     }
=20
+    /*
+     * Parse extra options file
+     */
+    if (option_file) {
+	char buf[1024];
+	FILE *opt;
+
+	opt =3D fopen(option_file, "r");
+	if (opt =3D=3D NULL) {
+	    perror("open");
+	    exit(1);
+	}
+
+	arg =3D calloc(2, sizeof(arg[0]));
+	if (arg =3D=3D NULL) {
+	    perror("calloc");
+	    exit(1);
+	}
+	arg[0] =3D option_file;
+	arg[1] =3D NULL;
+	len =3D 1;
+
+	while (fgets(buf, sizeof(buf), opt) !=3D NULL) {
+	    buf[strcspn(buf, "\n\r")] =3D '\0';
+
+	    arg =3D realloc(arg, (len + 2) * sizeof(arg[0]));
+	    if (arg =3D=3D NULL) {
+		perror("malloc");
+		exit(1);
+	    }
+	    arg[len] =3D strdup(buf);
+	    if (arg[len] =3D=3D NULL) {
+		perror("strdup");
+		exit(1);
+	    }
+	    arg[len + 1] =3D NULL;
+	    len++;
+	}
+	fclose(opt);
+
+	optidx =3D 0;
+	if(getarg(args, num_args, len, arg, &optidx))
+	    usage(1);
+
+	if (len !=3D optidx) {
+	    fprintf(stderr, "extra args");
+	    exit(1);
+	}
+    }
+
+
     init_generate (file, name);
+
+    if (one_code_file)
+	generate_header_of_codefile(name);
+
     initsym ();
     ret =3D yyparse ();
     if(ret !=3D 0 || error_flag !=3D 0)
@@ -129,5 +193,15 @@
     close_generate ();
     if (argc !=3D optidx)
 	fclose(yyin);
+
+    if (one_code_file)
+	close_codefile();
+
+    if (arg) {
+	for (i =3D 1; i < len; i++)
+	    free(arg[i]);
+	free(arg);
+    }
+
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/pkcs12.as=
n1
--- a/head/crypto/heimdal/lib/asn1/pkcs12.asn1	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/pkcs12.asn1	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
--- $Id: pkcs12.asn1 15715 2005-07-23 11:08:47Z lha $ --
+-- $Id$ --
=20
 PKCS12 DEFINITIONS ::=3D
=20
@@ -50,7 +50,7 @@
=20
 PKCS12-Attribute ::=3D SEQUENCE {
 	attrId	   	OBJECT IDENTIFIER,
-	attrValues 	-- SET OF -- heim_any_set=20
+	attrValues 	-- SET OF -- heim_any_set
 }
=20
 PKCS12-Attributes ::=3D SET OF PKCS12-Attribute
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/pkcs8.asn1
--- a/head/crypto/heimdal/lib/asn1/pkcs8.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/pkcs8.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
--- $Id: pkcs8.asn1 16060 2005-09-13 19:41:29Z lha $ --
+-- $Id$ --
=20
 PKCS8 DEFINITIONS ::=3D
=20
@@ -24,7 +24,7 @@
=20
 PKCS8EncryptedPrivateKeyInfo ::=3D SEQUENCE {
     encryptionAlgorithm AlgorithmIdentifier,
-    encryptedData PKCS8EncryptedData=20
+    encryptedData PKCS8EncryptedData
 }
=20
 END
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/pkcs9.asn1
--- a/head/crypto/heimdal/lib/asn1/pkcs9.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/pkcs9.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
--- $Id: pkcs9.asn1 17202 2006-04-24 08:59:10Z lha $ --
+-- $Id$ --
=20
 PKCS9 DEFINITIONS ::=3D
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/pkinit.as=
n1
--- a/head/crypto/heimdal/lib/asn1/pkinit.asn1	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/asn1/pkinit.asn1	Tue Apr 17 11:51:51 2012 +03=
00
@@ -17,16 +17,21 @@
 id-pkekuoid    OBJECT IDENTIFIER  ::=3D { id-pkinit 4 }
 id-pkkdcekuoid OBJECT IDENTIFIER  ::=3D { id-pkinit 5 }
=20
+id-pkinit-kdf OBJECT IDENTIFIER           ::=3D { id-pkinit 6 }
+id-pkinit-kdf-ah-sha1 OBJECT IDENTIFIER   ::=3D { id-pkinit-kdf 1 }
+id-pkinit-kdf-ah-sha256 OBJECT IDENTIFIER ::=3D { id-pkinit-kdf 2 }
+id-pkinit-kdf-ah-sha512 OBJECT IDENTIFIER ::=3D { id-pkinit-kdf 3 }
+
 id-pkinit-san	OBJECT IDENTIFIER ::=3D
   { iso(1) org(3) dod(6) internet(1) security(5) kerberosv5(2)
     x509-sanan(2) }
=20
 id-pkinit-ms-eku OBJECT IDENTIFIER ::=3D
-  { iso(1) org(3) dod(6) internet(1) private(4)=20
+  { iso(1) org(3) dod(6) internet(1) private(4)
     enterprise(1) microsoft(311) 20 2 2 }
=20
 id-pkinit-ms-san OBJECT IDENTIFIER ::=3D
-  { iso(1) org(3) dod(6) internet(1) private(4)=20
+  { iso(1) org(3) dod(6) internet(1) private(4)
     enterprise(1) microsoft(311) 20 2 3 }
=20
 MS-UPN-SAN ::=3D UTF8String
@@ -147,19 +152,18 @@
 	issuerAndSerial         [2] IssuerAndSerialNumber
 }
=20
-PA-PK-AS-REQ-Win2k ::=3D SEQUENCE {=20
-	signed-auth-pack	[0] IMPLICIT OCTET STRING,=20
-	trusted-certifiers	[2] SEQUENCE OF TrustedCA-Win2k OPTIONAL,=20
-	kdc-cert		[3] IMPLICIT OCTET STRING OPTIONAL,=20
+PA-PK-AS-REQ-Win2k ::=3D SEQUENCE {
+	signed-auth-pack	[0] IMPLICIT OCTET STRING,
+	trusted-certifiers	[2] SEQUENCE OF TrustedCA-Win2k OPTIONAL,
+	kdc-cert		[3] IMPLICIT OCTET STRING OPTIONAL,
 	encryption-cert		[4] IMPLICIT OCTET STRING OPTIONAL
 }
=20
 PA-PK-AS-REP-Win2k ::=3D CHOICE {
-	dhSignedData		[0] IMPLICIT OCTET STRING,=20
+	dhSignedData		[0] IMPLICIT OCTET STRING,
 	encKeyPack		[1] IMPLICIT OCTET STRING
 }
=20
-
 KDCDHKeyInfo-Win2k ::=3D SEQUENCE {
 	nonce			[0] INTEGER (-2147483648..2147483647),
 	subjectPublicKey	[2] BIT STRING
@@ -171,6 +175,20 @@
 	...
 }
=20
+PA-PK-AS-REP-BTMM ::=3D SEQUENCE {
+	dhSignedData		[0] heim_any OPTIONAL,
+	encKeyPack		[1] heim_any OPTIONAL
+}
+
+
+PkinitSP80056AOtherInfo ::=3D SEQUENCE {
+	algorithmID   AlgorithmIdentifier,
+	partyUInfo     [0] OCTET STRING,
+	partyVInfo     [1] OCTET STRING,
+	suppPubInfo    [2] OCTET STRING OPTIONAL,
+	suppPrivInfo   [3] OCTET STRING OPTIONAL
+}
+
 PkinitSuppPubInfo ::=3D SEQUENCE {
        enctype           [0] INTEGER (-2147483648..2147483647),
        as-REQ            [1] OCTET STRING,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/rfc2459.a=
sn1
--- a/head/crypto/heimdal/lib/asn1/rfc2459.asn1	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/asn1/rfc2459.asn1	Tue Apr 17 11:51:51 2012 +0=
300
@@ -6,7 +6,7 @@
 IMPORTS heim_any FROM heim;
=20
 Version ::=3D  INTEGER {
-	rfc3280_version_1(0),=20
+	rfc3280_version_1(0),
 	rfc3280_version_2(1),
 	rfc3280_version_3(2)
 }
@@ -29,7 +29,7 @@
 id-pkcs2-md4 OBJECT IDENTIFIER ::=3D		{ id-pkcs-2 4 }
 id-pkcs2-md5 OBJECT IDENTIFIER ::=3D		{ id-pkcs-2 5 }
=20
-id-rsa-digestAlgorithm OBJECT IDENTIFIER ::=3D=20
+id-rsa-digestAlgorithm OBJECT IDENTIFIER ::=3D
 { iso(1) member-body(2) us(840) rsadsi(113549) 2 }
=20
 id-rsa-digest-md2 OBJECT IDENTIFIER ::=3D { id-rsa-digestAlgorithm 2 }
@@ -52,9 +52,12 @@
 id-secsig-sha-1 OBJECT IDENTIFIER ::=3D { iso(1) identified-organization(3)
 	oiw(14) secsig(3) algorithm(2) 26 }
=20
+id-secsig-sha-1WithRSAEncryption OBJECT IDENTIFIER ::=3D { iso(1) identifi=
ed-organization(3)
+	oiw(14) secsig(3) algorithm(2) 29 }
+
 id-nistAlgorithm OBJECT IDENTIFIER ::=3D {
    joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3)=
 4 }
-  =20
+ =20
 id-nist-aes-algs OBJECT IDENTIFIER ::=3D { id-nistAlgorithm 1 }
=20
 id-aes-128-cbc OBJECT IDENTIFIER ::=3D		{ id-nist-aes-algs 2 }
@@ -72,9 +75,42 @@
         iso(1) member-body(2) us(840) ansi-x942(10046)
         number-type(2) 1 }
=20
+-- ECC
+
+id-ecPublicKey OBJECT IDENTIFIER ::=3D {
+       iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
+
+id-ecDH OBJECT IDENTIFIER ::=3D {
+       iso(1) identified-organization(3) certicom(132) schemes(1)
+       ecdh(12) }
+
+id-ecMQV OBJECT IDENTIFIER ::=3D {
+       iso(1) identified-organization(3) certicom(132) schemes(1)
+       ecmqv(13) }
+
+id-ecdsa-with-SHA256 OBJECT IDENTIFIER ::=3D {
+     iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+     ecdsa-with-SHA2(3) 2 }
+
+id-ecdsa-with-SHA1 OBJECT IDENTIFIER ::=3D {
+     iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 }
+
+-- some EC group ids
+
+id-ec-group-secp256r1 OBJECT IDENTIFIER ::=3D {
+       iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
+       prime(1) 7 }
+
+id-ec-group-secp160r1 OBJECT IDENTIFIER ::=3D {
+       iso(1) identified-organization(3) certicom(132) 0 8 }
+
+id-ec-group-secp160r2 OBJECT IDENTIFIER ::=3D {
+       iso(1) identified-organization(3) certicom(132) 0 30 }
+
+-- DSA
+
 id-x9-57 OBJECT IDENTIFIER ::=3D {
-        iso(1) member-body(2) us(840) ansi-x942(10046)
-	4 }
+        iso(1) member-body(2) us(840) ansi-x942(10046) 4 }
=20
 id-dsa OBJECT IDENTIFIER ::=3D		{ id-x9-57 1 }
 id-dsa-with-sha1 OBJECT IDENTIFIER ::=3D		{ id-x9-57 3 }
@@ -117,11 +153,9 @@
=20
 AttributeValue ::=3D   heim_any
=20
-TeletexStringx ::=3D [UNIVERSAL 20] IMPLICIT OCTET STRING
-
 DirectoryString ::=3D CHOICE {
 	ia5String	IA5String,
-	teletexString	TeletexStringx,
+	teletexString	TeletexString,
 	printableString	PrintableString,
 	universalString UniversalString,
 	utf8String	UTF8String,
@@ -210,6 +244,13 @@
 	validationParms	ValidationParms OPTIONAL -- ValidationParms
 }
=20
+-- As defined by PKCS3
+DHParameter ::=3D SEQUENCE {
+	prime		INTEGER, -- odd prime, p=3Djq +1
+	base		INTEGER, -- generator, g
+	privateValueLength INTEGER OPTIONAL
+}
+
 DHPublicKey ::=3D INTEGER
=20
 OtherName ::=3D SEQUENCE {
@@ -256,8 +297,8 @@
=20
 AuthorityKeyIdentifier ::=3D SEQUENCE {
 	keyIdentifier             [0] IMPLICIT OCTET STRING OPTIONAL,
-	authorityCertIssuer       [1] IMPLICIT -- GeneralName --=20
-		SEQUENCE -- SIZE (1..MAX) -- OF GeneralName OPTIONAL,=20
+	authorityCertIssuer       [1] IMPLICIT -- GeneralName --
+		SEQUENCE -- SIZE (1..MAX) -- OF GeneralName OPTIONAL,
 	authorityCertSerialNumber [2] IMPLICIT INTEGER OPTIONAL
 }
=20
@@ -269,7 +310,7 @@
=20
 BasicConstraints ::=3D SEQUENCE {
 	cA                      BOOLEAN OPTIONAL -- DEFAULT FALSE --,
-	pathLenConstraint	INTEGER (0..4294967295) OPTIONAL=20
+	pathLenConstraint	INTEGER (0..4294967295) OPTIONAL
 }
=20
 id-x509-ce-nameConstraints OBJECT IDENTIFIER ::=3D  { id-x509-ce 30 }
@@ -350,6 +391,21 @@
 	g	INTEGER
 }
=20
+-- draft-ietf-pkix-ecc-subpubkeyinfo-11
+
+ECPoint ::=3D OCTET STRING
+
+ECParameters ::=3D CHOICE {
+	namedCurve         OBJECT IDENTIFIER
+	-- implicitCurve   NULL
+	-- specifiedCurve  SpecifiedECDomain
+}
+
+ECDSA-Sig-Value ::=3D SEQUENCE {
+     r  INTEGER,
+     s  INTEGER
+}
+
 -- really pkcs1
=20
 RSAPublicKey ::=3D SEQUENCE {
@@ -382,7 +438,7 @@
=20
 -- szOID_CERTIFICATE_TEMPLATE "1.3.6.1.4.1.311.21.7" is Encoded as:
=20
--- TemplateVersion ::=3D INTEGER (0..4294967295)=20
+-- TemplateVersion ::=3D INTEGER (0..4294967295)
=20
 -- CertificateTemplate ::=3D SEQUENCE {
 --	templateID OBJECT IDENTIFIER,
@@ -393,7 +449,7 @@
=20
 --
 -- CRL
---=20
+--
=20
 TBSCRLCertList ::=3D  SEQUENCE  {
 	version			Version OPTIONAL, -- if present, MUST be v2
@@ -489,16 +545,16 @@
=20
 --- Netscape extentions
=20
-id-netscape OBJECT IDENTIFIER ::=3D=20
+id-netscape OBJECT IDENTIFIER ::=3D
     { joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(1137=
30) }
 id-netscape-cert-comment OBJECT IDENTIFIER ::=3D { id-netscape 1 13 }
=20
 --- MS extentions
=20
-id-ms-cert-enroll-domaincontroller OBJECT IDENTIFIER ::=3D=20
+id-ms-cert-enroll-domaincontroller OBJECT IDENTIFIER ::=3D
     { 1 3 6 1 4 1 311 20 2 }
=20
-id-ms-client-authentication OBJECT IDENTIFIER ::=3D=20
+id-ms-client-authentication OBJECT IDENTIFIER ::=3D
  { 1 3 6 1 5 5 7 3 2 }
=20
 -- DER:1e:20:00:44:00:6f:00:6d:00:61:00:69:00:6e:00:43:00:6f:00:6e:00:74:0=
0:72:00:6f:00:6c:00:6c:00:65:00:72
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/setchgpw2=
.asn1
--- a/head/crypto/heimdal/lib/asn1/setchgpw2.asn1	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/asn1/setchgpw2.asn1	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
--- $Id: setchgpw2.asn1 18010 2006-09-05 12:31:59Z lha $
+-- $Id$
=20
 SETCHGPW2 DEFINITIONS ::=3D
 BEGIN
@@ -138,7 +138,7 @@
 	get-supported-etypes[5]	Req-get-supported-etypes,
 	...
 }
-=20
+
 Op-rep ::=3D CHOICE {
 	null[0]			Rep-null,
 	change-pw[1]		Rep-change-pw,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/symbol.c
--- a/head/crypto/heimdal/lib/asn1/symbol.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/symbol.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
@@ -34,8 +34,6 @@
 #include "gen_locl.h"
 #include "lex.h"
=20
-RCSID("$Id: symbol.c 15617 2005-07-12 06:27:42Z lha $");
-
 static Hashtab *htab;
=20
 static int
@@ -68,7 +66,7 @@
     char *p;
=20
     for (p =3D s; *p; ++p)
-	if (*p =3D=3D '-')
+	if (*p =3D=3D '-' || *p =3D=3D '.')
 	    *p =3D '_';
 }
=20
@@ -95,7 +93,7 @@
 {
     Symbol *s =3D ptr;
     if (s->stype =3D=3D SUndefined) {
-	error_message("%s is still undefined\n", s->name);
+	lex_error_message("%s is still undefined\n", s->name);
 	*(int *) arg =3D 1;
     }
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/symbol.h
--- a/head/crypto/heimdal/lib/asn1/symbol.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/symbol.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,63 +1,64 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: symbol.h 19539 2006-12-28 17:15:05Z lha $ */
+/* $Id$ */
=20
 #ifndef _SYMBOL_H
 #define _SYMBOL_H
=20
 #include "asn1_queue.h"
=20
-enum typetype {=20
+enum typetype {
     TBitString,
     TBoolean,
-    TChoice,=20
+    TChoice,
     TEnumerated,
-    TGeneralString,=20
-    TGeneralizedTime,=20
+    TGeneralString,
+    TTeletexString,
+    TGeneralizedTime,
     TIA5String,
-    TInteger,=20
+    TInteger,
     TNull,
-    TOID,=20
-    TOctetString,=20
+    TOID,
+    TOctetString,
     TPrintableString,
-    TSequence,=20
+    TSequence,
     TSequenceOf,
-    TSet,=20
+    TSet,
     TSetOf,
-    TTag,=20
-    TType,=20
-    TUTCTime,=20
+    TTag,
+    TType,
+    TUTCTime,
     TUTF8String,
     TBMPString,
     TUniversalString,
@@ -69,10 +70,10 @@
 struct type;
=20
 struct value {
-    enum { booleanvalue,=20
-	   nullvalue,=20
-	   integervalue,=20
-	   stringvalue,=20
+    enum { booleanvalue,
+	   nullvalue,
+	   integervalue,
+	   stringvalue,
 	   objectidentifiervalue
     } type;
     union {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/test.asn1
--- a/head/crypto/heimdal/lib/asn1/test.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/test.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
--- $Id: test.asn1 21455 2007-07-10 12:51:19Z lha $ --
+-- $Id$ --
=20
 TEST DEFINITIONS ::=3D
=20
@@ -6,8 +6,11 @@
=20
 IMPORTS heim_any FROM heim;
=20
+TESTuint32 ::=3D INTEGER (0..4294967295)
+
 TESTLargeTag ::=3D SEQUENCE {
-	foo[127] INTEGER (-2147483648..2147483647)
+	foo[127] INTEGER (-2147483648..2147483647),
+	bar[128] INTEGER (-2147483648..2147483647)
 }
=20
 TESTSeq ::=3D SEQUENCE {
@@ -20,12 +23,12 @@
 TESTChoice1 ::=3D CHOICE {
 	i1[1]	INTEGER (-2147483648..2147483647),
 	i2[2]	INTEGER (-2147483648..2147483647),
-	...=09
+	...
 }
=20
 TESTChoice2 ::=3D CHOICE {
 	i1[1]	INTEGER (-2147483648..2147483647),
-	...=09
+	...
 }
=20
 TESTInteger ::=3D INTEGER (-2147483648..2147483647)
@@ -35,7 +38,7 @@
=20
 TESTImplicit ::=3D SEQUENCE {
 	ti1[0] IMPLICIT INTEGER (-2147483648..2147483647),
-	ti2[1] IMPLICIT SEQUENCE {=20
+	ti2[1] IMPLICIT SEQUENCE {
 		foo[127] INTEGER (-2147483648..2147483647)
 	},
 	ti3[2] IMPLICIT [5] IMPLICIT [4] IMPLICIT INTEGER (-2147483648..214748364=
7)
@@ -57,21 +60,26 @@
 	  tagless2 heim_any OPTIONAL
 }
=20
+TESTOptional ::=3D SEQUENCE {
+	  zero [0] INTEGER (-2147483648..2147483647) OPTIONAL,
+	  one [1] INTEGER (-2147483648..2147483647) OPTIONAL
+}
+
=20
 TESTCONTAINING ::=3D OCTET STRING ( CONTAINING INTEGER )
-TESTENCODEDBY ::=3D OCTET STRING ( ENCODED BY=20
+TESTENCODEDBY ::=3D OCTET STRING ( ENCODED BY
   { joint-iso-itu-t(2) asn(1) ber-derived(2) distinguished-encoding(1) }
 )
=20
-TESTDer OBJECT IDENTIFIER ::=3D {=20
+TESTDer OBJECT IDENTIFIER ::=3D {
 	joint-iso-itu-t(2) asn(1) ber-derived(2) distinguished-encoding(1)
 }
=20
-TESTCONTAININGENCODEDBY ::=3D OCTET STRING ( CONTAINING INTEGER ENCODED BY=20
+TESTCONTAININGENCODEDBY ::=3D OCTET STRING ( CONTAINING INTEGER ENCODED BY
   { joint-iso-itu-t(2) asn(1) ber-derived(2) distinguished-encoding(1) }
 )
=20
-TESTCONTAININGENCODEDBY2 ::=3D OCTET STRING (=20
+TESTCONTAININGENCODEDBY2 ::=3D OCTET STRING (
 	CONTAINING INTEGER ENCODED BY TESTDer
 )
=20
@@ -92,4 +100,39 @@
=20
 TESTOSSize1 ::=3D OCTET STRING SIZE (1..2)
=20
+TESTSeqOfSeq ::=3D SEQUENCE OF SEQUENCE {
+	zero [0] TESTInteger
+}
+
+TESTSeqOfSeq2 ::=3D SEQUENCE OF SEQUENCE {
+	string [0] GeneralString
+}
+
+TESTSeqOfSeq3 ::=3D SEQUENCE OF SEQUENCE {
+	zero [0] TESTInteger,
+	string [0] GeneralString
+}
+
+TESTSeqOf2 ::=3D SEQUENCE {
+	strings SEQUENCE OF GeneralString
+}
+
+TESTSeqOf3 ::=3D SEQUENCE {
+	strings SEQUENCE OF GeneralString OPTIONAL
+}
+
+TESTPreserve ::=3D SEQUENCE {
+	zero [0] TESTInteger,
+	one [1] TESTInteger
+}
+
+TESTBitString ::=3D BIT STRING {
+	      zero(0),
+	      eight(8),
+	      thirtyone(31)
+}
+
+TESTMechType::=3D OBJECT IDENTIFIER
+TESTMechTypeList ::=3D SEQUENCE OF TESTMechType
+
 END
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/test.gen
--- a/head/crypto/heimdal/lib/asn1/test.gen	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/test.gen	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: test.gen 15617 2005-07-12 06:27:42Z lha $
+# $Id$
 # Sample for TESTSeq in test.asn1
 #
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/asn1/timegm.c
--- a/head/crypto/heimdal/lib/asn1/timegm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/asn1/timegm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "der_locl.h"
=20
-RCSID("$Id: timegm.c 21366 2007-06-27 10:06:22Z lha $");
+#define ASN1_MAX_YEAR	2000
=20
 static int
 is_leap(unsigned y)
@@ -42,7 +42,11 @@
     return (y % 4) =3D=3D 0 && ((y % 100) !=3D 0 || (y % 400) =3D=3D 0);
 }
=20
-/*=20
+static const unsigned ndays[2][12] =3D{
+    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
+    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
+
+/*
  * This is a simplifed version of timegm(3) that doesn't accept out of
  * bound values that timegm(3) normally accepts but those are not
  * valid in asn1 encodings.
@@ -51,23 +55,26 @@
 time_t
 _der_timegm (struct tm *tm)
 {
-  static const unsigned ndays[2][12] =3D{
-    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
-    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
   time_t res =3D 0;
-  unsigned i;
+  int i;
=20
-  if (tm->tm_year < 0)=20
+  /*
+   * See comment in _der_gmtime
+   */
+  if (tm->tm_year > ASN1_MAX_YEAR)
+      return 0;
+
+  if (tm->tm_year < 0)
       return -1;
-  if (tm->tm_mon < 0 || tm->tm_mon > 11)=20
+  if (tm->tm_mon < 0 || tm->tm_mon > 11)
       return -1;
-  if (tm->tm_mday < 1 || tm->tm_mday > ndays[is_leap(tm->tm_year)][tm->tm_=
mon])
+  if (tm->tm_mday < 1 || tm->tm_mday > (int)ndays[is_leap(tm->tm_year)][tm=
->tm_mon])
       return -1;
-  if (tm->tm_hour < 0 || tm->tm_hour > 23)=20
+  if (tm->tm_hour < 0 || tm->tm_hour > 23)
       return -1;
-  if (tm->tm_min < 0 || tm->tm_min > 59)=20
+  if (tm->tm_min < 0 || tm->tm_min > 59)
       return -1;
-  if (tm->tm_sec < 0 || tm->tm_sec > 59)=20
+  if (tm->tm_sec < 0 || tm->tm_sec > 59)
       return -1;
=20
   for (i =3D 70; i < tm->tm_year; ++i)
@@ -84,3 +91,46 @@
   res +=3D tm->tm_sec;
   return res;
 }
+
+struct tm *
+_der_gmtime(time_t t, struct tm *tm)
+{
+    time_t secday =3D t % (3600 * 24);
+    time_t days =3D t / (3600 * 24);
+
+    memset(tm, 0, sizeof(*tm));
+
+    tm->tm_sec =3D secday % 60;
+    tm->tm_min =3D (secday % 3600) / 60;
+    tm->tm_hour =3D secday / 3600;
+
+    /*
+     * Refuse to calculate time ~ 2000 years into the future, this is
+     * not possible for systems where time_t is a int32_t, however,
+     * when time_t is a int64_t, that can happen, and this becomes a
+     * denial of sevice.
+     */
+    if (days > (ASN1_MAX_YEAR * 365))
+	return NULL;
+
+    tm->tm_year =3D 70;
+    while(1) {
+	unsigned dayinyear =3D (is_leap(tm->tm_year) ? 366 : 365);
+	if (days < dayinyear)
+	    break;
+	tm->tm_year +=3D 1;
+	days -=3D dayinyear;
+    }
+    tm->tm_mon =3D 0;
+
+    while (1) {
+	unsigned daysinmonth =3D ndays[is_leap(tm->tm_year)][tm->tm_mon];
+	if (days < daysinmonth)
+	    break;
+	days -=3D daysinmonth;
+	tm->tm_mon++;
+    }
+    tm->tm_mday =3D days + 1;
+
+    return tm;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/Change=
Log
--- a/head/crypto/heimdal/lib/com_err/ChangeLog	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/com_err/ChangeLog	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,34 +1,34 @@
-2007-07-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: split source files in dist and nodist.
=20
-2007-07-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Only do roken rename for the library.
=20
-2007-07-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: use version script.
 =09
 	* version-script.map: use version script.
=20
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: New library version.
 =09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am (compile_et_SOURCES): add lex.h
 =09
-2005-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* com_err.3: Document the _r functions.
 =09
-2005-07-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* com_err.h: Include <stdarg.h> for va_list to help AIX 5.2.
 =09
-2005-06-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse.y: rename base to base_id since flex defines a function
 	with the argument base
@@ -43,7 +43,7 @@
 =09
 	* compile_et.c: rename optind to optidx
 =09
-2005-05-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse.y: check allocation errors
=20
@@ -57,11 +57,11 @@
=20
 	* Makefile.am (LDADD): Add libcom_err.la
=20
-2005-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* include strlcpy and *printf and use them
=20
-2005-02-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* com_right.h: de-__P
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/Makefi=
le.am
--- a/head/crypto/heimdal/lib/com_err/Makefile.am	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/com_err/Makefile.am	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 21619 2007-07-17 07:34:00Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -11,19 +11,23 @@
 libcom_err_la_LDFLAGS +=3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scri=
pt.map
 endif
=20
+libcom_err_la_LIBADD =3D $(LIB_libintl)
+
 bin_PROGRAMS =3D compile_et
=20
 include_HEADERS =3D com_err.h com_right.h
=20
 compile_et_SOURCES =3D compile_et.c compile_et.h parse.y lex.l lex.h
=20
-libcom_err_la_CPPFLAGS =3D $(ROKEN_RENAME)
+libcom_err_la_CPPFLAGS =3D $(ROKEN_RENAME) $(INCLUDE_libintl)
 dist_libcom_err_la_SOURCES =3D error.c com_err.c roken_rename.h
=20
 if do_roken_rename
 nodist_libcom_err_la_SOURCES =3D snprintf.c strlcpy.c
 endif
=20
+libcom_err_la_DEPENDENCIES =3D version-script.map
+
 $(compile_et_OBJECTS): parse.h parse.c ## XXX broken automake 1.4s
=20
 compile_et_LDADD =3D \
@@ -36,4 +40,9 @@
 strlcpy.c:
 	$(LN_S) $(srcdir)/../roken/strlcpy.c .
=20
-EXTRA_DIST =3D version-script.map
+EXTRA_DIST =3D \
+	NTMakefile \
+	compile_et-version.rc \
+	libcom_err-version.rc \
+	libcom_err-exports.def \
+	version-script.map
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/Makefi=
le.in
--- a/head/crypto/heimdal/lib/com_err/Makefile.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/com_err/Makefile.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 21619 2007-07-17 07:34:00Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -49,7 +51,7 @@
 subdir =3D lib/com_err
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -64,7 +66,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -78,9 +80,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -88,23 +93,38 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \
 	"$(DESTDIR)$(includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
-libcom_err_la_LIBADD =3D
+am__DEPENDENCIES_1 =3D
 dist_libcom_err_la_OBJECTS =3D libcom_err_la-error.lo \
 	libcom_err_la-com_err.lo
 @do_roken_rename_TRUE at nodist_libcom_err_la_OBJECTS =3D  \
@@ -115,17 +135,15 @@
 libcom_err_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libcom_err_la_LDFLAGS) $(LDFLAGS) -o $@
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(bin_PROGRAMS)
 am_compile_et_OBJECTS =3D compile_et.$(OBJEXT) parse.$(OBJEXT) \
 	lex.$(OBJEXT)
 compile_et_OBJECTS =3D $(am_compile_et_OBJECTS)
-am__DEPENDENCIES_1 =3D
 compile_et_DEPENDENCIES =3D libcom_err.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -147,7 +165,6 @@
 SOURCES =3D $(dist_libcom_err_la_SOURCES) \
 	$(nodist_libcom_err_la_SOURCES) $(compile_et_SOURCES)
 DIST_SOURCES =3D $(dist_libcom_err_la_SOURCES) $(compile_et_SOURCES)
-includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
 HEADERS =3D $(include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
@@ -156,49 +173,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -222,10 +248,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -242,6 +269,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -257,31 +286,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -296,10 +339,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -340,59 +385,72 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 lib_LTLIBRARIES =3D libcom_err.la
 libcom_err_la_LDFLAGS =3D -version-info 2:3:1 $(am__append_1)
+libcom_err_la_LIBADD =3D $(LIB_libintl)
 include_HEADERS =3D com_err.h com_right.h
 compile_et_SOURCES =3D compile_et.c compile_et.h parse.y lex.l lex.h
-libcom_err_la_CPPFLAGS =3D $(ROKEN_RENAME)
+libcom_err_la_CPPFLAGS =3D $(ROKEN_RENAME) $(INCLUDE_libintl)
 dist_libcom_err_la_SOURCES =3D error.c com_err.c roken_rename.h
 @do_roken_rename_TRUE at nodist_libcom_err_la_SOURCES =3D snprintf.c strlcpy.c
+libcom_err_la_DEPENDENCIES =3D version-script.map
 compile_et_LDADD =3D \
 	libcom_err.la \
 	$(LIB_roken) \
 	$(LEXLIB)
=20
-EXTRA_DIST =3D version-script.map
+EXTRA_DIST =3D \
+	NTMakefile \
+	compile_et-version.rc \
+	libcom_err-version.rc \
+	libcom_err-exports.def \
+	version-script.map
+
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .l .lo .o .=
obj .y
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .l .lo =
.o .obj .y
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/com_e=
rr/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/com_err/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/com_err/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/com_err/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -410,23 +468,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -442,31 +505,46 @@
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 parse.h: parse.c
 	@if test ! -f $@; then \
 	  rm -f parse.c; \
@@ -482,26 +560,62 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/compile_et.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/lex.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libcom_err_la-com_err.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libcom_err_la-error.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libcom_err_la-snprintf.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libcom_err_la-strlcpy.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/parse.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 libcom_err_la-error.lo: error.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcom_err_la_CPPFLAGS) $(=
CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-error.lo `test -f 'err=
or.c' || echo '$(srcdir)/'`error.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libco=
m_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libcom_err_la-err=
or.lo -MD -MP -MF $(DEPDIR)/libcom_err_la-error.Tpo -c -o libcom_err_la-err=
or.lo `test -f 'error.c' || echo '$(srcdir)/'`error.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libcom_err_la-error.Tpo $(DEPDIR)=
/libcom_err_la-error.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'error.c' object=3D'libcom_err_=
la-error.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libc=
om_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-=
error.lo `test -f 'error.c' || echo '$(srcdir)/'`error.c
=20
 libcom_err_la-com_err.lo: com_err.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcom_err_la_CPPFLAGS) $(=
CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-com_err.lo `test -f 'c=
om_err.c' || echo '$(srcdir)/'`com_err.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libco=
m_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libcom_err_la-com=
_err.lo -MD -MP -MF $(DEPDIR)/libcom_err_la-com_err.Tpo -c -o libcom_err_la=
-com_err.lo `test -f 'com_err.c' || echo '$(srcdir)/'`com_err.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libcom_err_la-com_err.Tpo $(DEPDI=
R)/libcom_err_la-com_err.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'com_err.c' object=3D'libcom_er=
r_la-com_err.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libc=
om_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-=
com_err.lo `test -f 'com_err.c' || echo '$(srcdir)/'`com_err.c
=20
 libcom_err_la-snprintf.lo: snprintf.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcom_err_la_CPPFLAGS) $(=
CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-snprintf.lo `test -f '=
snprintf.c' || echo '$(srcdir)/'`snprintf.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libco=
m_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libcom_err_la-snp=
rintf.lo -MD -MP -MF $(DEPDIR)/libcom_err_la-snprintf.Tpo -c -o libcom_err_=
la-snprintf.lo `test -f 'snprintf.c' || echo '$(srcdir)/'`snprintf.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libcom_err_la-snprintf.Tpo $(DEPD=
IR)/libcom_err_la-snprintf.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'snprintf.c' object=3D'libcom_e=
rr_la-snprintf.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libc=
om_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-=
snprintf.lo `test -f 'snprintf.c' || echo '$(srcdir)/'`snprintf.c
=20
 libcom_err_la-strlcpy.lo: strlcpy.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libcom_err_la_CPPFLAGS) $(=
CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-strlcpy.lo `test -f 's=
trlcpy.c' || echo '$(srcdir)/'`strlcpy.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libco=
m_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libcom_err_la-str=
lcpy.lo -MD -MP -MF $(DEPDIR)/libcom_err_la-strlcpy.Tpo -c -o libcom_err_la=
-strlcpy.lo `test -f 'strlcpy.c' || echo '$(srcdir)/'`strlcpy.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libcom_err_la-strlcpy.Tpo $(DEPDI=
R)/libcom_err_la-strlcpy.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strlcpy.c' object=3D'libcom_er=
r_la-strlcpy.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libc=
om_err_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libcom_err_la-=
strlcpy.lo `test -f 'strlcpy.c' || echo '$(srcdir)/'`strlcpy.c
=20
 .l.c:
 	$(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMP=
ILE)
@@ -517,65 +631,72 @@
 install-includeHEADERS: $(include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'=
"; \
-	  $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -596,13 +717,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -639,6 +764,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -652,6 +778,7 @@
 	clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -662,6 +789,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -669,26 +798,35 @@
 install-data-am: install-includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -709,9 +847,8 @@
 	uninstall-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-binPROGRAMS clean-generic clean-libLTLIBRARIES \
@@ -800,6 +937,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -885,7 +1025,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -905,6 +1045,7 @@
 	$(LN_S) $(srcdir)/../roken/snprintf.c .
 strlcpy.c:
 	$(LN_S) $(srcdir)/../roken/strlcpy.c .
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/com_er=
r.c
--- a/head/crypto/heimdal/lib/com_err/com_err.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/com_err/com_err.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,40 +1,39 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-RCSID("$Id: com_err.c 14930 2005-04-24 19:43:06Z lha $");
-#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -44,7 +43,7 @@
 struct et_list *_et_list =3D NULL;
=20
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 error_message (long code)
 {
     static char msg[128];
@@ -57,23 +56,23 @@
     }
     if (p !=3D NULL && *p !=3D '\0') {
 	strlcpy(msg, p, sizeof(msg));
-    } else=20
+    } else
 	snprintf(msg, sizeof(msg), "Unknown error %ld", code);
     return msg;
 }
=20
-int
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 init_error_table(const char **msgs, long base, int count)
 {
     initialize_error_table_r(&_et_list, msgs, count, base);
     return 0;
 }
=20
-static void
+static void KRB5_CALLCONV
 default_proc (const char *whoami, long code, const char *fmt, va_list args)
     __attribute__((__format__(__printf__, 3, 0)));
-=20
-static void
+
+static void KRB5_CALLCONV
 default_proc (const char *whoami, long code, const char *fmt, va_list args)
 {
     if (whoami)
@@ -87,19 +86,19 @@
=20
 static errf com_err_hook =3D default_proc;
=20
-void=20
-com_err_va (const char *whoami,=20
-	    long code,=20
-	    const char *fmt,=20
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err_va (const char *whoami,
+	    long code,
+	    const char *fmt,
 	    va_list args)
 {
     (*com_err_hook) (whoami, code, fmt, args);
 }
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 com_err (const char *whoami,
 	 long code,
-	 const char *fmt,=20
+	 const char *fmt,
 	 ...)
 {
     va_list ap;
@@ -108,7 +107,7 @@
     va_end(ap);
 }
=20
-errf
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
 set_com_err_hook (errf new)
 {
     errf old =3D com_err_hook;
@@ -117,12 +116,12 @@
 	com_err_hook =3D new;
     else
 	com_err_hook =3D default_proc;
-   =20
+
     return old;
 }
=20
-errf
-reset_com_err_hook (void)=20
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+reset_com_err_hook (void)
 {
     return set_com_err_hook(NULL);
 }
@@ -135,7 +134,7 @@
=20
 static char buf[6];
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 error_table_name(int num)
 {
     int ch;
@@ -157,7 +156,7 @@
     return(buf);
 }
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 add_to_error_table(struct et_list *new_table)
 {
     struct et_list *et;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/com_er=
r.h
--- a/head/crypto/heimdal/lib/com_err/com_err.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/com_err/com_err.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: com_err.h 15566 2005-07-07 14:58:07Z lha $ */
+/* $Id$ */
=20
 /* MIT compatible com_err library */
=20
@@ -45,22 +45,32 @@
 #define __attribute__(X)
 #endif
=20
-typedef void (*errf) (const char *, long, const char *, va_list);
+typedef void (KRB5_CALLCONV *errf) (const char *, long, const char *, va_l=
ist);
=20
-const char * error_message (long);
-int init_error_table (const char**, long, int);
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_message (long);
=20
-void com_err_va (const char *, long, const char *, va_list)
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+init_error_table (const char**, long, int);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err_va (const char *, long, const char *, va_list)
     __attribute__((format(printf, 3, 0)));
=20
-void com_err (const char *, long, const char *, ...)
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+com_err (const char *, long, const char *, ...)
     __attribute__((format(printf, 3, 4)));
=20
-errf set_com_err_hook (errf);
-errf reset_com_err_hook (void);
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+set_com_err_hook (errf);
=20
-const char *error_table_name  (int num);
+KRB5_LIB_FUNCTION errf KRB5_LIB_CALL
+reset_com_err_hook (void);
=20
-void add_to_error_table (struct et_list *new_table);
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+error_table_name  (int num);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+add_to_error_table (struct et_list *new_table);
=20
 #endif /* __COM_ERR_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/com_ri=
ght.h
--- a/head/crypto/heimdal/lib/com_err/com_right.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/com_err/com_right.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,41 +1,61 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: com_right.h 14551 2005-02-03 08:45:13Z lha $ */
+/* $Id$ */
=20
 #ifndef __COM_RIGHT_H__
 #define __COM_RIGHT_H__
=20
+#ifndef KRB5_LIB
+#ifndef KRB5_LIB_FUNCTION
+#if defined(_WIN32)
+#define KRB5_LIB_FUNCTION __declspec(dllimport)
+#define KRB5_LIB_CALL __stdcall
+#define KRB5_LIB_VARIABLE __declspec(dllimport)
+#else
+#define KRB5_LIB_FUNCTION
+#define KRB5_LIB_CALL
+#define KRB5_LIB_VARIABLE
+#endif
+#endif
+#endif
+
+#ifdef _WIN32
+#define KRB5_CALLCONV __stdcall
+#else
+#define KRB5_CALLCONV
+#endif
+
 #ifdef __STDC__
 #include <stdarg.h>
 #endif
@@ -51,8 +71,16 @@
 };
 extern struct et_list *_et_list;
=20
-const char *com_right (struct et_list *list, long code);
-void initialize_error_table_r (struct et_list **, const char **, int, long=
);
-void free_error_table (struct et_list *);
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right (struct et_list *list, long code);
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right_r (struct et_list *list, long code, char *, size_t);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+initialize_error_table_r (struct et_list **, const char **, int, long);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+free_error_table (struct et_list *);
=20
 #endif /* __COM_RIGHT_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/compil=
e_et.c
--- a/head/crypto/heimdal/lib/com_err/compile_et.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/com_err/compile_et.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,42 +1,43 @@
 /*
- * Copyright (c) 1998-2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998-2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #undef ROKEN_RENAME
+
+#include "config.h"
+
 #include "compile_et.h"
 #include <getarg.h>
=20
-RCSID("$Id: compile_et.c 15426 2005-06-16 19:21:42Z lha $");
-
 #include <roken.h>
 #include <err.h>
 #include "parse.h"
@@ -75,13 +76,15 @@
 	return 1;
=20
     fprintf(c_file, "/* Generated from %s */\n", filename);
-    if(id_str)=20
+    if(id_str)
 	fprintf(c_file, "/* %s */\n", id_str);
     fprintf(c_file, "\n");
     fprintf(c_file, "#include <stddef.h>\n");
     fprintf(c_file, "#include <com_err.h>\n");
     fprintf(c_file, "#include \"%s\"\n", hfn);
     fprintf(c_file, "\n");
+    fprintf(c_file, "#define N_(x) (x)\n");
+    fprintf(c_file, "\n");
=20
     fprintf(c_file, "static const char *%s_error_strings[] =3D {\n", name);
=20
@@ -90,9 +93,10 @@
 	    fprintf(c_file, "\t/* %03d */ \"Reserved %s error (%d)\",\n",
 		    n, name, n);
 	    n++;
-	   =20
+
 	}
-	fprintf(c_file, "\t/* %03d */ \"%s\",\n", ec->number, ec->string);
+	fprintf(c_file, "\t/* %03d */ N_(\"%s\"),\n",
+		ec->number, ec->string);
     }
=20
     fprintf(c_file, "\tNULL\n");
@@ -100,11 +104,11 @@
     fprintf(c_file, "\n");
     fprintf(c_file, "#define num_errors %d\n", number);
     fprintf(c_file, "\n");
-    fprintf(c_file,=20
-	    "void initialize_%s_error_table_r(struct et_list **list)\n",=20
+    fprintf(c_file,
+	    "void initialize_%s_error_table_r(struct et_list **list)\n",
 	    name);
     fprintf(c_file, "{\n");
-    fprintf(c_file,=20
+    fprintf(c_file,
 	    "    initialize_error_table_r(list, %s_error_strings, "
 	    "num_errors, ERROR_TABLE_BASE_%s);\n", name, name);
     fprintf(c_file, "}\n");
@@ -135,9 +139,9 @@
     for(p =3D fn; *p; p++)
 	if(!isalnum((unsigned char)*p))
 	    *p =3D '_';
-   =20
+
     fprintf(h_file, "/* Generated from %s */\n", filename);
-    if(id_str)=20
+    if(id_str)
 	fprintf(h_file, "/* %s */\n", id_str);
     fprintf(h_file, "\n");
     fprintf(h_file, "#ifndef %s\n", fn);
@@ -145,18 +149,18 @@
     fprintf(h_file, "\n");
     fprintf(h_file, "struct et_list;\n");
     fprintf(h_file, "\n");
-    fprintf(h_file,=20
+    fprintf(h_file,
 	    "void initialize_%s_error_table_r(struct et_list **);\n",
 	    name);
     fprintf(h_file, "\n");
     fprintf(h_file, "void initialize_%s_error_table(void);\n", name);
-    fprintf(h_file, "#define init_%s_err_tbl initialize_%s_error_table\n",=20
+    fprintf(h_file, "#define init_%s_err_tbl initialize_%s_error_table\n",
 	    name, name);
     fprintf(h_file, "\n");
     fprintf(h_file, "typedef enum %s_error_number{\n", name);
=20
     for(ec =3D codes; ec; ec =3D ec->next) {
-	fprintf(h_file, "\t%s =3D %ld%s\n", ec->name, base_id + ec->number,=20
+	fprintf(h_file, "\t%s =3D %ld%s\n", ec->name, base_id + ec->number,
 		(ec->next !=3D NULL) ? "," : "");
     }
=20
@@ -164,6 +168,8 @@
     fprintf(h_file, "\n");
     fprintf(h_file, "#define ERROR_TABLE_BASE_%s %ld\n", name, base_id);
     fprintf(h_file, "\n");
+    fprintf(h_file, "#define COM_ERR_BINDDOMAIN_%s \"heim_com_err%ld\"\n",=
 name, base_id);
+    fprintf(h_file, "\n");
     fprintf(h_file, "#endif /* %s */\n", fn);
=20
=20
@@ -208,26 +214,26 @@
 	exit(0);
     }
=20
-    if(optidx =3D=3D argc)=20
+    if(optidx =3D=3D argc)
 	usage(1);
     filename =3D argv[optidx];
     yyin =3D fopen(filename, "r");
     if(yyin =3D=3D NULL)
 	err(1, "%s", filename);
-=09
-   =20
-    p =3D strrchr(filename, '/');
+
+
+    p =3D strrchr(filename, rk_PATH_DELIM);
     if(p)
 	p++;
     else
 	p =3D filename;
     strlcpy(Basename, p, sizeof(Basename));
-   =20
+
     Basename[strcspn(Basename, ".")] =3D '\0';
-   =20
+
     snprintf(hfn, sizeof(hfn), "%s.h", Basename);
     snprintf(cfn, sizeof(cfn), "%s.c", Basename);
-   =20
+
     yyparse();
     if(numerror)
 	return 1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/compil=
e_et.h
--- a/head/crypto/heimdal/lib/com_err/compile_et.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/com_err/compile_et.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,44 +1,42 @@
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: compile_et.h 15426 2005-06-16 19:21:42Z lha $ */
+/* $Id$ */
=20
 #ifndef __COMPILE_ET_H__
 #define __COMPILE_ET_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #include <err.h>
 #include <stdio.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/error.c
--- a/head/crypto/heimdal/lib/com_err/error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,52 +1,75 @@
 /*
- * Copyright (c) 1997, 1998, 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-RCSID("$Id: error.c 9724 2001-02-28 20:00:13Z joda $");
-#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <com_right.h>
+#include <roken.h>
=20
-const char *
+#ifdef LIBINTL
+#include <libintl.h>
+#else
+#define dgettext(d,s) (s)
+#endif
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 com_right(struct et_list *list, long code)
 {
     struct et_list *p;
-    for (p =3D list; p; p =3D p->next) {
+    for (p =3D list; p; p =3D p->next)
 	if (code >=3D p->table->base && code < p->table->base + p->table->n_msgs)
 	    return p->table->msgs[code - p->table->base];
+    return NULL;
+}
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+com_right_r(struct et_list *list, long code, char *str, size_t len)
+{
+    struct et_list *p;
+    for (p =3D list; p; p =3D p->next) {
+	if (code >=3D p->table->base && code < p->table->base + p->table->n_msgs)=
 {
+	    const char *msg =3D p->table->msgs[code - p->table->base];
+#ifdef LIBINTL
+	    char domain[12 + 20];
+	    snprintf(domain, sizeof(domain), "heim_com_err%d", p->table->base);
+#endif
+	    strlcpy(str, dgettext(domain, msg), len);
+	    return str;
+	}
     }
     return NULL;
 }
@@ -56,9 +79,9 @@
     struct error_table et;
 };
=20
-void
-initialize_error_table_r(struct et_list **list,=20
-			 const char **messages,=20
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+initialize_error_table_r(struct et_list **list,
+			 const char **messages,
 			 int num_errors,
 			 long base)
 {
@@ -78,9 +101,9 @@
     et->next =3D NULL;
     *end =3D et;
 }
-		=09
=20
-void
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 free_error_table(struct et_list *et)
 {
     while(et){
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/lex.c
--- a/head/crypto/heimdal/lib/com_err/lex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/lex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -8,7 +8,7 @@
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
 #define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 33
+#define YY_FLEX_SUBMINOR_VERSION 35
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -30,7 +30,7 @@
=20
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
=20
-#if __STDC_VERSION__ >=3D 199901L
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >=3D 199901L
=20
 /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
  * if you want the limit (max/min) macros for int types.=20
@@ -93,11 +93,12 @@
=20
 #else	/* ! __cplusplus */
=20
-#if __STDC__
+/* C99 requires __STDC__ to be defined as 1. */
+#if defined (__STDC__)
=20
 #define YY_USE_CONST
=20
-#endif	/* __STDC__ */
+#endif	/* defined (__STDC__) */
 #endif	/* ! __cplusplus */
=20
 #ifdef YY_USE_CONST
@@ -151,7 +152,12 @@
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
=20
-extern int yyleng;
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef size_t yy_size_t;
+#endif
+
+extern yy_size_t yyleng;
=20
 extern FILE *yyin, *yyout;
=20
@@ -177,16 +183,6 @@
=20
 #define unput(c) yyunput( c, (yytext_ptr)  )
=20
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
-
-#ifndef YY_TYPEDEF_YY_SIZE_T
-#define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
-#endif
-
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
@@ -204,7 +200,7 @@
 	/* Number of characters read into yy_ch_buf, not including EOB
 	 * characters.
 	 */
-	int yy_n_chars;
+	yy_size_t yy_n_chars;
=20
 	/* Whether we "own" the buffer - i.e., we know we created it,
 	 * and can realloc() it to grow it, and should free() it to
@@ -274,8 +270,8 @@
=20
 /* yy_hold_char holds the character lost when yytext is formed. */
 static char yy_hold_char;
-static int yy_n_chars;		/* number of characters read into yy_ch_buf */
-int yyleng;
+static yy_size_t yy_n_chars;		/* number of characters read into yy_ch_buf =
*/
+yy_size_t yyleng;
=20
 /* Points to current character in buffer. */
 static char *yy_c_buf_p =3D (char *) 0;
@@ -303,7 +299,7 @@
=20
 YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size  );
 YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str  );
-YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len  );
+YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len  );
=20
 void *yyalloc (yy_size_t  );
 void *yyrealloc (void *,yy_size_t  );
@@ -479,36 +475,36 @@
 #line 1 "lex.l"
 #line 2 "lex.l"
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /*
@@ -523,8 +519,6 @@
 #include "parse.h"
 #include "lex.h"
=20
-RCSID("$Id: lex.l 15143 2005-05-16 08:52:54Z lha $");
-
 static unsigned lineno =3D 1;
 static int getstring(void);
=20
@@ -532,7 +526,7 @@
=20
 #undef ECHO
=20
-#line 536 "lex.c"
+#line 530 "lex.c"
=20
 #define INITIAL 0
=20
@@ -550,6 +544,35 @@
=20
 static int yy_init_globals (void );
=20
+/* Accessor methods to globals.
+   These are made visible to non-reentrant scanners for convenience. */
+
+int yylex_destroy (void );
+
+int yyget_debug (void );
+
+void yyset_debug (int debug_flag  );
+
+YY_EXTRA_TYPE yyget_extra (void );
+
+void yyset_extra (YY_EXTRA_TYPE user_defined  );
+
+FILE *yyget_in (void );
+
+void yyset_in  (FILE * in_str  );
+
+FILE *yyget_out (void );
+
+void yyset_out  (FILE * out_str  );
+
+yy_size_t yyget_leng (void );
+
+char *yyget_text (void );
+
+int yyget_lineno (void );
+
+void yyset_lineno (int line_number  );
+
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
  */
@@ -562,8 +585,6 @@
 #endif
 #endif
=20
-    static void yyunput (int c,char *buf_ptr  );
-   =20
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char *,yyconst char *,int );
 #endif
@@ -592,7 +613,7 @@
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#define ECHO fwrite( yytext, yyleng, 1, yyout )
 #endif
=20
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_=
NULL,
@@ -603,7 +624,7 @@
 	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
 		{ \
 		int c =3D '*'; \
-		size_t n; \
+		yy_size_t n; \
 		for ( n =3D 0; n < max_size && \
 			     (c =3D getc( yyin )) !=3D EOF && c !=3D '\n'; ++n ) \
 			buf[n] =3D (char) c; \
@@ -685,9 +706,9 @@
 	register char *yy_cp, *yy_bp;
 	register int yy_act;
    =20
-#line 59 "lex.l"
+#line 58 "lex.l"
=20
-#line 691 "lex.c"
+#line 712 "lex.c"
=20
 	if ( !(yy_init) )
 		{
@@ -772,86 +793,86 @@
=20
 case 1:
 YY_RULE_SETUP
-#line 60 "lex.l"
+#line 59 "lex.l"
 { return ET; }
 	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 61 "lex.l"
+#line 60 "lex.l"
 { return ET; }
 	YY_BREAK
 case 3:
 YY_RULE_SETUP
-#line 62 "lex.l"
+#line 61 "lex.l"
 { return EC; }
 	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 63 "lex.l"
+#line 62 "lex.l"
 { return EC; }
 	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 64 "lex.l"
+#line 63 "lex.l"
 { return PREFIX; }
 	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 65 "lex.l"
+#line 64 "lex.l"
 { return INDEX; }
 	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 66 "lex.l"
+#line 65 "lex.l"
 { return ID; }
 	YY_BREAK
 case 8:
 YY_RULE_SETUP
-#line 67 "lex.l"
+#line 66 "lex.l"
 { return END; }
 	YY_BREAK
 case 9:
 YY_RULE_SETUP
-#line 68 "lex.l"
+#line 67 "lex.l"
 { yylval.number =3D atoi(yytext); return NUMBER; }
 	YY_BREAK
 case 10:
 YY_RULE_SETUP
-#line 69 "lex.l"
+#line 68 "lex.l"
 ;
 	YY_BREAK
 case 11:
 YY_RULE_SETUP
-#line 70 "lex.l"
+#line 69 "lex.l"
 ;
 	YY_BREAK
 case 12:
 /* rule 12 can match eol */
 YY_RULE_SETUP
-#line 71 "lex.l"
+#line 70 "lex.l"
 { lineno++; }
 	YY_BREAK
 case 13:
 YY_RULE_SETUP
-#line 72 "lex.l"
+#line 71 "lex.l"
 { return getstring(); }
 	YY_BREAK
 case 14:
 YY_RULE_SETUP
-#line 73 "lex.l"
+#line 72 "lex.l"
 { yylval.string =3D strdup(yytext); return STRING; }
 	YY_BREAK
 case 15:
 YY_RULE_SETUP
-#line 74 "lex.l"
+#line 73 "lex.l"
 { return *yytext; }
 	YY_BREAK
 case 16:
 YY_RULE_SETUP
-#line 75 "lex.l"
+#line 74 "lex.l"
 ECHO;
 	YY_BREAK
-#line 855 "lex.c"
+#line 876 "lex.c"
 case YY_STATE_EOF(INITIAL):
 	yyterminate();
=20
@@ -1037,7 +1058,7 @@
=20
 	else
 		{
-			int num_to_read =3D
+			yy_size_t num_to_read =3D
 			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
=20
 		while ( num_to_read <=3D 0 )
@@ -1051,7 +1072,7 @@
=20
 			if ( b->yy_is_our_buffer )
 				{
-				int new_size =3D b->yy_buf_size * 2;
+				yy_size_t new_size =3D b->yy_buf_size * 2;
=20
 				if ( new_size <=3D 0 )
 					b->yy_buf_size +=3D b->yy_buf_size / 8;
@@ -1106,6 +1127,14 @@
 	else
 		ret_val =3D EOB_ACT_CONTINUE_SCAN;
=20
+	if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALU=
E->yy_buf_size) {
+		/* Extend the array by 50%, plus the number we really need. */
+		yy_size_t new_size =3D (yy_n_chars) + number_to_move + ((yy_n_chars) >> =
1);
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf =3D (char *) yyrealloc((void *) YY_C=
URRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
+		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+	}
+
 	(yy_n_chars) +=3D number_to_move;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] =3D YY_END_OF_BUFFER_CH=
AR;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] =3D YY_END_OF_BUFFE=
R_CHAR;
@@ -1172,43 +1201,6 @@
 	return yy_is_jam ? 0 : yy_current_state;
 }
=20
-    static void yyunput (int c, register char * yy_bp )
-{
-	register char *yy_cp;
-   =20
-    yy_cp =3D (yy_c_buf_p);
-
-	/* undo effects of setting up yytext */
-	*yy_cp =3D (yy_hold_char);
-
-	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
-		{ /* need to shift things up to make room */
-		/* +2 for EOB chars. */
-		register int number_to_move =3D (yy_n_chars) + 2;
-		register char *dest =3D &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
-					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
-		register char *source =3D
-				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
-
-		while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
-			*--dest =3D *--source;
-
-		yy_cp +=3D (int) (dest - source);
-		yy_bp +=3D (int) (dest - source);
-		YY_CURRENT_BUFFER_LVALUE->yy_n_chars =3D
-			(yy_n_chars) =3D YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
-
-		if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
-			YY_FATAL_ERROR( "flex scanner push-back overflow" );
-		}
-
-	*--yy_cp =3D (char) c;
-
-	(yytext_ptr) =3D yy_bp;
-	(yy_hold_char) =3D *yy_cp;
-	(yy_c_buf_p) =3D yy_cp;
-}
-
 #ifndef YY_NO_INPUT
 #ifdef __cplusplus
     static int yyinput (void)
@@ -1233,7 +1225,7 @@
=20
 		else
 			{ /* need more input */
-			int offset =3D (yy_c_buf_p) - (yytext_ptr);
+			yy_size_t offset =3D (yy_c_buf_p) - (yytext_ptr);
 			++(yy_c_buf_p);
=20
 			switch ( yy_get_next_buffer(  ) )
@@ -1509,7 +1501,7 @@
  */
 static void yyensure_buffer_stack (void)
 {
-	int num_to_alloc;
+	yy_size_t num_to_alloc;
    =20
 	if (!(yy_buffer_stack)) {
=20
@@ -1521,7 +1513,9 @@
 		(yy_buffer_stack) =3D (struct yy_buffer_state**)yyalloc
 								(num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
-	=09
+		if ( ! (yy_buffer_stack) )
+			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
+								 =20
 		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_stat=
e*));
 			=09
 		(yy_buffer_stack_max) =3D num_to_alloc;
@@ -1539,6 +1533,8 @@
 								((yy_buffer_stack),
 								num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
+		if ( ! (yy_buffer_stack) )
+			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
=20
 		/* zero only the new slots.*/
 		memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(=
struct yy_buffer_state*));
@@ -1583,7 +1579,7 @@
=20
 /** Setup the input buffer state to scan a string. The next call to yylex(=
) will
  * scan from a @e copy of @a str.
- * @param str a NUL-terminated string to scan
+ * @param yystr a NUL-terminated string to scan
  *=20
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
@@ -1602,12 +1598,11 @@
  *=20
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len )
+YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, yy_size_t  _yybyte=
s_len )
 {
 	YY_BUFFER_STATE b;
 	char *buf;
-	yy_size_t n;
-	int i;
+	yy_size_t n, i;
    =20
 	/* Get memory for full buffer, including space for trailing EOB's. */
 	n =3D _yybytes_len + 2;
@@ -1689,7 +1684,7 @@
 /** Get the length of the current token.
  *=20
  */
-int yyget_leng  (void)
+yy_size_t yyget_leng  (void)
 {
         return yyleng;
 }
@@ -1837,13 +1832,13 @@
=20
 #define YYTABLES_NAME "yytables"
=20
-#line 75 "lex.l"
+#line 74 "lex.l"
=20
=20
=20
 #ifndef yywrap /* XXX */
 int
-yywrap ()=20
+yywrap ()
 {
      return 1;
 }
@@ -1863,7 +1858,7 @@
 	    continue;
 	}
 	if(c =3D=3D '\n'){
-	    error_message("unterminated string");
+	    _lex_error_message("unterminated string");
 	    lineno++;
 	    break;
 	}
@@ -1883,7 +1878,7 @@
 }
=20
 void
-error_message (const char *format, ...)
+_lex_error_message (const char *format, ...)
 {
      va_list args;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/lex.h
--- a/head/crypto/heimdal/lib/com_err/lex.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/lex.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: lex.h 8451 2000-06-22 00:42:52Z assar $ */
+/* $Id$ */
=20
-void error_message (const char *, ...)
+void _lex_error_message (const char *, ...)
 __attribute__ ((format (printf, 1, 2)));
=20
 int yylex(void);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/lex.l
--- a/head/crypto/heimdal/lib/com_err/lex.l	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/lex.l	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
 %{
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /*
@@ -44,8 +44,6 @@
 #include "parse.h"
 #include "lex.h"
=20
-RCSID("$Id: lex.l 15143 2005-05-16 08:52:54Z lha $");
-
 static unsigned lineno =3D 1;
 static int getstring(void);
=20
@@ -55,6 +53,7 @@
=20
 %}
=20
+%option nounput
=20
 %%
 et			{ return ET; }
@@ -76,7 +75,7 @@
=20
 #ifndef yywrap /* XXX */
 int
-yywrap ()=20
+yywrap ()
 {
      return 1;
 }
@@ -96,7 +95,7 @@
 	    continue;
 	}
 	if(c =3D=3D '\n'){
-	    error_message("unterminated string");
+	    _lex_error_message("unterminated string");
 	    lineno++;
 	    break;
 	}
@@ -116,7 +115,7 @@
 }
=20
 void
-error_message (const char *format, ...)
+_lex_error_message (const char *format, ...)
 {
      va_list args;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/parse.c
--- a/head/crypto/heimdal/lib/com_err/parse.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/parse.c	Tue Apr 17 11:51:51 2012 +0300
@@ -93,43 +93,41 @@
 #line 1 "parse.y"
=20
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "compile_et.h"
 #include "lex.h"
=20
-RCSID("$Id: parse.y 15426 2005-06-16 19:21:42Z lha $");
-
 void yyerror (char *s);
 static long name2number(const char *str);
=20
@@ -141,6 +139,9 @@
 #define alloca(x) malloc(x)
 #endif
=20
+#define YYMALLOC malloc
+#define YYFREE free
+
=20
=20
 /* Enabling traces.  */
@@ -163,13 +164,13 @@
=20
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-#line 53 "parse.y"
+#line 54 "parse.y"
 {
   char *string;
   int number;
 }
 /* Line 193 of yacc.c.  */
-#line 173 "parse.c"
+#line 174 "parse.c"
 	YYSTYPE;
 # define yystype YYSTYPE /* obsolescent; will be withdrawn */
 # define YYSTYPE_IS_DECLARED 1
@@ -182,7 +183,7 @@
=20
=20
 /* Line 216 of yacc.c.  */
-#line 186 "parse.c"
+#line 187 "parse.c"
=20
 #ifdef short
 # undef short
@@ -469,8 +470,8 @@
 /* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
 static const yytype_uint8 yyrline[] =3D
 {
-       0,    64,    64,    65,    68,    69,    72,    78,    84,    93,
-      94,    97,   101,   109,   116,   136
+       0,    65,    65,    66,    69,    70,    73,    79,    85,    94,
+      95,    98,   102,   110,   117,   137
 };
 #endif
=20
@@ -1381,14 +1382,14 @@
   switch (yyn)
     {
         case 6:
-#line 73 "parse.y"
+#line 74 "parse.y"
     {
 		    id_str =3D (yyvsp[(2) - (2)].string);
 		}
     break;
=20
   case 7:
-#line 79 "parse.y"
+#line 80 "parse.y"
     {
 		    base_id =3D name2number((yyvsp[(2) - (2)].string));
 		    strlcpy(name, (yyvsp[(2) - (2)].string), sizeof(name));
@@ -1397,7 +1398,7 @@
     break;
=20
   case 8:
-#line 85 "parse.y"
+#line 86 "parse.y"
     {
 		    base_id =3D name2number((yyvsp[(2) - (3)].string));
 		    strlcpy(name, (yyvsp[(3) - (3)].string), sizeof(name));
@@ -1407,14 +1408,14 @@
     break;
=20
   case 11:
-#line 98 "parse.y"
+#line 99 "parse.y"
     {
 			number =3D (yyvsp[(2) - (2)].number);
 		}
     break;
=20
   case 12:
-#line 102 "parse.y"
+#line 103 "parse.y"
     {
 		    free(prefix);
 		    asprintf (&prefix, "%s_", (yyvsp[(2) - (2)].string));
@@ -1425,7 +1426,7 @@
     break;
=20
   case 13:
-#line 110 "parse.y"
+#line 111 "parse.y"
     {
 		    prefix =3D realloc(prefix, 1);
 		    if (prefix =3D=3D NULL)
@@ -1435,10 +1436,10 @@
     break;
=20
   case 14:
-#line 117 "parse.y"
+#line 118 "parse.y"
     {
 		    struct error_code *ec =3D malloc(sizeof(*ec));
-		   =20
+
 		    if (ec =3D=3D NULL)
 			errx(1, "malloc");
=20
@@ -1458,7 +1459,7 @@
     break;
=20
   case 15:
-#line 137 "parse.y"
+#line 138 "parse.y"
     {
 			YYACCEPT;
 		}
@@ -1466,7 +1467,7 @@
=20
=20
 /* Line 1267 of yacc.c.  */
-#line 1470 "parse.c"
+#line 1471 "parse.c"
       default: break;
     }
   YY_SYMBOL_PRINT ("-> $$ =3D", yyr1[yyn], &yyval, &yyloc);
@@ -1680,7 +1681,7 @@
 }
=20
=20
-#line 142 "parse.y"
+#line 143 "parse.y"
=20
=20
 static long
@@ -1711,6 +1712,6 @@
 void
 yyerror (char *s)
 {
-     error_message ("%s\n", s);
+     _lex_error_message ("%s\n", s);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/parse.h
--- a/head/crypto/heimdal/lib/com_err/parse.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/parse.h	Tue Apr 17 11:51:51 2012 +0300
@@ -64,7 +64,7 @@
=20
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-#line 53 "parse.y"
+#line 54 "parse.y"
 {
   char *string;
   int number;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/parse.y
--- a/head/crypto/heimdal/lib/com_err/parse.y	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/parse.y	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,40 @@
 %{
 /*
- * Copyright (c) 1998 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "compile_et.h"
 #include "lex.h"
=20
-RCSID("$Id: parse.y 15426 2005-06-16 19:21:42Z lha $");
-
 void yyerror (char *s);
 static long name2number(const char *str);
=20
@@ -48,6 +46,9 @@
 #define alloca(x) malloc(x)
 #endif
=20
+#define YYMALLOC malloc
+#define YYFREE free
+
 %}
=20
 %union {
@@ -61,7 +62,7 @@
=20
 %%
=20
-file		: /* */=20
+file		: /* */
 		| header statements
 		;
=20
@@ -94,7 +95,7 @@
 		| statements statement
 		;
=20
-statement	: INDEX NUMBER=20
+statement	: INDEX NUMBER
 		{
 			number =3D $2;
 		}
@@ -116,7 +117,7 @@
 		| EC STRING ',' STRING
 		{
 		    struct error_code *ec =3D malloc(sizeof(*ec));
-		   =20
+
 		    if (ec =3D=3D NULL)
 			errx(1, "malloc");
=20
@@ -169,5 +170,5 @@
 void
 yyerror (char *s)
 {
-     error_message ("%s\n", s);
+     _lex_error_message ("%s\n", s);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/roken_=
rename.h
--- a/head/crypto/heimdal/lib/com_err/roken_rename.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/com_err/roken_rename.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,61 +1,61 @@
 /*
- * Copyright (c) 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: roken_rename.h 14930 2005-04-24 19:43:06Z lha $ */
+/* $Id$ */
=20
 #ifndef __roken_rename_h__
 #define __roken_rename_h__
=20
 #ifndef HAVE_SNPRINTF
-#define snprintf _com_err_snprintf
+#define rk_snprintf _com_err_snprintf
 #endif
 #ifndef HAVE_VSNPRINTF
-#define vsnprintf _com_err_vsnprintf
+#define rk_vsnprintf _com_err_vsnprintf
 #endif
 #ifndef HAVE_ASPRINTF
-#define asprintf _com_err_asprintf
+#define rk_asprintf _com_err_asprintf
 #endif
 #ifndef HAVE_ASNPRINTF
-#define asnprintf _com_err_asnprintf
+#define rk_asnprintf _com_err_asnprintf
 #endif
 #ifndef HAVE_VASPRINTF
-#define vasprintf _com_err_vasprintf
+#define rk_vasprintf _com_err_vasprintf
 #endif
 #ifndef HAVE_VASNPRINTF
-#define vasnprintf _com_err_vasnprintf
+#define rk_vasnprintf _com_err_vasnprintf
 #endif
 #ifndef HAVE_STRLCPY
-#define strlcpy _com_err_strlcpy
+#define rk_strlcpy _com_err_strlcpy
 #endif
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/com_err/versio=
n-script.map
--- a/head/crypto/heimdal/lib/com_err/version-script.map	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/com_err/version-script.map	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -3,6 +3,7 @@
 HEIMDAL_COM_ERR_1.0 {
 	global:
 		com_right;
+		com_right_r;
 		free_error_table;
 		initialize_error_table_r;
 		add_to_error_table;
@@ -13,6 +14,7 @@
 		init_error_table;
 		reset_com_err_hook;
 		set_com_err_hook;
+		_et_list;
 	local:
 		*;
 };
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ChangeL=
og
--- a/head/crypto/heimdal/lib/gssapi/ChangeLog	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/gssapi/ChangeLog	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,18 +1,125 @@
-2008-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-08-14  Love Hornquist Astrand  <lha at 10a140laptop.local>
+
+	* krb5/accept_sec_context.c: If there is a initiator subkey, copy
+	that to acceptor subkey to match windows behavior. From Metze.
+
+2008-08-02  Love H=C3=B6rnquist =C3=85strand  <lha at h5l.org>
+
+	* ntlm/init_sec_context.c: Catch error
+
+	* krb5/inquire_sec_context_by_oid.c: Catch store failure.
+
+	* mech/gss_canonicalize_name.c: Not init m, return never
+	used (overwritten later).
+
+2008-07-25  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* ntlm/init_sec_context.c: Use krb5_cc_get_config.
+
+2008-07-25  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* krb5/init_sec_context.c: Match the orignal patch I got from
+	metze, seems that DCE-STYLE is even more weirer then what I though
+	when I merged the patch.
+
+2008-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* krb5/init_sec_context.c: Don't add asn1 wrapping to token when
+	using DCE_STYLE.  Patch from Stefan Metzmacher.
+
+2008-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+=09
+	* ntlm/init_sec_context.c: use krb5_get_error_message
+
+2008-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+=09
+	* spnego/spnego_locl.h: Add back "mech/utils.h", its needed for
+	oid/buffer functions.
+
+2008-05-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* spnego: Changes from doug barton to make spnego indepedant of
+	the heimdal version of the plugin system.
+
+2008-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* krb5: use DES_set_key_unchecked()
+
+2008-04-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* add __declspec() for windows.
+
+2008-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* krb5/import_sec_context.c: Use tmp to read ac->flags value to
+	avoid warning.
+
+2008-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* mech/gss_mech_switch.c: Use unsigned where appropriate.
+
+2008-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* test_context.c: Add test for gsskrb5_register_acceptor_identity.
+
+2008-03-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* krb5/init_sec_context.c (init_auth): use right variable to
+	detect if we want to free or not.
+
+2008-02-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Makefile.am: add missing \
+
+	* Makefile.am: reshuffle depenencies
+
+	* Add flag to krb5 to not add GSS-API INT|CONF to the negotiation
+
+2008-02-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* make the SPNEGO mech store the error itself instead, works for
+	everything except other stackable mechs
+
+2008-02-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* spnego/init_sec_context.c (spnego_reply): if the reply token was
+	of length 0, make it the same as no token. Pointed out by Zeqing
+	Xia.
+
+	* krb5/acquire_cred.c (acquire_initiator_cred): handle the
+	credential cache better, use destroy/close when appriate and for
+	all cases. Thanks to Michael Allen for point out the memory-leak
+	that I also fixed.
+
+2008-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* spnego/accept_sec_context.c: Make error reporting somewhat more
+	correct for SPNEGO.
+
+2008-01-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* test_common.c: Improve the error message.
+
+2008-01-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* ntlm/accept_sec_context.c: Avoid free-ing type1 message before
+	its allocated.
+=09
+2008-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ntlm.c: Test source name (and make the acceptor in ntlm gss
 	mech useful).
=20
-2007-12-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/init_sec_context.c: Don't confuse target name and source
 	name, make regressiont tests pass again.
 =09
-2007-12-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ntlm: clean up name handling
=20
-2007-12-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/init_sec_context.c: Use credential if it was passed in.
=20
@@ -30,26 +137,26 @@
 	* mech/gss_release_oid_set.c: Avoid trying to deref NULL, from
 	Phil Fisher.
=20
-2007-12-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_acquire_cred.c: Always try to fetch cred (even with
 	GSS_C_NO_NAME).
=20
-2007-08-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/gss_krb5.c: Readd gss_krb5_get_tkt_flags.
=20
-2007-08-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* spnego/compat.c (_gss_spnego_internal_delete_sec_context):
 	release ctx->target_name too From Rafal Malinowski.
=20
-2007-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/gss_mech_switch.c: Don't try to do dlopen if system doesn't
 	have dlopen. From Rune of Chalmers.
=20
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/gss_duplicate_name.c: New signature of _gss_find_mn.
=20
@@ -73,7 +180,7 @@
=20
 	* Makefile.am: New library version.
=20
-2007-07-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/gss_oid_to_str.c: Refuse to print GSS_C_NULL_OID, from
 	Rafal Malinowski.
@@ -81,7 +188,7 @@
 	* spnego/spnego.asn1: Indent and make NegTokenInit and
 	NegTokenResp extendable.
=20
-2007-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/inquire_cred.c: Implement _gss_ntlm_inquire_cred.
=20
@@ -90,7 +197,7 @@
 	* mech/context.c: If the canned string is "", its no use to the
 	user, make it fall back to the default error string.
 =09
-2007-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/gss_display_name.c (gss_display_name): no name ->
 	fail. From Rafal Malinswski.
@@ -124,7 +231,7 @@
 	Rafal Malinowski, also while here moved to use NegotiationToken
 	for decoding.
=20
-2007-06-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/prf.c (_gsskrb5_pseudo_random): add missing break.
=20
@@ -142,14 +249,14 @@
=20
 	* mech/gss_krb5.c: Free memory in error case, found by beam.
=20
-2007-06-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/inquire_context.c: Use ctx->gssflags for flags.
=20
 	* krb5/display_name.c: Use KRB5_PRINCIPAL_UNPARSE_DISPLAY, this is
 	not ment for machine consumption.
=20
-2007-06-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/digest.c (kdc_alloc): free memory on failure, pointed out
 	by Rafal Malinowski.
@@ -160,11 +267,11 @@
 	* spnego/context_stubs.c (_gss_spnego_display_name): if input_name
 	is null, fail.  From Rafal Malinowski.
 =09
-2007-06-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ntlm/digest.c: Free memory when done.
 =09
-2007-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ntlm.c: Test both with and without keyex.
=20
@@ -173,7 +280,7 @@
=20
 	* test_ntlm.c: Set keyex flag and calculate session key.
 =09
-2007-05-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* spnego/accept_sec_context.c: Use the return value before is
 	overwritten by later calls.  From Rafal Malinowski
@@ -181,14 +288,14 @@
 	* krb5/release_cred.c: Give an minor_status argument to
 	gss_release_oid_set.  From Rafal Malinowski
 =09
-2007-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/accept_sec_context.c: Catch errors and return the up the
 	stack.
=20
 	* test_kcred.c: more testing of lifetimes
 =09
-2007-05-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Drop the gss oid_set function for the krb5 mech,
 	use the mech glue versions instead. Pointed out by Rafal
@@ -196,22 +303,22 @@
=20
 	* krb5: Use gss oid_set functions from mechglue
=20
-2007-05-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/accept_sec_context.c: Set session key only if we are
 	returned a session key. Found by David Love.
 =09
-2007-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* krb5/prf.c: switched MIN to min to make compile on solaris,
 	pointed out by David Love.
 =09
-2007-05-09 Love H=F6rnquist =C5strand <lha at it.su.se>
+2007-05-09 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* krb5/inquire_cred_by_mech.c: Fill in all of the variables if
 	they are passed in. Pointed out by Phil Fisher.
 =09
-2007-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/inquire_cred.c: Fix copy and paste error, bug spotted by
 	from Phil Fisher.
@@ -232,7 +339,7 @@
=20
 	* krb5/inquire_cred_by_mech.c: reimplement
 =09
-2007-05-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ntlm/acquire_cred.c: drop unused variable.
=20
@@ -242,19 +349,19 @@
=20
 	* ntlm: split out backend ntlm server processing
=20
-2007-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/delete_sec_context.c (_gss_ntlm_delete_sec_context): free
 	credcache when done
 =09
-2007-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/init_sec_context.c: ntlm-key credential entry is prefix with @
 =09
 	* ntlm/init_sec_context.c (get_user_ccache): pick up the ntlm
 	creds from the krb5 credential cache.
 =09
-2007-04-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/delete_sec_context.c: free the key stored in the context
=20
@@ -262,14 +369,14 @@
=20
 	* test_oid.c: Switch oid to one that is exported.
 =09
-2007-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/init_sec_context.c: move where hash is calculated to make
 	it easier to add ccache support.
=20
 	* Makefile.am: Add version-script.map to EXTRA_DIST.
 =09
-2007-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Unconfuse newer versions of automake that doesn't
 	know the diffrence between depenences and setting variables. foo:
@@ -283,7 +390,7 @@
 =09
 	* version-script.map: add version script if ld supports it
 =09
-2007-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: test_acquire_cred need test_common.[ch]
=20
@@ -298,7 +405,7 @@
=20
 	* mech/gss_krb5.c: reimplement gss_krb5_ccache_name
 =09
-2007-04-17  Love H=F6rnquist =C5strand <lha at it.su.se>
+2007-04-17  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* spnego/cred_stubs.c: Need to import spnego name before we can
 	use it as a gss_name_t.
@@ -309,27 +416,27 @@
 	* mech/gss_acquire_cred.c (gss_acquire_cred): dont init
 	cred->gc_mc every time in the loop.
 =09
-2007-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add test_common.h
 =09
-2007-02-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-02-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: Add link for
 	gsskrb5_register_acceptor_identity.
=20
-2007-02-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-02-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/copy_ccache.c: Try to leak less memory in the failure case.
 =09
-2007-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gss_display_status.c: Use right printf formater.
=20
 	* test_*.[ch]: split out the error printing function and try to
 	return better errors
=20
-2007-01-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/init_sec_context.c: revert 1.75: (init_auth): only turn on
 	GSS_C_CONF_FLAG and GSS_C_INT_FLAG if the caller requseted it.
@@ -337,7 +444,7 @@
 	This is because Kerberos always support INT|CONF, matches behavior
 	with MS and MIT. The creates problems for the GSS-SPNEGO mech.
 =09
-2007-01-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* krb5/prf.c: constrain desired_output_len
=20
@@ -364,7 +471,7 @@
=20
 	* gssapi_mech.h: Add hook for gm_pseudo_random.
 =09
-2007-01-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_context.c: Don't assume bufer from gss_display_status is
 	ok.
@@ -443,7 +550,7 @@
 	* mech/mech_locl.h (_mg_buffer_zero): new macro that zaps a
 	gss_buffer_t
=20
-2007-01-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech: sprinkel _gss_mg_error
=20
@@ -463,17 +570,17 @@
=20
 	* gss.c: Detect NTLM.
 =09
-2007-01-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gss_accept_sec_context.c: spelling
 =09
-2007-01-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: Include build (private) prototypes header files.
=20
 	* Makefile.am (ntlmsrc): add ntlm/ntlm-private.h
 =09
-2006-12-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ntlm/accept_sec_context.c: Pass signseal argument to
 	_gss_ntlm_set_key.
@@ -495,7 +602,7 @@
=20
 	* ntlm/crypto.c: NTLMv2 sign and verify.
 =09
-2006-12-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/accept_sec_context.c: Don't send targetinfo now.
 =09
@@ -508,7 +615,7 @@
 	* ntlm/init_sec_context.c: Add NTLM_NEG_NTLM2_SESSION, NTLMv2
 	session security (disable because missing sign and seal).
 =09
-2006-12-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ntlm/accept_sec_context.c: split RC4 send and recv keystreams
=20
@@ -540,7 +647,7 @@
 	on the opportunistic token instead of guessing the acceptor name
 	and do gss_acquire_cred, this make SPNEGO work like before.
 =09
-2006-12-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ntlm/init_sec_context.c: Calculate the NTLM version 1 "master"
 	key.
@@ -592,11 +699,11 @@
 	that there are no credentials for) split NegTokenInit and
 	NegTokenResp in acceptor
=20
-2006-12-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/import_name.c: Allocate the buffer from the right length.
 =09
-2006-12-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm/init_sec_context.c (init_sec_context): Tell the other side
 	what domain we think we are talking to.
@@ -633,33 +740,33 @@
=20
 	* ntlm/accept_sec_context.c: Check after a credential to use.
 =09
-2006-12-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* krb5/set_sec_context_option.c (GSS_KRB5_SET_DEFAULT_REALM_X):
 	don't fail on success.  Bug report from Stefan Metzmacher.
 =09
-2006-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* krb5/init_sec_context.c (init_auth): only turn on
 	GSS_C_CONF_FLAG and GSS_C_INT_FLAG if the caller requseted it.
 	From Stefan Metzmacher.
 =09
-2006-12-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am (libgssapi_la_OBJECTS): depends on gssapi_asn1.h
 	spnego_asn1.h.
=20
-2006-11-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/acquire_cred.c: Make krb5_get_init_creds_opt_free take a
 	context argument.
 =09
-2006-11-16  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-11-16  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* test_context.c: Test that token keys are the same, return
 	actual_mech.
 =09
-2006-11-15  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-11-15  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* spnego/spnego_locl.h: Make bitfields unsigned, add maybe_open.
=20
@@ -689,14 +796,14 @@
 	supported mechs list and make sure we don't select that for the
 	preferred mechamism.
 =09
-2006-11-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gss_init_sec_context.c (_gss_mech_cred_find): break out the
 	cred finding to its own function
=20
 	* krb5/wrap.c: Better error strings, from Andrew Bartlet.
 =09
-2006-11-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_context.c: Create our own krb5_context.
=20
@@ -708,13 +815,13 @@
 	* mech/gss_set_cred_option.c: When calling ->gm_set_cred_option
 	and checking for success, use GSS_S_COMPLETE. From Andrew Bartlet.
 =09
-2006-11-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Help solaris make even more.
=20
 	* Makefile.am: Help solaris make.
 =09
-2006-11-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: remove include $(srcdir)/Makefile-digest.am for now
=20
@@ -738,7 +845,7 @@
=20
 	* krb5/gkrb5_err.et: Move the GSS_KRB5_S error here.
 =09
-2006-11-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gss_krb5.c: Add gsskrb5_set_default_realm.
=20
@@ -749,7 +856,7 @@
=20
 	* krb5/external.c: add GSS_KRB5_SET_DEFAULT_REALM_X
 =09
-2006-11-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_context.c: rename krb5_[gs]et_time_wrap to
 	krb5_[gs]et_max_time_skew
@@ -784,12 +891,12 @@
 	* krb5/inquire_sec_context_by_oid.c: check if there is any key at
 	all
 =09
-2006-11-06  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-11-06  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* krb5/inquire_sec_context_by_oid.c: Set more error strings, use
 	right enum for acceptor subkey.  From Andrew Bartlett.
 =09
-2006-11-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_context.c: Test gsskrb5_extract_service_keyblock, needed in
 	PAC valication.  From Andrew Bartlett
@@ -802,7 +909,7 @@
=20
 	* krb5/external.c: Add GSS_KRB5_GET_SERVICE_KEYBLOCK_X
 =09
-2006-11-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_context.c: Rename various routines and constants from
 	canonize to canonicalize.  From Andrew Bartlett
@@ -819,12 +926,12 @@
 	* gssapi/gssapi_krb5.h: Rename various routines and constants from
 	canonize to canonicalize.  From Andrew Bartlett
 =09
-2006-10-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/accept_sec_context.c (gsskrb5_accept_delegated_token): need
 	to free ccache
 =09
-2006-10-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_context.c (loop): free target_name
=20
@@ -843,7 +950,7 @@
=20
 	* krb5/set_cred_option.c (import_cred): free sp
 =09
-2006-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/gss_add_oid_set_member.c: Use old implementation of
 	gss_add_oid_set_member, it leaks less memory.
@@ -855,7 +962,7 @@
 	* mech/gss_release_name.c (gss_release_name): free input_name
 	it-self.
 =09
-2006-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_context.c: Call setprogname.
=20
@@ -864,7 +971,7 @@
 	* gssapi/gssapi_krb5.h: add
 	gsskrb5_extract_authtime_from_sec_context
 =09
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* krb5/inquire_sec_context_by_oid.c: Add get_authtime.
=20
@@ -883,7 +990,7 @@
=20
 	* Makefile.am: more files
 =09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: remove spnego/gssapi_spnego.h, its now in gssapi/
=20
@@ -894,7 +1001,7 @@
 	* gssapi/gssapi.h: Rename GSS_DIGEST_MECHANISM to
 	GSS_SASL_DIGEST_MD5_MECHANISM
 =09
-2006-10-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gssapi.asn1: Make it into a heim_any_set, its doesn't
 	except a tag.
@@ -911,7 +1018,7 @@
 	* krb5/external.c: add GSS_KRB5_GET_INITIATOR_SUBKEY_X,
 	GSS_KRB5_GET_SUBKEY_X
 =09
-2006-10-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_context.c: Support switching on name type oid's
=20
@@ -932,7 +1039,7 @@
=20
 	* mech/gss_krb5.c: add bits to make lucid context work
 =09
-2006-10-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gss_oid_to_str.c: Prefix der primitives with der_.
=20
@@ -943,7 +1050,7 @@
=20
 	* mech/gss_oid_to_str.c: New der_print_heim_oid signature.
 =09
-2006-10-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add test_context
=20
@@ -964,11 +1071,11 @@
=20
 	* spnego/spnego_locl.h: Maybe include <netdb.h>.
 =09
-2006-10-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gss_mech_switch.c: define RTLD_LOCAL to 0 if not defined.
 =09
-2006-10-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: install gssapi_krb5.H and gssapi_spnego.h
=20
@@ -982,7 +1089,7 @@
=20
 	* krb5: reference all include files using 'krb5/'
=20
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: Add file inclusion protection.
=20
@@ -997,14 +1104,14 @@
=20
 	* Makefile.am: split build files into dist_ and noinst_ SOURCES
 =09
-2006-10-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss.c: #if 0 out unused code.
=20
 	* mech/gss_mech_switch.c: Cast argument to ctype(3) functions
 	to (unsigned char).
 =09
-2006-10-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/name.h: remove <sys/queue.h>
=20
@@ -1012,7 +1119,7 @@
 =09
 	* mech/cred.h: remove <sys/queue.h>
=20
-2006-10-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/arcfour.c: Thinker more with header lengths.
=20
@@ -1030,14 +1137,14 @@
 	* spnego/context_stubs.c: Make internal function static (and
 	rename).
 =09
-2006-10-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/inquire_cred.c: Fix "if (x) lock(y)" bug. From Harald
 	Barth.
=20
 	* spnego/spnego_locl.h: Include <sys/param.h> for MAXHOSTNAMELEN.
 =09
-2006-09-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/arcfour.c: Add wrap support, interrop with itself but not
 	w2k3s-sp1
@@ -1055,7 +1162,7 @@
 	protocol. It should be possible to detach the Kerberos DCE-style
 	since it starts with a AP-REQ PDU, but that have to wait for now.
 =09
-2006-09-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: Add GSS_C flags from
 	draft-brezak-win2k-krb-rc4-hmac-04.txt.
@@ -1072,18 +1179,18 @@
 	initiator part from the samba patch by Stefan Metzmacher and
 	Andrew Bartlet (still missing DCE/RPC support)
=20
-2006-08-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss.c (help): use sl_slc_help().
 =09
-2006-07-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss-commands.in: rename command to supported-mechanisms
=20
 	* Makefile.am: Make gss objects depend on the slc built
 	gss-commands.h
 =09
-2006-07-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* gss-commands.in: add slc commands for gss
=20
@@ -1116,7 +1223,7 @@
=20
 	* mech/name.h: no need to mark _gss_find_mn extern.
 =09
-2006-07-19  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-07-19  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* krb5/cfx.c: Redo the wrap length calculations.
=20
@@ -1124,7 +1231,7 @@
=20
 	* mech/gss_display_status.c: Handle more error codes.
 =09
-2006-07-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/mech_locl.h: Include <krb5-types.h> and "mechqueue.h"
=20
@@ -1146,7 +1253,7 @@
 	convert the name to a MN, fail with GSS_S_BAD_NAME rather then a
 	NULL de-reference.
 =09
-2006-07-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* spnego/external.c: readd gss_spnego_inquire_names_for_mech
=20
@@ -1171,7 +1278,7 @@
 	desired_mechs, get our own list with indicate_mechs and remove
 	ourself.
 =09
-2006-07-05 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-07-05 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* spnego/external.c: remove gss_spnego_inquire_names_for_mech, let
 	the mechglue layer implement it
@@ -1182,11 +1289,11 @@
 	* spnego/spnego_locl.c: remove gss_spnego_inquire_names_for_mech, let
 	the mechglue layer implement it
=20
-2006-07-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-07-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* mech/gss_set_cred_option.c: fix argument to gss_release_cred
 =09
-2006-06-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* krb5/init_sec_context.c: Make work on compilers that are
 	somewhat more picky then gcc4 (like gcc2.95)
@@ -1232,7 +1339,7 @@
 	preferred_mech_type and negotiated_mech_type, they where never
 	allocated from the begining.
 =09
-2006-06-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* mech/gss_import_name.c (gss_import_name): avoid
 	type-punned/strict aliasing rules
@@ -1254,7 +1361,7 @@
 	* mech/gss_acquire_cred.c (gss_acquire_cred): if desired_mechs is
 	NO_OID_SET, there is a need to load the mechs, so always do that.
 =09
-2006-06-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* krb5/inquire_cred_by_oid.c: Reimplement GSS_KRB5_COPY_CCACHE_X
 	to instead pass a fullname to the credential, then resolve and
@@ -1295,7 +1402,7 @@
 =09
 	* spnego: Import Luke Howard's SPNEGO from the mechglue branch
=20
-2006-06-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: Add oid_to_str.
=20
@@ -1305,7 +1412,7 @@
=20
 	* test_oid.c: Add test for gss_oid_to_str()
 =09
-2006-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* verify_mic.c: Less pointer signedness warnings.
=20
@@ -1331,21 +1438,21 @@
=20
 	* import_sec_context.c: Less pointer signedness warnings.
=20
-2006-05-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* accept_sec_context.c (gsskrb5_is_cfx): always set is_cfx. From
 	Andrew Abartlet.
 =09
-2006-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* get_mic.c (mic_des3): make sure message_buffer doesn't point to
 	free()ed memory on failure. Pointed out by IBM checker.
 =09
-2006-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Rename u_intXX_t to uintXX_t
 =09
-2006-05-04 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-05-04 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* cfx.c: Less pointer signedness warnings.
=20
@@ -1355,7 +1462,7 @@
 =09
 	* 8003.c (gssapi_decode_*): make data argument const void *
 =09
-2006-04-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* export_sec_context.c: Export sequence order element. From Wynn
 	Wilkes <wynn.wilkes at quest.com>.
@@ -1369,12 +1476,12 @@
=20
 	* test_sequence.c: Add test for import/export sequence.
 =09
-2006-04-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* add_cred.c: Check that cred !=3D GSS_C_NO_CREDENTIAL, this is a
 	standard conformance failure, but much better then a crash.
 =09
-2006-04-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* get_mic.c (get_mic*)_: make sure message_token is cleaned on
 	error, found by IBM checker.
@@ -1382,22 +1489,22 @@
 	* wrap.c (wrap*): Reset output_buffer on error, found by IBM
 	checker.
 =09
-2006-02-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* import_name.c: Accept both GSS_C_NT_HOSTBASED_SERVICE and
 	GSS_C_NT_HOSTBASED_SERVICE_X as nametype for hostbased names.
 =09
-2006-01-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* delete_sec_context.c (gss_delete_sec_context): if the context
 	handle is GSS_C_NO_CONTEXT, don't fall over.
=20
-2005-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: Replace gss_krb5_import_ccache with
 	gss_krb5_import_cred and add more references
 =09
-2005-12-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: Change gss_krb5_import_ccache to gss_krb5_import_cred,
 	it can handle keytabs too.
@@ -1407,7 +1514,7 @@
 	* context_time.c (gssapi_lifetime_left): define the 0 lifetime as
 	GSS_C_INDEFINITE.
 =09
-2005-12-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* acquire_cred.c (acquire_acceptor_cred): only check if principal
 	exists if we got called with principal as an argument.
@@ -1415,12 +1522,12 @@
 	* acquire_cred.c (acquire_acceptor_cred): check that the acceptor
 	exists in the keytab before returning ok.
 =09
-2005-11-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* copy_ccache.c (gss_krb5_import_cred): fix buglet, from Andrew
 	Bartlett.
 =09
-2005-11-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_kcred.c: Rename gss_krb5_import_ccache to
 	gss_krb5_import_cred.
@@ -1428,7 +1535,7 @@
 	* copy_ccache.c: Rename gss_krb5_import_ccache to
 	gss_krb5_import_cred and let it grow code to handle keytabs too.
 =09
-2005-11-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c: Change sematics of ok-as-delegate to match
 	windows if
@@ -1445,11 +1552,11 @@
 	* accept_sec_context.c (gsskrb5_accept_delegated_token): rewrite
 	to use gss_krb5_import_ccache
 =09
-2005-11-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* arcfour.c: Remove signedness warnings.
 =09
-2005-10-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: Document that gss_krb5_import_ccache is copy
 	by reference.
@@ -1462,7 +1569,7 @@
 =09
 	* test_kcred.c: Remove memory leaks.
 =09
-2005-10-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: build test_kcred
 =09
@@ -1484,13 +1591,13 @@
=20
 	* test_kcred.c: test gss_krb5_import_ccache
 =09
-2005-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* acquire_cred.c (acquire_initiator_cred): use krb5_cc_cache_match
 	to find a matching creditial cache, if that failes, fallback to
 	the default cache.
 =09
-2005-10-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi_locl.h: Add gssapi_krb5_set_status and
 	gssapi_krb5_clear_status
@@ -1501,17 +1608,17 @@
 	* display_status.c: Add gssapi_krb5_clear_status,
 	gssapi_krb5_set_status for handling error messages.
 =09
-2005-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* external.c: Use rk_UNCONST to avoid const warning.
 =09
 	* display_status.c: Constify strings to avoid warnings.
 =09
-2005-08-11 Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-11 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c: avoid warnings, update (c)
=20
-2005-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c (spnego_initial): use NegotiationToken
 	encoder now that we have one with the new asn1. compiler.
@@ -1519,7 +1626,7 @@
 	* Makefile.am: the new asn.1 compiler includes the modules name in
 	the depend file
=20
-2005-06-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* decapsulate.c: use rk_UNCONST
=20
@@ -1531,7 +1638,7 @@
 =09
 	* test_cred.c: rename optind to optidx
=20
-2005-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c (init_auth): honor ok-as-delegate if local
 	configuration approves
@@ -1540,7 +1647,7 @@
=20
 	* compat.c: export check_compat as _gss_check_compat
=20
-2005-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c: Prefix Der_class with ASN1_C_ to avoid
 	problems with system headerfiles that pollute the name space.
@@ -1548,13 +1655,13 @@
 	* accept_sec_context.c: Prefix Der_class with ASN1_C_ to avoid
 	problems with system headerfiles that pollute the name space.
=20
-2005-05-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c (init_auth): set
 	KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED (for java compatibility),
 	also while here, use krb5_auth_con_addflags
=20
-2005-05-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* arcfour.c (_gssapi_wrap_arcfour): fix calculating the encap
 	length. From: Tom Maher <tmaher at eecs.berkeley.edu>
@@ -1563,12 +1670,12 @@
=20
 	* test_cred.c (main): Call setprogname.
=20
-2005-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* prefix all sequence symbols with _, they are not part of the
 	GSS-API api. By comment from Wynn Wilkes <wynnw at vintela.com>
=20
-2005-04-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* accept_sec_context.c: break out the processing of the delegated
 	credential to a separate function to make error handling easier,
@@ -1578,26 +1685,26 @@
=20
 	* Makefile.am: add test_sequence to TESTS
=20
-2005-04-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* 8003.c (gssapi_krb5_verify_8003_checksum): check that cksum
 	isn't NULL From: Nicolas Pouvesle <npouvesle at tenablesecurity.com>
=20
-2005-03-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: use $(LIB_roken)
=20
-2005-03-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* display_status.c (gssapi_krb5_set_error_string): pass in the
 	krb5_context to krb5_free_error_string
 =09
-2005-03-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* display_status.c (gssapi_krb5_set_error_string): don't misuse
 	the krb5_get_error_string api
=20
-2005-03-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* compat.c (_gss_DES3_get_mic_compat): don't unlock mutex
 	here. Bug reported by Stefan Metzmacher <metze at samba.org>
@@ -1643,33 +1750,33 @@
 	* wrap.c: use gss_krb5_get_subkey(),
 	  support KEYTYPE_ARCFOUR_56
=20
-2004-11-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-11-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* inquire_cred.c: Reverse order of HEIMDAL_MUTEX_unlock and
 	gss_release_cred to avoid deadlock, from Luke Howard
 	<lukeh at padl.com>.
=20
-2004-09-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: gss_krb5_extract_authz_data_from_sec_context
 	was renamed to gsskrb5_extract_authz_data_from_sec_context
 =09
-2004-08-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* unwrap.c: mutex buglet, From: Luke Howard <lukeh at PADL.COM>
 =09
 	* arcfour.c: mutex buglet, From: Luke Howard <lukeh at PADL.COM>
 =09
-2004-05-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.3: spelling from Josef El-Rayes <josef at FreeBSD.org> while
 	here, write some text about the SPNEGO situation
 =09
-2004-04-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: s/CTXAcceptorSubkey/CFXAcceptorSubkey/
 =09
-2004-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: add GSS_C_EXPECTING_MECH_LIST_MIC_FLAG From: Luke
 	Howard <lukeh at padl.com>
@@ -1688,7 +1795,7 @@
 	* compat.c: add _gss_spnego_require_mechlist_mic for compatibility
 	with MS SPNEGO, From: Luke Howard <lukeh at padl.com>
 =09
-2004-04-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-04-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* accept_sec_context.c (gsskrb5_is_cfx): krb5_keyblock->keytype is
 	an enctype, not keytype
@@ -1700,7 +1807,7 @@
=20
 	* init_sec_context.c (spnego_initial): handle mech_token better
 =09
-2004-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: add gss_krb5_get_tkt_flags
 =09
@@ -1711,7 +1818,7 @@
 =09
 	* gss_acquire_cred.3: document gss_krb5_get_tkt_flags
 =09
-2004-03-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* acquire_cred.c (gss_acquire_cred): check usage before even
 	bothering to process it, add both keytab and initial tgt if
@@ -1744,7 +1851,7 @@
=20
 	* test_acquire_cred.c: fix comment
 =09
-2004-03-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* arcfour.h: drop structures for message formats, no longer used
 =09
@@ -1762,7 +1869,7 @@
 =09
 	* Makefile.am: spnego_files +=3D asn1_NegotiationToken.x
 =09
-2004-01-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: add gss_krb5_ccache_name
 =09
@@ -1776,51 +1883,51 @@
 =09
 	* gss_acquire_cred.3: document gss_krb5_ccache_name
 =09
-2003-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: make rrc a modulus operation if its longer then the
 	length of the message, noticed by Sam Hartman
=20
-2003-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* accept_sec_context.c: use krb5_auth_con_addflags
 =09
-2003-12-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: Wrap token id was in wrong order, found by Sam Hartman
 =09
-2003-12-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: add AcceptorSubkey (but no code understand it yet) ignore
 	unknown token flags
 =09
-2003-11-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* accept_sec_context.c: Don't require timestamp to be set on
 	delegated token, its already protected by the outer token (and
 	windows doesn't alway send it) Pointed out by Zi-Bin Yang
 	<zbyang at decru.com> on heimdal-discuss
=20
-2003-11-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: fix {} error, pointed out by Liqiang Zhu
 =09
-2003-11-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: Sequence number should be stored in bigendian order From:
 	Luke Howard <lukeh at padl.com>
 =09
-2003-11-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* delete_sec_context.c (gss_delete_sec_context): don't free
 	ticket, krb5_free_ticket does that now
=20
-2003-11-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: checksum the header last in MIC token, update to -03
 	From: Luke Howard <lukeh at padl.com>
 =09
-2003-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* add_cred.c: If its a MEMORY cc, make a copy. We need to do this
 	since now gss_release_cred will destroy the cred. This should be
@@ -1833,12 +1940,12 @@
 	* acquire_cred.c (acquire_initiator_cred): use kret instead of ret
 	where appropriate
=20
-2003-09-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: spelling
 	From: jmc <jmc at prioris.mini.pw.edu.pl>
 =09
-2003-09-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: - EC and RRC are big-endian, not little-endian - The
 	default is now to rotate regardless of GSS_C_DCE_STYLE. There are
@@ -1846,7 +1953,7 @@
 	avoids allocating memory on the heap if rrc <=3D 256
 	From: Luke Howard <lukeh at padl.com>
 =09
-2003-09-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.[ch]: rrc_rotate() was untested and broken, fix it.
 	Set and verify wrap Token->Filler.
@@ -1854,12 +1961,12 @@
 	were accidentally swapped with delete tokens.
 	From: Luke Howard <lukeh at PADL.COM>
=20
-2003-09-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.[ch]: no ASN.1-ish header on per-message tokens
 	From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-09-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* arcfour.h: remove depenency on gss_arcfour_mic_token and
 	gss_arcfour_warp_token
@@ -1867,11 +1974,11 @@
 	* arcfour.c: remove depenency on gss_arcfour_mic_token and
 	gss_arcfour_warp_token
=20
-2003-09-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* 8003.c: remove #if 0'ed code
 =09
-2003-09-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* accept_sec_context.c (gsskrb5_accept_sec_context): set sequence
 	number when not requesting mutual auth From: Luke Howard
@@ -1880,7 +1987,7 @@
 	* init_sec_context.c (init_auth): set sequence number when not
 	requesting mutual auth From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-09-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* arcfour.c (*): set minor_status
 	(gss_wrap): set conf_state to conf_req_flags on success
@@ -1889,14 +1996,14 @@
 	* wrap.c (gss_wrap_size_limit): use existing function From: Luke
 	Howard <lukeh at PADL.COM>
 =09
-2003-09-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* indicate_mechs.c (gss_indicate_mechs): in case of error, free
 	mech_set
=20
 	* indicate_mechs.c (gss_indicate_mechs): add SPNEGO
=20
-2003-09-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c (spnego_initial): catch errors and return
 	them
@@ -1905,7 +2012,7 @@
 	the CHOICE branch encoding, also where here, free no longer used
 	memory
=20
-2003-09-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: support GSS_SPNEGO_MECHANISM
 =09
@@ -1934,22 +2041,22 @@
 =09
 	* Makefile.am: build SPNEGO file
 =09
-2003-09-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* external.c: SPENGO and IAKERB oids
 =09
 	* spnego.asn1: SPENGO ASN1
 =09
-2003-09-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.c: RRC also need to be zero before wraping them
 	From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-09-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* encapsulate.c (gssapi_krb5_encap_length): don't return void
 =09
-2003-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* verify_mic.c: switch from the des_ to the DES_ api
 =09
@@ -1965,7 +2072,7 @@
 	* acquire_cred.c: use
 	krb5_get_init_creds_opt_alloc/krb5_get_init_creds_opt_free
=20
-2003-09-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* copy_ccache.c: rename
 	gss_krb5_extract_authz_data_from_sec_context to
@@ -1974,7 +2081,7 @@
 	* gssapi.h: rename gss_krb5_extract_authz_data_from_sec_context to
 	gsskrb5_extract_authz_data_from_sec_context
 =09
-2003-08-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* copy_ccache.c (gss_krb5_extract_authz_data_from_sec_context):
 	check that we have a ticket before we start to use it
@@ -1991,12 +2098,12 @@
 	* verify_mic.c (gss_verify_mic_internal): switch type and key
 	argument
=20
-2003-08-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cfx.[ch]: draft-ietf-krb-wg-gssapi-cfx-01.txt implemetation
 	From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-08-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* arcfour.c (arcfour_mic_cksum): use free_Checksum to free the
 	checksum
@@ -2048,7 +2155,7 @@
 =09
 	* 8003.c: add gssapi_{en,de}code_be_om_uint32
 =09
-2003-08-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* arcfour.c (_gssapi_verify_mic_arcfour): Do the checksum on right
 	area. Swap filler check, it was reversed.
@@ -2061,7 +2168,7 @@
=20
 	* arcfour.h: arcfour gss-api mech, get_mic/verify_mic working
 =09
-2003-08-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi_locl.h: always include cfx.h add prototype for
 	_gssapi_decapsulate
@@ -2072,7 +2179,7 @@
 	* decapsulate.c: add _gssapi_decapsulate, from Luke Howard
 	<lukeh at PADL.COM>
 =09
-2003-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* unwrap.c: encap/decap now takes a oid if the enctype/keytype is
 	arcfour, return error add hook for cfx
@@ -2104,17 +2211,17 @@
 	* inquire_cred.c (gss_inquire_cred): handle cred_handle being
 	GSS_C_NO_CREDENTIAL and use the default cred then.
 =09
-2003-08-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: break out extensions and document
 	gsskrb5_register_acceptor_identity
=20
-2003-08-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_acquire_cred.c (print_time): time is returned in seconds
 	from now, not unix time
=20
-2003-08-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* compat.c (check_compat): avoid leaking principal when finding a
 	match
@@ -2125,7 +2232,7 @@
 	* acquire_cred.c (gss_acquire_cred): 4th argument to
 	gss_test_oid_set_member is a int
=20
-2003-07-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c (repl_mutual): don't set kerberos error where
 	there was no kerberos error
@@ -2140,12 +2247,12 @@
 	krb5_context. Add destruction/creation functions for the thread
 	specific storage that the error string handling is using.
 =09
-2003-07-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: add missing prototype and missing .Ft
 	arguments
=20
-2003-06-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* verify_mic.c: reorder code so sequence numbers can can be used
 =09
@@ -2173,7 +2280,7 @@
=20
 	* Makefile.am: can't have sequence.c in two different places
=20
-2003-06-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_sequence.c: check rollover, print summery
 =09
@@ -2184,7 +2291,7 @@
 =09
 	From: Luke Howard <lukeh at PADL.COM>
 =09
-2003-06-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi_locl.h: add prototypes for sequence.c
 =09
@@ -2194,7 +2301,7 @@
 	* sequence.c: sequence number checks, order and replay
 	* test_sequence.c: sequence number checks, order and replay
=20
-2003-06-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* accept_sec_context.c (gss_accept_sec_context): make sure time is
 	returned in seconds from now, not in kerberos time
@@ -2213,7 +2320,7 @@
 	* verify_mic.c: make sure minor_status is always set, pointed out
 	by Luke Howard <lukeh at PADL.COM>
=20
-2003-05-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* *.[ch]: do some basic locking (no reference counting so contexts=20
 	  can be removed while still used)
@@ -2224,16 +2331,16 @@
 	* gss_acquire_cred.3: document argument lifetime_rec to function
 	gss_inquire_context
=20
-2003-05-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_acquire_cred.c: test gss_add_cred more then once
 =09
-2003-05-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-05-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.h: if __cplusplus, wrap the extern variable (just to be
 	safe) and functions in extern "C" { }
 =09
-2003-04-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.3: more about the des3 mic mess
 =09
@@ -2245,14 +2352,14 @@
 	* verify_mic.c (verify_mic_des3): If MIC verification fails,
 	retry using the `old' MIC computation (with zero IV).
=20
-2003-04-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: more about difference between comparing IN
 	and MN
=20
 	* gss_acquire_cred.3: more about name type and access control
 =09
-2003-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: document gss_context_time
 =09
@@ -2273,17 +2380,17 @@
 	(GSS_C_KRB5_COMPAT_DES3_MIC): cpp symbol that exists if
 	gss_krb5_compat_des3_mic exists
 =09
-2003-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am:  (libgssapi_la_LDFLAGS): update major
 	version of gssapi for incompatiblity in 3des getmic support
 =09
-2003-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: test_acquire_cred_LDADD: use libgssapi.la not
 	./libgssapi.la (make make -jN work)
=20
-2003-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.3: spelling
 =09
@@ -2291,7 +2398,7 @@
 	header.h, from Thomas Klausner <wiz at netbsd.org>
=20
 =09
-2003-04-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: spelling
 =09
@@ -2307,26 +2414,26 @@
=20
 	* test_acquire_cred.c: test gss_add_cred too
 =09
-2003-04-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: build test_acquire_cred
 =09
 	* test_acquire_cred.c: simple gss_acquire_cred test
 =09
-2003-04-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: s/gssapi/GSS-API/
 =09
-2003-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: document v1 interface (and that they are
 	obsolete)
=20
-2003-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_acquire_cred.3: list supported mechanism and nametypes
 =09
-2003-03-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* gss_acquire_cred.3: text about gss_display_name
=20
@@ -2438,7 +2545,7 @@
=20
 	* gssapi.h: comment out the argument names
 =09
-2003-03-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gssapi.3: add LIST OF FUNCTIONS and copyright/license
=20
@@ -2446,29 +2553,29 @@
 =09
 	* Makefile.am: man_MANS +=3D gss_aquire_cred.3
 =09
-2003-03-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gss_aquire_cred.3: the gssapi api manpage
 =09
-2003-03-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* inquire_context.c: (gss_inquire_context): rename argument open
 	to open_context
=20
 	* gssapi.h (gss_inquire_context): rename argument open to open_context
=20
-2003-02-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_sec_context.c (do_delegation): remove unused variable
 	subkey
=20
 	* gssapi.3: all 0.5.x version had broken token delegation
 =09
-2003-02-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* (init_auth): only generate one subkey
=20
-2003-01-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-01-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* verify_mic.c (verify_mic_des3): fix 3des verify_mic to conform
 	to rfc (and mit kerberos), provide backward compat hook
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/Makefil=
e.am
--- a/head/crypto/heimdal/lib/gssapi/Makefile.am	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/Makefile.am	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,12 +1,18 @@
-# $Id: Makefile.am 22399 2008-01-11 14:25:47Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
 AUTOMAKE_OPTIONS =3D subdir-objects
=20
-AM_CPPFLAGS +=3D -I$(srcdir)/../krb5 \
+AM_CPPFLAGS +=3D \
+	-I$(srcdir)/../krb5 \
 	-I$(srcdir) \
+	-I$(srcdir)/gssapi \
 	-I$(srcdir)/mech \
+	-I$(srcdir)/ntlm \
+	-I$(srcdir)/krb5 \
+	-I$(srcdir)/spnego \
+	$(INCLUDE_libintl) \
 	$(INCLUDE_hcrypto) \
 	$(INCLUDE_krb4)
=20
@@ -18,8 +24,10 @@
 	krb5/acquire_cred.c \
 	krb5/add_cred.c \
 	krb5/address_to_krb5addr.c \
+	krb5/aeap.c \
 	krb5/arcfour.c \
 	krb5/canonicalize_name.c \
+	krb5/creds.c \
 	krb5/ccache_name.c \
 	krb5/cfx.c \
 	krb5/cfx.h \
@@ -51,17 +59,19 @@
 	krb5/inquire_mechs_for_name.c \
 	krb5/inquire_names_for_mech.c \
 	krb5/inquire_sec_context_by_oid.c \
+	krb5/pname_to_uid.c \
 	krb5/process_context_token.c \
 	krb5/prf.c \
 	krb5/release_buffer.c \
 	krb5/release_cred.c \
 	krb5/release_name.c \
 	krb5/sequence.c \
+	krb5/store_cred.c \
 	krb5/set_cred_option.c \
 	krb5/set_sec_context_option.c \
 	krb5/ticket_flags.c \
 	krb5/unwrap.c \
-	krb5/v1.c \
+	krb5/authorize_localname.c \
 	krb5/verify_mic.c \
 	krb5/wrap.c
=20
@@ -69,25 +79,36 @@
 	mech/context.h \
 	mech/context.c \
 	mech/cred.h \
+	mech/compat.h \
+	mech/doxygen.c \
 	mech/gss_accept_sec_context.c \
 	mech/gss_acquire_cred.c \
+	mech/gss_acquire_cred_ext.c \
+	mech/gss_acquire_cred_with_password.c \
 	mech/gss_add_cred.c \
+	mech/gss_add_cred_with_password.c \
 	mech/gss_add_oid_set_member.c \
+	mech/gss_aeap.c \
 	mech/gss_buffer_set.c \
 	mech/gss_canonicalize_name.c \
 	mech/gss_compare_name.c \
 	mech/gss_context_time.c \
 	mech/gss_create_empty_oid_set.c \
+	mech/gss_cred.c \
 	mech/gss_decapsulate_token.c \
+	mech/gss_delete_name_attribute.c \
 	mech/gss_delete_sec_context.c \
 	mech/gss_display_name.c \
+	mech/gss_display_name_ext.c \
 	mech/gss_display_status.c \
 	mech/gss_duplicate_name.c \
 	mech/gss_duplicate_oid.c \
 	mech/gss_encapsulate_token.c \
 	mech/gss_export_name.c \
+	mech/gss_export_name_composite.c \
 	mech/gss_export_sec_context.c \
 	mech/gss_get_mic.c \
+	mech/gss_get_name_attribute.c \
 	mech/gss_import_name.c \
 	mech/gss_import_sec_context.c \
 	mech/gss_indicate_mechs.c \
@@ -97,12 +118,16 @@
 	mech/gss_inquire_cred_by_mech.c \
 	mech/gss_inquire_cred_by_oid.c \
 	mech/gss_inquire_mechs_for_name.c \
+	mech/gss_inquire_name.c \
 	mech/gss_inquire_names_for_mech.c \
 	mech/gss_krb5.c \
 	mech/gss_mech_switch.c \
+	mech/gss_mo.c \
 	mech/gss_names.c \
+	mech/gss_oid.c \
 	mech/gss_oid_equal.c \
 	mech/gss_oid_to_str.c \
+	mech/gss_pname_to_uid.c \
 	mech/gss_process_context_token.c \
 	mech/gss_pseudo_random.c \
 	mech/gss_release_buffer.c \
@@ -112,11 +137,14 @@
 	mech/gss_release_oid_set.c \
 	mech/gss_seal.c \
 	mech/gss_set_cred_option.c \
+	mech/gss_set_name_attribute.c \
 	mech/gss_set_sec_context_option.c \
 	mech/gss_sign.c \
+	mech/gss_store_cred.c \
 	mech/gss_test_oid_set_member.c \
 	mech/gss_unseal.c \
 	mech/gss_unwrap.c \
+	mech/gss_authorize_localname.c \
 	mech/gss_utils.c \
 	mech/gss_verify.c \
 	mech/gss_verify_mic.c \
@@ -146,6 +174,7 @@
 	ntlm/canonicalize_name.c \
 	ntlm/compare_name.c \
 	ntlm/context_time.c \
+	ntlm/creds.c \
 	ntlm/crypto.c \
 	ntlm/delete_sec_context.c \
 	ntlm/display_name.c \
@@ -161,14 +190,15 @@
 	ntlm/indicate_mechs.c \
 	ntlm/init_sec_context.c \
 	ntlm/inquire_context.c \
-	ntlm/inquire_cred.c \
 	ntlm/inquire_cred_by_mech.c \
 	ntlm/inquire_mechs_for_name.c \
 	ntlm/inquire_names_for_mech.c \
+	ntlm/inquire_sec_context_by_oid.c \
+	ntlm/iter_cred.c \
 	ntlm/process_context_token.c \
 	ntlm/release_cred.c \
 	ntlm/release_name.c \
-	ntlm/digest.c
+	ntlm/kdc.c
=20
 $(srcdir)/ntlm/ntlm-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p ntlm/ntlm-pr=
ivate.h $(ntlmsrc) || rm -f ntlm/ntlm-private.h
@@ -184,7 +214,9 @@
 	gkrb5_err.h \
 	$(BUILT_SOURCES)
=20
-libgssapi_la_LDFLAGS =3D -version-info 2:0:0
+libgssapi_la_DEPENDENCIES =3D version-script.map
+
+libgssapi_la_LDFLAGS =3D -version-info 3:0:0
=20
 if versionscript
 libgssapi_la_LDFLAGS +=3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-scrip=
t.map
@@ -206,9 +238,12 @@
 	ntlm/ntlm-private.h \
 	spnego/spnego-private.h \
 	krb5/gsskrb5-private.h
+
 nobase_include_HEADERS =3D \
 	gssapi/gssapi.h \
 	gssapi/gssapi_krb5.h \
+	gssapi/gssapi_ntlm.h \
+	gssapi/gssapi_oid.h \
 	gssapi/gssapi_spnego.h
=20
 gssapidir =3D $(includedir)/gssapi
@@ -227,9 +262,13 @@
 	asn1_NegTokenInitWin.x			\
 	asn1_NegTokenResp.x
=20
-$(libgssapi_la_OBJECTS): $(srcdir)/krb5/gsskrb5-private.h
-$(libgssapi_la_OBJECTS): $(srcdir)/spnego/spnego-private.h
-$(libgssapi_la_OBJECTS): $(srcdir)/ntlm/ntlm-private.h
+BUILTHEADERS =3D \
+	$(srcdir)/krb5/gsskrb5-private.h \
+	$(srcdir)/spnego/spnego-private.h \
+	$(srcdir)/ntlm/ntlm-private.h
+
+$(libgssapi_la_OBJECTS): $(BUILTHEADERS)
+$(test_context_OBJECTS): $(BUILTHEADERS)
=20
 $(libgssapi_la_OBJECTS): $(srcdir)/version-script.map
=20
@@ -237,18 +276,18 @@
=20
 CLEANFILES =3D $(BUILT_SOURCES) \
 	gkrb5_err.h gkrb5_err.c \
-	$(spnego_files) spnego_asn1.h spnego_asn1_files \
-	$(gssapi_files) gssapi_asn1.h gssapi_asn1_files \
+	$(spnego_files) spnego_asn1*.h* spnego_asn1_files spnego_asn1-template.c \
+	$(gssapi_files) gssapi_asn1*.h* gssapi_asn1_files gssapi_asn1-template.c \
 	gss-commands.h gss-commands.c
=20
-$(spnego_files) spnego_asn1.h: spnego_asn1_files
-$(gssapi_files) gssapi_asn1.h: gssapi_asn1_files
+$(spnego_files) spnego_asn1.hx spnego_asn1-priv.hx: spnego_asn1_files
+$(gssapi_files) gssapi_asn1.hx gssapi_asn1-priv.hx: gssapi_asn1_files
=20
-spnego_asn1_files: ../asn1/asn1_compile$(EXEEXT) $(srcdir)/spnego/spnego.a=
sn1
-	../asn1/asn1_compile$(EXEEXT) --sequence=3DMechTypeList $(srcdir)/spnego/=
spnego.asn1 spnego_asn1
+spnego_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/spnego/spnego.asn1 $(srcd=
ir)/spnego/spnego.opt
+	$(ASN1_COMPILE) --option-file=3D$(srcdir)/spnego/spnego.opt $(srcdir)/spn=
ego/spnego.asn1 spnego_asn1
=20
-gssapi_asn1_files: ../asn1/asn1_compile$(EXEEXT) $(srcdir)/mech/gssapi.asn1
-	../asn1/asn1_compile$(EXEEXT) $(srcdir)/mech/gssapi.asn1 gssapi_asn1
+gssapi_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/mech/gssapi.asn1
+	$(ASN1_COMPILE) $(srcdir)/mech/gssapi.asn1 gssapi_asn1
=20
 $(srcdir)/krb5/gsskrb5-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5/gsskrb5=
-private.h $(krb5src) || rm -f krb5/gsskrb5-private.h
@@ -264,7 +303,7 @@
=20
 check_PROGRAMS =3D test_acquire_cred $(TESTS)
=20
-bin_PROGRAMS =3D gss
+bin_PROGRAMS =3D gsstool
 noinst_PROGRAMS =3D test_cred test_kcred test_context test_ntlm
=20
 test_context_SOURCES =3D test_context.c test_common.c test_common.h
@@ -281,33 +320,39 @@
=20
 # gss
=20
-dist_gss_SOURCES =3D gss.c
-nodist_gss_SOURCES =3D gss-commands.c gss-commands.h
+dist_gsstool_SOURCES =3D gsstool.c
+nodist_gsstool_SOURCES =3D gss-commands.c gss-commands.h
=20
-gss_LDADD =3D libgssapi.la \
+gsstool_LDADD =3D libgssapi.la \
 	$(top_builddir)/lib/sl/libsl.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_readline) \
 	$(LIB_roken)
=20
-SLC =3D $(top_builddir)/lib/sl/slc
-
 gss-commands.c gss-commands.h: gss-commands.in
 	$(SLC) $(srcdir)/gss-commands.in
=20
-$(gss_OBJECTS): gss-commands.h
+$(gsstool_OBJECTS): gss-commands.h
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	libgssapi-version.rc \
+	libgssapi-exports.def \
 	$(man_MANS) \
 	krb5/gkrb5_err.et \
 	mech/gssapi.asn1 \
 	spnego/spnego.asn1 \
+	spnego/spnego.opt \
 	version-script.map \
 	gss-commands.in
=20
-# to help stupid solaris make
-
-$(libgssapi_la_OBJECTS): gkrb5_err.h gssapi_asn1.h spnego_asn1.h
+$(libgssapi_la_OBJECTS): gkrb5_err.h gssapi_asn1.h gssapi_asn1-priv.h
+$(libgssapi_la_OBJECTS): spnego_asn1.h spnego_asn1-priv.h
+$(libgssapi_la_OBJECTS): $(srcdir)/gssapi/gssapi_oid.h
=20
 gkrb5_err.h gkrb5_err.c: $(srcdir)/krb5/gkrb5_err.et
 	$(COMPILE_ET) $(srcdir)/krb5/gkrb5_err.et
+
+$(srcdir)/gssapi/gssapi_oid.h $(srcdir)/mech/gss_oid.c:
+	perl $(srcdir)/gen-oid.pl -b base -h $(srcdir)/oid.txt > $(srcdir)/gssapi=
/gssapi_oid.h
+	perl $(srcdir)/gen-oid.pl -b base $(srcdir)/oid.txt > $(srcdir)/mech/gss_=
oid.c
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/Makefil=
e.in
--- a/head/crypto/heimdal/lib/gssapi/Makefile.in	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/Makefile.in	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22399 2008-01-11 14:25:47Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -47,13 +49,13 @@
 @versionscript_TRUE at am__append_1 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
 TESTS =3D test_oid$(EXEEXT) test_names$(EXEEXT) test_cfx$(EXEEXT)
 check_PROGRAMS =3D test_acquire_cred$(EXEEXT) $(am__EXEEXT_1)
-bin_PROGRAMS =3D gss$(EXEEXT)
+bin_PROGRAMS =3D gsstool$(EXEEXT)
 noinst_PROGRAMS =3D test_cred$(EXEEXT) test_kcred$(EXEEXT) \
 	test_context$(EXEEXT) test_ntlm$(EXEEXT)
 subdir =3D lib/gssapi
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -68,7 +70,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -82,9 +84,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -92,36 +97,47 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \
 	"$(DESTDIR)$(man3dir)" "$(DESTDIR)$(man5dir)" \
 	"$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)" \
 	"$(DESTDIR)$(gssapidir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
 am__DEPENDENCIES_1 =3D
-libgssapi_la_DEPENDENCIES =3D $(top_builddir)/lib/ntlm/libheimntlm.la \
-	$(top_builddir)/lib/krb5/libkrb5.la \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
 am__dirstamp =3D $(am__leading_dot)dirstamp
 am__objects_1 =3D krb5/8003.lo krb5/accept_sec_context.lo \
 	krb5/acquire_cred.lo krb5/add_cred.lo \
-	krb5/address_to_krb5addr.lo krb5/arcfour.lo \
-	krb5/canonicalize_name.lo krb5/ccache_name.lo krb5/cfx.lo \
-	krb5/compare_name.lo krb5/compat.lo krb5/context_time.lo \
-	krb5/copy_ccache.lo krb5/decapsulate.lo \
+	krb5/address_to_krb5addr.lo krb5/aeap.lo krb5/arcfour.lo \
+	krb5/canonicalize_name.lo krb5/creds.lo krb5/ccache_name.lo \
+	krb5/cfx.lo krb5/compare_name.lo krb5/compat.lo \
+	krb5/context_time.lo krb5/copy_ccache.lo krb5/decapsulate.lo \
 	krb5/delete_sec_context.lo krb5/display_name.lo \
 	krb5/display_status.lo krb5/duplicate_name.lo \
 	krb5/encapsulate.lo krb5/export_name.lo \
@@ -131,54 +147,66 @@
 	krb5/inquire_context.lo krb5/inquire_cred.lo \
 	krb5/inquire_cred_by_mech.lo krb5/inquire_cred_by_oid.lo \
 	krb5/inquire_mechs_for_name.lo krb5/inquire_names_for_mech.lo \
-	krb5/inquire_sec_context_by_oid.lo \
+	krb5/inquire_sec_context_by_oid.lo krb5/pname_to_uid.lo \
 	krb5/process_context_token.lo krb5/prf.lo \
 	krb5/release_buffer.lo krb5/release_cred.lo \
-	krb5/release_name.lo krb5/sequence.lo krb5/set_cred_option.lo \
-	krb5/set_sec_context_option.lo krb5/ticket_flags.lo \
-	krb5/unwrap.lo krb5/v1.lo krb5/verify_mic.lo krb5/wrap.lo
-am__objects_2 =3D mech/context.lo mech/gss_accept_sec_context.lo \
-	mech/gss_acquire_cred.lo mech/gss_add_cred.lo \
-	mech/gss_add_oid_set_member.lo mech/gss_buffer_set.lo \
-	mech/gss_canonicalize_name.lo mech/gss_compare_name.lo \
-	mech/gss_context_time.lo mech/gss_create_empty_oid_set.lo \
-	mech/gss_decapsulate_token.lo mech/gss_delete_sec_context.lo \
-	mech/gss_display_name.lo mech/gss_display_status.lo \
+	krb5/release_name.lo krb5/sequence.lo krb5/store_cred.lo \
+	krb5/set_cred_option.lo krb5/set_sec_context_option.lo \
+	krb5/ticket_flags.lo krb5/unwrap.lo \
+	krb5/authorize_localname.lo krb5/verify_mic.lo krb5/wrap.lo
+am__objects_2 =3D mech/context.lo mech/doxygen.lo \
+	mech/gss_accept_sec_context.lo mech/gss_acquire_cred.lo \
+	mech/gss_acquire_cred_ext.lo \
+	mech/gss_acquire_cred_with_password.lo mech/gss_add_cred.lo \
+	mech/gss_add_cred_with_password.lo \
+	mech/gss_add_oid_set_member.lo mech/gss_aeap.lo \
+	mech/gss_buffer_set.lo mech/gss_canonicalize_name.lo \
+	mech/gss_compare_name.lo mech/gss_context_time.lo \
+	mech/gss_create_empty_oid_set.lo mech/gss_cred.lo \
+	mech/gss_decapsulate_token.lo \
+	mech/gss_delete_name_attribute.lo \
+	mech/gss_delete_sec_context.lo mech/gss_display_name.lo \
+	mech/gss_display_name_ext.lo mech/gss_display_status.lo \
 	mech/gss_duplicate_name.lo mech/gss_duplicate_oid.lo \
 	mech/gss_encapsulate_token.lo mech/gss_export_name.lo \
+	mech/gss_export_name_composite.lo \
 	mech/gss_export_sec_context.lo mech/gss_get_mic.lo \
-	mech/gss_import_name.lo mech/gss_import_sec_context.lo \
-	mech/gss_indicate_mechs.lo mech/gss_init_sec_context.lo \
-	mech/gss_inquire_context.lo mech/gss_inquire_cred.lo \
-	mech/gss_inquire_cred_by_mech.lo \
+	mech/gss_get_name_attribute.lo mech/gss_import_name.lo \
+	mech/gss_import_sec_context.lo mech/gss_indicate_mechs.lo \
+	mech/gss_init_sec_context.lo mech/gss_inquire_context.lo \
+	mech/gss_inquire_cred.lo mech/gss_inquire_cred_by_mech.lo \
 	mech/gss_inquire_cred_by_oid.lo \
-	mech/gss_inquire_mechs_for_name.lo \
+	mech/gss_inquire_mechs_for_name.lo mech/gss_inquire_name.lo \
 	mech/gss_inquire_names_for_mech.lo mech/gss_krb5.lo \
-	mech/gss_mech_switch.lo mech/gss_names.lo \
-	mech/gss_oid_equal.lo mech/gss_oid_to_str.lo \
-	mech/gss_process_context_token.lo mech/gss_pseudo_random.lo \
-	mech/gss_release_buffer.lo mech/gss_release_cred.lo \
-	mech/gss_release_name.lo mech/gss_release_oid.lo \
-	mech/gss_release_oid_set.lo mech/gss_seal.lo \
-	mech/gss_set_cred_option.lo mech/gss_set_sec_context_option.lo \
-	mech/gss_sign.lo mech/gss_test_oid_set_member.lo \
-	mech/gss_unseal.lo mech/gss_unwrap.lo mech/gss_utils.lo \
+	mech/gss_mech_switch.lo mech/gss_mo.lo mech/gss_names.lo \
+	mech/gss_oid.lo mech/gss_oid_equal.lo mech/gss_oid_to_str.lo \
+	mech/gss_pname_to_uid.lo mech/gss_process_context_token.lo \
+	mech/gss_pseudo_random.lo mech/gss_release_buffer.lo \
+	mech/gss_release_cred.lo mech/gss_release_name.lo \
+	mech/gss_release_oid.lo mech/gss_release_oid_set.lo \
+	mech/gss_seal.lo mech/gss_set_cred_option.lo \
+	mech/gss_set_name_attribute.lo \
+	mech/gss_set_sec_context_option.lo mech/gss_sign.lo \
+	mech/gss_store_cred.lo mech/gss_test_oid_set_member.lo \
+	mech/gss_unseal.lo mech/gss_unwrap.lo \
+	mech/gss_authorize_localname.lo mech/gss_utils.lo \
 	mech/gss_verify.lo mech/gss_verify_mic.lo mech/gss_wrap.lo \
 	mech/gss_wrap_size_limit.lo \
 	mech/gss_inquire_sec_context_by_oid.lo
 am__objects_3 =3D ntlm/accept_sec_context.lo ntlm/acquire_cred.lo \
 	ntlm/add_cred.lo ntlm/canonicalize_name.lo \
-	ntlm/compare_name.lo ntlm/context_time.lo ntlm/crypto.lo \
-	ntlm/delete_sec_context.lo ntlm/display_name.lo \
+	ntlm/compare_name.lo ntlm/context_time.lo ntlm/creds.lo \
+	ntlm/crypto.lo ntlm/delete_sec_context.lo ntlm/display_name.lo \
 	ntlm/display_status.lo ntlm/duplicate_name.lo \
 	ntlm/export_name.lo ntlm/export_sec_context.lo \
 	ntlm/external.lo ntlm/import_name.lo \
 	ntlm/import_sec_context.lo ntlm/indicate_mechs.lo \
 	ntlm/init_sec_context.lo ntlm/inquire_context.lo \
-	ntlm/inquire_cred.lo ntlm/inquire_cred_by_mech.lo \
-	ntlm/inquire_mechs_for_name.lo ntlm/inquire_names_for_mech.lo \
+	ntlm/inquire_cred_by_mech.lo ntlm/inquire_mechs_for_name.lo \
+	ntlm/inquire_names_for_mech.lo \
+	ntlm/inquire_sec_context_by_oid.lo ntlm/iter_cred.lo \
 	ntlm/process_context_token.lo ntlm/release_cred.lo \
-	ntlm/release_name.lo ntlm/digest.lo
+	ntlm/release_name.lo ntlm/kdc.lo
 am__objects_4 =3D spnego/accept_sec_context.lo spnego/compat.lo \
 	spnego/context_stubs.lo spnego/cred_stubs.lo \
 	spnego/external.lo spnego/init_sec_context.lo
@@ -197,13 +225,12 @@
 libgssapi_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libgssapi_la_LDFLAGS) $(LDFLAGS) -o $@
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 am__EXEEXT_1 =3D test_oid$(EXEEXT) test_names$(EXEEXT) test_cfx$(EXEEXT)
 PROGRAMS =3D $(bin_PROGRAMS) $(noinst_PROGRAMS)
-dist_gss_OBJECTS =3D gss.$(OBJEXT)
-nodist_gss_OBJECTS =3D gss-commands.$(OBJEXT)
-gss_OBJECTS =3D $(dist_gss_OBJECTS) $(nodist_gss_OBJECTS)
-gss_DEPENDENCIES =3D libgssapi.la $(top_builddir)/lib/sl/libsl.la \
+dist_gsstool_OBJECTS =3D gsstool.$(OBJEXT)
+nodist_gsstool_OBJECTS =3D gss-commands.$(OBJEXT)
+gsstool_OBJECTS =3D $(dist_gsstool_OBJECTS) $(nodist_gsstool_OBJECTS)
+gsstool_DEPENDENCIES =3D libgssapi.la $(top_builddir)/lib/sl/libsl.la \
 	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1)
 am_test_acquire_cred_OBJECTS =3D test_acquire_cred.$(OBJEXT) \
@@ -248,9 +275,9 @@
 test_oid_LDADD =3D $(LDADD)
 test_oid_DEPENDENCIES =3D libgssapi.la \
 	$(top_builddir)/lib/krb5/libkrb5.la $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -261,72 +288,80 @@
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
 SOURCES =3D $(dist_libgssapi_la_SOURCES) $(nodist_libgssapi_la_SOURCES) \
-	$(dist_gss_SOURCES) $(nodist_gss_SOURCES) \
+	$(dist_gsstool_SOURCES) $(nodist_gsstool_SOURCES) \
 	$(test_acquire_cred_SOURCES) $(test_cfx_SOURCES) \
 	$(test_context_SOURCES) test_cred.c test_kcred.c test_names.c \
 	$(test_ntlm_SOURCES) test_oid.c
-DIST_SOURCES =3D $(dist_libgssapi_la_SOURCES) $(dist_gss_SOURCES) \
+DIST_SOURCES =3D $(dist_libgssapi_la_SOURCES) $(dist_gsstool_SOURCES) \
 	$(test_acquire_cred_SOURCES) $(test_cfx_SOURCES) \
 	$(test_context_SOURCES) test_cred.c test_kcred.c test_names.c \
 	$(test_ntlm_SOURCES) test_oid.c
 man3dir =3D $(mandir)/man3
 man5dir =3D $(mandir)/man5
 MANS =3D $(man_MANS)
-includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-nobase_includeHEADERS_INSTALL =3D $(install_sh_DATA)
-nodist_gssapiHEADERS_INSTALL =3D $(INSTALL_HEADER)
 HEADERS =3D $(include_HEADERS) $(nobase_include_HEADERS) \
 	$(nodist_gssapi_HEADERS) $(noinst_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -350,10 +385,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -370,6 +406,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -385,31 +423,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -424,10 +476,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -468,31 +522,37 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	-I$(srcdir)/../krb5 -I$(srcdir) -I$(srcdir)/mech \
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I$(srcdir)/../krb5 -I$(srcdir) \
+	-I$(srcdir)/gssapi -I$(srcdir)/mech -I$(srcdir)/ntlm \
+	-I$(srcdir)/krb5 -I$(srcdir)/spnego $(INCLUDE_libintl) \
 	$(INCLUDE_hcrypto) $(INCLUDE_krb4)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 AUTOMAKE_OPTIONS =3D subdir-objects
 lib_LTLIBRARIES =3D libgssapi.la
@@ -502,8 +562,10 @@
 	krb5/acquire_cred.c \
 	krb5/add_cred.c \
 	krb5/address_to_krb5addr.c \
+	krb5/aeap.c \
 	krb5/arcfour.c \
 	krb5/canonicalize_name.c \
+	krb5/creds.c \
 	krb5/ccache_name.c \
 	krb5/cfx.c \
 	krb5/cfx.h \
@@ -535,17 +597,19 @@
 	krb5/inquire_mechs_for_name.c \
 	krb5/inquire_names_for_mech.c \
 	krb5/inquire_sec_context_by_oid.c \
+	krb5/pname_to_uid.c \
 	krb5/process_context_token.c \
 	krb5/prf.c \
 	krb5/release_buffer.c \
 	krb5/release_cred.c \
 	krb5/release_name.c \
 	krb5/sequence.c \
+	krb5/store_cred.c \
 	krb5/set_cred_option.c \
 	krb5/set_sec_context_option.c \
 	krb5/ticket_flags.c \
 	krb5/unwrap.c \
-	krb5/v1.c \
+	krb5/authorize_localname.c \
 	krb5/verify_mic.c \
 	krb5/wrap.c
=20
@@ -553,25 +617,36 @@
 	mech/context.h \
 	mech/context.c \
 	mech/cred.h \
+	mech/compat.h \
+	mech/doxygen.c \
 	mech/gss_accept_sec_context.c \
 	mech/gss_acquire_cred.c \
+	mech/gss_acquire_cred_ext.c \
+	mech/gss_acquire_cred_with_password.c \
 	mech/gss_add_cred.c \
+	mech/gss_add_cred_with_password.c \
 	mech/gss_add_oid_set_member.c \
+	mech/gss_aeap.c \
 	mech/gss_buffer_set.c \
 	mech/gss_canonicalize_name.c \
 	mech/gss_compare_name.c \
 	mech/gss_context_time.c \
 	mech/gss_create_empty_oid_set.c \
+	mech/gss_cred.c \
 	mech/gss_decapsulate_token.c \
+	mech/gss_delete_name_attribute.c \
 	mech/gss_delete_sec_context.c \
 	mech/gss_display_name.c \
+	mech/gss_display_name_ext.c \
 	mech/gss_display_status.c \
 	mech/gss_duplicate_name.c \
 	mech/gss_duplicate_oid.c \
 	mech/gss_encapsulate_token.c \
 	mech/gss_export_name.c \
+	mech/gss_export_name_composite.c \
 	mech/gss_export_sec_context.c \
 	mech/gss_get_mic.c \
+	mech/gss_get_name_attribute.c \
 	mech/gss_import_name.c \
 	mech/gss_import_sec_context.c \
 	mech/gss_indicate_mechs.c \
@@ -581,12 +656,16 @@
 	mech/gss_inquire_cred_by_mech.c \
 	mech/gss_inquire_cred_by_oid.c \
 	mech/gss_inquire_mechs_for_name.c \
+	mech/gss_inquire_name.c \
 	mech/gss_inquire_names_for_mech.c \
 	mech/gss_krb5.c \
 	mech/gss_mech_switch.c \
+	mech/gss_mo.c \
 	mech/gss_names.c \
+	mech/gss_oid.c \
 	mech/gss_oid_equal.c \
 	mech/gss_oid_to_str.c \
+	mech/gss_pname_to_uid.c \
 	mech/gss_process_context_token.c \
 	mech/gss_pseudo_random.c \
 	mech/gss_release_buffer.c \
@@ -596,11 +675,14 @@
 	mech/gss_release_oid_set.c \
 	mech/gss_seal.c \
 	mech/gss_set_cred_option.c \
+	mech/gss_set_name_attribute.c \
 	mech/gss_set_sec_context_option.c \
 	mech/gss_sign.c \
+	mech/gss_store_cred.c \
 	mech/gss_test_oid_set_member.c \
 	mech/gss_unseal.c \
 	mech/gss_unwrap.c \
+	mech/gss_authorize_localname.c \
 	mech/gss_utils.c \
 	mech/gss_verify.c \
 	mech/gss_verify_mic.c \
@@ -630,6 +712,7 @@
 	ntlm/canonicalize_name.c \
 	ntlm/compare_name.c \
 	ntlm/context_time.c \
+	ntlm/creds.c \
 	ntlm/crypto.c \
 	ntlm/delete_sec_context.c \
 	ntlm/display_name.c \
@@ -645,14 +728,15 @@
 	ntlm/indicate_mechs.c \
 	ntlm/init_sec_context.c \
 	ntlm/inquire_context.c \
-	ntlm/inquire_cred.c \
 	ntlm/inquire_cred_by_mech.c \
 	ntlm/inquire_mechs_for_name.c \
 	ntlm/inquire_names_for_mech.c \
+	ntlm/inquire_sec_context_by_oid.c \
+	ntlm/iter_cred.c \
 	ntlm/process_context_token.c \
 	ntlm/release_cred.c \
 	ntlm/release_name.c \
-	ntlm/digest.c
+	ntlm/kdc.c
=20
 dist_libgssapi_la_SOURCES =3D \
 	$(krb5src) \
@@ -665,7 +749,8 @@
 	gkrb5_err.h \
 	$(BUILT_SOURCES)
=20
-libgssapi_la_LDFLAGS =3D -version-info 2:0:0 $(am__append_1)
+libgssapi_la_DEPENDENCIES =3D version-script.map
+libgssapi_la_LDFLAGS =3D -version-info 3:0:0 $(am__append_1)
 libgssapi_la_LIBADD =3D \
 	$(top_builddir)/lib/ntlm/libheimntlm.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
@@ -685,6 +770,8 @@
 nobase_include_HEADERS =3D \
 	gssapi/gssapi.h \
 	gssapi/gssapi_krb5.h \
+	gssapi/gssapi_ntlm.h \
+	gssapi/gssapi_oid.h \
 	gssapi/gssapi_spnego.h
=20
 gssapidir =3D $(includedir)/gssapi
@@ -701,11 +788,16 @@
 	asn1_NegTokenInitWin.x			\
 	asn1_NegTokenResp.x
=20
+BUILTHEADERS =3D \
+	$(srcdir)/krb5/gsskrb5-private.h \
+	$(srcdir)/spnego/spnego-private.h \
+	$(srcdir)/ntlm/ntlm-private.h
+
 BUILT_SOURCES =3D $(spnego_files:.x=3D.c) $(gssapi_files:.x=3D.c)
 CLEANFILES =3D $(BUILT_SOURCES) \
 	gkrb5_err.h gkrb5_err.c \
-	$(spnego_files) spnego_asn1.h spnego_asn1_files \
-	$(gssapi_files) gssapi_asn1.h gssapi_asn1_files \
+	$(spnego_files) spnego_asn1*.h* spnego_asn1_files spnego_asn1-template.c \
+	$(gssapi_files) gssapi_asn1*.h* gssapi_asn1_files gssapi_asn1-template.c \
 	gss-commands.h gss-commands.c
=20
 # test_sequence=20
@@ -723,20 +815,23 @@
=20
=20
 # gss
-dist_gss_SOURCES =3D gss.c
-nodist_gss_SOURCES =3D gss-commands.c gss-commands.h
-gss_LDADD =3D libgssapi.la \
+dist_gsstool_SOURCES =3D gsstool.c
+nodist_gsstool_SOURCES =3D gss-commands.c gss-commands.h
+gsstool_LDADD =3D libgssapi.la \
 	$(top_builddir)/lib/sl/libsl.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(LIB_readline) \
 	$(LIB_roken)
=20
-SLC =3D $(top_builddir)/lib/sl/slc
 EXTRA_DIST =3D \
+	NTMakefile \
+	libgssapi-version.rc \
+	libgssapi-exports.def \
 	$(man_MANS) \
 	krb5/gkrb5_err.et \
 	mech/gssapi.asn1 \
 	spnego/spnego.asn1 \
+	spnego/spnego.opt \
 	version-script.map \
 	gss-commands.in
=20
@@ -744,19 +839,19 @@
 	$(MAKE) $(AM_MAKEFLAGS) all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/gssap=
i/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/gssapi/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/gssapi/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/gssapi/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -774,23 +869,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -804,202 +904,384 @@
 krb5/$(am__dirstamp):
 	@$(MKDIR_P) krb5
 	@: > krb5/$(am__dirstamp)
-krb5/8003.lo: krb5/$(am__dirstamp)
-krb5/accept_sec_context.lo: krb5/$(am__dirstamp)
-krb5/acquire_cred.lo: krb5/$(am__dirstamp)
-krb5/add_cred.lo: krb5/$(am__dirstamp)
-krb5/address_to_krb5addr.lo: krb5/$(am__dirstamp)
-krb5/arcfour.lo: krb5/$(am__dirstamp)
-krb5/canonicalize_name.lo: krb5/$(am__dirstamp)
-krb5/ccache_name.lo: krb5/$(am__dirstamp)
-krb5/cfx.lo: krb5/$(am__dirstamp)
-krb5/compare_name.lo: krb5/$(am__dirstamp)
-krb5/compat.lo: krb5/$(am__dirstamp)
-krb5/context_time.lo: krb5/$(am__dirstamp)
-krb5/copy_ccache.lo: krb5/$(am__dirstamp)
-krb5/decapsulate.lo: krb5/$(am__dirstamp)
-krb5/delete_sec_context.lo: krb5/$(am__dirstamp)
-krb5/display_name.lo: krb5/$(am__dirstamp)
-krb5/display_status.lo: krb5/$(am__dirstamp)
-krb5/duplicate_name.lo: krb5/$(am__dirstamp)
-krb5/encapsulate.lo: krb5/$(am__dirstamp)
-krb5/export_name.lo: krb5/$(am__dirstamp)
-krb5/export_sec_context.lo: krb5/$(am__dirstamp)
-krb5/external.lo: krb5/$(am__dirstamp)
-krb5/get_mic.lo: krb5/$(am__dirstamp)
-krb5/import_name.lo: krb5/$(am__dirstamp)
-krb5/import_sec_context.lo: krb5/$(am__dirstamp)
-krb5/indicate_mechs.lo: krb5/$(am__dirstamp)
-krb5/init.lo: krb5/$(am__dirstamp)
-krb5/init_sec_context.lo: krb5/$(am__dirstamp)
-krb5/inquire_context.lo: krb5/$(am__dirstamp)
-krb5/inquire_cred.lo: krb5/$(am__dirstamp)
-krb5/inquire_cred_by_mech.lo: krb5/$(am__dirstamp)
-krb5/inquire_cred_by_oid.lo: krb5/$(am__dirstamp)
-krb5/inquire_mechs_for_name.lo: krb5/$(am__dirstamp)
-krb5/inquire_names_for_mech.lo: krb5/$(am__dirstamp)
-krb5/inquire_sec_context_by_oid.lo: krb5/$(am__dirstamp)
-krb5/process_context_token.lo: krb5/$(am__dirstamp)
-krb5/prf.lo: krb5/$(am__dirstamp)
-krb5/release_buffer.lo: krb5/$(am__dirstamp)
-krb5/release_cred.lo: krb5/$(am__dirstamp)
-krb5/release_name.lo: krb5/$(am__dirstamp)
-krb5/sequence.lo: krb5/$(am__dirstamp)
-krb5/set_cred_option.lo: krb5/$(am__dirstamp)
-krb5/set_sec_context_option.lo: krb5/$(am__dirstamp)
-krb5/ticket_flags.lo: krb5/$(am__dirstamp)
-krb5/unwrap.lo: krb5/$(am__dirstamp)
-krb5/v1.lo: krb5/$(am__dirstamp)
-krb5/verify_mic.lo: krb5/$(am__dirstamp)
-krb5/wrap.lo: krb5/$(am__dirstamp)
+krb5/$(DEPDIR)/$(am__dirstamp):
+	@$(MKDIR_P) krb5/$(DEPDIR)
+	@: > krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/8003.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/accept_sec_context.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/acquire_cred.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/add_cred.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/address_to_krb5addr.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/aeap.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/arcfour.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/canonicalize_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/creds.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/ccache_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/cfx.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/compare_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/compat.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/context_time.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/copy_ccache.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/decapsulate.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/delete_sec_context.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/display_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/display_status.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/duplicate_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/encapsulate.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/export_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/export_sec_context.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/external.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/get_mic.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/import_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/import_sec_context.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/indicate_mechs.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/init.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/init_sec_context.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/inquire_context.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/inquire_cred.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/inquire_cred_by_mech.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/inquire_cred_by_oid.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/inquire_mechs_for_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/inquire_names_for_mech.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/inquire_sec_context_by_oid.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/pname_to_uid.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/process_context_token.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/prf.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/release_buffer.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/release_cred.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/release_name.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/sequence.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/store_cred.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/set_cred_option.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/set_sec_context_option.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/ticket_flags.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/unwrap.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/authorize_localname.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/verify_mic.lo: krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
+krb5/wrap.lo: krb5/$(am__dirstamp) krb5/$(DEPDIR)/$(am__dirstamp)
 mech/$(am__dirstamp):
 	@$(MKDIR_P) mech
 	@: > mech/$(am__dirstamp)
-mech/context.lo: mech/$(am__dirstamp)
-mech/gss_accept_sec_context.lo: mech/$(am__dirstamp)
-mech/gss_acquire_cred.lo: mech/$(am__dirstamp)
-mech/gss_add_cred.lo: mech/$(am__dirstamp)
-mech/gss_add_oid_set_member.lo: mech/$(am__dirstamp)
-mech/gss_buffer_set.lo: mech/$(am__dirstamp)
-mech/gss_canonicalize_name.lo: mech/$(am__dirstamp)
-mech/gss_compare_name.lo: mech/$(am__dirstamp)
-mech/gss_context_time.lo: mech/$(am__dirstamp)
-mech/gss_create_empty_oid_set.lo: mech/$(am__dirstamp)
-mech/gss_decapsulate_token.lo: mech/$(am__dirstamp)
-mech/gss_delete_sec_context.lo: mech/$(am__dirstamp)
-mech/gss_display_name.lo: mech/$(am__dirstamp)
-mech/gss_display_status.lo: mech/$(am__dirstamp)
-mech/gss_duplicate_name.lo: mech/$(am__dirstamp)
-mech/gss_duplicate_oid.lo: mech/$(am__dirstamp)
-mech/gss_encapsulate_token.lo: mech/$(am__dirstamp)
-mech/gss_export_name.lo: mech/$(am__dirstamp)
-mech/gss_export_sec_context.lo: mech/$(am__dirstamp)
-mech/gss_get_mic.lo: mech/$(am__dirstamp)
-mech/gss_import_name.lo: mech/$(am__dirstamp)
-mech/gss_import_sec_context.lo: mech/$(am__dirstamp)
-mech/gss_indicate_mechs.lo: mech/$(am__dirstamp)
-mech/gss_init_sec_context.lo: mech/$(am__dirstamp)
-mech/gss_inquire_context.lo: mech/$(am__dirstamp)
-mech/gss_inquire_cred.lo: mech/$(am__dirstamp)
-mech/gss_inquire_cred_by_mech.lo: mech/$(am__dirstamp)
-mech/gss_inquire_cred_by_oid.lo: mech/$(am__dirstamp)
-mech/gss_inquire_mechs_for_name.lo: mech/$(am__dirstamp)
-mech/gss_inquire_names_for_mech.lo: mech/$(am__dirstamp)
-mech/gss_krb5.lo: mech/$(am__dirstamp)
-mech/gss_mech_switch.lo: mech/$(am__dirstamp)
-mech/gss_names.lo: mech/$(am__dirstamp)
-mech/gss_oid_equal.lo: mech/$(am__dirstamp)
-mech/gss_oid_to_str.lo: mech/$(am__dirstamp)
-mech/gss_process_context_token.lo: mech/$(am__dirstamp)
-mech/gss_pseudo_random.lo: mech/$(am__dirstamp)
-mech/gss_release_buffer.lo: mech/$(am__dirstamp)
-mech/gss_release_cred.lo: mech/$(am__dirstamp)
-mech/gss_release_name.lo: mech/$(am__dirstamp)
-mech/gss_release_oid.lo: mech/$(am__dirstamp)
-mech/gss_release_oid_set.lo: mech/$(am__dirstamp)
-mech/gss_seal.lo: mech/$(am__dirstamp)
-mech/gss_set_cred_option.lo: mech/$(am__dirstamp)
-mech/gss_set_sec_context_option.lo: mech/$(am__dirstamp)
-mech/gss_sign.lo: mech/$(am__dirstamp)
-mech/gss_test_oid_set_member.lo: mech/$(am__dirstamp)
-mech/gss_unseal.lo: mech/$(am__dirstamp)
-mech/gss_unwrap.lo: mech/$(am__dirstamp)
-mech/gss_utils.lo: mech/$(am__dirstamp)
-mech/gss_verify.lo: mech/$(am__dirstamp)
-mech/gss_verify_mic.lo: mech/$(am__dirstamp)
-mech/gss_wrap.lo: mech/$(am__dirstamp)
-mech/gss_wrap_size_limit.lo: mech/$(am__dirstamp)
-mech/gss_inquire_sec_context_by_oid.lo: mech/$(am__dirstamp)
+mech/$(DEPDIR)/$(am__dirstamp):
+	@$(MKDIR_P) mech/$(DEPDIR)
+	@: > mech/$(DEPDIR)/$(am__dirstamp)
+mech/context.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/doxygen.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_accept_sec_context.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_acquire_cred.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_acquire_cred_ext.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_acquire_cred_with_password.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_add_cred.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_add_cred_with_password.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_add_oid_set_member.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_aeap.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_buffer_set.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_canonicalize_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_compare_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_context_time.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_create_empty_oid_set.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_cred.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_decapsulate_token.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_delete_name_attribute.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_delete_sec_context.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_display_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_display_name_ext.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_display_status.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_duplicate_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_duplicate_oid.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_encapsulate_token.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_export_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_export_name_composite.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_export_sec_context.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_get_mic.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_get_name_attribute.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_import_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_import_sec_context.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_indicate_mechs.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_init_sec_context.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_context.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_cred.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_cred_by_mech.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_cred_by_oid.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_mechs_for_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_names_for_mech.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_krb5.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_mech_switch.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_mo.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_names.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_oid.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_oid_equal.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_oid_to_str.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_pname_to_uid.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_process_context_token.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_pseudo_random.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_release_buffer.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_release_cred.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_release_name.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_release_oid.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_release_oid_set.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_seal.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_set_cred_option.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_set_name_attribute.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_set_sec_context_option.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_sign.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_store_cred.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_test_oid_set_member.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_unseal.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_unwrap.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_authorize_localname.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_utils.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_verify.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_verify_mic.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_wrap.lo: mech/$(am__dirstamp) mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_wrap_size_limit.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
+mech/gss_inquire_sec_context_by_oid.lo: mech/$(am__dirstamp) \
+	mech/$(DEPDIR)/$(am__dirstamp)
 ntlm/$(am__dirstamp):
 	@$(MKDIR_P) ntlm
 	@: > ntlm/$(am__dirstamp)
-ntlm/accept_sec_context.lo: ntlm/$(am__dirstamp)
-ntlm/acquire_cred.lo: ntlm/$(am__dirstamp)
-ntlm/add_cred.lo: ntlm/$(am__dirstamp)
-ntlm/canonicalize_name.lo: ntlm/$(am__dirstamp)
-ntlm/compare_name.lo: ntlm/$(am__dirstamp)
-ntlm/context_time.lo: ntlm/$(am__dirstamp)
-ntlm/crypto.lo: ntlm/$(am__dirstamp)
-ntlm/delete_sec_context.lo: ntlm/$(am__dirstamp)
-ntlm/display_name.lo: ntlm/$(am__dirstamp)
-ntlm/display_status.lo: ntlm/$(am__dirstamp)
-ntlm/duplicate_name.lo: ntlm/$(am__dirstamp)
-ntlm/export_name.lo: ntlm/$(am__dirstamp)
-ntlm/export_sec_context.lo: ntlm/$(am__dirstamp)
-ntlm/external.lo: ntlm/$(am__dirstamp)
-ntlm/import_name.lo: ntlm/$(am__dirstamp)
-ntlm/import_sec_context.lo: ntlm/$(am__dirstamp)
-ntlm/indicate_mechs.lo: ntlm/$(am__dirstamp)
-ntlm/init_sec_context.lo: ntlm/$(am__dirstamp)
-ntlm/inquire_context.lo: ntlm/$(am__dirstamp)
-ntlm/inquire_cred.lo: ntlm/$(am__dirstamp)
-ntlm/inquire_cred_by_mech.lo: ntlm/$(am__dirstamp)
-ntlm/inquire_mechs_for_name.lo: ntlm/$(am__dirstamp)
-ntlm/inquire_names_for_mech.lo: ntlm/$(am__dirstamp)
-ntlm/process_context_token.lo: ntlm/$(am__dirstamp)
-ntlm/release_cred.lo: ntlm/$(am__dirstamp)
-ntlm/release_name.lo: ntlm/$(am__dirstamp)
-ntlm/digest.lo: ntlm/$(am__dirstamp)
+ntlm/$(DEPDIR)/$(am__dirstamp):
+	@$(MKDIR_P) ntlm/$(DEPDIR)
+	@: > ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/accept_sec_context.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/acquire_cred.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/add_cred.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/canonicalize_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/compare_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/context_time.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/creds.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/crypto.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/delete_sec_context.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/display_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/display_status.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/duplicate_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/export_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/export_sec_context.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/external.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/import_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/import_sec_context.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/indicate_mechs.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/init_sec_context.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/inquire_context.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/inquire_cred_by_mech.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/inquire_mechs_for_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/inquire_names_for_mech.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/inquire_sec_context_by_oid.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/iter_cred.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/process_context_token.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/release_cred.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/release_name.lo: ntlm/$(am__dirstamp) \
+	ntlm/$(DEPDIR)/$(am__dirstamp)
+ntlm/kdc.lo: ntlm/$(am__dirstamp) ntlm/$(DEPDIR)/$(am__dirstamp)
 spnego/$(am__dirstamp):
 	@$(MKDIR_P) spnego
 	@: > spnego/$(am__dirstamp)
-spnego/accept_sec_context.lo: spnego/$(am__dirstamp)
-spnego/compat.lo: spnego/$(am__dirstamp)
-spnego/context_stubs.lo: spnego/$(am__dirstamp)
-spnego/cred_stubs.lo: spnego/$(am__dirstamp)
-spnego/external.lo: spnego/$(am__dirstamp)
-spnego/init_sec_context.lo: spnego/$(am__dirstamp)
+spnego/$(DEPDIR)/$(am__dirstamp):
+	@$(MKDIR_P) spnego/$(DEPDIR)
+	@: > spnego/$(DEPDIR)/$(am__dirstamp)
+spnego/accept_sec_context.lo: spnego/$(am__dirstamp) \
+	spnego/$(DEPDIR)/$(am__dirstamp)
+spnego/compat.lo: spnego/$(am__dirstamp) \
+	spnego/$(DEPDIR)/$(am__dirstamp)
+spnego/context_stubs.lo: spnego/$(am__dirstamp) \
+	spnego/$(DEPDIR)/$(am__dirstamp)
+spnego/cred_stubs.lo: spnego/$(am__dirstamp) \
+	spnego/$(DEPDIR)/$(am__dirstamp)
+spnego/external.lo: spnego/$(am__dirstamp) \
+	spnego/$(DEPDIR)/$(am__dirstamp)
+spnego/init_sec_context.lo: spnego/$(am__dirstamp) \
+	spnego/$(DEPDIR)/$(am__dirstamp)
 libgssapi.la: $(libgssapi_la_OBJECTS) $(libgssapi_la_DEPENDENCIES)=20
 	$(libgssapi_la_LINK) -rpath $(libdir) $(libgssapi_la_OBJECTS) $(libgssapi=
_la_LIBADD) $(LIBS)
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
-gss$(EXEEXT): $(gss_OBJECTS) $(gss_DEPENDENCIES)=20
-	@rm -f gss$(EXEEXT)
-	$(LINK) $(gss_OBJECTS) $(gss_LDADD) $(LIBS)
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
+gsstool$(EXEEXT): $(gsstool_OBJECTS) $(gsstool_DEPENDENCIES)=20
+	@rm -f gsstool$(EXEEXT)
+	$(LINK) $(gsstool_OBJECTS) $(gsstool_LDADD) $(LIBS)
 test_acquire_cred$(EXEEXT): $(test_acquire_cred_OBJECTS) $(test_acquire_cr=
ed_DEPENDENCIES)=20
 	@rm -f test_acquire_cred$(EXEEXT)
 	$(LINK) $(test_acquire_cred_OBJECTS) $(test_acquire_cred_LDADD) $(LIBS)
-krb5/test_cfx.$(OBJEXT): krb5/$(am__dirstamp)
+krb5/test_cfx.$(OBJEXT): krb5/$(am__dirstamp) \
+	krb5/$(DEPDIR)/$(am__dirstamp)
 test_cfx$(EXEEXT): $(test_cfx_OBJECTS) $(test_cfx_DEPENDENCIES)=20
 	@rm -f test_cfx$(EXEEXT)
 	$(LINK) $(test_cfx_OBJECTS) $(test_cfx_LDADD) $(LIBS)
@@ -1034,8 +1316,12 @@
 	-rm -f krb5/add_cred.lo
 	-rm -f krb5/address_to_krb5addr.$(OBJEXT)
 	-rm -f krb5/address_to_krb5addr.lo
+	-rm -f krb5/aeap.$(OBJEXT)
+	-rm -f krb5/aeap.lo
 	-rm -f krb5/arcfour.$(OBJEXT)
 	-rm -f krb5/arcfour.lo
+	-rm -f krb5/authorize_localname.$(OBJEXT)
+	-rm -f krb5/authorize_localname.lo
 	-rm -f krb5/canonicalize_name.$(OBJEXT)
 	-rm -f krb5/canonicalize_name.lo
 	-rm -f krb5/ccache_name.$(OBJEXT)
@@ -1050,6 +1336,8 @@
 	-rm -f krb5/context_time.lo
 	-rm -f krb5/copy_ccache.$(OBJEXT)
 	-rm -f krb5/copy_ccache.lo
+	-rm -f krb5/creds.$(OBJEXT)
+	-rm -f krb5/creds.lo
 	-rm -f krb5/decapsulate.$(OBJEXT)
 	-rm -f krb5/decapsulate.lo
 	-rm -f krb5/delete_sec_context.$(OBJEXT)
@@ -1094,6 +1382,8 @@
 	-rm -f krb5/inquire_names_for_mech.lo
 	-rm -f krb5/inquire_sec_context_by_oid.$(OBJEXT)
 	-rm -f krb5/inquire_sec_context_by_oid.lo
+	-rm -f krb5/pname_to_uid.$(OBJEXT)
+	-rm -f krb5/pname_to_uid.lo
 	-rm -f krb5/prf.$(OBJEXT)
 	-rm -f krb5/prf.lo
 	-rm -f krb5/process_context_token.$(OBJEXT)
@@ -1110,27 +1400,39 @@
 	-rm -f krb5/set_cred_option.lo
 	-rm -f krb5/set_sec_context_option.$(OBJEXT)
 	-rm -f krb5/set_sec_context_option.lo
+	-rm -f krb5/store_cred.$(OBJEXT)
+	-rm -f krb5/store_cred.lo
 	-rm -f krb5/test_cfx.$(OBJEXT)
 	-rm -f krb5/ticket_flags.$(OBJEXT)
 	-rm -f krb5/ticket_flags.lo
 	-rm -f krb5/unwrap.$(OBJEXT)
 	-rm -f krb5/unwrap.lo
-	-rm -f krb5/v1.$(OBJEXT)
-	-rm -f krb5/v1.lo
 	-rm -f krb5/verify_mic.$(OBJEXT)
 	-rm -f krb5/verify_mic.lo
 	-rm -f krb5/wrap.$(OBJEXT)
 	-rm -f krb5/wrap.lo
 	-rm -f mech/context.$(OBJEXT)
 	-rm -f mech/context.lo
+	-rm -f mech/doxygen.$(OBJEXT)
+	-rm -f mech/doxygen.lo
 	-rm -f mech/gss_accept_sec_context.$(OBJEXT)
 	-rm -f mech/gss_accept_sec_context.lo
 	-rm -f mech/gss_acquire_cred.$(OBJEXT)
 	-rm -f mech/gss_acquire_cred.lo
+	-rm -f mech/gss_acquire_cred_ext.$(OBJEXT)
+	-rm -f mech/gss_acquire_cred_ext.lo
+	-rm -f mech/gss_acquire_cred_with_password.$(OBJEXT)
+	-rm -f mech/gss_acquire_cred_with_password.lo
 	-rm -f mech/gss_add_cred.$(OBJEXT)
 	-rm -f mech/gss_add_cred.lo
+	-rm -f mech/gss_add_cred_with_password.$(OBJEXT)
+	-rm -f mech/gss_add_cred_with_password.lo
 	-rm -f mech/gss_add_oid_set_member.$(OBJEXT)
 	-rm -f mech/gss_add_oid_set_member.lo
+	-rm -f mech/gss_aeap.$(OBJEXT)
+	-rm -f mech/gss_aeap.lo
+	-rm -f mech/gss_authorize_localname.$(OBJEXT)
+	-rm -f mech/gss_authorize_localname.lo
 	-rm -f mech/gss_buffer_set.$(OBJEXT)
 	-rm -f mech/gss_buffer_set.lo
 	-rm -f mech/gss_canonicalize_name.$(OBJEXT)
@@ -1141,12 +1443,18 @@
 	-rm -f mech/gss_context_time.lo
 	-rm -f mech/gss_create_empty_oid_set.$(OBJEXT)
 	-rm -f mech/gss_create_empty_oid_set.lo
+	-rm -f mech/gss_cred.$(OBJEXT)
+	-rm -f mech/gss_cred.lo
 	-rm -f mech/gss_decapsulate_token.$(OBJEXT)
 	-rm -f mech/gss_decapsulate_token.lo
+	-rm -f mech/gss_delete_name_attribute.$(OBJEXT)
+	-rm -f mech/gss_delete_name_attribute.lo
 	-rm -f mech/gss_delete_sec_context.$(OBJEXT)
 	-rm -f mech/gss_delete_sec_context.lo
 	-rm -f mech/gss_display_name.$(OBJEXT)
 	-rm -f mech/gss_display_name.lo
+	-rm -f mech/gss_display_name_ext.$(OBJEXT)
+	-rm -f mech/gss_display_name_ext.lo
 	-rm -f mech/gss_display_status.$(OBJEXT)
 	-rm -f mech/gss_display_status.lo
 	-rm -f mech/gss_duplicate_name.$(OBJEXT)
@@ -1157,10 +1465,14 @@
 	-rm -f mech/gss_encapsulate_token.lo
 	-rm -f mech/gss_export_name.$(OBJEXT)
 	-rm -f mech/gss_export_name.lo
+	-rm -f mech/gss_export_name_composite.$(OBJEXT)
+	-rm -f mech/gss_export_name_composite.lo
 	-rm -f mech/gss_export_sec_context.$(OBJEXT)
 	-rm -f mech/gss_export_sec_context.lo
 	-rm -f mech/gss_get_mic.$(OBJEXT)
 	-rm -f mech/gss_get_mic.lo
+	-rm -f mech/gss_get_name_attribute.$(OBJEXT)
+	-rm -f mech/gss_get_name_attribute.lo
 	-rm -f mech/gss_import_name.$(OBJEXT)
 	-rm -f mech/gss_import_name.lo
 	-rm -f mech/gss_import_sec_context.$(OBJEXT)
@@ -1179,6 +1491,8 @@
 	-rm -f mech/gss_inquire_cred_by_oid.lo
 	-rm -f mech/gss_inquire_mechs_for_name.$(OBJEXT)
 	-rm -f mech/gss_inquire_mechs_for_name.lo
+	-rm -f mech/gss_inquire_name.$(OBJEXT)
+	-rm -f mech/gss_inquire_name.lo
 	-rm -f mech/gss_inquire_names_for_mech.$(OBJEXT)
 	-rm -f mech/gss_inquire_names_for_mech.lo
 	-rm -f mech/gss_inquire_sec_context_by_oid.$(OBJEXT)
@@ -1187,12 +1501,18 @@
 	-rm -f mech/gss_krb5.lo
 	-rm -f mech/gss_mech_switch.$(OBJEXT)
 	-rm -f mech/gss_mech_switch.lo
+	-rm -f mech/gss_mo.$(OBJEXT)
+	-rm -f mech/gss_mo.lo
 	-rm -f mech/gss_names.$(OBJEXT)
 	-rm -f mech/gss_names.lo
+	-rm -f mech/gss_oid.$(OBJEXT)
+	-rm -f mech/gss_oid.lo
 	-rm -f mech/gss_oid_equal.$(OBJEXT)
 	-rm -f mech/gss_oid_equal.lo
 	-rm -f mech/gss_oid_to_str.$(OBJEXT)
 	-rm -f mech/gss_oid_to_str.lo
+	-rm -f mech/gss_pname_to_uid.$(OBJEXT)
+	-rm -f mech/gss_pname_to_uid.lo
 	-rm -f mech/gss_process_context_token.$(OBJEXT)
 	-rm -f mech/gss_process_context_token.lo
 	-rm -f mech/gss_pseudo_random.$(OBJEXT)
@@ -1211,10 +1531,14 @@
 	-rm -f mech/gss_seal.lo
 	-rm -f mech/gss_set_cred_option.$(OBJEXT)
 	-rm -f mech/gss_set_cred_option.lo
+	-rm -f mech/gss_set_name_attribute.$(OBJEXT)
+	-rm -f mech/gss_set_name_attribute.lo
 	-rm -f mech/gss_set_sec_context_option.$(OBJEXT)
 	-rm -f mech/gss_set_sec_context_option.lo
 	-rm -f mech/gss_sign.$(OBJEXT)
 	-rm -f mech/gss_sign.lo
+	-rm -f mech/gss_store_cred.$(OBJEXT)
+	-rm -f mech/gss_store_cred.lo
 	-rm -f mech/gss_test_oid_set_member.$(OBJEXT)
 	-rm -f mech/gss_test_oid_set_member.lo
 	-rm -f mech/gss_unseal.$(OBJEXT)
@@ -1243,12 +1567,12 @@
 	-rm -f ntlm/compare_name.lo
 	-rm -f ntlm/context_time.$(OBJEXT)
 	-rm -f ntlm/context_time.lo
+	-rm -f ntlm/creds.$(OBJEXT)
+	-rm -f ntlm/creds.lo
 	-rm -f ntlm/crypto.$(OBJEXT)
 	-rm -f ntlm/crypto.lo
 	-rm -f ntlm/delete_sec_context.$(OBJEXT)
 	-rm -f ntlm/delete_sec_context.lo
-	-rm -f ntlm/digest.$(OBJEXT)
-	-rm -f ntlm/digest.lo
 	-rm -f ntlm/display_name.$(OBJEXT)
 	-rm -f ntlm/display_name.lo
 	-rm -f ntlm/display_status.$(OBJEXT)
@@ -1271,14 +1595,18 @@
 	-rm -f ntlm/init_sec_context.lo
 	-rm -f ntlm/inquire_context.$(OBJEXT)
 	-rm -f ntlm/inquire_context.lo
-	-rm -f ntlm/inquire_cred.$(OBJEXT)
-	-rm -f ntlm/inquire_cred.lo
 	-rm -f ntlm/inquire_cred_by_mech.$(OBJEXT)
 	-rm -f ntlm/inquire_cred_by_mech.lo
 	-rm -f ntlm/inquire_mechs_for_name.$(OBJEXT)
 	-rm -f ntlm/inquire_mechs_for_name.lo
 	-rm -f ntlm/inquire_names_for_mech.$(OBJEXT)
 	-rm -f ntlm/inquire_names_for_mech.lo
+	-rm -f ntlm/inquire_sec_context_by_oid.$(OBJEXT)
+	-rm -f ntlm/inquire_sec_context_by_oid.lo
+	-rm -f ntlm/iter_cred.$(OBJEXT)
+	-rm -f ntlm/iter_cred.lo
+	-rm -f ntlm/kdc.$(OBJEXT)
+	-rm -f ntlm/kdc.lo
 	-rm -f ntlm/process_context_token.$(OBJEXT)
 	-rm -f ntlm/process_context_token.lo
 	-rm -f ntlm/release_cred.$(OBJEXT)
@@ -1301,14 +1629,211 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_ContextFlags.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_GSSAPIContextToken.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_MechType.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_MechTypeList.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_NegHints.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_NegTokenInit.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_NegTokenInitWin.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_NegTokenResp.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_NegotiationToken.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_NegotiationTokenWin.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gkrb5_err.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gss-commands.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/gsstool.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_acquire_cred.Po at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_common.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_context.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_cred.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_kcred.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_names.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_ntlm.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_oid.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/8003.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/accept_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/acquire_cred.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/add_cred.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/address_to_krb5addr.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/aeap.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/arcfour.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/authorize_localname.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/canonicalize_name.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/ccache_name.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/cfx.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/compare_name.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/compat.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/context_time.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/copy_ccache.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/creds.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/decapsulate.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/delete_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/display_name.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/display_status.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/duplicate_name.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/encapsulate.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/export_name.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/export_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/external.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/get_mic.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/import_name.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/import_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/indicate_mechs.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/init.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/init_sec_context.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/inquire_context.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/inquire_cred.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/inquire_cred_by_mech.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/inquire_cred_by_oid.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/inquire_mechs_for_name=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/inquire_names_for_mech=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/inquire_sec_context_by=
_oid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/pname_to_uid.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/prf.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/process_context_token.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/release_buffer.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/release_cred.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/release_name.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/sequence.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/set_cred_option.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/set_sec_context_option=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/store_cred.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/test_cfx.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/ticket_flags.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/unwrap.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/verify_mic.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at krb5/$(DEPDIR)/wrap.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/context.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/doxygen.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_accept_sec_context=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_acquire_cred.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_acquire_cred_ext.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_acquire_cred_with_=
password.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_add_cred.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_add_cred_with_pass=
word.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_add_oid_set_member=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_aeap.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_authorize_localnam=
e.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_buffer_set.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_canonicalize_name.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_compare_name.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_context_time.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_create_empty_oid_s=
et.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_cred.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_decapsulate_token.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_delete_name_attrib=
ute.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_delete_sec_context=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_display_name.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_display_name_ext.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_display_status.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_duplicate_name.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_duplicate_oid.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_encapsulate_token.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_export_name.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_export_name_compos=
ite.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_export_sec_context=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_get_mic.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_get_name_attribute=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_import_name.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_import_sec_context=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_indicate_mechs.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_init_sec_context.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_context.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_cred.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_cred_by_me=
ch.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_cred_by_oi=
d.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_mechs_for_=
name.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_name.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_names_for_=
mech.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_inquire_sec_contex=
t_by_oid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_krb5.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_mech_switch.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_mo.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_names.Plo at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_oid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_oid_equal.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_oid_to_str.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_pname_to_uid.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_process_context_to=
ken.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_pseudo_random.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_release_buffer.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_release_cred.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_release_name.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_release_oid.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_release_oid_set.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_seal.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_set_cred_option.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_set_name_attribute=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_set_sec_context_op=
tion.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_sign.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_store_cred.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_test_oid_set_membe=
r.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_unseal.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_unwrap.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_utils.Plo at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_verify.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_verify_mic.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_wrap.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at mech/$(DEPDIR)/gss_wrap_size_limit.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/accept_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/acquire_cred.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/add_cred.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/canonicalize_name.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/compare_name.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/context_time.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/creds.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/crypto.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/delete_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/display_name.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/display_status.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/duplicate_name.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/export_name.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/export_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/external.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/import_name.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/import_sec_context.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/indicate_mechs.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/init_sec_context.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/inquire_context.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/inquire_cred_by_mech.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/inquire_mechs_for_name=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/inquire_names_for_mech=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/inquire_sec_context_by=
_oid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/iter_cred.Plo at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/kdc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/process_context_token.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/release_cred.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ntlm/$(DEPDIR)/release_name.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at spnego/$(DEPDIR)/accept_sec_context.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at spnego/$(DEPDIR)/compat.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at spnego/$(DEPDIR)/context_stubs.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at spnego/$(DEPDIR)/cred_stubs.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at spnego/$(DEPDIR)/external.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at spnego/$(DEPDIR)/init_sec_context.Plo=
@am__quote@
+
 .c.o:
-	$(COMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	depbase=3D`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.=
o$$||'`;\
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ =
$< &&\
+ at am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c -o $@ $<
=20
 .c.obj:
-	$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	depbase=3D`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.=
obj$$||'`;\
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ =
`$(CYGPATH_W) '$<'` &&\
+ at am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	depbase=3D`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.=
lo$$||'`;\
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $=
@ $< &&\
+ at am__fastdepCC_TRUE@	$(am__mv) $$depbase.Tpo $$depbase.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -1319,202 +1844,203 @@
 	-rm -rf mech/.libs mech/_libs
 	-rm -rf ntlm/.libs ntlm/_libs
 	-rm -rf spnego/.libs spnego/_libs
-install-man3: $(man3_MANS) $(man_MANS)
+install-man3: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man3dir)" || $(MKDIR_P) "$(DESTDIR)$(man3dir)"
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man3:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
-install-man5: $(man5_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man3dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man3dir)" && rm -f $$files; }
+install-man5: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man5dir)" || $(MKDIR_P) "$(DESTDIR)$(man5dir)"
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man5:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man5dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man5dir)" && rm -f $$files; }
 install-includeHEADERS: $(include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'=
"; \
-	  $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-nobase_includeHEADERS: $(nobase_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@$(am__vpath_adj_setup) \
-	list=3D'$(nobase_include_HEADERS)'; for p in $$list; do \
-	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  $(am__vpath_adj) \
-	  echo " $(nobase_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedi=
r)/$$f'"; \
-	  $(nobase_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"=
; \
+	@list=3D'$(nobase_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	$(am__nobase_list) | while read dir files; do \
+	  xfiles=3D; for file in $$files; do \
+	    if test -f "$$file"; then xfiles=3D"$$xfiles $$file"; \
+	    else xfiles=3D"$$xfiles $(srcdir)/$$file"; fi; done; \
+	  test -z "$$xfiles" || { \
+	    test "x$$dir" =3D x. || { \
+	      echo "$(MKDIR_P) '$(DESTDIR)$(includedir)/$$dir'"; \
+	      $(MKDIR_P) "$(DESTDIR)$(includedir)/$$dir"; }; \
+	    echo " $(INSTALL_HEADER) $$xfiles '$(DESTDIR)$(includedir)/$$dir'"; \
+	    $(INSTALL_HEADER) $$xfiles "$(DESTDIR)$(includedir)/$$dir" || exit $$=
?; }; \
 	done
=20
 uninstall-nobase_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@$(am__vpath_adj_setup) \
-	list=3D'$(nobase_include_HEADERS)'; for p in $$list; do \
-	  $(am__vpath_adj) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(nobase_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	$(am__nobase_strip_setup); files=3D`$(am__nobase_strip)`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-nodist_gssapiHEADERS: $(nodist_gssapi_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(gssapidir)" || $(MKDIR_P) "$(DESTDIR)$(gssapidir)"
-	@list=3D'$(nodist_gssapi_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_gssapi_HEADERS)'; test -n "$(gssapidir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_gssapiHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(gssapidir)=
/$$f'"; \
-	  $(nodist_gssapiHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(gssapidir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(gssapidir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(gssapidir)" || exit $$?; \
 	done
=20
 uninstall-nodist_gssapiHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_gssapi_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(gssapidir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(gssapidir)/$$f"; \
-	done
+	@list=3D'$(nodist_gssapi_HEADERS)'; test -n "$(gssapidir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(gssapidir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(gssapidir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -1523,49 +2049,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -1576,15 +2116,32 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -1600,13 +2157,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -1648,9 +2209,14 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
+	-rm -f krb5/$(DEPDIR)/$(am__dirstamp)
 	-rm -f krb5/$(am__dirstamp)
+	-rm -f mech/$(DEPDIR)/$(am__dirstamp)
 	-rm -f mech/$(am__dirstamp)
+	-rm -f ntlm/$(DEPDIR)/$(am__dirstamp)
 	-rm -f ntlm/$(am__dirstamp)
+	-rm -f spnego/$(DEPDIR)/$(am__dirstamp)
 	-rm -f spnego/$(am__dirstamp)
=20
 maintainer-clean-generic:
@@ -1664,6 +2230,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR) krb5/$(DEPDIR) mech/$(DEPDIR) ntlm/$(DEPDIR) spnego/$=
(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -1674,6 +2241,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -1682,26 +2251,35 @@
 	install-nobase_includeHEADERS install-nodist_gssapiHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man3 install-man5
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR) krb5/$(DEPDIR) mech/$(DEPDIR) ntlm/$(DEPDIR) spnego/$=
(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -1723,11 +2301,10 @@
 	uninstall-nobase_includeHEADERS uninstall-nodist_gssapiHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man3 uninstall-man5
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: all check check-am install install-am install-data-am \
+	install-exec-am install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
 	check-local clean clean-binPROGRAMS clean-checkPROGRAMS \
@@ -1821,6 +2398,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1906,7 +2486,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1923,20 +2503,19 @@
 $(srcdir)/ntlm/ntlm-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p ntlm/ntlm-pr=
ivate.h $(ntlmsrc) || rm -f ntlm/ntlm-private.h
=20
-$(libgssapi_la_OBJECTS): $(srcdir)/krb5/gsskrb5-private.h
-$(libgssapi_la_OBJECTS): $(srcdir)/spnego/spnego-private.h
-$(libgssapi_la_OBJECTS): $(srcdir)/ntlm/ntlm-private.h
+$(libgssapi_la_OBJECTS): $(BUILTHEADERS)
+$(test_context_OBJECTS): $(BUILTHEADERS)
=20
 $(libgssapi_la_OBJECTS): $(srcdir)/version-script.map
=20
-$(spnego_files) spnego_asn1.h: spnego_asn1_files
-$(gssapi_files) gssapi_asn1.h: gssapi_asn1_files
+$(spnego_files) spnego_asn1.hx spnego_asn1-priv.hx: spnego_asn1_files
+$(gssapi_files) gssapi_asn1.hx gssapi_asn1-priv.hx: gssapi_asn1_files
=20
-spnego_asn1_files: ../asn1/asn1_compile$(EXEEXT) $(srcdir)/spnego/spnego.a=
sn1
-	../asn1/asn1_compile$(EXEEXT) --sequence=3DMechTypeList $(srcdir)/spnego/=
spnego.asn1 spnego_asn1
+spnego_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/spnego/spnego.asn1 $(srcd=
ir)/spnego/spnego.opt
+	$(ASN1_COMPILE) --option-file=3D$(srcdir)/spnego/spnego.opt $(srcdir)/spn=
ego/spnego.asn1 spnego_asn1
=20
-gssapi_asn1_files: ../asn1/asn1_compile$(EXEEXT) $(srcdir)/mech/gssapi.asn1
-	../asn1/asn1_compile$(EXEEXT) $(srcdir)/mech/gssapi.asn1 gssapi_asn1
+gssapi_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/mech/gssapi.asn1
+	$(ASN1_COMPILE) $(srcdir)/mech/gssapi.asn1 gssapi_asn1
=20
 $(srcdir)/krb5/gsskrb5-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5/gsskrb5=
-private.h $(krb5src) || rm -f krb5/gsskrb5-private.h
@@ -1947,14 +2526,19 @@
 gss-commands.c gss-commands.h: gss-commands.in
 	$(SLC) $(srcdir)/gss-commands.in
=20
-$(gss_OBJECTS): gss-commands.h
+$(gsstool_OBJECTS): gss-commands.h
=20
-# to help stupid solaris make
-
-$(libgssapi_la_OBJECTS): gkrb5_err.h gssapi_asn1.h spnego_asn1.h
+$(libgssapi_la_OBJECTS): gkrb5_err.h gssapi_asn1.h gssapi_asn1-priv.h
+$(libgssapi_la_OBJECTS): spnego_asn1.h spnego_asn1-priv.h
+$(libgssapi_la_OBJECTS): $(srcdir)/gssapi/gssapi_oid.h
=20
 gkrb5_err.h gkrb5_err.c: $(srcdir)/krb5/gkrb5_err.et
 	$(COMPILE_ET) $(srcdir)/krb5/gkrb5_err.et
+
+$(srcdir)/gssapi/gssapi_oid.h $(srcdir)/mech/gss_oid.c:
+	perl $(srcdir)/gen-oid.pl -b base -h $(srcdir)/oid.txt > $(srcdir)/gssapi=
/gssapi_oid.h
+	perl $(srcdir)/gen-oid.pl -b base $(srcdir)/oid.txt > $(srcdir)/mech/gss_=
oid.c
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gss-com=
mands.in
--- a/head/crypto/heimdal/lib/gssapi/gss-commands.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gss-commands.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).=20
  * All rights reserved.=20
  *
@@ -30,13 +30,26 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
  * SUCH DAMAGE.=20
  */
-/* $Id: gss-commands.in 17870 2006-07-22 14:48:58Z lha $ */
+/* $Id$ */
=20
 command =3D {
 	name =3D "supported-mechanisms"
 	help =3D "Print the supported mechanisms"
 }
 command =3D {
+	name =3D "attrs-for-mech"
+	help =3D "Print the attributes for mechs"
+	option =3D {
+		long =3D "all"
+		type =3D "flag"
+	}
+	option =3D {
+		long =3D "mech"
+		type =3D "string"
+		argument =3D "mechanism"
+	}
+}
+command =3D {
 	name =3D "help"
 	name =3D "?"
 	argument =3D "[command]"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gss_acq=
uire_cred.3
--- a/head/crypto/heimdal/lib/gssapi/gss_acquire_cred.3	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gss_acquire_cred.3	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: gss_acquire_cred.3 20235 2007-02-16 11:19:03Z lha $
+.\" $Id$
 .\"
 .Dd October 26, 2005
 .Dt GSS_ACQUIRE_CRED 3
@@ -513,7 +513,7 @@
 .Dv gss_buffer_t .
 .Pp
 Exported names also have the property that they are specified by the
-mechanism itself and compatible between diffrent GSS-API
+mechanism itself and compatible between different GSS-API
 implementations.
 .El
 .Sh ACCESS CONTROL
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gssapi.3
--- a/head/crypto/heimdal/lib/gssapi/gssapi.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gssapi.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 2003 - 2005 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2003 - 2005 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: gssapi.3 22071 2007-11-14 20:04:50Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .\"
 .Dd April 20, 2005
 .Dt GSSAPI 3
@@ -53,57 +53,52 @@
 .Em libgssapi .
 Declarations for these functions may be obtained from the include file
 .Pa gssapi.h .
-.sp 2
-.nf
-.ta \w'gss_inquire_names_for_mech'u+2n +\w'Description goes here'u
-\fIName/Page\fP	\fIDescription\fP
-.ta \w'gss_inquire_names_for_mech'u+2n +\w'Description goes here'u+6nC
-.sp 5p
-gss_accept_sec_context.3
-gss_acquire_cred.3
-gss_add_cred.3
-gss_add_oid_set_member.3
-gss_canonicalize_name.3
-gss_compare_name.3
-gss_context_time.3
-gss_create_empty_oid_set.3
-gss_delete_sec_context.3
-gss_display_name.3
-gss_display_status.3
-gss_duplicate_name.3
-gss_export_name.3
-gss_export_sec_context.3
-gss_get_mic.3
-gss_import_name.3
-gss_import_sec_context.3
-gss_indicate_mechs.3
-gss_init_sec_context.3
-gss_inquire_context.3
-gss_inquire_cred.3
-gss_inquire_cred_by_mech.3
-gss_inquire_mechs_for_name.3
-gss_inquire_names_for_mech.3
-gss_krb5_ccache_name.3
-gss_krb5_compat_des3_mic.3
-gss_krb5_copy_ccache.3
-gss_krb5_extract_authz_data_from_sec_context.3
-gss_krb5_import_ccache.3
-gss_process_context_token.3
-gss_release_buffer.3
-gss_release_cred.3
-gss_release_name.3
-gss_release_oid_set.3
-gss_seal.3
-gss_sign.3
-gss_test_oid_set_member.3
-gss_unseal.3
-gss_unwrap.3
-gss_verify.3
-gss_verify_mic.3
-gss_wrap.3
-gss_wrap_size_limit.3
-.ta
-.Fi
+.Bl -column -compact
+.It Sy Name/Page
+.It Xr gss_accept_sec_context 3
+.It Xr gss_acquire_cred 3
+.It Xr gss_add_cred 3
+.It Xr gss_add_oid_set_member 3
+.It Xr gss_canonicalize_name 3
+.It Xr gss_compare_name 3
+.It Xr gss_context_time 3
+.It Xr gss_create_empty_oid_set 3
+.It Xr gss_delete_sec_context 3
+.It Xr gss_display_name 3
+.It Xr gss_display_status 3
+.It Xr gss_duplicate_name 3
+.It Xr gss_export_name 3
+.It Xr gss_export_sec_context 3
+.It Xr gss_get_mic 3
+.It Xr gss_import_name 3
+.It Xr gss_import_sec_context 3
+.It Xr gss_indicate_mechs 3
+.It Xr gss_init_sec_context 3
+.It Xr gss_inquire_context 3
+.It Xr gss_inquire_cred 3
+.It Xr gss_inquire_cred_by_mech 3
+.It Xr gss_inquire_mechs_for_name 3
+.It Xr gss_inquire_names_for_mech 3
+.It Xr gss_krb5_ccache_name 3
+.It Xr gss_krb5_compat_des3_mic 3
+.It Xr gss_krb5_copy_ccache 3
+.It Xr gss_krb5_extract_authz_data_from_sec_context 3
+.It Xr gss_krb5_import_ccache 3
+.It Xr gss_process_context_token 3
+.It Xr gss_release_buffer 3
+.It Xr gss_release_cred 3
+.It Xr gss_release_name 3
+.It Xr gss_release_oid_set 3
+.It Xr gss_seal 3
+.It Xr gss_sign 3
+.It Xr gss_test_oid_set_member 3
+.It Xr gss_unseal 3
+.It Xr gss_unwrap 3
+.It Xr gss_verify 3
+.It Xr gss_verify_mic 3
+.It Xr gss_wrap 3
+.It Xr gss_wrap_size_limit 3
+.El
 .Sh COMPATIBILITY
 The
 .Nm Heimdal
@@ -147,7 +142,7 @@
 .Pp
 This config option modifies behaviour for both clients and servers.
 .Pp
-Microsoft implemented SPNEGO to Windows2000, however, they manage to
+Microsoft implemented SPNEGO to Windows2000, however, they managed to
 get it wrong, their implementation didn't fill in the MechListMIC in
 the reply token with the right content.
 There is a work around for this problem, but not all implementation
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gssapi.h
--- a/head/crypto/heimdal/lib/gssapi/gssapi.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gssapi.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: gssapi.h 18332 2006-10-07 20:57:15Z lha $ */
+/* $Id$ */
=20
 #ifndef GSSAPI_H_
 #define GSSAPI_H_
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gssapi/=
gssapi.h
--- a/head/crypto/heimdal/lib/gssapi/gssapi/gssapi.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gssapi/gssapi.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,38 +1,36 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: gssapi.h 21004 2007-06-08 01:53:10Z lha $ */
-
 #ifndef GSSAPI_GSSAPI_H_
 #define GSSAPI_GSSAPI_H_
=20
@@ -43,6 +41,45 @@
=20
 #include <krb5-types.h>
=20
+#ifndef BUILD_GSSAPI_LIB
+#if defined(_WIN32)
+#define GSSAPI_LIB_FUNCTION __declspec(dllimport)
+#define GSSAPI_LIB_CALL     __stdcall
+#define GSSAPI_LIB_VARIABLE __declspec(dllimport)
+#else
+#define GSSAPI_LIB_FUNCTION
+#define GSSAPI_LIB_CALL
+#define GSSAPI_LIB_VARIABLE
+#endif
+#endif
+
+#ifndef GSSAPI_DEPRECATED_FUNCTION
+#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ =3D=3D 3) && (__GNU=
C_MINOR__ >=3D 1 )))
+#define GSSAPI_DEPRECATED_FUNCTION(X) __attribute__((deprecated))
+#else
+#define GSSAPI_DEPRECATED_FUNCTION(X)
+#endif
+#endif
+
+/* Compatiblity with MIT Kerberos on the Mac */
+#if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defin=
ed(__i386__) || defined(__x86_64__))
+#pragma pack(push,2)
+#endif
+
+#ifdef __cplusplus
+#define GSSAPI_CPP_START	extern "C" {
+#define GSSAPI_CPP_END		}
+#else
+#define GSSAPI_CPP_START
+#define GSSAPI_CPP_END
+#endif
+
+#ifdef _WIN32
+#define GSSAPI_CALLCONV __stdcall
+#else
+#define GSSAPI_CALLCONV
+#endif
+
 /*
  * Now define the three implementation-dependent types.
  */
@@ -54,29 +91,35 @@
=20
 struct gss_name_t_desc_struct;
 typedef struct gss_name_t_desc_struct *gss_name_t;
+typedef const struct gss_name_t_desc_struct *gss_const_name_t;
=20
 struct gss_ctx_id_t_desc_struct;
 typedef struct gss_ctx_id_t_desc_struct *gss_ctx_id_t;
+typedef const struct gss_ctx_id_t_desc_struct gss_const_ctx_id_t;
=20
 typedef struct gss_OID_desc_struct {
       OM_uint32 length;
       void      *elements;
 } gss_OID_desc, *gss_OID;
+typedef const gss_OID_desc * gss_const_OID;
=20
 typedef struct gss_OID_set_desc_struct  {
       size_t     count;
       gss_OID    elements;
 } gss_OID_set_desc, *gss_OID_set;
+typedef const gss_OID_set_desc * gss_const_OID_set;
=20
 typedef int gss_cred_usage_t;
=20
 struct gss_cred_id_t_desc_struct;
 typedef struct gss_cred_id_t_desc_struct *gss_cred_id_t;
+typedef const struct gss_cred_id_t_desc_struct *gss_const_cred_id_t;
=20
 typedef struct gss_buffer_desc_struct {
       size_t length;
       void *value;
 } gss_buffer_desc, *gss_buffer_t;
+typedef const gss_buffer_desc * gss_const_buffer_t;
=20
 typedef struct gss_channel_bindings_struct {
       OM_uint32 initiator_addrtype;
@@ -85,6 +128,7 @@
       gss_buffer_desc acceptor_address;
       gss_buffer_desc application_data;
 } *gss_channel_bindings_t;
+typedef const struct gss_channel_bindings_struct *gss_const_channel_bindin=
gs_t;
=20
 /* GGF extension data types */
 typedef struct gss_buffer_set_desc_struct {
@@ -92,11 +136,18 @@
       gss_buffer_desc *elements;
 } gss_buffer_set_desc, *gss_buffer_set_t;
=20
+typedef struct gss_iov_buffer_desc_struct {
+    OM_uint32 type;
+    gss_buffer_desc buffer;
+} gss_iov_buffer_desc, *gss_iov_buffer_t;
+
 /*
  * For now, define a QOP-type as an OM_uint32
  */
 typedef OM_uint32 gss_qop_t;
=20
+
+
 /*
  * Flag bits for context-level services.
  */
@@ -113,6 +164,7 @@
 #define GSS_C_DCE_STYLE 4096
 #define GSS_C_IDENTIFY_FLAG 8192
 #define GSS_C_EXTENDED_ERROR_FLAG 16384
+#define GSS_C_DELEG_POLICY_FLAG 32768
=20
 /*
  * Credential usage options
@@ -167,6 +219,7 @@
 #define GSS_C_NO_CREDENTIAL ((gss_cred_id_t) 0)
 #define GSS_C_NO_CHANNEL_BINDINGS ((gss_channel_bindings_t) 0)
 #define GSS_C_EMPTY_BUFFER {0, NULL}
+#define GSS_C_NO_IOV_BUFFER ((gss_iov_buffer_t)0)
=20
 /*
  * Some alternate names for a couple of the above
@@ -195,9 +248,33 @@
  */
 #define GSS_C_INDEFINITE 0xfffffffful
=20
-#ifdef __cplusplus
-extern "C" {
-#endif
+/*
+ * Type of gss_wrap_iov()/gss_unwrap_iov().
+ */
+
+#define GSS_IOV_BUFFER_TYPE_EMPTY 0
+#define GSS_IOV_BUFFER_TYPE_DATA 1
+#define GSS_IOV_BUFFER_TYPE_HEADER 2
+#define GSS_IOV_BUFFER_TYPE_MECH_PARAMS 3
+
+#define GSS_IOV_BUFFER_TYPE_TRAILER 7
+#define GSS_IOV_BUFFER_TYPE_PADDING 9
+#define GSS_IOV_BUFFER_TYPE_STREAM 10
+#define GSS_IOV_BUFFER_TYPE_SIGN_ONLY 11
+
+#define GSS_IOV_BUFFER_TYPE_FLAG_MASK		0xffff0000
+#define GSS_IOV_BUFFER_FLAG_ALLOCATE		0x00010000
+#define GSS_IOV_BUFFER_FLAG_ALLOCATED		0x00020000
+
+#define GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATE	0x00010000 /* old name */
+#define GSS_IOV_BUFFER_TYPE_FLAG_ALLOCATED	0x00020000 /* old name */
+
+#define GSS_IOV_BUFFER_TYPE(_t) ((_t) & ~GSS_IOV_BUFFER_TYPE_FLAG_MASK)
+#define GSS_IOV_BUFFER_FLAGS(_t) ((_t) & GSS_IOV_BUFFER_TYPE_FLAG_MASK)
+
+GSSAPI_CPP_START
+
+#include <gssapi/gssapi_oid.h>
=20
 /*
  * The implementation must reserve static storage for a
@@ -210,7 +287,8 @@
  * GSS_C_NT_USER_NAME should be initialized to point
  * to that gss_OID_desc.
  */
-extern gss_OID GSS_C_NT_USER_NAME;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_user_name_oid_desc;
+#define GSS_C_NT_USER_NAME (&__gss_c_nt_user_name_oid_desc)
=20
 /*
  * The implementation must reserve static storage for a
@@ -223,7 +301,8 @@
  * The constant GSS_C_NT_MACHINE_UID_NAME should be
  * initialized to point to that gss_OID_desc.
  */
-extern gss_OID GSS_C_NT_MACHINE_UID_NAME;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_machine_uid_name_oid_de=
sc;
+#define GSS_C_NT_MACHINE_UID_NAME (&__gss_c_nt_machine_uid_name_oid_desc)
=20
 /*
  * The implementation must reserve static storage for a
@@ -236,7 +315,8 @@
  * The constant GSS_C_NT_STRING_UID_NAME should be
  * initialized to point to that gss_OID_desc.
  */
-extern gss_OID GSS_C_NT_STRING_UID_NAME;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_string_uid_name_oid_des=
c;
+#define GSS_C_NT_STRING_UID_NAME (&__gss_c_nt_string_uid_name_oid_desc)
=20
 /*
  * The implementation must reserve static storage for a
@@ -255,7 +335,8 @@
  * parameter, but should not be emitted by GSS-API
  * implementations
  */
-extern gss_OID GSS_C_NT_HOSTBASED_SERVICE_X;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_hostbased_service_x_oid=
_desc;
+#define GSS_C_NT_HOSTBASED_SERVICE_X (&__gss_c_nt_hostbased_service_x_oid_=
desc)
=20
 /*
  * The implementation must reserve static storage for a
@@ -268,7 +349,8 @@
  * GSS_C_NT_HOSTBASED_SERVICE should be initialized
  * to point to that gss_OID_desc.
  */
-extern gss_OID GSS_C_NT_HOSTBASED_SERVICE;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_hostbased_service_oid_d=
esc;
+#define GSS_C_NT_HOSTBASED_SERVICE (&__gss_c_nt_hostbased_service_oid_desc)
=20
 /*
  * The implementation must reserve static storage for a
@@ -280,7 +362,8 @@
  * and GSS_C_NT_ANONYMOUS should be initialized to point
  * to that gss_OID_desc.
  */
-extern gss_OID GSS_C_NT_ANONYMOUS;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_anonymous_oid_desc;
+#define GSS_C_NT_ANONYMOUS (&__gss_c_nt_anonymous_oid_desc)
=20
 /*
  * The implementation must reserve static storage for a
@@ -292,19 +375,8 @@
  * GSS_C_NT_EXPORT_NAME should be initialized to point
  * to that gss_OID_desc.
  */
-extern gss_OID GSS_C_NT_EXPORT_NAME;
-
-/*
- * Digest mechanism
- */
-
-extern gss_OID GSS_SASL_DIGEST_MD5_MECHANISM;
-
-/*
- * NTLM mechanism
- */
-
-extern gss_OID GSS_NTLM_MECHANISM;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_c_nt_export_name_oid_desc;
+#define GSS_C_NT_EXPORT_NAME (&__gss_c_nt_export_name_oid_desc)
=20
 /* Major status codes */
=20
@@ -373,6 +445,12 @@
 #define GSS_S_UNAVAILABLE (16ul << GSS_C_ROUTINE_ERROR_OFFSET)
 #define GSS_S_DUPLICATE_ELEMENT (17ul << GSS_C_ROUTINE_ERROR_OFFSET)
 #define GSS_S_NAME_NOT_MN (18ul << GSS_C_ROUTINE_ERROR_OFFSET)
+#define GSS_S_BAD_MECH_ATTR (19ul << GSS_C_ROUTINE_ERROR_OFFSET)
+
+/*
+ * Apparently awating spec fix.
+ */
+#define GSS_S_CRED_UNAVAIL GSS_S_FAILURE
=20
 /*
  * Supplementary info bits:
@@ -387,7 +465,10 @@
  * Finally, function prototypes for the GSS-API routines.
  */
=20
-OM_uint32 gss_acquire_cred
+#define GSS_C_OPTION_MASK 0xffff
+#define GSS_C_CRED_NO_UI  0x10000
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred
            (OM_uint32 * /*minor_status*/,
             const gss_name_t /*desired_name*/,
             OM_uint32 /*time_req*/,
@@ -398,12 +479,12 @@
             OM_uint32 * /*time_rec*/
            );
=20
-OM_uint32 gss_release_cred
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_cred
            (OM_uint32 * /*minor_status*/,
             gss_cred_id_t * /*cred_handle*/
            );
=20
-OM_uint32 gss_init_sec_context
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_init_sec_context
            (OM_uint32 * /*minor_status*/,
             const gss_cred_id_t /*initiator_cred_handle*/,
             gss_ctx_id_t * /*context_handle*/,
@@ -419,7 +500,7 @@
             OM_uint32 * /*time_rec*/
            );
=20
-OM_uint32 gss_accept_sec_context
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_accept_sec_context
            (OM_uint32 * /*minor_status*/,
             gss_ctx_id_t * /*context_handle*/,
             const gss_cred_id_t /*acceptor_cred_handle*/,
@@ -433,25 +514,25 @@
             gss_cred_id_t * /*delegated_cred_handle*/
            );
=20
-OM_uint32 gss_process_context_token
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_process_context_token
            (OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             const gss_buffer_t /*token_buffer*/
            );
=20
-OM_uint32 gss_delete_sec_context
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_sec_context
            (OM_uint32 * /*minor_status*/,
             gss_ctx_id_t * /*context_handle*/,
             gss_buffer_t /*output_token*/
            );
=20
-OM_uint32 gss_context_time
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_context_time
            (OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             OM_uint32 * /*time_rec*/
            );
=20
-OM_uint32 gss_get_mic
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_mic
            (OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             gss_qop_t /*qop_req*/,
@@ -459,7 +540,7 @@
             gss_buffer_t /*message_token*/
            );
=20
-OM_uint32 gss_verify_mic
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify_mic
            (OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             const gss_buffer_t /*message_buffer*/,
@@ -467,7 +548,7 @@
             gss_qop_t * /*qop_state*/
            );
=20
-OM_uint32 gss_wrap
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap
            (OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             int /*conf_req_flag*/,
@@ -477,7 +558,7 @@
             gss_buffer_t /*output_message_buffer*/
            );
=20
-OM_uint32 gss_unwrap
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unwrap
            (OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             const gss_buffer_t /*input_message_buffer*/,
@@ -486,7 +567,7 @@
             gss_qop_t * /*qop_state*/
            );
=20
-OM_uint32 gss_display_status
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_status
            (OM_uint32 * /*minor_status*/,
             OM_uint32 /*status_value*/,
             int /*status_type*/,
@@ -495,54 +576,54 @@
             gss_buffer_t /*status_string*/
            );
=20
-OM_uint32 gss_indicate_mechs
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_indicate_mechs
            (OM_uint32 * /*minor_status*/,
             gss_OID_set * /*mech_set*/
            );
=20
-OM_uint32 gss_compare_name
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_compare_name
            (OM_uint32 * /*minor_status*/,
             const gss_name_t /*name1*/,
             const gss_name_t /*name2*/,
             int * /*name_equal*/
            );
=20
-OM_uint32 gss_display_name
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name
            (OM_uint32 * /*minor_status*/,
             const gss_name_t /*input_name*/,
             gss_buffer_t /*output_name_buffer*/,
             gss_OID * /*output_name_type*/
            );
=20
-OM_uint32 gss_import_name
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_name
            (OM_uint32 * /*minor_status*/,
             const gss_buffer_t /*input_name_buffer*/,
             const gss_OID /*input_name_type*/,
             gss_name_t * /*output_name*/
            );
=20
-OM_uint32 gss_export_name
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name
            (OM_uint32  * /*minor_status*/,
             const gss_name_t /*input_name*/,
             gss_buffer_t /*exported_name*/
            );
=20
-OM_uint32 gss_release_name
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_name
            (OM_uint32 * /*minor_status*/,
             gss_name_t * /*input_name*/
            );
=20
-OM_uint32 gss_release_buffer
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_buffer
            (OM_uint32 * /*minor_status*/,
             gss_buffer_t /*buffer*/
            );
=20
-OM_uint32 gss_release_oid_set
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_release_oid_set
            (OM_uint32 * /*minor_status*/,
             gss_OID_set * /*set*/
            );
=20
-OM_uint32 gss_inquire_cred
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred
            (OM_uint32 * /*minor_status*/,
             const gss_cred_id_t /*cred_handle*/,
             gss_name_t * /*name*/,
@@ -551,7 +632,7 @@
             gss_OID_set * /*mechanisms*/
            );
=20
-OM_uint32 gss_inquire_context (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_context (
             OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             gss_name_t * /*src_name*/,
@@ -563,7 +644,7 @@
             int * /*open_context*/
            );
=20
-OM_uint32 gss_wrap_size_limit (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_wrap_size_limit (
             OM_uint32 * /*minor_status*/,
             const gss_ctx_id_t /*context_handle*/,
             int /*conf_req_flag*/,
@@ -572,7 +653,7 @@
             OM_uint32 * /*max_input_size*/
            );
=20
-OM_uint32 gss_add_cred (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred (
             OM_uint32 * /*minor_status*/,
             const gss_cred_id_t /*input_cred_handle*/,
             const gss_name_t /*desired_name*/,
@@ -586,7 +667,7 @@
             OM_uint32 * /*acceptor_time_rec*/
            );
=20
-OM_uint32 gss_inquire_cred_by_mech (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_cred_by_mech (
             OM_uint32 * /*minor_status*/,
             const gss_cred_id_t /*cred_handle*/,
             const gss_OID /*mech_type*/,
@@ -596,80 +677,81 @@
             gss_cred_usage_t * /*cred_usage*/
            );
=20
-OM_uint32 gss_export_sec_context (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_sec_context (
             OM_uint32 * /*minor_status*/,
             gss_ctx_id_t * /*context_handle*/,
             gss_buffer_t /*interprocess_token*/
            );
=20
-OM_uint32 gss_import_sec_context (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_import_sec_context (
             OM_uint32 * /*minor_status*/,
             const gss_buffer_t /*interprocess_token*/,
             gss_ctx_id_t * /*context_handle*/
            );
=20
-OM_uint32 gss_create_empty_oid_set (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_create_empty_oid_set (
             OM_uint32 * /*minor_status*/,
             gss_OID_set * /*oid_set*/
            );
=20
-OM_uint32 gss_add_oid_set_member (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_oid_set_member (
             OM_uint32 * /*minor_status*/,
             const gss_OID /*member_oid*/,
             gss_OID_set * /*oid_set*/
            );
=20
-OM_uint32 gss_test_oid_set_member (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_test_oid_set_member (
             OM_uint32 * /*minor_status*/,
             const gss_OID /*member*/,
             const gss_OID_set /*set*/,
             int * /*present*/
            );
=20
-OM_uint32 gss_inquire_names_for_mech (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_names_for_mech (
             OM_uint32 * /*minor_status*/,
             const gss_OID /*mechanism*/,
             gss_OID_set * /*name_types*/
            );
=20
-OM_uint32 gss_inquire_mechs_for_name (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_mechs_for_name (
             OM_uint32 * /*minor_status*/,
             const gss_name_t /*input_name*/,
             gss_OID_set * /*mech_types*/
            );
=20
-OM_uint32 gss_canonicalize_name (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_canonicalize_name (
             OM_uint32 * /*minor_status*/,
             const gss_name_t /*input_name*/,
             const gss_OID /*mech_type*/,
             gss_name_t * /*output_name*/
            );
=20
-OM_uint32 gss_duplicate_name (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_name (
             OM_uint32 * /*minor_status*/,
             const gss_name_t /*src_name*/,
             gss_name_t * /*dest_name*/
            );
=20
-OM_uint32 gss_duplicate_oid (
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_duplicate_oid (
 	    OM_uint32 * /* minor_status */,
 	    gss_OID /* src_oid */,
 	    gss_OID * /* dest_oid */
            );
-OM_uint32
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_release_oid
 	(OM_uint32 * /*minor_status*/,
 	 gss_OID * /* oid */
 	);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_oid_to_str(
 	    OM_uint32 * /*minor_status*/,
 	    gss_OID /* oid */,
 	    gss_buffer_t /* str */
            );
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_inquire_sec_context_by_oid(
 	    OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
@@ -677,38 +759,38 @@
             gss_buffer_set_t *data_set
            );
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_set_sec_context_option (OM_uint32 *minor_status,
 			    gss_ctx_id_t *context_handle,
 			    const gss_OID desired_object,
 			    const gss_buffer_t value);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_set_cred_option (OM_uint32 *minor_status,
 		     gss_cred_id_t *cred_handle,
 		     const gss_OID object,
 		     const gss_buffer_t value);
=20
-int
-gss_oid_equal(const gss_OID a, const gss_OID b);
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_oid_equal(gss_const_OID a, gss_const_OID b);
=20
-OM_uint32=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_create_empty_buffer_set
 	   (OM_uint32 * minor_status,
 	    gss_buffer_set_t *buffer_set);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_add_buffer_set_member
 	   (OM_uint32 * minor_status,
 	    const gss_buffer_t member_buffer,
 	    gss_buffer_set_t *buffer_set);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_release_buffer_set
 	   (OM_uint32 * minor_status,
 	    gss_buffer_set_t *buffer_set);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_inquire_cred_by_oid(OM_uint32 *minor_status,
 	                const gss_cred_id_t cred_handle,
 	                const gss_OID desired_object,
@@ -721,7 +803,7 @@
 #define GSS_C_PRF_KEY_FULL 0
 #define GSS_C_PRF_KEY_PARTIAL 1
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_pseudo_random
 	(OM_uint32 *minor_status,
 	 gss_ctx_id_t context,
@@ -731,6 +813,41 @@
 	 gss_buffer_t prf_out
 	);
=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_store_cred(OM_uint32         * /* minor_status */,
+	       gss_cred_id_t     /* input_cred_handle */,
+	       gss_cred_usage_t  /* cred_usage */,
+	       const gss_OID     /* desired_mech */,
+	       OM_uint32         /* overwrite_cred */,
+	       OM_uint32         /* default_cred */,
+	       gss_OID_set       * /* elements_stored */,
+	       gss_cred_usage_t  * /* cred_usage_stored */);
+
+
+/*
+ * Query functions
+ */
+
+typedef struct {
+    size_t header; /**< size of header */
+    size_t trailer; /**< size of trailer */
+    size_t max_msg_size; /**< maximum message size */
+    size_t buffers; /**< extra GSS_IOV_BUFFER_TYPE_EMPTY buffer to pass */
+    size_t blocksize; /**< Specificed optimal size of messages, also
+			 is the maximum padding size
+			 (GSS_IOV_BUFFER_TYPE_PADDING) */
+} gss_context_stream_sizes;
+
+extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_attr_stream_sizes_oid_desc;
+#define GSS_C_ATTR_STREAM_SIZES (&__gss_c_attr_stream_sizes_oid_desc)
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_context_query_attributes(OM_uint32 * /* minor_status */,
+			     const gss_ctx_id_t /* context_handle */,
+			     const gss_OID /* attribute */,
+			     void * /*data*/,
+			     size_t /* len */);
 /*
  * The following routines are obsolete variants of gss_get_mic,
  * gss_verify_mic, gss_wrap and gss_unwrap.  They should be
@@ -742,23 +859,23 @@
  * obsolete versions of these routines and their current forms.
  */
=20
-OM_uint32 gss_sign
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_sign
            (OM_uint32 * /*minor_status*/,
             gss_ctx_id_t /*context_handle*/,
             int /*qop_req*/,
             gss_buffer_t /*message_buffer*/,
             gss_buffer_t /*message_token*/
-           );
+	    ) GSSAPI_DEPRECATED_FUNCTION("Use gss_get_mic");
=20
-OM_uint32 gss_verify
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_verify
            (OM_uint32 * /*minor_status*/,
             gss_ctx_id_t /*context_handle*/,
             gss_buffer_t /*message_buffer*/,
             gss_buffer_t /*token_buffer*/,
             int * /*qop_state*/
-           );
+	    ) GSSAPI_DEPRECATED_FUNCTION("Use gss_verify_mic");
=20
-OM_uint32 gss_seal
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_seal
            (OM_uint32 * /*minor_status*/,
             gss_ctx_id_t /*context_handle*/,
             int /*conf_req_flag*/,
@@ -766,44 +883,238 @@
             gss_buffer_t /*input_message_buffer*/,
             int * /*conf_state*/,
             gss_buffer_t /*output_message_buffer*/
-           );
+           ) GSSAPI_DEPRECATED_FUNCTION("Use gss_wrap");
=20
-OM_uint32 gss_unseal
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_unseal
            (OM_uint32 * /*minor_status*/,
             gss_ctx_id_t /*context_handle*/,
             gss_buffer_t /*input_message_buffer*/,
             gss_buffer_t /*output_message_buffer*/,
             int * /*conf_state*/,
             int * /*qop_state*/
+           )  GSSAPI_DEPRECATED_FUNCTION("Use gss_unwrap");
+
+/**
+ *
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_encapsulate_token(gss_const_buffer_t /* input_token */,
+		      gss_const_OID /* oid */,
+		      gss_buffer_t /* output_token */);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_decapsulate_token(gss_const_buffer_t /* input_token */,
+		      gss_const_OID /* oid */,
+		      gss_buffer_t /* output_token */);
+
+
+
+/*
+ * AEAD support
+ */
+
+/*
+ * GSS_IOV
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_iov(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t, int *,
+	     gss_iov_buffer_desc *, int);
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_unwrap_iov(OM_uint32 *, gss_ctx_id_t, int *, gss_qop_t *,
+	       gss_iov_buffer_desc *, int);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_wrap_iov_length(OM_uint32 *, gss_ctx_id_t, int, gss_qop_t, int *,
+		    gss_iov_buffer_desc *, int);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_release_iov_buffer(OM_uint32 *, gss_iov_buffer_desc *, int);
+
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_export_cred(OM_uint32 * /* minor_status */,
+		gss_cred_id_t /* cred_handle */,
+		gss_buffer_t /* cred_token */);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_import_cred(OM_uint32 * /* minor_status */,
+		gss_buffer_t /* cred_token */,
+		gss_cred_id_t * /* cred_handle */);
+
+/*
+ * mech option
+ */
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_mo_set(gss_const_OID mech, gss_const_OID option,
+	   int enable, gss_buffer_t value);
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_mo_get(gss_const_OID mech, gss_const_OID option, gss_buffer_t value);
+
+GSSAPI_LIB_FUNCTION void GSSAPI_LIB_CALL
+gss_mo_list(gss_const_OID mech, gss_OID_set *options);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_mo_name(gss_const_OID mech, gss_const_OID options, gss_buffer_t name);
+
+/*
+ * SASL glue functions and mech inquire
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_saslname_for_mech(OM_uint32 *minor_status,
+			      const gss_OID desired_mech,
+			      gss_buffer_t sasl_mech_name,
+			      gss_buffer_t mech_name,
+			      gss_buffer_t mech_description);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_mech_for_saslname(OM_uint32 *minor_status,
+			      const gss_buffer_t sasl_mech_name,
+			      gss_OID *mech_type);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_indicate_mechs_by_attrs(OM_uint32 * minor_status,
+			    gss_const_OID_set desired_mech_attrs,
+			    gss_const_OID_set except_mech_attrs,
+			    gss_const_OID_set critical_mech_attrs,
+			    gss_OID_set *mechs);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_inquire_attrs_for_mech(OM_uint32 * minor_status,
+			   gss_const_OID mech,
+			   gss_OID_set *mech_attr,
+			   gss_OID_set *known_mech_attrs);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_display_mech_attr(OM_uint32 * minor_status,
+		      gss_const_OID mech_attr,
+		      gss_buffer_t name,
+		      gss_buffer_t short_desc,
+		      gss_buffer_t long_desc);
+
+/*
+ * Solaris compat
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_acquire_cred_with_passwo=
rd
+           (OM_uint32 * /*minor_status*/,
+            const gss_name_t /*desired_name*/,
+            const gss_buffer_t /*password*/,
+            OM_uint32 /*time_req*/,
+            const gss_OID_set /*desired_mechs*/,
+            gss_cred_usage_t /*cred_usage*/,
+            gss_cred_id_t * /*output_cred_handle*/,
+            gss_OID_set * /*actual_mechs*/,
+            OM_uint32 * /*time_rec*/
            );
=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_add_cred_with_password (
+            OM_uint32 * /*minor_status*/,
+            const gss_cred_id_t /*input_cred_handle*/,
+            const gss_name_t /*desired_name*/,
+            const gss_OID /*desired_mech*/,
+            const gss_buffer_t /*password*/,
+            gss_cred_usage_t /*cred_usage*/,
+            OM_uint32 /*initiator_time_req*/,
+            OM_uint32 /*acceptor_time_req*/,
+            gss_cred_id_t * /*output_cred_handle*/,
+            gss_OID_set * /*actual_mechs*/,
+            OM_uint32 * /*initiator_time_rec*/,
+            OM_uint32 * /*acceptor_time_rec*/
+           );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_pname_to_uid(
+        OM_uint32 *minor,
+        const gss_name_t name,
+        const gss_OID mech_type,
+        uid_t *uidOut);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_authorize_localname(
+        OM_uint32 *minor,
+        const gss_name_t name,
+        const gss_name_t user);
+
+GSSAPI_LIB_FUNCTION int GSSAPI_LIB_CALL
+gss_userok(const gss_name_t name,
+           const char *user);
+
+extern GSSAPI_LIB_VARIABLE gss_buffer_desc __gss_c_attr_local_login_user;
+#define GSS_C_ATTR_LOCAL_LOGIN_USER (&__gss_c_attr_local_login_user)
+
+/*
+ * Naming extensions
+ */
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_display_name_ext (
+    OM_uint32 *,	/* minor_status */
+    gss_name_t,		/* name */
+    gss_OID,		/* display_as_name_type */
+    gss_buffer_t	/* display_name */
+    );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_inquire_name (
+    OM_uint32 *,	/* minor_status */
+    gss_name_t,		/* name */
+    int *,		/* name_is_MN */
+    gss_OID *,		/* MN_mech */
+    gss_buffer_set_t *	/* attrs */
+    );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_get_name_attribute (
+    OM_uint32 *,	/* minor_status */
+    gss_name_t,		/* name */
+    gss_buffer_t,	/* attr */
+    int *,		/* authenticated */
+    int *,		/* complete */
+    gss_buffer_t,	/* value */
+    gss_buffer_t,	/* display_value */
+    int *		/* more */
+    );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_set_name_attribute (
+    OM_uint32 *,	/* minor_status */
+    gss_name_t,		/* name */
+    int,		/* complete */
+    gss_buffer_t,	/* attr */
+    gss_buffer_t	/* value */
+    );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_delete_name_attribute (
+    OM_uint32 *,	/* minor_status */
+    gss_name_t,		/* name */
+    gss_buffer_t	/* attr */
+    );
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_export_name_composite (
+    OM_uint32 *,	/* minor_status */
+    gss_name_t,		/* name */
+    gss_buffer_t	/* exp_composite_name */
+    );
+
 /*
  *
  */
=20
-OM_uint32
-gss_inquire_sec_context_by_oid (OM_uint32 *minor_status,
-	                        const gss_ctx_id_t context_handle,
-	                        const gss_OID desired_object,
-	                        gss_buffer_set_t *data_set);
+GSSAPI_LIB_FUNCTION const char * GSSAPI_LIB_CALL
+gss_oid_to_name(gss_const_OID oid);
=20
-OM_uint32
-gss_encapsulate_token(gss_buffer_t /* input_token */,
-		      gss_OID /* oid */,
-		      gss_buffer_t /* output_token */);
+GSSAPI_LIB_FUNCTION gss_OID GSSAPI_LIB_CALL
+gss_name_to_oid(const char *name);
=20
-OM_uint32
-gss_decapsulate_token(gss_buffer_t /* input_token */,
-		      gss_OID /* oid */,
-		      gss_buffer_t /* output_token */);
+GSSAPI_CPP_END
=20
-
-
-#ifdef __cplusplus
-}
+#if defined(__APPLE__) && (defined(__ppc__) || defined(__ppc64__) || defin=
ed(__i386__) || defined(__x86_64__))
+#pragma pack(pop)
 #endif
=20
-#include <gssapi/gssapi_krb5.h>
-#include <gssapi/gssapi_spnego.h>
+#undef GSSAPI_DEPRECATED_FUNCTION
=20
 #endif /* GSSAPI_GSSAPI_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gssapi/=
gssapi_krb5.h
--- a/head/crypto/heimdal/lib/gssapi/gssapi/gssapi_krb5.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gssapi/gssapi_krb5.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,86 +1,73 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: gssapi_krb5.h 20385 2007-04-18 08:51:32Z lha $ */
+/* $Id$ */
=20
 #ifndef GSSAPI_KRB5_H_
 #define GSSAPI_KRB5_H_
=20
-#include <gssapi/gssapi.h>
+#include <gssapi.h>
=20
-#ifdef __cplusplus
-extern "C" {
+GSSAPI_CPP_START
+
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(x)
 #endif
=20
+#ifndef GSSKRB5_FUNCTION_DEPRECATED
+#define GSSKRB5_FUNCTION_DEPRECATED __attribute__((deprecated))
+#endif
+
+
 /*
  * This is for kerberos5 names.
  */
=20
-extern gss_OID GSS_KRB5_NT_PRINCIPAL_NAME;
-extern gss_OID GSS_KRB5_NT_USER_NAME;
-extern gss_OID GSS_KRB5_NT_MACHINE_UID_NAME;
-extern gss_OID GSS_KRB5_NT_STRING_UID_NAME;
+extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_oid_d=
esc;
+#define GSS_KRB5_NT_PRINCIPAL_NAME (&__gss_krb5_nt_principal_name_oid_desc)
=20
-extern gss_OID GSS_KRB5_MECHANISM;
+#define GSS_KRB5_NT_USER_NAME (&__gss_c_nt_user_name_oid_desc)
+#define GSS_KRB5_NT_MACHINE_UID_NAME (&__gss_c_nt_machine_uid_name_oid_des=
c)
+#define GSS_KRB5_NT_STRING_UID_NAME (&__gss_c_nt_string_uid_name_oid_desc)
+
+extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_mechanism_oid_desc;
+#define GSS_KRB5_MECHANISM (&__gss_krb5_mechanism_oid_desc)
=20
 /* for compatibility with MIT api */
=20
 #define gss_mech_krb5 GSS_KRB5_MECHANISM
 #define gss_krb5_nt_general_name GSS_KRB5_NT_PRINCIPAL_NAME
=20
-/* Extensions set contexts options */
-extern gss_OID GSS_KRB5_COPY_CCACHE_X;
-extern gss_OID GSS_KRB5_COMPAT_DES3_MIC_X;
-extern gss_OID GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X;
-extern gss_OID GSS_KRB5_SET_DNS_CANONICALIZE_X;
-extern gss_OID GSS_KRB5_SEND_TO_KDC_X;
-extern gss_OID GSS_KRB5_SET_DEFAULT_REALM_X;
-extern gss_OID GSS_KRB5_CCACHE_NAME_X;
-/* Extensions inquire context */
-extern gss_OID GSS_KRB5_GET_TKT_FLAGS_X;
-extern gss_OID GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X;
-extern gss_OID GSS_C_PEER_HAS_UPDATED_SPNEGO;
-extern gss_OID GSS_KRB5_EXPORT_LUCID_CONTEXT_X;
-extern gss_OID GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X;
-extern gss_OID GSS_KRB5_GET_SUBKEY_X;
-extern gss_OID GSS_KRB5_GET_INITIATOR_SUBKEY_X;
-extern gss_OID GSS_KRB5_GET_ACCEPTOR_SUBKEY_X;
-extern gss_OID GSS_KRB5_GET_AUTHTIME_X;
-extern gss_OID GSS_KRB5_GET_SERVICE_KEYBLOCK_X;
-/* Extensions creds */
-extern gss_OID GSS_KRB5_IMPORT_CRED_X;
-extern gss_OID GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X;
-
 /*
  * kerberos mechanism specific functions
  */
@@ -89,39 +76,42 @@
 struct krb5_ccache_data;
 struct Principal;
=20
-OM_uint32
-gss_krb5_ccache_name(OM_uint32 * /*minor_status*/,=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_ccache_name(OM_uint32 * /*minor_status*/,
 		     const char * /*name */,
 		     const char ** /*out_name */);
=20
-OM_uint32 gsskrb5_register_acceptor_identity
-        (const char */*identity*/);
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gsskrb5_register_acceptor_id=
entity
+        (const char * /*identity*/);
=20
-OM_uint32 gss_krb5_copy_ccache
-	(OM_uint32 */*minor*/,
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL krb5_gss_register_acceptor_i=
dentity
+	(const char * /*identity*/);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_copy_ccache
+	(OM_uint32 * /*minor*/,
 	 gss_cred_id_t /*cred*/,
-	 struct krb5_ccache_data */*out*/);
+	 struct krb5_ccache_data * /*out*/);
=20
-OM_uint32
-gss_krb5_import_cred(OM_uint32 */*minor*/,
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_import_cred(OM_uint32 * /*minor*/,
 		     struct krb5_ccache_data * /*in*/,
 		     struct Principal * /*keytab_principal*/,
 		     struct krb5_keytab_data * /*keytab*/,
-		     gss_cred_id_t */*out*/);
+		     gss_cred_id_t * /*out*/);
=20
-OM_uint32 gss_krb5_get_tkt_flags
-	(OM_uint32 */*minor*/,
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL gss_krb5_get_tkt_flags
+	(OM_uint32 * /*minor*/,
 	 gss_ctx_id_t /*context_handle*/,
-	 OM_uint32 */*tkt_flags*/);
+	 OM_uint32 * /*tkt_flags*/);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gsskrb5_extract_authz_data_from_sec_context
 	(OM_uint32 * /*minor_status*/,
 	 gss_ctx_id_t /*context_handle*/,
 	 int /*ad_type*/,
 	 gss_buffer_t /*ad_data*/);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gsskrb5_set_dns_canonicalize(int);
=20
 struct gsskrb5_send_to_kdc {
@@ -129,30 +119,47 @@
     void *ptr;
 };
=20
-OM_uint32
-gsskrb5_set_send_to_kdc(struct gsskrb5_send_to_kdc *);
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_send_to_kdc(struct gsskrb5_send_to_kdc *)
+    GSSKRB5_FUNCTION_DEPRECATED;
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gsskrb5_set_default_realm(const char *);
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gsskrb5_extract_authtime_from_sec_context(OM_uint32 *, gss_ctx_id_t, time_=
t *);
=20
 struct EncryptionKey;
=20
-OM_uint32=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gsskrb5_extract_service_keyblock(OM_uint32 *minor_status,
 				 gss_ctx_id_t context_handle,
 				 struct EncryptionKey **out);
-OM_uint32=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gsskrb5_get_initiator_subkey(OM_uint32 *minor_status,
 				 gss_ctx_id_t context_handle,
 				 struct EncryptionKey **out);
-OM_uint32=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gsskrb5_get_subkey(OM_uint32 *minor_status,
 		   gss_ctx_id_t context_handle,
 		   struct EncryptionKey **out);
=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_set_time_offset(int);
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_get_time_offset(int *);
+
+struct gsskrb5_krb5_plugin {
+    int type;
+    char *name;
+    void *symbol;
+};
+
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gsskrb5_plugin_register(struct gsskrb5_krb5_plugin *);
+
+
 /*
  * Lucid - NFSv4 interface to GSS-API KRB5 to expose key material to
  * do GSS content token handling in-kernel.
@@ -195,26 +202,24 @@
  * Function declarations
  */
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_krb5_export_lucid_sec_context(OM_uint32 *minor_status,
 				  gss_ctx_id_t *context_handle,
 				  OM_uint32 version,
 				  void **kctx);
=20
=20
-OM_uint32
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
 gss_krb5_free_lucid_sec_context(OM_uint32 *minor_status,
 				void *kctx);
=20
=20
-OM_uint32
-gss_krb5_set_allowable_enctypes(OM_uint32 *minor_status,=20
+GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL
+gss_krb5_set_allowable_enctypes(OM_uint32 *minor_status,
 				gss_cred_id_t cred,
 				OM_uint32 num_enctypes,
 				int32_t *enctypes);
=20
-#ifdef __cplusplus
-}
-#endif
+GSSAPI_CPP_END
=20
 #endif /* GSSAPI_SPNEGO_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gssapi/=
gssapi_spnego.h
--- a/head/crypto/heimdal/lib/gssapi/gssapi/gssapi_spnego.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gssapi/gssapi_spnego.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,46 +1,44 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: gssapi_spnego.h 18335 2006-10-07 22:26:21Z lha $ */
+/* $Id$ */
=20
 #ifndef GSSAPI_SPNEGO_H_
 #define GSSAPI_SPNEGO_H_
=20
 #include <gssapi.h>
=20
-#ifdef __cplusplus
-extern "C" {
-#endif
+GSSAPI_CPP_START
=20
 /*
  * RFC2478, SPNEGO:
@@ -48,11 +46,10 @@
  *  negotiation token is identified by the Object Identifier
  *  iso.org.dod.internet.security.mechanism.snego (1.3.6.1.5.5.2).
  */
-extern gss_OID GSS_SPNEGO_MECHANISM;
+extern GSSAPI_LIB_VARIABLE gss_OID_desc __gss_spnego_mechanism_oid_desc;
+#define GSS_SPNEGO_MECHANISM (&__gss_spnego_mechanism_oid_desc)
 #define gss_mech_spnego GSS_SPNEGO_MECHANISM
=20
-#ifdef __cplusplus
-}
-#endif
+GSSAPI_CPP_END
=20
 #endif /* GSSAPI_SPNEGO_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/gssapi_=
mech.h
--- a/head/crypto/heimdal/lib/gssapi/gssapi_mech.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/gssapi/gssapi_mech.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	$FreeBSD$
+ *	$FreeBSD: head/crypto/heimdal/lib/gssapi/gssapi_mech.h 233294 2012-03-2=
2 08:48:42Z stas $
  */
=20
 #ifndef GSSAPI_MECH_H
@@ -31,7 +31,7 @@
=20
 #include <gssapi.h>
=20
-typedef OM_uint32 _gss_acquire_cred_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_acquire_cred_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_name_t,       /* desired_name */
 	       OM_uint32,              /* time_req */
@@ -42,12 +42,12 @@
 	       OM_uint32 *             /* time_rec */
 	      );
=20
-typedef OM_uint32 _gss_release_cred_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_release_cred_t
 	      (OM_uint32 *,            /* minor_status */
 	       gss_cred_id_t *         /* cred_handle */
 	      );
=20
-typedef OM_uint32 _gss_init_sec_context_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_init_sec_context_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_cred_id_t,    /* initiator_cred_handle */
 	       gss_ctx_id_t *,         /* context_handle */
@@ -64,7 +64,7 @@
 	       OM_uint32 *             /* time_rec */
 	      );
=20
-typedef OM_uint32 _gss_accept_sec_context_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_accept_sec_context_t
 	      (OM_uint32 *,            /* minor_status */
 	       gss_ctx_id_t *,         /* context_handle */
 	       const gss_cred_id_t,    /* acceptor_cred_handle */
@@ -79,25 +79,25 @@
 	       gss_cred_id_t *         /* delegated_cred_handle */
 	      );
=20
-typedef OM_uint32 _gss_process_context_token_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_process_context_token_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       const gss_buffer_t      /* token_buffer */
 	      );
=20
-typedef OM_uint32 _gss_delete_sec_context_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_delete_sec_context_t
 	      (OM_uint32 *,            /* minor_status */
 	       gss_ctx_id_t *,         /* context_handle */
 	       gss_buffer_t            /* output_token */
 	      );
=20
-typedef OM_uint32 _gss_context_time_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_context_time_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       OM_uint32 *             /* time_rec */
 	      );
=20
-typedef OM_uint32 _gss_get_mic_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_get_mic_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       gss_qop_t,              /* qop_req */
@@ -105,7 +105,7 @@
 	       gss_buffer_t            /* message_token */
 	      );
=20
-typedef OM_uint32 _gss_verify_mic_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_verify_mic_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       const gss_buffer_t,     /* message_buffer */
@@ -113,7 +113,7 @@
 	       gss_qop_t *             /* qop_state */
 	      );
=20
-typedef OM_uint32 _gss_wrap_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       int,                    /* conf_req_flag */
@@ -123,7 +123,7 @@
 	       gss_buffer_t            /* output_message_buffer */
 	      );
=20
-typedef OM_uint32 _gss_unwrap_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_unwrap_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       const gss_buffer_t,     /* input_message_buffer */
@@ -132,7 +132,7 @@
 	       gss_qop_t *             /* qop_state */
 	      );
=20
-typedef OM_uint32 _gss_display_status_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_display_status_t
 	      (OM_uint32 *,            /* minor_status */
 	       OM_uint32,              /* status_value */
 	       int,                    /* status_type */
@@ -141,44 +141,44 @@
 	       gss_buffer_t            /* status_string */
 	      );
=20
-typedef OM_uint32 _gss_indicate_mechs_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_indicate_mechs_t
 	      (OM_uint32 *,            /* minor_status */
 	       gss_OID_set *           /* mech_set */
 	      );
=20
-typedef OM_uint32 _gss_compare_name_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_compare_name_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_name_t,       /* name1 */
 	       const gss_name_t,       /* name2 */
 	       int *                   /* name_equal */
 	      );
=20
-typedef OM_uint32 _gss_display_name_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_display_name_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_name_t,       /* input_name */
 	       gss_buffer_t,           /* output_name_buffer */
 	       gss_OID *               /* output_name_type */
 	      );
=20
-typedef OM_uint32 _gss_import_name_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_import_name_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_buffer_t,     /* input_name_buffer */
 	       const gss_OID,          /* input_name_type */
 	       gss_name_t *            /* output_name */
 	      );
=20
-typedef OM_uint32 _gss_export_name_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_export_name_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_name_t,       /* input_name */
 	       gss_buffer_t            /* exported_name */
 	      );
=20
-typedef OM_uint32 _gss_release_name_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_release_name_t
 	      (OM_uint32 *,            /* minor_status */
 	       gss_name_t *            /* input_name */
 	      );
=20
-typedef OM_uint32 _gss_inquire_cred_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_cred_id_t,    /* cred_handle */
 	       gss_name_t *,           /* name */
@@ -187,7 +187,7 @@
 	       gss_OID_set *           /* mechanisms */
 	      );
=20
-typedef OM_uint32 _gss_inquire_context_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_context_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       gss_name_t *,           /* src_name */
@@ -199,7 +199,7 @@
 	       int *                   /* open */
 	      );
=20
-typedef OM_uint32 _gss_wrap_size_limit_t
+typedef OM_uint32 GSSAPI_CALLCONV _gss_wrap_size_limit_t
 	      (OM_uint32 *,            /* minor_status */
 	       const gss_ctx_id_t,     /* context_handle */
 	       int,                    /* conf_req_flag */
@@ -208,7 +208,7 @@
 	       OM_uint32 *             /* max_input_size */
 	      );
=20
-typedef OM_uint32 _gss_add_cred_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_add_cred_t (
 	       OM_uint32 *,            /* minor_status */
 	       const gss_cred_id_t,    /* input_cred_handle */
 	       const gss_name_t,       /* desired_name */
@@ -222,7 +222,7 @@
 	       OM_uint32 *             /* acceptor_time_rec */
 	      );
=20
-typedef OM_uint32 _gss_inquire_cred_by_mech_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_by_mech_t (
 	       OM_uint32 *,            /* minor_status */
 	       const gss_cred_id_t,    /* cred_handle */
 	       const gss_OID,          /* mech_type */
@@ -232,65 +232,65 @@
 	       gss_cred_usage_t *      /* cred_usage */
 	      );
=20
-typedef OM_uint32 _gss_export_sec_context_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_export_sec_context_t (
 	       OM_uint32 *,            /* minor_status */
 	       gss_ctx_id_t *,         /* context_handle */
 	       gss_buffer_t            /* interprocess_token */
 	      );
=20
-typedef OM_uint32 _gss_import_sec_context_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_import_sec_context_t (
 	       OM_uint32 *,            /* minor_status */
 	       const gss_buffer_t,     /* interprocess_token */
 	       gss_ctx_id_t *          /* context_handle */
 	      );
=20
-typedef OM_uint32 _gss_inquire_names_for_mech_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_names_for_mech_t (
 	       OM_uint32 *,            /* minor_status */
 	       const gss_OID,          /* mechanism */
 	       gss_OID_set *           /* name_types */
 	      );
=20
-typedef OM_uint32 _gss_inquire_mechs_for_name_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_mechs_for_name_t (
 	       OM_uint32 *,            /* minor_status */
 	       const gss_name_t,       /* input_name */
 	       gss_OID_set *           /* mech_types */
 	      );
=20
-typedef OM_uint32 _gss_canonicalize_name_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_canonicalize_name_t (
 	       OM_uint32 *,            /* minor_status */
 	       const gss_name_t,       /* input_name */
 	       const gss_OID,          /* mech_type */
 	       gss_name_t *            /* output_name */
 	      );
=20
-typedef OM_uint32 _gss_duplicate_name_t (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_duplicate_name_t (
 	       OM_uint32 *,            /* minor_status */
 	       const gss_name_t,       /* src_name */
 	       gss_name_t *            /* dest_name */
 	      );
=20
-typedef OM_uint32 _gss_inquire_sec_context_by_oid (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_sec_context_by_oid (
 	       OM_uint32 *minor_status,
 	       const gss_ctx_id_t context_handle,
 	       const gss_OID desired_object,
 	       gss_buffer_set_t *data_set
 	      );
=20
-typedef OM_uint32 _gss_inquire_cred_by_oid (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_cred_by_oid (
 	       OM_uint32 *minor_status,
 	       const gss_cred_id_t cred,
 	       const gss_OID desired_object,
 	       gss_buffer_set_t *data_set
 	      );
=20
-typedef OM_uint32 _gss_set_sec_context_option (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_set_sec_context_option (
 	       OM_uint32 *minor_status,
 	       gss_ctx_id_t *cred_handle,
 	       const gss_OID desired_object,
 	       const gss_buffer_t value
  	      );
=20
-typedef OM_uint32 _gss_set_cred_option (
+typedef OM_uint32 GSSAPI_CALLCONV _gss_set_cred_option (
 	       OM_uint32 *minor_status,
 	       gss_cred_id_t *cred_handle,
 	       const gss_OID desired_object,
@@ -298,7 +298,7 @@
  	      );
=20
=20
-typedef OM_uint32 _gss_pseudo_random(
+typedef OM_uint32 GSSAPI_CALLCONV _gss_pseudo_random(
     	       OM_uint32 *minor_status,
 	       gss_ctx_id_t context,
 	       int prf_key,
@@ -307,12 +307,186 @@
 	       gss_buffer_t prf_out
               );
=20
-#define GMI_VERSION 1
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_wrap_iov_t(OM_uint32 *minor_status,
+		gss_ctx_id_t  context_handle,
+		int conf_req_flag,
+		gss_qop_t qop_req,
+		int * conf_state,
+		gss_iov_buffer_desc *iov,
+		int iov_count);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_unwrap_iov_t(OM_uint32 *minor_status,
+		  gss_ctx_id_t context_handle,
+		  int *conf_state,
+		  gss_qop_t *qop_state,
+		  gss_iov_buffer_desc *iov,
+		  int iov_count);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_wrap_iov_length_t(OM_uint32 * minor_status,
+		       gss_ctx_id_t context_handle,
+		       int conf_req_flag,
+		       gss_qop_t qop_req,
+		       int *conf_state,
+		       gss_iov_buffer_desc *iov,
+		       int iov_count);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_store_cred_t(OM_uint32         *minor_status,
+		  gss_cred_id_t     input_cred_handle,
+		  gss_cred_usage_t  cred_usage,
+		  const gss_OID     desired_mech,
+		  OM_uint32         overwrite_cred,
+		  OM_uint32         default_cred,
+		  gss_OID_set       *elements_stored,
+		  gss_cred_usage_t  *cred_usage_stored);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_export_cred_t(OM_uint32 *minor_status,
+		   gss_cred_id_t cred_handle,
+		   gss_buffer_t cred_token);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_import_cred_t(OM_uint32 * minor_status,
+		   gss_buffer_t cred_token,
+		   gss_cred_id_t * cred_handle);
+
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_acquire_cred_ext_t(OM_uint32 * /*minor_status */,
+		        const gss_name_t /* desired_name */,
+		        gss_const_OID /* credential_type */,
+		        const void * /* credential_data */,
+		        OM_uint32 /* time_req */,
+		        gss_const_OID /* desired_mech */,
+		        gss_cred_usage_t /* cred_usage */,
+		        gss_cred_id_t * /* output_cred_handle */);
+
+typedef void GSSAPI_CALLCONV
+_gss_iter_creds_t(OM_uint32 /* flags */,
+		  void * /* userctx */,
+		  void (* /*cred_iter */ )(void *, gss_OID, gss_cred_id_t));
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_destroy_cred_t(OM_uint32 * /* minor_status */,
+		    gss_cred_id_t * /* cred */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_hold_t(OM_uint32 * /* minor_status */,
+		 gss_cred_id_t /* cred */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_unhold_t(OM_uint32 * /* minor_status */,
+		   gss_cred_id_t /* cred */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_label_set_t(OM_uint32 * /* minor_status */,
+		      gss_cred_id_t /* cred */,
+		      const char * /* label */,
+		      gss_buffer_t /* value */);
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_cred_label_get_t(OM_uint32 * /* minor_status */,
+		      gss_cred_id_t /* cred */,
+		      const char * /* label */,
+		      gss_buffer_t /* value */);
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_display_name_ext_t (
+	       OM_uint32 *,            /* minor_status */
+	       gss_name_t,             /* name */
+	       gss_OID,                /* display_as_name_type */
+	       gss_buffer_t            /* display_name */
+	      );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_inquire_name_t (
+	       OM_uint32 *,            /* minor_status */
+	       gss_name_t,             /* name */
+	       int *,                  /* name_is_MN */
+	       gss_OID *,              /* MN_mech */
+	       gss_buffer_set_t *      /* attrs */
+	      );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_get_name_attribute_t (
+	       OM_uint32 *,	      /* minor_status */
+	       gss_name_t,            /* name */
+	       gss_buffer_t,          /* attr */
+	       int *,                 /* authenticated */
+	       int *,                 /* complete */
+	       gss_buffer_t,          /* value */
+	       gss_buffer_t,          /* display_value */
+	       int *                  /* more */
+	    );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_set_name_attribute_t (
+	       OM_uint32 *,           /* minor_status */
+	       gss_name_t,            /* name */
+	       int,                   /* complete */
+	       gss_buffer_t,          /* attr */
+	       gss_buffer_t           /* value */
+	    );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_delete_name_attribute_t (
+	       OM_uint32 *,           /* minor_status */
+	       gss_name_t,            /* name */
+	       gss_buffer_t           /* attr */
+	    );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_export_name_composite_t (
+	       OM_uint32 *,           /* minor_status */
+	       gss_name_t,            /* name */
+	       gss_buffer_t           /* exp_composite_name */
+	    );
+
+/*
+ *
+ */
+
+typedef struct gss_mo_desc_struct gss_mo_desc;
+
+typedef OM_uint32 GSSAPI_CALLCONV
+_gss_mo_init (OM_uint32 *, gss_OID, gss_mo_desc **, size_t *);
+
+
+struct gss_mo_desc_struct {
+    gss_OID option;
+    OM_uint32 flags;
+#define GSS_MO_MA		1
+#define GSS_MO_MA_CRITICAL	2
+    const char *name;
+    void *ctx;
+    int (*get)(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+    int (*set)(gss_const_OID, gss_mo_desc *, int, gss_buffer_t);
+};
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_pname_to_uid_t (
+	       OM_uint32 *,		/* minor_status */
+	       const gss_name_t,	/* name */
+	       const gss_OID,		/* mech_type */
+	       uid_t *			/* uidOut */
+	      );
+
+typedef OM_uint32 GSSAPI_CALLCONV _gss_authorize_localname_t (
+	       OM_uint32 *,		/* minor_status */
+	       const gss_name_t,	/* name */
+	       gss_const_buffer_t,	/* user */
+	       gss_const_OID		/* user_name_type */
+	      );
+
+/* mechglue internal */
+struct gss_mech_compat_desc_struct;
+
+#define GMI_VERSION 5
+
+/* gm_flags */
+#define GM_USE_MG_CRED      	1	/* uses mech glue credentials */
=20
 typedef struct gssapi_mech_interface_desc {
 	unsigned			gm_version;
 	const char			*gm_name;
 	gss_OID_desc			gm_mech_oid;
+        unsigned			gm_flags;
 	_gss_acquire_cred_t		*gm_acquire_cred;
 	_gss_release_cred_t		*gm_release_cred;
 	_gss_init_sec_context_t		*gm_init_sec_context;
@@ -347,13 +521,74 @@
 	_gss_set_sec_context_option	*gm_set_sec_context_option;
 	_gss_set_cred_option		*gm_set_cred_option;
 	_gss_pseudo_random		*gm_pseudo_random;
+	_gss_wrap_iov_t			*gm_wrap_iov;
+	_gss_unwrap_iov_t		*gm_unwrap_iov;
+	_gss_wrap_iov_length_t		*gm_wrap_iov_length;
+	_gss_store_cred_t		*gm_store_cred;
+	_gss_export_cred_t		*gm_export_cred;
+	_gss_import_cred_t		*gm_import_cred;
+	_gss_acquire_cred_ext_t		*gm_acquire_cred_ext;
+	_gss_iter_creds_t		*gm_iter_creds;
+	_gss_destroy_cred_t		*gm_destroy_cred;
+	_gss_cred_hold_t		*gm_cred_hold;
+	_gss_cred_unhold_t		*gm_cred_unhold;
+	_gss_cred_label_get_t		*gm_cred_label_get;
+	_gss_cred_label_set_t		*gm_cred_label_set;
+        gss_mo_desc			*gm_mo;
+        size_t				 gm_mo_num;
+        _gss_pname_to_uid_t             *gm_pname_to_uid;
+        _gss_authorize_localname_t      *gm_authorize_localname;
+        _gss_display_name_ext_t         *gm_display_name_ext;
+        _gss_inquire_name_t             *gm_inquire_name;
+        _gss_get_name_attribute_t       *gm_get_name_attribute;
+        _gss_set_name_attribute_t       *gm_set_name_attribute;
+        _gss_delete_name_attribute_t    *gm_delete_name_attribute;
+        _gss_export_name_composite_t    *gm_export_name_composite;
+        struct gss_mech_compat_desc_struct  *gm_compat;
 } gssapi_mech_interface_desc, *gssapi_mech_interface;
=20
 gssapi_mech_interface
-__gss_get_mechanism(gss_OID /* oid */);
+__gss_get_mechanism(gss_const_OID /* oid */);
=20
 gssapi_mech_interface __gss_spnego_initialize(void);
 gssapi_mech_interface __gss_krb5_initialize(void);
 gssapi_mech_interface __gss_ntlm_initialize(void);
=20
+void		gss_mg_collect_error(gss_OID, OM_uint32, OM_uint32);
+
+int _gss_mo_get_option_1(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+int _gss_mo_get_option_0(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+int _gss_mo_get_ctx_as_string(gss_const_OID, gss_mo_desc *, gss_buffer_t);
+
+struct _gss_oid_name_table {
+    gss_OID oid;
+    const char *name;
+    const char *short_desc;
+    const char *long_desc;
+};
+
+extern struct _gss_oid_name_table _gss_ont_mech[];
+extern struct _gss_oid_name_table _gss_ont_ma[];
+
+/*
+ * Extended credentials acqusition API, not to be exported until
+ * it or something equivalent has been standardised.
+ */
+extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_cred_password_oid_desc;
+#define GSS_C_CRED_PASSWORD (&__gss_c_cred_password_oid_desc)
+
+extern gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_cred_certificate_oid_desc;
+#define GSS_C_CRED_CERTIFICATE (&__gss_c_cred_certificate_oid_desc)
+
+OM_uint32 _gss_acquire_cred_ext
+           (OM_uint32 * /*minor_status*/,
+            const gss_name_t /*desired_name*/,
+            gss_const_OID /*credential_type*/,
+            const void * /*credential_data*/,
+            OM_uint32 /*time_req*/,
+            gss_const_OID /*desired_mech*/,
+            gss_cred_usage_t /*cred_usage*/,
+            gss_cred_id_t * /*output_cred_handle*/
+           );
+
 #endif /* GSSAPI_MECH_H */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/80=
03.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/8003.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/8003.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: 8003.c 18334 2006-10-07 22:16:04Z lha $");
+#include "gsskrb5_locl.h"
=20
 krb5_error_code
 _gsskrb5_encode_om_uint32(OM_uint32 n, u_char *p)
@@ -76,32 +74,36 @@
 			  u_char *p)
 {
   u_char num[4];
-  MD5_CTX md5;
+  EVP_MD_CTX *ctx;
=20
-  MD5_Init(&md5);
+  ctx =3D EVP_MD_CTX_create();
+  EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+
   _gsskrb5_encode_om_uint32 (b->initiator_addrtype, num);
-  MD5_Update (&md5, num, sizeof(num));
+  EVP_DigestUpdate(ctx, num, sizeof(num));
   _gsskrb5_encode_om_uint32 (b->initiator_address.length, num);
-  MD5_Update (&md5, num, sizeof(num));
+  EVP_DigestUpdate(ctx, num, sizeof(num));
   if (b->initiator_address.length)
-    MD5_Update (&md5,
-		b->initiator_address.value,
-		b->initiator_address.length);
+      EVP_DigestUpdate(ctx,
+		       b->initiator_address.value,
+		       b->initiator_address.length);
   _gsskrb5_encode_om_uint32 (b->acceptor_addrtype, num);
-  MD5_Update (&md5, num, sizeof(num));
+  EVP_DigestUpdate(ctx, num, sizeof(num));
   _gsskrb5_encode_om_uint32 (b->acceptor_address.length, num);
-  MD5_Update (&md5, num, sizeof(num));
+  EVP_DigestUpdate(ctx, num, sizeof(num));
   if (b->acceptor_address.length)
-    MD5_Update (&md5,
-		b->acceptor_address.value,
-		b->acceptor_address.length);
+      EVP_DigestUpdate(ctx,
+		       b->acceptor_address.value,
+		       b->acceptor_address.length);
   _gsskrb5_encode_om_uint32 (b->application_data.length, num);
-  MD5_Update (&md5, num, sizeof(num));
+  EVP_DigestUpdate(ctx, num, sizeof(num));
   if (b->application_data.length)
-    MD5_Update (&md5,
-		b->application_data.value,
-		b->application_data.length);
-  MD5_Final (p, &md5);
+      EVP_DigestUpdate(ctx,
+		       b->application_data.value,
+		       b->application_data.length);
+  EVP_DigestFinal_ex(ctx, p, NULL);
+  EVP_MD_CTX_destroy(ctx);
+
   return 0;
 }
=20
@@ -113,7 +115,7 @@
=20
 OM_uint32
 _gsskrb5_create_8003_checksum (
-		      OM_uint32 *minor_status,   =20
+		      OM_uint32 *minor_status,
 		      const gss_channel_bindings_t input_chan_bindings,
 		      OM_uint32 flags,
 		      const krb5_data *fwd_data,
@@ -121,20 +123,20 @@
 {
     u_char *p;
=20
-    /*=20
-     * see rfc1964 (section 1.1.1 (Initial Token), and the checksum value=20
+    /*
+     * see rfc1964 (section 1.1.1 (Initial Token), and the checksum value
      * field's format) */
     result->cksumtype =3D CKSUMTYPE_GSSAPI;
     if (fwd_data->length > 0 && (flags & GSS_C_DELEG_FLAG))
 	result->checksum.length =3D 24 + 4 + fwd_data->length;
-    else=20
+    else
 	result->checksum.length =3D 24;
     result->checksum.data   =3D malloc (result->checksum.length);
     if (result->checksum.data =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
     }
- =20
+
     p =3D result->checksum.data;
     _gsskrb5_encode_om_uint32 (16, p);
     p +=3D 4;
@@ -157,7 +159,7 @@
=20
 	p +=3D fwd_data->length;
     }
-    =20
+
     return GSS_S_COMPLETE;
 }
=20
@@ -168,7 +170,7 @@
=20
 OM_uint32
 _gsskrb5_verify_8003_checksum(
-		      OM_uint32 *minor_status,   =20
+		      OM_uint32 *minor_status,
 		      const gss_channel_bindings_t input_chan_bindings,
 		      const Checksum *cksum,
 		      OM_uint32 *flags,
@@ -180,40 +182,35 @@
     int DlgOpt;
     static unsigned char zeros[16];
=20
-    if (cksum =3D=3D NULL) {
-	*minor_status =3D 0;
-	return GSS_S_BAD_BINDINGS;
-    }
-
     /* XXX should handle checksums > 24 bytes */
     if(cksum->cksumtype !=3D CKSUMTYPE_GSSAPI || cksum->checksum.length < =
24) {
 	*minor_status =3D 0;
 	return GSS_S_BAD_BINDINGS;
     }
-   =20
+
     p =3D cksum->checksum.data;
     _gsskrb5_decode_om_uint32(p, &length);
     if(length !=3D sizeof(hash)) {
 	*minor_status =3D 0;
 	return GSS_S_BAD_BINDINGS;
     }
-   =20
+
     p +=3D 4;
-   =20
+
     if (input_chan_bindings !=3D GSS_C_NO_CHANNEL_BINDINGS
 	&& memcmp(p, zeros, sizeof(zeros)) !=3D 0) {
 	if(hash_input_chan_bindings(input_chan_bindings, hash) !=3D 0) {
 	    *minor_status =3D 0;
 	    return GSS_S_BAD_BINDINGS;
 	}
-	if(memcmp(hash, p, sizeof(hash)) !=3D 0) {
+	if(ct_memcmp(hash, p, sizeof(hash)) !=3D 0) {
 	    *minor_status =3D 0;
 	    return GSS_S_BAD_BINDINGS;
 	}
     }
-   =20
+
     p +=3D sizeof(hash);
-   =20
+
     _gsskrb5_decode_om_uint32(p, flags);
     p +=3D 4;
=20
@@ -222,7 +219,7 @@
 	    *minor_status =3D 0;
 	    return GSS_S_BAD_BINDINGS;
 	}
-   =20
+
 	DlgOpt =3D (p[0] << 0) | (p[1] << 8);
 	p +=3D 2;
 	if (DlgOpt !=3D 1) {
@@ -243,6 +240,6 @@
 	}
 	memcpy(fwd_data->data, p, fwd_data->length);
     }
-   =20
+
     return GSS_S_COMPLETE;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ac=
cept_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/accept_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/accept_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,53 +1,71 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: accept_sec_context.c 20199 2007-02-07 22:36:39Z lha $");
+#include "gsskrb5_locl.h"
=20
 HEIMDAL_MUTEX gssapi_keytab_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
 krb5_keytab _gsskrb5_keytab;
=20
+static krb5_error_code
+validate_keytab(krb5_context context, const char *name, krb5_keytab *id)
+{
+    krb5_error_code ret;
+
+    ret =3D krb5_kt_resolve(context, name, id);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_kt_have_content(context, *id);
+    if (ret) {
+	krb5_kt_close(context, *id);
+	*id =3D NULL;
+    }
+
+    return ret;
+}
+
 OM_uint32
-_gsskrb5_register_acceptor_identity (const char *identity)
+_gsskrb5_register_acceptor_identity(OM_uint32 *min_stat, const char *ident=
ity)
 {
     krb5_context context;
     krb5_error_code ret;
=20
+    *min_stat =3D 0;
+
     ret =3D _gsskrb5_init(&context);
     if(ret)
 	return GSS_S_FAILURE;
-   =20
+
     HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex);
=20
     if(_gsskrb5_keytab !=3D NULL) {
@@ -57,29 +75,37 @@
     if (identity =3D=3D NULL) {
 	ret =3D krb5_kt_default(context, &_gsskrb5_keytab);
     } else {
-	char *p;
-
-	asprintf(&p, "FILE:%s", identity);
-	if(p =3D=3D NULL) {
-	    HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex);
-	    return GSS_S_FAILURE;
+	/*
+	 * First check if we can the keytab as is and if it has content...
+	 */
+	ret =3D validate_keytab(context, identity, &_gsskrb5_keytab);
+	/*
+	 * if it doesn't, lets prepend FILE: and try again
+	 */
+	if (ret) {
+	    char *p =3D NULL;
+	    ret =3D asprintf(&p, "FILE:%s", identity);
+	    if(ret < 0 || p =3D=3D NULL) {
+		HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex);
+		return GSS_S_FAILURE;
+	    }
+	    ret =3D validate_keytab(context, p, &_gsskrb5_keytab);
+	    free(p);
 	}
-	ret =3D krb5_kt_resolve(context, p, &_gsskrb5_keytab);
-	free(p);
     }
     HEIMDAL_MUTEX_unlock(&gssapi_keytab_mutex);
-    if(ret)
+    if(ret) {
+	*min_stat =3D ret;
 	return GSS_S_FAILURE;
+    }
     return GSS_S_COMPLETE;
 }
=20
 void
-_gsskrb5i_is_cfx(gsskrb5_ctx ctx, int *is_cfx)
+_gsskrb5i_is_cfx(krb5_context context, gsskrb5_ctx ctx, int acceptor)
 {
+    krb5_error_code ret;
     krb5_keyblock *key;
-    int acceptor =3D (ctx->more_flags & LOCAL) =3D=3D 0;
-
-    *is_cfx =3D 0;
=20
     if (acceptor) {
 	if (ctx->auth_context->local_subkey)
@@ -97,23 +123,28 @@
=20
     if (key =3D=3D NULL)
 	return;
-	   =20
+
     switch (key->keytype) {
     case ETYPE_DES_CBC_CRC:
     case ETYPE_DES_CBC_MD4:
     case ETYPE_DES_CBC_MD5:
     case ETYPE_DES3_CBC_MD5:
+    case ETYPE_OLD_DES3_CBC_SHA1:
     case ETYPE_DES3_CBC_SHA1:
     case ETYPE_ARCFOUR_HMAC_MD5:
     case ETYPE_ARCFOUR_HMAC_MD5_56:
 	break;
     default :
-	*is_cfx =3D 1;
+        ctx->more_flags |=3D IS_CFX;
+
 	if ((acceptor && ctx->auth_context->local_subkey) ||
 	    (!acceptor && ctx->auth_context->remote_subkey))
 	    ctx->more_flags |=3D ACCEPTOR_SUBKEY;
 	break;
     }
+    if (ctx->crypto)
+        krb5_crypto_destroy(context, ctx->crypto);
+    ret =3D krb5_crypto_init(context, key, 0, &ctx->crypto);
 }
=20
=20
@@ -128,7 +159,7 @@
     krb5_ccache ccache =3D NULL;
     krb5_error_code kret;
     int32_t ac_flags, ret =3D GSS_S_COMPLETE;
-     =20
+
     *minor_status =3D 0;
=20
     /* XXX Create a new delegated_cred_handle? */
@@ -136,7 +167,8 @@
 	kret =3D krb5_cc_default (context, &ccache);
     } else {
 	*delegated_cred_handle =3D NULL;
-	kret =3D krb5_cc_gen_new (context, &krb5_mcc_ops, &ccache);
+	kret =3D krb5_cc_new_unique (context, krb5_cc_type_memory,
+				   NULL, &ccache);
     }
     if (kret) {
 	ctx->flags &=3D ~GSS_C_DELEG_FLAG;
@@ -148,7 +180,7 @@
 	ctx->flags &=3D ~GSS_C_DELEG_FLAG;
 	goto out;
     }
-     =20
+
     krb5_auth_con_removeflags(context,
 			      ctx->auth_context,
 			      KRB5_AUTH_CONTEXT_DO_TIME,
@@ -170,16 +202,16 @@
     if (delegated_cred_handle) {
 	gsskrb5_cred handle;
=20
-	ret =3D _gsskrb5_import_cred(minor_status,
-				   ccache,
-				   NULL,
-				   NULL,
-				   delegated_cred_handle);
+	ret =3D _gsskrb5_krb5_import_cred(minor_status,
+					ccache,
+					NULL,
+					NULL,
+					delegated_cred_handle);
 	if (ret !=3D GSS_S_COMPLETE)
 	    goto out;
=20
 	handle =3D (gsskrb5_cred) *delegated_cred_handle;
-   =20
+
 	handle->cred_flags |=3D GSS_CF_DESTROY_CRED_ON_RELEASE;
 	krb5_cc_close(context, ccache);
 	ccache =3D NULL;
@@ -206,11 +238,12 @@
     int32_t seq_number;
     int is_cfx =3D 0;
=20
-    krb5_auth_getremoteseqnumber (context,
-				  ctx->auth_context,
-				  &seq_number);
+    krb5_auth_con_getremoteseqnumber (context,
+				      ctx->auth_context,
+				      &seq_number);
=20
-    _gsskrb5i_is_cfx(ctx, &is_cfx);
+    _gsskrb5i_is_cfx(context, ctx, 1);
+    is_cfx =3D (ctx->more_flags & IS_CFX);
=20
     ret =3D _gssapi_msg_order_create(minor_status,
 				   &ctx->order,
@@ -219,7 +252,7 @@
     if (ret)
 	return ret;
=20
-    /*=20
+    /*
      * If requested, set local sequence num to remote sequence if this
      * isn't a mutual authentication context
      */
@@ -251,6 +284,66 @@
 }
=20
 static OM_uint32
+send_error_token(OM_uint32 *minor_status,
+		 krb5_context context,
+		 krb5_error_code kret,
+		 krb5_principal server,
+		 krb5_data *indata,
+		 gss_buffer_t output_token)
+{
+    krb5_principal ap_req_server =3D NULL;
+    krb5_error_code ret;
+    krb5_data outbuf;
+    /* this e_data value encodes KERB_AP_ERR_TYPE_SKEW_RECOVERY which
+       tells windows to try again with the corrected timestamp. See
+       [MS-KILE] 2.2.1 KERB-ERROR-DATA */
+    krb5_data e_data =3D { 7, rk_UNCONST("\x30\x05\xa1\x03\x02\x01\x02") };
+
+    /* build server from request if the acceptor had not selected one */
+    if (server =3D=3D NULL) {
+	AP_REQ ap_req;
+
+	ret =3D krb5_decode_ap_req(context, indata, &ap_req);
+	if (ret) {
+	    *minor_status =3D ret;
+	    return GSS_S_FAILURE;
+	}
+	ret =3D _krb5_principalname2krb5_principal(context,
+						  &ap_req_server,
+						  ap_req.ticket.sname,
+						  ap_req.ticket.realm);
+	free_AP_REQ(&ap_req);
+	if (ret) {
+	    *minor_status =3D ret;
+	    return GSS_S_FAILURE;
+	}
+	server =3D ap_req_server;
+    }
+
+    ret =3D krb5_mk_error(context, kret, NULL, &e_data, NULL,
+			server, NULL, NULL, &outbuf);
+    if (ap_req_server)
+	krb5_free_principal(context, ap_req_server);
+    if (ret) {
+	*minor_status =3D ret;
+	return GSS_S_FAILURE;
+    }
+
+    ret =3D _gsskrb5_encapsulate(minor_status,
+			       &outbuf,
+			       output_token,
+			       "\x03\x00",
+			       GSS_KRB5_MECHANISM);
+    krb5_data_free (&outbuf);
+    if (ret)
+	return ret;
+
+    *minor_status =3D 0;
+    return GSS_S_CONTINUE_NEEDED;
+}
+
+
+static OM_uint32
 gsskrb5_acceptor_start(OM_uint32 * minor_status,
 		       gsskrb5_ctx ctx,
 		       krb5_context context,
@@ -296,7 +389,7 @@
     } else if (acceptor_cred->keytab !=3D NULL) {
 	keytab =3D acceptor_cred->keytab;
     }
-   =20
+
     /*
      * We need to check the ticket and create the AP-REP packet
      */
@@ -304,6 +397,10 @@
     {
 	krb5_rd_req_in_ctx in =3D NULL;
 	krb5_rd_req_out_ctx out =3D NULL;
+	krb5_principal server =3D NULL;
+
+	if (acceptor_cred)
+	    server =3D acceptor_cred->principal;
=20
 	kret =3D krb5_rd_req_in_ctx_alloc(context, &in);
 	if (kret =3D=3D 0)
@@ -311,30 +408,37 @@
 	if (kret) {
 	    if (in)
 		krb5_rd_req_in_ctx_free(context, in);
-	    ret =3D GSS_S_FAILURE;
 	    *minor_status =3D kret;
-	    return ret;
+	    return GSS_S_FAILURE;
 	}
=20
 	kret =3D krb5_rd_req_ctx(context,
 			       &ctx->auth_context,
 			       &indata,
-			       (acceptor_cred_handle =3D=3D GSS_C_NO_CREDENTIAL) ? NULL : accep=
tor_cred->principal,
+			       server,
 			       in, &out);
 	krb5_rd_req_in_ctx_free(context, in);
-	if (kret) {
-	    ret =3D GSS_S_FAILURE;
+	if (kret =3D=3D KRB5KRB_AP_ERR_SKEW || kret =3D=3D KRB5KRB_AP_ERR_TKT_NYV=
) {
+	    /*
+	     * No reply in non-MUTUAL mode, but we don't know that its
+	     * non-MUTUAL mode yet, thats inside the 8003 checksum, so
+	     * lets only send the error token on clock skew, that
+	     * limit when send error token for non-MUTUAL.
+	     */
+	    return send_error_token(minor_status, context, kret,
+				    server, &indata, output_token);
+	} else if (kret) {
 	    *minor_status =3D kret;
-	    return ret;
+	    return GSS_S_FAILURE;
 	}
=20
 	/*
-	 * We need to remember some data on the context_handle.
+	 * we need to remember some data on the context_handle.
 	 */
 	kret =3D krb5_rd_req_out_get_ap_req_options(context, out,
 						  &ap_options);
 	if (kret =3D=3D 0)
-	    kret =3D krb5_rd_req_out_get_ticket(context, out,=20
+	    kret =3D krb5_rd_req_out_get_ticket(context, out,
 					      &ctx->ticket);
 	if (kret =3D=3D 0)
 	    kret =3D krb5_rd_req_out_get_keyblock(context, out,
@@ -348,8 +452,8 @@
 	    return ret;
 	}
     }
-   =20
-   =20
+
+
     /*
      * We need to copy the principal names to the context and the
      * calling layer.
@@ -362,7 +466,7 @@
 	*minor_status =3D kret;
     }
=20
-    kret =3D krb5_copy_principal(context,=20
+    kret =3D krb5_copy_principal(context,
 			       ctx->ticket->server,
 			       &ctx->target);
     if (kret) {
@@ -370,7 +474,7 @@
 	*minor_status =3D kret;
 	return ret;
     }
-   =20
+
     /*
      * We need to setup some compat stuff, this assumes that
      * context_handle->target is already set.
@@ -393,9 +497,10 @@
     /*
      * We need to get the flags out of the 8003 checksum.
      */
+
     {
 	krb5_authenticator authenticator;
-     =20
+
 	kret =3D krb5_auth_con_getauthenticator(context,
 					      ctx->auth_context,
 					      &authenticator);
@@ -405,6 +510,12 @@
 	    return ret;
 	}
=20
+	if (authenticator->cksum =3D=3D NULL) {
+	    krb5_free_authenticator(context, &authenticator);
+	    *minor_status =3D 0;
+	    return GSS_S_BAD_BINDINGS;
+	}
+
         if (authenticator->cksum->cksumtype =3D=3D CKSUMTYPE_GSSAPI) {
             ret =3D _gsskrb5_verify_8003_checksum(minor_status,
 						input_chan_bindings,
@@ -419,8 +530,8 @@
         } else {
 	    krb5_crypto crypto;
=20
-	    kret =3D krb5_crypto_init(context,=20
-				    ctx->auth_context->keyblock,=20
+	    kret =3D krb5_crypto_init(context,
+				    ctx->auth_context->keyblock,
 				    0, &crypto);
 	    if(kret) {
 		krb5_free_authenticator(context, &authenticator);
@@ -430,9 +541,9 @@
 		return ret;
 	    }
=20
-	    /*=20
+	    /*
 	     * Windows accepts Samba3's use of a kerberos, rather than
-	     * GSSAPI checksum here=20
+	     * GSSAPI checksum here
 	     */
=20
 	    kret =3D krb5_verify_checksum(context,
@@ -447,28 +558,51 @@
 		return ret;
 	    }
=20
-	    /*=20
-	     * Samba style get some flags (but not DCE-STYLE)
+	    /*
+	     * Samba style get some flags (but not DCE-STYLE), use
+	     * ap_options to guess the mutual flag.
 	     */
-	    ctx->flags =3D=20
-		GSS_C_MUTUAL_FLAG | GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG;
+ 	    ctx->flags =3D GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG;
+	    if (ap_options & AP_OPTS_MUTUAL_REQUIRED)
+		ctx->flags |=3D GSS_C_MUTUAL_FLAG;
         }
     }
-   =20
+
     if(ctx->flags & GSS_C_MUTUAL_FLAG) {
 	krb5_data outbuf;
-	   =20
-	_gsskrb5i_is_cfx(ctx, &is_cfx);
-	   =20
-	if (is_cfx !=3D 0=20
-	    || (ap_options & AP_OPTS_USE_SUBKEY)) {
-	    kret =3D krb5_auth_con_addflags(context,
-					  ctx->auth_context,
-					  KRB5_AUTH_CONTEXT_USE_SUBKEY,
-					  NULL);
+	int use_subkey =3D 0;
+
+	_gsskrb5i_is_cfx(context, ctx, 1);
+	is_cfx =3D (ctx->more_flags & IS_CFX);
+
+	if (is_cfx || (ap_options & AP_OPTS_USE_SUBKEY)) {
+	    use_subkey =3D 1;
+	} else {
+	    krb5_keyblock *rkey;
+
+	    /*
+	     * If there is a initiator subkey, copy that to acceptor
+	     * subkey to match Windows behavior
+	     */
+	    kret =3D krb5_auth_con_getremotesubkey(context,
+						 ctx->auth_context,
+						 &rkey);
+	    if (kret =3D=3D 0) {
+		kret =3D krb5_auth_con_setlocalsubkey(context,
+						    ctx->auth_context,
+						    rkey);
+		if (kret =3D=3D 0)
+		    use_subkey =3D 1;
+		krb5_free_keyblock(context, rkey);
+	    }
+	}
+	if (use_subkey) {
 	    ctx->more_flags |=3D ACCEPTOR_SUBKEY;
+	    krb5_auth_con_addflags(context, ctx->auth_context,
+				   KRB5_AUTH_CONTEXT_USE_SUBKEY,
+				   NULL);
 	}
-	   =20
+
 	kret =3D krb5_mk_rep(context,
 			   ctx->auth_context,
 			   &outbuf);
@@ -476,7 +610,7 @@
 	    *minor_status =3D kret;
 	    return GSS_S_FAILURE;
 	}
-	   =20
+
 	if (IS_DCE_STYLE(ctx)) {
 	    output_token->length =3D outbuf.length;
 	    output_token->value =3D outbuf.data;
@@ -491,17 +625,17 @@
 		return ret;
 	}
     }
-   =20
+
     ctx->flags |=3D GSS_C_TRANS_FLAG;
=20
     /* Remember the flags */
-   =20
+
     ctx->lifetime =3D ctx->ticket->ticket.endtime;
     ctx->more_flags |=3D OPEN;
-   =20
+
     if (mech_type)
 	*mech_type =3D GSS_KRB5_MECHANISM;
-   =20
+
     if (time_rec) {
 	ret =3D _gsskrb5_lifetime_left(minor_status,
 				     context,
@@ -528,7 +662,7 @@
 	return GSS_S_CONTINUE_NEEDED;
     }
=20
-    ret =3D gsskrb5_acceptor_ready(minor_status, ctx, context,=20
+    ret =3D gsskrb5_acceptor_ready(minor_status, ctx, context,
 				 delegated_cred_handle);
=20
     if (ret_flags)
@@ -555,15 +689,15 @@
     krb5_error_code kret;
     krb5_data inbuf;
     int32_t r_seq_number, l_seq_number;
-=09
-    /*=20
+
+    /*
      * We know it's GSS_C_DCE_STYLE so we don't need to decapsulate the AP=
_REP
      */
=20
     inbuf.length =3D input_token_buffer->length;
     inbuf.data =3D input_token_buffer->value;
=20
-    /*=20
+    /*
      * We need to remeber the old remote seq_number, then check if the
      * client has replied with our local seq_number, and then reset
      * the remote seq_number to the old value
@@ -577,9 +711,9 @@
 	    return GSS_S_FAILURE;
 	}
=20
-	kret =3D krb5_auth_getremoteseqnumber(context,
-					    ctx->auth_context,
-					    &r_seq_number);
+	kret =3D krb5_auth_con_getremoteseqnumber(context,
+						ctx->auth_context,
+						&r_seq_number);
 	if (kret) {
 	    *minor_status =3D kret;
 	    return GSS_S_FAILURE;
@@ -594,15 +728,15 @@
 	}
     }
=20
-    /*=20
+    /*
      * We need to verify the AP_REP, but we need to flag that this is
      * DCE_STYLE, so don't check the timestamps this time, but put the
      * flag DO_TIME back afterward.
-    */=20
+    */
     {
 	krb5_ap_rep_enc_part *repl;
 	int32_t auth_flags;
-	=09
+
 	krb5_auth_con_removeflags(context,
 				  ctx->auth_context,
 				  KRB5_AUTH_CONTEXT_DO_TIME,
@@ -631,7 +765,7 @@
 	if (lifetime_rec =3D=3D 0) {
 	    return GSS_S_CONTEXT_EXPIRED;
 	}
-=09
+
 	if (time_rec) *time_rec =3D lifetime_rec;
     }
=20
@@ -657,9 +791,9 @@
     {
 	int32_t tmp_r_seq_number, tmp_l_seq_number;
=20
-	kret =3D krb5_auth_getremoteseqnumber(context,
-					    ctx->auth_context,
-					    &tmp_r_seq_number);
+	kret =3D krb5_auth_con_getremoteseqnumber(context,
+						ctx->auth_context,
+						&tmp_r_seq_number);
 	if (kret) {
 	    *minor_status =3D kret;
 	    return GSS_S_FAILURE;
@@ -689,19 +823,19 @@
     {
 	kret =3D krb5_auth_con_setremoteseqnumber(context,
 						ctx->auth_context,
-						r_seq_number);=09
+						r_seq_number);
 	if (kret) {
 	    *minor_status =3D kret;
 	    return GSS_S_FAILURE;
 	}
     }
=20
-    return gsskrb5_acceptor_ready(minor_status, ctx, context,=20
+    return gsskrb5_acceptor_ready(minor_status, ctx, context,
 				  delegated_cred_handle);
 }
=20
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_accept_sec_context(OM_uint32 * minor_status,
 			    gss_ctx_id_t * context_handle,
 			    const gss_cred_id_t acceptor_cred_handle,
@@ -737,17 +871,17 @@
 	if (ret)
 	    return ret;
     }
-   =20
+
     ctx =3D (gsskrb5_ctx)*context_handle;
=20
-   =20
+
     /*
-     * TODO: check the channel_bindings=20
+     * TODO: check the channel_bindings
      * (above just sets them to krb5 layer)
      */
=20
     HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
-   =20
+
     switch (ctx->state) {
     case ACCEPTOR_START:
 	ret =3D gsskrb5_acceptor_start(minor_status,
@@ -778,7 +912,7 @@
 					 delegated_cred_handle);
 	break;
     case ACCEPTOR_READY:
-	/*=20
+	/*
 	 * If we get there, the caller have called
 	 * gss_accept_sec_context() one time too many.
 	 */
@@ -789,9 +923,9 @@
 	ret =3D  GSS_S_BAD_STATUS;
 	break;
     }
-   =20
+
     HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
-   =20
+
     if (GSS_ERROR(ret)) {
 	OM_uint32 min2;
 	_gsskrb5_delete_sec_context(&min2, context_handle, GSS_C_NO_BUFFER);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ac=
quire_cred.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/acquire_cred.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/acquire_cred.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: acquire_cred.c 22124 2007-12-04 00:03:52Z lha $");
+#include "gsskrb5_locl.h"
=20
 OM_uint32
 __gsskrb5_ccache_lifetime(OM_uint32 *minor_status,
@@ -42,13 +40,13 @@
 			  krb5_principal principal,
 			  OM_uint32 *lifetime)
 {
-    krb5_creds in_cred, *out_cred;
+    krb5_creds in_cred, out_cred;
     krb5_const_realm realm;
     krb5_error_code kret;
=20
     memset(&in_cred, 0, sizeof(in_cred));
     in_cred.client =3D principal;
-=09
+
     realm =3D krb5_principal_get_realm(context,  principal);
     if (realm =3D=3D NULL) {
 	_gsskrb5_clear_status ();
@@ -56,23 +54,23 @@
 	return GSS_S_FAILURE;
     }
=20
-    kret =3D krb5_make_principal(context, &in_cred.server,=20
+    kret =3D krb5_make_principal(context, &in_cred.server,
 			       realm, KRB5_TGS_NAME, realm, NULL);
     if (kret) {
 	*minor_status =3D kret;
 	return GSS_S_FAILURE;
     }
=20
-    kret =3D krb5_get_credentials(context, 0,=20
-				id, &in_cred, &out_cred);
+    kret =3D krb5_cc_retrieve_cred(context, id, 0, &in_cred, &out_cred);
     krb5_free_principal(context, in_cred.server);
     if (kret) {
-	*minor_status =3D kret;
-	return GSS_S_FAILURE;
+	*minor_status =3D 0;
+	*lifetime =3D 0;
+	return GSS_S_COMPLETE;
     }
=20
-    *lifetime =3D out_cred->times.endtime;
-    krb5_free_creds(context, out_cred);
+    *lifetime =3D out_cred.times.endtime;
+    krb5_free_cred_contents(context, &out_cred);
=20
     return GSS_S_COMPLETE;
 }
@@ -83,17 +81,18 @@
 static krb5_error_code
 get_keytab(krb5_context context, krb5_keytab *keytab)
 {
-    char kt_name[256];
     krb5_error_code kret;
=20
     HEIMDAL_MUTEX_lock(&gssapi_keytab_mutex);
=20
     if (_gsskrb5_keytab !=3D NULL) {
-	kret =3D krb5_kt_get_name(context,
-				_gsskrb5_keytab,
-				kt_name, sizeof(kt_name));
-	if (kret =3D=3D 0)
-	    kret =3D krb5_kt_resolve(context, kt_name, keytab);
+	char *name =3D NULL;
+
+	kret =3D krb5_kt_get_full_name(context, _gsskrb5_keytab, &name);
+	if (kret =3D=3D 0) {
+	    kret =3D krb5_kt_resolve(context, name, keytab);
+	    krb5_xfree(name);
+	}
     } else
 	kret =3D krb5_kt_default(context, keytab);
=20
@@ -105,13 +104,13 @@
 static OM_uint32 acquire_initiator_cred
 		  (OM_uint32 * minor_status,
 		   krb5_context context,
+		   gss_const_OID credential_type,
+		   const void *credential_data,
 		   const gss_name_t desired_name,
 		   OM_uint32 time_req,
-		   const gss_OID_set desired_mechs,
+		   gss_const_OID desired_mech,
 		   gss_cred_usage_t cred_usage,
-		   gsskrb5_cred handle,
-		   gss_OID_set * actual_mechs,
-		   OM_uint32 * time_rec
+		   gsskrb5_cred handle
 		  )
 {
     OM_uint32 ret;
@@ -128,70 +127,100 @@
     ret =3D GSS_S_FAILURE;
     memset(&cred, 0, sizeof(cred));
=20
-    /* If we have a preferred principal, lets try to find it in all
-     * caches, otherwise, fall back to default cache.  Ignore
-     * errors. */
-    if (handle->principal)
+    /*
+     * If we have a preferred principal, lets try to find it in all
+     * caches, otherwise, fall back to default cache, ignore all
+     * errors while searching.
+     */
+
+    if (credential_type !=3D GSS_C_NO_OID &&
+	!gss_oid_equal(credential_type, GSS_C_CRED_PASSWORD)) {
+	kret =3D KRB5_NOCREDS_SUPPLIED; /* XXX */
+	goto end;
+    }
+
+    if (handle->principal) {
 	kret =3D krb5_cc_cache_match (context,
 				    handle->principal,
-				    NULL,
 				    &ccache);
-   =20
+	if (kret =3D=3D 0) {
+	    ret =3D GSS_S_COMPLETE;
+	    goto found;
+	}
+    }
+
     if (ccache =3D=3D NULL) {
 	kret =3D krb5_cc_default(context, &ccache);
 	if (kret)
 	    goto end;
     }
-    kret =3D krb5_cc_get_principal(context, ccache,
-	&def_princ);
+    kret =3D krb5_cc_get_principal(context, ccache, &def_princ);
     if (kret !=3D 0) {
 	/* we'll try to use a keytab below */
-	krb5_cc_destroy(context, ccache);
-	ccache =3D NULL;
+	krb5_cc_close(context, ccache);
+	def_princ =3D NULL;
 	kret =3D 0;
     } else if (handle->principal =3D=3D NULL)  {
-	kret =3D krb5_copy_principal(context, def_princ,
-	    &handle->principal);
+	kret =3D krb5_copy_principal(context, def_princ, &handle->principal);
 	if (kret)
 	    goto end;
     } else if (handle->principal !=3D NULL &&
-	krb5_principal_compare(context, handle->principal,
-	def_princ) =3D=3D FALSE) {
-	/* Before failing, lets check the keytab */
+	       krb5_principal_compare(context, handle->principal,
+				      def_princ) =3D=3D FALSE) {
 	krb5_free_principal(context, def_princ);
 	def_princ =3D NULL;
+	krb5_cc_close(context, ccache);
+	ccache =3D NULL;
     }
     if (def_princ =3D=3D NULL) {
 	/* We have no existing credentials cache,
 	 * so attempt to get a TGT using a keytab.
 	 */
 	if (handle->principal =3D=3D NULL) {
-	    kret =3D krb5_get_default_principal(context,
-		&handle->principal);
+	    kret =3D krb5_get_default_principal(context, &handle->principal);
 	    if (kret)
 		goto end;
 	}
-	kret =3D get_keytab(context, &keytab);
-	if (kret)
-	    goto end;
 	kret =3D krb5_get_init_creds_opt_alloc(context, &opt);
 	if (kret)
 	    goto end;
-	kret =3D krb5_get_init_creds_keytab(context, &cred,
-	    handle->principal, keytab, 0, NULL, opt);
+	if (credential_type !=3D GSS_C_NO_OID &&
+	    gss_oid_equal(credential_type, GSS_C_CRED_PASSWORD)) {
+	    gss_buffer_t password =3D (gss_buffer_t)credential_data;
+
+	    /* XXX are we requiring password to be NUL terminated? */
+
+	    kret =3D krb5_get_init_creds_password(context, &cred,
+						handle->principal,
+						password->value,
+						NULL, NULL, 0, NULL, opt);
+	} else {
+	    kret =3D get_keytab(context, &keytab);
+	    if (kret) {
+		krb5_get_init_creds_opt_free(context, opt);
+		goto end;
+	    }
+	    kret =3D krb5_get_init_creds_keytab(context, &cred,
+					      handle->principal, keytab,
+					      0, NULL, opt);
+	}
 	krb5_get_init_creds_opt_free(context, opt);
 	if (kret)
 	    goto end;
-	kret =3D krb5_cc_gen_new(context, &krb5_mcc_ops,
-		&ccache);
+	kret =3D krb5_cc_new_unique(context, krb5_cc_type_memory,
+				  NULL, &ccache);
 	if (kret)
 	    goto end;
 	kret =3D krb5_cc_initialize(context, ccache, cred.client);
-	if (kret)
+	if (kret) {
+	    krb5_cc_destroy(context, ccache);
 	    goto end;
+	}
 	kret =3D krb5_cc_store_cred(context, ccache, &cred);
-	if (kret)
+	if (kret) {
+	    krb5_cc_destroy(context, ccache);
 	    goto end;
+	}
 	handle->lifetime =3D cred.times.endtime;
 	handle->cred_flags |=3D GSS_CF_DESTROY_CRED_ON_RELEASE;
     } else {
@@ -201,11 +230,13 @@
 					ccache,
 					handle->principal,
 					&handle->lifetime);
-	if (ret !=3D GSS_S_COMPLETE)
+	if (ret !=3D GSS_S_COMPLETE) {
+	    krb5_cc_close(context, ccache);
 	    goto end;
+	}
 	kret =3D 0;
     }
-
+ found:
     handle->ccache =3D ccache;
     ret =3D GSS_S_COMPLETE;
=20
@@ -216,49 +247,49 @@
 	krb5_free_principal(context, def_princ);
     if (keytab !=3D NULL)
 	krb5_kt_close(context, keytab);
-    if (ret !=3D GSS_S_COMPLETE) {
-	if (ccache !=3D NULL)
-	    krb5_cc_close(context, ccache);
-	if (kret !=3D 0) {
-	    *minor_status =3D kret;
-	}
-    }
+    if (ret !=3D GSS_S_COMPLETE && kret !=3D 0)
+	*minor_status =3D kret;
     return (ret);
 }
=20
 static OM_uint32 acquire_acceptor_cred
 		  (OM_uint32 * minor_status,
 		   krb5_context context,
+		   gss_const_OID credential_type,
+		   const void *credential_data,
 		   const gss_name_t desired_name,
 		   OM_uint32 time_req,
-		   const gss_OID_set desired_mechs,
+		   gss_const_OID desired_mech,
 		   gss_cred_usage_t cred_usage,
-		   gsskrb5_cred handle,
-		   gss_OID_set * actual_mechs,
-		   OM_uint32 * time_rec
+		   gsskrb5_cred handle
 		  )
 {
     OM_uint32 ret;
     krb5_error_code kret;
=20
-    kret =3D 0;
     ret =3D GSS_S_FAILURE;
+
+    if (credential_type !=3D GSS_C_NO_OID) {
+	kret =3D EINVAL;
+	goto end;
+    }
+
     kret =3D get_keytab(context, &handle->keytab);
     if (kret)
 	goto end;
-   =20
+
     /* check that the requested principal exists in the keytab */
     if (handle->principal) {
 	krb5_keytab_entry entry;
=20
-	kret =3D krb5_kt_get_entry(context, handle->keytab,=20
+	kret =3D krb5_kt_get_entry(context, handle->keytab,
 				 handle->principal, 0, 0, &entry);
 	if (kret)
 	    goto end;
 	krb5_kt_free_entry(context, &entry);
 	ret =3D GSS_S_COMPLETE;
     } else {
-	/*=20
+	/*
 	 * Check if there is at least one entry in the keytab before
 	 * declaring it as an useful keytab.
 	 */
@@ -273,7 +304,7 @@
 	    ret =3D GSS_S_COMPLETE; /* ok found one entry */
 	}
 	krb5_kt_end_seq_get (context, handle->keytab, &c);
-    }=20
+    }
 end:
     if (ret !=3D GSS_S_COMPLETE) {
 	if (handle->keytab !=3D NULL)
@@ -285,7 +316,7 @@
     return (ret);
 }
=20
-OM_uint32 _gsskrb5_acquire_cred
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_acquire_cred
 (OM_uint32 * minor_status,
  const gss_name_t desired_name,
  OM_uint32 time_req,
@@ -296,10 +327,60 @@
  OM_uint32 * time_rec
     )
 {
+    OM_uint32 ret;
+
+    if (desired_mechs) {
+	int present =3D 0;
+
+	ret =3D gss_test_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
+				      desired_mechs, &present);
+	if (ret)
+	    return ret;
+	if (!present) {
+	    *minor_status =3D 0;
+	    return GSS_S_BAD_MECH;
+	}
+    }
+
+    ret =3D _gsskrb5_acquire_cred_ext(minor_status,
+				    desired_name,
+				    GSS_C_NO_OID,
+				    NULL,
+				    time_req,
+				    GSS_KRB5_MECHANISM,
+				    cred_usage,
+				    output_cred_handle);
+    if (ret)
+	return ret;
+
+
+    ret =3D _gsskrb5_inquire_cred(minor_status, *output_cred_handle,
+				NULL, time_rec, NULL, actual_mechs);
+    if (ret) {
+	OM_uint32 tmp;
+	_gsskrb5_release_cred(&tmp, output_cred_handle);
+    }
+
+    return ret;
+}
+
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_acquire_cred_ext
+(OM_uint32 * minor_status,
+ const gss_name_t desired_name,
+ gss_const_OID credential_type,
+ const void *credential_data,
+ OM_uint32 time_req,
+ gss_const_OID desired_mech,
+ gss_cred_usage_t cred_usage,
+ gss_cred_id_t * output_cred_handle
+    )
+{
     krb5_context context;
     gsskrb5_cred handle;
     OM_uint32 ret;
=20
+    cred_usage &=3D GSS_C_OPTION_MASK;
+
     if (cred_usage !=3D GSS_C_ACCEPT && cred_usage !=3D GSS_C_INITIATE && =
cred_usage !=3D GSS_C_BOTH) {
 	*minor_status =3D GSS_KRB5_S_G_BAD_USAGE;
 	return GSS_S_FAILURE;
@@ -308,23 +389,6 @@
     GSSAPI_KRB5_INIT(&context);
=20
     *output_cred_handle =3D NULL;
-    if (time_rec)
-	*time_rec =3D 0;
-    if (actual_mechs)
-	*actual_mechs =3D GSS_C_NO_OID_SET;
-
-    if (desired_mechs) {
-	int present =3D 0;
-
-	ret =3D gss_test_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
-				      desired_mechs, &present);=20
-	if (ret)
-	    return ret;
-	if (!present) {
-	    *minor_status =3D 0;
-	    return GSS_S_BAD_MECH;
-	}
-    }
=20
     handle =3D calloc(1, sizeof(*handle));
     if (handle =3D=3D NULL) {
@@ -335,20 +399,19 @@
     HEIMDAL_MUTEX_init(&handle->cred_id_mutex);
=20
     if (desired_name !=3D GSS_C_NO_NAME) {
-	krb5_principal name =3D (krb5_principal)desired_name;
-	ret =3D krb5_copy_principal(context, name, &handle->principal);
+	ret =3D _gsskrb5_canon_name(minor_status, context, 1, NULL,
+				  desired_name, &handle->principal);
 	if (ret) {
 	    HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
-	    *minor_status =3D ret;
 	    free(handle);
-	    return GSS_S_FAILURE;
+	    return ret;
 	}
     }
     if (cred_usage =3D=3D GSS_C_INITIATE || cred_usage =3D=3D GSS_C_BOTH) {
 	ret =3D acquire_initiator_cred(minor_status, context,
+				     credential_type, credential_data,
 				     desired_name, time_req,
-				     desired_mechs, cred_usage, handle,
-				     actual_mechs, time_rec);
+				     desired_mech, cred_usage, handle);
     	if (ret !=3D GSS_S_COMPLETE) {
 	    HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
 	    krb5_free_principal(context, handle->principal);
@@ -358,8 +421,9 @@
     }
     if (cred_usage =3D=3D GSS_C_ACCEPT || cred_usage =3D=3D GSS_C_BOTH) {
 	ret =3D acquire_acceptor_cred(minor_status, context,
+				    credential_type, credential_data,
 				    desired_name, time_req,
-				    desired_mechs, cred_usage, handle, actual_mechs, time_rec);
+				    desired_mech, cred_usage, handle);
 	if (ret !=3D GSS_S_COMPLETE) {
 	    HEIMDAL_MUTEX_destroy(&handle->cred_id_mutex);
 	    krb5_free_principal(context, handle->principal);
@@ -371,9 +435,6 @@
     if (ret =3D=3D GSS_S_COMPLETE)
     	ret =3D gss_add_oid_set_member(minor_status, GSS_KRB5_MECHANISM,
 				     &handle->mechanisms);
-    if (ret =3D=3D GSS_S_COMPLETE)
-    	ret =3D _gsskrb5_inquire_cred(minor_status, (gss_cred_id_t)handle,=20
-				    NULL, time_rec, NULL, actual_mechs);
     if (ret !=3D GSS_S_COMPLETE) {
 	if (handle->mechanisms !=3D NULL)
 	    gss_release_oid_set(NULL, &handle->mechanisms);
@@ -381,18 +442,9 @@
 	krb5_free_principal(context, handle->principal);
 	free(handle);
 	return (ret);
-    }=20
-    *minor_status =3D 0;
-    if (time_rec) {
-	ret =3D _gsskrb5_lifetime_left(minor_status,
-				     context,
-				     handle->lifetime,
-				     time_rec);
-
-	if (ret)
-	    return ret;
     }
     handle->usage =3D cred_usage;
+    *minor_status =3D 0;
     *output_cred_handle =3D (gss_cred_id_t)handle;
     return (GSS_S_COMPLETE);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ad=
d_cred.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/add_cred.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/add_cred.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: add_cred.c 20688 2007-05-17 18:44:31Z lha $");
-
-OM_uint32 _gsskrb5_add_cred (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_add_cred (
      OM_uint32           *minor_status,
      const gss_cred_id_t input_cred_handle,
      const gss_name_t    desired_name,
@@ -74,7 +72,7 @@
 	return GSS_S_NO_CRED;
     }
=20
-    /* check if requested output usage is compatible with output usage */=20
+    /* check if requested output usage is compatible with output usage */
     if (output_cred_handle !=3D NULL) {
 	HEIMDAL_MUTEX_lock(&cred->cred_id_mutex);
 	if (cred->usage !=3D cred_usage && cred->usage !=3D GSS_C_BOTH) {
@@ -83,10 +81,10 @@
 	    return(GSS_S_FAILURE);
 	}
     }
-=09
+
     /* check that we have the same name */
     if (dname !=3D NULL &&
-	krb5_principal_compare(context, dname,=20
+	krb5_principal_compare(context, dname,
 			       cred->principal) !=3D FALSE) {
 	if (output_cred_handle)
 	    HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
@@ -112,7 +110,7 @@
 	handle->ccache =3D NULL;
 	handle->mechanisms =3D NULL;
 	HEIMDAL_MUTEX_init(&handle->cred_id_mutex);
-=09
+
 	ret =3D GSS_S_FAILURE;
=20
 	kret =3D krb5_copy_principal(context, cred->principal,
@@ -125,23 +123,11 @@
 	}
=20
 	if (cred->keytab) {
-	    char name[KRB5_KT_PREFIX_MAX_LEN + MAXPATHLEN];
-	    int len;
-	   =20
+	    char *name =3D NULL;
+
 	    ret =3D GSS_S_FAILURE;
=20
-	    kret =3D krb5_kt_get_type(context, cred->keytab,
-				    name, KRB5_KT_PREFIX_MAX_LEN);
-	    if (kret) {
-		*minor_status =3D kret;
-		goto failure;
-	    }
-	    len =3D strlen(name);
-	    name[len++] =3D ':';
-
-	    kret =3D krb5_kt_get_name(context, cred->keytab,
-				    name + len,=20
-				    sizeof(name) - len);
+	    kret =3D krb5_kt_get_full_name(context, cred->keytab, &name);
 	    if (kret) {
 		*minor_status =3D kret;
 		goto failure;
@@ -149,6 +135,7 @@
=20
 	    kret =3D krb5_kt_resolve(context, name,
 				   &handle->keytab);
+	    krb5_xfree(name);
 	    if (kret){
 		*minor_status =3D kret;
 		goto failure;
@@ -157,7 +144,7 @@
=20
 	if (cred->ccache) {
 	    const char *type, *name;
-	    char *type_name;
+	    char *type_name =3D NULL;
=20
 	    ret =3D GSS_S_FAILURE;
=20
@@ -168,8 +155,8 @@
 	    }
=20
 	    if (strcmp(type, "MEMORY") =3D=3D 0) {
-		ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops,
-				      &handle->ccache);
+		ret =3D krb5_cc_new_unique(context, type,
+					 NULL, &handle->ccache);
 		if (ret) {
 		    *minor_status =3D ret;
 		    goto failure;
@@ -188,20 +175,20 @@
 		    *minor_status =3D ENOMEM;
 		    goto failure;
 		}
-	=09
-		asprintf(&type_name, "%s:%s", type, name);
-		if (type_name =3D=3D NULL) {
+
+		kret =3D asprintf(&type_name, "%s:%s", type, name);
+		if (kret < 0 || type_name =3D=3D NULL) {
 		    *minor_status =3D ENOMEM;
 		    goto failure;
 		}
-	=09
+
 		kret =3D krb5_cc_resolve(context, type_name,
 				       &handle->ccache);
 		free(type_name);
 		if (kret) {
 		    *minor_status =3D kret;
 		    goto failure;
-		}	   =20
+		}
 	    }
 	}
 	ret =3D gss_create_empty_oid_set(minor_status, &handle->mechanisms);
@@ -216,7 +203,7 @@
=20
     HEIMDAL_MUTEX_unlock(&cred->cred_id_mutex);
=20
-    ret =3D _gsskrb5_inquire_cred(minor_status, (gss_cred_id_t)cred,=20
+    ret =3D _gsskrb5_inquire_cred(minor_status, (gss_cred_id_t)cred,
 				NULL, &lifetime, NULL, actual_mechs);
     if (ret)
 	goto failure;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ad=
dress_to_krb5addr.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/address_to_krb5addr.c	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/address_to_krb5addr.c	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2000 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
 #include <roken.h>
=20
@@ -46,32 +46,32 @@
    struct sockaddr sa;
    krb5_socklen_t sa_size =3D sizeof(sa);
    krb5_error_code problem;
-  =20
+
    if (gss_addr =3D=3D NULL)
-      return GSS_S_FAILURE;=20
-  =20
+      return GSS_S_FAILURE;
+
    switch (gss_addr_type) {
 #ifdef HAVE_IPV6
       case GSS_C_AF_INET6: addr_type =3D AF_INET6;
                            break;
 #endif /* HAVE_IPV6 */
-                          =20
+
       case GSS_C_AF_INET:  addr_type =3D AF_INET;
                            break;
       default:
                            return GSS_S_FAILURE;
    }
-                     =20
+
    problem =3D krb5_h_addr2sockaddr (context,
 				   addr_type,
-                                   gss_addr->value,=20
-                                   &sa,=20
-                                   &sa_size,=20
+                                   gss_addr->value,
+                                   &sa,
+                                   &sa_size,
                                    port);
    if (problem)
       return GSS_S_FAILURE;
=20
    problem =3D krb5_sockaddr2address (context, &sa, address);
=20
-   return problem; =20
+   return problem;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ar=
cfour.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/arcfour.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/arcfour.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2003 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: arcfour.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 /*
  * Implements draft-brezak-win2k-krb-rc4-hmac-04.txt
@@ -75,20 +73,20 @@
 		void *key6_data, size_t key6_size)
 {
     krb5_error_code ret;
-   =20
+
     Checksum cksum_k5;
     krb5_keyblock key5;
     char k5_data[16];
-   =20
+
     Checksum cksum_k6;
-   =20
+
     char T[4];
=20
     memset(T, 0, 4);
     cksum_k5.checksum.data =3D k5_data;
     cksum_k5.checksum.length =3D sizeof(k5_data);
=20
-    if (key->keytype =3D=3D KEYTYPE_ARCFOUR_56) {
+    if (key->keytype =3D=3D ENCTYPE_ARCFOUR_HMAC_MD5_56) {
 	char L40[14] =3D "fortybits";
=20
 	memcpy(L40 + 10, T, sizeof(T));
@@ -102,7 +100,7 @@
     if (ret)
 	return ret;
=20
-    key5.keytype =3D KEYTYPE_ARCFOUR;
+    key5.keytype =3D ENCTYPE_ARCFOUR_HMAC_MD5;
     key5.keyvalue =3D cksum_k5.checksum;
=20
     cksum_k6.checksum.data =3D key6_data;
@@ -126,7 +124,7 @@
     size_t len;
     krb5_crypto crypto;
     krb5_error_code ret;
-   =20
+
     assert(sgn_cksum_sz =3D=3D 8);
=20
     len =3D l1 + l2 + l3;
@@ -138,13 +136,13 @@
     memcpy(ptr, v1, l1);
     memcpy(ptr + l1, v2, l2);
     memcpy(ptr + l1 + l2, v3, l3);
-   =20
+
     ret =3D krb5_crypto_init(context, key, 0, &crypto);
     if (ret) {
 	free(ptr);
 	return ret;
     }
-   =20
+
     ret =3D krb5_create_checksum(context,
 			       crypto,
 			       usage,
@@ -175,22 +173,22 @@
     int32_t seq_number;
     size_t len, total_len;
     u_char k6_data[16], *p0, *p;
-    RC4_KEY rc4_key;
-   =20
+    EVP_CIPHER_CTX rc4_key;
+
     _gsskrb5_encap_length (22, &len, &total_len, GSS_KRB5_MECHANISM);
-   =20
+
     message_token->length =3D total_len;
     message_token->value  =3D malloc (total_len);
     if (message_token->value =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
     }
-   =20
+
     p0 =3D _gssapi_make_mech_header(message_token->value,
 				  len,
 				  GSS_KRB5_MECHANISM);
     p =3D p0;
-   =20
+
     *p++ =3D 0x01; /* TOK_ID */
     *p++ =3D 0x01;
     *p++ =3D 0x11; /* SGN_ALG */
@@ -229,20 +227,21 @@
 				     &seq_number);
     p =3D p0 + 8; /* SND_SEQ */
     _gsskrb5_encode_be_om_uint32(seq_number, p);
-   =20
+
     krb5_auth_con_setlocalseqnumber (context,
 				     context_handle->auth_context,
 				     ++seq_number);
     HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
-   =20
+
     memset (p + 4, (context_handle->more_flags & LOCAL) ? 0 : 0xff, 4);
=20
-    RC4_set_key (&rc4_key, sizeof(k6_data), k6_data);
-    RC4 (&rc4_key, 8, p, p);
-=09
-    memset(&rc4_key, 0, sizeof(rc4_key));
+    EVP_CIPHER_CTX_init(&rc4_key);
+    EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+    EVP_Cipher(&rc4_key, p, p, 8);
+    EVP_CIPHER_CTX_cleanup(&rc4_key);
+
     memset(k6_data, 0, sizeof(k6_data));
-   =20
+
     *minor_status =3D 0;
     return GSS_S_COMPLETE;
 }
@@ -256,7 +255,7 @@
 			   const gss_buffer_t token_buffer,
 			   gss_qop_t * qop_state,
 			   krb5_keyblock *key,
-			   char *type)
+			   const char *type)
 {
     krb5_error_code ret;
     uint32_t seq_number;
@@ -264,18 +263,18 @@
     u_char SND_SEQ[8], cksum_data[8], *p;
     char k6_data[16];
     int cmp;
-   =20
+
     if (qop_state)
 	*qop_state =3D 0;
=20
     p =3D token_buffer->value;
     omret =3D _gsskrb5_verify_header (&p,
 				       token_buffer->length,
-				       (u_char *)type,
+				       type,
 				       GSS_KRB5_MECHANISM);
     if (omret)
 	return omret;
-   =20
+
     if (memcmp(p, "\x11\x00", 2) !=3D 0) /* SGN_ALG =3D HMAC MD5 ARCFOUR */
 	return GSS_S_BAD_SIG;
     p +=3D 2;
@@ -302,19 +301,20 @@
 	return GSS_S_FAILURE;
     }
=20
-    cmp =3D memcmp(cksum_data, p + 8, 8);
+    cmp =3D ct_memcmp(cksum_data, p + 8, 8);
     if (cmp) {
 	*minor_status =3D 0;
 	return GSS_S_BAD_MIC;
     }
=20
     {
-	RC4_KEY rc4_key;
-=09
-	RC4_set_key (&rc4_key, sizeof(k6_data), (void*)k6_data);
-	RC4 (&rc4_key, 8, p, SND_SEQ);
-=09
-	memset(&rc4_key, 0, sizeof(rc4_key));
+	EVP_CIPHER_CTX rc4_key;
+
+	EVP_CIPHER_CTX_init(&rc4_key);
+	EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, (void *)k6_data, NULL, 0);
+	EVP_Cipher(&rc4_key, SND_SEQ, p, 8);
+	EVP_CIPHER_CTX_cleanup(&rc4_key);
+
 	memset(k6_data, 0, sizeof(k6_data));
     }
=20
@@ -330,7 +330,7 @@
 	*minor_status =3D 0;
 	return GSS_S_BAD_MIC;
     }
-   =20
+
     HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
     omret =3D _gssapi_msg_order_check(context_handle->order, seq_number);
     HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
@@ -379,7 +379,7 @@
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
     }
-   =20
+
     p0 =3D _gssapi_make_mech_header(output_message_buffer->value,
 				  len,
 				  GSS_KRB5_MECHANISM);
@@ -418,7 +418,7 @@
 	    4);
=20
     krb5_generate_random_block(p0 + 24, 8); /* fill in Confounder */
-   =20
+
     /* p points to data */
     p =3D p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE;
     memcpy(p, input_message_buffer->value, input_message_buffer->length);
@@ -428,10 +428,10 @@
=20
     ret =3D arcfour_mic_cksum(context,
 			    key, KRB5_KU_USAGE_SEAL,
-			    p0 + 16, 8, /* SGN_CKSUM */=20
+			    p0 + 16, 8, /* SGN_CKSUM */
 			    p0, 8, /* TOK_ID, SGN_ALG, SEAL_ALG, Filler */
 			    p0 + 24, 8, /* Confounder */
-			    p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE,=20
+			    p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE,
 			    datalen);
     if (ret) {
 	*minor_status =3D ret;
@@ -461,12 +461,12 @@
=20
=20
     if(conf_req_flag) {
-	RC4_KEY rc4_key;
+	EVP_CIPHER_CTX rc4_key;
=20
-	RC4_set_key (&rc4_key, sizeof(k6_data), (void *)k6_data);
-	/* XXX ? */
-	RC4 (&rc4_key, 8 + datalen, p0 + 24, p0 + 24); /* Confounder + data */
-	memset(&rc4_key, 0, sizeof(rc4_key));
+	EVP_CIPHER_CTX_init(&rc4_key);
+	EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+	EVP_Cipher(&rc4_key, p0 + 24, p0 + 24, 8 + datalen);
+	EVP_CIPHER_CTX_cleanup(&rc4_key);
     }
     memset(k6_data, 0, sizeof(k6_data));
=20
@@ -480,11 +480,12 @@
     }
=20
     {
-	RC4_KEY rc4_key;
-=09
-	RC4_set_key (&rc4_key, sizeof(k6_data), k6_data);
-	RC4 (&rc4_key, 8, p0 + 8, p0 + 8); /* SND_SEQ */
-	memset(&rc4_key, 0, sizeof(rc4_key));
+	EVP_CIPHER_CTX rc4_key;
+
+	EVP_CIPHER_CTX_init(&rc4_key);
+	EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+	EVP_Cipher(&rc4_key, p0 + 8, p0 + 8 /* SND_SEQ */, 8);
+	EVP_CIPHER_CTX_cleanup(&rc4_key);
 	memset(k6_data, 0, sizeof(k6_data));
     }
=20
@@ -516,7 +517,7 @@
     int cmp;
     int conf_flag;
     size_t padlen =3D 0, len;
-   =20
+
     if (conf_state)
 	*conf_state =3D 0;
     if (qop_state)
@@ -525,7 +526,7 @@
     p0 =3D input_message_buffer->value;
=20
     if (IS_DCE_STYLE(context_handle)) {
-	len =3D GSS_ARCFOUR_WRAP_TOKEN_SIZE +=20
+	len =3D GSS_ARCFOUR_WRAP_TOKEN_SIZE +
 	    GSS_ARCFOUR_WRAP_TOKEN_DCE_DER_HEADER_SIZE;
 	if (input_message_buffer->length < len)
 	    return GSS_S_BAD_MECH;
@@ -540,7 +541,7 @@
 	return omret;
=20
     /* length of mech header */
-    len =3D (p0 - (u_char *)input_message_buffer->value) +=20
+    len =3D (p0 - (u_char *)input_message_buffer->value) +
 	GSS_ARCFOUR_WRAP_TOKEN_SIZE;
=20
     if (len > input_message_buffer->length)
@@ -579,11 +580,12 @@
     }
=20
     {
-	RC4_KEY rc4_key;
-=09
-	RC4_set_key (&rc4_key, sizeof(k6_data), k6_data);
-	RC4 (&rc4_key, 8, p0 + 8, SND_SEQ); /* SND_SEQ */
-	memset(&rc4_key, 0, sizeof(rc4_key));
+	EVP_CIPHER_CTX rc4_key;
+
+	EVP_CIPHER_CTX_init(&rc4_key);
+	EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+	EVP_Cipher(&rc4_key, SND_SEQ, p0 + 8, 8);
+	EVP_CIPHER_CTX_cleanup(&rc4_key);
 	memset(k6_data, 0, sizeof(k6_data));
     }
=20
@@ -626,16 +628,16 @@
     output_message_buffer->length =3D datalen;
=20
     if(conf_flag) {
-	RC4_KEY rc4_key;
+	EVP_CIPHER_CTX rc4_key;
=20
-	RC4_set_key (&rc4_key, sizeof(k6_data), k6_data);
-	RC4 (&rc4_key, 8, p0 + 24, Confounder); /* Confounder */
-	RC4 (&rc4_key, datalen, p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE,
-	     output_message_buffer->value);
-	memset(&rc4_key, 0, sizeof(rc4_key));
+	EVP_CIPHER_CTX_init(&rc4_key);
+	EVP_CipherInit_ex(&rc4_key, EVP_rc4(), NULL, k6_data, NULL, 1);
+	EVP_Cipher(&rc4_key, Confounder, p0 + 24, 8);
+	EVP_Cipher(&rc4_key, output_message_buffer->value, p0 + GSS_ARCFOUR_WRAP_=
TOKEN_SIZE, datalen);
+	EVP_CIPHER_CTX_cleanup(&rc4_key);
     } else {
 	memcpy(Confounder, p0 + 24, 8); /* Confounder */
-	memcpy(output_message_buffer->value,=20
+	memcpy(output_message_buffer->value,
 	       p0 + GSS_ARCFOUR_WRAP_TOKEN_SIZE,
 	       datalen);
     }
@@ -654,9 +656,9 @@
     ret =3D arcfour_mic_cksum(context,
 			    key, KRB5_KU_USAGE_SEAL,
 			    cksum_data, sizeof(cksum_data),
-			    p0, 8,=20
+			    p0, 8,
 			    Confounder, sizeof(Confounder),
-			    output_message_buffer->value,=20
+			    output_message_buffer->value,
 			    output_message_buffer->length + padlen);
     if (ret) {
 	_gsskrb5_release_buffer(minor_status, output_message_buffer);
@@ -664,7 +666,7 @@
 	return GSS_S_FAILURE;
     }
=20
-    cmp =3D memcmp(cksum_data, p0 + 16, 8); /* SGN_CKSUM */
+    cmp =3D ct_memcmp(cksum_data, p0 + 16, 8); /* SGN_CKSUM */
     if (cmp) {
 	_gsskrb5_release_buffer(minor_status, output_message_buffer);
 	*minor_status =3D 0;
@@ -690,10 +692,10 @@
 			size_t input_length,
 			OM_uint32 *max_input_size)
 {
-    /*=20
+    /*
      * if GSS_C_DCE_STYLE is in use:
      *  - we only need to encapsulate the WRAP token
-     * However, since this is a fixed since, we just=20
+     * However, since this is a fixed since, we just
      */
     if (IS_DCE_STYLE(ctx)) {
 	size_t len, total_len;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ca=
nonicalize_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/canonicalize_name.c	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/canonicalize_name.c	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,46 +1,58 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: canonicalize_name.c 18334 2006-10-07 22:16:04Z lha $");
-
-OM_uint32 _gsskrb5_canonicalize_name (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_canonicalize_name (
             OM_uint32 * minor_status,
             const gss_name_t input_name,
             const gss_OID mech_type,
             gss_name_t * output_name
            )
 {
-    return _gsskrb5_duplicate_name (minor_status, input_name, output_name);
+    krb5_context context;
+    krb5_principal name;
+    OM_uint32 ret;
+
+    *output_name =3D NULL;
+
+    GSSAPI_KRB5_INIT (&context);
+
+    ret =3D _gsskrb5_canon_name(minor_status, context, 1, NULL, input_name=
, &name);
+    if (ret)
+	return ret;
+
+    *output_name =3D (gss_name_t)name;
+
+    return GSS_S_COMPLETE;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/cc=
ache_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/ccache_name.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/ccache_name.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,44 +1,42 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: ccache_name.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 char *last_out_name;
=20
 OM_uint32
-_gsskrb5_krb5_ccache_name(OM_uint32 *minor_status,=20
+_gsskrb5_krb5_ccache_name(OM_uint32 *minor_status,
 			  const char *name,
 			  const char **out_name)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/cf=
x.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/cfx.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/cfx.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -30,12 +30,10 @@
  * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: cfx.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 /*
- * Implementation of draft-ietf-krb-wg-gssapi-cfx-06.txt
+ * Implementation of RFC 4121
  */
=20
 #define CFXSentByAcceptor	(1 << 0)
@@ -46,6 +44,7 @@
 _gsskrb5cfx_wrap_length_cfx(krb5_context context,
 			    krb5_crypto crypto,
 			    int conf_req_flag,
+			    int dce_style,
 			    size_t input_length,
 			    size_t *output_length,
 			    size_t *cksumsize,
@@ -72,7 +71,11 @@
 	/* Header is concatenated with data before encryption */
 	input_length +=3D sizeof(gss_cfx_wrap_token_desc);
=20
-	ret =3D krb5_crypto_getpadsize(context, crypto, &padsize);
+	if (dce_style) {
+		ret =3D krb5_crypto_getblocksize(context, crypto, &padsize);
+	} else {
+		ret =3D krb5_crypto_getpadsize(context, crypto, &padsize);
+	}
 	if (ret) {
 	    return ret;
 	}
@@ -96,49 +99,48 @@
     return 0;
 }
=20
-krb5_error_code
-_gsskrb5cfx_max_wrap_length_cfx(krb5_context context,
-				krb5_crypto crypto,
-				int conf_req_flag,
-				size_t input_length,
-				OM_uint32 *output_length)
+OM_uint32
+_gssapi_wrap_size_cfx(OM_uint32 *minor_status,
+		      const gsskrb5_ctx ctx,
+		      krb5_context context,
+		      int conf_req_flag,
+		      gss_qop_t qop_req,
+		      OM_uint32 req_output_size,
+		      OM_uint32 *max_input_size)
 {
     krb5_error_code ret;
=20
-    *output_length =3D 0;
+    *max_input_size =3D 0;
=20
     /* 16-byte header is always first */
-    if (input_length < 16)
+    if (req_output_size < 16)
 	return 0;
-    input_length -=3D 16;
+    req_output_size -=3D 16;
=20
     if (conf_req_flag) {
 	size_t wrapped_size, sz;
=20
-	wrapped_size =3D input_length + 1;
+	wrapped_size =3D req_output_size + 1;
 	do {
 	    wrapped_size--;
-	    sz =3D krb5_get_wrapped_length(context,=20
-					 crypto, wrapped_size);
-	} while (wrapped_size && sz > input_length);
-	if (wrapped_size =3D=3D 0) {
-	    *output_length =3D 0;
+	    sz =3D krb5_get_wrapped_length(context,
+					 ctx->crypto, wrapped_size);
+	} while (wrapped_size && sz > req_output_size);
+	if (wrapped_size =3D=3D 0)
 	    return 0;
-	}
=20
 	/* inner header */
-	if (wrapped_size < 16) {
-	    *output_length =3D 0;
+	if (wrapped_size < 16)
 	    return 0;
-	}
+
 	wrapped_size -=3D 16;
=20
-	*output_length =3D wrapped_size;
+	*max_input_size =3D wrapped_size;
     } else {
 	krb5_cksumtype type;
 	size_t cksumsize;
=20
-	ret =3D krb5_crypto_get_checksum_type(context, crypto, &type);
+	ret =3D krb5_crypto_get_checksum_type(context, ctx->crypto, &type);
 	if (ret)
 	    return ret;
=20
@@ -146,48 +148,16 @@
 	if (ret)
 	    return ret;
=20
-	if (input_length < cksumsize)
+	if (req_output_size < cksumsize)
 	    return 0;
=20
 	/* Checksum is concatenated with data */
-	*output_length =3D input_length - cksumsize;
+	*max_input_size =3D req_output_size - cksumsize;
     }
=20
     return 0;
 }
=20
-
-OM_uint32 _gssapi_wrap_size_cfx(OM_uint32 *minor_status,
-				const gsskrb5_ctx context_handle,
-				krb5_context context,
-				int conf_req_flag,
-				gss_qop_t qop_req,
-				OM_uint32 req_output_size,
-				OM_uint32 *max_input_size,
-				krb5_keyblock *key)
-{
-    krb5_error_code ret;
-    krb5_crypto crypto;
-
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret !=3D 0) {
-	*minor_status =3D ret;
-	return GSS_S_FAILURE;
-    }
-
-    ret =3D _gsskrb5cfx_max_wrap_length_cfx(context, crypto, conf_req_flag=
,=20
-					  req_output_size, max_input_size);
-    if (ret !=3D 0) {
-	*minor_status =3D ret;
-	krb5_crypto_destroy(context, crypto);
-	return GSS_S_FAILURE;
-    }
-
-    krb5_crypto_destroy(context, crypto);
-
-    return GSS_S_COMPLETE;
-}
-
 /*
  * Rotate "rrc" bytes to the front or back
  */
@@ -212,10 +182,10 @@
 	tmp =3D buf;
     } else {
 	tmp =3D malloc(rrc);
-	if (tmp =3D=3D NULL)=20
+	if (tmp =3D=3D NULL)
 	    return ENOMEM;
     }
-=20
+
     if (unrotate) {
 	memcpy(tmp, data, rrc);
 	memmove(data, (u_char *)data + rrc, left);
@@ -226,23 +196,975 @@
 	memcpy(data, tmp, rrc);
     }
=20
-    if (rrc > sizeof(buf))=20
+    if (rrc > sizeof(buf))
 	free(tmp);
=20
     return 0;
 }
=20
+gss_iov_buffer_desc *
+_gk_find_buffer(gss_iov_buffer_desc *iov, int iov_count, OM_uint32 type)
+{
+    int i;
+
+    for (i =3D 0; i < iov_count; i++)
+	if (type =3D=3D GSS_IOV_BUFFER_TYPE(iov[i].type))
+	    return &iov[i];
+    return NULL;
+}
+
+OM_uint32
+_gk_allocate_buffer(OM_uint32 *minor_status, gss_iov_buffer_desc *buffer, =
size_t size)
+{
+    if (buffer->type & GSS_IOV_BUFFER_FLAG_ALLOCATED) {
+	if (buffer->buffer.length =3D=3D size)
+	    return GSS_S_COMPLETE;
+	free(buffer->buffer.value);
+    }
+
+    buffer->buffer.value =3D malloc(size);
+    buffer->buffer.length =3D size;
+    if (buffer->buffer.value =3D=3D NULL) {
+	*minor_status =3D ENOMEM;
+	return GSS_S_FAILURE;
+    }
+    buffer->type |=3D GSS_IOV_BUFFER_FLAG_ALLOCATED;
+
+    return GSS_S_COMPLETE;
+}
+
+
+OM_uint32
+_gk_verify_buffers(OM_uint32 *minor_status,
+		   const gsskrb5_ctx ctx,
+		   const gss_iov_buffer_desc *header,
+		   const gss_iov_buffer_desc *padding,
+		   const gss_iov_buffer_desc *trailer)
+{
+    if (header =3D=3D NULL) {
+	*minor_status =3D EINVAL;
+	return GSS_S_FAILURE;
+    }
+
+    if (IS_DCE_STYLE(ctx)) {
+	/*
+	 * In DCE style mode we reject having a padding or trailer buffer
+	 */
+	if (padding) {
+	    *minor_status =3D EINVAL;
+	    return GSS_S_FAILURE;
+	}
+	if (trailer) {
+	    *minor_status =3D EINVAL;
+	    return GSS_S_FAILURE;
+	}
+    } else {
+	/*
+	 * In non-DCE style mode we require having a padding buffer
+	 */
+	if (padding =3D=3D NULL) {
+	    *minor_status =3D EINVAL;
+	    return GSS_S_FAILURE;
+	}
+    }
+
+    *minor_status =3D 0;
+    return GSS_S_COMPLETE;
+}
+
+#if 0
+OM_uint32
+_gssapi_wrap_cfx_iov(OM_uint32 *minor_status,
+		     gsskrb5_ctx ctx,
+		     krb5_context context,
+		     int conf_req_flag,
+		     int *conf_state,
+		     gss_iov_buffer_desc *iov,
+		     int iov_count)
+{
+    OM_uint32 major_status, junk;
+    gss_iov_buffer_desc *header, *trailer, *padding;
+    size_t gsshsize, k5hsize;
+    size_t gsstsize, k5tsize;
+    size_t rrc =3D 0, ec =3D 0;
+    int i;
+    gss_cfx_wrap_token token;
+    krb5_error_code ret;
+    int32_t seq_number;
+    unsigned usage;
+    krb5_crypto_iov *data =3D NULL;
+
+    header =3D _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+    if (header =3D=3D NULL) {
+	*minor_status =3D EINVAL;
+	return GSS_S_FAILURE;
+    }
+
+    padding =3D _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDIN=
G);
+    if (padding !=3D NULL) {
+	padding->buffer.length =3D 0;
+    }
+
+    trailer =3D _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILE=
R);
+
+    major_status =3D _gk_verify_buffers(minor_status, ctx, header, padding=
, trailer);
+    if (major_status !=3D GSS_S_COMPLETE) {
+	    return major_status;
+    }
+
+    if (conf_req_flag) {
+	size_t k5psize =3D 0;
+	size_t k5pbase =3D 0;
+	size_t k5bsize =3D 0;
+	size_t size =3D 0;
+
+	for (i =3D 0; i < iov_count; i++) {
+	    switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+	    case GSS_IOV_BUFFER_TYPE_DATA:
+		size +=3D iov[i].buffer.length;
+		break;
+	    default:
+		break;
+	    }
+	}
+
+	size +=3D sizeof(gss_cfx_wrap_token_desc);
+
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_HEADER,
+					   &k5hsize);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_TRAILER,
+					   &k5tsize);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_PADDING,
+					   &k5pbase);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	if (k5pbase > 1) {
+	    k5psize =3D k5pbase - (size % k5pbase);
+	} else {
+	    k5psize =3D 0;
+	}
+
+	if (k5psize =3D=3D 0 && IS_DCE_STYLE(ctx)) {
+	    *minor_status =3D krb5_crypto_getblocksize(context, ctx->crypto,
+						     &k5bsize);
+	    if (*minor_status)
+		return GSS_S_FAILURE;
+	    ec =3D k5bsize;
+	} else {
+	    ec =3D k5psize;
+	}
+
+	gsshsize =3D sizeof(gss_cfx_wrap_token_desc) + k5hsize;
+	gsstsize =3D sizeof(gss_cfx_wrap_token_desc) + ec + k5tsize;
+    } else {
+	if (IS_DCE_STYLE(ctx)) {
+	    *minor_status =3D EINVAL;
+	    return GSS_S_FAILURE;
+	}
+
+	k5hsize =3D 0;
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_CHECKSUM,
+					   &k5tsize);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	gsshsize =3D sizeof(gss_cfx_wrap_token_desc);
+	gsstsize =3D k5tsize;
+    }
+
+    /*
+     *
+     */
+
+    if (trailer =3D=3D NULL) {
+	rrc =3D gsstsize;
+	if (IS_DCE_STYLE(ctx))
+	    rrc -=3D ec;
+	gsshsize +=3D gsstsize;
+	gsstsize =3D 0;
+    } else if (GSS_IOV_BUFFER_FLAGS(trailer->type) & GSS_IOV_BUFFER_FLAG_A=
LLOCATE) {
+	major_status =3D _gk_allocate_buffer(minor_status, trailer, gsstsize);
+	if (major_status)
+	    goto failure;
+    } else if (trailer->buffer.length < gsstsize) {
+	*minor_status =3D KRB5_BAD_MSIZE;
+	major_status =3D GSS_S_FAILURE;
+	goto failure;
+    } else
+	trailer->buffer.length =3D gsstsize;
+
+    /*
+     *
+     */
+
+    if (GSS_IOV_BUFFER_FLAGS(header->type) & GSS_IOV_BUFFER_FLAG_ALLOCATE)=
 {
+	major_status =3D _gk_allocate_buffer(minor_status, header, gsshsize);
+	if (major_status !=3D GSS_S_COMPLETE)
+	    goto failure;
+    } else if (header->buffer.length < gsshsize) {
+	*minor_status =3D KRB5_BAD_MSIZE;
+	major_status =3D GSS_S_FAILURE;
+	goto failure;
+    } else
+	header->buffer.length =3D gsshsize;
+
+    token =3D (gss_cfx_wrap_token)header->buffer.value;
+
+    token->TOK_ID[0] =3D 0x05;
+    token->TOK_ID[1] =3D 0x04;
+    token->Flags     =3D 0;
+    token->Filler    =3D 0xFF;
+
+    if ((ctx->more_flags & LOCAL) =3D=3D 0)
+	token->Flags |=3D CFXSentByAcceptor;
+
+    if (ctx->more_flags & ACCEPTOR_SUBKEY)
+	token->Flags |=3D CFXAcceptorSubkey;
+
+    if (ctx->more_flags & LOCAL)
+	usage =3D KRB5_KU_USAGE_INITIATOR_SEAL;
+    else
+	usage =3D KRB5_KU_USAGE_ACCEPTOR_SEAL;
+
+    if (conf_req_flag) {
+	/*
+	 * In Wrap tokens with confidentiality, the EC field is
+	 * used to encode the size (in bytes) of the random filler.
+	 */
+	token->Flags |=3D CFXSealed;
+	token->EC[0] =3D (ec >> 8) & 0xFF;
+	token->EC[1] =3D (ec >> 0) & 0xFF;
+
+    } else {
+	/*
+	 * In Wrap tokens without confidentiality, the EC field is
+	 * used to encode the size (in bytes) of the trailing
+	 * checksum.
+	 *
+	 * This is not used in the checksum calcuation itself,
+	 * because the checksum length could potentially vary
+	 * depending on the data length.
+	 */
+	token->EC[0] =3D 0;
+	token->EC[1] =3D 0;
+    }
+
+    /*
+     * In Wrap tokens that provide for confidentiality, the RRC
+     * field in the header contains the hex value 00 00 before
+     * encryption.
+     *
+     * In Wrap tokens that do not provide for confidentiality,
+     * both the EC and RRC fields in the appended checksum
+     * contain the hex value 00 00 for the purpose of calculating
+     * the checksum.
+     */
+    token->RRC[0] =3D 0;
+    token->RRC[1] =3D 0;
+
+    HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+    krb5_auth_con_getlocalseqnumber(context,
+				    ctx->auth_context,
+				    &seq_number);
+    _gsskrb5_encode_be_om_uint32(0,          &token->SND_SEQ[0]);
+    _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]);
+    krb5_auth_con_setlocalseqnumber(context,
+				    ctx->auth_context,
+				    ++seq_number);
+    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+    data =3D calloc(iov_count + 3, sizeof(data[0]));
+    if (data =3D=3D NULL) {
+	*minor_status =3D ENOMEM;
+	major_status =3D GSS_S_FAILURE;
+	goto failure;
+    }
+
+    if (conf_req_flag) {
+	/*
+	  plain packet:
+
+	  {"header" | encrypt(plaintext-data | ec-padding | E"header")}
+
+	  Expanded, this is with with RRC =3D 0:
+
+	  {"header" | krb5-header | plaintext-data | ec-padding | E"header" | krb=
5-trailer }
+
+	  In DCE-RPC mode =3D=3D no trailer: RRC =3D gss "trailer" =3D=3D length(=
ec-padding | E"header" | krb5-trailer)
+
+	  {"header" | ec-padding | E"header" | krb5-trailer | krb5-header | plain=
text-data  }
+	 */
+
+	i =3D 0;
+	data[i].flags =3D KRB5_CRYPTO_TYPE_HEADER;
+	data[i].data.data =3D ((uint8_t *)header->buffer.value) + header->buffer.=
length - k5hsize;
+	data[i].data.length =3D k5hsize;
+
+	for (i =3D 1; i < iov_count + 1; i++) {
+	    switch (GSS_IOV_BUFFER_TYPE(iov[i - 1].type)) {
+	    case GSS_IOV_BUFFER_TYPE_DATA:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+		break;
+	    case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_SIGN_ONLY;
+		break;
+	    default:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_EMPTY;
+		break;
+	    }
+	    data[i].data.length =3D iov[i - 1].buffer.length;
+	    data[i].data.data =3D iov[i - 1].buffer.value;
+	}
+
+	/*
+	 * Any necessary padding is added here to ensure that the
+	 * encrypted token header is always at the end of the
+	 * ciphertext.
+	 */
+
+	/* encrypted CFX header in trailer (or after the header if in
+	   DCE mode). Copy in header into E"header"
+	*/
+	data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+	if (trailer)
+	    data[i].data.data =3D trailer->buffer.value;
+	else
+	    data[i].data.data =3D ((uint8_t *)header->buffer.value) + sizeof(*tok=
en);
+
+	data[i].data.length =3D ec + sizeof(*token);
+	memset(data[i].data.data, 0xFF, ec);
+	memcpy(((uint8_t *)data[i].data.data) + ec, token, sizeof(*token));
+	i++;
+
+	/* Kerberos trailer comes after the gss trailer */
+	data[i].flags =3D KRB5_CRYPTO_TYPE_TRAILER;
+	data[i].data.data =3D ((uint8_t *)data[i-1].data.data) + ec + sizeof(*tok=
en);
+	data[i].data.length =3D k5tsize;
+	i++;
+
+	ret =3D krb5_encrypt_iov_ivec(context, ctx->crypto, usage, data, i, NULL);
+	if (ret !=3D 0) {
+	    *minor_status =3D ret;
+	    major_status =3D GSS_S_FAILURE;
+	    goto failure;
+	}
+
+	if (rrc) {
+	    token->RRC[0] =3D (rrc >> 8) & 0xFF;
+	    token->RRC[1] =3D (rrc >> 0) & 0xFF;
+	}
+
+    } else {
+	/*
+	  plain packet:
+
+	  {data | "header" | gss-trailer (krb5 checksum)
+
+	  don't do RRC !=3D 0
+
+	 */
+
+	for (i =3D 0; i < iov_count; i++) {
+	    switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+	    case GSS_IOV_BUFFER_TYPE_DATA:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+		break;
+	    case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_SIGN_ONLY;
+		break;
+	    default:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_EMPTY;
+		break;
+	    }
+	    data[i].data.length =3D iov[i].buffer.length;
+	    data[i].data.data =3D iov[i].buffer.value;
+	}
+
+	data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+	data[i].data.data =3D header->buffer.value;
+	data[i].data.length =3D sizeof(gss_cfx_wrap_token_desc);
+	i++;
+
+	data[i].flags =3D KRB5_CRYPTO_TYPE_CHECKSUM;
+	if (trailer) {
+		data[i].data.data =3D trailer->buffer.value;
+	} else {
+		data[i].data.data =3D (uint8_t *)header->buffer.value +
+				     sizeof(gss_cfx_wrap_token_desc);
+	}
+	data[i].data.length =3D k5tsize;
+	i++;
+
+	ret =3D krb5_create_checksum_iov(context, ctx->crypto, usage, data, i, NU=
LL);
+	if (ret) {
+	    *minor_status =3D ret;
+	    major_status =3D GSS_S_FAILURE;
+	    goto failure;
+	}
+
+	if (rrc) {
+	    token->RRC[0] =3D (rrc >> 8) & 0xFF;
+	    token->RRC[1] =3D (rrc >> 0) & 0xFF;
+	}
+
+	token->EC[0] =3D  (k5tsize >> 8) & 0xFF;
+	token->EC[1] =3D  (k5tsize >> 0) & 0xFF;
+    }
+
+    if (conf_state !=3D NULL)
+	*conf_state =3D conf_req_flag;
+
+    free(data);
+
+    *minor_status =3D 0;
+    return GSS_S_COMPLETE;
+
+ failure:
+    if (data)
+	free(data);
+
+    gss_release_iov_buffer(&junk, iov, iov_count);
+
+    return major_status;
+}
+#endif
+
+/* This is slowpath */
+static OM_uint32
+unrotate_iov(OM_uint32 *minor_status, size_t rrc, gss_iov_buffer_desc *iov=
, int iov_count)
+{
+    uint8_t *p, *q;
+    size_t len =3D 0, skip;
+    int i;
+
+    for (i =3D 0; i < iov_count; i++)
+	if (GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_DATA ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_PADDING ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_TRAILER)
+	    len +=3D iov[i].buffer.length;
+
+    p =3D malloc(len);
+    if (p =3D=3D NULL) {
+	*minor_status =3D ENOMEM;
+	return GSS_S_FAILURE;
+    }
+    q =3D p;
+
+    /* copy up */
+
+    for (i =3D 0; i < iov_count; i++) {
+	if (GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_DATA ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_PADDING ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_TRAILER)
+	{
+	    memcpy(q, iov[i].buffer.value, iov[i].buffer.length);
+	    q +=3D iov[i].buffer.length;
+	}
+    }
+    assert((size_t)(q - p) =3D=3D len);
+
+    /* unrotate first part */
+    q =3D p + rrc;
+    skip =3D rrc;
+    for (i =3D 0; i < iov_count; i++) {
+	if (GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_DATA ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_PADDING ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_TRAILER)
+	{
+	    if (iov[i].buffer.length <=3D skip) {
+		skip -=3D iov[i].buffer.length;
+	    } else {
+		memcpy(((uint8_t *)iov[i].buffer.value) + skip, q, iov[i].buffer.length =
- skip);
+		q +=3D iov[i].buffer.length - skip;
+		skip =3D 0;
+	    }
+	}
+    }
+    /* copy trailer */
+    q =3D p;
+    skip =3D rrc;
+    for (i =3D 0; i < iov_count; i++) {
+	if (GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_DATA ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_PADDING ||
+	    GSS_IOV_BUFFER_TYPE(iov[i].type) =3D=3D GSS_IOV_BUFFER_TYPE_TRAILER)
+	{
+	    memcpy(q, iov[i].buffer.value, min(iov[i].buffer.length, skip));
+	    if (iov[i].buffer.length > skip)
+		break;
+	    skip -=3D iov[i].buffer.length;
+	    q +=3D iov[i].buffer.length;
+	}
+    }
+    return GSS_S_COMPLETE;
+}
+
+#if 0
+
+OM_uint32
+_gssapi_unwrap_cfx_iov(OM_uint32 *minor_status,
+		       gsskrb5_ctx ctx,
+		       krb5_context context,
+		       int *conf_state,
+		       gss_qop_t *qop_state,
+		       gss_iov_buffer_desc *iov,
+		       int iov_count)
+{
+    OM_uint32 seq_number_lo, seq_number_hi, major_status, junk;
+    gss_iov_buffer_desc *header, *trailer, *padding;
+    gss_cfx_wrap_token token, ttoken;
+    u_char token_flags;
+    krb5_error_code ret;
+    unsigned usage;
+    uint16_t ec, rrc;
+    krb5_crypto_iov *data =3D NULL;
+    int i, j;
+
+    *minor_status =3D 0;
+
+    header =3D _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_HEADER);
+    if (header =3D=3D NULL) {
+	*minor_status =3D EINVAL;
+	return GSS_S_FAILURE;
+    }
+
+    if (header->buffer.length < sizeof(*token)) /* we check exact below */
+	return GSS_S_DEFECTIVE_TOKEN;
+
+    padding =3D _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_PADDIN=
G);
+    if (padding !=3D NULL && padding->buffer.length !=3D 0) {
+	*minor_status =3D EINVAL;
+	return GSS_S_FAILURE;
+    }
+
+    trailer =3D _gk_find_buffer(iov, iov_count, GSS_IOV_BUFFER_TYPE_TRAILE=
R);
+
+    major_status =3D _gk_verify_buffers(minor_status, ctx, header, padding=
, trailer);
+    if (major_status !=3D GSS_S_COMPLETE) {
+	    return major_status;
+    }
+
+    token =3D (gss_cfx_wrap_token)header->buffer.value;
+
+    if (token->TOK_ID[0] !=3D 0x05 || token->TOK_ID[1] !=3D 0x04)
+	return GSS_S_DEFECTIVE_TOKEN;
+
+    /* Ignore unknown flags */
+    token_flags =3D token->Flags &
+	(CFXSentByAcceptor | CFXSealed | CFXAcceptorSubkey);
+
+    if (token_flags & CFXSentByAcceptor) {
+	if ((ctx->more_flags & LOCAL) =3D=3D 0)
+	    return GSS_S_DEFECTIVE_TOKEN;
+    }
+
+    if (ctx->more_flags & ACCEPTOR_SUBKEY) {
+	if ((token_flags & CFXAcceptorSubkey) =3D=3D 0)
+	    return GSS_S_DEFECTIVE_TOKEN;
+    } else {
+	if (token_flags & CFXAcceptorSubkey)
+	    return GSS_S_DEFECTIVE_TOKEN;
+    }
+
+    if (token->Filler !=3D 0xFF)
+	return GSS_S_DEFECTIVE_TOKEN;
+
+    if (conf_state !=3D NULL)
+	*conf_state =3D (token_flags & CFXSealed) ? 1 : 0;
+
+    ec  =3D (token->EC[0]  << 8) | token->EC[1];
+    rrc =3D (token->RRC[0] << 8) | token->RRC[1];
+
+    /*
+     * Check sequence number
+     */
+    _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[0], &seq_number_hi);
+    _gsskrb5_decode_be_om_uint32(&token->SND_SEQ[4], &seq_number_lo);
+    if (seq_number_hi) {
+	/* no support for 64-bit sequence numbers */
+	*minor_status =3D ERANGE;
+	return GSS_S_UNSEQ_TOKEN;
+    }
+
+    HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+    ret =3D _gssapi_msg_order_check(ctx->order, seq_number_lo);
+    if (ret !=3D 0) {
+	*minor_status =3D 0;
+	HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+	return ret;
+    }
+    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
+
+    /*
+     * Decrypt and/or verify checksum
+     */
+
+    if (ctx->more_flags & LOCAL) {
+	usage =3D KRB5_KU_USAGE_ACCEPTOR_SEAL;
+    } else {
+	usage =3D KRB5_KU_USAGE_INITIATOR_SEAL;
+    }
+
+    data =3D calloc(iov_count + 3, sizeof(data[0]));
+    if (data =3D=3D NULL) {
+	*minor_status =3D ENOMEM;
+	major_status =3D GSS_S_FAILURE;
+	goto failure;
+    }
+
+    if (token_flags & CFXSealed) {
+	size_t k5tsize, k5hsize;
+
+	krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_HEADER, &k5hsiz=
e);
+	krb5_crypto_length(context, ctx->crypto, KRB5_CRYPTO_TYPE_TRAILER, &k5tsi=
ze);
+
+	/* Rotate by RRC; bogus to do this in-place XXX */
+	/* Check RRC */
+
+	if (trailer =3D=3D NULL) {
+	    size_t gsstsize =3D k5tsize + sizeof(*token);
+	    size_t gsshsize =3D k5hsize + sizeof(*token);
+
+	    if (rrc !=3D gsstsize) {
+		major_status =3D GSS_S_DEFECTIVE_TOKEN;
+		goto failure;
+	    }
+
+	    if (IS_DCE_STYLE(ctx))
+		gsstsize +=3D ec;
+
+	    gsshsize +=3D gsstsize;
+
+	    if (header->buffer.length !=3D gsshsize) {
+		major_status =3D GSS_S_DEFECTIVE_TOKEN;
+		goto failure;
+	    }
+	} else if (trailer->buffer.length !=3D sizeof(*token) + k5tsize) {
+	    major_status =3D GSS_S_DEFECTIVE_TOKEN;
+	    goto failure;
+	} else if (header->buffer.length !=3D sizeof(*token) + k5hsize) {
+	    major_status =3D GSS_S_DEFECTIVE_TOKEN;
+	    goto failure;
+	} else if (rrc !=3D 0) {
+	    /* go though slowpath */
+	    major_status =3D unrotate_iov(minor_status, rrc, iov, iov_count);
+	    if (major_status)
+		goto failure;
+	}
+
+	i =3D 0;
+	data[i].flags =3D KRB5_CRYPTO_TYPE_HEADER;
+	data[i].data.data =3D ((uint8_t *)header->buffer.value) + header->buffer.=
length - k5hsize;
+	data[i].data.length =3D k5hsize;
+	i++;
+
+	for (j =3D 0; j < iov_count; i++, j++) {
+	    switch (GSS_IOV_BUFFER_TYPE(iov[j].type)) {
+	    case GSS_IOV_BUFFER_TYPE_DATA:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+		break;
+	    case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_SIGN_ONLY;
+		break;
+	    default:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_EMPTY;
+		break;
+	    }
+	    data[i].data.length =3D iov[j].buffer.length;
+	    data[i].data.data =3D iov[j].buffer.value;
+	}
+
+	/* encrypted CFX header in trailer (or after the header if in
+	   DCE mode). Copy in header into E"header"
+	*/
+	data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+	if (trailer) {
+	    data[i].data.data =3D trailer->buffer.value;
+	} else {
+	    data[i].data.data =3D ((uint8_t *)header->buffer.value) +
+		header->buffer.length - k5hsize - k5tsize - ec- sizeof(*token);
+	}
+
+	data[i].data.length =3D ec + sizeof(*token);
+	ttoken =3D (gss_cfx_wrap_token)(((uint8_t *)data[i].data.data) + ec);
+	i++;
+
+	/* Kerberos trailer comes after the gss trailer */
+	data[i].flags =3D KRB5_CRYPTO_TYPE_TRAILER;
+	data[i].data.data =3D ((uint8_t *)data[i-1].data.data) + ec + sizeof(*tok=
en);
+	data[i].data.length =3D k5tsize;
+	i++;
+
+	ret =3D krb5_decrypt_iov_ivec(context, ctx->crypto, usage, data, i, NULL);
+	if (ret !=3D 0) {
+	    *minor_status =3D ret;
+	    major_status =3D GSS_S_FAILURE;
+	    goto failure;
+	}
+
+	ttoken->RRC[0] =3D token->RRC[0];
+	ttoken->RRC[1] =3D token->RRC[1];
+
+	/* Check the integrity of the header */
+	if (ct_memcmp(ttoken, token, sizeof(*token)) !=3D 0) {
+	    major_status =3D GSS_S_BAD_MIC;
+	    goto failure;
+	}
+    } else {
+	size_t gsstsize =3D ec;
+	size_t gsshsize =3D sizeof(*token);
+
+	if (trailer =3D=3D NULL) {
+	    /* Check RRC */
+	    if (rrc !=3D gsstsize) {
+	       *minor_status =3D EINVAL;
+	       major_status =3D GSS_S_FAILURE;
+	       goto failure;
+	    }
+
+	    gsshsize +=3D gsstsize;
+	    gsstsize =3D 0;
+	} else if (trailer->buffer.length !=3D gsstsize) {
+	    major_status =3D GSS_S_DEFECTIVE_TOKEN;
+	    goto failure;
+	} else if (rrc !=3D 0) {
+	    /* Check RRC */
+	    *minor_status =3D EINVAL;
+	    major_status =3D GSS_S_FAILURE;
+	    goto failure;
+	}
+
+	if (header->buffer.length !=3D gsshsize) {
+	    major_status =3D GSS_S_DEFECTIVE_TOKEN;
+	    goto failure;
+	}
+
+	for (i =3D 0; i < iov_count; i++) {
+	    switch (GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+	    case GSS_IOV_BUFFER_TYPE_DATA:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+		break;
+	    case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_SIGN_ONLY;
+		break;
+	    default:
+		data[i].flags =3D KRB5_CRYPTO_TYPE_EMPTY;
+		break;
+	    }
+	    data[i].data.length =3D iov[i].buffer.length;
+	    data[i].data.data =3D iov[i].buffer.value;
+	}
+
+	data[i].flags =3D KRB5_CRYPTO_TYPE_DATA;
+	data[i].data.data =3D header->buffer.value;
+	data[i].data.length =3D sizeof(*token);
+	i++;
+
+	data[i].flags =3D KRB5_CRYPTO_TYPE_CHECKSUM;
+	if (trailer) {
+		data[i].data.data =3D trailer->buffer.value;
+	} else {
+		data[i].data.data =3D (uint8_t *)header->buffer.value +
+				     sizeof(*token);
+	}
+	data[i].data.length =3D ec;
+	i++;
+
+	token =3D (gss_cfx_wrap_token)header->buffer.value;
+	token->EC[0]  =3D 0;
+	token->EC[1]  =3D 0;
+	token->RRC[0] =3D 0;
+	token->RRC[1] =3D 0;
+
+	ret =3D krb5_verify_checksum_iov(context, ctx->crypto, usage, data, i, NU=
LL);
+	if (ret) {
+	    *minor_status =3D ret;
+	    major_status =3D GSS_S_FAILURE;
+	    goto failure;
+	}
+    }
+
+    if (qop_state !=3D NULL) {
+	*qop_state =3D GSS_C_QOP_DEFAULT;
+    }
+
+    free(data);
+
+    *minor_status =3D 0;
+    return GSS_S_COMPLETE;
+
+ failure:
+    if (data)
+	free(data);
+
+    gss_release_iov_buffer(&junk, iov, iov_count);
+
+    return major_status;
+}
+#endif
+
+OM_uint32
+_gssapi_wrap_iov_length_cfx(OM_uint32 *minor_status,
+			    gsskrb5_ctx ctx,
+			    krb5_context context,
+			    int conf_req_flag,
+			    gss_qop_t qop_req,
+			    int *conf_state,
+			    gss_iov_buffer_desc *iov,
+			    int iov_count)
+{
+    OM_uint32 major_status;
+    size_t size;
+    int i;
+    gss_iov_buffer_desc *header =3D NULL;
+    gss_iov_buffer_desc *padding =3D NULL;
+    gss_iov_buffer_desc *trailer =3D NULL;
+    size_t gsshsize =3D 0;
+    size_t gsstsize =3D 0;
+    size_t k5hsize =3D 0;
+    size_t k5tsize =3D 0;
+
+    GSSAPI_KRB5_INIT (&context);
+    *minor_status =3D 0;
+
+    for (size =3D 0, i =3D 0; i < iov_count; i++) {
+	switch(GSS_IOV_BUFFER_TYPE(iov[i].type)) {
+	case GSS_IOV_BUFFER_TYPE_EMPTY:
+	    break;
+	case GSS_IOV_BUFFER_TYPE_DATA:
+	    size +=3D iov[i].buffer.length;
+	    break;
+	case GSS_IOV_BUFFER_TYPE_HEADER:
+	    if (header !=3D NULL) {
+		*minor_status =3D 0;
+		return GSS_S_FAILURE;
+	    }
+	    header =3D &iov[i];
+	    break;
+	case GSS_IOV_BUFFER_TYPE_TRAILER:
+	    if (trailer !=3D NULL) {
+		*minor_status =3D 0;
+		return GSS_S_FAILURE;
+	    }
+	    trailer =3D &iov[i];
+	    break;
+	case GSS_IOV_BUFFER_TYPE_PADDING:
+	    if (padding !=3D NULL) {
+		*minor_status =3D 0;
+		return GSS_S_FAILURE;
+	    }
+	    padding =3D &iov[i];
+	    break;
+	case GSS_IOV_BUFFER_TYPE_SIGN_ONLY:
+	    break;
+	default:
+	    *minor_status =3D EINVAL;
+	    return GSS_S_FAILURE;
+	}
+    }
+
+    major_status =3D _gk_verify_buffers(minor_status, ctx, header, padding=
, trailer);
+    if (major_status !=3D GSS_S_COMPLETE) {
+	    return major_status;
+    }
+
+    if (conf_req_flag) {
+	size_t k5psize =3D 0;
+	size_t k5pbase =3D 0;
+	size_t k5bsize =3D 0;
+	size_t ec =3D 0;
+
+	size +=3D sizeof(gss_cfx_wrap_token_desc);
+
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_HEADER,
+					   &k5hsize);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_TRAILER,
+					   &k5tsize);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_PADDING,
+					   &k5pbase);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	if (k5pbase > 1) {
+	    k5psize =3D k5pbase - (size % k5pbase);
+	} else {
+	    k5psize =3D 0;
+	}
+
+	if (k5psize =3D=3D 0 && IS_DCE_STYLE(ctx)) {
+	    *minor_status =3D krb5_crypto_getblocksize(context, ctx->crypto,
+						     &k5bsize);
+	    if (*minor_status)
+		return GSS_S_FAILURE;
+
+	    ec =3D k5bsize;
+	} else {
+	    ec =3D k5psize;
+	}
+
+	gsshsize =3D sizeof(gss_cfx_wrap_token_desc) + k5hsize;
+	gsstsize =3D sizeof(gss_cfx_wrap_token_desc) + ec + k5tsize;
+    } else {
+	*minor_status =3D krb5_crypto_length(context, ctx->crypto,
+					   KRB5_CRYPTO_TYPE_CHECKSUM,
+					   &k5tsize);
+	if (*minor_status)
+	    return GSS_S_FAILURE;
+
+	gsshsize =3D sizeof(gss_cfx_wrap_token_desc);
+	gsstsize =3D k5tsize;
+    }
+
+    if (trailer !=3D NULL) {
+	trailer->buffer.length =3D gsstsize;
+    } else {
+	gsshsize +=3D gsstsize;
+    }
+
+    header->buffer.length =3D gsshsize;
+
+    if (padding) {
+	/* padding is done via EC and is contained in the header or trailer */
+	padding->buffer.length =3D 0;
+    }
+
+    if (conf_state) {
+	*conf_state =3D conf_req_flag;
+    }
+
+    return GSS_S_COMPLETE;
+}
+
+
+
+
 OM_uint32 _gssapi_wrap_cfx(OM_uint32 *minor_status,
-			   const gsskrb5_ctx context_handle,
+			   const gsskrb5_ctx ctx,
 			   krb5_context context,
 			   int conf_req_flag,
-			   gss_qop_t qop_req,
 			   const gss_buffer_t input_message_buffer,
 			   int *conf_state,
-			   gss_buffer_t output_message_buffer,
-			   krb5_keyblock *key)
+			   gss_buffer_t output_message_buffer)
 {
-    krb5_crypto crypto;
     gss_cfx_wrap_token token;
     krb5_error_code ret;
     unsigned usage;
@@ -252,19 +1174,13 @@
     int32_t seq_number;
     u_char *p;
=20
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret !=3D 0) {
-	*minor_status =3D ret;
-	return GSS_S_FAILURE;
-    }
-
     ret =3D _gsskrb5cfx_wrap_length_cfx(context,
-				      crypto, conf_req_flag,=20
+				      ctx->crypto, conf_req_flag,
+				      IS_DCE_STYLE(ctx),
 				      input_message_buffer->length,
 				      &wrapped_len, &cksumsize, &padlength);
     if (ret !=3D 0) {
 	*minor_status =3D ret;
-	krb5_crypto_destroy(context, crypto);
 	return GSS_S_FAILURE;
     }
=20
@@ -275,7 +1191,6 @@
     output_message_buffer->value =3D malloc(output_message_buffer->length);
     if (output_message_buffer->value =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
-	krb5_crypto_destroy(context, crypto);
 	return GSS_S_FAILURE;
     }
=20
@@ -285,9 +1200,9 @@
     token->TOK_ID[1] =3D 0x04;
     token->Flags     =3D 0;
     token->Filler    =3D 0xFF;
-    if ((context_handle->more_flags & LOCAL) =3D=3D 0)
+    if ((ctx->more_flags & LOCAL) =3D=3D 0)
 	token->Flags |=3D CFXSentByAcceptor;
-    if (context_handle->more_flags & ACCEPTOR_SUBKEY)
+    if (ctx->more_flags & ACCEPTOR_SUBKEY)
 	token->Flags |=3D CFXAcceptorSubkey;
     if (conf_req_flag) {
 	/*
@@ -324,16 +1239,16 @@
     token->RRC[0] =3D 0;
     token->RRC[1] =3D 0;
=20
-    HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+    HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
     krb5_auth_con_getlocalseqnumber(context,
-				    context_handle->auth_context,
+				    ctx->auth_context,
 				    &seq_number);
     _gsskrb5_encode_be_om_uint32(0,          &token->SND_SEQ[0]);
     _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]);
     krb5_auth_con_setlocalseqnumber(context,
-				    context_handle->auth_context,
+				    ctx->auth_context,
 				    ++seq_number);
-    HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
=20
     /*
      * If confidentiality is requested, the token header is
@@ -344,7 +1259,7 @@
      * calculated over the plaintext concatenated with the
      * token header.
      */
-    if (context_handle->more_flags & LOCAL) {
+    if (ctx->more_flags & LOCAL) {
 	usage =3D KRB5_KU_USAGE_INITIATOR_SEAL;
     } else {
 	usage =3D KRB5_KU_USAGE_ACCEPTOR_SEAL;
@@ -365,25 +1280,31 @@
 	memcpy(p + input_message_buffer->length + padlength,
 	       token, sizeof(*token));
=20
-	ret =3D krb5_encrypt(context, crypto,
+	ret =3D krb5_encrypt(context, ctx->crypto,
 			   usage, p,
 			   input_message_buffer->length + padlength +
 				sizeof(*token),
 			   &cipher);
 	if (ret !=3D 0) {
 	    *minor_status =3D ret;
-	    krb5_crypto_destroy(context, crypto);
 	    _gsskrb5_release_buffer(minor_status, output_message_buffer);
 	    return GSS_S_FAILURE;
 	}
 	assert(sizeof(*token) + cipher.length =3D=3D wrapped_len);
-	token->RRC[0] =3D (rrc >> 8) & 0xFF; =20
+	token->RRC[0] =3D (rrc >> 8) & 0xFF;
 	token->RRC[1] =3D (rrc >> 0) & 0xFF;
=20
-	ret =3D rrc_rotate(cipher.data, cipher.length, rrc, FALSE);
+	/*
+	 * this is really ugly, but needed against windows
+	 * for DCERPC, as windows rotates by EC+RRC.
+	 */
+	if (IS_DCE_STYLE(ctx)) {
+		ret =3D rrc_rotate(cipher.data, cipher.length, rrc+padlength, FALSE);
+	} else {
+		ret =3D rrc_rotate(cipher.data, cipher.length, rrc, FALSE);
+	}
 	if (ret !=3D 0) {
 	    *minor_status =3D ret;
-	    krb5_crypto_destroy(context, crypto);
 	    _gsskrb5_release_buffer(minor_status, output_message_buffer);
 	    return GSS_S_FAILURE;
 	}
@@ -396,21 +1317,19 @@
 	buf =3D malloc(input_message_buffer->length + sizeof(*token));
 	if (buf =3D=3D NULL) {
 	    *minor_status =3D ENOMEM;
-	    krb5_crypto_destroy(context, crypto);
 	    _gsskrb5_release_buffer(minor_status, output_message_buffer);
 	    return GSS_S_FAILURE;
 	}
 	memcpy(buf, input_message_buffer->value, input_message_buffer->length);
 	memcpy(buf + input_message_buffer->length, token, sizeof(*token));
=20
-	ret =3D krb5_create_checksum(context, crypto,
-				   usage, 0, buf,=20
+	ret =3D krb5_create_checksum(context, ctx->crypto,
+				   usage, 0, buf,
 				   input_message_buffer->length +
-					sizeof(*token),=20
+					sizeof(*token),
 				   &cksum);
 	if (ret !=3D 0) {
 	    *minor_status =3D ret;
-	    krb5_crypto_destroy(context, crypto);
 	    _gsskrb5_release_buffer(minor_status, output_message_buffer);
 	    free(buf);
 	    return GSS_S_FAILURE;
@@ -421,7 +1340,7 @@
 	assert(cksum.checksum.length =3D=3D cksumsize);
 	token->EC[0] =3D  (cksum.checksum.length >> 8) & 0xFF;
 	token->EC[1] =3D  (cksum.checksum.length >> 0) & 0xFF;
-	token->RRC[0] =3D (rrc >> 8) & 0xFF; =20
+	token->RRC[0] =3D (rrc >> 8) & 0xFF;
 	token->RRC[1] =3D (rrc >> 0) & 0xFF;
=20
 	p +=3D sizeof(*token);
@@ -433,7 +1352,6 @@
 	    input_message_buffer->length + cksum.checksum.length, rrc, FALSE);
 	if (ret !=3D 0) {
 	    *minor_status =3D ret;
-	    krb5_crypto_destroy(context, crypto);
 	    _gsskrb5_release_buffer(minor_status, output_message_buffer);
 	    free_Checksum(&cksum);
 	    return GSS_S_FAILURE;
@@ -441,8 +1359,6 @@
 	free_Checksum(&cksum);
     }
=20
-    krb5_crypto_destroy(context, crypto);
-
     if (conf_state !=3D NULL) {
 	*conf_state =3D conf_req_flag;
     }
@@ -452,15 +1368,13 @@
 }
=20
 OM_uint32 _gssapi_unwrap_cfx(OM_uint32 *minor_status,
-			     const gsskrb5_ctx context_handle,
+			     const gsskrb5_ctx ctx,
 			     krb5_context context,
 			     const gss_buffer_t input_message_buffer,
 			     gss_buffer_t output_message_buffer,
 			     int *conf_state,
-			     gss_qop_t *qop_state,
-			     krb5_keyblock *key)
+			     gss_qop_t *qop_state)
 {
-    krb5_crypto crypto;
     gss_cfx_wrap_token token;
     u_char token_flags;
     krb5_error_code ret;
@@ -490,11 +1404,11 @@
 	(CFXSentByAcceptor | CFXSealed | CFXAcceptorSubkey);
=20
     if (token_flags & CFXSentByAcceptor) {
-	if ((context_handle->more_flags & LOCAL) =3D=3D 0)
+	if ((ctx->more_flags & LOCAL) =3D=3D 0)
 	    return GSS_S_DEFECTIVE_TOKEN;
     }
=20
-    if (context_handle->more_flags & ACCEPTOR_SUBKEY) {
+    if (ctx->more_flags & ACCEPTOR_SUBKEY) {
 	if ((token_flags & CFXAcceptorSubkey) =3D=3D 0)
 	    return GSS_S_DEFECTIVE_TOKEN;
     } else {
@@ -524,26 +1438,21 @@
 	return GSS_S_UNSEQ_TOKEN;
     }
=20
-    HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
-    ret =3D _gssapi_msg_order_check(context_handle->order, seq_number_lo);
+    HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+    ret =3D _gssapi_msg_order_check(ctx->order, seq_number_lo);
     if (ret !=3D 0) {
 	*minor_status =3D 0;
-	HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+	HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	_gsskrb5_release_buffer(minor_status, output_message_buffer);
 	return ret;
     }
-    HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
=20
     /*
      * Decrypt and/or verify checksum
      */
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret !=3D 0) {
-	*minor_status =3D ret;
-	return GSS_S_FAILURE;
-    }
=20
-    if (context_handle->more_flags & LOCAL) {
+    if (ctx->more_flags & LOCAL) {
 	usage =3D KRB5_KU_USAGE_ACCEPTOR_SEAL;
     } else {
 	usage =3D KRB5_KU_USAGE_INITIATOR_SEAL;
@@ -553,25 +1462,29 @@
     len =3D input_message_buffer->length;
     len -=3D (p - (u_char *)input_message_buffer->value);
=20
-    /* Rotate by RRC; bogus to do this in-place XXX */
-    *minor_status =3D rrc_rotate(p, len, rrc, TRUE);
-    if (*minor_status !=3D 0) {
-	krb5_crypto_destroy(context, crypto);
-	return GSS_S_FAILURE;
-    }
+    if (token_flags & CFXSealed) {
+	/*
+	 * this is really ugly, but needed against windows
+	 * for DCERPC, as windows rotates by EC+RRC.
+	 */
+	if (IS_DCE_STYLE(ctx)) {
+		*minor_status =3D rrc_rotate(p, len, rrc+ec, TRUE);
+	} else {
+		*minor_status =3D rrc_rotate(p, len, rrc, TRUE);
+	}
+	if (*minor_status !=3D 0) {
+	    return GSS_S_FAILURE;
+	}
=20
-    if (token_flags & CFXSealed) {
-	ret =3D krb5_decrypt(context, crypto, usage,
+	ret =3D krb5_decrypt(context, ctx->crypto, usage,
 	    p, len, &data);
 	if (ret !=3D 0) {
 	    *minor_status =3D ret;
-	    krb5_crypto_destroy(context, crypto);
 	    return GSS_S_BAD_MIC;
 	}
=20
 	/* Check that there is room for the pad and token header */
 	if (data.length < ec + sizeof(*token)) {
-	    krb5_crypto_destroy(context, crypto);
 	    krb5_data_free(&data);
 	    return GSS_S_DEFECTIVE_TOKEN;
 	}
@@ -583,8 +1496,7 @@
 	((gss_cfx_wrap_token)p)->RRC[1] =3D token->RRC[1];
=20
 	/* Check the integrity of the header */
-	if (memcmp(p, token, sizeof(*token)) !=3D 0) {
-	    krb5_crypto_destroy(context, crypto);
+	if (ct_memcmp(p, token, sizeof(*token)) !=3D 0) {
 	    krb5_data_free(&data);
 	    return GSS_S_BAD_MIC;
 	}
@@ -594,12 +1506,18 @@
     } else {
 	Checksum cksum;
=20
+	/* Rotate by RRC; bogus to do this in-place XXX */
+	*minor_status =3D rrc_rotate(p, len, rrc, TRUE);
+	if (*minor_status !=3D 0) {
+	    return GSS_S_FAILURE;
+	}
+
 	/* Determine checksum type */
 	ret =3D krb5_crypto_get_checksum_type(context,
-					    crypto, &cksum.cksumtype);
+					    ctx->crypto,
+					    &cksum.cksumtype);
 	if (ret !=3D 0) {
 	    *minor_status =3D ret;
-	    krb5_crypto_destroy(context, crypto);
 	    return GSS_S_FAILURE;
 	}
=20
@@ -608,7 +1526,6 @@
 	/* Check we have at least as much data as the checksum */
 	if (len < cksum.checksum.length) {
 	    *minor_status =3D ERANGE;
-	    krb5_crypto_destroy(context, crypto);
 	    return GSS_S_BAD_MIC;
 	}
=20
@@ -620,13 +1537,12 @@
 	output_message_buffer->value =3D malloc(len + sizeof(*token));
 	if (output_message_buffer->value =3D=3D NULL) {
 	    *minor_status =3D ENOMEM;
-	    krb5_crypto_destroy(context, crypto);
 	    return GSS_S_FAILURE;
 	}
=20
 	/* Checksum is over (plaintext-data | "header") */
 	memcpy(output_message_buffer->value, p, len);
-	memcpy((u_char *)output_message_buffer->value + len,=20
+	memcpy((u_char *)output_message_buffer->value + len,
 	       token, sizeof(*token));
=20
 	/* EC is not included in checksum calculation */
@@ -637,21 +1553,18 @@
 	token->RRC[0] =3D 0;
 	token->RRC[1] =3D 0;
=20
-	ret =3D krb5_verify_checksum(context, crypto,
+	ret =3D krb5_verify_checksum(context, ctx->crypto,
 				   usage,
 				   output_message_buffer->value,
 				   len + sizeof(*token),
 				   &cksum);
 	if (ret !=3D 0) {
 	    *minor_status =3D ret;
-	    krb5_crypto_destroy(context, crypto);
 	    _gsskrb5_release_buffer(minor_status, output_message_buffer);
 	    return GSS_S_BAD_MIC;
 	}
     }
=20
-    krb5_crypto_destroy(context, crypto);
-
     if (qop_state !=3D NULL) {
 	*qop_state =3D GSS_C_QOP_DEFAULT;
     }
@@ -661,14 +1574,12 @@
 }
=20
 OM_uint32 _gssapi_mic_cfx(OM_uint32 *minor_status,
-			  const gsskrb5_ctx context_handle,
+			  const gsskrb5_ctx ctx,
 			  krb5_context context,
 			  gss_qop_t qop_req,
 			  const gss_buffer_t message_buffer,
-			  gss_buffer_t message_token,
-			  krb5_keyblock *key)
+			  gss_buffer_t message_token)
 {
-    krb5_crypto crypto;
     gss_cfx_mic_token token;
     krb5_error_code ret;
     unsigned usage;
@@ -677,17 +1588,10 @@
     size_t len;
     int32_t seq_number;
=20
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret !=3D 0) {
-	*minor_status =3D ret;
-	return GSS_S_FAILURE;
-    }
-
     len =3D message_buffer->length + sizeof(*token);
     buf =3D malloc(len);
     if (buf =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
-	krb5_crypto_destroy(context, crypto);
 	return GSS_S_FAILURE;
     }
=20
@@ -697,38 +1601,36 @@
     token->TOK_ID[0] =3D 0x04;
     token->TOK_ID[1] =3D 0x04;
     token->Flags =3D 0;
-    if ((context_handle->more_flags & LOCAL) =3D=3D 0)
+    if ((ctx->more_flags & LOCAL) =3D=3D 0)
 	token->Flags |=3D CFXSentByAcceptor;
-    if (context_handle->more_flags & ACCEPTOR_SUBKEY)
+    if (ctx->more_flags & ACCEPTOR_SUBKEY)
 	token->Flags |=3D CFXAcceptorSubkey;
     memset(token->Filler, 0xFF, 5);
=20
-    HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+    HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
     krb5_auth_con_getlocalseqnumber(context,
-				    context_handle->auth_context,
+				    ctx->auth_context,
 				    &seq_number);
     _gsskrb5_encode_be_om_uint32(0,          &token->SND_SEQ[0]);
     _gsskrb5_encode_be_om_uint32(seq_number, &token->SND_SEQ[4]);
     krb5_auth_con_setlocalseqnumber(context,
-				    context_handle->auth_context,
+				    ctx->auth_context,
 				    ++seq_number);
-    HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
=20
-    if (context_handle->more_flags & LOCAL) {
+    if (ctx->more_flags & LOCAL) {
 	usage =3D KRB5_KU_USAGE_INITIATOR_SIGN;
     } else {
 	usage =3D KRB5_KU_USAGE_ACCEPTOR_SIGN;
     }
=20
-    ret =3D krb5_create_checksum(context, crypto,
+    ret =3D krb5_create_checksum(context, ctx->crypto,
 	usage, 0, buf, len, &cksum);
     if (ret !=3D 0) {
 	*minor_status =3D ret;
-	krb5_crypto_destroy(context, crypto);
 	free(buf);
 	return GSS_S_FAILURE;
     }
-    krb5_crypto_destroy(context, crypto);
=20
     /* Determine MIC length */
     message_token->length =3D sizeof(*token) + cksum.checksum.length;
@@ -753,14 +1655,12 @@
 }
=20
 OM_uint32 _gssapi_verify_mic_cfx(OM_uint32 *minor_status,
-				 const gsskrb5_ctx context_handle,
+				 const gsskrb5_ctx ctx,
 				 krb5_context context,
 				 const gss_buffer_t message_buffer,
 				 const gss_buffer_t token_buffer,
-				 gss_qop_t *qop_state,
-				 krb5_keyblock *key)
+				 gss_qop_t *qop_state)
 {
-    krb5_crypto crypto;
     gss_cfx_mic_token token;
     u_char token_flags;
     krb5_error_code ret;
@@ -787,10 +1687,10 @@
     token_flags =3D token->Flags & (CFXSentByAcceptor | CFXAcceptorSubkey);
=20
     if (token_flags & CFXSentByAcceptor) {
-	if ((context_handle->more_flags & LOCAL) =3D=3D 0)
+	if ((ctx->more_flags & LOCAL) =3D=3D 0)
 	    return GSS_S_DEFECTIVE_TOKEN;
     }
-    if (context_handle->more_flags & ACCEPTOR_SUBKEY) {
+    if (ctx->more_flags & ACCEPTOR_SUBKEY) {
 	if ((token_flags & CFXAcceptorSubkey) =3D=3D 0)
 	    return GSS_S_DEFECTIVE_TOKEN;
     } else {
@@ -798,7 +1698,7 @@
 	    return GSS_S_DEFECTIVE_TOKEN;
     }
=20
-    if (memcmp(token->Filler, "\xff\xff\xff\xff\xff", 5) !=3D 0) {
+    if (ct_memcmp(token->Filler, "\xff\xff\xff\xff\xff", 5) !=3D 0) {
 	return GSS_S_DEFECTIVE_TOKEN;
     }
=20
@@ -812,36 +1712,29 @@
 	return GSS_S_UNSEQ_TOKEN;
     }
=20
-    HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
-    ret =3D _gssapi_msg_order_check(context_handle->order, seq_number_lo);
+    HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+    ret =3D _gssapi_msg_order_check(ctx->order, seq_number_lo);
     if (ret !=3D 0) {
 	*minor_status =3D 0;
-	HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+	HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	return ret;
     }
-    HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
=20
     /*
      * Verify checksum
      */
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret !=3D 0) {
-	*minor_status =3D ret;
-	return GSS_S_FAILURE;
-    }
-
-    ret =3D krb5_crypto_get_checksum_type(context, crypto,
+    ret =3D krb5_crypto_get_checksum_type(context, ctx->crypto,
 					&cksum.cksumtype);
     if (ret !=3D 0) {
 	*minor_status =3D ret;
-	krb5_crypto_destroy(context, crypto);
 	return GSS_S_FAILURE;
     }
=20
     cksum.checksum.data =3D p + sizeof(*token);
     cksum.checksum.length =3D token_buffer->length - sizeof(*token);
=20
-    if (context_handle->more_flags & LOCAL) {
+    if (ctx->more_flags & LOCAL) {
 	usage =3D KRB5_KU_USAGE_ACCEPTOR_SIGN;
     } else {
 	usage =3D KRB5_KU_USAGE_INITIATOR_SIGN;
@@ -850,18 +1743,16 @@
     buf =3D malloc(message_buffer->length + sizeof(*token));
     if (buf =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
-	krb5_crypto_destroy(context, crypto);
 	return GSS_S_FAILURE;
     }
     memcpy(buf, message_buffer->value, message_buffer->length);
     memcpy(buf + message_buffer->length, token, sizeof(*token));
=20
-    ret =3D krb5_verify_checksum(context, crypto,
+    ret =3D krb5_verify_checksum(context, ctx->crypto,
 			       usage,
 			       buf,
 			       sizeof(*token) + message_buffer->length,
 			       &cksum);
-    krb5_crypto_destroy(context, crypto);
     if (ret !=3D 0) {
 	*minor_status =3D ret;
 	free(buf);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/cf=
x.h
--- a/head/crypto/heimdal/lib/gssapi/krb5/cfx.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/cfx.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -30,7 +30,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: cfx.h 19031 2006-11-13 18:02:57Z lha $ */
+/* $Id$ */
=20
 #ifndef GSSAPI_CFX_H_
 #define GSSAPI_CFX_H_ 1
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/co=
mpare_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/compare_name.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/compare_name.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: compare_name.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32 _gsskrb5_compare_name
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_compare_name
            (OM_uint32 * minor_status,
             const gss_name_t name1,
             const gss_name_t name2,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/co=
mpat.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/compat.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/compat.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,45 +1,42 @@
 /*
- * Copyright (c) 2003 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: compat.c 19031 2006-11-13 18:02:57Z lha $");
-
+#include "gsskrb5_locl.h"
=20
 static krb5_error_code
-check_compat(OM_uint32 *minor_status,=20
-	     krb5_context context, krb5_const_principal name,=20
-	     const char *option, krb5_boolean *compat,=20
+check_compat(OM_uint32 *minor_status,
+	     krb5_context context, krb5_const_principal name,
+	     const char *option, krb5_boolean *compat,
 	     krb5_boolean match_val)
 {
     krb5_error_code ret =3D 0;
@@ -62,7 +59,7 @@
 	    *compat =3D match_val;
 	    break;
 	}
-=09
+
 	krb5_free_principal(context, match);
 	match =3D NULL;
     }
@@ -92,11 +89,11 @@
     OM_uint32 ret;
=20
     if ((ctx->more_flags & COMPAT_OLD_DES3_SELECTED) =3D=3D 0) {
-	ret =3D check_compat(minor_status, context, ctx->target,=20
+	ret =3D check_compat(minor_status, context, ctx->target,
 			   "broken_des3_mic", &use_compat, TRUE);
 	if (ret)
 	    return ret;
-	ret =3D check_compat(minor_status, context, ctx->target,=20
+	ret =3D check_compat(minor_status, context, ctx->target,
 			   "correct_des3_mic", &use_compat, FALSE);
 	if (ret)
 	    return ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/co=
ntext_time.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/context_time.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/context_time.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,42 +1,40 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: context_time.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 OM_uint32
-_gsskrb5_lifetime_left(OM_uint32 *minor_status,=20
+_gsskrb5_lifetime_left(OM_uint32 *minor_status,
 		       krb5_context context,
 		       OM_uint32 lifetime,
 		       OM_uint32 *lifetime_rec)
@@ -55,7 +53,7 @@
 	return GSS_S_FAILURE;
     }
=20
-    if (lifetime < timeret)=20
+    if (lifetime < timeret)
 	*lifetime_rec =3D 0;
     else
 	*lifetime_rec =3D lifetime - timeret;
@@ -64,7 +62,7 @@
 }
=20
=20
-OM_uint32 _gsskrb5_context_time
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_context_time
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             OM_uint32 * time_rec
@@ -90,6 +88,6 @@
=20
     if (*time_rec =3D=3D 0)
 	return GSS_S_CONTEXT_EXPIRED;
-=09
+
     return GSS_S_COMPLETE;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/co=
py_ccache.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/copy_ccache.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/copy_ccache.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2000 - 2001, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2001, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: copy_ccache.c 20688 2007-05-17 18:44:31Z lha $");
+#include "gsskrb5_locl.h"
=20
 #if 0
 OM_uint32
@@ -65,11 +63,11 @@
=20
=20
 OM_uint32
-_gsskrb5_import_cred(OM_uint32 *minor_status,
-		     krb5_ccache id,
-		     krb5_principal keytab_principal,
-		     krb5_keytab keytab,
-		     gss_cred_id_t *cred)
+_gsskrb5_krb5_import_cred(OM_uint32 *minor_status,
+			  krb5_ccache id,
+			  krb5_principal keytab_principal,
+			  krb5_keytab keytab,
+			  gss_cred_id_t *cred)
 {
     krb5_context context;
     krb5_error_code kret;
@@ -102,7 +100,7 @@
 	    *minor_status =3D kret;
 	    return GSS_S_FAILURE;
 	}
-=09
+
 	if (keytab_principal) {
 	    krb5_boolean match;
=20
@@ -147,8 +145,8 @@
 	handle->usage |=3D GSS_C_ACCEPT;
=20
 	if (keytab_principal && handle->principal =3D=3D NULL) {
-	    kret =3D krb5_copy_principal(context,=20
-				       keytab_principal,=20
+	    kret =3D krb5_copy_principal(context,
+				       keytab_principal,
 				       &handle->principal);
 	    if (kret)
 		goto out;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/de=
capsulate.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/decapsulate.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/decapsulate.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: decapsulate.c 18334 2006-10-07 22:16:04Z lha $");
+#include "gsskrb5_locl.h"
=20
 /*
  * return the length of the mechanism in token or -1
@@ -82,9 +80,9 @@
=20
     if (mech_len !=3D mech->length)
 	return GSS_S_BAD_MECH;
-    if (memcmp(p,
-	       mech->elements,
-	       mech->length) !=3D 0)
+    if (ct_memcmp(p,
+		  mech->elements,
+		  mech->length) !=3D 0)
 	return GSS_S_BAD_MECH;
     p +=3D mech_len;
     *str =3D rk_UNCONST(p);
@@ -110,7 +108,7 @@
     if (len < 2)
 	return GSS_S_DEFECTIVE_TOKEN;
=20
-    if (memcmp (*str, type, 2) !=3D 0)
+    if (ct_memcmp (*str, type, 2) !=3D 0)
 	return GSS_S_DEFECTIVE_TOKEN;
     *str +=3D 2;
=20
@@ -154,7 +152,7 @@
  */
=20
 OM_uint32
-_gsskrb5_decapsulate(OM_uint32 *minor_status,   =20
+_gsskrb5_decapsulate(OM_uint32 *minor_status,
 			gss_buffer_t input_token_buffer,
 			krb5_data *out_data,
 			const void *type,
@@ -184,7 +182,7 @@
  */
=20
 OM_uint32
-_gssapi_verify_pad(gss_buffer_t wrapped_token,=20
+_gssapi_verify_pad(gss_buffer_t wrapped_token,
 		   size_t datalen,
 		   size_t *padlen)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/de=
lete_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/delete_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/delete_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: delete_sec_context.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_delete_sec_context(OM_uint32 * minor_status,
 			    gss_ctx_id_t * context_handle,
 			    gss_buffer_t output_token)
@@ -61,6 +59,9 @@
     HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
=20
     krb5_auth_con_free (context, ctx->auth_context);
+    krb5_auth_con_free (context, ctx->deleg_auth_context);
+    if (ctx->kcred)
+	krb5_free_creds(context, ctx->kcred);
     if(ctx->source)
 	krb5_free_principal (context, ctx->source);
     if(ctx->target)
@@ -72,6 +73,8 @@
     if (ctx->service_keyblock)
 	krb5_free_keyblock (context, ctx->service_keyblock);
     krb5_data_free(&ctx->fwd_data);
+    if (ctx->crypto)
+    	krb5_crypto_destroy(context, ctx->crypto);
=20
     HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
     HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/di=
splay_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/display_name.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/display_name.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: display_name.c 21077 2007-06-12 22:42:56Z lha $");
-
-OM_uint32 _gsskrb5_display_name
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_name
            (OM_uint32 * minor_status,
             const gss_name_t input_name,
             gss_buffer_t output_name_buffer,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/di=
splay_status.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/display_status.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/display_status.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1998 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: display_status.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 static const char *
 calling_error(OM_uint32 v)
@@ -118,29 +116,30 @@
=20
     if (_gsskrb5_init (&context) !=3D 0)
 	return;
-    krb5_clear_error_string(context);
+    krb5_clear_error_message(context);
 }
=20
 void
-_gsskrb5_set_status (const char *fmt, ...)
+_gsskrb5_set_status (int ret, const char *fmt, ...)
 {
     krb5_context context;
     va_list args;
     char *str;
+    int e;
=20
     if (_gsskrb5_init (&context) !=3D 0)
 	return;
=20
     va_start(args, fmt);
-    vasprintf(&str, fmt, args);
+    e =3D vasprintf(&str, fmt, args);
     va_end(args);
-    if (str) {
-	krb5_set_error_string(context, str);
+    if (e >=3D 0 && str) {
+	krb5_set_error_message(context, ret, "%s", str);
 	free(str);
     }
 }
=20
-OM_uint32 _gsskrb5_display_status
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_display_status
 (OM_uint32		*minor_status,
  OM_uint32		 status_value,
  int			 status_type,
@@ -149,7 +148,8 @@
  gss_buffer_t	 status_string)
 {
     krb5_context context;
-    char *buf;
+    char *buf =3D NULL;
+    int e =3D 0;
=20
     GSSAPI_KRB5_INIT (&context);
=20
@@ -164,28 +164,27 @@
=20
     if (status_type =3D=3D GSS_C_GSS_CODE) {
 	if (GSS_SUPPLEMENTARY_INFO(status_value))
-	    asprintf(&buf, "%s",=20
-		     supplementary_error(GSS_SUPPLEMENTARY_INFO(status_value)));
+	    e =3D asprintf(&buf, "%s",
+			 supplementary_error(GSS_SUPPLEMENTARY_INFO(status_value)));
 	else
-	    asprintf (&buf, "%s %s",
-		      calling_error(GSS_CALLING_ERROR(status_value)),
-		      routine_error(GSS_ROUTINE_ERROR(status_value)));
+	    e =3D asprintf (&buf, "%s %s",
+			  calling_error(GSS_CALLING_ERROR(status_value)),
+			  routine_error(GSS_ROUTINE_ERROR(status_value)));
     } else if (status_type =3D=3D GSS_C_MECH_CODE) {
-	buf =3D krb5_get_error_string(context);
-	if (buf =3D=3D NULL) {
-	    const char *tmp =3D krb5_get_err_text (context, status_value);
-	    if (tmp =3D=3D NULL)
-		asprintf(&buf, "unknown mech error-code %u",
+	const char *buf2 =3D krb5_get_error_message(context, status_value);
+	if (buf2) {
+	    buf =3D strdup(buf2);
+	    krb5_free_error_message(context, buf2);
+	} else {
+	    e =3D asprintf(&buf, "unknown mech error-code %u",
 			 (unsigned)status_value);
-	    else
-		buf =3D strdup(tmp);
 	}
     } else {
 	*minor_status =3D EINVAL;
 	return GSS_S_BAD_STATUS;
     }
=20
-    if (buf =3D=3D NULL) {
+    if (e < 0 || buf =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
     }
@@ -195,6 +194,6 @@
=20
     status_string->length =3D strlen(buf);
     status_string->value  =3D buf;
- =20
+
     return GSS_S_COMPLETE;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/du=
plicate_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/duplicate_name.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/duplicate_name.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,58 +1,57 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: duplicate_name.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32 _gsskrb5_duplicate_name (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_duplicate_name (
             OM_uint32 * minor_status,
             const gss_name_t src_name,
             gss_name_t * dest_name
            )
 {
+    krb5_const_principal src =3D (krb5_const_principal)src_name;
     krb5_context context;
-    krb5_const_principal src =3D (krb5_const_principal)src_name;
-    krb5_principal *dest =3D (krb5_principal *)dest_name;
+    krb5_principal dest;
     krb5_error_code kret;
=20
     GSSAPI_KRB5_INIT (&context);
=20
-    kret =3D krb5_copy_principal (context, src, dest);
+    kret =3D krb5_copy_principal (context, src, &dest);
     if (kret) {
 	*minor_status =3D kret;
 	return GSS_S_FAILURE;
     } else {
+	*dest_name =3D (gss_name_t)dest;
 	*minor_status =3D 0;
 	return GSS_S_COMPLETE;
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/en=
capsulate.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/encapsulate.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/encapsulate.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: encapsulate.c 18459 2006-10-14 10:12:16Z lha $");
+#include "gsskrb5_locl.h"
=20
 void
 _gssapi_encap_length (size_t data_len,
@@ -110,13 +108,13 @@
     void *p;
=20
     _gssapi_encap_length (in_data->length, &len, &outer_len, mech);
-   =20
+
     output_token->length =3D outer_len;
     output_token->value  =3D malloc (outer_len);
     if (output_token->value =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
-    }=09
+    }
=20
     p =3D _gssapi_make_mech_header (output_token->value, len, mech);
     memcpy (p, in_data->data, in_data->length);
@@ -130,7 +128,7 @@
=20
 OM_uint32
 _gsskrb5_encapsulate(
-			OM_uint32 *minor_status,   =20
+			OM_uint32 *minor_status,
 			const krb5_data *in_data,
 			gss_buffer_t output_token,
 			const void *type,
@@ -141,13 +139,13 @@
     u_char *p;
=20
     _gsskrb5_encap_length (in_data->length, &len, &outer_len, mech);
-   =20
+
     output_token->length =3D outer_len;
     output_token->value  =3D malloc (outer_len);
     if (output_token->value =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
-    }=09
+    }
=20
     p =3D _gsskrb5_make_header (output_token->value, len, type, mech);
     memcpy (p, in_data->data, in_data->length);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ex=
port_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/export_name.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/export_name.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: export_name.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32 _gsskrb5_export_name
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_export_name
            (OM_uint32  * minor_status,
             const gss_name_t input_name,
             gss_buffer_t exported_name
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ex=
port_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/export_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/export_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1999 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: export_sec_context.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_export_sec_context (
     OM_uint32 * minor_status,
     gss_ctx_id_t * context_handle,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ex=
ternal.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/external.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/external.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
 #include <gssapi_mech.h>
=20
-RCSID("$Id: external.c 22128 2007-12-04 00:56:55Z lha $");
-
 /*
  * The implementation must reserve static storage for a
  * gss_OID_desc object containing the value
@@ -48,10 +46,8 @@
  * to that gss_OID_desc.
  */
=20
-static gss_OID_desc gss_c_nt_user_name_oid_desc =3D
-{10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x01")};
-
-gss_OID GSS_C_NT_USER_NAME =3D &gss_c_nt_user_name_oid_desc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_user_name_oid_desc =3D
+    {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x01")};
=20
 /*
  * The implementation must reserve static storage for a
@@ -65,10 +61,8 @@
  * initialized to point to that gss_OID_desc.
  */
=20
-static gss_OID_desc gss_c_nt_machine_uid_name_oid_desc =3D
-{10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x02")};
-
-gss_OID GSS_C_NT_MACHINE_UID_NAME =3D &gss_c_nt_machine_uid_name_oid_desc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_machine_uid_name_oid_desc =3D
+    {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x02")};
=20
 /*
  * The implementation must reserve static storage for a
@@ -82,10 +76,8 @@
  * initialized to point to that gss_OID_desc.
  */
=20
-static gss_OID_desc gss_c_nt_string_uid_name_oid_desc =3D
-{10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x03")};
-
-gss_OID GSS_C_NT_STRING_UID_NAME =3D &gss_c_nt_string_uid_name_oid_desc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_string_uid_name_oid_desc =3D
+    {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x03")};
=20
 /*
  * The implementation must reserve static storage for a
@@ -105,10 +97,8 @@
  * implementations
  */
=20
-static gss_OID_desc gss_c_nt_hostbased_service_x_oid_desc =3D
-{6, rk_UNCONST("\x2b\x06\x01\x05\x06\x02")};
-
-gss_OID GSS_C_NT_HOSTBASED_SERVICE_X =3D &gss_c_nt_hostbased_service_x_oid=
_desc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_hostbased_service_x_oid_desc =
=3D
+    {6, rk_UNCONST("\x2b\x06\x01\x05\x06\x02")};
=20
 /*
  * The implementation must reserve static storage for a
@@ -121,10 +111,8 @@
  * GSS_C_NT_HOSTBASED_SERVICE should be initialized
  * to point to that gss_OID_desc.
  */
-static gss_OID_desc gss_c_nt_hostbased_service_oid_desc =3D
-{10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x04")};
-
-gss_OID GSS_C_NT_HOSTBASED_SERVICE =3D &gss_c_nt_hostbased_service_oid_des=
c;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_hostbased_service_oid_desc =3D
+    {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x04")};
=20
 /*
  * The implementation must reserve static storage for a
@@ -137,10 +125,8 @@
  * to that gss_OID_desc.
  */
=20
-static gss_OID_desc gss_c_nt_anonymous_oid_desc =3D
-{6, rk_UNCONST("\x2b\x06\01\x05\x06\x03")};
-
-gss_OID GSS_C_NT_ANONYMOUS =3D &gss_c_nt_anonymous_oid_desc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_anonymous_oid_desc =3D
+    {6, rk_UNCONST("\x2b\x06\01\x05\x06\x03")};
=20
 /*
  * The implementation must reserve static storage for a
@@ -153,10 +139,8 @@
  * to that gss_OID_desc.
  */
=20
-static gss_OID_desc gss_c_nt_export_name_oid_desc =3D
-{6, rk_UNCONST("\x2b\x06\x01\x05\x06\x04") };
-
-gss_OID GSS_C_NT_EXPORT_NAME =3D &gss_c_nt_export_name_oid_desc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_c_nt_export_name_oid_desc =3D
+    {6, rk_UNCONST("\x2b\x06\x01\x05\x06\x04") };
=20
 /*
  *   This name form shall be represented by the Object Identifier {iso(1)
@@ -165,66 +149,8 @@
  *   is "GSS_KRB5_NT_PRINCIPAL_NAME".
  */
=20
-static gss_OID_desc gss_krb5_nt_principal_name_oid_desc =3D
-{10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x01") };
-
-gss_OID GSS_KRB5_NT_PRINCIPAL_NAME =3D &gss_krb5_nt_principal_name_oid_des=
c;
-
-/*
- *   This name form shall be represented by the Object Identifier {iso(1)
- *   member-body(2) United States(840) mit(113554) infosys(1) gssapi(2)
- *   generic(1) user_name(1)}.  The recommended symbolic name for this
- *   type is "GSS_KRB5_NT_USER_NAME".
- */
-
-gss_OID GSS_KRB5_NT_USER_NAME =3D &gss_c_nt_user_name_oid_desc;
-
-/*
- *   This name form shall be represented by the Object Identifier {iso(1)
- *   member-body(2) United States(840) mit(113554) infosys(1) gssapi(2)
- *   generic(1) machine_uid_name(2)}.  The recommended symbolic name for
- *   this type is "GSS_KRB5_NT_MACHINE_UID_NAME".
- */
-
-gss_OID GSS_KRB5_NT_MACHINE_UID_NAME =3D &gss_c_nt_machine_uid_name_oid_de=
sc;
-
-/*
- *   This name form shall be represented by the Object Identifier {iso(1)
- *   member-body(2) United States(840) mit(113554) infosys(1) gssapi(2)
- *   generic(1) string_uid_name(3)}.  The recommended symbolic name for
- *   this type is "GSS_KRB5_NT_STRING_UID_NAME".
- */
-
-gss_OID GSS_KRB5_NT_STRING_UID_NAME =3D &gss_c_nt_string_uid_name_oid_desc;
-
-/*
- *   To support ongoing experimentation, testing, and evolution of the
- *   specification, the Kerberos V5 GSS-API mechanism as defined in this
- *   and any successor memos will be identified with the following Object
- *   Identifier, as defined in RFC-1510, until the specification is
- *   advanced to the level of Proposed Standard RFC:
- *
- *   {iso(1), org(3), dod(5), internet(1), security(5), kerberosv5(2)}
- *
- *   Upon advancement to the level of Proposed Standard RFC, the Kerberos
- *   V5 GSS-API mechanism will be identified by an Object Identifier
- *   having the value:
- *
- *   {iso(1) member-body(2) United States(840) mit(113554) infosys(1)
- *   gssapi(2) krb5(2)}
- */
-
-#if 0 /* This is the old OID */
-
-static gss_OID_desc gss_krb5_mechanism_oid_desc =3D
-{5, rk_UNCONST("\x2b\x05\x01\x05\x02")};
-
-#endif
-
-static gss_OID_desc gss_krb5_mechanism_oid_desc =3D
-{9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02") };
-
-gss_OID GSS_KRB5_MECHANISM =3D &gss_krb5_mechanism_oid_desc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_krb5_nt_principal_name_oid_desc =3D
+    {10, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x01") };
=20
 /*
  * draft-ietf-cat-iakerb-09, IAKERB:
@@ -239,141 +165,109 @@
  *   iakerbMinimumMessagesProtocol(2)}.
  */
=20
-static gss_OID_desc gss_iakerb_proxy_mechanism_oid_desc =3D
-{7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x01")};
+gss_OID_desc GSSAPI_LIB_VARIABLE  __gss_iakerb_proxy_mechanism_oid_desc =
=3D
+    {7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x01")};
=20
-gss_OID GSS_IAKERB_PROXY_MECHANISM =3D &gss_iakerb_proxy_mechanism_oid_des=
c;
-
-static gss_OID_desc gss_iakerb_min_msg_mechanism_oid_desc =3D
-{7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x02") };
-
-gss_OID GSS_IAKERB_MIN_MSG_MECHANISM =3D &gss_iakerb_min_msg_mechanism_oid=
_desc;
-
-/*
- *
- */
-
-static gss_OID_desc gss_c_peer_has_updated_spnego_oid_desc =3D
-{9, (void *)"\x2b\x06\x01\x04\x01\xa9\x4a\x13\x05"};
-
-gss_OID GSS_C_PEER_HAS_UPDATED_SPNEGO =3D &gss_c_peer_has_updated_spnego_o=
id_desc;
-
-/*
- * 1.2.752.43.13 Heimdal GSS-API Extentions
- */
-
-/* 1.2.752.43.13.1 */
-static gss_OID_desc gss_krb5_copy_ccache_x_oid_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x01")};
-
-gss_OID GSS_KRB5_COPY_CCACHE_X =3D &gss_krb5_copy_ccache_x_oid_desc;
-
-/* 1.2.752.43.13.2 */
-static gss_OID_desc gss_krb5_get_tkt_flags_x_oid_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x02")};
-
-gss_OID GSS_KRB5_GET_TKT_FLAGS_X =3D &gss_krb5_get_tkt_flags_x_oid_desc;
-
-/* 1.2.752.43.13.3 */
-static gss_OID_desc gss_krb5_extract_authz_data_from_sec_context_x_oid_des=
c =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x03")};
-
-gss_OID GSS_KRB5_EXTRACT_AUTHZ_DATA_FROM_SEC_CONTEXT_X =3D &gss_krb5_extra=
ct_authz_data_from_sec_context_x_oid_desc;
-
-/* 1.2.752.43.13.4 */
-static gss_OID_desc gss_krb5_compat_des3_mic_x_oid_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x04")};
-
-gss_OID GSS_KRB5_COMPAT_DES3_MIC_X =3D &gss_krb5_compat_des3_mic_x_oid_des=
c;
-
-/* 1.2.752.43.13.5 */
-static gss_OID_desc gss_krb5_register_acceptor_identity_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x05")};
-
-gss_OID GSS_KRB5_REGISTER_ACCEPTOR_IDENTITY_X =3D &gss_krb5_register_accep=
tor_identity_x_desc;
-
-/* 1.2.752.43.13.6 */
-static gss_OID_desc gss_krb5_export_lucid_context_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x06")};
-
-gss_OID GSS_KRB5_EXPORT_LUCID_CONTEXT_X =3D &gss_krb5_export_lucid_context=
_x_desc;
-
-/* 1.2.752.43.13.6.1 */
-static gss_OID_desc gss_krb5_export_lucid_context_v1_x_desc =3D
-{7, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x06\x01")};
-
-gss_OID GSS_KRB5_EXPORT_LUCID_CONTEXT_V1_X =3D &gss_krb5_export_lucid_cont=
ext_v1_x_desc;
-
-/* 1.2.752.43.13.7 */
-static gss_OID_desc gss_krb5_set_dns_canonicalize_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x07")};
-
-gss_OID GSS_KRB5_SET_DNS_CANONICALIZE_X =3D &gss_krb5_set_dns_canonicalize=
_x_desc;
-
-/* 1.2.752.43.13.8 */
-static gss_OID_desc gss_krb5_get_subkey_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x08")};
-
-gss_OID GSS_KRB5_GET_SUBKEY_X =3D &gss_krb5_get_subkey_x_desc;
-
-/* 1.2.752.43.13.9 */
-static gss_OID_desc gss_krb5_get_initiator_subkey_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x09")};
-
-gss_OID GSS_KRB5_GET_INITIATOR_SUBKEY_X =3D &gss_krb5_get_initiator_subkey=
_x_desc;
-
-/* 1.2.752.43.13.10 */
-static gss_OID_desc gss_krb5_get_acceptor_subkey_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0a")};
-
-gss_OID GSS_KRB5_GET_ACCEPTOR_SUBKEY_X =3D &gss_krb5_get_acceptor_subkey_x=
_desc;
-
-/* 1.2.752.43.13.11 */
-static gss_OID_desc gss_krb5_send_to_kdc_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0b")};
-
-gss_OID GSS_KRB5_SEND_TO_KDC_X =3D &gss_krb5_send_to_kdc_x_desc;
-
-/* 1.2.752.43.13.12 */
-static gss_OID_desc gss_krb5_get_authtime_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0c")};
-
-gss_OID GSS_KRB5_GET_AUTHTIME_X =3D &gss_krb5_get_authtime_x_desc;
-
-/* 1.2.752.43.13.13 */
-static gss_OID_desc gss_krb5_get_service_keyblock_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0d")};
-
-gss_OID GSS_KRB5_GET_SERVICE_KEYBLOCK_X =3D &gss_krb5_get_service_keyblock=
_x_desc;
-
-/* 1.2.752.43.13.14 */
-static gss_OID_desc gss_krb5_set_allowable_enctypes_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0e")};
-
-gss_OID GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X =3D &gss_krb5_set_allowable_enct=
ypes_x_desc;
-
-/* 1.2.752.43.13.15 */
-static gss_OID_desc gss_krb5_set_default_realm_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x0f")};
-
-gss_OID GSS_KRB5_SET_DEFAULT_REALM_X =3D &gss_krb5_set_default_realm_x_des=
c;
-
-/* 1.2.752.43.13.16 */
-static gss_OID_desc gss_krb5_ccache_name_x_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0d\x10")};
-
-gss_OID GSS_KRB5_CCACHE_NAME_X =3D &gss_krb5_ccache_name_x_desc;
-
-/* 1.2.752.43.14.1 */
-static gss_OID_desc gss_sasl_digest_md5_mechanism_desc =3D
-{6, rk_UNCONST("\x2a\x85\x70\x2b\x0e\x01") };
-
-gss_OID GSS_SASL_DIGEST_MD5_MECHANISM =3D &gss_sasl_digest_md5_mechanism_d=
esc;
+gss_OID_desc GSSAPI_LIB_VARIABLE __gss_iakerb_min_msg_mechanism_oid_desc =
=3D
+    {7, rk_UNCONST("\x2b\x06\x01\x05\x05\x0a\x02") };
=20
 /*
  * Context for krb5 calls.
  */
=20
+#if 0
+static gss_mo_desc krb5_mo[] =3D {
+    {
+	GSS_C_MA_SASL_MECH_NAME,
+	GSS_MO_MA,
+	"SASL mech name",
+	rk_UNCONST("GS2-KRB5"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_NAME,
+	GSS_MO_MA,
+	"Mechanism name",
+	rk_UNCONST("KRB5"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_DESCRIPTION,
+	GSS_MO_MA,
+	"Mechanism description",
+	rk_UNCONST("Heimdal Kerberos 5 mech"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_CONCRETE,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_ITOK_FRAMED,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_AUTH_INIT,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_AUTH_TARG,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_AUTH_INIT_ANON,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_DELEG_CRED,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_INTEG_PROT,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_CONF_PROT,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_MIC,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_WRAP,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_PROT_READY,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_REPLAY_DET,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_OOS_DET,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_CBINDINGS,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_PFS,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_CTX_TRANS,
+	GSS_MO_MA
+    }
+};
+#endif
+
 /*
  *
  */
@@ -381,7 +275,8 @@
 static gssapi_mech_interface_desc krb5_mech =3D {
     GMI_VERSION,
     "kerberos 5",
-    {9, "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" },
+    {9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02") },
+    0,
     _gsskrb5_acquire_cred,
     _gsskrb5_release_cred,
     _gsskrb5_init_sec_context,
@@ -415,7 +310,42 @@
     _gsskrb5_inquire_cred_by_oid,
     _gsskrb5_set_sec_context_option,
     _gsskrb5_set_cred_option,
-    _gsskrb5_pseudo_random
+    _gsskrb5_pseudo_random,
+#if 0
+    _gk_wrap_iov,
+    _gk_unwrap_iov,
+    _gk_wrap_iov_length,
+#else
+    NULL,
+    NULL,
+    NULL,
+#endif
+    _gsskrb5_store_cred,
+    _gsskrb5_export_cred,
+    _gsskrb5_import_cred,
+    _gsskrb5_acquire_cred_ext,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+#if 0
+    krb5_mo,
+    sizeof(krb5_mo) / sizeof(krb5_mo[0]),
+#else
+    NULL,
+    0,
+#endif
+    _gsskrb5_pname_to_uid,
+    _gsskrb5_authorize_localname,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL
 };
=20
 gssapi_mech_interface
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ge=
t_mic.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/get_mic.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/get_mic.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: get_mic.c 19031 2006-11-13 18:02:57Z lha $");
+#ifdef HEIM_WEAK_CRYPTO
=20
 static OM_uint32
 mic_des
@@ -47,9 +47,10 @@
            )
 {
   u_char *p;
-  MD5_CTX md5;
+  EVP_MD_CTX *md5;
   u_char hash[16];
   DES_key_schedule schedule;
+  EVP_CIPHER_CTX des_ctx;
   DES_cblock deskey;
   DES_cblock zero;
   int32_t seq_number;
@@ -68,7 +69,7 @@
   p =3D _gsskrb5_make_header(message_token->value,
 			      len,
 			      "\x01\x01", /* TOK_ID */
-			      GSS_KRB5_MECHANISM);=20
+			      GSS_KRB5_MECHANISM);
=20
   memcpy (p, "\x00\x00", 2);	/* SGN_ALG =3D DES MAC MD5 */
   p +=3D 2;
@@ -81,14 +82,16 @@
   p +=3D 16;
=20
   /* checksum */
-  MD5_Init (&md5);
-  MD5_Update (&md5, p - 24, 8);
-  MD5_Update (&md5, message_buffer->value, message_buffer->length);
-  MD5_Final (hash, &md5);
+  md5 =3D EVP_MD_CTX_create();
+  EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+  EVP_DigestUpdate(md5, p - 24, 8);
+  EVP_DigestUpdate(md5, message_buffer->value, message_buffer->length);
+  EVP_DigestFinal_ex(md5, hash, NULL);
+  EVP_MD_CTX_destroy(md5);
=20
   memset (&zero, 0, sizeof(zero));
   memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
-  DES_set_key (&deskey, &schedule);
+  DES_set_key_unchecked (&deskey, &schedule);
   DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
 		 &schedule, &zero);
   memcpy (p - 8, hash, 8);	/* SGN_CKSUM */
@@ -108,21 +111,23 @@
 	  (ctx->more_flags & LOCAL) ? 0 : 0xFF,
 	  4);
=20
-  DES_set_key (&deskey, &schedule);
-  DES_cbc_encrypt ((void *)p, (void *)p, 8,
-		   &schedule, (DES_cblock *)(p + 8), DES_ENCRYPT);
+  EVP_CIPHER_CTX_init(&des_ctx);
+  EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, p +=
 8, 1);
+  EVP_Cipher(&des_ctx, p, p, 8);
+  EVP_CIPHER_CTX_cleanup(&des_ctx);
=20
   krb5_auth_con_setlocalseqnumber (context,
 			       ctx->auth_context,
 			       ++seq_number);
   HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
- =20
+
   memset (deskey, 0, sizeof(deskey));
   memset (&schedule, 0, sizeof(schedule));
- =20
+
   *minor_status =3D 0;
   return GSS_S_COMPLETE;
 }
+#endif
=20
 static OM_uint32
 mic_des3
@@ -252,7 +257,7 @@
       *minor_status =3D kret;
       return GSS_S_FAILURE;
   }
- =20
+
   assert (encdata.length =3D=3D 8);
=20
   memcpy (p, encdata.data, encdata.length);
@@ -262,13 +267,13 @@
 			       ctx->auth_context,
 			       ++seq_number);
   HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
- =20
+
   free_Checksum (&cksum);
   *minor_status =3D 0;
   return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gsskrb5_get_mic
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_get_mic
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             gss_qop_t qop_req,
@@ -284,6 +289,10 @@
=20
   GSSAPI_KRB5_INIT (&context);
=20
+  if (ctx->more_flags & IS_CFX)
+      return _gssapi_mic_cfx (minor_status, ctx, context, qop_req,
+			      message_buffer, message_token);
+
   HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
   ret =3D _gsskrb5i_get_token_key(ctx, context, &key);
   HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
@@ -295,8 +304,12 @@
=20
   switch (keytype) {
   case KEYTYPE_DES :
+#ifdef HEIM_WEAK_CRYPTO
       ret =3D mic_des (minor_status, ctx, context, qop_req,
 		     message_buffer, message_token, key);
+#else
+      ret =3D GSS_S_FAILURE;
+#endif
       break;
   case KEYTYPE_DES3 :
       ret =3D mic_des3 (minor_status, ctx, context, qop_req,
@@ -308,8 +321,7 @@
 				     message_buffer, message_token, key);
       break;
   default :
-      ret =3D _gssapi_mic_cfx (minor_status, ctx, context, qop_req,
-			     message_buffer, message_token, key);
+      abort();
       break;
   }
   krb5_free_keyblock (context, key);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/gk=
rb5_err.et
--- a/head/crypto/heimdal/lib/gssapi/krb5/gkrb5_err.et	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/gkrb5_err.et	Tue Apr 17 11:51:51 =
2012 +0300
@@ -2,7 +2,7 @@
 # extended gss krb5 error messages
 #
=20
-id "$Id: gkrb5_err.et 20049 2007-01-24 00:14:24Z lha $"
+id "$Id$"
=20
 error_table gk5
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/gs=
skrb5-private.h
--- a/head/crypto/heimdal/lib/gssapi/krb5/gsskrb5-private.h	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/gsskrb5-private.h	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -16,6 +16,55 @@
 	OM_uint32 */*lifetime*/);
=20
 OM_uint32
+_gk_allocate_buffer (
+	OM_uint32 */*minor_status*/,
+	gss_iov_buffer_desc */*buffer*/,
+	size_t /*size*/);
+
+gss_iov_buffer_desc *
+_gk_find_buffer (
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/,
+	OM_uint32 /*type*/);
+
+OM_uint32 GSSAPI_CALLCONV
+_gk_unwrap_iov (
+	OM_uint32 */*minor_status*/,
+	gss_ctx_id_t /*context_handle*/,
+	int */*conf_state*/,
+	gss_qop_t */*qop_state*/,
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
+
+OM_uint32
+_gk_verify_buffers (
+	OM_uint32 */*minor_status*/,
+	const gsskrb5_ctx /*ctx*/,
+	const gss_iov_buffer_desc */*header*/,
+	const gss_iov_buffer_desc */*padding*/,
+	const gss_iov_buffer_desc */*trailer*/);
+
+OM_uint32 GSSAPI_CALLCONV
+_gk_wrap_iov (
+	OM_uint32 * /*minor_status*/,
+	gss_ctx_id_t /*context_handle*/,
+	int /*conf_req_flag*/,
+	gss_qop_t /*qop_req*/,
+	int * /*conf_state*/,
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
+
+OM_uint32 GSSAPI_CALLCONV
+_gk_wrap_iov_length (
+	OM_uint32 * /*minor_status*/,
+	gss_ctx_id_t /*context_handle*/,
+	int /*conf_req_flag*/,
+	gss_qop_t /*qop_req*/,
+	int */*conf_state*/,
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
+
+OM_uint32
 _gss_DES3_get_mic_compat (
 	OM_uint32 */*minor_status*/,
 	gsskrb5_ctx /*ctx*/,
@@ -61,12 +110,11 @@
 OM_uint32
 _gssapi_mic_cfx (
 	OM_uint32 */*minor_status*/,
-	const gsskrb5_ctx /*context_handle*/,
+	const gsskrb5_ctx /*ctx*/,
 	krb5_context /*context*/,
 	gss_qop_t /*qop_req*/,
 	const gss_buffer_t /*message_buffer*/,
-	gss_buffer_t /*message_token*/,
-	krb5_keyblock */*key*/);
+	gss_buffer_t /*message_token*/);
=20
 OM_uint32
 _gssapi_msg_order_check (
@@ -113,13 +161,22 @@
 OM_uint32
 _gssapi_unwrap_cfx (
 	OM_uint32 */*minor_status*/,
-	const gsskrb5_ctx /*context_handle*/,
+	const gsskrb5_ctx /*ctx*/,
 	krb5_context /*context*/,
 	const gss_buffer_t /*input_message_buffer*/,
 	gss_buffer_t /*output_message_buffer*/,
 	int */*conf_state*/,
+	gss_qop_t */*qop_state*/);
+
+OM_uint32
+_gssapi_unwrap_cfx_iov (
+	OM_uint32 */*minor_status*/,
+	gsskrb5_ctx /*ctx*/,
+	krb5_context /*context*/,
+	int */*conf_state*/,
 	gss_qop_t */*qop_state*/,
-	krb5_keyblock */*key*/);
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
=20
 OM_uint32
 _gssapi_verify_mech_header (
@@ -136,17 +193,16 @@
 	const gss_buffer_t /*token_buffer*/,
 	gss_qop_t * /*qop_state*/,
 	krb5_keyblock */*key*/,
-	char */*type*/);
+	const char */*type*/);
=20
 OM_uint32
 _gssapi_verify_mic_cfx (
 	OM_uint32 */*minor_status*/,
-	const gsskrb5_ctx /*context_handle*/,
+	const gsskrb5_ctx /*ctx*/,
 	krb5_context /*context*/,
 	const gss_buffer_t /*message_buffer*/,
 	const gss_buffer_t /*token_buffer*/,
-	gss_qop_t */*qop_state*/,
-	krb5_keyblock */*key*/);
+	gss_qop_t */*qop_state*/);
=20
 OM_uint32
 _gssapi_verify_pad (
@@ -169,14 +225,33 @@
 OM_uint32
 _gssapi_wrap_cfx (
 	OM_uint32 */*minor_status*/,
-	const gsskrb5_ctx /*context_handle*/,
+	const gsskrb5_ctx /*ctx*/,
+	krb5_context /*context*/,
+	int /*conf_req_flag*/,
+	const gss_buffer_t /*input_message_buffer*/,
+	int */*conf_state*/,
+	gss_buffer_t /*output_message_buffer*/);
+
+OM_uint32
+_gssapi_wrap_cfx_iov (
+	OM_uint32 */*minor_status*/,
+	gsskrb5_ctx /*ctx*/,
+	krb5_context /*context*/,
+	int /*conf_req_flag*/,
+	int */*conf_state*/,
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
+
+OM_uint32
+_gssapi_wrap_iov_length_cfx (
+	OM_uint32 */*minor_status*/,
+	gsskrb5_ctx /*ctx*/,
 	krb5_context /*context*/,
 	int /*conf_req_flag*/,
 	gss_qop_t /*qop_req*/,
-	const gss_buffer_t /*input_message_buffer*/,
 	int */*conf_state*/,
-	gss_buffer_t /*output_message_buffer*/,
-	krb5_keyblock */*key*/);
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
=20
 OM_uint32
 _gssapi_wrap_size_arcfour (
@@ -192,15 +267,14 @@
 OM_uint32
 _gssapi_wrap_size_cfx (
 	OM_uint32 */*minor_status*/,
-	const gsskrb5_ctx /*context_handle*/,
+	const gsskrb5_ctx /*ctx*/,
 	krb5_context /*context*/,
 	int /*conf_req_flag*/,
 	gss_qop_t /*qop_req*/,
 	OM_uint32 /*req_output_size*/,
-	OM_uint32 */*max_input_size*/,
-	krb5_keyblock */*key*/);
+	OM_uint32 */*max_input_size*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_accept_sec_context (
 	OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
@@ -214,7 +288,7 @@
 	OM_uint32 * /*time_rec*/,
 	gss_cred_id_t * /*delegated_cred_handle*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_acquire_cred (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*desired_name*/,
@@ -225,7 +299,18 @@
 	gss_OID_set * /*actual_mechs*/,
 	OM_uint32 * time_rec );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_acquire_cred_ext (
+	OM_uint32 * /*minor_status*/,
+	const gss_name_t /*desired_name*/,
+	gss_const_OID /*credential_type*/,
+	const void */*credential_data*/,
+	OM_uint32 /*time_req*/,
+	gss_const_OID /*desired_mech*/,
+	gss_cred_usage_t /*cred_usage*/,
+	gss_cred_id_t * output_cred_handle );
+
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_add_cred (
 	 OM_uint32 */*minor_status*/,
 	const gss_cred_id_t /*input_cred_handle*/,
@@ -239,7 +324,23 @@
 	OM_uint32 */*initiator_time_rec*/,
 	OM_uint32 */*acceptor_time_rec*/);
=20
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_authorize_localname (
+	OM_uint32 */*minor_status*/,
+	const gss_name_t /*input_name*/,
+	gss_const_buffer_t /*user_name*/,
+	gss_const_OID /*user_name_type*/);
+
 OM_uint32
+_gsskrb5_canon_name (
+	OM_uint32 */*minor_status*/,
+	krb5_context /*context*/,
+	int /*use_dns*/,
+	krb5_const_principal /*sourcename*/,
+	gss_name_t /*targetname*/,
+	krb5_principal */*out*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_canonicalize_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
@@ -249,14 +350,14 @@
 void
 _gsskrb5_clear_status (void);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_compare_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*name1*/,
 	const gss_name_t /*name2*/,
 	int * name_equal );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_context_time (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -296,20 +397,20 @@
 	const void */*ptr*/,
 	OM_uint32 */*n*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_delete_sec_context (
 	OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
 	gss_buffer_t /*output_token*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_display_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_buffer_t /*output_name_buffer*/,
 	gss_OID * output_name_type );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_display_status (
 	OM_uint32 */*minor_status*/,
 	OM_uint32 /*status_value*/,
@@ -318,7 +419,7 @@
 	OM_uint32 */*message_context*/,
 	gss_buffer_t /*status_string*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_duplicate_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*src_name*/,
@@ -349,13 +450,19 @@
 	OM_uint32 /*n*/,
 	u_char */*p*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_export_cred (
+	OM_uint32 */*minor_status*/,
+	gss_cred_id_t /*cred_handle*/,
+	gss_buffer_t /*cred_token*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_export_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_buffer_t exported_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_export_sec_context (
 	 OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
@@ -367,7 +474,7 @@
 	size_t /*total_len*/,
 	const u_char **/*mech_ret*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_get_mic (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -381,28 +488,26 @@
 	gsskrb5_ctx /*ctx*/,
 	OM_uint32 */*tkt_flags*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_import_cred (
-	OM_uint32 */*minor_status*/,
-	krb5_ccache /*id*/,
-	krb5_principal /*keytab_principal*/,
-	krb5_keytab /*keytab*/,
-	gss_cred_id_t */*cred*/);
+	OM_uint32 * /*minor_status*/,
+	gss_buffer_t /*cred_token*/,
+	gss_cred_id_t * /*cred_handle*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_import_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_buffer_t /*input_name_buffer*/,
 	const gss_OID /*input_name_type*/,
 	gss_name_t * output_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_import_sec_context (
 	 OM_uint32 * /*minor_status*/,
 	const gss_buffer_t /*interprocess_token*/,
 	gss_ctx_id_t * context_handle );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_indicate_mechs (
 	OM_uint32 * /*minor_status*/,
 	gss_OID_set * mech_set );
@@ -410,10 +515,10 @@
 krb5_error_code
 _gsskrb5_init (krb5_context */*context*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_init_sec_context (
 	OM_uint32 * /*minor_status*/,
-	const gss_cred_id_t /*initiator_cred_handle*/,
+	const gss_cred_id_t /*cred_handle*/,
 	gss_ctx_id_t * /*context_handle*/,
 	const gss_name_t /*target_name*/,
 	const gss_OID /*mech_type*/,
@@ -426,7 +531,7 @@
 	OM_uint32 * /*ret_flags*/,
 	OM_uint32 * time_rec );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_inquire_context (
 	 OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -438,7 +543,7 @@
 	int * /*locally_initiated*/,
 	int * open_context );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_inquire_cred (
 	OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
@@ -447,7 +552,7 @@
 	gss_cred_usage_t * /*cred_usage*/,
 	gss_OID_set * mechanisms );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_inquire_cred_by_mech (
 	 OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
@@ -457,26 +562,26 @@
 	OM_uint32 * /*acceptor_lifetime*/,
 	gss_cred_usage_t * cred_usage );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_inquire_cred_by_oid (
 	OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
 	const gss_OID /*desired_object*/,
 	gss_buffer_set_t */*data_set*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_inquire_mechs_for_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_OID_set * mech_types );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_inquire_names_for_mech (
 	 OM_uint32 * /*minor_status*/,
 	const gss_OID /*mechanism*/,
 	gss_OID_set * name_types );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_inquire_sec_context_by_oid (
 	OM_uint32 */*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -490,6 +595,14 @@
 	const char **/*out_name*/);
=20
 OM_uint32
+_gsskrb5_krb5_import_cred (
+	OM_uint32 */*minor_status*/,
+	krb5_ccache /*id*/,
+	krb5_principal /*keytab_principal*/,
+	krb5_keytab /*keytab*/,
+	gss_cred_id_t */*cred*/);
+
+OM_uint32
 _gsskrb5_lifetime_left (
 	OM_uint32 */*minor_status*/,
 	krb5_context /*context*/,
@@ -503,13 +616,20 @@
 	const void */*type*/,
 	const gss_OID /*mech*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_pname_to_uid (
+	OM_uint32 */*minor_status*/,
+	const gss_name_t /*pname*/,
+	const gss_OID /*mech_type*/,
+	uid_t */*uidp*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_process_context_token (
 	 OM_uint32 */*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
 	const gss_buffer_t token_buffer );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_pseudo_random (
 	OM_uint32 */*minor_status*/,
 	gss_ctx_id_t /*context_handle*/,
@@ -519,41 +639,33 @@
 	gss_buffer_t /*prf_out*/);
=20
 OM_uint32
-_gsskrb5_register_acceptor_identity (const char */*identity*/);
+_gsskrb5_register_acceptor_identity (
+	OM_uint32 */*min_stat*/,
+	const char */*identity*/);
=20
 OM_uint32
 _gsskrb5_release_buffer (
 	OM_uint32 * /*minor_status*/,
 	gss_buffer_t buffer );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_release_cred (
 	OM_uint32 * /*minor_status*/,
 	gss_cred_id_t * cred_handle );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_release_name (
 	OM_uint32 * /*minor_status*/,
 	gss_name_t * input_name );
=20
-OM_uint32
-_gsskrb5_seal (
-	OM_uint32 * /*minor_status*/,
-	gss_ctx_id_t /*context_handle*/,
-	int /*conf_req_flag*/,
-	int /*qop_req*/,
-	gss_buffer_t /*input_message_buffer*/,
-	int * /*conf_state*/,
-	gss_buffer_t output_message_buffer );
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_set_cred_option (
 	OM_uint32 */*minor_status*/,
 	gss_cred_id_t */*cred_handle*/,
 	const gss_OID /*desired_object*/,
 	const gss_buffer_t /*value*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_set_sec_context_option (
 	OM_uint32 */*minor_status*/,
 	gss_ctx_id_t */*context_handle*/,
@@ -562,27 +674,22 @@
=20
 void
 _gsskrb5_set_status (
+	int /*ret*/,
 	const char */*fmt*/,
 	...);
=20
-OM_uint32
-_gsskrb5_sign (
-	OM_uint32 * /*minor_status*/,
-	gss_ctx_id_t /*context_handle*/,
-	int /*qop_req*/,
-	gss_buffer_t /*message_buffer*/,
-	gss_buffer_t message_token );
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_store_cred (
+	OM_uint32 */*minor_status*/,
+	gss_cred_id_t /*input_cred_handle*/,
+	gss_cred_usage_t /*cred_usage*/,
+	const gss_OID /*desired_mech*/,
+	OM_uint32 /*overwrite_cred*/,
+	OM_uint32 /*default_cred*/,
+	gss_OID_set */*elements_stored*/,
+	gss_cred_usage_t */*cred_usage_stored*/);
=20
-OM_uint32
-_gsskrb5_unseal (
-	OM_uint32 * /*minor_status*/,
-	gss_ctx_id_t /*context_handle*/,
-	gss_buffer_t /*input_message_buffer*/,
-	gss_buffer_t /*output_message_buffer*/,
-	int * /*conf_state*/,
-	int * qop_state );
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_unwrap (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -592,14 +699,6 @@
 	gss_qop_t * qop_state );
=20
 OM_uint32
-_gsskrb5_verify (
-	OM_uint32 * /*minor_status*/,
-	gss_ctx_id_t /*context_handle*/,
-	gss_buffer_t /*message_buffer*/,
-	gss_buffer_t /*token_buffer*/,
-	int * qop_state );
-
-OM_uint32
 _gsskrb5_verify_8003_checksum (
 	 OM_uint32 */*minor_status*/,
 	const gss_channel_bindings_t /*input_chan_bindings*/,
@@ -614,7 +713,7 @@
 	const void */*type*/,
 	gss_OID /*oid*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_verify_mic (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -625,14 +724,14 @@
 OM_uint32
 _gsskrb5_verify_mic_internal (
 	OM_uint32 * /*minor_status*/,
-	const gsskrb5_ctx /*context_handle*/,
+	const gsskrb5_ctx /*ctx*/,
 	krb5_context /*context*/,
 	const gss_buffer_t /*message_buffer*/,
 	const gss_buffer_t /*token_buffer*/,
 	gss_qop_t * /*qop_state*/,
-	char * type );
+	const char * type );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_wrap (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -642,7 +741,7 @@
 	int * /*conf_state*/,
 	gss_buffer_t output_message_buffer );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_wrap_size_limit (
 	 OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -652,18 +751,11 @@
 	OM_uint32 * max_input_size );
=20
 krb5_error_code
-_gsskrb5cfx_max_wrap_length_cfx (
-	krb5_context /*context*/,
-	krb5_crypto /*crypto*/,
-	int /*conf_req_flag*/,
-	size_t /*input_length*/,
-	OM_uint32 */*output_length*/);
-
-krb5_error_code
 _gsskrb5cfx_wrap_length_cfx (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
 	int /*conf_req_flag*/,
+	int /*dce_style*/,
 	size_t /*input_length*/,
 	size_t */*output_length*/,
 	size_t */*cksumsize*/,
@@ -697,7 +789,8 @@
=20
 void
 _gsskrb5i_is_cfx (
+	krb5_context /*context*/,
 	gsskrb5_ctx /*ctx*/,
-	int */*is_cfx*/);
+	int /*acceptor*/);
=20
 #endif /* __gsskrb5_private_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/gs=
skrb5_locl.h
--- a/head/crypto/heimdal/lib/gssapi/krb5/gsskrb5_locl.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/gsskrb5_locl.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,49 +1,48 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: gsskrb5_locl.h 20324 2007-04-12 16:46:01Z lha $ */
+/* $Id$ */
=20
 #ifndef GSSKRB5_LOCL_H
 #define GSSKRB5_LOCL_H
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #include <krb5_locl.h>
 #include <gkrb5_err.h>
 #include <gssapi.h>
 #include <gssapi_mech.h>
+#include <gssapi_krb5.h>
 #include <assert.h>
=20
 #include "cfx.h"
@@ -54,19 +53,24 @@
=20
 struct gss_msg_order;
=20
-typedef struct {
+typedef struct gsskrb5_ctx {
   struct krb5_auth_context_data *auth_context;
+  struct krb5_auth_context_data *deleg_auth_context;
   krb5_principal source, target;
 #define IS_DCE_STYLE(ctx) (((ctx)->flags & GSS_C_DCE_STYLE) !=3D 0)
   OM_uint32 flags;
-  enum { LOCAL =3D 1, OPEN =3D 2,=20
+  enum { LOCAL =3D 1, OPEN =3D 2,
 	 COMPAT_OLD_DES3 =3D 4,
          COMPAT_OLD_DES3_SELECTED =3D 8,
-	 ACCEPTOR_SUBKEY =3D 16
+	 ACCEPTOR_SUBKEY =3D 16,
+	 RETRIED =3D 32,
+	 CLOSE_CCACHE =3D 64,
+	 IS_CFX =3D 128
   } more_flags;
   enum gss_ctx_id_t_state {
       /* initiator states */
       INITIATOR_START,
+      INITIATOR_RESTART,
       INITIATOR_WAIT_FOR_MUTAL,
       INITIATOR_READY,
       /* acceptor states */
@@ -74,18 +78,22 @@
       ACCEPTOR_WAIT_FOR_DCESTYLE,
       ACCEPTOR_READY
   } state;
+  krb5_creds *kcred;
+  krb5_ccache ccache;
   struct krb5_ticket *ticket;
   OM_uint32 lifetime;
   HEIMDAL_MUTEX ctx_id_mutex;
   struct gss_msg_order *order;
   krb5_keyblock *service_keyblock;
   krb5_data fwd_data;
+  krb5_crypto crypto;
 } *gsskrb5_ctx;
=20
 typedef struct {
   krb5_principal principal;
   int cred_flags;
 #define GSS_CF_DESTROY_CRED_ON_RELEASE	1
+#define GSS_CF_NO_CI_FLAGS		2
   struct krb5_keytab_data *keytab;
   OM_uint32 lifetime;
   gss_cred_usage_t usage;
@@ -104,16 +112,11 @@
 extern krb5_keytab _gsskrb5_keytab;
 extern HEIMDAL_MUTEX gssapi_keytab_mutex;
=20
-struct gssapi_thr_context {
-    HEIMDAL_MUTEX mutex;
-    char *error_string;
-};
-
 /*
  * Prototypes
  */
=20
-#include <krb5/gsskrb5-private.h>
+#include <gsskrb5-private.h>
=20
 #define GSSAPI_KRB5_INIT(ctx) do {				\
     krb5_error_code kret_gss_init;				\
@@ -131,4 +134,7 @@
 #define SC_LOCAL_SUBKEY	  0x08
 #define SC_REMOTE_SUBKEY  0x10
=20
+/* type to signal that that dns canon maybe should be done */
+#define MAGIC_HOSTBASED_NAME_TYPE 4711
+
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/im=
port_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/import_name.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/import_name.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: import_name.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 static OM_uint32
 parse_krb5_name (OM_uint32 *minor_status,
@@ -83,18 +81,61 @@
     return ret;
 }
=20
+OM_uint32
+_gsskrb5_canon_name(OM_uint32 *minor_status, krb5_context context,
+		    int use_dns, krb5_const_principal sourcename, gss_name_t targetname,
+		    krb5_principal *out)
+{
+    krb5_principal p =3D (krb5_principal)targetname;
+    krb5_error_code ret;
+    char *hostname =3D NULL, *service;
+
+    *minor_status =3D 0;
+
+    /* If its not a hostname */
+    if (krb5_principal_get_type(context, p) !=3D MAGIC_HOSTBASED_NAME_TYPE=
) {
+	ret =3D krb5_copy_principal(context, p, out);
+    } else if (!use_dns) {
+	ret =3D krb5_copy_principal(context, p, out);
+	if (ret)
+	    goto out;
+	krb5_principal_set_type(context, *out, KRB5_NT_SRV_HST);
+	if (sourcename)
+	    ret =3D krb5_principal_set_realm(context, *out, sourcename->realm);
+    } else {
+	if (p->name.name_string.len =3D=3D 0)
+	    return GSS_S_BAD_NAME;
+	else if (p->name.name_string.len > 1)
+	    hostname =3D p->name.name_string.val[1];
+
+	service =3D p->name.name_string.val[0];
+
+	ret =3D krb5_sname_to_principal(context,
+				      hostname,
+				      service,
+				      KRB5_NT_SRV_HST,
+				      out);
+    }
+
+ out:
+    if (ret) {
+	*minor_status =3D ret;
+	return GSS_S_FAILURE;
+    }
+
+    return 0;
+}
+
+
 static OM_uint32
 import_hostbased_name (OM_uint32 *minor_status,
 		       krb5_context context,
 		       const gss_buffer_t input_name_buffer,
 		       gss_name_t *output_name)
 {
+    krb5_principal princ =3D NULL;
     krb5_error_code kerr;
-    char *tmp;
-    char *p;
-    char *host;
-    char local_hostname[MAXHOSTNAMELEN];
-    krb5_principal princ =3D NULL;
+    char *tmp, *p, *host =3D NULL;
=20
     tmp =3D malloc (input_name_buffer->length + 1);
     if (tmp =3D=3D NULL) {
@@ -110,31 +151,20 @@
     if (p !=3D NULL) {
 	*p =3D '\0';
 	host =3D p + 1;
-    } else {
-	if (gethostname(local_hostname, sizeof(local_hostname)) < 0) {
-	    *minor_status =3D errno;
-	    free (tmp);
-	    return GSS_S_FAILURE;
-	}
-	host =3D local_hostname;
     }
=20
-    kerr =3D krb5_sname_to_principal (context,
-				    host,
-				    tmp,
-				    KRB5_NT_SRV_HST,
-				    &princ);
+    kerr =3D krb5_make_principal(context, &princ, NULL, tmp, host, NULL);
     free (tmp);
     *minor_status =3D kerr;
-    if (kerr =3D=3D 0) {
-	*output_name =3D (gss_name_t)princ;
-	return GSS_S_COMPLETE;
-    }
-
     if (kerr =3D=3D KRB5_PARSE_ILLCHAR || kerr =3D=3D KRB5_PARSE_MALFORMED)
 	return GSS_S_BAD_NAME;
+    else if (kerr)
+	return GSS_S_FAILURE;
=20
-    return GSS_S_FAILURE;
+    krb5_principal_set_type(context, princ, MAGIC_HOSTBASED_NAME_TYPE);
+    *output_name =3D (gss_name_t)princ;
+
+    return 0;
 }
=20
 static OM_uint32
@@ -159,7 +189,7 @@
 	p[3] !=3D GSS_KRB5_MECHANISM->length + 2 ||
 	p[4] !=3D 0x06 ||
 	p[5] !=3D GSS_KRB5_MECHANISM->length ||
-	memcmp(&p[6], GSS_KRB5_MECHANISM->elements,=20
+	memcmp(&p[6], GSS_KRB5_MECHANISM->elements,
 	       GSS_KRB5_MECHANISM->length) !=3D 0)
 	return GSS_S_BAD_NAME;
=20
@@ -185,7 +215,7 @@
     return ret;
 }
=20
-OM_uint32 _gsskrb5_import_name
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_import_name
            (OM_uint32 * minor_status,
             const gss_buffer_t input_name_buffer,
             const gss_OID input_name_type,
@@ -196,7 +226,7 @@
=20
     *minor_status =3D 0;
     *output_name =3D GSS_C_NO_NAME;
-   =20
+
     GSSAPI_KRB5_INIT (&context);
=20
     if (gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE) ||
@@ -205,7 +235,7 @@
 				      context,
 				      input_name_buffer,
 				      output_name);
-    else if (gss_oid_equal(input_name_type, GSS_C_NO_OID)
+    else if (input_name_type =3D=3D GSS_C_NO_OID
 	     || gss_oid_equal(input_name_type, GSS_C_NT_USER_NAME)
 	     || gss_oid_equal(input_name_type, GSS_KRB5_NT_PRINCIPAL_NAME))
  	/* default printable syntax */
@@ -216,7 +246,7 @@
     else if (gss_oid_equal(input_name_type, GSS_C_NT_EXPORT_NAME)) {
 	return import_export_name(minor_status,
 				  context,
-				  input_name_buffer,=20
+				  input_name_buffer,
 				  output_name);
     } else {
 	*minor_status =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/im=
port_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/import_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/import_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1999 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: import_sec_context.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_import_sec_context (
     OM_uint32 * minor_status,
     const gss_buffer_t interprocess_token,
@@ -52,8 +50,7 @@
     krb5_data data;
     gss_buffer_desc buffer;
     krb5_keyblock keyblock;
-    int32_t tmp;
-    int32_t flags;
+    int32_t flags, tmp;
     gsskrb5_ctx ctx;
     gss_name_t name;
=20
@@ -96,8 +93,9 @@
     /* retrieve the auth context */
=20
     ac =3D ctx->auth_context;
-    if (krb5_ret_uint32 (sp, &ac->flags) !=3D 0)
+    if (krb5_ret_int32 (sp, &tmp) !=3D 0)
 	goto failure;
+    ac->flags =3D tmp;
     if (flags & SC_LOCAL_ADDRESS) {
 	if (krb5_ret_address (sp, localp =3D &local) !=3D 0)
 	    goto failure;
@@ -184,7 +182,7 @@
 	    krb5_data_free (&data);
 	    goto failure;
 	}
-    }   =20
+    }
     ctx->target =3D (krb5_principal)name;
     krb5_data_free (&data);
=20
@@ -200,10 +198,12 @@
=20
     ret =3D _gssapi_msg_order_import(minor_status, sp, &ctx->order);
     if (ret)
-        goto failure;   =20
-   =20
+        goto failure;
+
     krb5_storage_free (sp);
=20
+    _gsskrb5i_is_cfx(context, ctx, (ctx->more_flags & LOCAL) =3D=3D 0);
+
     *context_handle =3D (gss_ctx_id_t)ctx;
=20
     return GSS_S_COMPLETE;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
dicate_mechs.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/indicate_mechs.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/indicate_mechs.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: indicate_mechs.c 20688 2007-05-17 18:44:31Z lha $");
-
-OM_uint32 _gsskrb5_indicate_mechs
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_indicate_mechs
            (OM_uint32 * minor_status,
             gss_OID_set * mech_set
            )
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
it.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/init.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/init.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2001, 2003, 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2003, 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: init.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 static HEIMDAL_MUTEX context_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
 static int created_key;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
it_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/init_sec_context.c	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/init_sec_context.c	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: init_sec_context.c 22071 2007-11-14 20:04:50Z lha $");
+#include "gsskrb5_locl.h"
=20
 /*
  * copy the addresses from `input_chan_bindings' (if any) to
@@ -43,14 +41,14 @@
 static OM_uint32
 set_addresses (krb5_context context,
 	       krb5_auth_context ac,
-	       const gss_channel_bindings_t input_chan_bindings)	      =20
+	       const gss_channel_bindings_t input_chan_bindings)
 {
-    /* Port numbers are expected to be in application_data.value,=20
-     * initator's port first */=20
+    /* Port numbers are expected to be in application_data.value,
+     * initator's port first */
=20
     krb5_address initiator_addr, acceptor_addr;
     krb5_error_code kret;
-      =20
+
     if (input_chan_bindings =3D=3D GSS_C_NO_CHANNEL_BINDINGS
 	|| input_chan_bindings->application_data.length !=3D
 	2 * sizeof(ac->local_port))
@@ -58,13 +56,13 @@
=20
     memset(&initiator_addr, 0, sizeof(initiator_addr));
     memset(&acceptor_addr, 0, sizeof(acceptor_addr));
-      =20
+
     ac->local_port =3D
 	*(int16_t *) input_chan_bindings->application_data.value;
-      =20
+
     ac->remote_port =3D
 	*((int16_t *) input_chan_bindings->application_data.value + 1);
-      =20
+
     kret =3D _gsskrb5i_address_to_krb5addr(context,
 					 input_chan_bindings->acceptor_addrtype,
 					 &input_chan_bindings->acceptor_address,
@@ -72,7 +70,7 @@
 					 &acceptor_addr);
     if (kret)
 	return kret;
-          =20
+
     kret =3D _gsskrb5i_address_to_krb5addr(context,
 					 input_chan_bindings->initiator_addrtype,
 					 &input_chan_bindings->initiator_address,
@@ -82,15 +80,15 @@
 	krb5_free_address (context, &acceptor_addr);
 	return kret;
     }
-      =20
+
     kret =3D krb5_auth_con_setaddrs(context,
 				  ac,
 				  &initiator_addr,  /* local address */
 				  &acceptor_addr);  /* remote address */
-      =20
+
     krb5_free_address (context, &initiator_addr);
     krb5_free_address (context, &acceptor_addr);
-      =20
+
 #if 0
     free(input_chan_bindings->application_data.value);
     input_chan_bindings->application_data.value =3D NULL;
@@ -119,8 +117,11 @@
 	return GSS_S_FAILURE;
     }
     ctx->auth_context		=3D NULL;
+    ctx->deleg_auth_context	=3D NULL;
     ctx->source			=3D NULL;
     ctx->target			=3D NULL;
+    ctx->kcred			=3D NULL;
+    ctx->ccache			=3D NULL;
     ctx->state			=3D state;
     ctx->flags			=3D 0;
     ctx->more_flags		=3D 0;
@@ -129,14 +130,21 @@
     krb5_data_zero(&ctx->fwd_data);
     ctx->lifetime		=3D GSS_C_INDEFINITE;
     ctx->order			=3D NULL;
+    ctx->crypto			=3D NULL;
     HEIMDAL_MUTEX_init(&ctx->ctx_id_mutex);
=20
     kret =3D krb5_auth_con_init (context, &ctx->auth_context);
     if (kret) {
 	*minor_status =3D kret;
+	HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
+	return GSS_S_FAILURE;
+    }
=20
+    kret =3D krb5_auth_con_init (context, &ctx->deleg_auth_context);
+    if (kret) {
+	*minor_status =3D kret;
+	krb5_auth_con_free(context, ctx->auth_context);
 	HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
-	=09
 	return GSS_S_FAILURE;
     }
=20
@@ -144,9 +152,22 @@
     if (kret) {
 	*minor_status =3D kret;
=20
+	krb5_auth_con_free(context, ctx->auth_context);
+	krb5_auth_con_free(context, ctx->deleg_auth_context);
+
 	HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
=20
+	return GSS_S_BAD_BINDINGS;
+    }
+
+    kret =3D set_addresses(context, ctx->deleg_auth_context, input_chan_bi=
ndings);
+    if (kret) {
+	*minor_status =3D kret;
+
 	krb5_auth_con_free(context, ctx->auth_context);
+	krb5_auth_con_free(context, ctx->deleg_auth_context);
+
+	HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
=20
 	return GSS_S_BAD_BINDINGS;
     }
@@ -161,6 +182,16 @@
 			   KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED,
 			   NULL);
=20
+    /*
+     * We need a sequence number
+     */
+
+    krb5_auth_con_addflags(context,
+			   ctx->deleg_auth_context,
+			   KRB5_AUTH_CONTEXT_DO_SEQUENCE |
+			   KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED,
+			   NULL);
+
     *context_handle =3D (gss_ctx_id_t)ctx;
=20
     return GSS_S_COMPLETE;
@@ -173,17 +204,29 @@
 	krb5_context context,
 	krb5_ccache ccache,
 	gsskrb5_ctx ctx,
-	krb5_const_principal target_name,
+	const gss_name_t target_name,
+	int use_dns,
 	OM_uint32 time_req,
-	OM_uint32 * time_rec,
-	krb5_creds ** cred)
+	OM_uint32 * time_rec)
 {
     OM_uint32 ret;
     krb5_error_code kret;
     krb5_creds this_cred;
     OM_uint32 lifetime_rec;
=20
-    *cred =3D NULL;
+    if (ctx->target) {
+	krb5_free_principal(context, ctx->target);
+	ctx->target =3D NULL;
+    }
+    if (ctx->kcred) {
+	krb5_free_creds(context, ctx->kcred);
+	ctx->kcred =3D NULL;
+    }
+
+    ret =3D _gsskrb5_canon_name(minor_status, context, use_dns,
+			      ctx->source, target_name, &ctx->target);
+    if (ret)
+	return ret;
=20
     memset(&this_cred, 0, sizeof(this_cred));
     this_cred.client =3D ctx->source;
@@ -204,13 +247,13 @@
 				0,
 				ccache,
 				&this_cred,
-				cred);
+				&ctx->kcred);
     if (kret) {
 	*minor_status =3D kret;
 	return GSS_S_FAILURE;
     }
=20
-    ctx->lifetime =3D (*cred)->times.endtime;
+    ctx->lifetime =3D ctx->kcred->times.endtime;
=20
     ret =3D _gsskrb5_lifetime_left(minor_status, context,
 				 ctx->lifetime, &lifetime_rec);
@@ -232,27 +275,33 @@
 	gsskrb5_ctx ctx,
 	krb5_context context)
 {
-	OM_uint32 ret;
-	int32_t seq_number;
-	int is_cfx =3D 0;
-	OM_uint32 flags =3D ctx->flags;
+    OM_uint32 ret;
+    int32_t seq_number;
+    int is_cfx =3D 0;
+    OM_uint32 flags =3D ctx->flags;
=20
-	krb5_auth_getremoteseqnumber (context,
-				      ctx->auth_context,
-				      &seq_number);
+    krb5_free_creds(context, ctx->kcred);
+    ctx->kcred =3D NULL;
=20
-	_gsskrb5i_is_cfx(ctx, &is_cfx);
+    if (ctx->more_flags & CLOSE_CCACHE)
+	krb5_cc_close(context, ctx->ccache);
+    ctx->ccache =3D NULL;
=20
-	ret =3D _gssapi_msg_order_create(minor_status,
-				       &ctx->order,
-				       _gssapi_msg_order_f(flags),
-				       seq_number, 0, is_cfx);
-	if (ret) return ret;
+    krb5_auth_con_getremoteseqnumber (context, ctx->auth_context, &seq_num=
ber);
=20
-	ctx->state	=3D INITIATOR_READY;
-	ctx->more_flags	|=3D OPEN;
+    _gsskrb5i_is_cfx(context, ctx, 0);
+    is_cfx =3D (ctx->more_flags & IS_CFX);
=20
-	return GSS_S_COMPLETE;
+    ret =3D _gssapi_msg_order_create(minor_status,
+				   &ctx->order,
+				   _gssapi_msg_order_f(flags),
+				   seq_number, 0, is_cfx);
+    if (ret) return ret;
+
+    ctx->state	=3D INITIATOR_READY;
+    ctx->more_flags	|=3D OPEN;
+
+    return GSS_S_COMPLETE;
 }
=20
 /*
@@ -266,39 +315,39 @@
 	       krb5_creds *cred,
 	       krb5_const_principal name,
 	       krb5_data *fwd_data,
+	       uint32_t flagmask,
 	       uint32_t *flags)
 {
     krb5_creds creds;
     KDCOptions fwd_flags;
     krb5_error_code kret;
-      =20
+
     memset (&creds, 0, sizeof(creds));
     krb5_data_zero (fwd_data);
-      =20
+
     kret =3D krb5_cc_get_principal(context, ccache, &creds.client);
-    if (kret)=20
+    if (kret)
 	goto out;
-      =20
-    kret =3D krb5_build_principal(context,
-				&creds.server,
-				strlen(creds.client->realm),
-				creds.client->realm,
-				KRB5_TGS_NAME,
-				creds.client->realm,
-				NULL);
+
+    kret =3D krb5_make_principal(context,
+			       &creds.server,
+			       creds.client->realm,
+			       KRB5_TGS_NAME,
+			       creds.client->realm,
+			       NULL);
     if (kret)
-	goto out;=20
-      =20
+	goto out;
+
     creds.times.endtime =3D 0;
-      =20
+
     memset(&fwd_flags, 0, sizeof(fwd_flags));
     fwd_flags.forwarded =3D 1;
     fwd_flags.forwardable =3D 1;
-      =20
+
     if ( /*target_name->name.name_type !=3D KRB5_NT_SRV_HST ||*/
-	name->name.name_string.len < 2)=20
+	name->name.name_string.len < 2)
 	goto out;
-      =20
+
     kret =3D krb5_get_forwarded_creds(context,
 				    ac,
 				    ccache,
@@ -306,13 +355,13 @@
 				    name->name.name_string.val[1],
 				    &creds,
 				    fwd_data);
-      =20
+
  out:
     if (kret)
-	*flags &=3D ~GSS_C_DELEG_FLAG;
+	*flags &=3D ~flagmask;
     else
-	*flags |=3D GSS_C_DELEG_FLAG;
-      =20
+	*flags |=3D flagmask;
+
     if (creds.client)
 	krb5_free_principal(context, creds.client);
     if (creds.server)
@@ -326,13 +375,143 @@
 static OM_uint32
 init_auth
 (OM_uint32 * minor_status,
- gsskrb5_cred initiator_cred_handle,
+ gsskrb5_cred cred,
  gsskrb5_ctx ctx,
  krb5_context context,
- krb5_const_principal name,
+ gss_name_t name,
  const gss_OID mech_type,
  OM_uint32 req_flags,
  OM_uint32 time_req,
+ const gss_buffer_t input_token,
+ gss_OID * actual_mech_type,
+ gss_buffer_t output_token,
+ OM_uint32 * ret_flags,
+ OM_uint32 * time_rec
+    )
+{
+    OM_uint32 ret =3D GSS_S_FAILURE;
+    krb5_error_code kret;
+    krb5_data outbuf;
+    krb5_data fwd_data;
+    OM_uint32 lifetime_rec;
+    int allow_dns =3D 1;
+
+    krb5_data_zero(&outbuf);
+    krb5_data_zero(&fwd_data);
+
+    *minor_status =3D 0;
+
+    if (actual_mech_type)
+	*actual_mech_type =3D GSS_KRB5_MECHANISM;
+
+    if (cred =3D=3D NULL) {
+	kret =3D krb5_cc_default (context, &ctx->ccache);
+	if (kret) {
+	    *minor_status =3D kret;
+	    ret =3D GSS_S_FAILURE;
+	    goto failure;
+	}
+	ctx->more_flags |=3D CLOSE_CCACHE;
+    } else
+	ctx->ccache =3D cred->ccache;
+
+    kret =3D krb5_cc_get_principal (context, ctx->ccache, &ctx->source);
+    if (kret) {
+	*minor_status =3D kret;
+	ret =3D GSS_S_FAILURE;
+	goto failure;
+    }
+
+    /*
+     * This is hideous glue for (NFS) clients that wants to limit the
+     * available enctypes to what it can support (encryption in
+     * kernel). If there is no enctypes selected for this credential,
+     * reset it to the default set of enctypes.
+     */
+    {
+	krb5_enctype *enctypes =3D NULL;
+
+	if (cred && cred->enctypes)
+	    enctypes =3D cred->enctypes;
+	krb5_set_default_in_tkt_etypes(context, enctypes);
+    }
+
+    /* canon name if needed for client + target realm */
+    kret =3D krb5_cc_get_config(context, ctx->ccache, NULL,
+			      "realm-config", &outbuf);
+    if (kret =3D=3D 0) {
+	/* XXX 2 is no server canon */
+	if (outbuf.length < 1 || ((((unsigned char *)outbuf.data)[0]) & 2))
+	    allow_dns =3D 0;
+	krb5_data_free(&outbuf);
+    }
+
+    /*
+     * First we try w/o dns, hope that the KDC have register alias
+     * (and referrals if cross realm) for this principal. If that
+     * fails and if we are allowed to using this realm try again with
+     * DNS canonicalizion.
+     */
+    ret =3D gsskrb5_get_creds(minor_status, context, ctx->ccache,
+			    ctx, name, 0, time_req,
+			    time_rec);
+    if (ret && allow_dns)
+	ret =3D gsskrb5_get_creds(minor_status, context, ctx->ccache,
+				ctx, name, 1, time_req,
+				time_rec);
+    if (ret)
+	goto failure;
+
+    ctx->lifetime =3D ctx->kcred->times.endtime;
+
+    ret =3D _gss_DES3_get_mic_compat(minor_status, ctx, context);
+    if (ret)
+	goto failure;
+
+    ret =3D _gsskrb5_lifetime_left(minor_status,
+				 context,
+				 ctx->lifetime,
+				 &lifetime_rec);
+    if (ret)
+	goto failure;
+
+    if (lifetime_rec =3D=3D 0) {
+	*minor_status =3D 0;
+	ret =3D GSS_S_CONTEXT_EXPIRED;
+	goto failure;
+    }
+
+    krb5_auth_con_setkey(context,
+			 ctx->auth_context,
+			 &ctx->kcred->session);
+
+    kret =3D krb5_auth_con_generatelocalsubkey(context,
+					     ctx->auth_context,
+					     &ctx->kcred->session);
+    if(kret) {
+	*minor_status =3D kret;
+	ret =3D GSS_S_FAILURE;
+	goto failure;
+    }
+
+    return GSS_S_COMPLETE;
+
+failure:
+    if (ctx->ccache && (ctx->more_flags & CLOSE_CCACHE))
+	krb5_cc_close(context, ctx->ccache);
+    ctx->ccache =3D NULL;
+
+    return ret;
+
+}
+
+static OM_uint32
+init_auth_restart
+(OM_uint32 * minor_status,
+ gsskrb5_cred cred,
+ gsskrb5_ctx ctx,
+ krb5_context context,
+ OM_uint32 req_flags,
  const gss_channel_bindings_t input_chan_bindings,
  const gss_buffer_t input_token,
  gss_OID * actual_mech_type,
@@ -344,142 +523,70 @@
     OM_uint32 ret =3D GSS_S_FAILURE;
     krb5_error_code kret;
     krb5_flags ap_options;
-    krb5_creds *cred =3D NULL;
     krb5_data outbuf;
-    krb5_ccache ccache =3D NULL;
     uint32_t flags;
     krb5_data authenticator;
     Checksum cksum;
     krb5_enctype enctype;
-    krb5_data fwd_data;
-    OM_uint32 lifetime_rec;
+    krb5_data fwd_data, timedata;
+    int32_t offset =3D 0, oldoffset =3D 0;
+    uint32_t flagmask;
=20
     krb5_data_zero(&outbuf);
     krb5_data_zero(&fwd_data);
=20
     *minor_status =3D 0;
=20
-    if (actual_mech_type)
-	*actual_mech_type =3D GSS_KRB5_MECHANISM;
+    /*
+     * If the credential doesn't have ok-as-delegate, check if there
+     * is a realm setting and use that.
+     */
+    if (!ctx->kcred->flags.b.ok_as_delegate) {
+	krb5_data data;
=20
-    if (initiator_cred_handle =3D=3D NULL) {
-	kret =3D krb5_cc_default (context, &ccache);
-	if (kret) {
-	    *minor_status =3D kret;
-	    ret =3D GSS_S_FAILURE;
-	    goto failure;
+	ret =3D krb5_cc_get_config(context, ctx->ccache, NULL,
+				 "realm-config", &data);
+	if (ret =3D=3D 0) {
+	    /* XXX 1 is use ok-as-delegate */
+	    if (data.length < 1 || ((((unsigned char *)data.data)[0]) & 1) =3D=3D=
 0)
+		req_flags &=3D ~(GSS_C_DELEG_FLAG|GSS_C_DELEG_POLICY_FLAG);
+	    krb5_data_free(&data);
 	}
-    } else
-	ccache =3D initiator_cred_handle->ccache;
-
-    kret =3D krb5_cc_get_principal (context, ccache, &ctx->source);
-    if (kret) {
-	*minor_status =3D kret;
-	ret =3D GSS_S_FAILURE;
-	goto failure;
     }
=20
-    kret =3D krb5_copy_principal (context, name, &ctx->target);
-    if (kret) {
-	*minor_status =3D kret;
-	ret =3D GSS_S_FAILURE;
-	goto failure;
-    }
+    flagmask =3D 0;
=20
-    ret =3D _gss_DES3_get_mic_compat(minor_status, ctx, context);
-    if (ret)
-	goto failure;
+    /* if we used GSS_C_DELEG_POLICY_FLAG, trust KDC */
+    if ((req_flags & GSS_C_DELEG_POLICY_FLAG)
+	&& ctx->kcred->flags.b.ok_as_delegate)
+	flagmask |=3D GSS_C_DELEG_FLAG | GSS_C_DELEG_POLICY_FLAG;
+    /* if there still is a GSS_C_DELEG_FLAG, use that */
+    if (req_flags & GSS_C_DELEG_FLAG)
+	flagmask |=3D GSS_C_DELEG_FLAG;
=20
=20
-    /*
-     * This is hideous glue for (NFS) clients that wants to limit the
-     * available enctypes to what it can support (encryption in
-     * kernel). If there is no enctypes selected for this credential,
-     * reset it to the default set of enctypes.
-     */
-    {
-	krb5_enctype *enctypes =3D NULL;
-
-	if (initiator_cred_handle && initiator_cred_handle->enctypes)
-	    enctypes =3D initiator_cred_handle->enctypes;
-	krb5_set_default_in_tkt_etypes(context, enctypes);
-    }
-
-    ret =3D gsskrb5_get_creds(minor_status,
-			    context,
-			    ccache,
-			    ctx,
-			    ctx->target,
-			    time_req,
-			    time_rec,
-			    &cred);
-    if (ret)
-	goto failure;
-
-    ctx->lifetime =3D cred->times.endtime;
-
-    ret =3D _gsskrb5_lifetime_left(minor_status,
-				 context,
-				 ctx->lifetime,
-				 &lifetime_rec);
-    if (ret) {
-	goto failure;
-    }
-
-    if (lifetime_rec =3D=3D 0) {
-	*minor_status =3D 0;
-	ret =3D GSS_S_CONTEXT_EXPIRED;
-	goto failure;
-    }
-
-    krb5_auth_con_setkey(context,=20
-			 ctx->auth_context,=20
-			 &cred->session);
-
-    kret =3D krb5_auth_con_generatelocalsubkey(context,=20
-					     ctx->auth_context,
-					     &cred->session);
-    if(kret) {
-	*minor_status =3D kret;
-	ret =3D GSS_S_FAILURE;
-	goto failure;
-    }
-   =20
-    /*=20
-     * If the credential doesn't have ok-as-delegate, check what local
-     * policy say about ok-as-delegate, default is FALSE that makes
-     * code ignore the KDC setting and follow what the application
-     * requested. If it is TRUE, strip of the GSS_C_DELEG_FLAG if the
-     * KDC doesn't set ok-as-delegate.
-     */
-    if (!cred->flags.b.ok_as_delegate) {
-	krb5_boolean delegate;
-   =20
-	krb5_appdefault_boolean(context,
-				"gssapi", name->realm,
-				"ok-as-delegate", FALSE, &delegate);
-	if (delegate)
-	    req_flags &=3D ~GSS_C_DELEG_FLAG;
-    }
-
     flags =3D 0;
     ap_options =3D 0;
-    if (req_flags & GSS_C_DELEG_FLAG)
+    if (flagmask & GSS_C_DELEG_FLAG) {
 	do_delegation (context,
-		       ctx->auth_context,
-		       ccache, cred, name, &fwd_data, &flags);
-   =20
+		       ctx->deleg_auth_context,
+		       ctx->ccache, ctx->kcred, ctx->target,
+		       &fwd_data, flagmask, &flags);
+    }
+
     if (req_flags & GSS_C_MUTUAL_FLAG) {
 	flags |=3D GSS_C_MUTUAL_FLAG;
 	ap_options |=3D AP_OPTS_MUTUAL_REQUIRED;
     }
-   =20
+
     if (req_flags & GSS_C_REPLAY_FLAG)
 	flags |=3D GSS_C_REPLAY_FLAG;
     if (req_flags & GSS_C_SEQUENCE_FLAG)
 	flags |=3D GSS_C_SEQUENCE_FLAG;
+#if 0
     if (req_flags & GSS_C_ANON_FLAG)
 	;                               /* XXX */
+#endif
     if (req_flags & GSS_C_DCE_STYLE) {
 	/* GSS_C_DCE_STYLE implies GSS_C_MUTUAL_FLAG */
 	flags |=3D GSS_C_DCE_STYLE | GSS_C_MUTUAL_FLAG;
@@ -490,15 +597,23 @@
     if (req_flags & GSS_C_EXTENDED_ERROR_FLAG)
 	flags |=3D GSS_C_EXTENDED_ERROR_FLAG;
=20
-    flags |=3D GSS_C_CONF_FLAG;
-    flags |=3D GSS_C_INTEG_FLAG;
+    if (req_flags & GSS_C_CONF_FLAG) {
+	flags |=3D GSS_C_CONF_FLAG;
+    }
+    if (req_flags & GSS_C_INTEG_FLAG) {
+	flags |=3D GSS_C_INTEG_FLAG;
+    }
+    if (cred =3D=3D NULL || !(cred->cred_flags & GSS_CF_NO_CI_FLAGS)) {
+	flags |=3D GSS_C_CONF_FLAG;
+	flags |=3D GSS_C_INTEG_FLAG;
+    }
     flags |=3D GSS_C_TRANS_FLAG;
-   =20
+
     if (ret_flags)
 	*ret_flags =3D flags;
     ctx->flags =3D flags;
     ctx->more_flags |=3D LOCAL;
-   =20
+
     ret =3D _gsskrb5_create_8003_checksum (minor_status,
 					 input_chan_bindings,
 					 flags,
@@ -510,16 +625,32 @@
=20
     enctype =3D ctx->auth_context->keyblock->keytype;
=20
-    kret =3D krb5_build_authenticator (context,
+    ret =3D krb5_cc_get_config(context, ctx->ccache, ctx->target,
+			     "time-offset", &timedata);
+    if (ret =3D=3D 0) {
+	if (timedata.length =3D=3D 4) {
+	    const u_char *p =3D timedata.data;
+	    offset =3D (p[0] <<24) | (p[1] << 16) | (p[2] << 8) | (p[3] << 0);
+	}
+	krb5_data_free(&timedata);
+    }
+
+    if (offset) {
+	krb5_get_kdc_sec_offset (context, &oldoffset, NULL);
+	krb5_set_kdc_sec_offset (context, offset, -1);
+    }
+
+    kret =3D _krb5_build_authenticator(context,
 				     ctx->auth_context,
 				     enctype,
-				     cred,
+				     ctx->kcred,
 				     &cksum,
-				     NULL,
 				     &authenticator,
 				     KRB5_KU_AP_REQ_AUTH);
=20
     if (kret) {
+	if (offset)
+	    krb5_set_kdc_sec_offset (context, oldoffset, -1);
 	*minor_status =3D kret;
 	ret =3D GSS_S_FAILURE;
 	goto failure;
@@ -527,27 +658,31 @@
=20
     kret =3D krb5_build_ap_req (context,
 			      enctype,
-			      cred,
+			      ctx->kcred,
 			      ap_options,
 			      authenticator,
 			      &outbuf);
-
+    if (offset)
+	krb5_set_kdc_sec_offset (context, oldoffset, -1);
     if (kret) {
 	*minor_status =3D kret;
 	ret =3D GSS_S_FAILURE;
 	goto failure;
     }
=20
-    ret =3D _gsskrb5_encapsulate (minor_status, &outbuf, output_token,
-				   (u_char *)"\x01\x00", GSS_KRB5_MECHANISM);
-    if (ret)
-	goto failure;
+    if (flags & GSS_C_DCE_STYLE) {
+	output_token->value =3D outbuf.data;
+	output_token->length =3D outbuf.length;
+    } else {
+        ret =3D _gsskrb5_encapsulate (minor_status, &outbuf, output_token,
+				    (u_char *)(intptr_t)"\x01\x00",
+				    GSS_KRB5_MECHANISM);
+	krb5_data_free (&outbuf);
+	if (ret)
+	    goto failure;
+    }
=20
-    krb5_data_free (&outbuf);
-    krb5_free_creds(context, cred);
     free_Checksum(&cksum);
-    if (initiator_cred_handle =3D=3D NULL)
-	krb5_cc_close(context, ccache);
=20
     if (flags & GSS_C_MUTUAL_FLAG) {
 	ctx->state =3D INITIATOR_WAIT_FOR_MUTAL;
@@ -556,15 +691,52 @@
=20
     return gsskrb5_initiator_ready(minor_status, ctx, context);
 failure:
-    if(cred)
-	krb5_free_creds(context, cred);
-    if (ccache && initiator_cred_handle =3D=3D NULL)
-	krb5_cc_close(context, ccache);
+    if (ctx->ccache && (ctx->more_flags & CLOSE_CCACHE))
+	krb5_cc_close(context, ctx->ccache);
+    ctx->ccache =3D NULL;
=20
     return ret;
+}
=20
+static krb5_error_code
+handle_error_packet(krb5_context context,
+		    gsskrb5_ctx ctx,
+		    krb5_data indata)
+{
+    krb5_error_code kret;
+    KRB_ERROR error;
+
+    kret =3D krb5_rd_error(context, &indata, &error);
+    if (kret =3D=3D 0) {
+	kret =3D krb5_error_from_rd_error(context, &error, NULL);
+
+	/* save the time skrew for this host */
+	if (kret =3D=3D KRB5KRB_AP_ERR_SKEW) {
+	    krb5_data timedata;
+	    unsigned char p[4];
+	    int32_t t =3D error.stime - time(NULL);
+
+	    p[0] =3D (t >> 24) & 0xFF;
+	    p[1] =3D (t >> 16) & 0xFF;
+	    p[2] =3D (t >> 8)  & 0xFF;
+	    p[3] =3D (t >> 0)  & 0xFF;
+
+	    timedata.data =3D p;
+	    timedata.length =3D sizeof(p);
+
+	    krb5_cc_set_config(context, ctx->ccache, ctx->target,
+			       "time-offset", &timedata);
+
+	    if ((ctx->more_flags & RETRIED) =3D=3D 0)
+		 ctx->state =3D INITIATOR_RESTART;
+	    ctx->more_flags |=3D RETRIED;
+	}
+	free_KRB_ERROR (&error);
+    }
+    return kret;
 }
=20
+
 static OM_uint32
 repl_mutual
 (OM_uint32 * minor_status,
@@ -585,7 +757,6 @@
     krb5_error_code kret;
     krb5_data indata;
     krb5_ap_rep_enc_part *repl;
-    int is_cfx =3D 0;
=20
     output_token->length =3D 0;
     output_token->value =3D NULL;
@@ -593,46 +764,57 @@
     if (actual_mech_type)
 	*actual_mech_type =3D GSS_KRB5_MECHANISM;
=20
-    if (ctx->flags & GSS_C_DCE_STYLE) {
+    if (IS_DCE_STYLE(ctx)) {
 	/* There is no OID wrapping. */
 	indata.length	=3D input_token->length;
 	indata.data	=3D input_token->value;
+	kret =3D krb5_rd_rep(context,
+			   ctx->auth_context,
+			   &indata,
+			   &repl);
+	if (kret) {
+	    ret =3D _gsskrb5_decapsulate(minor_status,
+				       input_token,
+				       &indata,
+				       "\x03\x00",
+				       GSS_KRB5_MECHANISM);
+	    if (ret =3D=3D GSS_S_COMPLETE) {
+		*minor_status =3D handle_error_packet(context, ctx, indata);
+	    } else {
+		*minor_status =3D kret;
+	    }
+	    return GSS_S_FAILURE;
+	}
     } else {
 	ret =3D _gsskrb5_decapsulate (minor_status,
 				    input_token,
 				    &indata,
 				    "\x02\x00",
 				    GSS_KRB5_MECHANISM);
-	if (ret) {
-	    /* XXX - Handle AP_ERROR */
-	    return ret;
+	if (ret =3D=3D GSS_S_DEFECTIVE_TOKEN) {
+	    /* check if there is an error token sent instead */
+	    ret =3D _gsskrb5_decapsulate (minor_status,
+					input_token,
+					&indata,
+					"\x03\x00",
+					GSS_KRB5_MECHANISM);
+	    if (ret =3D=3D GSS_S_COMPLETE) {
+		*minor_status =3D handle_error_packet(context, ctx, indata);
+		return GSS_S_FAILURE;
+	    }
+	}
+	kret =3D krb5_rd_rep (context,
+			    ctx->auth_context,
+			    &indata,
+			    &repl);
+	if (kret) {
+	    *minor_status =3D kret;
+	    return GSS_S_FAILURE;
 	}
     }
=20
-    kret =3D krb5_rd_rep (context,
-			ctx->auth_context,
-			&indata,
-			&repl);
-    if (kret) {
-	*minor_status =3D kret;
-	return GSS_S_FAILURE;
-    }
     krb5_free_ap_rep_enc_part (context,
 			       repl);
-   =20
-    _gsskrb5i_is_cfx(ctx, &is_cfx);
-    if (is_cfx) {
-	krb5_keyblock *key =3D NULL;
-
-	kret =3D krb5_auth_con_getremotesubkey(context,
-					     ctx->auth_context,=20
-					     &key);
-	if (kret =3D=3D 0 && key !=3D NULL) {
-    	    ctx->more_flags |=3D ACCEPTOR_SUBKEY;
-	    krb5_free_keyblock (context, key);
-	}
-    }
-
=20
     *minor_status =3D 0;
     if (time_rec) {
@@ -647,30 +829,31 @@
 	*ret_flags =3D ctx->flags;
=20
     if (req_flags & GSS_C_DCE_STYLE) {
-	int32_t con_flags;
+	int32_t local_seq, remote_seq;
 	krb5_data outbuf;
=20
-	/* Do don't do sequence number for the mk-rep */
-	krb5_auth_con_removeflags(context,
-				  ctx->auth_context,
-				  KRB5_AUTH_CONTEXT_DO_SEQUENCE,
-				  &con_flags);
+	/*
+	 * So DCE_STYLE is strange. The client echos the seq number
+	 * that the server used in the server's mk_rep in its own
+	 * mk_rep(). After when done, it resets to it's own seq number
+	 * for the gss_wrap calls.
+	 */
=20
-	kret =3D krb5_mk_rep(context,
-			   ctx->auth_context,
-			   &outbuf);
+	krb5_auth_con_getremoteseqnumber(context, ctx->auth_context, &remote_seq);
+	krb5_auth_con_getlocalseqnumber(context, ctx->auth_context, &local_seq);
+	krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, remote_seq);
+
+	kret =3D krb5_mk_rep(context, ctx->auth_context, &outbuf);
 	if (kret) {
 	    *minor_status =3D kret;
 	    return GSS_S_FAILURE;
 	}
-=09
+
+	/* reset local seq number */
+	krb5_auth_con_setlocalseqnumber(context, ctx->auth_context, local_seq);
+
 	output_token->length =3D outbuf.length;
 	output_token->value  =3D outbuf.data;
-
-	krb5_auth_con_removeflags(context,
-				  ctx->auth_context,
-				  KRB5_AUTH_CONTEXT_DO_SEQUENCE,
-				  NULL);
     }
=20
     return gsskrb5_initiator_ready(minor_status, ctx, context);
@@ -680,9 +863,9 @@
  * gss_init_sec_context
  */
=20
-OM_uint32 _gsskrb5_init_sec_context
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_init_sec_context
 (OM_uint32 * minor_status,
- const gss_cred_id_t initiator_cred_handle,
+ const gss_cred_id_t cred_handle,
  gss_ctx_id_t * context_handle,
  const gss_name_t target_name,
  const gss_OID mech_type,
@@ -697,8 +880,7 @@
     )
 {
     krb5_context context;
-    gsskrb5_cred cred =3D (gsskrb5_cred)initiator_cred_handle;
-    krb5_const_principal name =3D (krb5_const_principal)target_name;
+    gsskrb5_cred cred =3D (gsskrb5_cred)cred_handle;
     gsskrb5_ctx ctx;
     OM_uint32 ret;
=20
@@ -724,25 +906,25 @@
 	return GSS_S_BAD_NAME;
     }
=20
-    if (mech_type !=3D GSS_C_NO_OID &&=20
+    if (mech_type !=3D GSS_C_NO_OID &&
 	!gss_oid_equal(mech_type, GSS_KRB5_MECHANISM))
 	return GSS_S_BAD_MECH;
=20
     if (input_token =3D=3D GSS_C_NO_BUFFER || input_token->length =3D=3D 0=
) {
-	OM_uint32 ret;
+	OM_uint32 ret1;
=20
 	if (*context_handle !=3D GSS_C_NO_CONTEXT) {
 	    *minor_status =3D 0;
 	    return GSS_S_FAILURE | GSS_S_CALL_BAD_STRUCTURE;
 	}
-   =20
-	ret =3D _gsskrb5_create_ctx(minor_status,
+
+	ret1 =3D _gsskrb5_create_ctx(minor_status,
 				  context_handle,
 				  context,
 				  input_chan_bindings,
 				  INITIATOR_START);
-	if (ret)
-	    return ret;
+	if (ret1)
+	    return ret1;
     }
=20
     if (*context_handle =3D=3D GSS_C_NO_CONTEXT) {
@@ -754,22 +936,37 @@
=20
     HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
=20
+ again:
     switch (ctx->state) {
     case INITIATOR_START:
 	ret =3D init_auth(minor_status,
 			cred,
 			ctx,
 			context,
-			name,
+			target_name,
 			mech_type,
 			req_flags,
 			time_req,
-			input_chan_bindings,
 			input_token,
 			actual_mech_type,
 			output_token,
 			ret_flags,
 			time_rec);
+	if (ret !=3D GSS_S_COMPLETE)
+	    break;
+	/* FALL THOUGH */
+    case INITIATOR_RESTART:
+	ret =3D init_auth_restart(minor_status,
+				cred,
+				ctx,
+				context,
+				req_flags,
+				input_chan_bindings,
+				input_token,
+				actual_mech_type,
+				output_token,
+				ret_flags,
+				time_rec);
 	break;
     case INITIATOR_WAIT_FOR_MUTAL:
 	ret =3D repl_mutual(minor_status,
@@ -784,17 +981,24 @@
 			  output_token,
 			  ret_flags,
 			  time_rec);
+	if (ctx->state =3D=3D INITIATOR_RESTART)
+	    goto again;
 	break;
     case INITIATOR_READY:
-	/*=20
+	/*
 	 * If we get there, the caller have called
 	 * gss_init_sec_context() one time too many.
 	 */
-	*minor_status =3D 0;
+	_gsskrb5_set_status(EINVAL, "init_sec_context "
+			    "called one time too many");
+	*minor_status =3D EINVAL;
 	ret =3D GSS_S_BAD_STATUS;
 	break;
     default:
-	*minor_status =3D 0;
+	_gsskrb5_set_status(EINVAL, "init_sec_context "
+			    "invalid state %d for client",
+			    (int)ctx->state);
+	*minor_status =3D EINVAL;
 	ret =3D GSS_S_BAD_STATUS;
 	break;
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
quire_context.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/inquire_context.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/inquire_context.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: inquire_context.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32 _gsskrb5_inquire_context (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_context (
     OM_uint32 * minor_status,
 	const gss_ctx_id_t context_handle,
 	gss_name_t * src_name,
@@ -76,7 +74,7 @@
     }
=20
     if (lifetime_rec) {
-	ret =3D _gsskrb5_lifetime_left(minor_status,=20
+	ret =3D _gsskrb5_lifetime_left(minor_status,
 				     context,
 				     ctx->lifetime,
 				     lifetime_rec);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
quire_cred.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/inquire_cred.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/inquire_cred.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: inquire_cred.c 20688 2007-05-17 18:44:31Z lha $");
-
-OM_uint32 _gsskrb5_inquire_cred
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred
 (OM_uint32 * minor_status,
  const gss_cred_id_t cred_handle,
  gss_name_t * output_name,
@@ -60,7 +58,7 @@
     GSSAPI_KRB5_INIT (&context);
=20
     if (cred_handle =3D=3D GSS_C_NO_CREDENTIAL) {
-	ret =3D _gsskrb5_acquire_cred(minor_status,=20
+	ret =3D _gsskrb5_acquire_cred(minor_status,
 				    GSS_C_NO_NAME,
 				    GSS_C_INDEFINITE,
 				    GSS_C_NO_OID_SET,
@@ -71,7 +69,7 @@
 	if (ret =3D=3D GSS_S_COMPLETE)
 	    acred =3D (gsskrb5_cred)aqcred_accept;
=20
-	ret =3D _gsskrb5_acquire_cred(minor_status,=20
+	ret =3D _gsskrb5_acquire_cred(minor_status,
 				    GSS_C_NO_NAME,
 				    GSS_C_INDEFINITE,
 				    GSS_C_NO_OID_SET,
@@ -97,19 +95,19 @@
     if (output_name !=3D NULL) {
 	if (icred && icred->principal !=3D NULL) {
 	    gss_name_t name;
-	   =20
+
 	    if (acred && acred->principal)
 		name =3D (gss_name_t)acred->principal;
 	    else
 		name =3D (gss_name_t)icred->principal;
-	=09
+
             ret =3D _gsskrb5_duplicate_name(minor_status, name, output_nam=
e);
             if (ret)
 		goto out;
 	} else if (acred && acred->usage =3D=3D GSS_C_ACCEPT) {
 	    krb5_principal princ;
 	    *minor_status =3D krb5_sname_to_principal(context, NULL,
-						    NULL, KRB5_NT_SRV_HST,=20
+						    NULL, KRB5_NT_SRV_HST,
 						    &princ);
 	    if (*minor_status) {
 		ret =3D GSS_S_FAILURE;
@@ -133,7 +131,7 @@
 	if (acred) alife =3D acred->lifetime;
 	if (icred) ilife =3D icred->lifetime;
=20
-	ret =3D _gsskrb5_lifetime_left(minor_status,=20
+	ret =3D _gsskrb5_lifetime_left(minor_status,
 				     context,
 				     min(alife,ilife),
 				     lifetime);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
quire_cred_by_mech.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/inquire_cred_by_mech.c	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/inquire_cred_by_mech.c	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2003, 2006, 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003, 2006, 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: inquire_cred_by_mech.c 20634 2007-05-09 15:33:01Z lha $");
-
-OM_uint32 _gsskrb5_inquire_cred_by_mech (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_mech (
     OM_uint32 * minor_status,
 	const gss_cred_id_t cred_handle,
 	const gss_OID mech_type,
@@ -49,7 +47,7 @@
     OM_uint32 maj_stat;
     OM_uint32 lifetime;
=20
-    maj_stat =3D=20
+    maj_stat =3D
 	_gsskrb5_inquire_cred (minor_status, cred_handle,
 			       name, &lifetime, &usage, NULL);
     if (maj_stat)
@@ -61,7 +59,7 @@
 	else
 	    *initiator_lifetime =3D 0;
     }
-  =20
+
     if (acceptor_lifetime) {
 	if (usage =3D=3D GSS_C_ACCEPT || usage =3D=3D GSS_C_BOTH)
 	    *acceptor_lifetime =3D lifetime;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
quire_cred_by_oid.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/inquire_cred_by_oid.c	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/inquire_cred_by_oid.c	Tue Apr 17 =
11:51:51 2012 +0300
@@ -30,11 +30,9 @@
  * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: inquire_cred_by_oid.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32 _gsskrb5_inquire_cred_by_oid
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_cred_by_oid
 	   (OM_uint32 * minor_status,
 	    const gss_cred_id_t cred_handle,
 	    const gss_OID desired_object,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
quire_mechs_for_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/inquire_mechs_for_name.c	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/inquire_mechs_for_name.c	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: inquire_mechs_for_name.c 20688 2007-05-17 18:44:31Z lha $");
-
-OM_uint32 _gsskrb5_inquire_mechs_for_name (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_mechs_for_name (
             OM_uint32 * minor_status,
             const gss_name_t input_name,
             gss_OID_set * mech_types
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
quire_names_for_mech.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/inquire_names_for_mech.c	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/inquire_names_for_mech.c	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,50 +1,47 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: inquire_names_for_mech.c 20688 2007-05-17 18:44:31Z lha $");
-
-
-static gss_OID *name_list[] =3D {
-    &GSS_C_NT_HOSTBASED_SERVICE,
-    &GSS_C_NT_USER_NAME,
-    &GSS_KRB5_NT_PRINCIPAL_NAME,
-    &GSS_C_NT_EXPORT_NAME,
+static gss_OID name_list[] =3D {
+    GSS_C_NT_HOSTBASED_SERVICE,
+    GSS_C_NT_USER_NAME,
+    GSS_KRB5_NT_PRINCIPAL_NAME,
+    GSS_C_NT_EXPORT_NAME,
     NULL
 };
=20
-OM_uint32 _gsskrb5_inquire_names_for_mech (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_names_for_mech (
             OM_uint32 * minor_status,
             const gss_OID mechanism,
             gss_OID_set * name_types
@@ -64,10 +61,10 @@
     ret =3D gss_create_empty_oid_set(minor_status, name_types);
     if (ret !=3D GSS_S_COMPLETE)
 	return ret;
-   =20
+
     for (i =3D 0; name_list[i] !=3D NULL; i++) {
-	ret =3D gss_add_oid_set_member(minor_status,=20
-				     *(name_list[i]),
+	ret =3D gss_add_oid_set_member(minor_status,
+				     name_list[i],
 				     name_types);
 	if (ret !=3D GSS_S_COMPLETE)
 	    break;
@@ -75,6 +72,6 @@
=20
     if (ret !=3D GSS_S_COMPLETE)
 	gss_release_oid_set(NULL, name_types);
-=09
+
     return GSS_S_COMPLETE;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/in=
quire_sec_context_by_oid.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/inquire_sec_context_by_oid.c	Tue =
Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/inquire_sec_context_by_oid.c	Tue =
Apr 17 11:51:51 2012 +0300
@@ -30,9 +30,7 @@
  * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: inquire_sec_context_by_oid.c 19031 2006-11-13 18:02:57Z lha $"=
);
+#include "gsskrb5_locl.h"
=20
 static int
 oid_prefix_equal(gss_OID oid_enc, gss_OID prefix_enc, unsigned *suffix)
@@ -40,7 +38,7 @@
     int ret;
     heim_oid oid;
     heim_oid prefix;
-=20
+
     *suffix =3D 0;
=20
     ret =3D der_get_oid(oid_enc->elements, oid_enc->length,
@@ -84,7 +82,7 @@
=20
     if (context_handle->ticket =3D=3D NULL) {
 	HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
-	_gsskrb5_set_status("No ticket from which to obtain flags");
+	_gsskrb5_set_status(EINVAL, "No ticket from which to obtain flags");
 	*minor_status =3D EINVAL;
 	return GSS_S_BAD_MECH;
     }
@@ -137,15 +135,15 @@
 	ret =3D _gsskrb5i_get_token_key(context_handle, context, &key);
 	break;
     default:
-	_gsskrb5_set_status("%d is not a valid subkey type", keytype);
+	_gsskrb5_set_status(EINVAL, "%d is not a valid subkey type", keytype);
 	ret =3D EINVAL;
 	break;
    }
     HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
-    if (ret)=20
+    if (ret)
 	goto out;
     if (key =3D=3D NULL) {
-	_gsskrb5_set_status("have no subkey of type %d", keytype);
+	_gsskrb5_set_status(EINVAL, "have no subkey of type %d", keytype);
 	ret =3D EINVAL;
 	goto out;
     }
@@ -161,10 +159,10 @@
=20
     {
 	gss_buffer_desc value;
-=09
+
 	value.length =3D data.length;
 	value.value =3D data.data;
-=09
+
 	maj_stat =3D gss_add_buffer_set_member(minor_status,
 					     &value,
 					     data_set);
@@ -181,6 +179,46 @@
     return maj_stat;
 }
=20
+static OM_uint32 inquire_sec_context_get_sspi_session_key
+            (OM_uint32 *minor_status,
+             const gsskrb5_ctx context_handle,
+             krb5_context context,
+             gss_buffer_set_t *data_set)
+{
+    krb5_keyblock *key;
+    OM_uint32 maj_stat =3D GSS_S_COMPLETE;
+    krb5_error_code ret;
+    gss_buffer_desc value;
+
+    HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
+    ret =3D _gsskrb5i_get_token_key(context_handle, context, &key);
+    HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+
+    if (ret)
+        goto out;
+    if (key =3D=3D NULL) {
+        ret =3D EINVAL;
+        goto out;
+    }
+
+    value.length =3D key->keyvalue.length;
+    value.value =3D key->keyvalue.data;
+
+    maj_stat =3D gss_add_buffer_set_member(minor_status,
+                                         &value,
+                                         data_set);
+    krb5_free_keyblock(context, key);
+
+    /* MIT also returns the enctype encoded as an OID in data_set[1] */
+
+out:
+    if (ret) {
+        *minor_status =3D ret;
+        maj_stat =3D GSS_S_FAILURE;
+    }
+    return maj_stat;
+}
+
 static OM_uint32 inquire_sec_context_authz_data
            (OM_uint32 *minor_status,
             const gsskrb5_ctx context_handle,
@@ -199,7 +237,7 @@
     if (context_handle->ticket =3D=3D NULL) {
 	HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
 	*minor_status =3D EINVAL;
-	_gsskrb5_set_status("No ticket to obtain authz data from");
+	_gsskrb5_set_status(EINVAL, "No ticket to obtain authz data from");
 	return GSS_S_NO_CONTEXT;
     }
=20
@@ -242,7 +280,7 @@
      * mechanism.
      */
     HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
-    _gsskrb5i_is_cfx(context_handle, &is_updated);
+    is_updated =3D (context_handle->more_flags & IS_CFX);
     if (is_updated =3D=3D 0) {
 	krb5_keyblock *acceptor_subkey;
=20
@@ -277,12 +315,12 @@
     int32_t number;
     int is_cfx;
     krb5_data data;
-   =20
+
     *minor_status =3D 0;
=20
     HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
=20
-    _gsskrb5i_is_cfx(context_handle, &is_cfx);
+    is_cfx =3D (context_handle->more_flags & IS_CFX);
=20
     sp =3D krb5_storage_emem();
     if (sp =3D=3D NULL) {
@@ -301,12 +339,16 @@
 				     context_handle->auth_context,
 				     &number);
     ret =3D krb5_store_uint32(sp, (uint32_t)0); /* store top half as zero =
*/
+    if (ret) goto out;
     ret =3D krb5_store_uint32(sp, (uint32_t)number);
-    krb5_auth_getremoteseqnumber (context,
-				  context_handle->auth_context,
-				  &number);
+    if (ret) goto out;
+    krb5_auth_con_getremoteseqnumber (context,
+				      context_handle->auth_context,
+				      &number);
     ret =3D krb5_store_uint32(sp, (uint32_t)0); /* store top half as zero =
*/
+    if (ret) goto out;
     ret =3D krb5_store_uint32(sp, (uint32_t)number);
+    if (ret) goto out;
     ret =3D krb5_store_int32(sp, (is_cfx) ? 1 : 0);
     if (ret) goto out;
=20
@@ -390,7 +432,7 @@
=20
 static OM_uint32
 get_authtime(OM_uint32 *minor_status,
-	     gsskrb5_ctx ctx,=20
+	     gsskrb5_ctx ctx,
 	     gss_buffer_set_t *data_set)
=20
 {
@@ -401,13 +443,13 @@
     HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
     if (ctx->ticket =3D=3D NULL) {
 	HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
-	_gsskrb5_set_status("No ticket to obtain auth time from");
+	_gsskrb5_set_status(EINVAL, "No ticket to obtain auth time from");
 	*minor_status =3D EINVAL;
 	return GSS_S_FAILURE;
     }
-   =20
+
     authtime =3D ctx->ticket->ticket.authtime;
-   =20
+
     HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
=20
     _gsskrb5_encode_om_uint32(authtime, buf);
@@ -420,17 +462,17 @@
 }
=20
=20
-static OM_uint32=20
+static OM_uint32
 get_service_keyblock
         (OM_uint32 *minor_status,
-	 gsskrb5_ctx ctx,=20
+	 gsskrb5_ctx ctx,
 	 gss_buffer_set_t *data_set)
 {
     krb5_storage *sp =3D NULL;
     krb5_data data;
     OM_uint32 maj_stat =3D GSS_S_COMPLETE;
     krb5_error_code ret =3D EINVAL;
-   =20
+
     sp =3D krb5_storage_emem();
     if (sp =3D=3D NULL) {
 	_gsskrb5_clear_status();
@@ -441,9 +483,10 @@
     HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
     if (ctx->service_keyblock =3D=3D NULL) {
 	HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
-	_gsskrb5_set_status("No service keyblock on gssapi context");
+	krb5_storage_free(sp);
+	_gsskrb5_set_status(EINVAL, "No service keyblock on gssapi context");
 	*minor_status =3D EINVAL;
-	return GSS_S_FAILURE;=20
+	return GSS_S_FAILURE;
     }
=20
     krb5_data_zero(&data);
@@ -461,10 +504,10 @@
=20
     {
 	gss_buffer_desc value;
-=09
+
 	value.length =3D data.length;
 	value.value =3D data.data;
-=09
+
 	maj_stat =3D gss_add_buffer_set_member(minor_status,
 					     &value,
 					     data_set);
@@ -484,7 +527,7 @@
  *
  */
=20
-OM_uint32 _gsskrb5_inquire_sec_context_by_oid
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_inquire_sec_context_by_oid
            (OM_uint32 *minor_status,
             const gss_ctx_id_t context_handle,
             const gss_OID desired_object,
@@ -527,6 +570,11 @@
 					      context,
 					      ACCEPTOR_KEY,
 					      data_set);
+    } else if (gss_oid_equal(desired_object, GSS_C_INQ_SSPI_SESSION_KEY)) {
+        return inquire_sec_context_get_sspi_session_key(minor_status,
+                                                        ctx,
+                                                        context,
+                                                        data_set);
     } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_AUTHTIME_X)) {
 	return get_authtime(minor_status, ctx, data_set);
     } else if (oid_prefix_equal(desired_object,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/pr=
f.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/prf.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/prf.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: prf.c 21129 2007-06-18 20:28:44Z lha $");
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_pseudo_random(OM_uint32 *minor_status,
 		       gss_ctx_id_t context_handle,
 		       int prf_key,
@@ -49,18 +47,21 @@
     krb5_crypto crypto;
     krb5_data input, output;
     uint32_t num;
+    OM_uint32 junk;
     unsigned char *p;
     krb5_keyblock *key =3D NULL;
+    size_t dol;
=20
     if (ctx =3D=3D NULL) {
 	*minor_status =3D 0;
 	return GSS_S_NO_CONTEXT;
     }
=20
-    if (desired_output_len <=3D 0) {
+    if (desired_output_len <=3D 0 || prf_in->length + 4 < prf_in->length) {
 	*minor_status =3D 0;
 	return GSS_S_FAILURE;
     }
+    dol =3D desired_output_len;
=20
     GSSAPI_KRB5_INIT (&context);
=20
@@ -72,14 +73,14 @@
 	_gsskrb5i_get_initiator_subkey(ctx, context, &key);
 	break;
     default:
-	_gsskrb5_set_status("unknown kerberos prf_key");
-	*minor_status =3D 0;
+	_gsskrb5_set_status(EINVAL, "unknown kerberos prf_key");
+	*minor_status =3D EINVAL;
 	return GSS_S_FAILURE;
     }
=20
     if (key =3D=3D NULL) {
-	_gsskrb5_set_status("no prf_key found");
-	*minor_status =3D 0;
+	_gsskrb5_set_status(EINVAL, "no prf_key found");
+	*minor_status =3D EINVAL;
 	return GSS_S_FAILURE;
     }
=20
@@ -90,37 +91,38 @@
 	return GSS_S_FAILURE;
     }
=20
-    prf_out->value =3D malloc(desired_output_len);
+    prf_out->value =3D malloc(dol);
     if (prf_out->value =3D=3D NULL) {
-	_gsskrb5_set_status("Out of memory");
+	_gsskrb5_set_status(GSS_KRB5_S_KG_INPUT_TOO_LONG, "Out of memory");
 	*minor_status =3D GSS_KRB5_S_KG_INPUT_TOO_LONG;
 	krb5_crypto_destroy(context, crypto);
 	return GSS_S_FAILURE;
     }
-    prf_out->length =3D desired_output_len;
+    prf_out->length =3D dol;
=20
     HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
=20
     input.length =3D prf_in->length + 4;
     input.data =3D malloc(prf_in->length + 4);
     if (input.data =3D=3D NULL) {
-	OM_uint32 junk;
-	_gsskrb5_set_status("Out of memory");
+	_gsskrb5_set_status(GSS_KRB5_S_KG_INPUT_TOO_LONG, "Out of memory");
 	*minor_status =3D GSS_KRB5_S_KG_INPUT_TOO_LONG;
 	gss_release_buffer(&junk, prf_out);
 	krb5_crypto_destroy(context, crypto);
 	HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	return GSS_S_FAILURE;
     }
-    memcpy(((unsigned char *)input.data) + 4, prf_in->value, prf_in->lengt=
h);
+    memcpy(((uint8_t *)input.data) + 4, prf_in->value, prf_in->length);
=20
     num =3D 0;
     p =3D prf_out->value;
-    while(desired_output_len > 0) {
+    while(dol > 0) {
+	size_t tsize;
+
 	_gsskrb5_encode_om_uint32(num, input.data);
+
 	ret =3D krb5_crypto_prf(context, crypto, &input, &output);
 	if (ret) {
-	    OM_uint32 junk;
 	    *minor_status =3D ret;
 	    free(input.data);
 	    gss_release_buffer(&junk, prf_out);
@@ -128,12 +130,15 @@
 	    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	    return GSS_S_FAILURE;
 	}
-	memcpy(p, output.data, min(desired_output_len, output.length));
+
+	tsize =3D min(dol, output.length);
+	memcpy(p, output.data, tsize);
 	p +=3D output.length;
-	desired_output_len -=3D output.length;
+	dol -=3D tsize;
 	krb5_data_free(&output);
 	num++;
     }
+    free(input.data);
=20
     krb5_crypto_destroy(context, crypto);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/pr=
ocess_context_token.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/process_context_token.c	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/process_context_token.c	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: process_context_token.c 19031 2006-11-13 18:02:57Z lha $");
-
-OM_uint32 _gsskrb5_process_context_token (
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_process_context_token (
 	OM_uint32          *minor_status,
 	const gss_ctx_id_t context_handle,
 	const gss_buffer_t token_buffer
@@ -44,20 +42,18 @@
     krb5_context context;
     OM_uint32 ret =3D GSS_S_FAILURE;
     gss_buffer_desc empty_buffer;
-    gss_qop_t qop_state;
=20
     empty_buffer.length =3D 0;
     empty_buffer.value =3D NULL;
=20
     GSSAPI_KRB5_INIT (&context);
=20
-    qop_state =3D GSS_C_QOP_DEFAULT;
-
-    ret =3D _gsskrb5_verify_mic_internal(minor_status,=20
+    ret =3D _gsskrb5_verify_mic_internal(minor_status,
 				       (gsskrb5_ctx)context_handle,
 				       context,
 				       token_buffer, &empty_buffer,
-				       GSS_C_QOP_DEFAULT, "\x01\x02");
+				       GSS_C_QOP_DEFAULT,
+				       "\x01\x02");
=20
     if (ret =3D=3D GSS_S_COMPLETE)
 	ret =3D _gsskrb5_delete_sec_context(minor_status,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/re=
lease_buffer.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/release_buffer.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/release_buffer.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2000, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: release_buffer.c 18334 2006-10-07 22:16:04Z lha $");
+#include "gsskrb5_locl.h"
=20
 OM_uint32 _gsskrb5_release_buffer
            (OM_uint32 * minor_status,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/re=
lease_cred.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/release_cred.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/release_cred.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: release_cred.c 20753 2007-05-31 22:50:06Z lha $");
-
-OM_uint32 _gsskrb5_release_cred
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_cred
            (OM_uint32 * minor_status,
             gss_cred_id_t * cred_handle
            )
@@ -46,7 +44,7 @@
=20
     *minor_status =3D 0;
=20
-    if (*cred_handle =3D=3D NULL)=20
+    if (*cred_handle =3D=3D NULL)
         return GSS_S_COMPLETE;
=20
     cred =3D (gsskrb5_cred)*cred_handle;
@@ -61,11 +59,9 @@
     if (cred->keytab !=3D NULL)
 	krb5_kt_close(context, cred->keytab);
     if (cred->ccache !=3D NULL) {
-	const krb5_cc_ops *ops;
-	ops =3D krb5_cc_get_ops(context, cred->ccache);
 	if (cred->cred_flags & GSS_CF_DESTROY_CRED_ON_RELEASE)
 	    krb5_cc_destroy(context, cred->ccache);
-	else=20
+	else
 	    krb5_cc_close(context, cred->ccache);
     }
     gss_release_oid_set(&junk, &cred->mechanisms);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/re=
lease_name.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/release_name.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/release_name.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: release_name.c 21128 2007-06-18 20:26:50Z lha $");
-
-OM_uint32 _gsskrb5_release_name
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_release_name
            (OM_uint32 * minor_status,
             gss_name_t * input_name
            )
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/se=
quence.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/sequence.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/sequence.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2003 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: sequence.c 18334 2006-10-07 22:16:04Z lha $");
+#include "gsskrb5_locl.h"
=20
 #define DEFAULT_JITTER_WINDOW 20
=20
@@ -57,19 +55,19 @@
 		OM_uint32 jitter_window)
 {
     size_t len;
-   =20
+
     len =3D jitter_window * sizeof((*o)->elem[0]);
     len +=3D sizeof(**o);
     len -=3D sizeof((*o)->elem[0]);
-   =20
+
     *o =3D calloc(1, len);
     if (*o =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
-    }=09
-   =20
+    }
+
     *minor_status =3D 0;
-    return GSS_S_COMPLETE;   =20
+    return GSS_S_COMPLETE;
 }
=20
 /*
@@ -78,9 +76,9 @@
=20
 OM_uint32
 _gssapi_msg_order_create(OM_uint32 *minor_status,
-			 struct gss_msg_order **o,=20
-			 OM_uint32 flags,=20
-			 OM_uint32 seq_num,=20
+			 struct gss_msg_order **o,
+			 OM_uint32 flags,
+			 OM_uint32 seq_num,
 			 OM_uint32 jitter_window,
 			 int use_64)
 {
@@ -118,7 +116,7 @@
 }
=20
 static void
-elem_insert(struct gss_msg_order *o,=20
+elem_insert(struct gss_msg_order *o,
 	    unsigned int after_slot,
 	    OM_uint32 seq_num)
 {
@@ -143,7 +141,7 @@
 _gssapi_msg_order_check(struct gss_msg_order *o, OM_uint32 seq_num)
 {
     OM_uint32 r;
-    int i;
+    size_t i;
=20
     if (o =3D=3D NULL)
 	return GSS_S_COMPLETE;
@@ -159,11 +157,11 @@
=20
     r =3D (o->flags & (GSS_C_REPLAY_FLAG|GSS_C_SEQUENCE_FLAG))=3D=3DGSS_C_=
REPLAY_FLAG;
=20
-    /* sequence number larger then largest sequence number=20
+    /* sequence number larger then largest sequence number
      * or smaller then the first sequence number */
     if (seq_num > o->elem[0]
 	|| seq_num < o->first_seq
-	|| o->length =3D=3D 0)=20
+	|| o->length =3D=3D 0)
     {
 	elem_insert(o, 0, seq_num);
 	if (r) {
@@ -217,7 +215,7 @@
 {
     krb5_error_code kret;
     OM_uint32 i;
-   =20
+
     kret =3D krb5_store_int32(sp, o->flags);
     if (kret)
         return kret;
@@ -233,51 +231,51 @@
     kret =3D krb5_store_int32(sp, o->first_seq);
     if (kret)
         return kret;
-   =20
+
     for (i =3D 0; i < o->jitter_window; i++) {
         kret =3D krb5_store_int32(sp, o->elem[i]);
 	if (kret)
 	    return kret;
     }
-   =20
+
     return 0;
 }
=20
 OM_uint32
 _gssapi_msg_order_import(OM_uint32 *minor_status,
-			 krb5_storage *sp,=20
+			 krb5_storage *sp,
 			 struct gss_msg_order **o)
 {
     OM_uint32 ret;
     krb5_error_code kret;
     int32_t i, flags, start, length, jitter_window, first_seq;
-   =20
+
     kret =3D krb5_ret_int32(sp, &flags);
     if (kret)
 	goto failed;
-    ret =3D krb5_ret_int32(sp, &start);
+    kret =3D krb5_ret_int32(sp, &start);
     if (kret)
 	goto failed;
-    ret =3D krb5_ret_int32(sp, &length);
+    kret =3D krb5_ret_int32(sp, &length);
     if (kret)
 	goto failed;
-    ret =3D krb5_ret_int32(sp, &jitter_window);
+    kret =3D krb5_ret_int32(sp, &jitter_window);
     if (kret)
 	goto failed;
-    ret =3D krb5_ret_int32(sp, &first_seq);
+    kret =3D krb5_ret_int32(sp, &first_seq);
     if (kret)
 	goto failed;
-   =20
+
     ret =3D msg_order_alloc(minor_status, o, jitter_window);
     if (ret !=3D GSS_S_COMPLETE)
         return ret;
-   =20
+
     (*o)->flags =3D flags;
     (*o)->start =3D start;
     (*o)->length =3D length;
     (*o)->jitter_window =3D jitter_window;
     (*o)->first_seq =3D first_seq;
-   =20
+
     for( i =3D 0; i < jitter_window; i++ ) {
         kret =3D krb5_ret_int32(sp, (int32_t*)&((*o)->elem[i]));
 	if (kret)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/se=
t_cred_option.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/set_cred_option.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/set_cred_option.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -30,14 +30,7 @@
  * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: set_cred_option.c 20325 2007-04-12 16:49:17Z lha $");
-
-static gss_OID_desc gss_krb5_import_cred_x_oid_desc =3D
-{9, (void *)"\x2b\x06\x01\x04\x01\xa9\x4a\x13\x04"}; /* XXX */
-
-gss_OID GSS_KRB5_IMPORT_CRED_X =3D &gss_krb5_import_cred_x_oid_desc;
+#include "gsskrb5_locl.h"
=20
 static OM_uint32
 import_cred(OM_uint32 *minor_status,
@@ -112,8 +105,8 @@
     free(str);
     str =3D NULL;
=20
-    major_stat =3D _gsskrb5_import_cred(minor_status, id, keytab_principal,
-				      keytab, cred_handle);
+    major_stat =3D _gsskrb5_krb5_import_cred(minor_status, id, keytab_prin=
cipal,
+					   keytab, cred_handle);
 out:
     if (id)
 	krb5_cc_close(context, id);
@@ -201,8 +194,29 @@
     return major_stat;
 }
=20
+static OM_uint32
+no_ci_flags(OM_uint32 *minor_status,
+	    krb5_context context,
+	    gss_cred_id_t *cred_handle,
+	    const gss_buffer_t value)
+{
+    gsskrb5_cred cred;
=20
-OM_uint32
+    if (cred_handle =3D=3D NULL || *cred_handle =3D=3D GSS_C_NO_CREDENTIAL=
) {
+	*minor_status =3D 0;
+	return GSS_S_FAILURE;
+    }
+
+    cred =3D (gsskrb5_cred)*cred_handle;
+    cred->cred_flags |=3D GSS_CF_NO_CI_FLAGS;
+
+    *minor_status =3D 0;
+    return GSS_S_COMPLETE;
+
+}
+
+
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_set_cred_option
            (OM_uint32 *minor_status,
             gss_cred_id_t *cred_handle,
@@ -224,6 +238,11 @@
     if (gss_oid_equal(desired_object, GSS_KRB5_SET_ALLOWABLE_ENCTYPES_X))
 	return allowed_enctypes(minor_status, context, cred_handle, value);
=20
+    if (gss_oid_equal(desired_object, GSS_KRB5_CRED_NO_CI_FLAGS_X)) {
+	return no_ci_flags(minor_status, context, cred_handle, value);
+    }
+
+
     *minor_status =3D EINVAL;
     return GSS_S_FAILURE;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/se=
t_sec_context_option.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/set_sec_context_option.c	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/set_sec_context_option.c	Tue Apr =
17 11:51:51 2012 +0300
@@ -34,9 +34,7 @@
  *  glue routine for _gsskrb5_inquire_sec_context_by_oid
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: set_sec_context_option.c 20384 2007-04-18 08:51:06Z lha $");
+#include "gsskrb5_locl.h"
=20
 static OM_uint32
 get_bool(OM_uint32 *minor_status,
@@ -70,7 +68,37 @@
     return GSS_S_COMPLETE;
 }
=20
-OM_uint32
+static OM_uint32
+get_int32(OM_uint32 *minor_status,
+	  const gss_buffer_t value,
+	  OM_uint32 *ret)
+{
+    *minor_status =3D 0;
+    if (value =3D=3D NULL || value->length =3D=3D 0)
+	*ret =3D 0;
+    else if (value->length =3D=3D sizeof(*ret))
+	memcpy(ret, value->value, sizeof(*ret));
+    else
+	return GSS_S_UNAVAILABLE;
+
+    return GSS_S_COMPLETE;
+}
+
+static OM_uint32
+set_int32(OM_uint32 *minor_status,
+	  const gss_buffer_t value,
+	  OM_uint32 set)
+{
+    *minor_status =3D 0;
+    if (value->length =3D=3D sizeof(set))
+	memcpy(value->value, &set, sizeof(set));
+    else
+	return GSS_S_UNAVAILABLE;
+
+    return GSS_S_COMPLETE;
+}
+
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_set_sec_context_option
            (OM_uint32 *minor_status,
             gss_ctx_id_t *context_handle,
@@ -126,11 +154,10 @@
 	if (maj_stat !=3D GSS_S_COMPLETE)
 	    return maj_stat;
=20
-	_gsskrb5_register_acceptor_identity(str);
+	maj_stat =3D _gsskrb5_register_acceptor_identity(minor_status, str);
 	free(str);
=20
-	*minor_status =3D 0;
-	return GSS_S_COMPLETE;
+	return maj_stat;
=20
     } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_DEFAULT_REALM_X)=
) {
 	char *str;
@@ -162,7 +189,7 @@
 	    }
 	    memcpy(&c, value->value, sizeof(c));
 	    krb5_set_send_to_kdc_func(context,
-				      (krb5_send_to_kdc_func)c.func,=20
+				      (krb5_send_to_kdc_func)c.func,
 				      c.ptr);
 	}
=20
@@ -185,6 +212,47 @@
 	    return GSS_S_FAILURE;
=20
 	return GSS_S_COMPLETE;
+    } else if (gss_oid_equal(desired_object, GSS_KRB5_SET_TIME_OFFSET_X)) {
+	OM_uint32 offset;
+	time_t t;
+
+	maj_stat =3D get_int32(minor_status, value, &offset);
+	if (maj_stat !=3D GSS_S_COMPLETE)
+	    return maj_stat;
+
+	t =3D time(NULL) + offset;
+
+	krb5_set_real_time(context, t, 0);
+
+	*minor_status =3D 0;
+	return GSS_S_COMPLETE;
+    } else if (gss_oid_equal(desired_object, GSS_KRB5_GET_TIME_OFFSET_X)) {
+	krb5_timestamp sec;
+	int32_t usec;
+	time_t t;
+
+	t =3D time(NULL);
+
+	krb5_us_timeofday (context, &sec, &usec);
+
+	maj_stat =3D set_int32(minor_status, value, sec - t);
+	if (maj_stat !=3D GSS_S_COMPLETE)
+	    return maj_stat;
+
+	*minor_status =3D 0;
+	return GSS_S_COMPLETE;
+    } else if (gss_oid_equal(desired_object, GSS_KRB5_PLUGIN_REGISTER_X)) {
+	struct gsskrb5_krb5_plugin c;
+
+	if (value->length !=3D sizeof(c)) {
+	    *minor_status =3D EINVAL;
+	    return GSS_S_FAILURE;
+	}
+	memcpy(&c, value->value, sizeof(c));
+	krb5_plugin_register(context, c.type, c.name, c.symbol);
+
+	*minor_status =3D 0;
+	return GSS_S_COMPLETE;
     }
=20
     *minor_status =3D EINVAL;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/te=
st_cfx.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/test_cfx.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/test_cfx.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -31,9 +31,7 @@
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: test_cfx.c 19031 2006-11-13 18:02:57Z lha $");
+#include "gsskrb5_locl.h"
=20
 struct range {
     size_t lower;
@@ -49,22 +47,28 @@
 };
=20
 static void
-test_range(const struct range *r, int integ,=20
+test_range(const struct range *r, int integ,
 	   krb5_context context, krb5_crypto crypto)
 {
     krb5_error_code ret;
     size_t size, rsize;
+    struct gsskrb5_ctx ctx;
=20
     for (size =3D r->lower; size < r->upper; size++) {
-	OM_uint32 max_wrap_size;
 	size_t cksumsize;
 	uint16_t padsize;
+	OM_uint32 minor;
+	OM_uint32 max_wrap_size;
=20
-	ret =3D _gsskrb5cfx_max_wrap_length_cfx(context,
-					      crypto,
-					      integ,
-					      size,
-					      &max_wrap_size);
+	ctx.crypto =3D crypto;
+
+	ret =3D _gssapi_wrap_size_cfx(&minor,
+				    &ctx,
+				    context,
+				    integ,
+				    0,
+				    size,
+				    &max_wrap_size);
 	if (ret)
 	    krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret);
 	if (max_wrap_size =3D=3D 0)
@@ -73,13 +77,14 @@
 	ret =3D _gsskrb5cfx_wrap_length_cfx(context,
 					  crypto,
 					  integ,
+					  0,
 					  max_wrap_size,
 					  &rsize, &cksumsize, &padsize);
 	if (ret)
 	    krb5_errx(context, 1, "_gsskrb5cfx_wrap_length_cfx: %d", ret);
=20
 	if (size < rsize)
-	    krb5_errx(context, 1,=20
+	    krb5_errx(context, 1,
 		      "size (%d) < rsize (%d) for max_wrap_size %d",
 		      (int)size, (int)rsize, (int)max_wrap_size);
     }
@@ -94,25 +99,34 @@
     OM_uint32 max_wrap_size;
     size_t cksumsize;
     uint16_t padsize;
+    struct gsskrb5_ctx ctx;
+    OM_uint32 minor;
=20
-    ret =3D _gsskrb5cfx_max_wrap_length_cfx(context,
-					  crypto,
-					  integ,
-					  testsize,
-					  &max_wrap_size);
+    ctx.crypto =3D crypto;
+
+    ret =3D _gssapi_wrap_size_cfx(&minor,
+				&ctx,
+				context,
+				integ,
+				0,
+				testsize,
+				&max_wrap_size);
+    if (ret)
+      krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret);
     if (ret)
 	krb5_errx(context, 1, "_gsskrb5cfx_max_wrap_length_cfx: %d", ret);
-   =20
+
     ret =3D _gsskrb5cfx_wrap_length_cfx(context,
 				      crypto,
 				      integ,
+				      0,
 				      max_wrap_size,
 				      &rsize, &cksumsize, &padsize);
     if (ret)
 	krb5_errx(context, 1, "_gsskrb5cfx_wrap_length_cfx: %d", ret);
-   =20
+
     if (testsize < rsize)
-	krb5_errx(context, 1,=20
+	krb5_errx(context, 1,
 		  "testsize (%d) < rsize (%d) for max_wrap_size %d",
 		  (int)testsize, (int)rsize, (int)max_wrap_size);
 }
@@ -132,8 +146,8 @@
     ret =3D krb5_init_context(&context);
     if (ret)
 	errx(1, "krb5_context_init: %d", ret);
-   =20
-    ret =3D krb5_generate_random_keyblock(context,=20
+
+    ret =3D krb5_generate_random_keyblock(context,
 					ENCTYPE_AES256_CTS_HMAC_SHA1_96,
 					&keyblock);
     if (ret)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ti=
cket_flags.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/ticket_flags.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/ticket_flags.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: ticket_flags.c 18334 2006-10-07 22:16:04Z lha $");
+#include "gsskrb5_locl.h"
=20
 OM_uint32
 _gsskrb5_get_tkt_flags(OM_uint32 *minor_status,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/un=
wrap.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/unwrap.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/unwrap.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: unwrap.c 19031 2006-11-13 18:02:57Z lha $");
+#ifdef HEIM_WEAK_CRYPTO
=20
 static OM_uint32
 unwrap_des
@@ -48,21 +48,29 @@
 {
   u_char *p, *seq;
   size_t len;
-  MD5_CTX md5;
+  EVP_MD_CTX *md5;
   u_char hash[16];
+  EVP_CIPHER_CTX des_ctx;
   DES_key_schedule schedule;
   DES_cblock deskey;
   DES_cblock zero;
-  int i;
+  size_t i;
   uint32_t seq_number;
   size_t padlength;
   OM_uint32 ret;
   int cstate;
   int cmp;
+  int token_len;
+
+  if (IS_DCE_STYLE(context_handle)) {
+     token_len =3D 22 + 8 + 15; /* 45 */
+  } else {
+     token_len =3D input_message_buffer->length;
+  }
=20
   p =3D input_message_buffer->value;
   ret =3D _gsskrb5_verify_header (&p,
-				   input_message_buffer->length,
+				   token_len,
 				   "\x02\x01",
 				   GSS_KRB5_MECHANISM);
   if (ret)
@@ -90,49 +98,56 @@
   if(cstate) {
       /* decrypt data */
       memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
+      memset (&zero, 0, sizeof(zero));
=20
       for (i =3D 0; i < sizeof(deskey); ++i)
 	  deskey[i] ^=3D 0xf0;
-      DES_set_key (&deskey, &schedule);
-      memset (&zero, 0, sizeof(zero));
-      DES_cbc_encrypt ((void *)p,
-		       (void *)p,
-		       input_message_buffer->length - len,
-		       &schedule,
-		       &zero,
-		       DES_DECRYPT);
-     =20
-      memset (deskey, 0, sizeof(deskey));
+
+
+      EVP_CIPHER_CTX_init(&des_ctx);
+      EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, deskey, zero, 0);
+      EVP_Cipher(&des_ctx, p, p, input_message_buffer->length - len);
+      EVP_CIPHER_CTX_cleanup(&des_ctx);
+
       memset (&schedule, 0, sizeof(schedule));
   }
-  /* check pad */
-  ret =3D _gssapi_verify_pad(input_message_buffer,=20
-			   input_message_buffer->length - len,
-			   &padlength);
-  if (ret)
-      return ret;
=20
-  MD5_Init (&md5);
-  MD5_Update (&md5, p - 24, 8);
-  MD5_Update (&md5, p, input_message_buffer->length - len);
-  MD5_Final (hash, &md5);
+  if (IS_DCE_STYLE(context_handle)) {
+    padlength =3D 0;
+  } else {
+    /* check pad */
+    ret =3D _gssapi_verify_pad(input_message_buffer,
+			     input_message_buffer->length - len,
+			     &padlength);
+    if (ret)
+        return ret;
+  }
+
+  md5 =3D EVP_MD_CTX_create();
+  EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+  EVP_DigestUpdate(md5, p - 24, 8);
+  EVP_DigestUpdate(md5, p, input_message_buffer->length - len);
+  EVP_DigestFinal_ex(md5, hash, NULL);
+  EVP_MD_CTX_destroy(md5);
=20
   memset (&zero, 0, sizeof(zero));
   memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
-  DES_set_key (&deskey, &schedule);
+  DES_set_key_unchecked (&deskey, &schedule);
   DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
 		 &schedule, &zero);
-  if (memcmp (p - 8, hash, 8) !=3D 0)
+  if (ct_memcmp (p - 8, hash, 8) !=3D 0)
     return GSS_S_BAD_MIC;
=20
   /* verify sequence number */
- =20
+
   HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
=20
   p -=3D 16;
-  DES_set_key (&deskey, &schedule);
-  DES_cbc_encrypt ((void *)p, (void *)p, 8,
-		   &schedule, (DES_cblock *)hash, DES_DECRYPT);
+
+  EVP_CIPHER_CTX_init(&des_ctx);
+  EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, has=
h, 0);
+  EVP_Cipher(&des_ctx, p, p, 8);
+  EVP_CIPHER_CTX_cleanup(&des_ctx);
=20
   memset (deskey, 0, sizeof(deskey));
   memset (&schedule, 0, sizeof(schedule));
@@ -141,9 +156,9 @@
   _gsskrb5_decode_om_uint32(seq, &seq_number);
=20
   if (context_handle->more_flags & LOCAL)
-      cmp =3D memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+      cmp =3D ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
   else
-      cmp =3D memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+      cmp =3D ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
=20
   if (cmp !=3D 0) {
     HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
@@ -170,6 +185,7 @@
 	  output_message_buffer->length);
   return GSS_S_COMPLETE;
 }
+#endif
=20
 static OM_uint32
 unwrap_des3
@@ -195,10 +211,17 @@
   krb5_crypto crypto;
   Checksum csum;
   int cmp;
+  int token_len;
+
+  if (IS_DCE_STYLE(context_handle)) {
+     token_len =3D 34 + 8 + 15; /* 57 */
+  } else {
+     token_len =3D input_message_buffer->length;
+  }
=20
   p =3D input_message_buffer->value;
   ret =3D _gsskrb5_verify_header (&p,
-				   input_message_buffer->length,
+				   token_len,
 				   "\x02\x01",
 				   GSS_KRB5_MECHANISM);
   if (ret)
@@ -207,16 +230,16 @@
   if (memcmp (p, "\x04\x00", 2) !=3D 0) /* HMAC SHA1 DES3_KD */
     return GSS_S_BAD_SIG;
   p +=3D 2;
-  if (memcmp (p, "\x02\x00", 2) =3D=3D 0) {
+  if (ct_memcmp (p, "\x02\x00", 2) =3D=3D 0) {
     cstate =3D 1;
-  } else if (memcmp (p, "\xff\xff", 2) =3D=3D 0) {
+  } else if (ct_memcmp (p, "\xff\xff", 2) =3D=3D 0) {
     cstate =3D 0;
   } else
     return GSS_S_BAD_MIC;
   p +=3D 2;
   if(conf_state !=3D NULL)
     *conf_state =3D cstate;
-  if (memcmp (p, "\xff\xff", 2) !=3D 0)
+  if (ct_memcmp (p, "\xff\xff", 2) !=3D 0)
     return GSS_S_DEFECTIVE_TOKEN;
   p +=3D 2;
   p +=3D 28;
@@ -245,15 +268,20 @@
       memcpy (p, tmp.data, tmp.length);
       krb5_data_free(&tmp);
   }
-  /* check pad */
-  ret =3D _gssapi_verify_pad(input_message_buffer,=20
-			   input_message_buffer->length - len,
-			   &padlength);
-  if (ret)
-      return ret;
+
+  if (IS_DCE_STYLE(context_handle)) {
+    padlength =3D 0;
+  } else {
+    /* check pad */
+    ret =3D _gssapi_verify_pad(input_message_buffer,
+			     input_message_buffer->length - len,
+			     &padlength);
+    if (ret)
+        return ret;
+  }
=20
   /* verify sequence number */
- =20
+
   HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
=20
   p -=3D 28;
@@ -292,10 +320,10 @@
   _gsskrb5_decode_om_uint32(seq, &seq_number);
=20
   if (context_handle->more_flags & LOCAL)
-      cmp =3D memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+      cmp =3D ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
   else
-      cmp =3D memcmp(&seq[4], "\x00\x00\x00\x00", 4);
- =20
+      cmp =3D ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+
   krb5_data_free (&seq_data);
   if (cmp !=3D 0) {
       *minor_status =3D 0;
@@ -352,7 +380,7 @@
   return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gsskrb5_unwrap
+OM_uint32 GSSAPI_CALLCONV _gsskrb5_unwrap
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             const gss_buffer_t input_message_buffer,
@@ -369,11 +397,16 @@
=20
   output_message_buffer->value =3D NULL;
   output_message_buffer->length =3D 0;
+  if (qop_state !=3D NULL)
+      *qop_state =3D GSS_C_QOP_DEFAULT;
=20
   GSSAPI_KRB5_INIT (&context);
=20
-  if (qop_state !=3D NULL)
-      *qop_state =3D GSS_C_QOP_DEFAULT;
+  if (ctx->more_flags & IS_CFX)
+      return _gssapi_unwrap_cfx (minor_status, ctx, context,
+				 input_message_buffer, output_message_buffer,
+				 conf_state, qop_state);
+
   HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
   ret =3D _gsskrb5i_get_token_key(ctx, context, &key);
   HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
@@ -387,9 +420,13 @@
=20
   switch (keytype) {
   case KEYTYPE_DES :
+#ifdef HEIM_WEAK_CRYPTO
       ret =3D unwrap_des (minor_status, ctx,
 			input_message_buffer, output_message_buffer,
 			conf_state, qop_state, key);
+#else
+      ret =3D GSS_S_FAILURE;
+#endif
       break;
   case KEYTYPE_DES3 :
       ret =3D unwrap_des3 (minor_status, ctx, context,
@@ -403,9 +440,7 @@
 				    conf_state, qop_state, key);
       break;
   default :
-      ret =3D _gssapi_unwrap_cfx (minor_status, ctx, context,
-				input_message_buffer, output_message_buffer,
-				conf_state, qop_state, key);
+      abort();
       break;
   }
   krb5_free_keyblock (context, key);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/ve=
rify_mic.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/verify_mic.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/verify_mic.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
+#include "gsskrb5_locl.h"
=20
-RCSID("$Id: verify_mic.c 19031 2006-11-13 18:02:57Z lha $");
+#ifdef HEIM_WEAK_CRYPTO
=20
 static OM_uint32
 verify_mic_des
@@ -44,13 +44,14 @@
             const gss_buffer_t token_buffer,
             gss_qop_t * qop_state,
 	    krb5_keyblock *key,
-	    char *type
+	    const char *type
 	    )
 {
   u_char *p;
-  MD5_CTX md5;
+  EVP_MD_CTX *md5;
   u_char hash[16], *seq;
   DES_key_schedule schedule;
+  EVP_CIPHER_CTX des_ctx;
   DES_cblock zero;
   DES_cblock deskey;
   uint32_t seq_number;
@@ -74,32 +75,35 @@
   p +=3D 16;
=20
   /* verify checksum */
-  MD5_Init (&md5);
-  MD5_Update (&md5, p - 24, 8);
-  MD5_Update (&md5, message_buffer->value,
-	     message_buffer->length);
-  MD5_Final (hash, &md5);
+  md5 =3D EVP_MD_CTX_create();
+  EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+  EVP_DigestUpdate(md5, p - 24, 8);
+  EVP_DigestUpdate(md5, message_buffer->value, message_buffer->length);
+  EVP_DigestFinal_ex(md5, hash, NULL);
+  EVP_MD_CTX_destroy(md5);
=20
   memset (&zero, 0, sizeof(zero));
   memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
=20
-  DES_set_key (&deskey, &schedule);
+  DES_set_key_unchecked (&deskey, &schedule);
   DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
 		 &schedule, &zero);
-  if (memcmp (p - 8, hash, 8) !=3D 0) {
+  if (ct_memcmp (p - 8, hash, 8) !=3D 0) {
     memset (deskey, 0, sizeof(deskey));
     memset (&schedule, 0, sizeof(schedule));
     return GSS_S_BAD_MIC;
   }
=20
   /* verify sequence number */
- =20
+
   HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
=20
   p -=3D 16;
-  DES_set_key (&deskey, &schedule);
-  DES_cbc_encrypt ((void *)p, (void *)p, 8,
-		   &schedule, (DES_cblock *)hash, DES_DECRYPT);
+
+  EVP_CIPHER_CTX_init(&des_ctx);
+  EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, has=
h, 0);
+  EVP_Cipher(&des_ctx, p, p, 8);
+  EVP_CIPHER_CTX_cleanup(&des_ctx);
=20
   memset (deskey, 0, sizeof(deskey));
   memset (&schedule, 0, sizeof(schedule));
@@ -108,9 +112,9 @@
   _gsskrb5_decode_om_uint32(seq, &seq_number);
=20
   if (context_handle->more_flags & LOCAL)
-      cmp =3D memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+      cmp =3D ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
   else
-      cmp =3D memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+      cmp =3D ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
=20
   if (cmp !=3D 0) {
     HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
@@ -127,6 +131,7 @@
=20
   return GSS_S_COMPLETE;
 }
+#endif
=20
 static OM_uint32
 verify_mic_des3
@@ -137,7 +142,7 @@
             const gss_buffer_t token_buffer,
             gss_qop_t * qop_state,
 	    krb5_keyblock *key,
-	    char *type
+	    const char *type
 	    )
 {
   u_char *p;
@@ -150,7 +155,7 @@
   Checksum csum;
   char *tmp;
   char ivec[8];
- =20
+
   p =3D token_buffer->value;
   ret =3D _gsskrb5_verify_header (&p,
 				   token_buffer->length,
@@ -209,9 +214,9 @@
   _gsskrb5_decode_om_uint32(seq, &seq_number);
=20
   if (context_handle->more_flags & LOCAL)
-      cmp =3D memcmp(&seq[4], "\xff\xff\xff\xff", 4);
+      cmp =3D ct_memcmp(&seq[4], "\xff\xff\xff\xff", 4);
   else
-      cmp =3D memcmp(&seq[4], "\x00\x00\x00\x00", 4);
+      cmp =3D ct_memcmp(&seq[4], "\x00\x00\x00\x00", 4);
=20
   krb5_data_free (&seq_data);
   if (cmp !=3D 0) {
@@ -246,6 +251,14 @@
   csum.checksum.length =3D 20;
   csum.checksum.data   =3D p + 8;
=20
+  krb5_crypto_destroy (context, crypto);
+  ret =3D krb5_crypto_init(context, key,
+			 ETYPE_DES3_CBC_SHA1, &crypto);
+  if (ret){
+      *minor_status =3D ret;
+      return GSS_S_FAILURE;
+  }
+
   ret =3D krb5_verify_checksum (context, crypto,
 			      KRB5_KU_USAGE_SIGN,
 			      tmp, message_buffer->length + 8,
@@ -266,21 +279,26 @@
 OM_uint32
 _gsskrb5_verify_mic_internal
            (OM_uint32 * minor_status,
-            const gsskrb5_ctx context_handle,
+            const gsskrb5_ctx ctx,
 	    krb5_context context,
             const gss_buffer_t message_buffer,
             const gss_buffer_t token_buffer,
             gss_qop_t * qop_state,
-	    char * type
+	    const char * type
 	    )
 {
     krb5_keyblock *key;
     OM_uint32 ret;
     krb5_keytype keytype;
=20
-    HEIMDAL_MUTEX_lock(&context_handle->ctx_id_mutex);
-    ret =3D _gsskrb5i_get_token_key(context_handle, context, &key);
-    HEIMDAL_MUTEX_unlock(&context_handle->ctx_id_mutex);
+    if (ctx->more_flags & IS_CFX)
+        return _gssapi_verify_mic_cfx (minor_status, ctx,
+				       context, message_buffer, token_buffer,
+				       qop_state);
+
+    HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
+    ret =3D _gsskrb5i_get_token_key(ctx, context, &key);
+    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
     if (ret) {
 	*minor_status =3D ret;
 	return GSS_S_FAILURE;
@@ -289,35 +307,35 @@
     krb5_enctype_to_keytype (context, key->keytype, &keytype);
     switch (keytype) {
     case KEYTYPE_DES :
-	ret =3D verify_mic_des (minor_status, context_handle, context,
+#ifdef HEIM_WEAK_CRYPTO
+	ret =3D verify_mic_des (minor_status, ctx, context,
 			      message_buffer, token_buffer, qop_state, key,
 			      type);
+#else
+      ret =3D GSS_S_FAILURE;
+#endif
 	break;
     case KEYTYPE_DES3 :
-	ret =3D verify_mic_des3 (minor_status, context_handle, context,
+	ret =3D verify_mic_des3 (minor_status, ctx, context,
 			       message_buffer, token_buffer, qop_state, key,
 			       type);
 	break;
     case KEYTYPE_ARCFOUR :
     case KEYTYPE_ARCFOUR_56 :
-	ret =3D _gssapi_verify_mic_arcfour (minor_status, context_handle,
+	ret =3D _gssapi_verify_mic_arcfour (minor_status, ctx,
 					  context,
 					  message_buffer, token_buffer,
 					  qop_state, key, type);
 	break;
     default :
-	ret =3D _gssapi_verify_mic_cfx (minor_status, context_handle,
-				      context,
-				      message_buffer, token_buffer, qop_state,
-				      key);
-	break;
+        abort();
     }
     krb5_free_keyblock (context, key);
-   =20
+
     return ret;
 }
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_verify_mic
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
@@ -334,11 +352,11 @@
     if (qop_state !=3D NULL)
 	*qop_state =3D GSS_C_QOP_DEFAULT;
=20
-    ret =3D _gsskrb5_verify_mic_internal(minor_status,=20
+    ret =3D _gsskrb5_verify_mic_internal(minor_status,
 				       (gsskrb5_ctx)context_handle,
 				       context,
 				       message_buffer, token_buffer,
-				       qop_state, "\x01\x01");
+				       qop_state, (void *)(intptr_t)"\x01\x01");
=20
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/krb5/wr=
ap.c
--- a/head/crypto/heimdal/lib/gssapi/krb5/wrap.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/krb5/wrap.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "krb5/gsskrb5_locl.h"
-
-RCSID("$Id: wrap.c 19035 2006-11-14 09:49:56Z lha $");
+#include "gsskrb5_locl.h"
=20
 /*
  * Return initiator subkey, or if that doesn't exists, the subkey.
@@ -49,19 +47,19 @@
=20
     if (ctx->more_flags & LOCAL) {
 	ret =3D krb5_auth_con_getlocalsubkey(context,
-				     ctx->auth_context,=20
+				     ctx->auth_context,
 				     key);
     } else {
 	ret =3D krb5_auth_con_getremotesubkey(context,
-				      ctx->auth_context,=20
+				      ctx->auth_context,
 				      key);
     }
     if (ret =3D=3D 0 && *key =3D=3D NULL)
 	ret =3D krb5_auth_con_getkey(context,
-				   ctx->auth_context,=20
+				   ctx->auth_context,
 				   key);
     if (ret =3D=3D 0 && *key =3D=3D NULL) {
-	krb5_set_error_string(context, "No initiator subkey available");
+	krb5_set_error_message(context, 0, "No initiator subkey available");
 	return GSS_KRB5_S_KG_NO_SUBKEY;
     }
     return ret;
@@ -77,15 +75,15 @@
=20
     if (ctx->more_flags & LOCAL) {
 	ret =3D krb5_auth_con_getremotesubkey(context,
-				      ctx->auth_context,=20
+				      ctx->auth_context,
 				      key);
     } else {
 	ret =3D krb5_auth_con_getlocalsubkey(context,
-				     ctx->auth_context,=20
+				     ctx->auth_context,
 				     key);
     }
     if (ret =3D=3D 0 && *key =3D=3D NULL) {
-	krb5_set_error_string(context, "No acceptor subkey available");
+	krb5_set_error_message(context, 0, "No acceptor subkey available");
 	return GSS_KRB5_S_KG_NO_SUBKEY;
     }
     return ret;
@@ -106,7 +104,7 @@
 	    _gsskrb5i_get_initiator_subkey(ctx, context, key);
     }
     if (*key =3D=3D NULL) {
-	krb5_set_error_string(context, "No token key available");
+	krb5_set_error_message(context, 0, "No token key available");
 	return GSS_KRB5_S_KG_NO_SUBKEY;
     }
     return 0;
@@ -120,7 +118,7 @@
 	    int extrasize
            )
 {
-    size_t len, total_len;=20
+    size_t len, total_len;
=20
     len =3D 8 + req_output_size + blocksize + extrasize;
=20
@@ -136,7 +134,7 @@
     return GSS_S_COMPLETE;
 }
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gsskrb5_wrap_size_limit (
             OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
@@ -154,6 +152,11 @@
=20
   GSSAPI_KRB5_INIT (&context);
=20
+  if (ctx->more_flags & IS_CFX)
+      return _gssapi_wrap_size_cfx(minor_status, ctx, context,
+				   conf_req_flag, qop_req,
+				   req_output_size, max_input_size);
+
   HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
   ret =3D _gsskrb5i_get_token_key(ctx, context, &key);
   HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
@@ -165,21 +168,23 @@
=20
   switch (keytype) {
   case KEYTYPE_DES :
+#ifdef HEIM_WEAK_CRYPTO
       ret =3D sub_wrap_size(req_output_size, max_input_size, 8, 22);
+#else
+      ret =3D GSS_S_FAILURE;
+#endif
       break;
-  case KEYTYPE_ARCFOUR:
-  case KEYTYPE_ARCFOUR_56:
+  case ENCTYPE_ARCFOUR_HMAC_MD5:
+  case ENCTYPE_ARCFOUR_HMAC_MD5_56:
       ret =3D _gssapi_wrap_size_arcfour(minor_status, ctx, context,
-				      conf_req_flag, qop_req,=20
+				      conf_req_flag, qop_req,
 				      req_output_size, max_input_size, key);
       break;
   case KEYTYPE_DES3 :
       ret =3D sub_wrap_size(req_output_size, max_input_size, 8, 34);
       break;
   default :
-      ret =3D _gssapi_wrap_size_cfx(minor_status, ctx, context,
-				  conf_req_flag, qop_req,=20
-				  req_output_size, max_input_size, key);
+      abort();
       break;
   }
   krb5_free_keyblock (context, key);
@@ -187,6 +192,8 @@
   return ret;
 }
=20
+#ifdef HEIM_WEAK_CRYPTO
+
 static OM_uint32
 wrap_des
            (OM_uint32 * minor_status,
@@ -201,19 +208,29 @@
            )
 {
   u_char *p;
-  MD5_CTX md5;
+  EVP_MD_CTX *md5;
   u_char hash[16];
   DES_key_schedule schedule;
+  EVP_CIPHER_CTX des_ctx;
   DES_cblock deskey;
   DES_cblock zero;
-  int i;
+  size_t i;
   int32_t seq_number;
   size_t len, total_len, padlength, datalen;
=20
-  padlength =3D 8 - (input_message_buffer->length % 8);
-  datalen =3D input_message_buffer->length + padlength + 8;
-  len =3D datalen + 22;
-  _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+  if (IS_DCE_STYLE(ctx)) {
+    padlength =3D 0;
+    datalen =3D input_message_buffer->length;
+    len =3D 22 + 8;
+    _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+    total_len +=3D datalen;
+    datalen +=3D 8;
+  } else {
+    padlength =3D 8 - (input_message_buffer->length % 8);
+    datalen =3D input_message_buffer->length + padlength + 8;
+    len =3D datalen + 22;
+    _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+  }
=20
   output_message_buffer->length =3D total_len;
   output_message_buffer->value  =3D malloc (total_len);
@@ -252,14 +269,16 @@
   memset (p + 8 + input_message_buffer->length, padlength, padlength);
=20
   /* checksum */
-  MD5_Init (&md5);
-  MD5_Update (&md5, p - 24, 8);
-  MD5_Update (&md5, p, datalen);
-  MD5_Final (hash, &md5);
+  md5 =3D EVP_MD_CTX_create();
+  EVP_DigestInit_ex(md5, EVP_md5(), NULL);
+  EVP_DigestUpdate(md5, p - 24, 8);
+  EVP_DigestUpdate(md5, p, datalen);
+  EVP_DigestFinal_ex(md5, hash, NULL);
+  EVP_MD_CTX_destroy(md5);
=20
   memset (&zero, 0, sizeof(zero));
   memcpy (&deskey, key->keyvalue.data, sizeof(deskey));
-  DES_set_key (&deskey, &schedule);
+  DES_set_key_unchecked (&deskey, &schedule);
   DES_cbc_cksum ((void *)hash, (void *)hash, sizeof(hash),
 		 &schedule, &zero);
   memcpy (p - 8, hash, 8);
@@ -279,9 +298,10 @@
 	  (ctx->more_flags & LOCAL) ? 0 : 0xFF,
 	  4);
=20
-  DES_set_key (&deskey, &schedule);
-  DES_cbc_encrypt ((void *)p, (void *)p, 8,
-		   &schedule, (DES_cblock *)(p + 8), DES_ENCRYPT);
+  EVP_CIPHER_CTX_init(&des_ctx);
+  EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, key->keyvalue.data, p +=
 8, 1);
+  EVP_Cipher(&des_ctx, p, p, 8);
+  EVP_CIPHER_CTX_cleanup(&des_ctx);
=20
   krb5_auth_con_setlocalseqnumber (context,
 			       ctx->auth_context,
@@ -296,14 +316,11 @@
=20
       for (i =3D 0; i < sizeof(deskey); ++i)
 	  deskey[i] ^=3D 0xf0;
-      DES_set_key (&deskey, &schedule);
-      memset (&zero, 0, sizeof(zero));
-      DES_cbc_encrypt ((void *)p,
-		       (void *)p,
-		       datalen,
-		       &schedule,
-		       &zero,
-		       DES_ENCRYPT);
+
+      EVP_CIPHER_CTX_init(&des_ctx);
+      EVP_CipherInit_ex(&des_ctx, EVP_des_cbc(), NULL, deskey, zero, 1);
+      EVP_Cipher(&des_ctx, p, p, datalen);
+      EVP_CIPHER_CTX_cleanup(&des_ctx);
   }
   memset (deskey, 0, sizeof(deskey));
   memset (&schedule, 0, sizeof(schedule));
@@ -314,6 +331,8 @@
   return GSS_S_COMPLETE;
 }
=20
+#endif
+
 static OM_uint32
 wrap_des3
            (OM_uint32 * minor_status,
@@ -336,10 +355,19 @@
   Checksum cksum;
   krb5_data encdata;
=20
-  padlength =3D 8 - (input_message_buffer->length % 8);
-  datalen =3D input_message_buffer->length + padlength + 8;
-  len =3D datalen + 34;
-  _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+  if (IS_DCE_STYLE(ctx)) {
+    padlength =3D 0;
+    datalen =3D input_message_buffer->length;
+    len =3D 34 + 8;
+    _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+    total_len +=3D datalen;
+    datalen +=3D 8;
+  } else {
+    padlength =3D 8 - (input_message_buffer->length % 8);
+    datalen =3D input_message_buffer->length + padlength + 8;
+    len =3D datalen + 34;
+    _gsskrb5_encap_length (len, &len, &total_len, GSS_KRB5_MECHANISM);
+  }
=20
   output_message_buffer->length =3D total_len;
   output_message_buffer->value  =3D malloc (total_len);
@@ -352,7 +380,7 @@
   p =3D _gsskrb5_make_header(output_message_buffer->value,
 			      len,
 			      "\x02\x01", /* TOK_ID */
-			      GSS_KRB5_MECHANISM);=20
+			      GSS_KRB5_MECHANISM);
=20
   /* SGN_ALG */
   memcpy (p, "\x04\x00", 2);	/* HMAC SHA1 DES3-KD */
@@ -449,7 +477,7 @@
       *minor_status =3D ret;
       return GSS_S_FAILURE;
   }
- =20
+
   assert (encdata.length =3D=3D 8);
=20
   memcpy (p, encdata.data, encdata.length);
@@ -496,7 +524,8 @@
   return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gsskrb5_wrap
+OM_uint32 GSSAPI_CALLCONV
+_gsskrb5_wrap
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             int conf_req_flag,
@@ -512,8 +541,16 @@
   krb5_keytype keytype;
   const gsskrb5_ctx ctx =3D (const gsskrb5_ctx) context_handle;
=20
+  output_message_buffer->value =3D NULL;
+  output_message_buffer->length =3D 0;
+
   GSSAPI_KRB5_INIT (&context);
=20
+  if (ctx->more_flags & IS_CFX)
+      return _gssapi_wrap_cfx (minor_status, ctx, context, conf_req_flag,
+			       input_message_buffer, conf_state,
+			       output_message_buffer);
+
   HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
   ret =3D _gsskrb5i_get_token_key(ctx, context, &key);
   HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
@@ -525,9 +562,13 @@
=20
   switch (keytype) {
   case KEYTYPE_DES :
+#ifdef HEIM_WEAK_CRYPTO
       ret =3D wrap_des (minor_status, ctx, context, conf_req_flag,
 		      qop_req, input_message_buffer, conf_state,
 		      output_message_buffer, key);
+#else
+      ret =3D GSS_S_FAILURE;
+#endif
       break;
   case KEYTYPE_DES3 :
       ret =3D wrap_des3 (minor_status, ctx, context, conf_req_flag,
@@ -541,9 +582,7 @@
 				  output_message_buffer, key);
       break;
   default :
-      ret =3D _gssapi_wrap_cfx (minor_status, ctx, context, conf_req_flag,
-			      qop_req, input_message_buffer, conf_state,
-			      output_message_buffer, key);
+      abort();
       break;
   }
   krb5_free_keyblock (context, key);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/ac=
cept_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/accept_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/accept_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
-
-RCSID("$Id: accept_sec_context.c 22521 2008-01-24 11:53:18Z lha $");
+#include "ntlm.h"
=20
 /*
  *
@@ -43,10 +41,17 @@
 _gss_ntlm_allocate_ctx(OM_uint32 *minor_status, ntlm_ctx *ctx)
 {
     OM_uint32 maj_stat;
+    struct ntlm_server_interface *ns_interface =3D NULL;
+
+#ifdef DIGEST
+    ns_interface =3D &ntlmsspi_kdc_digest;
+#endif
+    if (ns_interface =3D=3D NULL)
+	return GSS_S_FAILURE;
=20
     *ctx =3D calloc(1, sizeof(**ctx));
=20
-    (*ctx)->server =3D &ntlmsspi_kdc_digest;
+    (*ctx)->server =3D ns_interface;
=20
     maj_stat =3D (*(*ctx)->server->nsi_init)(minor_status, &(*ctx)->ictx);
     if (maj_stat !=3D GSS_S_COMPLETE)
@@ -59,7 +64,7 @@
  *
  */
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_accept_sec_context
 (OM_uint32 * minor_status,
  gss_ctx_id_t * context_handle,
@@ -76,6 +81,7 @@
 {
     krb5_error_code ret;
     struct ntlm_buf data;
+    OM_uint32 junk;
     ntlm_ctx ctx;
=20
     output_token->value =3D NULL;
@@ -85,7 +91,7 @@
=20
     if (context_handle =3D=3D NULL)
 	return GSS_S_FAILURE;
-=09
+
     if (input_token_buffer =3D=3D GSS_C_NO_BUFFER)
 	return GSS_S_FAILURE;
=20
@@ -110,7 +116,7 @@
 	if (major_status)
 	    return major_status;
 	*context_handle =3D (gss_ctx_id_t)ctx;
-=09
+
 	/* check if the mechs is allowed by remote service */
 	major_status =3D (*ctx->server->nsi_probe)(minor_status, ctx->ictx, NULL);
 	if (major_status) {
@@ -120,7 +126,7 @@
=20
 	data.data =3D input_token_buffer->value;
 	data.length =3D input_token_buffer->length;
-=09
+
 	ret =3D heim_ntlm_decode_type1(&data, &type1);
 	if (ret) {
 	    _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
@@ -149,15 +155,15 @@
 						 &out);
 	heim_ntlm_free_type1(&type1);
 	if (major_status !=3D GSS_S_COMPLETE) {
-	    OM_uint32 junk;
-	    _gss_ntlm_delete_sec_context(&junk, context_handle, NULL);
+	    OM_uint32 gunk;
+	    _gss_ntlm_delete_sec_context(&gunk, context_handle, NULL);
 	    return major_status;
 	}
=20
 	output_token->value =3D malloc(out.length);
-	if (output_token->value =3D=3D NULL) {
-	    OM_uint32 junk;
-	    _gss_ntlm_delete_sec_context(&junk, context_handle, NULL);
+	if (output_token->value =3D=3D NULL && out.length !=3D 0) {
+	    OM_uint32 gunk;
+	    _gss_ntlm_delete_sec_context(&gunk, context_handle, NULL);
 	    *minor_status =3D ENOMEM;
 	    return GSS_S_FAILURE;
 	}
@@ -201,27 +207,31 @@
 		n->domain =3D strdup(type3.targetname);
 	    }
 	    if (n =3D=3D NULL || n->user =3D=3D NULL || n->domain =3D=3D NULL) {
+		gss_name_t tempn =3D  (gss_name_t)n;
+		_gss_ntlm_release_name(&junk, &tempn);
 		heim_ntlm_free_type3(&type3);
-		_gss_ntlm_delete_sec_context(minor_status,=20
+		_gss_ntlm_delete_sec_context(minor_status,
 					     context_handle, NULL);
 		return maj_stat;
 	    }
 	    *src_name =3D (gss_name_t)n;
-	}	   =20
+	}
=20
 	heim_ntlm_free_type3(&type3);
=20
-	ret =3D krb5_data_copy(&ctx->sessionkey,=20
+	ret =3D krb5_data_copy(&ctx->sessionkey,
 			     session.data, session.length);
-	if (ret) {=09
+	if (ret) {
+	    if (src_name)
+		_gss_ntlm_release_name(&junk, src_name);
 	    _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
 	    *minor_status =3D ret;
 	    return GSS_S_FAILURE;
 	}
-=09
+
 	if (session.length !=3D 0) {
=20
-	    ctx->status |=3D STATUS_SESSIONKEY;=20
+	    ctx->status |=3D STATUS_SESSIONKEY;
=20
 	    if (ctx->flags & NTLM_NEG_NTLM2_SESSION) {
 		_gss_ntlm_set_key(&ctx->u.v2.send, 1,
@@ -233,10 +243,10 @@
 				  ctx->sessionkey.data,
 				  ctx->sessionkey.length);
 	    } else {
-		RC4_set_key(&ctx->u.v1.crypto_send.key,=20
+		RC4_set_key(&ctx->u.v1.crypto_send.key,
 			    ctx->sessionkey.length,
 			    ctx->sessionkey.data);
-		RC4_set_key(&ctx->u.v1.crypto_recv.key,=20
+		RC4_set_key(&ctx->u.v1.crypto_recv.key,
 			    ctx->sessionkey.length,
 			    ctx->sessionkey.data);
 	    }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/ac=
quire_cred.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/acquire_cred.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/acquire_cred.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: acquire_cred.c 22380 2007-12-29 18:42:56Z lha $");
-
-OM_uint32 _gss_ntlm_acquire_cred
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_acquire_cred
            (OM_uint32 * min_stat,
             const gss_name_t desired_name,
             OM_uint32 time_req,
@@ -51,8 +49,7 @@
     ntlm_ctx ctx;
=20
     *min_stat =3D 0;
-    if (output_cred_handle)
-	*output_cred_handle =3D GSS_C_NO_CREDENTIAL;
+    *output_cred_handle =3D GSS_C_NO_CREDENTIAL;
     if (actual_mechs)
 	*actual_mechs =3D GSS_C_NO_OID_SET;
     if (time_rec)
@@ -66,19 +63,17 @@
 	maj_stat =3D _gss_ntlm_allocate_ctx(min_stat, &ctx);
 	if (maj_stat !=3D GSS_S_COMPLETE)
 	    return maj_stat;
-=09
-	maj_stat =3D (*ctx->server->nsi_probe)(min_stat, ctx->ictx,=20
+
+	maj_stat =3D (*ctx->server->nsi_probe)(min_stat, ctx->ictx,
 					     name->domain);
-
+	{
+	    gss_ctx_id_t context =3D (gss_ctx_id_t)ctx;
+	    OM_uint32 junk;
+	    _gss_ntlm_delete_sec_context(&junk, &context, NULL);
+	}
 	if (maj_stat)
 	    return maj_stat;
-
-	{
-	    gss_ctx_id_t context =3D (gss_ctx_id_t)ctx;
-	    _gss_ntlm_delete_sec_context(min_stat, &context, NULL);
-	    *min_stat =3D 0;
-	}
-    }=09
+    }
     if (cred_usage =3D=3D GSS_C_BOTH || cred_usage =3D=3D GSS_C_INITIATE) {
 	ntlm_cred cred;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/ad=
d_cred.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/add_cred.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/add_cred.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: add_cred.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_add_cred (
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_add_cred (
      OM_uint32           *minor_status,
      const gss_cred_id_t input_cred_handle,
      const gss_name_t    desired_name,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/ca=
nonicalize_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/canonicalize_name.c	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/canonicalize_name.c	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: canonicalize_name.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_canonicalize_name (
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_canonicalize_name (
             OM_uint32 * minor_status,
             const gss_name_t input_name,
             const gss_OID mech_type,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/co=
mpare_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/compare_name.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/compare_name.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: compare_name.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_compare_name
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_compare_name
            (OM_uint32 * minor_status,
             const gss_name_t name1,
             const gss_name_t name2,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/co=
ntext_time.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/context_time.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/context_time.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: context_time.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_context_time
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_context_time
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             OM_uint32 * time_rec
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/cr=
ypto.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/crypto.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/crypto.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
-
-RCSID("$Id: crypto.c 19535 2006-12-28 14:49:01Z lha $");
+#include "ntlm.h"
=20
 uint32_t
 _krb5_crc_update (const char *p, size_t len, uint32_t res);
@@ -80,7 +78,7 @@
 		  unsigned char *data, size_t len)
 {
     unsigned char out[16];
-    MD5_CTX ctx;
+    EVP_MD_CTX *ctx;
     const char *signmagic;
     const char *sealmagic;
=20
@@ -94,15 +92,17 @@
=20
     key->seq =3D 0;
=20
-    MD5_Init(&ctx);
-    MD5_Update(&ctx, data, len);
-    MD5_Update(&ctx, signmagic, strlen(signmagic) + 1);
-    MD5_Final(key->signkey, &ctx);
+    ctx =3D EVP_MD_CTX_create();
+    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+    EVP_DigestUpdate(ctx, data, len);
+    EVP_DigestUpdate(ctx, signmagic, strlen(signmagic) + 1);
+    EVP_DigestFinal_ex(ctx, key->signkey, NULL);
=20
-    MD5_Init(&ctx);
-    MD5_Update(&ctx, data, len);
-    MD5_Update(&ctx, sealmagic, strlen(sealmagic) + 1);
-    MD5_Final(out, &ctx);
+    EVP_DigestInit_ex(ctx, EVP_md5(), NULL);
+    EVP_DigestUpdate(ctx, data, len);
+    EVP_DigestUpdate(ctx, sealmagic, strlen(sealmagic) + 1);
+    EVP_DigestFinal_ex(ctx, out, NULL);
+    EVP_MD_CTX_destroy(ctx);
=20
     RC4_set_key(&key->sealkey, 16, out);
     if (sealsign)
@@ -121,20 +121,20 @@
 {
     unsigned char sigature[12];
     uint32_t crc;
-   =20
+
     _krb5_crc_init_table();
     crc =3D _krb5_crc_update(in->value, in->length, 0);
-   =20
+
     encode_le_uint32(0, &sigature[0]);
     encode_le_uint32(crc, &sigature[4]);
     encode_le_uint32(seq, &sigature[8]);
-   =20
+
     encode_le_uint32(1, out); /* version */
     RC4(signkey, sizeof(sigature), sigature, out + 4);
-   =20
+
     if (RAND_bytes(out + 4, 4) !=3D 1)
 	return GSS_S_UNAVAILABLE;
-   =20
+
     return 0;
 }
=20
@@ -152,7 +152,7 @@
=20
     HMAC_CTX_init(&c);
     HMAC_Init_ex(&c, signkey, 16, EVP_md5(), NULL);
-   =20
+
     encode_le_uint32(seq, hmac);
     HMAC_Update(&c, hmac, 4);
     HMAC_Update(&c, in->value, in->length);
@@ -188,7 +188,7 @@
 	return GSS_S_BAD_MIC;
=20
     return GSS_S_COMPLETE;
-}   =20
+}
=20
 static OM_uint32
 v2_seal_message(const gss_buffer_t in,
@@ -259,8 +259,9 @@
 /*
  *
  */
-=20
-OM_uint32 _gss_ntlm_get_mic
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_get_mic
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             gss_qop_t qop_req,
@@ -271,12 +272,7 @@
     ntlm_ctx ctx =3D (ntlm_ctx)context_handle;
     OM_uint32 junk;
=20
-    if (minor_status)
-	*minor_status =3D 0;
-    if (message_token) {
-	message_token->length =3D 0;
-	message_token->value =3D NULL;
-    }
+    *minor_status =3D 0;
=20
     message_token->value =3D malloc(16);
     message_token->length =3D 16;
@@ -339,7 +335,7 @@
  *
  */
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_verify_mic
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
@@ -388,7 +384,7 @@
 	    ((unsigned char *)token_buffer->value) + 4, sigature);
=20
 	_krb5_crc_init_table();
-	crc =3D _krb5_crc_update(message_buffer->value,=20
+	crc =3D _krb5_crc_update(message_buffer->value,
 			       message_buffer->length, 0);
 	/* skip first 4 bytes in the encrypted checksum */
 	decode_le_uint32(&sigature[4], &num);
@@ -425,7 +421,7 @@
  *
  */
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_wrap_size_limit (
             OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
@@ -456,7 +452,8 @@
  *
  */
=20
-OM_uint32 _gss_ntlm_wrap
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_wrap
 (OM_uint32 * minor_status,
  const gss_ctx_id_t context_handle,
  int conf_req_flag,
@@ -469,14 +466,13 @@
     ntlm_ctx ctx =3D (ntlm_ctx)context_handle;
     OM_uint32 ret;
=20
-    if (minor_status)
-	*minor_status =3D 0;
+    *minor_status =3D 0;
     if (conf_state)
 	*conf_state =3D 0;
     if (output_message_buffer =3D=3D GSS_C_NO_BUFFER)
 	return GSS_S_FAILURE;
=20
-   =20
+
     if (CTX_FLAGS_ISSET(ctx, NTLM_NEG_SEAL|NTLM_NEG_NTLM2_SESSION)) {
=20
 	return v2_seal_message(input_message_buffer,
@@ -499,7 +495,7 @@
=20
 	RC4(&ctx->u.v1.crypto_send.key, input_message_buffer->length,
 	    input_message_buffer->value, output_message_buffer->value);
-=09
+
 	ret =3D _gss_ntlm_get_mic(minor_status, context_handle,
 				0, input_message_buffer,
 				&trailer);
@@ -512,7 +508,7 @@
 	    gss_release_buffer(&junk, &trailer);
 	    return GSS_S_FAILURE;
 	}
-	memcpy(((unsigned char *)output_message_buffer->value) +=20
+	memcpy(((unsigned char *)output_message_buffer->value) +
 	       input_message_buffer->length,
 	       trailer.value, trailer.length);
 	gss_release_buffer(&junk, &trailer);
@@ -527,7 +523,8 @@
  *
  */
=20
-OM_uint32 _gss_ntlm_unwrap
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_unwrap
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             const gss_buffer_t input_message_buffer,
@@ -539,12 +536,10 @@
     ntlm_ctx ctx =3D (ntlm_ctx)context_handle;
     OM_uint32 ret;
=20
-    if (minor_status)
-	*minor_status =3D 0;
-    if (output_message_buffer) {
-	output_message_buffer->value =3D NULL;
-	output_message_buffer->length =3D 0;
-    }
+    *minor_status =3D 0;
+    output_message_buffer->value =3D NULL;
+    output_message_buffer->length =3D 0;
+
     if (conf_state)
 	*conf_state =3D 0;
     if (qop_state)
@@ -572,10 +567,10 @@
 	    output_message_buffer->length =3D 0;
 	    return GSS_S_FAILURE;
 	}
-=09
+
 	RC4(&ctx->u.v1.crypto_recv.key, output_message_buffer->length,
 	    input_message_buffer->value, output_message_buffer->value);
-=09
+
 	trailer.value =3D ((unsigned char *)input_message_buffer->value) +
 	    output_message_buffer->length;
 	trailer.length =3D 16;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/de=
lete_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/delete_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/delete_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: delete_sec_context.c 22163 2007-12-04 21:25:06Z lha $");
-
-OM_uint32 _gss_ntlm_delete_sec_context
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_delete_sec_context
            (OM_uint32 * minor_status,
             gss_ctx_id_t * context_handle,
             gss_buffer_t output_token
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/di=
splay_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/display_name.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/display_name.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: display_name.c 22373 2007-12-28 18:36:06Z lha $");
-
-OM_uint32 _gss_ntlm_display_name
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_display_name
            (OM_uint32 * minor_status,
             const gss_name_t input_name,
             gss_buffer_t output_name_buffer,
@@ -49,9 +48,9 @@
=20
     if (output_name_buffer) {
 	ntlm_name n =3D (ntlm_name)input_name;
-	char *str;
+	char *str =3D NULL;
 	int len;
-=09
+
 	output_name_buffer->length =3D 0;
 	output_name_buffer->value =3D NULL;
=20
@@ -61,7 +60,7 @@
 	}
=20
 	len =3D asprintf(&str, "%s@%s", n->user, n->domain);
-	if (str =3D=3D NULL) {
+	if (len < 0 || str =3D=3D NULL) {
 	    *minor_status =3D ENOMEM;
 	    return GSS_S_FAILURE;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/di=
splay_status.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/display_status.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/display_status.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 1998 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: display_status.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_display_status
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_display_status
            (OM_uint32		*minor_status,
 	    OM_uint32		 status_value,
 	    int			 status_type,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/du=
plicate_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/duplicate_name.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/duplicate_name.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: duplicate_name.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_duplicate_name (
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_duplicate_name (
             OM_uint32 * minor_status,
             const gss_name_t src_name,
             gss_name_t * dest_name
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/ex=
port_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/export_name.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/export_name.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1999, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: export_name.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_export_name
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_export_name
            (OM_uint32  * minor_status,
             const gss_name_t input_name,
             gss_buffer_t exported_name
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/ex=
port_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/export_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/export_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1999 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: export_sec_context.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_export_sec_context (
     OM_uint32 * minor_status,
     gss_ctx_id_t * context_handle,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/ex=
ternal.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/external.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/external.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,44 +1,73 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: external.c 19359 2006-12-15 20:01:48Z lha $");
+#if 0
+static gss_mo_desc ntlm_mo[] =3D {
+    {
+	GSS_C_MA_SASL_MECH_NAME,
+	GSS_MO_MA,
+	"SASL mech name",
+	rk_UNCONST("NTLM"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_NAME,
+	GSS_MO_MA,
+	"Mechanism name",
+	rk_UNCONST("NTLMSPP"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_DESCRIPTION,
+	GSS_MO_MA,
+	"Mechanism description",
+	rk_UNCONST("Heimdal NTLMSSP Mechanism"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    }
+};
+
+#endif
=20
 static gssapi_mech_interface_desc ntlm_mech =3D {
     GMI_VERSION,
     "ntlm",
     {10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") },
+    0,
     _gss_ntlm_acquire_cred,
     _gss_ntlm_release_cred,
     _gss_ntlm_init_sec_context,
@@ -67,7 +96,38 @@
     _gss_ntlm_inquire_names_for_mech,
     _gss_ntlm_inquire_mechs_for_name,
     _gss_ntlm_canonicalize_name,
-    _gss_ntlm_duplicate_name
+    _gss_ntlm_duplicate_name,
+    _gss_ntlm_inquire_sec_context_by_oid,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    _gss_ntlm_iter_creds_f,
+    _gss_ntlm_destroy_cred,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+#if 0
+    ntlm_mo,
+    sizeof(ntlm_mo) / sizeof(ntlm_mo[0]),
+#else
+    NULL,
+    0,
+#endif
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
 };
=20
 gssapi_mech_interface
@@ -75,8 +135,3 @@
 {
 	return &ntlm_mech;
 }
-
-static gss_OID_desc _gss_ntlm_mechanism_desc =3D=20
-{10, rk_UNCONST("\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a") };
-
-gss_OID GSS_NTLM_MECHANISM =3D &_gss_ntlm_mechanism_desc;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/im=
port_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/import_name.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/import_name.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: import_name.c 22373 2007-12-28 18:36:06Z lha $");
-
-OM_uint32 _gss_ntlm_import_name
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_import_name
            (OM_uint32 * minor_status,
             const gss_buffer_t input_name_buffer,
             const gss_OID input_name_type,
@@ -43,14 +42,21 @@
            )
 {
     char *name, *p, *p2;
+    int is_hostnamed;
+    int is_username;
     ntlm_name n;
=20
     *minor_status =3D 0;
=20
-    if (output_name)
-	*output_name =3D GSS_C_NO_NAME;
+    if (output_name =3D=3D NULL)
+	return GSS_S_CALL_INACCESSIBLE_WRITE;
=20
-    if (!gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SERVICE))
+    *output_name =3D GSS_C_NO_NAME;
+
+    is_hostnamed =3D gss_oid_equal(input_name_type, GSS_C_NT_HOSTBASED_SER=
VICE);
+    is_username =3D gss_oid_equal(input_name_type, GSS_C_NT_USER_NAME);
+
+    if (!is_hostnamed && !is_username)
 	return GSS_S_BAD_NAMETYPE;
=20
     name =3D malloc(input_name_buffer->length + 1);
@@ -63,21 +69,25 @@
=20
     /* find "domain" part of the name and uppercase it */
     p =3D strchr(name, '@');
-    if (p =3D=3D NULL)
+    if (p =3D=3D NULL) {
+        free(name);
 	return GSS_S_BAD_NAME;
+    }
     p[0] =3D '\0';
     p++;
     p2 =3D strchr(p, '.');
     if (p2 && p2[1] !=3D '\0') {
-	p =3D p2 + 1;
-	p2 =3D strchr(p, '.');
+	if (is_hostnamed) {
+	    p =3D p2 + 1;
+	    p2 =3D strchr(p, '.');
+	}
 	if (p2)
 	    *p2 =3D '\0';
     }
     strupr(p);
-   =20
+
     n =3D calloc(1, sizeof(*n));
-    if (name =3D=3D NULL) {
+    if (n =3D=3D NULL) {
 	free(name);
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/im=
port_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/import_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/import_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1999 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: import_sec_context.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_import_sec_context (
     OM_uint32 * minor_status,
     const gss_buffer_t interprocess_token,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/in=
dicate_mechs.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/indicate_mechs.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/indicate_mechs.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
-
-RCSID("$Id: indicate_mechs.c 19334 2006-12-14 12:17:34Z lha $");
+#include "ntlm.h"
=20
 OM_uint32 _gss_ntlm_indicate_mechs
 (OM_uint32 * minor_status,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/in=
it_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/init_sec_context.c	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/init_sec_context.c	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,50 +1,49 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
-
-RCSID("$Id: init_sec_context.c 22382 2007-12-30 12:13:17Z lha $");
+#include "ntlm.h"
=20
 static int
-from_file(const char *fn, const char *target_domain,=20
+from_file(const char *fn, const char *target_domain,
 	  char **username, struct ntlm_buf *key)
-{	 =20
+{
     char *str, buf[1024];
     FILE *f;
=20
     f =3D fopen(fn, "r");
     if (f =3D=3D NULL)
 	return ENOENT;
+    rk_cloexec_file(f);
=20
     while (fgets(buf, sizeof(buf), f) !=3D NULL) {
 	char *d, *u, *p;
@@ -74,7 +73,7 @@
 }
=20
 static int
-get_user_file(const ntlm_name target_name,=20
+get_user_file(const ntlm_name target_name,
 	      char **username, struct ntlm_buf *key)
 {
     const char *fn;
@@ -98,19 +97,18 @@
 static int
 get_user_ccache(const ntlm_name name, char **username, struct ntlm_buf *ke=
y)
 {
+    krb5_context context =3D NULL;
     krb5_principal client;
-    krb5_context context =3D NULL;
+    krb5_ccache id =3D NULL;
     krb5_error_code ret;
-    krb5_ccache id =3D NULL;
-    krb5_creds mcreds, creds;
+    char *confname;
+    krb5_data data;
=20
     *username =3D NULL;
+    krb5_data_zero(&data);
     key->length =3D 0;
     key->data =3D NULL;
=20
-    memset(&creds, 0, sizeof(creds));
-    memset(&mcreds, 0, sizeof(mcreds));
-
     ret =3D krb5_init_context(&context);
     if (ret)
 	return ret;
@@ -126,47 +124,36 @@
     ret =3D krb5_unparse_name_flags(context, client,
 				  KRB5_PRINCIPAL_UNPARSE_NO_REALM,
 				  username);
-    if (ret)
-	goto out;
-
-    ret =3D krb5_make_principal(context, &mcreds.server,
-			      krb5_principal_get_realm(context, client),
-			      "@ntlm-key", name->domain, NULL);
     krb5_free_principal(context, client);
     if (ret)
 	goto out;
=20
-    mcreds.session.keytype =3D ENCTYPE_ARCFOUR_HMAC_MD5;
-    ret =3D krb5_cc_retrieve_cred(context, id, KRB5_TC_MATCH_KEYTYPE,=20
-				&mcreds, &creds);
-    if (ret) {
-	char *s =3D krb5_get_error_message(context, ret);
-	krb5_free_error_string(context, s);
+    asprintf(&confname, "ntlm-key-%s", name->domain);
+    if (confname =3D=3D NULL) {
+	krb5_clear_error_message(context);
+	ret =3D ENOMEM;
 	goto out;
     }
=20
-    key->data =3D malloc(creds.session.keyvalue.length);
-    if (key->data =3D=3D NULL)
+    ret =3D krb5_cc_get_config(context, id, NULL,
+			     confname, &data);
+    if (ret)
 	goto out;
-    key->length =3D creds.session.keyvalue.length;
-    memcpy(key->data, creds.session.keyvalue.data, key->length);
=20
-    krb5_free_cred_contents(context, &creds);
+    key->data =3D malloc(data.length);
+    if (key->data =3D=3D NULL) {
+	ret =3D ENOMEM;
+	goto out;
+    }
+    key->length =3D data.length;
+    memcpy(key->data, data.data, data.length);
=20
-    return 0;
-
-out:
-    if (*username) {
-	free(*username);
-	*username =3D NULL;
-    }
-    krb5_free_cred_contents(context, &creds);
-    if (mcreds.server)
-	krb5_free_principal(context, mcreds.server);
+ out:
+    krb5_data_free(&data);
     if (id)
 	krb5_cc_close(context, id);
-    if (context)
-	krb5_free_context(context);
+
+    krb5_free_context(context);
=20
     return ret;
 }
@@ -177,11 +164,11 @@
 {
     ntlm_cred cred;
     int ret;
-=20
+
     cred =3D calloc(1, sizeof(*cred));
     if (cred =3D=3D NULL)
 	return ENOMEM;
-   =20
+
     ret =3D get_user_file(target_name, &cred->username, &cred->key);
     if (ret)
 	ret =3D get_user_ccache(target_name, &cred->username, &cred->key);
@@ -189,7 +176,7 @@
 	free(cred);
 	return ret;
     }
-   =20
+
     cred->domain =3D strdup(target_name->domain);
     *rcred =3D cred;
=20
@@ -199,7 +186,7 @@
 static int
 _gss_copy_cred(ntlm_cred from, ntlm_cred *to)
 {
-    *to =3D calloc(1, sizeof(*to));
+    *to =3D calloc(1, sizeof(**to));
     if (*to =3D=3D NULL)
 	return ENOMEM;
     (*to)->username =3D strdup(from->username);
@@ -226,7 +213,7 @@
     return 0;
 }
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_init_sec_context
            (OM_uint32 * minor_status,
             const gss_cred_id_t initiator_cred_handle,
@@ -260,7 +247,7 @@
 	struct ntlm_buf data;
 	uint32_t flags =3D 0;
 	int ret;
-=09
+
 	ctx =3D calloc(1, sizeof(*ctx));
 	if (ctx =3D=3D NULL) {
 	    *minor_status =3D EINVAL;
@@ -293,23 +280,23 @@
 	flags |=3D NTLM_NEG_KEYEX;
=20
 	memset(&type1, 0, sizeof(type1));
-=09
+
 	type1.flags =3D flags;
 	type1.domain =3D name->domain;
 	type1.hostname =3D NULL;
 	type1.os[0] =3D 0;
 	type1.os[1] =3D 0;
-=09
+
 	ret =3D heim_ntlm_encode_type1(&type1, &data);
 	if (ret) {
 	    _gss_ntlm_delete_sec_context(minor_status, context_handle, NULL);
 	    *minor_status =3D ret;
 	    return GSS_S_FAILURE;
 	}
-=09
+
 	output_token->value =3D data.data;
 	output_token->length =3D data.length;
-=09
+
 	return GSS_S_CONTINUE_NEEDED;
     } else {
 	krb5_error_code ret;
@@ -331,7 +318,7 @@
=20
 	ctx->flags =3D type2.flags;
=20
-	/* XXX check that type2.targetinfo matches `target_name=B4 */
+	/* XXX check that type2.targetinfo matches `target_name=C2=B4 */
 	/* XXX check verify targetinfo buffer */
=20
 	memset(&type3, 0, sizeof(type3));
@@ -352,21 +339,21 @@
 		unsigned char nonce[8];
=20
 		if (RAND_bytes(nonce, sizeof(nonce)) !=3D 1) {
-		    _gss_ntlm_delete_sec_context(minor_status,=20
+		    _gss_ntlm_delete_sec_context(minor_status,
 						 context_handle, NULL);
 		    *minor_status =3D EINVAL;
 		    return GSS_S_FAILURE;
 		}
=20
 		ret =3D heim_ntlm_calculate_ntlm2_sess(nonce,
-						     type2.challange,
+						     type2.challenge,
 						     ctx->client->key.data,
 						     &type3.lm,
 						     &type3.ntlm);
 	    } else {
-		ret =3D heim_ntlm_calculate_ntlm1(ctx->client->key.data,=20
+		ret =3D heim_ntlm_calculate_ntlm1(ctx->client->key.data,
 						ctx->client->key.length,
-						type2.challange,
+						type2.challenge,
 						&type3.ntlm);
=20
 	    }
@@ -376,7 +363,7 @@
 		return GSS_S_FAILURE;
 	    }
=20
-	    ret =3D heim_ntlm_build_ntlm1_master(ctx->client->key.data,=20
+	    ret =3D heim_ntlm_build_ntlm1_master(ctx->client->key.data,
 					       ctx->client->key.length,
 					       &sessionkey,
 					       &type3.sessionkey);
@@ -390,7 +377,7 @@
 		return GSS_S_FAILURE;
 	    }
=20
-	    ret =3D krb5_data_copy(&ctx->sessionkey,=20
+	    ret =3D krb5_data_copy(&ctx->sessionkey,
 				 sessionkey.data, sessionkey.length);
 	    free(sessionkey.data);
 	    if (ret) {
@@ -402,7 +389,7 @@
 		*minor_status =3D ret;
 		return GSS_S_FAILURE;
 	    }
-	    ctx->status |=3D STATUS_SESSIONKEY;=20
+	    ctx->status |=3D STATUS_SESSIONKEY;
=20
 	} else {
 	    struct ntlm_buf sessionkey;
@@ -410,17 +397,17 @@
 	    struct ntlm_targetinfo ti;
=20
 	    /* verify infotarget */
-	   =20
+
 	    ret =3D heim_ntlm_decode_targetinfo(&type2.targetinfo, 1, &ti);
 	    if(ret) {
-		_gss_ntlm_delete_sec_context(minor_status,=20
+		_gss_ntlm_delete_sec_context(minor_status,
 					     context_handle, NULL);
 		*minor_status =3D ret;
 		return GSS_S_FAILURE;
 	    }
=20
 	    if (ti.domainname && strcmp(ti.domainname, name->domain) !=3D 0) {
-		_gss_ntlm_delete_sec_context(minor_status,=20
+		_gss_ntlm_delete_sec_context(minor_status,
 					     context_handle, NULL);
 		*minor_status =3D EINVAL;
 		return GSS_S_FAILURE;
@@ -430,12 +417,12 @@
 					    ctx->client->key.length,
 					    ctx->client->username,
 					    name->domain,
-					    type2.challange,
+					    type2.challenge,
 					    &type2.targetinfo,
 					    ntlmv2,
 					    &type3.ntlm);
 	    if (ret) {
-		_gss_ntlm_delete_sec_context(minor_status,=20
+		_gss_ntlm_delete_sec_context(minor_status,
 					     context_handle, NULL);
 		*minor_status =3D ret;
 		return GSS_S_FAILURE;
@@ -446,21 +433,27 @@
 					       &type3.sessionkey);
 	    memset(ntlmv2, 0, sizeof(ntlmv2));
 	    if (ret) {
-		_gss_ntlm_delete_sec_context(minor_status,=20
+		_gss_ntlm_delete_sec_context(minor_status,
 					     context_handle, NULL);
 		*minor_status =3D ret;
 		return GSS_S_FAILURE;
 	    }
-	   =20
+
 	    ctx->flags |=3D NTLM_NEG_NTLM2_SESSION;
=20
-	    ret =3D krb5_data_copy(&ctx->sessionkey,=20
+	    ret =3D krb5_data_copy(&ctx->sessionkey,
 				 sessionkey.data, sessionkey.length);
 	    free(sessionkey.data);
+	    if (ret) {
+		_gss_ntlm_delete_sec_context(minor_status,
+					     context_handle, NULL);
+		*minor_status =3D ret;
+		return GSS_S_FAILURE;
+	    }
 	}
=20
 	if (ctx->flags & NTLM_NEG_NTLM2_SESSION) {
-	    ctx->status |=3D STATUS_SESSIONKEY;=20
+	    ctx->status |=3D STATUS_SESSIONKEY;
 	    _gss_ntlm_set_key(&ctx->u.v2.send, 0, (ctx->flags & NTLM_NEG_KEYEX),
 			      ctx->sessionkey.data,
 			      ctx->sessionkey.length);
@@ -468,15 +461,15 @@
 			      ctx->sessionkey.data,
 			      ctx->sessionkey.length);
 	} else {
-	    ctx->status |=3D STATUS_SESSIONKEY;=20
-	    RC4_set_key(&ctx->u.v1.crypto_recv.key,=20
+	    ctx->status |=3D STATUS_SESSIONKEY;
+	    RC4_set_key(&ctx->u.v1.crypto_recv.key,
 			ctx->sessionkey.length,
 			ctx->sessionkey.data);
-	    RC4_set_key(&ctx->u.v1.crypto_send.key,=20
+	    RC4_set_key(&ctx->u.v1.crypto_send.key,
 			ctx->sessionkey.length,
 			ctx->sessionkey.data);
 	}
-=09
+
=20
=20
 	ret =3D heim_ntlm_encode_type3(&type3, &data);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/in=
quire_context.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/inquire_context.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/inquire_context.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: inquire_context.c 21079 2007-06-13 00:25:25Z lha $");
-
-OM_uint32 _gss_ntlm_inquire_context (
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_context (
             OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             gss_name_t * src_name,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/in=
quire_cred_by_mech.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/inquire_cred_by_mech.c	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/inquire_cred_by_mech.c	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: inquire_cred_by_mech.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_inquire_cred_by_mech (
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_cred_by_mech (
             OM_uint32 * minor_status,
             const gss_cred_id_t cred_handle,
             const gss_OID mech_type,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/in=
quire_mechs_for_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/inquire_mechs_for_name.c	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/inquire_mechs_for_name.c	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: inquire_mechs_for_name.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_inquire_mechs_for_name (
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_mechs_for_name (
             OM_uint32 * minor_status,
             const gss_name_t input_name,
             gss_OID_set * mech_types
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/in=
quire_names_for_mech.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/inquire_names_for_mech.c	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/inquire_names_for_mech.c	Tue Apr =
17 11:51:51 2012 +0300
@@ -1,42 +1,40 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: inquire_names_for_mech.c 19334 2006-12-14 12:17:34Z lha $");
-
-
-OM_uint32 _gss_ntlm_inquire_names_for_mech (
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_names_for_mech (
             OM_uint32 * minor_status,
             const gss_OID mechanism,
             gss_OID_set * name_types
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/nt=
lm-private.h
--- a/head/crypto/heimdal/lib/gssapi/ntlm/ntlm-private.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/ntlm-private.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -7,7 +7,7 @@
 gssapi_mech_interface
 __gss_ntlm_initialize (void);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_accept_sec_context (
 	OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
@@ -21,7 +21,7 @@
 	OM_uint32 * /*time_rec*/,
 	gss_cred_id_t * delegated_cred_handle );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_acquire_cred (
 	OM_uint32 * /*min_stat*/,
 	const gss_name_t /*desired_name*/,
@@ -32,7 +32,7 @@
 	gss_OID_set * /*actual_mechs*/,
 	OM_uint32 * time_rec );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_add_cred (
 	 OM_uint32 */*minor_status*/,
 	const gss_cred_id_t /*input_cred_handle*/,
@@ -51,40 +51,45 @@
 	OM_uint32 */*minor_status*/,
 	ntlm_ctx */*ctx*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_canonicalize_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	const gss_OID /*mech_type*/,
 	gss_name_t * output_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_compare_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*name1*/,
 	const gss_name_t /*name2*/,
 	int * name_equal );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_context_time (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
 	OM_uint32 * time_rec );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_delete_sec_context (
 	OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
 	gss_buffer_t output_token );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_destroy_cred (
+	OM_uint32 */*minor_status*/,
+	gss_cred_id_t */*cred_handle*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_display_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_buffer_t /*output_name_buffer*/,
 	gss_OID * output_name_type );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_display_status (
 	OM_uint32 */*minor_status*/,
 	OM_uint32 /*status_value*/,
@@ -93,25 +98,25 @@
 	OM_uint32 */*message_context*/,
 	gss_buffer_t /*status_string*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_duplicate_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*src_name*/,
 	gss_name_t * dest_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_export_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_buffer_t exported_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_export_sec_context (
 	 OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
 	gss_buffer_t interprocess_token );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_get_mic (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -124,14 +129,14 @@
 	const ntlm_name /*target_name*/,
 	ntlm_cred */*rcred*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_import_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_buffer_t /*input_name_buffer*/,
 	const gss_OID /*input_name_type*/,
 	gss_name_t * output_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_import_sec_context (
 	 OM_uint32 * /*minor_status*/,
 	const gss_buffer_t /*interprocess_token*/,
@@ -142,7 +147,7 @@
 	OM_uint32 * /*minor_status*/,
 	gss_OID_set * mech_set );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_init_sec_context (
 	OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*initiator_cred_handle*/,
@@ -158,7 +163,7 @@
 	OM_uint32 * /*ret_flags*/,
 	OM_uint32 * time_rec );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_inquire_context (
 	 OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -170,7 +175,7 @@
 	int * /*locally_initiated*/,
 	int * open_context );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_inquire_cred (
 	OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
@@ -179,7 +184,7 @@
 	gss_cred_usage_t * /*cred_usage*/,
 	gss_OID_set * mechanisms );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_inquire_cred_by_mech (
 	 OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
@@ -189,30 +194,43 @@
 	OM_uint32 * /*acceptor_lifetime*/,
 	gss_cred_usage_t * cred_usage );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_inquire_mechs_for_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_OID_set * mech_types );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_inquire_names_for_mech (
 	 OM_uint32 * /*minor_status*/,
 	const gss_OID /*mechanism*/,
 	gss_OID_set * name_types );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_inquire_sec_context_by_oid (
+	OM_uint32 */*minor_status*/,
+	const gss_ctx_id_t /*context_handle*/,
+	const gss_OID /*desired_object*/,
+	gss_buffer_set_t */*data_set*/);
+
+void GSSAPI_CALLCONV
+_gss_ntlm_iter_creds_f (
+	OM_uint32 /*flags*/,
+	void *userctx ,
+	void (*/*cred_iter*/)(void *, gss_OID, gss_cred_id_t));
+
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_process_context_token (
 	 OM_uint32 */*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
 	const gss_buffer_t token_buffer );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_release_cred (
 	OM_uint32 * /*minor_status*/,
 	gss_cred_id_t * cred_handle );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_release_name (
 	OM_uint32 * /*minor_status*/,
 	gss_name_t * input_name );
@@ -225,7 +243,7 @@
 	unsigned char */*data*/,
 	size_t /*len*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_unwrap (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -234,7 +252,7 @@
 	int * /*conf_state*/,
 	gss_qop_t * qop_state );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_verify_mic (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -242,7 +260,7 @@
 	const gss_buffer_t /*token_buffer*/,
 	gss_qop_t * qop_state );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_wrap (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -252,7 +270,7 @@
 	int * /*conf_state*/,
 	gss_buffer_t output_message_buffer );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_ntlm_wrap_size_limit (
 	 OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/nt=
lm.h
--- a/head/crypto/heimdal/lib/gssapi/ntlm/ntlm.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/ntlm.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,44 +1,42 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: ntlm.h 22373 2007-12-28 18:36:06Z lha $ */
+/* $Id$ */
=20
 #ifndef NTLM_NTLM_H
 #define NTLM_NTLM_H
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -46,15 +44,20 @@
 #include <string.h>
 #include <errno.h>
=20
+#include <roken.h>
+
 #include <gssapi.h>
+#include <gssapi_ntlm.h>
 #include <gssapi_mech.h>
+#include <gssapi_oid.h>
=20
 #include <krb5.h>
-#include <roken.h>
+#include <kcm.h>
 #include <heim_threads.h>
=20
 #include <heimntlm.h>
=20
+#define HC_DEPRECATED_CRYPTO
 #include "crypto-headers.h"
=20
 typedef OM_uint32
@@ -108,6 +111,7 @@
     void *ictx;
     ntlm_cred client;
     OM_uint32 gssflags;
+    uint32_t kcmflags;
     uint32_t flags;
     uint32_t status;
 #define STATUS_OPEN 1
@@ -115,6 +119,8 @@
 #define STATUS_SESSIONKEY 4
     krb5_data sessionkey;
=20
+    gss_buffer_desc pac;
+
     union {
 	struct {
 	    struct {
@@ -133,7 +139,7 @@
     char *domain;
 } *ntlm_name;
=20
-#include <ntlm/ntlm-private.h>
+#include <ntlm-private.h>
=20
=20
 #endif /* NTLM_NTLM_H */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/pr=
ocess_context_token.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/process_context_token.c	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/process_context_token.c	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: process_context_token.c 19334 2006-12-14 12:17:34Z lha $");
-
-OM_uint32 _gss_ntlm_process_context_token (
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_process_context_token (
 	OM_uint32          *minor_status,
 	const gss_ctx_id_t context_handle,
 	const gss_buffer_t token_buffer
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/re=
lease_cred.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/release_cred.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/release_cred.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: release_cred.c 22163 2007-12-04 21:25:06Z lha $");
-
-OM_uint32 _gss_ntlm_release_cred
+OM_uint32 GSSAPI_CALLCONV _gss_ntlm_release_cred
            (OM_uint32 * minor_status,
             gss_cred_id_t * cred_handle
            )
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/ntlm/re=
lease_name.c
--- a/head/crypto/heimdal/lib/gssapi/ntlm/release_name.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/ntlm/release_name.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "ntlm/ntlm.h"
+#include "ntlm.h"
=20
-RCSID("$Id: release_name.c 22373 2007-12-28 18:36:06Z lha $");
-
-OM_uint32 _gss_ntlm_release_name
+OM_uint32 GSSAPI_CALLCONV
+_gss_ntlm_release_name
            (OM_uint32 * minor_status,
             gss_name_t * input_name
            )
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
accept_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/spnego/accept_sec_context.c	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/accept_sec_context.c	Tue Apr 17=
 11:51:51 2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * Portions Copyright (c) 2004 PADL Software Pty Ltd.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "spnego/spnego_locl.h"
-
-RCSID("$Id: accept_sec_context.c 21461 2007-07-10 14:01:13Z lha $");
-/* $FreeBSD$ */
+#include "spnego_locl.h"
=20
 static OM_uint32
 send_reject (OM_uint32 *minor_status,
@@ -54,7 +51,7 @@
     nt.u.negTokenResp.supportedMech =3D NULL;
     nt.u.negTokenResp.responseToken =3D NULL;
     nt.u.negTokenResp.mechListMIC   =3D NULL;
-   =20
+
     ASN1_MALLOC_ENCODE(NegotiationToken,
 		       output_token->value, output_token->length, &nt,
 		       &size, *minor_status);
@@ -77,14 +74,14 @@
=20
     gss_create_empty_oid_set(&junk, &oidset);
     gss_add_oid_set_member(&junk, mech, &oidset);
-   =20
+
     ret =3D gss_acquire_cred(&junk, target_name, GSS_C_INDEFINITE, oidset,
 			   GSS_C_ACCEPT, &cred, NULL, NULL);
     gss_release_oid_set(&junk, &oidset);
     if (ret !=3D GSS_S_COMPLETE)
 	return ret;
     gss_release_cred(&junk, &cred);
-   =20
+
     return GSS_S_COMPLETE;
 }
=20
@@ -93,13 +90,7 @@
 		      gss_buffer_t output_token)
 {
     NegotiationTokenWin nt;
-    char hostname[MAXHOSTNAMELEN + 1], *p;
-    gss_buffer_desc name_buf;
-    gss_OID name_type;
-    gss_name_t target_princ;
-    gss_name_t canon_princ;
-    OM_uint32 minor;
-    size_t buf_len;
+    size_t buf_len =3D 0;
     gss_buffer_desc data;
     OM_uint32 ret;
=20
@@ -117,62 +108,9 @@
 	return ret;
     }
=20
-    memset(&target_princ, 0, sizeof(target_princ));
-    if (gethostname(hostname, sizeof(hostname) - 2) !=3D 0) {
-	*minor_status =3D errno;
-	free_NegotiationTokenWin(&nt);
-	return GSS_S_FAILURE;
-    }
-    hostname[sizeof(hostname) - 1] =3D '\0';
-
-    /* Send the constructed SAM name for this host */
-    for (p =3D hostname; *p !=3D '\0' && *p !=3D '.'; p++) {
-	*p =3D toupper((unsigned char)*p);
-    }
-    *p++ =3D '$';
-    *p =3D '\0';
-
-    name_buf.length =3D strlen(hostname);
-    name_buf.value =3D hostname;
-
-    ret =3D gss_import_name(minor_status, &name_buf,
-			  GSS_C_NO_OID,
-			  &target_princ);
-    if (ret !=3D GSS_S_COMPLETE) {
-	free_NegotiationTokenWin(&nt);
-	return ret;
-    }
-
-    name_buf.length =3D 0;
-    name_buf.value =3D NULL;
-
-    /* Canonicalize the name using the preferred mechanism */
-    ret =3D gss_canonicalize_name(minor_status,
-				target_princ,
-				GSS_C_NO_OID,
-				&canon_princ);
-    if (ret !=3D GSS_S_COMPLETE) {
-	free_NegotiationTokenWin(&nt);
-	gss_release_name(&minor, &target_princ);
-	return ret;
-    }
-
-    ret =3D gss_display_name(minor_status, canon_princ,
-			   &name_buf, &name_type);
-    if (ret !=3D GSS_S_COMPLETE) {
-	free_NegotiationTokenWin(&nt);
-	gss_release_name(&minor, &canon_princ);
-	gss_release_name(&minor, &target_princ);
-	return ret;
-    }
-
-    gss_release_name(&minor, &canon_princ);
-    gss_release_name(&minor, &target_princ);
-
     ALLOC(nt.u.negTokenInit.negHints, 1);
     if (nt.u.negTokenInit.negHints =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
-	gss_release_buffer(&minor, &name_buf);
 	free_NegotiationTokenWin(&nt);
 	return GSS_S_FAILURE;
     }
@@ -180,23 +118,24 @@
     ALLOC(nt.u.negTokenInit.negHints->hintName, 1);
     if (nt.u.negTokenInit.negHints->hintName =3D=3D NULL) {
 	*minor_status =3D ENOMEM;
-	gss_release_buffer(&minor, &name_buf);
 	free_NegotiationTokenWin(&nt);
 	return GSS_S_FAILURE;
     }
=20
-    *(nt.u.negTokenInit.negHints->hintName) =3D name_buf.value;
-    name_buf.value =3D NULL;
+    *nt.u.negTokenInit.negHints->hintName =3D strdup("not_defined_in_RFC41=
78 at please_ignore");
     nt.u.negTokenInit.negHints->hintAddress =3D NULL;
=20
-    ASN1_MALLOC_ENCODE(NegotiationTokenWin,=20
+    ASN1_MALLOC_ENCODE(NegotiationTokenWin,
 		       data.value, data.length, &nt, &buf_len, ret);
     free_NegotiationTokenWin(&nt);
     if (ret) {
-	return ret;
+	*minor_status =3D ret;
+	return GSS_S_FAILURE;
     }
-    if (data.length !=3D buf_len)
+    if (data.length !=3D buf_len) {
 	abort();
+        UNREACHABLE(return GSS_S_FAILURE);
+    }
=20
     ret =3D gss_encapsulate_token(&data, GSS_SPNEGO_MECHANISM, output_toke=
n);
=20
@@ -308,7 +247,7 @@
=20
     } else
 	nt.u.negTokenResp.mechListMIC =3D NULL;
-=20
+
     ASN1_MALLOC_ENCODE(NegotiationToken,
 		       output_token->value, output_token->length,
 		       &nt, &size, ret);
@@ -379,7 +318,7 @@
     gss_OID_desc oid;
     gss_OID oidp;
     gss_OID_set mechs;
-    int i;
+    size_t i;
     OM_uint32 ret, junk;
=20
     ret =3D der_put_oid ((unsigned char *)mechbuf + sizeof(mechbuf) - 1,
@@ -431,11 +370,16 @@
=20
 	host =3D getenv("GSSAPI_SPNEGO_NAME");
 	if (host =3D=3D NULL || issuid()) {
+	    int rv;
 	    if (gethostname(hostname, sizeof(hostname)) !=3D 0) {
 		*minor_status =3D errno;
 		return GSS_S_FAILURE;
 	    }
-	    asprintf(&str, "host@%s", hostname);
+	    rv =3D asprintf(&str, "host@%s", hostname);
+	    if (rv < 0 || str =3D=3D NULL) {
+		*minor_status =3D ENOMEM;
+		return GSS_S_FAILURE;
+	    }
 	    host =3D str;
 	}
=20
@@ -469,20 +413,16 @@
 {
     OM_uint32 ret;
     int require_mic, verify_mic;
-    gss_buffer_desc buf;
-
-    buf.length =3D 0;
-    buf.value =3D NULL;
=20
     ret =3D _gss_spnego_require_mechlist_mic(minor_status, ctx, &require_m=
ic);
     if (ret)
 	return ret;
-   =20
+
     ctx->require_mic =3D require_mic;
=20
     if (mic !=3D NULL)
 	require_mic =3D 1;
-   =20
+
     if (ctx->open && require_mic) {
 	if (mech_input_token =3D=3D GSS_C_NO_BUFFER) { /* Even/One */
 	    verify_mic =3D 1;
@@ -494,44 +434,39 @@
 	    verify_mic =3D 0;
 	    *get_mic =3D 1;
 	}
-=09
-	if (verify_mic || get_mic) {
+
+	if (verify_mic || *get_mic) {
 	    int eret;
-	    size_t buf_len;
-	   =20
-	    ASN1_MALLOC_ENCODE(MechTypeList,=20
+	    size_t buf_len =3D 0;
+
+	    ASN1_MALLOC_ENCODE(MechTypeList,
 			       mech_buf->value, mech_buf->length,
 			       &ctx->initiator_mech_types, &buf_len, eret);
 	    if (eret) {
 		*minor_status =3D eret;
 		return GSS_S_FAILURE;
 	    }
-	    if (buf.length !=3D buf_len)
-		abort();
+	    heim_assert(mech_buf->length =3D=3D buf_len, "Internal ASN.1 error");
+	    UNREACHABLE(return GSS_S_FAILURE);
 	}
-=09
+
 	if (verify_mic) {
 	    ret =3D verify_mechlist_mic(minor_status, ctx, mech_buf, mic);
 	    if (ret) {
-		if (get_mic)
+		if (*get_mic)
 		    send_reject (minor_status, output_token);
-		if (buf.value)
-		    free(buf.value);
 		return ret;
 	    }
 	    ctx->verified_mic =3D 1;
 	}
-	if (buf.value)
-	    free(buf.value);
+    } else
+	*get_mic =3D 0;
=20
-    } else
-	*get_mic =3D verify_mic =3D 0;
-   =20
     return GSS_S_COMPLETE;
 }
=20
=20
-static OM_uint32
+static OM_uint32 GSSAPI_CALLCONV
 acceptor_start
 	   (OM_uint32 * minor_status,
 	    gss_ctx_id_t * context_handle,
@@ -546,18 +481,16 @@
 	    gss_cred_id_t *delegated_cred_handle
 	   )
 {
-    OM_uint32 ret, junk, minor;
+    OM_uint32 ret, junk;
     NegotiationToken nt;
     size_t nt_len;
     NegTokenInit *ni;
-    int i;
     gss_buffer_desc data;
     gss_buffer_t mech_input_token =3D GSS_C_NO_BUFFER;
     gss_buffer_desc mech_output_token;
     gss_buffer_desc mech_buf;
     gss_OID preferred_mech_type =3D GSS_C_NO_OID;
     gssspnego_ctx ctx;
-    gssspnego_cred acceptor_cred =3D (gssspnego_cred)acceptor_cred_handle;
     int get_mic =3D 0;
     int first_ok =3D 0;
=20
@@ -567,7 +500,7 @@
=20
     if (input_token_buffer->length =3D=3D 0)
 	return send_supported_mechs (minor_status, output_token);
-=09
+
     ret =3D _gss_spnego_alloc_sec_context(minor_status, context_handle);
     if (ret !=3D GSS_S_COMPLETE)
 	return ret;
@@ -615,38 +548,28 @@
     /*
      * First we try the opportunistic token if we have support for it,
      * don't try to verify we have credential for the token,
-     * gss_accept_sec_context will (hopefully) tell us that.
-     * If that failes,=20
+     * gss_accept_sec_context() will (hopefully) tell us that.
+     * If that failes,
      */
=20
     ret =3D select_mech(minor_status,
-		      &ni->mechTypes.val[0],=20
+		      &ni->mechTypes.val[0],
 		      0,
 		      &preferred_mech_type);
=20
     if (ret =3D=3D 0 && ni->mechToken !=3D NULL) {
-	gss_cred_id_t mech_delegated_cred =3D GSS_C_NO_CREDENTIAL;
-	gss_cred_id_t mech_cred;
 	gss_buffer_desc ibuf;
=20
 	ibuf.length =3D ni->mechToken->length;
 	ibuf.value =3D ni->mechToken->data;
 	mech_input_token =3D &ibuf;
=20
-	if (acceptor_cred !=3D NULL)
-	    mech_cred =3D acceptor_cred->negotiated_cred_id;
-	else
-	    mech_cred =3D GSS_C_NO_CREDENTIAL;
-=09
 	if (ctx->mech_src_name !=3D GSS_C_NO_NAME)
-	    gss_release_name(&minor, &ctx->mech_src_name);
-=09
-	if (ctx->delegated_cred_id !=3D GSS_C_NO_CREDENTIAL)
-	    _gss_spnego_release_cred(&minor, &ctx->delegated_cred_id);
-=09
-	ret =3D gss_accept_sec_context(&minor,
+	    gss_release_name(&junk, &ctx->mech_src_name);
+
+	ret =3D gss_accept_sec_context(minor_status,
 				     &ctx->negotiated_ctx_id,
-				     mech_cred,
+				     acceptor_cred_handle,
 				     mech_input_token,
 				     input_chan_bindings,
 				     &ctx->mech_src_name,
@@ -654,20 +577,13 @@
 				     &mech_output_token,
 				     &ctx->mech_flags,
 				     &ctx->mech_time_rec,
-				     &mech_delegated_cred);
+				     delegated_cred_handle);
+
 	if (ret =3D=3D GSS_S_COMPLETE || ret =3D=3D GSS_S_CONTINUE_NEEDED) {
 	    ctx->preferred_mech_type =3D preferred_mech_type;
-	    ctx->negotiated_mech_type =3D preferred_mech_type;
 	    if (ret =3D=3D GSS_S_COMPLETE)
 		ctx->open =3D 1;
=20
-	    if (mech_delegated_cred && delegated_cred_handle)
-		ret =3D _gss_spnego_alloc_cred(minor_status,
-					     mech_delegated_cred,
-					     delegated_cred_handle);
-	    else
-		gss_release_cred(&junk, &mech_delegated_cred);
-
 	    ret =3D acceptor_complete(minor_status,
 				    ctx,
 				    &get_mic,
@@ -680,6 +596,8 @@
 		goto out;
=20
 	    first_ok =3D 1;
+	} else {
+	    gss_mg_collect_error(preferred_mech_type, ret, *minor_status);
 	}
     }
=20
@@ -687,12 +605,15 @@
      * If opportunistic token failed, lets try the other mechs.
      */
=20
-    if (!first_ok) {
+    if (!first_ok && ni->mechToken !=3D NULL) {
+	size_t j;
+
+	preferred_mech_type =3D GSS_C_NO_OID;
=20
 	/* Call glue layer to find first mech we support */
-	for (i =3D 1; i < ni->mechTypes.len; ++i) {
+	for (j =3D 1; j < ni->mechTypes.len; ++j) {
 	    ret =3D select_mech(minor_status,
-			      &ni->mechTypes.val[i],
+			      &ni->mechTypes.val[j],
 			      1,
 			      &preferred_mech_type);
 	    if (ret =3D=3D 0)
@@ -701,11 +622,10 @@
 	if (preferred_mech_type =3D=3D GSS_C_NO_OID) {
 	    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	    free_NegotiationToken(&nt);
-	    return GSS_S_BAD_MECH;
+	    return ret;
 	}
=20
 	ctx->preferred_mech_type =3D preferred_mech_type;
-	ctx->negotiated_mech_type =3D preferred_mech_type;
     }
=20
     /*
@@ -720,10 +640,10 @@
 		       output_token);
     if (ret)
 	goto out;
-   =20
+
 out:
     if (mech_output_token.value !=3D NULL)
-	gss_release_buffer(&minor, &mech_output_token);
+	gss_release_buffer(&junk, &mech_output_token);
     if (mech_buf.value !=3D NULL) {
 	free(mech_buf.value);
 	mech_buf.value =3D NULL;
@@ -742,12 +662,8 @@
 		*src_name =3D (gss_name_t)name;
 	    }
 	}
-        if (delegated_cred_handle !=3D NULL) {
-	    *delegated_cred_handle =3D ctx->delegated_cred_id;
-	    ctx->delegated_cred_id =3D GSS_C_NO_CREDENTIAL;
-	}
     }
-   =20
+
     if (mech_type !=3D NULL)
 	*mech_type =3D ctx->negotiated_mech_type;
     if (ret_flags !=3D NULL)
@@ -760,14 +676,14 @@
  	return ret;
     }
=20
-    _gss_spnego_internal_delete_sec_context(&minor, context_handle,
+    _gss_spnego_internal_delete_sec_context(&junk, context_handle,
 					    GSS_C_NO_BUFFER);
-   =20
+
     return ret;
 }
=20
=20
-static OM_uint32
+static OM_uint32 GSSAPI_CALLCONV
 acceptor_continue
 	   (OM_uint32 * minor_status,
 	    gss_ctx_id_t * context_handle,
@@ -791,7 +707,6 @@
     gss_buffer_t mech_output_token =3D GSS_C_NO_BUFFER;
     gss_buffer_desc mech_buf;
     gssspnego_ctx ctx;
-    gssspnego_cred acceptor_cred =3D (gssspnego_cred)acceptor_cred_handle;
=20
     mech_buf.value =3D NULL;
=20
@@ -802,7 +717,7 @@
      * context token (negTokenInit).
      */
=20
-    ret =3D decode_NegotiationToken(input_token_buffer->value,=20
+    ret =3D decode_NegotiationToken(input_token_buffer->value,
 				  input_token_buffer->length,
 				  &nt, &nt_len);
     if (ret) {
@@ -837,31 +752,13 @@
 	}
=20
 	if (mech_input_token !=3D GSS_C_NO_BUFFER) {
-	    gss_cred_id_t mech_cred;
-	    gss_cred_id_t mech_delegated_cred;
-	    gss_cred_id_t *mech_delegated_cred_p;
-
-	    if (acceptor_cred !=3D NULL)
-		mech_cred =3D acceptor_cred->negotiated_cred_id;
-	    else
-		mech_cred =3D GSS_C_NO_CREDENTIAL;
-
-	    if (delegated_cred_handle !=3D NULL) {
-		mech_delegated_cred =3D GSS_C_NO_CREDENTIAL;
-		mech_delegated_cred_p =3D &mech_delegated_cred;
-	    } else {
-		mech_delegated_cred_p =3D NULL;
-	    }
=20
 	    if (ctx->mech_src_name !=3D GSS_C_NO_NAME)
 		gss_release_name(&minor, &ctx->mech_src_name);
=20
-	    if (ctx->delegated_cred_id !=3D GSS_C_NO_CREDENTIAL)
-		_gss_spnego_release_cred(&minor, &ctx->delegated_cred_id);
-
 	    ret =3D gss_accept_sec_context(&minor,
 					 &ctx->negotiated_ctx_id,
-					 mech_cred,
+					 acceptor_cred_handle,
 					 mech_input_token,
 					 input_chan_bindings,
 					 &ctx->mech_src_name,
@@ -869,20 +766,14 @@
 					 &obuf,
 					 &ctx->mech_flags,
 					 &ctx->mech_time_rec,
-					 mech_delegated_cred_p);
+					 delegated_cred_handle);
+
 	    if (ret =3D=3D GSS_S_COMPLETE || ret =3D=3D GSS_S_CONTINUE_NEEDED) {
-		if (mech_delegated_cred_p !=3D NULL &&
-		    mech_delegated_cred !=3D GSS_C_NO_CREDENTIAL) {
-		    ret2 =3D _gss_spnego_alloc_cred(minor_status,
-						  mech_delegated_cred,
-						  &ctx->delegated_cred_id);
-		    if (ret2 !=3D GSS_S_COMPLETE)
-			ret =3D ret2;
-		}
 		mech_output_token =3D &obuf;
 	    }
 	    if (ret !=3D GSS_S_COMPLETE && ret !=3D GSS_S_CONTINUE_NEEDED) {
 		free_NegotiationToken(&nt);
+		gss_mg_collect_error(ctx->negotiated_mech_type, ret, minor);
 		send_reject (minor_status, output_token);
 		HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 		return ret;
@@ -892,7 +783,7 @@
 	} else
 	    ret =3D GSS_S_COMPLETE;
=20
-	ret2 =3D _gss_spnego_require_mechlist_mic(minor_status,=20
+	ret2 =3D _gss_spnego_require_mechlist_mic(minor_status,
 						ctx,
 						&require_mic);
 	if (ret2)
@@ -959,10 +850,6 @@
 		*src_name =3D (gss_name_t)name;
 	    }
 	}
-        if (delegated_cred_handle !=3D NULL) {
-	    *delegated_cred_handle =3D ctx->delegated_cred_id;
-	    ctx->delegated_cred_id =3D GSS_C_NO_CREDENTIAL;
-	}
     }
=20
     if (mech_type !=3D NULL)
@@ -983,7 +870,7 @@
     return ret;
 }
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_accept_sec_context
 	   (OM_uint32 * minor_status,
 	    gss_ctx_id_t * context_handle,
@@ -1017,11 +904,11 @@
 	*delegated_cred_handle =3D GSS_C_NO_CREDENTIAL;
=20
=20
-    if (*context_handle =3D=3D GSS_C_NO_CONTEXT)=20
+    if (*context_handle =3D=3D GSS_C_NO_CONTEXT)
 	func =3D acceptor_start;
     else
 	func =3D acceptor_continue;
-   =20
+
=20
     return (*func)(minor_status, context_handle, acceptor_cred_handle,
 		   input_token_buffer, input_chan_bindings,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
compat.c
--- a/head/crypto/heimdal/lib/gssapi/spnego/compat.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/compat.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -30,9 +30,7 @@
  * SUCH DAMAGE.
  */
=20
-#include "spnego/spnego_locl.h"
-
-RCSID("$Id: compat.c 21866 2007-08-08 11:31:29Z lha $");
+#include "spnego_locl.h"
=20
 /*
  * Apparently Microsoft got the OID wrong, and used
@@ -43,16 +41,17 @@
  * Kerberos mechanism.
  */
 gss_OID_desc _gss_spnego_mskrb_mechanism_oid_desc =3D
-	{9, (void *)"\x2a\x86\x48\x82\xf7\x12\x01\x02\x02"};
+    {9, rk_UNCONST("\x2a\x86\x48\x82\xf7\x12\x01\x02\x02")};
=20
 gss_OID_desc _gss_spnego_krb5_mechanism_oid_desc =3D
-	{9, (void *)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"};
+    {9, rk_UNCONST("\x2a\x86\x48\x86\xf7\x12\x01\x02\x02")};
=20
 /*
  * Allocate a SPNEGO context handle
  */
-OM_uint32 _gss_spnego_alloc_sec_context (OM_uint32 * minor_status,
-					 gss_ctx_id_t *context_handle)
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_alloc_sec_context (OM_uint32 * minor_status,
+			       gss_ctx_id_t *context_handle)
 {
     gssspnego_ctx ctx;
=20
@@ -76,7 +75,6 @@
     ctx->mech_flags =3D 0;
     ctx->mech_time_rec =3D 0;
     ctx->mech_src_name =3D GSS_C_NO_NAME;
-    ctx->delegated_cred_id =3D GSS_C_NO_CREDENTIAL;
=20
     ctx->open =3D 0;
     ctx->local =3D 0;
@@ -94,7 +92,7 @@
  * Free a SPNEGO context handle. The caller must have acquired
  * the lock before this is called.
  */
-OM_uint32 _gss_spnego_internal_delete_sec_context
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_internal_delete_sec_context
            (OM_uint32 *minor_status,
             gss_ctx_id_t *context_handle,
             gss_buffer_t output_token
@@ -124,8 +122,6 @@
     if (ctx->initiator_mech_types.val !=3D NULL)
 	free_MechTypeList(&ctx->initiator_mech_types);
=20
-    _gss_spnego_release_cred(&minor, &ctx->delegated_cred_id);
-
     gss_release_oid(&minor, &ctx->preferred_mech_type);
     ctx->negotiated_mech_type =3D GSS_C_NO_OID;
=20
@@ -145,7 +141,6 @@
     HEIMDAL_MUTEX_destroy(&ctx->ctx_id_mutex);
=20
     free(ctx);
-    *context_handle =3D NULL;
=20
     return ret;
 }
@@ -156,7 +151,7 @@
  * a non-preferred mechanism was negotiated
  */
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_require_mechlist_mic(OM_uint32 *minor_status,
 				 gssspnego_ctx ctx,
 				 int *require_mic)
@@ -234,26 +229,26 @@
 }
=20
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_indicate_mechtypelist (OM_uint32 *minor_status,
 				   gss_name_t target_name,
 				   OM_uint32 (*func)(gss_name_t, gss_OID),
 				   int includeMSCompatOID,
-				   const gssspnego_cred cred_handle,
+				   const gss_cred_id_t cred_handle,
 				   MechTypeList *mechtypelist,
 				   gss_OID *preferred_mech)
 {
     gss_OID_set supported_mechs =3D GSS_C_NO_OID_SET;
     gss_OID first_mech =3D GSS_C_NO_OID;
     OM_uint32 ret;
-    int i;
+    size_t i;
=20
     mechtypelist->len =3D 0;
     mechtypelist->val =3D NULL;
=20
-    if (cred_handle !=3D NULL) {
+    if (cred_handle) {
 	ret =3D gss_inquire_cred(minor_status,
-			       cred_handle->negotiated_cred_id,
+			       cred_handle,
 			       NULL,
 			       NULL,
 			       NULL,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
context_stubs.c
--- a/head/crypto/heimdal/lib/gssapi/spnego/context_stubs.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/context_stubs.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -30,16 +30,14 @@
  * SUCH DAMAGE.
  */
=20
-#include "spnego/spnego_locl.h"
-
-RCSID("$Id: context_stubs.c 21035 2007-06-09 15:32:47Z lha $");
+#include "spnego_locl.h"
=20
 static OM_uint32
 spnego_supported_mechs(OM_uint32 *minor_status, gss_OID_set *mechs)
 {
     OM_uint32 ret, junk;
     gss_OID_set m;
-    int i;
+    size_t i;
=20
     ret =3D gss_indicate_mechs(minor_status, &m);
     if (ret !=3D GSS_S_COMPLETE)
@@ -62,12 +60,13 @@
 	    return ret;
 	}
     }
+    gss_release_oid_set(&junk, &m);
     return ret;
 }
=20
=20
=20
-OM_uint32 _gss_spnego_process_context_token
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_process_context_token
            (OM_uint32 *minor_status,
             const gss_ctx_id_t context_handle,
             const gss_buffer_t token_buffer
@@ -100,7 +99,7 @@
 					   GSS_C_NO_BUFFER);
 }
=20
-OM_uint32 _gss_spnego_delete_sec_context
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_delete_sec_context
            (OM_uint32 *minor_status,
             gss_ctx_id_t *context_handle,
             gss_buffer_t output_token
@@ -120,7 +119,7 @@
 						   output_token);
 }
=20
-OM_uint32 _gss_spnego_context_time
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_context_time
            (OM_uint32 *minor_status,
             const gss_ctx_id_t context_handle,
             OM_uint32 *time_rec
@@ -144,7 +143,7 @@
 			    time_rec);
 }
=20
-OM_uint32 _gss_spnego_get_mic
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_get_mic
            (OM_uint32 *minor_status,
             const gss_ctx_id_t context_handle,
             gss_qop_t qop_req,
@@ -170,7 +169,7 @@
 		       qop_req, message_buffer, message_token);
 }
=20
-OM_uint32 _gss_spnego_verify_mic
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_verify_mic
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             const gss_buffer_t message_buffer,
@@ -199,7 +198,7 @@
 			  qop_state);
 }
=20
-OM_uint32 _gss_spnego_wrap
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             int conf_req_flag,
@@ -232,7 +231,7 @@
 		    output_message_buffer);
 }
=20
-OM_uint32 _gss_spnego_unwrap
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_unwrap
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             const gss_buffer_t input_message_buffer,
@@ -263,19 +262,7 @@
 		      qop_state);
 }
=20
-OM_uint32 _gss_spnego_display_status
-           (OM_uint32 * minor_status,
-            OM_uint32 status_value,
-            int status_type,
-            const gss_OID mech_type,
-            OM_uint32 * message_context,
-            gss_buffer_t status_string
-           )
-{
-    return GSS_S_FAILURE;
-}
-
-OM_uint32 _gss_spnego_compare_name
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_compare_name
            (OM_uint32 *minor_status,
             const gss_name_t name1,
             const gss_name_t name2,
@@ -299,7 +286,7 @@
     return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gss_spnego_display_name
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_display_name
            (OM_uint32 * minor_status,
             const gss_name_t input_name,
             gss_buffer_t output_name_buffer,
@@ -317,7 +304,7 @@
 			    output_name_buffer, output_name_type);
 }
=20
-OM_uint32 _gss_spnego_import_name
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_name
            (OM_uint32 * minor_status,
             const gss_buffer_t name_buffer,
             const gss_OID name_type,
@@ -334,13 +321,13 @@
 	*minor_status =3D ENOMEM;
 	return GSS_S_FAILURE;
     }
-   =20
+
     maj_stat =3D _gss_copy_oid(minor_status, name_type, &name->type);
     if (maj_stat) {
 	free(name);
 	return GSS_S_FAILURE;
     }
-   =20
+
     maj_stat =3D _gss_copy_buffer(minor_status, name_buffer, &name->value);
     if (maj_stat) {
 	gss_name_t rname =3D (gss_name_t)name;
@@ -353,7 +340,7 @@
     return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gss_spnego_export_name
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_name
            (OM_uint32  * minor_status,
             const gss_name_t input_name,
             gss_buffer_t exported_name
@@ -372,7 +359,7 @@
     return gss_export_name(minor_status, name->mech, exported_name);
 }
=20
-OM_uint32 _gss_spnego_release_name
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_release_name
            (OM_uint32 * minor_status,
             gss_name_t * input_name
            )
@@ -393,7 +380,7 @@
     return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gss_spnego_inquire_context (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_context (
             OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             gss_name_t * src_name,
@@ -406,31 +393,61 @@
            )
 {
     gssspnego_ctx ctx;
+    OM_uint32 maj_stat, junk;
+    gss_name_t src_mn, targ_mn;
=20
     *minor_status =3D 0;
=20
-    if (context_handle =3D=3D GSS_C_NO_CONTEXT) {
+    if (context_handle =3D=3D GSS_C_NO_CONTEXT)
 	return GSS_S_NO_CONTEXT;
-    }
=20
     ctx =3D (gssspnego_ctx)context_handle;
=20
-    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
+    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT)
 	return GSS_S_NO_CONTEXT;
-    }
=20
-    return gss_inquire_context(minor_status,
-			       ctx->negotiated_ctx_id,
-			       src_name,
-			       targ_name,
-			       lifetime_rec,
-			       mech_type,
-			       ctx_flags,
-			       locally_initiated,
-			       open_context);
+    maj_stat =3D gss_inquire_context(minor_status,
+				   ctx->negotiated_ctx_id,
+				   &src_mn,
+				   &targ_mn,
+				   lifetime_rec,
+				   mech_type,
+				   ctx_flags,
+				   locally_initiated,
+				   open_context);
+    if (maj_stat !=3D GSS_S_COMPLETE)
+	return maj_stat;
+
+    if (src_name) {
+	spnego_name name =3D calloc(1, sizeof(*name));
+	if (name =3D=3D NULL)
+	    goto enomem;
+	name->mech =3D src_mn;
+	*src_name =3D (gss_name_t)name;
+    } else
+	gss_release_name(&junk, &src_mn);
+
+    if (targ_name) {
+	spnego_name name =3D calloc(1, sizeof(*name));
+	if (name =3D=3D NULL) {
+	    gss_release_name(minor_status, src_name);
+	    goto enomem;
+	}
+	name->mech =3D targ_mn;
+	*targ_name =3D (gss_name_t)name;
+    } else
+	gss_release_name(&junk, &targ_mn);
+
+    return GSS_S_COMPLETE;
+
+enomem:
+    gss_release_name(&junk, &targ_mn);
+    gss_release_name(&junk, &src_mn);
+    *minor_status =3D ENOMEM;
+    return GSS_S_FAILURE;
 }
=20
-OM_uint32 _gss_spnego_wrap_size_limit (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_wrap_size_limit (
             OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             int conf_req_flag,
@@ -461,7 +478,7 @@
 			       max_input_size);
 }
=20
-OM_uint32 _gss_spnego_export_sec_context (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_export_sec_context (
             OM_uint32 * minor_status,
             gss_ctx_id_t * context_handle,
             gss_buffer_t interprocess_token
@@ -504,7 +521,7 @@
     return ret;
 }
=20
-OM_uint32 _gss_spnego_import_sec_context (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_import_sec_context (
             OM_uint32 * minor_status,
             const gss_buffer_t interprocess_token,
             gss_ctx_id_t *context_handle
@@ -540,7 +557,7 @@
     return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gss_spnego_inquire_names_for_mech (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_names_for_mech (
             OM_uint32 * minor_status,
             const gss_OID mechanism,
             gss_OID_set * name_types
@@ -548,7 +565,7 @@
 {
     gss_OID_set mechs, names, n;
     OM_uint32 ret, junk;
-    int i, j;
+    size_t i, j;
=20
     *name_types =3D NULL;
=20
@@ -580,10 +597,10 @@
=20
     gss_release_oid_set(&junk, &mechs);
=20
-    return GSS_S_COMPLETE;
+    return ret;
 }
=20
-OM_uint32 _gss_spnego_inquire_mechs_for_name (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_mechs_for_name (
             OM_uint32 * minor_status,
             const gss_name_t input_name,
             gss_OID_set * mech_types
@@ -604,7 +621,7 @@
     return ret;
 }
=20
-OM_uint32 _gss_spnego_canonicalize_name (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_canonicalize_name (
             OM_uint32 * minor_status,
             const gss_name_t input_name,
             const gss_OID mech_type,
@@ -615,7 +632,7 @@
     return gss_duplicate_name(minor_status, input_name, output_name);
 }
=20
-OM_uint32 _gss_spnego_duplicate_name (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_duplicate_name (
             OM_uint32 * minor_status,
             const gss_name_t src_name,
             gss_name_t * dest_name
@@ -624,207 +641,74 @@
     return gss_duplicate_name(minor_status, src_name, dest_name);
 }
=20
-OM_uint32 _gss_spnego_sign
-           (OM_uint32 * minor_status,
-            gss_ctx_id_t context_handle,
-            int qop_req,
-            gss_buffer_t message_buffer,
-            gss_buffer_t message_token
-           )
+#if 0
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_wrap_iov(OM_uint32 * minor_status,
+		     gss_ctx_id_t  context_handle,
+		     int conf_req_flag,
+		     gss_qop_t qop_req,
+		     int * conf_state,
+		     gss_iov_buffer_desc *iov,
+		     int iov_count)
 {
-    gssspnego_ctx ctx;
+    gssspnego_ctx ctx =3D (gssspnego_ctx)context_handle;
=20
     *minor_status =3D 0;
=20
-    if (context_handle =3D=3D GSS_C_NO_CONTEXT) {
+    if (ctx =3D=3D NULL || ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT)
 	return GSS_S_NO_CONTEXT;
-    }
=20
-    ctx =3D (gssspnego_ctx)context_handle;
-
-    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    return gss_sign(minor_status,
-		    ctx->negotiated_ctx_id,
-		    qop_req,
-		    message_buffer,
-		    message_token);
+    return gss_wrap_iov(minor_status, ctx->negotiated_ctx_id,
+			conf_req_flag, qop_req, conf_state,
+			iov, iov_count);
 }
=20
-OM_uint32 _gss_spnego_verify
-           (OM_uint32 * minor_status,
-            gss_ctx_id_t context_handle,
-            gss_buffer_t message_buffer,
-            gss_buffer_t token_buffer,
-            int * qop_state
-           )
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_unwrap_iov(OM_uint32 *minor_status,
+		       gss_ctx_id_t context_handle,
+		       int *conf_state,
+		       gss_qop_t *qop_state,
+		       gss_iov_buffer_desc *iov,
+		       int iov_count)
 {
-    gssspnego_ctx ctx;
+    gssspnego_ctx ctx =3D (gssspnego_ctx)context_handle;
=20
     *minor_status =3D 0;
=20
-    if (context_handle =3D=3D GSS_C_NO_CONTEXT) {
+    if (ctx =3D=3D NULL || ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT)
 	return GSS_S_NO_CONTEXT;
-    }
=20
-    ctx =3D (gssspnego_ctx)context_handle;
-
-    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    return gss_verify(minor_status,
-		      ctx->negotiated_ctx_id,
-		      message_buffer,
-		      token_buffer,
-		      qop_state);
+    return gss_unwrap_iov(minor_status,
+			  ctx->negotiated_ctx_id,
+			  conf_state, qop_state,
+			  iov, iov_count);
 }
=20
-OM_uint32 _gss_spnego_seal
-           (OM_uint32 * minor_status,
-            gss_ctx_id_t context_handle,
-            int conf_req_flag,
-            int qop_req,
-            gss_buffer_t input_message_buffer,
-            int * conf_state,
-            gss_buffer_t output_message_buffer
-           )
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_wrap_iov_length(OM_uint32 * minor_status,
+			    gss_ctx_id_t context_handle,
+			    int conf_req_flag,
+			    gss_qop_t qop_req,
+			    int *conf_state,
+			    gss_iov_buffer_desc *iov,
+			    int iov_count)
 {
-    gssspnego_ctx ctx;
+    gssspnego_ctx ctx =3D (gssspnego_ctx)context_handle;
=20
     *minor_status =3D 0;
=20
-    if (context_handle =3D=3D GSS_C_NO_CONTEXT) {
+    if (ctx =3D=3D NULL || ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT)
 	return GSS_S_NO_CONTEXT;
-    }
=20
-    ctx =3D (gssspnego_ctx)context_handle;
-
-    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    return gss_seal(minor_status,
-		    ctx->negotiated_ctx_id,
-		    conf_req_flag,
-		    qop_req,
-		    input_message_buffer,
-		    conf_state,
-		    output_message_buffer);
+    return gss_wrap_iov_length(minor_status, ctx->negotiated_ctx_id,
+			       conf_req_flag, qop_req, conf_state,
+			       iov, iov_count);
 }
=20
-OM_uint32 _gss_spnego_unseal
-           (OM_uint32 * minor_status,
-            gss_ctx_id_t context_handle,
-            gss_buffer_t input_message_buffer,
-            gss_buffer_t output_message_buffer,
-            int * conf_state,
-            int * qop_state
-           )
-{
-    gssspnego_ctx ctx;
-
-    *minor_status =3D 0;
-
-    if (context_handle =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    ctx =3D (gssspnego_ctx)context_handle;
-
-    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    return gss_unseal(minor_status,
-		      ctx->negotiated_ctx_id,
-		      input_message_buffer,
-		      output_message_buffer,
-		      conf_state,
-		      qop_state);
-}
+#endif
=20
 #if 0
-OM_uint32 _gss_spnego_unwrap_ex
-           (OM_uint32 * minor_status,
-            const gss_ctx_id_t context_handle,
-	    const gss_buffer_t token_header_buffer,
-	    const gss_buffer_t associated_data_buffer,
-	    const gss_buffer_t input_message_buffer,
-	    gss_buffer_t output_message_buffer,
-	    int * conf_state,
-	    gss_qop_t * qop_state)
-{
-    gssspnego_ctx ctx;
-
-    *minor_status =3D 0;
-
-    if (context_handle =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    ctx =3D (gssspnego_ctx)context_handle;
-
-    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    return gss_unwrap_ex(minor_status,
-			 ctx->negotiated_ctx_id,
-			 token_header_buffer,
-			 associated_data_buffer,
-			 input_message_buffer,
-			 output_message_buffer,
-			 conf_state,
-			 qop_state);
-}
-
-OM_uint32 _gss_spnego_wrap_ex
-           (OM_uint32 * minor_status,
-            const gss_ctx_id_t context_handle,
-            int conf_req_flag,
-            gss_qop_t qop_req,
-            const gss_buffer_t associated_data_buffer,
-            const gss_buffer_t input_message_buffer,
-            int * conf_state,
-            gss_buffer_t output_token_buffer,
-            gss_buffer_t output_message_buffer
-	   )
-{
-    gssspnego_ctx ctx;
-
-    *minor_status =3D 0;
-
-    if (context_handle =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    ctx =3D (gssspnego_ctx)context_handle;
-
-    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
-	return GSS_S_NO_CONTEXT;
-    }
-
-    if ((ctx->mech_flags & GSS_C_DCE_STYLE) =3D=3D 0 &&
-	associated_data_buffer->length !=3D input_message_buffer->length) {
-	*minor_status =3D EINVAL;
-	return GSS_S_BAD_QOP;
-    }
-
-    return gss_wrap_ex(minor_status,
-		       ctx->negotiated_ctx_id,
-		       conf_req_flag,
-		       qop_req,
-		       associated_data_buffer,
-		       input_message_buffer,
-		       conf_state,
-		       output_token_buffer,
-		       output_message_buffer);
-}
-
-OM_uint32 _gss_spnego_complete_auth_token
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_complete_auth_token
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
 	    gss_buffer_t input_message_buffer)
@@ -849,7 +733,7 @@
 }
 #endif
=20
-OM_uint32 _gss_spnego_inquire_sec_context_by_oid
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_sec_context_by_oid
            (OM_uint32 * minor_status,
             const gss_ctx_id_t context_handle,
             const gss_OID desired_object,
@@ -875,7 +759,7 @@
 					  data_set);
 }
=20
-OM_uint32 _gss_spnego_set_sec_context_option
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_set_sec_context_option
            (OM_uint32 * minor_status,
             gss_ctx_id_t * context_handle,
             const gss_OID desired_object,
@@ -889,7 +773,7 @@
 	return GSS_S_NO_CONTEXT;
     }
=20
-    ctx =3D (gssspnego_ctx)context_handle;
+    ctx =3D (gssspnego_ctx)*context_handle;
=20
     if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
 	return GSS_S_NO_CONTEXT;
@@ -901,3 +785,31 @@
 				      value);
 }
=20
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_pseudo_random(OM_uint32 *minor_status,
+			  gss_ctx_id_t context_handle,
+			  int prf_key,
+			  const gss_buffer_t prf_in,
+			  ssize_t desired_output_len,
+			  gss_buffer_t prf_out)
+{
+    gssspnego_ctx ctx;
+
+    *minor_status =3D 0;
+
+    if (context_handle =3D=3D GSS_C_NO_CONTEXT)
+	return GSS_S_NO_CONTEXT;
+
+    ctx =3D (gssspnego_ctx)context_handle;
+
+    if (ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT)
+	return GSS_S_NO_CONTEXT;
+
+    return gss_pseudo_random(minor_status,
+			     ctx->negotiated_ctx_id,
+			     prf_key,
+			     prf_in,
+			     desired_output_len,
+			     prf_out);
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
cred_stubs.c
--- a/head/crypto/heimdal/lib/gssapi/spnego/cred_stubs.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/cred_stubs.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -30,63 +30,31 @@
  * SUCH DAMAGE.
  */
=20
-#include "spnego/spnego_locl.h"
+#include "spnego_locl.h"
=20
-RCSID("$Id: cred_stubs.c 20619 2007-05-08 13:43:45Z lha $");
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_release_cred(OM_uint32 *minor_status, gss_cred_id_t *cred_hand=
le)
 {
-    gssspnego_cred cred;
     OM_uint32 ret;
-   =20
+
     *minor_status =3D 0;
=20
-    if (*cred_handle =3D=3D GSS_C_NO_CREDENTIAL) {
+    if (cred_handle =3D=3D NULL || *cred_handle =3D=3D GSS_C_NO_CREDENTIAL)
 	return GSS_S_COMPLETE;
-    }
-    cred =3D (gssspnego_cred)*cred_handle;
=20
-    ret =3D gss_release_cred(minor_status, &cred->negotiated_cred_id);
+    ret =3D gss_release_cred(minor_status, cred_handle);
=20
-    free(cred);
     *cred_handle =3D GSS_C_NO_CREDENTIAL;
=20
     return ret;
 }
=20
-OM_uint32
-_gss_spnego_alloc_cred(OM_uint32 *minor_status,
-		       gss_cred_id_t mech_cred_handle,
-		       gss_cred_id_t *cred_handle)
-{
-    gssspnego_cred cred;
-
-    if (*cred_handle !=3D GSS_C_NO_CREDENTIAL) {
-	*minor_status =3D EINVAL;
-	return GSS_S_FAILURE;
-    }
-
-    cred =3D calloc(1, sizeof(*cred));
-    if (cred =3D=3D NULL) {
-	*cred_handle =3D GSS_C_NO_CREDENTIAL;
-	*minor_status =3D ENOMEM;
-	return GSS_S_FAILURE;
-    }
-
-    cred->negotiated_cred_id =3D mech_cred_handle;
-
-    *cred_handle =3D (gss_cred_id_t)cred;
-
-    return GSS_S_COMPLETE;=20
-}
-
 /*
  * For now, just a simple wrapper that avoids recursion. When
  * we support gss_{get,set}_neg_mechs() we will need to expose
  * more functionality.
  */
-OM_uint32 _gss_spnego_acquire_cred
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_acquire_cred
 (OM_uint32 *minor_status,
  const gss_name_t desired_name,
  OM_uint32 time_req,
@@ -102,9 +70,7 @@
     OM_uint32 ret, tmp;
     gss_OID_set_desc actual_desired_mechs;
     gss_OID_set mechs;
-    int i, j;
-    gss_cred_id_t cred_handle =3D GSS_C_NO_CREDENTIAL;
-    gssspnego_cred cred;
+    size_t i, j;
=20
     *output_cred_handle =3D GSS_C_NO_CREDENTIAL;
=20
@@ -114,7 +80,7 @@
 	    return ret;
 	}
     }
-   =20
+
     ret =3D gss_indicate_mechs(minor_status, &mechs);
     if (ret !=3D GSS_S_COMPLETE) {
 	gss_release_name(minor_status, &name);
@@ -140,22 +106,14 @@
     }
     actual_desired_mechs.count =3D j;
=20
-    ret =3D _gss_spnego_alloc_cred(minor_status, GSS_C_NO_CREDENTIAL,
-				 &cred_handle);
-    if (ret !=3D GSS_S_COMPLETE)
-	goto out;
-
-    cred =3D (gssspnego_cred)cred_handle;
     ret =3D gss_acquire_cred(minor_status, name,
 			   time_req, &actual_desired_mechs,
 			   cred_usage,
-			   &cred->negotiated_cred_id,
+			   output_cred_handle,
 			   actual_mechs, time_rec);
     if (ret !=3D GSS_S_COMPLETE)
 	goto out;
=20
-    *output_cred_handle =3D cred_handle;
-
 out:
     gss_release_name(minor_status, &name);
     gss_release_oid_set(&tmp, &mechs);
@@ -163,13 +121,13 @@
 	free(actual_desired_mechs.elements);
     }
     if (ret !=3D GSS_S_COMPLETE) {
-	_gss_spnego_release_cred(&tmp, &cred_handle);
+	_gss_spnego_release_cred(&tmp, output_cred_handle);
     }
=20
     return ret;
 }
=20
-OM_uint32 _gss_spnego_inquire_cred
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred
            (OM_uint32 * minor_status,
             const gss_cred_id_t cred_handle,
             gss_name_t * name,
@@ -178,7 +136,6 @@
             gss_OID_set * mechanisms
            )
 {
-    gssspnego_cred cred;
     spnego_name sname =3D NULL;
     OM_uint32 ret;
=20
@@ -195,10 +152,8 @@
 	}
     }
=20
-    cred =3D (gssspnego_cred)cred_handle;
-
     ret =3D gss_inquire_cred(minor_status,
-			   cred->negotiated_cred_id,
+			   cred_handle,
 			   sname ? &sname->mech : NULL,
 			   lifetime,
 			   cred_usage,
@@ -214,56 +169,7 @@
     return ret;
 }
=20
-OM_uint32 _gss_spnego_add_cred (
-            OM_uint32 * minor_status,
-            const gss_cred_id_t input_cred_handle,
-            const gss_name_t desired_name,
-            const gss_OID desired_mech,
-            gss_cred_usage_t cred_usage,
-            OM_uint32 initiator_time_req,
-            OM_uint32 acceptor_time_req,
-            gss_cred_id_t * output_cred_handle,
-            gss_OID_set * actual_mechs,
-            OM_uint32 * initiator_time_rec,
-            OM_uint32 * acceptor_time_rec
-           )
-{
-    gss_cred_id_t spnego_output_cred_handle =3D GSS_C_NO_CREDENTIAL;
-    OM_uint32 ret, tmp;
-    gssspnego_cred input_cred, output_cred;
-
-    *output_cred_handle =3D GSS_C_NO_CREDENTIAL;
-
-    ret =3D _gss_spnego_alloc_cred(minor_status, GSS_C_NO_CREDENTIAL,
-				 &spnego_output_cred_handle);
-    if (ret)
-	return ret;
-
-    input_cred =3D (gssspnego_cred)input_cred_handle;
-    output_cred =3D (gssspnego_cred)spnego_output_cred_handle;
-
-    ret =3D gss_add_cred(minor_status,
-		       input_cred->negotiated_cred_id,
-		       desired_name,
-		       desired_mech,
-		       cred_usage,
-		       initiator_time_req,
-		       acceptor_time_req,
-		       &output_cred->negotiated_cred_id,
-		       actual_mechs,
-		       initiator_time_rec,
-		       acceptor_time_rec);
-    if (ret) {
-	_gss_spnego_release_cred(&tmp, &spnego_output_cred_handle);
-	return ret;
-    }
-
-    *output_cred_handle =3D spnego_output_cred_handle;
-
-    return GSS_S_COMPLETE;
-}
-
-OM_uint32 _gss_spnego_inquire_cred_by_mech (
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred_by_mech (
             OM_uint32 * minor_status,
             const gss_cred_id_t cred_handle,
             const gss_OID mech_type,
@@ -273,7 +179,6 @@
             gss_cred_usage_t * cred_usage
            )
 {
-    gssspnego_cred cred;
     spnego_name sname =3D NULL;
     OM_uint32 ret;
=20
@@ -290,10 +195,8 @@
 	}
     }
=20
-    cred =3D (gssspnego_cred)cred_handle;
-
     ret =3D gss_inquire_cred_by_mech(minor_status,
-				   cred->negotiated_cred_id,
+				   cred_handle,
 				   mech_type,
 				   sname ? &sname->mech : NULL,
 				   initiator_lifetime,
@@ -311,26 +214,60 @@
     return GSS_S_COMPLETE;
 }
=20
-OM_uint32 _gss_spnego_inquire_cred_by_oid
+OM_uint32 GSSAPI_CALLCONV _gss_spnego_inquire_cred_by_oid
            (OM_uint32 * minor_status,
             const gss_cred_id_t cred_handle,
             const gss_OID desired_object,
             gss_buffer_set_t *data_set)
 {
-    gssspnego_cred cred;
     OM_uint32 ret;
=20
     if (cred_handle =3D=3D GSS_C_NO_CREDENTIAL) {
 	*minor_status =3D 0;
 	return GSS_S_NO_CRED;
     }
-    cred =3D (gssspnego_cred)cred_handle;
=20
     ret =3D gss_inquire_cred_by_oid(minor_status,
-				  cred->negotiated_cred_id,
+				  cred_handle,
 				  desired_object,
 				  data_set);
=20
     return ret;
 }
=20
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_set_cred_option (OM_uint32 *minor_status,
+			     gss_cred_id_t *cred_handle,
+			     const gss_OID object,
+			     const gss_buffer_t value)
+{
+    if (cred_handle =3D=3D NULL || *cred_handle =3D=3D GSS_C_NO_CREDENTIAL=
) {
+	*minor_status =3D 0;
+	return GSS_S_NO_CRED;
+    }
+
+    return gss_set_cred_option(minor_status,
+			      cred_handle,
+			      object,
+			      value);
+}
+
+#if 0
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_export_cred (OM_uint32 *minor_status,
+			 gss_cred_id_t cred_handle,
+			 gss_buffer_t value)
+{
+    return gss_export_cred(minor_status, cred_handle, value);
+}
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_import_cred (OM_uint32 *minor_status,
+			 gss_buffer_t value,
+			 gss_cred_id_t *cred_handle)
+{
+    return gss_import_cred(minor_status, value, cred_handle);
+}
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
external.c
--- a/head/crypto/heimdal/lib/gssapi/spnego/external.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/external.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -30,22 +30,57 @@
  * SUCH DAMAGE.
  */
=20
-#include "spnego/spnego_locl.h"
+#include "spnego_locl.h"
 #include <gssapi_mech.h>
=20
-RCSID("$Id: external.c 18336 2006-10-07 22:27:13Z lha $");
-
 /*
  * RFC2478, SPNEGO:
  *  The security mechanism of the initial
  *  negotiation token is identified by the Object Identifier
  *  iso.org.dod.internet.security.mechanism.snego (1.3.6.1.5.5.2).
  */
+#if 0
+static gss_mo_desc spnego_mo[] =3D {
+    {
+	GSS_C_MA_SASL_MECH_NAME,
+	GSS_MO_MA,
+	"SASL mech name",
+	rk_UNCONST("SPNEGO"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_NAME,
+	GSS_MO_MA,
+	"Mechanism name",
+	rk_UNCONST("SPNEGO"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_DESCRIPTION,
+	GSS_MO_MA,
+	"Mechanism description",
+	rk_UNCONST("Heimdal SPNEGO Mechanism"),
+	_gss_mo_get_ctx_as_string,
+	NULL
+    },
+    {
+	GSS_C_MA_MECH_NEGO,
+	GSS_MO_MA
+    },
+    {
+	GSS_C_MA_MECH_PSEUDO,
+	GSS_MO_MA
+    }
+};
+#endif
=20
 static gssapi_mech_interface_desc spnego_mech =3D {
     GMI_VERSION,
     "spnego",
-    {6, (void *)"\x2b\x06\x01\x05\x05\x02"},
+    {6, rk_UNCONST("\x2b\x06\x01\x05\x05\x02") },
+    0,
     _gss_spnego_acquire_cred,
     _gss_spnego_release_cred,
     _gss_spnego_init_sec_context,
@@ -57,8 +92,8 @@
     _gss_spnego_verify_mic,
     _gss_spnego_wrap,
     _gss_spnego_unwrap,
-    _gss_spnego_display_status,
-    NULL,
+    NULL, /* gm_display_status */
+    NULL, /* gm_indicate_mechs */
     _gss_spnego_compare_name,
     _gss_spnego_display_name,
     _gss_spnego_import_name,
@@ -67,14 +102,56 @@
     _gss_spnego_inquire_cred,
     _gss_spnego_inquire_context,
     _gss_spnego_wrap_size_limit,
-    _gss_spnego_add_cred,
+    gss_add_cred,
     _gss_spnego_inquire_cred_by_mech,
     _gss_spnego_export_sec_context,
     _gss_spnego_import_sec_context,
-    _gss_spnego_inquire_names_for_mech,
+    NULL /* _gss_spnego_inquire_names_for_mech */,
     _gss_spnego_inquire_mechs_for_name,
     _gss_spnego_canonicalize_name,
-    _gss_spnego_duplicate_name
+    _gss_spnego_duplicate_name,
+    _gss_spnego_inquire_sec_context_by_oid,
+    _gss_spnego_inquire_cred_by_oid,
+    _gss_spnego_set_sec_context_option,
+    _gss_spnego_set_cred_option,
+    _gss_spnego_pseudo_random,
+#if 0
+    _gss_spnego_wrap_iov,
+    _gss_spnego_unwrap_iov,
+    _gss_spnego_wrap_iov_length,
+#else
+    NULL,
+    NULL,
+    NULL,
+#endif
+    NULL,
+#if 0
+    _gss_spnego_export_cred,
+    _gss_spnego_import_cred,
+#else
+    NULL,
+    NULL,
+#endif
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+#if 0
+    spnego_mo,
+    sizeof(spnego_mo) / sizeof(spnego_mo[0]),
+#else
+    NULL,
+    0,
+#endif
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
+    NULL,
 };
=20
 gssapi_mech_interface
@@ -82,8 +159,3 @@
 {
 	return &spnego_mech;
 }
-
-static gss_OID_desc _gss_spnego_mechanism_desc =3D=20
-    {6, (void *)"\x2b\x06\x01\x05\x05\x02"};
-
-gss_OID GSS_SPNEGO_MECHANISM =3D &_gss_spnego_mechanism_desc;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
init_sec_context.c
--- a/head/crypto/heimdal/lib/gssapi/spnego/init_sec_context.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/init_sec_context.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,42 +1,40 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * Portions Copyright (c) 2004 PADL Software Pty Ltd.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include "spnego/spnego_locl.h"
-
-RCSID("$Id: init_sec_context.c 19411 2006-12-18 15:42:03Z lha $");
+#include "spnego_locl.h"
=20
 /*
- * Is target_name an sane target for `mech=B4.
+ * Is target_name an sane target for `mech=C2=B4.
  */
=20
 static OM_uint32
@@ -45,7 +43,7 @@
     OM_uint32 min_stat, maj_stat;
     gss_ctx_id_t ctx =3D GSS_C_NO_CONTEXT;
     gss_buffer_desc out;
-   =20
+
     maj_stat =3D gss_init_sec_context(&min_stat,
 				    GSS_C_NO_CREDENTIAL,
 				    &ctx,
@@ -59,8 +57,10 @@
 				    &out,
 				    NULL,
 				    NULL);
-    if (GSS_ERROR(maj_stat))
+    if (GSS_ERROR(maj_stat)) {
+	gss_mg_collect_error(mech, maj_stat, min_stat);
 	return GSS_S_BAD_MECH;
+    }
     gss_release_buffer(&min_stat, &out);
     gss_delete_sec_context(&min_stat, &ctx, NULL);
=20
@@ -177,7 +177,7 @@
 static OM_uint32
 spnego_initial
            (OM_uint32 * minor_status,
-	    gssspnego_cred cred,
+	    gss_cred_id_t cred,
             gss_ctx_id_t * context_handle,
             const gss_name_t target_name,
             const gss_OID mech_type,
@@ -230,7 +230,7 @@
 	return sub;
     }
=20
-    sub =3D _gss_spnego_indicate_mechtypelist(&minor,=20
+    sub =3D _gss_spnego_indicate_mechtypelist(&minor,
 					    ctx->target_name,
 					    initiator_approved,
 					    0,
@@ -252,8 +252,7 @@
=20
     /* generate optimistic token */
     sub =3D gss_init_sec_context(&minor,
-			       (cred !=3D NULL) ? cred->negotiated_cred_id :
-			          GSS_C_NO_CREDENTIAL,
+			       cred,
 			       &ctx->negotiated_ctx_id,
 			       ctx->target_name,
 			       ctx->preferred_mech_type,
@@ -268,6 +267,7 @@
     if (GSS_ERROR(sub)) {
 	free_NegTokenInit(&ni);
 	*minor_status =3D minor;
+	gss_mg_collect_error(ctx->preferred_mech_type, sub, minor);
 	_gss_spnego_internal_delete_sec_context(&minor, &context, GSS_C_NO_BUFFER=
);
 	return sub;
     }
@@ -344,7 +344,7 @@
     ctx->initiator_mech_types.val =3D ni.mechTypes.val;
     ni.mechTypes.len =3D 0;
     ni.mechTypes.val =3D NULL;
-=20
+
     free_NegTokenInit(&ni);
=20
     sub =3D gss_encapsulate_token(&data,
@@ -374,7 +374,7 @@
 static OM_uint32
 spnego_reply
            (OM_uint32 * minor_status,
-	    const gssspnego_cred cred,
+	    const gss_cred_id_t cred,
             gss_ctx_id_t * context_handle,
             const gss_name_t target_name,
             const gss_OID mech_type,
@@ -389,11 +389,10 @@
     )
 {
     OM_uint32 ret, minor;
-    NegTokenResp resp;
-    size_t len, taglen;
+    NegotiationToken resp;
     gss_OID_desc mech;
     int require_mic;
-    size_t buf_len;
+    size_t buf_len =3D 0;
     gss_buffer_desc mic_buf, mech_buf;
     gss_buffer_desc mech_output_token;
     gssspnego_ctx ctx;
@@ -411,27 +410,23 @@
     mech_buf.value =3D NULL;
     mech_buf.length =3D 0;
=20
-    ret =3D der_match_tag_and_length(input_token->value, input_token->leng=
th,
-				   ASN1_C_CONTEXT, CONS, 1, &len, &taglen);
+    ret =3D decode_NegotiationToken(input_token->value, input_token->lengt=
h,
+				  &resp, NULL);
     if (ret)
-	return ret;
+      return ret;
=20
-    if (len > input_token->length - taglen)
-	return ASN1_OVERRUN;
-
-    ret =3D decode_NegTokenResp((const unsigned char *)input_token->value+=
taglen,
-			      len, &resp, NULL);
-    if (ret) {
-	*minor_status =3D ENOMEM;
-	return GSS_S_FAILURE;
+    if (resp.element !=3D choice_NegotiationToken_negTokenResp) {
+	free_NegotiationToken(&resp);
+	*minor_status =3D 0;
+	return GSS_S_BAD_MECH;
     }
=20
-    if (resp.negResult =3D=3D NULL
-	|| *(resp.negResult) =3D=3D reject
-	/* || resp.supportedMech =3D=3D NULL */
+    if (resp.u.negTokenResp.negResult =3D=3D NULL
+	|| *(resp.u.negTokenResp.negResult) =3D=3D reject
+	/* || resp.u.negTokenResp.supportedMech =3D=3D NULL */
 	)
     {
-	free_NegTokenResp(&resp);
+	free_NegotiationToken(&resp);
 	return GSS_S_BAD_MECH;
     }
=20
@@ -442,16 +437,16 @@
=20
     HEIMDAL_MUTEX_lock(&ctx->ctx_id_mutex);
=20
-    if (resp.supportedMech) {
+    if (resp.u.negTokenResp.supportedMech) {
=20
 	if (ctx->oidlen) {
-	    free_NegTokenResp(&resp);
+	    free_NegotiationToken(&resp);
 	    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	    return GSS_S_BAD_MECH;
 	}
 	ret =3D der_put_oid(ctx->oidbuf + sizeof(ctx->oidbuf) - 1,
 			  sizeof(ctx->oidbuf),
-			  resp.supportedMech,
+			  resp.u.negTokenResp.supportedMech,
 			  &ctx->oidlen);
 	/* Avoid recursively embedded SPNEGO */
 	if (ret || (ctx->oidlen =3D=3D GSS_SPNEGO_MECHANISM->length &&
@@ -459,7 +454,7 @@
 			   GSS_SPNEGO_MECHANISM->elements,
 			   ctx->oidlen) =3D=3D 0))
 	{
-	    free_NegTokenResp(&resp);
+	    free_NegotiationToken(&resp);
 	    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	    return GSS_S_BAD_MECH;
 	}
@@ -470,23 +465,24 @@
 		   ctx->preferred_mech_type->elements,
 		   ctx->oidlen) !=3D 0)
 	{
-	    gss_delete_sec_context(&minor, &ctx->negotiated_ctx_id,=20
+	    gss_delete_sec_context(&minor, &ctx->negotiated_ctx_id,
 				   GSS_C_NO_BUFFER);
 	    ctx->negotiated_ctx_id =3D GSS_C_NO_CONTEXT;
 	}
     } else if (ctx->oidlen =3D=3D 0) {
-	free_NegTokenResp(&resp);
+	free_NegotiationToken(&resp);
 	HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	return GSS_S_BAD_MECH;
     }
=20
-    if (resp.responseToken !=3D NULL ||=20
+    /* if a token (of non zero length), or no context, pass to underlaying=
 mech */
+    if ((resp.u.negTokenResp.responseToken !=3D NULL && resp.u.negTokenRes=
p.responseToken->length) ||
 	ctx->negotiated_ctx_id =3D=3D GSS_C_NO_CONTEXT) {
 	gss_buffer_desc mech_input_token;
=20
-	if (resp.responseToken) {
-	    mech_input_token.length =3D resp.responseToken->length;
-	    mech_input_token.value  =3D resp.responseToken->data;
+	if (resp.u.negTokenResp.responseToken) {
+	    mech_input_token.length =3D resp.u.negTokenResp.responseToken->length;
+	    mech_input_token.value  =3D resp.u.negTokenResp.responseToken->data;
 	} else {
 	    mech_input_token.length =3D 0;
 	    mech_input_token.value =3D NULL;
@@ -499,8 +495,7 @@
 	/* Fall through as if the negotiated mechanism
 	   was requested explicitly */
 	ret =3D gss_init_sec_context(&minor,
-				   (cred !=3D NULL) ? cred->negotiated_cred_id :
-				       GSS_C_NO_CREDENTIAL,
+				   cred,
 				   &ctx->negotiated_ctx_id,
 				   ctx->target_name,
 				   &mech,
@@ -514,19 +509,20 @@
 				   &ctx->mech_time_rec);
 	if (GSS_ERROR(ret)) {
 	    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
-	    free_NegTokenResp(&resp);
+	    free_NegotiationToken(&resp);
+	    gss_mg_collect_error(&mech, ret, minor);
 	    *minor_status =3D minor;
 	    return ret;
 	}
 	if (ret =3D=3D GSS_S_COMPLETE) {
 	    ctx->open =3D 1;
 	}
-    } else if (*(resp.negResult) =3D=3D accept_completed) {
+    } else if (*(resp.u.negTokenResp.negResult) =3D=3D accept_completed) {
 	if (ctx->maybe_open)
 	    ctx->open =3D 1;
     }
=20
-    if (*(resp.negResult) =3D=3D request_mic) {
+    if (*(resp.u.negTokenResp.negResult) =3D=3D request_mic) {
 	ctx->require_mic =3D 1;
     }
=20
@@ -535,14 +531,14 @@
 	 * Verify the mechListMIC if one was provided or CFX was
 	 * used and a non-preferred mechanism was selected
 	 */
-	if (resp.mechListMIC !=3D NULL) {
+	if (resp.u.negTokenResp.mechListMIC !=3D NULL) {
 	    require_mic =3D 1;
 	} else {
 	    ret =3D _gss_spnego_require_mechlist_mic(minor_status, ctx,
 						   &require_mic);
 	    if (ret) {
 		HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
-		free_NegTokenResp(&resp);
+		free_NegotiationToken(&resp);
 		gss_release_buffer(&minor, &mech_output_token);
 		return ret;
 	    }
@@ -556,23 +552,25 @@
 			   &ctx->initiator_mech_types, &buf_len, ret);
 	if (ret) {
 	    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
-	    free_NegTokenResp(&resp);
+	    free_NegotiationToken(&resp);
 	    gss_release_buffer(&minor, &mech_output_token);
 	    *minor_status =3D ret;
 	    return GSS_S_FAILURE;
 	}
-	if (mech_buf.length !=3D buf_len)
+	if (mech_buf.length !=3D buf_len) {
 	    abort();
+            UNREACHABLE(return GSS_S_FAILURE);
+        }
=20
-	if (resp.mechListMIC =3D=3D NULL) {
+	if (resp.u.negTokenResp.mechListMIC =3D=3D NULL) {
 	    HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 	    free(mech_buf.value);
-	    free_NegTokenResp(&resp);
+	    free_NegotiationToken(&resp);
 	    *minor_status =3D 0;
 	    return GSS_S_DEFECTIVE_TOKEN;
 	}
-	mic_buf.length =3D resp.mechListMIC->length;
-	mic_buf.value  =3D resp.mechListMIC->data;
+	mic_buf.length =3D resp.u.negTokenResp.mechListMIC->length;
+	mic_buf.value  =3D resp.u.negTokenResp.mechListMIC->data;
=20
 	if (mech_output_token.length =3D=3D 0) {
 	    ret =3D gss_verify_mic(minor_status,
@@ -584,7 +582,7 @@
 		HEIMDAL_MUTEX_unlock(&ctx->ctx_id_mutex);
 		free(mech_buf.value);
 		gss_release_buffer(&minor, &mech_output_token);
-		free_NegTokenResp(&resp);
+		free_NegotiationToken(&resp);
 		return GSS_S_DEFECTIVE_TOKEN;
 	    }
 	    ctx->verified_mic =3D 1;
@@ -599,7 +597,7 @@
     if (mech_buf.value !=3D NULL)
 	free(mech_buf.value);
=20
-    free_NegTokenResp(&resp);
+    free_NegotiationToken(&resp);
     gss_release_buffer(&minor, &mech_output_token);
=20
     if (actual_mech_type)
@@ -613,7 +611,8 @@
     return ret;
 }
=20
-OM_uint32 _gss_spnego_init_sec_context
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_init_sec_context
            (OM_uint32 * minor_status,
             const gss_cred_id_t initiator_cred_handle,
             gss_ctx_id_t * context_handle,
@@ -629,11 +628,9 @@
             OM_uint32 * time_rec
            )
 {
-    gssspnego_cred cred =3D (gssspnego_cred)initiator_cred_handle;
-
     if (*context_handle =3D=3D GSS_C_NO_CONTEXT)
 	return spnego_initial (minor_status,
-			       cred,
+			       initiator_cred_handle,
 			       context_handle,
 			       target_name,
 			       mech_type,
@@ -647,7 +644,7 @@
 			       time_rec);
     else
 	return spnego_reply (minor_status,
-			     cred,
+			     initiator_cred_handle,
 			     context_handle,
 			     target_name,
 			     mech_type,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
spnego-private.h
--- a/head/crypto/heimdal/lib/gssapi/spnego/spnego-private.h	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/spnego-private.h	Tue Apr 17 11:=
51:51 2012 +0300
@@ -7,7 +7,7 @@
 gssapi_mech_interface
 __gss_spnego_initialize (void);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_accept_sec_context (
 	OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
@@ -21,7 +21,7 @@
 	OM_uint32 * /*time_rec*/,
 	gss_cred_id_t *delegated_cred_handle );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_acquire_cred (
 	OM_uint32 */*minor_status*/,
 	const gss_name_t /*desired_name*/,
@@ -32,92 +32,69 @@
 	gss_OID_set * /*actual_mechs*/,
 	OM_uint32 * time_rec );
=20
-OM_uint32
-_gss_spnego_add_cred (
-	 OM_uint32 * /*minor_status*/,
-	const gss_cred_id_t /*input_cred_handle*/,
-	const gss_name_t /*desired_name*/,
-	const gss_OID /*desired_mech*/,
-	gss_cred_usage_t /*cred_usage*/,
-	OM_uint32 /*initiator_time_req*/,
-	OM_uint32 /*acceptor_time_req*/,
-	gss_cred_id_t * /*output_cred_handle*/,
-	gss_OID_set * /*actual_mechs*/,
-	OM_uint32 * /*initiator_time_rec*/,
-	OM_uint32 * acceptor_time_rec );
-
-OM_uint32
-_gss_spnego_alloc_cred (
-	OM_uint32 */*minor_status*/,
-	gss_cred_id_t /*mech_cred_handle*/,
-	gss_cred_id_t */*cred_handle*/);
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_alloc_sec_context (
 	OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t */*context_handle*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_canonicalize_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	const gss_OID /*mech_type*/,
 	gss_name_t * output_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_compare_name (
 	OM_uint32 */*minor_status*/,
 	const gss_name_t /*name1*/,
 	const gss_name_t /*name2*/,
 	int * name_equal );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_context_time (
 	OM_uint32 */*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
 	OM_uint32 *time_rec );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_delete_sec_context (
 	OM_uint32 */*minor_status*/,
 	gss_ctx_id_t */*context_handle*/,
 	gss_buffer_t output_token );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_display_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_buffer_t /*output_name_buffer*/,
 	gss_OID * output_name_type );
=20
-OM_uint32
-_gss_spnego_display_status (
-	OM_uint32 * /*minor_status*/,
-	OM_uint32 /*status_value*/,
-	int /*status_type*/,
-	const gss_OID /*mech_type*/,
-	OM_uint32 * /*message_context*/,
-	gss_buffer_t status_string );
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_duplicate_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*src_name*/,
 	gss_name_t * dest_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_export_cred (
+	OM_uint32 */*minor_status*/,
+	gss_cred_id_t /*cred_handle*/,
+	gss_buffer_t /*value*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_export_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_buffer_t exported_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_export_sec_context (
 	 OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
 	gss_buffer_t interprocess_token );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_get_mic (
 	OM_uint32 */*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -125,30 +102,36 @@
 	const gss_buffer_t /*message_buffer*/,
 	gss_buffer_t message_token );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_import_cred (
+	OM_uint32 */*minor_status*/,
+	gss_buffer_t /*value*/,
+	gss_cred_id_t */*cred_handle*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_import_name (
 	OM_uint32 * /*minor_status*/,
 	const gss_buffer_t /*name_buffer*/,
 	const gss_OID /*name_type*/,
 	gss_name_t * output_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_import_sec_context (
 	 OM_uint32 * /*minor_status*/,
 	const gss_buffer_t /*interprocess_token*/,
 	gss_ctx_id_t *context_handle );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_indicate_mechtypelist (
 	OM_uint32 */*minor_status*/,
 	gss_name_t /*target_name*/,
 	OM_uint32 (*/*func*/)(gss_name_t, gss_OID),
 	int /*includeMSCompatOID*/,
-	const gssspnego_cred /*cred_handle*/,
+	const gss_cred_id_t /*cred_handle*/,
 	MechTypeList */*mechtypelist*/,
 	gss_OID */*preferred_mech*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_init_sec_context (
 	OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*initiator_cred_handle*/,
@@ -164,7 +147,7 @@
 	OM_uint32 * /*ret_flags*/,
 	OM_uint32 * time_rec );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_inquire_context (
 	 OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -176,7 +159,7 @@
 	int * /*locally_initiated*/,
 	int * open_context );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_inquire_cred (
 	OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
@@ -185,7 +168,7 @@
 	gss_cred_usage_t * /*cred_usage*/,
 	gss_OID_set * mechanisms );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_inquire_cred_by_mech (
 	 OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
@@ -195,95 +178,84 @@
 	OM_uint32 * /*acceptor_lifetime*/,
 	gss_cred_usage_t * cred_usage );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_inquire_cred_by_oid (
 	OM_uint32 * /*minor_status*/,
 	const gss_cred_id_t /*cred_handle*/,
 	const gss_OID /*desired_object*/,
 	gss_buffer_set_t */*data_set*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_inquire_mechs_for_name (
 	 OM_uint32 * /*minor_status*/,
 	const gss_name_t /*input_name*/,
 	gss_OID_set * mech_types );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_inquire_names_for_mech (
 	 OM_uint32 * /*minor_status*/,
 	const gss_OID /*mechanism*/,
 	gss_OID_set * name_types );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_inquire_sec_context_by_oid (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
 	const gss_OID /*desired_object*/,
 	gss_buffer_set_t */*data_set*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_internal_delete_sec_context (
 	OM_uint32 */*minor_status*/,
 	gss_ctx_id_t */*context_handle*/,
 	gss_buffer_t output_token );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_process_context_token (
 	OM_uint32 */*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
 	const gss_buffer_t token_buffer );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_pseudo_random (
+	OM_uint32 */*minor_status*/,
+	gss_ctx_id_t /*context_handle*/,
+	int /*prf_key*/,
+	const gss_buffer_t /*prf_in*/,
+	ssize_t /*desired_output_len*/,
+	gss_buffer_t /*prf_out*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_release_cred (
 	OM_uint32 */*minor_status*/,
 	gss_cred_id_t */*cred_handle*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_release_name (
 	OM_uint32 * /*minor_status*/,
 	gss_name_t * input_name );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_require_mechlist_mic (
 	OM_uint32 */*minor_status*/,
 	gssspnego_ctx /*ctx*/,
 	int */*require_mic*/);
=20
-OM_uint32
-_gss_spnego_seal (
-	OM_uint32 * /*minor_status*/,
-	gss_ctx_id_t /*context_handle*/,
-	int /*conf_req_flag*/,
-	int /*qop_req*/,
-	gss_buffer_t /*input_message_buffer*/,
-	int * /*conf_state*/,
-	gss_buffer_t output_message_buffer );
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_set_cred_option (
+	OM_uint32 */*minor_status*/,
+	gss_cred_id_t */*cred_handle*/,
+	const gss_OID /*object*/,
+	const gss_buffer_t /*value*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_set_sec_context_option (
 	OM_uint32 * /*minor_status*/,
 	gss_ctx_id_t * /*context_handle*/,
 	const gss_OID /*desired_object*/,
 	const gss_buffer_t /*value*/);
=20
-OM_uint32
-_gss_spnego_sign (
-	OM_uint32 * /*minor_status*/,
-	gss_ctx_id_t /*context_handle*/,
-	int /*qop_req*/,
-	gss_buffer_t /*message_buffer*/,
-	gss_buffer_t message_token );
-
-OM_uint32
-_gss_spnego_unseal (
-	OM_uint32 * /*minor_status*/,
-	gss_ctx_id_t /*context_handle*/,
-	gss_buffer_t /*input_message_buffer*/,
-	gss_buffer_t /*output_message_buffer*/,
-	int * /*conf_state*/,
-	int * qop_state );
-
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_unwrap (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -292,15 +264,16 @@
 	int * /*conf_state*/,
 	gss_qop_t * qop_state );
=20
-OM_uint32
-_gss_spnego_verify (
-	OM_uint32 * /*minor_status*/,
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_unwrap_iov (
+	OM_uint32 */*minor_status*/,
 	gss_ctx_id_t /*context_handle*/,
-	gss_buffer_t /*message_buffer*/,
-	gss_buffer_t /*token_buffer*/,
-	int * qop_state );
+	int */*conf_state*/,
+	gss_qop_t */*qop_state*/,
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_verify_mic (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -308,7 +281,7 @@
 	const gss_buffer_t /*token_buffer*/,
 	gss_qop_t * qop_state );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_wrap (
 	OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
@@ -318,7 +291,27 @@
 	int * /*conf_state*/,
 	gss_buffer_t output_message_buffer );
=20
-OM_uint32
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_wrap_iov (
+	OM_uint32 * /*minor_status*/,
+	gss_ctx_id_t /*context_handle*/,
+	int /*conf_req_flag*/,
+	gss_qop_t /*qop_req*/,
+	int * /*conf_state*/,
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
+
+OM_uint32 GSSAPI_CALLCONV
+_gss_spnego_wrap_iov_length (
+	OM_uint32 * /*minor_status*/,
+	gss_ctx_id_t /*context_handle*/,
+	int /*conf_req_flag*/,
+	gss_qop_t /*qop_req*/,
+	int */*conf_state*/,
+	gss_iov_buffer_desc */*iov*/,
+	int /*iov_count*/);
+
+OM_uint32 GSSAPI_CALLCONV
 _gss_spnego_wrap_size_limit (
 	 OM_uint32 * /*minor_status*/,
 	const gss_ctx_id_t /*context_handle*/,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
spnego.asn1
--- a/head/crypto/heimdal/lib/gssapi/spnego/spnego.asn1	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/spnego.asn1	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
--- $Id: spnego.asn1 21403 2007-07-04 08:13:12Z lha $
+-- $Id$
=20
 SPNEGO DEFINITIONS ::=3D
 BEGIN
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/spnego/=
spnego_locl.h
--- a/head/crypto/heimdal/lib/gssapi/spnego/spnego_locl.h	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/spnego/spnego_locl.h	Tue Apr 17 11:51:=
51 2012 +0300
@@ -30,15 +30,12 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: spnego_locl.h 19411 2006-12-18 15:42:03Z lha $ */
-/* $FreeBSD$ */
+/* $Id$ */
=20
 #ifndef SPNEGO_LOCL_H
 #define SPNEGO_LOCL_H
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -47,12 +44,15 @@
 #include <sys/param.h>
 #endif
=20
+#include <roken.h>
+
 #ifdef HAVE_PTHREAD_H
 #include <pthread.h>
 #endif
=20
-#include <gssapi/gssapi_spnego.h>
 #include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
 #include <assert.h>
 #include <stdlib.h>
 #include <string.h>
@@ -68,17 +68,14 @@
 #include <gssapi_mech.h>
=20
 #include "spnego_asn1.h"
+#include "utils.h"
 #include <der.h>
=20
-#include <roken.h>
+#include <heimbase.h>
=20
 #define ALLOC(X, N) (X) =3D calloc((N), sizeof(*(X)))
=20
 typedef struct {
-	gss_cred_id_t		negotiated_cred_id;
-} *gssspnego_cred;
-
-typedef struct {
 	MechTypeList		initiator_mech_types;
 	gss_OID			preferred_mech_type;
 	gss_OID			negotiated_mech_type;
@@ -86,7 +83,6 @@
 	OM_uint32		mech_flags;
 	OM_uint32		mech_time_rec;
 	gss_name_t		mech_src_name;
-	gss_cred_id_t		delegated_cred_id;
 	unsigned int		open : 1;
 	unsigned int		local : 1;
 	unsigned int		require_mic : 1;
@@ -110,6 +106,6 @@
 extern gss_OID_desc _gss_spnego_mskrb_mechanism_oid_desc;
 extern gss_OID_desc _gss_spnego_krb5_mechanism_oid_desc;
=20
-#include <spnego/spnego-private.h>
+#include <spnego-private.h>
=20
 #endif /* SPNEGO_LOCL_H */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_ac=
quire_cred.c
--- a/head/crypto/heimdal/lib/gssapi/test_acquire_cred.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/test_acquire_cred.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -35,19 +35,19 @@
 #include <config.h>
 #endif
=20
+#include <roken.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
 #include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
 #include <err.h>
-#include <roken.h>
 #include <getarg.h>
=20
 #include "test_common.h"
=20
-RCSID("$Id: test_acquire_cred.c 22129 2007-12-04 01:13:13Z lha $");
-
 static void
 print_time(OM_uint32 time_rec)
 {
@@ -79,7 +79,7 @@
 				 NULL,
 				 &time_rec,
 				 NULL);
-			   =20
+
     if (GSS_ERROR(major_status))
 	errx(1, "add_cred failed");
=20
@@ -98,7 +98,7 @@
     gss_cred_id_t cred_handle;
     OM_uint32 time_rec;
=20
-    major_status =3D gss_acquire_cred(&minor_status,=20
+    major_status =3D gss_acquire_cred(&minor_status,
 				    GSS_C_NO_NAME,
 				    0,
 				    NULL,
@@ -108,7 +108,7 @@
 				    &time_rec);
     if (GSS_ERROR(major_status))
 	errx(1, "acquire_cred failed");
-=09
+
     print_time(time_rec);
=20
     test_add(cred_handle);
@@ -122,9 +122,10 @@
 }
 #endif
=20
-static void
+static gss_cred_id_t
 acquire_cred_service(const char *service,
 		     gss_OID nametype,
+		     gss_OID_set oidset,
 		     int flags)
 {
     OM_uint32 major_status, minor_status;
@@ -136,7 +137,7 @@
     if (service) {
 	name_buffer.value =3D rk_UNCONST(service);
 	name_buffer.length =3D strlen(service);
-=09
+
 	major_status =3D gss_import_name(&minor_status,
 				       &name_buffer,
 				       nametype,
@@ -145,18 +146,18 @@
 	    errx(1, "import_name failed");
     }
=20
-    major_status =3D gss_acquire_cred(&minor_status,=20
+    major_status =3D gss_acquire_cred(&minor_status,
 				    name,
 				    0,
-				    NULL,
+				    oidset,
 				    flags,
 				    &cred_handle,
 				    NULL,
 				    &time_rec);
     if (GSS_ERROR(major_status)) {
-	warnx("acquire_cred failed: %s",=20
+	warnx("acquire_cred failed: %s",
 	     gssapi_err(major_status, minor_status, GSS_C_NO_OID));
-    } else {   =20
+    } else {
 	print_time(time_rec);
 	gss_release_cred(&minor_status, &cred_handle);
     }
@@ -166,18 +167,28 @@
=20
     if (GSS_ERROR(major_status))
 	exit(1);
+
+    return cred_handle;
 }
=20
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
+static int kerberos_flag =3D 0;
+static int enctype =3D 0;
 static char *acquire_name;
 static char *acquire_type;
+static char *target_name;
 static char *name_type;
 static char *ccache;
+static int num_loops =3D 1;
=20
 static struct getargs args[] =3D {
     {"acquire-name", 0,	arg_string,	&acquire_name, "name", NULL },
     {"acquire-type", 0,	arg_string,	&acquire_type, "type", NULL },
+    {"enctype", 0,	arg_integer,	&enctype, "enctype-num", NULL },
+    {"loops", 0,	arg_integer,	&num_loops, "enctype-num", NULL },
+    {"kerberos", 0,	arg_flag,	&kerberos_flag, "enctype-num", NULL },
+    {"target-name", 0,	arg_string,	&target_name, "name", NULL },
     {"ccache", 0,	arg_string,	&ccache, "name", NULL },
     {"name-type", 0,	arg_string,	&name_type, "type", NULL },
     {"version",	0,	arg_flag,	&version_flag, "print version", NULL },
@@ -194,14 +205,19 @@
 int
 main(int argc, char **argv)
 {
-    int optidx =3D 0;
+    gss_OID_set oidset =3D GSS_C_NULL_OID_SET;
+    gss_OID mechoid =3D GSS_C_NO_OID;
+    OM_uint32 maj_stat, min_stat;
+    gss_cred_id_t cred;
+    gss_name_t target =3D GSS_C_NO_NAME;
+    int i, optidx =3D 0;
     OM_uint32 flag;
     gss_OID type;
=20
     setprogname(argv[0]);
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -227,7 +243,7 @@
 	    errx(1, "unknown type %s", acquire_type);
     } else
 	flag =3D GSS_C_ACCEPT;
-=09
+
     if (name_type) {
 	if (strcasecmp("hostbased-service", name_type) =3D=3D 0)
 	    type =3D GSS_C_NT_HOSTBASED_SERVICE;
@@ -239,15 +255,75 @@
 	type =3D GSS_C_NT_HOSTBASED_SERVICE;
=20
     if (ccache) {
-	OM_uint32 major_status, minor_status;
-	major_status =3D gss_krb5_ccache_name(&minor_status,
-					    ccache, NULL);
-	if (GSS_ERROR(major_status))
-	    errx(1, "gss_krb5_ccache_name %s",=20
-		 gssapi_err(major_status, minor_status, GSS_C_NO_OID));
+	maj_stat =3D gss_krb5_ccache_name(&min_stat, ccache, NULL);
+	if (GSS_ERROR(maj_stat))
+	    errx(1, "gss_krb5_ccache_name %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
     }
=20
-    acquire_cred_service(acquire_name, type, flag);
+    if (kerberos_flag) {
+	mechoid =3D GSS_KRB5_MECHANISM;
+
+	maj_stat =3D gss_create_empty_oid_set(&min_stat, &oidset);
+	if (maj_stat !=3D GSS_S_COMPLETE)
+	    errx(1, "gss_create_empty_oid_set: %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+	maj_stat =3D gss_add_oid_set_member(&min_stat, GSS_KRB5_MECHANISM, &oidse=
t);
+	if (maj_stat !=3D GSS_S_COMPLETE)
+	    errx(1, "gss_add_oid_set_member: %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+    }
+
+    if (target_name) {
+	gss_buffer_desc name;
+
+	name.value =3D target_name;
+	name.length =3D strlen(target_name);
+	maj_stat =3D gss_import_name(&min_stat, &name,
+				   GSS_C_NT_HOSTBASED_SERVICE, &target);
+	if (maj_stat !=3D GSS_S_COMPLETE)
+	    errx(1, "gss_import_name: %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+    }
+
+    for (i =3D 0; i < num_loops; i++) {
+
+	cred =3D acquire_cred_service(acquire_name, type, oidset, flag);
+
+	if (enctype) {
+	    int32_t enctypelist =3D enctype;
+
+	    maj_stat =3D gss_krb5_set_allowable_enctypes(&min_stat, cred,
+						       1, &enctypelist);
+	    if (maj_stat)
+		errx(1, "gss_krb5_set_allowable_enctypes: %s",
+		     gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+	}
+
+	if (target) {
+	    gss_ctx_id_t context =3D GSS_C_NO_CONTEXT;
+	    gss_buffer_desc out;
+
+	    out.length =3D 0;
+	    out.value =3D NULL;
+
+	    maj_stat =3D gss_init_sec_context(&min_stat,
+					    cred, &context,
+					    target, mechoid,
+					    GSS_C_MUTUAL_FLAG, 0, NULL,
+					    GSS_C_NO_BUFFER, NULL,
+					    &out, NULL, NULL);
+	    if (maj_stat !=3D GSS_S_COMPLETE && maj_stat !=3D GSS_S_CONTINUE_NEED=
ED)
+		errx(1, "init_sec_context failed: %s",
+		     gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+
+	    gss_release_buffer(&min_stat, &out);
+	    gss_delete_sec_context(&min_stat, &context, NULL);
+	}
+	gss_release_cred(&min_stat, &cred);
+    }
+
=20
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_co=
mmon.c
--- a/head/crypto/heimdal/lib/gssapi/test_common.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/gssapi/test_common.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -35,8 +35,6 @@
 #include <err.h>
 #include "test_common.h"
=20
-RCSID("$Id: test_common.c 20075 2007-01-31 06:05:19Z lha $");
-
 char *
 gssapi_err(OM_uint32 maj_stat, OM_uint32 min_stat, gss_OID mech)
 {
@@ -51,20 +49,21 @@
 	maj_error_message.value =3D NULL;
 	min_error_message.length =3D 0;
 	min_error_message.value =3D NULL;
-=09
-	disp_maj_stat =3D gss_display_status(&disp_min_stat, maj_stat,=20
+
+	disp_maj_stat =3D gss_display_status(&disp_min_stat, maj_stat,
 					   GSS_C_GSS_CODE,
 					   mech, &msg_ctx, &maj_error_message);
 	disp_maj_stat =3D gss_display_status(&disp_min_stat, min_stat,
 					   GSS_C_MECH_CODE,
 					   mech, &msg_ctx, &min_error_message);
-	asprintf(&ret, "gss-code: %lu %.*s\nmech-code: %lu %.*s",=20
-		 (unsigned long)maj_stat,
-		 (int)maj_error_message.length,=20
-		 (char *)maj_error_message.value,=20
-		 (unsigned long)min_stat,
-		 (int)min_error_message.length,=20
-		 (char *)min_error_message.value);
+	if (asprintf(&ret, "gss-code: %lu %.*s -- mech-code: %lu %.*s",
+		     (unsigned long)maj_stat,
+		     (int)maj_error_message.length,
+		     (char *)maj_error_message.value,
+		     (unsigned long)min_stat,
+		     (int)min_error_message.length,
+		     (char *)min_error_message.value) < 0 || ret =3D=3D NULL)
+	    errx(1, "malloc");
=20
 	gss_release_buffer(&disp_min_stat, &maj_error_message);
 	gss_release_buffer(&disp_min_stat, &min_error_message);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_co=
mmon.h
--- a/head/crypto/heimdal/lib/gssapi/test_common.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/gssapi/test_common.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -31,6 +31,6 @@
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
=20
-/* $Id: test_common.h 20075 2007-01-31 06:05:19Z lha $ */
+/* $Id$ */
=20
 char * gssapi_err(OM_uint32, OM_uint32, gss_OID);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_co=
ntext.c
--- a/head/crypto/heimdal/lib/gssapi/test_context.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/gssapi/test_context.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,41 +34,67 @@
 #include "krb5/gsskrb5_locl.h"
 #include <err.h>
 #include <getarg.h>
+#include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
+#include <gssapi_ntlm.h>
 #include "test_common.h"
=20
-RCSID("$Id: test_context.c 20075 2007-01-31 06:05:19Z lha $");
-
 static char *type_string;
 static char *mech_string;
 static char *ret_mech_string;
+static char *client_name;
+static char *client_password;
 static int dns_canon_flag =3D -1;
 static int mutual_auth_flag =3D 0;
 static int dce_style_flag =3D 0;
 static int wrapunwrap_flag =3D 0;
+static int iov_flag =3D 0;
 static int getverifymic_flag =3D 0;
 static int deleg_flag =3D 0;
+static int policy_deleg_flag =3D 0;
+static int server_no_deleg_flag =3D 0;
+static int ei_flag =3D 0;
+static char *gsskrb5_acceptor_identity =3D NULL;
+static char *session_enctype_string =3D NULL;
+static int client_time_offset =3D 0;
+static int server_time_offset =3D 0;
+static int max_loops =3D 0;
+static char *limit_enctype_string =3D NULL;
 static int version_flag =3D 0;
 static int verbose_flag =3D 0;
 static int help_flag	=3D 0;
=20
+static krb5_context context;
+static krb5_enctype limit_enctype =3D 0;
+
 static struct {
     const char *name;
-    gss_OID *oid;
+    gss_OID oid;
 } o2n[] =3D {
-    { "krb5", &GSS_KRB5_MECHANISM },
-    { "spnego", &GSS_SPNEGO_MECHANISM },
-    { "ntlm", &GSS_NTLM_MECHANISM },
-    { "sasl-digest-md5", &GSS_SASL_DIGEST_MD5_MECHANISM }
+    { "krb5", NULL /* GSS_KRB5_MECHANISM */ },
+    { "spnego", NULL /* GSS_SPNEGO_MECHANISM */ },
+    { "ntlm", NULL /* GSS_NTLM_MECHANISM */ },
+    { "sasl-digest-md5", NULL /* GSS_SASL_DIGEST_MD5_MECHANISM */ }
 };
=20
+static void
+init_o2n(void)
+{
+    o2n[0].oid =3D GSS_KRB5_MECHANISM;
+    o2n[1].oid =3D GSS_SPNEGO_MECHANISM;
+    o2n[2].oid =3D GSS_NTLM_MECHANISM;
+    o2n[3].oid =3D GSS_SASL_DIGEST_MD5_MECHANISM;
+}
+
 static gss_OID
 string_to_oid(const char *name)
 {
     int i;
     for (i =3D 0; i < sizeof(o2n)/sizeof(o2n[0]); i++)
 	if (strcasecmp(name, o2n[i].name) =3D=3D 0)
-	    return *o2n[i].oid;
-    errx(1, "name %s not unknown", name);
+	    return o2n[i].oid;
+    errx(1, "name '%s' not unknown", name);
 }
=20
 static const char *
@@ -76,7 +102,7 @@
 {
     int i;
     for (i =3D 0; i < sizeof(o2n)/sizeof(o2n[0]); i++)
-	if (gss_oid_equal(oid, *o2n[i].oid))
+	if (gss_oid_equal(oid, o2n[i].oid))
 	    return o2n[i].name;
     return "unknown oid";
 }
@@ -86,16 +112,17 @@
      gss_OID nameoid, const char *target,
      gss_cred_id_t init_cred,
      gss_ctx_id_t *sctx, gss_ctx_id_t *cctx,
-     gss_OID *actual_mech,=20
+     gss_OID *actual_mech,
      gss_cred_id_t *deleg_cred)
 {
     int server_done =3D 0, client_done =3D 0;
+    int num_loops =3D 0;
     OM_uint32 maj_stat, min_stat;
     gss_name_t gss_target_name;
     gss_buffer_desc input_token, output_token;
     OM_uint32 flags =3D 0, ret_cflags, ret_sflags;
-    gss_OID actual_mech_client;=20
-    gss_OID actual_mech_server;=20
+    gss_OID actual_mech_client;
+    gss_OID actual_mech_server;
=20
     *actual_mech =3D GSS_C_NO_OID;
=20
@@ -108,6 +135,8 @@
 	flags |=3D GSS_C_DCE_STYLE;
     if (deleg_flag)
 	flags |=3D GSS_C_DELEG_FLAG;
+    if (policy_deleg_flag)
+	flags |=3D GSS_C_DELEG_POLICY_FLAG;
=20
     input_token.value =3D rk_UNCONST(target);
     input_token.length =3D strlen(target);
@@ -123,14 +152,17 @@
     input_token.value =3D NULL;
=20
     while (!server_done || !client_done) {
+	num_loops++;
+
+	gsskrb5_set_time_offset(client_time_offset);
=20
 	maj_stat =3D gss_init_sec_context(&min_stat,
 					init_cred,
 					cctx,
 					gss_target_name,
-					mechoid,=20
+					mechoid,
 					flags,
-					0,=20
+					0,
 					NULL,
 					&input_token,
 					&actual_mech_client,
@@ -145,12 +177,16 @@
 	else
 	    client_done =3D 1;
=20
+	gsskrb5_get_time_offset(&client_time_offset);
+
 	if (client_done && server_done)
 	    break;
=20
 	if (input_token.length !=3D 0)
 	    gss_release_buffer(&min_stat, &input_token);
=20
+	gsskrb5_set_time_offset(server_time_offset);
+
 	maj_stat =3D gss_accept_sec_context(&min_stat,
 					  sctx,
 					  GSS_C_NO_CREDENTIAL,
@@ -166,8 +202,7 @@
 		errx(1, "accept_sec_context: %s",
 		     gssapi_err(maj_stat, min_stat, actual_mech_server));
=20
-	if (verbose_flag)
-	    printf("%.*s", (int)input_token.length, (char *)input_token.value);
+	gsskrb5_get_time_offset(&server_time_offset);
=20
 	if (output_token.length !=3D 0)
 	    gss_release_buffer(&min_stat, &output_token);
@@ -176,24 +211,42 @@
 	    ;
 	else
 	    server_done =3D 1;
-    }=09
+    }
     if (output_token.length !=3D 0)
 	gss_release_buffer(&min_stat, &output_token);
     if (input_token.length !=3D 0)
 	gss_release_buffer(&min_stat, &input_token);
     gss_release_name(&min_stat, &gss_target_name);
=20
+    if (deleg_flag || policy_deleg_flag) {
+	if (server_no_deleg_flag) {
+	    if (*deleg_cred !=3D GSS_C_NO_CREDENTIAL)
+		errx(1, "got delegated cred but didn't expect one");
+	} else if (*deleg_cred =3D=3D GSS_C_NO_CREDENTIAL)
+	    errx(1, "asked for delegarated cred but did get one");
+    } else if (*deleg_cred !=3D GSS_C_NO_CREDENTIAL)
+	  errx(1, "got deleg_cred cred but didn't ask");
+
     if (gss_oid_equal(actual_mech_server, actual_mech_client) =3D=3D 0)
 	errx(1, "mech mismatch");
     *actual_mech =3D actual_mech_server;
+
+    if (max_loops && num_loops > max_loops)
+	errx(1, "num loops %d was lager then max loops %d",
+	     num_loops, max_loops);
+
+    if (verbose_flag) {
+	printf("server time offset: %d\n", server_time_offset);
+	printf("client time offset: %d\n", client_time_offset);
+	printf("num loops %d\n", num_loops);
+    }
 }
=20
 static void
-wrapunwrap(gss_ctx_id_t cctx, gss_ctx_id_t sctx, gss_OID mechoid)
+wrapunwrap(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID mechoi=
d)
 {
     gss_buffer_desc input_token, output_token, output_token2;
     OM_uint32 min_stat, maj_stat;
-    int32_t flags =3D 0;
     gss_qop_t qop_state;
     int conf_state;
=20
@@ -211,6 +264,155 @@
     if (maj_stat !=3D GSS_S_COMPLETE)
 	errx(1, "gss_unwrap failed: %s",
 	     gssapi_err(maj_stat, min_stat, mechoid));
+
+    gss_release_buffer(&min_stat, &output_token);
+    gss_release_buffer(&min_stat, &output_token2);
+
+#if 0 /* doesn't work for NTLM yet */
+    if (!!conf_state !=3D !!flags)
+	errx(1, "conf_state mismatch");
+#endif
+}
+
+#define USE_CONF		1
+#define USE_HEADER_ONLY		2
+#define USE_SIGN_ONLY		4
+#define FORCE_IOV		8
+
+static void
+wrapunwrap_iov(gss_ctx_id_t cctx, gss_ctx_id_t sctx, int flags, gss_OID me=
choid)
+{
+    krb5_data token, header, trailer;
+    OM_uint32 min_stat, maj_stat;
+    gss_qop_t qop_state;
+    int conf_state, conf_state2;
+    gss_iov_buffer_desc iov[6];
+    unsigned char *p;
+    int iov_len;
+    char header_data[9] =3D "ABCheader";
+    char trailer_data[10] =3D "trailerXYZ";
+
+    char token_data[16] =3D "0123456789abcdef";
+
+    memset(&iov, 0, sizeof(iov));
+
+    if (flags & USE_SIGN_ONLY) {
+	header.data =3D header_data;
+	header.length =3D 9;
+	trailer.data =3D trailer_data;
+	trailer.length =3D 10;
+    } else {
+	header.data =3D NULL;
+	header.length =3D 0;
+	trailer.data =3D NULL;
+	trailer.length =3D 0;
+    }
+
+    token.data =3D token_data;
+    token.length =3D 16;
+
+    iov_len =3D sizeof(iov)/sizeof(iov[0]);
+
+    memset(iov, 0, sizeof(iov));
+
+    iov[0].type =3D GSS_IOV_BUFFER_TYPE_HEADER | GSS_IOV_BUFFER_TYPE_FLAG_=
ALLOCATE;
+
+    if (header.length !=3D 0) {
+	iov[1].type =3D GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+	iov[1].buffer.length =3D header.length;
+	iov[1].buffer.value =3D header.data;
+    } else {
+	iov[1].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+	iov[1].buffer.length =3D 0;
+	iov[1].buffer.value =3D NULL;
+    }
+    iov[2].type =3D GSS_IOV_BUFFER_TYPE_DATA;
+    iov[2].buffer.length =3D token.length;
+    iov[2].buffer.value =3D token.data;
+    if (trailer.length !=3D 0) {
+	iov[3].type =3D GSS_IOV_BUFFER_TYPE_SIGN_ONLY;
+	iov[3].buffer.length =3D trailer.length;
+	iov[3].buffer.value =3D trailer.data;
+    } else {
+	iov[3].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+	iov[3].buffer.length =3D 0;
+	iov[3].buffer.value =3D NULL;
+    }
+    if (dce_style_flag) {
+	iov[4].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+    } else {
+	iov[4].type =3D GSS_IOV_BUFFER_TYPE_PADDING | GSS_IOV_BUFFER_TYPE_FLAG_AL=
LOCATE;
+    }
+    iov[4].buffer.length =3D 0;
+    iov[4].buffer.value =3D 0;
+    if (dce_style_flag) {
+	iov[5].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+    } else if (flags & USE_HEADER_ONLY) {
+	iov[5].type =3D GSS_IOV_BUFFER_TYPE_EMPTY;
+    } else {
+	iov[5].type =3D GSS_IOV_BUFFER_TYPE_TRAILER | GSS_IOV_BUFFER_TYPE_FLAG_AL=
LOCATE;
+    }
+    iov[5].buffer.length =3D 0;
+    iov[5].buffer.value =3D 0;
+
+    maj_stat =3D gss_wrap_iov(&min_stat, cctx, dce_style_flag || flags & U=
SE_CONF, 0, &conf_state,
+			    iov, iov_len);
+    if (maj_stat !=3D GSS_S_COMPLETE)
+	errx(1, "gss_wrap_iov failed");
+
+    token.length =3D
+	iov[0].buffer.length +
+	iov[1].buffer.length +
+	iov[2].buffer.length +
+	iov[3].buffer.length +
+	iov[4].buffer.length +
+	iov[5].buffer.length;
+    token.data =3D emalloc(token.length);
+
+    p =3D token.data;
+    memcpy(p, iov[0].buffer.value, iov[0].buffer.length);
+    p +=3D iov[0].buffer.length;
+    memcpy(p, iov[1].buffer.value, iov[1].buffer.length);
+    p +=3D iov[1].buffer.length;
+    memcpy(p, iov[2].buffer.value, iov[2].buffer.length);
+    p +=3D iov[2].buffer.length;
+    memcpy(p, iov[3].buffer.value, iov[3].buffer.length);
+    p +=3D iov[3].buffer.length;
+    memcpy(p, iov[4].buffer.value, iov[4].buffer.length);
+    p +=3D iov[4].buffer.length;
+    memcpy(p, iov[5].buffer.value, iov[5].buffer.length);
+    p +=3D iov[5].buffer.length;
+
+    assert(p - ((unsigned char *)token.data) =3D=3D token.length);
+
+    if ((flags & (USE_SIGN_ONLY|FORCE_IOV)) =3D=3D 0) {
+	gss_buffer_desc input, output;
+
+	input.value =3D token.data;
+	input.length =3D token.length;
+
+	maj_stat =3D gss_unwrap(&min_stat, sctx, &input,
+			      &output, &conf_state2, &qop_state);
+
+	if (maj_stat !=3D GSS_S_COMPLETE)
+	    errx(1, "gss_unwrap from gss_wrap_iov failed: %s",
+		 gssapi_err(maj_stat, min_stat, mechoid));
+
+	gss_release_buffer(&min_stat, &output);
+    } else {
+	maj_stat =3D gss_unwrap_iov(&min_stat, sctx, &conf_state2, &qop_state,
+				  iov, iov_len);
+
+	if (maj_stat !=3D GSS_S_COMPLETE)
+	    errx(1, "gss_unwrap_iov failed: %x %s", flags,
+		 gssapi_err(maj_stat, min_stat, mechoid));
+
+    }
+    if (conf_state2 !=3D conf_state)
+	errx(1, "conf state wrong for iov: %x", flags);
+
+
+    free(token.data);
 }
=20
 static void
@@ -234,8 +436,24 @@
     if (maj_stat !=3D GSS_S_COMPLETE)
 	errx(1, "gss_verify_mic failed: %s",
 	     gssapi_err(maj_stat, min_stat, mechoid));
+
+    gss_release_buffer(&min_stat, &output_token);
 }
=20
+static void
+empty_release(void)
+{
+    gss_ctx_id_t ctx =3D GSS_C_NO_CONTEXT;
+    gss_cred_id_t cred =3D GSS_C_NO_CREDENTIAL;
+    gss_name_t name =3D GSS_C_NO_NAME;
+    gss_OID_set oidset =3D GSS_C_NO_OID_SET;
+    OM_uint32 junk;
+
+    gss_delete_sec_context(&junk, &ctx, NULL);
+    gss_release_cred(&junk, &cred);
+    gss_release_name(&junk, &name);
+    gss_release_oid_set(&junk, &oidset);
+}
=20
 /*
  *
@@ -246,14 +464,27 @@
     {"mech-type",0,	arg_string, &mech_string,  "type of mech", NULL },
     {"ret-mech-type",0,	arg_string, &ret_mech_string,
      "type of return mech", NULL },
-    {"dns-canonicalize",0,arg_negative_flag, &dns_canon_flag,=20
+    {"dns-canonicalize",0,arg_negative_flag, &dns_canon_flag,
      "use dns to canonicalize", NULL },
     {"mutual-auth",0,	arg_flag,	&mutual_auth_flag,"mutual auth", NULL },
+    {"client-name", 0,  arg_string,     &client_name, "client name", NULL =
},
+    {"client-password", 0,  arg_string, &client_password, "client password=
", NULL },
+    {"limit-enctype",0,	arg_string,	&limit_enctype_string, "enctype", NULL=
 },
     {"dce-style",0,	arg_flag,	&dce_style_flag, "dce-style", NULL },
     {"wrapunwrap",0,	arg_flag,	&wrapunwrap_flag, "wrap/unwrap", NULL },
-    {"getverifymic",0,	arg_flag,	&getverifymic_flag,=20
+    {"iov", 0, 		arg_flag,	&iov_flag, "wrap/unwrap iov", NULL },
+    {"getverifymic",0,	arg_flag,	&getverifymic_flag,
      "get and verify mic", NULL },
     {"delegate",0,	arg_flag,	&deleg_flag, "delegate credential", NULL },
+    {"policy-delegate",0,	arg_flag,	&policy_deleg_flag, "policy delegate c=
redential", NULL },
+    {"server-no-delegate",0,	arg_flag,	&server_no_deleg_flag,
+     "server should get a credential", NULL },
+    {"export-import-cred",0,	arg_flag,	&ei_flag, "test export/import cred"=
, NULL },
+    {"gsskrb5-acceptor-identity", 0, arg_string, &gsskrb5_acceptor_identit=
y, "keytab", NULL },
+    {"session-enctype",	0, arg_string,	&session_enctype_string, "enctype",=
 NULL },
+    {"client-time-offset",	0, arg_integer,	&client_time_offset, "time", NU=
LL },
+    {"server-time-offset",	0, arg_integer,	&server_time_offset, "time", NU=
LL },
+    {"max-loops",	0, arg_integer,	&max_loops, "time", NULL },
     {"version",	0,	arg_flag,	&version_flag, "print version", NULL },
     {"verbose",	'v',	arg_flag,	&verbose_flag, "verbose", NULL },
     {"help",	0,	arg_flag,	&help_flag,  NULL, NULL }
@@ -274,16 +505,23 @@
     OM_uint32 min_stat, maj_stat;
     gss_ctx_id_t cctx, sctx;
     void *ctx;
-    gss_OID nameoid, mechoid, actual_mech;
-    gss_cred_id_t deleg_cred =3D GSS_C_NO_CREDENTIAL;
+    gss_OID nameoid, mechoid, actual_mech, actual_mech2;
+    gss_cred_id_t client_cred =3D GSS_C_NO_CREDENTIAL, deleg_cred =3D GSS_=
C_NO_CREDENTIAL;
+    gss_name_t cname =3D GSS_C_NO_NAME;
+    gss_buffer_desc credential_data =3D GSS_C_EMPTY_BUFFER;
=20
     setprogname(argv[0]);
=20
+    init_o2n();
+
+    if (krb5_init_context(&context))
+	errx(1, "krb5_init_context");
+
     cctx =3D sctx =3D GSS_C_NO_CONTEXT;
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optind))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -312,12 +550,85 @@
=20
     if (mech_string =3D=3D NULL)
 	mechoid =3D GSS_KRB5_MECHANISM;
-    else=20
+    else
 	mechoid =3D string_to_oid(mech_string);
=20
-    loop(mechoid, nameoid, argv[0], GSS_C_NO_CREDENTIAL,
+    if (gsskrb5_acceptor_identity) {
+	maj_stat =3D gsskrb5_register_acceptor_identity(gsskrb5_acceptor_identity=
);
+	if (maj_stat)
+	    errx(1, "gsskrb5_acceptor_identity: %s",
+		 gssapi_err(maj_stat, 0, GSS_C_NO_OID));
+    }
+
+    if (client_password) {
+	credential_data.value =3D client_password;
+	credential_data.length =3D strlen(client_password);
+    }
+
+    if (client_name) {
+	gss_buffer_desc cn;
+
+	cn.value =3D client_name;
+	cn.length =3D strlen(client_name);
+
+	maj_stat =3D gss_import_name(&min_stat, &cn, GSS_C_NT_USER_NAME, &cname);
+	if (maj_stat)
+	    errx(1, "gss_import_name: %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+    }
+
+    if (client_password) {
+	maj_stat =3D gss_acquire_cred_with_password(&min_stat,
+						  cname,
+						  &credential_data,
+						  GSS_C_INDEFINITE,
+						  GSS_C_NO_OID_SET,
+						  GSS_C_INITIATE,
+						  &client_cred,
+						  NULL,
+						  NULL);
+	if (GSS_ERROR(maj_stat))
+	    errx(1, "gss_acquire_cred_with_password: %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+    } else {
+	maj_stat =3D gss_acquire_cred(&min_stat,
+				    cname,
+				    GSS_C_INDEFINITE,
+				    GSS_C_NO_OID_SET,
+				    GSS_C_INITIATE,
+				    &client_cred,
+				    NULL,
+				    NULL);
+	if (GSS_ERROR(maj_stat))
+	    errx(1, "gss_acquire_cred: %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+    }
+
+    if (limit_enctype_string) {
+	krb5_error_code ret;
+
+	ret =3D krb5_string_to_enctype(context,
+				     limit_enctype_string,
+				     &limit_enctype);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_string_to_enctype");
+    }
+
+
+    if (limit_enctype) {
+	if (client_cred =3D=3D NULL)
+	    errx(1, "client_cred missing");
+
+	maj_stat =3D gss_krb5_set_allowable_enctypes(&min_stat, client_cred,
+						   1, &limit_enctype);
+	if (maj_stat)
+	    errx(1, "gss_krb5_set_allowable_enctypes: %s",
+		 gssapi_err(maj_stat, min_stat, GSS_C_NO_OID));
+    }
+
+    loop(mechoid, nameoid, argv[0], client_cred,
 	 &sctx, &cctx, &actual_mech, &deleg_cred);
-   =20
+
     if (verbose_flag)
 	printf("resulting mech: %s\n", oid_to_string(actual_mech));
=20
@@ -327,43 +638,38 @@
 	retoid =3D string_to_oid(ret_mech_string);
=20
 	if (gss_oid_equal(retoid, actual_mech) =3D=3D 0)
-	    errx(1, "actual_mech mech is not the expected type %s",=20
+	    errx(1, "actual_mech mech is not the expected type %s",
 		 ret_mech_string);
     }
=20
     /* XXX should be actual_mech */
-    if (gss_oid_equal(mechoid, GSS_KRB5_MECHANISM)) {=20
-	krb5_context context;
-	time_t time, skew;
+    if (gss_oid_equal(mechoid, GSS_KRB5_MECHANISM)) {
+	time_t time;
 	gss_buffer_desc authz_data;
 	gss_buffer_desc in, out1, out2;
 	krb5_keyblock *keyblock, *keyblock2;
 	krb5_timestamp now;
 	krb5_error_code ret;
=20
-	ret =3D krb5_init_context(&context);
+	ret =3D krb5_timeofday(context, &now);
 	if (ret)
-	    errx(1, "krb5_init_context");
+	    errx(1, "krb5_timeofday failed");
=20
-	ret =3D krb5_timeofday(context, &now);
-	if (ret)=20
-		errx(1, "krb5_timeofday failed");
-=09
 	/* client */
 	maj_stat =3D gss_krb5_export_lucid_sec_context(&min_stat,
 						     &cctx,
 						     1, /* version */
 						     &ctx);
 	if (maj_stat !=3D GSS_S_COMPLETE)
-		errx(1, "gss_krb5_export_lucid_sec_context failed: %s",
-		     gssapi_err(maj_stat, min_stat, actual_mech));
-=09
-=09
+	    errx(1, "gss_krb5_export_lucid_sec_context failed: %s",
+		 gssapi_err(maj_stat, min_stat, actual_mech));
+
+
 	maj_stat =3D gss_krb5_free_lucid_sec_context(&maj_stat, ctx);
 	if (maj_stat !=3D GSS_S_COMPLETE)
 	    errx(1, "gss_krb5_free_lucid_sec_context failed: %s",
 		     gssapi_err(maj_stat, min_stat, actual_mech));
-=09
+
 	/* server */
 	maj_stat =3D gss_krb5_export_lucid_sec_context(&min_stat,
 						     &sctx,
@@ -384,13 +690,10 @@
 	    errx(1, "gsskrb5_extract_authtime_from_sec_context failed: %s",
 		     gssapi_err(maj_stat, min_stat, actual_mech));
=20
-	skew =3D abs(time - now);
-	if (skew > krb5_get_max_time_skew(context)) {
+	if (time > now)
 	    errx(1, "gsskrb5_extract_authtime_from_sec_context failed: "
-		 "time skew too great %llu > %llu",=20
-		 (unsigned long long)skew,=20
-		 (unsigned long long)krb5_get_max_time_skew(context));
-	}
+		 "time authtime is before now: %ld %ld",
+		 (long)time, (long)now);
=20
  	maj_stat =3D gsskrb5_extract_service_keyblock(&min_stat,
 						    sctx,
@@ -404,24 +707,28 @@
  	maj_stat =3D gsskrb5_get_subkey(&min_stat,
 				      sctx,
 				      &keyblock);
-	if (maj_stat !=3D GSS_S_COMPLETE=20
+	if (maj_stat !=3D GSS_S_COMPLETE
 	    && (!(maj_stat =3D=3D GSS_S_FAILURE && min_stat =3D=3D GSS_KRB5_S_KG_=
NO_SUBKEY)))
 	    errx(1, "gsskrb5_get_subkey server failed: %s",
 		     gssapi_err(maj_stat, min_stat, actual_mech));
=20
 	if (maj_stat !=3D GSS_S_COMPLETE)
 	    keyblock =3D NULL;
-=09
+	else if (limit_enctype && keyblock->keytype !=3D limit_enctype)
+	    errx(1, "gsskrb5_get_subkey wrong enctype");
+
  	maj_stat =3D gsskrb5_get_subkey(&min_stat,
 				      cctx,
 				      &keyblock2);
-	if (maj_stat !=3D GSS_S_COMPLETE=20
+	if (maj_stat !=3D GSS_S_COMPLETE
 	    && (!(maj_stat =3D=3D GSS_S_FAILURE && min_stat =3D=3D GSS_KRB5_S_KG_=
NO_SUBKEY)))
 	    errx(1, "gsskrb5_get_subkey client failed: %s",
 		     gssapi_err(maj_stat, min_stat, actual_mech));
=20
 	if (maj_stat !=3D GSS_S_COMPLETE)
 	    keyblock2 =3D NULL;
+	else if (limit_enctype && keyblock->keytype !=3D limit_enctype)
+	    errx(1, "gsskrb5_get_subkey wrong enctype");
=20
 	if (keyblock || keyblock2) {
 	    if (keyblock =3D=3D NULL)
@@ -433,11 +740,26 @@
 		errx(1, "enctype mismatch");
 	    if (keyblock->keyvalue.length !=3D keyblock2->keyvalue.length)
 		errx(1, "key length mismatch");
-	    if (memcmp(keyblock->keyvalue.data, keyblock2->keyvalue.data,=20
+	    if (memcmp(keyblock->keyvalue.data, keyblock2->keyvalue.data,
 		       keyblock2->keyvalue.length) !=3D 0)
 		errx(1, "key data mismatch");
 	}
=20
+	if (session_enctype_string) {
+	    krb5_enctype enctype;
+
+	    ret =3D krb5_string_to_enctype(context,
+					 session_enctype_string,
+					 &enctype);
+
+	    if (ret)
+		krb5_err(context, 1, ret, "krb5_string_to_enctype");
+
+	    if (enctype !=3D keyblock->keytype)
+		errx(1, "keytype is not the expected %d !=3D %d",
+		     (int)enctype, (int)keyblock2->keytype);
+	}
+
 	if (keyblock)
 	    krb5_free_keyblock(context, keyblock);
 	if (keyblock2)
@@ -446,13 +768,17 @@
  	maj_stat =3D gsskrb5_get_initiator_subkey(&min_stat,
 						sctx,
 						&keyblock);
-	if (maj_stat !=3D GSS_S_COMPLETE=20
+	if (maj_stat !=3D GSS_S_COMPLETE
 	    && (!(maj_stat =3D=3D GSS_S_FAILURE && min_stat =3D=3D GSS_KRB5_S_KG_=
NO_SUBKEY)))
 	    errx(1, "gsskrb5_get_initiator_subkey failed: %s",
 		     gssapi_err(maj_stat, min_stat, actual_mech));
=20
-	if (maj_stat =3D=3D GSS_S_COMPLETE)
+	if (maj_stat =3D=3D GSS_S_COMPLETE) {
+
+	    if (limit_enctype && keyblock->keytype !=3D limit_enctype)
+		errx(1, "gsskrb5_get_initiator_subkey wrong enctype");
 	    krb5_free_keyblock(context, keyblock);
+	}
=20
  	maj_stat =3D gsskrb5_extract_authz_data_from_sec_context(&min_stat,
 							       sctx,
@@ -461,8 +787,6 @@
 	if (maj_stat =3D=3D GSS_S_COMPLETE)
 	    gss_release_buffer(&min_stat, &authz_data);
=20
-	krb5_free_context(context);
-
=20
 	memset(&out1, 0, sizeof(out1));
 	memset(&out2, 0, sizeof(out2));
@@ -470,19 +794,19 @@
 	in.value =3D "foo";
 	in.length =3D 3;
=20
-	gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in,=20
+	gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in,
 			  100, &out1);
-	gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_FULL, &in,=20
+	gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_FULL, &in,
 			  100, &out2);
=20
 	if (out1.length !=3D out2.length)
 	    errx(1, "prf len mismatch");
 	if (memcmp(out1.value, out2.value, out1.length) !=3D 0)
 	    errx(1, "prf data mismatch");
-=09
+
 	gss_release_buffer(&min_stat, &out1);
=20
-	gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in,=20
+	gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_FULL, &in,
 			  100, &out1);
=20
 	if (out1.length !=3D out2.length)
@@ -496,9 +820,9 @@
 	in.value =3D "bar";
 	in.length =3D 3;
=20
-	gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_PARTIAL, &in,=20
+	gss_pseudo_random(&min_stat, sctx, GSS_C_PRF_KEY_PARTIAL, &in,
 			  100, &out1);
-	gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_PARTIAL, &in,=20
+	gss_pseudo_random(&min_stat, cctx, GSS_C_PRF_KEY_PARTIAL, &in,
 			  100, &out2);
=20
 	if (out1.length !=3D out2.length)
@@ -514,11 +838,48 @@
     }
=20
     if (wrapunwrap_flag) {
-	wrapunwrap(cctx, sctx, actual_mech);
-	wrapunwrap(cctx, sctx, actual_mech);
-	wrapunwrap(sctx, cctx, actual_mech);
-	wrapunwrap(sctx, cctx, actual_mech);
+	wrapunwrap(cctx, sctx, 0, actual_mech);
+	wrapunwrap(cctx, sctx, 1, actual_mech);
+	wrapunwrap(sctx, cctx, 0, actual_mech);
+	wrapunwrap(sctx, cctx, 1, actual_mech);
     }
+
+    if (iov_flag) {
+	wrapunwrap_iov(cctx, sctx, 0, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY, actual_mech);
+
+	wrapunwrap_iov(cctx, sctx, FORCE_IOV, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mec=
h);
+
+	wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|USE_SIGN_ONLY|FORCE_I=
OV, actual_mech);
+
+/* works */
+	wrapunwrap_iov(cctx, sctx, 0, actual_mech);
+	wrapunwrap_iov(cctx, sctx, FORCE_IOV, actual_mech);
+
+	wrapunwrap_iov(cctx, sctx, USE_CONF, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|FORCE_IOV, actual_mech);
+
+	wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_SIGN_ONLY|FORCE_IOV, actual_mech);
+
+	wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_HEADER_ONLY|FORCE_IOV, actual_mech);
+
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY, actual_mech);
+	wrapunwrap_iov(cctx, sctx, USE_CONF|USE_HEADER_ONLY|FORCE_IOV, actual_mec=
h);
+    }
+
     if (getverifymic_flag) {
 	getverifymic(cctx, sctx, actual_mech);
 	getverifymic(cctx, sctx, actual_mech);
@@ -526,17 +887,84 @@
 	getverifymic(sctx, cctx, actual_mech);
     }
=20
+
     gss_delete_sec_context(&min_stat, &cctx, NULL);
     gss_delete_sec_context(&min_stat, &sctx, NULL);
=20
     if (deleg_cred !=3D GSS_C_NO_CREDENTIAL) {
+	gss_cred_id_t cred2 =3D GSS_C_NO_CREDENTIAL;
+	gss_buffer_desc cb;
=20
-	loop(mechoid, nameoid, argv[0], deleg_cred, &cctx, &sctx, &actual_mech, N=
ULL);
+	if (verbose_flag)
+	    printf("checking actual mech (%s) on delegated cred\n",
+		   oid_to_string(actual_mech));
+	loop(actual_mech, nameoid, argv[0], deleg_cred, &sctx, &cctx, &actual_mec=
h2, &cred2);
=20
 	gss_delete_sec_context(&min_stat, &cctx, NULL);
 	gss_delete_sec_context(&min_stat, &sctx, NULL);
=20
+	gss_release_cred(&min_stat, &cred2);
+
+	/* try again using SPNEGO */
+	if (verbose_flag)
+	    printf("checking spnego on delegated cred\n");
+	loop(GSS_SPNEGO_MECHANISM, nameoid, argv[0], deleg_cred, &sctx, &cctx,
+	     &actual_mech2, &cred2);
+
+	gss_delete_sec_context(&min_stat, &cctx, NULL);
+	gss_delete_sec_context(&min_stat, &sctx, NULL);
+
+	gss_release_cred(&min_stat, &cred2);
+
+	/* check export/import */
+	if (ei_flag) {
+
+	    maj_stat =3D gss_export_cred(&min_stat, deleg_cred, &cb);
+	    if (maj_stat !=3D GSS_S_COMPLETE)
+		errx(1, "export failed: %s",
+		     gssapi_err(maj_stat, min_stat, NULL));
+
+	    maj_stat =3D gss_import_cred(&min_stat, &cb, &cred2);
+	    if (maj_stat !=3D GSS_S_COMPLETE)
+		errx(1, "import failed: %s",
+		     gssapi_err(maj_stat, min_stat, NULL));
+
+	    gss_release_buffer(&min_stat, &cb);
+	    gss_release_cred(&min_stat, &deleg_cred);
+
+	    if (verbose_flag)
+		printf("checking actual mech (%s) on export/imported cred\n",
+		       oid_to_string(actual_mech));
+	    loop(actual_mech, nameoid, argv[0], cred2, &sctx, &cctx,
+		 &actual_mech2, &deleg_cred);
+
+	    gss_release_cred(&min_stat, &deleg_cred);
+
+	    gss_delete_sec_context(&min_stat, &cctx, NULL);
+	    gss_delete_sec_context(&min_stat, &sctx, NULL);
+
+	    /* try again using SPNEGO */
+	    if (verbose_flag)
+		printf("checking SPNEGO on export/imported cred\n");
+	    loop(GSS_SPNEGO_MECHANISM, nameoid, argv[0], cred2, &sctx, &cctx,
+		 &actual_mech2, &deleg_cred);
+
+	    gss_release_cred(&min_stat, &deleg_cred);
+
+	    gss_delete_sec_context(&min_stat, &cctx, NULL);
+	    gss_delete_sec_context(&min_stat, &sctx, NULL);
+
+	    gss_release_cred(&min_stat, &cred2);
+
+	} else  {
+	    gss_release_cred(&min_stat, &deleg_cred);
+	}
+
     }
=20
+    empty_release();
+
+    krb5_free_context(context);
+
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_cr=
ed.c
--- a/head/crypto/heimdal/lib/gssapi/test_cred.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/test_cred.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -35,17 +35,17 @@
 #include <config.h>
 #endif
=20
+#include <roken.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
 #include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
 #include <err.h>
-#include <roken.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_cred.c 17750 2006-06-30 11:55:28Z lha $");
-
 static void
 gss_print_errors (int min_stat)
 {
@@ -62,7 +62,8 @@
 				  &msg_ctx,
 				  &status_string);
 	if (!GSS_ERROR(ret)) {
-	    fprintf (stderr, "%s\n", (char *)status_string.value);
+	    fprintf (stderr, "%.*s\n", (int)status_string.length,
+					(char *)status_string.value);
 	    gss_release_buffer (&new_stat, &status_string);
 	}
     } while (!GSS_ERROR(ret) && msg_ctx !=3D 0);
@@ -96,12 +97,12 @@
 				    NULL,
 				    NULL);
 	if (maj_stat !=3D GSS_S_COMPLETE)
-	    gss_err(1, min_stat, "aquire %d %d !=3D GSS_S_COMPLETE",=20
+	    gss_err(1, min_stat, "aquire %d %d !=3D GSS_S_COMPLETE",
 		    i, (int)maj_stat);
-				   =20
+
 	maj_stat =3D gss_release_cred(&min_stat, &cred);
 	if (maj_stat !=3D GSS_S_COMPLETE)
-	    gss_err(1, min_stat, "release %d %d !=3D GSS_S_COMPLETE",=20
+	    gss_err(1, min_stat, "release %d %d !=3D GSS_S_COMPLETE",
 		    i, (int)maj_stat);
     }
 }
@@ -122,7 +123,7 @@
 				NULL);
     if (maj_stat !=3D GSS_S_COMPLETE)
 	gss_err(1, min_stat, "aquire %d !=3D GSS_S_COMPLETE", (int)maj_stat);
-   =20
+
     maj_stat =3D gss_add_cred(&min_stat,
 			    cred,
 			    GSS_C_NO_NAME,
@@ -134,7 +135,7 @@
 			    NULL,
 			    NULL,
 			    NULL);
-			   =20
+
     if (maj_stat !=3D GSS_S_COMPLETE)
 	gss_err(1, min_stat, "add_cred %d !=3D GSS_S_COMPLETE", (int)maj_stat);
=20
@@ -191,7 +192,7 @@
     setprogname(argv[0]);
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_kc=
red.c
--- a/head/crypto/heimdal/lib/gssapi/test_kcred.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/gssapi/test_kcred.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -35,18 +35,18 @@
 #include <config.h>
 #endif
=20
+#include <roken.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
 #include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
 #include <krb5.h>
 #include <err.h>
-#include <roken.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_kcred.c 20694 2007-05-30 13:58:46Z lha $");
-
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
@@ -79,9 +79,9 @@
     if (ret)
 	errx(1, "krb5_init_context");
=20
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &id);
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_cc_gen_new");
+	krb5_err(context, 1, ret, "krb5_cc_new_unique");
=20
     maj_stat =3D gss_krb5_copy_ccache(&min_stat, cred1, id);
     if (maj_stat !=3D GSS_S_COMPLETE)
@@ -101,7 +101,7 @@
 	errx(1, "gss_compare_name");
     if (!equal)
 	errx(1, "names not equal");
-=09
+
     if (lifetime1 !=3D lifetime2)
 	errx(1, "lifetime not equal %lu !=3D %lu",
 	     (unsigned long)lifetime1, (unsigned long)lifetime2);
@@ -125,7 +125,7 @@
 	errx(1, "gss_compare_name");
     if (!equal)
 	errx(1, "names not equal");
-=09
+
     if (lifetime1 !=3D lifetime2)
 	errx(1, "lifetime not equal %lu !=3D %lu",
 	     (unsigned long)lifetime1, (unsigned long)lifetime2);
@@ -168,7 +168,7 @@
     setprogname(argv[0]);
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_na=
mes.c
--- a/head/crypto/heimdal/lib/gssapi/test_names.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/gssapi/test_names.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -35,17 +35,17 @@
 #include <config.h>
 #endif
=20
+#include <roken.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
 #include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
 #include <err.h>
-#include <roken.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_names.c 17856 2006-07-20 05:13:25Z lha $");
-
 static void
 gss_print_errors (int min_stat)
 {
@@ -62,7 +62,8 @@
 				  &msg_ctx,
 				  &status_string);
 	if (!GSS_ERROR(ret)) {
-	    fprintf (stderr, "%s\n", (char *)status_string.value);
+	    fprintf (stderr, "%.*s\n", (int)status_string.length,
+					(char *)status_string.value);
 	    gss_release_buffer (&new_stat, &status_string);
 	}
     } while (!GSS_ERROR(ret) && msg_ctx !=3D 0);
@@ -110,7 +111,7 @@
     setprogname(argv[0]);
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -122,12 +123,15 @@
     argc -=3D optidx;
     argv +=3D optidx;
=20
+    gsskrb5_set_default_realm("MIT.EDU");
+
     /*
      * test import/export
      */
=20
+    str =3D NULL;
     len =3D asprintf(&str, "ftp at freeze-arrow.mit.edu");
-    if (len =3D=3D -1)
+    if (len < 0 || str =3D=3D NULL)
 	errx(1, "asprintf");
=20
     name_buffer.value =3D str;
@@ -180,8 +184,9 @@
      * Dovecot SASL lib does this.
      */
=20
+    str =3D NULL;
     len =3D asprintf(&str, "lha");
-    if (len =3D=3D -1)
+    if (len < 0 || str =3D=3D NULL)
 	errx(1, "asprintf");
=20
     name_buffer.value =3D str;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_nt=
lm.c
--- a/head/crypto/heimdal/lib/gssapi/test_ntlm.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/gssapi/test_ntlm.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 - 2008 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,22 +33,20 @@
=20
 #include "config.h"
=20
+#include <roken.h>
 #include <stdio.h>
 #include <gssapi.h>
 #include <err.h>
-#include <roken.h>
 #include <getarg.h>
 #include "test_common.h"
=20
-RCSID("$Id: test_ntlm.c 22423 2008-01-13 09:45:03Z lha $");
-
 #include <krb5.h>
 #include <heimntlm.h>
=20
 static int
 test_libntlm_v1(int flags)
 {
-    const char *user =3D "foo",=20
+    const char *user =3D "foo",
 	*domain =3D "mydomain",
 	*password =3D "digestpassword";
     OM_uint32 maj_stat, min_stat;
@@ -60,7 +58,7 @@
     struct ntlm_buf data;
     krb5_error_code ret;
     gss_name_t src_name =3D GSS_C_NO_NAME;
-   =20
+
     memset(&type1, 0, sizeof(type1));
     memset(&type2, 0, sizeof(type2));
     memset(&type3, 0, sizeof(type3));
@@ -120,7 +118,7 @@
 	heim_ntlm_nt_key(password, &key);
=20
 	heim_ntlm_calculate_ntlm1(key.data, key.length,
-				  type2.challange,
+				  type2.challenge,
 				  &type3.ntlm);
=20
 	if (flags & NTLM_NEG_KEYEX) {
@@ -175,7 +173,7 @@
 static int
 test_libntlm_v2(int flags)
 {
-    const char *user =3D "foo",=20
+    const char *user =3D "foo",
 	*domain =3D "mydomain",
 	*password =3D "digestpassword";
     OM_uint32 maj_stat, min_stat;
@@ -186,7 +184,7 @@
     struct ntlm_type3 type3;
     struct ntlm_buf data;
     krb5_error_code ret;
-   =20
+
     memset(&type1, 0, sizeof(type1));
     memset(&type2, 0, sizeof(type2));
     memset(&type3, 0, sizeof(type3));
@@ -247,7 +245,7 @@
 	heim_ntlm_calculate_ntlm2(key.data, key.length,
 				  user,
 				  type2.targetname,
-				  type2.challange,
+				  type2.challenge,
 				  &type2.targetinfo,
 				  ntlmv2,
 				  &type3.ntlm);
@@ -317,7 +315,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optind))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/test_oi=
d.c
--- a/head/crypto/heimdal/lib/gssapi/test_oid.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/gssapi/test_oid.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,46 +1,46 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifdef HAVE_CONFIG_H
 #include <config.h>
 #endif
=20
+#include <roken.h>
 #include <stdio.h>
 #include <gssapi.h>
+#include <gssapi_krb5.h>
+#include <gssapi_spnego.h>
 #include <err.h>
-#include <roken.h>
-
-RCSID("$Id: test_oid.c 20488 2007-04-21 06:29:11Z lha $");
=20
 int
 main(int argc, char **argv)
@@ -53,7 +53,7 @@
     if (GSS_ERROR(maj_stat))
 	errx(1, "gss_oid_to_str failed");
=20
-    ret =3D strcmp(data.value, "1 2 840 113554 1 2 2");
+    ret =3D strncmp(data.value, "1 2 840 113554 1 2 2", data.length);
     gss_release_buffer(&maj_stat, &data);
     if (ret)
 	return 1;
@@ -62,7 +62,7 @@
     if (GSS_ERROR(maj_stat))
 	errx(1, "gss_oid_to_str failed");
=20
-    ret =3D strcmp(data.value, "1 3 6 1 5 6 4");
+    ret =3D strncmp(data.value, "1 3 6 1 5 6 4", data.length);
     gss_release_buffer(&maj_stat, &data);
     if (ret)
 	return 1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/gssapi/version=
-script.map
--- a/head/crypto/heimdal/lib/gssapi/version-script.map	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/gssapi/version-script.map	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,96 +1,195 @@
-# $Id: version-script.map 20493 2007-04-21 07:56:20Z lha $
+# $Id$
=20
-HEIMDAL_GSS_1.0 {
+HEIMDAL_GSS_2.0 {
 	global:
-		GSS_KRB5_MECHANISM;
-		GSS_NTLM_MECHANISM;
-		GSS_SPNEGO_MECHANISM;
-		GSS_SASL_DIGEST_MD5_MECHANISM;
-		GSS_C_NT_ANONYMOUS;
-		GSS_C_NT_EXPORT_NAME;
-		GSS_C_NT_HOSTBASED_SERVICE;
-		GSS_C_NT_HOSTBASED_SERVICE_X;
-		GSS_C_NT_MACHINE_UID_NAME;
-		GSS_C_NT_STRING_UID_NAME;
-		GSS_C_NT_USER_NAME;
-		GSS_KRB5_NT_PRINCIPAL_NAME;
-		GSS_KRB5_NT_USER_NAME;
-		GSS_KRB5_NT_MACHINE_UID_NAME;
-		GSS_KRB5_NT_STRING_UID_NAME;
+#		__gss_c_nt_anonymous;
+		__gss_c_nt_anonymous_oid_desc;
+		__gss_c_nt_export_name_oid_desc;
+		__gss_c_nt_hostbased_service_oid_desc;
+		__gss_c_nt_hostbased_service_x_oid_desc;
+		__gss_c_nt_machine_uid_name_oid_desc;
+		__gss_c_nt_string_uid_name_oid_desc;
+		__gss_c_nt_user_name_oid_desc;
+		__gss_krb5_nt_principal_name_oid_desc;
+		__gss_c_attr_stream_sizes_oid_desc;
+		__gss_c_cred_password_oid_desc;
+		__gss_c_cred_certificate_oid_desc;
+		__gss_c_attr_local_login_user;
+		gss_accept_sec_context;
 		gss_acquire_cred;
+		gss_acquire_cred_with_password;
+		gss_add_buffer_set_member;
+		gss_add_cred;
+		gss_add_cred_with_password;
+		gss_add_oid_set_member;
+		gss_authorize_localname;
+		gss_canonicalize_name;
+		gss_compare_name;
+		gss_context_query_attributes;
+		gss_context_time;
+		gss_create_empty_buffer_set;
+		gss_create_empty_oid_set;
+		gss_decapsulate_token;
+		gss_delete_name_attribute;
+		gss_delete_sec_context;
+		gss_display_name;
+		gss_display_name_ext;
+		gss_display_status;
+		gss_duplicate_name;
+		gss_duplicate_oid;
+		gss_encapsulate_token;
+		gss_export_cred;
+		gss_export_name;
+		gss_export_name_composite;
+		gss_export_sec_context;
+		gss_get_mic;
+		gss_get_name_attribute;
+		gss_import_cred;
+		gss_import_name;
+		gss_import_sec_context;
+		gss_indicate_mechs;
+		gss_init_sec_context;
+		gss_inquire_context;
+		gss_inquire_cred;
+		gss_inquire_cred_by_mech;
+		gss_inquire_cred_by_oid;
+		gss_inquire_mechs_for_name;
+		gss_inquire_name;
+		gss_inquire_names_for_mech;
+		gss_inquire_sec_context_by_oid;
+		gss_inquire_sec_context_by_oid;
+		gss_krb5_ccache_name;
+		gss_krb5_copy_ccache;
+		gss_krb5_export_lucid_sec_context;
+		gss_krb5_free_lucid_sec_context;
+		gss_krb5_get_tkt_flags;
+		gss_krb5_import_cred;
+		gss_krb5_set_allowable_enctypes;
+		gss_mg_collect_error;
+		gss_oid_equal;
+		gss_oid_to_str;
+		gss_pname_to_uid;
+		gss_process_context_token;
+		gss_pseudo_random;
+		gss_release_buffer;
+		gss_release_buffer_set;
 		gss_release_cred;
-		gss_init_sec_context;
-		gss_accept_sec_context;
-		gss_process_context_token;
-		gss_delete_sec_context;
-		gss_context_time;
-		gss_get_mic;
+		gss_release_iov_buffer;
+		gss_release_name;
+		gss_release_oid;
+		gss_release_oid_set;
+		gss_seal;
+		gss_set_cred_option;
+		gss_set_name_attribute;
+		gss_set_sec_context_option;
+		gss_sign;
+		gss_store_cred;
+		gss_test_oid_set_member;
+		gss_unseal;
+		gss_unwrap;
+		gss_unwrap_iov;
+		gss_userok;
+		gss_verify;
 		gss_verify_mic;
 		gss_wrap;
-		gss_unwrap;
-		gss_display_status;
-		gss_indicate_mechs;
-		gss_compare_name;
-		gss_display_name;
-		gss_import_name;
-		gss_export_name;
-		gss_release_name;
-		gss_release_buffer;
-		gss_release_oid_set;
-		gss_inquire_cred;
-		gss_inquire_context;
+		gss_wrap_iov;
+		gss_wrap_iov_length;
 		gss_wrap_size_limit;
-		gss_add_cred;
-		gss_inquire_cred_by_mech;
-		gss_export_sec_context;
-		gss_import_sec_context;
-		gss_create_empty_oid_set;
-		gss_add_oid_set_member;
-		gss_test_oid_set_member;
-		gss_inquire_names_for_mech;
-		gss_inquire_mechs_for_name;
-		gss_canonicalize_name;
-		gss_duplicate_name;
-		gss_duplicate_oid;
-		gss_release_oid;
-		gss_oid_to_str;
-		gss_inquire_sec_context_by_oid;
-		gss_set_sec_context_option;
-		gss_set_cred_option;
-		gss_oid_equal;
-		gss_create_empty_buffer_set;
-		gss_add_buffer_set_member;
-		gss_release_buffer_set;
-		gss_inquire_cred_by_oid;
-		gss_pseudo_random;
-		gss_sign;
-		gss_verify;
-		gss_seal;
-		gss_unseal;
-		gss_inquire_sec_context_by_oid;
-		gss_encapsulate_token;
-		gss_decapsulate_token;
-		gss_krb5_ccache_name;
-		gsskrb5_register_acceptor_identity;
-		gss_krb5_copy_ccache;
-		gss_krb5_import_cred;
-		gss_krb5_get_tkt_flags;
+		gsskrb5_extract_authtime_from_sec_context;
 		gsskrb5_extract_authz_data_from_sec_context;
-		gsskrb5_set_dns_canonicalize;
-		gsskrb5_set_send_to_kdc;
-		gsskrb5_set_default_realm;
-		gsskrb5_extract_authtime_from_sec_context;
 		gsskrb5_extract_service_keyblock;
 		gsskrb5_get_initiator_subkey;
 		gsskrb5_get_subkey;
-		gss_krb5_export_lucid_sec_context;
-		gss_krb5_free_lucid_sec_context;
-		gss_krb5_set_allowable_enctypes;
+		gsskrb5_get_time_offset;
+		gsskrb5_register_acceptor_identity;
+		gsskrb5_set_default_realm;
+		gsskrb5_set_dns_canonicalize;
+		gsskrb5_set_send_to_kdc;
+		gsskrb5_set_time_offset;
+		krb5_gss_register_acceptor_identity;
+		gss_display_mech_attr;
+		gss_inquire_attrs_for_mech;
+		gss_indicate_mechs_by_attrs;
+		gss_inquire_mech_for_saslname;
+		gss_inquire_saslname_for_mech;
+		gss_mo_get;
+		gss_mo_set;
+		gss_mo_list;
+		gss_mo_name;
+		gss_name_to_oid;
+		gss_oid_to_name;
=20
 		# _gsskrb5cfx_ are really internal symbols, but export
 		# then now to make testing easier.
-		_gsskrb5cfx_max_wrap_length_cfx;
 		_gsskrb5cfx_wrap_length_cfx;
+		_gssapi_wrap_size_cfx;
+
+		__gss_krb5_copy_ccache_x_oid_desc;
+		__gss_krb5_get_tkt_flags_x_oid_desc;
+		__gss_krb5_extract_authz_data_from_sec_context_x_oid_desc;
+		__gss_krb5_compat_des3_mic_x_oid_desc;
+		__gss_krb5_register_acceptor_identity_x_oid_desc;
+		__gss_krb5_export_lucid_context_x_oid_desc;
+		__gss_krb5_export_lucid_context_v1_x_oid_desc;
+		__gss_krb5_set_dns_canonicalize_x_oid_desc;
+		__gss_krb5_get_subkey_x_oid_desc;
+		__gss_krb5_get_initiator_subkey_x_oid_desc;
+		__gss_krb5_get_acceptor_subkey_x_oid_desc;
+		__gss_krb5_send_to_kdc_x_oid_desc;
+		__gss_krb5_get_authtime_x_oid_desc;
+		__gss_krb5_get_service_keyblock_x_oid_desc;
+		__gss_krb5_set_allowable_enctypes_x_oid_desc;
+		__gss_krb5_set_default_realm_x_oid_desc;
+		__gss_krb5_ccache_name_x_oid_desc;
+		__gss_krb5_set_time_offset_x_oid_desc;
+		__gss_krb5_get_time_offset_x_oid_desc;
+		__gss_krb5_plugin_register_x_oid_desc;
+		__gss_ntlm_get_session_key_x_oid_desc;
+		__gss_c_nt_ntlm_oid_desc;
+		__gss_c_nt_dn_oid_desc;
+		__gss_krb5_nt_principal_name_referral_oid_desc;
+		__gss_c_ntlm_avguest_oid_desc;
+		__gss_c_ntlm_v1_oid_desc;
+		__gss_c_ntlm_v2_oid_desc;
+		__gss_c_ntlm_session_key_oid_desc;
+		__gss_c_ntlm_force_v1_oid_desc;
+		__gss_krb5_cred_no_ci_flags_x_oid_desc;
+		__gss_krb5_import_cred_x_oid_desc;
+		__gss_c_ma_sasl_mech_name_oid_desc;
+		__gss_c_ma_mech_name_oid_desc;
+		__gss_c_ma_mech_description_oid_desc;
+		__gss_sasl_digest_md5_mechanism_oid_desc;
+		__gss_krb5_mechanism_oid_desc;
+		__gss_ntlm_mechanism_oid_desc;
+		__gss_spnego_mechanism_oid_desc;
+		__gss_c_peer_has_updated_spnego_oid_desc;
+		__gss_c_ma_mech_concrete_oid_desc;
+		__gss_c_ma_mech_pseudo_oid_desc;
+		__gss_c_ma_mech_composite_oid_desc;
+		__gss_c_ma_mech_nego_oid_desc;
+		__gss_c_ma_mech_glue_oid_desc;
+		__gss_c_ma_not_mech_oid_desc;
+		__gss_c_ma_deprecated_oid_desc;
+		__gss_c_ma_not_dflt_mech_oid_desc;
+		__gss_c_ma_itok_framed_oid_desc;
+		__gss_c_ma_auth_init_oid_desc;
+		__gss_c_ma_auth_targ_oid_desc;
+		__gss_c_ma_auth_init_init_oid_desc;
+		__gss_c_ma_auth_targ_init_oid_desc;
+		__gss_c_ma_auth_init_anon_oid_desc;
+		__gss_c_ma_auth_targ_anon_oid_desc;
+		__gss_c_ma_deleg_cred_oid_desc;
+		__gss_c_ma_integ_prot_oid_desc;
+		__gss_c_ma_conf_prot_oid_desc;
+		__gss_c_ma_mic_oid_desc;
+		__gss_c_ma_wrap_oid_desc;
+		__gss_c_ma_prot_ready_oid_desc;
+		__gss_c_ma_replay_det_oid_desc;
+		__gss_c_ma_oos_det_oid_desc;
+		__gss_c_ma_cbindings_oid_desc;
+		__gss_c_ma_pfs_oid_desc;
+		__gss_c_ma_compress_oid_desc;
+		__gss_c_ma_ctx_trans_oid_desc;
=20
 	local:
 		*;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/Makefile.am
--- a/head/crypto/heimdal/lib/hdb/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,15 @@
-# $Id: Makefile.am 22490 2008-01-21 11:49:33Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
 AM_CPPFLAGS +=3D -I../asn1 -I$(srcdir)/../asn1 $(INCLUDE_hcrypto)
+AM_CPPFLAGS +=3D $(INCLUDE_openldap) -DHDB_DB_DIR=3D\"$(DIR_hdbdir)\"
+AM_CPPFLAGS +=3D -I$(srcdir)/../krb5
+AM_CPPFLAGS +=3D $(INCLUDE_sqlite3)
+AM_CPPFLAGS +=3D $(INCLUDE_libintl)
+if HAVE_DBHEADER
+AM_CPPFLAGS +=3D -I$(DBHEADER)
+endif
=20
 BUILT_SOURCES =3D \
 	$(gen_files_hdb:.x=3D.c)	\
@@ -16,6 +23,7 @@
 	asn1_HDBFlags.x \
 	asn1_GENERATION.x \
 	asn1_HDB_Ext_PKINIT_acl.x \
+	asn1_HDB_Ext_PKINIT_cert.x \
 	asn1_HDB_Ext_PKINIT_hash.x \
 	asn1_HDB_Ext_Constrained_delegation_acl.x \
 	asn1_HDB_Ext_Lan_Manager_OWF.x \
@@ -24,27 +32,33 @@
 	asn1_HDB_extension.x \
 	asn1_HDB_extensions.x \
 	asn1_hdb_entry.x \
-	asn1_hdb_entry_alias.x
+	asn1_hdb_entry_alias.x \
+	asn1_hdb_keyset.x
=20
-CLEANFILES =3D $(BUILT_SOURCES) $(gen_files_hdb) hdb_asn1.h hdb_asn1_files
+CLEANFILES =3D $(BUILT_SOURCES) $(gen_files_hdb) \
+	hdb_asn1{,-priv}.h* hdb_asn1_files hdb_asn1-template.c*
=20
 LDADD =3D libhdb.la \
 	$(LIB_openldap) \
+	$(LIB_libintl) \
 	../krb5/libkrb5.la \
 	../asn1/libasn1.la \
 	$(LIB_hcrypto) \
 	$(LIB_roken) \
 	$(LIB_ldopen)
=20
+
 if OPENLDAP_MODULE
=20
 ldap_so =3D hdb_ldap.la
 hdb_ldap_la_SOURCES =3D hdb-ldap.c
-hdb_ldap_la_LDFLAGS =3D -module
+hdb_ldap_la_LDFLAGS =3D -module -avoid-version
+hdb_ldap_la_LIBADD =3D $(LIB_openldap) libhdb.la
=20
 else
=20
 ldap =3D hdb-ldap.c
+ldap_lib =3D $(LIB_openldap)
=20
 endif
=20
@@ -52,7 +66,11 @@
 lib_LTLIBRARIES =3D libhdb.la $(ldap_so)
 libhdb_la_LDFLAGS =3D -version-info 11:0:2
=20
-noinst_PROGRAMS =3D test_dbinfo
+if versionscript
+libhdb_la_LDFLAGS +=3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.m=
ap
+endif
+
+noinst_PROGRAMS =3D test_dbinfo test_hdbkeys test_mkey
=20
 dist_libhdb_la_SOURCES =3D			\
 	common.c				\
@@ -61,6 +79,9 @@
 	ext.c					\
 	$(ldap)					\
 	hdb.c					\
+	hdb-sqlite.c				\
+	hdb-keytab.c				\
+	hdb-mitdb.c				\
 	hdb_locl.h				\
 	hdb-private.h				\
 	keys.c					\
@@ -72,24 +93,24 @@
=20
 nodist_libhdb_la_SOURCES =3D $(BUILT_SOURCES)
=20
-AM_CPPFLAGS +=3D $(INCLUDE_openldap)
+libhdb_la_DEPENDENCIES =3D version-script.map
=20
 include_HEADERS =3D hdb.h hdb-protos.h
 nodist_include_HEADERS =3D  hdb_err.h hdb_asn1.h
=20
-libhdb_la_CPPFLAGS =3D -DHDB_DB_DIR=3D\"$(DIR_hdbdir)\"
-
 libhdb_la_LIBADD =3D \
 	$(LIB_com_err) \
 	../krb5/libkrb5.la \
 	../asn1/libasn1.la \
+	$(LIB_sqlite3) \
 	$(LIBADD_roken) \
-	$(LIB_openldap) \
+	$(ldap_lib) \
 	$(LIB_dlopen) \
 	$(DBLIB) \
 	$(LIB_NDBM)
=20
 $(libhdb_la_OBJECTS): $(srcdir)/hdb-protos.h $(srcdir)/hdb-private.h
+$(libhdb_la_OBJECTS): hdb_asn1.h hdb_asn1-priv.h hdb_err.h
=20
 $(srcdir)/hdb-protos.h:
 	cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -o hdb-protos.h $=
(dist_libhdb_la_SOURCES) || rm -f hdb-protos.h
@@ -97,19 +118,27 @@
 $(srcdir)/hdb-private.h:
 	cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -p hdb-private.h =
$(dist_libhdb_la_SOURCES) || rm -f hdb-private.h
=20
-$(gen_files_hdb) hdb_asn1.h: hdb_asn1_files
+$(gen_files_hdb) hdb_asn1.hx hdb_asn1-priv.hx: hdb_asn1_files
=20
-hdb_asn1_files: ../asn1/asn1_compile$(EXEEXT) $(srcdir)/hdb.asn1
-	../asn1/asn1_compile$(EXEEXT) $(srcdir)/hdb.asn1 hdb_asn1
-
-$(libhdb_la_OBJECTS): hdb_asn1.h hdb_err.h
-
-test_dbinfo_SOURCES =3D test_dbinfo.c
+hdb_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/hdb.asn1
+	$(ASN1_COMPILE) $(srcdir)/hdb.asn1 hdb_asn1
=20
 test_dbinfo_LIBS =3D libhdb.la
=20
+test_hdbkeys_LIBS =3D ../krb5/libkrb5.la libhdb.la
+test_mkey_LIBS =3D $(test_hdbkeys_LIBS)
+
 # to help stupid solaris make
=20
 hdb_err.h: hdb_err.et
=20
-EXTRA_DIST =3D hdb.asn1 hdb_err.et hdb.schema
+EXTRA_DIST =3D \
+	NTMakefile \
+	libhdb-version.rc \
+	libhdb-exports.def \
+	hdb.asn1 \
+	hdb_err.et \
+	hdb.schema \
+	version-script.map \
+	data-mkey.mit.des3.le \
+	data-mkey.mit.des3.be
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/Makefile.in
--- a/head/crypto/heimdal/lib/hdb/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22490 2008-01-21 11:49:33Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -43,11 +45,14 @@
 DIST_COMMON =3D $(include_HEADERS) $(srcdir)/Makefile.am \
 	$(srcdir)/Makefile.in $(top_srcdir)/Makefile.am.common \
 	$(top_srcdir)/cf/Makefile.am.common
-noinst_PROGRAMS =3D test_dbinfo$(EXEEXT)
+ at HAVE_DBHEADER_TRUE@am__append_1 =3D -I$(DBHEADER)
+ at versionscript_TRUE@am__append_2 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
+noinst_PROGRAMS =3D test_dbinfo$(EXEEXT) test_hdbkeys$(EXEEXT) \
+	test_mkey$(EXEEXT)
 subdir =3D lib/hdb
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -62,7 +67,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -76,9 +81,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -86,23 +94,40 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" \
 	"$(DESTDIR)$(includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
-hdb_ldap_la_LIBADD =3D
+am__DEPENDENCIES_1 =3D
+ at OPENLDAP_MODULE_TRUE@hdb_ldap_la_DEPENDENCIES =3D  \
+ at OPENLDAP_MODULE_TRUE@	$(am__DEPENDENCIES_1) libhdb.la
 am__hdb_ldap_la_SOURCES_DIST =3D hdb-ldap.c
 @OPENLDAP_MODULE_TRUE at am_hdb_ldap_la_OBJECTS =3D hdb-ldap.lo
 hdb_ldap_la_OBJECTS =3D $(am_hdb_ldap_la_OBJECTS)
@@ -110,33 +135,24 @@
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(hdb_ldap_la_LDFLAGS) $(LDFLAGS) -o $@
 @OPENLDAP_MODULE_TRUE at am_hdb_ldap_la_rpath =3D -rpath $(libdir)
-am__DEPENDENCIES_1 =3D
-libhdb_la_DEPENDENCIES =3D $(am__DEPENDENCIES_1) ../krb5/libkrb5.la \
-	../asn1/libasn1.la $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
+ at OPENLDAP_MODULE_FALSE@am__DEPENDENCIES_2 =3D $(am__DEPENDENCIES_1)
 am__dist_libhdb_la_SOURCES_DIST =3D common.c db.c db3.c ext.c hdb-ldap.c \
-	hdb.c hdb_locl.h hdb-private.h keys.c keytab.c dbinfo.c mkey.c \
-	ndbm.c print.c
- at OPENLDAP_MODULE_FALSE@am__objects_1 =3D libhdb_la-hdb-ldap.lo
-dist_libhdb_la_OBJECTS =3D libhdb_la-common.lo libhdb_la-db.lo \
-	libhdb_la-db3.lo libhdb_la-ext.lo $(am__objects_1) \
-	libhdb_la-hdb.lo libhdb_la-keys.lo libhdb_la-keytab.lo \
-	libhdb_la-dbinfo.lo libhdb_la-mkey.lo libhdb_la-ndbm.lo \
-	libhdb_la-print.lo
-am__objects_2 =3D libhdb_la-asn1_Salt.lo libhdb_la-asn1_Key.lo \
-	libhdb_la-asn1_Event.lo libhdb_la-asn1_HDBFlags.lo \
-	libhdb_la-asn1_GENERATION.lo \
-	libhdb_la-asn1_HDB_Ext_PKINIT_acl.lo \
-	libhdb_la-asn1_HDB_Ext_PKINIT_hash.lo \
-	libhdb_la-asn1_HDB_Ext_Constrained_delegation_acl.lo \
-	libhdb_la-asn1_HDB_Ext_Lan_Manager_OWF.lo \
-	libhdb_la-asn1_HDB_Ext_Password.lo \
-	libhdb_la-asn1_HDB_Ext_Aliases.lo \
-	libhdb_la-asn1_HDB_extension.lo \
-	libhdb_la-asn1_HDB_extensions.lo libhdb_la-asn1_hdb_entry.lo \
-	libhdb_la-asn1_hdb_entry_alias.lo
-am__objects_3 =3D $(am__objects_2) libhdb_la-hdb_err.lo
+	hdb.c hdb-sqlite.c hdb-keytab.c hdb-mitdb.c hdb_locl.h \
+	hdb-private.h keys.c keytab.c dbinfo.c mkey.c ndbm.c print.c
+ at OPENLDAP_MODULE_FALSE@am__objects_1 =3D hdb-ldap.lo
+dist_libhdb_la_OBJECTS =3D common.lo db.lo db3.lo ext.lo \
+	$(am__objects_1) hdb.lo hdb-sqlite.lo hdb-keytab.lo \
+	hdb-mitdb.lo keys.lo keytab.lo dbinfo.lo mkey.lo ndbm.lo \
+	print.lo
+am__objects_2 =3D asn1_Salt.lo asn1_Key.lo asn1_Event.lo \
+	asn1_HDBFlags.lo asn1_GENERATION.lo asn1_HDB_Ext_PKINIT_acl.lo \
+	asn1_HDB_Ext_PKINIT_cert.lo asn1_HDB_Ext_PKINIT_hash.lo \
+	asn1_HDB_Ext_Constrained_delegation_acl.lo \
+	asn1_HDB_Ext_Lan_Manager_OWF.lo asn1_HDB_Ext_Password.lo \
+	asn1_HDB_Ext_Aliases.lo asn1_HDB_extension.lo \
+	asn1_HDB_extensions.lo asn1_hdb_entry.lo \
+	asn1_hdb_entry_alias.lo asn1_hdb_keyset.lo
+am__objects_3 =3D $(am__objects_2) hdb_err.lo
 nodist_libhdb_la_OBJECTS =3D $(am__objects_3)
 libhdb_la_OBJECTS =3D $(dist_libhdb_la_OBJECTS) \
 	$(nodist_libhdb_la_OBJECTS)
@@ -144,15 +160,27 @@
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libhdb_la_LDFLAGS) $(LDFLAGS) -o $@
 PROGRAMS =3D $(noinst_PROGRAMS)
-am_test_dbinfo_OBJECTS =3D test_dbinfo.$(OBJEXT)
-test_dbinfo_OBJECTS =3D $(am_test_dbinfo_OBJECTS)
+test_dbinfo_SOURCES =3D test_dbinfo.c
+test_dbinfo_OBJECTS =3D test_dbinfo.$(OBJEXT)
 test_dbinfo_LDADD =3D $(LDADD)
 test_dbinfo_DEPENDENCIES =3D libhdb.la $(am__DEPENDENCIES_1) \
-	../krb5/libkrb5.la ../asn1/libasn1.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(am__DEPENDENCIES_1) ../krb5/libkrb5.la ../asn1/libasn1.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+test_hdbkeys_SOURCES =3D test_hdbkeys.c
+test_hdbkeys_OBJECTS =3D test_hdbkeys.$(OBJEXT)
+test_hdbkeys_LDADD =3D $(LDADD)
+test_hdbkeys_DEPENDENCIES =3D libhdb.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) ../krb5/libkrb5.la ../asn1/libasn1.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+test_mkey_SOURCES =3D test_mkey.c
+test_mkey_OBJECTS =3D test_mkey.$(OBJEXT)
+test_mkey_LDADD =3D $(LDADD)
+test_mkey_DEPENDENCIES =3D libhdb.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) ../krb5/libkrb5.la ../asn1/libasn1.la \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -163,11 +191,11 @@
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
 SOURCES =3D $(hdb_ldap_la_SOURCES) $(dist_libhdb_la_SOURCES) \
-	$(nodist_libhdb_la_SOURCES) $(test_dbinfo_SOURCES)
+	$(nodist_libhdb_la_SOURCES) test_dbinfo.c test_hdbkeys.c \
+	test_mkey.c
 DIST_SOURCES =3D $(am__hdb_ldap_la_SOURCES_DIST) \
-	$(am__dist_libhdb_la_SOURCES_DIST) $(test_dbinfo_SOURCES)
-includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-nodist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
+	$(am__dist_libhdb_la_SOURCES_DIST) test_dbinfo.c \
+	test_hdbkeys.c test_mkey.c
 HEADERS =3D $(include_HEADERS) $(nodist_include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
@@ -176,49 +204,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -242,10 +279,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -262,6 +300,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -277,31 +317,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -316,10 +370,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -360,30 +416,37 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) -I../asn1 \
-	-I$(srcdir)/../asn1 $(INCLUDE_hcrypto) $(INCLUDE_openldap)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) -I../asn1 -I$(srcdir)/../asn1 \
+	$(INCLUDE_hcrypto) $(INCLUDE_openldap) \
+	-DHDB_DB_DIR=3D\"$(DIR_hdbdir)\" -I$(srcdir)/../krb5 \
+	$(INCLUDE_sqlite3) $(INCLUDE_libintl) $(am__append_1)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 BUILT_SOURCES =3D \
 	$(gen_files_hdb:.x=3D.c)	\
@@ -397,6 +460,7 @@
 	asn1_HDBFlags.x \
 	asn1_GENERATION.x \
 	asn1_HDB_Ext_PKINIT_acl.x \
+	asn1_HDB_Ext_PKINIT_cert.x \
 	asn1_HDB_Ext_PKINIT_hash.x \
 	asn1_HDB_Ext_Constrained_delegation_acl.x \
 	asn1_HDB_Ext_Lan_Manager_OWF.x \
@@ -405,11 +469,15 @@
 	asn1_HDB_extension.x \
 	asn1_HDB_extensions.x \
 	asn1_hdb_entry.x \
-	asn1_hdb_entry_alias.x
+	asn1_hdb_entry_alias.x \
+	asn1_hdb_keyset.x
=20
-CLEANFILES =3D $(BUILT_SOURCES) $(gen_files_hdb) hdb_asn1.h hdb_asn1_files
+CLEANFILES =3D $(BUILT_SOURCES) $(gen_files_hdb) \
+	hdb_asn1{,-priv}.h* hdb_asn1_files hdb_asn1-template.c*
+
 LDADD =3D libhdb.la \
 	$(LIB_openldap) \
+	$(LIB_libintl) \
 	../krb5/libkrb5.la \
 	../asn1/libasn1.la \
 	$(LIB_hcrypto) \
@@ -418,10 +486,12 @@
=20
 @OPENLDAP_MODULE_TRUE at ldap_so =3D hdb_ldap.la
 @OPENLDAP_MODULE_TRUE at hdb_ldap_la_SOURCES =3D hdb-ldap.c
- at OPENLDAP_MODULE_TRUE@hdb_ldap_la_LDFLAGS =3D -module
+ at OPENLDAP_MODULE_TRUE@hdb_ldap_la_LDFLAGS =3D -module -avoid-version
+ at OPENLDAP_MODULE_TRUE@hdb_ldap_la_LIBADD =3D $(LIB_openldap) libhdb.la
 @OPENLDAP_MODULE_FALSE at ldap =3D hdb-ldap.c
+ at OPENLDAP_MODULE_FALSE@ldap_lib =3D $(LIB_openldap)
 lib_LTLIBRARIES =3D libhdb.la $(ldap_so)
-libhdb_la_LDFLAGS =3D -version-info 11:0:2
+libhdb_la_LDFLAGS =3D -version-info 11:0:2 $(am__append_2)
 dist_libhdb_la_SOURCES =3D \
 	common.c				\
 	db.c					\
@@ -429,6 +499,9 @@
 	ext.c					\
 	$(ldap)					\
 	hdb.c					\
+	hdb-sqlite.c				\
+	hdb-keytab.c				\
+	hdb-mitdb.c				\
 	hdb_locl.h				\
 	hdb-private.h				\
 	keys.c					\
@@ -439,39 +512,51 @@
 	print.c
=20
 nodist_libhdb_la_SOURCES =3D $(BUILT_SOURCES)
+libhdb_la_DEPENDENCIES =3D version-script.map
 include_HEADERS =3D hdb.h hdb-protos.h
 nodist_include_HEADERS =3D hdb_err.h hdb_asn1.h
-libhdb_la_CPPFLAGS =3D -DHDB_DB_DIR=3D\"$(DIR_hdbdir)\"
 libhdb_la_LIBADD =3D \
 	$(LIB_com_err) \
 	../krb5/libkrb5.la \
 	../asn1/libasn1.la \
+	$(LIB_sqlite3) \
 	$(LIBADD_roken) \
-	$(LIB_openldap) \
+	$(ldap_lib) \
 	$(LIB_dlopen) \
 	$(DBLIB) \
 	$(LIB_NDBM)
=20
-test_dbinfo_SOURCES =3D test_dbinfo.c
 test_dbinfo_LIBS =3D libhdb.la
-EXTRA_DIST =3D hdb.asn1 hdb_err.et hdb.schema
+test_hdbkeys_LIBS =3D ../krb5/libkrb5.la libhdb.la
+test_mkey_LIBS =3D $(test_hdbkeys_LIBS)
+EXTRA_DIST =3D \
+	NTMakefile \
+	libhdb-version.rc \
+	libhdb-exports.def \
+	hdb.asn1 \
+	hdb_err.et \
+	hdb.schema \
+	version-script.map \
+	data-mkey.mit.des3.le \
+	data-mkey.mit.des3.be
+
 all: $(BUILT_SOURCES)
 	$(MAKE) $(AM_MAKEFLAGS) all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/hdb/M=
akefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/hdb/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/hdb/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/hdb/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -489,23 +574,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -522,14 +612,22 @@
 	$(libhdb_la_LINK) -rpath $(libdir) $(libhdb_la_OBJECTS) $(libhdb_la_LIBAD=
D) $(LIBS)
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 test_dbinfo$(EXEEXT): $(test_dbinfo_OBJECTS) $(test_dbinfo_DEPENDENCIES)=20
 	@rm -f test_dbinfo$(EXEEXT)
 	$(LINK) $(test_dbinfo_OBJECTS) $(test_dbinfo_LDADD) $(LIBS)
+test_hdbkeys$(EXEEXT): $(test_hdbkeys_OBJECTS) $(test_hdbkeys_DEPENDENCIES=
)=20
+	@rm -f test_hdbkeys$(EXEEXT)
+	$(LINK) $(test_hdbkeys_OBJECTS) $(test_hdbkeys_LDADD) $(LIBS)
+test_mkey$(EXEEXT): $(test_mkey_OBJECTS) $(test_mkey_DEPENDENCIES)=20
+	@rm -f test_mkey$(EXEEXT)
+	$(LINK) $(test_mkey_OBJECTS) $(test_mkey_LDADD) $(LIBS)
=20
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
@@ -537,98 +635,63 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_Event.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_GENERATION.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDBFlags.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_Ext_Aliases.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_Ext_Constrained_=
delegation_acl.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_Ext_Lan_Manager_=
OWF.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_Ext_PKINIT_acl.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_Ext_PKINIT_cert.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_Ext_PKINIT_hash.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_Ext_Password.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_extension.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_HDB_extensions.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_Key.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_Salt.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_hdb_entry.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_hdb_entry_alias.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/asn1_hdb_keyset.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/common.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/db.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/db3.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/dbinfo.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ext.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdb-keytab.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdb-ldap.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdb-mitdb.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdb-sqlite.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdb.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hdb_err.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/keys.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/keytab.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/mkey.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ndbm.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/print.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_dbinfo.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_hdbkeys.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_mkey.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
-
-libhdb_la-common.lo: common.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-common.lo `test -f 'common.c' =
|| echo '$(srcdir)/'`common.c
-
-libhdb_la-db.lo: db.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-db.lo `test -f 'db.c' || echo =
'$(srcdir)/'`db.c
-
-libhdb_la-db3.lo: db3.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-db3.lo `test -f 'db3.c' || ech=
o '$(srcdir)/'`db3.c
-
-libhdb_la-ext.lo: ext.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-ext.lo `test -f 'ext.c' || ech=
o '$(srcdir)/'`ext.c
-
-libhdb_la-hdb-ldap.lo: hdb-ldap.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-hdb-ldap.lo `test -f 'hdb-ldap=
.c' || echo '$(srcdir)/'`hdb-ldap.c
-
-libhdb_la-hdb.lo: hdb.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-hdb.lo `test -f 'hdb.c' || ech=
o '$(srcdir)/'`hdb.c
-
-libhdb_la-keys.lo: keys.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-keys.lo `test -f 'keys.c' || e=
cho '$(srcdir)/'`keys.c
-
-libhdb_la-keytab.lo: keytab.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-keytab.lo `test -f 'keytab.c' =
|| echo '$(srcdir)/'`keytab.c
-
-libhdb_la-dbinfo.lo: dbinfo.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-dbinfo.lo `test -f 'dbinfo.c' =
|| echo '$(srcdir)/'`dbinfo.c
-
-libhdb_la-mkey.lo: mkey.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-mkey.lo `test -f 'mkey.c' || e=
cho '$(srcdir)/'`mkey.c
-
-libhdb_la-ndbm.lo: ndbm.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-ndbm.lo `test -f 'ndbm.c' || e=
cho '$(srcdir)/'`ndbm.c
-
-libhdb_la-print.lo: print.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-print.lo `test -f 'print.c' ||=
 echo '$(srcdir)/'`print.c
-
-libhdb_la-asn1_Salt.lo: asn1_Salt.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_Salt.lo `test -f 'asn1_Sa=
lt.c' || echo '$(srcdir)/'`asn1_Salt.c
-
-libhdb_la-asn1_Key.lo: asn1_Key.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_Key.lo `test -f 'asn1_Key=
.c' || echo '$(srcdir)/'`asn1_Key.c
-
-libhdb_la-asn1_Event.lo: asn1_Event.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_Event.lo `test -f 'asn1_E=
vent.c' || echo '$(srcdir)/'`asn1_Event.c
-
-libhdb_la-asn1_HDBFlags.lo: asn1_HDBFlags.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDBFlags.lo `test -f 'asn=
1_HDBFlags.c' || echo '$(srcdir)/'`asn1_HDBFlags.c
-
-libhdb_la-asn1_GENERATION.lo: asn1_GENERATION.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_GENERATION.lo `test -f 'a=
sn1_GENERATION.c' || echo '$(srcdir)/'`asn1_GENERATION.c
-
-libhdb_la-asn1_HDB_Ext_PKINIT_acl.lo: asn1_HDB_Ext_PKINIT_acl.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_Ext_PKINIT_acl.lo `te=
st -f 'asn1_HDB_Ext_PKINIT_acl.c' || echo '$(srcdir)/'`asn1_HDB_Ext_PKINIT_=
acl.c
-
-libhdb_la-asn1_HDB_Ext_PKINIT_hash.lo: asn1_HDB_Ext_PKINIT_hash.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_Ext_PKINIT_hash.lo `t=
est -f 'asn1_HDB_Ext_PKINIT_hash.c' || echo '$(srcdir)/'`asn1_HDB_Ext_PKINI=
T_hash.c
-
-libhdb_la-asn1_HDB_Ext_Constrained_delegation_acl.lo: asn1_HDB_Ext_Constra=
ined_delegation_acl.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_Ext_Constrained_deleg=
ation_acl.lo `test -f 'asn1_HDB_Ext_Constrained_delegation_acl.c' || echo '=
$(srcdir)/'`asn1_HDB_Ext_Constrained_delegation_acl.c
-
-libhdb_la-asn1_HDB_Ext_Lan_Manager_OWF.lo: asn1_HDB_Ext_Lan_Manager_OWF.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_Ext_Lan_Manager_OWF.l=
o `test -f 'asn1_HDB_Ext_Lan_Manager_OWF.c' || echo '$(srcdir)/'`asn1_HDB_E=
xt_Lan_Manager_OWF.c
-
-libhdb_la-asn1_HDB_Ext_Password.lo: asn1_HDB_Ext_Password.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_Ext_Password.lo `test=
 -f 'asn1_HDB_Ext_Password.c' || echo '$(srcdir)/'`asn1_HDB_Ext_Password.c
-
-libhdb_la-asn1_HDB_Ext_Aliases.lo: asn1_HDB_Ext_Aliases.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_Ext_Aliases.lo `test =
-f 'asn1_HDB_Ext_Aliases.c' || echo '$(srcdir)/'`asn1_HDB_Ext_Aliases.c
-
-libhdb_la-asn1_HDB_extension.lo: asn1_HDB_extension.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_extension.lo `test -f=
 'asn1_HDB_extension.c' || echo '$(srcdir)/'`asn1_HDB_extension.c
-
-libhdb_la-asn1_HDB_extensions.lo: asn1_HDB_extensions.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_HDB_extensions.lo `test -=
f 'asn1_HDB_extensions.c' || echo '$(srcdir)/'`asn1_HDB_extensions.c
-
-libhdb_la-asn1_hdb_entry.lo: asn1_hdb_entry.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_hdb_entry.lo `test -f 'as=
n1_hdb_entry.c' || echo '$(srcdir)/'`asn1_hdb_entry.c
-
-libhdb_la-asn1_hdb_entry_alias.lo: asn1_hdb_entry_alias.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-asn1_hdb_entry_alias.lo `test =
-f 'asn1_hdb_entry_alias.c' || echo '$(srcdir)/'`asn1_hdb_entry_alias.c
-
-libhdb_la-hdb_err.lo: hdb_err.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhdb_la_CPPFLAGS) $(CPPF=
LAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhdb_la-hdb_err.lo `test -f 'hdb_err.c=
' || echo '$(srcdir)/'`hdb_err.c
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -638,82 +701,92 @@
 install-includeHEADERS: $(include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'=
"; \
-	  $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-nodist_includeHEADERS: $(nodist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedi=
r)/$$f'"; \
-	  $(nodist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"=
; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -734,13 +807,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -778,6 +855,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -789,6 +867,7 @@
 	clean-noinstPROGRAMS mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -799,6 +878,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -806,26 +887,35 @@
 install-data-am: install-includeHEADERS install-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -846,9 +936,8 @@
 	uninstall-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: all check check-am install install-am install-data-am \
+	install-exec-am install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libLTLIBRARIES clean-libtool \
@@ -938,6 +1027,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1023,7 +1115,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1038,6 +1130,7 @@
 	done
=20
 $(libhdb_la_OBJECTS): $(srcdir)/hdb-protos.h $(srcdir)/hdb-private.h
+$(libhdb_la_OBJECTS): hdb_asn1.h hdb_asn1-priv.h hdb_err.h
=20
 $(srcdir)/hdb-protos.h:
 	cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -o hdb-protos.h $=
(dist_libhdb_la_SOURCES) || rm -f hdb-protos.h
@@ -1045,16 +1138,15 @@
 $(srcdir)/hdb-private.h:
 	cd $(srcdir); perl ../../cf/make-proto.pl -q -P comment -p hdb-private.h =
$(dist_libhdb_la_SOURCES) || rm -f hdb-private.h
=20
-$(gen_files_hdb) hdb_asn1.h: hdb_asn1_files
+$(gen_files_hdb) hdb_asn1.hx hdb_asn1-priv.hx: hdb_asn1_files
=20
-hdb_asn1_files: ../asn1/asn1_compile$(EXEEXT) $(srcdir)/hdb.asn1
-	../asn1/asn1_compile$(EXEEXT) $(srcdir)/hdb.asn1 hdb_asn1
-
-$(libhdb_la_OBJECTS): hdb_asn1.h hdb_err.h
+hdb_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/hdb.asn1
+	$(ASN1_COMPILE) $(srcdir)/hdb.asn1 hdb_asn1
=20
 # to help stupid solaris make
=20
 hdb_err.h: hdb_err.et
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/common.c
--- a/head/crypto/heimdal/lib/hdb/common.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/common.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,49 +1,47 @@
 /*
- * Copyright (c) 1997-2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
=20
-RCSID("$Id: common.c 20236 2007-02-16 23:52:29Z lha $");
-
 int
 hdb_principal2key(krb5_context context, krb5_const_principal p, krb5_data =
*key)
 {
     Principal new;
-    size_t len;
+    size_t len =3D 0;
     int ret;
=20
     ret =3D copy_Principal(p, &new);
-    if(ret)=20
+    if(ret)
 	return ret;
     new.name.name_type =3D 0;
=20
@@ -63,9 +61,9 @@
 int
 hdb_entry2value(krb5_context context, const hdb_entry *ent, krb5_data *val=
ue)
 {
-    size_t len;
+    size_t len =3D 0;
     int ret;
-   =20
+
     ASN1_MALLOC_ENCODE(hdb_entry, value->data, value->length, ent, &len, r=
et);
     if (ret =3D=3D 0 && value->length !=3D len)
 	krb5_abortx(context, "internal asn.1 encoder error");
@@ -79,14 +77,14 @@
 }
=20
 int
-hdb_entry_alias2value(krb5_context context,=20
+hdb_entry_alias2value(krb5_context context,
 		      const hdb_entry_alias *alias,
 		      krb5_data *value)
 {
-    size_t len;
+    size_t len =3D 0;
     int ret;
-   =20
-    ASN1_MALLOC_ENCODE(hdb_entry_alias, value->data, value->length,=20
+
+    ASN1_MALLOC_ENCODE(hdb_entry_alias, value->data, value->length,
 		       alias, &len, ret);
     if (ret =3D=3D 0 && value->length !=3D len)
 	krb5_abortx(context, "internal asn.1 encoder error");
@@ -94,20 +92,39 @@
 }
=20
 int
-hdb_value2entry_alias(krb5_context context, krb5_data *value,=20
+hdb_value2entry_alias(krb5_context context, krb5_data *value,
 		      hdb_entry_alias *ent)
 {
     return decode_hdb_entry_alias(value->data, value->length, ent, NULL);
 }
=20
 krb5_error_code
-_hdb_fetch(krb5_context context, HDB *db, krb5_const_principal principal,
-	   unsigned flags, hdb_entry_ex *entry)
+_hdb_fetch_kvno(krb5_context context, HDB *db, krb5_const_principal princi=
pal,
+		unsigned flags, krb5_kvno kvno, hdb_entry_ex *entry)
 {
+    krb5_principal enterprise_principal =3D NULL;
     krb5_data key, value;
+    krb5_error_code ret;
     int code;
=20
+    if (principal->name.name_type =3D=3D KRB5_NT_ENTERPRISE_PRINCIPAL) {
+	if (principal->name.name_string.len !=3D 1) {
+	    ret =3D KRB5_PARSE_MALFORMED;
+	    krb5_set_error_message(context, ret, "malformed principal: "
+				   "enterprise name with %d name components",
+				   principal->name.name_string.len);
+	    return ret;
+	}
+	ret =3D krb5_parse_name(context, principal->name.name_string.val[0],
+			      &enterprise_principal);
+	if (ret)
+	    return ret;
+	principal =3D enterprise_principal;
+    }
+
     hdb_principal2key(context, principal, &key);
+    if (enterprise_principal)
+	krb5_free_principal(context, enterprise_principal);
     code =3D db->hdb__get(context, db, key, &value);
     krb5_data_free(&key);
     if(code)
@@ -154,14 +171,14 @@
     krb5_error_code code;
     hdb_entry oldentry;
     krb5_data value;
-    int i;
+    size_t i;
=20
     code =3D db->hdb__get(context, db, *key, &value);
     if (code =3D=3D HDB_ERR_NOENTRY)
 	return 0;
     else if (code)
 	return code;
-	   =20
+
     code =3D hdb_value2entry(context, &value, &oldentry);
     krb5_data_free(&value);
     if (code)
@@ -188,22 +205,22 @@
 }
=20
 static krb5_error_code
-hdb_add_aliases(krb5_context context, HDB *db,=20
+hdb_add_aliases(krb5_context context, HDB *db,
 		unsigned flags, hdb_entry_ex *entry)
 {
     const HDB_Ext_Aliases *aliases;
     krb5_error_code code;
     krb5_data key, value;
-    int i;
-   =20
+    size_t i;
+
     code =3D hdb_entry_get_aliases(&entry->entry, &aliases);
     if (code || aliases =3D=3D NULL)
 	return code;
-   =20
+
     for (i =3D 0; i < aliases->aliases.len; i++) {
 	hdb_entry_alias entryalias;
 	entryalias.principal =3D entry->entry.principal;
-=09
+
 	hdb_principal2key(context, &aliases->aliases.val[i], &key);
 	code =3D hdb_entry_alias2value(context, &entryalias, &value);
 	if (code) {
@@ -219,17 +236,64 @@
     return 0;
 }
=20
+static krb5_error_code
+hdb_check_aliases(krb5_context context, HDB *db, hdb_entry_ex *entry)
+{
+    const HDB_Ext_Aliases *aliases;
+    int code;
+    size_t i;
+
+    /* check if new aliases already is used */
+
+    code =3D hdb_entry_get_aliases(&entry->entry, &aliases);
+    if (code)
+	return code;
+
+    for (i =3D 0; aliases && i < aliases->aliases.len; i++) {
+	hdb_entry_alias alias;
+	krb5_data akey, value;
+
+	hdb_principal2key(context, &aliases->aliases.val[i], &akey);
+	code =3D db->hdb__get(context, db, akey, &value);
+	krb5_data_free(&akey);
+	if (code =3D=3D HDB_ERR_NOENTRY)
+	    continue;
+	else if (code)
+	    return code;
+
+	code =3D hdb_value2entry_alias(context, &value, &alias);
+	krb5_data_free(&value);
+
+	if (code =3D=3D ASN1_BAD_ID)
+	    return HDB_ERR_EXISTS;
+	else if (code)
+	    return code;
+
+	code =3D krb5_principal_compare(context, alias.principal,
+				      entry->entry.principal);
+	free_hdb_entry_alias(&alias);
+	if (code =3D=3D 0)
+	    return HDB_ERR_EXISTS;
+    }
+    return 0;
+}
+
 krb5_error_code
 _hdb_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *en=
try)
 {
     krb5_data key, value;
     int code;
=20
+    /* check if new aliases already is used */
+    code =3D hdb_check_aliases(context, db, entry);
+    if (code)
+	return code;
+
     if(entry->entry.generation =3D=3D NULL) {
 	struct timeval t;
 	entry->entry.generation =3D malloc(sizeof(*entry->entry.generation));
 	if(entry->entry.generation =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    return ENOMEM;
 	}
 	gettimeofday(&t, NULL);
@@ -238,12 +302,12 @@
 	entry->entry.generation->gen =3D 0;
     } else
 	entry->entry.generation->gen++;
+
+    code =3D hdb_seal_keys(context, db, &entry->entry);
+    if (code)
+	return code;
+
     hdb_principal2key(context, entry->entry.principal, &key);
-    code =3D hdb_seal_keys(context, db, &entry->entry);
-    if (code) {
-	krb5_data_free(&key);
-	return code;
-    }
=20
     /* remove aliases */
     code =3D hdb_remove_aliases(context, db, &key);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/db.c
--- a/head/crypto/heimdal/lib/hdb/db.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/db.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
=20
-RCSID("$Id: db.c 20215 2007-02-09 21:59:53Z lha $");
-
 #if HAVE_DB1
=20
 #if defined(HAVE_DB_185_H)
@@ -68,8 +66,8 @@
     DB *d =3D (DB*)db->hdb_db;
     int fd =3D (*d->fd)(d);
     if(fd < 0) {
-	krb5_set_error_string(context,
-			      "Can't lock database: %s", db->hdb_name);
+	krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB,
+			       "Can't lock database: %s", db->hdb_name);
 	return HDB_ERR_CANT_LOCK_DB;
     }
     return hdb_lock(fd, operation);
@@ -81,8 +79,8 @@
     DB *d =3D (DB*)db->hdb_db;
     int fd =3D (*d->fd)(d);
     if(fd < 0) {
-	krb5_set_error_string(context,=20
-			      "Can't unlock database: %s", db->hdb_name);
+	krb5_set_error_message(context, HDB_ERR_CANT_LOCK_DB,
+			       "Can't unlock database: %s", db->hdb_name);
 	return HDB_ERR_CANT_LOCK_DB;
     }
     return hdb_unlock(fd);
@@ -100,19 +98,19 @@
=20
     code =3D db->hdb_lock(context, db, HDB_RLOCK);
     if(code =3D=3D -1) {
-	krb5_set_error_string(context, "Database %s in use", db->hdb_name);
+	krb5_set_error_message(context, HDB_ERR_DB_INUSE, "Database %s in use", d=
b->hdb_name);
 	return HDB_ERR_DB_INUSE;
     }
     code =3D (*d->seq)(d, &key, &value, flag);
     db->hdb_unlock(context, db); /* XXX check value */
     if(code =3D=3D -1) {
 	code =3D errno;
-	krb5_set_error_string(context, "Database %s seq error: %s",=20
-			      db->hdb_name, strerror(code));
+	krb5_set_error_message(context, code, "Database %s seq error: %s",
+			       db->hdb_name, strerror(code));
 	return code;
     }
     if(code =3D=3D 1) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return HDB_ERR_NOENTRY;
     }
=20
@@ -131,8 +129,8 @@
     if (code =3D=3D 0 && entry->entry.principal =3D=3D NULL) {
 	entry->entry.principal =3D malloc(sizeof(*entry->entry.principal));
 	if (entry->entry.principal =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
 	    code =3D ENOMEM;
+	    krb5_set_error_message(context, code, "malloc: out of memory");
 	    hdb_free_entry (context, entry);
 	} else {
 	    hdb_key2principal(context, &key_data, entry->entry.principal);
@@ -168,7 +166,7 @@
     free(new);
     if(ret)
 	return errno;
-   =20
+
     free(db->hdb_name);
     db->hdb_name =3D strdup(new_name);
     return 0;
@@ -190,21 +188,21 @@
     db->hdb_unlock(context, db);
     if(code < 0) {
 	code =3D errno;
-	krb5_set_error_string(context, "Database %s get error: %s",=20
-			      db->hdb_name, strerror(code));
+	krb5_set_error_message(context, code, "Database %s get error: %s",
+			       db->hdb_name, strerror(code));
 	return code;
     }
     if(code =3D=3D 1) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return HDB_ERR_NOENTRY;
     }
-   =20
+
     krb5_data_copy(reply, v.data, v.size);
     return 0;
 }
=20
 static krb5_error_code
-DB__put(krb5_context context, HDB *db, int replace,=20
+DB__put(krb5_context context, HDB *db, int replace,
 	krb5_data key, krb5_data value)
 {
     DB *d =3D (DB*)db->hdb_db;
@@ -222,12 +220,12 @@
     db->hdb_unlock(context, db);
     if(code < 0) {
 	code =3D errno;
-	krb5_set_error_string(context, "Database %s put error: %s",=20
-			      db->hdb_name, strerror(code));
+	krb5_set_error_message(context, code, "Database %s put error: %s",
+			       db->hdb_name, strerror(code));
 	return code;
     }
     if(code =3D=3D 1) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return HDB_ERR_EXISTS;
     }
     return 0;
@@ -248,8 +246,8 @@
     db->hdb_unlock(context, db);
     if(code =3D=3D 1) {
 	code =3D errno;
-	krb5_set_error_string(context, "Database %s put error: %s",=20
-			      db->hdb_name, strerror(code));
+	krb5_set_error_message(context, code, "Database %s put error: %s",
+			       db->hdb_name, strerror(code));
 	return code;
     }
     if(code < 0)
@@ -265,7 +263,7 @@
=20
     asprintf(&fn, "%s.db", db->hdb_name);
     if (fn =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     db->hdb_db =3D dbopen(fn, flags, mode, DB_BTREE, NULL);
@@ -275,7 +273,7 @@
 	db->hdb_db =3D dbopen(db->hdb_name, flags, mode, DB_BTREE, NULL);
     if(db->hdb_db =3D=3D NULL) {
 	ret =3D errno;
-	krb5_set_error_string(context, "dbopen (%s): %s",
+	krb5_set_error_message(context, ret, "dbopen (%s): %s",
 			      db->hdb_name, strerror(ret));
 	return ret;
     }
@@ -284,42 +282,43 @@
     else
 	ret =3D hdb_init_db(context, db);
     if(ret =3D=3D HDB_ERR_NOENTRY) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return 0;
     }
     if (ret) {
 	DB_close(context, db);
-	krb5_set_error_string(context, "hdb_open: failed %s database %s",
-			      (flags & O_ACCMODE) =3D=3D O_RDONLY ?=20
-			      "checking format of" : "initialize",=20
+	krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+			      (flags & O_ACCMODE) =3D=3D O_RDONLY ?
+			      "checking format of" : "initialize",
 			      db->hdb_name);
     }
     return ret;
 }
=20
 krb5_error_code
-hdb_db_create(krb5_context context, HDB **db,=20
+hdb_db_create(krb5_context context, HDB **db,
 	      const char *filename)
 {
     *db =3D calloc(1, sizeof(**db));
     if (*db =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
=20
     (*db)->hdb_db =3D NULL;
     (*db)->hdb_name =3D strdup(filename);
     if ((*db)->hdb_name =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	free(*db);
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     (*db)->hdb_master_key_set =3D 0;
     (*db)->hdb_openp =3D 0;
+    (*db)->hdb_capability_flags =3D HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
     (*db)->hdb_open =3D DB_open;
     (*db)->hdb_close =3D DB_close;
-    (*db)->hdb_fetch =3D _hdb_fetch;
+    (*db)->hdb_fetch_kvno =3D _hdb_fetch_kvno;
     (*db)->hdb_store =3D _hdb_store;
     (*db)->hdb_remove =3D _hdb_remove;
     (*db)->hdb_firstkey =3D DB_firstkey;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/db3.c
--- a/head/crypto/heimdal/lib/hdb/db3.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/db3.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,45 +1,47 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
=20
-RCSID("$Id: db3.c 21610 2007-07-17 07:10:45Z lha $");
-
 #if HAVE_DB3
=20
-#ifdef HAVE_DB4_DB_H
+#ifdef HAVE_DBHEADER
+#include <db.h>
+#elif HAVE_DB5_DB_H
+#include <db5/db.h>
+#elif HAVE_DB4_DB_H
 #include <db4/db.h>
-#elif defined(HAVE_DB3_DB_H)
+#elif HAVE_DB3_DB_H
 #include <db3/db.h>
 #else
 #include <db.h>
@@ -125,7 +127,7 @@
 	entry->entry.principal =3D malloc(sizeof(*entry->entry.principal));
 	if (entry->entry.principal =3D=3D NULL) {
 	    hdb_free_entry (context, entry);
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    return ENOMEM;
 	} else {
 	    hdb_key2principal(context, &key_data, entry->entry.principal);
@@ -161,7 +163,7 @@
     free(new);
     if(ret)
 	return errno;
-   =20
+
     free(db->hdb_name);
     db->hdb_name =3D strdup(new_name);
     return 0;
@@ -193,7 +195,7 @@
 }
=20
 static krb5_error_code
-DB__put(krb5_context context, HDB *db, int replace,=20
+DB__put(krb5_context context, HDB *db, int replace,
 	krb5_data key, krb5_data value)
 {
     DB *d =3D (DB*)db->hdb_db;
@@ -264,10 +266,14 @@
=20
     asprintf(&fn, "%s.db", db->hdb_name);
     if (fn =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
-    db_create(&d, NULL, 0);
+    if (db_create(&d, NULL, 0) !=3D 0) {
+	free(fn);
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	return ENOMEM;
+    }
     db->hdb_db =3D d;
=20
 #if (DB_VERSION_MAJOR >=3D 4) && (DB_VERSION_MINOR >=3D 1)
@@ -282,14 +288,14 @@
 	ret =3D (*d->open)(db->hdb_db, NULL, db->hdb_name, NULL, DB_BTREE,
 			 myflags, mode);
 #else
-	ret =3D (*d->open)(db->hdb_db, db->hdb_name, NULL, DB_BTREE,=20
+	ret =3D (*d->open)(db->hdb_db, db->hdb_name, NULL, DB_BTREE,
 			 myflags, mode);
 #endif
     }
=20
     if (ret) {
 	free(fn);
-	krb5_set_error_string(context, "opening %s: %s",
+	krb5_set_error_message(context, ret, "opening %s: %s",
 			      db->hdb_name, strerror(ret));
 	return ret;
     }
@@ -297,7 +303,7 @@
=20
     ret =3D (*d->cursor)(d, NULL, &dbc, 0);
     if (ret) {
-	krb5_set_error_string(context, "d->cursor: %s", strerror(ret));
+	krb5_set_error_message(context, ret, "d->cursor: %s", strerror(ret));
         return ret;
     }
     db->hdb_dbc =3D dbc;
@@ -310,38 +316,39 @@
 	return 0;
     if (ret) {
 	DB_close(context, db);
-	krb5_set_error_string(context, "hdb_open: failed %s database %s",
-			      (flags & O_ACCMODE) =3D=3D O_RDONLY ?=20
-			      "checking format of" : "initialize",=20
-			      db->hdb_name);
+	krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+			       (flags & O_ACCMODE) =3D=3D O_RDONLY ?
+			       "checking format of" : "initialize",
+			       db->hdb_name);
     }
=20
     return ret;
 }
=20
 krb5_error_code
-hdb_db_create(krb5_context context, HDB **db,=20
+hdb_db_create(krb5_context context, HDB **db,
 	      const char *filename)
 {
     *db =3D calloc(1, sizeof(**db));
     if (*db =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
=20
     (*db)->hdb_db =3D NULL;
     (*db)->hdb_name =3D strdup(filename);
     if ((*db)->hdb_name =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	free(*db);
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     (*db)->hdb_master_key_set =3D 0;
     (*db)->hdb_openp =3D 0;
+    (*db)->hdb_capability_flags =3D HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
     (*db)->hdb_open  =3D DB_open;
     (*db)->hdb_close =3D DB_close;
-    (*db)->hdb_fetch =3D _hdb_fetch;
+    (*db)->hdb_fetch_kvno =3D _hdb_fetch_kvno;
     (*db)->hdb_store =3D _hdb_store;
     (*db)->hdb_remove =3D _hdb_remove;
     (*db)->hdb_firstkey =3D DB_firstkey;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/dbinfo.c
--- a/head/crypto/heimdal/lib/hdb/dbinfo.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/dbinfo.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
=20
-RCSID("$Id: dbinfo.c 22306 2007-12-14 12:22:38Z lha $");
-
 struct hdb_dbinfo {
     char *label;
     char *realm;
@@ -63,7 +61,7 @@
=20
     di =3D calloc(1, sizeof(*di));
     if (di =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     di->label =3D strdup(label);
@@ -104,24 +102,24 @@
     dt =3D NULL;
     databases =3D NULL;
=20
-    db_binding =3D krb5_config_get(context, NULL, krb5_config_list,
-				 "kdc",=20
-				 "database",
-				 NULL);
+    db_binding =3D krb5_config_get_list(context, NULL,
+				      "kdc",
+				      "database",
+				      NULL);
     if (db_binding) {
=20
 	ret =3D get_dbinfo(context, db_binding, "default", &di);
 	if (ret =3D=3D 0 && di) {
 	    databases =3D di;
 	    dt =3D &di->next;
-	}	=09
+	}
=20
 	for ( ; db_binding !=3D NULL; db_binding =3D db_binding->next) {
=20
 	    if (db_binding->type !=3D krb5_config_list)
 		continue;
=20
-	    ret =3D get_dbinfo(context, db_binding->u.list,=20
+	    ret =3D get_dbinfo(context, db_binding->u.list,
 			     db_binding->name, &di);
 	    if (ret)
 		krb5_err(context, 1, ret, "failed getting realm");
@@ -159,7 +157,7 @@
 	    else
 		/* the filename is something.else, replace .else with
                    .mkey */
-		asprintf(&di->mkey_file, "%.*s.mkey",=20
+		asprintf(&di->mkey_file, "%.*s.mkey",
 			 (int)(p - di->dbname), di->dbname);
 	}
 	if(di->acl_file =3D=3D NULL)
@@ -228,10 +226,12 @@
=20
     for(di =3D *dbp; di !=3D NULL; di =3D ndi) {
 	ndi =3D di->next;
+	free (di->label);
 	free (di->realm);
 	free (di->dbname);
-	if (di->mkey_file)
-	    free (di->mkey_file);
+	free (di->mkey_file);
+	free (di->acl_file);
+	free (di->log_file);
 	free(di);
     }
     *dbp =3D NULL;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/ext.c
--- a/head/crypto/heimdal/lib/hdb/ext.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/ext.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,60 +1,59 @@
 /*
- * Copyright (c) 2004 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
 #include <der.h>
=20
-RCSID("$Id: ext.c 21113 2007-06-18 12:59:32Z lha $");
-
 krb5_error_code
 hdb_entry_check_mandatory(krb5_context context, const hdb_entry *ent)
 {
-    int i;
+    size_t i;
=20
     if (ent->extensions =3D=3D NULL)
 	return 0;
=20
-    /*=20
+    /*
      * check for unknown extensions and if they where tagged mandatory
      */
=20
     for (i =3D 0; i < ent->extensions->len; i++) {
-	if (ent->extensions->val[i].data.element !=3D=20
+	if (ent->extensions->val[i].data.element !=3D
 	    choice_HDB_extension_data_asn1_ellipsis)
 	    continue;
 	if (ent->extensions->val[i].mandatory) {
-	    krb5_set_error_string(context,  "Principal have unknown "
-				  "mandatory extension");
+	    krb5_set_error_message(context, HDB_ERR_MANDATORY_OPTION,
+				   "Principal have unknown "
+				   "mandatory extension");
 	    return HDB_ERR_MANDATORY_OPTION;
 	}
     }
@@ -64,13 +63,13 @@
 HDB_extension *
 hdb_find_extension(const hdb_entry *entry, int type)
 {
-    int i;
+    size_t i;
=20
     if (entry->extensions =3D=3D NULL)
 	return NULL;
=20
     for (i =3D 0; i < entry->extensions->len; i++)
-	if (entry->extensions->val[i].data.element =3D=3D type)
+	if (entry->extensions->val[i].data.element =3D=3D (unsigned)type)
 	    return &entry->extensions->val[i];
     return NULL;
 }
@@ -82,8 +81,8 @@
  */
=20
 krb5_error_code
-hdb_replace_extension(krb5_context context,=20
-		      hdb_entry *entry,=20
+hdb_replace_extension(krb5_context context,
+		      hdb_entry *entry,
 		      const HDB_extension *ext)
 {
     HDB_extension *ext2;
@@ -95,13 +94,13 @@
     if (entry->extensions =3D=3D NULL) {
 	entry->extensions =3D calloc(1, sizeof(*entry->extensions));
 	if (entry->extensions =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    return ENOMEM;
 	}
     } else if (ext->data.element !=3D choice_HDB_extension_data_asn1_ellip=
sis) {
 	ext2 =3D hdb_find_extension(entry, ext->data.element);
     } else {
-	/*=20
+	/*
 	 * This is an unknown extention, and we are asked to replace a
 	 * possible entry in `entry' that is of the same type. This
 	 * might seem impossible, but ASN.1 CHOICE comes to our
@@ -113,15 +112,15 @@
 	Der_type replace_type, list_type;
 	unsigned int replace_tag, list_tag;
 	size_t size;
-	int i;
+	size_t i;
=20
 	ret =3D der_get_tag(ext->data.u.asn1_ellipsis.data,
 			  ext->data.u.asn1_ellipsis.length,
 			  &replace_class, &replace_type, &replace_tag,
 			  &size);
 	if (ret) {
-	    krb5_set_error_string(context, "hdb: failed to decode "
-				  "replacement hdb extention");
+	    krb5_set_error_message(context, ret, "hdb: failed to decode "
+				   "replacement hdb extention");
 	    return ret;
 	}
=20
@@ -136,8 +135,8 @@
 			      &list_class, &list_type, &list_tag,
 			      &size);
 	    if (ret) {
-		krb5_set_error_string(context, "hdb: failed to decode "
-				      "present hdb extention");
+		krb5_set_error_message(context, ret, "hdb: failed to decode "
+				       "present hdb extention");
 		return ret;
 	    }
=20
@@ -153,15 +152,15 @@
 	free_HDB_extension(ext2);
 	ret =3D copy_HDB_extension(ext, ext2);
 	if (ret)
-	    krb5_set_error_string(context, "hdb: failed to copy replacement "
-				  "hdb extention");
+	    krb5_set_error_message(context, ret, "hdb: failed to copy replacement=
 "
+				   "hdb extention");
 	return ret;
     }
=20
-    es =3D realloc(entry->extensions->val,=20
+    es =3D realloc(entry->extensions->val,
 		 (entry->extensions->len+1)*sizeof(entry->extensions->val[0]));
     if (es =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     entry->extensions->val =3D es;
@@ -171,23 +170,23 @@
     if (ret =3D=3D 0)
 	entry->extensions->len++;
     else
-	krb5_set_error_string(context, "hdb: failed to copy new extension");
+	krb5_set_error_message(context, ret, "hdb: failed to copy new extension");
=20
     return ret;
 }
=20
 krb5_error_code
-hdb_clear_extension(krb5_context context,=20
-		    hdb_entry *entry,=20
+hdb_clear_extension(krb5_context context,
+		    hdb_entry *entry,
 		    int type)
 {
-    int i;
+    size_t i;
=20
     if (entry->extensions =3D=3D NULL)
 	return 0;
=20
     for (i =3D 0; i < entry->extensions->len; i++) {
-	if (entry->extensions->val[i].data.element =3D=3D type) {
+	if (entry->extensions->val[i].data.element =3D=3D (unsigned)type) {
 	    free_HDB_extension(&entry->extensions->val[i]);
 	    memmove(&entry->extensions->val[i],
 		    &entry->extensions->val[i + 1],
@@ -234,6 +233,20 @@
 }
=20
 krb5_error_code
+hdb_entry_get_pkinit_cert(const hdb_entry *entry, const HDB_Ext_PKINIT_cer=
t **a)
+{
+    const HDB_extension *ext;
+
+    ext =3D hdb_find_extension(entry, choice_HDB_extension_data_pkinit_cer=
t);
+    if (ext)
+	*a =3D &ext->data.u.pkinit_cert;
+    else
+	*a =3D NULL;
+
+    return 0;
+}
+
+krb5_error_code
 hdb_entry_get_pw_change_time(const hdb_entry *entry, time_t *t)
 {
     const HDB_extension *ext;
@@ -248,7 +261,7 @@
 }
=20
 krb5_error_code
-hdb_entry_set_pw_change_time(krb5_context context,=20
+hdb_entry_set_pw_change_time(krb5_context context,
 			     hdb_entry *entry,
 			     time_t t)
 {
@@ -264,7 +277,7 @@
 }
=20
 int
-hdb_entry_get_password(krb5_context context, HDB *db,=20
+hdb_entry_get_password(krb5_context context, HDB *db,
 		       const hdb_entry *entry, char **p)
 {
     HDB_extension *ext;
@@ -273,18 +286,19 @@
=20
     ext =3D hdb_find_extension(entry, choice_HDB_extension_data_password);
     if (ext) {
-	heim_utf8_string str;
+	heim_utf8_string xstr;
 	heim_octet_string pw;
=20
 	if (db->hdb_master_key_set && ext->data.u.password.mkvno) {
 	    hdb_master_key key;
=20
-	    key =3D _hdb_find_master_key(ext->data.u.password.mkvno,=20
+	    key =3D _hdb_find_master_key(ext->data.u.password.mkvno,
 				       db->hdb_master_key);
=20
 	    if (key =3D=3D NULL) {
-		krb5_set_error_string(context, "master key %d missing",
-				      *ext->data.u.password.mkvno);
+		krb5_set_error_message(context, HDB_ERR_NO_MKEY,
+				       "master key %d missing",
+				       *ext->data.u.password.mkvno);
 		return HDB_ERR_NO_MKEY;
 	    }
=20
@@ -296,21 +310,21 @@
 	    ret =3D der_copy_octet_string(&ext->data.u.password.password, &pw);
 	}
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    return ret;
 	}
=20
-	str =3D pw.data;
-	if (str[pw.length - 1] !=3D '\0') {
-	    krb5_set_error_string(context, "password malformated");
+	xstr =3D pw.data;
+	if (xstr[pw.length - 1] !=3D '\0') {
+	    krb5_set_error_message(context, EINVAL, "malformed password");
 	    return EINVAL;
 	}
=20
-	*p =3D strdup(str);
+	*p =3D strdup(xstr);
=20
 	der_free_octet_string(&pw);
 	if (*p =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    return ENOMEM;
 	}
 	return 0;
@@ -318,16 +332,17 @@
=20
     ret =3D krb5_unparse_name(context, entry->principal, &str);
     if (ret =3D=3D 0) {
-	krb5_set_error_string(context, "no password attributefor %s", str);
+	krb5_set_error_message(context, ENOENT,
+			       "no password attribute for %s", str);
 	free(str);
-    } else=20
-	krb5_clear_error_string(context);
+    } else
+	krb5_clear_error_message(context);
=20
     return ENOENT;
 }
=20
 int
-hdb_entry_set_password(krb5_context context, HDB *db,=20
+hdb_entry_set_password(krb5_context context, HDB *db,
 		       hdb_entry *entry, const char *p)
 {
     HDB_extension ext;
@@ -341,22 +356,23 @@
=20
 	key =3D _hdb_find_master_key(NULL, db->hdb_master_key);
 	if (key =3D=3D NULL) {
-	    krb5_set_error_string(context, "hdb_entry_set_password: "
-				  "failed to find masterkey");
+	    krb5_set_error_message(context, HDB_ERR_NO_MKEY,
+				   "hdb_entry_set_password: "
+				   "failed to find masterkey");
 	    return HDB_ERR_NO_MKEY;
 	}
=20
 	ret =3D _hdb_mkey_encrypt(context, key, HDB_KU_MKEY,
-				p, strlen(p) + 1,=20
+				p, strlen(p) + 1,
 				&ext.data.u.password.password);
 	if (ret)
 	    return ret;
=20
-	ext.data.u.password.mkvno =3D=20
+	ext.data.u.password.mkvno =3D
 	    malloc(sizeof(*ext.data.u.password.mkvno));
 	if (ext.data.u.password.mkvno =3D=3D NULL) {
 	    free_HDB_extension(&ext);
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    return ENOMEM;
 	}
 	*ext.data.u.password.mkvno =3D _hdb_mkey_version(key);
@@ -364,10 +380,10 @@
     } else {
 	ext.data.u.password.mkvno =3D NULL;
=20
-	ret =3D krb5_data_copy(&ext.data.u.password.password,=20
+	ret =3D krb5_data_copy(&ext.data.u.password.password,
 			     p, strlen(p) + 1);
 	if (ret) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    free_HDB_extension(&ext);
 	    return ret;
 	}
@@ -383,17 +399,17 @@
 int
 hdb_entry_clear_password(krb5_context context, hdb_entry *entry)
 {
-    return hdb_clear_extension(context, entry,=20
+    return hdb_clear_extension(context, entry,
 			       choice_HDB_extension_data_password);
 }
=20
 krb5_error_code
-hdb_entry_get_ConstrainedDelegACL(const hdb_entry *entry,=20
+hdb_entry_get_ConstrainedDelegACL(const hdb_entry *entry,
 				  const HDB_Ext_Constrained_delegation_acl **a)
 {
     const HDB_extension *ext;
=20
-    ext =3D hdb_find_extension(entry,=20
+    ext =3D hdb_find_extension(entry,
 			     choice_HDB_extension_data_allowed_to_delegate_to);
     if (ext)
 	*a =3D &ext->data.u.allowed_to_delegate_to;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb-ldap.c
--- a/head/crypto/heimdal/lib/hdb/hdb-ldap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/hdb-ldap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
  * Copyright (c) 2004, Andrew Bartlett.
- * Copyright (c) 2003 - 2007, Kungliga Tekniska H=F6gskolan.
+ * Copyright (c) 2003 - 2008, Kungliga Tekniska H=C3=B6gskolan.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -34,8 +34,6 @@
=20
 #include "hdb_locl.h"
=20
-RCSID("$Id: hdb-ldap.c 22071 2007-11-14 20:04:50Z lha $");
-
 #ifdef OPENLDAP
=20
 #include <lber.h>
@@ -48,7 +46,7 @@
=20
 static krb5_error_code
 LDAP_message2entry(krb5_context context, HDB * db, LDAPMessage * msg,
-		   hdb_entry_ex * ent);
+		   int flags, hdb_entry_ex * ent);
=20
 static const char *default_structural_object =3D "account";
 static char *structural_object;
@@ -74,7 +72,7 @@
  *
  */
=20
-static char * krb5kdcentry_attrs[] =3D {=20
+static char * krb5kdcentry_attrs[] =3D {
     "cn",
     "createTimestamp",
     "creatorsName",
@@ -121,8 +119,9 @@
=20
     ret =3D ldap_set_option(lp, LDAP_OPT_SIZELIMIT, (const void *)&limit);
     if (ret !=3D LDAP_SUCCESS) {
-	krb5_set_error_string(context, "ldap_set_option: %s",
-			      ldap_err2string(ret));
+	krb5_set_error_message(context, HDB_ERR_BADVERSION,
+			       "ldap_set_option: %s",
+			       ldap_err2string(ret));
 	return HDB_ERR_BADVERSION;
     }
     return 0;
@@ -222,7 +221,7 @@
=20
 	(*modlist)[cMods]->mod_bvalues =3D bv;
=20
-	bv[i] =3D ber_memalloc(sizeof(*bv));;
+	bv[i] =3D ber_memalloc(sizeof(**bv));;
 	if (bv[i] =3D=3D NULL)
 	    return ENOMEM;
=20
@@ -295,8 +294,9 @@
=20
     ret =3D asprintf(&buf, "%ld", l);
     if (ret < 0) {
-	krb5_set_error_string(context, "asprintf: out of memory:");
-	return ret;
+	krb5_set_error_message(context, ENOMEM,
+			       "asprintf: out of memory:");
+	return ENOMEM;
     }
     ret =3D LDAP_addmod(mods, modop, attribute, buf);
     free (buf);
@@ -307,38 +307,40 @@
 LDAP_get_string_value(HDB * db, LDAPMessage * entry,
 		      const char *attribute, char **ptr)
 {
-    char **vals;
-    int ret;
+    struct berval **vals;
=20
-    vals =3D ldap_get_values(HDB2LDAP(db), entry, (char *) attribute);
-    if (vals =3D=3D NULL) {
+    vals =3D ldap_get_values_len(HDB2LDAP(db), entry, attribute);
+    if (vals =3D=3D NULL || vals[0] =3D=3D NULL) {
 	*ptr =3D NULL;
 	return HDB_ERR_NOENTRY;
     }
=20
-    *ptr =3D strdup(vals[0]);
-    if (*ptr =3D=3D NULL)
-	ret =3D ENOMEM;
-    else
-	ret =3D 0;
+    *ptr =3D malloc(vals[0]->bv_len + 1);
+    if (*ptr =3D=3D NULL) {
+	ldap_value_free_len(vals);
+	return ENOMEM;
+    }
=20
-    ldap_value_free(vals);
+    memcpy(*ptr, vals[0]->bv_val, vals[0]->bv_len);
+    (*ptr)[vals[0]->bv_len] =3D 0;
=20
-    return ret;
+    ldap_value_free_len(vals);
+
+    return 0;
 }
=20
 static krb5_error_code
 LDAP_get_integer_value(HDB * db, LDAPMessage * entry,
 		       const char *attribute, int *ptr)
 {
-    char **vals;
+    krb5_error_code ret;
+    char *val;
=20
-    vals =3D ldap_get_values(HDB2LDAP(db), entry, (char *) attribute);
-    if (vals =3D=3D NULL)
-	return HDB_ERR_NOENTRY;
-
-    *ptr =3D atoi(vals[0]);
-    ldap_value_free(vals);
+    ret =3D LDAP_get_string_value(db, entry, attribute, &val);
+    if (ret)
+	return ret;
+    *ptr =3D atoi(val);
+    free(val);
     return 0;
 }
=20
@@ -369,6 +371,14 @@
     return 0;
 }
=20
+static int
+bervalstrcmp(struct berval *v, const char *str)
+{
+    size_t len =3D strlen(str);
+    return (v->bv_len =3D=3D len) && strncasecmp(str, (char *)v->bv_val, l=
en) =3D=3D 0;
+}
+
+
 static krb5_error_code
 LDAP_entry2mods(krb5_context context, HDB * db, hdb_entry_ex * ent,
 		LDAPMessage * msg, LDAPMod *** pmods)
@@ -386,40 +396,39 @@
     krb5_boolean is_heimdal_entry =3D FALSE;
     krb5_boolean is_heimdal_principal =3D FALSE;
=20
-    char **values;
+    struct berval **vals;
=20
     *pmods =3D NULL;
=20
     if (msg !=3D NULL) {
=20
-	ret =3D LDAP_message2entry(context, db, msg, &orig);
+	ret =3D LDAP_message2entry(context, db, msg, 0, &orig);
 	if (ret)
 	    goto out;
=20
 	is_new_entry =3D FALSE;
-	   =20
-	values =3D ldap_get_values(HDB2LDAP(db), msg, "objectClass");
-	if (values) {
-	    int num_objectclasses =3D ldap_count_values(values);
+
+	vals =3D ldap_get_values_len(HDB2LDAP(db), msg, "objectClass");
+	if (vals) {
+	    int num_objectclasses =3D ldap_count_values_len(vals);
 	    for (i=3D0; i < num_objectclasses; i++) {
-		if (strcasecmp(values[i], "sambaSamAccount") =3D=3D 0) {
+		if (bervalstrcmp(vals[i], "sambaSamAccount"))
 		    is_samba_account =3D TRUE;
-		} else if (strcasecmp(values[i], structural_object) =3D=3D 0) {
+		else if (bervalstrcmp(vals[i], structural_object))
 		    is_account =3D TRUE;
-		} else if (strcasecmp(values[i], "krb5Principal") =3D=3D 0) {
+		else if (bervalstrcmp(vals[i], "krb5Principal"))
 		    is_heimdal_principal =3D TRUE;
-		} else if (strcasecmp(values[i], "krb5KDCEntry") =3D=3D 0) {
+		else if (bervalstrcmp(vals[i], "krb5KDCEntry"))
 		    is_heimdal_entry =3D TRUE;
-		}
 	    }
-	    ldap_value_free(values);
+	    ldap_value_free_len(vals);
 	}
=20
 	/*
 	 * If this is just a "account" entry and no other objectclass
 	 * is hanging on this entry, it's really a new entry.
 	 */
-	if (is_samba_account =3D=3D FALSE && is_heimdal_principal =3D=3D FALSE &&=20
+	if (is_samba_account =3D=3D FALSE && is_heimdal_principal =3D=3D FALSE &&
 	    is_heimdal_entry =3D=3D FALSE) {
 	    if (is_account =3D=3D TRUE) {
 		is_new_entry =3D TRUE;
@@ -440,10 +449,10 @@
 	ret =3D LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass", "top");
 	if (ret)
 	    goto out;
-=09
+
 	/* account is the structural object class */
 	if (is_account =3D=3D FALSE) {
-	    ret =3D LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass",=20
+	    ret =3D LDAP_addmod(&mods, LDAP_MOD_ADD, "objectClass",
 			      structural_object);
 	    is_account =3D TRUE;
 	    if (ret)
@@ -461,7 +470,7 @@
 	    goto out;
     }
=20
-    if (is_new_entry ||=20
+    if (is_new_entry ||
 	krb5_principal_compare(context, ent->entry.principal, orig.entry.principa=
l)
 	=3D=3D FALSE)
     {
@@ -495,7 +504,7 @@
=20
     if (is_heimdal_entry && (ent->entry.kvno !=3D orig.entry.kvno || is_ne=
w_entry)) {
 	ret =3D LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
-			    "krb5KeyVersionNumber",=20
+			    "krb5KeyVersionNumber",
 			    ent->entry.kvno);
 	if (ret)
 	    goto out;
@@ -514,7 +523,7 @@
=20
     if (ent->entry.valid_end) {
  	if (orig.entry.valid_end =3D=3D NULL || (*(ent->entry.valid_end) !=3D *(=
orig.entry.valid_end))) {
-	    if (is_heimdal_entry) {=20
+	    if (is_heimdal_entry) {
 		ret =3D LDAP_addmod_generalized_time(&mods, LDAP_MOD_REPLACE,
 						   "krb5ValidEnd",
 						   ent->entry.valid_end);
@@ -523,7 +532,7 @@
             }
 	    if (is_samba_account) {
 		ret =3D LDAP_addmod_integer(context, &mods,  LDAP_MOD_REPLACE,
-					  "sambaKickoffTime",=20
+					  "sambaKickoffTime",
 					  *(ent->entry.valid_end));
 		if (ret)
 		    goto out;
@@ -543,7 +552,7 @@
=20
 	    if (is_samba_account) {
 		ret =3D LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
-					  "sambaPwdMustChange",=20
+					  "sambaPwdMustChange",
 					  *(ent->entry.pw_end));
 		if (ret)
 		    goto out;
@@ -556,7 +565,7 @@
     if (is_samba_account && ent->entry.last_pw_change) {
 	if (orig.entry.last_pw_change =3D=3D NULL || (*(ent->entry.last_pw_change=
) !=3D *(orig.entry.last_pw_change))) {
 	    ret =3D LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
-				      "sambaPwdLastSet",=20
+				      "sambaPwdLastSet",
 				      *(ent->entry.last_pw_change));
 	    if (ret)
 		goto out;
@@ -569,7 +578,7 @@
 	    || (*(ent->entry.max_life) !=3D *(orig.entry.max_life))) {
=20
 	    ret =3D LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
-				      "krb5MaxLife",=20
+				      "krb5MaxLife",
 				      *(ent->entry.max_life));
 	    if (ret)
 		goto out;
@@ -602,9 +611,9 @@
=20
     /* Remove keys if they exists, and then replace keys. */
     if (!is_new_entry && orig.entry.keys.len > 0) {
-	values =3D ldap_get_values(HDB2LDAP(db), msg, "krb5Key");
-	if (values) {
-	    ldap_value_free(values);
+	vals =3D ldap_get_values_len(HDB2LDAP(db), msg, "krb5Key");
+	if (vals) {
+	    ldap_value_free_len(vals);
=20
 	    ret =3D LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5Key", NULL);
 	    if (ret)
@@ -618,38 +627,43 @@
 	    && ent->entry.keys.val[i].key.keytype =3D=3D ETYPE_ARCFOUR_HMAC_MD5) {
 	    char *ntHexPassword;
 	    char *nt;
-		   =20
+	    time_t now =3D time(NULL);
+
 	    /* the key might have been 'sealed', but samba passwords
 	       are clear in the directory */
 	    ret =3D hdb_unseal_key(context, db, &ent->entry.keys.val[i]);
 	    if (ret)
 		goto out;
-		   =20
+
 	    nt =3D ent->entry.keys.val[i].key.keyvalue.data;
 	    /* store in ntPassword, not krb5key */
 	    ret =3D hex_encode(nt, 16, &ntHexPassword);
 	    if (ret < 0) {
-		krb5_set_error_string(context, "hdb-ldap: failed to "
+		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "hdb-ldap: failed to "
 				      "hex encode key");
-		ret =3D ENOMEM;
 		goto out;
 	    }
-	    ret =3D LDAP_addmod(&mods, LDAP_MOD_REPLACE, "sambaNTPassword",=20
+	    ret =3D LDAP_addmod(&mods, LDAP_MOD_REPLACE, "sambaNTPassword",
 			      ntHexPassword);
 	    free(ntHexPassword);
 	    if (ret)
 		goto out;
-		   =20
+	    ret =3D LDAP_addmod_integer(context, &mods, LDAP_MOD_REPLACE,
+				      "sambaPwdLastSet", now);
+	    if (ret)
+		goto out;
+
 	    /* have to kill the LM passwod if it exists */
-	    values =3D ldap_get_values(HDB2LDAP(db), msg, "sambaLMPassword");
-	    if (values) {
-		ldap_value_free(values);
+	    vals =3D ldap_get_values_len(HDB2LDAP(db), msg, "sambaLMPassword");
+	    if (vals) {
+		ldap_value_free_len(vals);
 		ret =3D LDAP_addmod(&mods, LDAP_MOD_DELETE,
 				  "sambaLMPassword", NULL);
 		if (ret)
 		    goto out;
 	    }
-		   =20
+
 	} else if (is_heimdal_entry) {
 	    unsigned char *buf;
 	    size_t len, buf_size;
@@ -670,15 +684,15 @@
     if (ent->entry.etypes) {
 	int add_krb5EncryptionType =3D 0;
=20
-	/*=20
+	/*
 	 * Only add/modify krb5EncryptionType if it's a new heimdal
 	 * entry or krb5EncryptionType already exists on the entry.
 	 */
=20
 	if (!is_new_entry) {
-	    values =3D ldap_get_values(HDB2LDAP(db), msg, "krb5EncryptionType");
-	    if (values) {
-		ldap_value_free(values);
+	    vals =3D ldap_get_values_len(HDB2LDAP(db), msg, "krb5EncryptionType");
+	    if (vals) {
+		ldap_value_free_len(vals);
 		ret =3D LDAP_addmod(&mods, LDAP_MOD_DELETE, "krb5EncryptionType",
 				  NULL);
 		if (ret)
@@ -690,7 +704,7 @@
=20
 	if (add_krb5EncryptionType) {
 	    for (i =3D 0; i < ent->entry.etypes->len; i++) {
-		if (is_samba_account &&=20
+		if (is_samba_account &&
 		    ent->entry.keys.val[i].key.keytype =3D=3D ETYPE_ARCFOUR_HMAC_MD5)
 		{
 		    ;
@@ -730,20 +744,22 @@
     krb5_error_code ret;
     int rc;
     const char *filter =3D "(objectClass=3Dkrb5Principal)";
-    char **values;
     LDAPMessage *res =3D NULL, *e;
+    char *p;
=20
     ret =3D LDAP_no_size_limit(context, HDB2LDAP(db));
     if (ret)
 	goto out;
=20
-    rc =3D ldap_search_s(HDB2LDAP(db), dn, LDAP_SCOPE_SUBTREE,
-		       filter, krb5principal_attrs,
-		       0, &res);
+    rc =3D ldap_search_ext_s(HDB2LDAP(db), dn, LDAP_SCOPE_SUBTREE,
+			   filter, krb5principal_attrs, 0,
+			   NULL, NULL, NULL,
+			   0, &res);
     if (check_ldap(context, db, rc)) {
-	krb5_set_error_string(context, "ldap_search_s: filter: %s error: %s",
-			      filter, ldap_err2string(rc));
 	ret =3D HDB_ERR_NOENTRY;
+	krb5_set_error_message(context, ret, "ldap_search_ext_s: "
+			       "filter: %s error: %s",
+			       filter, ldap_err2string(rc));
 	goto out;
     }
=20
@@ -753,14 +769,14 @@
 	goto out;
     }
=20
-    values =3D ldap_get_values(HDB2LDAP(db), e, "krb5PrincipalName");
-    if (values =3D=3D NULL) {
+    ret =3D LDAP_get_string_value(db, e, "krb5PrincipalName", &p);
+    if (ret) {
 	ret =3D HDB_ERR_NOENTRY;
 	goto out;
     }
=20
-    ret =3D krb5_parse_name(context, values[0], principal);
-    ldap_value_free(values);
+    ret =3D krb5_parse_name(context, p, principal);
+    free(p);
=20
   out:
     if (res)
@@ -769,6 +785,49 @@
     return ret;
 }
=20
+static int
+need_quote(unsigned char c)
+{
+    return (c & 0x80) ||
+	(c < 32) ||
+	(c =3D=3D '(') ||
+	(c =3D=3D ')') ||
+	(c =3D=3D '*') ||
+	(c =3D=3D '\\') ||
+	(c =3D=3D 0x7f);
+}
+
+const static char hexchar[] =3D "0123456789ABCDEF";
+
+static krb5_error_code
+escape_value(krb5_context context, const unsigned char *unquoted, char **q=
uoted)
+{
+    size_t i, len;
+
+    for (i =3D 0, len =3D 0; unquoted[i] !=3D '\0'; i++, len++) {
+	if (need_quote((unsigned char)unquoted[i]))
+	    len +=3D 2;
+    }
+
+    *quoted =3D malloc(len + 1);
+    if (*quoted =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	return ENOMEM;
+    }
+
+    for (i =3D 0; unquoted[0] ; unquoted++) {
+	if (need_quote((unsigned char *)unquoted[0])) {
+	    (*quoted)[i++] =3D '\\';
+	    (*quoted)[i++] =3D hexchar[(unquoted[0] >> 4) & 0xf];
+	    (*quoted)[i++] =3D hexchar[(unquoted[0]     ) & 0xf];
+	} else
+	    (*quoted)[i++] =3D (char)unquoted[0];
+    }
+    (*quoted)[i] =3D '\0';
+    return 0;
+}
+
+
 static krb5_error_code
 LDAP__lookup_princ(krb5_context context,
 		   HDB *db,
@@ -778,18 +837,29 @@
 {
     krb5_error_code ret;
     int rc;
-    char *filter =3D NULL;
+    char *quote, *filter =3D NULL;
=20
     ret =3D LDAP__connect(context, db);
     if (ret)
 	return ret;
=20
+    /*
+     * Quote searches that contain filter language, this quote
+     * searches for *@REALM, which takes very long time.
+     */
+
+    ret =3D escape_value(context, princname, &quote);
+    if (ret)
+	goto out;
+
     rc =3D asprintf(&filter,
 		  "(&(objectClass=3Dkrb5Principal)(krb5PrincipalName=3D%s))",
-		  princname);
+		  quote);
+    free(quote);
+
     if (rc < 0) {
-	krb5_set_error_string(context, "asprintf: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, "malloc: out of memory");
 	goto out;
     }
=20
@@ -797,12 +867,16 @@
     if (ret)
 	goto out;
=20
-    rc =3D ldap_search_s(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE, f=
ilter,=20
-		       krb5kdcentry_attrs, 0, msg);
+    rc =3D ldap_search_ext_s(HDB2LDAP(db), HDB2BASE(db),
+			   LDAP_SCOPE_SUBTREE, filter,
+			   krb5kdcentry_attrs, 0,
+			   NULL, NULL, NULL,
+			   0, msg);
     if (check_ldap(context, db, rc)) {
-	krb5_set_error_string(context, "ldap_search_s: filter: %s - error: %s",
+	ret =3D HDB_ERR_NOENTRY;
+	krb5_set_error_message(context, ret, "ldap_search_ext_s: "
+			      "filter: %s - error: %s",
 			      filter, ldap_err2string(rc));
-	ret =3D HDB_ERR_NOENTRY;
 	goto out;
     }
=20
@@ -811,27 +885,34 @@
 	filter =3D NULL;
 	ldap_msgfree(*msg);
 	*msg =3D NULL;
-=09
+
+	ret =3D escape_value(context, userid, &quote);
+	if (ret)
+	    goto out;
+
 	rc =3D asprintf(&filter,
 	    "(&(|(objectClass=3DsambaSamAccount)(objectClass=3D%s))(uid=3D%s))",
-		      structural_object, userid);
+		      structural_object, quote);
+	free(quote);
 	if (rc < 0) {
-	    krb5_set_error_string(context, "asprintf: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "asprintf: out of memory");
 	    goto out;
 	}
-	   =20
+
 	ret =3D LDAP_no_size_limit(context, HDB2LDAP(db));
 	if (ret)
 	    goto out;
=20
-	rc =3D ldap_search_s(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE,=20
-			   filter, krb5kdcentry_attrs, 0, msg);
+	rc =3D ldap_search_ext_s(HDB2LDAP(db), HDB2BASE(db), LDAP_SCOPE_SUBTREE,
+			       filter, krb5kdcentry_attrs, 0,
+			       NULL, NULL, NULL,
+			       0, msg);
 	if (check_ldap(context, db, rc)) {
-	    krb5_set_error_string(context,=20
-				  "ldap_search_s: filter: %s error: %s",
-				  filter, ldap_err2string(rc));
 	    ret =3D HDB_ERR_NOENTRY;
+	    krb5_set_error_message(context, ret,
+				   "ldap_search_ext_s: filter: %s error: %s",
+				   filter, ldap_err2string(rc));
 	    goto out;
 	}
     }
@@ -889,14 +970,13 @@
  */
 static krb5_error_code
 LDAP_message2entry(krb5_context context, HDB * db, LDAPMessage * msg,
-		   hdb_entry_ex * ent)
+		   int flags, hdb_entry_ex * ent)
 {
     char *unparsed_name =3D NULL, *dn =3D NULL, *ntPasswordIN =3D NULL;
     char *samba_acct_flags =3D NULL;
-    unsigned long tmp;
     struct berval **keys;
-    char **values;
-    int tmp_time, i, ret, have_arcfour =3D 0;
+    struct berval **vals;
+    int tmp, tmp_time, i, ret, have_arcfour =3D 0;
=20
     memset(ent, 0, sizeof(*ent));
     ent->entry.flags =3D int2HDBFlags(0);
@@ -914,7 +994,8 @@
 	    if (ret)
 		goto out;
 	} else {
-	    krb5_set_error_string(context, "hdb-ldap: ldap entry missing"
+	    krb5_set_error_message(context, HDB_ERR_NOENTRY,
+				   "hdb-ldap: ldap entry missing"
 				  "principal name");
 	    return HDB_ERR_NOENTRY;
 	}
@@ -938,8 +1019,8 @@
 	ent->entry.keys.len =3D ldap_count_values_len(keys);
 	ent->entry.keys.val =3D (Key *) calloc(ent->entry.keys.len, sizeof(Key));
 	if (ent->entry.keys.val =3D=3D NULL) {
-	    krb5_set_error_string(context, "calloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "calloc: out of memory");
 	    goto out;
 	}
 	for (i =3D 0; i < ent->entry.keys.len; i++) {
@@ -962,27 +1043,39 @@
 #endif
     }
=20
-    values =3D ldap_get_values(HDB2LDAP(db), msg, "krb5EncryptionType");
-    if (values !=3D NULL) {
+    vals =3D ldap_get_values_len(HDB2LDAP(db), msg, "krb5EncryptionType");
+    if (vals !=3D NULL) {
 	int i;
=20
 	ent->entry.etypes =3D malloc(sizeof(*(ent->entry.etypes)));
 	if (ent->entry.etypes =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret,"malloc: out of memory");
 	    goto out;
 	}
-	ent->entry.etypes->len =3D ldap_count_values(values);
+	ent->entry.etypes->len =3D ldap_count_values_len(vals);
 	ent->entry.etypes->val =3D calloc(ent->entry.etypes->len, sizeof(int));
 	if (ent->entry.etypes->val =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
+	    ent->entry.etypes->len =3D 0;
 	    goto out;
 	}
 	for (i =3D 0; i < ent->entry.etypes->len; i++) {
-	    ent->entry.etypes->val[i] =3D atoi(values[i]);
+	    char *buf;
+
+	    buf =3D malloc(vals[i]->bv_len + 1);
+	    if (buf =3D=3D NULL) {
+		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
+		goto out;
+	    }
+	    memcpy(buf, vals[i]->bv_val, vals[i]->bv_len);
+	    buf[vals[i]->bv_len] =3D '\0';
+	    ent->entry.etypes->val[i] =3D atoi(buf);
+	    free(buf);
 	}
-	ldap_value_free(values);
+	ldap_value_free_len(vals);
     }
=20
     for (i =3D 0; i < ent->entry.keys.len; i++) {
@@ -1003,8 +1096,8 @@
 		       (ent->entry.keys.len + 1) * sizeof(ent->entry.keys.val[0]));
 	if (keys =3D=3D NULL) {
 	    free(ntPasswordIN);
-	    krb5_set_error_string(context, "malloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	ent->entry.keys.val =3D keys;
@@ -1012,7 +1105,7 @@
 	ent->entry.keys.val[ent->entry.keys.len].key.keytype =3D ETYPE_ARCFOUR_HM=
AC_MD5;
 	ret =3D krb5_data_alloc (&ent->entry.keys.val[ent->entry.keys.len].key.ke=
yvalue, 16);
 	if (ret) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    free(ntPasswordIN);
 	    ret =3D ENOMEM;
 	    goto out;
@@ -1024,8 +1117,8 @@
 	if (ent->entry.etypes =3D=3D NULL) {
 	    ent->entry.etypes =3D malloc(sizeof(*(ent->entry.etypes)));
 	    if (ent->entry.etypes =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
 	    ent->entry.etypes->val =3D NULL;
@@ -1037,16 +1130,16 @@
 		break;
 	/* If there is no ARCFOUR enctype, add one */
 	if (i =3D=3D ent->entry.etypes->len) {
-	    etypes =3D realloc(ent->entry.etypes->val,=20
-			     (ent->entry.etypes->len + 1) *=20
+	    etypes =3D realloc(ent->entry.etypes->val,
+			     (ent->entry.etypes->len + 1) *
 			     sizeof(ent->entry.etypes->val[0]));
 	    if (etypes =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
 		ret =3D ENOMEM;
-		goto out;			   =20
+		krb5_set_error_message(context, ret, "malloc: out of memory");
+		goto out;
 	    }
 	    ent->entry.etypes->val =3D etypes;
-	    ent->entry.etypes->val[ent->entry.etypes->len] =3D=20
+	    ent->entry.etypes->val[ent->entry.etypes->len] =3D
 		ETYPE_ARCFOUR_HMAC_MD5;
 	    ent->entry.etypes->len++;
 	}
@@ -1059,37 +1152,38 @@
=20
     ent->entry.created_by.principal =3D NULL;
=20
-    ret =3D LDAP_get_string_value(db, msg, "creatorsName", &dn);
-    if (ret =3D=3D 0) {
-	if (LDAP_dn2principal(context, db, dn, &ent->entry.created_by.principal)
-	    !=3D 0) {
-	    ent->entry.created_by.principal =3D NULL;
+    if (flags & HDB_F_ADMIN_DATA) {
+	ret =3D LDAP_get_string_value(db, msg, "creatorsName", &dn);
+	if (ret =3D=3D 0) {
+	    LDAP_dn2principal(context, db, dn, &ent->entry.created_by.principal);
+	    free(dn);
 	}
-	free(dn);
-    }
=20
-    ent->entry.modified_by =3D (Event *) malloc(sizeof(Event));
-    if (ent->entry.modified_by =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	ret =3D ENOMEM;
-	goto out;
-    }
-    ret =3D LDAP_get_generalized_time_value(db, msg, "modifyTimestamp",
-					  &ent->entry.modified_by->time);
-    if (ret =3D=3D 0) {
-	ret =3D LDAP_get_string_value(db, msg, "modifiersName", &dn);
-	if (LDAP_dn2principal(context, db, dn, &ent->entry.modified_by->principal=
))
-	    ent->entry.modified_by->principal =3D NULL;
-	free(dn);
-    } else {
-	free(ent->entry.modified_by);
-	ent->entry.modified_by =3D NULL;
+	ent->entry.modified_by =3D calloc(1, sizeof(*ent->entry.modified_by));
+	if (ent->entry.modified_by =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
+	    goto out;
+	}
+
+	ret =3D LDAP_get_generalized_time_value(db, msg, "modifyTimestamp",
+					      &ent->entry.modified_by->time);
+	if (ret =3D=3D 0) {
+	    ret =3D LDAP_get_string_value(db, msg, "modifiersName", &dn);
+	    if (ret =3D=3D 0) {
+		LDAP_dn2principal(context, db, dn, &ent->entry.modified_by->principal);
+		free(dn);
+	    } else {
+		free(ent->entry.modified_by);
+		ent->entry.modified_by =3D NULL;
+	    }
+	}
     }
=20
     ent->entry.valid_start =3D malloc(sizeof(*ent->entry.valid_start));
     if (ent->entry.valid_start =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, "malloc: out of memory");
 	goto out;
     }
     ret =3D LDAP_get_generalized_time_value(db, msg, "krb5ValidStart",
@@ -1099,11 +1193,11 @@
 	free(ent->entry.valid_start);
 	ent->entry.valid_start =3D NULL;
     }
-   =20
+
     ent->entry.valid_end =3D malloc(sizeof(*ent->entry.valid_end));
     if (ent->entry.valid_end =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, "malloc: out of memory");
 	goto out;
     }
     ret =3D LDAP_get_generalized_time_value(db, msg, "krb5ValidEnd",
@@ -1119,8 +1213,8 @@
  	if (ent->entry.valid_end =3D=3D NULL) {
  	    ent->entry.valid_end =3D malloc(sizeof(*ent->entry.valid_end));
  	    if (ent->entry.valid_end =3D=3D NULL) {
- 		krb5_set_error_string(context, "malloc: out of memory");
  		ret =3D ENOMEM;
+ 		krb5_set_error_message(context, ret, "malloc: out of memory");
  		goto out;
  	    }
  	}
@@ -1129,8 +1223,8 @@
=20
     ent->entry.pw_end =3D malloc(sizeof(*ent->entry.pw_end));
     if (ent->entry.pw_end =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, "malloc: out of memory");
 	goto out;
     }
     ret =3D LDAP_get_generalized_time_value(db, msg, "krb5PasswordEnd",
@@ -1141,13 +1235,34 @@
 	ent->entry.pw_end =3D NULL;
     }
=20
+    ret =3D LDAP_get_integer_value(db, msg, "sambaPwdLastSet", &tmp_time);
+    if (ret =3D=3D 0) {
+	time_t delta;
+
+	if (ent->entry.pw_end =3D=3D NULL) {
+            ent->entry.pw_end =3D malloc(sizeof(*ent->entry.pw_end));
+            if (ent->entry.pw_end =3D=3D NULL) {
+                ret =3D ENOMEM;
+                krb5_set_error_message(context, ret, "malloc: out of memor=
y");
+                goto out;
+            }
+        }
+
+	delta =3D krb5_config_get_time_default(context, NULL,
+					     365 * 24 * 60 * 60,
+					     "kadmin",
+					     "password_lifetime",
+					     NULL);
+        *ent->entry.pw_end =3D tmp_time + delta;
+    }
+
     ret =3D LDAP_get_integer_value(db, msg, "sambaPwdMustChange", &tmp_tim=
e);
     if (ret =3D=3D 0) {
 	if (ent->entry.pw_end =3D=3D NULL) {
 	    ent->entry.pw_end =3D malloc(sizeof(*ent->entry.pw_end));
 	    if (ent->entry.pw_end =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
 		goto out;
 	    }
 	}
@@ -1164,8 +1279,8 @@
=20
 	ent->entry.max_life =3D malloc(sizeof(*ent->entry.max_life));
 	if (ent->entry.max_life =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	ret =3D LDAP_get_integer_value(db, msg, "krb5MaxLife", &max_life);
@@ -1181,8 +1296,8 @@
=20
 	ent->entry.max_renew =3D malloc(sizeof(*ent->entry.max_renew));
 	if (ent->entry.max_renew =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	    goto out;
 	}
 	ret =3D LDAP_get_integer_value(db, msg, "krb5MaxRenew", &max_renew);
@@ -1193,18 +1308,9 @@
 	    *ent->entry.max_renew =3D max_renew;
     }
=20
-    values =3D ldap_get_values(HDB2LDAP(db), msg, "krb5KDCFlags");
-    if (values !=3D NULL) {
-	errno =3D 0;
-	tmp =3D strtoul(values[0], (char **) NULL, 10);
-	if (tmp =3D=3D ULONG_MAX && errno =3D=3D ERANGE) {
-	    krb5_set_error_string(context, "strtoul: could not convert flag");
-	    ret =3D ERANGE;
-	    goto out;
-	}
-    } else {
+    ret =3D LDAP_get_integer_value(db, msg, "krb5KDCFlags", &tmp);
+    if (ret)
 	tmp =3D 0;
-    }
=20
     ent->entry.flags =3D int2HDBFlags(tmp);
=20
@@ -1212,29 +1318,29 @@
     ret =3D LDAP_get_string_value(db, msg, "sambaAcctFlags", &samba_acct_f=
lags);
     if (ret =3D=3D 0) {
 	/* parse the [UXW...] string:
-	      =20
-	   'N'    No password	=20
-	   'D'    Disabled	=20
-	   'H'    Homedir required	=20
-	   'T'    Temp account.	=20
-	   'U'    User account (normal) 	=20
-	   'M'    MNS logon user account - what is this ? 	=20
-	   'W'    Workstation account	=20
-	   'S'    Server account 	=20
-	   'L'    Locked account	=20
-	   'X'    No Xpiry on password 	=20
-	   'I'    Interdomain trust account	=20
-	   =20
-	*/	=20
-	   =20
+
+	   'N'    No password
+	   'D'    Disabled
+	   'H'    Homedir required
+	   'T'    Temp account.
+	   'U'    User account (normal)
+	   'M'    MNS logon user account - what is this ?
+	   'W'    Workstation account
+	   'S'    Server account
+	   'L'    Locked account
+	   'X'    No Xpiry on password
+	   'I'    Interdomain trust account
+
+	*/
+
 	int i;
 	int flags_len =3D strlen(samba_acct_flags);
=20
 	if (flags_len < 2)
 	    goto out2;
=20
-	if (samba_acct_flags[0] !=3D '['=20
-	    || samba_acct_flags[flags_len - 1] !=3D ']')=20
+	if (samba_acct_flags[0] !=3D '['
+	    || samba_acct_flags[flags_len - 1] !=3D ']')
 	    goto out2;
=20
 	/* Allow forwarding */
@@ -1307,7 +1413,7 @@
 	ldap_unbind_ext(HDB2LDAP(db), NULL, NULL);
 	((struct hdbldapdb *)db->hdb_db)->h_lp =3D NULL;
     }
-   =20
+
     return 0;
 }
=20
@@ -1343,7 +1449,7 @@
 	    break;
 	case LDAP_RES_SEARCH_ENTRY:
 	    /* We have an entry. Parse it. */
-	    ret =3D LDAP_message2entry(context, db, e, entry);
+	    ret =3D LDAP_message2entry(context, db, e, flags, entry);
 	    ldap_msgfree(e);
 	    break;
 	case LDAP_RES_SEARCH_RESULT:
@@ -1351,13 +1457,13 @@
 	    parserc =3D
 		ldap_parse_result(HDB2LDAP(db), e, NULL, NULL, NULL,
 				  NULL, NULL, 1);
+	    ret =3D HDB_ERR_NOENTRY;
 	    if (parserc !=3D LDAP_SUCCESS
 		&& parserc !=3D LDAP_MORE_RESULTS_TO_RETURN) {
-	        krb5_set_error_string(context, "ldap_parse_result: %s",
-				      ldap_err2string(parserc));
-		ldap_abandon(HDB2LDAP(db), msgid);
+	        krb5_set_error_message(context, ret, "ldap_parse_result: %s",
+				       ldap_err2string(parserc));
+		ldap_abandon_ext(HDB2LDAP(db), msgid, NULL, NULL);
 	    }
-	    ret =3D HDB_ERR_NOENTRY;
 	    HDBSETMSGID(db, -1);
 	    break;
 	case LDAP_SERVER_DOWN:
@@ -1369,7 +1475,7 @@
 	default:
 	    /* Some unspecified error (timeout?). Abandon. */
 	    ldap_msgfree(e);
-	    ldap_abandon(HDB2LDAP(db), msgid);
+	    ldap_abandon_ext(HDB2LDAP(db), msgid, NULL, NULL);
 	    ret =3D HDB_ERR_NOENTRY;
 	    HDBSETMSGID(db, -1);
 	    break;
@@ -1402,10 +1508,11 @@
     if (ret)
 	return ret;
=20
-    msgid =3D ldap_search(HDB2LDAP(db), HDB2BASE(db),
+    ret =3D ldap_search_ext(HDB2LDAP(db), HDB2BASE(db),
 			LDAP_SCOPE_SUBTREE,
 			"(|(objectClass=3Dkrb5Principal)(objectClass=3DsambaSamAccount))",
-			krb5kdcentry_attrs, 0);
+			krb5kdcentry_attrs, 0,
+			NULL, NULL, NULL, 0, &msgid);
     if (msgid < 0)
 	return HDB_ERR_NOENTRY;
=20
@@ -1451,16 +1558,16 @@
=20
     rc =3D ldap_initialize(&((struct hdbldapdb *)db->hdb_db)->h_lp, HDB2UR=
L(db));
     if (rc !=3D LDAP_SUCCESS) {
-	krb5_set_error_string(context, "ldap_initialize: %s",=20
-			      ldap_err2string(rc));
+	krb5_set_error_message(context, HDB_ERR_NOENTRY, "ldap_initialize: %s",
+			       ldap_err2string(rc));
 	return HDB_ERR_NOENTRY;
     }
=20
     rc =3D ldap_set_option(HDB2LDAP(db), LDAP_OPT_PROTOCOL_VERSION,
 			 (const void *)&version);
     if (rc !=3D LDAP_SUCCESS) {
-	krb5_set_error_string(context, "ldap_set_option: %s",
-			      ldap_err2string(rc));
+	krb5_set_error_message(context, HDB_ERR_BADVERSION,
+			       "ldap_set_option: %s", ldap_err2string(rc));
 	LDAP_close(context, db);
 	return HDB_ERR_BADVERSION;
     }
@@ -1468,8 +1575,8 @@
     rc =3D ldap_sasl_bind_s(HDB2LDAP(db), NULL, "EXTERNAL", &bv,
 			  NULL, NULL, NULL);
     if (rc !=3D LDAP_SUCCESS) {
-	krb5_set_error_string(context, "ldap_sasl_bind_s: %s",
-			      ldap_err2string(rc));
+	krb5_set_error_message(context, HDB_ERR_BADVERSION,
+			      "ldap_sasl_bind_s: %s", ldap_err2string(rc));
 	LDAP_close(context, db);
 	return HDB_ERR_BADVERSION;
     }
@@ -1497,8 +1604,8 @@
 }
=20
 static krb5_error_code
-LDAP_fetch(krb5_context context, HDB * db, krb5_const_principal principal,
-	   unsigned flags, hdb_entry_ex * entry)
+LDAP_fetch_kvno(krb5_context context, HDB * db, krb5_const_principal princ=
ipal,
+		unsigned flags, krb5_kvno kvno, hdb_entry_ex * entry)
 {
     LDAPMessage *msg, *e;
     krb5_error_code ret;
@@ -1513,7 +1620,7 @@
 	goto out;
     }
=20
-    ret =3D LDAP_message2entry(context, db, e, entry);
+    ret =3D LDAP_message2entry(context, db, e, flags, entry);
     if (ret =3D=3D 0) {
 	if (db->hdb_master_key_set && (flags & HDB_F_DECRYPT)) {
 	    ret =3D hdb_unseal_keys(context, db, &entry->entry);
@@ -1529,6 +1636,14 @@
 }
=20
 static krb5_error_code
+LDAP_fetch(krb5_context context, HDB * db, krb5_const_principal principal,
+	   unsigned flags, hdb_entry_ex * entry)
+{
+    return LDAP_fetch_kvno(context, db, principal,
+			   flags & (~HDB_F_KVNO_SPECIFIED), 0, entry);
+}
+
+static krb5_error_code
 LDAP_store(krb5_context context, HDB * db, unsigned flags,
 	   hdb_entry_ex * entry)
 {
@@ -1561,8 +1676,8 @@
     if (e =3D=3D NULL) {
 	ret =3D asprintf(&dn, "krb5PrincipalName=3D%s,%s", name, HDB2CREATE(db));
 	if (ret < 0) {
-	    krb5_set_error_string(context, "asprintf: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, "asprintf: out of memory");
 	    goto out;
 	}
     } else if (flags & HDB_F_REPLACE) {
@@ -1577,21 +1692,21 @@
     /* write entry into directory */
     if (e =3D=3D NULL) {
 	/* didn't exist before */
-	rc =3D ldap_add_s(HDB2LDAP(db), dn, mods);
-	errfn =3D "ldap_add_s";
+	rc =3D ldap_add_ext_s(HDB2LDAP(db), dn, mods, NULL, NULL );
+	errfn =3D "ldap_add_ext_s";
     } else {
 	/* already existed, send deltas only */
-	rc =3D ldap_modify_s(HDB2LDAP(db), dn, mods);
-	errfn =3D "ldap_modify_s";
+	rc =3D ldap_modify_ext_s(HDB2LDAP(db), dn, mods, NULL, NULL );
+	errfn =3D "ldap_modify_ext_s";
     }
=20
     if (check_ldap(context, db, rc)) {
 	char *ld_error =3D NULL;
 	ldap_get_option(HDB2LDAP(db), LDAP_OPT_ERROR_STRING,
 			&ld_error);
-	krb5_set_error_string(context, "%s: %s (DN=3D%s) %s: %s",=20
+	ret =3D HDB_ERR_CANT_LOCK_DB;
+	krb5_set_error_message(context, ret, "%s: %s (DN=3D%s) %s: %s",
 			      errfn, name, dn, ldap_err2string(rc), ld_error);
-	ret =3D HDB_ERR_CANT_LOCK_DB;
     } else
 	ret =3D 0;
=20
@@ -1635,17 +1750,17 @@
=20
     rc =3D ldap_set_option(HDB2LDAP(db), LDAP_OPT_SIZELIMIT, (const void *=
)&limit);
     if (rc !=3D LDAP_SUCCESS) {
-	krb5_set_error_string(context, "ldap_set_option: %s",
+	ret =3D HDB_ERR_BADVERSION;
+	krb5_set_error_message(context, ret, "ldap_set_option: %s",
 			      ldap_err2string(rc));
-	ret =3D HDB_ERR_BADVERSION;
 	goto out;
     }
=20
-    rc =3D ldap_delete_s(HDB2LDAP(db), dn);
+    rc =3D ldap_delete_ext_s(HDB2LDAP(db), dn, NULL, NULL );
     if (check_ldap(context, db, rc)) {
-	krb5_set_error_string(context, "ldap_delete_s: %s",=20
-			      ldap_err2string(rc));
 	ret =3D HDB_ERR_CANT_LOCK_DB;
+	krb5_set_error_message(context, ret, "ldap_delete_ext_s: %s",
+			       ldap_err2string(rc));
     } else
 	ret =3D 0;
=20
@@ -1680,7 +1795,7 @@
     return ret;
 }
=20
-krb5_error_code
+static krb5_error_code
 hdb_ldap_common(krb5_context context,
 		HDB ** db,
 		const char *search_base,
@@ -1690,40 +1805,40 @@
     const char *create_base =3D NULL;
=20
     if (search_base =3D=3D NULL && search_base[0] =3D=3D '\0') {
-	krb5_set_error_string(context, "ldap search base not configured");
+	krb5_set_error_message(context, ENOMEM, "ldap search base not configured"=
);
 	return ENOMEM; /* XXX */
     }
=20
     if (structural_object =3D=3D NULL) {
 	const char *p;
=20
-	p =3D krb5_config_get_string(context, NULL, "kdc",=20
+	p =3D krb5_config_get_string(context, NULL, "kdc",
 				   "hdb-ldap-structural-object", NULL);
 	if (p =3D=3D NULL)
 	    p =3D default_structural_object;
 	structural_object =3D strdup(p);
 	if (structural_object =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    return ENOMEM;
 	}
     }
=20
-    samba_forwardable =3D=20
+    samba_forwardable =3D
 	krb5_config_get_bool_default(context, NULL, TRUE,
 				     "kdc", "hdb-samba-forwardable", NULL);
=20
     *db =3D calloc(1, sizeof(**db));
     if (*db =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     memset(*db, 0, sizeof(**db));
=20
     h =3D calloc(1, sizeof(*h));
     if (h =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	free(*db);
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     (*db)->hdb_db =3D h;
@@ -1731,8 +1846,8 @@
     /* XXX */
     if (asprintf(&(*db)->hdb_name, "ldap:%s", search_base) =3D=3D -1) {
 	LDAP_destroy(context, *db);
-	krb5_set_error_string(context, "strdup: out of memory");
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "strdup: out of memory");
 	return ENOMEM;
     }
=20
@@ -1740,12 +1855,12 @@
     h->h_base =3D strdup(search_base);
     if (h->h_url =3D=3D NULL || h->h_base =3D=3D NULL) {
 	LDAP_destroy(context, *db);
-	krb5_set_error_string(context, "strdup: out of memory");
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "strdup: out of memory");
 	return ENOMEM;
     }
=20
-    create_base =3D krb5_config_get_string(context, NULL, "kdc",=20
+    create_base =3D krb5_config_get_string(context, NULL, "kdc",
 					 "hdb-ldap-create-base", NULL);
     if (create_base =3D=3D NULL)
 	create_base =3D h->h_base;
@@ -1753,16 +1868,17 @@
     h->h_createbase =3D strdup(create_base);
     if (h->h_createbase =3D=3D NULL) {
 	LDAP_destroy(context, *db);
-	krb5_set_error_string(context, "strdup: out of memory");
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "strdup: out of memory");
 	return ENOMEM;
     }
=20
     (*db)->hdb_master_key_set =3D 0;
     (*db)->hdb_openp =3D 0;
+    (*db)->hdb_capability_flags =3D 0;
     (*db)->hdb_open =3D LDAP_open;
     (*db)->hdb_close =3D LDAP_close;
-    (*db)->hdb_fetch =3D LDAP_fetch;
+    (*db)->hdb_fetch_kvno =3D LDAP_fetch_kvno;
     (*db)->hdb_store =3D LDAP_store;
     (*db)->hdb_remove =3D LDAP_remove;
     (*db)->hdb_firstkey =3D LDAP_firstkey;
@@ -1792,14 +1908,15 @@
=20
     asprintf(&p, "ldapi:%s", arg);
     if (p =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "out of memory");
 	return ENOMEM;
     }
     search_base =3D strchr(p + strlen("ldapi://"), ':');
     if (search_base =3D=3D NULL) {
-	krb5_set_error_string(context, "search base missing");
 	*db =3D NULL;
+	krb5_set_error_message(context, HDB_ERR_BADVERSION,
+			       "search base missing");
 	return HDB_ERR_BADVERSION;
     }
     *search_base =3D '\0';
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb-privat=
e.h
--- a/head/crypto/heimdal/lib/hdb/hdb-private.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hdb/hdb-private.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -5,11 +5,12 @@
 #include <stdarg.h>
=20
 krb5_error_code
-_hdb_fetch (
+_hdb_fetch_kvno (
 	krb5_context /*context*/,
 	HDB */*db*/,
 	krb5_const_principal /*principal*/,
 	unsigned /*flags*/,
+	krb5_kvno /*kvno*/,
 	hdb_entry_ex */*entry*/);
=20
 hdb_master_key
@@ -17,6 +18,12 @@
 	uint32_t */*mkvno*/,
 	hdb_master_key /*mkey*/);
=20
+krb5_error_code
+_hdb_keytab2hdb_entry (
+	krb5_context /*context*/,
+	const krb5_keytab_entry */*ktentry*/,
+	hdb_entry_ex */*entry*/);
+
 int
 _hdb_mkey_decrypt (
 	krb5_context /*context*/,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb-protos=
.h
--- a/head/crypto/heimdal/lib/hdb/hdb-protos.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/hdb/hdb-protos.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -146,6 +146,11 @@
 	const HDB_Ext_PKINIT_acl **/*a*/);
=20
 krb5_error_code
+hdb_entry_get_pkinit_cert (
+	const hdb_entry */*entry*/,
+	const HDB_Ext_PKINIT_cert **/*a*/);
+
+krb5_error_code
 hdb_entry_get_pkinit_hash (
 	const hdb_entry */*entry*/,
 	const HDB_Ext_PKINIT_hash **/*a*/);
@@ -238,11 +243,10 @@
 	krb5_principal /*p*/);
=20
 krb5_error_code
-hdb_ldap_common (
+hdb_keytab_create (
 	krb5_context /*context*/,
 	HDB ** /*db*/,
-	const char */*search_base*/,
-	const char */*url*/);
+	const char */*arg*/);
=20
 krb5_error_code
 hdb_ldap_create (
@@ -267,6 +271,12 @@
 	int /*operation*/);
=20
 krb5_error_code
+hdb_mdb_create (
+	krb5_context /*context*/,
+	HDB **/*db*/,
+	const char */*filename*/);
+
+krb5_error_code
 hdb_ndbm_create (
 	krb5_context /*context*/,
 	HDB **/*db*/,
@@ -349,6 +359,12 @@
 	const char */*keyfile*/);
=20
 krb5_error_code
+hdb_sqlite_create (
+	krb5_context /*context*/,
+	HDB **/*db*/,
+	const char */*argument*/);
+
+krb5_error_code
 hdb_unlock (int /*fd*/);
=20
 krb5_error_code
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb.asn1
--- a/head/crypto/heimdal/lib/hdb/hdb.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/hdb.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
--- $Id: hdb.asn1 20236 2007-02-16 23:52:29Z lha $
+-- $Id$
 HDB DEFINITIONS ::=3D
 BEGIN
=20
@@ -13,7 +13,8 @@
=20
 Salt ::=3D SEQUENCE {
 	type[0]		INTEGER (0..4294967295),
-	salt[1]		OCTET STRING
+	salt[1]		OCTET STRING,
+	opaque[2]	OCTET STRING OPTIONAL
 }
=20
 Key ::=3D SEQUENCE {
@@ -44,7 +45,9 @@
 	immutable(13),			-- may not be deleted
 	trusted-for-delegation(14),	-- Trusted to print forwardabled tickets
 	allow-kerberos4(15),		-- Allow Kerberos 4 requests
-	allow-digest(16)		-- Allow digest requests
+	allow-digest(16),		-- Allow digest requests
+	locked-out(17)			-- Account is locked out,
+					-- authentication will be denied
 }
=20
 GENERATION ::=3D SEQUENCE {
@@ -64,6 +67,10 @@
 	digest[1] OCTET STRING
 }
=20
+HDB-Ext-PKINIT-cert ::=3D SEQUENCE OF SEQUENCE {
+	cert[0] OCTET STRING
+}
+
 HDB-Ext-Constrained-delegation-acl ::=3D SEQUENCE OF Principal
=20
 -- hdb-ext-referrals ::=3D PA-SERVER-REFERRAL-DATA
@@ -94,6 +101,7 @@
 		password[5]			HDB-Ext-Password,
 		aliases[6]			HDB-Ext-Aliases,
 		last-pw-change[7]		KerberosTime,
+	        pkinit-cert[8]  		HDB-Ext-PKINIT-cert,
 		...
 	},
 	...
@@ -101,6 +109,10 @@
=20
 HDB-extensions ::=3D SEQUENCE OF HDB-extension
=20
+hdb_keyset ::=3D SEQUENCE {
+	kvno[1]		INTEGER (0..4294967295),
+	keys[0]		SEQUENCE OF Key
+}
=20
 hdb_entry ::=3D SEQUENCE {
 	principal[0]	Principal  OPTIONAL, -- this is optional only=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb.c
--- a/head/crypto/heimdal/lib/hdb/hdb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/hdb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,70 +1,95 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
+#include "krb5_locl.h"
 #include "hdb_locl.h"
=20
-RCSID("$Id: hdb.c 20214 2007-02-09 21:51:10Z lha $");
-
 #ifdef HAVE_DLFCN_H
 #include <dlfcn.h>
 #endif
=20
-struct hdb_method {
-    const char *prefix;
-    krb5_error_code (*create)(krb5_context, HDB **, const char *filename);
-};
+/*! @mainpage Heimdal database backend library
+ *
+ * @section intro Introduction
+ *
+ * Heimdal libhdb library provides the backend support for Heimdal kdc
+ * and kadmind. Its here where plugins for diffrent database engines
+ * can be pluged in and extend support for here Heimdal get the
+ * principal and policy data from.
+ *
+ * Example of Heimdal backend are:
+ * - Berkeley DB 1.85
+ * - Berkeley DB 3.0
+ * - Berkeley DB 4.0
+ * - New Berkeley DB
+ * - LDAP
+ *
+ *
+ * The project web page: http://www.h5l.org/
+ *
+ */
+
+const int hdb_interface_version =3D HDB_INTERFACE_VERSION;
=20
 static struct hdb_method methods[] =3D {
 #if HAVE_DB1 || HAVE_DB3
-    {"db:",	hdb_db_create},
+    { HDB_INTERFACE_VERSION, "db:",	hdb_db_create},
+#endif
+#if HAVE_DB1
+    { HDB_INTERFACE_VERSION, "mit-db:",	hdb_mdb_create},
 #endif
 #if HAVE_NDBM
-    {"ndbm:",	hdb_ndbm_create},
+    { HDB_INTERFACE_VERSION, "ndbm:",	hdb_ndbm_create},
 #endif
+    { HDB_INTERFACE_VERSION, "keytab:",	hdb_keytab_create},
 #if defined(OPENLDAP) && !defined(OPENLDAP_MODULE)
-    {"ldap:",	hdb_ldap_create},
-    {"ldapi:",	hdb_ldapi_create},
+    { HDB_INTERFACE_VERSION, "ldap:",	hdb_ldap_create},
+    { HDB_INTERFACE_VERSION, "ldapi:",	hdb_ldapi_create},
 #endif
-#ifdef HAVE_LDB /* Used for integrated samba build */
-    {"ldb:",	hdb_ldb_create},
+#ifdef HAVE_SQLITE3
+    { HDB_INTERFACE_VERSION, "sqlite:", hdb_sqlite_create},
 #endif
-    {NULL,	NULL}
+    {0, NULL,	NULL}
 };
=20
 #if HAVE_DB1 || HAVE_DB3
-static struct hdb_method dbmetod =3D {"",	hdb_db_create };
+static struct hdb_method dbmetod =3D
+    { HDB_INTERFACE_VERSION, "", hdb_db_create };
 #elif defined(HAVE_NDBM)
-static struct hdb_method dbmetod =3D {"",	hdb_ndbm_create };
+static struct hdb_method dbmetod =3D
+    { HDB_INTERFACE_VERSION, "", hdb_ndbm_create };
 #endif
=20
=20
@@ -75,25 +100,26 @@
 		     Key **key)
 {
     Key *k;
-   =20
+
     for (k =3D *key ? (*key) + 1 : e->keys.val;
-	 k < e->keys.val + e->keys.len;=20
-	 k++)=20
+	 k < e->keys.val + e->keys.len;
+	 k++)
     {
 	if(k->key.keytype =3D=3D enctype){
 	    *key =3D k;
 	    return 0;
 	}
     }
-    krb5_set_error_string(context, "No next enctype %d for hdb-entry",=20
+    krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+			   "No next enctype %d for hdb-entry",
 			  (int)enctype);
     return KRB5_PROG_ETYPE_NOSUPP; /* XXX */
 }
=20
 krb5_error_code
-hdb_enctype2key(krb5_context context,=20
-		hdb_entry *e,=20
-		krb5_enctype enctype,=20
+hdb_enctype2key(krb5_context context,
+		hdb_entry *e,
+		krb5_enctype enctype,
 		Key **key)
 {
     *key =3D NULL;
@@ -103,7 +129,7 @@
 void
 hdb_free_key(Key *key)
 {
-    memset(key->key.keyvalue.data,=20
+    memset(key->key.keyvalue.data,
 	   0,
 	   key->key.keyvalue.length);
     free_Key(key);
@@ -142,7 +168,7 @@
 void
 hdb_free_entry(krb5_context context, hdb_entry_ex *ent)
 {
-    int i;
+    size_t i;
=20
     if (ent->free_entry)
 	(*ent->free_entry)(context, ent);
@@ -166,7 +192,7 @@
     hdb_entry_ex entry;
     ret =3D db->hdb_firstkey(context, db, flags, &entry);
     if (ret =3D=3D 0)
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
     while(ret =3D=3D 0){
 	ret =3D (*func)(context, db, &entry, data);
 	hdb_free_entry(context, &entry);
@@ -191,7 +217,7 @@
     if (ret)
 	return ret;
=20
-    tag.data =3D HDB_DB_FORMAT_ENTRY;
+    tag.data =3D (void *)(intptr_t)HDB_DB_FORMAT_ENTRY;
     tag.length =3D strlen(tag.data);
     ret =3D (*db->hdb__get)(context, db, tag, &version);
     ret2 =3D db->hdb_unlock(context, db);
@@ -215,16 +241,16 @@
     krb5_data tag;
     krb5_data version;
     char ver[32];
-   =20
+
     ret =3D hdb_check_db_format(context, db);
     if(ret !=3D HDB_ERR_NOENTRY)
 	return ret;
-   =20
+
     ret =3D db->hdb_lock(context, db, HDB_WLOCK);
     if (ret)
 	return ret;
=20
-    tag.data =3D HDB_DB_FORMAT_ENTRY;
+    tag.data =3D (void *)(intptr_t)HDB_DB_FORMAT_ENTRY;
     tag.length =3D strlen(tag.data);
     snprintf(ver, sizeof(ver), "%u", HDB_DB_FORMAT);
     version.data =3D ver;
@@ -233,7 +259,7 @@
     ret2 =3D db->hdb_unlock(context, db);
     if (ret) {
 	if (ret2)
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	return ret;
     }
     return ret2;
@@ -248,7 +274,7 @@
=20
 static const struct hdb_method *
 find_dynamic_method (krb5_context context,
-		     const char *filename,=20
+		     const char *filename,
 		     const char **rest)
 {
     static struct hdb_method method;
@@ -257,7 +283,7 @@
     const char *p;
     void *dl;
     size_t len;
-   =20
+
     p =3D strchr(filename, ':');
=20
     /* if no prefix, don't know what module to load, just ignore it */
@@ -266,11 +292,12 @@
=20
     len =3D p - filename;
     *rest =3D filename + len + 1;
-   =20
-    prefix =3D strndup(filename, len);
+
+    prefix =3D malloc(len + 1);
     if (prefix =3D=3D NULL)
 	krb5_errx(context, 1, "out of memory");
-   =20
+    strlcpy(prefix, filename, len + 1);
+
     if (asprintf(&path, LIBDIR "/hdb_%s.so", prefix) =3D=3D -1)
 	krb5_errx(context, 1, "out of memory");
=20
@@ -289,13 +316,13 @@
 	free(path);
 	return NULL;
     }
-   =20
+
     if (asprintf(&symbol, "hdb_%s_interface", prefix) =3D=3D -1)
 	krb5_errx(context, 1, "out of memory");
-=09
-    mso =3D dlsym(dl, symbol);
+
+    mso =3D (struct hdb_so_method *) dlsym(dl, symbol);
     if (mso =3D=3D NULL) {
-	krb5_warnx(context, "error finding symbol %s in %s: %s\n",=20
+	krb5_warnx(context, "error finding symbol %s in %s: %s\n",
 		   symbol, path, dlerror());
 	dlclose(dl);
 	free(symbol);
@@ -307,9 +334,9 @@
     free(symbol);
=20
     if (mso->version !=3D HDB_INTERFACE_VERSION) {
-	krb5_warnx(context,=20
+	krb5_warnx(context,
 		   "error wrong version in shared module %s "
-		   "version: %d should have been %d\n",=20
+		   "version: %d should have been %d\n",
 		   prefix, mso->version, HDB_INTERFACE_VERSION);
 	dlclose(dl);
 	free(prefix);
@@ -378,7 +405,7 @@
     len +=3D 1;
     buf =3D malloc(len);
     if (buf =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     buf[0] =3D '\0';
@@ -393,15 +420,65 @@
 }
=20
 krb5_error_code
+_hdb_keytab2hdb_entry(krb5_context context,
+		      const krb5_keytab_entry *ktentry,
+		      hdb_entry_ex *entry)
+{
+    entry->entry.kvno =3D ktentry->vno;
+    entry->entry.created_by.time =3D ktentry->timestamp;
+
+    entry->entry.keys.val =3D calloc(1, sizeof(entry->entry.keys.val[0]));
+    if (entry->entry.keys.val =3D=3D NULL)
+	return ENOMEM;
+    entry->entry.keys.len =3D 1;
+
+    entry->entry.keys.val[0].mkvno =3D NULL;
+    entry->entry.keys.val[0].salt =3D NULL;
+
+    return krb5_copy_keyblock_contents(context,
+				       &ktentry->keyblock,
+				       &entry->entry.keys.val[0].key);
+}
+
+/**
+ * Create a handle for a Kerberos database
+ *
+ * Create a handle for a Kerberos database backend specified by a
+ * filename.  Doesn't create a file if its doesn't exists, you have to
+ * use O_CREAT to tell the backend to create the file.
+ */
+
+krb5_error_code
 hdb_create(krb5_context context, HDB **db, const char *filename)
 {
     const struct hdb_method *h;
     const char *residual;
+    krb5_error_code ret;
+    struct krb5_plugin *list =3D NULL, *e;
=20
     if(filename =3D=3D NULL)
 	filename =3D HDB_DEFAULT_DB;
     krb5_add_et_list(context, initialize_hdb_error_table_r);
     h =3D find_method (filename, &residual);
+
+    if (h =3D=3D NULL) {
+	    ret =3D _krb5_plugin_find(context, PLUGIN_TYPE_DATA, "hdb", &list);
+	    if(ret =3D=3D 0 && list !=3D NULL) {
+		    for (e =3D list; e !=3D NULL; e =3D _krb5_plugin_get_next(e)) {
+			    h =3D _krb5_plugin_get_symbol(e);
+			    if (strncmp (filename, h->prefix, strlen(h->prefix)) =3D=3D 0
+				&& h->interface_version =3D=3D HDB_INTERFACE_VERSION) {
+				    residual =3D filename + strlen(h->prefix);
+				    break;
+			    }
+		    }
+		    if (e =3D=3D NULL) {
+			    h =3D NULL;
+			    _krb5_plugin_free(list);
+		    }
+	    }
+    }
+
 #ifdef HAVE_DLOPEN
     if (h =3D=3D NULL)
 	h =3D find_dynamic_method (context, filename, &residual);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb.h
--- a/head/crypto/heimdal/lib/hdb/hdb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/hdb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,43 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: hdb.h 22198 2007-12-07 13:09:25Z lha $ */
+/* $Id$ */
=20
 #ifndef __HDB_H__
 #define __HDB_H__
=20
+#include <krb5.h>
+
 #include <hdb_err.h>
=20
 #include <heim_asn1.h>
@@ -53,12 +55,36 @@
 #define HDB_F_GET_KRBTGT	16	/* fetch krbtgt */
 #define HDB_F_GET_ANY		28	/* fetch any of client,server,krbtgt */
 #define HDB_F_CANON		32	/* want canonicalition */
+#define HDB_F_ADMIN_DATA	64	/* want data that kdc don't use  */
+#define HDB_F_KVNO_SPECIFIED	128	/* we want a particular KVNO */
+#define HDB_F_CURRENT_KVNO	256	/* we want the current KVNO */
+/* 512, 1024, 2048 are reserved for kvno operations that is not part of th=
e 1.5 branch */
+#define HDB_F_ALL_KVNOS		2048	/* we want all the keys, live or not */
+#define HDB_F_FOR_AS_REQ	4096	/* fetch is for a AS REQ */
+#define HDB_F_FOR_TGS_REQ	8192	/* fetch is for a TGS REQ */
+
+/* hdb_capability_flags */
+#define HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL 1
+#define HDB_CAP_F_HANDLE_PASSWORDS	2
+#define HDB_CAP_F_PASSWORD_UPDATE_KEYS	4
+
+/* auth status values */
+#define HDB_AUTH_SUCCESS		0
+#define HDB_AUTH_WRONG_PASSWORD		1
+#define HDB_AUTH_INVALID_SIGNATURE	2
=20
 /* key usage for master key */
 #define HDB_KU_MKEY	0x484442
=20
 typedef struct hdb_master_key_data *hdb_master_key;
=20
+/**
+ * hdb_entry_ex is a wrapper structure around the hdb_entry structure
+ * that allows backends to keep a pointer to the backing store, ie in
+ * ->hdb_fetch_kvno(), so that we the kadmin/kpasswd backend gets around to
+ * ->hdb_store(), the backend doesn't need to lookup the entry again.
+ */
+
 typedef struct hdb_entry_ex {
     void *ctx;
     hdb_entry entry;
@@ -66,68 +92,173 @@
 } hdb_entry_ex;
=20
=20
+/**
+ * HDB backend function pointer structure
+ *
+ * The HDB structure is what the KDC and kadmind framework uses to
+ * query the backend database when talking about principals.
+ */
+
 typedef struct HDB{
     void *hdb_db;
-    void *hdb_dbc;
+    void *hdb_dbc; /** don't use, only for DB3 */
     char *hdb_name;
     int hdb_master_key_set;
     hdb_master_key hdb_master_key;
     int hdb_openp;
+    int hdb_capability_flags;
+    /**
+     * Open (or create) the a Kerberos database.
+     *
+     * Open (or create) the a Kerberos database that was resolved with
+     * hdb_create(). The third and fourth flag to the function are the
+     * same as open(), thus passing O_CREAT will create the data base
+     * if it doesn't exists.
+     *
+     * Then done the caller should call hdb_close(), and to release
+     * all resources hdb_destroy().
+     */
+    krb5_error_code (*hdb_open)(krb5_context, struct HDB*, int, mode_t);
+    /**
+     * Close the database for transaction
+     *
+     * Closes the database for further transactions, wont release any
+     * permanant resources. the database can be ->hdb_open-ed again.
+     */
+    krb5_error_code (*hdb_close)(krb5_context, struct HDB*);
+    /**
+     * Free an entry after use.
+     */
+    void	    (*hdb_free)(krb5_context, struct HDB*, hdb_entry_ex*);
+    /**
+     * Fetch an entry from the backend
+     *
+     * Fetch an entry from the backend, flags are what type of entry
+     * should be fetch: client, server, krbtgt.
+     * knvo (if specified and flags HDB_F_KVNO_SPECIFIED set) is the kvno =
to get
+     */
+    krb5_error_code (*hdb_fetch_kvno)(krb5_context, struct HDB*,
+				      krb5_const_principal, unsigned, krb5_kvno,
+				      hdb_entry_ex*);
+    /**
+     * Store an entry to database
+     */
+    krb5_error_code (*hdb_store)(krb5_context, struct HDB*,
+				 unsigned, hdb_entry_ex*);
+    /**
+     * Remove an entry from the database.
+     */
+    krb5_error_code (*hdb_remove)(krb5_context, struct HDB*,
+				  krb5_const_principal);
+    /**
+     * As part of iteration, fetch one entry
+     */
+    krb5_error_code (*hdb_firstkey)(krb5_context, struct HDB*,
+				    unsigned, hdb_entry_ex*);
+    /**
+     * As part of iteration, fetch next entry
+     */
+    krb5_error_code (*hdb_nextkey)(krb5_context, struct HDB*,
+				   unsigned, hdb_entry_ex*);
+    /**
+     * Lock database
+     *
+     * A lock can only be held by one consumers. Transaction can still
+     * happen on the database while the lock is held, so the entry is
+     * only useful for syncroning creation of the database and renaming of=
 the database.
+     */
+    krb5_error_code (*hdb_lock)(krb5_context, struct HDB*, int);
+    /**
+     * Unlock database
+     */
+    krb5_error_code (*hdb_unlock)(krb5_context, struct HDB*);
+    /**
+     * Rename the data base.
+     *
+     * Assume that the database is not hdb_open'ed and not locked.
+     */
+    krb5_error_code (*hdb_rename)(krb5_context, struct HDB*, const char*);
+    /**
+     * Get an hdb_entry from a classical DB backend
+     *
+     * If the database is a classical DB (ie BDB, NDBM, GDBM, etc)
+     * backend, this function will take a principal key (krb5_data)
+     * and return all data related to principal in the return
+     * krb5_data. The returned encoded entry is of type hdb_entry or
+     * hdb_entry_alias.
+     */
+    krb5_error_code (*hdb__get)(krb5_context, struct HDB*,
+				krb5_data, krb5_data*);
+    /**
+     * Store an hdb_entry from a classical DB backend
+     *
+     * Same discussion as in @ref HDB::hdb__get
+     */
+    krb5_error_code (*hdb__put)(krb5_context, struct HDB*, int,
+				krb5_data, krb5_data);
+    /**
+     * Delete and hdb_entry from a classical DB backend
+     *
+     * Same discussion as in @ref HDB::hdb__get
+     */
+    krb5_error_code (*hdb__del)(krb5_context, struct HDB*, krb5_data);
+    /**
+     * Destroy the handle to the database.
+     *
+     * Destroy the handle to the database, deallocate all memory and
+     * related resources. Does not remove any permanent data. Its the
+     * logical reverse of hdb_create() function that is the entry
+     * point for the module.
+     */
+    krb5_error_code (*hdb_destroy)(krb5_context, struct HDB*);
+    /**
+     * Get the list of realms this backend handles.
+     * This call is optional to support. The returned realms are used
+     * for announcing the realms over bonjour. Free returned array
+     * with krb5_free_host_realm().
+     */
+    krb5_error_code (*hdb_get_realms)(krb5_context, struct HDB *, krb5_rea=
lm **);
+    /**
+     * Change password.
+     *
+     * Will update keys for the entry when given password.  The new
+     * keys must be written into the entry and will then later be
+     * ->hdb_store() into the database. The backend will still perform
+     * all other operations, increasing the kvno, and update
+     * modification timestamp.
+     *
+     * The backend needs to call _kadm5_set_keys() and perform password
+     * quality checks.
+     */
+    krb5_error_code (*hdb_password)(krb5_context, struct HDB*, hdb_entry_e=
x*, const char *, int);
=20
-    krb5_error_code (*hdb_open)(krb5_context,
-				struct HDB*,
-				int,
-				mode_t);
-    krb5_error_code (*hdb_close)(krb5_context,=20
-				 struct HDB*);
-    void	    (*hdb_free)(krb5_context,
-				struct HDB*,
-				hdb_entry_ex*);
-    krb5_error_code (*hdb_fetch)(krb5_context,
-				 struct HDB*,
-				 krb5_const_principal,
-				 unsigned,
-				 hdb_entry_ex*);
-    krb5_error_code (*hdb_store)(krb5_context,
-				 struct HDB*,
-				 unsigned,
-				 hdb_entry_ex*);
-    krb5_error_code (*hdb_remove)(krb5_context,
-				  struct HDB*,
-				  krb5_const_principal);
-    krb5_error_code (*hdb_firstkey)(krb5_context,
-				    struct HDB*,
-				    unsigned,
-				    hdb_entry_ex*);
-    krb5_error_code (*hdb_nextkey)(krb5_context,
-				   struct HDB*,
-				   unsigned,
-				   hdb_entry_ex*);
-    krb5_error_code (*hdb_lock)(krb5_context,
-				struct HDB*,
-				int operation);
-    krb5_error_code (*hdb_unlock)(krb5_context,
-				  struct HDB*);
-    krb5_error_code (*hdb_rename)(krb5_context,
-				  struct HDB*,
-				  const char*);
-    krb5_error_code (*hdb__get)(krb5_context,
-				struct HDB*,
-				krb5_data,
-				krb5_data*);
-    krb5_error_code (*hdb__put)(krb5_context,
-				struct HDB*,
-				int,=20
-				krb5_data,
-				krb5_data);
-    krb5_error_code (*hdb__del)(krb5_context,=20
-				struct HDB*,
-				krb5_data);
-    krb5_error_code (*hdb_destroy)(krb5_context,
-				   struct HDB*);
+    /**
+     * Auth feedback
+     *
+     * This is a feedback call that allows backends that provides
+     * lockout functionality to register failure and/or successes.
+     *
+     * In case the entry is locked out, the backend should set the
+     * hdb_entry.flags.locked-out flag.
+     */
+    krb5_error_code (*hdb_auth_status)(krb5_context, struct HDB *, hdb_ent=
ry_ex *, int);
+    /**
+     * Check if delegation is allowed.
+     */
+    krb5_error_code (*hdb_check_constrained_delegation)(krb5_context, stru=
ct HDB *, hdb_entry_ex *, krb5_const_principal);
+
+    /**
+     * Check if this name is an alias for the supplied client for PKINIT u=
serPrinicpalName logins
+     */
+    krb5_error_code (*hdb_check_pkinit_ms_upn_match)(krb5_context, struct =
HDB *, hdb_entry_ex *, krb5_const_principal);
+
+    /**
+     * Check if s4u2self is allowed from this client to this server
+     */
+    krb5_error_code (*hdb_check_s4u2self)(krb5_context, struct HDB *, hdb_=
entry_ex *, krb5_const_principal);
 }HDB;
=20
-#define HDB_INTERFACE_VERSION	4
+#define HDB_INTERFACE_VERSION	7
=20
 struct hdb_so_method {
     int version;
@@ -139,6 +270,14 @@
 					      hdb_entry_ex*, void*);
 extern krb5_kt_ops hdb_kt_ops;
=20
+struct hdb_method {
+    int interface_version;
+    const char *prefix;
+    krb5_error_code (*create)(krb5_context, HDB **, const char *filename);
+};
+
+extern const int hdb_interface_version;
+
 #include <hdb-protos.h>
=20
 #endif /* __HDB_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb.schema
--- a/head/crypto/heimdal/lib/hdb/hdb.schema	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/hdb.schema	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 # Definitions for a Kerberos V KDC schema
 #
-# $Id: hdb.schema 14958 2005-04-25 17:33:40Z lha $
+# $Id$
 #
 # This version is compatible with OpenLDAP 1.8
 #
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb_err.et
--- a/head/crypto/heimdal/lib/hdb/hdb_err.et	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/hdb_err.et	Tue Apr 17 11:51:51 2012 +0300
@@ -3,7 +3,7 @@
 #
 # This might look like a com_err file, but is not
 #
-id "$Id: hdb_err.et 15878 2005-08-11 13:17:22Z lha $"
+id "$Id$"
=20
 error_table hdb
=20
@@ -24,5 +24,7 @@
 error_code BADVERSION,		"Wrong database version"
 error_code NO_MKEY,		"No correct master key"
 error_code MANDATORY_OPTION,	"Entry contains unknown mandatory extension"
+error_code NO_WRITE_SUPPORT,	"HDB backend doesn't contain write support"
+error_code NOT_FOUND_HERE,	"The secret for this entry is not replicated to=
 this database"
=20
 end
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/hdb_locl.h
--- a/head/crypto/heimdal/lib/hdb/hdb_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/hdb_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 1997-2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: hdb_locl.h 22209 2007-12-07 19:03:41Z lha $ */
-/* $FreeBSD$ */
+/* $Id$ */
=20
 #ifndef __HDB_LOCL_H__
 #define __HDB_LOCL_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/keys.c
--- a/head/crypto/heimdal/lib/hdb/keys.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/keys.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,39 @@
+
 /*
- * Copyright (c) 1997 - 2001, 2003 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2003 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
=20
-RCSID("$Id: keys.c 22071 2007-11-14 20:04:50Z lha $");
-
 /*
  * free all the memory used by (len, keys)
  */
@@ -57,7 +56,7 @@
     free (keys);
 }
=20
-/*=20
+/*
  * for each entry in `default_keys' try to parse it as a sequence
  * of etype:salttype:salt, syntax of this if something like:
  * [(des|des3|etype):](pw-salt|afs3)[:string], if etype is omitted it
@@ -68,19 +67,21 @@
  *	afs or afs3 =3D=3D des:afs3-salt
  */
=20
-/* the 3 DES types must be first */
-static const krb5_enctype all_etypes[] =3D {=20
+static const krb5_enctype des_etypes[] =3D {
     ETYPE_DES_CBC_MD5,
     ETYPE_DES_CBC_MD4,
-    ETYPE_DES_CBC_CRC,
+    ETYPE_DES_CBC_CRC
+};
+
+static const krb5_enctype all_etypes[] =3D {
     ETYPE_AES256_CTS_HMAC_SHA1_96,
     ETYPE_ARCFOUR_HMAC_MD5,
     ETYPE_DES3_CBC_SHA1
 };
=20
 static krb5_error_code
-parse_key_set(krb5_context context, const char *key,=20
-	      krb5_enctype **ret_enctypes, size_t *ret_num_enctypes,=20
+parse_key_set(krb5_context context, const char *key,
+	      krb5_enctype **ret_enctypes, size_t *ret_num_enctypes,
 	      krb5_salt *salt, krb5_principal principal)
 {
     const char *p;
@@ -90,7 +91,7 @@
     krb5_enctype e;
     const krb5_enctype *enctypes =3D NULL;
     krb5_error_code ret;
-   =20
+
     p =3D key;
=20
     *ret_enctypes =3D NULL;
@@ -110,8 +111,8 @@
 	    /* XXX there should be a string_to_etypes handling
 	       special cases like `des' and `all' */
 	    if(strcmp(buf[i], "des") =3D=3D 0) {
-		enctypes =3D all_etypes;
-		num_enctypes =3D 3;
+		enctypes =3D des_etypes;
+		num_enctypes =3D sizeof(des_etypes)/sizeof(des_etypes[0]);
 	    } else if(strcmp(buf[i], "des3") =3D=3D 0) {
 		e =3D ETYPE_DES3_CBC_SHA1;
 		enctypes =3D &e;
@@ -139,8 +140,8 @@
 		salt->salttype =3D KRB5_PW_SALT;
 	    } else if(strcmp(buf[i], "afs3-salt") =3D=3D 0) {
 		if(enctypes =3D=3D NULL) {
-		    enctypes =3D all_etypes;
-		    num_enctypes =3D 3;
+		    enctypes =3D des_etypes;
+		    num_enctypes =3D sizeof(des_etypes)/sizeof(des_etypes[0]);
 		}
 		salt->salttype =3D KRB5_AFS3_SALT;
 	    }
@@ -153,39 +154,40 @@
 	       v4 compat, and a cell name for afs compat */
 	    salt->saltvalue.data =3D strdup(buf[i]);
 	    if (salt->saltvalue.data =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
+		krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 		return ENOMEM;
 	    }
 	    salt->saltvalue.length =3D strlen(buf[i]);
 	}
     }
-   =20
+
     if(enctypes =3D=3D NULL || salt->salttype =3D=3D 0) {
-	krb5_set_error_string(context, "bad value for default_keys `%s'", key);
+	krb5_set_error_message(context, EINVAL, "bad value for default_keys `%s'"=
, key);
 	return EINVAL;
     }
-   =20
+
     /* if no salt was specified make up default salt */
     if(salt->saltvalue.data =3D=3D NULL) {
 	if(salt->salttype =3D=3D KRB5_PW_SALT)
 	    ret =3D krb5_get_pw_salt(context, principal, salt);
 	else if(salt->salttype =3D=3D KRB5_AFS3_SALT) {
-	    krb5_realm *realm =3D krb5_princ_realm(context, principal);
-	    salt->saltvalue.data =3D strdup(*realm);
+	    krb5_const_realm realm =3D krb5_principal_get_realm(context, principa=
l);
+	    salt->saltvalue.data =3D strdup(realm);
 	    if(salt->saltvalue.data =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory while "
-				      "parsing salt specifiers");
+		krb5_set_error_message(context, ENOMEM,
+				       "out of memory while "
+				       "parsing salt specifiers");
 		return ENOMEM;
 	    }
 	    strlwr(salt->saltvalue.data);
-	    salt->saltvalue.length =3D strlen(*realm);
+	    salt->saltvalue.length =3D strlen(realm);
 	}
     }
=20
     *ret_enctypes =3D malloc(sizeof(enctypes[0]) * num_enctypes);
     if (*ret_enctypes =3D=3D NULL) {
 	krb5_free_salt(context, *salt);
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     memcpy(*ret_enctypes, enctypes, sizeof(enctypes[0]) * num_enctypes);
@@ -195,7 +197,7 @@
 }
=20
 static krb5_error_code
-add_enctype_to_key_set(Key **key_set, size_t *nkeyset,=20
+add_enctype_to_key_set(Key **key_set, size_t *nkeyset,
 		       krb5_enctype enctype, krb5_salt *salt)
 {
     krb5_error_code ret;
@@ -206,25 +208,25 @@
     tmp =3D realloc(*key_set, (*nkeyset + 1) * sizeof((*key_set)[0]));
     if (tmp =3D=3D NULL)
 	return ENOMEM;
-   =20
+
     *key_set =3D tmp;
=20
     key.key.keytype =3D enctype;
     key.key.keyvalue.length =3D 0;
     key.key.keyvalue.data =3D NULL;
-   =20
+
     if (salt) {
-	key.salt =3D malloc(sizeof(*key.salt));
+	key.salt =3D calloc(1, sizeof(*key.salt));
 	if (key.salt =3D=3D NULL) {
 	    free_Key(&key);
 	    return ENOMEM;
 	}
-=09
+
 	key.salt->type =3D salt->salttype;
 	krb5_data_zero (&key.salt->salt);
-=09
-	ret =3D krb5_data_copy(&key.salt->salt,=20
-			     salt->saltvalue.data,=20
+
+	ret =3D krb5_data_copy(&key.salt->salt,
+			     salt->saltvalue.data,
 			     salt->saltvalue.length);
 	if (ret) {
 	    free_Key(&key);
@@ -232,9 +234,9 @@
 	}
     } else
 	key.salt =3D NULL;
-   =20
+
     (*key_set)[*nkeyset] =3D key;
-   =20
+
     *nkeyset +=3D 1;
=20
     return 0;
@@ -254,28 +256,24 @@
     char **ktypes, **kp;
     krb5_error_code ret;
     Key *k, *key_set;
-    int i, j;
-    char *default_keytypes[] =3D {
-	"des:pw-salt",
+    size_t i, j;
+    static const char *default_keytypes[] =3D {
 	"aes256-cts-hmac-sha1-96:pw-salt",
 	"des3-cbc-sha1:pw-salt",
 	"arcfour-hmac-md5:pw-salt",
 	NULL
     };
-   =20
+
     ktypes =3D krb5_config_get_strings(context, NULL, "kadmin",
 				     "default_keys", NULL);
     if (ktypes =3D=3D NULL)
-	ktypes =3D default_keytypes;
-
-    if (ktypes =3D=3D NULL)
-	abort();
+	ktypes =3D (char **)(intptr_t)default_keytypes;
=20
     *ret_key_set =3D key_set =3D NULL;
     *nkeyset =3D 0;
=20
     ret =3D 0;
-=20
+
     for(kp =3D ktypes; kp && *kp; kp++) {
 	const char *p;
 	krb5_salt salt;
@@ -292,7 +290,7 @@
 	    p =3D "des:afs3-salt";
 	else if (strcmp(p, "arcfour-hmac-md5") =3D=3D 0)
 	    p =3D "arcfour-hmac-md5:pw-salt";
-	   =20
+
 	memset(&salt, 0, sizeof(salt));
=20
 	ret =3D parse_key_set(context, p,
@@ -316,14 +314,14 @@
 			break;
 		    if (k->salt->type =3D=3D salt.salttype &&
 			k->salt->salt.length =3D=3D salt.saltvalue.length &&
-			memcmp(k->salt->salt.data, salt.saltvalue.data,=20
+			memcmp(k->salt->salt.data, salt.saltvalue.data,
 			       salt.saltvalue.length) =3D=3D 0)
 			break;
 		}
 	    }
 	    /* not a duplicate, lets add it */
 	    if (j =3D=3D *nkeyset) {
-		ret =3D add_enctype_to_key_set(&key_set, nkeyset, enctypes[i],=20
+		ret =3D add_enctype_to_key_set(&key_set, nkeyset, enctypes[i],
 					     no_salt ? NULL : &salt);
 		if (ret) {
 		    free(enctypes);
@@ -335,22 +333,22 @@
 	free(enctypes);
 	krb5_free_salt(context, salt);
     }
-   =20
+
     *ret_key_set =3D key_set;
=20
  out:
-    if (ktypes !=3D default_keytypes)
+    if (ktypes !=3D (char **)(intptr_t)default_keytypes)
 	krb5_config_free_strings(ktypes);
=20
     if (ret) {
-	krb5_warn(context, ret,=20
+	krb5_warn(context, ret,
 		  "failed to parse the [kadmin]default_keys values");
=20
 	for (i =3D 0; i < *nkeyset; i++)
 	    free_Key(&key_set[i]);
 	free(key_set);
     } else if (*nkeyset =3D=3D 0) {
-	krb5_warnx(context,=20
+	krb5_warnx(context,
 		   "failed to parse any of the [kadmin]default_keys values");
 	ret =3D EINVAL; /* XXX */
     }
@@ -360,13 +358,13 @@
=20
=20
 krb5_error_code
-hdb_generate_key_set_password(krb5_context context,=20
-			      krb5_principal principal,=20
-			      const char *password,=20
-			      Key **keys, size_t *num_keys)=20
+hdb_generate_key_set_password(krb5_context context,
+			      krb5_principal principal,
+			      const char *password,
+			      Key **keys, size_t *num_keys)
 {
     krb5_error_code ret;
-    int i;
+    size_t i;
=20
     ret =3D hdb_generate_key_set(context, principal,
 				keys, num_keys, 0);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/keytab.c
--- a/head/crypto/heimdal/lib/hdb/keytab.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/keytab.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,53 +1,58 @@
 /*
- * Copyright (c) 1999 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
=20
 /* keytab backend for HDB databases */
=20
-RCSID("$Id: keytab.c 18380 2006-10-09 12:36:40Z lha $");
-
 struct hdb_data {
     char *dbname;
     char *mkey;
 };
=20
+struct hdb_cursor {
+    HDB *db;
+    hdb_entry_ex hdb_entry;
+    int first, next;
+    int key_idx;
+};
+
 /*
  * the format for HDB keytabs is:
- * HDB:[database:file:mkey]
+ * HDB:[HDBFORMAT:database-specific-data[:mkey=3Dmkey-file]]
  */
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 hdb_resolve(krb5_context context, const char *name, krb5_keytab id)
 {
     struct hdb_data *d;
@@ -55,41 +60,38 @@
=20
     d =3D malloc(sizeof(*d));
     if(d =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     db =3D name;
-    mkey =3D strchr(name, ':');
-    if(mkey =3D=3D NULL || mkey[1] =3D=3D '\0') {
+    mkey =3D strstr(name, ":mkey=3D");
+    if(mkey =3D=3D NULL || mkey[5] =3D=3D '\0') {
 	if(*name =3D=3D '\0')
 	    d->dbname =3D NULL;
 	else {
 	    d->dbname =3D strdup(name);
 	    if(d->dbname =3D=3D NULL) {
 		free(d);
-		krb5_set_error_string(context, "malloc: out of memory");
+		krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 		return ENOMEM;
 	    }
 	}
 	d->mkey =3D NULL;
     } else {
-	if((mkey - db) =3D=3D 0) {
-	    d->dbname =3D NULL;
-	} else {
-	    d->dbname =3D malloc(mkey - db + 1);
-	    if(d->dbname =3D=3D NULL) {
-		free(d);
-		krb5_set_error_string(context, "malloc: out of memory");
-		return ENOMEM;
-	    }
-	    memmove(d->dbname, db, mkey - db);
-	    d->dbname[mkey - db] =3D '\0';
+	d->dbname =3D malloc(mkey - db + 1);
+	if(d->dbname =3D=3D NULL) {
+	    free(d);
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	    return ENOMEM;
 	}
-	d->mkey =3D strdup(mkey + 1);
+	memmove(d->dbname, db, mkey - db);
+	d->dbname[mkey - db] =3D '\0';
+
+	d->mkey =3D strdup(mkey + 5);
 	if(d->mkey =3D=3D NULL) {
 	    free(d->dbname);
 	    free(d);
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    return ENOMEM;
 	}
     }
@@ -97,7 +99,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 hdb_close(krb5_context context, krb5_keytab id)
 {
     struct hdb_data *d =3D id->data;
@@ -108,76 +110,58 @@
     return 0;
 }
=20
-static krb5_error_code=20
-hdb_get_name(krb5_context context,=20
-	     krb5_keytab id,=20
-	     char *name,=20
+static krb5_error_code KRB5_CALLCONV
+hdb_get_name(krb5_context context,
+	     krb5_keytab id,
+	     char *name,
 	     size_t namesize)
 {
     struct hdb_data *d =3D id->data;
=20
-    snprintf(name, namesize, "%s%s%s",=20
+    snprintf(name, namesize, "%s%s%s",
 	     d->dbname ? d->dbname : "",
 	     (d->dbname || d->mkey) ? ":" : "",
 	     d->mkey ? d->mkey : "");
     return 0;
 }
=20
-static void
-set_config (krb5_context context,
-	    const krb5_config_binding *binding,
-	    const char **dbname,
-	    const char **mkey)
-{
-    *dbname =3D krb5_config_get_string(context, binding, "dbname", NULL);
-    *mkey   =3D krb5_config_get_string(context, binding, "mkey_file", NULL=
);
-}
-
 /*
  * try to figure out the database (`dbname') and master-key (`mkey')
  * that should be used for `principal'.
  */
=20
-static void
+static krb5_error_code
 find_db (krb5_context context,
-	 const char **dbname,
-	 const char **mkey,
+	 char **dbname,
+	 char **mkey,
 	 krb5_const_principal principal)
 {
-    const krb5_config_binding *top_bind =3D NULL;
-    const krb5_config_binding *default_binding =3D NULL;
-    const krb5_config_binding *db;
-    krb5_realm *prealm =3D krb5_princ_realm(context, rk_UNCONST(principal)=
);
+    krb5_const_realm realm =3D krb5_principal_get_realm(context, principal=
);
+    krb5_error_code ret;
+    struct hdb_dbinfo *head, *dbinfo =3D NULL;
=20
     *dbname =3D *mkey =3D NULL;
=20
-    while ((db =3D
-	    krb5_config_get_next(context,
-				 NULL,
-				 &top_bind,
-				 krb5_config_list,
-				 "kdc",
-				 "database",
-				 NULL)) !=3D NULL) {
-	const char *p;
-=09
-	p =3D krb5_config_get_string (context, db, "realm", NULL);
-	if (p =3D=3D NULL) {
-	    if(default_binding) {
-		krb5_warnx(context, "WARNING: more than one realm-less "
-			   "database specification");
-		krb5_warnx(context, "WARNING: using the first encountered");
-	    } else
-		default_binding =3D db;
-	} else if (strcmp (*prealm, p) =3D=3D 0) {
-	    set_config (context, db, dbname, mkey);
+    ret =3D hdb_get_dbinfo(context, &head);
+    if (ret)
+	return ret;
+
+    while ((dbinfo =3D hdb_dbinfo_get_next(head, dbinfo)) !=3D NULL) {
+	const char *p =3D hdb_dbinfo_get_realm(context, dbinfo);
+	if (p && strcmp (realm, p) =3D=3D 0) {
+	    p =3D hdb_dbinfo_get_dbname(context, dbinfo);
+	    if (p)
+		*dbname =3D strdup(p);
+	    p =3D hdb_dbinfo_get_mkey_file(context, dbinfo);
+	    if (p)
+		*mkey =3D strdup(p);
 	    break;
 	}
     }
-    if (*dbname =3D=3D NULL && default_binding !=3D NULL)
-	set_config (context, default_binding, dbname, mkey);
+    hdb_free_dbinfo(context, &head);
     if (*dbname =3D=3D NULL)
-	*dbname =3D HDB_DEFAULT_DB;
+	*dbname =3D strdup(HDB_DEFAULT_DB);
+    return 0;
 }
=20
 /*
@@ -185,7 +169,7 @@
  * it in `entry'.  return 0 or an error code
  */
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 hdb_get_entry(krb5_context context,
 	      krb5_keytab id,
 	      krb5_const_principal principal,
@@ -196,34 +180,41 @@
     hdb_entry_ex ent;
     krb5_error_code ret;
     struct hdb_data *d =3D id->data;
-    int i;
-    HDB *db;
     const char *dbname =3D d->dbname;
     const char *mkey   =3D d->mkey;
+    char *fdbname =3D NULL, *fmkey =3D NULL;
+    HDB *db;
+    size_t i;
=20
     memset(&ent, 0, sizeof(ent));
=20
-    if (dbname =3D=3D NULL)
-	find_db (context, &dbname, &mkey, principal);
+    if (dbname =3D=3D NULL) {
+	ret =3D find_db(context, &fdbname, &fmkey, principal);
+	if (ret)
+	    return ret;
+	dbname =3D fdbname;
+	mkey =3D fmkey;
+    }
=20
     ret =3D hdb_create (context, &db, dbname);
     if (ret)
-	return ret;
+	goto out2;
     ret =3D hdb_set_master_keyfile (context, db, mkey);
     if (ret) {
 	(*db->hdb_destroy)(context, db);
-	return ret;
+	goto out2;
     }
-=09
+
     ret =3D (*db->hdb_open)(context, db, O_RDONLY, 0);
     if (ret) {
 	(*db->hdb_destroy)(context, db);
-	return ret;
+	goto out2;
     }
-    ret =3D (*db->hdb_fetch)(context, db, principal,=20
-			   HDB_F_DECRYPT|
-			   HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
-			   &ent);
+
+    ret =3D (*db->hdb_fetch_kvno)(context, db, principal,
+				HDB_F_DECRYPT|HDB_F_KVNO_SPECIFIED|
+				HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
+				kvno, &ent);
=20
     if(ret =3D=3D HDB_ERR_NOENTRY) {
 	ret =3D KRB5_KT_NOTFOUND;
@@ -231,7 +222,7 @@
     }else if(ret)
 	goto out;
=20
-    if(kvno && ent.entry.kvno !=3D kvno) {
+    if(kvno && (krb5_kvno)ent.entry.kvno !=3D kvno) {
 	hdb_free_entry(context, &ent);
  	ret =3D KRB5_KT_NOTFOUND;
 	goto out;
@@ -244,29 +235,190 @@
 	if(ent.entry.keys.val[i].key.keytype =3D=3D enctype) {
 	    krb5_copy_principal(context, principal, &entry->principal);
 	    entry->vno =3D ent.entry.kvno;
-	    krb5_copy_keyblock_contents(context,=20
-					&ent.entry.keys.val[i].key,=20
+	    krb5_copy_keyblock_contents(context,
+					&ent.entry.keys.val[i].key,
 					&entry->keyblock);
 	    ret =3D 0;
 	    break;
 	}
     }
     hdb_free_entry(context, &ent);
-out:
+ out:
     (*db->hdb_close)(context, db);
     (*db->hdb_destroy)(context, db);
+ out2:
+    free(fdbname);
+    free(fmkey);
     return ret;
 }
=20
+/*
+ * find the keytab entry in `id' for `principal, kvno, enctype' and return
+ * it in `entry'.  return 0 or an error code
+ */
+
+static krb5_error_code KRB5_CALLCONV
+hdb_start_seq_get(krb5_context context,
+		  krb5_keytab id,
+		  krb5_kt_cursor *cursor)
+{
+    krb5_error_code ret;
+    struct hdb_cursor *c;
+    struct hdb_data *d =3D id->data;
+    const char *dbname =3D d->dbname;
+    const char *mkey   =3D d->mkey;
+    HDB *db;
+
+    if (dbname =3D=3D NULL) {
+	/*
+	 * We don't support enumerating without being told what
+	 * backend to enumerate on
+	 */
+  	ret =3D KRB5_KT_NOTFOUND;
+	return ret;
+    }
+
+    ret =3D hdb_create (context, &db, dbname);
+    if (ret)
+	return ret;
+    ret =3D hdb_set_master_keyfile (context, db, mkey);
+    if (ret) {
+	(*db->hdb_destroy)(context, db);
+	return ret;
+    }
+
+    ret =3D (*db->hdb_open)(context, db, O_RDONLY, 0);
+    if (ret) {
+	(*db->hdb_destroy)(context, db);
+	return ret;
+    }
+
+    cursor->data =3D c =3D malloc (sizeof(*c));
+    if(c =3D=3D NULL){
+	(*db->hdb_close)(context, db);
+	(*db->hdb_destroy)(context, db);
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	return ENOMEM;
+    }
+
+    c->db =3D db;
+    c->first =3D TRUE;
+    c->next =3D TRUE;
+    c->key_idx =3D 0;
+
+    cursor->data =3D c;
+    return ret;
+}
+
+static int KRB5_CALLCONV
+hdb_next_entry(krb5_context context,
+	       krb5_keytab id,
+	       krb5_keytab_entry *entry,
+	       krb5_kt_cursor *cursor)
+{
+    struct hdb_cursor *c =3D cursor->data;
+    krb5_error_code ret;
+
+    memset(entry, 0, sizeof(*entry));
+
+    if (c->first) {
+	c->first =3D FALSE;
+	ret =3D (c->db->hdb_firstkey)(context, c->db,
+				    HDB_F_DECRYPT|
+				    HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
+				    &c->hdb_entry);
+	if (ret =3D=3D HDB_ERR_NOENTRY)
+	    return KRB5_KT_END;
+	else if (ret)
+	    return ret;
+
+	if (c->hdb_entry.entry.keys.len =3D=3D 0)
+	    hdb_free_entry(context, &c->hdb_entry);
+	else
+	    c->next =3D FALSE;
+    }
+
+    while (c->next) {
+	ret =3D (c->db->hdb_nextkey)(context, c->db,
+				   HDB_F_DECRYPT|
+				   HDB_F_GET_CLIENT|HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
+				   &c->hdb_entry);
+	if (ret =3D=3D HDB_ERR_NOENTRY)
+	    return KRB5_KT_END;
+	else if (ret)
+	    return ret;
+
+	/* If no keys on this entry, try again */
+	if (c->hdb_entry.entry.keys.len =3D=3D 0)
+	    hdb_free_entry(context, &c->hdb_entry);
+	else
+	    c->next =3D FALSE;
+    }
+
+    /*
+     * Return next enc type (keytabs are one slot per key, while
+     * hdb is one record per principal.
+     */
+
+    ret =3D krb5_copy_principal(context,
+			      c->hdb_entry.entry.principal,
+			      &entry->principal);
+    if (ret)
+	return ret;
+
+    entry->vno =3D c->hdb_entry.entry.kvno;
+    ret =3D krb5_copy_keyblock_contents(context,
+				      &c->hdb_entry.entry.keys.val[c->key_idx].key,
+				      &entry->keyblock);
+    if (ret) {
+	krb5_free_principal(context, entry->principal);
+	memset(entry, 0, sizeof(*entry));
+	return ret;
+    }
+    c->key_idx++;
+
+    /*
+     * Once we get to the end of the list, signal that we want the
+     * next entry
+     */
+
+    if ((size_t)c->key_idx =3D=3D c->hdb_entry.entry.keys.len) {
+	hdb_free_entry(context, &c->hdb_entry);
+	c->next =3D TRUE;
+	c->key_idx =3D 0;
+    }
+
+    return 0;
+}
+
+
+static int KRB5_CALLCONV
+hdb_end_seq_get(krb5_context context,
+		krb5_keytab id,
+		krb5_kt_cursor *cursor)
+{
+    struct hdb_cursor *c =3D cursor->data;
+
+    if (!c->next)
+	hdb_free_entry(context, &c->hdb_entry);
+
+    (c->db->hdb_close)(context, c->db);
+    (c->db->hdb_destroy)(context, c->db);
+
+    free(c);
+    return 0;
+}
+
 krb5_kt_ops hdb_kt_ops =3D {
     "HDB",
     hdb_resolve,
     hdb_get_name,
     hdb_close,
+    NULL,		/* destroy */
     hdb_get_entry,
-    NULL,		/* start_seq_get */
-    NULL,		/* next_entry */
-    NULL,		/* end_seq_get */
+    hdb_start_seq_get,
+    hdb_next_entry,
+    hdb_end_seq_get,
     NULL,		/* add */
     NULL		/* remove */
 };
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/mkey.c
--- a/head/crypto/heimdal/lib/hdb/mkey.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/mkey.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2000 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
@@ -36,8 +36,6 @@
 #define O_BINARY 0
 #endif
=20
-RCSID("$Id: mkey.c 21745 2007-07-31 16:11:25Z lha $");
-
 struct hdb_master_key_data {
     krb5_keytab_entry keytab;
     krb5_crypto crypto;
@@ -67,7 +65,7 @@
=20
     *mkey =3D calloc(1, sizeof(**mkey));
     if(*mkey =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     (*mkey)->keytab.vno =3D kvno;
@@ -110,7 +108,7 @@
 }
=20
 static krb5_error_code
-read_master_keytab(krb5_context context, const char *filename,=20
+read_master_keytab(krb5_context context, const char *filename,
 		   hdb_master_key *mkey)
 {
     krb5_error_code ret;
@@ -118,7 +116,7 @@
     krb5_kt_cursor cursor;
     krb5_keytab_entry entry;
     hdb_master_key p;
-   =20
+
     ret =3D krb5_kt_resolve(context, filename, &id);
     if(ret)
 	return ret;
@@ -147,20 +145,20 @@
=20
 /* read a MIT master keyfile */
 static krb5_error_code
-read_master_mit(krb5_context context, const char *filename,=20
-		hdb_master_key *mkey)
+read_master_mit(krb5_context context, const char *filename,
+		int byteorder, hdb_master_key *mkey)
 {
     int fd;
     krb5_error_code ret;
     krb5_storage *sp;
     int16_t enctype;
     krb5_keyblock key;
-	      =20
+
     fd =3D open(filename, O_RDONLY | O_BINARY);
     if(fd < 0) {
 	int save_errno =3D errno;
-	krb5_set_error_string(context, "failed to open %s: %s", filename,
-			      strerror(save_errno));
+	krb5_set_error_message(context, save_errno, "failed to open %s: %s",
+			       filename, strerror(save_errno));
 	return save_errno;
     }
     sp =3D krb5_storage_from_fd(fd);
@@ -168,25 +166,22 @@
 	close(fd);
 	return errno;
     }
-    krb5_storage_set_flags(sp, KRB5_STORAGE_HOST_BYTEORDER);
-#if 0
+    krb5_storage_set_flags(sp, byteorder);
     /* could possibly use ret_keyblock here, but do it with more
        checks for now */
-    ret =3D krb5_ret_keyblock(sp, &key);
-#else
-    ret =3D krb5_ret_int16(sp, &enctype);
-    if((htons(enctype) & 0xff00) =3D=3D 0x3000) {
-	krb5_set_error_string(context, "unknown keytype in %s: %#x, expected %#x"=
,=20
-			      filename, htons(enctype), 0x3000);
-	ret =3D HEIM_ERR_BAD_MKEY;
-	goto out;
+    {
+	ret =3D krb5_ret_int16(sp, &enctype);
+	if (ret)
+	    goto out;
+	ret =3D krb5_enctype_valid(context, enctype);
+	if (ret)
+	   goto out;
+	key.keytype =3D enctype;
+	ret =3D krb5_ret_data(sp, &key.keyvalue);
+	if(ret)
+	    goto out;
     }
-    key.keytype =3D enctype;
-    ret =3D krb5_ret_data(sp, &key.keyvalue);
-    if(ret)
-	goto out;
-#endif
-    ret =3D hdb_process_master_key(context, 0, &key, 0, mkey);
+    ret =3D hdb_process_master_key(context, 1, &key, 0, mkey);
     krb5_free_keyblock_contents(context, &key);
   out:
     krb5_storage_free(sp);
@@ -196,7 +191,7 @@
=20
 /* read an old master key file */
 static krb5_error_code
-read_master_encryptionkey(krb5_context context, const char *filename,=20
+read_master_encryptionkey(krb5_context context, const char *filename,
 			  hdb_master_key *mkey)
 {
     int fd;
@@ -205,20 +200,20 @@
     unsigned char buf[256];
     ssize_t len;
     size_t ret_len;
-	      =20
+
     fd =3D open(filename, O_RDONLY | O_BINARY);
     if(fd < 0) {
 	int save_errno =3D errno;
-	krb5_set_error_string(context, "failed to open %s: %s",=20
+	krb5_set_error_message(context, save_errno, "failed to open %s: %s",
 			      filename, strerror(save_errno));
 	return save_errno;
     }
-   =20
+
     len =3D read(fd, buf, sizeof(buf));
     close(fd);
     if(len < 0) {
 	int save_errno =3D errno;
-	krb5_set_error_string(context, "error reading %s: %s",=20
+	krb5_set_error_message(context, save_errno, "error reading %s: %s",
 			      filename, strerror(save_errno));
 	return save_errno;
     }
@@ -233,9 +228,9 @@
        should cover all cases, but will break if someone has hacked
        this code to really use des-cbc-md5 -- but then that's not my
        problem. */
-    if(key.keytype =3D=3D KEYTYPE_DES || key.keytype =3D=3D ETYPE_DES_CBC_=
MD5)
+    if(key.keytype =3D=3D ETYPE_DES_CBC_CRC || key.keytype =3D=3D ETYPE_DE=
S_CBC_MD5)
 	key.keytype =3D ETYPE_DES_CFB64_NONE;
-   =20
+
     ret =3D hdb_process_master_key(context, 0, &key, 0, mkey);
     krb5_free_keyblock_contents(context, &key);
     return ret;
@@ -243,7 +238,7 @@
=20
 /* read a krb4 /.k style file */
 static krb5_error_code
-read_master_krb4(krb5_context context, const char *filename,=20
+read_master_krb4(krb5_context context, const char *filename,
 		 hdb_master_key *mkey)
 {
     int fd;
@@ -251,25 +246,26 @@
     krb5_error_code ret;
     unsigned char buf[256];
     ssize_t len;
-	      =20
+
     fd =3D open(filename, O_RDONLY | O_BINARY);
     if(fd < 0) {
 	int save_errno =3D errno;
-	krb5_set_error_string(context, "failed to open %s: %s",=20
-			      filename, strerror(save_errno));
+	krb5_set_error_message(context, save_errno, "failed to open %s: %s",
+			       filename, strerror(save_errno));
 	return save_errno;
     }
-   =20
+
     len =3D read(fd, buf, sizeof(buf));
     close(fd);
     if(len < 0) {
 	int save_errno =3D errno;
-	krb5_set_error_string(context, "error reading %s: %s",=20
-			      filename, strerror(save_errno));
+	krb5_set_error_message(context, save_errno, "error reading %s: %s",
+			       filename, strerror(save_errno));
 	return save_errno;
     }
     if(len !=3D 8) {
-	krb5_set_error_string(context, "bad contents of %s", filename);
+	krb5_set_error_message(context, HEIM_ERR_EOF,
+			       "bad contents of %s", filename);
 	return HEIM_ERR_EOF; /* XXX file might be too large */
     }
=20
@@ -277,7 +273,7 @@
     key.keytype =3D ETYPE_DES_PCBC_NONE;
     ret =3D krb5_data_copy(&key.keyvalue, buf, len);
     memset(buf, 0, sizeof(buf));
-    if(ret)=20
+    if(ret)
 	return ret;
=20
     ret =3D hdb_process_master_key(context, 0, &key, 0, mkey);
@@ -286,7 +282,7 @@
 }
=20
 krb5_error_code
-hdb_read_master_key(krb5_context context, const char *filename,=20
+hdb_read_master_key(krb5_context context, const char *filename,
 		    hdb_master_key *mkey)
 {
     FILE *f;
@@ -303,26 +299,26 @@
     f =3D fopen(filename, "r");
     if(f =3D=3D NULL) {
 	int save_errno =3D errno;
-	krb5_set_error_string(context, "failed to open %s: %s",=20
-			      filename, strerror(save_errno));
+	krb5_set_error_message(context, save_errno, "failed to open %s: %s",
+			       filename, strerror(save_errno));
 	return save_errno;
     }
-   =20
+
     if(fread(buf, 1, 2, f) !=3D 2) {
-	krb5_set_error_string(context, "end of file reading %s", filename);
 	fclose(f);
+	krb5_set_error_message(context, HEIM_ERR_EOF, "end of file reading %s", f=
ilename);
 	return HEIM_ERR_EOF;
     }
-   =20
+
     fseek(f, 0, SEEK_END);
     len =3D ftell(f);
=20
     if(fclose(f) !=3D 0)
 	return errno;
-   =20
+
     if(len < 0)
 	return errno;
-   =20
+
     if(len =3D=3D 8) {
 	ret =3D read_master_krb4(context, filename, mkey);
     } else if(buf[0] =3D=3D 0x30 && len <=3D 127 && buf[1] =3D=3D len - 2)=
 {
@@ -330,13 +326,20 @@
     } else if(buf[0] =3D=3D 5 && buf[1] >=3D 1 && buf[1] <=3D 2) {
 	ret =3D read_master_keytab(context, filename, mkey);
     } else {
-	ret =3D read_master_mit(context, filename, mkey);
+      /*
+       * Check both LittleEndian and BigEndian since they key file
+       * might be moved from a machine with diffrent byte order, or
+       * its running on MacOS X that always uses BE master keys.
+       */
+      ret =3D read_master_mit(context, filename, KRB5_STORAGE_BYTEORDER_LE=
, mkey);
+      if (ret)
+          ret =3D read_master_mit(context, filename, KRB5_STORAGE_BYTEORDE=
R_BE, mkey);
     }
     return ret;
 }
=20
 krb5_error_code
-hdb_write_master_key(krb5_context context, const char *filename,=20
+hdb_write_master_key(krb5_context context, const char *filename,
 		     hdb_master_key mkey)
 {
     krb5_error_code ret;
@@ -369,7 +372,7 @@
 	if(mkvno =3D=3D NULL) {
 	    if(ret =3D=3D NULL || mkey->keytab.vno > ret->keytab.vno)
 		ret =3D mkey;
-	} else if(mkey->keytab.vno =3D=3D *mkvno)
+	} else if((uint32_t)mkey->keytab.vno =3D=3D *mkvno)
 	    return mkey;
 	mkey =3D mkey->next;
     }
@@ -401,9 +404,9 @@
 }
=20
 krb5_error_code
-hdb_unseal_key_mkey(krb5_context context, Key *k, hdb_master_key mkey)=20
+hdb_unseal_key_mkey(krb5_context context, Key *k, hdb_master_key mkey)
 {
-=09
+
     krb5_error_code ret;
     krb5_data res;
     size_t keysize;
@@ -412,7 +415,7 @@
=20
     if(k->mkvno =3D=3D NULL)
 	return 0;
-=09
+
     key =3D _hdb_find_master_key(k->mkvno, mkey);
=20
     if (key =3D=3D NULL)
@@ -428,7 +431,7 @@
 				k->key.keyvalue.data,
 				k->key.keyvalue.length,
 				&res);
-    }   =20
+    }
     if (ret)
 	return ret;
=20
@@ -456,13 +459,13 @@
 krb5_error_code
 hdb_unseal_keys_mkey(krb5_context context, hdb_entry *ent, hdb_master_key =
mkey)
 {
-    int i;
+    size_t i;
=20
     for(i =3D 0; i < ent->keys.len; i++){
 	krb5_error_code ret;
=20
 	ret =3D hdb_unseal_key_mkey(context, &ent->keys.val[i], mkey);
-	if (ret)=20
+	if (ret)
 	    return ret;
     }
     return 0;
@@ -516,14 +519,14 @@
 	    return ENOMEM;
     }
     *k->mkvno =3D key->keytab.vno;
-=09
+
     return 0;
 }
=20
 krb5_error_code
 hdb_seal_keys_mkey(krb5_context context, hdb_entry *ent, hdb_master_key mk=
ey)
 {
-    int i;
+    size_t i;
     for(i =3D 0; i < ent->keys.len; i++){
 	krb5_error_code ret;
=20
@@ -539,7 +542,7 @@
 {
     if (db->hdb_master_key_set =3D=3D 0)
 	return 0;
-   =20
+
     return hdb_seal_keys_mkey(context, ent, db->hdb_master_key);
 }
=20
@@ -548,7 +551,7 @@
 {
     if (db->hdb_master_key_set =3D=3D 0)
 	return 0;
-   =20
+
     return hdb_seal_key_mkey(context, k, db->hdb_master_key);
 }
=20
@@ -583,7 +586,7 @@
     if (ret) {
 	if (ret !=3D ENOENT)
 	    return ret;
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return 0;
     }
     db->hdb_master_key =3D key;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/ndbm.c
--- a/head/crypto/heimdal/lib/hdb/ndbm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/ndbm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,47 +1,47 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
=20
-RCSID("$Id: ndbm.c 16395 2005-12-13 11:54:10Z lha $");
-
 #if HAVE_NDBM
=20
 #if defined(HAVE_GDBM_NDBM_H)
 #include <gdbm/ndbm.h>
+#define WRITE_SUPPORT 1
 #elif defined(HAVE_NDBM_H)
 #include <ndbm.h>
 #elif defined(HAVE_DBM_H)
+#define WRITE_SUPPORT 1
 #include <dbm.h>
 #endif
=20
@@ -53,9 +53,7 @@
 static krb5_error_code
 NDBM_destroy(krb5_context context, HDB *db)
 {
-    krb5_error_code ret;
-
-    ret =3D hdb_clear_master_key (context, db);
+    hdb_clear_master_key (context, db);
     free(db->hdb_name);
     free(db);
     return 0;
@@ -76,7 +74,7 @@
 }
=20
 static krb5_error_code
-NDBM_seq(krb5_context context, HDB *db,=20
+NDBM_seq(krb5_context context, HDB *db,
 	 unsigned flags, hdb_entry_ex *entry, int first)
=20
 {
@@ -110,9 +108,9 @@
     if (ret =3D=3D 0 && entry->entry.principal =3D=3D NULL) {
 	entry->entry.principal =3D malloc (sizeof(*entry->entry.principal));
 	if (entry->entry.principal =3D=3D NULL) {
+	    hdb_free_entry (context, entry);
 	    ret =3D ENOMEM;
-	    hdb_free_entry (context, entry);
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, "malloc: out of memory");
 	} else {
 	    hdb_key2principal (context, &key_data, entry->entry.principal);
 	}
@@ -135,40 +133,59 @@
 }
=20
 static krb5_error_code
+open_lock_file(krb5_context context, const char *db_name, int *fd)
+{
+    char *lock_file;
+
+    /* lock old and new databases */
+    asprintf(&lock_file, "%s.lock", db_name);
+    if(lock_file =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	return ENOMEM;
+    }
+
+    *fd =3D open(lock_file, O_RDWR | O_CREAT, 0600);
+    free(lock_file);
+    if(*fd < 0) {
+	int ret =3D errno;
+	krb5_set_error_message(context, ret, "open(%s): %s", lock_file,
+			       strerror(ret));
+	return ret;
+    }
+    return 0;
+}
+
+
+static krb5_error_code
 NDBM_rename(krb5_context context, HDB *db, const char *new_name)
 {
-    /* XXX this function will break */
-    struct ndbm_db *d =3D db->hdb_db;
-
     int ret;
     char *old_dir, *old_pag, *new_dir, *new_pag;
-    char *new_lock;
-    int lock_fd;
+    int old_lock_fd, new_lock_fd;
=20
     /* lock old and new databases */
-    ret =3D db->hdb_lock(context, db, HDB_WLOCK);
-    if(ret)
+    ret =3D open_lock_file(context, db->hdb_name, &old_lock_fd);
+    if (ret)
 	return ret;
-    asprintf(&new_lock, "%s.lock", new_name);
-    if(new_lock =3D=3D NULL) {
-	db->hdb_unlock(context, db);
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    lock_fd =3D open(new_lock, O_RDWR | O_CREAT, 0600);
-    if(lock_fd < 0) {
-	ret =3D errno;
-	db->hdb_unlock(context, db);
-	krb5_set_error_string(context, "open(%s): %s", new_lock,
-			      strerror(ret));
-	free(new_lock);
+
+    ret =3D hdb_lock(old_lock_fd, HDB_WLOCK);
+    if(ret) {
+	close(old_lock_fd);
 	return ret;
     }
-    free(new_lock);
-    ret =3D hdb_lock(lock_fd, HDB_WLOCK);
+
+    ret =3D open_lock_file(context, new_name, &new_lock_fd);
+    if (ret) {
+	hdb_unlock(old_lock_fd);
+	close(old_lock_fd);
+	return ret;
+    }
+
+    ret =3D hdb_lock(new_lock_fd, HDB_WLOCK);
     if(ret) {
-	db->hdb_unlock(context, db);
-	close(lock_fd);
+	hdb_unlock(old_lock_fd);
+	close(old_lock_fd);
+	close(new_lock_fd);
 	return ret;
     }
=20
@@ -178,23 +195,26 @@
     asprintf(&new_pag, "%s.pag", new_name);
=20
     ret =3D rename(old_dir, new_dir) || rename(old_pag, new_pag);
+    if (ret) {
+	ret =3D errno;
+	if (ret =3D=3D 0)
+	    ret =3D EPERM;
+	krb5_set_error_message(context, ret, "rename: %s", strerror(ret));
+    }
+
     free(old_dir);
     free(old_pag);
     free(new_dir);
     free(new_pag);
-    hdb_unlock(lock_fd);
-    db->hdb_unlock(context, db);
=20
-    if(ret) {
-	ret =3D errno;
-	close(lock_fd);
-	krb5_set_error_string(context, "rename: %s", strerror(ret));
+    hdb_unlock(new_lock_fd);
+    hdb_unlock(old_lock_fd);
+    close(new_lock_fd);
+    close(old_lock_fd);
+
+    if(ret)
 	return ret;
-    }
=20
-    close(d->lock_fd);
-    d->lock_fd =3D lock_fd;
-   =20
     free(db->hdb_name);
     db->hdb_name =3D strdup(new_name);
     return 0;
@@ -222,9 +242,10 @@
 }
=20
 static krb5_error_code
-NDBM__put(krb5_context context, HDB *db, int replace,=20
+NDBM__put(krb5_context context, HDB *db, int replace,
 	krb5_data key, krb5_data value)
 {
+#ifdef WRITE_SUPPORT
     struct ndbm_db *d =3D (struct ndbm_db *)db->hdb_db;
     datum k, v;
     int code;
@@ -244,6 +265,9 @@
     if (code < 0)
 	return code;
     return 0;
+#else
+    return HDB_ERR_NO_WRITE_SUPPORT;
+#endif
 }
=20
 static krb5_error_code
@@ -281,38 +305,31 @@
 {
     krb5_error_code ret;
     struct ndbm_db *d =3D malloc(sizeof(*d));
-    char *lock_file;
=20
     if(d =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
-    asprintf(&lock_file, "%s.lock", (char*)db->hdb_name);
-    if(lock_file =3D=3D NULL) {
-	free(d);
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
+
     d->db =3D dbm_open((char*)db->hdb_name, flags, mode);
     if(d->db =3D=3D NULL){
 	ret =3D errno;
 	free(d);
-	free(lock_file);
-	krb5_set_error_string(context, "dbm_open(%s): %s", db->hdb_name,
-			      strerror(ret));
+	krb5_set_error_message(context, ret, "dbm_open(%s): %s", db->hdb_name,
+			       strerror(ret));
 	return ret;
     }
-    d->lock_fd =3D open(lock_file, O_RDWR | O_CREAT, 0600);
-    if(d->lock_fd < 0){
+
+    ret =3D open_lock_file(context, db->hdb_name, &d->lock_fd);
+    if (ret) {
 	ret =3D errno;
 	dbm_close(d->db);
 	free(d);
-	krb5_set_error_string(context, "open(%s): %s", lock_file,
-			      strerror(ret));
-	free(lock_file);
+	krb5_set_error_message(context, ret, "open(lock file): %s",
+			       strerror(ret));
 	return ret;
     }
-    free(lock_file);
+
     db->hdb_db =3D d;
     if((flags & O_ACCMODE) =3D=3D O_RDONLY)
 	ret =3D hdb_check_db_format(context, db);
@@ -322,37 +339,38 @@
 	return 0;
     if (ret) {
 	NDBM_close(context, db);
-	krb5_set_error_string(context, "hdb_open: failed %s database %s",
-			      (flags & O_ACCMODE) =3D=3D O_RDONLY ?=20
-			      "checking format of" : "initialize",=20
-			      db->hdb_name);
+	krb5_set_error_message(context, ret, "hdb_open: failed %s database %s",
+			       (flags & O_ACCMODE) =3D=3D O_RDONLY ?
+			       "checking format of" : "initialize",
+			       db->hdb_name);
     }
     return ret;
 }
=20
 krb5_error_code
-hdb_ndbm_create(krb5_context context, HDB **db,=20
+hdb_ndbm_create(krb5_context context, HDB **db,
 		const char *filename)
 {
     *db =3D calloc(1, sizeof(**db));
     if (*db =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
=20
     (*db)->hdb_db =3D NULL;
     (*db)->hdb_name =3D strdup(filename);
     if ((*db)->hdb_name =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	free(*db);
 	*db =3D NULL;
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     (*db)->hdb_master_key_set =3D 0;
     (*db)->hdb_openp =3D 0;
+    (*db)->hdb_capability_flags =3D HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
     (*db)->hdb_open =3D NDBM_open;
     (*db)->hdb_close =3D NDBM_close;
-    (*db)->hdb_fetch =3D _hdb_fetch;
+    (*db)->hdb_fetch_kvno =3D _hdb_fetch_kvno;
     (*db)->hdb_store =3D _hdb_store;
     (*db)->hdb_remove =3D _hdb_remove;
     (*db)->hdb_firstkey =3D NDBM_firstkey;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/print.c
--- a/head/crypto/heimdal/lib/hdb/print.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hdb/print.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,9 +34,7 @@
 #include <hex.h>
 #include <ctype.h>
=20
-RCSID("$Id: print.c 16378 2005-12-12 12:40:12Z lha $");
-
-/*=20
+/*
    This is the present contents of a dump line. This might change at
    any time. Fields are separated by white space.
=20
@@ -69,7 +67,7 @@
     vasprintf(&s, fmt, ap);
     va_end(ap);
     if(s =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     ret =3D krb5_storage_write(sp, s, strlen(s));
@@ -80,7 +78,8 @@
 static krb5_error_code
 append_hex(krb5_context context, krb5_storage *sp, krb5_data *data)
 {
-    int i, printable =3D 1;
+    int printable =3D 1;
+    size_t i;
     char *p;
=20
     p =3D data->data;
@@ -128,7 +127,7 @@
 entry2string_int (krb5_context context, krb5_storage *sp, hdb_entry *ent)
 {
     char *p;
-    int i;
+    size_t i;
     krb5_error_code ret;
=20
     /* --- principal */
@@ -143,11 +142,11 @@
     for(i =3D 0; i < ent->keys.len; i++){
 	/* --- mkvno, keytype */
 	if(ent->keys.val[i].mkvno)
-	    append_string(context, sp, ":%d:%d:",=20
-			  *ent->keys.val[i].mkvno,=20
+	    append_string(context, sp, ":%d:%d:",
+			  *ent->keys.val[i].mkvno,
 			  ent->keys.val[i].key.keytype);
 	else
-	    append_string(context, sp, "::%d:",=20
+	    append_string(context, sp, "::%d:",
 			  ent->keys.val[i].key.keytype);
 	/* --- keydata */
 	append_hex(context, sp, &ent->keys.val[i].key.keyvalue);
@@ -176,7 +175,7 @@
 	append_string(context, sp, "%s ", time2str(*ent->valid_end));
     else
 	append_string(context, sp, "- ");
-   =20
+
     /* --- password ends */
     if(ent->pw_end)
 	append_string(context, sp, "%s ", time2str(*ent->pw_end));
@@ -194,7 +193,7 @@
 	append_string(context, sp, "%d ", *ent->max_renew);
     else
 	append_string(context, sp, "- ");
-   =20
+
     /* --- flags */
     append_string(context, sp, "%d ", HDBFlags2int(ent->flags));
=20
@@ -210,12 +209,12 @@
     if(ent->extensions && ent->extensions->len > 0) {
 	for(i =3D 0; i < ent->extensions->len; i++) {
 	    void *d;
-	    size_t size, sz;
+	    size_t size, sz =3D 0;
=20
 	    ASN1_MALLOC_ENCODE(HDB_extension, d, size,
 			       &ent->extensions->val[i], &sz, ret);
 	    if (ret) {
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		return ret;
 	    }
 	    if(size !=3D sz)
@@ -223,19 +222,19 @@
=20
 	    if (hex_encode(d, size, &p) < 0) {
 		free(d);
-		krb5_set_error_string(context, "malloc: out of memory");
+		krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 		return ENOMEM;
 	    }
=20
 	    free(d);
-	    append_string(context, sp, "%s%s", p,=20
+	    append_string(context, sp, "%s%s", p,
 			  ent->extensions->len - 1 !=3D i ? ":" : "");
 	    free(p);
 	}
     } else
 	append_string(context, sp, "-");
=20
-   =20
+
     return 0;
 }
=20
@@ -248,10 +247,10 @@
=20
     sp =3D krb5_storage_emem();
     if(sp =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
-   =20
+
     ret =3D entry2string_int(context, sp, ent);
     if(ret) {
 	krb5_storage_free(sp);
@@ -278,10 +277,10 @@
     fflush(f);
     sp =3D krb5_storage_from_fd(fileno(f));
     if(sp =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
-   =20
+
     ret =3D entry2string_int(context, sp, &entry->entry);
     if(ret) {
 	krb5_storage_free(sp);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hdb/test_dbinf=
o.c
--- a/head/crypto/heimdal/lib/hdb/test_dbinfo.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hdb/test_dbinfo.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hdb_locl.h"
 #include <getarg.h>
=20
-RCSID("$Id: test_dbinfo.c 20575 2007-04-27 20:20:32Z lha $");
-
 static int help_flag;
 static int version_flag;
=20
@@ -60,7 +58,7 @@
=20
     if(help_flag)
 	krb5_std_usage(0, args, num_args);
-   =20
+
     if(version_flag){
 	print_version(NULL);
 	exit(0);
@@ -76,11 +74,17 @@
=20
     d =3D NULL;
     while ((d =3D hdb_dbinfo_get_next(info, d)) !=3D NULL) {
-	printf("label: %s\n", hdb_dbinfo_get_label(context, d));
-	printf("\trealm: %s\n", hdb_dbinfo_get_realm(context, d));
-	printf("\tdbname: %s\n", hdb_dbinfo_get_dbname(context, d));
-	printf("\tmkey_file: %s\n", hdb_dbinfo_get_mkey_file(context, d));
-	printf("\tacl_file: %s\n", hdb_dbinfo_get_acl_file(context, d));
+	const char *s;
+	s =3D hdb_dbinfo_get_label(context, d);
+	printf("label: %s\n", s ? s : "no label");
+	s =3D hdb_dbinfo_get_realm(context, d);
+	printf("\trealm: %s\n", s ? s : "no realm");
+	s =3D hdb_dbinfo_get_dbname(context, d);
+	printf("\tdbname: %s\n", s ? s : "no dbname");
+	s =3D hdb_dbinfo_get_mkey_file(context, d);
+	printf("\tmkey_file: %s\n", s ? s : "no mkey file");
+	s =3D hdb_dbinfo_get_acl_file(context, d);
+	printf("\tacl_file: %s\n", s ? s : "no acl file");
     }
=20
     hdb_free_dbinfo(context, &info);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ChangeLog
--- a/head/crypto/heimdal/lib/hx509/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,120 @@
-2008-01-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-07-14  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* hxtool.c: Break out print_eval_types().
+=09
+2008-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* ks_p12.c: pass in time_now to unevelope
+
+	* cms.c: Pass in time_now to unevelope, us verify context time in
+	verify_signed.
+
+2008-05-23  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+=09
+	* hx_locl.h: Include <limits.h> for TYPE_MAX defines.
+
+2008-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* sel-lex.l: Use _hx509_sel_yyerror() instead of error_message().
+=09
+2008-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* sel-lex.l: Include <config.h>
+
+2008-04-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Makefile.am: Update make-proto usage.
+
+2008-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* ca.c: BasicConstraints.pathLenConstraint unsigned int.
+
+	* sel-lex.l: Prefix sel_error with _hx509_ since its global on
+	platforms w/o symbol versioning.
+=09
+	* sel.h: rename yyerror to sel_yyerror in the whole library, not
+	just the lexer
+
+	* sel-lex.l: rename yyerror to sel_yyerror in the whole library,
+	not just the lexer
+=09
+2008-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* sel-lex.l: Rename yyerror to sel_yyerror and make it static.
+
+2008-04-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* hx509.h: Make self-standing by including missing files.
+
+2008-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* ks_p11.c: Use unsigned where appropriate.
+
+	* softp11.c: call va_start before using vsnprintf.
+
+	* crypto.c: make refcount slightly more sane.
+
+	* keyset.c: make refcount slightly more sane.
+
+	* cert.c: make refcount slightly more sane.
+
+2008-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* test_nist2.in: Try to find unzip.
+
+2008-03-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* version-script.map: add missing symbols
+
+	* spnego: Make delegated credentials delegated directly, Oleg
+	Sharoiko pointed out that it always didnt work with the old
+	code. Also add som missing cred and context pass-thou functions in
+	the SPNEGO layer.
+=09
+2008-03-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* rename to be more consistent, export for teting
+
+	* Add language to support querying certificates to find a
+	match. Support constructs like "1.3.6.1.5.2.3.5" IN
+	%{certificate.eku} AND %{certificate.subject} TAILMATCH "C=3DSE".
+
+2008-02-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* version-script.map: add hx509_pem_read
+
+	* hxtool-commands.in: Add --pem to cms-verify-sd.
+
+	* test_cms.in: Test verifying PEM signature files.
+
+	* hxtool.c: Support verifying PEM signature files.
+
+2008-02-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Makefile.am: libhx509_la_OBJECTS depends on hx_locl.h
+
+2008-02-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Use ldap-prep (with libwind) to compare names
+
+2008-01-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* cert.c (hx509_query_match_eku): update to support the NULL
+	eku (reset), clearify the old behaivor with regards repetitive
+	calls.
+
+	* Add matching on EKU, validate EKUs, add hxtool matching glue,
+	add check. Adapted from pach from Tim Miller of Mitre
+
+2008-01-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_soft_pkcs11.c: use func for more C_ functions.
 =09
-2008-01-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* version-script.map: Export hx509_free_error_string().
=20
-2008-01-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* version-script.map: only export C_GetFunctionList
=20
@@ -17,7 +125,7 @@
 	* softp11.c: Add option app-fatal to control if softtoken should
 	abort() on erroneous input from applications.
=20
-2008-01-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_pkcs11.in: Test password less certificates too
=20
@@ -29,7 +137,7 @@
=20
 	* test_soft_pkcs11.c: Only log in if needed.
=20
-2008-01-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* softp11.c: Support PINs to login to the store.
=20
@@ -45,20 +153,20 @@
 	* softp11.c: Add more glue to figure out what keytype this
 	certificate is using.
=20
-2008-01-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_pkcs11.in: test debug
=20
 	* Add a PKCS11 provider supporting signing and verifing sigatures.
=20
-2008-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* version-script.map: Replace hx509_name_to_der_name with
 	hx509_name_binary.
=20
 	* print.c: make print_func static
=20
-2007-12-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* print.c: doxygen
=20
@@ -68,15 +176,15 @@
=20
 	* ca.c: doxygen.
=20
-2007-12-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ca.c: doxygen
=20
-2007-12-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* error.c: doxygen
 =09
-2007-12-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* More documentation
 =09
@@ -86,17 +194,17 @@
=20
 	* cms.c: Doxygen documentation.
=20
-2007-12-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* *.[ch]: More documentation
=20
-2007-12-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* handle refcount on NULL.
=20
 	* test_nist_pkcs12.in: drop echo -n, doesn't work with posix sh
=20
-2007-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_nist2.in: Print that this is version 2 of the tests
=20
@@ -118,20 +226,20 @@
=20
 	* revoke.c (_hx509_revoke_ref): new function.
=20
-2007-11-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-11-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_keychain.c: Check if SecKeyGetCSPHandle needs prototype.
=20
-2007-08-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* data/nist-data: Make work on case senstive filesystems too.
 =09
-2007-08-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cert.c: match rfc822 contrains better, provide better error
 	strings.
=20
-2007-08-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cert.c: "self-signed doesn't count" doesn't apply to trust
 	anchor certificate.  make trust anchor check consistant.
@@ -145,7 +253,7 @@
=20
 	* cert.c: Fix NC, comment on how to use _hx509_check_key_usage.
=20
-2007-08-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_nist2.in, Makefile, test/nist*: Add nist pkits tests.=20
=20
@@ -160,12 +268,12 @@
 	* revoke.c: Search for the right issuer when looking for the
 	issuer of the CRL signer.
=20
-2007-08-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* revoke.c: Handle CRL signing certificate better, try to not
 	revalidate invalid CRLs over and over.
=20
-2007-08-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c: remove stale comment.
=20
@@ -177,21 +285,21 @@
=20
 	* Makefile.am: clean PKITS_data
=20
-2007-07-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add version-script.map to EXTRA_DIST
=20
-2007-07-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add depenency on asn1_compile for asn1 built files.
 =09
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* peer.c: update (c), indent.
=20
 	* Makefile.am: New library version.
=20
-2007-06-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_p11.c: Add sha2 types.
=20
@@ -207,7 +315,7 @@
=20
 	* print.c: Rename proxyCertInfo oid.
 =09
-2007-06-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ca.in: Adapt to new request handling.
=20
@@ -231,7 +339,7 @@
=20
 	* version-script.map: add missing ;
=20
-2007-06-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c: Use hx509_crypto_random_iv.
=20
@@ -285,7 +393,7 @@
=20
 	* hxtool.c: Verify hostname and test max-depth.
=20
-2007-06-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_cms.in: Test --id-by-name.
=20
@@ -302,7 +410,7 @@
 	* cert.c (match_general_name): more strict rfc822Name matching.
 	(hx509_verify_hostname): add hostname type for matching.
=20
-2007-06-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c: Make compile again.
=20
@@ -317,7 +425,7 @@
=20
 	* test_cert.in: more cert and keyset tests.
=20
-2007-06-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* revoke.c: Avoid stomping on NULL.
=20
@@ -333,7 +441,7 @@
=20
 	* crypto.c: Free memory in failure case.
=20
-2007-06-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* *.c: Add hx509_cert_init_data and use everywhere
=20
@@ -352,13 +460,13 @@
 	* cert.c: Change logic for default trust anchors, make it be
 	either default trust anchor, the user supplied, or non at all.
=20
-2007-06-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add data/j.pem.
=20
 	* Makefile.am: Add test_windows.in.
 =09
-2007-06-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_keychain.c: rename functions, leaks less memory and more
 	paranoia.
@@ -383,7 +491,7 @@
=20
 	* Makefile.am: add wcrl.crl
 =09
-2007-06-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hx_locl.h: Disable KEYCHAIN for now, its slow.
=20
@@ -407,7 +515,7 @@
 	special and be the system X509Anchors file. By not specifing any
 	keychain ("KEYCHAIN:"), all keychains are probed.
 =09
-2007-06-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c (verify): Friendlier error message.
=20
@@ -465,7 +573,7 @@
=20
 	* name.c: Reset name before parsing it.
 =09
-2007-06-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* revoke.c (hx509_crl_*): fix sizeof() mistakes to fix memory
 	corruption.
@@ -491,7 +599,7 @@
=20
 	* cert.c (hx509_context_free): free querystat
 =09
-2007-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_chain.in: test ocsp-verify
 =09
@@ -505,7 +613,7 @@
=20
 	* hxtool-commands.in: New command ocsp-verify.
 =09
-2007-06-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ca.in: Create crl and verify that is works.
=20
@@ -558,7 +666,7 @@
=20
 	* ca.c (hx509_ca_tbs_add_crl_dp_uri): plug memory leak
 =09
-2007-05-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* print.c: print utf8 type SAN's
=20
@@ -577,7 +685,7 @@
=20
 	* hxtool-commands.in: make ca and alias of certificate-sign
 =09
-2007-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* crypto.c (hx509_crypto_select): copy AI to the right place.
=20
@@ -608,11 +716,11 @@
=20
 	* hx509.h: Add HX509_SELECT_SECRET_ENC.
 =09
-2007-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ks_p11.c: add more mechtypes
 =09
-2007-05-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* print.c: Indent.
=20
@@ -632,17 +740,17 @@
=20
 	* ks_p11.c: Add some more hashes.
 =09
-2007-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c (crypto_select): stop memory leak
 =09
-2007-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* peer.c (hx509_peer_info_free): free memory used too
=20
 	* hxtool.c (crypto_select): only free peer if it was used.
 =09
-2007-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c: free template
=20
@@ -663,18 +771,18 @@
 	* ks_mem.c (mem_getkeys): allocate one more the we have elements
 	so its possible to store the NULL pointer at the end.
 =09
-2007-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: CLEANFILES +=3D cert-null.pem cert-sub-ca2.pem
 =09
-2007-02-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-02-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ca.c: Disable CRLDistributionPoints for now, its IMPLICIT code
 	in the asn1 parser.
=20
 	* print.c: Add some more \n's.
 =09
-2007-02-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* file.c: Allow mapping using heim_octet_string.
=20
@@ -693,7 +801,7 @@
=20
 	* cert.c: Fix printing and plug leak-on-error.
 =09
-2007-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_ca.in: Add test for ca --crl-uri.
=20
@@ -710,27 +818,27 @@
=20
 	* cert.c (is_proxy_cert): free info if we wont return it.
 =09
-2007-01-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* hxtool.c: Try to help how to use this command.
 =09
-2007-01-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* switch to sha256 as default digest for signing
=20
-2007-01-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ca.in: Really test sub-ca code, add basic constraints tests
 =09
-2007-01-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: Fix makefile problem.
 =09
-2007-01-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c: Set num of bits before we generate the key.
 =09
-2007-01-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* cms.c (hx509_cms_create_signed_1): use hx509_cert_binary
=20
@@ -741,7 +849,7 @@
 	* cert.c (hx509_cert_binary): return binary encoded
 	certificate (DER format)
 =09
-2007-01-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ca.c (hx509_ca_tbs_subject_expand): new function.
=20
@@ -763,7 +871,7 @@
=20
 	* cert.c: Export more stuff from certificate.
 =09
-2007-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ca.c: update (c)
=20
@@ -782,7 +890,7 @@
=20
 	* env.c: key-value pair help functions
 =09
-2007-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ca.c: Don't issue certs with subject DN that is NULL and have no
 	SANs
@@ -808,7 +916,7 @@
=20
 	* print.c: Print id-pkix-on-xmppAddr OtherName.
 =09
-2007-01-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* no random, no RSA/DH tests
=20
@@ -838,7 +946,7 @@
=20
 	* Makefile.am: add data/test-nopw.p12 to EXTRA_DIST
 =09
-2007-01-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* print.c: BasicConstraints vs criticality bit is complicated and
 	not really possible to evaluate on its own, silly RFC3280.
@@ -851,7 +959,7 @@
=20
 	* name.c (hx509_name_cmp): add
 =09
-2007-01-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_p11.c (collect_private_key): Missing CKA_MODULUS is ok
 	too (XXX why should these be fetched given they are not used).
@@ -867,11 +975,11 @@
 =20
 	* data/gen-req.sh: Generate a no password pkcs12 file.
 =09
-2007-01-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c: Check for internal ASN1 encoder error.
 =09
-2007-01-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: Drop most of the pkcs11 files.
=20
@@ -888,7 +996,7 @@
 	* ref: Replace with Marcus Brinkmann of g10 Code GmbH pkcs11
 	headerfile that is compatible with GPL (file taken from scute)
=20
-2007-01-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ca.in: Test to generate key and use them.
=20
@@ -914,7 +1022,7 @@
=20
 	* hxtool.c (pcert_verify): Fix format string.
=20
-2006-12-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c: Allow setting path length
=20
@@ -944,7 +1052,7 @@
=20
 	* name.c: Split building RDN to a separate function.
 =09
-2006-12-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: clean test_ca files.
=20
@@ -987,7 +1095,7 @@
=20
 	* ocsp.asn1: remove id-kp-OCSPSigning, its in rfc2459.asn1 now
 =09
-2006-12-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ca.c: Add KeyUsage extension.
=20
@@ -1008,21 +1116,21 @@
=20
 	* ca.c: Naive certificate signer.
 =09
-2006-12-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* hxtool.c: add hxtool_hex
 =09
-2006-12-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: use top_builddir for libasn1.la
 =09
-2006-12-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* hxtool.c (print_certificate): print serial number.
=20
 	* name.c (no): add S=3DstateOrProvinceName
 =09
-2006-12-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* crypto.c (_hx509_private_key_assign_rsa): set a default sig alg
=20
@@ -1030,7 +1138,7 @@
 	uses to do sigatures so there is no need to hardcode RSA into this
 	function.
 =09
-2006-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_file.c: Pass filename to the parse functions and use it in
 	the error messages
@@ -1050,7 +1158,7 @@
 	* cert.c: Clairfy and make proxy cert handling work for multiple
 	levels, before it was too restrictive. More helpful error message.
 =09
-2006-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* cert.c (check_key_usage): tell what keyusages are missing
=20
@@ -1061,7 +1169,7 @@
=20
 	* Makefile.am: CLEANFILES +=3D test
 =09
-2006-12-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am (EXTRA_DIST): add data/pkinit-proxy* files
=20
@@ -1094,7 +1202,7 @@
 	* test_cms.in: Tests for CMS SignedData with incomplete chain from
 	the signer.
 =09
-2006-11-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c (hx509_cms_verify_signed): specify what signature we
 	failed to verify
@@ -1116,7 +1224,7 @@
 	* crypto.c: use unsigned int as counter to fit better with the
 	asn1 compiler
 =09
-2006-11-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* cms.c: Remove trailing white space.
=20
@@ -1142,7 +1250,7 @@
 	* crypto.c (hx509_crypto_select): improve
 	(hx509_crypto_available): new function
 =09
-2006-11-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* cert.c: Sprinkle more error string and hx509_contexts.
=20
@@ -1168,17 +1276,17 @@
 =09
 	* cert.c: Handle that _hx509_verify_signature takes a context.
 =09
-2006-11-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c: Sprinkle error strings.
=20
 	* crypto.c: Sprinkle context and error strings.
 =09
-2006-11-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* name.c: Handle printing and parsing raw oids in name.
=20
-2006-11-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cert.c (_hx509_calculate_path): allow to calculate optimistic
 	path when we don't know the trust anchors, just follow the chain
@@ -1192,27 +1300,27 @@
=20
 	* data/gen-req.sh: Build pk-init proxy cert.
 =09
-2006-11-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* error.c (hx509_get_error_string): Put ", " between strings in
 	error message.
 =09
-2006-11-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* data/openssl.cnf: Change realm to TEST.H5L.SE
 =09
-2006-11-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* revoke.c: Sprinkle error strings.
 =09
-2006-11-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* hx_locl.h: add context variable to cmp function.
=20
 	* cert.c (hx509_query_match_cmp_func): allow setting the match
 	function.
 =09
-2006-10-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_p11.c: Return less EINVAL.
=20
@@ -1243,7 +1351,7 @@
 	* cert.c (hx509_cert_get_base_subject): one less EINVAL
 	(_hx509_cert_private_decrypt): one less EINVAL
 =09
-2006-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* collector.c: indent
=20
@@ -1255,7 +1363,7 @@
=20
 	* req.c: Try to not leak memory.
 =09
-2006-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_crypto.in: Read 50 kilobyte random data
 =09
@@ -1273,22 +1381,22 @@
=20
 	* cms.c: Try harder to free certificate.
 =09
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add make check data.
 =09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ks_p11.c (p11_list_keys): make element of search_data[0]
 	constants and set them later
=20
 	* Makefile.am: Add more files.
 =09
-2006-10-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ks_file.c: set ret, remember to free ivdata
 =09
-2006-10-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hx_locl.h: Include <parse_bytes.h>.
=20
@@ -1307,7 +1415,7 @@
=20
 	* ks_p11.c: Remember to release certs.
 =09
-2006-10-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* prefix der primitives with der_
=20
@@ -1315,7 +1423,7 @@
=20
 	* hx_locl.h: Drop heim_any.h
 =09
-2006-10-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ks_p11.c (p11_release_module): j needs to be used as inter loop
 	index. From Douglas Engert.
@@ -1323,12 +1431,12 @@
 	* ks_file.c (parse_rsa_private_key): try all passwords and
 	prompter.
 =09
-2006-10-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_*.in: Parameterise the invocation of hxtool, so we can make
 	it run under TESTS_ENVIRONMENT. From Andrew Bartlett
=20
-2006-10-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_crypto.in: Put all test stuck at 2006-09-25 since all their
 	chains where valied then.
@@ -1348,14 +1456,14 @@
 	keystore related error.  Patched based on code from Douglas
 	Engert.
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Make depenency for slc built files just like
 	everywhere else.
=20
 	* cert.c: Add all openssl algs and init asn1 et
 =09
-2006-10-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_file.c (parse_rsa_private_key): free type earlier.
=20
@@ -1363,18 +1471,18 @@
=20
 	* name.c (_hx509_Name_to_string): remove dup const
 =09
-2006-10-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: Add more libs to libhx509
 =09
-2006-10-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_p11.c: Fix double free's, NULL ptr de-reference, and conform
 	better to pkcs11.  From Douglas Engert.
=20
 	* ref: remove ^M, it breaks solaris 10s cc. From Harald Barth
=20
-2006-09-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_crypto.in: Bleichenbacher bad cert from Ralf-Philipp
 	Weinmann and Andrew Pyshkin, pad right.
@@ -1382,7 +1490,7 @@
 	* data: starfield test root cert and Ralf-Philipp and Andreis
 	correctly padded bad cert
=20
-2006-09-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_crypto.in: Add test for yutaka certs.
=20
@@ -1393,12 +1501,12 @@
=20
 	* hxtool.c: Improve printing and error reporting.
 =09
-2006-09-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_crypto.in,Makefile.am,data/bleichenbacher-{bad,good}.pem:
 	test bleichenbacher from eay
=20
-2006-09-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c: Make common function for all getarg_strings and
 	hx509_certs_append commonly used.
@@ -1406,7 +1514,7 @@
 	* cms.c: HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT is a negative
 	flag, treat it was such.
 =09
-2006-09-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* req.c: Use the new add_GeneralNames function.
=20
@@ -1419,14 +1527,14 @@
 	* cms.c: Allow passing in encryptedContent and flag.  Add new flag
 	HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT.
 =09
-2006-09-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ks_p11.c: cast void * to char * when using it for %s formating
 	in printf.
=20
 	* name.c: New function _hx509_Name_to_string.
 =09
-2006-09-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_file.c: Sprinkle error messages.
=20
@@ -1440,7 +1548,7 @@
 	* ks_p11.c: Don't build most of the pkcs11 module if there are no
 	dlopen().
 =09
-2006-09-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c (hx509_cms_unenvelope): try to save the error string from
 	find_CMSIdentifier so we have one more bit of information what
@@ -1455,7 +1563,7 @@
 	* ks_p11.c (p11_list_keys): fetch CKA_LABEL and use it to set the
 	friendlyname for the certificate.
 =09
-2006-09-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* crypto.c: check that there are no extra bytes in the checksum
 	and that the parameters are NULL or the NULL-type. All to avoid
@@ -1482,7 +1590,7 @@
=20
 	* ks_p11.c (p11_get_session): return better error messages
 =09
-2006-09-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ref: update to pkcs11 reference files 2.20
=20
@@ -1517,12 +1625,12 @@
 	* crypto.c: Start to hang the private key operations of the
 	private key, pass hx509_context to create_checksum.
 =09
-2006-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_p11.c: Iterate over all slots, not just the first/selected
 	one.
 =09
-2006-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cert.c: Add release function for certifiates so backend knowns
 	when its no longer used.
@@ -1532,11 +1640,11 @@
=20
 	* cms.c: sprinkle more hx509_clear_error_string
=20
-2006-05-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_p11.c: Sprinkle some hx509_set_error_strings
 =09
-2006-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* hxtool.c: Avoid shadowing.
=20
@@ -1546,7 +1654,7 @@
=20
 	* cert.c: Avoid shadowing.
 =09
-2006-05-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lock.c (hx509_prompt_hidden): reshuffle to avoid gcc warning
 =09
@@ -1557,7 +1665,7 @@
=20
 	* revoke.c (hx509_revoke_free): allow free of NULL.
 =09
-2006-05-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ks_file.c (file_init): Avoid shadowing ret (and thus avoiding
 	crashing).
@@ -1566,7 +1674,7 @@
=20
 	* ks_p11.c: Catch more errors.
 =09
-2006-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* crypto.c (hx509_crypto_encrypt): free correctly in error
 	path. From Andrew Bartlett.
@@ -1574,11 +1682,11 @@
 	* crypto.c: If RAND_bytes fails, then we will attempt to
 	double-free crypt->key.data.  From Andrew Bartlett.
 =09
-2006-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* name.c: Rename u_intXX_t to uintXX_t
 =09
-2006-05-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* TODO: More to do about the about the PKCS11 code.
=20
@@ -1589,7 +1697,7 @@
=20
 	* hx509.h: Make hx509_prompt.reply not a pointer.
 =09
-2006-05-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* keyset.c: Sprinkle setting error strings.
=20
@@ -1599,7 +1707,7 @@
=20
 	* cms.c: Sprinkle setting error strings.
 =09
-2006-05-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_name.c: renamed one error code
=20
@@ -1638,7 +1746,7 @@
=20
 	* keyset.c (hx509_certs_init): pass the right error code back
 =09
-2006-04-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* revoke.c: Revert previous patch.
 	(hx509_ocsp_verify): new function that returns the expiration of
@@ -1656,7 +1764,7 @@
=20
 	* cert.c: remove _hx509_cert_private_sigature
 =09
-2006-04-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* name.c: Expose more of Name.
=20
@@ -1670,7 +1778,7 @@
 	copy_octet_string
 	(hx509_cert_find_subjectAltName_otherName): make work
 =09
-2006-04-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* data/{pkinit,kdc}.{crt,key}: pkinit certificates
=20
@@ -1680,11 +1788,11 @@
=20
 	* cert.c (hx509_verify_hostname): implement stub function
 =09
-2006-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* TODO: CRL delta support
=20
-2006-04-26 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-04-26 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* data/.cvsignore: ignore leftover from OpenSSL cert generation
=20
@@ -1757,7 +1865,7 @@
=20
 	* cert.c: Initial support for proxy certificates.
 =09
-2006-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c: some error checking
=20
@@ -1765,7 +1873,7 @@
=20
 	* TODO: merge with old todo file
 =09
-2006-04-23 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-04-23 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* test_query.in: make quiet
=20
@@ -1779,7 +1887,7 @@
=20
 	* test_nist.in: SKIP test if there is no RSA support.
 =09
-2006-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool-commands.in: Allow passing in pool and anchor to
 	signedData
@@ -1814,7 +1922,7 @@
=20
 	* cert.c (hx509_query_match_friendly_name): New function.
 =09
-2006-04-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ks_p11.c: Add support for parsing slot-number.
=20
@@ -1861,7 +1969,7 @@
=20
 	* crypto.c: Handle rsa private keys better.
 =09
-2006-04-20  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-04-20  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* hxtool.c: Use hx509_cms_{,un}wrap_ContentInfo
=20
@@ -1875,14 +1983,14 @@
 =09
 	* crypto.c: Use the right length for the sha256 checksums.
 =09
-2006-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* crypto.c: Fix breakage from sha256 code.
=20
 	* crypto.c: Add SHA256 support, and symbols for the other new
 	SHA-2 types.
 =09
-2006-04-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_cms.in: test rc2-40 rc2-64 rc2-128 enveloped data
 =09
@@ -1893,13 +2001,13 @@
 	* crypto.c: Break out the parameter handling code for encrypting
 	data to handle RC2.  Needed for Windows 2k pk-init support.
 =09
-2006-04-04  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-04-04  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* Makefile.am: Split libhx509_la_SOURCES into build file and
 	distributed files so we can avoid building prototypes for
 	build-files.
 =09
-2006-04-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* TODO: split certificate request into pkcs10 and CRMF
=20
@@ -1951,7 +2059,7 @@
 	* crypto.c: Add _hx509_private_key2SPKI and support
 	functions (only support RSA for now).
 =09
-2006-04-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* hxtool-commands.in: Add pkcs10-create command.
=20
@@ -1968,7 +2076,7 @@
=20
 	* name.c (hx509_name_copy): new function.
 =09
-2006-04-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* TODO: fill out what do
=20
@@ -2049,7 +2157,7 @@
 	* cert.c: Add ocsp glue, use new
 	_hx509_verify_signature_bitstring, add eku checking function.
 =09
-2006-03-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add id_kp_OCSPSigning.x
=20
@@ -2076,17 +2184,17 @@
 	* hx_locl.h: rename HX509_CTX_CRL_MISSING_OK to
 	HX509_CTX_VERIFY_MISSING_OK now that we have OCSP glue
 =09
-2006-03-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hx_locl.h: Add <krb5-types.h> to make it compile on Solaris,
 	from Alex V. Labuta.
 =09
-2006-03-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* crypto.c (_hx509_pbe_decrypt): try all passwords, not just the
 	first one.
 =09
-2006-03-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* print.c (check_altName): Print the othername oid.
=20
@@ -2110,7 +2218,7 @@
=20
 	* cms.c: Check for signature error, check consitency of error
 =09
-2006-03-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-03-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* collector.c (_hx509_collector_alloc): handle errors
=20
@@ -2138,7 +2246,7 @@
=20
 	* hx509.h: Add hx509_query.
 =09
-2006-02-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cert.c: Add exceptions for null (empty) subjectNames
=20
@@ -2157,17 +2265,17 @@
 	If the name restrictions are merged to a list, the certificate
 	will pass this test.
=20
-2006-02-14 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-02-14 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* cert.c: Handle more name constraints cases.
=20
 	* crypto.c (dsa_verify_signature): if test if malloc failed
=20
-2006-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c: Drop partial pkcs12 string2key implementation.
 =09
-2006-01-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* data/nist-data: Add commited out DSA tests (they fail).
=20
@@ -2191,7 +2299,7 @@
=20
 	* test_nist_cert.in: test parse all nist certs
 =09
-2006-01-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hx509_err.et: Add HX509_CRL_UNKNOWN_EXTENSION.
=20
@@ -2228,7 +2336,7 @@
=20
 	* test_cms.in: Use static file, add --missing-crl.
 =09
-2006-01-18  Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-01-18  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* print.c: Its cRLReason, not cRLReasons.
=20
@@ -2246,17 +2354,17 @@
=20
 	* hx509.h: Add hx509_revoke_ctx.
 =09
-2006-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* delete crypto_headers.h, use global file instead.
=20
 	* crypto.c (PBE_string2key): libdes now supports PKCS12_key_gen
 =09
-2006-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* crypto_headers.h: Need BN_is_negative too.
 =09
-2006-01-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ks_p11.c (p11_rsa_public_decrypt): since is wrong, don't provide
 	it. PKCS11 can't do public_decrypt, it support verify though. All
@@ -2265,7 +2373,7 @@
 	* crypto_headers.h: Provide glue to compile with less warnings
 	with OpenSSL
 =09
-2006-01-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: Depend on LIB_des
=20
@@ -2282,7 +2390,7 @@
 	and use "crypto-headers.h".
 =09
=20
-2006-01-04 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-01-04 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
 =09
 	* add a hx509_context where we can store configuration
=20
@@ -2337,7 +2445,7 @@
 	* hxtool.c (print_f): print if there is a friendly name and if
 	there is a private key
 =09
-2006-01-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* name.c: Avoid warning from missing __attribute__((noreturn))
=20
@@ -2380,7 +2488,7 @@
=20
 	* name.c: use _hx509_abort
 =09
-2006-01-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* name.c (hx509_name_to_string): don't cut bmpString in half.
=20
@@ -2404,7 +2512,7 @@
 	* ks_dir.c: Add new keystore that treats all files in a directory
 	a keystore, useful for regression tests.
 =09
-2005-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_nist_pkcs12.in: Test parse PKCS12 files from NIST.
=20
@@ -2412,16 +2520,16 @@
 =09
 	* hxtool.c: Print error code on failure.
 =09
-2005-10-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* crypto.c: Support DSA signature operations.
 =09
-2005-10-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* print.c: Validate that issuerAltName and subjectAltName isn't
 	empty.
 =09
-2005-09-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* p11.c: Cast to unsigned char to avoid warning.
=20
@@ -2431,7 +2539,7 @@
 =09
 	* ks_p11.c: Starting point of a pkcs11 module.
 =09
-2005-09-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* lock.c: Implement prompter.
=20
@@ -2447,7 +2555,7 @@
 	* name.c: Add DC, handle all Directory strings, fix signless
 	problems.
 =09
-2005-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_query.in: Pass in --pass to all commands.
=20
@@ -2473,11 +2581,11 @@
=20
 	* test_query.in: Use echo, the function check isn't defined here.
 =09
-2005-08-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool-commands.in: Add more options that was missing.
=20
-2005-07-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_cms.in: Use --certificate=3D for enveloped/unenvelope.
=20
@@ -2498,7 +2606,7 @@
 =09
 	* crypto.c: add "new" RC2 oid
 =09
-2005-07-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hx_locl.h, cert.c: Add HX509_QUERY_MATCH_FUNCTION that allows
 	caller to match by function, note that this doesn't not work
@@ -2571,7 +2679,7 @@
 =09
 	* hxtool.c,Makefile.am,hxtool-commands.in: switch to slc
=20
-2005-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cert.c (hx509_verify_destroy_ctx): add
 =09
@@ -2579,7 +2687,7 @@
 =09
 	* name.c (_hx509_name_ds_cmp): make sure all strings are not equal
=20
-2005-07-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hxtool.c: return error
 =09
@@ -2618,7 +2726,7 @@
=20
 	* cert.c: more checks on KeyUsage, allow to query on them too
=20
-2005-07-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* cms.c: Add missing break.
 =09
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/Makefile=
.am
--- a/head/crypto/heimdal/lib/hx509/Makefile.am	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hx509/Makefile.am	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,11 +1,10 @@
-# $Id: Makefile.am 22459 2008-01-15 21:46:20Z lha $
-
 include $(top_srcdir)/Makefile.am.common
=20
 lib_LTLIBRARIES =3D libhx509.la
-libhx509_la_LDFLAGS =3D -version-info 3:0:0
+libhx509_la_LDFLAGS =3D -version-info 5:0:0
=20
 BUILT_SOURCES =3D				\
+	sel-gram.h			\
 	$(gen_files_ocsp:.x=3D.c)		\
 	$(gen_files_pkcs10:.x=3D.c)	\
 	hx509_err.c			\
@@ -50,9 +49,12 @@
 	asn1_ProofOfPossession.x	\
 	asn1_SubsequentMessage.x=09
=20
+AM_YFLAGS =3D -d
+
 dist_libhx509_la_SOURCES =3D \
 	ca.c \
 	cert.c \
+	char_map.h \
 	cms.c \
 	collector.c \
 	crypto.c \
@@ -64,6 +66,10 @@
 	hx509-protos.h \
 	hx509.h \
 	hx_locl.h \
+	sel.c \
+	sel.h \
+	sel-gram.y \
+	sel-lex.l \
 	keyset.c \
 	ks_dir.c \
 	ks_file.c \
@@ -81,10 +87,15 @@
 	req.c \
 	revoke.c
=20
+sel-lex.c: sel-gram.h
+
+libhx509_la_DEPENDENCIES =3D version-script.map
+
 libhx509_la_LIBADD =3D \
 	$(LIB_com_err) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la \
 	$(LIBADD_roken) \
 	$(LIB_dlopen)
=20
@@ -95,39 +106,45 @@
 if versionscript
 libhx509_la_LDFLAGS +=3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script=
.map
 endif
-$(libhx509_la_OBJECTS): $(srcdir)/version-script.map
+$(libhx509_la_OBJECTS): $(srcdir)/version-script.map $(nodist_include_HEAD=
ERS) $(priv_headers)
=20
 libhx509_la_CPPFLAGS =3D -I$(srcdir)/ref $(INCLUDE_hcrypto)
 nodist_libhx509_la_SOURCES =3D $(BUILT_SOURCES)
=20
-$(gen_files_ocsp) ocsp_asn1.h: ocsp_asn1_files
-$(gen_files_pkcs10) pkcs10_asn1.h: pkcs10_asn1_files
-$(gen_files_crmf) crmf_asn1.h: crmf_asn1_files
+$(gen_files_ocsp) ocsp_asn1.hx ocsp_asn1-priv.hx: ocsp_asn1_files
+$(gen_files_pkcs10) pkcs10_asn1.hx pkcs10_asn1-priv.hx: pkcs10_asn1_files
+$(gen_files_crmf) crmf_asn1.hx crmf_asn1-priv.hx: crmf_asn1_files
=20
-asn1_compile =3D ../asn1/asn1_compile$(EXEEXT)
+dist_include_HEADERS =3D hx509.h hx509-protos.h
=20
-ocsp_asn1_files: $(asn1_compile) $(srcdir)/ocsp.asn1
-	$(asn1_compile) --preserve-binary=3DOCSPTBSRequest --preserve-binary=3DOC=
SPResponseData $(srcdir)/ocsp.asn1 ocsp_asn1 || (rm -f ocsp_asn1_files ; ex=
it 1)
+nodist_include_HEADERS =3D hx509_err.h
+nodist_include_HEADERS +=3D ocsp_asn1.h
+nodist_include_HEADERS +=3D pkcs10_asn1.h
+nodist_include_HEADERS +=3D crmf_asn1.h
=20
-pkcs10_asn1_files: $(asn1_compile) $(srcdir)/pkcs10.asn1
-	$(asn1_compile) --preserve-binary=3DCertificationRequestInfo $(srcdir)/pk=
cs10.asn1 pkcs10_asn1 || (rm -f pkcs10_asn1_files ; exit 1)
+priv_headers  =3D ocsp_asn1-priv.h
+priv_headers +=3D pkcs10_asn1-priv.h
+priv_headers +=3D crmf_asn1-priv.h
=20
-crmf_asn1_files: $(asn1_compile) $(srcdir)/crmf.asn1
-	$(asn1_compile) $(srcdir)/crmf.asn1 crmf_asn1 || (rm -f crmf_asn1_files ;=
 exit 1)
=20
-$(libhx509_la_OBJECTS): $(srcdir)/hx509-protos.h $(srcdir)/hx509-private.h
+ocsp_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/ocsp.asn1 $(srcdir)/ocsp.opt
+	$(ASN1_COMPILE) --option-file=3D$(srcdir)/ocsp.opt $(srcdir)/ocsp.asn1 oc=
sp_asn1 || (rm -f ocsp_asn1_files ; exit 1)
+
+pkcs10_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/pkcs10.asn1 $(srcdir)/pkc=
s10.opt
+	$(ASN1_COMPILE) --option-file=3D$(srcdir)/pkcs10.opt $(srcdir)/pkcs10.asn=
1 pkcs10_asn1 || (rm -f pkcs10_asn1_files ; exit 1)
+
+crmf_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/crmf.asn1
+	$(ASN1_COMPILE) $(srcdir)/crmf.asn1 crmf_asn1 || (rm -f crmf_asn1_files ;=
 exit 1)
+
+$(libhx509_la_OBJECTS): $(srcdir)/hx509-protos.h $(srcdir)/hx509-private.h=
 $(srcdir)/hx_locl.h
+$(libhx509_la_OBJECTS): ocsp_asn1.h pkcs10_asn1.h
=20
 $(srcdir)/hx509-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -R '^(_|^C)' -E HX509_LIB_FUN=
CTION -q -P comment -o hx509-protos.h $(dist_libhx509_la_SOURCES) || rm -f =
hx509-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -R '^(_|^C)' -E HX509_LIB -q =
-P comment -o hx509-protos.h $(dist_libhx509_la_SOURCES) || rm -f hx509-pro=
tos.h
=20
 $(srcdir)/hx509-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p hx509-privat=
e.h $(dist_libhx509_la_SOURCES) || rm -f hx509-private.h
=20
-dist_include_HEADERS =3D hx509.h hx509-protos.h
-nodist_include_HEADERS =3D hx509_err.h
-
-SLC =3D $(top_builddir)/lib/sl/slc
-
 bin_PROGRAMS =3D hxtool
=20
 hxtool-commands.c hxtool-commands.h: hxtool-commands.in $(SLC)
@@ -146,14 +163,18 @@
 	$(LIB_roken) \
 	$(top_builddir)/lib/sl/libsl.la
=20
-CLEANFILES =3D $(BUILT_SOURCES) \
-	$(gen_files_ocsp) ocsp_asn1_files ocsp_asn1.h \
-	$(gen_files_pkcs10) pkcs10_asn1_files pkcs10_asn1.h \
-	$(gen_files_crmf) crmf_asn1_files crmf_asn1.h \
+CLEANFILES =3D $(BUILT_SOURCES) sel-gram.c sel-lex.c \
+	$(gen_files_ocsp) ocsp_asn1_files ocsp_asn1{,-priv}.h* \
+	ocsp_asn1-template.[ch]* \
+	$(gen_files_pkcs10) pkcs10_asn1_files pkcs10_asn1{,-priv}.h* \
+	pkcs10_asn1-template.[ch]* \
+	$(gen_files_crmf) crmf_asn1_files crmf_asn1{,-priv}.h* \
+	crmf_asn1-template.[ch]* \
 	$(TESTS) \
 	hxtool-commands.c hxtool-commands.h *.tmp \
 	request.out \
 	out.pem out2.pem \
+	sd sd.pem \
 	sd.data sd.data.out \
 	ev.data ev.data.out \
 	cert-null.pem cert-sub-ca2.pem \
@@ -180,10 +201,14 @@
 test_soft_pkcs11_LDADD =3D libhx509.la
 test_soft_pkcs11_CPPFLAGS =3D -I$(srcdir)/ref
=20
+test_name_CPPFLAGS =3D $(INCLUDE_hcrypto)
+test_name_LDADD =3D libhx509.la $(LIB_roken)
+
 TESTS =3D $(SCRIPT_TESTS) $(PROGRAM_TESTS)
=20
 PROGRAM_TESTS =3D 		\
-	test_name
+	test_name		\
+	test_expr
=20
 SCRIPT_TESTS =3D 			\
 	test_ca			\
@@ -202,7 +227,8 @@
 	test_query
=20
 do_subst =3D sed -e 's,[@]srcdir[@],$(srcdir),g' \
-	-e 's,[@]objdir[@],$(top_builddir)/lib/hx509,g'
+	-e 's,[@]objdir[@],$(top_builddir)/lib/hx509,g' \
+	-e 's,[@]egrep[@],$(EGREP),g'
=20
 test_ca: test_ca.in Makefile
 	$(do_subst) < $(srcdir)/test_ca.in > test_ca.tmp
@@ -275,13 +301,18 @@
 	mv test_query.tmp test_query
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	hxtool-version.rc \
+	libhx509-exports.def \
 	version-script.map \
 	crmf.asn1 \
-	data/bleichenbacher-bad.pem \
 	hx509_err.et \
 	hxtool-commands.in \
+	quote.py \
 	ocsp.asn1 \
+	ocsp.opt \
 	pkcs10.asn1 \
+	pkcs10.opt \
 	test_ca.in \
 	test_chain.in \
 	test_cert.in \
@@ -307,6 +338,17 @@
 	tst-crypto-select5 \
 	tst-crypto-select6 \
 	tst-crypto-select7 \
+	data/n0ll.pem \
+	data/secp160r1TestCA.cert.pem \
+	data/secp160r1TestCA.key.pem \
+	data/secp160r1TestCA.pem \
+	data/secp160r2TestClient.cert.pem \
+	data/secp160r2TestClient.key.pem \
+	data/secp160r2TestClient.pem \
+	data/secp160r2TestServer.cert.pem \
+	data/secp160r2TestServer.key.pem \
+	data/secp160r2TestServer.pem \
+	data/bleichenbacher-bad.pem \
 	data/bleichenbacher-good.pem \
 	data/bleichenbacher-sf-pad-correct.pem \
 	data/ca.crt \
@@ -342,6 +384,8 @@
 	data/pkinit-pw.key \
 	data/pkinit.crt \
 	data/pkinit.key \
+	data/pkinit-ec.crt \
+	data/pkinit-ec.key \
 	data/proxy-level-test.crt \
 	data/proxy-level-test.key \
 	data/proxy-test.crt \
@@ -377,10 +421,14 @@
 	data/test-signed-data \
 	data/test-signed-data-noattr \
 	data/test-signed-data-noattr-nocerts \
+	data/test-signed-sha-1 \
+	data/test-signed-sha-256 \
+	data/test-signed-sha-512 \
 	data/test.combined.crt \
 	data/test.crt \
 	data/test.key \
 	data/test.p12 \
+	data/win-u16-in-printablestring.der \
 	data/yutaka-pad-broken-ca.pem \
 	data/yutaka-pad-broken-cert.pem \
 	data/yutaka-pad-ok-ca.pem \
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/Makefile=
.in
--- a/head/crypto/heimdal/lib/hx509/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hx509/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22459 2008-01-15 21:46:20Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
-
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -42,7 +42,8 @@
 host_triplet =3D @host@
 DIST_COMMON =3D $(dist_include_HEADERS) $(srcdir)/Makefile.am \
 	$(srcdir)/Makefile.in $(top_srcdir)/Makefile.am.common \
-	$(top_srcdir)/cf/Makefile.am.common ChangeLog TODO
+	$(top_srcdir)/cf/Makefile.am.common ChangeLog TODO sel-gram.c \
+	sel-gram.h sel-lex.c
 @FRAMEWORK_SECURITY_TRUE at am__append_1 =3D -framework Security -framework C=
oreFoundation
 @versionscript_TRUE at am__append_2 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
 bin_PROGRAMS =3D hxtool$(EXEEXT)
@@ -51,7 +52,7 @@
 subdir =3D lib/hx509
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -66,7 +67,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -80,9 +81,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -90,36 +94,50 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \
 	"$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
 am__DEPENDENCIES_1 =3D
-libhx509_la_DEPENDENCIES =3D $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
 dist_libhx509_la_OBJECTS =3D libhx509_la-ca.lo libhx509_la-cert.lo \
 	libhx509_la-cms.lo libhx509_la-collector.lo \
 	libhx509_la-crypto.lo libhx509_la-doxygen.lo \
 	libhx509_la-error.lo libhx509_la-env.lo libhx509_la-file.lo \
-	libhx509_la-keyset.lo libhx509_la-ks_dir.lo \
-	libhx509_la-ks_file.lo libhx509_la-ks_mem.lo \
-	libhx509_la-ks_null.lo libhx509_la-ks_p11.lo \
-	libhx509_la-ks_p12.lo libhx509_la-ks_keychain.lo \
-	libhx509_la-lock.lo libhx509_la-name.lo libhx509_la-peer.lo \
-	libhx509_la-print.lo libhx509_la-softp11.lo libhx509_la-req.lo \
+	libhx509_la-sel.lo libhx509_la-sel-gram.lo \
+	libhx509_la-sel-lex.lo libhx509_la-keyset.lo \
+	libhx509_la-ks_dir.lo libhx509_la-ks_file.lo \
+	libhx509_la-ks_mem.lo libhx509_la-ks_null.lo \
+	libhx509_la-ks_p11.lo libhx509_la-ks_p12.lo \
+	libhx509_la-ks_keychain.lo libhx509_la-lock.lo \
+	libhx509_la-name.lo libhx509_la-peer.lo libhx509_la-print.lo \
+	libhx509_la-softp11.lo libhx509_la-req.lo \
 	libhx509_la-revoke.lo
 am__objects_1 =3D libhx509_la-asn1_OCSPBasicOCSPResponse.lo \
 	libhx509_la-asn1_OCSPCertID.lo \
@@ -149,8 +167,7 @@
 libhx509_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libhx509_la_LDFLAGS) $(LDFLAGS) -o $@
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-am__EXEEXT_1 =3D test_name$(EXEEXT)
+am__EXEEXT_1 =3D test_name$(EXEEXT) test_expr$(EXEEXT)
 PROGRAMS =3D $(bin_PROGRAMS)
 dist_hxtool_OBJECTS =3D hxtool-hxtool.$(OBJEXT)
 nodist_hxtool_OBJECTS =3D hxtool-hxtool-commands.$(OBJEXT)
@@ -158,17 +175,20 @@
 hxtool_DEPENDENCIES =3D libhx509.la $(top_builddir)/lib/asn1/libasn1.la \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
 	$(top_builddir)/lib/sl/libsl.la
+test_expr_SOURCES =3D test_expr.c
+test_expr_OBJECTS =3D test_expr.$(OBJEXT)
+test_expr_LDADD =3D $(LDADD)
+test_expr_DEPENDENCIES =3D libhx509.la
 test_name_SOURCES =3D test_name.c
-test_name_OBJECTS =3D test_name.$(OBJEXT)
-test_name_LDADD =3D $(LDADD)
-test_name_DEPENDENCIES =3D libhx509.la
+test_name_OBJECTS =3D test_name-test_name.$(OBJEXT)
+test_name_DEPENDENCIES =3D libhx509.la $(am__DEPENDENCIES_1)
 test_soft_pkcs11_SOURCES =3D test_soft_pkcs11.c
 test_soft_pkcs11_OBJECTS =3D  \
 	test_soft_pkcs11-test_soft_pkcs11.$(OBJEXT)
 test_soft_pkcs11_DEPENDENCIES =3D libhx509.la
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -178,64 +198,82 @@
 LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
+ at MAINTAINER_MODE_FALSE@am__skiplex =3D test -f $@ ||
+LEXCOMPILE =3D $(LEX) $(LFLAGS) $(AM_LFLAGS)
+LTLEXCOMPILE =3D $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
+	--mode=3Dcompile $(LEX) $(LFLAGS) $(AM_LFLAGS)
+YLWRAP =3D $(top_srcdir)/ylwrap
+ at MAINTAINER_MODE_FALSE@am__skipyacc =3D test -f $@ ||
+YACCCOMPILE =3D $(YACC) $(YFLAGS) $(AM_YFLAGS)
+LTYACCCOMPILE =3D $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
+	--mode=3Dcompile $(YACC) $(YFLAGS) $(AM_YFLAGS)
 SOURCES =3D $(dist_libhx509_la_SOURCES) $(nodist_libhx509_la_SOURCES) \
-	$(dist_hxtool_SOURCES) $(nodist_hxtool_SOURCES) test_name.c \
-	test_soft_pkcs11.c
+	$(dist_hxtool_SOURCES) $(nodist_hxtool_SOURCES) test_expr.c \
+	test_name.c test_soft_pkcs11.c
 DIST_SOURCES =3D $(dist_libhx509_la_SOURCES) $(dist_hxtool_SOURCES) \
-	test_name.c test_soft_pkcs11.c
-dist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-nodist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
+	test_expr.c test_name.c test_soft_pkcs11.c
 HEADERS =3D $(dist_include_HEADERS) $(nodist_include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -259,10 +297,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -279,6 +318,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -294,31 +335,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -333,10 +388,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -377,34 +434,40 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 lib_LTLIBRARIES =3D libhx509.la
-libhx509_la_LDFLAGS =3D -version-info 3:0:0 $(am__append_1) \
+libhx509_la_LDFLAGS =3D -version-info 5:0:0 $(am__append_1) \
 	$(am__append_2)
 BUILT_SOURCES =3D \
+	sel-gram.h			\
 	$(gen_files_ocsp:.x=3D.c)		\
 	$(gen_files_pkcs10:.x=3D.c)	\
 	hx509_err.c			\
@@ -449,9 +512,11 @@
 	asn1_ProofOfPossession.x	\
 	asn1_SubsequentMessage.x=09
=20
+AM_YFLAGS =3D -d
 dist_libhx509_la_SOURCES =3D \
 	ca.c \
 	cert.c \
+	char_map.h \
 	cms.c \
 	collector.c \
 	crypto.c \
@@ -463,6 +528,10 @@
 	hx509-protos.h \
 	hx509.h \
 	hx_locl.h \
+	sel.c \
+	sel.h \
+	sel-gram.y \
+	sel-lex.l \
 	keyset.c \
 	ks_dir.c \
 	ks_file.c \
@@ -480,19 +549,21 @@
 	req.c \
 	revoke.c
=20
+libhx509_la_DEPENDENCIES =3D version-script.map
 libhx509_la_LIBADD =3D \
 	$(LIB_com_err) \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la \
 	$(LIBADD_roken) \
 	$(LIB_dlopen)
=20
 libhx509_la_CPPFLAGS =3D -I$(srcdir)/ref $(INCLUDE_hcrypto)
 nodist_libhx509_la_SOURCES =3D $(BUILT_SOURCES)
-asn1_compile =3D ../asn1/asn1_compile$(EXEEXT)
 dist_include_HEADERS =3D hx509.h hx509-protos.h
-nodist_include_HEADERS =3D hx509_err.h
-SLC =3D $(top_builddir)/lib/sl/slc
+nodist_include_HEADERS =3D hx509_err.h ocsp_asn1.h pkcs10_asn1.h \
+	crmf_asn1.h
+priv_headers =3D ocsp_asn1-priv.h pkcs10_asn1-priv.h crmf_asn1-priv.h
 dist_hxtool_SOURCES =3D hxtool.c
 nodist_hxtool_SOURCES =3D hxtool-commands.c hxtool-commands.h
 hxtool_CPPFLAGS =3D $(INCLUDE_hcrypto)
@@ -503,14 +574,18 @@
 	$(LIB_roken) \
 	$(top_builddir)/lib/sl/libsl.la
=20
-CLEANFILES =3D $(BUILT_SOURCES) \
-	$(gen_files_ocsp) ocsp_asn1_files ocsp_asn1.h \
-	$(gen_files_pkcs10) pkcs10_asn1_files pkcs10_asn1.h \
-	$(gen_files_crmf) crmf_asn1_files crmf_asn1.h \
+CLEANFILES =3D $(BUILT_SOURCES) sel-gram.c sel-lex.c \
+	$(gen_files_ocsp) ocsp_asn1_files ocsp_asn1{,-priv}.h* \
+	ocsp_asn1-template.[ch]* \
+	$(gen_files_pkcs10) pkcs10_asn1_files pkcs10_asn1{,-priv}.h* \
+	pkcs10_asn1-template.[ch]* \
+	$(gen_files_crmf) crmf_asn1_files crmf_asn1{,-priv}.h* \
+	crmf_asn1-template.[ch]* \
 	$(TESTS) \
 	hxtool-commands.c hxtool-commands.h *.tmp \
 	request.out \
 	out.pem out2.pem \
+	sd sd.pem \
 	sd.data sd.data.out \
 	ev.data ev.data.out \
 	cert-null.pem cert-sub-ca2.pem \
@@ -530,8 +605,11 @@
 LDADD =3D libhx509.la
 test_soft_pkcs11_LDADD =3D libhx509.la
 test_soft_pkcs11_CPPFLAGS =3D -I$(srcdir)/ref
+test_name_CPPFLAGS =3D $(INCLUDE_hcrypto)
+test_name_LDADD =3D libhx509.la $(LIB_roken)
 PROGRAM_TESTS =3D \
-	test_name
+	test_name		\
+	test_expr
=20
 SCRIPT_TESTS =3D \
 	test_ca			\
@@ -550,16 +628,22 @@
 	test_query
=20
 do_subst =3D sed -e 's,[@]srcdir[@],$(srcdir),g' \
-	-e 's,[@]objdir[@],$(top_builddir)/lib/hx509,g'
+	-e 's,[@]objdir[@],$(top_builddir)/lib/hx509,g' \
+	-e 's,[@]egrep[@],$(EGREP),g'
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	hxtool-version.rc \
+	libhx509-exports.def \
 	version-script.map \
 	crmf.asn1 \
-	data/bleichenbacher-bad.pem \
 	hx509_err.et \
 	hxtool-commands.in \
+	quote.py \
 	ocsp.asn1 \
+	ocsp.opt \
 	pkcs10.asn1 \
+	pkcs10.opt \
 	test_ca.in \
 	test_chain.in \
 	test_cert.in \
@@ -585,6 +669,17 @@
 	tst-crypto-select5 \
 	tst-crypto-select6 \
 	tst-crypto-select7 \
+	data/n0ll.pem \
+	data/secp160r1TestCA.cert.pem \
+	data/secp160r1TestCA.key.pem \
+	data/secp160r1TestCA.pem \
+	data/secp160r2TestClient.cert.pem \
+	data/secp160r2TestClient.key.pem \
+	data/secp160r2TestClient.pem \
+	data/secp160r2TestServer.cert.pem \
+	data/secp160r2TestServer.key.pem \
+	data/secp160r2TestServer.pem \
+	data/bleichenbacher-bad.pem \
 	data/bleichenbacher-good.pem \
 	data/bleichenbacher-sf-pad-correct.pem \
 	data/ca.crt \
@@ -620,6 +715,8 @@
 	data/pkinit-pw.key \
 	data/pkinit.crt \
 	data/pkinit.key \
+	data/pkinit-ec.crt \
+	data/pkinit-ec.key \
 	data/proxy-level-test.crt \
 	data/proxy-level-test.key \
 	data/proxy-test.crt \
@@ -655,10 +752,14 @@
 	data/test-signed-data \
 	data/test-signed-data-noattr \
 	data/test-signed-data-noattr-nocerts \
+	data/test-signed-sha-1 \
+	data/test-signed-sha-256 \
+	data/test-signed-sha-512 \
 	data/test.combined.crt \
 	data/test.crt \
 	data/test.key \
 	data/test.p12 \
+	data/win-u16-in-printablestring.der \
 	data/yutaka-pad-broken-ca.pem \
 	data/yutaka-pad-broken-cert.pem \
 	data/yutaka-pad-ok-ca.pem \
@@ -669,19 +770,19 @@
 	$(MAKE) $(AM_MAKEFLAGS) all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .l .lo =
.o .obj .y
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/hx509=
/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/hx509/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/hx509/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/hx509/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -699,23 +800,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -726,46 +832,71 @@
 	  echo "rm -f \"$${dir}/so_locations\""; \
 	  rm -f "$${dir}/so_locations"; \
 	done
+sel-gram.h: sel-gram.c
+	@if test ! -f $@; then \
+	  rm -f sel-gram.c; \
+	  $(MAKE) $(AM_MAKEFLAGS) sel-gram.c; \
+	else :; fi
 libhx509.la: $(libhx509_la_OBJECTS) $(libhx509_la_DEPENDENCIES)=20
 	$(libhx509_la_LINK) -rpath $(libdir) $(libhx509_la_OBJECTS) $(libhx509_la=
_LIBADD) $(LIBS)
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 hxtool$(EXEEXT): $(hxtool_OBJECTS) $(hxtool_DEPENDENCIES)=20
 	@rm -f hxtool$(EXEEXT)
 	$(LINK) $(hxtool_OBJECTS) $(hxtool_LDADD) $(LIBS)
+test_expr$(EXEEXT): $(test_expr_OBJECTS) $(test_expr_DEPENDENCIES)=20
+	@rm -f test_expr$(EXEEXT)
+	$(LINK) $(test_expr_OBJECTS) $(test_expr_LDADD) $(LIBS)
 test_name$(EXEEXT): $(test_name_OBJECTS) $(test_name_DEPENDENCIES)=20
 	@rm -f test_name$(EXEEXT)
 	$(LINK) $(test_name_OBJECTS) $(test_name_LDADD) $(LIBS)
@@ -779,167 +910,478 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hxtool-hxtool-commands.Po=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hxtool-hxtool.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_Certific=
ationRequest.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_Certific=
ationRequestInfo.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPBasi=
cOCSPResponse.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPCert=
ID.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPCert=
Status.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPInne=
rRequest.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPKeyH=
ash.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPRequ=
est.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPResp=
onderID.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPResp=
onse.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPResp=
onseBytes.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPResp=
onseData.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPResp=
onseStatus.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPSign=
ature.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPSing=
leResponse.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPTBSR=
equest.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_OCSPVers=
ion.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_id_pkix_=
ocsp.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_id_pkix_=
ocsp_basic.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-asn1_id_pkix_=
ocsp_nonce.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ca.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-cert.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-cms.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-collector.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-crypto.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-doxygen.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-env.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-error.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-file.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-hx509_err.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-keyset.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ks_dir.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ks_file.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ks_keychain.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ks_mem.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ks_null.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ks_p11.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-ks_p12.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-lock.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-name.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-peer.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-print.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-req.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-revoke.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-sel-gram.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-sel-lex.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-sel.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libhx509_la-softp11.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_expr.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_name-test_name.Po at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_soft_pkcs11-test_sof=
t_pkcs11.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 libhx509_la-ca.lo: ca.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ca.lo `test -f 'ca.c' || e=
cho '$(srcdir)/'`ca.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ca.lo -=
MD -MP -MF $(DEPDIR)/libhx509_la-ca.Tpo -c -o libhx509_la-ca.lo `test -f 'c=
a.c' || echo '$(srcdir)/'`ca.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ca.Tpo $(DEPDIR)/libh=
x509_la-ca.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ca.c' object=3D'libhx509_la-ca=
.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ca.l=
o `test -f 'ca.c' || echo '$(srcdir)/'`ca.c
=20
 libhx509_la-cert.lo: cert.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-cert.lo `test -f 'cert.c' =
|| echo '$(srcdir)/'`cert.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-cert.lo=
 -MD -MP -MF $(DEPDIR)/libhx509_la-cert.Tpo -c -o libhx509_la-cert.lo `test=
 -f 'cert.c' || echo '$(srcdir)/'`cert.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-cert.Tpo $(DEPDIR)/li=
bhx509_la-cert.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'cert.c' object=3D'libhx509_la-=
cert.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-cert=
.lo `test -f 'cert.c' || echo '$(srcdir)/'`cert.c
=20
 libhx509_la-cms.lo: cms.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-cms.lo `test -f 'cms.c' ||=
 echo '$(srcdir)/'`cms.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-cms.lo =
-MD -MP -MF $(DEPDIR)/libhx509_la-cms.Tpo -c -o libhx509_la-cms.lo `test -f=
 'cms.c' || echo '$(srcdir)/'`cms.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-cms.Tpo $(DEPDIR)/lib=
hx509_la-cms.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'cms.c' object=3D'libhx509_la-c=
ms.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-cms.=
lo `test -f 'cms.c' || echo '$(srcdir)/'`cms.c
=20
 libhx509_la-collector.lo: collector.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-collector.lo `test -f 'col=
lector.c' || echo '$(srcdir)/'`collector.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-collect=
or.lo -MD -MP -MF $(DEPDIR)/libhx509_la-collector.Tpo -c -o libhx509_la-col=
lector.lo `test -f 'collector.c' || echo '$(srcdir)/'`collector.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-collector.Tpo $(DEPDI=
R)/libhx509_la-collector.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'collector.c' object=3D'libhx50=
9_la-collector.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-coll=
ector.lo `test -f 'collector.c' || echo '$(srcdir)/'`collector.c
=20
 libhx509_la-crypto.lo: crypto.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-crypto.lo `test -f 'crypto=
.c' || echo '$(srcdir)/'`crypto.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-crypto.=
lo -MD -MP -MF $(DEPDIR)/libhx509_la-crypto.Tpo -c -o libhx509_la-crypto.lo=
 `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-crypto.Tpo $(DEPDIR)/=
libhx509_la-crypto.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto.c' object=3D'libhx509_l=
a-crypto.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-cryp=
to.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c
=20
 libhx509_la-doxygen.lo: doxygen.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-doxygen.lo `test -f 'doxyg=
en.c' || echo '$(srcdir)/'`doxygen.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-doxygen=
.lo -MD -MP -MF $(DEPDIR)/libhx509_la-doxygen.Tpo -c -o libhx509_la-doxygen=
.lo `test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-doxygen.Tpo $(DEPDIR)=
/libhx509_la-doxygen.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'doxygen.c' object=3D'libhx509_=
la-doxygen.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-doxy=
gen.lo `test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c
=20
 libhx509_la-error.lo: error.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-error.lo `test -f 'error.c=
' || echo '$(srcdir)/'`error.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-error.l=
o -MD -MP -MF $(DEPDIR)/libhx509_la-error.Tpo -c -o libhx509_la-error.lo `t=
est -f 'error.c' || echo '$(srcdir)/'`error.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-error.Tpo $(DEPDIR)/l=
ibhx509_la-error.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'error.c' object=3D'libhx509_la=
-error.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-erro=
r.lo `test -f 'error.c' || echo '$(srcdir)/'`error.c
=20
 libhx509_la-env.lo: env.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-env.lo `test -f 'env.c' ||=
 echo '$(srcdir)/'`env.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-env.lo =
-MD -MP -MF $(DEPDIR)/libhx509_la-env.Tpo -c -o libhx509_la-env.lo `test -f=
 'env.c' || echo '$(srcdir)/'`env.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-env.Tpo $(DEPDIR)/lib=
hx509_la-env.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'env.c' object=3D'libhx509_la-e=
nv.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-env.=
lo `test -f 'env.c' || echo '$(srcdir)/'`env.c
=20
 libhx509_la-file.lo: file.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-file.lo `test -f 'file.c' =
|| echo '$(srcdir)/'`file.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-file.lo=
 -MD -MP -MF $(DEPDIR)/libhx509_la-file.Tpo -c -o libhx509_la-file.lo `test=
 -f 'file.c' || echo '$(srcdir)/'`file.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-file.Tpo $(DEPDIR)/li=
bhx509_la-file.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'file.c' object=3D'libhx509_la-=
file.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-file=
.lo `test -f 'file.c' || echo '$(srcdir)/'`file.c
+
+libhx509_la-sel.lo: sel.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-sel.lo =
-MD -MP -MF $(DEPDIR)/libhx509_la-sel.Tpo -c -o libhx509_la-sel.lo `test -f=
 'sel.c' || echo '$(srcdir)/'`sel.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-sel.Tpo $(DEPDIR)/lib=
hx509_la-sel.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'sel.c' object=3D'libhx509_la-s=
el.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-sel.=
lo `test -f 'sel.c' || echo '$(srcdir)/'`sel.c
+
+libhx509_la-sel-gram.lo: sel-gram.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-sel-gra=
m.lo -MD -MP -MF $(DEPDIR)/libhx509_la-sel-gram.Tpo -c -o libhx509_la-sel-g=
ram.lo `test -f 'sel-gram.c' || echo '$(srcdir)/'`sel-gram.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-sel-gram.Tpo $(DEPDIR=
)/libhx509_la-sel-gram.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'sel-gram.c' object=3D'libhx509=
_la-sel-gram.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-sel-=
gram.lo `test -f 'sel-gram.c' || echo '$(srcdir)/'`sel-gram.c
+
+libhx509_la-sel-lex.lo: sel-lex.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-sel-lex=
.lo -MD -MP -MF $(DEPDIR)/libhx509_la-sel-lex.Tpo -c -o libhx509_la-sel-lex=
.lo `test -f 'sel-lex.c' || echo '$(srcdir)/'`sel-lex.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-sel-lex.Tpo $(DEPDIR)=
/libhx509_la-sel-lex.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'sel-lex.c' object=3D'libhx509_=
la-sel-lex.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-sel-=
lex.lo `test -f 'sel-lex.c' || echo '$(srcdir)/'`sel-lex.c
=20
 libhx509_la-keyset.lo: keyset.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-keyset.lo `test -f 'keyset=
.c' || echo '$(srcdir)/'`keyset.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-keyset.=
lo -MD -MP -MF $(DEPDIR)/libhx509_la-keyset.Tpo -c -o libhx509_la-keyset.lo=
 `test -f 'keyset.c' || echo '$(srcdir)/'`keyset.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-keyset.Tpo $(DEPDIR)/=
libhx509_la-keyset.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keyset.c' object=3D'libhx509_l=
a-keyset.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-keys=
et.lo `test -f 'keyset.c' || echo '$(srcdir)/'`keyset.c
=20
 libhx509_la-ks_dir.lo: ks_dir.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_dir.lo `test -f 'ks_dir=
.c' || echo '$(srcdir)/'`ks_dir.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ks_dir.=
lo -MD -MP -MF $(DEPDIR)/libhx509_la-ks_dir.Tpo -c -o libhx509_la-ks_dir.lo=
 `test -f 'ks_dir.c' || echo '$(srcdir)/'`ks_dir.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ks_dir.Tpo $(DEPDIR)/=
libhx509_la-ks_dir.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ks_dir.c' object=3D'libhx509_l=
a-ks_dir.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_d=
ir.lo `test -f 'ks_dir.c' || echo '$(srcdir)/'`ks_dir.c
=20
 libhx509_la-ks_file.lo: ks_file.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_file.lo `test -f 'ks_fi=
le.c' || echo '$(srcdir)/'`ks_file.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ks_file=
.lo -MD -MP -MF $(DEPDIR)/libhx509_la-ks_file.Tpo -c -o libhx509_la-ks_file=
.lo `test -f 'ks_file.c' || echo '$(srcdir)/'`ks_file.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ks_file.Tpo $(DEPDIR)=
/libhx509_la-ks_file.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ks_file.c' object=3D'libhx509_=
la-ks_file.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_f=
ile.lo `test -f 'ks_file.c' || echo '$(srcdir)/'`ks_file.c
=20
 libhx509_la-ks_mem.lo: ks_mem.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_mem.lo `test -f 'ks_mem=
.c' || echo '$(srcdir)/'`ks_mem.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ks_mem.=
lo -MD -MP -MF $(DEPDIR)/libhx509_la-ks_mem.Tpo -c -o libhx509_la-ks_mem.lo=
 `test -f 'ks_mem.c' || echo '$(srcdir)/'`ks_mem.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ks_mem.Tpo $(DEPDIR)/=
libhx509_la-ks_mem.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ks_mem.c' object=3D'libhx509_l=
a-ks_mem.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_m=
em.lo `test -f 'ks_mem.c' || echo '$(srcdir)/'`ks_mem.c
=20
 libhx509_la-ks_null.lo: ks_null.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_null.lo `test -f 'ks_nu=
ll.c' || echo '$(srcdir)/'`ks_null.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ks_null=
.lo -MD -MP -MF $(DEPDIR)/libhx509_la-ks_null.Tpo -c -o libhx509_la-ks_null=
.lo `test -f 'ks_null.c' || echo '$(srcdir)/'`ks_null.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ks_null.Tpo $(DEPDIR)=
/libhx509_la-ks_null.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ks_null.c' object=3D'libhx509_=
la-ks_null.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_n=
ull.lo `test -f 'ks_null.c' || echo '$(srcdir)/'`ks_null.c
=20
 libhx509_la-ks_p11.lo: ks_p11.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_p11.lo `test -f 'ks_p11=
.c' || echo '$(srcdir)/'`ks_p11.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ks_p11.=
lo -MD -MP -MF $(DEPDIR)/libhx509_la-ks_p11.Tpo -c -o libhx509_la-ks_p11.lo=
 `test -f 'ks_p11.c' || echo '$(srcdir)/'`ks_p11.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ks_p11.Tpo $(DEPDIR)/=
libhx509_la-ks_p11.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ks_p11.c' object=3D'libhx509_l=
a-ks_p11.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_p=
11.lo `test -f 'ks_p11.c' || echo '$(srcdir)/'`ks_p11.c
=20
 libhx509_la-ks_p12.lo: ks_p12.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_p12.lo `test -f 'ks_p12=
.c' || echo '$(srcdir)/'`ks_p12.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ks_p12.=
lo -MD -MP -MF $(DEPDIR)/libhx509_la-ks_p12.Tpo -c -o libhx509_la-ks_p12.lo=
 `test -f 'ks_p12.c' || echo '$(srcdir)/'`ks_p12.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ks_p12.Tpo $(DEPDIR)/=
libhx509_la-ks_p12.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ks_p12.c' object=3D'libhx509_l=
a-ks_p12.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_p=
12.lo `test -f 'ks_p12.c' || echo '$(srcdir)/'`ks_p12.c
=20
 libhx509_la-ks_keychain.lo: ks_keychain.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_keychain.lo `test -f 'k=
s_keychain.c' || echo '$(srcdir)/'`ks_keychain.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-ks_keyc=
hain.lo -MD -MP -MF $(DEPDIR)/libhx509_la-ks_keychain.Tpo -c -o libhx509_la=
-ks_keychain.lo `test -f 'ks_keychain.c' || echo '$(srcdir)/'`ks_keychain.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-ks_keychain.Tpo $(DEP=
DIR)/libhx509_la-ks_keychain.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ks_keychain.c' object=3D'libhx=
509_la-ks_keychain.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-ks_k=
eychain.lo `test -f 'ks_keychain.c' || echo '$(srcdir)/'`ks_keychain.c
=20
 libhx509_la-lock.lo: lock.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-lock.lo `test -f 'lock.c' =
|| echo '$(srcdir)/'`lock.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-lock.lo=
 -MD -MP -MF $(DEPDIR)/libhx509_la-lock.Tpo -c -o libhx509_la-lock.lo `test=
 -f 'lock.c' || echo '$(srcdir)/'`lock.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-lock.Tpo $(DEPDIR)/li=
bhx509_la-lock.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'lock.c' object=3D'libhx509_la-=
lock.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-lock=
.lo `test -f 'lock.c' || echo '$(srcdir)/'`lock.c
=20
 libhx509_la-name.lo: name.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-name.lo `test -f 'name.c' =
|| echo '$(srcdir)/'`name.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-name.lo=
 -MD -MP -MF $(DEPDIR)/libhx509_la-name.Tpo -c -o libhx509_la-name.lo `test=
 -f 'name.c' || echo '$(srcdir)/'`name.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-name.Tpo $(DEPDIR)/li=
bhx509_la-name.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'name.c' object=3D'libhx509_la-=
name.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-name=
.lo `test -f 'name.c' || echo '$(srcdir)/'`name.c
=20
 libhx509_la-peer.lo: peer.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-peer.lo `test -f 'peer.c' =
|| echo '$(srcdir)/'`peer.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-peer.lo=
 -MD -MP -MF $(DEPDIR)/libhx509_la-peer.Tpo -c -o libhx509_la-peer.lo `test=
 -f 'peer.c' || echo '$(srcdir)/'`peer.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-peer.Tpo $(DEPDIR)/li=
bhx509_la-peer.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'peer.c' object=3D'libhx509_la-=
peer.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-peer=
.lo `test -f 'peer.c' || echo '$(srcdir)/'`peer.c
=20
 libhx509_la-print.lo: print.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-print.lo `test -f 'print.c=
' || echo '$(srcdir)/'`print.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-print.l=
o -MD -MP -MF $(DEPDIR)/libhx509_la-print.Tpo -c -o libhx509_la-print.lo `t=
est -f 'print.c' || echo '$(srcdir)/'`print.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-print.Tpo $(DEPDIR)/l=
ibhx509_la-print.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'print.c' object=3D'libhx509_la=
-print.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-prin=
t.lo `test -f 'print.c' || echo '$(srcdir)/'`print.c
=20
 libhx509_la-softp11.lo: softp11.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-softp11.lo `test -f 'softp=
11.c' || echo '$(srcdir)/'`softp11.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-softp11=
.lo -MD -MP -MF $(DEPDIR)/libhx509_la-softp11.Tpo -c -o libhx509_la-softp11=
.lo `test -f 'softp11.c' || echo '$(srcdir)/'`softp11.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-softp11.Tpo $(DEPDIR)=
/libhx509_la-softp11.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'softp11.c' object=3D'libhx509_=
la-softp11.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-soft=
p11.lo `test -f 'softp11.c' || echo '$(srcdir)/'`softp11.c
=20
 libhx509_la-req.lo: req.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-req.lo `test -f 'req.c' ||=
 echo '$(srcdir)/'`req.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-req.lo =
-MD -MP -MF $(DEPDIR)/libhx509_la-req.Tpo -c -o libhx509_la-req.lo `test -f=
 'req.c' || echo '$(srcdir)/'`req.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-req.Tpo $(DEPDIR)/lib=
hx509_la-req.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'req.c' object=3D'libhx509_la-r=
eq.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-req.=
lo `test -f 'req.c' || echo '$(srcdir)/'`req.c
=20
 libhx509_la-revoke.lo: revoke.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-revoke.lo `test -f 'revoke=
.c' || echo '$(srcdir)/'`revoke.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-revoke.=
lo -MD -MP -MF $(DEPDIR)/libhx509_la-revoke.Tpo -c -o libhx509_la-revoke.lo=
 `test -f 'revoke.c' || echo '$(srcdir)/'`revoke.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-revoke.Tpo $(DEPDIR)/=
libhx509_la-revoke.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'revoke.c' object=3D'libhx509_l=
a-revoke.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-revo=
ke.lo `test -f 'revoke.c' || echo '$(srcdir)/'`revoke.c
=20
 libhx509_la-asn1_OCSPBasicOCSPResponse.lo: asn1_OCSPBasicOCSPResponse.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPBasicOCSPResponse=
.lo `test -f 'asn1_OCSPBasicOCSPResponse.c' || echo '$(srcdir)/'`asn1_OCSPB=
asicOCSPResponse.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPBasicOCSPResponse.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPBasicOCSP=
Response.Tpo -c -o libhx509_la-asn1_OCSPBasicOCSPResponse.lo `test -f 'asn1=
_OCSPBasicOCSPResponse.c' || echo '$(srcdir)/'`asn1_OCSPBasicOCSPResponse.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPBasicOCSPRes=
ponse.Tpo $(DEPDIR)/libhx509_la-asn1_OCSPBasicOCSPResponse.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPBasicOCSPResponse.c' =
object=3D'libhx509_la-asn1_OCSPBasicOCSPResponse.lo' libtool=3Dyes @AMDEPBA=
CKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPBasicOCSPResponse.lo `test -f 'asn1_OCSPBasicOCSPResponse.c' || echo '=
$(srcdir)/'`asn1_OCSPBasicOCSPResponse.c
=20
 libhx509_la-asn1_OCSPCertID.lo: asn1_OCSPCertID.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPCertID.lo `test -=
f 'asn1_OCSPCertID.c' || echo '$(srcdir)/'`asn1_OCSPCertID.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPCertID.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPCertID.Tpo -c -o lib=
hx509_la-asn1_OCSPCertID.lo `test -f 'asn1_OCSPCertID.c' || echo '$(srcdir)=
/'`asn1_OCSPCertID.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPCertID.Tpo $=
(DEPDIR)/libhx509_la-asn1_OCSPCertID.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPCertID.c' object=3D'l=
ibhx509_la-asn1_OCSPCertID.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPCertID.lo `test -f 'asn1_OCSPCertID.c' || echo '$(srcdir)/'`asn1_OCSPC=
ertID.c
=20
 libhx509_la-asn1_OCSPCertStatus.lo: asn1_OCSPCertStatus.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPCertStatus.lo `te=
st -f 'asn1_OCSPCertStatus.c' || echo '$(srcdir)/'`asn1_OCSPCertStatus.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPCertStatus.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPCertStatus.Tpo -=
c -o libhx509_la-asn1_OCSPCertStatus.lo `test -f 'asn1_OCSPCertStatus.c' ||=
 echo '$(srcdir)/'`asn1_OCSPCertStatus.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPCertStatus.T=
po $(DEPDIR)/libhx509_la-asn1_OCSPCertStatus.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPCertStatus.c' object=
=3D'libhx509_la-asn1_OCSPCertStatus.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPCertStatus.lo `test -f 'asn1_OCSPCertStatus.c' || echo '$(srcdir)/'`as=
n1_OCSPCertStatus.c
=20
 libhx509_la-asn1_OCSPInnerRequest.lo: asn1_OCSPInnerRequest.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPInnerRequest.lo `=
test -f 'asn1_OCSPInnerRequest.c' || echo '$(srcdir)/'`asn1_OCSPInnerReques=
t.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPInnerRequest.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPInnerRequest.T=
po -c -o libhx509_la-asn1_OCSPInnerRequest.lo `test -f 'asn1_OCSPInnerReque=
st.c' || echo '$(srcdir)/'`asn1_OCSPInnerRequest.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPInnerRequest=
.Tpo $(DEPDIR)/libhx509_la-asn1_OCSPInnerRequest.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPInnerRequest.c' objec=
t=3D'libhx509_la-asn1_OCSPInnerRequest.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPInnerRequest.lo `test -f 'asn1_OCSPInnerRequest.c' || echo '$(srcdir)/=
'`asn1_OCSPInnerRequest.c
=20
 libhx509_la-asn1_OCSPKeyHash.lo: asn1_OCSPKeyHash.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPKeyHash.lo `test =
-f 'asn1_OCSPKeyHash.c' || echo '$(srcdir)/'`asn1_OCSPKeyHash.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPKeyHash.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPKeyHash.Tpo -c -o l=
ibhx509_la-asn1_OCSPKeyHash.lo `test -f 'asn1_OCSPKeyHash.c' || echo '$(src=
dir)/'`asn1_OCSPKeyHash.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPKeyHash.Tpo =
$(DEPDIR)/libhx509_la-asn1_OCSPKeyHash.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPKeyHash.c' object=3D'=
libhx509_la-asn1_OCSPKeyHash.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPKeyHash.lo `test -f 'asn1_OCSPKeyHash.c' || echo '$(srcdir)/'`asn1_OCS=
PKeyHash.c
=20
 libhx509_la-asn1_OCSPRequest.lo: asn1_OCSPRequest.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPRequest.lo `test =
-f 'asn1_OCSPRequest.c' || echo '$(srcdir)/'`asn1_OCSPRequest.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPRequest.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPRequest.Tpo -c -o l=
ibhx509_la-asn1_OCSPRequest.lo `test -f 'asn1_OCSPRequest.c' || echo '$(src=
dir)/'`asn1_OCSPRequest.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPRequest.Tpo =
$(DEPDIR)/libhx509_la-asn1_OCSPRequest.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPRequest.c' object=3D'=
libhx509_la-asn1_OCSPRequest.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPRequest.lo `test -f 'asn1_OCSPRequest.c' || echo '$(srcdir)/'`asn1_OCS=
PRequest.c
=20
 libhx509_la-asn1_OCSPResponderID.lo: asn1_OCSPResponderID.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPResponderID.lo `t=
est -f 'asn1_OCSPResponderID.c' || echo '$(srcdir)/'`asn1_OCSPResponderID.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPResponderID.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPResponderID.Tpo=
 -c -o libhx509_la-asn1_OCSPResponderID.lo `test -f 'asn1_OCSPResponderID.c=
' || echo '$(srcdir)/'`asn1_OCSPResponderID.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPResponderID.=
Tpo $(DEPDIR)/libhx509_la-asn1_OCSPResponderID.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPResponderID.c' object=
=3D'libhx509_la-asn1_OCSPResponderID.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPResponderID.lo `test -f 'asn1_OCSPResponderID.c' || echo '$(srcdir)/'`=
asn1_OCSPResponderID.c
=20
 libhx509_la-asn1_OCSPResponse.lo: asn1_OCSPResponse.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPResponse.lo `test=
 -f 'asn1_OCSPResponse.c' || echo '$(srcdir)/'`asn1_OCSPResponse.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPResponse.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPResponse.Tpo -c -o=
 libhx509_la-asn1_OCSPResponse.lo `test -f 'asn1_OCSPResponse.c' || echo '$=
(srcdir)/'`asn1_OCSPResponse.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPResponse.Tpo=
 $(DEPDIR)/libhx509_la-asn1_OCSPResponse.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPResponse.c' object=3D=
'libhx509_la-asn1_OCSPResponse.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPResponse.lo `test -f 'asn1_OCSPResponse.c' || echo '$(srcdir)/'`asn1_O=
CSPResponse.c
=20
 libhx509_la-asn1_OCSPResponseBytes.lo: asn1_OCSPResponseBytes.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPResponseBytes.lo =
`test -f 'asn1_OCSPResponseBytes.c' || echo '$(srcdir)/'`asn1_OCSPResponseB=
ytes.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPResponseBytes.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPResponseBytes=
.Tpo -c -o libhx509_la-asn1_OCSPResponseBytes.lo `test -f 'asn1_OCSPRespons=
eBytes.c' || echo '$(srcdir)/'`asn1_OCSPResponseBytes.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPResponseByte=
s.Tpo $(DEPDIR)/libhx509_la-asn1_OCSPResponseBytes.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPResponseBytes.c' obje=
ct=3D'libhx509_la-asn1_OCSPResponseBytes.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPResponseBytes.lo `test -f 'asn1_OCSPResponseBytes.c' || echo '$(srcdir=
)/'`asn1_OCSPResponseBytes.c
=20
 libhx509_la-asn1_OCSPResponseData.lo: asn1_OCSPResponseData.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPResponseData.lo `=
test -f 'asn1_OCSPResponseData.c' || echo '$(srcdir)/'`asn1_OCSPResponseDat=
a.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPResponseData.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPResponseData.T=
po -c -o libhx509_la-asn1_OCSPResponseData.lo `test -f 'asn1_OCSPResponseDa=
ta.c' || echo '$(srcdir)/'`asn1_OCSPResponseData.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPResponseData=
.Tpo $(DEPDIR)/libhx509_la-asn1_OCSPResponseData.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPResponseData.c' objec=
t=3D'libhx509_la-asn1_OCSPResponseData.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPResponseData.lo `test -f 'asn1_OCSPResponseData.c' || echo '$(srcdir)/=
'`asn1_OCSPResponseData.c
=20
 libhx509_la-asn1_OCSPResponseStatus.lo: asn1_OCSPResponseStatus.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPResponseStatus.lo=
 `test -f 'asn1_OCSPResponseStatus.c' || echo '$(srcdir)/'`asn1_OCSPRespons=
eStatus.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPResponseStatus.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPResponseStat=
us.Tpo -c -o libhx509_la-asn1_OCSPResponseStatus.lo `test -f 'asn1_OCSPResp=
onseStatus.c' || echo '$(srcdir)/'`asn1_OCSPResponseStatus.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPResponseStat=
us.Tpo $(DEPDIR)/libhx509_la-asn1_OCSPResponseStatus.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPResponseStatus.c' obj=
ect=3D'libhx509_la-asn1_OCSPResponseStatus.lo' libtool=3Dyes @AMDEPBACKSLAS=
H@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPResponseStatus.lo `test -f 'asn1_OCSPResponseStatus.c' || echo '$(srcd=
ir)/'`asn1_OCSPResponseStatus.c
=20
 libhx509_la-asn1_OCSPSignature.lo: asn1_OCSPSignature.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPSignature.lo `tes=
t -f 'asn1_OCSPSignature.c' || echo '$(srcdir)/'`asn1_OCSPSignature.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPSignature.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPSignature.Tpo -c =
-o libhx509_la-asn1_OCSPSignature.lo `test -f 'asn1_OCSPSignature.c' || ech=
o '$(srcdir)/'`asn1_OCSPSignature.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPSignature.Tp=
o $(DEPDIR)/libhx509_la-asn1_OCSPSignature.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPSignature.c' object=
=3D'libhx509_la-asn1_OCSPSignature.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPSignature.lo `test -f 'asn1_OCSPSignature.c' || echo '$(srcdir)/'`asn1=
_OCSPSignature.c
=20
 libhx509_la-asn1_OCSPSingleResponse.lo: asn1_OCSPSingleResponse.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPSingleResponse.lo=
 `test -f 'asn1_OCSPSingleResponse.c' || echo '$(srcdir)/'`asn1_OCSPSingleR=
esponse.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPSingleResponse.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPSingleRespon=
se.Tpo -c -o libhx509_la-asn1_OCSPSingleResponse.lo `test -f 'asn1_OCSPSing=
leResponse.c' || echo '$(srcdir)/'`asn1_OCSPSingleResponse.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPSingleRespon=
se.Tpo $(DEPDIR)/libhx509_la-asn1_OCSPSingleResponse.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPSingleResponse.c' obj=
ect=3D'libhx509_la-asn1_OCSPSingleResponse.lo' libtool=3Dyes @AMDEPBACKSLAS=
H@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPSingleResponse.lo `test -f 'asn1_OCSPSingleResponse.c' || echo '$(srcd=
ir)/'`asn1_OCSPSingleResponse.c
=20
 libhx509_la-asn1_OCSPTBSRequest.lo: asn1_OCSPTBSRequest.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPTBSRequest.lo `te=
st -f 'asn1_OCSPTBSRequest.c' || echo '$(srcdir)/'`asn1_OCSPTBSRequest.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPTBSRequest.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPTBSRequest.Tpo -=
c -o libhx509_la-asn1_OCSPTBSRequest.lo `test -f 'asn1_OCSPTBSRequest.c' ||=
 echo '$(srcdir)/'`asn1_OCSPTBSRequest.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPTBSRequest.T=
po $(DEPDIR)/libhx509_la-asn1_OCSPTBSRequest.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPTBSRequest.c' object=
=3D'libhx509_la-asn1_OCSPTBSRequest.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPTBSRequest.lo `test -f 'asn1_OCSPTBSRequest.c' || echo '$(srcdir)/'`as=
n1_OCSPTBSRequest.c
=20
 libhx509_la-asn1_OCSPVersion.lo: asn1_OCSPVersion.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_OCSPVersion.lo `test =
-f 'asn1_OCSPVersion.c' || echo '$(srcdir)/'`asn1_OCSPVersion.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_OC=
SPVersion.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_OCSPVersion.Tpo -c -o l=
ibhx509_la-asn1_OCSPVersion.lo `test -f 'asn1_OCSPVersion.c' || echo '$(src=
dir)/'`asn1_OCSPVersion.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_OCSPVersion.Tpo =
$(DEPDIR)/libhx509_la-asn1_OCSPVersion.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_OCSPVersion.c' object=3D'=
libhx509_la-asn1_OCSPVersion.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_OCSPVersion.lo `test -f 'asn1_OCSPVersion.c' || echo '$(srcdir)/'`asn1_OCS=
PVersion.c
=20
 libhx509_la-asn1_id_pkix_ocsp.lo: asn1_id_pkix_ocsp.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_id_pkix_ocsp.lo `test=
 -f 'asn1_id_pkix_ocsp.c' || echo '$(srcdir)/'`asn1_id_pkix_ocsp.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_id=
_pkix_ocsp.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp.Tpo -c -o=
 libhx509_la-asn1_id_pkix_ocsp.lo `test -f 'asn1_id_pkix_ocsp.c' || echo '$=
(srcdir)/'`asn1_id_pkix_ocsp.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp.Tpo=
 $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_id_pkix_ocsp.c' object=3D=
'libhx509_la-asn1_id_pkix_ocsp.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_id_pkix_ocsp.lo `test -f 'asn1_id_pkix_ocsp.c' || echo '$(srcdir)/'`asn1_i=
d_pkix_ocsp.c
=20
 libhx509_la-asn1_id_pkix_ocsp_basic.lo: asn1_id_pkix_ocsp_basic.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_id_pkix_ocsp_basic.lo=
 `test -f 'asn1_id_pkix_ocsp_basic.c' || echo '$(srcdir)/'`asn1_id_pkix_ocs=
p_basic.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_id=
_pkix_ocsp_basic.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp_bas=
ic.Tpo -c -o libhx509_la-asn1_id_pkix_ocsp_basic.lo `test -f 'asn1_id_pkix_=
ocsp_basic.c' || echo '$(srcdir)/'`asn1_id_pkix_ocsp_basic.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp_bas=
ic.Tpo $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp_basic.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_id_pkix_ocsp_basic.c' obj=
ect=3D'libhx509_la-asn1_id_pkix_ocsp_basic.lo' libtool=3Dyes @AMDEPBACKSLAS=
H@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_id_pkix_ocsp_basic.lo `test -f 'asn1_id_pkix_ocsp_basic.c' || echo '$(srcd=
ir)/'`asn1_id_pkix_ocsp_basic.c
=20
 libhx509_la-asn1_id_pkix_ocsp_nonce.lo: asn1_id_pkix_ocsp_nonce.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_id_pkix_ocsp_nonce.lo=
 `test -f 'asn1_id_pkix_ocsp_nonce.c' || echo '$(srcdir)/'`asn1_id_pkix_ocs=
p_nonce.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_id=
_pkix_ocsp_nonce.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp_non=
ce.Tpo -c -o libhx509_la-asn1_id_pkix_ocsp_nonce.lo `test -f 'asn1_id_pkix_=
ocsp_nonce.c' || echo '$(srcdir)/'`asn1_id_pkix_ocsp_nonce.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp_non=
ce.Tpo $(DEPDIR)/libhx509_la-asn1_id_pkix_ocsp_nonce.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_id_pkix_ocsp_nonce.c' obj=
ect=3D'libhx509_la-asn1_id_pkix_ocsp_nonce.lo' libtool=3Dyes @AMDEPBACKSLAS=
H@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_id_pkix_ocsp_nonce.lo `test -f 'asn1_id_pkix_ocsp_nonce.c' || echo '$(srcd=
ir)/'`asn1_id_pkix_ocsp_nonce.c
=20
 libhx509_la-asn1_CertificationRequestInfo.lo: asn1_CertificationRequestInf=
o.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_CertificationRequestI=
nfo.lo `test -f 'asn1_CertificationRequestInfo.c' || echo '$(srcdir)/'`asn1=
_CertificationRequestInfo.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_Ce=
rtificationRequestInfo.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_Certificat=
ionRequestInfo.Tpo -c -o libhx509_la-asn1_CertificationRequestInfo.lo `test=
 -f 'asn1_CertificationRequestInfo.c' || echo '$(srcdir)/'`asn1_Certificati=
onRequestInfo.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_CertificationReq=
uestInfo.Tpo $(DEPDIR)/libhx509_la-asn1_CertificationRequestInfo.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_CertificationRequestInfo.=
c' object=3D'libhx509_la-asn1_CertificationRequestInfo.lo' libtool=3Dyes @A=
MDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_CertificationRequestInfo.lo `test -f 'asn1_CertificationRequestInfo.c' || =
echo '$(srcdir)/'`asn1_CertificationRequestInfo.c
=20
 libhx509_la-asn1_CertificationRequest.lo: asn1_CertificationRequest.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1_CertificationRequest.=
lo `test -f 'asn1_CertificationRequest.c' || echo '$(srcdir)/'`asn1_Certifi=
cationRequest.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-asn1_Ce=
rtificationRequest.lo -MD -MP -MF $(DEPDIR)/libhx509_la-asn1_CertificationR=
equest.Tpo -c -o libhx509_la-asn1_CertificationRequest.lo `test -f 'asn1_Ce=
rtificationRequest.c' || echo '$(srcdir)/'`asn1_CertificationRequest.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-asn1_CertificationReq=
uest.Tpo $(DEPDIR)/libhx509_la-asn1_CertificationRequest.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_CertificationRequest.c' o=
bject=3D'libhx509_la-asn1_CertificationRequest.lo' libtool=3Dyes @AMDEPBACK=
SLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-asn1=
_CertificationRequest.lo `test -f 'asn1_CertificationRequest.c' || echo '$(=
srcdir)/'`asn1_CertificationRequest.c
=20
 libhx509_la-hx509_err.lo: hx509_err.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx509_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-hx509_err.lo `test -f 'hx5=
09_err.c' || echo '$(srcdir)/'`hx509_err.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libhx=
509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libhx509_la-hx509_e=
rr.lo -MD -MP -MF $(DEPDIR)/libhx509_la-hx509_err.Tpo -c -o libhx509_la-hx5=
09_err.lo `test -f 'hx509_err.c' || echo '$(srcdir)/'`hx509_err.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libhx509_la-hx509_err.Tpo $(DEPDI=
R)/libhx509_la-hx509_err.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'hx509_err.c' object=3D'libhx50=
9_la-hx509_err.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libh=
x509_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libhx509_la-hx50=
9_err.lo `test -f 'hx509_err.c' || echo '$(srcdir)/'`hx509_err.c
=20
 hxtool-hxtool.o: hxtool.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtool_CPPFLAGS) $(CPPFLA=
GS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool.o `test -f 'hxtool.c' || ech=
o '$(srcdir)/'`hxtool.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtoo=
l_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hxtool-hxtool.o -MD -MP =
-MF $(DEPDIR)/hxtool-hxtool.Tpo -c -o hxtool-hxtool.o `test -f 'hxtool.c' |=
| echo '$(srcdir)/'`hxtool.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/hxtool-hxtool.Tpo $(DEPDIR)/hxtoo=
l-hxtool.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'hxtool.c' object=3D'hxtool-hxt=
ool.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxto=
ol_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool.o `test=
 -f 'hxtool.c' || echo '$(srcdir)/'`hxtool.c
=20
 hxtool-hxtool.obj: hxtool.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtool_CPPFLAGS) $(CPPFLA=
GS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool.obj `if test -f 'hxtool.c'; =
then $(CYGPATH_W) 'hxtool.c'; else $(CYGPATH_W) '$(srcdir)/hxtool.c'; fi`
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtoo=
l_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hxtool-hxtool.obj -MD -M=
P -MF $(DEPDIR)/hxtool-hxtool.Tpo -c -o hxtool-hxtool.obj `if test -f 'hxto=
ol.c'; then $(CYGPATH_W) 'hxtool.c'; else $(CYGPATH_W) '$(srcdir)/hxtool.c'=
; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/hxtool-hxtool.Tpo $(DEPDIR)/hxtoo=
l-hxtool.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'hxtool.c' object=3D'hxtool-hxt=
ool.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxto=
ol_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool.obj `if=
 test -f 'hxtool.c'; then $(CYGPATH_W) 'hxtool.c'; else $(CYGPATH_W) '$(src=
dir)/hxtool.c'; fi`
=20
 hxtool-hxtool-commands.o: hxtool-commands.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtool_CPPFLAGS) $(CPPFLA=
GS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool-commands.o `test -f 'hxtool-=
commands.c' || echo '$(srcdir)/'`hxtool-commands.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtoo=
l_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hxtool-hxtool-commands.o=
 -MD -MP -MF $(DEPDIR)/hxtool-hxtool-commands.Tpo -c -o hxtool-hxtool-comma=
nds.o `test -f 'hxtool-commands.c' || echo '$(srcdir)/'`hxtool-commands.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/hxtool-hxtool-commands.Tpo $(DEPD=
IR)/hxtool-hxtool-commands.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'hxtool-commands.c' object=3D'h=
xtool-hxtool-commands.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxto=
ol_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool-command=
s.o `test -f 'hxtool-commands.c' || echo '$(srcdir)/'`hxtool-commands.c
=20
 hxtool-hxtool-commands.obj: hxtool-commands.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtool_CPPFLAGS) $(CPPFLA=
GS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool-commands.obj `if test -f 'hx=
tool-commands.c'; then $(CYGPATH_W) 'hxtool-commands.c'; else $(CYGPATH_W) =
'$(srcdir)/hxtool-commands.c'; fi`
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxtoo=
l_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hxtool-hxtool-commands.o=
bj -MD -MP -MF $(DEPDIR)/hxtool-hxtool-commands.Tpo -c -o hxtool-hxtool-com=
mands.obj `if test -f 'hxtool-commands.c'; then $(CYGPATH_W) 'hxtool-comman=
ds.c'; else $(CYGPATH_W) '$(srcdir)/hxtool-commands.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/hxtool-hxtool-commands.Tpo $(DEPD=
IR)/hxtool-hxtool-commands.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'hxtool-commands.c' object=3D'h=
xtool-hxtool-commands.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(hxto=
ol_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hxtool-hxtool-command=
s.obj `if test -f 'hxtool-commands.c'; then $(CYGPATH_W) 'hxtool-commands.c=
'; else $(CYGPATH_W) '$(srcdir)/hxtool-commands.c'; fi`
+
+test_name-test_name.o: test_name.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_=
name_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_name-test_name.o=
 -MD -MP -MF $(DEPDIR)/test_name-test_name.Tpo -c -o test_name-test_name.o =
`test -f 'test_name.c' || echo '$(srcdir)/'`test_name.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/test_name-test_name.Tpo $(DEPDIR)=
/test_name-test_name.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'test_name.c' object=3D'test_na=
me-test_name.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test=
_name_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_name-test_nam=
e.o `test -f 'test_name.c' || echo '$(srcdir)/'`test_name.c
+
+test_name-test_name.obj: test_name.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_=
name_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_name-test_name.o=
bj -MD -MP -MF $(DEPDIR)/test_name-test_name.Tpo -c -o test_name-test_name.=
obj `if test -f 'test_name.c'; then $(CYGPATH_W) 'test_name.c'; else $(CYGP=
ATH_W) '$(srcdir)/test_name.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/test_name-test_name.Tpo $(DEPDIR)=
/test_name-test_name.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'test_name.c' object=3D'test_na=
me-test_name.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test=
_name_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_name-test_nam=
e.obj `if test -f 'test_name.c'; then $(CYGPATH_W) 'test_name.c'; else $(CY=
GPATH_W) '$(srcdir)/test_name.c'; fi`
=20
 test_soft_pkcs11-test_soft_pkcs11.o: test_soft_pkcs11.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_soft_pkcs11_CPPFLAGS=
) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_soft_pkcs11-test_soft_pkcs1=
1.o `test -f 'test_soft_pkcs11.c' || echo '$(srcdir)/'`test_soft_pkcs11.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_=
soft_pkcs11_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_soft_pkcs=
11-test_soft_pkcs11.o -MD -MP -MF $(DEPDIR)/test_soft_pkcs11-test_soft_pkcs=
11.Tpo -c -o test_soft_pkcs11-test_soft_pkcs11.o `test -f 'test_soft_pkcs11=
.c' || echo '$(srcdir)/'`test_soft_pkcs11.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/test_soft_pkcs11-test_soft_pkcs11=
.Tpo $(DEPDIR)/test_soft_pkcs11-test_soft_pkcs11.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'test_soft_pkcs11.c' object=3D'=
test_soft_pkcs11-test_soft_pkcs11.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test=
_soft_pkcs11_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_soft_p=
kcs11-test_soft_pkcs11.o `test -f 'test_soft_pkcs11.c' || echo '$(srcdir)/'=
`test_soft_pkcs11.c
=20
 test_soft_pkcs11-test_soft_pkcs11.obj: test_soft_pkcs11.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_soft_pkcs11_CPPFLAGS=
) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_soft_pkcs11-test_soft_pkcs1=
1.obj `if test -f 'test_soft_pkcs11.c'; then $(CYGPATH_W) 'test_soft_pkcs11=
.c'; else $(CYGPATH_W) '$(srcdir)/test_soft_pkcs11.c'; fi`
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test_=
soft_pkcs11_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT test_soft_pkcs=
11-test_soft_pkcs11.obj -MD -MP -MF $(DEPDIR)/test_soft_pkcs11-test_soft_pk=
cs11.Tpo -c -o test_soft_pkcs11-test_soft_pkcs11.obj `if test -f 'test_soft=
_pkcs11.c'; then $(CYGPATH_W) 'test_soft_pkcs11.c'; else $(CYGPATH_W) '$(sr=
cdir)/test_soft_pkcs11.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/test_soft_pkcs11-test_soft_pkcs11=
.Tpo $(DEPDIR)/test_soft_pkcs11-test_soft_pkcs11.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'test_soft_pkcs11.c' object=3D'=
test_soft_pkcs11-test_soft_pkcs11.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(test=
_soft_pkcs11_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o test_soft_p=
kcs11-test_soft_pkcs11.obj `if test -f 'test_soft_pkcs11.c'; then $(CYGPATH=
_W) 'test_soft_pkcs11.c'; else $(CYGPATH_W) '$(srcdir)/test_soft_pkcs11.c';=
 fi`
+
+.l.c:
+	$(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMP=
ILE)
+
+.y.c:
+	$(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h $*.h y.output $*=
.output -- $(YACCCOMPILE)
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -949,90 +1391,101 @@
 install-dist_includeHEADERS: $(dist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(dist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)=
/$$f'"; \
-	  $(dist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-dist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-nodist_includeHEADERS: $(nodist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedi=
r)/$$f'"; \
-	  $(nodist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"=
; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -1041,49 +1494,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -1094,11 +1561,15 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
@@ -1118,13 +1589,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -1165,10 +1640,14 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
 	@echo "it deletes files that may require special tools to rebuild."
+	-rm -f sel-gram.c
+	-rm -f sel-gram.h
+	-rm -f sel-lex.c
 	-test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES)
 clean: clean-am
=20
@@ -1176,6 +1655,7 @@
 	clean-libLTLIBRARIES clean-libtool clean-local mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -1186,6 +1666,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -1194,26 +1676,35 @@
 	install-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -1234,9 +1725,8 @@
 	uninstall-libLTLIBRARIES uninstall-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: all check check-am install install-am install-data-am \
+	install-exec-am install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
 	check-local clean clean-binPROGRAMS clean-checkPROGRAMS \
@@ -1327,6 +1817,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1412,7 +1905,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1425,25 +1918,28 @@
 	  (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) distdir-in-tree) ; \
 	  fi ; \
 	done
-$(libhx509_la_OBJECTS): $(srcdir)/version-script.map
=20
-$(gen_files_ocsp) ocsp_asn1.h: ocsp_asn1_files
-$(gen_files_pkcs10) pkcs10_asn1.h: pkcs10_asn1_files
-$(gen_files_crmf) crmf_asn1.h: crmf_asn1_files
+sel-lex.c: sel-gram.h
+$(libhx509_la_OBJECTS): $(srcdir)/version-script.map $(nodist_include_HEAD=
ERS) $(priv_headers)
=20
-ocsp_asn1_files: $(asn1_compile) $(srcdir)/ocsp.asn1
-	$(asn1_compile) --preserve-binary=3DOCSPTBSRequest --preserve-binary=3DOC=
SPResponseData $(srcdir)/ocsp.asn1 ocsp_asn1 || (rm -f ocsp_asn1_files ; ex=
it 1)
+$(gen_files_ocsp) ocsp_asn1.hx ocsp_asn1-priv.hx: ocsp_asn1_files
+$(gen_files_pkcs10) pkcs10_asn1.hx pkcs10_asn1-priv.hx: pkcs10_asn1_files
+$(gen_files_crmf) crmf_asn1.hx crmf_asn1-priv.hx: crmf_asn1_files
=20
-pkcs10_asn1_files: $(asn1_compile) $(srcdir)/pkcs10.asn1
-	$(asn1_compile) --preserve-binary=3DCertificationRequestInfo $(srcdir)/pk=
cs10.asn1 pkcs10_asn1 || (rm -f pkcs10_asn1_files ; exit 1)
+ocsp_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/ocsp.asn1 $(srcdir)/ocsp.opt
+	$(ASN1_COMPILE) --option-file=3D$(srcdir)/ocsp.opt $(srcdir)/ocsp.asn1 oc=
sp_asn1 || (rm -f ocsp_asn1_files ; exit 1)
=20
-crmf_asn1_files: $(asn1_compile) $(srcdir)/crmf.asn1
-	$(asn1_compile) $(srcdir)/crmf.asn1 crmf_asn1 || (rm -f crmf_asn1_files ;=
 exit 1)
+pkcs10_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/pkcs10.asn1 $(srcdir)/pkc=
s10.opt
+	$(ASN1_COMPILE) --option-file=3D$(srcdir)/pkcs10.opt $(srcdir)/pkcs10.asn=
1 pkcs10_asn1 || (rm -f pkcs10_asn1_files ; exit 1)
=20
-$(libhx509_la_OBJECTS): $(srcdir)/hx509-protos.h $(srcdir)/hx509-private.h
+crmf_asn1_files: $(ASN1_COMPILE_DEP) $(srcdir)/crmf.asn1
+	$(ASN1_COMPILE) $(srcdir)/crmf.asn1 crmf_asn1 || (rm -f crmf_asn1_files ;=
 exit 1)
+
+$(libhx509_la_OBJECTS): $(srcdir)/hx509-protos.h $(srcdir)/hx509-private.h=
 $(srcdir)/hx_locl.h
+$(libhx509_la_OBJECTS): ocsp_asn1.h pkcs10_asn1.h
=20
 $(srcdir)/hx509-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -R '^(_|^C)' -E HX509_LIB_FUN=
CTION -q -P comment -o hx509-protos.h $(dist_libhx509_la_SOURCES) || rm -f =
hx509-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -R '^(_|^C)' -E HX509_LIB -q =
-P comment -o hx509-protos.h $(dist_libhx509_la_SOURCES) || rm -f hx509-pro=
tos.h
=20
 $(srcdir)/hx509-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p hx509-privat=
e.h $(dist_libhx509_la_SOURCES) || rm -f hx509-private.h
@@ -1525,6 +2021,7 @@
 	$(do_subst) < $(srcdir)/test_query.in > test_query.tmp
 	chmod +x test_query.tmp
 	mv test_query.tmp test_query
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ca.c
--- a/head/crypto/heimdal/lib/hx509/ca.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ca.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,38 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2010 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
 #include <pkinit_asn1.h>
-RCSID("$Id: ca.c 22456 2008-01-15 20:22:53Z lha $");
=20
 /**
  * @page page_ca Hx509 CA functions
@@ -54,11 +53,15 @@
 	unsigned int key:1;
 	unsigned int serial:1;
 	unsigned int domaincontroller:1;
+	unsigned int xUniqueID:1;
     } flags;
     time_t notBefore;
     time_t notAfter;
     int pathLenConstraint; /* both for CA and Proxy */
     CRLDistributionPoints crldp;
+    heim_bit_string subjectUniqueID;
+    heim_bit_string issuerUniqueID;
+
 };
=20
 /**
@@ -81,15 +84,6 @@
     if (*tbs =3D=3D NULL)
 	return ENOMEM;
=20
-    (*tbs)->subject =3D NULL;
-    (*tbs)->san.len =3D 0;
-    (*tbs)->san.val =3D NULL;
-    (*tbs)->eku.len =3D 0;
-    (*tbs)->eku.val =3D NULL;
-    (*tbs)->pathLenConstraint =3D 0;
-    (*tbs)->crldp.len =3D 0;
-    (*tbs)->crldp.val =3D NULL;
-
     return 0;
 }
=20
@@ -112,7 +106,8 @@
     free_ExtKeyUsage(&(*tbs)->eku);
     der_free_heim_integer(&(*tbs)->serial);
     free_CRLDistributionPoints(&(*tbs)->crldp);
-
+    der_free_bit_string(&(*tbs)->subjectUniqueID);
+    der_free_bit_string(&(*tbs)->issuerUniqueID);
     hx509_name_free(&(*tbs)->subject);
=20
     memset(*tbs, 0, sizeof(**tbs));
@@ -236,7 +231,7 @@
 	    hx509_name_free(&tbs->subject);
 	ret =3D hx509_cert_get_subject(cert, &tbs->subject);
 	if (ret) {
-	    hx509_set_error_string(context, 0, ret,=20
+	    hx509_set_error_string(context, 0, ret,
 				   "Failed to get subject from template");
 	    return ret;
 	}
@@ -246,7 +241,7 @@
 	ret =3D hx509_cert_get_serialnumber(cert, &tbs->serial);
 	tbs->flags.serial =3D !ret;
 	if (ret) {
-	    hx509_set_error_string(context, 0, ret,=20
+	    hx509_set_error_string(context, 0, ret,
 				   "Failed to copy serial number");
 	    return ret;
 	}
@@ -271,7 +266,7 @@
     }
     if (flags & HX509_CA_TEMPLATE_EKU) {
 	ExtKeyUsage eku;
-	int i;
+	size_t i;
 	ret =3D _hx509_cert_get_eku(context, cert, &eku);
 	if (ret)
 	    return ret;
@@ -473,7 +468,7 @@
     int ret;
=20
     memset(&dp, 0, sizeof(dp));
-   =20
+
     dp.distributionPoint =3D ecalloc(1, sizeof(*dp.distributionPoint));
=20
     {
@@ -486,10 +481,11 @@
 	name.u.fullName.val =3D &gn;
=20
 	gn.element =3D choice_GeneralName_uniformResourceIdentifier;
-	gn.u.uniformResourceIdentifier =3D rk_UNCONST(uri);
+	gn.u.uniformResourceIdentifier.data =3D rk_UNCONST(uri);
+	gn.u.uniformResourceIdentifier.length =3D strlen(uri);
=20
-	ASN1_MALLOC_ENCODE(DistributionPointName,=20
-			   dp.distributionPoint->data,=20
+	ASN1_MALLOC_ENCODE(DistributionPointName,
+			   dp.distributionPoint->data,
 			   dp.distributionPoint->length,
 			   &name, &size, ret);
 	if (ret) {
@@ -509,7 +505,7 @@
 	hx509_set_error_string(context, 0, EINVAL,
 			       "CRLDistributionPoints.name.issuername not yet supported");
 	return EINVAL;
-#else=20
+#else
 	GeneralNames *crlissuer;
 	GeneralName gn;
 	Name n;
@@ -579,7 +575,7 @@
     gn.element =3D choice_GeneralName_otherName;
     gn.u.otherName.type_id =3D *oid;
     gn.u.otherName.value =3D *os;
-   =20
+
     return add_GeneralNames(&tbs->san, &gn);
 }
=20
@@ -614,14 +610,14 @@
 	const char *str;
 	char *q;
 	int n;
-=09
+
 	/* count number of component */
 	n =3D 1;
 	for(str =3D principal; *str !=3D '\0' && *str !=3D '@'; str++){
 	    if(*str=3D=3D'\\'){
 		if(str[1] =3D=3D '\0' || str[1] =3D=3D '@') {
 		    ret =3D HX509_PARSING_NAME_FAILED;
-		    hx509_set_error_string(context, 0, ret,=20
+		    hx509_set_error_string(context, 0, ret,
 					   "trailing \\ in principal name");
 		    goto out;
 		}
@@ -629,7 +625,7 @@
 	    } else if(*str =3D=3D '/')
 		n++;
 	}
-	p.principalName.name_string.val =3D=20
+	p.principalName.name_string.val =3D
 	    calloc(n, sizeof(*p.principalName.name_string.val));
 	if (p.principalName.name_string.val =3D=3D NULL) {
 	    ret =3D ENOMEM;
@@ -637,7 +633,7 @@
 	    goto out;
 	}
 	p.principalName.name_string.len =3D n;
-=09
+
 	p.principalName.name_type =3D KRB5_NT_PRINCIPAL;
 	q =3D s =3D strdup(principal);
 	if (q =3D=3D NULL) {
@@ -661,7 +657,7 @@
 		*q++ =3D '\0';
 	}
     }
-   =20
+
     ASN1_MALLOC_ENCODE(KRB5PrincipalName, os.data, os.length, &p, &size, r=
et);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "Out of memory");
@@ -669,10 +665,10 @@
     }
     if (size !=3D os.length)
 	_hx509_abort("internal ASN.1 encoder error");
-   =20
+
     ret =3D hx509_ca_tbs_add_san_otherName(context,
 					 tbs,
-					 oid_id_pkinit_san(),
+					 &asn1_oid_id_pkinit_san,
 					 &os);
     free(os.data);
 out:
@@ -682,7 +678,7 @@
 	free(s);
     return ret;
 }
-   =20
+
 /*
  *
  */
@@ -693,7 +689,7 @@
 	     const heim_oid *oid,
 	     const char *string)
 {
-    const PKIXXmppAddr ustring =3D (const PKIXXmppAddr)string;
+    const PKIXXmppAddr ustring =3D (const PKIXXmppAddr)(intptr_t)string;
     heim_octet_string os;
     size_t size;
     int ret;
@@ -708,7 +704,7 @@
     }
     if (size !=3D os.length)
 	_hx509_abort("internal ASN.1 encoder error");
-   =20
+
     ret =3D hx509_ca_tbs_add_san_otherName(context,
 					 tbs,
 					 oid,
@@ -736,7 +732,7 @@
 			    hx509_ca_tbs tbs,
 			    const char *principal)
 {
-    return add_utf8_san(context, tbs, oid_id_pkinit_ms_san(), principal);
+    return add_utf8_san(context, tbs, &asn1_oid_id_pkinit_ms_san, principa=
l);
 }
=20
 /**
@@ -757,7 +753,7 @@
 			 hx509_ca_tbs tbs,
 			 const char *jid)
 {
-    return add_utf8_san(context, tbs, oid_id_pkix_on_xmppAddr(), jid);
+    return add_utf8_san(context, tbs, &asn1_oid_id_pkix_on_xmppAddr, jid);
 }
=20
=20
@@ -786,8 +782,9 @@
=20
     memset(&gn, 0, sizeof(gn));
     gn.element =3D choice_GeneralName_dNSName;
-    gn.u.dNSName =3D rk_UNCONST(dnsname);
-   =20
+    gn.u.dNSName.data =3D rk_UNCONST(dnsname);
+    gn.u.dNSName.length =3D strlen(dnsname);
+
     return add_GeneralNames(&tbs->san, &gn);
 }
=20
@@ -813,8 +810,9 @@
=20
     memset(&gn, 0, sizeof(gn));
     gn.element =3D choice_GeneralName_rfc822Name;
-    gn.u.rfc822Name =3D rk_UNCONST(rfc822Name);
-   =20
+    gn.u.rfc822Name.data =3D rk_UNCONST(rfc822Name);
+    gn.u.rfc822Name.length =3D strlen(rfc822Name);
+
     return add_GeneralNames(&tbs->san, &gn);
 }
=20
@@ -841,6 +839,50 @@
 }
=20
 /**
+ * Set the issuerUniqueID and subjectUniqueID
+ *
+ * These are only supposed to be used considered with version 2
+ * certificates, replaced by the two extensions SubjectKeyIdentifier
+ * and IssuerKeyIdentifier. This function is to allow application
+ * using legacy protocol to issue them.
+ *
+ * @param context A hx509 context.
+ * @param tbs object to be signed.
+ * @param issuerUniqueID to be set
+ * @param subjectUniqueID to be set
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_ca
+ */
+
+int
+hx509_ca_tbs_set_unique(hx509_context context,
+			hx509_ca_tbs tbs,
+			const heim_bit_string *subjectUniqueID,
+			const heim_bit_string *issuerUniqueID)
+{
+    int ret;
+
+    der_free_bit_string(&tbs->subjectUniqueID);
+    der_free_bit_string(&tbs->issuerUniqueID);
+
+    if (subjectUniqueID) {
+	ret =3D der_copy_bit_string(subjectUniqueID, &tbs->subjectUniqueID);
+	if (ret)
+	    return ret;
+    }
+
+    if (issuerUniqueID) {
+	ret =3D der_copy_bit_string(issuerUniqueID, &tbs->issuerUniqueID);
+	if (ret)
+	    return ret;
+    }
+
+    return 0;
+}
+
+/**
  * Expand the the subject name in the to-be-signed certificate object
  * using hx509_name_expand().
  *
@@ -862,6 +904,10 @@
     return hx509_name_expand(context, tbs->subject, env);
 }
=20
+/*
+ *
+ */
+
 static int
 add_extension(hx509_context context,
 	      TBSCertificate *tbsc,
@@ -926,7 +972,7 @@
 	return ENOMEM;
     }
     /* prefix with CN=3D<ts>,...*/
-    ret =3D _hx509_name_modify(context, subject, 1, oid_id_at_commonName()=
, tstr);
+    ret =3D _hx509_name_modify(context, subject, 1, &asn1_oid_id_at_common=
Name, tstr);
     free(tstr);
     if (ret)
 	free_Name(subject);
@@ -1005,7 +1051,7 @@
 	    return EINVAL;
 	}
 	if (hx509_name_is_null_p(tbs->subject) && tbs->san.len =3D=3D 0) {
-	    hx509_set_error_string(context, 0, EINVAL,=20
+	    hx509_set_error_string(context, 0, EINVAL,
 				   "NULL subject and no SubjectAltNames");
 	    return EINVAL;
 	}
@@ -1017,7 +1063,7 @@
     }
     if (tbs->flags.proxy) {
 	if (tbs->san.len > 0) {
-	    hx509_set_error_string(context, 0, EINVAL,=20
+	    hx509_set_error_string(context, 0, EINVAL,
 				   "Proxy certificate is not allowed "
 				   "to have SubjectAltNames");
 	    return EINVAL;
@@ -1091,7 +1137,35 @@
 	goto out;
     }
     /* issuerUniqueID  [1]  IMPLICIT BIT STRING OPTIONAL */
+    if (tbs->issuerUniqueID.length) {
+	tbsc->issuerUniqueID =3D calloc(1, sizeof(*tbsc->issuerUniqueID));
+	if (tbsc->issuerUniqueID =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    hx509_set_error_string(context, 0, ret, "Out of memory");
+	    goto out;
+	}
+	ret =3D der_copy_bit_string(&tbs->issuerUniqueID, tbsc->issuerUniqueID);
+	if (ret) {
+	    hx509_set_error_string(context, 0, ret, "Out of memory");
+	    goto out;
+	}
+    }
     /* subjectUniqueID [2]  IMPLICIT BIT STRING OPTIONAL */
+    if (tbs->subjectUniqueID.length) {
+	tbsc->subjectUniqueID =3D calloc(1, sizeof(*tbsc->subjectUniqueID));
+	if (tbsc->subjectUniqueID =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    hx509_set_error_string(context, 0, ret, "Out of memory");
+	    goto out;
+	}
+
+	ret =3D der_copy_bit_string(&tbs->subjectUniqueID, tbsc->subjectUniqueID);
+	if (ret) {
+	    hx509_set_error_string(context, 0, ret, "Out of memory");
+	    goto out;
+	}
+    }
+
     /* extensions      [3]  EXPLICIT Extensions OPTIONAL */
     tbsc->extensions =3D calloc(1, sizeof(*tbsc->extensions));
     if (tbsc->extensions =3D=3D NULL) {
@@ -1099,7 +1173,7 @@
 	hx509_set_error_string(context, 0, ret, "Out of memory");
 	goto out;
     }
-   =20
+
     /* Add the text BMP string Domaincontroller to the cert */
     if (tbs->flags.domaincontroller) {
 	data.data =3D rk_UNCONST("\x1e\x20\x00\x44\x00\x6f\x00\x6d"
@@ -1110,7 +1184,7 @@
 	data.length =3D 34;
=20
 	ret =3D add_extension(context, tbsc, 0,
-			    oid_id_ms_cert_enroll_domaincontroller(),
+			    &asn1_oid_id_ms_cert_enroll_domaincontroller,
 			    &data);
 	if (ret)
 	    goto out;
@@ -1129,7 +1203,7 @@
 	if (size !=3D data.length)
 	    _hx509_abort("internal ASN.1 encoder error");
 	ret =3D add_extension(context, tbsc, 1,
-			    oid_id_x509_ce_keyUsage(), &data);
+			    &asn1_oid_id_x509_ce_keyUsage, &data);
 	free(data.data);
 	if (ret)
 	    goto out;
@@ -1137,7 +1211,7 @@
=20
     /* add ExtendedKeyUsage */
     if (tbs->eku.len > 0) {
-	ASN1_MALLOC_ENCODE(ExtKeyUsage, data.data, data.length,=20
+	ASN1_MALLOC_ENCODE(ExtKeyUsage, data.data, data.length,
 			   &tbs->eku, &size, ret);
 	if (ret) {
 	    hx509_set_error_string(context, 0, ret, "Out of memory");
@@ -1146,7 +1220,7 @@
 	if (size !=3D data.length)
 	    _hx509_abort("internal ASN.1 encoder error");
 	ret =3D add_extension(context, tbsc, 0,
-			    oid_id_x509_ce_extKeyUsage(), &data);
+			    &asn1_oid_id_x509_ce_extKeyUsage, &data);
 	free(data.data);
 	if (ret)
 	    goto out;
@@ -1154,7 +1228,7 @@
=20
     /* add Subject Alternative Name */
     if (tbs->san.len > 0) {
-	ASN1_MALLOC_ENCODE(GeneralNames, data.data, data.length,=20
+	ASN1_MALLOC_ENCODE(GeneralNames, data.data, data.length,
 			   &tbs->san, &size, ret);
 	if (ret) {
 	    hx509_set_error_string(context, 0, ret, "Out of memory");
@@ -1163,7 +1237,7 @@
 	if (size !=3D data.length)
 	    _hx509_abort("internal ASN.1 encoder error");
 	ret =3D add_extension(context, tbsc, 0,
-			    oid_id_x509_ce_subjectAltName(),
+			    &asn1_oid_id_x509_ce_subjectAltName,
 			    &data);
 	free(data.data);
 	if (ret)
@@ -1172,7 +1246,7 @@
=20
     /* Add Authority Key Identifier */
     if (ai) {
-	ASN1_MALLOC_ENCODE(AuthorityKeyIdentifier, data.data, data.length,=20
+	ASN1_MALLOC_ENCODE(AuthorityKeyIdentifier, data.data, data.length,
 			   ai, &size, ret);
 	if (ret) {
 	    hx509_set_error_string(context, 0, ret, "Out of memory");
@@ -1181,7 +1255,7 @@
 	if (size !=3D data.length)
 	    _hx509_abort("internal ASN.1 encoder error");
 	ret =3D add_extension(context, tbsc, 0,
-			    oid_id_x509_ce_authorityKeyIdentifier(),
+			    &asn1_oid_id_x509_ce_authorityKeyIdentifier,
 			    &data);
 	free(data.data);
 	if (ret)
@@ -1194,18 +1268,20 @@
 	unsigned char hash[SHA_DIGEST_LENGTH];
=20
 	{
-	    SHA_CTX m;
-	   =20
-	    SHA1_Init(&m);
-	    SHA1_Update(&m, tbs->spki.subjectPublicKey.data,
-			tbs->spki.subjectPublicKey.length / 8);
-	    SHA1_Final (hash, &m);
+	    EVP_MD_CTX *ctx;
+
+	    ctx =3D EVP_MD_CTX_create();
+	    EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
+	    EVP_DigestUpdate(ctx, tbs->spki.subjectPublicKey.data,
+			     tbs->spki.subjectPublicKey.length / 8);
+	    EVP_DigestFinal_ex(ctx, hash, NULL);
+	    EVP_MD_CTX_destroy(ctx);
 	}
=20
 	si.data =3D hash;
 	si.length =3D sizeof(hash);
=20
-	ASN1_MALLOC_ENCODE(SubjectKeyIdentifier, data.data, data.length,=20
+	ASN1_MALLOC_ENCODE(SubjectKeyIdentifier, data.data, data.length,
 			   &si, &size, ret);
 	if (ret) {
 	    hx509_set_error_string(context, 0, ret, "Out of memory");
@@ -1214,18 +1290,18 @@
 	if (size !=3D data.length)
 	    _hx509_abort("internal ASN.1 encoder error");
 	ret =3D add_extension(context, tbsc, 0,
-			    oid_id_x509_ce_subjectKeyIdentifier(),
+			    &asn1_oid_id_x509_ce_subjectKeyIdentifier,
 			    &data);
 	free(data.data);
 	if (ret)
 	    goto out;
     }
=20
-    /* Add BasicConstraints */=20
+    /* Add BasicConstraints */
     {
 	BasicConstraints bc;
 	int aCA =3D 1;
-	uint32_t path;
+	unsigned int path;
=20
 	memset(&bc, 0, sizeof(bc));
=20
@@ -1237,7 +1313,7 @@
 	    }
 	}
=20
-	ASN1_MALLOC_ENCODE(BasicConstraints, data.data, data.length,=20
+	ASN1_MALLOC_ENCODE(BasicConstraints, data.data, data.length,
 			   &bc, &size, ret);
 	if (ret) {
 	    hx509_set_error_string(context, 0, ret, "Out of memory");
@@ -1247,7 +1323,7 @@
 	    _hx509_abort("internal ASN.1 encoder error");
 	/* Critical if this is a CA */
 	ret =3D add_extension(context, tbsc, tbs->flags.ca,
-			    oid_id_x509_ce_basicConstraints(),
+			    &asn1_oid_id_x509_ce_basicConstraints,
 			    &data);
 	free(data.data);
 	if (ret)
@@ -1261,7 +1337,7 @@
 	memset(&info, 0, sizeof(info));
=20
 	if (tbs->pathLenConstraint >=3D 0) {
-	    info.pCPathLenConstraint =3D=20
+	    info.pCPathLenConstraint =3D
 		malloc(sizeof(*info.pCPathLenConstraint));
 	    if (info.pCPathLenConstraint =3D=3D NULL) {
 		ret =3D ENOMEM;
@@ -1271,7 +1347,7 @@
 	    *info.pCPathLenConstraint =3D tbs->pathLenConstraint;
 	}
=20
-	ret =3D der_copy_oid(oid_id_pkix_ppl_inheritAll(),
+	ret =3D der_copy_oid(&asn1_oid_id_pkix_ppl_inheritAll,
 			   &info.proxyPolicy.policyLanguage);
 	if (ret) {
 	    free_ProxyCertInfo(&info);
@@ -1279,7 +1355,7 @@
 	    goto out;
 	}
=20
-	ASN1_MALLOC_ENCODE(ProxyCertInfo, data.data, data.length,=20
+	ASN1_MALLOC_ENCODE(ProxyCertInfo, data.data, data.length,
 			   &info, &size, ret);
 	free_ProxyCertInfo(&info);
 	if (ret) {
@@ -1289,7 +1365,7 @@
 	if (size !=3D data.length)
 	    _hx509_abort("internal ASN.1 encoder error");
 	ret =3D add_extension(context, tbsc, 0,
-			    oid_id_pkix_pe_proxyCertInfo(),
+			    &asn1_oid_id_pkix_pe_proxyCertInfo,
 			    &data);
 	free(data.data);
 	if (ret)
@@ -1307,7 +1383,7 @@
 	if (size !=3D data.length)
 	    _hx509_abort("internal ASN.1 encoder error");
 	ret =3D add_extension(context, tbsc, FALSE,
-			    oid_id_x509_ce_cRLDistributionPoints(),
+			    &asn1_oid_id_x509_ce_cRLDistributionPoints,
 			    &data);
 	free(data.data);
 	if (ret)
@@ -1377,14 +1453,14 @@
 	memset(&gns, 0, sizeof(gns));
 	memset(&name, 0, sizeof(name));
=20
-	ai->authorityCertIssuer =3D=20
+	ai->authorityCertIssuer =3D
 	    calloc(1, sizeof(*ai->authorityCertIssuer));
 	if (ai->authorityCertIssuer =3D=3D NULL) {
 	    ret =3D ENOMEM;
 	    hx509_set_error_string(context, 0, ret, "Out of memory");
 	    goto out;
 	}
-	ai->authorityCertSerialNumber =3D=20
+	ai->authorityCertSerialNumber =3D
 	    calloc(1, sizeof(*ai->authorityCertSerialNumber));
 	if (ai->authorityCertSerialNumber =3D=3D NULL) {
 	    ret =3D ENOMEM;
@@ -1392,22 +1468,21 @@
 	    goto out;
 	}
=20
-	/*=20
+	/*
 	 * XXX unbreak when asn1 compiler handle IMPLICIT
 	 *
 	 * This is so horrible.
 	 */
=20
 	ret =3D copy_Name(&certificate->tbsCertificate.subject, &name);
-	if (ai->authorityCertSerialNumber =3D=3D NULL) {
-	    ret =3D ENOMEM;
+	if (ret) {
 	    hx509_set_error_string(context, 0, ret, "Out of memory");
 	    goto out;
 	}
=20
 	memset(&gn, 0, sizeof(gn));
 	gn.element =3D choice_GeneralName_directoryName;
-	gn.u.directoryName.element =3D=20
+	gn.u.directoryName.element =3D
 	    choice_GeneralName_directoryName_rdnSequence;
 	gn.u.directoryName.u.rdnSequence =3D name.u.rdnSequence;
=20
@@ -1436,7 +1511,7 @@
=20
=20
 /**
- * Sign a to-be-signed certificate object with a issuer certificate.=20
+ * Sign a to-be-signed certificate object with a issuer certificate.
  *
  * The caller needs to at least have called the following functions on the
  * to-be-signed certificate object:
@@ -1478,7 +1553,7 @@
 	goto out;
=20
     ret =3D ca_sign(context,
-		  tbs,=20
+		  tbs,
 		  _hx509_cert_private_key(signer),
 		  &ai,
 		  &signer_cert->tbsCertificate.subject,
@@ -1510,7 +1585,7 @@
 		   hx509_cert *certificate)
 {
     return ca_sign(context,
-		   tbs,=20
+		   tbs,
 		   signer,
 		   NULL,
 		   NULL,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/cert.c
--- a/head/crypto/heimdal/lib/hx509/cert.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/cert.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: cert.c 22450 2008-01-15 19:39:14Z lha $");
 #include "crypto-headers.h"
 #include <rtbl.h>
=20
@@ -59,6 +58,7 @@
 #define HX509_VERIFY_CTX_F_REQUIRE_RFC3280		4
 #define HX509_VERIFY_CTX_F_CHECK_TRUST_ANCHORS		8
 #define HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS		16
+#define HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK		32
     time_t time_now;
     unsigned int max_depth;
 #define HX509_VERIFY_MAX_DEPTH 30
@@ -138,10 +138,10 @@
=20
 /**
  * Selects if the hx509_revoke_verify() function is going to require
- * the existans of a revokation method (OSCP, CRL) or not. Note that
+ * the existans of a revokation method (OCSP, CRL) or not. Note that
  * hx509_verify_path(), hx509_cms_verify_signed(), and other function
  * call hx509_revoke_verify().
- *=20
+ *
  * @param context hx509 context to change the flag for.
  * @param flag zero, revokation method required, non zero missing
  * revokation method ok
@@ -160,7 +160,7 @@
=20
 /**
  * Free the context allocated by hx509_context_init().
- *=20
+ *
  * @param context context to be freed.
  *
  * @ingroup hx509
@@ -205,7 +205,7 @@
=20
 /**
  * Allocate and init an hx509 certificate object from the decoded
- * certificate `c=B4.
+ * certificate `c=C2=B4.
  *
  * @param context A hx509 context.
  * @param c
@@ -268,7 +268,7 @@
  */
=20
 int
-hx509_cert_init_data(hx509_context context,=20
+hx509_cert_init_data(hx509_context context,
 		     const void *ptr,
 		     size_t len,
 		     hx509_cert *cert)
@@ -283,6 +283,7 @@
 	return ret;
     }
     if (size !=3D len) {
+	free_Certificate(&t);
 	hx509_set_error_string(context, 0, HX509_EXTRA_DATA_AFTER_STRUCTURE,
 			       "Extra data after certificate");
 	return HX509_EXTRA_DATA_AFTER_STRUCTURE;
@@ -294,7 +295,7 @@
 }
=20
 void
-_hx509_cert_set_release(hx509_cert cert,=20
+_hx509_cert_set_release(hx509_cert cert,
 			_hx509_cert_release_func release,
 			void *ctx)
 {
@@ -309,7 +310,7 @@
 _hx509_cert_assign_key(hx509_cert cert, hx509_private_key private_key)
 {
     if (cert->private_key)
-	_hx509_private_key_free(&cert->private_key);
+	hx509_private_key_free(&cert->private_key);
     cert->private_key =3D _hx509_private_key_ref(private_key);
     return 0;
 }
@@ -326,7 +327,7 @@
 void
 hx509_cert_free(hx509_cert cert)
 {
-    int i;
+    size_t i;
=20
     if (cert =3D=3D NULL)
 	return;
@@ -340,7 +341,7 @@
 	(cert->release)(cert, cert->ctx);
=20
     if (cert->private_key)
-	_hx509_private_key_free(&cert->private_key);
+	hx509_private_key_free(&cert->private_key);
=20
     free_Certificate(cert->data);
     free(cert->data);
@@ -354,7 +355,7 @@
     free(cert->friendlyname);
     if (cert->basename)
 	hx509_name_free(&cert->basename);
-    memset(cert, 0, sizeof(cert));
+    memset(cert, 0, sizeof(*cert));
     free(cert);
 }
=20
@@ -383,7 +384,7 @@
=20
 /**
  * Allocate an verification context that is used fo control the
- * verification process.=20
+ * verification process.
  *
  * @param context A hx509 context.
  * @param ctx returns a pointer to a hx509_verify_ctx object.
@@ -405,7 +406,7 @@
     c->max_depth =3D HX509_VERIFY_MAX_DEPTH;
=20
     *ctx =3D c;
-   =20
+
     return 0;
 }
=20
@@ -432,6 +433,7 @@
  * Set the trust anchors in the verification context, makes an
  * reference to the keyset, so the consumer can free the keyset
  * independent of the destruction of the verification context (ctx).
+ * If there already is a keyset attached, it's released.
  *
  * @param ctx a verification context
  * @param set a keyset containing the trust anchors.
@@ -442,7 +444,9 @@
 void
 hx509_verify_attach_anchors(hx509_verify_ctx ctx, hx509_certs set)
 {
-    ctx->trust_anchors =3D _hx509_certs_ref(set);
+    if (ctx->trust_anchors)
+	hx509_certs_free(&ctx->trust_anchors);
+    ctx->trust_anchors =3D hx509_certs_ref(set);
 }
=20
 /**
@@ -485,6 +489,12 @@
     ctx->time_now =3D t;
 }
=20
+time_t
+_hx509_verify_get_time(hx509_verify_ctx ctx)
+{
+    return ctx->time_now;
+}
+
 /**
  * Set the maximum depth of the certificate chain that the path
  * builder is going to try.
@@ -563,14 +573,24 @@
 	ctx->flags |=3D HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS;
 }
=20
+void
+hx509_verify_ctx_f_allow_best_before_signature_algs(hx509_context ctx,
+						    int boolean)
+{
+    if (boolean)
+	ctx->flags &=3D ~HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK;
+    else
+	ctx->flags |=3D HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK;
+}
+
 static const Extension *
-find_extension(const Certificate *cert, const heim_oid *oid, int *idx)
+find_extension(const Certificate *cert, const heim_oid *oid, size_t *idx)
 {
     const TBSCertificate *c =3D &cert->tbsCertificate;
=20
     if (c->version =3D=3D NULL || *c->version < 2 || c->extensions =3D=3D =
NULL)
 	return NULL;
-   =20
+
     for (;*idx < c->extensions->len; (*idx)++) {
 	if (der_heim_oid_cmp(&c->extensions->val[*idx].extnID, oid) =3D=3D 0)
 	    return &c->extensions->val[(*idx)++];
@@ -579,21 +599,21 @@
 }
=20
 static int
-find_extension_auth_key_id(const Certificate *subject,=20
+find_extension_auth_key_id(const Certificate *subject,
 			   AuthorityKeyIdentifier *ai)
 {
     const Extension *e;
     size_t size;
-    int i =3D 0;
+    size_t i =3D 0;
=20
     memset(ai, 0, sizeof(*ai));
=20
-    e =3D find_extension(subject, oid_id_x509_ce_authorityKeyIdentifier(),=
 &i);
+    e =3D find_extension(subject, &asn1_oid_id_x509_ce_authorityKeyIdentif=
ier, &i);
     if (e =3D=3D NULL)
 	return HX509_EXTENSION_NOT_FOUND;
-   =20
-    return decode_AuthorityKeyIdentifier(e->extnValue.data,=20
-					 e->extnValue.length,=20
+
+    return decode_AuthorityKeyIdentifier(e->extnValue.data,
+					 e->extnValue.length,
 					 ai, &size);
 }
=20
@@ -603,40 +623,40 @@
 {
     const Extension *e;
     size_t size;
-    int i =3D 0;
+    size_t i =3D 0;
=20
     memset(si, 0, sizeof(*si));
=20
-    e =3D find_extension(issuer, oid_id_x509_ce_subjectKeyIdentifier(), &i=
);
+    e =3D find_extension(issuer, &asn1_oid_id_x509_ce_subjectKeyIdentifier=
, &i);
     if (e =3D=3D NULL)
 	return HX509_EXTENSION_NOT_FOUND;
-   =20
-    return decode_SubjectKeyIdentifier(e->extnValue.data,=20
+
+    return decode_SubjectKeyIdentifier(e->extnValue.data,
 				       e->extnValue.length,
 				       si, &size);
 }
=20
 static int
-find_extension_name_constraints(const Certificate *subject,=20
+find_extension_name_constraints(const Certificate *subject,
 				NameConstraints *nc)
 {
     const Extension *e;
     size_t size;
-    int i =3D 0;
+    size_t i =3D 0;
=20
     memset(nc, 0, sizeof(*nc));
=20
-    e =3D find_extension(subject, oid_id_x509_ce_nameConstraints(), &i);
+    e =3D find_extension(subject, &asn1_oid_id_x509_ce_nameConstraints, &i=
);
     if (e =3D=3D NULL)
 	return HX509_EXTENSION_NOT_FOUND;
-   =20
-    return decode_NameConstraints(e->extnValue.data,=20
-				  e->extnValue.length,=20
+
+    return decode_NameConstraints(e->extnValue.data,
+				  e->extnValue.length,
 				  nc, &size);
 }
=20
 static int
-find_extension_subject_alt_name(const Certificate *cert, int *i,
+find_extension_subject_alt_name(const Certificate *cert, size_t *i,
 				GeneralNames *sa)
 {
     const Extension *e;
@@ -644,11 +664,11 @@
=20
     memset(sa, 0, sizeof(*sa));
=20
-    e =3D find_extension(cert, oid_id_x509_ce_subjectAltName(), i);
+    e =3D find_extension(cert, &asn1_oid_id_x509_ce_subjectAltName, i);
     if (e =3D=3D NULL)
 	return HX509_EXTENSION_NOT_FOUND;
-   =20
-    return decode_GeneralNames(e->extnValue.data,=20
+
+    return decode_GeneralNames(e->extnValue.data,
 			       e->extnValue.length,
 			       sa, &size);
 }
@@ -658,15 +678,15 @@
 {
     const Extension *e;
     size_t size;
-    int i =3D 0;
+    size_t i =3D 0;
=20
     memset(eku, 0, sizeof(*eku));
=20
-    e =3D find_extension(cert, oid_id_x509_ce_extKeyUsage(), &i);
+    e =3D find_extension(cert, &asn1_oid_id_x509_ce_extKeyUsage, &i);
     if (e =3D=3D NULL)
 	return HX509_EXTENSION_NOT_FOUND;
-   =20
-    return decode_ExtKeyUsage(e->extnValue.data,=20
+
+    return decode_ExtKeyUsage(e->extnValue.data,
 			      e->extnValue.length,
 			      eku, &size);
 }
@@ -700,7 +720,7 @@
 void
 hx509_free_octet_string_list(hx509_octet_string_list *list)
 {
-    int i;
+    size_t i;
     for (i =3D 0; i < list->len; i++)
 	der_free_octet_string(&list->val[i]);
     free(list->val);
@@ -710,7 +730,7 @@
=20
 /**
  * Return a list of subjectAltNames specified by oid in the
- * certificate. On error the=20
+ * certificate. On error the
  *
  * The returned list of octet string should be freed with
  * hx509_free_octet_string_list().
@@ -732,7 +752,8 @@
 					 hx509_octet_string_list *list)
 {
     GeneralNames sa;
-    int ret, i, j;
+    int ret;
+    size_t i, j;
=20
     list->val =3D NULL;
     list->len =3D 0;
@@ -742,8 +763,7 @@
 	ret =3D find_extension_subject_alt_name(_hx509_get_cert(cert), &i, &sa);
 	i++;
 	if (ret =3D=3D HX509_EXTENSION_NOT_FOUND) {
-	    ret =3D 0;
-	    break;
+	    return 0;
 	} else if (ret !=3D 0) {
 	    hx509_set_error_string(context, 0, ret, "Error searching for SAN");
 	    hx509_free_octet_string_list(list);
@@ -752,11 +772,11 @@
=20
 	for (j =3D 0; j < sa.len; j++) {
 	    if (sa.val[j].element =3D=3D choice_GeneralName_otherName &&
-		der_heim_oid_cmp(&sa.val[j].u.otherName.type_id, oid) =3D=3D 0)=20
+		der_heim_oid_cmp(&sa.val[j].u.otherName.type_id, oid) =3D=3D 0)
 	    {
 		ret =3D add_to_list(list, &sa.val[j].u.otherName.value);
 		if (ret) {
-		    hx509_set_error_string(context, 0, ret,=20
+		    hx509_set_error_string(context, 0, ret,
 					   "Error adding an exra SAN to "
 					   "return list");
 		    hx509_free_octet_string_list(list);
@@ -767,24 +787,24 @@
 	}
 	free_GeneralNames(&sa);
     }
-    return 0;
 }
=20
=20
 static int
-check_key_usage(hx509_context context, const Certificate *cert,=20
+check_key_usage(hx509_context context, const Certificate *cert,
 		unsigned flags, int req_present)
 {
     const Extension *e;
     KeyUsage ku;
     size_t size;
-    int ret, i =3D 0;
+    int ret;
+    size_t i =3D 0;
     unsigned ku_flags;
=20
     if (_hx509_cert_get_version(cert) < 3)
 	return 0;
=20
-    e =3D find_extension(cert, oid_id_x509_ce_keyUsage(), &i);
+    e =3D find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i);
     if (e =3D=3D NULL) {
 	if (req_present) {
 	    hx509_set_error_string(context, 0, HX509_KU_CERT_MISSING,
@@ -794,7 +814,7 @@
 	}
 	return 0;
     }
-   =20
+
     ret =3D decode_KeyUsage(e->extnValue.data, e->extnValue.length, &ku, &=
size);
     if (ret)
 	return ret;
@@ -821,7 +841,7 @@
  */
=20
 int
-_hx509_check_key_usage(hx509_context context, hx509_cert cert,=20
+_hx509_check_key_usage(hx509_context context, hx509_cert cert,
 		       unsigned flags, int req_present)
 {
     return check_key_usage(context, _hx509_get_cert(cert), flags, req_pres=
ent);
@@ -830,18 +850,19 @@
 enum certtype { PROXY_CERT, EE_CERT, CA_CERT };
=20
 static int
-check_basic_constraints(hx509_context context, const Certificate *cert,=20
-			enum certtype type, int depth)
+check_basic_constraints(hx509_context context, const Certificate *cert,
+			enum certtype type, size_t depth)
 {
     BasicConstraints bc;
     const Extension *e;
     size_t size;
-    int ret, i =3D 0;
+    int ret;
+    size_t i =3D 0;
=20
     if (_hx509_cert_get_version(cert) < 3)
 	return 0;
=20
-    e =3D find_extension(cert, oid_id_x509_ce_basicConstraints(), &i);
+    e =3D find_extension(cert, &asn1_oid_id_x509_ce_basicConstraints, &i);
     if (e =3D=3D NULL) {
 	switch(type) {
 	case PROXY_CERT:
@@ -859,8 +880,8 @@
 	}
 	}
     }
-   =20
-    ret =3D decode_BasicConstraints(e->extnValue.data,=20
+
+    ret =3D decode_BasicConstraints(e->extnValue.data,
 				  e->extnValue.length, &bc,
 				  &size);
     if (ret)
@@ -893,13 +914,16 @@
     int diff;
     AuthorityKeyIdentifier ai;
     SubjectKeyIdentifier si;
-    int ret_ai, ret_si;
-
-    diff =3D _hx509_name_cmp(&issuer->tbsCertificate.subject,=20
-			   &subject->tbsCertificate.issuer);
+    int ret_ai, ret_si, ret;
+
+    ret =3D _hx509_name_cmp(&issuer->tbsCertificate.subject,
+			  &subject->tbsCertificate.issuer,
+			  &diff);
+    if (ret)
+	return ret;
     if (diff)
 	return diff;
-   =20
+
     memset(&ai, 0, sizeof(ai));
     memset(&si, 0, sizeof(si));
=20
@@ -928,7 +952,7 @@
 	    goto out;
 	}
     }
-   =20
+
     if (ai.keyIdentifier =3D=3D NULL) {
 	Name name;
=20
@@ -937,7 +961,7 @@
 	if (ai.authorityCertSerialNumber =3D=3D NULL)
 	    return -1;
=20
-	diff =3D der_heim_integer_cmp(ai.authorityCertSerialNumber,=20
+	diff =3D der_heim_integer_cmp(ai.authorityCertSerialNumber,
 				    &issuer->tbsCertificate.serialNumber);
 	if (diff)
 	    return diff;
@@ -945,14 +969,17 @@
 	    return -1;
 	if (ai.authorityCertIssuer->val[0].element !=3D choice_GeneralName_direct=
oryName)
 	    return -1;
-=09
-	name.element =3D=20
+
+	name.element =3D
 	    ai.authorityCertIssuer->val[0].u.directoryName.element;
-	name.u.rdnSequence =3D=20
+	name.u.rdnSequence =3D
 	    ai.authorityCertIssuer->val[0].u.directoryName.u.rdnSequence;
=20
-	diff =3D _hx509_name_cmp(&issuer->tbsCertificate.subject,=20
-			       &name);
+	ret =3D _hx509_name_cmp(&issuer->tbsCertificate.subject,
+			      &name,
+			      &diff);
+	if (ret)
+	    return ret;
 	if (diff)
 	    return diff;
 	diff =3D 0;
@@ -991,10 +1018,21 @@
 }
=20
 static int
-certificate_is_self_signed(const Certificate *cert)
+certificate_is_self_signed(hx509_context context,
+			   const Certificate *cert,
+			   int *self_signed)
 {
-    return _hx509_name_cmp(&cert->tbsCertificate.subject,=20
-			   &cert->tbsCertificate.issuer) =3D=3D 0;
+    int ret, diff;
+    ret =3D _hx509_name_cmp(&cert->tbsCertificate.subject,
+			  &cert->tbsCertificate.issuer, &diff);
+    *self_signed =3D (diff =3D=3D 0);
+    if (ret) {
+	hx509_set_error_string(context, 0, ret,
+			       "Failed to check if self signed");
+    } else
+	ret =3D _hx509_self_signed_valid(context, &cert->signatureAlgorithm);
+
+    return ret;
 }
=20
 /*
@@ -1013,7 +1051,7 @@
 	    time_t time_now,
 	    hx509_certs trust_anchors,
 	    hx509_path *path,
-	    hx509_certs pool,=20
+	    hx509_certs pool,
 	    hx509_cert current,
 	    hx509_cert *parent)
 {
@@ -1023,7 +1061,7 @@
=20
     *parent =3D NULL;
     memset(&ai, 0, sizeof(ai));
-   =20
+
     _hx509_query_clear(&q);
=20
     if (!subject_null_p(current->data)) {
@@ -1088,7 +1126,7 @@
 	    hx509_clear_error_string(context);
 	    return HX509_ISSUER_NOT_FOUND;
 	}
-=09
+
 	hx509_set_error_string(context, 0, HX509_ISSUER_NOT_FOUND,
 			       "Failed to find issuer for "
 			       "certificate with subject: '%s'", str);
@@ -1102,26 +1140,27 @@
  */
=20
 static int
-is_proxy_cert(hx509_context context,=20
-	      const Certificate *cert,=20
+is_proxy_cert(hx509_context context,
+	      const Certificate *cert,
 	      ProxyCertInfo *rinfo)
 {
     ProxyCertInfo info;
     const Extension *e;
     size_t size;
-    int ret, i =3D 0;
+    int ret;
+    size_t i =3D 0;
=20
     if (rinfo)
 	memset(rinfo, 0, sizeof(*rinfo));
=20
-    e =3D find_extension(cert, oid_id_pkix_pe_proxyCertInfo(), &i);
+    e =3D find_extension(cert, &asn1_oid_id_pkix_pe_proxyCertInfo, &i);
     if (e =3D=3D NULL) {
 	hx509_clear_error_string(context);
 	return HX509_EXTENSION_NOT_FOUND;
     }
=20
-    ret =3D decode_ProxyCertInfo(e->extnValue.data,=20
-			       e->extnValue.length,=20
+    ret =3D decode_ProxyCertInfo(e->extnValue.data,
+			       e->extnValue.length,
 			       &info,
 			       &size);
     if (ret) {
@@ -1131,7 +1170,7 @@
     if (size !=3D e->extnValue.length) {
 	free_ProxyCertInfo(&info);
 	hx509_clear_error_string(context);
-	return HX509_EXTRA_DATA_AFTER_STRUCTURE;=20
+	return HX509_EXTRA_DATA_AFTER_STRUCTURE;
     }
     if (rinfo =3D=3D NULL)
 	free_ProxyCertInfo(&info);
@@ -1167,7 +1206,7 @@
 _hx509_path_free(hx509_path *path)
 {
     unsigned i;
-   =20
+
     for (i =3D 0; i < path->len; i++)
 	hx509_cert_free(path->val[i]);
     free(path->val);
@@ -1188,7 +1227,7 @@
  * The path includes a path from the top certificate to the anchor
  * certificate.
  *
- * The caller needs to free `path=B4 both on successful built path and
+ * The caller needs to free `path=C2=B4 both on successful built path and
  * failure.
  */
=20
@@ -1216,7 +1255,7 @@
=20
     while (!certificate_is_anchor(context, anchors, current)) {
=20
-	ret =3D find_parent(context, time_now, anchors, path,=20
+	ret =3D find_parent(context, time_now, anchors, path,
 			  pool, current, &parent);
 	hx509_cert_free(current);
 	if (ret)
@@ -1236,8 +1275,8 @@
 	}
     }
=20
-    if ((flags & HX509_CALCULATE_PATH_NO_ANCHOR) &&=20
-	path->len > 0 &&=20
+    if ((flags & HX509_CALCULATE_PATH_NO_ANCHOR) &&
+	path->len > 0 &&
 	certificate_is_anchor(context, anchors, path->val[path->len - 1]))
     {
 	hx509_cert_free(path->val[path->len - 1]);
@@ -1277,7 +1316,7 @@
     diff =3D der_heim_bit_string_cmp(&p->signatureValue, &q->signatureValu=
e);
     if (diff)
 	return diff;
-    diff =3D _hx509_AlgorithmIdentifier_cmp(&p->signatureAlgorithm,=20
+    diff =3D _hx509_AlgorithmIdentifier_cmp(&p->signatureAlgorithm,
 					  &q->signatureAlgorithm);
     if (diff)
 	return diff;
@@ -1452,7 +1491,9 @@
  * @param context a hx509 context.
  * @param p a hx509 certificate object.
  * @param alg AlgorithmIdentifier, should be freed with
- * free_AlgorithmIdentifier().
+ *            free_AlgorithmIdentifier(). The algorithmidentifier is
+ *            typicly rsaEncryption, or id-ecPublicKey, or some other
+ *            public key mechanism.
  *
  * @return An hx509 error code, see hx509_get_error_string().
  *
@@ -1461,7 +1502,7 @@
=20
 int
 hx509_cert_get_SPKI_AlgorithmIdentifier(hx509_context context,
-					hx509_cert p,=20
+					hx509_cert p,
 					AlgorithmIdentifier *alg)
 {
     int ret;
@@ -1473,6 +1514,65 @@
     return ret;
 }
=20
+static int
+get_x_unique_id(hx509_context context, const char *name,
+		const heim_bit_string *cert, heim_bit_string *subject)
+{
+    int ret;
+
+    if (cert =3D=3D NULL) {
+	ret =3D HX509_EXTENSION_NOT_FOUND;
+	hx509_set_error_string(context, 0, ret, "%s unique id doesn't exists", na=
me);
+	return ret;
+    }
+    ret =3D der_copy_bit_string(cert, subject);
+    if (ret) {
+	hx509_set_error_string(context, 0, ret, "malloc out of memory", name);
+	return ret;
+    }
+    return 0;
+}
+
+/**
+ * Get a copy of the Issuer Unique ID
+ *
+ * @param context a hx509_context
+ * @param p a hx509 certificate
+ * @param issuer the issuer id returned, free with der_free_bit_string()
+ *
+ * @return An hx509 error code, see hx509_get_error_string(). The
+ * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate
+ * doesn't have a issuerUniqueID
+ *
+ * @ingroup hx509_cert
+ */
+
+int
+hx509_cert_get_issuer_unique_id(hx509_context context, hx509_cert p, heim_=
bit_string *issuer)
+{
+    return get_x_unique_id(context, "issuer", p->data->tbsCertificate.issu=
erUniqueID, issuer);
+}
+
+/**
+ * Get a copy of the Subect Unique ID
+ *
+ * @param context a hx509_context
+ * @param p a hx509 certificate
+ * @param subject the subject id returned, free with der_free_bit_string()
+ *
+ * @return An hx509 error code, see hx509_get_error_string(). The
+ * error code HX509_EXTENSION_NOT_FOUND is returned if the certificate
+ * doesn't have a subjectUniqueID
+ *
+ * @ingroup hx509_cert
+ */
+
+int
+hx509_cert_get_subject_unique_id(hx509_context context, hx509_cert p, heim=
_bit_string *subject)
+{
+    return get_x_unique_id(context, "subject", p->data->tbsCertificate.sub=
jectUniqueID, subject);
+}
+
=20
 hx509_private_key
 _hx509_cert_private_key(hx509_cert p)
@@ -1511,15 +1611,15 @@
 	return HX509_PRIVATE_KEY_MISSING;
     }
=20
-    return _hx509_private_key_private_decrypt(context,
+    return hx509_private_key_private_decrypt(context,
 					      ciphertext,
 					      encryption_oid,
-					      p->private_key,=20
+					      p->private_key,
 					      cleartext);
 }
=20
 int
-_hx509_cert_public_encrypt(hx509_context context,
+hx509_cert_public_encrypt(hx509_context context,
 			   const heim_octet_string *cleartext,
 			   const hx509_cert p,
 			   heim_oid *encryption_oid,
@@ -1599,15 +1699,20 @@
 match_RDN(const RelativeDistinguishedName *c,
 	  const RelativeDistinguishedName *n)
 {
-    int i;
+    size_t i;
=20
     if (c->len !=3D n->len)
 	return HX509_NAME_CONSTRAINT_ERROR;
-   =20
+
     for (i =3D 0; i < n->len; i++) {
+	int diff, ret;
+
 	if (der_heim_oid_cmp(&c->val[i].type, &n->val[i].type) !=3D 0)
 	    return HX509_NAME_CONSTRAINT_ERROR;
-	if (_hx509_name_ds_cmp(&c->val[i].value, &n->val[i].value) !=3D 0)
+	ret =3D _hx509_name_ds_cmp(&c->val[i].value, &n->val[i].value, &diff);
+	if (ret)
+	    return ret;
+	if (diff !=3D 0)
 	    return HX509_NAME_CONSTRAINT_ERROR;
     }
     return 0;
@@ -1616,7 +1721,8 @@
 static int
 match_X501Name(const Name *c, const Name *n)
 {
-    int i, ret;
+    size_t i;
+    int ret;
=20
     if (c->element !=3D choice_Name_rdnSequence
 	|| n->element !=3D choice_Name_rdnSequence)
@@ -1629,13 +1735,13 @@
 	    return ret;
     }
     return 0;
-}=20
+}
=20
=20
 static int
 match_general_name(const GeneralName *c, const GeneralName *n, int *match)
 {
-    /*=20
+    /*
      * Name constraints only apply to the same name type, see RFC3280,
      * 4.2.1.11.
      */
@@ -1654,19 +1760,20 @@
     case choice_GeneralName_rfc822Name: {
 	const char *s;
 	size_t len1, len2;
-	s =3D strchr(c->u.rfc822Name, '@');
+	s =3D memchr(c->u.rfc822Name.data, '@', c->u.rfc822Name.length);
 	if (s) {
-	    if (strcasecmp(c->u.rfc822Name, n->u.rfc822Name) !=3D 0)
+	    if (der_printable_string_cmp(&c->u.rfc822Name, &n->u.rfc822Name) !=3D=
 0)
 		return HX509_NAME_CONSTRAINT_ERROR;
 	} else {
-	    s =3D strchr(n->u.rfc822Name, '@');
+	    s =3D memchr(n->u.rfc822Name.data, '@', n->u.rfc822Name.length);
 	    if (s =3D=3D NULL)
 		return HX509_NAME_CONSTRAINT_ERROR;
-	    len1 =3D strlen(c->u.rfc822Name);
-	    len2 =3D strlen(s + 1);
+	    len1 =3D c->u.rfc822Name.length;
+	    len2 =3D n->u.rfc822Name.length -
+		(s - ((char *)n->u.rfc822Name.data));
 	    if (len1 > len2)
 		return HX509_NAME_CONSTRAINT_ERROR;
-	    if (strcasecmp(s + 1 + len2 - len1, c->u.rfc822Name) !=3D 0)
+	    if (memcmp(s + 1 + len2 - len1, c->u.rfc822Name.data, len1) !=3D 0)
 		return HX509_NAME_CONSTRAINT_ERROR;
 	    if (len1 < len2 && s[len2 - len1 + 1] !=3D '.')
 		return HX509_NAME_CONSTRAINT_ERROR;
@@ -1676,14 +1783,16 @@
     }
     case choice_GeneralName_dNSName: {
 	size_t lenc, lenn;
-
-	lenc =3D strlen(c->u.dNSName);
-	lenn =3D strlen(n->u.dNSName);
+	char *ptr;
+
+	lenc =3D c->u.dNSName.length;
+	lenn =3D n->u.dNSName.length;
 	if (lenc > lenn)
 	    return HX509_NAME_CONSTRAINT_ERROR;
-	if (strcasecmp(&n->u.dNSName[lenn - lenc], c->u.dNSName) !=3D 0)
+	ptr =3D n->u.dNSName.data;
+	if (memcmp(&ptr[lenn - lenc], c->u.dNSName.data, lenc) !=3D 0)
 	    return HX509_NAME_CONSTRAINT_ERROR;
-	if (lenc !=3D lenn && n->u.dNSName[lenn - lenc - 1] !=3D '.')
+	if (lenn !=3D lenc && ptr[lenn - lenc - 1] !=3D '.')
 	    return HX509_NAME_CONSTRAINT_ERROR;
 	*match =3D 1;
 	return 0;
@@ -1716,11 +1825,12 @@
 }
=20
 static int
-match_alt_name(const GeneralName *n, const Certificate *c,=20
+match_alt_name(const GeneralName *n, const Certificate *c,
 	       int *same, int *match)
 {
     GeneralNames sa;
-    int ret, i, j;
+    int ret;
+    size_t i, j;
=20
     i =3D 0;
     do {
@@ -1765,14 +1875,14 @@
 	    && !subject_null_p(c))
 	{
 	    GeneralName certname;
-	   =20
+
 	    memset(&certname, 0, sizeof(certname));
 	    certname.element =3D choice_GeneralName_directoryName;
-	    certname.u.directoryName.element =3D=20
+	    certname.u.directoryName.element =3D
 		c->tbsCertificate.subject.element;
-	    certname.u.directoryName.u.rdnSequence =3D=20
+	    certname.u.directoryName.u.rdnSequence =3D
 		c->tbsCertificate.subject.u.rdnSequence;
-   =20
+
 	    ret =3D match_general_name(&t->val[i].base, &certname, &name);
 	}
=20
@@ -1789,12 +1899,12 @@
 }
=20
 static int
-check_name_constraints(hx509_context context,=20
+check_name_constraints(hx509_context context,
 		       const hx509_name_constraints *nc,
 		       const Certificate *c)
 {
     int match, ret;
-    int i;
+    size_t i;
=20
     for (i =3D 0 ; i < nc->len; i++) {
 	GeneralSubtrees gs;
@@ -1837,7 +1947,7 @@
 static void
 free_name_constraints(hx509_name_constraints *nc)
 {
-    int i;
+    size_t i;
=20
     for (i =3D 0 ; i < nc->len; i++)
 	free_NameConstraints(&nc->val[i]);
@@ -1867,10 +1977,8 @@
 {
     hx509_name_constraints nc;
     hx509_path path;
-#if 0
-    const AlgorithmIdentifier *alg_id;
-#endif
-    int ret, i, proxy_cert_depth, selfsigned_depth;
+    int ret, proxy_cert_depth, selfsigned_depth, diff;
+    size_t i, k;
     enum certtype type;
     Name proxy_issuer;
     hx509_certs anchors =3D NULL;
@@ -1878,7 +1986,7 @@
     memset(&proxy_issuer, 0, sizeof(proxy_issuer));
=20
     ret =3D init_name_constraints(&nc);
-    if (ret)=09
+    if (ret)
 	return ret;
=20
     path.val =3D NULL;
@@ -1891,9 +1999,9 @@
      *
      */
     if (ctx->trust_anchors)
-	anchors =3D _hx509_certs_ref(ctx->trust_anchors);
+	anchors =3D hx509_certs_ref(ctx->trust_anchors);
     else if (context->default_trust_anchors && ALLOW_DEF_TA(ctx))
-	anchors =3D _hx509_certs_ref(context->default_trust_anchors);
+	anchors =3D hx509_certs_ref(context->default_trust_anchors);
     else {
 	ret =3D hx509_certs_init(context, "MEMORY:no-TA", 0, NULL, &anchors);
 	if (ret)
@@ -1910,10 +2018,6 @@
     if (ret)
 	goto out;
=20
-#if 0
-    alg_id =3D path.val[path->len - 1]->data->tbsCertificate.signature;
-#endif
-
     /*
      * Check CA and proxy certificate chain from the top of the
      * certificate chain. Also check certificate is valid with respect
@@ -1934,7 +2038,7 @@
 	time_t t;
=20
 	c =3D _hx509_get_cert(path.val[i]);
-=09
+
 	/*
 	 * Lets do some basic check on issuer like
 	 * keyUsage.keyCertSign and basicConstraints.cA bit depending
@@ -1943,6 +2047,7 @@
=20
 	switch (type) {
 	case CA_CERT:
+
 	    /* XXX make constants for keyusage */
 	    ret =3D check_key_usage(context, c, 1 << 5,
 				  REQUIRE_RFC3280(ctx) ? TRUE : FALSE);
@@ -1952,15 +2057,23 @@
 		goto out;
 	    }
=20
-	    if (i + 1 !=3D path.len && certificate_is_self_signed(c))=20
-		selfsigned_depth++;
+	    /* self signed cert doesn't add to path length */
+	    if (i + 1 !=3D path.len) {
+		int selfsigned;
+
+		ret =3D certificate_is_self_signed(context, c, &selfsigned);
+		if (ret)
+		    goto out;
+		if (selfsigned)
+		    selfsigned_depth++;
+	    }
=20
 	    break;
 	case PROXY_CERT: {
-	    ProxyCertInfo info;	   =20
+	    ProxyCertInfo info;
=20
 	    if (is_proxy_cert(context, c, &info) =3D=3D 0) {
-		int j;
+		size_t j;
=20
 		if (info.pCPathLenConstraint !=3D NULL &&
 		    *info.pCPathLenConstraint < i)
@@ -1974,26 +2087,26 @@
 		}
 		/* XXX MUST check info.proxyPolicy */
 		free_ProxyCertInfo(&info);
-	=09
+
 		j =3D 0;
-		if (find_extension(c, oid_id_x509_ce_subjectAltName(), &j)) {
+		if (find_extension(c, &asn1_oid_id_x509_ce_subjectAltName, &j)) {
 		    ret =3D HX509_PROXY_CERT_INVALID;
-		    hx509_set_error_string(context, 0, ret,=20
+		    hx509_set_error_string(context, 0, ret,
 					   "Proxy certificate have explicity "
 					   "forbidden subjectAltName");
 		    goto out;
 		}
=20
 		j =3D 0;
-		if (find_extension(c, oid_id_x509_ce_issuerAltName(), &j)) {
+		if (find_extension(c, &asn1_oid_id_x509_ce_issuerAltName, &j)) {
 		    ret =3D HX509_PROXY_CERT_INVALID;
-		    hx509_set_error_string(context, 0, ret,=20
+		    hx509_set_error_string(context, 0, ret,
 					   "Proxy certificate have explicity "
 					   "forbidden issuerAltName");
 		    goto out;
 		}
-		=09
-		/*=20
+
+		/*
 		 * The subject name of the proxy certificate should be
 		 * CN=3DXXX,<proxy issuer>, prune of CN and check if its
 		 * the same over the whole chain of proxy certs and
@@ -2001,8 +2114,12 @@
 		 */
=20
 		if (proxy_cert_depth) {
-		    ret =3D _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.subject);
+		    ret =3D _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.subject, &=
diff);
 		    if (ret) {
+			hx509_set_error_string(context, 0, ret, "Out of memory");
+			goto out;
+		    }
+		    if (diff) {
 			ret =3D HX509_PROXY_CERT_NAME_WRONG;
 			hx509_set_error_string(context, 0, ret,
 					       "Base proxy name not right");
@@ -2019,10 +2136,10 @@
 		}
=20
 		j =3D proxy_issuer.u.rdnSequence.len;
-		if (proxy_issuer.u.rdnSequence.len < 2=20
+		if (proxy_issuer.u.rdnSequence.len < 2
 		    || proxy_issuer.u.rdnSequence.val[j - 1].len > 1
 		    || der_heim_oid_cmp(&proxy_issuer.u.rdnSequence.val[j - 1].val[0].ty=
pe,
-					oid_id_at_commonName()))
+					&asn1_oid_id_at_commonName))
 		{
 		    ret =3D HX509_PROXY_CERT_NAME_WRONG;
 		    hx509_set_error_string(context, 0, ret,
@@ -2035,8 +2152,12 @@
 		free_RelativeDistinguishedName(&proxy_issuer.u.rdnSequence.val[j - 1]);
 		proxy_issuer.u.rdnSequence.len -=3D 1;
=20
-		ret =3D _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.issuer);
-		if (ret !=3D 0) {
+		ret =3D _hx509_name_cmp(&proxy_issuer, &c->tbsCertificate.issuer, &diff);
+		if (ret) {
+		    hx509_set_error_string(context, 0, ret, "Out of memory");
+		    goto out;
+		}
+		if (diff !=3D 0) {
 		    ret =3D HX509_PROXY_CERT_NAME_WRONG;
 		    hx509_set_error_string(context, 0, ret,
 					   "Proxy issuer name not as expected");
@@ -2045,7 +2166,7 @@
=20
 		break;
 	    } else {
-		/*=20
+		/*
 		 * Now we are done with the proxy certificates, this
 		 * cert was an EE cert and we we will fall though to
 		 * EE checking below.
@@ -2063,15 +2184,19 @@
 	    if (proxy_cert_depth) {
=20
 		ret =3D _hx509_name_cmp(&proxy_issuer,
-				      &c->tbsCertificate.subject);
+				      &c->tbsCertificate.subject, &diff);
 		if (ret) {
+		    hx509_set_error_string(context, 0, ret, "out of memory");
+		    goto out;
+		}
+		if (diff) {
 		    ret =3D HX509_PROXY_CERT_NAME_WRONG;
 		    hx509_clear_error_string(context);
 		    goto out;
 		}
 		if (cert->basename)
 		    hx509_name_free(&cert->basename);
-	=09
+
 		ret =3D _hx509_name_from_Name(&proxy_issuer, &cert->basename);
 		if (ret) {
 		    hx509_clear_error_string(context);
@@ -2082,11 +2207,11 @@
 	    break;
 	}
=20
-	ret =3D check_basic_constraints(context, c, type,=20
+	ret =3D check_basic_constraints(context, c, type,
 				      i - proxy_cert_depth - selfsigned_depth);
 	if (ret)
 	    goto out;
-	   =20
+
 	/*
 	 * Don't check the trust anchors expiration time since they
 	 * are transported out of band, from RFC3820.
@@ -2118,13 +2243,19 @@
      * checked in the right order.
      */
=20
-    for (ret =3D 0, i =3D path.len - 1; i >=3D 0; i--) {
+    for (ret =3D 0, k =3D path.len; k > 0; k--) {
 	Certificate *c;
+	int selfsigned;
+	i =3D k - 1;
=20
 	c =3D _hx509_get_cert(path.val[i]);
=20
+	ret =3D certificate_is_self_signed(context, c, &selfsigned);
+	if (ret)
+	    goto out;
+
 	/* verify name constraints, not for selfsigned and anchor */
-	if (!certificate_is_self_signed(c) || i + 1 !=3D path.len) {
+	if (!selfsigned || i + 1 !=3D path.len) {
 	    ret =3D check_name_constraints(context, &nc, c);
 	    if (ret) {
 		goto out;
@@ -2164,10 +2295,10 @@
 	}
=20
 	for (i =3D 0; i < path.len - 1; i++) {
-	    int parent =3D (i < path.len - 1) ? i + 1 : i;
+	    size_t parent =3D (i < path.len - 1) ? i + 1 : i;
=20
 	    ret =3D hx509_revoke_verify(context,
-				      ctx->revoke_ctx,=20
+				      ctx->revoke_ctx,
 				      certs,
 				      ctx->time_now,
 				      path.val[i],
@@ -2185,21 +2316,29 @@
      * parameter is passed up from the anchor up though the chain.
      */
=20
-    for (i =3D path.len - 1; i >=3D 0; i--) {
-	Certificate *signer, *c;
+    for (k =3D path.len; k > 0; k--) {
+	hx509_cert signer;
+	Certificate *c;
+	i =3D k - 1;
=20
 	c =3D _hx509_get_cert(path.val[i]);
=20
 	/* is last in chain (trust anchor) */
 	if (i + 1 =3D=3D path.len) {
-	    signer =3D path.val[i]->data;
+	    int selfsigned;
+
+	    signer =3D path.val[i];
+
+	    ret =3D certificate_is_self_signed(context, signer->data, &selfsigned=
);
+	    if (ret)
+		goto out;
=20
 	    /* if trust anchor is not self signed, don't check sig */
-	    if (!certificate_is_self_signed(signer))
+	    if (!selfsigned)
 		continue;
 	} else {
 	    /* take next certificate in chain */
-	    signer =3D path.val[i + 1]->data;
+	    signer =3D path.val[i + 1];
 	}
=20
 	/* verify signatureValue */
@@ -2213,6 +2352,24 @@
 				   "Failed to verify signature of certificate");
 	    goto out;
 	}
+	/*
+	 * Verify that the sigature algorithm "best-before" date is
+	 * before the creation date of the certificate, do this for
+	 * trust anchors too, since any trust anchor that is created
+	 * after a algorithm is known to be bad deserved to be invalid.
+	 *
+	 * Skip the leaf certificate for now...
+	 */
+
+	if (i !=3D 0 && (ctx->flags & HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK) =
=3D=3D 0) {
+	    time_t notBefore =3D
+		_hx509_Time2time_t(&c->tbsCertificate.validity.notBefore);
+	    ret =3D _hx509_signature_best_before(context,
+					       &c->signatureAlgorithm,
+					       notBefore);
+	    if (ret)
+		goto out;
+	}
     }
=20
 out:
@@ -2245,9 +2402,31 @@
 		       const heim_octet_string *data,
 		       const heim_octet_string *sig)
 {
-    return _hx509_verify_signature(context, signer->data, alg, data, sig);
+    return _hx509_verify_signature(context, signer, alg, data, sig);
 }
=20
+int
+_hx509_verify_signature_bitstring(hx509_context context,
+				  const hx509_cert signer,
+				  const AlgorithmIdentifier *alg,
+				  const heim_octet_string *data,
+				  const heim_bit_string *sig)
+{
+    heim_octet_string os;
+
+    if (sig->length & 7) {
+	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
+			       "signature not multiple of 8 bits");
+	return HX509_CRYPTO_SIG_INVALID_FORMAT;
+    }
+
+    os.data =3D sig->data;
+    os.length =3D sig->length / 8;
+
+    return _hx509_verify_signature(context, signer, alg, data, &os);
+}
+
+
=20
 /**
  * Verify that the certificate is allowed to be used for the hostname
@@ -2276,10 +2455,12 @@
 		      hx509_hostname_type type,
 		      const char *hostname,
 		      const struct sockaddr *sa,
-		      /* XXX krb5_socklen_t */ int sa_size)=20
+		      /* XXX krb5_socklen_t */ int sa_size)
 {
     GeneralNames san;
-    int ret, i, j;
+    const Name *name;
+    int ret;
+    size_t i, j, k;
=20
     if (sa && sa_size <=3D 0)
 	return EINVAL;
@@ -2289,20 +2470,24 @@
     i =3D 0;
     do {
 	ret =3D find_extension_subject_alt_name(cert->data, &i, &san);
-	if (ret =3D=3D HX509_EXTENSION_NOT_FOUND) {
-	    ret =3D 0;
+	if (ret =3D=3D HX509_EXTENSION_NOT_FOUND)
 	    break;
-	} else if (ret !=3D 0)
-	    break;
+	else if (ret !=3D 0)
+	    return HX509_PARSING_NAME_FAILED;
=20
 	for (j =3D 0; j < san.len; j++) {
 	    switch (san.val[j].element) {
-	    case choice_GeneralName_dNSName:
-		if (strcasecmp(san.val[j].u.dNSName, hostname) =3D=3D 0) {
+	    case choice_GeneralName_dNSName: {
+		heim_printable_string hn;
+		hn.data =3D rk_UNCONST(hostname);
+		hn.length =3D strlen(hostname);
+
+		if (der_printable_string_cmp(&san.val[j].u.dNSName, &hn) =3D=3D 0) {
 		    free_GeneralNames(&san);
 		    return 0;
 		}
 		break;
+	    }
 	    default:
 		break;
 	    }
@@ -2310,31 +2495,42 @@
 	free_GeneralNames(&san);
     } while (1);
=20
-    {
-	Name *name =3D &cert->data->tbsCertificate.subject;
-
-	/* match if first component is a CN=3D */
-	if (name->u.rdnSequence.len > 0
-	    && name->u.rdnSequence.val[0].len =3D=3D 1
-	    && der_heim_oid_cmp(&name->u.rdnSequence.val[0].val[0].type,
-				oid_id_at_commonName()) =3D=3D 0)
-	{
-	    DirectoryString *ds =3D &name->u.rdnSequence.val[0].val[0].value;
-
-	    switch (ds->element) {
-	    case choice_DirectoryString_printableString:
-		if (strcasecmp(ds->u.printableString, hostname) =3D=3D 0)
-		    return 0;
-		break;
-	    case choice_DirectoryString_ia5String:
-		if (strcasecmp(ds->u.ia5String, hostname) =3D=3D 0)
-		    return 0;
-		break;
-	    case choice_DirectoryString_utf8String:
-		if (strcasecmp(ds->u.utf8String, hostname) =3D=3D 0)
-		    return 0;
-	    default:
-		break;
+    name =3D &cert->data->tbsCertificate.subject;
+
+    /* Find first CN=3D in the name, and try to match the hostname on that=
 */
+    for (ret =3D 0, k =3D name->u.rdnSequence.len; ret =3D=3D 0 && k > 0; =
k--) {
+	i =3D k - 1;
+	for (j =3D 0; ret =3D=3D 0 && j < name->u.rdnSequence.val[i].len; j++) {
+	    AttributeTypeAndValue *n =3D &name->u.rdnSequence.val[i].val[j];
+
+	    if (der_heim_oid_cmp(&n->type, &asn1_oid_id_at_commonName) =3D=3D 0) {
+		DirectoryString *ds =3D &n->value;
+		switch (ds->element) {
+		case choice_DirectoryString_printableString: {
+		    heim_printable_string hn;
+		    hn.data =3D rk_UNCONST(hostname);
+		    hn.length =3D strlen(hostname);
+
+		    if (der_printable_string_cmp(&ds->u.printableString, &hn) =3D=3D 0)
+			return 0;
+		    break;
+		}
+		case choice_DirectoryString_ia5String: {
+		    heim_ia5_string hn;
+		    hn.data =3D rk_UNCONST(hostname);
+		    hn.length =3D strlen(hostname);
+
+		    if (der_ia5_string_cmp(&ds->u.ia5String, &hn) =3D=3D 0)
+			return 0;
+		    break;
+		}
+		case choice_DirectoryString_utf8String:
+		    if (strcasecmp(ds->u.utf8String, hostname) =3D=3D 0)
+			return 0;
+		default:
+		    break;
+		}
+		ret =3D HX509_NAME_CONSTRAINT_ERROR;
 	    }
 	}
     }
@@ -2347,8 +2543,8 @@
=20
 int
 _hx509_set_cert_attribute(hx509_context context,
-			  hx509_cert cert,=20
-			  const heim_oid *oid,=20
+			  hx509_cert cert,
+			  const heim_oid *oid,
 			  const heim_octet_string *attr)
 {
     hx509_cert_attribute a;
@@ -2357,7 +2553,7 @@
     if (hx509_cert_get_attribute(cert, oid) !=3D NULL)
 	return 0;
=20
-    d =3D realloc(cert->attrs.val,=20
+    d =3D realloc(cert->attrs.val,
 		sizeof(cert->attrs.val[0]) * (cert->attrs.len + 1));
     if (d =3D=3D NULL) {
 	hx509_clear_error_string(context);
@@ -2371,7 +2567,7 @@
=20
     der_copy_octet_string(attr, &a->data);
     der_copy_oid(oid, &a->oid);
-   =20
+
     cert->attrs.val[cert->attrs.len] =3D a;
     cert->attrs.len++;
=20
@@ -2394,7 +2590,7 @@
 hx509_cert_attribute
 hx509_cert_get_attribute(hx509_cert cert, const heim_oid *oid)
 {
-    int i;
+    size_t i;
     for (i =3D 0; i < cert->attrs.len; i++)
 	if (der_heim_oid_cmp(oid, &cert->attrs.val[i]->oid) =3D=3D 0)
 	    return cert->attrs.val[i];
@@ -2440,32 +2636,41 @@
     hx509_cert_attribute a;
     PKCS9_friendlyName n;
     size_t sz;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     if (cert->friendlyname)
 	return cert->friendlyname;
=20
-    a =3D hx509_cert_get_attribute(cert, oid_id_pkcs_9_at_friendlyName());
+    a =3D hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_friendlyNa=
me);
     if (a =3D=3D NULL) {
-	/* XXX use subject name ? */
-	return NULL;=20
+	hx509_name name;
+
+	ret =3D hx509_cert_get_subject(cert, &name);
+	if (ret)
+	    return NULL;
+	ret =3D hx509_name_to_string(name, &cert->friendlyname);
+	hx509_name_free(&name);
+	if (ret)
+	    return NULL;
+	return cert->friendlyname;
     }
=20
     ret =3D decode_PKCS9_friendlyName(a->data.data, a->data.length, &n, &s=
z);
     if (ret)
 	return NULL;
-=09
+
     if (n.len !=3D 1) {
 	free_PKCS9_friendlyName(&n);
 	return NULL;
     }
-   =20
+
     cert->friendlyname =3D malloc(n.val[0].length + 1);
     if (cert->friendlyname =3D=3D NULL) {
 	free_PKCS9_friendlyName(&n);
 	return NULL;
     }
-   =20
+
     for (i =3D 0; i < n.val[0].length; i++) {
 	if (n.val[0].data[i] <=3D 0xff)
 	    cert->friendlyname[i] =3D n.val[0].data[i] & 0xff;
@@ -2504,6 +2709,7 @@
     return 0;
 }
=20
+
 /**
  * Set match options for the hx509 query controller.
  *
@@ -2552,7 +2758,7 @@
=20
 int
 hx509_query_match_issuer_serial(hx509_query *q,
-				const Name *issuer,=20
+				const Name *issuer,
 				const heim_integer *serialNumber)
 {
     int ret;
@@ -2610,6 +2816,69 @@
 }
=20
 /**
+ * Set the query controller to require an one specific EKU (extended
+ * key usage). Any previous EKU matching is overwitten. If NULL is
+ * passed in as the eku, the EKU requirement is reset.
+ *
+ * @param q a hx509 query controller.
+ * @param eku an EKU to match on.
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_cert
+ */
+
+int
+hx509_query_match_eku(hx509_query *q, const heim_oid *eku)
+{
+    int ret;
+
+    if (eku =3D=3D NULL) {
+	if (q->eku) {
+	    der_free_oid(q->eku);
+	    free(q->eku);
+	    q->eku =3D NULL;
+	}
+	q->match &=3D ~HX509_QUERY_MATCH_EKU;
+    } else {
+	if (q->eku) {
+	    der_free_oid(q->eku);
+	} else {
+	    q->eku =3D calloc(1, sizeof(*q->eku));
+	    if (q->eku =3D=3D NULL)
+		return ENOMEM;
+	}
+	ret =3D der_copy_oid(eku, q->eku);
+	if (ret) {
+	    free(q->eku);
+	    q->eku =3D NULL;
+	    return ret;
+	}
+	q->match |=3D HX509_QUERY_MATCH_EKU;
+    }
+    return 0;
+}
+
+int
+hx509_query_match_expr(hx509_context context, hx509_query *q, const char *=
expr)
+{
+    if (q->expr) {
+	_hx509_expr_free(q->expr);
+	q->expr =3D NULL;
+    }
+
+    if (expr =3D=3D NULL) {
+	q->match &=3D ~HX509_QUERY_MATCH_EXPR;
+    } else {
+	q->expr =3D _hx509_expr_parse(expr);
+	if (q->expr)
+	    q->match |=3D HX509_QUERY_MATCH_EXPR;
+    }
+
+    return 0;
+}
+
+/**
  * Set the query controller to match using a specific match function.
  *
  * @param q a hx509 query controller.
@@ -2624,7 +2893,7 @@
=20
 int
 hx509_query_match_cmp_func(hx509_query *q,
-			   int (*func)(void *, hx509_cert),
+			   int (*func)(hx509_context, hx509_cert, void *),
 			   void *ctx)
 {
     if (func)
@@ -2648,20 +2917,27 @@
 void
 hx509_query_free(hx509_context context, hx509_query *q)
 {
+    if (q =3D=3D NULL)
+	return;
+
     if (q->serial) {
 	der_free_heim_integer(q->serial);
 	free(q->serial);
-	q->serial =3D NULL;
     }
     if (q->issuer_name) {
 	free_Name(q->issuer_name);
 	free(q->issuer_name);
-	q->issuer_name =3D NULL;
     }
-    if (q) {
+    if (q->eku) {
+	der_free_oid(q->eku);
+	free(q->eku);
+    }
+    if (q->friendlyname)
 	free(q->friendlyname);
-	memset(q, 0, sizeof(*q));
-    }
+    if (q->expr)
+	_hx509_expr_free(q->expr);
+
+    memset(q, 0, sizeof(*q));
     free(q);
 }
=20
@@ -2669,6 +2945,7 @@
 _hx509_query_match_cert(hx509_context context, const hx509_query *q, hx509=
_cert cert)
 {
     Certificate *c =3D _hx509_get_cert(cert);
+    int ret, diff;
=20
     _hx509_query_statistic(context, 1, q);
=20
@@ -2684,17 +2961,20 @@
 	&& der_heim_integer_cmp(&c->tbsCertificate.serialNumber, q->serial) !=3D =
0)
 	return 0;
=20
-    if ((q->match & HX509_QUERY_MATCH_ISSUER_NAME)
-	&& _hx509_name_cmp(&c->tbsCertificate.issuer, q->issuer_name) !=3D 0)
-	return 0;
-
-    if ((q->match & HX509_QUERY_MATCH_SUBJECT_NAME)
-	&& _hx509_name_cmp(&c->tbsCertificate.subject, q->subject_name) !=3D 0)
-	return 0;
+    if (q->match & HX509_QUERY_MATCH_ISSUER_NAME) {
+	ret =3D _hx509_name_cmp(&c->tbsCertificate.issuer, q->issuer_name, &diff);
+	if (ret || diff)
+	    return 0;
+    }
+
+    if (q->match & HX509_QUERY_MATCH_SUBJECT_NAME) {
+	ret =3D _hx509_name_cmp(&c->tbsCertificate.subject, q->subject_name, &dif=
f);
+	if (ret || diff)
+	    return 0;
+    }
=20
     if (q->match & HX509_QUERY_MATCH_SUBJECT_KEY_ID) {
 	SubjectKeyIdentifier si;
-	int ret;
=20
 	ret =3D _hx509_find_extension_subject_key_id(c, &si);
 	if (ret =3D=3D 0) {
@@ -2707,7 +2987,7 @@
     }
     if ((q->match & HX509_QUERY_MATCH_ISSUER_ID))
 	return 0;
-    if ((q->match & HX509_QUERY_PRIVATE_KEY) &&=20
+    if ((q->match & HX509_QUERY_PRIVATE_KEY) &&
 	_hx509_cert_private_key(cert) =3D=3D NULL)
 	return 0;
=20
@@ -2736,7 +3016,7 @@
     if (q->match & HX509_QUERY_MATCH_LOCAL_KEY_ID) {
 	hx509_cert_attribute a;
=20
-	a =3D hx509_cert_get_attribute(cert, oid_id_pkcs_9_at_localKeyId());
+	a =3D hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_localKeyId);
 	if (a =3D=3D NULL)
 	    return 0;
 	if (der_heim_octet_string_cmp(&a->data, q->local_key_id) !=3D 0)
@@ -2758,17 +3038,16 @@
 	    return 0;
     }
     if (q->match & HX509_QUERY_MATCH_FUNCTION) {
-	int ret =3D (*q->cmp_func)(q->cmp_func_ctx, cert);
+	ret =3D (*q->cmp_func)(context, cert, q->cmp_func_ctx);
 	if (ret !=3D 0)
 	    return 0;
     }
=20
     if (q->match & HX509_QUERY_MATCH_KEY_HASH_SHA1) {
 	heim_octet_string os;
-	int ret;
=20
 	os.data =3D c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
-	os.length =3D=20
+	os.length =3D
 	    c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
=20
 	ret =3D _hx509_verify_signature(context,
@@ -2790,6 +3069,24 @@
 	    return 0;
     }
=20
+    /* If an EKU is required, check the cert for it. */
+    if ((q->match & HX509_QUERY_MATCH_EKU) &&
+	hx509_cert_check_eku(context, cert, q->eku, 0))
+	return 0;
+
+    if ((q->match & HX509_QUERY_MATCH_EXPR)) {
+	hx509_env env =3D NULL;
+
+	ret =3D _hx509_cert_to_env(context, cert, &env);
+	if (ret)
+	    return 0;
+
+	ret =3D _hx509_expr_eval(context, env, q->expr);
+	hx509_env_free(&env);
+	if (ret =3D=3D 0)
+	    return 0;
+    }
+
     if (q->match & ~HX509_QUERY_MASK)
 	return 0;
=20
@@ -2822,6 +3119,7 @@
     f =3D fopen(context->querystat, "a");
     if (f =3D=3D NULL)
 	return;
+    rk_cloexec_file(f);
     fprintf(f, "%d %d\n", type, q->match);
     fclose(f);
 }
@@ -2880,7 +3178,8 @@
 {
     rtbl_t t;
     FILE *f;
-    int type, mask, i, num;
+    int type, mask, num;
+    size_t i;
     unsigned long multiqueries =3D 0, totalqueries =3D 0;
     struct stat_el stats[32];
=20
@@ -2888,11 +3187,12 @@
 	return;
     f =3D fopen(context->querystat, "r");
     if (f =3D=3D NULL) {
-	fprintf(out, "No statistic file %s: %s.\n",=20
+	fprintf(out, "No statistic file %s: %s.\n",
 		context->querystat, strerror(errno));
 	return;
     }
-   =20
+    rk_cloexec_file(f);
+
     for (i =3D 0; i < sizeof(stats)/sizeof(stats[0]); i++) {
 	stats[i].index =3D i;
 	stats[i].stats =3D 0;
@@ -2923,7 +3223,7 @@
 	errx(1, "out of memory");
=20
     rtbl_set_separator (t, "  ");
-   =20
+
     rtbl_add_column_by_id (t, 0, "Name", 0);
     rtbl_add_column_by_id (t, 1, "Counter", 0);
=20
@@ -2931,7 +3231,7 @@
     for (i =3D 0; i < sizeof(stats)/sizeof(stats[0]); i++) {
 	char str[10];
=20
-	if (stats[i].index < sizeof(statname)/sizeof(statname[0]))=20
+	if (stats[i].index < sizeof(statname)/sizeof(statname[0]))
 	    rtbl_add_column_entry_by_id (t, 0, statname[stats[i].index]);
 	else {
 	    snprintf(str, sizeof(str), "%d", stats[i].index);
@@ -2944,7 +3244,7 @@
     rtbl_format(t, out);
     rtbl_destroy(t);
=20
-    fprintf(out, "\nQueries: multi %lu total %lu\n",=20
+    fprintf(out, "\nQueries: multi %lu total %lu\n",
 	    multiqueries, totalqueries);
 }
=20
@@ -2967,7 +3267,8 @@
 		     const heim_oid *eku, int allow_any_eku)
 {
     ExtKeyUsage e;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     ret =3D find_extension_eku(_hx509_get_cert(cert), &e);
     if (ret) {
@@ -3002,7 +3303,8 @@
     Certificate *cert;
     const Extension *e;
     size_t size;
-    int ret, i =3D 0;
+    int ret;
+    size_t i =3D 0;
=20
     memset(ku, 0, sizeof(*ku));
=20
@@ -3011,10 +3313,10 @@
     if (_hx509_cert_get_version(cert) < 3)
 	return 0;
=20
-    e =3D find_extension(cert, oid_id_x509_ce_keyUsage(), &i);
+    e =3D find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i);
     if (e =3D=3D NULL)
 	return HX509_KU_CERT_MISSING;
-   =20
+
     ret =3D decode_KeyUsage(e->extnValue.data, e->extnValue.length, ku, &s=
ize);
     if (ret)
 	return ret;
@@ -3044,7 +3346,7 @@
  * @param context A hx509 context.
  * @param c the certificate to encode.
  * @param os the encode certificate, set to NULL, 0 on case of
- * error. Free the returned structure with hx509_xfree().
+ * error. Free the os->data with hx509_xfree().
  *
  * @return An hx509 error code, see hx509_get_error_string().
  *
@@ -3060,7 +3362,7 @@
     os->data =3D NULL;
     os->length =3D 0;
=20
-    ASN1_MALLOC_ENCODE(Certificate, os->data, os->length,=20
+    ASN1_MALLOC_ENCODE(Certificate, os->data, os->length,
 		       _hx509_get_cert(c), &size, ret);
     if (ret) {
 	os->data =3D NULL;
@@ -3106,3 +3408,205 @@
 {
     free(ptr);
 }
+
+/**
+ *
+ */
+
+int
+_hx509_cert_to_env(hx509_context context, hx509_cert cert, hx509_env *env)
+{
+    ExtKeyUsage eku;
+    hx509_name name;
+    char *buf;
+    int ret;
+    hx509_env envcert =3D NULL;
+
+    *env =3D NULL;
+
+    /* version */
+    asprintf(&buf, "%d", _hx509_cert_get_version(_hx509_get_cert(cert)));
+    ret =3D hx509_env_add(context, &envcert, "version", buf);
+    free(buf);
+    if (ret)
+	goto out;
+
+    /* subject */
+    ret =3D hx509_cert_get_subject(cert, &name);
+    if (ret)
+	goto out;
+
+    ret =3D hx509_name_to_string(name, &buf);
+    if (ret) {
+	hx509_name_free(&name);
+	goto out;
+    }
+
+    ret =3D hx509_env_add(context, &envcert, "subject", buf);
+    hx509_name_free(&name);
+    if (ret)
+	goto out;
+
+    /* issuer */
+    ret =3D hx509_cert_get_issuer(cert, &name);
+    if (ret)
+	goto out;
+
+    ret =3D hx509_name_to_string(name, &buf);
+    hx509_name_free(&name);
+    if (ret)
+	goto out;
+
+    ret =3D hx509_env_add(context, &envcert, "issuer", buf);
+    hx509_xfree(buf);
+    if (ret)
+	goto out;
+
+    /* eku */
+
+    ret =3D _hx509_cert_get_eku(context, cert, &eku);
+    if (ret =3D=3D HX509_EXTENSION_NOT_FOUND)
+	;
+    else if (ret !=3D 0)
+	goto out;
+    else {
+	size_t i;
+	hx509_env enveku =3D NULL;
+
+	for (i =3D 0; i < eku.len; i++) {
+
+	    ret =3D der_print_heim_oid(&eku.val[i], '.', &buf);
+	    if (ret) {
+		free_ExtKeyUsage(&eku);
+		hx509_env_free(&enveku);
+		goto out;
+	    }
+	    ret =3D hx509_env_add(context, &enveku, buf, "oid-name-here");
+	    free(buf);
+	    if (ret) {
+		free_ExtKeyUsage(&eku);
+		hx509_env_free(&enveku);
+		goto out;
+	    }
+	}
+	free_ExtKeyUsage(&eku);
+
+	ret =3D hx509_env_add_binding(context, &envcert, "eku", enveku);
+	if (ret) {
+	    hx509_env_free(&enveku);
+	    goto out;
+	}
+    }
+
+    {
+	Certificate *c =3D _hx509_get_cert(cert);
+        heim_octet_string os, sig;
+	hx509_env envhash =3D NULL;
+
+	os.data =3D c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
+	os.length =3D
+	  c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
+
+	ret =3D _hx509_create_signature(context,
+				      NULL,
+				      hx509_signature_sha1(),
+				      &os,
+				      NULL,
+				      &sig);
+	if (ret !=3D 0)
+	    goto out;
+
+	ret =3D hex_encode(sig.data, sig.length, &buf);
+	der_free_octet_string(&sig);
+	if (ret < 0) {
+	    ret =3D ENOMEM;
+	    hx509_set_error_string(context, 0, ret,
+				   "Out of memory");
+	    goto out;
+	}
+
+	ret =3D hx509_env_add(context, &envhash, "sha1", buf);
+	free(buf);
+	if (ret)
+	    goto out;
+
+	ret =3D hx509_env_add_binding(context, &envcert, "hash", envhash);
+	if (ret) {
+	  hx509_env_free(&envhash);
+	  goto out;
+	}
+    }
+
+    ret =3D hx509_env_add_binding(context, env, "certificate", envcert);
+    if (ret)
+	goto out;
+
+    return 0;
+
+out:
+    hx509_env_free(&envcert);
+    return ret;
+}
+
+/**
+ * Print a simple representation of a certificate
+ *
+ * @param context A hx509 context, can be NULL
+ * @param cert certificate to print
+ * @param out the stdio output stream, if NULL, stdout is used
+ *
+ * @return An hx509 error code
+ *
+ * @ingroup hx509_cert
+ */
+
+int
+hx509_print_cert(hx509_context context, hx509_cert cert, FILE *out)
+{
+    hx509_name name;
+    char *str;
+    int ret;
+
+    if (out =3D=3D NULL)
+	out =3D stderr;
+
+    ret =3D hx509_cert_get_issuer(cert, &name);
+    if (ret)
+	return ret;
+    hx509_name_to_string(name, &str);
+    hx509_name_free(&name);
+    fprintf(out, "    issuer:  \"%s\"\n", str);
+    free(str);
+
+    ret =3D hx509_cert_get_subject(cert, &name);
+    if (ret)
+	return ret;
+    hx509_name_to_string(name, &str);
+    hx509_name_free(&name);
+    fprintf(out, "    subject: \"%s\"\n", str);
+    free(str);
+
+    {
+	heim_integer serialNumber;
+
+	ret =3D hx509_cert_get_serialnumber(cert, &serialNumber);
+	if (ret)
+	    return ret;
+	ret =3D der_print_hex_heim_integer(&serialNumber, &str);
+	if (ret)
+	    return ret;
+	der_free_heim_integer(&serialNumber);
+	fprintf(out, "    serial: %s\n", str);
+	free(str);
+    }
+
+    printf("    keyusage: ");
+    ret =3D hx509_cert_keyusage_print(context, cert, &str);
+    if (ret =3D=3D 0) {
+	fprintf(out, "%s\n", str);
+	free(str);
+    } else
+	fprintf(out, "no");
+
+    return 0;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/cms.c
--- a/head/crypto/heimdal/lib/hx509/cms.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/cms.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003 - 2007 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2003 - 2007 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
@@ -32,13 +32,12 @@
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: cms.c 22327 2007-12-15 04:49:37Z lha $");
=20
 /**
  * @page page_cms CMS/PKCS7 message functions.
  *
  * CMS is defined in RFC 3369 and is an continuation of the RSA Labs
- * standard PKCS7. The basic messages in CMS is=20
+ * standard PKCS7. The basic messages in CMS is
  *
  * - SignedData
  *   Data signed with private key (RSA, DSA, ECDSA) or secret
@@ -68,7 +67,7 @@
  * der_free_octet_string().
  *
  * @return Returns an hx509 error code.
- *=20
+ *
  * @ingroup hx509_cms
  */
=20
@@ -122,7 +121,7 @@
  * diffrence between no data and the zero length data.
  *
  * @return Returns an hx509 error code.
- *=20
+ *
  * @ingroup hx509_cms
  */
=20
@@ -260,6 +259,7 @@
 find_CMSIdentifier(hx509_context context,
 		   CMSIdentifier *client,
 		   hx509_certs certs,
+		   time_t time_now,
 		   hx509_cert *signer_cert,
 		   int match)
 {
@@ -292,7 +292,10 @@
     q.match |=3D match;
=20
     q.match |=3D HX509_QUERY_MATCH_TIME;
-    q.timenow =3D time(NULL);
+    if (time_now)
+	q.timenow =3D time_now;
+    else
+	q.timenow =3D time(NULL);
=20
     ret =3D hx509_certs_find(context, certs, &q, &cert);
     if (ret =3D=3D HX509_CERT_NOT_FOUND) {
@@ -333,6 +336,7 @@
  * @param length length of the data that data point to.
  * @param encryptedContent in case of detached signature, this
  * contains the actual encrypted data, othersize its should be NULL.
+ * @param time_now set the current time, if zero the library uses now as t=
he date.
  * @param contentType output type oid, should be freed with der_free_oid().
  * @param content the data, free with der_free_octet_string().
  *
@@ -346,6 +350,7 @@
 		     const void *data,
 		     size_t length,
 		     const heim_octet_string *encryptedContent,
+		     time_t time_now,
 		     heim_oid *contentType,
 		     heim_octet_string *content)
 {
@@ -357,7 +362,8 @@
     heim_octet_string *params, params_data;
     heim_octet_string ivec;
     size_t size;
-    int ret, i, matched =3D 0, findflags =3D 0;
+    int ret, matched =3D 0, findflags =3D 0;
+    size_t i;
=20
=20
     memset(&key, 0, sizeof(key));
@@ -407,7 +413,8 @@
=20
 	ri =3D &ed.recipientInfos.val[i];
=20
-	ret =3D find_CMSIdentifier(context, &ri->rid, certs, &cert,
+	ret =3D find_CMSIdentifier(context, &ri->rid, certs,
+				 time_now, &cert,
 				 HX509_QUERY_PRIVATE_KEY|findflags);
 	if (ret)
 	    continue;
@@ -466,7 +473,10 @@
 	ret =3D hx509_crypto_init(context, NULL, &ai->algorithm, &crypto);
 	if (ret)
 	    goto out;
-=09
+
+	if (flags & HX509_CMS_UE_ALLOW_WEAK)
+	    hx509_crypto_allow_weak(crypto);
+
 	if (params) {
 	    ret =3D hx509_crypto_set_params(context, crypto, params, &ivec);
 	    if (ret) {
@@ -483,7 +493,7 @@
 				   "of EnvelopedData");
 	    goto out;
 	}
-=09
+
 	ret =3D hx509_crypto_decrypt(crypto,
 				   enccontent->data,
 				   enccontent->length,
@@ -520,7 +530,10 @@
  * used to RSA.
  *
  * @param context A hx509 context.
- * @param flags flags to control the behavior, no flags today
+ * @param flags flags to control the behavior.
+ *    - HX509_CMS_EV_NO_KU_CHECK - Dont check KU on certificate
+ *    - HX509_CMS_EV_ALLOW_WEAK - Allow weak crytpo
+ *    - HX509_CMS_EV_ID_NAME - prefer issuer name and serial number
  * @param cert Certificate to encrypt the EnvelopedData encryption key
  * with.
  * @param data pointer the data to encrypt.
@@ -548,9 +561,9 @@
     heim_octet_string ivec;
     heim_octet_string key;
     hx509_crypto crypto =3D NULL;
+    int ret, cmsidflag;
     EnvelopedData ed;
     size_t size;
-    int ret;
=20
     memset(&ivec, 0, sizeof(ivec));
     memset(&key, 0, sizeof(key));
@@ -558,16 +571,21 @@
     memset(content, 0, sizeof(*content));
=20
     if (encryption_type =3D=3D NULL)
-	encryption_type =3D oid_id_aes_256_cbc();
+	encryption_type =3D &asn1_oid_id_aes_256_cbc;
=20
-    ret =3D _hx509_check_key_usage(context, cert, 1 << 2, TRUE);
-    if (ret)
-	goto out;
+    if ((flags & HX509_CMS_EV_NO_KU_CHECK) =3D=3D 0) {
+	ret =3D _hx509_check_key_usage(context, cert, 1 << 2, TRUE);
+	if (ret)
+	    goto out;
+    }
=20
     ret =3D hx509_crypto_init(context, NULL, encryption_type, &crypto);
     if (ret)
 	goto out;
=20
+    if (flags & HX509_CMS_EV_ALLOW_WEAK)
+	hx509_crypto_allow_weak(crypto);
+
     ret =3D hx509_crypto_set_random_key(crypto, &key);
     if (ret) {
 	hx509_set_error_string(context, 0, ret,
@@ -602,7 +620,7 @@
 				   "Failed to set crypto oid "
 				   "for EnvelopedData");
 	    goto out;
-	}=09
+	}
 	ALLOC(enc_alg->parameters, 1);
 	if (enc_alg->parameters =3D=3D NULL) {
 	    ret =3D ENOMEM;
@@ -632,8 +650,15 @@
=20
     ri =3D &ed.recipientInfos.val[0];
=20
-    ri->version =3D 0;
-    ret =3D fill_CMSIdentifier(cert, CMS_ID_SKI, &ri->rid);
+    if (flags & HX509_CMS_EV_ID_NAME) {
+	ri->version =3D 0;
+	cmsidflag =3D CMS_ID_NAME;
+    } else {
+	ri->version =3D 2;
+	cmsidflag =3D CMS_ID_SKI;
+    }
+
+    ret =3D fill_CMSIdentifier(cert, cmsidflag, &ri->rid);
     if (ret) {
 	hx509_set_error_string(context, 0, ret,
 			       "Failed to set CMS identifier info "
@@ -641,7 +666,7 @@
 	goto out;
     }
=20
-    ret =3D _hx509_cert_public_encrypt(context,
+    ret =3D hx509_cert_public_encrypt(context,
 				     &key, cert,
 				     &ri->keyEncryptionAlgorithm.algorithm,
 				     &ri->encryptedKey);
@@ -694,7 +719,8 @@
 static int
 any_to_certs(hx509_context context, const SignedData *sd, hx509_certs cert=
s)
 {
-    int ret, i;
+    int ret;
+    size_t i;
=20
     if (sd->certificates =3D=3D NULL)
 	return 0;
@@ -702,8 +728,8 @@
     for (i =3D 0; i < sd->certificates->len; i++) {
 	hx509_cert c;
=20
-	ret =3D hx509_cert_init_data(context,=20
-				   sd->certificates->val[i].data,=20
+	ret =3D hx509_cert_init_data(context,
+				   sd->certificates->val[i].data,
 				   sd->certificates->val[i].length,
 				   &c);
 	if (ret)
@@ -720,7 +746,7 @@
 static const Attribute *
 find_attribute(const CMSAttributes *attr, const heim_oid *oid)
 {
-    int i;
+    size_t i;
     for (i =3D 0; i < attr->len; i++)
 	if (der_heim_oid_cmp(&attr->val[i].type, oid) =3D=3D 0)
 	    return &attr->val[i];
@@ -731,12 +757,16 @@
  * Decode SignedData and verify that the signature is correct.
  *
  * @param context A hx509 context.
- * @param ctx a hx509 version context
- * @param data
+ * @param ctx a hx509 verify context.
+ * @param flags to control the behaivor of the function.
+ *    - HX509_CMS_VS_NO_KU_CHECK - Don't check KeyUsage
+ *    - HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH - allow oid mismatch
+ *    - HX509_CMS_VS_ALLOW_ZERO_SIGNER - no signer, see below.
+ * @param data pointer to CMS SignedData encoded data.
  * @param length length of the data that data point to.
- * @param signedContent
+ * @param signedContent external data used for signature.
  * @param pool certificate pool to build certificates paths.
- * @param contentType free with der_free_oid()
+ * @param contentType free with der_free_oid().
  * @param content the output of the function, free with
  * der_free_octet_string().
  * @param signer_certs list of the cerficates used to sign this
@@ -748,6 +778,7 @@
 int
 hx509_cms_verify_signed(hx509_context context,
 			hx509_verify_ctx ctx,
+			unsigned int flags,
 			const void *data,
 			size_t length,
 			const heim_octet_string *signedContent,
@@ -761,7 +792,8 @@
     hx509_certs certs =3D NULL;
     SignedData sd;
     size_t size;
-    int ret, i, found_valid_sig;
+    int ret, found_valid_sig;
+    size_t i;
=20
     *signer_certs =3D NULL;
     content->data =3D NULL;
@@ -790,8 +822,15 @@
 			       "Both external and internal SignedData");
 	goto out;
     }
+
     if (sd.encapContentInfo.eContent)
-	signedContent =3D sd.encapContentInfo.eContent;
+	ret =3D der_copy_octet_string(sd.encapContentInfo.eContent, content);
+    else
+	ret =3D der_copy_octet_string(signedContent, content);
+    if (ret) {
+	hx509_set_error_string(context, 0, ret, "malloc: out of memory");
+	goto out;
+    }
=20
     ret =3D hx509_certs_init(context, "MEMORY:cms-cert-buffer",
 			   0, NULL, &certs);
@@ -816,7 +855,7 @@
     }
=20
     for (found_valid_sig =3D 0, i =3D 0; i < sd.signerInfos.len; i++) {
-	heim_octet_string *signed_data;
+	heim_octet_string signed_data;
 	const heim_oid *match_oid;
 	heim_oid decode_oid;
=20
@@ -831,14 +870,29 @@
 	    continue;
 	}
=20
-	ret =3D find_CMSIdentifier(context, &signer_info->sid, certs, &cert,
+	ret =3D find_CMSIdentifier(context, &signer_info->sid, certs,
+				 _hx509_verify_get_time(ctx), &cert,
 				 HX509_QUERY_KU_DIGITALSIGNATURE);
-	if (ret)
-	    continue;
+	if (ret) {
+	    /**
+	     * If HX509_CMS_VS_NO_KU_CHECK is set, allow more liberal
+	     * search for matching certificates by not considering
+	     * KeyUsage bits on the certificates.
+	     */
+	    if ((flags & HX509_CMS_VS_NO_KU_CHECK) =3D=3D 0)
+		continue;
+
+	    ret =3D find_CMSIdentifier(context, &signer_info->sid, certs,
+				     _hx509_verify_get_time(ctx), &cert,
+				     0);
+	    if (ret)
+		continue;
+
+	}
=20
 	if (signer_info->signedAttrs) {
 	    const Attribute *attr;
-=09
+
 	    CMSAttributes sa;
 	    heim_octet_string os;
=20
@@ -846,7 +900,7 @@
 	    sa.len =3D signer_info->signedAttrs->len;
=20
 	    /* verify that sigature exists */
-	    attr =3D find_attribute(&sa, oid_id_pkcs9_messageDigest());
+	    attr =3D find_attribute(&sa, &asn1_oid_id_pkcs9_messageDigest);
 	    if (attr =3D=3D NULL) {
 		ret =3D HX509_CRYPTO_SIGNATURE_MISSING;
 		hx509_set_error_string(context, 0, ret,
@@ -862,7 +916,7 @@
 				       "messageDigest (signature)");
 		goto next_sigature;
 	    }
-=09
+
 	    ret =3D decode_MessageDigest(attr->value.val[0].data,
 				       attr->value.val[0].length,
 				       &os,
@@ -877,7 +931,7 @@
 	    ret =3D _hx509_verify_signature(context,
 					  NULL,
 					  &signer_info->digestAlgorithm,
-					  signedContent,
+					  content,
 					  &os);
 	    der_free_octet_string(&os);
 	    if (ret) {
@@ -890,9 +944,9 @@
 	     * Fetch content oid inside signedAttrs or set it to
 	     * id-pkcs7-data.
 	     */
-	    attr =3D find_attribute(&sa, oid_id_pkcs9_contentType());
+	    attr =3D find_attribute(&sa, &asn1_oid_id_pkcs9_contentType);
 	    if (attr =3D=3D NULL) {
-		match_oid =3D oid_id_pkcs7_data();
+		match_oid =3D &asn1_oid_id_pkcs7_data;
 	    } else {
 		if (attr->value.len !=3D 1) {
 		    ret =3D HX509_CMS_DATA_OID_MISMATCH;
@@ -914,36 +968,36 @@
 		match_oid =3D &decode_oid;
 	    }
=20
-	    ALLOC(signed_data, 1);
-	    if (signed_data =3D=3D NULL) {
-		if (match_oid =3D=3D &decode_oid)
-		    der_free_oid(&decode_oid);
-		ret =3D ENOMEM;
-		hx509_clear_error_string(context);
-		goto next_sigature;
-	    }
-=09
 	    ASN1_MALLOC_ENCODE(CMSAttributes,
-			       signed_data->data,
-			       signed_data->length,
+			       signed_data.data,
+			       signed_data.length,
 			       &sa,
 			       &size, ret);
 	    if (ret) {
 		if (match_oid =3D=3D &decode_oid)
 		    der_free_oid(&decode_oid);
-		free(signed_data);
 		hx509_clear_error_string(context);
 		goto next_sigature;
 	    }
-	    if (size !=3D signed_data->length)
+	    if (size !=3D signed_data.length)
 		_hx509_abort("internal ASN.1 encoder error");
=20
 	} else {
-	    signed_data =3D rk_UNCONST(signedContent);
-	    match_oid =3D oid_id_pkcs7_data();
+	    signed_data.data =3D content->data;
+	    signed_data.length =3D content->length;
+	    match_oid =3D &asn1_oid_id_pkcs7_data;
 	}
=20
-	if (der_heim_oid_cmp(match_oid, &sd.encapContentInfo.eContentType)) {
+	/**
+	 * If HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH, allow
+	 * encapContentInfo mismatch with the oid in signedAttributes
+	 * (or if no signedAttributes where use, pkcs7-data oid).
+	 * This is only needed to work with broken CMS implementations
+	 * that doesn't follow CMS signedAttributes rules.
+	 */
+
+	if (der_heim_oid_cmp(match_oid, &sd.encapContentInfo.eContentType) &&
+	    (flags & HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH) =3D=3D 0) {
 	    ret =3D HX509_CMS_DATA_OID_MISMATCH;
 	    hx509_set_error_string(context, 0, ret,
 				   "Oid in message mismatch from the expected");
@@ -955,23 +1009,28 @@
 	    ret =3D hx509_verify_signature(context,
 					 cert,
 					 &signer_info->signatureAlgorithm,
-					 signed_data,
+					 &signed_data,
 					 &signer_info->signature);
 	    if (ret)
 		hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
-				       "Failed to verify sigature in "
+				       "Failed to verify signature in "
 				       "CMS SignedData");
 	}
-	if (signed_data !=3D signedContent) {
-	    der_free_octet_string(signed_data);
-	    free(signed_data);
-	}
+        if (signer_info->signedAttrs)
+	    free(signed_data.data);
 	if (ret)
 	    goto next_sigature;
=20
-	ret =3D hx509_verify_path(context, ctx, cert, certs);
-	if (ret)
-	    goto next_sigature;
+	/**
+	 * If HX509_CMS_VS_NO_VALIDATE flags is set, do not verify the
+	 * signing certificates and leave that up to the caller.
+	 */
+
+	if ((flags & HX509_CMS_VS_NO_VALIDATE) =3D=3D 0) {
+	    ret =3D hx509_verify_path(context, ctx, cert, certs);
+	    if (ret)
+		goto next_sigature;
+	}
=20
 	ret =3D hx509_certs_add(context, *signer_certs, cert);
 	if (ret)
@@ -984,7 +1043,18 @@
 	    hx509_cert_free(cert);
 	cert =3D NULL;
     }
-    if (found_valid_sig =3D=3D 0) {
+    /**
+     * If HX509_CMS_VS_ALLOW_ZERO_SIGNER is set, allow empty
+     * SignerInfo (no signatures). If SignedData have no signatures,
+     * the function will return 0 with signer_certs set to NULL. Zero
+     * signers is allowed by the standard, but since its only useful
+     * in corner cases, it make into a flag that the caller have to
+     * turn on.
+     */
+    if (sd.signerInfos.len =3D=3D 0 && (flags & HX509_CMS_VS_ALLOW_ZERO_SI=
GNER)) {
+	if (*signer_certs)
+	    hx509_certs_free(signer_certs);
+    } else if (found_valid_sig =3D=3D 0) {
 	if (ret =3D=3D 0) {
 	    ret =3D HX509_CMS_SIGNER_NOT_FOUND;
 	    hx509_set_error_string(context, 0, ret,
@@ -999,20 +1069,13 @@
 	goto out;
     }
=20
-    content->data =3D malloc(signedContent->length);
-    if (content->data =3D=3D NULL) {
-	hx509_clear_error_string(context);
-	ret =3D ENOMEM;
-	goto out;
-    }
-    content->length =3D signedContent->length;
-    memcpy(content->data, signedContent->data, content->length);
-
 out:
     free_SignedData(&sd);
     if (certs)
 	hx509_certs_free(&certs);
     if (ret) {
+	if (content->data)
+	    der_free_octet_string(content);
 	if (*signer_certs)
 	    hx509_certs_free(signer_certs);
 	der_free_oid(contentType);
@@ -1053,7 +1116,7 @@
=20
     return 0;
 }
-=09
+
 /**
  * Decode SignedData and verify that the signature is correct.
  *
@@ -1089,26 +1152,56 @@
 			  hx509_certs pool,
 			  heim_octet_string *signed_data)
 {
+    hx509_certs certs;
+    int ret =3D 0;
+
+    signed_data->data =3D NULL;
+    signed_data->length =3D 0;
+
+    ret =3D hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs);
+    if (ret)
+	return ret;
+    ret =3D hx509_certs_add(context, certs, cert);
+    if (ret)
+	goto out;
+
+    ret =3D hx509_cms_create_signed(context, flags, eContentType, data, le=
ngth,
+				  digest_alg, certs, peer, anchors, pool,
+				  signed_data);
+
+ out:
+    hx509_certs_free(&certs);
+    return ret;
+}
+
+struct sigctx {
+    SignedData sd;
+    const AlgorithmIdentifier *digest_alg;
+    const heim_oid *eContentType;
+    heim_octet_string content;
+    hx509_peer_info peer;
+    int cmsidflag;
+    int leafonly;
+    hx509_certs certs;
+    hx509_certs anchors;
+    hx509_certs pool;
+};
+
+static int
+sig_process(hx509_context context, void *ctx, hx509_cert cert)
+{
+    struct sigctx *sigctx =3D ctx;
+    heim_octet_string buf, sigdata =3D { 0, NULL };
+    SignerInfo *signer_info =3D NULL;
     AlgorithmIdentifier digest;
-    hx509_name name;
-    SignerInfo *signer_info;
-    heim_octet_string buf, content, sigdata =3D { 0, NULL };
-    SignedData sd;
+    size_t size;
+    void *ptr;
     int ret;
-    size_t size;
+    SignedData *sd =3D &sigctx->sd;
     hx509_path path;
-    int cmsidflag =3D CMS_ID_SKI;
=20
-    memset(&sd, 0, sizeof(sd));
-    memset(&name, 0, sizeof(name));
+    memset(&digest, 0, sizeof(digest));
     memset(&path, 0, sizeof(path));
-    memset(&digest, 0, sizeof(digest));
-
-    content.data =3D rk_UNCONST(data);
-    content.length =3D length;
-
-    if (flags & HX509_CMS_SIGATURE_ID_NAME)
-	cmsidflag =3D CMS_ID_NAME;
=20
     if (_hx509_cert_private_key(cert) =3D=3D NULL) {
 	hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
@@ -1116,64 +1209,45 @@
 	return HX509_PRIVATE_KEY_MISSING;
     }
=20
-    if (digest_alg =3D=3D NULL) {
-	ret =3D hx509_crypto_select(context, HX509_SELECT_DIGEST,
-				  _hx509_cert_private_key(cert), peer, &digest);
-    } else {
-	ret =3D copy_AlgorithmIdentifier(digest_alg, &digest);
+    if (sigctx->digest_alg) {
+	ret =3D copy_AlgorithmIdentifier(sigctx->digest_alg, &digest);
 	if (ret)
 	    hx509_clear_error_string(context);
+    } else {
+	ret =3D hx509_crypto_select(context, HX509_SELECT_DIGEST,
+				  _hx509_cert_private_key(cert),
+				  sigctx->peer, &digest);
     }
     if (ret)
 	goto out;
=20
-    sd.version =3D CMSVersion_v3;
+    /*
+     * Allocate on more signerInfo and do the signature processing
+     */
=20
-    if (eContentType =3D=3D NULL)
-	eContentType =3D oid_id_pkcs7_data();
-
-    der_copy_oid(eContentType, &sd.encapContentInfo.eContentType);
-
-    /* */
-    if ((flags & HX509_CMS_SIGATURE_DETACHED) =3D=3D 0) {
-	ALLOC(sd.encapContentInfo.eContent, 1);
-	if (sd.encapContentInfo.eContent =3D=3D NULL) {
-	    hx509_clear_error_string(context);
-	    ret =3D ENOMEM;
-	    goto out;
-	}
-=09
-	sd.encapContentInfo.eContent->data =3D malloc(length);
-	if (sd.encapContentInfo.eContent->data =3D=3D NULL) {
-	    hx509_clear_error_string(context);
-	    ret =3D ENOMEM;
-	    goto out;
-	}
-	memcpy(sd.encapContentInfo.eContent->data, data, length);
-	sd.encapContentInfo.eContent->length =3D length;
-    }
-
-    ALLOC_SEQ(&sd.signerInfos, 1);
-    if (sd.signerInfos.val =3D=3D NULL) {
-	hx509_clear_error_string(context);
+    ptr =3D realloc(sd->signerInfos.val,
+		  (sd->signerInfos.len + 1) * sizeof(sd->signerInfos.val[0]));
+    if (ptr =3D=3D NULL) {
 	ret =3D ENOMEM;
 	goto out;
     }
+    sd->signerInfos.val =3D ptr;
=20
-    signer_info =3D &sd.signerInfos.val[0];
+    signer_info =3D &sd->signerInfos.val[sd->signerInfos.len];
+
+    memset(signer_info, 0, sizeof(*signer_info));
=20
     signer_info->version =3D 1;
=20
-    ret =3D fill_CMSIdentifier(cert, cmsidflag, &signer_info->sid);
+    ret =3D fill_CMSIdentifier(cert, sigctx->cmsidflag, &signer_info->sid);
     if (ret) {
 	hx509_clear_error_string(context);
 	goto out;
-    }		=09
+    }
=20
     signer_info->signedAttrs =3D NULL;
     signer_info->unsignedAttrs =3D NULL;
=20
-
     ret =3D copy_AlgorithmIdentifier(&digest, &signer_info->digestAlgorith=
m);
     if (ret) {
 	hx509_clear_error_string(context);
@@ -1184,8 +1258,8 @@
      * If it isn't pkcs7-data send signedAttributes
      */
=20
-    if (der_heim_oid_cmp(eContentType, oid_id_pkcs7_data()) !=3D 0) {
-	CMSAttributes sa;=09
+    if (der_heim_oid_cmp(sigctx->eContentType, &asn1_oid_id_pkcs7_data) !=
=3D 0) {
+	CMSAttributes sa;
 	heim_octet_string sig;
=20
 	ALLOC(signer_info->signedAttrs, 1);
@@ -1197,7 +1271,7 @@
 	ret =3D _hx509_create_signature(context,
 				      NULL,
 				      &digest,
-				      &content,
+				      &sigctx->content,
 				      NULL,
 				      &sig);
 	if (ret)
@@ -1219,9 +1293,10 @@
=20
 	ret =3D add_one_attribute(&signer_info->signedAttrs->val,
 				&signer_info->signedAttrs->len,
-				oid_id_pkcs9_messageDigest(),
+				&asn1_oid_id_pkcs9_messageDigest,
 				&buf);
 	if (ret) {
+	    free(buf.data);
 	    hx509_clear_error_string(context);
 	    goto out;
 	}
@@ -1230,7 +1305,7 @@
 	ASN1_MALLOC_ENCODE(ContentType,
 			   buf.data,
 			   buf.length,
-			   eContentType,
+			   sigctx->eContentType,
 			   &size,
 			   ret);
 	if (ret)
@@ -1240,16 +1315,17 @@
=20
 	ret =3D add_one_attribute(&signer_info->signedAttrs->val,
 				&signer_info->signedAttrs->len,
-				oid_id_pkcs9_contentType(),
+				&asn1_oid_id_pkcs9_contentType,
 				&buf);
 	if (ret) {
+	    free(buf.data);
 	    hx509_clear_error_string(context);
 	    goto out;
 	}
=20
 	sa.val =3D signer_info->signedAttrs->val;
 	sa.len =3D signer_info->signedAttrs->len;
-=09
+
 	ASN1_MALLOC_ENCODE(CMSAttributes,
 			   sigdata.data,
 			   sigdata.length,
@@ -1263,16 +1339,15 @@
 	if (size !=3D sigdata.length)
 	    _hx509_abort("internal ASN.1 encoder error");
     } else {
-	sigdata.data =3D content.data;
-	sigdata.length =3D content.length;
+	sigdata.data =3D sigctx->content.data;
+	sigdata.length =3D sigctx->content.length;
     }
=20
-
     {
 	AlgorithmIdentifier sigalg;
=20
 	ret =3D hx509_crypto_select(context, HX509_SELECT_PUBLIC_SIG,
-				  _hx509_cert_private_key(cert), peer,
+				  _hx509_cert_private_key(cert), sigctx->peer,
 				  &sigalg);
 	if (ret)
 	    goto out;
@@ -1288,54 +1363,30 @@
 	    goto out;
     }
=20
-    ALLOC_SEQ(&sd.digestAlgorithms, 1);
-    if (sd.digestAlgorithms.val =3D=3D NULL) {
-	ret =3D ENOMEM;
-	hx509_clear_error_string(context);
-	goto out;
-    }
-
-    ret =3D copy_AlgorithmIdentifier(&digest, &sd.digestAlgorithms.val[0]);
-    if (ret) {
-	hx509_clear_error_string(context);
-	goto out;
-    }
+    sigctx->sd.signerInfos.len++;
+    signer_info =3D NULL;
=20
     /*
      * Provide best effort path
      */
-    if (pool) {
-	_hx509_calculate_path(context,
-			      HX509_CALCULATE_PATH_NO_ANCHOR,			     =20
-			      time(NULL),
-			      anchors,
-			      0,
-			      cert,
-			      pool,
-			      &path);
-    } else
-	_hx509_path_append(context, &path, cert);
+    if (sigctx->certs) {
+	unsigned int i;
=20
-
-    if (path.len) {
-	int i;
-
-	ALLOC(sd.certificates, 1);
-	if (sd.certificates =3D=3D NULL) {
-	    hx509_clear_error_string(context);
-	    ret =3D ENOMEM;
-	    goto out;
-	}
-	ALLOC_SEQ(sd.certificates, path.len);
-	if (sd.certificates->val =3D=3D NULL) {
-	    hx509_clear_error_string(context);
-	    ret =3D ENOMEM;
-	    goto out;
-	}
+	if (sigctx->pool && sigctx->leafonly =3D=3D 0) {
+	    _hx509_calculate_path(context,
+				  HX509_CALCULATE_PATH_NO_ANCHOR,
+				  time(NULL),
+				  sigctx->anchors,
+				  0,
+				  cert,
+				  sigctx->pool,
+				  &path);
+	} else
+	    _hx509_path_append(context, &path, cert);
=20
 	for (i =3D 0; i < path.len; i++) {
-	    ret =3D hx509_cert_binary(context, path.val[i],
-				    &sd.certificates->val[i]);
+	    /* XXX remove dups */
+	    ret =3D hx509_certs_add(context, sigctx->certs, path.val[i]);
 	    if (ret) {
 		hx509_clear_error_string(context);
 		goto out;
@@ -1343,9 +1394,180 @@
 	}
     }
=20
+ out:
+    if (signer_info)
+	free_SignerInfo(signer_info);
+    if (sigdata.data !=3D sigctx->content.data)
+	der_free_octet_string(&sigdata);
+    _hx509_path_free(&path);
+    free_AlgorithmIdentifier(&digest);
+
+    return ret;
+}
+
+static int
+cert_process(hx509_context context, void *ctx, hx509_cert cert)
+{
+    struct sigctx *sigctx =3D ctx;
+    const unsigned int i =3D sigctx->sd.certificates->len;
+    void *ptr;
+    int ret;
+
+    ptr =3D realloc(sigctx->sd.certificates->val,
+		  (i + 1) * sizeof(sigctx->sd.certificates->val[0]));
+    if (ptr =3D=3D NULL)
+	return ENOMEM;
+    sigctx->sd.certificates->val =3D ptr;
+
+    ret =3D hx509_cert_binary(context, cert,
+			    &sigctx->sd.certificates->val[i]);
+    if (ret =3D=3D 0)
+	sigctx->sd.certificates->len++;
+
+    return ret;
+}
+
+static int
+cmp_AlgorithmIdentifier(const AlgorithmIdentifier *p, const AlgorithmIdent=
ifier *q)
+{
+    return der_heim_oid_cmp(&p->algorithm, &q->algorithm);
+}
+
+int
+hx509_cms_create_signed(hx509_context context,
+			int flags,
+			const heim_oid *eContentType,
+			const void *data, size_t length,
+			const AlgorithmIdentifier *digest_alg,
+			hx509_certs certs,
+			hx509_peer_info peer,
+			hx509_certs anchors,
+			hx509_certs pool,
+			heim_octet_string *signed_data)
+{
+    unsigned int i, j;
+    hx509_name name;
+    int ret;
+    size_t size;
+    struct sigctx sigctx;
+
+    memset(&sigctx, 0, sizeof(sigctx));
+    memset(&name, 0, sizeof(name));
+
+    if (eContentType =3D=3D NULL)
+	eContentType =3D &asn1_oid_id_pkcs7_data;
+
+    sigctx.digest_alg =3D digest_alg;
+    sigctx.content.data =3D rk_UNCONST(data);
+    sigctx.content.length =3D length;
+    sigctx.eContentType =3D eContentType;
+    sigctx.peer =3D peer;
+    /**
+     * Use HX509_CMS_SIGNATURE_ID_NAME to preferred use of issuer name
+     * and serial number if possible. Otherwise subject key identifier
+     * will preferred.
+     */
+    if (flags & HX509_CMS_SIGNATURE_ID_NAME)
+	sigctx.cmsidflag =3D CMS_ID_NAME;
+    else
+	sigctx.cmsidflag =3D CMS_ID_SKI;
+
+    /**
+     * Use HX509_CMS_SIGNATURE_LEAF_ONLY to only request leaf
+     * certificates to be added to the SignedData.
+     */
+    sigctx.leafonly =3D (flags & HX509_CMS_SIGNATURE_LEAF_ONLY) ? 1 : 0;
+
+    /**
+     * Use HX509_CMS_NO_CERTS to make the SignedData contain no
+     * certificates, overrides HX509_CMS_SIGNATURE_LEAF_ONLY.
+     */
+
+    if ((flags & HX509_CMS_SIGNATURE_NO_CERTS) =3D=3D 0) {
+	ret =3D hx509_certs_init(context, "MEMORY:certs", 0, NULL, &sigctx.certs);
+	if (ret)
+	    return ret;
+    }
+
+    sigctx.anchors =3D anchors;
+    sigctx.pool =3D pool;
+
+    sigctx.sd.version =3D CMSVersion_v3;
+
+    der_copy_oid(eContentType, &sigctx.sd.encapContentInfo.eContentType);
+
+    /**
+     * Use HX509_CMS_SIGNATURE_DETACHED to create detached signatures.
+     */
+    if ((flags & HX509_CMS_SIGNATURE_DETACHED) =3D=3D 0) {
+	ALLOC(sigctx.sd.encapContentInfo.eContent, 1);
+	if (sigctx.sd.encapContentInfo.eContent =3D=3D NULL) {
+	    hx509_clear_error_string(context);
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+
+	sigctx.sd.encapContentInfo.eContent->data =3D malloc(length);
+	if (sigctx.sd.encapContentInfo.eContent->data =3D=3D NULL) {
+	    hx509_clear_error_string(context);
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+	memcpy(sigctx.sd.encapContentInfo.eContent->data, data, length);
+	sigctx.sd.encapContentInfo.eContent->length =3D length;
+    }
+
+    /**
+     * Use HX509_CMS_SIGNATURE_NO_SIGNER to create no sigInfo (no
+     * signatures).
+     */
+    if ((flags & HX509_CMS_SIGNATURE_NO_SIGNER) =3D=3D 0) {
+	ret =3D hx509_certs_iter_f(context, certs, sig_process, &sigctx);
+	if (ret)
+	    goto out;
+    }
+
+    if (sigctx.sd.signerInfos.len) {
+
+	/*
+	 * For each signerInfo, collect all different digest types.
+	 */
+	for (i =3D 0; i < sigctx.sd.signerInfos.len; i++) {
+	    AlgorithmIdentifier *di =3D
+		&sigctx.sd.signerInfos.val[i].digestAlgorithm;
+
+	    for (j =3D 0; j < sigctx.sd.digestAlgorithms.len; j++)
+		if (cmp_AlgorithmIdentifier(di, &sigctx.sd.digestAlgorithms.val[j]) =3D=
=3D 0)
+		    break;
+	    if (j =3D=3D sigctx.sd.digestAlgorithms.len) {
+		ret =3D add_DigestAlgorithmIdentifiers(&sigctx.sd.digestAlgorithms, di);
+		if (ret) {
+		    hx509_clear_error_string(context);
+		    goto out;
+		}
+	    }
+	}
+    }
+
+    /*
+     * Add certs we think are needed, build as part of sig_process
+     */
+    if (sigctx.certs) {
+	ALLOC(sigctx.sd.certificates, 1);
+	if (sigctx.sd.certificates =3D=3D NULL) {
+	    hx509_clear_error_string(context);
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+
+	ret =3D hx509_certs_iter_f(context, sigctx.certs, cert_process, &sigctx);
+	if (ret)
+	    goto out;
+    }
+
     ASN1_MALLOC_ENCODE(SignedData,
 		       signed_data->data, signed_data->length,
-		       &sd, &size, ret);
+		       &sigctx.sd, &size, ret);
     if (ret) {
 	hx509_clear_error_string(context);
 	goto out;
@@ -1354,11 +1576,8 @@
 	_hx509_abort("internal ASN.1 encoder error");
=20
 out:
-    if (sigdata.data !=3D content.data)
-	der_free_octet_string(&sigdata);
-    free_AlgorithmIdentifier(&digest);
-    _hx509_path_free(&path);
-    free_SignedData(&sd);
+    hx509_certs_free(&sigctx.certs);
+    free_SignedData(&sigctx.sd);
=20
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/collecto=
r.c
--- a/head/crypto/heimdal/lib/hx509/collector.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hx509/collector.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: collector.c 20778 2007-06-01 22:04:13Z lha $");
=20
 struct private_key {
     AlgorithmIdentifier alg;
@@ -106,14 +105,14 @@
 {
     free_AlgorithmIdentifier(&key->alg);
     if (key->private_key)
-	_hx509_private_key_free(&key->private_key);
+	hx509_private_key_free(&key->private_key);
     der_free_octet_string(&key->localKeyId);
     free(key);
 }
=20
 int
 _hx509_collector_private_key_add(hx509_context context,
-				 struct hx509_collector *c,=20
+				 struct hx509_collector *c,
 				 const AlgorithmIdentifier *alg,
 				 hx509_private_key private_key,
 				 const heim_octet_string *key_data,
@@ -134,7 +133,7 @@
 	return ENOMEM;
     }
     c->val.data =3D d;
-=09
+
     ret =3D copy_AlgorithmIdentifier(alg, &key->alg);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "Failed to copy "
@@ -144,8 +143,9 @@
     if (private_key) {
 	key->private_key =3D private_key;
     } else {
-	ret =3D _hx509_parse_private_key(context, &alg->algorithm,
+	ret =3D hx509_parse_private_key(context, alg,
 				       key_data->data, key_data->length,
+				       HX509_KEY_FORMAT_DER,
 				       &key->private_key);
 	if (ret)
 	    goto out;
@@ -153,7 +153,7 @@
     if (localKeyId) {
 	ret =3D der_copy_octet_string(localKeyId, &key->localKeyId);
 	if (ret) {
-	    hx509_set_error_string(context, 0, ret,=20
+	    hx509_set_error_string(context, 0, ret,
 				   "Failed to copy localKeyId");
 	    goto out;
 	}
@@ -187,12 +187,12 @@
=20
     _hx509_query_clear(&q);
     q.match |=3D HX509_QUERY_MATCH_LOCAL_KEY_ID;
-   =20
+
     q.local_key_id =3D &value->localKeyId;
-   =20
+
     ret =3D hx509_certs_find(context, certs, &q, &cert);
     if (ret =3D=3D 0) {
-=09
+
 	if (value->private_key)
 	    _hx509_cert_assign_key(cert, value->private_key);
 	hx509_cert_free(cert);
@@ -208,7 +208,7 @@
     int ret, found =3D HX509_CERT_NOT_FOUND;
=20
     if (value->private_key =3D=3D NULL) {
-	hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,=20
+	hx509_set_error_string(context, 0, HX509_PRIVATE_KEY_MISSING,
 			       "No private key to compare with");
 	return HX509_PRIVATE_KEY_MISSING;
     }
@@ -248,12 +248,13 @@
 }
=20
 int
-_hx509_collector_collect_certs(hx509_context context,=20
+_hx509_collector_collect_certs(hx509_context context,
 			       struct hx509_collector *c,
 			       hx509_certs *ret_certs)
 {
     hx509_certs certs;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     *ret_certs =3D NULL;
=20
@@ -282,11 +283,11 @@
 }
=20
 int
-_hx509_collector_collect_private_keys(hx509_context context,=20
+_hx509_collector_collect_private_keys(hx509_context context,
 				      struct hx509_collector *c,
 				      hx509_private_key **keys)
 {
-    int i, nkeys;
+    size_t i, nkeys;
=20
     *keys =3D NULL;
=20
@@ -306,7 +307,7 @@
 	    c->val.data[i]->private_key =3D NULL;
 	}
     }
-    (*keys)[nkeys++] =3D NULL;
+    (*keys)[nkeys] =3D NULL;
=20
     return 0;
 }
@@ -315,7 +316,7 @@
 void
 _hx509_collector_free(struct hx509_collector *c)
 {
-    int i;
+    size_t i;
=20
     if (c->unenvelop_certs)
 	hx509_certs_free(&c->unenvelop_certs);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/crmf.asn1
--- a/head/crypto/heimdal/lib/hx509/crmf.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/crmf.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
--- $Id: crmf.asn1 17102 2006-04-18 13:05:21Z lha $
+-- $Id$
 PKCS10 DEFINITIONS ::=3D
=20
 BEGIN
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/crypto.c
--- a/head/crypto/heimdal/lib/hx509/crypto.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/crypto.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,47 +1,42 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: crypto.c 22435 2008-01-14 20:53:56Z lha $");
=20
 struct hx509_crypto;
=20
 struct signature_alg;
=20
-enum crypto_op_type {
-    COT_SIGN
-};
-
 struct hx509_generate_private_context {
     const heim_oid *key_oid;
     int isCA;
@@ -50,40 +45,23 @@
=20
 struct hx509_private_key_ops {
     const char *pemtype;
-    const heim_oid *(*key_oid)(void);
+    const heim_oid *key_oid;
+    int (*available)(const hx509_private_key,
+		     const AlgorithmIdentifier *);
     int (*get_spki)(hx509_context,
 		    const hx509_private_key,
 		    SubjectPublicKeyInfo *);
     int (*export)(hx509_context context,
 		  const hx509_private_key,
+		  hx509_key_format_t,
 		  heim_octet_string *);
-    int (*import)(hx509_context,
-		  const void *data,
-		  size_t len,
-		  hx509_private_key private_key);
+    int (*import)(hx509_context, const AlgorithmIdentifier *,
+		  const void *, size_t, hx509_key_format_t,
+		  hx509_private_key);
     int (*generate_private_key)(hx509_context,
 				struct hx509_generate_private_context *,
 				hx509_private_key);
     BIGNUM *(*get_internal)(hx509_context, hx509_private_key, const char *=
);
-    int (*handle_alg)(const hx509_private_key,
-		      const AlgorithmIdentifier *,
-		      enum crypto_op_type);
-    int (*sign)(hx509_context context,
-		const hx509_private_key,
-		const AlgorithmIdentifier *,
-		const heim_octet_string *,
-		AlgorithmIdentifier *,
-		heim_octet_string *);
-#if 0
-    const AlgorithmIdentifier *(*preferred_sig_alg)
-	(const hx509_private_key,
-	 const hx509_peer_info);
-    int (*unwrap)(hx509_context context,
-		  const hx509_private_key,
-		  const AlgorithmIdentifier *,
-		  const heim_octet_string *,
-		  heim_octet_string *);
-#endif
 };
=20
 struct hx509_private_key {
@@ -93,8 +71,10 @@
     union {
 	RSA *rsa;
 	void *keydata;
+#ifdef HAVE_OPENSSL
+	EC_KEY *ecdsa;
+#endif
     } private_key;
-    /* new crypto layer */
     hx509_private_key_ops *ops;
 };
=20
@@ -104,13 +84,14 @@
=20
 struct signature_alg {
     const char *name;
-    const heim_oid *(*sig_oid)(void);
-    const AlgorithmIdentifier *(*sig_alg)(void);
-    const heim_oid *(*key_oid)(void);
-    const heim_oid *(*digest_oid)(void);
+    const heim_oid *sig_oid;
+    const AlgorithmIdentifier *sig_alg;
+    const heim_oid *key_oid;
+    const AlgorithmIdentifier *digest_alg;
     int flags;
-#define PROVIDE_CONF 1
-#define REQUIRE_SIGNER 2
+#define PROVIDE_CONF	0x1
+#define REQUIRE_SIGNER	0x2
+#define SELF_SIGNED_OK	0x4
=20
 #define SIG_DIGEST	0x100
 #define SIG_PUBLIC_SIG	0x200
@@ -118,7 +99,8 @@
=20
 #define RA_RSA_USES_DIGEST_INFO 0x1000000
=20
-
+    time_t best_before; /* refuse signature made after best before date */
+    const EVP_MD *(*evp_md)(void);
     int (*verify_signature)(hx509_context context,
 			    const struct signature_alg *,
 			    const Certificate *,
@@ -132,6 +114,106 @@
 			    const heim_octet_string *,
 			    AlgorithmIdentifier *,
 			    heim_octet_string *);
+    int digest_size;
+};
+
+static const struct signature_alg *
+find_sig_alg(const heim_oid *oid);
+
+/*
+ *
+ */
+
+static const heim_octet_string null_entry_oid =3D { 2, rk_UNCONST("\x05\x0=
0") };
+
+static const unsigned sha512_oid_tree[] =3D { 2, 16, 840, 1, 101, 3, 4, 2,=
 3 };
+const AlgorithmIdentifier _hx509_signature_sha512_data =3D {
+    { 9, rk_UNCONST(sha512_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned sha384_oid_tree[] =3D { 2, 16, 840, 1, 101, 3, 4, 2,=
 2 };
+const AlgorithmIdentifier _hx509_signature_sha384_data =3D {
+    { 9, rk_UNCONST(sha384_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned sha256_oid_tree[] =3D { 2, 16, 840, 1, 101, 3, 4, 2,=
 1 };
+const AlgorithmIdentifier _hx509_signature_sha256_data =3D {
+    { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned sha1_oid_tree[] =3D { 1, 3, 14, 3, 2, 26 };
+const AlgorithmIdentifier _hx509_signature_sha1_data =3D {
+    { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned md5_oid_tree[] =3D { 1, 2, 840, 113549, 2, 5 };
+const AlgorithmIdentifier _hx509_signature_md5_data =3D {
+    { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid)
+};
+
+static const unsigned ecPublicKey[] =3D{ 1, 2, 840, 10045, 2, 1 };
+const AlgorithmIdentifier _hx509_signature_ecPublicKey =3D {
+    { 6, rk_UNCONST(ecPublicKey) }, NULL
+};
+
+static const unsigned ecdsa_with_sha256_oid[] =3D{ 1, 2, 840, 10045, 4, 3,=
 2 };
+const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha256_data =3D {
+    { 7, rk_UNCONST(ecdsa_with_sha256_oid) }, NULL
+};
+
+static const unsigned ecdsa_with_sha1_oid[] =3D{ 1, 2, 840, 10045, 4, 1 };
+const AlgorithmIdentifier _hx509_signature_ecdsa_with_sha1_data =3D {
+    { 6, rk_UNCONST(ecdsa_with_sha1_oid) }, NULL
+};
+
+static const unsigned rsa_with_sha512_oid[] =3D{ 1, 2, 840, 113549, 1, 1, =
13 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha512_data =3D {
+    { 7, rk_UNCONST(rsa_with_sha512_oid) }, NULL
+};
+
+static const unsigned rsa_with_sha384_oid[] =3D{ 1, 2, 840, 113549, 1, 1, =
12 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha384_data =3D {
+    { 7, rk_UNCONST(rsa_with_sha384_oid) }, NULL
+};
+
+static const unsigned rsa_with_sha256_oid[] =3D{ 1, 2, 840, 113549, 1, 1, =
11 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha256_data =3D {
+    { 7, rk_UNCONST(rsa_with_sha256_oid) }, NULL
+};
+
+static const unsigned rsa_with_sha1_oid[] =3D{ 1, 2, 840, 113549, 1, 1, 5 =
};
+const AlgorithmIdentifier _hx509_signature_rsa_with_sha1_data =3D {
+    { 7, rk_UNCONST(rsa_with_sha1_oid) }, NULL
+};
+
+static const unsigned rsa_with_md5_oid[] =3D{ 1, 2, 840, 113549, 1, 1, 4 };
+const AlgorithmIdentifier _hx509_signature_rsa_with_md5_data =3D {
+    { 7, rk_UNCONST(rsa_with_md5_oid) }, NULL
+};
+
+static const unsigned rsa_oid[] =3D{ 1, 2, 840, 113549, 1, 1, 1 };
+const AlgorithmIdentifier _hx509_signature_rsa_data =3D {
+    { 7, rk_UNCONST(rsa_oid) }, NULL
+};
+
+static const unsigned rsa_pkcs1_x509_oid[] =3D{ 1, 2, 752, 43, 16, 1 };
+const AlgorithmIdentifier _hx509_signature_rsa_pkcs1_x509_data =3D {
+    { 6, rk_UNCONST(rsa_pkcs1_x509_oid) }, NULL
+};
+
+static const unsigned des_rsdi_ede3_cbc_oid[] =3D{ 1, 2, 840, 113549, 3, 7=
 };
+const AlgorithmIdentifier _hx509_des_rsdi_ede3_cbc_oid =3D {
+    { 6, rk_UNCONST(des_rsdi_ede3_cbc_oid) }, NULL
+};
+
+static const unsigned aes128_cbc_oid[] =3D{ 2, 16, 840, 1, 101, 3, 4, 1, 2=
 };
+const AlgorithmIdentifier _hx509_crypto_aes128_cbc_data =3D {
+    { 9, rk_UNCONST(aes128_cbc_oid) }, NULL
+};
+
+static const unsigned aes256_cbc_oid[] =3D{ 2, 16, 840, 1, 101, 3, 4, 1, 4=
2 };
+const AlgorithmIdentifier _hx509_crypto_aes256_cbc_data =3D {
+    { 9, rk_UNCONST(aes256_cbc_oid) }, NULL
 };
=20
 /*
@@ -184,6 +266,265 @@
     return 0;
 }
=20
+#ifdef HAVE_OPENSSL
+
+static int
+heim_oid2ecnid(heim_oid *oid)
+{
+    /*
+     * Now map to openssl OID fun
+     */
+
+    if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP256R1) =3D=3D 0)
+	return NID_X9_62_prime256v1;
+    else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP160R1) =3D=3D =
0)
+	return NID_secp160r1;
+    else if (der_heim_oid_cmp(oid, ASN1_OID_ID_EC_GROUP_SECP160R2) =3D=3D =
0)
+	return NID_secp160r2;
+
+    return -1;
+}
+
+static int
+parse_ECParameters(hx509_context context,
+		   heim_octet_string *parameters, int *nid)
+{
+    ECParameters ecparam;
+    size_t size;
+    int ret;
+
+    if (parameters =3D=3D NULL) {
+	ret =3D HX509_PARSING_KEY_FAILED;
+	hx509_set_error_string(context, 0, ret,
+			       "EC parameters missing");
+	return ret;
+    }
+
+    ret =3D decode_ECParameters(parameters->data, parameters->length,
+			      &ecparam, &size);
+    if (ret) {
+	hx509_set_error_string(context, 0, ret,
+			       "Failed to decode EC parameters");
+	return ret;
+    }
+
+    if (ecparam.element !=3D choice_ECParameters_namedCurve) {
+	free_ECParameters(&ecparam);
+	hx509_set_error_string(context, 0, ret,
+			       "EC parameters is not a named curve");
+	return HX509_CRYPTO_SIG_INVALID_FORMAT;
+    }
+
+    *nid =3D heim_oid2ecnid(&ecparam.u.namedCurve);
+    free_ECParameters(&ecparam);
+    if (*nid =3D=3D -1) {
+	hx509_set_error_string(context, 0, ret,
+			       "Failed to find matcing NID for EC curve");
+	return HX509_CRYPTO_SIG_INVALID_FORMAT;
+    }
+    return 0;
+}
+
+
+/*
+ *
+ */
+
+static int
+ecdsa_verify_signature(hx509_context context,
+		       const struct signature_alg *sig_alg,
+		       const Certificate *signer,
+		       const AlgorithmIdentifier *alg,
+		       const heim_octet_string *data,
+		       const heim_octet_string *sig)
+{
+    const AlgorithmIdentifier *digest_alg;
+    const SubjectPublicKeyInfo *spi;
+    heim_octet_string digest;
+    int ret;
+    EC_KEY *key =3D NULL;
+    int groupnid;
+    EC_GROUP *group;
+    const unsigned char *p;
+    long len;
+
+    digest_alg =3D sig_alg->digest_alg;
+
+    ret =3D _hx509_create_signature(context,
+				  NULL,
+				  digest_alg,
+				  data,
+				  NULL,
+				  &digest);
+    if (ret)
+	return ret;
+
+    /* set up EC KEY */
+    spi =3D &signer->tbsCertificate.subjectPublicKeyInfo;
+
+    if (der_heim_oid_cmp(&spi->algorithm.algorithm, ASN1_OID_ID_ECPUBLICKE=
Y) !=3D 0)
+	return HX509_CRYPTO_SIG_INVALID_FORMAT;
+
+#ifdef HAVE_OPENSSL
+    /*
+     * Find the group id
+     */
+
+    ret =3D parse_ECParameters(context, spi->algorithm.parameters, &groupn=
id);
+    if (ret) {
+	der_free_octet_string(&digest);
+	return ret;
+    }
+
+    /*
+     * Create group, key, parse key
+     */
+
+    key =3D EC_KEY_new();
+    group =3D EC_GROUP_new_by_curve_name(groupnid);
+    EC_KEY_set_group(key, group);
+    EC_GROUP_free(group);
+
+    p =3D spi->subjectPublicKey.data;
+    len =3D spi->subjectPublicKey.length / 8;
+
+    if (o2i_ECPublicKey(&key, &p, len) =3D=3D NULL) {
+	EC_KEY_free(key);
+	return HX509_CRYPTO_SIG_INVALID_FORMAT;
+    }
+#else
+    key =3D SubjectPublicKeyInfo2EC_KEY(spi);
+#endif
+
+    ret =3D ECDSA_verify(-1, digest.data, digest.length,
+		       sig->data, sig->length, key);
+    der_free_octet_string(&digest);
+    EC_KEY_free(key);
+    if (ret !=3D 1) {
+	ret =3D HX509_CRYPTO_SIG_INVALID_FORMAT;
+	return ret;
+    }
+
+    return 0;
+}
+
+static int
+ecdsa_create_signature(hx509_context context,
+		       const struct signature_alg *sig_alg,
+		       const hx509_private_key signer,
+		       const AlgorithmIdentifier *alg,
+		       const heim_octet_string *data,
+		       AlgorithmIdentifier *signatureAlgorithm,
+		       heim_octet_string *sig)
+{
+    const AlgorithmIdentifier *digest_alg;
+    heim_octet_string indata;
+    const heim_oid *sig_oid;
+    unsigned int siglen;
+    int ret;
+
+    if (signer->ops && der_heim_oid_cmp(signer->ops->key_oid, ASN1_OID_ID_=
ECPUBLICKEY) !=3D 0)
+	_hx509_abort("internal error passing private key to wrong ops");
+
+    sig_oid =3D sig_alg->sig_oid;
+    digest_alg =3D sig_alg->digest_alg;
+
+    if (signatureAlgorithm) {
+	ret =3D set_digest_alg(signatureAlgorithm, sig_oid, "\x05\x00", 2);
+	if (ret) {
+	    hx509_clear_error_string(context);
+	    goto error;
+	}
+    }
+
+    ret =3D _hx509_create_signature(context,
+				  NULL,
+				  digest_alg,
+				  data,
+				  NULL,
+				  &indata);
+    if (ret) {
+	if (signatureAlgorithm)
+	    free_AlgorithmIdentifier(signatureAlgorithm);
+	goto error;
+    }
+
+    sig->length =3D ECDSA_size(signer->private_key.ecdsa);
+    sig->data =3D malloc(sig->length);
+    if (sig->data =3D=3D NULL) {
+	der_free_octet_string(&indata);
+	ret =3D ENOMEM;
+	hx509_set_error_string(context, 0, ret, "out of memory");
+	goto error;
+    }
+
+    siglen =3D sig->length;
+
+    ret =3D ECDSA_sign(-1, indata.data, indata.length,
+		     sig->data, &siglen, signer->private_key.ecdsa);
+    der_free_octet_string(&indata);
+    if (ret !=3D 1) {
+	ret =3D HX509_CMS_FAILED_CREATE_SIGATURE;
+	hx509_set_error_string(context, 0, ret,
+			       "ECDSA sign failed: %d", ret);
+	goto error;
+    }
+    if (siglen > sig->length)
+	_hx509_abort("ECDSA signature prelen longer the output len");
+
+    sig->length =3D siglen;
+
+    return 0;
+ error:
+    if (signatureAlgorithm)
+	free_AlgorithmIdentifier(signatureAlgorithm);
+    return ret;
+}
+
+static int
+ecdsa_available(const hx509_private_key signer,
+		const AlgorithmIdentifier *sig_alg)
+{
+    const struct signature_alg *sig;
+    const EC_GROUP *group;
+    BN_CTX *bnctx =3D NULL;
+    BIGNUM *order =3D NULL;
+    int ret =3D 0;
+
+    if (der_heim_oid_cmp(signer->ops->key_oid, &asn1_oid_id_ecPublicKey) !=
=3D 0)
+	_hx509_abort("internal error passing private key to wrong ops");
+
+    sig =3D find_sig_alg(&sig_alg->algorithm);
+
+    if (sig =3D=3D NULL || sig->digest_size =3D=3D 0)
+	return 0;
+
+    group =3D EC_KEY_get0_group(signer->private_key.ecdsa);
+    if (group =3D=3D NULL)
+	return 0;
+
+    bnctx =3D BN_CTX_new();
+    order =3D BN_new();
+    if (order =3D=3D NULL)
+	goto err;
+
+    if (EC_GROUP_get_order(group, order, bnctx) !=3D 1)
+	goto err;
+
+    if (BN_num_bytes(order) > sig->digest_size)
+	ret =3D 1;
+ err:
+    if (bnctx)
+	BN_CTX_free(bnctx);
+    if (order)
+	BN_clear_free(order);
+
+    return ret;
+}
+
+
+#endif /* HAVE_OPENSSL */
+
 /*
  *
  */
@@ -202,32 +543,18 @@
     int tosize, retsize;
     int ret;
     RSA *rsa;
-    RSAPublicKey pk;
     size_t size;
+    const unsigned char *p;
=20
     memset(&di, 0, sizeof(di));
=20
     spi =3D &signer->tbsCertificate.subjectPublicKeyInfo;
=20
-    rsa =3D RSA_new();
+    p =3D spi->subjectPublicKey.data;
+    size =3D spi->subjectPublicKey.length / 8;
+
+    rsa =3D d2i_RSAPublicKey(NULL, &p, size);
     if (rsa =3D=3D NULL) {
-	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
-	return ENOMEM;
-    }
-    ret =3D decode_RSAPublicKey(spi->subjectPublicKey.data,
-			      spi->subjectPublicKey.length / 8,
-			      &pk, &size);
-    if (ret) {
-	hx509_set_error_string(context, 0, ret, "Failed to decode RSAPublicKey");
-	goto out;
-    }
-
-    rsa->n =3D heim_int2BN(&pk.modulus);
-    rsa->e =3D heim_int2BN(&pk.publicExponent);
-
-    free_RSAPublicKey(&pk);
-
-    if (rsa->n =3D=3D NULL || rsa->e =3D=3D NULL) {
 	ret =3D ENOMEM;
 	hx509_set_error_string(context, 0, ret, "out of memory");
 	goto out;
@@ -241,11 +568,11 @@
 	goto out;
     }
=20
-    retsize =3D RSA_public_decrypt(sig->length, (unsigned char *)sig->data=
,=20
+    retsize =3D RSA_public_decrypt(sig->length, (unsigned char *)sig->data,
 				 to, rsa, RSA_PKCS1_PADDING);
     if (retsize <=3D 0) {
 	ret =3D HX509_CRYPTO_SIG_INVALID_FORMAT;
-	hx509_set_error_string(context, 0, ret,=20
+	hx509_set_error_string(context, 0, ret,
 			       "RSA public decrypt failed: %d", retsize);
 	free(to);
 	goto out;
@@ -260,23 +587,23 @@
 	if (ret) {
 	    goto out;
 	}
-=09
+
 	/* Check for extra data inside the sigature */
-	if (size !=3D retsize) {
+	if (size !=3D (size_t)retsize) {
 	    ret =3D HX509_CRYPTO_SIG_INVALID_FORMAT;
 	    hx509_set_error_string(context, 0, ret, "size from decryption mismatc=
h");
 	    goto out;
 	}
-=09
-	if (sig_alg->digest_oid &&
-	    der_heim_oid_cmp(&di.digestAlgorithm.algorithm,=20
-			     (*sig_alg->digest_oid)()) !=3D 0)=20
+
+	if (sig_alg->digest_alg &&
+	    der_heim_oid_cmp(&di.digestAlgorithm.algorithm,
+			     &sig_alg->digest_alg->algorithm) !=3D 0)
 	{
 	    ret =3D HX509_CRYPTO_OID_MISMATCH;
 	    hx509_set_error_string(context, 0, ret, "object identifier in RSA sig=
 mismatch");
 	    goto out;
 	}
-=09
+
 	/* verify that the parameters are NULL or the NULL-type */
 	if (di.digestAlgorithm.parameters !=3D NULL &&
 	    (di.digestAlgorithm.parameters->length !=3D 2 ||
@@ -293,8 +620,8 @@
 				      data,
 				      &di.digest);
     } else {
-	if (retsize !=3D data->length ||
-	    memcmp(to, data->data, retsize) !=3D 0)
+	if ((size_t)retsize !=3D data->length ||
+	    ct_memcmp(to, data->data, retsize) !=3D 0)
 	{
 	    ret =3D HX509_CRYPTO_SIG_INVALID_FORMAT;
 	    hx509_set_error_string(context, 0, ret, "RSA Signature incorrect");
@@ -302,10 +629,12 @@
 	}
 	free(to);
     }
+    ret =3D 0;
=20
  out:
     free_DigestInfo(&di);
-    RSA_free(rsa);
+    if (rsa)
+	RSA_free(rsa);
     return ret;
 }
=20
@@ -323,25 +652,32 @@
     const heim_oid *sig_oid;
     size_t size;
     int ret;
-   =20
+
+    if (signer->ops && der_heim_oid_cmp(signer->ops->key_oid, ASN1_OID_ID_=
PKCS1_RSAENCRYPTION) !=3D 0)
+	return HX509_ALG_NOT_SUPP;
+
     if (alg)
 	sig_oid =3D &alg->algorithm;
     else
 	sig_oid =3D signer->signature_alg;
=20
-    if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_sha256WithRSAEncryption()) =
=3D=3D 0) {
+    if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTIO=
N) =3D=3D 0) {
+	digest_alg =3D hx509_signature_sha512();
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA384WITHRSAEN=
CRYPTION) =3D=3D 0) {
+	digest_alg =3D hx509_signature_sha384();
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA256WITHRSAEN=
CRYPTION) =3D=3D 0) {
 	digest_alg =3D hx509_signature_sha256();
-    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_sha1WithRSAEncryptio=
n()) =3D=3D 0) {
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_SHA1WITHRSAENCR=
YPTION) =3D=3D 0) {
 	digest_alg =3D hx509_signature_sha1();
-    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_md5WithRSAEncryption=
()) =3D=3D 0) {
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRY=
PTION) =3D=3D 0) {
 	digest_alg =3D hx509_signature_md5();
-    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_md5WithRSAEncryption=
()) =3D=3D 0) {
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_MD5WITHRSAENCRY=
PTION) =3D=3D 0) {
 	digest_alg =3D hx509_signature_md5();
-    } else if (der_heim_oid_cmp(sig_oid, oid_id_dsa_with_sha1()) =3D=3D 0)=
 {
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_DSA_WITH_SHA1) =3D=3D=
 0) {
 	digest_alg =3D hx509_signature_sha1();
-    } else if (der_heim_oid_cmp(sig_oid, oid_id_pkcs1_rsaEncryption()) =3D=
=3D 0) {
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) =
=3D=3D 0) {
 	digest_alg =3D hx509_signature_sha1();
-    } else if (der_heim_oid_cmp(sig_oid, oid_id_heim_rsa_pkcs1_x509()) =3D=
=3D 0) {
+    } else if (der_heim_oid_cmp(sig_oid, ASN1_OID_ID_HEIM_RSA_PKCS1_X509) =
=3D=3D 0) {
 	digest_alg =3D NULL;
     } else
 	return HX509_ALG_NOT_SUPP;
@@ -391,8 +727,8 @@
 	return ENOMEM;
     }
=20
-    ret =3D RSA_private_encrypt(indata.length, indata.data,=20
-			      sig->data,=20
+    ret =3D RSA_private_encrypt(indata.length, indata.data,
+			      sig->data,
 			      signer->private_key.rsa,
 			      RSA_PKCS1_PADDING);
     if (indata.data !=3D data->data)
@@ -400,33 +736,43 @@
     if (ret <=3D 0) {
 	ret =3D HX509_CMS_FAILED_CREATE_SIGATURE;
 	hx509_set_error_string(context, 0, ret,
-			       "RSA private decrypt failed: %d", ret);
+			       "RSA private encrypt failed: %d", ret);
 	return ret;
     }
-    if (ret > sig->length)
+    if ((size_t)ret > sig->length)
 	_hx509_abort("RSA signature prelen longer the output len");
=20
     sig->length =3D ret;
-   =20
+
     return 0;
 }
=20
 static int
 rsa_private_key_import(hx509_context context,
+		       const AlgorithmIdentifier *keyai,
 		       const void *data,
 		       size_t len,
+		       hx509_key_format_t format,
 		       hx509_private_key private_key)
 {
-    const unsigned char *p =3D data;
-
-    private_key->private_key.rsa =3D=20
-	d2i_RSAPrivateKey(NULL, &p, len);
-    if (private_key->private_key.rsa =3D=3D NULL) {
-	hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
-			       "Failed to parse RSA key");
-	return HX509_PARSING_KEY_FAILED;
+    switch (format) {
+    case HX509_KEY_FORMAT_DER: {
+	const unsigned char *p =3D data;
+
+	private_key->private_key.rsa =3D
+	    d2i_RSAPrivateKey(NULL, &p, len);
+	if (private_key->private_key.rsa =3D=3D NULL) {
+	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+				   "Failed to parse RSA key");
+	    return HX509_PARSING_KEY_FAILED;
+	}
+	private_key->signature_alg =3D ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
+	break;
+
     }
-    private_key->signature_alg =3D oid_id_pkcs1_sha1WithRSAEncryption();
+    default:
+	return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
+    }
=20
     return 0;
 }
@@ -449,7 +795,7 @@
     }
     spki->subjectPublicKey.length =3D len * 8;
=20
-    ret =3D set_digest_alg(&spki->algorithm,oid_id_pkcs1_rsaEncryption(),=20
+    ret =3D set_digest_alg(&spki->algorithm, ASN1_OID_ID_PKCS1_RSAENCRYPTI=
ON,
 			 "\x05\x00", 2);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "malloc - out of memory");
@@ -468,7 +814,7 @@
 }
=20
 static int
-rsa_generate_private_key(hx509_context context,=20
+rsa_generate_private_key(hx509_context context,
 			 struct hx509_generate_private_context *ctx,
 			 hx509_private_key private_key)
 {
@@ -477,7 +823,7 @@
     unsigned long bits;
=20
     static const int default_rsa_e =3D 65537;
-    static const int default_rsa_bits =3D 1024;
+    static const int default_rsa_bits =3D 2048;
=20
     private_key->private_key.rsa =3D RSA_new();
     if (private_key->private_key.rsa =3D=3D NULL) {
@@ -485,7 +831,7 @@
 			       "Failed to generate RSA key");
 	return HX509_PARSING_KEY_FAILED;
     }
-   =20
+
     e =3D BN_new();
     BN_set_word(e, default_rsa_e);
=20
@@ -493,8 +839,6 @@
=20
     if (ctx->num_bits)
 	bits =3D ctx->num_bits;
-    else if (ctx->isCA)
-	bits *=3D 2;
=20
     ret =3D RSA_generate_key_ex(private_key->private_key.rsa, bits, e, NUL=
L);
     BN_free(e);
@@ -503,14 +847,15 @@
 			       "Failed to generate RSA key");
 	return HX509_PARSING_KEY_FAILED;
     }
-    private_key->signature_alg =3D oid_id_pkcs1_sha1WithRSAEncryption();
+    private_key->signature_alg =3D ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
=20
     return 0;
 }
=20
-static int=20
+static int
 rsa_private_key_export(hx509_context context,
 		       const hx509_private_key key,
+		       hx509_key_format_t format,
 		       heim_octet_string *data)
 {
     int ret;
@@ -518,32 +863,41 @@
     data->data =3D NULL;
     data->length =3D 0;
=20
-    ret =3D i2d_RSAPrivateKey(key->private_key.rsa, NULL);
-    if (ret <=3D 0) {
-	ret =3D EINVAL;
-	hx509_set_error_string(context, 0, ret,
+    switch (format) {
+    case HX509_KEY_FORMAT_DER:
+
+	ret =3D i2d_RSAPrivateKey(key->private_key.rsa, NULL);
+	if (ret <=3D 0) {
+	    ret =3D EINVAL;
+	    hx509_set_error_string(context, 0, ret,
 			       "Private key is not exportable");
-	return ret;
-    }
-
-    data->data =3D malloc(ret);
-    if (data->data =3D=3D NULL) {
-	ret =3D ENOMEM;
-	hx509_set_error_string(context, 0, ret, "malloc out of memory");
-	return ret;
-    }
-    data->length =3D ret;
-   =20
-    {
-	unsigned char *p =3D data->data;
-	i2d_RSAPrivateKey(key->private_key.rsa, &p);
+	    return ret;
+	}
+
+	data->data =3D malloc(ret);
+	if (data->data =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    hx509_set_error_string(context, 0, ret, "malloc out of memory");
+	    return ret;
+	}
+	data->length =3D ret;
+
+	{
+	    unsigned char *p =3D data->data;
+	    i2d_RSAPrivateKey(key->private_key.rsa, &p);
+	}
+	break;
+    default:
+	return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
     }
=20
     return 0;
 }
=20
 static BIGNUM *
-rsa_get_internal(hx509_context context, hx509_private_key key, const char =
*type)
+rsa_get_internal(hx509_context context,
+		 hx509_private_key key,
+		 const char *type)
 {
     if (strcasecmp(type, "rsa-modulus") =3D=3D 0) {
 	return BN_dup(key->private_key.rsa->n);
@@ -557,7 +911,8 @@
=20
 static hx509_private_key_ops rsa_private_key_ops =3D {
     "RSA PRIVATE KEY",
-    oid_id_pkcs1_rsaEncryption,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    NULL,
     rsa_private_key2SPKI,
     rsa_private_key_export,
     rsa_private_key_import,
@@ -565,6 +920,114 @@
     rsa_get_internal
 };
=20
+#ifdef HAVE_OPENSSL
+
+static int
+ecdsa_private_key2SPKI(hx509_context context,
+		       hx509_private_key private_key,
+		       SubjectPublicKeyInfo *spki)
+{
+    memset(spki, 0, sizeof(*spki));
+    return ENOMEM;
+}
+
+static int
+ecdsa_private_key_export(hx509_context context,
+			 const hx509_private_key key,
+			 hx509_key_format_t format,
+			 heim_octet_string *data)
+{
+    return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
+}
+
+static int
+ecdsa_private_key_import(hx509_context context,
+			 const AlgorithmIdentifier *keyai,
+			 const void *data,
+			 size_t len,
+			 hx509_key_format_t format,
+			 hx509_private_key private_key)
+{
+    const unsigned char *p =3D data;
+    EC_KEY **pkey =3D NULL;
+
+    if (keyai->parameters) {
+	EC_GROUP *group;
+	int groupnid;
+	EC_KEY *key;
+	int ret;
+
+	ret =3D parse_ECParameters(context, keyai->parameters, &groupnid);
+	if (ret)
+	    return ret;
+
+	key =3D EC_KEY_new();
+	if (key =3D=3D NULL)
+	    return ENOMEM;
+
+	group =3D EC_GROUP_new_by_curve_name(groupnid);
+	if (group =3D=3D NULL) {
+	    EC_KEY_free(key);
+	    return ENOMEM;
+	}
+	EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
+	if (EC_KEY_set_group(key, group) =3D=3D 0) {
+	    EC_KEY_free(key);
+	    EC_GROUP_free(group);
+	    return ENOMEM;
+	}
+	EC_GROUP_free(group);
+	pkey =3D &key;
+    }
+
+    switch (format) {
+    case HX509_KEY_FORMAT_DER:
+
+	private_key->private_key.ecdsa =3D d2i_ECPrivateKey(pkey, &p, len);
+	if (private_key->private_key.ecdsa =3D=3D NULL) {
+	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
+				   "Failed to parse EC private key");
+	    return HX509_PARSING_KEY_FAILED;
+	}
+	private_key->signature_alg =3D ASN1_OID_ID_ECDSA_WITH_SHA256;
+	break;
+
+    default:
+	return HX509_CRYPTO_KEY_FORMAT_UNSUPPORTED;
+    }
+
+    return 0;
+}
+
+static int
+ecdsa_generate_private_key(hx509_context context,
+			   struct hx509_generate_private_context *ctx,
+			   hx509_private_key private_key)
+{
+    return ENOMEM;
+}
+
+static BIGNUM *
+ecdsa_get_internal(hx509_context context,
+		   hx509_private_key key,
+		   const char *type)
+{
+    return NULL;
+}
+
+
+static hx509_private_key_ops ecdsa_private_key_ops =3D {
+    "EC PRIVATE KEY",
+    ASN1_OID_ID_ECPUBLICKEY,
+    ecdsa_available,
+    ecdsa_private_key2SPKI,
+    ecdsa_private_key_export,
+    ecdsa_private_key_import,
+    ecdsa_generate_private_key,
+    ecdsa_get_internal
+};
+
+#endif /* HAVE_OPENSSL */
=20
 /*
  *
@@ -664,11 +1127,11 @@
 {
     const unsigned char *p =3D data;
=20
-    private_key->private_key.dsa =3D=20
+    private_key->private_key.dsa =3D
 	d2i_DSAPrivateKey(NULL, &p, len);
     if (private_key->private_key.dsa =3D=3D NULL)
 	return EINVAL;
-    private_key->signature_alg =3D oid_id_dsa_with_sha1();
+    private_key->signature_alg =3D ASN1_OID_ID_DSA_WITH_SHA1;
=20
     return 0;
 /* else */
@@ -678,39 +1141,8 @@
 }
 #endif
=20
-
 static int
-sha1_verify_signature(hx509_context context,
-		      const struct signature_alg *sig_alg,
-		      const Certificate *signer,
-		      const AlgorithmIdentifier *alg,
-		      const heim_octet_string *data,
-		      const heim_octet_string *sig)
-{
-    unsigned char digest[SHA_DIGEST_LENGTH];
-    SHA_CTX m;
-   =20
-    if (sig->length !=3D SHA_DIGEST_LENGTH) {
-	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
-			       "SHA1 sigature have wrong length");
-	return HX509_CRYPTO_SIG_INVALID_FORMAT;
-    }
-
-    SHA1_Init(&m);
-    SHA1_Update(&m, data->data, data->length);
-    SHA1_Final (digest, &m);
-=09
-    if (memcmp(digest, sig->data, SHA_DIGEST_LENGTH) !=3D 0) {
-	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
-			       "Bad SHA1 sigature");
-	return HX509_CRYPTO_BAD_SIGNATURE;
-    }
-
-    return 0;
-}
-
-static int
-sha256_create_signature(hx509_context context,
+evp_md_create_signature(hx509_context context,
 			const struct signature_alg *sig_alg,
 			const hx509_private_key signer,
 			const AlgorithmIdentifier *alg,
@@ -718,339 +1150,448 @@
 			AlgorithmIdentifier *signatureAlgorithm,
 			heim_octet_string *sig)
 {
-    SHA256_CTX m;
-   =20
+    size_t sigsize =3D EVP_MD_size(sig_alg->evp_md());
+    EVP_MD_CTX *ctx;
+
     memset(sig, 0, sizeof(*sig));
=20
     if (signatureAlgorithm) {
 	int ret;
-	ret =3D set_digest_alg(signatureAlgorithm, (*sig_alg->sig_oid)(),
+	ret =3D set_digest_alg(signatureAlgorithm, sig_alg->sig_oid,
 			     "\x05\x00", 2);
 	if (ret)
 	    return ret;
     }
-	   =20
-
-    sig->data =3D malloc(SHA256_DIGEST_LENGTH);
+
+
+    sig->data =3D malloc(sigsize);
     if (sig->data =3D=3D NULL) {
 	sig->length =3D 0;
 	return ENOMEM;
     }
-    sig->length =3D SHA256_DIGEST_LENGTH;
-
-    SHA256_Init(&m);
-    SHA256_Update(&m, data->data, data->length);
-    SHA256_Final (sig->data, &m);
+    sig->length =3D sigsize;
+
+    ctx =3D EVP_MD_CTX_create();
+    EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL);
+    EVP_DigestUpdate(ctx, data->data, data->length);
+    EVP_DigestFinal_ex(ctx, sig->data, NULL);
+    EVP_MD_CTX_destroy(ctx);
+
=20
     return 0;
 }
=20
 static int
-sha256_verify_signature(hx509_context context,
+evp_md_verify_signature(hx509_context context,
 			const struct signature_alg *sig_alg,
 			const Certificate *signer,
 			const AlgorithmIdentifier *alg,
 			const heim_octet_string *data,
 			const heim_octet_string *sig)
 {
-    unsigned char digest[SHA256_DIGEST_LENGTH];
-    SHA256_CTX m;
-   =20
-    if (sig->length !=3D SHA256_DIGEST_LENGTH) {
+    unsigned char digest[EVP_MAX_MD_SIZE];
+    EVP_MD_CTX *ctx;
+    size_t sigsize =3D EVP_MD_size(sig_alg->evp_md());
+
+    if (sig->length !=3D sigsize || sigsize > sizeof(digest)) {
 	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
 			       "SHA256 sigature have wrong length");
 	return HX509_CRYPTO_SIG_INVALID_FORMAT;
     }
=20
-    SHA256_Init(&m);
-    SHA256_Update(&m, data->data, data->length);
-    SHA256_Final (digest, &m);
-=09
-    if (memcmp(digest, sig->data, SHA256_DIGEST_LENGTH) !=3D 0) {
+    ctx =3D EVP_MD_CTX_create();
+    EVP_DigestInit_ex(ctx, sig_alg->evp_md(), NULL);
+    EVP_DigestUpdate(ctx, data->data, data->length);
+    EVP_DigestFinal_ex(ctx, digest, NULL);
+    EVP_MD_CTX_destroy(ctx);
+
+    if (ct_memcmp(digest, sig->data, sigsize) !=3D 0) {
 	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
-			       "Bad SHA256 sigature");
+			       "Bad %s sigature", sig_alg->name);
 	return HX509_CRYPTO_BAD_SIGNATURE;
     }
=20
     return 0;
 }
=20
-static int
-sha1_create_signature(hx509_context context,
-		      const struct signature_alg *sig_alg,
-		      const hx509_private_key signer,
-		      const AlgorithmIdentifier *alg,
-		      const heim_octet_string *data,
-		      AlgorithmIdentifier *signatureAlgorithm,
-		      heim_octet_string *sig)
-{
-    SHA_CTX m;
-   =20
-    memset(sig, 0, sizeof(*sig));
-
-    if (signatureAlgorithm) {
-	int ret;
-	ret =3D set_digest_alg(signatureAlgorithm, (*sig_alg->sig_oid)(),=20
-			     "\x05\x00", 2);
-	if (ret)
-	    return ret;
-    }
-	   =20
-
-    sig->data =3D malloc(SHA_DIGEST_LENGTH);
-    if (sig->data =3D=3D NULL) {
-	sig->length =3D 0;
-	return ENOMEM;
-    }
-    sig->length =3D SHA_DIGEST_LENGTH;
-
-    SHA1_Init(&m);
-    SHA1_Update(&m, data->data, data->length);
-    SHA1_Final (sig->data, &m);
-
-    return 0;
-}
-
-static int
-md5_verify_signature(hx509_context context,
-		     const struct signature_alg *sig_alg,
-		     const Certificate *signer,
-		     const AlgorithmIdentifier *alg,
-		     const heim_octet_string *data,
-		     const heim_octet_string *sig)
-{
-    unsigned char digest[MD5_DIGEST_LENGTH];
-    MD5_CTX m;
-   =20
-    if (sig->length !=3D MD5_DIGEST_LENGTH) {
-	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
-			       "MD5 sigature have wrong length");
-	return HX509_CRYPTO_SIG_INVALID_FORMAT;
-    }
-
-    MD5_Init(&m);
-    MD5_Update(&m, data->data, data->length);
-    MD5_Final (digest, &m);
-=09
-    if (memcmp(digest, sig->data, MD5_DIGEST_LENGTH) !=3D 0) {
-	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
-			       "Bad MD5 sigature");
-	return HX509_CRYPTO_BAD_SIGNATURE;
-    }
-
-    return 0;
-}
-
-static int
-md2_verify_signature(hx509_context context,
-		     const struct signature_alg *sig_alg,
-		     const Certificate *signer,
-		     const AlgorithmIdentifier *alg,
-		     const heim_octet_string *data,
-		     const heim_octet_string *sig)
-{
-    unsigned char digest[MD2_DIGEST_LENGTH];
-    MD2_CTX m;
-   =20
-    if (sig->length !=3D MD2_DIGEST_LENGTH) {
-	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
-			       "MD2 sigature have wrong length");
-	return HX509_CRYPTO_SIG_INVALID_FORMAT;
-    }
-
-    MD2_Init(&m);
-    MD2_Update(&m, data->data, data->length);
-    MD2_Final (digest, &m);
-=09
-    if (memcmp(digest, sig->data, MD2_DIGEST_LENGTH) !=3D 0) {
-	hx509_set_error_string(context, 0, HX509_CRYPTO_BAD_SIGNATURE,
-			       "Bad MD2 sigature");
-	return HX509_CRYPTO_BAD_SIGNATURE;
-    }
-
-    return 0;
-}
+#ifdef HAVE_OPENSSL
+
+static const struct signature_alg ecdsa_with_sha256_alg =3D {
+    "ecdsa-with-sha256",
+    ASN1_OID_ID_ECDSA_WITH_SHA256,
+    &_hx509_signature_ecdsa_with_sha256_data,
+    ASN1_OID_ID_ECPUBLICKEY,
+    &_hx509_signature_sha256_data,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
+    ecdsa_verify_signature,
+    ecdsa_create_signature,
+    32
+};
+
+static const struct signature_alg ecdsa_with_sha1_alg =3D {
+    "ecdsa-with-sha1",
+    ASN1_OID_ID_ECDSA_WITH_SHA1,
+    &_hx509_signature_ecdsa_with_sha1_data,
+    ASN1_OID_ID_ECPUBLICKEY,
+    &_hx509_signature_sha1_data,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
+    ecdsa_verify_signature,
+    ecdsa_create_signature,
+    20
+};
+
+#endif
=20
 static const struct signature_alg heim_rsa_pkcs1_x509 =3D {
     "rsa-pkcs1-x509",
-    oid_id_heim_rsa_pkcs1_x509,
-    hx509_signature_rsa_pkcs1_x509,
-    oid_id_pkcs1_rsaEncryption,
+    ASN1_OID_ID_HEIM_RSA_PKCS1_X509,
+    &_hx509_signature_rsa_pkcs1_x509_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
     NULL,
     PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
+    0,
+    NULL,
     rsa_verify_signature,
-    rsa_create_signature
+    rsa_create_signature,
+    0
 };
=20
 static const struct signature_alg pkcs1_rsa_sha1_alg =3D {
     "rsa",
-    oid_id_pkcs1_rsaEncryption,
-    hx509_signature_rsa_with_sha1,
-    oid_id_pkcs1_rsaEncryption,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    &_hx509_signature_rsa_with_sha1_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
     NULL,
-    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
     rsa_verify_signature,
-    rsa_create_signature
+    rsa_create_signature,
+    0
+};
+
+static const struct signature_alg rsa_with_sha512_alg =3D {
+    "rsa-with-sha512",
+    ASN1_OID_ID_PKCS1_SHA512WITHRSAENCRYPTION,
+    &_hx509_signature_rsa_with_sha512_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    &_hx509_signature_sha512_data,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
+    rsa_verify_signature,
+    rsa_create_signature,
+    0
+};
+
+static const struct signature_alg rsa_with_sha384_alg =3D {
+    "rsa-with-sha384",
+    ASN1_OID_ID_PKCS1_SHA384WITHRSAENCRYPTION,
+    &_hx509_signature_rsa_with_sha384_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    &_hx509_signature_sha384_data,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
+    rsa_verify_signature,
+    rsa_create_signature,
+    0
 };
=20
 static const struct signature_alg rsa_with_sha256_alg =3D {
     "rsa-with-sha256",
-    oid_id_pkcs1_sha256WithRSAEncryption,
-    hx509_signature_rsa_with_sha256,
-    oid_id_pkcs1_rsaEncryption,
-    oid_id_sha256,
-    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG,
+    ASN1_OID_ID_PKCS1_SHA256WITHRSAENCRYPTION,
+    &_hx509_signature_rsa_with_sha256_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    &_hx509_signature_sha256_data,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
     rsa_verify_signature,
-    rsa_create_signature
+    rsa_create_signature,
+    0
 };
=20
 static const struct signature_alg rsa_with_sha1_alg =3D {
     "rsa-with-sha1",
-    oid_id_pkcs1_sha1WithRSAEncryption,
-    hx509_signature_rsa_with_sha1,
-    oid_id_pkcs1_rsaEncryption,
-    oid_id_secsig_sha_1,
-    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG,
+    ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION,
+    &_hx509_signature_rsa_with_sha1_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    &_hx509_signature_sha1_data,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
     rsa_verify_signature,
-    rsa_create_signature
+    rsa_create_signature,
+    0
+};
+
+static const struct signature_alg rsa_with_sha1_alg_secsig =3D {
+    "rsa-with-sha1",
+    ASN1_OID_ID_SECSIG_SHA_1WITHRSAENCRYPTION,
+    &_hx509_signature_rsa_with_sha1_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    &_hx509_signature_sha1_data,
+    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG|SEL=
F_SIGNED_OK,
+    0,
+    NULL,
+    rsa_verify_signature,
+    rsa_create_signature,
+    0
 };
=20
 static const struct signature_alg rsa_with_md5_alg =3D {
     "rsa-with-md5",
-    oid_id_pkcs1_md5WithRSAEncryption,
-    hx509_signature_rsa_with_md5,
-    oid_id_pkcs1_rsaEncryption,
-    oid_id_rsa_digest_md5,
+    ASN1_OID_ID_PKCS1_MD5WITHRSAENCRYPTION,
+    &_hx509_signature_rsa_with_md5_data,
+    ASN1_OID_ID_PKCS1_RSAENCRYPTION,
+    &_hx509_signature_md5_data,
     PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG,
+    1230739889,
+    NULL,
     rsa_verify_signature,
-    rsa_create_signature
-};
-
-static const struct signature_alg rsa_with_md2_alg =3D {
-    "rsa-with-md2",
-    oid_id_pkcs1_md2WithRSAEncryption,
-    hx509_signature_rsa_with_md2,
-    oid_id_pkcs1_rsaEncryption,
-    oid_id_rsa_digest_md2,
-    PROVIDE_CONF|REQUIRE_SIGNER|RA_RSA_USES_DIGEST_INFO|SIG_PUBLIC_SIG,
-    rsa_verify_signature,
-    rsa_create_signature
+    rsa_create_signature,
+    0
 };
=20
 static const struct signature_alg dsa_sha1_alg =3D {
     "dsa-with-sha1",
-    oid_id_dsa_with_sha1,
+    ASN1_OID_ID_DSA_WITH_SHA1,
     NULL,
-    oid_id_dsa,=20
-    oid_id_secsig_sha_1,
+    ASN1_OID_ID_DSA,
+    &_hx509_signature_sha1_data,
     PROVIDE_CONF|REQUIRE_SIGNER|SIG_PUBLIC_SIG,
+    0,
+    NULL,
     dsa_verify_signature,
     /* create_signature */ NULL,
+    0
+};
+
+static const struct signature_alg sha512_alg =3D {
+    "sha-512",
+    ASN1_OID_ID_SHA512,
+    &_hx509_signature_sha512_data,
+    NULL,
+    NULL,
+    SIG_DIGEST,
+    0,
+    EVP_sha512,
+    evp_md_verify_signature,
+    evp_md_create_signature,
+    0
+};
+
+static const struct signature_alg sha384_alg =3D {
+    "sha-384",
+    ASN1_OID_ID_SHA512,
+    &_hx509_signature_sha384_data,
+    NULL,
+    NULL,
+    SIG_DIGEST,
+    0,
+    EVP_sha384,
+    evp_md_verify_signature,
+    evp_md_create_signature,
+    0
 };
=20
 static const struct signature_alg sha256_alg =3D {
     "sha-256",
-    oid_id_sha256,
-    hx509_signature_sha256,
+    ASN1_OID_ID_SHA256,
+    &_hx509_signature_sha256_data,
     NULL,
     NULL,
     SIG_DIGEST,
-    sha256_verify_signature,
-    sha256_create_signature
+    0,
+    EVP_sha256,
+    evp_md_verify_signature,
+    evp_md_create_signature,
+    0
 };
=20
 static const struct signature_alg sha1_alg =3D {
     "sha1",
-    oid_id_secsig_sha_1,
-    hx509_signature_sha1,
+    ASN1_OID_ID_SECSIG_SHA_1,
+    &_hx509_signature_sha1_data,
     NULL,
     NULL,
     SIG_DIGEST,
-    sha1_verify_signature,
-    sha1_create_signature
+    0,
+    EVP_sha1,
+    evp_md_verify_signature,
+    evp_md_create_signature,
+    0
 };
=20
 static const struct signature_alg md5_alg =3D {
     "rsa-md5",
-    oid_id_rsa_digest_md5,
-    hx509_signature_md5,
+    ASN1_OID_ID_RSA_DIGEST_MD5,
+    &_hx509_signature_md5_data,
     NULL,
     NULL,
     SIG_DIGEST,
-    md5_verify_signature
+    0,
+    EVP_md5,
+    evp_md_verify_signature,
+    NULL,
+    0
 };
=20
-static const struct signature_alg md2_alg =3D {
-    "rsa-md2",
-    oid_id_rsa_digest_md2,
-    hx509_signature_md2,
-    NULL,
-    NULL,
-    SIG_DIGEST,
-    md2_verify_signature
-};
-
-/*=20
+/*
  * Order matter in this structure, "best" first for each "key
- * compatible" type (type is RSA, DSA, none, etc)
+ * compatible" type (type is ECDSA, RSA, DSA, none, etc)
  */
=20
 static const struct signature_alg *sig_algs[] =3D {
+#ifdef HAVE_OPENSSL
+    &ecdsa_with_sha256_alg,
+    &ecdsa_with_sha1_alg,
+#endif
+    &rsa_with_sha512_alg,
+    &rsa_with_sha384_alg,
     &rsa_with_sha256_alg,
     &rsa_with_sha1_alg,
+    &rsa_with_sha1_alg_secsig,
     &pkcs1_rsa_sha1_alg,
     &rsa_with_md5_alg,
-    &rsa_with_md2_alg,
     &heim_rsa_pkcs1_x509,
     &dsa_sha1_alg,
+    &sha512_alg,
+    &sha384_alg,
     &sha256_alg,
     &sha1_alg,
     &md5_alg,
-    &md2_alg,
     NULL
 };
=20
 static const struct signature_alg *
 find_sig_alg(const heim_oid *oid)
 {
-    int i;
+    unsigned int i;
     for (i =3D 0; sig_algs[i]; i++)
-	if (der_heim_oid_cmp((*sig_algs[i]->sig_oid)(), oid) =3D=3D 0)
+	if (der_heim_oid_cmp(sig_algs[i]->sig_oid, oid) =3D=3D 0)
 	    return sig_algs[i];
     return NULL;
 }
=20
+static const AlgorithmIdentifier *
+alg_for_privatekey(const hx509_private_key pk, int type)
+{
+    const heim_oid *keytype;
+    unsigned int i;
+
+    if (pk->ops =3D=3D NULL)
+	return NULL;
+
+    keytype =3D pk->ops->key_oid;
+
+    for (i =3D 0; sig_algs[i]; i++) {
+	if (sig_algs[i]->key_oid =3D=3D NULL)
+	    continue;
+	if (der_heim_oid_cmp(sig_algs[i]->key_oid, keytype) !=3D 0)
+	    continue;
+	if (pk->ops->available &&
+	    pk->ops->available(pk, sig_algs[i]->sig_alg) =3D=3D 0)
+	    continue;
+	if (type =3D=3D HX509_SELECT_PUBLIC_SIG)
+	    return sig_algs[i]->sig_alg;
+	if (type =3D=3D HX509_SELECT_DIGEST)
+	    return sig_algs[i]->digest_alg;
+
+	return NULL;
+    }
+    return NULL;
+}
+
 /*
  *
  */
=20
 static struct hx509_private_key_ops *private_algs[] =3D {
     &rsa_private_key_ops,
+#ifdef HAVE_OPENSSL
+    &ecdsa_private_key_ops,
+#endif
     NULL
 };
=20
-static hx509_private_key_ops *
-find_private_alg(const heim_oid *oid)
+hx509_private_key_ops *
+hx509_find_private_alg(const heim_oid *oid)
 {
     int i;
     for (i =3D 0; private_algs[i]; i++) {
 	if (private_algs[i]->key_oid =3D=3D NULL)
 	    continue;
-	if (der_heim_oid_cmp((*private_algs[i]->key_oid)(), oid) =3D=3D 0)
+	if (der_heim_oid_cmp(private_algs[i]->key_oid, oid) =3D=3D 0)
 	    return private_algs[i];
     }
     return NULL;
 }
=20
+/*
+ * Check if the algorithm `alg' have a best before date, and if it
+ * des, make sure the its before the time `t'.
+ */
+
+int
+_hx509_signature_best_before(hx509_context context,
+			     const AlgorithmIdentifier *alg,
+			     time_t t)
+{
+    const struct signature_alg *md;
+
+    md =3D find_sig_alg(&alg->algorithm);
+    if (md =3D=3D NULL) {
+	hx509_clear_error_string(context);
+	return HX509_SIG_ALG_NO_SUPPORTED;
+    }
+    if (md->best_before && md->best_before < t) {
+	hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE,
+			       "Algorithm %s has passed it best before date",
+			       md->name);
+	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+    }
+    return 0;
+}
+
+int
+_hx509_self_signed_valid(hx509_context context,
+			 const AlgorithmIdentifier *alg)
+{
+    const struct signature_alg *md;
+
+    md =3D find_sig_alg(&alg->algorithm);
+    if (md =3D=3D NULL) {
+	hx509_clear_error_string(context);
+	return HX509_SIG_ALG_NO_SUPPORTED;
+    }
+    if ((md->flags & SELF_SIGNED_OK) =3D=3D 0) {
+	hx509_set_error_string(context, 0, HX509_CRYPTO_ALGORITHM_BEST_BEFORE,
+			       "Algorithm %s not trusted for self signatures",
+			       md->name);
+	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+    }
+    return 0;
+}
+
=20
 int
 _hx509_verify_signature(hx509_context context,
-			const Certificate *signer,
+			const hx509_cert cert,
 			const AlgorithmIdentifier *alg,
 			const heim_octet_string *data,
 			const heim_octet_string *sig)
 {
     const struct signature_alg *md;
+    const Certificate *signer =3D NULL;
+
+    if (cert)
+	signer =3D _hx509_get_cert(cert);
=20
     md =3D find_sig_alg(&alg->algorithm);
     if (md =3D=3D NULL) {
@@ -1069,7 +1610,7 @@
 	const SubjectPublicKeyInfo *spi;
 	spi =3D &signer->tbsCertificate.subjectPublicKeyInfo;
=20
-	if (der_heim_oid_cmp(&spi->algorithm.algorithm, (*md->key_oid)()) !=3D 0)=
 {
+	if (der_heim_oid_cmp(&spi->algorithm.algorithm, md->key_oid) !=3D 0) {
 	    hx509_clear_error_string(context);
 	    return HX509_SIG_ALG_DONT_MATCH_KEY_ALG;
 	}
@@ -1078,27 +1619,6 @@
 }
=20
 int
-_hx509_verify_signature_bitstring(hx509_context context,
-				  const Certificate *signer,
-				  const AlgorithmIdentifier *alg,
-				  const heim_octet_string *data,
-				  const heim_bit_string *sig)
-{
-    heim_octet_string os;
-
-    if (sig->length & 7) {
-	hx509_set_error_string(context, 0, HX509_CRYPTO_SIG_INVALID_FORMAT,
-			       "signature not multiple of 8 bits");
-	return HX509_CRYPTO_SIG_INVALID_FORMAT;
-    }
-
-    os.data =3D sig->data;
-    os.length =3D sig->length / 8;
-   =20
-    return _hx509_verify_signature(context, signer, alg, data, &os);
-}
-
-int
 _hx509_create_signature(hx509_context context,
 			const hx509_private_key signer,
 			const AlgorithmIdentifier *alg,
@@ -1108,13 +1628,6 @@
 {
     const struct signature_alg *md;
=20
-    if (signer && signer->ops && signer->ops->handle_alg &&
-	(*signer->ops->handle_alg)(signer, alg, COT_SIGN))
-    {
-	return (*signer->ops->sign)(context, signer, alg, data,=20
-				    signatureAlgorithm, sig);
-    }
-
     md =3D find_sig_alg(&alg->algorithm);
     if (md =3D=3D NULL) {
 	hx509_set_error_string(context, 0, HX509_SIG_ALG_NO_SUPPORTED,
@@ -1128,7 +1641,7 @@
 	return HX509_CRYPTO_SIG_NO_CONF;
     }
=20
-    return (*md->create_signature)(context, md, signer, alg, data,=20
+    return (*md->create_signature)(context, md, signer, alg, data,
 				   signatureAlgorithm, sig);
 }
=20
@@ -1164,39 +1677,23 @@
     int tosize;
     int ret;
     RSA *rsa;
-    RSAPublicKey pk;
     size_t size;
+    const unsigned char *p;
=20
     ciphertext->data =3D NULL;
     ciphertext->length =3D 0;
=20
     spi =3D &cert->tbsCertificate.subjectPublicKeyInfo;
=20
-    rsa =3D RSA_new();
+    p =3D spi->subjectPublicKey.data;
+    size =3D spi->subjectPublicKey.length / 8;
+
+    rsa =3D d2i_RSAPublicKey(NULL, &p, size);
     if (rsa =3D=3D NULL) {
 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
 	return ENOMEM;
     }
=20
-    ret =3D decode_RSAPublicKey(spi->subjectPublicKey.data,
-			      spi->subjectPublicKey.length / 8,
-			      &pk, &size);
-    if (ret) {
-	RSA_free(rsa);
-	hx509_set_error_string(context, 0, ret, "RSAPublicKey decode failure");
-	return ret;
-    }
-    rsa->n =3D heim_int2BN(&pk.modulus);
-    rsa->e =3D heim_int2BN(&pk.publicExponent);
-
-    free_RSAPublicKey(&pk);
-
-    if (rsa->n =3D=3D NULL || rsa->e =3D=3D NULL) {
-	RSA_free(rsa);
-	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
-	return ENOMEM;
-    }
-
     tosize =3D RSA_size(rsa);
     to =3D malloc(tosize);
     if (to =3D=3D NULL) {
@@ -1205,8 +1702,8 @@
 	return ENOMEM;
     }
=20
-    ret =3D RSA_public_encrypt(cleartext->length,=20
-			     (unsigned char *)cleartext->data,=20
+    ret =3D RSA_public_encrypt(cleartext->length,
+			     (unsigned char *)cleartext->data,
 			     to, rsa, RSA_PKCS1_PADDING);
     RSA_free(rsa);
     if (ret <=3D 0) {
@@ -1221,7 +1718,7 @@
     ciphertext->length =3D ret;
     ciphertext->data =3D to;
=20
-    ret =3D der_copy_oid(oid_id_pkcs1_rsaEncryption(), encryption_oid);
+    ret =3D der_copy_oid(ASN1_OID_ID_PKCS1_RSAENCRYPTION, encryption_oid);
     if (ret) {
 	der_free_octet_string(ciphertext);
 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
@@ -1232,7 +1729,7 @@
 }
=20
 int
-_hx509_private_key_private_decrypt(hx509_context context,
+hx509_private_key_private_decrypt(hx509_context context,
 				   const heim_octet_string *ciphertext,
 				   const heim_oid *encryption_oid,
 				   hx509_private_key p,
@@ -1265,7 +1762,7 @@
 			       "Failed to decrypt using private key: %d", ret);
 	return HX509_CRYPTO_RSA_PRIVATE_DECRYPT;
     }
-    if (cleartext->length < ret)
+    if (cleartext->length < (size_t)ret)
 	_hx509_abort("internal rsa decryption failure: ret > tosize");
=20
     cleartext->length =3D ret;
@@ -1275,10 +1772,11 @@
=20
=20
 int
-_hx509_parse_private_key(hx509_context context,
-			 const heim_oid *key_oid,
+hx509_parse_private_key(hx509_context context,
+			 const AlgorithmIdentifier *keyai,
 			 const void *data,
 			 size_t len,
+			 hx509_key_format_t format,
 			 hx509_private_key *private_key)
 {
     struct hx509_private_key_ops *ops;
@@ -1286,21 +1784,21 @@
=20
     *private_key =3D NULL;
=20
-    ops =3D find_private_alg(key_oid);
+    ops =3D hx509_find_private_alg(&keyai->algorithm);
     if (ops =3D=3D NULL) {
 	hx509_clear_error_string(context);
 	return HX509_SIG_ALG_NO_SUPPORTED;
     }
=20
-    ret =3D _hx509_private_key_init(private_key, ops, NULL);
+    ret =3D hx509_private_key_init(private_key, ops, NULL);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "out of memory");
 	return ret;
     }
=20
-    ret =3D (*ops->import)(context, data, len, *private_key);
+    ret =3D (*ops->import)(context, keyai, data, len, format, *private_key=
);
     if (ret)
-	_hx509_private_key_free(private_key);
+	hx509_private_key_free(private_key);
=20
     return ret;
 }
@@ -1310,7 +1808,7 @@
  */
=20
 int
-_hx509_private_key2SPKI(hx509_context context,
+hx509_private_key2SPKI(hx509_context context,
 			hx509_private_key private_key,
 			SubjectPublicKeyInfo *spki)
 {
@@ -1330,8 +1828,8 @@
 {
     *ctx =3D NULL;
=20
-    if (der_heim_oid_cmp(oid, oid_id_pkcs1_rsaEncryption()) !=3D 0) {
-	hx509_set_error_string(context, 0, EINVAL,=20
+    if (der_heim_oid_cmp(oid, ASN1_OID_ID_PKCS1_RSAENCRYPTION) !=3D 0) {
+	hx509_set_error_string(context, 0, EINVAL,
 			       "private key not an RSA key");
 	return EINVAL;
     }
@@ -1381,13 +1879,13 @@
=20
     *private_key =3D NULL;
=20
-    ops =3D find_private_alg(ctx->key_oid);
+    ops =3D hx509_find_private_alg(ctx->key_oid);
     if (ops =3D=3D NULL) {
 	hx509_clear_error_string(context);
 	return HX509_SIG_ALG_NO_SUPPORTED;
     }
=20
-    ret =3D _hx509_private_key_init(private_key, ops, NULL);
+    ret =3D hx509_private_key_init(private_key, ops, NULL);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "out of memory");
 	return ret;
@@ -1395,103 +1893,15 @@
=20
     ret =3D (*ops->generate_private_key)(context, ctx, *private_key);
     if (ret)
-	_hx509_private_key_free(private_key);
+	hx509_private_key_free(private_key);
=20
     return ret;
 }
=20
-
 /*
  *
  */
=20
-static const heim_octet_string null_entry_oid =3D { 2, rk_UNCONST("\x05\x0=
0") };
-
-static const unsigned sha512_oid_tree[] =3D { 2, 16, 840, 1, 101, 3, 4, 2,=
 3 };
-const AlgorithmIdentifier _hx509_signature_sha512_data =3D {=20
-    { 9, rk_UNCONST(sha512_oid_tree) }, rk_UNCONST(&null_entry_oid)
-};
-
-static const unsigned sha384_oid_tree[] =3D { 2, 16, 840, 1, 101, 3, 4, 2,=
 2 };
-const AlgorithmIdentifier _hx509_signature_sha384_data =3D {=20
-    { 9, rk_UNCONST(sha384_oid_tree) }, rk_UNCONST(&null_entry_oid)
-};
-
-static const unsigned sha256_oid_tree[] =3D { 2, 16, 840, 1, 101, 3, 4, 2,=
 1 };
-const AlgorithmIdentifier _hx509_signature_sha256_data =3D {=20
-    { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid)
-};
-
-static const unsigned sha1_oid_tree[] =3D { 1, 3, 14, 3, 2, 26 };
-const AlgorithmIdentifier _hx509_signature_sha1_data =3D {=20
-    { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid)
-};
-
-static const unsigned md5_oid_tree[] =3D { 1, 2, 840, 113549, 2, 5 };
-const AlgorithmIdentifier _hx509_signature_md5_data =3D {=20
-    { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid)
-};
-
-static const unsigned md2_oid_tree[] =3D { 1, 2, 840, 113549, 2, 2 };
-const AlgorithmIdentifier _hx509_signature_md2_data =3D {=20
-    { 6, rk_UNCONST(md2_oid_tree) }, rk_UNCONST(&null_entry_oid)
-};
-
-static const unsigned rsa_with_sha512_oid[] =3D{ 1, 2, 840, 113549, 1, 1, =
13 };
-const AlgorithmIdentifier _hx509_signature_rsa_with_sha512_data =3D {=20
-    { 7, rk_UNCONST(rsa_with_sha512_oid) }, NULL
-};
-
-static const unsigned rsa_with_sha384_oid[] =3D{ 1, 2, 840, 113549, 1, 1, =
12 };
-const AlgorithmIdentifier _hx509_signature_rsa_with_sha384_data =3D {=20
-    { 7, rk_UNCONST(rsa_with_sha384_oid) }, NULL
-};
-
-static const unsigned rsa_with_sha256_oid[] =3D{ 1, 2, 840, 113549, 1, 1, =
11 };
-const AlgorithmIdentifier _hx509_signature_rsa_with_sha256_data =3D {=20
-    { 7, rk_UNCONST(rsa_with_sha256_oid) }, NULL
-};
-
-static const unsigned rsa_with_sha1_oid[] =3D{ 1, 2, 840, 113549, 1, 1, 5 =
};
-const AlgorithmIdentifier _hx509_signature_rsa_with_sha1_data =3D {=20
-    { 7, rk_UNCONST(rsa_with_sha1_oid) }, NULL
-};
-
-static const unsigned rsa_with_md5_oid[] =3D{ 1, 2, 840, 113549, 1, 1, 4 };
-const AlgorithmIdentifier _hx509_signature_rsa_with_md5_data =3D {=20
-    { 7, rk_UNCONST(rsa_with_md5_oid) }, NULL
-};
-
-static const unsigned rsa_with_md2_oid[] =3D{ 1, 2, 840, 113549, 1, 1, 2 };
-const AlgorithmIdentifier _hx509_signature_rsa_with_md2_data =3D {=20
-    { 7, rk_UNCONST(rsa_with_md2_oid) }, NULL
-};
-
-static const unsigned rsa_oid[] =3D{ 1, 2, 840, 113549, 1, 1, 1 };
-const AlgorithmIdentifier _hx509_signature_rsa_data =3D {=20
-    { 7, rk_UNCONST(rsa_oid) }, NULL
-};
-
-static const unsigned rsa_pkcs1_x509_oid[] =3D{ 1, 2, 752, 43, 16, 1 };
-const AlgorithmIdentifier _hx509_signature_rsa_pkcs1_x509_data =3D {=20
-    { 6, rk_UNCONST(rsa_pkcs1_x509_oid) }, NULL
-};
-
-static const unsigned des_rsdi_ede3_cbc_oid[] =3D{ 1, 2, 840, 113549, 3, 7=
 };
-const AlgorithmIdentifier _hx509_des_rsdi_ede3_cbc_oid =3D {
-    { 6, rk_UNCONST(des_rsdi_ede3_cbc_oid) }, NULL
-};
-
-static const unsigned aes128_cbc_oid[] =3D{ 2, 16, 840, 1, 101, 3, 4, 1, 2=
 };
-const AlgorithmIdentifier _hx509_crypto_aes128_cbc_data =3D {
-    { 9, rk_UNCONST(aes128_cbc_oid) }, NULL
-};
-
-static const unsigned aes256_cbc_oid[] =3D{ 2, 16, 840, 1, 101, 3, 4, 1, 4=
2 };
-const AlgorithmIdentifier _hx509_crypto_aes256_cbc_data =3D {
-    { 9, rk_UNCONST(aes256_cbc_oid) }, NULL
-};
-
 const AlgorithmIdentifier *
 hx509_signature_sha512(void)
 { return &_hx509_signature_sha512_data; }
@@ -1513,8 +1923,16 @@
 { return &_hx509_signature_md5_data; }
=20
 const AlgorithmIdentifier *
-hx509_signature_md2(void)
-{ return &_hx509_signature_md2_data; }
+hx509_signature_ecPublicKey(void)
+{ return &_hx509_signature_ecPublicKey; }
+
+const AlgorithmIdentifier *
+hx509_signature_ecdsa_with_sha256(void)
+{ return &_hx509_signature_ecdsa_with_sha256_data; }
+
+const AlgorithmIdentifier *
+hx509_signature_ecdsa_with_sha1(void)
+{ return &_hx509_signature_ecdsa_with_sha1_data; }
=20
 const AlgorithmIdentifier *
 hx509_signature_rsa_with_sha512(void)
@@ -1537,10 +1955,6 @@
 { return &_hx509_signature_rsa_with_md5_data; }
=20
 const AlgorithmIdentifier *
-hx509_signature_rsa_with_md2(void)
-{ return &_hx509_signature_rsa_with_md2_data; }
-
-const AlgorithmIdentifier *
 hx509_signature_rsa(void)
 { return &_hx509_signature_rsa_data; }
=20
@@ -1564,11 +1978,11 @@
  *
  */
=20
-const AlgorithmIdentifier * _hx509_crypto_default_sig_alg =3D=20
-    &_hx509_signature_rsa_with_sha1_data;
-const AlgorithmIdentifier * _hx509_crypto_default_digest_alg =3D=20
-    &_hx509_signature_sha1_data;
-const AlgorithmIdentifier * _hx509_crypto_default_secret_alg =3D=20
+const AlgorithmIdentifier * _hx509_crypto_default_sig_alg =3D
+    &_hx509_signature_rsa_with_sha256_data;
+const AlgorithmIdentifier * _hx509_crypto_default_digest_alg =3D
+    &_hx509_signature_sha256_data;
+const AlgorithmIdentifier * _hx509_crypto_default_secret_alg =3D
     &_hx509_crypto_aes128_cbc_data;
=20
 /*
@@ -1576,7 +1990,7 @@
  */
=20
 int
-_hx509_private_key_init(hx509_private_key *key,
+hx509_private_key_init(hx509_private_key *key,
 			hx509_private_key_ops *ops,
 			void *keydata)
 {
@@ -1592,11 +2006,11 @@
 hx509_private_key
 _hx509_private_key_ref(hx509_private_key key)
 {
-    if (key->ref <=3D 0)
-	_hx509_abort("refcount <=3D 0");
+    if (key->ref =3D=3D 0)
+	_hx509_abort("key refcount <=3D 0 on ref");
     key->ref++;
-    if (key->ref =3D=3D 0)
-	_hx509_abort("refcount =3D=3D 0");
+    if (key->ref =3D=3D UINT_MAX)
+	_hx509_abort("key refcount =3D=3D UINT_MAX on ref");
     return key;
 }
=20
@@ -1607,18 +2021,25 @@
 }
=20
 int
-_hx509_private_key_free(hx509_private_key *key)
+hx509_private_key_free(hx509_private_key *key)
 {
     if (key =3D=3D NULL || *key =3D=3D NULL)
 	return 0;
=20
-    if ((*key)->ref <=3D 0)
-	_hx509_abort("refcount <=3D 0");
+    if ((*key)->ref =3D=3D 0)
+	_hx509_abort("key refcount =3D=3D 0 on free");
     if (--(*key)->ref > 0)
 	return 0;
=20
-    if ((*key)->private_key.rsa)
-	RSA_free((*key)->private_key.rsa);
+    if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid, ASN1_OID_ID_=
PKCS1_RSAENCRYPTION) =3D=3D 0) {
+	if ((*key)->private_key.rsa)
+	    RSA_free((*key)->private_key.rsa);
+#ifdef HAVE_OPENSSL
+    } else if ((*key)->ops && der_heim_oid_cmp((*key)->ops->key_oid, ASN1_=
OID_ID_ECPUBLICKEY) =3D=3D 0) {
+	if ((*key)->private_key.ecdsa)
+	    EC_KEY_free((*key)->private_key.ecdsa);
+#endif
+    }
     (*key)->private_key.rsa =3D NULL;
     free(*key);
     *key =3D NULL;
@@ -1626,22 +2047,22 @@
 }
=20
 void
-_hx509_private_key_assign_rsa(hx509_private_key key, void *ptr)
+hx509_private_key_assign_rsa(hx509_private_key key, void *ptr)
 {
     if (key->private_key.rsa)
 	RSA_free(key->private_key.rsa);
     key->private_key.rsa =3D ptr;
-    key->signature_alg =3D oid_id_pkcs1_sha1WithRSAEncryption();
+    key->signature_alg =3D ASN1_OID_ID_PKCS1_SHA1WITHRSAENCRYPTION;
     key->md =3D &pkcs1_rsa_sha1_alg;
 }
=20
-int=20
+int
 _hx509_private_key_oid(hx509_context context,
 		       const hx509_private_key key,
 		       heim_oid *data)
 {
     int ret;
-    ret =3D der_copy_oid((*key->ops->key_oid)(), data);
+    ret =3D der_copy_oid(key->ops->key_oid, data);
     if (ret)
 	hx509_set_error_string(context, 0, ret, "malloc out of memory");
     return ret;
@@ -1657,7 +2078,7 @@
=20
 BIGNUM *
 _hx509_private_key_get_internal(hx509_context context,
-				hx509_private_key key,=20
+				hx509_private_key key,
 				const char *type)
 {
     if (key->ops->get_internal =3D=3D NULL)
@@ -1665,16 +2086,17 @@
     return (*key->ops->get_internal)(context, key, type);
 }
=20
-int=20
+int
 _hx509_private_key_export(hx509_context context,
 			  const hx509_private_key key,
+			  hx509_key_format_t format,
 			  heim_octet_string *data)
 {
     if (key->ops->export =3D=3D NULL) {
 	hx509_clear_error_string(context);
 	return HX509_UNIMPLEMENTED_OPERATION;
     }
-    return (*key->ops->export)(context, key, data);
+    return (*key->ops->export)(context, key, format, data);
 }
=20
 /*
@@ -1683,17 +2105,25 @@
=20
 struct hx509cipher {
     const char *name;
-    const heim_oid *(*oid_func)(void);
+    int flags;
+#define CIPHER_WEAK 1
+    const heim_oid *oid;
     const AlgorithmIdentifier *(*ai_func)(void);
     const EVP_CIPHER *(*evp_func)(void);
     int (*get_params)(hx509_context, const hx509_crypto,
 		      const heim_octet_string *, heim_octet_string *);
-    int (*set_params)(hx509_context, const heim_octet_string *,=20
+    int (*set_params)(hx509_context, const heim_octet_string *,
 		      hx509_crypto, heim_octet_string *);
 };
=20
 struct hx509_crypto_data {
     char *name;
+    int flags;
+#define ALLOW_WEAK 	1
+
+#define PADDING_NONE	2
+#define PADDING_PKCS7	4
+#define PADDING_FLAGS	(2|4)
     const struct hx509cipher *cipher;
     const EVP_CIPHER *c;
     heim_octet_string key;
@@ -1705,15 +2135,10 @@
  *
  */
=20
-static const heim_oid *
-oid_private_rc2_40(void)
-{
-    static unsigned oid_data[] =3D { 127, 1 };
-    static const heim_oid oid =3D { 2, oid_data };
-
-    return &oid;
-}
-
+static unsigned private_rc2_40_oid_data[] =3D { 127, 1 };
+
+static heim_oid asn1_oid_private_rc2_40 =3D
+    { 2, private_rc2_40_oid_data };
=20
 /*
  *
@@ -1853,7 +2278,8 @@
 static const struct hx509cipher ciphers[] =3D {
     {
 	"rc2-cbc",
-	oid_id_pkcs3_rc2_cbc,
+	CIPHER_WEAK,
+	ASN1_OID_ID_PKCS3_RC2_CBC,
 	NULL,
 	EVP_rc2_cbc,
 	CMSRC2CBCParam_get,
@@ -1861,7 +2287,8 @@
     },
     {
 	"rc2-cbc",
-	oid_id_rsadsi_rc2_cbc,
+	CIPHER_WEAK,
+	ASN1_OID_ID_RSADSI_RC2_CBC,
 	NULL,
 	EVP_rc2_cbc,
 	CMSRC2CBCParam_get,
@@ -1869,7 +2296,8 @@
     },
     {
 	"rc2-40-cbc",
-	oid_private_rc2_40,
+	CIPHER_WEAK,
+	&asn1_oid_private_rc2_40,
 	NULL,
 	EVP_rc2_40_cbc,
 	CMSRC2CBCParam_get,
@@ -1877,7 +2305,8 @@
     },
     {
 	"des-ede3-cbc",
-	oid_id_pkcs3_des_ede3_cbc,
+	0,
+	ASN1_OID_ID_PKCS3_DES_EDE3_CBC,
 	NULL,
 	EVP_des_ede3_cbc,
 	CMSCBCParam_get,
@@ -1885,7 +2314,8 @@
     },
     {
 	"des-ede3-cbc",
-	oid_id_rsadsi_des_ede3_cbc,
+	0,
+	ASN1_OID_ID_RSADSI_DES_EDE3_CBC,
 	hx509_crypto_des_rsdi_ede3_cbc,
 	EVP_des_ede3_cbc,
 	CMSCBCParam_get,
@@ -1893,7 +2323,8 @@
     },
     {
 	"aes-128-cbc",
-	oid_id_aes_128_cbc,
+	0,
+	ASN1_OID_ID_AES_128_CBC,
 	hx509_crypto_aes128_cbc,
 	EVP_aes_128_cbc,
 	CMSCBCParam_get,
@@ -1901,7 +2332,8 @@
     },
     {
 	"aes-192-cbc",
-	oid_id_aes_192_cbc,
+	0,
+	ASN1_OID_ID_AES_192_CBC,
 	NULL,
 	EVP_aes_192_cbc,
 	CMSCBCParam_get,
@@ -1909,7 +2341,8 @@
     },
     {
 	"aes-256-cbc",
-	oid_id_aes_256_cbc,
+	0,
+	ASN1_OID_ID_AES_256_CBC,
 	hx509_crypto_aes256_cbc,
 	EVP_aes_256_cbc,
 	CMSCBCParam_get,
@@ -1920,10 +2353,10 @@
 static const struct hx509cipher *
 find_cipher_by_oid(const heim_oid *oid)
 {
-    int i;
+    size_t i;
=20
     for (i =3D 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
-	if (der_heim_oid_cmp(oid, (*ciphers[i].oid_func)()) =3D=3D 0)
+	if (der_heim_oid_cmp(oid, ciphers[i].oid) =3D=3D 0)
 	    return &ciphers[i];
=20
     return NULL;
@@ -1932,7 +2365,7 @@
 static const struct hx509cipher *
 find_cipher_by_name(const char *name)
 {
-    int i;
+    size_t i;
=20
     for (i =3D 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++)
 	if (strcasecmp(name, ciphers[i].name) =3D=3D 0)
@@ -1950,7 +2383,7 @@
     cipher =3D find_cipher_by_name(name);
     if (cipher =3D=3D NULL)
 	return NULL;
-    return (*cipher->oid_func)();
+    return cipher->oid;
 }
=20
 int
@@ -1976,6 +2409,7 @@
 	return ENOMEM;
     }
=20
+    (*crypto)->flags =3D PADDING_PKCS7;
     (*crypto)->cipher =3D cipher;
     (*crypto)->c =3D (*cipher->evp_func)();
=20
@@ -2015,10 +2449,33 @@
     return 0;
 }
=20
+void
+hx509_crypto_allow_weak(hx509_crypto crypto)
+{
+    crypto->flags |=3D ALLOW_WEAK;
+}
+
+void
+hx509_crypto_set_padding(hx509_crypto crypto, int padding_type)
+{
+    switch (padding_type) {
+    case HX509_CRYPTO_PADDING_PKCS7:
+	crypto->flags &=3D ~PADDING_FLAGS;
+	crypto->flags |=3D PADDING_PKCS7;
+	break;
+    case HX509_CRYPTO_PADDING_NONE:
+	crypto->flags &=3D ~PADDING_FLAGS;
+	crypto->flags |=3D PADDING_NONE;
+	break;
+    default:
+	_hx509_abort("Invalid padding");
+    }
+}
+
 int
 hx509_crypto_set_key_data(hx509_crypto crypto, const void *data, size_t le=
ngth)
 {
-    if (EVP_CIPHER_key_length(crypto->c) > length)
+    if (EVP_CIPHER_key_length(crypto->c) > (int)length)
 	return HX509_CRYPTO_INTERNAL_ERROR;
=20
     if (crypto->key.data) {
@@ -2063,7 +2520,7 @@
=20
 int
 hx509_crypto_set_params(hx509_context context,
-			hx509_crypto crypto,=20
+			hx509_crypto crypto,
 			const heim_octet_string *param,
 			heim_octet_string *ivec)
 {
@@ -2072,7 +2529,7 @@
=20
 int
 hx509_crypto_get_params(hx509_context context,
-			hx509_crypto crypto,=20
+			hx509_crypto crypto,
 			const heim_octet_string *ivec,
 			heim_octet_string *param)
 {
@@ -2106,12 +2563,16 @@
 		     heim_octet_string **ciphertext)
 {
     EVP_CIPHER_CTX evp;
-    size_t padsize;
+    size_t padsize, bsize;
     int ret;
=20
     *ciphertext =3D NULL;
=20
-    assert(EVP_CIPHER_iv_length(crypto->c) =3D=3D ivec->length);
+    if ((crypto->cipher->flags & CIPHER_WEAK) &&
+	(crypto->flags & ALLOW_WEAK) =3D=3D 0)
+	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+
+    assert(EVP_CIPHER_iv_length(crypto->c) =3D=3D (int)ivec->length);
=20
     EVP_CIPHER_CTX_init(&evp);
=20
@@ -2128,23 +2589,30 @@
 	ret =3D ENOMEM;
 	goto out;
     }
-   =20
-    if (EVP_CIPHER_block_size(crypto->c) =3D=3D 1) {
-	padsize =3D 0;
-    } else {
-	int bsize =3D EVP_CIPHER_block_size(crypto->c);
-	padsize =3D bsize - (length % bsize);
+
+    assert(crypto->flags & PADDING_FLAGS);
+
+    bsize =3D EVP_CIPHER_block_size(crypto->c);
+    padsize =3D 0;
+
+    if (crypto->flags & PADDING_NONE) {
+	if (bsize !=3D 1 && (length % bsize) !=3D 0)
+	    return HX509_CMS_PADDING_ERROR;
+    } else if (crypto->flags & PADDING_PKCS7) {
+	if (bsize !=3D 1)
+	    padsize =3D bsize - (length % bsize);
     }
+
     (*ciphertext)->length =3D length + padsize;
     (*ciphertext)->data =3D malloc(length + padsize);
     if ((*ciphertext)->data =3D=3D NULL) {
 	ret =3D ENOMEM;
 	goto out;
     }
-=09
+
     memcpy((*ciphertext)->data, data, length);
     if (padsize) {
-	int i;
+	size_t i;
 	unsigned char *p =3D (*ciphertext)->data;
 	p +=3D length;
 	for (i =3D 0; i < padsize; i++)
@@ -2189,7 +2657,11 @@
     clear->data =3D NULL;
     clear->length =3D 0;
=20
-    if (ivec && EVP_CIPHER_iv_length(crypto->c) < ivec->length)
+    if ((crypto->cipher->flags & CIPHER_WEAK) &&
+	(crypto->flags & ALLOW_WEAK) =3D=3D 0)
+	return HX509_CRYPTO_ALGORITHM_BEST_BEFORE;
+
+    if (ivec && EVP_CIPHER_iv_length(crypto->c) < (int)ivec->length)
 	return HX509_CRYPTO_INTERNAL_ERROR;
=20
     if (crypto->key.data =3D=3D NULL)
@@ -2220,12 +2692,12 @@
     }
     EVP_CIPHER_CTX_cleanup(&evp);
=20
-    if (EVP_CIPHER_block_size(crypto->c) > 1) {
+    if ((crypto->flags & PADDING_PKCS7) && EVP_CIPHER_block_size(crypto->c=
) > 1) {
 	int padsize;
-	unsigned char *p;=20
+	unsigned char *p;
 	int j, bsize =3D EVP_CIPHER_block_size(crypto->c);
=20
-	if (clear->length < bsize) {
+	if ((int)clear->length < bsize) {
 	    ret =3D HX509_CMS_PADDING_ERROR;
 	    goto out;
 	}
@@ -2259,7 +2731,7 @@
 typedef int (*PBE_string2key_func)(hx509_context,
 				   const char *,
 				   const heim_octet_string *,
-				   hx509_crypto *, heim_octet_string *,=20
+				   hx509_crypto *, heim_octet_string *,
 				   heim_octet_string *,
 				   const heim_oid *, const EVP_MD *);
=20
@@ -2267,7 +2739,7 @@
 PBE_string2key(hx509_context context,
 	       const char *password,
 	       const heim_octet_string *parameters,
-	       hx509_crypto *crypto,=20
+	       hx509_crypto *crypto,
 	       heim_octet_string *key, heim_octet_string *iv,
 	       const heim_oid *enc_oid,
 	       const EVP_MD *md)
@@ -2296,13 +2768,13 @@
     salt =3D p12params.salt.data;
     saltlen =3D p12params.salt.length;
=20
-    if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,=20
+    if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,
 			 PKCS12_KEY_ID, iter, key->length, key->data, md)) {
 	ret =3D HX509_CRYPTO_INTERNAL_ERROR;
 	goto out;
     }
-   =20
-    if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,=20
+
+    if (!PKCS12_key_gen (password, passwordlen, salt, saltlen,
 			 PKCS12_IV_ID, iter, iv->length, iv->data, md)) {
 	ret =3D HX509_CRYPTO_INTERNAL_ERROR;
 	goto out;
@@ -2312,6 +2784,8 @@
     if (ret)
 	goto out;
=20
+    hx509_crypto_allow_weak(c);
+
     ret =3D hx509_crypto_set_key_data(c, key->data, key->length);
     if (ret) {
 	hx509_crypto_destroy(c);
@@ -2325,38 +2799,38 @@
 }
=20
 static const heim_oid *
-find_string2key(const heim_oid *oid,=20
-		const EVP_CIPHER **c,=20
+find_string2key(const heim_oid *oid,
+		const EVP_CIPHER **c,
 		const EVP_MD **md,
 		PBE_string2key_func *s2k)
 {
-    if (der_heim_oid_cmp(oid, oid_id_pbewithSHAAnd40BitRC2_CBC()) =3D=3D 0=
) {
+    if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC2_CBC) =3D=
=3D 0) {
 	*c =3D EVP_rc2_40_cbc();
 	*md =3D EVP_sha1();
 	*s2k =3D PBE_string2key;
-	return oid_private_rc2_40();
-    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd128BitRC2_CBC()) =
=3D=3D 0) {
+	return &asn1_oid_private_rc2_40;
+    } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC2_CB=
C) =3D=3D 0) {
 	*c =3D EVP_rc2_cbc();
 	*md =3D EVP_sha1();
 	*s2k =3D PBE_string2key;
-	return oid_id_pkcs3_rc2_cbc();
+	return ASN1_OID_ID_PKCS3_RC2_CBC;
 #if 0
-    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd40BitRC4()) =3D=
=3D 0) {
+    } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND40BITRC4) =
=3D=3D 0) {
 	*c =3D EVP_rc4_40();
 	*md =3D EVP_sha1();
 	*s2k =3D PBE_string2key;
 	return NULL;
-    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd128BitRC4()) =3D=
=3D 0) {
+    } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND128BITRC4) =
=3D=3D 0) {
 	*c =3D EVP_rc4();
 	*md =3D EVP_sha1();
 	*s2k =3D PBE_string2key;
-	return oid_id_pkcs3_rc4();
+	return ASN1_OID_ID_PKCS3_RC4;
 #endif
-    } else if (der_heim_oid_cmp(oid, oid_id_pbeWithSHAAnd3_KeyTripleDES_CB=
C()) =3D=3D 0) {
+    } else if (der_heim_oid_cmp(oid, ASN1_OID_ID_PBEWITHSHAAND3_KEYTRIPLED=
ES_CBC) =3D=3D 0) {
 	*c =3D EVP_des_ede3_cbc();
 	*md =3D EVP_sha1();
 	*s2k =3D PBE_string2key;
-	return oid_id_pkcs3_des_ede3_cbc();
+	return ASN1_OID_ID_PKCS3_DES_EDE3_CBC;
     }
=20
     return NULL;
@@ -2394,7 +2868,8 @@
     const EVP_CIPHER *c;
     const EVP_MD *md;
     PBE_string2key_func s2k;
-    int i, ret =3D 0;
+    int ret =3D 0;
+    size_t i;
=20
     memset(&key, 0, sizeof(key));
     memset(&iv, 0, sizeof(iv));
@@ -2439,7 +2914,7 @@
 	else
 	    password =3D NULL;
=20
-	ret =3D (*s2k)(context, password, ai->parameters, &crypto,=20
+	ret =3D (*s2k)(context, password, ai->parameters, &crypto,
 		     &key, &iv, enc_oid, md);
 	if (ret)
 	    goto out;
@@ -2452,7 +2927,7 @@
 	hx509_crypto_destroy(crypto);
 	if (ret =3D=3D 0)
 	    goto out;
-				  =20
+
     }
 out:
     if (key.data)
@@ -2467,8 +2942,8 @@
  */
=20
=20
-int
-_hx509_match_keys(hx509_cert c, hx509_private_key private_key)
+static int
+match_keys_rsa(hx509_cert c, hx509_private_key private_key)
 {
     const Certificate *cert;
     const SubjectPublicKeyInfo *spi;
@@ -2510,7 +2985,7 @@
     rsa->dmq1 =3D BN_dup(private_key->private_key.rsa->dmq1);
     rsa->iqmp =3D BN_dup(private_key->private_key.rsa->iqmp);
=20
-    if (rsa->n =3D=3D NULL || rsa->e =3D=3D NULL ||=20
+    if (rsa->n =3D=3D NULL || rsa->e =3D=3D NULL ||
 	rsa->d =3D=3D NULL || rsa->p =3D=3D NULL|| rsa->q =3D=3D NULL ||
 	rsa->dmp1 =3D=3D NULL || rsa->dmq1 =3D=3D NULL) {
 	RSA_free(rsa);
@@ -2523,6 +2998,25 @@
     return ret =3D=3D 1;
 }
=20
+static int
+match_keys_ec(hx509_cert c, hx509_private_key private_key)
+{
+    return 1; /* XXX use EC_KEY_check_key */
+}
+
+
+int
+_hx509_match_keys(hx509_cert c, hx509_private_key key)
+{
+    if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_PKCS1_RSAENCRYPTIO=
N) =3D=3D 0)
+	return match_keys_rsa(c, key);
+    if (der_heim_oid_cmp(key->ops->key_oid, ASN1_OID_ID_ECPUBLICKEY) =3D=
=3D 0)
+	return match_keys_ec(c, key);
+    return 0;
+
+}
+
+
 static const heim_oid *
 find_keytype(const hx509_private_key key)
 {
@@ -2534,10 +3028,9 @@
     md =3D find_sig_alg(key->signature_alg);
     if (md =3D=3D NULL)
 	return NULL;
-    return (*md->key_oid)();
+    return md->key_oid;
 }
=20
-
 int
 hx509_crypto_select(const hx509_context context,
 		    int type,
@@ -2545,7 +3038,7 @@
 		    hx509_peer_info peer,
 		    AlgorithmIdentifier *selected)
 {
-    const AlgorithmIdentifier *def;
+    const AlgorithmIdentifier *def =3D NULL;
     size_t i, j;
     int ret, bits;
=20
@@ -2553,16 +3046,22 @@
=20
     if (type =3D=3D HX509_SELECT_DIGEST) {
 	bits =3D SIG_DIGEST;
-	def =3D _hx509_crypto_default_digest_alg;
+	if (source)
+	    def =3D alg_for_privatekey(source, type);
+	if (def =3D=3D NULL)
+	    def =3D _hx509_crypto_default_digest_alg;
     } else if (type =3D=3D HX509_SELECT_PUBLIC_SIG) {
 	bits =3D SIG_PUBLIC_SIG;
-	/* XXX depend on `source=B4 and `peer=B4 */
-	def =3D _hx509_crypto_default_sig_alg;
+	/* XXX depend on `source=C2=B4 and `peer=C2=B4 */
+	if (source)
+	    def =3D alg_for_privatekey(source, type);
+	if (def =3D=3D NULL)
+	    def =3D _hx509_crypto_default_sig_alg;
     } else if (type =3D=3D HX509_SELECT_SECRET_ENC) {
 	bits =3D SIG_SECRET;
 	def =3D _hx509_crypto_default_secret_alg;
     } else {
-	hx509_set_error_string(context, 0, EINVAL,=20
+	hx509_set_error_string(context, 0, EINVAL,
 			       "Unknown type %d of selection", type);
 	return EINVAL;
     }
@@ -2576,11 +3075,11 @@
 	    for (j =3D 0; sig_algs[j]; j++) {
 		if ((sig_algs[j]->flags & bits) !=3D bits)
 		    continue;
-		if (der_heim_oid_cmp((*sig_algs[j]->sig_oid)(),=20
+		if (der_heim_oid_cmp(sig_algs[j]->sig_oid,
 				     &peer->val[i].algorithm) !=3D 0)
 		    continue;
-		if (keytype && sig_algs[j]->key_oid &&=20
-		    der_heim_oid_cmp(keytype, (*sig_algs[j]->key_oid)()))
+		if (keytype && sig_algs[j]->key_oid &&
+		    der_heim_oid_cmp(keytype, sig_algs[j]->key_oid))
 		    continue;
=20
 		/* found one, use that */
@@ -2633,7 +3132,7 @@
     } else if (type =3D=3D HX509_SELECT_PUBLIC_SIG) {
 	bits =3D SIG_PUBLIC_SIG;
     } else {
-	hx509_set_error_string(context, 0, EINVAL,=20
+	hx509_set_error_string(context, 0, EINVAL,
 			       "Unknown type %d of available", type);
 	return EINVAL;
     }
@@ -2647,8 +3146,8 @@
 	    continue;
 	if (sig_algs[i]->sig_alg =3D=3D NULL)
 	    continue;
-	if (keytype && sig_algs[i]->key_oid &&=20
-	    der_heim_oid_cmp((*sig_algs[i]->key_oid)(), keytype))
+	if (keytype && sig_algs[i]->key_oid &&
+	    der_heim_oid_cmp(sig_algs[i]->key_oid, keytype))
 	    continue;
=20
 	/* found one, add that to the list */
@@ -2657,7 +3156,7 @@
 	    goto out;
 	*val =3D ptr;
=20
-	ret =3D copy_AlgorithmIdentifier((*sig_algs[i]->sig_alg)(), &(*val)[len]);
+	ret =3D copy_AlgorithmIdentifier(sig_algs[i]->sig_alg, &(*val)[len]);
 	if (ret)
 	    goto out;
 	len++;
@@ -2667,7 +3166,9 @@
     if (bits & SIG_SECRET) {
=20
 	for (i =3D 0; i < sizeof(ciphers)/sizeof(ciphers[0]); i++) {
-=09
+
+	    if (ciphers[i].flags & CIPHER_WEAK)
+		continue;
 	    if (ciphers[i].ai_func =3D=3D NULL)
 		continue;
=20
@@ -2675,7 +3176,7 @@
 	    if (ptr =3D=3D NULL)
 		goto out;
 	    *val =3D ptr;
-	   =20
+
 	    ret =3D copy_AlgorithmIdentifier((ciphers[i].ai_func)(), &(*val)[len]=
);
 	    if (ret)
 		goto out;
@@ -2703,4 +3204,4 @@
     for (i =3D 0; i < len; i++)
 	free_AlgorithmIdentifier(&val[i]);
     free(val);
-}   =20
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/doxygen.c
--- a/head/crypto/heimdal/lib/hx509/doxygen.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/doxygen.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /** @mainpage Heimdal PKIX/X.509 library
@@ -37,7 +37,7 @@
  *
  * Heimdal libhx509 library is a implementation of the PKIX/X.509 and
  * related protocols.
- *=20
+ *
  * PKIX/X.509 is ...
  *
  *
@@ -70,7 +70,7 @@
  * See the @ref page_cms for description and examples. */
 /** @defgroup hx509_crypto hx509 crypto functions */
 /** @defgroup hx509_misc hx509 misc functions */
-/** @defgroup hx509_name hx509 name functions=20
+/** @defgroup hx509_name hx509 name functions
  * See the @ref page_name for description and examples. */
 /** @defgroup hx509_revoke hx509 revokation checking functions
  * See the @ref page_revoke for description and examples. */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/env.c
--- a/head/crypto/heimdal/lib/hx509/env.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/env.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: env.c 22349 2007-12-26 19:32:49Z lha $");
=20
 /**
  * @page page_env Hx509 enviroment functions
@@ -40,36 +39,6 @@
  * See the library functions here: @ref hx509_env
  */
=20
-struct hx509_env {
-    struct {
-	char *key;
-	char *value;
-    } *val;
-    size_t len;
-};
-
-/**
- * Allocate a new hx509_env container object.
- *
- * @param context A hx509 context.
- * @param env return a hx509_env structure, free with hx509_env_free().
- *
- * @return An hx509 error code, see hx509_get_error_string().
- *
- * @ingroup hx509_env
- */
-
-int
-hx509_env_init(hx509_context context, hx509_env *env)
-{
-    *env =3D calloc(1, sizeof(**env));
-    if (*env =3D=3D NULL) {
-	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
-	return ENOMEM;
-    }
-    return 0;
-}
-
 /**
  * Add a new key/value pair to the hx509_env.
  *
@@ -84,34 +53,92 @@
  */
=20
 int
-hx509_env_add(hx509_context context, hx509_env env,=20
+hx509_env_add(hx509_context context, hx509_env *env,
 	      const char *key, const char *value)
 {
-    void *ptr;
+    hx509_env n;
=20
-    ptr =3D realloc(env->val, sizeof(env->val[0]) * (env->len + 1));
-    if (ptr =3D=3D NULL) {
+    n =3D malloc(sizeof(*n));
+    if (n =3D=3D NULL) {
 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
 	return ENOMEM;
     }
-    env->val =3D ptr;
-    env->val[env->len].key =3D strdup(key);
-    if (env->val[env->len].key =3D=3D NULL) {
-	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+
+    n->type =3D env_string;
+    n->next =3D NULL;
+    n->name =3D strdup(key);
+    if (n->name =3D=3D NULL) {
+	free(n);
 	return ENOMEM;
     }
-    env->val[env->len].value =3D strdup(value);
-    if (env->val[env->len].value =3D=3D NULL) {
-	free(env->val[env->len].key);
-	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+    n->u.string =3D strdup(value);
+    if (n->u.string =3D=3D NULL) {
+	free(n->name);
+	free(n);
 	return ENOMEM;
     }
-    env->len++;
+
+    /* add to tail */
+    if (*env) {
+	hx509_env e =3D *env;
+	while (e->next)
+	    e =3D e->next;
+	e->next =3D n;
+    } else
+	*env =3D n;
+
     return 0;
 }
=20
 /**
- * Search the hx509_env for a key.
+ * Add a new key/binding pair to the hx509_env.
+ *
+ * @param context A hx509 context.
+ * @param env enviroment to add the enviroment variable too.
+ * @param key key to add
+ * @param list binding list to add
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_env
+ */
+
+int
+hx509_env_add_binding(hx509_context context, hx509_env *env,
+		      const char *key, hx509_env list)
+{
+    hx509_env n;
+
+    n =3D malloc(sizeof(*n));
+    if (n =3D=3D NULL) {
+	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+	return ENOMEM;
+    }
+
+    n->type =3D env_list;
+    n->next =3D NULL;
+    n->name =3D strdup(key);
+    if (n->name =3D=3D NULL) {
+	free(n);
+	return ENOMEM;
+    }
+    n->u.list =3D list;
+
+    /* add to tail */
+    if (*env) {
+	hx509_env e =3D *env;
+	while (e->next)
+	    e =3D e->next;
+	e->next =3D n;
+    } else
+	*env =3D n;
+
+    return 0;
+}
+
+
+/**
+ * Search the hx509_env for a length based key.
  *
  * @param context A hx509 context.
  * @param env enviroment to add the enviroment variable too.
@@ -127,17 +154,81 @@
 hx509_env_lfind(hx509_context context, hx509_env env,
 		const char *key, size_t len)
 {
-    size_t i;
-
-    for (i =3D 0; i < env->len; i++) {
-	char *s =3D env->val[i].key;
-	if (strncmp(key, s, len) =3D=3D 0 && s[len] =3D=3D '\0')
-	    return env->val[i].value;
+    while(env) {
+	if (strncmp(key, env->name ,len) =3D=3D 0
+	    && env->name[len] =3D=3D '\0' && env->type =3D=3D env_string)
+	    return env->u.string;
+	env =3D env->next;
     }
     return NULL;
 }
=20
 /**
+ * Search the hx509_env for a key.
+ *
+ * @param context A hx509 context.
+ * @param env enviroment to add the enviroment variable too.
+ * @param key key to search for.
+ *
+ * @return the value if the key is found, NULL otherwise.
+ *
+ * @ingroup hx509_env
+ */
+
+const char *
+hx509_env_find(hx509_context context, hx509_env env, const char *key)
+{
+    while(env) {
+	if (strcmp(key, env->name) =3D=3D 0 && env->type =3D=3D env_string)
+	    return env->u.string;
+	env =3D env->next;
+    }
+    return NULL;
+}
+
+/**
+ * Search the hx509_env for a binding.
+ *
+ * @param context A hx509 context.
+ * @param env enviroment to add the enviroment variable too.
+ * @param key key to search for.
+ *
+ * @return the binding if the key is found, NULL if not found.
+ *
+ * @ingroup hx509_env
+ */
+
+hx509_env
+hx509_env_find_binding(hx509_context context,
+		       hx509_env env,
+		       const char *key)
+{
+    while(env) {
+	if (strcmp(key, env->name) =3D=3D 0 && env->type =3D=3D env_list)
+	    return env->u.list;
+	env =3D env->next;
+    }
+    return NULL;
+}
+
+static void
+env_free(hx509_env b)
+{
+    while(b) {
+	hx509_env next =3D b->next;
+
+	if (b->type =3D=3D env_string)
+	    free(b->u.string);
+	else if (b->type =3D=3D env_list)
+	    env_free(b->u.list);
+
+	free(b->name);
+	free(b);
+	b =3D next;
+    }
+}
+
+/**
  * Free an hx509_env enviroment context.
  *
  * @param env the enviroment to free.
@@ -148,14 +239,7 @@
 void
 hx509_env_free(hx509_env *env)
 {
-    size_t i;
-
-    for (i =3D 0; i < (*env)->len; i++) {
-	free((*env)->val[i].key);
-	free((*env)->val[i].value);
-    }
-    free((*env)->val);
-    free(*env);
+    if (*env)
+	env_free(*env);
     *env =3D NULL;
 }
-
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/error.c
--- a/head/crypto/heimdal/lib/hx509/error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: error.c 22332 2007-12-17 01:03:22Z lha $");
=20
 /**
  * @page page_error Hx509 error reporting functions
@@ -68,8 +67,10 @@
 void
 hx509_clear_error_string(hx509_context context)
 {
-    free_error_string(context->error);
-    context->error =3D NULL;
+    if (context) {
+	free_error_string(context->error);
+	context->error =3D NULL;
+    }
 }
=20
 /**
@@ -87,11 +88,14 @@
  */
=20
 void
-hx509_set_error_stringv(hx509_context context, int flags, int code,=20
+hx509_set_error_stringv(hx509_context context, int flags, int code,
 			const char *fmt, va_list ap)
 {
     hx509_error msg;
=20
+    if (context =3D=3D NULL)
+	return;
+
     msg =3D calloc(1, sizeof(*msg));
     if (msg =3D=3D NULL) {
 	hx509_clear_error_string(context);
@@ -115,7 +119,7 @@
 }
=20
 /**
- * See hx509_set_error_stringv().=20
+ * See hx509_set_error_stringv().
  *
  * @param context A hx509 context.
  * @param flags
@@ -172,7 +176,7 @@
     }
=20
     for (msg =3D context->error; msg; msg =3D msg->next)
-	p =3D rk_strpoolprintf(p, "%s%s", msg->msg,=20
+	p =3D rk_strpoolprintf(p, "%s%s", msg->msg,
 			     msg->next !=3D NULL ? "; " : "");
=20
     return rk_strpoolcollect(p);
@@ -205,7 +209,7 @@
  */
=20
 void
-hx509_err(hx509_context context, int exit_code,=20
+hx509_err(hx509_context context, int exit_code,
 	  int error_code, const char *fmt, ...)
 {
     va_list ap;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/file.c
--- a/head/crypto/heimdal/lib/hx509/file.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/file.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,47 +1,46 @@
 /*
- * Copyright (c) 2005 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$ID$");
=20
 int
-_hx509_map_file_os(const char *fn, heim_octet_string *os, struct stat *rsb)
+_hx509_map_file_os(const char *fn, heim_octet_string *os)
 {
     size_t length;
     void *data;
     int ret;
=20
-    ret =3D _hx509_map_file(fn, &data, &length, rsb);
+    ret =3D rk_undumpdata(fn, &data, &length);
=20
     os->data =3D data;
     os->length =3D length;
@@ -52,86 +51,13 @@
 void
 _hx509_unmap_file_os(heim_octet_string *os)
 {
-    _hx509_unmap_file(os->data, os->length);
-}
-
-int
-_hx509_map_file(const char *fn, void **data, size_t *length, struct stat *=
rsb)
-{
-    struct stat sb;
-    size_t len;
-    ssize_t l;
-    int ret;
-    void *d;
-    int fd;
-
-    *data =3D NULL;
-    *length =3D 0;
-
-    fd =3D open(fn, O_RDONLY);
-    if (fd < 0)
-	return errno;
-   =20
-    if (fstat(fd, &sb) < 0) {
-	ret =3D errno;
-	close(fd);
-	return ret;
-    }
-
-    len =3D sb.st_size;
-
-    d =3D malloc(len);
-    if (d =3D=3D NULL) {
-	close(fd);
-	return ENOMEM;
-    }
-   =20
-    l =3D read(fd, d, len);
-    close(fd);
-    if (l < 0 || l !=3D len) {
-	free(d);
-	return EINVAL;
-    }
-
-    if (rsb)
-	*rsb =3D sb;
-    *data =3D d;
-    *length =3D len;
-    return 0;
-}
-
-void
-_hx509_unmap_file(void *data, size_t len)
-{
-    free(data);
+    rk_xfree(os->data);
 }
=20
 int
 _hx509_write_file(const char *fn, const void *data, size_t length)
 {
-    ssize_t sz;
-    const unsigned char *p =3D data;
-    int fd;
-
-    fd =3D open(fn, O_WRONLY|O_TRUNC|O_CREAT, 0644);
-    if (fd < 0)
-	return errno;
-
-    do {
-	sz =3D write(fd, p, length);
-	if (sz < 0) {
-	    int saved_errno =3D errno;
-	    close(fd);
-	    return saved_errno;
-	}
-	if (sz =3D=3D 0)
-	    break;
-	length -=3D sz;
-    } while (length > 0);
-	=09
-    if (close(fd) =3D=3D -1)
-	return errno;
-
+    rk_dumpdata(fn, data, length);
     return 0;
 }
=20
@@ -140,13 +66,13 @@
  */
=20
 static void
-header(FILE *f, const char *type, const char *str)
+print_pem_stamp(FILE *f, const char *type, const char *str)
 {
     fprintf(f, "-----%s %s-----\n", type, str);
 }
=20
 int
-hx509_pem_write(hx509_context context, const char *type,=20
+hx509_pem_write(hx509_context context, const char *type,
 		hx509_pem_header *headers, FILE *f,
 		const void *data, size_t size)
 {
@@ -155,11 +81,11 @@
     char *line;
=20
 #define ENCODE_LINE_LENGTH	54
-   =20
-    header(f, "BEGIN", type);
+
+    print_pem_stamp(f, "BEGIN", type);
=20
     while (headers) {
-	fprintf(f, "%s: %s\n%s",=20
+	fprintf(f, "%s: %s\n%s",
 		headers->header, headers->value,
 		headers->next ? "" : "\n");
 	headers =3D headers->next;
@@ -167,11 +93,11 @@
=20
     while (size > 0) {
 	ssize_t l;
-=09
+
 	length =3D size;
 	if (length > ENCODE_LINE_LENGTH)
 	    length =3D ENCODE_LINE_LENGTH;
-=09
+
 	l =3D base64_encode(p, length, &line);
 	if (l < 0) {
 	    hx509_set_error_string(context, 0, ENOMEM,
@@ -184,7 +110,7 @@
 	free(line);
     }
=20
-    header(f, "END", type);
+    print_pem_stamp(f, "END", type);
=20
     return 0;
 }
@@ -194,7 +120,7 @@
  */
=20
 int
-hx509_pem_add_header(hx509_pem_header **headers,=20
+hx509_pem_add_header(hx509_pem_header **headers,
 		     const char *header, const char *value)
 {
     hx509_pem_header *h;
@@ -255,7 +181,7 @@
=20
 int
 hx509_pem_read(hx509_context context,
-	       FILE *f,=20
+	       FILE *f,
 	       hx509_pem_read_func func,
 	       void *ctx)
 {
@@ -285,7 +211,7 @@
 	    if (i > 0)
 		i--;
 	}
-	   =20
+
 	switch (where) {
 	case BEFORE:
 	    if (strncmp("-----BEGIN ", buf, 11) =3D=3D 0) {
@@ -334,7 +260,7 @@
 		free(p);
 		goto out;
 	    }
-	   =20
+
 	    data =3D erealloc(data, len + i);
 	    memcpy(((char *)data) + len, p, i);
 	    free(p);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/hx509-pr=
ivate.h
--- a/head/crypto/heimdal/lib/hx509/hx509-private.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/hx509/hx509-private.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -30,7 +30,7 @@
 _hx509_abort (
 	const char */*fmt*/,
 	...)
-    __attribute__ ((noreturn, format (printf, 1, 2)));
+     __attribute__ ((noreturn, format (printf, 1, 2)));
=20
 int
 _hx509_calculate_path (
@@ -83,14 +83,6 @@
 int
 _hx509_cert_private_key_exportable (hx509_cert /*p*/);
=20
-int
-_hx509_cert_public_encrypt (
-	hx509_context /*context*/,
-	const heim_octet_string */*cleartext*/,
-	const hx509_cert /*p*/,
-	heim_oid */*encryption_oid*/,
-	heim_octet_string */*ciphertext*/);
-
 void
 _hx509_cert_set_release (
 	hx509_cert /*cert*/,
@@ -98,6 +90,12 @@
 	void */*ctx*/);
=20
 int
+_hx509_cert_to_env (
+	hx509_context /*context*/,
+	hx509_cert /*cert*/,
+	hx509_env */*env*/);
+
+int
 _hx509_certs_keys_add (
 	hx509_context /*context*/,
 	hx509_certs /*certs*/,
@@ -114,9 +112,6 @@
 	hx509_certs /*certs*/,
 	hx509_private_key **/*keys*/);
=20
-hx509_certs
-_hx509_certs_ref (hx509_certs /*certs*/);
-
 int
 _hx509_check_key_usage (
 	hx509_context /*context*/,
@@ -182,6 +177,18 @@
 	heim_bit_string */*sig*/);
=20
 int
+_hx509_expr_eval (
+	hx509_context /*context*/,
+	hx509_env /*env*/,
+	struct hx_expr */*expr*/);
+
+void
+_hx509_expr_free (struct hx_expr */*expr*/);
+
+struct hx_expr *
+_hx509_expr_parse (const char */*buf*/);
+
+int
 _hx509_find_extension_subject_key_id (
 	const Certificate */*issuer*/,
 	SubjectKeyIdentifier */*si*/);
@@ -253,33 +260,33 @@
 hx509_certs
 _hx509_lock_unlock_certs (hx509_lock /*lock*/);
=20
-int
-_hx509_map_file (
-	const char */*fn*/,
-	void **/*data*/,
-	size_t */*length*/,
-	struct stat */*rsb*/);
+struct hx_expr *
+_hx509_make_expr (
+	enum hx_expr_op /*op*/,
+	void */*arg1*/,
+	void */*arg2*/);
=20
 int
 _hx509_map_file_os (
 	const char */*fn*/,
-	heim_octet_string */*os*/,
-	struct stat */*rsb*/);
+	heim_octet_string */*os*/);
=20
 int
 _hx509_match_keys (
 	hx509_cert /*c*/,
-	hx509_private_key /*private_key*/);
+	hx509_private_key /*key*/);
=20
 int
 _hx509_name_cmp (
 	const Name */*n1*/,
-	const Name */*n2*/);
+	const Name */*n2*/,
+	int */*c*/);
=20
 int
 _hx509_name_ds_cmp (
 	const DirectoryString */*ds1*/,
-	const DirectoryString */*ds2*/);
+	const DirectoryString */*ds2*/,
+	int */*diff*/);
=20
 int
 _hx509_name_from_Name (
@@ -295,14 +302,6 @@
 	const char */*str*/);
=20
 int
-_hx509_parse_private_key (
-	hx509_context /*context*/,
-	const heim_oid */*key_oid*/,
-	const void */*data*/,
-	size_t /*len*/,
-	hx509_private_key */*private_key*/);
-
-int
 _hx509_path_append (
 	hx509_context /*context*/,
 	hx509_path */*path*/,
@@ -335,28 +334,15 @@
 	...);
=20
 int
-_hx509_private_key2SPKI (
-	hx509_context /*context*/,
-	hx509_private_key /*private_key*/,
-	SubjectPublicKeyInfo */*spki*/);
-
-void
-_hx509_private_key_assign_rsa (
-	hx509_private_key /*key*/,
-	void */*ptr*/);
-
-int
 _hx509_private_key_export (
 	hx509_context /*context*/,
 	const hx509_private_key /*key*/,
+	hx509_key_format_t /*format*/,
 	heim_octet_string */*data*/);
=20
 int
 _hx509_private_key_exportable (hx509_private_key /*key*/);
=20
-int
-_hx509_private_key_free (hx509_private_key */*key*/);
-
 BIGNUM *
 _hx509_private_key_get_internal (
 	hx509_context /*context*/,
@@ -364,25 +350,11 @@
 	const char */*type*/);
=20
 int
-_hx509_private_key_init (
-	hx509_private_key */*key*/,
-	hx509_private_key_ops */*ops*/,
-	void */*keydata*/);
-
-int
 _hx509_private_key_oid (
 	hx509_context /*context*/,
 	const hx509_private_key /*key*/,
 	heim_oid */*data*/);
=20
-int
-_hx509_private_key_private_decrypt (
-	hx509_context /*context*/,
-	const heim_octet_string */*ciphertext*/,
-	const heim_oid */*encryption_oid*/,
-	hx509_private_key /*p*/,
-	heim_octet_string */*cleartext*/);
-
 hx509_private_key
 _hx509_private_key_ref (hx509_private_key /*key*/);
=20
@@ -430,26 +402,6 @@
 	hx509_request /*req*/,
 	const char */*email*/);
=20
-void
-_hx509_request_free (hx509_request */*req*/);
-
-int
-_hx509_request_get_SubjectPublicKeyInfo (
-	hx509_context /*context*/,
-	hx509_request /*req*/,
-	SubjectPublicKeyInfo */*key*/);
-
-int
-_hx509_request_get_name (
-	hx509_context /*context*/,
-	hx509_request /*req*/,
-	hx509_name */*name*/);
-
-int
-_hx509_request_init (
-	hx509_context /*context*/,
-	hx509_request */*req*/);
-
 int
 _hx509_request_parse (
 	hx509_context /*context*/,
@@ -463,18 +415,6 @@
 	FILE */*f*/);
=20
 int
-_hx509_request_set_SubjectPublicKeyInfo (
-	hx509_context /*context*/,
-	hx509_request /*req*/,
-	const SubjectPublicKeyInfo */*key*/);
-
-int
-_hx509_request_set_name (
-	hx509_context /*context*/,
-	hx509_request /*req*/,
-	hx509_name /*name*/);
-
-int
 _hx509_request_to_pkcs10 (
 	hx509_context /*context*/,
 	const hx509_request /*req*/,
@@ -484,6 +424,14 @@
 hx509_revoke_ctx
 _hx509_revoke_ref (hx509_revoke_ctx /*ctx*/);
=20
+void
+_hx509_sel_yyerror (const char */*s*/);
+
+int
+_hx509_self_signed_valid (
+	hx509_context /*context*/,
+	const AlgorithmIdentifier */*alg*/);
+
 int
 _hx509_set_cert_attribute (
 	hx509_context /*context*/,
@@ -491,10 +439,11 @@
 	const heim_oid */*oid*/,
 	const heim_octet_string */*attr*/);
=20
-void
-_hx509_unmap_file (
-	void */*data*/,
-	size_t /*len*/);
+int
+_hx509_signature_best_before (
+	hx509_context /*context*/,
+	const AlgorithmIdentifier */*alg*/,
+	time_t /*t*/);
=20
 void
 _hx509_unmap_file_os (heim_octet_string */*os*/);
@@ -504,10 +453,13 @@
 	const Name */*aname*/,
 	char **/*str*/);
=20
+time_t
+_hx509_verify_get_time (hx509_verify_ctx /*ctx*/);
+
 int
 _hx509_verify_signature (
 	hx509_context /*context*/,
-	const Certificate */*signer*/,
+	const hx509_cert /*cert*/,
 	const AlgorithmIdentifier */*alg*/,
 	const heim_octet_string */*data*/,
 	const heim_octet_string */*sig*/);
@@ -515,7 +467,7 @@
 int
 _hx509_verify_signature_bitstring (
 	hx509_context /*context*/,
-	const Certificate */*signer*/,
+	const hx509_cert /*signer*/,
 	const AlgorithmIdentifier */*alg*/,
 	const heim_octet_string */*data*/,
 	const heim_bit_string */*sig*/);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/hx509-pr=
otos.h
--- a/head/crypto/heimdal/lib/hx509/hx509-protos.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/hx509/hx509-protos.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -8,14 +8,19 @@
 extern "C" {
 #endif
=20
+#ifndef HX509_LIB
 #ifndef HX509_LIB_FUNCTION
 #if defined(_WIN32)
-#define HX509_LIB_FUNCTION _stdcall
+#define HX509_LIB_FUNCTION __declspec(dllimport)
+#define HX509_LIB_CALL __stdcall
+#define HX509_LIB_VARIABLE __declspec(dllimport)
 #else
 #define HX509_LIB_FUNCTION
+#define HX509_LIB_CALL
+#define HX509_LIB_VARIABLE
 #endif
 #endif
-
+#endif
 void
 hx509_bitstring_print (
 	const heim_bit_string */*b*/,
@@ -155,6 +160,13 @@
 	hx509_cert /*cert*/);
=20
 int
+hx509_ca_tbs_set_unique (
+	hx509_context /*context*/,
+	hx509_ca_tbs /*tbs*/,
+	const heim_bit_string */*subjectUniqueID*/,
+	const heim_bit_string */*issuerUniqueID*/);
+
+int
 hx509_ca_tbs_subject_expand (
 	hx509_context /*context*/,
 	hx509_ca_tbs /*tbs*/,
@@ -222,6 +234,12 @@
 	hx509_cert /*p*/,
 	hx509_name */*name*/);
=20
+int
+hx509_cert_get_issuer_unique_id (
+	hx509_context /*context*/,
+	hx509_cert /*p*/,
+	heim_bit_string */*issuer*/);
+
 time_t
 hx509_cert_get_notAfter (hx509_cert /*p*/);
=20
@@ -239,6 +257,12 @@
 	hx509_name */*name*/);
=20
 int
+hx509_cert_get_subject_unique_id (
+	hx509_context /*context*/,
+	hx509_cert /*p*/,
+	heim_bit_string */*subject*/);
+
+int
 hx509_cert_have_private_key (hx509_cert /*p*/);
=20
 int
@@ -260,6 +284,14 @@
 	hx509_cert /*c*/,
 	char **/*s*/);
=20
+int
+hx509_cert_public_encrypt (
+	hx509_context /*context*/,
+	const heim_octet_string */*cleartext*/,
+	const hx509_cert /*p*/,
+	heim_oid */*encryption_oid*/,
+	heim_octet_string */*ciphertext*/);
+
 hx509_cert
 hx509_cert_ref (hx509_cert /*cert*/);
=20
@@ -288,6 +320,13 @@
 	hx509_cursor /*cursor*/);
=20
 int
+hx509_certs_filter (
+	hx509_context /*context*/,
+	hx509_certs /*certs*/,
+	const hx509_query */*q*/,
+	hx509_certs */*result*/);
+
+int
 hx509_certs_find (
 	hx509_context /*context*/,
 	hx509_certs /*certs*/,
@@ -312,10 +351,18 @@
 	hx509_lock /*lock*/,
 	hx509_certs */*certs*/);
=20
+#ifdef __BLOCKS__
 int
 hx509_certs_iter (
 	hx509_context /*context*/,
 	hx509_certs /*certs*/,
+	int (^func)(hx509_cert));
+#endif /* __BLOCKS__ */
+
+int
+hx509_certs_iter_f (
+	hx509_context /*context*/,
+	hx509_certs /*certs*/,
 	int (*/*func*/)(hx509_context, void *, hx509_cert),
 	void */*ctx*/);
=20
@@ -332,6 +379,9 @@
 	hx509_cursor /*cursor*/,
 	hx509_cert */*cert*/);
=20
+hx509_certs
+hx509_certs_ref (hx509_certs /*certs*/);
+
 int
 hx509_certs_start_seq (
 	hx509_context /*context*/,
@@ -355,6 +405,20 @@
 hx509_clear_error_string (hx509_context /*context*/);
=20
 int
+hx509_cms_create_signed (
+	hx509_context /*context*/,
+	int /*flags*/,
+	const heim_oid */*eContentType*/,
+	const void */*data*/,
+	size_t /*length*/,
+	const AlgorithmIdentifier */*digest_alg*/,
+	hx509_certs /*certs*/,
+	hx509_peer_info /*peer*/,
+	hx509_certs /*anchors*/,
+	hx509_certs /*pool*/,
+	heim_octet_string */*signed_data*/);
+
+int
 hx509_cms_create_signed_1 (
 	hx509_context /*context*/,
 	int /*flags*/,
@@ -396,6 +460,7 @@
 	const void */*data*/,
 	size_t /*length*/,
 	const heim_octet_string */*encryptedContent*/,
+	time_t /*time_now*/,
 	heim_oid */*contentType*/,
 	heim_octet_string */*content*/);
=20
@@ -410,6 +475,7 @@
 hx509_cms_verify_signed (
 	hx509_context /*context*/,
 	hx509_verify_ctx /*ctx*/,
+	unsigned int /*flags*/,
 	const void */*data*/,
 	size_t /*length*/,
 	const heim_octet_string */*signedContent*/,
@@ -470,6 +536,9 @@
 const AlgorithmIdentifier *
 hx509_crypto_aes256_cbc (void);
=20
+void
+hx509_crypto_allow_weak (hx509_crypto /*crypto*/);
+
 int
 hx509_crypto_available (
 	hx509_context /*context*/,
@@ -549,6 +618,11 @@
 	hx509_crypto /*crypto*/,
 	const char */*name*/);
=20
+void
+hx509_crypto_set_padding (
+	hx509_crypto /*crypto*/,
+	int /*padding_type*/);
+
 int
 hx509_crypto_set_params (
 	hx509_context /*context*/,
@@ -564,18 +638,32 @@
 int
 hx509_env_add (
 	hx509_context /*context*/,
-	hx509_env /*env*/,
+	hx509_env */*env*/,
 	const char */*key*/,
 	const char */*value*/);
=20
+int
+hx509_env_add_binding (
+	hx509_context /*context*/,
+	hx509_env */*env*/,
+	const char */*key*/,
+	hx509_env /*list*/);
+
+const char *
+hx509_env_find (
+	hx509_context /*context*/,
+	hx509_env /*env*/,
+	const char */*key*/);
+
+hx509_env
+hx509_env_find_binding (
+	hx509_context /*context*/,
+	hx509_env /*env*/,
+	const char */*key*/);
+
 void
 hx509_env_free (hx509_env */*env*/);
=20
-int
-hx509_env_init (
-	hx509_context /*context*/,
-	hx509_env */*env*/);
-
 const char *
 hx509_env_lfind (
 	hx509_context /*context*/,
@@ -591,6 +679,9 @@
 	const char */*fmt*/,
 	...);
=20
+hx509_private_key_ops *
+hx509_find_private_alg (const heim_oid */*oid*/);
+
 void
 hx509_free_error_string (char */*str*/);
=20
@@ -746,6 +837,21 @@
 	hx509_name */*name*/);
=20
 int
+hx509_parse_private_key (
+	hx509_context /*context*/,
+	const AlgorithmIdentifier */*keyai*/,
+	const void */*data*/,
+	size_t /*len*/,
+	hx509_key_format_t /*format*/,
+	hx509_private_key */*private_key*/);
+
+int
+hx509_peer_info_add_cms_alg (
+	hx509_context /*context*/,
+	hx509_peer_info /*peer*/,
+	const AlgorithmIdentifier */*val*/);
+
+int
 hx509_peer_info_alloc (
 	hx509_context /*context*/,
 	hx509_peer_info */*peer*/);
@@ -795,6 +901,12 @@
 	const void */*data*/,
 	size_t /*size*/);
=20
+int
+hx509_print_cert (
+	hx509_context /*context*/,
+	hx509_cert /*cert*/,
+	FILE */*out*/);
+
 void
 hx509_print_stdout (
 	void */*ctx*/,
@@ -802,6 +914,34 @@
 	va_list /*va*/);
=20
 int
+hx509_private_key2SPKI (
+	hx509_context /*context*/,
+	hx509_private_key /*private_key*/,
+	SubjectPublicKeyInfo */*spki*/);
+
+void
+hx509_private_key_assign_rsa (
+	hx509_private_key /*key*/,
+	void */*ptr*/);
+
+int
+hx509_private_key_free (hx509_private_key */*key*/);
+
+int
+hx509_private_key_init (
+	hx509_private_key */*key*/,
+	hx509_private_key_ops */*ops*/,
+	void */*keydata*/);
+
+int
+hx509_private_key_private_decrypt (
+	hx509_context /*context*/,
+	const heim_octet_string */*ciphertext*/,
+	const heim_oid */*encryption_oid*/,
+	hx509_private_key /*p*/,
+	heim_octet_string */*cleartext*/);
+
+int
 hx509_prompt_hidden (hx509_prompt_type /*type*/);
=20
 int
@@ -817,10 +957,21 @@
 int
 hx509_query_match_cmp_func (
 	hx509_query */*q*/,
-	int (*/*func*/)(void *, hx509_cert),
+	int (*/*func*/)(hx509_context, hx509_cert, void *),
 	void */*ctx*/);
=20
 int
+hx509_query_match_eku (
+	hx509_query */*q*/,
+	const heim_oid */*eku*/);
+
+int
+hx509_query_match_expr (
+	hx509_context /*context*/,
+	hx509_query */*q*/,
+	const char */*expr*/);
+
+int
 hx509_query_match_friendly_name (
 	hx509_query */*q*/,
 	const char */*name*/);
@@ -847,6 +998,38 @@
 	int /*printtype*/,
 	FILE */*out*/);
=20
+void
+hx509_request_free (hx509_request */*req*/);
+
+int
+hx509_request_get_SubjectPublicKeyInfo (
+	hx509_context /*context*/,
+	hx509_request /*req*/,
+	SubjectPublicKeyInfo */*key*/);
+
+int
+hx509_request_get_name (
+	hx509_context /*context*/,
+	hx509_request /*req*/,
+	hx509_name */*name*/);
+
+int
+hx509_request_init (
+	hx509_context /*context*/,
+	hx509_request */*req*/);
+
+int
+hx509_request_set_SubjectPublicKeyInfo (
+	hx509_context /*context*/,
+	hx509_request /*req*/,
+	const SubjectPublicKeyInfo */*key*/);
+
+int
+hx509_request_set_name (
+	hx509_context /*context*/,
+	hx509_request /*req*/,
+	hx509_name /*name*/);
+
 int
 hx509_revoke_add_crl (
 	hx509_context /*context*/,
@@ -899,7 +1082,13 @@
 	va_list /*ap*/);
=20
 const AlgorithmIdentifier *
-hx509_signature_md2 (void);
+hx509_signature_ecPublicKey (void);
+
+const AlgorithmIdentifier *
+hx509_signature_ecdsa_with_sha1 (void);
+
+const AlgorithmIdentifier *
+hx509_signature_ecdsa_with_sha256 (void);
=20
 const AlgorithmIdentifier *
 hx509_signature_md5 (void);
@@ -911,9 +1100,6 @@
 hx509_signature_rsa_pkcs1_x509 (void);
=20
 const AlgorithmIdentifier *
-hx509_signature_rsa_with_md2 (void);
-
-const AlgorithmIdentifier *
 hx509_signature_rsa_with_md5 (void);
=20
 const AlgorithmIdentifier *
@@ -982,6 +1168,11 @@
 	hx509_revoke_ctx /*revoke_ctx*/);
=20
 void
+hx509_verify_ctx_f_allow_best_before_signature_algs (
+	hx509_context /*ctx*/,
+	int /*boolean*/);
+
+void
 hx509_verify_ctx_f_allow_default_trustanchors (
 	hx509_verify_ctx /*ctx*/,
 	int /*boolean*/);
@@ -1042,6 +1233,9 @@
 void
 hx509_xfree (void */*ptr*/);
=20
+int
+yywrap (void);
+
 #ifdef __cplusplus
 }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/hx509.h
--- a/head/crypto/heimdal/lib/hx509/hx509.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/hx509.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,44 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: hx509.h 22464 2008-01-16 14:24:50Z lha $ */
+/* $Id$ */
+
+#ifndef HEIMDAL_HX509_H
+#define HEIMDAL_HX509_H 1
+
+#include <rfc2459_asn1.h>
+#include <stdarg.h>
+#include <stdio.h>
=20
 typedef struct hx509_cert_attribute_data *hx509_cert_attribute;
 typedef struct hx509_cert_data *hx509_cert;
@@ -41,6 +48,7 @@
 typedef struct hx509_lock_data *hx509_lock;
 typedef struct hx509_name_data *hx509_name;
 typedef struct hx509_private_key *hx509_private_key;
+typedef struct hx509_private_key_ops hx509_private_key_ops;
 typedef struct hx509_validate_ctx_data *hx509_validate_ctx;
 typedef struct hx509_verify_ctx_data *hx509_verify_ctx;
 typedef struct hx509_revoke_ctx_data *hx509_revoke_ctx;
@@ -50,7 +58,7 @@
 typedef struct hx509_error_data *hx509_error;
 typedef struct hx509_peer_info *hx509_peer_info;
 typedef struct hx509_ca_tbs *hx509_ca_tbs;
-typedef struct hx509_env *hx509_env;
+typedef struct hx509_env_data *hx509_env;
 typedef struct hx509_crl *hx509_crl;
=20
 typedef void (*hx509_vprint_func)(void *, const char *, va_list);
@@ -64,6 +72,18 @@
     HX509_VALIDATE_F_VERBOSE =3D 2
 };
=20
+enum {
+    HX509_CRYPTO_PADDING_PKCS7 =3D 0,
+    HX509_CRYPTO_PADDING_NONE =3D 1
+};
+
+enum {
+    HX509_KEY_FORMAT_GUESS =3D 0,
+    HX509_KEY_FORMAT_DER =3D 1,
+    HX509_KEY_FORMAT_WIN_BACKUPKEY =3D 2
+};
+typedef uint32_t hx509_key_format_t;
+
 struct hx509_cert_attribute_data {
     heim_oid oid;
     heim_octet_string data;
@@ -118,6 +138,18 @@
=20
 /* flags to hx509_cms_unenvelope */
 #define HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT	0x01
+#define HX509_CMS_UE_ALLOW_WEAK				0x02
+
+/* flags to hx509_cms_envelope_1 */
+#define HX509_CMS_EV_NO_KU_CHECK			0x01
+#define HX509_CMS_EV_ALLOW_WEAK				0x02
+#define HX509_CMS_EV_ID_NAME				0x04
+
+/* flags to hx509_cms_verify_signed */
+#define HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH		0x01
+#define HX509_CMS_VS_NO_KU_CHECK			0x02
+#define HX509_CMS_VS_ALLOW_ZERO_SIGNER			0x04
+#define HX509_CMS_VS_NO_VALIDATE			0x08
=20
 /* selectors passed to hx509_crypto_select and hx509_crypto_available */
 #define HX509_SELECT_ALL 0
@@ -136,8 +168,11 @@
 #define HX509_CA_TEMPLATE_EKU 64
=20
 /* flags hx509_cms_create_signed* */
-#define HX509_CMS_SIGATURE_DETACHED 1
-#define HX509_CMS_SIGATURE_ID_NAME 2
+#define HX509_CMS_SIGNATURE_DETACHED			0x01
+#define HX509_CMS_SIGNATURE_ID_NAME			0x02
+#define HX509_CMS_SIGNATURE_NO_SIGNER			0x04
+#define HX509_CMS_SIGNATURE_LEAF_ONLY			0x08
+#define HX509_CMS_SIGNATURE_NO_CERTS			0x10
=20
 /* hx509_verify_hostname nametype */
 typedef enum  {
@@ -146,3 +181,6 @@
 } hx509_hostname_type;
=20
 #include <hx509-protos.h>
+#include <hx509_err.h>
+
+#endif /* HEIMDAL_HX509_H */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/hx509_er=
r.et
--- a/head/crypto/heimdal/lib/hx509/hx509_err.et	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/hx509/hx509_err.et	Tue Apr 17 11:51:51 2012 +=
0300
@@ -3,7 +3,7 @@
 #
 # This might look like a com_err file, but is not
 #
-id "$Id: hx509_err.et 22329 2007-12-15 05:13:14Z lha $"
+id "$Id$"
=20
 error_table hx
 prefix HX509
@@ -62,9 +62,11 @@
 error_code NO_PROMPTER, "No prompter function defined"
 error_code SIGNATURE_WITHOUT_SIGNER, "Signature require signer, but non av=
ailable"
 error_code RSA_PUBLIC_ENCRYPT, "RSA public encyption failed"
-error_code RSA_PRIVATE_ENCRYPT, "RSA public encyption failed"
-error_code RSA_PUBLIC_DECRYPT, "RSA private decryption failed"
+error_code RSA_PRIVATE_ENCRYPT, "RSA private encyption failed"
+error_code RSA_PUBLIC_DECRYPT, "RSA public decryption failed"
 error_code RSA_PRIVATE_DECRYPT, "RSA private decryption failed"
+error_code ALGORITHM_BEST_BEFORE, "Algorithm has passed its best before da=
te"
+error_code KEY_FORMAT_UNSUPPORTED, "Key format is unsupported"
=20
 # revoke related errors
 index 96
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/hx_locl.h
--- a/head/crypto/heimdal/lib/hx509/hx_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/hx_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,54 +1,57 @@
 /*
- * Copyright (c) 2004 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: hx_locl.h 21083 2007-06-13 02:11:19Z lha $ */
+/* $Id$ */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #include <stdio.h>
 #include <stdlib.h>
 #include <ctype.h>
 #include <errno.h>
+#ifdef HAVE_STRINGS_H
 #include <strings.h>
+#endif
 #include <assert.h>
 #include <stdarg.h>
 #include <err.h>
+#include <limits.h>
+
+#include <roken.h>
+
 #include <getarg.h>
 #include <base64.h>
 #include <hex.h>
-#include <roken.h>
 #include <com_err.h>
 #include <parse_units.h>
 #include <parse_bytes.h>
@@ -67,6 +70,7 @@
=20
 #include <der.h>
=20
+#define HC_DEPRECATED_CRYPTO
 #include "crypto-headers.h"
=20
 struct hx509_keyset_ops;
@@ -78,7 +82,8 @@
=20
 typedef void (*_hx509_cert_release_func)(struct hx509_cert_data *, void *);
=20
-typedef struct hx509_private_key_ops hx509_private_key_ops;
+
+#include "sel.h"
=20
 #include <hx509-private.h>
 #include <hx509_err.h>
@@ -128,7 +133,9 @@
 #define HX509_QUERY_MATCH_FUNCTION		0x080000
 #define HX509_QUERY_MATCH_KEY_HASH_SHA1		0x100000
 #define HX509_QUERY_MATCH_TIME			0x200000
-#define HX509_QUERY_MASK			0x3fffff
+#define HX509_QUERY_MATCH_EKU			0x400000
+#define HX509_QUERY_MATCH_EXPR			0x800000
+#define HX509_QUERY_MASK			0xffffff
     Certificate *subject;
     Certificate *certificate;
     heim_integer *serial;
@@ -138,26 +145,28 @@
     Name *subject_name;
     hx509_path *path;
     char *friendlyname;
-    int (*cmp_func)(void *, hx509_cert);
+    int (*cmp_func)(hx509_context, hx509_cert, void *);
     void *cmp_func_ctx;
     heim_octet_string *keyhash_sha1;
     time_t timenow;
+    heim_oid *eku;
+    struct hx_expr *expr;
 };
=20
 struct hx509_keyset_ops {
     const char *name;
     int flags;
-    int (*init)(hx509_context, hx509_certs, void **,=20
+    int (*init)(hx509_context, hx509_certs, void **,
 		int, const char *, hx509_lock);
     int (*store)(hx509_context, hx509_certs, void *, int, hx509_lock);
     int (*free)(hx509_certs, void *);
     int (*add)(hx509_context, hx509_certs, void *, hx509_cert);
-    int (*query)(hx509_context, hx509_certs, void *,=20
+    int (*query)(hx509_context, hx509_certs, void *,
 		 const hx509_query *, hx509_cert *);
     int (*iter_start)(hx509_context, hx509_certs, void *, void **);
     int (*iter)(hx509_context, hx509_certs, void *, void *, hx509_cert *);
     int (*iter_end)(hx509_context, hx509_certs, void *, void *);
-    int (*printinfo)(hx509_context, hx509_certs,=20
+    int (*printinfo)(hx509_context, hx509_certs,
 		     void *, int (*)(void *, const char *), void *);
     int (*getkeys)(hx509_context, hx509_certs, void *, hx509_private_key *=
*);
     int (*addkey)(hx509_context, hx509_certs, void *, hx509_private_key);
@@ -186,6 +195,18 @@
 /* _hx509_calculate_path flag field */
 #define HX509_CALCULATE_PATH_NO_ANCHOR 1
=20
+/* environment */
+struct hx509_env_data {
+    enum { env_string, env_list } type;
+    char *name;
+    struct hx509_env_data *next;
+    union {
+	char *string;
+	struct hx509_env_data *list;
+    } u;
+};
+
+
 extern const AlgorithmIdentifier * _hx509_crypto_default_sig_alg;
 extern const AlgorithmIdentifier * _hx509_crypto_default_digest_alg;
 extern const AlgorithmIdentifier * _hx509_crypto_default_secret_alg;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/hxtool-c=
ommands.in
--- a/head/crypto/heimdal/lib/hx509/hxtool-commands.in	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/hxtool-commands.in	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005 - 2007 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2005 - 2007 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).=20
  * All rights reserved.=20
  *
@@ -30,10 +30,11 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
  * SUCH DAMAGE.=20
  */
-/* $Id: hxtool-commands.in 21343 2007-06-26 14:21:55Z lha $ */
+/* $Id$ */
=20
 command =3D {
 	name =3D "cms-create-sd"
+	name =3D "cms-sign"
 	option =3D {
 		long =3D "certificate"
 		short =3D "c"
@@ -94,11 +95,26 @@
 		help =3D "create a detached signature"
 	}
 	option =3D {
+		long =3D "signer"
+		type =3D "-flag"
+		help =3D "do not sign"
+	}
+	option =3D {
 		long =3D "id-by-name"
 		type =3D "flag"
 		help =3D "use subject name for CMS Identifier"
 	}
-	min_args=3D"2"
+	option =3D {
+		long =3D "embedded-certs"
+		type =3D "-flag"
+		help =3D "dont embedded certficiates"
+	}
+	option =3D {
+		long =3D "embed-leaf-only"
+		type =3D "flag"
+		help =3D "only embed leaf certificate"
+	}
+	min_args=3D"1"
 	max_args=3D"2"
 	argument=3D"in-file out-file"
 	help =3D "Wrap a file within a SignedData object"
@@ -107,6 +123,7 @@
 	name =3D "cms-verify-sd"
 	option =3D {
 		long =3D "anchors"
+		short =3D "D"
 		type =3D "strings"
 		argument =3D "certificate-store"
 		help =3D "trust anchors"
@@ -135,13 +152,28 @@
 		help =3D "unwrap in-data that's in a ContentInfo"
 	}
 	option =3D {
+		long =3D "pem"
+		type =3D "flag"
+		help =3D "unwrap in-data from PEM armor"
+	}
+	option =3D {
+		long =3D "signer-allowed"
+		type =3D "-flag"
+		help =3D "allow no signer"
+	}
+	option =3D {
+		long =3D "allow-wrong-oid"
+		type =3D "flag"
+		help =3D "allow wrong oid flag"
+	}
+	option =3D {
 		long =3D "signed-content"
 		type =3D "string"
 		help =3D "file containing content"
 	}
-	min_args=3D"2"
+	min_args=3D"1"
 	max_args=3D"2"
-	argument=3D"in-file out-file"
+	argument=3D"in-file [out-file]"
 	help =3D "Verify a file within a SignedData object"
 }
 command =3D {
@@ -164,6 +196,11 @@
 		type =3D "flag"
 		help =3D "wrapped out-data in a ContentInfo"
 	}
+	option =3D {
+		long =3D "allow-weak-crypto"
+		type =3D "flag"
+		help =3D "allow weak crypto"
+	}
 	min_args=3D"2"
 	argument=3D"in-file out-file"
 	help =3D "Unenvelope a file containing a EnvelopedData object"
@@ -201,6 +238,11 @@
 		type =3D "flag"
 		help =3D "wrapped out-data in a ContentInfo"
 	}
+	option =3D {
+		long =3D "allow-weak-crypto"
+		type =3D "flag"
+		help =3D "allow weak crypto"
+	}
 	min_args=3D"2"
 	argument=3D"in-file out-file"
 	help =3D "Envelope a file containing a EnvelopedData object"
@@ -263,6 +305,11 @@
 		help =3D "print the content of the certificates"
 	}
 	option =3D {
+		long =3D "never-fail"
+		type =3D "flag"
+		help =3D "never fail with an error code"
+	}
+	option =3D {
 		long =3D "info"
 		type =3D "flag"
 		help =3D "print the information about the certificate store"
@@ -438,6 +485,18 @@
 		help =3D "match on friendly name"
 	}
 	option =3D {
+		long =3D "eku"
+		type =3D "string"
+		argument =3D "oid-string"
+		help =3D "match on EKU"
+	}
+	option =3D {
+		long =3D "expr"
+		type =3D "string"
+		argument =3D "expression"
+		help =3D "match on expression"
+	}
+	option =3D {
 		long =3D "keyEncipherment"
 		type =3D "flag"
 		help =3D "match keyEncipherment certificates"
@@ -557,7 +616,7 @@
 	option =3D {
 		long =3D "type"
 		type =3D "strings"
-		help =3D "Type of certificate to issue"
+		help =3D "Types of certificate to issue (can be used more then once)"
 	}
 	option =3D {
 		long =3D "lifetime"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/hxtool.c
--- a/head/crypto/heimdal/lib/hx509/hxtool.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/hxtool.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: hxtool.c 22333 2007-12-17 01:03:43Z lha $");
=20
 #include <hxtool-commands.h>
 #include <sl.h>
+#include <rtbl.h>
 #include <parse_time.h>
=20
 static hx509_context context;
@@ -45,9 +45,9 @@
 static int help_flag;
=20
 struct getargs args[] =3D {
-    { "statistic-file", 0, arg_string, &stat_file_string },
-    { "version", 0, arg_flag, &version_flag },
-    { "help", 0, arg_flag, &help_flag }
+    { "statistic-file", 0, arg_string, &stat_file_string, NULL, NULL },
+    { "version", 0, arg_flag, &version_flag, NULL, NULL },
+    { "help", 0, arg_flag, &help_flag, NULL, NULL }
 };
 int num_args =3D sizeof(args) / sizeof(args[0]);
=20
@@ -70,7 +70,7 @@
     for (i =3D 0; i < pass->num_strings; i++) {
 	int ret =3D hx509_lock_command_string(lock, pass->strings[i]);
 	if (ret)
-	    errx(1, "hx509_lock_command_string: %s: %d",=20
+	    errx(1, "hx509_lock_command_string: %s: %d",
 		 pass->strings[i], ret);
     }
 }
@@ -80,15 +80,15 @@
  */
=20
 static void
-certs_strings(hx509_context context, const char *type, hx509_certs certs,
+certs_strings(hx509_context contextp, const char *type, hx509_certs certs,
 	      hx509_lock lock, const getarg_strings *s)
 {
     int i, ret;
=20
     for (i =3D 0; i < s->num_strings; i++) {
-	ret =3D hx509_certs_append(context, certs, lock, s->strings[i]);
+	ret =3D hx509_certs_append(contextp, certs, lock, s->strings[i]);
 	if (ret)
-	    hx509_err(context, 1, ret,
+	    hx509_err(contextp, 1, ret,
 		      "hx509_certs_append: %s %s", type, s->strings[i]);
     }
 }
@@ -114,27 +114,27 @@
  */
=20
 static void
-peer_strings(hx509_context context,
-	     hx509_peer_info *peer,=20
+peer_strings(hx509_context contextp,
+	     hx509_peer_info *peer,
 	     const getarg_strings *s)
 {
     AlgorithmIdentifier *val;
     int ret, i;
-   =20
-    ret =3D hx509_peer_info_alloc(context, peer);
+
+    ret =3D hx509_peer_info_alloc(contextp, peer);
     if (ret)
-	hx509_err(context, 1, ret, "hx509_peer_info_alloc");
-   =20
+	hx509_err(contextp, 1, ret, "hx509_peer_info_alloc");
+
     val =3D calloc(s->num_strings, sizeof(*val));
     if (val =3D=3D NULL)
 	err(1, "malloc");
=20
     for (i =3D 0; i < s->num_strings; i++)
 	parse_oid(s->strings[i], NULL, &val[i].algorithm);
-	   =20
-    ret =3D hx509_peer_info_set_cms_algs(context, *peer, val, s->num_strin=
gs);
+
+    ret =3D hx509_peer_info_set_cms_algs(contextp, *peer, val, s->num_stri=
ngs);
     if (ret)
-	hx509_err(context, 1, ret, "hx509_peer_info_set_cms_algs");
+	hx509_err(contextp, 1, ret, "hx509_peer_info_set_cms_algs");
=20
     for (i =3D 0; i < s->num_strings; i++)
 	free_AlgorithmIdentifier(&val[i]);
@@ -145,6 +145,36 @@
  *
  */
=20
+struct pem_data {
+    heim_octet_string *os;
+    int detached_data;
+};
+
+static int
+pem_reader(hx509_context contextp, const char *type,
+	   const hx509_pem_header *headers,
+	   const void *data , size_t length, void *ctx)
+{
+    struct pem_data *p =3D (struct pem_data *)ctx;
+    const char *h;
+
+    p->os->data =3D malloc(length);
+    if (p->os->data =3D=3D NULL)
+	return ENOMEM;
+    memcpy(p->os->data, data, length);
+    p->os->length =3D length;
+
+    h =3D hx509_pem_find_header(headers, "Content-disposition");
+    if (h && strcasecmp(h, "detached") =3D=3D 0)
+	p->detached_data =3D 1;
+
+    return 0;
+}
+
+/*
+ *
+ */
+
 int
 cms_verify_sd(struct cms_verify_sd_options *opt, int argc, char **argv)
 {
@@ -155,10 +185,10 @@
     hx509_certs signers =3D NULL;
     hx509_certs anchors =3D NULL;
     hx509_lock lock;
-    int ret;
+    int ret, flags =3D 0;
=20
     size_t sz;
-    void *p;
+    void *p =3D NULL;
=20
     if (opt->missing_revoke_flag)
 	hx509_context_set_missing_revoke(context, 1);
@@ -166,28 +196,67 @@
     hx509_lock_init(context, &lock);
     lock_strings(lock, &opt->pass_strings);
=20
-    ret =3D _hx509_map_file(argv[0], &p, &sz, NULL);
+    ret =3D hx509_verify_init_ctx(context, &ctx);
     if (ret)
-	err(1, "map_file: %s: %d", argv[0], ret);
+	hx509_err(context, 1, ret, "hx509_verify_init_ctx");
+
+    ret =3D hx509_certs_init(context, "MEMORY:cms-anchors", 0, NULL, &anch=
ors);
+    if (ret)
+	hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+    ret =3D hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &store=
);
+    if (ret)
+	hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
+
+    certs_strings(context, "anchors", anchors, lock, &opt->anchors_strings=
);
+    certs_strings(context, "store", store, lock, &opt->certificate_strings=
);
+
+    if (opt->pem_flag) {
+	struct pem_data pd;
+	FILE *f;
+
+	pd.os =3D &co;
+	pd.detached_data =3D 0;
+
+	f =3D fopen(argv[0], "r");
+	if (f =3D=3D NULL)
+	    err(1, "Failed to open file %s", argv[0]);
+
+	ret =3D hx509_pem_read(context, f, pem_reader, &pd);
+	fclose(f);
+	if (ret)
+	    errx(1, "PEM reader failed: %d", ret);
+
+	if (pd.detached_data && opt->signed_content_string =3D=3D NULL) {
+	    char *r =3D strrchr(argv[0], '.');
+	    if (r && strcasecmp(r, ".pem") =3D=3D 0) {
+		char *s =3D strdup(argv[0]);
+		if (s =3D=3D NULL)
+		    errx(1, "malloc: out of memory");
+		s[r - argv[0]] =3D '\0';
+		ret =3D _hx509_map_file_os(s, &signeddata);
+		if (ret)
+		    errx(1, "map_file: %s: %d", s, ret);
+		free(s);
+		sd =3D &signeddata;
+	    }
+	}
+
+    } else {
+	ret =3D rk_undumpdata(argv[0], &p, &sz);
+	if (ret)
+	    err(1, "map_file: %s: %d", argv[0], ret);
+
+	co.data =3D p;
+	co.length =3D sz;
+    }
=20
     if (opt->signed_content_string) {
-	ret =3D _hx509_map_file_os(opt->signed_content_string, &signeddata, NULL);
+	ret =3D _hx509_map_file_os(opt->signed_content_string, &signeddata);
 	if (ret)
-	    err(1, "map_file: %s: %d", opt->signed_content_string, ret);
+	    errx(1, "map_file: %s: %d", opt->signed_content_string, ret);
 	sd =3D &signeddata;
     }
=20
-    ret =3D hx509_verify_init_ctx(context, &ctx);
-
-    ret =3D hx509_certs_init(context, "MEMORY:cms-anchors", 0, NULL, &anch=
ors);
-    ret =3D hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &store=
);
-
-    certs_strings(context, "anchors", anchors, lock, &opt->anchors_strings=
);
-    certs_strings(context, "store", store, lock, &opt->certificate_strings=
);
-
-    co.data =3D p;
-    co.length =3D sz;
-
     if (opt->content_info_flag) {
 	heim_octet_string uwco;
 	heim_oid oid;
@@ -196,19 +265,32 @@
 	if (ret)
 	    errx(1, "hx509_cms_unwrap_ContentInfo: %d", ret);
=20
-	if (der_heim_oid_cmp(&oid, oid_id_pkcs7_signedData()) !=3D 0)
+	if (der_heim_oid_cmp(&oid, &asn1_oid_id_pkcs7_signedData) !=3D 0)
 	    errx(1, "Content is not SignedData");
 	der_free_oid(&oid);
=20
+	if (p =3D=3D NULL)
+	    der_free_octet_string(&co);
+	else {
+	    rk_xfree(p);
+	    p =3D NULL;
+	}
 	co =3D uwco;
     }
=20
     hx509_verify_attach_anchors(ctx, anchors);
=20
-    ret =3D hx509_cms_verify_signed(context, ctx, co.data, co.length, sd,
+    if (!opt->signer_allowed_flag)
+	flags |=3D HX509_CMS_VS_ALLOW_ZERO_SIGNER;
+    if (opt->allow_wrong_oid_flag)
+	flags |=3D HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH;
+
+    ret =3D hx509_cms_verify_signed(context, ctx, flags, co.data, co.lengt=
h, sd,
 				  store, &type, &c, &signers);
-    if (co.data !=3D p)
+    if (p !=3D co.data)
 	der_free_octet_string(&co);
+    else
+	rk_xfree(p);
     if (ret)
 	hx509_err(context, 1, ret, "hx509_cms_verify_signed");
=20
@@ -219,8 +301,12 @@
 	free(str);
 	der_free_oid(&type);
     }
-    printf("signers:\n");
-    hx509_certs_iter(context, signers, hx509_ci_print_names, stdout);
+    if (signers =3D=3D NULL) {
+	printf("unsigned\n");
+    } else {
+	printf("signers:\n");
+	hx509_certs_iter_f(context, signers, hx509_ci_print_names, stdout);
+    }
=20
     hx509_verify_destroy_ctx(ctx);
=20
@@ -230,18 +316,43 @@
=20
     hx509_lock_free(lock);
=20
-    ret =3D _hx509_write_file(argv[1], c.data, c.length);
-    if (ret)
-	errx(1, "hx509_write_file: %d", ret);
+    if (argc > 1) {
+	ret =3D _hx509_write_file(argv[1], c.data, c.length);
+	if (ret)
+	    errx(1, "hx509_write_file: %d", ret);
+    }
=20
     der_free_octet_string(&c);
-    _hx509_unmap_file(p, sz);
+
     if (sd)
 	_hx509_unmap_file_os(sd);
=20
     return 0;
 }
=20
+static int
+print_signer(hx509_context contextp, void *ctx, hx509_cert cert)
+{
+    hx509_pem_header **header =3D ctx;
+    char *signer_name =3D NULL;
+    hx509_name name;
+    int ret;
+
+    ret =3D hx509_cert_get_subject(cert, &name);
+    if (ret)
+	errx(1, "hx509_cert_get_subject");
+
+    ret =3D hx509_name_to_string(name, &signer_name);
+    hx509_name_free(&name);
+    if (ret)
+	errx(1, "hx509_name_to_string");
+
+    hx509_pem_add_header(header, "Signer", signer_name);
+
+    free(signer_name);
+    return 0;
+}
+
 int
 cms_create_sd(struct cms_create_sd_options *opt, int argc, char **argv)
 {
@@ -250,96 +361,100 @@
     heim_octet_string o;
     hx509_query *q;
     hx509_lock lock;
-    hx509_certs store, pool, anchors;
-    hx509_cert cert;
+    hx509_certs store, pool, anchors, signer =3D NULL;
     size_t sz;
     void *p;
     int ret, flags =3D 0;
-    char *signer_name =3D NULL;
+    char *infile, *outfile =3D NULL;
=20
     memset(&contentType, 0, sizeof(contentType));
=20
-    if (argc < 2)
-	errx(1, "argc < 2");
+    infile =3D argv[0];
+
+    if (argc < 2) {
+	asprintf(&outfile, "%s.%s", infile,
+		 opt->pem_flag ? "pem" : "cms-signeddata");
+	if (outfile =3D=3D NULL)
+	    errx(1, "out of memory");
+    } else
+	outfile =3D argv[1];
=20
     hx509_lock_init(context, &lock);
     lock_strings(lock, &opt->pass_strings);
=20
     ret =3D hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &store=
);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
     ret =3D hx509_certs_init(context, "MEMORY:cert-pool", 0, NULL, &pool);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     certs_strings(context, "store", store, lock, &opt->certificate_strings=
);
     certs_strings(context, "pool", pool, lock, &opt->pool_strings);
=20
     if (opt->anchors_strings.num_strings) {
-	ret =3D hx509_certs_init(context, "MEMORY:cert-anchors",=20
+	ret =3D hx509_certs_init(context, "MEMORY:cert-anchors",
 			       0, NULL, &anchors);
+	if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
 	certs_strings(context, "anchors", anchors, lock, &opt->anchors_strings);
     } else
 	anchors =3D NULL;
=20
     if (opt->detached_signature_flag)
-	flags |=3D HX509_CMS_SIGATURE_DETACHED;
+	flags |=3D HX509_CMS_SIGNATURE_DETACHED;
     if (opt->id_by_name_flag)
-	flags |=3D HX509_CMS_SIGATURE_ID_NAME;
-
-    ret =3D hx509_query_alloc(context, &q);
+	flags |=3D HX509_CMS_SIGNATURE_ID_NAME;
+    if (!opt->signer_flag) {
+	flags |=3D HX509_CMS_SIGNATURE_NO_SIGNER;
+
+    }
+
+    if (opt->signer_flag) {
+	ret =3D hx509_query_alloc(context, &q);
+	if (ret)
+	    errx(1, "hx509_query_alloc: %d", ret);
+
+	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
+
+	if (opt->signer_string)
+	    hx509_query_match_friendly_name(q, opt->signer_string);
+
+	ret =3D hx509_certs_filter(context, store, q, &signer);
+	hx509_query_free(context, q);
+	if (ret)
+	    hx509_err(context, 1, ret, "hx509_certs_find");
+    }
+    if (!opt->embedded_certs_flag)
+	flags |=3D HX509_CMS_SIGNATURE_NO_CERTS;
+    if (opt->embed_leaf_only_flag)
+	flags |=3D HX509_CMS_SIGNATURE_LEAF_ONLY;
+
+    ret =3D rk_undumpdata(infile, &p, &sz);
     if (ret)
-	errx(1, "hx509_query_alloc: %d", ret);
-
-    hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
-    hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
-			    =20
-    if (opt->signer_string)
-	hx509_query_match_friendly_name(q, opt->signer_string);
-
-    ret =3D hx509_certs_find(context, store, q, &cert);
-    hx509_query_free(context, q);
-    if (ret)
-	hx509_err(context, 1, ret, "hx509_certs_find");
-
-    ret =3D _hx509_map_file(argv[0], &p, &sz, NULL);
-    if (ret)
-	err(1, "map_file: %s: %d", argv[0], ret);
+	err(1, "map_file: %s: %d", infile, ret);
=20
     if (opt->peer_alg_strings.num_strings)
 	peer_strings(context, &peer, &opt->peer_alg_strings);
=20
-    parse_oid(opt->content_type_string, oid_id_pkcs7_data(), &contentType);
-
-    ret =3D hx509_cms_create_signed_1(context,
-				    flags,
-				    &contentType,
-				    p,
-				    sz,=20
-				    NULL,
-				    cert,
-				    peer,
-				    anchors,
-				    pool,
-				    &o);
+    parse_oid(opt->content_type_string, &asn1_oid_id_pkcs7_data, &contentT=
ype);
+
+    ret =3D hx509_cms_create_signed(context,
+				  flags,
+				  &contentType,
+				  p,
+				  sz,
+				  NULL,
+				  signer,
+				  peer,
+				  anchors,
+				  pool,
+				  &o);
     if (ret)
-	errx(1, "hx509_cms_create_signed: %d", ret);
-
-    {
-	hx509_name name;
-=09
-	ret =3D hx509_cert_get_subject(cert, &name);
-	if (ret)
-	    errx(1, "hx509_cert_get_subject");
-=09
-	ret =3D hx509_name_to_string(name, &signer_name);
-	hx509_name_free(&name);
-	if (ret)
-	    errx(1, "hx509_name_to_string");
-    }
-
+	hx509_err(context, 1, ret, "hx509_cms_create_signed: %d", ret);
=20
     hx509_certs_free(&anchors);
     hx509_certs_free(&pool);
-    hx509_cert_free(cert);
     hx509_certs_free(&store);
-    _hx509_unmap_file(p, sz);
+    rk_xfree(p);
     hx509_lock_free(lock);
     hx509_peer_info_free(peer);
     der_free_oid(&contentType);
@@ -347,7 +462,7 @@
     if (opt->content_info_flag) {
 	heim_octet_string wo;
=20
-	ret =3D hx509_cms_wrap_ContentInfo(oid_id_pkcs7_signedData(), &o, &wo);
+	ret =3D hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &o, &wo=
);
 	if (ret)
 	    errx(1, "hx509_cms_wrap_ContentInfo: %d", ret);
=20
@@ -359,15 +474,20 @@
 	hx509_pem_header *header =3D NULL;
 	FILE *f;
=20
-	hx509_pem_add_header(&header, "Content-disposition",=20
-			     opt->detached_signature_flag ? "detached" : "inline");
-	hx509_pem_add_header(&header, "Signer", signer_name);
-
-	f =3D fopen(argv[1], "w");
+	hx509_pem_add_header(&header, "Content-disposition",
+			     opt->detached_signature_flag ?
+			     "detached" : "inline");
+	if (signer) {
+	    ret =3D hx509_certs_iter_f(context, signer, print_signer, header);
+	    if (ret)
+		hx509_err(context, 1, ret, "print signer");
+	}
+
+	f =3D fopen(outfile, "w");
 	if (f =3D=3D NULL)
-	    err(1, "open %s", argv[1]);
-=09
-	ret =3D hx509_pem_write(context, "CMS SIGNEDDATA", header, f,=20
+	    err(1, "open %s", outfile);
+
+	ret =3D hx509_pem_write(context, "CMS SIGNEDDATA", header, f,
 			      o.data, o.length);
 	fclose(f);
 	hx509_pem_free_header(header);
@@ -375,12 +495,12 @@
 	    errx(1, "hx509_pem_write: %d", ret);
=20
     } else {
-	ret =3D _hx509_write_file(argv[1], o.data, o.length);
+	ret =3D _hx509_write_file(outfile, o.data, o.length);
 	if (ret)
 	    errx(1, "hx509_write_file: %d", ret);
     }
=20
-    free(signer_name);
+    hx509_certs_free(&signer);
     free(o.data);
=20
     return 0;
@@ -396,11 +516,12 @@
     void *p;
     int ret;
     hx509_lock lock;
+    int flags =3D 0;
=20
     hx509_lock_init(context, &lock);
     lock_strings(lock, &opt->pass_strings);
=20
-    ret =3D _hx509_map_file(argv[0], &p, &sz, NULL);
+    ret =3D rk_undumpdata(argv[0], &p, &sz);
     if (ret)
 	err(1, "map_file: %s: %d", argv[0], ret);
=20
@@ -415,7 +536,7 @@
 	if (ret)
 	    errx(1, "hx509_cms_unwrap_ContentInfo: %d", ret);
=20
-	if (der_heim_oid_cmp(&oid, oid_id_pkcs7_envelopedData()) !=3D 0)
+	if (der_heim_oid_cmp(&oid, &asn1_oid_id_pkcs7_envelopedData) !=3D 0)
 	    errx(1, "Content is not SignedData");
 	der_free_oid(&oid);
=20
@@ -428,14 +549,17 @@
=20
     certs_strings(context, "store", certs, lock, &opt->certificate_strings=
);
=20
-    ret =3D hx509_cms_unenvelope(context, certs, 0, co.data, co.length,
-			       NULL, &contentType, &o);
+    if (opt->allow_weak_crypto_flag)
+	flags |=3D HX509_CMS_UE_ALLOW_WEAK;
+
+    ret =3D hx509_cms_unenvelope(context, certs, flags, co.data, co.length,
+			       NULL, 0, &contentType, &o);
     if (co.data !=3D p)
 	der_free_octet_string(&co);
     if (ret)
 	hx509_err(context, 1, ret, "hx509_cms_unenvelope");
=20
-    _hx509_unmap_file(p, sz);
+    rk_xfree(p);
     hx509_lock_free(lock);
     hx509_certs_free(&certs);
     der_free_oid(&contentType);
@@ -462,24 +586,29 @@
     size_t sz;
     void *p;
     hx509_lock lock;
+    int flags =3D 0;
=20
     memset(&contentType, 0, sizeof(contentType));
=20
     hx509_lock_init(context, &lock);
     lock_strings(lock, &opt->pass_strings);
=20
-    ret =3D _hx509_map_file(argv[0], &p, &sz, NULL);
+    ret =3D rk_undumpdata(argv[0], &p, &sz);
     if (ret)
 	err(1, "map_file: %s: %d", argv[0], ret);
=20
     ret =3D hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs=
);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     certs_strings(context, "store", certs, lock, &opt->certificate_strings=
);
=20
+    if (opt->allow_weak_crypto_flag)
+	flags |=3D HX509_CMS_EV_ALLOW_WEAK;
+
     if (opt->encryption_type_string) {
 	enctype =3D hx509_crypto_enctype_by_name(opt->encryption_type_string);
 	if (enctype =3D=3D NULL)
-	    errx(1, "encryption type: %s no found",=20
+	    errx(1, "encryption type: %s no found",
 		 opt->encryption_type_string);
     }
=20
@@ -494,22 +623,22 @@
     if (ret)
 	errx(1, "hx509_certs_find: %d", ret);
=20
-    parse_oid(opt->content_type_string, oid_id_pkcs7_data(), &contentType);
-
-    ret =3D hx509_cms_envelope_1(context, 0, cert, p, sz, enctype,=20
+    parse_oid(opt->content_type_string, &asn1_oid_id_pkcs7_data, &contentT=
ype);
+
+    ret =3D hx509_cms_envelope_1(context, flags, cert, p, sz, enctype,
 			       &contentType, &o);
     if (ret)
 	errx(1, "hx509_cms_envelope_1: %d", ret);
=20
     hx509_cert_free(cert);
     hx509_certs_free(&certs);
-    _hx509_unmap_file(p, sz);
+    rk_xfree(p);
     der_free_oid(&contentType);
=20
     if (opt->content_info_flag) {
 	heim_octet_string wo;
=20
-	ret =3D hx509_cms_wrap_ContentInfo(oid_id_pkcs7_envelopedData(), &o, &wo);
+	ret =3D hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_envelopedData, &o, =
&wo);
 	if (ret)
 	    errx(1, "hx509_cms_wrap_ContentInfo: %d", ret);
=20
@@ -531,46 +660,18 @@
 static void
 print_certificate(hx509_context hxcontext, hx509_cert cert, int verbose)
 {
-    hx509_name name;
     const char *fn;
-    char *str;
     int ret;
-   =20
+
     fn =3D hx509_cert_get_friendly_name(cert);
     if (fn)
 	printf("    friendly name: %s\n", fn);
-    printf("    private key: %s\n",=20
+    printf("    private key: %s\n",
 	   _hx509_cert_private_key(cert) ? "yes" : "no");
=20
-    ret =3D hx509_cert_get_issuer(cert, &name);
-    hx509_name_to_string(name, &str);
-    hx509_name_free(&name);
-    printf("    issuer:  \"%s\"\n", str);
-    free(str);
-
-    ret =3D hx509_cert_get_subject(cert, &name);
-    hx509_name_to_string(name, &str);
-    hx509_name_free(&name);
-    printf("    subject: \"%s\"\n", str);
-    free(str);
-
-    {
-	heim_integer serialNumber;
-
-	hx509_cert_get_serialnumber(cert, &serialNumber);
-	der_print_hex_heim_integer(&serialNumber, &str);
-	der_free_heim_integer(&serialNumber);
-	printf("    serial: %s\n", str);
-	free(str);
-    }
-
-    printf("    keyusage: ");
-    ret =3D hx509_cert_keyusage_print(hxcontext, cert, &str);
-    if (ret =3D=3D 0) {
-	printf("%s\n", str);
-	free(str);
-    } else
-	printf("no");
+    ret =3D hx509_print_cert(hxcontext, cert, NULL);
+    if (ret)
+	errx(1, "failed to print cert");
=20
     if (verbose) {
 	hx509_validate_ctx vctx;
@@ -579,7 +680,7 @@
 	hx509_validate_ctx_set_print(vctx, hx509_print_stdout, stdout);
 	hx509_validate_ctx_add_flags(vctx, HX509_VALIDATE_F_VALIDATE);
 	hx509_validate_ctx_add_flags(vctx, HX509_VALIDATE_F_VERBOSE);
-=09
+
 	hx509_validate_cert(hxcontext, vctx, cert);
=20
 	hx509_validate_ctx_free(vctx);
@@ -596,7 +697,7 @@
 print_f(hx509_context hxcontext, void *ctx, hx509_cert cert)
 {
     struct print_s *s =3D ctx;
-   =20
+
     printf("cert: %d\n", s->counter++);
     print_certificate(context, cert, s->verbose);
=20
@@ -619,11 +720,16 @@
     while(argc--) {
 	int ret;
 	ret =3D hx509_certs_init(context, argv[0], 0, lock, &certs);
-	if (ret)
+	if (ret) {
+	    if (opt->never_fail_flag) {
+		printf("ignoreing failure: %d\n", ret);
+		continue;
+	    }
 	    hx509_err(context, 1, ret, "hx509_certs_init");
+	}
 	if (opt->info_flag)
 	    hx509_certs_info(context, certs, NULL, NULL);
-	hx509_certs_iter(context, certs, print_f, &s);
+	hx509_certs_iter_f(context, certs, print_f, &s);
 	hx509_certs_free(&certs);
 	argv++;
     }
@@ -660,7 +766,7 @@
 	ret =3D hx509_certs_init(context, argv[0], 0, lock, &certs);
 	if (ret)
 	    errx(1, "hx509_certs_init: %d", ret);
-	hx509_certs_iter(context, certs, validate_f, ctx);
+	hx509_certs_iter_f(context, certs, validate_f, ctx);
 	hx509_certs_free(&certs);
 	argv++;
     }
@@ -675,31 +781,40 @@
 certificate_copy(struct certificate_copy_options *opt, int argc, char **ar=
gv)
 {
     hx509_certs certs;
-    hx509_lock lock;
+    hx509_lock inlock, outlock =3D NULL;
     int ret;
=20
-    hx509_lock_init(context, &lock);
-    lock_strings(lock, &opt->in_pass_strings);
-
-    ret =3D hx509_certs_init(context, argv[argc - 1],=20
-			   HX509_CERTS_CREATE, lock, &certs);
+    hx509_lock_init(context, &inlock);
+    lock_strings(inlock, &opt->in_pass_strings);
+
+    if (opt->out_pass_string) {
+	hx509_lock_init(context, &outlock);
+	ret =3D hx509_lock_command_string(outlock, opt->out_pass_string);
+	if (ret)
+	    errx(1, "hx509_lock_command_string: %s: %d",
+		 opt->out_pass_string, ret);
+    }
+
+    ret =3D hx509_certs_init(context, argv[argc - 1],
+			   HX509_CERTS_CREATE, inlock, &certs);
     if (ret)
 	hx509_err(context, 1, ret, "hx509_certs_init");
=20
     while(argc-- > 1) {
-	int ret;
-	ret =3D hx509_certs_append(context, certs, lock, argv[0]);
-	if (ret)
-	    hx509_err(context, 1, ret, "hx509_certs_append");
+	int retx;
+	retx =3D hx509_certs_append(context, certs, inlock, argv[0]);
+	if (retx)
+	    hx509_err(context, 1, retx, "hx509_certs_append");
 	argv++;
     }
=20
-    ret =3D hx509_certs_store(context, certs, 0, NULL);
+    ret =3D hx509_certs_store(context, certs, 0, outlock);
 	if (ret)
 	    hx509_err(context, 1, ret, "hx509_certs_store");
=20
     hx509_certs_free(&certs);
-    hx509_lock_free(lock);
+    hx509_lock_free(inlock);
+    hx509_lock_free(outlock);
=20
     return 0;
 }
@@ -709,6 +824,7 @@
     hx509_certs chain;
     const char *hostname;
     int errors;
+    int count;
 };
=20
 static int
@@ -723,8 +839,10 @@
 	printf("verify_path: %s: %d\n", s, ret);
 	hx509_free_error_string(s);
 	v->errors++;
-    } else
+    } else {
+	v->count++;
 	printf("path ok\n");
+    }
=20
     if (v->hostname) {
 	ret =3D hx509_verify_hostname(hxcontext, c, 0, HX509_HN_HOSTNAME,
@@ -753,9 +871,17 @@
 	hx509_context_set_missing_revoke(context, 1);
=20
     ret =3D hx509_verify_init_ctx(context, &ctx);
+    if (ret)
+	hx509_err(context, 1, ret, "hx509_verify_init_ctx");
     ret =3D hx509_certs_init(context, "MEMORY:anchors", 0, NULL, &anchors);
+    if (ret)
+	hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
     ret =3D hx509_certs_init(context, "MEMORY:chain", 0, NULL, &chain);
+    if (ret)
+	hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
     ret =3D hx509_certs_init(context, "MEMORY:certs", 0, NULL, &certs);
+    if (ret)
+	hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     if (opt->allow_proxy_certificate_flag)
 	hx509_verify_set_proxy_certificate(ctx, 1);
@@ -771,7 +897,7 @@
 	if (p =3D=3D NULL)
 	    errx(1, "Failed to parse time %s, need to be on format %%Y-%%m-%%d",
 		 opt->time_string);
-=09
+
 	t =3D tm2time (tm, 0);
=20
 	hx509_verify_set_time(ctx, t);
@@ -808,7 +934,7 @@
=20
 	    ret =3D hx509_certs_append(context, certs, NULL, s);
 	    if (ret)
-		hx509_err(context, 1, ret, "hx509_certs_append: certs: %s: %d",=20
+		hx509_err(context, 1, ret, "hx509_certs_append: certs: %s: %d",
 			  s, ret);
=20
 	} else if (strncmp(s, "crl:", 4) =3D=3D 0) {
@@ -836,7 +962,7 @@
     v.ctx =3D ctx;
     v.chain =3D chain;
=20
-    hx509_certs_iter(context, certs, verify_f, &v);
+    hx509_certs_iter_f(context, certs, verify_f, &v);
=20
     hx509_verify_destroy_ctx(ctx);
=20
@@ -846,6 +972,12 @@
=20
     hx509_revoke_free(&revoke_ctx);
=20
+
+    if (v.count =3D=3D 0) {
+	printf("no certs verify at all\n");
+	return 1;
+    }
+
     if (v.errors) {
 	printf("failed verifing %d checks\n", v.errors);
 	return 1;
@@ -871,6 +1003,7 @@
     lock_strings(lock, &opt->pass_strings);
=20
     ret =3D hx509_certs_init(context, "MEMORY:cert-store", 0, NULL, &certs=
);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     while (argc > 0) {
=20
@@ -885,6 +1018,17 @@
     if (opt->friendlyname_string)
 	hx509_query_match_friendly_name(q, opt->friendlyname_string);
=20
+    if (opt->eku_string) {
+	heim_oid oid;
+
+	parse_oid(opt->eku_string, NULL, &oid);
+
+	ret =3D hx509_query_match_eku(q, &oid);
+	if (ret)
+	    errx(1, "hx509_query_match_eku: %d", ret);
+	der_free_oid(&oid);
+    }
+
     if (opt->private_key_flag)
 	hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
=20
@@ -894,6 +1038,9 @@
     if (opt->digitalSignature_flag)
 	hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
=20
+    if (opt->expr_string)
+	hx509_query_match_expr(context, q, opt->expr_string);
+
     ret =3D hx509_certs_find(context, certs, q, &c);
     hx509_query_free(context, q);
     if (ret)
@@ -935,12 +1082,14 @@
 	url =3D opt->url_path_string;
=20
     ret =3D hx509_certs_init(context, "MEMORY:ocsp-pool", 0, NULL, &pool);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     certs_strings(context, "ocsp-pool", pool, lock, &opt->pool_strings);
=20
     file =3D argv[0];
=20
     ret =3D hx509_certs_init(context, "MEMORY:ocsp-req", 0, NULL, &reqcert=
s);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     for (i =3D 1; i < argc; i++) {
 	ret =3D hx509_certs_append(context, reqcerts, lock, argv[i]);
@@ -951,7 +1100,7 @@
     ret =3D hx509_ocsp_request(context, reqcerts, pool, NULL, NULL, &req, =
nonce);
     if (ret)
 	errx(1, "hx509_ocsp_request: req: %d", ret);
-=09
+
     {
 	FILE *f;
=20
@@ -959,7 +1108,7 @@
 	if (f =3D=3D NULL)
 	    abort();
=20
-	fprintf(f,=20
+	fprintf(f,
 		"POST %s HTTP/1.0\r\n"
 		"Content-Type: application/ocsp-request\r\n"
 		"Content-Length: %ld\r\n"
@@ -997,7 +1146,7 @@
     time_t expiration;
     int ret;
=20
-    ret =3D hx509_ocsp_verify(context, 0, c, 0,=20
+    ret =3D hx509_ocsp_verify(context, 0, c, 0,
 			    os->data, os->length, &expiration);
     if (ret) {
 	char *s =3D hx509_get_error_string(hxcontext, ret);
@@ -1017,17 +1166,18 @@
     hx509_certs certs;
     int ret, i;
     heim_octet_string os;
-   =20
+
     hx509_lock_init(context, &lock);
=20
     if (opt->ocsp_file_string =3D=3D NULL)
 	errx(1, "no ocsp file given");
=20
-    ret =3D _hx509_map_file(opt->ocsp_file_string, &os.data, &os.length, N=
ULL);
+    ret =3D _hx509_map_file_os(opt->ocsp_file_string, &os);
     if (ret)
 	err(1, "map_file: %s: %d", argv[0], ret);
-   =20
+
     ret =3D hx509_certs_init(context, "MEMORY:test-certs", 0, NULL, &certs=
);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     for (i =3D 0; i < argc; i++) {
 	ret =3D hx509_certs_append(context, certs, lock, argv[i]);
@@ -1035,10 +1185,10 @@
 	    hx509_err(context, 1, ret, "hx509_certs_append: %s", argv[i]);
     }
=20
-    ret =3D hx509_certs_iter(context, certs, verify_o, &os);
+    ret =3D hx509_certs_iter_f(context, certs, verify_o, &os);
=20
     hx509_certs_free(&certs);
-    _hx509_unmap_file(os.data, os.length);
+    _hx509_unmap_file_os(&os);
     hx509_lock_free(lock);
=20
     return ret;
@@ -1050,7 +1200,7 @@
     hx509_private_key *keys;
     hx509_certs certs;
     int ret;
-   =20
+
     *key =3D NULL;
=20
     ret =3D hx509_certs_init(context, fn, 0, NULL, &certs);
@@ -1085,10 +1235,10 @@
=20
 	if (fn =3D=3D NULL)
 	    errx(1, "no key argument, don't know here to store key");
-=09
+
 	if (strcasecmp(type, "rsa") !=3D 0)
 	    errx(1, "can only handle rsa keys for now");
-	   =20
+
 	e =3D BN_new();
 	BN_set_word(e, 0x10001);
=20
@@ -1110,13 +1260,13 @@
 	p0 =3D p =3D malloc(len);
 	if (p =3D=3D NULL)
 	    errx(1, "out of memory");
-=09
+
 	i2d_RSAPrivateKey(rsa, &p);
=20
 	rk_dumpdata(fn, p0, len);
 	memset(p0, 0, len);
 	free(p0);
-=09
+
 	RSA_free(rsa);
=20
     } else if (fn =3D=3D NULL)
@@ -1139,12 +1289,12 @@
=20
     memset(&key, 0, sizeof(key));
=20
-    get_key(opt->key_string,=20
+    get_key(opt->key_string,
 	    opt->generate_key_string,
 	    opt->key_bits_integer,
 	    &signer);
-   =20
-    _hx509_request_init(context, &req);
+
+    hx509_request_init(context, &req);
=20
     if (opt->subject_string) {
 	hx509_name name =3D NULL;
@@ -1152,7 +1302,7 @@
 	ret =3D hx509_parse_name(context, opt->subject_string, &name);
 	if (ret)
 	    errx(1, "hx509_parse_name: %d\n", ret);
-	_hx509_request_set_name(context, req, name);
+	hx509_request_set_name(context, req, name);
=20
 	if (opt->verbose_flag) {
 	    char *s;
@@ -1163,26 +1313,30 @@
     }
=20
     for (i =3D 0; i < opt->email_strings.num_strings; i++) {
-	ret =3D _hx509_request_add_email(context, req,=20
+	ret =3D _hx509_request_add_email(context, req,
 				       opt->email_strings.strings[i]);
+	if (ret)
+	    hx509_err(context, 1, ret, "hx509_request_add_email");
     }
=20
     for (i =3D 0; i < opt->dnsname_strings.num_strings; i++) {
-	ret =3D _hx509_request_add_dns_name(context, req,=20
+	ret =3D _hx509_request_add_dns_name(context, req,
 					  opt->dnsname_strings.strings[i]);
+	if (ret)
+	    hx509_err(context, 1, ret, "hx509_request_add_dns_name");
     }
=20
=20
-    ret =3D _hx509_private_key2SPKI(context, signer, &key);
+    ret =3D hx509_private_key2SPKI(context, signer, &key);
     if (ret)
-	errx(1, "_hx509_private_key2SPKI: %d\n", ret);
-
-    ret =3D _hx509_request_set_SubjectPublicKeyInfo(context,
+	errx(1, "hx509_private_key2SPKI: %d\n", ret);
+
+    ret =3D hx509_request_set_SubjectPublicKeyInfo(context,
 						  req,
 						  &key);
     free_SubjectPublicKeyInfo(&key);
     if (ret)
-	hx509_err(context, 1, ret, "_hx509_request_set_SubjectPublicKeyInfo");
+	hx509_err(context, 1, ret, "hx509_request_set_SubjectPublicKeyInfo");
=20
     ret =3D _hx509_request_to_pkcs10(context,
 				   req,
@@ -1191,8 +1345,8 @@
     if (ret)
 	hx509_err(context, 1, ret, "_hx509_request_to_pkcs10");
=20
-    _hx509_private_key_free(&signer);
-    _hx509_request_free(&req);
+    hx509_private_key_free(&signer);
+    hx509_request_free(&req);
=20
     if (ret =3D=3D 0)
 	rk_dumpdata(outfile, request.data, request.length);
@@ -1216,7 +1370,7 @@
 	    hx509_err(context, 1, ret, "parse_request: %s", argv[i]);
=20
 	ret =3D _hx509_request_print(context, req, stdout);
-	_hx509_request_free(&req);
+	hx509_request_free(&req);
 	if (ret)
 	    hx509_err(context, 1, ret, "Failed to print file %s", argv[i]);
     }
@@ -1240,6 +1394,15 @@
 	if (m !=3D NULL)
 	    printf("dh: %s\n", m->name);
     }
+#ifdef HAVE_OPENSSL
+    {
+	printf("ecdsa: ECDSA_METHOD-not-export\n");
+    }
+#else
+    {
+	printf("ecdsa: hcrypto null\n");
+    }
+#endif
     {
 	int ret =3D RAND_status();
 	printf("rand: %s\n", ret =3D=3D 1 ? "ok" : "not available");
@@ -1286,7 +1449,7 @@
 {
     AlgorithmIdentifier *val;
     unsigned int len, i;
-    int ret, type;
+    int ret, type =3D HX509_SELECT_ALL;
=20
     if (opt->type_string) {
 	if (strcmp(opt->type_string, "all") =3D=3D 0)
@@ -1299,8 +1462,7 @@
 	    type =3D HX509_SELECT_SECRET_ENC;
 	else
 	    errx(1, "unknown type: %s", opt->type_string);
-    } else
-	type =3D HX509_SELECT_ALL;
+    }
=20
     ret =3D hx509_crypto_available(context, type, NULL, &val, &len);
     if (ret)
@@ -1323,7 +1485,7 @@
 {
     hx509_peer_info peer =3D NULL;
     AlgorithmIdentifier selected;
-    int ret, type;
+    int ret, type =3D HX509_SELECT_DIGEST;
     char *s;
=20
     if (opt->type_string) {
@@ -1335,8 +1497,7 @@
 	    type =3D HX509_SELECT_SECRET_ENC;
 	else
 	    errx(1, "unknown type: %s", opt->type_string);
-    } else
-	type =3D HX509_SELECT_DIGEST;
+    }
=20
     if (opt->peer_cmstype_strings.num_strings)
 	peer_strings(context, &peer, &opt->peer_cmstype_strings);
@@ -1371,15 +1532,17 @@
 	    len =3D hex_decode(p, buf2, strlen(p));
 	    if (len < 0)
 		errx(1, "hex_decode failed");
-	    if (fwrite(buf2, 1, len, stdout) !=3D len)
+	    if (fwrite(buf2, 1, len, stdout) !=3D (size_t)len)
 		errx(1, "fwrite failed");
 	}
     } else {
-	char buf[28], *p;
-	size_t len;
+        char buf[28], *p;
+	ssize_t len;
=20
 	while((len =3D fread(buf, 1, sizeof(buf), stdin)) !=3D 0) {
 	    len =3D hex_encode(buf, len, &p);
+	    if (len < 0)
+	        continue;
 	    fprintf(stdout, "%s\n", p);
 	    free(p);
 	}
@@ -1387,112 +1550,193 @@
     return 0;
 }
=20
+struct cert_type_opt {
+    int pkinit;
+};
+
+
 static int
-eval_types(hx509_context context,=20
+https_server(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_op=
t *opt)
+{
+    return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_server=
Auth);
+}
+
+static int
+https_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_op=
t *opt)
+{
+    return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_client=
Auth);
+}
+
+static int
+peap_server(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt=
 *opt)
+{
+    return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_server=
Auth);
+}
+
+static int
+pkinit_kdc(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_opt =
*opt)
+{
+    opt->pkinit++;
+    return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkkdcekuoid);
+}
+
+static int
+pkinit_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_o=
pt *opt)
+{
+    int ret;
+
+    opt->pkinit++;
+
+    ret =3D hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkekuoid);
+    if (ret)
+	return ret;
+
+    ret =3D hx509_ca_tbs_add_eku(context, tbs, &asn1_oid_id_ms_client_auth=
entication);
+    if (ret)
+	return ret;
+
+    return hx509_ca_tbs_add_eku(context, tbs, &asn1_oid_id_pkinit_ms_eku);
+}
+
+static int
+email_client(hx509_context contextp, hx509_ca_tbs tbs, struct cert_type_op=
t *opt)
+{
+    return hx509_ca_tbs_add_eku(contextp, tbs, &asn1_oid_id_pkix_kp_emailP=
rotection);
+}
+
+struct {
+    const char *type;
+    const char *desc;
+    int (*eval)(hx509_context, hx509_ca_tbs, struct cert_type_opt *);
+} certtypes[] =3D {
+    {
+	"https-server",
+	"Used for HTTPS server and many other TLS server certificate types",
+	https_server
+    },
+    {
+	"https-client",
+	"Used for HTTPS client certificates",
+	https_client
+    },
+    {
+	"email-client",
+	"Certificate will be use for email",
+	email_client
+    },
+    {
+	"pkinit-client",
+	"Certificate used for Kerberos PK-INIT client certificates",
+	pkinit_client
+    },
+    {
+	"pkinit-kdc",
+	"Certificates used for Kerberos PK-INIT KDC certificates",
+	pkinit_kdc
+    },
+    {
+	"peap-server",
+	"Certificate used for Radius PEAP (Protected EAP)",
+	peap_server
+    }
+};
+
+static void
+print_eval_types(FILE *out)
+{
+    rtbl_t table;
+    unsigned i;
+
+    table =3D rtbl_create();
+    rtbl_add_column_by_id (table, 0, "Name", 0);
+    rtbl_add_column_by_id (table, 1, "Description", 0);
+
+    for (i =3D 0; i < sizeof(certtypes)/sizeof(certtypes[0]); i++) {
+	rtbl_add_column_entry_by_id(table, 0, certtypes[i].type);
+	rtbl_add_column_entry_by_id(table, 1, certtypes[i].desc);
+    }
+
+    rtbl_format (table, out);
+    rtbl_destroy (table);
+}
+
+static int
+eval_types(hx509_context contextp,
 	   hx509_ca_tbs tbs,
 	   const struct certificate_sign_options *opt)
 {
-    int pkinit =3D 0;
-    int i, ret;
+    struct cert_type_opt ctopt;
+    int i;
+    size_t j;
+    int ret;
+
+    memset(&ctopt, 0, sizeof(ctopt));
=20
     for (i =3D 0; i < opt->type_strings.num_strings; i++) {
 	const char *type =3D opt->type_strings.strings[i];
-=09
-	if (strcmp(type, "https-server") =3D=3D 0) {
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_pkix_kp_serverAuth());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-	} else if (strcmp(type, "https-client") =3D=3D 0) {
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_pkix_kp_clientAuth());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-	} else if (strcmp(type, "peap-server") =3D=3D 0) {
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_pkix_kp_serverAuth());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-	} else if (strcmp(type, "pkinit-kdc") =3D=3D 0) {
-	    pkinit++;
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_pkkdcekuoid());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-	} else if (strcmp(type, "pkinit-client") =3D=3D 0) {
-	    pkinit++;
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_pkekuoid());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_ms_client_authentication());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_pkinit_ms_eku());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-
-	} else if (strcmp(type, "email") =3D=3D 0) {
-	    ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				       oid_id_pkix_kp_emailProtection());
-	    if (ret)
-		hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
-	} else
-	    errx(1, "unknown type %s", type);
+
+	for (j =3D 0; j < sizeof(certtypes)/sizeof(certtypes[0]); j++) {
+	    if (strcasecmp(type, certtypes[j].type) =3D=3D 0) {
+		ret =3D (*certtypes[j].eval)(contextp, tbs, &ctopt);
+		if (ret)
+		    hx509_err(contextp, 1, ret,
+			      "Failed to evaluate cert type %s", type);
+		break;
+	    }
+	}
+	if (j >=3D sizeof(certtypes)/sizeof(certtypes[0])) {
+	    fprintf(stderr, "Unknown certificate type %s\n\n", type);
+	    fprintf(stderr, "Available types:\n");
+	    print_eval_types(stderr);
+	    exit(1);
+	}
     }
=20
-    if (pkinit > 1)
-	errx(1, "More the one PK-INIT type given");
-
     if (opt->pk_init_principal_string) {
-	if (!pkinit)
+	if (!ctopt.pkinit)
 	    errx(1, "pk-init principal given but no pk-init oid");
=20
-	ret =3D hx509_ca_tbs_add_san_pkinit(context, tbs,
+	ret =3D hx509_ca_tbs_add_san_pkinit(contextp, tbs,
 					  opt->pk_init_principal_string);
 	if (ret)
-	    hx509_err(context, 1, ret, "hx509_ca_tbs_add_san_pkinit");
+	    hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_pkinit");
     }
=20
     if (opt->ms_upn_string) {
-	if (!pkinit)
-	    errx(1, "MS up given but no pk-init oid");
-
-	ret =3D hx509_ca_tbs_add_san_ms_upn(context, tbs, opt->ms_upn_string);
+	if (!ctopt.pkinit)
+	    errx(1, "MS upn given but no pk-init oid");
+
+	ret =3D hx509_ca_tbs_add_san_ms_upn(contextp, tbs, opt->ms_upn_string);
 	if (ret)
-	    hx509_err(context, 1, ret, "hx509_ca_tbs_add_san_ms_upn");
+	    hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_ms_upn");
     }
=20
-   =20
+
     for (i =3D 0; i < opt->hostname_strings.num_strings; i++) {
 	const char *hostname =3D opt->hostname_strings.strings[i];
=20
-	ret =3D hx509_ca_tbs_add_san_hostname(context, tbs, hostname);
+	ret =3D hx509_ca_tbs_add_san_hostname(contextp, tbs, hostname);
 	if (ret)
-	    hx509_err(context, 1, ret, "hx509_ca_tbs_add_san_hostname");
+	    hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_hostname");
     }
=20
     for (i =3D 0; i < opt->email_strings.num_strings; i++) {
 	const char *email =3D opt->email_strings.strings[i];
=20
-	ret =3D hx509_ca_tbs_add_san_rfc822name(context, tbs, email);
+	ret =3D hx509_ca_tbs_add_san_rfc822name(contextp, tbs, email);
 	if (ret)
-	    hx509_err(context, 1, ret, "hx509_ca_tbs_add_san_hostname");
-=09
-	ret =3D hx509_ca_tbs_add_eku(context, tbs,=20
-				   oid_id_pkix_kp_emailProtection());
+	    hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_hostname");
+
+	ret =3D hx509_ca_tbs_add_eku(contextp, tbs,
+				   &asn1_oid_id_pkix_kp_emailProtection);
 	if (ret)
-	    hx509_err(context, 1, ret, "hx509_ca_tbs_add_eku");
+	    hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_eku");
     }
=20
     if (opt->jid_string) {
-	ret =3D hx509_ca_tbs_add_san_jid(context, tbs, opt->jid_string);
+	ret =3D hx509_ca_tbs_add_san_jid(contextp, tbs, opt->jid_string);
 	if (ret)
-	    hx509_err(context, 1, ret, "hx509_ca_tbs_add_san_jid");
+	    hx509_err(contextp, 1, ret, "hx509_ca_tbs_add_san_jid");
     }
=20
     return 0;
@@ -1557,6 +1801,9 @@
 	if (opt->generate_key_string =3D=3D NULL
 	    && opt->ca_private_key_string =3D=3D NULL)
 	    errx(1, "no signing private key");
+
+	if (opt->req_string)
+	    errx(1, "can't be self-signing and have a request at the same time");
     } else
 	errx(1, "missing ca key");
=20
@@ -1566,9 +1813,9 @@
 	if (ret)
 	    err(1, "read_private_key");
=20
-	ret =3D _hx509_private_key2SPKI(context, private_key, &spki);
+	ret =3D hx509_private_key2SPKI(context, private_key, &spki);
 	if (ret)
-	    errx(1, "_hx509_private_key2SPKI: %d\n", ret);
+	    errx(1, "hx509_private_key2SPKI: %d\n", ret);
=20
 	if (opt->self_signed_flag)
 	    cert_key =3D private_key;
@@ -1580,21 +1827,23 @@
 	ret =3D _hx509_request_parse(context, opt->req_string, &req);
 	if (ret)
 	    hx509_err(context, 1, ret, "parse_request: %s", opt->req_string);
-	ret =3D _hx509_request_get_name(context, req, &subject);
+	ret =3D hx509_request_get_name(context, req, &subject);
 	if (ret)
 	    hx509_err(context, 1, ret, "get name");
-	ret =3D _hx509_request_get_SubjectPublicKeyInfo(context, req, &spki);
+	ret =3D hx509_request_get_SubjectPublicKeyInfo(context, req, &spki);
 	if (ret)
 	    hx509_err(context, 1, ret, "get spki");
-	_hx509_request_free(&req);
+	hx509_request_free(&req);
     }
=20
     if (opt->generate_key_string) {
 	struct hx509_generate_private_context *keyctx;
=20
-	ret =3D _hx509_generate_private_key_init(context,=20
-					       oid_id_pkcs1_rsaEncryption(),
+	ret =3D _hx509_generate_private_key_init(context,
+					       &asn1_oid_id_pkcs1_rsaEncryption,
 					       &keyctx);
+	if (ret)
+	    hx509_err(context, 1, ret, "generate private key");
=20
 	if (opt->issue_ca_flag)
 	    _hx509_generate_private_key_is_ca(context, keyctx);
@@ -1608,10 +1857,10 @@
 	_hx509_generate_private_key_free(&keyctx);
 	if (ret)
 	    hx509_err(context, 1, ret, "generate private key");
-=09
-	ret =3D _hx509_private_key2SPKI(context, cert_key, &spki);
+
+	ret =3D hx509_private_key2SPKI(context, cert_key, &spki);
 	if (ret)
-	    errx(1, "_hx509_private_key2SPKI: %d\n", ret);
+	    errx(1, "hx509_private_key2SPKI: %d\n", ret);
=20
 	if (opt->self_signed_flag)
 	    private_key =3D cert_key;
@@ -1638,7 +1887,7 @@
     ret =3D hx509_ca_tbs_init(context, &tbs);
     if (ret)
 	hx509_err(context, 1, ret, "hx509_ca_tbs_init");
-=09
+
     if (opt->template_certificate_string) {
 	hx509_cert template;
 	hx509_certs tcerts;
@@ -1656,7 +1905,7 @@
 	if (ret)
 	    hx509_err(context, 1, ret, "no template certificate found");
=20
-	flags =3D parse_units(opt->template_fields_string,=20
+	flags =3D parse_units(opt->template_fields_string,
 			    hx509_ca_tbs_template_units(), "");
=20
 	ret =3D hx509_ca_tbs_set_template(context, tbs, flags, template);
@@ -1692,7 +1941,7 @@
     }
=20
     if (opt->crl_uri_string) {
-	ret =3D hx509_ca_tbs_add_crl_dp_uri(context, tbs,=20
+	ret =3D hx509_ca_tbs_add_crl_dp_uri(context, tbs,
 					  opt->crl_uri_string, NULL);
 	if (ret)
 	    hx509_err(context, 1, ret, "hx509_ca_tbs_add_crl_dp_uri");
@@ -1720,7 +1969,7 @@
 	ret =3D hx509_ca_tbs_set_notAfter_lifetime(context, tbs, delta);
 	if (ret)
 	    hx509_err(context, 1, ret, "hx509_ca_tbs_set_notAfter_lifetime");
-    }=09
+    }
=20
     if (opt->self_signed_flag) {
 	ret =3D hx509_ca_sign_self(context, tbs, private_key, &cert);
@@ -1736,12 +1985,12 @@
 	ret =3D _hx509_cert_assign_key(cert, cert_key);
 	if (ret)
 	    hx509_err(context, 1, ret, "_hx509_cert_assign_key");
-    }	   =20
+    }
=20
     {
 	hx509_certs certs;
=20
-	ret =3D hx509_certs_init(context, opt->certificate_string,=20
+	ret =3D hx509_certs_init(context, opt->certificate_string,
 			       HX509_CERTS_CREATE, NULL, &certs);
 	if (ret)
 	    hx509_err(context, 1, ret, "hx509_certs_init");
@@ -1765,8 +2014,8 @@
     free_SubjectPublicKeyInfo(&spki);
=20
     if (private_key !=3D cert_key)
-	_hx509_private_key_free(&private_key);
-    _hx509_private_key_free(&cert_key);
+	hx509_private_key_free(&private_key);
+    hx509_private_key_free(&cert_key);
=20
     hx509_ca_tbs_free(&tbs);
=20
@@ -1790,7 +2039,7 @@
     if (ret)
 	errx(1, "hx509_cms_create_signed_1");
=20
-    ret =3D hx509_cms_verify_signed(context, vctx, sd.data, sd.length,
+    ret =3D hx509_cms_verify_signed(context, vctx, 0, sd.data, sd.length,
 				  NULL, NULL, &type, &c, &signer);
     free(sd.data);
     if (ret)
@@ -1815,6 +2064,7 @@
     lock_strings(lock, &opt->pass_strings);
=20
     ret =3D hx509_certs_init(context, "MEMORY:test-crypto", 0, NULL, &cert=
s);
+    if (ret) hx509_err(context, 1, ret, "hx509_certs_init: MEMORY");
=20
     for (i =3D 0; i < argc; i++) {
 	ret =3D hx509_certs_append(context, certs, lock, argv[i]);
@@ -1828,7 +2078,9 @@
=20
     hx509_verify_attach_anchors(vctx, certs);
=20
-    ret =3D hx509_certs_iter(context, certs, test_one_cert, vctx);
+    ret =3D hx509_certs_iter_f(context, certs, test_one_cert, vctx);
+    if (ret)
+	hx509_err(context, 1, ret, "hx509_cert_iter");
=20
     hx509_certs_free(&certs);
=20
@@ -1880,7 +2132,7 @@
 	ret =3D hx509_certs_init(context, opt->signer_string, 0,
 			       NULL, &certs);
 	if (ret)
-	    hx509_err(context, 1, ret,=20
+	    hx509_err(context, 1, ret,
 		      "hx509_certs_init: %s", opt->signer_string);
=20
 	ret =3D hx509_query_alloc(context, &q);
@@ -1912,6 +2164,9 @@
=20
 	ret =3D hx509_certs_init(context, "MEMORY:revoked-certs", 0,
 			       NULL, &revoked);
+	if (ret)
+	    hx509_err(context, 1, ret,
+		      "hx509_certs_init: MEMORY cert");
=20
 	for (i =3D 0; i < argc; i++) {
 	    ret =3D hx509_certs_append(context, revoked, lock, argv[i]);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/keyset.c
--- a/head/crypto/heimdal/lib/hx509/keyset.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/keyset.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,39 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: keyset.c 22466 2008-01-16 14:26:35Z lha $");
=20
 /**
  * @page page_keyset Certificate store operations
@@ -40,7 +41,7 @@
  * Type of certificates store:
  * - MEMORY
  *   In memory based format. Doesnt support storing.
- * - FILE=20
+ * - FILE
  *   FILE supports raw DER certicates and PEM certicates. When PEM is
  *   used the file can contain may certificates and match private
  *   keys. Support storing the certificates. DER format only supports
@@ -59,7 +60,7 @@
  */
=20
 struct hx509_certs_data {
-    int ref;
+    unsigned int ref;
     struct hx509_keyset_ops *ops;
     void *ops_data;
 };
@@ -84,7 +85,7 @@
     if (_hx509_ks_type(context, ops->name))
 	return;
=20
-    val =3D realloc(context->ks_ops,=20
+    val =3D realloc(context->ks_ops,
 		  (context->ks_num_ops + 1) * sizeof(context->ks_ops[0]));
     if (val =3D=3D NULL)
 	return;
@@ -138,10 +139,10 @@
 	hx509_clear_error_string(context);
 	return ENOMEM;
     }
-   =20
+
     ops =3D _hx509_ks_type(context, type);
     if (ops =3D=3D NULL) {
-	hx509_set_error_string(context, 0, ENOENT,=20
+	hx509_set_error_string(context, 0, ENOENT,
 			       "Keyset type %s is not supported", type);
 	free(type);
 	return ENOENT;
@@ -199,15 +200,15 @@
=20
=20
 hx509_certs
-_hx509_certs_ref(hx509_certs certs)
+hx509_certs_ref(hx509_certs certs)
 {
     if (certs =3D=3D NULL)
 	return NULL;
-    if (certs->ref <=3D 0)
-	_hx509_abort("certs refcount <=3D 0");
+    if (certs->ref =3D=3D 0)
+	_hx509_abort("certs refcount =3D=3D 0 on ref");
+    if (certs->ref =3D=3D UINT_MAX)
+	_hx509_abort("certs refcount =3D=3D UINT_MAX on ref");
     certs->ref++;
-    if (certs->ref =3D=3D 0)
-	_hx509_abort("certs refcount =3D=3D 0");
     return certs;
 }
=20
@@ -223,8 +224,8 @@
 hx509_certs_free(hx509_certs *certs)
 {
     if (*certs) {
-	if ((*certs)->ref <=3D 0)
-	    _hx509_abort("refcount <=3D 0");
+	if ((*certs)->ref =3D=3D 0)
+	    _hx509_abort("cert refcount =3D=3D 0 on free");
 	if (--(*certs)->ref > 0)
 	    return;
=20
@@ -257,8 +258,8 @@
     int ret;
=20
     if (certs->ops->iter_start =3D=3D NULL) {
-	hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,=20
-			       "Keyset type %s doesn't support iteration",=20
+	hx509_set_error_string(context, 0, HX509_UNSUPPORTED_OPERATION,
+			       "Keyset type %s doesn't support iteration",
 			       certs->ops->name);
 	return HX509_UNSUPPORTED_OPERATION;
     }
@@ -324,7 +325,7 @@
  * @param certs certificate store to iterate over.
  * @param func function to call for each certificate. The function
  * should return non-zero to abort the iteration, that value is passed
- * back to te caller of hx509_certs_iter().
+ * back to the caller of hx509_certs_iter_f().
  * @param ctx context variable that will passed to the function.
  *
  * @return Returns an hx509 error code.
@@ -333,10 +334,10 @@
  */
=20
 int
-hx509_certs_iter(hx509_context context,=20
-		 hx509_certs certs,=20
-		 int (*func)(hx509_context, void *, hx509_cert),
-		 void *ctx)
+hx509_certs_iter_f(hx509_context context,
+		   hx509_certs certs,
+		   int (*func)(hx509_context, void *, hx509_cert),
+		   void *ctx)
 {
     hx509_cursor cursor;
     hx509_cert c;
@@ -345,7 +346,7 @@
     ret =3D hx509_certs_start_seq(context, certs, &cursor);
     if (ret)
 	return ret;
-   =20
+
     while (1) {
 	ret =3D hx509_certs_next_cert(context, certs, cursor, &c);
 	if (ret)
@@ -365,13 +366,61 @@
     return ret;
 }
=20
+/**
+ * Iterate over all certificates in a keystore and call an function
+ * for each fo them.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to iterate over.
+ * @param func function to call for each certificate. The function
+ * should return non-zero to abort the iteration, that value is passed
+ * back to the caller of hx509_certs_iter().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+#ifdef __BLOCKS__
+
+static int
+certs_iter(hx509_context context, void *ctx, hx509_cert cert)
+{
+    int (^func)(hx509_cert) =3D ctx;
+    return func(cert);
+}
=20
 /**
- * Function to use to hx509_certs_iter() as a function argument, the
- * ctx variable to hx509_certs_iter() should be a FILE file descriptor.
+ * Iterate over all certificates in a keystore and call an block
+ * for each fo them.
  *
  * @param context a hx509 context.
- * @param ctx used by hx509_certs_iter().
+ * @param certs certificate store to iterate over.
+ * @param func block to call for each certificate. The function
+ * should return non-zero to abort the iteration, that value is passed
+ * back to the caller of hx509_certs_iter().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+int
+hx509_certs_iter(hx509_context context,
+		 hx509_certs certs,
+		 int (^func)(hx509_cert))
+{
+    return hx509_certs_iter_f(context, certs, certs_iter, func);
+}
+#endif
+
+
+/**
+ * Function to use to hx509_certs_iter_f() as a function argument, the
+ * ctx variable to hx509_certs_iter_f() should be a FILE file descriptor.
+ *
+ * @param context a hx509 context.
+ * @param ctx used by hx509_certs_iter_f().
  * @param c a certificate
  *
  * @return Returns an hx509 error code.
@@ -420,8 +469,8 @@
 hx509_certs_add(hx509_context context, hx509_certs certs, hx509_cert cert)
 {
     if (certs->ops->add =3D=3D NULL) {
-	hx509_set_error_string(context, 0, ENOENT,=20
-			       "Keyset type %s doesn't support add operation",=20
+	hx509_set_error_string(context, 0, ENOENT,
+			       "Keyset type %s doesn't support add operation",
 			       certs->ops->name);
 	return ENOENT;
     }
@@ -445,7 +494,7 @@
=20
 int
 hx509_certs_find(hx509_context context,
-		 hx509_certs certs,=20
+		 hx509_certs certs,
 		 const hx509_query *q,
 		 hx509_cert *r)
 {
@@ -481,6 +530,10 @@
     hx509_certs_end_seq(context, certs, cursor);
     if (ret)
 	return ret;
+    /**
+     * Return HX509_CERT_NOT_FOUND if no certificate in certs matched
+     * the query.
+     */
     if (c =3D=3D NULL) {
 	hx509_clear_error_string(context);
 	return HX509_CERT_NOT_FOUND;
@@ -489,6 +542,77 @@
     return 0;
 }
=20
+/**
+ * Filter certificate matching the query.
+ *
+ * @param context a hx509 context.
+ * @param certs certificate store to search.
+ * @param q query allocated with @ref hx509_query functions.
+ * @param result the filtered certificate store, caller must free with
+ *        hx509_certs_free().
+ *
+ * @return Returns an hx509 error code.
+ *
+ * @ingroup hx509_keyset
+ */
+
+int
+hx509_certs_filter(hx509_context context,
+		   hx509_certs certs,
+		   const hx509_query *q,
+		   hx509_certs *result)
+{
+    hx509_cursor cursor;
+    hx509_cert c;
+    int ret, found =3D 0;
+
+    _hx509_query_statistic(context, 0, q);
+
+    ret =3D hx509_certs_init(context, "MEMORY:filter-certs", 0,
+			   NULL, result);
+    if (ret)
+	return ret;
+
+    ret =3D hx509_certs_start_seq(context, certs, &cursor);
+    if (ret) {
+	hx509_certs_free(result);
+	return ret;
+    }
+
+    c =3D NULL;
+    while (1) {
+	ret =3D hx509_certs_next_cert(context, certs, cursor, &c);
+	if (ret)
+	    break;
+	if (c =3D=3D NULL)
+	    break;
+	if (_hx509_query_match_cert(context, q, c)) {
+	    hx509_certs_add(context, *result, c);
+	    found =3D 1;
+	}
+	hx509_cert_free(c);
+    }
+
+    hx509_certs_end_seq(context, certs, cursor);
+    if (ret) {
+	hx509_certs_free(result);
+	return ret;
+    }
+
+    /**
+     * Return HX509_CERT_NOT_FOUND if no certificate in certs matched
+     * the query.
+     */
+    if (!found) {
+	hx509_certs_free(result);
+	hx509_clear_error_string(context);
+	return HX509_CERT_NOT_FOUND;
+    }
+
+    return 0;
+}
+
+
 static int
 certs_merge_func(hx509_context context, void *ctx, hx509_cert c)
 {
@@ -513,7 +637,7 @@
 {
     if (from =3D=3D NULL)
 	return 0;
-    return hx509_certs_iter(context, from, certs_merge_func, to);
+    return hx509_certs_iter_f(context, from, certs_merge_func, to);
 }
=20
 /**
@@ -604,7 +728,7 @@
  */
=20
 int
-hx509_certs_info(hx509_context context,=20
+hx509_certs_info(hx509_context context,
 		 hx509_certs certs,
 		 int (*func)(void *, const char *),
 		 void *ctx)
@@ -639,8 +763,8 @@
 }
=20
 int
-_hx509_certs_keys_get(hx509_context context,=20
-		      hx509_certs certs,=20
+_hx509_certs_keys_get(hx509_context context,
+		      hx509_certs certs,
 		      hx509_private_key **keys)
 {
     if (certs->ops->getkeys =3D=3D NULL) {
@@ -651,8 +775,8 @@
 }
=20
 int
-_hx509_certs_keys_add(hx509_context context,=20
-		      hx509_certs certs,=20
+_hx509_certs_keys_add(hx509_context context,
+		      hx509_certs certs,
 		      hx509_private_key key)
 {
     if (certs->ops->addkey =3D=3D NULL) {
@@ -672,6 +796,6 @@
 {
     int i;
     for (i =3D 0; keys[i]; i++)
-	_hx509_private_key_free(&keys[i]);
+	hx509_private_key_free(&keys[i]);
     free(keys);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ks_dir.c
--- a/head/crypto/heimdal/lib/hx509/ks_dir.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ks_dir.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: ks_dir.c 19778 2007-01-09 10:52:13Z lha $");
 #include <dirent.h>
=20
 /*
@@ -55,7 +54,7 @@
=20
 static int
 dir_init(hx509_context context,
-	 hx509_certs certs, void **data, int flags,=20
+	 hx509_certs certs, void **data, int flags,
 	 const char *residue, hx509_lock lock)
 {
     *data =3D NULL;
@@ -71,7 +70,7 @@
 	    return ENOENT;
 	}
=20
-	if ((sb.st_mode & S_IFDIR) =3D=3D 0) {
+	if (!S_ISDIR(sb.st_mode)) {
 	    hx509_set_error_string(context, 0, ENOTDIR,
 				   "%s is not a directory", residue);
 	    return ENOTDIR;
@@ -94,9 +93,7 @@
     return 0;
 }
=20
-
-
-static int=20
+static int
 dir_iter_start(hx509_context context,
 	       hx509_certs certs, void *data, void **cursor)
 {
@@ -116,6 +113,7 @@
 	free(d);
 	return errno;
     }
+    rk_cloexec_dir(d->dir);
     d->certs =3D NULL;
     d->iter =3D NULL;
=20
@@ -129,7 +127,7 @@
 {
     struct dircursor *d =3D iter;
     int ret =3D 0;
-   =20
+
     *cert =3D NULL;
=20
     do {
@@ -160,10 +158,10 @@
 	}
 	if (strcmp(dir->d_name, ".") =3D=3D 0 || strcmp(dir->d_name, "..") =3D=3D=
 0)
 	    continue;
-=09
+
 	if (asprintf(&fn, "FILE:%s/%s", (char *)data, dir->d_name) =3D=3D -1)
 	    return ENOMEM;
-=09
+
 	ret =3D hx509_certs_init(context, fn, 0, NULL, &d->certs);
 	if (ret =3D=3D 0) {
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ks_file.c
--- a/head/crypto/heimdal/lib/hx509/ks_file.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ks_file.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2005 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: ks_file.c 22465 2008-01-16 14:25:24Z lha $");
=20
 typedef enum { USE_PEM, USE_DER } outformat;
=20
@@ -47,10 +46,11 @@
  */
=20
 static int
-parse_certificate(hx509_context context, const char *fn,=20
-		  struct hx509_collector *c,=20
+parse_certificate(hx509_context context, const char *fn,
+		  struct hx509_collector *c,
 		  const hx509_pem_header *headers,
-		  const void *data, size_t len)
+		  const void *data, size_t len,
+		  const AlgorithmIdentifier *ai)
 {
     hx509_cert cert;
     int ret;
@@ -112,7 +112,7 @@
 	EVP_CipherInit_ex(&ctx, c, NULL, key, ivdata, 0);
 	EVP_Cipher(&ctx, clear.data, cipher, len);
 	EVP_CIPHER_CTX_cleanup(&ctx);
-    }=09
+    }
=20
     ret =3D _hx509_collector_private_key_add(context,
 					   collector,
@@ -130,10 +130,40 @@
 }
=20
 static int
-parse_rsa_private_key(hx509_context context, const char *fn,
-		      struct hx509_collector *c,=20
+parse_pkcs8_private_key(hx509_context context, const char *fn,
+			struct hx509_collector *c,
+			const hx509_pem_header *headers,
+			const void *data, size_t length,
+			const AlgorithmIdentifier *ai)
+{
+    PKCS8PrivateKeyInfo ki;
+    heim_octet_string keydata;
+
+    int ret;
+
+    ret =3D decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL);
+    if (ret)
+	return ret;
+
+    keydata.data =3D rk_UNCONST(data);
+    keydata.length =3D length;
+
+    ret =3D _hx509_collector_private_key_add(context,
+					   c,
+					   &ki.privateKeyAlgorithm,
+					   NULL,
+					   &ki.privateKey,
+					   &keydata);
+    free_PKCS8PrivateKeyInfo(&ki);
+    return ret;
+}
+
+static int
+parse_pem_private_key(hx509_context context, const char *fn,
+		      struct hx509_collector *c,
 		      const hx509_pem_header *headers,
-		      const void *data, size_t len)
+		      const void *data, size_t len,
+		      const AlgorithmIdentifier *ai)
 {
     int ret =3D 0;
     const char *enc;
@@ -147,7 +177,8 @@
 	const EVP_CIPHER *cipher;
 	const struct _hx509_password *pw;
 	hx509_lock lock;
-	int i, decrypted =3D 0;
+	int decrypted =3D 0;
+	size_t i;
=20
 	lock =3D _hx509_collector_get_lock(c);
 	if (lock =3D=3D NULL) {
@@ -159,7 +190,7 @@
=20
 	if (strcmp(enc, "4,ENCRYPTED") !=3D 0) {
 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
-				   "RSA key encrypted in unknown method %s "
+				   "Private key encrypted in unknown method %s "
 				   "in file",
 				   enc, fn);
 	    hx509_clear_error_string(context);
@@ -169,7 +200,7 @@
 	dek =3D hx509_pem_find_header(headers, "DEK-Info");
 	if (dek =3D=3D NULL) {
 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
-				   "Encrypted RSA missing DEK-Info");
+				   "Encrypted private key missing DEK-Info");
 	    return HX509_PARSING_KEY_FAILED;
 	}
=20
@@ -201,7 +232,7 @@
 	if (cipher =3D=3D NULL) {
 	    free(ivdata);
 	    hx509_set_error_string(context, 0, HX509_ALG_NOT_SUPP,
-				   "RSA key encrypted with "
+				   "Private key encrypted with "
 				   "unsupported cipher: %s",
 				   type);
 	    free(type);
@@ -218,10 +249,11 @@
 	if (ssize < 0 || ssize < PKCS5_SALT_LEN || ssize < EVP_CIPHER_iv_length(c=
ipher)) {
 	    free(ivdata);
 	    hx509_set_error_string(context, 0, HX509_PARSING_KEY_FAILED,
-				   "Salt have wrong length in RSA key file");
+				   "Salt have wrong length in "
+				   "private key file");
 	    return HX509_PARSING_KEY_FAILED;
 	}
-=09
+
 	pw =3D _hx509_lock_get_passwords(lock);
 	if (pw !=3D NULL) {
 	    const void *password;
@@ -230,10 +262,9 @@
 	    for (i =3D 0; i < pw->len; i++) {
 		password =3D pw->val[i];
 		passwordlen =3D strlen(password);
-	=09
-		ret =3D try_decrypt(context, c, hx509_signature_rsa(),
-				  cipher, ivdata, password, passwordlen,
-				  data, len);
+
+		ret =3D try_decrypt(context, c, ai, cipher, ivdata,
+				  password, passwordlen, data, len);
 		if (ret =3D=3D 0) {
 		    decrypted =3D 1;
 		    break;
@@ -253,9 +284,8 @@
=20
 	    ret =3D hx509_lock_prompt(lock, &prompt);
 	    if (ret =3D=3D 0)
-		ret =3D try_decrypt(context, c, hx509_signature_rsa(),
-				  cipher, ivdata, password, strlen(password),
-				  data, len);
+		ret =3D try_decrypt(context, c, ai, cipher, ivdata, password,
+				  strlen(password), data, len);
 	    /* XXX add password to lock password collection ? */
 	    memset(password, 0, sizeof(password));
 	}
@@ -267,12 +297,8 @@
 	keydata.data =3D rk_UNCONST(data);
 	keydata.length =3D len;
=20
-	ret =3D _hx509_collector_private_key_add(context,
-					       c,
-					       hx509_signature_rsa(),
-					       NULL,
-					       &keydata,
-					       NULL);
+	ret =3D _hx509_collector_private_key_add(context, c, ai, NULL,
+					       &keydata, NULL);
     }
=20
     return ret;
@@ -281,11 +307,15 @@
=20
 struct pem_formats {
     const char *name;
-    int (*func)(hx509_context, const char *, struct hx509_collector *,=20
-		const hx509_pem_header *, const void *, size_t);
+    int (*func)(hx509_context, const char *, struct hx509_collector *,
+		const hx509_pem_header *, const void *, size_t,
+		const AlgorithmIdentifier *);
+    const AlgorithmIdentifier *(*ai)(void);
 } formats[] =3D {
-    { "CERTIFICATE", parse_certificate },
-    { "RSA PRIVATE KEY", parse_rsa_private_key }
+    { "CERTIFICATE", parse_certificate, NULL },
+    { "PRIVATE KEY", parse_pkcs8_private_key, NULL },
+    { "RSA PRIVATE KEY", parse_pem_private_key, hx509_signature_rsa },
+    { "EC PRIVATE KEY", parse_pem_private_key, hx509_signature_ecPublicKey=
 }
 };
=20
=20
@@ -300,14 +330,24 @@
 	 const void *data, size_t len, void *ctx)
 {
     struct pem_ctx *pem_ctx =3D (struct pem_ctx*)ctx;
-    int ret =3D 0, j;
+    int ret =3D 0;
+    size_t j;
=20
     for (j =3D 0; j < sizeof(formats)/sizeof(formats[0]); j++) {
 	const char *q =3D formats[j].name;
 	if (strcasecmp(type, q) =3D=3D 0) {
-	    ret =3D (*formats[j].func)(context, NULL, pem_ctx->c,  header, data, =
len);
-	    if (ret =3D=3D 0)
-		break;
+	    const AlgorithmIdentifier *ai =3D NULL;
+	    if (formats[j].ai !=3D NULL)
+		ai =3D (*formats[j].ai)();
+
+	    ret =3D (*formats[j].func)(context, NULL, pem_ctx->c,
+				     header, data, len, ai);
+	    if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL)) {
+		hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+				       "Failed parseing PEM format %s", type);
+		return ret;
+	    }
+	    break;
 	}
     }
     if (j =3D=3D sizeof(formats)/sizeof(formats[0])) {
@@ -316,8 +356,6 @@
 			       "Found no matching PEM format for %s", type);
 	return ret;
     }
-    if (ret && (pem_ctx->flags & HX509_CERTS_UNPROTECT_ALL))
-	return ret;
     return 0;
 }
=20
@@ -327,11 +365,11 @@
=20
 static int
 file_init_common(hx509_context context,
-		 hx509_certs certs, void **data, int flags,=20
+		 hx509_certs certs, void **data, int flags,
 		 const char *residue, hx509_lock lock, outformat format)
 {
     char *p, *pnext;
-    struct ks_file *f =3D NULL;
+    struct ks_file *ksf =3D NULL;
     hx509_private_key *keys =3D NULL;
     int ret;
     struct pem_ctx pem_ctx;
@@ -344,31 +382,31 @@
     if (lock =3D=3D NULL)
 	lock =3D _hx509_empty_lock;
=20
-    f =3D calloc(1, sizeof(*f));
-    if (f =3D=3D NULL) {
+    ksf =3D calloc(1, sizeof(*ksf));
+    if (ksf =3D=3D NULL) {
 	hx509_clear_error_string(context);
 	return ENOMEM;
     }
-    f->format =3D format;
+    ksf->format =3D format;
=20
-    f->fn =3D strdup(residue);
-    if (f->fn =3D=3D NULL) {
+    ksf->fn =3D strdup(residue);
+    if (ksf->fn =3D=3D NULL) {
 	hx509_clear_error_string(context);
 	ret =3D ENOMEM;
 	goto out;
     }
=20
-    /*=20
+    /*
      * XXX this is broken, the function should parse the file before
      * overwriting it
      */
=20
     if (flags & HX509_CERTS_CREATE) {
-	ret =3D hx509_certs_init(context, "MEMORY:ks-file-create",=20
-			       0, lock, &f->certs);
+	ret =3D hx509_certs_init(context, "MEMORY:ks-file-create",
+			       0, lock, &ksf->certs);
 	if (ret)
 	    goto out;
-	*data =3D f;
+	*data =3D ksf;
 	return 0;
     }
=20
@@ -376,49 +414,56 @@
     if (ret)
 	goto out;
=20
-    for (p =3D f->fn; p !=3D NULL; p =3D pnext) {
+    for (p =3D ksf->fn; p !=3D NULL; p =3D pnext) {
 	FILE *f;
=20
 	pnext =3D strchr(p, ',');
 	if (pnext)
 	    *pnext++ =3D '\0';
-=09
+
=20
 	if ((f =3D fopen(p, "r")) =3D=3D NULL) {
 	    ret =3D ENOENT;
-	    hx509_set_error_string(context, 0, ret,=20
-				   "Failed to open PEM file \"%s\": %s",=20
+	    hx509_set_error_string(context, 0, ret,
+				   "Failed to open PEM file \"%s\": %s",
 				   p, strerror(errno));
 	    goto out;
 	}
+	rk_cloexec_file(f);
=20
 	ret =3D hx509_pem_read(context, f, pem_func, &pem_ctx);
-	fclose(f);		    =20
+	fclose(f);
 	if (ret !=3D 0 && ret !=3D HX509_PARSING_KEY_FAILED)
 	    goto out;
 	else if (ret =3D=3D HX509_PARSING_KEY_FAILED) {
 	    size_t length;
 	    void *ptr;
-	    int i;
+	    size_t i;
=20
-	    ret =3D _hx509_map_file(p, &ptr, &length, NULL);
+	    ret =3D rk_undumpdata(p, &ptr, &length);
 	    if (ret) {
 		hx509_clear_error_string(context);
 		goto out;
 	    }
=20
 	    for (i =3D 0; i < sizeof(formats)/sizeof(formats[0]); i++) {
-		ret =3D (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length);
+		const AlgorithmIdentifier *ai =3D NULL;
+		if (formats[i].ai !=3D NULL)
+		    ai =3D (*formats[i].ai)();
+
+		ret =3D (*formats[i].func)(context, p, pem_ctx.c, NULL, ptr, length, ai);
 		if (ret =3D=3D 0)
 		    break;
 	    }
-	    _hx509_unmap_file(ptr, length);
-	    if (ret)
+	    rk_xfree(ptr);
+	    if (ret) {
+		hx509_clear_error_string(context);
 		goto out;
+	    }
 	}
     }
=20
-    ret =3D _hx509_collector_collect_certs(context, pem_ctx.c, &f->certs);
+    ret =3D _hx509_collector_collect_certs(context, pem_ctx.c, &ksf->certs=
);
     if (ret)
 	goto out;
=20
@@ -427,17 +472,17 @@
 	int i;
=20
 	for (i =3D 0; keys[i]; i++)
-	    _hx509_certs_keys_add(context, f->certs, keys[i]);
+	    _hx509_certs_keys_add(context, ksf->certs, keys[i]);
 	_hx509_certs_keys_free(context, keys);
     }
=20
 out:
     if (ret =3D=3D 0)
-	*data =3D f;
+	*data =3D ksf;
     else {
-	if (f->fn)
-	    free(f->fn);
-	free(f);
+	if (ksf->fn)
+	    free(ksf->fn);
+	free(ksf);
     }
     if (pem_ctx.c)
 	_hx509_collector_free(pem_ctx.c);
@@ -447,7 +492,7 @@
=20
 static int
 file_init_pem(hx509_context context,
-	      hx509_certs certs, void **data, int flags,=20
+	      hx509_certs certs, void **data, int flags,
 	      const char *residue, hx509_lock lock)
 {
     return file_init_common(context, certs, data, flags, residue, lock, US=
E_PEM);
@@ -455,7 +500,7 @@
=20
 static int
 file_init_der(hx509_context context,
-	      hx509_certs certs, void **data, int flags,=20
+	      hx509_certs certs, void **data, int flags,
 	      const char *residue, hx509_lock lock)
 {
     return file_init_common(context, certs, data, flags, residue, lock, US=
E_DER);
@@ -464,10 +509,10 @@
 static int
 file_free(hx509_certs certs, void *data)
 {
-    struct ks_file *f =3D data;
-    hx509_certs_free(&f->certs);
-    free(f->fn);
-    free(f);
+    struct ks_file *ksf =3D data;
+    hx509_certs_free(&ksf->certs);
+    free(ksf->fn);
+    free(ksf);
     return 0;
 }
=20
@@ -486,19 +531,20 @@
     ret =3D hx509_cert_binary(context, c, &data);
     if (ret)
 	return ret;
-   =20
+
     switch (sc->format) {
     case USE_DER:
 	fwrite(data.data, data.length, 1, sc->f);
 	free(data.data);
 	break;
     case USE_PEM:
-	hx509_pem_write(context, "CERTIFICATE", NULL, sc->f,=20
+	hx509_pem_write(context, "CERTIFICATE", NULL, sc->f,
 			data.data, data.length);
 	free(data.data);
 	if (_hx509_cert_private_key_exportable(c)) {
 	    hx509_private_key key =3D _hx509_cert_private_key(c);
-	    ret =3D _hx509_private_key_export(context, key, &data);
+	    ret =3D _hx509_private_key_export(context, key,
+					    HX509_KEY_FORMAT_DER, &data);
 	    if (ret)
 		break;
 	    hx509_pem_write(context, _hx509_private_pem_name(key), NULL, sc->f,
@@ -512,47 +558,48 @@
 }
=20
 static int
-file_store(hx509_context context,=20
+file_store(hx509_context context,
 	   hx509_certs certs, void *data, int flags, hx509_lock lock)
 {
-    struct ks_file *f =3D data;
+    struct ks_file *ksf =3D data;
     struct store_ctx sc;
     int ret;
=20
-    sc.f =3D fopen(f->fn, "w");
+    sc.f =3D fopen(ksf->fn, "w");
     if (sc.f =3D=3D NULL) {
 	hx509_set_error_string(context, 0, ENOENT,
 			       "Failed to open file %s for writing");
 	return ENOENT;
     }
-    sc.format =3D f->format;
+    rk_cloexec_file(sc.f);
+    sc.format =3D ksf->format;
=20
-    ret =3D hx509_certs_iter(context, f->certs, store_func, &sc);
+    ret =3D hx509_certs_iter_f(context, ksf->certs, store_func, &sc);
     fclose(sc.f);
     return ret;
 }
=20
-static int=20
+static int
 file_add(hx509_context context, hx509_certs certs, void *data, hx509_cert =
c)
 {
-    struct ks_file *f =3D data;
-    return hx509_certs_add(context, f->certs, c);
+    struct ks_file *ksf =3D data;
+    return hx509_certs_add(context, ksf->certs, c);
 }
=20
-static int=20
+static int
 file_iter_start(hx509_context context,
 		hx509_certs certs, void *data, void **cursor)
 {
-    struct ks_file *f =3D data;
-    return hx509_certs_start_seq(context, f->certs, cursor);
+    struct ks_file *ksf =3D data;
+    return hx509_certs_start_seq(context, ksf->certs, cursor);
 }
=20
 static int
 file_iter(hx509_context context,
 	  hx509_certs certs, void *data, void *iter, hx509_cert *cert)
 {
-    struct ks_file *f =3D data;
-    return hx509_certs_next_cert(context, f->certs, iter, cert);
+    struct ks_file *ksf =3D data;
+    return hx509_certs_next_cert(context, ksf->certs, iter, cert);
 }
=20
 static int
@@ -561,8 +608,8 @@
 	      void *data,
 	      void *cursor)
 {
-    struct ks_file *f =3D data;
-    return hx509_certs_end_seq(context, f->certs, cursor);
+    struct ks_file *ksf =3D data;
+    return hx509_certs_end_seq(context, ksf->certs, cursor);
 }
=20
 static int
@@ -571,8 +618,8 @@
 	     void *data,
 	     hx509_private_key **keys)
 {
-    struct ks_file *f =3D data;
-    return _hx509_certs_keys_get(context, f->certs, keys);
+    struct ks_file *ksf =3D data;
+    return _hx509_certs_keys_get(context, ksf->certs, keys);
 }
=20
 static int
@@ -581,8 +628,8 @@
 	     void *data,
 	     hx509_private_key key)
 {
-    struct ks_file *f =3D data;
-    return _hx509_certs_keys_add(context, f->certs, key);
+    struct ks_file *ksf =3D data;
+    return _hx509_certs_keys_add(context, ksf->certs, key);
 }
=20
 static struct hx509_keyset_ops keyset_file =3D {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ks_keych=
ain.c
--- a/head/crypto/heimdal/lib/hx509/ks_keychain.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/hx509/ks_keychain.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: ks_keychain.c 22084 2007-11-16 20:12:30Z lha $");
=20
 #ifdef HAVE_FRAMEWORK_SECURITY
=20
@@ -44,13 +43,14 @@
 OSStatus SecKeyGetCredentials(SecKeyRef, CSSM_ACL_AUTHORIZATION_TAG,
 			      int, const CSSM_ACCESS_CREDENTIALS **);
 #define kSecCredentialTypeDefault 0
+#define CSSM_SIZE uint32_t
 #endif
=20
=20
 static int
 getAttribute(SecKeychainItemRef itemRef, SecItemAttr item,
 	     SecKeychainAttributeList **attrs)
-{	    =20
+{
     SecKeychainAttributeInfo attrInfo;
     UInt32 attrFormat =3D 0;
     OSStatus ret;
@@ -60,7 +60,7 @@
     attrInfo.count =3D 1;
     attrInfo.tag =3D &item;
     attrInfo.format =3D &attrFormat;
- =20
+
     ret =3D SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
 					       attrs, NULL, NULL);
     if (ret)
@@ -101,7 +101,7 @@
=20
=20
 static int
-kc_rsa_private_encrypt(int flen,=20
+kc_rsa_private_encrypt(int flen,
 		       const unsigned char *from,
 		       unsigned char *to,
 		       RSA *rsa,
@@ -119,6 +119,8 @@
     CSSM_DATA sig, in;
     int fret =3D 0;
=20
+    if (padding !=3D RSA_PKCS1_PADDING)
+	return -1;
=20
     cret =3D SecKeyGetCSSMKey(privKeyRef, &cssmKey);
     if(cret) abort();
@@ -136,10 +138,10 @@
=20
     in.Data =3D (uint8 *)from;
     in.Length =3D flen;
-=09
+
     sig.Data =3D (uint8 *)to;
     sig.Length =3D kc->keysize;
-=09
+
     cret =3D CSSM_SignData(sigHandle, &in, 1, CSSM_ALGID_NONE, &sig);
     if(cret) {
 	/* cssmErrorString(cret); */
@@ -157,10 +159,65 @@
 kc_rsa_private_decrypt(int flen, const unsigned char *from, unsigned char =
*to,
 		       RSA * rsa, int padding)
 {
-    return -1;
+    struct kc_rsa *kc =3D RSA_get_app_data(rsa);
+
+    CSSM_RETURN cret;
+    OSStatus ret;
+    const CSSM_ACCESS_CREDENTIALS *creds;
+    SecKeyRef privKeyRef =3D (SecKeyRef)kc->item;
+    CSSM_CSP_HANDLE cspHandle;
+    const CSSM_KEY *cssmKey;
+    CSSM_CC_HANDLE handle =3D 0;
+    CSSM_DATA out, in, rem;
+    int fret =3D 0;
+    CSSM_SIZE outlen =3D 0;
+    char remdata[1024];
+
+    if (padding !=3D RSA_PKCS1_PADDING)
+	return -1;
+
+    cret =3D SecKeyGetCSSMKey(privKeyRef, &cssmKey);
+    if(cret) abort();
+
+    cret =3D SecKeyGetCSPHandle(privKeyRef, &cspHandle);
+    if(cret) abort();
+
+    ret =3D SecKeyGetCredentials(privKeyRef, CSSM_ACL_AUTHORIZATION_DECRYP=
T,
+			       kSecCredentialTypeDefault, &creds);
+    if(ret) abort();
+
+
+    ret =3D CSSM_CSP_CreateAsymmetricContext (cspHandle,
+					    CSSM_ALGID_RSA,
+					    creds,
+					    cssmKey,
+					    CSSM_PADDING_PKCS1,
+					    &handle);
+    if(ret) abort();
+
+    in.Data =3D (uint8 *)from;
+    in.Length =3D flen;
+
+    out.Data =3D (uint8 *)to;
+    out.Length =3D kc->keysize;
+
+    rem.Data =3D (uint8 *)remdata;
+    rem.Length =3D sizeof(remdata);
+
+    cret =3D CSSM_DecryptData(handle, &in, 1, &out, 1, &outlen, &rem);
+    if(cret) {
+	/* cssmErrorString(cret); */
+	fret =3D -1;
+    } else
+	fret =3D out.Length;
+
+    if(handle)
+	CSSM_DeleteContext(handle);
+
+    return fret;
 }
=20
-static int=20
+static int
 kc_rsa_init(RSA *rsa)
 {
     return 1;
@@ -202,7 +259,7 @@
     RSA *rsa;
     int ret;
=20
-    ret =3D _hx509_private_key_init(&key, NULL, NULL);
+    ret =3D hx509_private_key_init(&key, NULL, NULL);
     if (ret)
 	return ret;
=20
@@ -245,7 +302,7 @@
     if (ret !=3D 1)
 	_hx509_abort("RSA_set_app_data");
=20
-    _hx509_private_key_assign_rsa(key, rsa);
+    hx509_private_key_assign_rsa(key, rsa);
     _hx509_cert_assign_key(cert, key);
=20
     return 0;
@@ -281,12 +338,12 @@
=20
 	    ret =3D SecKeychainOpen(residue + 5, &ctx->keychain);
 	    if (ret !=3D noErr) {
-		hx509_set_error_string(context, 0, ENOENT,=20
+		hx509_set_error_string(context, 0, ENOENT,
 				       "Failed to open %s", residue);
 		return ENOENT;
 	    }
 	} else {
-	    hx509_set_error_string(context, 0, ENOENT,=20
+	    hx509_set_error_string(context, 0, ENOENT,
 				   "Unknown subtype %s", residue);
 	    return ENOENT;
 	}
@@ -321,7 +378,7 @@
     SecKeychainSearchRef searchRef;
 };
=20
-static int=20
+static int
 keychain_iter_start(hx509_context context,
 		    hx509_certs certs, void *data, void **cursor)
 {
@@ -339,7 +396,7 @@
 	int ret;
 	int i;
=20
-	ret =3D hx509_certs_init(context, "MEMORY:ks-file-create",=20
+	ret =3D hx509_certs_init(context, "MEMORY:ks-file-create",
 			       0, NULL, &iter->certs);
 	if (ret) {
 	    free(iter);
@@ -350,12 +407,12 @@
 	if (ret !=3D 0) {
 	    hx509_certs_free(&iter->certs);
 	    free(iter);
-	    hx509_set_error_string(context, 0, ENOMEM,=20
+	    hx509_set_error_string(context, 0, ENOMEM,
 				   "Can't get trust anchors from Keychain");
 	    return ENOMEM;
 	}
 	for (i =3D 0; i < CFArrayGetCount(anchors); i++) {
-	    SecCertificateRef cr;=20
+	    SecCertificateRef cr;
 	    hx509_cert cert;
 	    CSSM_DATA cssm;
=20
@@ -390,7 +447,7 @@
 						    &iter->searchRef);
 	if (ret) {
 	    free(iter);
-	    hx509_set_error_string(context, 0, ret,=20
+	    hx509_set_error_string(context, 0, ret,
 				   "Failed to start search for attributes");
 	    return ENOMEM;
 	}
@@ -428,7 +485,7 @@
 	return 0;
     else if (ret !=3D 0)
 	return EINVAL;
-=09
+
     /*
      * Pick out certificate and matching "keyid"
      */
@@ -438,7 +495,7 @@
     attrInfo.count =3D 1;
     attrInfo.tag =3D item;
     attrInfo.format =3D attrFormat;
- =20
+
     ret =3D SecKeychainItemCopyAttributesAndData(itemRef, &attrInfo, NULL,
 					       &attrs, &len, &ptr);
     if (ret)
@@ -448,7 +505,7 @@
     if (ret)
 	goto out;
=20
-    /*=20
+    /*
      * Find related private key if there is one by looking at
      * kSecPublicKeyHashItemAttr =3D=3D kSecKeyLabel
      */
@@ -460,7 +517,7 @@
 	attrKeyid.tag =3D kSecKeyLabel;
 	attrKeyid.length =3D attrs->attr[0].length;
 	attrKeyid.data =3D attrs->attr[0].data;
-=09
+
 	attrList.count =3D 1;
 	attrList.attr =3D &attrKeyid;
=20
@@ -504,8 +561,7 @@
     struct iter *iter =3D cursor;
=20
     if (iter->certs) {
-	int ret;
-	ret =3D hx509_certs_end_seq(context, iter->certs, iter->cursor);
+	hx509_certs_end_seq(context, iter->certs, iter->cursor);
 	hx509_certs_free(&iter->certs);
     } else {
 	CFRelease(iter->searchRef);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ks_mem.c
--- a/head/crypto/heimdal/lib/hx509/ks_mem.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ks_mem.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2005 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("Id$");
=20
 /*
  * Should use two hash/tree certificates intead of a array.  Criteria
@@ -74,12 +73,12 @@
 {
     struct mem_data *mem =3D data;
     unsigned long i;
-   =20
+
     for (i =3D 0; i < mem->certs.len; i++)
 	hx509_cert_free(mem->certs.val[i]);
     free(mem->certs.val);
     for (i =3D 0; mem->keys && mem->keys[i]; i++)
-	_hx509_private_key_free(&mem->keys[i]);
+	hx509_private_key_free(&mem->keys[i]);
     free(mem->keys);
     free(mem->name);
     free(mem);
@@ -87,13 +86,13 @@
     return 0;
 }
=20
-static int=20
+static int
 mem_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
 {
     struct mem_data *mem =3D data;
     hx509_cert *val;
=20
-    val =3D realloc(mem->certs.val,=20
+    val =3D realloc(mem->certs.val,
 		  (mem->certs.len + 1) * sizeof(mem->certs.val[0]));
     if (val =3D=3D NULL)
 	return ENOMEM;
@@ -105,7 +104,7 @@
     return 0;
 }
=20
-static int=20
+static int
 mem_iter_start(hx509_context context,
 	       hx509_certs certs,
 	       void *data,
@@ -125,7 +124,7 @@
 static int
 mem_iter(hx509_context contexst,
 	 hx509_certs certs,
-	 void *data,=20
+	 void *data,
 	 void *cursor,
 	 hx509_cert *cert)
 {
@@ -168,11 +167,11 @@
 	(*keys)[i] =3D _hx509_private_key_ref(mem->keys[i]);
 	if ((*keys)[i] =3D=3D NULL) {
 	    while (--i >=3D 0)
-		_hx509_private_key_free(&(*keys)[i]);
+		hx509_private_key_free(&(*keys)[i]);
 	    hx509_set_error_string(context, 0, ENOMEM, "out of memory");
 	    return ENOMEM;
 	}
-    }	   =20
+    }
     (*keys)[i] =3D NULL;
     return 0;
 }
@@ -195,8 +194,8 @@
 	return ENOMEM;
     }
     mem->keys =3D ptr;
-    mem->keys[i++] =3D _hx509_private_key_ref(key);
-    mem->keys[i++] =3D NULL;
+    mem->keys[i] =3D _hx509_private_key_ref(key);
+    mem->keys[i + 1] =3D NULL;
     return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ks_null.c
--- a/head/crypto/heimdal/lib/hx509/ks_null.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ks_null.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2005 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: ks_null.c 20901 2007-06-04 23:14:08Z lha $");
=20
=20
 static int
@@ -51,7 +50,7 @@
     return 0;
 }
=20
-static int=20
+static int
 null_iter_start(hx509_context context,
 		hx509_certs certs, void *data, void **cursor)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ks_p11.c
--- a/head/crypto/heimdal/lib/hx509/ks_p11.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ks_p11.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2004 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: ks_p11.c 22071 2007-11-14 20:04:50Z lha $");
 #ifdef HAVE_DLFCN_H
 #include <dlfcn.h>
 #endif
@@ -65,7 +64,7 @@
     void *dl_handle;
     CK_FUNCTION_LIST_PTR funcs;
     CK_ULONG num_slots;
-    unsigned int refcount;
+    unsigned int ref;
     struct p11_slot *slot;
 };
=20
@@ -83,7 +82,7 @@
=20
 static int p11_list_keys(hx509_context,
 			 struct p11_module *,
-			 struct p11_slot *,=20
+			 struct p11_slot *,
 			 CK_SESSION_HANDLE,
 			 hx509_lock,
 			 hx509_certs *);
@@ -121,7 +120,7 @@
=20
=20
 static int
-p11_rsa_private_encrypt(int flen,=20
+p11_rsa_private_encrypt(int flen,
 			const unsigned char *from,
 			unsigned char *to,
 			RSA *rsa,
@@ -152,8 +151,8 @@
 	return -1;
     }
=20
-    ret =3D P11FUNC(p11rsa->p, Sign,=20
-		  (session, (CK_BYTE *)from, flen, to, &ck_sigsize));
+    ret =3D P11FUNC(p11rsa->p, Sign,
+		  (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
     p11_put_session(p11rsa->p, p11rsa->slot, session);
     if (ret !=3D CKR_OK)
 	return -1;
@@ -190,8 +189,8 @@
 	return -1;
     }
=20
-    ret =3D P11FUNC(p11rsa->p, Decrypt,=20
-		  (session, (CK_BYTE *)from, flen, to, &ck_sigsize));
+    ret =3D P11FUNC(p11rsa->p, Decrypt,
+		  (session, (CK_BYTE *)(intptr_t)from, flen, to, &ck_sigsize));
     p11_put_session(p11rsa->p, p11rsa->slot, session);
     if (ret !=3D CKR_OK)
 	return -1;
@@ -199,7 +198,7 @@
     return ck_sigsize;
 }
=20
-static int=20
+static int
 p11_rsa_init(RSA *rsa)
 {
     return 1;
@@ -299,7 +298,7 @@
 }
=20
 static int
-p11_init_slot(hx509_context context,=20
+p11_init_slot(hx509_context context,
 	      struct p11_module *p,
 	      hx509_lock lock,
 	      CK_SLOT_ID id,
@@ -309,7 +308,8 @@
     CK_SESSION_HANDLE session;
     CK_SLOT_INFO slot_info;
     CK_TOKEN_INFO token_info;
-    int ret, i;
+    size_t i;
+    int ret;
=20
     slot->certs =3D NULL;
     slot->id =3D id;
@@ -331,7 +331,7 @@
     }
=20
     asprintf(&slot->name, "%.*s",
-	     i, slot_info.slotDescription);
+	     (int)i, slot_info.slotDescription);
=20
     if ((slot_info.flags & CKF_TOKEN_PRESENT) =3D=3D 0)
 	return 0;
@@ -375,14 +375,14 @@
=20
     if (slot->flags & P11_SESSION_IN_USE)
 	_hx509_abort("slot already in session");
-   =20
+
     if (slot->flags & P11_SESSION) {
 	slot->flags |=3D P11_SESSION_IN_USE;
 	*psession =3D slot->session;
 	return 0;
     }
=20
-    ret =3D P11FUNC(p, OpenSession, (slot->id,=20
+    ret =3D P11FUNC(p, OpenSession, (slot->id,
 				   CKF_SERIAL_SESSION,
 				   NULL,
 				   NULL,
@@ -395,10 +395,10 @@
 				   (int)slot->id, ret);
 	return HX509_PKCS11_OPEN_SESSION;
     }
-   =20
+
     slot->flags |=3D P11_SESSION;
-   =20
-    /*=20
+
+    /*
      * If we have have to login, and haven't tried before and have a
      * prompter or known to work pin code.
      *
@@ -418,8 +418,6 @@
 	char pin[20];
 	char *str;
=20
-	slot->flags |=3D P11_LOGIN_DONE;
-
 	if (slot->pin =3D=3D NULL) {
=20
 	    memset(&prompt, 0, sizeof(prompt));
@@ -429,7 +427,7 @@
 	    prompt.type =3D HX509_PROMPT_TYPE_PASSWORD;
 	    prompt.reply.data =3D pin;
 	    prompt.reply.length =3D sizeof(pin);
-	   =20
+
 	    ret =3D hx509_lock_prompt(lock, &prompt);
 	    if (ret) {
 		free(str);
@@ -453,16 +451,16 @@
 				       "Failed to login on slot id %d "
 				       "with error: 0x%08x",
 				       (int)slot->id, ret);
-	    p11_put_session(p, slot, slot->session);
 	    return HX509_PKCS11_LOGIN;
-	}
+	} else
+	    slot->flags |=3D P11_LOGIN_DONE;
+
 	if (slot->pin =3D=3D NULL) {
 	    slot->pin =3D strdup(pin);
 	    if (slot->pin =3D=3D NULL) {
 		if (context)
 		    hx509_set_error_string(context, 0, ENOMEM,
 					   "out of memory");
-		p11_put_session(p, slot, slot->session);
 		return ENOMEM;
 	    }
 	}
@@ -478,7 +476,7 @@
=20
 static int
 p11_put_session(struct p11_module *p,
-		struct p11_slot *slot,=20
+		struct p11_slot *slot,
 		CK_SESSION_HANDLE session)
 {
     if ((slot->flags & P11_SESSION_IN_USE) =3D=3D 0)
@@ -502,7 +500,7 @@
 {
     CK_OBJECT_HANDLE object;
     CK_ULONG object_count;
-    int ret, i;
+    int ret, ret2, i;
=20
     ret =3D P11FUNC(p, FindObjectsInit, (session, search_data, num_search_=
data));
     if (ret !=3D CKR_OK) {
@@ -515,11 +513,11 @@
 	}
 	if (object_count =3D=3D 0)
 	    break;
-=09
+
 	for (i =3D 0; i < num_query; i++)
 	    query[i].pValue =3D NULL;
=20
-	ret =3D P11FUNC(p, GetAttributeValue,=20
+	ret =3D P11FUNC(p, GetAttributeValue,
 		      (session, object, query, num_query));
 	if (ret !=3D CKR_OK) {
 	    return -1;
@@ -537,7 +535,7 @@
 	    ret =3D -1;
 	    goto out;
 	}
-=09
+
 	ret =3D (*func)(context, p, slot, session, object, ptr, query, num_query);
 	if (ret)
 	    goto out;
@@ -556,20 +554,19 @@
 	query[i].pValue =3D NULL;
     }
=20
-    ret =3D P11FUNC(p, FindObjectsFinal, (session));
-    if (ret !=3D CKR_OK) {
-	return -2;
+    ret2 =3D P11FUNC(p, FindObjectsFinal, (session));
+    if (ret2 !=3D CKR_OK) {
+	return ret2;
     }
=20
+    return ret;
+}
=20
-    return 0;
-}
-	=09
 static BIGNUM *
 getattr_bn(struct p11_module *p,
 	   struct p11_slot *slot,
 	   CK_SESSION_HANDLE session,
-	   CK_OBJECT_HANDLE object,=20
+	   CK_OBJECT_HANDLE object,
 	   unsigned int type)
 {
     CK_ATTRIBUTE query;
@@ -580,14 +577,14 @@
     query.pValue =3D NULL;
     query.ulValueLen =3D 0;
=20
-    ret =3D P11FUNC(p, GetAttributeValue,=20
+    ret =3D P11FUNC(p, GetAttributeValue,
 		  (session, object, &query, 1));
     if (ret !=3D CKR_OK)
 	return NULL;
=20
     query.pValue =3D malloc(query.ulValueLen);
=20
-    ret =3D P11FUNC(p, GetAttributeValue,=20
+    ret =3D P11FUNC(p, GetAttributeValue,
 		  (session, object, &query, 1));
     if (ret !=3D CKR_OK) {
 	free(query.pValue);
@@ -616,7 +613,7 @@
     localKeyId.data =3D query[0].pValue;
     localKeyId.length =3D query[0].ulValueLen;
=20
-    ret =3D _hx509_private_key_init(&key, NULL, NULL);
+    ret =3D hx509_private_key_init(&key, NULL, NULL);
     if (ret)
 	return ret;
=20
@@ -624,7 +621,7 @@
     if (rsa =3D=3D NULL)
 	_hx509_abort("out of memory");
=20
-    /*=20
+    /*
      * The exponent and modulus should always be present according to
      * the pkcs11 specification, but some smartcards leaves it out,
      * let ignore any failure to fetch it.
@@ -639,17 +636,19 @@
     p11rsa->p =3D p;
     p11rsa->slot =3D slot;
     p11rsa->private_key =3D object;
-   =20
-    p->refcount++;
-    if (p->refcount =3D=3D 0)
-	_hx509_abort("pkcs11 refcount to high");
+
+    if (p->ref =3D=3D 0)
+	_hx509_abort("pkcs11 ref =3D=3D 0 on alloc");
+    p->ref++;
+    if (p->ref =3D=3D UINT_MAX)
+	_hx509_abort("pkcs11 ref =3D=3D UINT_MAX on alloc");
=20
     RSA_set_method(rsa, &p11_rsa_pkcs1_method);
     ret =3D RSA_set_app_data(rsa, p11rsa);
     if (ret !=3D 1)
 	_hx509_abort("RSA_set_app_data");
=20
-    _hx509_private_key_assign_rsa(key, rsa);
+    hx509_private_key_assign_rsa(key, rsa);
=20
     ret =3D _hx509_collector_private_key_add(context,
 					   collector,
@@ -659,7 +658,7 @@
 					   &localKeyId);
=20
     if (ret) {
-	_hx509_private_key_free(&key);
+	hx509_private_key_free(&key);
 	return ret;
     }
     return 0;
@@ -674,7 +673,7 @@
=20
=20
 static int
-collect_cert(hx509_context context,=20
+collect_cert(hx509_context context,
 	     struct p11_module *p, struct p11_slot *slot,
 	     CK_SESSION_HANDLE session,
 	     CK_OBJECT_HANDLE object,
@@ -685,31 +684,33 @@
     int ret;
=20
     if ((CK_LONG)query[0].ulValueLen =3D=3D -1 ||
-	(CK_LONG)query[1].ulValueLen =3D=3D -1)=20
+	(CK_LONG)query[1].ulValueLen =3D=3D -1)
     {
 	return 0;
     }
=20
-    ret =3D hx509_cert_init_data(context, query[1].pValue,=20
+    ret =3D hx509_cert_init_data(context, query[1].pValue,
 			       query[1].ulValueLen, &cert);
     if (ret)
 	return ret;
=20
-    p->refcount++;
-    if (p->refcount =3D=3D 0)
-	_hx509_abort("pkcs11 refcount to high");
+    if (p->ref =3D=3D 0)
+	_hx509_abort("pkcs11 ref =3D=3D 0 on alloc");
+    p->ref++;
+    if (p->ref =3D=3D UINT_MAX)
+	_hx509_abort("pkcs11 ref to high");
=20
     _hx509_cert_set_release(cert, p11_cert_release, p);
=20
     {
 	heim_octet_string data;
-=09
+
 	data.data =3D query[0].pValue;
 	data.length =3D query[0].ulValueLen;
-=09
+
 	_hx509_set_cert_attribute(context,
 				  cert,
-				  oid_id_pkcs_9_at_localKeyId(),
+				  &asn1_oid_id_pkcs_9_at_localKeyId,
 				  &data);
     }
=20
@@ -734,7 +735,7 @@
 static int
 p11_list_keys(hx509_context context,
 	      struct p11_module *p,
-	      struct p11_slot *slot,=20
+	      struct p11_slot *slot,
 	      CK_SESSION_HANDLE session,
 	      hx509_lock lock,
 	      hx509_certs *certs)
@@ -788,7 +789,7 @@
=20
 static int
 p11_init(hx509_context context,
-	 hx509_certs certs, void **data, int flags,=20
+	 hx509_certs certs, void **data, int flags,
 	 const char *residue, hx509_lock lock)
 {
     CK_C_GetFunctionList getFuncs;
@@ -808,7 +809,7 @@
 	return ENOMEM;
     }
=20
-    p->refcount =3D 1;
+    p->ref =3D 1;
=20
     str =3D strchr(list, ',');
     if (str)
@@ -834,11 +835,11 @@
 	goto out;
     }
=20
-    getFuncs =3D dlsym(p->dl_handle, "C_GetFunctionList");
+    getFuncs =3D (CK_C_GetFunctionList) dlsym(p->dl_handle, "C_GetFunction=
List");
     if (getFuncs =3D=3D NULL) {
 	ret =3D HX509_PKCS11_LOAD;
 	hx509_set_error_string(context, 0, ret,
-			       "C_GetFunctionList missing in %s: %s",=20
+			       "C_GetFunctionList missing in %s: %s",
 			       list, dlerror());
 	goto out;
     }
@@ -877,7 +878,8 @@
=20
     {
 	CK_SLOT_ID_PTR slot_ids;
-	int i, num_tokens =3D 0;
+	int num_tokens =3D 0;
+	size_t i;
=20
 	slot_ids =3D malloc(p->num_slots * sizeof(*slot_ids));
 	if (slot_ids =3D=3D NULL) {
@@ -904,7 +906,7 @@
 	    ret =3D ENOMEM;
 	    goto out;
 	}
-			=20
+
 	for (i =3D 0; i < p->num_slots; i++) {
 	    ret =3D p11_init_slot(context, p, lock, slot_ids[i], i, &p->slot[i]);
 	    if (ret)
@@ -924,7 +926,7 @@
     *data =3D p;
=20
     return 0;
- out:   =20
+ out:
     p11_release_module(p);
     return ret;
 }
@@ -932,22 +934,18 @@
 static void
 p11_release_module(struct p11_module *p)
 {
-    int i;
+    size_t i;
=20
-    if (p->refcount =3D=3D 0)
-	_hx509_abort("pkcs11 refcount to low");
-    if (--p->refcount > 0)
+    if (p->ref =3D=3D 0)
+	_hx509_abort("pkcs11 ref to low");
+    if (--p->ref > 0)
 	return;
=20
     for (i =3D 0; i < p->num_slots; i++) {
 	if (p->slot[i].flags & P11_SESSION_IN_USE)
 	    _hx509_abort("pkcs11 module release while session in use");
 	if (p->slot[i].flags & P11_SESSION) {
-	    int ret;
-
-	    ret =3D P11FUNC(p, CloseSession, (p->slot[i].session));
-	    if (ret !=3D CKR_OK)
-		;
+	    P11FUNC(p, CloseSession, (p->slot[i].session));
 	}
=20
 	if (p->slot[i].name)
@@ -960,7 +958,7 @@
 	    free(p->slot[i].mechs.list);
=20
 	    if (p->slot[i].mechs.infos) {
-		int j;
+		size_t j;
=20
 		for (j =3D 0 ; j < p->slot[i].mechs.num ; j++)
 		    free(p->slot[i].mechs.infos[j]);
@@ -984,7 +982,7 @@
 p11_free(hx509_certs certs, void *data)
 {
     struct p11_module *p =3D data;
-    int i;
+    size_t i;
=20
     for (i =3D 0; i < p->num_slots; i++) {
 	if (p->slot[i].certs)
@@ -999,13 +997,14 @@
     void *cursor;
 };
=20
-static int=20
+static int
 p11_iter_start(hx509_context context,
 	       hx509_certs certs, void *data, void **cursor)
 {
     struct p11_module *p =3D data;
     struct p11_cursor *c;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     c =3D malloc(sizeof(*c));
     if (c =3D=3D NULL) {
@@ -1099,16 +1098,16 @@
 #undef MECHFLAG
=20
 static int
-p11_printinfo(hx509_context context,=20
-	      hx509_certs certs,=20
+p11_printinfo(hx509_context context,
+	      hx509_certs certs,
 	      void *data,
 	      int (*func)(void *, const char *),
 	      void *ctx)
 {
     struct p11_module *p =3D data;
-    int i, j;
-       =20
-    _hx509_pi_printf(func, ctx, "pkcs11 driver with %d slot%s",=20
+    size_t i, j;
+
+    _hx509_pi_printf(func, ctx, "pkcs11 driver with %d slot%s",
 		     p->num_slots, p->num_slots > 1 ? "s" : "");
=20
     for (i =3D 0; i < p->num_slots; i++) {
@@ -1117,7 +1116,7 @@
 	_hx509_pi_printf(func, ctx, "slot %d: id: %d name: %s flags: %08x",
 			 i, (int)s->id, s->name, s->flags);
=20
-	_hx509_pi_printf(func, ctx, "number of supported mechanisms: %lu",=20
+	_hx509_pi_printf(func, ctx, "number of supported mechanisms: %lu",
 			 (unsigned long)s->mechs.num);
 	for (j =3D 0; j < s->mechs.num; j++) {
 	    const char *mechname =3D "unknown";
@@ -1142,7 +1141,6 @@
 		MECHNAME(CKM_SHA256, "sha256");
 		MECHNAME(CKM_SHA_1, "sha1");
 		MECHNAME(CKM_MD5, "md5");
-		MECHNAME(CKM_MD2, "md2");
 		MECHNAME(CKM_RIPEMD160, "ripemd-160");
 		MECHNAME(CKM_DES_ECB, "des-ecb");
 		MECHNAME(CKM_DES_CBC, "des-cbc");
@@ -1151,13 +1149,13 @@
 		MECHNAME(CKM_DH_PKCS_PARAMETER_GEN, "dh-pkcs-parameter-gen");
 	    default:
 		snprintf(unknownname, sizeof(unknownname),
-			 "unknown-mech-%lu",=20
+			 "unknown-mech-%lu",
 			 (unsigned long)s->mechs.list[j]);
 		mechname =3D unknownname;
 		break;
 	    }
 #undef MECHNAME
-	    unparse_flags(s->mechs.infos[j]->flags, mechflags,=20
+	    unparse_flags(s->mechs.infos[j]->flags, mechflags,
 			  flags, sizeof(flags));
=20
 	    _hx509_pi_printf(func, ctx, "  %s: %s", mechname, flags);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ks_p12.c
--- a/head/crypto/heimdal/lib/hx509/ks_p12.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ks_p12.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: ks_p12.c 21146 2007-06-18 21:37:25Z lha $");
=20
 struct ks_pkcs12 {
     hx509_certs certs;
@@ -45,19 +44,19 @@
 			      const PKCS12_Attributes *);
=20
 struct type {
-    const heim_oid * (*oid)(void);
+    const heim_oid *oid;
     collector_func func;
 };
=20
 static void
-parse_pkcs12_type(hx509_context, struct hx509_collector *, const heim_oid =
*,=20
+parse_pkcs12_type(hx509_context, struct hx509_collector *, const heim_oid =
*,
 		  const void *, size_t, const PKCS12_Attributes *);
=20
=20
 static const PKCS12_Attribute *
 find_attribute(const PKCS12_Attributes *attrs, const heim_oid *oid)
 {
-    int i;
+    size_t i;
     if (attrs =3D=3D NULL)
 	return NULL;
     for (i =3D 0; i < attrs->len; i++)
@@ -68,7 +67,7 @@
=20
 static int
 keyBag_parser(hx509_context context,
-	      struct hx509_collector *c,=20
+	      struct hx509_collector *c,
 	      const void *data, size_t length,
 	      const PKCS12_Attributes *attrs)
 {
@@ -77,14 +76,14 @@
     const heim_octet_string *os =3D NULL;
     int ret;
=20
-    attr =3D find_attribute(attrs, oid_id_pkcs_9_at_localKeyId());
+    attr =3D find_attribute(attrs, &asn1_oid_id_pkcs_9_at_localKeyId);
     if (attr)
 	os =3D &attr->attrValues;
=20
     ret =3D decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL);
     if (ret)
 	return ret;
-   =20
+
     _hx509_collector_private_key_add(context,
 				     c,
 				     &ki.privateKeyAlgorithm,
@@ -97,16 +96,16 @@
=20
 static int
 ShroudedKeyBag_parser(hx509_context context,
-		      struct hx509_collector *c,=20
+		      struct hx509_collector *c,
 		      const void *data, size_t length,
 		      const PKCS12_Attributes *attrs)
 {
     PKCS8EncryptedPrivateKeyInfo pk;
     heim_octet_string content;
     int ret;
-   =20
+
     memset(&pk, 0, sizeof(pk));
-   =20
+
     ret =3D decode_PKCS8EncryptedPrivateKeyInfo(data, length, &pk, NULL);
     if (ret)
 	return ret;
@@ -127,7 +126,7 @@
=20
 static int
 certBag_parser(hx509_context context,
-	       struct hx509_collector *c,=20
+	       struct hx509_collector *c,
 	       const void *data, size_t length,
 	       const PKCS12_Attributes *attrs)
 {
@@ -140,12 +139,12 @@
     if (ret)
 	return ret;
=20
-    if (der_heim_oid_cmp(oid_id_pkcs_9_at_certTypes_x509(), &cb.certType))=
 {
+    if (der_heim_oid_cmp(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certTy=
pe)) {
 	free_PKCS12_CertBag(&cb);
 	return 0;
     }
=20
-    ret =3D decode_PKCS12_OctetString(cb.certValue.data,=20
+    ret =3D decode_PKCS12_OctetString(cb.certValue.data,
 				    cb.certValue.length,
 				    &os,
 				    NULL);
@@ -166,18 +165,18 @@
=20
     {
 	const PKCS12_Attribute *attr;
-	const heim_oid * (*oids[])(void) =3D {
-	    oid_id_pkcs_9_at_localKeyId, oid_id_pkcs_9_at_friendlyName
+	const heim_oid *oids[] =3D {
+	    &asn1_oid_id_pkcs_9_at_localKeyId, &asn1_oid_id_pkcs_9_at_friendlyName
 	};
-	int i;
+	size_t i;
=20
-	for (i =3D 0; i < sizeof(oids)/sizeof(oids[0]); i++) {
-	    const heim_oid *oid =3D (*(oids[i]))();
+	for  (i =3D 0; i < sizeof(oids)/sizeof(oids[0]); i++) {
+	    const heim_oid *oid =3D oids[i];
 	    attr =3D find_attribute(attrs, oid);
 	    if (attr)
 		_hx509_set_cert_attribute(context, cert, oid,
 					  &attr->attrValues);
-	}=09
+	}
     }
=20
     hx509_cert_free(cert);
@@ -187,11 +186,12 @@
=20
 static int
 parse_safe_content(hx509_context context,
-		   struct hx509_collector *c,=20
+		   struct hx509_collector *c,
 		   const unsigned char *p, size_t len)
 {
     PKCS12_SafeContents sc;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     memset(&sc, 0, sizeof(sc));
=20
@@ -213,7 +213,7 @@
=20
 static int
 safeContent_parser(hx509_context context,
-		   struct hx509_collector *c,=20
+		   struct hx509_collector *c,
 		   const void *data, size_t length,
 		   const PKCS12_Attributes *attrs)
 {
@@ -237,7 +237,7 @@
     heim_octet_string content;
     heim_oid contentType;
     int ret;
-	=09
+
     memset(&contentType, 0, sizeof(contentType));
=20
     ret =3D hx509_cms_decrypt_encrypted(context,
@@ -248,7 +248,7 @@
     if (ret)
 	return ret;
=20
-    if (der_heim_oid_cmp(&contentType, oid_id_pkcs7_data()) =3D=3D 0)
+    if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) =3D=3D 0)
 	ret =3D parse_safe_content(context, c, content.data, content.length);
=20
     der_free_octet_string(&content);
@@ -266,7 +266,7 @@
     heim_oid contentType;
     hx509_lock lock;
     int ret;
-	=09
+
     memset(&contentType, 0, sizeof(contentType));
=20
     lock =3D _hx509_collector_get_lock(c);
@@ -276,15 +276,16 @@
 			       0,
 			       data, length,
 			       NULL,
+			       0,
 			       &contentType,
 			       &content);
     if (ret) {
-	hx509_set_error_string(context, HX509_ERROR_APPEND, ret,=20
+	hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
 			       "PKCS12 failed to unenvelope");
 	return ret;
     }
=20
-    if (der_heim_oid_cmp(&contentType, oid_id_pkcs7_data()) =3D=3D 0)
+    if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) =3D=3D 0)
 	ret =3D parse_safe_content(context, c, content.data, content.length);
=20
     der_free_octet_string(&content);
@@ -295,31 +296,31 @@
=20
=20
 struct type bagtypes[] =3D {
-    { oid_id_pkcs12_keyBag, keyBag_parser },
-    { oid_id_pkcs12_pkcs8ShroudedKeyBag, ShroudedKeyBag_parser },
-    { oid_id_pkcs12_certBag, certBag_parser },
-    { oid_id_pkcs7_data, safeContent_parser },
-    { oid_id_pkcs7_encryptedData, encryptedData_parser },
-    { oid_id_pkcs7_envelopedData, envelopedData_parser }
+    { &asn1_oid_id_pkcs12_keyBag, keyBag_parser },
+    { &asn1_oid_id_pkcs12_pkcs8ShroudedKeyBag, ShroudedKeyBag_parser },
+    { &asn1_oid_id_pkcs12_certBag, certBag_parser },
+    { &asn1_oid_id_pkcs7_data, safeContent_parser },
+    { &asn1_oid_id_pkcs7_encryptedData, encryptedData_parser },
+    { &asn1_oid_id_pkcs7_envelopedData, envelopedData_parser }
 };
=20
 static void
 parse_pkcs12_type(hx509_context context,
 		  struct hx509_collector *c,
-		  const heim_oid *oid,=20
+		  const heim_oid *oid,
 		  const void *data, size_t length,
 		  const PKCS12_Attributes *attrs)
 {
-    int i;
+    size_t i;
=20
     for (i =3D 0; i < sizeof(bagtypes)/sizeof(bagtypes[0]); i++)
-	if (der_heim_oid_cmp((*bagtypes[i].oid)(), oid) =3D=3D 0)
+	if (der_heim_oid_cmp(bagtypes[i].oid, oid) =3D=3D 0)
 	    (*bagtypes[i].func)(context, c, data, length, attrs);
 }
=20
 static int
 p12_init(hx509_context context,
-	 hx509_certs certs, void **data, int flags,=20
+	 hx509_certs certs, void **data, int flags,
 	 const char *residue, hx509_lock lock)
 {
     struct ks_pkcs12 *p12;
@@ -327,7 +328,8 @@
     void *buf;
     PKCS12_PFX pfx;
     PKCS12_AuthenticatedSafe as;
-    int ret, i;
+    int ret;
+    size_t i;
     struct hx509_collector *c;
=20
     *data =3D NULL;
@@ -361,21 +363,21 @@
 	goto out;
     }
=20
-    ret =3D _hx509_map_file(residue, &buf, &len, NULL);
+    ret =3D rk_undumpdata(residue, &buf, &len);
     if (ret) {
 	hx509_clear_error_string(context);
 	goto out;
     }
=20
     ret =3D decode_PKCS12_PFX(buf, len, &pfx, NULL);
-    _hx509_unmap_file(buf, len);
+    rk_xfree(buf);
     if (ret) {
 	hx509_set_error_string(context, 0, ret,
 			       "Failed to decode the PFX in %s", residue);
 	goto out;
     }
=20
-    if (der_heim_oid_cmp(&pfx.authSafe.contentType, oid_id_pkcs7_data()) !=
=3D 0) {
+    if (der_heim_oid_cmp(&pfx.authSafe.contentType, &asn1_oid_id_pkcs7_dat=
a) !=3D 0) {
 	free_PKCS12_PFX(&pfx);
 	ret =3D EINVAL;
 	hx509_set_error_string(context, 0, ret,
@@ -403,7 +405,7 @@
 	    hx509_clear_error_string(context);
 	    goto out;
 	}
-	ret =3D decode_PKCS12_AuthenticatedSafe(asdata.data,=20
+	ret =3D decode_PKCS12_AuthenticatedSafe(asdata.data,
 					      asdata.length,
 					      &as,
 					      NULL);
@@ -464,7 +466,7 @@
 	hx509_set_error_string(context, 0, ret, "out of memory");
 	return ret;
     }
-   =20
+
     as->val[as->len].content =3D calloc(1, sizeof(*as->val[0].content));
     if (as->val[as->len].content =3D=3D NULL) {
 	der_free_oid(&as->val[as->len].contentType);
@@ -505,7 +507,7 @@
     free(os.data);
     if (ret)
 	goto out;
-    ret =3D der_copy_oid(oid_id_pkcs_9_at_certTypes_x509(), &cb.certType);
+    ret =3D der_copy_oid(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certTy=
pe);
     if (ret) {
 	free_PKCS12_CertBag(&cb);
 	goto out;
@@ -516,7 +518,7 @@
     if (ret)
 	goto out;
=20
-    ret =3D addBag(context, as, oid_id_pkcs12_certBag(), os.data, os.lengt=
h);
+    ret =3D addBag(context, as, &asn1_oid_id_pkcs12_certBag, os.data, os.l=
ength);
=20
     if (_hx509_cert_private_key_exportable(c)) {
 	hx509_private_key key =3D _hx509_cert_private_key(c);
@@ -527,7 +529,7 @@
 	ret =3D der_parse_hex_heim_integer("00", &pki.version);
 	if (ret)
 	    return ret;
-	ret =3D _hx509_private_key_oid(context, key,=20
+	ret =3D _hx509_private_key_oid(context, key,
 				     &pki.privateKeyAlgorithm.algorithm);
 	if (ret) {
 	    free_PKCS8PrivateKeyInfo(&pki);
@@ -535,12 +537,13 @@
 	}
 	ret =3D _hx509_private_key_export(context,
 					_hx509_cert_private_key(c),
+					HX509_KEY_FORMAT_DER,
 					&pki.privateKey);
 	if (ret) {
 	    free_PKCS8PrivateKeyInfo(&pki);
 	    return ret;
 	}
-	/* set attribute, oid_id_pkcs_9_at_localKeyId() */
+	/* set attribute, asn1_oid_id_pkcs_9_at_localKeyId */
=20
 	ASN1_MALLOC_ENCODE(PKCS8PrivateKeyInfo, os.data, os.length,
 			   &pki, &size, ret);
@@ -548,7 +551,7 @@
 	if (ret)
 	    return ret;
=20
-	ret =3D addBag(context, as, oid_id_pkcs12_keyBag(), os.data, os.length);
+	ret =3D addBag(context, as, &asn1_oid_id_pkcs12_keyBag, os.data, os.lengt=
h);
 	if (ret)
 	    return ret;
     }
@@ -558,7 +561,7 @@
 }
=20
 static int
-p12_store(hx509_context context,=20
+p12_store(hx509_context context,
 	  hx509_certs certs, void *data, int flags, hx509_lock lock)
 {
     struct ks_pkcs12 *p12 =3D data;
@@ -571,7 +574,7 @@
     memset(&as, 0, sizeof(as));
     memset(&pfx, 0, sizeof(pfx));
=20
-    ret =3D hx509_certs_iter(context, p12->certs, store_func, &as);
+    ret =3D hx509_certs_iter_f(context, p12->certs, store_func, &as);
     if (ret)
 	goto out;
=20
@@ -580,7 +583,7 @@
     free_PKCS12_AuthenticatedSafe(&as);
     if (ret)
 	return ret;
-		      =20
+
     ret =3D der_parse_hex_heim_integer("03", &pfx.version);
     if (ret) {
 	free(asdata.data);
@@ -589,7 +592,7 @@
=20
     pfx.authSafe.content =3D calloc(1, sizeof(*pfx.authSafe.content));
=20
-    ASN1_MALLOC_ENCODE(PKCS12_OctetString,=20
+    ASN1_MALLOC_ENCODE(PKCS12_OctetString,
 		       pfx.authSafe.content->data,
 		       pfx.authSafe.content->length,
 		       &asdata, &size, ret);
@@ -597,7 +600,7 @@
     if (ret)
 	goto out;
=20
-    ret =3D der_copy_oid(oid_id_pkcs7_data(), &pfx.authSafe.contentType);
+    ret =3D der_copy_oid(&asn1_oid_id_pkcs7_data, &pfx.authSafe.contentTyp=
e);
     if (ret)
 	goto out;
=20
@@ -646,14 +649,14 @@
     return 0;
 }
=20
-static int=20
+static int
 p12_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
 {
     struct ks_pkcs12 *p12 =3D data;
     return hx509_certs_add(context, p12->certs, c);
 }
=20
-static int=20
+static int
 p12_iter_start(hx509_context context,
 	       hx509_certs certs,
 	       void *data,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/lock.c
--- a/head/crypto/heimdal/lib/hx509/lock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/lock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2005 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: lock.c 22327 2007-12-15 04:49:37Z lha $");
=20
 /**
  * @page page_lock Locking and unlocking certificates and encrypted data.
@@ -69,8 +68,8 @@
     if (l =3D=3D NULL)
 	return ENOMEM;
=20
-    ret =3D hx509_certs_init(context,=20
-			   "MEMORY:locks-internal",=20
+    ret =3D hx509_certs_init(context,
+			   "MEMORY:locks-internal",
 			   0,
 			   NULL,
 			   &l->certs);
@@ -122,7 +121,7 @@
 void
 hx509_lock_reset_passwords(hx509_lock lock)
 {
-    int i;
+    size_t i;
     for (i =3D 0; i < lock->password.len; i++)
 	free(lock->password.val[i]);
     free(lock->password.val);
@@ -147,8 +146,8 @@
 {
     hx509_certs certs =3D lock->certs;
     int ret;
-   =20
-    ret =3D hx509_certs_init(context,=20
+
+    ret =3D hx509_certs_init(context,
 			   "MEMORY:locks-internal",
 			   0,
 			   NULL,
@@ -181,7 +180,7 @@
     lock->prompt_data =3D NULL;
 }
=20
-static int=20
+static int
 default_prompter(void *data, const hx509_prompt *prompter)
 {
     if (hx509_prompt_hidden(prompter->type)) {
@@ -215,10 +214,12 @@
 void
 hx509_lock_free(hx509_lock lock)
 {
-    hx509_certs_free(&lock->certs);
-    hx509_lock_reset_passwords(lock);
-    memset(lock, 0, sizeof(*lock));
-    free(lock);
+    if (lock) {
+	hx509_certs_free(&lock->certs);
+	hx509_lock_reset_passwords(lock);
+	memset(lock, 0, sizeof(*lock));
+	free(lock);
+    }
 }
=20
 int
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/name.c
--- a/head/crypto/heimdal/lib/hx509/name.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/name.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,39 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2009 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: name.c 22432 2008-01-13 14:08:03Z lha $");
+#include <wind.h>
+#include "char_map.h"
=20
 /**
  * @page page_name PKIX/X.509 Names
@@ -43,7 +44,7 @@
  * (RDN). Each RDN consists of an unordered list of typed strings. The
  * types are defined by OID and have long and short description. For
  * example id-at-commonName (2.5.4.3) have the long name CommonName
- * and short name CN. The string itself can be of serveral encoding,
+ * and short name CN. The string itself can be of several encoding,
  * UTF8, UTF16, Teltex string, etc. The type limit what encoding
  * should be used.
  *
@@ -62,27 +63,28 @@
=20
 static const struct {
     const char *n;
-    const heim_oid *(*o)(void);
+    const heim_oid *o;
+    wind_profile_flags flags;
 } no[] =3D {
-    { "C", oid_id_at_countryName },
-    { "CN", oid_id_at_commonName },
-    { "DC", oid_id_domainComponent },
-    { "L", oid_id_at_localityName },
-    { "O", oid_id_at_organizationName },
-    { "OU", oid_id_at_organizationalUnitName },
-    { "S", oid_id_at_stateOrProvinceName },
-    { "STREET", oid_id_at_streetAddress },
-    { "UID", oid_id_Userid },
-    { "emailAddress", oid_id_pkcs9_emailAddress },
-    { "serialNumber", oid_id_at_serialNumber }
+    { "C", &asn1_oid_id_at_countryName, 0 },
+    { "CN", &asn1_oid_id_at_commonName, 0 },
+    { "DC", &asn1_oid_id_domainComponent, 0 },
+    { "L", &asn1_oid_id_at_localityName, 0 },
+    { "O", &asn1_oid_id_at_organizationName, 0 },
+    { "OU", &asn1_oid_id_at_organizationalUnitName, 0 },
+    { "S", &asn1_oid_id_at_stateOrProvinceName, 0 },
+    { "STREET", &asn1_oid_id_at_streetAddress, 0 },
+    { "UID", &asn1_oid_id_Userid, 0 },
+    { "emailAddress", &asn1_oid_id_pkcs9_emailAddress, 0 },
+    { "serialNumber", &asn1_oid_id_at_serialNumber, 0 }
 };
=20
 static char *
-quote_string(const char *f, size_t len, size_t *rlen)
+quote_string(const char *f, size_t len, int flags, size_t *rlen)
 {
     size_t i, j, tolen;
-    const char *from =3D f;
-    char *to;
+    const unsigned char *from =3D (const unsigned char *)f;
+    unsigned char *to;
=20
     tolen =3D len * 3 + 1;
     to =3D malloc(tolen);
@@ -90,37 +92,40 @@
 	return NULL;
=20
     for (i =3D 0, j =3D 0; i < len; i++) {
-	if (from[i] =3D=3D ' ' && i + 1 < len)
-	    to[j++] =3D from[i];
-	else if (from[i] =3D=3D ',' || from[i] =3D=3D '=3D' || from[i] =3D=3D '+'=
 ||
-		 from[i] =3D=3D '<' || from[i] =3D=3D '>' || from[i] =3D=3D '#' ||
-		 from[i] =3D=3D ';' || from[i] =3D=3D ' ')
-	{
+	unsigned char map =3D char_map[from[i]] & flags;
+	if (i =3D=3D 0 && (map & Q_RFC2253_QUOTE_FIRST)) {
 	    to[j++] =3D '\\';
 	    to[j++] =3D from[i];
-	} else if (((unsigned char)from[i]) >=3D 32 && ((unsigned char)from[i]) <=
=3D 127) {
+	} else if ((i + 1) =3D=3D len && (map & Q_RFC2253_QUOTE_LAST)) {
+
+	    to[j++] =3D '\\';
 	    to[j++] =3D from[i];
-	} else {
-	    int l =3D snprintf(&to[j], tolen - j - 1,
+	} else if (map & Q_RFC2253_QUOTE) {
+	    to[j++] =3D '\\';
+	    to[j++] =3D from[i];
+	} else if (map & Q_RFC2253_HEX) {
+	    int l =3D snprintf((char *)&to[j], tolen - j - 1,
 			     "#%02x", (unsigned char)from[i]);
 	    j +=3D l;
+	} else {
+	    to[j++] =3D from[i];
 	}
     }
     to[j] =3D '\0';
     assert(j < tolen);
     *rlen =3D j;
-    return to;
+    return (char *)to;
 }
=20
=20
 static int
-append_string(char **str, size_t *total_len, const char *ss,=20
+append_string(char **str, size_t *total_len, const char *ss,
 	      size_t len, int quote)
 {
     char *s, *qs;
=20
     if (quote)
-	qs =3D quote_string(ss, len, &len);
+	qs =3D quote_string(ss, len, Q_RFC2253, &len);
     else
 	qs =3D rk_UNCONST(ss);
=20
@@ -141,9 +146,9 @@
 {
     char *s;
     size_t i;
-   =20
+
     for (i =3D 0; i < sizeof(no)/sizeof(no[0]); i++) {
-	if (der_heim_oid_cmp((*no[i].o)(), type) =3D=3D 0)
+	if (der_heim_oid_cmp(no[i].o, type) =3D=3D 0)
 	    return strdup(no[i].n);
     }
     if (der_print_heim_oid(type, '.', &s) !=3D 0)
@@ -154,14 +159,15 @@
 static int
 stringtooid(const char *name, size_t len, heim_oid *oid)
 {
-    int i, ret;
+    int ret;
+    size_t i;
     char *s;
-   =20
+
     memset(oid, 0, sizeof(*oid));
=20
     for (i =3D 0; i < sizeof(no)/sizeof(no[0]); i++) {
 	if (strncasecmp(no[i].n, name, len) =3D=3D 0)
-	    return der_copy_oid((*no[i].o)(), oid);
+	    return der_copy_oid(no[i].o, oid);
     }
     s =3D malloc(len + 1);
     if (s =3D=3D NULL)
@@ -195,63 +201,81 @@
 _hx509_Name_to_string(const Name *n, char **str)
 {
     size_t total_len =3D 0;
-    int i, j;
+    size_t i, j, m;
+    int ret;
=20
     *str =3D strdup("");
     if (*str =3D=3D NULL)
 	return ENOMEM;
=20
-    for (i =3D n->u.rdnSequence.len - 1 ; i >=3D 0 ; i--) {
-	int len;
+    for (m =3D n->u.rdnSequence.len; m > 0; m--) {
+	size_t len;
+	i =3D m - 1;
=20
 	for (j =3D 0; j < n->u.rdnSequence.val[i].len; j++) {
 	    DirectoryString *ds =3D &n->u.rdnSequence.val[i].val[j].value;
 	    char *oidname;
 	    char *ss;
-	   =20
+
 	    oidname =3D oidtostring(&n->u.rdnSequence.val[i].val[j].type);
=20
 	    switch(ds->element) {
 	    case choice_DirectoryString_ia5String:
-		ss =3D ds->u.ia5String;
+		ss =3D ds->u.ia5String.data;
+		len =3D ds->u.ia5String.length;
 		break;
 	    case choice_DirectoryString_printableString:
-		ss =3D ds->u.printableString;
+		ss =3D ds->u.printableString.data;
+		len =3D ds->u.printableString.length;
 		break;
 	    case choice_DirectoryString_utf8String:
 		ss =3D ds->u.utf8String;
+		len =3D strlen(ss);
 		break;
 	    case choice_DirectoryString_bmpString: {
-		uint16_t *bmp =3D ds->u.bmpString.data;
+	        const uint16_t *bmp =3D ds->u.bmpString.data;
 		size_t bmplen =3D ds->u.bmpString.length;
 		size_t k;
=20
-		ss =3D malloc(bmplen + 1);
+		ret =3D wind_ucs2utf8_length(bmp, bmplen, &k);
+		if (ret)
+		    return ret;
+
+		ss =3D malloc(k + 1);
 		if (ss =3D=3D NULL)
 		    _hx509_abort("allocation failure"); /* XXX */
-		for (k =3D 0; k < bmplen; k++)
-		    ss[k] =3D bmp[k] & 0xff; /* XXX */
+		ret =3D wind_ucs2utf8(bmp, bmplen, ss, NULL);
+		if (ret) {
+		    free(ss);
+		    return ret;
+		}
 		ss[k] =3D '\0';
+		len =3D k;
 		break;
 	    }
 	    case choice_DirectoryString_teletexString:
-		ss =3D malloc(ds->u.teletexString.length + 1);
-		if (ss =3D=3D NULL)
-		    _hx509_abort("allocation failure"); /* XXX */
-		memcpy(ss, ds->u.teletexString.data, ds->u.teletexString.length);
-		ss[ds->u.teletexString.length] =3D '\0';
+		ss =3D ds->u.teletexString;
+		len =3D strlen(ss);
 		break;
 	    case choice_DirectoryString_universalString: {
-		uint32_t *uni =3D ds->u.universalString.data;
+	        const uint32_t *uni =3D ds->u.universalString.data;
 		size_t unilen =3D ds->u.universalString.length;
 		size_t k;
=20
-		ss =3D malloc(unilen + 1);
+		ret =3D wind_ucs4utf8_length(uni, unilen, &k);
+		if (ret)
+		    return ret;
+
+		ss =3D malloc(k + 1);
 		if (ss =3D=3D NULL)
 		    _hx509_abort("allocation failure"); /* XXX */
-		for (k =3D 0; k < unilen; k++)
-		    ss[k] =3D uni[k] & 0xff; /* XXX */
+		ret =3D wind_ucs4utf8(uni, unilen, ss, NULL);
+		if (ret) {
+		    free(ss);
+		    return ret;
+		}
 		ss[k] =3D '\0';
+		len =3D k;
 		break;
 	    }
 	    default:
@@ -261,11 +285,9 @@
 	    append_string(str, &total_len, oidname, strlen(oidname), 0);
 	    free(oidname);
 	    append_string(str, &total_len, "=3D", 1, 0);
-	    len =3D strlen(ss);
 	    append_string(str, &total_len, ss, len, 1);
-	    if (ds->element =3D=3D choice_DirectoryString_universalString ||
-		ds->element =3D=3D choice_DirectoryString_bmpString ||
-		ds->element =3D=3D choice_DirectoryString_teletexString)
+	    if (ds->element =3D=3D choice_DirectoryString_bmpString ||
+		ds->element =3D=3D choice_DirectoryString_universalString)
 	    {
 		free(ss);
 	    }
@@ -279,95 +301,174 @@
     return 0;
 }
=20
-/*
- * XXX this function is broken, it needs to compare code points, not
- * bytes.
- */
+#define COPYCHARARRAY(_ds,_el,_l,_n)		\
+        (_l) =3D strlen(_ds->u._el);		\
+	(_n) =3D malloc((_l) * sizeof((_n)[0]));	\
+	if ((_n) =3D=3D NULL)			\
+	    return ENOMEM;			\
+	for (i =3D 0; i < (_l); i++)		\
+	    (_n)[i] =3D _ds->u._el[i]
=20
-static void
-prune_space(const unsigned char **s)
+
+#define COPYVALARRAY(_ds,_el,_l,_n)		\
+        (_l) =3D _ds->u._el.length;		\
+	(_n) =3D malloc((_l) * sizeof((_n)[0]));	\
+	if ((_n) =3D=3D NULL)			\
+	    return ENOMEM;			\
+	for (i =3D 0; i < (_l); i++)		\
+	    (_n)[i] =3D _ds->u._el.data[i]
+
+#define COPYVOIDARRAY(_ds,_el,_l,_n)		\
+        (_l) =3D _ds->u._el.length;		\
+	(_n) =3D malloc((_l) * sizeof((_n)[0]));	\
+	if ((_n) =3D=3D NULL)			\
+	    return ENOMEM;			\
+	for (i =3D 0; i < (_l); i++)		\
+	    (_n)[i] =3D ((unsigned char *)_ds->u._el.data)[i]
+
+
+
+static int
+dsstringprep(const DirectoryString *ds, uint32_t **rname, size_t *rlen)
 {
-    while (**s =3D=3D ' ')
-	(*s)++;
+    wind_profile_flags flags;
+    size_t i, len;
+    int ret;
+    uint32_t *name;
+
+    *rname =3D NULL;
+    *rlen =3D 0;
+
+    switch(ds->element) {
+    case choice_DirectoryString_ia5String:
+	flags =3D WIND_PROFILE_LDAP;
+	COPYVOIDARRAY(ds, ia5String, len, name);
+	break;
+    case choice_DirectoryString_printableString:
+	flags =3D WIND_PROFILE_LDAP;
+	flags |=3D WIND_PROFILE_LDAP_CASE_EXACT_ATTRIBUTE;
+	COPYVOIDARRAY(ds, printableString, len, name);
+	break;
+    case choice_DirectoryString_teletexString:
+	flags =3D WIND_PROFILE_LDAP_CASE;
+	COPYCHARARRAY(ds, teletexString, len, name);
+	break;
+    case choice_DirectoryString_bmpString:
+	flags =3D WIND_PROFILE_LDAP;
+	COPYVALARRAY(ds, bmpString, len, name);
+	break;
+    case choice_DirectoryString_universalString:
+	flags =3D WIND_PROFILE_LDAP;
+	COPYVALARRAY(ds, universalString, len, name);
+	break;
+    case choice_DirectoryString_utf8String:
+	flags =3D WIND_PROFILE_LDAP;
+	ret =3D wind_utf8ucs4_length(ds->u.utf8String, &len);
+	if (ret)
+	    return ret;
+	name =3D malloc(len * sizeof(name[0]));
+	if (name =3D=3D NULL)
+	    return ENOMEM;
+	ret =3D wind_utf8ucs4(ds->u.utf8String, name, &len);
+	if (ret) {
+	    free(name);
+	    return ret;
+	}
+	break;
+    default:
+	_hx509_abort("unknown directory type: %d", ds->element);
+    }
+
+    *rlen =3D len;
+    /* try a couple of times to get the length right, XXX gross */
+    for (i =3D 0; i < 4; i++) {
+	*rlen =3D *rlen * 2;
+	*rname =3D malloc(*rlen * sizeof((*rname)[0]));
+
+	ret =3D wind_stringprep(name, len, *rname, rlen, flags);
+	if (ret =3D=3D WIND_ERR_OVERRUN) {
+	    free(*rname);
+	    *rname =3D NULL;
+	    continue;
+	} else
+	    break;
+    }
+    free(name);
+    if (ret) {
+	if (*rname)
+	    free(*rname);
+	*rname =3D NULL;
+	*rlen =3D 0;
+	return ret;
+    }
+
+    return 0;
 }
=20
 int
-_hx509_name_ds_cmp(const DirectoryString *ds1, const DirectoryString *ds2)
+_hx509_name_ds_cmp(const DirectoryString *ds1,
+		   const DirectoryString *ds2,
+		   int *diff)
 {
-    int c;
+    uint32_t *ds1lp, *ds2lp;
+    size_t ds1len, ds2len, i;
+    int ret;
=20
-    c =3D ds1->element - ds2->element;
-    if (c)
-	return c;
+    ret =3D dsstringprep(ds1, &ds1lp, &ds1len);
+    if (ret)
+	return ret;
+    ret =3D dsstringprep(ds2, &ds2lp, &ds2len);
+    if (ret) {
+	free(ds1lp);
+	return ret;
+    }
=20
-    switch(ds1->element) {
-    case choice_DirectoryString_ia5String:
-	c =3D strcmp(ds1->u.ia5String, ds2->u.ia5String);
-	break;
-    case choice_DirectoryString_teletexString:
-	c =3D der_heim_octet_string_cmp(&ds1->u.teletexString,
-				  &ds2->u.teletexString);
-	break;
-    case choice_DirectoryString_printableString: {
-	const unsigned char *s1 =3D (unsigned char*)ds1->u.printableString;
-	const unsigned char *s2 =3D (unsigned char*)ds2->u.printableString;
-	prune_space(&s1); prune_space(&s2);
-	while (*s1 && *s2) {
-	    if (toupper(*s1) !=3D toupper(*s2)) {
-		c =3D toupper(*s1) - toupper(*s2);
+    if (ds1len !=3D ds2len)
+	*diff =3D ds1len - ds2len;
+    else {
+	for (i =3D 0; i < ds1len; i++) {
+	    *diff =3D ds1lp[i] - ds2lp[i];
+	    if (*diff)
 		break;
-	    }
-	    if (*s1 =3D=3D ' ') { prune_space(&s1); prune_space(&s2); }
-	    else { s1++; s2++; }
-	}	   =20
-	prune_space(&s1); prune_space(&s2);
-	c =3D *s1 - *s2;
-	break;
+	}
     }
-    case choice_DirectoryString_utf8String:
-	c =3D strcmp(ds1->u.utf8String, ds2->u.utf8String);
-	break;
-    case choice_DirectoryString_universalString:
-	c =3D der_heim_universal_string_cmp(&ds1->u.universalString,
-					  &ds2->u.universalString);
-	break;
-    case choice_DirectoryString_bmpString:
-	c =3D der_heim_bmp_string_cmp(&ds1->u.bmpString,
-				    &ds2->u.bmpString);
-	break;
-    default:
-	c =3D 1;
-	break;
-    }
-    return c;
+    free(ds1lp);
+    free(ds2lp);
+
+    return 0;
 }
=20
 int
-_hx509_name_cmp(const Name *n1, const Name *n2)
+_hx509_name_cmp(const Name *n1, const Name *n2, int *c)
 {
-    int i, j, c;
+    int ret;
+    size_t i, j;
=20
-    c =3D n1->u.rdnSequence.len - n2->u.rdnSequence.len;
-    if (c)
-	return c;
+    *c =3D n1->u.rdnSequence.len - n2->u.rdnSequence.len;
+    if (*c)
+	return 0;
=20
     for (i =3D 0 ; i < n1->u.rdnSequence.len; i++) {
-	c =3D n1->u.rdnSequence.val[i].len - n2->u.rdnSequence.val[i].len;
-	if (c)
-	    return c;
+	*c =3D n1->u.rdnSequence.val[i].len - n2->u.rdnSequence.val[i].len;
+	if (*c)
+	    return 0;
=20
 	for (j =3D 0; j < n1->u.rdnSequence.val[i].len; j++) {
-	    c =3D der_heim_oid_cmp(&n1->u.rdnSequence.val[i].val[j].type,
-				 &n1->u.rdnSequence.val[i].val[j].type);
-	    if (c)
-		return c;
-			    =20
-	    c =3D _hx509_name_ds_cmp(&n1->u.rdnSequence.val[i].val[j].value,
-				   &n2->u.rdnSequence.val[i].val[j].value);
-	    if (c)
-		return c;
+	    *c =3D der_heim_oid_cmp(&n1->u.rdnSequence.val[i].val[j].type,
+				  &n1->u.rdnSequence.val[i].val[j].type);
+	    if (*c)
+		return 0;
+
+	    ret =3D _hx509_name_ds_cmp(&n1->u.rdnSequence.val[i].val[j].value,
+				     &n2->u.rdnSequence.val[i].val[j].value,
+				     c);
+	    if (ret)
+		return ret;
+	    if (*c)
+		return 0;
 	}
     }
+    *c =3D 0;
     return 0;
 }
=20
@@ -386,7 +487,11 @@
 int
 hx509_name_cmp(hx509_name n1, hx509_name n2)
 {
-    return _hx509_name_cmp(&n1->der_name, &n2->der_name);
+    int ret, diff;
+    ret =3D _hx509_name_cmp(&n1->der_name, &n2->der_name, &diff);
+    if (ret)
+	return ret;
+    return diff;
 }
=20
=20
@@ -407,17 +512,17 @@
=20
 int
 _hx509_name_modify(hx509_context context,
-		   Name *name,=20
+		   Name *name,
 		   int append,
-		   const heim_oid *oid,=20
+		   const heim_oid *oid,
 		   const char *str)
 {
     RelativeDistinguishedName *rdn;
     int ret;
     void *ptr;
=20
-    ptr =3D realloc(name->u.rdnSequence.val,=20
-		  sizeof(name->u.rdnSequence.val[0]) *=20
+    ptr =3D realloc(name->u.rdnSequence.val,
+		  sizeof(name->u.rdnSequence.val[0]) *
 		  (name->u.rdnSequence.len + 1));
     if (ptr =3D=3D NULL) {
 	hx509_set_error_string(context, 0, ENOMEM, "Out of memory");
@@ -430,9 +535,9 @@
     } else {
 	memmove(&name->u.rdnSequence.val[1],
 		&name->u.rdnSequence.val[0],
-		name->u.rdnSequence.len *=20
+		name->u.rdnSequence.len *
 		sizeof(name->u.rdnSequence.val[0]));
-=09
+
 	rdn =3D &name->u.rdnSequence.val[0];
     }
     rdn->val =3D malloc(sizeof(rdn->val[0]));
@@ -504,12 +609,12 @@
 	}
 	if (q =3D=3D p) {
 	    ret =3D HX509_PARSING_NAME_FAILED;
-	    hx509_set_error_string(context, 0, ret,=20
+	    hx509_set_error_string(context, 0, ret,
 				   "missing name before =3D in %s", p);
 	    goto out;
 	}
-=09
-	if ((q - p) > len) {
+
+	if ((size_t)(q - p) > len) {
 	    ret =3D HX509_PARSING_NAME_FAILED;
 	    hx509_set_error_string(context, 0, ret, " =3D after , in %s", p);
 	    goto out;
@@ -518,16 +623,16 @@
 	ret =3D stringtooid(p, q - p, &oid);
 	if (ret) {
 	    ret =3D HX509_PARSING_NAME_FAILED;
-	    hx509_set_error_string(context, 0, ret,=20
+	    hx509_set_error_string(context, 0, ret,
 				   "unknown type: %.*s", (int)(q - p), p);
 	    goto out;
 	}
-=09
+
 	{
 	    size_t pstr_len =3D len - (q - p) - 1;
 	    const char *pstr =3D p + (q - p) + 1;
 	    char *r;
-	   =20
+
 	    r =3D malloc(pstr_len + 1);
 	    if (r =3D=3D NULL) {
 		der_free_oid(&oid);
@@ -626,7 +731,7 @@
 		  hx509_env env)
 {
     Name *n =3D &name->der_name;
-    int i, j;
+    size_t i, j;
=20
     if (env =3D=3D NULL)
 	return 0;
@@ -658,8 +763,8 @@
 	    }
 	    p =3D strstr(ds->u.utf8String, "${");
 	    if (p) {
-		strpool =3D rk_strpoolprintf(strpool, "%.*s",=20
-					   (int)(p - ds->u.utf8String),=20
+		strpool =3D rk_strpoolprintf(strpool, "%.*s",
+					   (int)(p - ds->u.utf8String),
 					   ds->u.utf8String);
 		if (strpool =3D=3D NULL) {
 		    hx509_set_error_string(context, 0, ENOMEM, "out of memory");
@@ -678,7 +783,7 @@
 		p +=3D 2;
 		value =3D hx509_env_lfind(context, env, p, p2 - p);
 		if (value =3D=3D NULL) {
-		    hx509_set_error_string(context, 0, EINVAL,=20
+		    hx509_set_error_string(context, 0, EINVAL,
 					   "variable %.*s missing",
 					   (int)(p2 - p), p);
 		    rk_strpoolfree(strpool);
@@ -693,7 +798,7 @@
=20
 		p =3D strstr(p2, "${");
 		if (p)
-		    strpool =3D rk_strpoolprintf(strpool, "%.*s",=20
+		    strpool =3D rk_strpoolprintf(strpool, "%.*s",
 					       (int)(p - p2), p2);
 		else
 		    strpool =3D rk_strpoolprintf(strpool, "%s", p2);
@@ -824,7 +929,7 @@
  * @param name the name to print
  * @param str an allocated string returns the name in string form
  *
- * @return An hx509 error code, see krb5_get_error_string().
+ * @return An hx509 error code, see hx509_get_error_string().
  *
  * @ingroup hx509_name
  */
@@ -838,21 +943,23 @@
=20
     switch (name->element) {
     case choice_GeneralName_otherName: {
-	char *str;
-	hx509_oid_sprint(&name->u.otherName.type_id, &str);
-	if (str =3D=3D NULL)
+	char *oid;
+	hx509_oid_sprint(&name->u.otherName.type_id, &oid);
+	if (oid =3D=3D NULL)
 	    return ENOMEM;
-	strpool =3D rk_strpoolprintf(strpool, "otherName: %s", str);
-	free(str);
+	strpool =3D rk_strpoolprintf(strpool, "otherName: %s", oid);
+	free(oid);
 	break;
     }
     case choice_GeneralName_rfc822Name:
-	strpool =3D rk_strpoolprintf(strpool, "rfc822Name: %s\n",
-				   name->u.rfc822Name);
+	strpool =3D rk_strpoolprintf(strpool, "rfc822Name: %.*s\n",
+				   (int)name->u.rfc822Name.length,
+				   (char *)name->u.rfc822Name.data);
 	break;
     case choice_GeneralName_dNSName:
-	strpool =3D rk_strpoolprintf(strpool, "dNSName: %s\n",
-				   name->u.dNSName);
+	strpool =3D rk_strpoolprintf(strpool, "dNSName: %.*s\n",
+				   (int)name->u.dNSName.length,
+				   (char *)name->u.dNSName.data);
 	break;
     case choice_GeneralName_directoryName: {
 	Name dir;
@@ -869,8 +976,9 @@
 	break;
     }
     case choice_GeneralName_uniformResourceIdentifier:
-	strpool =3D rk_strpoolprintf(strpool, "URI: %s",=20
-				   name->u.uniformResourceIdentifier);
+	strpool =3D rk_strpoolprintf(strpool, "URI: %.*s",
+				   (int)name->u.uniformResourceIdentifier.length,
+				   (char *)name->u.uniformResourceIdentifier.data);
 	break;
     case choice_GeneralName_iPAddress: {
 	unsigned char *a =3D name->u.iPAddress.data;
@@ -879,31 +987,31 @@
 	if (strpool =3D=3D NULL)
 	    break;
 	if (name->u.iPAddress.length =3D=3D 4)
-	    strpool =3D rk_strpoolprintf(strpool, "%d.%d.%d.%d",=20
+	    strpool =3D rk_strpoolprintf(strpool, "%d.%d.%d.%d",
 				       a[0], a[1], a[2], a[3]);
 	else if (name->u.iPAddress.length =3D=3D 16)
-	    strpool =3D rk_strpoolprintf(strpool,=20
+	    strpool =3D rk_strpoolprintf(strpool,
 				       "%02X:%02X:%02X:%02X:"
 				       "%02X:%02X:%02X:%02X:"
 				       "%02X:%02X:%02X:%02X:"
-				       "%02X:%02X:%02X:%02X",=20
+				       "%02X:%02X:%02X:%02X",
 				       a[0], a[1], a[2], a[3],
 				       a[4], a[5], a[6], a[7],
 				       a[8], a[9], a[10], a[11],
 				       a[12], a[13], a[14], a[15]);
 	else
-	    strpool =3D rk_strpoolprintf(strpool,=20
+	    strpool =3D rk_strpoolprintf(strpool,
 				       "unknown IP address of length %lu",
 				       (unsigned long)name->u.iPAddress.length);
 	break;
     }
     case choice_GeneralName_registeredID: {
-	char *str;
-	hx509_oid_sprint(&name->u.registeredID, &str);
-	if (str =3D=3D NULL)
+	char *oid;
+	hx509_oid_sprint(&name->u.registeredID, &oid);
+	if (oid =3D=3D NULL)
 	    return ENOMEM;
-	strpool =3D rk_strpoolprintf(strpool, "registeredID: %s", str);
-	free(str);
+	strpool =3D rk_strpoolprintf(strpool, "registeredID: %s", oid);
+	free(oid);
 	break;
     }
     default:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/ocsp.asn1
--- a/head/crypto/heimdal/lib/hx509/ocsp.asn1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/ocsp.asn1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 -- From rfc2560
--- $Id: ocsp.asn1 19576 2006-12-30 12:40:43Z lha $
+-- $Id$
 OCSP DEFINITIONS EXPLICIT TAGS::=3D
=20
 BEGIN
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/peer.c
--- a/head/crypto/heimdal/lib/hx509/peer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/peer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,39 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: peer.c 22345 2007-12-26 19:03:51Z lha $");
=20
 /**
  * @page page_peer Hx509 crypto selecting functions
@@ -121,6 +122,40 @@
 }
=20
 /**
+ * Add an additional algorithm that the peer supports.
+ *
+ * @param context A hx509 context.
+ * @param peer the peer to set the new algorithms for
+ * @param val an AlgorithmsIdentier to add
+ *
+ * @return An hx509 error code, see hx509_get_error_string().
+ *
+ * @ingroup hx509_peer
+ */
+
+int
+hx509_peer_info_add_cms_alg(hx509_context context,
+			    hx509_peer_info peer,
+			    const AlgorithmIdentifier *val)
+{
+    void *ptr;
+    int ret;
+
+    ptr =3D realloc(peer->val, sizeof(peer->val[0]) * (peer->len + 1));
+    if (ptr =3D=3D NULL) {
+	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
+	return ENOMEM;
+    }
+    peer->val =3D ptr;
+    ret =3D copy_AlgorithmIdentifier(val, &peer->val[peer->len]);
+    if (ret =3D=3D 0)
+	peer->len +=3D 1;
+    else
+	hx509_set_error_string(context, 0, ret, "out of memory");
+    return ret;
+}
+
+/**
  * Set the algorithms that the peer supports.
  *
  * @param context A hx509 context.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/pkcs10.a=
sn1
--- a/head/crypto/heimdal/lib/hx509/pkcs10.asn1	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hx509/pkcs10.asn1	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
--- $Id: pkcs10.asn1 16918 2006-04-01 09:46:57Z lha $
+-- $Id$
 PKCS10 DEFINITIONS ::=3D
=20
 BEGIN
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/print.c
--- a/head/crypto/heimdal/lib/hx509/print.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/print.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: print.c 22420 2008-01-13 09:42:35Z lha $");
=20
 /**
  * @page page_print Hx509 printing functions
@@ -114,7 +113,7 @@
=20
 /**
  * Print a oid to a string.
- *=20
+ *
  * @param oid oid to print
  * @param str allocated string, free with hx509_xfree().
  *
@@ -132,7 +131,7 @@
 /**
  * Print a oid using a hx509_vprint_func function. To print to stdout
  * use hx509_print_stdout().
- *=20
+ *
  * @param oid oid to print
  * @param func hx509_vprint_func to print with.
  * @param ctx context variable to hx509_vprint_func function.
@@ -152,7 +151,7 @@
 /**
  * Print a bitstring using a hx509_vprint_func function. To print to
  * stdout use hx509_print_stdout().
- *=20
+ *
  * @param b bit string to print.
  * @param func hx509_vprint_func to print with.
  * @param ctx context variable to hx509_vprint_func function.
@@ -164,11 +163,11 @@
 hx509_bitstring_print(const heim_bit_string *b,
 		      hx509_vprint_func func, void *ctx)
 {
-    int i;
+    size_t i;
     print_func(func, ctx, "\tlength: %d\n\t", b->length);
     for (i =3D 0; i < (b->length + 7) / 8; i++)
 	print_func(func, ctx, "%02x%s%s",
-		   ((unsigned char *)b->data)[i],=20
+		   ((unsigned char *)b->data)[i],
 		   i < (b->length - 7) / 8
 		   && (i =3D=3D 0 || (i % 16) !=3D 15) ? ":" : "",
 		   i !=3D 0 && (i % 16) =3D=3D 15 ?
@@ -177,7 +176,7 @@
=20
 /**
  * Print certificate usage for a certificate to a string.
- *=20
+ *
  * @param context A hx509 context.
  * @param c a certificate print the keyusage for.
  * @param s the return string with the keysage printed in to, free
@@ -234,7 +233,7 @@
     va_end(va);
 }
=20
-/*=20
+/*
  * Dont Care, SHOULD critical, SHOULD NOT critical, MUST critical,
  * MUST NOT critical
  */
@@ -275,7 +274,7 @@
 }
=20
 static int
-check_subjectKeyIdentifier(hx509_validate_ctx ctx,=20
+check_subjectKeyIdentifier(hx509_validate_ctx ctx,
 			   struct cert_status *status,
 			   enum critical_flag cf,
 			   const Extension *e)
@@ -287,7 +286,7 @@
     status->haveSKI =3D 1;
     check_Null(ctx, status, cf, e);
=20
-    ret =3D decode_SubjectKeyIdentifier(e->extnValue.data,=20
+    ret =3D decode_SubjectKeyIdentifier(e->extnValue.data,
 				      e->extnValue.length,
 				      &si, &size);
     if (ret) {
@@ -323,7 +322,7 @@
 }
=20
 static int
-check_authorityKeyIdentifier(hx509_validate_ctx ctx,=20
+check_authorityKeyIdentifier(hx509_validate_ctx ctx,
 			     struct cert_status *status,
 			     enum critical_flag cf,
 			     const Extension *e)
@@ -335,10 +334,7 @@
     status->haveAKI =3D 1;
     check_Null(ctx, status, cf, e);
=20
-    status->haveSKI =3D 1;
-    check_Null(ctx, status, cf, e);
-
-    ret =3D decode_AuthorityKeyIdentifier(e->extnValue.data,=20
+    ret =3D decode_AuthorityKeyIdentifier(e->extnValue.data,
 					e->extnValue.length,
 					&ai, &size);
     if (ret) {
@@ -365,6 +361,56 @@
     return 0;
 }
=20
+static int
+check_extKeyUsage(hx509_validate_ctx ctx,
+		  struct cert_status *status,
+		  enum critical_flag cf,
+		  const Extension *e)
+{
+    ExtKeyUsage eku;
+    size_t size, i;
+    int ret;
+
+    check_Null(ctx, status, cf, e);
+
+    ret =3D decode_ExtKeyUsage(e->extnValue.data,
+			     e->extnValue.length,
+			     &eku, &size);
+    if (ret) {
+	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+		       "Decoding ExtKeyUsage failed: %d", ret);
+	return 1;
+    }
+    if (size !=3D e->extnValue.length) {
+	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+		       "Padding data in EKU");
+	free_ExtKeyUsage(&eku);
+	return 1;
+    }
+    if (eku.len =3D=3D 0) {
+	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+		       "ExtKeyUsage length is 0");
+	return 1;
+    }
+
+    for (i =3D 0; i < eku.len; i++) {
+	char *str;
+	ret =3D der_print_heim_oid (&eku.val[i], '.', &str);
+	if (ret) {
+	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
+			   "\tEKU: failed to print oid %d", i);
+	    free_ExtKeyUsage(&eku);
+	    return 1;
+	}
+	validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
+		       "\teku-%d: %s\n", i, str);;
+	free(str);
+    }
+
+    free_ExtKeyUsage(&eku);
+
+    return 0;
+}
=20
 static int
 check_pkinit_san(hx509_validate_ctx ctx, heim_any *a)
@@ -389,7 +435,7 @@
=20
     /* print kerberos principal, add code to quote / within components */
     for (i =3D 0; i < kn.principalName.name_string.len; i++) {
-	validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s",=20
+	validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s",
 		       kn.principalName.name_string.val[i]);
 	if (i + 1 < kn.principalName.name_string.len)
 	    validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "/");
@@ -428,18 +474,19 @@
 }
=20
 static int
-check_CRLDistributionPoints(hx509_validate_ctx ctx,=20
+check_CRLDistributionPoints(hx509_validate_ctx ctx,
 			   struct cert_status *status,
 			   enum critical_flag cf,
 			   const Extension *e)
 {
     CRLDistributionPoints dp;
     size_t size;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     check_Null(ctx, status, cf, e);
=20
-    ret =3D decode_CRLDistributionPoints(e->extnValue.data,=20
+    ret =3D decode_CRLDistributionPoints(e->extnValue.data,
 				       e->extnValue.length,
 				       &dp, &size);
     if (ret) {
@@ -453,12 +500,12 @@
 	if (dp.val[i].distributionPoint) {
 	    DistributionPointName dpname;
 	    heim_any *data =3D dp.val[i].distributionPoint;
-	    int j;
-	   =20
+	    size_t j;
+
 	    ret =3D decode_DistributionPointName(data->data, data->length,
 					       &dpname, NULL);
 	    if (ret) {
-		validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+		validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 			       "Failed to parse CRL Distribution Point Name: %d\n", ret);
 		continue;
 	    }
@@ -466,7 +513,7 @@
 	    switch (dpname.element) {
 	    case choice_DistributionPointName_fullName:
 		validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "Fullname:\n");
-	=09
+
 		for (j =3D 0 ; j < dpname.u.fullName.len; j++) {
 		    char *s;
 		    GeneralName *name =3D &dpname.u.fullName.val[j];
@@ -500,14 +547,14 @@
=20
 struct {
     const char *name;
-    const heim_oid *(*oid)(void);
+    const heim_oid *oid;
     int (*func)(hx509_validate_ctx, heim_any *);
-} check_altname[] =3D {
-    { "pk-init", oid_id_pkinit_san, check_pkinit_san },
-    { "jabber", oid_id_pkix_on_xmppAddr, check_utf8_string_san },
-    { "dns-srv", oid_id_pkix_on_dnsSRV, check_altnull },
-    { "card-id", oid_id_uspkicommon_card_id, check_altnull },
-    { "Microsoft NT-PRINCIPAL-NAME", oid_id_pkinit_ms_san, check_utf8_stri=
ng_san }
+} altname_types[] =3D {
+    { "pk-init", &asn1_oid_id_pkinit_san, check_pkinit_san },
+    { "jabber", &asn1_oid_id_pkix_on_xmppAddr, check_utf8_string_san },
+    { "dns-srv", &asn1_oid_id_pkix_on_dnsSRV, check_altnull },
+    { "card-id", &asn1_oid_id_uspkicommon_card_id, check_altnull },
+    { "Microsoft NT-PRINCIPAL-NAME", &asn1_oid_id_pkinit_ms_san, check_utf=
8_string_san }
 };
=20
 static int
@@ -519,7 +566,8 @@
 {
     GeneralNames gn;
     size_t size;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     check_Null(ctx, status, cf, e);
=20
@@ -532,7 +580,7 @@
 			      &gn, &size);
     if (ret) {
 	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
-		       "\tret =3D %d while decoding %s GeneralNames\n",=20
+		       "\tret =3D %d while decoding %s GeneralNames\n",
 		       ret, name);
 	return 1;
     }
@@ -550,17 +598,17 @@
 	    validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
 			   "%sAltName otherName ", name);
=20
-	    for (j =3D 0; j < sizeof(check_altname)/sizeof(check_altname[0]); j++=
) {
-		if (der_heim_oid_cmp((*check_altname[j].oid)(),=20
+	    for (j =3D 0; j < sizeof(altname_types)/sizeof(altname_types[0]); j++=
) {
+		if (der_heim_oid_cmp(altname_types[j].oid,
 				     &gn.val[i].u.otherName.type_id) !=3D 0)
 		    continue;
-	=09
-		validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s: ",=20
-			       check_altname[j].name);
-		(*check_altname[j].func)(ctx, &gn.val[i].u.otherName.value);
+
+		validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "%s: ",
+			       altname_types[j].name);
+		(*altname_types[j].func)(ctx, &gn.val[i].u.otherName.value);
 		break;
 	    }
-	    if (j =3D=3D sizeof(check_altname)/sizeof(check_altname[0])) {
+	    if (j =3D=3D sizeof(altname_types)/sizeof(altname_types[0])) {
 		hx509_oid_print(&gn.val[i].u.otherName.type_id,
 				validate_vprint, ctx);
 		validate_print(ctx, HX509_VALIDATE_F_VERBOSE, " unknown");
@@ -610,9 +658,9 @@
=20
=20
 static int
-check_basicConstraints(hx509_validate_ctx ctx,=20
+check_basicConstraints(hx509_validate_ctx ctx,
 		       struct cert_status *status,
-		       enum critical_flag cf,=20
+		       enum critical_flag cf,
 		       const Extension *e)
 {
     BasicConstraints b;
@@ -620,7 +668,7 @@
     int ret;
=20
     check_Null(ctx, status, cf, e);
-   =20
+
     ret =3D decode_BasicConstraints(e->extnValue.data, e->extnValue.length,
 				  &b, &size);
     if (ret) {
@@ -653,9 +701,9 @@
 }
=20
 static int
-check_proxyCertInfo(hx509_validate_ctx ctx,=20
+check_proxyCertInfo(hx509_validate_ctx ctx,
 		    struct cert_status *status,
-		    enum critical_flag cf,=20
+		    enum critical_flag cf,
 		    const Extension *e)
 {
     check_Null(ctx, status, cf, e);
@@ -664,18 +712,19 @@
 }
=20
 static int
-check_authorityInfoAccess(hx509_validate_ctx ctx,=20
+check_authorityInfoAccess(hx509_validate_ctx ctx,
 			  struct cert_status *status,
-			  enum critical_flag cf,=20
+			  enum critical_flag cf,
 			  const Extension *e)
 {
     AuthorityInfoAccessSyntax aia;
     size_t size;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     check_Null(ctx, status, cf, e);
=20
-    ret =3D decode_AuthorityInfoAccessSyntax(e->extnValue.data,=20
+    ret =3D decode_AuthorityInfoAccessSyntax(e->extnValue.data,
 					   e->extnValue.length,
 					   &aia, &size);
     if (ret) {
@@ -704,14 +753,14 @@
=20
 struct {
     const char *name;
-    const heim_oid *(*oid)(void);
-    int (*func)(hx509_validate_ctx ctx,=20
+    const heim_oid *oid;
+    int (*func)(hx509_validate_ctx ctx,
 		struct cert_status *status,
-		enum critical_flag cf,=20
+		enum critical_flag cf,
 		const Extension *);
     enum critical_flag cf;
 } check_extension[] =3D {
-#define ext(name, checkname) #name, &oid_id_x509_ce_##name, check_##checkn=
ame=20
+#define ext(name, checkname) #name, &asn1_oid_id_x509_ce_##name, check_##c=
heckname
     { ext(subjectDirectoryAttributes, Null), M_N_C },
     { ext(subjectKeyIdentifier, subjectKeyIdentifier), M_N_C },
     { ext(keyUsage, Null), S_C },
@@ -727,28 +776,28 @@
     { ext(certificateIssuer, Null), M_C },
     { ext(nameConstraints, Null), M_C },
     { ext(cRLDistributionPoints, CRLDistributionPoints), S_N_C },
-    { ext(certificatePolicies, Null) },
+    { ext(certificatePolicies, Null), 0 },
     { ext(policyMappings, Null), M_N_C },
     { ext(authorityKeyIdentifier, authorityKeyIdentifier), M_N_C },
     { ext(policyConstraints, Null), D_C },
-    { ext(extKeyUsage, Null), D_C },
+    { ext(extKeyUsage, extKeyUsage), D_C },
     { ext(freshestCRL, Null), M_N_C },
     { ext(inhibitAnyPolicy, Null), M_C },
 #undef ext
-#define ext(name, checkname) #name, &oid_id_pkix_pe_##name, check_##checkn=
ame=20
+#define ext(name, checkname) #name, &asn1_oid_id_pkix_pe_##name, check_##c=
heckname
     { ext(proxyCertInfo, proxyCertInfo), M_C },
     { ext(authorityInfoAccess, authorityInfoAccess), M_C },
 #undef ext
-    { "US Fed PKI - PIV Interim", oid_id_uspkicommon_piv_interim,=20
+    { "US Fed PKI - PIV Interim", &asn1_oid_id_uspkicommon_piv_interim,
       check_Null, D_C },
-    { "Netscape cert comment", oid_id_netscape_cert_comment,=20
+    { "Netscape cert comment", &asn1_oid_id_netscape_cert_comment,
       check_Null, D_C },
-    { NULL }
+    { NULL, NULL, NULL, 0 }
 };
=20
 /**
  * Allocate a hx509 validation/printing context.
- *=20
+ *
  * @param context A hx509 context.
  * @param ctx a new allocated hx509 validation context, free with
  * hx509_validate_ctx_free().
@@ -770,7 +819,7 @@
=20
 /**
  * Set the printing functions for the validation context.
- *=20
+ *
  * @param ctx a hx509 valication context.
  * @param func the printing function to usea.
  * @param c the context variable to the printing function.
@@ -781,7 +830,7 @@
  */
=20
 void
-hx509_validate_ctx_set_print(hx509_validate_ctx ctx,=20
+hx509_validate_ctx_set_print(hx509_validate_ctx ctx,
 			     hx509_vprint_func func,
 			     void *c)
 {
@@ -792,7 +841,7 @@
 /**
  * Add flags to control the behaivor of the hx509_validate_cert()
  * function.
- *=20
+ *
  * @param ctx A hx509 validation context.
  * @param flags flags to add to the validation context.
  *
@@ -809,7 +858,7 @@
=20
 /**
  * Free an hx509 validate context.
- *=20
+ *
  * @param ctx the hx509 validate context to free.
  *
  * @ingroup hx509_print
@@ -823,7 +872,7 @@
=20
 /**
  * Validate/Print the status of the certificate.
- *=20
+ *
  * @param context A hx509 context.
  * @param ctx A hx509 validation context.
  * @param cert the cerificate to validate/print.
@@ -850,11 +899,11 @@
     if (_hx509_cert_get_version(c) !=3D 3)
 	validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
 		       "Not version 3 certificate\n");
-   =20
+
     if ((t->version =3D=3D NULL || *t->version < 2) && t->extensions)
 	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 		       "Not version 3 certificate with extensions\n");
-=09
+
     if (_hx509_cert_get_version(c) >=3D 3 && t->extensions =3D=3D NULL)
 	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 		       "Version 3 certificate without extensions\n");
@@ -890,7 +939,7 @@
     free(str);
=20
     if (t->extensions) {
-	int i, j;
+	size_t i, j;
=20
 	if (t->extensions->len =3D=3D 0) {
 	    validate_print(ctx,
@@ -902,7 +951,7 @@
 	for (i =3D 0; i < t->extensions->len; i++) {
=20
 	    for (j =3D 0; check_extension[j].name; j++)
-		if (der_heim_oid_cmp((*check_extension[j].oid)(),
+		if (der_heim_oid_cmp(check_extension[j].oid,
 				     &t->extensions->val[i].extnID) =3D=3D 0)
 		    break;
 	    if (check_extension[j].name =3D=3D NULL) {
@@ -913,7 +962,7 @@
 		if (t->extensions->val[i].critical)
 		    validate_print(ctx, flags, "and is CRITICAL ");
 		if (ctx->flags & flags)
-		    hx509_oid_print(&t->extensions->val[i].extnID,=20
+		    hx509_oid_print(&t->extensions->val[i].extnID,
 				    validate_vprint, ctx);
 		validate_print(ctx, flags, " is\n");
 		continue;
@@ -929,57 +978,57 @@
 	}
     } else
 	validate_print(ctx, HX509_VALIDATE_F_VERBOSE, "no extentions\n");
-=09
+
     if (status.isca) {
 	if (!status.haveSKI)
-	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 			   "CA certificate have no SubjectKeyIdentifier\n");
=20
     } else {
 	if (!status.haveAKI)
-	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 			   "Is not CA and doesn't have "
 			   "AuthorityKeyIdentifier\n");
     }
-	   =20
+
=20
     if (!status.haveSKI)
-	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 		       "Doesn't have SubjectKeyIdentifier\n");
=20
     if (status.isproxy && status.isca)
-	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 		       "Proxy and CA at the same time!\n");
=20
     if (status.isproxy) {
 	if (status.haveSAN)
-	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 			   "Proxy and have SAN\n");
 	if (status.haveIAN)
-	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 			   "Proxy and have IAN\n");
     }
=20
     if (hx509_name_is_null_p(subject) && !status.haveSAN)
-	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 		       "NULL subject DN and doesn't have a SAN\n");
=20
     if (!status.selfsigned && !status.haveCRLDP)
-	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 		       "Not a CA nor PROXY and doesn't have"
 		       "CRL Dist Point\n");
=20
     if (status.selfsigned) {
 	ret =3D _hx509_verify_signature_bitstring(context,
-						c,
+						cert,
 						&c->signatureAlgorithm,
 						&c->tbsCertificate._save,
 						&c->signatureValue);
 	if (ret =3D=3D 0)
-	    validate_print(ctx, HX509_VALIDATE_F_VERBOSE,=20
+	    validate_print(ctx, HX509_VALIDATE_F_VERBOSE,
 			   "Self-signed certificate was self-signed\n");
 	else
-	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,=20
+	    validate_print(ctx, HX509_VALIDATE_F_VALIDATE,
 			   "Self-signed certificate NOT really self-signed!\n");
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/req.c
--- a/head/crypto/heimdal/lib/hx509/req.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/req.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,38 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
 #include <pkcs10_asn1.h>
-RCSID("$Id: req.c 21344 2007-06-26 14:22:34Z lha $");
=20
 struct hx509_request_data {
     hx509_name name;
@@ -47,7 +46,7 @@
  */
=20
 int
-_hx509_request_init(hx509_context context, hx509_request *req)
+hx509_request_init(hx509_context context, hx509_request *req)
 {
     *req =3D calloc(1, sizeof(**req));
     if (*req =3D=3D NULL)
@@ -57,7 +56,7 @@
 }
=20
 void
-_hx509_request_free(hx509_request *req)
+hx509_request_free(hx509_request *req)
 {
     if ((*req)->name)
 	hx509_name_free(&(*req)->name);
@@ -70,7 +69,7 @@
 }
=20
 int
-_hx509_request_set_name(hx509_context context,
+hx509_request_set_name(hx509_context context,
 			hx509_request req,
 			hx509_name name)
 {
@@ -85,7 +84,7 @@
 }
=20
 int
-_hx509_request_get_name(hx509_context context,
+hx509_request_get_name(hx509_context context,
 			hx509_request req,
 			hx509_name *name)
 {
@@ -97,7 +96,7 @@
 }
=20
 int
-_hx509_request_set_SubjectPublicKeyInfo(hx509_context context,
+hx509_request_set_SubjectPublicKeyInfo(hx509_context context,
 					hx509_request req,
 					const SubjectPublicKeyInfo *key)
 {
@@ -106,7 +105,7 @@
 }
=20
 int
-_hx509_request_get_SubjectPublicKeyInfo(hx509_context context,
+hx509_request_get_SubjectPublicKeyInfo(hx509_context context,
 					hx509_request req,
 					SubjectPublicKeyInfo *key)
 {
@@ -144,7 +143,8 @@
=20
     memset(&name, 0, sizeof(name));
     name.element =3D choice_GeneralName_dNSName;
-    name.u.dNSName =3D rk_UNCONST(hostname);
+    name.u.dNSName.data =3D rk_UNCONST(hostname);
+    name.u.dNSName.length =3D strlen(hostname);
=20
     return add_GeneralNames(&req->san, &name);
 }
@@ -158,7 +158,8 @@
=20
     memset(&name, 0, sizeof(name));
     name.element =3D choice_GeneralName_rfc822Name;
-    name.u.dNSName =3D rk_UNCONST(email);
+    name.u.dNSName.data =3D rk_UNCONST(email);
+    name.u.dNSName.length =3D strlen(email);
=20
     return add_GeneralNames(&req->san, &name);
 }
@@ -195,14 +196,14 @@
 				    &r.certificationRequestInfo.subjectPKInfo);
     if (ret)
 	goto out;
-    r.certificationRequestInfo.attributes =3D=20
+    r.certificationRequestInfo.attributes =3D
 	calloc(1, sizeof(*r.certificationRequestInfo.attributes));
     if (r.certificationRequestInfo.attributes =3D=3D NULL) {
 	ret =3D ENOMEM;
 	goto out;
     }
=20
-    ASN1_MALLOC_ENCODE(CertificationRequestInfo, data.data, data.length,=20
+    ASN1_MALLOC_ENCODE(CertificationRequestInfo, data.data, data.length,
 		       &r.certificationRequestInfo, &size, ret);
     if (ret)
 	goto out;
@@ -237,7 +238,7 @@
 }
=20
 int
-_hx509_request_parse(hx509_context context,=20
+_hx509_request_parse(hx509_context context,
 		     const char *path,
 		     hx509_request *req)
 {
@@ -257,20 +258,20 @@
=20
     /* XXX PEM request */
=20
-    ret =3D _hx509_map_file(path, &p, &len, NULL);
+    ret =3D rk_undumpdata(path, &p, &len);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "Failed to map file %s", path);
 	return ret;
     }
=20
     ret =3D decode_CertificationRequest(p, len, &r, &size);
-    _hx509_unmap_file(p, len);
+    rk_xfree(p);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "Failed to decode %s", path);
 	return ret;
     }
=20
-    ret =3D _hx509_request_init(context, req);
+    ret =3D hx509_request_init(context, req);
     if (ret) {
 	free_CertificationRequest(&r);
 	return ret;
@@ -278,25 +279,25 @@
=20
     rinfo =3D &r.certificationRequestInfo;
=20
-    ret =3D _hx509_request_set_SubjectPublicKeyInfo(context, *req,
+    ret =3D hx509_request_set_SubjectPublicKeyInfo(context, *req,
 						  &rinfo->subjectPKInfo);
     if (ret) {
 	free_CertificationRequest(&r);
-	_hx509_request_free(req);
+	hx509_request_free(req);
 	return ret;
     }
=20
     ret =3D _hx509_name_from_Name(&rinfo->subject, &subject);
     if (ret) {
 	free_CertificationRequest(&r);
-	_hx509_request_free(req);
+	hx509_request_free(req);
 	return ret;
     }
-    ret =3D _hx509_request_set_name(context, *req, subject);
+    ret =3D hx509_request_set_name(context, *req, subject);
     hx509_name_free(&subject);
     free_CertificationRequest(&r);
     if (ret) {
-	_hx509_request_free(req);
+	hx509_request_free(req);
 	return ret;
     }
=20
@@ -319,7 +320,7 @@
         fprintf(f, "name: %s\n", subject);
 	free(subject);
     }
-   =20
+
     return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/revoke.c
--- a/head/crypto/heimdal/lib/hx509/revoke.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/revoke.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /**
@@ -50,7 +50,6 @@
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: revoke.c 22275 2007-12-11 11:02:11Z lha $");
=20
 struct revoke_crl {
     char *path;
@@ -70,7 +69,7 @@
=20
=20
 struct hx509_revoke_ctx_data {
-    unsigned ref;
+    unsigned int ref;
     struct {
 	struct revoke_crl *val;
 	size_t len;
@@ -113,11 +112,11 @@
 {
     if (ctx =3D=3D NULL)
 	return NULL;
-    if (ctx->ref <=3D 0)
-	_hx509_abort("revoke ctx refcount <=3D 0");
+    if (ctx->ref =3D=3D 0)
+	_hx509_abort("revoke ctx refcount =3D=3D 0 on ref");
     ctx->ref++;
-    if (ctx->ref =3D=3D 0)
-	_hx509_abort("revoke ctx refcount =3D=3D 0");
+    if (ctx->ref =3D=3D UINT_MAX)
+	_hx509_abort("revoke ctx refcount =3D=3D UINT_MAX on ref");
     return ctx;
 }
=20
@@ -146,8 +145,8 @@
     if (ctx =3D=3D NULL || *ctx =3D=3D NULL)
 	return;
=20
-    if ((*ctx)->ref <=3D 0)
-	_hx509_abort("revoke ctx refcount <=3D 0 on free");
+    if ((*ctx)->ref =3D=3D 0)
+	_hx509_abort("revoke ctx refcount =3D=3D 0 on free");
     if (--(*ctx)->ref > 0)
 	return;
=20
@@ -177,9 +176,9 @@
     hx509_cert signer =3D NULL;
     hx509_query q;
     int ret;
-=09
+
     _hx509_query_clear(&q);
-=09
+
     /*
      * Need to match on issuer too in case there are two CA that have
      * issued the same name to a certificate. One example of this is
@@ -199,7 +198,7 @@
 	q.keyhash_sha1 =3D &ocsp->ocsp.tbsResponseData.responderID.u.byKey;
 	break;
     }
-=09
+
     ret =3D hx509_certs_find(context, certs, &q, &signer);
     if (ret && ocsp->certs)
 	ret =3D hx509_certs_find(context, ocsp->certs, &q, &signer);
@@ -218,36 +217,36 @@
 	ret =3D _hx509_cert_is_parent_cmp(s, p, 0);
 	if (ret !=3D 0) {
 	    ret =3D HX509_PARENT_NOT_CA;
-	    hx509_set_error_string(context, 0, ret, "Revoke OSCP signer is "
+	    hx509_set_error_string(context, 0, ret, "Revoke OCSP signer is "
 				   "doesn't have CA as signer certificate");
 	    goto out;
 	}
=20
 	ret =3D _hx509_verify_signature_bitstring(context,
-						p,
+						parent,
 						&s->signatureAlgorithm,
 						&s->tbsCertificate._save,
 						&s->signatureValue);
 	if (ret) {
 	    hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
-				   "OSCP signer signature invalid");
+				   "OCSP signer signature invalid");
 	    goto out;
 	}
=20
-	ret =3D hx509_cert_check_eku(context, signer,=20
-				   oid_id_pkix_kp_OCSPSigning(), 0);
+	ret =3D hx509_cert_check_eku(context, signer,
+				   &asn1_oid_id_pkix_kp_OCSPSigning, 0);
 	if (ret)
 	    goto out;
     }
=20
     ret =3D _hx509_verify_signature_bitstring(context,
-					    _hx509_get_cert(signer),=20
+					    signer,
 					    &ocsp->ocsp.signatureAlgorithm,
 					    &ocsp->ocsp.tbsResponseData._save,
 					    &ocsp->ocsp.signature);
     if (ret) {
-	hx509_set_error_string(context, HX509_ERROR_APPEND, ret,=20
-			       "OSCP signature invalid");
+	hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
+			       "OCSP signature invalid");
 	goto out;
     }
=20
@@ -294,8 +293,8 @@
 	return EINVAL;
     }
=20
-    ret =3D der_heim_oid_cmp(&resp.responseBytes->responseType,=20
-			   oid_id_pkix_ocsp_basic());
+    ret =3D der_heim_oid_cmp(&resp.responseBytes->responseType,
+			   &asn1_oid_id_pkix_ocsp_basic);
     if (ret !=3D 0) {
 	free_OCSPResponse(&resp);
 	return HX509_REVOKE_WRONG_DATA;
@@ -333,12 +332,16 @@
     void *data;
     int ret;
=20
-    ret =3D _hx509_map_file(ocsp->path, &data, &length, &sb);
+    ret =3D rk_undumpdata(ocsp->path, &data, &length);
     if (ret)
 	return ret;
=20
+    ret =3D stat(ocsp->path, &sb);
+    if (ret)
+	return errno;
+
     ret =3D parse_ocsp_basic(data, length, &basic);
-    _hx509_unmap_file(data, length);
+    rk_xfree(data);
     if (ret) {
 	hx509_set_error_string(context, 0, ret,
 			       "Failed to parse OCSP response");
@@ -346,9 +349,9 @@
     }
=20
     if (basic.certs) {
-	int i;
+	size_t i;
=20
-	ret =3D hx509_certs_init(context, "MEMORY:ocsp-certs", 0,=20
+	ret =3D hx509_certs_init(context, "MEMORY:ocsp-certs", 0,
 			       NULL, &certs);
 	if (ret) {
 	    free_OCSPBasicOCSPResponse(&basic);
@@ -357,11 +360,11 @@
=20
 	for (i =3D 0; i < basic.certs->len; i++) {
 	    hx509_cert c;
-	   =20
+
 	    ret =3D hx509_cert_init(context, &basic.certs->val[i], &c);
 	    if (ret)
 		continue;
-	   =20
+
 	    ret =3D hx509_certs_add(context, certs, c);
 	    hx509_cert_free(c);
 	    if (ret)
@@ -416,7 +419,7 @@
 	    return 0;
     }
=20
-    data =3D realloc(ctx->ocsps.val,=20
+    data =3D realloc(ctx->ocsps.val,
 		   (ctx->ocsps.len + 1) * sizeof(ctx->ocsps.val[0]));
     if (data =3D=3D NULL) {
 	hx509_clear_error_string(context);
@@ -425,7 +428,7 @@
=20
     ctx->ocsps.val =3D data;
=20
-    memset(&ctx->ocsps.val[ctx->ocsps.len], 0,=20
+    memset(&ctx->ocsps.val[ctx->ocsps.len], 0,
 	   sizeof(ctx->ocsps.val[0]));
=20
     ctx->ocsps.val[ctx->ocsps.len].path =3D strdup(path);
@@ -460,7 +463,7 @@
     hx509_query q;
     time_t t;
     int ret;
-=09
+
     t =3D _hx509_Time2time_t(&crl->tbsCertList.thisUpdate);
     if (t > time_now) {
 	hx509_set_error_string(context, 0, HX509_CRL_USED_BEFORE_TIME,
@@ -482,7 +485,7 @@
     }
=20
     _hx509_query_clear(&q);
-=09
+
     /*
      * If it's the signer have CRLSIGN bit set, use that as the signer
      * cert for the certificate, otherwise, search for a certificate.
@@ -493,7 +496,7 @@
 	q.match =3D HX509_QUERY_MATCH_SUBJECT_NAME;
 	q.match |=3D HX509_QUERY_KU_CRLSIGN;
 	q.subject_name =3D &crl->tbsCertList.issuer;
-=09
+
 	ret =3D hx509_certs_find(context, certs, &q, &signer);
 	if (ret) {
 	    hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
@@ -503,7 +506,7 @@
     }
=20
     ret =3D _hx509_verify_signature_bitstring(context,
-					    _hx509_get_cert(signer),=20
+					    signer,
 					    &crl->signatureAlgorithm,
 					    &crl->tbsCertList._save,
 					    &crl->signatureValue);
@@ -513,7 +516,7 @@
 	goto out;
     }
=20
-    /*=20
+    /*
      * If signer is not CA cert, need to check revoke status of this
      * CRL signing cert too, this include all parent CRL signer cert
      * up to the root *sigh*, assume root at least hve CERTSIGN flag
@@ -523,11 +526,11 @@
 	hx509_cert crl_parent;
=20
 	_hx509_query_clear(&q);
-=09
+
 	q.match =3D HX509_QUERY_MATCH_SUBJECT_NAME;
 	q.match |=3D HX509_QUERY_KU_CRLSIGN;
 	q.subject_name =3D &_hx509_get_cert(signer)->tbsCertificate.issuer;
-=09
+
 	ret =3D hx509_certs_find(context, certs, &q, &crl_parent);
 	if (ret) {
 	    hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
@@ -536,7 +539,7 @@
 	}
=20
 	ret =3D hx509_revoke_verify(context,
-				  ctx,=20
+				  ctx,
 				  certs,
 				  time_now,
 				  signer,
@@ -567,14 +570,18 @@
=20
     memset(crl, 0, sizeof(*crl));
=20
-    ret =3D _hx509_map_file(path, &data, &length, &sb);
+    ret =3D rk_undumpdata(path, &data, &length);
     if (ret)
 	return ret;
=20
+    ret =3D stat(path, &sb);
+    if (ret)
+	return errno;
+
     *t =3D sb.st_mtime;
=20
     ret =3D decode_CRLCertificateList(data, length, crl, &size);
-    _hx509_unmap_file(data, length);
+    rk_xfree(data);
     if (ret)
 	return ret;
=20
@@ -613,7 +620,7 @@
 	return HX509_UNSUPPORTED_OPERATION;
     }
=20
-   =20
+
     path +=3D 5;
=20
     for (i =3D 0; i < ctx->crls.len; i++) {
@@ -621,7 +628,7 @@
 	    return 0;
     }
=20
-    data =3D realloc(ctx->crls.val,=20
+    data =3D realloc(ctx->crls.val,
 		   (ctx->crls.len + 1) * sizeof(ctx->crls.val[0]));
     if (data =3D=3D NULL) {
 	hx509_clear_error_string(context);
@@ -637,7 +644,7 @@
 	return ENOMEM;
     }
=20
-    ret =3D load_crl(path,=20
+    ret =3D load_crl(path,
 		   &ctx->crls.val[ctx->crls.len].last_modfied,
 		   &ctx->crls.val[ctx->crls.len].crl);
     if (ret) {
@@ -711,7 +718,7 @@
 				   &c->tbsCertificate.serialNumber);
 	    if (ret !=3D 0)
 		continue;
-	   =20
+
 	    /* verify issuer hashes hash */
 	    ret =3D _hx509_verify_signature(context,
 					  NULL,
@@ -736,7 +743,7 @@
 	    case choice_OCSPCertStatus_good:
 		break;
 	    case choice_OCSPCertStatus_revoked:
-		hx509_set_error_string(context, 0,=20
+		hx509_set_error_string(context, 0,
 				       HX509_CERT_REVOKED,
 				       "Certificate revoked by issuer in OCSP");
 		return HX509_CERT_REVOKED;
@@ -745,7 +752,7 @@
 	    }
=20
 	    /* don't allow the update to be in the future */
-	    if (ocsp->ocsp.tbsResponseData.responses.val[j].thisUpdate >=20
+	    if (ocsp->ocsp.tbsResponseData.responses.val[j].thisUpdate >
 		now + context->ocsp_time_diff)
 		continue;
=20
@@ -753,8 +760,7 @@
 	    if (ocsp->ocsp.tbsResponseData.responses.val[j].nextUpdate) {
 		if (*ocsp->ocsp.tbsResponseData.responses.val[j].nextUpdate < now)
 		    continue;
-	    } else
-		/* Should force a refetch, but can we ? */;
+	    } /* else should force a refetch, but can we ? */
=20
 	    return 0;
 	}
@@ -763,11 +769,12 @@
     for (i =3D 0; i < ctx->crls.len; i++) {
 	struct revoke_crl *crl =3D &ctx->crls.val[i];
 	struct stat sb;
+	int diff;
=20
 	/* check if cert.issuer =3D=3D crls.val[i].crl.issuer */
-	ret =3D _hx509_name_cmp(&c->tbsCertificate.issuer,=20
-			      &crl->crl.tbsCertList.issuer);
-	if (ret)
+	ret =3D _hx509_name_cmp(&c->tbsCertificate.issuer,
+			      &crl->crl.tbsCertList.issuer, &diff);
+	if (ret || diff)
 	    continue;
=20
 	ret =3D stat(crl->path, &sb);
@@ -798,7 +805,7 @@
 	if (crl->crl.tbsCertList.crlExtensions) {
 	    for (j =3D 0; j < crl->crl.tbsCertList.crlExtensions->len; j++) {
 		if (crl->crl.tbsCertList.crlExtensions->val[j].critical) {
-		    hx509_set_error_string(context, 0,=20
+		    hx509_set_error_string(context, 0,
 					   HX509_CRL_UNKNOWN_EXTENSION,
 					   "Unknown CRL extension");
 		    return HX509_CRL_UNKNOWN_EXTENSION;
@@ -821,13 +828,13 @@
 	    t =3D _hx509_Time2time_t(&crl->crl.tbsCertList.revokedCertificates->v=
al[j].revocationDate);
 	    if (t > now)
 		continue;
-	   =20
+
 	    if (crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensio=
ns)
 		for (k =3D 0; k < crl->crl.tbsCertList.revokedCertificates->val[j].crlEn=
tryExtensions->len; k++)
 		    if (crl->crl.tbsCertList.revokedCertificates->val[j].crlEntryExtensi=
ons->val[k].critical)
 			return HX509_CRL_UNKNOWN_EXTENSION;
-	   =20
-	    hx509_set_error_string(context, 0,=20
+
+	    hx509_set_error_string(context, 0,
 				   HX509_CERT_REVOKED,
 				   "Certificate revoked by issuer in CRL");
 	    return HX509_CERT_REVOKED;
@@ -839,7 +846,7 @@
=20
     if (context->flags & HX509_CTX_VERIFY_MISSING_OK)
 	return 0;
-    hx509_set_error_string(context, HX509_ERROR_APPEND,=20
+    hx509_set_error_string(context, HX509_ERROR_APPEND,
 			   HX509_REVOKE_STATUS_MISSING,
 			   "No revoke status found for "
 			   "certificates");
@@ -865,13 +872,13 @@
     hx509_query q;
     void *d;
=20
-    d =3D realloc(ctx->req->requestList.val,=20
+    d =3D realloc(ctx->req->requestList.val,
 		sizeof(ctx->req->requestList.val[0]) *
 		(ctx->req->requestList.len + 1));
     if (d =3D=3D NULL)
 	return ENOMEM;
     ctx->req->requestList.val =3D d;
-   =20
+
     one =3D &ctx->req->requestList.val[ctx->req->requestList.len];
     memset(one, 0, sizeof(*one));
=20
@@ -911,7 +918,7 @@
 	goto out;
=20
     os.data =3D p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.da=
ta;
-    os.length =3D=20
+    os.length =3D
 	p->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
=20
     ret =3D _hx509_create_signature(context,
@@ -981,13 +988,13 @@
     ctx.digest =3D digest;
     ctx.parent =3D NULL;
=20
-    ret =3D hx509_certs_iter(context, reqcerts, add_to_req, &ctx);
+    ret =3D hx509_certs_iter_f(context, reqcerts, add_to_req, &ctx);
     hx509_cert_free(ctx.parent);
     if (ret)
 	goto out;
-   =20
+
     if (nonce) {
-	req.tbsRequest.requestExtensions =3D=20
+	req.tbsRequest.requestExtensions =3D
 	    calloc(1, sizeof(*req.tbsRequest.requestExtensions));
 	if (req.tbsRequest.requestExtensions =3D=3D NULL) {
 	    ret =3D ENOMEM;
@@ -995,15 +1002,14 @@
 	}
=20
 	es =3D req.tbsRequest.requestExtensions;
-=09
+
 	es->val =3D calloc(es->len, sizeof(es->val[0]));
 	if (es->val =3D=3D NULL) {
 	    ret =3D ENOMEM;
 	    goto out;
 	}
 	es->len =3D 1;
-=09
-	ret =3D der_copy_oid(oid_id_pkix_ocsp_nonce(), &es->val[0].extnID);
+	ret =3D der_copy_oid(&asn1_oid_id_pkix_ocsp_nonce, &es->val[0].extnID);
 	if (ret) {
 	    free_OCSPRequest(&req);
 	    return ret;
@@ -1015,7 +1021,7 @@
 	    goto out;
 	}
 	es->val[0].extnValue.length =3D 10;
-=09
+
 	ret =3D RAND_bytes(es->val[0].extnValue.data,
 			 es->val[0].extnValue.length);
 	if (ret !=3D 1) {
@@ -1048,8 +1054,13 @@
 printable_time(time_t t)
 {
     static char s[128];
-    strlcpy(s, ctime(&t)+ 4, sizeof(s));
-    s[20] =3D 0;
+    char *p;
+    if ((p =3D ctime(&t)) =3D=3D NULL)
+       strlcpy(s, "?", sizeof(s));
+    else {
+       strlcpy(s, p + 4, sizeof(s));
+       s[20] =3D 0;
+    }
     return s;
 }
=20
@@ -1069,8 +1080,9 @@
 hx509_revoke_ocsp_print(hx509_context context, const char *path, FILE *out)
 {
     struct revoke_ocsp ocsp;
-    int ret, i;
-   =20
+    int ret;
+    size_t i;
+
     if (out =3D=3D NULL)
 	out =3D stdout;
=20
@@ -1113,7 +1125,7 @@
 	break;
     }
=20
-    fprintf(out, "producedAt: %s\n",=20
+    fprintf(out, "producedAt: %s\n",
 	    printable_time(ocsp.ocsp.tbsResponseData.producedAt));
=20
     fprintf(out, "replies: %d\n", ocsp.ocsp.tbsResponseData.responses.len);
@@ -1134,19 +1146,19 @@
 	    status =3D "element unknown";
 	}
=20
-	fprintf(out, "\t%d. status: %s\n", i, status);
+	fprintf(out, "\t%zu. status: %s\n", i, status);
=20
-	fprintf(out, "\tthisUpdate: %s\n",=20
+	fprintf(out, "\tthisUpdate: %s\n",
 		printable_time(ocsp.ocsp.tbsResponseData.responses.val[i].thisUpdate));
 	if (ocsp.ocsp.tbsResponseData.responses.val[i].nextUpdate)
-	    fprintf(out, "\tproducedAt: %s\n",=20
+	    fprintf(out, "\tproducedAt: %s\n",
 		    printable_time(ocsp.ocsp.tbsResponseData.responses.val[i].thisUpdate=
));
=20
     }
=20
     fprintf(out, "appended certs:\n");
     if (ocsp.certs)
-	ret =3D hx509_certs_iter(context, ocsp.certs, hx509_ci_print_names, out);
+	ret =3D hx509_certs_iter_f(context, ocsp.certs, hx509_ci_print_names, out=
);
=20
     free_ocsp(&ocsp);
     return ret;
@@ -1181,7 +1193,8 @@
 {
     const Certificate *c =3D _hx509_get_cert(cert);
     OCSPBasicOCSPResponse basic;
-    int ret, i;
+    int ret;
+    size_t i;
=20
     if (now =3D=3D 0)
 	now =3D time(NULL);
@@ -1201,7 +1214,7 @@
 			       &c->tbsCertificate.serialNumber);
 	if (ret !=3D 0)
 	    continue;
-	   =20
+
 	/* verify issuer hashes hash */
 	ret =3D _hx509_verify_signature(context,
 				      NULL,
@@ -1220,7 +1233,7 @@
 	}
=20
 	/* don't allow the update to be in the future */
-	if (basic.tbsResponseData.responses.val[i].thisUpdate >=20
+	if (basic.tbsResponseData.responses.val[i].thisUpdate >
 	    now + context->ocsp_time_diff)
 	    continue;
=20
@@ -1241,7 +1254,7 @@
     {
 	hx509_name name;
 	char *subject;
-=09
+
 	ret =3D hx509_cert_get_subject(cert, &name);
 	if (ret) {
 	    hx509_clear_error_string(context);
@@ -1314,7 +1327,7 @@
=20
 int
 hx509_crl_add_revoked_certs(hx509_context context,
-			    hx509_crl crl,=20
+			    hx509_crl crl,
 			    hx509_certs certs)
 {
     return hx509_certs_merge(context, crl->revoked, certs);
@@ -1377,13 +1390,13 @@
     }
     c->revokedCertificates->val =3D ptr;
=20
-    ret =3D hx509_cert_get_serialnumber(cert,=20
+    ret =3D hx509_cert_get_serialnumber(cert,
 				      &c->revokedCertificates->val[num].userCertificate);
     if (ret) {
 	hx509_clear_error_string(context);
 	return ret;
     }
-    c->revokedCertificates->val[num].revocationDate.element =3D=20
+    c->revokedCertificates->val[num].revocationDate.element =3D
 	choice_Time_generalTime;
     c->revokedCertificates->val[num].revocationDate.u.generalTime =3D
 	time(NULL) - 3600 * 24;
@@ -1392,7 +1405,7 @@
     c->revokedCertificates->len++;
=20
     return 0;
-}   =20
+}
=20
 /**
  * Sign a CRL and return an encode certificate.
@@ -1470,7 +1483,7 @@
 	c.tbsCertList.nextUpdate->u.generalTime =3D next;
     }
=20
-    c.tbsCertList.revokedCertificates =3D=20
+    c.tbsCertList.revokedCertificates =3D
 	calloc(1, sizeof(*c.tbsCertList.revokedCertificates));
     if (c.tbsCertList.revokedCertificates =3D=3D NULL) {
 	hx509_set_error_string(context, 0, ENOMEM, "out of memory");
@@ -1479,7 +1492,7 @@
     }
     c.tbsCertList.crlExtensions =3D NULL;
=20
-    ret =3D hx509_certs_iter(context, crl->revoked, add_revoked, &c.tbsCer=
tList);
+    ret =3D hx509_certs_iter_f(context, crl->revoked, add_revoked, &c.tbsC=
ertList);
     if (ret)
 	goto out;
=20
@@ -1506,10 +1519,13 @@
 					    &c.signatureAlgorithm,
 					    &c.signatureValue);
     free(os->data);
+    if (ret) {
+	hx509_set_error_string(context, 0, ret, "Failed to sign CRL");
+	goto out;
+    }
=20
     ASN1_MALLOC_ENCODE(CRLCertificateList, os->data, os->length,
 		       &c, &size, ret);
-    free_CRLCertificateList(&c);
     if (ret) {
 	hx509_set_error_string(context, 0, ret, "failed to encode CRL");
 	goto out;
@@ -1517,6 +1533,8 @@
     if (size !=3D os->length)
 	_hx509_abort("internal ASN.1 encoder error");
=20
+    free_CRLCertificateList(&c);
+
     return 0;
=20
 out:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/softp11.c
--- a/head/crypto/heimdal/lib/hx509/softp11.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/softp11.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,36 +1,38 @@
 /*
- * Copyright (c) 2004 - 2008 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
+#define CRYPTOKI_EXPORTS 1
+
 #include "hx_locl.h"
 #include "pkcs11.h"
=20
@@ -38,6 +40,14 @@
 #define HANDLE_OBJECT_ID(h)	((h) & OBJECT_ID_MASK)
 #define OBJECT_ID(obj)		HANDLE_OBJECT_ID((obj)->object_handle)
=20
+#ifndef HAVE_RANDOM
+#define random() rand()
+#define srandom(s) srand(s)
+#endif
+
+#ifdef _WIN32
+#include <shlobj.h>
+#endif
=20
 struct st_attr {
     CK_ATTRIBUTE attribute;
@@ -127,11 +137,12 @@
 {
     int len;
     va_list ap;
+    va_start(ap, fmt);
     len =3D vsnprintf(str, size, fmt, ap);
     va_end(ap);
-    if (len < 0 || len > size)
+    if (len < 0 || (size_t)len > size)
 	return;
-    while(len < size)
+    while ((size_t)len < size)
 	str[len++] =3D fillchar;
 }
=20
@@ -141,9 +152,9 @@
=20
 #define VERIFY_SESSION_HANDLE(s, state)			\
 {							\
-    CK_RV ret;						\
-    ret =3D verify_session_handle(s, state);		\
-    if (ret !=3D CKR_OK) {				\
+    CK_RV xret;						\
+    xret =3D verify_session_handle(s, state);		\
+    if (xret !=3D CKR_OK) {				\
 	/* return CKR_OK */;				\
     }							\
 }
@@ -152,7 +163,7 @@
 verify_session_handle(CK_SESSION_HANDLE hSession,
 		      struct session_state **state)
 {
-    int i;
+    size_t i;
=20
     for (i =3D 0; i < MAX_NUM_SESSION; i++){
 	if (soft_token.state[i].session_handle =3D=3D hSession)
@@ -295,13 +306,10 @@
     struct st_object *o, **objs;
     int i;
=20
-    o =3D malloc(sizeof(*o));
+    o =3D calloc(1, sizeof(*o));
     if (o =3D=3D NULL)
 	return NULL;
-    memset(o, 0, sizeof(*o));
-    o->attrs =3D NULL;
-    o->num_attributes =3D 0;
-   =20
+
     for (i =3D 0; i < soft_token.object.num_objs; i++) {
 	if (soft_token.object.objs =3D=3D NULL) {
 	    soft_token.object.objs[i] =3D o;
@@ -317,7 +325,7 @@
 	}
 	soft_token.object.objs =3D objs;
 	soft_token.object.objs[soft_token.object.num_objs++] =3D o;
-    }=09
+    }
     soft_token.object.objs[i]->object_handle =3D
 	(random() & (~OBJECT_ID_MASK)) | i;
=20
@@ -325,7 +333,7 @@
 }
=20
 static CK_RV
-add_object_attribute(struct st_object *o,=20
+add_object_attribute(struct st_object *o,
 		     int secret,
 		     CK_ATTRIBUTE_TYPE type,
 		     CK_VOID_PTR pValue,
@@ -361,14 +369,14 @@
     CK_ULONG modulus_bits =3D 0;
     CK_BYTE *exponent =3D NULL;
     size_t exponent_len =3D 0;
-   =20
+
     if (key_type !=3D CKK_RSA)
 	return CKR_OK;
     if (_hx509_cert_private_key(cert) =3D=3D NULL)
 	return CKR_OK;
=20
-    num =3D _hx509_private_key_get_internal(context,=20
-					  _hx509_cert_private_key(cert),=20
+    num =3D _hx509_private_key_get_internal(context,
+					  _hx509_cert_private_key(cert),
 					  "rsa-modulus");
     if (num =3D=3D NULL)
 	return CKR_GENERAL_ERROR;
@@ -384,9 +392,9 @@
 			 &modulus_bits, sizeof(modulus_bits));
=20
     free(modulus);
-=09
-    num =3D _hx509_private_key_get_internal(context,=20
-					  _hx509_cert_private_key(cert),=20
+
+    num =3D _hx509_private_key_get_internal(context,
+					  _hx509_cert_private_key(cert),
 					  "rsa-exponent");
     if (num =3D=3D NULL)
 	return CKR_GENERAL_ERROR;
@@ -413,6 +421,7 @@
 static int
 add_cert(hx509_context hxctx, void *ctx, hx509_cert cert)
 {
+    static char empty[] =3D "";
     struct foo *foo =3D (struct foo *)ctx;
     struct st_object *o =3D NULL;
     CK_OBJECT_CLASS type;
@@ -512,8 +521,8 @@
=20
     add_object_attribute(o, 0, CKA_KEY_TYPE, &key_type, sizeof(key_type));
     add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id));
-    add_object_attribute(o, 0, CKA_START_DATE, "", 1); /* XXX */
-    add_object_attribute(o, 0, CKA_END_DATE, "", 1); /* XXX */
+    add_object_attribute(o, 0, CKA_START_DATE, empty, 1); /* XXX */
+    add_object_attribute(o, 0, CKA_END_DATE, empty, 1); /* XXX */
     add_object_attribute(o, 0, CKA_DERIVE, &bool_false, sizeof(bool_false)=
);
     add_object_attribute(o, 0, CKA_LOCAL, &bool_false, sizeof(bool_false));
     mech_type =3D CKM_RSA_X_509;
@@ -549,8 +558,8 @@
=20
 	add_object_attribute(o, 0, CKA_KEY_TYPE, &key_type, sizeof(key_type));
 	add_object_attribute(o, 0, CKA_ID, foo->id, strlen(foo->id));
-	add_object_attribute(o, 0, CKA_START_DATE, "", 1); /* XXX */
-	add_object_attribute(o, 0, CKA_END_DATE, "", 1); /* XXX */
+	add_object_attribute(o, 0, CKA_START_DATE, empty, 1); /* XXX */
+	add_object_attribute(o, 0, CKA_END_DATE, empty, 1); /* XXX */
 	add_object_attribute(o, 0, CKA_DERIVE, &bool_false, sizeof(bool_false));
 	add_object_attribute(o, 0, CKA_LOCAL, &bool_false, sizeof(bool_false));
 	mech_type =3D CKM_RSA_X_509;
@@ -621,7 +630,7 @@
 	return CKR_GENERAL_ERROR;
     }
=20
-    ret =3D hx509_certs_iter(context, certs, add_cert, &foo);
+    ret =3D hx509_certs_iter_f(context, certs, add_cert, &foo);
     hx509_certs_free(&certs);
     if (ret) {
 	st_logf("failed adding certs from file %s\n", cert_file);
@@ -685,40 +694,43 @@
 read_conf_file(const char *fn, CK_USER_TYPE userType, const char *pin)
 {
     char buf[1024], *type, *s, *p;
-    int anchor;
     FILE *f;
     CK_RV ret =3D CKR_OK;
     CK_RV failed =3D CKR_OK;
=20
+    if (fn =3D=3D NULL) {
+        st_logf("Can't open configuration file.  No file specified\n");
+        return CKR_GENERAL_ERROR;
+    }
+
     f =3D fopen(fn, "r");
     if (f =3D=3D NULL) {
 	st_logf("can't open configuration file %s\n", fn);
 	return CKR_GENERAL_ERROR;
     }
+    rk_cloexec_file(f);
=20
     while(fgets(buf, sizeof(buf), f) !=3D NULL) {
 	buf[strcspn(buf, "\n")] =3D '\0';
=20
-	anchor =3D 0;
-
 	st_logf("line: %s\n", buf);
=20
 	p =3D buf;
-	while (isspace(*p))
+	while (isspace((unsigned char)*p))
 	    p++;
 	if (*p =3D=3D '#')
 	    continue;
-	while (isspace(*p))
+	while (isspace((unsigned char)*p))
 	    p++;
=20
 	s =3D NULL;
 	type =3D strtok_r(p, "\t", &s);
 	if (type =3D=3D NULL)
 	    continue;
-=09
+
 	if (strcasecmp("certificate", type) =3D=3D 0) {
 	    char *cert, *id, *label;
-	   =20
+
 	    id =3D strtok_r(NULL, "\t", &s);
 	    if (id =3D=3D NULL) {
 		st_logf("no id\n");
@@ -735,9 +747,9 @@
 		st_logf("no certfiicate store\n");
 		continue;
 	    }
-	   =20
+
 	    st_logf("adding: %s: %s in file %s\n", id, label, cert);
-	   =20
+
 	    ret =3D add_certificate(cert, pin, id, label);
 	    if (ret)
 		failed =3D ret;
@@ -755,11 +767,14 @@
=20
 	    if (strcasecmp(name, "stdout") =3D=3D 0)
 		soft_token.logfile =3D stdout;
-	    else
+	    else {
 		soft_token.logfile =3D fopen(name, "a");
+		if (soft_token.logfile)
+		    rk_cloexec_file(soft_token.logfile);
+	    }
 	    if (soft_token.logfile =3D=3D NULL)
 		st_logf("failed to open file: %s\n", name);
-	=09
+
 	} else if (strcasecmp("app-fatal", type) =3D=3D 0) {
 	    char *name;
=20
@@ -793,12 +808,59 @@
     return CKR_FUNCTION_NOT_SUPPORTED;
 }
=20
-CK_RV
+static char *
+get_config_file_for_user(void)
+{
+    char *fn =3D NULL;
+
+#ifndef _WIN32
+    char *home =3D NULL;
+
+    if (!issuid()) {
+        fn =3D getenv("SOFTPKCS11RC");
+        if (fn)
+            fn =3D strdup(fn);
+        home =3D getenv("HOME");
+    }
+    if (fn =3D=3D NULL && home =3D=3D NULL) {
+        struct passwd *pw =3D getpwuid(getuid());
+        if(pw !=3D NULL)
+            home =3D pw->pw_dir;
+    }
+    if (fn =3D=3D NULL) {
+        if (home)
+            asprintf(&fn, "%s/.soft-token.rc", home);
+        else
+            fn =3D strdup("/etc/soft-token.rc");
+    }
+#else  /* Windows */
+
+    char appdatafolder[MAX_PATH];
+
+    fn =3D getenv("SOFTPKCS11RC");
+
+    /* Retrieve the roaming AppData folder for the current user.  The
+       current user is the user account represented by the current
+       thread token. */
+
+    if (fn =3D=3D NULL &&
+        SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CU=
RRENT, appdatafolder))) {
+
+        asprintf(&fn, "%s\\.soft-token.rc", appdatafolder);
+    }
+
+#endif  /* _WIN32 */
+
+    return fn;
+}
+
+
+CK_RV CK_SPEC
 C_Initialize(CK_VOID_PTR a)
 {
     CK_C_INITIALIZE_ARGS_PTR args =3D a;
     CK_RV ret;
-    int i;
+    size_t i;
=20
     st_logf("Initialize\n");
=20
@@ -806,7 +868,7 @@
=20
     OpenSSL_add_all_algorithms();
=20
-    srandom(getpid() ^ time(NULL));
+    srandom(getpid() ^ (int) time(NULL));
=20
     for (i =3D 0; i < MAX_NUM_SESSION; i++) {
 	soft_token.state[i].session_handle =3D CK_INVALID_HANDLE;
@@ -822,7 +884,7 @@
=20
     soft_token.object.objs =3D NULL;
     soft_token.object.num_objs =3D 0;
-   =20
+
     soft_token.logfile =3D NULL;
 #if 0
     soft_token.logfile =3D stdout;
@@ -839,29 +901,7 @@
 	st_logf("\tFlags\t%04x\n", (unsigned int)args->flags);
     }
=20
-    {
-	char *fn =3D NULL, *home =3D NULL;
-
-	if (getuid() =3D=3D geteuid()) {
-	    fn =3D getenv("SOFTPKCS11RC");
-	    if (fn)
-		fn =3D strdup(fn);
-	    home =3D getenv("HOME");
-	}
-	if (fn =3D=3D NULL && home =3D=3D NULL) {
-	    struct passwd *pw =3D getpwuid(getuid());=09
-	    if(pw !=3D NULL)
-		home =3D pw->pw_dir;
-	}
-	if (fn =3D=3D NULL) {
-	    if (home)
-		asprintf(&fn, "%s/.soft-token.rc", home);
-	    else
-		fn =3D strdup("/etc/soft-token.rc");
-	}
-
-	soft_token.config_file =3D fn;
-    }
+    soft_token.config_file =3D get_config_file_for_user();
=20
     /*
      * This operations doesn't return CKR_OK if any of the
@@ -877,7 +917,7 @@
 CK_RV
 C_Finalize(CK_VOID_PTR args)
 {
-    int i;
+    size_t i;
=20
     INIT_CONTEXT();
=20
@@ -904,11 +944,11 @@
     memset(args, 17, sizeof(*args));
     args->cryptokiVersion.major =3D 2;
     args->cryptokiVersion.minor =3D 10;
-    snprintf_fill((char *)args->manufacturerID,=20
+    snprintf_fill((char *)args->manufacturerID,
 		  sizeof(args->manufacturerID),
 		  ' ',
 		  "Heimdal hx509 SoftToken");
-    snprintf_fill((char *)args->libraryDescription,=20
+    snprintf_fill((char *)args->libraryDescription,
 		  sizeof(args->libraryDescription), ' ',
 		  "Heimdal hx509 SoftToken");
     args->libraryVersion.major =3D 2;
@@ -954,7 +994,7 @@
     if (slotID !=3D 1)
 	return CKR_ARGUMENTS_BAD;
=20
-    snprintf_fill((char *)pInfo->slotDescription,=20
+    snprintf_fill((char *)pInfo->slotDescription,
 		  sizeof(pInfo->slotDescription),
 		  ' ',
 		  "Heimdal hx509 SoftToken (slot)");
@@ -969,7 +1009,7 @@
     pInfo->hardwareVersion.minor =3D 0;
     pInfo->firmwareVersion.major =3D 1;
     pInfo->firmwareVersion.minor =3D 0;
-   =20
+
     return CKR_OK;
 }
=20
@@ -978,15 +1018,15 @@
 	       CK_TOKEN_INFO_PTR pInfo)
 {
     INIT_CONTEXT();
-    st_logf("GetTokenInfo: %s\n", has_session());=20
+    st_logf("GetTokenInfo: %s\n", has_session());
=20
     memset(pInfo, 19, sizeof(*pInfo));
=20
-    snprintf_fill((char *)pInfo->label,=20
+    snprintf_fill((char *)pInfo->label,
 		  sizeof(pInfo->label),
 		  ' ',
 		  "Heimdal hx509 SoftToken (token)");
-    snprintf_fill((char *)pInfo->manufacturerID,=20
+    snprintf_fill((char *)pInfo->manufacturerID,
 		  sizeof(pInfo->manufacturerID),
 		  ' ',
 		  "Heimdal hx509 SoftToken (token)");
@@ -994,12 +1034,12 @@
 		  sizeof(pInfo->model),
 		  ' ',
 		  "Heimdal hx509 SoftToken (token)");
-    snprintf_fill((char *)pInfo->serialNumber,=20
+    snprintf_fill((char *)pInfo->serialNumber,
 		  sizeof(pInfo->serialNumber),
 		  ' ',
 		  "4711");
-    pInfo->flags =3D=20
-	CKF_TOKEN_INITIALIZED |=20
+    pInfo->flags =3D
+	CKF_TOKEN_INITIALIZED |
 	CKF_USER_PIN_INITIALIZED;
=20
     if (soft_token.flags.login_done =3D=3D 0)
@@ -1073,10 +1113,10 @@
 	      CK_NOTIFY Notify,
 	      CK_SESSION_HANDLE_PTR phSession)
 {
-    int i;
+    size_t i;
     INIT_CONTEXT();
     st_logf("OpenSession: slot: %d\n", (int)slotID);
-   =20
+
     if (soft_token.open_sessions =3D=3D MAX_NUM_SESSION)
 	return CKR_SESSION_COUNT;
=20
@@ -1116,7 +1156,7 @@
 CK_RV
 C_CloseAllSessions(CK_SLOT_ID slotID)
 {
-    int i;
+    size_t i;
     INIT_CONTEXT();
=20
     st_logf("CloseAllSessions\n");
@@ -1134,7 +1174,7 @@
 {
     st_logf("GetSessionInfo\n");
     INIT_CONTEXT();
-   =20
+
     VERIFY_SESSION_HANDLE(hSession, NULL);
=20
     memset(pInfo, 20, sizeof(*pInfo));
@@ -1178,7 +1218,7 @@
 	soft_token.flags.login_done =3D 1;
=20
     free(pin);
-   =20
+
     return soft_token.flags.login_done ? CKR_OK : CKR_PIN_INCORRECT;
 }
=20
@@ -1276,12 +1316,12 @@
=20
 	print_attributes(pTemplate, ulCount);
=20
-	state->find.attributes =3D=20
+	state->find.attributes =3D
 	    calloc(1, ulCount * sizeof(state->find.attributes[0]));
 	if (state->find.attributes =3D=3D NULL)
 	    return CKR_DEVICE_MEMORY;
 	for (i =3D 0; i < ulCount; i++) {
-	    state->find.attributes[i].pValue =3D=20
+	    state->find.attributes[i].pValue =3D
 		malloc(pTemplate[i].ulValueLen);
 	    if (state->find.attributes[i].pValue =3D=3D NULL) {
 		find_object_final(state);
@@ -1390,7 +1430,7 @@
=20
=20
 static CK_RV
-dup_mechanism(CK_MECHANISM_PTR *dup, const CK_MECHANISM_PTR pMechanism)
+dup_mechanism(CK_MECHANISM_PTR *dp, const CK_MECHANISM_PTR pMechanism)
 {
     CK_MECHANISM_PTR p;
=20
@@ -1398,9 +1438,9 @@
     if (p =3D=3D NULL)
 	return CKR_DEVICE_MEMORY;
=20
-    if (*dup)
-	free(*dup);
-    *dup =3D p;
+    if (*dp)
+	free(*dp);
+    *dp =3D p;
     memcpy(p, pMechanism, sizeof(*p));
=20
     return CKR_OK;
@@ -1433,15 +1473,15 @@
     INIT_CONTEXT();
     st_logf("SignInit\n");
     VERIFY_SESSION_HANDLE(hSession, &state);
-   =20
-    ret =3D commonInit(attr, sizeof(attr)/sizeof(attr[0]),=20
+
+    ret =3D commonInit(attr, sizeof(attr)/sizeof(attr[0]),
 		     mechs, sizeof(mechs)/sizeof(mechs[0]),
 		     pMechanism, hKey, &o);
     if (ret)
 	return ret;
=20
     ret =3D dup_mechanism(&state->sign_mechanism, pMechanism);
-    if (ret =3D=3D CKR_OK)=20
+    if (ret =3D=3D CKR_OK)
 	state->sign_object =3D OBJECT_ID(o);
=20
     return CKR_OK;
@@ -1457,7 +1497,7 @@
     struct session_state *state;
     struct st_object *o;
     CK_RV ret;
-    uint hret;
+    int hret;
     const AlgorithmIdentifier *alg;
     heim_octet_string sig, data;
=20
@@ -1498,7 +1538,7 @@
 	ret =3D CKR_FUNCTION_NOT_SUPPORTED;
 	goto out;
     }
-   =20
+
     data.data =3D pData;
     data.length =3D ulDataLen;
=20
@@ -1566,17 +1606,17 @@
     INIT_CONTEXT();
     st_logf("VerifyInit\n");
     VERIFY_SESSION_HANDLE(hSession, &state);
-   =20
-    ret =3D commonInit(attr, sizeof(attr)/sizeof(attr[0]),=20
+
+    ret =3D commonInit(attr, sizeof(attr)/sizeof(attr[0]),
 		     mechs, sizeof(mechs)/sizeof(mechs[0]),
 		     pMechanism, hKey, &o);
     if (ret)
 	return ret;
=20
     ret =3D dup_mechanism(&state->verify_mechanism, pMechanism);
-    if (ret =3D=3D CKR_OK)=20
+    if (ret =3D=3D CKR_OK)
 	state->verify_object =3D OBJECT_ID(o);
-		=09
+
     return ret;
 }
=20
@@ -1618,7 +1658,7 @@
     data.length =3D ulSignatureLen;
=20
     hret =3D _hx509_verify_signature(context,
-				   _hx509_get_cert(o->cert),
+				   o->cert,
 				   alg,
 				   &data,
 				   &sig);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_ca.=
in
--- a/head/crypto/heimdal/lib/hx509/test_ca.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/hx509/test_ca.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_ca.in 21345 2007-06-26 14:22:57Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_cer=
t.in
--- a/head/crypto/heimdal/lib/hx509/test_cert.in	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/hx509/test_cert.in	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -65,5 +65,20 @@
=20
 cmp cert-pem.tmp cert-pem2.tmp || exit 1
=20
+echo "verify n0ll cert (fail)"
+${hxtool} verify --missing-revoke \
+	--hostname=3Dfoo.com \
+	cert:FILE:$srcdir/data/n0ll.pem \
+	anchor:FILE:$srcdir/data/n0ll.pem && exit 1
+
+echo "verify n0ll cert (fail)"
+${hxtool} verify --missing-revoke \
+	cert:FILE:$srcdir/data/n0ll.pem \
+	anchor:FILE:$srcdir/data/n0ll.pem && exit 1
+
+echo "check that windows cert with utf16 in printable string works"
+${hxtool} verify --missing-revoke \
+	cert:FILE:$srcdir/data/win-u16-in-printablestring.der \
+	anchor:FILE:$srcdir/data/win-u16-in-printablestring.der || exit 1
=20
 exit 0
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_cha=
in.in
--- a/head/crypto/heimdal/lib/hx509/test_chain.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/hx509/test_chain.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2004 - 2006 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2004 - 2006 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_chain.in 21278 2007-06-25 04:54:43Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
@@ -187,6 +187,20 @@
     anchor:FILE:$srcdir/data/ca.crt \
     crl:FILE:$srcdir/data/crl1.der > /dev/null && exit 1
=20
+if ${hxtool} info | grep 'ecdsa: hcrypto null' > /dev/null ; then
+    echo "not testing ECDSA since hcrypto doesnt support ECDSA"
+else
+    echo "eccert -> root"
+    ${hxtool} verify --missing-revoke \
+    	cert:FILE:$srcdir/data/secp160r2TestServer.cert.pem \
+    	anchor:FILE:$srcdir/data/secp160r1TestCA.cert.pem > /dev/null || exit=
 1
+   =20
+    echo "eccert -> root"
+    ${hxtool} verify --missing-revoke \
+    	cert:FILE:$srcdir/data/secp160r2TestClient.cert.pem \
+    	anchor:FILE:$srcdir/data/secp160r1TestCA.cert.pem > /dev/null || exit=
 1
+fi
+
 echo "proxy cert"
 ${hxtool} verify --missing-revoke \
     --allow-proxy-certificate \
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_cms=
.in
--- a/head/crypto/heimdal/lib/hx509/test_cms.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hx509/test_cms.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_cms.in 21311 2007-06-25 18:26:37Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
@@ -48,6 +48,23 @@
     exit 77
 fi
=20
+if ${hxtool} info | grep 'ecdsa: hcrypto null' > /dev/null ; then
+    echo "not testing ECDSA since hcrypto doesnt support ECDSA"
+else
+    echo "create signed data (ec)"
+    ${hxtool} cms-create-sd \
+    	--certificate=3DFILE:$srcdir/data/secp160r2TestClient.pem \
+    	"$srcdir/test_chain.in" \
+    	sd.data > /dev/null || exit 1
+   =20
+    echo "verify signed data (ec)"
+    ${hxtool} cms-verify-sd \
+    	--missing-revoke \
+    	--anchors=3DFILE:$srcdir/data/secp160r1TestCA.cert.pem \
+    	sd.data sd.data.out > /dev/null || exit 1
+    cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+fi
+   =20
 echo "create signed data"
 ${hxtool} cms-create-sd \
 	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
@@ -61,6 +78,29 @@
 	sd.data sd.data.out > /dev/null || exit 1
 cmp "$srcdir/test_chain.in" sd.data.out || exit 1
=20
+echo "create signed data (no signer)"
+${hxtool} cms-create-sd \
+        --no-signer \
+	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+	"$srcdir/test_chain.in" \
+	sd.data > /dev/null || exit 1
+
+echo "verify signed data (no signer)"
+${hxtool} cms-verify-sd \
+	--missing-revoke \
+        --no-signer-allowed \
+	--anchors=3DFILE:$srcdir/data/ca.crt \
+	sd.data sd.data.out > signer.tmp || exit 1
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+grep "unsigned" signer.tmp > /dev/null || exit 1
+
+echo "verify signed data (no signer) (test failure)"
+${hxtool} cms-verify-sd \
+	--missing-revoke \
+	--anchors=3DFILE:$srcdir/data/ca.crt \
+	sd.data sd.data.out 2> signer.tmp && exit 1
+grep "No signers where found" signer.tmp > /dev/null || exit 1
+
 echo "create signed data (id-by-name)"
 ${hxtool} cms-create-sd \
 	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
@@ -145,6 +185,14 @@
 	"$srcdir/test_chain.in" \
 	sd.data > /dev/null || exit 1
=20
+echo "verify signed data (pem)"
+${hxtool} cms-verify-sd \
+	--missing-revoke \
+	--anchors=3DFILE:$srcdir/data/ca.crt \
+	--pem \
+        sd.data sd.data.out > /dev/null
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
 echo "create signed data (pem, detached)"
 ${hxtool} cms-create-sd \
 	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
@@ -153,6 +201,15 @@
 	"$srcdir/test_chain.in" \
 	sd.data > /dev/null || exit 1
=20
+echo "verify signed data (pem, detached)"
+${hxtool} cms-verify-sd \
+	--missing-revoke \
+	--anchors=3DFILE:$srcdir/data/ca.crt \
+	--pem \
+        --signed-content=3D"$srcdir/test_chain.in" \
+        sd.data sd.data.out > /dev/null
+cmp "$srcdir/test_chain.in" sd.data.out || exit 1
+
 echo "create signed data (p12)"
 ${hxtool} cms-create-sd \
 	--pass=3DPASS:foobar \
@@ -195,6 +252,31 @@
 	sd.data.out > /dev/null || exit 1
 cmp "$srcdir/data/static-file" sd.data.out || exit 1
=20
+echo "verify signed data - sha1"
+${hxtool} cms-verify-sd \
+	--missing-revoke \
+	--anchors=3DFILE:$srcdir/data/ca.crt \
+	--content-info \
+	"$srcdir/data/test-signed-sha-1" sd.data.out > /dev/null || exit 1
+cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+echo "verify signed data - sha256"
+${hxtool} cms-verify-sd \
+	--missing-revoke \
+	--anchors=3DFILE:$srcdir/data/ca.crt \
+	--content-info \
+	"$srcdir/data/test-signed-sha-256" sd.data.out > /dev/null || exit 1
+cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+#echo "verify signed data - sha512"
+#${hxtool} cms-verify-sd \
+#	--missing-revoke \
+#	--anchors=3DFILE:$srcdir/data/ca.crt \
+#	--content-info \
+#	"$srcdir/data/test-signed-sha-512" sd.data.out > /dev/null || exit 1
+#cmp "$srcdir/data/static-file" sd.data.out || exit 1
+
+
 echo "create signed data (subcert, no certs)"
 ${hxtool} cms-create-sd \
 	--certificate=3DFILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
@@ -317,6 +399,60 @@
 	sd.data sd.data.out > /dev/null 2>/dev/null || exit 1
 cmp "$srcdir/test_chain.in" sd.data.out || exit 1
=20
+echo "create signed data (pem, detached)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+	--detached-signature \
+	--pem \
+	sd > /dev/null || exit 1
+
+echo "verify signed data (pem, detached)"
+${hxtool} cms-verify-sd \
+	--missing-revoke \
+	--anchors=3DFILE:$srcdir/data/ca.crt \
+	--pem \
+	sd.pem > /dev/null
+
+echo "create signed data (no certs, detached sig)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+	--detached-signature \
+	--no-embedded-certs \
+	"$srcdir/data/static-file" \
+	sd > /dev/null || exit 1
+
+echo "create signed data (leif only, detached sig)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+	--detached-signature \
+	--embed-leaf-only \
+	"$srcdir/data/static-file" \
+	sd > /dev/null || exit 1
+
+echo "create signed data (no certs, detached sig, 2 signers)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+	--certificate=3DFILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+	--detached-signature \
+	--no-embedded-certs \
+	"$srcdir/data/static-file" \
+	sd > /dev/null || exit 1
+
+echo "create signed data (no certs, detached sig, 3 signers)"
+cp "$srcdir/test_chain.in" sd
+${hxtool} cms-sign \
+	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
+	--certificate=3DFILE:$srcdir/data/sub-cert.crt,$srcdir/data/sub-cert.key \
+	--certificate=3DFILE:$srcdir/data/test-ds-only.crt,$srcdir/data/test-ds-o=
nly.key \
+	--detached-signature \
+	--no-embedded-certs \
+	"$srcdir/data/static-file" \
+	sd > /dev/null || exit 1
+
 echo "envelope data (content-type)"
 ${hxtool} cms-envelope \
 	--certificate=3DFILE:$srcdir/data/test.crt \
@@ -370,6 +506,7 @@
     ${hxtool} cms-unenvelope \
 	--certificate=3DFILE:$srcdir/data/test.crt,$srcdir/data/test.key \
 	--content-info \
+	--allow-weak \
 	"$srcdir/data/test-enveloped-$a" ev.data.out > /dev/null || exit 1
     cmp "$srcdir/data/static-file" ev.data.out || exit 1
 done
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_cry=
pto.in
--- a/head/crypto/heimdal/lib/hx509/test_crypto.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/hx509/test_crypto.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_crypto.in 20898 2007-06-04 23:07:46Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
@@ -144,12 +144,12 @@
 cmp test ${srcdir}/tst-crypto-select7 > /dev/null || \
 	{ echo "select7 failure"; exit 1; }
=20
-echo "crypto available1"
-${hxtool} crypto-available \
-	--type=3Dall \
-	> test || { echo "available1"; exit 1; }
-cmp test ${srcdir}/tst-crypto-available1 > /dev/null || \
-	{ echo "available1 failure"; exit 1; }
+#echo "crypto available1"
+#${hxtool} crypto-available \
+#	--type=3Dall \
+#	> test || { echo "available1"; exit 1; }
+#cmp test ${srcdir}/tst-crypto-available1 > /dev/null || \
+#	{ echo "available1 failure"; exit 1; }
=20
 echo "crypto available2"
 ${hxtool} crypto-available \
@@ -158,12 +158,12 @@
 cmp test ${srcdir}/tst-crypto-available2 > /dev/null || \
 	{ echo "available2 failure"; exit 1; }
=20
-echo "crypto available3"
-${hxtool} crypto-available \
-	--type=3Dpublic-sig \
-	> test || { echo "available3"; exit 1; }
-cmp test ${srcdir}/tst-crypto-available3 > /dev/null || \
-	{ echo "available3 failure"; exit 1; }
+#echo "crypto available3"
+#${hxtool} crypto-available \
+#	--type=3Dpublic-sig \
+#	> test || { echo "available3"; exit 1; }
+#cmp test ${srcdir}/tst-crypto-available3 > /dev/null || \
+#	{ echo "available3 failure"; exit 1; }
=20
 echo "copy keystore FILE existing -> FILE"
 ${hxtool} certificate-copy \
@@ -184,4 +184,9 @@
 ${hxtool} print \
 	FILE:$srcdir/data/j.pem >/dev/null 2>/dev/null || exit 1
=20
+echo "Make sure that we can parse EC private keys"
+${hxtool} print --content \
+    FILE:$srcdir/data/pkinit-ec.crt,$srcdir/data/pkinit-ec.key \
+    > /dev/null || exit 1
+
 exit 0
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_jav=
a_pkcs11.in
--- a/head/crypto/heimdal/lib/hx509/test_java_pkcs11.in	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/test_java_pkcs11.in	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2008 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2008 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_nam=
e.c
--- a/head/crypto/heimdal/lib/hx509/test_name.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hx509/test_name.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
-RCSID("$Id: test_name.c 19882 2007-01-13 01:02:57Z lha $");
=20
 static int
 test_name(hx509_context context, const char *name)
@@ -72,13 +71,12 @@
 static int
 test_expand(hx509_context context, const char *name, const char *expected)
 {
-    hx509_env env;
+    hx509_env env =3D NULL;
     hx509_name n;
     char *s;
     int ret;
=20
-    hx509_env_init(context, &env);
-    hx509_env_add(context, env, "uid", "lha");
+    hx509_env_add(context, &env, "uid", "lha");
=20
     ret =3D hx509_parse_name(context, name, &n);
     if (ret)
@@ -93,7 +91,7 @@
     hx509_name_free(&n);
     if (ret)
 	return 1;
-   =20
+
     ret =3D strcmp(s, expected) !=3D 0;
     free(s);
     if (ret)
@@ -102,6 +100,256 @@
     return 0;
 }
=20
+char certdata1[] =3D
+    "\x30\x82\x04\x1d\x30\x82\x03\x05\xa0\x03\x02\x01\x02\x02\x10\x4e"
+    "\x81\x2d\x8a\x82\x65\xe0\x0b\x02\xee\x3e\x35\x02\x46\xe5\x3d\x30"
+    "\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30\x81"
+    "\x81\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31\x1b"
+    "\x30\x19\x06\x03\x55\x04\x08\x13\x12\x47\x72\x65\x61\x74\x65\x72"
+    "\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e\x06"
+    "\x03\x55\x04\x07\x13\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a\x30"
+    "\x18\x06\x03\x55\x04\x0a\x13\x11\x43\x4f\x4d\x4f\x44\x4f\x20\x43"
+    "\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x27\x30\x25\x06\x03\x55"
+    "\x04\x03\x13\x1e\x43\x4f\x4d\x4f\x44\x4f\x20\x43\x65\x72\x74\x69"
+    "\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x41\x75\x74\x68\x6f\x72\x69"
+    "\x74\x79\x30\x1e\x17\x0d\x30\x36\x31\x32\x30\x31\x30\x30\x30\x30"
+    "\x30\x30\x5a\x17\x0d\x32\x39\x31\x32\x33\x31\x32\x33\x35\x39\x35"
+    "\x39\x5a\x30\x81\x81\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02"
+    "\x47\x42\x31\x1b\x30\x19\x06\x03\x55\x04\x08\x13\x12\x47\x72\x65"
+    "\x61\x74\x65\x72\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31"
+    "\x10\x30\x0e\x06\x03\x55\x04\x07\x13\x07\x53\x61\x6c\x66\x6f\x72"
+    "\x64\x31\x1a\x30\x18\x06\x03\x55\x04\x0a\x13\x11\x43\x4f\x4d\x4f"
+    "\x44\x4f\x20\x43\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x27\x30"
+    "\x25\x06\x03\x55\x04\x03\x13\x1e\x43\x4f\x4d\x4f\x44\x4f\x20\x43"
+    "\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e\x20\x41\x75\x74"
+    "\x68\x6f\x72\x69\x74\x79\x30\x82\x01\x22\x30\x0d\x06\x09\x2a\x86"
+    "\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x82\x01\x0f\x00\x30\x82"
+    "\x01\x0a\x02\x82\x01\x01\x00\xd0\x40\x8b\x8b\x72\xe3\x91\x1b\xf7"
+    "\x51\xc1\x1b\x54\x04\x98\xd3\xa9\xbf\xc1\xe6\x8a\x5d\x3b\x87\xfb"
+    "\xbb\x88\xce\x0d\xe3\x2f\x3f\x06\x96\xf0\xa2\x29\x50\x99\xae\xdb"
+    "\x3b\xa1\x57\xb0\x74\x51\x71\xcd\xed\x42\x91\x4d\x41\xfe\xa9\xc8"
+    "\xd8\x6a\x86\x77\x44\xbb\x59\x66\x97\x50\x5e\xb4\xd4\x2c\x70\x44"
+    "\xcf\xda\x37\x95\x42\x69\x3c\x30\xc4\x71\xb3\x52\xf0\x21\x4d\xa1"
+    "\xd8\xba\x39\x7c\x1c\x9e\xa3\x24\x9d\xf2\x83\x16\x98\xaa\x16\x7c"
+    "\x43\x9b\x15\x5b\xb7\xae\x34\x91\xfe\xd4\x62\x26\x18\x46\x9a\x3f"
+    "\xeb\xc1\xf9\xf1\x90\x57\xeb\xac\x7a\x0d\x8b\xdb\x72\x30\x6a\x66"
+    "\xd5\xe0\x46\xa3\x70\xdc\x68\xd9\xff\x04\x48\x89\x77\xde\xb5\xe9"
+    "\xfb\x67\x6d\x41\xe9\xbc\x39\xbd\x32\xd9\x62\x02\xf1\xb1\xa8\x3d"
+    "\x6e\x37\x9c\xe2\x2f\xe2\xd3\xa2\x26\x8b\xc6\xb8\x55\x43\x88\xe1"
+    "\x23\x3e\xa5\xd2\x24\x39\x6a\x47\xab\x00\xd4\xa1\xb3\xa9\x25\xfe"
+    "\x0d\x3f\xa7\x1d\xba\xd3\x51\xc1\x0b\xa4\xda\xac\x38\xef\x55\x50"
+    "\x24\x05\x65\x46\x93\x34\x4f\x2d\x8d\xad\xc6\xd4\x21\x19\xd2\x8e"
+    "\xca\x05\x61\x71\x07\x73\x47\xe5\x8a\x19\x12\xbd\x04\x4d\xce\x4e"
+    "\x9c\xa5\x48\xac\xbb\x26\xf7\x02\x03\x01\x00\x01\xa3\x81\x8e\x30"
+    "\x81\x8b\x30\x1d\x06\x03\x55\x1d\x0e\x04\x16\x04\x14\x0b\x58\xe5"
+    "\x8b\xc6\x4c\x15\x37\xa4\x40\xa9\x30\xa9\x21\xbe\x47\x36\x5a\x56"
+    "\xff\x30\x0e\x06\x03\x55\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x01"
+    "\x06\x30\x0f\x06\x03\x55\x1d\x13\x01\x01\xff\x04\x05\x30\x03\x01"
+    "\x01\xff\x30\x49\x06\x03\x55\x1d\x1f\x04\x42\x30\x40\x30\x3e\xa0"
+    "\x3c\xa0\x3a\x86\x38\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e"
+    "\x63\x6f\x6d\x6f\x64\x6f\x63\x61\x2e\x63\x6f\x6d\x2f\x43\x4f\x4d"
+    "\x4f\x44\x4f\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f\x6e"
+    "\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x2e\x63\x72\x6c\x30\x0d\x06"
+    "\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x03\x82\x01\x01"
+    "\x00\x3e\x98\x9e\x9b\xf6\x1b\xe9\xd7\x39\xb7\x78\xae\x1d\x72\x18"
+    "\x49\xd3\x87\xe4\x43\x82\xeb\x3f\xc9\xaa\xf5\xa8\xb5\xef\x55\x7c"
+    "\x21\x52\x65\xf9\xd5\x0d\xe1\x6c\xf4\x3e\x8c\x93\x73\x91\x2e\x02"
+    "\xc4\x4e\x07\x71\x6f\xc0\x8f\x38\x61\x08\xa8\x1e\x81\x0a\xc0\x2f"
+    "\x20\x2f\x41\x8b\x91\xdc\x48\x45\xbc\xf1\xc6\xde\xba\x76\x6b\x33"
+    "\xc8\x00\x2d\x31\x46\x4c\xed\xe7\x9d\xcf\x88\x94\xff\x33\xc0\x56"
+    "\xe8\x24\x86\x26\xb8\xd8\x38\x38\xdf\x2a\x6b\xdd\x12\xcc\xc7\x3f"
+    "\x47\x17\x4c\xa2\xc2\x06\x96\x09\xd6\xdb\xfe\x3f\x3c\x46\x41\xdf"
+    "\x58\xe2\x56\x0f\x3c\x3b\xc1\x1c\x93\x35\xd9\x38\x52\xac\xee\xc8"
+    "\xec\x2e\x30\x4e\x94\x35\xb4\x24\x1f\x4b\x78\x69\xda\xf2\x02\x38"
+    "\xcc\x95\x52\x93\xf0\x70\x25\x59\x9c\x20\x67\xc4\xee\xf9\x8b\x57"
+    "\x61\xf4\x92\x76\x7d\x3f\x84\x8d\x55\xb7\xe8\xe5\xac\xd5\xf1\xf5"
+    "\x19\x56\xa6\x5a\xfb\x90\x1c\xaf\x93\xeb\xe5\x1c\xd4\x67\x97\x5d"
+    "\x04\x0e\xbe\x0b\x83\xa6\x17\x83\xb9\x30\x12\xa0\xc5\x33\x15\x05"
+    "\xb9\x0d\xfb\xc7\x05\x76\xe3\xd8\x4a\x8d\xfc\x34\x17\xa3\xc6\x21"
+    "\x28\xbe\x30\x45\x31\x1e\xc7\x78\xbe\x58\x61\x38\xac\x3b\xe2\x01"
+    "\x65";
+
+char certdata2[] =3D
+    "\x30\x82\x03\x02\x30\x82\x02\x6b\x02\x10\x39\xca\x54\x89\xfe\x50"
+    "\x22\x32\xfe\x32\xd9\xdb\xfb\x1b\x84\x19\x30\x0d\x06\x09\x2a\x86"
+    "\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30\x81\xc1\x31\x0b\x30\x09"
+    "\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31\x17\x30\x15\x06\x03\x55"
+    "\x04\x0a\x13\x0e\x56\x65\x72\x69\x53\x69\x67\x6e\x2c\x20\x49\x6e"
+    "\x63\x2e\x31\x3c\x30\x3a\x06\x03\x55\x04\x0b\x13\x33\x43\x6c\x61"
+    "\x73\x73\x20\x31\x20\x50\x75\x62\x6c\x69\x63\x20\x50\x72\x69\x6d"
+    "\x61\x72\x79\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x69\x6f"
+    "\x6e\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x20\x2d\x20\x47\x32"
+    "\x31\x3a\x30\x38\x06\x03\x55\x04\x0b\x13\x31\x28\x63\x29\x20\x31"
+    "\x39\x39\x38\x20\x56\x65\x72\x69\x53\x69\x67\x6e\x2c\x20\x49\x6e"
+    "\x63\x2e\x20\x2d\x20\x46\x6f\x72\x20\x61\x75\x74\x68\x6f\x72\x69"
+    "\x7a\x65\x64\x20\x75\x73\x65\x20\x6f\x6e\x6c\x79\x31\x1f\x30\x1d"
+    "\x06\x03\x55\x04\x0b\x13\x16\x56\x65\x72\x69\x53\x69\x67\x6e\x20"
+    "\x54\x72\x75\x73\x74\x20\x4e\x65\x74\x77\x6f\x72\x6b\x30\x1e\x17"
+    "\x0d\x39\x38\x30\x35\x31\x38\x30\x30\x30\x30\x30\x30\x5a\x17\x0d"
+    "\x31\x38\x30\x35\x31\x38\x32\x33\x35\x39\x35\x39\x5a\x30\x81\xc1"
+    "\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x55\x53\x31\x17\x30"
+    "\x15\x06\x03\x55\x04\x0a\x13\x0e\x56\x65\x72\x69\x53\x69\x67\x6e"
+    "\x2c\x20\x49\x6e\x63\x2e\x31\x3c\x30\x3a\x06\x03\x55\x04\x0b\x13"
+    "\x33\x43\x6c\x61\x73\x73\x20\x31\x20\x50\x75\x62\x6c\x69\x63\x20"
+    "\x50\x72\x69\x6d\x61\x72\x79\x20\x43\x65\x72\x74\x69\x66\x69\x63"
+    "\x61\x74\x69\x6f\x6e\x20\x41\x75\x74\x68\x6f\x72\x69\x74\x79\x20"
+    "\x2d\x20\x47\x32\x31\x3a\x30\x38\x06\x03\x55\x04\x0b\x13\x31\x28"
+    "\x63\x29\x20\x31\x39\x39\x38\x20\x56\x65\x72\x69\x53\x69\x67\x6e"
+    "\x2c\x20\x49\x6e\x63\x2e\x20\x2d\x20\x46\x6f\x72\x20\x61\x75\x74"
+    "\x68\x6f\x72\x69\x7a\x65\x64\x20\x75\x73\x65\x20\x6f\x6e\x6c\x79"
+    "\x31\x1f\x30\x1d\x06\x03\x55\x04\x0b\x13\x16\x56\x65\x72\x69\x53"
+    "\x69\x67\x6e\x20\x54\x72\x75\x73\x74\x20\x4e\x65\x74\x77\x6f\x72"
+    "\x6b\x30\x81\x9f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01"
+    "\x01\x05\x00\x03\x81\x8d\x00\x30\x81\x89\x02\x81\x81\x00\xaa\xd0"
+    "\xba\xbe\x16\x2d\xb8\x83\xd4\xca\xd2\x0f\xbc\x76\x31\xca\x94\xd8"
+    "\x1d\x93\x8c\x56\x02\xbc\xd9\x6f\x1a\x6f\x52\x36\x6e\x75\x56\x0a"
+    "\x55\xd3\xdf\x43\x87\x21\x11\x65\x8a\x7e\x8f\xbd\x21\xde\x6b\x32"
+    "\x3f\x1b\x84\x34\x95\x05\x9d\x41\x35\xeb\x92\xeb\x96\xdd\xaa\x59"
+    "\x3f\x01\x53\x6d\x99\x4f\xed\xe5\xe2\x2a\x5a\x90\xc1\xb9\xc4\xa6"
+    "\x15\xcf\xc8\x45\xeb\xa6\x5d\x8e\x9c\x3e\xf0\x64\x24\x76\xa5\xcd"
+    "\xab\x1a\x6f\xb6\xd8\x7b\x51\x61\x6e\xa6\x7f\x87\xc8\xe2\xb7\xe5"
+    "\x34\xdc\x41\x88\xea\x09\x40\xbe\x73\x92\x3d\x6b\xe7\x75\x02\x03"
+    "\x01\x00\x01\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05"
+    "\x05\x00\x03\x81\x81\x00\x8b\xf7\x1a\x10\xce\x76\x5c\x07\xab\x83"
+    "\x99\xdc\x17\x80\x6f\x34\x39\x5d\x98\x3e\x6b\x72\x2c\xe1\xc7\xa2"
+    "\x7b\x40\x29\xb9\x78\x88\xba\x4c\xc5\xa3\x6a\x5e\x9e\x6e\x7b\xe3"
+    "\xf2\x02\x41\x0c\x66\xbe\xad\xfb\xae\xa2\x14\xce\x92\xf3\xa2\x34"
+    "\x8b\xb4\xb2\xb6\x24\xf2\xe5\xd5\xe0\xc8\xe5\x62\x6d\x84\x7b\xcb"
+    "\xbe\xbb\x03\x8b\x7c\x57\xca\xf0\x37\xa9\x90\xaf\x8a\xee\x03\xbe"
+    "\x1d\x28\x9c\xd9\x26\x76\xa0\xcd\xc4\x9d\x4e\xf0\xae\x07\x16\xd5"
+    "\xbe\xaf\x57\x08\x6a\xd0\xa0\x42\x42\x42\x1e\xf4\x20\xcc\xa5\x78"
+    "\x82\x95\x26\x38\x8a\x47";
+
+char certdata3[] =3D
+    "\x30\x82\x04\x43\x30\x82\x03\x2b\xa0\x03\x02\x01\x02\x02\x01\x01"
+    "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05\x05\x00\x30"
+    "\x7f\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31\x1b"
+    "\x30\x19\x06\x03\x55\x04\x08\x0c\x12\x47\x72\x65\x61\x74\x65\x72"
+    "\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e\x06"
+    "\x03\x55\x04\x07\x0c\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a\x30"
+    "\x18\x06\x03\x55\x04\x0a\x0c\x11\x43\x6f\x6d\x6f\x64\x6f\x20\x43"
+    "\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x25\x30\x23\x06\x03\x55"
+    "\x04\x03\x0c\x1c\x54\x72\x75\x73\x74\x65\x64\x20\x43\x65\x72\x74"
+    "\x69\x66\x69\x63\x61\x74\x65\x20\x53\x65\x72\x76\x69\x63\x65\x73"
+    "\x30\x1e\x17\x0d\x30\x34\x30\x31\x30\x31\x30\x30\x30\x30\x30\x30"
+    "\x5a\x17\x0d\x32\x38\x31\x32\x33\x31\x32\x33\x35\x39\x35\x39\x5a"
+    "\x30\x7f\x31\x0b\x30\x09\x06\x03\x55\x04\x06\x13\x02\x47\x42\x31"
+    "\x1b\x30\x19\x06\x03\x55\x04\x08\x0c\x12\x47\x72\x65\x61\x74\x65"
+    "\x72\x20\x4d\x61\x6e\x63\x68\x65\x73\x74\x65\x72\x31\x10\x30\x0e"
+    "\x06\x03\x55\x04\x07\x0c\x07\x53\x61\x6c\x66\x6f\x72\x64\x31\x1a"
+    "\x30\x18\x06\x03\x55\x04\x0a\x0c\x11\x43\x6f\x6d\x6f\x64\x6f\x20"
+    "\x43\x41\x20\x4c\x69\x6d\x69\x74\x65\x64\x31\x25\x30\x23\x06\x03"
+    "\x55\x04\x03\x0c\x1c\x54\x72\x75\x73\x74\x65\x64\x20\x43\x65\x72"
+    "\x74\x69\x66\x69\x63\x61\x74\x65\x20\x53\x65\x72\x76\x69\x63\x65"
+    "\x73\x30\x82\x01\x22\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01"
+    "\x01\x01\x05\x00\x03\x82\x01\x0f\x00\x30\x82\x01\x0a\x02\x82\x01"
+    "\x01\x00\xdf\x71\x6f\x36\x58\x53\x5a\xf2\x36\x54\x57\x80\xc4\x74"
+    "\x08\x20\xed\x18\x7f\x2a\x1d\xe6\x35\x9a\x1e\x25\xac\x9c\xe5\x96"
+    "\x7e\x72\x52\xa0\x15\x42\xdb\x59\xdd\x64\x7a\x1a\xd0\xb8\x7b\xdd"
+    "\x39\x15\xbc\x55\x48\xc4\xed\x3a\x00\xea\x31\x11\xba\xf2\x71\x74"
+    "\x1a\x67\xb8\xcf\x33\xcc\xa8\x31\xaf\xa3\xe3\xd7\x7f\xbf\x33\x2d"
+    "\x4c\x6a\x3c\xec\x8b\xc3\x92\xd2\x53\x77\x24\x74\x9c\x07\x6e\x70"
+    "\xfc\xbd\x0b\x5b\x76\xba\x5f\xf2\xff\xd7\x37\x4b\x4a\x60\x78\xf7"
+    "\xf0\xfa\xca\x70\xb4\xea\x59\xaa\xa3\xce\x48\x2f\xa9\xc3\xb2\x0b"
+    "\x7e\x17\x72\x16\x0c\xa6\x07\x0c\x1b\x38\xcf\xc9\x62\xb7\x3f\xa0"
+    "\x93\xa5\x87\x41\xf2\xb7\x70\x40\x77\xd8\xbe\x14\x7c\xe3\xa8\xc0"
+    "\x7a\x8e\xe9\x63\x6a\xd1\x0f\x9a\xc6\xd2\xf4\x8b\x3a\x14\x04\x56"
+    "\xd4\xed\xb8\xcc\x6e\xf5\xfb\xe2\x2c\x58\xbd\x7f\x4f\x6b\x2b\xf7"
+    "\x60\x24\x58\x24\xce\x26\xef\x34\x91\x3a\xd5\xe3\x81\xd0\xb2\xf0"
+    "\x04\x02\xd7\x5b\xb7\x3e\x92\xac\x6b\x12\x8a\xf9\xe4\x05\xb0\x3b"
+    "\x91\x49\x5c\xb2\xeb\x53\xea\xf8\x9f\x47\x86\xee\xbf\x95\xc0\xc0"
+    "\x06\x9f\xd2\x5b\x5e\x11\x1b\xf4\xc7\x04\x35\x29\xd2\x55\x5c\xe4"
+    "\xed\xeb\x02\x03\x01\x00\x01\xa3\x81\xc9\x30\x81\xc6\x30\x1d\x06"
+    "\x03\x55\x1d\x0e\x04\x16\x04\x14\xc5\x7b\x58\xbd\xed\xda\x25\x69"
+    "\xd2\xf7\x59\x16\xa8\xb3\x32\xc0\x7b\x27\x5b\xf4\x30\x0e\x06\x03"
+    "\x55\x1d\x0f\x01\x01\xff\x04\x04\x03\x02\x01\x06\x30\x0f\x06\x03"
+    "\x55\x1d\x13\x01\x01\xff\x04\x05\x30\x03\x01\x01\xff\x30\x81\x83"
+    "\x06\x03\x55\x1d\x1f\x04\x7c\x30\x7a\x30\x3c\xa0\x3a\xa0\x38\x86"
+    "\x36\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e\x63\x6f\x6d\x6f"
+    "\x64\x6f\x63\x61\x2e\x63\x6f\x6d\x2f\x54\x72\x75\x73\x74\x65\x64"
+    "\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x53\x65\x72\x76\x69"
+    "\x63\x65\x73\x2e\x63\x72\x6c\x30\x3a\xa0\x38\xa0\x36\x86\x34\x68"
+    "\x74\x74\x70\x3a\x2f\x2f\x63\x72\x6c\x2e\x63\x6f\x6d\x6f\x64\x6f"
+    "\x2e\x6e\x65\x74\x2f\x54\x72\x75\x73\x74\x65\x64\x43\x65\x72\x74"
+    "\x69\x66\x69\x63\x61\x74\x65\x53\x65\x72\x76\x69\x63\x65\x73\x2e"
+    "\x63\x72\x6c\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x05"
+    "\x05\x00\x03\x82\x01\x01\x00\xc8\x93\x81\x3b\x89\xb4\xaf\xb8\x84"
+    "\x12\x4c\x8d\xd2\xf0\xdb\x70\xba\x57\x86\x15\x34\x10\xb9\x2f\x7f"
+    "\x1e\xb0\xa8\x89\x60\xa1\x8a\xc2\x77\x0c\x50\x4a\x9b\x00\x8b\xd8"
+    "\x8b\xf4\x41\xe2\xd0\x83\x8a\x4a\x1c\x14\x06\xb0\xa3\x68\x05\x70"
+    "\x31\x30\xa7\x53\x9b\x0e\xe9\x4a\xa0\x58\x69\x67\x0e\xae\x9d\xf6"
+    "\xa5\x2c\x41\xbf\x3c\x06\x6b\xe4\x59\xcc\x6d\x10\xf1\x96\x6f\x1f"
+    "\xdf\xf4\x04\x02\xa4\x9f\x45\x3e\xc8\xd8\xfa\x36\x46\x44\x50\x3f"
+    "\x82\x97\x91\x1f\x28\xdb\x18\x11\x8c\x2a\xe4\x65\x83\x57\x12\x12"
+    "\x8c\x17\x3f\x94\x36\xfe\x5d\xb0\xc0\x04\x77\x13\xb8\xf4\x15\xd5"
+    "\x3f\x38\xcc\x94\x3a\x55\xd0\xac\x98\xf5\xba\x00\x5f\xe0\x86\x19"
+    "\x81\x78\x2f\x28\xc0\x7e\xd3\xcc\x42\x0a\xf5\xae\x50\xa0\xd1\x3e"
+    "\xc6\xa1\x71\xec\x3f\xa0\x20\x8c\x66\x3a\x89\xb4\x8e\xd4\xd8\xb1"
+    "\x4d\x25\x47\xee\x2f\x88\xc8\xb5\xe1\x05\x45\xc0\xbe\x14\x71\xde"
+    "\x7a\xfd\x8e\x7b\x7d\x4d\x08\x96\xa5\x12\x73\xf0\x2d\xca\x37\x27"
+    "\x74\x12\x27\x4c\xcb\xb6\x97\xe9\xd9\xae\x08\x6d\x5a\x39\x40\xdd"
+    "\x05\x47\x75\x6a\x5a\x21\xb3\xa3\x18\xcf\x4e\xf7\x2e\x57\xb7\x98"
+    "\x70\x5e\xc8\xc4\x78\xb0\x62";
+
+
+static int
+compare_subject(hx509_cert c1, hx509_cert c2, int *l)
+{
+    hx509_name n1, n2;
+    int ret;
+
+    ret =3D hx509_cert_get_subject(c1, &n1);
+    if (ret) return 1;
+    ret =3D hx509_cert_get_subject(c2, &n2);
+    if (ret) return 1;
+
+    *l =3D hx509_name_cmp(n1, n2);
+    hx509_name_free(&n1);
+    hx509_name_free(&n2);
+
+    return 0;
+}
+
+static int
+test_compare(hx509_context context)
+{
+    int ret;
+    hx509_cert c1, c2, c3;
+    int l0, l1, l2, l3;
+
+    /* check transative properties of name compare function */
+
+    ret =3D hx509_cert_init_data(context, certdata1, sizeof(certdata1) - 1=
, &c1);
+    if (ret) return 1;
+
+    ret =3D hx509_cert_init_data(context, certdata2, sizeof(certdata2) - 1=
, &c2);
+    if (ret) return 1;
+
+    ret =3D hx509_cert_init_data(context, certdata3, sizeof(certdata3) - 1=
, &c3);
+    if (ret) return 1;
+
+    ret =3D compare_subject(c1, c1, &l0);
+    if (ret) return 1;
+    ret =3D compare_subject(c1, c2, &l1);
+    if (ret) return 1;
+    ret =3D compare_subject(c1, c3, &l2);
+    if (ret) return 1;
+    ret =3D compare_subject(c2, c3, &l3);
+    if (ret) return 1;
+
+    if (l0 !=3D 0) return 1;
+    if (l2 < l1) return 1;
+    if (l3 < l2) return 1;
+    if (l3 < l1) return 1;
+
+    hx509_cert_free(c1);
+    hx509_cert_free(c2);
+    hx509_cert_free(c3);
+
+    return 0;
+}
+
+
 int
 main(int argc, char **argv)
 {
@@ -126,6 +374,8 @@
     ret +=3D test_expand(context, "UID=3D${uid}${uid},C=3DSE", "UID=3Dlhal=
ha,C=3DSE");
     ret +=3D test_expand(context, "UID=3D${uid}{uid},C=3DSE", "UID=3Dlha{u=
id},C=3DSE");
=20
+    ret +=3D test_compare(context);
+
     hx509_context_free(&context);
=20
     return ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_nis=
t.in
--- a/head/crypto/heimdal/lib/hx509/test_nist.in	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/hx509/test_nist.in	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2004 - 2005 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2004 - 2005 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_nist.in 22240 2007-12-08 22:55:03Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
@@ -96,7 +96,7 @@
     args=3D"$args crl:FILE:$nistdir/crls/TrustAnchorRootCRL.crl"
     args=3D"$args cert:FILE:$nistdir/certs/$cert"
=20
-    if ${hxtool} verify $args > /dev/null; then
+    if ${hxtool} verify --time=3D2008-05-20 $args > /dev/null; then
 	if test "$verify" =3D "f"; then
 	    echo "verify passed on fail: $id $cert"
 	    exit 1
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_nis=
t2.in
--- a/head/crypto/heimdal/lib/hx509/test_nist2.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/hx509/test_nist2.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2004 - 2005 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2004 - 2008 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -38,6 +38,7 @@
 objdir=3D"@objdir@"
 nistdir=3D${objdir}/PKITS_data
 nistzip=3D${srcdir}/data/PKITS_data.zip
+egrep=3D"@egrep@"
=20
 limit=3D"${1:-nolimit}"
=20
@@ -55,6 +56,22 @@
     exit 77
 fi
=20
+#--------- Try to find unzip
+
+oldifs=3D$IFS
+IFS=3D:
+set -- $PATH
+IFS=3D$oldifs
+found=3D
+
+for p in "$@" ; do
+    test -x "$p/unzip" && { found=3D1 ; break; }
+done
+test "X$found" =3D "X" && exit 77
+
+#---------
+
+
 echo "nist tests, version 2"
=20
 if [ ! -d "$nistdir" ] ; then
@@ -80,13 +97,12 @@
     args=3D"$args cert:FILE:$nistdir/certs/$cert"
     args=3D"$args chain:DIR:$nistdir/certs"
     args=3D"$args anchor:FILE:$nistdir/certs/TrustAnchorRootCertificate.cr=
t"
-#    args=3D"$args crl:FILE:$nistdir/crls/TrustAnchorRootCRL.crl"
=20
     for a in $nistdir/crls/*.crl; do
 	args=3D"$args crl:FILE:$a"
     done
=20
-    cmd=3D"${hxtool} verify $args"
+    cmd=3D"${hxtool} verify --time=3D2008-05-20 $args"
     eval ${cmd} > /dev/null
     res=3D$?
=20
@@ -97,12 +113,14 @@
     [123],*) r=3D"PASSf";;
     *) echo=3D"unknown result ${result},${res}" ; exit 1 ;;
     esac
-    if grep "${name} FAIL" $srcdir/data/nist-result2 > /dev/null; then
+    if ${egrep} "^${name} FAIL" $srcdir/data/nist-result2 > /dev/null; then
 	if expr "$r" : "PASS" >/dev/null; then
 	    echo "${name} passed when expected not to"
 	    echo "# ${description}" > nist2-passed-${name}.tmp
 	    ec=3D1
 	fi
+    elif ${egrep} "^${name} EITHER" $srcdir/data/nist-result2 > /dev/null;=
 then
+	:
     elif expr "$r" : "FAIL.*" >/dev/null ; then
 	echo "$r ${name} ${description}"
 	echo "# ${description}" > nist2-failed-${name}.tmp
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_nis=
t_cert.in
--- a/head/crypto/heimdal/lib/hx509/test_nist_cert.in	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/hx509/test_nist_cert.in	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_nist_cert.in 21823 2007-08-03 15:13:37Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_nis=
t_pkcs12.in
--- a/head/crypto/heimdal/lib/hx509/test_nist_pkcs12.in	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/test_nist_pkcs12.in	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2004 - 2005 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2004 - 2005 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_nist_pkcs12.in 22256 2007-12-09 06:04:02Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_pkc=
s11.in
--- a/head/crypto/heimdal/lib/hx509/test_pkcs11.in	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/hx509/test_pkcs11.in	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2008 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2008 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_que=
ry.in
--- a/head/crypto/heimdal/lib/hx509/test_query.in	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/hx509/test_query.in	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2005 - 2007 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2005 - 2008 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_query.in 20782 2007-06-02 00:46:00Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
@@ -44,8 +44,15 @@
 echo "try printing"
 ${hxtool} print \
 	--pass=3DPASS:foobar \
+        --info --content \
 	PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null || exit 1
=20
+echo "try printing"
+${hxtool} print \
+	--pass=3DPASS:foobar \
+        --info --content \
+	FILE:$srcdir/data/kdc.crt  >/dev/null 2>/dev/null || exit 1
+
 ${hxtool} print \
 	--pass=3DPASS:foobar \
 	--info \
@@ -63,6 +70,16 @@
 	--friendlyname=3Dfriendlyname-test-not  \
 	PKCS12:$srcdir/data/test.p12 >/dev/null 2>/dev/null && exit 1
=20
+echo "make sure entry is found (eku)"
+${hxtool} query \
+	--eku=3D1.3.6.1.5.2.3.5  \
+	FILE:$srcdir/data/kdc.crt  >/dev/null 2>/dev/null || exit 1
+
+echo "make sure entry is not found  (eku)"
+${hxtool} query \
+	--eku=3D1.3.6.1.5.2.3.6  \
+	FILE:$srcdir/data/kdc.crt >/dev/null 2>/dev/null && exit 1
+
 echo "make sure entry is found (friendlyname, no-pw)"
 ${hxtool} query \
 	--friendlyname=3Dfriendlyname-cert  \
@@ -142,5 +159,45 @@
 	--keyEncipherment \
 	FILE:$srcdir/data/test-ke-only.crt >/dev/null 2>/dev/null && exit 1
=20
+echo "make sure entry is found (eku) in query language"
+${hxtool} query \
+	--expr=3D'"1.3.6.1.5.2.3.5" IN %{certificate.eku}'  \
+	FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry is not found (eku) in query language"
+${hxtool} query \
+	--expr=3D'"1.3.6.1.5.2.3.6" IN %{certificate.eku}'  \
+	FILE:$srcdir/data/kdc.crt > /dev/null && exit 1
+
+echo "make sure entry is found (subject) in query language"
+${hxtool} query \
+	--expr=3D'%{certificate.subject} =3D=3D "CN=3Dkdc,C=3DSE"'  \
+	FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry is found using TAILMATCH (subject) in query language"
+${hxtool} query \
+	--expr=3D'%{certificate.subject} TAILMATCH "C=3DSE"'  \
+	FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry is not found using TAILMATCH (subject) in query lang=
uage"
+${hxtool} query \
+	--expr=3D'%{certificate.subject} TAILMATCH "C=3DFI"'  \
+	FILE:$srcdir/data/kdc.crt > /dev/null && exit 1
+
+echo "make sure entry is found (issuer) in query language"
+${hxtool} query \
+	--expr=3D'%{certificate.issuer} =3D=3D "C=3DSE,CN=3Dhx509 Test Root CA"' =
 \
+	FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry match with EKU and TAILMATCH in query language"
+${hxtool} query \
+	--expr=3D'"1.3.6.1.5.2.3.5" IN %{certificate.eku} AND %{certificate.subje=
ct} TAILMATCH "C=3DSE"'  \
+	FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+echo "make sure entry match with hash.sha1"
+${hxtool} query \
+	--expr=3D'"%{certificate.hash.sha1}EQ "412120212A2CBFD777DE5499ECB4724345=
F33F16"' \
+	FILE:$srcdir/data/kdc.crt > /dev/null || exit 1
+
+
 exit 0
-
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_req=
.in
--- a/head/crypto/heimdal/lib/hx509/test_req.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/hx509/test_req.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2005 - 2007 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2005 - 2007 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_req.in 21341 2007-06-26 14:20:56Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_sof=
t_pkcs11.c
--- a/head/crypto/heimdal/lib/hx509/test_soft_pkcs11.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/test_soft_pkcs11.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2006 - 2008 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "hx_locl.h"
@@ -39,9 +39,9 @@
=20
=20
 static CK_RV
-find_object(CK_SESSION_HANDLE session,=20
+find_object(CK_SESSION_HANDLE session,
 	    char *id,
-	    CK_OBJECT_CLASS key_class,=20
+	    CK_OBJECT_CLASS key_class,
 	    CK_OBJECT_HANDLE_PTR object)
 {
     CK_ULONG object_count;
@@ -119,11 +119,11 @@
     if ((slot_info.flags & CKF_TOKEN_PRESENT) =3D=3D 0)
 	errx(1, "no token present");
=20
-    ret =3D (*func->C_OpenSession)(slot, CKF_SERIAL_SESSION,=20
+    ret =3D (*func->C_OpenSession)(slot, CKF_SERIAL_SESSION,
 				 NULL, NULL, &session);
     if (ret !=3D CKR_OK)
 	errx(1, "C_OpenSession failed: %d", (int)ret);
-   =20
+
     ret =3D (*func->C_GetTokenInfo)(slot, &token_info);
     if (ret)
 	errx(1, "C_GetTokenInfo1 failed: %d", (int)ret);
@@ -159,7 +159,7 @@
 	ret =3D (*func->C_SignInit)(session, &mechanism, private);
 	if (ret !=3D CKR_OK)
 	    return 1;
-=09
+
 	ck_sigsize =3D sizeof(signature);
 	ret =3D (*func->C_Sign)(session, (CK_BYTE *)sighash, strlen(sighash),
 			      (CK_BYTE *)signature, &ck_sigsize);
@@ -172,7 +172,7 @@
 	if (ret !=3D CKR_OK)
 	    return 1;
=20
-	ret =3D (*func->C_Verify)(session, (CK_BYTE *)signature, ck_sigsize,=20
+	ret =3D (*func->C_Verify)(session, (CK_BYTE *)signature, ck_sigsize,
 				(CK_BYTE *)sighash, strlen(sighash));
 	if (ret !=3D CKR_OK) {
 	    printf("message: %d\n", (int)ret);
@@ -192,7 +192,7 @@
 	ret =3D (*func->C_EncryptInit)(session, &mechanism, public);
 	if (ret !=3D CKR_OK)
 	    return 1;
-=09
+
 	ck_sigsize =3D sizeof(signature);
 	ret =3D (*func->C_Encrypt)(session, (CK_BYTE *)sighash, strlen(sighash),
 				 (CK_BYTE *)signature, &ck_sigsize);
@@ -206,14 +206,14 @@
 	    return 1;
=20
 	outsize =3D sizeof(outdata);
-	ret =3D (*func->C_Decrypt)(session, (CK_BYTE *)signature, ck_sigsize,=20
+	ret =3D (*func->C_Decrypt)(session, (CK_BYTE *)signature, ck_sigsize,
 				 (CK_BYTE *)outdata, &outsize);
 	if (ret !=3D CKR_OK) {
 	    printf("message: %d\n", (int)ret);
 	    return 1;
 	}
=20
-	if (memcmp(sighash, outdata, strlen(sighash)) !=3D 0)
+	if (ct_memcmp(sighash, outdata, strlen(sighash)) !=3D 0)
 	    return 1;
     }
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/test_win=
dows.in
--- a/head/crypto/heimdal/lib/hx509/test_windows.in	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/hx509/test_windows.in	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #
@@ -31,7 +31,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: test_windows.in 21004 2007-06-08 01:53:10Z lha $
+# $Id$
 #
=20
 srcdir=3D"@srcdir@"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/tst-cryp=
to-available2
--- a/head/crypto/heimdal/lib/hx509/tst-crypto-available2	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/tst-crypto-available2	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,5 @@
+2.16.840.1.101.3.4.2.3
+2.16.840.1.101.3.4.2.2
 2.16.840.1.101.3.4.2.1
 1.3.14.3.2.26
 1.2.840.113549.2.5
-1.2.840.113549.2.2
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/tst-cryp=
to-select1
--- a/head/crypto/heimdal/lib/hx509/tst-crypto-select1	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/tst-crypto-select1	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,1 +1,1 @@
-1.3.14.3.2.26
+2.16.840.1.101.3.4.2.1
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/tst-cryp=
to-select2
--- a/head/crypto/heimdal/lib/hx509/tst-crypto-select2	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/tst-crypto-select2	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,1 +1,1 @@
-1.2.840.113549.1.1.5
+1.2.840.113549.1.1.11
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/hx509/version-=
script.map
--- a/head/crypto/heimdal/lib/hx509/version-script.map	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/hx509/version-script.map	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,8 +1,31 @@
 # $Id$
=20
-HEIMDAL_X509_1.0 {
+HEIMDAL_X509_1.2 {
 	global:
-		initialize_hx_error_table_r;
+		_hx509_cert_assign_key;
+		_hx509_cert_private_key;
+		_hx509_certs_keys_free;
+		_hx509_certs_keys_get;
+		_hx509_expr_eval;
+		_hx509_expr_free;
+		_hx509_expr_parse;
+		_hx509_generate_private_key;
+		_hx509_generate_private_key_bits;
+		_hx509_generate_private_key_free;
+		_hx509_generate_private_key_init;
+		_hx509_generate_private_key_is_ca;
+		_hx509_map_file_os;
+		_hx509_name_from_Name;
+		_hx509_private_key_ref;
+		_hx509_request_add_dns_name;
+		_hx509_request_add_email;
+		_hx509_request_parse;
+		_hx509_request_print;
+		_hx509_request_set_email;
+		_hx509_request_to_pkcs10;
+		_hx509_request_to_pkcs10;
+		_hx509_unmap_file_os;
+		_hx509_write_file;
 		hx509_bitstring_print;
 		hx509_ca_sign;
 		hx509_ca_sign_self;
@@ -26,15 +49,18 @@
 		hx509_ca_tbs_set_spki;
 		hx509_ca_tbs_set_subject;
 		hx509_ca_tbs_set_template;
+		hx509_ca_tbs_set_unique;
 		hx509_ca_tbs_subject_expand;
 		hx509_ca_tbs_template_units;
+		hx509_cert;
+		hx509_cert_attribute;
 		hx509_cert_binary;
 		hx509_cert_check_eku;
 		hx509_cert_cmp;
 		hx509_cert_find_subjectAltName_otherName;
 		hx509_cert_free;
 		hx509_cert_get_SPKI;
-		hx509_cert_attribute;
+		hx509_cert_get_SPKI_AlgorithmIdentifier;
 		hx509_cert_get_attribute;
 		hx509_cert_get_base_subject;
 		hx509_cert_get_friendly_name;
@@ -43,26 +69,32 @@
 		hx509_cert_get_notBefore;
 		hx509_cert_get_serialnumber;
 		hx509_cert_get_subject;
+		hx509_cert_get_issuer_unique_id;
+		hx509_cert_get_subject_unique_id;
 		hx509_cert_init;
 		hx509_cert_init_data;
 		hx509_cert_keyusage_print;
-		hx509_cert;
+		hx509_cert_public_encrypt;
 		hx509_cert_ref;
 		hx509_cert_set_friendly_name;
 		hx509_certs_add;
 		hx509_certs_append;
 		hx509_certs_end_seq;
+		hx509_certs_ref;
+		hx509_certs_filter;
 		hx509_certs_find;
 		hx509_certs_free;
 		hx509_certs_info;
 		hx509_certs_init;
 		hx509_certs_iter;
+		hx509_certs_iter_f;
 		hx509_certs_merge;
 		hx509_certs_next_cert;
 		hx509_certs_start_seq;
 		hx509_certs_store;
 		hx509_ci_print_names;
 		hx509_clear_error_string;
+		hx509_cms_create_signed;
 		hx509_cms_create_signed_1;
 		hx509_cms_decrypt_encrypted;
 		hx509_cms_envelope_1;
@@ -80,6 +112,7 @@
 		hx509_crl_sign;
 		hx509_crypto_aes128_cbc;
 		hx509_crypto_aes256_cbc;
+		hx509_crypto_allow_weak;
 		hx509_crypto_available;
 		hx509_crypto_decrypt;
 		hx509_crypto_des_rsdi_ede3_cbc;
@@ -93,15 +126,20 @@
 		hx509_crypto_select;
 		hx509_crypto_set_key_data;
 		hx509_crypto_set_key_name;
+		hx509_crypto_set_padding;
 		hx509_crypto_set_params;
 		hx509_crypto_set_random_key;
 		hx509_env_add;
+		hx509_env_add_binding;
+		hx509_env_find;
+		hx509_env_find_binding;
 		hx509_env_free;
 		hx509_env_init;
 		hx509_env_lfind;
 		hx509_err;
 		hx509_free_error_string;
 		hx509_free_octet_string_list;
+		hx509_find_private_alg;
 		hx509_general_name_unparse;
 		hx509_get_error_string;
 		hx509_get_one_cert;
@@ -116,6 +154,7 @@
 		hx509_lock_reset_passwords;
 		hx509_lock_reset_promper;
 		hx509_lock_set_prompter;
+		hx509_name_binary;
 		hx509_name_cmp;
 		hx509_name_copy;
 		hx509_name_expand;
@@ -123,27 +162,47 @@
 		hx509_name_is_null_p;
 		hx509_name_normalize;
 		hx509_name_to_Name;
-		hx509_name_binary;
 		hx509_name_to_string;
 		hx509_ocsp_request;
 		hx509_ocsp_verify;
 		hx509_oid_print;
 		hx509_oid_sprint;
 		hx509_parse_name;
+		hx509_parse_private_key;
+		hx509_peer_info_add_cms_alg;
 		hx509_peer_info_alloc;
 		hx509_peer_info_free;
 		hx509_peer_info_set_cert;
 		hx509_peer_info_set_cms_algs;
+		hx509_pem_add_header;
+		hx509_pem_find_header;
+		hx509_pem_free_header;
+		hx509_pem_read;
+		hx509_pem_write;
 		hx509_print_stdout;
+		hx509_print_cert;
+		hx509_private_key_assign_rsa;
+		hx509_private_key_free;
+		hx509_private_key_private_decrypt;
+		hx509_private_key_init;
+		hx509_private_key2SPKI;
 		hx509_prompt_hidden;
 		hx509_query_alloc;
 		hx509_query_free;
 		hx509_query_match_cmp_func;
+		hx509_query_match_eku;
+		hx509_query_match_expr;
 		hx509_query_match_friendly_name;
 		hx509_query_match_issuer_serial;
 		hx509_query_match_option;
 		hx509_query_statistic_file;
 		hx509_query_unparse_stats;
+		hx509_request_get_name;
+		hx509_request_get_SubjectPublicKeyInfo;
+		hx509_request_free;
+		hx509_request_init;
+		hx509_request_set_name;
+		hx509_request_set_SubjectPublicKeyInfo;
 		hx509_revoke_add_crl;
 		hx509_revoke_add_ocsp;
 		hx509_revoke_free;
@@ -152,10 +211,8 @@
 		hx509_revoke_verify;
 		hx509_set_error_string;
 		hx509_set_error_stringv;
-		hx509_signature_md2;
 		hx509_signature_md5;
 		hx509_signature_rsa;
-		hx509_signature_rsa_with_md2;
 		hx509_signature_rsa_with_md5;
 		hx509_signature_rsa_with_sha1;
 		hx509_signature_rsa_with_sha256;
@@ -183,42 +240,8 @@
 		hx509_verify_set_strict_rfc3280_verification;
 		hx509_verify_set_time;
 		hx509_verify_signature;
-		hx509_pem_write;
-		hx509_pem_add_header;
-		hx509_pem_find_header;
-		hx509_pem_free_header;
 		hx509_xfree;
-		_hx509_write_file;
-		_hx509_map_file;
-		_hx509_map_file_os;
-		_hx509_unmap_file;
-		_hx509_unmap_file_os;
-		_hx509_certs_keys_free;
-		_hx509_certs_keys_get;
-		_hx509_request_init;
-		_hx509_request_add_dns_name;
-		_hx509_request_add_email;
-		_hx509_request_get_name;
-		_hx509_request_set_name;
-		_hx509_request_set_email;
-		_hx509_request_get_SubjectPublicKeyInfo;
-		_hx509_request_set_SubjectPublicKeyInfo;
-		_hx509_request_to_pkcs10;
-		_hx509_request_to_pkcs10;
-		_hx509_request_free;
-		_hx509_request_print;
-		_hx509_request_parse;
-		_hx509_private_key_ref;
-		_hx509_private_key_free;
-		_hx509_private_key2SPKI;
-		_hx509_generate_private_key_init;
-		_hx509_generate_private_key_is_ca;
-		_hx509_generate_private_key_bits;
-		_hx509_generate_private_key;
-		_hx509_generate_private_key_free;
-		_hx509_cert_assign_key;
-		_hx509_cert_private_key;
-		_hx509_name_from_Name;
+		initialize_hx_error_table_r;
 		# pkcs11 symbols
 		C_GetFunctionList;
 	local:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/ChangeLog
--- a/head/crypto/heimdal/lib/kadm5/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,13 +1,19 @@
-2008-01-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* ipropd_master.c: Only log "sending AYT" once, pointed out by Dr
+	A V Le Blanc.
+=09
+
+2008-01-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* default_keys.c: Use hdb_free_keys().
=20
-2008-01-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-01-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add check-cracklib.pl, flush.c,
 	sample_passwd_check.c
=20
-2007-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-12-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* use hdb_db_dir() and hdb_default_db()
=20
@@ -16,11 +22,11 @@
 	* init_c.c: We are getting default_client, not client. this way
 	the user can override the result.
 =09
-2007-09-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-09-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* iprop.8: fix spelling, From Antoine Jacoutt.
=20
-2007-08-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* version-script.map: export _kadm5_unmarshal_params,
 	_kadm5_acl_check_permission
@@ -29,26 +35,26 @@
=20
 	* log.c: Unexport the specific log replay operations.
 =09
-2007-08-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: build sample_passwd_check.la as part of noinst.
=20
 	* sample_passwd_check.c: Add missing prototype for check_length().
=20
-2007-08-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* log.c: Sprinkle krb5_set_error_string().
=20
 	* ipropd_slave.c: Provide better error why kadm5_log_replay
 	failed.
=20
-2007-08-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_master.c: - don't push whole database to the new client
 	every time.  - make slaves get the whole new database if they have
 	a newer log the the master (and thus have them go back in time).
=20
-2007-08-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_slave.c: make more sane.
=20
@@ -63,12 +69,12 @@
=20
 	* ipropd_master.c: Start the server at the current version, not 0.
=20
-2007-08-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_master.c: Add more logging, to figure out what is
 	happening in the master.
=20
-2007-08-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add version-script for libkadm5srv.la
=20
@@ -81,42 +87,42 @@
 	hostname, catch signals and print why we are quiting, make nop
 	cause one new version, not two
=20
-2007-07-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_master.c (send_diffs): make current slave's version
 	uptodate when diff have been sent.
 =09
-2007-07-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_slave.c: More comments and some more error checking.
 =09
-2007-07-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_c.c (get_cache_principal): make sure id is reset if we
 	fail. From Benjamin Bennet.
=20
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* context_s.c (find_db_spec): match realm-less as the default
 	realm.
=20
 	* Makefile.am: New library version.
=20
-2007-07-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* context_s.c: Use hdb_get_dbinfo to pick up configuration.
 	ctx->config.realm can be NULL, check for that, from Bjorn S.
 =09
-2007-07-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_c.c: Try harder to use the right principal.
=20
-2007-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_slave.c: Catch return value from krb5_program_setup. From
 	Steven Luo.
 =09
-2007-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* delete_s.c: Write log entry after store is successful, rename
 	out goto statments.
@@ -131,7 +137,7 @@
=20
 	* create_s.c: Write log entry after store is successful.
 =09
-2007-05-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* iprop-commands.in: Add default values to make this working
 	again.
@@ -151,7 +157,7 @@
 	* log.c (kadm5_log_previous): document assumptions and make less
 	broken.  Bug report from Ronny Blomme.
 =09
-2007-02-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-02-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* admin.h: add support to get aliases
=20
@@ -161,22 +167,22 @@
=20
 	* iprop-log.8: Small fixes, from David Love.
 =09
-2006-12-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_c.c: if the user have a kadmin/admin initial ticket, don't
 	ask for password, just use the credential instead.
 =09
-2006-12-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ipropd_master.c: Use strcspn to remove \n from string returned
-	by fgets.  From Bj=F6rn Sandell
+	by fgets.  From Bj=C3=B6rn Sandell
 =09
-2006-11-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_c.c (kadm_connect): clear error string before trying to
 	print a errno, this way we don't pick up a random failure code
 =09
-2006-11-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_slave.c: Make krb5_get_init_creds_opt_free take a context
 	argument.
@@ -184,15 +190,15 @@
 	* init_c.c: Make krb5_get_init_creds_opt_free take a context
 	argument.
 =09
-2006-10-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ent_setup.c: Try to not leak memory.
 =09
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: split build files into dist_ and noinst_ SOURCES
 =09
-2006-08-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* get_s.c: Add KRB5_KDB_ALLOW_DIGEST
=20
@@ -200,12 +206,12 @@
=20
 	* admin.h: Add KRB5_KDB_ALLOW_DIGEST
 =09
-2006-06-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-cracklib.pl: Add password reuse checking. From Harald
 	Barth.
 =09
-2006-06-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ent_setup.c (attr_to_flags): Add KRB5_KDB_ALLOW_KERBEROS4
=20
@@ -213,31 +219,31 @@
=20
 	* admin.h: Add KRB5_KDB_ALLOW_KERBEROS4
 =09
-2006-06-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ent_setup.c (attr_to_flags): Add KRB5_KDB_TRUSTED_FOR_DELEGATION
=20
-2006-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* password_quality.c (kadm5_check_password_quality): set error
 	message in context.
 =09
-2006-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* iprop-log.c: Avoid shadowing.
=20
 	* rename_s.c: Avoid shadowing.
=20
-2006-05-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* privs_c.c (kadm5_c_get_privs): privs is a uint32_t, let copy it
 	that way.
 =09
-2006-05-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Rename u_intXX_t to uintXX_t
=20
-2006-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* chpass_s.c,delete_s.c,get_s.c,log.c,modify_s.c,randkey_s.c,rename_s.c:
 	Pass in HDB_F_GET_ANY to all ->hdb fetch to hint what entries we are look=
ing for
@@ -265,12 +271,12 @@
 	* chpass_s.c: Break out the that we request from principal from
 	the entry and pass it in as a separate argument.
 =09
-2006-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* create_s.c (create_principal*): If client doesn't send kvno,
 	make sure to set it to 1.
 =09
-2006-04-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* log.c: (kadm5_log_rename): handle errors better
 	Fixes Coverity, NetBSD CID#628
@@ -285,39 +291,39 @@
 	* init_c.c (_kadm5_c_get_cred_cache): Free client principal in
 	case of error. Coverity NetBSD CID#1908
 =09
-2006-02-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* kadm5_err.et: (PASS_REUSE): Spelling,=20
-	from V=E1clav H?la <ax at natur.cuni.cz>
+	from V=C3=A1clav H?la <ax at natur.cuni.cz>
 =09
-2006-01-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* send_recv.c: Clear error-string when introducing new errors.
=20
 	* *_c.c: Clear error-string when introducing new errors.
 =09
-2006-01-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am (libkadm5clnt.la) doesn't depend on libhdb, remove
 	dependency
 =09
-2005-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* memset hdb_entry_ex before use
 =09
-2005-12-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Wrap hdb_entry with hdb_entry_ex, patch originally=20
 	from Andrew Bartlet
=20
-2005-11-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-11-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* context_s.c (set_field): try another way to calculate the path
 	to the database/logfile/signal-socket
=20
 	* log.c (kadm5_log_init): set error string on failures
 =09
-2005-09-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Constify password.
=20
@@ -327,11 +333,11 @@
 =09
 	* get_s.c (kadm5_s_get_principal): clear error string
 =09
-2005-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* iprop-log.8: More text about iprop-log.
 =09
-2005-08-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* iprop.8: SEE ALSO iprop-log.
=20
@@ -343,7 +349,7 @@
 	iprop-log.
=20
 	* log.c (kadm5_log_foreach): add a context variable and pass it
-	down to `func=B4.
+	down to `func=C2=B4.
=20
 	* iprop-commands.in: Move truncate_log and replay_log into
 	iprop-log.
@@ -371,7 +377,7 @@
 	* Makefile.am: New program iprop-log that incorperates dump_log as
 	a subcommand, truncate_log and replay_log soon to come after.
 =09
-2005-08-11 Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-11 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* get_s.c: Implement KADM5_LAST_PWD_CHANGE.
 =09
@@ -393,7 +399,7 @@
=20
 	* admin.h: Add more TL types (password and extension).
=20
-2005-06-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* constify
=20
@@ -414,7 +420,7 @@
=20
 	* common_glue.c: rename variable exp to expression
=20
-2005-05-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ent_setup.c (attr_to_flags): check for KRB5_KDB_OK_AS_DELEGATE
 =09
@@ -422,7 +428,7 @@
=20
 	* admin.h: add KRB5_KDB_OK_AS_DELEGATE, sync KRB5_TL_ flags
=20
-2005-05-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kadm5_pwcheck.3: please mdoclint
=20
@@ -441,7 +447,7 @@
=20
 	* ipropd_master.c: Don't test HAVE_DAEMON since roken supplies it.
=20
-2005-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_c.c (_kadm5_c_init_context): fix memory leak in case of
 	failure
@@ -454,12 +460,12 @@
 	* test_pw_quality.c (main): Call kadm5_setup_passwd_quality_check
 	and kadm5_add_passwd_quality_verifier.
=20
-2005-04-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* default_keys.c: #include <err.h>, only print salt it its longer
 	then 0, use krb5_err instead of errx where appropriate
 =09
-2005-04-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_slave.c: add the documented option --port
=20
@@ -467,25 +473,25 @@
 =09
 	* dump_log.c: use the newly generated units function
=20
-2005-04-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* dump_log.c: use strlcpy
 =09
 	* password_quality.c: don't use sizeof(pointer)
 =09
-2005-04-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* check-cracklib.pl: external password verifier sample
=20
 	* password_quality.c (kadm5_add_passwd_quality_verifier): if NULL
 	is passed in, load defaults
=20
-2005-04-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* password_quality.c: add an end tag to the external password
 	quality check protocol
=20
-2005-04-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* password_quality.c: add external passsword quality check builtin
 	module
@@ -497,7 +503,7 @@
 	To approve password a, make the test program return APPROVED on
 	stderr and fail with exit code 0.
 =09
-2004-10-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: bump version to 7:7:0 and 6:5:2
 =09
@@ -511,7 +517,7 @@
=20
 	* ipropd_master.c: add help strings to some options
 =09
-2004-09-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* chpass_s.c: deal with changed prototype for _kadm5_free_keys
 =09
@@ -522,7 +528,7 @@
 	(function) static variable and returned allocated memory
 	(_kadm5_generate_key_set): free enctypes returned by parse_key_set
=20
-2004-09-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* set_keys.c: Fix memory leak, don't return stack variables From
 	Andrew Bartlett
@@ -530,7 +536,7 @@
 	* set_keys.c: make all_etypes const and move outside function to
 	avoid returning data on stack
 =09
-2004-08-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* acl.c (fetch_acl): use " \t\n" instead of just "\n" for the
 	delim of the third element, this is so we can match
@@ -539,7 +545,7 @@
 	what really happen was that the last <SPC> was stamped out, and
 	the it never strtok_r never needed to parse over it.
 =09
-2004-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* set_keys.c (_kadm5_generate_key_set): since arcfour-hmac-md5 is
 	without salting, some people tries to add the string
@@ -550,17 +556,17 @@
=20
 	* ipropd_slave.c: add --detach
=20
-2004-07-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-07-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ad.c: use new tsasl interface remove debug printf add upn to
 	computer-accounts
 =09
-2004-06-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ad.c: implement kadm5_ad_init_with_password_ctx set more error
 	strings
 =09
-2004-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: man_MANS =3D kadm5_pwcheck.3
 =09
@@ -571,22 +577,22 @@
 =09
 	* kadm5-pwcheck.h: new password check interface
 =09
-2004-06-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_master.c (main): process all slaves, not just up to the
 	last slave sending data
-	(bug report from Bj=F6rn Sandell <biorn at dce.chalmers.se>)
+	(bug report from Bj=C3=B6rn Sandell <biorn at dce.chalmers.se>)
 	(*): only send one ARE_YOU_THERE
=20
-2004-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ad.c: use krb5_set_password_using_ccache
 =09
-2004-06-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ad.c: try handle spn's better
 =09
-2004-05-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ad.c: add expiration time
 =09
@@ -594,7 +600,7 @@
 =09
 	* ad.c: handle create and delete
 =09
-2004-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ad.c: more code for get, handle attributes
 =09
@@ -603,7 +609,7 @@
=20
 	* ad.c: more code for get, only fetches kvno for now
 =09
-2004-05-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ad.c: add support for tsasl
 =09
@@ -618,12 +624,12 @@
 =09
 	* ad.c: framework for windows AD backend
 =09
-2004-03-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* create_s.c (kadm5_s_create_principal): remove old XXX command
 	and related code, _kadm5_set_keys will do all this now
 =09
-2004-02-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* set_keys.c (_kadm5_set_keys_randomly): make sure enctype to copy
 	enctype for des keys From: Andrew Bartlett <abartlet at samba.org>
@@ -640,27 +646,27 @@
 	* set_keys.c (_kadm5_set_*): don't change the kvno, let the callee
 	to that
=20
-2003-12-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* chpass_s.c (change): fix same-password-again by decrypting keys
 	and setting an error code From: Buck Huppmann <buckh at pobox.com>
 =09
-2003-12-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_c.c (_kadm5_c_init_context): catch errors from strdup and
 	other krb5_ functions
=20
-2003-12-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rename_s.c (kadm5_s_rename_principal): allow principal to change
 	realm From Panasas Inc
 =09
-2003-12-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* destroy_c.c (kadm5_c_destroy): fix memory leaks, From Panasas,
 	Inc
=20
-2003-11-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* iprop.h: don't include <krb5-private.h>
 =09
@@ -670,7 +676,7 @@
 	* ipropd_master.c: stop using krb5 lib private byte-frobbing
 	functions and replace them with with krb5_storage
 =09
-2003-11-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_slave.c (receive_loop): when seeking over the entries we
 	already have, skip over the trailer.  From: Jeffrey Hutzelman
@@ -680,14 +686,14 @@
 	replay_log.c,truncate_log.c: parse kdc.conf
 	From: Jeffrey Hutzelman <jhutz at cmu.edu>
=20
-2003-10-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: +=3D test_pw_quality
 =09
 	* test_pw_quality.c: test program for verifying password quality
 	function
=20
-2003-09-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add and enable check program default_keys
 =09
@@ -696,61 +702,61 @@
 	* init_c.c: use
 	krb5_get_init_creds_opt_alloc/krb5_get_init_creds_opt_free
=20
-2003-08-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* set_keys.c (_kadm5_set_keys_randomly): remove dup return
 =09
 	* ipropd_master.c (main): make sure current_version is initialized
 =09
-2003-08-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* set_keys.c: use default_keys for the both random keys and
 	password derived keys if its defined
 =09
-2003-07-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_slave.c (receive_everything): switch close and rename
 	From: Alf Wachsmann <alfw at SLAC.Stanford.EDU>
 =09
-2003-07-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* iprop.h, ipropd_master.c, ipropd_slave.c:
 	Add probing from the server that the client is still there, also
 	make the client check that the server is probing.
=20
-2003-07-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* truncate_log.c (main): add missing ``if (ret)''
 =09
-2003-06-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* set_keys.c (make_keys): add AES support
 =09
 	* set_keys.c: fix off by one in the aes case, pointed out by Ken
 	Raeburn
=20
-2003-04-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* set_keys.c (_kadm5_set_keys_randomly): add
 	ETYPE_AES256_CTS_HMAC_SHA1_96 key when configuried with aes
 	support
=20
-2003-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* send_recv.c: check return values from krb5_data_alloc
 	* log.c: check return values from krb5_data_alloc
 =09
-2003-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* dump_log.c (print_entry): check return values from
 	krb5_data_alloc
=20
-2003-04-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* init_c.c (kadm_connect): if a context realm was passed in, use
 	that to form the kadmin/admin principal
 =09
-2003-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ipropd_master.c (main): make sure we don't consider dead slave
 	for select processing
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/Makefile=
.am
--- a/head/crypto/heimdal/lib/kadm5/Makefile.am	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/Makefile.am	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,9 +1,7 @@
-# $Id: Makefile.am 22403 2008-01-11 14:37:26Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-SLC =3D $(top_builddir)/lib/sl/slc
-
 lib_LTLIBRARIES =3D libkadm5srv.la libkadm5clnt.la
 libkadm5srv_la_LDFLAGS =3D -version-info 8:1:0
 libkadm5clnt_la_LDFLAGS =3D -version-info 7:1:0
@@ -34,7 +32,9 @@
 kadm5includedir =3D $(includedir)/kadm5
 buildkadm5include =3D $(buildinclude)/kadm5
=20
-dist_kadm5include_HEADERS =3D admin.h private.h kadm5-protos.h kadm5-priva=
te.h
+dist_kadm5include_HEADERS =3D admin.h private.h kadm5-pwcheck.h
+dist_kadm5include_HEADERS +=3D kadm5-protos.h kadm5-private.h
+
 nodist_kadm5include_HEADERS =3D kadm5_err.h
=20
 install-build-headers:: $(dist_kadm5include_HEADERS) $(nodist_kadm5include=
_HEADERS)
@@ -71,7 +71,6 @@
 	randkey_c.c				\
 	rename_c.c				\
 	send_recv.c				\
-	kadm5-pwcheck.h				\
 	admin.h
=20
 nodist_libkadm5clnt_la_SOURCES =3D		\
@@ -108,13 +107,15 @@
 	server_glue.c				\
 	set_keys.c				\
 	set_modifier.c				\
-	kadm5-pwcheck.h				\
 	admin.h
=20
 nodist_libkadm5srv_la_SOURCES =3D 		\
 	kadm5_err.c				\
 	kadm5_err.h
=20
+libkadm5srv_la_DEPENDENCIES =3D			\
+	version-script.map
+
 dist_iprop_log_SOURCES =3D iprop-log.c
 nodist_iprop_log_SOURCES =3D iprop-commands.c
=20
@@ -127,7 +128,6 @@
 LDADD =3D \
 	libkadm5srv.la \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_hcrypto) \
@@ -139,7 +139,6 @@
 iprop_log_LDADD =3D \
 	libkadm5srv.la \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_hcrypto) \
@@ -183,6 +182,12 @@
 		|| rm -f kadm5-private.h
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	iprop-log-version.rc \
+	ipropd-master-version.rc \
+	ipropd-slave-version.rc \
+	libkadm5srv-version.rc \
+	libkadm5srv-exports.def \
 	kadm5_err.et \
 	iprop-commands.in \
 	$(man_MANS) \
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/Makefile=
.in
--- a/head/crypto/heimdal/lib/kadm5/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22403 2008-01-11 14:37:26Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -51,7 +53,7 @@
 subdir =3D lib/kadm5
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -66,7 +68,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -80,9 +82,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -90,23 +95,38 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(libexecdir)" \
 	"$(DESTDIR)$(sbindir)" "$(DESTDIR)$(man3dir)" \
 	"$(DESTDIR)$(man8dir)" "$(DESTDIR)$(kadm5includedir)" \
 	"$(DESTDIR)$(kadm5includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES)
 am__DEPENDENCIES_1 =3D
 libkadm5clnt_la_DEPENDENCIES =3D $(am__DEPENDENCIES_1) \
@@ -121,8 +141,6 @@
 libkadm5clnt_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libkadm5clnt_la_LDFLAGS) $(LDFLAGS) -o $@
-libkadm5srv_la_DEPENDENCIES =3D $(am__DEPENDENCIES_1) ../krb5/libkrb5.la \
-	../hdb/libhdb.la $(am__DEPENDENCIES_1)
 dist_libkadm5srv_la_OBJECTS =3D acl.lo bump_pw_expire.lo chpass_s.lo \
 	common_glue.lo context_s.lo create_s.lo delete_s.lo \
 	destroy_s.lo ent_setup.lo error.lo flush_s.lo free.lo \
@@ -141,14 +159,12 @@
 sample_passwd_check_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(sample_passwd_check_la_LDFLAGS) $(LDFLAGS) -o $@
-libexecPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
-sbinPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 PROGRAMS =3D $(libexec_PROGRAMS) $(noinst_PROGRAMS) $(sbin_PROGRAMS)
 am_default_keys_OBJECTS =3D default_keys.$(OBJEXT)
 default_keys_OBJECTS =3D $(am_default_keys_OBJECTS)
 default_keys_LDADD =3D $(LDADD)
 default_keys_DEPENDENCIES =3D libkadm5srv.la \
-	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/hdb/libhdb.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
@@ -158,7 +174,7 @@
 iprop_log_OBJECTS =3D $(dist_iprop_log_OBJECTS) \
 	$(nodist_iprop_log_OBJECTS)
 iprop_log_DEPENDENCIES =3D libkadm5srv.la \
-	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/hdb/libhdb.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
 	$(top_builddir)/lib/sl/libsl.la $(am__DEPENDENCIES_1) \
@@ -169,7 +185,7 @@
 ipropd_master_OBJECTS =3D $(am_ipropd_master_OBJECTS)
 ipropd_master_LDADD =3D $(LDADD)
 ipropd_master_DEPENDENCIES =3D libkadm5srv.la \
-	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/hdb/libhdb.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
@@ -179,7 +195,7 @@
 ipropd_slave_OBJECTS =3D $(am_ipropd_slave_OBJECTS)
 ipropd_slave_LDADD =3D $(LDADD)
 ipropd_slave_DEPENDENCIES =3D libkadm5srv.la \
-	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/hdb/libhdb.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
@@ -188,14 +204,14 @@
 test_pw_quality_OBJECTS =3D test_pw_quality.$(OBJEXT)
 test_pw_quality_LDADD =3D $(LDADD)
 test_pw_quality_DEPENDENCIES =3D libkadm5srv.la \
-	$(top_builddir)/lib/hdb/libhdb.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/hdb/libhdb.la \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
 	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -221,8 +237,6 @@
 man3dir =3D $(mandir)/man3
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
-dist_kadm5includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-nodist_kadm5includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
 HEADERS =3D $(dist_kadm5include_HEADERS) $(nodist_kadm5include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
@@ -231,49 +245,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -297,10 +320,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -317,6 +341,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -332,31 +358,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -371,10 +411,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -415,31 +457,35 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
-SLC =3D $(top_builddir)/lib/sl/slc
 lib_LTLIBRARIES =3D libkadm5srv.la libkadm5clnt.la
 libkadm5srv_la_LDFLAGS =3D -version-info 8:1:0 $(am__append_1)
 libkadm5clnt_la_LDFLAGS =3D -version-info 7:1:0
@@ -456,7 +502,8 @@
 default_keys_SOURCES =3D default_keys.c
 kadm5includedir =3D $(includedir)/kadm5
 buildkadm5include =3D $(buildinclude)/kadm5
-dist_kadm5include_HEADERS =3D admin.h private.h kadm5-protos.h kadm5-priva=
te.h
+dist_kadm5include_HEADERS =3D admin.h private.h kadm5-pwcheck.h \
+	kadm5-protos.h kadm5-private.h
 nodist_kadm5include_HEADERS =3D kadm5_err.h
 dist_libkadm5clnt_la_SOURCES =3D \
 	ad.c					\
@@ -479,7 +526,6 @@
 	randkey_c.c				\
 	rename_c.c				\
 	send_recv.c				\
-	kadm5-pwcheck.h				\
 	admin.h
=20
 nodist_libkadm5clnt_la_SOURCES =3D \
@@ -516,13 +562,15 @@
 	server_glue.c				\
 	set_keys.c				\
 	set_modifier.c				\
-	kadm5-pwcheck.h				\
 	admin.h
=20
 nodist_libkadm5srv_la_SOURCES =3D \
 	kadm5_err.c				\
 	kadm5_err.h
=20
+libkadm5srv_la_DEPENDENCIES =3D \
+	version-script.map
+
 dist_iprop_log_SOURCES =3D iprop-log.c
 nodist_iprop_log_SOURCES =3D iprop-commands.c
 ipropd_master_SOURCES =3D ipropd_master.c ipropd_common.c iprop.h kadm5_lo=
cl.h
@@ -531,7 +579,6 @@
 LDADD =3D \
 	libkadm5srv.la \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_hcrypto) \
@@ -543,7 +590,6 @@
 iprop_log_LDADD =3D \
 	libkadm5srv.la \
 	$(top_builddir)/lib/hdb/libhdb.la \
-	$(LIB_openldap) \
 	$(top_builddir)/lib/krb5/libkrb5.la \
 	$(top_builddir)/lib/asn1/libasn1.la \
 	$(LIB_hcrypto) \
@@ -557,6 +603,12 @@
 CLEANFILES =3D kadm5_err.c kadm5_err.h iprop-commands.h iprop-commands.c
 proto_opts =3D -q -R '^(_|kadm5_c_|kadm5_s_|kadm5_log)' -P comment
 EXTRA_DIST =3D \
+	NTMakefile \
+	iprop-log-version.rc \
+	ipropd-master-version.rc \
+	ipropd-slave-version.rc \
+	libkadm5srv-version.rc \
+	libkadm5srv-exports.def \
 	kadm5_err.et \
 	iprop-commands.in \
 	$(man_MANS) \
@@ -568,19 +620,19 @@
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/kadm5=
/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/kadm5/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/kadm5/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/kadm5/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -598,23 +650,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -642,74 +699,108 @@
 	$(sample_passwd_check_la_LINK)  $(sample_passwd_check_la_OBJECTS) $(sampl=
e_passwd_check_la_LIBADD) $(LIBS)
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-libexecPROGRAMS: $(libexec_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(libexecdir)" || $(MKDIR_P) "$(DESTDIR)$(libexecdir)"
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPRO=
GRAMS_INSTALL) '$$p' '$(DESTDIR)$(libexecdir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(libexecPROGRAMS_I=
NSTALL) "$$p" "$(DESTDIR)$(libexecdir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexecdir)=
$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexecdir)$$dir" =
|| exit $$?; \
+	    } \
+	; done
=20
 uninstall-libexecPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(libexecdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(libexecdir)/$$f"; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$(libexecdir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexecdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexecdir)" && rm -f $$files
=20
 clean-libexecPROGRAMS:
-	@list=3D'$(libexec_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(libexec_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 install-sbinPROGRAMS: $(sbin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(sbindir)" || $(MKDIR_P) "$(DESTDIR)$(sbindir)"
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRA=
MS_INSTALL) '$$p' '$(DESTDIR)$(sbindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(sbinPROGRAMS_INST=
ALL) "$$p" "$(DESTDIR)$(sbindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(sbindir)$$d=
ir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(sbindir)$$dir" || =
exit $$?; \
+	    } \
+	; done
=20
 uninstall-sbinPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(sbindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(sbindir)/$$f"; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$(sbindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(sbindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(sbindir)" && rm -f $$files
=20
 clean-sbinPROGRAMS:
-	@list=3D'$(sbin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(sbin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 default_keys$(EXEEXT): $(default_keys_OBJECTS) $(default_keys_DEPENDENCIES=
)=20
 	@rm -f default_keys$(EXEEXT)
 	$(LINK) $(default_keys_OBJECTS) $(default_keys_LDADD) $(LIBS)
@@ -732,194 +823,266 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/acl.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ad.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/bump_pw_expire.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/chpass_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/chpass_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/client_glue.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/common_glue.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/context_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/create_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/create_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/default_keys.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/delete_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/delete_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/destroy_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/destroy_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ent_setup.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/error.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/flush_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/flush_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/free.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/get_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/get_princs_c.Plo at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/get_princs_s.Plo at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/get_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/init_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/init_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/iprop-commands.Po at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/iprop-log.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ipropd_common.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ipropd_master.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ipropd_slave.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/kadm5_err.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/keys.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/log.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/marshall.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/modify_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/modify_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/password_quality.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/privs_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/privs_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/randkey_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/randkey_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rename_c.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rename_s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/sample_passwd_check.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/send_recv.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/server_glue.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/set_keys.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/set_modifier.Plo at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_pw_quality.Po at am__qu=
ote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man3: $(man3_MANS) $(man_MANS)
+install-man3: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man3dir)" || $(MKDIR_P) "$(DESTDIR)$(man3dir)"
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man3:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
-install-man8: $(man8_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man3dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man3dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
 install-dist_kadm5includeHEADERS: $(dist_kadm5include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(kadm5includedir)" || $(MKDIR_P) "$(DESTDIR)$(kadm5includedir)"
-	@list=3D'$(dist_kadm5include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(dist_kadm5include_HEADERS)'; test -n "$(kadm5includedir)" || l=
ist=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(dist_kadm5includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(kadm5i=
ncludedir)/$$f'"; \
-	  $(dist_kadm5includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(kadm5included=
ir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(kadm5includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(kadm5includedir)" || exit $$?; \
 	done
=20
 uninstall-dist_kadm5includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(dist_kadm5include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(kadm5includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(kadm5includedir)/$$f"; \
-	done
+	@list=3D'$(dist_kadm5include_HEADERS)'; test -n "$(kadm5includedir)" || l=
ist=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(kadm5includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(kadm5includedir)" && rm -f $$files
 install-nodist_kadm5includeHEADERS: $(nodist_kadm5include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(kadm5includedir)" || $(MKDIR_P) "$(DESTDIR)$(kadm5includedir)"
-	@list=3D'$(nodist_kadm5include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_kadm5include_HEADERS)'; test -n "$(kadm5includedir)" ||=
 list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_kadm5includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(kadm=
5includedir)/$$f'"; \
-	  $(nodist_kadm5includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(kadm5includ=
edir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(kadm5includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(kadm5includedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_kadm5includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_kadm5include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(kadm5includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(kadm5includedir)/$$f"; \
-	done
+	@list=3D'$(nodist_kadm5include_HEADERS)'; test -n "$(kadm5includedir)" ||=
 list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(kadm5includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(kadm5includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -935,13 +1098,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -979,6 +1146,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -990,6 +1158,7 @@
 	clean-noinstPROGRAMS clean-sbinPROGRAMS mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -1000,6 +1169,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -1008,27 +1179,36 @@
 	install-nodist_kadm5includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libLTLIBRARIES install-libexecPROGRAMS \
 	install-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man3 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -1051,11 +1231,10 @@
 	uninstall-sbinPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man3 uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \
@@ -1150,6 +1329,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1235,7 +1417,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1288,6 +1470,7 @@
 		$(dist_libkadm5clnt_la_SOURCES) \
 		$(dist_libkadm5srv_la_SOURCES) \
 		|| rm -f kadm5-private.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/acl.c
--- a/head/crypto/heimdal/lib/kadm5/acl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/acl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: acl.c 17445 2006-05-05 10:37:46Z lha $");
+RCSID("$Id$");
=20
 static struct units acl_units[] =3D {
     { "all",		KADM5_PRIV_ALL },
@@ -44,7 +44,7 @@
     { "modify",		KADM5_PRIV_MODIFY },
     { "add",		KADM5_PRIV_ADD },
     { "get", 		KADM5_PRIV_GET },
-    { NULL }
+    { NULL,		0 }
 };
=20
 kadm5_ret_t
@@ -103,7 +103,7 @@
 	ret =3D krb5_parse_name(context->context, p, &this_princ);
 	if(ret)
 	    break;
-	if(!krb5_principal_compare(context->context,=20
+	if(!krb5_principal_compare(context->context,
 				   context->caller, this_princ)) {
 	    krb5_free_principal(context->context, this_princ);
 	    continue;
@@ -150,7 +150,7 @@
 {
     krb5_principal princ;
     krb5_error_code ret;
-   =20
+
     ret =3D krb5_parse_name(context->context, KADM5_ADMIN_SERVICE, &princ);
     if (ret)
 	return ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/ad.c
--- a/head/crypto/heimdal/lib/kadm5/ad.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/ad.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #define HAVE_TSASL 1
@@ -47,7 +47,7 @@
 #include <base64.h>
 #endif
=20
-RCSID("$Id: ad.c 17445 2006-05-05 10:37:46Z lha $");
+RCSID("$Id$");
=20
 #ifdef OPENLDAP
=20
@@ -141,7 +141,7 @@
     rc =3D ldap_search_s(ld, "", LDAP_SCOPE_BASE, NULL, attrs, 0, &m0);
     if (rc !=3D LDAP_SUCCESS)
 	goto out;
-   =20
+
     m =3D ldap_first_entry(ld, m0);
     if (m =3D=3D NULL) {
 	ldap_msgfree(m0);
@@ -175,7 +175,7 @@
 	ret =3D tsasl_request(peer, &in, &out);
 	if (in.tb_size !=3D 0) {
 	    free(in.tb_data);
-	    in.tb_data =3D NULL;=20
+	    in.tb_data =3D NULL;
 	    in.tb_size =3D 0;
 	}
 	if (ret !=3D TSASL_DONE && ret !=3D TSASL_CONTINUE) {
@@ -278,23 +278,23 @@
=20
 	asprintf(&domain, "_ldap._tcp.%s", context->realm);
 	if (domain =3D=3D NULL) {
-	    krb5_set_error_string(context->context, "malloc");
+	    krb5_set_error_message(context->context, KADM5_NO_SRV, "malloc");
 	    return KADM5_NO_SRV;
 	}
=20
 	r =3D dns_lookup(domain, "SRV");
 	free(domain);
 	if (r =3D=3D NULL) {
-	    krb5_set_error_string(context->context, "Didn't find ldap dns");
+	    krb5_set_error_message(context->context, KADM5_NO_SRV, "Didn't find l=
dap dns");
 	    return KADM5_NO_SRV;
-	}=09
+	}
=20
 	for (rr =3D r->head ; rr !=3D NULL; rr =3D rr->next) {
-	    if (rr->type !=3D T_SRV)
+	    if (rr->type !=3D rk_ns_t_srv)
 		continue;
 	    s =3D realloc(servers, sizeof(*servers) * (num_servers + 1));
 	    if (s =3D=3D NULL) {
-		krb5_set_error_string(context->context, "malloc");
+		krb5_set_error_message(context->context, KADM5_RPC_ERROR, "malloc");
 		dns_free_data(r);
 		goto fail;
 	    }
@@ -307,7 +307,7 @@
     }
=20
     if (num_servers =3D=3D 0) {
-	krb5_set_error_string(context->context, "No AD server found in DNS");
+	krb5_set_error_message(context->context, KADM5_NO_SRV, "No AD server foun=
d in DNS");
 	return KADM5_NO_SRV;
     }
=20
@@ -318,29 +318,29 @@
 	lp =3D ldap_init(servers[i].server, servers[i].port);
 	if (lp =3D=3D NULL)
 	    continue;
-=09
+
 	if (ldap_set_option(lp, LDAP_OPT_PROTOCOL_VERSION, &version)) {
 	    ldap_unbind(lp);
 	    continue;
 	}
-=09
+
 	if (ldap_set_option(lp, LDAP_OPT_REFERRALS, LDAP_OPT_OFF)) {
 	    ldap_unbind(lp);
 	    continue;
 	}
-=09
+
 #ifdef HAVE_TSASL
 	lret =3D ldap_tsasl_bind_s(lp, NULL, NULL, NULL, servers[i].server);
-				=20
+
 #else
-	lret =3D ldap_sasl_interactive_bind_s(lp, NULL, NULL, NULL, NULL,=20
+	lret =3D ldap_sasl_interactive_bind_s(lp, NULL, NULL, NULL, NULL,
 					    LDAP_SASL_QUIET,
 					    sasl_interact, NULL);
 #endif
 	if (lret !=3D LDAP_SUCCESS) {
-	    krb5_set_error_string(context->context,=20
-				  "Couldn't contact any AD servers: %s",
-				  ldap_err2string(lret));
+	    krb5_set_error_message(context->context, 0,
+				   "Couldn't contact any AD servers: %s",
+				   ldap_err2string(lret));
 	    ldap_unbind(lp);
 	    continue;
 	}
@@ -358,10 +358,10 @@
 	int attrlen =3D 0;
 	char **vals;
 	int ret;
-=09
+
 	laddattr(&attr, &attrlen, "defaultNamingContext");
=20
-	ret =3D ldap_search_s(CTX2LP(context), "", LDAP_SCOPE_BASE,=20
+	ret =3D ldap_search_s(CTX2LP(context), "", LDAP_SCOPE_BASE,
 			    "objectclass=3D*", attr, 0, &m);
 	free(attr);
 	if (check_ldap(context, ret))
@@ -370,16 +370,16 @@
 	if (ldap_count_entries(CTX2LP(context), m) > 0) {
 	    m0 =3D ldap_first_entry(CTX2LP(context), m);
 	    if (m0 =3D=3D NULL) {
-		krb5_set_error_string(context->context,
-				      "Error in AD ldap responce");
+		krb5_set_error_message(context->context, KADM5_RPC_ERROR,
+				       "Error in AD ldap responce");
 		ldap_msgfree(m);
 		goto fail;
 	    }
-	    vals =3D ldap_get_values(CTX2LP(context),=20
+	    vals =3D ldap_get_values(CTX2LP(context),
 				   m0, "defaultNamingContext");
 	    if (vals =3D=3D NULL) {
-		krb5_set_error_string(context->context,
-				      "No naming context found");
+		krb5_set_error_message(context->context, KADM5_RPC_ERROR,
+				       "No naming context found");
 		goto fail;
 	    }
 	    context->base_dn =3D strdup(vals[0]);
@@ -444,7 +444,7 @@
 	*name =3D NULL;
=20
     if (fqdn)
-	asprintf(&filter,=20
+	asprintf(&filter,
 		 "(&(objectClass=3Dcomputer)(|(dNSHostName=3D%s)(servicePrincipalName=3D=
%s)))",
 		 fqdn, pn);
     else if(pn)
@@ -453,7 +453,7 @@
 	return KADM5_RPC_ERROR;
=20
     ret =3D ldap_search_s(CTX2LP(context), CTX2BASE(context),
-			LDAP_SCOPE_SUBTREE,=20
+			LDAP_SCOPE_SUBTREE,
 			filter, attr, 0, &m);
     free(filter);
     if (check_ldap(context, ret))
@@ -496,7 +496,7 @@
     ret =3D _kadm5_c_get_cred_cache(context->context,
 				  context->client_name,
 				  service,
-				  password, krb5_prompter_posix,=20
+				  password, krb5_prompter_posix,
 				  NULL, NULL, &cc);
     free(service);
     if(ret)
@@ -522,14 +522,14 @@
     krb5_data_zero (&result_code_string);
     krb5_data_zero (&result_string);
=20
-    ret =3D krb5_set_password_using_ccache (context->context,=20
+    ret =3D krb5_set_password_using_ccache (context->context,
 					  context->ccache,
 					  password,
 					  principal,
 					  &result_code,
 					  &result_code_string,
 					  &result_string);
-   =20
+
     krb5_data_free (&result_code_string);
     krb5_data_free (&result_string);
=20
@@ -548,7 +548,7 @@
     s =3D krb5_principal_get_comp_string(context, p, 0);
     if (p =3D=3D NULL)
 	return NULL;
-   =20
+
     for (i =3D 0; i < sizeof(hosttypes)/sizeof(hosttypes[0]); i++) {
 	if (strcasecmp(s, hosttypes[i]) =3D=3D 0)
 	    return krb5_principal_get_comp_string(context, p, 1);
@@ -574,42 +574,42 @@
=20
 #ifdef OPENLDAP
     LDAPMod *attrs[8], rattrs[7], *a;
-    char *useraccvals[2] =3D { NULL, NULL },=20
+    char *useraccvals[2] =3D { NULL, NULL },
 	*samvals[2], *dnsvals[2], *spnvals[5], *upnvals[2], *tv[2];
-    char *ocvals_spn[] =3D { "top", "person", "organizationalPerson",=20
-			   "user", "computer", NULL};=20
+    char *ocvals_spn[] =3D { "top", "person", "organizationalPerson",
+			   "user", "computer", NULL};
     char *p, *realmless_p, *p_msrealm =3D NULL, *dn =3D NULL;
     const char *fqdn;
     char *s, *samname =3D NULL, *short_spn =3D NULL;
     int ret, i;
     int32_t uf_flags =3D 0;
-   =20
+
     if ((mask & KADM5_PRINCIPAL) =3D=3D 0)
 	return KADM5_BAD_MASK;
=20
     for (i =3D 0; i < sizeof(rattrs)/sizeof(rattrs[0]); i++)
 	attrs[i] =3D &rattrs[i];
     attrs[i] =3D NULL;
-   =20
+
     ret =3D ad_get_cred(context, NULL);
     if (ret)
 	return ret;
-   =20
+
     ret =3D _kadm5_ad_connect(server_handle);
     if (ret)
 	return ret;
-   =20
+
     fqdn =3D get_fqdn(context->context, entry->principal);
-   =20
+
     ret =3D krb5_unparse_name(context->context, entry->principal, &p);
     if (ret)
 	return ret;
-   =20
+
     if (ad_find_entry(context, fqdn, p, NULL) =3D=3D 0) {
 	free(p);
 	return KADM5_DUP;
     }
-   =20
+
     if (mask & KADM5_ATTRIBUTES) {
 	if (entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)
 	    uf_flags |=3D UF_ACCOUNTDISABLE|UF_LOCKOUT;
@@ -618,7 +618,7 @@
 	if (entry->attributes & KRB5_KDB_REQUIRES_HW_AUTH)
 	    uf_flags |=3D UF_SMARTCARD_REQUIRED;
     }
-   =20
+
     realmless_p =3D strdup(p);
     if (realmless_p =3D=3D NULL) {
 	ret =3D ENOMEM;
@@ -627,7 +627,7 @@
     s =3D strrchr(realmless_p, '@');
     if (s)
 	*s =3D '\0';
-   =20
+
     if (fqdn) {
 	/* create computer account */
 	asprintf(&samname, "%s$", fqdn);
@@ -640,7 +640,7 @@
 	    s[0] =3D '$';
 	    s[1] =3D '\0';
 	}
-=09
+
 	short_spn =3D strdup(p);
 	if (short_spn =3D=3D NULL) {
 	    errno =3D ENOMEM;
@@ -733,12 +733,12 @@
=20
     } else {
 	/* create user account */
-=09
+
 	a =3D &rattrs[0];
 	a->mod_op =3D LDAP_MOD_ADD;
 	a->mod_type =3D "userAccountControl";
 	a->mod_values =3D useraccvals;
-	asprintf(&useraccvals[0], "%d",=20
+	asprintf(&useraccvals[0], "%d",
 		 uf_flags |
 		 UF_PASSWD_NOT_EXPIRE);
 	useraccvals[1] =3D NULL;
@@ -788,7 +788,7 @@
=20
     return 0;
 #else
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 #endif
 }
@@ -830,7 +830,7 @@
 	return KADM5_RPC_ERROR;
     return 0;
 #else
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 #endif
 }
@@ -864,19 +864,14 @@
 kadm5_ad_flush(void *server_handle)
 {
     kadm5_ad_context *context =3D server_handle;
-#ifdef OPENLDAP
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
-#else
-    krb5_set_error_string(context->context, "Function not implemented");
-    return KADM5_RPC_ERROR;
-#endif
 }
=20
 static kadm5_ret_t
 kadm5_ad_get_principal(void *server_handle,
-		       krb5_principal principal,=20
-		       kadm5_principal_ent_t entry,=20
+		       krb5_principal principal,
+		       kadm5_principal_ent_t entry,
 		       uint32_t mask)
 {
     kadm5_ad_context *context =3D server_handle;
@@ -921,14 +916,14 @@
     if (q && (p !=3D q && *(q - 1) !=3D '\\'))
 	*q =3D '/';
=20
-    asprintf(&filter,=20
+    asprintf(&filter,
 	     "(|(userPrincipalName=3D%s)(servicePrincipalName=3D%s)(servicePrinci=
palName=3D%s))",
 	     u, p, u);
     free(p);
     free(u);
=20
     ret =3D ldap_search_s(CTX2LP(context), CTX2BASE(context),
-			LDAP_SCOPE_SUBTREE,=20
+			LDAP_SCOPE_SUBTREE,
 			filter, attr, 0, &m);
     free(attr);
     if (check_ldap(context, ret))
@@ -995,7 +990,7 @@
 	    }
 	}
 	if (mask & KADM5_KVNO) {
-	    vals =3D ldap_get_values(CTX2LP(context), m0,=20
+	    vals =3D ldap_get_values(CTX2LP(context), m0,
 				   "msDS-KeyVersionNumber");
 	    if (vals)
 		entry->kvno =3D atoi(vals[0]);
@@ -1014,7 +1009,7 @@
  fail:
     return KADM5_RPC_ERROR;
 #else
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 #endif
 }
@@ -1042,10 +1037,10 @@
     if (ret)
 	return ret;
=20
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 #else
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 #endif
 }
@@ -1054,7 +1049,7 @@
 kadm5_ad_get_privs(void *server_handle, uint32_t*privs)
 {
     kadm5_ad_context *context =3D server_handle;
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 }
=20
@@ -1065,7 +1060,7 @@
 {
     kadm5_ad_context *context =3D server_handle;
=20
-    /*=20
+    /*
      * KADM5_ATTRIBUTES
      * KRB5_KDB_DISALLOW_ALL_TIX (| KADM5_KVNO)
      */
@@ -1109,14 +1104,14 @@
     if (q && (p !=3D q && *(q - 1) !=3D '\\'))
 	*q =3D '\0';
=20
-    asprintf(&filter,=20
+    asprintf(&filter,
 	     "(|(userPrincipalName=3D%s)(servicePrincipalName=3D%s))",
 	     s, s);
     free(p);
     free(s);
=20
     ret =3D ldap_search_s(CTX2LP(context), CTX2BASE(context),
-			LDAP_SCOPE_SUBTREE,=20
+			LDAP_SCOPE_SUBTREE,
 			filter, attr, 0, &m);
     free(attr);
     free(filter);
@@ -1199,7 +1194,7 @@
 	a->mod_values =3D tv;
 	a++;
     }
-   =20
+
     vals =3D ldap_get_values(CTX2LP(context), m0, "distinguishedName");
     if (vals =3D=3D NULL) {
 	ret =3D KADM5_RPC_ERROR;
@@ -1224,7 +1219,7 @@
 	free(tv[0]);
     return ret;
 #else
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 #endif
 }
@@ -1267,7 +1262,7 @@
     krb5_data_zero (&result_code_string);
     krb5_data_zero (&result_string);
=20
-    ret =3D krb5_set_password_using_ccache (context->context,=20
+    ret =3D krb5_set_password_using_ccache (context->context,
 					  context->ccache,
 					  password,
 					  principal,
@@ -1308,7 +1303,7 @@
     *keys =3D NULL;
     *n_keys =3D 0;
=20
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 #endif
 }
@@ -1319,18 +1314,18 @@
 			  krb5_principal to)
 {
     kadm5_ad_context *context =3D server_handle;
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 }
=20
 static kadm5_ret_t
-kadm5_ad_chpass_principal_with_key(void *server_handle,=20
+kadm5_ad_chpass_principal_with_key(void *server_handle,
 				   krb5_principal princ,
 				   int n_key_data,
 				   krb5_key_data *key_data)
 {
     kadm5_ad_context *context =3D server_handle;
-    krb5_set_error_string(context->context, "Function not implemented");
+    krb5_set_error_message(context->context, KADM5_RPC_ERROR, "Function no=
t implemented");
     return KADM5_RPC_ERROR;
 }
=20
@@ -1352,7 +1347,7 @@
     SET(c, rename_principal);
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_ad_init_with_password_ctx(krb5_context context,
 				const char *client_name,
 				const char *password,
@@ -1415,7 +1410,7 @@
     return 0;
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_ad_init_with_password(const char *client_name,
 			    const char *password,
 			    const char *service_name,
@@ -1431,7 +1426,7 @@
     ret =3D krb5_init_context(&context);
     if (ret)
 	return ret;
-    ret =3D kadm5_ad_init_with_password_ctx(context,=20
+    ret =3D kadm5_ad_init_with_password_ctx(context,
 					  client_name,
 					  password,
 					  service_name,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/admin.h
--- a/head/crypto/heimdal/lib/kadm5/admin.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/admin.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,36 +1,36 @@
 /*
- * Copyright (c) 1997-2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
-/* $Id: admin.h 20237 2007-02-16 23:54:34Z lha $ */
+/* $Id$ */
=20
 #ifndef __KADM5_ADMIN_H__
 #define __KADM5_ADMIN_H__
@@ -104,7 +104,7 @@
 #define KADM5_HIST_PRINCIPAL	"kadmin/history"
 #define KADM5_CHANGEPW_SERVICE	"kadmin/changepw"
=20
-typedef struct _krb5_key_data {
+typedef struct {
     int16_t key_data_ver;	/* Version */
     int16_t key_data_kvno;	/* Key Version */
     int16_t key_data_type[2];	/* Array of types */
@@ -114,9 +114,9 @@
=20
 typedef struct _krb5_tl_data {
     struct _krb5_tl_data* tl_data_next;
-    int16_t tl_data_type;        =20
-    int16_t tl_data_length;      =20
-    void*   tl_data_contents;    =20
+    int16_t tl_data_type;
+    int16_t tl_data_length;
+    void*   tl_data_contents;
 } krb5_tl_data;
=20
 #define KRB5_TL_LAST_PWD_CHANGE		0x0001
@@ -223,7 +223,7 @@
=20
 #if 0
 /* unimplemented functions */
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_decrypt_key(void *server_handle,
 		  kadm5_principal_ent_t entry, int32_t
 		  ktype, int32_t stype, int32_t
@@ -232,7 +232,7 @@
=20
 kadm5_ret_t
 kadm5_create_policy(void *server_handle,
-		    kadm5_policy_ent_t policy, uint32_t mask);=20
+		    kadm5_policy_ent_t policy, uint32_t mask);
=20
 kadm5_ret_t
 kadm5_delete_policy(void *server_handle, char *policy);
@@ -240,17 +240,17 @@
=20
 kadm5_ret_t
 kadm5_modify_policy(void *server_handle,
-		    kadm5_policy_ent_t policy,=20
+		    kadm5_policy_ent_t policy,
 		    uint32_t mask);
=20
 kadm5_ret_t
-kadm5_get_policy(void *server_handle, char *policy, kadm5_policy_ent_t ent=
);=20
+kadm5_get_policy(void *server_handle, char *policy, kadm5_policy_ent_t ent=
);
=20
 kadm5_ret_t
 kadm5_get_policies(void *server_handle, char *exp,
 		   char ***pols, int *count);
=20
-void=20
+void
 kadm5_free_policy_ent(kadm5_policy_ent_t policy);
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/bump_pw_=
expire.c
--- a/head/crypto/heimdal/lib/kadm5/bump_pw_expire.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/kadm5/bump_pw_expire.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: bump_pw_expire.c 8797 2000-07-24 03:47:54Z assar $");
+RCSID("$Id$");
=20
 /*
  * extend password_expiration if it's defined
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/check-cr=
acklib.pl
--- a/head/crypto/heimdal/lib/kadm5/check-cracklib.pl	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/check-cracklib.pl	Tue Apr 17 11:51:51 2=
012 +0300
@@ -29,7 +29,7 @@
 #     	policies =3D builtin:external-check
 #     	external_program =3D <your-path>/check-cracklib.pl
 #
-# $Id: check-cracklib.pl 20578 2007-05-07 22:21:51Z lha $
+# $Id$
=20
 use strict;
 use Crypt::Cracklib;
@@ -40,6 +40,9 @@
 my $historydb =3D '/var/heimdal/historydb';
 # NEED TO CHANGE THESE TO MATCH YOUR SYSTEM
=20
+# seconds password reuse allowed (to catch retries from clients)
+my $reusetime =3D 60;=20
+
 my %params;
=20
 sub check_basic
@@ -60,6 +63,7 @@
     my $result  =3D 'Do not reuse passwords';
     my %DB;
     my $md5context =3D new Digest::MD5;
+    my $timenow =3D scalar(time());
=20
     $md5context->reset();
     $md5context->add($principal, ":", $passwd);
@@ -67,8 +71,10 @@
     my $key=3D$md5context->hexdigest();
=20
     dbmopen(%DB,$historydb,0600) or die "Internal: Could not open $history=
db";
-    $result =3D "ok" if (!$DB{$key});
-    $DB{$key}=3Dscalar(time());
+    if (!$DB{$key} || ($timenow - $DB{$key} < $reusetime)) {=20
+	$result =3D "ok";
+	$DB{$key}=3D$timenow;
+    }
     dbmclose(%DB) or die "Internal: Could not close $historydb";
     return $result;
 }
@@ -80,7 +86,7 @@
     exit 0
 }
=20
-while (<>) {
+while (<STDIN>) {
     last if /^end$/;
     if (!/^([^:]+): (.+)$/) {
 	die "key value pair not correct: $_";
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/chpass_c=
.c
--- a/head/crypto/heimdal/lib/kadm5/chpass_c.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/chpass_c.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 1997-2000, 2005-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2000, 2005-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: chpass_c.c 16661 2006-01-25 12:50:10Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
-kadm5_c_chpass_principal(void *server_handle,=20
+kadm5_c_chpass_principal(void *server_handle,
 			 krb5_principal princ,
 			 const char *password)
 {
@@ -53,7 +53,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_chpass);
@@ -61,24 +61,26 @@
     krb5_store_string(sp, password);
     ret =3D _kadm5_client_send(context, sp);
     krb5_storage_free(sp);
+    if (ret)
+	return ret;
     ret =3D _kadm5_client_recv(context, &reply);
     if(ret)
 	return ret;
     sp =3D krb5_storage_from_data (&reply);
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
     krb5_ret_int32(sp, &tmp);
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     krb5_storage_free(sp);
     krb5_data_free (&reply);
     return tmp;
 }
=20
 kadm5_ret_t
-kadm5_c_chpass_principal_with_key(void *server_handle,=20
+kadm5_c_chpass_principal_with_key(void *server_handle,
 				  krb5_principal princ,
 				  int n_key_data,
 				  krb5_key_data *key_data)
@@ -97,7 +99,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_chpass_with_key);
@@ -107,17 +109,19 @@
 	kadm5_store_key_data (sp, &key_data[i]);
     ret =3D _kadm5_client_send(context, sp);
     krb5_storage_free(sp);
+    if (ret)
+	return ret;
     ret =3D _kadm5_client_recv(context, &reply);
     if(ret)
 	return ret;
     sp =3D krb5_storage_from_data (&reply);
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
     krb5_ret_int32(sp, &tmp);
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     krb5_storage_free(sp);
     krb5_data_free (&reply);
     return tmp;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/chpass_s=
.c
--- a/head/crypto/heimdal/lib/kadm5/chpass_s.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/chpass_s.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: chpass_s.c 20608 2007-05-08 07:11:48Z lha $");
+RCSID("$Id$");
=20
 static kadm5_ret_t
-change(void *server_handle,=20
+change(void *server_handle,
        krb5_principal princ,
        const char *password,
        int cond)
@@ -46,39 +46,55 @@
     kadm5_ret_t ret;
     Key *keys;
     size_t num_keys;
-    int cmp =3D 1;
+    int existsp =3D 0;
=20
     memset(&ent, 0, sizeof(ent));
     ret =3D context->db->hdb_open(context->context, context->db, O_RDWR, 0=
);
     if(ret)
 	return ret;
-    ret =3D context->db->hdb_fetch(context->context, context->db, princ,
-				 HDB_F_DECRYPT|HDB_F_GET_ANY, &ent);
-    if(ret =3D=3D HDB_ERR_NOENTRY)
+
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db, pri=
nc,
+				      HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
+    if(ret)
 	goto out;
=20
-    num_keys =3D ent.entry.keys.len;
-    keys     =3D ent.entry.keys.val;
+    if (context->db->hdb_capability_flags & HDB_CAP_F_HANDLE_PASSWORDS) {
+	ret =3D context->db->hdb_password(context->context, context->db,
+					&ent, password, cond);
+	if (ret)
+	    goto out2;
+    } else {
=20
-    ent.entry.keys.len =3D 0;
-    ent.entry.keys.val =3D NULL;
+	num_keys =3D ent.entry.keys.len;
+	keys     =3D ent.entry.keys.val;
=20
-    ret =3D _kadm5_set_keys(context, &ent.entry, password);
-    if(ret) {
+	ent.entry.keys.len =3D 0;
+	ent.entry.keys.val =3D NULL;
+
+	ret =3D _kadm5_set_keys(context, &ent.entry, password);
+	if(ret) {
+	    _kadm5_free_keys (context->context, num_keys, keys);
+	    goto out2;
+	}
+
+	if (cond)
+	    existsp =3D _kadm5_exists_keys (ent.entry.keys.val,
+					  ent.entry.keys.len,
+					  keys, num_keys);
 	_kadm5_free_keys (context->context, num_keys, keys);
-	goto out2;
+
+	if (existsp) {
+	    ret =3D KADM5_PASS_REUSE;
+	    krb5_set_error_message(context->context, ret,
+				   "Password reuse forbidden");
+	    goto out2;
+	}
+
+	ret =3D hdb_seal_keys(context->context, context->db, &ent.entry);
+	if (ret)
+	    goto out2;
     }
     ent.entry.kvno++;
-    if (cond)
-	cmp =3D _kadm5_cmp_keys (ent.entry.keys.val, ent.entry.keys.len,
-			       keys, num_keys);
-    _kadm5_free_keys (context->context, num_keys, keys);
-
-    if (cmp =3D=3D 0) {
-	krb5_set_error_string(context->context, "Password reuse forbidden");
-	ret =3D KADM5_PASS_REUSE;
-	goto out2;
-    }
=20
     ret =3D _kadm5_set_modifier(context, &ent.entry);
     if(ret)
@@ -88,11 +104,7 @@
     if (ret)
 	goto out2;
=20
-    ret =3D hdb_seal_keys(context->context, context->db, &ent.entry);
-    if (ret)
-	goto out2;
-
-    ret =3D context->db->hdb_store(context->context, context->db,=20
+    ret =3D context->db->hdb_store(context->context, context->db,
 				 HDB_F_REPLACE, &ent);
     if (ret)
 	goto out2;
@@ -117,7 +129,7 @@
  */
=20
 kadm5_ret_t
-kadm5_s_chpass_principal_cond(void *server_handle,=20
+kadm5_s_chpass_principal_cond(void *server_handle,
 			      krb5_principal princ,
 			      const char *password)
 {
@@ -129,7 +141,7 @@
  */
=20
 kadm5_ret_t
-kadm5_s_chpass_principal(void *server_handle,=20
+kadm5_s_chpass_principal(void *server_handle,
 			 krb5_principal princ,
 			 const char *password)
 {
@@ -141,7 +153,7 @@
  */
=20
 kadm5_ret_t
-kadm5_s_chpass_principal_with_key(void *server_handle,=20
+kadm5_s_chpass_principal_with_key(void *server_handle,
 				  krb5_principal princ,
 				  int n_key_data,
 				  krb5_key_data *key_data)
@@ -154,8 +166,8 @@
     ret =3D context->db->hdb_open(context->context, context->db, O_RDWR, 0=
);
     if(ret)
 	return ret;
-    ret =3D context->db->hdb_fetch(context->context, context->db, princ,=20
-				 HDB_F_GET_ANY, &ent);
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db, pri=
nc, 0,
+				      HDB_F_GET_ANY|HDB_F_ADMIN_DATA, &ent);
     if(ret =3D=3D HDB_ERR_NOENTRY)
 	goto out;
     ret =3D _kadm5_set_keys2(context, &ent.entry, n_key_data, key_data);
@@ -173,7 +185,7 @@
     if (ret)
 	goto out2;
=20
-    ret =3D context->db->hdb_store(context->context, context->db,=20
+    ret =3D context->db->hdb_store(context->context, context->db,
 				 HDB_F_REPLACE, &ent);
     if (ret)
 	goto out2;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/client_g=
lue.c
--- a/head/crypto/heimdal/lib/kadm5/client_glue.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/kadm5/client_glue.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: client_glue.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_init_with_password(const char *client_name,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/common_g=
lue.c
--- a/head/crypto/heimdal/lib/kadm5/common_glue.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/kadm5/common_glue.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: common_glue.c 17445 2006-05-05 10:37:46Z lha $");
+RCSID("$Id$");
=20
 #define __CALL(F, P) (*((kadm5_common_context*)server_handle)->funcs.F)P;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/context_=
s.c
--- a/head/crypto/heimdal/lib/kadm5/context_s.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/context_s.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: context_s.c 22211 2007-12-07 19:27:27Z lha $");
+RCSID("$Id$");
=20
 static void
 set_funcs(kadm5_server_context *c)
@@ -53,6 +53,8 @@
     SET(c, rename_principal);
 }
=20
+#ifndef NO_UNIX_SOCKETS
+
 static void
 set_socket_name(krb5_context context, struct sockaddr_un *un)
 {
@@ -61,7 +63,17 @@
     memset(un, 0, sizeof(*un));
     un->sun_family =3D AF_UNIX;
     strlcpy (un->sun_path, fn, sizeof(un->sun_path));
+
 }
+#else
+
+static void
+set_socket_info(krb5_context context, struct addrinfo **info)
+{
+    kadm5_log_signal_socket_info(context, 0, info);
+}
+
+#endif
=20
 static kadm5_ret_t
 find_db_spec(kadm5_server_context *ctx)
@@ -75,27 +87,27 @@
 	ret =3D hdb_get_dbinfo(context, &info);
 	if (ret)
 	    return ret;
-=09
+
 	d =3D NULL;
 	while ((d =3D hdb_dbinfo_get_next(info, d)) !=3D NULL) {
 	    const char *p =3D hdb_dbinfo_get_realm(context, d);
-	   =20
+
 	    /* match default (realm-less) */
 	    if(p !=3D NULL && strcmp(ctx->config.realm, p) !=3D 0)
 		continue;
-	   =20
+
 	    p =3D hdb_dbinfo_get_dbname(context, d);
 	    if (p)
 		ctx->config.dbname =3D strdup(p);
-	   =20
+
 	    p =3D hdb_dbinfo_get_acl_file(context, d);
 	    if (p)
 		ctx->config.acl_file =3D strdup(p);
-	   =20
+
 	    p =3D hdb_dbinfo_get_mkey_file(context, d);
 	    if (p)
 		ctx->config.stash_file =3D strdup(p);
-	   =20
+
 	    p =3D hdb_dbinfo_get_log_file(context, d);
 	    if (p)
 		ctx->log_context.log_file =3D strdup(p);
@@ -115,13 +127,17 @@
     if (ctx->log_context.log_file =3D=3D NULL)
 	asprintf(&ctx->log_context.log_file, "%s/log", hdb_db_dir(context));
=20
+#ifndef NO_UNIX_SOCKETS
     set_socket_name(context, &ctx->log_context.socket_name);
+#else
+    set_socket_info(context, &ctx->log_context.socket_info);
+#endif
=20
     return 0;
 }
=20
 kadm5_ret_t
-_kadm5_s_init_context(kadm5_server_context **ctx,=20
+_kadm5_s_init_context(kadm5_server_context **ctx,
 		      kadm5_config_params *params,
 		      krb5_context context)
 {
@@ -143,11 +159,11 @@
 	(*ctx)->config.acl_file =3D strdup(params->acl_file);
     if(is_set(STASH_FILE))
 	(*ctx)->config.stash_file =3D strdup(params->stash_file);
-   =20
+
     find_db_spec(*ctx);
-   =20
+
     /* PROFILE can't be specified for now */
-    /* KADMIND_PORT is supposed to be used on the server also,=20
+    /* KADMIND_PORT is supposed to be used on the server also,
        but this doesn't make sense */
     /* ADMIN_SERVER is client only */
     /* ADNAME is not used at all (as far as I can tell) */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/create_c=
.c
--- a/head/crypto/heimdal/lib/kadm5/create_c.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/create_c.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,43 +1,43 @@
 /*
- * Copyright (c) 1997-2000, 2005-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2000, 2005-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: create_c.c 17445 2006-05-05 10:37:46Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_c_create_principal(void *server_handle,
-			 kadm5_principal_ent_t princ,=20
+			 kadm5_principal_ent_t princ,
 			 uint32_t mask,
 			 const char *password)
 {
@@ -54,7 +54,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_create);
@@ -63,17 +63,19 @@
     krb5_store_string(sp, password);
     ret =3D _kadm5_client_send(context, sp);
     krb5_storage_free(sp);
+    if (ret)
+	return ret;
     ret =3D _kadm5_client_recv(context, &reply);
     if(ret)
 	return ret;
     sp =3D krb5_storage_from_data (&reply);
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
     krb5_ret_int32(sp, &tmp);
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     krb5_storage_free(sp);
     krb5_data_free (&reply);
     return tmp;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/create_s=
.c
--- a/head/crypto/heimdal/lib/kadm5/create_s.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/create_s.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,53 +1,53 @@
 /*
- * Copyright (c) 1997-2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: create_s.c 20607 2007-05-08 07:11:11Z lha $");
+RCSID("$Id$");
=20
 static kadm5_ret_t
-get_default(kadm5_server_context *context, krb5_principal princ,=20
+get_default(kadm5_server_context *context, krb5_principal princ,
 	    kadm5_principal_ent_t def)
 {
     kadm5_ret_t ret;
     krb5_principal def_principal;
-    krb5_realm *realm =3D krb5_princ_realm(context->context, princ);
+    krb5_const_realm realm =3D krb5_principal_get_realm(context->context, =
princ);
=20
-    ret =3D krb5_make_principal(context->context, &def_principal,=20
-			      *realm, "default", NULL);
+    ret =3D krb5_make_principal(context->context, &def_principal,
+			      realm, "default", NULL);
     if (ret)
 	return ret;
-    ret =3D kadm5_s_get_principal(context, def_principal, def,=20
+    ret =3D kadm5_s_get_principal(context, def_principal, def,
 				KADM5_PRINCIPAL_NORMAL_MASK);
     krb5_free_principal (context->context, def_principal);
     return ret;
@@ -64,7 +64,7 @@
     kadm5_ret_t ret;
     kadm5_principal_ent_rec defrec, *defent;
     uint32_t def_mask;
-   =20
+
     if((mask & required_mask) !=3D required_mask)
 	return KADM5_BAD_MASK;
     if((mask & forbidden_mask))
@@ -73,11 +73,11 @@
 	/* XXX no real policies for now */
 	return KADM5_UNK_POLICY;
     memset(ent, 0, sizeof(*ent));
-    ret  =3D krb5_copy_principal(context->context, princ->principal,=20
+    ret  =3D krb5_copy_principal(context->context, princ->principal,
 			       &ent->entry.principal);
     if(ret)
 	return ret;
-   =20
+
     defent =3D &defrec;
     ret =3D get_default(context, princ->principal, defent);
     if(ret) {
@@ -93,12 +93,13 @@
 			     defent, def_mask);
     if(defent)
 	kadm5_free_principal_ent(context, defent);
-   =20
+    if (ret)
+	return ret;
+
     ent->entry.created_by.time =3D time(NULL);
-    ret =3D krb5_copy_principal(context->context, context->caller,=20
-			      &ent->entry.created_by.principal);
=20
-    return ret;
+    return krb5_copy_principal(context->context, context->caller,
+			       &ent->entry.created_by.principal);
 }
=20
 kadm5_ret_t
@@ -112,10 +113,10 @@
=20
     ret =3D create_principal(context, princ, mask, &ent,
 			   KADM5_PRINCIPAL | KADM5_KEY_DATA,
-			   KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME=20
-			   | KADM5_MOD_NAME | KADM5_MKVNO=20
-			   | KADM5_AUX_ATTRIBUTES=20
-			   | KADM5_POLICY_CLR | KADM5_LAST_SUCCESS=20
+			   KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME
+			   | KADM5_MOD_NAME | KADM5_MKVNO
+			   | KADM5_AUX_ATTRIBUTES
+			   | KADM5_POLICY_CLR | KADM5_LAST_SUCCESS
 			   | KADM5_LAST_FAILED | KADM5_FAIL_AUTH_COUNT);
     if(ret)
 	goto out;
@@ -126,7 +127,7 @@
     ret =3D hdb_seal_keys(context->context, context->db, &ent.entry);
     if (ret)
 	goto out;
-   =20
+
     ret =3D context->db->hdb_open(context->context, context->db, O_RDWR, 0=
);
     if(ret)
 	goto out;
@@ -140,11 +141,11 @@
     hdb_free_entry(context->context, &ent);
     return _kadm5_error_code(ret);
 }
-				 =20
+
=20
 kadm5_ret_t
 kadm5_s_create_principal(void *server_handle,
-			 kadm5_principal_ent_t princ,=20
+			 kadm5_principal_ent_t princ,
 			 uint32_t mask,
 			 const char *password)
 {
@@ -154,10 +155,10 @@
=20
     ret =3D create_principal(context, princ, mask, &ent,
 			   KADM5_PRINCIPAL,
-			   KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME=20
-			   | KADM5_MOD_NAME | KADM5_MKVNO=20
+			   KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME
+			   | KADM5_MOD_NAME | KADM5_MKVNO
 			   | KADM5_AUX_ATTRIBUTES | KADM5_KEY_DATA
-			   | KADM5_POLICY_CLR | KADM5_LAST_SUCCESS=20
+			   | KADM5_POLICY_CLR | KADM5_LAST_SUCCESS
 			   | KADM5_LAST_FAILED | KADM5_FAIL_AUTH_COUNT);
     if(ret)
 	goto out;
@@ -175,7 +176,7 @@
     ret =3D hdb_seal_keys(context->context, context->db, &ent.entry);
     if (ret)
 	goto out;
-   =20
+
     ret =3D context->db->hdb_open(context->context, context->db, O_RDWR, 0=
);
     if(ret)
 	goto out;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/default_=
keys.c
--- a/head/crypto/heimdal/lib/kadm5/default_keys.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/kadm5/default_keys.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: default_keys.c 22494 2008-01-21 11:56:44Z lha $");
+RCSID("$Id$");
=20
 static void
 print_keys(krb5_context context, Key *keys, size_t nkeys)
@@ -72,7 +72,7 @@
 	    if (keys[i].salt->salt.length)
 		printf("%.*s", (int)keys[i].salt->salt.length,
 		       (char *)keys[i].salt->salt.data);
-	}=09
+	}
 	printf("\n");
     }
     printf("end keys:\n");
@@ -102,7 +102,7 @@
     krb5_principal principal;
=20
     ret =3D krb5_init_context(&context);
-    if (ret)=20
+    if (ret)
 	errx(1, "krb5_init_context");
=20
     ret =3D krb5_parse_name(context, "lha at SU.SE", &principal);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/delete_c=
.c
--- a/head/crypto/heimdal/lib/kadm5/delete_c.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/delete_c.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: delete_c.c 16661 2006-01-25 12:50:10Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_c_delete_principal(void *server_handle, krb5_principal princ)
@@ -51,7 +51,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_delete);
@@ -65,12 +65,12 @@
 	return ret;
     sp =3D krb5_storage_from_data (&reply);
     if(sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
     krb5_ret_int32(sp, &tmp);
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     krb5_storage_free(sp);
     krb5_data_free (&reply);
     return tmp;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/delete_s=
.c
--- a/head/crypto/heimdal/lib/kadm5/delete_s.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/delete_s.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001, 2003, 2005 - 2006 Kungliga Tekniska H=F6gsko=
lan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2003, 2005 - 2006 Kungliga Tekniska H=C3=B6g=
skolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: delete_s.c 20612 2007-05-08 07:13:45Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_s_delete_principal(void *server_handle, krb5_principal princ)
@@ -48,15 +48,15 @@
 	krb5_warn(context->context, ret, "opening database");
 	return ret;
     }
-    ret =3D context->db->hdb_fetch(context->context, context->db, princ,
-				 HDB_F_DECRYPT|HDB_F_GET_ANY, &ent);
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db, pri=
nc,
+				      HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
     if(ret =3D=3D HDB_ERR_NOENTRY)
 	goto out;
     if(ent.entry.flags.immutable) {
 	ret =3D KADM5_PROTECT_PRINCIPAL;
 	goto out2;
     }
-   =20
+
     ret =3D hdb_seal_keys(context->context, context->db, &ent.entry);
     if (ret)
 	goto out2;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/destroy_=
c.c
--- a/head/crypto/heimdal/lib/kadm5/destroy_c.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/destroy_c.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: destroy_c.c 13198 2003-12-07 19:01:39Z lha $");
+RCSID("$Id$");
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_c_destroy(void *server_handle)
 {
     kadm5_client_context *context =3D server_handle;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/destroy_=
s.c
--- a/head/crypto/heimdal/lib/kadm5/destroy_s.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/destroy_s.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: destroy_s.c 12880 2003-09-19 00:25:35Z lha $");
+RCSID("$Id$");
=20
 /*
  * dealloc a `kadm5_config_params'
@@ -56,14 +56,20 @@
 destroy_kadm5_log_context (kadm5_log_context *c)
 {
     free (c->log_file);
-    close (c->socket_fd);
+    rk_closesocket (c->socket_fd);
+#ifdef NO_UNIX_SOCKETS
+    if (c->socket_info) {
+	freeaddrinfo(c->socket_info);
+	c->socket_info =3D NULL;
+    }
+#endif
 }
=20
 /*
  * destroy a kadm5 handle
  */
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_destroy(void *server_handle)
 {
     kadm5_ret_t ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/ent_setu=
p.c
--- a/head/crypto/heimdal/lib/kadm5/ent_setup.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/ent_setup.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,41 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: ent_setup.c 18823 2006-10-22 10:15:53Z lha $");
+RCSID("$Id$");
=20
 #define set_value(X, V) do { if((X) =3D=3D NULL) (X) =3D malloc(sizeof(*(X=
))); *(X) =3D V; } while(0)
 #define set_null(X)     do { if((X) !=3D NULL) free((X)); (X) =3D NULL; } =
while (0)
@@ -66,7 +68,7 @@
 static kadm5_ret_t
 perform_tl_data(krb5_context context,
 		HDB *db,
-		hdb_entry_ex *ent,=20
+		hdb_entry_ex *ent,
 		const krb5_tl_data *tl_data)
 {
     kadm5_ret_t ret =3D 0;
@@ -101,7 +103,7 @@
 				   NULL);
 	if (ret)
 	    return KADM5_BAD_TL_TYPE;
-=09
+
 	ret =3D hdb_replace_extension(context, &ent->entry, &ext);
 	free_HDB_extension(&ext);
     } else {
@@ -110,6 +112,17 @@
     return ret;
 }
=20
+static void
+default_flags(hdb_entry_ex *ent, int server)
+{
+    ent->entry.flags.client      =3D 1;
+    ent->entry.flags.server      =3D !!server;
+    ent->entry.flags.forwardable =3D 1;
+    ent->entry.flags.proxiable   =3D 1;
+    ent->entry.flags.renewable   =3D 1;
+    ent->entry.flags.postdate    =3D 1;
+}
+
=20
 /*
  * Create the hdb entry `ent' based on data from `princ' with
@@ -121,7 +134,7 @@
 _kadm5_setup_entry(kadm5_server_context *context,
 		   hdb_entry_ex *ent,
 		   uint32_t mask,
-		   kadm5_principal_ent_t princ,=20
+		   kadm5_principal_ent_t princ,
 		   uint32_t princ_mask,
 		   kadm5_principal_ent_t def,
 		   uint32_t def_mask)
@@ -147,14 +160,10 @@
 	    attr_to_flags(def->attributes, &ent->entry.flags);
 	    ent->entry.flags.invalid =3D 0;
 	} else {
-	    ent->entry.flags.client      =3D 1;
-	    ent->entry.flags.server      =3D 1;
-	    ent->entry.flags.forwardable =3D 1;
-	    ent->entry.flags.proxiable   =3D 1;
-	    ent->entry.flags.renewable   =3D 1;
-	    ent->entry.flags.postdate    =3D 1;
+	    default_flags(ent, 1);
 	}
     }
+
     if(mask & KADM5_MAX_LIFE) {
 	if(princ_mask & KADM5_MAX_LIFE) {
 	    if(princ->max_life)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/error.c
--- a/head/crypto/heimdal/lib/kadm5/error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: error.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 _kadm5_error_code(kadm5_ret_t code)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/flush.c
--- a/head/crypto/heimdal/lib/kadm5/flush.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/flush.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,47 +1,47 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: flush.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_flush(void *server_handle)
 {
     return 0;
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_c_flush(void *server_handle)
 {
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/flush_c.c
--- a/head/crypto/heimdal/lib/kadm5/flush_c.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/flush_c.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,9 +32,9 @@
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: flush_c.c 5723 1999-03-23 18:23:37Z joda $");
+RCSID("$Id$");
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_c_flush(void *server_handle)
 {
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/flush_s.c
--- a/head/crypto/heimdal/lib/kadm5/flush_s.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/flush_s.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,9 +32,9 @@
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: flush_s.c 5723 1999-03-23 18:23:37Z joda $");
+RCSID("$Id$");
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_flush(void *server_handle)
 {
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/free.c
--- a/head/crypto/heimdal/lib/kadm5/free.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/free.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,49 +1,49 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: free.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
-void=20
+void
 kadm5_free_key_data(void *server_handle,
-		    int16_t *n_key_data,=20
+		    int16_t *n_key_data,
 		    krb5_key_data *key_data)
 {
     int i;
     for(i =3D 0; i < *n_key_data; i++){
 	if(key_data[i].key_data_contents[0]){
-	    memset(key_data[i].key_data_contents[0],=20
+	    memset(key_data[i].key_data_contents[0],
 		   0,
 		   key_data[i].key_data_length[0]);
 	    free(key_data[i].key_data_contents[0]);
@@ -55,7 +55,7 @@
 }
=20
=20
-void=20
+void
 kadm5_free_principal_ent(void *server_handle,
 			 kadm5_principal_ent_t princ)
 {
@@ -78,9 +78,9 @@
 	free (princ->key_data);
 }
=20
-void=20
+void
 kadm5_free_name_list(void *server_handle,
-		     char **names,=20
+		     char **names,
 		     int *count)
 {
     int i;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/get_c.c
--- a/head/crypto/heimdal/lib/kadm5/get_c.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/get_c.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,44 @@
 /*
- * Copyright (c) 1997 - 2000, 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000, 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: get_c.c 17445 2006-05-05 10:37:46Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
-kadm5_c_get_principal(void *server_handle,=20
-		      krb5_principal princ,=20
-		      kadm5_principal_ent_t out,=20
+kadm5_c_get_principal(void *server_handle,
+		      krb5_principal princ,
+		      kadm5_principal_ent_t out,
 		      uint32_t mask)
 {
     kadm5_client_context *context =3D server_handle;
@@ -54,7 +54,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_get);
@@ -69,13 +69,13 @@
 	return ret;
     sp =3D krb5_storage_from_data (&reply);
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
     krb5_ret_int32(sp, &tmp);
     ret =3D tmp;
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     if(ret =3D=3D 0)
 	kadm5_ret_principal_ent(sp, out);
     krb5_storage_free(sp);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/get_prin=
cs_c.c
--- a/head/crypto/heimdal/lib/kadm5/get_princs_c.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/kadm5/get_princs_c.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,44 +1,44 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: get_princs_c.c 15484 2005-06-17 05:21:07Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
-kadm5_c_get_principals(void *server_handle,=20
+kadm5_c_get_principals(void *server_handle,
 		       const char *expression,
-		       char ***princs,=20
+		       char ***princs,
 		       int *count)
 {
     kadm5_client_context *context =3D server_handle;
@@ -61,6 +61,8 @@
 	krb5_store_string(sp, expression);
     ret =3D _kadm5_client_send(context, sp);
     krb5_storage_free(sp);
+    if (ret)
+	return ret;
     ret =3D _kadm5_client_recv(context, &reply);
     if(ret)
 	return ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/get_prin=
cs_s.c
--- a/head/crypto/heimdal/lib/kadm5/get_princs_s.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/kadm5/get_princs_s.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: get_princs_s.c 16378 2005-12-12 12:40:12Z lha $");
+RCSID("$Id$");
=20
 struct foreach_data {
     const char *exp;
@@ -77,9 +77,9 @@
 }
=20
 kadm5_ret_t
-kadm5_s_get_principals(void *server_handle,=20
+kadm5_s_get_principals(void *server_handle,
 		       const char *expression,
-		       char ***princs,=20
+		       char ***princs,
 		       int *count)
 {
     struct foreach_data d;
@@ -99,7 +99,7 @@
     }
     d.princs =3D NULL;
     d.count =3D 0;
-    ret =3D hdb_foreach(context->context, context->db, 0, foreach, &d);
+    ret =3D hdb_foreach(context->context, context->db, HDB_F_ADMIN_DATA, f=
oreach, &d);
     context->db->hdb_close(context->context, context->db);
     if(ret =3D=3D 0)
 	ret =3D add_princ(&d, NULL);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/get_s.c
--- a/head/crypto/heimdal/lib/kadm5/get_s.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/get_s.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: get_s.c 21745 2007-07-31 16:11:25Z lha $");
+RCSID("$Id$");
=20
 static kadm5_ret_t
-add_tl_data(kadm5_principal_ent_t ent, int16_t type,=20
+add_tl_data(kadm5_principal_ent_t ent, int16_t type,
 	    const void *data, size_t size)
 {
     krb5_tl_data *tl;
@@ -48,7 +48,7 @@
     tl->tl_data_type =3D type;
     tl->tl_data_length =3D size;
     tl->tl_data_contents =3D malloc(size);
-    if (tl->tl_data_contents =3D=3D NULL) {
+    if (tl->tl_data_contents =3D=3D NULL && size !=3D 0) {
 	free(tl);
 	return _kadm5_error_code(ENOMEM);
     }
@@ -61,32 +61,32 @@
     return 0;
 }
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 _krb5_put_int(void *buffer, unsigned long value, size_t size); /* XXX */
=20
 kadm5_ret_t
-kadm5_s_get_principal(void *server_handle,=20
-		      krb5_principal princ,=20
-		      kadm5_principal_ent_t out,=20
+kadm5_s_get_principal(void *server_handle,
+		      krb5_principal princ,
+		      kadm5_principal_ent_t out,
 		      uint32_t mask)
 {
     kadm5_server_context *context =3D server_handle;
     kadm5_ret_t ret;
     hdb_entry_ex ent;
-   =20
+
     memset(&ent, 0, sizeof(ent));
     ret =3D context->db->hdb_open(context->context, context->db, O_RDONLY,=
 0);
     if(ret)
 	return ret;
-    ret =3D context->db->hdb_fetch(context->context, context->db, princ,
-				 HDB_F_DECRYPT|HDB_F_GET_ANY, &ent);
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db, pri=
nc,
+				      HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
     context->db->hdb_close(context->context, context->db);
     if(ret)
 	return _kadm5_error_code(ret);
=20
     memset(out, 0, sizeof(*out));
     if(mask & KADM5_PRINCIPAL)
-	ret  =3D krb5_copy_principal(context->context, ent.entry.principal,=20
+	ret  =3D krb5_copy_principal(context->context, ent.entry.principal,
 				   &out->principal);
     if(ret)
 	goto out;
@@ -126,11 +126,11 @@
     if(mask & KADM5_MOD_NAME) {
 	if(ent.entry.modified_by) {
 	    if (ent.entry.modified_by->principal !=3D NULL)
-		ret =3D krb5_copy_principal(context->context,=20
+		ret =3D krb5_copy_principal(context->context,
 					  ent.entry.modified_by->principal,
 					  &out->mod_name);
 	} else if(ent.entry.created_by.principal !=3D NULL)
-	    ret =3D krb5_copy_principal(context->context,=20
+	    ret =3D krb5_copy_principal(context->context,
 				      ent.entry.created_by.principal,
 				      &out->mod_name);
 	else
@@ -142,7 +142,7 @@
     if(mask & KADM5_KVNO)
 	out->kvno =3D ent.entry.kvno;
     if(mask & KADM5_MKVNO) {
-	int n;
+	size_t n;
 	out->mkvno =3D 0; /* XXX */
 	for(n =3D 0; n < ent.entry.keys.len; n++)
 	    if(ent.entry.keys.val[n].mkvno) {
@@ -150,8 +150,16 @@
 		break;
 	    }
     }
+#if 0 /* XXX implement */
     if(mask & KADM5_AUX_ATTRIBUTES)
-	/* XXX implement */;
+	;
+    if(mask & KADM5_LAST_SUCCESS)
+	;
+    if(mask & KADM5_LAST_FAILED)
+	;
+    if(mask & KADM5_FAIL_AUTH_COUNT)
+	;
+#endif
     if(mask & KADM5_POLICY)
 	out->policy =3D NULL;
     if(mask & KADM5_MAX_RLIFE) {
@@ -160,21 +168,15 @@
 	else
 	    out->max_renewable_life =3D INT_MAX;
     }
-    if(mask & KADM5_LAST_SUCCESS)
-	/* XXX implement */;
-    if(mask & KADM5_LAST_FAILED)
-	/* XXX implement */;
-    if(mask & KADM5_FAIL_AUTH_COUNT)
-	/* XXX implement */;
     if(mask & KADM5_KEY_DATA){
-	int i;
+	size_t i;
 	Key *key;
 	krb5_key_data *kd;
 	krb5_salt salt;
 	krb5_data *sp;
 	krb5_get_pw_salt(context->context, ent.entry.principal, &salt);
 	out->key_data =3D malloc(ent.entry.keys.len * sizeof(*out->key_data));
-	if (out->key_data =3D=3D NULL) {
+	if (out->key_data =3D=3D NULL && ent.entry.keys.len !=3D 0) {
 	    ret =3D ENOMEM;
 	    goto out;
 	}
@@ -191,11 +193,11 @@
 	    /* setup key */
 	    kd->key_data_length[0] =3D key->key.keyvalue.length;
 	    kd->key_data_contents[0] =3D malloc(kd->key_data_length[0]);
-	    if(kd->key_data_contents[0] =3D=3D NULL){
+	    if(kd->key_data_contents[0] =3D=3D NULL && kd->key_data_length[0] !=
=3D 0){
 		ret =3D ENOMEM;
 		break;
 	    }
-	    memcpy(kd->key_data_contents[0], key->key.keyvalue.data,=20
+	    memcpy(kd->key_data_contents[0], key->key.keyvalue.data,
 		   kd->key_data_length[0]);
 	    /* setup salt */
 	    if(key->salt)
@@ -221,6 +223,7 @@
     }
     if(mask & KADM5_TL_DATA) {
 	time_t last_pw_expire;
+	const HDB_Ext_PKINIT_acl *acl;
 	const HDB_Ext_Aliases *aliases;
=20
 	ret =3D hdb_entry_get_pw_change_time(&ent.entry, &last_pw_expire);
@@ -233,21 +236,46 @@
 	    kadm5_free_principal_ent(context, out);
 	    goto out;
 	}
-	/*=20
+	/*
 	 * If the client was allowed to get key data, let it have the
 	 * password too.
 	 */
 	if(mask & KADM5_KEY_DATA) {
 	    heim_utf8_string pw;
=20
-	    ret =3D hdb_entry_get_password(context->context,=20
+	    ret =3D hdb_entry_get_password(context->context,
 					 context->db, &ent.entry, &pw);
 	    if (ret =3D=3D 0) {
 		ret =3D add_tl_data(out, KRB5_TL_PASSWORD, pw, strlen(pw) + 1);
 		free(pw);
 	    }
-	    krb5_clear_error_string(context->context);
-	    ret =3D 0;
+	    krb5_clear_error_message(context->context);
+	}
+
+	ret =3D hdb_entry_get_pkinit_acl(&ent.entry, &acl);
+	if (ret =3D=3D 0 && acl) {
+	    krb5_data buf;
+	    size_t len;
+
+	    ASN1_MALLOC_ENCODE(HDB_Ext_PKINIT_acl, buf.data, buf.length,
+				acl, &len, ret);
+	    if (ret) {
+		kadm5_free_principal_ent(context, out);
+		goto out;
+	    }
+	    if (len !=3D buf.length)
+		krb5_abortx(context->context,
+			    "internal ASN.1 encoder error");
+	    ret =3D add_tl_data(out, KRB5_TL_PKINIT_ACL, buf.data, buf.length);
+	    free(buf.data);
+	    if (ret) {
+		kadm5_free_principal_ent(context, out);
+		goto out;
+	    }
+	}
+	if(ret){
+	    kadm5_free_principal_ent(context, out);
+	    goto out;
 	}
=20
 	ret =3D hdb_entry_get_aliases(&ent.entry, &aliases);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/init_c.c
--- a/head/crypto/heimdal/lib/kadm5/init_c.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/init_c.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,49 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
 #include <sys/types.h>
+#ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
+#endif
+#ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
+#endif
+#ifdef HAVE_NETDB_H
 #include <netdb.h>
+#endif
=20
-RCSID("$Id: init_c.c 21972 2007-10-18 19:11:15Z lha $");
+RCSID("$Id$");
=20
 static void
 set_funcs(kadm5_client_context *c)
@@ -58,7 +64,7 @@
 }
=20
 kadm5_ret_t
-_kadm5_c_init_context(kadm5_client_context **ctx,=20
+_kadm5_c_init_context(kadm5_client_context **ctx,
 		      kadm5_config_params *params,
 		      krb5_context context)
 {
@@ -117,7 +123,7 @@
 	(*ctx)->kadmind_port =3D htons(strtol (colon, &end, 0));
     }
     if ((*ctx)->kadmind_port =3D=3D 0)
-	(*ctx)->kadmind_port =3D krb5_getportbyname (context, "kerberos-adm",=20
+	(*ctx)->kadmind_port =3D krb5_getportbyname (context, "kerberos-adm",
 						   "tcp", 749);
     return 0;
 }
@@ -130,11 +136,11 @@
 {
     krb5_error_code ret;
     krb5_creds in, *out;
-   =20
+
     memset(&in, 0, sizeof(in));
     in.client =3D client;
     ret =3D krb5_parse_name(context, server_name, &in.server);
-    if(ret)=20
+    if(ret)
 	return ret;
     ret =3D krb5_get_credentials(context, 0, id, &in, &out);
     if(ret =3D=3D 0)
@@ -156,14 +162,14 @@
     krb5_creds cred;
     krb5_get_init_creds_opt *opt;
     krb5_ccache id;
-   =20
+
     ret =3D krb5_get_init_creds_opt_alloc (context, &opt);
     if (ret)
 	return ret;
=20
-    krb5_get_init_creds_opt_set_default_flags(context, "kadmin",=20
-					      krb5_principal_get_realm(context,=20
-								       client),=20
+    krb5_get_init_creds_opt_set_default_flags(context, "kadmin",
+					      krb5_principal_get_realm(context,
+								       client),
 					      opt);
=20
=20
@@ -210,7 +216,7 @@
     default:
 	return ret;
     }
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &id);
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
     if(ret)
 	return ret;
     ret =3D krb5_cc_initialize (context, id, cred.client);
@@ -225,7 +231,7 @@
 }
=20
 /*
- * Check the credential cache `id=B4 to figure out what principal to use
+ * Check the credential cache `id=C2=B4 to figure out what principal to use
  * when talking to the kadmind. If there is a initial kadmin/admin@
  * credential in the cache, use that client principal. Otherwise, use
  * the client principals first component and add /admin to the
@@ -246,7 +252,7 @@
 	*id =3D NULL;
 	return ret;
     }
-   =20
+
     ret =3D krb5_cc_get_principal(context, *id, &p1);
     if(ret) {
 	krb5_cc_close(context, *id);
@@ -254,7 +260,7 @@
 	return ret;
     }
=20
-    ret =3D krb5_make_principal(context, &p2, NULL,=20
+    ret =3D krb5_make_principal(context, &p2, NULL,
 			      "kadmin", "admin", NULL);
     if (ret) {
 	krb5_cc_close(context, *id);
@@ -319,16 +325,16 @@
     krb5_error_code ret;
     krb5_ccache id =3D NULL;
     krb5_principal default_client =3D NULL, client =3D NULL;
-   =20
+
     /* treat empty password as NULL */
     if(password && *password =3D=3D '\0')
 	password =3D NULL;
     if(server_name =3D=3D NULL)
 	server_name =3D KADM5_ADMIN_SERVICE;
-   =20
+
     if(client_name !=3D NULL) {
 	ret =3D krb5_parse_name(context, client_name, &client);
-	if(ret)=20
+	if(ret)
 	    return ret;
     }
=20
@@ -342,7 +348,7 @@
=20
 	ret =3D get_cache_principal(context, &id, &default_client);
 	if (ret) {
-	    /*=20
+	    /*
 	     * No client was specified by the caller and we cannot
 	     * determine the client from a credentials cache.
 	     */
@@ -351,10 +357,10 @@
 	    user =3D get_default_username ();
=20
 	    if(user =3D=3D NULL) {
-		krb5_set_error_string(context, "Unable to find local user name");
+		krb5_set_error_message(context, KADM5_FAILURE, "Unable to find local use=
r name");
 		return KADM5_FAILURE;
 	    }
-	    ret =3D krb5_make_principal(context, &default_client,=20
+	    ret =3D krb5_make_principal(context, &default_client,
 				      NULL, user, "admin", NULL);
 	    if(ret)
 		return ret;
@@ -369,9 +375,9 @@
     if (client =3D=3D NULL && default_client !=3D NULL)
 	client =3D default_client;
=20
-   =20
-    if(id && (default_client =3D=3D NULL ||=20
-	      krb5_principal_compare(context, client, default_client))) {
+
+    if(id && client && (default_client =3D=3D NULL ||
+	      krb5_principal_compare(context, client, default_client) !=3D 0)) {
 	ret =3D get_kadm_ticket(context, id, client, server_name);
 	if(ret =3D=3D 0) {
 	    *ret_cache =3D id;
@@ -390,7 +396,7 @@
     if (client !=3D default_client)
 	krb5_free_principal(context, default_client);
=20
-    ret =3D get_new_cache(context, client, password, prompter, keytab,=20
+    ret =3D get_new_cache(context, client, password, prompter, keytab,
 			server_name, ret_cache);
     krb5_free_principal(context, client);
     return ret;
@@ -402,7 +408,7 @@
     kadm5_ret_t ret;
     krb5_principal server;
     krb5_ccache cc;
-    int s;
+    rk_socket_t s =3D rk_INVALID_SOCKET;
     struct addrinfo *ai, *a;
     struct addrinfo hints;
     int error;
@@ -414,7 +420,7 @@
     memset (&hints, 0, sizeof(hints));
     hints.ai_socktype =3D SOCK_STREAM;
     hints.ai_protocol =3D IPPROTO_TCP;
-   =20
+
     snprintf (portstr, sizeof(portstr), "%u", ntohs(ctx->kadmind_port));
=20
     hostname =3D ctx->admin_server;
@@ -424,37 +430,37 @@
=20
     error =3D getaddrinfo (hostname, portstr, &hints, &ai);
     if (error) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return KADM5_BAD_SERVER_NAME;
     }
-   =20
+
     for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
 	s =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
 	if (s < 0)
 	    continue;
 	if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    krb5_warn (context, errno, "connect(%s)", hostname);
-	    close (s);
+	    rk_closesocket (s);
 	    continue;
 	}
 	break;
     }
     if (a =3D=3D NULL) {
 	freeaddrinfo (ai);
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	krb5_warnx (context, "failed to contact %s", hostname);
 	return KADM5_FAILURE;
     }
     ret =3D _kadm5_c_get_cred_cache(context,
-				  ctx->client_name,=20
-				  ctx->service_name,=20
-				  NULL, ctx->prompter, ctx->keytab,=20
+				  ctx->client_name,
+				  ctx->service_name,
+				  NULL, ctx->prompter, ctx->keytab,
 				  ctx->ccache, &cc);
-   =20
+
     if(ret) {
 	freeaddrinfo (ai);
-	close(s);
+	rk_closesocket(s);
 	return ret;
     }
=20
@@ -465,8 +471,8 @@
=20
     if (service_name =3D=3D NULL) {
 	freeaddrinfo (ai);
-	close(s);
-	krb5_clear_error_string(context);
+	rk_closesocket(s);
+	krb5_clear_error_message(context);
 	return ENOMEM;
     }
=20
@@ -476,14 +482,14 @@
 	freeaddrinfo (ai);
 	if(ctx->ccache =3D=3D NULL)
 	    krb5_cc_close(context, cc);
-	close(s);
+	rk_closesocket(s);
 	return ret;
     }
     ctx->ac =3D NULL;
=20
-    ret =3D krb5_sendauth(context, &ctx->ac, &s,=20
-			KADMIN_APPL_VERSION, NULL,=20
-			server, AP_OPTS_MUTUAL_REQUIRED,=20
+    ret =3D krb5_sendauth(context, &ctx->ac, &s,
+			KADMIN_APPL_VERSION, NULL,
+			server, AP_OPTS_MUTUAL_REQUIRED,
 			NULL, NULL, cc, NULL, NULL, NULL);
     if(ret =3D=3D 0) {
 	krb5_data params;
@@ -494,47 +500,47 @@
 	    p.realm =3D ctx->realm;
 	}
 	ret =3D _kadm5_marshal_params(context, &p, &params);
-=09
+
 	ret =3D krb5_write_priv_message(context, ctx->ac, &s, &params);
 	krb5_data_free(&params);
 	if(ret) {
 	    freeaddrinfo (ai);
-	    close(s);
+	    rk_closesocket(s);
 	    if(ctx->ccache =3D=3D NULL)
 		krb5_cc_close(context, cc);
 	    return ret;
 	}
     } else if(ret =3D=3D KRB5_SENDAUTH_BADAPPLVERS) {
-	close(s);
+	rk_closesocket(s);
=20
 	s =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
 	if (s < 0) {
 	    freeaddrinfo (ai);
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    return errno;
 	}
 	if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
-	    close (s);
+	    rk_closesocket (s);
 	    freeaddrinfo (ai);
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    return errno;
 	}
-	ret =3D krb5_sendauth(context, &ctx->ac, &s,=20
-			    KADMIN_OLD_APPL_VERSION, NULL,=20
-			    server, AP_OPTS_MUTUAL_REQUIRED,=20
+	ret =3D krb5_sendauth(context, &ctx->ac, &s,
+			    KADMIN_OLD_APPL_VERSION, NULL,
+			    server, AP_OPTS_MUTUAL_REQUIRED,
 			    NULL, NULL, cc, NULL, NULL, NULL);
     }
     freeaddrinfo (ai);
     if(ret) {
-	close(s);
+	rk_closesocket(s);
 	return ret;
     }
-   =20
+
     krb5_free_principal(context, server);
     if(ctx->ccache =3D=3D NULL)
 	krb5_cc_close(context, cc);
     ctx->sock =3D s;
-   =20
+
     return 0;
 }
=20
@@ -547,9 +553,9 @@
     return 0;
 }
=20
-static kadm5_ret_t=20
+static kadm5_ret_t
 kadm5_c_init_with_context(krb5_context context,
-			  const char *client_name,=20
+			  const char *client_name,
 			  const char *password,
 			  krb5_prompter_fct prompter,
 			  const char *keytab,
@@ -569,15 +575,15 @@
 	return ret;
=20
     if(password !=3D NULL && *password !=3D '\0') {
-	ret =3D _kadm5_c_get_cred_cache(context,=20
+	ret =3D _kadm5_c_get_cred_cache(context,
 				      client_name,
-				      service_name,=20
+				      service_name,
 				      password, prompter, keytab, ccache, &cc);
 	if(ret)
 	    return ret; /* XXX */
 	ccache =3D cc;
     }
-   =20
+
=20
     if (client_name !=3D NULL)
 	ctx->client_name =3D strdup(client_name);
@@ -592,13 +598,13 @@
     ctx->ccache =3D ccache;
     /* maybe we should copy the params here */
     ctx->sock =3D -1;
-   =20
+
     *server_handle =3D ctx;
     return 0;
 }
=20
-static kadm5_ret_t=20
-init_context(const char *client_name,=20
+static kadm5_ret_t
+init_context(const char *client_name,
 	     const char *password,
 	     krb5_prompter_fct prompter,
 	     const char *keytab,
@@ -612,7 +618,7 @@
     krb5_context context;
     kadm5_ret_t ret;
     kadm5_server_context *ctx;
-   =20
+
     ret =3D krb5_init_context(&context);
     if (ret)
 	return ret;
@@ -636,9 +642,9 @@
     return 0;
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_c_init_with_password_ctx(krb5_context context,
-			       const char *client_name,=20
+			       const char *client_name,
 			       const char *password,
 			       const char *service_name,
 			       kadm5_config_params *realm_params,
@@ -659,8 +665,8 @@
 				     server_handle);
 }
=20
-kadm5_ret_t=20
-kadm5_c_init_with_password(const char *client_name,=20
+kadm5_ret_t
+kadm5_c_init_with_password(const char *client_name,
 			   const char *password,
 			   const char *service_name,
 			   kadm5_config_params *realm_params,
@@ -668,21 +674,21 @@
 			   unsigned long api_version,
 			   void **server_handle)
 {
-    return init_context(client_name,=20
-			password,=20
+    return init_context(client_name,
+			password,
 			krb5_prompter_posix,
 			NULL,
 			NULL,
-			service_name,=20
-			realm_params,=20
-			struct_version,=20
-			api_version,=20
+			service_name,
+			realm_params,
+			struct_version,
+			api_version,
 			server_handle);
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_c_init_with_skey_ctx(krb5_context context,
-			   const char *client_name,=20
+			   const char *client_name,
 			   const char *keytab,
 			   const char *service_name,
 			   kadm5_config_params *realm_params,
@@ -704,8 +710,8 @@
 }
=20
=20
-kadm5_ret_t=20
-kadm5_c_init_with_skey(const char *client_name,=20
+kadm5_ret_t
+kadm5_c_init_with_skey(const char *client_name,
 		     const char *keytab,
 		     const char *service_name,
 		     kadm5_config_params *realm_params,
@@ -713,19 +719,19 @@
 		     unsigned long api_version,
 		     void **server_handle)
 {
-    return init_context(client_name,=20
+    return init_context(client_name,
 			NULL,
 			NULL,
 			keytab,
 			NULL,
-			service_name,=20
-			realm_params,=20
-			struct_version,=20
-			api_version,=20
+			service_name,
+			realm_params,
+			struct_version,
+			api_version,
 			server_handle);
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_c_init_with_creds_ctx(krb5_context context,
 			    const char *client_name,
 			    krb5_ccache ccache,
@@ -748,7 +754,7 @@
 				     server_handle);
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_c_init_with_creds(const char *client_name,
 			krb5_ccache ccache,
 			const char *service_name,
@@ -757,20 +763,20 @@
 			unsigned long api_version,
 			void **server_handle)
 {
-    return init_context(client_name,=20
+    return init_context(client_name,
 			NULL,
 			NULL,
 			NULL,
 			ccache,
-			service_name,=20
-			realm_params,=20
-			struct_version,=20
-			api_version,=20
+			service_name,
+			realm_params,
+			struct_version,
+			api_version,
 			server_handle);
 }
=20
 #if 0
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_init(char *client_name, char *pass,
 	   char *service_name,
 	   kadm5_config_params *realm_params,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/init_s.c
--- a/head/crypto/heimdal/lib/kadm5/init_s.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/init_s.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,44 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: init_s.c 9441 2000-12-31 08:01:16Z assar $");
+RCSID("$Id$");
=20
=20
-static kadm5_ret_t=20
+static kadm5_ret_t
 kadm5_s_init_with_context(krb5_context context,
-			  const char *client_name,=20
+			  const char *client_name,
 			  const char *service_name,
 			  kadm5_config_params *realm_params,
 			  unsigned long struct_version,
@@ -55,19 +55,29 @@
     assert(ctx->config.stash_file !=3D NULL);
     assert(ctx->config.acl_file !=3D NULL);
     assert(ctx->log_context.log_file !=3D NULL);
+#ifndef NO_UNIX_SOCKETS
     assert(ctx->log_context.socket_name.sun_path[0] !=3D '\0');
+#else
+    assert(ctx->log_context.socket_info !=3D NULL);
+#endif
=20
     ret =3D hdb_create(ctx->context, &ctx->db, ctx->config.dbname);
     if(ret)
 	return ret;
-    ret =3D hdb_set_master_keyfile (ctx->context,=20
+    ret =3D hdb_set_master_keyfile (ctx->context,
 				  ctx->db, ctx->config.stash_file);
     if(ret)
 	return ret;
=20
     ctx->log_context.log_fd   =3D -1;
=20
+#ifndef NO_UNIX_SOCKETS
     ctx->log_context.socket_fd =3D socket (AF_UNIX, SOCK_DGRAM, 0);
+#else
+    ctx->log_context.socket_fd =3D socket (ctx->log_context.socket_info->a=
i_family,
+					 ctx->log_context.socket_info->ai_socktype,
+					 ctx->log_context.socket_info->ai_protocol);
+#endif
=20
     ret =3D krb5_parse_name(ctx->context, client_name, &ctx->caller);
     if(ret)
@@ -76,14 +86,14 @@
     ret =3D _kadm5_acl_init(ctx);
     if(ret)
 	return ret;
-   =20
+
     *server_handle =3D ctx;
     return 0;
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_init_with_password_ctx(krb5_context context,
-			       const char *client_name,=20
+			       const char *client_name,
 			       const char *password,
 			       const char *service_name,
 			       kadm5_config_params *realm_params,
@@ -100,8 +110,8 @@
 				     server_handle);
 }
=20
-kadm5_ret_t=20
-kadm5_s_init_with_password(const char *client_name,=20
+kadm5_ret_t
+kadm5_s_init_with_password(const char *client_name,
 			   const char *password,
 			   const char *service_name,
 			   kadm5_config_params *realm_params,
@@ -116,13 +126,13 @@
     ret =3D krb5_init_context(&context);
     if (ret)
 	return ret;
-    ret =3D kadm5_s_init_with_password_ctx(context,=20
-					 client_name,=20
-					 password,=20
-					 service_name,=20
-					 realm_params,=20
-					 struct_version,=20
-					 api_version,=20
+    ret =3D kadm5_s_init_with_password_ctx(context,
+					 client_name,
+					 password,
+					 service_name,
+					 realm_params,
+					 struct_version,
+					 api_version,
 					 server_handle);
     if(ret){
 	krb5_free_context(context);
@@ -133,9 +143,9 @@
     return 0;
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_init_with_skey_ctx(krb5_context context,
-			   const char *client_name,=20
+			   const char *client_name,
 			   const char *keytab,
 			   const char *service_name,
 			   kadm5_config_params *realm_params,
@@ -152,7 +162,7 @@
 				     server_handle);
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_init_with_skey(const char *client_name,
 		       const char *keytab,
 		       const char *service_name,
@@ -168,13 +178,13 @@
     ret =3D krb5_init_context(&context);
     if (ret)
 	return ret;
-    ret =3D kadm5_s_init_with_skey_ctx(context,=20
-				     client_name,=20
-				     keytab,=20
-				     service_name,=20
-				     realm_params,=20
-				     struct_version,=20
-				     api_version,=20
+    ret =3D kadm5_s_init_with_skey_ctx(context,
+				     client_name,
+				     keytab,
+				     service_name,
+				     realm_params,
+				     struct_version,
+				     api_version,
 				     server_handle);
     if(ret){
 	krb5_free_context(context);
@@ -185,7 +195,7 @@
     return 0;
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_init_with_creds_ctx(krb5_context context,
 			    const char *client_name,
 			    krb5_ccache ccache,
@@ -204,7 +214,7 @@
 				     server_handle);
 }
=20
-kadm5_ret_t=20
+kadm5_ret_t
 kadm5_s_init_with_creds(const char *client_name,
 			krb5_ccache ccache,
 			const char *service_name,
@@ -220,13 +230,13 @@
     ret =3D krb5_init_context(&context);
     if (ret)
 	return ret;
-    ret =3D kadm5_s_init_with_creds_ctx(context,=20
-				      client_name,=20
-				      ccache,=20
-				      service_name,=20
-				      realm_params,=20
-				      struct_version,=20
-				      api_version,=20
+    ret =3D kadm5_s_init_with_creds_ctx(context,
+				      client_name,
+				      ccache,
+				      service_name,
+				      realm_params,
+				      struct_version,
+				      api_version,
 				      server_handle);
     if(ret){
 	krb5_free_context(context);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/iprop-co=
mmands.in
--- a/head/crypto/heimdal/lib/kadm5/iprop-commands.in	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/iprop-commands.in	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).=20
  * All rights reserved.=20
  *
@@ -30,7 +30,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
  * SUCH DAMAGE.=20
  */
-/* $Id: iprop-commands.in 20602 2007-05-08 03:08:35Z lha $ */
+/* $Id$ */
=20
 command =3D {
 	name =3D "dump"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/iprop-lo=
g.8
--- a/head/crypto/heimdal/lib/kadm5/iprop-log.8	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/iprop-log.8	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,110 +1,98 @@
-.\" $Id: iprop-log.8 21713 2007-07-27 14:38:49Z lha $
-.\"=20
-.\" Copyright (c) 2005 - 2007 Kungliga Tekniska H=F6gskolan
+.\" $Id$
+.\"
+.\" Copyright (c) 2005 - 2007 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
-.\" All rights reserved.=20
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
 .\"
-.\"	$Id: iprop-log.8 21713 2007-07-27 14:38:49Z lha $
+.\"	$Id$
 .\"
 .Dd February 18, 2007
 .Dt IPROP-LOG 8
 .Os Heimdal
 .Sh NAME
 .Nm iprop-log
-.Nd
-maintain the iprop log file
+.Nd maintain the iprop log file
 .Sh SYNOPSIS
 .Nm
-.Op Fl -version
-.Op Fl h | Fl -help
+.Op Fl Fl version
+.Op Fl h | Fl Fl help
 .Ar command
 .Pp
 .Nm iprop-log truncate
 .Oo Fl c Ar file \*(Ba Xo
-.Fl -config-file=3D Ns Ar file
+.Fl Fl config-file=3D Ns Ar file
 .Xc
 .Oc
 .Oo Fl r Ar string \*(Ba Xo
-.Fl -realm=3D Ns Ar string
+.Fl Fl realm=3D Ns Ar string
 .Xc
 .Oc
-.Op Fl h | Fl -help
+.Op Fl h | Fl Fl help
 .Pp
 .Nm iprop-log dump
 .Oo Fl c Ar file \*(Ba Xo
-.Fl -config-file=3D Ns Ar file
+.Fl Fl config-file=3D Ns Ar file
 .Xc
 .Oc
 .Oo Fl r Ar string \*(Ba Xo
-.Fl -realm=3D Ns Ar string
+.Fl Fl realm=3D Ns Ar string
 .Xc
 .Oc
-.Op Fl h | Fl -help
+.Op Fl h | Fl Fl help
 .Pp
 .Nm iprop-log replay
-.Op Fl -start-version=3D Ns Ar version-number
-.Op Fl -end-version=3D Ns Ar version-number
+.Op Fl Fl start-version=3D Ns Ar version-number
+.Op Fl Fl end-version=3D Ns Ar version-number
 .Oo Fl c Ar file \*(Ba Xo
-.Fl -config-file=3D Ns Ar file
+.Fl Fl config-file=3D Ns Ar file
 .Xc
 .Oc
 .Oo Fl r Ar string \*(Ba Xo
-.Fl -realm=3D Ns Ar string
+.Fl Fl realm=3D Ns Ar string
 .Xc
 .Oc
-.Op Fl h | Fl -help
+.Op Fl h | Fl Fl help
 .Sh DESCRIPTION
 Supported options:
 .Bl -tag -width Ds
-.It Xo
-.Fl -version
-.Xc
-.It Xo
-.Fl h ,
-.Fl -help
-.Xc
+.It Fl Fl version
+.It Fl h , Fl Fl help
 .El
 .Pp
 command can be one of the following:
 .Bl -tag -width truncate
 .It truncate
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 configuration file
-.It Xo
-.Fl r Ar string ,
-.Fl -realm=3D Ns Ar string
-.Xc
+.It Fl r Ar string , Fl Fl realm=3D Ns Ar string
 realm
 .El
 .Pp
@@ -113,38 +101,27 @@
 file, the log will start over at the first version (0).
 .It dump
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 configuration file
 .It Xo
 .Fl r Ar string ,
-.Fl -realm=3D Ns Ar string
+.Fl Fl realm=3D Ns Ar string
 .Xc
 realm
 .El
 .Pp
-Print out all entires in the log to standard output.
+Print out all entries in the log to standard output.
 .It replay
 .Bl -tag -width Ds
-.It Xo
-.Fl -start-version=3D Ns Ar version-number
-.Xc
+.It Fl Fl start-version=3D Ns Ar version-number
 start replay with this version
 .It Xo
-.Fl -end-version=3D Ns Ar version-number
+.Fl Fl end-version=3D Ns Ar version-number
 .Xc
 end replay with this version
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 configuration file
-.It Xo
-.Fl r Ar string ,
-.Fl -realm=3D Ns Ar string
-.Xc
+.It Fl r Ar string , Fl Fl realm=3D Ns Ar string
 realm
 .El
 .Pp
@@ -152,15 +129,9 @@
 specified) in the transaction log to the database.
 .It last-version
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar file ,
-.Fl -config-file=3D Ns Ar file
-.Xc
+.It Fl c Ar file , Fl Fl config-file=3D Ns Ar file
 configuration file
-.It Xo
-.Fl r Ar string ,
-.Fl -realm=3D Ns Ar string
-.Xc
+.It Fl r Ar string , Fl Fl realm=3D Ns Ar string
 realm
 .El
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/iprop-lo=
g.c
--- a/head/crypto/heimdal/lib/kadm5/iprop-log.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/iprop-log.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "iprop.h"
@@ -36,7 +36,7 @@
 #include <parse_time.h>
 #include "iprop-commands.h"
=20
-RCSID("$Id: iprop-log.c 22211 2007-12-07 19:27:27Z lha $");
+RCSID("$Id$");
=20
 static krb5_context context;
=20
@@ -75,7 +75,7 @@
 					KADM5_ADMIN_SERVICE,
 					NULL,
 					KADM5_ADMIN_SERVICE,
-					&conf, 0, 0,=20
+					&conf, 0, 0,
 					&kadm_handle);
     if (ret)
 	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");
@@ -119,12 +119,12 @@
     krb5_context scontext =3D server_context->context;
=20
     off_t end =3D krb5_storage_seek(sp, 0, SEEK_CUR) + len;
-   =20
+
     krb5_error_code ret;
=20
     strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
=20
-    if(op < kadm_get || op > kadm_nop) {
+    if((int)op < (int)kadm_get || (int)op > (int)kadm_nop) {
 	printf("unknown op: %d\n", op);
 	krb5_storage_seek(sp, end, SEEK_SET);
 	return;
@@ -184,7 +184,7 @@
 	    if(ent.valid_end =3D=3D NULL) {
 		strlcpy(t, "never", sizeof(t));
 	    } else {
-		strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S",=20
+		strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S",
 			 localtime(ent.valid_end));
 	    }
 	    printf("    expires =3D %s\n", t);
@@ -193,7 +193,7 @@
 	    if(ent.pw_end =3D=3D NULL) {
 		strlcpy(t, "never", sizeof(t));
 	    } else {
-		strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S",=20
+		strftime(t, sizeof(t), "%Y-%m-%d %H:%M:%S",
 			 localtime(ent.pw_end));
 	    }
 	    printf("    password exp =3D %s\n", t);
@@ -201,7 +201,7 @@
 	if(mask & KADM5_LAST_PWD_CHANGE) {
 	}
 	if(mask & KADM5_ATTRIBUTES) {
-	    unparse_flags(HDBFlags2int(ent.flags),=20
+	    unparse_flags(HDBFlags2int(ent.flags),
 			  asn1_HDBFlags_units(), t, sizeof(t));
 	    printf("    attributes =3D %s\n", t);
 	}
@@ -271,7 +271,7 @@
     kadm5_server_context *server_context;
     krb5_error_code ret;
=20
-    server_context =3D get_kadmin_context(opt->config_file_string,=20
+    server_context =3D get_kadmin_context(opt->config_file_string,
 					opt->realm_string);
=20
     ret =3D kadm5_log_init (server_context);
@@ -294,7 +294,7 @@
     kadm5_server_context *server_context;
     krb5_error_code ret;
=20
-    server_context =3D get_kadmin_context(opt->config_file_string,=20
+    server_context =3D get_kadmin_context(opt->config_file_string,
 					opt->realm_string);
=20
     ret =3D kadm5_log_truncate (server_context);
@@ -311,7 +311,7 @@
     krb5_error_code ret;
     uint32_t version;
=20
-    server_context =3D get_kadmin_context(opt->config_file_string,=20
+    server_context =3D get_kadmin_context(opt->config_file_string,
 					opt->realm_string);
=20
     ret =3D kadm5_log_init (server_context);
@@ -344,14 +344,14 @@
 	    time_t timestamp,
 	    enum kadm_ops op,
 	    uint32_t len,
-	    krb5_storage *sp,=20
+	    krb5_storage *sp,
 	    void *ctx)
 {
     struct replay_options *opt =3D ctx;
     krb5_error_code ret;
=20
-    if((opt->start_version_integer !=3D -1 && ver < opt->start_version_int=
eger) ||
-       (opt->end_version_integer !=3D -1 && ver > opt->end_version_integer=
)) {
+    if((opt->start_version_integer !=3D -1 && ver < (uint32_t)opt->start_v=
ersion_integer) ||
+       (opt->end_version_integer !=3D -1 && ver > (uint32_t)opt->end_versi=
on_integer)) {
 	/* XXX skip this entry */
 	krb5_storage_seek(sp, len, SEEK_CUR);
 	return;
@@ -363,7 +363,7 @@
 			    op, ver, len, sp);
     if (ret)
 	krb5_warn (server_context->context, ret, "kadm5_log_replay");
-   =20
+
     printf ("done\n");
 }
=20
@@ -373,7 +373,7 @@
     kadm5_server_context *server_context;
     krb5_error_code ret;
=20
-    server_context =3D get_kadmin_context(opt->config_file_string,=20
+    server_context =3D get_kadmin_context(opt->config_file_string,
 					opt->realm_string);
=20
     ret =3D server_context->db->hdb_open(context,
@@ -404,9 +404,9 @@
=20
 static struct getargs args[] =3D {
     { "version", 	0,	arg_flag, 	&version_flag,
-      NULL,		NULL=20
-    },=20
-    { "help", 	'h', 	arg_flag, 	&help_flag,=20
+      NULL,		NULL
+    },
+    { "help", 	'h', 	arg_flag, 	&help_flag,
       NULL, NULL
     }
 };
@@ -426,8 +426,11 @@
 		     argv[0]);
 	} else {
 	    if(c->func) {
-		char *fake[] =3D { NULL, "--help", NULL };
+		static char shelp[] =3D "--help";
+		char *fake[3];
 		fake[0] =3D argv[0];
+		fake[1] =3D shelp;
+		fake[2] =3D NULL;
 		(*c->func)(2, fake);
 		fprintf(stderr, "\n");
 	    }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/iprop.8
--- a/head/crypto/heimdal/lib/kadm5/iprop.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/iprop.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" $Id: iprop.8 21940 2007-09-28 22:28:09Z lha $
-.\"=20
-.\" Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+.\" $Id$
+.\"
+.\" Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
-.\" All rights reserved.=20
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
 .\"
 .Dd May 24, 2005
 .Dt IPROP 8
@@ -38,51 +38,49 @@
 .Nm iprop ,
 .Nm ipropd-master ,
 .Nm ipropd-slave
-.Nd
-propagate changes to a Heimdal Kerberos master KDC to slave KDCs
+.Nd propagate changes to a Heimdal Kerberos master KDC to slave KDCs
 .Sh SYNOPSIS
 .Nm ipropd-master
 .Oo Fl c Ar string \*(Ba Xo
-.Fl -config-file=3D Ns Ar string
+.Fl Fl config-file=3D Ns Ar string
 .Xc
 .Oc
 .Oo Fl r Ar string \*(Ba Xo
-.Fl -realm=3D Ns Ar string
+.Fl Fl realm=3D Ns Ar string
 .Xc
 .Oc
 .Oo Fl k Ar kspec \*(Ba Xo
-.Fl -keytab=3D Ns Ar kspec
+.Fl Fl keytab=3D Ns Ar kspec
 .Xc
 .Oc
 .Oo Fl d Ar file \*(Ba Xo
-.Fl -database=3D Ns Ar file
+.Fl Fl database=3D Ns Ar file
 .Xc
 .Oc
-.Op Fl -slave-stats-file=3D Ns Ar file
-.Op Fl -time-missing=3D Ns Ar time
-.Op Fl -time-gone=3D Ns Ar time
-.Op Fl -detach
-.Op Fl -version
-.Op Fl -help
+.Op Fl Fl slave-stats-file=3D Ns Ar file
+.Op Fl Fl time-missing=3D Ns Ar time
+.Op Fl Fl time-gone=3D Ns Ar time
+.Op Fl Fl detach
+.Op Fl Fl version
+.Op Fl Fl help
 .Nm ipropd-slave
 .Oo Fl c Ar string \*(Ba Xo
-.Fl -config-file=3D Ns Ar string
+.Fl Fl config-file=3D Ns Ar string
 .Xc
 .Oc
 .Oo Fl r Ar string \*(Ba Xo
-.Fl -realm=3D Ns Ar string
+.Fl Fl realm=3D Ns Ar string
 .Xc
 .Oc
 .Oo Fl k Ar kspec \*(Ba Xo
-.Fl -keytab=3D Ns Ar kspec
+.Fl Fl keytab=3D Ns Ar kspec
 .Xc
 .Oc
-.Op Fl -time-lost=3D Ns Ar time
-.Op Fl -detach
-.Op Fl -version
-.Op Fl -help
+.Op Fl Fl time-lost=3D Ns Ar time
+.Op Fl Fl detach
+.Op Fl Fl version
+.Op Fl Fl help
 .Ar master
-.Pp
 .Sh DESCRIPTION
 .Nm ipropd-master
 is used to propagate changes to a Heimdal Kerberos database from the
@@ -96,9 +94,9 @@
 .Pa /var/heimdal/slaves .
 This has principals one per-line of the form
 .Dl iprop/ Ns Ar slave Ns @ Ns Ar REALM
-where=20
-.Ar slave=20
-is the hostname of the slave server in the given=20
+where
+.Ar slave
+is the hostname of the slave server in the given
 .Ar REALM ,
 e.g.\&
 .Dl iprop/kerberos-1.example.com at EXAMPLE.COM
@@ -110,20 +108,23 @@
 .Xr hprop 8 ,
 which sends the whole database to the slaves regularly,
 .Nm
-normally sends only the changes as they happen on the master.  The
-master keeps track of all the changes by assigning a version number to
-every change to the database.  The slaves know which was the latest
-version they saw, and in this way it can be determined if they are in
-sync or not.  A log of all the changes is kept on the master.  When a
-slave is at an older version than the oldest one in the log, the whole
-database has to be sent.
+normally sends only the changes as they happen on the master.
+The master keeps track of all the changes by assigning a version
+number to every change to the database.
+The slaves know which was the latest version they saw, and in this
+way it can be determined if they are in sync or not.
+A log of all the changes is kept on the master.
+When a slave is at an older version than the oldest one in the log,
+the whole database has to be sent.
 .Pp
 The changes are propagated over a secure channel (on port 2121 by
-default).  This should normally be defined as
+default).
+This should normally be defined as
 .Dq iprop/tcp
 in
 .Pa /etc/services
-or another source of the services database.  The master and slaves
+or another source of the services database.
+The master and slaves
 must each have access to a keytab with keys for the
 .Nm iprop
 service principal on the local host.
@@ -136,78 +137,37 @@
 Supported options for
 .Nm ipropd-master :
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar string ,
-.Fl -config-file=3D Ns Ar string
-.Xc
-.It Xo
-.Fl r Ar string ,
-.Fl -realm=3D Ns Ar string
-.Xc
-.It Xo
-.Fl k Ar kspec ,
-.Fl -keytab=3D Ns Ar kspec
-.Xc
+.It Fl c Ar string , Fl Fl config-file=3D Ns Ar string
+.It Fl r Ar string , Fl Fl realm=3D Ns Ar string
+.It Fl k Ar kspec , Fl Fl keytab=3D Ns Ar kspec
 keytab to get authentication from
-.It Xo
-.Fl d Ar file ,
-.Fl -database=3D Ns Ar file
-.Xc
+.It Fl d Ar file , Fl Fl database=3D Ns Ar file
 Database (default per KDC)
-.It Xo
-.Fl -slave-stats-file=3D Ns Ar file
-.Xc
+.It Fl Fl slave-stats-file=3D Ns Ar file
 file for slave status information
-.It Xo
-.Fl -time-missing=3D Ns Ar time
-.Xc
+.It Fl Fl time-missing=3D Ns Ar time
 time before slave is polled for presence (default 2 min)
-.It Xo
-.Fl -time-gone=3D Ns Ar time
-.Xc
+.It Fl Fl time-gone=3D Ns Ar time
 time of inactivity after which a slave is considered gone (default 5 min)
-.It Xo
-.Fl -detach
-.Xc
+.It Fl Fl detach
 detach from console
-.It Xo
-.Fl -version
-.Xc
-.It Xo
-.Fl -help
-.Xc
+.It Fl Fl version
+.It Fl Fl help
 .El
 .Pp
 Supported options for
 .Nm ipropd-slave :
 .Bl -tag -width Ds
-.It Xo
-.Fl c Ar string ,
-.Fl -config-file=3D Ns Ar string
-.Xc
-.It Xo
-.Fl r Ar string ,
-.Fl -realm=3D Ns Ar string
-.Xc
-.It Xo
-.Fl k Ar kspec ,
-.Fl -keytab=3D Ns Ar kspec
-.Xc
+.It Fl c Ar string , Fl Fl config-file=3D Ns Ar string
+.It Fl r Ar string , Fl Fl realm=3D Ns Ar string
+.It Fl k Ar kspec , Fl Fl keytab=3D Ns Ar kspec
 keytab to get authentication from
-.It Xo
-.Fl -time-lost=3D Ns Ar time
-.Xc
+.It Fl Fl time-lost=3D Ns Ar time
 time before server is considered lost (default 5 min)
-.It Xo
-.Fl -detach
-.Xc
+.It Fl Fl detach
 detach from console
-.It Xo
-.Fl -version
-.Xc
-.It Xo
-.Fl -help
-.Xc
+.It Fl Fl version
+.It Fl Fl help
 .El
 Time arguments for the relevant options above may be specified in forms
 like 5 min, 300 s, or simply a number of seconds.
@@ -216,8 +176,8 @@
 .Pa slave-stats
 in the database directory.
 .Sh SEE ALSO
+.Xr krb5.conf 5 ,
+.Xr hprop 8 ,
 .Xr hpropd 8 ,
-.Xr hprop 8 ,
-.Xr krb5.conf 8 ,=20
-.Xr kdc 8 ,
-.Xr iprop-log 8 .
+.Xr iprop-log 8 ,
+.Xr kdc 8 .
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/iprop.h
--- a/head/crypto/heimdal/lib/kadm5/iprop.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/iprop.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1998-2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998-2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: iprop.h 22211 2007-12-07 19:27:27Z lha $ */
+/* $Id$ */
=20
 #ifndef __IPROP_H__
 #define __IPROP_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/ipropd_c=
ommon.c
--- a/head/crypto/heimdal/lib/kadm5/ipropd_common.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/kadm5/ipropd_common.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "iprop.h"
@@ -63,7 +63,11 @@
 #else
     signal(SIGINT, sigterm);
     signal(SIGTERM, sigterm);
+#ifndef NO_SIGXCPU
     signal(SIGXCPU, sigterm);
+#endif
+#ifndef NO_SIGPIPE
     signal(SIGPIPE, SIG_IGN);
 #endif
+#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/ipropd_m=
aster.c
--- a/head/crypto/heimdal/lib/kadm5/ipropd_master.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/kadm5/ipropd_master.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "iprop.h"
 #include <rtbl.h>
=20
-RCSID("$Id: ipropd_master.c 22211 2007-12-07 19:27:27Z lha $");
-
 static krb5_log_facility *log_facility;
=20
 const char *slave_stats_file;
@@ -47,12 +45,13 @@
=20
 const char *master_hostname;
=20
-static int
+static krb5_socket_t
 make_signal_socket (krb5_context context)
 {
+#ifndef NO_UNIX_SOCKETS
     struct sockaddr_un addr;
     const char *fn;
-    int fd;
+    krb5_socket_t fd;
=20
     fn =3D kadm5_log_signal_socket(context);
=20
@@ -66,25 +65,39 @@
     if (bind (fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
 	krb5_err (context, 1, errno, "bind %s", addr.sun_path);
     return fd;
+#else
+    struct addrinfo *ai =3D NULL;
+    krb5_socket_t fd;
+
+    kadm5_log_signal_socket_info(context, 1, &ai);
+
+    fd =3D socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
+    if (rk_IS_BAD_SOCKET(fd))
+	krb5_err (context, 1, rk_SOCK_ERRNO, "socket AF=3D%d", ai->ai_family);
+
+    if (rk_IS_SOCKET_ERROR( bind (fd, ai->ai_addr, ai->ai_addrlen) ))
+	krb5_err (context, 1, rk_SOCK_ERRNO, "bind");
+    return fd;
+#endif
 }
=20
-static int
+static krb5_socket_t
 make_listen_socket (krb5_context context, const char *port_str)
 {
-    int fd;
+    krb5_socket_t fd;
     int one =3D 1;
     struct sockaddr_in addr;
=20
     fd =3D socket (AF_INET, SOCK_STREAM, 0);
-    if (fd < 0)
-	krb5_err (context, 1, errno, "socket AF_INET");
+    if (rk_IS_BAD_SOCKET(fd))
+	krb5_err (context, 1, rk_SOCK_ERRNO, "socket AF_INET");
     setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (void *)&one, sizeof(one));
     memset (&addr, 0, sizeof(addr));
     addr.sin_family =3D AF_INET;
=20
     if (port_str) {
 	addr.sin_port =3D krb5_getportbyname (context,
-					      port_str, "tcp",=20
+					      port_str, "tcp",
 					      0);
 	if (addr.sin_port =3D=3D 0) {
 	    char *ptr;
@@ -96,7 +109,7 @@
 	    addr.sin_port =3D htons(port);
 	}
     } else {
-	addr.sin_port =3D krb5_getportbyname (context, IPROP_SERVICE,=20
+	addr.sin_port =3D krb5_getportbyname (context, IPROP_SERVICE,
 					    "tcp", IPROP_PORT);
     }
     if(bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
@@ -107,7 +120,7 @@
 }
=20
 struct slave {
-    int fd;
+    krb5_socket_t fd;
     struct sockaddr_in addr;
     char *name;
     krb5_auth_context ac;
@@ -128,9 +141,11 @@
     FILE *fp;
     char buf[256];
     int ret =3D 1;
-    char *slavefile;
+    char *slavefile =3D NULL;
=20
-    asprintf(&slavefile, "%s/slaves", hdb_db_dir(context));
+    if (asprintf(&slavefile, "%s/slaves", hdb_db_dir(context)) =3D=3D -1
+	|| slavefile =3D=3D NULL)
+	errx(1, "out of memory");
=20
     fn =3D krb5_config_get_string_default(context,
 					NULL,
@@ -182,9 +197,9 @@
 {
     krb5_warnx(context, "slave %s dead", s->name);
=20
-    if (s->fd >=3D 0) {
-	close (s->fd);
-	s->fd =3D -1;
+    if (!rk_IS_BAD_SOCKET(s->fd)) {
+	rk_closesocket (s->fd);
+	s->fd =3D rk_INVALID_SOCKET;
     }
     s->flags |=3D SLAVE_F_DEAD;
     slave_seen(s);
@@ -195,8 +210,8 @@
 {
     slave **p;
=20
-    if (s->fd >=3D 0)
-	close (s->fd);
+    if (!rk_IS_BAD_SOCKET(s->fd))
+	rk_closesocket (s->fd);
     if (s->name)
 	free (s->name);
     if (s->ac)
@@ -211,7 +226,8 @@
 }
=20
 static void
-add_slave (krb5_context context, krb5_keytab keytab, slave **root, int fd)
+add_slave (krb5_context context, krb5_keytab keytab, slave **root,
+	   krb5_socket_t fd)
 {
     krb5_principal server;
     krb5_error_code ret;
@@ -230,8 +246,8 @@
=20
     addr_len =3D sizeof(s->addr);
     s->fd =3D accept (fd, (struct sockaddr *)&s->addr, &addr_len);
-    if (s->fd < 0) {
-	krb5_warn (context, errno, "accept");
+    if (rk_IS_BAD_SOCKET(s->fd)) {
+	krb5_warn (context, rk_SOCK_ERRNO, "accept");
 	goto error;
     }
     if (master_hostname)
@@ -254,6 +270,7 @@
 	goto error;
     }
     ret =3D krb5_unparse_name (context, ticket->client, &s->name);
+    krb5_free_ticket (context, ticket);
     if (ret) {
 	krb5_warn (context, ret, "krb5_unparse_name");
 	goto error;
@@ -262,8 +279,6 @@
 	krb5_warnx (context, "%s not in acl", s->name);
 	goto error;
     }
-    krb5_free_ticket (context, ticket);
-    ticket =3D NULL;
=20
     {
 	slave *l =3D *root;
@@ -297,7 +312,7 @@
=20
 struct prop_context {
     krb5_auth_context auth_context;
-    int fd;
+    krb5_socket_t fd;
 };
=20
 static int
@@ -364,7 +379,7 @@
 	return ret;
     }
=20
-    ret =3D hdb_foreach (context, db, 0, prop_one, s);
+    ret =3D hdb_foreach (context, db, HDB_F_ADMIN_DATA, prop_one, s);
     if (ret) {
 	krb5_warn (context, ret, "hdb_foreach");
 	slave_dead(context, s);
@@ -408,6 +423,8 @@
     if (s->flags & (SLAVE_F_DEAD|SLAVE_F_AYT))
 	return 0;
=20
+    krb5_warnx(context, "slave %s missing, sending AYT", s->name);
+
     s->flags |=3D SLAVE_F_AYT;
=20
     data.data =3D buf;
@@ -467,7 +484,7 @@
     for (;;) {
 	ret =3D kadm5_log_previous (context, sp, &ver, &timestamp, &op, &len);
 	if (ret)
-	    krb5_err(context, 1, ret,=20
+	    krb5_err(context, 1, ret,
 		     "send_diffs: failed to find previous entry");
 	left =3D krb5_storage_seek(sp, -16, SEEK_CUR);
 	if (ver =3D=3D s->version)
@@ -475,6 +492,7 @@
 	if (ver =3D=3D s->version + 1)
 	    break;
 	if (left =3D=3D 0) {
+	    krb5_storage_free(sp);
 	    krb5_warnx(context,
 		       "slave %s (version %lu) out of sync with master "
 		       "(first version in log %lu), sending complete database",
@@ -490,6 +508,7 @@
=20
     ret =3D krb5_data_alloc (&data, right - left + 4);
     if (ret) {
+	krb5_storage_free(sp);
 	krb5_warn (context, ret, "send_diffs: krb5_data_alloc");
 	slave_dead(context, s);
 	return 1;
@@ -556,14 +575,15 @@
 	}
 	/* new started slave that have old log */
 	if (s->version =3D=3D 0 && tmp !=3D 0) {
-	    if (s->version < tmp) {
-		krb5_warnx (context, "Slave %s have later version the master "
-			    "OUT OF SYNC", s->name);
-	    } else {
-		s->version =3D tmp;
+	    if (current_version < (uint32_t)tmp) {
+		krb5_warnx (context, "Slave %s (version %lu) have later version "
+			    "the master (version %lu) OUT OF SYNC",
+			    s->name, (unsigned long)tmp,
+			    (unsigned long)current_version);
 	    }
+	    s->version =3D tmp;
 	}
-	if (tmp < s->version) {
+	if ((uint32_t)tmp < s->version) {
 	    krb5_warnx (context, "Slave claims to not have "
 			"version we already sent to it");
 	} else {
@@ -580,6 +600,7 @@
     }
=20
     krb5_data_free (&out);
+    krb5_storage_free (sp);
=20
     slave_seen(s);
=20
@@ -627,7 +648,7 @@
     fp =3D open_stats(context);
     if (fp =3D=3D NULL)
 	return;
-    krb5_format_time(context, t, str, sizeof(str), TRUE);=20
+    krb5_format_time(context, t, str, sizeof(str), TRUE);
     fprintf(fp, "master down at %s\n", str);
=20
     fclose(fp);
@@ -645,7 +666,7 @@
     if (fp =3D=3D NULL)
 	return;
=20
-    krb5_format_time(context, t, str, sizeof(str), TRUE);=20
+    krb5_format_time(context, t, str, sizeof(str), TRUE);
     fprintf(fp, "Status for slaves, last updated: %s\n\n", str);
=20
     fprintf(fp, "Master version: %lu\n\n", (unsigned long)current_version);
@@ -669,7 +690,7 @@
 	krb5_address addr;
 	krb5_error_code ret;
 	rtbl_add_column_entry(tbl, SLAVE_NAME, slaves->name);
-	ret =3D krb5_sockaddr2address (context,=20
+	ret =3D krb5_sockaddr2address (context,
 				     (struct sockaddr*)&slaves->addr, &addr);
 	if(ret =3D=3D 0) {
 	    krb5_print_address(&addr, str, sizeof(str), NULL);
@@ -677,7 +698,7 @@
 	    rtbl_add_column_entry(tbl, SLAVE_ADDRESS, str);
 	} else
 	    rtbl_add_column_entry(tbl, SLAVE_ADDRESS, "<unknown>");
-=09
+
 	snprintf(str, sizeof(str), "%u", (unsigned)slaves->version);
 	rtbl_add_column_entry(tbl, SLAVE_VERSION, str);
=20
@@ -686,7 +707,7 @@
 	else
 	    rtbl_add_column_entry(tbl, SLAVE_STATUS, "Up");
=20
-	ret =3D krb5_format_time(context, slaves->seen, str, sizeof(str), TRUE);=20
+	ret =3D krb5_format_time(context, slaves->seen, str, sizeof(str), TRUE);
 	rtbl_add_column_entry(tbl, SLAVE_SEEN, str);
=20
 	slaves =3D slaves->next;
@@ -699,35 +720,40 @@
 }
=20
=20
+static char sHDB[] =3D "HDB:";
 static char *realm;
 static int version_flag;
 static int help_flag;
-static char *keytab_str =3D "HDB:";
+static char *keytab_str =3D sHDB;
 static char *database;
 static char *config_file;
 static char *port_str;
+#ifdef SUPPORT_DETACH
 static int detach_from_console =3D 0;
+#endif
=20
 static struct getargs args[] =3D {
-    { "config-file", 'c', arg_string, &config_file },
-    { "realm", 'r', arg_string, &realm },
+    { "config-file", 'c', arg_string, &config_file, NULL, NULL },
+    { "realm", 'r', arg_string, &realm, NULL, NULL },
     { "keytab", 'k', arg_string, &keytab_str,
       "keytab to get authentication from", "kspec" },
     { "database", 'd', arg_string, &database, "database", "file"},
-    { "slave-stats-file", 0, arg_string, &slave_stats_file,=20
+    { "slave-stats-file", 0, arg_string, rk_UNCONST(&slave_stats_file),
       "file for slave status information", "file"},
-    { "time-missing", 0, arg_string, &slave_time_missing,=20
+    { "time-missing", 0, arg_string, rk_UNCONST(&slave_time_missing),
       "time before slave is polled for presence", "time"},
-    { "time-gone", 0, arg_string, &slave_time_gone,
+    { "time-gone", 0, arg_string, rk_UNCONST(&slave_time_gone),
       "time of inactivity after which a slave is considered gone", "time"},
     { "port", 0, arg_string, &port_str,
       "port ipropd will listen to", "port"},
-    { "detach", 0, arg_flag, &detach_from_console,=20
-      "detach from console" },
-    { "hostname", 0, arg_string, &master_hostname,=20
+#ifdef SUPPORT_DETACH
+    { "detach", 0, arg_flag, &detach_from_console,
+      "detach from console", NULL },
+#endif
+    { "hostname", 0, arg_string, rk_UNCONST(&master_hostname),
       "hostname of master (if not same as hostname)", "hostname" },
-    { "version", 0, arg_flag, &version_flag },
-    { "help", 0, arg_flag, &help_flag }
+    { "version", 0, arg_flag, &version_flag, NULL, NULL },
+    { "help", 0, arg_flag, &help_flag, NULL, NULL }
 };
 static int num_args =3D sizeof(args) / sizeof(args[0]);
=20
@@ -739,16 +765,16 @@
     void *kadm_handle;
     kadm5_server_context *server_context;
     kadm5_config_params conf;
-    int signal_fd, listen_fd;
+    krb5_socket_t signal_fd, listen_fd;
     int log_fd;
     slave *slaves =3D NULL;
     uint32_t current_version =3D 0, old_version =3D 0;
     krb5_keytab keytab;
     int optidx;
     char **files;
-   =20
+
     optidx =3D krb5_program_setup(&context, argc, argv, args, num_args, NU=
LL);
-   =20
+
     if(help_flag)
 	krb5_std_usage(0, args, num_args);
     if(version_flag) {
@@ -780,8 +806,10 @@
     if (time_before_missing < 0)
 	krb5_errx (context, 1, "couldn't parse time: %s", slave_time_missing);
=20
+#ifdef SUPPORT_DETACH
     if (detach_from_console)
 	daemon(0, 0);
+#endif
     pidfile (NULL);
     krb5_openlog (context, "ipropd-master", &log_facility);
     krb5_set_warn_dest(context, log_facility);
@@ -793,7 +821,7 @@
     ret =3D krb5_kt_resolve(context, keytab_str, &keytab);
     if(ret)
 	krb5_err(context, 1, ret, "krb5_kt_resolve: %s", keytab_str);
-   =20
+
     memset(&conf, 0, sizeof(conf));
     if(realm) {
 	conf.mask |=3D KADM5_CONFIG_REALM;
@@ -803,7 +831,7 @@
 				    KADM5_ADMIN_SERVICE,
 				    NULL,
 				    KADM5_ADMIN_SERVICE,
-				    &conf, 0, 0,=20
+				    &conf, 0, 0,
 				    &kadm_handle);
     if (ret)
 	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");
@@ -820,7 +848,7 @@
=20
     kadm5_log_get_version_fd (log_fd, &current_version);
=20
-    krb5_warnx(context, "ipropd-master started at version: %lu",=20
+    krb5_warnx(context, "ipropd-master started at version: %lu",
 	       (unsigned long)current_version);
=20
     while(exit_flag =3D=3D 0){
@@ -830,8 +858,10 @@
 	struct timeval to =3D {30, 0};
 	uint32_t vers;
=20
+#ifndef NO_LIMIT_FD_SETSIZE
 	if (signal_fd >=3D FD_SETSIZE || listen_fd >=3D FD_SETSIZE)
 	    krb5_errx (context, 1, "fd too large");
+#endif
=20
 	FD_ZERO(&readset);
 	FD_SET(signal_fd, &readset);
@@ -860,7 +890,7 @@
 	    kadm5_log_get_version_fd (log_fd, &current_version);
=20
 	    if (current_version > old_version) {
-		krb5_warnx(context,=20
+		krb5_warnx(context,
 			   "Missed a signal, updating slaves %lu to %lu",
 			   (unsigned long)old_version,
 			   (unsigned long)current_version);
@@ -873,7 +903,11 @@
 	}
=20
 	if (ret && FD_ISSET(signal_fd, &readset)) {
+#ifndef NO_UNIX_SOCKETS
 	    struct sockaddr_un peer_addr;
+#else
+	    struct sockaddr_storage peer_addr;
+#endif
 	    socklen_t peer_len =3D sizeof(peer_addr);
=20
 	    if(recvfrom(signal_fd, (void *)&vers, sizeof(vers), 0,
@@ -886,14 +920,17 @@
 	    old_version =3D current_version;
 	    kadm5_log_get_version_fd (log_fd, &current_version);
 	    if (current_version > old_version) {
-		krb5_warnx(context,=20
+		krb5_warnx(context,
 			   "Got a signal, updating slaves %lu to %lu",
 			   (unsigned long)old_version,
 			   (unsigned long)current_version);
-		for (p =3D slaves; p !=3D NULL; p =3D p->next)
+		for (p =3D slaves; p !=3D NULL; p =3D p->next) {
+		    if (p->flags & SLAVE_F_DEAD)
+			continue;
 		    send_diffs (context, p, log_fd, database, current_version);
+		}
 	    } else {
-		krb5_warnx(context,=20
+		krb5_warnx(context,
 			   "Got a signal, but no update in log version %lu",
 			   (unsigned long)current_version);
 	    }
@@ -909,10 +946,8 @@
 		    slave_dead(context, p);
 	    } else if (slave_gone_p (p))
 		slave_dead(context, p);
-	    else if (slave_missing_p (p)) {
-		krb5_warnx(context, "slave %s missing, sending AYT", p->name);
+	    else if (slave_missing_p (p))
 		send_are_you_there (context, p);
-	    }
 	}
=20
 	if (ret && FD_ISSET(listen_fd, &readset)) {
@@ -923,13 +958,15 @@
 	write_stats(context, slaves, current_version);
     }
=20
-    if(exit_flag =3D=3D SIGXCPU)
+    if(exit_flag =3D=3D SIGINT || exit_flag =3D=3D SIGTERM)
+	krb5_warnx(context, "%s terminated", getprogname());
+#ifdef SIGXCPU
+    else if(exit_flag =3D=3D SIGXCPU)
 	krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
-    else if(exit_flag =3D=3D SIGINT || exit_flag =3D=3D SIGTERM)
-	krb5_warnx(context, "%s terminated", getprogname());
+#endif
     else
-	krb5_warnx(context, "%s unexpected exit reason: %d",=20
-		   getprogname(), exit_flag);
+	krb5_warnx(context, "%s unexpected exit reason: %ld",
+		   getprogname(), (long)exit_flag);
=20
     write_master_down(context);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/ipropd_s=
lave.c
--- a/head/crypto/heimdal/lib/kadm5/ipropd_slave.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/kadm5/ipropd_slave.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,42 +1,45 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "iprop.h"
=20
-RCSID("$Id: ipropd_slave.c 22211 2007-12-07 19:27:27Z lha $");
+RCSID("$Id$");
+
+static const char *config_name =3D "ipropd-slave";
=20
 static krb5_log_facility *log_facility;
-static char *server_time_lost =3D "5 min";
+static char five_min[] =3D "5 min";
+static char *server_time_lost =3D five_min;
 static int time_before_lost;
 const char *slave_str =3D NULL;
=20
@@ -44,39 +47,53 @@
 connect_to_master (krb5_context context, const char *master,
 		   const char *port_str)
 {
-    int fd;
-    struct sockaddr_in addr;
-    struct hostent *he;
+    char port[NI_MAXSERV];
+    struct addrinfo *ai, *a;
+    struct addrinfo hints;
+    int error;
+    int s =3D -1;
=20
-    fd =3D socket (AF_INET, SOCK_STREAM, 0);
-    if (fd < 0)
-	krb5_err (context, 1, errno, "socket AF_INET");
-    memset (&addr, 0, sizeof(addr));
-    addr.sin_family =3D AF_INET;
-    if (port_str) {
-	addr.sin_port =3D krb5_getportbyname (context,
-					    port_str, "tcp",=20
-					    0);
-	if (addr.sin_port =3D=3D 0) {
-	    char *ptr;
-	    long port;
-	   =20
-	    port =3D strtol (port_str, &ptr, 10);
-	    if (port =3D=3D 0 && ptr =3D=3D port_str)
-		krb5_errx (context, 1, "bad port `%s'", port_str);
-	    addr.sin_port =3D htons(port);
+    memset (&hints, 0, sizeof(hints));
+    hints.ai_socktype =3D SOCK_STREAM;
+
+    if (port_str =3D=3D NULL) {
+	snprintf(port, sizeof(port), "%u", IPROP_PORT);
+	port_str =3D port;
+    }
+
+    error =3D getaddrinfo (master, port_str, &hints, &ai);
+    if (error) {
+	krb5_warnx(context, "Failed to get address of to %s: %s",
+		   master, gai_strerror(error));
+	return -1;
+    }
+
+    for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
+	char node[NI_MAXHOST];
+	error =3D getnameinfo(a->ai_addr, a->ai_addrlen,
+			    node, sizeof(node), NULL, 0, NI_NUMERICHOST);
+	if (error)
+	    strlcpy(node, "[unknown-addr]", sizeof(node));
+
+	s =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
+	if (s < 0)
+	    continue;
+	if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
+	    krb5_warn(context, errno, "connection failed to %s[%s]",
+		      master, node);
+	    close (s);
+	    continue;
 	}
-    } else {
-	addr.sin_port =3D krb5_getportbyname (context, IPROP_SERVICE,=20
-					    "tcp", IPROP_PORT);
+	krb5_warnx(context, "connection successful "
+		   "to master: %s[%s]", master, node);
+	break;
     }
-    he =3D roken_gethostbyname (master);
-    if (he =3D=3D NULL)
-	krb5_errx (context, 1, "gethostbyname: %s", hstrerror(h_errno));
-    memcpy (&addr.sin_addr, he->h_addr, sizeof(addr.sin_addr));
-    if(connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
-	krb5_err (context, 1, errno, "connect");
-    return fd;
+    freeaddrinfo (ai);
+
+    if (a =3D=3D NULL)
+	return -1;
+
+    return s;
 }
=20
 static void
@@ -90,7 +107,7 @@
     krb5_creds creds;
     char *server;
     char keytab_buf[256];
-   =20
+
     if (keytab_str =3D=3D NULL) {
 	ret =3D krb5_kt_default_name (context, keytab_buf, sizeof(keytab_buf));
 	if (ret)
@@ -101,7 +118,7 @@
     ret =3D krb5_kt_resolve(context, keytab_str, &keytab);
     if(ret)
 	krb5_err(context, 1, ret, "%s", keytab_str);
-   =20
+
=20
     ret =3D krb5_sname_to_principal (context, slave_str, IPROP_NAME,
 				   KRB5_NT_SRV_HST, &client);
@@ -119,21 +136,24 @@
     free (server);
     krb5_get_init_creds_opt_free(context, init_opts);
     if(ret) krb5_err(context, 1, ret, "krb5_get_init_creds");
-   =20
+
     ret =3D krb5_kt_close(context, keytab);
     if(ret) krb5_err(context, 1, ret, "krb5_kt_close");
-   =20
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, cache);
-    if(ret) krb5_err(context, 1, ret, "krb5_cc_gen_new");
+
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, cache);
+    if(ret) krb5_err(context, 1, ret, "krb5_cc_new_unique");
=20
     ret =3D krb5_cc_initialize(context, *cache, client);
     if(ret) krb5_err(context, 1, ret, "krb5_cc_initialize");
=20
     ret =3D krb5_cc_store_cred(context, *cache, &creds);
     if(ret) krb5_err(context, 1, ret, "krb5_cc_store_cred");
+
+    krb5_free_cred_contents(context, &creds);
+    krb5_free_principal(context, client);
 }
=20
-static void
+static krb5_error_code
 ihave (krb5_context context, krb5_auth_context auth_context,
        int fd, uint32_t version)
 {
@@ -148,10 +168,11 @@
     krb5_storage_free (sp);
     data.length =3D 8;
     data.data   =3D buf;
-   =20
+
     ret =3D krb5_write_priv_message(context, auth_context, &fd, &data);
     if (ret)
-	krb5_err (context, 1, ret, "krb5_write_priv_message");
+	krb5_warn (context, ret, "krb5_write_message");
+    return ret;
 }
=20
 static void
@@ -178,9 +199,9 @@
 	krb5_ret_int32 (sp, &tmp);
 	op =3D tmp;
 	krb5_ret_int32 (sp, &len);
-	if (vers <=3D server_context->log_context.version)
+	if ((uint32_t)vers <=3D server_context->log_context.version)
 	    krb5_storage_seek(sp, len + 8, SEEK_CUR);
-    } while(vers <=3D server_context->log_context.version);
+    } while((uint32_t)vers <=3D server_context->log_context.version);
=20
     /*
      * Read up rest of the entires into the memory...
@@ -226,8 +247,8 @@
 	if (ret) krb5_errx(context, 1, "entry %ld: too short", (long)vers);
 	if (len < 0)
 	    krb5_errx(context, 1, "log is corrupted, "
-			"negative length of entry version %ld: %ld",
-			(long)vers, (long)len);
+		      "negative length of entry version %ld: %ld",
+		      (long)vers, (long)len);
 	cur =3D krb5_storage_seek(sp, 0, SEEK_CUR);
=20
 	krb5_warnx (context, "replaying entry %d", (int)vers);
@@ -235,22 +256,22 @@
 	ret =3D kadm5_log_replay (server_context,
 				op, vers, len, sp);
 	if (ret) {
-	    char *s =3D krb5_get_error_message(server_context->context, ret);
+	    const char *s =3D krb5_get_error_message(server_context->context, ret=
);
 	    krb5_warnx (context,
-		       "kadm5_log_replay: %ld. Lost entry entry, "
-		       "Database out of sync ?: %s (%d)",
+			"kadm5_log_replay: %ld. Lost entry entry, "
+			"Database out of sync ?: %s (%d)",
 			(long)vers, s ? s : "unknown error", ret);
-	    krb5_xfree(s);
+	    krb5_free_error_message(context, s);
 	}
=20
 	{
-	    /*=20
+	    /*
 	     * Make sure the krb5_log_replay does the right thing wrt
 	     * reading out data from the sp.
 	     */
 	    cur2 =3D krb5_storage_seek(sp, 0, SEEK_CUR);
 	    if (cur + len !=3D cur2)
-		krb5_errx(context, 1,=20
+		krb5_errx(context, 1,
 			  "kadm5_log_reply version: %ld didn't read the whole entry",
 			  (long)vers);
 	}
@@ -318,20 +339,20 @@
 	krb5_err (context, 1, ret, "krb5_write_priv_message");
 }
=20
-static void
+static krb5_error_code
 receive_everything (krb5_context context, int fd,
 		    kadm5_server_context *server_context,
 		    krb5_auth_context auth_context)
 {
     int ret;
     krb5_data data;
-    int32_t vno;
+    int32_t vno =3D 0;
     int32_t opcode;
     krb5_storage *sp;
=20
     char *dbname;
     HDB *mydb;
- =20
+
     krb5_warnx(context, "receive complete database");
=20
     asprintf(&dbname, "%s-NEW", server_context->db->hdb_name);
@@ -339,12 +360,12 @@
     if(ret)
 	krb5_err(context,1, ret, "hdb_create");
     free(dbname);
-=20
+
     ret =3D hdb_set_master_keyfile (context,
 				  mydb, server_context->config.stash_file);
     if(ret)
 	krb5_err(context,1, ret, "hdb_set_master_keyfile");
-=20
+
     /* I really want to use O_EXCL here, but given that I can't easily cle=
an
        up on error, I won't */
     ret =3D mydb->hdb_open(context, mydb, O_RDWR | O_CREAT | O_TRUNC, 0600=
);
@@ -355,8 +376,10 @@
     do {
 	ret =3D krb5_read_priv_message(context, auth_context, &fd, &data);
=20
-	if (ret)
-	    krb5_err (context, 1, ret, "krb5_read_priv_message");
+	if (ret) {
+	    krb5_warn (context, ret, "krb5_read_priv_message");
+	    goto cleanup;
+	}
=20
 	sp =3D krb5_storage_from_data (&data);
 	if (sp =3D=3D NULL)
@@ -408,12 +431,13 @@
     if (ret)
 	krb5_err (context, 1, ret, "kadm5_log_nop");
=20
-    krb5_data_free (&data);
-
     ret =3D mydb->hdb_rename (context, mydb, server_context->db->hdb_name);
     if (ret)
 	krb5_err (context, 1, ret, "db->rename");
=20
+ cleanup:
+    krb5_data_free (&data);
+
     ret =3D mydb->hdb_close (context, mydb);
     if (ret)
 	krb5_err (context, 1, ret, "db->close");
@@ -423,6 +447,7 @@
 	krb5_err (context, 1, ret, "db->destroy");
=20
     krb5_warnx(context, "receive complete database, version %ld", (long)vn=
o);
+    return ret;
 }
=20
 static char *config_file;
@@ -431,27 +456,38 @@
 static int help_flag;
 static char *keytab_str;
 static char *port_str;
+#ifdef SUPPORT_DETACH
 static int detach_from_console =3D 0;
+#endif
=20
 static struct getargs args[] =3D {
-    { "config-file", 'c', arg_string, &config_file },
-    { "realm", 'r', arg_string, &realm },
+    { "config-file", 'c', arg_string, &config_file, NULL, NULL },
+    { "realm", 'r', arg_string, &realm, NULL, NULL },
     { "keytab", 'k', arg_string, &keytab_str,
       "keytab to get authentication from", "kspec" },
     { "time-lost", 0, arg_string, &server_time_lost,
       "time before server is considered lost", "time" },
     { "port", 0, arg_string, &port_str,
       "port ipropd-slave will connect to", "port"},
-    { "detach", 0, arg_flag, &detach_from_console,=20
-      "detach from console" },
-    { "hostname", 0, arg_string, &slave_str,=20
+#ifdef SUPPORT_DETACH
+    { "detach", 0, arg_flag, &detach_from_console,
+      "detach from console", NULL },
+#endif
+    { "hostname", 0, arg_string, rk_UNCONST(&slave_str),
       "hostname of slave (if not same as hostname)", "hostname" },
-    { "version", 0, arg_flag, &version_flag },
-    { "help", 0, arg_flag, &help_flag }
+    { "version", 0, arg_flag, &version_flag, NULL, NULL },
+    { "help", 0, arg_flag, &help_flag, NULL, NULL }
 };
=20
 static int num_args =3D sizeof(args) / sizeof(args[0]);
=20
+static void
+usage(int status)
+{
+    arg_printusage(args, num_args, NULL, "master");
+    exit(status);
+}
+
 int
 main(int argc, char **argv)
 {
@@ -465,24 +501,36 @@
     krb5_ccache ccache;
     krb5_principal server;
     char **files;
-    int optidx;
+    int optidx =3D 0;
+    time_t reconnect_min;
+    time_t backoff;
+    time_t reconnect_max;
+    time_t reconnect;
+    time_t before =3D 0;
=20
     const char *master;
-   =20
-    optidx =3D krb5_program_setup(&context, argc, argv, args, num_args, NU=
LL);
-   =20
+
+    setprogname(argv[0]);
+
+    if(getarg(args, num_args, argc, argv, &optidx))
+	usage(1);
+
     if(help_flag)
-	krb5_std_usage(0, args, num_args);
+	usage(0);
     if(version_flag) {
 	print_version(NULL);
 	exit(0);
     }
=20
+    ret =3D krb5_init_context(&context);
+    if (ret)
+	errx (1, "krb5_init_context failed: %d", ret);
+
     setup_signal();
=20
     if (config_file =3D=3D NULL) {
-	asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context));
-	if (config_file =3D=3D NULL)
+	if (asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)) =3D=3D -1
+	    || config_file =3D=3D NULL)
 	    errx(1, "out of memory");
     }
=20
@@ -499,12 +547,14 @@
     argv +=3D optidx;
=20
     if (argc !=3D 1)
-	krb5_std_usage(1, args, num_args);
+	usage(1);
=20
     master =3D argv[0];
=20
+#ifdef SUPPORT_DETACH
     if (detach_from_console)
 	daemon(0, 0);
+#endif
     pidfile (NULL);
     krb5_openlog (context, "ipropd-slave", &log_facility);
     krb5_set_warn_dest(context, log_facility);
@@ -526,7 +576,7 @@
 					KADM5_ADMIN_SERVICE,
 					NULL,
 					KADM5_ADMIN_SERVICE,
-					&conf, 0, 0,=20
+					&conf, 0, 0,
 					&kadm_handle);
     if (ret)
 	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");
@@ -539,94 +589,160 @@
=20
     get_creds(context, keytab_str, &ccache, master);
=20
-    master_fd =3D connect_to_master (context, master, port_str);
-
     ret =3D krb5_sname_to_principal (context, master, IPROP_NAME,
 				   KRB5_NT_SRV_HST, &server);
     if (ret)
 	krb5_err (context, 1, ret, "krb5_sname_to_principal");
=20
     auth_context =3D NULL;
-    ret =3D krb5_sendauth (context, &auth_context, &master_fd,
-			 IPROP_VERSION, NULL, server,
-			 AP_OPTS_MUTUAL_REQUIRED, NULL, NULL,
-			 ccache, NULL, NULL, NULL);
-    if (ret)
-	krb5_err (context, 1, ret, "krb5_sendauth");
+    master_fd =3D -1;
=20
-    krb5_warnx(context, "ipropd-slave started at version: %ld",
-	       (long)server_context->log_context.version);
+    krb5_appdefault_time(context, config_name, NULL, "reconnect-min",
+			 10, &reconnect_min);
+    krb5_appdefault_time(context, config_name, NULL, "reconnect-max",
+			 300, &reconnect_max);
+    krb5_appdefault_time(context, config_name, NULL, "reconnect-backoff",
+			 10, &backoff);
+    reconnect =3D reconnect_min;
=20
-    ihave (context, auth_context, master_fd,
-	   server_context->log_context.version);
+    while (!exit_flag) {
+	time_t now, elapsed;
+	int connected =3D FALSE;
=20
-    while (exit_flag =3D=3D 0) {
-	krb5_data out;
-	krb5_storage *sp;
-	int32_t tmp;
-	fd_set readset;
-	struct timeval to;
+	now =3D time(NULL);
+	elapsed =3D now - before;
=20
-	if (master_fd >=3D FD_SETSIZE)
-	    krb5_errx (context, 1, "fd too large");
+	if (elapsed < reconnect) {
+	    time_t left =3D reconnect - elapsed;
+	    krb5_warnx(context, "sleeping %d seconds before "
+		       "retrying to connect", (int)left);
+	    sleep(left);
+	}
+	before =3D now;
=20
-	FD_ZERO(&readset);
-	FD_SET(master_fd, &readset);
+	master_fd =3D connect_to_master (context, master, port_str);
+	if (master_fd < 0)
+	    goto retry;
=20
-	to.tv_sec =3D time_before_lost;
-	to.tv_usec =3D 0;
+	reconnect =3D reconnect_min;
=20
-	ret =3D select (master_fd + 1,
-		      &readset, NULL, NULL, &to);
-	if (ret < 0) {
-	    if (errno =3D=3D EINTR)
+	if (auth_context) {
+	    krb5_auth_con_free(context, auth_context);
+	    auth_context =3D NULL;
+	    krb5_cc_destroy(context, ccache);
+	    get_creds(context, keytab_str, &ccache, master);
+	}
+	ret =3D krb5_sendauth (context, &auth_context, &master_fd,
+			     IPROP_VERSION, NULL, server,
+			     AP_OPTS_MUTUAL_REQUIRED, NULL, NULL,
+			     ccache, NULL, NULL, NULL);
+	if (ret) {
+	    krb5_warn (context, ret, "krb5_sendauth");
+	    goto retry;
+	}
+
+	krb5_warnx(context, "ipropd-slave started at version: %ld",
+		   (long)server_context->log_context.version);
+
+	ret =3D ihave (context, auth_context, master_fd,
+		     server_context->log_context.version);
+	if (ret)
+	    goto retry;
+
+	connected =3D TRUE;
+
+	while (connected && !exit_flag) {
+	    krb5_data out;
+	    krb5_storage *sp;
+	    int32_t tmp;
+	    fd_set readset;
+	    struct timeval to;
+
+#ifndef NO_LIMIT_FD_SETSIZE
+	    if (master_fd >=3D FD_SETSIZE)
+		krb5_errx (context, 1, "fd too large");
+#endif
+
+	    FD_ZERO(&readset);
+	    FD_SET(master_fd, &readset);
+
+	    to.tv_sec =3D time_before_lost;
+	    to.tv_usec =3D 0;
+
+	    ret =3D select (master_fd + 1,
+			  &readset, NULL, NULL, &to);
+	    if (ret < 0) {
+		if (errno =3D=3D EINTR)
+		    continue;
+		else
+		    krb5_err (context, 1, errno, "select");
+	    }
+	    if (ret =3D=3D 0)
+		krb5_errx (context, 1, "server didn't send a message "
+			   "in %d seconds", time_before_lost);
+
+	    ret =3D krb5_read_priv_message(context, auth_context, &master_fd, &ou=
t);
+	    if (ret) {
+		krb5_warn (context, ret, "krb5_read_priv_message");
+		connected =3D FALSE;
 		continue;
-	    else
-		krb5_err (context, 1, errno, "select");
+	    }
+
+	    sp =3D krb5_storage_from_mem (out.data, out.length);
+	    krb5_ret_int32 (sp, &tmp);
+	    switch (tmp) {
+	    case FOR_YOU :
+		receive (context, sp, server_context);
+		ret =3D ihave (context, auth_context, master_fd,
+			     server_context->log_context.version);
+		if (ret)
+		    connected =3D FALSE;
+		break;
+	    case TELL_YOU_EVERYTHING :
+		ret =3D receive_everything (context, master_fd, server_context,
+					  auth_context);
+		if (ret)
+		    connected =3D FALSE;
+		break;
+	    case ARE_YOU_THERE :
+		send_im_here (context, master_fd, auth_context);
+		break;
+	    case NOW_YOU_HAVE :
+	    case I_HAVE :
+	    case ONE_PRINC :
+	    case I_AM_HERE :
+	    default :
+		krb5_warnx (context, "Ignoring command %d", tmp);
+		break;
+	    }
+	    krb5_storage_free (sp);
+	    krb5_data_free (&out);
+
 	}
-	if (ret =3D=3D 0)
-	    krb5_errx (context, 1, "server didn't send a message "
-		       "in %d seconds", time_before_lost);
+    retry:
+	if (connected =3D=3D FALSE)
+	    krb5_warnx (context, "disconnected for server");
+	if (exit_flag)
+	    krb5_warnx (context, "got an exit signal");
=20
-	ret =3D krb5_read_priv_message(context, auth_context, &master_fd, &out);
+	if (master_fd >=3D 0)
+	    close(master_fd);
=20
-	if (ret)
-	    krb5_err (context, 1, ret, "krb5_read_priv_message");
+	reconnect +=3D backoff;
+	if (reconnect > reconnect_max)
+	    reconnect =3D reconnect_max;
+    }
=20
-	sp =3D krb5_storage_from_mem (out.data, out.length);
-	krb5_ret_int32 (sp, &tmp);
-	switch (tmp) {
-	case FOR_YOU :
-	    receive (context, sp, server_context);
-	    ihave (context, auth_context, master_fd,
-		   server_context->log_context.version);
-	    break;
-	case TELL_YOU_EVERYTHING :
-	    receive_everything (context, master_fd, server_context,
-				auth_context);
-	    break;
-	case ARE_YOU_THERE :
-	    send_im_here (context, master_fd, auth_context);
-	    break;
-	case NOW_YOU_HAVE :
-	case I_HAVE :
-	case ONE_PRINC :
-	case I_AM_HERE :
-	default :
-	    krb5_warnx (context, "Ignoring command %d", tmp);
-	    break;
-	}
-	krb5_storage_free (sp);
-	krb5_data_free (&out);
-    }
-   =20
-    if(exit_flag =3D=3D SIGXCPU)
+    if (0);
+#ifndef NO_SIGXCPU
+    else if(exit_flag =3D=3D SIGXCPU)
 	krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
+#endif
     else if(exit_flag =3D=3D SIGINT || exit_flag =3D=3D SIGTERM)
 	krb5_warnx(context, "%s terminated", getprogname());
     else
-	krb5_warnx(context, "%s unexpected exit reason: %d",=20
-		   getprogname(), exit_flag);
+	krb5_warnx(context, "%s unexpected exit reason: %ld",
+		       getprogname(), (long)exit_flag);
=20
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/kadm5-pr=
ivate.h
--- a/head/crypto/heimdal/lib/kadm5/kadm5-private.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/kadm5/kadm5-private.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -45,19 +45,19 @@
 	kadm5_client_context */*context*/,
 	krb5_storage */*sp*/);
=20
-int
-_kadm5_cmp_keys (
-	Key */*keys1*/,
-	int /*len1*/,
-	Key */*keys2*/,
-	int /*len2*/);
-
 kadm5_ret_t
 _kadm5_connect (void */*handle*/);
=20
 kadm5_ret_t
 _kadm5_error_code (kadm5_ret_t /*code*/);
=20
+int
+_kadm5_exists_keys (
+	Key */*keys1*/,
+	int /*len1*/,
+	Key */*keys2*/,
+	int /*len2*/);
+
 void
 _kadm5_free_keys (
 	krb5_context /*context*/,
@@ -354,6 +354,12 @@
 kadm5_log_signal_socket (krb5_context /*context*/);
=20
 kadm5_ret_t
+kadm5_log_signal_socket_info (
+	krb5_context /*context*/,
+	int /*server_end*/,
+	struct addrinfo **/*ret_addrs*/);
+
+kadm5_ret_t
 kadm5_log_truncate (kadm5_server_context */*server_context*/);
=20
 kadm5_ret_t
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/kadm5-pw=
check.h
--- a/head/crypto/heimdal/lib/kadm5/kadm5-pwcheck.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/kadm5/kadm5-pwcheck.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: kadm5-pwcheck.h 15489 2005-06-17 06:45:52Z lha $ */
+/* $Id$ */
=20
 #ifndef KADM5_PWCHECK_H
 #define KADM5_PWCHECK_H 1
@@ -44,7 +44,7 @@
 							  krb5_principal,
 							  krb5_data*);
=20
-/*=20
+/*
  * The 4th argument, is a tuning parameter for the quality check
  * function, the lib/caller will providing it for the password quality
  * module.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/kadm5_er=
r.et
--- a/head/crypto/heimdal/lib/kadm5/kadm5_err.et	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/kadm5/kadm5_err.et	Tue Apr 17 11:51:51 2012 +=
0300
@@ -3,7 +3,7 @@
 #
 # This might look like a com_err file, but is not
 #
-id "$Id: kadm5_err.et 16683 2006-02-02 13:11:47Z lha $"
+id "$Id$"
=20
 error_table ovk kadm5
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/kadm5_lo=
cl.h
--- a/head/crypto/heimdal/lib/kadm5/kadm5_locl.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/kadm5/kadm5_locl.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,44 +1,43 @@
 /*
- * Copyright (c) 1997-2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: kadm5_locl.h 8579 2000-07-08 11:57:40Z assar $ */
+/* $Id$ */
=20
 #ifndef __KADM5_LOCL_H__
 #define __KADM5_LOCL_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+#include <roken.h>
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -78,7 +77,6 @@
 #include "kadm5_err.h"
 #include <hdb.h>
 #include <der.h>
-#include <roken.h>
 #include <parse_units.h>
 #include "private.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/kadm5_pw=
check.3
--- a/head/crypto/heimdal/lib/kadm5/kadm5_pwcheck.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/kadm5/kadm5_pwcheck.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: kadm5_pwcheck.3 15237 2005-05-25 13:16:27Z lha $
+.\" $Id$
 .\"
 .Dd February 29, 2004
 .Dt KADM5_PWCHECK 3
@@ -77,16 +77,17 @@
 .Pp
 There are two versions of the shared object API; the old version (0)
 is deprecated, but still supported.  The new version (1) supports
-multiple password quality checking modules in the same shared object.
+multiple password quality checking policies in the same shared object.
 See below for details.
 .Pp
-The password quality checker will run over all tests that are
-configured by the user.
+The password quality checker will run all policies that are
+configured by the user.  If any policy rejects the password, the password
+will be rejected.
 .Pp
-Module names are of the form
-.Ql vendor:test-name
-or, if the the test name is unique enough, just
-.Ql test-name .
+Policy names are of the form
+.Ql module-name:policy-name
+or, if the the policy name is unique enough, just
+.Ql policy-name .
 .Sh IMPLEMENTING A PASSWORD QUALITY CHECKING SHARED OBJECT
 (This refers to the version 1 API only.)
 .Pp
@@ -101,10 +102,16 @@
 .Ft name
 and
 .Ft vendor
-fields should be contain the obvious information and
+fields should contain the obvious information.
+.Ft name
+must match the
+.Ql module-name
+portion of the policy name (the part before the colon), if the policy name
+contains a colon, or the policy will not be run.
 .Ft version
 should be
 .Dv KADM5_PASSWD_VERSION_V1 .
+.Pp
 .Ft funcs
 contains an array of
 .Ft "struct kadm5_pw_policy_check_func"
@@ -113,8 +120,14 @@
 component is
 .Dv NULL .
 The
+.Ft name
+field of the array must match the
+.Ql policy-name
+portion of a policy name (the part after the colon, or the complete policy
+name if there is no colon) specified by the user or the policy will not be
+run.  The
 .Ft func
-Fields of the array elements are functions that are exported by the
+fields of the array elements are functions that are exported by the
 module to be called to check the password.  They get the following
 arguments:  the Kerberos context, principal, password, a tuning parameter,=
 and
 a pointer to a message buffer and its length.  The tuning parameter
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/keys.c
--- a/head/crypto/heimdal/lib/kadm5/keys.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/keys.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: keys.c 14297 2004-10-11 23:50:25Z lha $");
+RCSID("$Id$");
=20
 /*
  * free all the memory used by (len, keys)
@@ -64,37 +64,39 @@
 }
=20
 /*
- * return 0 iff `keys1, len1' and `keys2, len2' are identical
+ * return 1 if any key in `keys1, len1' exists in `keys2, len2'
  */
=20
 int
-_kadm5_cmp_keys(Key *keys1, int len1, Key *keys2, int len2)
+_kadm5_exists_keys(Key *keys1, int len1, Key *keys2, int len2)
 {
-    int i;
-
-    if (len1 !=3D len2)
-	return 1;
+    int i, j;
=20
     for (i =3D 0; i < len1; ++i) {
-	if ((keys1[i].salt !=3D NULL && keys2[i].salt =3D=3D NULL)
-	    || (keys1[i].salt =3D=3D NULL && keys2[i].salt !=3D NULL))
+	for (j =3D 0; j < len2; j++) {
+	    if ((keys1[i].salt !=3D NULL && keys2[j].salt =3D=3D NULL)
+		|| (keys1[i].salt =3D=3D NULL && keys2[j].salt !=3D NULL))
+		continue;
+
+	    if (keys1[i].salt !=3D NULL) {
+		if (keys1[i].salt->type !=3D keys2[j].salt->type)
+		    continue;
+		if (keys1[i].salt->salt.length !=3D keys2[j].salt->salt.length)
+		    continue;
+		if (memcmp (keys1[i].salt->salt.data, keys2[j].salt->salt.data,
+			    keys1[i].salt->salt.length) !=3D 0)
+		    continue;
+	    }
+	    if (keys1[i].key.keytype !=3D keys2[j].key.keytype)
+		continue;
+	    if (keys1[i].key.keyvalue.length !=3D keys2[j].key.keyvalue.length)
+		continue;
+	    if (memcmp (keys1[i].key.keyvalue.data, keys2[j].key.keyvalue.data,
+			keys1[i].key.keyvalue.length) !=3D 0)
+		continue;
+
 	    return 1;
-	if (keys1[i].salt !=3D NULL) {
-	    if (keys1[i].salt->type !=3D keys2[i].salt->type)
-		return 1;
-	    if (keys1[i].salt->salt.length !=3D keys2[i].salt->salt.length)
-		return 1;
-	    if (memcmp (keys1[i].salt->salt.data, keys2[i].salt->salt.data,
-			keys1[i].salt->salt.length) !=3D 0)
-		return 1;
 	}
-	if (keys1[i].key.keytype !=3D keys2[i].key.keytype)
-	    return 1;
-	if (keys1[i].key.keyvalue.length !=3D keys2[i].key.keyvalue.length)
-	    return 1;
-	if (memcmp (keys1[i].key.keyvalue.data, keys2[i].key.keyvalue.data,
-		    keys1[i].key.keyvalue.length) !=3D 0)
-	    return 1;
     }
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/log.c
--- a/head/crypto/heimdal/lib/kadm5/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
 #include "heim_threads.h"
=20
-RCSID("$Id: log.c 22211 2007-12-07 19:27:27Z lha $");
+RCSID("$Id$");
=20
 /*
  * A log record consists of:
@@ -99,13 +99,15 @@
 	return 0;
     fd =3D open (log_context->log_file, O_RDWR | O_CREAT, 0600);
     if (fd < 0) {
-	krb5_set_error_string(context->context, "kadm5_log_init: open %s",
+	ret =3D errno;
+	krb5_set_error_message(context->context, ret, "kadm5_log_init: open %s",
 			      log_context->log_file);
-	return errno;
+	return ret;
     }
     if (flock (fd, LOCK_EX) < 0) {
-	krb5_set_error_string(context->context, "kadm5_log_init: flock %s",
-			      log_context->log_file);
+	ret =3D errno;
+	krb5_set_error_message(context->context, ret, "kadm5_log_init: flock %s",
+			       log_context->log_file);
 	close (fd);
 	return errno;
     }
@@ -191,12 +193,12 @@
 {
     krb5_data data;
     size_t len;
-    int ret;
+    ssize_t ret;
=20
     krb5_storage_to_data(sp, &data);
     len =3D data.length;
     ret =3D write (log_context->log_fd, data.data, len);
-    if (ret !=3D len) {
+    if (ret < 0 || (size_t)ret !=3D len) {
 	krb5_data_free(&data);
 	return errno;
     }
@@ -204,15 +206,25 @@
 	krb5_data_free(&data);
 	return errno;
     }
+
     /*
      * Try to send a signal to any running `ipropd-master'
      */
+#ifndef NO_UNIX_SOCKETS
     sendto (log_context->socket_fd,
 	    (void *)&log_context->version,
 	    sizeof(log_context->version),
 	    0,
 	    (struct sockaddr *)&log_context->socket_name,
 	    sizeof(log_context->socket_name));
+#else
+    sendto (log_context->socket_fd,
+	    (void *)&log_context->version,
+	    sizeof(log_context->version),
+	    0,
+	    log_context->socket_info->ai_addr,
+	    log_context->socket_info->ai_addrlen);
+#endif
=20
     krb5_data_free(&data);
     return 0;
@@ -279,15 +291,15 @@
=20
     ret =3D krb5_data_alloc (&data, len);
     if (ret) {
-	krb5_set_error_string(context->context, "out of memory");
+	krb5_set_error_message(context->context, ret, "out of memory");
 	return ret;
     }
     krb5_storage_read (sp, data.data, len);
     ret =3D hdb_value2entry (context->context, &data, &ent.entry);
     krb5_data_free(&data);
     if (ret) {
-	krb5_set_error_string(context->context,=20
-			      "Unmarshaling hdb entry failed");
+	krb5_set_error_message(context->context, ret,
+			       "Unmarshaling hdb entry failed");
 	return ret;
     }
     ret =3D context->db->hdb_store(context->context, context->db, 0, &ent);
@@ -358,8 +370,8 @@
=20
     ret =3D krb5_ret_principal (sp, &principal);
     if (ret) {
-	krb5_set_error_string(context->context,  "Failed to read deleted "
-			      "principal from log version: %ld",  (long)ver);
+	krb5_set_error_message(context->context,  ret, "Failed to read deleted "
+			       "principal from log version: %ld",  (long)ver);
 	return ret;
     }
=20
@@ -456,8 +468,8 @@
     off =3D krb5_storage_seek(sp, 0, SEEK_CUR);
     ret =3D krb5_ret_principal (sp, &source);
     if (ret) {
-	krb5_set_error_string(context->context, "Failed to read renamed "
-			      "principal in log, version: %ld", (long)ver);
+	krb5_set_error_message(context->context, ret, "Failed to read renamed "
+			       "principal in log, version: %ld", (long)ver);
 	return ret;
     }
     princ_len =3D krb5_storage_seek(sp, 0, SEEK_CUR) - off;
@@ -474,7 +486,7 @@
 	krb5_free_principal (context->context, source);
 	return ret;
     }
-    ret =3D context->db->hdb_store (context->context, context->db,=20
+    ret =3D context->db->hdb_store (context->context, context->db,
 				  0, &target_ent);
     hdb_free_entry (context->context, &target_ent);
     if (ret) {
@@ -561,7 +573,7 @@
     len -=3D 4;
     ret =3D krb5_data_alloc (&value, len);
     if (ret) {
-	krb5_set_error_string(context->context, "out of memory");
+	krb5_set_error_message(context->context, ret, "out of memory");
 	return ret;
     }
     krb5_storage_read (sp, value.data, len);
@@ -571,9 +583,9 @@
 	return ret;
=20
     memset(&ent, 0, sizeof(ent));
-    ret =3D context->db->hdb_fetch(context->context, context->db,
-				 log_ent.entry.principal,
-				 HDB_F_DECRYPT|HDB_F_GET_ANY, &ent);
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db,
+				      log_ent.entry.principal,
+				      HDB_F_DECRYPT|HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
     if (ret)
 	goto out;
     if (mask & KADM5_PRINC_EXPIRE_TIME) {
@@ -583,8 +595,8 @@
 	    if (ent.entry.valid_end =3D=3D NULL) {
 		ent.entry.valid_end =3D malloc(sizeof(*ent.entry.valid_end));
 		if (ent.entry.valid_end =3D=3D NULL) {
-		    krb5_set_error_string(context->context, "out of memory");
 		    ret =3D ENOMEM;
+		    krb5_set_error_message(context->context, ret, "out of memory");
 		    goto out;
 		}
 	    }
@@ -598,8 +610,8 @@
 	    if (ent.entry.pw_end =3D=3D NULL) {
 		ent.entry.pw_end =3D malloc(sizeof(*ent.entry.pw_end));
 		if (ent.entry.pw_end =3D=3D NULL) {
-		    krb5_set_error_string(context->context, "out of memory");
 		    ret =3D ENOMEM;
+		    krb5_set_error_message(context->context, ret, "out of memory");
 		    goto out;
 		}
 	    }
@@ -619,8 +631,8 @@
 	    if (ent.entry.max_life =3D=3D NULL) {
 		ent.entry.max_life =3D malloc (sizeof(*ent.entry.max_life));
 		if (ent.entry.max_life =3D=3D NULL) {
-		    krb5_set_error_string(context->context, "out of memory");
 		    ret =3D ENOMEM;
+		    krb5_set_error_message(context->context, ret, "out of memory");
 		    goto out;
 		}
 	    }
@@ -631,15 +643,15 @@
 	if (ent.entry.modified_by =3D=3D NULL) {
 	    ent.entry.modified_by =3D malloc(sizeof(*ent.entry.modified_by));
 	    if (ent.entry.modified_by =3D=3D NULL) {
-		krb5_set_error_string(context->context, "out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context->context, ret, "out of memory");
 		goto out;
 	    }
 	} else
 	    free_Event(ent.entry.modified_by);
 	ret =3D copy_Event(log_ent.entry.modified_by, ent.entry.modified_by);
 	if (ret) {
-	    krb5_set_error_string(context->context, "out of memory");
+	    krb5_set_error_message(context->context, ret, "out of memory");
 	    goto out;
 	}
     }
@@ -665,8 +677,8 @@
 	    if (ent.entry.max_renew =3D=3D NULL) {
 		ent.entry.max_renew =3D malloc (sizeof(*ent.entry.max_renew));
 		if (ent.entry.max_renew =3D=3D NULL) {
-		    krb5_set_error_string(context->context, "out of memory");
 		    ret =3D ENOMEM;
+		    krb5_set_error_message(context->context, ret, "out of memory");
 		    goto out;
 		}
 	    }
@@ -684,7 +696,7 @@
     }
     if (mask & KADM5_KEY_DATA) {
 	size_t num;
-	int i;
+	size_t i;
=20
 	for (i =3D 0; i < ent.entry.keys.len; ++i)
 	    free_Key(&ent.entry.keys.val[i]);
@@ -695,14 +707,14 @@
 	ent.entry.keys.len =3D num;
 	ent.entry.keys.val =3D malloc(len * sizeof(*ent.entry.keys.val));
 	if (ent.entry.keys.val =3D=3D NULL) {
-	    krb5_set_error_string(context->context, "out of memory");
+	    krb5_set_error_message(context->context, ENOMEM, "out of memory");
 	    return ENOMEM;
 	}
 	for (i =3D 0; i < ent.entry.keys.len; ++i) {
 	    ret =3D copy_Key(&log_ent.entry.keys.val[i],
 			   &ent.entry.keys.val[i]);
 	    if (ret) {
-		krb5_set_error_string(context->context, "out of memory");
+		krb5_set_error_message(context->context, ret, "out of memory");
 		goto out;
 	    }
 	}
@@ -717,7 +729,7 @@
 	ret =3D copy_HDB_extensions(log_ent.entry.extensions,
 				  ent.entry.extensions);
 	if (ret) {
-	    krb5_set_error_string(context->context, "out of memory");
+	    krb5_set_error_message(context->context, ret, "out of memory");
 	    free(ent.entry.extensions);
 	    ent.entry.extensions =3D es;
 	    goto out;
@@ -727,7 +739,7 @@
 	    free(es);
 	}
     }
-    ret =3D context->db->hdb_store(context->context, context->db,=20
+    ret =3D context->db->hdb_store(context->context, context->db,
 				 HDB_F_REPLACE, &ent);
  out:
     hdb_free_entry (context->context, &ent);
@@ -834,9 +846,9 @@
=20
 /*
  * Return previous log entry.
- *=20
- * The pointer in `sp=B4 is assumed to be at the top of the entry before
- * previous entry. On success, the `sp=B4 pointer is set to data portion
+ *
+ * The pointer in `sp=C2=B4 is assumed to be at the top of the entry before
+ * previous entry. On success, the `sp=C2=B4 pointer is set to data portion
  * of previous entry. In case of error, it's not changed at all.
  */
=20
@@ -860,16 +872,22 @@
 	goto end_of_storage;
     *len =3D tmp;
     ret =3D krb5_ret_int32 (sp, &tmp);
+    if (ret)
+	goto end_of_storage;
     *ver =3D tmp;
     off =3D 24 + *len;
     krb5_storage_seek(sp, -off, SEEK_CUR);
     ret =3D krb5_ret_int32 (sp, &tmp);
     if (ret)
 	goto end_of_storage;
-    if (tmp !=3D *ver) {
+    if ((uint32_t)tmp !=3D *ver) {
 	krb5_storage_seek(sp, oldoff, SEEK_SET);
-	krb5_set_error_string(context, "kadm5_log_previous: log entry "
-			      "have consistency failure, version number wrong");
+	krb5_set_error_message(context, KADM5_BAD_DB,
+			       "kadm5_log_previous: log entry "
+			       "have consistency failure, version number wrong "
+			       "(tmp %lu ver %lu)",
+			       (unsigned long)tmp,
+			       (unsigned long)*ver);
 	return KADM5_BAD_DB;
     }
     ret =3D krb5_ret_int32 (sp, &tmp);
@@ -877,22 +895,25 @@
 	goto end_of_storage;
     *timestamp =3D tmp;
     ret =3D krb5_ret_int32 (sp, &tmp);
+    if (ret)
+	goto end_of_storage;
     *op =3D tmp;
     ret =3D krb5_ret_int32 (sp, &tmp);
     if (ret)
 	goto end_of_storage;
-    if (tmp !=3D *len) {
+    if ((uint32_t)tmp !=3D *len) {
 	krb5_storage_seek(sp, oldoff, SEEK_SET);
-	krb5_set_error_string(context, "kadm5_log_previous: log entry "
-			      "have consistency failure, length wrong");
+	krb5_set_error_message(context, KADM5_BAD_DB,
+			       "kadm5_log_previous: log entry "
+			       "have consistency failure, length wrong");
 	return KADM5_BAD_DB;
     }
     return 0;
=20
  end_of_storage:
     krb5_storage_seek(sp, oldoff, SEEK_SET);
-    krb5_set_error_string(context, "kadm5_log_previous: end of storage "
-			  "reached before end");
+    krb5_set_error_message(context, ret, "kadm5_log_previous: end of stora=
ge "
+			   "reached before end");
     return ret;
 }
=20
@@ -919,8 +940,8 @@
     case kadm_nop :
 	return kadm5_log_replay_nop (context, ver, len, sp);
     default :
-	krb5_set_error_string(context->context,=20
-			      "Unsupported replay op %d", (int)op);
+	krb5_set_error_message(context->context, KADM5_FAILURE,
+			       "Unsupported replay op %d", (int)op);
 	return KADM5_FAILURE;
     }
 }
@@ -962,6 +983,8 @@
=20
 }
=20
+#ifndef NO_UNIX_SOCKETS
+
 static char *default_signal =3D NULL;
 static HEIMDAL_MUTEX signal_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
=20
@@ -980,3 +1003,55 @@
 					  "signal_socket",
 					  NULL);
 }
+
+#else  /* NO_UNIX_SOCKETS */
+
+#define SIGNAL_SOCKET_HOST "127.0.0.1"
+#define SIGNAL_SOCKET_PORT "12701"
+
+kadm5_ret_t
+kadm5_log_signal_socket_info(krb5_context context,
+			     int server_end,
+			     struct addrinfo **ret_addrs)
+{
+    struct addrinfo hints;
+    struct addrinfo *addrs =3D NULL;
+    kadm5_ret_t ret =3D KADM5_FAILURE;
+    int wsret;
+
+    memset(&hints, 0, sizeof(hints));
+
+    hints.ai_flags =3D AI_NUMERICHOST;
+    if (server_end)
+	hints.ai_flags |=3D AI_PASSIVE;
+    hints.ai_family =3D AF_INET;
+    hints.ai_socktype =3D SOCK_STREAM;
+    hints.ai_protocol =3D IPPROTO_TCP;
+
+    wsret =3D getaddrinfo(SIGNAL_SOCKET_HOST,
+			SIGNAL_SOCKET_PORT,
+			&hints, &addrs);
+
+    if (wsret !=3D 0) {
+	krb5_set_error_message(context, KADM5_FAILURE,
+			       "%s", gai_strerror(wsret));
+	goto done;
+    }
+
+    if (addrs =3D=3D NULL) {
+	krb5_set_error_message(context, KADM5_FAILURE,
+			       "getaddrinfo() failed to return address list");
+	goto done;
+    }
+
+    *ret_addrs =3D addrs;
+    addrs =3D NULL;
+    ret =3D 0;
+
+ done:
+    if (addrs)
+	freeaddrinfo(addrs);
+    return ret;
+}
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/marshall=
.c
--- a/head/crypto/heimdal/lib/kadm5/marshall.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/marshall.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: marshall.c 21745 2007-07-31 16:11:25Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_store_key_data(krb5_storage *sp,
@@ -189,7 +189,7 @@
=20
     if (mask & KADM5_PRINCIPAL)
 	krb5_ret_principal(sp, &princ->principal);
-   =20
+
     if (mask & KADM5_PRINC_EXPIRE_TIME) {
 	krb5_ret_int32(sp, &tmp);
 	princ->princ_expire_time =3D tmp;
@@ -260,7 +260,7 @@
 	krb5_ret_int32(sp, &tmp);
 	princ->n_key_data =3D tmp;
 	princ->key_data =3D malloc(princ->n_key_data * sizeof(*princ->key_data));
-	if (princ->key_data =3D=3D NULL)
+	if (princ->key_data =3D=3D NULL && princ->n_key_data !=3D 0)
 	    return ENOMEM;
 	for(i =3D 0; i < princ->n_key_data; i++)
 	    kadm5_ret_key_data(sp, &princ->key_data[i]);
@@ -301,14 +301,14 @@
 }
=20
 kadm5_ret_t
-_kadm5_marshal_params(krb5_context context,=20
-		      kadm5_config_params *params,=20
+_kadm5_marshal_params(krb5_context context,
+		      kadm5_config_params *params,
 		      krb5_data *out)
 {
     krb5_storage *sp =3D krb5_storage_emem();
-   =20
+
     krb5_store_int32(sp, params->mask & (KADM5_CONFIG_REALM));
-=09
+
     if(params->mask & KADM5_CONFIG_REALM)
 	krb5_store_string(sp, params->realm);
     krb5_storage_to_data(sp, out);
@@ -322,15 +322,23 @@
 			krb5_data *in,
 			kadm5_config_params *params)
 {
-    krb5_storage *sp =3D krb5_storage_from_data(in);
+    krb5_error_code ret;
+    krb5_storage *sp;
     int32_t mask;
-   =20
-    krb5_ret_int32(sp, &mask);
+
+    sp =3D krb5_storage_from_data(in);
+    if (sp =3D=3D NULL)
+	return ENOMEM;
+
+    ret =3D krb5_ret_int32(sp, &mask);
+    if (ret)
+	goto out;
     params->mask =3D mask;
-=09
+
     if(params->mask & KADM5_CONFIG_REALM)
-	krb5_ret_string(sp, &params->realm);
+	ret =3D krb5_ret_string(sp, &params->realm);
+ out:
     krb5_storage_free(sp);
=20
-    return 0;
+    return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/modify_c=
.c
--- a/head/crypto/heimdal/lib/kadm5/modify_c.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/modify_c.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,43 +1,43 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: modify_c.c 17445 2006-05-05 10:37:46Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_c_modify_principal(void *server_handle,
-			 kadm5_principal_ent_t princ,=20
+			 kadm5_principal_ent_t princ,
 			 uint32_t mask)
 {
     kadm5_client_context *context =3D server_handle;
@@ -53,7 +53,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_modify);
@@ -68,12 +68,12 @@
 	return ret;
     sp =3D krb5_storage_from_data (&reply);
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
     krb5_ret_int32(sp, &tmp);
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     krb5_storage_free(sp);
     krb5_data_free (&reply);
     return tmp;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/modify_s=
.c
--- a/head/crypto/heimdal/lib/kadm5/modify_s.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/modify_s.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,43 +1,43 @@
 /*
- * Copyright (c) 1997-2001, 2003, 2005-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2001, 2003, 2005-2006 Kungliga Tekniska H=C3=B6gskol=
an
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: modify_s.c 20610 2007-05-08 07:12:37Z lha $");
+RCSID("$Id$");
=20
 static kadm5_ret_t
 modify_principal(void *server_handle,
-		 kadm5_principal_ent_t princ,=20
+		 kadm5_principal_ent_t princ,
 		 uint32_t mask,
 		 uint32_t forbidden_mask)
 {
@@ -48,13 +48,13 @@
 	return KADM5_BAD_MASK;
     if((mask & KADM5_POLICY) && strcmp(princ->policy, "default"))
 	return KADM5_UNK_POLICY;
-   =20
+
     memset(&ent, 0, sizeof(ent));
     ret =3D context->db->hdb_open(context->context, context->db, O_RDWR, 0=
);
     if(ret)
 	return ret;
-    ret =3D context->db->hdb_fetch(context->context, context->db,=20
-				 princ->principal, HDB_F_GET_ANY, &ent);
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db,
+				      princ->principal, HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
     if(ret)
 	goto out;
     ret =3D _kadm5_setup_entry(context, &ent, mask, princ, mask, NULL, 0);
@@ -68,7 +68,7 @@
     if (ret)
 	goto out2;
=20
-    ret =3D context->db->hdb_store(context->context, context->db,=20
+    ret =3D context->db->hdb_store(context->context, context->db,
 			     HDB_F_REPLACE, &ent);
     if (ret)
 	goto out2;
@@ -87,12 +87,12 @@
=20
 kadm5_ret_t
 kadm5_s_modify_principal(void *server_handle,
-			 kadm5_principal_ent_t princ,=20
+			 kadm5_principal_ent_t princ,
 			 uint32_t mask)
 {
-    return modify_principal(server_handle, princ, mask,=20
-			    KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME=20
-			    | KADM5_MOD_NAME | KADM5_MKVNO=20
+    return modify_principal(server_handle, princ, mask,
+			    KADM5_LAST_PWD_CHANGE | KADM5_MOD_TIME
+			    | KADM5_MOD_NAME | KADM5_MKVNO
 			    | KADM5_AUX_ATTRIBUTES | KADM5_LAST_SUCCESS
 			    | KADM5_LAST_FAILED);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/password=
_quality.c
--- a/head/crypto/heimdal/lib/kadm5/password_quality.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/password_quality.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2000, 2003-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2000, 2003-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
 #include "kadm5-pwcheck.h"
=20
-RCSID("$Id: password_quality.c 17595 2006-05-30 21:51:55Z lha $");
-
 #ifdef HAVE_SYS_WAIT_H
 #include <sys/wait.h>
 #endif
@@ -95,8 +93,8 @@
 	"1234567890",
 	"!@#$%^&*()/?<>,.{[]}\\|'~`\" "
     };
-    int i, counter =3D 0, req_classes;
-    size_t len;
+    int counter =3D 0, req_classes;
+    size_t i, len;
     char *pw;
=20
     req_classes =3D krb5_config_get_int_default(context, NULL, 3,
@@ -148,7 +146,7 @@
     char reply[1024];
     FILE *in =3D NULL, *out =3D NULL, *error =3D NULL;
=20
-    if (memchr(pwd->data, pwd->length, '\n') !=3D NULL) {
+    if (memchr(pwd->data, '\n', pwd->length) !=3D NULL) {
 	snprintf(message, length, "password contains newline, "
 		 "not valid for external test");
 	return 1;
@@ -170,7 +168,7 @@
 	return 1;
     }
=20
-    child =3D pipe_execv(&in, &out, &error, program, p, NULL);
+    child =3D pipe_execv(&in, &out, &error, program, program, p, NULL);
     if (child < 0) {
 	snprintf(message, length, "external password quality "
 		 "program failed to execute for principal %s", p);
@@ -182,7 +180,7 @@
 	    "new-password: %.*s\n"
 	    "end\n",
 	    p, (int)pwd->length, (char *)pwd->data);
-   =20
+
     fclose(in);
=20
     if (fgets(reply, sizeof(reply), out) =3D=3D NULL) {
@@ -199,7 +197,7 @@
=20
 	fclose(out);
 	fclose(error);
-	waitpid(child, &status, 0);
+	wait_for_process(child);
 	return 1;
     }
     reply[strcspn(reply, "\n")] =3D '\0';
@@ -207,12 +205,9 @@
     fclose(out);
     fclose(error);
=20
-    if (waitpid(child, &status, 0) < 0) {
-	snprintf(message, length, "external program failed: %s", reply);
-	free(p);
-	return 1;
-    }
-    if (!WIFEXITED(status) || WEXITSTATUS(status) !=3D 0) {
+    status =3D wait_for_process(child);
+
+    if (SE_IS_ERROR(status) || SE_PROCSTATUS(status) !=3D 0) {
 	snprintf(message, length, "external program failed: %s", reply);
 	free(p);
 	return 1;
@@ -230,18 +225,18 @@
 }
=20
=20
-static kadm5_passwd_quality_check_func_v0 passwd_quality_check =3D=20
+static kadm5_passwd_quality_check_func_v0 passwd_quality_check =3D
 	min_length_passwd_quality_v0;
=20
 struct kadm5_pw_policy_check_func builtin_funcs[] =3D {
     { "minimum-length", min_length_passwd_quality },
     { "character-class", char_class_passwd_quality },
     { "external-check", external_passwd_quality },
-    { NULL }
+    { NULL, NULL }
 };
 struct kadm5_pw_policy_verifier builtin_verifier =3D {
-    "builtin",=20
-    KADM5_PASSWD_VERSION_V1,=20
+    "builtin",
+    KADM5_PASSWD_VERSION_V1,
     "Heimdal builtin",
     builtin_funcs
 };
@@ -269,17 +264,17 @@
     const char *tmp;
=20
     if(check_library =3D=3D NULL) {
-	tmp =3D krb5_config_get_string(context, NULL,=20
-				     "password_quality",=20
-				     "check_library",=20
+	tmp =3D krb5_config_get_string(context, NULL,
+				     "password_quality",
+				     "check_library",
 				     NULL);
 	if(tmp !=3D NULL)
 	    check_library =3D tmp;
     }
     if(check_function =3D=3D NULL) {
-	tmp =3D krb5_config_get_string(context, NULL,=20
-				     "password_quality",=20
-				     "check_function",=20
+	tmp =3D krb5_config_get_string(context, NULL,
+				     "password_quality",
+				     "check_function",
 				     NULL);
 	if(tmp !=3D NULL)
 	    check_function =3D tmp;
@@ -294,7 +289,7 @@
 	krb5_warnx(context, "failed to open `%s'", check_library);
 	return;
     }
-    version =3D dlsym(handle, "version");
+    version =3D (int *) dlsym(handle, "version");
     if(version =3D=3D NULL) {
 	krb5_warnx(context,
 		   "didn't find `version' symbol in `%s'", check_library);
@@ -310,8 +305,8 @@
     }
     sym =3D dlsym(handle, check_function);
     if(sym =3D=3D NULL) {
-	krb5_warnx(context,=20
-		   "didn't find `%s' symbol in `%s'",=20
+	krb5_warnx(context,
+		   "didn't find `%s' symbol in `%s'",
 		   check_function, check_library);
 	dlclose(handle);
 	return;
@@ -334,7 +329,7 @@
 	krb5_warnx(context, "failed to open `%s'", check_library);
 	return ENOENT;
     }
-    v =3D dlsym(handle, "kadm5_password_verifier");
+    v =3D (struct kadm5_pw_policy_verifier *) dlsym(handle, "kadm5_passwor=
d_verifier");
     if(v =3D=3D NULL) {
 	krb5_warnx(context,
 		   "didn't find `kadm5_password_verifier' symbol "
@@ -385,21 +380,23 @@
 	krb5_error_code ret;
 	char **tmp;
=20
-	tmp =3D krb5_config_get_strings(context, NULL,=20
-				      "password_quality",=20
-				      "policy_libraries",=20
+	tmp =3D krb5_config_get_strings(context, NULL,
+				      "password_quality",
+				      "policy_libraries",
 				      NULL);
-	if(tmp =3D=3D NULL)
+	if(tmp =3D=3D NULL || *tmp =3D=3D NULL)
 	    return 0;
=20
-	while(tmp) {
+	while (*tmp) {
 	    ret =3D add_verifier(context, *tmp);
 	    if (ret)
 		return ret;
 	    tmp++;
 	}
+	return 0;
+    } else {
+	return add_verifier(context, check_library);
     }
-    return add_verifier(context, check_library);
 #else
     return 0;
 #endif /* HAVE_DLOPEN */
@@ -419,10 +416,12 @@
=20
     p =3D strchr(name, ':');
     if (p) {
+	size_t len =3D p - name + 1;
 	func =3D p + 1;
-	module =3D strndup(name, p - name);
+	module =3D malloc(len);
 	if (module =3D=3D NULL)
 	    return NULL;
+	strlcpy(module, name, len);
     } else
 	func =3D name;
=20
@@ -431,7 +430,7 @@
 	if (module && strcmp(module, verifiers[i]->name) !=3D 0)
 	    continue;
 	for (f =3D verifiers[i]->funcs; f->name ; f++)
-	    if (strcmp(name, f->name) =3D=3D 0) {
+	    if (strcmp(func, f->name) =3D=3D 0) {
 		if (module)
 		    free(module);
 		return f;
@@ -466,13 +465,14 @@
      * Check if we should use the old version of policy function.
      */
=20
-    v =3D krb5_config_get_strings(context, NULL,=20
-				"password_quality",=20
-				"policies",=20
+    v =3D krb5_config_get_strings(context, NULL,
+				"password_quality",
+				"policies",
 				NULL);
     if (v =3D=3D NULL) {
 	msg =3D (*passwd_quality_check) (context, principal, pwd_data);
-	krb5_set_error_string(context, "password policy failed: %s", msg);
+	if (msg)
+	    krb5_set_error_message(context, 0, "password policy failed: %s", msg);
 	return msg;
     }
=20
@@ -483,16 +483,16 @@
 	proc =3D find_func(context, *vp);
 	if (proc =3D=3D NULL) {
 	    msg =3D "failed to find password verifier function";
-	    krb5_set_error_string(context, "Failed to find password policy "
-				  "function: %s", *vp);
+	    krb5_set_error_message(context, 0, "Failed to find password policy "
+				   "function: %s", *vp);
 	    break;
 	}
 	ret =3D (proc->func)(context, principal, pwd_data, NULL,
 			   error_msg, sizeof(error_msg));
 	if (ret) {
-	    krb5_set_error_string(context, "Password policy "
-				  "%s failed with %s",=20
-				  proc->name, error_msg);
+	    krb5_set_error_message(context, 0, "Password policy "
+				   "%s failed with %s",
+				   proc->name, error_msg);
 	    msg =3D error_msg;
 	    break;
 	}
@@ -504,9 +504,9 @@
     if (msg =3D=3D NULL && passwd_quality_check !=3D min_length_passwd_qua=
lity_v0) {
 	msg =3D (*passwd_quality_check) (context, principal, pwd_data);
 	if (msg)
-	    krb5_set_error_string(context, "(old) password policy "
-				  "failed with %s", msg);
-	   =20
+	    krb5_set_error_message(context, 0, "(old) password policy "
+				   "failed with %s", msg);
+
     }
     return msg;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/private.h
--- a/head/crypto/heimdal/lib/kadm5/private.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/private.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,54 +1,54 @@
 /*
- * Copyright (c) 1997-2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: private.h 22211 2007-12-07 19:27:27Z lha $ */
+/* $Id$ */
=20
 #ifndef __kadm5_privatex_h__
 #define __kadm5_privatex_h__
=20
 struct kadm_func {
     kadm5_ret_t (*chpass_principal) (void *, krb5_principal, const char*);
-    kadm5_ret_t (*create_principal) (void*, kadm5_principal_ent_t,=20
+    kadm5_ret_t (*create_principal) (void*, kadm5_principal_ent_t,
 				     uint32_t, const char*);
     kadm5_ret_t (*delete_principal) (void*, krb5_principal);
     kadm5_ret_t (*destroy) (void*);
     kadm5_ret_t (*flush) (void*);
-    kadm5_ret_t (*get_principal) (void*, krb5_principal,=20
+    kadm5_ret_t (*get_principal) (void*, krb5_principal,
 				  kadm5_principal_ent_t, uint32_t);
     kadm5_ret_t (*get_principals) (void*, const char*, char***, int*);
     kadm5_ret_t (*get_privs) (void*, uint32_t*);
     kadm5_ret_t (*modify_principal) (void*, kadm5_principal_ent_t, uint32_=
t);
-    kadm5_ret_t (*randkey_principal) (void*, krb5_principal,=20
+    kadm5_ret_t (*randkey_principal) (void*, krb5_principal,
 				      krb5_keyblock**, int*);
     kadm5_ret_t (*rename_principal) (void*, krb5_principal, krb5_principal=
);
     kadm5_ret_t (*chpass_principal_with_key) (void *, krb5_principal,
@@ -74,8 +74,12 @@
     char *log_file;
     int log_fd;
     uint32_t version;
+#ifndef NO_UNIX_SOCKETS
     struct sockaddr_un socket_name;
-    int socket_fd;
+#else
+    struct addrinfo *socket_info;
+#endif
+    krb5_socket_t socket_fd;
 } kadm5_log_context;
=20
 typedef struct kadm5_server_context {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/privs_c.c
--- a/head/crypto/heimdal/lib/kadm5/privs_c.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/privs_c.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: privs_c.c 17512 2006-05-08 13:43:17Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_c_get_privs(void *server_handle, uint32_t *privs)
@@ -53,7 +53,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_get_privs);
@@ -66,12 +66,12 @@
 	return ret;
     sp =3D krb5_storage_from_data(&reply);
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
     krb5_ret_int32(sp, &tmp);
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     ret =3D tmp;
     if(ret =3D=3D 0){
 	krb5_ret_uint32(sp, privs);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/privs_s.c
--- a/head/crypto/heimdal/lib/kadm5/privs_s.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/privs_s.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: privs_s.c 17445 2006-05-05 10:37:46Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_s_get_privs(void *server_handle, uint32_t *privs)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/randkey_=
c.c
--- a/head/crypto/heimdal/lib/kadm5/randkey_c.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/randkey_c.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,44 +1,44 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: randkey_c.c 16662 2006-01-25 12:53:09Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
-kadm5_c_randkey_principal(void *server_handle,=20
+kadm5_c_randkey_principal(void *server_handle,
 			  krb5_principal princ,
-			  krb5_keyblock **new_keys,=20
+			  krb5_keyblock **new_keys,
 			  int *n_keys)
 {
     kadm5_client_context *context =3D server_handle;
@@ -54,7 +54,7 @@
=20
     sp =3D krb5_storage_from_mem(buf, sizeof(buf));
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     krb5_store_int32(sp, kadm_randkey);
@@ -68,11 +68,11 @@
 	return ret;
     sp =3D krb5_storage_from_data(&reply);
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free (&reply);
 	return ENOMEM;
     }
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     krb5_ret_int32(sp, &tmp);
     ret =3D tmp;
     if(ret =3D=3D 0){
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/randkey_=
s.c
--- a/head/crypto/heimdal/lib/kadm5/randkey_s.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/randkey_s.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997-2001, 2003-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2001, 2003-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: randkey_s.c 20611 2007-05-08 07:13:07Z lha $");
+RCSID("$Id$");
=20
 /*
  * Set the keys of `princ' to random values, returning the random keys
@@ -41,9 +41,9 @@
  */
=20
 kadm5_ret_t
-kadm5_s_randkey_principal(void *server_handle,=20
+kadm5_s_randkey_principal(void *server_handle,
 			  krb5_principal princ,
-			  krb5_keyblock **new_keys,=20
+			  krb5_keyblock **new_keys,
 			  int *n_keys)
 {
     kadm5_server_context *context =3D server_handle;
@@ -54,8 +54,8 @@
     ret =3D context->db->hdb_open(context->context, context->db, O_RDWR, 0=
);
     if(ret)
 	return ret;
-    ret =3D context->db->hdb_fetch(context->context, context->db, princ,=20
-				 HDB_F_GET_ANY, &ent);
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db, pri=
nc,
+				      HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
     if(ret)
 	goto out;
=20
@@ -78,7 +78,7 @@
     if (ret)
 	goto out2;
=20
-    ret =3D context->db->hdb_store(context->context, context->db,=20
+    ret =3D context->db->hdb_store(context->context, context->db,
 				 HDB_F_REPLACE, &ent);
     if (ret)
 	goto out2;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/rename_c=
.c
--- a/head/crypto/heimdal/lib/kadm5/rename_c.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/rename_c.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: rename_c.c 8655 2000-07-11 16:00:19Z joda $");
+RCSID("$Id$");
=20
 kadm5_ret_t
-kadm5_c_rename_principal(void *server_handle,=20
+kadm5_c_rename_principal(void *server_handle,
 			 krb5_principal source,
 			 krb5_principal target)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/rename_s=
.c
--- a/head/crypto/heimdal/lib/kadm5/rename_s.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/rename_s.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 1997 - 2001, 2003, 2005 - 2005 Kungliga Tekniska H=F6gsko=
lan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2003, 2005 - 2005 Kungliga Tekniska H=C3=B6g=
skolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: rename_s.c 21745 2007-07-31 16:11:25Z lha $");
+RCSID("$Id$");
=20
 kadm5_ret_t
-kadm5_s_rename_principal(void *server_handle,=20
+kadm5_s_rename_principal(void *server_handle,
 			 krb5_principal source,
 			 krb5_principal target)
 {
@@ -51,8 +51,8 @@
     ret =3D context->db->hdb_open(context->context, context->db, O_RDWR, 0=
);
     if(ret)
 	return ret;
-    ret =3D context->db->hdb_fetch(context->context, context->db,=20
-				 source, HDB_F_GET_ANY, &ent);
+    ret =3D context->db->hdb_fetch_kvno(context->context, context->db,
+				      source, HDB_F_GET_ANY|HDB_F_ADMIN_DATA, 0, &ent);
     if(ret){
 	context->db->hdb_close(context->context, context->db);
 	goto out;
@@ -62,15 +62,16 @@
 	goto out2;
     {
 	/* fix salt */
-	int i;
+	size_t i;
 	Salt salt;
 	krb5_salt salt2;
+	memset(&salt, 0, sizeof(salt));
 	krb5_get_pw_salt(context->context, source, &salt2);
 	salt.type =3D hdb_pw_salt;
 	salt.salt =3D salt2.saltvalue;
 	for(i =3D 0; i < ent.entry.keys.len; i++){
 	    if(ent.entry.keys.val[i].salt =3D=3D NULL){
-		ent.entry.keys.val[i].salt =3D=20
+		ent.entry.keys.val[i].salt =3D
 		    malloc(sizeof(*ent.entry.keys.val[i].salt));
 		if(ent.entry.keys.val[i].salt =3D=3D NULL)
 		    return ENOMEM;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/sample_p=
asswd_check.c
--- a/head/crypto/heimdal/lib/kadm5/sample_passwd_check.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/sample_passwd_check.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -30,7 +30,7 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
=20
-/* $Id: sample_passwd_check.c 21901 2007-08-10 06:05:35Z lha $ */
+/* $Id$ */
=20
 #include <string.h>
 #include <stdlib.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/send_rec=
v.c
--- a/head/crypto/heimdal/lib/kadm5/send_recv.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kadm5/send_recv.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,41 +1,41 @@
 /*
- * Copyright (c) 1997-2003, 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2003, 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: send_recv.c 17311 2006-04-27 11:10:07Z lha $");
+RCSID("$Id$");
=20
-kadm5_ret_t=20
+kadm5_ret_t
 _kadm5_client_send(kadm5_client_context *context, krb5_storage *sp)
 {
     krb5_data msg, out;
@@ -48,27 +48,27 @@
     len =3D krb5_storage_seek(sp, 0, SEEK_CUR);
     ret =3D krb5_data_alloc(&msg, len);
     if (ret) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ret;
     }
     krb5_storage_seek(sp, 0, SEEK_SET);
     krb5_storage_read(sp, msg.data, msg.length);
-   =20
+
     ret =3D krb5_mk_priv(context->context, context->ac, &msg, &out, NULL);
     krb5_data_free(&msg);
     if(ret)
 	return ret;
-   =20
+
     sock =3D krb5_storage_from_fd(context->sock);
     if(sock =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	krb5_data_free(&out);
 	return ENOMEM;
     }
-   =20
+
     ret =3D krb5_store_data(sock, out);
     if (ret)
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
     krb5_storage_free(sock);
     krb5_data_free(&out);
     return ret;
@@ -83,12 +83,12 @@
=20
     sock =3D krb5_storage_from_fd(context->sock);
     if(sock =3D=3D NULL) {
-	krb5_clear_error_string(context->context);
+	krb5_clear_error_message(context->context);
 	return ENOMEM;
     }
     ret =3D krb5_ret_data(sock, &data);
     krb5_storage_free(sock);
-    krb5_clear_error_string(context->context);
+    krb5_clear_error_message(context->context);
     if(ret =3D=3D KRB5_CC_END)
 	return KADM5_RPC_ERROR;
     else if(ret)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/server_g=
lue.c
--- a/head/crypto/heimdal/lib/kadm5/server_glue.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/kadm5/server_glue.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: server_glue.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 kadm5_init_with_password(const char *client_name,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/set_keys=
.c
--- a/head/crypto/heimdal/lib/kadm5/set_keys.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kadm5/set_keys.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: set_keys.c 15888 2005-08-11 13:40:35Z lha $");
+RCSID("$Id$");
=20
 /*
  * Set the keys of `ent' to the string-to-key of `password'
@@ -41,7 +41,7 @@
=20
 kadm5_ret_t
 _kadm5_set_keys(kadm5_server_context *context,
-		hdb_entry *ent,=20
+		hdb_entry *ent,
 		const char *password)
 {
     Key *keys;
@@ -49,7 +49,7 @@
     kadm5_ret_t ret;
=20
     ret =3D hdb_generate_key_set_password(context->context,
-					ent->principal,=20
+					ent->principal,
 					password, &keys, &num_keys);
     if (ret)
 	return ret;
@@ -60,7 +60,7 @@
=20
     hdb_entry_set_pw_change_time(context->context, ent, 0);
=20
-    if (krb5_config_get_bool_default(context->context, NULL, FALSE,=20
+    if (krb5_config_get_bool_default(context->context, NULL, FALSE,
 				     "kadmin", "save-password", NULL))
     {
 	ret =3D hdb_entry_set_password(context->context, context->db,
@@ -78,8 +78,8 @@
=20
 kadm5_ret_t
 _kadm5_set_keys2(kadm5_server_context *context,
-		 hdb_entry *ent,=20
-		 int16_t n_key_data,=20
+		 hdb_entry *ent,
+		 int16_t n_key_data,
 		 krb5_key_data *key_data)
 {
     krb5_error_code ret;
@@ -89,7 +89,7 @@
=20
     len  =3D n_key_data;
     keys =3D malloc (len * sizeof(*keys));
-    if (keys =3D=3D NULL)
+    if (keys =3D=3D NULL && len !=3D 0)
 	return ENOMEM;
=20
     _kadm5_init_keys (keys, len);
@@ -105,14 +105,14 @@
 	if(key_data[i].key_data_ver =3D=3D 2) {
 	    Salt *salt;
=20
-	    salt =3D malloc(sizeof(*salt));
+	    salt =3D calloc(1, sizeof(*salt));
 	    if(salt =3D=3D NULL) {
 		ret =3D ENOMEM;
 		goto out;
 	    }
 	    keys[i].salt =3D salt;
 	    salt->type =3D key_data[i].key_data_type[1];
-	    krb5_data_copy(&salt->salt,=20
+	    krb5_data_copy(&salt->salt,
 			   key_data[i].key_data_contents[1],
 			   key_data[i].key_data_length[1]);
 	} else
@@ -148,7 +148,7 @@
=20
     len  =3D n_keys;
     keys =3D malloc (len * sizeof(*keys));
-    if (keys =3D=3D NULL)
+    if (keys =3D=3D NULL && len !=3D 0)
 	return ENOMEM;
=20
     _kadm5_init_keys (keys, len);
@@ -201,8 +201,8 @@
 {
    krb5_keyblock *kblock =3D NULL;
    kadm5_ret_t ret =3D 0;
-   int i, des_keyblock;
-   size_t num_keys;
+   int des_keyblock;
+   size_t i, num_keys;
    Key *keys;
=20
    ret =3D hdb_generate_key_set(context->context, ent->principal,
@@ -221,7 +221,7 @@
    des_keyblock =3D -1;
    for (i =3D 0; i < num_keys; i++) {
=20
-	/*=20
+	/*
 	 * To make sure all des keys are the the same we generate only
 	 * the first one and then copy key to all other des keys.
 	 */
@@ -259,7 +259,7 @@
 	_kadm5_free_keys (context->context, num_keys, keys);
 	return ret;
    }
-  =20
+
    _kadm5_free_keys (context->context, ent->keys.len, ent->keys.val);
    ent->keys.val =3D keys;
    ent->keys.len =3D num_keys;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/set_modi=
fier.c
--- a/head/crypto/heimdal/lib/kadm5/set_modifier.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/kadm5/set_modifier.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
=20
-RCSID("$Id: set_modifier.c 7464 1999-12-02 17:05:13Z joda $");
+RCSID("$Id$");
=20
 kadm5_ret_t
 _kadm5_set_modifier(kadm5_server_context *context,
@@ -47,7 +47,7 @@
     } else
 	free_Event(ent->modified_by);
     ent->modified_by->time =3D time(NULL);
-    ret =3D krb5_copy_principal(context->context, context->caller,=20
+    ret =3D krb5_copy_principal(context->context, context->caller,
 			      &ent->modified_by->principal);
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kadm5/test_pw_=
quality.c
--- a/head/crypto/heimdal/lib/kadm5/test_pw_quality.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/kadm5/test_pw_quality.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 2003, 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003, 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kadm5_locl.h"
 #include <getarg.h>
=20
-RCSID("$Id: test_pw_quality.c 15105 2005-05-09 19:13:29Z lha $");
+RCSID("$Id$");
=20
 static int version_flag;
 static int help_flag;
@@ -59,7 +59,7 @@
     krb5_data pw_data;
=20
     krb5_program_setup(&context, argc, argv, args, num_args, NULL);
-   =20
+
     if(help_flag)
 	krb5_std_usage(0, args, num_args);
     if(version_flag) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/ChangeLog
--- a/head/crypto/heimdal/lib/kafs/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kafs/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,30 +1,40 @@
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-07-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* common.c: Try afs/cell at REALM before afs at REALM since that is what
+	OpenAFS folks have been saying is best pratices for some time
+	now. Patch from Derrick Brashear.
+
+2008-04-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+	* afssys.c: Avoid using entry points depending on _IOWR if there
+	is no _IOWR (on cygwin).
+
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: New library version.
=20
-2007-05-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs.h: Add VIOCSETTOK2
 =09
-2006-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: unbreak previous
 =09
 	* Makefile.am: split dist and nodist sources
 =09
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: add more files
 =09
-2006-05-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-05-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
-	* kafs.3: Spelling, from Bj=F6rn Sandell.
+	* kafs.3: Spelling, from Bj=C3=B6rn Sandell.
 =09
-2006-04-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afssys.c: use afs_ioctlnum, From Tomas Olsson <tol at it.su.se>
 =09
-2006-04-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afssys.c: Try harder to get the pioctl to work via the /proc or
 	/dev interface, OpenAFS choose to reuse the same ioctl number,
@@ -34,13 +44,13 @@
 	* afskrb5.c (afslog_uid_int): use the simpler
 	krb5_principal_get_realm function.
 =09
-2005-12-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-12-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Remove dependency on config.h, breaks IRIX build,
 	could depend on libkafs_la_OBJECTS, but that is just asking for
 	trubble.
 =09
-2005-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afssys.c (k_hasafs_recheck): new function, allow rechecking if
 	AFS client have started now, internaly it resets the internal
@@ -48,7 +58,7 @@
 	with calling k_hasaf() is that is plays around with signals, and
 	that cases problem for some systems/applications.
 =09
-2005-10-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs_locl.h: Maybe include <sys/sysctl.h>.
=20
@@ -57,22 +67,22 @@
 	version.  Every after 10.0 (darwin 8.0) uses the /dev/ version of
 	the pioctl.
 =09
-2005-10-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-10-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afssys.c: Support the new MacOS X 10.4 ioctl interface that is a
 	device node. Patched from Tomas Olson <tol at it.su.se>.
 =09
-2005-08-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afskrb5.c: Default to use 2b tokens.
=20
-2005-06-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* common.c: rename index to idx
=20
 	* afssys.c (k_afs_cell_of_file): unconst path
 =09
-2005-06-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* use struct kafs_data everywhere, don't mix with the typedef
 	kafs_data
@@ -82,19 +92,19 @@
 	* afssys.c: Don't building map_syscall_name_to_number where its
 	not used.
=20
-2005-02-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: bump version to 4:1:4
=20
-2005-02-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs.h: de-__P
 =09
-2004-12-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-12-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afskrb5.c: s/KEYTYPE_DES/ETYPE_DES_CBC_CRC/
 =09
-2004-08-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-08-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afssysdefs.h: ifdef protect AFS_SYSCALL for DragonFly since they
 	still define __FreeBSD__ (and __FreeBSD_version), but claim that
@@ -102,14 +112,14 @@
 =09
 	* afssysdefs.h: dragonflybsd uses 339 just like freebsd5
 =09
-2004-06-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afssys.c: s/arla/nnpfs/
 =09
 	* afssys.c: support the linux /proc/fs/mumel/afs_ioctl afs
 	"syscall" interface
=20
-2004-01-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* common.c: search paths for AFS configuration files for the
 	OpenAFS MacOS X, fix comment
@@ -117,42 +127,42 @@
 	* kafs.h: search paths for AFS configuration files for the OpenAFS
 	MacOS X
=20
-2003-12-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* common.c: add _PATH_ARLA_OPENBSD & c/o
 =09
 	* kafs.h: add _PATH_ARLA_OPENBSD & c/o
 =09
-2003-11-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* common.c: typo, Bruno Rohee <bruno at rohee.com>
 =09
-2003-11-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-11-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs.3: spelling, partly from jmc <jmc at prioris.mini.pw.edu.pl>
 =09
-2003-09-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afskrb5.c (krb5_afslog_uid_home): be even more friendly to the
 	user and fetch context and id ourself
 =09
-2003-09-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-09-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afskrb5.c (afslog_uid_int): just belive that realm hint the user
 	passed us
=20
-2003-07-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-07-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: always include v4 symbols
 =09
 	* afskrb.c: provide dummy krb_ function to there is no need to
 	bump major
=20
-2003-06-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-06-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afskrb5.c (v5_convert): rename one of the two c to cred4
 =09
-2003-04-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* common.c, kafs.h: drop the int argument (the error code) from
 	the logging function
@@ -162,12 +172,12 @@
 	* afskrb5.c (v5_convert): better match what other functions do
 	with values from krb5.conf, like case insensitivity
=20
-2003-04-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs.3: Change .Fd #include <header.h> to .In header.h
 	from Thomas Klausner <wiz at netbsd.org>
=20
-2003-04-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: (libkafs_la_LDFLAGS): update version
 =09
@@ -192,7 +202,7 @@
 	* kafs_locl.h (kafs_data): add name
 	(_kafs_foldup): internally export
=20
-2003-04-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs.3: tell that cell-name is uppercased
 =09
@@ -204,18 +214,18 @@
 	have updated their servers but not afs/cell at REALM. Add constant
 	KAFS_RXKAD_2B_KVNO.
=20
-2003-04-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-04-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs.3: s/kerberos/Kerberos/
 =09
-2003-03-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* kafs.3: spelling, from <jmc at prioris.mini.pw.edu.pl>
 =09
 	* kafs.3: document the kafs_settoken functions write about the
 	krb5_appdefault option for kerberos 5 afs tokens fix prototypes
 =09
-2003-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afskrb5.c (kafs_settoken5): change signature to include a
 	krb5_context, use v5_convert
@@ -254,7 +264,7 @@
 	internal structure struct kafs_token that carries around for rxkad
 	data that is independant of kerberos version
 =09
-2003-02-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* dlfcn.h: s/intialize/initialize, from
 	<jmc at prioris.mini.pw.edu.pl>
@@ -263,7 +273,7 @@
=20
 	* afssysdefs.h: fix FreeBSD section
=20
-2003-02-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-02-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* afssysdefs.h: use syscall 208 on openbsd (all version) use
 	syscall 339 on freebsd 5.0 and later, use 210 on 4.x and earlier
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/Makefile.=
am
--- a/head/crypto/heimdal/lib/kafs/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kafs/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,18 +1,9 @@
-# $Id: Makefile.am 21446 2007-07-10 12:45:36Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
 AM_CPPFLAGS +=3D $(AFS_EXTRA_DEFS) $(ROKEN_RENAME)
=20
-if KRB4
-DEPLIB_krb4 =3D $(LIB_krb4) $(LIB_hcrypto)
-krb4_am_workaround =3D $(INCLUDE_krb4)
-else
-DEPLIB_krb4  =3D
-krb4_am_workaround =3D=20
-endif # KRB4
-AM_CPPFLAGS +=3D $(krb4_am_workaround)
-
 if KRB5
 DEPLIB_krb5 =3D ../krb5/libkrb5.la=20
 krb5_am_workaround =3D $(INCLUDE_hcrypto) -I$(top_srcdir)/lib/krb5
@@ -33,11 +24,7 @@
 endif
=20
 if AIX_DYNAMIC_AFS
-if HAVE_DLOPEN
 AIX_SRC =3D=20
-else
-AIX_SRC =3D dlfcn.c
-endif
 AFS_EXTRA_LIBS =3D afslib.so
 AFS_EXTRA_DEFS =3D
 else
@@ -51,7 +38,7 @@
 AIX_SRC =3D
 endif # AIX
=20
-libkafs_la_LIBADD =3D $(DEPLIB_krb5) $(LIBADD_roken) $(DEPLIB_krb4)
+libkafs_la_LIBADD =3D $(DEPLIB_krb5) $(LIBADD_roken)
=20
 lib_LTLIBRARIES =3D libkafs.la
 libkafs_la_LDFLAGS =3D -version-info 5:1:5
@@ -64,7 +51,7 @@
 include_HEADERS =3D kafs.h
=20
 if KRB5
-afskrb5_c =3D afskrb5.c
+afskrb5_c =3D=20
 endif
=20
 if do_roken_rename
@@ -73,8 +60,7 @@
=20
 dist_libkafs_la_SOURCES =3D			\
 	afssys.c				\
-	afskrb.c				\
-	$(afskrb5_c)				\
+	afskrb5.c				\
 	common.c				\
 	$(AIX_SRC)				\
 	kafs_locl.h				\
@@ -83,9 +69,9 @@
=20
 nodist_libkafs_la_SOURCES =3D $(ROKEN_SRCS)
=20
-EXTRA_libkafs_la_SOURCES =3D afskrb.c afskrb5.c dlfcn.c afslib.c dlfcn.h
+EXTRA_libkafs_la_SOURCES =3D afskrb5.c afslib.c
=20
-EXTRA_DIST =3D README.dlfcn afsl.exp afslib.exp $(man_MANS)
+EXTRA_DIST =3D NTMakefile afsl.exp afslib.exp $(man_MANS)
=20
 man_MANS =3D kafs.3
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/Makefile.=
in
--- a/head/crypto/heimdal/lib/kafs/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kafs/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 21446 2007-07-10 12:45:36Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -46,7 +48,7 @@
 subdir =3D lib/kafs
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -61,7 +63,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -75,9 +77,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -85,48 +90,56 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(man3dir)" \
 	"$(DESTDIR)$(foodir)" "$(DESTDIR)$(includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
 @KRB5_TRUE at am__DEPENDENCIES_1 =3D ../krb5/libkrb5.la
 am__DEPENDENCIES_2 =3D
- at KRB4_TRUE@am__DEPENDENCIES_3 =3D $(am__DEPENDENCIES_2) \
- at KRB4_TRUE@	$(am__DEPENDENCIES_2)
-libkafs_la_DEPENDENCIES =3D $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2) \
-	$(am__DEPENDENCIES_3)
-am__dist_libkafs_la_SOURCES_DIST =3D afssys.c afskrb.c afskrb5.c \
-	common.c afslib.c dlfcn.c kafs_locl.h afssysdefs.h \
-	roken_rename.h
- at KRB5_TRUE@am__objects_1 =3D afskrb5.lo
- at AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE at am__objects_2 =3D afslib.lo
- at AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE@@HAVE_DLOPEN_FALSE at am__objects_2 =3D  \
- at AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE@@HAVE_DLOPEN_FALSE@	dlfcn.lo
-dist_libkafs_la_OBJECTS =3D afssys.lo afskrb.lo $(am__objects_1) \
-	common.lo $(am__objects_2)
- at do_roken_rename_TRUE@am__objects_3 =3D resolve.lo strtok_r.lo \
+libkafs_la_DEPENDENCIES =3D $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2)
+am__dist_libkafs_la_SOURCES_DIST =3D afssys.c afskrb5.c common.c \
+	afslib.c kafs_locl.h afssysdefs.h roken_rename.h
+ at AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE at am__objects_1 =3D afslib.lo
+dist_libkafs_la_OBJECTS =3D afssys.lo afskrb5.lo common.lo \
+	$(am__objects_1)
+ at do_roken_rename_TRUE@am__objects_2 =3D resolve.lo strtok_r.lo \
 @do_roken_rename_TRUE@	strlcpy.lo strsep.lo
-nodist_libkafs_la_OBJECTS =3D $(am__objects_3)
+nodist_libkafs_la_OBJECTS =3D $(am__objects_2)
 libkafs_la_OBJECTS =3D $(dist_libkafs_la_OBJECTS) \
 	$(nodist_libkafs_la_OBJECTS)
 libkafs_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libkafs_la_LDFLAGS) $(LDFLAGS) -o $@
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -142,9 +155,7 @@
 	$(am__dist_libkafs_la_SOURCES_DIST)
 man3dir =3D $(mandir)/man3
 MANS =3D $(man_MANS)
-fooDATA_INSTALL =3D $(INSTALL_DATA)
 DATA =3D $(foo_DATA)
-includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
 HEADERS =3D $(include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
@@ -153,49 +164,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -219,10 +239,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -239,6 +260,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -254,31 +277,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -293,10 +330,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -337,36 +376,36 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(AFS_EXTRA_DEFS) $(ROKEN_RENAME) $(krb4_am_workaround) \
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(AFS_EXTRA_DEFS) $(ROKEN_RENAME) \
 	$(krb5_am_workaround)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
- at KRB4_FALSE@DEPLIB_krb4 =3D=20
- at KRB4_TRUE@DEPLIB_krb4 =3D $(LIB_krb4) $(LIB_hcrypto)
- at KRB4_FALSE@krb4_am_workaround =3D=20
- at KRB4_TRUE@krb4_am_workaround =3D $(INCLUDE_krb4)
 @KRB5_FALSE at DEPLIB_krb5 =3D=20
 @KRB5_TRUE at DEPLIB_krb5 =3D ../krb5/libkrb5.la=20
 @KRB5_FALSE at krb5_am_workaround =3D=20
@@ -376,14 +415,13 @@
 @AIX4_FALSE@@AIX_TRUE at AFS_EXTRA_LD =3D -e _nostart
 @AIX4_TRUE@@AIX_TRUE at AFS_EXTRA_LD =3D -bnoentry
 @AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE at AIX_SRC =3D afslib.c
- at AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE@@HAVE_DLOPEN_FALSE at AIX_SRC =3D dlfcn.c
- at AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE@@HAVE_DLOPEN_TRUE at AIX_SRC =3D=20
+ at AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE at AIX_SRC =3D=20
 @AIX_FALSE at AIX_SRC =3D=20
 @AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE at AFS_EXTRA_LIBS =3D=20
 @AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE at AFS_EXTRA_LIBS =3D afslib.so
 @AIX_DYNAMIC_AFS_FALSE@@AIX_TRUE at AFS_EXTRA_DEFS =3D -DSTATIC_AFS
 @AIX_DYNAMIC_AFS_TRUE@@AIX_TRUE at AFS_EXTRA_DEFS =3D=20
-libkafs_la_LIBADD =3D $(DEPLIB_krb5) $(LIBADD_roken) $(DEPLIB_krb4)
+libkafs_la_LIBADD =3D $(DEPLIB_krb5) $(LIBADD_roken)
 lib_LTLIBRARIES =3D libkafs.la
 libkafs_la_LDFLAGS =3D -version-info 5:1:5
 foodir =3D $(libdir)
@@ -391,12 +429,11 @@
 # EXTRA_DATA =3D afslib.so
 CLEANFILES =3D $(AFS_EXTRA_LIBS) $(ROKEN_SRCS)
 include_HEADERS =3D kafs.h
- at KRB5_TRUE@afskrb5_c =3D afskrb5.c
+ at KRB5_TRUE@afskrb5_c =3D=20
 @do_roken_rename_TRUE at ROKEN_SRCS =3D resolve.c strtok_r.c strlcpy.c strsep=
.c
 dist_libkafs_la_SOURCES =3D \
 	afssys.c				\
-	afskrb.c				\
-	$(afskrb5_c)				\
+	afskrb5.c				\
 	common.c				\
 	$(AIX_SRC)				\
 	kafs_locl.h				\
@@ -404,25 +441,25 @@
 	roken_rename.h
=20
 nodist_libkafs_la_SOURCES =3D $(ROKEN_SRCS)
-EXTRA_libkafs_la_SOURCES =3D afskrb.c afskrb5.c dlfcn.c afslib.c dlfcn.h
-EXTRA_DIST =3D README.dlfcn afsl.exp afslib.exp $(man_MANS)
+EXTRA_libkafs_la_SOURCES =3D afskrb5.c afslib.c
+EXTRA_DIST =3D NTMakefile afsl.exp afslib.exp $(man_MANS)
 man_MANS =3D kafs.3
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/kafs/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/kafs/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/kafs/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/kafs/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -440,23 +477,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -476,149 +518,186 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/afskrb5.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/afslib.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/afssys.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/common.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/resolve.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/strlcpy.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/strsep.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/strtok_r.Plo at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man3: $(man3_MANS) $(man_MANS)
+install-man3: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man3dir)" || $(MKDIR_P) "$(DESTDIR)$(man3dir)"
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man3:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man3dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man3dir)" && rm -f $$files; }
 install-fooDATA: $(foo_DATA)
 	@$(NORMAL_INSTALL)
 	test -z "$(foodir)" || $(MKDIR_P) "$(DESTDIR)$(foodir)"
-	@list=3D'$(foo_DATA)'; for p in $$list; do \
+	@list=3D'$(foo_DATA)'; test -n "$(foodir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(fooDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(foodir)/$$f'"; \
-	  $(fooDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(foodir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(foodir)'"; \
+	  $(INSTALL_DATA) $$files "$(DESTDIR)$(foodir)" || exit $$?; \
 	done
=20
 uninstall-fooDATA:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(foo_DATA)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(foodir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(foodir)/$$f"; \
-	done
+	@list=3D'$(foo_DATA)'; test -n "$(foodir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(foodir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(foodir)" && rm -f $$files
 install-includeHEADERS: $(include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'=
"; \
-	  $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -634,13 +713,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -676,6 +759,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -686,6 +770,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -696,6 +781,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -703,26 +790,35 @@
 install-data-am: install-fooDATA install-includeHEADERS install-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man3
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -743,11 +839,10 @@
 	uninstall-libLTLIBRARIES uninstall-man
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man3
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libLTLIBRARIES clean-libtool ctags \
@@ -836,6 +931,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -921,7 +1019,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -951,6 +1049,7 @@
=20
 strsep.c:
 	$(LN_S) $(srcdir)/../roken/strsep.c .
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/afskrb5.c
--- a/head/crypto/heimdal/lib/kafs/afskrb5.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kafs/afskrb5.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-2003 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2003 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,15 +33,13 @@
=20
 #include "kafs_locl.h"
=20
-RCSID("$Id: afskrb5.c 17032 2006-04-10 08:45:04Z lha $");
-
 struct krb5_kafs_data {
     krb5_context context;
     krb5_ccache id;
     krb5_const_realm realm;
 };
=20
-enum {=20
+enum {
     KAFS_RXKAD_2B_KVNO =3D 213,
     KAFS_RXKAD_K5_KVNO =3D 256
 };
@@ -113,7 +111,7 @@
=20
 static krb5_error_code
 v5_convert(krb5_context context, krb5_ccache id,
-	   krb5_creds *cred, uid_t uid,=20
+	   krb5_creds *cred, uid_t uid,
 	   const char *cell,
 	   struct kafs_token *kt)
 {
@@ -129,26 +127,12 @@
 			    "afs-use-524", "2b", &val);
     free(c);
=20
-    if (strcasecmp(val, "local") =3D=3D 0 ||=20
+    if (strcasecmp(val, "local") =3D=3D 0 ||
 	strcasecmp(val, "2b") =3D=3D 0)
 	ret =3D v5_to_kt(cred, uid, kt, 1);
-    else if(strcasecmp(val, "yes") =3D=3D 0 ||
-	    strcasecmp(val, "true") =3D=3D 0 ||
-	    atoi(val)) {
-	struct credentials cred4;
-=09
-	if (id =3D=3D NULL)
-	    ret =3D krb524_convert_creds_kdc(context, cred, &cred4);
-	else
-	    ret =3D krb524_convert_creds_kdc_ccache(context, id, cred, &cred4);
-	if (ret)
-	    goto out;
-
-	ret =3D _kafs_v4_to_kt(&cred4, uid, kt);
-    } else=20
+    else
 	ret =3D v5_to_kt(cred, uid, kt, 0);
=20
- out:
     free(val);
     return ret;
 }
@@ -159,16 +143,18 @@
  */
=20
 static int
-get_cred(struct kafs_data *data, const char *name, const char *inst,=20
+get_cred(struct kafs_data *data, const char *name, const char *inst,
 	 const char *realm, uid_t uid, struct kafs_token *kt)
 {
     krb5_error_code ret;
     krb5_creds in_creds, *out_creds;
     struct krb5_kafs_data *d =3D data->data;
+    int invalid;
=20
     memset(&in_creds, 0, sizeof(in_creds));
-    ret =3D krb5_425_conv_principal(d->context, name, inst, realm,=20
-				  &in_creds.server);
+
+    ret =3D krb5_make_principal(d->context, &in_creds.server,
+			      realm, name, inst, NULL);
     if(ret)
 	return ret;
     ret =3D krb5_cc_get_principal(d->context, d->id, &in_creds.client);
@@ -176,20 +162,49 @@
 	krb5_free_principal(d->context, in_creds.server);
 	return ret;
     }
+
     in_creds.session.keytype =3D ETYPE_DES_CBC_CRC;
+
+    /* check if des is disable, and in that case enable it for afs */
+    invalid =3D krb5_enctype_valid(d->context, in_creds.session.keytype);
+    if (invalid)
+	krb5_enctype_enable(d->context, in_creds.session.keytype);
+
     ret =3D krb5_get_credentials(d->context, 0, d->id, &in_creds, &out_cre=
ds);
+    if (ret) {
+	in_creds.session.keytype =3D ETYPE_DES_CBC_MD5;
+	ret =3D krb5_get_credentials(d->context, 0, d->id, &in_creds, &out_creds);
+    }
+
+    if (invalid)
+	krb5_enctype_disable(d->context, in_creds.session.keytype);
+
     krb5_free_principal(d->context, in_creds.server);
     krb5_free_principal(d->context, in_creds.client);
     if(ret)
 	return ret;
=20
-    ret =3D v5_convert(d->context, d->id, out_creds, uid,=20
+    ret =3D v5_convert(d->context, d->id, out_creds, uid,
 		     (inst !=3D NULL && inst[0] !=3D '\0') ? inst : realm, kt);
     krb5_free_creds(d->context, out_creds);
=20
     return ret;
 }
=20
+static const char *
+get_error(struct kafs_data *data, int error)
+{
+    struct krb5_kafs_data *d =3D data->data;
+    return krb5_get_error_message(d->context, error);
+}
+
+static void
+free_error(struct kafs_data *data, const char *str)
+{
+    struct krb5_kafs_data *d =3D data->data;
+    krb5_free_error_message(d->context, str);
+}
+
 static krb5_error_code
 afslog_uid_int(struct kafs_data *data, const char *cell, const char *rh,
 	       uid_t uid, const char *homedir)
@@ -199,7 +214,7 @@
     krb5_principal princ;
     const char *trealm; /* ticket realm */
     struct krb5_kafs_data *d =3D data->data;
-   =20
+
     if (cell =3D=3D 0 || cell[0] =3D=3D 0)
 	return _kafs_afslog_all_local_cells (data, uid, homedir);
=20
@@ -212,7 +227,7 @@
     kt.ticket =3D NULL;
     ret =3D _kafs_get_cred(data, cell, d->realm, trealm, uid, &kt);
     krb5_free_principal (d->context, princ);
-   =20
+
     if(ret =3D=3D 0) {
 	ret =3D kafs_settoken_rxkad(cell, &kt.ct, kt.ticket, kt.ticket_len);
 	free(kt.ticket);
@@ -249,6 +264,8 @@
     kd.afslog_uid =3D afslog_uid_int;
     kd.get_cred =3D get_cred;
     kd.get_realm =3D get_realm;
+    kd.get_error =3D get_error;
+    kd.free_error =3D free_error;
     kd.data =3D &d;
     if (context =3D=3D NULL) {
 	ret =3D krb5_init_context(&d.context);
@@ -284,7 +301,7 @@
=20
 krb5_error_code
 krb5_afslog(krb5_context context,
-	    krb5_ccache id,=20
+	    krb5_ccache id,
 	    const char *cell,
 	    krb5_const_realm realm)
 {
@@ -293,7 +310,7 @@
=20
 krb5_error_code
 krb5_afslog_home(krb5_context context,
-		 krb5_ccache id,=20
+		 krb5_ccache id,
 		 const char *cell,
 		 krb5_const_realm realm,
 		 const char *homedir)
@@ -312,6 +329,8 @@
=20
     kd.name =3D "krb5";
     kd.get_realm =3D get_realm;
+    kd.get_error =3D get_error;
+    kd.free_error =3D free_error;
     return _kafs_realm_of_cell(&kd, cell, realm);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/afslib.c
--- a/head/crypto/heimdal/lib/kafs/afslib.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kafs/afslib.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,12 @@
  * SUCH DAMAGE.
  */
=20
-/*=20
- * This file is only used with AIX=20
+/*
+ * This file is only used with AIX
  */
=20
 #include "kafs_locl.h"
=20
-RCSID("$Id: afslib.c 7463 1999-12-02 16:58:55Z joda $");
-
 int
 aix_pioctl(char *a_path,
 	   int o_opcode,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/afssys.c
--- a/head/crypto/heimdal/lib/kafs/afssys.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kafs/afssys.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2000, 2002, 2004, 2005 Kungliga Tekniska H=F6gskol=
an
+ * Copyright (c) 1995 - 2000, 2002, 2004, 2005 Kungliga Tekniska H=C3=B6gs=
kolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -33,8 +33,6 @@
=20
 #include "kafs_locl.h"
=20
-RCSID("$Id: afssys.c 17050 2006-04-11 08:12:29Z lha $");
-
 struct procdata {
     unsigned long param4;
     unsigned long param3;
@@ -54,8 +52,10 @@
     unsigned long param6;
     unsigned long retval;
 };
+#ifdef _IOWR
 #define VIOC_SYSCALL_DEV _IOWR('C', 2, struct devdata)
 #define VIOC_SYSCALL_DEV_OPENAFS _IOWR('C', 1, struct devdata)
+#endif
=20
=20
 int _kafs_debug; /* this should be done in a better way */
@@ -103,7 +103,7 @@
 	strlcpy(path, p, sizeof(path));
     else
 	snprintf(path, sizeof(path), "%s/afslib.so", LIBDIR);
-=09
+
     ptr =3D dlopen(path, RTLD_NOW);
     if(ptr =3D=3D NULL) {
 	if(_kafs_debug) {
@@ -115,7 +115,7 @@
 	return 1;
     }
     Setpag =3D (int (*)(void))dlsym(ptr, "aix_setpag");
-    Pioctl =3D (int (*)(char*, int,=20
+    Pioctl =3D (int (*)(char*, int,
 		      struct ViceIoctl*, int))dlsym(ptr, "aix_pioctl");
 #endif
     afs_entry_point =3D AIX_ENTRY_POINTS;
@@ -123,9 +123,9 @@
 }
 #endif /* _AIX */
=20
-/*=20
+/*
  * This probably only works under Solaris and could get confused if
- * there's a /etc/name_to_sysnum file. =20
+ * there's a /etc/name_to_sysnum file.
  */
=20
 #if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3)
@@ -163,7 +163,7 @@
 }
 #endif
=20
-static int=20
+static int
 try_ioctlpath(const char *path, unsigned long ioctlnum, int entrypoint)
 {
     int fd, ret, saved_errno;
@@ -189,13 +189,13 @@
     }
     saved_errno =3D errno;
     close(fd);
-    /*=20
+    /*
      * Be quite liberal in what error are ok, the first is the one
      * that should trigger given that params is NULL.
      */
-    if (ret &&=20
+    if (ret &&
 	(saved_errno !=3D EFAULT &&
-	 saved_errno !=3D EDOM &&=20
+	 saved_errno !=3D EDOM &&
 	 saved_errno !=3D ENOTCONN))
 	return 1;
     afs_ioctlnum =3D ioctlnum;
@@ -253,23 +253,23 @@
     case MACOS_DEV_POINT: {
 	struct devdata data =3D { AFSCALL_PIOCTL, 0, 0, 0, 0, 0, 0, 0 };
 	int ret;
-=09
+
 	data.param1 =3D (unsigned long)a_path;
 	data.param2 =3D (unsigned long)o_opcode;
 	data.param3 =3D (unsigned long)a_paramsP;
 	data.param4 =3D (unsigned long)a_followSymlinks;
-=09
+
 	ret =3D do_ioctl(&data);
 	if (ret)
 	    return ret;
-=09
+
 	return data.retval;
     }
 #ifdef _AIX
     case AIX_ENTRY_POINTS:
 	return Pioctl(a_path, o_opcode, a_paramsP, a_followSymlinks);
 #endif
-    }   =20
+    }
     errno =3D ENOSYS;
 #ifdef SIGSYS
     kill(getpid(), SIGSYS);	/* You lose! */
@@ -328,7 +328,7 @@
 	return Setpag();
 #endif
     }
-   =20
+
     errno =3D ENOSYS;
 #ifdef SIGSYS
     kill(getpid(), SIGSYS);	/* You lose! */
@@ -413,7 +413,7 @@
=20
     if (!issuid())
 	env =3D getenv ("AFS_SYSCALL");
- =20
+
     /*
      * Already checked presence of AFS syscalls?
      */
@@ -426,7 +426,7 @@
      * If the syscall is absent we recive a SIGSYS.
      */
     afs_entry_point =3D NO_ENTRY_POINT;
- =20
+
     saved_errno =3D errno;
 #ifndef NO_AFS
 #ifdef SIGSYS
@@ -439,10 +439,14 @@
 		goto done;
 	}
 	if (strncmp("/dev/", env, 5) =3D=3D 0) {
+#ifdef VIOC_SYSCALL_DEV
 	    if (try_ioctlpath(env, VIOC_SYSCALL_DEV, MACOS_DEV_POINT) =3D=3D 0)
 		goto done;
+#endif
+#ifdef VIOC_SYSCALL_DEV_OPENAFS
 	    if (try_ioctlpath(env,VIOC_SYSCALL_DEV_OPENAFS,MACOS_DEV_POINT) =3D=
=3D0)
 		goto done;
+#endif
 	}
     }
=20
@@ -450,18 +454,22 @@
 			VIOC_SYSCALL_PROC, LINUX_PROC_POINT);
     if (ret =3D=3D 0)
 	goto done;
-    ret =3D try_ioctlpath("/proc/fs/nnpfs/afs_ioctl",=20
+    ret =3D try_ioctlpath("/proc/fs/nnpfs/afs_ioctl",
 			VIOC_SYSCALL_PROC, LINUX_PROC_POINT);
     if (ret =3D=3D 0)
 	goto done;
=20
-    ret =3D try_ioctlpath("/dev/openafs_ioctl",=20
+#ifdef VIOC_SYSCALL_DEV_OPENAFS
+    ret =3D try_ioctlpath("/dev/openafs_ioctl",
 			VIOC_SYSCALL_DEV_OPENAFS, MACOS_DEV_POINT);
     if (ret =3D=3D 0)
 	goto done;
+#endif
+#ifdef VIOC_SYSCALL_DEV
     ret =3D try_ioctlpath("/dev/nnpfs_ioctl", VIOC_SYSCALL_DEV, MACOS_DEV_=
POINT);
     if (ret =3D=3D 0)
 	goto done;
+#endif
=20
 #if defined(AFS_SYSCALL) || defined(AFS_SYSCALL2) || defined(AFS_SYSCALL3)
     {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/afssysdef=
s.h
--- a/head/crypto/heimdal/lib/kafs/afssysdefs.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/kafs/afssysdefs.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2003 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2003 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: afssysdefs.h 14102 2004-08-09 13:41:32Z lha $ */
+/* $Id$ */
=20
 /*
  * This section is for machines using single entry point AFS syscalls!
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/common.c
--- a/head/crypto/heimdal/lib/kafs/common.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kafs/common.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "kafs_locl.h"
=20
-RCSID("$Id: common.c 15461 2005-06-16 22:52:33Z lha $");
-
 #define AUTH_SUPERUSER "afs"
=20
 /*
@@ -75,7 +73,7 @@
     struct ViceIoctl parms;
     char buf[2048], *t;
     int32_t sizeof_x;
-   =20
+
     t =3D buf;
     /*
      * length of secret token followed by secret token
@@ -141,47 +139,18 @@
     }
 }
=20
-
-int
-_kafs_v4_to_kt(CREDENTIALS *c, uid_t uid, struct kafs_token *kt)
-{
-    kt->ticket =3D NULL;
-
-    if (c->ticket_st.length > MAX_KTXT_LEN)
-	return EINVAL;
-
-    kt->ticket =3D malloc(c->ticket_st.length);
-    if (kt->ticket =3D=3D NULL)
-	return ENOMEM;
-    kt->ticket_len =3D c->ticket_st.length;
-    memcpy(kt->ticket, c->ticket_st.dat, kt->ticket_len);
-   =20
-    /*
-     * Build a struct ClearToken
-     */
-    kt->ct.AuthHandle =3D c->kvno;
-    memcpy (kt->ct.HandShakeKey, c->session, sizeof(c->session));
-    kt->ct.ViceId =3D uid;
-    kt->ct.BeginTimestamp =3D c->issue_date;
-    kt->ct.EndTimestamp =3D krb_life_to_time(c->issue_date, c->lifetime);
-
-    _kafs_fixup_viceid(&kt->ct, uid);
-
-    return 0;
-}
-
 /* Try to get a db-server for an AFS cell from a AFSDB record */
=20
 static int
 dns_find_cell(const char *cell, char *dbserver, size_t len)
 {
-    struct dns_reply *r;
+    struct rk_dns_reply *r;
     int ok =3D -1;
-    r =3D dns_lookup(cell, "afsdb");
+    r =3D rk_dns_lookup(cell, "afsdb");
     if(r){
-	struct resource_record *rr =3D r->head;
+	struct rk_resource_record *rr =3D r->head;
 	while(rr){
-	    if(rr->type =3D=3D T_AFSDB && rr->u.afsdb->preference =3D=3D 1){
+	    if(rr->type =3D=3D rk_ns_t_afsdb && rr->u.afsdb->preference =3D=3D 1){
 		strlcpy(dbserver,
 				rr->u.afsdb->domain,
 				len);
@@ -190,7 +159,7 @@
 	    }
 	    rr =3D rr->next;
 	}
-	dns_free_data(r);
+	rk_dns_free_data(r);
     }
     return ok;
 }
@@ -282,7 +251,7 @@
     find_cells(_PATH_ARLA_DEBIAN_THISCELL, &cells, &idx);
     find_cells(_PATH_ARLA_OPENBSD_THESECELLS, &cells, &idx);
     find_cells(_PATH_ARLA_OPENBSD_THISCELL, &cells, &idx);
-   =20
+
     ret =3D afslog_cells(data, cells, idx, uid, homedir);
     while(idx > 0)
 	free(cells[--idx]);
@@ -292,7 +261,7 @@
=20
=20
 static int
-file_find_cell(struct kafs_data *data,=20
+file_find_cell(struct kafs_data *data,
 	       const char *cell, char **realm, int exact)
 {
     FILE *F;
@@ -378,11 +347,14 @@
=20
     ret =3D (*data->get_cred)(data, user, cell, realm, uid, kt);
     if (kafs_verbose) {
+	const char *estr =3D (*data->get_error)(data, ret);
 	char *str;
-	asprintf(&str, "%s tried afs%s%s@%s -> %d",
-		 data->name, cell[0] =3D=3D '\0' ? "" : "/",=20
-		 cell, realm, ret);
+	asprintf(&str, "%s tried afs%s%s@%s -> %s (%d)",
+		 data->name, cell ? "/" : "",
+		 cell ? cell : "", realm, estr ? estr : "unknown", ret);
 	(*kafs_verbose)(kafs_verbose_ctx, str);
+	if (estr)
+	    (*data->free_error)(data, estr);
 	free(str);
     }
=20
@@ -392,7 +364,7 @@
=20
 int
 _kafs_get_cred(struct kafs_data *data,
-	       const char *cell,=20
+	       const char *cell,
 	       const char *realm_hint,
 	       const char *realm,
 	       uid_t uid,
@@ -419,54 +391,53 @@
      * really a long shot.
      *
      */
- =20
+
     /* comments on the ordering of these tests */
=20
     /* If the user passes a realm, she probably knows something we don't
      * know and we should try afs at realm_hint.
      */
- =20
+
     if (realm_hint) {
 	ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,
 				 cell, realm_hint, uid, kt);
 	if (ret =3D=3D 0) return 0;
 	ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,
-				 "", realm_hint, uid, kt);
+				 NULL, realm_hint, uid, kt);
 	if (ret =3D=3D 0) return 0;
     }
=20
     _kafs_foldup(CELL, cell);
=20
     /*
+     * If the AFS servers have a file /usr/afs/etc/krb.conf containing
+     * REALM we still don't have to resort to cross-cell authentication.
+     * Try afs.cell at REALM.
+     */
+    ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,
+			     cell, realm, uid, kt);
+    if (ret =3D=3D 0) return 0;
+
+    /*
      * If cell =3D=3D realm we don't need no cross-cell authentication.
      * Try afs at REALM.
      */
     if (strcmp(CELL, realm) =3D=3D 0) {
         ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,
-				 "", realm, uid, kt);
+				 NULL, realm, uid, kt);
 	if (ret =3D=3D 0) return 0;
-	/* Try afs.cell at REALM below. */
     }
=20
     /*
-     * If the AFS servers have a file /usr/afs/etc/krb.conf containing
-     * REALM we still don't have to resort to cross-cell authentication.
-     * Try afs.cell at REALM.
-     */
-    ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,=20
-			     cell, realm, uid, kt);
-    if (ret =3D=3D 0) return 0;
-
-    /*
      * We failed to get ``first class tickets'' for afs,
      * fall back to cross-cell authentication.
      * Try afs at CELL.
      * Try afs.cell at CELL.
      */
     ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,
-			     "", CELL, uid, kt);
+			     NULL, CELL, uid, kt);
     if (ret =3D=3D 0) return 0;
-    ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,=20
+    ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,
 			     cell, CELL, uid, kt);
     if (ret =3D=3D 0) return 0;
=20
@@ -483,7 +454,7 @@
 				 cell, vl_realm, uid, kt);
 	if (ret)
 	    ret =3D _kafs_try_get_cred(data, AUTH_SUPERUSER,
-				     "", vl_realm, uid, kt);
+				     NULL, vl_realm, uid, kt);
 	free(vl_realm);
 	if (ret =3D=3D 0) return 0;
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/kafs.3
--- a/head/crypto/heimdal/lib/kafs/kafs.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kafs/kafs.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 1998 - 2006 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1998 - 2006 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\"	$Id: kafs.3 17380 2006-05-01 07:01:18Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\"	$Id$
 .\"
 .Dd May  1, 2006
 .Os HEIMDAL
@@ -161,7 +161,7 @@
 .Pp
 .Fn krb5_afslog ,
 .Fn kafs_settoken5
-can be configured to behave differently via a=20
+can be configured to behave differently via a
 .Nm krb5_appdefault
 option
 .Li afs-use-524
@@ -279,6 +279,18 @@
 .%T File Server/Cache Manager Interface
 .%D 1991
 .Re
+.Sh FILES
+libkafs will search for
+.Pa ThisCell and
+.Pa TheseCells
+in the following locations:
+.Pa /usr/vice/etc ,
+.Pa /etc/openafs ,
+.Pa /var/db/openafs/etc ,
+.Pa /usr/arla/etc ,
+.Pa /etc/arla ,
+and
+.Pa /etc/afs
 .Sh BUGS
 .Ev AFS_SYSCALL
 has no effect under AIX.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/kafs.h
--- a/head/crypto/heimdal/lib/kafs/kafs.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/kafs/kafs.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001, 2003 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2001, 2003 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: kafs.h 20652 2007-05-10 19:30:18Z lha $ */
+/* $Id$ */
=20
 #ifndef __KAFS_H
 #define __KAFS_H
@@ -82,15 +82,15 @@
 #define VIOC_AFS_SYSNAME	_VICEIOCTL(38)
 #define VIOC_EXPORTAFS		_VICEIOCTL(39)
 #define VIOCGETCACHEPARAMS	_VICEIOCTL(40)
-#define VIOC_GCPAGS		_VICEIOCTL(48)=20
+#define VIOC_GCPAGS		_VICEIOCTL(48)
=20
 #define VIOCGETTOK2		_AFSCIOCTL(7)
 #define VIOCSETTOK2		_AFSCIOCTL(8)
=20
 struct ViceIoctl {
   caddr_t in, out;
-  short in_size;
-  short out_size;
+  unsigned short in_size;
+  unsigned short out_size;
 };
=20
 struct ClearToken {
@@ -157,7 +157,7 @@
 				     krb5_const_realm realm,
 				     uid_t uid);
 krb5_error_code krb5_afslog (krb5_context context,
-				 krb5_ccache id,=20
+				 krb5_ccache id,
 				 const char *cell,
 				 krb5_const_realm realm);
 krb5_error_code krb5_afslog_uid_home (krb5_context context,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/kafs_locl=
.h
--- a/head/crypto/heimdal/lib/kafs/kafs_locl.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/kafs/kafs_locl.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: kafs_locl.h 16116 2005-10-02 03:14:47Z lha $ */
+/* $Id$ */
=20
 #ifndef __KAFS_LOCL_H__
 #define __KAFS_LOCL_H__
@@ -94,15 +94,11 @@
 #ifdef KRB5
 #include <krb5.h>
 #endif
-#ifdef KRB4
-#include <krb.h>
-#else
 #ifdef KRB5
 #include "crypto-headers.h"
 #include <krb5-v4compat.h>
 typedef struct credentials CREDENTIALS;
 #endif /* KRB5 */
-#endif /* KRB4 */
 #include <kafs.h>
=20
 #include <resolve.h>
@@ -117,7 +113,7 @@
 				 uid_t,
 				 const char *);
=20
-typedef int (*get_cred_func_t)(struct kafs_data*, const char*, const char*=
,=20
+typedef int (*get_cred_func_t)(struct kafs_data*, const char*, const char*,
 			       const char*, uid_t, struct kafs_token *);
=20
 typedef char* (*get_realm_func_t)(struct kafs_data*, const char*);
@@ -127,6 +123,8 @@
     afslog_uid_func_t afslog_uid;
     get_cred_func_t get_cred;
     get_realm_func_t get_realm;
+    const char *(*get_error)(struct kafs_data *, int);
+    void (*free_error)(struct kafs_data *, const char *);
     void *data;
 };
=20
@@ -140,7 +138,7 @@
=20
 int _kafs_afslog_all_local_cells(struct kafs_data*, uid_t, const char*);
=20
-int _kafs_get_cred(struct kafs_data*, const char*, const char*, const char=
 *,=20
+int _kafs_get_cred(struct kafs_data*, const char*, const char*, const char=
 *,
 		   uid_t, struct kafs_token *);
=20
 int
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/kafs/roken_ren=
ame.h
--- a/head/crypto/heimdal/lib/kafs/roken_rename.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/kafs/roken_rename.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2001-2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001-2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: roken_rename.h 15341 2005-06-02 07:35:45Z lha $ */
+/* $Id$ */
=20
 #ifndef __roken_rename_h__
 #define __roken_rename_h__
@@ -52,13 +52,13 @@
 #define rk_dns_parse_reply _kafs_dns_parse_reply
=20
 #ifndef HAVE_STRTOK_R
-#define strtok_r _kafs_strtok_r
+#define rk_strtok_r _kafs_strtok_r
 #endif
 #ifndef HAVE_STRLCPY
-#define strlcpy _kafs_strlcpy
+#define rk_strlcpy _kafs_strlcpy
 #endif
 #ifndef HAVE_STRSEP
-#define strsep _kafs_strsep
+#define rk_strsep _kafs_strsep
 #endif
=20
 #endif /* __roken_rename_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/Makefile.=
am
--- a/head/crypto/heimdal/lib/krb5/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,25 +1,29 @@
-# $Id: Makefile.am 22501 2008-01-21 15:43:21Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-AM_CPPFLAGS +=3D $(INCLUDE_krb4) $(INCLUDE_hcrypto) -I../com_err -I$(srcdi=
r)/../com_err
+AM_CPPFLAGS +=3D $(INCLUDE_krb4) $(INCLUDE_hcrypto) -I../com_err -I$(srcdi=
r)/../com_err $(INCLUDE_sqlite3) $(INCLUDE_libintl)
=20
 bin_PROGRAMS =3D verify_krb5_conf
=20
 noinst_PROGRAMS =3D				\
 	krbhst-test				\
+	test_gic				\
 	test_alname				\
 	test_crypto				\
+	test_rfc3961				\
 	test_get_addrs				\
 	test_kuserok				\
 	test_renew				\
 	test_forward
=20
+noinst_LTLIBRARIES =3D				\
+	librfc3961.la
+
 TESTS =3D						\
 	aes-test				\
 	derived-key-test			\
 	n-fold-test				\
-	name-45-test				\
 	parse-name-test				\
 	store-test				\
 	string-to-key-test			\
@@ -27,6 +31,7 @@
 	test_addr				\
 	test_cc					\
 	test_config				\
+	test_fx					\
 	test_prf				\
 	test_store				\
 	test_crypto_wrapping			\
@@ -36,25 +41,54 @@
 	test_plugin				\
 	test_princ				\
 	test_pkinit_dh2key			\
-	test_time
+	test_pknistkdf				\
+	test_time				\
+	test_x500
=20
-check_PROGRAMS =3D $(TESTS) test_hostname
+check_DATA =3D test_config_strings.out
+
+check_PROGRAMS =3D $(TESTS) test_hostname test_ap-req
=20
 LDADD =3D libkrb5.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la \
 	$(LIB_roken)
=20
 if PKINIT
 LIB_pkinit =3D ../hx509/libhx509.la
 endif
=20
+if have_scc
+use_sqlite =3D $(LIB_sqlite3)
+endif
+
 libkrb5_la_LIBADD =3D \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ipc/libheim-ipcc.la \
+	$(top_builddir)/lib/wind/libwind.la \
+	$(top_builddir)/base/libheimbase.la \
 	$(LIB_pkinit) \
+	$(use_sqlite) \
 	$(LIB_com_err) \
 	$(LIB_hcrypto) \
+	$(LIB_libintl) \
+	$(LIBADD_roken) \
+	$(PTHREAD_LIBADD) \
+	$(LIB_door_create) \
+	$(LIB_dlopen)
+
+librfc3961_la_LIBADD =3D \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ipc/libheim-ipcc.la \
+	$(top_builddir)/lib/wind/libwind.la \
+	$(LIB_pkinit) \
+	$(use_sqlite) \
+	$(LIB_com_err) \
+	$(LIB_hcrypto) \
+	$(LIB_libintl) \
 	$(LIBADD_roken) \
+	$(PTHREAD_LIBADD) \
 	$(LIB_door_create) \
 	$(LIB_dlopen)
=20
@@ -62,7 +96,15 @@
=20
 ERR_FILES =3D krb5_err.c krb_err.c heim_err.c k524_err.c
=20
-libkrb5_la_CPPFLAGS =3D -DBUILD_KRB5_LIB $(AM_CPPFLAGS)
+libkrb5_la_CPPFLAGS =3D \
+	-DBUILD_KRB5_LIB \
+	$(AM_CPPFLAGS) \
+	-DHEIMDAL_LOCALEDIR=3D'"$(localedir)"'
+
+librfc3961_la_CPPFLAGS =3D \
+	-DBUILD_KRB5_LIB \
+	$(AM_CPPFLAGS) \
+	-DHEIMDAL_LOCALEDIR=3D'"$(localedir)"'
=20
 dist_libkrb5_la_SOURCES =3D			\
 	acache.c				\
@@ -79,7 +121,6 @@
 	changepw.c				\
 	codec.c					\
 	config_file.c				\
-	config_file_netinfo.c			\
 	convert_creds.c				\
 	constants.c				\
 	context.c				\
@@ -87,12 +128,25 @@
 	crc.c					\
 	creds.c					\
 	crypto.c				\
+	crypto.h				\
+	crypto-aes.c				\
+	crypto-algs.c				\
+	crypto-arcfour.c			\
+	crypto-des.c				\
+	crypto-des-common.c			\
+	crypto-des3.c				\
+	crypto-evp.c				\
+	crypto-null.c				\
+	crypto-pk.c				\
+	crypto-rand.c				\
 	doxygen.c				\
 	data.c					\
+	deprecated.c				\
 	digest.c				\
 	eai_to_heim_errno.c			\
 	error_string.c				\
 	expand_hostname.c			\
+	expand_path.c				\
 	fcache.c				\
 	free.c					\
 	free_host_realm.c			\
@@ -105,11 +159,7 @@
 	get_for_creds.c				\
 	get_host_realm.c			\
 	get_in_tkt.c				\
-	get_in_tkt_pw.c				\
-	get_in_tkt_with_keytab.c		\
-	get_in_tkt_with_skey.c			\
 	get_port.c				\
-	heim_threads.h				\
 	init_creds.c				\
 	init_creds_pw.c				\
 	kcm.c					\
@@ -119,7 +169,6 @@
 	keytab_any.c				\
 	keytab_file.c				\
 	keytab_keyfile.c			\
-	keytab_krb4.c				\
 	keytab_memory.c				\
 	krb5_locl.h				\
 	krb5-v4compat.h				\
@@ -140,6 +189,7 @@
 	n-fold.c				\
 	pac.c					\
 	padata.c				\
+	pcache.c				\
 	pkinit.c				\
 	principal.c				\
 	prog_setup.c				\
@@ -153,11 +203,18 @@
 	read_message.c				\
 	recvauth.c				\
 	replay.c				\
+	salt.c					\
+	salt-aes.c				\
+	salt-arcfour.c				\
+	salt-des.c				\
+	salt-des3.c				\
+	scache.c				\
 	send_to_kdc.c				\
 	sendauth.c				\
 	set_default_realm.c			\
 	sock_principal.c			\
 	store.c					\
+	store-int.c				\
 	store-int.h				\
 	store_emem.c				\
 	store_fd.c				\
@@ -166,7 +223,6 @@
 	ticket.c				\
 	time.c					\
 	transited.c				\
-	v4_glue.c				\
 	verify_init.c				\
 	verify_user.c				\
 	version.c				\
@@ -176,45 +232,73 @@
 nodist_libkrb5_la_SOURCES =3D			\
 	$(ERR_FILES)
=20
-libkrb5_la_LDFLAGS =3D -version-info 24:0:0
+libkrb5_la_DEPENDENCIES =3D			\
+	version-script.map
+
+libkrb5_la_LDFLAGS =3D -version-info 26:0:0
=20
 if versionscript
 libkrb5_la_LDFLAGS +=3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script.=
map
 endif
=20
-$(libkrb5_la_OBJECTS) $(verify_krb5_conf_OBJECTS): $(srcdir)/krb5-protos.h=
 $(srcdir)/krb5-private.h
+$(libkrb5_la_OBJECTS) $(verify_krb5_conf_OBJECTS) $(librfc3961_la_OBJECTS)=
: $(srcdir)/krb5-protos.h $(srcdir)/krb5-private.h krb5_err.h heim_err.h k5=
24_err.h krb5_err.h krb_err.h k524_err.h
+
+librfc3961_la_SOURCES =3D				\
+	crc.c					\
+	crypto.c				\
+	crypto.h				\
+	crypto-aes.c				\
+	crypto-algs.c				\
+	crypto-arcfour.c			\
+	crypto-des.c				\
+	crypto-des-common.c			\
+	crypto-des3.c				\
+	crypto-evp.c				\
+	crypto-null.c				\
+	crypto-pk.c				\
+	crypto-rand.c				\
+	crypto-stubs.c				\
+	data.c					\
+	error_string.c				\
+	keyblock.c				\
+	n-fold.c				\
+	salt.c					\
+	salt-aes.c				\
+	salt-arcfour.c				\
+	salt-des.c				\
+	salt-des3.c				\
+	store-int.c				\
+	warn.c
+
+test_rfc3961_LDADD =3D 				\
+	librfc3961.la 				\
+	$(top_builddir)/lib/asn1/libasn1.la	\
+	$(top_builddir)/lib/wind/libwind.la 	\
+	$(LIB_hcrypto)				\
+	$(LIB_roken)
=20
 $(srcdir)/krb5-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -E KRB5_LIB_FUNCTION -q -P co=
mment -o krb5-protos.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -E KRB5_LIB -q -P comment -o =
krb5-protos.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-protos.h
=20
 $(srcdir)/krb5-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5-private=
.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-private.h
=20
 man_MANS =3D					\
 	kerberos.8				\
-	krb5.3					\
 	krb5.conf.5				\
 	krb524_convert_creds_kdc.3		\
 	krb5_425_conv_principal.3		\
 	krb5_acl_match_file.3			\
-	krb5_address.3				\
 	krb5_aname_to_localname.3		\
 	krb5_appdefault.3			\
 	krb5_auth_context.3			\
 	krb5_c_make_checksum.3			\
-	krb5_ccache.3				\
 	krb5_check_transited.3			\
-	krb5_compare_creds.3			\
-	krb5_config.3				\
-	krb5_context.3				\
 	krb5_create_checksum.3			\
 	krb5_creds.3				\
-	krb5_crypto_init.3			\
-	krb5_data.3				\
 	krb5_digest.3				\
 	krb5_eai_to_heim_errno.3		\
 	krb5_encrypt.3				\
-	krb5_expand_hostname.3			\
 	krb5_find_padata.3			\
 	krb5_generate_random_block.3		\
 	krb5_get_all_client_addrs.3		\
@@ -227,10 +311,7 @@
 	krb5_getportbyname.3			\
 	krb5_init_context.3			\
 	krb5_is_thread_safe.3			\
-	krb5_keyblock.3				\
-	krb5_keytab.3				\
 	krb5_krbhst_init.3			\
-	krb5_kuserok.3				\
 	krb5_mk_req.3				\
 	krb5_mk_safe.3				\
 	krb5_openlog.3				\
@@ -241,14 +322,10 @@
 	krb5_rd_safe.3				\
 	krb5_set_default_realm.3		\
 	krb5_set_password.3			\
-	krb5_storage.3				\
 	krb5_string_to_key.3			\
-	krb5_ticket.3				\
 	krb5_timeofday.3			\
-	krb5_unparse_name.3			\
 	krb5_verify_init_creds.3		\
 	krb5_verify_user.3			\
-	krb5_warn.3				\
 	verify_krb5_conf.8
=20
 dist_include_HEADERS =3D \
@@ -257,18 +334,19 @@
 	krb5-private.h \
 	krb5_ccapi.h
=20
-nodist_include_HEADERS =3D krb5_err.h heim_err.h k524_err.h=20
+nodist_include_HEADERS =3D krb5_err.h heim_err.h k524_err.h
=20
 # XXX use nobase_include_HEADERS =3D krb5/locate_plugin.h
 krb5dir =3D $(includedir)/krb5
-krb5_HEADERS =3D locate_plugin.h
+krb5_HEADERS =3D locate_plugin.h send_to_kdc_plugin.h ccache_plugin.h
=20
 build_HEADERZ =3D \
-	heim_threads.h \
 	$(krb5_HEADERS) \
 	krb_err.h
=20
 CLEANFILES =3D \
+	test_config_strings.out \
+	test-store-data \
 	krb5_err.c krb5_err.h \
 	krb_err.c krb_err.h \
 	heim_err.c heim_err.h \
@@ -276,13 +354,19 @@
=20
 $(libkrb5_la_OBJECTS): krb5_err.h krb_err.h heim_err.h k524_err.h
=20
+test_config_strings.out: test_config_strings.cfg
+	$(CP) $(srcdir)/test_config_strings.cfg test_config_strings.out
+
 EXTRA_DIST =3D \
+	NTMakefile \
+	verify_krb5_conf-version.rc \
 	krb5_err.et \
 	krb_err.et \
 	heim_err.et \
 	k524_err.et \
 	$(man_MANS) \
 	version-script.map \
+	test_config_strings.cfg \
 	krb5.moduli
=20
 #sysconf_DATA =3D krb5.moduli
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/Makefile.=
in
--- a/head/crypto/heimdal/lib/krb5/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22501 2008-01-21 15:43:21Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,26 +47,28 @@
 	$(top_srcdir)/Makefile.am.common \
 	$(top_srcdir)/cf/Makefile.am.common
 bin_PROGRAMS =3D verify_krb5_conf$(EXEEXT)
-noinst_PROGRAMS =3D krbhst-test$(EXEEXT) test_alname$(EXEEXT) \
-	test_crypto$(EXEEXT) test_get_addrs$(EXEEXT) \
+noinst_PROGRAMS =3D krbhst-test$(EXEEXT) test_gic$(EXEEXT) \
+	test_alname$(EXEEXT) test_crypto$(EXEEXT) \
+	test_rfc3961$(EXEEXT) test_get_addrs$(EXEEXT) \
 	test_kuserok$(EXEEXT) test_renew$(EXEEXT) \
 	test_forward$(EXEEXT)
 TESTS =3D aes-test$(EXEEXT) derived-key-test$(EXEEXT) \
-	n-fold-test$(EXEEXT) name-45-test$(EXEEXT) \
-	parse-name-test$(EXEEXT) store-test$(EXEEXT) \
-	string-to-key-test$(EXEEXT) test_acl$(EXEEXT) \
-	test_addr$(EXEEXT) test_cc$(EXEEXT) test_config$(EXEEXT) \
-	test_prf$(EXEEXT) test_store$(EXEEXT) \
-	test_crypto_wrapping$(EXEEXT) test_keytab$(EXEEXT) \
-	test_mem$(EXEEXT) test_pac$(EXEEXT) test_plugin$(EXEEXT) \
-	test_princ$(EXEEXT) test_pkinit_dh2key$(EXEEXT) \
-	test_time$(EXEEXT)
-check_PROGRAMS =3D $(am__EXEEXT_1) test_hostname$(EXEEXT)
+	n-fold-test$(EXEEXT) parse-name-test$(EXEEXT) \
+	store-test$(EXEEXT) string-to-key-test$(EXEEXT) \
+	test_acl$(EXEEXT) test_addr$(EXEEXT) test_cc$(EXEEXT) \
+	test_config$(EXEEXT) test_fx$(EXEEXT) test_prf$(EXEEXT) \
+	test_store$(EXEEXT) test_crypto_wrapping$(EXEEXT) \
+	test_keytab$(EXEEXT) test_mem$(EXEEXT) test_pac$(EXEEXT) \
+	test_plugin$(EXEEXT) test_princ$(EXEEXT) \
+	test_pkinit_dh2key$(EXEEXT) test_pknistkdf$(EXEEXT) \
+	test_time$(EXEEXT) test_x500$(EXEEXT)
+check_PROGRAMS =3D $(am__EXEEXT_1) test_hostname$(EXEEXT) \
+	test_ap-req$(EXEEXT)
 @versionscript_TRUE at am__append_1 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
 subdir =3D lib/krb5
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -79,7 +83,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -93,9 +97,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -103,79 +110,97 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \
 	"$(DESTDIR)$(man3dir)" "$(DESTDIR)$(man5dir)" \
 	"$(DESTDIR)$(man8dir)" "$(DESTDIR)$(includedir)" \
 	"$(DESTDIR)$(krb5dir)" "$(DESTDIR)$(includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
-LTLIBRARIES =3D $(lib_LTLIBRARIES)
+LTLIBRARIES =3D $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES)
 am__DEPENDENCIES_1 =3D
-libkrb5_la_DEPENDENCIES =3D $(LIB_pkinit) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1) $(top_builddir)/lib/asn1/libasn1.la \
-	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
+ at have_scc_TRUE@am__DEPENDENCIES_2 =3D $(am__DEPENDENCIES_1)
 dist_libkrb5_la_OBJECTS =3D libkrb5_la-acache.lo libkrb5_la-acl.lo \
 	libkrb5_la-add_et_list.lo libkrb5_la-addr_families.lo \
 	libkrb5_la-aname_to_localname.lo libkrb5_la-appdefault.lo \
 	libkrb5_la-asn1_glue.lo libkrb5_la-auth_context.lo \
 	libkrb5_la-build_ap_req.lo libkrb5_la-build_auth.lo \
 	libkrb5_la-cache.lo libkrb5_la-changepw.lo libkrb5_la-codec.lo \
-	libkrb5_la-config_file.lo libkrb5_la-config_file_netinfo.lo \
-	libkrb5_la-convert_creds.lo libkrb5_la-constants.lo \
-	libkrb5_la-context.lo libkrb5_la-copy_host_realm.lo \
-	libkrb5_la-crc.lo libkrb5_la-creds.lo libkrb5_la-crypto.lo \
-	libkrb5_la-doxygen.lo libkrb5_la-data.lo libkrb5_la-digest.lo \
+	libkrb5_la-config_file.lo libkrb5_la-convert_creds.lo \
+	libkrb5_la-constants.lo libkrb5_la-context.lo \
+	libkrb5_la-copy_host_realm.lo libkrb5_la-crc.lo \
+	libkrb5_la-creds.lo libkrb5_la-crypto.lo \
+	libkrb5_la-crypto-aes.lo libkrb5_la-crypto-algs.lo \
+	libkrb5_la-crypto-arcfour.lo libkrb5_la-crypto-des.lo \
+	libkrb5_la-crypto-des-common.lo libkrb5_la-crypto-des3.lo \
+	libkrb5_la-crypto-evp.lo libkrb5_la-crypto-null.lo \
+	libkrb5_la-crypto-pk.lo libkrb5_la-crypto-rand.lo \
+	libkrb5_la-doxygen.lo libkrb5_la-data.lo \
+	libkrb5_la-deprecated.lo libkrb5_la-digest.lo \
 	libkrb5_la-eai_to_heim_errno.lo libkrb5_la-error_string.lo \
-	libkrb5_la-expand_hostname.lo libkrb5_la-fcache.lo \
-	libkrb5_la-free.lo libkrb5_la-free_host_realm.lo \
+	libkrb5_la-expand_hostname.lo libkrb5_la-expand_path.lo \
+	libkrb5_la-fcache.lo libkrb5_la-free.lo \
+	libkrb5_la-free_host_realm.lo \
 	libkrb5_la-generate_seq_number.lo \
 	libkrb5_la-generate_subkey.lo libkrb5_la-get_addrs.lo \
 	libkrb5_la-get_cred.lo libkrb5_la-get_default_principal.lo \
 	libkrb5_la-get_default_realm.lo libkrb5_la-get_for_creds.lo \
 	libkrb5_la-get_host_realm.lo libkrb5_la-get_in_tkt.lo \
-	libkrb5_la-get_in_tkt_pw.lo \
-	libkrb5_la-get_in_tkt_with_keytab.lo \
-	libkrb5_la-get_in_tkt_with_skey.lo libkrb5_la-get_port.lo \
-	libkrb5_la-init_creds.lo libkrb5_la-init_creds_pw.lo \
-	libkrb5_la-kcm.lo libkrb5_la-keyblock.lo libkrb5_la-keytab.lo \
+	libkrb5_la-get_port.lo libkrb5_la-init_creds.lo \
+	libkrb5_la-init_creds_pw.lo libkrb5_la-kcm.lo \
+	libkrb5_la-keyblock.lo libkrb5_la-keytab.lo \
 	libkrb5_la-keytab_any.lo libkrb5_la-keytab_file.lo \
-	libkrb5_la-keytab_keyfile.lo libkrb5_la-keytab_krb4.lo \
-	libkrb5_la-keytab_memory.lo libkrb5_la-krbhst.lo \
-	libkrb5_la-kuserok.lo libkrb5_la-log.lo libkrb5_la-mcache.lo \
-	libkrb5_la-misc.lo libkrb5_la-mk_error.lo \
+	libkrb5_la-keytab_keyfile.lo libkrb5_la-keytab_memory.lo \
+	libkrb5_la-krbhst.lo libkrb5_la-kuserok.lo libkrb5_la-log.lo \
+	libkrb5_la-mcache.lo libkrb5_la-misc.lo libkrb5_la-mk_error.lo \
 	libkrb5_la-mk_priv.lo libkrb5_la-mk_rep.lo \
 	libkrb5_la-mk_req.lo libkrb5_la-mk_req_ext.lo \
 	libkrb5_la-mk_safe.lo libkrb5_la-mit_glue.lo \
 	libkrb5_la-net_read.lo libkrb5_la-net_write.lo \
 	libkrb5_la-n-fold.lo libkrb5_la-pac.lo libkrb5_la-padata.lo \
-	libkrb5_la-pkinit.lo libkrb5_la-principal.lo \
-	libkrb5_la-prog_setup.lo libkrb5_la-prompter_posix.lo \
-	libkrb5_la-rd_cred.lo libkrb5_la-rd_error.lo \
-	libkrb5_la-rd_priv.lo libkrb5_la-rd_rep.lo \
-	libkrb5_la-rd_req.lo libkrb5_la-rd_safe.lo \
-	libkrb5_la-read_message.lo libkrb5_la-recvauth.lo \
-	libkrb5_la-replay.lo libkrb5_la-send_to_kdc.lo \
+	libkrb5_la-pcache.lo libkrb5_la-pkinit.lo \
+	libkrb5_la-principal.lo libkrb5_la-prog_setup.lo \
+	libkrb5_la-prompter_posix.lo libkrb5_la-rd_cred.lo \
+	libkrb5_la-rd_error.lo libkrb5_la-rd_priv.lo \
+	libkrb5_la-rd_rep.lo libkrb5_la-rd_req.lo \
+	libkrb5_la-rd_safe.lo libkrb5_la-read_message.lo \
+	libkrb5_la-recvauth.lo libkrb5_la-replay.lo libkrb5_la-salt.lo \
+	libkrb5_la-salt-aes.lo libkrb5_la-salt-arcfour.lo \
+	libkrb5_la-salt-des.lo libkrb5_la-salt-des3.lo \
+	libkrb5_la-scache.lo libkrb5_la-send_to_kdc.lo \
 	libkrb5_la-sendauth.lo libkrb5_la-set_default_realm.lo \
 	libkrb5_la-sock_principal.lo libkrb5_la-store.lo \
-	libkrb5_la-store_emem.lo libkrb5_la-store_fd.lo \
-	libkrb5_la-store_mem.lo libkrb5_la-plugin.lo \
-	libkrb5_la-ticket.lo libkrb5_la-time.lo \
-	libkrb5_la-transited.lo libkrb5_la-v4_glue.lo \
-	libkrb5_la-verify_init.lo libkrb5_la-verify_user.lo \
-	libkrb5_la-version.lo libkrb5_la-warn.lo \
-	libkrb5_la-write_message.lo
+	libkrb5_la-store-int.lo libkrb5_la-store_emem.lo \
+	libkrb5_la-store_fd.lo libkrb5_la-store_mem.lo \
+	libkrb5_la-plugin.lo libkrb5_la-ticket.lo libkrb5_la-time.lo \
+	libkrb5_la-transited.lo libkrb5_la-verify_init.lo \
+	libkrb5_la-verify_user.lo libkrb5_la-version.lo \
+	libkrb5_la-warn.lo libkrb5_la-write_message.lo
 am__objects_1 =3D libkrb5_la-krb5_err.lo libkrb5_la-krb_err.lo \
 	libkrb5_la-heim_err.lo libkrb5_la-k524_err.lo
 nodist_libkrb5_la_OBJECTS =3D $(am__objects_1)
@@ -184,171 +209,251 @@
 libkrb5_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libkrb5_la_LDFLAGS) $(LDFLAGS) -o $@
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
+librfc3961_la_DEPENDENCIES =3D $(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ipc/libheim-ipcc.la \
+	$(top_builddir)/lib/wind/libwind.la $(LIB_pkinit) \
+	$(am__DEPENDENCIES_2) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1)
+am_librfc3961_la_OBJECTS =3D librfc3961_la-crc.lo \
+	librfc3961_la-crypto.lo librfc3961_la-crypto-aes.lo \
+	librfc3961_la-crypto-algs.lo librfc3961_la-crypto-arcfour.lo \
+	librfc3961_la-crypto-des.lo librfc3961_la-crypto-des-common.lo \
+	librfc3961_la-crypto-des3.lo librfc3961_la-crypto-evp.lo \
+	librfc3961_la-crypto-null.lo librfc3961_la-crypto-pk.lo \
+	librfc3961_la-crypto-rand.lo librfc3961_la-crypto-stubs.lo \
+	librfc3961_la-data.lo librfc3961_la-error_string.lo \
+	librfc3961_la-keyblock.lo librfc3961_la-n-fold.lo \
+	librfc3961_la-salt.lo librfc3961_la-salt-aes.lo \
+	librfc3961_la-salt-arcfour.lo librfc3961_la-salt-des.lo \
+	librfc3961_la-salt-des3.lo librfc3961_la-store-int.lo \
+	librfc3961_la-warn.lo
+librfc3961_la_OBJECTS =3D $(am_librfc3961_la_OBJECTS)
 am__EXEEXT_1 =3D aes-test$(EXEEXT) derived-key-test$(EXEEXT) \
-	n-fold-test$(EXEEXT) name-45-test$(EXEEXT) \
-	parse-name-test$(EXEEXT) store-test$(EXEEXT) \
-	string-to-key-test$(EXEEXT) test_acl$(EXEEXT) \
-	test_addr$(EXEEXT) test_cc$(EXEEXT) test_config$(EXEEXT) \
-	test_prf$(EXEEXT) test_store$(EXEEXT) \
-	test_crypto_wrapping$(EXEEXT) test_keytab$(EXEEXT) \
-	test_mem$(EXEEXT) test_pac$(EXEEXT) test_plugin$(EXEEXT) \
-	test_princ$(EXEEXT) test_pkinit_dh2key$(EXEEXT) \
-	test_time$(EXEEXT)
+	n-fold-test$(EXEEXT) parse-name-test$(EXEEXT) \
+	store-test$(EXEEXT) string-to-key-test$(EXEEXT) \
+	test_acl$(EXEEXT) test_addr$(EXEEXT) test_cc$(EXEEXT) \
+	test_config$(EXEEXT) test_fx$(EXEEXT) test_prf$(EXEEXT) \
+	test_store$(EXEEXT) test_crypto_wrapping$(EXEEXT) \
+	test_keytab$(EXEEXT) test_mem$(EXEEXT) test_pac$(EXEEXT) \
+	test_plugin$(EXEEXT) test_princ$(EXEEXT) \
+	test_pkinit_dh2key$(EXEEXT) test_pknistkdf$(EXEEXT) \
+	test_time$(EXEEXT) test_x500$(EXEEXT)
 PROGRAMS =3D $(bin_PROGRAMS) $(noinst_PROGRAMS)
 aes_test_SOURCES =3D aes-test.c
 aes_test_OBJECTS =3D aes-test.$(OBJEXT)
 aes_test_LDADD =3D $(LDADD)
 aes_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 derived_key_test_SOURCES =3D derived-key-test.c
 derived_key_test_OBJECTS =3D derived-key-test.$(OBJEXT)
 derived_key_test_LDADD =3D $(LDADD)
 derived_key_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 krbhst_test_SOURCES =3D krbhst-test.c
 krbhst_test_OBJECTS =3D krbhst-test.$(OBJEXT)
 krbhst_test_LDADD =3D $(LDADD)
 krbhst_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 n_fold_test_SOURCES =3D n-fold-test.c
 n_fold_test_OBJECTS =3D n-fold-test.$(OBJEXT)
 n_fold_test_LDADD =3D $(LDADD)
 n_fold_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
-name_45_test_SOURCES =3D name-45-test.c
-name_45_test_OBJECTS =3D name-45-test.$(OBJEXT)
-name_45_test_LDADD =3D $(LDADD)
-name_45_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 parse_name_test_SOURCES =3D parse-name-test.c
 parse_name_test_OBJECTS =3D parse-name-test.$(OBJEXT)
 parse_name_test_LDADD =3D $(LDADD)
 parse_name_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 store_test_SOURCES =3D store-test.c
 store_test_OBJECTS =3D store-test.$(OBJEXT)
 store_test_LDADD =3D $(LDADD)
 store_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 string_to_key_test_SOURCES =3D string-to-key-test.c
 string_to_key_test_OBJECTS =3D string-to-key-test.$(OBJEXT)
 string_to_key_test_LDADD =3D $(LDADD)
 string_to_key_test_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_acl_SOURCES =3D test_acl.c
 test_acl_OBJECTS =3D test_acl.$(OBJEXT)
 test_acl_LDADD =3D $(LDADD)
 test_acl_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_addr_SOURCES =3D test_addr.c
 test_addr_OBJECTS =3D test_addr.$(OBJEXT)
 test_addr_LDADD =3D $(LDADD)
 test_addr_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_alname_SOURCES =3D test_alname.c
 test_alname_OBJECTS =3D test_alname.$(OBJEXT)
 test_alname_LDADD =3D $(LDADD)
 test_alname_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
+test_ap_req_SOURCES =3D test_ap-req.c
+test_ap_req_OBJECTS =3D test_ap-req.$(OBJEXT)
+test_ap_req_LDADD =3D $(LDADD)
+test_ap_req_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_cc_SOURCES =3D test_cc.c
 test_cc_OBJECTS =3D test_cc.$(OBJEXT)
 test_cc_LDADD =3D $(LDADD)
 test_cc_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_config_SOURCES =3D test_config.c
 test_config_OBJECTS =3D test_config.$(OBJEXT)
 test_config_LDADD =3D $(LDADD)
 test_config_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_crypto_SOURCES =3D test_crypto.c
 test_crypto_OBJECTS =3D test_crypto.$(OBJEXT)
 test_crypto_LDADD =3D $(LDADD)
 test_crypto_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_crypto_wrapping_SOURCES =3D test_crypto_wrapping.c
 test_crypto_wrapping_OBJECTS =3D test_crypto_wrapping.$(OBJEXT)
 test_crypto_wrapping_LDADD =3D $(LDADD)
 test_crypto_wrapping_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_forward_SOURCES =3D test_forward.c
 test_forward_OBJECTS =3D test_forward.$(OBJEXT)
 test_forward_LDADD =3D $(LDADD)
 test_forward_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
+test_fx_SOURCES =3D test_fx.c
+test_fx_OBJECTS =3D test_fx.$(OBJEXT)
+test_fx_LDADD =3D $(LDADD)
+test_fx_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_get_addrs_SOURCES =3D test_get_addrs.c
 test_get_addrs_OBJECTS =3D test_get_addrs.$(OBJEXT)
 test_get_addrs_LDADD =3D $(LDADD)
 test_get_addrs_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
+test_gic_SOURCES =3D test_gic.c
+test_gic_OBJECTS =3D test_gic.$(OBJEXT)
+test_gic_LDADD =3D $(LDADD)
+test_gic_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_hostname_SOURCES =3D test_hostname.c
 test_hostname_OBJECTS =3D test_hostname.$(OBJEXT)
 test_hostname_LDADD =3D $(LDADD)
 test_hostname_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_keytab_SOURCES =3D test_keytab.c
 test_keytab_OBJECTS =3D test_keytab.$(OBJEXT)
 test_keytab_LDADD =3D $(LDADD)
 test_keytab_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_kuserok_SOURCES =3D test_kuserok.c
 test_kuserok_OBJECTS =3D test_kuserok.$(OBJEXT)
 test_kuserok_LDADD =3D $(LDADD)
 test_kuserok_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_mem_SOURCES =3D test_mem.c
 test_mem_OBJECTS =3D test_mem.$(OBJEXT)
 test_mem_LDADD =3D $(LDADD)
 test_mem_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_pac_SOURCES =3D test_pac.c
 test_pac_OBJECTS =3D test_pac.$(OBJEXT)
 test_pac_LDADD =3D $(LDADD)
 test_pac_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_pkinit_dh2key_SOURCES =3D test_pkinit_dh2key.c
 test_pkinit_dh2key_OBJECTS =3D test_pkinit_dh2key.$(OBJEXT)
 test_pkinit_dh2key_LDADD =3D $(LDADD)
 test_pkinit_dh2key_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
+test_pknistkdf_SOURCES =3D test_pknistkdf.c
+test_pknistkdf_OBJECTS =3D test_pknistkdf.$(OBJEXT)
+test_pknistkdf_LDADD =3D $(LDADD)
+test_pknistkdf_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_plugin_SOURCES =3D test_plugin.c
 test_plugin_OBJECTS =3D test_plugin.$(OBJEXT)
 test_plugin_LDADD =3D $(LDADD)
 test_plugin_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_prf_SOURCES =3D test_prf.c
 test_prf_OBJECTS =3D test_prf.$(OBJEXT)
 test_prf_LDADD =3D $(LDADD)
 test_prf_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_princ_SOURCES =3D test_princ.c
 test_princ_OBJECTS =3D test_princ.$(OBJEXT)
 test_princ_LDADD =3D $(LDADD)
 test_princ_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_renew_SOURCES =3D test_renew.c
 test_renew_OBJECTS =3D test_renew.$(OBJEXT)
 test_renew_LDADD =3D $(LDADD)
 test_renew_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
+test_rfc3961_SOURCES =3D test_rfc3961.c
+test_rfc3961_OBJECTS =3D test_rfc3961.$(OBJEXT)
+test_rfc3961_DEPENDENCIES =3D librfc3961.la \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
 test_store_SOURCES =3D test_store.c
 test_store_OBJECTS =3D test_store.$(OBJEXT)
 test_store_LDADD =3D $(LDADD)
 test_store_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 test_time_SOURCES =3D test_time.c
 test_time_OBJECTS =3D test_time.$(OBJEXT)
 test_time_LDADD =3D $(LDADD)
 test_time_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
+test_x500_SOURCES =3D test_x500.c
+test_x500_OBJECTS =3D test_x500.$(OBJEXT)
+test_x500_LDADD =3D $(LDADD)
+test_x500_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
 verify_krb5_conf_SOURCES =3D verify_krb5_conf.c
 verify_krb5_conf_OBJECTS =3D verify_krb5_conf.$(OBJEXT)
 verify_krb5_conf_LDADD =3D $(LDADD)
 verify_krb5_conf_DEPENDENCIES =3D libkrb5.la $(am__DEPENDENCIES_1) \
-	$(top_builddir)/lib/asn1/libasn1.la $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -359,82 +464,93 @@
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
 SOURCES =3D $(dist_libkrb5_la_SOURCES) $(nodist_libkrb5_la_SOURCES) \
+	$(librfc3961_la_SOURCES) aes-test.c derived-key-test.c \
+	krbhst-test.c n-fold-test.c parse-name-test.c store-test.c \
+	string-to-key-test.c test_acl.c test_addr.c test_alname.c \
+	test_ap-req.c test_cc.c test_config.c test_crypto.c \
+	test_crypto_wrapping.c test_forward.c test_fx.c \
+	test_get_addrs.c test_gic.c test_hostname.c test_keytab.c \
+	test_kuserok.c test_mem.c test_pac.c test_pkinit_dh2key.c \
+	test_pknistkdf.c test_plugin.c test_prf.c test_princ.c \
+	test_renew.c test_rfc3961.c test_store.c test_time.c \
+	test_x500.c verify_krb5_conf.c
+DIST_SOURCES =3D $(dist_libkrb5_la_SOURCES) $(librfc3961_la_SOURCES) \
 	aes-test.c derived-key-test.c krbhst-test.c n-fold-test.c \
-	name-45-test.c parse-name-test.c store-test.c \
-	string-to-key-test.c test_acl.c test_addr.c test_alname.c \
-	test_cc.c test_config.c test_crypto.c test_crypto_wrapping.c \
-	test_forward.c test_get_addrs.c test_hostname.c test_keytab.c \
-	test_kuserok.c test_mem.c test_pac.c test_pkinit_dh2key.c \
-	test_plugin.c test_prf.c test_princ.c test_renew.c \
-	test_store.c test_time.c verify_krb5_conf.c
-DIST_SOURCES =3D $(dist_libkrb5_la_SOURCES) aes-test.c \
-	derived-key-test.c krbhst-test.c n-fold-test.c name-45-test.c \
 	parse-name-test.c store-test.c string-to-key-test.c test_acl.c \
-	test_addr.c test_alname.c test_cc.c test_config.c \
-	test_crypto.c test_crypto_wrapping.c test_forward.c \
-	test_get_addrs.c test_hostname.c test_keytab.c test_kuserok.c \
-	test_mem.c test_pac.c test_pkinit_dh2key.c test_plugin.c \
-	test_prf.c test_princ.c test_renew.c test_store.c test_time.c \
-	verify_krb5_conf.c
+	test_addr.c test_alname.c test_ap-req.c test_cc.c \
+	test_config.c test_crypto.c test_crypto_wrapping.c \
+	test_forward.c test_fx.c test_get_addrs.c test_gic.c \
+	test_hostname.c test_keytab.c test_kuserok.c test_mem.c \
+	test_pac.c test_pkinit_dh2key.c test_pknistkdf.c test_plugin.c \
+	test_prf.c test_princ.c test_renew.c test_rfc3961.c \
+	test_store.c test_time.c test_x500.c verify_krb5_conf.c
 man3dir =3D $(mandir)/man3
 man5dir =3D $(mandir)/man5
 man8dir =3D $(mandir)/man8
 MANS =3D $(man_MANS)
-dist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-krb5HEADERS_INSTALL =3D $(INSTALL_HEADER)
-nodist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
 HEADERS =3D $(dist_include_HEADERS) $(krb5_HEADERS) \
 	$(nodist_include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -458,10 +574,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -478,6 +595,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -493,31 +612,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -532,10 +665,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -576,50 +711,90 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(INCLUDE_krb4) $(INCLUDE_hcrypto) -I../com_err \
-	-I$(srcdir)/../com_err
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_krb4) $(INCLUDE_hcrypto) \
+	-I../com_err -I$(srcdir)/../com_err $(INCLUDE_sqlite3) \
+	$(INCLUDE_libintl)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
+noinst_LTLIBRARIES =3D \
+	librfc3961.la
+
+check_DATA =3D test_config_strings.out
 LDADD =3D libkrb5.la \
 	$(LIB_hcrypto) \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/wind/libwind.la \
 	$(LIB_roken)
=20
 @PKINIT_TRUE at LIB_pkinit =3D ../hx509/libhx509.la
+ at have_scc_TRUE@use_sqlite =3D $(LIB_sqlite3)
 libkrb5_la_LIBADD =3D \
+	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ipc/libheim-ipcc.la \
+	$(top_builddir)/lib/wind/libwind.la \
+	$(top_builddir)/base/libheimbase.la \
 	$(LIB_pkinit) \
+	$(use_sqlite) \
 	$(LIB_com_err) \
 	$(LIB_hcrypto) \
+	$(LIB_libintl) \
+	$(LIBADD_roken) \
+	$(PTHREAD_LIBADD) \
+	$(LIB_door_create) \
+	$(LIB_dlopen)
+
+librfc3961_la_LIBADD =3D \
 	$(top_builddir)/lib/asn1/libasn1.la \
+	$(top_builddir)/lib/ipc/libheim-ipcc.la \
+	$(top_builddir)/lib/wind/libwind.la \
+	$(LIB_pkinit) \
+	$(use_sqlite) \
+	$(LIB_com_err) \
+	$(LIB_hcrypto) \
+	$(LIB_libintl) \
 	$(LIBADD_roken) \
+	$(PTHREAD_LIBADD) \
 	$(LIB_door_create) \
 	$(LIB_dlopen)
=20
 lib_LTLIBRARIES =3D libkrb5.la
 ERR_FILES =3D krb5_err.c krb_err.c heim_err.c k524_err.c
-libkrb5_la_CPPFLAGS =3D -DBUILD_KRB5_LIB $(AM_CPPFLAGS)
+libkrb5_la_CPPFLAGS =3D \
+	-DBUILD_KRB5_LIB \
+	$(AM_CPPFLAGS) \
+	-DHEIMDAL_LOCALEDIR=3D'"$(localedir)"'
+
+librfc3961_la_CPPFLAGS =3D \
+	-DBUILD_KRB5_LIB \
+	$(AM_CPPFLAGS) \
+	-DHEIMDAL_LOCALEDIR=3D'"$(localedir)"'
+
 dist_libkrb5_la_SOURCES =3D \
 	acache.c				\
 	acl.c					\
@@ -635,7 +810,6 @@
 	changepw.c				\
 	codec.c					\
 	config_file.c				\
-	config_file_netinfo.c			\
 	convert_creds.c				\
 	constants.c				\
 	context.c				\
@@ -643,12 +817,25 @@
 	crc.c					\
 	creds.c					\
 	crypto.c				\
+	crypto.h				\
+	crypto-aes.c				\
+	crypto-algs.c				\
+	crypto-arcfour.c			\
+	crypto-des.c				\
+	crypto-des-common.c			\
+	crypto-des3.c				\
+	crypto-evp.c				\
+	crypto-null.c				\
+	crypto-pk.c				\
+	crypto-rand.c				\
 	doxygen.c				\
 	data.c					\
+	deprecated.c				\
 	digest.c				\
 	eai_to_heim_errno.c			\
 	error_string.c				\
 	expand_hostname.c			\
+	expand_path.c				\
 	fcache.c				\
 	free.c					\
 	free_host_realm.c			\
@@ -661,11 +848,7 @@
 	get_for_creds.c				\
 	get_host_realm.c			\
 	get_in_tkt.c				\
-	get_in_tkt_pw.c				\
-	get_in_tkt_with_keytab.c		\
-	get_in_tkt_with_skey.c			\
 	get_port.c				\
-	heim_threads.h				\
 	init_creds.c				\
 	init_creds_pw.c				\
 	kcm.c					\
@@ -675,7 +858,6 @@
 	keytab_any.c				\
 	keytab_file.c				\
 	keytab_keyfile.c			\
-	keytab_krb4.c				\
 	keytab_memory.c				\
 	krb5_locl.h				\
 	krb5-v4compat.h				\
@@ -696,6 +878,7 @@
 	n-fold.c				\
 	pac.c					\
 	padata.c				\
+	pcache.c				\
 	pkinit.c				\
 	principal.c				\
 	prog_setup.c				\
@@ -709,11 +892,18 @@
 	read_message.c				\
 	recvauth.c				\
 	replay.c				\
+	salt.c					\
+	salt-aes.c				\
+	salt-arcfour.c				\
+	salt-des.c				\
+	salt-des3.c				\
+	scache.c				\
 	send_to_kdc.c				\
 	sendauth.c				\
 	set_default_realm.c			\
 	sock_principal.c			\
 	store.c					\
+	store-int.c				\
 	store-int.h				\
 	store_emem.c				\
 	store_fd.c				\
@@ -722,7 +912,6 @@
 	ticket.c				\
 	time.c					\
 	transited.c				\
-	v4_glue.c				\
 	verify_init.c				\
 	verify_user.c				\
 	version.c				\
@@ -732,32 +921,60 @@
 nodist_libkrb5_la_SOURCES =3D \
 	$(ERR_FILES)
=20
-libkrb5_la_LDFLAGS =3D -version-info 24:0:0 $(am__append_1)
+libkrb5_la_DEPENDENCIES =3D \
+	version-script.map
+
+libkrb5_la_LDFLAGS =3D -version-info 26:0:0 $(am__append_1)
+librfc3961_la_SOURCES =3D \
+	crc.c					\
+	crypto.c				\
+	crypto.h				\
+	crypto-aes.c				\
+	crypto-algs.c				\
+	crypto-arcfour.c			\
+	crypto-des.c				\
+	crypto-des-common.c			\
+	crypto-des3.c				\
+	crypto-evp.c				\
+	crypto-null.c				\
+	crypto-pk.c				\
+	crypto-rand.c				\
+	crypto-stubs.c				\
+	data.c					\
+	error_string.c				\
+	keyblock.c				\
+	n-fold.c				\
+	salt.c					\
+	salt-aes.c				\
+	salt-arcfour.c				\
+	salt-des.c				\
+	salt-des3.c				\
+	store-int.c				\
+	warn.c
+
+test_rfc3961_LDADD =3D \
+	librfc3961.la 				\
+	$(top_builddir)/lib/asn1/libasn1.la	\
+	$(top_builddir)/lib/wind/libwind.la 	\
+	$(LIB_hcrypto)				\
+	$(LIB_roken)
+
 man_MANS =3D \
 	kerberos.8				\
-	krb5.3					\
 	krb5.conf.5				\
 	krb524_convert_creds_kdc.3		\
 	krb5_425_conv_principal.3		\
 	krb5_acl_match_file.3			\
-	krb5_address.3				\
 	krb5_aname_to_localname.3		\
 	krb5_appdefault.3			\
 	krb5_auth_context.3			\
 	krb5_c_make_checksum.3			\
-	krb5_ccache.3				\
 	krb5_check_transited.3			\
-	krb5_compare_creds.3			\
-	krb5_config.3				\
-	krb5_context.3				\
 	krb5_create_checksum.3			\
 	krb5_creds.3				\
-	krb5_crypto_init.3			\
-	krb5_data.3				\
 	krb5_digest.3				\
 	krb5_eai_to_heim_errno.3		\
 	krb5_encrypt.3				\
-	krb5_expand_hostname.3			\
 	krb5_find_padata.3			\
 	krb5_generate_random_block.3		\
 	krb5_get_all_client_addrs.3		\
@@ -770,10 +987,7 @@
 	krb5_getportbyname.3			\
 	krb5_init_context.3			\
 	krb5_is_thread_safe.3			\
-	krb5_keyblock.3				\
-	krb5_keytab.3				\
 	krb5_krbhst_init.3			\
-	krb5_kuserok.3				\
 	krb5_mk_req.3				\
 	krb5_mk_safe.3				\
 	krb5_openlog.3				\
@@ -784,14 +998,10 @@
 	krb5_rd_safe.3				\
 	krb5_set_default_realm.3		\
 	krb5_set_password.3			\
-	krb5_storage.3				\
 	krb5_string_to_key.3			\
-	krb5_ticket.3				\
 	krb5_timeofday.3			\
-	krb5_unparse_name.3			\
 	krb5_verify_init_creds.3		\
 	krb5_verify_user.3			\
-	krb5_warn.3				\
 	verify_krb5_conf.8
=20
 dist_include_HEADERS =3D \
@@ -800,47 +1010,51 @@
 	krb5-private.h \
 	krb5_ccapi.h
=20
-nodist_include_HEADERS =3D krb5_err.h heim_err.h k524_err.h=20
+nodist_include_HEADERS =3D krb5_err.h heim_err.h k524_err.h
=20
 # XXX use nobase_include_HEADERS =3D krb5/locate_plugin.h
 krb5dir =3D $(includedir)/krb5
-krb5_HEADERS =3D locate_plugin.h
+krb5_HEADERS =3D locate_plugin.h send_to_kdc_plugin.h ccache_plugin.h
 build_HEADERZ =3D \
-	heim_threads.h \
 	$(krb5_HEADERS) \
 	krb_err.h
=20
 CLEANFILES =3D \
+	test_config_strings.out \
+	test-store-data \
 	krb5_err.c krb5_err.h \
 	krb_err.c krb_err.h \
 	heim_err.c heim_err.h \
 	k524_err.c k524_err.h
=20
 EXTRA_DIST =3D \
+	NTMakefile \
+	verify_krb5_conf-version.rc \
 	krb5_err.et \
 	krb_err.et \
 	heim_err.et \
 	k524_err.et \
 	$(man_MANS) \
 	version-script.map \
+	test_config_strings.cfg \
 	krb5.moduli
=20
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/krb5/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/krb5/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/krb5/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/krb5/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -858,23 +1072,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -885,50 +1104,80 @@
 	  echo "rm -f \"$${dir}/so_locations\""; \
 	  rm -f "$${dir}/so_locations"; \
 	done
+
+clean-noinstLTLIBRARIES:
+	-test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
+	@list=3D'$(noinst_LTLIBRARIES)'; for p in $$list; do \
+	  dir=3D"`echo $$p | sed -e 's|/[^/]*$$||'`"; \
+	  test "$$dir" !=3D "$$p" || dir=3D.; \
+	  echo "rm -f \"$${dir}/so_locations\""; \
+	  rm -f "$${dir}/so_locations"; \
+	done
 libkrb5.la: $(libkrb5_la_OBJECTS) $(libkrb5_la_DEPENDENCIES)=20
 	$(libkrb5_la_LINK) -rpath $(libdir) $(libkrb5_la_OBJECTS) $(libkrb5_la_LI=
BADD) $(LIBS)
+librfc3961.la: $(librfc3961_la_OBJECTS) $(librfc3961_la_DEPENDENCIES)=20
+	$(LINK)  $(librfc3961_la_OBJECTS) $(librfc3961_la_LIBADD) $(LIBS)
 install-binPROGRAMS: $(bin_PROGRAMS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$di=
r'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || e=
xit $$?; \
+	    } \
+	; done
=20
 uninstall-binPROGRAMS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$(bindir)" || list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 aes-test$(EXEEXT): $(aes_test_OBJECTS) $(aes_test_DEPENDENCIES)=20
 	@rm -f aes-test$(EXEEXT)
 	$(LINK) $(aes_test_OBJECTS) $(aes_test_LDADD) $(LIBS)
@@ -941,9 +1190,6 @@
 n-fold-test$(EXEEXT): $(n_fold_test_OBJECTS) $(n_fold_test_DEPENDENCIES)=20
 	@rm -f n-fold-test$(EXEEXT)
 	$(LINK) $(n_fold_test_OBJECTS) $(n_fold_test_LDADD) $(LIBS)
-name-45-test$(EXEEXT): $(name_45_test_OBJECTS) $(name_45_test_DEPENDENCIES=
)=20
-	@rm -f name-45-test$(EXEEXT)
-	$(LINK) $(name_45_test_OBJECTS) $(name_45_test_LDADD) $(LIBS)
 parse-name-test$(EXEEXT): $(parse_name_test_OBJECTS) $(parse_name_test_DEP=
ENDENCIES)=20
 	@rm -f parse-name-test$(EXEEXT)
 	$(LINK) $(parse_name_test_OBJECTS) $(parse_name_test_LDADD) $(LIBS)
@@ -962,6 +1208,9 @@
 test_alname$(EXEEXT): $(test_alname_OBJECTS) $(test_alname_DEPENDENCIES)=20
 	@rm -f test_alname$(EXEEXT)
 	$(LINK) $(test_alname_OBJECTS) $(test_alname_LDADD) $(LIBS)
+test_ap-req$(EXEEXT): $(test_ap_req_OBJECTS) $(test_ap_req_DEPENDENCIES)=20
+	@rm -f test_ap-req$(EXEEXT)
+	$(LINK) $(test_ap_req_OBJECTS) $(test_ap_req_LDADD) $(LIBS)
 test_cc$(EXEEXT): $(test_cc_OBJECTS) $(test_cc_DEPENDENCIES)=20
 	@rm -f test_cc$(EXEEXT)
 	$(LINK) $(test_cc_OBJECTS) $(test_cc_LDADD) $(LIBS)
@@ -977,9 +1226,15 @@
 test_forward$(EXEEXT): $(test_forward_OBJECTS) $(test_forward_DEPENDENCIES=
)=20
 	@rm -f test_forward$(EXEEXT)
 	$(LINK) $(test_forward_OBJECTS) $(test_forward_LDADD) $(LIBS)
+test_fx$(EXEEXT): $(test_fx_OBJECTS) $(test_fx_DEPENDENCIES)=20
+	@rm -f test_fx$(EXEEXT)
+	$(LINK) $(test_fx_OBJECTS) $(test_fx_LDADD) $(LIBS)
 test_get_addrs$(EXEEXT): $(test_get_addrs_OBJECTS) $(test_get_addrs_DEPEND=
ENCIES)=20
 	@rm -f test_get_addrs$(EXEEXT)
 	$(LINK) $(test_get_addrs_OBJECTS) $(test_get_addrs_LDADD) $(LIBS)
+test_gic$(EXEEXT): $(test_gic_OBJECTS) $(test_gic_DEPENDENCIES)=20
+	@rm -f test_gic$(EXEEXT)
+	$(LINK) $(test_gic_OBJECTS) $(test_gic_LDADD) $(LIBS)
 test_hostname$(EXEEXT): $(test_hostname_OBJECTS) $(test_hostname_DEPENDENC=
IES)=20
 	@rm -f test_hostname$(EXEEXT)
 	$(LINK) $(test_hostname_OBJECTS) $(test_hostname_LDADD) $(LIBS)
@@ -998,6 +1253,9 @@
 test_pkinit_dh2key$(EXEEXT): $(test_pkinit_dh2key_OBJECTS) $(test_pkinit_d=
h2key_DEPENDENCIES)=20
 	@rm -f test_pkinit_dh2key$(EXEEXT)
 	$(LINK) $(test_pkinit_dh2key_OBJECTS) $(test_pkinit_dh2key_LDADD) $(LIBS)
+test_pknistkdf$(EXEEXT): $(test_pknistkdf_OBJECTS) $(test_pknistkdf_DEPEND=
ENCIES)=20
+	@rm -f test_pknistkdf$(EXEEXT)
+	$(LINK) $(test_pknistkdf_OBJECTS) $(test_pknistkdf_LDADD) $(LIBS)
 test_plugin$(EXEEXT): $(test_plugin_OBJECTS) $(test_plugin_DEPENDENCIES)=20
 	@rm -f test_plugin$(EXEEXT)
 	$(LINK) $(test_plugin_OBJECTS) $(test_plugin_LDADD) $(LIBS)
@@ -1010,12 +1268,18 @@
 test_renew$(EXEEXT): $(test_renew_OBJECTS) $(test_renew_DEPENDENCIES)=20
 	@rm -f test_renew$(EXEEXT)
 	$(LINK) $(test_renew_OBJECTS) $(test_renew_LDADD) $(LIBS)
+test_rfc3961$(EXEEXT): $(test_rfc3961_OBJECTS) $(test_rfc3961_DEPENDENCIES=
)=20
+	@rm -f test_rfc3961$(EXEEXT)
+	$(LINK) $(test_rfc3961_OBJECTS) $(test_rfc3961_LDADD) $(LIBS)
 test_store$(EXEEXT): $(test_store_OBJECTS) $(test_store_DEPENDENCIES)=20
 	@rm -f test_store$(EXEEXT)
 	$(LINK) $(test_store_OBJECTS) $(test_store_LDADD) $(LIBS)
 test_time$(EXEEXT): $(test_time_OBJECTS) $(test_time_DEPENDENCIES)=20
 	@rm -f test_time$(EXEEXT)
 	$(LINK) $(test_time_OBJECTS) $(test_time_LDADD) $(LIBS)
+test_x500$(EXEEXT): $(test_x500_OBJECTS) $(test_x500_DEPENDENCIES)=20
+	@rm -f test_x500$(EXEEXT)
+	$(LINK) $(test_x500_OBJECTS) $(test_x500_LDADD) $(LIBS)
 verify_krb5_conf$(EXEEXT): $(verify_krb5_conf_OBJECTS) $(verify_krb5_conf_=
DEPENDENCIES)=20
 	@rm -f verify_krb5_conf$(EXEEXT)
 	$(LINK) $(verify_krb5_conf_OBJECTS) $(verify_krb5_conf_LDADD) $(LIBS)
@@ -1026,577 +1290,1452 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/aes-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/derived-key-test.Po at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/krbhst-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-acache.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-acl.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-add_et_list.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-addr_families.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-aname_to_local=
name.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-appdefault.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-asn1_glue.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-auth_context.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-build_ap_req.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-build_auth.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-cache.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-changepw.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-codec.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-config_file.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-constants.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-context.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-convert_creds.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-copy_host_real=
m.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crc.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-creds.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-aes.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-algs.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-arcfour=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-des-com=
mon.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-des.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-des3.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-evp.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-null.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-pk.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto-rand.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-crypto.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-data.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-deprecated.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-digest.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-doxygen.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-eai_to_heim_er=
rno.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-error_string.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-expand_hostnam=
e.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-expand_path.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-fcache.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-free.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-free_host_real=
m.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-generate_seq_n=
umber.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-generate_subke=
y.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_addrs.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_cred.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_default_pr=
incipal.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_default_re=
alm.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_for_creds.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_host_realm=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_in_tkt.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-get_port.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-heim_err.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-init_creds.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-init_creds_pw.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-k524_err.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-kcm.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-keyblock.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-keytab.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-keytab_any.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-keytab_file.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-keytab_keyfile=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-keytab_memory.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-krb5_err.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-krb_err.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-krbhst.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-kuserok.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-log.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mcache.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-misc.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mit_glue.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mk_error.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mk_priv.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mk_rep.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mk_req.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mk_req_ext.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-mk_safe.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-n-fold.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-net_read.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-net_write.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-pac.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-padata.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-pcache.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-pkinit.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-plugin.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-principal.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-prog_setup.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-prompter_posix=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-rd_cred.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-rd_error.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-rd_priv.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-rd_rep.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-rd_req.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-rd_safe.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-read_message.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-recvauth.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-replay.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-salt-aes.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-salt-arcfour.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-salt-des.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-salt-des3.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-salt.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-scache.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-send_to_kdc.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-sendauth.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-set_default_re=
alm.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-sock_principal=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-store-int.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-store.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-store_emem.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-store_fd.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-store_mem.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-ticket.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-time.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-transited.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-verify_init.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-verify_user.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-version.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-warn.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libkrb5_la-write_message.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crc.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-aes.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-algs=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-arcf=
our.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-des-=
common.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-des.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-des3=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-evp.=
Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-null=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-pk.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-rand=
.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto-stub=
s.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-crypto.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-data.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-error_strin=
g.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-keyblock.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-n-fold.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-salt-aes.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-salt-arcfou=
r.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-salt-des.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-salt-des3.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-salt.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-store-int.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/librfc3961_la-warn.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/n-fold-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/parse-name-test.Po at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/store-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/string-to-key-test.Po at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_acl.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_addr.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_alname.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_ap-req.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_cc.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_config.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_crypto.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_crypto_wrapping.Po at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_forward.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_fx.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_get_addrs.Po at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_gic.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_hostname.Po at am__quot=
e@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_keytab.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_kuserok.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_mem.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_pac.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_pkinit_dh2key.Po at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_pknistkdf.Po at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_plugin.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_prf.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_princ.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_renew.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_rfc3961.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_store.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_time.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_x500.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/verify_krb5_conf.Po at am__q=
uote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 libkrb5_la-acache.lo: acache.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-acache.lo `test -f 'acache.c=
' || echo '$(srcdir)/'`acache.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-acache.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-acache.Tpo -c -o libkrb5_la-acache.lo `te=
st -f 'acache.c' || echo '$(srcdir)/'`acache.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-acache.Tpo $(DEPDIR)/l=
ibkrb5_la-acache.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'acache.c' object=3D'libkrb5_la=
-acache.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-acache=
.lo `test -f 'acache.c' || echo '$(srcdir)/'`acache.c
=20
 libkrb5_la-acl.lo: acl.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-acl.lo `test -f 'acl.c' || e=
cho '$(srcdir)/'`acl.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-acl.lo -M=
D -MP -MF $(DEPDIR)/libkrb5_la-acl.Tpo -c -o libkrb5_la-acl.lo `test -f 'ac=
l.c' || echo '$(srcdir)/'`acl.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-acl.Tpo $(DEPDIR)/libk=
rb5_la-acl.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'acl.c' object=3D'libkrb5_la-ac=
l.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-acl.lo=
 `test -f 'acl.c' || echo '$(srcdir)/'`acl.c
=20
 libkrb5_la-add_et_list.lo: add_et_list.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-add_et_list.lo `test -f 'add=
_et_list.c' || echo '$(srcdir)/'`add_et_list.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-add_et_li=
st.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-add_et_list.Tpo -c -o libkrb5_la-add=
_et_list.lo `test -f 'add_et_list.c' || echo '$(srcdir)/'`add_et_list.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-add_et_list.Tpo $(DEPD=
IR)/libkrb5_la-add_et_list.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'add_et_list.c' object=3D'libkr=
b5_la-add_et_list.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-add_et=
_list.lo `test -f 'add_et_list.c' || echo '$(srcdir)/'`add_et_list.c
=20
 libkrb5_la-addr_families.lo: addr_families.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-addr_families.lo `test -f 'a=
ddr_families.c' || echo '$(srcdir)/'`addr_families.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-addr_fami=
lies.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-addr_families.Tpo -c -o libkrb5_la=
-addr_families.lo `test -f 'addr_families.c' || echo '$(srcdir)/'`addr_fami=
lies.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-addr_families.Tpo $(DE=
PDIR)/libkrb5_la-addr_families.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'addr_families.c' object=3D'lib=
krb5_la-addr_families.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-addr_f=
amilies.lo `test -f 'addr_families.c' || echo '$(srcdir)/'`addr_families.c
=20
 libkrb5_la-aname_to_localname.lo: aname_to_localname.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-aname_to_localname.lo `test =
-f 'aname_to_localname.c' || echo '$(srcdir)/'`aname_to_localname.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-aname_to_=
localname.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-aname_to_localname.Tpo -c -o =
libkrb5_la-aname_to_localname.lo `test -f 'aname_to_localname.c' || echo '$=
(srcdir)/'`aname_to_localname.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-aname_to_localname.Tpo=
 $(DEPDIR)/libkrb5_la-aname_to_localname.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'aname_to_localname.c' object=
=3D'libkrb5_la-aname_to_localname.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-aname_=
to_localname.lo `test -f 'aname_to_localname.c' || echo '$(srcdir)/'`aname_=
to_localname.c
=20
 libkrb5_la-appdefault.lo: appdefault.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-appdefault.lo `test -f 'appd=
efault.c' || echo '$(srcdir)/'`appdefault.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-appdefaul=
t.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-appdefault.Tpo -c -o libkrb5_la-appde=
fault.lo `test -f 'appdefault.c' || echo '$(srcdir)/'`appdefault.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-appdefault.Tpo $(DEPDI=
R)/libkrb5_la-appdefault.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'appdefault.c' object=3D'libkrb=
5_la-appdefault.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-appdef=
ault.lo `test -f 'appdefault.c' || echo '$(srcdir)/'`appdefault.c
=20
 libkrb5_la-asn1_glue.lo: asn1_glue.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-asn1_glue.lo `test -f 'asn1_=
glue.c' || echo '$(srcdir)/'`asn1_glue.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-asn1_glue=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-asn1_glue.Tpo -c -o libkrb5_la-asn1_gl=
ue.lo `test -f 'asn1_glue.c' || echo '$(srcdir)/'`asn1_glue.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-asn1_glue.Tpo $(DEPDIR=
)/libkrb5_la-asn1_glue.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'asn1_glue.c' object=3D'libkrb5=
_la-asn1_glue.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-asn1_g=
lue.lo `test -f 'asn1_glue.c' || echo '$(srcdir)/'`asn1_glue.c
=20
 libkrb5_la-auth_context.lo: auth_context.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-auth_context.lo `test -f 'au=
th_context.c' || echo '$(srcdir)/'`auth_context.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-auth_cont=
ext.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-auth_context.Tpo -c -o libkrb5_la-a=
uth_context.lo `test -f 'auth_context.c' || echo '$(srcdir)/'`auth_context.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-auth_context.Tpo $(DEP=
DIR)/libkrb5_la-auth_context.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'auth_context.c' object=3D'libk=
rb5_la-auth_context.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-auth_c=
ontext.lo `test -f 'auth_context.c' || echo '$(srcdir)/'`auth_context.c
=20
 libkrb5_la-build_ap_req.lo: build_ap_req.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-build_ap_req.lo `test -f 'bu=
ild_ap_req.c' || echo '$(srcdir)/'`build_ap_req.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-build_ap_=
req.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-build_ap_req.Tpo -c -o libkrb5_la-b=
uild_ap_req.lo `test -f 'build_ap_req.c' || echo '$(srcdir)/'`build_ap_req.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-build_ap_req.Tpo $(DEP=
DIR)/libkrb5_la-build_ap_req.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'build_ap_req.c' object=3D'libk=
rb5_la-build_ap_req.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-build_=
ap_req.lo `test -f 'build_ap_req.c' || echo '$(srcdir)/'`build_ap_req.c
=20
 libkrb5_la-build_auth.lo: build_auth.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-build_auth.lo `test -f 'buil=
d_auth.c' || echo '$(srcdir)/'`build_auth.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-build_aut=
h.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-build_auth.Tpo -c -o libkrb5_la-build=
_auth.lo `test -f 'build_auth.c' || echo '$(srcdir)/'`build_auth.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-build_auth.Tpo $(DEPDI=
R)/libkrb5_la-build_auth.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'build_auth.c' object=3D'libkrb=
5_la-build_auth.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-build_=
auth.lo `test -f 'build_auth.c' || echo '$(srcdir)/'`build_auth.c
=20
 libkrb5_la-cache.lo: cache.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-cache.lo `test -f 'cache.c' =
|| echo '$(srcdir)/'`cache.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-cache.lo =
-MD -MP -MF $(DEPDIR)/libkrb5_la-cache.Tpo -c -o libkrb5_la-cache.lo `test =
-f 'cache.c' || echo '$(srcdir)/'`cache.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-cache.Tpo $(DEPDIR)/li=
bkrb5_la-cache.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'cache.c' object=3D'libkrb5_la-=
cache.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-cache.=
lo `test -f 'cache.c' || echo '$(srcdir)/'`cache.c
=20
 libkrb5_la-changepw.lo: changepw.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-changepw.lo `test -f 'change=
pw.c' || echo '$(srcdir)/'`changepw.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-changepw.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-changepw.Tpo -c -o libkrb5_la-changepw.=
lo `test -f 'changepw.c' || echo '$(srcdir)/'`changepw.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-changepw.Tpo $(DEPDIR)=
/libkrb5_la-changepw.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'changepw.c' object=3D'libkrb5_=
la-changepw.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-change=
pw.lo `test -f 'changepw.c' || echo '$(srcdir)/'`changepw.c
=20
 libkrb5_la-codec.lo: codec.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-codec.lo `test -f 'codec.c' =
|| echo '$(srcdir)/'`codec.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-codec.lo =
-MD -MP -MF $(DEPDIR)/libkrb5_la-codec.Tpo -c -o libkrb5_la-codec.lo `test =
-f 'codec.c' || echo '$(srcdir)/'`codec.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-codec.Tpo $(DEPDIR)/li=
bkrb5_la-codec.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'codec.c' object=3D'libkrb5_la-=
codec.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-codec.=
lo `test -f 'codec.c' || echo '$(srcdir)/'`codec.c
=20
 libkrb5_la-config_file.lo: config_file.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-config_file.lo `test -f 'con=
fig_file.c' || echo '$(srcdir)/'`config_file.c
-
-libkrb5_la-config_file_netinfo.lo: config_file_netinfo.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-config_file_netinfo.lo `test=
 -f 'config_file_netinfo.c' || echo '$(srcdir)/'`config_file_netinfo.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-config_fi=
le.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-config_file.Tpo -c -o libkrb5_la-con=
fig_file.lo `test -f 'config_file.c' || echo '$(srcdir)/'`config_file.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-config_file.Tpo $(DEPD=
IR)/libkrb5_la-config_file.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'config_file.c' object=3D'libkr=
b5_la-config_file.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-config=
_file.lo `test -f 'config_file.c' || echo '$(srcdir)/'`config_file.c
=20
 libkrb5_la-convert_creds.lo: convert_creds.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-convert_creds.lo `test -f 'c=
onvert_creds.c' || echo '$(srcdir)/'`convert_creds.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-convert_c=
reds.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-convert_creds.Tpo -c -o libkrb5_la=
-convert_creds.lo `test -f 'convert_creds.c' || echo '$(srcdir)/'`convert_c=
reds.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-convert_creds.Tpo $(DE=
PDIR)/libkrb5_la-convert_creds.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'convert_creds.c' object=3D'lib=
krb5_la-convert_creds.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-conver=
t_creds.lo `test -f 'convert_creds.c' || echo '$(srcdir)/'`convert_creds.c
=20
 libkrb5_la-constants.lo: constants.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-constants.lo `test -f 'const=
ants.c' || echo '$(srcdir)/'`constants.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-constants=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-constants.Tpo -c -o libkrb5_la-constan=
ts.lo `test -f 'constants.c' || echo '$(srcdir)/'`constants.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-constants.Tpo $(DEPDIR=
)/libkrb5_la-constants.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'constants.c' object=3D'libkrb5=
_la-constants.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-consta=
nts.lo `test -f 'constants.c' || echo '$(srcdir)/'`constants.c
=20
 libkrb5_la-context.lo: context.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-context.lo `test -f 'context=
.c' || echo '$(srcdir)/'`context.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-context.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-context.Tpo -c -o libkrb5_la-context.lo =
`test -f 'context.c' || echo '$(srcdir)/'`context.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-context.Tpo $(DEPDIR)/=
libkrb5_la-context.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'context.c' object=3D'libkrb5_l=
a-context.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-contex=
t.lo `test -f 'context.c' || echo '$(srcdir)/'`context.c
=20
 libkrb5_la-copy_host_realm.lo: copy_host_realm.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-copy_host_realm.lo `test -f =
'copy_host_realm.c' || echo '$(srcdir)/'`copy_host_realm.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-copy_host=
_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-copy_host_realm.Tpo -c -o libkrb=
5_la-copy_host_realm.lo `test -f 'copy_host_realm.c' || echo '$(srcdir)/'`c=
opy_host_realm.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-copy_host_realm.Tpo $(=
DEPDIR)/libkrb5_la-copy_host_realm.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'copy_host_realm.c' object=3D'l=
ibkrb5_la-copy_host_realm.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-copy_h=
ost_realm.lo `test -f 'copy_host_realm.c' || echo '$(srcdir)/'`copy_host_re=
alm.c
=20
 libkrb5_la-crc.lo: crc.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crc.lo `test -f 'crc.c' || e=
cho '$(srcdir)/'`crc.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crc.lo -M=
D -MP -MF $(DEPDIR)/libkrb5_la-crc.Tpo -c -o libkrb5_la-crc.lo `test -f 'cr=
c.c' || echo '$(srcdir)/'`crc.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crc.Tpo $(DEPDIR)/libk=
rb5_la-crc.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crc.c' object=3D'libkrb5_la-cr=
c.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crc.lo=
 `test -f 'crc.c' || echo '$(srcdir)/'`crc.c
=20
 libkrb5_la-creds.lo: creds.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-creds.lo `test -f 'creds.c' =
|| echo '$(srcdir)/'`creds.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-creds.lo =
-MD -MP -MF $(DEPDIR)/libkrb5_la-creds.Tpo -c -o libkrb5_la-creds.lo `test =
-f 'creds.c' || echo '$(srcdir)/'`creds.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-creds.Tpo $(DEPDIR)/li=
bkrb5_la-creds.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'creds.c' object=3D'libkrb5_la-=
creds.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-creds.=
lo `test -f 'creds.c' || echo '$(srcdir)/'`creds.c
=20
 libkrb5_la-crypto.lo: crypto.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto.lo `test -f 'crypto.c=
' || echo '$(srcdir)/'`crypto.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto.Tpo -c -o libkrb5_la-crypto.lo `te=
st -f 'crypto.c' || echo '$(srcdir)/'`crypto.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto.Tpo $(DEPDIR)/l=
ibkrb5_la-crypto.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto.c' object=3D'libkrb5_la=
-crypto.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c
+
+libkrb5_la-crypto-aes.lo: crypto-aes.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-ae=
s.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-aes.Tpo -c -o libkrb5_la-crypt=
o-aes.lo `test -f 'crypto-aes.c' || echo '$(srcdir)/'`crypto-aes.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-aes.Tpo $(DEPDI=
R)/libkrb5_la-crypto-aes.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-aes.c' object=3D'libkrb=
5_la-crypto-aes.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-aes.lo `test -f 'crypto-aes.c' || echo '$(srcdir)/'`crypto-aes.c
+
+libkrb5_la-crypto-algs.lo: crypto-algs.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-al=
gs.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-algs.Tpo -c -o libkrb5_la-cry=
pto-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypto-algs.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-algs.Tpo $(DEPD=
IR)/libkrb5_la-crypto-algs.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-algs.c' object=3D'libkr=
b5_la-crypto-algs.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypto-algs.c
+
+libkrb5_la-crypto-arcfour.lo: crypto-arcfour.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-ar=
cfour.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-arcfour.Tpo -c -o libkrb5_=
la-crypto-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(srcdir)/'`crypt=
o-arcfour.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-arcfour.Tpo $(D=
EPDIR)/libkrb5_la-crypto-arcfour.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-arcfour.c' object=3D'li=
bkrb5_la-crypto-arcfour.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(srcdir)/'`crypto-arcfour=
.c
+
+libkrb5_la-crypto-des.lo: crypto-des.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-de=
s.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-des.Tpo -c -o libkrb5_la-crypt=
o-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-des.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-des.Tpo $(DEPDI=
R)/libkrb5_la-crypto-des.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-des.c' object=3D'libkrb=
5_la-crypto-des.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-des.c
+
+libkrb5_la-crypto-des-common.lo: crypto-des-common.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-de=
s-common.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-des-common.Tpo -c -o li=
bkrb5_la-crypto-des-common.lo `test -f 'crypto-des-common.c' || echo '$(src=
dir)/'`crypto-des-common.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-des-common.Tpo =
$(DEPDIR)/libkrb5_la-crypto-des-common.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-des-common.c' object=3D=
'libkrb5_la-crypto-des-common.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-des-common.lo `test -f 'crypto-des-common.c' || echo '$(srcdir)/'`crypto-d=
es-common.c
+
+libkrb5_la-crypto-des3.lo: crypto-des3.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-de=
s3.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-des3.Tpo -c -o libkrb5_la-cry=
pto-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypto-des3.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-des3.Tpo $(DEPD=
IR)/libkrb5_la-crypto-des3.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-des3.c' object=3D'libkr=
b5_la-crypto-des3.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypto-des3.c
+
+libkrb5_la-crypto-evp.lo: crypto-evp.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-ev=
p.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-evp.Tpo -c -o libkrb5_la-crypt=
o-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-evp.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-evp.Tpo $(DEPDI=
R)/libkrb5_la-crypto-evp.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-evp.c' object=3D'libkrb=
5_la-crypto-evp.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-evp.c
+
+libkrb5_la-crypto-null.lo: crypto-null.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-nu=
ll.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-null.Tpo -c -o libkrb5_la-cry=
pto-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypto-null.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-null.Tpo $(DEPD=
IR)/libkrb5_la-crypto-null.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-null.c' object=3D'libkr=
b5_la-crypto-null.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypto-null.c
+
+libkrb5_la-crypto-pk.lo: crypto-pk.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-pk=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-pk.Tpo -c -o libkrb5_la-crypto-=
pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-pk.Tpo $(DEPDIR=
)/libkrb5_la-crypto-pk.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-pk.c' object=3D'libkrb5=
_la-crypto-pk.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c
+
+libkrb5_la-crypto-rand.lo: crypto-rand.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-crypto-ra=
nd.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-crypto-rand.Tpo -c -o libkrb5_la-cry=
pto-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypto-rand.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-crypto-rand.Tpo $(DEPD=
IR)/libkrb5_la-crypto-rand.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-rand.c' object=3D'libkr=
b5_la-crypto-rand.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-crypto=
-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypto-rand.c
=20
 libkrb5_la-doxygen.lo: doxygen.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-doxygen.lo `test -f 'doxygen=
.c' || echo '$(srcdir)/'`doxygen.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-doxygen.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-doxygen.Tpo -c -o libkrb5_la-doxygen.lo =
`test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-doxygen.Tpo $(DEPDIR)/=
libkrb5_la-doxygen.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'doxygen.c' object=3D'libkrb5_l=
a-doxygen.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-doxyge=
n.lo `test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c
=20
 libkrb5_la-data.lo: data.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-data.lo `test -f 'data.c' ||=
 echo '$(srcdir)/'`data.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-data.lo -=
MD -MP -MF $(DEPDIR)/libkrb5_la-data.Tpo -c -o libkrb5_la-data.lo `test -f =
'data.c' || echo '$(srcdir)/'`data.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-data.Tpo $(DEPDIR)/lib=
krb5_la-data.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'data.c' object=3D'libkrb5_la-d=
ata.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-data.l=
o `test -f 'data.c' || echo '$(srcdir)/'`data.c
+
+libkrb5_la-deprecated.lo: deprecated.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-deprecate=
d.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-deprecated.Tpo -c -o libkrb5_la-depre=
cated.lo `test -f 'deprecated.c' || echo '$(srcdir)/'`deprecated.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-deprecated.Tpo $(DEPDI=
R)/libkrb5_la-deprecated.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'deprecated.c' object=3D'libkrb=
5_la-deprecated.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-deprec=
ated.lo `test -f 'deprecated.c' || echo '$(srcdir)/'`deprecated.c
=20
 libkrb5_la-digest.lo: digest.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-digest.lo `test -f 'digest.c=
' || echo '$(srcdir)/'`digest.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-digest.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-digest.Tpo -c -o libkrb5_la-digest.lo `te=
st -f 'digest.c' || echo '$(srcdir)/'`digest.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-digest.Tpo $(DEPDIR)/l=
ibkrb5_la-digest.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'digest.c' object=3D'libkrb5_la=
-digest.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-digest=
.lo `test -f 'digest.c' || echo '$(srcdir)/'`digest.c
=20
 libkrb5_la-eai_to_heim_errno.lo: eai_to_heim_errno.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-eai_to_heim_errno.lo `test -=
f 'eai_to_heim_errno.c' || echo '$(srcdir)/'`eai_to_heim_errno.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-eai_to_he=
im_errno.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-eai_to_heim_errno.Tpo -c -o li=
bkrb5_la-eai_to_heim_errno.lo `test -f 'eai_to_heim_errno.c' || echo '$(src=
dir)/'`eai_to_heim_errno.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-eai_to_heim_errno.Tpo =
$(DEPDIR)/libkrb5_la-eai_to_heim_errno.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'eai_to_heim_errno.c' object=3D=
'libkrb5_la-eai_to_heim_errno.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-eai_to=
_heim_errno.lo `test -f 'eai_to_heim_errno.c' || echo '$(srcdir)/'`eai_to_h=
eim_errno.c
=20
 libkrb5_la-error_string.lo: error_string.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-error_string.lo `test -f 'er=
ror_string.c' || echo '$(srcdir)/'`error_string.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-error_str=
ing.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-error_string.Tpo -c -o libkrb5_la-e=
rror_string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`error_string.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-error_string.Tpo $(DEP=
DIR)/libkrb5_la-error_string.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'error_string.c' object=3D'libk=
rb5_la-error_string.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-error_=
string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`error_string.c
=20
 libkrb5_la-expand_hostname.lo: expand_hostname.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-expand_hostname.lo `test -f =
'expand_hostname.c' || echo '$(srcdir)/'`expand_hostname.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-expand_ho=
stname.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-expand_hostname.Tpo -c -o libkrb=
5_la-expand_hostname.lo `test -f 'expand_hostname.c' || echo '$(srcdir)/'`e=
xpand_hostname.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-expand_hostname.Tpo $(=
DEPDIR)/libkrb5_la-expand_hostname.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'expand_hostname.c' object=3D'l=
ibkrb5_la-expand_hostname.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-expand=
_hostname.lo `test -f 'expand_hostname.c' || echo '$(srcdir)/'`expand_hostn=
ame.c
+
+libkrb5_la-expand_path.lo: expand_path.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-expand_pa=
th.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-expand_path.Tpo -c -o libkrb5_la-exp=
and_path.lo `test -f 'expand_path.c' || echo '$(srcdir)/'`expand_path.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-expand_path.Tpo $(DEPD=
IR)/libkrb5_la-expand_path.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'expand_path.c' object=3D'libkr=
b5_la-expand_path.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-expand=
_path.lo `test -f 'expand_path.c' || echo '$(srcdir)/'`expand_path.c
=20
 libkrb5_la-fcache.lo: fcache.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-fcache.lo `test -f 'fcache.c=
' || echo '$(srcdir)/'`fcache.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-fcache.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-fcache.Tpo -c -o libkrb5_la-fcache.lo `te=
st -f 'fcache.c' || echo '$(srcdir)/'`fcache.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-fcache.Tpo $(DEPDIR)/l=
ibkrb5_la-fcache.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'fcache.c' object=3D'libkrb5_la=
-fcache.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-fcache=
.lo `test -f 'fcache.c' || echo '$(srcdir)/'`fcache.c
=20
 libkrb5_la-free.lo: free.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-free.lo `test -f 'free.c' ||=
 echo '$(srcdir)/'`free.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-free.lo -=
MD -MP -MF $(DEPDIR)/libkrb5_la-free.Tpo -c -o libkrb5_la-free.lo `test -f =
'free.c' || echo '$(srcdir)/'`free.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-free.Tpo $(DEPDIR)/lib=
krb5_la-free.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'free.c' object=3D'libkrb5_la-f=
ree.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-free.l=
o `test -f 'free.c' || echo '$(srcdir)/'`free.c
=20
 libkrb5_la-free_host_realm.lo: free_host_realm.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-free_host_realm.lo `test -f =
'free_host_realm.c' || echo '$(srcdir)/'`free_host_realm.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-free_host=
_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-free_host_realm.Tpo -c -o libkrb=
5_la-free_host_realm.lo `test -f 'free_host_realm.c' || echo '$(srcdir)/'`f=
ree_host_realm.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-free_host_realm.Tpo $(=
DEPDIR)/libkrb5_la-free_host_realm.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'free_host_realm.c' object=3D'l=
ibkrb5_la-free_host_realm.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-free_h=
ost_realm.lo `test -f 'free_host_realm.c' || echo '$(srcdir)/'`free_host_re=
alm.c
=20
 libkrb5_la-generate_seq_number.lo: generate_seq_number.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-generate_seq_number.lo `test=
 -f 'generate_seq_number.c' || echo '$(srcdir)/'`generate_seq_number.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-generate_=
seq_number.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-generate_seq_number.Tpo -c -=
o libkrb5_la-generate_seq_number.lo `test -f 'generate_seq_number.c' || ech=
o '$(srcdir)/'`generate_seq_number.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-generate_seq_number.Tp=
o $(DEPDIR)/libkrb5_la-generate_seq_number.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'generate_seq_number.c' object=
=3D'libkrb5_la-generate_seq_number.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-genera=
te_seq_number.lo `test -f 'generate_seq_number.c' || echo '$(srcdir)/'`gene=
rate_seq_number.c
=20
 libkrb5_la-generate_subkey.lo: generate_subkey.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-generate_subkey.lo `test -f =
'generate_subkey.c' || echo '$(srcdir)/'`generate_subkey.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-generate_=
subkey.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-generate_subkey.Tpo -c -o libkrb=
5_la-generate_subkey.lo `test -f 'generate_subkey.c' || echo '$(srcdir)/'`g=
enerate_subkey.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-generate_subkey.Tpo $(=
DEPDIR)/libkrb5_la-generate_subkey.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'generate_subkey.c' object=3D'l=
ibkrb5_la-generate_subkey.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-genera=
te_subkey.lo `test -f 'generate_subkey.c' || echo '$(srcdir)/'`generate_sub=
key.c
=20
 libkrb5_la-get_addrs.lo: get_addrs.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_addrs.lo `test -f 'get_a=
ddrs.c' || echo '$(srcdir)/'`get_addrs.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_addrs=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_addrs.Tpo -c -o libkrb5_la-get_add=
rs.lo `test -f 'get_addrs.c' || echo '$(srcdir)/'`get_addrs.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_addrs.Tpo $(DEPDIR=
)/libkrb5_la-get_addrs.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_addrs.c' object=3D'libkrb5=
_la-get_addrs.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_ad=
drs.lo `test -f 'get_addrs.c' || echo '$(srcdir)/'`get_addrs.c
=20
 libkrb5_la-get_cred.lo: get_cred.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_cred.lo `test -f 'get_cr=
ed.c' || echo '$(srcdir)/'`get_cred.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_cred.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_cred.Tpo -c -o libkrb5_la-get_cred.=
lo `test -f 'get_cred.c' || echo '$(srcdir)/'`get_cred.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_cred.Tpo $(DEPDIR)=
/libkrb5_la-get_cred.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_cred.c' object=3D'libkrb5_=
la-get_cred.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_cr=
ed.lo `test -f 'get_cred.c' || echo '$(srcdir)/'`get_cred.c
=20
 libkrb5_la-get_default_principal.lo: get_default_principal.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_default_principal.lo `te=
st -f 'get_default_principal.c' || echo '$(srcdir)/'`get_default_principal.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_defau=
lt_principal.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_default_principal.Tpo =
-c -o libkrb5_la-get_default_principal.lo `test -f 'get_default_principal.c=
' || echo '$(srcdir)/'`get_default_principal.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_default_principal.=
Tpo $(DEPDIR)/libkrb5_la-get_default_principal.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_default_principal.c' objec=
t=3D'libkrb5_la-get_default_principal.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_de=
fault_principal.lo `test -f 'get_default_principal.c' || echo '$(srcdir)/'`=
get_default_principal.c
=20
 libkrb5_la-get_default_realm.lo: get_default_realm.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_default_realm.lo `test -=
f 'get_default_realm.c' || echo '$(srcdir)/'`get_default_realm.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_defau=
lt_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_default_realm.Tpo -c -o li=
bkrb5_la-get_default_realm.lo `test -f 'get_default_realm.c' || echo '$(src=
dir)/'`get_default_realm.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_default_realm.Tpo =
$(DEPDIR)/libkrb5_la-get_default_realm.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_default_realm.c' object=3D=
'libkrb5_la-get_default_realm.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_de=
fault_realm.lo `test -f 'get_default_realm.c' || echo '$(srcdir)/'`get_defa=
ult_realm.c
=20
 libkrb5_la-get_for_creds.lo: get_for_creds.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_for_creds.lo `test -f 'g=
et_for_creds.c' || echo '$(srcdir)/'`get_for_creds.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_for_c=
reds.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_for_creds.Tpo -c -o libkrb5_la=
-get_for_creds.lo `test -f 'get_for_creds.c' || echo '$(srcdir)/'`get_for_c=
reds.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_for_creds.Tpo $(DE=
PDIR)/libkrb5_la-get_for_creds.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_for_creds.c' object=3D'lib=
krb5_la-get_for_creds.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_fo=
r_creds.lo `test -f 'get_for_creds.c' || echo '$(srcdir)/'`get_for_creds.c
=20
 libkrb5_la-get_host_realm.lo: get_host_realm.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_host_realm.lo `test -f '=
get_host_realm.c' || echo '$(srcdir)/'`get_host_realm.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_host_=
realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_host_realm.Tpo -c -o libkrb5_=
la-get_host_realm.lo `test -f 'get_host_realm.c' || echo '$(srcdir)/'`get_h=
ost_realm.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_host_realm.Tpo $(D=
EPDIR)/libkrb5_la-get_host_realm.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_host_realm.c' object=3D'li=
bkrb5_la-get_host_realm.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_ho=
st_realm.lo `test -f 'get_host_realm.c' || echo '$(srcdir)/'`get_host_realm=
.c
=20
 libkrb5_la-get_in_tkt.lo: get_in_tkt.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_in_tkt.lo `test -f 'get_=
in_tkt.c' || echo '$(srcdir)/'`get_in_tkt.c
-
-libkrb5_la-get_in_tkt_pw.lo: get_in_tkt_pw.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_in_tkt_pw.lo `test -f 'g=
et_in_tkt_pw.c' || echo '$(srcdir)/'`get_in_tkt_pw.c
-
-libkrb5_la-get_in_tkt_with_keytab.lo: get_in_tkt_with_keytab.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_in_tkt_with_keytab.lo `t=
est -f 'get_in_tkt_with_keytab.c' || echo '$(srcdir)/'`get_in_tkt_with_keyt=
ab.c
-
-libkrb5_la-get_in_tkt_with_skey.lo: get_in_tkt_with_skey.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_in_tkt_with_skey.lo `tes=
t -f 'get_in_tkt_with_skey.c' || echo '$(srcdir)/'`get_in_tkt_with_skey.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_in_tk=
t.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_in_tkt.Tpo -c -o libkrb5_la-get_i=
n_tkt.lo `test -f 'get_in_tkt.c' || echo '$(srcdir)/'`get_in_tkt.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_in_tkt.Tpo $(DEPDI=
R)/libkrb5_la-get_in_tkt.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_in_tkt.c' object=3D'libkrb=
5_la-get_in_tkt.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_in=
_tkt.lo `test -f 'get_in_tkt.c' || echo '$(srcdir)/'`get_in_tkt.c
=20
 libkrb5_la-get_port.lo: get_port.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_port.lo `test -f 'get_po=
rt.c' || echo '$(srcdir)/'`get_port.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-get_port.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-get_port.Tpo -c -o libkrb5_la-get_port.=
lo `test -f 'get_port.c' || echo '$(srcdir)/'`get_port.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-get_port.Tpo $(DEPDIR)=
/libkrb5_la-get_port.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_port.c' object=3D'libkrb5_=
la-get_port.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-get_po=
rt.lo `test -f 'get_port.c' || echo '$(srcdir)/'`get_port.c
=20
 libkrb5_la-init_creds.lo: init_creds.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-init_creds.lo `test -f 'init=
_creds.c' || echo '$(srcdir)/'`init_creds.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-init_cred=
s.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-init_creds.Tpo -c -o libkrb5_la-init_=
creds.lo `test -f 'init_creds.c' || echo '$(srcdir)/'`init_creds.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-init_creds.Tpo $(DEPDI=
R)/libkrb5_la-init_creds.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'init_creds.c' object=3D'libkrb=
5_la-init_creds.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-init_c=
reds.lo `test -f 'init_creds.c' || echo '$(srcdir)/'`init_creds.c
=20
 libkrb5_la-init_creds_pw.lo: init_creds_pw.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-init_creds_pw.lo `test -f 'i=
nit_creds_pw.c' || echo '$(srcdir)/'`init_creds_pw.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-init_cred=
s_pw.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-init_creds_pw.Tpo -c -o libkrb5_la=
-init_creds_pw.lo `test -f 'init_creds_pw.c' || echo '$(srcdir)/'`init_cred=
s_pw.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-init_creds_pw.Tpo $(DE=
PDIR)/libkrb5_la-init_creds_pw.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'init_creds_pw.c' object=3D'lib=
krb5_la-init_creds_pw.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-init_c=
reds_pw.lo `test -f 'init_creds_pw.c' || echo '$(srcdir)/'`init_creds_pw.c
=20
 libkrb5_la-kcm.lo: kcm.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-kcm.lo `test -f 'kcm.c' || e=
cho '$(srcdir)/'`kcm.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-kcm.lo -M=
D -MP -MF $(DEPDIR)/libkrb5_la-kcm.Tpo -c -o libkrb5_la-kcm.lo `test -f 'kc=
m.c' || echo '$(srcdir)/'`kcm.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-kcm.Tpo $(DEPDIR)/libk=
rb5_la-kcm.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'kcm.c' object=3D'libkrb5_la-kc=
m.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-kcm.lo=
 `test -f 'kcm.c' || echo '$(srcdir)/'`kcm.c
=20
 libkrb5_la-keyblock.lo: keyblock.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keyblock.lo `test -f 'keyblo=
ck.c' || echo '$(srcdir)/'`keyblock.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keyblock.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keyblock.Tpo -c -o libkrb5_la-keyblock.=
lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-keyblock.Tpo $(DEPDIR)=
/libkrb5_la-keyblock.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keyblock.c' object=3D'libkrb5_=
la-keyblock.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keyblo=
ck.lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c
=20
 libkrb5_la-keytab.lo: keytab.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab.lo `test -f 'keytab.c=
' || echo '$(srcdir)/'`keytab.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab.Tpo -c -o libkrb5_la-keytab.lo `te=
st -f 'keytab.c' || echo '$(srcdir)/'`keytab.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-keytab.Tpo $(DEPDIR)/l=
ibkrb5_la-keytab.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keytab.c' object=3D'libkrb5_la=
-keytab.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab=
.lo `test -f 'keytab.c' || echo '$(srcdir)/'`keytab.c
=20
 libkrb5_la-keytab_any.lo: keytab_any.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_any.lo `test -f 'keyt=
ab_any.c' || echo '$(srcdir)/'`keytab_any.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_an=
y.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_any.Tpo -c -o libkrb5_la-keyta=
b_any.lo `test -f 'keytab_any.c' || echo '$(srcdir)/'`keytab_any.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-keytab_any.Tpo $(DEPDI=
R)/libkrb5_la-keytab_any.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keytab_any.c' object=3D'libkrb=
5_la-keytab_any.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab=
_any.lo `test -f 'keytab_any.c' || echo '$(srcdir)/'`keytab_any.c
=20
 libkrb5_la-keytab_file.lo: keytab_file.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_file.lo `test -f 'key=
tab_file.c' || echo '$(srcdir)/'`keytab_file.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_fi=
le.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_file.Tpo -c -o libkrb5_la-key=
tab_file.lo `test -f 'keytab_file.c' || echo '$(srcdir)/'`keytab_file.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-keytab_file.Tpo $(DEPD=
IR)/libkrb5_la-keytab_file.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keytab_file.c' object=3D'libkr=
b5_la-keytab_file.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab=
_file.lo `test -f 'keytab_file.c' || echo '$(srcdir)/'`keytab_file.c
=20
 libkrb5_la-keytab_keyfile.lo: keytab_keyfile.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_keyfile.lo `test -f '=
keytab_keyfile.c' || echo '$(srcdir)/'`keytab_keyfile.c
-
-libkrb5_la-keytab_krb4.lo: keytab_krb4.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_krb4.lo `test -f 'key=
tab_krb4.c' || echo '$(srcdir)/'`keytab_krb4.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_ke=
yfile.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_keyfile.Tpo -c -o libkrb5_=
la-keytab_keyfile.lo `test -f 'keytab_keyfile.c' || echo '$(srcdir)/'`keyta=
b_keyfile.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-keytab_keyfile.Tpo $(D=
EPDIR)/libkrb5_la-keytab_keyfile.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keytab_keyfile.c' object=3D'li=
bkrb5_la-keytab_keyfile.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab=
_keyfile.lo `test -f 'keytab_keyfile.c' || echo '$(srcdir)/'`keytab_keyfile=
.c
=20
 libkrb5_la-keytab_memory.lo: keytab_memory.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab_memory.lo `test -f 'k=
eytab_memory.c' || echo '$(srcdir)/'`keytab_memory.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-keytab_me=
mory.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-keytab_memory.Tpo -c -o libkrb5_la=
-keytab_memory.lo `test -f 'keytab_memory.c' || echo '$(srcdir)/'`keytab_me=
mory.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-keytab_memory.Tpo $(DE=
PDIR)/libkrb5_la-keytab_memory.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keytab_memory.c' object=3D'lib=
krb5_la-keytab_memory.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-keytab=
_memory.lo `test -f 'keytab_memory.c' || echo '$(srcdir)/'`keytab_memory.c
=20
 libkrb5_la-krbhst.lo: krbhst.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krbhst.lo `test -f 'krbhst.c=
' || echo '$(srcdir)/'`krbhst.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-krbhst.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-krbhst.Tpo -c -o libkrb5_la-krbhst.lo `te=
st -f 'krbhst.c' || echo '$(srcdir)/'`krbhst.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-krbhst.Tpo $(DEPDIR)/l=
ibkrb5_la-krbhst.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'krbhst.c' object=3D'libkrb5_la=
-krbhst.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krbhst=
.lo `test -f 'krbhst.c' || echo '$(srcdir)/'`krbhst.c
=20
 libkrb5_la-kuserok.lo: kuserok.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-kuserok.lo `test -f 'kuserok=
.c' || echo '$(srcdir)/'`kuserok.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-kuserok.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-kuserok.Tpo -c -o libkrb5_la-kuserok.lo =
`test -f 'kuserok.c' || echo '$(srcdir)/'`kuserok.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-kuserok.Tpo $(DEPDIR)/=
libkrb5_la-kuserok.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'kuserok.c' object=3D'libkrb5_l=
a-kuserok.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-kusero=
k.lo `test -f 'kuserok.c' || echo '$(srcdir)/'`kuserok.c
=20
 libkrb5_la-log.lo: log.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-log.lo `test -f 'log.c' || e=
cho '$(srcdir)/'`log.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-log.lo -M=
D -MP -MF $(DEPDIR)/libkrb5_la-log.Tpo -c -o libkrb5_la-log.lo `test -f 'lo=
g.c' || echo '$(srcdir)/'`log.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-log.Tpo $(DEPDIR)/libk=
rb5_la-log.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'log.c' object=3D'libkrb5_la-lo=
g.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-log.lo=
 `test -f 'log.c' || echo '$(srcdir)/'`log.c
=20
 libkrb5_la-mcache.lo: mcache.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mcache.lo `test -f 'mcache.c=
' || echo '$(srcdir)/'`mcache.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mcache.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-mcache.Tpo -c -o libkrb5_la-mcache.lo `te=
st -f 'mcache.c' || echo '$(srcdir)/'`mcache.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mcache.Tpo $(DEPDIR)/l=
ibkrb5_la-mcache.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mcache.c' object=3D'libkrb5_la=
-mcache.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mcache=
.lo `test -f 'mcache.c' || echo '$(srcdir)/'`mcache.c
=20
 libkrb5_la-misc.lo: misc.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-misc.lo `test -f 'misc.c' ||=
 echo '$(srcdir)/'`misc.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-misc.lo -=
MD -MP -MF $(DEPDIR)/libkrb5_la-misc.Tpo -c -o libkrb5_la-misc.lo `test -f =
'misc.c' || echo '$(srcdir)/'`misc.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-misc.Tpo $(DEPDIR)/lib=
krb5_la-misc.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'misc.c' object=3D'libkrb5_la-m=
isc.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-misc.l=
o `test -f 'misc.c' || echo '$(srcdir)/'`misc.c
=20
 libkrb5_la-mk_error.lo: mk_error.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_error.lo `test -f 'mk_err=
or.c' || echo '$(srcdir)/'`mk_error.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_error.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_error.Tpo -c -o libkrb5_la-mk_error.=
lo `test -f 'mk_error.c' || echo '$(srcdir)/'`mk_error.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mk_error.Tpo $(DEPDIR)=
/libkrb5_la-mk_error.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mk_error.c' object=3D'libkrb5_=
la-mk_error.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_err=
or.lo `test -f 'mk_error.c' || echo '$(srcdir)/'`mk_error.c
=20
 libkrb5_la-mk_priv.lo: mk_priv.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_priv.lo `test -f 'mk_priv=
.c' || echo '$(srcdir)/'`mk_priv.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_priv.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_priv.Tpo -c -o libkrb5_la-mk_priv.lo =
`test -f 'mk_priv.c' || echo '$(srcdir)/'`mk_priv.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mk_priv.Tpo $(DEPDIR)/=
libkrb5_la-mk_priv.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mk_priv.c' object=3D'libkrb5_l=
a-mk_priv.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_pri=
v.lo `test -f 'mk_priv.c' || echo '$(srcdir)/'`mk_priv.c
=20
 libkrb5_la-mk_rep.lo: mk_rep.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_rep.lo `test -f 'mk_rep.c=
' || echo '$(srcdir)/'`mk_rep.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_rep.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_rep.Tpo -c -o libkrb5_la-mk_rep.lo `te=
st -f 'mk_rep.c' || echo '$(srcdir)/'`mk_rep.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mk_rep.Tpo $(DEPDIR)/l=
ibkrb5_la-mk_rep.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mk_rep.c' object=3D'libkrb5_la=
-mk_rep.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_rep=
.lo `test -f 'mk_rep.c' || echo '$(srcdir)/'`mk_rep.c
=20
 libkrb5_la-mk_req.lo: mk_req.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_req.lo `test -f 'mk_req.c=
' || echo '$(srcdir)/'`mk_req.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_req.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_req.Tpo -c -o libkrb5_la-mk_req.lo `te=
st -f 'mk_req.c' || echo '$(srcdir)/'`mk_req.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mk_req.Tpo $(DEPDIR)/l=
ibkrb5_la-mk_req.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mk_req.c' object=3D'libkrb5_la=
-mk_req.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_req=
.lo `test -f 'mk_req.c' || echo '$(srcdir)/'`mk_req.c
=20
 libkrb5_la-mk_req_ext.lo: mk_req_ext.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_req_ext.lo `test -f 'mk_r=
eq_ext.c' || echo '$(srcdir)/'`mk_req_ext.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_req_ex=
t.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_req_ext.Tpo -c -o libkrb5_la-mk_re=
q_ext.lo `test -f 'mk_req_ext.c' || echo '$(srcdir)/'`mk_req_ext.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mk_req_ext.Tpo $(DEPDI=
R)/libkrb5_la-mk_req_ext.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mk_req_ext.c' object=3D'libkrb=
5_la-mk_req_ext.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_req=
_ext.lo `test -f 'mk_req_ext.c' || echo '$(srcdir)/'`mk_req_ext.c
=20
 libkrb5_la-mk_safe.lo: mk_safe.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_safe.lo `test -f 'mk_safe=
.c' || echo '$(srcdir)/'`mk_safe.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mk_safe.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-mk_safe.Tpo -c -o libkrb5_la-mk_safe.lo =
`test -f 'mk_safe.c' || echo '$(srcdir)/'`mk_safe.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mk_safe.Tpo $(DEPDIR)/=
libkrb5_la-mk_safe.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mk_safe.c' object=3D'libkrb5_l=
a-mk_safe.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mk_saf=
e.lo `test -f 'mk_safe.c' || echo '$(srcdir)/'`mk_safe.c
=20
 libkrb5_la-mit_glue.lo: mit_glue.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mit_glue.lo `test -f 'mit_gl=
ue.c' || echo '$(srcdir)/'`mit_glue.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-mit_glue.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-mit_glue.Tpo -c -o libkrb5_la-mit_glue.=
lo `test -f 'mit_glue.c' || echo '$(srcdir)/'`mit_glue.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-mit_glue.Tpo $(DEPDIR)=
/libkrb5_la-mit_glue.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mit_glue.c' object=3D'libkrb5_=
la-mit_glue.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-mit_gl=
ue.lo `test -f 'mit_glue.c' || echo '$(srcdir)/'`mit_glue.c
=20
 libkrb5_la-net_read.lo: net_read.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-net_read.lo `test -f 'net_re=
ad.c' || echo '$(srcdir)/'`net_read.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-net_read.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-net_read.Tpo -c -o libkrb5_la-net_read.=
lo `test -f 'net_read.c' || echo '$(srcdir)/'`net_read.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-net_read.Tpo $(DEPDIR)=
/libkrb5_la-net_read.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'net_read.c' object=3D'libkrb5_=
la-net_read.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-net_re=
ad.lo `test -f 'net_read.c' || echo '$(srcdir)/'`net_read.c
=20
 libkrb5_la-net_write.lo: net_write.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-net_write.lo `test -f 'net_w=
rite.c' || echo '$(srcdir)/'`net_write.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-net_write=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-net_write.Tpo -c -o libkrb5_la-net_wri=
te.lo `test -f 'net_write.c' || echo '$(srcdir)/'`net_write.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-net_write.Tpo $(DEPDIR=
)/libkrb5_la-net_write.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'net_write.c' object=3D'libkrb5=
_la-net_write.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-net_wr=
ite.lo `test -f 'net_write.c' || echo '$(srcdir)/'`net_write.c
=20
 libkrb5_la-n-fold.lo: n-fold.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-n-fold.lo `test -f 'n-fold.c=
' || echo '$(srcdir)/'`n-fold.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-n-fold.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-n-fold.Tpo -c -o libkrb5_la-n-fold.lo `te=
st -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-n-fold.Tpo $(DEPDIR)/l=
ibkrb5_la-n-fold.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'n-fold.c' object=3D'libkrb5_la=
-n-fold.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-n-fold=
.lo `test -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c
=20
 libkrb5_la-pac.lo: pac.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pac.lo `test -f 'pac.c' || e=
cho '$(srcdir)/'`pac.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-pac.lo -M=
D -MP -MF $(DEPDIR)/libkrb5_la-pac.Tpo -c -o libkrb5_la-pac.lo `test -f 'pa=
c.c' || echo '$(srcdir)/'`pac.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-pac.Tpo $(DEPDIR)/libk=
rb5_la-pac.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'pac.c' object=3D'libkrb5_la-pa=
c.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pac.lo=
 `test -f 'pac.c' || echo '$(srcdir)/'`pac.c
=20
 libkrb5_la-padata.lo: padata.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-padata.lo `test -f 'padata.c=
' || echo '$(srcdir)/'`padata.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-padata.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-padata.Tpo -c -o libkrb5_la-padata.lo `te=
st -f 'padata.c' || echo '$(srcdir)/'`padata.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-padata.Tpo $(DEPDIR)/l=
ibkrb5_la-padata.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'padata.c' object=3D'libkrb5_la=
-padata.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-padata=
.lo `test -f 'padata.c' || echo '$(srcdir)/'`padata.c
+
+libkrb5_la-pcache.lo: pcache.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-pcache.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-pcache.Tpo -c -o libkrb5_la-pcache.lo `te=
st -f 'pcache.c' || echo '$(srcdir)/'`pcache.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-pcache.Tpo $(DEPDIR)/l=
ibkrb5_la-pcache.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'pcache.c' object=3D'libkrb5_la=
-pcache.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pcache=
.lo `test -f 'pcache.c' || echo '$(srcdir)/'`pcache.c
=20
 libkrb5_la-pkinit.lo: pkinit.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pkinit.lo `test -f 'pkinit.c=
' || echo '$(srcdir)/'`pkinit.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-pkinit.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-pkinit.Tpo -c -o libkrb5_la-pkinit.lo `te=
st -f 'pkinit.c' || echo '$(srcdir)/'`pkinit.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-pkinit.Tpo $(DEPDIR)/l=
ibkrb5_la-pkinit.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'pkinit.c' object=3D'libkrb5_la=
-pkinit.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-pkinit=
.lo `test -f 'pkinit.c' || echo '$(srcdir)/'`pkinit.c
=20
 libkrb5_la-principal.lo: principal.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-principal.lo `test -f 'princ=
ipal.c' || echo '$(srcdir)/'`principal.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-principal=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-principal.Tpo -c -o libkrb5_la-princip=
al.lo `test -f 'principal.c' || echo '$(srcdir)/'`principal.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-principal.Tpo $(DEPDIR=
)/libkrb5_la-principal.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'principal.c' object=3D'libkrb5=
_la-principal.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-princi=
pal.lo `test -f 'principal.c' || echo '$(srcdir)/'`principal.c
=20
 libkrb5_la-prog_setup.lo: prog_setup.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-prog_setup.lo `test -f 'prog=
_setup.c' || echo '$(srcdir)/'`prog_setup.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-prog_setu=
p.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-prog_setup.Tpo -c -o libkrb5_la-prog_=
setup.lo `test -f 'prog_setup.c' || echo '$(srcdir)/'`prog_setup.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-prog_setup.Tpo $(DEPDI=
R)/libkrb5_la-prog_setup.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'prog_setup.c' object=3D'libkrb=
5_la-prog_setup.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-prog_s=
etup.lo `test -f 'prog_setup.c' || echo '$(srcdir)/'`prog_setup.c
=20
 libkrb5_la-prompter_posix.lo: prompter_posix.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-prompter_posix.lo `test -f '=
prompter_posix.c' || echo '$(srcdir)/'`prompter_posix.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-prompter_=
posix.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-prompter_posix.Tpo -c -o libkrb5_=
la-prompter_posix.lo `test -f 'prompter_posix.c' || echo '$(srcdir)/'`promp=
ter_posix.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-prompter_posix.Tpo $(D=
EPDIR)/libkrb5_la-prompter_posix.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'prompter_posix.c' object=3D'li=
bkrb5_la-prompter_posix.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-prompt=
er_posix.lo `test -f 'prompter_posix.c' || echo '$(srcdir)/'`prompter_posix=
.c
=20
 libkrb5_la-rd_cred.lo: rd_cred.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_cred.lo `test -f 'rd_cred=
.c' || echo '$(srcdir)/'`rd_cred.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_cred.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_cred.Tpo -c -o libkrb5_la-rd_cred.lo =
`test -f 'rd_cred.c' || echo '$(srcdir)/'`rd_cred.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-rd_cred.Tpo $(DEPDIR)/=
libkrb5_la-rd_cred.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rd_cred.c' object=3D'libkrb5_l=
a-rd_cred.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_cre=
d.lo `test -f 'rd_cred.c' || echo '$(srcdir)/'`rd_cred.c
=20
 libkrb5_la-rd_error.lo: rd_error.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_error.lo `test -f 'rd_err=
or.c' || echo '$(srcdir)/'`rd_error.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_error.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_error.Tpo -c -o libkrb5_la-rd_error.=
lo `test -f 'rd_error.c' || echo '$(srcdir)/'`rd_error.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-rd_error.Tpo $(DEPDIR)=
/libkrb5_la-rd_error.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rd_error.c' object=3D'libkrb5_=
la-rd_error.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_err=
or.lo `test -f 'rd_error.c' || echo '$(srcdir)/'`rd_error.c
=20
 libkrb5_la-rd_priv.lo: rd_priv.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_priv.lo `test -f 'rd_priv=
.c' || echo '$(srcdir)/'`rd_priv.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_priv.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_priv.Tpo -c -o libkrb5_la-rd_priv.lo =
`test -f 'rd_priv.c' || echo '$(srcdir)/'`rd_priv.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-rd_priv.Tpo $(DEPDIR)/=
libkrb5_la-rd_priv.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rd_priv.c' object=3D'libkrb5_l=
a-rd_priv.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_pri=
v.lo `test -f 'rd_priv.c' || echo '$(srcdir)/'`rd_priv.c
=20
 libkrb5_la-rd_rep.lo: rd_rep.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_rep.lo `test -f 'rd_rep.c=
' || echo '$(srcdir)/'`rd_rep.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_rep.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_rep.Tpo -c -o libkrb5_la-rd_rep.lo `te=
st -f 'rd_rep.c' || echo '$(srcdir)/'`rd_rep.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-rd_rep.Tpo $(DEPDIR)/l=
ibkrb5_la-rd_rep.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rd_rep.c' object=3D'libkrb5_la=
-rd_rep.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_rep=
.lo `test -f 'rd_rep.c' || echo '$(srcdir)/'`rd_rep.c
=20
 libkrb5_la-rd_req.lo: rd_req.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_req.lo `test -f 'rd_req.c=
' || echo '$(srcdir)/'`rd_req.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_req.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_req.Tpo -c -o libkrb5_la-rd_req.lo `te=
st -f 'rd_req.c' || echo '$(srcdir)/'`rd_req.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-rd_req.Tpo $(DEPDIR)/l=
ibkrb5_la-rd_req.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rd_req.c' object=3D'libkrb5_la=
-rd_req.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_req=
.lo `test -f 'rd_req.c' || echo '$(srcdir)/'`rd_req.c
=20
 libkrb5_la-rd_safe.lo: rd_safe.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_safe.lo `test -f 'rd_safe=
.c' || echo '$(srcdir)/'`rd_safe.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-rd_safe.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-rd_safe.Tpo -c -o libkrb5_la-rd_safe.lo =
`test -f 'rd_safe.c' || echo '$(srcdir)/'`rd_safe.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-rd_safe.Tpo $(DEPDIR)/=
libkrb5_la-rd_safe.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rd_safe.c' object=3D'libkrb5_l=
a-rd_safe.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-rd_saf=
e.lo `test -f 'rd_safe.c' || echo '$(srcdir)/'`rd_safe.c
=20
 libkrb5_la-read_message.lo: read_message.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-read_message.lo `test -f 're=
ad_message.c' || echo '$(srcdir)/'`read_message.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-read_mess=
age.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-read_message.Tpo -c -o libkrb5_la-r=
ead_message.lo `test -f 'read_message.c' || echo '$(srcdir)/'`read_message.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-read_message.Tpo $(DEP=
DIR)/libkrb5_la-read_message.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'read_message.c' object=3D'libk=
rb5_la-read_message.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-read_m=
essage.lo `test -f 'read_message.c' || echo '$(srcdir)/'`read_message.c
=20
 libkrb5_la-recvauth.lo: recvauth.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-recvauth.lo `test -f 'recvau=
th.c' || echo '$(srcdir)/'`recvauth.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-recvauth.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-recvauth.Tpo -c -o libkrb5_la-recvauth.=
lo `test -f 'recvauth.c' || echo '$(srcdir)/'`recvauth.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-recvauth.Tpo $(DEPDIR)=
/libkrb5_la-recvauth.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'recvauth.c' object=3D'libkrb5_=
la-recvauth.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-recvau=
th.lo `test -f 'recvauth.c' || echo '$(srcdir)/'`recvauth.c
=20
 libkrb5_la-replay.lo: replay.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-replay.lo `test -f 'replay.c=
' || echo '$(srcdir)/'`replay.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-replay.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-replay.Tpo -c -o libkrb5_la-replay.lo `te=
st -f 'replay.c' || echo '$(srcdir)/'`replay.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-replay.Tpo $(DEPDIR)/l=
ibkrb5_la-replay.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'replay.c' object=3D'libkrb5_la=
-replay.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-replay=
.lo `test -f 'replay.c' || echo '$(srcdir)/'`replay.c
+
+libkrb5_la-salt.lo: salt.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt.lo -=
MD -MP -MF $(DEPDIR)/libkrb5_la-salt.Tpo -c -o libkrb5_la-salt.lo `test -f =
'salt.c' || echo '$(srcdir)/'`salt.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-salt.Tpo $(DEPDIR)/lib=
krb5_la-salt.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt.c' object=3D'libkrb5_la-s=
alt.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt.l=
o `test -f 'salt.c' || echo '$(srcdir)/'`salt.c
+
+libkrb5_la-salt-aes.lo: salt-aes.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-aes.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-aes.Tpo -c -o libkrb5_la-salt-aes.=
lo `test -f 'salt-aes.c' || echo '$(srcdir)/'`salt-aes.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-salt-aes.Tpo $(DEPDIR)=
/libkrb5_la-salt-aes.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-aes.c' object=3D'libkrb5_=
la-salt-aes.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-a=
es.lo `test -f 'salt-aes.c' || echo '$(srcdir)/'`salt-aes.c
+
+libkrb5_la-salt-arcfour.lo: salt-arcfour.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-arcf=
our.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-arcfour.Tpo -c -o libkrb5_la-s=
alt-arcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`salt-arcfour.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-salt-arcfour.Tpo $(DEP=
DIR)/libkrb5_la-salt-arcfour.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-arcfour.c' object=3D'libk=
rb5_la-salt-arcfour.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-a=
rcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`salt-arcfour.c
+
+libkrb5_la-salt-des.lo: salt-des.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-des.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-des.Tpo -c -o libkrb5_la-salt-des.=
lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-salt-des.Tpo $(DEPDIR)=
/libkrb5_la-salt-des.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-des.c' object=3D'libkrb5_=
la-salt-des.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-d=
es.lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c
+
+libkrb5_la-salt-des3.lo: salt-des3.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-salt-des3=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-salt-des3.Tpo -c -o libkrb5_la-salt-de=
s3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-salt-des3.Tpo $(DEPDIR=
)/libkrb5_la-salt-des3.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-des3.c' object=3D'libkrb5=
_la-salt-des3.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-salt-d=
es3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c
+
+libkrb5_la-scache.lo: scache.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-scache.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-scache.Tpo -c -o libkrb5_la-scache.lo `te=
st -f 'scache.c' || echo '$(srcdir)/'`scache.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-scache.Tpo $(DEPDIR)/l=
ibkrb5_la-scache.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'scache.c' object=3D'libkrb5_la=
-scache.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-scache=
.lo `test -f 'scache.c' || echo '$(srcdir)/'`scache.c
=20
 libkrb5_la-send_to_kdc.lo: send_to_kdc.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-send_to_kdc.lo `test -f 'sen=
d_to_kdc.c' || echo '$(srcdir)/'`send_to_kdc.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-send_to_k=
dc.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-send_to_kdc.Tpo -c -o libkrb5_la-sen=
d_to_kdc.lo `test -f 'send_to_kdc.c' || echo '$(srcdir)/'`send_to_kdc.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-send_to_kdc.Tpo $(DEPD=
IR)/libkrb5_la-send_to_kdc.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'send_to_kdc.c' object=3D'libkr=
b5_la-send_to_kdc.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-send_t=
o_kdc.lo `test -f 'send_to_kdc.c' || echo '$(srcdir)/'`send_to_kdc.c
=20
 libkrb5_la-sendauth.lo: sendauth.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-sendauth.lo `test -f 'sendau=
th.c' || echo '$(srcdir)/'`sendauth.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-sendauth.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-sendauth.Tpo -c -o libkrb5_la-sendauth.=
lo `test -f 'sendauth.c' || echo '$(srcdir)/'`sendauth.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-sendauth.Tpo $(DEPDIR)=
/libkrb5_la-sendauth.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'sendauth.c' object=3D'libkrb5_=
la-sendauth.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-sendau=
th.lo `test -f 'sendauth.c' || echo '$(srcdir)/'`sendauth.c
=20
 libkrb5_la-set_default_realm.lo: set_default_realm.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-set_default_realm.lo `test -=
f 'set_default_realm.c' || echo '$(srcdir)/'`set_default_realm.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-set_defau=
lt_realm.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-set_default_realm.Tpo -c -o li=
bkrb5_la-set_default_realm.lo `test -f 'set_default_realm.c' || echo '$(src=
dir)/'`set_default_realm.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-set_default_realm.Tpo =
$(DEPDIR)/libkrb5_la-set_default_realm.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'set_default_realm.c' object=3D=
'libkrb5_la-set_default_realm.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-set_de=
fault_realm.lo `test -f 'set_default_realm.c' || echo '$(srcdir)/'`set_defa=
ult_realm.c
=20
 libkrb5_la-sock_principal.lo: sock_principal.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-sock_principal.lo `test -f '=
sock_principal.c' || echo '$(srcdir)/'`sock_principal.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-sock_prin=
cipal.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-sock_principal.Tpo -c -o libkrb5_=
la-sock_principal.lo `test -f 'sock_principal.c' || echo '$(srcdir)/'`sock_=
principal.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-sock_principal.Tpo $(D=
EPDIR)/libkrb5_la-sock_principal.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'sock_principal.c' object=3D'li=
bkrb5_la-sock_principal.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-sock_p=
rincipal.lo `test -f 'sock_principal.c' || echo '$(srcdir)/'`sock_principal=
.c
=20
 libkrb5_la-store.lo: store.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store.lo `test -f 'store.c' =
|| echo '$(srcdir)/'`store.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store.lo =
-MD -MP -MF $(DEPDIR)/libkrb5_la-store.Tpo -c -o libkrb5_la-store.lo `test =
-f 'store.c' || echo '$(srcdir)/'`store.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-store.Tpo $(DEPDIR)/li=
bkrb5_la-store.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'store.c' object=3D'libkrb5_la-=
store.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store.=
lo `test -f 'store.c' || echo '$(srcdir)/'`store.c
+
+libkrb5_la-store-int.lo: store-int.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store-int=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store-int.Tpo -c -o libkrb5_la-store-i=
nt.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-store-int.Tpo $(DEPDIR=
)/libkrb5_la-store-int.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'store-int.c' object=3D'libkrb5=
_la-store-int.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store-=
int.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c
=20
 libkrb5_la-store_emem.lo: store_emem.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_emem.lo `test -f 'stor=
e_emem.c' || echo '$(srcdir)/'`store_emem.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store_eme=
m.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store_emem.Tpo -c -o libkrb5_la-store=
_emem.lo `test -f 'store_emem.c' || echo '$(srcdir)/'`store_emem.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-store_emem.Tpo $(DEPDI=
R)/libkrb5_la-store_emem.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'store_emem.c' object=3D'libkrb=
5_la-store_emem.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_=
emem.lo `test -f 'store_emem.c' || echo '$(srcdir)/'`store_emem.c
=20
 libkrb5_la-store_fd.lo: store_fd.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_fd.lo `test -f 'store_=
fd.c' || echo '$(srcdir)/'`store_fd.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store_fd.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store_fd.Tpo -c -o libkrb5_la-store_fd.=
lo `test -f 'store_fd.c' || echo '$(srcdir)/'`store_fd.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-store_fd.Tpo $(DEPDIR)=
/libkrb5_la-store_fd.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'store_fd.c' object=3D'libkrb5_=
la-store_fd.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_=
fd.lo `test -f 'store_fd.c' || echo '$(srcdir)/'`store_fd.c
=20
 libkrb5_la-store_mem.lo: store_mem.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_mem.lo `test -f 'store=
_mem.c' || echo '$(srcdir)/'`store_mem.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-store_mem=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-store_mem.Tpo -c -o libkrb5_la-store_m=
em.lo `test -f 'store_mem.c' || echo '$(srcdir)/'`store_mem.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-store_mem.Tpo $(DEPDIR=
)/libkrb5_la-store_mem.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'store_mem.c' object=3D'libkrb5=
_la-store_mem.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-store_=
mem.lo `test -f 'store_mem.c' || echo '$(srcdir)/'`store_mem.c
=20
 libkrb5_la-plugin.lo: plugin.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-plugin.lo `test -f 'plugin.c=
' || echo '$(srcdir)/'`plugin.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-plugin.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-plugin.Tpo -c -o libkrb5_la-plugin.lo `te=
st -f 'plugin.c' || echo '$(srcdir)/'`plugin.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-plugin.Tpo $(DEPDIR)/l=
ibkrb5_la-plugin.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'plugin.c' object=3D'libkrb5_la=
-plugin.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-plugin=
.lo `test -f 'plugin.c' || echo '$(srcdir)/'`plugin.c
=20
 libkrb5_la-ticket.lo: ticket.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-ticket.lo `test -f 'ticket.c=
' || echo '$(srcdir)/'`ticket.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-ticket.lo=
 -MD -MP -MF $(DEPDIR)/libkrb5_la-ticket.Tpo -c -o libkrb5_la-ticket.lo `te=
st -f 'ticket.c' || echo '$(srcdir)/'`ticket.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-ticket.Tpo $(DEPDIR)/l=
ibkrb5_la-ticket.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ticket.c' object=3D'libkrb5_la=
-ticket.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-ticket=
.lo `test -f 'ticket.c' || echo '$(srcdir)/'`ticket.c
=20
 libkrb5_la-time.lo: time.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-time.lo `test -f 'time.c' ||=
 echo '$(srcdir)/'`time.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-time.lo -=
MD -MP -MF $(DEPDIR)/libkrb5_la-time.Tpo -c -o libkrb5_la-time.lo `test -f =
'time.c' || echo '$(srcdir)/'`time.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-time.Tpo $(DEPDIR)/lib=
krb5_la-time.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'time.c' object=3D'libkrb5_la-t=
ime.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-time.l=
o `test -f 'time.c' || echo '$(srcdir)/'`time.c
=20
 libkrb5_la-transited.lo: transited.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-transited.lo `test -f 'trans=
ited.c' || echo '$(srcdir)/'`transited.c
-
-libkrb5_la-v4_glue.lo: v4_glue.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-v4_glue.lo `test -f 'v4_glue=
.c' || echo '$(srcdir)/'`v4_glue.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-transited=
.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-transited.Tpo -c -o libkrb5_la-transit=
ed.lo `test -f 'transited.c' || echo '$(srcdir)/'`transited.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-transited.Tpo $(DEPDIR=
)/libkrb5_la-transited.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'transited.c' object=3D'libkrb5=
_la-transited.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-transi=
ted.lo `test -f 'transited.c' || echo '$(srcdir)/'`transited.c
=20
 libkrb5_la-verify_init.lo: verify_init.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-verify_init.lo `test -f 'ver=
ify_init.c' || echo '$(srcdir)/'`verify_init.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-verify_in=
it.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-verify_init.Tpo -c -o libkrb5_la-ver=
ify_init.lo `test -f 'verify_init.c' || echo '$(srcdir)/'`verify_init.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-verify_init.Tpo $(DEPD=
IR)/libkrb5_la-verify_init.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'verify_init.c' object=3D'libkr=
b5_la-verify_init.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-verify=
_init.lo `test -f 'verify_init.c' || echo '$(srcdir)/'`verify_init.c
=20
 libkrb5_la-verify_user.lo: verify_user.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-verify_user.lo `test -f 'ver=
ify_user.c' || echo '$(srcdir)/'`verify_user.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-verify_us=
er.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-verify_user.Tpo -c -o libkrb5_la-ver=
ify_user.lo `test -f 'verify_user.c' || echo '$(srcdir)/'`verify_user.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-verify_user.Tpo $(DEPD=
IR)/libkrb5_la-verify_user.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'verify_user.c' object=3D'libkr=
b5_la-verify_user.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-verify=
_user.lo `test -f 'verify_user.c' || echo '$(srcdir)/'`verify_user.c
=20
 libkrb5_la-version.lo: version.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-version.lo `test -f 'version=
.c' || echo '$(srcdir)/'`version.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-version.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-version.Tpo -c -o libkrb5_la-version.lo =
`test -f 'version.c' || echo '$(srcdir)/'`version.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-version.Tpo $(DEPDIR)/=
libkrb5_la-version.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'version.c' object=3D'libkrb5_l=
a-version.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-versio=
n.lo `test -f 'version.c' || echo '$(srcdir)/'`version.c
=20
 libkrb5_la-warn.lo: warn.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-warn.lo `test -f 'warn.c' ||=
 echo '$(srcdir)/'`warn.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-warn.lo -=
MD -MP -MF $(DEPDIR)/libkrb5_la-warn.Tpo -c -o libkrb5_la-warn.lo `test -f =
'warn.c' || echo '$(srcdir)/'`warn.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-warn.Tpo $(DEPDIR)/lib=
krb5_la-warn.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'warn.c' object=3D'libkrb5_la-w=
arn.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-warn.l=
o `test -f 'warn.c' || echo '$(srcdir)/'`warn.c
=20
 libkrb5_la-write_message.lo: write_message.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-write_message.lo `test -f 'w=
rite_message.c' || echo '$(srcdir)/'`write_message.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-write_mes=
sage.lo -MD -MP -MF $(DEPDIR)/libkrb5_la-write_message.Tpo -c -o libkrb5_la=
-write_message.lo `test -f 'write_message.c' || echo '$(srcdir)/'`write_mes=
sage.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-write_message.Tpo $(DE=
PDIR)/libkrb5_la-write_message.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'write_message.c' object=3D'lib=
krb5_la-write_message.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-write_=
message.lo `test -f 'write_message.c' || echo '$(srcdir)/'`write_message.c
=20
 libkrb5_la-krb5_err.lo: krb5_err.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krb5_err.lo `test -f 'krb5_e=
rr.c' || echo '$(srcdir)/'`krb5_err.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-krb5_err.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-krb5_err.Tpo -c -o libkrb5_la-krb5_err.=
lo `test -f 'krb5_err.c' || echo '$(srcdir)/'`krb5_err.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-krb5_err.Tpo $(DEPDIR)=
/libkrb5_la-krb5_err.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'krb5_err.c' object=3D'libkrb5_=
la-krb5_err.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krb5_e=
rr.lo `test -f 'krb5_err.c' || echo '$(srcdir)/'`krb5_err.c
=20
 libkrb5_la-krb_err.lo: krb_err.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krb_err.lo `test -f 'krb_err=
.c' || echo '$(srcdir)/'`krb_err.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-krb_err.l=
o -MD -MP -MF $(DEPDIR)/libkrb5_la-krb_err.Tpo -c -o libkrb5_la-krb_err.lo =
`test -f 'krb_err.c' || echo '$(srcdir)/'`krb_err.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-krb_err.Tpo $(DEPDIR)/=
libkrb5_la-krb_err.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'krb_err.c' object=3D'libkrb5_l=
a-krb_err.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-krb_er=
r.lo `test -f 'krb_err.c' || echo '$(srcdir)/'`krb_err.c
=20
 libkrb5_la-heim_err.lo: heim_err.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-heim_err.lo `test -f 'heim_e=
rr.c' || echo '$(srcdir)/'`heim_err.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-heim_err.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-heim_err.Tpo -c -o libkrb5_la-heim_err.=
lo `test -f 'heim_err.c' || echo '$(srcdir)/'`heim_err.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-heim_err.Tpo $(DEPDIR)=
/libkrb5_la-heim_err.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'heim_err.c' object=3D'libkrb5_=
la-heim_err.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-heim_e=
rr.lo `test -f 'heim_err.c' || echo '$(srcdir)/'`heim_err.c
=20
 libkrb5_la-k524_err.lo: k524_err.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkrb5_la_CPPFLAGS) $(CPP=
FLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-k524_err.lo `test -f 'k524_e=
rr.c' || echo '$(srcdir)/'`k524_err.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libkr=
b5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libkrb5_la-k524_err.=
lo -MD -MP -MF $(DEPDIR)/libkrb5_la-k524_err.Tpo -c -o libkrb5_la-k524_err.=
lo `test -f 'k524_err.c' || echo '$(srcdir)/'`k524_err.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libkrb5_la-k524_err.Tpo $(DEPDIR)=
/libkrb5_la-k524_err.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'k524_err.c' object=3D'libkrb5_=
la-k524_err.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libk=
rb5_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libkrb5_la-k524_e=
rr.lo `test -f 'k524_err.c' || echo '$(srcdir)/'`k524_err.c
+
+librfc3961_la-crc.lo: crc.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-crc=
.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crc.Tpo -c -o librfc3961_la-crc.lo =
`test -f 'crc.c' || echo '$(srcdir)/'`crc.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crc.Tpo $(DEPDIR)/l=
ibrfc3961_la-crc.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crc.c' object=3D'librfc3961_la=
-crc.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crc.lo `test -f 'crc.c' || echo '$(srcdir)/'`crc.c
+
+librfc3961_la-crypto.lo: crypto.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto.Tpo -c -o librfc3961_la-c=
rypto.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto.Tpo $(DEPDIR=
)/librfc3961_la-crypto.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto.c' object=3D'librfc3961=
_la-crypto.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto.lo `test -f 'crypto.c' || echo '$(srcdir)/'`crypto.c
+
+librfc3961_la-crypto-aes.lo: crypto-aes.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-aes.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-aes.Tpo -c -o librfc3=
961_la-crypto-aes.lo `test -f 'crypto-aes.c' || echo '$(srcdir)/'`crypto-ae=
s.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-aes.Tpo $(DE=
PDIR)/librfc3961_la-crypto-aes.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-aes.c' object=3D'librfc=
3961_la-crypto-aes.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-aes.lo `test -f 'crypto-aes.c' || echo '$(srcdir)/'`crypto-aes.c
+
+librfc3961_la-crypto-algs.lo: crypto-algs.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-algs.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-algs.Tpo -c -o librf=
c3961_la-crypto-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypt=
o-algs.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-algs.Tpo $(D=
EPDIR)/librfc3961_la-crypto-algs.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-algs.c' object=3D'librf=
c3961_la-crypto-algs.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-algs.lo `test -f 'crypto-algs.c' || echo '$(srcdir)/'`crypto-algs.c
+
+librfc3961_la-crypto-arcfour.lo: crypto-arcfour.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-arcfour.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-arcfour.Tpo -c -o=
 librfc3961_la-crypto-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(src=
dir)/'`crypto-arcfour.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-arcfour.Tpo =
$(DEPDIR)/librfc3961_la-crypto-arcfour.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-arcfour.c' object=3D'li=
brfc3961_la-crypto-arcfour.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-arcfour.lo `test -f 'crypto-arcfour.c' || echo '$(srcdir)/'`crypto-a=
rcfour.c
+
+librfc3961_la-crypto-des.lo: crypto-des.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-des.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-des.Tpo -c -o librfc3=
961_la-crypto-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-de=
s.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-des.Tpo $(DE=
PDIR)/librfc3961_la-crypto-des.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-des.c' object=3D'librfc=
3961_la-crypto-des.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-des.lo `test -f 'crypto-des.c' || echo '$(srcdir)/'`crypto-des.c
+
+librfc3961_la-crypto-des-common.lo: crypto-des-common.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-des-common.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-des-common.Tpo=
 -c -o librfc3961_la-crypto-des-common.lo `test -f 'crypto-des-common.c' ||=
 echo '$(srcdir)/'`crypto-des-common.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-des-common.T=
po $(DEPDIR)/librfc3961_la-crypto-des-common.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-des-common.c' object=3D=
'librfc3961_la-crypto-des-common.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-des-common.lo `test -f 'crypto-des-common.c' || echo '$(srcdir)/'`cr=
ypto-des-common.c
+
+librfc3961_la-crypto-des3.lo: crypto-des3.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-des3.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-des3.Tpo -c -o librf=
c3961_la-crypto-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypt=
o-des3.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-des3.Tpo $(D=
EPDIR)/librfc3961_la-crypto-des3.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-des3.c' object=3D'librf=
c3961_la-crypto-des3.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-des3.lo `test -f 'crypto-des3.c' || echo '$(srcdir)/'`crypto-des3.c
+
+librfc3961_la-crypto-evp.lo: crypto-evp.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-evp.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-evp.Tpo -c -o librfc3=
961_la-crypto-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-ev=
p.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-evp.Tpo $(DE=
PDIR)/librfc3961_la-crypto-evp.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-evp.c' object=3D'librfc=
3961_la-crypto-evp.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-evp.lo `test -f 'crypto-evp.c' || echo '$(srcdir)/'`crypto-evp.c
+
+librfc3961_la-crypto-null.lo: crypto-null.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-null.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-null.Tpo -c -o librf=
c3961_la-crypto-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypt=
o-null.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-null.Tpo $(D=
EPDIR)/librfc3961_la-crypto-null.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-null.c' object=3D'librf=
c3961_la-crypto-null.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-null.lo `test -f 'crypto-null.c' || echo '$(srcdir)/'`crypto-null.c
+
+librfc3961_la-crypto-pk.lo: crypto-pk.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-pk.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-pk.Tpo -c -o librfc396=
1_la-crypto-pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-pk.Tpo $(DEP=
DIR)/librfc3961_la-crypto-pk.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-pk.c' object=3D'librfc3=
961_la-crypto-pk.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-pk.lo `test -f 'crypto-pk.c' || echo '$(srcdir)/'`crypto-pk.c
+
+librfc3961_la-crypto-rand.lo: crypto-rand.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-rand.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-rand.Tpo -c -o librf=
c3961_la-crypto-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypt=
o-rand.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-rand.Tpo $(D=
EPDIR)/librfc3961_la-crypto-rand.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-rand.c' object=3D'librf=
c3961_la-crypto-rand.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-rand.lo `test -f 'crypto-rand.c' || echo '$(srcdir)/'`crypto-rand.c
+
+librfc3961_la-crypto-stubs.lo: crypto-stubs.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-cry=
pto-stubs.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-crypto-stubs.Tpo -c -o lib=
rfc3961_la-crypto-stubs.lo `test -f 'crypto-stubs.c' || echo '$(srcdir)/'`c=
rypto-stubs.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-crypto-stubs.Tpo $(=
DEPDIR)/librfc3961_la-crypto-stubs.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'crypto-stubs.c' object=3D'libr=
fc3961_la-crypto-stubs.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
crypto-stubs.lo `test -f 'crypto-stubs.c' || echo '$(srcdir)/'`crypto-stubs=
.c
+
+librfc3961_la-data.lo: data.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-dat=
a.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-data.Tpo -c -o librfc3961_la-data.=
lo `test -f 'data.c' || echo '$(srcdir)/'`data.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-data.Tpo $(DEPDIR)/=
librfc3961_la-data.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'data.c' object=3D'librfc3961_l=
a-data.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
data.lo `test -f 'data.c' || echo '$(srcdir)/'`data.c
+
+librfc3961_la-error_string.lo: error_string.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-err=
or_string.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-error_string.Tpo -c -o lib=
rfc3961_la-error_string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`e=
rror_string.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-error_string.Tpo $(=
DEPDIR)/librfc3961_la-error_string.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'error_string.c' object=3D'libr=
fc3961_la-error_string.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
error_string.lo `test -f 'error_string.c' || echo '$(srcdir)/'`error_string=
.c
+
+librfc3961_la-keyblock.lo: keyblock.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-key=
block.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-keyblock.Tpo -c -o librfc3961_=
la-keyblock.lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-keyblock.Tpo $(DEPD=
IR)/librfc3961_la-keyblock.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'keyblock.c' object=3D'librfc39=
61_la-keyblock.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
keyblock.lo `test -f 'keyblock.c' || echo '$(srcdir)/'`keyblock.c
+
+librfc3961_la-n-fold.lo: n-fold.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-n-f=
old.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-n-fold.Tpo -c -o librfc3961_la-n=
-fold.lo `test -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-n-fold.Tpo $(DEPDIR=
)/librfc3961_la-n-fold.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'n-fold.c' object=3D'librfc3961=
_la-n-fold.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
n-fold.lo `test -f 'n-fold.c' || echo '$(srcdir)/'`n-fold.c
+
+librfc3961_la-salt.lo: salt.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-sal=
t.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt.Tpo -c -o librfc3961_la-salt.=
lo `test -f 'salt.c' || echo '$(srcdir)/'`salt.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-salt.Tpo $(DEPDIR)/=
librfc3961_la-salt.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt.c' object=3D'librfc3961_l=
a-salt.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
salt.lo `test -f 'salt.c' || echo '$(srcdir)/'`salt.c
+
+librfc3961_la-salt-aes.lo: salt-aes.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-sal=
t-aes.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-aes.Tpo -c -o librfc3961_=
la-salt-aes.lo `test -f 'salt-aes.c' || echo '$(srcdir)/'`salt-aes.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-salt-aes.Tpo $(DEPD=
IR)/librfc3961_la-salt-aes.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-aes.c' object=3D'librfc39=
61_la-salt-aes.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
salt-aes.lo `test -f 'salt-aes.c' || echo '$(srcdir)/'`salt-aes.c
+
+librfc3961_la-salt-arcfour.lo: salt-arcfour.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-sal=
t-arcfour.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-arcfour.Tpo -c -o lib=
rfc3961_la-salt-arcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`s=
alt-arcfour.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-salt-arcfour.Tpo $(=
DEPDIR)/librfc3961_la-salt-arcfour.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-arcfour.c' object=3D'libr=
fc3961_la-salt-arcfour.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
salt-arcfour.lo `test -f 'salt-arcfour.c' || echo '$(srcdir)/'`salt-arcfour=
.c
+
+librfc3961_la-salt-des.lo: salt-des.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-sal=
t-des.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-des.Tpo -c -o librfc3961_=
la-salt-des.lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-salt-des.Tpo $(DEPD=
IR)/librfc3961_la-salt-des.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-des.c' object=3D'librfc39=
61_la-salt-des.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
salt-des.lo `test -f 'salt-des.c' || echo '$(srcdir)/'`salt-des.c
+
+librfc3961_la-salt-des3.lo: salt-des3.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-sal=
t-des3.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-salt-des3.Tpo -c -o librfc396=
1_la-salt-des3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-salt-des3.Tpo $(DEP=
DIR)/librfc3961_la-salt-des3.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'salt-des3.c' object=3D'librfc3=
961_la-salt-des3.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
salt-des3.lo `test -f 'salt-des3.c' || echo '$(srcdir)/'`salt-des3.c
+
+librfc3961_la-store-int.lo: store-int.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-sto=
re-int.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-store-int.Tpo -c -o librfc396=
1_la-store-int.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-store-int.Tpo $(DEP=
DIR)/librfc3961_la-store-int.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'store-int.c' object=3D'librfc3=
961_la-store-int.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
store-int.lo `test -f 'store-int.c' || echo '$(srcdir)/'`store-int.c
+
+librfc3961_la-warn.lo: warn.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(librf=
c3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT librfc3961_la-war=
n.lo -MD -MP -MF $(DEPDIR)/librfc3961_la-warn.Tpo -c -o librfc3961_la-warn.=
lo `test -f 'warn.c' || echo '$(srcdir)/'`warn.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/librfc3961_la-warn.Tpo $(DEPDIR)/=
librfc3961_la-warn.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'warn.c' object=3D'librfc3961_l=
a-warn.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
fc3961_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o librfc3961_la-=
warn.lo `test -f 'warn.c' || echo '$(srcdir)/'`warn.c
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man3: $(man3_MANS) $(man_MANS)
+install-man3: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man3dir)" || $(MKDIR_P) "$(DESTDIR)$(man3dir)"
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man3:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
-install-man5: $(man5_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man3dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man3dir)" && rm -f $$files; }
+install-man5: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man5dir)" || $(MKDIR_P) "$(DESTDIR)$(man5dir)"
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man5:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man5_MANS) $(dist_man5_MANS) $(nodist_man5_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.5*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    5*) ;; \
-	    *) ext=3D'5' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man5dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man5dir)/$$inst"; \
-	done
-install-man8: $(man8_MANS) $(man_MANS)
+	@list=3D''; test -n "$(man5dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.5[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man5dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man5dir)" && rm -f $$files; }
+install-man8: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man8dir)" || $(MKDIR_P) "$(DESTDIR)$(man8dir)"
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man8:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man8_MANS) $(dist_man8_MANS) $(nodist_man8_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.8*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    8*) ;; \
-	    *) ext=3D'8' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man8dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man8dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man8dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.8[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man8dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man8dir)" && rm -f $$files; }
 install-dist_includeHEADERS: $(dist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(dist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)=
/$$f'"; \
-	  $(dist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-dist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-krb5HEADERS: $(krb5_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(krb5dir)" || $(MKDIR_P) "$(DESTDIR)$(krb5dir)"
-	@list=3D'$(krb5_HEADERS)'; for p in $$list; do \
+	@list=3D'$(krb5_HEADERS)'; test -n "$(krb5dir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(krb5HEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(krb5dir)/$$f'"; \
-	  $(krb5HEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(krb5dir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(krb5dir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(krb5dir)" || exit $$?; \
 	done
=20
 uninstall-krb5HEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(krb5_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(krb5dir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(krb5dir)/$$f"; \
-	done
+	@list=3D'$(krb5_HEADERS)'; test -n "$(krb5dir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(krb5dir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(krb5dir)" && rm -f $$files
 install-nodist_includeHEADERS: $(nodist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedi=
r)/$$f'"; \
-	  $(nodist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"=
; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -1605,49 +2744,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -1658,15 +2811,32 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -1682,13 +2852,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -1696,7 +2870,7 @@
 	  top_distdir=3D"$(top_distdir)" distdir=3D"$(distdir)" \
 	  dist-hook
 check-am: all-am
-	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS)
+	$(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(check_DATA)
 	$(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local
 check: check-am
 all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(MANS) $(HEADERS) \
@@ -1728,6 +2902,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -1735,10 +2910,11 @@
 clean: clean-am
=20
 clean-am: clean-binPROGRAMS clean-checkPROGRAMS clean-generic \
-	clean-libLTLIBRARIES clean-libtool clean-noinstPROGRAMS \
-	mostlyclean-am
+	clean-libLTLIBRARIES clean-libtool clean-noinstLTLIBRARIES \
+	clean-noinstPROGRAMS mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -1749,6 +2925,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -1757,26 +2935,35 @@
 	install-man install-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binPROGRAMS install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man3 install-man5 install-man8
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -1798,24 +2985,24 @@
 	uninstall-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man3 uninstall-man5 uninstall-man8
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
 	check-local clean clean-binPROGRAMS clean-checkPROGRAMS \
 	clean-generic clean-libLTLIBRARIES clean-libtool \
-	clean-noinstPROGRAMS ctags dist-hook distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-binPROGRAMS install-data \
-	install-data-am install-data-hook install-dist_includeHEADERS \
-	install-dvi install-dvi-am install-exec install-exec-am \
-	install-exec-hook install-html install-html-am install-info \
-	install-info-am install-krb5HEADERS install-libLTLIBRARIES \
-	install-man install-man3 install-man5 install-man8 \
+	clean-noinstLTLIBRARIES clean-noinstPROGRAMS ctags dist-hook \
+	distclean distclean-compile distclean-generic \
+	distclean-libtool distclean-tags distdir dvi dvi-am html \
+	html-am info info-am install install-am install-binPROGRAMS \
+	install-data install-data-am install-data-hook \
+	install-dist_includeHEADERS install-dvi install-dvi-am \
+	install-exec install-exec-am install-exec-hook install-html \
+	install-html-am install-info install-info-am \
+	install-krb5HEADERS install-libLTLIBRARIES install-man \
+	install-man3 install-man5 install-man8 \
 	install-nodist_includeHEADERS install-pdf install-pdf-am \
 	install-ps install-ps-am install-strip installcheck \
 	installcheck-am installdirs maintainer-clean \
@@ -1896,6 +3083,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1981,7 +3171,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1995,16 +3185,19 @@
 	  fi ; \
 	done
=20
-$(libkrb5_la_OBJECTS) $(verify_krb5_conf_OBJECTS): $(srcdir)/krb5-protos.h=
 $(srcdir)/krb5-private.h
+$(libkrb5_la_OBJECTS) $(verify_krb5_conf_OBJECTS) $(librfc3961_la_OBJECTS)=
: $(srcdir)/krb5-protos.h $(srcdir)/krb5-private.h krb5_err.h heim_err.h k5=
24_err.h krb5_err.h krb_err.h k524_err.h
=20
 $(srcdir)/krb5-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -E KRB5_LIB_FUNCTION -q -P co=
mment -o krb5-protos.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -E KRB5_LIB -q -P comment -o =
krb5-protos.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-protos.h
=20
 $(srcdir)/krb5-private.h:
 	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -p krb5-private=
.h $(dist_libkrb5_la_SOURCES) || rm -f krb5-private.h
=20
 $(libkrb5_la_OBJECTS): krb5_err.h krb_err.h heim_err.h k524_err.h
=20
+test_config_strings.out: test_config_strings.cfg
+	$(CP) $(srcdir)/test_config_strings.cfg test_config_strings.out
+
 #sysconf_DATA =3D krb5.moduli
=20
 # to help stupid solaris make
@@ -2016,6 +3209,7 @@
 heim_err.h: heim_err.et
=20
 k524_err.h: k524_err.et
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/acache.c
--- a/head/crypto/heimdal/lib/krb5/acache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/acache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,36 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
@@ -37,14 +39,15 @@
 #include <dlfcn.h>
 #endif
=20
-RCSID("$Id: acache.c 22099 2007-12-03 17:14:34Z lha $");
+#ifndef KCM_IS_API_CACHE
=20
-/* XXX should we fetch these for each open ? */
 static HEIMDAL_MUTEX acc_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
 static cc_initialize_func init_func;
+static void (KRB5_CALLCONV *set_target_uid)(uid_t);
+static void (KRB5_CALLCONV *clear_target)(void);
=20
 #ifdef HAVE_DLOPEN
-static void *cc_handle;=20
+static void *cc_handle;
 #endif
=20
 typedef struct krb5_acc {
@@ -53,7 +56,7 @@
     cc_ccache_t ccache;
 } krb5_acc;
=20
-static krb5_error_code acc_close(krb5_context, krb5_ccache);
+static krb5_error_code KRB5_CALLCONV acc_close(krb5_context, krb5_ccache);
=20
 #define ACACHE(X) ((krb5_acc *)(X)->data.data)
=20
@@ -68,14 +71,15 @@
     { ccIteratorEnd,		KRB5_CC_END },
     { ccErrNoMem,		KRB5_CC_NOMEM },
     { ccErrServerUnavailable,	KRB5_CC_NOSUPP },
+    { ccErrInvalidCCache,	KRB5_CC_BADNAME },
     { ccNoError,		0 }
 };
=20
 static krb5_error_code
 translate_cc_error(krb5_context context, cc_int32 error)
 {
-    int i;
-    krb5_clear_error_string(context);
+    size_t i;
+    krb5_clear_error_message(context);
     for(i =3D 0; i < sizeof(cc_errors)/sizeof(cc_errors[0]); i++)
 	if (cc_errors[i].error =3D=3D error)
 	    return cc_errors[i].ret;
@@ -85,21 +89,25 @@
 static krb5_error_code
 init_ccapi(krb5_context context)
 {
-    const char *lib;
+    const char *lib =3D NULL;
=20
     HEIMDAL_MUTEX_lock(&acc_mutex);
     if (init_func) {
 	HEIMDAL_MUTEX_unlock(&acc_mutex);
-	krb5_clear_error_string(context);
+	if (context)
+	    krb5_clear_error_message(context);
 	return 0;
     }
=20
-    lib =3D krb5_config_get_string(context, NULL,
-				 "libdefaults", "ccapi_library",=20
-				 NULL);
+    if (context)
+	lib =3D krb5_config_get_string(context, NULL,
+				     "libdefaults", "ccapi_library",
+				     NULL);
     if (lib =3D=3D NULL) {
 #ifdef __APPLE__
 	lib =3D "/System/Library/Frameworks/Kerberos.framework/Kerberos";
+#elif defined(KRB5_USE_PATH_TOKENS) && defined(_WIN32)
+	lib =3D "%{LIBDIR}/libkrb5_cc.dll";
 #else
 	lib =3D "/usr/lib/libkrb5_cc.so";
 #endif
@@ -110,19 +118,42 @@
 #ifndef RTLD_LAZY
 #define RTLD_LAZY 0
 #endif
+#ifndef RTLD_LOCAL
+#define RTLD_LOCAL 0
+#endif
=20
-    cc_handle =3D dlopen(lib, RTLD_LAZY);
+#ifdef KRB5_USE_PATH_TOKENS
+    {
+      char * explib =3D NULL;
+      if (_krb5_expand_path_tokens(context, lib, &explib) =3D=3D 0) {
+	cc_handle =3D dlopen(explib, RTLD_LAZY|RTLD_LOCAL);
+	free(explib);
+      }
+    }
+#else
+    cc_handle =3D dlopen(lib, RTLD_LAZY|RTLD_LOCAL);
+#endif
+
     if (cc_handle =3D=3D NULL) {
 	HEIMDAL_MUTEX_unlock(&acc_mutex);
-	krb5_set_error_string(context, "Failed to load %s", lib);
+	if (context)
+	    krb5_set_error_message(context, KRB5_CC_NOSUPP,
+				   N_("Failed to load API cache module %s", "file"),
+				   lib);
 	return KRB5_CC_NOSUPP;
     }
=20
     init_func =3D (cc_initialize_func)dlsym(cc_handle, "cc_initialize");
+    set_target_uid =3D (void (KRB5_CALLCONV *)(uid_t))
+	dlsym(cc_handle, "krb5_ipc_client_set_target_uid");
+    clear_target =3D (void (KRB5_CALLCONV *)(void))
+	dlsym(cc_handle, "krb5_ipc_client_clear_target");
     HEIMDAL_MUTEX_unlock(&acc_mutex);
     if (init_func =3D=3D NULL) {
-	krb5_set_error_string(context, "Failed to find cc_initialize"
-			      "in %s: %s", lib, dlerror());
+	if (context)
+	    krb5_set_error_message(context, KRB5_CC_NOSUPP,
+				   N_("Failed to find cc_initialize"
+				      "in %s: %s", "file, error"), lib, dlerror());
 	dlclose(cc_handle);
 	return KRB5_CC_NOSUPP;
     }
@@ -130,10 +161,28 @@
     return 0;
 #else
     HEIMDAL_MUTEX_unlock(&acc_mutex);
-    krb5_set_error_string(context, "no support for shared object");
+    if (context)
+	krb5_set_error_message(context, KRB5_CC_NOSUPP,
+			       N_("no support for shared object", ""));
     return KRB5_CC_NOSUPP;
 #endif
-}   =20
+}
+
+void
+_heim_krb5_ipc_client_set_target_uid(uid_t uid)
+{
+    init_ccapi(NULL);
+    if (set_target_uid !=3D NULL)
+        (*set_target_uid)(uid);
+}
+
+void
+_heim_krb5_ipc_client_clear_target(void)
+{
+    init_ccapi(NULL);
+    if (clear_target !=3D NULL)
+        (*clear_target)();
+}
=20
 static krb5_error_code
 make_cred_from_ccred(krb5_context context,
@@ -141,7 +190,7 @@
 		     krb5_creds *cred)
 {
     krb5_error_code ret;
-    int i;
+    unsigned int i;
=20
     memset(cred, 0, sizeof(*cred));
=20
@@ -180,13 +229,13 @@
=20
     cred->authdata.val =3D NULL;
     cred->authdata.len =3D 0;
-   =20
+
     cred->addresses.val =3D NULL;
     cred->addresses.len =3D 0;
-   =20
+
     for (i =3D 0; incred->authdata && incred->authdata[i]; i++)
 	;
-   =20
+
     if (i) {
 	cred->authdata.val =3D calloc(i, sizeof(cred->authdata.val[0]));
 	if (cred->authdata.val =3D=3D NULL)
@@ -201,16 +250,16 @@
 		goto nomem;
 	}
     }
-   =20
+
     for (i =3D 0; incred->addresses && incred->addresses[i]; i++)
 	;
-   =20
+
     if (i) {
 	cred->addresses.val =3D calloc(i, sizeof(cred->addresses.val[0]));
 	if (cred->addresses.val =3D=3D NULL)
 	    goto nomem;
 	cred->addresses.len =3D i;
-=09
+
 	for (i =3D 0; i < cred->addresses.len; i++) {
 	    cred->addresses.val[i].addr_type =3D incred->addresses[i]->type;
 	    ret =3D krb5_data_copy(&cred->addresses.val[i].address,
@@ -220,7 +269,7 @@
 		goto nomem;
 	}
     }
-   =20
+
     cred->flags.i =3D 0;
     if (incred->ticket_flags & KRB5_CCAPI_TKT_FLG_FORWARDABLE)
 	cred->flags.b.forwardable =3D 1;
@@ -252,11 +301,11 @@
 	cred->flags.b.anonymous =3D 1;
=20
     return 0;
-   =20
+
 nomem:
     ret =3D ENOMEM;
-    krb5_set_error_string(context, "malloc - out of memory");
-   =20
+    krb5_set_error_message(context, ret, N_("malloc: out of memory", "mall=
oc"));
+
 fail:
     krb5_free_cred_contents(context, cred);
     return ret;
@@ -288,7 +337,7 @@
 		     cc_credentials_v5_t *cred)
 {
     krb5_error_code ret;
-    int i;
+    size_t i;
=20
     memset(cred, 0, sizeof(*cred));
=20
@@ -317,8 +366,8 @@
=20
     /* XXX this one should also be filled in */
     cred->authdata =3D NULL;
-   =20
-    cred->addresses =3D calloc(incred->addresses.len + 1,=20
+
+    cred->addresses =3D calloc(incred->addresses.len + 1,
 			     sizeof(cred->addresses[0]));
     if (cred->addresses =3D=3D NULL) {
=20
@@ -337,10 +386,11 @@
 	addr->length =3D incred->addresses.val[i].address.length;
 	addr->data =3D malloc(addr->length);
 	if (addr->data =3D=3D NULL) {
+	    free(addr);
 	    ret =3D ENOMEM;
 	    goto fail;
 	}
-	memcpy(addr->data, incred->addresses.val[i].address.data,=20
+	memcpy(addr->data, incred->addresses.val[i].address.data,
 	       addr->length);
 	cred->addresses[i] =3D addr;
     }
@@ -378,49 +428,69 @@
=20
     return 0;
=20
-fail:   =20
+fail:
     free_ccred(cred);
=20
-    krb5_clear_error_string(context);
+    krb5_clear_error_message(context);
     return ret;
 }
=20
-static char *
-get_cc_name(cc_ccache_t cache)
+static cc_int32
+get_cc_name(krb5_acc *a)
 {
     cc_string_t name;
     cc_int32 error;
-    char *str;
=20
-    error =3D (*cache->func->get_name)(cache, &name);
+    error =3D (*a->ccache->func->get_name)(a->ccache, &name);
     if (error)
-	return NULL;
+	return error;
=20
-    str =3D strdup(name->data);
+    a->cache_name =3D strdup(name->data);
     (*name->func->release)(name);
-    return str;
+    if (a->cache_name =3D=3D NULL)
+	return ccErrNoMem;
+    return ccNoError;
 }
=20
=20
-static const char*
+static const char* KRB5_CALLCONV
 acc_get_name(krb5_context context,
 	     krb5_ccache id)
 {
     krb5_acc *a =3D ACACHE(id);
-    static char n[255];
-    char *name;
+    int32_t error;
=20
-    name =3D get_cc_name(a->ccache);
-    if (name =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return NULL;
+    if (a->cache_name =3D=3D NULL) {
+	krb5_error_code ret;
+	krb5_principal principal;
+	char *name;
+
+	ret =3D _krb5_get_default_principal_local(context, &principal);
+	if (ret)
+	    return NULL;
+
+	ret =3D krb5_unparse_name(context, principal, &name);
+	krb5_free_principal(context, principal);
+	if (ret)
+	    return NULL;
+
+	error =3D (*a->context->func->create_new_ccache)(a->context,
+						       cc_credentials_v5,
+						       name,
+						       &a->ccache);
+	krb5_xfree(name);
+	if (error)
+	    return NULL;
+
+	error =3D get_cc_name(a);
+	if (error)
+	    return NULL;
     }
-    strlcpy(n, name, sizeof(n));
-    free(name);
-    return n;
+
+    return a->cache_name;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_alloc(krb5_context context, krb5_ccache *id)
 {
     krb5_error_code ret;
@@ -433,10 +503,10 @@
=20
     ret =3D krb5_data_alloc(&(*id)->data, sizeof(*a));
     if (ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
-   =20
+
     a =3D ACACHE(*id);
=20
     error =3D (*init_func)(&a->context, ccapi_version_3, NULL, NULL);
@@ -450,7 +520,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_resolve(krb5_context context, krb5_ccache *id, const char *res)
 {
     krb5_error_code ret;
@@ -463,20 +533,25 @@
=20
     a =3D ACACHE(*id);
=20
-    error =3D (*a->context->func->open_ccache)(a->context, res,
-					     &a->ccache);
-    if (error =3D=3D 0) {
-	a->cache_name =3D get_cc_name(a->ccache);
-	if (a->cache_name =3D=3D NULL) {
+    error =3D (*a->context->func->open_ccache)(a->context, res, &a->ccache=
);
+    if (error =3D=3D ccNoError) {
+	cc_time_t offset;
+	error =3D get_cc_name(a);
+	if (error !=3D ccNoError) {
 	    acc_close(context, *id);
 	    *id =3D NULL;
-	    krb5_set_error_string(context, "malloc: out of memory");
-	    return ENOMEM;
+	    return translate_cc_error(context, error);
 	}
+
+	error =3D (*a->ccache->func->get_kdc_time_offset)(a->ccache,
+							cc_credentials_v5,
+							&offset);
+	if (error =3D=3D 0)
+	    context->kdc_sec_offset =3D offset;
+
     } else if (error =3D=3D ccErrCCacheNotFound) {
 	a->ccache =3D NULL;
 	a->cache_name =3D NULL;
-	error =3D 0;
     } else {
 	*id =3D NULL;
 	return translate_cc_error(context, error);
@@ -485,7 +560,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_gen_new(krb5_context context, krb5_ccache *id)
 {
     krb5_error_code ret;
@@ -503,7 +578,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_initialize(krb5_context context,
 	       krb5_ccache id,
 	       krb5_principal primary_principal)
@@ -517,16 +592,47 @@
     if (ret)
 	return ret;
=20
-    error =3D (*a->context->func->create_new_ccache)(a->context,
-						   cc_credentials_v5,
-						   name,
-						   &a->ccache);
-    free(name);
+    if (a->cache_name =3D=3D NULL) {
+	error =3D (*a->context->func->create_new_ccache)(a->context,
+						       cc_credentials_v5,
+						       name,
+						       &a->ccache);
+	free(name);
+	if (error =3D=3D ccNoError)
+	    error =3D get_cc_name(a);
+    } else {
+	cc_credentials_iterator_t iter;
+	cc_credentials_t ccred;
+
+	error =3D (*a->ccache->func->new_credentials_iterator)(a->ccache, &iter);
+	if (error) {
+	    free(name);
+	    return translate_cc_error(context, error);
+	}
+
+	while (1) {
+	    error =3D (*iter->func->next)(iter, &ccred);
+	    if (error)
+		break;
+	    (*a->ccache->func->remove_credentials)(a->ccache, ccred);
+	    (*ccred->func->release)(ccred);
+	}
+	(*iter->func->release)(iter);
+
+	error =3D (*a->ccache->func->set_principal)(a->ccache,
+						  cc_credentials_v5,
+						  name);
+    }
+
+    if (error =3D=3D 0 && context->kdc_sec_offset)
+	error =3D (*a->ccache->func->set_kdc_time_offset)(a->ccache,
+							cc_credentials_v5,
+							context->kdc_sec_offset);
=20
     return translate_cc_error(context, error);
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_close(krb5_context context,
 	  krb5_ccache id)
 {
@@ -540,13 +646,15 @@
 	free(a->cache_name);
 	a->cache_name =3D NULL;
     }
-    (*a->context->func->release)(a->context);
-    a->context =3D NULL;
+    if (a->context) {
+	(*a->context->func->release)(a->context);
+	a->context =3D NULL;
+    }
     krb5_data_free(&id->data);
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_destroy(krb5_context context,
 	    krb5_ccache id)
 {
@@ -564,7 +672,7 @@
     return translate_cc_error(context, error);
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_store_cred(krb5_context context,
 	       krb5_ccache id,
 	       krb5_creds *creds)
@@ -574,16 +682,17 @@
     cc_credentials_v5_t v5cred;
     krb5_error_code ret;
     cc_int32 error;
-   =20
+
     if (a->ccache =3D=3D NULL) {
-	krb5_set_error_string(context, "No API credential found");
+	krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+			       N_("No API credential found", ""));
 	return KRB5_CC_NOTFOUND;
     }
=20
     cred.version =3D cc_credentials_v5;
     cred.credentials.credentials_v5 =3D &v5cred;
=20
-    ret =3D make_ccred_from_cred(context,=20
+    ret =3D make_ccred_from_cred(context,
 			       creds,
 			       &v5cred);
     if (ret)
@@ -598,7 +707,7 @@
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_get_principal(krb5_context context,
 		  krb5_ccache id,
 		  krb5_principal *principal)
@@ -609,7 +718,8 @@
     cc_string_t name;
=20
     if (a->ccache =3D=3D NULL) {
-	krb5_set_error_string(context, "No API credential found");
+	krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+			       N_("No API credential found", ""));
 	return KRB5_CC_NOTFOUND;
     }
=20
@@ -618,14 +728,14 @@
 					      &name);
     if (error)
 	return translate_cc_error(context, error);
-   =20
+
     ret =3D krb5_parse_name(context, name->data, principal);
-   =20
+
     (*name->func->release)(name);
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_get_first (krb5_context context,
 	       krb5_ccache id,
 	       krb5_cc_cursor *cursor)
@@ -633,15 +743,16 @@
     cc_credentials_iterator_t iter;
     krb5_acc *a =3D ACACHE(id);
     int32_t error;
-   =20
+
     if (a->ccache =3D=3D NULL) {
-	krb5_set_error_string(context, "No API credential found");
+	krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+			       N_("No API credential found", ""));
 	return KRB5_CC_NOTFOUND;
     }
=20
     error =3D (*a->ccache->func->new_credentials_iterator)(a->ccache, &ite=
r);
     if (error) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ENOENT;
     }
     *cursor =3D iter;
@@ -649,7 +760,7 @@
 }
=20
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_get_next (krb5_context context,
 	      krb5_ccache id,
 	      krb5_cc_cursor *cursor,
@@ -669,14 +780,14 @@
 	(*cred->func->release)(cred);
     }
=20
-    ret =3D make_cred_from_ccred(context,=20
+    ret =3D make_cred_from_ccred(context,
 			       cred->data->credentials.credentials_v5,
 			       creds);
     (*cred->func->release)(cred);
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_end_get (krb5_context context,
 	     krb5_ccache id,
 	     krb5_cc_cursor *cursor)
@@ -686,7 +797,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_remove_cred(krb5_context context,
 		krb5_ccache id,
 		krb5_flags which,
@@ -698,9 +809,10 @@
     krb5_error_code ret;
     cc_int32 error;
     char *client, *server;
-   =20
+
     if (a->ccache =3D=3D NULL) {
-	krb5_set_error_string(context, "No API credential found");
+	krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+			       N_("No API credential found", ""));
 	return KRB5_CC_NOTFOUND;
     }
=20
@@ -752,15 +864,16 @@
     (*iter->func->release)(iter);
=20
     if (ret)
-	krb5_set_error_string(context, "Can't find credential %s in cache",=20
-			      server);
+	krb5_set_error_message(context, ret,
+			       N_("Can't find credential %s in cache",
+				 "principal"), server);
     free(server);
     free(client);
=20
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_set_flags(krb5_context context,
 	      krb5_ccache id,
 	      krb5_flags flags)
@@ -768,19 +881,19 @@
     return 0;
 }
=20
-static krb5_error_code
+static int KRB5_CALLCONV
 acc_get_version(krb5_context context,
 		krb5_ccache id)
 {
     return 0;
 }
-		   =20
+
 struct cache_iter {
     cc_context_t context;
     cc_ccache_iterator_t iter;
 };
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
 {
     struct cache_iter *iter;
@@ -793,7 +906,7 @@
=20
     iter =3D calloc(1, sizeof(*iter));
     if (iter =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
=20
@@ -807,14 +920,14 @@
 							&iter->iter);
     if (error) {
 	free(iter);
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ENOENT;
     }
     *cursor =3D iter;
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccach=
e *id)
 {
     struct cache_iter *iter =3D cursor;
@@ -843,17 +956,16 @@
     a =3D ACACHE(*id);
     a->ccache =3D cache;
=20
-    a->cache_name =3D get_cc_name(a->ccache);
-    if (a->cache_name =3D=3D NULL) {
+    error =3D get_cc_name(a);
+    if (error) {
 	acc_close(context, *id);
 	*id =3D NULL;
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }=09
+	return translate_cc_error(context, error);
+    }
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
 {
     struct cache_iter *iter =3D cursor;
@@ -866,7 +978,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 acc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
 {
     krb5_acc *afrom =3D ACACHE(from);
@@ -881,7 +993,7 @@
 						      &name);
 	if (error)
 	    return translate_cc_error(context, error);
-   =20
+
 	error =3D (*ato->context->func->create_new_ccache)(ato->context,
 							 cc_credentials_v5,
 							 name->data,
@@ -891,13 +1003,15 @@
 	    return translate_cc_error(context, error);
     }
=20
+    error =3D (*ato->ccache->func->move)(afrom->ccache, ato->ccache);
=20
-    error =3D (*ato->ccache->func->move)(afrom->ccache, ato->ccache);
+    acc_destroy(context, from);
+
     return translate_cc_error(context, error);
 }
=20
-static krb5_error_code
-acc_default_name(krb5_context context, char **str)
+static krb5_error_code KRB5_CALLCONV
+acc_get_default_name(krb5_context context, char **str)
 {
     krb5_error_code ret;
     cc_context_t cc;
@@ -917,18 +1031,58 @@
 	(*cc->func->release)(cc);
 	return translate_cc_error(context, error);
     }
-=09
-    asprintf(str, "API:%s", name->data);
+
+    error =3D asprintf(str, "API:%s", name->data);
     (*name->func->release)(name);
     (*cc->func->release)(cc);
=20
-    if (*str =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+    if (error < 0 || *str =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
+static krb5_error_code KRB5_CALLCONV
+acc_set_default(krb5_context context, krb5_ccache id)
+{
+    krb5_acc *a =3D ACACHE(id);
+    cc_int32 error;
+
+    if (a->ccache =3D=3D NULL) {
+	krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+			       N_("No API credential found", ""));
+	return KRB5_CC_NOTFOUND;
+    }
+
+    error =3D (*a->ccache->func->set_default)(a->ccache);
+    if (error)
+	return translate_cc_error(context, error);
+
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+acc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+    krb5_acc *a =3D ACACHE(id);
+    cc_int32 error;
+    cc_time_t t;
+
+    if (a->ccache =3D=3D NULL) {
+	krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+			       N_("No API credential found", ""));
+	return KRB5_CC_NOTFOUND;
+    }
+
+    error =3D (*a->ccache->func->get_change_time)(a->ccache, &t);
+    if (error)
+	return translate_cc_error(context, error);
+
+    *mtime =3D t;
+
+    return 0;
+}
=20
 /**
  * Variable containing the API based credential cache implemention.
@@ -936,7 +1090,8 @@
  * @ingroup krb5_ccache
  */
=20
-const krb5_cc_ops krb5_acc_ops =3D {
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_acc_ops =3D {
+    KRB5_CC_OPS_VERSION,
     "API",
     acc_get_name,
     acc_resolve,
@@ -957,5 +1112,11 @@
     acc_get_cache_next,
     acc_end_cache_get,
     acc_move,
-    acc_default_name
+    acc_get_default_name,
+    acc_set_default,
+    acc_lastchange,
+    NULL,
+    NULL,
 };
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/acl.c
--- a/head/crypto/heimdal/lib/krb5/acl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/acl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000 - 2002, 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000 - 2002, 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -34,8 +34,6 @@
 #include "krb5_locl.h"
 #include <fnmatch.h>
=20
-RCSID("$Id: acl.c 22119 2007-12-03 22:02:48Z lha $");
-
 struct acl_field {
     enum { acl_string, acl_fnmatch, acl_retval } type;
     union {
@@ -83,7 +81,8 @@
     for(p =3D format; *p !=3D '\0'; p++) {
 	tmp =3D malloc(sizeof(*tmp));
 	if(tmp =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
 	    acl_free_list(acl, 0);
 	    return ENOMEM;
 	}
@@ -98,8 +97,9 @@
 	    tmp->u.retv =3D va_arg(ap, char **);
 	    *tmp->u.retv =3D NULL;
 	} else {
-	    krb5_set_error_string(context, "acl_parse_format: "
-				  "unknown format specifier %c", *p);
+	    krb5_set_error_message(context, EINVAL,
+				   N_("Unknown format specifier %c while "
+				     "parsing ACL", "specifier"), *p);
 	    acl_free_list(acl, 0);
 	    free(tmp);
 	    return EINVAL;
@@ -180,7 +180,7 @@
  *
  * @code
  * char *s;
- *=20
+ *
  * ret =3D krb5_acl_match_string(context, "foo", "s", "foo");
  * if (ret)
  *     krb5_errx(context, 1, "acl didn't match");
@@ -198,7 +198,7 @@
  * @ingroup krb5_support
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_acl_match_string(krb5_context context,
 		      const char *string,
 		      const char *format,
@@ -220,11 +220,11 @@
     if (found) {
 	return 0;
     } else {
-	krb5_set_error_string(context, "ACL did not match");
+	krb5_set_error_message(context, EACCES, N_("ACL did not match", ""));
 	return EACCES;
     }
 }
-	      =20
+
 /**
  * krb5_acl_match_file matches ACL format against each line in a file
  * using krb5_acl_match_string(). Lines starting with # are treated
@@ -241,7 +241,7 @@
  * @ingroup krb5_support
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_acl_match_file(krb5_context context,
 		    const char *file,
 		    const char *format,
@@ -257,11 +257,13 @@
     f =3D fopen(file, "r");
     if(f =3D=3D NULL) {
 	int save_errno =3D errno;
-
-	krb5_set_error_string(context, "open(%s): %s", file,
-			      strerror(save_errno));
+	rk_strerror_r(save_errno, buf, sizeof(buf));
+	krb5_set_error_message(context, save_errno,
+			       N_("open(%s): %s", "file, errno"),
+			       file, buf);
 	return save_errno;
     }
+    rk_cloexec_file(f);
=20
     va_start(ap, format);
     ret =3D acl_parse_format(context, &acl, format, ap);
@@ -287,7 +289,7 @@
     if (found) {
 	return 0;
     } else {
-	krb5_set_error_string(context, "ACL did not match");
+	krb5_set_error_message(context, EACCES, N_("ACL did not match", ""));
 	return EACCES;
     }
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/add_et_li=
st.c
--- a/head/crypto/heimdal/lib/krb5/add_et_list.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/add_et_list.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,47 +1,53 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: add_et_list.c 13713 2004-04-13 14:33:45Z lha $");
-
-/*
+/**
  * Add a specified list of error messages to the et list in context.
  * Call func (probably a comerr-generated function) with a pointer to
  * the current et_list.
+ *
+ * @param context A kerberos context.
+ * @param func The generated com_err et function.
+ *
+ * @return Returns 0 to indicate success.  Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_add_et_list (krb5_context context,
 		  void (*func)(struct et_list **))
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/addr_fami=
lies.c
--- a/head/crypto/heimdal/lib/krb5/addr_families.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/addr_families.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: addr_families.c 22039 2007-11-10 11:47:35Z lha $");
-
 struct addr_operations {
     int af;
     krb5_address_type atype;
@@ -46,14 +44,15 @@
     void (*h_addr2sockaddr)(const char *, struct sockaddr *, krb5_socklen_=
t *, int);
     krb5_error_code (*h_addr2addr)(const char *, krb5_address *);
     krb5_boolean (*uninteresting)(const struct sockaddr *);
+    krb5_boolean (*is_loopback)(const struct sockaddr *);
     void (*anyaddr)(struct sockaddr *, krb5_socklen_t *, int);
     int (*print_addr)(const krb5_address *, char *, size_t);
     int (*parse_addr)(krb5_context, const char*, krb5_address *);
     int (*order_addr)(krb5_context, const krb5_address*, const krb5_addres=
s*);
     int (*free_addr)(krb5_context, krb5_address*);
     int (*copy_addr)(krb5_context, const krb5_address*, krb5_address*);
-    int (*mask_boundary)(krb5_context, const krb5_address*, unsigned long,=20
-				     krb5_address*, krb5_address*);
+    int (*mask_boundary)(krb5_context, const krb5_address*, unsigned long,
+			 krb5_address*, krb5_address*);
 };
=20
 /*
@@ -138,6 +137,17 @@
     return FALSE;
 }
=20
+static krb5_boolean
+ipv4_is_loopback (const struct sockaddr *sa)
+{
+    const struct sockaddr_in *sin4 =3D (const struct sockaddr_in *)sa;
+
+    if ((ntohl(sin4->sin_addr.s_addr) >> 24) =3D=3D IN_LOOPBACKNET)
+	return TRUE;
+
+    return FALSE;
+}
+
 static void
 ipv4_anyaddr (struct sockaddr *sa, krb5_socklen_t *sa_size, int port)
 {
@@ -177,16 +187,8 @@
 	    return -1;
     } else
 	p =3D address;
-#ifdef HAVE_INET_ATON
     if(inet_aton(p, &a) =3D=3D 0)
 	return -1;
-#elif defined(HAVE_INET_ADDR)
-    a.s_addr =3D inet_addr(p);
-    if(a.s_addr =3D=3D INADDR_NONE)
-	return -1;
-#else
-    return -1;
-#endif
     addr->addr_type =3D KRB5_ADDRESS_INET;
     if(krb5_data_alloc(&addr->address, 4) !=3D 0)
 	return -1;
@@ -202,7 +204,8 @@
     uint32_t l, h, m =3D 0xffffffff;
=20
     if (len > 32) {
-	krb5_set_error_string(context, "IPv4 prefix too large (%ld)", len);
+	krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+			       N_("IPv4 prefix too large (%ld)", "len"), len);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
     m =3D m << (32 - len);
@@ -310,7 +313,7 @@
 }
=20
 /*
- *=20
+ *
  */
=20
 static krb5_boolean
@@ -318,12 +321,20 @@
 {
     const struct sockaddr_in6 *sin6 =3D (const struct sockaddr_in6 *)sa;
     const struct in6_addr *in6 =3D (const struct in6_addr *)&sin6->sin6_ad=
dr;
-   =20
-    return
-	IN6_IS_ADDR_LINKLOCAL(in6)
+
+    return IN6_IS_ADDR_LINKLOCAL(in6)
 	|| IN6_IS_ADDR_V4COMPAT(in6);
 }
=20
+static krb5_boolean
+ipv6_is_loopback (const struct sockaddr *sa)
+{
+    const struct sockaddr_in6 *sin6 =3D (const struct sockaddr_in6 *)sa;
+    const struct in6_addr *in6 =3D (const struct in6_addr *)&sin6->sin6_ad=
dr;
+
+    return (IN6_IS_ADDR_LOOPBACK(in6));
+}
+
 static void
 ipv6_anyaddr (struct sockaddr *sa, krb5_socklen_t *sa_size, int port)
 {
@@ -340,12 +351,10 @@
 ipv6_print_addr (const krb5_address *addr, char *str, size_t len)
 {
     char buf[128], buf2[3];
-#ifdef HAVE_INET_NTOP
     if(inet_ntop(AF_INET6, addr->address.data, buf, sizeof(buf)) =3D=3D NU=
LL)
-#endif
 	{
 	    /* XXX this is pretty ugly, but better than abort() */
-	    int i;
+	    size_t i;
 	    unsigned char *p =3D addr->address.data;
 	    buf[0] =3D '\0';
 	    for(i =3D 0; i < addr->address.length; i++) {
@@ -395,12 +404,14 @@
     int i, sub_len;
=20
     if (len > 128) {
-	krb5_set_error_string(context, "IPv6 prefix too large (%ld)", len);
+	krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+			       N_("IPv6 prefix too large (%ld)", "length"), len);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
=20
     if (inaddr->address.length !=3D sizeof(addr)) {
-	krb5_set_error_string(context, "IPv6 addr bad length");
+	krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+			       N_("IPv6 addr bad length", ""));
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
=20
@@ -410,7 +421,7 @@
 	sub_len =3D min(8, len);
=20
 	m =3D 0xff << (8 - sub_len);
-=09
+
 	laddr.s6_addr[i] =3D addr.s6_addr[i] & m;
 	haddr.s6_addr[i] =3D (addr.s6_addr[i] & m) | ~m;
=20
@@ -437,6 +448,8 @@
=20
 #endif /* IPv6 */
=20
+#ifndef HEIMDAL_SMALLER
+
 /*
  * table
  */
@@ -449,17 +462,17 @@
 };
=20
 static int
-arange_parse_addr (krb5_context context,=20
+arange_parse_addr (krb5_context context,
 		   const char *address, krb5_address *addr)
 {
     char buf[1024], *p;
     krb5_address low0, high0;
     struct arange *a;
     krb5_error_code ret;
-   =20
+
     if(strncasecmp(address, "RANGE:", 6) !=3D 0)
 	return -1;
-   =20
+
     address +=3D 6;
=20
     p =3D strrchr(address, '/');
@@ -478,7 +491,7 @@
 	    krb5_free_addresses(context, &addrmask);
 	    return -1;
 	}
-=09
+
 	address +=3D p - address + 1;
=20
 	num =3D strtol(address, &q, 10);
@@ -495,7 +508,7 @@
=20
     } else {
 	krb5_addresses low, high;
-=09
+
 	strsep_copy(&address, "-", buf, sizeof(buf));
 	ret =3D krb5_parse_address(context, buf, &low);
 	if(ret)
@@ -504,14 +517,14 @@
 	    krb5_free_addresses(context, &low);
 	    return -1;
 	}
-=09
+
 	strsep_copy(&address, "-", buf, sizeof(buf));
 	ret =3D krb5_parse_address(context, buf, &high);
 	if(ret) {
 	    krb5_free_addresses(context, &low);
 	    return ret;
 	}
-=09
+
 	if(high.len !=3D 1 && high.val[0].addr_type !=3D low.val[0].addr_type) {
 	    krb5_free_addresses(context, &low);
 	    krb5_free_addresses(context, &high);
@@ -557,7 +570,7 @@
=20
=20
 static int
-arange_copy (krb5_context context, const krb5_address *inaddr,=20
+arange_copy (krb5_context context, const krb5_address *inaddr,
 	     krb5_address *outaddr)
 {
     krb5_error_code ret;
@@ -597,7 +610,7 @@
     if (l > len)
 	l =3D len;
     size =3D l;
-=09
+
     ret =3D krb5_print_address (&a->low, str + size, len - size, &l);
     if (ret)
 	return ret;
@@ -623,8 +636,8 @@
 }
=20
 static int
-arange_order_addr(krb5_context context,=20
-		  const krb5_address *addr1,=20
+arange_order_addr(krb5_context context,
+		  const krb5_address *addr1,
 		  const krb5_address *addr2)
 {
     int tmp1, tmp2, sign;
@@ -639,9 +652,11 @@
 	a =3D addr2->address.data;
 	a2 =3D addr1;
 	sign =3D -1;
-    } else
+    } else {
 	abort();
-=09
+        UNREACHABLE(return 0);
+    }
+
     if(a2->addr_type =3D=3D KRB5_ADDRESS_ARANGE) {
 	struct arange *b =3D a2->address.data;
 	tmp1 =3D krb5_address_order(context, &a->low, &b->low);
@@ -661,6 +676,8 @@
     }
 }
=20
+#endif /* HEIMDAL_SMALLER */
+
 static int
 addrport_print_addr (const krb5_address *addr, char *str, size_t len)
 {
@@ -671,6 +688,9 @@
     krb5_storage *sp;
=20
     sp =3D krb5_storage_from_data((krb5_data*)rk_UNCONST(&addr->address));
+    if (sp =3D=3D NULL)
+        return ENOMEM;
+
     /* for totally obscure reasons, these are not in network byteorder */
     krb5_storage_set_byteorder(sp, KRB5_STORAGE_BYTEORDER_LE);
=20
@@ -709,32 +729,78 @@
 }
=20
 static struct addr_operations at[] =3D {
-    {AF_INET,	KRB5_ADDRESS_INET, sizeof(struct sockaddr_in),
-     ipv4_sockaddr2addr,=20
-     ipv4_sockaddr2port,
-     ipv4_addr2sockaddr,
-     ipv4_h_addr2sockaddr,
-     ipv4_h_addr2addr,
-     ipv4_uninteresting, ipv4_anyaddr, ipv4_print_addr, ipv4_parse_addr,
-     NULL, NULL, NULL, ipv4_mask_boundary },
+    {
+	AF_INET,	KRB5_ADDRESS_INET, sizeof(struct sockaddr_in),
+	ipv4_sockaddr2addr,
+	ipv4_sockaddr2port,
+	ipv4_addr2sockaddr,
+	ipv4_h_addr2sockaddr,
+	ipv4_h_addr2addr,
+	ipv4_uninteresting,
+	ipv4_is_loopback,
+	ipv4_anyaddr,
+	ipv4_print_addr,
+	ipv4_parse_addr,
+	NULL,
+	NULL,
+	NULL,
+     ipv4_mask_boundary
+    },
 #ifdef HAVE_IPV6
-    {AF_INET6,	KRB5_ADDRESS_INET6, sizeof(struct sockaddr_in6),
-     ipv6_sockaddr2addr,=20
-     ipv6_sockaddr2port,
-     ipv6_addr2sockaddr,
-     ipv6_h_addr2sockaddr,
-     ipv6_h_addr2addr,
-     ipv6_uninteresting, ipv6_anyaddr, ipv6_print_addr, ipv6_parse_addr,
-     NULL, NULL, NULL, ipv6_mask_boundary } ,
+    {
+	AF_INET6,	KRB5_ADDRESS_INET6, sizeof(struct sockaddr_in6),
+	ipv6_sockaddr2addr,
+	ipv6_sockaddr2port,
+	ipv6_addr2sockaddr,
+	ipv6_h_addr2sockaddr,
+	ipv6_h_addr2addr,
+	ipv6_uninteresting,
+	ipv6_is_loopback,
+	ipv6_anyaddr,
+	ipv6_print_addr,
+	ipv6_parse_addr,
+	NULL,
+	NULL,
+	NULL,
+	ipv6_mask_boundary
+    } ,
 #endif
-    {KRB5_ADDRESS_ADDRPORT, KRB5_ADDRESS_ADDRPORT, 0,
-     NULL, NULL, NULL, NULL, NULL,=20
-     NULL, NULL, addrport_print_addr, NULL, NULL, NULL, NULL },
+#ifndef HEIMDAL_SMALLER
     /* fake address type */
-    {KRB5_ADDRESS_ARANGE, KRB5_ADDRESS_ARANGE, sizeof(struct arange),
-     NULL, NULL, NULL, NULL, NULL, NULL, NULL,
-     arange_print_addr, arange_parse_addr,=20
-     arange_order_addr, arange_free, arange_copy }
+    {
+	KRB5_ADDRESS_ARANGE, KRB5_ADDRESS_ARANGE, sizeof(struct arange),
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	arange_print_addr,
+	arange_parse_addr,
+	arange_order_addr,
+	arange_free,
+	arange_copy,
+	NULL
+    },
+#endif
+    {
+	KRB5_ADDRESS_ADDRPORT, KRB5_ADDRESS_ADDRPORT, 0,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	NULL,
+	addrport_print_addr,
+	NULL,
+	NULL,
+	NULL,
+	NULL
+    }
 };
=20
 static int num_addrs =3D sizeof(at) / sizeof(at[0]);
@@ -757,7 +823,7 @@
 }
=20
 static struct addr_operations *
-find_atype(int atype)
+find_atype(krb5_address_type atype)
 {
     struct addr_operations *a;
=20
@@ -769,7 +835,7 @@
=20
 /**
  * krb5_sockaddr2address stores a address a "struct sockaddr" sa in
- * the krb5_address addr.=20
+ * the krb5_address addr.
  *
  * @param context a Keberos context
  * @param sa a struct sockaddr to extract the address from
@@ -780,14 +846,15 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sockaddr2address (krb5_context context,
 		       const struct sockaddr *sa, krb5_address *addr)
 {
     struct addr_operations *a =3D find_af(sa->sa_family);
     if (a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address family %d not supported",
-			       sa->sa_family);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				N_("Address family %d not supported", ""),
+				sa->sa_family);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
     return (*a->sockaddr2addr)(sa, addr);
@@ -807,14 +874,15 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sockaddr2port (krb5_context context,
 		    const struct sockaddr *sa, int16_t *port)
 {
     struct addr_operations *a =3D find_af(sa->sa_family);
     if (a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address family %d not supported",
-			       sa->sa_family);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				N_("Address family %d not supported", ""),
+				sa->sa_family);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
     return (*a->sockaddr2port)(sa, port);
@@ -841,7 +909,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_addr2sockaddr (krb5_context context,
 		    const krb5_address *addr,
 		    struct sockaddr *sa,
@@ -851,14 +919,17 @@
     struct addr_operations *a =3D find_atype(addr->addr_type);
=20
     if (a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address type %d not supported",
-			       addr->addr_type);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				N_("Address type %d not supported",
+				   "krb5_address type"),
+				addr->addr_type);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
     if (a->addr2sockaddr =3D=3D NULL) {
-	krb5_set_error_string (context,
-			       "Can't convert address type %d to sockaddr",
-			       addr->addr_type);
+	krb5_set_error_message (context,
+				KRB5_PROG_ATYPE_NOSUPP,
+				N_("Can't convert address type %d to sockaddr", ""),
+				addr->addr_type);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
     (*a->addr2sockaddr)(addr, sa, sa_size, port);
@@ -874,7 +945,7 @@
  * @ingroup krb5_address
  */
=20
-size_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
 krb5_max_sockaddr_size (void)
 {
     if (max_sockaddr_size =3D=3D 0) {
@@ -898,7 +969,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_sockaddr_uninteresting(const struct sockaddr *sa)
 {
     struct addr_operations *a =3D find_af(sa->sa_family);
@@ -907,6 +978,15 @@
     return (*a->uninteresting)(sa);
 }
=20
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_sockaddr_is_loopback(const struct sockaddr *sa)
+{
+    struct addr_operations *a =3D find_af(sa->sa_family);
+    if (a =3D=3D NULL || a->is_loopback =3D=3D NULL)
+	return TRUE;
+    return (*a->is_loopback)(sa);
+}
+
 /**
  * krb5_h_addr2sockaddr initializes a "struct sockaddr sa" from af and
  * the "struct hostent" (see gethostbyname(3) ) h_addr_list
@@ -926,7 +1006,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_h_addr2sockaddr (krb5_context context,
 		      int af,
 		      const char *addr, struct sockaddr *sa,
@@ -935,7 +1015,8 @@
 {
     struct addr_operations *a =3D find_af(af);
     if (a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address family %d not supported", af);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				"Address family %d not supported", af);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
     (*a->h_addr2sockaddr)(addr, sa, sa_size, port);
@@ -956,14 +1037,15 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_h_addr2addr (krb5_context context,
 		  int af,
 		  const char *haddr, krb5_address *addr)
 {
     struct addr_operations *a =3D find_af(af);
     if (a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address family %d not supported", af);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				N_("Address family %d not supported", ""), af);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
     return (*a->h_addr2addr)(haddr, addr);
@@ -986,7 +1068,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_anyaddr (krb5_context context,
 	      int af,
 	      struct sockaddr *sa,
@@ -996,7 +1078,8 @@
     struct addr_operations *a =3D find_af (af);
=20
     if (a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address family %d not supported", af);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				N_("Address family %d not supported", ""), af);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
=20
@@ -1020,8 +1103,8 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_print_address (const krb5_address *addr,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_print_address (const krb5_address *addr,
 		    char *str, size_t len, size_t *ret_len)
 {
     struct addr_operations *a =3D find_atype(addr->addr_type);
@@ -1030,17 +1113,17 @@
     if (a =3D=3D NULL || a->print_addr =3D=3D NULL) {
 	char *s;
 	int l;
-	int i;
+	size_t i;
=20
 	s =3D str;
 	l =3D snprintf(s, len, "TYPE_%d:", addr->addr_type);
-	if (l < 0 || l >=3D len)
+	if (l < 0 || (size_t)l >=3D len)
 	    return EINVAL;
 	s +=3D l;
 	len -=3D l;
 	for(i =3D 0; i < addr->address.length; i++) {
 	    l =3D snprintf(s, len, "%02x", ((char*)addr->address.data)[i]);
-	    if (l < 0 || l >=3D len)
+	    if (l < 0 || (size_t)l >=3D len)
 		return EINVAL;
 	    len -=3D l;
 	    s +=3D l;
@@ -1070,7 +1153,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_address(krb5_context context,
 		   const char *string,
 		   krb5_addresses *addresses)
@@ -1089,7 +1172,8 @@
 	    if((*at[i].parse_addr)(context, string, &addr) =3D=3D 0) {
 		ALLOC_SEQ(addresses, 1);
 		if (addresses->val =3D=3D NULL) {
-		    krb5_set_error_string(context, "malloc: out of memory");
+		    krb5_set_error_message(context, ENOMEM,
+					   N_("malloc: out of memory", ""));
 		    return ENOMEM;
 		}
 		addresses->val[0] =3D addr;
@@ -1100,18 +1184,22 @@
=20
     error =3D getaddrinfo (string, NULL, NULL, &ai);
     if (error) {
+	krb5_error_code ret2;
 	save_errno =3D errno;
-	krb5_set_error_string (context, "%s: %s", string, gai_strerror(error));
-	return krb5_eai_to_heim_errno(error, save_errno);
+	ret2 =3D krb5_eai_to_heim_errno(error, save_errno);
+	krb5_set_error_message (context, ret2, "%s: %s",
+				string, gai_strerror(error));
+	return ret2;
     }
-   =20
+
     n =3D 0;
     for (a =3D ai; a !=3D NULL; a =3D a->ai_next)
 	++n;
=20
     ALLOC_SEQ(addresses, n);
     if (addresses->val =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	freeaddrinfo(ai);
 	return ENOMEM;
     }
@@ -1120,10 +1208,12 @@
     for (a =3D ai, i =3D 0; a !=3D NULL; a =3D a->ai_next) {
 	if (krb5_sockaddr2address (context, ai->ai_addr, &addresses->val[i]))
 	    continue;
-	if(krb5_address_search(context, &addresses->val[i], addresses))
+	if(krb5_address_search(context, &addresses->val[i], addresses)) {
+	    krb5_free_address(context, &addresses->val[i]);
 	    continue;
+	}
+	i++;
 	addresses->len =3D i;
-	i++;
     }
     freeaddrinfo (ai);
     return 0;
@@ -1132,7 +1222,7 @@
 /**
  * krb5_address_order compares the addresses addr1 and addr2 so that
  * it can be used for sorting addresses. If the addresses are the same
- * address krb5_address_order will return 0. Behavies like memcmp(2).=20
+ * address krb5_address_order will return 0. Behavies like memcmp(2).
  *
  * @param context a Keberos context
  * @param addr1 krb5_address to compare
@@ -1144,7 +1234,7 @@
  * @ingroup krb5_address
  */
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_address_order(krb5_context context,
 		   const krb5_address *addr1,
 		   const krb5_address *addr2)
@@ -1152,21 +1242,23 @@
     /* this sucks; what if both addresses have order functions, which
        should we call? this works for now, though */
     struct addr_operations *a;
-    a =3D find_atype(addr1->addr_type);=20
+    a =3D find_atype(addr1->addr_type);
     if(a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address family %d not supported",=20
-			       addr1->addr_type);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				N_("Address family %d not supported", ""),
+				addr1->addr_type);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
-    if(a->order_addr !=3D NULL)=20
-	return (*a->order_addr)(context, addr1, addr2);=20
-    a =3D find_atype(addr2->addr_type);=20
+    if(a->order_addr !=3D NULL)
+	return (*a->order_addr)(context, addr1, addr2);
+    a =3D find_atype(addr2->addr_type);
     if(a =3D=3D NULL) {
-	krb5_set_error_string (context, "Address family %d not supported",=20
-			       addr2->addr_type);
+	krb5_set_error_message (context, KRB5_PROG_ATYPE_NOSUPP,
+				N_("Address family %d not supported", ""),
+				addr2->addr_type);
 	return KRB5_PROG_ATYPE_NOSUPP;
     }
-    if(a->order_addr !=3D NULL)=20
+    if(a->order_addr !=3D NULL)
 	return (*a->order_addr)(context, addr1, addr2);
=20
     if(addr1->addr_type !=3D addr2->addr_type)
@@ -1191,7 +1283,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_address_compare(krb5_context context,
 		     const krb5_address *addr1,
 		     const krb5_address *addr2)
@@ -1212,12 +1304,12 @@
  * @ingroup krb5_address
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_address_search(krb5_context context,
 		    const krb5_address *addr,
 		    const krb5_addresses *addrlist)
 {
-    int i;
+    size_t i;
=20
     for (i =3D 0; i < addrlist->len; ++i)
 	if (krb5_address_compare (context, addr, &addrlist->val[i]))
@@ -1237,7 +1329,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_address(krb5_context context,
 		  krb5_address *address)
 {
@@ -1261,11 +1353,11 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_addresses(krb5_context context,
 		    krb5_addresses *addresses)
 {
-    int i;
+    size_t i;
     for(i =3D 0; i < addresses->len; i++)
 	krb5_free_address(context, &addresses->val[i]);
     free(addresses->val);
@@ -1287,7 +1379,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_address(krb5_context context,
 		  const krb5_address *inaddr,
 		  krb5_address *outaddr)
@@ -1311,12 +1403,12 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_addresses(krb5_context context,
 		    const krb5_addresses *inaddr,
 		    krb5_addresses *outaddr)
 {
-    int i;
+    size_t i;
     ALLOC_SEQ(outaddr, inaddr->len);
     if(inaddr->len > 0 && outaddr->val =3D=3D NULL)
 	return ENOMEM;
@@ -1338,18 +1430,19 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_append_addresses(krb5_context context,
 		      krb5_addresses *dest,
 		      const krb5_addresses *source)
 {
     krb5_address *tmp;
     krb5_error_code ret;
-    int i;
+    size_t i;
     if(source->len > 0) {
 	tmp =3D realloc(dest->val, (dest->len + source->len) * sizeof(*tmp));
 	if(tmp =3D=3D NULL) {
-	    krb5_set_error_string(context, "realloc: out of memory");
+	    krb5_set_error_message (context, ENOMEM,
+				    N_("malloc: out of memory", ""));
 	    return ENOMEM;
 	}
 	dest->val =3D tmp;
@@ -1357,8 +1450,8 @@
 	    /* skip duplicates */
 	    if(krb5_address_search(context, &source->val[i], dest))
 		continue;
-	    ret =3D krb5_copy_address(context,=20
-				    &source->val[i],=20
+	    ret =3D krb5_copy_address(context,
+				    &source->val[i],
 				    &dest->val[dest->len]);
 	    if(ret)
 		return ret;
@@ -1381,7 +1474,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_make_addrport (krb5_context context,
 		    krb5_address **res, const krb5_address *addr, int16_t port)
 {
@@ -1391,13 +1484,15 @@
=20
     *res =3D malloc (sizeof(**res));
     if (*res =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message (context, ENOMEM,
+				N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     (*res)->addr_type =3D KRB5_ADDRESS_ADDRPORT;
     ret =3D krb5_data_alloc (&(*res)->address, len);
     if (ret) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message (context, ret,
+				N_("malloc: out of memory", ""));
 	free (*res);
 	*res =3D NULL;
 	return ret;
@@ -1427,7 +1522,6 @@
     *p++ =3D (2 >> 24) & 0xFF;
=20
     memcpy (p, &port, 2);
-    p +=3D 2;
=20
     return 0;
 }
@@ -1447,7 +1541,7 @@
  * @ingroup krb5_address
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_address_prefixlen_boundary(krb5_context context,
 				const krb5_address *inaddr,
 				unsigned long prefixlen,
@@ -1457,7 +1551,9 @@
     struct addr_operations *a =3D find_atype (inaddr->addr_type);
     if(a !=3D NULL && a->mask_boundary !=3D NULL)
 	return (*a->mask_boundary)(context, inaddr, prefixlen, low, high);
-    krb5_set_error_string(context, "Address family %d doesn't support "
-			  "address mask operation", inaddr->addr_type);
+    krb5_set_error_message(context, KRB5_PROG_ATYPE_NOSUPP,
+			   N_("Address family %d doesn't support "
+			      "address mask operation", ""),
+			   inaddr->addr_type);
     return KRB5_PROG_ATYPE_NOSUPP;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/aes-test.c
--- a/head/crypto/heimdal/lib/krb5/aes-test.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/aes-test.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,13 +33,12 @@
 #include "krb5_locl.h"
 #include <hex.h>
 #include <err.h>
+#include <assert.h>
=20
 #ifdef HAVE_OPENSSL
 #include <openssl/evp.h>
 #endif
=20
-RCSID("$Id: aes-test.c 18301 2006-10-07 13:50:34Z lha $");
-
 static int verbose =3D 0;
=20
 static void
@@ -62,16 +61,16 @@
     char *pbkdf2;
     char *key;
 } keys[] =3D {
-    {=20
+    {
 	"password", "ATHENA.MIT.EDUraeburn", -1,
-	1,=20
+	1,
 	ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
 	"\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15",
 	"\x42\x26\x3c\x6e\x89\xf4\xfc\x28\xb8\xdf\x68\xee\x09\x79\x9f\x15"
     },
     {
 	"password", "ATHENA.MIT.EDUraeburn", -1,
-	1,=20
+	1,
 	ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
 	"\xcd\xed\xb5\x28\x1b\xb2\xf8\x01\x56\x5a\x11\x22\xb2\x56\x35\x15"
 	"\x0a\xd1\xf7\xa0\x4b\xb9\xf3\xa3\x33\xec\xc0\xe2\xe1\xf7\x08\x37",
@@ -87,7 +86,7 @@
     },
     {
 	"password", "ATHENA.MIT.EDUraeburn", -1,
-	2,=20
+	2,
 	ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
 	"\x01\xdb\xee\x7f\x4a\x9e\x24\x3e\x98\x8b\x62\xc7\x3c\xda\x93\x5d"
 	"\xa0\x53\x78\xb9\x32\x44\xec\x8f\x48\xa9\x9e\x61\xad\x79\x9d\x86",
@@ -96,14 +95,14 @@
     },
     {
 	"password", "ATHENA.MIT.EDUraeburn", -1,
-	1200,=20
+	1200,
 	ETYPE_AES128_CTS_HMAC_SHA1_96, 16,
 	"\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b",
 	"\x4c\x01\xcd\x46\xd6\x32\xd0\x1e\x6d\xbe\x23\x0a\x01\xed\x64\x2a"
     },
     {
 	"password", "ATHENA.MIT.EDUraeburn", -1,
-	1200,=20
+	1200,
 	ETYPE_AES256_CTS_HMAC_SHA1_96, 32,
 	"\x5c\x08\xeb\x61\xfd\xf7\x1e\x4e\x4e\xc3\xcf\x6b\xa1\xf5\x51\x2b"
 	"\xa7\xe5\x2d\xdb\xc5\xe5\x14\x2f\x70\x8a\x31\xe2\xe6\x2b\x1e\x13",
@@ -180,14 +179,14 @@
 	"\x57\x18\x48\xb7\x84\xa3\xd6\xbd\xc3\x46\x58\x9a\x3e\x39\x3f\x9e"
     },
     {
-	"foo", "", -1,=20
+	"foo", "", -1,
 	0,
 	ETYPE_ARCFOUR_HMAC_MD5, 16,
 	NULL,
 	"\xac\x8e\x65\x7f\x83\xdf\x82\xbe\xea\x5d\x43\xbd\xaf\x78\x00\xcc"
     },
     {
-	"test", "", -1,=20
+	"test", "", -1,
 	0,
 	ETYPE_ARCFOUR_HMAC_MD5, 16,
 	NULL,
@@ -215,11 +214,11 @@
 	    salt.saltvalue.length =3D strlen(salt.saltvalue.data);
 	else
 	    salt.saltvalue.length =3D keys[i].saltlen;
-   =20
+
 	opaque.data =3D iter;
 	opaque.length =3D sizeof(iter);
 	_krb5_put_int(iter, keys[i].iterations, 4);
-=09
+
 	if (keys[i].pbkdf2) {
 	    unsigned char keyout[32];
=20
@@ -228,15 +227,15 @@
=20
 	    PKCS5_PBKDF2_HMAC_SHA1(password.data, password.length,
 				   salt.saltvalue.data, salt.saltvalue.length,
-				   keys[i].iterations,=20
+				   keys[i].iterations,
 				   keys[i].keylen, keyout);
-	   =20
+
 	    if (memcmp(keyout, keys[i].pbkdf2, keys[i].keylen) !=3D 0) {
 		krb5_warnx(context, "%d: pbkdf2", i);
 		val =3D 1;
 		continue;
 	    }
-	   =20
+
 	    if (verbose) {
 		printf("PBKDF2:\n");
 		hex_dump_data(keyout, keys[i].keylen);
@@ -248,31 +247,31 @@
=20
 	    ret =3D krb5_string_to_key_data_salt_opaque (context,
 						       keys[i].enctype,
-						       password,=20
-						       salt,=20
-						       opaque,=20
+						       password,
+						       salt,
+						       opaque,
 						       &key);
 	    if (ret) {
-		krb5_warn(context, ret, "%d: string_to_key_data_salt_opaque",=20
+		krb5_warn(context, ret, "%d: string_to_key_data_salt_opaque",
 			  i);
 		val =3D 1;
 		continue;
 	    }
-	   =20
+
 	    if (key.keyvalue.length !=3D keys[i].keylen) {
 		krb5_warnx(context, "%d: key wrong length (%lu/%lu)",
-			   i, (unsigned long)key.keyvalue.length,=20
+			   i, (unsigned long)key.keyvalue.length,
 			   (unsigned long)keys[i].keylen);
 		val =3D 1;
 		continue;
 	    }
-	   =20
+
 	    if (memcmp(key.keyvalue.data, keys[i].key, keys[i].keylen) !=3D 0) {
 		krb5_warnx(context, "%d: key wrong", i);
 		val =3D 1;
 		continue;
 	    }
-	   =20
+
 	    if (verbose) {
 		printf("key:\n");
 		hex_dump_data(key.keyvalue.data, key.keyvalue.length);
@@ -283,295 +282,11 @@
     return val;
 }
=20
-struct enc_test {
-    size_t len;
-    char *input;
-    char *output;
-    char *nextiv;
-};
-
-struct enc_test encs1[] =3D {
-    {
-	17,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20",
-	"\xc6\x35\x35\x68\xf2\xbf\x8c\xb4\xd8\xa5\x80\x36\x2d\xa7\xff\x7f"
-	"\x97",
-	"\xc6\x35\x35\x68\xf2\xbf\x8c\xb4\xd8\xa5\x80\x36\x2d\xa7\xff\x7f"
-    },
-    {
-	31,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20",
-	"\xfc\x00\x78\x3e\x0e\xfd\xb2\xc1\xd4\x45\xd4\xc8\xef\xf7\xed\x22"
-	"\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5",
-	"\xfc\x00\x78\x3e\x0e\xfd\xb2\xc1\xd4\x45\xd4\xc8\xef\xf7\xed\x22"
-    },
-    {
-	32,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43",
-	"\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5\xa8"
-	"\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84",
-	"\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5\xa8"
-    },
-    {
-	47,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c",
-	"\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84"
-	"\xb3\xff\xfd\x94\x0c\x16\xa1\x8c\x1b\x55\x49\xd2\xf8\x38\x02\x9e"
-	"\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5",
-	"\xb3\xff\xfd\x94\x0c\x16\xa1\x8c\x1b\x55\x49\xd2\xf8\x38\x02\x9e"
-    },
-    {
-	48,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20",
-	"\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84"
-	"\x9d\xad\x8b\xbb\x96\xc4\xcd\xc0\x3b\xc1\x03\xe1\xa1\x94\xbb\xd8"
-	"\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5\xa8",
-	"\x9d\xad\x8b\xbb\x96\xc4\xcd\xc0\x3b\xc1\x03\xe1\xa1\x94\xbb\xd8"
-    },
-    {
-	64,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20"
-	"\x61\x6e\x64\x20\x77\x6f\x6e\x74\x6f\x6e\x20\x73\x6f\x75\x70\x2e",
-	"\x97\x68\x72\x68\xd6\xec\xcc\xc0\xc0\x7b\x25\xe2\x5e\xcf\xe5\x84"
-	"\x39\x31\x25\x23\xa7\x86\x62\xd5\xbe\x7f\xcb\xcc\x98\xeb\xf5\xa8"
-	"\x48\x07\xef\xe8\x36\xee\x89\xa5\x26\x73\x0d\xbc\x2f\x7b\xc8\x40"
-	"\x9d\xad\x8b\xbb\x96\xc4\xcd\xc0\x3b\xc1\x03\xe1\xa1\x94\xbb\xd8",
-	"\x48\x07\xef\xe8\x36\xee\x89\xa5\x26\x73\x0d\xbc\x2f\x7b\xc8\x40"
-    }
-};
-=09
-
-struct enc_test encs2[] =3D {
-    {
-	17,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20",
-	"\x5c\x13\x26\x27\xc4\xcb\xca\x04\x14\x43\x8a\xb5\x97\x97\x7c\x10"
-	"\x16"
-    },
-    {
-	31,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20",
-	"\x16\xb3\xd8\xe5\xcd\x93\xe6\x2c\x28\x70\xa0\x36\x6e\x9a\xb9\x74"
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53"
-    },
-    {
-	32,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43",
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff\xc8"
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-    },
-    {
-	47,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c",
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-	"\xe5\x56\xb4\x88\x41\xb9\xde\x27\xf0\x07\xa1\x6e\x89\x94\x47\xf1"
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff"
-    },
-    {
-	48,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20",
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-	"\xfd\x68\xd1\x56\x32\x23\x7b\xfa\xb0\x09\x86\x3b\x17\x53\xfa\x30"
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff\xc8"
-    },
-    {
-	64,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20"
-	"\x61\x6e\x64\x20\x77\x6f\x6e\x74\x6f\x6e\x20\x73\x6f\x75\x70\x2e",
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff\xc8"
-	"\x70\x29\xf2\x6f\x7c\x79\xc1\x77\x91\xad\x94\xb0\x78\x62\x27\x67"
-	"\xfd\x68\xd1\x56\x32\x23\x7b\xfa\xb0\x09\x86\x3b\x17\x53\xfa\x30"
-    },
-    {
-	78,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20"
-	"\x61\x6e\x64\x20\x77\x6f\x6e\x74\x6f\x6e\x20\x73\x6f\x75\x70\x2e"
-	"\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41",
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff\xc8"
-	"\xfd\x68\xd1\x56\x32\x23\x7b\xfa\xb0\x09\x86\x3b\x17\x53\xfa\x30"
-	"\x73\xfb\x2c\x36\x76\xaf\xcf\x31\xff\xe3\x8a\x89\x0c\x7e\x99\x3f"
-	"\x70\x29\xf2\x6f\x7c\x79\xc1\x77\x91\xad\x94\xb0\x78\x62"
-    },
-    {
-	83,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20"
-	"\x61\x6e\x64\x20\x77\x6f\x6e\x74\x6f\x6e\x20\x73\x6f\x75\x70\x2e"
-	"\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41"
-	"\x41\x41\x41",
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff\xc8"
-	"\xfd\x68\xd1\x56\x32\x23\x7b\xfa\xb0\x09\x86\x3b\x17\x53\xfa\x30"
-	"\x70\x29\xf2\x6f\x7c\x79\xc1\x77\x91\xad\x94\xb0\x78\x62\x27\x67"
-	"\x65\x39\x3a\xdb\x92\x05\x4d\x4f\x08\xa1\xfa\x59\xda\x56\x58\x0e"
-	"\x3b\xac\x12"
-    },
-    {
-	92,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20"
-	"\x61\x6e\x64\x20\x77\x6f\x6e\x74\x6f\x6e\x20\x73\x6f\x75\x70\x2e"
-	"\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41"
-	"\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41",
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff\xc8"
-	"\xfd\x68\xd1\x56\x32\x23\x7b\xfa\xb0\x09\x86\x3b\x17\x53\xfa\x30"
-	"\x70\x29\xf2\x6f\x7c\x79\xc1\x77\x91\xad\x94\xb0\x78\x62\x27\x67"
-	"\x0c\xff\xd7\x63\x50\xf8\x4e\xf9\xec\x56\x1c\x79\xc5\xc8\xfe\x50"
-	"\x3b\xac\x12\x6e\xd3\x2d\x02\xc4\xe5\x06\x43\x5f"
-    },
-    {
-	96,
-	"\x49\x20\x77\x6f\x75\x6c\x64\x20\x6c\x69\x6b\x65\x20\x74\x68\x65"
-	"\x20\x47\x65\x6e\x65\x72\x61\x6c\x20\x47\x61\x75\x27\x73\x20\x43"
-	"\x68\x69\x63\x6b\x65\x6e\x2c\x20\x70\x6c\x65\x61\x73\x65\x2c\x20"
-	"\x61\x6e\x64\x20\x77\x6f\x6e\x74\x6f\x6e\x20\x73\x6f\x75\x70\x2e"
-	"\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41"
-	"\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41",
-	"\x16\xc1\xee\xdf\x39\xc8\x3f\xfb\xc5\xf6\x72\xe9\xc1\x6e\x53\x0c"
-	"\x69\xde\xce\x59\x83\x6a\x82\xe1\xcd\x21\x93\xd0\x9e\x2a\xff\xc8"
-	"\xfd\x68\xd1\x56\x32\x23\x7b\xfa\xb0\x09\x86\x3b\x17\x53\xfa\x30"
-	"\x70\x29\xf2\x6f\x7c\x79\xc1\x77\x91\xad\x94\xb0\x78\x62\x27\x67"
-	"\x08\x28\x49\xad\xfc\x2d\x8e\x86\xae\x69\xa5\xa8\xd9\x29\x9e\xe4"
-	"\x3b\xac\x12\x6e\xd3\x2d\x02\xc4\xe5\x06\x43\x5f\x4c\x41\xd1\xb8"
-    }
-};
-
-
-
-char *aes_key1 =3D=20
-	"\x63\x68\x69\x63\x6b\x65\x6e\x20\x74\x65\x72\x69\x79\x61\x6b\x69";
-
-char *aes_key2 =3D
-	"\x63\x68\x69\x63\x6b\x65\x6e\x20\x74\x65\x72\x69\x79\x61\x6b\x69"
-	"\x2c\x20\x79\x75\x6d\x6d\x79\x20\x79\x75\x6d\x6d\x79\x21\x21\x21";
-
-
-static int
-samep(int testn, char *type, const void *pp1, const void *pp2, size_t len)
-{
-    const unsigned char *p1 =3D pp1, *p2 =3D pp2;
-    size_t i;
-    int val =3D 1;
-
-    for (i =3D 0; i < len; i++) {
-	if (p1[i] !=3D p2[i]) {
-	    if (verbose)
-		printf("M");
-	    val =3D 0;
-	} else {
-	    if (verbose)
-		printf(".");
-	}
-    }
-    if (verbose)
-	printf("\n");
-    return val;
-}
-
-static int
-encryption_test(krb5_context context, const void *key, size_t keylen,
-		struct enc_test *enc, int numenc)
-{
-    unsigned char iv[AES_BLOCK_SIZE];
-    int i, val, failed =3D 0;
-    AES_KEY ekey, dkey;
-    unsigned char *p;
-
-    AES_set_encrypt_key(key, keylen, &ekey);
-    AES_set_decrypt_key(key, keylen, &dkey);
-
-    for (i =3D 0; i < numenc; i++) {
-	val =3D 0;
-
-	if (verbose)
-	    printf("test: %d\n", i);
-	memset(iv, 0, sizeof(iv));
-
-	p =3D malloc(enc[i].len + 1);
-	if (p =3D=3D NULL)
-	    krb5_errx(context, 1, "malloc");
-
-	p[enc[i].len] =3D '\0';
-
-	memcpy(p, enc[i].input, enc[i].len);
-
-	_krb5_aes_cts_encrypt(p, p, enc[i].len,
-			      &ekey, iv, AES_ENCRYPT);
-
-	if (p[enc[i].len] !=3D '\0') {
-	    krb5_warnx(context, "%d: encrypt modified off end", i);
-	    val =3D 1;
-	}
-
-	if (!samep(i, "cipher", p, enc[i].output, enc[i].len)) {
-	    krb5_warnx(context, "%d: cipher", i);
-	    val =3D 1;
-	}
-
-	if (enc[i].nextiv && !samep(i, "iv", iv, enc[i].nextiv, 16)){ /*XXX*/=20
-	    krb5_warnx(context, "%d: iv", i);
-	    val =3D 1;
-	}
-
-	memset(iv, 0, sizeof(iv));
-
-	_krb5_aes_cts_encrypt(p, p, enc[i].len,
-			      &dkey, iv, AES_DECRYPT);
-
-	if (p[enc[i].len] !=3D '\0') {
-	    krb5_warnx(context, "%d: decrypt modified off end", i);
-	    val =3D 1;
-	}
-
-	if (!samep(i, "clear", p, enc[i].input, enc[i].len))
-	    val =3D 1;
-
-	if (enc[i].nextiv && !samep(i, "iv", iv, enc[i].nextiv, 16)){ /*XXX*/=20
-	    krb5_warnx(context, "%d: iv", i);
-	    val =3D 1;
-	}
-
-	free(p);
-
-	if (val) {
-	    printf("test %d failed\n", i);
-	    failed =3D 1;
-	}
-	val =3D 0;
-    }
-    return failed;
-}
-
 static int
 krb_enc(krb5_context context,
-	krb5_crypto crypto,=20
+	krb5_crypto crypto,
 	unsigned usage,
-	krb5_data *cipher,=20
+	krb5_data *cipher,
 	krb5_data *clear)
 {
     krb5_data decrypt;
@@ -603,13 +318,213 @@
 }
=20
 static int
+krb_enc_iov2(krb5_context context,
+	     krb5_crypto crypto,
+	     unsigned usage,
+	     size_t cipher_len,
+	     krb5_data *clear)
+{
+    krb5_crypto_iov iov[4];
+    krb5_data decrypt;
+    int ret;
+    char *p, *q;
+    size_t len, i;
+
+    p =3D clear->data;
+    len =3D clear->length;
+
+    iov[0].flags =3D KRB5_CRYPTO_TYPE_HEADER;
+    krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length);
+    iov[0].data.data =3D emalloc(iov[0].data.length);
+
+    iov[1].flags =3D KRB5_CRYPTO_TYPE_DATA;
+    iov[1].data.length =3D len;
+    iov[1].data.data =3D emalloc(iov[1].data.length);
+    memcpy(iov[1].data.data, p, iov[1].data.length);
+
+    /* padding buffer */
+    iov[2].flags =3D KRB5_CRYPTO_TYPE_PADDING;
+    krb5_crypto_length(context, crypto, KRB5_CRYPTO_TYPE_PADDING, &iov[2].=
data.length);
+    iov[2].data.data =3D emalloc(iov[2].data.length);
+
+    iov[3].flags =3D KRB5_CRYPTO_TYPE_TRAILER;
+    krb5_crypto_length(context, crypto, iov[3].flags, &iov[3].data.length);
+    iov[3].data.data =3D emalloc(iov[3].data.length);
+
+    ret =3D krb5_encrypt_iov_ivec(context, crypto, usage,
+				iov, sizeof(iov)/sizeof(iov[0]), NULL);
+    if (ret)
+	errx(1, "encrypt iov failed: %d", ret);
+
+    /* check len */
+    for (i =3D 0, len =3D 0; i < sizeof(iov)/sizeof(iov[0]); i++)
+	len +=3D iov[i].data.length;
+    if (len !=3D cipher_len)
+	errx(1, "cipher len wrong");
+
+    /*
+     * Plain decrypt
+     */
+
+    p =3D q =3D emalloc(len);
+    for (i =3D 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+	memcpy(q, iov[i].data.data, iov[i].data.length);
+	q +=3D iov[i].data.length;
+    }
+
+    ret =3D krb5_decrypt(context, crypto, usage, p, len, &decrypt);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_decrypt");
+    else
+	krb5_data_free(&decrypt);
+
+    free(p);
+
+    /*
+     * Now decrypt use iov
+     */
+
+    /* padding turn into data */
+    p =3D q =3D emalloc(iov[1].data.length + iov[2].data.length);
+
+    memcpy(q, iov[1].data.data, iov[1].data.length);
+    q +=3D iov[1].data.length;
+    memcpy(q, iov[2].data.data, iov[2].data.length);
+
+    free(iov[1].data.data);
+    free(iov[2].data.data);
+
+    iov[1].data.data =3D p;
+    iov[1].data.length +=3D iov[2].data.length;
+
+    iov[2].flags =3D KRB5_CRYPTO_TYPE_EMPTY;
+    iov[2].data.length =3D 0;
+
+    ret =3D krb5_decrypt_iov_ivec(context, crypto, usage,
+				iov, sizeof(iov)/sizeof(iov[0]), NULL);
+    free(iov[0].data.data);
+    free(iov[3].data.data);
+
+    if (ret)
+	krb5_err(context, 1, ret, "decrypt iov failed: %d", ret);
+
+    if (clear->length !=3D iov[1].data.length)
+	errx(1, "length incorrect");
+
+    p =3D clear->data;
+    if (memcmp(iov[1].data.data, p, iov[1].data.length) !=3D 0)
+	errx(1, "iov[1] incorrect");
+
+    free(iov[1].data.data);
+
+    return 0;
+}
+
+
+static int
+krb_enc_iov(krb5_context context,
+	    krb5_crypto crypto,
+	    unsigned usage,
+	    krb5_data *cipher,
+	    krb5_data *clear)
+{
+    krb5_crypto_iov iov[3];
+    int ret;
+    char *p;
+    size_t len;
+
+    p =3D cipher->data;
+    len =3D cipher->length;
+
+    iov[0].flags =3D KRB5_CRYPTO_TYPE_HEADER;
+    krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length);
+    iov[0].data.data =3D emalloc(iov[0].data.length);
+    memcpy(iov[0].data.data, p, iov[0].data.length);
+    p +=3D iov[0].data.length;
+    len -=3D iov[0].data.length;
+
+    iov[1].flags =3D KRB5_CRYPTO_TYPE_TRAILER;
+    krb5_crypto_length(context, crypto, iov[1].flags, &iov[1].data.length);
+    iov[1].data.data =3D emalloc(iov[1].data.length);
+    memcpy(iov[1].data.data, p + len - iov[1].data.length, iov[1].data.len=
gth);
+    len -=3D iov[1].data.length;
+
+    iov[2].flags =3D KRB5_CRYPTO_TYPE_DATA;
+    iov[2].data.length =3D len;
+    iov[2].data.data =3D emalloc(len);
+    memcpy(iov[2].data.data, p, len);
+
+    ret =3D krb5_decrypt_iov_ivec(context, crypto, usage,
+				iov, sizeof(iov)/sizeof(iov[0]), NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb_enc_iov decrypt iov failed: %d", ret);
+
+    if (clear->length !=3D iov[2].data.length)
+	errx(1, "length incorrect");
+
+    p =3D clear->data;
+    if (memcmp(iov[2].data.data, p, iov[2].data.length) !=3D 0)
+	errx(1, "iov[2] incorrect");
+
+    free(iov[0].data.data);
+    free(iov[1].data.data);
+    free(iov[2].data.data);
+
+
+    return 0;
+}
+
+static int
+krb_checksum_iov(krb5_context context,
+		 krb5_crypto crypto,
+		 unsigned usage,
+		 krb5_data *plain)
+{
+    krb5_crypto_iov iov[4];
+    int ret;
+    char *p;
+    size_t len;
+
+    p =3D plain->data;
+    len =3D plain->length;
+
+    iov[0].flags =3D KRB5_CRYPTO_TYPE_CHECKSUM;
+    krb5_crypto_length(context, crypto, iov[0].flags, &iov[0].data.length);
+    iov[0].data.data =3D emalloc(iov[0].data.length);
+
+    iov[1].flags =3D KRB5_CRYPTO_TYPE_DATA;
+    iov[1].data.length =3D len;
+    iov[1].data.data =3D p;
+
+    iov[2].flags =3D KRB5_CRYPTO_TYPE_TRAILER;
+    krb5_crypto_length(context, crypto, iov[0].flags, &iov[2].data.length);
+    iov[2].data.data =3D malloc(iov[2].data.length);
+
+    ret =3D krb5_create_checksum_iov(context, crypto, usage,
+				   iov, sizeof(iov)/sizeof(iov[0]), NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_create_checksum_iov failed");
+
+    ret =3D krb5_verify_checksum_iov(context, crypto, usage, iov, sizeof(i=
ov)/sizeof(iov[0]), NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_verify_checksum_iov");
+
+    free(iov[0].data.data);
+    free(iov[2].data.data);
+
+    return 0;
+}
+
+
+static int
 krb_enc_mit(krb5_context context,
 	    krb5_enctype enctype,
 	    krb5_keyblock *key,
 	    unsigned usage,
-	    krb5_data *cipher,=20
+	    krb5_data *cipher,
 	    krb5_data *clear)
 {
+#ifndef HEIMDAL_SMALLER
     krb5_error_code ret;
     krb5_enc_data e;
     krb5_data decrypt;
@@ -640,7 +555,7 @@
 		   (unsigned long)len, (unsigned long)cipher->length);
 	return EINVAL;
     }
-
+#endif /* HEIMDAL_SMALLER */
     return 0;
 }
=20
@@ -655,10 +570,10 @@
     size_t plen;
     void *pdata;
 } krbencs[] =3D  {
-    {=20
+    {
 	ETYPE_AES256_CTS_HMAC_SHA1_96,
 	7,
-	32,  =20
+	32,
 	"\x47\x75\x69\x64\x65\x6c\x69\x6e\x65\x73\x20\x74\x6f\x20\x41\x75"
 	"\x74\x68\x6f\x72\x73\x20\x6f\x66\x20\x49\x6e\x74\x65\x72\x6e\x65",
 	44,
@@ -678,7 +593,7 @@
     krb5_crypto crypto;
     krb5_keyblock kb;
     krb5_data cipher, plain;
-    int i, failed =3D 0;
+    int i;
=20
     for (i =3D 0; i < sizeof(krbencs)/sizeof(krbencs[0]); i++) {
=20
@@ -692,27 +607,216 @@
 	cipher.data =3D krbencs[i].edata;
 	plain.length =3D krbencs[i].plen;
 	plain.data =3D krbencs[i].pdata;
-=09
+
 	ret =3D krb_enc(context, crypto, krbencs[i].usage, &cipher, &plain);
-		      =20
-	if (ret) {
-	    failed =3D 1;
-	    printf("krb_enc failed with %d\n", ret);
-	}
+
+	if (ret)
+	    errx(1, "krb_enc failed with %d for test %d", ret, i);
+
+	ret =3D krb_enc_iov(context, crypto, krbencs[i].usage, &cipher, &plain);
+	if (ret)
+	    errx(1, "krb_enc_iov failed with %d for test %d", ret, i);
+
+	ret =3D krb_enc_iov2(context, crypto, krbencs[i].usage,
+			   cipher.length, &plain);
+	if (ret)
+	    errx(1, "krb_enc_iov2 failed with %d for test %d", ret, i);
+
+	ret =3D krb_checksum_iov(context, crypto, krbencs[i].usage, &plain);
+	if (ret)
+	    errx(1, "krb_checksum_iov failed with %d for test %d", ret, i);
+
 	krb5_crypto_destroy(context, crypto);
=20
-	ret =3D krb_enc_mit(context, krbencs[i].enctype, &kb,=20
+	ret =3D krb_enc_mit(context, krbencs[i].enctype, &kb,
 			  krbencs[i].usage, &cipher, &plain);
-	if (ret) {
-	    failed =3D 1;
-	    printf("krb_enc_mit failed with %d\n", ret);
-	}
-
+	if (ret)
+	    errx(1, "krb_enc_mit failed with %d for test %d", ret, i);
     }
=20
-    return failed;
+    return 0;
 }
=20
+static int
+iov_test(krb5_context context)
+{
+    krb5_enctype enctype =3D ENCTYPE_AES256_CTS_HMAC_SHA1_96;
+    krb5_error_code ret;
+    krb5_crypto crypto;
+    krb5_keyblock key;
+    krb5_data signonly, in, in2;
+    krb5_crypto_iov iov[6];
+    size_t len, i;
+    unsigned char *base, *p;
+
+    ret =3D krb5_generate_random_keyblock(context, enctype, &key);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_generate_random_keyblock");
+
+    ret =3D krb5_crypto_init(context, &key, 0, &crypto);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_crypto_init");
+
+
+    ret =3D krb5_crypto_length(context, crypto, KRB5_CRYPTO_TYPE_HEADER, &=
len);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_crypto_length");
+
+    signonly.data =3D "This should be signed";
+    signonly.length =3D strlen(signonly.data);
+    in.data =3D "inputdata";
+    in.length =3D strlen(in.data);
+
+    in2.data =3D "INPUTDATA";
+    in2.length =3D strlen(in2.data);
+
+
+    memset(iov, 0, sizeof(iov));
+
+    iov[0].flags =3D KRB5_CRYPTO_TYPE_HEADER;
+    iov[1].flags =3D KRB5_CRYPTO_TYPE_DATA;
+    iov[1].data =3D in;
+    iov[2].flags =3D KRB5_CRYPTO_TYPE_SIGN_ONLY;
+    iov[2].data =3D signonly;
+    iov[3].flags =3D KRB5_CRYPTO_TYPE_EMPTY;
+    iov[4].flags =3D KRB5_CRYPTO_TYPE_PADDING;
+    iov[5].flags =3D KRB5_CRYPTO_TYPE_TRAILER;
+
+    ret =3D krb5_crypto_length_iov(context, crypto, iov,
+				 sizeof(iov)/sizeof(iov[0]));
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_crypto_length_iov");
+
+    for (len =3D 0, i =3D 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+	if (iov[i].flags =3D=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	len +=3D iov[i].data.length;
+    }
+
+    base =3D emalloc(len);
+
+    /*
+     * Allocate data for the fields
+     */
+
+    for (p =3D base, i =3D 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+	if (iov[i].flags =3D=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;;
+	iov[i].data.data =3D p;
+	p +=3D iov[i].data.length;
+    }
+    assert(iov[1].data.length =3D=3D in.length);
+    memcpy(iov[1].data.data, in.data, iov[1].data.length);
+
+    /*
+     * Encrypt
+     */
+
+    ret =3D krb5_encrypt_iov_ivec(context, crypto, 7, iov,
+				sizeof(iov)/sizeof(iov[0]), NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_encrypt_iov_ivec");
+
+    /*
+     * Decrypt
+     */
+
+    ret =3D krb5_decrypt_iov_ivec(context, crypto, 7,
+				iov, sizeof(iov)/sizeof(iov[0]), NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_decrypt_iov_ivec");
+
+    /*
+     * Verify data
+     */
+
+    if (krb5_data_cmp(&iov[1].data, &in) !=3D 0)
+	krb5_errx(context, 1, "decrypted data not same");
+
+    /*
+     * Free memory
+     */
+
+    free(base);
+
+    /* Set up for second try */
+
+    iov[3].flags =3D KRB5_CRYPTO_TYPE_DATA;
+    iov[3].data =3D in;
+
+    ret =3D krb5_crypto_length_iov(context, crypto,
+				 iov, sizeof(iov)/sizeof(iov[0]));
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_crypto_length_iov");
+
+    for (len =3D 0, i =3D 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+	if (iov[i].flags =3D=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	len +=3D iov[i].data.length;
+    }
+
+    base =3D emalloc(len);
+
+    /*
+     * Allocate data for the fields
+     */
+
+    for (p =3D base, i =3D 0; i < sizeof(iov)/sizeof(iov[0]); i++) {
+	if (iov[i].flags =3D=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;;
+	iov[i].data.data =3D p;
+	p +=3D iov[i].data.length;
+    }
+    assert(iov[1].data.length =3D=3D in.length);
+    memcpy(iov[1].data.data, in.data, iov[1].data.length);
+
+    assert(iov[3].data.length =3D=3D in2.length);
+    memcpy(iov[3].data.data, in2.data, iov[3].data.length);
+
+
+
+    /*
+     * Encrypt
+     */
+
+    ret =3D krb5_encrypt_iov_ivec(context, crypto, 7,
+				iov, sizeof(iov)/sizeof(iov[0]), NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_encrypt_iov_ivec");
+
+    /*
+     * Decrypt
+     */
+
+    ret =3D krb5_decrypt_iov_ivec(context, crypto, 7,
+				iov, sizeof(iov)/sizeof(iov[0]), NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_decrypt_iov_ivec");
+
+    /*
+     * Verify data
+     */
+
+    if (krb5_data_cmp(&iov[1].data, &in) !=3D 0)
+	krb5_errx(context, 1, "decrypted data 2.1 not same");
+
+    if (krb5_data_cmp(&iov[3].data, &in2) !=3D 0)
+	krb5_errx(context, 1, "decrypted data 2.2 not same");
+
+    /*
+     * Free memory
+     */
+
+    free(base);
+
+    krb5_crypto_destroy(context, crypto);
+
+    krb5_free_keyblock_contents(context, &key);
+
+    return 0;
+}
+
+
=20
 static int
 random_to_key(krb5_context context)
@@ -746,26 +850,22 @@
     return 0;
 }
=20
-
 int
 main(int argc, char **argv)
 {
     krb5_error_code ret;
     krb5_context context;
     int val =3D 0;
-   =20
+
     ret =3D krb5_init_context (&context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
=20
     val |=3D string_to_key_test(context);
=20
-    val |=3D encryption_test(context, aes_key1, 128,
-			   encs1, sizeof(encs1)/sizeof(encs1[0]));
-    val |=3D encryption_test(context, aes_key2, 256,=20
-			   encs2, sizeof(encs2)/sizeof(encs2[0]));
     val |=3D krb_enc_test(context);
     val |=3D random_to_key(context);
+    val |=3D iov_test(context);
=20
     if (verbose && val =3D=3D 0)
 	printf("all ok\n");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/aname_to_=
localname.c
--- a/head/crypto/heimdal/lib/krb5/aname_to_localname.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/aname_to_localname.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 1999, 2002 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999, 2002 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: aname_to_localname.c 13863 2004-05-25 21:46:46Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_aname_to_localname (krb5_context context,
 			 krb5_const_principal aname,
 			 size_t lnsize,
@@ -74,7 +72,7 @@
 	ret =3D krb5_copy_principal(context, aname, &rootprinc);
 	if (ret)
 	    return ret;
-=09
+
 	userok =3D krb5_kuserok(context, rootprinc, res);
 	krb5_free_principal(context, rootprinc);
 	if (!userok)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/appdefaul=
t.c
--- a/head/crypto/heimdal/lib/krb5/appdefault.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/appdefault.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,118 +1,116 @@
 /*
- * Copyright (c) 2000 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: appdefault.c 14465 2005-01-05 05:40:59Z lukeh $");
-
-void KRB5_LIB_FUNCTION
-krb5_appdefault_boolean(krb5_context context, const char *appname,=20
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_appdefault_boolean(krb5_context context, const char *appname,
 			krb5_const_realm realm, const char *option,
 			krb5_boolean def_val, krb5_boolean *ret_val)
 {
-   =20
+
     if(appname =3D=3D NULL)
 	appname =3D getprogname();
=20
-    def_val =3D krb5_config_get_bool_default(context, NULL, def_val,=20
+    def_val =3D krb5_config_get_bool_default(context, NULL, def_val,
 					   "libdefaults", option, NULL);
     if(realm !=3D NULL)
-	def_val =3D krb5_config_get_bool_default(context, NULL, def_val,=20
+	def_val =3D krb5_config_get_bool_default(context, NULL, def_val,
 					       "realms", realm, option, NULL);
-=09
-    def_val =3D krb5_config_get_bool_default(context, NULL, def_val,=20
-					   "appdefaults",=20
-					   option,=20
+
+    def_val =3D krb5_config_get_bool_default(context, NULL, def_val,
+					   "appdefaults",
+					   option,
 					   NULL);
     if(realm !=3D NULL)
 	def_val =3D krb5_config_get_bool_default(context, NULL, def_val,
-					       "appdefaults",=20
-					       realm,=20
-					       option,=20
+					       "appdefaults",
+					       realm,
+					       option,
 					       NULL);
     if(appname !=3D NULL) {
-	def_val =3D krb5_config_get_bool_default(context, NULL, def_val,=20
-					       "appdefaults",=20
-					       appname,=20
-					       option,=20
+	def_val =3D krb5_config_get_bool_default(context, NULL, def_val,
+					       "appdefaults",
+					       appname,
+					       option,
 					       NULL);
 	if(realm !=3D NULL)
 	    def_val =3D krb5_config_get_bool_default(context, NULL, def_val,
-						   "appdefaults",=20
-						   appname,=20
-						   realm,=20
-						   option,=20
+						   "appdefaults",
+						   appname,
+						   realm,
+						   option,
 						   NULL);
     }
     *ret_val =3D def_val;
 }
=20
-void KRB5_LIB_FUNCTION
-krb5_appdefault_string(krb5_context context, const char *appname,=20
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_appdefault_string(krb5_context context, const char *appname,
 		       krb5_const_realm realm, const char *option,
 		       const char *def_val, char **ret_val)
 {
     if(appname =3D=3D NULL)
 	appname =3D getprogname();
=20
-    def_val =3D krb5_config_get_string_default(context, NULL, def_val,=20
+    def_val =3D krb5_config_get_string_default(context, NULL, def_val,
 					     "libdefaults", option, NULL);
     if(realm !=3D NULL)
-	def_val =3D krb5_config_get_string_default(context, NULL, def_val,=20
+	def_val =3D krb5_config_get_string_default(context, NULL, def_val,
 						 "realms", realm, option, NULL);
=20
-    def_val =3D krb5_config_get_string_default(context, NULL, def_val,=20
-					     "appdefaults",=20
-					     option,=20
+    def_val =3D krb5_config_get_string_default(context, NULL, def_val,
+					     "appdefaults",
+					     option,
 					     NULL);
     if(realm !=3D NULL)
 	def_val =3D krb5_config_get_string_default(context, NULL, def_val,
-						 "appdefaults",=20
-						 realm,=20
-						 option,=20
+						 "appdefaults",
+						 realm,
+						 option,
 						 NULL);
     if(appname !=3D NULL) {
-	def_val =3D krb5_config_get_string_default(context, NULL, def_val,=20
-						 "appdefaults",=20
-						 appname,=20
-						 option,=20
+	def_val =3D krb5_config_get_string_default(context, NULL, def_val,
+						 "appdefaults",
+						 appname,
+						 option,
 						 NULL);
 	if(realm !=3D NULL)
 	    def_val =3D krb5_config_get_string_default(context, NULL, def_val,
-						     "appdefaults",=20
-						     appname,=20
-						     realm,=20
-						     option,=20
+						     "appdefaults",
+						     appname,
+						     realm,
+						     option,
 						     NULL);
     }
     if(def_val !=3D NULL)
@@ -121,7 +119,7 @@
 	*ret_val =3D NULL;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_appdefault_time(krb5_context context, const char *appname,
 		     krb5_const_realm realm, const char *option,
 		     time_t def_val, time_t *ret_val)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/asn1_glue=
.c
--- a/head/crypto/heimdal/lib/krb5/asn1_glue.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/asn1_glue.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 /*
@@ -37,28 +37,36 @@
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: asn1_glue.c 21745 2007-07-31 16:11:25Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_principal2principalname (PrincipalName *p,
 			       const krb5_principal from)
 {
     return copy_PrincipalName(&from->name, p);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_principalname2krb5_principal (krb5_context context,
 				    krb5_principal *principal,
 				    const PrincipalName from,
 				    const Realm realm)
 {
-    krb5_principal p =3D malloc(sizeof(*p));
+    krb5_error_code ret;
+    krb5_principal p;
+
+    p =3D malloc(sizeof(*p));
     if (p =3D=3D NULL)
 	return ENOMEM;
-    copy_PrincipalName(&from, &p->name);
+    ret =3D copy_PrincipalName(&from, &p->name);
+    if (ret) {
+	free(p);
+	return ret;
+    }
     p->realm =3D strdup(realm);
-    if (p->realm =3D=3D NULL)
+    if (p->realm =3D=3D NULL) {
+	free_PrincipalName(&p->name);
+        free(p);
 	return ENOMEM;
+    }
     *principal =3D p;
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/auth_cont=
ext.c
--- a/head/crypto/heimdal/lib/krb5/auth_context.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/auth_context.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: auth_context.c 21745 2007-07-31 16:11:25Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_init(krb5_context context,
 		   krb5_auth_context *auth_context)
 {
@@ -43,13 +41,13 @@
=20
     ALLOC(p, 1);
     if(!p) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memset(p, 0, sizeof(*p));
     ALLOC(p->authenticator, 1);
     if (!p->authenticator) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(p);
 	return ENOMEM;
     }
@@ -60,13 +58,13 @@
     p->remote_address =3D NULL;
     p->local_port     =3D 0;
     p->remote_port    =3D 0;
-    p->keytype        =3D KEYTYPE_NULL;
+    p->keytype        =3D ENCTYPE_NULL;
     p->cksumtype      =3D CKSUMTYPE_NONE;
     *auth_context     =3D p;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_free(krb5_context context,
 		   krb5_auth_context auth_context)
 {
@@ -88,7 +86,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setflags(krb5_context context,
 		       krb5_auth_context auth_context,
 		       int32_t flags)
@@ -98,7 +96,7 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getflags(krb5_context context,
 		       krb5_auth_context auth_context,
 		       int32_t *flags)
@@ -107,7 +105,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_addflags(krb5_context context,
 		       krb5_auth_context auth_context,
 		       int32_t addflags,
@@ -119,7 +117,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_removeflags(krb5_context context,
 			  krb5_auth_context auth_context,
 			  int32_t removeflags,
@@ -131,7 +129,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setaddrs(krb5_context context,
 		       krb5_auth_context auth_context,
 		       krb5_address *local_addr,
@@ -156,10 +154,10 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_auth_con_genaddrs(krb5_context context,=20
-		       krb5_auth_context auth_context,=20
-		       int fd, int flags)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_genaddrs(krb5_context context,
+		       krb5_auth_context auth_context,
+		       krb5_socket_t fd, int flags)
 {
     krb5_error_code ret;
     krb5_address local_k_address, remote_k_address;
@@ -172,10 +170,11 @@
     if(flags & KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR) {
 	if (auth_context->local_address =3D=3D NULL) {
 	    len =3D sizeof(ss_local);
-	    if(getsockname(fd, local, &len) < 0) {
-		ret =3D errno;
-		krb5_set_error_string (context, "getsockname: %s",
-				       strerror(ret));
+	    if(rk_IS_SOCKET_ERROR(getsockname(fd, local, &len))) {
+		char buf[128];
+		ret =3D rk_SOCK_ERRNO;
+		rk_strerror_r(ret, buf, sizeof(buf));
+		krb5_set_error_message(context, ret, "getsockname: %s", buf);
 		goto out;
 	    }
 	    ret =3D krb5_sockaddr2address (context, local, &local_k_address);
@@ -189,9 +188,11 @@
     }
     if(flags & KRB5_AUTH_CONTEXT_GENERATE_REMOTE_ADDR) {
 	len =3D sizeof(ss_remote);
-	if(getpeername(fd, remote, &len) < 0) {
-	    ret =3D errno;
-	    krb5_set_error_string (context, "getpeername: %s", strerror(ret));
+	if(rk_IS_SOCKET_ERROR(getpeername(fd, remote, &len))) {
+	    char buf[128];
+	    ret =3D rk_SOCK_ERRNO;
+	    rk_strerror_r(ret, buf, sizeof(buf));
+	    krb5_set_error_message(context, ret, "getpeername: %s", buf);
 	    goto out;
 	}
 	ret =3D krb5_sockaddr2address (context, remote, &remote_k_address);
@@ -215,12 +216,12 @@
=20
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setaddrs_from_fd (krb5_context context,
 				krb5_auth_context auth_context,
 				void *p_fd)
 {
-    int fd =3D *(int*)p_fd;
+    krb5_socket_t fd =3D *(krb5_socket_t *)p_fd;
     int flags =3D 0;
     if(auth_context->local_address =3D=3D NULL)
 	flags |=3D KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR;
@@ -229,7 +230,7 @@
     return krb5_auth_con_genaddrs(context, auth_context, fd, flags);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getaddrs(krb5_context context,
 		       krb5_auth_context auth_context,
 		       krb5_address **local_addr,
@@ -239,7 +240,7 @@
 	krb5_free_address (context, *local_addr);
     *local_addr =3D malloc (sizeof(**local_addr));
     if (*local_addr =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     krb5_copy_address(context,
@@ -250,7 +251,7 @@
 	krb5_free_address (context, *remote_addr);
     *remote_addr =3D malloc (sizeof(**remote_addr));
     if (*remote_addr =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	krb5_free_address (context, *local_addr);
 	*local_addr =3D NULL;
 	return ENOMEM;
@@ -261,6 +262,7 @@
     return 0;
 }
=20
+/* coverity[+alloc : arg-*2] */
 static krb5_error_code
 copy_key(krb5_context context,
 	 krb5_keyblock *in,
@@ -272,7 +274,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getkey(krb5_context context,
 		     krb5_auth_context auth_context,
 		     krb5_keyblock **keyblock)
@@ -280,7 +282,7 @@
     return copy_key(context, auth_context->keyblock, keyblock);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getlocalsubkey(krb5_context context,
 			     krb5_auth_context auth_context,
 			     krb5_keyblock **keyblock)
@@ -288,7 +290,8 @@
     return copy_key(context, auth_context->local_subkey, keyblock);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/* coverity[+alloc : arg-*2] */
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getremotesubkey(krb5_context context,
 			      krb5_auth_context auth_context,
 			      krb5_keyblock **keyblock)
@@ -296,7 +299,7 @@
     return copy_key(context, auth_context->remote_subkey, keyblock);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setkey(krb5_context context,
 		     krb5_auth_context auth_context,
 		     krb5_keyblock *keyblock)
@@ -306,7 +309,7 @@
     return copy_key(context, keyblock, &auth_context->keyblock);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setlocalsubkey(krb5_context context,
 			     krb5_auth_context auth_context,
 			     krb5_keyblock *keyblock)
@@ -316,7 +319,7 @@
     return copy_key(context, keyblock, &auth_context->local_subkey);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_generatelocalsubkey(krb5_context context,
 				  krb5_auth_context auth_context,
 				  krb5_keyblock *key)
@@ -336,7 +339,7 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setremotesubkey(krb5_context context,
 			      krb5_auth_context auth_context,
 			      krb5_keyblock *keyblock)
@@ -346,7 +349,7 @@
     return copy_key(context, keyblock, &auth_context->remote_subkey);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setcksumtype(krb5_context context,
 			   krb5_auth_context auth_context,
 			   krb5_cksumtype cksumtype)
@@ -355,7 +358,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getcksumtype(krb5_context context,
 			   krb5_auth_context auth_context,
 			   krb5_cksumtype *cksumtype)
@@ -364,7 +367,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setkeytype (krb5_context context,
 			  krb5_auth_context auth_context,
 			  krb5_keytype keytype)
@@ -373,7 +376,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getkeytype (krb5_context context,
 			  krb5_auth_context auth_context,
 			  krb5_keytype *keytype)
@@ -383,7 +386,7 @@
 }
=20
 #if 0
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setenctype(krb5_context context,
 			 krb5_auth_context auth_context,
 			 krb5_enctype etype)
@@ -397,7 +400,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getenctype(krb5_context context,
 			 krb5_auth_context auth_context,
 			 krb5_enctype *etype)
@@ -406,7 +409,7 @@
 }
 #endif
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getlocalseqnumber(krb5_context context,
 			    krb5_auth_context auth_context,
 			    int32_t *seqnumber)
@@ -415,7 +418,7 @@
   return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setlocalseqnumber (krb5_context context,
 			     krb5_auth_context auth_context,
 			     int32_t seqnumber)
@@ -424,16 +427,16 @@
   return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_auth_getremoteseqnumber(krb5_context context,
-			     krb5_auth_context auth_context,
-			     int32_t *seqnumber)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getremoteseqnumber(krb5_context context,
+				 krb5_auth_context auth_context,
+				 int32_t *seqnumber)
 {
   *seqnumber =3D auth_context->remote_seqnumber;
   return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setremoteseqnumber (krb5_context context,
 			      krb5_auth_context auth_context,
 			      int32_t seqnumber)
@@ -443,14 +446,14 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getauthenticator(krb5_context context,
 			   krb5_auth_context auth_context,
 			   krb5_authenticator *authenticator)
 {
     *authenticator =3D malloc(sizeof(**authenticator));
     if (*authenticator =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -460,7 +463,7 @@
 }
=20
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_authenticator(krb5_context context,
 			krb5_authenticator *authenticator)
 {
@@ -470,7 +473,7 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setuserkey(krb5_context context,
 			 krb5_auth_context auth_context,
 			 krb5_keyblock *keyblock)
@@ -480,7 +483,7 @@
     return krb5_copy_keyblock(context, keyblock, &auth_context->keyblock);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getrcache(krb5_context context,
 			krb5_auth_context auth_context,
 			krb5_rcache *rcache)
@@ -489,7 +492,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setrcache(krb5_context context,
 			krb5_auth_context auth_context,
 			krb5_rcache rcache)
@@ -500,7 +503,7 @@
=20
 #if 0 /* not implemented */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_initivector(krb5_context context,
 			  krb5_auth_context auth_context)
 {
@@ -508,7 +511,7 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setivector(krb5_context context,
 			 krb5_auth_context auth_context,
 			 krb5_pointer ivector)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/build_ap_=
req.c
--- a/head/crypto/heimdal/lib/krb5/build_ap_req.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/build_ap_req.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: build_ap_req.c 13863 2004-05-25 21:46:46Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_ap_req (krb5_context context,
 		   krb5_enctype enctype,
 		   krb5_creds *cred,
@@ -47,13 +45,13 @@
   AP_REQ ap;
   Ticket t;
   size_t len;
- =20
+
   ap.pvno =3D 5;
   ap.msg_type =3D krb_ap_req;
   memset(&ap.ap_options, 0, sizeof(ap.ap_options));
   ap.ap_options.use_session_key =3D (ap_options & AP_OPTS_USE_SESSION_KEY)=
 > 0;
   ap.ap_options.mutual_required =3D (ap_options & AP_OPTS_MUTUAL_REQUIRED)=
 > 0;
- =20
+
   ap.ticket.tkt_vno =3D 5;
   copy_Realm(&cred->server->realm, &ap.ticket.realm);
   copy_PrincipalName(&cred->server->name, &ap.ticket.sname);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/build_aut=
h.c
--- a/head/crypto/heimdal/lib/krb5/build_auth.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/build_auth.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
-
-RCSID("$Id: build_auth.c 17033 2006-04-10 08:53:21Z lha $");
+#include "krb5_locl.h"
=20
 static krb5_error_code
 make_etypelist(krb5_context context,
@@ -43,10 +41,12 @@
     krb5_error_code ret;
     krb5_authdata ad;
     u_char *buf;
-    size_t len;
+    size_t len =3D 0;
     size_t buf_size;
-    =20
-    ret =3D krb5_init_etype(context, &etypes.len, &etypes.val, NULL);
+
+    ret =3D _krb5_init_etype(context, KRB5_PDU_NONE,
+			   &etypes.len, &etypes.val,
+			   NULL);
     if (ret)
 	return ret;
=20
@@ -62,7 +62,7 @@
     ALLOC_SEQ(&ad, 1);
     if (ad.val =3D=3D NULL) {
 	free(buf);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -74,21 +74,23 @@
     if (ret) {
 	free_AuthorizationData(&ad);
 	return ret;
-    }=20
+    }
     if(buf_size !=3D len)
 	krb5_abortx(context, "internal error in ASN.1 encoder");
     free_AuthorizationData(&ad);
=20
     ALLOC(*auth_data, 1);
     if (*auth_data =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+        free(buf);
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
     ALLOC_SEQ(*auth_data, 1);
     if ((*auth_data)->val =3D=3D NULL) {
+        free(*auth_data);
 	free(buf);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -99,71 +101,76 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_build_authenticator (krb5_context context,
-			  krb5_auth_context auth_context,
-			  krb5_enctype enctype,
-			  krb5_creds *cred,
-			  Checksum *cksum,
-			  Authenticator **auth_result,
-			  krb5_data *result,
-			  krb5_key_usage usage)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_build_authenticator (krb5_context context,
+			   krb5_auth_context auth_context,
+			   krb5_enctype enctype,
+			   krb5_creds *cred,
+			   Checksum *cksum,
+			   krb5_data *result,
+			   krb5_key_usage usage)
 {
-    Authenticator *auth;
+    Authenticator auth;
     u_char *buf =3D NULL;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     krb5_error_code ret;
     krb5_crypto crypto;
=20
-    auth =3D calloc(1, sizeof(*auth));
-    if (auth =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
+    memset(&auth, 0, sizeof(auth));
=20
-    auth->authenticator_vno =3D 5;
-    copy_Realm(&cred->client->realm, &auth->crealm);
-    copy_PrincipalName(&cred->client->name, &auth->cname);
+    auth.authenticator_vno =3D 5;
+    copy_Realm(&cred->client->realm, &auth.crealm);
+    copy_PrincipalName(&cred->client->name, &auth.cname);
=20
-    krb5_us_timeofday (context, &auth->ctime, &auth->cusec);
-   =20
-    ret =3D krb5_auth_con_getlocalsubkey(context, auth_context, &auth->sub=
key);
+    krb5_us_timeofday (context, &auth.ctime, &auth.cusec);
+
+    ret =3D krb5_auth_con_getlocalsubkey(context, auth_context, &auth.subk=
ey);
     if(ret)
 	goto fail;
=20
     if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
 	if(auth_context->local_seqnumber =3D=3D 0)
 	    krb5_generate_seq_number (context,
-				      &cred->session,=20
+				      &cred->session,
 				      &auth_context->local_seqnumber);
-	ALLOC(auth->seq_number, 1);
-	if(auth->seq_number =3D=3D NULL) {
+	ALLOC(auth.seq_number, 1);
+	if(auth.seq_number =3D=3D NULL) {
 	    ret =3D ENOMEM;
 	    goto fail;
 	}
-	*auth->seq_number =3D auth_context->local_seqnumber;
+	*auth.seq_number =3D auth_context->local_seqnumber;
     } else
-	auth->seq_number =3D NULL;
-    auth->authorization_data =3D NULL;
-    auth->cksum =3D cksum;
+	auth.seq_number =3D NULL;
+    auth.authorization_data =3D NULL;
=20
-    if (cksum !=3D NULL && cksum->cksumtype =3D=3D CKSUMTYPE_GSSAPI) {
-	/*
-	 * This is not GSS-API specific, we only enable it for
-	 * GSS for now
-	 */
-	ret =3D make_etypelist(context, &auth->authorization_data);
+    if (cksum) {
+	ALLOC(auth.cksum, 1);
+	if (auth.cksum =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    goto fail;
+	}
+	ret =3D copy_Checksum(cksum, auth.cksum);
 	if (ret)
 	    goto fail;
+
+	if (auth.cksum->cksumtype =3D=3D CKSUMTYPE_GSSAPI) {
+	    /*
+	     * This is not GSS-API specific, we only enable it for
+	     * GSS for now
+	     */
+	    ret =3D make_etypelist(context, &auth.authorization_data);
+	    if (ret)
+		goto fail;
+	}
     }
=20
     /* XXX - Copy more to auth_context? */
=20
-    auth_context->authenticator->ctime =3D auth->ctime;
-    auth_context->authenticator->cusec =3D auth->cusec;
+    auth_context->authenticator->ctime =3D auth.ctime;
+    auth_context->authenticator->cusec =3D auth.cusec;
=20
-    ASN1_MALLOC_ENCODE(Authenticator, buf, buf_size, auth, &len, ret);
+    ASN1_MALLOC_ENCODE(Authenticator, buf, buf_size, &auth, &len, ret);
     if (ret)
 	goto fail;
     if(buf_size !=3D len)
@@ -175,7 +182,7 @@
     ret =3D krb5_encrypt (context,
 			crypto,
 			usage /* KRB5_KU_AP_REQ_AUTH */,
-			buf + buf_size - len,=20
+			buf,
 			len,
 			result);
     krb5_crypto_destroy(context, crypto);
@@ -183,20 +190,9 @@
     if (ret)
 	goto fail;
=20
+ fail:
+    free_Authenticator (&auth);
     free (buf);
=20
-    if (auth_result)
-	*auth_result =3D auth;
-    else {
-	/* Don't free the `cksum', it's allocated by the caller */
-	auth->cksum =3D NULL;
-	free_Authenticator (auth);
-	free (auth);
-    }
-    return ret;
-  fail:
-    free_Authenticator (auth);
-    free (auth);
-    free (buf);
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/cache.c
--- a/head/crypto/heimdal/lib/krb5/cache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/cache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,104 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: cache.c 22127 2007-12-04 00:54:37Z lha $");
+/**
+ * @page krb5_ccache_intro The credential cache functions
+ * @section section_krb5_ccache Kerberos credential caches
+ *
+ * krb5_ccache structure holds a Kerberos credential cache.
+ *
+ * Heimdal support the follow types of credential caches:
+ *
+ * - SCC
+ *   Store the credential in a database
+ * - FILE
+ *   Store the credential in memory
+ * - MEMORY
+ *   Store the credential in memory
+ * - API
+ *   A credential cache server based solution for Mac OS X
+ * - KCM
+ *   A credential cache server based solution for all platforms
+ *
+ * @subsection Example
+ *
+ * This is a minimalistic version of klist:
+ at code
+#include <krb5.h>
+
+int
+main (int argc, char **argv)
+{
+    krb5_context context;
+    krb5_cc_cursor cursor;
+    krb5_error_code ret;
+    krb5_ccache id;
+    krb5_creds creds;
+
+    if (krb5_init_context (&context) !=3D 0)
+	errx(1, "krb5_context");
+
+    ret =3D krb5_cc_default (context, &id);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_default");
+
+    ret =3D krb5_cc_start_seq_get(context, id, &cursor);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_start_seq_get");
+
+    while((ret =3D krb5_cc_next_cred(context, id, &cursor, &creds)) =3D=3D=
 0){
+        char *principal;
+
+	krb5_unparse_name(context, creds.server, &principal);
+	printf("principal: %s\\n", principal);
+	free(principal);
+	krb5_free_cred_contents (context, &creds);
+    }
+    ret =3D krb5_cc_end_seq_get(context, id, &cursor);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_end_seq_get");
+
+    krb5_cc_close(context, id);
+
+    krb5_free_context(context);
+    return 0;
+}
+* @endcode
+*/
=20
 /**
  * Add a new ccache type with operations `ops', overwriting any
@@ -44,43 +109,44 @@
  * @param override flag to select if the registration is to overide
  * an existing ops with the same name.
  *
- * @return Return an error code or 0.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cc_register(krb5_context context,=20
-		 const krb5_cc_ops *ops,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_register(krb5_context context,
+		 const krb5_cc_ops *ops,
 		 krb5_boolean override)
 {
     int i;
=20
-    for(i =3D 0; i < context->num_cc_ops && context->cc_ops[i].prefix; i++=
) {
-	if(strcmp(context->cc_ops[i].prefix, ops->prefix) =3D=3D 0) {
+    for(i =3D 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i+=
+) {
+	if(strcmp(context->cc_ops[i]->prefix, ops->prefix) =3D=3D 0) {
 	    if(!override) {
-		krb5_set_error_string(context,
-				      "ccache type %s already exists",
-				      ops->prefix);
+		krb5_set_error_message(context,
+				       KRB5_CC_TYPE_EXISTS,
+				       N_("cache type %s already exists", "type"),
+				       ops->prefix);
 		return KRB5_CC_TYPE_EXISTS;
 	    }
 	    break;
 	}
     }
     if(i =3D=3D context->num_cc_ops) {
-	krb5_cc_ops *o =3D realloc(context->cc_ops,
-				 (context->num_cc_ops + 1) *
-				 sizeof(*context->cc_ops));
+	const krb5_cc_ops **o =3D realloc(rk_UNCONST(context->cc_ops),
+					(context->num_cc_ops + 1) *
+					sizeof(context->cc_ops[0]));
 	if(o =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, KRB5_CC_NOMEM,
+				   N_("malloc: out of memory", ""));
 	    return KRB5_CC_NOMEM;
 	}
+	context->cc_ops =3D o;
+	context->cc_ops[context->num_cc_ops] =3D NULL;
 	context->num_cc_ops++;
-	context->cc_ops =3D o;
-	memset(context->cc_ops + i, 0,=20
-	       (context->num_cc_ops - i) * sizeof(*context->cc_ops));
     }
-    memcpy(&context->cc_ops[i], ops, sizeof(context->cc_ops[i]));
+    context->cc_ops[i] =3D ops;
     return 0;
 }
=20
@@ -90,7 +156,7 @@
  */
=20
 krb5_error_code
-_krb5_cc_allocate(krb5_context context,=20
+_krb5_cc_allocate(krb5_context context,
 		  const krb5_cc_ops *ops,
 		  krb5_ccache *id)
 {
@@ -98,7 +164,8 @@
=20
     p =3D malloc (sizeof(*p));
     if(p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
     p->ops =3D ops;
@@ -119,16 +186,58 @@
 		 krb5_ccache *id)
 {
     krb5_error_code ret;
+#ifdef KRB5_USE_PATH_TOKENS
+    char * exp_residual =3D NULL;
+
+    ret =3D _krb5_expand_path_tokens(context, residual, &exp_residual);
+    if (ret)
+	return ret;
+
+    residual =3D exp_residual;
+#endif
=20
     ret =3D _krb5_cc_allocate(context, ops, id);
-    if (ret)
+    if (ret) {
+#ifdef KRB5_USE_PATH_TOKENS
+	if (exp_residual)
+	    free(exp_residual);
+#endif
 	return ret;
+    }
+
     ret =3D (*id)->ops->resolve(context, id, residual);
-    if(ret)
+    if(ret) {
 	free(*id);
+        *id =3D NULL;
+    }
+
+#ifdef KRB5_USE_PATH_TOKENS
+    if (exp_residual)
+	free(exp_residual);
+#endif
+
     return ret;
 }
=20
+static int
+is_possible_path_name(const char * name)
+{
+    const char * colon;
+
+    if ((colon =3D strchr(name, ':')) =3D=3D NULL)
+        return TRUE;
+
+#ifdef _WIN32
+    /* <drive letter>:\path\to\cache ? */
+
+    if (colon =3D=3D name + 1 &&
+        strchr(colon + 1, ':') =3D=3D NULL)
+        return TRUE;
+#endif
+
+    return FALSE;
+}
+
 /**
  * Find and allocate a ccache in `id' from the specification in `residual'.
  * If the ccache name doesn't contain any colon, interpret it as a file na=
me.
@@ -138,13 +247,13 @@
  * @param id return pointer to a found credential cache.
  *
  * @return Return 0 or an error code. In case of an error, id is set
- * to NULL.
+ * to NULL, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_resolve(krb5_context context,
 		const char *name,
 		krb5_ccache *id)
@@ -153,73 +262,60 @@
=20
     *id =3D NULL;
=20
-    for(i =3D 0; i < context->num_cc_ops && context->cc_ops[i].prefix; i++=
) {
-	size_t prefix_len =3D strlen(context->cc_ops[i].prefix);
+    for(i =3D 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i+=
+) {
+	size_t prefix_len =3D strlen(context->cc_ops[i]->prefix);
=20
-	if(strncmp(context->cc_ops[i].prefix, name, prefix_len) =3D=3D 0
+	if(strncmp(context->cc_ops[i]->prefix, name, prefix_len) =3D=3D 0
 	   && name[prefix_len] =3D=3D ':') {
-	    return allocate_ccache (context, &context->cc_ops[i],
+	    return allocate_ccache (context, context->cc_ops[i],
 				    name + prefix_len + 1,
 				    id);
 	}
     }
-    if (strchr (name, ':') =3D=3D NULL)
+    if (is_possible_path_name(name))
 	return allocate_ccache (context, &krb5_fcc_ops, name, id);
     else {
-	krb5_set_error_string(context, "unknown ccache type %s", name);
+	krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+			       N_("unknown ccache type %s", "name"), name);
 	return KRB5_CC_UNKNOWN_TYPE;
     }
 }
=20
 /**
- * Generate a new ccache of type `ops' in `id'.
- *
- * @return Return 0 or an error code.
- *
- * @ingroup krb5_ccache
- */
-
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cc_gen_new(krb5_context context,
-		const krb5_cc_ops *ops,
-		krb5_ccache *id)
-{
-    return krb5_cc_new_unique(context, ops->prefix, NULL, id);
-}
-
-/**
  * Generates a new unique ccache of `type` in `id'. If `type' is NULL,
  * the library chooses the default credential cache type. The supplied
  * `hint' (that can be NULL) is a string that the credential cache
  * type can use to base the name of the credential on, this is to make
  * it easier for the user to differentiate the credentials.
  *
- * @return Returns 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cc_new_unique(krb5_context context, const char *type,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_new_unique(krb5_context context, const char *type,
 		   const char *hint, krb5_ccache *id)
 {
-    const krb5_cc_ops *ops =3D KRB5_DEFAULT_CCTYPE;
+    const krb5_cc_ops *ops;
     krb5_error_code ret;
=20
-    if (type) {
-	ops =3D krb5_cc_get_prefix_ops(context, type);
-	if (ops =3D=3D NULL) {
-	    krb5_set_error_string(context,
-				  "Credential cache type %s is unknown", type);
-	    return KRB5_CC_UNKNOWN_TYPE;
-	}
+    ops =3D krb5_cc_get_prefix_ops(context, type);
+    if (ops =3D=3D NULL) {
+	krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+			      "Credential cache type %s is unknown", type);
+	return KRB5_CC_UNKNOWN_TYPE;
     }
=20
     ret =3D _krb5_cc_allocate(context, ops, id);
     if (ret)
 	return ret;
-    return (*id)->ops->gen_new(context, id);
+    ret =3D (*id)->ops->gen_new(context, id);
+    if (ret) {
+	free(*id);
+	*id =3D NULL;
+    }
+    return ret;
 }
=20
 /**
@@ -229,7 +325,7 @@
  */
=20
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_cc_get_name(krb5_context context,
 		 krb5_ccache id)
 {
@@ -243,7 +339,7 @@
  */
=20
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_cc_get_type(krb5_context context,
 		 krb5_ccache id)
 {
@@ -251,15 +347,19 @@
 }
=20
 /**
- * Return the complete resolvable name the ccache `id' in `str=B4.
- * `str` should be freed with free(3).
- * Returns 0 or an error (and then *str is set to NULL).
+ * Return the complete resolvable name the cache
+
+ * @param context a Keberos context
+ * @param id return pointer to a found credential cache
+ * @param str the returned name of a credential cache, free with krb5_xfre=
e()
+ *
+ * @return Returns 0 or an error (and then *str is set to NULL).
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_get_full_name(krb5_context context,
 		      krb5_ccache id,
 		      char **str)
@@ -270,18 +370,20 @@
=20
     type =3D krb5_cc_get_type(context, id);
     if (type =3D=3D NULL) {
-	krb5_set_error_string(context, "cache have no name of type");
+	krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+			       "cache have no name of type");
 	return KRB5_CC_UNKNOWN_TYPE;
     }
=20
     name =3D krb5_cc_get_name(context, id);
     if (name =3D=3D NULL) {
-	krb5_set_error_string(context, "cache of type %s have no name", type);
+	krb5_set_error_message(context, KRB5_CC_BADNAME,
+			       "cache of type %s have no name", type);
 	return KRB5_CC_BADNAME;
     }
-   =20
+
     if (asprintf(str, "%s:%s", type, name) =3D=3D -1) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	*str =3D NULL;
 	return ENOMEM;
     }
@@ -295,7 +397,7 @@
  */
=20
=20
-const krb5_cc_ops *
+KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL
 krb5_cc_get_ops(krb5_context context, krb5_ccache id)
 {
     return id->ops;
@@ -308,68 +410,7 @@
 krb5_error_code
 _krb5_expand_default_cc_name(krb5_context context, const char *str, char *=
*res)
 {
-    size_t tlen, len =3D 0;
-    char *tmp, *tmp2, *append;
-
-    *res =3D NULL;
-
-    while (str && *str) {
-	tmp =3D strstr(str, "%{");
-	if (tmp && tmp !=3D str) {
-	    append =3D malloc((tmp - str) + 1);
-	    if (append) {
-		memcpy(append, str, tmp - str);
-		append[tmp - str] =3D '\0';
-	    }
-	    str =3D tmp;
-	} else if (tmp) {
-	    tmp2 =3D strchr(tmp, '}');
-	    if (tmp2 =3D=3D NULL) {
-		free(*res);
-		*res =3D NULL;
-		krb5_set_error_string(context, "variable missing }");
-		return KRB5_CONFIG_BADFORMAT;
-	    }
-	    if (strncasecmp(tmp, "%{uid}", 6) =3D=3D 0)
-		asprintf(&append, "%u", (unsigned)getuid());
-	    else if (strncasecmp(tmp, "%{null}", 7) =3D=3D 0)
-		append =3D strdup("");
-	    else {
-		free(*res);
-		*res =3D NULL;
-		krb5_set_error_string(context,=20
-				      "expand default cache unknown "
-				      "variable \"%.*s\"",
-				      (int)(tmp2 - tmp) - 2, tmp + 2);
-		return KRB5_CONFIG_BADFORMAT;
-	    }
-	    str =3D tmp2 + 1;
-	} else {
-	    append =3D strdup(str);
-	    str =3D NULL;
-	}
-	if (append =3D=3D NULL) {
-	    free(*res);
-	    *res =3D NULL;
-	    krb5_set_error_string(context, "malloc - out of memory");
-	    return ENOMEM;
-	}
-=09
-	tlen =3D strlen(append);
-	tmp =3D realloc(*res, len + tlen + 1);
-	if (tmp =3D=3D NULL) {
-	    free(append);
-	    free(*res);
-	    *res =3D NULL;
-	    krb5_set_error_string(context, "malloc - out of memory");
-	    return ENOMEM;
-	}
-	*res =3D tmp;
-	memcpy(*res + len, append, tlen + 1);
-	len =3D len + tlen;
-	free(append);
-    }   =20
-    return 0;
+    return _krb5_expand_path_tokens(context, str, res);
 }
=20
 /*
@@ -386,6 +427,12 @@
     if (context->default_cc_name_set)
 	return 0;
=20
+    /* XXX performance: always ask KCM/API if default name has changed */
+    if (context->default_cc_name &&
+	(strncmp(context->default_cc_name, "KCM:", 4) =3D=3D 0 ||
+	 strncmp(context->default_cc_name, "API:", 4) =3D=3D 0))
+	return 1;
+
     if(issuid())
 	return 0;
=20
@@ -406,17 +453,55 @@
 }
=20
 /**
+ * Switch the default default credential cache for a specific
+ * credcache type (and name for some implementations).
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_switch(krb5_context context, krb5_ccache id)
+{
+#ifdef _WIN32
+    _krb5_set_default_cc_name_to_registry(context, id);
+#endif
+
+    if (id->ops->set_default =3D=3D NULL)
+	return 0;
+
+    return (*id->ops->set_default)(context, id);
+}
+
+/**
+ * Return true if the default credential cache support switch
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_cc_support_switch(krb5_context context, const char *type)
+{
+    const krb5_cc_ops *ops;
+
+    ops =3D krb5_cc_get_prefix_ops(context, type);
+    if (ops && ops->set_default)
+	return 1;
+    return FALSE;
+}
+
+/**
  * Set the default cc name for `context' to `name'.
  *
  * @ingroup krb5_ccache
  */
=20
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_set_default_name(krb5_context context, const char *name)
 {
     krb5_error_code ret =3D 0;
-    char *p;
+    char *p =3D NULL, *exp_p =3D NULL;
=20
     if (name =3D=3D NULL) {
 	const char *e =3D NULL;
@@ -430,6 +515,12 @@
 		context->default_cc_name_env =3D strdup(e);
 	    }
 	}
+
+#ifdef _WIN32
+        if (e =3D=3D NULL) {
+            e =3D p =3D _krb5_get_default_cc_name_from_registry(context);
+        }
+#endif
 	if (e =3D=3D NULL) {
 	    e =3D krb5_config_get_string(context, NULL, "libdefaults",
 				       "default_cc_name", NULL);
@@ -440,7 +531,19 @@
 	    }
 	    if (e =3D=3D NULL) {
 		const krb5_cc_ops *ops =3D KRB5_DEFAULT_CCTYPE;
-		ret =3D (*ops->default_name)(context, &p);
+		e =3D krb5_config_get_string(context, NULL, "libdefaults",
+					   "default_cc_type", NULL);
+		if (e) {
+		    ops =3D krb5_cc_get_prefix_ops(context, e);
+		    if (ops =3D=3D NULL) {
+			krb5_set_error_message(context,
+					       KRB5_CC_UNKNOWN_TYPE,
+					       "Credential cache type %s "
+					      "is unknown", e);
+			return KRB5_CC_UNKNOWN_TYPE;
+		    }
+		}
+		ret =3D (*ops->get_default_name)(context, &p);
 		if (ret)
 		    return ret;
 	    }
@@ -452,16 +555,21 @@
     }
=20
     if (p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
+    ret =3D _krb5_expand_path_tokens(context, p, &exp_p);
+    free(p);
+    if (ret)
+	return ret;
+
     if (context->default_cc_name)
 	free(context->default_cc_name);
=20
-    context->default_cc_name =3D p;
+    context->default_cc_name =3D exp_p;
=20
-    return ret;
+    return 0;
 }
=20
 /**
@@ -474,7 +582,7 @@
  */
=20
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_cc_default_name(krb5_context context)
 {
     if (context->default_cc_name =3D=3D NULL || environment_changed(contex=
t))
@@ -486,20 +594,20 @@
 /**
  * Open the default ccache in `id'.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_default(krb5_context context,
 		krb5_ccache *id)
 {
     const char *p =3D krb5_cc_default_name(context);
=20
     if (p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return krb5_cc_resolve(context, p, id);
@@ -508,13 +616,13 @@
 /**
  * Create a new ccache in `id' for `primary_principal'.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_initialize(krb5_context context,
 		   krb5_ccache id,
 		   krb5_principal primary_principal)
@@ -526,13 +634,13 @@
 /**
  * Remove the ccache `id'.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_destroy(krb5_context context,
 		krb5_ccache id)
 {
@@ -546,13 +654,13 @@
 /**
  * Stop using the ccache `id' and free the related resources.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_close(krb5_context context,
 	      krb5_ccache id)
 {
@@ -565,13 +673,13 @@
 /**
  * Store `creds' in the ccache `id'.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_store_cred(krb5_context context,
 		   krb5_ccache id,
 		   krb5_creds *creds)
@@ -584,13 +692,20 @@
  * from `id' in `creds'. 'creds' must be free by the caller using
  * krb5_free_cred_contents.
  *
- * @return Return 0 or an error code.
+ * @param context A Kerberos 5 context
+ * @param id a Kerberos 5 credential cache
+ * @param whichfields what fields to use for matching credentials, same
+ *        flags as whichfields in krb5_compare_creds()
+ * @param mcreds template credential to use for comparing
+ * @param creds returned credential, free with krb5_free_cred_contents()
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_retrieve_cred(krb5_context context,
 		      krb5_ccache id,
 		      krb5_flags whichfields,
@@ -622,13 +737,13 @@
 /**
  * Return the principal of `id' in `principal'.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_get_principal(krb5_context context,
 		      krb5_ccache id,
 		      krb5_principal *principal)
@@ -638,15 +753,15 @@
=20
 /**
  * Start iterating over `id', `cursor' is initialized to the
- * beginning.
+ * beginning.  Caller must free the cursor with krb5_cc_end_seq_get().
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_start_seq_get (krb5_context context,
 		       const krb5_ccache id,
 		       krb5_cc_cursor *cursor)
@@ -658,13 +773,13 @@
  * Retrieve the next cred pointed to by (`id', `cursor') in `creds'
  * and advance `cursor'.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_next_cred (krb5_context context,
 		   const krb5_ccache id,
 		   krb5_cc_cursor *cursor,
@@ -674,39 +789,13 @@
 }
=20
 /**
- * Like krb5_cc_next_cred, but allow for selective retrieval
- *
- * @ingroup krb5_ccache
- */
-
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cc_next_cred_match(krb5_context context,
-			const krb5_ccache id,
-			krb5_cc_cursor * cursor,
-			krb5_creds * creds,
-			krb5_flags whichfields,
-			const krb5_creds * mcreds)
-{
-    krb5_error_code ret;
-    while (1) {
-	ret =3D krb5_cc_next_cred(context, id, cursor, creds);
-	if (ret)
-	    return ret;
-	if (mcreds =3D=3D NULL || krb5_compare_creds(context, whichfields, mcreds=
, creds))
-	    return 0;
-	krb5_free_cred_contents(context, creds);
-    }
-}
-
-/**
  * Destroy the cursor `cursor'.
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_end_seq_get (krb5_context context,
 		     const krb5_ccache id,
 		     krb5_cc_cursor *cursor)
@@ -721,16 +810,17 @@
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_remove_cred(krb5_context context,
 		    krb5_ccache id,
 		    krb5_flags which,
 		    krb5_creds *cred)
 {
     if(id->ops->remove_cred =3D=3D NULL) {
-	krb5_set_error_string(context,
-			      "ccache %s does not support remove_cred",
-			      id->ops->prefix);
+	krb5_set_error_message(context,
+			       EACCES,
+			       "ccache %s does not support remove_cred",
+			       id->ops->prefix);
 	return EACCES; /* XXX */
     }
     return (*id->ops->remove_cred)(context, id, which, cred);
@@ -743,34 +833,61 @@
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_set_flags(krb5_context context,
 		  krb5_ccache id,
 		  krb5_flags flags)
 {
     return (*id->ops->set_flags)(context, id, flags);
 }
-		   =20
+
 /**
- * Copy the contents of `from' to `to'.
+ * Get the flags of `id', store them in `flags'.
  *
  * @ingroup krb5_ccache
  */
=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_flags(krb5_context context,
+		  krb5_ccache id,
+		  krb5_flags *flags)
+{
+    *flags =3D 0;
+    return 0;
+}
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cc_copy_cache_match(krb5_context context,
-			 const krb5_ccache from,
-			 krb5_ccache to,
-			 krb5_flags whichfields,
-			 const krb5_creds * mcreds,
-			 unsigned int *matched)
+/**
+ * Copy the contents of `from' to `to' if the given match function
+ * return true.
+ *
+ * @param context A Kerberos 5 context.
+ * @param from the cache to copy data from.
+ * @param to the cache to copy data to.
+ * @param match a match function that should return TRUE if cred argument =
should be copied, if NULL, all credentials are copied.
+ * @param matchctx context passed to match function.
+ * @param matched set to true if there was a credential that matched, may =
be NULL.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_copy_match_f(krb5_context context,
+		     const krb5_ccache from,
+		     krb5_ccache to,
+		     krb5_boolean (*match)(krb5_context, void *, const krb5_creds *),
+		     void *matchctx,
+		     unsigned int *matched)
 {
     krb5_error_code ret;
     krb5_cc_cursor cursor;
     krb5_creds cred;
     krb5_principal princ;
=20
+    if (matched)
+	*matched =3D 0;
+
     ret =3D krb5_cc_get_principal(context, from, &princ);
     if (ret)
 	return ret;
@@ -784,34 +901,36 @@
 	krb5_free_principal(context, princ);
 	return ret;
     }
-    if (matched)
-	*matched =3D 0;
-    while (ret =3D=3D 0 &&
-	   krb5_cc_next_cred_match(context, from, &cursor, &cred,
-				   whichfields, mcreds) =3D=3D 0) {
-	if (matched)
-	    (*matched)++;
-	ret =3D krb5_cc_store_cred(context, to, &cred);
-	krb5_free_cred_contents(context, &cred);
+
+    while ((ret =3D krb5_cc_next_cred(context, from, &cursor, &cred)) =3D=
=3D 0) {
+	   if (match =3D=3D NULL || (*match)(context, matchctx, &cred) =3D=3D 0) {
+	       if (matched)
+		   (*matched)++;
+	       ret =3D krb5_cc_store_cred(context, to, &cred);
+	       if (ret)
+		   break;
+	   }
+	   krb5_free_cred_contents(context, &cred);
     }
     krb5_cc_end_seq_get(context, from, &cursor);
     krb5_free_principal(context, princ);
+    if (ret =3D=3D KRB5_CC_END)
+	ret =3D 0;
     return ret;
 }
=20
 /**
- * Just like krb5_cc_copy_cache_match, but copy everything.
+ * Just like krb5_cc_copy_match_f(), but copy everything.
  *
- * @ingroup krb5_ccache
+ * @ingroup @krb5_ccache
  */
=20
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_copy_cache(krb5_context context,
 		   const krb5_ccache from,
 		   krb5_ccache to)
 {
-    return krb5_cc_copy_cache_match(context, from, to, 0, NULL, NULL);
+    return krb5_cc_copy_match_f(context, from, to, NULL, NULL, NULL);
 }
=20
 /**
@@ -821,7 +940,7 @@
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_get_version(krb5_context context,
 		    const krb5_ccache id)
 {
@@ -838,7 +957,7 @@
  */
=20
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_cc_clear_mcred(krb5_creds *mcred)
 {
     memset(mcred, 0, sizeof(*mcred));
@@ -846,37 +965,41 @@
=20
 /**
  * Get the cc ops that is registered in `context' to handle the
- * `prefix'. `prefix' can be a complete credential cache name or a
+ * prefix. prefix can be a complete credential cache name or a
  * prefix, the function will only use part up to the first colon (:)
- * if there is one.
- * Returns NULL if ops not found.
+ * if there is one. If prefix the argument is NULL, the default ccache
+ * implemtation is returned.
+ *
+ * @return Returns NULL if ops not found.
  *
  * @ingroup krb5_ccache
  */
=20
=20
-const krb5_cc_ops *
+KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL
 krb5_cc_get_prefix_ops(krb5_context context, const char *prefix)
 {
     char *p, *p1;
     int i;
-   =20
+
+    if (prefix =3D=3D NULL)
+	return KRB5_DEFAULT_CCTYPE;
     if (prefix[0] =3D=3D '/')
 	return &krb5_fcc_ops;
=20
     p =3D strdup(prefix);
     if (p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return NULL;
     }
     p1 =3D strchr(p, ':');
     if (p1)
 	*p1 =3D '\0';
=20
-    for(i =3D 0; i < context->num_cc_ops && context->cc_ops[i].prefix; i++=
) {
-	if(strcmp(context->cc_ops[i].prefix, p) =3D=3D 0) {
+    for(i =3D 0; i < context->num_cc_ops && context->cc_ops[i]->prefix; i+=
+) {
+	if(strcmp(context->cc_ops[i]->prefix, p) =3D=3D 0) {
 	    free(p);
-	    return &context->cc_ops[i];
+	    return context->cc_ops[i];
 	}
     }
     free(p);
@@ -889,16 +1012,20 @@
 };
=20
 /**
- * Start iterating over all caches of `type'. If `type' is NULL, the
- * default type is * used. `cursor' is initialized to the beginning.
+ * Start iterating over all caches of specified type. See also
+ * krb5_cccol_cursor_new().
+
+ * @param context A Kerberos 5 context
+ * @param type optional type to iterate over, if NULL, the default cache i=
s used.
+ * @param cursor cursor should be freed with krb5_cc_cache_end_seq_get().
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_get_first (krb5_context context,
 			 const char *type,
 			 krb5_cc_cache_cursor *cursor)
@@ -911,20 +1038,23 @@
=20
     ops =3D krb5_cc_get_prefix_ops(context, type);
     if (ops =3D=3D NULL) {
-	krb5_set_error_string(context, "Unknown type \"%s\" when iterating "
-			      "trying to iterate the credential caches", type);
+	krb5_set_error_message(context, KRB5_CC_UNKNOWN_TYPE,
+			       "Unknown type \"%s\" when iterating "
+			       "trying to iterate the credential caches", type);
 	return KRB5_CC_UNKNOWN_TYPE;
     }
=20
     if (ops->get_cache_first =3D=3D NULL) {
-	krb5_set_error_string(context, "Credential cache type %s doesn't support "
-			      "iterations over caches", ops->prefix);
+	krb5_set_error_message(context, KRB5_CC_NOSUPP,
+			       N_("Credential cache type %s doesn't support "
+				 "iterations over caches", "type"),
+			       ops->prefix);
 	return KRB5_CC_NOSUPP;
     }
=20
     *cursor =3D calloc(1, sizeof(**cursor));
     if (*cursor =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -942,13 +1072,18 @@
  * Retrieve the next cache pointed to by (`cursor') in `id'
  * and advance `cursor'.
  *
- * @return Return 0 or an error code.
+ * @param context A Kerberos 5 context
+ * @param cursor the iterator cursor, returned by krb5_cc_cache_get_first()
+ * @param id next ccache
+ *
+ * @return Return 0 or an error code. Returns KRB5_CC_END when the end
+ *         of caches is reached, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_next (krb5_context context,
 		   krb5_cc_cache_cursor cursor,
 		   krb5_ccache *id)
@@ -959,13 +1094,13 @@
 /**
  * Destroy the cursor `cursor'.
  *
- * @return Return 0 or an error code.
+ * @return Return an error code or 0, see krb5_get_error_message().
  *
  * @ingroup krb5_ccache
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_end_seq_get (krb5_context context,
 			   krb5_cc_cache_cursor cursor)
 {
@@ -977,10 +1112,13 @@
 }
=20
 /**
- * Search for a matching credential cache of type `type' that have the
- * `principal' as the default principal. If NULL is used for `type',
- * the default type is used. On success, `id' needs to be freed with
- * krb5_cc_close or krb5_cc_destroy.
+ * Search for a matching credential cache that have the
+ * `principal' as the default principal. On success, `id' needs to be
+ * freed with krb5_cc_close() or krb5_cc_destroy().
+ *
+ * @param context A Kerberos 5 context
+ * @param client The principal to search for
+ * @param id the returned credential cache
  *
  * @return On failure, error code is returned and `id' is set to NULL.
  *
@@ -988,29 +1126,28 @@
  */
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_match (krb5_context context,
 		     krb5_principal client,
-		     const char *type,
 		     krb5_ccache *id)
 {
-    krb5_cc_cache_cursor cursor;
+    krb5_cccol_cursor cursor;
     krb5_error_code ret;
     krb5_ccache cache =3D NULL;
=20
     *id =3D NULL;
=20
-    ret =3D krb5_cc_cache_get_first (context, type, &cursor);
+    ret =3D krb5_cccol_cursor_new (context, &cursor);
     if (ret)
 	return ret;
=20
-    while ((ret =3D krb5_cc_cache_next (context, cursor, &cache)) =3D=3D 0=
) {
+    while (krb5_cccol_cursor_next (context, cursor, &cache) =3D=3D 0 && ca=
che !=3D NULL) {
 	krb5_principal principal;
=20
 	ret =3D krb5_cc_get_principal(context, cache, &principal);
 	if (ret =3D=3D 0) {
 	    krb5_boolean match;
-	   =20
+
 	    match =3D krb5_principal_compare(context, principal, client);
 	    krb5_free_principal(context, principal);
 	    if (match)
@@ -1021,15 +1158,17 @@
 	cache =3D NULL;
     }
=20
-    krb5_cc_cache_end_seq_get(context, cursor);
+    krb5_cccol_cursor_free(context, &cursor);
=20
     if (cache =3D=3D NULL) {
 	char *str;
=20
 	krb5_unparse_name(context, client, &str);
=20
-	krb5_set_error_string(context, "Principal %s not found in a "
-			  "credential cache", str ? str : "<out of memory>");
+	krb5_set_error_message(context, KRB5_CC_NOTFOUND,
+			       N_("Principal %s not found in any "
+				  "credential cache", ""),
+			       str ? str : "<out of memory>");
 	if (str)
 	    free(str);
 	return KRB5_CC_NOTFOUND;
@@ -1041,26 +1180,27 @@
=20
 /**
  * Move the content from one credential cache to another. The
- * operation is an atomic switch.=20
+ * operation is an atomic switch.
  *
  * @param context a Keberos context
  * @param from the credential cache to move the content from
  * @param to the credential cache to move the content to
=20
  * @return On sucess, from is freed. On failure, error code is
- * returned and from and to are both still allocated.
+ * returned and from and to are both still allocated, see krb5_get_error_m=
essage().
  *
  * @ingroup krb5_ccache
  */
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
 {
     krb5_error_code ret;
=20
     if (strcmp(from->ops->prefix, to->ops->prefix) !=3D 0) {
-	krb5_set_error_string(context, "Moving credentials between diffrent "
-			      "types not yet supported");
+	krb5_set_error_message(context, KRB5_CC_NOSUPP,
+			       N_("Moving credentials between diffrent "
+				 "types not yet supported", ""));
 	return KRB5_CC_NOSUPP;
     }
=20
@@ -1071,3 +1211,553 @@
     }
     return ret;
 }
+
+#define KRB5_CONF_NAME "krb5_ccache_conf_data"
+#define KRB5_REALM_NAME "X-CACHECONF:"
+
+static krb5_error_code
+build_conf_principals(krb5_context context, krb5_ccache id,
+		      krb5_const_principal principal,
+		      const char *name, krb5_creds *cred)
+{
+    krb5_principal client;
+    krb5_error_code ret;
+    char *pname =3D NULL;
+
+    memset(cred, 0, sizeof(*cred));
+
+    ret =3D krb5_cc_get_principal(context, id, &client);
+    if (ret)
+	return ret;
+
+    if (principal) {
+	ret =3D krb5_unparse_name(context, principal, &pname);
+	if (ret)
+	    return ret;
+    }
+
+    ret =3D krb5_make_principal(context, &cred->server,
+			      KRB5_REALM_NAME,
+			      KRB5_CONF_NAME, name, pname, NULL);
+    free(pname);
+    if (ret) {
+	krb5_free_principal(context, client);
+	return ret;
+    }
+    ret =3D krb5_copy_principal(context, client, &cred->client);
+    krb5_free_principal(context, client);
+    return ret;
+}
+
+/**
+ * Return TRUE (non zero) if the principal is a configuration
+ * principal (generated part of krb5_cc_set_config()). Returns FALSE
+ * (zero) if not a configuration principal.
+ *
+ * @param context a Keberos context
+ * @param principal principal to check if it a configuration principal
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_is_config_principal(krb5_context context,
+			 krb5_const_principal principal)
+{
+    if (strcmp(principal->realm, KRB5_REALM_NAME) !=3D 0)
+	return FALSE;
+
+    if (principal->name.name_string.len =3D=3D 0 ||
+	strcmp(principal->name.name_string.val[0], KRB5_CONF_NAME) !=3D 0)
+	return FALSE;
+
+    return TRUE;
+}
+
+/**
+ * Store some configuration for the credential cache in the cache.
+ * Existing configuration under the same name is over-written.
+ *
+ * @param context a Keberos context
+ * @param id the credential cache to store the data for
+ * @param principal configuration for a specific principal, if
+ * NULL, global for the whole cache.
+ * @param name name under which the configuraion is stored.
+ * @param data data to store, if NULL, configure is removed.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_config(krb5_context context, krb5_ccache id,
+		   krb5_const_principal principal,
+		   const char *name, krb5_data *data)
+{
+    krb5_error_code ret;
+    krb5_creds cred;
+
+    ret =3D build_conf_principals(context, id, principal, name, &cred);
+    if (ret)
+	goto out;
+
+    /* Remove old configuration */
+    ret =3D krb5_cc_remove_cred(context, id, 0, &cred);
+    if (ret && ret !=3D KRB5_CC_NOTFOUND)
+        goto out;
+
+    if (data) {
+	/* not that anyone care when this expire */
+	cred.times.authtime =3D time(NULL);
+	cred.times.endtime =3D cred.times.authtime + 3600 * 24 * 30;
+
+	ret =3D krb5_data_copy(&cred.ticket, data->data, data->length);
+	if (ret)
+	    goto out;
+
+	ret =3D krb5_cc_store_cred(context, id, &cred);
+    }
+
+out:
+    krb5_free_cred_contents (context, &cred);
+    return ret;
+}
+
+/**
+ * Get some configuration for the credential cache in the cache.
+ *
+ * @param context a Keberos context
+ * @param id the credential cache to store the data for
+ * @param principal configuration for a specific principal, if
+ * NULL, global for the whole cache.
+ * @param name name under which the configuraion is stored.
+ * @param data data to fetched, free with krb5_data_free()
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_config(krb5_context context, krb5_ccache id,
+		   krb5_const_principal principal,
+		   const char *name, krb5_data *data)
+{
+    krb5_creds mcred, cred;
+    krb5_error_code ret;
+
+    memset(&cred, 0, sizeof(cred));
+    krb5_data_zero(data);
+
+    ret =3D build_conf_principals(context, id, principal, name, &mcred);
+    if (ret)
+	goto out;
+
+    ret =3D krb5_cc_retrieve_cred(context, id, 0, &mcred, &cred);
+    if (ret)
+	goto out;
+
+    ret =3D krb5_data_copy(data, cred.ticket.data, cred.ticket.length);
+
+out:
+    krb5_free_cred_contents (context, &cred);
+    krb5_free_cred_contents (context, &mcred);
+    return ret;
+}
+
+/*
+ *
+ */
+
+struct krb5_cccol_cursor_data {
+    int idx;
+    krb5_cc_cache_cursor cursor;
+};
+
+/**
+ * Get a new cache interation cursor that will interate over all
+ * credentials caches independent of type.
+ *
+ * @param context a Keberos context
+ * @param cursor passed into krb5_cccol_cursor_next() and free with krb5_c=
ccol_cursor_free().
+ *
+ * @return Returns 0 or and error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_new(krb5_context context, krb5_cccol_cursor *cursor)
+{
+    *cursor =3D calloc(1, sizeof(**cursor));
+    if (*cursor =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
+    (*cursor)->idx =3D 0;
+    (*cursor)->cursor =3D NULL;
+
+    return 0;
+}
+
+/**
+ * Get next credential cache from the iteration.
+ *
+ * @param context A Kerberos 5 context
+ * @param cursor the iteration cursor
+ * @param cache the returned cursor, pointer is set to NULL on failure
+ *        and a cache on success. The returned cache needs to be freed
+ *        with krb5_cc_close() or destroyed with krb5_cc_destroy().
+ *        MIT Kerberos behavies slightly diffrent and sets cache to NULL
+ *        when all caches are iterated over and return 0.
+ *
+ * @return Return 0 or and error, KRB5_CC_END is returned at the end
+ *        of iteration. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_next(krb5_context context, krb5_cccol_cursor cursor,
+		       krb5_ccache *cache)
+{
+    krb5_error_code ret;
+
+    *cache =3D NULL;
+
+    while (cursor->idx < context->num_cc_ops) {
+
+	if (cursor->cursor =3D=3D NULL) {
+	    ret =3D krb5_cc_cache_get_first (context,
+					   context->cc_ops[cursor->idx]->prefix,
+					   &cursor->cursor);
+	    if (ret) {
+		cursor->idx++;
+		continue;
+	    }
+	}
+	ret =3D krb5_cc_cache_next(context, cursor->cursor, cache);
+	if (ret =3D=3D 0)
+	    break;
+
+	krb5_cc_cache_end_seq_get(context, cursor->cursor);
+	cursor->cursor =3D NULL;
+	if (ret !=3D KRB5_CC_END)
+	    break;
+
+	cursor->idx++;
+    }
+    if (cursor->idx >=3D context->num_cc_ops) {
+	krb5_set_error_message(context, KRB5_CC_END,
+			       N_("Reached end of credential caches", ""));
+	return KRB5_CC_END;
+    }
+
+    return 0;
+}
+
+/**
+ * End an iteration and free all resources, can be done before end is reac=
hed.
+ *
+ * @param context A Kerberos 5 context
+ * @param cursor the iteration cursor to be freed.
+ *
+ * @return Return 0 or and error, KRB5_CC_END is returned at the end
+ *        of iteration. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_free(krb5_context context, krb5_cccol_cursor *cursor)
+{
+    krb5_cccol_cursor c =3D *cursor;
+
+    *cursor =3D NULL;
+    if (c) {
+	if (c->cursor)
+	    krb5_cc_cache_end_seq_get(context, c->cursor);
+	free(c);
+    }
+    return 0;
+}
+
+/**
+ * Return the last time the credential cache was modified.
+ *
+ * @param context A Kerberos 5 context
+ * @param id The credential cache to probe
+ * @param mtime the last modification time, set to 0 on error.
+
+ * @return Return 0 or and error. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_last_change_time(krb5_context context,
+			 krb5_ccache id,
+			 krb5_timestamp *mtime)
+{
+    *mtime =3D 0;
+    return (*id->ops->lastchange)(context, id, mtime);
+}
+
+/**
+ * Return the last modfication time for a cache collection. The query
+ * can be limited to a specific cache type. If the function return 0
+ * and mtime is 0, there was no credentials in the caches.
+ *
+ * @param context A Kerberos 5 context
+ * @param type The credential cache to probe, if NULL, all type are traver=
sed.
+ * @param mtime the last modification time, set to 0 on error.
+
+ * @return Return 0 or and error. See krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_last_change_time(krb5_context context,
+			    const char *type,
+			    krb5_timestamp *mtime)
+{
+    krb5_cccol_cursor cursor;
+    krb5_error_code ret;
+    krb5_ccache id;
+    krb5_timestamp t =3D 0;
+
+    *mtime =3D 0;
+
+    ret =3D krb5_cccol_cursor_new (context, &cursor);
+    if (ret)
+	return ret;
+
+    while (krb5_cccol_cursor_next(context, cursor, &id) =3D=3D 0 && id !=
=3D NULL) {
+
+	if (type && strcmp(krb5_cc_get_type(context, id), type) !=3D 0)
+	    continue;
+
+	ret =3D krb5_cc_last_change_time(context, id, &t);
+	krb5_cc_close(context, id);
+	if (ret)
+	    continue;
+	if (t > *mtime)
+	    *mtime =3D t;
+    }
+
+    krb5_cccol_cursor_free(context, &cursor);
+
+    return 0;
+}
+/**
+ * Return a friendly name on credential cache. Free the result with krb5_x=
free().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_friendly_name(krb5_context context,
+			  krb5_ccache id,
+			  char **name)
+{
+    krb5_error_code ret;
+    krb5_data data;
+
+    ret =3D krb5_cc_get_config(context, id, NULL, "FriendlyName", &data);
+    if (ret) {
+	krb5_principal principal;
+	ret =3D krb5_cc_get_principal(context, id, &principal);
+	if (ret)
+	    return ret;
+	ret =3D krb5_unparse_name(context, principal, name);
+	krb5_free_principal(context, principal);
+    } else {
+	ret =3D asprintf(name, "%.*s", (int)data.length, (char *)data.data);
+	krb5_data_free(&data);
+	if (ret <=3D 0) {
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	} else
+	    ret =3D 0;
+    }
+
+    return ret;
+}
+
+/**
+ * Set the friendly name on credential cache.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_friendly_name(krb5_context context,
+			  krb5_ccache id,
+			  const char *name)
+{
+    krb5_data data;
+
+    data.data =3D rk_UNCONST(name);
+    data.length =3D strlen(name);
+
+    return krb5_cc_set_config(context, id, NULL, "FriendlyName", &data);
+}
+
+/**
+ * Get the lifetime of the initial ticket in the cache
+ *
+ * Get the lifetime of the initial ticket in the cache, if the initial
+ * ticket was not found, the error code KRB5_CC_END is returned.
+ *
+ * @param context A Kerberos 5 context.
+ * @param id a credential cache
+ * @param t the relative lifetime of the initial ticket
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_lifetime(krb5_context context, krb5_ccache id, time_t *t)
+{
+    krb5_cc_cursor cursor;
+    krb5_error_code ret;
+    krb5_creds cred;
+    time_t now;
+
+    *t =3D 0;
+    now =3D time(NULL);
+
+    ret =3D krb5_cc_start_seq_get(context, id, &cursor);
+    if (ret)
+	return ret;
+
+    while ((ret =3D krb5_cc_next_cred(context, id, &cursor, &cred)) =3D=3D=
 0) {
+	if (cred.flags.b.initial) {
+	    if (now < cred.times.endtime)
+		*t =3D cred.times.endtime - now;
+	    krb5_free_cred_contents(context, &cred);
+	    break;
+	}
+	krb5_free_cred_contents(context, &cred);
+    }
+
+    krb5_cc_end_seq_get(context, id, &cursor);
+
+    return ret;
+}
+
+/**
+ * Set the time offset betwen the client and the KDC
+ *
+ * If the backend doesn't support KDC offset, use the context global setti=
ng.
+ *
+ * @param context A Kerberos 5 context.
+ * @param id a credential cache
+ * @param offset the offset in seconds
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat o=
ffset)
+{
+    if (id->ops->set_kdc_offset =3D=3D NULL) {
+	context->kdc_sec_offset =3D offset;
+	context->kdc_usec_offset =3D 0;
+	return 0;
+    }
+    return (*id->ops->set_kdc_offset)(context, id, offset);
+}
+
+/**
+ * Get the time offset betwen the client and the KDC
+ *
+ * If the backend doesn't support KDC offset, use the context global setti=
ng.
+ *
+ * @param context A Kerberos 5 context.
+ * @param id a credential cache
+ * @param offset the offset in seconds
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *=
offset)
+{
+    if (id->ops->get_kdc_offset =3D=3D NULL) {
+	*offset =3D context->kdc_sec_offset;
+	return 0;
+    }
+    return (*id->ops->get_kdc_offset)(context, id, offset);
+}
+
+
+#ifdef _WIN32
+
+#define REGPATH_MIT_KRB5 "SOFTWARE\\MIT\\Kerberos5"
+char *
+_krb5_get_default_cc_name_from_registry(krb5_context context)
+{
+    HKEY hk_k5 =3D 0;
+    LONG code;
+    char * ccname =3D NULL;
+
+    code =3D RegOpenKeyEx(HKEY_CURRENT_USER,
+                        REGPATH_MIT_KRB5,
+                        0, KEY_READ, &hk_k5);
+
+    if (code !=3D ERROR_SUCCESS)
+        return NULL;
+
+    ccname =3D _krb5_parse_reg_value_as_string(context, hk_k5, "ccname",
+                                             REG_NONE, 0);
+
+    RegCloseKey(hk_k5);
+
+    return ccname;
+}
+
+int
+_krb5_set_default_cc_name_to_registry(krb5_context context, krb5_ccache id)
+{
+    HKEY hk_k5 =3D 0;
+    LONG code;
+    int ret =3D -1;
+    char * ccname =3D NULL;
+
+    code =3D RegOpenKeyEx(HKEY_CURRENT_USER,
+                        REGPATH_MIT_KRB5,
+                        0, KEY_READ|KEY_WRITE, &hk_k5);
+
+    if (code !=3D ERROR_SUCCESS)
+        return -1;
+
+    ret =3D asprintf(&ccname, "%s:%s", krb5_cc_get_type(context, id), krb5=
_cc_get_name(context, id));
+    if (ret < 0)
+        goto cleanup;
+
+    ret =3D _krb5_store_string_to_reg_value(context, hk_k5, "ccname",
+                                          REG_SZ, ccname, -1, 0);
+
+  cleanup:
+
+    if (ccname)
+        free(ccname);
+
+    RegCloseKey(hk_k5);
+
+    return ret;
+}
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/changepw.c
--- a/head/crypto/heimdal/lib/krb5/changepw.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/changepw.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,41 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: changepw.c 21505 2007-07-12 12:28:38Z lha $");
+#undef __attribute__
+#define __attribute__(X)
+
=20
 static void
 str2data (krb5_data *d,
@@ -57,7 +59,7 @@
 /*
  * Change password protocol defined by
  * draft-ietf-cat-kerb-chg-password-02.txt
- *=20
+ *
  * Share the response part of the protocol with MS set password
  * (RFC3244)
  */
@@ -68,7 +70,7 @@
 		    krb5_creds *creds,
 		    krb5_principal targprinc,
 		    int is_stream,
-		    int sock,
+		    rk_socket_t sock,
 		    const char *passwd,
 		    const char *host)
 {
@@ -78,7 +80,6 @@
     krb5_data passwd_data;
     size_t len;
     u_char header[6];
-    u_char *p;
     struct iovec iov[3];
     struct msghdr msghdr;
=20
@@ -114,13 +115,12 @@
 	goto out2;
=20
     len =3D 6 + ap_req_data.length + krb_priv_data.length;
-    p =3D header;
-    *p++ =3D (len >> 8) & 0xFF;
-    *p++ =3D (len >> 0) & 0xFF;
-    *p++ =3D 0;
-    *p++ =3D 1;
-    *p++ =3D (ap_req_data.length >> 8) & 0xFF;
-    *p++ =3D (ap_req_data.length >> 0) & 0xFF;
+    header[0] =3D (len >> 8) & 0xFF;
+    header[1] =3D (len >> 0) & 0xFF;
+    header[2] =3D 0;
+    header[3] =3D 1;
+    header[4] =3D (ap_req_data.length >> 8) & 0xFF;
+    header[5] =3D (ap_req_data.length >> 0) & 0xFF;
=20
     memset(&msghdr, 0, sizeof(msghdr));
     msghdr.msg_name       =3D NULL;
@@ -139,9 +139,10 @@
     iov[2].iov_base    =3D krb_priv_data.data;
     iov[2].iov_len     =3D krb_priv_data.length;
=20
-    if (sendmsg (sock, &msghdr, 0) < 0) {
-	ret =3D errno;
-	krb5_set_error_string(context, "sendmsg %s: %s", host, strerror(ret));
+    if (rk_IS_SOCKET_ERROR( sendmsg (sock, &msghdr, 0) )) {
+	ret =3D rk_SOCK_ERRNO;
+	krb5_set_error_message(context, ret, "sendmsg %s: %s",
+			       host, strerror(ret));
     }
=20
     krb5_data_free (&krb_priv_data);
@@ -161,7 +162,7 @@
 		    krb5_creds *creds,
 		    krb5_principal targprinc,
 		    int is_stream,
-		    int sock,
+		    rk_socket_t sock,
 		    const char *passwd,
 		    const char *host)
 {
@@ -170,7 +171,7 @@
     krb5_data krb_priv_data;
     krb5_data pwd_data;
     ChangePasswdDataMS chpw;
-    size_t len;
+    size_t len =3D 0;
     u_char header[4 + 6];
     u_char *p;
     struct iovec iov[3];
@@ -196,7 +197,7 @@
 	chpw.targname =3D NULL;
 	chpw.targrealm =3D NULL;
     }
-=09
+
     ASN1_MALLOC_ENCODE(ChangePasswdDataMS, pwd_data.data, pwd_data.length,
 		       &chpw, &len, ret);
     if (ret) {
@@ -226,7 +227,7 @@
     *p++ =3D 0xff;
     *p++ =3D 0x80;
     *p++ =3D (ap_req_data.length >> 8) & 0xFF;
-    *p++ =3D (ap_req_data.length >> 0) & 0xFF;
+    *p   =3D (ap_req_data.length >> 0) & 0xFF;
=20
     memset(&msghdr, 0, sizeof(msghdr));
     msghdr.msg_name       =3D NULL;
@@ -248,9 +249,10 @@
     iov[2].iov_base    =3D krb_priv_data.data;
     iov[2].iov_len     =3D krb_priv_data.length;
=20
-    if (sendmsg (sock, &msghdr, 0) < 0) {
-	ret =3D errno;
-	krb5_set_error_string(context, "sendmsg %s: %s", host, strerror(ret));
+    if (rk_IS_SOCKET_ERROR( sendmsg (sock, &msghdr, 0) )) {
+	ret =3D rk_SOCK_ERRNO;
+	krb5_set_error_message(context, ret, "sendmsg %s: %s",
+			       host, strerror(ret));
     }
=20
     krb5_data_free (&krb_priv_data);
@@ -264,7 +266,7 @@
 process_reply (krb5_context context,
 	       krb5_auth_context auth_context,
 	       int is_stream,
-	       int sock,
+	       rk_socket_t sock,
 	       int *result_code,
 	       krb5_data *result_code_string,
 	       krb5_data *result_string,
@@ -272,7 +274,7 @@
 {
     krb5_error_code ret;
     u_char reply[1024 * 3];
-    ssize_t len;
+    size_t len;
     uint16_t pkt_len, pkt_ver;
     krb5_data ap_rep_data;
     int save_errno;
@@ -282,15 +284,16 @@
 	while (len < sizeof(reply)) {
 	    unsigned long size;
=20
-	    ret =3D recvfrom (sock, reply + len, sizeof(reply) - len,=20
+	    ret =3D recvfrom (sock, reply + len, sizeof(reply) - len,
 			    0, NULL, NULL);
-	    if (ret < 0) {
-		save_errno =3D errno;
-		krb5_set_error_string(context, "recvfrom %s: %s",
-				      host, strerror(save_errno));
+	    if (rk_IS_SOCKET_ERROR(ret)) {
+		save_errno =3D rk_SOCK_ERRNO;
+		krb5_set_error_message(context, save_errno,
+				       "recvfrom %s: %s",
+				       host, strerror(save_errno));
 		return save_errno;
 	    } else if (ret =3D=3D 0) {
-		krb5_set_error_string(context, "recvfrom timeout %s", host);
+		krb5_set_error_message(context, 1,"recvfrom timeout %s", host);
 		return 1;
 	    }
 	    len +=3D ret;
@@ -299,21 +302,23 @@
 	    _krb5_get_int(reply, &size, 4);
 	    if (size + 4 < len)
 		continue;
-	    memmove(reply, reply + 4, size);	=09
+	    memmove(reply, reply + 4, size);
 	    len =3D size;
 	    break;
 	}
 	if (len =3D=3D sizeof(reply)) {
-	    krb5_set_error_string(context, "message too large from %s",
-				  host);
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("Message too large from %s", "host"),
+				   host);
 	    return ENOMEM;
 	}
     } else {
 	ret =3D recvfrom (sock, reply, sizeof(reply), 0, NULL, NULL);
-	if (ret < 0) {
-	    save_errno =3D errno;
-	    krb5_set_error_string(context, "recvfrom %s: %s",
-				  host, strerror(save_errno));
+	if (rk_IS_SOCKET_ERROR(ret)) {
+	    save_errno =3D rk_SOCK_ERRNO;
+	    krb5_set_error_message(context, save_errno,
+				   "recvfrom %s: %s",
+				   host, strerror(save_errno));
 	    return save_errno;
 	}
 	len =3D ret;
@@ -321,7 +326,7 @@
=20
     if (len < 6) {
 	str2data (result_string, "server %s sent to too short message "
-		  "(%ld bytes)", host, (long)len);
+		  "(%zu bytes)", host, len);
 	*result_code =3D KRB5_KPASSWD_MALFORMED;
 	return 0;
     }
@@ -352,7 +357,7 @@
 	*result_code =3D (p[0] << 8) | p[1];
 	if (error.e_data->length =3D=3D 2)
 	    str2data(result_string, "server only sent error code");
-	else=20
+	else
 	    krb5_data_copy (result_string,
 			    p + 2,
 			    error.e_data->length - 2);
@@ -374,7 +379,7 @@
=20
     ap_rep_data.data =3D reply + 6;
     ap_rep_data.length  =3D (reply[4] << 8) | (reply[5]);
- =20
+
     if (reply + len < (u_char *)ap_rep_data.data + ap_rep_data.length) {
 	str2data (result_string, "client: wrong AP len in reply");
 	*result_code =3D KRB5_KPASSWD_MALFORMED;
@@ -416,7 +421,7 @@
 	}
=20
         p =3D result_code_string->data;
-     =20
+
         *result_code =3D (p[0] << 8) | p[1];
         krb5_data_copy (result_string,
                         (unsigned char*)result_code_string->data + 2,
@@ -426,7 +431,7 @@
 	KRB_ERROR error;
 	size_t size;
 	u_char *p;
-     =20
+
 	ret =3D decode_KRB_ERROR(reply + 6, len - 6, &error, &size);
 	if (ret) {
 	    return ret;
@@ -457,13 +462,13 @@
 					      krb5_creds *,
 					      krb5_principal,
 					      int,
-					      int,
+					      rk_socket_t,
 					      const char *,
 					      const char *);
 typedef krb5_error_code (*kpwd_process_reply) (krb5_context,
 					       krb5_auth_context,
 					       int,
-					       int,
+					       rk_socket_t,
 					       int *,
 					       krb5_data *,
 					       krb5_data *,
@@ -478,9 +483,9 @@
     kpwd_process_reply process_rep;
 } procs[] =3D {
     {
-	"MS set password",=20
+	"MS set password",
 	SUPPORT_TCP|SUPPORT_UDP,
-	setpw_send_request,=20
+	setpw_send_request,
 	process_reply
     },
     {
@@ -489,20 +494,9 @@
 	chgpw_send_request,
 	process_reply
     },
-    { NULL }
+    { NULL, 0, NULL, NULL }
 };
=20
-static struct kpwd_proc *
-find_chpw_proto(const char *name)
-{
-    struct kpwd_proc *p;
-    for (p =3D procs; p->name !=3D NULL; p++) {
-	if (strcmp(p->name, name) =3D=3D 0)
-	    return p;
-    }
-    return NULL;
-}
-
 /*
  *
  */
@@ -521,8 +515,8 @@
     krb5_auth_context auth_context =3D NULL;
     krb5_krbhst_handle handle =3D NULL;
     krb5_krbhst_info *hi;
-    int sock;
-    int i;
+    rk_socket_t sock;
+    unsigned int i;
     int done =3D 0;
     krb5_realm realm;
=20
@@ -568,20 +562,21 @@
 	for (a =3D ai; !done && a !=3D NULL; a =3D a->ai_next) {
 	    int replied =3D 0;
=20
-	    sock =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
-	    if (sock < 0)
+	    sock =3D socket (a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_p=
rotocol);
+	    if (rk_IS_BAD_SOCKET(sock))
 		continue;
+	    rk_cloexec(sock);
=20
 	    ret =3D connect(sock, a->ai_addr, a->ai_addrlen);
-	    if (ret < 0) {
-		close (sock);
+	    if (rk_IS_SOCKET_ERROR(ret)) {
+		rk_closesocket (sock);
 		goto out;
 	    }
=20
 	    ret =3D krb5_auth_con_genaddrs (context, auth_context, sock,
 					  KRB5_AUTH_CONTEXT_GENERATE_LOCAL_ADDR);
 	    if (ret) {
-		close (sock);
+		rk_closesocket (sock);
 		goto out;
 	    }
=20
@@ -591,7 +586,7 @@
=20
 		if (!replied) {
 		    replied =3D 0;
-		   =20
+
 		    ret =3D (*proc->send_req) (context,
 					     &auth_context,
 					     creds,
@@ -601,17 +596,20 @@
 					     newpw,
 					     hi->hostname);
 		    if (ret) {
-			close(sock);
+			rk_closesocket(sock);
 			goto out;
 		    }
 		}
-	   =20
+
+#ifndef NO_LIMIT_FD_SETSIZE
 		if (sock >=3D FD_SETSIZE) {
-		    krb5_set_error_string(context, "fd %d too large", sock);
 		    ret =3D ERANGE;
-		    close (sock);
+		    krb5_set_error_message(context, ret,
+					   "fd %d too large", sock);
+		    rk_closesocket (sock);
 		    goto out;
 		}
+#endif
=20
 		FD_ZERO(&fdset);
 		FD_SET(sock, &fdset);
@@ -619,8 +617,8 @@
 		tv.tv_sec  =3D 1 + (1 << i);
=20
 		ret =3D select (sock + 1, &fdset, NULL, NULL, &tv);
-		if (ret < 0 && errno !=3D EINTR) {
-		    close(sock);
+		if (rk_IS_SOCKET_ERROR(ret) && rk_SOCK_ERRNO !=3D EINTR) {
+		    rk_closesocket(sock);
 		    goto out;
 		}
 		if (ret =3D=3D 1) {
@@ -640,40 +638,60 @@
 		    ret =3D KRB5_KDC_UNREACH;
 		}
 	    }
-	    close (sock);
+	    rk_closesocket (sock);
 	}
     }
=20
  out:
     krb5_krbhst_free (context, handle);
     krb5_auth_con_free (context, auth_context);
-    if (done)
-	return 0;
-    else {
-	if (ret =3D=3D KRB5_KDC_UNREACH) {
-	    krb5_set_error_string(context,
-				  "unable to reach any changepw server "
-				  " in realm %s", realm);
-	    *result_code =3D KRB5_KPASSWD_HARDERROR;
-	}
-	return ret;
+
+    if (ret =3D=3D KRB5_KDC_UNREACH) {
+	krb5_set_error_message(context,
+			       ret,
+			       N_("Unable to reach any changepw server "
+				 " in realm %s", "realm"), realm);
+	*result_code =3D KRB5_KPASSWD_HARDERROR;
     }
+    return ret;
 }
=20
+#ifndef HEIMDAL_SMALLER
=20
-/*
- * change the password using the credentials in `creds' (for the
- * principal indicated in them) to `newpw', storing the result of
- * the operation in `result_*' and an error code or 0.
+static struct kpwd_proc *
+find_chpw_proto(const char *name)
+{
+    struct kpwd_proc *p;
+    for (p =3D procs; p->name !=3D NULL; p++) {
+	if (strcmp(p->name, name) =3D=3D 0)
+	    return p;
+    }
+    return NULL;
+}
+
+/**
+ * Deprecated: krb5_change_password() is deprecated, use krb5_set_password=
().
+ *
+ * @param context a Keberos context
+ * @param creds
+ * @param newpw
+ * @param result_code
+ * @param result_code_string
+ * @param result_string
+ *
+ * @return On sucess password is changed.
+
+ * @ingroup @krb5_deprecated
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_change_password (krb5_context	context,
 		      krb5_creds	*creds,
 		      const char	*newpw,
 		      int		*result_code,
 		      krb5_data		*result_code_string,
 		      krb5_data		*result_string)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     struct kpwd_proc *p =3D find_chpw_proto("change password");
=20
@@ -684,16 +702,31 @@
     if (p =3D=3D NULL)
 	return KRB5_KPASSWD_MALFORMED;
=20
-    return change_password_loop(context, creds, NULL, newpw,=20
-				result_code, result_code_string,=20
+    return change_password_loop(context, creds, NULL, newpw,
+				result_code, result_code_string,
 				result_string, p);
 }
+#endif /* HEIMDAL_SMALLER */
=20
-/*
+/**
+ * Change password using creds.
  *
+ * @param context a Keberos context
+ * @param creds The initial kadmin/passwd for the principal or an admin pr=
incipal
+ * @param newpw The new password to set
+ * @param targprinc if unset, the default principal is used.
+ * @param result_code Result code, KRB5_KPASSWD_SUCCESS is when password i=
s changed.
+ * @param result_code_string binary message from the server, contains
+ * at least the result_code.
+ * @param result_string A message from the kpasswd service or the
+ * library in human printable form. The string is NUL terminated.
+ *
+ * @return On sucess and *result_code is KRB5_KPASSWD_SUCCESS, the passwor=
d is changed.
+
+ * @ingroup @krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_password(krb5_context context,
 		  krb5_creds *creds,
 		  const char *newpw,
@@ -707,8 +740,8 @@
     int i;
=20
     *result_code =3D KRB5_KPASSWD_MALFORMED;
-    result_code_string->data =3D result_string->data =3D NULL;
-    result_code_string->length =3D result_string->length =3D 0;
+    krb5_data_zero(result_code_string);
+    krb5_data_zero(result_string);
=20
     if (targprinc =3D=3D NULL) {
 	ret =3D krb5_get_default_principal(context, &principal);
@@ -719,9 +752,9 @@
=20
     for (i =3D 0; procs[i].name !=3D NULL; i++) {
 	*result_code =3D 0;
-	ret =3D change_password_loop(context, creds, principal, newpw,=20
-				   result_code, result_code_string,=20
-				   result_string,=20
+	ret =3D change_password_loop(context, creds, principal, newpw,
+				   result_code, result_code_string,
+				   result_string,
 				   &procs[i]);
 	if (ret =3D=3D 0 && *result_code =3D=3D 0)
 	    break;
@@ -736,7 +769,7 @@
  *
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_password_using_ccache(krb5_context context,
 			       krb5_ccache ccache,
 			       const char *newpw,
@@ -762,7 +795,7 @@
     } else
 	principal =3D targprinc;
=20
-    ret =3D krb5_make_principal(context, &creds.server,=20
+    ret =3D krb5_make_principal(context, &creds.server,
 			      krb5_principal_get_realm(context, principal),
 			      "kadmin", "changepw", NULL);
     if (ret)
@@ -788,7 +821,7 @@
 			    result_code_string,
 			    result_string);
=20
-    krb5_free_creds(context, credsp);=20
+    krb5_free_creds(context, credsp);
=20
     return ret;
  out:
@@ -801,7 +834,7 @@
  *
  */
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_passwd_result_to_string (krb5_context context,
 			      int result)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/codec.c
--- a/head/crypto/heimdal/lib/krb5/codec.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/codec.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,196 +1,214 @@
 /*
- * Copyright (c) 1998 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: codec.c 13863 2004-05-25 21:46:46Z lha $");
+#ifndef HEIMDAL_SMALLER
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncTicketPart (krb5_context context,
 			   const void *data,
 			   size_t length,
 			   EncTicketPart *t,
 			   size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_EncTicketPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncTicketPart (krb5_context context,
 			   void *data,
 			   size_t length,
 			   EncTicketPart *t,
 			   size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_EncTicketPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncASRepPart (krb5_context context,
 			  const void *data,
 			  size_t length,
 			  EncASRepPart *t,
 			  size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_EncASRepPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncASRepPart (krb5_context context,
 			  void *data,
 			  size_t length,
 			  EncASRepPart *t,
 			  size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_EncASRepPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncTGSRepPart (krb5_context context,
 			   const void *data,
 			   size_t length,
 			   EncTGSRepPart *t,
 			   size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_EncTGSRepPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncTGSRepPart (krb5_context context,
 			   void *data,
 			   size_t length,
 			   EncTGSRepPart *t,
 			   size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_EncTGSRepPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncAPRepPart (krb5_context context,
 			  const void *data,
 			  size_t length,
 			  EncAPRepPart *t,
 			  size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_EncAPRepPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncAPRepPart (krb5_context context,
 			  void *data,
 			  size_t length,
 			  EncAPRepPart *t,
 			  size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_EncAPRepPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_Authenticator (krb5_context context,
 			   const void *data,
 			   size_t length,
 			   Authenticator *t,
 			   size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_Authenticator(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_Authenticator (krb5_context context,
 			   void *data,
 			   size_t length,
 			   Authenticator *t,
 			   size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_Authenticator(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncKrbCredPart (krb5_context context,
 			    const void *data,
 			    size_t length,
 			    EncKrbCredPart *t,
 			    size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_EncKrbCredPart(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncKrbCredPart (krb5_context context,
 			    void *data,
 			    size_t length,
 			    EncKrbCredPart *t,
 			    size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_EncKrbCredPart (data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_ETYPE_INFO (krb5_context context,
 			const void *data,
 			size_t length,
 			ETYPE_INFO *t,
 			size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_ETYPE_INFO(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_ETYPE_INFO (krb5_context context,
 			void *data,
 			size_t length,
 			ETYPE_INFO *t,
 			size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_ETYPE_INFO (data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_ETYPE_INFO2 (krb5_context context,
 			const void *data,
 			size_t length,
 			ETYPE_INFO2 *t,
 			size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return decode_ETYPE_INFO2(data, length, t, len);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_ETYPE_INFO2 (krb5_context context,
 			 void *data,
 			 size_t length,
 			 ETYPE_INFO2 *t,
 			 size_t *len)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     return encode_ETYPE_INFO2 (data, length, t, len);
 }
+
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/config_fi=
le.c
--- a/head/crypto/heimdal/lib/krb5/config_file.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/config_file.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,43 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-RCSID("$Id: config_file.c 19213 2006-12-04 23:36:36Z lha $");
=20
-#ifndef HAVE_NETINFO
+#ifdef __APPLE__
+#include <CoreFoundation/CoreFoundation.h>
+#endif
=20
 /* Gaah! I want a portable funopen */
 struct fileptr {
@@ -58,7 +61,7 @@
 	p =3D ptr->s + strcspn(ptr->s, "\n");
 	if(*p =3D=3D '\n')
 	    p++;
-	l =3D min(len, p - ptr->s);
+	l =3D min(len, (size_t)(p - ptr->s));
 	if(len > 0) {
 	    memcpy(str, ptr->s, l);
 	    str[l] =3D '\0';
@@ -70,23 +73,23 @@
=20
 static krb5_error_code parse_section(char *p, krb5_config_section **s,
 				     krb5_config_section **res,
-				     const char **error_message);
+				     const char **err_message);
 static krb5_error_code parse_binding(struct fileptr *f, unsigned *lineno, =
char *p,
 				     krb5_config_binding **b,
 				     krb5_config_binding **parent,
-				     const char **error_message);
+				     const char **err_message);
 static krb5_error_code parse_list(struct fileptr *f, unsigned *lineno,
 				  krb5_config_binding **parent,
-				  const char **error_message);
+				  const char **err_message);
=20
-static krb5_config_section *
-get_entry(krb5_config_section **parent, const char *name, int type)
+krb5_config_section *
+_krb5_config_get_entry(krb5_config_section **parent, const char *name, int=
 type)
 {
     krb5_config_section **q;
=20
     for(q =3D parent; *q !=3D NULL; q =3D &(*q)->next)
-	if(type =3D=3D krb5_config_list &&=20
-	   type =3D=3D (*q)->type &&
+	if(type =3D=3D krb5_config_list &&
+	   (unsigned)type =3D=3D (*q)->type &&
 	   strcmp(name, (*q)->name) =3D=3D 0)
 	    return *q;
     *q =3D calloc(1, sizeof(**q));
@@ -111,28 +114,28 @@
  *		a
  *	    }
  * ...
- *=20
+ *
  * starting at the line in `p', storing the resulting structure in
  * `s' and hooking it into `parent'.
- * Store the error message in `error_message'.
+ * Store the error message in `err_message'.
  */
=20
 static krb5_error_code
 parse_section(char *p, krb5_config_section **s, krb5_config_section **pare=
nt,
-	      const char **error_message)
+	      const char **err_message)
 {
     char *p1;
     krb5_config_section *tmp;
=20
     p1 =3D strchr (p + 1, ']');
     if (p1 =3D=3D NULL) {
-	*error_message =3D "missing ]";
+	*err_message =3D "missing ]";
 	return KRB5_CONFIG_BADFORMAT;
     }
     *p1 =3D '\0';
-    tmp =3D get_entry(parent, p + 1, krb5_config_list);
+    tmp =3D _krb5_config_get_entry(parent, p + 1, krb5_config_list);
     if(tmp =3D=3D NULL) {
-	*error_message =3D "out of memory";
+	*err_message =3D "out of memory";
 	return KRB5_CONFIG_BADFORMAT;
     }
     *s =3D tmp;
@@ -142,14 +145,14 @@
 /*
  * Parse a brace-enclosed list from `f', hooking in the structure at
  * `parent'.
- * Store the error message in `error_message'.
+ * Store the error message in `err_message'.
  */
=20
 static krb5_error_code
 parse_list(struct fileptr *f, unsigned *lineno, krb5_config_binding **pare=
nt,
-	   const char **error_message)
+	   const char **err_message)
 {
-    char buf[BUFSIZ];
+    char buf[KRB5_BUFSIZ];
     krb5_error_code ret;
     krb5_config_binding *b =3D NULL;
     unsigned beg_lineno =3D *lineno;
@@ -170,12 +173,12 @@
 	    return 0;
 	if (*p =3D=3D '\0')
 	    continue;
-	ret =3D parse_binding (f, lineno, p, &b, parent, error_message);
+	ret =3D parse_binding (f, lineno, p, &b, parent, err_message);
 	if (ret)
 	    return ret;
     }
     *lineno =3D beg_lineno;
-    *error_message =3D "unclosed {";
+    *err_message =3D "unclosed {";
     return KRB5_CONFIG_BADFORMAT;
 }
=20
@@ -186,7 +189,7 @@
 static krb5_error_code
 parse_binding(struct fileptr *f, unsigned *lineno, char *p,
 	      krb5_config_binding **b, krb5_config_binding **parent,
-	      const char **error_message)
+	      const char **err_message)
 {
     krb5_config_binding *tmp;
     char *p1, *p2;
@@ -196,14 +199,14 @@
     while (*p && *p !=3D '=3D' && !isspace((unsigned char)*p))
 	++p;
     if (*p =3D=3D '\0') {
-	*error_message =3D "missing =3D";
+	*err_message =3D "missing =3D";
 	return KRB5_CONFIG_BADFORMAT;
     }
     p2 =3D p;
     while (isspace((unsigned char)*p))
 	++p;
     if (*p !=3D '=3D') {
-	*error_message =3D "missing =3D";
+	*err_message =3D "missing =3D";
 	return KRB5_CONFIG_BADFORMAT;
     }
     ++p;
@@ -211,16 +214,16 @@
 	++p;
     *p2 =3D '\0';
     if (*p =3D=3D '{') {
-	tmp =3D get_entry(parent, p1, krb5_config_list);
+	tmp =3D _krb5_config_get_entry(parent, p1, krb5_config_list);
 	if (tmp =3D=3D NULL) {
-	    *error_message =3D "out of memory";
+	    *err_message =3D "out of memory";
 	    return KRB5_CONFIG_BADFORMAT;
 	}
-	ret =3D parse_list (f, lineno, &tmp->u.list, error_message);
+	ret =3D parse_list (f, lineno, &tmp->u.list, err_message);
     } else {
-	tmp =3D get_entry(parent, p1, krb5_config_string);
+	tmp =3D _krb5_config_get_entry(parent, p1, krb5_config_string);
 	if (tmp =3D=3D NULL) {
-	    *error_message =3D "out of memory";
+	    *err_message =3D "out of memory";
 	    return KRB5_CONFIG_BADFORMAT;
 	}
 	p1 =3D p;
@@ -234,20 +237,120 @@
     return ret;
 }
=20
+#if defined(__APPLE__)
+
+#if MAC_OS_X_VERSION_MIN_REQUIRED >=3D 1060
+#define HAVE_CFPROPERTYLISTCREATEWITHSTREAM 1
+#endif
+
+static char *
+cfstring2cstring(CFStringRef string)
+{
+    CFIndex len;
+    char *str;
+
+    str =3D (char *) CFStringGetCStringPtr(string, kCFStringEncodingUTF8);
+    if (str)
+	return strdup(str);
+
+    len =3D CFStringGetLength(string);
+    len =3D 1 + CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUT=
F8);
+    str =3D malloc(len);
+    if (str =3D=3D NULL)
+	return NULL;
+
+    if (!CFStringGetCString (string, str, len, kCFStringEncodingUTF8)) {
+	free (str);
+	return NULL;
+    }
+    return str;
+}
+
+static void
+convert_content(const void *key, const void *value, void *context)
+{
+    krb5_config_section *tmp, **parent =3D context;
+    char *k;
+
+    if (CFGetTypeID(key) !=3D CFStringGetTypeID())
+	return;
+
+    k =3D cfstring2cstring(key);
+    if (k =3D=3D NULL)
+	return;
+
+    if (CFGetTypeID(value) =3D=3D CFStringGetTypeID()) {
+	tmp =3D _krb5_config_get_entry(parent, k, krb5_config_string);
+	tmp->u.string =3D cfstring2cstring(value);
+    } else if (CFGetTypeID(value) =3D=3D CFDictionaryGetTypeID()) {
+	tmp =3D _krb5_config_get_entry(parent, k, krb5_config_list);
+	CFDictionaryApplyFunction(value, convert_content, &tmp->u.list);
+    } else {
+	/* log */
+    }
+    free(k);
+}
+
+static krb5_error_code
+parse_plist_config(krb5_context context, const char *path, krb5_config_sec=
tion **parent)
+{
+    CFReadStreamRef s;
+    CFDictionaryRef d;
+    CFURLRef url;
+
+    url =3D CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (=
UInt8 *)path, strlen(path), FALSE);
+    if (url =3D=3D NULL) {
+	krb5_clear_error_message(context);
+	return ENOMEM;
+    }
+
+    s =3D CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
+    CFRelease(url);
+    if (s =3D=3D NULL) {
+	krb5_clear_error_message(context);
+	return ENOMEM;
+    }
+
+    if (!CFReadStreamOpen(s)) {
+	CFRelease(s);
+	krb5_clear_error_message(context);
+	return ENOENT;
+    }
+
+#ifdef HAVE_CFPROPERTYLISTCREATEWITHSTREAM
+    d =3D (CFDictionaryRef)CFPropertyListCreateWithStream(NULL, s, 0, kCFP=
ropertyListImmutable, NULL, NULL);
+#else
+    d =3D (CFDictionaryRef)CFPropertyListCreateFromStream(NULL, s, 0, kCFP=
ropertyListImmutable, NULL, NULL);
+#endif
+    CFRelease(s);
+    if (d =3D=3D NULL) {
+	krb5_clear_error_message(context);
+	return ENOENT;
+    }
+
+    CFDictionaryApplyFunction(d, convert_content, parent);
+    CFRelease(d);
+
+    return 0;
+}
+
+#endif
+
+
 /*
  * Parse the config file `fname', generating the structures into `res'
- * returning error messages in `error_message'
+ * returning error messages in `err_message'
  */
=20
 static krb5_error_code
 krb5_config_parse_debug (struct fileptr *f,
 			 krb5_config_section **res,
 			 unsigned *lineno,
-			 const char **error_message)
+			 const char **err_message)
 {
     krb5_config_section *s =3D NULL;
     krb5_config_binding *b =3D NULL;
-    char buf[BUFSIZ];
+    char buf[KRB5_BUFSIZ];
     krb5_error_code ret;
=20
     while (config_fgets(buf, sizeof(buf), f) !=3D NULL) {
@@ -261,19 +364,19 @@
 	if (*p =3D=3D '#' || *p =3D=3D ';')
 	    continue;
 	if (*p =3D=3D '[') {
-	    ret =3D parse_section(p, &s, res, error_message);
-	    if (ret)=20
+	    ret =3D parse_section(p, &s, res, err_message);
+	    if (ret)
 		return ret;
 	    b =3D NULL;
 	} else if (*p =3D=3D '}') {
-	    *error_message =3D "unmatched }";
+	    *err_message =3D "unmatched }";
 	    return EINVAL;	/* XXX */
 	} else if(*p !=3D '\0') {
 	    if (s =3D=3D NULL) {
-		*error_message =3D "binding before section";
+		*err_message =3D "binding before section";
 		return EINVAL;
 	    }
-	    ret =3D parse_binding(f, lineno, p, &b, &s->u.list, error_message);
+	    ret =3D parse_binding(f, lineno, p, &b, &s->u.list, err_message);
 	    if (ret)
 		return ret;
 	}
@@ -281,53 +384,142 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_config_parse_string_multi(krb5_context context,
-			       const char *string,
-			       krb5_config_section **res)
+static int
+is_plist_file(const char *fname)
 {
-    const char *str;
-    unsigned lineno =3D 0;
-    krb5_error_code ret;
-    struct fileptr f;
-    f.f =3D NULL;
-    f.s =3D string;
-
-    ret =3D krb5_config_parse_debug (&f, res, &lineno, &str);
-    if (ret) {
-	krb5_set_error_string (context, "%s:%u: %s", "<constant>", lineno, str);
-	return ret;
-    }
-    return 0;
+    size_t len =3D strlen(fname);
+    char suffix[] =3D ".plist";
+    if (len < sizeof(suffix))
+	return 0;
+    if (strcasecmp(&fname[len - (sizeof(suffix) - 1)], suffix) !=3D 0)
+	return 0;
+    return 1;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Parse a configuration file and add the result into res. This
+ * interface can be used to parse several configuration files into one
+ * resulting krb5_config_section by calling it repeatably.
+ *
+ * @param context a Kerberos 5 context.
+ * @param fname a file name to a Kerberos configuration file
+ * @param res the returned result, must be free with krb5_free_config_file=
s().
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_config_parse_file_multi (krb5_context context,
 			      const char *fname,
 			      krb5_config_section **res)
 {
     const char *str;
+    char *newfname =3D NULL;
     unsigned lineno =3D 0;
     krb5_error_code ret;
     struct fileptr f;
-    f.f =3D fopen(fname, "r");
-    f.s =3D NULL;
-    if(f.f =3D=3D NULL) {
-	ret =3D errno;
-	krb5_set_error_string (context, "open %s: %s", fname, strerror(ret));
-	return ret;
+
+    /**
+     * If the fname starts with "~/" parse configuration file in the
+     * current users home directory. The behavior can be disabled and
+     * enabled by calling krb5_set_home_dir_access().
+     */
+    if (fname[0] =3D=3D '~' && fname[1] =3D=3D '/') {
+#ifndef KRB5_USE_PATH_TOKENS
+	const char *home =3D NULL;
+
+	if (!_krb5_homedir_access(context)) {
+	    krb5_set_error_message(context, EPERM,
+				   "Access to home directory not allowed");
+	    return EPERM;
+	}
+
+	if(!issuid())
+	    home =3D getenv("HOME");
+
+	if (home =3D=3D NULL) {
+	    struct passwd *pw =3D getpwuid(getuid());
+	    if(pw !=3D NULL)
+		home =3D pw->pw_dir;
+	}
+	if (home) {
+	    asprintf(&newfname, "%s%s", home, &fname[1]);
+	    if (newfname =3D=3D NULL) {
+		krb5_set_error_message(context, ENOMEM,
+				       N_("malloc: out of memory", ""));
+		return ENOMEM;
+	    }
+	    fname =3D newfname;
+	}
+#else  /* KRB5_USE_PATH_TOKENS */
+	if (asprintf(&newfname, "%%{USERCONFIG}%s", &fname[1]) < 0 ||
+	    newfname =3D=3D NULL)
+	{
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
+	    return ENOMEM;
+	}
+	fname =3D newfname;
+#endif
     }
=20
-    ret =3D krb5_config_parse_debug (&f, res, &lineno, &str);
-    fclose(f.f);
-    if (ret) {
-	krb5_set_error_string (context, "%s:%u: %s", fname, lineno, str);
-	return ret;
+    if (is_plist_file(fname)) {
+#ifdef __APPLE__
+	ret =3D parse_plist_config(context, fname, res);
+	if (ret) {
+	    krb5_set_error_message(context, ret,
+				   "Failed to parse plist %s", fname);
+	    if (newfname)
+		free(newfname);
+	    return ret;
+	}
+#else
+	krb5_set_error_message(context, ENOENT,
+			       "no support for plist configuration files");
+	return ENOENT;
+#endif
+    } else {
+#ifdef KRB5_USE_PATH_TOKENS
+	char * exp_fname =3D NULL;
+
+	ret =3D _krb5_expand_path_tokens(context, fname, &exp_fname);
+	if (ret) {
+	    if (newfname)
+		free(newfname);
+	    return ret;
+	}
+
+	if (newfname)
+	    free(newfname);
+	fname =3D newfname =3D exp_fname;
+#endif
+
+	f.f =3D fopen(fname, "r");
+	f.s =3D NULL;
+	if(f.f =3D=3D NULL) {
+	    ret =3D errno;
+	    krb5_set_error_message (context, ret, "open %s: %s",
+				    fname, strerror(ret));
+	    if (newfname)
+		free(newfname);
+	    return ret;
+	}
+
+	ret =3D krb5_config_parse_debug (&f, res, &lineno, &str);
+	fclose(f.f);
+	if (ret) {
+	    krb5_set_error_message (context, ret, "%s:%u: %s",
+				    fname, lineno, str);
+	    if (newfname)
+		free(newfname);
+	    return ret;
+	}
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_config_parse_file (krb5_context context,
 			const char *fname,
 			krb5_config_section **res)
@@ -336,8 +528,6 @@
     return krb5_config_parse_file_multi(context, fname, res);
 }
=20
-#endif /* !HAVE_NETINFO */
-
 static void
 free_binding (krb5_context context, krb5_config_binding *b)
 {
@@ -350,7 +540,7 @@
 	else if (b->type =3D=3D krb5_config_list)
 	    free_binding (context, b->u.list);
 	else
-	    krb5_abortx(context, "unknown binding type (%d) in free_binding",=20
+	    krb5_abortx(context, "unknown binding type (%d) in free_binding",
 			b->type);
 	next_b =3D b->next;
 	free (b);
@@ -358,25 +548,76 @@
     }
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Free configuration file section, the result of
+ * krb5_config_parse_file() and krb5_config_parse_file_multi().
+ *
+ * @param context A Kerberos 5 context
+ * @param s the configuration section to free
+ *
+ * @return returns 0 on successes, otherwise an error code, see
+ *          krb5_get_error_message()
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_config_file_free (krb5_context context, krb5_config_section *s)
 {
     free_binding (context, s);
     return 0;
 }
=20
-const void *
-krb5_config_get_next (krb5_context context,
-		      const krb5_config_section *c,
-		      const krb5_config_binding **pointer,
-		      int type,
-		      ...)
+#ifndef HEIMDAL_SMALLER
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_config_copy(krb5_context context,
+		  krb5_config_section *c,
+		  krb5_config_section **head)
+{
+    krb5_config_binding *d, *previous =3D NULL;
+
+    *head =3D NULL;
+
+    while (c) {
+	d =3D calloc(1, sizeof(*d));
+
+	if (*head =3D=3D NULL)
+	    *head =3D d;
+
+	d->name =3D strdup(c->name);
+	d->type =3D c->type;
+	if (d->type =3D=3D krb5_config_string)
+	    d->u.string =3D strdup(c->u.string);
+	else if (d->type =3D=3D krb5_config_list)
+	    _krb5_config_copy (context, c->u.list, &d->u.list);
+	else
+	    krb5_abortx(context,
+			"unknown binding type (%d) in krb5_config_copy",
+			d->type);
+	if (previous)
+	    previous->next =3D d;
+
+	previous =3D d;
+	c =3D c->next;
+    }
+    return 0;
+}
+
+#endif /* HEIMDAL_SMALLER */
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_get_next (krb5_context context,
+		       const krb5_config_section *c,
+		       const krb5_config_binding **pointer,
+		       int type,
+		       ...)
 {
     const char *ret;
     va_list args;
=20
     va_start(args, type);
-    ret =3D krb5_config_vget_next (context, c, pointer, type, args);
+    ret =3D _krb5_config_vget_next (context, c, pointer, type, args);
     va_end(args);
     return ret;
 }
@@ -392,7 +633,7 @@
     const char *p =3D va_arg(args, const char *);
     while(b !=3D NULL) {
 	if(strcmp(b->name, name) =3D=3D 0) {
-	    if(b->type =3D=3D type && p =3D=3D NULL) {
+	    if(b->type =3D=3D (unsigned)type && p =3D=3D NULL) {
 		*pointer =3D b;
 		return b->u.generic;
 	    } else if(b->type =3D=3D krb5_config_list && p !=3D NULL) {
@@ -404,12 +645,12 @@
     return NULL;
 }
=20
-const void *
-krb5_config_vget_next (krb5_context context,
-		       const krb5_config_section *c,
-		       const krb5_config_binding **pointer,
-		       int type,
-		       va_list args)
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_vget_next (krb5_context context,
+			const krb5_config_section *c,
+			const krb5_config_binding **pointer,
+			int type,
+			va_list args)
 {
     const krb5_config_binding *b;
     const char *p;
@@ -432,7 +673,7 @@
     /* we were called again, so just look for more entries with the
        same name and type */
     for (b =3D (*pointer)->next; b !=3D NULL; b =3D b->next) {
-	if(strcmp(b->name, (*pointer)->name) =3D=3D 0 && b->type =3D=3D type) {
+	if(strcmp(b->name, (*pointer)->name) =3D=3D 0 && b->type =3D=3D (unsigned=
)type) {
 	    *pointer =3D b;
 	    return b->u.generic;
 	}
@@ -440,33 +681,46 @@
     return NULL;
 }
=20
-const void *
-krb5_config_get (krb5_context context,
-		 const krb5_config_section *c,
-		 int type,
-		 ...)
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_get (krb5_context context,
+		  const krb5_config_section *c,
+		  int type,
+		  ...)
 {
     const void *ret;
     va_list args;
=20
     va_start(args, type);
-    ret =3D krb5_config_vget (context, c, type, args);
+    ret =3D _krb5_config_vget (context, c, type, args);
     va_end(args);
     return ret;
 }
=20
+
 const void *
-krb5_config_vget (krb5_context context,
-		  const krb5_config_section *c,
-		  int type,
-		  va_list args)
+_krb5_config_vget (krb5_context context,
+		   const krb5_config_section *c,
+		   int type,
+		   va_list args)
 {
     const krb5_config_binding *foo =3D NULL;
=20
-    return krb5_config_vget_next (context, c, &foo, type, args);
+    return _krb5_config_vget_next (context, c, &foo, type, args);
 }
=20
-const krb5_config_binding *
+/**
+ * Get a list of configuration binding list for more processing
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return NULL if configuration list is not found, a list otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL
 krb5_config_get_list (krb5_context context,
 		      const krb5_config_section *c,
 		      ...)
@@ -480,15 +734,42 @@
     return ret;
 }
=20
-const krb5_config_binding *
+/**
+ * Get a list of configuration binding list for more processing
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param args a va_list of arguments
+ *
+ * @return NULL if configuration list is not found, a list otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL
 krb5_config_vget_list (krb5_context context,
 		       const krb5_config_section *c,
 		       va_list args)
 {
-    return krb5_config_vget (context, c, krb5_config_list, args);
+    return _krb5_config_vget (context, c, krb5_config_list, args);
 }
=20
-const char* KRB5_LIB_FUNCTION
+/**
+ * Returns a "const char *" to a string in the configuration database.
+ * The string may not be valid after a reload of the configuration
+ * database so a caller should make a local copy if it needs to keep
+ * the string.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return NULL if configuration string not found, a string otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_get_string (krb5_context context,
 			const krb5_config_section *c,
 			...)
@@ -502,15 +783,42 @@
     return ret;
 }
=20
-const char* KRB5_LIB_FUNCTION
+/**
+ * Like krb5_config_get_string(), but uses a va_list instead of ...
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param args a va_list of arguments
+ *
+ * @return NULL if configuration string not found, a string otherwise
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_vget_string (krb5_context context,
 			 const krb5_config_section *c,
 			 va_list args)
 {
-    return krb5_config_vget (context, c, krb5_config_string, args);
+    return _krb5_config_vget (context, c, krb5_config_string, args);
 }
=20
-const char* KRB5_LIB_FUNCTION
+/**
+ * Like krb5_config_vget_string(), but instead of returning NULL,
+ * instead return a default value.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param def_value the default value to return if no configuration
+ *        found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return a configuration string
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_vget_string_default (krb5_context context,
 				 const krb5_config_section *c,
 				 const char *def_value,
@@ -524,7 +832,22 @@
     return ret;
 }
=20
-const char* KRB5_LIB_FUNCTION
+/**
+ * Like krb5_config_get_string(), but instead of returning NULL,
+ * instead return a default value.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param def_value the default value to return if no configuration
+ *        found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return a configuration string
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_get_string_default (krb5_context context,
 				const krb5_config_section *c,
 				const char *def_value,
@@ -539,7 +862,64 @@
     return ret;
 }
=20
-char ** KRB5_LIB_FUNCTION
+static char *
+next_component_string(char * begin, const char * delims, char **state)
+{
+    char * end;
+
+    if (begin =3D=3D NULL)
+        begin =3D *state;
+
+    if (*begin =3D=3D '\0')
+        return NULL;
+
+    end =3D begin;
+    while (*end =3D=3D '"') {
+        char * t =3D strchr(end + 1, '"');
+
+        if (t)
+            end =3D ++t;
+        else
+            end +=3D strlen(end);
+    }
+
+    if (*end !=3D '\0') {
+        size_t pos;
+
+        pos =3D strcspn(end, delims);
+        end =3D end + pos;
+    }
+
+    if (*end !=3D '\0') {
+        *end =3D '\0';
+        *state =3D end + 1;
+        if (*begin =3D=3D '"' && *(end - 1) =3D=3D '"' && begin + 1 < end)=
 {
+            begin++; *(end - 1) =3D '\0';
+        }
+        return begin;
+    }
+
+    *state =3D end;
+    if (*begin =3D=3D '"' && *(end - 1) =3D=3D '"' && begin + 1 < end) {
+        begin++; *(end - 1) =3D '\0';
+    }
+    return begin;
+}
+
+/**
+ * Get a list of configuration strings, free the result with
+ * krb5_config_free_strings().
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION char ** KRB5_LIB_CALL
 krb5_config_vget_strings(krb5_context context,
 			 const krb5_config_section *c,
 			 va_list args)
@@ -549,14 +929,14 @@
     const krb5_config_binding *b =3D NULL;
     const char *p;
=20
-    while((p =3D krb5_config_vget_next(context, c, &b,=20
-				     krb5_config_string, args))) {
+    while((p =3D _krb5_config_vget_next(context, c, &b,
+				      krb5_config_string, args))) {
 	char *tmp =3D strdup(p);
 	char *pos =3D NULL;
 	char *s;
 	if(tmp =3D=3D NULL)
 	    goto cleanup;
-	s =3D strtok_r(tmp, " \t", &pos);
+	s =3D next_component_string(tmp, " \t", &pos);
 	while(s){
 	    char **tmp2 =3D realloc(strings, (nstr + 1) * sizeof(*strings));
 	    if(tmp2 =3D=3D NULL)
@@ -566,7 +946,7 @@
 	    nstr++;
 	    if(strings[nstr-1] =3D=3D NULL)
 		goto cleanup;
-	    s =3D strtok_r(NULL, " \t", &pos);
+	    s =3D next_component_string(NULL, " \t", &pos);
 	}
 	free(tmp);
     }
@@ -586,7 +966,20 @@
=20
 }
=20
-char**
+/**
+ * Get a list of configuration strings, free the result with
+ * krb5_config_free_strings().
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION char** KRB5_LIB_CALL
 krb5_config_get_strings(krb5_context context,
 			const krb5_config_section *c,
 			...)
@@ -599,7 +992,16 @@
     return ret;
 }
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Free the resulting strings from krb5_config-get_strings() and
+ * krb5_config_vget_strings().
+ *
+ * @param strings strings to free
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_config_free_strings(char **strings)
 {
     char **s =3D strings;
@@ -610,7 +1012,25 @@
     free(strings);
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+/**
+ * Like krb5_config_get_bool_default() but with a va_list list of
+ * configuration selection.
+ *
+ * Configuration value to a boolean value, where yes/true and any
+ * non-zero number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param def_value the default value to return if no configuration
+ *        found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_vget_bool_default (krb5_context context,
 			       const krb5_config_section *c,
 			       krb5_boolean def_value,
@@ -626,7 +1046,21 @@
     return FALSE;
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+/**
+ * krb5_config_get_bool() will convert the configuration
+ * option value to a boolean value, where yes/true and any non-zero
+ * number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param args a va_list of arguments
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_vget_bool  (krb5_context context,
 			const krb5_config_section *c,
 			va_list args)
@@ -634,7 +1068,23 @@
     return krb5_config_vget_bool_default (context, c, FALSE, args);
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+/**
+ * krb5_config_get_bool_default() will convert the configuration
+ * option value to a boolean value, where yes/true and any non-zero
+ * number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param def_value the default value to return if no configuration
+ *        found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_get_bool_default (krb5_context context,
 			      const krb5_config_section *c,
 			      krb5_boolean def_value,
@@ -648,7 +1098,23 @@
     return ret;
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+/**
+ * Like krb5_config_get_bool() but with a va_list list of
+ * configuration selection.
+ *
+ * Configuration value to a boolean value, where yes/true and any
+ * non-zero number means TRUE and other value is FALSE.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return TRUE or FALSE
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_get_bool (krb5_context context,
 		      const krb5_config_section *c,
 		      ...)
@@ -661,7 +1127,24 @@
     return ret;
 }
=20
-int KRB5_LIB_FUNCTION
+/**
+ * Get the time from the configuration file using a relative time.
+ *
+ * Like krb5_config_get_time_default() but with a va_list list of
+ * configuration selection.
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param def_value the default value to return if no configuration
+ *        found in the database.
+ * @param args a va_list of arguments
+ *
+ * @return parsed the time (or def_value on parse error)
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_time_default (krb5_context context,
 			       const krb5_config_section *c,
 			       int def_value,
@@ -678,7 +1161,19 @@
     return t;
 }
=20
-int KRB5_LIB_FUNCTION
+/**
+ * Get the time from the configuration file using a relative time, for exa=
mple: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param args a va_list of arguments
+ *
+ * @return parsed the time or -1 on error
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_time  (krb5_context context,
 			const krb5_config_section *c,
 			va_list args)
@@ -686,7 +1181,21 @@
     return krb5_config_vget_time_default (context, c, -1, args);
 }
=20
-int KRB5_LIB_FUNCTION
+/**
+ * Get the time from the configuration file using a relative time, for exa=
mple: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param def_value the default value to return if no configuration
+ *        found in the database.
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return parsed the time (or def_value on parse error)
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_time_default (krb5_context context,
 			      const krb5_config_section *c,
 			      int def_value,
@@ -700,7 +1209,19 @@
     return ret;
 }
=20
-int KRB5_LIB_FUNCTION
+/**
+ * Get the time from the configuration file using a relative time, for exa=
mple: 1h30s
+ *
+ * @param context A Kerberos 5 context.
+ * @param c a configuration section, or NULL to use the section from conte=
xt
+ * @param ... a list of names, terminated with NULL.
+ *
+ * @return parsed the time or -1 on error
+ *
+ * @ingroup krb5_support
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_time (krb5_context context,
 		      const krb5_config_section *c,
 		      ...)
@@ -714,7 +1235,7 @@
 }
=20
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_int_default (krb5_context context,
 			      const krb5_config_section *c,
 			      int def_value,
@@ -724,18 +1245,18 @@
     str =3D krb5_config_vget_string (context, c, args);
     if(str =3D=3D NULL)
 	return def_value;
-    else {=20
-	char *endptr;=20
-	long l;=20
-	l =3D strtol(str, &endptr, 0);=20
-	if (endptr =3D=3D str)=20
-	    return def_value;=20
-	else=20
+    else {
+	char *endptr;
+	long l;
+	l =3D strtol(str, &endptr, 0);
+	if (endptr =3D=3D str)
+	    return def_value;
+	else
 	    return l;
     }
 }
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_int  (krb5_context context,
 		       const krb5_config_section *c,
 		       va_list args)
@@ -743,7 +1264,7 @@
     return krb5_config_vget_int_default (context, c, -1, args);
 }
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_int_default (krb5_context context,
 			     const krb5_config_section *c,
 			     int def_value,
@@ -757,7 +1278,7 @@
     return ret;
 }
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_int (krb5_context context,
 		     const krb5_config_section *c,
 		     ...)
@@ -769,3 +1290,36 @@
     va_end(ap);
     return ret;
 }
+
+
+#ifndef HEIMDAL_SMALLER
+
+/**
+ * Deprecated: configuration files are not strings
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_config_parse_string_multi(krb5_context context,
+			       const char *string,
+			       krb5_config_section **res)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+    const char *str;
+    unsigned lineno =3D 0;
+    krb5_error_code ret;
+    struct fileptr f;
+    f.f =3D NULL;
+    f.s =3D string;
+
+    ret =3D krb5_config_parse_debug (&f, res, &lineno, &str);
+    if (ret) {
+	krb5_set_error_message (context, ret, "%s:%u: %s",
+				"<constant>", lineno, str);
+	return ret;
+    }
+    return 0;
+}
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/constants=
.c
--- a/head/crypto/heimdal/lib/krb5/constants.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/constants.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,43 +1,61 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: constants.c 14253 2004-09-23 07:57:37Z joda $");
+KRB5_LIB_VARIABLE const char *krb5_config_file =3D
+#ifdef __APPLE__
+"~/Library/Preferences/com.apple.Kerberos.plist" PATH_SEP
+"/Library/Preferences/com.apple.Kerberos.plist" PATH_SEP
+"~/Library/Preferences/edu.mit.Kerberos" PATH_SEP
+"/Library/Preferences/edu.mit.Kerberos" PATH_SEP
+#endif	/* __APPLE__ */
+"~/.krb5/config" PATH_SEP
+SYSCONFDIR "/krb5.conf"
+#ifdef _WIN32
+PATH_SEP "%{COMMON_APPDATA}/Kerberos/krb5.conf"
+PATH_SEP "%{WINDOWS}/krb5.ini"
+#else
+PATH_SEP "/etc/krb5.conf"
+#endif
+;
=20
-const char *krb5_config_file =3D=20
-#ifdef __APPLE__
-"/Library/Preferences/edu.mit.Kerberos:"
-#endif
-SYSCONFDIR "/krb5.conf:/etc/krb5.conf";
-const char *krb5_defkeyname =3D KEYTAB_DEFAULT;
+KRB5_LIB_VARIABLE const char *krb5_defkeyname =3D KEYTAB_DEFAULT;
+
+KRB5_LIB_VARIABLE const char *krb5_cc_type_api =3D "API";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_file =3D "FILE";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_memory =3D "MEMORY";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_kcm =3D "KCM";
+KRB5_LIB_VARIABLE const char *krb5_cc_type_scc =3D "SCC";
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/context.c
--- a/head/crypto/heimdal/lib/krb5/context.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/context.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,42 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2010 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
+#include <assert.h>
 #include <com_err.h>
=20
-RCSID("$Id: context.c 22293 2007-12-14 05:25:59Z lha $");
-
 #define INIT_FIELD(C, T, E, D, F)					\
     (C)->E =3D krb5_config_get_ ## T ## _default ((C), NULL, (D), 	\
 						"libdefaults", F, NULL)
@@ -60,7 +61,7 @@
     char **etypes_str;
     krb5_enctype *etypes =3D NULL;
=20
-    etypes_str =3D krb5_config_get_strings(context, NULL, "libdefaults",=20
+    etypes_str =3D krb5_config_get_strings(context, NULL, "libdefaults",
 					 name, NULL);
     if(etypes_str){
 	int i, j, k;
@@ -68,7 +69,7 @@
 	etypes =3D malloc((i+1) * sizeof(*etypes));
 	if (etypes =3D=3D NULL) {
 	    krb5_config_free_strings (etypes_str);
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message (context, ENOMEM, N_("malloc: out of memory", =
""));
 	    return ENOMEM;
 	}
 	for(j =3D 0, k =3D 0; j < i; j++) {
@@ -81,7 +82,7 @@
 	}
 	etypes[k] =3D ETYPE_NULL;
 	krb5_config_free_strings(etypes_str);
-    }=20
+    }
     *ret_enctypes =3D etypes;
     return 0;
 }
@@ -95,6 +96,7 @@
 {
     krb5_error_code ret;
     const char * tmp;
+    char **s;
     krb5_enctype *tmptypes;
=20
     INIT_FIELD(context, time, max_skew, 5 * 60, "clockskew");
@@ -102,19 +104,49 @@
     INIT_FIELD(context, int, max_retries, 3, "max_retries");
=20
     INIT_FIELD(context, string, http_proxy, NULL, "http_proxy");
-   =20
+
+    ret =3D krb5_config_get_bool_default(context, NULL, FALSE,
+				       "libdefaults",
+				       "allow_weak_crypto", NULL);
+    if (ret) {
+	krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
+	krb5_enctype_enable(context, ETYPE_DES_CBC_MD4);
+	krb5_enctype_enable(context, ETYPE_DES_CBC_MD5);
+	krb5_enctype_enable(context, ETYPE_DES_CBC_NONE);
+	krb5_enctype_enable(context, ETYPE_DES_CFB64_NONE);
+	krb5_enctype_enable(context, ETYPE_DES_PCBC_NONE);
+    }
+
     ret =3D set_etypes (context, "default_etypes", &tmptypes);
     if(ret)
 	return ret;
     free(context->etypes);
     context->etypes =3D tmptypes;
-   =20
+
     ret =3D set_etypes (context, "default_etypes_des", &tmptypes);
     if(ret)
 	return ret;
     free(context->etypes_des);
     context->etypes_des =3D tmptypes;
=20
+    ret =3D set_etypes (context, "default_as_etypes", &tmptypes);
+    if(ret)
+	return ret;
+    free(context->as_etypes);
+    context->as_etypes =3D tmptypes;
+
+    ret =3D set_etypes (context, "default_tgs_etypes", &tmptypes);
+    if(ret)
+	return ret;
+    free(context->tgs_etypes);
+    context->tgs_etypes =3D tmptypes;
+
+    ret =3D set_etypes (context, "permitted_enctypes", &tmptypes);
+    if(ret)
+	return ret;
+    free(context->permitted_enctypes);
+    context->permitted_enctypes =3D tmptypes;
+
     /* default keytab name */
     tmp =3D NULL;
     if(!issuid())
@@ -122,27 +154,27 @@
     if(tmp !=3D NULL)
 	context->default_keytab =3D tmp;
     else
-	INIT_FIELD(context, string, default_keytab,=20
+	INIT_FIELD(context, string, default_keytab,
 		   KEYTAB_DEFAULT, "default_keytab_name");
=20
-    INIT_FIELD(context, string, default_keytab_modify,=20
+    INIT_FIELD(context, string, default_keytab_modify,
 	       NULL, "default_keytab_modify_name");
=20
-    INIT_FIELD(context, string, time_fmt,=20
+    INIT_FIELD(context, string, time_fmt,
 	       "%Y-%m-%dT%H:%M:%S", "time_format");
=20
-    INIT_FIELD(context, string, date_fmt,=20
+    INIT_FIELD(context, string, date_fmt,
 	       "%Y-%m-%d", "date_format");
=20
-    INIT_FIELD(context, bool, log_utc,=20
+    INIT_FIELD(context, bool, log_utc,
 	       FALSE, "log_utc");
=20
=20
-   =20
+
     /* init dns-proxy slime */
-    tmp =3D krb5_config_get_string(context, NULL, "libdefaults",=20
+    tmp =3D krb5_config_get_string(context, NULL, "libdefaults",
 				 "dns_proxy", NULL);
-    if(tmp)=20
+    if(tmp)
 	roken_gethostby_setup(context->http_proxy, tmp);
     krb5_free_host_realm (context, context->default_realms);
     context->default_realms =3D NULL;
@@ -152,9 +184,9 @@
 	char **adr, **a;
=20
 	krb5_set_extra_addresses(context, NULL);
-	adr =3D krb5_config_get_strings(context, NULL,=20
-				      "libdefaults",=20
-				      "extra_addresses",=20
+	adr =3D krb5_config_get_strings(context, NULL,
+				      "libdefaults",
+				      "extra_addresses",
 				      NULL);
 	memset(&addresses, 0, sizeof(addresses));
 	for(a =3D adr; a && *a; a++) {
@@ -167,9 +199,9 @@
 	krb5_config_free_strings(adr);
=20
 	krb5_set_ignore_addresses(context, NULL);
-	adr =3D krb5_config_get_strings(context, NULL,=20
-				      "libdefaults",=20
-				      "ignore_addresses",=20
+	adr =3D krb5_config_get_strings(context, NULL,
+				      "libdefaults",
+				      "ignore_addresses",
 				      NULL);
 	memset(&addresses, 0, sizeof(addresses));
 	for(a =3D adr; a && *a; a++) {
@@ -181,7 +213,7 @@
 	}
 	krb5_config_free_strings(adr);
     }
-   =20
+
     INIT_FIELD(context, bool, scan_interfaces, TRUE, "scan_interfaces");
     INIT_FIELD(context, int, fcache_vno, 0, "fcache_version");
     /* prefer dns_lookup_kdc over srv_lookup. */
@@ -192,9 +224,138 @@
     INIT_FLAG(context, flags, KRB5_CTX_F_CHECK_PAC, TRUE, "check_pac");
     context->default_cc_name =3D NULL;
     context->default_cc_name_set =3D 0;
+
+    s =3D krb5_config_get_strings(context, NULL, "logging", "krb5", NULL);
+    if(s) {
+	char **p;
+	krb5_initlog(context, "libkrb5", &context->debug_dest);
+	for(p =3D s; *p; p++)
+	    krb5_addlog_dest(context, context->debug_dest, *p);
+	krb5_config_free_strings(s);
+    }
+
+    tmp =3D krb5_config_get_string(context, NULL, "libdefaults",
+				 "check-rd-req-server", NULL);
+    if (tmp =3D=3D NULL && !issuid())
+	tmp =3D getenv("KRB5_CHECK_RD_REQ_SERVER");
+    if(tmp) {
+	if (strcasecmp(tmp, "ignore") =3D=3D 0)
+	    context->flags |=3D KRB5_CTX_F_RD_REQ_IGNORE;
+    }
+
     return 0;
 }
=20
+static krb5_error_code
+cc_ops_register(krb5_context context)
+{
+    context->cc_ops =3D NULL;
+    context->num_cc_ops =3D 0;
+
+#ifndef KCM_IS_API_CACHE
+    krb5_cc_register(context, &krb5_acc_ops, TRUE);
+#endif
+    krb5_cc_register(context, &krb5_fcc_ops, TRUE);
+    krb5_cc_register(context, &krb5_mcc_ops, TRUE);
+#ifdef HAVE_SCC
+    krb5_cc_register(context, &krb5_scc_ops, TRUE);
+#endif
+#ifdef HAVE_KCM
+#ifdef KCM_IS_API_CACHE
+    krb5_cc_register(context, &krb5_akcm_ops, TRUE);
+#endif
+    krb5_cc_register(context, &krb5_kcm_ops, TRUE);
+#endif
+    _krb5_load_ccache_plugins(context);
+    return 0;
+}
+
+static krb5_error_code
+cc_ops_copy(krb5_context context, const krb5_context src_context)
+{
+    const krb5_cc_ops **cc_ops;
+
+    context->cc_ops =3D NULL;
+    context->num_cc_ops =3D 0;
+
+    if (src_context->num_cc_ops =3D=3D 0)
+	return 0;
+
+    cc_ops =3D malloc(sizeof(cc_ops[0]) * src_context->num_cc_ops);
+    if (cc_ops =3D=3D NULL) {
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
+	return KRB5_CC_NOMEM;
+    }
+
+    memcpy(rk_UNCONST(cc_ops), src_context->cc_ops,
+	   sizeof(cc_ops[0]) * src_context->num_cc_ops);
+    context->cc_ops =3D cc_ops;
+    context->num_cc_ops =3D src_context->num_cc_ops;
+
+    return 0;
+}
+
+static krb5_error_code
+kt_ops_register(krb5_context context)
+{
+    context->num_kt_types =3D 0;
+    context->kt_types     =3D NULL;
+
+    krb5_kt_register (context, &krb5_fkt_ops);
+    krb5_kt_register (context, &krb5_wrfkt_ops);
+    krb5_kt_register (context, &krb5_javakt_ops);
+    krb5_kt_register (context, &krb5_mkt_ops);
+#ifndef HEIMDAL_SMALLER
+    krb5_kt_register (context, &krb5_akf_ops);
+#endif
+    krb5_kt_register (context, &krb5_any_ops);
+    return 0;
+}
+
+static krb5_error_code
+kt_ops_copy(krb5_context context, const krb5_context src_context)
+{
+    context->num_kt_types =3D 0;
+    context->kt_types     =3D NULL;
+
+    if (src_context->num_kt_types =3D=3D 0)
+	return 0;
+
+    context->kt_types =3D malloc(sizeof(context->kt_types[0]) * src_contex=
t->num_kt_types);
+    if (context->kt_types =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
+
+    context->num_kt_types =3D src_context->num_kt_types;
+    memcpy(context->kt_types, src_context->kt_types,
+	   sizeof(context->kt_types[0]) * src_context->num_kt_types);
+
+    return 0;
+}
+
+static const char *sysplugin_dirs[] =3D  {
+    LIBDIR "/plugin/krb5",
+#ifdef __APPLE__
+    "/Library/KerberosPlugins/KerberosFrameworkPlugins",
+    "/System/Library/KerberosPlugins/KerberosFrameworkPlugins",
+#endif
+    NULL
+};
+
+static void
+init_context_once(void *ctx)
+{
+    krb5_context context =3D ctx;
+
+    _krb5_load_plugins(context, "krb5", sysplugin_dirs);
+
+    bindtextdomain(HEIMDAL_TEXTDOMAIN, HEIMDAL_LOCALEDIR);
+}
+
+
 /**
  * Initializes the context structure and reads the configuration file
  * /etc/krb5.conf. The structure should be freed by calling
@@ -210,9 +371,10 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_init_context(krb5_context *context)
 {
+    static heim_base_once_t init_context =3D HEIM_BASE_ONCE_INIT;
     krb5_context p;
     krb5_error_code ret;
     char **files;
@@ -230,55 +392,181 @@
     }
     HEIMDAL_MUTEX_init(p->mutex);
=20
+    p->flags |=3D KRB5_CTX_F_HOMEDIR_ACCESS;
+
     ret =3D krb5_get_default_config_files(&files);
-    if(ret)=20
+    if(ret)
 	goto out;
     ret =3D krb5_set_config_files(p, files);
     krb5_free_config_files(files);
-    if(ret)=20
+    if(ret)
 	goto out;
=20
     /* init error tables */
     krb5_init_ets(p);
+    cc_ops_register(p);
+    kt_ops_register(p);
=20
-    p->cc_ops =3D NULL;
-    p->num_cc_ops =3D 0;
-    krb5_cc_register(p, &krb5_acc_ops, TRUE);
-    krb5_cc_register(p, &krb5_fcc_ops, TRUE);
-    krb5_cc_register(p, &krb5_mcc_ops, TRUE);
-#ifdef HAVE_KCM
-    krb5_cc_register(p, &krb5_kcm_ops, TRUE);
+#ifdef PKINIT
+    ret =3D hx509_context_init(&p->hx509ctx);
+    if (ret)
+	goto out;
 #endif
-
-    p->num_kt_types =3D 0;
-    p->kt_types     =3D NULL;
-    krb5_kt_register (p, &krb5_fkt_ops);
-    krb5_kt_register (p, &krb5_wrfkt_ops);
-    krb5_kt_register (p, &krb5_javakt_ops);
-    krb5_kt_register (p, &krb5_mkt_ops);
-    krb5_kt_register (p, &krb5_akf_ops);
-    krb5_kt_register (p, &krb4_fkt_ops);
-    krb5_kt_register (p, &krb5_srvtab_fkt_ops);
-    krb5_kt_register (p, &krb5_any_ops);
+    if (rk_SOCK_INIT())
+	p->flags |=3D KRB5_CTX_F_SOCKETS_INITIALIZED;
=20
 out:
     if(ret) {
 	krb5_free_context(p);
 	p =3D NULL;
+    } else {
+	heim_base_once_f(&init_context, p, init_context_once);
     }
     *context =3D p;
     return ret;
 }
=20
+#ifndef HEIMDAL_SMALLER
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_permitted_enctypes(krb5_context context,
+			    krb5_enctype **etypes)
+{
+    return krb5_get_default_in_tkt_etypes(context, KRB5_PDU_NONE, etypes);
+}
+
+/*
+ *
+ */
+
+static krb5_error_code
+copy_etypes (krb5_context context,
+	     krb5_enctype *enctypes,
+	     krb5_enctype **ret_enctypes)
+{
+    unsigned int i;
+
+    for (i =3D 0; enctypes[i]; i++)
+	;
+    i++;
+
+    *ret_enctypes =3D malloc(sizeof(ret_enctypes[0]) * i);
+    if (*ret_enctypes =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
+    memcpy(*ret_enctypes, enctypes, sizeof(ret_enctypes[0]) * i);
+    return 0;
+}
+
+/**
+ * Make a copy for the Kerberos 5 context, the new krb5_context shoud
+ * be freed with krb5_free_context().
+ *
+ * @param context the Kerberos context to copy
+ * @param out the copy of the Kerberos, set to NULL error.
+ *
+ * @return Returns 0 to indicate success.  Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_context(krb5_context context, krb5_context *out)
+{
+    krb5_error_code ret;
+    krb5_context p;
+
+    *out =3D NULL;
+
+    p =3D calloc(1, sizeof(*p));
+    if (p =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
+
+    p->mutex =3D malloc(sizeof(HEIMDAL_MUTEX));
+    if (p->mutex =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+	free(p);
+	return ENOMEM;
+    }
+    HEIMDAL_MUTEX_init(p->mutex);
+
+
+    if (context->default_cc_name)
+	p->default_cc_name =3D strdup(context->default_cc_name);
+    if (context->default_cc_name_env)
+	p->default_cc_name_env =3D strdup(context->default_cc_name_env);
+
+    if (context->etypes) {
+	ret =3D copy_etypes(context, context->etypes, &p->etypes);
+	if (ret)
+	    goto out;
+    }
+    if (context->etypes_des) {
+	ret =3D copy_etypes(context, context->etypes_des, &p->etypes_des);
+	if (ret)
+	    goto out;
+    }
+
+    if (context->default_realms) {
+	ret =3D krb5_copy_host_realm(context,
+				   context->default_realms, &p->default_realms);
+	if (ret)
+	    goto out;
+    }
+
+    ret =3D _krb5_config_copy(context, context->cf, &p->cf);
+    if (ret)
+	goto out;
+
+    /* XXX should copy */
+    krb5_init_ets(p);
+
+    cc_ops_copy(p, context);
+    kt_ops_copy(p, context);
+
+#if 0 /* XXX */
+    if(context->warn_dest !=3D NULL)
+	;
+    if(context->debug_dest !=3D NULL)
+	;
+#endif
+
+    ret =3D krb5_set_extra_addresses(p, context->extra_addresses);
+    if (ret)
+	goto out;
+    ret =3D krb5_set_extra_addresses(p, context->ignore_addresses);
+    if (ret)
+	goto out;
+
+    ret =3D _krb5_copy_send_to_kdc_func(p, context);
+    if (ret)
+	goto out;
+
+    *out =3D p;
+
+    return 0;
+
+ out:
+    krb5_free_context(p);
+    return ret;
+}
+
+#endif
+
 /**
  * Frees the krb5_context allocated by krb5_init_context().
  *
  * @param context context to be freed.
  *
- *  @ingroup krb5
-*/
+ * @ingroup krb5
+ */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_context(krb5_context context)
 {
     if (context->default_cc_name)
@@ -290,18 +578,28 @@
     krb5_free_host_realm (context, context->default_realms);
     krb5_config_file_free (context, context->cf);
     free_error_table (context->et_list);
-    free(context->cc_ops);
+    free(rk_UNCONST(context->cc_ops));
     free(context->kt_types);
-    krb5_clear_error_string(context);
+    krb5_clear_error_message(context);
     if(context->warn_dest !=3D NULL)
 	krb5_closelog(context, context->warn_dest);
+    if(context->debug_dest !=3D NULL)
+	krb5_closelog(context, context->debug_dest);
     krb5_set_extra_addresses(context, NULL);
     krb5_set_ignore_addresses(context, NULL);
     krb5_set_send_to_kdc_func(context, NULL, NULL);
-    if (context->mutex !=3D NULL) {
-	HEIMDAL_MUTEX_destroy(context->mutex);
-	free(context->mutex);
+
+#ifdef PKINIT
+    if (context->hx509ctx)
+	hx509_context_free(&context->hx509ctx);
+#endif
+
+    HEIMDAL_MUTEX_destroy(context->mutex);
+    free(context->mutex);
+    if (context->flags & KRB5_CTX_F_SOCKETS_INITIALIZED) {
+ 	rk_SOCK_EXIT();
     }
+
     memset(context, 0, sizeof(*context));
     free(context);
 }
@@ -318,14 +616,14 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_config_files(krb5_context context, char **filenames)
 {
     krb5_error_code ret;
     krb5_config_binding *tmp =3D NULL;
     while(filenames !=3D NULL && *filenames !=3D NULL && **filenames !=3D =
'\0') {
 	ret =3D krb5_config_parse_file_multi(context, *filenames, &tmp);
-	if(ret !=3D 0 && ret !=3D ENOENT && ret !=3D EACCES) {
+	if(ret !=3D 0 && ret !=3D ENOENT && ret !=3D EACCES && ret !=3D EPERM) {
 	    krb5_config_file_free(context, tmp);
 	    return ret;
 	}
@@ -337,6 +635,11 @@
     if(tmp =3D=3D NULL)
 	return ENXIO;
 #endif
+
+#ifdef _WIN32
+    _krb5_load_config_from_registry(context, &tmp);
+#endif
+
     krb5_config_file_free(context, context->cf);
     context->cf =3D tmp;
     ret =3D init_context_from_config_file(context);
@@ -373,7 +676,7 @@
  *  `pq' isn't free, it's up the the caller
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_prepend_config_files(const char *filelist, char **pq, char ***ret_pp)
 {
     krb5_error_code ret;
@@ -389,7 +692,7 @@
     while(1) {
 	ssize_t l;
 	q =3D p;
-	l =3D strsep_copy(&q, ":", NULL, 0);
+	l =3D strsep_copy(&q, PATH_SEP, NULL, 0);
 	if(l =3D=3D -1)
 	    break;
 	fn =3D malloc(l + 1);
@@ -397,7 +700,7 @@
 	    krb5_free_config_files(pp);
 	    return ENOMEM;
 	}
-	l =3D strsep_copy(&p, ":", fn, l + 1);
+	(void)strsep_copy(&p, PATH_SEP, fn, l + 1);
 	ret =3D add_file(&pp, &len, fn);
 	if (ret) {
 	    krb5_free_config_files(pp);
@@ -438,12 +741,12 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_prepend_config_files_default(const char *filelist, char ***pfilenames)
 {
     krb5_error_code ret;
     char **defpp, **pp =3D NULL;
-   =20
+
     ret =3D krb5_get_default_config_files(&defpp);
     if (ret)
 	return ret;
@@ -452,11 +755,50 @@
     krb5_free_config_files(defpp);
     if (ret) {
 	return ret;
-    }=09
+    }
     *pfilenames =3D pp;
     return 0;
 }
=20
+#ifdef _WIN32
+
+/**
+ * Checks the registry for configuration file location
+ *
+ * Kerberos for Windows and other legacy Kerberos applications expect
+ * to find the configuration file location in the
+ * SOFTWARE\MIT\Kerberos registry key under the value "config".
+ */
+char *
+_krb5_get_default_config_config_files_from_registry()
+{
+    static const char * KeyName =3D "Software\\MIT\\Kerberos";
+    char *config_file =3D NULL;
+    LONG rcode;
+    HKEY key;
+
+    rcode =3D RegOpenKeyEx(HKEY_CURRENT_USER, KeyName, 0, KEY_READ, &key);
+    if (rcode =3D=3D ERROR_SUCCESS) {
+        config_file =3D _krb5_parse_reg_value_as_multi_string(NULL, key, "=
config",
+                                                            REG_NONE, 0, P=
ATH_SEP);
+        RegCloseKey(key);
+    }
+
+    if (config_file)
+        return config_file;
+
+    rcode =3D RegOpenKeyEx(HKEY_LOCAL_MACHINE, KeyName, 0, KEY_READ, &key);
+    if (rcode =3D=3D ERROR_SUCCESS) {
+        config_file =3D _krb5_parse_reg_value_as_multi_string(NULL, key, "=
config",
+                                                            REG_NONE, 0, P=
ATH_SEP);
+        RegCloseKey(key);
+    }
+
+    return config_file;
+}
+
+#endif
+
 /**
  * Get the global configuration list.
  *
@@ -468,7 +810,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_config_files(char ***pfilenames)
 {
     const char *files =3D NULL;
@@ -477,6 +819,22 @@
         return EINVAL;
     if(!issuid())
 	files =3D getenv("KRB5_CONFIG");
+
+#ifdef _WIN32
+    if (files =3D=3D NULL) {
+        char * reg_files;
+        reg_files =3D _krb5_get_default_config_config_files_from_registry(=
);
+        if (reg_files !=3D NULL) {
+            krb5_error_code code;
+
+            code =3D krb5_prepend_config_files(reg_files, NULL, pfilenames=
);
+            free(reg_files);
+
+            return code;
+        }
+    }
+#endif
+
     if (files =3D=3D NULL)
 	files =3D krb5_config_file;
=20
@@ -486,7 +844,8 @@
 /**
  * Free a list of configuration files.
  *
- * @param filenames list to be freed.
+ * @param filenames list, terminated with a NULL pointer, to be
+ * freed. NULL is an valid argument.
  *
  * @return Returns 0 to indicate success. Otherwise an kerberos et
  * error code is returned, see krb5_get_error_message().
@@ -494,11 +853,11 @@
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_config_files(char **filenames)
 {
     char **p;
-    for(p =3D filenames; *p !=3D NULL; p++)
+    for(p =3D filenames; p && *p !=3D NULL; p++)
 	free(*p);
     free(filenames);
 }
@@ -516,7 +875,7 @@
  * @ingroup krb5
  */
=20
-const krb5_enctype * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const krb5_enctype * KRB5_LIB_CALL
 krb5_kerberos_enctypes(krb5_context context)
 {
     static const krb5_enctype p[] =3D {
@@ -534,34 +893,49 @@
 }
=20
 /*
+ *
+ */
+
+static krb5_error_code
+copy_enctypes(krb5_context context,
+	      const krb5_enctype *in,
+	      krb5_enctype **out)
+{
+    krb5_enctype *p =3D NULL;
+    size_t m, n;
+
+    for (n =3D 0; in[n]; n++)
+	;
+    n++;
+    ALLOC(p, n);
+    if(p =3D=3D NULL)
+	return krb5_enomem(context);
+    for (n =3D 0, m =3D 0; in[n]; n++) {
+	if (krb5_enctype_valid(context, in[n]) !=3D 0)
+	    continue;
+	p[m++] =3D in[n];
+    }
+    p[m] =3D KRB5_ENCTYPE_NULL;
+    if (m =3D=3D 0) {
+	free(p);
+	krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+				N_("no valid enctype set", ""));
+	return KRB5_PROG_ETYPE_NOSUPP;
+    }
+    *out =3D p;
+    return 0;
+}
+
+
+/*
  * set `etype' to a malloced list of the default enctypes
  */
=20
 static krb5_error_code
 default_etypes(krb5_context context, krb5_enctype **etype)
 {
-    const krb5_enctype *p;
-    krb5_enctype *e =3D NULL, *ep;
-    int i, n =3D 0;
-
-    p =3D krb5_kerberos_enctypes(context);
-
-    for (i =3D 0; p[i] !=3D ETYPE_NULL; i++) {
-	if (krb5_enctype_valid(context, p[i]) !=3D 0)
-	    continue;
-	ep =3D realloc(e, (n + 2) * sizeof(*e));
-	if (ep =3D=3D NULL) {
-	    free(e);
-	    krb5_set_error_string (context, "malloc: out of memory");
-	    return ENOMEM;
-	}
-	e =3D ep;
-	e[n] =3D p[i];
-	e[n + 1] =3D ETYPE_NULL;
-	n++;
-    }
-    *etype =3D e;
-    return 0;
+    const krb5_enctype *p =3D krb5_kerberos_enctypes(context);
+    return copy_enctypes(context, p, etype);
 }
=20
 /**
@@ -577,27 +951,17 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_set_default_in_tkt_etypes(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_default_in_tkt_etypes(krb5_context context,
 			       const krb5_enctype *etypes)
 {
+    krb5_error_code ret;
     krb5_enctype *p =3D NULL;
-    int i;
=20
     if(etypes) {
-	for (i =3D 0; etypes[i]; ++i) {
-	    krb5_error_code ret;
-	    ret =3D krb5_enctype_valid(context, etypes[i]);
-	    if (ret)
-		return ret;
-	}
-	++i;
-	ALLOC(p, i);
-	if(!p) {
-	    krb5_set_error_string (context, "malloc: out of memory");
-	    return ENOMEM;
-	}
-	memmove(p, etypes, i * sizeof(krb5_enctype));
+	ret =3D copy_enctypes(context, etypes, &p);
+	if (ret)
+	    return ret;
     }
     if(context->etypes)
 	free(context->etypes);
@@ -619,75 +983,69 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_in_tkt_etypes(krb5_context context,
+			       krb5_pdu pdu_type,
 			       krb5_enctype **etypes)
 {
-  krb5_enctype *p;
-  int i;
-  krb5_error_code ret;
+    krb5_enctype *enctypes =3D NULL;
+    krb5_error_code ret;
+    krb5_enctype *p;
=20
-  if(context->etypes) {
-    for(i =3D 0; context->etypes[i]; i++);
-    ++i;
-    ALLOC(p, i);
-    if(!p) {
-      krb5_set_error_string (context, "malloc: out of memory");
-      return ENOMEM;
+    heim_assert(pdu_type =3D=3D KRB5_PDU_AS_REQUEST ||=20
+		pdu_type =3D=3D KRB5_PDU_TGS_REQUEST ||
+		pdu_type =3D=3D KRB5_PDU_NONE, "pdu contant not as expected");
+
+    if (pdu_type =3D=3D KRB5_PDU_AS_REQUEST && context->as_etypes !=3D NUL=
L)
+	enctypes =3D context->as_etypes;
+    else if (pdu_type =3D=3D KRB5_PDU_TGS_REQUEST && context->tgs_etypes !=
=3D NULL)
+	enctypes =3D context->tgs_etypes;
+    else if (context->etypes !=3D NULL)
+	enctypes =3D context->etypes;
+
+    if (enctypes !=3D NULL) {
+	ret =3D copy_enctypes(context, enctypes, &p);
+	if (ret)
+	    return ret;
+    } else {
+	ret =3D default_etypes(context, &p);
+	if (ret)
+	    return ret;
     }
-    memmove(p, context->etypes, i * sizeof(krb5_enctype));
-  } else {
-    ret =3D default_etypes(context, &p);
-    if (ret)
-      return ret;
-  }
-  *etypes =3D p;
-  return 0;
+    *etypes =3D p;
+    return 0;
 }
=20
 /**
- * Return the error string for the error code. The caller must not
- * free the string.
- *
- * @param context Kerberos 5 context.
- * @param code Kerberos error code.
- *
- * @return the error message matching code
- *
- * @ingroup krb5
- */
-
-const char* KRB5_LIB_FUNCTION
-krb5_get_err_text(krb5_context context, krb5_error_code code)
-{
-    const char *p =3D NULL;
-    if(context !=3D NULL)
-	p =3D com_right(context->et_list, code);
-    if(p =3D=3D NULL)
-	p =3D strerror(code);
-    if (p =3D=3D NULL)
-	p =3D "Unknown error";
-    return p;
-}
-
-/**
- * Init the built-in ets in the Kerberos library.=20
+ * Init the built-in ets in the Kerberos library.
  *
  * @param context kerberos context to add the ets too
  *
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_init_ets(krb5_context context)
 {
     if(context->et_list =3D=3D NULL){
 	krb5_add_et_list(context, initialize_krb5_error_table_r);
 	krb5_add_et_list(context, initialize_asn1_error_table_r);
 	krb5_add_et_list(context, initialize_heim_error_table_r);
+
 	krb5_add_et_list(context, initialize_k524_error_table_r);
+
+#ifdef COM_ERR_BINDDOMAIN_krb5
+	bindtextdomain(COM_ERR_BINDDOMAIN_krb5, HEIMDAL_LOCALEDIR);
+	bindtextdomain(COM_ERR_BINDDOMAIN_asn1, HEIMDAL_LOCALEDIR);
+	bindtextdomain(COM_ERR_BINDDOMAIN_heim, HEIMDAL_LOCALEDIR);
+	bindtextdomain(COM_ERR_BINDDOMAIN_k524, HEIMDAL_LOCALEDIR);
+#endif
+
 #ifdef PKINIT
 	krb5_add_et_list(context, initialize_hx_error_table_r);
+#ifdef COM_ERR_BINDDOMAIN_hx
+	bindtextdomain(COM_ERR_BINDDOMAIN_hx, HEIMDAL_LOCALEDIR);
+#endif
 #endif
     }
 }
@@ -701,7 +1059,7 @@
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_set_use_admin_kdc (krb5_context context, krb5_boolean flag)
 {
     context->use_admin_kdc =3D flag;
@@ -717,7 +1075,7 @@
  * @ingroup krb5
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_get_use_admin_kdc (krb5_context context)
 {
     return context->use_admin_kdc;
@@ -736,12 +1094,12 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_add_extra_addresses(krb5_context context, krb5_addresses *addresses)
 {
=20
     if(context->extra_addresses)
-	return krb5_append_addresses(context,=20
+	return krb5_append_addresses(context,
 				     context->extra_addresses, addresses);
     else
 	return krb5_set_extra_addresses(context, addresses);
@@ -760,7 +1118,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_extra_addresses(krb5_context context, const krb5_addresses *addre=
sses)
 {
     if(context->extra_addresses)
@@ -776,7 +1134,7 @@
     if(context->extra_addresses =3D=3D NULL) {
 	context->extra_addresses =3D malloc(sizeof(*context->extra_addresses));
 	if(context->extra_addresses =3D=3D NULL) {
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message (context, ENOMEM, N_("malloc: out of memory", =
""));
 	    return ENOMEM;
 	}
     }
@@ -796,7 +1154,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_extra_addresses(krb5_context context, krb5_addresses *addresses)
 {
     if(context->extra_addresses =3D=3D NULL) {
@@ -819,12 +1177,12 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_add_ignore_addresses(krb5_context context, krb5_addresses *addresses)
 {
=20
     if(context->ignore_addresses)
-	return krb5_append_addresses(context,=20
+	return krb5_append_addresses(context,
 				     context->ignore_addresses, addresses);
     else
 	return krb5_set_ignore_addresses(context, addresses);
@@ -843,7 +1201,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_ignore_addresses(krb5_context context, const krb5_addresses *addr=
esses)
 {
     if(context->ignore_addresses)
@@ -858,7 +1216,7 @@
     if(context->ignore_addresses =3D=3D NULL) {
 	context->ignore_addresses =3D malloc(sizeof(*context->ignore_addresses));
 	if(context->ignore_addresses =3D=3D NULL) {
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message (context, ENOMEM, N_("malloc: out of memory", =
""));
 	    return ENOMEM;
 	}
     }
@@ -878,7 +1236,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_ignore_addresses(krb5_context context, krb5_addresses *addresses)
 {
     if(context->ignore_addresses =3D=3D NULL) {
@@ -900,7 +1258,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_fcache_version(krb5_context context, int version)
 {
     context->fcache_vno =3D version;
@@ -919,7 +1277,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_fcache_version(krb5_context context, int *version)
 {
     *version =3D context->fcache_vno;
@@ -935,7 +1293,7 @@
  */
=20
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_is_thread_safe(void)
 {
 #ifdef ENABLE_PTHREAD_SUPPORT
@@ -954,7 +1312,7 @@
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_set_dns_canonicalize_hostname (krb5_context context, krb5_boolean fla=
g)
 {
     if (flag)
@@ -973,7 +1331,7 @@
  * @ingroup krb5
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_get_dns_canonicalize_hostname (krb5_context context)
 {
     return (context->flags & KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME) ? 1 : 0;
@@ -986,12 +1344,12 @@
  * @param sec seconds part of offset.
  * @param usec micro seconds part of offset.
  *
- * @return return non zero if the library uses DNS to canonicalize hostnam=
es.
+ * @return returns zero
  *
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_kdc_sec_offset (krb5_context context, int32_t *sec, int32_t *usec)
 {
     if (sec)
@@ -1002,6 +1360,27 @@
 }
=20
 /**
+ * Set current offset in time to the KDC.
+ *
+ * @param context Kerberos 5 context.
+ * @param sec seconds part of offset.
+ * @param usec micro seconds part of offset.
+ *
+ * @return returns zero
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_kdc_sec_offset (krb5_context context, int32_t sec, int32_t usec)
+{
+    context->kdc_sec_offset =3D sec;
+    if (usec >=3D 0)
+	context->kdc_usec_offset =3D usec;
+    return 0;
+}
+
+/**
  * Get max time skew allowed.
  *
  * @param context Kerberos 5 context.
@@ -1011,7 +1390,7 @@
  * @ingroup krb5
  */
=20
-time_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
 krb5_get_max_time_skew (krb5_context context)
 {
     return context->max_skew;
@@ -1026,8 +1405,112 @@
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_set_max_time_skew (krb5_context context, time_t t)
 {
     context->max_skew =3D t;
 }
+
+/*
+ * Init encryption types in len, val with etypes.
+ *
+ * @param context Kerberos 5 context.
+ * @param pdu_type type of pdu
+ * @param len output length of val.
+ * @param val output array of enctypes.
+ * @param etypes etypes to set val and len to, if NULL, use default enctyp=
es.
+
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_init_etype(krb5_context context,
+		 krb5_pdu pdu_type,
+		 unsigned *len,
+		 krb5_enctype **val,
+		 const krb5_enctype *etypes)
+{
+    krb5_error_code ret;
+
+    if (etypes =3D=3D NULL)
+	ret =3D krb5_get_default_in_tkt_etypes(context, pdu_type, val);
+    else
+	ret =3D copy_enctypes(context, etypes, val);
+    if (ret)
+	return ret;
+
+    if (len) {
+	*len =3D 0;
+	while ((*val)[*len] !=3D KRB5_ENCTYPE_NULL)
+	    (*len)++;
+    }
+    return 0;
+}
+
+/*
+ * Allow homedir accces
+ */
+
+static HEIMDAL_MUTEX homedir_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
+static krb5_boolean allow_homedir =3D TRUE;
+
+krb5_boolean
+_krb5_homedir_access(krb5_context context)
+{
+    krb5_boolean allow;
+
+#ifdef HAVE_GETEUID
+    /* is never allowed for root */
+    if (geteuid() =3D=3D 0)
+	return FALSE;
+#endif
+
+    if (context && (context->flags & KRB5_CTX_F_HOMEDIR_ACCESS) =3D=3D 0)
+	return FALSE;
+
+    HEIMDAL_MUTEX_lock(&homedir_mutex);
+    allow =3D allow_homedir;
+    HEIMDAL_MUTEX_unlock(&homedir_mutex);
+    return allow;
+}
+
+/**
+ * Enable and disable home directory access on either the global state
+ * or the krb5_context state. By calling krb5_set_home_dir_access()
+ * with context set to NULL, the global state is configured otherwise
+ * the state for the krb5_context is modified.
+ *
+ * For home directory access to be allowed, both the global state and
+ * the krb5_context state have to be allowed.
+ *
+ * Administrator (root user), never uses the home directory.
+ *
+ * @param context a Kerberos 5 context or NULL
+ * @param allow allow if TRUE home directory
+ * @return the old value
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_set_home_dir_access(krb5_context context, krb5_boolean allow)
+{
+    krb5_boolean old;
+    if (context) {
+	old =3D (context->flags & KRB5_CTX_F_HOMEDIR_ACCESS) ? TRUE : FALSE;
+	if (allow)
+	    context->flags |=3D KRB5_CTX_F_HOMEDIR_ACCESS;
+	else
+	    context->flags &=3D ~KRB5_CTX_F_HOMEDIR_ACCESS;
+    } else {
+	HEIMDAL_MUTEX_lock(&homedir_mutex);
+	old =3D allow_homedir;
+	allow_homedir =3D allow;
+	HEIMDAL_MUTEX_unlock(&homedir_mutex);
+    }
+
+    return old;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/convert_c=
reds.c
--- a/head/crypto/heimdal/lib/krb5/convert_creds.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/convert_creds.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,46 +1,40 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-RCSID("$Id: convert_creds.c 22050 2007-11-11 11:20:46Z lha $");
-
 #include "krb5-v4compat.h"
=20
-static krb5_error_code
-check_ticket_flags(TicketFlags f)
-{
-    return 0; /* maybe add some more tests here? */
-}
+#ifndef HEIMDAL_SMALLER
=20
 /**
  * Convert the v5 credentials in in_cred to v4-dito in v4creds.  This
@@ -58,90 +52,16 @@
  * @ingroup krb5_v4compat
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb524_convert_creds_kdc(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb524_convert_creds_kdc(krb5_context context,
 			 krb5_creds *in_cred,
 			 struct credentials *v4creds)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
-    krb5_error_code ret;
-    krb5_data reply;
-    krb5_storage *sp;
-    int32_t tmp;
-    krb5_data ticket;
-    char realm[REALM_SZ];
-    krb5_creds *v5_creds =3D in_cred;
-
-    ret =3D check_ticket_flags(v5_creds->flags.b);
-    if(ret)
-	goto out2;
-
-    {
-	krb5_krbhst_handle handle;
-
-	ret =3D krb5_krbhst_init(context,
-			       krb5_principal_get_realm(context,=20
-							v5_creds->server),
-			       KRB5_KRBHST_KRB524,
-			       &handle);
-	if (ret)
-	    goto out2;
-
-	ret =3D krb5_sendto (context,
-			   &v5_creds->ticket,
-			   handle,
-			   &reply);
-	krb5_krbhst_free(context, handle);
-	if (ret)
-	    goto out2;
-    }
-    sp =3D krb5_storage_from_mem(reply.data, reply.length);
-    if(sp =3D=3D NULL) {
-	ret =3D ENOMEM;
-	krb5_set_error_string (context, "malloc: out of memory");
-	goto out2;
-    }
-    krb5_ret_int32(sp, &tmp);
-    ret =3D tmp;
-    if(ret =3D=3D 0) {
-	memset(v4creds, 0, sizeof(*v4creds));
-	ret =3D krb5_ret_int32(sp, &tmp);
-	if(ret)
-	    goto out;
-	v4creds->kvno =3D tmp;
-	ret =3D krb5_ret_data(sp, &ticket);
-	if(ret)
-	    goto out;
-	v4creds->ticket_st.length =3D ticket.length;
-	memcpy(v4creds->ticket_st.dat, ticket.data, ticket.length);
-	krb5_data_free(&ticket);
-	ret =3D krb5_524_conv_principal(context,=20
-				      v5_creds->server,=20
-				      v4creds->service,=20
-				      v4creds->instance,=20
-				      v4creds->realm);
-	if(ret)
-	    goto out;
-	v4creds->issue_date =3D v5_creds->times.starttime;
-	v4creds->lifetime =3D _krb5_krb_time_to_life(v4creds->issue_date,
-						   v5_creds->times.endtime);
-	ret =3D krb5_524_conv_principal(context, v5_creds->client,=20
-				      v4creds->pname,=20
-				      v4creds->pinst,=20
-				      realm);
-	if(ret)
-	    goto out;
-	memcpy(v4creds->session, v5_creds->session.keyvalue.data, 8);
-    } else {
-	krb5_set_error_string(context, "converting credentials: %s",=20
-			      krb5_get_err_text(context, ret));
-    }
-out:
-    krb5_storage_free(sp);
-    krb5_data_free(&reply);
-out2:
-    if (v5_creds !=3D in_cred)
-	krb5_free_creds (context, v5_creds);
-    return ret;
+    memset(v4creds, 0, sizeof(*v4creds));
+    krb5_set_error_message(context, EINVAL,
+			   N_("krb524_convert_creds_kdc not supported", ""));
+    return EINVAL;
 }
=20
 /**
@@ -159,46 +79,17 @@
  * @ingroup krb5_v4compat
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb524_convert_creds_kdc_ccache(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb524_convert_creds_kdc_ccache(krb5_context context,
 				krb5_ccache ccache,
 				krb5_creds *in_cred,
 				struct credentials *v4creds)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
-    krb5_error_code ret;
-    krb5_creds *v5_creds =3D in_cred;
-    krb5_keytype keytype;
+    memset(v4creds, 0, sizeof(*v4creds));
+    krb5_set_error_message(context, EINVAL,
+			   N_("krb524_convert_creds_kdc_ccache not supported", ""));
+    return EINVAL;
+}
=20
-    keytype =3D v5_creds->session.keytype;
-
-    if (keytype !=3D ENCTYPE_DES_CBC_CRC) {
-	/* MIT krb524d doesn't like nothing but des-cbc-crc tickets,
-           so go get one */
-	krb5_creds template;
-
-	memset (&template, 0, sizeof(template));
-	template.session.keytype =3D ENCTYPE_DES_CBC_CRC;
-	ret =3D krb5_copy_principal (context, in_cred->client, &template.client);
-	if (ret) {
-	    krb5_free_cred_contents (context, &template);
-	    return ret;
-	}
-	ret =3D krb5_copy_principal (context, in_cred->server, &template.server);
-	if (ret) {
-	    krb5_free_cred_contents (context, &template);
-	    return ret;
-	}
-
-	ret =3D krb5_get_credentials (context, 0, ccache,
-				    &template, &v5_creds);
-	krb5_free_cred_contents (context, &template);
-	if (ret)
-	    return ret;
-    }
-
-    ret =3D krb524_convert_creds_kdc(context, v5_creds, v4creds);
-
-    if (v5_creds !=3D in_cred)
-	krb5_free_creds (context, v5_creds);
-    return ret;
-}
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/copy_host=
_realm.c
--- a/head/crypto/heimdal/lib/krb5/copy_host_realm.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/copy_host_realm.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: copy_host_realm.c 22057 2007-11-11 15:13:13Z lha $");
-
 /**
  * Copy the list of realms from `from' to `to'.
  *
@@ -48,29 +46,30 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_host_realm(krb5_context context,
 		     const krb5_realm *from,
 		     krb5_realm **to)
 {
-    int n, i;
+    unsigned int n, i;
     const krb5_realm *p;
=20
-    for (n =3D 0, p =3D from; *p !=3D NULL; ++p)
+    for (n =3D 1, p =3D from; *p !=3D NULL; ++p)
 	++n;
-    ++n;
-    *to =3D malloc (n * sizeof(**to));
+
+    *to =3D calloc (n, sizeof(**to));
     if (*to =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message (context, ENOMEM,
+				N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
-    for (i =3D 0; i < n; ++i)
-	(*to)[i] =3D NULL;
+
     for (i =3D 0, p =3D from; *p !=3D NULL; ++p, ++i) {
 	(*to)[i] =3D strdup(*p);
 	if ((*to)[i] =3D=3D NULL) {
 	    krb5_free_host_realm (context, *to);
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message (context, ENOMEM,
+				    N_("malloc: out of memory", ""));
 	    return ENOMEM;
 	}
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/crc.c
--- a/head/crypto/heimdal/lib/krb5/crc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/crc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2000 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: crc.c 17442 2006-05-05 09:31:15Z lha $");
-
 static u_long table[256];
=20
 #define CRC_GEN 0xEDB88320L
@@ -44,8 +42,8 @@
 {
     static int flag =3D 0;
     unsigned long crc, poly;
-    int     i, j;
-   =20
+    unsigned int i, j;
+
     if(flag) return;
     poly =3D CRC_GEN;
     for (i =3D 0; i < 256; i++) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/creds.c
--- a/head/crypto/heimdal/lib/krb5/creds.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/creds.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,50 +1,38 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: creds.c 22062 2007-11-11 15:41:50Z lha $");
-
-#undef __attribute__
-#define __attribute__(X)
-
-/* keep this for compatibility with older code */
-krb5_error_code KRB5_LIB_FUNCTION __attribute__((deprecated))
-krb5_free_creds_contents (krb5_context context, krb5_creds *c)
-{
-    return krb5_free_cred_contents (context, c);
-}   =20
-
 /**
  * Free content of krb5_creds.
  *
@@ -57,7 +45,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_cred_contents (krb5_context context, krb5_creds *c)
 {
     krb5_free_principal (context, c->client);
@@ -86,7 +74,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_creds_contents (krb5_context context,
 			  const krb5_creds *incred,
 			  krb5_creds *c)
@@ -143,7 +131,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_creds (krb5_context context,
 		 const krb5_creds *incred,
 		 krb5_creds **outcred)
@@ -152,7 +140,8 @@
=20
     c =3D malloc (sizeof (*c));
     if (c =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message (context, ENOMEM,
+				N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memset (c, 0, sizeof(*c));
@@ -172,7 +161,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_creds (krb5_context context, krb5_creds *c)
 {
     krb5_free_cred_contents (context, c);
@@ -194,6 +183,18 @@
  * Return TRUE if `mcreds' and `creds' are equal (`whichfields'
  * determines what equal means).
  *
+ *
+ * The following flags, set in whichfields affects the comparison:
+ * - KRB5_TC_MATCH_SRV_NAMEONLY Consider all realms equal when comparing t=
he service principal.
+ * - KRB5_TC_MATCH_KEYTYPE Compare enctypes.
+ * - KRB5_TC_MATCH_FLAGS_EXACT Make sure that the ticket flags are identic=
al.
+ * - KRB5_TC_MATCH_FLAGS Make sure that all ticket flags set in mcreds are=
 also present in creds .
+ * - KRB5_TC_MATCH_TIMES_EXACT Compares the ticket times exactly.
+ * - KRB5_TC_MATCH_TIMES Compares only the expiration times of the creds.
+ * - KRB5_TC_MATCH_AUTHDATA Compares the authdata fields.
+ * - KRB5_TC_MATCH_2ND_TKT Compares the second tickets (used by user-to-us=
er authentication).
+ * - KRB5_TC_MATCH_IS_SKEY Compares the existance of the second ticket.
+ *
  * @param context Kerberos 5 context.
  * @param whichfields which fields to compare.
  * @param mcreds cred to compare with.
@@ -204,34 +205,32 @@
  * @ingroup krb5
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_compare_creds(krb5_context context, krb5_flags whichfields,
 		   const krb5_creds * mcreds, const krb5_creds * creds)
 {
     krb5_boolean match =3D TRUE;
-   =20
+
     if (match && mcreds->server) {
-	if (whichfields & (KRB5_TC_DONT_MATCH_REALM | KRB5_TC_MATCH_SRV_NAMEONLY)=
)=20
-	    match =3D krb5_principal_compare_any_realm (context, mcreds->server,=20
+	if (whichfields & (KRB5_TC_DONT_MATCH_REALM | KRB5_TC_MATCH_SRV_NAMEONLY))
+	    match =3D krb5_principal_compare_any_realm (context, mcreds->server,
 						      creds->server);
 	else
-	    match =3D krb5_principal_compare (context, mcreds->server,=20
+	    match =3D krb5_principal_compare (context, mcreds->server,
 					    creds->server);
     }
=20
     if (match && mcreds->client) {
 	if(whichfields & KRB5_TC_DONT_MATCH_REALM)
-	    match =3D krb5_principal_compare_any_realm (context, mcreds->client,=20
+	    match =3D krb5_principal_compare_any_realm (context, mcreds->client,
 						      creds->client);
 	else
-	    match =3D krb5_principal_compare (context, mcreds->client,=20
+	    match =3D krb5_principal_compare (context, mcreds->client,
 					    creds->client);
     }
-	   =20
+
     if (match && (whichfields & KRB5_TC_MATCH_KEYTYPE))
-	match =3D krb5_enctypes_compatible_keys(context,
-					      mcreds->session.keytype,
-					      creds->session.keytype);
+        match =3D mcreds->session.keytype =3D=3D creds->session.keytype;
=20
     if (match && (whichfields & KRB5_TC_MATCH_FLAGS_EXACT))
 	match =3D mcreds->flags.i =3D=3D creds->flags.i;
@@ -241,7 +240,7 @@
=20
     if (match && (whichfields & KRB5_TC_MATCH_TIMES_EXACT))
 	match =3D krb5_times_equal(&mcreds->times, &creds->times);
-   =20
+
     if (match && (whichfields & KRB5_TC_MATCH_TIMES))
 	/* compare only expiration times */
 	match =3D (mcreds->times.renew_till <=3D creds->times.renew_till) &&
@@ -253,7 +252,7 @@
 	    match =3D FALSE;
 	else
 	    for(i =3D 0; match && i < mcreds->authdata.len; i++)
-		match =3D (mcreds->authdata.val[i].ad_type =3D=3D=20
+		match =3D (mcreds->authdata.val[i].ad_type =3D=3D
 			 creds->authdata.val[i].ad_type) &&
 		    (krb5_data_cmp(&mcreds->authdata.val[i].ad_data,
 				   &creds->authdata.val[i].ad_data) =3D=3D 0);
@@ -262,8 +261,25 @@
 	match =3D (krb5_data_cmp(&mcreds->second_ticket, &creds->second_ticket) =
=3D=3D 0);
=20
     if (match && (whichfields & KRB5_TC_MATCH_IS_SKEY))
-	match =3D ((mcreds->second_ticket.length =3D=3D 0) =3D=3D=20
+	match =3D ((mcreds->second_ticket.length =3D=3D 0) =3D=3D
 		 (creds->second_ticket.length =3D=3D 0));
=20
     return match;
 }
+
+/**
+ * Returns the ticket flags for the credentials in creds.
+ * See also krb5_ticket_get_flags().
+ *
+ * @param creds credential to get ticket flags from
+ *
+ * @return ticket flags
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL
+krb5_creds_get_ticket_flags(krb5_creds *creds)
+{
+    return TicketFlags2int(creds->flags.b);
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/crypto.c
--- a/head/crypto/heimdal/lib/krb5/crypto.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/crypto.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,1135 +1,146 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-RCSID("$Id: crypto.c 22200 2007-12-07 13:48:01Z lha $");
-/* RCSID("$FreeBSD$"); */
=20
-#undef CRYPTO_DEBUG
-#ifdef CRYPTO_DEBUG
-static void krb5_crypto_debug(krb5_context, int, size_t, krb5_keyblock*);
+struct _krb5_key_usage {
+    unsigned usage;
+    struct _krb5_key_data key;
+};
+
+
+#ifndef HEIMDAL_SMALLER
+#define DES3_OLD_ENCTYPE 1
 #endif
=20
+static krb5_error_code _get_derived_key(krb5_context, krb5_crypto,
+					unsigned, struct _krb5_key_data**);
+static struct _krb5_key_data *_new_derived_key(krb5_crypto crypto, unsigne=
d usage);
=20
-struct key_data {
-    krb5_keyblock *key;
-    krb5_data *schedule;
-};
+static void free_key_schedule(krb5_context,
+			      struct _krb5_key_data *,
+			      struct _krb5_encryption_type *);
=20
-struct key_usage {
-    unsigned usage;
-    struct key_data key;
-};
-
-struct krb5_crypto_data {
-    struct encryption_type *et;
-    struct key_data key;
-    int num_key_usage;
-    struct key_usage *key_usage;
-};
-
-#define CRYPTO_ETYPE(C) ((C)->et->type)
-
-/* bits for `flags' below */
-#define F_KEYED		 1	/* checksum is keyed */
-#define F_CPROOF	 2	/* checksum is collision proof */
-#define F_DERIVED	 4	/* uses derived keys */
-#define F_VARIANT	 8	/* uses `variant' keys (6.4.3) */
-#define F_PSEUDO	16	/* not a real protocol type */
-#define F_SPECIAL	32	/* backwards */
-#define F_DISABLED	64	/* enctype/checksum disabled */
-
-struct salt_type {
-    krb5_salttype type;
-    const char *name;
-    krb5_error_code (*string_to_key)(krb5_context, krb5_enctype, krb5_data=
,=20
-				     krb5_salt, krb5_data, krb5_keyblock*);
-};
-
-struct key_type {
-    krb5_keytype type; /* XXX */
-    const char *name;
-    size_t bits;
-    size_t size;
-    size_t schedule_size;
-#if 0
-    krb5_enctype best_etype;
-#endif
-    void (*random_key)(krb5_context, krb5_keyblock*);
-    void (*schedule)(krb5_context, struct key_data *);
-    struct salt_type *string_to_key;
-    void (*random_to_key)(krb5_context, krb5_keyblock*, const void*, size_=
t);
-};
-
-struct checksum_type {
-    krb5_cksumtype type;
-    const char *name;
-    size_t blocksize;
-    size_t checksumsize;
-    unsigned flags;
-    void (*checksum)(krb5_context context,
-		     struct key_data *key,
-		     const void *buf, size_t len,
-		     unsigned usage,
-		     Checksum *csum);
-    krb5_error_code (*verify)(krb5_context context,
-			      struct key_data *key,
-			      const void *buf, size_t len,
-			      unsigned usage,
-			      Checksum *csum);
-};
-
-struct encryption_type {
-    krb5_enctype type;
-    const char *name;
-    heim_oid *oid;
-    size_t blocksize;
-    size_t padsize;
-    size_t confoundersize;
-    struct key_type *keytype;
-    struct checksum_type *checksum;
-    struct checksum_type *keyed_checksum;
-    unsigned flags;
-    krb5_error_code (*encrypt)(krb5_context context,
-			       struct key_data *key,
-			       void *data, size_t len,
-			       krb5_boolean encryptp,
-			       int usage,
-			       void *ivec);
-    size_t prf_length;
-    krb5_error_code (*prf)(krb5_context,
-			   krb5_crypto, const krb5_data *, krb5_data *);
-};
-
-#define ENCRYPTION_USAGE(U) (((U) << 8) | 0xAA)
-#define INTEGRITY_USAGE(U) (((U) << 8) | 0x55)
-#define CHECKSUM_USAGE(U) (((U) << 8) | 0x99)
-
-static struct checksum_type *_find_checksum(krb5_cksumtype type);
-static struct encryption_type *_find_enctype(krb5_enctype type);
-static struct key_type *_find_keytype(krb5_keytype type);
-static krb5_error_code _get_derived_key(krb5_context, krb5_crypto,=20
-					unsigned, struct key_data**);
-static struct key_data *_new_derived_key(krb5_crypto crypto, unsigned usag=
e);
-static krb5_error_code derive_key(krb5_context context,
-				  struct encryption_type *et,
-				  struct key_data *key,
-				  const void *constant,
-				  size_t len);
-static krb5_error_code hmac(krb5_context context,
-			    struct checksum_type *cm,=20
-			    const void *data,=20
-			    size_t len,=20
-			    unsigned usage,
-			    struct key_data *keyblock,
-			    Checksum *result);
-static void free_key_data(krb5_context context, struct key_data *key);
-static krb5_error_code usage2arcfour (krb5_context, unsigned *);
-static void xor (DES_cblock *, const unsigned char *);
-
-/************************************************************
- *                                                          *
- ************************************************************/
-
-static HEIMDAL_MUTEX crypto_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
-
-
-static void
-krb5_DES_random_key(krb5_context context,
-	       krb5_keyblock *key)
-{
-    DES_cblock *k =3D key->keyvalue.data;
-    do {
-	krb5_generate_random_block(k, sizeof(DES_cblock));
-	DES_set_odd_parity(k);
-    } while(DES_is_weak_key(k));
-}
-
-static void
-krb5_DES_schedule(krb5_context context,
-		  struct key_data *key)
-{
-    DES_set_key(key->key->keyvalue.data, key->schedule->data);
-}
-
-#ifdef ENABLE_AFS_STRING_TO_KEY
-
-/* This defines the Andrew string_to_key function.  It accepts a password
- * string as input and converts it via a one-way encryption algorithm to a=
 DES
- * encryption key.  It is compatible with the original Andrew authenticati=
on
- * service password database.
+/*=20
+ * Converts etype to a user readable string and sets as a side effect
+ * the krb5_error_message containing this string. Returns
+ * KRB5_PROG_ETYPE_NOSUPP in not the conversion of the etype failed in
+ * which case the error code of the etype convesion is returned.
  */
=20
-/*
- * Short passwords, i.e 8 characters or less.
- */
-static void
-krb5_DES_AFS3_CMU_string_to_key (krb5_data pw,
-			    krb5_data cell,
-			    DES_cblock *key)
+static krb5_error_code
+unsupported_enctype(krb5_context context, krb5_enctype etype)
 {
-    char  password[8+1];	/* crypt is limited to 8 chars anyway */
-    int   i;
-   =20
-    for(i =3D 0; i < 8; i++) {
-	char c =3D ((i < pw.length) ? ((char*)pw.data)[i] : 0) ^
-		 ((i < cell.length) ?
-		  tolower(((unsigned char*)cell.data)[i]) : 0);
-	password[i] =3D c ? c : 'X';
-    }
-    password[8] =3D '\0';
+    krb5_error_code ret;
+    char *name;
=20
-    memcpy(key, crypt(password, "p1") + 2, sizeof(DES_cblock));
+    ret =3D krb5_enctype_to_string(context, etype, &name);
+    if (ret)
+	return ret;
=20
-    /* parity is inserted into the LSB so left shift each byte up one
-       bit. This allows ascii characters with a zero MSB to retain as
-       much significance as possible. */
-    for (i =3D 0; i < sizeof(DES_cblock); i++)
-	((unsigned char*)key)[i] <<=3D 1;
-    DES_set_odd_parity (key);
-}
-
-/*
- * Long passwords, i.e 9 characters or more.
- */
-static void
-krb5_DES_AFS3_Transarc_string_to_key (krb5_data pw,
-				 krb5_data cell,
-				 DES_cblock *key)
-{
-    DES_key_schedule schedule;
-    DES_cblock temp_key;
-    DES_cblock ivec;
-    char password[512];
-    size_t passlen;
-
-    memcpy(password, pw.data, min(pw.length, sizeof(password)));
-    if(pw.length < sizeof(password)) {
-	int len =3D min(cell.length, sizeof(password) - pw.length);
-	int i;
-
-	memcpy(password + pw.length, cell.data, len);
-	for (i =3D pw.length; i < pw.length + len; ++i)
-	    password[i] =3D tolower((unsigned char)password[i]);
-    }
-    passlen =3D min(sizeof(password), pw.length + cell.length);
-    memcpy(&ivec, "kerberos", 8);
-    memcpy(&temp_key, "kerberos", 8);
-    DES_set_odd_parity (&temp_key);
-    DES_set_key (&temp_key, &schedule);
-    DES_cbc_cksum ((void*)password, &ivec, passlen, &schedule, &ivec);
-
-    memcpy(&temp_key, &ivec, 8);
-    DES_set_odd_parity (&temp_key);
-    DES_set_key (&temp_key, &schedule);
-    DES_cbc_cksum ((void*)password, key, passlen, &schedule, &ivec);
-    memset(&schedule, 0, sizeof(schedule));
-    memset(&temp_key, 0, sizeof(temp_key));
-    memset(&ivec, 0, sizeof(ivec));
-    memset(password, 0, sizeof(password));
-
-    DES_set_odd_parity (key);
-}
-
-static krb5_error_code
-DES_AFS3_string_to_key(krb5_context context,
-		       krb5_enctype enctype,
-		       krb5_data password,
-		       krb5_salt salt,
-		       krb5_data opaque,
-		       krb5_keyblock *key)
-{
-    DES_cblock tmp;
-    if(password.length > 8)
-	krb5_DES_AFS3_Transarc_string_to_key(password, salt.saltvalue, &tmp);
-    else
-	krb5_DES_AFS3_CMU_string_to_key(password, salt.saltvalue, &tmp);
-    key->keytype =3D enctype;
-    krb5_data_copy(&key->keyvalue, tmp, sizeof(tmp));
-    memset(&key, 0, sizeof(key));
-    return 0;
-}
-#endif /* ENABLE_AFS_STRING_TO_KEY */
-
-static void
-DES_string_to_key_int(unsigned char *data, size_t length, DES_cblock *key)
-{
-    DES_key_schedule schedule;
-    int i;
-    int reverse =3D 0;
-    unsigned char *p;
-
-    unsigned char swap[] =3D { 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe,=20
-			     0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf };
-    memset(key, 0, 8);
-   =20
-    p =3D (unsigned char*)key;
-    for (i =3D 0; i < length; i++) {
-	unsigned char tmp =3D data[i];
-	if (!reverse)
-	    *p++ ^=3D (tmp << 1);
-	else
-	    *--p ^=3D (swap[tmp & 0xf] << 4) | swap[(tmp & 0xf0) >> 4];
-	if((i % 8) =3D=3D 7)
-	    reverse =3D !reverse;
-    }
-    DES_set_odd_parity(key);
-    if(DES_is_weak_key(key))
-	(*key)[7] ^=3D 0xF0;
-    DES_set_key(key, &schedule);
-    DES_cbc_cksum((void*)data, key, length, &schedule, key);
-    memset(&schedule, 0, sizeof(schedule));
-    DES_set_odd_parity(key);
-    if(DES_is_weak_key(key))
-	(*key)[7] ^=3D 0xF0;
-}
-
-static krb5_error_code
-krb5_DES_string_to_key(krb5_context context,
-		  krb5_enctype enctype,
-		  krb5_data password,
-		  krb5_salt salt,
-		  krb5_data opaque,
-		  krb5_keyblock *key)
-{
-    unsigned char *s;
-    size_t len;
-    DES_cblock tmp;
-
-#ifdef ENABLE_AFS_STRING_TO_KEY
-    if (opaque.length =3D=3D 1) {
-	unsigned long v;
-	_krb5_get_int(opaque.data, &v, 1);
-	if (v =3D=3D 1)
-	    return DES_AFS3_string_to_key(context, enctype, password,
-					  salt, opaque, key);
-    }
-#endif
-
-    len =3D password.length + salt.saltvalue.length;
-    s =3D malloc(len);
-    if(len > 0 && s =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    memcpy(s, password.data, password.length);
-    memcpy(s + password.length, salt.saltvalue.data, salt.saltvalue.length=
);
-    DES_string_to_key_int(s, len, &tmp);
-    key->keytype =3D enctype;
-    krb5_data_copy(&key->keyvalue, tmp, sizeof(tmp));
-    memset(&tmp, 0, sizeof(tmp));
-    memset(s, 0, len);
-    free(s);
-    return 0;
-}
-
-static void
-krb5_DES_random_to_key(krb5_context context,
-		       krb5_keyblock *key,
-		       const void *data,
-		       size_t size)
-{
-    DES_cblock *k =3D key->keyvalue.data;
-    memcpy(k, data, key->keyvalue.length);
-    DES_set_odd_parity(k);
-    if(DES_is_weak_key(k))
-	xor(k, (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
+    krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+			   N_("Encryption type %s not supported", ""),
+			   name);
+    free(name);
+    return KRB5_PROG_ETYPE_NOSUPP;
 }
=20
 /*
  *
  */
=20
-static void
-DES3_random_key(krb5_context context,
-		krb5_keyblock *key)
-{
-    DES_cblock *k =3D key->keyvalue.data;
-    do {
-	krb5_generate_random_block(k, 3 * sizeof(DES_cblock));
-	DES_set_odd_parity(&k[0]);
-	DES_set_odd_parity(&k[1]);
-	DES_set_odd_parity(&k[2]);
-    } while(DES_is_weak_key(&k[0]) ||
-	    DES_is_weak_key(&k[1]) ||
-	    DES_is_weak_key(&k[2]));
-}
-
-static void
-DES3_schedule(krb5_context context,
-	      struct key_data *key)
-{
-    DES_cblock *k =3D key->key->keyvalue.data;
-    DES_key_schedule *s =3D key->schedule->data;
-    DES_set_key(&k[0], &s[0]);
-    DES_set_key(&k[1], &s[1]);
-    DES_set_key(&k[2], &s[2]);
-}
-
-/*
- * A =3D A xor B. A & B are 8 bytes.
- */
-
-static void
-xor (DES_cblock *key, const unsigned char *b)
-{
-    unsigned char *a =3D (unsigned char*)key;
-    a[0] ^=3D b[0];
-    a[1] ^=3D b[1];
-    a[2] ^=3D b[2];
-    a[3] ^=3D b[3];
-    a[4] ^=3D b[4];
-    a[5] ^=3D b[5];
-    a[6] ^=3D b[6];
-    a[7] ^=3D b[7];
-}
-
-static krb5_error_code
-DES3_string_to_key(krb5_context context,
-		   krb5_enctype enctype,
-		   krb5_data password,
-		   krb5_salt salt,
-		   krb5_data opaque,
-		   krb5_keyblock *key)
-{
-    char *str;
-    size_t len;
-    unsigned char tmp[24];
-    DES_cblock keys[3];
-    krb5_error_code ret;
-   =20
-    len =3D password.length + salt.saltvalue.length;
-    str =3D malloc(len);
-    if(len !=3D 0 && str =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    memcpy(str, password.data, password.length);
-    memcpy(str + password.length, salt.saltvalue.data, salt.saltvalue.leng=
th);
-    {
-	DES_cblock ivec;
-	DES_key_schedule s[3];
-	int i;
-=09
-	ret =3D _krb5_n_fold(str, len, tmp, 24);
-	if (ret) {
-	    memset(str, 0, len);
-	    free(str);
-	    krb5_set_error_string(context, "out of memory");
-	    return ret;
-	}
-=09
-	for(i =3D 0; i < 3; i++){
-	    memcpy(keys + i, tmp + i * 8, sizeof(keys[i]));
-	    DES_set_odd_parity(keys + i);
-	    if(DES_is_weak_key(keys + i))
-		xor(keys + i, (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
-	    DES_set_key(keys + i, &s[i]);
-	}
-	memset(&ivec, 0, sizeof(ivec));
-	DES_ede3_cbc_encrypt(tmp,
-			     tmp, sizeof(tmp),=20
-			     &s[0], &s[1], &s[2], &ivec, DES_ENCRYPT);
-	memset(s, 0, sizeof(s));
-	memset(&ivec, 0, sizeof(ivec));
-	for(i =3D 0; i < 3; i++){
-	    memcpy(keys + i, tmp + i * 8, sizeof(keys[i]));
-	    DES_set_odd_parity(keys + i);
-	    if(DES_is_weak_key(keys + i))
-		xor(keys + i, (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
-	}
-	memset(tmp, 0, sizeof(tmp));
-    }
-    key->keytype =3D enctype;
-    krb5_data_copy(&key->keyvalue, keys, sizeof(keys));
-    memset(keys, 0, sizeof(keys));
-    memset(str, 0, len);
-    free(str);
-    return 0;
-}
-
-static krb5_error_code
-DES3_string_to_key_derived(krb5_context context,
-			   krb5_enctype enctype,
-			   krb5_data password,
-			   krb5_salt salt,
-			   krb5_data opaque,
-			   krb5_keyblock *key)
-{
-    krb5_error_code ret;
-    size_t len =3D password.length + salt.saltvalue.length;
-    char *s;
-
-    s =3D malloc(len);
-    if(len !=3D 0 && s =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    memcpy(s, password.data, password.length);
-    memcpy(s + password.length, salt.saltvalue.data, salt.saltvalue.length=
);
-    ret =3D krb5_string_to_key_derived(context,
-				     s,
-				     len,
-				     enctype,
-				     key);
-    memset(s, 0, len);
-    free(s);
-    return ret;
-}
-
-static void
-DES3_random_to_key(krb5_context context,
-		   krb5_keyblock *key,
-		   const void *data,
-		   size_t size)
-{
-    unsigned char *x =3D key->keyvalue.data;
-    const u_char *q =3D data;
-    DES_cblock *k;
-    int i, j;
-
-    memset(x, 0, sizeof(x));
-    for (i =3D 0; i < 3; ++i) {
-	unsigned char foo;
-	for (j =3D 0; j < 7; ++j) {
-	    unsigned char b =3D q[7 * i + j];
-
-	    x[8 * i + j] =3D b;
-	}
-	foo =3D 0;
-	for (j =3D 6; j >=3D 0; --j) {
-	    foo |=3D q[7 * i + j] & 1;
-	    foo <<=3D 1;
-	}
-	x[8 * i + 7] =3D foo;
-    }
-    k =3D key->keyvalue.data;
-    for (i =3D 0; i < 3; i++) {
-	DES_set_odd_parity(&k[i]);
-	if(DES_is_weak_key(&k[i]))
-	    xor(&k[i], (const unsigned char*)"\0\0\0\0\0\0\0\xf0");
-    }   =20
-}
-
-/*
- * ARCFOUR
- */
-
-static void
-ARCFOUR_schedule(krb5_context context,=20
-		 struct key_data *kd)
-{
-    RC4_set_key (kd->schedule->data,
-		 kd->key->keyvalue.length, kd->key->keyvalue.data);
-}
-
-static krb5_error_code
-ARCFOUR_string_to_key(krb5_context context,
-		  krb5_enctype enctype,
-		  krb5_data password,
-		  krb5_salt salt,
-		  krb5_data opaque,
-		  krb5_keyblock *key)
-{
-    char *s, *p;
-    size_t len;
-    int i;
-    MD4_CTX m;
-    krb5_error_code ret;
-
-    len =3D 2 * password.length;
-    s =3D malloc (len);
-    if (len !=3D 0 && s =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	ret =3D ENOMEM;
-	goto out;
-    }
-    for (p =3D s, i =3D 0; i < password.length; ++i) {
-	*p++ =3D ((char *)password.data)[i];
-	*p++ =3D 0;
-    }
-    MD4_Init (&m);
-    MD4_Update (&m, s, len);
-    key->keytype =3D enctype;
-    ret =3D krb5_data_alloc (&key->keyvalue, 16);
-    if (ret) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	goto out;
-    }
-    MD4_Final (key->keyvalue.data, &m);
-    memset (s, 0, len);
-    ret =3D 0;
-out:
-    free (s);
-    return ret;
-}
-
-/*
- * AES
- */
-
-int _krb5_AES_string_to_default_iterator =3D 4096;
-
-static krb5_error_code
-AES_string_to_key(krb5_context context,
-		  krb5_enctype enctype,
-		  krb5_data password,
-		  krb5_salt salt,
-		  krb5_data opaque,
-		  krb5_keyblock *key)
-{
-    krb5_error_code ret;
-    uint32_t iter;
-    struct encryption_type *et;
-    struct key_data kd;
-
-    if (opaque.length =3D=3D 0)
-	iter =3D _krb5_AES_string_to_default_iterator;
-    else if (opaque.length =3D=3D 4) {
-	unsigned long v;
-	_krb5_get_int(opaque.data, &v, 4);
-	iter =3D ((uint32_t)v);
-    } else
-	return KRB5_PROG_KEYTYPE_NOSUPP; /* XXX */
-=09
-    et =3D _find_enctype(enctype);
-    if (et =3D=3D NULL)
-	return KRB5_PROG_KEYTYPE_NOSUPP;
-
-    kd.schedule =3D NULL;
-    ALLOC(kd.key, 1);
-    if(kd.key =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    kd.key->keytype =3D enctype;
-    ret =3D krb5_data_alloc(&kd.key->keyvalue, et->keytype->size);
-    if (ret) {
-	krb5_set_error_string(context, "Failed to allocate pkcs5 key");
-	return ret;
-    }
-
-    ret =3D PKCS5_PBKDF2_HMAC_SHA1(password.data, password.length,
-				 salt.saltvalue.data, salt.saltvalue.length,
-				 iter,=20
-				 et->keytype->size, kd.key->keyvalue.data);
-    if (ret !=3D 1) {
-	free_key_data(context, &kd);
-	krb5_set_error_string(context, "Error calculating s2k");
-	return KRB5_PROG_KEYTYPE_NOSUPP;
-    }
-
-    ret =3D derive_key(context, et, &kd, "kerberos", strlen("kerberos"));
-    if (ret =3D=3D 0)
-	ret =3D krb5_copy_keyblock_contents(context, kd.key, key);
-    free_key_data(context, &kd);
-
-    return ret;
-}
-
-struct krb5_aes_schedule {
-    AES_KEY ekey;
-    AES_KEY dkey;
-};
-
-static void
-AES_schedule(krb5_context context,
-	     struct key_data *kd)
-{
-    struct krb5_aes_schedule *key =3D kd->schedule->data;
-    int bits =3D kd->key->keyvalue.length * 8;
-
-    memset(key, 0, sizeof(*key));
-    AES_set_encrypt_key(kd->key->keyvalue.data, bits, &key->ekey);
-    AES_set_decrypt_key(kd->key->keyvalue.data, bits, &key->dkey);
-}
-
-/*
- *
- */
-
-static struct salt_type des_salt[] =3D {
-    {
-	KRB5_PW_SALT,
-	"pw-salt",
-	krb5_DES_string_to_key
-    },
-#ifdef ENABLE_AFS_STRING_TO_KEY
-    {
-	KRB5_AFS3_SALT,
-	"afs3-salt",
-	DES_AFS3_string_to_key
-    },
-#endif
-    { 0 }
-};
-
-static struct salt_type des3_salt[] =3D {
-    {
-	KRB5_PW_SALT,
-	"pw-salt",
-	DES3_string_to_key
-    },
-    { 0 }
-};
-
-static struct salt_type des3_salt_derived[] =3D {
-    {
-	KRB5_PW_SALT,
-	"pw-salt",
-	DES3_string_to_key_derived
-    },
-    { 0 }
-};
-
-static struct salt_type AES_salt[] =3D {
-    {
-	KRB5_PW_SALT,
-	"pw-salt",
-	AES_string_to_key
-    },
-    { 0 }
-};
-
-static struct salt_type arcfour_salt[] =3D {
-    {
-	KRB5_PW_SALT,
-	"pw-salt",
-	ARCFOUR_string_to_key
-    },
-    { 0 }
-};
-
-/*
- *
- */
-
-static struct key_type keytype_null =3D {
-    KEYTYPE_NULL,
-    "null",
-    0,
-    0,
-    0,
-    NULL,
-    NULL,
-    NULL
-};
-
-static struct key_type keytype_des =3D {
-    KEYTYPE_DES,
-    "des",
-    56,
-    sizeof(DES_cblock),
-    sizeof(DES_key_schedule),
-    krb5_DES_random_key,
-    krb5_DES_schedule,
-    des_salt,
-    krb5_DES_random_to_key
-};
-
-static struct key_type keytype_des3 =3D {
-    KEYTYPE_DES3,
-    "des3",
-    168,
-    3 * sizeof(DES_cblock),=20
-    3 * sizeof(DES_key_schedule),=20
-    DES3_random_key,
-    DES3_schedule,
-    des3_salt,
-    DES3_random_to_key
-};
-
-static struct key_type keytype_des3_derived =3D {
-    KEYTYPE_DES3,
-    "des3",
-    168,
-    3 * sizeof(DES_cblock),
-    3 * sizeof(DES_key_schedule),=20
-    DES3_random_key,
-    DES3_schedule,
-    des3_salt_derived,
-    DES3_random_to_key
-};
-
-static struct key_type keytype_aes128 =3D {
-    KEYTYPE_AES128,
-    "aes-128",
-    128,
-    16,
-    sizeof(struct krb5_aes_schedule),
-    NULL,
-    AES_schedule,
-    AES_salt
-};
-
-static struct key_type keytype_aes256 =3D {
-    KEYTYPE_AES256,
-    "aes-256",
-    256,
-    32,
-    sizeof(struct krb5_aes_schedule),
-    NULL,
-    AES_schedule,
-    AES_salt
-};
-
-static struct key_type keytype_arcfour =3D {
-    KEYTYPE_ARCFOUR,
-    "arcfour",
-    128,
-    16,
-    sizeof(RC4_KEY),
-    NULL,
-    ARCFOUR_schedule,
-    arcfour_salt
-};
-
-static struct key_type *keytypes[] =3D {
-    &keytype_null,
-    &keytype_des,
-    &keytype_des3_derived,
-    &keytype_des3,
-    &keytype_aes128,
-    &keytype_aes256,
-    &keytype_arcfour
-};
-
-static int num_keytypes =3D sizeof(keytypes) / sizeof(keytypes[0]);
-
-static struct key_type *
-_find_keytype(krb5_keytype type)
-{
-    int i;
-    for(i =3D 0; i < num_keytypes; i++)
-	if(keytypes[i]->type =3D=3D type)
-	    return keytypes[i];
-    return NULL;
-}
-
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_salttype_to_string (krb5_context context,
-			 krb5_enctype etype,
-			 krb5_salttype stype,
-			 char **string)
-{
-    struct encryption_type *e;
-    struct salt_type *st;
-
-    e =3D _find_enctype (etype);
-    if (e =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      etype);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    for (st =3D e->keytype->string_to_key; st && st->type; st++) {
-	if (st->type =3D=3D stype) {
-	    *string =3D strdup (st->name);
-	    if (*string =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
-		return ENOMEM;
-	    }
-	    return 0;
-	}
-    }
-    krb5_set_error_string(context, "salttype %d not supported", stype);
-    return HEIM_ERR_SALTTYPE_NOSUPP;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_salttype (krb5_context context,
-			 krb5_enctype etype,
-			 const char *string,
-			 krb5_salttype *salttype)
-{
-    struct encryption_type *e;
-    struct salt_type *st;
-
-    e =3D _find_enctype (etype);
-    if (e =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      etype);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    for (st =3D e->keytype->string_to_key; st && st->type; st++) {
-	if (strcasecmp (st->name, string) =3D=3D 0) {
-	    *salttype =3D st->type;
-	    return 0;
-	}
-    }
-    krb5_set_error_string(context, "salttype %s not supported", string);
-    return HEIM_ERR_SALTTYPE_NOSUPP;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_pw_salt(krb5_context context,
-		 krb5_const_principal principal,
-		 krb5_salt *salt)
-{
-    size_t len;
-    int i;
-    krb5_error_code ret;
-    char *p;
-    =20
-    salt->salttype =3D KRB5_PW_SALT;
-    len =3D strlen(principal->realm);
-    for (i =3D 0; i < principal->name.name_string.len; ++i)
-	len +=3D strlen(principal->name.name_string.val[i]);
-    ret =3D krb5_data_alloc (&salt->saltvalue, len);
-    if (ret)
-	return ret;
-    p =3D salt->saltvalue.data;
-    memcpy (p, principal->realm, strlen(principal->realm));
-    p +=3D strlen(principal->realm);
-    for (i =3D 0; i < principal->name.name_string.len; ++i) {
-	memcpy (p,
-		principal->name.name_string.val[i],
-		strlen(principal->name.name_string.val[i]));
-	p +=3D strlen(principal->name.name_string.val[i]);
-    }
-    return 0;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_free_salt(krb5_context context,=20
-	       krb5_salt salt)
-{
-    krb5_data_free(&salt.saltvalue);
-    return 0;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_key_data (krb5_context context,
-			 krb5_enctype enctype,
-			 krb5_data password,
-			 krb5_principal principal,
-			 krb5_keyblock *key)
-{
-    krb5_error_code ret;
-    krb5_salt salt;
-
-    ret =3D krb5_get_pw_salt(context, principal, &salt);
-    if(ret)
-	return ret;
-    ret =3D krb5_string_to_key_data_salt(context, enctype, password, salt,=
 key);
-    krb5_free_salt(context, salt);
-    return ret;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_key (krb5_context context,
-		    krb5_enctype enctype,
-		    const char *password,
-		    krb5_principal principal,
-		    krb5_keyblock *key)
-{
-    krb5_data pw;
-    pw.data =3D rk_UNCONST(password);
-    pw.length =3D strlen(password);
-    return krb5_string_to_key_data(context, enctype, pw, principal, key);
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_key_data_salt (krb5_context context,
-			      krb5_enctype enctype,
-			      krb5_data password,
-			      krb5_salt salt,
-			      krb5_keyblock *key)
-{
-    krb5_data opaque;
-    krb5_data_zero(&opaque);
-    return krb5_string_to_key_data_salt_opaque(context, enctype, password,=20
-					       salt, opaque, key);
-}
-
-/*
- * Do a string -> key for encryption type `enctype' operation on
- * `password' (with salt `salt' and the enctype specific data string
- * `opaque'), returning the resulting key in `key'
- */
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_key_data_salt_opaque (krb5_context context,
-				     krb5_enctype enctype,
-				     krb5_data password,
-				     krb5_salt salt,
-				     krb5_data opaque,
-				     krb5_keyblock *key)
-{
-    struct encryption_type *et =3D_find_enctype(enctype);
-    struct salt_type *st;
-    if(et =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      enctype);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    for(st =3D et->keytype->string_to_key; st && st->type; st++)=20
-	if(st->type =3D=3D salt.salttype)
-	    return (*st->string_to_key)(context, enctype, password,=20
-					salt, opaque, key);
-    krb5_set_error_string(context, "salt type %d not supported",
-			  salt.salttype);
-    return HEIM_ERR_SALTTYPE_NOSUPP;
-}
-
-/*
- * Do a string -> key for encryption type `enctype' operation on the
- * string `password' (with salt `salt'), returning the resulting key
- * in `key'
- */
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_key_salt (krb5_context context,
-			 krb5_enctype enctype,
-			 const char *password,
-			 krb5_salt salt,
-			 krb5_keyblock *key)
-{
-    krb5_data pw;
-    pw.data =3D rk_UNCONST(password);
-    pw.length =3D strlen(password);
-    return krb5_string_to_key_data_salt(context, enctype, pw, salt, key);
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_key_salt_opaque (krb5_context context,
-				krb5_enctype enctype,
-				const char *password,
-				krb5_salt salt,
-				krb5_data opaque,
-				krb5_keyblock *key)
-{
-    krb5_data pw;
-    pw.data =3D rk_UNCONST(password);
-    pw.length =3D strlen(password);
-    return krb5_string_to_key_data_salt_opaque(context, enctype,=20
-					       pw, salt, opaque, key);
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_keytype_to_string(krb5_context context,
-		       krb5_keytype keytype,
-		       char **string)
-{
-    struct key_type *kt =3D _find_keytype(keytype);
-    if(kt =3D=3D NULL) {
-	krb5_set_error_string(context, "key type %d not supported", keytype);
-	return KRB5_PROG_KEYTYPE_NOSUPP;
-    }
-    *string =3D strdup(kt->name);
-    if(*string =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    return 0;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_keytype(krb5_context context,
-		       const char *string,
-		       krb5_keytype *keytype)
-{
-    int i;
-    for(i =3D 0; i < num_keytypes; i++)
-	if(strcasecmp(keytypes[i]->name, string) =3D=3D 0){
-	    *keytype =3D keytypes[i]->type;
-	    return 0;
-	}
-    krb5_set_error_string(context, "key type %s not supported", string);
-    return KRB5_PROG_KEYTYPE_NOSUPP;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_keysize(krb5_context context,
 		     krb5_enctype type,
 		     size_t *keysize)
 {
-    struct encryption_type *et =3D _find_enctype(type);
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(type);
     if(et =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      type);
-	return KRB5_PROG_ETYPE_NOSUPP;
+        return unsupported_enctype (context, type);
     }
     *keysize =3D et->keytype->size;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_keybits(krb5_context context,
 		     krb5_enctype type,
 		     size_t *keybits)
 {
-    struct encryption_type *et =3D _find_enctype(type);
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(type);
     if(et =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      type);
-	return KRB5_PROG_ETYPE_NOSUPP;
+        return unsupported_enctype (context, type);
     }
     *keybits =3D et->keytype->bits;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_generate_random_keyblock(krb5_context context,
 			      krb5_enctype type,
 			      krb5_keyblock *key)
 {
     krb5_error_code ret;
-    struct encryption_type *et =3D _find_enctype(type);
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(type);
     if(et =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      type);
-	return KRB5_PROG_ETYPE_NOSUPP;
+        return unsupported_enctype (context, type);
     }
     ret =3D krb5_data_alloc(&key->keyvalue, et->keytype->size);
-    if(ret)=20
+    if(ret)
 	return ret;
     key->keytype =3D type;
     if(et->keytype->random_key)
 	(*et->keytype->random_key)(context, key);
     else
-	krb5_generate_random_block(key->keyvalue.data,=20
+	krb5_generate_random_block(key->keyvalue.data,
 				   key->keyvalue.length);
     return 0;
 }
=20
 static krb5_error_code
 _key_schedule(krb5_context context,
-	      struct key_data *key)
+	      struct _krb5_key_data *key)
 {
     krb5_error_code ret;
-    struct encryption_type *et =3D _find_enctype(key->key->keytype);
-    struct key_type *kt =3D et->keytype;
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(key->key->keyt=
ype);
+    struct _krb5_key_type *kt;
+
+    if (et =3D=3D NULL) {
+        return unsupported_enctype (context,
+                               key->key->keytype);
+    }
+
+    kt =3D et->keytype;
=20
     if(kt->schedule =3D=3D NULL)
 	return 0;
@@ -1137,7 +148,7 @@
 	return 0;
     ALLOC(key->schedule, 1);
     if(key->schedule =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ret =3D krb5_data_alloc(key->schedule, kt->schedule_size);
@@ -1146,7 +157,7 @@
 	key->schedule =3D NULL;
 	return ret;
     }
-    (*kt->schedule)(context, key);
+    (*kt->schedule)(context, kt, key);
     return 0;
 }
=20
@@ -1154,277 +165,34 @@
  *                                                          *
  ************************************************************/
=20
-static void
-NONE_checksum(krb5_context context,
-	      struct key_data *key,
+static krb5_error_code
+SHA1_checksum(krb5_context context,
+	      struct _krb5_key_data *key,
 	      const void *data,
 	      size_t len,
 	      unsigned usage,
 	      Checksum *C)
 {
+    if (EVP_Digest(data, len, C->checksum.data, NULL, EVP_sha1(), NULL) !=
=3D 1)
+	krb5_abortx(context, "sha1 checksum failed");
+    return 0;
 }
=20
-static void
-CRC32_checksum(krb5_context context,
-	       struct key_data *key,
-	       const void *data,
-	       size_t len,
-	       unsigned usage,
-	       Checksum *C)
-{
-    uint32_t crc;
-    unsigned char *r =3D C->checksum.data;
-    _krb5_crc_init_table ();
-    crc =3D _krb5_crc_update (data, len, 0);
-    r[0] =3D crc & 0xff;
-    r[1] =3D (crc >> 8)  & 0xff;
-    r[2] =3D (crc >> 16) & 0xff;
-    r[3] =3D (crc >> 24) & 0xff;
-}
-
-static void
-RSA_MD4_checksum(krb5_context context,
-		 struct key_data *key,
-		 const void *data,
-		 size_t len,
-		 unsigned usage,
-		 Checksum *C)
-{
-    MD4_CTX m;
-
-    MD4_Init (&m);
-    MD4_Update (&m, data, len);
-    MD4_Final (C->checksum.data, &m);
-}
-
-static void
-RSA_MD4_DES_checksum(krb5_context context,=20
-		     struct key_data *key,
-		     const void *data,=20
-		     size_t len,=20
-		     unsigned usage,
-		     Checksum *cksum)
-{
-    MD4_CTX md4;
-    DES_cblock ivec;
-    unsigned char *p =3D cksum->checksum.data;
-   =20
-    krb5_generate_random_block(p, 8);
-    MD4_Init (&md4);
-    MD4_Update (&md4, p, 8);
-    MD4_Update (&md4, data, len);
-    MD4_Final (p + 8, &md4);
-    memset (&ivec, 0, sizeof(ivec));
-    DES_cbc_encrypt(p,=20
-		    p,=20
-		    24,=20
-		    key->schedule->data,=20
-		    &ivec,=20
-		    DES_ENCRYPT);
-}
-
-static krb5_error_code
-RSA_MD4_DES_verify(krb5_context context,
-		   struct key_data *key,
-		   const void *data,
-		   size_t len,
-		   unsigned usage,
-		   Checksum *C)
-{
-    MD4_CTX md4;
-    unsigned char tmp[24];
-    unsigned char res[16];
-    DES_cblock ivec;
-    krb5_error_code ret =3D 0;
-
-    memset(&ivec, 0, sizeof(ivec));
-    DES_cbc_encrypt(C->checksum.data,
-		    (void*)tmp,=20
-		    C->checksum.length,=20
-		    key->schedule->data,
-		    &ivec,
-		    DES_DECRYPT);
-    MD4_Init (&md4);
-    MD4_Update (&md4, tmp, 8); /* confounder */
-    MD4_Update (&md4, data, len);
-    MD4_Final (res, &md4);
-    if(memcmp(res, tmp + 8, sizeof(res)) !=3D 0) {
-	krb5_clear_error_string (context);
-	ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
-    }
-    memset(tmp, 0, sizeof(tmp));
-    memset(res, 0, sizeof(res));
-    return ret;
-}
-
-static void
-RSA_MD5_checksum(krb5_context context,
-		 struct key_data *key,
-		 const void *data,
-		 size_t len,
-		 unsigned usage,
-		 Checksum *C)
-{
-    MD5_CTX m;
-
-    MD5_Init  (&m);
-    MD5_Update(&m, data, len);
-    MD5_Final (C->checksum.data, &m);
-}
-
-static void
-RSA_MD5_DES_checksum(krb5_context context,
-		     struct key_data *key,
-		     const void *data,
-		     size_t len,
-		     unsigned usage,
-		     Checksum *C)
-{
-    MD5_CTX md5;
-    DES_cblock ivec;
-    unsigned char *p =3D C->checksum.data;
-   =20
-    krb5_generate_random_block(p, 8);
-    MD5_Init (&md5);
-    MD5_Update (&md5, p, 8);
-    MD5_Update (&md5, data, len);
-    MD5_Final (p + 8, &md5);
-    memset (&ivec, 0, sizeof(ivec));
-    DES_cbc_encrypt(p,=20
-		    p,=20
-		    24,=20
-		    key->schedule->data,=20
-		    &ivec,=20
-		    DES_ENCRYPT);
-}
-
-static krb5_error_code
-RSA_MD5_DES_verify(krb5_context context,
-		   struct key_data *key,
-		   const void *data,
-		   size_t len,
-		   unsigned usage,
-		   Checksum *C)
-{
-    MD5_CTX md5;
-    unsigned char tmp[24];
-    unsigned char res[16];
-    DES_cblock ivec;
-    DES_key_schedule *sched =3D key->schedule->data;
-    krb5_error_code ret =3D 0;
-
-    memset(&ivec, 0, sizeof(ivec));
-    DES_cbc_encrypt(C->checksum.data,=20
-		    (void*)tmp,=20
-		    C->checksum.length,=20
-		    &sched[0],
-		    &ivec,
-		    DES_DECRYPT);
-    MD5_Init (&md5);
-    MD5_Update (&md5, tmp, 8); /* confounder */
-    MD5_Update (&md5, data, len);
-    MD5_Final (res, &md5);
-    if(memcmp(res, tmp + 8, sizeof(res)) !=3D 0) {
-	krb5_clear_error_string (context);
-	ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
-    }
-    memset(tmp, 0, sizeof(tmp));
-    memset(res, 0, sizeof(res));
-    return ret;
-}
-
-static void
-RSA_MD5_DES3_checksum(krb5_context context,
-		      struct key_data *key,
-		      const void *data,
-		      size_t len,
-		      unsigned usage,
-		      Checksum *C)
-{
-    MD5_CTX md5;
-    DES_cblock ivec;
-    unsigned char *p =3D C->checksum.data;
-    DES_key_schedule *sched =3D key->schedule->data;
-   =20
-    krb5_generate_random_block(p, 8);
-    MD5_Init (&md5);
-    MD5_Update (&md5, p, 8);
-    MD5_Update (&md5, data, len);
-    MD5_Final (p + 8, &md5);
-    memset (&ivec, 0, sizeof(ivec));
-    DES_ede3_cbc_encrypt(p,=20
-			 p,=20
-			 24,=20
-			 &sched[0], &sched[1], &sched[2],
-			 &ivec,=20
-			 DES_ENCRYPT);
-}
-
-static krb5_error_code
-RSA_MD5_DES3_verify(krb5_context context,
-		    struct key_data *key,
+/* HMAC according to RFC2104 */
+krb5_error_code
+_krb5_internal_hmac(krb5_context context,
+		    struct _krb5_checksum_type *cm,
 		    const void *data,
 		    size_t len,
 		    unsigned usage,
-		    Checksum *C)
-{
-    MD5_CTX md5;
-    unsigned char tmp[24];
-    unsigned char res[16];
-    DES_cblock ivec;
-    DES_key_schedule *sched =3D key->schedule->data;
-    krb5_error_code ret =3D 0;
-
-    memset(&ivec, 0, sizeof(ivec));
-    DES_ede3_cbc_encrypt(C->checksum.data,=20
-			 (void*)tmp,=20
-			 C->checksum.length,=20
-			 &sched[0], &sched[1], &sched[2],
-			 &ivec,
-			 DES_DECRYPT);
-    MD5_Init (&md5);
-    MD5_Update (&md5, tmp, 8); /* confounder */
-    MD5_Update (&md5, data, len);
-    MD5_Final (res, &md5);
-    if(memcmp(res, tmp + 8, sizeof(res)) !=3D 0) {
-	krb5_clear_error_string (context);
-	ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
-    }
-    memset(tmp, 0, sizeof(tmp));
-    memset(res, 0, sizeof(res));
-    return ret;
-}
-
-static void
-SHA1_checksum(krb5_context context,
-	      struct key_data *key,
-	      const void *data,
-	      size_t len,
-	      unsigned usage,
-	      Checksum *C)
-{
-    SHA_CTX m;
-
-    SHA1_Init(&m);
-    SHA1_Update(&m, data, len);
-    SHA1_Final(C->checksum.data, &m);
-}
-
-/* HMAC according to RFC2104 */
-static krb5_error_code
-hmac(krb5_context context,
-     struct checksum_type *cm,=20
-     const void *data,=20
-     size_t len,=20
-     unsigned usage,
-     struct key_data *keyblock,
-     Checksum *result)
+		    struct _krb5_key_data *keyblock,
+		    Checksum *result)
 {
     unsigned char *ipad, *opad;
     unsigned char *key;
     size_t key_len;
-    int i;
-   =20
+    size_t i;
+
     ipad =3D malloc(cm->blocksize + len);
     if (ipad =3D=3D NULL)
 	return ENOMEM;
@@ -1437,10 +205,10 @@
     memset(opad, 0x5c, cm->blocksize);
=20
     if(keyblock->key->keyvalue.length > cm->blocksize){
-	(*cm->checksum)(context,=20
-			keyblock,=20
-			keyblock->key->keyvalue.data,=20
-			keyblock->key->keyvalue.length,=20
+	(*cm->checksum)(context,
+			keyblock,
+			keyblock->key->keyvalue.data,
+			keyblock->key->keyvalue.length,
 			usage,
 			result);
 	key =3D result->checksum.data;
@@ -1456,9 +224,9 @@
     memcpy(ipad + cm->blocksize, data, len);
     (*cm->checksum)(context, keyblock, ipad, cm->blocksize + len,
 		    usage, result);
-    memcpy(opad + cm->blocksize, result->checksum.data,=20
+    memcpy(opad + cm->blocksize, result->checksum.data,
 	   result->checksum.length);
-    (*cm->checksum)(context, keyblock, opad,=20
+    (*cm->checksum)(context, keyblock, opad,
 		    cm->blocksize + cm->checksumsize, usage, result);
     memset(ipad, 0, cm->blocksize + len);
     free(ipad);
@@ -1468,45 +236,46 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_hmac(krb5_context context,
 	  krb5_cksumtype cktype,
 	  const void *data,
 	  size_t len,
-	  unsigned usage,=20
+	  unsigned usage,
 	  krb5_keyblock *key,
 	  Checksum *result)
 {
-    struct checksum_type *c =3D _find_checksum(cktype);
-    struct key_data kd;
+    struct _krb5_checksum_type *c =3D _krb5_find_checksum(cktype);
+    struct _krb5_key_data kd;
     krb5_error_code ret;
=20
     if (c =3D=3D NULL) {
-	krb5_set_error_string (context, "checksum type %d not supported",
-			       cktype);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type %d not supported", ""),
+				cktype);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
=20
     kd.key =3D key;
     kd.schedule =3D NULL;
=20
-    ret =3D hmac(context, c, data, len, usage, &kd, result);
+    ret =3D _krb5_internal_hmac(context, c, data, len, usage, &kd, result);
=20
     if (kd.schedule)
 	krb5_free_data(context, kd.schedule);
=20
     return ret;
- }
+}
=20
-static void
-SP_HMAC_SHA1_checksum(krb5_context context,
-		      struct key_data *key,=20
-		      const void *data,=20
-		      size_t len,=20
-		      unsigned usage,
-		      Checksum *result)
+krb5_error_code
+_krb5_SP_HMAC_SHA1_checksum(krb5_context context,
+			    struct _krb5_key_data *key,
+			    const void *data,
+			    size_t len,
+			    unsigned usage,
+			    Checksum *result)
 {
-    struct checksum_type *c =3D _find_checksum(CKSUMTYPE_SHA1);
+    struct _krb5_checksum_type *c =3D _krb5_find_checksum(CKSUMTYPE_SHA1);
     Checksum res;
     char sha1_data[20];
     krb5_error_code ret;
@@ -1514,183 +283,14 @@
     res.checksum.data =3D sha1_data;
     res.checksum.length =3D sizeof(sha1_data);
=20
-    ret =3D hmac(context, c, data, len, usage, key, &res);
+    ret =3D _krb5_internal_hmac(context, c, data, len, usage, key, &res);
     if (ret)
 	krb5_abortx(context, "hmac failed");
     memcpy(result->checksum.data, res.checksum.data, result->checksum.leng=
th);
+    return 0;
 }
=20
-/*
- * checksum according to section 5. of draft-brezak-win2k-krb-rc4-hmac-03.=
txt
- */
-
-static void
-HMAC_MD5_checksum(krb5_context context,
-		  struct key_data *key,
-		  const void *data,
-		  size_t len,
-		  unsigned usage,
-		  Checksum *result)
-{
-    MD5_CTX md5;
-    struct checksum_type *c =3D _find_checksum (CKSUMTYPE_RSA_MD5);
-    const char signature[] =3D "signaturekey";
-    Checksum ksign_c;
-    struct key_data ksign;
-    krb5_keyblock kb;
-    unsigned char t[4];
-    unsigned char tmp[16];
-    unsigned char ksign_c_data[16];
-    krb5_error_code ret;
-
-    ksign_c.checksum.length =3D sizeof(ksign_c_data);
-    ksign_c.checksum.data   =3D ksign_c_data;
-    ret =3D hmac(context, c, signature, sizeof(signature), 0, key, &ksign_=
c);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-    ksign.key =3D &kb;
-    kb.keyvalue =3D ksign_c.checksum;
-    MD5_Init (&md5);
-    t[0] =3D (usage >>  0) & 0xFF;
-    t[1] =3D (usage >>  8) & 0xFF;
-    t[2] =3D (usage >> 16) & 0xFF;
-    t[3] =3D (usage >> 24) & 0xFF;
-    MD5_Update (&md5, t, 4);
-    MD5_Update (&md5, data, len);
-    MD5_Final (tmp, &md5);
-    ret =3D hmac(context, c, tmp, sizeof(tmp), 0, &ksign, result);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-}
-
-/*
- * same as previous but being used while encrypting.
- */
-
-static void
-HMAC_MD5_checksum_enc(krb5_context context,
-		      struct key_data *key,
-		      const void *data,
-		      size_t len,
-		      unsigned usage,
-		      Checksum *result)
-{
-    struct checksum_type *c =3D _find_checksum (CKSUMTYPE_RSA_MD5);
-    Checksum ksign_c;
-    struct key_data ksign;
-    krb5_keyblock kb;
-    unsigned char t[4];
-    unsigned char ksign_c_data[16];
-    krb5_error_code ret;
-
-    t[0] =3D (usage >>  0) & 0xFF;
-    t[1] =3D (usage >>  8) & 0xFF;
-    t[2] =3D (usage >> 16) & 0xFF;
-    t[3] =3D (usage >> 24) & 0xFF;
-
-    ksign_c.checksum.length =3D sizeof(ksign_c_data);
-    ksign_c.checksum.data   =3D ksign_c_data;
-    ret =3D hmac(context, c, t, sizeof(t), 0, key, &ksign_c);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-    ksign.key =3D &kb;
-    kb.keyvalue =3D ksign_c.checksum;
-    ret =3D hmac(context, c, data, len, 0, &ksign, result);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-}
-
-static struct checksum_type checksum_none =3D {
-    CKSUMTYPE_NONE,=20
-    "none",=20
-    1,=20
-    0,=20
-    0,
-    NONE_checksum,=20
-    NULL
-};
-static struct checksum_type checksum_crc32 =3D {
-    CKSUMTYPE_CRC32,
-    "crc32",
-    1,
-    4,
-    0,
-    CRC32_checksum,
-    NULL
-};
-static struct checksum_type checksum_rsa_md4 =3D {
-    CKSUMTYPE_RSA_MD4,
-    "rsa-md4",
-    64,
-    16,
-    F_CPROOF,
-    RSA_MD4_checksum,
-    NULL
-};
-static struct checksum_type checksum_rsa_md4_des =3D {
-    CKSUMTYPE_RSA_MD4_DES,
-    "rsa-md4-des",
-    64,
-    24,
-    F_KEYED | F_CPROOF | F_VARIANT,
-    RSA_MD4_DES_checksum,
-    RSA_MD4_DES_verify
-};
-#if 0
-static struct checksum_type checksum_des_mac =3D {=20
-    CKSUMTYPE_DES_MAC,
-    "des-mac",
-    0,
-    0,
-    0,
-    DES_MAC_checksum
-};
-static struct checksum_type checksum_des_mac_k =3D {
-    CKSUMTYPE_DES_MAC_K,
-    "des-mac-k",
-    0,
-    0,
-    0,
-    DES_MAC_K_checksum
-};
-static struct checksum_type checksum_rsa_md4_des_k =3D {
-    CKSUMTYPE_RSA_MD4_DES_K,=20
-    "rsa-md4-des-k",=20
-    0,=20
-    0,=20
-    0,=20
-    RSA_MD4_DES_K_checksum,
-    RSA_MD4_DES_K_verify
-};
-#endif
-static struct checksum_type checksum_rsa_md5 =3D {
-    CKSUMTYPE_RSA_MD5,
-    "rsa-md5",
-    64,
-    16,
-    F_CPROOF,
-    RSA_MD5_checksum,
-    NULL
-};
-static struct checksum_type checksum_rsa_md5_des =3D {
-    CKSUMTYPE_RSA_MD5_DES,
-    "rsa-md5-des",
-    64,
-    24,
-    F_KEYED | F_CPROOF | F_VARIANT,
-    RSA_MD5_DES_checksum,
-    RSA_MD5_DES_verify
-};
-static struct checksum_type checksum_rsa_md5_des3 =3D {
-    CKSUMTYPE_RSA_MD5_DES3,
-    "rsa-md5-des3",
-    64,
-    24,
-    F_KEYED | F_CPROOF | F_VARIANT,
-    RSA_MD5_DES3_checksum,
-    RSA_MD5_DES3_verify
-};
-static struct checksum_type checksum_sha1 =3D {
+struct _krb5_checksum_type _krb5_checksum_sha1 =3D {
     CKSUMTYPE_SHA1,
     "sha1",
     64,
@@ -1699,115 +299,43 @@
     SHA1_checksum,
     NULL
 };
-static struct checksum_type checksum_hmac_sha1_des3 =3D {
-    CKSUMTYPE_HMAC_SHA1_DES3,
-    "hmac-sha1-des3",
-    64,
-    20,
-    F_KEYED | F_CPROOF | F_DERIVED,
-    SP_HMAC_SHA1_checksum,
-    NULL
-};
=20
-static struct checksum_type checksum_hmac_sha1_aes128 =3D {
-    CKSUMTYPE_HMAC_SHA1_96_AES_128,
-    "hmac-sha1-96-aes128",
-    64,
-    12,
-    F_KEYED | F_CPROOF | F_DERIVED,
-    SP_HMAC_SHA1_checksum,
-    NULL
-};
-
-static struct checksum_type checksum_hmac_sha1_aes256 =3D {
-    CKSUMTYPE_HMAC_SHA1_96_AES_256,
-    "hmac-sha1-96-aes256",
-    64,
-    12,
-    F_KEYED | F_CPROOF | F_DERIVED,
-    SP_HMAC_SHA1_checksum,
-    NULL
-};
-
-static struct checksum_type checksum_hmac_md5 =3D {
-    CKSUMTYPE_HMAC_MD5,
-    "hmac-md5",
-    64,
-    16,
-    F_KEYED | F_CPROOF,
-    HMAC_MD5_checksum,
-    NULL
-};
-
-static struct checksum_type checksum_hmac_md5_enc =3D {
-    CKSUMTYPE_HMAC_MD5_ENC,
-    "hmac-md5-enc",
-    64,
-    16,
-    F_KEYED | F_CPROOF | F_PSEUDO,
-    HMAC_MD5_checksum_enc,
-    NULL
-};
-
-static struct checksum_type *checksum_types[] =3D {
-    &checksum_none,
-    &checksum_crc32,
-    &checksum_rsa_md4,
-    &checksum_rsa_md4_des,
-#if 0
-    &checksum_des_mac,=20
-    &checksum_des_mac_k,
-    &checksum_rsa_md4_des_k,
-#endif
-    &checksum_rsa_md5,
-    &checksum_rsa_md5_des,
-    &checksum_rsa_md5_des3,
-    &checksum_sha1,
-    &checksum_hmac_sha1_des3,
-    &checksum_hmac_sha1_aes128,
-    &checksum_hmac_sha1_aes256,
-    &checksum_hmac_md5,
-    &checksum_hmac_md5_enc
-};
-
-static int num_checksums =3D sizeof(checksum_types) / sizeof(checksum_type=
s[0]);
-
-static struct checksum_type *
-_find_checksum(krb5_cksumtype type)
+struct _krb5_checksum_type *
+_krb5_find_checksum(krb5_cksumtype type)
 {
     int i;
-    for(i =3D 0; i < num_checksums; i++)
-	if(checksum_types[i]->type =3D=3D type)
-	    return checksum_types[i];
+    for(i =3D 0; i < _krb5_num_checksums; i++)
+	if(_krb5_checksum_types[i]->type =3D=3D type)
+	    return _krb5_checksum_types[i];
     return NULL;
 }
=20
 static krb5_error_code
-get_checksum_key(krb5_context context,=20
+get_checksum_key(krb5_context context,
 		 krb5_crypto crypto,
 		 unsigned usage,  /* not krb5_key_usage */
-		 struct checksum_type *ct,=20
-		 struct key_data **key)
+		 struct _krb5_checksum_type *ct,
+		 struct _krb5_key_data **key)
 {
     krb5_error_code ret =3D 0;
=20
     if(ct->flags & F_DERIVED)
 	ret =3D _get_derived_key(context, crypto, usage, key);
     else if(ct->flags & F_VARIANT) {
-	int i;
+	size_t i;
=20
 	*key =3D _new_derived_key(crypto, 0xff/* KRB5_KU_RFC1510_VARIANT */);
 	if(*key =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "=
"));
 	    return ENOMEM;
 	}
 	ret =3D krb5_copy_keyblock(context, crypto->key.key, &(*key)->key);
-	if(ret)=20
+	if(ret)
 	    return ret;
 	for(i =3D 0; i < (*key)->key->keyvalue.length; i++)
 	    ((unsigned char*)(*key)->key->keyvalue.data)[i] ^=3D 0xF0;
     } else {
-	*key =3D &crypto->key;=20
+	*key =3D &crypto->key;
     }
     if(ret =3D=3D 0)
 	ret =3D _key_schedule(context, *key);
@@ -1816,7 +344,7 @@
=20
 static krb5_error_code
 create_checksum (krb5_context context,
-		 struct checksum_type *ct,
+		 struct _krb5_checksum_type *ct,
 		 krb5_crypto crypto,
 		 unsigned usage,
 		 void *data,
@@ -1824,18 +352,19 @@
 		 Checksum *result)
 {
     krb5_error_code ret;
-    struct key_data *dkey;
+    struct _krb5_key_data *dkey;
     int keyed_checksum;
-   =20
+
     if (ct->flags & F_DISABLED) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     keyed_checksum =3D (ct->flags & F_KEYED) !=3D 0;
     if(keyed_checksum && crypto =3D=3D NULL) {
-	krb5_set_error_string (context, "Checksum type %s is keyed "
-			       "but no crypto context (key) was passed in",
-			       ct->name);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("Checksum type %s is keyed but no "
+				   "crypto context (key) was passed in", ""),
+				ct->name);
 	return KRB5_PROG_SUMTYPE_NOSUPP; /* XXX */
     }
     if(keyed_checksum) {
@@ -1848,18 +377,17 @@
     ret =3D krb5_data_alloc(&result->checksum, ct->checksumsize);
     if (ret)
 	return (ret);
-    (*ct->checksum)(context, dkey, data, len, usage, result);
-    return 0;
+    return (*ct->checksum)(context, dkey, data, len, usage, result);
 }
=20
 static int
-arcfour_checksum_p(struct checksum_type *ct, krb5_crypto crypto)
+arcfour_checksum_p(struct _krb5_checksum_type *ct, krb5_crypto crypto)
 {
     return (ct->type =3D=3D CKSUMTYPE_HMAC_MD5) &&
 	(crypto->key.key->keytype =3D=3D KEYTYPE_ARCFOUR);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_create_checksum(krb5_context context,
 		     krb5_crypto crypto,
 		     krb5_key_usage usage,
@@ -1868,12 +396,12 @@
 		     size_t len,
 		     Checksum *result)
 {
-    struct checksum_type *ct =3D NULL;
+    struct _krb5_checksum_type *ct =3D NULL;
     unsigned keyusage;
=20
     /* type 0 -> pick from crypto */
     if (type) {
-	ct =3D _find_checksum(type);
+	ct =3D _krb5_find_checksum(type);
     } else if (crypto) {
 	ct =3D crypto->et->keyed_checksum;
 	if (ct =3D=3D NULL)
@@ -1881,14 +409,15 @@
     }
=20
     if(ct =3D=3D NULL) {
-	krb5_set_error_string (context, "checksum type %d not supported",
-			       type);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type %d not supported", ""),
+				type);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
=20
     if (arcfour_checksum_p(ct, crypto)) {
 	keyusage =3D usage;
-	usage2arcfour(context, &keyusage);
+	_krb5_usage2arcfour(context, &keyusage);
     } else
 	keyusage =3D CHECKSUM_USAGE(usage);
=20
@@ -1905,45 +434,85 @@
 		Checksum *cksum)
 {
     krb5_error_code ret;
-    struct key_data *dkey;
+    struct _krb5_key_data *dkey;
     int keyed_checksum;
     Checksum c;
-    struct checksum_type *ct;
+    struct _krb5_checksum_type *ct;
=20
-    ct =3D _find_checksum(cksum->cksumtype);
+    ct =3D _krb5_find_checksum(cksum->cksumtype);
     if (ct =3D=3D NULL || (ct->flags & F_DISABLED)) {
-	krb5_set_error_string (context, "checksum type %d not supported",
-			       cksum->cksumtype);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type %d not supported", ""),
+				cksum->cksumtype);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     if(ct->checksumsize !=3D cksum->checksum.length) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
+	krb5_set_error_message(context, KRB5KRB_AP_ERR_BAD_INTEGRITY,
+			       N_("Decrypt integrity check failed for checksum type %s, "
+				  "length was %u, expected %u", ""),
+			       ct->name, (unsigned)cksum->checksum.length,
+			       (unsigned)ct->checksumsize);
+
 	return KRB5KRB_AP_ERR_BAD_INTEGRITY; /* XXX */
     }
     keyed_checksum =3D (ct->flags & F_KEYED) !=3D 0;
-    if(keyed_checksum && crypto =3D=3D NULL) {
-	krb5_set_error_string (context, "Checksum type %s is keyed "
-			       "but no crypto context (key) was passed in",
-			       ct->name);
-	return KRB5_PROG_SUMTYPE_NOSUPP; /* XXX */
+    if(keyed_checksum) {
+	struct _krb5_checksum_type *kct;
+	if (crypto =3D=3D NULL) {
+	    krb5_set_error_message(context, KRB5_PROG_SUMTYPE_NOSUPP,
+				   N_("Checksum type %s is keyed but no "
+				      "crypto context (key) was passed in", ""),
+				   ct->name);
+	    return KRB5_PROG_SUMTYPE_NOSUPP; /* XXX */
+	}
+	kct =3D crypto->et->keyed_checksum;
+	if (kct =3D=3D NULL || kct->type !=3D ct->type) {
+	    krb5_set_error_message(context, KRB5_PROG_SUMTYPE_NOSUPP,
+				   N_("Checksum type %s is keyed, but "
+				      "the key type %s passed didnt have that checksum "
+				      "type as the keyed type", ""),
+				    ct->name, crypto->et->name);
+	    return KRB5_PROG_SUMTYPE_NOSUPP; /* XXX */
+	}
+
+	ret =3D get_checksum_key(context, crypto, usage, ct, &dkey);
+	if (ret)
+	    return ret;
+    } else
+	dkey =3D NULL;
+
+    /*
+     * If checksum have a verify function, lets use that instead of
+     * calling ->checksum and then compare result.
+     */
+
+    if(ct->verify) {
+	ret =3D (*ct->verify)(context, dkey, data, len, usage, cksum);
+	if (ret)
+	    krb5_set_error_message(context, ret,
+				   N_("Decrypt integrity check failed for checksum "
+				      "type %s, key type %s", ""),
+				   ct->name, (crypto !=3D NULL)? crypto->et->name : "(none)");
+	return ret;
     }
-    if(keyed_checksum)
-	ret =3D get_checksum_key(context, crypto, usage, ct, &dkey);
-    else
-	dkey =3D NULL;
-    if(ct->verify)
-	return (*ct->verify)(context, dkey, data, len, usage, cksum);
=20
     ret =3D krb5_data_alloc (&c.checksum, ct->checksumsize);
     if (ret)
 	return ret;
=20
-    (*ct->checksum)(context, dkey, data, len, usage, &c);
+    ret =3D (*ct->checksum)(context, dkey, data, len, usage, &c);
+    if (ret) {
+	krb5_data_free(&c.checksum);
+	return ret;
+    }
=20
-    if(c.checksum.length !=3D cksum->checksum.length ||=20
-       memcmp(c.checksum.data, cksum->checksum.data, c.checksum.length)) {
-	krb5_clear_error_string (context);
+    if(krb5_data_ct_cmp(&c.checksum, &cksum->checksum) !=3D 0) {
 	ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
+	krb5_set_error_message(context, ret,
+			       N_("Decrypt integrity check failed for checksum "
+				  "type %s, key type %s", ""),
+			       ct->name, crypto ? crypto->et->name : "(unkeyed)");
     } else {
 	ret =3D 0;
     }
@@ -1951,27 +520,28 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_checksum(krb5_context context,
 		     krb5_crypto crypto,
-		     krb5_key_usage usage,=20
+		     krb5_key_usage usage,
 		     void *data,
 		     size_t len,
 		     Checksum *cksum)
 {
-    struct checksum_type *ct;
+    struct _krb5_checksum_type *ct;
     unsigned keyusage;
=20
-    ct =3D _find_checksum(cksum->cksumtype);
+    ct =3D _krb5_find_checksum(cksum->cksumtype);
     if(ct =3D=3D NULL) {
-	krb5_set_error_string (context, "checksum type %d not supported",
-			       cksum->cksumtype);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type %d not supported", ""),
+				cksum->cksumtype);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
=20
     if (arcfour_checksum_p(ct, crypto)) {
 	keyusage =3D usage;
-	usage2arcfour(context, &keyusage);
+	_krb5_usage2arcfour(context, &keyusage);
     } else
 	keyusage =3D CHECKSUM_USAGE(usage);
=20
@@ -1979,82 +549,87 @@
 			   data, len, cksum);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_get_checksum_type(krb5_context context,
                               krb5_crypto crypto,
 			      krb5_cksumtype *type)
 {
-    struct checksum_type *ct =3D NULL;
-   =20
+    struct _krb5_checksum_type *ct =3D NULL;
+
     if (crypto !=3D NULL) {
         ct =3D crypto->et->keyed_checksum;
         if (ct =3D=3D NULL)
             ct =3D crypto->et->checksum;
     }
-   =20
+
     if (ct =3D=3D NULL) {
-	krb5_set_error_string (context, "checksum type not found");
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type not found", ""));
         return KRB5_PROG_SUMTYPE_NOSUPP;
-    }   =20
+    }
=20
     *type =3D ct->type;
-   =20
-    return 0;     =20
+
+    return 0;
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_checksumsize(krb5_context context,
 		  krb5_cksumtype type,
 		  size_t *size)
 {
-    struct checksum_type *ct =3D _find_checksum(type);
+    struct _krb5_checksum_type *ct =3D _krb5_find_checksum(type);
     if(ct =3D=3D NULL) {
-	krb5_set_error_string (context, "checksum type %d not supported",
-			       type);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type %d not supported", ""),
+				type);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     *size =3D ct->checksumsize;
     return 0;
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_checksum_is_keyed(krb5_context context,
 		       krb5_cksumtype type)
 {
-    struct checksum_type *ct =3D _find_checksum(type);
+    struct _krb5_checksum_type *ct =3D _krb5_find_checksum(type);
     if(ct =3D=3D NULL) {
 	if (context)
-	    krb5_set_error_string (context, "checksum type %d not supported",
-				   type);
+	    krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				    N_("checksum type %d not supported", ""),
+				    type);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     return ct->flags & F_KEYED;
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_checksum_is_collision_proof(krb5_context context,
 				 krb5_cksumtype type)
 {
-    struct checksum_type *ct =3D _find_checksum(type);
+    struct _krb5_checksum_type *ct =3D _krb5_find_checksum(type);
     if(ct =3D=3D NULL) {
 	if (context)
-	    krb5_set_error_string (context, "checksum type %d not supported",
-				   type);
+	    krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				    N_("checksum type %d not supported", ""),
+				    type);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     return ct->flags & F_CPROOF;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_checksum_disable(krb5_context context,
 		      krb5_cksumtype type)
 {
-    struct checksum_type *ct =3D _find_checksum(type);
+    struct _krb5_checksum_type *ct =3D _krb5_find_checksum(type);
     if(ct =3D=3D NULL) {
 	if (context)
-	    krb5_set_error_string (context, "checksum type %d not supported",
-				   type);
+	    krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				    N_("checksum type %d not supported", ""),
+				    type);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     ct->flags |=3D F_DISABLED;
@@ -2065,912 +640,157 @@
  *                                                          *
  ************************************************************/
=20
-static krb5_error_code
-NULL_encrypt(krb5_context context,
-	     struct key_data *key,=20
-	     void *data,=20
-	     size_t len,=20
-	     krb5_boolean encryptp,
-	     int usage,
-	     void *ivec)
-{
-    return 0;
-}
-
-static krb5_error_code
-DES_CBC_encrypt_null_ivec(krb5_context context,
-			  struct key_data *key,=20
-			  void *data,=20
-			  size_t len,=20
-			  krb5_boolean encryptp,
-			  int usage,
-			  void *ignore_ivec)
-{
-    DES_cblock ivec;
-    DES_key_schedule *s =3D key->schedule->data;
-    memset(&ivec, 0, sizeof(ivec));
-    DES_cbc_encrypt(data, data, len, s, &ivec, encryptp);
-    return 0;
-}
-
-static krb5_error_code
-DES_CBC_encrypt_key_ivec(krb5_context context,
-			 struct key_data *key,=20
-			 void *data,=20
-			 size_t len,=20
-			 krb5_boolean encryptp,
-			 int usage,
-			 void *ignore_ivec)
-{
-    DES_cblock ivec;
-    DES_key_schedule *s =3D key->schedule->data;
-    memcpy(&ivec, key->key->keyvalue.data, sizeof(ivec));
-    DES_cbc_encrypt(data, data, len, s, &ivec, encryptp);
-    return 0;
-}
-
-static krb5_error_code
-DES3_CBC_encrypt(krb5_context context,
-		 struct key_data *key,=20
-		 void *data,=20
-		 size_t len,=20
-		 krb5_boolean encryptp,
-		 int usage,
-		 void *ivec)
-{
-    DES_cblock local_ivec;
-    DES_key_schedule *s =3D key->schedule->data;
-    if(ivec =3D=3D NULL) {
-	ivec =3D &local_ivec;
-	memset(local_ivec, 0, sizeof(local_ivec));
-    }
-    DES_ede3_cbc_encrypt(data, data, len, &s[0], &s[1], &s[2], ivec, encry=
ptp);
-    return 0;
-}
-
-static krb5_error_code
-DES_CFB64_encrypt_null_ivec(krb5_context context,
-			    struct key_data *key,=20
-			    void *data,=20
-			    size_t len,=20
-			    krb5_boolean encryptp,
-			    int usage,
-			    void *ignore_ivec)
-{
-    DES_cblock ivec;
-    int num =3D 0;
-    DES_key_schedule *s =3D key->schedule->data;
-    memset(&ivec, 0, sizeof(ivec));
-
-    DES_cfb64_encrypt(data, data, len, s, &ivec, &num, encryptp);
-    return 0;
-}
-
-static krb5_error_code
-DES_PCBC_encrypt_key_ivec(krb5_context context,
-			  struct key_data *key,=20
-			  void *data,=20
-			  size_t len,=20
-			  krb5_boolean encryptp,
-			  int usage,
-			  void *ignore_ivec)
-{
-    DES_cblock ivec;
-    DES_key_schedule *s =3D key->schedule->data;
-    memcpy(&ivec, key->key->keyvalue.data, sizeof(ivec));
-
-    DES_pcbc_encrypt(data, data, len, s, &ivec, encryptp);
-    return 0;
-}
-
-/*
- * AES draft-raeburn-krb-rijndael-krb-02
- */
-
-void KRB5_LIB_FUNCTION
-_krb5_aes_cts_encrypt(const unsigned char *in, unsigned char *out,
-		      size_t len, const AES_KEY *key,
-		      unsigned char *ivec, const int encryptp)
-{
-    unsigned char tmp[AES_BLOCK_SIZE];
-    int i;
-
-    /*
-     * In the framework of kerberos, the length can never be shorter
-     * then at least one blocksize.
-     */
-
-    if (encryptp) {
-
-	while(len > AES_BLOCK_SIZE) {
-	    for (i =3D 0; i < AES_BLOCK_SIZE; i++)
-		tmp[i] =3D in[i] ^ ivec[i];
-	    AES_encrypt(tmp, out, key);
-	    memcpy(ivec, out, AES_BLOCK_SIZE);
-	    len -=3D AES_BLOCK_SIZE;
-	    in +=3D AES_BLOCK_SIZE;
-	    out +=3D AES_BLOCK_SIZE;
-	}
-
-	for (i =3D 0; i < len; i++)
-	    tmp[i] =3D in[i] ^ ivec[i];
-	for (; i < AES_BLOCK_SIZE; i++)
-	    tmp[i] =3D 0 ^ ivec[i];
-
-	AES_encrypt(tmp, out - AES_BLOCK_SIZE, key);
-
-	memcpy(out, ivec, len);
-	memcpy(ivec, out - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
-
-    } else {
-	unsigned char tmp2[AES_BLOCK_SIZE];
-	unsigned char tmp3[AES_BLOCK_SIZE];
-
-	while(len > AES_BLOCK_SIZE * 2) {
-	    memcpy(tmp, in, AES_BLOCK_SIZE);
-	    AES_decrypt(in, out, key);
-	    for (i =3D 0; i < AES_BLOCK_SIZE; i++)
-		out[i] ^=3D ivec[i];
-	    memcpy(ivec, tmp, AES_BLOCK_SIZE);
-	    len -=3D AES_BLOCK_SIZE;
-	    in +=3D AES_BLOCK_SIZE;
-	    out +=3D AES_BLOCK_SIZE;
-	}
-
-	len -=3D AES_BLOCK_SIZE;
-
-	memcpy(tmp, in, AES_BLOCK_SIZE); /* save last iv */
-	AES_decrypt(in, tmp2, key);
-
-	memcpy(tmp3, in + AES_BLOCK_SIZE, len);
-	memcpy(tmp3 + len, tmp2 + len, AES_BLOCK_SIZE - len); /* xor 0 */
-
-	for (i =3D 0; i < len; i++)
-	    out[i + AES_BLOCK_SIZE] =3D tmp2[i] ^ tmp3[i];
-
-	AES_decrypt(tmp3, out, key);
-	for (i =3D 0; i < AES_BLOCK_SIZE; i++)
-	    out[i] ^=3D ivec[i];
-	memcpy(ivec, tmp, AES_BLOCK_SIZE);
-    }
-}
-
-static krb5_error_code
-AES_CTS_encrypt(krb5_context context,
-		struct key_data *key,
-		void *data,
-		size_t len,
-		krb5_boolean encryptp,
-		int usage,
-		void *ivec)
-{
-    struct krb5_aes_schedule *aeskey =3D key->schedule->data;
-    char local_ivec[AES_BLOCK_SIZE];
-    AES_KEY *k;
-
-    if (encryptp)
-	k =3D &aeskey->ekey;
-    else
-	k =3D &aeskey->dkey;
-   =20
-    if (len < AES_BLOCK_SIZE)
-	krb5_abortx(context, "invalid use of AES_CTS_encrypt");
-    if (len =3D=3D AES_BLOCK_SIZE) {
-	if (encryptp)
-	    AES_encrypt(data, data, k);
-	else
-	    AES_decrypt(data, data, k);
-    } else {
-	if(ivec =3D=3D NULL) {
-	    memset(local_ivec, 0, sizeof(local_ivec));
-	    ivec =3D local_ivec;
-	}
-	_krb5_aes_cts_encrypt(data, data, len, k, ivec, encryptp);
-    }
-
-    return 0;
-}
-
-/*
- * section 6 of draft-brezak-win2k-krb-rc4-hmac-03
- *
- * warning: not for small children
- */
-
-static krb5_error_code
-ARCFOUR_subencrypt(krb5_context context,
-		   struct key_data *key,
-		   void *data,
-		   size_t len,
-		   unsigned usage,
-		   void *ivec)
-{
-    struct checksum_type *c =3D _find_checksum (CKSUMTYPE_RSA_MD5);
-    Checksum k1_c, k2_c, k3_c, cksum;
-    struct key_data ke;
-    krb5_keyblock kb;
-    unsigned char t[4];
-    RC4_KEY rc4_key;
-    unsigned char *cdata =3D data;
-    unsigned char k1_c_data[16], k2_c_data[16], k3_c_data[16];
-    krb5_error_code ret;
-
-    t[0] =3D (usage >>  0) & 0xFF;
-    t[1] =3D (usage >>  8) & 0xFF;
-    t[2] =3D (usage >> 16) & 0xFF;
-    t[3] =3D (usage >> 24) & 0xFF;
-
-    k1_c.checksum.length =3D sizeof(k1_c_data);
-    k1_c.checksum.data   =3D k1_c_data;
-
-    ret =3D hmac(NULL, c, t, sizeof(t), 0, key, &k1_c);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-
-    memcpy (k2_c_data, k1_c_data, sizeof(k1_c_data));
-
-    k2_c.checksum.length =3D sizeof(k2_c_data);
-    k2_c.checksum.data   =3D k2_c_data;
-
-    ke.key =3D &kb;
-    kb.keyvalue =3D k2_c.checksum;
-
-    cksum.checksum.length =3D 16;
-    cksum.checksum.data   =3D data;
-
-    ret =3D hmac(NULL, c, cdata + 16, len - 16, 0, &ke, &cksum);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-
-    ke.key =3D &kb;
-    kb.keyvalue =3D k1_c.checksum;
-
-    k3_c.checksum.length =3D sizeof(k3_c_data);
-    k3_c.checksum.data   =3D k3_c_data;
-
-    ret =3D hmac(NULL, c, data, 16, 0, &ke, &k3_c);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-
-    RC4_set_key (&rc4_key, k3_c.checksum.length, k3_c.checksum.data);
-    RC4 (&rc4_key, len - 16, cdata + 16, cdata + 16);
-    memset (k1_c_data, 0, sizeof(k1_c_data));
-    memset (k2_c_data, 0, sizeof(k2_c_data));
-    memset (k3_c_data, 0, sizeof(k3_c_data));
-    return 0;
-}
-
-static krb5_error_code
-ARCFOUR_subdecrypt(krb5_context context,
-		   struct key_data *key,
-		   void *data,
-		   size_t len,
-		   unsigned usage,
-		   void *ivec)
-{
-    struct checksum_type *c =3D _find_checksum (CKSUMTYPE_RSA_MD5);
-    Checksum k1_c, k2_c, k3_c, cksum;
-    struct key_data ke;
-    krb5_keyblock kb;
-    unsigned char t[4];
-    RC4_KEY rc4_key;
-    unsigned char *cdata =3D data;
-    unsigned char k1_c_data[16], k2_c_data[16], k3_c_data[16];
-    unsigned char cksum_data[16];
-    krb5_error_code ret;
-
-    t[0] =3D (usage >>  0) & 0xFF;
-    t[1] =3D (usage >>  8) & 0xFF;
-    t[2] =3D (usage >> 16) & 0xFF;
-    t[3] =3D (usage >> 24) & 0xFF;
-
-    k1_c.checksum.length =3D sizeof(k1_c_data);
-    k1_c.checksum.data   =3D k1_c_data;
-
-    ret =3D hmac(NULL, c, t, sizeof(t), 0, key, &k1_c);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-
-    memcpy (k2_c_data, k1_c_data, sizeof(k1_c_data));
-
-    k2_c.checksum.length =3D sizeof(k2_c_data);
-    k2_c.checksum.data   =3D k2_c_data;
-
-    ke.key =3D &kb;
-    kb.keyvalue =3D k1_c.checksum;
-
-    k3_c.checksum.length =3D sizeof(k3_c_data);
-    k3_c.checksum.data   =3D k3_c_data;
-
-    ret =3D hmac(NULL, c, cdata, 16, 0, &ke, &k3_c);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-
-    RC4_set_key (&rc4_key, k3_c.checksum.length, k3_c.checksum.data);
-    RC4 (&rc4_key, len - 16, cdata + 16, cdata + 16);
-
-    ke.key =3D &kb;
-    kb.keyvalue =3D k2_c.checksum;
-
-    cksum.checksum.length =3D 16;
-    cksum.checksum.data   =3D cksum_data;
-
-    ret =3D hmac(NULL, c, cdata + 16, len - 16, 0, &ke, &cksum);
-    if (ret)
-	krb5_abortx(context, "hmac failed");
-
-    memset (k1_c_data, 0, sizeof(k1_c_data));
-    memset (k2_c_data, 0, sizeof(k2_c_data));
-    memset (k3_c_data, 0, sizeof(k3_c_data));
-
-    if (memcmp (cksum.checksum.data, data, 16) !=3D 0) {
-	krb5_clear_error_string (context);
-	return KRB5KRB_AP_ERR_BAD_INTEGRITY;
-    } else {
-	return 0;
-    }
-}
-
-/*
- * convert the usage numbers used in
- * draft-ietf-cat-kerb-key-derivation-00.txt to the ones in
- * draft-brezak-win2k-krb-rc4-hmac-04.txt
- */
-
-static krb5_error_code
-usage2arcfour (krb5_context context, unsigned *usage)
-{
-    switch (*usage) {
-    case KRB5_KU_AS_REP_ENC_PART : /* 3 */
-    case KRB5_KU_TGS_REP_ENC_PART_SUB_KEY : /* 9 */
-	*usage =3D 8;
-	return 0;
-    case KRB5_KU_USAGE_SEAL :  /* 22 */
-	*usage =3D 13;
-	return 0;
-    case KRB5_KU_USAGE_SIGN : /* 23 */
-        *usage =3D 15;
-        return 0;
-    case KRB5_KU_USAGE_SEQ: /* 24 */
-	*usage =3D 0;
-	return 0;
-    default :
-	return 0;
-    }
-}
-
-static krb5_error_code
-ARCFOUR_encrypt(krb5_context context,
-		struct key_data *key,
-		void *data,
-		size_t len,
-		krb5_boolean encryptp,
-		int usage,
-		void *ivec)
-{
-    krb5_error_code ret;
-    unsigned keyusage =3D usage;
-
-    if((ret =3D usage2arcfour (context, &keyusage)) !=3D 0)
-	return ret;
-
-    if (encryptp)
-	return ARCFOUR_subencrypt (context, key, data, len, keyusage, ivec);
-    else
-	return ARCFOUR_subdecrypt (context, key, data, len, keyusage, ivec);
-}
-
-
-/*
- *
- */
-
-static krb5_error_code
-AES_PRF(krb5_context context,
-	krb5_crypto crypto,
-	const krb5_data *in,
-	krb5_data *out)
-{
-    struct checksum_type *ct =3D crypto->et->checksum;
-    krb5_error_code ret;
-    Checksum result;
-    krb5_keyblock *derived;
-
-    result.cksumtype =3D ct->type;
-    ret =3D krb5_data_alloc(&result.checksum, ct->checksumsize);
-    if (ret) {
-	krb5_set_error_string(context, "out memory");
-	return ret;
-    }
-
-    (*ct->checksum)(context, NULL, in->data, in->length, 0, &result);
-
-    if (result.checksum.length < crypto->et->blocksize)
-	krb5_abortx(context, "internal prf error");
-
-    derived =3D NULL;
-    ret =3D krb5_derive_key(context, crypto->key.key,=20
-			  crypto->et->type, "prf", 3, &derived);
-    if (ret)
-	krb5_abortx(context, "krb5_derive_key");
-
-    ret =3D krb5_data_alloc(out, crypto->et->blocksize);
-    if (ret)
-	krb5_abortx(context, "malloc failed");
-   =20
-    {=20
-	AES_KEY key;
-
-	AES_set_encrypt_key(derived->keyvalue.data,=20
-			    crypto->et->keytype->bits, &key);
-	AES_encrypt(result.checksum.data, out->data, &key);
-	memset(&key, 0, sizeof(key));
-    }
-
-    krb5_data_free(&result.checksum);
-    krb5_free_keyblock(context, derived);
-
-    return ret;
-}
-
-/*
- * these should currently be in reverse preference order.
- * (only relevant for !F_PSEUDO) */
-
-static struct encryption_type enctype_null =3D {
-    ETYPE_NULL,
-    "null",
-    NULL,
-    1,
-    1,
-    0,
-    &keytype_null,
-    &checksum_none,
-    NULL,
-    F_DISABLED,
-    NULL_encrypt,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des_cbc_crc =3D {
-    ETYPE_DES_CBC_CRC,
-    "des-cbc-crc",
-    NULL,
-    8,
-    8,
-    8,
-    &keytype_des,
-    &checksum_crc32,
-    NULL,
-    0,
-    DES_CBC_encrypt_key_ivec,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des_cbc_md4 =3D {
-    ETYPE_DES_CBC_MD4,
-    "des-cbc-md4",
-    NULL,
-    8,
-    8,
-    8,
-    &keytype_des,
-    &checksum_rsa_md4,
-    &checksum_rsa_md4_des,
-    0,
-    DES_CBC_encrypt_null_ivec,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des_cbc_md5 =3D {
-    ETYPE_DES_CBC_MD5,
-    "des-cbc-md5",
-    NULL,
-    8,
-    8,
-    8,
-    &keytype_des,
-    &checksum_rsa_md5,
-    &checksum_rsa_md5_des,
-    0,
-    DES_CBC_encrypt_null_ivec,
-    0,
-    NULL
-};
-static struct encryption_type enctype_arcfour_hmac_md5 =3D {
-    ETYPE_ARCFOUR_HMAC_MD5,
-    "arcfour-hmac-md5",
-    NULL,
-    1,
-    1,
-    8,
-    &keytype_arcfour,
-    &checksum_hmac_md5,
-    NULL,
-    F_SPECIAL,
-    ARCFOUR_encrypt,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des3_cbc_md5 =3D {=20
-    ETYPE_DES3_CBC_MD5,
-    "des3-cbc-md5",
-    NULL,
-    8,
-    8,
-    8,
-    &keytype_des3,
-    &checksum_rsa_md5,
-    &checksum_rsa_md5_des3,
-    0,
-    DES3_CBC_encrypt,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des3_cbc_sha1 =3D {
-    ETYPE_DES3_CBC_SHA1,
-    "des3-cbc-sha1",
-    NULL,
-    8,
-    8,
-    8,
-    &keytype_des3_derived,
-    &checksum_sha1,
-    &checksum_hmac_sha1_des3,
-    F_DERIVED,
-    DES3_CBC_encrypt,
-    0,
-    NULL
-};
-static struct encryption_type enctype_old_des3_cbc_sha1 =3D {
-    ETYPE_OLD_DES3_CBC_SHA1,
-    "old-des3-cbc-sha1",
-    NULL,
-    8,
-    8,
-    8,
-    &keytype_des3,
-    &checksum_sha1,
-    &checksum_hmac_sha1_des3,
-    0,
-    DES3_CBC_encrypt,
-    0,
-    NULL
-};
-static struct encryption_type enctype_aes128_cts_hmac_sha1 =3D {
-    ETYPE_AES128_CTS_HMAC_SHA1_96,
-    "aes128-cts-hmac-sha1-96",
-    NULL,
-    16,
-    1,
-    16,
-    &keytype_aes128,
-    &checksum_sha1,
-    &checksum_hmac_sha1_aes128,
-    F_DERIVED,
-    AES_CTS_encrypt,
-    16,
-    AES_PRF
-};
-static struct encryption_type enctype_aes256_cts_hmac_sha1 =3D {
-    ETYPE_AES256_CTS_HMAC_SHA1_96,
-    "aes256-cts-hmac-sha1-96",
-    NULL,
-    16,
-    1,
-    16,
-    &keytype_aes256,
-    &checksum_sha1,
-    &checksum_hmac_sha1_aes256,
-    F_DERIVED,
-    AES_CTS_encrypt,
-    16,
-    AES_PRF
-};
-static struct encryption_type enctype_des_cbc_none =3D {
-    ETYPE_DES_CBC_NONE,
-    "des-cbc-none",
-    NULL,
-    8,
-    8,
-    0,
-    &keytype_des,
-    &checksum_none,
-    NULL,
-    F_PSEUDO,
-    DES_CBC_encrypt_null_ivec,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des_cfb64_none =3D {
-    ETYPE_DES_CFB64_NONE,
-    "des-cfb64-none",
-    NULL,
-    1,
-    1,
-    0,
-    &keytype_des,
-    &checksum_none,
-    NULL,
-    F_PSEUDO,
-    DES_CFB64_encrypt_null_ivec,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des_pcbc_none =3D {
-    ETYPE_DES_PCBC_NONE,
-    "des-pcbc-none",
-    NULL,
-    8,
-    8,
-    0,
-    &keytype_des,
-    &checksum_none,
-    NULL,
-    F_PSEUDO,
-    DES_PCBC_encrypt_key_ivec,
-    0,
-    NULL
-};
-static struct encryption_type enctype_des3_cbc_none =3D {
-    ETYPE_DES3_CBC_NONE,
-    "des3-cbc-none",
-    NULL,
-    8,
-    8,
-    0,
-    &keytype_des3_derived,
-    &checksum_none,
-    NULL,
-    F_PSEUDO,
-    DES3_CBC_encrypt,
-    0,
-    NULL
-};
-
-static struct encryption_type *etypes[] =3D {
-    &enctype_null,
-    &enctype_des_cbc_crc,
-    &enctype_des_cbc_md4,
-    &enctype_des_cbc_md5,
-    &enctype_arcfour_hmac_md5,
-    &enctype_des3_cbc_md5,=20
-    &enctype_des3_cbc_sha1,
-    &enctype_old_des3_cbc_sha1,
-    &enctype_aes128_cts_hmac_sha1,
-    &enctype_aes256_cts_hmac_sha1,
-    &enctype_des_cbc_none,
-    &enctype_des_cfb64_none,
-    &enctype_des_pcbc_none,
-    &enctype_des3_cbc_none
-};
-
-static unsigned num_etypes =3D sizeof(etypes) / sizeof(etypes[0]);
-
-
-static struct encryption_type *
-_find_enctype(krb5_enctype type)
+struct _krb5_encryption_type *
+_krb5_find_enctype(krb5_enctype type)
 {
     int i;
-    for(i =3D 0; i < num_etypes; i++)
-	if(etypes[i]->type =3D=3D type)
-	    return etypes[i];
+    for(i =3D 0; i < _krb5_num_etypes; i++)
+	if(_krb5_etypes[i]->type =3D=3D type)
+	    return _krb5_etypes[i];
     return NULL;
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_to_string(krb5_context context,
 		       krb5_enctype etype,
 		       char **string)
 {
-    struct encryption_type *e;
-    e =3D _find_enctype(etype);
+    struct _krb5_encryption_type *e;
+    e =3D _krb5_find_enctype(etype);
     if(e =3D=3D NULL) {
-	krb5_set_error_string (context, "encryption type %d not supported",
-			       etype);
+	krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+				N_("encryption type %d not supported", ""),
+				etype);
 	*string =3D NULL;
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
     *string =3D strdup(e->name);
     if(*string =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_enctype(krb5_context context,
 		       const char *string,
 		       krb5_enctype *etype)
 {
     int i;
-    for(i =3D 0; i < num_etypes; i++)
-	if(strcasecmp(etypes[i]->name, string) =3D=3D 0){
-	    *etype =3D etypes[i]->type;
+    for(i =3D 0; i < _krb5_num_etypes; i++)
+	if(strcasecmp(_krb5_etypes[i]->name, string) =3D=3D 0){
+	    *etype =3D _krb5_etypes[i]->type;
 	    return 0;
 	}
-    krb5_set_error_string (context, "encryption type %s not supported",
-			   string);
+    krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+			    N_("encryption type %s not supported", ""),
+			    string);
     return KRB5_PROG_ETYPE_NOSUPP;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_enctype_to_oid(krb5_context context,
-		    krb5_enctype etype,
-		    heim_oid *oid)
-{
-    struct encryption_type *et =3D _find_enctype(etype);
-    if(et =3D=3D NULL) {
-	krb5_set_error_string (context, "encryption type %d not supported",
-			       etype);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    if(et->oid =3D=3D NULL) {
-	krb5_set_error_string (context, "%s have not oid", et->name);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    krb5_clear_error_string(context);
-    return der_copy_oid(et->oid, oid);
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_oid_to_enctype(krb5_context context,
-		     const heim_oid *oid,
-		     krb5_enctype *etype)
-{
-    int i;
-    for(i =3D 0; i < num_etypes; i++) {
-	if(etypes[i]->oid && der_heim_oid_cmp(etypes[i]->oid, oid) =3D=3D 0) {
-	    *etype =3D etypes[i]->type;
-	    return 0;
-	}
-    }
-    krb5_set_error_string(context, "enctype for oid not supported");
-    return KRB5_PROG_ETYPE_NOSUPP;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_to_keytype(krb5_context context,
 			krb5_enctype etype,
 			krb5_keytype *keytype)
 {
-    struct encryption_type *e =3D _find_enctype(etype);
+    struct _krb5_encryption_type *e =3D _krb5_find_enctype(etype);
     if(e =3D=3D NULL) {
-	krb5_set_error_string (context, "encryption type %d not supported",
-			       etype);
-	return KRB5_PROG_ETYPE_NOSUPP;
+        return unsupported_enctype (context, etype);
     }
     *keytype =3D e->keytype->type; /* XXX */
     return 0;
 }
=20
-#if 0
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_keytype_to_enctype(krb5_context context,
-			krb5_keytype keytype,
-			krb5_enctype *etype)
+/**
+ * Check if a enctype is valid, return 0 if it is.
+ *
+ * @param context Kerberos context
+ * @param etype enctype to check if its valid or not
+ *
+ * @return Return an error code for an failure or 0 on success (enctype va=
lid).
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_valid(krb5_context context,
+		   krb5_enctype etype)
 {
-    struct key_type *kt =3D _find_keytype(keytype);
-    krb5_warnx(context, "krb5_keytype_to_enctype(%u)", keytype);
-    if(kt =3D=3D NULL)
-	return KRB5_PROG_KEYTYPE_NOSUPP;
-    *etype =3D kt->best_etype;
-    return 0;
+    struct _krb5_encryption_type *e =3D _krb5_find_enctype(etype);
+    if(e && (e->flags & F_DISABLED) =3D=3D 0)
+	return 0;
+    if (context =3D=3D NULL)
+	return KRB5_PROG_ETYPE_NOSUPP;
+    if(e =3D=3D NULL) {
+        return unsupported_enctype (context, etype);
+    }
+    /* Must be (e->flags & F_DISABLED) */
+    krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+			    N_("encryption type %s is disabled", ""),
+			    e->name);
+    return KRB5_PROG_ETYPE_NOSUPP;
 }
-#endif
-   =20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_keytype_to_enctypes (krb5_context context,
-			  krb5_keytype keytype,
-			  unsigned *len,
-			  krb5_enctype **val)
+
+/**
+ * Return the coresponding encryption type for a checksum type.
+ *
+ * @param context Kerberos context
+ * @param ctype The checksum type to get the result enctype for
+ * @param etype The returned encryption, when the matching etype is
+ * not found, etype is set to ETYPE_NULL.
+ *
+ * @return Return an error code for an failure or 0 on success.
+ * @ingroup krb5_crypto
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cksumtype_to_enctype(krb5_context context,
+			  krb5_cksumtype ctype,
+			  krb5_enctype *etype)
 {
     int i;
-    unsigned n =3D 0;
-    krb5_enctype *ret;
=20
-    for (i =3D num_etypes - 1; i >=3D 0; --i) {
-	if (etypes[i]->keytype->type =3D=3D keytype
-	    && !(etypes[i]->flags & F_PSEUDO))
-	    ++n;
+    *etype =3D ETYPE_NULL;
+
+    for(i =3D 0; i < _krb5_num_etypes; i++) {
+	if(_krb5_etypes[i]->keyed_checksum &&
+	   _krb5_etypes[i]->keyed_checksum->type =3D=3D ctype)
+	    {
+		*etype =3D _krb5_etypes[i]->type;
+		return 0;
+	    }
     }
-    ret =3D malloc(n * sizeof(*ret));
-    if (ret =3D=3D NULL && n !=3D 0) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    n =3D 0;
-    for (i =3D num_etypes - 1; i >=3D 0; --i) {
-	if (etypes[i]->keytype->type =3D=3D keytype
-	    && !(etypes[i]->flags & F_PSEUDO))
-	    ret[n++] =3D etypes[i]->type;
-    }
-    *len =3D n;
-    *val =3D ret;
-    return 0;
+
+    krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+			    N_("checksum type %d not supported", ""),
+			    (int)ctype);
+    return KRB5_PROG_SUMTYPE_NOSUPP;
 }
=20
-/*
- * First take the configured list of etypes for `keytype' if available,
- * else, do `krb5_keytype_to_enctypes'.
- */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_keytype_to_enctypes_default (krb5_context context,
-				  krb5_keytype keytype,
-				  unsigned *len,
-				  krb5_enctype **val)
-{
-    int i, n;
-    krb5_enctype *ret;
-
-    if (keytype !=3D KEYTYPE_DES || context->etypes_des =3D=3D NULL)
-	return krb5_keytype_to_enctypes (context, keytype, len, val);
-
-    for (n =3D 0; context->etypes_des[n]; ++n)
-	;
-    ret =3D malloc (n * sizeof(*ret));
-    if (ret =3D=3D NULL && n !=3D 0) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    for (i =3D 0; i < n; ++i)
-	ret[i] =3D context->etypes_des[i];
-    *len =3D n;
-    *val =3D ret;
-    return 0;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_enctype_valid(krb5_context context,=20
-		 krb5_enctype etype)
-{
-    struct encryption_type *e =3D _find_enctype(etype);
-    if(e =3D=3D NULL) {
-	krb5_set_error_string (context, "encryption type %d not supported",
-			       etype);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    if (e->flags & F_DISABLED) {
-	krb5_set_error_string (context, "encryption type %s is disabled",
-			       e->name);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    return 0;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cksumtype_valid(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cksumtype_valid(krb5_context context,
 		     krb5_cksumtype ctype)
 {
-    struct checksum_type *c =3D _find_checksum(ctype);
+    struct _krb5_checksum_type *c =3D _krb5_find_checksum(ctype);
     if (c =3D=3D NULL) {
-	krb5_set_error_string (context, "checksum type %d not supported",
-			       ctype);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type %d not supported", ""),
+				ctype);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     if (c->flags & F_DISABLED) {
-	krb5_set_error_string (context, "checksum type %s is disabled",
-			       c->name);
+	krb5_set_error_message (context, KRB5_PROG_SUMTYPE_NOSUPP,
+				N_("checksum type %s is disabled", ""),
+				c->name);
 	return KRB5_PROG_SUMTYPE_NOSUPP;
     }
     return 0;
 }
=20
=20
-/* if two enctypes have compatible keys */
-krb5_boolean KRB5_LIB_FUNCTION
-krb5_enctypes_compatible_keys(krb5_context context,
-			      krb5_enctype etype1,
-			      krb5_enctype etype2)
-{
-    struct encryption_type *e1 =3D _find_enctype(etype1);
-    struct encryption_type *e2 =3D _find_enctype(etype2);
-    return e1 !=3D NULL && e2 !=3D NULL && e1->keytype =3D=3D e2->keytype;
-}
-
 static krb5_boolean
 derived_crypto(krb5_context context,
 	       krb5_crypto crypto)
@@ -3001,9 +821,9 @@
     Checksum cksum;
     unsigned char *p, *q;
     krb5_error_code ret;
-    struct key_data *dkey;
-    const struct encryption_type *et =3D crypto->et;
-   =20
+    struct _krb5_key_data *dkey;
+    const struct _krb5_encryption_type *et =3D crypto->et;
+
     checksum_sz =3D CHECKSUMSIZE(et->keyed_checksum);
=20
     sz =3D et->confoundersize + len;
@@ -3011,25 +831,25 @@
     total_sz =3D block_sz + checksum_sz;
     p =3D calloc(1, total_sz);
     if(p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
-   =20
+
     q =3D p;
     krb5_generate_random_block(q, et->confoundersize); /* XXX */
     q +=3D et->confoundersize;
     memcpy(q, data, len);
-   =20
-    ret =3D create_checksum(context,=20
+
+    ret =3D create_checksum(context,
 			  et->keyed_checksum,
-			  crypto,=20
+			  crypto,
 			  INTEGRITY_USAGE(usage),
-			  p,=20
+			  p,
 			  block_sz,
 			  &cksum);
     if(ret =3D=3D 0 && cksum.checksum.length !=3D checksum_sz) {
 	free_Checksum (&cksum);
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	ret =3D KRB5_CRYPTO_INTERNAL;
     }
     if(ret)
@@ -3042,9 +862,6 @@
     ret =3D _key_schedule(context, dkey);
     if(ret)
 	goto fail;
-#ifdef CRYPTO_DEBUG
-    krb5_crypto_debug(context, 1, block_sz, dkey->key);
-#endif
     ret =3D (*et->encrypt)(context, dkey, p, block_sz, 1, usage, ivec);
     if (ret)
 	goto fail;
@@ -3070,18 +887,18 @@
     Checksum cksum;
     unsigned char *p, *q;
     krb5_error_code ret;
-    const struct encryption_type *et =3D crypto->et;
-   =20
+    const struct _krb5_encryption_type *et =3D crypto->et;
+
     checksum_sz =3D CHECKSUMSIZE(et->checksum);
-   =20
+
     sz =3D et->confoundersize + checksum_sz + len;
     block_sz =3D (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */
     p =3D calloc(1, block_sz);
     if(p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
-   =20
+
     q =3D p;
     krb5_generate_random_block(q, et->confoundersize); /* XXX */
     q +=3D et->confoundersize;
@@ -3089,15 +906,15 @@
     q +=3D checksum_sz;
     memcpy(q, data, len);
=20
-    ret =3D create_checksum(context,=20
+    ret =3D create_checksum(context,
 			  et->checksum,
 			  crypto,
 			  0,
-			  p,=20
+			  p,
 			  block_sz,
 			  &cksum);
     if(ret =3D=3D 0 && cksum.checksum.length !=3D checksum_sz) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	free_Checksum(&cksum);
 	ret =3D KRB5_CRYPTO_INTERNAL;
     }
@@ -3108,9 +925,6 @@
     ret =3D _key_schedule(context, &crypto->key);
     if(ret)
 	goto fail;
-#ifdef CRYPTO_DEBUG
-    krb5_crypto_debug(context, 1, block_sz, crypto->key.key);
-#endif
     ret =3D (*et->encrypt)(context, &crypto->key, p, block_sz, 1, 0, ivec);
     if (ret) {
 	memset(p, 0, block_sz);
@@ -3135,7 +949,7 @@
 			 krb5_data *result,
 			 void *ivec)
 {
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_encryption_type *et =3D crypto->et;
     size_t cksum_sz =3D CHECKSUMSIZE(et->checksum);
     size_t sz =3D len + cksum_sz + et->confoundersize;
     char *tmp, *p;
@@ -3143,7 +957,7 @@
=20
     tmp =3D malloc (sz);
     if (tmp =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     p =3D tmp;
@@ -3176,25 +990,26 @@
     Checksum cksum;
     unsigned char *p;
     krb5_error_code ret;
-    struct key_data *dkey;
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_key_data *dkey;
+    struct _krb5_encryption_type *et =3D crypto->et;
     unsigned long l;
-   =20
+
     checksum_sz =3D CHECKSUMSIZE(et->keyed_checksum);
     if (len < checksum_sz + et->confoundersize) {
-	krb5_set_error_string(context, "Encrypted data shorter then "
-			      "checksum + confunder");
+	krb5_set_error_message(context, KRB5_BAD_MSIZE,
+			       N_("Encrypted data shorter then "
+				  "checksum + confunder", ""));
 	return KRB5_BAD_MSIZE;
     }
=20
     if (((len - checksum_sz) % et->padsize) !=3D 0) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return KRB5_BAD_MSIZE;
     }
=20
     p =3D malloc(len);
     if(len !=3D 0 && p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memcpy(p, data, len);
@@ -3211,9 +1026,6 @@
 	free(p);
 	return ret;
     }
-#ifdef CRYPTO_DEBUG
-    krb5_crypto_debug(context, 0, len, dkey->key);
-#endif
     ret =3D (*et->encrypt)(context, dkey, p, len, 0, usage, ivec);
     if (ret) {
 	free(p);
@@ -3239,7 +1051,7 @@
     result->data =3D realloc(p, l);
     if(result->data =3D=3D NULL && l !=3D 0) {
 	free(p);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     result->length =3D l;
@@ -3258,29 +1070,32 @@
     unsigned char *p;
     Checksum cksum;
     size_t checksum_sz, l;
-    struct encryption_type *et =3D crypto->et;
-   =20
+    struct _krb5_encryption_type *et =3D crypto->et;
+
     if ((len % et->padsize) !=3D 0) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
+	return KRB5_BAD_MSIZE;
+    }
+    checksum_sz =3D CHECKSUMSIZE(et->checksum);
+    if (len < checksum_sz + et->confoundersize) {
+	krb5_set_error_message(context, KRB5_BAD_MSIZE,
+			       N_("Encrypted data shorter then "
+				  "checksum + confunder", ""));
 	return KRB5_BAD_MSIZE;
     }
=20
-    checksum_sz =3D CHECKSUMSIZE(et->checksum);
     p =3D malloc(len);
     if(len !=3D 0 && p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memcpy(p, data, len);
-   =20
+
     ret =3D _key_schedule(context, &crypto->key);
     if(ret) {
 	free(p);
 	return ret;
     }
-#ifdef CRYPTO_DEBUG
-    krb5_crypto_debug(context, 0, len, crypto->key.key);
-#endif
     ret =3D (*et->encrypt)(context, &crypto->key, p, len, 0, 0, ivec);
     if (ret) {
 	free(p);
@@ -3304,7 +1119,7 @@
     result->data =3D realloc(p, l);
     if(result->data =3D=3D NULL && l !=3D 0) {
 	free(p);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     result->length =3D l;
@@ -3320,24 +1135,30 @@
 			 krb5_data *result,
 			 void *ivec)
 {
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_encryption_type *et =3D crypto->et;
     size_t cksum_sz =3D CHECKSUMSIZE(et->checksum);
     size_t sz =3D len - cksum_sz - et->confoundersize;
     unsigned char *p;
     krb5_error_code ret;
=20
     if ((len % et->padsize) !=3D 0) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
+	return KRB5_BAD_MSIZE;
+    }
+    if (len < cksum_sz + et->confoundersize) {
+	krb5_set_error_message(context, KRB5_BAD_MSIZE,
+			       N_("Encrypted data shorter then "
+				  "checksum + confunder", ""));
 	return KRB5_BAD_MSIZE;
     }
=20
     p =3D malloc (len);
     if (p =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memcpy(p, data, len);
-   =20
+
     ret =3D (*et->encrypt)(context, &crypto->key, p, len, FALSE, usage, iv=
ec);
     if (ret) {
 	free(p);
@@ -3348,15 +1169,583 @@
     result->data =3D realloc(p, sz);
     if(result->data =3D=3D NULL && sz !=3D 0) {
 	free(p);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     result->length =3D sz;
     return 0;
 }
=20
+static krb5_crypto_iov *
+find_iv(krb5_crypto_iov *data, size_t num_data, unsigned type)
+{
+    size_t i;
+    for (i =3D 0; i < num_data; i++)
+	if (data[i].flags =3D=3D type)
+	    return &data[i];
+    return NULL;
+}
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Inline encrypt a kerberos message
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param ivec initial cbc/cts vector
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ *
+ * Kerberos encrypted data look like this:
+ *
+ * 1. KRB5_CRYPTO_TYPE_HEADER
+ * 2. array [1,...] KRB5_CRYPTO_TYPE_DATA and array [0,...]
+ *    KRB5_CRYPTO_TYPE_SIGN_ONLY in any order, however the receiver
+ *    have to aware of the order. KRB5_CRYPTO_TYPE_SIGN_ONLY is
+ *    commonly used headers and trailers.
+ * 3. KRB5_CRYPTO_TYPE_PADDING, at least on padsize long if padsize > 1
+ * 4. KRB5_CRYPTO_TYPE_TRAILER
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encrypt_iov_ivec(krb5_context context,
+		      krb5_crypto crypto,
+		      unsigned usage,
+		      krb5_crypto_iov *data,
+		      int num_data,
+		      void *ivec)
+{
+    size_t headersz, trailersz, len;
+    int i;
+    size_t sz, block_sz, pad_sz;
+    Checksum cksum;
+    unsigned char *p, *q;
+    krb5_error_code ret;
+    struct _krb5_key_data *dkey;
+    const struct _krb5_encryption_type *et =3D crypto->et;
+    krb5_crypto_iov *tiv, *piv, *hiv;
+
+    if (num_data < 0) {
+        krb5_clear_error_message(context);
+	return KRB5_CRYPTO_INTERNAL;
+    }
+
+    if(!derived_crypto(context, crypto)) {
+	krb5_clear_error_message(context);
+	return KRB5_CRYPTO_INTERNAL;
+    }
+
+    headersz =3D et->confoundersize;
+    trailersz =3D CHECKSUMSIZE(et->keyed_checksum);
+
+    for (len =3D 0, i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA)
+	    continue;
+	len +=3D data[i].data.length;
+    }
+
+    sz =3D headersz + len;
+    block_sz =3D (sz + et->padsize - 1) &~ (et->padsize - 1); /* pad */
+
+    pad_sz =3D block_sz - sz;
+
+    /* header */
+
+    hiv =3D find_iv(data, num_data, KRB5_CRYPTO_TYPE_HEADER);
+    if (hiv =3D=3D NULL || hiv->data.length !=3D headersz)
+	return KRB5_BAD_MSIZE;
+
+    krb5_generate_random_block(hiv->data.data, hiv->data.length);
+
+    /* padding */
+    piv =3D find_iv(data, num_data, KRB5_CRYPTO_TYPE_PADDING);
+    /* its ok to have no TYPE_PADDING if there is no padding */
+    if (piv =3D=3D NULL && pad_sz !=3D 0)
+	return KRB5_BAD_MSIZE;
+    if (piv) {
+	if (piv->data.length < pad_sz)
+	    return KRB5_BAD_MSIZE;
+	piv->data.length =3D pad_sz;
+	if (pad_sz)
+	    memset(piv->data.data, pad_sz, pad_sz);
+	else
+	    piv =3D NULL;
+    }
+
+    /* trailer */
+    tiv =3D find_iv(data, num_data, KRB5_CRYPTO_TYPE_TRAILER);
+    if (tiv =3D=3D NULL || tiv->data.length !=3D trailersz)
+	return KRB5_BAD_MSIZE;
+
+    /*
+     * XXX replace with EVP_Sign? at least make create_checksum an iov
+     * function.
+     * XXX CTS EVP is broken, can't handle multi buffers :(
+     */
+
+    len =3D block_sz;
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	len +=3D data[i].data.length;
+    }
+
+    p =3D q =3D malloc(len);
+
+    memcpy(q, hiv->data.data, hiv->data.length);
+    q +=3D hiv->data.length;
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA &&
+	    data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	memcpy(q, data[i].data.data, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+    if (piv)
+	memset(q, 0, piv->data.length);
+
+    ret =3D create_checksum(context,
+			  et->keyed_checksum,
+			  crypto,
+			  INTEGRITY_USAGE(usage),
+			  p,
+			  len,
+			  &cksum);
+    free(p);
+    if(ret =3D=3D 0 && cksum.checksum.length !=3D trailersz) {
+	free_Checksum (&cksum);
+	krb5_clear_error_message (context);
+	ret =3D KRB5_CRYPTO_INTERNAL;
+    }
+    if(ret)
+	return ret;
+
+    /* save cksum at end */
+    memcpy(tiv->data.data, cksum.checksum.data, cksum.checksum.length);
+    free_Checksum (&cksum);
+
+    /* XXX replace with EVP_Cipher */
+    p =3D q =3D malloc(block_sz);
+    if(p =3D=3D NULL)
+	return ENOMEM;
+
+    memcpy(q, hiv->data.data, hiv->data.length);
+    q +=3D hiv->data.length;
+
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA)
+	    continue;
+	memcpy(q, data[i].data.data, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+    if (piv)
+	memset(q, 0, piv->data.length);
+
+
+    ret =3D _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dk=
ey);
+    if(ret) {
+	free(p);
+	return ret;
+    }
+    ret =3D _key_schedule(context, dkey);
+    if(ret) {
+	free(p);
+	return ret;
+    }
+
+    ret =3D (*et->encrypt)(context, dkey, p, block_sz, 1, usage, ivec);
+    if (ret) {
+	free(p);
+	return ret;
+    }
+
+    /* now copy data back to buffers */
+    q =3D p;
+
+    memcpy(hiv->data.data, q, hiv->data.length);
+    q +=3D hiv->data.length;
+
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA)
+	    continue;
+	memcpy(data[i].data.data, q, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+    if (piv)
+	memcpy(piv->data.data, q, pad_sz);
+
+    free(p);
+
+    return ret;
+}
+
+/**
+ * Inline decrypt a Kerberos message.
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param ivec initial cbc/cts vector
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ *
+ * 1. KRB5_CRYPTO_TYPE_HEADER
+ * 2. one KRB5_CRYPTO_TYPE_DATA and array [0,...] of KRB5_CRYPTO_TYPE_SIGN=
_ONLY in
+ *  any order, however the receiver have to aware of the
+ *  order. KRB5_CRYPTO_TYPE_SIGN_ONLY is commonly used unencrypoted
+ *  protocol headers and trailers. The output data will be of same
+ *  size as the input data or shorter.
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decrypt_iov_ivec(krb5_context context,
+		      krb5_crypto crypto,
+		      unsigned usage,
+		      krb5_crypto_iov *data,
+		      unsigned int num_data,
+		      void *ivec)
+{
+    unsigned int i;
+    size_t headersz, trailersz, len;
+    Checksum cksum;
+    unsigned char *p, *q;
+    krb5_error_code ret;
+    struct _krb5_key_data *dkey;
+    struct _krb5_encryption_type *et =3D crypto->et;
+    krb5_crypto_iov *tiv, *hiv;
+
+    if(!derived_crypto(context, crypto)) {
+	krb5_clear_error_message(context);
+	return KRB5_CRYPTO_INTERNAL;
+    }
+
+    headersz =3D et->confoundersize;
+
+    hiv =3D find_iv(data, num_data, KRB5_CRYPTO_TYPE_HEADER);
+    if (hiv =3D=3D NULL || hiv->data.length !=3D headersz)
+	return KRB5_BAD_MSIZE;
+
+    /* trailer */
+    trailersz =3D CHECKSUMSIZE(et->keyed_checksum);
+
+    tiv =3D find_iv(data, num_data, KRB5_CRYPTO_TYPE_TRAILER);
+    if (tiv->data.length !=3D trailersz)
+	return KRB5_BAD_MSIZE;
+
+    /* Find length of data we will decrypt */
+
+    len =3D headersz;
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA)
+	    continue;
+	len +=3D data[i].data.length;
+    }
+
+    if ((len % et->padsize) !=3D 0) {
+	krb5_clear_error_message(context);
+	return KRB5_BAD_MSIZE;
+    }
+
+    /* XXX replace with EVP_Cipher */
+
+    p =3D q =3D malloc(len);
+    if (p =3D=3D NULL)
+	return ENOMEM;
+
+    memcpy(q, hiv->data.data, hiv->data.length);
+    q +=3D hiv->data.length;
+
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA)
+	    continue;
+	memcpy(q, data[i].data.data, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+
+    ret =3D _get_derived_key(context, crypto, ENCRYPTION_USAGE(usage), &dk=
ey);
+    if(ret) {
+	free(p);
+	return ret;
+    }
+    ret =3D _key_schedule(context, dkey);
+    if(ret) {
+	free(p);
+	return ret;
+    }
+
+    ret =3D (*et->encrypt)(context, dkey, p, len, 0, usage, ivec);
+    if (ret) {
+	free(p);
+	return ret;
+    }
+
+    /* copy data back to buffers */
+    memcpy(hiv->data.data, p, hiv->data.length);
+    q =3D p + hiv->data.length;
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA)
+	    continue;
+	memcpy(data[i].data.data, q, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+
+    free(p);
+
+    /* check signature */
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	len +=3D data[i].data.length;
+    }
+
+    p =3D q =3D malloc(len);
+    if (p =3D=3D NULL)
+	return ENOMEM;
+
+    memcpy(q, hiv->data.data, hiv->data.length);
+    q +=3D hiv->data.length;
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA &&
+	    data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	memcpy(q, data[i].data.data, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+
+    cksum.checksum.data   =3D tiv->data.data;
+    cksum.checksum.length =3D tiv->data.length;
+    cksum.cksumtype       =3D CHECKSUMTYPE(et->keyed_checksum);
+
+    ret =3D verify_checksum(context,
+			  crypto,
+			  INTEGRITY_USAGE(usage),
+			  p,
+			  len,
+			  &cksum);
+    free(p);
+    return ret;
+}
+
+/**
+ * Create a Kerberos message checksum.
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param type output data
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_create_checksum_iov(krb5_context context,
+			 krb5_crypto crypto,
+			 unsigned usage,
+			 krb5_crypto_iov *data,
+			 unsigned int num_data,
+			 krb5_cksumtype *type)
+{
+    Checksum cksum;
+    krb5_crypto_iov *civ;
+    krb5_error_code ret;
+    size_t i;
+    size_t len;
+    char *p, *q;
+
+    if(!derived_crypto(context, crypto)) {
+	krb5_clear_error_message(context);
+	return KRB5_CRYPTO_INTERNAL;
+    }
+
+    civ =3D find_iv(data, num_data, KRB5_CRYPTO_TYPE_CHECKSUM);
+    if (civ =3D=3D NULL)
+	return KRB5_BAD_MSIZE;
+
+    len =3D 0;
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA &&
+	    data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	len +=3D data[i].data.length;
+    }
+
+    p =3D q =3D malloc(len);
+
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA &&
+	    data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	memcpy(q, data[i].data.data, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+
+    ret =3D krb5_create_checksum(context, crypto, usage, 0, p, len, &cksum=
);
+    free(p);
+    if (ret)
+	return ret;
+
+    if (type)
+	*type =3D cksum.cksumtype;
+
+    if (cksum.checksum.length > civ->data.length) {
+	krb5_set_error_message(context, KRB5_BAD_MSIZE,
+			       N_("Checksum larger then input buffer", ""));
+	free_Checksum(&cksum);
+	return KRB5_BAD_MSIZE;
+    }
+
+    civ->data.length =3D cksum.checksum.length;
+    memcpy(civ->data.data, cksum.checksum.data, civ->data.length);
+    free_Checksum(&cksum);
+
+    return 0;
+}
+
+/**
+ * Verify a Kerberos message checksum.
+ *
+ * @param context Kerberos context
+ * @param crypto Kerberos crypto context
+ * @param usage Key usage for this buffer
+ * @param data array of buffers to process
+ * @param num_data length of array
+ * @param type return checksum type if not NULL
+ *
+ * @return Return an error code or 0.
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_checksum_iov(krb5_context context,
+			 krb5_crypto crypto,
+			 unsigned usage,
+			 krb5_crypto_iov *data,
+			 unsigned int num_data,
+			 krb5_cksumtype *type)
+{
+    struct _krb5_encryption_type *et =3D crypto->et;
+    Checksum cksum;
+    krb5_crypto_iov *civ;
+    krb5_error_code ret;
+    size_t i;
+    size_t len;
+    char *p, *q;
+
+    if(!derived_crypto(context, crypto)) {
+	krb5_clear_error_message(context);
+	return KRB5_CRYPTO_INTERNAL;
+    }
+
+    civ =3D find_iv(data, num_data, KRB5_CRYPTO_TYPE_CHECKSUM);
+    if (civ =3D=3D NULL)
+	return KRB5_BAD_MSIZE;
+
+    len =3D 0;
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA &&
+	    data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	len +=3D data[i].data.length;
+    }
+
+    p =3D q =3D malloc(len);
+
+    for (i =3D 0; i < num_data; i++) {
+	if (data[i].flags !=3D KRB5_CRYPTO_TYPE_DATA &&
+	    data[i].flags !=3D KRB5_CRYPTO_TYPE_SIGN_ONLY)
+	    continue;
+	memcpy(q, data[i].data.data, data[i].data.length);
+	q +=3D data[i].data.length;
+    }
+
+    cksum.cksumtype =3D CHECKSUMTYPE(et->keyed_checksum);
+    cksum.checksum.length =3D civ->data.length;
+    cksum.checksum.data =3D civ->data.data;
+
+    ret =3D krb5_verify_checksum(context, crypto, usage, p, len, &cksum);
+    free(p);
+
+    if (ret =3D=3D 0 && type)
+	*type =3D cksum.cksumtype;
+
+    return ret;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_length(krb5_context context,
+		   krb5_crypto crypto,
+		   int type,
+		   size_t *len)
+{
+    if (!derived_crypto(context, crypto)) {
+	krb5_set_error_message(context, EINVAL, "not a derived crypto");
+	return EINVAL;
+    }
+
+    switch(type) {
+    case KRB5_CRYPTO_TYPE_EMPTY:
+	*len =3D 0;
+	return 0;
+    case KRB5_CRYPTO_TYPE_HEADER:
+	*len =3D crypto->et->blocksize;
+	return 0;
+    case KRB5_CRYPTO_TYPE_DATA:
+    case KRB5_CRYPTO_TYPE_SIGN_ONLY:
+	/* len must already been filled in */
+	return 0;
+    case KRB5_CRYPTO_TYPE_PADDING:
+	if (crypto->et->padsize > 1)
+	    *len =3D crypto->et->padsize;
+	else
+	    *len =3D 0;
+	return 0;
+    case KRB5_CRYPTO_TYPE_TRAILER:
+	*len =3D CHECKSUMSIZE(crypto->et->keyed_checksum);
+	return 0;
+    case KRB5_CRYPTO_TYPE_CHECKSUM:
+	if (crypto->et->keyed_checksum)
+	    *len =3D CHECKSUMSIZE(crypto->et->keyed_checksum);
+	else
+	    *len =3D CHECKSUMSIZE(crypto->et->checksum);
+	return 0;
+    }
+    krb5_set_error_message(context, EINVAL,
+			   "%d not a supported type", type);
+    return EINVAL;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_length_iov(krb5_context context,
+		       krb5_crypto crypto,
+		       krb5_crypto_iov *data,
+		       unsigned int num_data)
+{
+    krb5_error_code ret;
+    size_t i;
+
+    for (i =3D 0; i < num_data; i++) {
+	ret =3D krb5_crypto_length(context, crypto,
+				 data[i].flags,
+				 &data[i].data.length);
+	if (ret)
+	    return ret;
+    }
+    return 0;
+}
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encrypt_ivec(krb5_context context,
 		  krb5_crypto crypto,
 		  unsigned usage,
@@ -3366,7 +1755,7 @@
 		  void *ivec)
 {
     if(derived_crypto(context, crypto))
-	return encrypt_internal_derived(context, crypto, usage,=20
+	return encrypt_internal_derived(context, crypto, usage,
 					data, len, result, ivec);
     else if (special_crypto(context, crypto))
 	return encrypt_internal_special (context, crypto, usage,
@@ -3375,7 +1764,7 @@
 	return encrypt_internal(context, crypto, data, len, result, ivec);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encrypt(krb5_context context,
 	     krb5_crypto crypto,
 	     unsigned usage,
@@ -3386,7 +1775,7 @@
     return krb5_encrypt_ivec(context, crypto, usage, data, len, result, NU=
LL);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encrypt_EncryptedData(krb5_context context,
 			   krb5_crypto crypto,
 			   unsigned usage,
@@ -3404,7 +1793,7 @@
     return krb5_encrypt(context, crypto, usage, data, len, &result->cipher=
);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt_ivec(krb5_context context,
 		  krb5_crypto crypto,
 		  unsigned usage,
@@ -3414,7 +1803,7 @@
 		  void *ivec)
 {
     if(derived_crypto(context, crypto))
-	return decrypt_internal_derived(context, crypto, usage,=20
+	return decrypt_internal_derived(context, crypto, usage,
 					data, len, result, ivec);
     else if (special_crypto (context, crypto))
 	return decrypt_internal_special(context, crypto, usage,
@@ -3423,7 +1812,7 @@
 	return decrypt_internal(context, crypto, data, len, result, ivec);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt(krb5_context context,
 	     krb5_crypto crypto,
 	     unsigned usage,
@@ -3435,14 +1824,14 @@
 			      NULL);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt_EncryptedData(krb5_context context,
 			   krb5_crypto crypto,
 			   unsigned usage,
 			   const EncryptedData *e,
 			   krb5_data *result)
 {
-    return krb5_decrypt(context, crypto, usage,=20
+    return krb5_decrypt(context, crypto, usage,
 			e->cipher.data, e->cipher.length, result);
 }
=20
@@ -3450,96 +1839,17 @@
  *                                                          *
  ************************************************************/
=20
-#define ENTROPY_NEEDED 128
-
-static int
-seed_something(void)
+krb5_error_code
+_krb5_derive_key(krb5_context context,
+		 struct _krb5_encryption_type *et,
+		 struct _krb5_key_data *key,
+		 const void *constant,
+		 size_t len)
 {
-    char buf[1024], seedfile[256];
-
-    /* If there is a seed file, load it. But such a file cannot be trusted,
-       so use 0 for the entropy estimate */
-    if (RAND_file_name(seedfile, sizeof(seedfile))) {
-	int fd;
-	fd =3D open(seedfile, O_RDONLY);
-	if (fd >=3D 0) {
-	    ssize_t ret;
-	    ret =3D read(fd, buf, sizeof(buf));
-	    if (ret > 0)
-		RAND_add(buf, ret, 0.0);
-	    close(fd);
-	} else
-	    seedfile[0] =3D '\0';
-    } else
-	seedfile[0] =3D '\0';
-
-    /* Calling RAND_status() will try to use /dev/urandom if it exists so
-       we do not have to deal with it. */
-    if (RAND_status() !=3D 1) {
-	krb5_context context;
-	const char *p;
-
-	/* Try using egd */
-	if (!krb5_init_context(&context)) {
-	    p =3D krb5_config_get_string(context, NULL, "libdefaults",
-		"egd_socket", NULL);
-	    if (p !=3D NULL)
-		RAND_egd_bytes(p, ENTROPY_NEEDED);
-	    krb5_free_context(context);
-	}
-    }
-   =20
-    if (RAND_status() =3D=3D 1)	{
-	/* Update the seed file */
-	if (seedfile[0])
-	    RAND_write_file(seedfile);
-
-	return 0;
-    } else
-	return -1;
-}
-
-void KRB5_LIB_FUNCTION
-krb5_generate_random_block(void *buf, size_t len)
-{
-    static int rng_initialized =3D 0;
-   =20
-    HEIMDAL_MUTEX_lock(&crypto_mutex);
-    if (!rng_initialized) {
-	if (seed_something())
-	    krb5_abortx(NULL, "Fatal: could not seed the "
-			"random number generator");
-=09
-	rng_initialized =3D 1;
-    }
-    HEIMDAL_MUTEX_unlock(&crypto_mutex);
-    if (RAND_bytes(buf, len) !=3D 1)
-	krb5_abortx(NULL, "Failed to generate random block");
-}
-
-static void
-DES3_postproc(krb5_context context,
-	      unsigned char *k, size_t len, struct key_data *key)
-{
-    DES3_random_to_key(context, key->key, k, len);
-
-    if (key->schedule) {
-	krb5_free_data(context, key->schedule);
-	key->schedule =3D NULL;
-    }
-}
-
-static krb5_error_code
-derive_key(krb5_context context,
-	   struct encryption_type *et,
-	   struct key_data *key,
-	   const void *constant,
-	   size_t len)
-{
-    unsigned char *k;
+    unsigned char *k =3D NULL;
     unsigned int nblocks =3D 0, i;
     krb5_error_code ret =3D 0;
-    struct key_type *kt =3D et->keytype;
+    struct _krb5_key_type *kt =3D et->keytype;
=20
     ret =3D _key_schedule(context, key);
     if(ret)
@@ -3548,18 +1858,19 @@
 	nblocks =3D (kt->bits + et->blocksize * 8 - 1) / (et->blocksize * 8);
 	k =3D malloc(nblocks * et->blocksize);
 	if(k =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
-	    return ENOMEM;
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
 	}
 	ret =3D _krb5_n_fold(constant, len, k, et->blocksize);
 	if (ret) {
-	    free(k);
-	    krb5_set_error_string(context, "out of memory");
-	    return ret;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
 	}
+
 	for(i =3D 0; i < nblocks; i++) {
 	    if(i > 0)
-		memcpy(k + i * et->blocksize,=20
+		memcpy(k + i * et->blocksize,
 		       k + (i - 1) * et->blocksize,
 		       et->blocksize);
 	    (*et->encrypt)(context, key, k + i * et->blocksize, et->blocksize,
@@ -3571,55 +1882,59 @@
 	size_t res_len =3D (kt->bits + 7) / 8;
=20
 	if(len !=3D 0 && c =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
-	    return ENOMEM;
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
 	}
 	memcpy(c, constant, len);
 	(*et->encrypt)(context, key, c, len, 1, 0, NULL);
 	k =3D malloc(res_len);
 	if(res_len !=3D 0 && k =3D=3D NULL) {
 	    free(c);
-	    krb5_set_error_string(context, "malloc: out of memory");
-	    return ENOMEM;
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
 	}
 	ret =3D _krb5_n_fold(c, len, k, res_len);
+	free(c);
 	if (ret) {
-	    free(k);
-	    krb5_set_error_string(context, "out of memory");
-	    return ret;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
 	}
-	free(c);
     }
-   =20
+
     /* XXX keytype dependent post-processing */
     switch(kt->type) {
-    case KEYTYPE_DES3:
-	DES3_postproc(context, k, nblocks * et->blocksize, key);
+    case ETYPE_OLD_DES3_CBC_SHA1:
+	_krb5_DES3_random_to_key(context, key->key, k, nblocks * et->blocksize);
 	break;
-    case KEYTYPE_AES128:
-    case KEYTYPE_AES256:
+    case ENCTYPE_AES128_CTS_HMAC_SHA1_96:
+    case ENCTYPE_AES256_CTS_HMAC_SHA1_96:
 	memcpy(key->key->keyvalue.data, k, key->key->keyvalue.length);
 	break;
     default:
-	krb5_set_error_string(context,
-			      "derive_key() called with unknown keytype (%u)",=20
-			      kt->type);
 	ret =3D KRB5_CRYPTO_INTERNAL;
+	krb5_set_error_message(context, ret,
+			       N_("derive_key() called with unknown keytype (%u)", ""),
+			       kt->type);
 	break;
     }
+ out:
     if (key->schedule) {
-	krb5_free_data(context, key->schedule);
+	free_key_schedule(context, key, et);
 	key->schedule =3D NULL;
     }
-    memset(k, 0, nblocks * et->blocksize);
-    free(k);
+    if (k) {
+	memset(k, 0, nblocks * et->blocksize);
+	free(k);
+    }
     return ret;
 }
=20
-static struct key_data *
+static struct _krb5_key_data *
 _new_derived_key(krb5_crypto crypto, unsigned usage)
 {
-    struct key_usage *d =3D crypto->key_usage;
+    struct _krb5_key_usage *d =3D crypto->key_usage;
     d =3D realloc(d, (crypto->num_key_usage + 1) * sizeof(*d));
     if(d =3D=3D NULL)
 	return NULL;
@@ -3630,7 +1945,7 @@
     return &d->key;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_derive_key(krb5_context context,
 		const krb5_keyblock *key,
 		krb5_enctype etype,
@@ -3639,16 +1954,14 @@
 		krb5_keyblock **derived_key)
 {
     krb5_error_code ret;
-    struct encryption_type *et;
-    struct key_data d;
+    struct _krb5_encryption_type *et;
+    struct _krb5_key_data d;
=20
     *derived_key =3D NULL;
=20
-    et =3D _find_enctype (etype);
+    et =3D _krb5_find_enctype (etype);
     if (et =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      etype);
-	return KRB5_PROG_ETYPE_NOSUPP;
+        return unsupported_enctype (context, etype);
     }
=20
     ret =3D krb5_copy_keyblock(context, key, &d.key);
@@ -3656,21 +1969,21 @@
 	return ret;
=20
     d.schedule =3D NULL;
-    ret =3D derive_key(context, et, &d, constant, constant_len);
+    ret =3D _krb5_derive_key(context, et, &d, constant, constant_len);
     if (ret =3D=3D 0)
 	ret =3D krb5_copy_keyblock(context, d.key, derived_key);
-    free_key_data(context, &d);   =20
+    _krb5_free_key_data(context, &d, et);
     return ret;
 }
=20
 static krb5_error_code
-_get_derived_key(krb5_context context,=20
-		 krb5_crypto crypto,=20
-		 unsigned usage,=20
-		 struct key_data **key)
+_get_derived_key(krb5_context context,
+		 krb5_crypto crypto,
+		 unsigned usage,
+		 struct _krb5_key_data **key)
 {
     int i;
-    struct key_data *d;
+    struct _krb5_key_data *d;
     unsigned char constant[5];
=20
     for(i =3D 0; i < crypto->num_key_usage; i++)
@@ -3680,18 +1993,35 @@
 	}
     d =3D _new_derived_key(crypto, usage);
     if(d =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     krb5_copy_keyblock(context, crypto->key.key, &d->key);
     _krb5_put_int(constant, usage, 5);
-    derive_key(context, crypto->et, d, constant, sizeof(constant));
+    _krb5_derive_key(context, crypto->et, d, constant, sizeof(constant));
     *key =3D d;
     return 0;
 }
=20
+/**
+ * Create a crypto context used for all encryption and signature
+ * operation. The encryption type to use is taken from the key, but
+ * can be overridden with the enctype parameter.  This can be useful
+ * for encryptions types which is compatiable (DES for example).
+ *
+ * To free the crypto context, use krb5_crypto_destroy().
+ *
+ * @param context Kerberos context
+ * @param key the key block information with all key data
+ * @param etype the encryption type
+ * @param crypto the resulting crypto context
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_init(krb5_context context,
 		 const krb5_keyblock *key,
 		 krb5_enctype etype,
@@ -3700,23 +2030,22 @@
     krb5_error_code ret;
     ALLOC(*crypto, 1);
     if(*crypto =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     if(etype =3D=3D ETYPE_NULL)
 	etype =3D key->keytype;
-    (*crypto)->et =3D _find_enctype(etype);
+    (*crypto)->et =3D _krb5_find_enctype(etype);
     if((*crypto)->et =3D=3D NULL || ((*crypto)->et->flags & F_DISABLED)) {
 	free(*crypto);
 	*crypto =3D NULL;
-	krb5_set_error_string (context, "encryption type %d not supported",
-			       etype);
-	return KRB5_PROG_ETYPE_NOSUPP;
+	return unsupported_enctype(context, etype);
     }
     if((*crypto)->et->keytype->size !=3D key->keyvalue.length) {
 	free(*crypto);
 	*crypto =3D NULL;
-	krb5_set_error_string (context, "encryption key has bad length");
+	krb5_set_error_message (context, KRB5_BAD_KEYSIZE,
+				"encryption key has bad length");
 	return KRB5_BAD_KEYSIZE;
     }
     ret =3D krb5_copy_keyblock(context, key, &(*crypto)->key.key);
@@ -3732,36 +2061,72 @@
 }
=20
 static void
-free_key_data(krb5_context context, struct key_data *key)
+free_key_schedule(krb5_context context,
+		  struct _krb5_key_data *key,
+		  struct _krb5_encryption_type *et)
+{
+    if (et->keytype->cleanup)
+	(*et->keytype->cleanup)(context, key);
+    memset(key->schedule->data, 0, key->schedule->length);
+    krb5_free_data(context, key->schedule);
+}
+
+void
+_krb5_free_key_data(krb5_context context, struct _krb5_key_data *key,
+	      struct _krb5_encryption_type *et)
 {
     krb5_free_keyblock(context, key->key);
     if(key->schedule) {
-	memset(key->schedule->data, 0, key->schedule->length);
-	krb5_free_data(context, key->schedule);
+	free_key_schedule(context, key, et);
+	key->schedule =3D NULL;
     }
 }
=20
 static void
-free_key_usage(krb5_context context, struct key_usage *ku)
+free_key_usage(krb5_context context, struct _krb5_key_usage *ku,
+	       struct _krb5_encryption_type *et)
 {
-    free_key_data(context, &ku->key);
+    _krb5_free_key_data(context, &ku->key, et);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Free a crypto context created by krb5_crypto_init().
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to free
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_destroy(krb5_context context,
 		    krb5_crypto crypto)
 {
     int i;
-   =20
+
     for(i =3D 0; i < crypto->num_key_usage; i++)
-	free_key_usage(context, &crypto->key_usage[i]);
+	free_key_usage(context, &crypto->key_usage[i], crypto->et);
     free(crypto->key_usage);
-    free_key_data(context, &crypto->key);
+    _krb5_free_key_data(context, &crypto->key, crypto->et);
     free (crypto);
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Return the blocksize used algorithm referenced by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param blocksize the resulting blocksize
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getblocksize(krb5_context context,
 			 krb5_crypto crypto,
 			 size_t *blocksize)
@@ -3770,25 +2135,61 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Return the encryption type used by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param enctype the resulting encryption type
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getenctype(krb5_context context,
 		       krb5_crypto crypto,
 		       krb5_enctype *enctype)
 {
     *enctype =3D crypto->et->type;
-     return 0;
+    return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Return the padding size used by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param padsize the return padding size
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getpadsize(krb5_context context,
                        krb5_crypto crypto,
-                       size_t *padsize)     =20
+                       size_t *padsize)
 {
     *padsize =3D crypto->et->padsize;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Return the confounder size used by the crypto context
+ *
+ * @param context Kerberos context
+ * @param crypto crypto context to query
+ * @param confoundersize the returned confounder size
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getconfoundersize(krb5_context context,
                               krb5_crypto crypto,
                               size_t *confoundersize)
@@ -3797,76 +2198,86 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+
+/**
+ * Disable encryption type
+ *
+ * @param context Kerberos 5 context
+ * @param enctype encryption type to disable
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_disable(krb5_context context,
 		     krb5_enctype enctype)
 {
-    struct encryption_type *et =3D _find_enctype(enctype);
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(enctype);
     if(et =3D=3D NULL) {
 	if (context)
-	    krb5_set_error_string (context, "encryption type %d not supported",
-				   enctype);
+	    krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+				    N_("encryption type %d not supported", ""),
+				    enctype);
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
     et->flags |=3D F_DISABLED;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_string_to_key_derived(krb5_context context,
-			   const void *str,
-			   size_t len,
-			   krb5_enctype etype,
-			   krb5_keyblock *key)
+/**
+ * Enable encryption type
+ *
+ * @param context Kerberos 5 context
+ * @param enctype encryption type to enable
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_enable(krb5_context context,
+		    krb5_enctype enctype)
 {
-    struct encryption_type *et =3D _find_enctype(etype);
-    krb5_error_code ret;
-    struct key_data kd;
-    size_t keylen;
-    u_char *tmp;
-
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(enctype);
     if(et =3D=3D NULL) {
-	krb5_set_error_string (context, "encryption type %d not supported",
-			       etype);
+	if (context)
+	    krb5_set_error_message (context, KRB5_PROG_ETYPE_NOSUPP,
+				    N_("encryption type %d not supported", ""),
+				    enctype);
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
-    keylen =3D et->keytype->bits / 8;
+    et->flags &=3D ~F_DISABLED;
+    return 0;
+}
=20
-    ALLOC(kd.key, 1);
-    if(kd.key =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    ret =3D krb5_data_alloc(&kd.key->keyvalue, et->keytype->size);
-    if(ret) {
-	free(kd.key);
-	return ret;
-    }
-    kd.key->keytype =3D etype;
-    tmp =3D malloc (keylen);
-    if(tmp =3D=3D NULL) {
-	krb5_free_keyblock(context, kd.key);
-	krb5_set_error_string (context, "malloc: out of memory");
-	return ENOMEM;
-    }
-    ret =3D _krb5_n_fold(str, len, tmp, keylen);
-    if (ret) {
-	free(tmp);
-	krb5_set_error_string(context, "out of memory");
-	return ret;
-    }
-    kd.schedule =3D NULL;
-    DES3_postproc (context, tmp, keylen, &kd); /* XXX */
-    memset(tmp, 0, keylen);
-    free(tmp);
-    ret =3D derive_key(context,=20
-		     et,
-		     &kd,
-		     "kerberos", /* XXX well known constant */
-		     strlen("kerberos"));
-    ret =3D krb5_copy_keyblock_contents(context, kd.key, key);
-    free_key_data(context, &kd);
-    return ret;
+/**
+ * Enable or disable all weak encryption types
+ *
+ * @param context Kerberos 5 context
+ * @param enable true to enable, false to disable
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_allow_weak_crypto(krb5_context context,
+		       krb5_boolean enable)
+{
+    int i;
+
+    for(i =3D 0; i < _krb5_num_etypes; i++)
+	if(_krb5_etypes[i]->flags & F_WEAK) {
+	    if(enable)
+		_krb5_etypes[i]->flags &=3D ~F_DISABLED;
+	    else
+		_krb5_etypes[i]->flags |=3D F_DISABLED;
+	}
+    return 0;
 }
=20
 static size_t
@@ -3874,7 +2285,7 @@
 		krb5_crypto  crypto,
 		size_t       data_len)
 {
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_encryption_type *et =3D crypto->et;
     size_t padsize =3D et->padsize;
     size_t checksumsize =3D CHECKSUMSIZE(et->checksum);
     size_t res;
@@ -3889,7 +2300,7 @@
 			krb5_crypto  crypto,
 			size_t       data_len)
 {
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_encryption_type *et =3D crypto->et;
     size_t padsize =3D et->padsize;
     size_t res;
=20
@@ -3906,7 +2317,7 @@
  * Return the size of an encrypted packet of length `data_len'
  */
=20
-size_t
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
 krb5_get_wrapped_length (krb5_context context,
 			 krb5_crypto  crypto,
 			 size_t       data_len)
@@ -3925,7 +2336,7 @@
 crypto_overhead (krb5_context context,
 		 krb5_crypto  crypto)
 {
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_encryption_type *et =3D crypto->et;
     size_t res;
=20
     res =3D CHECKSUMSIZE(et->checksum);
@@ -3939,7 +2350,7 @@
 crypto_overhead_dervied (krb5_context context,
 			 krb5_crypto  crypto)
 {
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_encryption_type *et =3D crypto->et;
     size_t res;
=20
     if (et->keyed_checksum)
@@ -3952,7 +2363,7 @@
     return res;
 }
=20
-size_t
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
 krb5_crypto_overhead (krb5_context context, krb5_crypto crypto)
 {
     if (derived_crypto (context, crypto))
@@ -3961,7 +2372,24 @@
 	return crypto_overhead (context, crypto);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Converts the random bytestring to a protocol key according to
+ * Kerberos crypto frame work. It may be assumed that all the bits of
+ * the input string are equally random, even though the entropy
+ * present in the random source may be limited.
+ *
+ * @param context Kerberos 5 context
+ * @param type the enctype resulting key will be of
+ * @param data input random data to convert to a key
+ * @param size size of input random data, at least krb5_enctype_keysize() =
long
+ * @param key key, output key, free with krb5_free_keyblock_contents()
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_random_to_key(krb5_context context,
 		   krb5_enctype type,
 		   const void *data,
@@ -3969,20 +2397,23 @@
 		   krb5_keyblock *key)
 {
     krb5_error_code ret;
-    struct encryption_type *et =3D _find_enctype(type);
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(type);
     if(et =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      type);
+	krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+			       N_("encryption type %d not supported", ""),
+			       type);
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
     if ((et->keytype->bits + 7) / 8 > size) {
-	krb5_set_error_string(context, "encryption key %s needs %d bytes "
-			      "of random to make an encryption key out of it",
-			      et->name, (int)et->keytype->size);
+	krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+			       N_("encryption key %s needs %d bytes "
+				  "of random to make an encryption key "
+				  "out of it", ""),
+			       et->name, (int)et->keytype->size);
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
     ret =3D krb5_data_alloc(&key->keyvalue, et->keytype->size);
-    if(ret)=20
+    if(ret)
 	return ret;
     key->keytype =3D type;
     if (et->keytype->random_to_key)
@@ -3993,74 +2424,19 @@
     return 0;
 }
=20
-krb5_error_code
-_krb5_pk_octetstring2key(krb5_context context,
-			 krb5_enctype type,
-			 const void *dhdata,
-			 size_t dhsize,
-			 const heim_octet_string *c_n,
-			 const heim_octet_string *k_n,
-			 krb5_keyblock *key)
-{
-    struct encryption_type *et =3D _find_enctype(type);
-    krb5_error_code ret;
-    size_t keylen, offset;
-    void *keydata;
-    unsigned char counter;
-    unsigned char shaoutput[20];
=20
-    if(et =3D=3D NULL) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      type);
-	return KRB5_PROG_ETYPE_NOSUPP;
-    }
-    keylen =3D (et->keytype->bits + 7) / 8;
=20
-    keydata =3D malloc(keylen);
-    if (keydata =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	return ENOMEM;
-    }
-
-    counter =3D 0;
-    offset =3D 0;
-    do {
-	SHA_CTX m;
-=09
-	SHA1_Init(&m);
-	SHA1_Update(&m, &counter, 1);
-	SHA1_Update(&m, dhdata, dhsize);
-	if (c_n)
-	    SHA1_Update(&m, c_n->data, c_n->length);
-	if (k_n)
-	    SHA1_Update(&m, k_n->data, k_n->length);
-	SHA1_Final(shaoutput, &m);
-
-	memcpy((unsigned char *)keydata + offset,
-	       shaoutput,
-	       min(keylen - offset, sizeof(shaoutput)));
-
-	offset +=3D sizeof(shaoutput);
-	counter++;
-    } while(offset < keylen);
-    memset(shaoutput, 0, sizeof(shaoutput));
-
-    ret =3D krb5_random_to_key(context, type, keydata, keylen, key);
-    memset(keydata, 0, sizeof(keylen));
-    free(keydata);
-    return ret;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_prf_length(krb5_context context,
 		       krb5_enctype type,
 		       size_t *length)
 {
-    struct encryption_type *et =3D _find_enctype(type);
+    struct _krb5_encryption_type *et =3D _krb5_find_enctype(type);
=20
     if(et =3D=3D NULL || et->prf_length =3D=3D 0) {
-	krb5_set_error_string(context, "encryption type %d not supported",
-			      type);
+	krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+			       N_("encryption type %d not supported", ""),
+			       type);
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
=20
@@ -4068,126 +2444,207 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_prf(krb5_context context,
 		const krb5_crypto crypto,
-		const krb5_data *input,=20
+		const krb5_data *input,
 		krb5_data *output)
 {
-    struct encryption_type *et =3D crypto->et;
+    struct _krb5_encryption_type *et =3D crypto->et;
=20
     krb5_data_zero(output);
=20
     if(et->prf =3D=3D NULL) {
-	krb5_set_error_string(context, "kerberos prf for %s not supported",
-			      et->name);
+	krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+			       "kerberos prf for %s not supported",
+			       et->name);
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
=20
     return (*et->prf)(context, crypto, input, output);
 }
-=09
-
-
-
-#ifdef CRYPTO_DEBUG
=20
 static krb5_error_code
-krb5_get_keyid(krb5_context context,
-	       krb5_keyblock *key,
-	       uint32_t *keyid)
+krb5_crypto_prfplus(krb5_context context,
+		    const krb5_crypto crypto,
+		    const krb5_data *input,
+		    size_t length,
+		    krb5_data *output)
 {
-    MD5_CTX md5;
-    unsigned char tmp[16];
+    krb5_error_code ret;
+    krb5_data input2;
+    unsigned char i =3D 1;
+    unsigned char *p;
=20
-    MD5_Init (&md5);
-    MD5_Update (&md5, key->keyvalue.data, key->keyvalue.length);
-    MD5_Final (tmp, &md5);
-    *keyid =3D (tmp[12] << 24) | (tmp[13] << 16) | (tmp[14] << 8) | tmp[15=
];
+    krb5_data_zero(&input2);
+    krb5_data_zero(output);
+
+    krb5_clear_error_message(context);
+
+    ret =3D krb5_data_alloc(output, length);
+    if (ret) goto out;
+    ret =3D krb5_data_alloc(&input2, input->length + 1);
+    if (ret) goto out;
+
+    krb5_clear_error_message(context);
+
+    memcpy(((unsigned char *)input2.data) + 1, input->data, input->length);
+
+    p =3D output->data;
+
+    while (length) {
+	krb5_data block;
+
+	((unsigned char *)input2.data)[0] =3D i++;
+
+	ret =3D krb5_crypto_prf(context, crypto, &input2, &block);
+	if (ret)
+	    goto out;
+
+	if (block.length < length) {
+	    memcpy(p, block.data, block.length);
+	    length -=3D block.length;
+	} else {
+	    memcpy(p, block.data, length);
+	    length =3D 0;
+	}
+	p +=3D block.length;
+	krb5_data_free(&block);
+    }
+
+ out:
+    krb5_data_free(&input2);
+    if (ret)
+	krb5_data_free(output);
     return 0;
 }
=20
-static void
-krb5_crypto_debug(krb5_context context,
-		  int encryptp,
-		  size_t len,
-		  krb5_keyblock *key)
+/**
+ * The FX-CF2 key derivation function, used in FAST and preauth framework.
+ *
+ * @param context Kerberos 5 context
+ * @param crypto1 first key to combine
+ * @param crypto2 second key to combine
+ * @param pepper1 factor to combine with first key to garante uniqueness
+ * @param pepper2 factor to combine with second key to garante uniqueness
+ * @param enctype the encryption type of the resulting key
+ * @param res allocated key, free with krb5_free_keyblock_contents()
+ *
+ * @return Return an error code or 0.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_fx_cf2(krb5_context context,
+		   const krb5_crypto crypto1,
+		   const krb5_crypto crypto2,
+		   krb5_data *pepper1,
+		   krb5_data *pepper2,
+		   krb5_enctype enctype,
+		   krb5_keyblock *res)
 {
-    uint32_t keyid;
-    char *kt;
-    krb5_get_keyid(context, key, &keyid);
-    krb5_enctype_to_string(context, key->keytype, &kt);
-    krb5_warnx(context, "%s %lu bytes with key-id %#x (%s)",=20
-	       encryptp ? "encrypting" : "decrypting",
-	       (unsigned long)len,
-	       keyid,
-	       kt);
-    free(kt);
+    krb5_error_code ret;
+    krb5_data os1, os2;
+    size_t i, keysize;
+
+    memset(res, 0, sizeof(*res));
+
+    ret =3D krb5_enctype_keysize(context, enctype, &keysize);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_data_alloc(&res->keyvalue, keysize);
+    if (ret)
+	goto out;
+    ret =3D krb5_crypto_prfplus(context, crypto1, pepper1, keysize, &os1);
+    if (ret)
+	goto out;
+    ret =3D krb5_crypto_prfplus(context, crypto2, pepper2, keysize, &os2);
+    if (ret)
+	goto out;
+
+    res->keytype =3D enctype;
+    {
+	unsigned char *p1 =3D os1.data, *p2 =3D os2.data, *p3 =3D res->keyvalue.d=
ata;
+	for (i =3D 0; i < keysize; i++)
+	    p3[i] =3D p1[i] ^ p2[i];
+    }
+ out:
+    if (ret)
+	krb5_data_free(&res->keyvalue);
+    krb5_data_free(&os1);
+    krb5_data_free(&os2);
+
+    return ret;
 }
=20
-#endif /* CRYPTO_DEBUG */
=20
-#if 0
-int
-main()
+
+#ifndef HEIMDAL_SMALLER
+
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_keytype_to_enctypes (krb5_context context,
+			  krb5_keytype keytype,
+			  unsigned *len,
+			  krb5_enctype **val)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
-#if 0
     int i;
-    krb5_context context;
-    krb5_crypto crypto;
-    struct key_data *d;
-    krb5_keyblock key;
-    char constant[4];
-    unsigned usage =3D ENCRYPTION_USAGE(3);
-    krb5_error_code ret;
+    unsigned n =3D 0;
+    krb5_enctype *ret;
=20
-    ret =3D krb5_init_context(&context);
-    if (ret)
-	errx (1, "krb5_init_context failed: %d", ret);
+    for (i =3D _krb5_num_etypes - 1; i >=3D 0; --i) {
+	if (_krb5_etypes[i]->keytype->type =3D=3D keytype
+	    && !(_krb5_etypes[i]->flags & F_PSEUDO)
+	    && krb5_enctype_valid(context, _krb5_etypes[i]->type) =3D=3D 0)
+	    ++n;
+    }
+    if (n =3D=3D 0) {
+	krb5_set_error_message(context, KRB5_PROG_KEYTYPE_NOSUPP,
+			       "Keytype have no mapping");
+	return KRB5_PROG_KEYTYPE_NOSUPP;
+    }
=20
-    key.keytype =3D ETYPE_NEW_DES3_CBC_SHA1;
-    key.keyvalue.data =3D "\xb3\x85\x58\x94\xd9\xdc\x7c\xc8"
-	"\x25\xe9\x85\xab\x3e\xb5\xfb\x0e"
-	"\xc8\xdf\xab\x26\x86\x64\x15\x25";
-    key.keyvalue.length =3D 24;
+    ret =3D malloc(n * sizeof(*ret));
+    if (ret =3D=3D NULL && n !=3D 0) {
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	return ENOMEM;
+    }
+    n =3D 0;
+    for (i =3D _krb5_num_etypes - 1; i >=3D 0; --i) {
+	if (_krb5_etypes[i]->keytype->type =3D=3D keytype
+	    && !(_krb5_etypes[i]->flags & F_PSEUDO)
+	    && krb5_enctype_valid(context, _krb5_etypes[i]->type) =3D=3D 0)
+	    ret[n++] =3D _krb5_etypes[i]->type;
+    }
+    *len =3D n;
+    *val =3D ret;
+    return 0;
+}
=20
-    krb5_crypto_init(context, &key, 0, &crypto);
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes.
+ *
+ * @ingroup krb5_deprecated
+ */
=20
-    d =3D _new_derived_key(crypto, usage);
-    if(d =3D=3D NULL)
-	krb5_errx(context, 1, "_new_derived_key failed");
-    krb5_copy_keyblock(context, crypto->key.key, &d->key);
-    _krb5_put_int(constant, usage, 4);
-    derive_key(context, crypto->et, d, constant, sizeof(constant));
-    return 0;
-#else
-    int i;
-    krb5_context context;
-    krb5_crypto crypto;
-    struct key_data *d;
-    krb5_keyblock key;
-    krb5_error_code ret;
-    Checksum res;
+/* if two enctypes have compatible keys */
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_enctypes_compatible_keys(krb5_context context,
+			      krb5_enctype etype1,
+			      krb5_enctype etype2)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+    struct _krb5_encryption_type *e1 =3D _krb5_find_enctype(etype1);
+    struct _krb5_encryption_type *e2 =3D _krb5_find_enctype(etype2);
+    return e1 !=3D NULL && e2 !=3D NULL && e1->keytype =3D=3D e2->keytype;
+}
=20
-    char *data =3D "what do ya want for nothing?";
-
-    ret =3D krb5_init_context(&context);
-    if (ret)
-	errx (1, "krb5_init_context failed: %d", ret);
-
-    key.keytype =3D ETYPE_NEW_DES3_CBC_SHA1;
-    key.keyvalue.data =3D "Jefe";
-    /* "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"
-       "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"; */
-    key.keyvalue.length =3D 4;
-
-    d =3D ecalloc(1, sizeof(*d));
-    d->key =3D &key;
-    res.checksum.length =3D 20;
-    res.checksum.data =3D emalloc(res.checksum.length);
-    SP_HMAC_SHA1_checksum(context, d, data, 28, &res);
-
-    return 0;
-#endif
-}
-#endif
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/data.c
--- a/head/crypto/heimdal/lib/krb5/data.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/data.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: data.c 22064 2007-11-11 16:28:14Z lha $");
-
 /**
  * Reset the (potentially uninitalized) krb5_data structure.
  *
@@ -43,7 +41,7 @@
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_data_zero(krb5_data *p)
 {
     p->length =3D 0;
@@ -52,14 +50,16 @@
=20
 /**
  * Free the content of krb5_data structure, its ok to free a zeroed
- * structure. When done, the structure will be zeroed.
- *=20
+ * structure (with memset() or krb5_data_zero()). When done, the
+ * structure will be zeroed. The same function is called
+ * krb5_free_data_contents() in MIT Kerberos.
+ *
  * @param p krb5_data to free.
  *
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_data_free(krb5_data *p)
 {
     if(p->data !=3D NULL)
@@ -68,30 +68,15 @@
 }
=20
 /**
- * Same as krb5_data_free().
- *=20
- * @param context Kerberos 5 context.
- * @param data krb5_data to free.
+ * Free krb5_data (and its content).
  *
- * @ingroup krb5
- */
-
-void KRB5_LIB_FUNCTION=20
-krb5_free_data_contents(krb5_context context, krb5_data *data)
-{
-    krb5_data_free(data);
-}
-
-/**
- * Free krb5_data (and its content).
- *=20
  * @param context Kerberos 5 context.
  * @param p krb5_data to free.
  *
  * @ingroup krb5
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_data(krb5_context context,
 	       krb5_data *p)
 {
@@ -101,8 +86,8 @@
=20
 /**
  * Allocate data of and krb5_data.
- *=20
- * @param p krb5_data to free.
+ *
+ * @param p krb5_data to allocate.
  * @param len size to allocate.
  *
  * @return Returns 0 to indicate success. Otherwise an kerberos et
@@ -111,7 +96,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_data_alloc(krb5_data *p, int len)
 {
     p->data =3D malloc(len);
@@ -123,7 +108,7 @@
=20
 /**
  * Grow (or shrink) the content of krb5_data to a new size.
- *=20
+ *
  * @param p krb5_data to free.
  * @param len new size.
  *
@@ -133,7 +118,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_data_realloc(krb5_data *p, int len)
 {
     void *tmp;
@@ -147,7 +132,7 @@
=20
 /**
  * Copy the data of len into the krb5_data.
- *=20
+ *
  * @param p krb5_data to copy into.
  * @param data data to copy..
  * @param len new size.
@@ -158,7 +143,7 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_data_copy(krb5_data *p, const void *data, size_t len)
 {
     if (len) {
@@ -173,7 +158,7 @@
=20
 /**
  * Copy the data into a newly allocated krb5_data.
- *=20
+ *
  * @param context Kerberos 5 context.
  * @param indata the krb5_data data to copy
  * @param outdata new krb5_date to copy too. Free with krb5_free_data().
@@ -184,20 +169,20 @@
  * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_copy_data(krb5_context context,=20
-	       const krb5_data *indata,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_data(krb5_context context,
+	       const krb5_data *indata,
 	       krb5_data **outdata)
 {
     krb5_error_code ret;
     ALLOC(*outdata, 1);
     if(*outdata =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
     ret =3D der_copy_octet_string(indata, *outdata);
     if(ret) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	free(*outdata);
 	*outdata =3D NULL;
     }
@@ -206,7 +191,7 @@
=20
 /**
  * Compare to data.
- *=20
+ *
  * @param data1 krb5_data to compare
  * @param data2 krb5_data to compare
  *
@@ -215,10 +200,29 @@
  * @ingroup krb5
  */
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_data_cmp(const krb5_data *data1, const krb5_data *data2)
 {
     if (data1->length !=3D data2->length)
 	return data1->length - data2->length;
     return memcmp(data1->data, data2->data, data1->length);
 }
+
+/**
+ * Compare to data not exposing timing information from the checksum data
+ *
+ * @param data1 krb5_data to compare
+ * @param data2 krb5_data to compare
+ *
+ * @return returns zero for same data, otherwise non zero.
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_data_ct_cmp(const krb5_data *data1, const krb5_data *data2)
+{
+    if (data1->length !=3D data2->length)
+	return data1->length - data2->length;
+    return ct_memcmp(data1->data, data2->data, data1->length);
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/derived-k=
ey-test.c
--- a/head/crypto/heimdal/lib/krb5/derived-key-test.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/derived-key-test.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: derived-key-test.c 16342 2005-12-02 14:14:43Z lha $");
-
 enum { MAXSIZE =3D 24 };
=20
 static struct testcase {
@@ -77,7 +75,7 @@
     {0}
 };
=20
-int KRB5_LIB_FUNCTION
+int
 main(int argc, char **argv)
 {
     struct testcase *t;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/digest.c
--- a/head/crypto/heimdal/lib/krb5/digest.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/digest.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,41 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-RCSID("$Id: digest.c 22156 2007-12-04 20:02:49Z lha $");
 #include "digest_asn1.h"
=20
+#ifndef HEIMDAL_SMALLER
+
 struct krb5_digest_data {
     char *cbtype;
     char *cbbinding;
@@ -45,7 +46,7 @@
     DigestResponse response;
 };
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_alloc(krb5_context context, krb5_digest *digest)
 {
     krb5_digest d;
@@ -53,7 +54,7 @@
     d =3D calloc(1, sizeof(*d));
     if (d =3D=3D NULL) {
 	*digest =3D NULL;
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest =3D d;
@@ -61,7 +62,7 @@
     return 0;
 }
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_digest_free(krb5_digest digest)
 {
     if (digest =3D=3D NULL)
@@ -75,14 +76,15 @@
     return;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_server_cb(krb5_context context,
 			  krb5_digest digest,
 			  const char *type,
 			  const char *binding)
 {
     if (digest->init.channel) {
-	krb5_set_error_string(context, "server channel binding already set");
+	krb5_set_error_message(context, EINVAL,
+			       N_("server channel binding already set", ""));
 	return EINVAL;
     }
     digest->init.channel =3D calloc(1, sizeof(*digest->init.channel));
@@ -94,54 +96,54 @@
 	goto error;
=20
     digest->init.channel->cb_binding =3D strdup(binding);
-    if (digest->init.channel->cb_binding =3D=3D NULL)=20
+    if (digest->init.channel->cb_binding =3D=3D NULL)
 	goto error;
     return 0;
-error:
+ error:
     if (digest->init.channel) {
 	free(digest->init.channel->cb_type);
 	free(digest->init.channel->cb_binding);
 	free(digest->init.channel);
 	digest->init.channel =3D NULL;
     }
-    krb5_set_error_string(context, "out of memory");
+    krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""=
));
     return ENOMEM;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_type(krb5_context context,
 		     krb5_digest digest,
 		     const char *type)
 {
     if (digest->init.type) {
-	krb5_set_error_string(context, "client type already set");
+	krb5_set_error_message(context, EINVAL, "client type already set");
 	return EINVAL;
     }
     digest->init.type =3D strdup(type);
     if (digest->init.type =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_hostname(krb5_context context,
 			 krb5_digest digest,
 			 const char *hostname)
 {
     if (digest->init.hostname) {
-	krb5_set_error_string(context, "server hostname already set");
+	krb5_set_error_message(context, EINVAL, "server hostname already set");
 	return EINVAL;
     }
     digest->init.hostname =3D malloc(sizeof(*digest->init.hostname));
     if (digest->init.hostname =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->init.hostname =3D strdup(hostname);
     if (*digest->init.hostname =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->init.hostname);
 	digest->init.hostname =3D NULL;
 	return ENOMEM;
@@ -149,55 +151,55 @@
     return 0;
 }
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_server_nonce(krb5_context context,
 			     krb5_digest digest)
 {
     return digest->initReply.nonce;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_server_nonce(krb5_context context,
 			     krb5_digest digest,
 			     const char *nonce)
 {
     if (digest->request.serverNonce) {
-	krb5_set_error_string(context, "nonce already set");
+	krb5_set_error_message(context, EINVAL, N_("nonce already set", ""));
 	return EINVAL;
     }
     digest->request.serverNonce =3D strdup(nonce);
     if (digest->request.serverNonce =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_opaque(krb5_context context,
 		       krb5_digest digest)
 {
     return digest->initReply.opaque;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_opaque(krb5_context context,
 		       krb5_digest digest,
 		       const char *opaque)
 {
     if (digest->request.opaque) {
-	krb5_set_error_string(context, "opaque already set");
+	krb5_set_error_message(context, EINVAL, "opaque already set");
 	return EINVAL;
     }
     digest->request.opaque =3D strdup(opaque);
     if (digest->request.opaque =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_identifier(krb5_context context,
 			   krb5_digest digest)
 {
@@ -206,23 +208,23 @@
     return *digest->initReply.identifier;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_identifier(krb5_context context,
 			   krb5_digest digest,
 			   const char *id)
 {
     if (digest->request.identifier) {
-	krb5_set_error_string(context, "identifier already set");
+	krb5_set_error_message(context, EINVAL, N_("identifier already set", ""));
 	return EINVAL;
     }
     digest->request.identifier =3D calloc(1, sizeof(*digest->request.ident=
ifier));
     if (digest->request.identifier =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.identifier =3D strdup(id);
     if (*digest->request.identifier =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.identifier);
 	digest->request.identifier =3D NULL;
 	return ENOMEM;
@@ -242,7 +244,7 @@
     DigestREP rep;
     krb5_error_code ret;
     krb5_data data, data2;
-    size_t size;
+    size_t size =3D 0;
     krb5_crypto crypto =3D NULL;
     krb5_auth_context ac =3D NULL;
     krb5_principal principal =3D NULL;
@@ -272,7 +274,7 @@
      *
      */
=20
-    ret =3D krb5_make_principal(context, &principal,=20
+    ret =3D krb5_make_principal(context, &principal,
 			      r, KRB5_DIGEST_NAME, r, NULL);
     if (ret)
 	goto out;
@@ -280,14 +282,14 @@
     ASN1_MALLOC_ENCODE(DigestReqInner, data.data, data.length,
 		       ireq, &size, ret);
     if (ret) {
-	krb5_set_error_string(context,
-			      "Failed to encode digest inner request");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to encode digest inner request", ""));
 	goto out;
     }
     if (size !=3D data.length)
 	krb5_abortx(context, "ASN.1 internal encoder error");
=20
-    ret =3D krb5_mk_req_exact(context, &ac,=20
+    ret =3D krb5_mk_req_exact(context, &ac,
 			    AP_OPTS_USE_SUBKEY|AP_OPTS_MUTUAL_REQUIRED,
 			    principal, NULL, id, &req.apReq);
     if (ret)
@@ -300,8 +302,9 @@
 	if (ret)
 	    goto out;
 	if (key =3D=3D NULL) {
-	    krb5_set_error_string(context, "Digest failed to get local subkey");
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret,
+				   N_("Digest failed to get local subkey", ""));
 	    goto out;
 	}
=20
@@ -312,7 +315,7 @@
     }
=20
     ret =3D krb5_encrypt_EncryptedData(context, crypto, usage,
-				     data.data, data.length, 0,=20
+				     data.data, data.length, 0,
 				     &req.innerReq);
     if (ret)
 	goto out;
@@ -322,7 +325,8 @@
     ASN1_MALLOC_ENCODE(DigestREQ, data.data, data.length,
 		       &req, &size, ret);
     if (ret) {
-	krb5_set_error_string(context, "Failed to encode DigestREQest");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to encode DigestREQest", ""));
 	goto out;
     }
     if (size !=3D data.length)
@@ -334,7 +338,8 @@
=20
     ret =3D decode_DigestREP(data2.data, data2.length, &rep, NULL);
     if (ret) {
-	krb5_set_error_string(context, "Failed to parse digest response");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to parse digest response", ""));
 	goto out;
     }
=20
@@ -355,8 +360,8 @@
 	    goto out;
 	if (key =3D=3D NULL) {
 	    ret =3D EINVAL;
-	    krb5_set_error_string(context,=20
-				  "Digest reply have no remote subkey");
+	    krb5_set_error_message(context, ret,
+				   N_("Digest reply have no remote subkey", ""));
 	    goto out;
 	}
=20
@@ -372,14 +377,15 @@
 				     &rep.innerRep, &data);
     if (ret)
 	goto out;
-   =20
+
     ret =3D decode_DigestRepInner(data.data, data.length, irep, NULL);
     if (ret) {
-	krb5_set_error_string(context, "Failed to decode digest inner reply");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to decode digest inner reply", ""));
 	goto out;
     }
=20
-out:
+ out:
     if (ccache =3D=3D NULL && id)
 	krb5_cc_close(context, id);
     if (realm =3D=3D NULL && r)
@@ -400,7 +406,7 @@
     return ret;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_init_request(krb5_context context,
 			 krb5_digest digest,
 			 krb5_realm realm,
@@ -414,7 +420,8 @@
     memset(&irep, 0, sizeof(irep));
=20
     if (digest->init.type =3D=3D NULL) {
-	krb5_set_error_string(context, "Type missing from init req");
+	krb5_set_error_message(context, EINVAL,
+			       N_("Type missing from init req", ""));
 	return EINVAL;
     }
=20
@@ -427,49 +434,52 @@
 	goto out;
=20
     if (irep.element =3D=3D choice_DigestRepInner_error) {
-	krb5_set_error_string(context, "Digest init error: %s",
-			      irep.u.error.reason);
 	ret =3D irep.u.error.code;
+	krb5_set_error_message(context, ret, N_("Digest init error: %s", ""),
+			       irep.u.error.reason);
 	goto out;
     }
=20
     if (irep.element !=3D choice_DigestRepInner_initReply) {
-	krb5_set_error_string(context, "digest reply not an initReply");
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret,
+			       N_("digest reply not an initReply", ""));
 	goto out;
     }
=20
     ret =3D copy_DigestInitReply(&irep.u.initReply, &digest->initReply);
     if (ret) {
-	krb5_set_error_string(context, "Failed to copy initReply");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to copy initReply", ""));
 	goto out;
     }
=20
-out:
+ out:
     free_DigestRepInner(&irep);
=20
     return ret;
 }
=20
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_client_nonce(krb5_context context,
 			     krb5_digest digest,
 			     const char *nonce)
 {
     if (digest->request.clientNonce) {
-	krb5_set_error_string(context, "clientNonce already set");
+	krb5_set_error_message(context, EINVAL,
+			       N_("clientNonce already set", ""));
 	return EINVAL;
     }
-    digest->request.clientNonce =3D=20
+    digest->request.clientNonce =3D
 	calloc(1, sizeof(*digest->request.clientNonce));
     if (digest->request.clientNonce =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.clientNonce =3D strdup(nonce);
     if (*digest->request.clientNonce =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.clientNonce);
 	digest->request.clientNonce =3D NULL;
 	return ENOMEM;
@@ -477,57 +487,58 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_digest(krb5_context context,
 		       krb5_digest digest,
 		       const char *dgst)
 {
     if (digest->request.digest) {
-	krb5_set_error_string(context, "digest already set");
+	krb5_set_error_message(context, EINVAL,
+			       N_("digest already set", ""));
 	return EINVAL;
     }
     digest->request.digest =3D strdup(dgst);
     if (digest->request.digest =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_username(krb5_context context,
 			 krb5_digest digest,
 			 const char *username)
 {
     if (digest->request.username) {
-	krb5_set_error_string(context, "username already set");
+	krb5_set_error_message(context, EINVAL, "username already set");
 	return EINVAL;
     }
     digest->request.username =3D strdup(username);
     if (digest->request.username =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_authid(krb5_context context,
 		       krb5_digest digest,
 		       const char *authid)
 {
     if (digest->request.authid) {
-	krb5_set_error_string(context, "authid already set");
+	krb5_set_error_message(context, EINVAL, "authid already set");
 	return EINVAL;
     }
     digest->request.authid =3D malloc(sizeof(*digest->request.authid));
     if (digest->request.authid =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.authid =3D strdup(authid);
     if (*digest->request.authid =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.authid);
 	digest->request.authid =3D NULL;
 	return ENOMEM;
@@ -535,7 +546,7 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_authentication_user(krb5_context context,
 				    krb5_digest digest,
 				    krb5_principal authentication_user)
@@ -543,36 +554,35 @@
     krb5_error_code ret;
=20
     if (digest->request.authentication_user) {
-	krb5_set_error_string(context, "authentication_user already set");
+	krb5_set_error_message(context, EINVAL,
+			       N_("authentication_user already set", ""));
 	return EINVAL;
     }
     ret =3D krb5_copy_principal(context,
 			      authentication_user,
 			      &digest->request.authentication_user);
-    if (digest->request.authentication_user =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
-    }
+    if (ret)
+	return ret;
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_realm(krb5_context context,
 		      krb5_digest digest,
 		      const char *realm)
 {
     if (digest->request.realm) {
-	krb5_set_error_string(context, "realm already set");
+	krb5_set_error_message(context, EINVAL, "realm already set");
 	return EINVAL;
     }
     digest->request.realm =3D malloc(sizeof(*digest->request.realm));
     if (digest->request.realm =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.realm =3D strdup(realm);
     if (*digest->request.realm =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.realm);
 	digest->request.realm =3D NULL;
 	return ENOMEM;
@@ -580,23 +590,24 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_method(krb5_context context,
 		       krb5_digest digest,
 		       const char *method)
 {
     if (digest->request.method) {
-	krb5_set_error_string(context, "method already set");
+	krb5_set_error_message(context, EINVAL,
+			       N_("method already set", ""));
 	return EINVAL;
     }
     digest->request.method =3D malloc(sizeof(*digest->request.method));
     if (digest->request.method =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.method =3D strdup(method);
     if (*digest->request.method =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.method);
 	digest->request.method =3D NULL;
 	return ENOMEM;
@@ -604,23 +615,23 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_uri(krb5_context context,
 		    krb5_digest digest,
 		    const char *uri)
 {
     if (digest->request.uri) {
-	krb5_set_error_string(context, "uri already set");
+	krb5_set_error_message(context, EINVAL, N_("uri already set", ""));
 	return EINVAL;
     }
     digest->request.uri =3D malloc(sizeof(*digest->request.uri));
     if (digest->request.uri =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.uri =3D strdup(uri);
     if (*digest->request.uri =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.uri);
 	digest->request.uri =3D NULL;
 	return ENOMEM;
@@ -628,24 +639,25 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_nonceCount(krb5_context context,
 			   krb5_digest digest,
 			   const char *nonce_count)
 {
     if (digest->request.nonceCount) {
-	krb5_set_error_string(context, "nonceCount already set");
+	krb5_set_error_message(context, EINVAL,
+			       N_("nonceCount already set", ""));
 	return EINVAL;
     }
-    digest->request.nonceCount =3D=20
+    digest->request.nonceCount =3D
 	malloc(sizeof(*digest->request.nonceCount));
     if (digest->request.nonceCount =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.nonceCount =3D strdup(nonce_count);
     if (*digest->request.nonceCount =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.nonceCount);
 	digest->request.nonceCount =3D NULL;
 	return ENOMEM;
@@ -653,23 +665,23 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_qop(krb5_context context,
 		    krb5_digest digest,
 		    const char *qop)
 {
     if (digest->request.qop) {
-	krb5_set_error_string(context, "qop already set");
+	krb5_set_error_message(context, EINVAL, "qop already set");
 	return EINVAL;
     }
     digest->request.qop =3D malloc(sizeof(*digest->request.qop));
     if (digest->request.qop =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *digest->request.qop =3D strdup(qop);
     if (*digest->request.qop =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	free(digest->request.qop);
 	digest->request.qop =3D NULL;
 	return ENOMEM;
@@ -677,20 +689,20 @@
     return 0;
 }
=20
-int
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_digest_set_responseData(krb5_context context,
 			     krb5_digest digest,
 			     const char *response)
 {
     digest->request.responseData =3D strdup(response);
     if (digest->request.responseData =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_request(krb5_context context,
 		    krb5_digest digest,
 		    krb5_realm realm,
@@ -708,14 +720,17 @@
=20
     if (digest->request.type =3D=3D NULL) {
 	if (digest->init.type =3D=3D NULL) {
-	    krb5_set_error_string(context, "Type missing from req");
+	    krb5_set_error_message(context, EINVAL,
+				   N_("Type missing from req", ""));
 	    return EINVAL;
 	}
 	ireq.u.digestRequest.type =3D digest->init.type;
     }
=20
-    if (ireq.u.digestRequest.digest =3D=3D NULL)
-	ireq.u.digestRequest.digest =3D "md5";
+    if (ireq.u.digestRequest.digest =3D=3D NULL) {
+	static char md5[] =3D "md5";
+	ireq.u.digestRequest.digest =3D md5;
+    }
=20
     ret =3D digest_request(context, realm, ccache,
 			 KRB5_KU_DIGEST_ENCRYPT, &ireq, &irep);
@@ -723,38 +738,41 @@
 	return ret;
=20
     if (irep.element =3D=3D choice_DigestRepInner_error) {
-	krb5_set_error_string(context, "Digest response error: %s",
-			      irep.u.error.reason);
 	ret =3D irep.u.error.code;
+	krb5_set_error_message(context, ret,
+			       N_("Digest response error: %s", ""),
+			       irep.u.error.reason);
 	goto out;
     }
=20
     if (irep.element !=3D choice_DigestRepInner_response) {
-	krb5_set_error_string(context, "digest reply not an DigestResponse");
+	krb5_set_error_message(context, EINVAL,
+			       N_("digest reply not an DigestResponse", ""));
 	ret =3D EINVAL;
 	goto out;
     }
=20
     ret =3D copy_DigestResponse(&irep.u.response, &digest->response);
     if (ret) {
-	krb5_set_error_string(context, "Failed to copy initReply");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to copy initReply,", ""));
 	goto out;
     }
=20
-out:
+ out:
     free_DigestRepInner(&irep);
=20
     return ret;
 }
=20
-krb5_boolean
-krb5_digest_rep_get_status(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_digest_rep_get_status(krb5_context context,
 			   krb5_digest digest)
 {
     return digest->response.success ? TRUE : FALSE;
 }
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_rsp(krb5_context context,
 		    krb5_digest digest)
 {
@@ -763,7 +781,7 @@
     return *digest->response.rsp;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_get_tickets(krb5_context context,
 			krb5_digest digest,
 			Ticket **tickets)
@@ -773,7 +791,7 @@
 }
=20
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_get_client_binding(krb5_context context,
 			       krb5_digest digest,
 			       char **type,
@@ -785,7 +803,7 @@
 	if (*type =3D=3D NULL || *binding =3D=3D NULL) {
 	    free(*type);
 	    free(*binding);
-	    krb5_set_error_string(context, "out of memory");
+	    krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "=
"));
 	    return ENOMEM;
 	}
     } else {
@@ -795,7 +813,7 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_get_session_key(krb5_context context,
 			    krb5_digest digest,
 			    krb5_data *data)
@@ -807,7 +825,7 @@
 	return 0;
     ret =3D der_copy_octet_string(digest->response.session_key, data);
     if (ret)
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
=20
     return ret;
 }
@@ -819,19 +837,19 @@
     NTLMResponse response;
 };
=20
-krb5_error_code
-krb5_ntlm_alloc(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_alloc(krb5_context context,
 		krb5_ntlm *ntlm)
 {
     *ntlm =3D calloc(1, sizeof(**ntlm));
     if (*ntlm =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_free(krb5_context context, krb5_ntlm ntlm)
 {
     free_NTLMInit(&ntlm->init);
@@ -844,8 +862,8 @@
 }
=20
=20
-krb5_error_code
-krb5_ntlm_init_request(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_init_request(krb5_context context,
 		       krb5_ntlm ntlm,
 		       krb5_realm realm,
 		       krb5_ccache ccache,
@@ -879,31 +897,33 @@
 	goto out;
=20
     if (irep.element =3D=3D choice_DigestRepInner_error) {
-	krb5_set_error_string(context, "Digest init error: %s",
-			      irep.u.error.reason);
 	ret =3D irep.u.error.code;
+	krb5_set_error_message(context, ret, N_("Digest init error: %s", ""),
+			       irep.u.error.reason);
 	goto out;
     }
=20
     if (irep.element !=3D choice_DigestRepInner_ntlmInitReply) {
-	krb5_set_error_string(context, "ntlm reply not an initReply");
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret,
+			       N_("ntlm reply not an initReply", ""));
 	goto out;
     }
=20
     ret =3D copy_NTLMInitReply(&irep.u.ntlmInitReply, &ntlm->initReply);
     if (ret) {
-	krb5_set_error_string(context, "Failed to copy initReply");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to copy initReply", ""));
 	goto out;
     }
=20
-out:
+ out:
     free_DigestRepInner(&irep);
=20
     return ret;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_flags(krb5_context context,
 			 krb5_ntlm ntlm,
 			 uint32_t *flags)
@@ -912,7 +932,7 @@
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_challange(krb5_context context,
 			     krb5_ntlm ntlm,
 			     krb5_data *challange)
@@ -921,12 +941,12 @@
=20
     ret =3D der_copy_octet_string(&ntlm->initReply.challange, challange);
     if (ret)
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
=20
     return ret;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_opaque(krb5_context context,
 			  krb5_ntlm ntlm,
 			  krb5_data *opaque)
@@ -935,25 +955,25 @@
=20
     ret =3D der_copy_octet_string(&ntlm->initReply.opaque, opaque);
     if (ret)
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
=20
     return ret;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_targetname(krb5_context context,
 			      krb5_ntlm ntlm,
 			      char **name)
 {
     *name =3D strdup(ntlm->initReply.targetname);
     if (*name =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_targetinfo(krb5_context context,
 			      krb5_ntlm ntlm,
 			      krb5_data *data)
@@ -969,14 +989,14 @@
 			 ntlm->initReply.targetinfo->data,
 			 ntlm->initReply.targetinfo->length);
     if (ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
     return 0;
 }
=20
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_request(krb5_context context,
 		  krb5_ntlm ntlm,
 		  krb5_realm realm,
@@ -998,32 +1018,35 @@
 	return ret;
=20
     if (irep.element =3D=3D choice_DigestRepInner_error) {
-	krb5_set_error_string(context, "NTLM response error: %s",
-			      irep.u.error.reason);
 	ret =3D irep.u.error.code;
+	krb5_set_error_message(context, ret,
+			       N_("NTLM response error: %s", ""),
+			       irep.u.error.reason);
 	goto out;
     }
=20
     if (irep.element !=3D choice_DigestRepInner_ntlmResponse) {
-	krb5_set_error_string(context, "NTLM reply not an NTLMResponse");
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret,
+			       N_("NTLM reply not an NTLMResponse", ""));
 	goto out;
     }
=20
     ret =3D copy_NTLMResponse(&irep.u.ntlmResponse, &ntlm->response);
     if (ret) {
-	krb5_set_error_string(context, "Failed to copy NTLMResponse");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to copy NTLMResponse", ""));
 	goto out;
     }
=20
-out:
+ out:
     free_DigestRepInner(&irep);
=20
     return ret;
 }
=20
-krb5_error_code
-krb5_ntlm_req_set_flags(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_flags(krb5_context context,
 			krb5_ntlm ntlm,
 			uint32_t flags)
 {
@@ -1031,40 +1054,40 @@
     return 0;
 }
=20
-krb5_error_code
-krb5_ntlm_req_set_username(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_username(krb5_context context,
 			   krb5_ntlm ntlm,
 			   const char *username)
 {
     ntlm->request.username =3D strdup(username);
     if (ntlm->request.username =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
-krb5_ntlm_req_set_targetname(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_targetname(krb5_context context,
 			     krb5_ntlm ntlm,
 			     const char *targetname)
 {
     ntlm->request.targetname =3D strdup(targetname);
     if (ntlm->request.targetname =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-krb5_error_code
-krb5_ntlm_req_set_lm(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_lm(krb5_context context,
 		     krb5_ntlm ntlm,
 		     void *hash, size_t len)
 {
     ntlm->request.lm.data =3D malloc(len);
-    if (ntlm->request.lm.data =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+    if (ntlm->request.lm.data =3D=3D NULL && len !=3D 0) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ntlm->request.lm.length =3D len;
@@ -1072,14 +1095,14 @@
     return 0;
 }
=20
-krb5_error_code
-krb5_ntlm_req_set_ntlm(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_ntlm(krb5_context context,
 		       krb5_ntlm ntlm,
 		       void *hash, size_t len)
 {
     ntlm->request.ntlm.data =3D malloc(len);
-    if (ntlm->request.ntlm.data =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+    if (ntlm->request.ntlm.data =3D=3D NULL && len !=3D 0) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ntlm->request.ntlm.length =3D len;
@@ -1087,14 +1110,14 @@
     return 0;
 }
=20
-krb5_error_code
-krb5_ntlm_req_set_opaque(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_opaque(krb5_context context,
 			 krb5_ntlm ntlm,
 			 krb5_data *opaque)
 {
     ntlm->request.opaque.data =3D malloc(opaque->length);
-    if (ntlm->request.opaque.data =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+    if (ntlm->request.opaque.data =3D=3D NULL && opaque->length !=3D 0) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ntlm->request.opaque.length =3D opaque->length;
@@ -1102,19 +1125,19 @@
     return 0;
 }
=20
-krb5_error_code
-krb5_ntlm_req_set_session(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_req_set_session(krb5_context context,
 			  krb5_ntlm ntlm,
 			  void *sessionkey, size_t length)
 {
     ntlm->request.sessionkey =3D calloc(1, sizeof(*ntlm->request.sessionke=
y));
     if (ntlm->request.sessionkey =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ntlm->request.sessionkey->data =3D malloc(length);
-    if (ntlm->request.sessionkey->data =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+    if (ntlm->request.sessionkey->data =3D=3D NULL && length !=3D 0) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memcpy(ntlm->request.sessionkey->data, sessionkey, length);
@@ -1122,23 +1145,24 @@
     return 0;
 }
=20
-krb5_boolean
-krb5_ntlm_rep_get_status(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_ntlm_rep_get_status(krb5_context context,
 			 krb5_ntlm ntlm)
 {
     return ntlm->response.success ? TRUE : FALSE;
 }
=20
-krb5_error_code
-krb5_ntlm_rep_get_sessionkey(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_ntlm_rep_get_sessionkey(krb5_context context,
 			     krb5_ntlm ntlm,
 			     krb5_data *data)
 {
     if (ntlm->response.sessionkey =3D=3D NULL) {
-	krb5_set_error_string(context, "no ntlm session key");
+	krb5_set_error_message(context, EINVAL,
+			       N_("no ntlm session key", ""));
 	return EINVAL;
     }
-    krb5_clear_error_string(context);
+    krb5_clear_error_message(context);
     return krb5_data_copy(data,
 			  ntlm->response.sessionkey->data,
 			  ntlm->response.sessionkey->length);
@@ -1157,7 +1181,7 @@
  * @ingroup krb5_digest
  */
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_probe(krb5_context context,
 		  krb5_realm realm,
 		  krb5_ccache ccache,
@@ -1178,22 +1202,24 @@
 	goto out;
=20
     if (irep.element =3D=3D choice_DigestRepInner_error) {
-	krb5_set_error_string(context, "Digest probe error: %s",
-			      irep.u.error.reason);
 	ret =3D irep.u.error.code;
+	krb5_set_error_message(context, ret, "Digest probe error: %s",
+			       irep.u.error.reason);
 	goto out;
     }
=20
     if (irep.element !=3D choice_DigestRepInner_supportedMechs) {
-	krb5_set_error_string(context, "Digest reply not an probe");
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret, "Digest reply not an probe");
 	goto out;
     }
=20
     *flags =3D DigestTypes2int(irep.u.supportedMechs);
=20
-out:
+ out:
     free_DigestRepInner(&irep);
=20
     return ret;
 }
+
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/doxygen.c
--- a/head/crypto/heimdal/lib/krb5/doxygen.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/doxygen.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,67 +1,700 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007-2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-RCSID("$Id$");
=20
 /**
- *=20
+ *
  */
=20
-/*! \mainpage Heimdal Kerberos 5 library
+/*! @mainpage Heimdal Kerberos 5 library
  *
- * \section intro Introduction
+ * @section intro Introduction
  *
  * Heimdal libkrb5 library is a implementation of the Kerberos
  * protocol.
- *=20
+ *
  * Kerberos is a system for authenticating users and services on a
  * network.  It is built upon the assumption that the network is
  * ``unsafe''.  For example, data sent over the network can be
  * eavesdropped and altered, and addresses can also be faked.
  * Therefore they cannot be used for authentication purposes.
  *
- * The project web page:\n
- * http://www.h5l.org/
+ *
+ * - @ref krb5_introduction
+ * - @ref krb5_principal_intro
+ * - @ref krb5_ccache_intro
+ * - @ref krb5_keytab_intro
+ *
+ * If you want to know more about the file formats that is used by
+ * Heimdal, please see: @ref krb5_fileformats
+ *
+ * The project web page: http://www.h5l.org/
  *
  */
=20
 /** @defgroup krb5 Heimdal Kerberos 5 library */
 /** @defgroup krb5_address Heimdal Kerberos 5 address functions */
+/** @defgroup krb5_principal Heimdal Kerberos 5 principal functions */
 /** @defgroup krb5_ccache Heimdal Kerberos 5 credential cache functions */
+/** @defgroup krb5_crypto Heimdal Kerberos 5 cryptography functions */
 /** @defgroup krb5_credential Heimdal Kerberos 5 credential handing functi=
ons */
 /** @defgroup krb5_deprecated Heimdal Kerberos 5 deprecated functions */
 /** @defgroup krb5_digest Heimdal Kerberos 5 digest service */
 /** @defgroup krb5_error Heimdal Kerberos 5 error reporting functions */
+/** @defgroup krb5_keytab Heimdal Kerberos 5 keytab handling functions */
+/** @defgroup krb5_ticket Heimdal Kerberos 5 ticket functions */
+/** @defgroup krb5_pac Heimdal Kerberos 5 PAC handling functions */
 /** @defgroup krb5_v4compat Heimdal Kerberos 4 compatiblity functions */
+/** @defgroup krb5_storage Heimdal Kerberos 5 storage functions */
 /** @defgroup krb5_support Heimdal Kerberos 5 support functions */
+/** @defgroup krb5_auth Heimdal Kerberos 5 authentication functions */
+
+
+/**
+ * @page krb5_introduction Introduction to the Kerberos 5 API
+ * @section api_overview Kerberos 5 API Overview
+ *
+ * All functions are documented in manual pages.  This section tries
+ * to give an overview of the major components used in Kerberos
+ * library, and point to where to look for a specific function.
+ *
+ * @subsection intro_krb5_context Kerberos context
+ *
+ * A kerberos context (krb5_context) holds all per thread state. All
+ * global variables that are context specific are stored in this
+ * structure, including default encryption types, credential cache
+ * (for example, a ticket file), and default realms.
+ *
+ * The internals of the structure should never be accessed directly,
+ * functions exist for extracting information.
+ *
+ * See the manual page for krb5_init_context() how to create a context
+ * and module @ref krb5 for more information about the functions.
+ *
+ * @subsection intro_krb5_auth_context Kerberos authentication context
+ *
+ * Kerberos authentication context (krb5_auth_context) holds all
+ * context related to an authenticated connection, in a similar way to
+ * the kerberos context that holds the context for the thread or
+ * process.
+ *
+ * The krb5_auth_context is used by various functions that are
+ * directly related to authentication between the
+ * server/client. Example of data that this structure contains are
+ * various flags, addresses of client and server, port numbers,
+ * keyblocks (and subkeys), sequence numbers, replay cache, and
+ * checksum types.
+ *
+ * @subsection intro_krb5_principal Kerberos principal
+ *
+ * The Kerberos principal is the structure that identifies a user or
+ * service in Kerberos. The structure that holds the principal is the
+ * krb5_principal. There are function to extract the realm and
+ * elements of the principal, but most applications have no reason to
+ * inspect the content of the structure.
+ *
+ * The are several ways to create a principal (with different degree of
+ * portability), and one way to free it.
+ *
+ * See also the page @ref krb5_principal_intro for more information and al=
so
+ * module @ref krb5_principal.
+ *
+ * @subsection intro_krb5_ccache Credential cache
+ *
+ * A credential cache holds the tickets for a user. A given user can
+ * have several credential caches, one for each realm where the user
+ * have the initial tickets (the first krbtgt).
+ *
+ * The credential cache data can be stored internally in different
+ * way, each of them for different proposes.  File credential (FILE)
+ * caches and processes based (KCM) caches are for permanent
+ * storage. While memory caches (MEMORY) are local caches to the local
+ * process.
+ *
+ * Caches are opened with krb5_cc_resolve() or created with
+ * krb5_cc_new_unique().
+ *
+ * If the cache needs to be opened again (using krb5_cc_resolve())
+ * krb5_cc_close() will close the handle, but not the remove the
+ * cache. krb5_cc_destroy() will zero out the cache, remove the cache
+ * so it can no longer be referenced.
+ *
+ * See also @ref krb5_ccache_intro and @ref krb5_ccache .
+ *
+ * @subsection intro_krb5_error_code Kerberos errors
+ *
+ * Kerberos errors are based on the com_err library.  All error codes are
+ * 32-bit signed numbers, the first 24 bits define what subsystem the
+ * error originates from, and last 8 bits are 255 error codes within the
+ * library.  Each error code have fixed string associated with it.  For
+ * example, the error-code -1765328383 have the symbolic name
+ * KRB5KDC_ERR_NAME_EXP, and associated error string ``Client's entry in
+ * database has expired''.
+ *
+ * This is a great improvement compared to just getting one of the unix
+ * error-codes back.  However, Heimdal have an extention to pass back
+ * customised errors messages.  Instead of getting ``Key table entry not
+ * found'', the user might back ``failed to find
+ * host/host.example.com\@EXAMLE.COM(kvno 3) in keytab /etc/krb5.keytab
+ * (des-cbc-crc)''.  This improves the chance that the user find the
+ * cause of the error so you should use the customised error message
+ * whenever it's available.
+ *
+ * See also module @ref krb5_error .
+ *
+ *
+ * @subsection intro_krb5_keytab Keytab management
+ *
+ * A keytab is a storage for locally stored keys. Heimdal includes keytab
+ * support for Kerberos 5 keytabs, Kerberos 4 srvtab, AFS-KeyFile's,
+ * and for storing keys in memory.
+ *
+ * Keytabs are used for servers and long-running services.
+ *
+ * See also @ref krb5_keytab_intro and @ref krb5_keytab .
+ *
+ * @subsection intro_krb5_crypto Kerberos crypto
+ *
+ * Heimdal includes a implementation of the Kerberos crypto framework,
+ * all crypto operations. To create a crypto context call krb5_crypto_init=
().
+ *
+ * See also module @ref krb5_crypto .
+ *
+ * @section kerberos5_client Walkthrough of a sample Kerberos 5 client
+ *
+ * This example contains parts of a sample TCP Kerberos 5 clients, if you
+ * want a real working client, please look in appl/test directory in
+ * the Heimdal distribution.
+ *
+ * All Kerberos error-codes that are returned from kerberos functions in
+ * this program are passed to krb5_err, that will print a
+ * descriptive text of the error code and exit. Graphical programs can
+ * convert error-code to a human readable error-string with the
+ * krb5_get_error_message() function.
+ *
+ * Note that you should not use any Kerberos function before
+ * krb5_init_context() have completed successfully. That is the
+ * reason err() is used when krb5_init_context() fails.
+ *
+ * First the client needs to call krb5_init_context to initialise
+ * the Kerberos 5 library. This is only needed once per thread
+ * in the program. If the function returns a non-zero value it indicates
+ * that either the Kerberos implementation is failing or it's disabled on
+ * this host.
+ *
+ * @code
+ * #include <krb5.h>
+ *
+ * int
+ * main(int argc, char **argv)
+ * {
+ *         krb5_context context;
+ *
+ *         if (krb5_init_context(&context))
+ *                 errx (1, "krb5_context");
+ * @endcode
+ *
+ * Now the client wants to connect to the host at the other end. The
+ * preferred way of doing this is using getaddrinfo (for
+ * operating system that have this function implemented), since getaddrinfo
+ * is neutral to the address type and can use any protocol that is availab=
le.
+ *
+ * @code
+ *         struct addrinfo *ai, *a;
+ *         struct addrinfo hints;
+ *         int error;
+ *
+ *         memset (&hints, 0, sizeof(hints));
+ *         hints.ai_socktype =3D SOCK_STREAM;
+ *         hints.ai_protocol =3D IPPROTO_TCP;
+ *
+ *         error =3D getaddrinfo (hostname, "pop3", &hints, &ai);
+ *         if (error)
+ *                 errx (1, "%s: %s", hostname, gai_strerror(error));
+ *
+ *         for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
+ *                 int s;
+ *
+ *                 s =3D socket (a->ai_family, a->ai_socktype, a->ai_proto=
col);
+ *                 if (s < 0)
+ *                         continue;
+ *                 if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
+ *                         warn ("connect(%s)", hostname);
+ *                             close (s);
+ *                             continue;
+ *                 }
+ *                 freeaddrinfo (ai);
+ *                 ai =3D NULL;
+ *         }
+ *         if (ai) {
+ *                     freeaddrinfo (ai);
+ *                     errx ("failed to contact %s", hostname);
+ *         }
+ * @endcode
+ *
+ * Before authenticating, an authentication context needs to be
+ * created. This context keeps all information for one (to be) authenticat=
ed
+ * connection (see krb5_auth_context).
+ *
+ * @code
+ *         status =3D krb5_auth_con_init (context, &auth_context);
+ *         if (status)
+ *                 krb5_err (context, 1, status, "krb5_auth_con_init");
+ * @endcode
+ *
+ * For setting the address in the authentication there is a help function
+ * krb5_auth_con_setaddrs_from_fd() that does everything that is needed
+ * when given a connected file descriptor to the socket.
+ *
+ * @code
+ *         status =3D krb5_auth_con_setaddrs_from_fd (context,
+ *                                                  auth_context,
+ *                                                  &sock);
+ *         if (status)
+ *                 krb5_err (context, 1, status,
+ *                           "krb5_auth_con_setaddrs_from_fd");
+ * @endcode
+ *
+ * The next step is to build a server principal for the service we want
+ * to connect to. (See also krb5_sname_to_principal().)
+ *
+ * @code
+ *         status =3D krb5_sname_to_principal (context,
+ *                                           hostname,
+ *                                           service,
+ *                                           KRB5_NT_SRV_HST,
+ *                                           &server);
+ *         if (status)
+ *                 krb5_err (context, 1, status, "krb5_sname_to_principal"=
);
+ * @endcode
+ *
+ * The client principal is not passed to krb5_sendauth()
+ * function, this causes the krb5_sendauth() function to try to figure it
+ * out itself.
+ *
+ * The server program is using the function krb5_recvauth() to
+ * receive the Kerberos 5 authenticator.
+ *
+ * In this case, mutual authentication will be tried. That means that the =
server
+ * will authenticate to the client. Using mutual authentication
+ * is good since it enables the user to verify that they are talking to the
+ * right server (a server that knows the key).
+ *
+ * If you are using a non-blocking socket you will need to do all work of
+ * krb5_sendauth() yourself. Basically you need to send over the
+ * authenticator from krb5_mk_req() and, in case of mutual
+ * authentication, verifying the result from the server with
+ * krb5_rd_rep().
+ *
+ * @code
+ *         status =3D krb5_sendauth (context,
+ *                                 &auth_context,
+ *                                 &sock,
+ *                                 VERSION,
+ *                                 NULL,
+ *                                 server,
+ *                                 AP_OPTS_MUTUAL_REQUIRED,
+ *                                 NULL,
+ *                                 NULL,
+ *                                 NULL,
+ *                                 NULL,
+ *                                 NULL,
+ *                                 NULL);
+ *         if (status)
+ *                 krb5_err (context, 1, status, "krb5_sendauth");
+ * @endcode
+ *
+ * Once authentication has been performed, it is time to send some
+ * data. First we create a krb5_data structure, then we sign it with
+ * krb5_mk_safe() using the auth_context that contains the
+ * session-key that was exchanged in the
+ * krb5_sendauth()/krb5_recvauth() authentication
+ * sequence.
+ *
+ * @code
+ *         data.data   =3D "hej";
+ *         data.length =3D 3;
+ *
+ *         krb5_data_zero (&packet);
+ *
+ *         status =3D krb5_mk_safe (context,
+ *                                auth_context,
+ *                                &data,
+ *                                &packet,
+ *                                NULL);
+ *         if (status)
+ *                 krb5_err (context, 1, status, "krb5_mk_safe");
+ * @endcode
+ *
+ * And send it over the network.
+ *
+ * @code
+ *         len =3D packet.length;
+ *         net_len =3D htonl(len);
+ *
+ *         if (krb5_net_write (context, &sock, &net_len, 4) !=3D 4)
+ *                 err (1, "krb5_net_write");
+ *         if (krb5_net_write (context, &sock, packet.data, len) !=3D len)
+ *                 err (1, "krb5_net_write");
+ * @endcode
+ *
+ * To send encrypted (and signed) data krb5_mk_priv() should be
+ * used instead. krb5_mk_priv() works the same way as
+ * krb5_mk_safe(), with the exception that it encrypts the data
+ * in addition to signing it.
+ *
+ * @code
+ *         data.data   =3D "hemligt";
+ *         data.length =3D 7;
+ *
+ *         krb5_data_free (&packet);
+ *
+ *         status =3D krb5_mk_priv (context,
+ *                                auth_context,
+ *                                &data,
+ *                                &packet,
+ *                                NULL);
+ *         if (status)
+ *                 krb5_err (context, 1, status, "krb5_mk_priv");
+ * @endcode
+ *
+ * And send it over the network.
+ *
+ * @code
+ *         len =3D packet.length;
+ *         net_len =3D htonl(len);
+ *
+ *         if (krb5_net_write (context, &sock, &net_len, 4) !=3D 4)
+ *                 err (1, "krb5_net_write");
+ *         if (krb5_net_write (context, &sock, packet.data, len) !=3D len)
+ *                 err (1, "krb5_net_write");
+ *
+ * @endcode
+ *
+ * The server is using krb5_rd_safe() and
+ * krb5_rd_priv() to verify the signature and decrypt the packet.
+ *
+ * @section intro_krb5_verify_user Validating a password in an application
+ *
+ * See the manual page for krb5_verify_user().
+ *
+ * @section mit_differences API differences to MIT Kerberos
+ *
+ * This section is somewhat disorganised, but so far there is no overall
+ * structure to the differences, though some of the have their root in
+ * that Heimdal uses an ASN.1 compiler and MIT doesn't.
+ *
+ * @subsection mit_krb5_principal Principal and realms
+ *
+ * Heimdal stores the realm as a krb5_realm, that is a char *.
+ * MIT Kerberos uses a krb5_data to store a realm.
+ *
+ * In Heimdal krb5_principal doesn't contain the component
+ * name_type; it's instead stored in component
+ * name.name_type. To get and set the nametype in Heimdal, use
+ * krb5_principal_get_type() and
+ * krb5_principal_set_type().
+ *
+ * For more information about principal and realms, see
+ * krb5_principal.
+ *
+ * @subsection mit_krb5_error_code Error messages
+ *
+ * To get the error string, Heimdal uses
+ * krb5_get_error_message(). This is to return custom error messages
+ * (like ``Can't find host/datan.example.com\@CODE.COM in
+ * /etc/krb5.conf.'' instead of a ``Key table entry not found'' that
+ * error_message returns.
+ *
+ * Heimdal uses a threadsafe(r) version of the com_err interface; the
+ * global com_err table isn't initialised.  Then
+ * error_message returns quite a boring error string (just
+ * the error code itself).
+ *
+ *
+ */
+
+/**
+ *
+ *
+ * @page krb5_fileformats File formats
+ *
+ * @section fileformats File formats
+ *
+ * This section documents the diffrent file formats that are used in
+ * Heimdal and other Kerberos implementations.
+ *
+ * @subsection file_keytab keytab
+ *
+ * The keytab binary format is not a standard format. The format has
+ * evolved and may continue to. It is however understood by several
+ * Kerberos implementations including Heimdal, MIT, Sun's Java ktab and
+ * are created by the ktpass.exe utility from Windows. So it has
+ * established itself as the defacto format for storing Kerberos keys.
+ *
+ * The following C-like structure definitions illustrate the MIT keytab
+ * file format. All values are in network byte order. All text is ASCII.
+ *
+ * @code
+ *   keytab {
+ *       uint16_t file_format_version;                    # 0x502
+ *       keytab_entry entries[*];
+ *   };
+ *
+ *   keytab_entry {
+ *       int32_t size;
+ *       uint16_t num_components;   # subtract 1 if version 0x501
+ *       counted_octet_string realm;
+ *       counted_octet_string components[num_components];
+ *       uint32_t name_type;       # not present if version 0x501
+ *       uint32_t timestamp;
+ *       uint8_t vno8;
+ *       keyblock key;
+ *       uint32_t vno; #only present if >=3D 4 bytes left in entry
+ *       uint32_t flags; #only present if >=3D 4 bytes left in entry
+ *   };
+ *
+ *   counted_octet_string {
+ *       uint16_t length;
+ *       uint8_t data[length];
+ *   };
+ *
+ *   keyblock {
+ *       uint16_t type;
+ *       counted_octet_string;
+ *   };
+ * @endcode
+ *
+ * All numbers are stored in network byteorder (big endian) format.
+ *
+ * The keytab file format begins with the 16 bit file_format_version which
+ * at the time this document was authored is 0x502. The format of older
+ * keytabs is described at the end of this document.
+ *
+ * The file_format_version is immediately followed by an array of
+ * keytab_entry structures which are prefixed with a 32 bit size indicating
+ * the number of bytes that follow in the entry. Note that the size should=
 be
+ * evaluated as signed. This is because a negative value indicates that the
+ * entry is in fact empty (e.g. it has been deleted) and that the negative
+ * value of that negative value (which is of course a positive value) is
+ * the offset to the next keytab_entry. Based on these size values alone
+ * the entire keytab file can be traversed.
+ *
+ * The size is followed by a 16 bit num_components field indicating the
+ * number of counted_octet_string components in the components array.
+ *
+ * The num_components field is followed by a counted_octet_string
+ * representing the realm of the principal.
+ *
+ * A counted_octet_string is simply an array of bytes prefixed with a 16
+ * bit length. For the realm and name components, the counted_octet_string
+ * bytes are ASCII encoded text with no zero terminator.
+ *
+ * Following the realm is the components array that represents the name of
+ * the principal. The text of these components may be joined with slashs
+ * to construct the typical SPN representation. For example, the service
+ * principal HTTP/www.foo.net\@FOO.NET would consist of name components
+ * "HTTP" followed by "www.foo.net".
+ *
+ * Following the components array is the 32 bit name_type (e.g. 1 is
+ * KRB5_NT_PRINCIPAL, 2 is KRB5_NT_SRV_INST, 5 is KRB5_NT_UID, etc). In
+ * practice the name_type is almost certainly 1 meaning KRB5_NT_PRINCIPAL.
+ *
+ * The 32 bit timestamp indicates the time the key was established for that
+ * principal. The value represents the number of seconds since Jan 1, 1970.
+ *
+ * The 8 bit vno8 field is the version number of the key. This value is
+ * overridden by the 32 bit vno field if it is present. The vno8 field is
+ * filled with the lower 8 bits of the 32 bit protocol kvno field.
+ *
+ * The keyblock structure consists of a 16 bit value indicating the
+ * encryption type and is a counted_octet_string containing the key.  The
+ * encryption type is the same as the Kerberos standard (e.g. 3 is
+ * des-cbc-md5, 23 is arcfour-hmac-md5, etc).
+ *
+ * The last field of the keytab_entry structure is optional. If the size of
+ * the keytab_entry indicates that there are at least 4 bytes remaining,
+ * a 32 bit value representing the key version number is present. This
+ * value supersedes the 8 bit vno8 value preceeding the keyblock.
+ *
+ * Older keytabs with a file_format_version of 0x501 are different in
+ * three ways:
+ *
+ * - All integers are in host byte order [1].
+ * - The num_components field is 1 too large (i.e. after decoding, decreme=
nt by 1).
+ * - The 32 bit name_type field is not present.
+ *
+ * [1] The file_format_version field should really be treated as two
+ * separate 8 bit quantities representing the major and minor version
+ * number respectively.
+ *
+ * @subsection file_hdb_dump Heimdal database dump file
+ *
+ * Format of the Heimdal text dump file as of Heimdal 0.6.3:
+ *
+ * Each line in the dump file is one entry in the database.
+ *
+ * Each field of a line is separated by one or more spaces, with the
+ * exception of fields consisting of principals containing spaces, where
+ * space can be quoted with \ and \ is quoted by \.
+ *
+ * Fields and their types are:
+ *
+ * @code
+ * 	Quoted princial (quote character is \) [string]
+ * 	Keys [keys]
+ * 	Created by [event]
+ * 	Modified by [event optional]
+ * 	Valid start time [time optional]
+ * 	Valid end time [time optional]
+ * 	Password end valid time [time optional]
+ * 	Max lifetime of ticket [time optional]
+ * 	Max renew time of ticket [integer optional]
+ * 	Flags [hdb flags]
+ * 	Generation number [generation optional]
+ * 	Extensions [extentions optional]
+ * @endcode
+ *
+ * Fields following these silently are ignored.
+ *
+ * All optional fields will be skipped if they fail to parse (or comprise
+ * the optional field marker of "-", w/o quotes).
+ *
+ * Example:
+ *
+ * @code
+ * fred\@CODE.COM 27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba3737=
33d26ca59ba6c789666f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a9338811=
78c744f4232172dcd774c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b1=
3eb795d76f3a80717d469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e=
16d8078bf60c781da90f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:- 2002=
0415130120:admin\@CODE.COM 20041221112428:fred\@CODE.COM - - - 86400 604800=
 126 20020415130120:793707:28 -
+ * @endcode
+ *
+ * Encoding of types are as follows:
+ *
+ * - keys
+ *
+ * @code
+ * kvno:[masterkvno:keytype:keydata:salt]{zero or more separated by :}
+ * @endcode
+ *
+ * kvno is the key version number.
+ *
+ * keydata is hex-encoded
+ *
+ * masterkvno is the kvno of the database master key.  If this field is
+ * empty, the kadmin load and merge operations will encrypt the key data
+ * with the master key if there is one.  Otherwise the key data will be
+ * imported asis.
+ *
+ * salt is encoded as "-" (no/default salt) or
+ *
+ * @code
+ * salt-type /
+ * salt-type / "string"
+ * salt-type / hex-encoded-data
+ * @endcode
+ *
+ * keytype is the protocol enctype number; see enum ENCTYPE in
+ * include/krb5_asn1.h for values.
+ *
+ * Example:
+ * @code
+ * 27:1:16:e8b4c8fc7e60b9e641dcf4cff3f08a701d982a2f89ba373733d26ca59ba6c78=
9666f6b8bfcf169412bb1e5dceb9b33cda29f3412:-:1:3:4498a933881178c744f4232172d=
cd774c64e81fa6d05ecdf643a7e390624a0ebf3c7407a:-:1:2:b01934b13eb795d76f3a807=
17d469639b4da0cfb644161340ef44fdeb375e54d684dbb85:-:1:1:ea8e16d8078bf60c781=
da90f508d4deccba70595258b9d31888d33987cd31af0c9cced2e:-
+ * @endcode
+ *
+ *
+ * @code
+ * kvno=3D27,{key: masterkvno=3D1,keytype=3Ddes3-cbc-sha1,keydata=3D..., d=
efault salt}...
+ * @endcode
+ *
+ * - time
+ *
+ * Format of the time is: YYYYmmddHHMMSS, corresponding to strftime
+ * format "%Y%m%d%k%M%S".
+ *
+ * Time is expressed in UTC.
+ *
+ * Time can be optional (using -), when the time 0 is used.
+ *
+ * Example:
+ *
+ * @code
+ * 20041221112428
+ * @endcode
+ *
+ * - event
+ *
+ * @code
+ * 	time:principal
+ * @endcode
+ *
+ * time is as given in format time
+ *
+ * principal is a string.  Not quoting it may not work in earlier
+ * versions of Heimdal.
+ *
+ * Example:
+ * @code
+ * 20041221112428:bloggs\@CODE.COM
+ * @endcode
+ *
+ * - hdb flags
+ *
+ * Integer encoding of HDB flags, see HDBFlags in lib/hdb/hdb.asn1. Each
+ * bit in the integer is the same as the bit in the specification.
+ *
+ * - generation:
+ *
+ * @code
+ * time:usec:gen
+ * @endcode
+ *
+ *
+ * usec is a the microsecond, integer.
+ * gen is generation number, integer.
+ *
+ * The generation can be defaulted (using '-') or the empty string
+ *
+ * - extensions:
+ *
+ * @code
+ * first-hex-encoded-HDB-Extension[:second-...]
+ * @endcode
+ *
+ * HDB-extension is encoded the DER encoded HDB-Extension from
+ * lib/hdb/hdb.asn1. Consumers HDB extensions should be aware that
+ * unknown entires needs to be preserved even thought the ASN.1 data
+ * content might be unknown. There is a critical flag in the data to show
+ * to the KDC that the entry MUST be understod if the entry is to be
+ * used.
+ *
+ *
+ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/eai_to_he=
im_errno.c
--- a/head/crypto/heimdal/lib/krb5/eai_to_heim_errno.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/eai_to_heim_errno.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 2000 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
-
-RCSID("$Id: eai_to_heim_errno.c 22065 2007-11-11 16:41:06Z lha $");
+#include "krb5_locl.h"
=20
 /**
  * Convert the getaddrinfo() error code to a Kerberos et error code.
@@ -46,7 +44,7 @@
  * @ingroup krb5_error
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_eai_to_heim_errno(int eai_errno, int system_error)
 {
     switch(eai_errno) {
@@ -70,14 +68,20 @@
     case EAI_NODATA:
 	return HEIM_EAI_NODATA;
 #endif
+#ifdef WSANO_DATA
+    case WSANO_DATA:
+	return HEIM_EAI_NODATA;
+#endif
     case EAI_NONAME:
 	return HEIM_EAI_NONAME;
     case EAI_SERVICE:
 	return HEIM_EAI_SERVICE;
     case EAI_SOCKTYPE:
 	return HEIM_EAI_SOCKTYPE;
+#ifdef EAI_SYSTEM
     case EAI_SYSTEM:
 	return system_error;
+#endif
     default:
 	return HEIM_EAI_UNKNOWN; /* XXX */
     }
@@ -94,7 +98,7 @@
  * @ingroup krb5_error
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_h_errno_to_heim_errno(int eai_errno)
 {
     switch(eai_errno) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/error_str=
ing.c
--- a/head/crypto/heimdal/lib/krb5/error_string.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/error_string.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,104 +1,209 @@
 /*
- * Copyright (c) 2001, 2003, 2005 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001, 2003, 2005 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: error_string.c 22142 2007-12-04 16:56:02Z lha $");
+#undef __attribute__
+#define __attribute__(x)
=20
-#undef __attribute__
-#define __attribute__(X)
+/**
+ * Clears the error message from the Kerberos 5 context.
+ *
+ * @param context The Kerberos 5 context to clear
+ *
+ * @ingroup krb5_error
+ */
=20
-void KRB5_LIB_FUNCTION
-krb5_free_error_string(krb5_context context, char *str)
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_clear_error_message(krb5_context context)
 {
     HEIMDAL_MUTEX_lock(context->mutex);
-    if (str !=3D context->error_buf)
-	free(str);
-    HEIMDAL_MUTEX_unlock(context->mutex);
-}
-
-void KRB5_LIB_FUNCTION
-krb5_clear_error_string(krb5_context context)
-{
-    HEIMDAL_MUTEX_lock(context->mutex);
-    if (context->error_string !=3D NULL
-	&& context->error_string !=3D context->error_buf)
+    if (context->error_string)
 	free(context->error_string);
+    context->error_code =3D 0;
     context->error_string =3D NULL;
     HEIMDAL_MUTEX_unlock(context->mutex);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_set_error_string(krb5_context context, const char *fmt, ...)
-    __attribute__((format (printf, 2, 3)))
+/**
+ * Set the context full error string for a specific error code.
+ * The error that is stored should be internationalized.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param ... printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_set_error_message(krb5_context context, krb5_error_code ret,
+		       const char *fmt, ...)
+    __attribute__ ((format (printf, 3, 4)))
 {
-    krb5_error_code ret;
     va_list ap;
=20
     va_start(ap, fmt);
-    ret =3D krb5_vset_error_string (context, fmt, ap);
+    krb5_vset_error_message (context, ret, fmt, ap);
     va_end(ap);
-    return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_vset_error_string(krb5_context context, const char *fmt, va_list args)
-    __attribute__ ((format (printf, 2, 0)))
+/**
+ * Set the context full error string for a specific error code.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param args printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_vset_error_message (krb5_context context, krb5_error_code ret,
+			 const char *fmt, va_list args)
+    __attribute__ ((format (printf, 3, 0)))
 {
-    krb5_clear_error_string(context);
+    int r;
+
+    if (context =3D=3D NULL)
+	return;
+
     HEIMDAL_MUTEX_lock(context->mutex);
-    vasprintf(&context->error_string, fmt, args);
-    if(context->error_string =3D=3D NULL) {
-	vsnprintf (context->error_buf, sizeof(context->error_buf), fmt, args);
-	context->error_string =3D context->error_buf;
+    if (context->error_string) {
+	free(context->error_string);
+	context->error_string =3D NULL;
     }
+    context->error_code =3D ret;
+    r =3D vasprintf(&context->error_string, fmt, args);
+    if (r < 0)
+	context->error_string =3D NULL;
     HEIMDAL_MUTEX_unlock(context->mutex);
-    return 0;
 }
=20
 /**
+ * Prepend the context full error string for a specific error code.
+ * The error that is stored should be internationalized.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param ... printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_prepend_error_message(krb5_context context, krb5_error_code ret,
+			   const char *fmt, ...)
+    __attribute__ ((format (printf, 3, 4)))
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    krb5_vprepend_error_message(context, ret, fmt, ap);
+    va_end(ap);
+}
+
+/**
+ * Prepend the contexts's full error string for a specific error code.
+ *
+ * The if context is NULL, no error string is stored.
+ *
+ * @param context Kerberos 5 context
+ * @param ret The error code
+ * @param fmt Error string for the error code
+ * @param args printf(3) style parameters.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_vprepend_error_message(krb5_context context, krb5_error_code ret,
+			    const char *fmt, va_list args)
+    __attribute__ ((format (printf, 3, 0)))
+{
+    char *str =3D NULL, *str2 =3D NULL;
+
+    if (context =3D=3D NULL)
+	return;
+
+    HEIMDAL_MUTEX_lock(context->mutex);
+    if (context->error_code !=3D ret) {
+	HEIMDAL_MUTEX_unlock(context->mutex);
+	return;
+    }
+    if (vasprintf(&str, fmt, args) < 0 || str =3D=3D NULL) {
+	HEIMDAL_MUTEX_unlock(context->mutex);
+	return;
+    }
+    if (context->error_string) {
+	int e;
+
+	e =3D asprintf(&str2, "%s: %s", str, context->error_string);
+	free(context->error_string);
+	if (e < 0 || str2 =3D=3D NULL)
+	    context->error_string =3D NULL;
+	else
+	    context->error_string =3D str2;
+	free(str);
+    } else
+	context->error_string =3D str;
+    HEIMDAL_MUTEX_unlock(context->mutex);
+}
+
+
+/**
  * Return the error message in context. On error or no error string,
  * the function returns NULL.
  *
  * @param context Kerberos 5 context
  *
  * @return an error string, needs to be freed with
- * krb5_free_error_string(). The functions return NULL on error.
+ * krb5_free_error_message(). The functions return NULL on error.
  *
  * @ingroup krb5_error
  */
=20
-char * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION char * KRB5_LIB_CALL
 krb5_get_error_string(krb5_context context)
 {
     char *ret =3D NULL;
@@ -110,7 +215,7 @@
     return ret;
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_have_error_string(krb5_context context)
 {
     char *str;
@@ -121,35 +226,117 @@
 }
=20
 /**
- * Return the error message for `code' in context. On error the
- * function returns NULL.
+ * Return the error message for `code' in context. On memory
+ * allocation error the function returns NULL.
  *
  * @param context Kerberos 5 context
  * @param code Error code related to the error
  *
  * @return an error string, needs to be freed with
- * krb5_free_error_string(). The functions return NULL on error.
+ * krb5_free_error_message(). The functions return NULL on error.
  *
  * @ingroup krb5_error
  */
=20
-char * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_get_error_message(krb5_context context, krb5_error_code code)
 {
-    const char *cstr;
-    char *str;
+    char *str =3D NULL;
+    const char *cstr =3D NULL;
+    char buf[128];
+    int free_context =3D 0;
=20
-    str =3D krb5_get_error_string(context);
-    if (str)
-	return str;
+    if (code =3D=3D 0)
+	return strdup("Success");
=20
-    cstr =3D krb5_get_err_text(context, code);
+    /*
+     * The MIT version of this function ignores the krb5_context
+     * and several widely deployed applications call krb5_get_error_messag=
e()
+     * with a NULL context in order to translate an error code as a
+     * replacement for error_message().  Another reason a NULL context
+     * might be provided is if the krb5_init_context() call itself
+     * failed.
+     */
+    if (context)
+    {
+        HEIMDAL_MUTEX_lock(context->mutex);
+        if (context->error_string &&
+            (code =3D=3D context->error_code || context->error_code =3D=3D=
 0))
+        {
+            str =3D strdup(context->error_string);
+        }
+        HEIMDAL_MUTEX_unlock(context->mutex);
+
+        if (str)
+            return str;
+    }
+    else
+    {
+        if (krb5_init_context(&context) =3D=3D 0)
+            free_context =3D 1;
+    }
+
+    if (context)
+        cstr =3D com_right_r(context->et_list, code, buf, sizeof(buf));
+
+    if (free_context)
+        krb5_free_context(context);
+
     if (cstr)
-	return strdup(cstr);
+        return strdup(cstr);
=20
-    if (asprintf(&str, "<unknown error: %d>", code) =3D=3D -1)
+    cstr =3D error_message(code);
+    if (cstr)
+        return strdup(cstr);
+
+    if (asprintf(&str, "<unknown error: %d>", (int)code) =3D=3D -1 || str =
=3D=3D NULL)
 	return NULL;
=20
     return str;
 }
=20
+
+/**
+ * Free the error message returned by krb5_get_error_message().
+ *
+ * @param context Kerberos context
+ * @param msg error message to free, returned byg
+ *        krb5_get_error_message().
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_error_message(krb5_context context, const char *msg)
+{
+    free(rk_UNCONST(msg));
+}
+
+
+/**
+ * Return the error string for the error code. The caller must not
+ * free the string.
+ *
+ * This function is deprecated since its not threadsafe.
+ *
+ * @param context Kerberos 5 context.
+ * @param code Kerberos error code.
+ *
+ * @return the error message matching code
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
+krb5_get_err_text(krb5_context context, krb5_error_code code)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+    const char *p =3D NULL;
+    if(context !=3D NULL)
+	p =3D com_right(context->et_list, code);
+    if(p =3D=3D NULL)
+	p =3D strerror(code);
+    if (p =3D=3D NULL)
+	p =3D "Unknown error";
+    return p;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/expand_ho=
stname.c
--- a/head/crypto/heimdal/lib/krb5/expand_hostname.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/expand_hostname.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: expand_hostname.c 22229 2007-12-08 21:40:59Z lha $");
-
 static krb5_error_code
 copy_hostname(krb5_context context,
 	      const char *orig_hostname,
@@ -42,19 +40,30 @@
 {
     *new_hostname =3D strdup (orig_hostname);
     if (*new_hostname =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     strlwr (*new_hostname);
     return 0;
 }
=20
-/*
- * Try to make `orig_hostname' into a more canonical one in the newly
- * allocated space returned in `new_hostname'.
+/**
+ * krb5_expand_hostname() tries to make orig_hostname into a more
+ * canonical one in the newly allocated space returned in
+ * new_hostname.
+
+ * @param context a Keberos context
+ * @param orig_hostname hostname to canonicalise.
+ * @param new_hostname output hostname, caller must free hostname with
+ *        krb5_xfree().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_support
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_expand_hostname (krb5_context context,
 		      const char *orig_hostname,
 		      char **new_hostname)
@@ -76,7 +85,8 @@
 	    *new_hostname =3D strdup (a->ai_canonname);
 	    freeaddrinfo (ai);
 	    if (*new_hostname =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
+		krb5_set_error_message(context, ENOMEM,
+				       N_("malloc: out of memory", ""));
 		return ENOMEM;
 	    } else {
 		return 0;
@@ -112,12 +122,25 @@
     return 0;
 }
=20
-/*
- * expand `hostname' to a name we believe to be a hostname in newly
- * allocated space in `host' and return realms in `realms'.
+/**
+ * krb5_expand_hostname_realms() expands orig_hostname to a name we
+ * believe to be a hostname in newly allocated space in new_hostname
+ * and return the realms new_hostname is believed to belong to in
+ * realms.
+ *
+ * @param context a Keberos context
+ * @param orig_hostname hostname to canonicalise.
+ * @param new_hostname output hostname, caller must free hostname with
+ *        krb5_xfree().
+ * @param realms output possible realms, is an array that is terminated
+ *        with NULL. Caller must free with krb5_free_host_realm().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_support
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_expand_hostname_realms (krb5_context context,
 			     const char *orig_hostname,
 			     char **new_hostname,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/fcache.c
--- a/head/crypto/heimdal/lib/krb5/fcache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/fcache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 1997 - 2008 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: fcache.c 22522 2008-01-24 11:56:25Z lha $");
-
 typedef struct krb5_fcache{
     char *filename;
     int version;
@@ -58,10 +58,13 @@
=20
 #define FCC_CURSOR(C) ((struct fcc_cursor*)(C))
=20
-static const char*
+static const char* KRB5_CALLCONV
 fcc_get_name(krb5_context context,
 	     krb5_ccache id)
 {
+    if (FCACHE(id) =3D=3D NULL)
+        return NULL;
+
     return FILENAME(id);
 }
=20
@@ -90,17 +93,22 @@
     case 0:
 	break;
     case EINVAL: /* filesystem doesn't support locking, let the user have =
it */
-	ret =3D 0;=20
+	ret =3D 0;
 	break;
     case EAGAIN:
-	krb5_set_error_string(context, "timed out locking cache file %s",=20
-			      filename);
+	krb5_set_error_message(context, ret,
+			       N_("timed out locking cache file %s", "file"),
+			       filename);
 	break;
-    default:
-	krb5_set_error_string(context, "error locking cache file %s: %s",
-			      filename, strerror(ret));
+    default: {
+	char buf[128];
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret,
+			       N_("error locking cache file %s: %s",
+				  "file, error"), filename, buf);
 	break;
     }
+    }
     return ret;
 }
=20
@@ -124,42 +132,72 @@
     case 0:
 	break;
     case EINVAL: /* filesystem doesn't support locking, let the user have =
it */
-	ret =3D 0;=20
+	ret =3D 0;
 	break;
-    default:
-	krb5_set_error_string(context,=20
-			      "Failed to unlock file: %s", strerror(ret));
+    default: {
+	char buf[128];
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret,
+			       N_("Failed to unlock file: %s", ""), buf);
 	break;
     }
+    }
     return ret;
 }
=20
 static krb5_error_code
+write_storage(krb5_context context, krb5_storage *sp, int fd)
+{
+    krb5_error_code ret;
+    krb5_data data;
+    ssize_t sret;
+
+    ret =3D krb5_storage_to_data(sp, &data);
+    if (ret) {
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	return ret;
+    }
+    sret =3D write(fd, data.data, data.length);
+    ret =3D (sret !=3D (ssize_t)data.length);
+    krb5_data_free(&data);
+    if (ret) {
+	ret =3D errno;
+	krb5_set_error_message(context, ret,
+			       N_("Failed to write FILE credential data", ""));
+	return ret;
+    }
+    return 0;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
 fcc_lock(krb5_context context, krb5_ccache id,
 	 int fd, krb5_boolean exclusive)
 {
     return _krb5_xlock(context, fd, exclusive, fcc_get_name(context, id));
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_unlock(krb5_context context, int fd)
 {
     return _krb5_xunlock(context, fd);
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_resolve(krb5_context context, krb5_ccache *id, const char *res)
 {
     krb5_fcache *f;
     f =3D malloc(sizeof(*f));
     if(f =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
     f->filename =3D strdup(res);
     if(f->filename =3D=3D NULL){
 	free(f);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
     f->version =3D 0;
@@ -185,13 +223,17 @@
         return errno;
     memset(buf, 0, sizeof(buf));
     while(pos > 0) {
-        ssize_t tmp =3D write(fd, buf, min(sizeof(buf), pos));
+        ssize_t tmp =3D write(fd, buf, min((off_t)sizeof(buf), pos));
=20
 	if (tmp < 0)
 	    return errno;
 	pos -=3D tmp;
     }
+#ifdef _MSC_VER
+    _commit (fd);
+#else
     fsync (fd);
+#endif
     return 0;
 }
=20
@@ -202,8 +244,8 @@
  * hardlink)
  */
=20
-static krb5_error_code
-erase_file(const char *filename)
+krb5_error_code
+_krb5_erase_file(krb5_context context, const char *filename)
 {
     int fd;
     struct stat sb1, sb2;
@@ -220,12 +262,20 @@
 	else
 	    return errno;
     }
+    rk_cloexec(fd);
+    ret =3D _krb5_xlock(context, fd, 1, filename);
+    if (ret) {
+	close(fd);
+	return ret;
+    }
     if (unlink(filename) < 0) {
+	_krb5_xunlock(context, fd);
         close (fd);
         return errno;
     }
     ret =3D fstat (fd, &sb2);
     if (ret < 0) {
+	_krb5_xunlock(context, fd);
 	close (fd);
 	return errno;
     }
@@ -233,6 +283,7 @@
     /* check if someone was playing with symlinks */
=20
     if (sb1.st_dev !=3D sb2.st_dev || sb1.st_ino !=3D sb2.st_ino) {
+	_krb5_xunlock(context, fd);
 	close (fd);
 	return EPERM;
     }
@@ -240,43 +291,60 @@
     /* there are still hard links to this file */
=20
     if (sb2.st_nlink !=3D 0) {
+	_krb5_xunlock(context, fd);
         close (fd);
         return 0;
     }
=20
     ret =3D scrub_file (fd);
+    if (ret) {
+	_krb5_xunlock(context, fd);
+	close(fd);
+	return ret;
+    }
+    ret =3D _krb5_xunlock(context, fd);
     close (fd);
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_gen_new(krb5_context context, krb5_ccache *id)
 {
+    char *file =3D NULL, *exp_file =3D NULL;
+    krb5_error_code ret;
     krb5_fcache *f;
     int fd;
-    char *file;
=20
     f =3D malloc(sizeof(*f));
     if(f =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
-    asprintf (&file, "%sXXXXXX", KRB5_DEFAULT_CCFILE_ROOT);
-    if(file =3D=3D NULL) {
+    ret =3D asprintf (&file, "%sXXXXXX", KRB5_DEFAULT_CCFILE_ROOT);
+    if(ret < 0 || file =3D=3D NULL) {
 	free(f);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
-    fd =3D mkstemp(file);
+    ret =3D _krb5_expand_path_tokens(context, file, &exp_file);
+    free(file);
+    if (ret)
+	return ret;
+
+    file =3D exp_file;
+
+    fd =3D mkstemp(exp_file);
     if(fd < 0) {
-	int ret =3D errno;
-	krb5_set_error_string(context, "mkstemp %s", file);
+	int xret =3D errno;
+	krb5_set_error_message(context, xret, N_("mkstemp %s failed", ""), exp_fi=
le);
 	free(f);
-	free(file);
-	return ret;
+	free(exp_file);
+	return xret;
     }
     close(fd);
-    f->filename =3D file;
+    f->filename =3D exp_file;
     f->version =3D 0;
     (*id)->data.data =3D f;
     (*id)->data.length =3D sizeof(*f);
@@ -302,13 +370,13 @@
     case KRB5_FCC_FVNO_4:
 	break;
     default:
-	krb5_abortx(context,=20
+	krb5_abortx(context,
 		    "storage_set_flags called with bad vno (%x)", vno);
     }
     krb5_storage_set_flags(sp, flags);
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_open(krb5_context context,
 	 krb5_ccache id,
 	 int *fd_ret,
@@ -318,16 +386,25 @@
     krb5_boolean exclusive =3D ((flags | O_WRONLY) =3D=3D flags ||
 			      (flags | O_RDWR) =3D=3D flags);
     krb5_error_code ret;
-    const char *filename =3D FILENAME(id);
+    const char *filename;
     int fd;
+
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
+    filename =3D FILENAME(id);
+
     fd =3D open(filename, flags, mode);
     if(fd < 0) {
+	char buf[128];
 	ret =3D errno;
-	krb5_set_error_string(context, "open(%s): %s", filename,
-			      strerror(ret));
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret, N_("open(%s): %s", "file, error"),
+			       filename, buf);
 	return ret;
     }
-=09
+    rk_cloexec(fd);
+
     if((ret =3D fcc_lock(context, id, fd, exclusive)) !=3D 0) {
 	close(fd);
 	return ret;
@@ -336,7 +413,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_initialize(krb5_context context,
 	       krb5_ccache id,
 	       krb5_principal primary_principal)
@@ -344,16 +421,18 @@
     krb5_fcache *f =3D FCACHE(id);
     int ret =3D 0;
     int fd;
-    char *filename =3D f->filename;
=20
-    unlink (filename);
- =20
-    ret =3D fcc_open(context, id, &fd, O_RDWR | O_CREAT | O_EXCL | O_BINAR=
Y, 0600);
+    if (f =3D=3D NULL)
+        return krb5_einval(context, 2);
+
+    unlink (f->filename);
+
+    ret =3D fcc_open(context, id, &fd, O_RDWR | O_CREAT | O_EXCL | O_BINAR=
Y | O_CLOEXEC, 0600);
     if(ret)
 	return ret;
     {
-	krb5_storage *sp;   =20
-	sp =3D krb5_storage_from_fd(fd);
+	krb5_storage *sp;
+	sp =3D krb5_storage_emem();
 	krb5_storage_set_eof_code(sp, KRB5_CC_END);
 	if(context->fcache_vno !=3D 0)
 	    f->version =3D context->fcache_vno;
@@ -375,37 +454,47 @@
 	    }
 	}
 	ret |=3D krb5_store_principal(sp, primary_principal);
-=09
+
+	ret |=3D write_storage(context, sp, fd);
+
 	krb5_storage_free(sp);
     }
     fcc_unlock(context, fd);
     if (close(fd) < 0)
 	if (ret =3D=3D 0) {
+	    char buf[128];
 	    ret =3D errno;
-	    krb5_set_error_string (context, "close %s: %s",=20
-				   FILENAME(id), strerror(ret));
+	    rk_strerror_r(ret, buf, sizeof(buf));
+	    krb5_set_error_message (context, ret, N_("close %s: %s", ""),
+				    FILENAME(id), buf);
 	}
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_close(krb5_context context,
 	  krb5_ccache id)
 {
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
     free (FILENAME(id));
     krb5_data_free(&id->data);
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_destroy(krb5_context context,
 	    krb5_ccache id)
 {
-    erase_file(FILENAME(id));
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
+    _krb5_erase_file(context, FILENAME(id));
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_store_cred(krb5_context context,
 	       krb5_ccache id,
 	       krb5_creds *creds)
@@ -413,12 +502,13 @@
     int ret;
     int fd;
=20
-    ret =3D fcc_open(context, id, &fd, O_WRONLY | O_APPEND | O_BINARY, 0);
+    ret =3D fcc_open(context, id, &fd, O_WRONLY | O_APPEND | O_BINARY | O_=
CLOEXEC, 0);
     if(ret)
 	return ret;
     {
 	krb5_storage *sp;
-	sp =3D krb5_storage_from_fd(fd);
+
+	sp =3D krb5_storage_emem();
 	krb5_storage_set_eof_code(sp, KRB5_CC_END);
 	storage_set_flags(context, sp, FCACHE(id)->version);
 	if (!krb5_config_get_bool_default(context, NULL, TRUE,
@@ -427,15 +517,20 @@
 					  NULL))
 	    krb5_storage_set_flags(sp, KRB5_STORAGE_CREDS_FLAGS_WRONG_BITORDER);
 	ret =3D krb5_store_creds(sp, creds);
+	if (ret =3D=3D 0)
+	    ret =3D write_storage(context, sp, fd);
 	krb5_storage_free(sp);
     }
     fcc_unlock(context, fd);
-    if (close(fd) < 0)
+    if (close(fd) < 0) {
 	if (ret =3D=3D 0) {
+	    char buf[128];
+	    rk_strerror_r(ret, buf, sizeof(buf));
 	    ret =3D errno;
-	    krb5_set_error_string (context, "close %s: %s",=20
-				   FILENAME(id), strerror(ret));
+	    krb5_set_error_message (context, ret, N_("close %s: %s", ""),
+				    FILENAME(id), buf);
 	}
+    }
     return ret;
 }
=20
@@ -443,20 +538,24 @@
 init_fcc (krb5_context context,
 	  krb5_ccache id,
 	  krb5_storage **ret_sp,
-	  int *ret_fd)
+	  int *ret_fd,
+	  krb5_deltat *kdc_offset)
 {
     int fd;
     int8_t pvno, tag;
     krb5_storage *sp;
     krb5_error_code ret;
=20
-    ret =3D fcc_open(context, id, &fd, O_RDONLY | O_BINARY, 0);
+    if (kdc_offset)
+	*kdc_offset =3D 0;
+
+    ret =3D fcc_open(context, id, &fd, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
     if(ret)
 	return ret;
-   =20
+
     sp =3D krb5_storage_from_fd(fd);
     if(sp =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	ret =3D ENOMEM;
 	goto out;
     }
@@ -464,25 +563,28 @@
     ret =3D krb5_ret_int8(sp, &pvno);
     if(ret !=3D 0) {
 	if(ret =3D=3D KRB5_CC_END) {
-	    krb5_set_error_string(context, "Empty credential cache file: %s",
-				  FILENAME(id));
 	    ret =3D ENOENT;
+	    krb5_set_error_message(context, ret,
+				   N_("Empty credential cache file: %s", ""),
+				   FILENAME(id));
 	} else
-	    krb5_set_error_string(context, "Error reading pvno in "
-				  "cache file: %s", FILENAME(id));
+	    krb5_set_error_message(context, ret, N_("Error reading pvno "
+						    "in cache file: %s", ""),
+				   FILENAME(id));
 	goto out;
     }
     if(pvno !=3D 5) {
-	krb5_set_error_string(context, "Bad version number in credential "
-			      "cache file: %s", FILENAME(id));
 	ret =3D KRB5_CCACHE_BADVNO;
+	krb5_set_error_message(context, ret, N_("Bad version number in credential=
 "
+						"cache file: %s", ""),
+			       FILENAME(id));
 	goto out;
     }
     ret =3D krb5_ret_int8(sp, &tag); /* should not be host byte order */
     if(ret !=3D 0) {
-	krb5_set_error_string(context, "Error reading tag in "
+	ret =3D KRB5_CC_FORMAT;
+	krb5_set_error_message(context, ret, "Error reading tag in "
 			      "cache file: %s", FILENAME(id));
-	ret =3D KRB5_CC_FORMAT;
 	goto out;
     }
     FCACHE(id)->version =3D tag;
@@ -494,8 +596,9 @@
 	ret =3D krb5_ret_int16 (sp, &length);
 	if(ret) {
 	    ret =3D KRB5_CC_FORMAT;
-	    krb5_set_error_string(context, "Error reading tag length in "
-			      "cache file: %s", FILENAME(id));
+	    krb5_set_error_message(context, ret,
+				   N_("Error reading tag length in "
+				      "cache file: %s", ""), FILENAME(id));
 	    goto out;
 	}
 	while(length > 0) {
@@ -505,43 +608,49 @@
=20
 	    ret =3D krb5_ret_int16 (sp, &dtag);
 	    if(ret) {
-		krb5_set_error_string(context, "Error reading dtag in "
-				      "cache file: %s", FILENAME(id));
 		ret =3D KRB5_CC_FORMAT;
+		krb5_set_error_message(context, ret, N_("Error reading dtag in "
+							"cache file: %s", ""),
+				       FILENAME(id));
 		goto out;
 	    }
 	    ret =3D krb5_ret_int16 (sp, &data_len);
 	    if(ret) {
-		krb5_set_error_string(context, "Error reading dlength in "
-				      "cache file: %s", FILENAME(id));
 		ret =3D KRB5_CC_FORMAT;
+		krb5_set_error_message(context, ret,
+				       N_("Error reading dlength "
+					  "in cache file: %s",""),
+				       FILENAME(id));
 		goto out;
 	    }
 	    switch (dtag) {
-	    case FCC_TAG_DELTATIME :
-		ret =3D krb5_ret_int32 (sp, &context->kdc_sec_offset);
+	    case FCC_TAG_DELTATIME : {
+		int32_t offset;
+
+		ret =3D krb5_ret_int32 (sp, &offset);
+		ret |=3D krb5_ret_int32 (sp, &context->kdc_usec_offset);
 		if(ret) {
-		    krb5_set_error_string(context, "Error reading kdc_sec in "
-					  "cache file: %s", FILENAME(id));
 		    ret =3D KRB5_CC_FORMAT;
+		    krb5_set_error_message(context, ret,
+					   N_("Error reading kdc_sec in "
+					      "cache file: %s", ""),
+					   FILENAME(id));
 		    goto out;
 		}
-		ret =3D krb5_ret_int32 (sp, &context->kdc_usec_offset);
-		if(ret) {
-		    krb5_set_error_string(context, "Error reading kdc_usec in "
-					  "cache file: %s", FILENAME(id));
-		    ret =3D KRB5_CC_FORMAT;
-		    goto out;
-		}
+		context->kdc_sec_offset =3D offset;
+		if (kdc_offset)
+		    *kdc_offset =3D offset;
 		break;
+	    }
 	    default :
 		for (i =3D 0; i < data_len; ++i) {
 		    ret =3D krb5_ret_int8 (sp, &dummy);
 		    if(ret) {
-			krb5_set_error_string(context, "Error reading unknown "
-					      "tag in cache file: %s",=20
-					      FILENAME(id));
 			ret =3D KRB5_CC_FORMAT;
+			krb5_set_error_message(context, ret,
+					       N_("Error reading unknown "
+						  "tag in cache file: %s", ""),
+					       FILENAME(id));
 			goto out;
 		    }
 		}
@@ -557,14 +666,15 @@
 	break;
     default :
 	ret =3D KRB5_CCACHE_BADVNO;
-	krb5_set_error_string(context, "Unknown version number (%d) in "
-			      "credential cache file: %s",
-			      (int)tag, FILENAME(id));
+	krb5_set_error_message(context, ret,
+			       N_("Unknown version number (%d) in "
+				  "credential cache file: %s", ""),
+			       (int)tag, FILENAME(id));
 	goto out;
     }
     *ret_sp =3D sp;
     *ret_fd =3D fd;
-   =20
+
     return 0;
   out:
     if(sp !=3D NULL)
@@ -574,7 +684,7 @@
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_get_principal(krb5_context context,
 		  krb5_ccache id,
 		  krb5_principal *principal)
@@ -583,24 +693,24 @@
     int fd;
     krb5_storage *sp;
=20
-    ret =3D init_fcc (context, id, &sp, &fd);
+    ret =3D init_fcc (context, id, &sp, &fd, NULL);
     if (ret)
 	return ret;
     ret =3D krb5_ret_principal(sp, principal);
     if (ret)
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
     krb5_storage_free(sp);
     fcc_unlock(context, fd);
     close(fd);
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_end_get (krb5_context context,
 	     krb5_ccache id,
 	     krb5_cc_cursor *cursor);
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_get_first (krb5_context context,
 	       krb5_ccache id,
 	       krb5_cc_cursor *cursor)
@@ -608,15 +718,18 @@
     krb5_error_code ret;
     krb5_principal principal;
=20
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
     *cursor =3D malloc(sizeof(struct fcc_cursor));
     if (*cursor =3D=3D NULL) {
-        krb5_set_error_string (context, "malloc: out of memory");
+        krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory"=
, ""));
 	return ENOMEM;
     }
     memset(*cursor, 0, sizeof(struct fcc_cursor));
=20
-    ret =3D init_fcc (context, id, &FCC_CURSOR(*cursor)->sp,=20
-		    &FCC_CURSOR(*cursor)->fd);
+    ret =3D init_fcc (context, id, &FCC_CURSOR(*cursor)->sp,
+		    &FCC_CURSOR(*cursor)->fd, NULL);
     if (ret) {
 	free(*cursor);
 	*cursor =3D NULL;
@@ -624,7 +737,7 @@
     }
     ret =3D krb5_ret_principal (FCC_CURSOR(*cursor)->sp, &principal);
     if(ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	fcc_end_get(context, id, cursor);
 	return ret;
     }
@@ -633,29 +746,43 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_get_next (krb5_context context,
 	      krb5_ccache id,
 	      krb5_cc_cursor *cursor,
 	      krb5_creds *creds)
 {
     krb5_error_code ret;
+
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
+    if (FCC_CURSOR(*cursor) =3D=3D NULL)
+        return krb5_einval(context, 3);
+
     if((ret =3D fcc_lock(context, id, FCC_CURSOR(*cursor)->fd, FALSE)) !=
=3D 0)
 	return ret;
=20
     ret =3D krb5_ret_creds(FCC_CURSOR(*cursor)->sp, creds);
     if (ret)
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
=20
     fcc_unlock(context, FCC_CURSOR(*cursor)->fd);
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_end_get (krb5_context context,
 	     krb5_ccache id,
 	     krb5_cc_cursor *cursor)
 {
+
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
+    if (FCC_CURSOR(*cursor) =3D=3D NULL)
+        return krb5_einval(context, 3);
+
     krb5_storage_free(FCC_CURSOR(*cursor)->sp);
     close (FCC_CURSOR(*cursor)->fd);
     free(*cursor);
@@ -663,16 +790,21 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_remove_cred(krb5_context context,
 		 krb5_ccache id,
 		 krb5_flags which,
 		 krb5_creds *cred)
 {
     krb5_error_code ret;
-    krb5_ccache copy;
+    krb5_ccache copy, newfile;
+    char *newname =3D NULL;
+    int fd;
=20
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &copy);
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &copy);
     if (ret)
 	return ret;
=20
@@ -688,49 +820,86 @@
 	return ret;
     }
=20
-    fcc_destroy(context, id);
+    ret =3D asprintf(&newname, "FILE:%s.XXXXXX", FILENAME(id));
+    if (ret < 0 || newname =3D=3D NULL) {
+	krb5_cc_destroy(context, copy);
+	return ENOMEM;
+    }
=20
-    ret =3D krb5_cc_copy_cache(context, copy, id);
+    fd =3D mkstemp(&newname[5]);
+    if (fd < 0) {
+	ret =3D errno;
+	krb5_cc_destroy(context, copy);
+	return ret;
+    }
+    close(fd);
+
+    ret =3D krb5_cc_resolve(context, newname, &newfile);
+    if (ret) {
+	unlink(&newname[5]);
+	free(newname);
+	krb5_cc_destroy(context, copy);
+	return ret;
+    }
+
+    ret =3D krb5_cc_copy_cache(context, copy, newfile);
     krb5_cc_destroy(context, copy);
+    if (ret) {
+	free(newname);
+	krb5_cc_destroy(context, newfile);
+	return ret;
+    }
+
+    ret =3D rk_rename(&newname[5], FILENAME(id));
+    if (ret)
+	ret =3D errno;
+    free(newname);
+    krb5_cc_close(context, newfile);
=20
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_set_flags(krb5_context context,
 	      krb5_ccache id,
 	      krb5_flags flags)
 {
+    if (FCACHE(id) =3D=3D NULL)
+        return krb5_einval(context, 2);
+
     return 0; /* XXX */
 }
=20
-static krb5_error_code
+static int KRB5_CALLCONV
 fcc_get_version(krb5_context context,
 		krb5_ccache id)
 {
+    if (FCACHE(id) =3D=3D NULL)
+        return -1;
+
     return FCACHE(id)->version;
 }
-		   =20
+
 struct fcache_iter {
     int first;
 };
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
 {
     struct fcache_iter *iter;
=20
     iter =3D calloc(1, sizeof(*iter));
     if (iter =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
-    }   =20
+    }
     iter->first =3D 1;
     *cursor =3D iter;
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccach=
e *id)
 {
     struct fcache_iter *iter =3D cursor;
@@ -738,47 +907,68 @@
     const char *fn;
     char *expandedfn =3D NULL;
=20
+    if (iter =3D=3D NULL)
+        return krb5_einval(context, 2);
+
     if (!iter->first) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return KRB5_CC_END;
     }
     iter->first =3D 0;
=20
     fn =3D krb5_cc_default_name(context);
-    if (strncasecmp(fn, "FILE:", 5) !=3D 0) {
-	ret =3D _krb5_expand_default_cc_name(context,=20
+    if (fn =3D=3D NULL || strncasecmp(fn, "FILE:", 5) !=3D 0) {
+	ret =3D _krb5_expand_default_cc_name(context,
 					   KRB5_DEFAULT_CCNAME_FILE,
 					   &expandedfn);
 	if (ret)
 	    return ret;
+	fn =3D expandedfn;
+    }
+    /* check if file exists, don't return a non existant "next" */
+    if (strncasecmp(fn, "FILE:", 5) =3D=3D 0) {
+	struct stat sb;
+	ret =3D stat(fn + 5, &sb);
+	if (ret) {
+	    ret =3D KRB5_CC_END;
+	    goto out;
+	}
     }
     ret =3D krb5_cc_resolve(context, fn, id);
+ out:
     if (expandedfn)
 	free(expandedfn);
-   =20
+
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
 {
     struct fcache_iter *iter =3D cursor;
+
+    if (iter =3D=3D NULL)
+        return krb5_einval(context, 2);
+
     free(iter);
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fcc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
 {
     krb5_error_code ret =3D 0;
=20
-    ret =3D rename(FILENAME(from), FILENAME(to));
+    ret =3D rk_rename(FILENAME(from), FILENAME(to));
+
     if (ret && errno !=3D EXDEV) {
+	char buf[128];
 	ret =3D errno;
-	krb5_set_error_string(context,
-			      "Rename of file from %s to %s failed: %s",=20
-			      FILENAME(from), FILENAME(to),
-			      strerror(ret));
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret,
+			       N_("Rename of file from %s "
+				  "to %s failed: %s", ""),
+			       FILENAME(from), FILENAME(to), buf);
 	return ret;
     } else if (ret && errno =3D=3D EXDEV) {
 	/* make a copy and delete the orignal */
@@ -786,14 +976,14 @@
 	int fd1, fd2;
 	char buf[BUFSIZ];
=20
-	ret =3D fcc_open(context, from, &fd1, O_RDONLY | O_BINARY, 0);
+	ret =3D fcc_open(context, from, &fd1, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
 	if(ret)
 	    return ret;
=20
 	unlink(FILENAME(to));
=20
-	ret =3D fcc_open(context, to, &fd2,=20
-		       O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0600);
+	ret =3D fcc_open(context, to, &fd2,
+		       O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, 0600);
 	if(ret)
 	    goto out1;
=20
@@ -801,21 +991,19 @@
 	    sz2 =3D write(fd2, buf, sz1);
 	    if (sz1 !=3D sz2) {
 		ret =3D EIO;
-		krb5_set_error_string(context,
-				      "Failed to write data from one file "
-				      "credential cache to the other");
+		krb5_set_error_message(context, ret,
+				       N_("Failed to write data from one file "
+					  "credential cache to the other", ""));
 		goto out2;
 	    }
 	}
 	if (sz1 < 0) {
 	    ret =3D EIO;
-	    krb5_set_error_string(context,
-				  "Failed to read data from one file "
-				  "credential cache to the other");
+	    krb5_set_error_message(context, ret,
+				   N_("Failed to read data from one file "
+				      "credential cache to the other", ""));
 	    goto out2;
 	}
-	erase_file(FILENAME(from));
-	   =20
     out2:
 	fcc_unlock(context, fd2);
 	close(fd2);
@@ -824,8 +1012,10 @@
 	fcc_unlock(context, fd1);
 	close(fd1);
=20
+	_krb5_erase_file(context, FILENAME(from));
+
 	if (ret) {
-	    erase_file(FILENAME(to));
+	    _krb5_erase_file(context, FILENAME(to));
 	    return ret;
 	}
     }
@@ -834,29 +1024,78 @@
     {
 	krb5_storage *sp;
 	int fd;
-	ret =3D init_fcc (context, to, &sp, &fd);
-	krb5_storage_free(sp);
-	fcc_unlock(context, fd);
-	close(fd);
-    }   =20
+	if ((ret =3D init_fcc (context, to, &sp, &fd, NULL)) =3D=3D 0) {
+	    if (sp)
+		krb5_storage_free(sp);
+	    fcc_unlock(context, fd);
+	    close(fd);
+	}
+    }
+
+    fcc_close(context, from);
+
     return ret;
 }
=20
-static krb5_error_code
-fcc_default_name(krb5_context context, char **str)
+static krb5_error_code KRB5_CALLCONV
+fcc_get_default_name(krb5_context context, char **str)
 {
-    return _krb5_expand_default_cc_name(context,=20
+    return _krb5_expand_default_cc_name(context,
 					KRB5_DEFAULT_CCNAME_FILE,
 					str);
 }
=20
+static krb5_error_code KRB5_CALLCONV
+fcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+    krb5_error_code ret;
+    struct stat sb;
+    int fd;
+
+    ret =3D fcc_open(context, id, &fd, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
+    if(ret)
+	return ret;
+    ret =3D fstat(fd, &sb);
+    close(fd);
+    if (ret) {
+	ret =3D errno;
+	krb5_set_error_message(context, ret, N_("Failed to stat cache file", ""));
+	return ret;
+    }
+    *mtime =3D sb.st_mtime;
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_o=
ffset)
+{
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_=
offset)
+{
+    krb5_error_code ret;
+    krb5_storage *sp =3D NULL;
+    int fd;
+    ret =3D init_fcc(context, id, &sp, &fd, kdc_offset);
+    if (sp)
+	krb5_storage_free(sp);
+    fcc_unlock(context, fd);
+    close(fd);
+
+    return ret;
+}
+
+
 /**
  * Variable containing the FILE based credential cache implemention.
  *
  * @ingroup krb5_ccache
  */
=20
-const krb5_cc_ops krb5_fcc_ops =3D {
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_fcc_ops =3D {
+    KRB5_CC_OPS_VERSION,
     "FILE",
     fcc_get_name,
     fcc_resolve,
@@ -877,5 +1116,9 @@
     fcc_get_cache_next,
     fcc_end_cache_get,
     fcc_move,
-    fcc_default_name
+    fcc_get_default_name,
+    NULL,
+    fcc_lastchange,
+    fcc_set_kdc_offset,
+    fcc_get_kdc_offset
 };
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/free.c
--- a/head/crypto/heimdal/lib/krb5/free.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/free.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 1999, 2004 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999, 2004 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: free.c 15175 2005-05-18 10:06:16Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_kdc_rep(krb5_context context, krb5_kdc_rep *rep)
 {
     free_KDC_REP(&rep->kdc_rep);
@@ -45,7 +43,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_xfree (void *ptr)
 {
     free (ptr);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/free_host=
_realm.c
--- a/head/crypto/heimdal/lib/krb5/free_host_realm.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/free_host_realm.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,45 +1,50 @@
 /*
- * Copyright (c) 1997, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: free_host_realm.c 13863 2004-05-25 21:46:46Z lha $");
-
-/*
+/**
  * Free all memory allocated by `realmlist'
+ *
+ * @param context A Kerberos 5 context.
+ * @param realmlist realmlist to free, NULL is ok
+ *
+ * @return a Kerberos error code, always 0.
+ *
+ * @ingroup krb5_support
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_host_realm(krb5_context context,
 		     krb5_realm *realmlist)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/generate_=
seq_number.c
--- a/head/crypto/heimdal/lib/krb5/generate_seq_number.c	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/generate_seq_number.c	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,62 +1,48 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: generate_seq_number.c 17442 2006-05-05 09:31:15Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_generate_seq_number(krb5_context context,
 			 const krb5_keyblock *key,
 			 uint32_t *seqno)
 {
-    krb5_error_code ret;
-    krb5_keyblock *subkey;
-    uint32_t q;
-    u_char *p;
-    int i;
-
-    ret =3D krb5_generate_subkey (context, key, &subkey);
-    if (ret)
-	return ret;
-
-    q =3D 0;
-    for (p =3D (u_char *)subkey->keyvalue.data, i =3D 0;
-	 i < subkey->keyvalue.length;
-	 ++i, ++p)
-	q =3D (q << 8) | *p;
-    q &=3D 0xffffffff;
-    *seqno =3D q;
-    krb5_free_keyblock (context, subkey);
+    if (RAND_bytes((void *)seqno, sizeof(*seqno)) <=3D 0)
+	krb5_abortx(context, "Failed to generate random block");
+    /* MIT used signed numbers, lets not stomp into that space directly */
+    *seqno &=3D 0x3fffffff;
+    if (*seqno =3D=3D 0)
+	*seqno =3D 1;
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/generate_=
subkey.c
--- a/head/crypto/heimdal/lib/krb5/generate_subkey.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/generate_subkey.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,49 +1,52 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: generate_subkey.c 14455 2005-01-05 02:39:21Z lukeh $");
+/**
+ * Generate subkey, from keyblock
+ *
+ * @param context kerberos context
+ * @param key session key
+ * @param etype encryption type of subkey, if ETYPE_NULL, use key's enctype
+ * @param subkey returned new, free with krb5_free_keyblock().
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+* @ingroup krb5_crypto
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_generate_subkey(krb5_context context,
-		     const krb5_keyblock *key,
-		     krb5_keyblock **subkey)
-{
-    return krb5_generate_subkey_extended(context, key, key->keytype, subke=
y);
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_generate_subkey_extended(krb5_context context,
 			      const krb5_keyblock *key,
 			      krb5_enctype etype,
@@ -53,7 +56,7 @@
=20
     ALLOC(*subkey, 1);
     if (*subkey =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_addrs=
.c
--- a/head/crypto/heimdal/lib/krb5/get_addrs.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/get_addrs.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: get_addrs.c 13863 2004-05-25 21:46:46Z lha $");
-
 #ifdef __osf__
 /* hate */
 struct rtentry;
@@ -54,20 +52,20 @@
=20
     if (gethostname (hostname, sizeof(hostname))) {
 	ret =3D errno;
-	krb5_set_error_string (context, "gethostname: %s", strerror(ret));
+	krb5_set_error_message(context, ret, "gethostname: %s", strerror(ret));
 	return ret;
     }
     hostent =3D roken_gethostbyname (hostname);
     if (hostent =3D=3D NULL) {
 	ret =3D errno;
-	krb5_set_error_string (context, "gethostbyname %s: %s",
-			       hostname, strerror(ret));
+	krb5_set_error_message (context, ret, "gethostbyname %s: %s",
+				hostname, strerror(ret));
 	return ret;
     }
     res->len =3D 1;
     res->val =3D malloc (sizeof(*res->val));
     if (res->val =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     res->val[0].addr_type =3D hostent->h_addrtype;
@@ -84,8 +82,8 @@
 }
=20
 enum {
-    LOOP            =3D 1,	/* do include loopback interfaces */
-    LOOP_IF_NONE    =3D 2,	/* include loopback if no other if's */
+    LOOP            =3D 1,	/* do include loopback addrs */
+    LOOP_IF_NONE    =3D 2,	/* include loopback addrs if no others */
     EXTRA_ADDRESSES =3D 4,	/* include extra addresses */
     SCAN_INTERFACES =3D 8		/* scan interfaces for addresses */
 };
@@ -100,15 +98,13 @@
 {
     struct sockaddr sa_zero;
     struct ifaddrs *ifa0, *ifa;
-    krb5_error_code ret =3D ENXIO;=20
-    int num, idx;
+    krb5_error_code ret =3D ENXIO;
+    unsigned int num, idx;
     krb5_addresses ignore_addresses;
=20
-    res->val =3D NULL;
-
     if (getifaddrs(&ifa0) =3D=3D -1) {
 	ret =3D errno;
-	krb5_set_error_string(context, "getifaddrs: %s", strerror(ret));
+	krb5_set_error_message(context, ret, "getifaddrs: %s", strerror(ret));
 	return (ret);
     }
=20
@@ -120,7 +116,7 @@
=20
     if (num =3D=3D 0) {
 	freeifaddrs(ifa0);
-	krb5_set_error_string(context, "no addresses found");
+	krb5_set_error_message(context, ENXIO, N_("no addresses found", ""));
 	return (ENXIO);
     }
=20
@@ -136,8 +132,8 @@
     if (res->val =3D=3D NULL) {
 	krb5_free_addresses(context, &ignore_addresses);
 	freeifaddrs(ifa0);
-	krb5_set_error_string (context, "malloc: out of memory");
-	return (ENOMEM);
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+	return ENOMEM;
     }
=20
     /* Now traverse the list. */
@@ -150,11 +146,9 @@
 	    continue;
 	if (krb5_sockaddr_uninteresting(ifa->ifa_addr))
 	    continue;
-	if ((ifa->ifa_flags & IFF_LOOPBACK) !=3D 0) {
+	if (krb5_sockaddr_is_loopback(ifa->ifa_addr) && (flags & LOOP) =3D=3D 0)
 	    /* We'll deal with the LOOP_IF_NONE case later. */
-	    if ((flags & LOOP) =3D=3D 0)
-		continue;
-	}
+	    continue;
=20
 	ret =3D krb5_sockaddr2address(context, ifa->ifa_addr, &res->val[idx]);
 	if (ret) {
@@ -167,7 +161,7 @@
 	    continue;
 	}
 	/* possibly skip this address? */
-	if((flags & EXTRA_ADDRESSES) &&=20
+	if((flags & EXTRA_ADDRESSES) &&
 	   krb5_address_search(context, &res->val[idx], &ignore_addresses)) {
 	    krb5_free_address(context, &res->val[idx]);
 	    flags &=3D ~LOOP_IF_NONE; /* we actually found an address,
@@ -193,33 +187,32 @@
 		continue;
 	    if (krb5_sockaddr_uninteresting(ifa->ifa_addr))
 		continue;
-
-	    if ((ifa->ifa_flags & IFF_LOOPBACK) !=3D 0) {
-		ret =3D krb5_sockaddr2address(context,
-					    ifa->ifa_addr, &res->val[idx]);
-		if (ret) {
-		    /*
-		     * See comment above.
-		     */
-		    continue;
-		}
-		if((flags & EXTRA_ADDRESSES) &&=20
-		   krb5_address_search(context, &res->val[idx],=20
-				       &ignore_addresses)) {
-		    krb5_free_address(context, &res->val[idx]);
-		    continue;
-		}
-		idx++;
+	    if (!krb5_sockaddr_is_loopback(ifa->ifa_addr))
+		continue;
+	    if ((ifa->ifa_flags & IFF_LOOPBACK) =3D=3D 0)
+		/* Presumably loopback addrs are only used on loopback ifs! */
+		continue;
+	    ret =3D krb5_sockaddr2address(context,
+					ifa->ifa_addr, &res->val[idx]);
+	    if (ret)
+		continue; /* We don't consider this failure fatal */
+	    if((flags & EXTRA_ADDRESSES) &&
+	       krb5_address_search(context, &res->val[idx],
+				   &ignore_addresses)) {
+		krb5_free_address(context, &res->val[idx]);
+		continue;
 	    }
+	    idx++;
 	}
     }
=20
     if (flags & EXTRA_ADDRESSES)
 	krb5_free_addresses(context, &ignore_addresses);
     freeifaddrs(ifa0);
-    if (ret)
+    if (ret) {
 	free(res->val);
-    else
+	res->val =3D NULL;
+    } else
 	res->len =3D idx;        /* Now a count. */
     return (ret);
 }
@@ -229,13 +222,14 @@
 {
     krb5_error_code ret =3D -1;
=20
+    res->len =3D 0;
+    res->val =3D NULL;
+
     if (flags & SCAN_INTERFACES) {
 	ret =3D find_all_addresses (context, res, flags);
 	if(ret || res->len =3D=3D 0)
 	    ret =3D gethostname_fallback (context, res);
     } else {
-	res->len =3D 0;
-	res->val =3D NULL;
 	ret =3D 0;
     }
=20
@@ -268,7 +262,7 @@
  * Only include loopback address if there are no other.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_all_client_addrs (krb5_context context, krb5_addresses *res)
 {
     int flags =3D LOOP_IF_NONE | EXTRA_ADDRESSES;
@@ -284,7 +278,7 @@
  * If that fails, we return the address corresponding to `hostname'.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_all_server_addrs (krb5_context context, krb5_addresses *res)
 {
     return get_addrs_int (context, res, LOOP | SCAN_INTERFACES);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_cred.c
--- a/head/crypto/heimdal/lib/krb5/get_cred.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/get_cred.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,45 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
+#include <assert.h>
=20
-RCSID("$Id: get_cred.c 21668 2007-07-22 11:28:05Z lha $");
+static krb5_error_code
+get_cred_kdc_capath(krb5_context, krb5_kdc_flags,
+		    krb5_ccache, krb5_creds *, krb5_principal,
+		    Ticket *, krb5_creds **, krb5_creds ***);
=20
 /*
  * Take the `body' and encode it into `padata' using the credentials
@@ -41,16 +47,15 @@
  */
=20
 static krb5_error_code
-make_pa_tgs_req(krb5_context context,=20
+make_pa_tgs_req(krb5_context context,
 		krb5_auth_context ac,
 		KDC_REQ_BODY *body,
 		PA_DATA *padata,
-		krb5_creds *creds,
-		krb5_key_usage usage)
+		krb5_creds *creds)
 {
     u_char *buf;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     krb5_data in_data;
     krb5_error_code ret;
=20
@@ -65,8 +70,7 @@
     ret =3D _krb5_mk_req_internal(context, &ac, 0, &in_data, creds,
 				&padata->padata_value,
 				KRB5_KU_TGS_REQ_AUTH_CKSUM,
-				usage
-				/* KRB5_KU_TGS_REQ_AUTH */);
+				KRB5_KU_TGS_REQ_AUTH);
  out:
     free (buf);
     if(ret)
@@ -83,10 +87,10 @@
 set_auth_data (krb5_context context,
 	       KDC_REQ_BODY *req_body,
 	       krb5_authdata *authdata,
-	       krb5_keyblock *key)
+	       krb5_keyblock *subkey)
 {
     if(authdata->len) {
-	size_t len, buf_size;
+	size_t len =3D 0, buf_size;
 	unsigned char *buf;
 	krb5_crypto crypto;
 	krb5_error_code ret;
@@ -101,20 +105,20 @@
 	ALLOC(req_body->enc_authorization_data, 1);
 	if (req_body->enc_authorization_data =3D=3D NULL) {
 	    free (buf);
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
 	    return ENOMEM;
 	}
-	ret =3D krb5_crypto_init(context, key, 0, &crypto);
+	ret =3D krb5_crypto_init(context, subkey, 0, &crypto);
 	if (ret) {
 	    free (buf);
 	    free (req_body->enc_authorization_data);
 	    req_body->enc_authorization_data =3D NULL;
 	    return ret;
 	}
-	krb5_encrypt_EncryptedData(context,=20
+	krb5_encrypt_EncryptedData(context,
 				   crypto,
-				   KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY,=20
-				   /* KRB5_KU_TGS_REQ_AUTH_DAT_SESSION? */
+				   KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY,
 				   buf,
 				   len,
 				   0,
@@ -125,7 +129,7 @@
 	req_body->enc_authorization_data =3D NULL;
     }
     return 0;
-}   =20
+}
=20
 /*
  * Create a tgs-req in `t' with `addresses', `flags', `second_ticket'
@@ -144,9 +148,9 @@
 	      unsigned nonce,
 	      const METHOD_DATA *padata,
 	      krb5_keyblock **subkey,
-	      TGS_REQ *t,
-	      krb5_key_usage usage)
+	      TGS_REQ *t)
 {
+    krb5_auth_context ac =3D NULL;
     krb5_error_code ret =3D 0;
=20
     memset(t, 0, sizeof(*t));
@@ -156,15 +160,17 @@
 	ALLOC_SEQ(&t->req_body.etype, 1);
 	if(t->req_body.etype.val =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	t->req_body.etype.val[0] =3D in_creds->session.keytype;
     } else {
-	ret =3D krb5_init_etype(context,=20
-			      &t->req_body.etype.len,=20
-			      &t->req_body.etype.val,=20
-			      NULL);
+	ret =3D _krb5_init_etype(context,
+			       KRB5_PDU_TGS_REQUEST,
+			       &t->req_body.etype.len,
+			       &t->req_body.etype.val,
+			       NULL);
     }
     if (ret)
 	goto fail;
@@ -176,7 +182,7 @@
     ALLOC(t->req_body.sname, 1);
     if (t->req_body.sname =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
=20
@@ -192,107 +198,83 @@
     ALLOC(t->req_body.till, 1);
     if(t->req_body.till =3D=3D NULL){
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
     *t->req_body.till =3D in_creds->times.endtime;
-   =20
+
     t->req_body.nonce =3D nonce;
     if(second_ticket){
 	ALLOC(t->req_body.additional_tickets, 1);
 	if (t->req_body.additional_tickets =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	ALLOC_SEQ(t->req_body.additional_tickets, 1);
 	if (t->req_body.additional_tickets->val =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto fail;
 	}
-	ret =3D copy_Ticket(second_ticket, t->req_body.additional_tickets->val);=20
+	ret =3D copy_Ticket(second_ticket, t->req_body.additional_tickets->val);
 	if (ret)
 	    goto fail;
     }
     ALLOC(t->padata, 1);
     if (t->padata =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
     ALLOC_SEQ(t->padata, 1 + padata->len);
     if (t->padata->val =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
     {
-	int i;
+	size_t i;
 	for (i =3D 0; i < padata->len; i++) {
 	    ret =3D copy_PA_DATA(&padata->val[i], &t->padata->val[i + 1]);
 	    if (ret) {
-		krb5_set_error_string(context, "malloc: out of memory");
+		krb5_set_error_message(context, ret,
+				       N_("malloc: out of memory", ""));
 		goto fail;
 	    }
 	}
     }
=20
-    {
-	krb5_auth_context ac;
-	krb5_keyblock *key =3D NULL;
+    ret =3D krb5_auth_con_init(context, &ac);
+    if(ret)
+	goto fail;
=20
-	ret =3D krb5_auth_con_init(context, &ac);
-	if(ret)
-	    goto fail;
+    ret =3D krb5_auth_con_generatelocalsubkey(context, ac, &krbtgt->sessio=
n);
+    if (ret)
+	goto fail;
=20
-	if (krb5_config_get_bool_default(context, NULL, FALSE,
-					 "realms",
-					 krbtgt->server->realm,
-					 "tgs_require_subkey",
-					 NULL))
-	{
-	    ret =3D krb5_generate_subkey (context, &krbtgt->session, &key);
-	    if (ret) {
-		krb5_auth_con_free (context, ac);
-		goto fail;
-	    }
+    ret =3D set_auth_data (context, &t->req_body, &in_creds->authdata,
+			 ac->local_subkey);
+    if (ret)
+	goto fail;
=20
-	    ret =3D krb5_auth_con_setlocalsubkey(context, ac, key);
-	    if (ret) {
-		if (key)
-		    krb5_free_keyblock (context, key);
-		krb5_auth_con_free (context, ac);
-		goto fail;
-	    }
-	}
+    ret =3D make_pa_tgs_req(context,
+			  ac,
+			  &t->req_body,
+			  &t->padata->val[0],
+			  krbtgt);
+    if(ret)
+	goto fail;
=20
-	ret =3D set_auth_data (context, &t->req_body, &in_creds->authdata,
-			     key ? key : &krbtgt->session);
-	if (ret) {
-	    if (key)
-		krb5_free_keyblock (context, key);
-	    krb5_auth_con_free (context, ac);
-	    goto fail;
-	}
+    ret =3D krb5_auth_con_getlocalsubkey(context, ac, subkey);
+    if (ret)
+	goto fail;
=20
-	ret =3D make_pa_tgs_req(context,
-			      ac,
-			      &t->req_body,=20
-			      &t->padata->val[0],
-			      krbtgt,
-			      usage);
-	if(ret) {
-	    if (key)
-		krb5_free_keyblock (context, key);
-	    krb5_auth_con_free(context, ac);
-	    goto fail;
-	}
-	*subkey =3D key;
-=09
+fail:
+    if (ac)
 	krb5_auth_con_free(context, ac);
-    }
-fail:
     if (ret) {
 	t->req_body.addresses =3D NULL;
 	free_TGS_REQ (t);
@@ -315,7 +297,7 @@
     if (ret)
 	return ret;
=20
-    ret =3D krb5_make_principal(context,=20
+    ret =3D krb5_make_principal(context,
 			      &tmp_cred.server,
 			      realm,
 			      KRB5_TGS_NAME,
@@ -338,29 +320,27 @@
 }
=20
 /* DCE compatible decrypt proc */
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 decrypt_tkt_with_subkey (krb5_context context,
 			 krb5_keyblock *key,
 			 krb5_key_usage usage,
-			 krb5_const_pointer subkey,
+			 krb5_const_pointer skey,
 			 krb5_kdc_rep *dec_rep)
 {
-    krb5_error_code ret;
+    const krb5_keyblock *subkey =3D skey;
+    krb5_error_code ret =3D 0;
     krb5_data data;
     size_t size;
     krb5_crypto crypto;
-   =20
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret)
-	return ret;
-    ret =3D krb5_decrypt_EncryptedData (context,
-				      crypto,
-				      usage,
-				      &dec_rep->kdc_rep.enc_part,
-				      &data);
-    krb5_crypto_destroy(context, crypto);
-    if(ret && subkey){
-	/* DCE compat -- try to decrypt with subkey */
+
+    assert(usage =3D=3D 0);
+
+    krb5_data_zero(&data);
+
+    /*
+     * start out with trying with subkey if we have one
+     */
+    if (subkey) {
 	ret =3D krb5_crypto_init(context, subkey, 0, &crypto);
 	if (ret)
 	    return ret;
@@ -369,37 +349,59 @@
 					  KRB5_KU_TGS_REP_ENC_PART_SUB_KEY,
 					  &dec_rep->kdc_rep.enc_part,
 					  &data);
+	/*
+	 * If the is Windows 2000 DC, we need to retry with key usage
+	 * 8 when doing ARCFOUR.
+	 */
+	if (ret && subkey->keytype =3D=3D ETYPE_ARCFOUR_HMAC_MD5) {
+	    ret =3D krb5_decrypt_EncryptedData(context,
+					     crypto,
+					     8,
+					     &dec_rep->kdc_rep.enc_part,
+					     &data);
+	}
+	krb5_crypto_destroy(context, crypto);
+    }
+    if (subkey =3D=3D NULL || ret) {
+	ret =3D krb5_crypto_init(context, key, 0, &crypto);
+	if (ret)
+	    return ret;
+	ret =3D krb5_decrypt_EncryptedData (context,
+					  crypto,
+					  KRB5_KU_TGS_REP_ENC_PART_SESSION,
+					  &dec_rep->kdc_rep.enc_part,
+					  &data);
 	krb5_crypto_destroy(context, crypto);
     }
     if (ret)
 	return ret;
-   =20
-    ret =3D krb5_decode_EncASRepPart(context,
-				   data.data,
+
+    ret =3D decode_EncASRepPart(data.data,
+			      data.length,
+			      &dec_rep->enc_part,
+			      &size);
+    if (ret)
+	ret =3D decode_EncTGSRepPart(data.data,
 				   data.length,
-				   &dec_rep->enc_part,=20
+				   &dec_rep->enc_part,
 				   &size);
     if (ret)
-	ret =3D krb5_decode_EncTGSRepPart(context,
-					data.data,
-					data.length,
-					&dec_rep->enc_part,=20
-					&size);
+      krb5_set_error_message(context, ret,
+			     N_("Failed to decode encpart in ticket", ""));
     krb5_data_free (&data);
     return ret;
 }
=20
 static krb5_error_code
-get_cred_kdc_usage(krb5_context context,=20
-		   krb5_ccache id,=20
-		   krb5_kdc_flags flags,
-		   krb5_addresses *addresses,=20
-		   krb5_creds *in_creds,
-		   krb5_creds *krbtgt,
-		   krb5_principal impersonate_principal,
-		   Ticket *second_ticket,
-		   krb5_creds *out_creds,
-		   krb5_key_usage usage)
+get_cred_kdc(krb5_context context,
+	     krb5_ccache id,
+	     krb5_kdc_flags flags,
+	     krb5_addresses *addresses,
+	     krb5_creds *in_creds,
+	     krb5_creds *krbtgt,
+	     krb5_principal impersonate_principal,
+	     Ticket *second_ticket,
+	     krb5_creds *out_creds)
 {
     TGS_REQ req;
     krb5_data enc;
@@ -409,10 +411,10 @@
     krb5_error_code ret;
     unsigned nonce;
     krb5_keyblock *subkey =3D NULL;
-    size_t len;
+    size_t len =3D 0;
     Ticket second_ticket_data;
     METHOD_DATA padata;
-   =20
+
     krb5_data_zero(&resp);
     krb5_data_zero(&enc);
     padata.val =3D NULL;
@@ -420,10 +422,10 @@
=20
     krb5_generate_random_block(&nonce, sizeof(nonce));
     nonce &=3D 0xffffffff;
-   =20
+
     if(flags.b.enc_tkt_in_skey && second_ticket =3D=3D NULL){
-	ret =3D decode_Ticket(in_creds->second_ticket.data,=20
-			    in_creds->second_ticket.length,=20
+	ret =3D decode_Ticket(in_creds->second_ticket.data,
+			    in_creds->second_ticket.length,
 			    &second_ticket_data, &len);
 	if(ret)
 	    return ret;
@@ -436,12 +438,12 @@
 	PA_S4U2Self self;
 	krb5_data data;
 	void *buf;
-	size_t size;
+	size_t size =3D 0;
=20
 	self.name =3D impersonate_principal->name;
 	self.realm =3D impersonate_principal->realm;
 	self.auth =3D estrdup("Kerberos");
-=09
+
 	ret =3D _krb5_s4u2self_to_checksumdata(context, &self, &data);
 	if (ret) {
 	    free(self.auth);
@@ -460,7 +462,7 @@
 				   KRB5_KU_OTHER_CKSUM,
 				   0,
 				   data.data,
-				   data.length,=20
+				   data.length,
 				   &self.cksum);
 	krb5_crypto_destroy(context, crypto);
 	krb5_data_free(&data);
@@ -476,8 +478,8 @@
 	    goto out;
 	if (len !=3D size)
 	    krb5_abortx(context, "internal asn1 error");
-=09
-	ret =3D krb5_padata_add(context, &padata, KRB5_PADATA_S4U2SELF, buf, len);
+
+	ret =3D krb5_padata_add(context, &padata, KRB5_PADATA_FOR_USER, buf, len);
 	if (ret)
 	    goto out;
     }
@@ -491,14 +493,13 @@
 			krbtgt,
 			nonce,
 			&padata,
-			&subkey,=20
-			&req,
-			usage);
+			&subkey,
+			&req);
     if (ret)
 	goto out;
=20
     ASN1_MALLOC_ENCODE(TGS_REQ, enc.data, enc.length, &req, &len, ret);
-    if (ret)=20
+    if (ret)
 	goto out;
     if(enc.length !=3D len)
 	krb5_abortx(context, "internal error in ASN.1 encoder");
@@ -526,42 +527,48 @@
 	goto out;
=20
     memset(&rep, 0, sizeof(rep));
-    if(decode_TGS_REP(resp.data, resp.length, &rep.kdc_rep, &len) =3D=3D 0=
){
-	ret =3D krb5_copy_principal(context,=20
-				  in_creds->client,=20
+    if(decode_TGS_REP(resp.data, resp.length, &rep.kdc_rep, &len) =3D=3D 0=
) {
+	unsigned eflags =3D 0;
+
+	ret =3D krb5_copy_principal(context,
+				  in_creds->client,
 				  &out_creds->client);
 	if(ret)
-	    goto out;
-	ret =3D krb5_copy_principal(context,=20
-				  in_creds->server,=20
+	    goto out2;
+	ret =3D krb5_copy_principal(context,
+				  in_creds->server,
 				  &out_creds->server);
 	if(ret)
-	    goto out;
+	    goto out2;
 	/* this should go someplace else */
 	out_creds->times.endtime =3D in_creds->times.endtime;
=20
+	/* XXX should do better testing */
+	if (flags.b.constrained_delegation || impersonate_principal)
+	    eflags |=3D EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
+
 	ret =3D _krb5_extract_ticket(context,
 				   &rep,
 				   out_creds,
 				   &krbtgt->session,
 				   NULL,
-				   KRB5_KU_TGS_REP_ENC_PART_SESSION,
+				   0,
 				   &krbtgt->addresses,
 				   nonce,
-				   EXTRACT_TICKET_ALLOW_CNAME_MISMATCH|
-				   EXTRACT_TICKET_ALLOW_SERVER_MISMATCH,
+				   eflags,
 				   decrypt_tkt_with_subkey,
 				   subkey);
+    out2:
 	krb5_free_kdc_rep(context, &rep);
     } else if(krb5_rd_error(context, &resp, &error) =3D=3D 0) {
 	ret =3D krb5_error_from_rd_error(context, &error, in_creds);
 	krb5_free_error_contents(context, &error);
-    } else if(resp.data && ((char*)resp.data)[0] =3D=3D 4) {
+    } else if(resp.length > 0 && ((char*)resp.data)[0] =3D=3D 4) {
 	ret =3D KRB5KRB_AP_ERR_V4_REPLY;
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
     } else {
 	ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
     }
=20
 out:
@@ -570,62 +577,58 @@
     free_METHOD_DATA(&padata);
     krb5_data_free(&resp);
     krb5_data_free(&enc);
-    if(subkey){
-	krb5_free_keyblock_contents(context, subkey);
-	free(subkey);
-    }
+    if(subkey)
+	krb5_free_keyblock(context, subkey);
     return ret;
-   =20
+
 }
=20
+/*
+ * same as above, just get local addresses first if the krbtgt have
+ * them and the realm is not addressless
+ */
+
 static krb5_error_code
-get_cred_kdc(krb5_context context,=20
-	     krb5_ccache id,=20
-	     krb5_kdc_flags flags,
-	     krb5_addresses *addresses,=20
-	     krb5_creds *in_creds,=20
-	     krb5_creds *krbtgt,
-	     krb5_principal impersonate_principal,
-	     Ticket *second_ticket,
-	     krb5_creds *out_creds)
+get_cred_kdc_address(krb5_context context,
+		     krb5_ccache id,
+		     krb5_kdc_flags flags,
+		     krb5_addresses *addrs,
+		     krb5_creds *in_creds,
+		     krb5_creds *krbtgt,
+		     krb5_principal impersonate_principal,
+		     Ticket *second_ticket,
+		     krb5_creds *out_creds)
 {
     krb5_error_code ret;
+    krb5_addresses addresses =3D { 0, NULL };
=20
-    ret =3D get_cred_kdc_usage(context, id, flags, addresses, in_creds,
-			     krbtgt, impersonate_principal, second_ticket,
-			     out_creds, KRB5_KU_TGS_REQ_AUTH);
-    if (ret =3D=3D KRB5KRB_AP_ERR_BAD_INTEGRITY) {
-	krb5_clear_error_string (context);
-	ret =3D get_cred_kdc_usage(context, id, flags, addresses, in_creds,
-				 krbtgt, impersonate_principal, second_ticket,
-				 out_creds, KRB5_KU_AP_REQ_AUTH);
+    /*
+     * Inherit the address-ness of the krbtgt if the address is not
+     * specified.
+     */
+
+    if (addrs =3D=3D NULL && krbtgt->addresses.len !=3D 0) {
+	krb5_boolean noaddr;
+
+	krb5_appdefault_boolean(context, NULL, krbtgt->server->realm,
+				"no-addresses", FALSE, &noaddr);
+
+	if (!noaddr) {
+	    krb5_get_all_client_addrs(context, &addresses);
+	    /* XXX this sucks. */
+	    addrs =3D &addresses;
+	    if(addresses.len =3D=3D 0)
+		addrs =3D NULL;
+	}
     }
-    return ret;
-}
-
-/* same as above, just get local addresses first */
-
-static krb5_error_code
-get_cred_kdc_la(krb5_context context, krb5_ccache id, krb5_kdc_flags flags=
,=20
-		krb5_creds *in_creds, krb5_creds *krbtgt,=20
-		krb5_principal impersonate_principal, Ticket *second_ticket,
-		krb5_creds *out_creds)
-{
-    krb5_error_code ret;
-    krb5_addresses addresses, *addrs =3D &addresses;
-   =20
-    krb5_get_all_client_addrs(context, &addresses);
-    /* XXX this sucks. */
-    if(addresses.len =3D=3D 0)
-	addrs =3D NULL;
-    ret =3D get_cred_kdc(context, id, flags, addrs,=20
-		       in_creds, krbtgt, impersonate_principal, second_ticket,
-		       out_creds);
+    ret =3D get_cred_kdc(context, id, flags, addrs, in_creds,
+		       krbtgt, impersonate_principal,
+		       second_ticket, out_creds);
     krb5_free_addresses(context, &addresses);
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_kdc_cred(krb5_context context,
 		  krb5_ccache id,
 		  krb5_kdc_flags flags,
@@ -640,7 +643,8 @@
=20
     *out_creds =3D calloc(1, sizeof(**out_creds));
     if(*out_creds =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ret =3D _krb5_get_krbtgt (context,
@@ -649,29 +653,34 @@
 			    &krbtgt);
     if(ret) {
 	free(*out_creds);
+	*out_creds =3D NULL;
 	return ret;
     }
-    ret =3D get_cred_kdc(context, id, flags, addresses,=20
+    ret =3D get_cred_kdc(context, id, flags, addresses,
 		       in_creds, krbtgt, NULL, NULL, *out_creds);
     krb5_free_creds (context, krbtgt);
-    if(ret)
+    if(ret) {
 	free(*out_creds);
+	*out_creds =3D NULL;
+    }
     return ret;
 }
=20
-static void
-not_found(krb5_context context, krb5_const_principal p)
+static int
+not_found(krb5_context context, krb5_const_principal p, krb5_error_code co=
de)
 {
     krb5_error_code ret;
     char *str;
=20
     ret =3D krb5_unparse_name(context, p, &str);
     if(ret) {
-	krb5_clear_error_string(context);
-	return;
+	krb5_clear_error_message(context);
+	return code;
     }
-    krb5_set_error_string(context, "Matching credential (%s) not found", s=
tr);
+    krb5_set_error_message(context, code,
+			   N_("Matching credential (%s) not found", ""), str);
     free(str);
+    return code;
 }
=20
 static krb5_error_code
@@ -686,24 +695,23 @@
=20
     krb5_cc_clear_mcred(&mcreds);
     mcreds.server =3D server;
-    ret =3D krb5_cc_retrieve_cred(context, id, KRB5_TC_DONT_MATCH_REALM,=20
+    ret =3D krb5_cc_retrieve_cred(context, id, KRB5_TC_DONT_MATCH_REALM,
 				&mcreds, out_creds);
     if(ret =3D=3D 0)
 	return 0;
     while(tgts && *tgts){
-	if(krb5_compare_creds(context, KRB5_TC_DONT_MATCH_REALM,=20
+	if(krb5_compare_creds(context, KRB5_TC_DONT_MATCH_REALM,
 			      &mcreds, *tgts)){
 	    ret =3D krb5_copy_creds_contents(context, *tgts, out_creds);
 	    return ret;
 	}
 	tgts++;
     }
-    not_found(context, server);
-    return KRB5_CC_NOTFOUND;
+    return not_found(context, server, KRB5_CC_NOTFOUND);
 }
=20
 static krb5_error_code
-add_cred(krb5_context context, krb5_creds ***tgts, krb5_creds *tkt)
+add_cred(krb5_context context, krb5_creds const *tkt, krb5_creds ***tgts)
 {
     int i;
     krb5_error_code ret;
@@ -712,7 +720,8 @@
     for(i =3D 0; tmp && tmp[i]; i++); /* XXX */
     tmp =3D realloc(tmp, (i+2)*sizeof(*tmp));
     if(tmp =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *tgts =3D tmp;
@@ -721,6 +730,141 @@
     return ret;
 }
=20
+static krb5_error_code
+get_cred_kdc_capath_worker(krb5_context context,
+                           krb5_kdc_flags flags,
+                           krb5_ccache ccache,
+                           krb5_creds *in_creds,
+                           krb5_const_realm try_realm,
+                           krb5_principal impersonate_principal,
+                           Ticket *second_ticket,
+                           krb5_creds **out_creds,
+                           krb5_creds ***ret_tgts)
+{
+    krb5_error_code ret;
+    krb5_creds *tgt, tmp_creds;
+    krb5_const_realm client_realm, server_realm;
+    int ok_as_delegate =3D 1;
+
+    *out_creds =3D NULL;
+
+    client_realm =3D krb5_principal_get_realm(context, in_creds->client);
+    server_realm =3D krb5_principal_get_realm(context, in_creds->server);
+    memset(&tmp_creds, 0, sizeof(tmp_creds));
+    ret =3D krb5_copy_principal(context, in_creds->client, &tmp_creds.clie=
nt);
+    if(ret)
+	return ret;
+
+    ret =3D krb5_make_principal(context,
+			      &tmp_creds.server,
+			      try_realm,
+			      KRB5_TGS_NAME,
+			      server_realm,
+			      NULL);
+    if(ret){
+	krb5_free_principal(context, tmp_creds.client);
+	return ret;
+    }
+    {
+	krb5_creds tgts;
+
+	ret =3D find_cred(context, ccache, tmp_creds.server,
+			*ret_tgts, &tgts);
+	if(ret =3D=3D 0){
+	    /* only allow implicit ok_as_delegate if the realm is the clients rea=
lm */
+	    if (strcmp(try_realm, client_realm) !=3D 0 || strcmp(try_realm, serve=
r_realm) !=3D 0)
+		ok_as_delegate =3D tgts.flags.b.ok_as_delegate;
+
+	    *out_creds =3D calloc(1, sizeof(**out_creds));
+	    if(*out_creds =3D=3D NULL) {
+		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret,
+				       N_("malloc: out of memory", ""));
+	    } else {
+		ret =3D get_cred_kdc_address(context, ccache, flags, NULL,
+					   in_creds, &tgts,
+					   impersonate_principal,
+					   second_ticket,
+					   *out_creds);
+		if (ret) {
+		    free (*out_creds);
+		    *out_creds =3D NULL;
+		} else if (ok_as_delegate =3D=3D 0)
+		    (*out_creds)->flags.b.ok_as_delegate =3D 0;
+	    }
+	    krb5_free_cred_contents(context, &tgts);
+	    krb5_free_principal(context, tmp_creds.server);
+	    krb5_free_principal(context, tmp_creds.client);
+	    return ret;
+	}
+    }
+    if(krb5_realm_compare(context, in_creds->client, in_creds->server))
+	return not_found(context, in_creds->server, KRB5_CC_NOTFOUND);
+
+    /* XXX this can loop forever */
+    while(1){
+	heim_general_string tgt_inst;
+
+	ret =3D get_cred_kdc_capath(context, flags, ccache, &tmp_creds,
+				  NULL, NULL, &tgt, ret_tgts);
+	if(ret) {
+	    krb5_free_principal(context, tmp_creds.server);
+	    krb5_free_principal(context, tmp_creds.client);
+	    return ret;
+	}
+	/*
+	 * if either of the chain or the ok_as_delegate was stripped
+	 * by the kdc, make sure we strip it too.
+	 */
+	if (ok_as_delegate =3D=3D 0 || tgt->flags.b.ok_as_delegate =3D=3D 0) {
+	    ok_as_delegate =3D 0;
+	    tgt->flags.b.ok_as_delegate =3D 0;
+	}
+
+	ret =3D add_cred(context, tgt, ret_tgts);
+	if(ret) {
+	    krb5_free_principal(context, tmp_creds.server);
+	    krb5_free_principal(context, tmp_creds.client);
+	    return ret;
+	}
+	tgt_inst =3D tgt->server->name.name_string.val[1];
+	if(strcmp(tgt_inst, server_realm) =3D=3D 0)
+	    break;
+	krb5_free_principal(context, tmp_creds.server);
+	ret =3D krb5_make_principal(context, &tmp_creds.server,
+				  tgt_inst, KRB5_TGS_NAME, server_realm, NULL);
+	if(ret) {
+	    krb5_free_principal(context, tmp_creds.server);
+	    krb5_free_principal(context, tmp_creds.client);
+	    return ret;
+	}
+	ret =3D krb5_free_creds(context, tgt);
+	if(ret) {
+	    krb5_free_principal(context, tmp_creds.server);
+	    krb5_free_principal(context, tmp_creds.client);
+	    return ret;
+	}
+    }
+
+    krb5_free_principal(context, tmp_creds.server);
+    krb5_free_principal(context, tmp_creds.client);
+    *out_creds =3D calloc(1, sizeof(**out_creds));
+    if(*out_creds =3D=3D NULL) {
+	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+    } else {
+	ret =3D get_cred_kdc_address (context, ccache, flags, NULL,
+				    in_creds, tgt, impersonate_principal,
+				    second_ticket, *out_creds);
+	if (ret) {
+	    free (*out_creds);
+	    *out_creds =3D NULL;
+	}
+    }
+    krb5_free_creds(context, tgt);
+    return ret;
+}
+
 /*
 get_cred(server)
 	creds =3D cc_get_cred(server)
@@ -737,187 +881,243 @@
 	*/
=20
 static krb5_error_code
-get_cred_from_kdc_flags(krb5_context context,
-			krb5_kdc_flags flags,
-			krb5_ccache ccache,
-			krb5_creds *in_creds,
-			krb5_principal impersonate_principal,
-			Ticket *second_ticket,		=09
-			krb5_creds **out_creds,
-			krb5_creds ***ret_tgts)
+get_cred_kdc_capath(krb5_context context,
+		    krb5_kdc_flags flags,
+		    krb5_ccache ccache,
+		    krb5_creds *in_creds,
+		    krb5_principal impersonate_principal,
+		    Ticket *second_ticket,
+		    krb5_creds **out_creds,
+		    krb5_creds ***ret_tgts)
 {
     krb5_error_code ret;
-    krb5_creds *tgt, tmp_creds;
     krb5_const_realm client_realm, server_realm, try_realm;
=20
+    client_realm =3D krb5_principal_get_realm(context, in_creds->client);
+    server_realm =3D krb5_principal_get_realm(context, in_creds->server);
+
+    try_realm =3D client_realm;
+    ret =3D get_cred_kdc_capath_worker(context, flags, ccache, in_creds, t=
ry_realm,
+                                     impersonate_principal, second_ticket,=
 out_creds,
+                                     ret_tgts);
+
+    if (ret =3D=3D KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) {
+        try_realm =3D krb5_config_get_string(context, NULL, "capaths",
+                                           client_realm, server_realm, NUL=
L);
+
+        if (try_realm !=3D NULL && strcmp(try_realm, client_realm)) {
+            ret =3D get_cred_kdc_capath_worker(context, flags, ccache, in_=
creds,
+                                             try_realm, impersonate_princi=
pal,
+                                             second_ticket, out_creds, ret=
_tgts);
+        }
+    }
+
+    return ret;
+}
+
+static krb5_error_code
+get_cred_kdc_referral(krb5_context context,
+		      krb5_kdc_flags flags,
+		      krb5_ccache ccache,
+		      krb5_creds *in_creds,
+		      krb5_principal impersonate_principal,
+		      Ticket *second_ticket,
+		      krb5_creds **out_creds,
+		      krb5_creds ***ret_tgts)
+{
+    krb5_const_realm client_realm;
+    krb5_error_code ret;
+    krb5_creds tgt, referral, ticket;
+    int loop =3D 0;
+    int ok_as_delegate =3D 1;
+
+    if (in_creds->server->name.name_string.len < 2 && !flags.b.canonicaliz=
e) {
+	krb5_set_error_message(context, KRB5KDC_ERR_PATH_NOT_ACCEPTED,
+			       N_("Name too short to do referals, skipping", ""));
+	return KRB5KDC_ERR_PATH_NOT_ACCEPTED;
+    }
+
+    memset(&tgt, 0, sizeof(tgt));
+    memset(&ticket, 0, sizeof(ticket));
+
+    flags.b.canonicalize =3D 1;
+
     *out_creds =3D NULL;
=20
     client_realm =3D krb5_principal_get_realm(context, in_creds->client);
-    server_realm =3D krb5_principal_get_realm(context, in_creds->server);
-    memset(&tmp_creds, 0, sizeof(tmp_creds));
-    ret =3D krb5_copy_principal(context, in_creds->client, &tmp_creds.clie=
nt);
-    if(ret)
-	return ret;
=20
-    try_realm =3D krb5_config_get_string(context, NULL, "capaths",=20
-				       client_realm, server_realm, NULL);
-   =20
-#if 1
-    /* XXX remove in future release */
-    if(try_realm =3D=3D NULL)
-	try_realm =3D krb5_config_get_string(context, NULL, "libdefaults",=20
-					   "capath", server_realm, NULL);
-#endif
+    /* find tgt for the clients base realm */
+    {
+	krb5_principal tgtname;
=20
-    if (try_realm =3D=3D NULL)
-	try_realm =3D client_realm;
+	ret =3D krb5_make_principal(context, &tgtname,
+				  client_realm,
+				  KRB5_TGS_NAME,
+				  client_realm,
+				  NULL);
+	if(ret)
+	    return ret;
=20
-    ret =3D krb5_make_principal(context,
-			      &tmp_creds.server,
-			      try_realm,
-			      KRB5_TGS_NAME,
-			      server_realm,=20
-			      NULL);
-    if(ret){
-	krb5_free_principal(context, tmp_creds.client);
+	ret =3D find_cred(context, ccache, tgtname, *ret_tgts, &tgt);
+	krb5_free_principal(context, tgtname);
+	if (ret)
+	    return ret;
+    }
+
+    referral =3D *in_creds;
+    ret =3D krb5_copy_principal(context, in_creds->server, &referral.serve=
r);
+    if (ret) {
+	krb5_free_cred_contents(context, &tgt);
 	return ret;
     }
-    {
-	krb5_creds tgts;
-	/* XXX try krb5_cc_retrieve_cred first? */
-	ret =3D find_cred(context, ccache, tmp_creds.server,=20
-			*ret_tgts, &tgts);
-	if(ret =3D=3D 0){
-	    *out_creds =3D calloc(1, sizeof(**out_creds));
-	    if(*out_creds =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
-		ret =3D ENOMEM;
-	    } else {
-		krb5_boolean noaddr;
+    ret =3D krb5_principal_set_realm(context, referral.server, client_real=
m);
+    if (ret) {
+	krb5_free_cred_contents(context, &tgt);
+	krb5_free_principal(context, referral.server);
+	return ret;
+    }
=20
-		krb5_appdefault_boolean(context, NULL, tgts.server->realm,
-					"no-addresses", FALSE, &noaddr);
+    while (loop++ < 17) {
+	krb5_creds **tickets;
+	krb5_creds mcreds;
+	char *referral_realm;
=20
-		if (noaddr)
-		    ret =3D get_cred_kdc(context, ccache, flags, NULL,
-				       in_creds, &tgts,
-				       impersonate_principal,=20
-				       second_ticket,
-				       *out_creds);
-		else
-		    ret =3D get_cred_kdc_la(context, ccache, flags,=20
-					  in_creds, &tgts,=20
-					  impersonate_principal,=20
-					  second_ticket,
-					  *out_creds);
-		if (ret) {
-		    free (*out_creds);
-		    *out_creds =3D NULL;
-		}
+	/* Use cache if we are not doing impersonation or contrainte deleg */
+	if (impersonate_principal =3D=3D NULL || flags.b.constrained_delegation) {
+	    krb5_cc_clear_mcred(&mcreds);
+	    mcreds.server =3D referral.server;
+	    ret =3D krb5_cc_retrieve_cred(context, ccache, 0, &mcreds, &ticket);
+	} else
+	    ret =3D EINVAL;
+
+	if (ret) {
+	    ret =3D get_cred_kdc_address(context, ccache, flags, NULL,
+				       &referral, &tgt, impersonate_principal,
+				       second_ticket, &ticket);
+	    if (ret)
+		goto out;
+	}
+
+	/* Did we get the right ticket ? */
+	if (krb5_principal_compare_any_realm(context,
+					     referral.server,
+					     ticket.server))
+	    break;
+
+	if (!krb5_principal_is_krbtgt(context, ticket.server)) {
+	    krb5_set_error_message(context, KRB5KRB_AP_ERR_NOT_US,
+				   N_("Got back an non krbtgt "
+				      "ticket referrals", ""));
+	    ret =3D KRB5KRB_AP_ERR_NOT_US;
+	    goto out;
+	}
+
+	referral_realm =3D ticket.server->name.name_string.val[1];
+
+	/* check that there are no referrals loops */
+	tickets =3D *ret_tgts;
+
+	krb5_cc_clear_mcred(&mcreds);
+	mcreds.server =3D ticket.server;
+
+	while(tickets && *tickets){
+	    if(krb5_compare_creds(context,
+				  KRB5_TC_DONT_MATCH_REALM,
+				  &mcreds,
+				  *tickets))
+	    {
+		krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+				       N_("Referral from %s "
+					  "loops back to realm %s", ""),
+				       tgt.server->realm,
+				       referral_realm);
+		ret =3D KRB5_GET_IN_TKT_LOOP;
+                goto out;
 	    }
-	    krb5_free_cred_contents(context, &tgts);
-	    krb5_free_principal(context, tmp_creds.server);
-	    krb5_free_principal(context, tmp_creds.client);
-	    return ret;
+	    tickets++;
 	}
+
+	/*
+	 * if either of the chain or the ok_as_delegate was stripped
+	 * by the kdc, make sure we strip it too.
+	 */
+
+	if (ok_as_delegate =3D=3D 0 || ticket.flags.b.ok_as_delegate =3D=3D 0) {
+	    ok_as_delegate =3D 0;
+	    ticket.flags.b.ok_as_delegate =3D 0;
+	}
+
+	ret =3D add_cred(context, &ticket, ret_tgts);
+	if (ret)
+	    goto out;
+
+	/* try realm in the referral */
+	ret =3D krb5_principal_set_realm(context,
+				       referral.server,
+				       referral_realm);
+	krb5_free_cred_contents(context, &tgt);
+	tgt =3D ticket;
+	memset(&ticket, 0, sizeof(ticket));
+	if (ret)
+	    goto out;
     }
-    if(krb5_realm_compare(context, in_creds->client, in_creds->server)) {
-	not_found(context, in_creds->server);
-	return KRB5_CC_NOTFOUND;
-    }
-    /* XXX this can loop forever */
-    while(1){
-	heim_general_string tgt_inst;
=20
-	ret =3D get_cred_from_kdc_flags(context, flags, ccache, &tmp_creds,=20
-				      NULL, NULL, &tgt, ret_tgts);
-	if(ret) {
-	    krb5_free_principal(context, tmp_creds.server);
-	    krb5_free_principal(context, tmp_creds.client);
-	    return ret;
-	}
-	ret =3D add_cred(context, ret_tgts, tgt);
-	if(ret) {
-	    krb5_free_principal(context, tmp_creds.server);
-	    krb5_free_principal(context, tmp_creds.client);
-	    return ret;
-	}
-	tgt_inst =3D tgt->server->name.name_string.val[1];
-	if(strcmp(tgt_inst, server_realm) =3D=3D 0)
-	    break;
-	krb5_free_principal(context, tmp_creds.server);
-	ret =3D krb5_make_principal(context, &tmp_creds.server,=20
-				  tgt_inst, KRB5_TGS_NAME, server_realm, NULL);
-	if(ret) {
-	    krb5_free_principal(context, tmp_creds.server);
-	    krb5_free_principal(context, tmp_creds.client);
-	    return ret;
-	}
-	ret =3D krb5_free_creds(context, tgt);
-	if(ret) {
-	    krb5_free_principal(context, tmp_creds.server);
-	    krb5_free_principal(context, tmp_creds.client);
-	    return ret;
-	}
-    }
-=09
-    krb5_free_principal(context, tmp_creds.server);
-    krb5_free_principal(context, tmp_creds.client);
-    *out_creds =3D calloc(1, sizeof(**out_creds));
-    if(*out_creds =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	ret =3D ENOMEM;
-    } else {
-	krb5_boolean noaddr;
+    ret =3D krb5_copy_creds(context, &ticket, out_creds);
=20
-	krb5_appdefault_boolean(context, NULL, tgt->server->realm,
-				"no-addresses", KRB5_ADDRESSLESS_DEFAULT,
-				&noaddr);
-	if (noaddr)
-	    ret =3D get_cred_kdc (context, ccache, flags, NULL,
-				in_creds, tgt, NULL, NULL,
-				*out_creds);
-	else
-	    ret =3D get_cred_kdc_la(context, ccache, flags,=20
-				  in_creds, tgt, NULL, NULL,
-				  *out_creds);
-	if (ret) {
-	    free (*out_creds);
-	    *out_creds =3D NULL;
-	}
-    }
-    krb5_free_creds(context, tgt);
+out:
+    krb5_free_principal(context, referral.server);
+    krb5_free_cred_contents(context, &tgt);
+    krb5_free_cred_contents(context, &ticket);
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_cred_from_kdc_opt(krb5_context context,
-			   krb5_ccache ccache,
-			   krb5_creds *in_creds,
-			   krb5_creds **out_creds,
-			   krb5_creds ***ret_tgts,
-			   krb5_flags flags)
-{
-    krb5_kdc_flags f;
-    f.i =3D flags;
-    return get_cred_from_kdc_flags(context, f, ccache,=20
-				   in_creds, NULL, NULL,
-				   out_creds, ret_tgts);
-}
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_cred_from_kdc(krb5_context context,
+/*
+ * Glue function between referrals version and old client chasing
+ * codebase.
+ */
+
+krb5_error_code
+_krb5_get_cred_kdc_any(krb5_context context,
+		       krb5_kdc_flags flags,
 		       krb5_ccache ccache,
 		       krb5_creds *in_creds,
+		       krb5_principal impersonate_principal,
+		       Ticket *second_ticket,
 		       krb5_creds **out_creds,
 		       krb5_creds ***ret_tgts)
 {
-    return krb5_get_cred_from_kdc_opt(context, ccache,=20
-				      in_creds, out_creds, ret_tgts, 0);
+    krb5_error_code ret;
+    krb5_deltat offset;
+
+    ret =3D krb5_cc_get_kdc_offset(context, ccache, &offset);
+    if (ret) {
+	context->kdc_sec_offset =3D offset;
+	context->kdc_usec_offset =3D 0;
+    }
+
+    ret =3D get_cred_kdc_referral(context,
+				flags,
+				ccache,
+				in_creds,
+				impersonate_principal,
+				second_ticket,
+				out_creds,
+				ret_tgts);
+    if (ret =3D=3D 0 || flags.b.canonicalize)
+	return ret;
+    return get_cred_kdc_capath(context,
+				flags,
+				ccache,
+				in_creds,
+				impersonate_principal,
+				second_ticket,
+				out_creds,
+				ret_tgts);
 }
-    =20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_credentials_with_flags(krb5_context context,
 				krb5_flags options,
 				krb5_kdc_flags flags,
@@ -929,18 +1129,25 @@
     krb5_creds **tgts;
     krb5_creds *res_creds;
     int i;
-   =20
+
+    if (in_creds->session.keytype) {
+	ret =3D krb5_enctype_valid(context, in_creds->session.keytype);
+	if (ret)
+	    return ret;
+    }
+
     *out_creds =3D NULL;
     res_creds =3D calloc(1, sizeof(*res_creds));
     if (res_creds =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
     if (in_creds->session.keytype)
 	options |=3D KRB5_TC_MATCH_KEYTYPE;
=20
-    /*=20
+    /*
      * If we got a credential, check if credential is expired before
      * returning it.
      */
@@ -949,7 +1156,7 @@
                                 in_creds->session.keytype ?
                                 KRB5_TC_MATCH_KEYTYPE : 0,
                                 in_creds, res_creds);
-    /*=20
+    /*
      * If we got a credential, check if credential is expired before
      * returning it, but only if KRB5_GC_EXPIRED_OK is not set.
      */
@@ -961,7 +1168,7 @@
             *out_creds =3D res_creds;
             return 0;
         }
-	   =20
+
 	krb5_timeofday(context, &timeret);
 	if(res_creds->times.endtime > timeret) {
 	    *out_creds =3D res_creds;
@@ -975,18 +1182,17 @@
         return ret;
     }
     free(res_creds);
-    if(options & KRB5_GC_CACHED) {
-	not_found(context, in_creds->server);
-        return KRB5_CC_NOTFOUND;
-    }
+    if(options & KRB5_GC_CACHED)
+	return not_found(context, in_creds->server, KRB5_CC_NOTFOUND);
+
     if(options & KRB5_GC_USER_USER)
 	flags.b.enc_tkt_in_skey =3D 1;
     if (flags.b.enc_tkt_in_skey)
 	options |=3D KRB5_GC_NO_STORE;
=20
     tgts =3D NULL;
-    ret =3D get_cred_from_kdc_flags(context, flags, ccache,=20
-				  in_creds, NULL, NULL, out_creds, &tgts);
+    ret =3D _krb5_get_cred_kdc_any(context, flags, ccache,
+				 in_creds, NULL, NULL, out_creds, &tgts);
     for(i =3D 0; tgts && tgts[i]; i++) {
 	krb5_cc_store_cred(context, ccache, tgts[i]);
 	krb5_free_creds(context, tgts[i]);
@@ -997,7 +1203,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_credentials(krb5_context context,
 		     krb5_flags options,
 		     krb5_ccache ccache,
@@ -1018,27 +1224,32 @@
 };
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds_opt_alloc(krb5_context context, krb5_get_creds_opt *opt)
 {
     *opt =3D calloc(1, sizeof(**opt));
     if (*opt =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_free(krb5_context context, krb5_get_creds_opt opt)
 {
     if (opt->self)
 	krb5_free_principal(context, opt->self);
+    if (opt->ticket) {
+	free_Ticket(opt->ticket);
+	free(opt->ticket);
+    }
     memset(opt, 0, sizeof(*opt));
     free(opt);
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_set_options(krb5_context context,
 			       krb5_get_creds_opt opt,
 			       krb5_flags options)
@@ -1046,7 +1257,7 @@
     opt->options =3D options;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_add_options(krb5_context context,
 			       krb5_get_creds_opt opt,
 			       krb5_flags options)
@@ -1054,7 +1265,7 @@
     opt->options |=3D options;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_set_enctype(krb5_context context,
 			       krb5_get_creds_opt opt,
 			       krb5_enctype enctype)
@@ -1062,7 +1273,7 @@
     opt->enctype =3D enctype;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds_opt_set_impersonate(krb5_context context,
 				   krb5_get_creds_opt opt,
 				   krb5_const_principal self)
@@ -1072,7 +1283,7 @@
     return krb5_copy_principal(context, self, &opt->self);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds_opt_set_ticket(krb5_context context,
 			      krb5_get_creds_opt opt,
 			      const Ticket *ticket)
@@ -1087,14 +1298,16 @@
=20
 	opt->ticket =3D malloc(sizeof(*ticket));
 	if (opt->ticket =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
 	    return ENOMEM;
 	}
 	ret =3D copy_Ticket(ticket, opt->ticket);
 	if (ret) {
 	    free(opt->ticket);
 	    opt->ticket =3D NULL;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    return ret;
 	}
     }
@@ -1103,7 +1316,7 @@
=20
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds(krb5_context context,
 	       krb5_get_creds_opt opt,
 	       krb5_ccache ccache,
@@ -1117,7 +1330,13 @@
     krb5_creds **tgts;
     krb5_creds *res_creds;
     int i;
-   =20
+
+    if (opt && opt->enctype) {
+	ret =3D krb5_enctype_valid(context, opt->enctype);
+	if (ret)
+	    return ret;
+    }
+
     memset(&in_creds, 0, sizeof(in_creds));
     in_creds.server =3D rk_UNCONST(inprinc);
=20
@@ -1125,31 +1344,35 @@
     if (ret)
 	return ret;
=20
-    options =3D opt->options;
+    if (opt)
+	options =3D opt->options;
+    else
+	options =3D 0;
     flags.i =3D 0;
=20
     *out_creds =3D NULL;
     res_creds =3D calloc(1, sizeof(*res_creds));
     if (res_creds =3D=3D NULL) {
 	krb5_free_principal(context, in_creds.client);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
-    if (opt->enctype) {
+    if (opt && opt->enctype) {
 	in_creds.session.keytype =3D opt->enctype;
 	options |=3D KRB5_TC_MATCH_KEYTYPE;
     }
=20
-    /*=20
+    /*
      * If we got a credential, check if credential is expired before
      * returning it.
      */
     ret =3D krb5_cc_retrieve_cred(context,
                                 ccache,
-				opt->enctype ? KRB5_TC_MATCH_KEYTYPE : 0,
+				options & KRB5_TC_MATCH_KEYTYPE,
                                 &in_creds, res_creds);
-    /*=20
+    /*
      * If we got a credential, check if credential is expired before
      * returning it, but only if KRB5_GC_EXPIRED_OK is not set.
      */
@@ -1160,14 +1383,14 @@
         if(options & KRB5_GC_EXPIRED_OK) {
             *out_creds =3D res_creds;
 	    krb5_free_principal(context, in_creds.client);
-            return 0;
+            goto out;
         }
-	   =20
+
 	krb5_timeofday(context, &timeret);
 	if(res_creds->times.endtime > timeret) {
 	    *out_creds =3D res_creds;
 	    krb5_free_principal(context, in_creds.client);
-	    return 0;
+            goto out;
 	}
 	if(options & KRB5_GC_CACHED)
 	    krb5_cc_remove_cred(context, ccache, 0, res_creds);
@@ -1175,13 +1398,13 @@
     } else if(ret !=3D KRB5_CC_END) {
         free(res_creds);
 	krb5_free_principal(context, in_creds.client);
-        return ret;
+	goto out;
     }
     free(res_creds);
     if(options & KRB5_GC_CACHED) {
-	not_found(context, in_creds.server);
 	krb5_free_principal(context, in_creds.client);
-        return KRB5_CC_NOTFOUND;
+	ret =3D not_found(context, in_creds.server, KRB5_CC_NOTFOUND);
+	goto out;
     }
     if(options & KRB5_GC_USER_USER) {
 	flags.b.enc_tkt_in_skey =3D 1;
@@ -1195,11 +1418,13 @@
 	flags.b.request_anonymous =3D 1; /* XXX ARGH confusion */
 	flags.b.constrained_delegation =3D 1;
     }
+    if (options & KRB5_GC_CANONICALIZE)
+	flags.b.canonicalize =3D 1;
=20
     tgts =3D NULL;
-    ret =3D get_cred_from_kdc_flags(context, flags, ccache,=20
-				  &in_creds, opt->self, opt->ticket,
-				  out_creds, &tgts);
+    ret =3D _krb5_get_cred_kdc_any(context, flags, ccache,
+				 &in_creds, opt->self, opt->ticket,
+				 out_creds, &tgts);
     krb5_free_principal(context, in_creds.client);
     for(i =3D 0; tgts && tgts[i]; i++) {
 	krb5_cc_store_cred(context, ccache, tgts[i]);
@@ -1208,6 +1433,10 @@
     free(tgts);
     if(ret =3D=3D 0 && (options & KRB5_GC_NO_STORE) =3D=3D 0)
 	krb5_cc_store_cred(context, ccache, *out_creds);
+
+ out:
+    _krb5_debug(context, 5, "krb5_get_creds: ret =3D %d", ret);
+
     return ret;
 }
=20
@@ -1215,7 +1444,7 @@
  *
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_renewed_creds(krb5_context context,
 		       krb5_creds *creds,
 		       krb5_const_principal client,
@@ -1241,7 +1470,7 @@
 	}
     } else {
 	const char *realm =3D krb5_principal_get_realm(context, client);
-=09
+
 	ret =3D krb5_make_principal(context, &in.server, realm, KRB5_TGS_NAME,
 				  realm, NULL);
 	if (ret) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_defau=
lt_principal.c
--- a/head/crypto/heimdal/lib/krb5/get_default_principal.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/get_default_principal.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: get_default_principal.c 14870 2005-04-20 20:53:29Z lha $");
-
 /*
  * Try to find out what's a reasonable default principal.
  */
@@ -50,6 +48,8 @@
     return user;
 }
=20
+#ifndef _WIN32
+
 /*
  * Will only use operating-system dependant operation to get the
  * default principal, for use of functions that in ccache layer to
@@ -57,7 +57,7 @@
  */
=20
 krb5_error_code
-_krb5_get_default_principal_local (krb5_context context,=20
+_krb5_get_default_principal_local (krb5_context context,
 				   krb5_principal *princ)
 {
     krb5_error_code ret;
@@ -66,7 +66,7 @@
=20
     *princ =3D NULL;
=20
-    uid =3D getuid();   =20
+    uid =3D getuid();
     if(uid =3D=3D 0) {
 	user =3D getlogin();
 	if(user =3D=3D NULL)
@@ -76,7 +76,7 @@
 	else
 	    ret =3D krb5_make_principal(context, princ, NULL, "root", NULL);
     } else {
-	struct passwd *pw =3D getpwuid(uid);=09
+	struct passwd *pw =3D getpwuid(uid);
 	if(pw !=3D NULL)
 	    user =3D pw->pw_name;
 	else {
@@ -85,8 +85,9 @@
 		user =3D getlogin();
 	}
 	if(user =3D=3D NULL) {
-	    krb5_set_error_string(context,
-				  "unable to figure out current principal");
+	    krb5_set_error_message(context, ENOTTY,
+				   N_("unable to figure out current "
+				      "principal", ""));
 	    return ENOTTY; /* XXX */
 	}
 	ret =3D krb5_make_principal(context, princ, NULL, user, NULL);
@@ -94,7 +95,56 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+#else  /* _WIN32 */
+
+#define SECURITY_WIN32
+#include <security.h>
+
+krb5_error_code
+_krb5_get_default_principal_local(krb5_context context,
+				  krb5_principal *princ)
+{
+    /* See if we can get the principal first.  We only expect this to
+       work if logged into a domain. */
+    {
+	char username[1024];
+	ULONG sz =3D sizeof(username);
+
+	if (GetUserNameEx(NameUserPrincipal, username, &sz)) {
+	    return krb5_parse_name_flags(context, username,
+					 KRB5_PRINCIPAL_PARSE_ENTERPRISE,
+					 princ);
+	}
+    }
+
+    /* Just get the Windows username.  This should pretty much always
+       work. */
+    {
+	char username[1024];
+	DWORD dsz =3D sizeof(username);
+
+	if (GetUserName(username, &dsz)) {
+	    return krb5_make_principal(context, princ, NULL, username, NULL);
+	}
+    }
+
+    /* Failing that, we look at the environment */
+    {
+	const char * username =3D get_env_user();
+
+	if (username =3D=3D NULL) {
+	    krb5_set_error_string(context,
+				  "unable to figure out current principal");
+	    return ENOTTY;	/* Really? */
+	}
+
+	return krb5_make_principal(context, princ, NULL, username, NULL);
+    }
+}
+
+#endif
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_principal (krb5_context context,
 			    krb5_principal *princ)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_defau=
lt_realm.c
--- a/head/crypto/heimdal/lib/krb5/get_default_realm.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/get_default_realm.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,46 +1,44 @@
 /*
- * Copyright (c) 1997 - 2001, 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: get_default_realm.c 13863 2004-05-25 21:46:46Z lha $");
-
 /*
  * Return a NULL-terminated list of default realms in `realms'.
  * Free this memory with krb5_free_host_realm.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_realms (krb5_context context,
 			 krb5_realm **realms)
 {
@@ -59,7 +57,7 @@
  * Return the first default realm.  For compatibility.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_realm(krb5_context context,
 		       krb5_realm *realm)
 {
@@ -68,7 +66,7 @@
=20
     if (context->default_realms =3D=3D NULL
 	|| context->default_realms[0] =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	ret =3D krb5_set_default_realm (context, NULL);
 	if (ret)
 	    return ret;
@@ -76,7 +74,8 @@
=20
     res =3D strdup (context->default_realms[0]);
     if (res =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *realm =3D res;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_for_c=
reds.c
--- a/head/crypto/heimdal/lib/krb5/get_for_creds.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/get_for_creds.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
-
-RCSID("$Id: get_for_creds.c 22504 2008-01-21 15:49:58Z lha $");
+#include "krb5_locl.h"
=20
 static krb5_error_code
 add_addrs(krb5_context context,
@@ -51,8 +49,8 @@
=20
     tmp =3D realloc(addr->val, (addr->len + n) * sizeof(*addr->val));
     if (tmp =3D=3D NULL && (addr->len + n) !=3D 0) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
     addr->val =3D tmp;
@@ -72,7 +70,7 @@
 		addr->val[i++] =3D ad;
 	}
 	else if (ret =3D=3D KRB5_PROG_ATYPE_NOSUPP)
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	else
 	    goto fail;
 	addr->len =3D i;
@@ -102,7 +100,7 @@
  * @ingroup krb5_credential
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_fwd_tgt_creds (krb5_context	context,
 		    krb5_auth_context	auth_context,
 		    const char		*hostname,
@@ -129,23 +127,22 @@
=20
 	if (inst !=3D NULL &&
 	    strcmp(inst, "host") =3D=3D 0 &&
-	    host !=3D NULL &&=20
+	    host !=3D NULL &&
 	    krb5_principal_get_comp_string(context, server, 2) =3D=3D NULL)
 	    hostname =3D host;
     }
=20
     client_realm =3D krb5_principal_get_realm(context, client);
-   =20
+
     memset (&creds, 0, sizeof(creds));
     creds.client =3D client;
=20
-    ret =3D krb5_build_principal(context,
-			       &creds.server,
-			       strlen(client_realm),
-			       client_realm,
-			       KRB5_TGS_NAME,
-			       client_realm,
-			       NULL);
+    ret =3D krb5_make_principal(context,
+			      &creds.server,
+			      client_realm,
+			      KRB5_TGS_NAME,
+			      client_realm,
+			      NULL);
     if (ret)
 	return ret;
=20
@@ -163,7 +160,7 @@
  * Gets tickets forwarded to hostname. If the tickets that are
  * forwarded are address-less, the forwarded tickets will also be
  * address-less.
- *=20
+ *
  * If the ticket have any address, hostname will be used for figure
  * out the address to forward the ticket too. This since this might
  * use DNS, its insecure and also doesn't represent configured all
@@ -186,7 +183,7 @@
  * @ingroup krb5_credential
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_forwarded_creds (krb5_context	    context,
 			  krb5_auth_context auth_context,
 			  krb5_ccache       ccache,
@@ -207,7 +204,6 @@
     krb5_kdc_flags kdc_flags;
     krb5_crypto crypto;
     struct addrinfo *ai;
-    int save_errno;
     krb5_creds *ticket;
=20
     paddrs =3D NULL;
@@ -222,14 +218,14 @@
     } else {
 	krb5_boolean noaddr;
 	krb5_appdefault_boolean(context, NULL,
-				krb5_principal_get_realm(context,=20
+				krb5_principal_get_realm(context,
 							 in_creds->client),
 				"no-addresses", KRB5_ADDRESSLESS_DEFAULT,
 				&noaddr);
 	if (!noaddr)
 	    paddrs =3D &addrs;
     }
-=09
+
     /*
      * If tickets have addresses, get the address of the remote host.
      */
@@ -238,18 +234,20 @@
=20
 	ret =3D getaddrinfo (hostname, NULL, NULL, &ai);
 	if (ret) {
-	    save_errno =3D errno;
-	    krb5_set_error_string(context, "resolving %s: %s",
+	    krb5_error_code ret2 =3D krb5_eai_to_heim_errno(ret, errno);
+	    krb5_set_error_message(context, ret2,
+				   N_("resolving host %s failed: %s",
+				      "hostname, error"),
 				  hostname, gai_strerror(ret));
-	    return krb5_eai_to_heim_errno(ret, save_errno);
+	    return ret2;
 	}
-=09
+
 	ret =3D add_addrs (context, &addrs, ai);
 	freeaddrinfo (ai);
 	if (ret)
 	    return ret;
     }
-   =20
+
     kdc_flags.b =3D int2KDCOptions(flags);
=20
     ret =3D krb5_get_kdc_cred (context,
@@ -269,7 +267,7 @@
     ALLOC_SEQ(&cred.tickets, 1);
     if (cred.tickets.val =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto out2;
     }
     ret =3D decode_Ticket(out_creds->ticket.data,
@@ -282,27 +280,27 @@
     ALLOC_SEQ(&enc_krb_cred_part.ticket_info, 1);
     if (enc_krb_cred_part.ticket_info.val =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto out4;
     }
-   =20
+
     if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
 	krb5_timestamp sec;
 	int32_t usec;
-=09
+
 	krb5_us_timeofday (context, &sec, &usec);
-=09
+
 	ALLOC(enc_krb_cred_part.timestamp, 1);
 	if (enc_krb_cred_part.timestamp =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto out4;
 	}
 	*enc_krb_cred_part.timestamp =3D sec;
 	ALLOC(enc_krb_cred_part.usec, 1);
 	if (enc_krb_cred_part.usec =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto out4;
 	}
 	*enc_krb_cred_part.usec      =3D usec;
@@ -346,7 +344,8 @@
 	    ALLOC(enc_krb_cred_part.r_address, 1);
 	    if (enc_krb_cred_part.r_address =3D=3D NULL) {
 		ret =3D ENOMEM;
-		krb5_set_error_string(context, "malloc: out of memory");
+		krb5_set_error_message(context, ret,
+				       N_("malloc: out of memory", ""));
 		goto out4;
 	    }
=20
@@ -389,7 +388,7 @@
=20
     /* encode EncKrbCredPart */
=20
-    ASN1_MALLOC_ENCODE(EncKrbCredPart, buf, buf_size,=20
+    ASN1_MALLOC_ENCODE(EncKrbCredPart, buf, buf_size,
 		       &enc_krb_cred_part, &len, ret);
     free_EncKrbCredPart (&enc_krb_cred_part);
     if (ret) {
@@ -413,13 +412,13 @@
 	cred.enc_part.cipher.data =3D buf;
 	cred.enc_part.cipher.length =3D buf_size;
     } else {
-	/*=20
+	/*
 	 * Here older versions then 0.7.2 of Heimdal used the local or
 	 * remote subkey. That is wrong, the session key should be
 	 * used. Heimdal 0.7.2 and newer have code to try both in the
 	 * receiving end.
 	 */
-=09
+
 	ret =3D krb5_crypto_init(context, auth_context->keyblock, 0, &crypto);
 	if (ret) {
 	    free(buf);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_host_=
realm.c
--- a/head/crypto/heimdal/lib/krb5/get_host_realm.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/get_host_realm.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include <resolve.h>
=20
-RCSID("$Id: get_host_realm.c 18541 2006-10-17 19:28:36Z lha $");
-
 /* To automagically find the correct realm of a host (without
  * [domain_realm] in krb5.conf) add a text record for your domain with
  * the name of your realm, like this:
@@ -51,14 +49,14 @@
  */
=20
 static int
-copy_txt_to_realms (struct resource_record *head,
+copy_txt_to_realms (struct rk_resource_record *head,
 		    krb5_realm **realms)
 {
-    struct resource_record *rr;
-    int n, i;
+    struct rk_resource_record *rr;
+    unsigned int n, i;
=20
     for(n =3D 0, rr =3D head; rr; rr =3D rr->next)
-	if (rr->type =3D=3D T_TXT)
+	if (rr->type =3D=3D rk_ns_t_txt)
 	    ++n;
=20
     if (n =3D=3D 0)
@@ -72,7 +70,7 @@
 	(*realms)[i] =3D NULL;
=20
     for (i =3D 0, rr =3D head; rr; rr =3D rr->next) {
-	if (rr->type =3D=3D T_TXT) {
+	if (rr->type =3D=3D rk_ns_t_txt) {
 	    char *tmp;
=20
 	    tmp =3D strdup(rr->u.txt);
@@ -96,11 +94,11 @@
 {
     static const char *default_labels[] =3D { "_kerberos", NULL };
     char dom[MAXHOSTNAMELEN];
-    struct dns_reply *r;
+    struct rk_dns_reply *r;
     const char **labels;
     char **config_labels;
     int i, ret;
-   =20
+
     config_labels =3D krb5_config_get_strings(context, NULL, "libdefaults",
 					    "dns_lookup_realm_labels", NULL);
     if(config_labels !=3D NULL)
@@ -111,15 +109,15 @@
 	domain++;
     for (i =3D 0; labels[i] !=3D NULL; i++) {
 	ret =3D snprintf(dom, sizeof(dom), "%s.%s.", labels[i], domain);
-	if(ret < 0 || ret >=3D sizeof(dom)) {
+	if(ret < 0 || (size_t)ret >=3D sizeof(dom)) {
 	    if (config_labels)
 		krb5_config_free_strings(config_labels);
 	    return -1;
 	}
-    	r =3D dns_lookup(dom, "TXT");
+    	r =3D rk_dns_lookup(dom, "TXT");
     	if(r !=3D NULL) {
 	    ret =3D copy_txt_to_realms (r->head, realms);
-	    dns_free_data(r);
+	    rk_dns_free_data(r);
 	    if(ret =3D=3D 0) {
 		if (config_labels)
 		    krb5_config_free_strings(config_labels);
@@ -138,8 +136,8 @@
  */
=20
 static int
-config_find_realm(krb5_context context,=20
-		  const char *domain,=20
+config_find_realm(krb5_context context,
+		  const char *domain,
 		  krb5_realm **realms)
 {
     char **tmp =3D krb5_config_get_strings (context, NULL,
@@ -160,7 +158,7 @@
  * fall back to guessing
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_get_host_realm_int (krb5_context context,
 			  const char *host,
 			  krb5_boolean use_dns,
@@ -178,8 +176,8 @@
 		    for (q =3D host; q !=3D NULL; q =3D strchr(q + 1, '.'))
 			if(dns_find_realm(context, q, realms) =3D=3D 0)
 			    return 0;
-		continue;=20
-	    } else=20
+		continue;
+	    } else
 	    	return 0;
 	}
 	else if(use_dns && dns_locate_enable) {
@@ -192,21 +190,23 @@
 	p++;
 	*realms =3D malloc(2 * sizeof(krb5_realm));
 	if (*realms =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "=
"));
 	    return ENOMEM;
 	}
=20
 	(*realms)[0] =3D strdup(p);
 	if((*realms)[0] =3D=3D NULL) {
 	    free(*realms);
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "=
"));
 	    return ENOMEM;
 	}
 	strupr((*realms)[0]);
 	(*realms)[1] =3D NULL;
 	return 0;
     }
-    krb5_set_error_string(context, "unable to find realm of host %s", host=
);
+    krb5_set_error_message(context, KRB5_ERR_HOST_REALM_UNKNOWN,
+			   N_("unable to find realm of host %s", ""),
+			   host);
     return KRB5_ERR_HOST_REALM_UNKNOWN;
 }
=20
@@ -215,7 +215,7 @@
  * `realms'. Free `realms' with krb5_free_host_realm().
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_host_realm(krb5_context context,
 		    const char *targethost,
 		    krb5_realm **realms)
@@ -233,7 +233,7 @@
 	host =3D hostname;
     }
=20
-    /*=20
+    /*
      * If our local hostname is without components, don't even try to dns.
      */
=20
@@ -248,8 +248,9 @@
 	 */
 	ret =3D krb5_get_default_realms(context, realms);
 	if (ret) {
-	    krb5_set_error_string(context, "Unable to find realm of host %s",
-				  host);
+	    krb5_set_error_message(context, KRB5_ERR_HOST_REALM_UNKNOWN,
+				   N_("Unable to find realm of host %s", ""),
+				   host);
 	    return KRB5_ERR_HOST_REALM_UNKNOWN;
 	}
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_in_tk=
t.c
--- a/head/crypto/heimdal/lib/krb5/get_in_tkt.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/get_in_tkt.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,331 +1,54 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: get_in_tkt.c 20226 2007-02-16 03:31:50Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_init_etype (krb5_context context,
-		 unsigned *len,
-		 krb5_enctype **val,
-		 const krb5_enctype *etypes)
-{
-    int i;
-    krb5_error_code ret;
-    krb5_enctype *tmp =3D NULL;
-
-    ret =3D 0;
-    if (etypes =3D=3D NULL) {
-	ret =3D krb5_get_default_in_tkt_etypes(context,
-					     &tmp);
-	if (ret)
-	    return ret;
-	etypes =3D tmp;
-    }
-
-    for (i =3D 0; etypes[i]; ++i)
-	;
-    *len =3D i;
-    *val =3D malloc(i * sizeof(**val));
-    if (i !=3D 0 && *val =3D=3D NULL) {
-	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
-	goto cleanup;
-    }
-    memmove (*val,
-	     etypes,
-	     i * sizeof(*tmp));
-cleanup:
-    if (tmp !=3D NULL)
-	free (tmp);
-    return ret;
-}
-
+#ifndef HEIMDAL_SMALLER
=20
 static krb5_error_code
-decrypt_tkt (krb5_context context,
-	     krb5_keyblock *key,
-	     krb5_key_usage usage,
-	     krb5_const_pointer decrypt_arg,
-	     krb5_kdc_rep *dec_rep)
-{
-    krb5_error_code ret;
-    krb5_data data;
-    size_t size;
-    krb5_crypto crypto;
-
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret)
-	return ret;
-
-    ret =3D krb5_decrypt_EncryptedData (context,
-				      crypto,
-				      usage,
-				      &dec_rep->kdc_rep.enc_part,
-				      &data);
-    krb5_crypto_destroy(context, crypto);
-
-    if (ret)
-	return ret;
-
-    ret =3D krb5_decode_EncASRepPart(context,
-				   data.data,
-				   data.length,
-				   &dec_rep->enc_part,=20
-				   &size);
-    if (ret)
-	ret =3D krb5_decode_EncTGSRepPart(context,
-					data.data,
-					data.length,
-					&dec_rep->enc_part,=20
-					&size);
-    krb5_data_free (&data);
-    if (ret)
-	return ret;
-    return 0;
-}
-
-int
-_krb5_extract_ticket(krb5_context context,=20
-		     krb5_kdc_rep *rep,=20
-		     krb5_creds *creds,	=09
-		     krb5_keyblock *key,
-		     krb5_const_pointer keyseed,
-		     krb5_key_usage key_usage,
-		     krb5_addresses *addrs,
-		     unsigned nonce,
-		     unsigned flags,
-		     krb5_decrypt_proc decrypt_proc,
-		     krb5_const_pointer decryptarg)
-{
-    krb5_error_code ret;
-    krb5_principal tmp_principal;
-    int tmp;
-    size_t len;
-    time_t tmp_time;
-    krb5_timestamp sec_now;
-
-    ret =3D _krb5_principalname2krb5_principal (context,
-					      &tmp_principal,
-					      rep->kdc_rep.cname,
-					      rep->kdc_rep.crealm);
-    if (ret)
-	goto out;
-
-    /* compare client */
-
-    if((flags & EXTRACT_TICKET_ALLOW_CNAME_MISMATCH) =3D=3D 0){
-	tmp =3D krb5_principal_compare (context, tmp_principal, creds->client);
-	if (!tmp) {
-	    krb5_free_principal (context, tmp_principal);
-	    krb5_clear_error_string (context);
-	    ret =3D KRB5KRB_AP_ERR_MODIFIED;
-	    goto out;
-	}
-    }
-
-    krb5_free_principal (context, creds->client);
-    creds->client =3D tmp_principal;
-
-    /* extract ticket */
-    ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,=20
-		       &rep->kdc_rep.ticket, &len, ret);
-    if(ret)
-	goto out;
-    if (creds->ticket.length !=3D len)
-	krb5_abortx(context, "internal error in ASN.1 encoder");
-    creds->second_ticket.length =3D 0;
-    creds->second_ticket.data   =3D NULL;
-
-    /* compare server */
-
-    ret =3D _krb5_principalname2krb5_principal (context,
-					      &tmp_principal,
-					      rep->kdc_rep.ticket.sname,
-					      rep->kdc_rep.ticket.realm);
-    if (ret)
-	goto out;
-    if(flags & EXTRACT_TICKET_ALLOW_SERVER_MISMATCH){
-	krb5_free_principal(context, creds->server);
-	creds->server =3D tmp_principal;
-	tmp_principal =3D NULL;
-    } else {
-	tmp =3D krb5_principal_compare (context, tmp_principal,
-				      creds->server);
-	krb5_free_principal (context, tmp_principal);
-	if (!tmp) {
-	    ret =3D KRB5KRB_AP_ERR_MODIFIED;
-	    krb5_clear_error_string (context);
-	    goto out;
-	}
-    }
-   =20
-    /* decrypt */
-
-    if (decrypt_proc =3D=3D NULL)
-	decrypt_proc =3D decrypt_tkt;
-   =20
-    ret =3D (*decrypt_proc)(context, key, key_usage, decryptarg, rep);
-    if (ret)
-	goto out;
-
-    /* verify names */
-    if(flags & EXTRACT_TICKET_MATCH_REALM){
-	const char *srealm =3D krb5_principal_get_realm(context, creds->server);
-	const char *crealm =3D krb5_principal_get_realm(context, creds->client);
-
-	if (strcmp(rep->enc_part.srealm, srealm) !=3D 0 ||
-	    strcmp(rep->enc_part.srealm, crealm) !=3D 0)
-	{
-	    ret =3D KRB5KRB_AP_ERR_MODIFIED;
-	    krb5_clear_error_string(context);
-	    goto out;
-	}
-    }
-
-    /* compare nonces */
-
-    if (nonce !=3D rep->enc_part.nonce) {
-	ret =3D KRB5KRB_AP_ERR_MODIFIED;
-	krb5_set_error_string(context, "malloc: out of memory");
-	goto out;
-    }
-
-    /* set kdc-offset */
-
-    krb5_timeofday (context, &sec_now);
-    if (rep->enc_part.flags.initial
-	&& context->kdc_sec_offset =3D=3D 0
-	&& krb5_config_get_bool (context, NULL,
-				 "libdefaults",
-				 "kdc_timesync",
-				 NULL)) {
-	context->kdc_sec_offset =3D rep->enc_part.authtime - sec_now;
-	krb5_timeofday (context, &sec_now);
-    }
-
-    /* check all times */
-
-    if (rep->enc_part.starttime) {
-	tmp_time =3D *rep->enc_part.starttime;
-    } else
-	tmp_time =3D rep->enc_part.authtime;
-
-    if (creds->times.starttime =3D=3D 0
-	&& abs(tmp_time - sec_now) > context->max_skew) {
-	ret =3D KRB5KRB_AP_ERR_SKEW;
-	krb5_set_error_string (context,
-			       "time skew (%d) larger than max (%d)",
-			       abs(tmp_time - sec_now),
-			       (int)context->max_skew);
-	goto out;
-    }
-
-    if (creds->times.starttime !=3D 0
-	&& tmp_time !=3D creds->times.starttime) {
-	krb5_clear_error_string (context);
-	ret =3D KRB5KRB_AP_ERR_MODIFIED;
-	goto out;
-    }
-
-    creds->times.starttime =3D tmp_time;
-
-    if (rep->enc_part.renew_till) {
-	tmp_time =3D *rep->enc_part.renew_till;
-    } else
-	tmp_time =3D 0;
-
-    if (creds->times.renew_till !=3D 0
-	&& tmp_time > creds->times.renew_till) {
-	krb5_clear_error_string (context);
-	ret =3D KRB5KRB_AP_ERR_MODIFIED;
-	goto out;
-    }
-
-    creds->times.renew_till =3D tmp_time;
-
-    creds->times.authtime =3D rep->enc_part.authtime;
-
-    if (creds->times.endtime !=3D 0
-	&& rep->enc_part.endtime > creds->times.endtime) {
-	krb5_clear_error_string (context);
-	ret =3D KRB5KRB_AP_ERR_MODIFIED;
-	goto out;
-    }
-
-    creds->times.endtime  =3D rep->enc_part.endtime;
-
-    if(rep->enc_part.caddr)
-	krb5_copy_addresses (context, rep->enc_part.caddr, &creds->addresses);
-    else if(addrs)
-	krb5_copy_addresses (context, addrs, &creds->addresses);
-    else {
-	creds->addresses.len =3D 0;
-	creds->addresses.val =3D NULL;
-    }
-    creds->flags.b =3D rep->enc_part.flags;
-	 =20
-    creds->authdata.len =3D 0;
-    creds->authdata.val =3D NULL;
-    creds->session.keyvalue.length =3D 0;
-    creds->session.keyvalue.data   =3D NULL;
-    creds->session.keytype =3D rep->enc_part.key.keytype;
-    ret =3D krb5_data_copy (&creds->session.keyvalue,
-			  rep->enc_part.key.keyvalue.data,
-			  rep->enc_part.key.keyvalue.length);
-
-out:
-    memset (rep->enc_part.key.keyvalue.data, 0,
-	    rep->enc_part.key.keyvalue.length);
-    return ret;
-}
-
-
-static krb5_error_code
-make_pa_enc_timestamp(krb5_context context, PA_DATA *pa,=20
+make_pa_enc_timestamp(krb5_context context, PA_DATA *pa,
 		      krb5_enctype etype, krb5_keyblock *key)
 {
     PA_ENC_TS_ENC p;
     unsigned char *buf;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     EncryptedData encdata;
     krb5_error_code ret;
     int32_t usec;
     int usec2;
     krb5_crypto crypto;
-   =20
+
     krb5_us_timeofday (context, &p.patimestamp, &usec);
     usec2         =3D usec;
     p.pausec      =3D &usec2;
@@ -340,7 +63,7 @@
 	free(buf);
 	return ret;
     }
-    ret =3D krb5_encrypt_EncryptedData(context,=20
+    ret =3D krb5_encrypt_EncryptedData(context,
 				     crypto,
 				     KRB5_KU_PA_ENC_TIMESTAMP,
 				     buf,
@@ -351,7 +74,7 @@
     krb5_crypto_destroy(context, crypto);
     if (ret)
 	return ret;
-		   =20
+
     ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
     free_EncryptedData(&encdata);
     if (ret)
@@ -366,7 +89,7 @@
=20
 static krb5_error_code
 add_padata(krb5_context context,
-	   METHOD_DATA *md,=20
+	   METHOD_DATA *md,
 	   krb5_principal client,
 	   krb5_key_proc key_proc,
 	   krb5_const_pointer keyseed,
@@ -378,11 +101,13 @@
     PA_DATA *pa2;
     krb5_salt salt2;
     krb5_enctype *ep;
-    int i;
-   =20
+    size_t i;
+
     if(salt =3D=3D NULL) {
 	/* default to standard salt */
 	ret =3D krb5_get_pw_salt (context, client, &salt2);
+	if (ret)
+	    return ret;
 	salt =3D &salt2;
     }
     if (!enctypes) {
@@ -393,7 +118,7 @@
     }
     pa2 =3D realloc (md->val, (md->len + netypes) * sizeof(*md->val));
     if (pa2 =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     md->val =3D pa2;
@@ -440,13 +165,13 @@
     a->req_body.cname =3D malloc(sizeof(*a->req_body.cname));
     if (a->req_body.cname =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
     a->req_body.sname =3D malloc(sizeof(*a->req_body.sname));
     if (a->req_body.sname =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
     ret =3D _krb5_principal2principalname (a->req_body.cname, creds->clien=
t);
@@ -463,7 +188,7 @@
 	a->req_body.from =3D malloc(sizeof(*a->req_body.from));
 	if (a->req_body.from =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	*a->req_body.from =3D creds->times.starttime;
@@ -476,13 +201,14 @@
 	a->req_body.rtime =3D malloc(sizeof(*a->req_body.rtime));
 	if (a->req_body.rtime =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	*a->req_body.rtime =3D creds->times.renew_till;
     }
     a->req_body.nonce =3D nonce;
-    ret =3D krb5_init_etype (context,
+    ret =3D _krb5_init_etype(context,
+			   KRB5_PDU_AS_REQUEST,
 			   &a->req_body.etype.len,
 			   &a->req_body.etype.val,
 			   etypes);
@@ -499,7 +225,7 @@
 	a->req_body.addresses =3D malloc(sizeof(*a->req_body.addresses));
 	if (a->req_body.addresses =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
=20
@@ -520,18 +246,18 @@
     a->req_body.additional_tickets =3D NULL;
=20
     if(preauth !=3D NULL) {
-	int i;
+	size_t i;
 	ALLOC(a->padata, 1);
 	if(a->padata =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	a->padata->val =3D NULL;
 	a->padata->len =3D 0;
 	for(i =3D 0; i < preauth->len; i++) {
 	    if(preauth->val[i].type =3D=3D KRB5_PADATA_ENC_TIMESTAMP){
-		int j;
+		size_t j;
=20
 		for(j =3D 0; j < preauth->val[i].info.len; j++) {
 		    krb5_salt *sp =3D &salt;
@@ -546,8 +272,8 @@
 			    sp =3D NULL;
 			else
 			    krb5_data_zero(&salt.saltvalue);
-		    ret =3D add_padata(context, a->padata, creds->client,=20
-				     key_proc, keyseed,=20
+		    ret =3D add_padata(context, a->padata, creds->client,
+				     key_proc, keyseed,
 				     &preauth->val[i].info.val[j].etype, 1,
 				     sp);
 		    if (ret =3D=3D 0)
@@ -555,7 +281,7 @@
 		}
 	    }
 	}
-    } else=20
+    } else
     /* not sure this is the way to use `ptypes' */
     if (ptypes =3D=3D NULL || *ptypes =3D=3D KRB5_PADATA_NONE)
 	a->padata =3D NULL;
@@ -563,27 +289,28 @@
 	ALLOC(a->padata, 1);
 	if (a->padata =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	a->padata->len =3D 0;
 	a->padata->val =3D NULL;
=20
 	/* make a v5 salted pa-data */
-	add_padata(context, a->padata, creds->client,=20
+	add_padata(context, a->padata, creds->client,
 		   key_proc, keyseed, a->req_body.etype.val,
 		   a->req_body.etype.len, NULL);
-=09
+
 	/* make a v4 salted pa-data */
 	salt.salttype =3D KRB5_PW_SALT;
 	krb5_data_zero(&salt.saltvalue);
-	add_padata(context, a->padata, creds->client,=20
+	add_padata(context, a->padata, creds->client,
 		   key_proc, keyseed, a->req_body.etype.val,
 		   a->req_body.etype.len, &salt);
     } else {
-	krb5_set_error_string (context, "pre-auth type %d not supported",
+	ret =3D KRB5_PREAUTH_BAD_TYPE;
+	krb5_set_error_message (context, ret,
+				N_("pre-auth type %d not supported", ""),
 			       *ptypes);
-	ret =3D KRB5_PREAUTH_BAD_TYPE;
 	goto fail;
     }
     return 0;
@@ -594,7 +321,7 @@
=20
 static int
 set_ptypes(krb5_context context,
-	   KRB_ERROR *error,=20
+	   KRB_ERROR *error,
 	   const krb5_preauthtype **ptypes,
 	   krb5_preauthdata **preauth)
 {
@@ -603,10 +330,10 @@
=20
     if(error->e_data) {
 	METHOD_DATA md;
-	int i;
-	decode_METHOD_DATA(error->e_data->data,=20
-			   error->e_data->length,=20
-			   &md,=20
+	size_t i;
+	decode_METHOD_DATA(error->e_data->data,
+			   error->e_data->length,
+			   &md,
 			   NULL);
 	for(i =3D 0; i < md.len; i++){
 	    switch(md.val[i].padata_type){
@@ -617,11 +344,10 @@
 		*preauth =3D &preauth2;
 		ALLOC_SEQ(*preauth, 1);
 		(*preauth)->val[0].type =3D KRB5_PADATA_ENC_TIMESTAMP;
-		krb5_decode_ETYPE_INFO(context,
-				       md.val[i].padata_value.data,=20
-				       md.val[i].padata_value.length,
-				       &(*preauth)->val[0].info,
-				       NULL);
+		decode_ETYPE_INFO(md.val[i].padata_value.data,
+				  md.val[i].padata_value.length,
+				  &(*preauth)->val[0].info,
+				  NULL);
 		break;
 	    default:
 		break;
@@ -634,7 +360,7 @@
     return(1);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_in_cred(krb5_context context,
 		 krb5_flags options,
 		 const krb5_addresses *addrs,
@@ -647,12 +373,13 @@
 		 krb5_const_pointer decryptarg,
 		 krb5_creds *creds,
 		 krb5_kdc_rep *ret_as_reply)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     krb5_error_code ret;
     AS_REQ a;
     krb5_kdc_rep rep;
     krb5_data req, resp;
-    size_t len;
+    size_t len =3D 0;
     krb5_salt salt;
     krb5_keyblock *key;
     size_t size;
@@ -725,7 +452,7 @@
 		    done =3D 0;
 		    preauth =3D my_preauth;
 		    krb5_free_error_contents(context, &error);
-		    krb5_clear_error_string(context);
+		    krb5_clear_error_message(context);
 		    continue;
 		}
 		if(ret_as_reply)
@@ -738,29 +465,29 @@
 	}
 	krb5_data_free(&resp);
     } while(!done);
-   =20
+
     pa =3D NULL;
     etype =3D rep.kdc_rep.enc_part.etype;
     if(rep.kdc_rep.padata){
 	int i =3D 0;
-	pa =3D krb5_find_padata(rep.kdc_rep.padata->val, rep.kdc_rep.padata->len,=20
+	pa =3D krb5_find_padata(rep.kdc_rep.padata->val, rep.kdc_rep.padata->len,
 			      KRB5_PADATA_PW_SALT, &i);
 	if(pa =3D=3D NULL) {
 	    i =3D 0;
-	    pa =3D krb5_find_padata(rep.kdc_rep.padata->val,=20
-				  rep.kdc_rep.padata->len,=20
+	    pa =3D krb5_find_padata(rep.kdc_rep.padata->val,
+				  rep.kdc_rep.padata->len,
 				  KRB5_PADATA_AFS3_SALT, &i);
 	}
     }
     if(pa) {
-	salt.salttype =3D pa->padata_type;
+	salt.salttype =3D (krb5_salttype)pa->padata_type;
 	salt.saltvalue =3D pa->padata_value;
-=09
+
 	ret =3D (*key_proc)(context, etype, salt, keyseed, &key);
     } else {
 	/* make a v5 salted pa-data */
 	ret =3D krb5_get_pw_salt (context, creds->client, &salt);
-=09
+
 	if (ret)
 	    goto out;
 	ret =3D (*key_proc)(context, etype, salt, keyseed, &key);
@@ -768,22 +495,22 @@
     }
     if (ret)
 	goto out;
-=09
+
     {
-	unsigned flags =3D 0;
+	unsigned flags =3D EXTRACT_TICKET_TIMESYNC;
 	if (opts.request_anonymous)
 	    flags |=3D EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
=20
-	ret =3D _krb5_extract_ticket(context,=20
-				   &rep,=20
-				   creds,=20
-				   key,=20
-				   keyseed,=20
+	ret =3D _krb5_extract_ticket(context,
+				   &rep,
+				   creds,
+				   key,
+				   keyseed,
 				   KRB5_KU_AS_REP_ENC_PART,
-				   NULL,=20
-				   nonce,=20
+				   NULL,
+				   nonce,
 				   flags,
-				   decrypt_proc,=20
+				   decrypt_proc,
 				   decryptarg);
     }
     memset (key->keyvalue.data, 0, key->keyvalue.length);
@@ -798,7 +525,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_in_tkt(krb5_context context,
 		krb5_flags options,
 		const krb5_addresses *addrs,
@@ -811,9 +538,10 @@
 		krb5_creds *creds,
 		krb5_ccache ccache,
 		krb5_kdc_rep *ret_as_reply)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
     krb5_error_code ret;
-   =20
+
     ret =3D krb5_get_in_cred (context,
 			    options,
 			    addrs,
@@ -826,9 +554,11 @@
 			    decryptarg,
 			    creds,
 			    ret_as_reply);
-    if(ret)=20
+    if(ret)
 	return ret;
     if (ccache)
 	ret =3D krb5_cc_store_cred (context, ccache, creds);
     return ret;
 }
+
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/get_port.c
--- a/head/crypto/heimdal/lib/krb5/get_port.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/get_port.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: get_port.c 13863 2004-05-25 21:46:46Z lha $");
-
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_getportbyname (krb5_context context,
 		    const char *service,
 		    const char *proto,
@@ -45,7 +43,7 @@
=20
     if ((sp =3D roken_getservbyname (service, proto)) =3D=3D NULL) {
 #if 0
-	krb5_warnx(context, "%s/%s unknown service, using default port %d",=20
+	krb5_warnx(context, "%s/%s unknown service, using default port %d",
 		   service, proto, default_port);
 #endif
 	return htons(default_port);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/heim_err.=
et
--- a/head/crypto/heimdal/lib/krb5/heim_err.et	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/heim_err.et	Tue Apr 17 11:51:51 2012 +03=
00
@@ -3,7 +3,7 @@
 #
 # This might look like a com_err file, but is not
 #
-id "$Id: heim_err.et 13352 2004-02-13 16:23:40Z lha $"
+id "$Id$"
=20
 error_table heim
=20
@@ -17,6 +17,9 @@
 error_code EOF,			"End of file"
 error_code BAD_MKEY,		"Failed to get the master key"
 error_code SERVICE_NOMATCH,	"Unacceptable service used"
+error_code NOT_SEEKABLE,	"File descriptor not seekable"
+error_code TOO_BIG,		"Offset too large"
+error_code BAD_HDBENT_ENCODING,	"Invalid HDB entry encoding"
=20
 index 64
 prefix HEIM_PKINIT
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/init_cred=
s.c
--- a/head/crypto/heimdal/lib/krb5/init_creds.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/init_creds.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,8 +1,10 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -33,32 +35,41 @@
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: init_creds.c 21711 2007-07-27 14:22:02Z lha $");
+#undef __attribute__
+#define __attribute__(x)
=20
-void KRB5_LIB_FUNCTION
-krb5_get_init_creds_opt_init(krb5_get_init_creds_opt *opt)
-{
-    memset (opt, 0, sizeof(*opt));
-    opt->flags =3D 0;
-    opt->opt_private =3D NULL;
-}
+/**
+ * @page krb5_init_creds_intro The initial credential handing functions
+ * @section section_krb5_init_creds Initial credential
+ *
+ * Functions to get initial credentials: @ref krb5_credential .
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_init_creds_opt_alloc(krb5_context context,=20
+/**
+ * Allocate a new krb5_get_init_creds_opt structure, free with
+ * krb5_get_init_creds_opt_free().
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_alloc(krb5_context context,
 			      krb5_get_init_creds_opt **opt)
 {
     krb5_get_init_creds_opt *o;
-   =20
+
     *opt =3D NULL;
     o =3D calloc(1, sizeof(*o));
     if (o =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
-    krb5_get_init_creds_opt_init(o);
+
     o->opt_private =3D calloc(1, sizeof(*o->opt_private));
     if (o->opt_private =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	free(o);
 	return ENOMEM;
     }
@@ -67,69 +78,13 @@
     return 0;
 }
=20
-krb5_error_code
-_krb5_get_init_creds_opt_copy(krb5_context context,=20
-			      const krb5_get_init_creds_opt *in,
-			      krb5_get_init_creds_opt **out)
-{
-    krb5_get_init_creds_opt *opt;
+/**
+ * Free krb5_get_init_creds_opt structure.
+ *
+ * @ingroup krb5_credential
+ */
=20
-    *out =3D NULL;
-    opt =3D calloc(1, sizeof(*opt));
-    if (opt =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
-    }
-    if (in)
-	*opt =3D *in;
-    if(opt->opt_private =3D=3D NULL) {
-	opt->opt_private =3D calloc(1, sizeof(*opt->opt_private));
-	if (opt->opt_private =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
-	    free(opt);
-	    return ENOMEM;
-	}
-	opt->opt_private->refcount =3D 1;
-    } else
-	opt->opt_private->refcount++;
-    *out =3D opt;
-    return 0;
-}
-
-void KRB5_LIB_FUNCTION
-_krb5_get_init_creds_opt_free_krb5_error(krb5_get_init_creds_opt *opt)
-{
-    if (opt->opt_private =3D=3D NULL || opt->opt_private->error =3D=3D NUL=
L)
-	return;
-    free_KRB_ERROR(opt->opt_private->error);
-    free(opt->opt_private->error);
-    opt->opt_private->error =3D NULL;
-}
-
-void KRB5_LIB_FUNCTION
-_krb5_get_init_creds_opt_set_krb5_error(krb5_context context,
-					krb5_get_init_creds_opt *opt,=20
-					const KRB_ERROR *error)
-{
-    krb5_error_code ret;
-
-    if (opt->opt_private =3D=3D NULL)
-	return;
-
-    _krb5_get_init_creds_opt_free_krb5_error(opt);
-
-    opt->opt_private->error =3D malloc(sizeof(*opt->opt_private->error));
-    if (opt->opt_private->error =3D=3D NULL)
-	return;
-    ret =3D copy_KRB_ERROR(error, opt->opt_private->error);
-    if (ret) {
-	free(opt->opt_private->error);
-	opt->opt_private->error =3D NULL;
-    }=09
-}
-
-
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_free(krb5_context context,
 			     krb5_get_init_creds_opt *opt)
 {
@@ -138,7 +93,6 @@
     if (opt->opt_private->refcount < 1) /* abort ? */
 	return;
     if (--opt->opt_private->refcount =3D=3D 0) {
-	_krb5_get_init_creds_opt_free_krb5_error(opt);
 	_krb5_get_init_creds_opt_free_pkinit(opt);
 	free(opt->opt_private);
     }
@@ -172,20 +126,21 @@
=20
 static krb5_boolean
 get_config_bool (krb5_context context,
+		 krb5_boolean def_value,
 		 const char *realm,
 		 const char *name)
 {
-    return krb5_config_get_bool (context,
-				 NULL,
-				 "realms",
-				 realm,
-				 name,
-				 NULL)
-	|| krb5_config_get_bool (context,
-				 NULL,
-				 "libdefaults",
-				 name,
-				 NULL);
+    krb5_boolean b;
+
+    b =3D krb5_config_get_bool_default(context, NULL, def_value,
+				     "realms", realm, name, NULL);
+    if (b !=3D def_value)
+	return b;
+    b =3D krb5_config_get_bool_default (context, NULL, def_value,
+				      "libdefaults", name, NULL);
+    if (b !=3D def_value)
+	return b;
+    return def_value;
 }
=20
 /*
@@ -195,7 +150,7 @@
  * [realms] or [libdefaults] for some of the values.
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_default_flags(krb5_context context,
 					  const char *appname,
 					  krb5_const_realm realm,
@@ -204,11 +159,12 @@
     krb5_boolean b;
     time_t t;
=20
-    b =3D get_config_bool (context, realm, "forwardable");
+    b =3D get_config_bool (context, KRB5_FORWARDABLE_DEFAULT,
+			 realm, "forwardable");
     krb5_appdefault_boolean(context, appname, realm, "forwardable", b, &b);
     krb5_get_init_creds_opt_set_forwardable(opt, b);
=20
-    b =3D get_config_bool (context, realm, "proxiable");
+    b =3D get_config_bool (context, FALSE, realm, "proxiable");
     krb5_appdefault_boolean(context, appname, realm, "proxiable", b, &b);
     krb5_get_init_creds_opt_set_proxiable (opt, b);
=20
@@ -224,7 +180,7 @@
     if(t !=3D 0)
 	krb5_get_init_creds_opt_set_renew_life(opt, t);
=20
-    krb5_appdefault_boolean(context, appname, realm, "no-addresses",=20
+    krb5_appdefault_boolean(context, appname, realm, "no-addresses",
 			    KRB5_ADDRESSLESS_DEFAULT, &b);
     krb5_get_init_creds_opt_set_addressless (context, opt, b);
=20
@@ -245,7 +201,7 @@
 }
=20
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_tkt_life(krb5_get_init_creds_opt *opt,
 				     krb5_deltat tkt_life)
 {
@@ -253,7 +209,7 @@
     opt->tkt_life =3D tkt_life;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_renew_life(krb5_get_init_creds_opt *opt,
 				       krb5_deltat renew_life)
 {
@@ -261,7 +217,7 @@
     opt->renew_life =3D renew_life;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_forwardable(krb5_get_init_creds_opt *opt,
 					int forwardable)
 {
@@ -269,7 +225,7 @@
     opt->forwardable =3D forwardable;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_proxiable(krb5_get_init_creds_opt *opt,
 				      int proxiable)
 {
@@ -277,7 +233,7 @@
     opt->proxiable =3D proxiable;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_etype_list(krb5_get_init_creds_opt *opt,
 				       krb5_enctype *etype_list,
 				       int etype_list_length)
@@ -287,7 +243,7 @@
     opt->etype_list_length =3D etype_list_length;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_address_list(krb5_get_init_creds_opt *opt,
 					 krb5_addresses *addresses)
 {
@@ -295,7 +251,7 @@
     opt->address_list =3D addresses;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_preauth_list(krb5_get_init_creds_opt *opt,
 					 krb5_preauthtype *preauth_list,
 					 int preauth_list_length)
@@ -305,7 +261,7 @@
     opt->preauth_list =3D preauth_list;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_salt(krb5_get_init_creds_opt *opt,
 				 krb5_data *salt)
 {
@@ -313,7 +269,7 @@
     opt->salt =3D salt;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_anonymous(krb5_get_init_creds_opt *opt,
 				      int anonymous)
 {
@@ -327,13 +283,14 @@
 		const char *type)
 {
     if (opt->opt_private =3D=3D NULL) {
-	krb5_set_error_string(context, "%s on non extendable opt", type);
+	krb5_set_error_message(context, EINVAL,
+			       N_("%s on non extendable opt", ""), type);
 	return EINVAL;
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_pa_password(krb5_context context,
 					krb5_get_init_creds_opt *opt,
 					const char *password,
@@ -348,7 +305,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_pac_request(krb5_context context,
 					krb5_get_init_creds_opt *opt,
 					krb5_boolean req_pac)
@@ -363,36 +320,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_init_creds_opt_get_error(krb5_context context,
-				  krb5_get_init_creds_opt *opt,
-				  KRB_ERROR **error)
-{
-    krb5_error_code ret;
-
-    *error =3D NULL;
-
-    ret =3D require_ext_opt(context, opt, "init_creds_opt_get_error");
-    if (ret)
-	return ret;
-
-    if (opt->opt_private->error =3D=3D NULL)
-	return 0;
-
-    *error =3D malloc(sizeof(**error));
-    if (*error =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out memory");
-	return ENOMEM;
-    }
-
-    ret =3D copy_KRB_ERROR(opt->opt_private->error, *error);
-    if (ret)
-	krb5_clear_error_string(context);
-
-    return 0;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_addressless(krb5_context context,
 					krb5_get_init_creds_opt *opt,
 					krb5_boolean addressless)
@@ -408,7 +336,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_canonicalize(krb5_context context,
 					 krb5_get_init_creds_opt *opt,
 					 krb5_boolean req)
@@ -424,7 +352,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_win2k(krb5_context context,
 				  krb5_get_init_creds_opt *opt,
 				  krb5_boolean req)
@@ -433,10 +361,74 @@
     ret =3D require_ext_opt(context, opt, "init_creds_opt_set_win2k");
     if (ret)
 	return ret;
-    if (req)
+    if (req) {
 	opt->opt_private->flags |=3D KRB5_INIT_CREDS_NO_C_CANON_CHECK;
-    else
+	opt->opt_private->flags |=3D KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK;
+    } else {
 	opt->opt_private->flags &=3D ~KRB5_INIT_CREDS_NO_C_CANON_CHECK;
+	opt->opt_private->flags &=3D ~KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK;
+    }
     return 0;
 }
=20
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_process_last_req(krb5_context context,
+					     krb5_get_init_creds_opt *opt,
+					     krb5_gic_process_last_req func,
+					     void *ctx)
+{
+    krb5_error_code ret;
+    ret =3D require_ext_opt(context, opt, "init_creds_opt_set_win2k");
+    if (ret)
+	return ret;
+
+    opt->opt_private->lr.func =3D func;
+    opt->opt_private->lr.ctx =3D ctx;
+
+    return 0;
+}
+
+
+#ifndef HEIMDAL_SMALLER
+
+/**
+ * Deprecated: use krb5_get_init_creds_opt_alloc().
+ *
+ * The reason krb5_get_init_creds_opt_init() is deprecated is that
+ * krb5_get_init_creds_opt is a static structure and for ABI reason it
+ * can't grow, ie can't add new functionality.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_init(krb5_get_init_creds_opt *opt)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+    memset (opt, 0, sizeof(*opt));
+}
+
+/**
+ * Deprecated: use the new krb5_init_creds_init() and
+ * krb5_init_creds_get_error().
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_get_error(krb5_context context,
+				  krb5_get_init_creds_opt *opt,
+				  KRB_ERROR **error)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
+{
+    *error =3D calloc(1, sizeof(**error));
+    if (*error =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
+
+    return 0;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/init_cred=
s_pw.c
--- a/head/crypto/heimdal/lib/krb5/init_creds_pw.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/init_creds_pw.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,47 +1,47 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: init_creds_pw.c 21931 2007-08-27 14:11:55Z lha $");
-
 typedef struct krb5_get_init_creds_ctx {
     KDCOptions flags;
     krb5_creds cred;
     krb5_addresses *addrs;
     krb5_enctype *etypes;
     krb5_preauthtype *pre_auth_types;
-    const char *in_tkt_service;
+    char *in_tkt_service;
     unsigned nonce;
     unsigned pk_nonce;
=20
@@ -49,17 +49,53 @@
     AS_REQ as_req;
     int pa_counter;
=20
-    const char *password;
-    krb5_s2k_proc key_proc;
+    /* password and keytab_data is freed on completion */
+    char *password;
+    krb5_keytab_key_proc_args *keytab_data;
+
+    krb5_pointer *keyseed;
+    krb5_s2k_proc keyproc;
=20
     krb5_get_init_creds_tristate req_pac;
=20
     krb5_pk_init_ctx pk_init_ctx;
     int ic_flags;
+
+    int used_pa_types;
+#define  USED_PKINIT	1
+#define  USED_PKINIT_W2K	2
+#define  USED_ENC_TS_GUESS	4
+#define  USED_ENC_TS_INFO	8
+
+    METHOD_DATA md;
+    KRB_ERROR error;
+    AS_REP as_rep;
+    EncKDCRepPart enc_part;
+
+    krb5_prompter_fct prompter;
+    void *prompter_data;
+
+    struct pa_info_data *ppaid;
+
 } krb5_get_init_creds_ctx;
=20
-static krb5_error_code
-default_s2k_func(krb5_context context, krb5_enctype type,=20
+
+struct pa_info_data {
+    krb5_enctype etype;
+    krb5_salt salt;
+    krb5_data *s2kparams;
+};
+
+static void
+free_paid(krb5_context context, struct pa_info_data *ppaid)
+{
+    krb5_free_salt(context, ppaid->salt);
+    if (ppaid->s2kparams)
+	krb5_free_data(context, ppaid->s2kparams);
+}
+
+static krb5_error_code KRB5_CALLCONV
+default_s2k_func(krb5_context context, krb5_enctype type,
 		 krb5_const_pointer keyseed,
 		 krb5_salt salt, krb5_data *s2kparms,
 		 krb5_keyblock **key)
@@ -68,13 +104,15 @@
     krb5_data password;
     krb5_data opaque;
=20
+    _krb5_debug(context, 5, "krb5_get_init_creds: using default_s2k_func");
+
     password.data =3D rk_UNCONST(keyseed);
     password.length =3D strlen(keyseed);
     if (s2kparms)
 	opaque =3D *s2kparms;
     else
 	krb5_data_zero(&opaque);
-=09
+
     *key =3D malloc(sizeof(**key));
     if (*key =3D=3D NULL)
 	return ENOMEM;
@@ -88,14 +126,32 @@
 }
=20
 static void
-free_init_creds_ctx(krb5_context context, krb5_get_init_creds_ctx *ctx)
+free_init_creds_ctx(krb5_context context, krb5_init_creds_context ctx)
 {
     if (ctx->etypes)
 	free(ctx->etypes);
     if (ctx->pre_auth_types)
 	free (ctx->pre_auth_types);
+    if (ctx->in_tkt_service)
+	free(ctx->in_tkt_service);
+    if (ctx->keytab_data)
+	free(ctx->keytab_data);
+    if (ctx->password) {
+	memset(ctx->password, 0, strlen(ctx->password));
+	free(ctx->password);
+    }
+    krb5_data_free(&ctx->req_buffer);
+    krb5_free_cred_contents(context, &ctx->cred);
+    free_METHOD_DATA(&ctx->md);
+    free_AS_REP(&ctx->as_rep);
+    free_EncKDCRepPart(&ctx->enc_part);
+    free_KRB_ERROR(&ctx->error);
     free_AS_REQ(&ctx->as_req);
-    memset(&ctx->as_req, 0, sizeof(ctx->as_req));
+    if (ctx->ppaid) {
+	free_paid(context, ctx->ppaid);
+	free(ctx->ppaid);
+    }
+    memset(ctx, 0, sizeof(*ctx));
 }
=20
 static int
@@ -127,18 +183,16 @@
 	   krb5_creds *cred,
 	   krb5_principal client,
 	   krb5_deltat start_time,
-	   const char *in_tkt_service,
 	   krb5_get_init_creds_opt *options)
 {
     krb5_error_code ret;
-    krb5_const_realm client_realm;
     int tmp;
     krb5_timestamp now;
=20
     krb5_timeofday (context, &now);
=20
     memset (cred, 0, sizeof(*cred));
-   =20
+
     if (client)
 	krb5_copy_principal(context, client, &cred->client);
     else {
@@ -148,8 +202,6 @@
 	    goto out;
     }
=20
-    client_realm =3D krb5_principal_get_realm (context, cred->client);
-
     if (start_time)
 	cred->times.starttime  =3D now + start_time;
=20
@@ -164,22 +216,6 @@
 	cred->times.renew_till =3D now + options->renew_life;
     }
=20
-    if (in_tkt_service) {
-	krb5_realm server_realm;
-
-	ret =3D krb5_parse_name (context, in_tkt_service, &cred->server);
-	if (ret)
-	    goto out;
-	server_realm =3D strdup (client_realm);
-	free (*krb5_princ_realm(context, cred->server));
-	krb5_princ_set_realm (context, cred->server, &server_realm);
-    } else {
-	ret =3D krb5_make_principal(context, &cred->server,=20
-				  client_realm, KRB5_TGS_NAME, client_realm,
-				  NULL);
-	if (ret)
-	    goto out;
-    }
     return 0;
=20
 out:
@@ -198,29 +234,73 @@
 		   const char *str,
 		   time_t now)
 {
-    char *p;
-	   =20
-    asprintf (&p, "%s%s", str, ctime(&now));
-    (*prompter) (context, data, NULL, p, 0, NULL);
-    free (p);
+    char *p =3D NULL;
+
+    if (asprintf(&p, "%s%s", str, ctime(&now)) < 0 || p =3D=3D NULL)
+	return;
+    (*prompter)(context, data, NULL, p, 0, NULL);
+    free(p);
 }
=20
 /*
- * Parse the last_req data and show it to the user if it's interesting
+ * Check the context, and in the case there is a expiration warning,
+ * use the prompter to print the warning.
+ *
+ * @param context A Kerberos 5 context.
+ * @param options An GIC options structure
+ * @param ctx The krb5_init_creds_context check for expiration.
  */
=20
-static void
-print_expire (krb5_context context,
-	      krb5_const_realm realm,
-	      krb5_kdc_rep *rep,
-	      krb5_prompter_fct prompter,
-	      krb5_data *data)
+static krb5_error_code
+process_last_request(krb5_context context,
+		     krb5_get_init_creds_opt *options,
+		     krb5_init_creds_context ctx)
 {
-    int i;
-    LastReq *lr =3D &rep->enc_part.last_req;
+    krb5_const_realm realm;
+    LastReq *lr;
+    krb5_boolean reported =3D FALSE;
     krb5_timestamp sec;
     time_t t;
-    krb5_boolean reported =3D FALSE;
+    size_t i;
+
+    /*
+     * First check if there is a API consumer.
+     */
+
+    realm =3D krb5_principal_get_realm (context, ctx->cred.client);
+    lr =3D &ctx->enc_part.last_req;
+
+    if (options && options->opt_private && options->opt_private->lr.func) {
+	krb5_last_req_entry **lre;
+
+	lre =3D calloc(lr->len + 1, sizeof(**lre));
+	if (lre =3D=3D NULL) {
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
+	    return ENOMEM;
+	}
+	for (i =3D 0; i < lr->len; i++) {
+	    lre[i] =3D calloc(1, sizeof(*lre[i]));
+	    if (lre[i] =3D=3D NULL)
+		break;
+	    lre[i]->lr_type =3D lr->val[i].lr_type;
+	    lre[i]->value =3D lr->val[i].lr_value;
+	}
+
+	(*options->opt_private->lr.func)(context, lre,
+					 options->opt_private->lr.ctx);
+
+	for (i =3D 0; i < lr->len; i++)
+	    free(lre[i]);
+	free(lre);
+    }
+
+    /*
+     * Now check if we should prompt the user
+     */
+
+    if (ctx->prompter =3D=3D NULL)
+        return 0;
=20
     krb5_timeofday (context, &sec);
=20
@@ -233,13 +313,15 @@
 	if (lr->val[i].lr_value <=3D t) {
 	    switch (abs(lr->val[i].lr_type)) {
 	    case LR_PW_EXPTIME :
-		report_expiration(context, prompter, data,
+		report_expiration(context, ctx->prompter,
+				  ctx->prompter_data,
 				  "Your password will expire at ",
 				  lr->val[i].lr_value);
 		reported =3D TRUE;
 		break;
 	    case LR_ACCT_EXPTIME :
-		report_expiration(context, prompter, data,
+		report_expiration(context, ctx->prompter,
+				  ctx->prompter_data,
 				  "Your account will expire at ",
 				  lr->val[i].lr_value);
 		reported =3D TRUE;
@@ -249,12 +331,14 @@
     }
=20
     if (!reported
-	&& rep->enc_part.key_expiration
-	&& *rep->enc_part.key_expiration <=3D t) {
-	report_expiration(context, prompter, data,
+	&& ctx->enc_part.key_expiration
+	&& *ctx->enc_part.key_expiration <=3D t) {
+        report_expiration(context, ctx->prompter,
+			  ctx->prompter_data,
 			  "Your password/account will expire at ",
-			  *rep->enc_part.key_expiration);
+			  *ctx->enc_part.key_expiration);
     }
+    return 0;
 }
=20
 static krb5_addresses no_addrs =3D { 0, NULL };
@@ -263,11 +347,10 @@
 get_init_creds_common(krb5_context context,
 		      krb5_principal client,
 		      krb5_deltat start_time,
-		      const char *in_tkt_service,
 		      krb5_get_init_creds_opt *options,
-		      krb5_get_init_creds_ctx *ctx)
+		      krb5_init_creds_context ctx)
 {
-    krb5_get_init_creds_opt default_opt;
+    krb5_get_init_creds_opt *default_opt =3D NULL;
     krb5_error_code ret;
     krb5_enctype *etypes;
     krb5_preauthtype *pre_auth_types;
@@ -275,37 +358,51 @@
     memset(ctx, 0, sizeof(*ctx));
=20
     if (options =3D=3D NULL) {
-	krb5_get_init_creds_opt_init (&default_opt);
-	options =3D &default_opt;
-    } else {
-	_krb5_get_init_creds_opt_free_krb5_error(options);
+	const char *realm =3D krb5_principal_get_realm(context, client);
+
+        krb5_get_init_creds_opt_alloc (context, &default_opt);
+	options =3D default_opt;
+	krb5_get_init_creds_opt_set_default_flags(context, NULL, realm, options);
     }
=20
     if (options->opt_private) {
-	ctx->password =3D options->opt_private->password;
-	ctx->key_proc =3D options->opt_private->key_proc;
+	if (options->opt_private->password) {
+	    ret =3D krb5_init_creds_set_password(context, ctx,
+					       options->opt_private->password);
+	    if (ret)
+		goto out;
+	}
+
+	ctx->keyproc =3D options->opt_private->key_proc;
 	ctx->req_pac =3D options->opt_private->req_pac;
 	ctx->pk_init_ctx =3D options->opt_private->pk_init_ctx;
 	ctx->ic_flags =3D options->opt_private->flags;
     } else
 	ctx->req_pac =3D KRB5_INIT_CREDS_TRISTATE_UNSET;
=20
-    if (ctx->key_proc =3D=3D NULL)
-	ctx->key_proc =3D default_s2k_func;
+    if (ctx->keyproc =3D=3D NULL)
+	ctx->keyproc =3D default_s2k_func;
=20
-    if (ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE)
+    /* Enterprise name implicitly turns on canonicalize */
+    if ((ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE) ||
+	krb5_principal_get_type(context, client) =3D=3D KRB5_NT_ENTERPRISE_PRINCI=
PAL)
 	ctx->flags.canonicalize =3D 1;
=20
     ctx->pre_auth_types =3D NULL;
     ctx->addrs =3D NULL;
     ctx->etypes =3D NULL;
     ctx->pre_auth_types =3D NULL;
-    ctx->in_tkt_service =3D in_tkt_service;
=20
-    ret =3D init_cred (context, &ctx->cred, client, start_time,
-		     in_tkt_service, options);
+    ret =3D init_cred(context, &ctx->cred, client, start_time, options);
+    if (ret) {
+	if (default_opt)
+	    krb5_get_init_creds_opt_free(context, default_opt);
+	return ret;
+    }
+
+    ret =3D krb5_init_creds_set_service(context, ctx, NULL);
     if (ret)
-	return ret;
+	goto out;
=20
     if (options->flags & KRB5_GET_INIT_CREDS_OPT_FORWARDABLE)
 	ctx->flags.forwardable =3D options->forwardable;
@@ -337,11 +434,15 @@
 	}
     }
     if (options->flags & KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST) {
+	if (ctx->etypes)
+	    free(ctx->etypes);
+
 	etypes =3D malloc((options->etype_list_length + 1)
 			* sizeof(krb5_enctype));
 	if (etypes =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
-	    return ENOMEM;
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
 	}
 	memcpy (etypes, options->etype_list,
 		options->etype_list_length * sizeof(krb5_enctype));
@@ -352,19 +453,24 @@
 	pre_auth_types =3D malloc((options->preauth_list_length + 1)
 				* sizeof(krb5_preauthtype));
 	if (pre_auth_types =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
-	    return ENOMEM;
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
 	}
 	memcpy (pre_auth_types, options->preauth_list,
 		options->preauth_list_length * sizeof(krb5_preauthtype));
 	pre_auth_types[options->preauth_list_length] =3D KRB5_PADATA_NONE;
 	ctx->pre_auth_types =3D pre_auth_types;
     }
-    if (options->flags & KRB5_GET_INIT_CREDS_OPT_SALT)
-	;			/* XXX */
     if (options->flags & KRB5_GET_INIT_CREDS_OPT_ANONYMOUS)
 	ctx->flags.request_anonymous =3D options->anonymous;
+    if (default_opt)
+        krb5_get_init_creds_opt_free(context, default_opt);
     return 0;
+ out:
+    if (default_opt)
+	krb5_get_init_creds_opt_free(context, default_opt);
+    return ret;
 }
=20
 static krb5_error_code
@@ -386,18 +492,20 @@
     krb5_data result_code_string;
     krb5_data result_string;
     char *p;
-    krb5_get_init_creds_opt options;
+    krb5_get_init_creds_opt *options;
=20
     memset (&cpw_cred, 0, sizeof(cpw_cred));
=20
-    krb5_get_init_creds_opt_init (&options);
-    krb5_get_init_creds_opt_set_tkt_life (&options, 60);
-    krb5_get_init_creds_opt_set_forwardable (&options, FALSE);
-    krb5_get_init_creds_opt_set_proxiable (&options, FALSE);
+    ret =3D krb5_get_init_creds_opt_alloc(context, &options);
+    if (ret)
+        return ret;
+    krb5_get_init_creds_opt_set_tkt_life (options, 60);
+    krb5_get_init_creds_opt_set_forwardable (options, FALSE);
+    krb5_get_init_creds_opt_set_proxiable (options, FALSE);
     if (old_options && old_options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUT=
H_LIST)
-	krb5_get_init_creds_opt_set_preauth_list (&options,
+	krb5_get_init_creds_opt_set_preauth_list (options,
 						  old_options->preauth_list,
-						  old_options->preauth_list_length);					     =20
+						  old_options->preauth_list_length);
=20
     krb5_data_zero (&result_code_string);
     krb5_data_zero (&result_string);
@@ -410,7 +518,8 @@
 					data,
 					0,
 					"kadmin/changepw",
-					&options);
+					options);
+    krb5_get_init_creds_opt_free(context, options);
     if (ret)
 	goto out;
=20
@@ -444,28 +553,36 @@
 	memset (buf1, 0, sizeof(buf1));
 	memset (buf2, 0, sizeof(buf2));
     }
-   =20
-    ret =3D krb5_change_password (context,
-				&cpw_cred,
-				buf1,
-				&result_code,
-				&result_code_string,
-				&result_string);
+
+    ret =3D krb5_set_password (context,
+			     &cpw_cred,
+			     buf1,
+			     client,
+			     &result_code,
+			     &result_code_string,
+			     &result_string);
     if (ret)
 	goto out;
-    asprintf (&p, "%s: %.*s\n",
-	      result_code ? "Error" : "Success",
-	      (int)result_string.length,
-	      result_string.length > 0 ? (char*)result_string.data : "");
+    if (asprintf(&p, "%s: %.*s\n",
+		 result_code ? "Error" : "Success",
+		 (int)result_string.length,
+		 result_string.length > 0 ? (char*)result_string.data : "") < 0)
+    {
+	ret =3D ENOMEM;
+	goto out;
+    }
=20
-    ret =3D (*prompter) (context, data, NULL, p, 0, NULL);
+    /* return the result */
+    (*prompter) (context, data, NULL, p, 0, NULL);
+
     free (p);
     if (result_code =3D=3D 0) {
 	strlcpy (newpw, buf1, newpw_sz);
 	ret =3D 0;
     } else {
-	krb5_set_error_string (context, "failed changing password");
 	ret =3D ENOTTY;
+	krb5_set_error_message(context, ret,
+			       N_("failed changing password", ""));
     }
=20
 out:
@@ -477,7 +594,8 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_keyblock_key_proc (krb5_context context,
 			krb5_keytype type,
 			krb5_data *salt,
@@ -487,68 +605,17 @@
     return krb5_copy_keyblock (context, keyseed, key);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_init_creds_keytab(krb5_context context,
-			   krb5_creds *creds,
-			   krb5_principal client,
-			   krb5_keytab keytab,
-			   krb5_deltat start_time,
-			   const char *in_tkt_service,
-			   krb5_get_init_creds_opt *options)
-{
-    krb5_get_init_creds_ctx ctx;
-    krb5_error_code ret;
-    krb5_keytab_key_proc_args *a;
-   =20
-    ret =3D get_init_creds_common(context, client, start_time,
-				in_tkt_service, options, &ctx);
-    if (ret)
-	goto out;
-
-    a =3D malloc (sizeof(*a));
-    if (a =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	ret =3D ENOMEM;
-	goto out;
-    }
-    a->principal =3D ctx.cred.client;
-    a->keytab    =3D keytab;
-
-    ret =3D krb5_get_in_cred (context,
-			    KDCOptions2int(ctx.flags),
-			    ctx.addrs,
-			    ctx.etypes,
-			    ctx.pre_auth_types,
-			    NULL,
-			    krb5_keytab_key_proc,
-			    a,
-			    NULL,
-			    NULL,
-			    &ctx.cred,
-			    NULL);
-    free (a);
-
-    if (ret =3D=3D 0 && creds)
-	*creds =3D ctx.cred;
-    else
-	krb5_free_cred_contents (context, &ctx.cred);
-
- out:
-    free_init_creds_ctx(context, &ctx);
-    return ret;
-}
-
 /*
  *
  */
=20
 static krb5_error_code
-init_creds_init_as_req (krb5_context context,
-			KDCOptions opts,
-			const krb5_creds *creds,
-			const krb5_addresses *addrs,
-			const krb5_enctype *etypes,
-			AS_REQ *a)
+init_as_req (krb5_context context,
+	     KDCOptions opts,
+	     const krb5_creds *creds,
+	     const krb5_addresses *addrs,
+	     const krb5_enctype *etypes,
+	     AS_REQ *a)
 {
     krb5_error_code ret;
=20
@@ -560,13 +627,13 @@
     a->req_body.cname =3D malloc(sizeof(*a->req_body.cname));
     if (a->req_body.cname =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
     a->req_body.sname =3D malloc(sizeof(*a->req_body.sname));
     if (a->req_body.sname =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto fail;
     }
=20
@@ -585,7 +652,7 @@
 	a->req_body.from =3D malloc(sizeof(*a->req_body.from));
 	if (a->req_body.from =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	*a->req_body.from =3D creds->times.starttime;
@@ -598,13 +665,14 @@
 	a->req_body.rtime =3D malloc(sizeof(*a->req_body.rtime));
 	if (a->req_body.rtime =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
 	*a->req_body.rtime =3D creds->times.renew_till;
     }
     a->req_body.nonce =3D 0;
-    ret =3D krb5_init_etype (context,
+    ret =3D _krb5_init_etype(context,
+			   KRB5_PDU_AS_REQUEST,
 			   &a->req_body.etype.len,
 			   &a->req_body.etype.val,
 			   etypes);
@@ -621,7 +689,7 @@
 	a->req_body.addresses =3D malloc(sizeof(*a->req_body.addresses));
 	if (a->req_body.addresses =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    goto fail;
 	}
=20
@@ -650,20 +718,6 @@
     return ret;
 }
=20
-struct pa_info_data {
-    krb5_enctype etype;
-    krb5_salt salt;
-    krb5_data *s2kparams;
-};
-
-static void
-free_paid(krb5_context context, struct pa_info_data *ppaid)
-{
-    krb5_free_salt(context, ppaid->salt);
-    if (ppaid->s2kparams)
-	krb5_free_data(context, ppaid->s2kparams);
-}
-
=20
 static krb5_error_code
 set_paid(struct pa_info_data *paid, krb5_context context,
@@ -675,7 +729,7 @@
     paid->salt.salttype =3D salttype;
     paid->salt.saltvalue.data =3D malloc(salt_len + 1);
     if (paid->salt.saltvalue.data =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ENOMEM;
     }
     memcpy(paid->salt.saltvalue.data, salt_string, salt_len);
@@ -686,7 +740,7 @@
=20
 	ret =3D krb5_copy_data(context, s2kparams, &paid->s2kparams);
 	if (ret) {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    krb5_free_salt(context, paid->salt);
 	    return ret;
 	}
@@ -698,15 +752,15 @@
=20
 static struct pa_info_data *
 pa_etype_info2(krb5_context context,
-	       const krb5_principal client,=20
+	       const krb5_principal client,
 	       const AS_REQ *asreq,
-	       struct pa_info_data *paid,=20
+	       struct pa_info_data *paid,
 	       heim_octet_string *data)
 {
     krb5_error_code ret;
     ETYPE_INFO2 e;
     size_t sz;
-    int i, j;
+    size_t i, j;
=20
     memset(&e, 0, sizeof(e));
     ret =3D decode_ETYPE_INFO2(data->data, data->length, &e, &sz);
@@ -728,7 +782,7 @@
 		if (ret =3D=3D 0)
 		    ret =3D set_paid(paid, context, e.val[i].etype,
 				   KRB5_PW_SALT,
-				   salt.saltvalue.data,=20
+				   salt.saltvalue.data,
 				   salt.saltvalue.length,
 				   e.val[i].s2kparams);
 		if (e.val[i].salt =3D=3D NULL)
@@ -747,7 +801,7 @@
=20
 static struct pa_info_data *
 pa_etype_info(krb5_context context,
-	      const krb5_principal client,=20
+	      const krb5_principal client,
 	      const AS_REQ *asreq,
 	      struct pa_info_data *paid,
 	      heim_octet_string *data)
@@ -755,7 +809,7 @@
     krb5_error_code ret;
     ETYPE_INFO e;
     size_t sz;
-    int i, j;
+    size_t i, j;
=20
     memset(&e, 0, sizeof(e));
     ret =3D decode_ETYPE_INFO(data->data, data->length, &e, &sz);
@@ -779,7 +833,7 @@
 		if (ret =3D=3D 0) {
 		    ret =3D set_paid(paid, context, e.val[i].etype,
 				   salt.salttype,
-				   salt.saltvalue.data,=20
+				   salt.saltvalue.data,
 				   salt.saltvalue.length,
 				   NULL);
 		    if (e.val[i].salt =3D=3D NULL)
@@ -799,7 +853,7 @@
=20
 static struct pa_info_data *
 pa_pw_or_afs3_salt(krb5_context context,
-		   const krb5_principal client,=20
+		   const krb5_principal client,
 		   const AS_REQ *asreq,
 		   struct pa_info_data *paid,
 		   heim_octet_string *data)
@@ -807,10 +861,10 @@
     krb5_error_code ret;
     if (paid->etype =3D=3D ENCTYPE_NULL)
 	return NULL;
-    ret =3D set_paid(paid, context,=20
+    ret =3D set_paid(paid, context,
 		   paid->etype,
 		   paid->salt.salttype,
-		   data->data,=20
+		   data->data,
 		   data->length,
 		   NULL);
     if (ret)
@@ -822,9 +876,9 @@
 struct pa_info {
     krb5_preauthtype type;
     struct pa_info_data *(*salt_info)(krb5_context,
-				      const krb5_principal,=20
+				      const krb5_principal,
 				      const AS_REQ *,
-				      struct pa_info_data *,=20
+				      struct pa_info_data *,
 				      heim_octet_string *);
 };
=20
@@ -834,11 +888,11 @@
     { KRB5_PADATA_PW_SALT, pa_pw_or_afs3_salt },
     { KRB5_PADATA_AFS3_SALT, pa_pw_or_afs3_salt }
 };
-   =20
+
 static PA_DATA *
-find_pa_data(const METHOD_DATA *md, int type)
+find_pa_data(const METHOD_DATA *md, unsigned type)
 {
-    int i;
+    size_t i;
     if (md =3D=3D NULL)
 	return NULL;
     for (i =3D 0; i < md->len; i++)
@@ -848,20 +902,20 @@
 }
=20
 static struct pa_info_data *
-process_pa_info(krb5_context context,=20
-		const krb5_principal client,=20
+process_pa_info(krb5_context context,
+		const krb5_principal client,
 		const AS_REQ *asreq,
 		struct pa_info_data *paid,
 		METHOD_DATA *md)
 {
     struct pa_info_data *p =3D NULL;
-    int i;
+    size_t i;
=20
     for (i =3D 0; p =3D=3D NULL && i < sizeof(pa_prefs)/sizeof(pa_prefs[0]=
); i++) {
 	PA_DATA *pa =3D find_pa_data(md, pa_prefs[i].type);
 	if (pa =3D=3D NULL)
 	    continue;
-	paid->salt.salttype =3D pa_prefs[i].type;
+	paid->salt.salttype =3D (krb5_salttype)pa_prefs[i].type;
 	p =3D (*pa_prefs[i].salt_info)(context, client, asreq,
 				     paid, &pa->padata_value);
     }
@@ -869,19 +923,19 @@
 }
=20
 static krb5_error_code
-make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md,=20
+make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md,
 		      krb5_enctype etype, krb5_keyblock *key)
 {
     PA_ENC_TS_ENC p;
     unsigned char *buf;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     EncryptedData encdata;
     krb5_error_code ret;
     int32_t usec;
     int usec2;
     krb5_crypto crypto;
-   =20
+
     krb5_us_timeofday (context, &p.patimestamp, &usec);
     usec2         =3D usec;
     p.pausec      =3D &usec2;
@@ -897,7 +951,7 @@
 	free(buf);
 	return ret;
     }
-    ret =3D krb5_encrypt_EncryptedData(context,=20
+    ret =3D krb5_encrypt_EncryptedData(context,
 				     crypto,
 				     KRB5_KU_PA_ENC_TIMESTAMP,
 				     buf,
@@ -908,7 +962,7 @@
     krb5_crypto_destroy(context, crypto);
     if (ret)
 	return ret;
-		   =20
+
     ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret);
     free_EncryptedData(&encdata);
     if (ret)
@@ -924,9 +978,9 @@
=20
 static krb5_error_code
 add_enc_ts_padata(krb5_context context,
-		  METHOD_DATA *md,=20
+		  METHOD_DATA *md,
 		  krb5_principal client,
-		  krb5_s2k_proc key_proc,
+		  krb5_s2k_proc keyproc,
 		  krb5_const_pointer keyseed,
 		  krb5_enctype *enctypes,
 		  unsigned netypes,
@@ -936,11 +990,13 @@
     krb5_error_code ret;
     krb5_salt salt2;
     krb5_enctype *ep;
-    int i;
-   =20
+    size_t i;
+
     if(salt =3D=3D NULL) {
 	/* default to standard salt */
 	ret =3D krb5_get_pw_salt (context, client, &salt2);
+	if (ret)
+	    return ret;
 	salt =3D &salt2;
     }
     if (!enctypes) {
@@ -953,8 +1009,10 @@
     for (i =3D 0; i < netypes; ++i) {
 	krb5_keyblock *key;
=20
-	ret =3D (*key_proc)(context, enctypes[i], keyseed,
-			  *salt, s2kparams, &key);
+	_krb5_debug(context, 5, "krb5_get_init_creds: using ENC-TS with enctype %=
d", enctypes[i]);
+
+	ret =3D (*keyproc)(context, enctypes[i], keyseed,
+			 *salt, s2kparams, &key);
 	if (ret)
 	    continue;
 	ret =3D make_pa_enc_timestamp (context, md, enctypes[i], key);
@@ -975,29 +1033,31 @@
 		     struct pa_info_data *ppaid,
 		     METHOD_DATA *md)
 {
-    if (ctx->key_proc =3D=3D NULL || ctx->password =3D=3D NULL)
+    if (ctx->keyproc =3D=3D NULL || ctx->keyseed =3D=3D NULL)
 	return 0;
=20
     if (ppaid) {
-	add_enc_ts_padata(context, md, client,=20
-			  ctx->key_proc, ctx->password,
+	add_enc_ts_padata(context, md, client,
+			  ctx->keyproc, ctx->keyseed,
 			  &ppaid->etype, 1,
 			  &ppaid->salt, ppaid->s2kparams);
     } else {
 	krb5_salt salt;
-=09
+
+	_krb5_debug(context, 5, "krb5_get_init_creds: pa-info not found, guessing=
 salt");
+
 	/* make a v5 salted pa-data */
-	add_enc_ts_padata(context, md, client,=20
-			  ctx->key_proc, ctx->password,
-			  a->req_body.etype.val, a->req_body.etype.len,=20
+	add_enc_ts_padata(context, md, client,
+			  ctx->keyproc, ctx->keyseed,
+			  a->req_body.etype.val, a->req_body.etype.len,
 			  NULL, NULL);
-=09
+
 	/* make a v4 salted pa-data */
 	salt.salttype =3D KRB5_PW_SALT;
 	krb5_data_zero(&salt.saltvalue);
-	add_enc_ts_padata(context, md, client,=20
-			  ctx->key_proc, ctx->password,=20
-			  a->req_body.etype.val, a->req_body.etype.len,=20
+	add_enc_ts_padata(context, md, client,
+			  ctx->keyproc, ctx->keyseed,
+			  a->req_body.etype.val, a->req_body.etype.len,
 			  &salt, NULL);
     }
     return 0;
@@ -1014,7 +1074,7 @@
 {
     krb5_error_code ret;
=20
-    ret =3D (*ctx->key_proc)(context, etype, ctx->password,
+    ret =3D (*ctx->keyproc)(context, etype, ctx->keyseed,
 			   salt, s2kparams, key);
     return ret;
 }
@@ -1024,6 +1084,7 @@
 pa_data_to_md_pkinit(krb5_context context,
 		     const AS_REQ *a,
 		     const krb5_principal client,
+		     int win2k,
 		     krb5_get_init_creds_ctx *ctx,
 		     METHOD_DATA *md)
 {
@@ -1031,12 +1092,15 @@
 	return 0;
 #ifdef PKINIT
     return _krb5_pk_mk_padata(context,
-			     ctx->pk_init_ctx,
-			     &a->req_body,
-			     ctx->pk_nonce,
-			     md);
+			      ctx->pk_init_ctx,
+			      ctx->ic_flags,
+			      win2k,
+			      &a->req_body,
+			      ctx->pk_nonce,
+			      md);
 #else
-    krb5_set_error_string(context, "no support for PKINIT compiled in");
+    krb5_set_error_message(context, EINVAL,
+			   N_("no support for PKINIT compiled in", ""));
     return EINVAL;
 #endif
 }
@@ -1046,11 +1110,11 @@
 			krb5_get_init_creds_ctx *ctx,
 			METHOD_DATA *md)
 {
-    size_t len, length;
+    size_t len =3D 0, length;
     krb5_error_code ret;
     PA_PAC_REQUEST req;
     void *buf;
-   =20
+
     switch (ctx->req_pac) {
     case KRB5_INIT_CREDS_TRISTATE_UNSET:
 	return 0; /* don't bother */
@@ -1059,9 +1123,9 @@
 	break;
     case KRB5_INIT_CREDS_TRISTATE_FALSE:
 	req.include_pac =3D 0;
-    }=09
+    }
=20
-    ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length,=20
+    ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length,
 		       &req, &len, ret);
     if (ret)
 	return ret;
@@ -1093,12 +1157,19 @@
=20
     ALLOC(*out_md, 1);
     if (*out_md =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     (*out_md)->len =3D 0;
     (*out_md)->val =3D NULL;
-   =20
+
+    if (_krb5_have_debug(context, 5)) {
+	unsigned i;
+	_krb5_debug(context, 5, "KDC send %d patypes", in_md->len);
+	for (i =3D 0; i < in_md->len; i++)
+	    _krb5_debug(context, 5, "KDC send PA-DATA type: %d", in_md->val[i].pa=
data_type);
+    }
+
     /*
      * Make sure we don't sent both ENC-TS and PK-INIT pa data, no
      * need to expose our password protecting our PKCS12 key.
@@ -1106,21 +1177,62 @@
=20
     if (ctx->pk_init_ctx) {
=20
-	ret =3D pa_data_to_md_pkinit(context, a, creds->client, ctx, *out_md);
+ 	_krb5_debug(context, 5, "krb5_get_init_creds: "
+		    "prepareing PKINIT padata (%s)",
+ 		    (ctx->used_pa_types & USED_PKINIT_W2K) ? "win2k" : "ietf");
+
+ 	if (ctx->used_pa_types & USED_PKINIT_W2K) {
+ 	    krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+ 				   "Already tried pkinit, looping");
+ 	    return KRB5_GET_IN_TKT_LOOP;
+ 	}
+
+	ret =3D pa_data_to_md_pkinit(context, a, creds->client,
+				   (ctx->used_pa_types & USED_PKINIT),
+				   ctx, *out_md);
 	if (ret)
 	    return ret;
=20
+	if (ctx->used_pa_types & USED_PKINIT)
+	    ctx->used_pa_types |=3D USED_PKINIT_W2K;
+ 	else
+ 	    ctx->used_pa_types |=3D USED_PKINIT;
+
     } else if (in_md->len !=3D 0) {
-	struct pa_info_data paid, *ppaid;
-=09
-	memset(&paid, 0, sizeof(paid));
-=09
-	paid.etype =3D ENCTYPE_NULL;
-	ppaid =3D process_pa_info(context, creds->client, a, &paid, in_md);
-=09
+	struct pa_info_data *paid, *ppaid;
+ 	unsigned flag;
+
+	paid =3D calloc(1, sizeof(*paid));
+
+	paid->etype =3D ENCTYPE_NULL;
+	ppaid =3D process_pa_info(context, creds->client, a, paid, in_md);
+
+ 	if (ppaid)
+ 	    flag =3D USED_ENC_TS_INFO;
+ 	else
+ 	    flag =3D USED_ENC_TS_GUESS;
+
+ 	if (ctx->used_pa_types & flag) {
+ 	    if (ppaid)
+ 		free_paid(context, ppaid);
+ 	    krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+ 				   "Already tried ENC-TS-%s, looping",
+ 				   flag =3D=3D USED_ENC_TS_INFO ? "info" : "guess");
+ 	    return KRB5_GET_IN_TKT_LOOP;
+ 	}
+
 	pa_data_to_md_ts_enc(context, a, creds->client, ctx, ppaid, *out_md);
-	if (ppaid)
-	    free_paid(context, ppaid);
+
+	ctx->used_pa_types |=3D flag;
+
+	if (ppaid) {
+	    if (ctx->ppaid) {
+		free_paid(context, ctx->ppaid);
+		free(ctx->ppaid);
+	    }
+	    ctx->ppaid =3D ppaid;
+	} else
+	    free(paid);
     }
=20
     pa_data_add_pac_request(context, ctx, *out_md);
@@ -1138,7 +1250,7 @@
 		       krb5_get_init_creds_ctx *ctx,
 		       krb5_creds *creds,
 		       AS_REQ *a,
-		       krb5_kdc_rep *rep,
+		       AS_REP *rep,
 		       const krb5_krbhst_info *hi,
 		       krb5_keyblock **key)
 {
@@ -1149,38 +1261,43 @@
=20
     memset(&paid, 0, sizeof(paid));
=20
-    etype =3D rep->kdc_rep.enc_part.etype;
+    etype =3D rep->enc_part.etype;
=20
-    if (rep->kdc_rep.padata) {
+    if (rep->padata) {
 	paid.etype =3D etype;
-	ppaid =3D process_pa_info(context, creds->client, a, &paid,=20
-				rep->kdc_rep.padata);
+	ppaid =3D process_pa_info(context, creds->client, a, &paid,
+				rep->padata);
     }
+    if (ppaid =3D=3D NULL)
+	ppaid =3D ctx->ppaid;
     if (ppaid =3D=3D NULL) {
 	ret =3D krb5_get_pw_salt (context, creds->client, &paid.salt);
 	if (ret)
 	    return ret;
 	paid.etype =3D etype;
 	paid.s2kparams =3D NULL;
+	ppaid =3D &paid;
     }
=20
     pa =3D NULL;
-    if (rep->kdc_rep.padata) {
+    if (rep->padata) {
 	int idx =3D 0;
-	pa =3D krb5_find_padata(rep->kdc_rep.padata->val,=20
-			      rep->kdc_rep.padata->len,
+	pa =3D krb5_find_padata(rep->padata->val,
+			      rep->padata->len,
 			      KRB5_PADATA_PK_AS_REP,
 			      &idx);
 	if (pa =3D=3D NULL) {
 	    idx =3D 0;
-	    pa =3D krb5_find_padata(rep->kdc_rep.padata->val,=20
-				  rep->kdc_rep.padata->len,
+	    pa =3D krb5_find_padata(rep->padata->val,
+				  rep->padata->len,
 				  KRB5_PADATA_PK_AS_REP_19,
 				  &idx);
 	}
     }
     if (pa && ctx->pk_init_ctx) {
 #ifdef PKINIT
+	_krb5_debug(context, 5, "krb5_get_init_creds: using PKINIT");
+
 	ret =3D _krb5_pk_rd_pa_reply(context,
 				   a->req_body.realm,
 				   ctx->pk_init_ctx,
@@ -1191,124 +1308,442 @@
 				   pa,
 				   key);
 #else
-	krb5_set_error_string(context, "no support for PKINIT compiled in");
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret, N_("no support for PKINIT compiled i=
n", ""));
 #endif
-    } else if (ctx->password)
-	ret =3D pa_data_to_key_plain(context, creds->client, ctx,=20
-				   paid.salt, paid.s2kparams, etype, key);
-    else {
-	krb5_set_error_string(context, "No usable pa data type");
+    } else if (ctx->keyseed) {
+ 	_krb5_debug(context, 5, "krb5_get_init_creds: using keyproc");
+	ret =3D pa_data_to_key_plain(context, creds->client, ctx,
+				   ppaid->salt, ppaid->s2kparams, etype, key);
+    } else {
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret, N_("No usable pa data type", ""));
     }
=20
     free_paid(context, &paid);
     return ret;
 }
=20
-static krb5_error_code
-init_cred_loop(krb5_context context,
-	       krb5_get_init_creds_opt *init_cred_opts,
-	       const krb5_prompter_fct prompter,
-	       void *prompter_data,
-	       krb5_get_init_creds_ctx *ctx,
-	       krb5_creds *creds,
-	       krb5_kdc_rep *ret_as_reply)
+/**
+ * Start a new context to get a new initial credential.
+ *
+ * @param context A Kerberos 5 context.
+ * @param client The Kerberos principal to get the credential for, if
+ *     NULL is given, the default principal is used as determined by
+ *     krb5_get_default_principal().
+ * @param prompter
+ * @param prompter_data
+ * @param start_time the time the ticket should start to be valid or 0 for=
 now.
+ * @param options a options structure, can be NULL for default options.
+ * @param rctx A new allocated free with krb5_init_creds_free().
+ *
+ * @return 0 for success or an Kerberos 5 error code, see krb5_get_error_m=
essage().
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_init(krb5_context context,
+		     krb5_principal client,
+		     krb5_prompter_fct prompter,
+		     void *prompter_data,
+		     krb5_deltat start_time,
+		     krb5_get_init_creds_opt *options,
+		     krb5_init_creds_context *rctx)
 {
+    krb5_init_creds_context ctx;
     krb5_error_code ret;
-    krb5_kdc_rep rep;
-    METHOD_DATA md;
-    krb5_data resp;
-    size_t len;
-    size_t size;
-    krb5_krbhst_info *hi =3D NULL;
-    krb5_sendto_ctx stctx =3D NULL;
=20
+    *rctx =3D NULL;
=20
-    memset(&md, 0, sizeof(md));
-    memset(&rep, 0, sizeof(rep));
+    ctx =3D calloc(1, sizeof(*ctx));
+    if (ctx =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
=20
-    _krb5_get_init_creds_opt_free_krb5_error(init_cred_opts);
+    ret =3D get_init_creds_common(context, client, start_time, options, ct=
x);
+    if (ret) {
+	free(ctx);
+	return ret;
+    }
=20
-    if (ret_as_reply)
-	memset(ret_as_reply, 0, sizeof(*ret_as_reply));
+    /* Set a new nonce. */
+    krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce));
+    ctx->nonce &=3D 0x7fffffff;
+    /* XXX these just needs to be the same when using Windows PK-INIT */
+    ctx->pk_nonce =3D ctx->nonce;
=20
-    ret =3D init_creds_init_as_req(context, ctx->flags, creds,
-				 ctx->addrs, ctx->etypes, &ctx->as_req);
+    ctx->prompter =3D prompter;
+    ctx->prompter_data =3D prompter_data;
+
+    *rctx =3D ctx;
+
+    return ret;
+}
+
+/**
+ * Sets the service that the is requested. This call is only neede for
+ * special initial tickets, by default the a krbtgt is fetched in the defa=
ult realm.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx a krb5_init_creds_context context.
+ * @param service the service given as a string, for example
+ *        "kadmind/admin". If NULL, the default krbtgt in the clients
+ *        realm is set.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_=
message().
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_service(krb5_context context,
+			    krb5_init_creds_context ctx,
+			    const char *service)
+{
+    krb5_const_realm client_realm;
+    krb5_principal principal;
+    krb5_error_code ret;
+
+    client_realm =3D krb5_principal_get_realm (context, ctx->cred.client);
+
+    if (service) {
+	ret =3D krb5_parse_name (context, service, &principal);
+	if (ret)
+	    return ret;
+	krb5_principal_set_realm (context, principal, client_realm);
+    } else {
+	ret =3D krb5_make_principal(context, &principal,
+				  client_realm, KRB5_TGS_NAME, client_realm,
+				  NULL);
+	if (ret)
+	    return ret;
+    }
+
+    /*
+     * This is for Windows RODC that are picky about what name type
+     * the server principal have, and the really strange part is that
+     * they are picky about the AS-REQ name type and not the TGS-REQ
+     * later. Oh well.
+     */
+
+    if (krb5_principal_is_krbtgt(context, principal))
+	krb5_principal_set_type(context, principal, KRB5_NT_SRV_INST);
+
+    krb5_free_principal(context, ctx->cred.server);
+    ctx->cred.server =3D principal;
+
+    return 0;
+}
+
+/**
+ * Sets the password that will use for the request.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx ctx krb5_init_creds_context context.
+ * @param password the password to use.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_=
message().
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_password(krb5_context context,
+			     krb5_init_creds_context ctx,
+			     const char *password)
+{
+    if (ctx->password) {
+	memset(ctx->password, 0, strlen(ctx->password));
+	free(ctx->password);
+    }
+    if (password) {
+	ctx->password =3D strdup(password);
+	if (ctx->password =3D=3D NULL) {
+	    krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", "=
"));
+	    return ENOMEM;
+	}
+	ctx->keyseed =3D (void *) ctx->password;
+    } else {
+	ctx->keyseed =3D NULL;
+	ctx->password =3D NULL;
+    }
+
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+keytab_key_proc(krb5_context context, krb5_enctype enctype,
+		krb5_const_pointer keyseed,
+		krb5_salt salt, krb5_data *s2kparms,
+		krb5_keyblock **key)
+{
+    krb5_keytab_key_proc_args *args  =3D rk_UNCONST(keyseed);
+    krb5_keytab keytab =3D args->keytab;
+    krb5_principal principal =3D args->principal;
+    krb5_error_code ret;
+    krb5_keytab real_keytab;
+    krb5_keytab_entry entry;
+
+    if(keytab =3D=3D NULL)
+	krb5_kt_default(context, &real_keytab);
+    else
+	real_keytab =3D keytab;
+
+    ret =3D krb5_kt_get_entry (context, real_keytab, principal,
+			     0, enctype, &entry);
+
+    if (keytab =3D=3D NULL)
+	krb5_kt_close (context, real_keytab);
+
     if (ret)
 	return ret;
=20
-    ret =3D krb5_sendto_ctx_alloc(context, &stctx);
-    if (ret)
-	goto out;
-    krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);
+    ret =3D krb5_copy_keyblock (context, &entry.keyblock, key);
+    krb5_kt_free_entry(context, &entry);
+    return ret;
+}
=20
-    /* Set a new nonce. */
-    krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce));
-    ctx->nonce &=3D 0xffffffff;
-    /* XXX these just needs to be the same when using Windows PK-INIT */
-    ctx->pk_nonce =3D ctx->nonce;
+
+/**
+ * Set the keytab to use for authentication.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx ctx krb5_init_creds_context context.
+ * @param keytab the keytab to read the key from.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_=
message().
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_keytab(krb5_context context,
+			   krb5_init_creds_context ctx,
+			   krb5_keytab keytab)
+{
+    krb5_keytab_key_proc_args *a;
+    krb5_keytab_entry entry;
+    krb5_kt_cursor cursor;
+    krb5_enctype *etypes =3D NULL;
+    krb5_error_code ret;
+    size_t netypes =3D 0;
+    int kvno =3D 0;
+
+    a =3D malloc(sizeof(*a));
+    if (a =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
+
+    a->principal =3D ctx->cred.client;
+    a->keytab    =3D keytab;
+
+    ctx->keytab_data =3D a;
+    ctx->keyseed =3D (void *)a;
+    ctx->keyproc =3D keytab_key_proc;
=20
     /*
-     * Increase counter when we want other pre-auth types then
-     * KRB5_PA_ENC_TIMESTAMP.
+     * We need to the KDC what enctypes we support for this keytab,
+     * esp if the keytab is really a password based entry, then the
+     * KDC might have more enctypes in the database then what we have
+     * in the keytab.
      */
-#define MAX_PA_COUNTER 3=20
=20
-    ctx->pa_counter =3D 0;
-    while (ctx->pa_counter < MAX_PA_COUNTER) {
+    ret =3D krb5_kt_start_seq_get(context, keytab, &cursor);
+    if(ret)
+	goto out;
=20
-	ctx->pa_counter++;
+    while(krb5_kt_next_entry(context, keytab, &entry, &cursor) =3D=3D 0){
+	void *ptr;
=20
-	if (ctx->as_req.padata) {
-	    free_METHOD_DATA(ctx->as_req.padata);
-	    free(ctx->as_req.padata);
-	    ctx->as_req.padata =3D NULL;
+	if (!krb5_principal_compare(context, entry.principal, ctx->cred.client))
+	    goto next;
+
+	/* check if we ahve this kvno already */
+	if (entry.vno > kvno) {
+	    /* remove old list of etype */
+	    if (etypes)
+		free(etypes);
+	    etypes =3D NULL;
+	    netypes =3D 0;
+	    kvno =3D entry.vno;
+	} else if (entry.vno !=3D kvno)
+	    goto next;
+
+	/* check if enctype is supported */
+	if (krb5_enctype_valid(context, entry.keyblock.keytype) !=3D 0)
+	    goto next;
+
+	/* add enctype to supported list */
+	ptr =3D realloc(etypes, sizeof(etypes[0]) * (netypes + 2));
+	if (ptr =3D=3D NULL)
+	    goto next;
+
+	etypes =3D ptr;
+	etypes[netypes] =3D entry.keyblock.keytype;
+	etypes[netypes + 1] =3D ETYPE_NULL;
+	netypes++;
+    next:
+	krb5_kt_free_entry(context, &entry);
+    }
+    krb5_kt_end_seq_get(context, keytab, &cursor);
+
+    if (etypes) {
+	if (ctx->etypes)
+	    free(ctx->etypes);
+	ctx->etypes =3D etypes;
+    }
+
+ out:
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+keyblock_key_proc(krb5_context context, krb5_enctype enctype,
+		  krb5_const_pointer keyseed,
+		  krb5_salt salt, krb5_data *s2kparms,
+		  krb5_keyblock **key)
+{
+    return krb5_copy_keyblock (context, keyseed, key);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_keyblock(krb5_context context,
+			     krb5_init_creds_context ctx,
+			     krb5_keyblock *keyblock)
+{
+    ctx->keyseed =3D (void *)keyblock;
+    ctx->keyproc =3D keyblock_key_proc;
+
+    return 0;
+}
+
+/**
+ * The core loop if krb5_get_init_creds() function family. Create the
+ * packets and have the caller send them off to the KDC.
+ *
+ * If the caller want all work been done for them, use
+ * krb5_init_creds_get() instead.
+ *
+ * @param context a Kerberos 5 context.
+ * @param ctx ctx krb5_init_creds_context context.
+ * @param in input data from KDC, first round it should be reset by krb5_d=
ata_zer().
+ * @param out reply to KDC.
+ * @param hostinfo KDC address info, first round it can be NULL.
+ * @param flags status of the round, if
+ *        KRB5_INIT_CREDS_STEP_FLAG_CONTINUE is set, continue one more rou=
nd.
+ *
+ * @return 0 for success, or an Kerberos 5 error code, see
+ *     krb5_get_error_message().
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_step(krb5_context context,
+		     krb5_init_creds_context ctx,
+		     krb5_data *in,
+		     krb5_data *out,
+		     krb5_krbhst_info *hostinfo,
+		     unsigned int *flags)
+{
+    krb5_error_code ret;
+    size_t len =3D 0;
+    size_t size;
+
+    krb5_data_zero(out);
+
+    if (ctx->as_req.req_body.cname =3D=3D NULL) {
+	ret =3D init_as_req(context, ctx->flags, &ctx->cred,
+			  ctx->addrs, ctx->etypes, &ctx->as_req);
+	if (ret) {
+	    free_init_creds_ctx(context, ctx);
+	    return ret;
 	}
+    }
=20
-	/* Set a new nonce. */
-	ctx->as_req.req_body.nonce =3D ctx->nonce;
+#define MAX_PA_COUNTER 10
+    if (ctx->pa_counter > MAX_PA_COUNTER) {
+	krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP,
+			       N_("Looping %d times while getting "
+				  "initial credentials", ""),
+			       ctx->pa_counter);
+	return KRB5_GET_IN_TKT_LOOP;
+    }
+    ctx->pa_counter++;
=20
-	/* fill_in_md_data */
-	ret =3D process_pa_data_to_md(context, creds, &ctx->as_req, ctx,
-				    &md, &ctx->as_req.padata,
-				    prompter, prompter_data);
-	if (ret)
-	    goto out;
+    _krb5_debug(context, 5, "krb5_get_init_creds: loop %d", ctx->pa_counte=
r);
=20
-	krb5_data_free(&ctx->req_buffer);
+    /* Lets process the input packet */
+    if (in && in->length) {
+	krb5_kdc_rep rep;
=20
-	ASN1_MALLOC_ENCODE(AS_REQ,=20
-			   ctx->req_buffer.data, ctx->req_buffer.length,=20
-			   &ctx->as_req, &len, ret);
-	if (ret)
-	    goto out;
-	if(len !=3D ctx->req_buffer.length)
-	    krb5_abortx(context, "internal error in ASN.1 encoder");
+	memset(&rep, 0, sizeof(rep));
=20
-	ret =3D krb5_sendto_context (context, stctx, &ctx->req_buffer,
-				   creds->client->realm, &resp);
-    	if (ret)
-	    goto out;
+	_krb5_debug(context, 5, "krb5_get_init_creds: processing input");
=20
-	memset (&rep, 0, sizeof(rep));
-	ret =3D decode_AS_REP(resp.data, resp.length, &rep.kdc_rep, &size);
+	ret =3D decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size);
 	if (ret =3D=3D 0) {
-	    krb5_data_free(&resp);
-	    krb5_clear_error_string(context);
-	    break;
+	    krb5_keyblock *key =3D NULL;
+	    unsigned eflags =3D EXTRACT_TICKET_AS_REQ | EXTRACT_TICKET_TIMESYNC;
+
+	    if (ctx->flags.canonicalize) {
+		eflags |=3D EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
+		eflags |=3D EXTRACT_TICKET_MATCH_REALM;
+	    }
+	    if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK)
+		eflags |=3D EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
+
+	    ret =3D process_pa_data_to_key(context, ctx, &ctx->cred,
+					 &ctx->as_req, &rep.kdc_rep, hostinfo, &key);
+	    if (ret) {
+		free_AS_REP(&rep.kdc_rep);
+		goto out;
+	    }
+
+	    _krb5_debug(context, 5, "krb5_get_init_creds: extracting ticket");
+
+	    ret =3D _krb5_extract_ticket(context,
+				       &rep,
+				       &ctx->cred,
+				       key,
+				       NULL,
+				       KRB5_KU_AS_REP_ENC_PART,
+				       NULL,
+				       ctx->nonce,
+				       eflags,
+				       NULL,
+				       NULL);
+	    krb5_free_keyblock(context, key);
+
+	    *flags =3D 0;
+
+	    if (ret =3D=3D 0)
+		ret =3D copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part);
+
+	    free_AS_REP(&rep.kdc_rep);
+	    free_EncASRepPart(&rep.enc_part);
+
+	    return ret;
+
 	} else {
 	    /* let's try to parse it as a KRB-ERROR */
-	    KRB_ERROR error;
=20
-	    ret =3D krb5_rd_error(context, &resp, &error);
-	    if(ret && resp.data && ((char*)resp.data)[0] =3D=3D 4)
+	    _krb5_debug(context, 5, "krb5_get_init_creds: got an error");
+
+	    free_KRB_ERROR(&ctx->error);
+
+	    ret =3D krb5_rd_error(context, in, &ctx->error);
+	    if(ret && in->length && ((char*)in->data)[0] =3D=3D 4)
 		ret =3D KRB5KRB_AP_ERR_V4_REPLY;
-	    krb5_data_free(&resp);
-	    if (ret)
+	    if (ret) {
+		_krb5_debug(context, 5, "krb5_get_init_creds: failed to read error");
 		goto out;
+	    }
=20
-	    ret =3D krb5_error_from_rd_error(context, &error, creds);
+	    ret =3D krb5_error_from_rd_error(context, &ctx->error, &ctx->cred);
+
+	    _krb5_debug(context, 5, "krb5_get_init_creds: KRB-ERROR %d", ret);
=20
 	    /*
 	     * If no preauth was set and KDC requires it, give it one
@@ -1316,223 +1751,212 @@
 	     */
=20
 	    if (ret =3D=3D KRB5KDC_ERR_PREAUTH_REQUIRED) {
-		free_METHOD_DATA(&md);
-		memset(&md, 0, sizeof(md));
=20
-		if (error.e_data) {
-		    ret =3D decode_METHOD_DATA(error.e_data->data,=20
-					     error.e_data->length,=20
-					     &md,=20
+	        free_METHOD_DATA(&ctx->md);
+	        memset(&ctx->md, 0, sizeof(ctx->md));
+
+		if (ctx->error.e_data) {
+		    ret =3D decode_METHOD_DATA(ctx->error.e_data->data,
+					     ctx->error.e_data->length,
+					     &ctx->md,
 					     NULL);
 		    if (ret)
-			krb5_set_error_string(context,
-					      "failed to decode METHOD DATA");
+			krb5_set_error_message(context, ret,
+					       N_("Failed to decode METHOD-DATA", ""));
 		} else {
-		    /* XXX guess what the server want here add add md */
+		    krb5_set_error_message(context, ret,
+					   N_("Preauth required but no preauth "
+					      "options send by KDC", ""));
 		}
-		krb5_free_error_contents(context, &error);
-		if (ret)
+	    } else if (ret =3D=3D KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset =
=3D=3D 0) {
+		/*
+		 * Try adapt to timeskrew when we are using pre-auth, and
+		 * if there was a time skew, try again.
+		 */
+		krb5_set_real_time(context, ctx->error.stime, -1);
+		if (context->kdc_sec_offset)
+		    ret =3D 0;
+
+		_krb5_debug(context, 10, "init_creds: err skew updateing kdc offset to %=
d",
+			    context->kdc_sec_offset);
+
+		ctx->used_pa_types =3D 0;
+
+	    } else if (ret =3D=3D KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonica=
lize) {
+	        /* client referal to a new realm */
+
+		if (ctx->error.crealm =3D=3D NULL) {
+		    krb5_set_error_message(context, ret,
+					   N_("Got a client referral, not but no realm", ""));
 		    goto out;
-	    } else {
-		_krb5_get_init_creds_opt_set_krb5_error(context,
-							init_cred_opts,
-							&error);
-		if (ret_as_reply)
-		    rep.error =3D error;
-		else
-		    krb5_free_error_contents(context, &error);
+		}
+		_krb5_debug(context, 5,
+			    "krb5_get_init_creds: got referal to realm %s",
+			    *ctx->error.crealm);
+
+		ret =3D krb5_principal_set_realm(context,
+					       ctx->cred.client,
+					       *ctx->error.crealm);
+
+		ctx->used_pa_types =3D 0;
+	    }
+	    if (ret)
 		goto out;
-	    }
 	}
     }
=20
-    {
-	krb5_keyblock *key =3D NULL;
-	unsigned flags =3D 0;
+    if (ctx->as_req.padata) {
+	free_METHOD_DATA(ctx->as_req.padata);
+	free(ctx->as_req.padata);
+	ctx->as_req.padata =3D NULL;
+    }
=20
-	if (ctx->flags.request_anonymous)
-	    flags |=3D EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
-	if (ctx->flags.canonicalize) {
-	    flags |=3D EXTRACT_TICKET_ALLOW_CNAME_MISMATCH;
-	    flags |=3D EXTRACT_TICKET_ALLOW_SERVER_MISMATCH;
-	    flags |=3D EXTRACT_TICKET_MATCH_REALM;
-	}
+    /* Set a new nonce. */
+    ctx->as_req.req_body.nonce =3D ctx->nonce;
=20
-	ret =3D process_pa_data_to_key(context, ctx, creds,=20
-				     &ctx->as_req, &rep, hi, &key);
-	if (ret)
-	    goto out;
-=09
-	ret =3D _krb5_extract_ticket(context,
-				   &rep,
-				   creds,
-				   key,
-				   NULL,
-				   KRB5_KU_AS_REP_ENC_PART,
-				   NULL,
-				   ctx->nonce,
-				   flags,
-				   NULL,
-				   NULL);
-	krb5_free_keyblock(context, key);
-    }
-    /*
-     * Verify referral data
-     */
-    if ((ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE) &&
-	(ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK) =3D=3D 0)
-    {
-	PA_ClientCanonicalized canon;
-	krb5_crypto crypto;
-	krb5_data data;
-	PA_DATA *pa;
-	size_t len;
+    /* fill_in_md_data */
+    ret =3D process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx,
+				&ctx->md, &ctx->as_req.padata,
+				ctx->prompter, ctx->prompter_data);
+    if (ret)
+	goto out;
=20
-	pa =3D find_pa_data(rep.kdc_rep.padata, KRB5_PADATA_CLIENT_CANONICALIZED);
-	if (pa =3D=3D NULL) {
-	    ret =3D EINVAL;
-	    krb5_set_error_string(context, "Client canonicalizion not signed");
-	    goto out;
-	}
-=09
-	ret =3D decode_PA_ClientCanonicalized(pa->padata_value.data,=20
-					    pa->padata_value.length,
-					    &canon, &len);
-	if (ret) {
-	    krb5_set_error_string(context, "Failed to decode "
-				  "PA_ClientCanonicalized");
-	    goto out;
-	}
+    krb5_data_free(&ctx->req_buffer);
=20
-	ASN1_MALLOC_ENCODE(PA_ClientCanonicalizedNames, data.data, data.length,
-			   &canon.names, &len, ret);
-	if (ret)=20
-	    goto out;
-	if (data.length !=3D len)
-	    krb5_abortx(context, "internal asn.1 error");
+    ASN1_MALLOC_ENCODE(AS_REQ,
+		       ctx->req_buffer.data, ctx->req_buffer.length,
+		       &ctx->as_req, &len, ret);
+    if (ret)
+	goto out;
+    if(len !=3D ctx->req_buffer.length)
+	krb5_abortx(context, "internal error in ASN.1 encoder");
=20
-	ret =3D krb5_crypto_init(context, &creds->session, 0, &crypto);
-	if (ret) {
-	    free(data.data);
-	    free_PA_ClientCanonicalized(&canon);
-	    goto out;
-	}
+    out->data =3D ctx->req_buffer.data;
+    out->length =3D ctx->req_buffer.length;
=20
-	ret =3D krb5_verify_checksum(context, crypto, KRB5_KU_CANONICALIZED_NAMES,
-				   data.data, data.length,
-				   &canon.canon_checksum);
-	krb5_crypto_destroy(context, crypto);
-	free(data.data);
-	free_PA_ClientCanonicalized(&canon);
-	if (ret) {
-	    krb5_set_error_string(context, "Failed to verify "
-				  "client canonicalized data");
-	    goto out;
-	}
-    }
-out:
-    if (stctx)
-	krb5_sendto_ctx_free(context, stctx);
-    krb5_data_free(&ctx->req_buffer);
-    free_METHOD_DATA(&md);
-    memset(&md, 0, sizeof(md));
+    *flags =3D KRB5_INIT_CREDS_STEP_FLAG_CONTINUE;
=20
-    if (ret =3D=3D 0 && ret_as_reply)
-	*ret_as_reply =3D rep;
-    else=20
-	krb5_free_kdc_rep (context, &rep);
+    return 0;
+ out:
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_init_creds(krb5_context context,
-		    krb5_creds *creds,
-		    krb5_principal client,
-		    krb5_prompter_fct prompter,
-		    void *data,
-		    krb5_deltat start_time,
-		    const char *in_tkt_service,
-		    krb5_get_init_creds_opt *options)
+/**
+ * Extract the newly acquired credentials from krb5_init_creds_context
+ * context.
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx
+ * @param cred credentials, free with krb5_free_cred_contents().
+ *
+ * @return 0 for sucess or An Kerberos error code, see krb5_get_error_mess=
age().
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get_creds(krb5_context context,
+			  krb5_init_creds_context ctx,
+			  krb5_creds *cred)
 {
-    krb5_get_init_creds_ctx ctx;
-    krb5_kdc_rep kdc_reply;
+    return krb5_copy_creds_contents(context, &ctx->cred, cred);
+}
+
+/**
+ * Get the last error from the transaction.
+ *
+ * @return Returns 0 or an error code
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get_error(krb5_context context,
+			  krb5_init_creds_context ctx,
+			  KRB_ERROR *error)
+{
     krb5_error_code ret;
-    char buf[BUFSIZ];
-    int done;
=20
-    memset(&kdc_reply, 0, sizeof(kdc_reply));
-
-    ret =3D get_init_creds_common(context, client, start_time,
-				in_tkt_service, options, &ctx);
+    ret =3D copy_KRB_ERROR(&ctx->error, error);
     if (ret)
-	goto out;
-
-    done =3D 0;
-    while(!done) {
-	memset(&kdc_reply, 0, sizeof(kdc_reply));
-
-	ret =3D init_cred_loop(context,
-			     options,
-			     prompter,
-			     data,
-			     &ctx,
-			     &ctx.cred,
-			     &kdc_reply);
-=09
-	switch (ret) {
-	case 0 :
-	    done =3D 1;
-	    break;
-	case KRB5KDC_ERR_KEY_EXPIRED :
-	    /* try to avoid recursion */
-
-	    /* don't try to change password where then where none */
-	    if (prompter =3D=3D NULL || ctx.password =3D=3D NULL)
-		goto out;
-
-	    krb5_clear_error_string (context);
-
-	    if (ctx.in_tkt_service !=3D NULL
-		&& strcmp (ctx.in_tkt_service, "kadmin/changepw") =3D=3D 0)
-		goto out;
-
-	    ret =3D change_password (context,
-				   client,
-				   ctx.password,
-				   buf,
-				   sizeof(buf),
-				   prompter,
-				   data,
-				   options);
-	    if (ret)
-		goto out;
-	    ctx.password =3D buf;
-	    break;
-	default:
-	    goto out;
-	}
-    }
-
-    if (prompter)
-	print_expire (context,
-		      krb5_principal_get_realm (context, ctx.cred.client),
-		      &kdc_reply,
-		      prompter,
-		      data);
-
- out:
-    memset (buf, 0, sizeof(buf));
-    free_init_creds_ctx(context, &ctx);
-    krb5_free_kdc_rep (context, &kdc_reply);
-    if (ret =3D=3D 0)
-	*creds =3D ctx.cred;
-    else
-	krb5_free_cred_contents (context, &ctx.cred);
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
=20
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Free the krb5_init_creds_context allocated by krb5_init_creds_init().
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx The krb5_init_creds_context to free.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_init_creds_free(krb5_context context,
+		     krb5_init_creds_context ctx)
+{
+    free_init_creds_ctx(context, ctx);
+    free(ctx);
+}
+
+/**
+ * Get new credentials as setup by the krb5_init_creds_context.
+ *
+ * @param context A Kerberos 5 context.
+ * @param ctx The krb5_init_creds_context to process.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx)
+{
+    krb5_sendto_ctx stctx =3D NULL;
+    krb5_krbhst_info *hostinfo =3D NULL;
+    krb5_error_code ret;
+    krb5_data in, out;
+    unsigned int flags =3D 0;
+
+    krb5_data_zero(&in);
+    krb5_data_zero(&out);
+
+    ret =3D krb5_sendto_ctx_alloc(context, &stctx);
+    if (ret)
+	goto out;
+    krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL);
+
+    while (1) {
+	flags =3D 0;
+	ret =3D krb5_init_creds_step(context, ctx, &in, &out, hostinfo, &flags);
+	krb5_data_free(&in);
+	if (ret)
+	    goto out;
+
+	if ((flags & 1) =3D=3D 0)
+	    break;
+
+	ret =3D krb5_sendto_context (context, stctx, &out,
+				   ctx->cred.client->realm, &in);
+    	if (ret)
+	    goto out;
+
+    }
+
+ out:
+    if (stctx)
+	krb5_sendto_ctx_free(context, stctx);
+
+    return ret;
+}
+
+/**
+ * Get new credentials using password.
+ *
+ * @ingroup krb5_credential
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_password(krb5_context context,
 			     krb5_creds *creds,
 			     krb5_principal client,
@@ -1541,29 +1965,23 @@
 			     void *data,
 			     krb5_deltat start_time,
 			     const char *in_tkt_service,
-			     krb5_get_init_creds_opt *in_options)
+			     krb5_get_init_creds_opt *options)
 {
-    krb5_get_init_creds_opt *options;
+    krb5_init_creds_context ctx;
     char buf[BUFSIZ];
     krb5_error_code ret;
+    int chpw =3D 0;
=20
-    if (in_options =3D=3D NULL) {
-	const char *realm =3D krb5_principal_get_realm(context, client);
-	ret =3D krb5_get_init_creds_opt_alloc(context, &options);
-	if (ret =3D=3D 0)
-	    krb5_get_init_creds_opt_set_default_flags(context,=20
-						      NULL,=20
-						      realm,=20
-						      options);
-    } else
-	ret =3D _krb5_get_init_creds_opt_copy(context, in_options, &options);
+ again:
+    ret =3D krb5_init_creds_init(context, client, prompter, data, start_ti=
me, options, &ctx);
     if (ret)
-	return ret;
+	goto out;
=20
-    if (password =3D=3D NULL &&
-	options->opt_private->password =3D=3D NULL &&
-	options->opt_private->pk_init_ctx =3D=3D NULL)
-    {
+    ret =3D krb5_init_creds_set_service(context, ctx, in_tkt_service);
+    if (ret)
+	goto out;
+
+    if (prompter !=3D NULL && ctx->password =3D=3D NULL && password =3D=3D=
 NULL) {
 	krb5_prompt prompt;
 	krb5_data password_data;
 	char *p, *q;
@@ -1582,42 +2000,69 @@
 	free (q);
 	if (ret) {
 	    memset (buf, 0, sizeof(buf));
-	    krb5_get_init_creds_opt_free(context, options);
 	    ret =3D KRB5_LIBOS_PWDINTR;
-	    krb5_clear_error_string (context);
-	    return ret;
+	    krb5_clear_error_message (context);
+	    goto out;
 	}
 	password =3D password_data.data;
     }
=20
-    if (options->opt_private->password =3D=3D NULL) {
-	ret =3D krb5_get_init_creds_opt_set_pa_password(context, options,
-						      password, NULL);
-	if (ret) {
-	    krb5_get_init_creds_opt_free(context, options);
-	    memset(buf, 0, sizeof(buf));
-	    return ret;
-	}
+    if (password) {
+	ret =3D krb5_init_creds_set_password(context, ctx, password);
+	if (ret)
+	    goto out;
     }
=20
-    ret =3D krb5_get_init_creds(context, creds, client, prompter,
-			      data, start_time, in_tkt_service, options);
-    krb5_get_init_creds_opt_free(context, options);
+    ret =3D krb5_init_creds_get(context, ctx);
+
+    if (ret =3D=3D 0)
+	process_last_request(context, options, ctx);
+
+
+    if (ret =3D=3D KRB5KDC_ERR_KEY_EXPIRED && chpw =3D=3D 0) {
+	char buf2[1024];
+
+	/* try to avoid recursion */
+	if (in_tkt_service !=3D NULL && strcmp(in_tkt_service, "kadmin/changepw")=
 =3D=3D 0)
+	   goto out;
+
+	/* don't try to change password where then where none */
+	if (prompter =3D=3D NULL)
+	    goto out;
+
+	ret =3D change_password (context,
+			       client,
+			       ctx->password,
+			       buf2,
+			       sizeof(buf),
+			       prompter,
+			       data,
+			       options);
+	if (ret)
+	    goto out;
+	chpw =3D 1;
+	krb5_init_creds_free(context, ctx);
+	goto again;
+    }
+
+ out:
+    if (ret =3D=3D 0)
+	krb5_init_creds_get_creds(context, ctx, creds);
+
+    if (ctx)
+	krb5_init_creds_free(context, ctx);
+
     memset(buf, 0, sizeof(buf));
     return ret;
 }
=20
-static krb5_error_code
-init_creds_keyblock_key_proc (krb5_context context,
-			      krb5_enctype type,
-			      krb5_salt salt,
-			      krb5_const_pointer keyseed,
-			      krb5_keyblock **key)
-{
-    return krb5_copy_keyblock (context, keyseed, key);
-}
+/**
+ * Get new credentials using keyblock.
+ *
+ * @ingroup krb5_credential
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_keyblock(krb5_context context,
 			     krb5_creds *creds,
 			     krb5_principal client,
@@ -1626,33 +2071,80 @@
 			     const char *in_tkt_service,
 			     krb5_get_init_creds_opt *options)
 {
-    struct krb5_get_init_creds_ctx ctx;
+    krb5_init_creds_context ctx;
     krb5_error_code ret;
-   =20
-    ret =3D get_init_creds_common(context, client, start_time,
-				in_tkt_service, options, &ctx);
+
+    memset(creds, 0, sizeof(*creds));
+
+    ret =3D krb5_init_creds_init(context, client, NULL, NULL, start_time, =
options, &ctx);
     if (ret)
 	goto out;
=20
-    ret =3D krb5_get_in_cred (context,
-			    KDCOptions2int(ctx.flags),
-			    ctx.addrs,
-			    ctx.etypes,
-			    ctx.pre_auth_types,
-			    NULL,
-			    init_creds_keyblock_key_proc,
-			    keyblock,
-			    NULL,
-			    NULL,
-			    &ctx.cred,
-			    NULL);
+    ret =3D krb5_init_creds_set_service(context, ctx, in_tkt_service);
+    if (ret)
+	goto out;
=20
-    if (ret =3D=3D 0 && creds)
-	*creds =3D ctx.cred;
-    else
-	krb5_free_cred_contents (context, &ctx.cred);
+    ret =3D krb5_init_creds_set_keyblock(context, ctx, keyblock);
+    if (ret)
+	goto out;
+
+    ret =3D krb5_init_creds_get(context, ctx);
+
+    if (ret =3D=3D 0)
+        process_last_request(context, options, ctx);
=20
  out:
-    free_init_creds_ctx(context, &ctx);
+    if (ret =3D=3D 0)
+	krb5_init_creds_get_creds(context, ctx, creds);
+
+    if (ctx)
+	krb5_init_creds_free(context, ctx);
+
     return ret;
 }
+
+/**
+ * Get new credentials using keytab.
+ *
+ * @ingroup krb5_credential
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_keytab(krb5_context context,
+			   krb5_creds *creds,
+			   krb5_principal client,
+			   krb5_keytab keytab,
+			   krb5_deltat start_time,
+			   const char *in_tkt_service,
+			   krb5_get_init_creds_opt *options)
+{
+    krb5_init_creds_context ctx;
+    krb5_error_code ret;
+
+    memset(creds, 0, sizeof(*creds));
+
+    ret =3D krb5_init_creds_init(context, client, NULL, NULL, start_time, =
options, &ctx);
+    if (ret)
+	goto out;
+
+    ret =3D krb5_init_creds_set_service(context, ctx, in_tkt_service);
+    if (ret)
+	goto out;
+
+    ret =3D krb5_init_creds_set_keytab(context, ctx, keytab);
+    if (ret)
+	goto out;
+
+    ret =3D krb5_init_creds_get(context, ctx);
+    if (ret =3D=3D 0)
+        process_last_request(context, options, ctx);
+
+ out:
+    if (ret =3D=3D 0)
+	krb5_init_creds_get_creds(context, ctx, creds);
+
+    if (ctx)
+	krb5_init_creds_free(context, ctx);
+
+    return ret;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/k524_err.=
et
--- a/head/crypto/heimdal/lib/krb5/k524_err.et	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/k524_err.et	Tue Apr 17 11:51:51 2012 +03=
00
@@ -3,7 +3,7 @@
 #
 # This might look like a com_err file, but is not
 #
-id "$Id: k524_err.et 10141 2001-06-20 02:45:58Z joda $"
+id "$Id$"
=20
 error_table k524
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/kcm.c
--- a/head/crypto/heimdal/lib/krb5/kcm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/kcm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -37,130 +39,68 @@
  * Client library for Kerberos Credentials Manager (KCM) daemon
  */
=20
-#ifdef HAVE_SYS_UN_H
-#include <sys/un.h>
-#endif
+#include "kcm.h"
+#include <heim-ipc.h>
=20
-#include "kcm.h"
+static krb5_error_code
+kcm_set_kdc_offset(krb5_context, krb5_ccache, krb5_deltat);
=20
-RCSID("$Id: kcm.c 22108 2007-12-03 17:23:53Z lha $");
+static const char *kcm_ipc_name =3D "ANY:org.h5l.kcm";
=20
 typedef struct krb5_kcmcache {
     char *name;
-    struct sockaddr_un path;
-    char *door_path;
 } krb5_kcmcache;
=20
+typedef struct krb5_kcm_cursor {
+    unsigned long offset;
+    unsigned long length;
+    kcmuuid_t *uuids;
+} *krb5_kcm_cursor;
+
+
 #define KCMCACHE(X)	((krb5_kcmcache *)(X)->data.data)
 #define CACHENAME(X)	(KCMCACHE(X)->name)
-#define KCMCURSOR(C)	(*(uint32_t *)(C))
+#define KCMCURSOR(C)	((krb5_kcm_cursor)(C))
+
+static HEIMDAL_MUTEX kcm_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
+static heim_ipc kcm_ipc =3D NULL;
=20
 static krb5_error_code
-try_door(krb5_context context, const krb5_kcmcache *k,
-	 krb5_data *request_data,
-	 krb5_data *response_data)
-{
-#ifdef HAVE_DOOR_CREATE
-    door_arg_t arg;
-    int fd;
-    int ret;
-
-    memset(&arg, 0, sizeof(arg));
-	  =20
-    fd =3D open(k->door_path, O_RDWR);
-    if (fd < 0)
-	return KRB5_CC_IO;
-
-    arg.data_ptr =3D request_data->data;
-    arg.data_size =3D request_data->length;
-    arg.desc_ptr =3D NULL;
-    arg.desc_num =3D 0;
-    arg.rbuf =3D NULL;
-    arg.rsize =3D 0;
-
-    ret =3D door_call(fd, &arg);
-    close(fd);
-    if (ret !=3D 0)
-	return KRB5_CC_IO;
-
-    ret =3D krb5_data_copy(response_data, arg.rbuf, arg.rsize);
-    munmap(arg.rbuf, arg.rsize);
-    if (ret)
-	return ret;
-
-    return 0;
-#else
-    return KRB5_CC_IO;
-#endif
-}
-
-static krb5_error_code
-try_unix_socket(krb5_context context, const krb5_kcmcache *k,
-		krb5_data *request_data,
-		krb5_data *response_data)
-{
-    krb5_error_code ret;
-    int fd;
-
-    fd =3D socket(AF_UNIX, SOCK_STREAM, 0);
-    if (fd < 0)
-	return KRB5_CC_IO;
-   =20
-    if (connect(fd, rk_UNCONST(&k->path), sizeof(k->path)) !=3D 0) {
-	close(fd);
-	return KRB5_CC_IO;
-    }
-   =20
-    ret =3D _krb5_send_and_recv_tcp(fd, context->kdc_timeout,
-				  request_data, response_data);
-    close(fd);
-    return ret;
-}
-   =20
-static krb5_error_code
 kcm_send_request(krb5_context context,
-		 krb5_kcmcache *k,
 		 krb5_storage *request,
 		 krb5_data *response_data)
 {
-    krb5_error_code ret;
+    krb5_error_code ret =3D 0;
     krb5_data request_data;
-    int i;
=20
-    response_data->data =3D NULL;
-    response_data->length =3D 0;
+    HEIMDAL_MUTEX_lock(&kcm_mutex);
+    if (kcm_ipc =3D=3D NULL)
+	ret =3D heim_ipc_init_context(kcm_ipc_name, &kcm_ipc);
+    HEIMDAL_MUTEX_unlock(&kcm_mutex);
+    if (ret)
+	return KRB5_CC_NOSUPP;
=20
     ret =3D krb5_storage_to_data(request, &request_data);
     if (ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return KRB5_CC_NOMEM;
     }
=20
-    ret =3D KRB5_CC_IO;
-
-    for (i =3D 0; i < context->max_retries; i++) {
-	ret =3D try_door(context, k, &request_data, response_data);
-	if (ret =3D=3D 0 && response_data->length !=3D 0)
-	    break;
-	ret =3D try_unix_socket(context, k, &request_data, response_data);
-	if (ret =3D=3D 0 && response_data->length !=3D 0)
-	    break;
-    }
-
+    ret =3D heim_ipc_call(kcm_ipc, &request_data, response_data, NULL);
     krb5_data_free(&request_data);
=20
     if (ret) {
-	krb5_clear_error_string(context);
-	ret =3D KRB5_CC_IO;
+	krb5_clear_error_message(context);
+	ret =3D KRB5_CC_NOSUPP;
     }
=20
     return ret;
 }
=20
-static krb5_error_code
-kcm_storage_request(krb5_context context,
-		    kcm_operation opcode,
-		    krb5_storage **storage_p)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kcm_storage_request(krb5_context context,
+			 uint16_t opcode,
+			 krb5_storage **storage_p)
 {
     krb5_storage *sp;
     krb5_error_code ret;
@@ -169,7 +109,7 @@
=20
     sp =3D krb5_storage_emem();
     if (sp =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM, N_("malloc: out of memory"=
, ""));
 	return KRB5_CC_NOMEM;
     }
=20
@@ -187,22 +127,23 @@
     *storage_p =3D sp;
  fail:
     if (ret) {
-	krb5_set_error_string(context, "Failed to encode request");
+	krb5_set_error_message(context, ret,
+			       N_("Failed to encode KCM request", ""));
 	krb5_storage_free(sp);
     }
-  =20
-    return ret;=20
+
+    return ret;
 }
=20
 static krb5_error_code
 kcm_alloc(krb5_context context, const char *name, krb5_ccache *id)
 {
     krb5_kcmcache *k;
-    const char *path;
=20
     k =3D malloc(sizeof(*k));
     if (k =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
=20
@@ -210,40 +151,24 @@
 	k->name =3D strdup(name);
 	if (k->name =3D=3D NULL) {
 	    free(k);
-	    krb5_set_error_string(context, "malloc: out of memory");
+	    krb5_set_error_message(context, KRB5_CC_NOMEM,
+				   N_("malloc: out of memory", ""));
 	    return KRB5_CC_NOMEM;
 	}
     } else
 	k->name =3D NULL;
=20
-    path =3D krb5_config_get_string_default(context, NULL,
-					  _PATH_KCM_SOCKET,
-					  "libdefaults",=20
-					  "kcm_socket",
-					  NULL);
-   =20
-    k->path.sun_family =3D AF_UNIX;
-    strlcpy(k->path.sun_path, path, sizeof(k->path.sun_path));
-
-    path =3D krb5_config_get_string_default(context, NULL,
-					  _PATH_KCM_DOOR,
-					  "libdefaults",=20
-					  "kcm_door",
-					  NULL);
-    k->door_path =3D strdup(path);
-
     (*id)->data.data =3D k;
     (*id)->data.length =3D sizeof(*k);
=20
     return 0;
 }
=20
-static krb5_error_code
-kcm_call(krb5_context context,
-	 krb5_kcmcache *k,
-	 krb5_storage *request,
-	 krb5_storage **response_p,
-	 krb5_data *response_data_p)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kcm_call(krb5_context context,
+	      krb5_storage *request,
+	      krb5_storage **response_p,
+	      krb5_data *response_data_p)
 {
     krb5_data response_data;
     krb5_error_code ret;
@@ -253,10 +178,11 @@
     if (response_p !=3D NULL)
 	*response_p =3D NULL;
=20
-    ret =3D kcm_send_request(context, k, request, &response_data);
-    if (ret) {
+    krb5_data_zero(&response_data);
+
+    ret =3D kcm_send_request(context, request, &response_data);
+    if (ret)
 	return ret;
-    }
=20
     response =3D krb5_storage_from_data(&response_data);
     if (response =3D=3D NULL) {
@@ -298,13 +224,9 @@
     if (k !=3D NULL) {
 	if (k->name !=3D NULL)
 	    free(k->name);
-	if (k->door_path)
-	    free(k->door_path);
 	memset(k, 0, sizeof(*k));
 	krb5_data_free(&(*id)->data);
     }
-
-    *id =3D NULL;
 }
=20
 static const char *
@@ -340,13 +262,13 @@
=20
     k =3D KCMCACHE(*id);
=20
-    ret =3D kcm_storage_request(context, KCM_OP_GEN_NEW, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GEN_NEW, &request);
     if (ret) {
 	kcm_free(context, id);
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, &response, &response_data);
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
     if (ret) {
 	krb5_storage_free(request);
 	kcm_free(context, id);
@@ -384,7 +306,7 @@
     krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_INITIALIZE, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_INITIALIZE, &request);
     if (ret)
 	return ret;
=20
@@ -400,9 +322,13 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
+
+    if (context->kdc_sec_offset)
+	kcm_set_kdc_offset(context, id, context->kdc_sec_offset);
+
     return ret;
 }
=20
@@ -429,7 +355,7 @@
     krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_DESTROY, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_DESTROY, &request);
     if (ret)
 	return ret;
=20
@@ -439,7 +365,7 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
     return ret;
@@ -462,7 +388,7 @@
     krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_STORE, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_STORE, &request);
     if (ret)
 	return ret;
=20
@@ -478,12 +404,13 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
     return ret;
 }
=20
+#if 0
 /*
  * Request:
  *      NameZ
@@ -506,7 +433,7 @@
     krb5_storage *request, *response;
     krb5_data response_data;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_RETRIEVE, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_RETRIEVE, &request);
     if (ret)
 	return ret;
=20
@@ -528,7 +455,7 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, &response, &response_data);
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
     if (ret) {
 	krb5_storage_free(request);
 	return ret;
@@ -544,6 +471,7 @@
=20
     return ret;
 }
+#endif
=20
 /*
  * Request:
@@ -562,7 +490,7 @@
     krb5_storage *request, *response;
     krb5_data response_data;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_GET_PRINCIPAL, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_PRINCIPAL, &reque=
st);
     if (ret)
 	return ret;
=20
@@ -572,7 +500,7 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, &response, &response_data);
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
     if (ret) {
 	krb5_storage_free(request);
 	return ret;
@@ -603,12 +531,12 @@
 	       krb5_cc_cursor *cursor)
 {
     krb5_error_code ret;
+    krb5_kcm_cursor c;
     krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request, *response;
     krb5_data response_data;
-    int32_t tmp;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_GET_FIRST, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_CRED_UUID_LIST, &=
request);
     if (ret)
 	return ret;
=20
@@ -618,28 +546,57 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, &response, &response_data);
-    if (ret) {
-	krb5_storage_free(request);
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
+    krb5_storage_free(request);
+    if (ret)
+	return ret;
+
+    c =3D calloc(1, sizeof(*c));
+    if (c =3D=3D NULL) {
+	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret,
+			       N_("malloc: out of memory", ""));
 	return ret;
     }
=20
-    ret =3D krb5_ret_int32(response, &tmp);
-    if (ret || tmp < 0)
-	ret =3D KRB5_CC_IO;
+    while (1) {
+	ssize_t sret;
+	kcmuuid_t uuid;
+	void *ptr;
=20
-    krb5_storage_free(request);
+	sret =3D krb5_storage_read(response, &uuid, sizeof(uuid));
+	if (sret =3D=3D 0) {
+	    ret =3D 0;
+	    break;
+	} else if (sret !=3D sizeof(uuid)) {
+	    ret =3D EINVAL;
+	    break;
+	}
+
+	ptr =3D realloc(c->uuids, sizeof(c->uuids[0]) * (c->length + 1));
+	if (ptr =3D=3D NULL) {
+	    free(c->uuids);
+	    free(c);
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
+	    return ENOMEM;
+	}
+	c->uuids =3D ptr;
+
+	memcpy(&c->uuids[c->length], &uuid, sizeof(uuid));
+	c->length +=3D 1;
+    }
+
     krb5_storage_free(response);
     krb5_data_free(&response_data);
=20
-    if (ret)
+    if (ret) {
+        free(c->uuids);
+        free(c);
 	return ret;
+    }
=20
-    *cursor =3D malloc(sizeof(tmp));
-    if (*cursor =3D=3D NULL)
-	return KRB5_CC_NOMEM;
-
-    KCMCURSOR(*cursor) =3D tmp;
+    *cursor =3D c;
=20
     return 0;
 }
@@ -660,10 +617,17 @@
 {
     krb5_error_code ret;
     krb5_kcmcache *k =3D KCMCACHE(id);
+    krb5_kcm_cursor c =3D KCMCURSOR(*cursor);
     krb5_storage *request, *response;
     krb5_data response_data;
+    ssize_t sret;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_GET_NEXT, &request);
+ again:
+
+    if (c->offset >=3D c->length)
+	return KRB5_CC_END;
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_CRED_BY_UUID, &re=
quest);
     if (ret)
 	return ret;
=20
@@ -673,23 +637,26 @@
 	return ret;
     }
=20
-    ret =3D krb5_store_int32(request, KCMCURSOR(*cursor));
-    if (ret) {
+    sret =3D krb5_storage_write(request,
+			      &c->uuids[c->offset],
+			      sizeof(c->uuids[c->offset]));
+    c->offset++;
+    if (sret !=3D sizeof(c->uuids[c->offset])) {
 	krb5_storage_free(request);
-	return ret;
+	krb5_clear_error_message(context);
+	return ENOMEM;
     }
=20
-    ret =3D kcm_call(context, k, request, &response, &response_data);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
+    krb5_storage_free(request);
+    if (ret =3D=3D KRB5_CC_END) {
+	goto again;
     }
=20
     ret =3D krb5_ret_creds(response, creds);
     if (ret)
 	ret =3D KRB5_CC_IO;
=20
-    krb5_storage_free(request);
     krb5_storage_free(response);
     krb5_data_free(&response_data);
=20
@@ -709,39 +676,14 @@
 	     krb5_ccache id,
 	     krb5_cc_cursor *cursor)
 {
-    krb5_error_code ret;
-    krb5_kcmcache *k =3D KCMCACHE(id);
-    krb5_storage *request;
+    krb5_kcm_cursor c =3D KCMCURSOR(*cursor);
=20
-    ret =3D kcm_storage_request(context, KCM_OP_END_GET, &request);
-    if (ret)
-	return ret;
+    free(c->uuids);
+    free(c);
=20
-    ret =3D krb5_store_stringz(request, k->name);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
-
-    ret =3D krb5_store_int32(request, KCMCURSOR(*cursor));
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
-
-    ret =3D kcm_call(context, k, request, NULL, NULL);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
- =20
-    krb5_storage_free(request);
-
-    KCMCURSOR(*cursor) =3D 0;
-    free(*cursor);
     *cursor =3D NULL;
=20
-    return ret;
+    return 0;
 }
=20
 /*
@@ -763,7 +705,7 @@
     krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_REMOVE_CRED, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_REMOVE_CRED, &request=
);
     if (ret)
 	return ret;
=20
@@ -785,7 +727,7 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
     return ret;
@@ -800,7 +742,7 @@
     krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_SET_FLAGS, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_SET_FLAGS, &request);
     if (ret)
 	return ret;
=20
@@ -816,32 +758,342 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
+
+    krb5_storage_free(request);
+    return ret;
+}
+
+static int
+kcm_get_version(krb5_context context,
+		krb5_ccache id)
+{
+    return 0;
+}
+
+/*
+ * Send nothing
+ * get back list of uuids
+ */
+
+static krb5_error_code
+kcm_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
+{
+    krb5_error_code ret;
+    krb5_kcm_cursor c;
+    krb5_storage *request, *response;
+    krb5_data response_data;
+
+    *cursor =3D NULL;
+
+    c =3D calloc(1, sizeof(*c));
+    if (c =3D=3D NULL) {
+	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret,
+			       N_("malloc: out of memory", ""));
+	goto out;
+    }
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_CACHE_UUID_LIST, =
&request);
+    if (ret)
+	goto out;
+
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
+    krb5_storage_free(request);
+    if (ret)
+	goto out;
+
+    while (1) {
+	ssize_t sret;
+	kcmuuid_t uuid;
+	void *ptr;
+
+	sret =3D krb5_storage_read(response, &uuid, sizeof(uuid));
+	if (sret =3D=3D 0) {
+	    ret =3D 0;
+	    break;
+	} else if (sret !=3D sizeof(uuid)) {
+	    ret =3D EINVAL;
+	    goto out;
+	}
+
+	ptr =3D realloc(c->uuids, sizeof(c->uuids[0]) * (c->length + 1));
+	if (ptr =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
+	    goto out;
+	}
+	c->uuids =3D ptr;
+
+	memcpy(&c->uuids[c->length], &uuid, sizeof(uuid));
+	c->length +=3D 1;
+    }
+
+    krb5_storage_free(response);
+    krb5_data_free(&response_data);
+
+ out:
+    if (ret && c) {
+        free(c->uuids);
+        free(c);
+    } else
+	*cursor =3D c;
+
+    return ret;
+}
+
+/*
+ * Send uuid
+ * Recv cache name
+ */
+
+static krb5_error_code
+kcm_get_cache_next(krb5_context context, krb5_cc_cursor cursor, const krb5=
_cc_ops *ops, krb5_ccache *id)
+{
+    krb5_error_code ret;
+    krb5_kcm_cursor c =3D KCMCURSOR(cursor);
+    krb5_storage *request, *response;
+    krb5_data response_data;
+    ssize_t sret;
+    char *name;
+
+    *id =3D NULL;
+
+ again:
+
+    if (c->offset >=3D c->length)
+	return KRB5_CC_END;
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_CACHE_BY_UUID, &r=
equest);
+    if (ret)
+	return ret;
+
+    sret =3D krb5_storage_write(request,
+			      &c->uuids[c->offset],
+			      sizeof(c->uuids[c->offset]));
+    c->offset++;
+    if (sret !=3D sizeof(c->uuids[c->offset])) {
+	krb5_storage_free(request);
+	krb5_clear_error_message(context);
+	return ENOMEM;
+    }
+
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
+    krb5_storage_free(request);
+    if (ret =3D=3D KRB5_CC_END)
+	goto again;
+
+    ret =3D krb5_ret_stringz(response, &name);
+    krb5_storage_free(response);
+    krb5_data_free(&response_data);
+
+    if (ret =3D=3D 0) {
+	ret =3D _krb5_cc_allocate(context, ops, id);
+	if (ret =3D=3D 0)
+	    ret =3D kcm_alloc(context, name, id);
+	krb5_xfree(name);
+    }
+
+    return ret;
+}
+
+static krb5_error_code
+kcm_get_cache_next_kcm(krb5_context context, krb5_cc_cursor cursor, krb5_c=
cache *id)
+{
+#ifndef KCM_IS_API_CACHE
+    return kcm_get_cache_next(context, cursor, &krb5_kcm_ops, id);
+#else
+    return KRB5_CC_END;
+#endif
+}
+
+static krb5_error_code
+kcm_get_cache_next_api(krb5_context context, krb5_cc_cursor cursor, krb5_c=
cache *id)
+{
+    return kcm_get_cache_next(context, cursor, &krb5_akcm_ops, id);
+}
+
+
+static krb5_error_code
+kcm_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
+{
+    krb5_kcm_cursor c =3D KCMCURSOR(cursor);
+
+    free(c->uuids);
+    free(c);
+    return 0;
+}
+
+
+static krb5_error_code
+kcm_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+{
+    krb5_error_code ret;
+    krb5_kcmcache *oldk =3D KCMCACHE(from);
+    krb5_kcmcache *newk =3D KCMCACHE(to);
+    krb5_storage *request;
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_MOVE_CACHE, &request);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_store_stringz(request, oldk->name);
+    if (ret) {
+	krb5_storage_free(request);
+	return ret;
+    }
+
+    ret =3D krb5_store_stringz(request, newk->name);
+    if (ret) {
+	krb5_storage_free(request);
+	return ret;
+    }
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
     return ret;
 }
=20
 static krb5_error_code
-kcm_get_version(krb5_context context,
-		krb5_ccache id)
+kcm_get_default_name(krb5_context context, const krb5_cc_ops *ops,
+		     const char *defstr, char **str)
 {
+    krb5_error_code ret;
+    krb5_storage *request, *response;
+    krb5_data response_data;
+    char *name;
+
+    *str =3D NULL;
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_DEFAULT_CACHE, &r=
equest);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
+    krb5_storage_free(request);
+    if (ret)
+	return _krb5_expand_default_cc_name(context, defstr, str);
+
+    ret =3D krb5_ret_stringz(response, &name);
+    krb5_storage_free(response);
+    krb5_data_free(&response_data);
+    if (ret)
+	return ret;
+
+    asprintf(str, "%s:%s", ops->prefix, name);
+    free(name);
+    if (str =3D=3D NULL)
+	return ENOMEM;
+
     return 0;
 }
=20
 static krb5_error_code
-kcm_move(krb5_context context, krb5_ccache from, krb5_ccache to)
+kcm_get_default_name_api(krb5_context context, char **str)
 {
-    krb5_set_error_string(context, "kcm_move not implemented");
-    return EINVAL;
+    return kcm_get_default_name(context, &krb5_akcm_ops,
+				KRB5_DEFAULT_CCNAME_KCM_API, str);
 }
=20
 static krb5_error_code
-kcm_default_name(krb5_context context, char **str)
+kcm_get_default_name_kcm(krb5_context context, char **str)
 {
-    return _krb5_expand_default_cc_name(context,=20
-					KRB5_DEFAULT_CCNAME_KCM,
-					str);
+    return kcm_get_default_name(context, &krb5_kcm_ops,
+				KRB5_DEFAULT_CCNAME_KCM_KCM, str);
+}
+
+static krb5_error_code
+kcm_set_default(krb5_context context, krb5_ccache id)
+{
+    krb5_error_code ret;
+    krb5_storage *request;
+    krb5_kcmcache *k =3D KCMCACHE(id);
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_SET_DEFAULT_CACHE, &r=
equest);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_store_stringz(request, k->name);
+    if (ret) {
+	krb5_storage_free(request);
+	return ret;
+    }
+
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
+    krb5_storage_free(request);
+
+    return ret;
+}
+
+static krb5_error_code
+kcm_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+    *mtime =3D time(NULL);
+    return 0;
+}
+
+static krb5_error_code
+kcm_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_o=
ffset)
+{
+    krb5_kcmcache *k =3D KCMCACHE(id);
+    krb5_error_code ret;
+    krb5_storage *request;
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_SET_KDC_OFFSET, &requ=
est);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_store_stringz(request, k->name);
+    if (ret) {
+	krb5_storage_free(request);
+	return ret;
+    }
+    ret =3D krb5_store_int32(request, kdc_offset);
+    if (ret) {
+	krb5_storage_free(request);
+	return ret;
+    }
+
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
+    krb5_storage_free(request);
+
+    return ret;
+}
+
+static krb5_error_code
+kcm_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_=
offset)
+{
+    krb5_kcmcache *k =3D KCMCACHE(id);
+    krb5_error_code ret;
+    krb5_storage *request, *response;
+    krb5_data response_data;
+    int32_t offset;
+
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_KDC_OFFSET, &requ=
est);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_store_stringz(request, k->name);
+    if (ret) {
+	krb5_storage_free(request);
+	return ret;
+    }
+
+    ret =3D krb5_kcm_call(context, request, &response, &response_data);
+    krb5_storage_free(request);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_ret_int32(response, &offset);
+    krb5_storage_free(response);
+    krb5_data_free(&response_data);
+    if (ret)
+	return ret;
+
+    *kdc_offset =3D offset;
+
+    return 0;
 }
=20
 /**
@@ -850,7 +1102,8 @@
  * @ingroup krb5_ccache
  */
=20
-const krb5_cc_ops krb5_kcm_ops =3D {
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_kcm_ops =3D {
+    KRB5_CC_OPS_VERSION,
     "KCM",
     kcm_get_name,
     kcm_resolve,
@@ -859,7 +1112,7 @@
     kcm_destroy,
     kcm_close,
     kcm_store_cred,
-    kcm_retrieve,
+    NULL /* kcm_retrieve */,
     kcm_get_principal,
     kcm_get_first,
     kcm_get_next,
@@ -867,14 +1120,48 @@
     kcm_remove_cred,
     kcm_set_flags,
     kcm_get_version,
-    NULL,
-    NULL,
-    NULL,
+    kcm_get_cache_first,
+    kcm_get_cache_next_kcm,
+    kcm_end_cache_get,
     kcm_move,
-    kcm_default_name
+    kcm_get_default_name_kcm,
+    kcm_set_default,
+    kcm_lastchange,
+    kcm_set_kdc_offset,
+    kcm_get_kdc_offset
 };
=20
-krb5_boolean
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_akcm_ops =3D {
+    KRB5_CC_OPS_VERSION,
+    "API",
+    kcm_get_name,
+    kcm_resolve,
+    kcm_gen_new,
+    kcm_initialize,
+    kcm_destroy,
+    kcm_close,
+    kcm_store_cred,
+    NULL /* kcm_retrieve */,
+    kcm_get_principal,
+    kcm_get_first,
+    kcm_get_next,
+    kcm_end_get,
+    kcm_remove_cred,
+    kcm_set_flags,
+    kcm_get_version,
+    kcm_get_cache_first,
+    kcm_get_cache_next_api,
+    kcm_end_cache_get,
+    kcm_move,
+    kcm_get_default_name_api,
+    kcm_set_default,
+    kcm_lastchange,
+    NULL,
+    NULL
+};
+
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 _krb5_kcm_is_running(krb5_context context)
 {
     krb5_error_code ret;
@@ -899,107 +1186,18 @@
  * Response:
  *
  */
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_kcm_noop(krb5_context context,
 	       krb5_ccache id)
 {
     krb5_error_code ret;
-    krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_NOOP, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_NOOP, &request);
     if (ret)
 	return ret;
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
-
-    krb5_storage_free(request);
-    return ret;
-}
-
-
-/*
- * Request:
- *      NameZ
- *      Mode
- *
- * Response:
- *
- */
-krb5_error_code
-_krb5_kcm_chmod(krb5_context context,
-		krb5_ccache id,
-		uint16_t mode)
-{
-    krb5_error_code ret;
-    krb5_kcmcache *k =3D KCMCACHE(id);
-    krb5_storage *request;
-
-    ret =3D kcm_storage_request(context, KCM_OP_CHMOD, &request);
-    if (ret)
-	return ret;
-
-    ret =3D krb5_store_stringz(request, k->name);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
-
-    ret =3D krb5_store_int16(request, mode);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
-
-    ret =3D kcm_call(context, k, request, NULL, NULL);
-
-    krb5_storage_free(request);
-    return ret;
-}
-
-
-/*
- * Request:
- *      NameZ
- *      UID
- *      GID
- *
- * Response:
- *
- */
-krb5_error_code
-_krb5_kcm_chown(krb5_context context,
-		krb5_ccache id,
-		uint32_t uid,
-		uint32_t gid)
-{
-    krb5_error_code ret;
-    krb5_kcmcache *k =3D KCMCACHE(id);
-    krb5_storage *request;
-
-    ret =3D kcm_storage_request(context, KCM_OP_CHOWN, &request);
-    if (ret)
-	return ret;
-
-    ret =3D krb5_store_stringz(request, k->name);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
-
-    ret =3D krb5_store_int32(request, uid);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
-
-    ret =3D krb5_store_int32(request, gid);
-    if (ret) {
-	krb5_storage_free(request);
-	return ret;
-    }
-
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
     return ret;
@@ -1016,17 +1214,17 @@
  * Repsonse:
  *
  */
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_kcm_get_initial_ticket(krb5_context context,
 			     krb5_ccache id,
 			     krb5_principal server,
 			     krb5_keyblock *key)
 {
+    krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_error_code ret;
-    krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_GET_INITIAL_TICKET, &reque=
st);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_INITIAL_TICKET, &=
request);
     if (ret)
 	return ret;
=20
@@ -1056,7 +1254,7 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
     return ret;
@@ -1073,7 +1271,7 @@
  * Repsonse:
  *
  */
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_kcm_get_ticket(krb5_context context,
 		     krb5_ccache id,
 		     krb5_kdc_flags flags,
@@ -1084,7 +1282,7 @@
     krb5_kcmcache *k =3D KCMCACHE(id);
     krb5_storage *request;
=20
-    ret =3D kcm_storage_request(context, KCM_OP_GET_TICKET, &request);
+    ret =3D krb5_kcm_storage_request(context, KCM_OP_GET_TICKET, &request);
     if (ret)
 	return ret;
=20
@@ -1112,11 +1310,10 @@
 	return ret;
     }
=20
-    ret =3D kcm_call(context, k, request, NULL, NULL);
+    ret =3D krb5_kcm_call(context, request, NULL, NULL);
=20
     krb5_storage_free(request);
     return ret;
 }
=20
-
 #endif /* HAVE_KCM */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/kcm.h
--- a/head/crypto/heimdal/lib/krb5/kcm.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/kcm.h	Tue Apr 17 11:51:51 2012 +0300
@@ -2,6 +2,8 @@
  * Copyright (c) 2005, PADL Software Pty Ltd.
  * All rights reserved.
  *
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
@@ -37,9 +39,11 @@
  * KCM protocol definitions
  */
=20
-#define KCM_PROTOCOL_VERSION_MAJOR	1
+#define KCM_PROTOCOL_VERSION_MAJOR	2
 #define KCM_PROTOCOL_VERSION_MINOR	0
=20
+typedef unsigned char kcmuuid_t[16];
+
 typedef enum kcm_operation {
     KCM_OP_NOOP,
     KCM_OP_GET_NAME,
@@ -50,20 +54,37 @@
     KCM_OP_STORE,
     KCM_OP_RETRIEVE,
     KCM_OP_GET_PRINCIPAL,
-    KCM_OP_GET_FIRST,
-    KCM_OP_GET_NEXT,
-    KCM_OP_END_GET,
+    KCM_OP_GET_CRED_UUID_LIST,
+    KCM_OP_GET_CRED_BY_UUID,
     KCM_OP_REMOVE_CRED,
     KCM_OP_SET_FLAGS,
     KCM_OP_CHOWN,
     KCM_OP_CHMOD,
     KCM_OP_GET_INITIAL_TICKET,
     KCM_OP_GET_TICKET,
+    KCM_OP_MOVE_CACHE,
+    KCM_OP_GET_CACHE_UUID_LIST,
+    KCM_OP_GET_CACHE_BY_UUID,
+    KCM_OP_GET_DEFAULT_CACHE,
+    KCM_OP_SET_DEFAULT_CACHE,
+    KCM_OP_GET_KDC_OFFSET,
+    KCM_OP_SET_KDC_OFFSET,
+    /* NTLM operations */
+    KCM_OP_ADD_NTLM_CRED,
+    KCM_OP_HAVE_NTLM_CRED,
+    KCM_OP_DEL_NTLM_CRED,
+    KCM_OP_DO_NTLM_AUTH,
+    KCM_OP_GET_NTLM_USER_LIST,
     KCM_OP_MAX
 } kcm_operation;
=20
 #define _PATH_KCM_SOCKET      "/var/run/.kcm_socket"
 #define _PATH_KCM_DOOR      "/var/run/.kcm_door"
=20
+#define KCM_NTLM_FLAG_SESSIONKEY 1
+#define KCM_NTLM_FLAG_NTLM2_SESSION 2
+#define KCM_NTLM_FLAG_KEYEX 4
+#define KCM_NTLM_FLAG_AV_GUEST 8
+
 #endif /* __KCM_H__ */
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/kerberos.8
--- a/head/crypto/heimdal/lib/krb5/kerberos.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/kerberos.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: kerberos.8 16121 2005-10-03 14:24:36Z lha $
+.\" $Id$
 .\"
 .Dd September 1, 2000
 .Dt KERBEROS 8
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/keyblock.c
--- a/head/crypto/heimdal/lib/krb5/keyblock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/keyblock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,48 +1,63 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: keyblock.c 15167 2005-05-18 04:21:57Z lha $");
+/**
+ * Zero out a keyblock
+ *
+ * @param keyblock keyblock to zero out
+ *
+ * @ingroup krb5_crypto
+ */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_keyblock_zero(krb5_keyblock *keyblock)
 {
     keyblock->keytype =3D 0;
     krb5_data_zero(&keyblock->keyvalue);
 }
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Free a keyblock's content, also zero out the content of the keyblock.
+ *
+ * @param context a Kerberos 5 context
+ * @param keyblock keyblock content to free, NULL is valid argument
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_keyblock_contents(krb5_context context,
 			    krb5_keyblock *keyblock)
 {
@@ -54,7 +69,17 @@
     }
 }
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Free a keyblock, also zero out the content of the keyblock, uses
+ * krb5_free_keyblock_contents() to free the content.
+ *
+ * @param context a Kerberos 5 context
+ * @param keyblock keyblock to free, NULL is valid argument
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_keyblock(krb5_context context,
 		   krb5_keyblock *keyblock)
 {
@@ -64,7 +89,20 @@
     }
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Copy a keyblock, free the output keyblock with
+ * krb5_free_keyblock_contents().
+ *
+ * @param context a Kerberos 5 context
+ * @param inblock the key to copy
+ * @param to the output key.
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_keyblock_contents (krb5_context context,
 			     const krb5_keyblock *inblock,
 			     krb5_keyblock *to)
@@ -72,34 +110,67 @@
     return copy_EncryptionKey(inblock, to);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Copy a keyblock, free the output keyblock with
+ * krb5_free_keyblock().
+ *
+ * @param context a Kerberos 5 context
+ * @param inblock the key to copy
+ * @param to the output key.
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+ * @ingroup krb5_crypto
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_keyblock (krb5_context context,
 		    const krb5_keyblock *inblock,
 		    krb5_keyblock **to)
 {
+    krb5_error_code ret;
     krb5_keyblock *k;
=20
-    k =3D malloc (sizeof(*k));
+    *to =3D NULL;
+
+    k =3D calloc (1, sizeof(*k));
     if (k =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
+
+    ret =3D krb5_copy_keyblock_contents (context, inblock, k);
+    if (ret) {
+      free(k);
+      return ret;
+    }
     *to =3D k;
-    return krb5_copy_keyblock_contents (context, inblock, k);
+    return 0;
 }
=20
-krb5_enctype
+/**
+ * Get encryption type of a keyblock.
+ *
+ * @ingroup krb5_crypto
+ */
+
+KRB5_LIB_FUNCTION krb5_enctype KRB5_LIB_CALL
 krb5_keyblock_get_enctype(const krb5_keyblock *block)
 {
     return block->keytype;
 }
=20
-/*
+/**
  * Fill in `key' with key data of type `enctype' from `data' of length
- * `size'. Key should be freed using krb5_free_keyblock_contents.
+ * `size'. Key should be freed using krb5_free_keyblock_contents().
+ *
+ * @return 0 on success or a Kerberos 5 error code
+ *
+ * @ingroup krb5_crypto
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_keyblock_init(krb5_context context,
 		   krb5_enctype type,
 		   const void *data,
@@ -116,15 +187,15 @@
 	return ret;
=20
     if (len !=3D size) {
-	krb5_set_error_string(context, "Encryption key %d is %lu bytes "
-			      "long, %lu was passed in",
-			      type, (unsigned long)len, (unsigned long)size);
+	krb5_set_error_message(context, KRB5_PROG_ETYPE_NOSUPP,
+			       "Encryption key %d is %lu bytes "
+			       "long, %lu was passed in",
+			       type, (unsigned long)len, (unsigned long)size);
 	return KRB5_PROG_ETYPE_NOSUPP;
     }
     ret =3D krb5_data_copy(&key->keyvalue, data, len);
     if(ret) {
-	krb5_set_error_string(context, "malloc failed: %lu",
-			      (unsigned long)len);
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	return ret;
     }
     key->keytype =3D type;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/keytab.c
--- a/head/crypto/heimdal/lib/krb5/keytab.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/keytab.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,60 +1,161 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: keytab.c 20211 2007-02-09 07:11:03Z lha $");
+/**
+ * @page krb5_keytab_intro The keytab handing functions
+ * @section section_krb5_keytab Kerberos Keytabs
+ *
+ * See the library functions here: @ref krb5_keytab
+ *
+ * Keytabs are long term key storage for servers, their equvalment of
+ * password files.
+ *
+ * Normally the only function that useful for server are to specify
+ * what keytab to use to other core functions like krb5_rd_req()
+ * krb5_kt_resolve(), and krb5_kt_close().
+ *
+ * @subsection krb5_keytab_names Keytab names
+ *
+ * A keytab name is on the form type:residual. The residual part is
+ * specific to each keytab-type.
+ *
+ * When a keytab-name is resolved, the type is matched with an internal
+ * list of keytab types. If there is no matching keytab type,
+ * the default keytab is used. The current default type is FILE.
+ *
+ * The default value can be changed in the configuration file
+ * /etc/krb5.conf by setting the variable
+ * [defaults]default_keytab_name.
+ *
+ * The keytab types that are implemented in Heimdal are:
+ * - file
+ *   store the keytab in a file, the type's name is FILE .  The
+ *   residual part is a filename. For compatibility with other
+ *   Kerberos implemtation WRFILE and JAVA14 is also accepted.  WRFILE
+ *   has the same format as FILE. JAVA14 have a format that is
+ *   compatible with older versions of MIT kerberos and SUN's Java
+ *   based installation.  They store a truncted kvno, so when the knvo
+ *   excess 255, they are truncted in this format.
+ *
+ * - keytab
+ *   store the keytab in a AFS keyfile (usually /usr/afs/etc/KeyFile ),
+ *   the type's name is AFSKEYFILE. The residual part is a filename.
+ *
+ * - memory
+ *   The keytab is stored in a memory segment. This allows sensitive
+ *   and/or temporary data not to be stored on disk. The type's name
+ *   is MEMORY. Each MEMORY keytab is referenced counted by and
+ *   opened by the residual name, so two handles can point to the
+ *   same memory area.  When the last user closes using krb5_kt_close()
+ *   the keytab, the keys in they keytab is memset() to zero and freed
+ *   and can no longer be looked up by name.
+ *
+ *
+ * @subsection krb5_keytab_example Keytab example
+ *
+ *  This is a minimalistic version of ktutil.
+ *
+ * @code
+int
+main (int argc, char **argv)
+{
+    krb5_context context;
+    krb5_keytab keytab;
+    krb5_kt_cursor cursor;
+    krb5_keytab_entry entry;
+    krb5_error_code ret;
+    char *principal;
=20
-/*
- * Register a new keytab in `ops'
- * Return 0 or an error.
+    if (krb5_init_context (&context) !=3D 0)
+	errx(1, "krb5_context");
+
+    ret =3D krb5_kt_default (context, &keytab);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_kt_default");
+
+    ret =3D krb5_kt_start_seq_get(context, keytab, &cursor);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_kt_start_seq_get");
+    while((ret =3D krb5_kt_next_entry(context, keytab, &entry, &cursor)) =
=3D=3D 0){
+	krb5_unparse_name(context, entry.principal, &principal);
+	printf("principal: %s\n", principal);
+	free(principal);
+	krb5_kt_free_entry(context, &entry);
+    }
+    ret =3D krb5_kt_end_seq_get(context, keytab, &cursor);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_kt_end_seq_get");
+    ret =3D krb5_kt_close(context, keytab);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_kt_close");
+    krb5_free_context(context);
+    return 0;
+}
+ * @endcode
+ *
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+
+/**
+ * Register a new keytab backend.
+ *
+ * @param context a Keberos context.
+ * @param ops a backend to register.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_register(krb5_context context,
 		 const krb5_kt_ops *ops)
 {
     struct krb5_keytab_data *tmp;
=20
     if (strlen(ops->prefix) > KRB5_KT_PREFIX_MAX_LEN - 1) {
-	krb5_set_error_string(context, "krb5_kt_register; prefix too long");
+	krb5_set_error_message(context, KRB5_KT_BADNAME,
+			       N_("can't register cache type, prefix too long", ""));
 	return KRB5_KT_BADNAME;
     }
=20
     tmp =3D realloc(context->kt_types,
 		  (context->num_kt_types + 1) * sizeof(*context->kt_types));
     if(tmp =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memcpy(&tmp[context->num_kt_types], ops,
@@ -64,13 +165,49 @@
     return 0;
 }
=20
-/*
+static const char *
+keytab_name(const char *name, const char **type, size_t *type_len)
+{
+    const char *residual;
+
+    residual =3D strchr(name, ':');
+
+    if (residual =3D=3D NULL ||
+	name[0] =3D=3D '/'
+#ifdef _WIN32
+        /* Avoid treating <drive>:<path> as a keytab type
+         * specification */
+        || name + 1 =3D=3D residual
+#endif
+        ) {
+
+        *type =3D "FILE";
+        *type_len =3D strlen(*type);
+        residual =3D name;
+    } else {
+        *type =3D name;
+        *type_len =3D residual - name;
+        residual++;
+    }
+
+    return residual;
+}
+
+/**
  * Resolve the keytab name (of the form `type:residual') in `name'
  * into a keytab in `id'.
- * Return 0 or an error
+ *
+ * @param context a Keberos context.
+ * @param name name to resolve
+ * @param id resulting keytab, free with krb5_kt_close().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_resolve(krb5_context context,
 		const char *name,
 		krb5_keytab *id)
@@ -81,30 +218,22 @@
     size_t type_len;
     krb5_error_code ret;
=20
-    residual =3D strchr(name, ':');
-    if(residual =3D=3D NULL) {
-	type =3D "FILE";
-	type_len =3D strlen(type);
-	residual =3D name;
-    } else {
-	type =3D name;
-	type_len =3D residual - name;
-	residual++;
-    }
-   =20
+    residual =3D keytab_name(name, &type, &type_len);
+
     for(i =3D 0; i < context->num_kt_types; i++) {
 	if(strncasecmp(type, context->kt_types[i].prefix, type_len) =3D=3D 0)
 	    break;
     }
     if(i =3D=3D context->num_kt_types) {
-	krb5_set_error_string(context, "unknown keytab type %.*s",=20
-			      (int)type_len, type);
+	krb5_set_error_message(context, KRB5_KT_UNKNOWN_TYPE,
+			       N_("unknown keytab type %.*s", "type"),
+			       (int)type_len, type);
 	return KRB5_KT_UNKNOWN_TYPE;
     }
-   =20
+
     k =3D malloc (sizeof(*k));
     if (k =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memcpy(k, &context->kt_types[i], sizeof(*k));
@@ -118,27 +247,41 @@
     return ret;
 }
=20
-/*
+/**
  * copy the name of the default keytab into `name'.
- * Return 0 or KRB5_CONFIG_NOTENUFSPACE if `namesize' is too short.
+ *
+ * @param context a Keberos context.
+ * @param name buffer where the name will be written
+ * @param namesize length of name
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_default_name(krb5_context context, char *name, size_t namesize)
 {
     if (strlcpy (name, context->default_keytab, namesize) >=3D namesize) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_CONFIG_NOTENUFSPACE;
     }
     return 0;
 }
=20
-/*
- * copy the name of the default modify keytab into `name'.
- * Return 0 or KRB5_CONFIG_NOTENUFSPACE if `namesize' is too short.
+/**
+ * Copy the name of the default modify keytab into `name'.
+ *
+ * @param context a Keberos context.
+ * @param name buffer where the name will be written
+ * @param namesize length of name
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_default_modify_name(krb5_context context, char *name, size_t names=
ize)
 {
     const char *kt =3D NULL;
@@ -148,40 +291,56 @@
 	else {
 	    size_t len =3D strcspn(context->default_keytab + 4, ",");
 	    if(len >=3D namesize) {
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		return KRB5_CONFIG_NOTENUFSPACE;
 	    }
 	    strlcpy(name, context->default_keytab + 4, namesize);
 	    name[len] =3D '\0';
 	    return 0;
-	}   =20
+	}
     } else
 	kt =3D context->default_keytab_modify;
     if (strlcpy (name, kt, namesize) >=3D namesize) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_CONFIG_NOTENUFSPACE;
     }
     return 0;
 }
=20
-/*
+/**
  * Set `id' to the default keytab.
- * Return 0 or an error.
+ *
+ * @param context a Keberos context.
+ * @param id the new default keytab.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_default(krb5_context context, krb5_keytab *id)
 {
     return krb5_kt_resolve (context, context->default_keytab, id);
 }
=20
-/*
+/**
  * Read the key identified by `(principal, vno, enctype)' from the
  * keytab in `keyprocarg' (the default if =3D=3D NULL) into `*key'.
- * Return 0 or an error.
+ *
+ * @param context a Keberos context.
+ * @param keyprocarg
+ * @param principal
+ * @param vno
+ * @param enctype
+ * @param key
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_read_service_key(krb5_context context,
 			 krb5_pointer keyprocarg,
 			 krb5_principal principal,
@@ -210,12 +369,21 @@
     return ret;
 }
=20
-/*
+/**
  * Return the type of the `keytab' in the string `prefix of length
  * `prefixsize'.
+ *
+ * @param context a Keberos context.
+ * @param keytab the keytab to get the prefix for
+ * @param prefix prefix buffer
+ * @param prefixsize length of prefix buffer
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_get_type(krb5_context context,
 		 krb5_keytab keytab,
 		 char *prefix,
@@ -225,13 +393,21 @@
     return 0;
 }
=20
-/*
+/**
  * Retrieve the name of the keytab `keytab' into `name', `namesize'
- * Return 0 or an error.
+ *
+ * @param context a Keberos context.
+ * @param keytab the keytab to get the name for.
+ * @param name name buffer.
+ * @param namesize size of name buffer.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_kt_get_name(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_get_name(krb5_context context,
 		 krb5_keytab keytab,
 		 char *name,
 		 size_t namesize)
@@ -239,21 +415,29 @@
     return (*keytab->get_name)(context, keytab, name, namesize);
 }
=20
-/*
+/**
  * Retrieve the full name of the keytab `keytab' and store the name in
- * `str'. `str' needs to be freed by the caller using free(3).
- * Returns 0 or an error. On error, *str is set to NULL.
+ * `str'.
+ *
+ * @param context a Keberos context.
+ * @param keytab keytab to get name for.
+ * @param str the name of the keytab name, usee krb5_xfree() to free
+ *        the string.  On error, *str is set to NULL.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_kt_get_full_name(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_get_full_name(krb5_context context,
 		      krb5_keytab keytab,
 		      char **str)
 {
     char type[KRB5_KT_PREFIX_MAX_LEN];
     char name[MAXPATHLEN];
     krb5_error_code ret;
-	     =20
+
     *str =3D NULL;
=20
     ret =3D krb5_kt_get_type(context, keytab, type, sizeof(type));
@@ -265,7 +449,7 @@
 	return ret;
=20
     if (asprintf(str, "%s:%s", type, name) =3D=3D -1) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	*str =3D NULL;
 	return ENOMEM;
     }
@@ -273,13 +457,20 @@
     return 0;
 }
=20
-/*
+/**
  * Finish using the keytab in `id'.  All resources will be released,
- * even on errors.  Return 0 or an error.
+ * even on errors.
+ *
+ * @param context a Keberos context.
+ * @param id keytab to close.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_kt_close(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_close(krb5_context context,
 	      krb5_keytab id)
 {
     krb5_error_code ret;
@@ -290,21 +481,73 @@
     return ret;
 }
=20
+/**
+ * Destroy (remove) the keytab in `id'.  All resources will be released,
+ * even on errors, does the equvalment of krb5_kt_close() on the resources.
+ *
+ * @param context a Keberos context.
+ * @param id keytab to destroy.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_destroy(krb5_context context,
+		krb5_keytab id)
+{
+    krb5_error_code ret;
+
+    ret =3D (*id->destroy)(context, id);
+    krb5_kt_close(context, id);
+    return ret;
+}
+
 /*
+ * Match any aliases in keytab `entry' with `principal'.
+ */
+
+static krb5_boolean
+compare_aliseses(krb5_context context,
+		 krb5_keytab_entry *entry,
+		 krb5_const_principal principal)
+{
+    unsigned int i;
+    if (entry->aliases =3D=3D NULL)
+	return FALSE;
+    for (i =3D 0; i < entry->aliases->len; i++)
+	if (krb5_principal_compare(context, &entry->aliases->val[i], principal))
+	    return TRUE;
+    return FALSE;
+}
+
+/**
  * Compare `entry' against `principal, vno, enctype'.
  * Any of `principal, vno, enctype' might be 0 which acts as a wildcard.
  * Return TRUE if they compare the same, FALSE otherwise.
+ *
+ * @param context a Keberos context.
+ * @param entry an entry to match with.
+ * @param principal principal to match, NULL matches all principals.
+ * @param vno key version to match, 0 matches all key version numbers.
+ * @param enctype encryption type to match, 0 matches all encryption types.
+ *
+ * @return Return TRUE or match, FALSE if not matched.
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_kt_compare(krb5_context context,
-		krb5_keytab_entry *entry,=20
+		krb5_keytab_entry *entry,
 		krb5_const_principal principal,
 		krb5_kvno vno,
 		krb5_enctype enctype)
 {
-    if(principal !=3D NULL &&=20
-       !krb5_principal_compare(context, entry->principal, principal))
+    if(principal !=3D NULL &&
+       !(krb5_principal_compare(context, entry->principal, principal) ||
+	 compare_aliseses(context, entry, principal)))
 	return FALSE;
     if(vno && vno !=3D entry->vno)
 	return FALSE;
@@ -313,14 +556,56 @@
     return TRUE;
 }
=20
-/*
+krb5_error_code
+_krb5_kt_principal_not_found(krb5_context context,
+			     krb5_error_code ret,
+			     krb5_keytab id,
+			     krb5_const_principal principal,
+			     krb5_enctype enctype,
+			     int kvno)
+{
+    char princ[256], kvno_str[25], *kt_name;
+    char *enctype_str =3D NULL;
+
+    krb5_unparse_name_fixed (context, principal, princ, sizeof(princ));
+    krb5_kt_get_full_name (context, id, &kt_name);
+    krb5_enctype_to_string(context, enctype, &enctype_str);
+
+    if (kvno)
+	snprintf(kvno_str, sizeof(kvno_str), "(kvno %d)", kvno);
+    else
+	kvno_str[0] =3D '\0';
+
+    krb5_set_error_message (context, ret,
+			    N_("Failed to find %s%s in keytab %s (%s)",
+			       "principal, kvno, keytab file, enctype"),
+			    princ,
+			    kvno_str,
+			    kt_name ? kt_name : "unknown keytab",
+			    enctype_str ? enctype_str : "unknown enctype");
+    free(kt_name);
+    free(enctype_str);
+    return ret;
+}
+
+
+/**
  * Retrieve the keytab entry for `principal, kvno, enctype' into `entry'
- * from the keytab `id'.
- * kvno =3D=3D 0 is a wildcard and gives the keytab with the highest vno.
- * Return 0 or an error.
+ * from the keytab `id'. Matching is done like krb5_kt_compare().
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param principal principal to match, NULL matches all principals.
+ * @param kvno key version to match, 0 matches all key version numbers.
+ * @param enctype encryption type to match, 0 matches all encryption types.
+ * @param entry the returned entry, free with krb5_kt_free_entry().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_get_entry(krb5_context context,
 		  krb5_keytab id,
 		  krb5_const_principal principal,
@@ -337,8 +622,10 @@
=20
     ret =3D krb5_kt_start_seq_get (context, id, &cursor);
     if (ret) {
-	krb5_clear_error_string(context);
-	return KRB5_KT_NOTFOUND; /* XXX i.e. file not found */
+	/* This is needed for krb5_verify_init_creds, but keep error
+	 * string from previous error for the human. */
+	context->error_code =3D KRB5_KT_NOTFOUND;
+	return KRB5_KT_NOTFOUND;
     }
=20
     entry->vno =3D 0;
@@ -361,38 +648,25 @@
 	krb5_kt_free_entry(context, &tmp);
     }
     krb5_kt_end_seq_get (context, id, &cursor);
-    if (entry->vno) {
-	return 0;
-    } else {
-	char princ[256], kvno_str[25], *kt_name;
-	char *enctype_str =3D NULL;
-
-	krb5_unparse_name_fixed (context, principal, princ, sizeof(princ));
-	krb5_kt_get_full_name (context, id, &kt_name);
-	krb5_enctype_to_string(context, enctype, &enctype_str);
-
-	if (kvno)
-	    snprintf(kvno_str, sizeof(kvno_str), "(kvno %d)", kvno);
-	else
-	    kvno_str[0] =3D '\0';
-
-	krb5_set_error_string (context,
- 			       "Failed to find %s%s in keytab %s (%s)",
-			       princ,
-			       kvno_str,
-			       kt_name ? kt_name : "unknown keytab",
-			       enctype_str ? enctype_str : "unknown enctype");
-	free(kt_name);
-	free(enctype_str);
-	return KRB5_KT_NOTFOUND;
-    }
+    if (entry->vno =3D=3D 0)
+	return _krb5_kt_principal_not_found(context, KRB5_KT_NOTFOUND,
+					    id, principal, enctype, kvno);
+    return 0;
 }
=20
-/*
+/**
  * Copy the contents of `in' into `out'.
- * Return 0 or an error.  */
+ *
+ * @param context a Keberos context.
+ * @param in the keytab entry to copy.
+ * @param out the copy of the keytab entry, free with krb5_kt_free_entry().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_copy_entry_contents(krb5_context context,
 			    const krb5_keytab_entry *in,
 			    krb5_keytab_entry *out)
@@ -417,11 +691,18 @@
     return ret;
 }
=20
-/*
+/**
  * Free the contents of `entry'.
+ *
+ * @param context a Keberos context.
+ * @param entry the entry to free
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_free_entry(krb5_context context,
 		   krb5_keytab_entry *entry)
 {
@@ -431,98 +712,182 @@
     return 0;
 }
=20
-/*
+/**
  * Set `cursor' to point at the beginning of `id'.
- * Return 0 or an error.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param cursor a newly allocated cursor, free with krb5_kt_end_seq_get().
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_start_seq_get(krb5_context context,
 		      krb5_keytab id,
 		      krb5_kt_cursor *cursor)
 {
     if(id->start_seq_get =3D=3D NULL) {
-	krb5_set_error_string(context,
-			      "start_seq_get is not supported in the %s "
-			      " keytab", id->prefix);
+	krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP,
+			       N_("start_seq_get is not supported "
+				  "in the %s keytab type", ""),
+			       id->prefix);
 	return HEIM_ERR_OPNOTSUPP;
     }
     return (*id->start_seq_get)(context, id, cursor);
 }
=20
-/*
- * Get the next entry from `id' pointed to by `cursor' and advance the
- * `cursor'.
- * Return 0 or an error.
+/**
+ * Get the next entry from keytab, advance the cursor.  On last entry
+ * the function will return KRB5_KT_END.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param entry the returned entry, free with krb5_kt_free_entry().
+ * @param cursor the cursor of the iteration.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_next_entry(krb5_context context,
 		   krb5_keytab id,
 		   krb5_keytab_entry *entry,
 		   krb5_kt_cursor *cursor)
 {
     if(id->next_entry =3D=3D NULL) {
-	krb5_set_error_string(context,
-			      "next_entry is not supported in the %s "
-			      " keytab", id->prefix);
+	krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP,
+			       N_("next_entry is not supported in the %s "
+				  " keytab", ""),
+			       id->prefix);
 	return HEIM_ERR_OPNOTSUPP;
     }
     return (*id->next_entry)(context, id, entry, cursor);
 }
=20
-/*
+/**
  * Release all resources associated with `cursor'.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param cursor the cursor to free.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_end_seq_get(krb5_context context,
 		    krb5_keytab id,
 		    krb5_kt_cursor *cursor)
 {
     if(id->end_seq_get =3D=3D NULL) {
-	krb5_set_error_string(context,
-			      "end_seq_get is not supported in the %s "
-			      " keytab", id->prefix);
+	krb5_set_error_message(context, HEIM_ERR_OPNOTSUPP,
+			       "end_seq_get is not supported in the %s "
+			       " keytab", id->prefix);
 	return HEIM_ERR_OPNOTSUPP;
     }
     return (*id->end_seq_get)(context, id, cursor);
 }
=20
-/*
+/**
  * Add the entry in `entry' to the keytab `id'.
- * Return 0 or an error.
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param entry the entry to add
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_add_entry(krb5_context context,
 		  krb5_keytab id,
 		  krb5_keytab_entry *entry)
 {
     if(id->add =3D=3D NULL) {
-	krb5_set_error_string(context, "Add is not supported in the %s keytab",
-			      id->prefix);
+	krb5_set_error_message(context, KRB5_KT_NOWRITE,
+			       N_("Add is not supported in the %s keytab", ""),
+			       id->prefix);
 	return KRB5_KT_NOWRITE;
     }
     entry->timestamp =3D time(NULL);
     return (*id->add)(context, id,entry);
 }
=20
-/*
- * Remove the entry `entry' from the keytab `id'.
- * Return 0 or an error.
+/**
+ * Remove an entry from the keytab, matching is done using
+ * krb5_kt_compare().
+
+ * @param context a Keberos context.
+ * @param id a keytab.
+ * @param entry the entry to remove
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_remove_entry(krb5_context context,
 		     krb5_keytab id,
 		     krb5_keytab_entry *entry)
 {
     if(id->remove =3D=3D NULL) {
-	krb5_set_error_string(context,
-			      "Remove is not supported in the %s keytab",
-			      id->prefix);
+	krb5_set_error_message(context, KRB5_KT_NOWRITE,
+			       N_("Remove is not supported in the %s keytab", ""),
+			       id->prefix);
 	return KRB5_KT_NOWRITE;
     }
     return (*id->remove)(context, id, entry);
 }
+
+/**
+ * Return true if the keytab exists and have entries
+ *
+ * @param context a Keberos context.
+ * @param id a keytab.
+ *
+ * @return Return an error code or 0, see krb5_get_error_message().
+ *
+ * @ingroup krb5_keytab
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_kt_have_content(krb5_context context,
+		     krb5_keytab id)
+{
+    krb5_keytab_entry entry;
+    krb5_kt_cursor cursor;
+    krb5_error_code ret;
+    char *name;
+
+    ret =3D krb5_kt_start_seq_get(context, id, &cursor);
+    if (ret)
+	goto notfound;
+
+    ret =3D krb5_kt_next_entry(context, id, &entry, &cursor);
+    krb5_kt_end_seq_get(context, id, &cursor);
+    if (ret)
+	goto notfound;
+
+    krb5_kt_free_entry(context, &entry);
+
+    return 0;
+
+ notfound:
+    ret =3D krb5_kt_get_full_name(context, id, &name);
+    if (ret =3D=3D 0) {
+	krb5_set_error_message(context, KRB5_KT_NOTFOUND,
+			       N_("No entry in keytab: %s", ""), name);
+	free(name);
+    }
+    return KRB5_KT_NOTFOUND;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/keytab_an=
y.c
--- a/head/crypto/heimdal/lib/krb5/keytab_any.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/keytab_any.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 2001-2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001-2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: keytab_any.c 17035 2006-04-10 09:20:13Z lha $");
-
 struct any_data {
     krb5_keytab kt;
     char *name;
@@ -55,7 +53,7 @@
     }
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 any_resolve(krb5_context context, const char *name, krb5_keytab id)
 {
     struct any_data *a, *a0 =3D NULL, *prev =3D NULL;
@@ -63,7 +61,7 @@
     char buf[256];
=20
     while (strsep_copy(&name, ",", buf, sizeof(buf)) !=3D -1) {
-	a =3D malloc(sizeof(*a));
+	a =3D calloc(1, sizeof(*a));
 	if (a =3D=3D NULL) {
 	    ret =3D ENOMEM;
 	    goto fail;
@@ -72,8 +70,8 @@
 	    a0 =3D a;
 	    a->name =3D strdup(buf);
 	    if (a->name =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
 		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 		goto fail;
 	    }
 	} else
@@ -87,7 +85,7 @@
 	prev =3D a;
     }
     if (a0 =3D=3D NULL) {
-	krb5_set_error_string(context, "empty ANY: keytab");
+	krb5_set_error_message(context, ENOENT, N_("empty ANY: keytab", ""));
 	return ENOENT;
     }
     id->data =3D a0;
@@ -97,7 +95,7 @@
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 any_get_name (krb5_context context,
 	      krb5_keytab id,
 	      char *name,
@@ -108,7 +106,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 any_close (krb5_context context,
 	   krb5_keytab id)
 {
@@ -123,9 +121,9 @@
     krb5_kt_cursor cursor;
 };
=20
-static krb5_error_code
-any_start_seq_get(krb5_context context,=20
-		  krb5_keytab id,=20
+static krb5_error_code KRB5_CALLCONV
+any_start_seq_get(krb5_context context,
+		  krb5_keytab id,
 		  krb5_kt_cursor *c)
 {
     struct any_data *a =3D id->data;
@@ -134,21 +132,25 @@
=20
     c->data =3D malloc (sizeof(struct any_cursor_extra_data));
     if(c->data =3D=3D NULL){
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ed =3D (struct any_cursor_extra_data *)c->data;
-    ed->a =3D a;
-    ret =3D krb5_kt_start_seq_get(context, ed->a->kt, &ed->cursor);
-    if (ret) {
+    for (ed->a =3D a; ed->a !=3D NULL; ed->a =3D ed->a->next) {
+	ret =3D krb5_kt_start_seq_get(context, ed->a->kt, &ed->cursor);
+	if (ret =3D=3D 0)
+	    break;
+    }
+    if (ed->a =3D=3D NULL) {
 	free (c->data);
 	c->data =3D NULL;
-	return ret;
+	krb5_clear_error_message (context);
+	return KRB5_KT_END;
     }
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 any_next_entry (krb5_context context,
 		krb5_keytab id,
 		krb5_keytab_entry *entry,
@@ -174,13 +176,13 @@
 		break;
 	}
 	if (ed->a =3D=3D NULL) {
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    return KRB5_KT_END;
 	}
     } while (1);
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 any_end_seq_get(krb5_context context,
 		krb5_keytab id,
 		krb5_kt_cursor *cursor)
@@ -196,7 +198,7 @@
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 any_add_entry(krb5_context context,
 	      krb5_keytab id,
 	      krb5_keytab_entry *entry)
@@ -206,8 +208,9 @@
     while(a !=3D NULL) {
 	ret =3D krb5_kt_add_entry(context, a->kt, entry);
 	if(ret !=3D 0 && ret !=3D KRB5_KT_NOWRITE) {
-	    krb5_set_error_string(context, "failed to add entry to %s",=20
-				  a->name);
+	    krb5_set_error_message(context, ret,
+				   N_("failed to add entry to %s", ""),
+				   a->name);
 	    return ret;
 	}
 	a =3D a->next;
@@ -215,7 +218,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 any_remove_entry(krb5_context context,
 		 krb5_keytab id,
 		 krb5_keytab_entry *entry)
@@ -229,8 +232,10 @@
 	    found++;
 	else {
 	    if(ret !=3D KRB5_KT_NOWRITE && ret !=3D KRB5_KT_NOTFOUND) {
-		krb5_set_error_string(context, "failed to remove entry from %s",=20
-				      a->name);
+		krb5_set_error_message(context, ret,
+				       N_("Failed to remove keytab "
+					  "entry from %s", "keytab name"),
+				       a->name);
 		return ret;
 	    }
 	}
@@ -246,6 +251,7 @@
     any_resolve,
     any_get_name,
     any_close,
+    NULL, /* destroy */
     NULL, /* get */
     any_start_seq_get,
     any_next_entry,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/keytab_fi=
le.c
--- a/head/crypto/heimdal/lib/krb5/keytab_file.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/keytab_file.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: keytab_file.c 17457 2006-05-05 12:36:57Z lha $");
-
 #define KRB5_KT_VNO_1 1
 #define KRB5_KT_VNO_2 2
 #define KRB5_KT_VNO   KRB5_KT_VNO_2
@@ -62,7 +60,7 @@
     data->length =3D size;
     data->data =3D malloc(size);
     if (data->data =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ret =3D krb5_storage_read(sp, data->data, size);
@@ -83,7 +81,7 @@
 	return ret;
     *data =3D malloc(size + 1);
     if (*data =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ret =3D krb5_storage_read(sp, *data, size);
@@ -103,7 +101,7 @@
     if(ret < 0)
 	return ret;
     ret =3D krb5_storage_write(sp, data.data, data.length);
-    if(ret !=3D data.length){
+    if(ret !=3D (int)data.length){
 	if(ret < 0)
 	    return errno;
 	return KRB5_KT_END;
@@ -121,7 +119,7 @@
     if(ret < 0)
 	return ret;
     ret =3D krb5_storage_write(sp, data, len);
-    if(ret !=3D len){
+    if(ret !=3D (int)len){
 	if(ret < 0)
 	    return errno;
 	return KRB5_KT_END;
@@ -130,76 +128,113 @@
 }
=20
 static krb5_error_code
-krb5_kt_ret_keyblock(krb5_context context, krb5_storage *sp, krb5_keyblock=
 *p)
+krb5_kt_ret_keyblock(krb5_context context,
+		     struct fkt_data *fkt,
+		     krb5_storage *sp,
+		     krb5_keyblock *p)
 {
     int ret;
     int16_t tmp;
=20
     ret =3D krb5_ret_int16(sp, &tmp); /* keytype + etype */
-    if(ret) return ret;
+    if(ret)  {
+	krb5_set_error_message(context, ret,
+			       N_("Cant read keyblock from file %s", ""),
+			       fkt->filename);
+	return ret;
+    }
     p->keytype =3D tmp;
     ret =3D krb5_kt_ret_data(context, sp, &p->keyvalue);
+    if (ret)
+	krb5_set_error_message(context, ret,
+			       N_("Cant read keyblock from file %s", ""),
+			       fkt->filename);
     return ret;
 }
=20
 static krb5_error_code
 krb5_kt_store_keyblock(krb5_context context,
-		       krb5_storage *sp,=20
+		       struct fkt_data *fkt,
+		       krb5_storage *sp,
 		       krb5_keyblock *p)
 {
     int ret;
=20
     ret =3D krb5_store_int16(sp, p->keytype); /* keytype + etype */
-    if(ret) return ret;
+    if(ret) {
+	krb5_set_error_message(context, ret,
+			       N_("Cant store keyblock to file %s", ""),
+			       fkt->filename);
+	return ret;
+    }
     ret =3D krb5_kt_store_data(context, sp, p->keyvalue);
+    if (ret)
+	krb5_set_error_message(context, ret,
+			       N_("Cant store keyblock to file %s", ""),
+			       fkt->filename);
     return ret;
 }
=20
=20
 static krb5_error_code
 krb5_kt_ret_principal(krb5_context context,
+		      struct fkt_data *fkt,
 		      krb5_storage *sp,
 		      krb5_principal *princ)
 {
-    int i;
+    size_t i;
     int ret;
     krb5_principal p;
     int16_t len;
-   =20
+
     ALLOC(p, 1);
     if(p =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
     ret =3D krb5_ret_int16(sp, &len);
     if(ret) {
-	krb5_set_error_string(context,
-			      "Failed decoding length of keytab principal");
+	krb5_set_error_message(context, ret,
+			       N_("Failed decoding length of "
+				  "keytab principal in keytab file %s", ""),
+			       fkt->filename);
 	goto out;
     }
     if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONEN=
TS))
 	len--;
     if (len < 0) {
-	krb5_set_error_string(context,=20
-			      "Keytab principal contains invalid length");
 	ret =3D KRB5_KT_END;
+	krb5_set_error_message(context, ret,
+			       N_("Keytab principal contains "
+				  "invalid length in keytab %s", ""),
+			       fkt->filename);
 	goto out;
     }
     ret =3D krb5_kt_ret_string(context, sp, &p->realm);
-    if(ret)
+    if(ret) {
+	krb5_set_error_message(context, ret,
+			       N_("Can't read realm from keytab: %s", ""),
+			       fkt->filename);
 	goto out;
+    }
     p->name.name_string.val =3D calloc(len, sizeof(*p->name.name_string.va=
l));
     if(p->name.name_string.val =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto out;
     }
     p->name.name_string.len =3D len;
     for(i =3D 0; i < p->name.name_string.len; i++){
 	ret =3D krb5_kt_ret_string(context, sp, p->name.name_string.val + i);
-	if(ret)
+	if(ret) {
+	    krb5_set_error_message(context, ret,
+				   N_("Can't read principal from "
+				      "keytab: %s", ""),
+				   fkt->filename);
 	    goto out;
+	}
     }
     if (krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE))
 	p->name.name_type =3D KRB5_NT_UNKNOWN;
@@ -207,8 +242,13 @@
 	int32_t tmp32;
 	ret =3D krb5_ret_int32(sp, &tmp32);
 	p->name.name_type =3D tmp32;
-	if (ret)
+	if (ret) {
+	    krb5_set_error_message(context, ret,
+				   N_("Can't read name-type from "
+				      "keytab: %s", ""),
+				   fkt->filename);
 	    goto out;
+	}
     }
     *princ =3D p;
     return 0;
@@ -222,9 +262,9 @@
 			krb5_storage *sp,
 			krb5_principal p)
 {
-    int i;
+    size_t i;
     int ret;
-   =20
+
     if(krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_WRONG_NUM_COMPONEN=
TS))
 	ret =3D krb5_store_int16(sp, p->name.name_string.len + 1);
     else
@@ -246,20 +286,20 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fkt_resolve(krb5_context context, const char *name, krb5_keytab id)
 {
     struct fkt_data *d;
=20
     d =3D malloc(sizeof(*d));
     if(d =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     d->filename =3D strdup(name);
     if(d->filename =3D=3D NULL) {
 	free(d);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     d->flags =3D 0;
@@ -267,7 +307,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fkt_resolve_java14(krb5_context context, const char *name, krb5_keytab id)
 {
     krb5_error_code ret;
@@ -280,7 +320,7 @@
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fkt_close(krb5_context context, krb5_keytab id)
 {
     struct fkt_data *d =3D id->data;
@@ -289,10 +329,18 @@
     return 0;
 }
=20
-static krb5_error_code=20
-fkt_get_name(krb5_context context,=20
-	     krb5_keytab id,=20
-	     char *name,=20
+static krb5_error_code KRB5_CALLCONV
+fkt_destroy(krb5_context context, krb5_keytab id)
+{
+    struct fkt_data *d =3D id->data;
+    _krb5_erase_file(context, d->filename);
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+fkt_get_name(krb5_context context,
+	     krb5_keytab id,
+	     char *name,
 	     size_t namesize)
 {
     /* This function is XXX */
@@ -314,15 +362,15 @@
     case KRB5_KT_VNO_2:
 	break;
     default:
-	krb5_warnx(context,=20
+	krb5_warnx(context,
 		   "storage_set_flags called with bad vno (%d)", vno);
     }
     krb5_storage_set_flags(sp, flags);
 }
=20
 static krb5_error_code
-fkt_start_seq_get_int(krb5_context context,=20
-		      krb5_keytab id,=20
+fkt_start_seq_get_int(krb5_context context,
+		      krb5_keytab id,
 		      int flags,
 		      int exclusive,
 		      krb5_kt_cursor *c)
@@ -330,14 +378,16 @@
     int8_t pvno, tag;
     krb5_error_code ret;
     struct fkt_data *d =3D id->data;
-   =20
+
     c->fd =3D open (d->filename, flags);
     if (c->fd < 0) {
 	ret =3D errno;
-	krb5_set_error_string(context, "%s: %s", d->filename,
-			      strerror(ret));
+	krb5_set_error_message(context, ret,
+			       N_("keytab %s open failed: %s", ""),
+			       d->filename, strerror(ret));
 	return ret;
     }
+    rk_cloexec(c->fd);
     ret =3D _krb5_xlock(context, c->fd, exclusive, d->filename);
     if (ret) {
 	close(c->fd);
@@ -347,7 +397,8 @@
     if (c->sp =3D=3D NULL) {
 	_krb5_xunlock(context, c->fd);
 	close(c->fd);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     krb5_storage_set_eof_code(c->sp, KRB5_KT_END);
@@ -356,14 +407,14 @@
 	krb5_storage_free(c->sp);
 	_krb5_xunlock(context, c->fd);
 	close(c->fd);
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
     if(pvno !=3D 5) {
 	krb5_storage_free(c->sp);
 	_krb5_xunlock(context, c->fd);
 	close(c->fd);
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_KEYTAB_BADVNO;
     }
     ret =3D krb5_ret_int8(c->sp, &tag);
@@ -371,7 +422,7 @@
 	krb5_storage_free(c->sp);
 	_krb5_xunlock(context, c->fd);
 	close(c->fd);
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
     id->version =3D tag;
@@ -379,26 +430,28 @@
     return 0;
 }
=20
-static krb5_error_code
-fkt_start_seq_get(krb5_context context,=20
-		  krb5_keytab id,=20
+static krb5_error_code KRB5_CALLCONV
+fkt_start_seq_get(krb5_context context,
+		  krb5_keytab id,
 		  krb5_kt_cursor *c)
 {
-    return fkt_start_seq_get_int(context, id, O_RDONLY | O_BINARY, 0, c);
+    return fkt_start_seq_get_int(context, id, O_RDONLY | O_BINARY | O_CLOE=
XEC, 0, c);
 }
=20
 static krb5_error_code
-fkt_next_entry_int(krb5_context context,=20
-		   krb5_keytab id,=20
-		   krb5_keytab_entry *entry,=20
+fkt_next_entry_int(krb5_context context,
+		   krb5_keytab id,
+		   krb5_keytab_entry *entry,
 		   krb5_kt_cursor *cursor,
 		   off_t *start,
 		   off_t *end)
 {
+    struct fkt_data *d =3D id->data;
     int32_t len;
     int ret;
     int8_t tmp8;
     int32_t tmp32;
+    uint32_t utmp32;
     off_t pos, curpos;
=20
     pos =3D krb5_storage_seek(cursor->sp, 0, SEEK_CUR);
@@ -410,18 +463,18 @@
 	pos =3D krb5_storage_seek(cursor->sp, -len, SEEK_CUR);
 	goto loop;
     }
-    ret =3D krb5_kt_ret_principal (context, cursor->sp, &entry->principal);
+    ret =3D krb5_kt_ret_principal (context, d, cursor->sp, &entry->princip=
al);
     if (ret)
 	goto out;
-    ret =3D krb5_ret_int32(cursor->sp, &tmp32);
-    entry->timestamp =3D tmp32;
+    ret =3D krb5_ret_uint32(cursor->sp, &utmp32);
+    entry->timestamp =3D utmp32;
     if (ret)
 	goto out;
     ret =3D krb5_ret_int8(cursor->sp, &tmp8);
     if (ret)
 	goto out;
     entry->vno =3D tmp8;
-    ret =3D krb5_kt_ret_keyblock (context, cursor->sp, &entry->keyblock);
+    ret =3D krb5_kt_ret_keyblock (context, d, cursor->sp, &entry->keyblock=
);
     if (ret)
 	goto out;
     /* there might be a 32 bit kvno here
@@ -430,10 +483,19 @@
     curpos =3D krb5_storage_seek(cursor->sp, 0, SEEK_CUR);
     if(len + 4 + pos - curpos >=3D 4) {
 	ret =3D krb5_ret_int32(cursor->sp, &tmp32);
-	if (ret =3D=3D 0 && tmp32 !=3D 0) {
+	if (ret =3D=3D 0 && tmp32 !=3D 0)
 	    entry->vno =3D tmp32;
-	}
     }
+    /* there might be a flags field here */
+    if(len + 4 + pos - curpos >=3D 8) {
+	ret =3D krb5_ret_uint32(cursor->sp, &utmp32);
+	if (ret =3D=3D 0)
+	    entry->flags =3D utmp32;
+    } else
+	entry->flags =3D 0;
+
+    entry->aliases =3D NULL;
+
     if(start) *start =3D pos;
     if(end) *end =3D pos + 4 + len;
  out:
@@ -441,17 +503,17 @@
     return ret;
 }
=20
-static krb5_error_code
-fkt_next_entry(krb5_context context,=20
-	       krb5_keytab id,=20
-	       krb5_keytab_entry *entry,=20
+static krb5_error_code KRB5_CALLCONV
+fkt_next_entry(krb5_context context,
+	       krb5_keytab id,
+	       krb5_keytab_entry *entry,
 	       krb5_kt_cursor *cursor)
 {
     return fkt_next_entry_int(context, id, entry, cursor, NULL, NULL);
 }
=20
-static krb5_error_code
-fkt_end_seq_get(krb5_context context,=20
+static krb5_error_code KRB5_CALLCONV
+fkt_end_seq_get(krb5_context context,
 		krb5_keytab id,
 		krb5_kt_cursor *cursor)
 {
@@ -461,7 +523,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fkt_setup_keytab(krb5_context context,
 		 krb5_keytab id,
 		 krb5_storage *sp)
@@ -474,8 +536,8 @@
 	id->version =3D KRB5_KT_VNO;
     return krb5_store_int8 (sp, id->version);
 }
-		=20
-static krb5_error_code
+
+static krb5_error_code KRB5_CALLCONV
 fkt_add_entry(krb5_context context,
 	      krb5_keytab id,
 	      krb5_keytab_entry *entry)
@@ -486,16 +548,19 @@
     struct fkt_data *d =3D id->data;
     krb5_data keytab;
     int32_t len;
-   =20
-    fd =3D open (d->filename, O_RDWR | O_BINARY);
+
+    fd =3D open (d->filename, O_RDWR | O_BINARY | O_CLOEXEC);
     if (fd < 0) {
-	fd =3D open (d->filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
+	fd =3D open (d->filename, O_RDWR | O_CREAT | O_EXCL | O_BINARY | O_CLOEXE=
C, 0600);
 	if (fd < 0) {
 	    ret =3D errno;
-	    krb5_set_error_string(context, "open(%s): %s", d->filename,
-				  strerror(ret));
+	    krb5_set_error_message(context, ret,
+				   N_("open(%s): %s", ""), d->filename,
+				   strerror(ret));
 	    return ret;
 	}
+	rk_cloexec(fd);
+
 	ret =3D _krb5_xlock(context, fd, 1, d->filename);
 	if (ret) {
 	    close(fd);
@@ -510,6 +575,9 @@
 	storage_set_flags(context, sp, id->version);
     } else {
 	int8_t pvno, tag;
+
+	rk_cloexec(fd);
+
 	ret =3D _krb5_xlock(context, fd, 1, d->filename);
 	if (ret) {
 	    close(fd);
@@ -523,22 +591,26 @@
                properly */
 	    ret =3D fkt_setup_keytab(context, id, sp);
 	    if(ret) {
-		krb5_set_error_string(context, "%s: keytab is corrupted: %s",=20
-				      d->filename, strerror(ret));
+		krb5_set_error_message(context, ret,
+				       N_("%s: keytab is corrupted: %s", ""),
+				       d->filename, strerror(ret));
 		goto out;
 	    }
 	    storage_set_flags(context, sp, id->version);
 	} else {
 	    if(pvno !=3D 5) {
 		ret =3D KRB5_KEYTAB_BADVNO;
-		krb5_set_error_string(context, "%s: %s",=20
-				      d->filename, strerror(ret));
+		krb5_set_error_message(context, ret,
+				       N_("Bad version in keytab %s", ""),
+				       d->filename);
 		goto out;
 	    }
 	    ret =3D krb5_ret_int8 (sp, &tag);
 	    if (ret) {
-		krb5_set_error_string(context, "%s: reading tag: %s",=20
-				      d->filename, strerror(ret));
+		krb5_set_error_message(context, ret,
+				       N_("failed reading tag from "
+					  "keytab %s", ""),
+				       d->filename);
 		goto out;
 	    }
 	    id->version =3D tag;
@@ -551,25 +623,38 @@
 	emem =3D krb5_storage_emem();
 	if(emem =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto out;
 	}
 	ret =3D krb5_kt_store_principal(context, emem, entry->principal);
 	if(ret) {
+	    krb5_set_error_message(context, ret,
+				   N_("Failed storing principal "
+				      "in keytab %s", ""),
+				   d->filename);
 	    krb5_storage_free(emem);
 	    goto out;
 	}
 	ret =3D krb5_store_int32 (emem, entry->timestamp);
 	if(ret) {
+	    krb5_set_error_message(context, ret,
+				   N_("Failed storing timpstamp "
+				      "in keytab %s", ""),
+				   d->filename);
 	    krb5_storage_free(emem);
 	    goto out;
 	}
 	ret =3D krb5_store_int8 (emem, entry->vno % 256);
 	if(ret) {
+	    krb5_set_error_message(context, ret,
+				   N_("Failed storing kvno "
+				      "in keytab %s", ""),
+				   d->filename);
 	    krb5_storage_free(emem);
 	    goto out;
 	}
-	ret =3D krb5_kt_store_keyblock (context, emem, &entry->keyblock);
+	ret =3D krb5_kt_store_keyblock (context, d, emem, &entry->keyblock);
 	if(ret) {
 	    krb5_storage_free(emem);
 	    goto out;
@@ -577,6 +662,19 @@
 	if ((d->flags & KRB5_KT_FL_JAVA) =3D=3D 0) {
 	    ret =3D krb5_store_int32 (emem, entry->vno);
 	    if (ret) {
+		krb5_set_error_message(context, ret,
+				       N_("Failed storing extended kvno "
+					  "in keytab %s", ""),
+				       d->filename);
+		krb5_storage_free(emem);
+		goto out;
+	    }
+	    ret =3D krb5_store_uint32 (emem, entry->flags);
+	    if (ret) {
+		krb5_set_error_message(context, ret,
+				       N_("Failed storing extended kvno "
+					  "in keytab %s", ""),
+				       d->filename);
 		krb5_storage_free(emem);
 		goto out;
 	    }
@@ -584,10 +682,15 @@
=20
 	ret =3D krb5_storage_to_data(emem, &keytab);
 	krb5_storage_free(emem);
-	if(ret)
+	if(ret) {
+	    krb5_set_error_message(context, ret,
+				   N_("Failed converting keytab entry "
+				      "to memory block for keytab %s", ""),
+				   d->filename);
 	    goto out;
+	}
     }
-   =20
+
     while(1) {
 	ret =3D krb5_ret_int32(sp, &len);
 	if(ret =3D=3D KRB5_KT_END) {
@@ -596,7 +699,7 @@
 	}
 	if(len < 0) {
 	    len =3D -len;
-	    if(len >=3D keytab.length) {
+	    if(len >=3D (int)keytab.length) {
 		krb5_storage_seek(sp, -4, SEEK_CUR);
 		break;
 	    }
@@ -604,8 +707,13 @@
 	krb5_storage_seek(sp, len, SEEK_CUR);
     }
     ret =3D krb5_store_int32(sp, len);
-    if(krb5_storage_write(sp, keytab.data, keytab.length) < 0)
+    if(krb5_storage_write(sp, keytab.data, keytab.length) < 0) {
 	ret =3D errno;
+	krb5_set_error_message(context, ret,
+			       N_("Failed writing keytab block "
+				  "in keytab %s: %s", ""),
+			       d->filename, strerror(ret));
+    }
     memset(keytab.data, 0, keytab.length);
     krb5_data_free(&keytab);
   out:
@@ -615,7 +723,7 @@
     return ret;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 fkt_remove_entry(krb5_context context,
 		 krb5_keytab id,
 		 krb5_keytab_entry *entry)
@@ -625,13 +733,13 @@
     off_t pos_start, pos_end;
     int found =3D 0;
     krb5_error_code ret;
-   =20
-    ret =3D fkt_start_seq_get_int(context, id, O_RDWR | O_BINARY, 1, &curs=
or);
-    if(ret !=3D 0)=20
+
+    ret =3D fkt_start_seq_get_int(context, id, O_RDWR | O_BINARY | O_CLOEX=
EC, 1, &cursor);
+    if(ret !=3D 0)
 	goto out; /* return other error here? */
-    while(fkt_next_entry_int(context, id, &e, &cursor,=20
+    while(fkt_next_entry_int(context, id, &e, &cursor,
 			     &pos_start, &pos_end) =3D=3D 0) {
-	if(krb5_kt_compare(context, &e, entry->principal,=20
+	if(krb5_kt_compare(context, &e, entry->principal,
 			   entry->vno, entry->keyblock.keytype)) {
 	    int32_t len;
 	    unsigned char buf[128];
@@ -641,8 +749,9 @@
 	    krb5_store_int32(cursor.sp, -len);
 	    memset(buf, 0, sizeof(buf));
 	    while(len > 0) {
-		krb5_storage_write(cursor.sp, buf, min(len, sizeof(buf)));
-		len -=3D min(len, sizeof(buf));
+		krb5_storage_write(cursor.sp, buf,
+		    min((size_t)len, sizeof(buf)));
+		len -=3D min((size_t)len, sizeof(buf));
 	    }
 	}
 	krb5_kt_free_entry(context, &e);
@@ -650,7 +759,7 @@
     krb5_kt_end_seq_get(context, id, &cursor);
   out:
     if (!found) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_KT_NOTFOUND;
     }
     return 0;
@@ -661,6 +770,7 @@
     fkt_resolve,
     fkt_get_name,
     fkt_close,
+    fkt_destroy,
     NULL, /* get */
     fkt_start_seq_get,
     fkt_next_entry,
@@ -674,6 +784,7 @@
     fkt_resolve,
     fkt_get_name,
     fkt_close,
+    fkt_destroy,
     NULL, /* get */
     fkt_start_seq_get,
     fkt_next_entry,
@@ -687,6 +798,7 @@
     fkt_resolve_java14,
     fkt_get_name,
     fkt_close,
+    fkt_destroy,
     NULL, /* get */
     fkt_start_seq_get,
     fkt_next_entry,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/keytab_ke=
yfile.c
--- a/head/crypto/heimdal/lib/krb5/keytab_keyfile.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/keytab_keyfile.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,45 +1,45 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: keytab_keyfile.c 20695 2007-05-30 14:09:09Z lha $");
+#ifndef HEIMDAL_SMALLER
=20
 /* afs keyfile operations --------------------------------------- */
=20
 /*
  * Minimum tools to handle the AFS KeyFile.
- *=20
+ *
  * Format of the KeyFile is:
  * <int32_t numkeys> {[<int32_t kvno> <char[8] deskey>] * numkeys}
  *
@@ -52,7 +52,7 @@
 #define AFS_SERVERMAGICKRBCONF "/usr/afs/etc/krb.conf"
=20
 struct akf_data {
-    int num_entries;
+    uint32_t num_entries;
     char *filename;
     char *cell;
     char *realm;
@@ -72,13 +72,17 @@
     f =3D fopen (AFS_SERVERTHISCELL, "r");
     if (f =3D=3D NULL) {
 	ret =3D errno;
-	krb5_set_error_string (context, "open %s: %s", AFS_SERVERTHISCELL,
-			       strerror(ret));
+	krb5_set_error_message (context, ret,
+				N_("Open ThisCell %s: %s", ""),
+				AFS_SERVERTHISCELL,
+				strerror(ret));
 	return ret;
     }
     if (fgets (buf, sizeof(buf), f) =3D=3D NULL) {
 	fclose (f);
-	krb5_set_error_string (context, "no cell in %s", AFS_SERVERTHISCELL);
+	krb5_set_error_message (context, EINVAL,
+				N_("No cell in ThisCell file %s", ""),
+				AFS_SERVERTHISCELL);
 	return EINVAL;
     }
     buf[strcspn(buf, "\n")] =3D '\0';
@@ -86,7 +90,8 @@
=20
     d->cell =3D strdup (buf);
     if (d->cell =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -96,8 +101,9 @@
 	    free (d->cell);
 	    d->cell =3D NULL;
 	    fclose (f);
-	    krb5_set_error_string (context, "no realm in %s",
-				   AFS_SERVERMAGICKRBCONF);
+	    krb5_set_error_message (context, EINVAL,
+				    N_("No realm in ThisCell file %s", ""),
+				    AFS_SERVERMAGICKRBCONF);
 	    return EINVAL;
 	}
 	buf[strcspn(buf, "\n")] =3D '\0';
@@ -106,12 +112,13 @@
     /* uppercase */
     for (cp =3D buf; *cp !=3D '\0'; cp++)
 	*cp =3D toupper((unsigned char)*cp);
-   =20
+
     d->realm =3D strdup (buf);
     if (d->realm =3D=3D NULL) {
 	free (d->cell);
 	d->cell =3D NULL;
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
@@ -121,17 +128,18 @@
  * init and get filename
  */
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 akf_resolve(krb5_context context, const char *name, krb5_keytab id)
 {
     int ret;
     struct akf_data *d =3D malloc(sizeof (struct akf_data));
=20
     if (d =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
-   =20
+
     d->num_entries =3D 0;
     ret =3D get_cell_and_realm (context, d);
     if (ret) {
@@ -143,11 +151,12 @@
 	free (d->cell);
 	free (d->realm);
 	free (d);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     id->data =3D d;
-   =20
+
     return 0;
 }
=20
@@ -155,7 +164,7 @@
  * cleanup
  */
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 akf_close(krb5_context context, krb5_keytab id)
 {
     struct akf_data *d =3D id->data;
@@ -170,10 +179,10 @@
  * Return filename
  */
=20
-static krb5_error_code=20
-akf_get_name(krb5_context context,=20
-	     krb5_keytab id,=20
-	     char *name,=20
+static krb5_error_code KRB5_CALLCONV
+akf_get_name(krb5_context context,
+	     krb5_keytab id,
+	     char *name,
 	     size_t name_sz)
 {
     struct akf_data *d =3D id->data;
@@ -183,31 +192,40 @@
 }
=20
 /*
- * Init=20
+ * Init
  */
=20
-static krb5_error_code
-akf_start_seq_get(krb5_context context,=20
-		  krb5_keytab id,=20
+static krb5_error_code KRB5_CALLCONV
+akf_start_seq_get(krb5_context context,
+		  krb5_keytab id,
 		  krb5_kt_cursor *c)
 {
     int32_t ret;
     struct akf_data *d =3D id->data;
=20
-    c->fd =3D open (d->filename, O_RDONLY|O_BINARY, 0600);
+    c->fd =3D open (d->filename, O_RDONLY | O_BINARY | O_CLOEXEC, 0600);
     if (c->fd < 0) {
 	ret =3D errno;
-	krb5_set_error_string(context, "open(%s): %s", d->filename,
-			      strerror(ret));
+	krb5_set_error_message(context, ret,
+			       N_("keytab afs keyfile open %s failed: %s", ""),
+			       d->filename, strerror(ret));
 	return ret;
     }
=20
+    c->data =3D NULL;
     c->sp =3D krb5_storage_from_fd(c->fd);
-    ret =3D krb5_ret_int32(c->sp, &d->num_entries);
-    if(ret) {
+    if (c->sp =3D=3D NULL) {
+	close(c->fd);
+	krb5_clear_error_message (context);
+	return KRB5_KT_NOTFOUND;
+    }
+    krb5_storage_set_eof_code(c->sp, KRB5_KT_END);
+
+    ret =3D krb5_ret_uint32(c->sp, &d->num_entries);
+    if(ret || d->num_entries > INT_MAX / 8) {
 	krb5_storage_free(c->sp);
 	close(c->fd);
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	if(ret =3D=3D KRB5_KT_END)
 	    return KRB5_KT_NOTFOUND;
 	return ret;
@@ -216,10 +234,10 @@
     return 0;
 }
=20
-static krb5_error_code
-akf_next_entry(krb5_context context,=20
-	       krb5_keytab id,=20
-	       krb5_keytab_entry *entry,=20
+static krb5_error_code KRB5_CALLCONV
+akf_next_entry(krb5_context context,
+	       krb5_keytab id,
+	       krb5_keytab_entry *entry,
 	       krb5_kt_cursor *cursor)
 {
     struct akf_data *d =3D id->data;
@@ -245,12 +263,16 @@
=20
     entry->vno =3D kvno;
=20
-    entry->keyblock.keytype         =3D ETYPE_DES_CBC_MD5;
+    if (cursor->data)
+	entry->keyblock.keytype         =3D ETYPE_DES_CBC_MD5;
+    else
+	entry->keyblock.keytype         =3D ETYPE_DES_CBC_CRC;
     entry->keyblock.keyvalue.length =3D 8;
     entry->keyblock.keyvalue.data   =3D malloc (8);
     if (entry->keyblock.keyvalue.data =3D=3D NULL) {
 	krb5_free_principal (context, entry->principal);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	ret =3D ENOMEM;
 	goto out;
     }
@@ -262,23 +284,30 @@
 	ret =3D 0;
=20
     entry->timestamp =3D time(NULL);
+    entry->flags =3D 0;
+    entry->aliases =3D NULL;
=20
  out:
-    krb5_storage_seek(cursor->sp, pos + 4 + 8, SEEK_SET);
+    if (cursor->data) {
+	krb5_storage_seek(cursor->sp, pos + 4 + 8, SEEK_SET);
+	cursor->data =3D NULL;
+    } else
+	cursor->data =3D cursor;
     return ret;
 }
=20
-static krb5_error_code
-akf_end_seq_get(krb5_context context,=20
+static krb5_error_code KRB5_CALLCONV
+akf_end_seq_get(krb5_context context,
 		krb5_keytab id,
 		krb5_kt_cursor *cursor)
 {
     krb5_storage_free(cursor->sp);
     close(cursor->fd);
+    cursor->data =3D NULL;
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 akf_add_entry(krb5_context context,
 	      krb5_keytab id,
 	      krb5_keytab_entry *entry)
@@ -301,14 +330,16 @@
 	return 0;
     }
=20
-    fd =3D open (d->filename, O_RDWR | O_BINARY);
+    fd =3D open (d->filename, O_RDWR | O_BINARY | O_CLOEXEC);
     if (fd < 0) {
 	fd =3D open (d->filename,
-		   O_RDWR | O_BINARY | O_CREAT | O_EXCL, 0600);
+		   O_RDWR | O_BINARY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
 	if (fd < 0) {
 	    ret =3D errno;
-	    krb5_set_error_string(context, "open(%s): %s", d->filename,
-				  strerror(ret));
+	    krb5_set_error_message(context, ret,
+				   N_("open keyfile(%s): %s", ""),
+				   d->filename,
+				   strerror(ret));
 	    return ret;
 	}
 	created =3D 1;
@@ -317,7 +348,8 @@
     sp =3D krb5_storage_from_fd(fd);
     if(sp =3D=3D NULL) {
 	close(fd);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     if (created)
@@ -327,10 +359,12 @@
 	    ret =3D errno;
 	    krb5_storage_free(sp);
 	    close(fd);
-	    krb5_set_error_string (context, "seek: %s", strerror(ret));
+	    krb5_set_error_message(context, ret,
+				   N_("seeking in keyfile: %s", ""),
+				   strerror(ret));
 	    return ret;
 	}
-	   =20
+
 	ret =3D krb5_ret_int32(sp, &len);
 	if(ret) {
 	    krb5_storage_free(sp);
@@ -350,11 +384,15 @@
 	for (i =3D 0; i < len; i++) {
 	    ret =3D krb5_ret_int32(sp, &kvno);
 	    if (ret) {
-		krb5_set_error_string (context, "Failed to get kvno ");
+		krb5_set_error_message (context, ret,
+					N_("Failed getting kvno from keyfile", ""));
 		goto out;
 	    }
 	    if(krb5_storage_seek(sp, 8, SEEK_CUR) < 0) {
-		krb5_set_error_string (context, "seek: %s", strerror(ret));
+		ret =3D errno;
+		krb5_set_error_message (context, ret,
+					N_("Failed seeing in keyfile: %s", ""),
+					strerror(ret));
 		goto out;
 	    }
 	    if (kvno =3D=3D entry->vno) {
@@ -365,38 +403,45 @@
     }
=20
     len++;
-=09
+
     if(krb5_storage_seek(sp, 0, SEEK_SET) < 0) {
 	ret =3D errno;
-	krb5_set_error_string (context, "seek: %s", strerror(ret));
+	krb5_set_error_message (context, ret,
+				N_("Failed seeing in keyfile: %s", ""),
+				strerror(ret));
 	goto out;
     }
-=09
+
     ret =3D krb5_store_int32(sp, len);
     if(ret) {
-	krb5_set_error_string(context, "keytab keyfile failed new length");
+	ret =3D errno;
+	krb5_set_error_message (context, ret,
+				N_("keytab keyfile failed new length", ""));
 	return ret;
     }
=20
     if(krb5_storage_seek(sp, (len - 1) * (8 + 4), SEEK_CUR) < 0) {
 	ret =3D errno;
-	krb5_set_error_string (context, "seek to end: %s", strerror(ret));
+	krb5_set_error_message (context, ret,
+				N_("seek to end: %s", ""), strerror(ret));
 	goto out;
     }
-=09
+
     ret =3D krb5_store_int32(sp, entry->vno);
     if(ret) {
-	krb5_set_error_string(context, "keytab keyfile failed store kvno");
+	krb5_set_error_message(context, ret,
+			       N_("keytab keyfile failed store kvno", ""));
 	goto out;
     }
-    ret =3D krb5_storage_write(sp, entry->keyblock.keyvalue.data,=20
+    ret =3D krb5_storage_write(sp, entry->keyblock.keyvalue.data,
 			     entry->keyblock.keyvalue.length);
     if(ret !=3D entry->keyblock.keyvalue.length) {
 	if (ret < 0)
 	    ret =3D errno;
 	else
 	    ret =3D ENOTTY;
-	krb5_set_error_string(context, "keytab keyfile failed to add key");
+	krb5_set_error_message(context, ret,
+			       N_("keytab keyfile failed to add key", ""));
 	goto out;
     }
     ret =3D 0;
@@ -411,6 +456,7 @@
     akf_resolve,
     akf_get_name,
     akf_close,
+    NULL, /* destroy */
     NULL, /* get */
     akf_start_seq_get,
     akf_next_entry,
@@ -418,3 +464,5 @@
     akf_add_entry,
     NULL /* remove */
 };
+
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/keytab_me=
mory.c
--- a/head/crypto/heimdal/lib/krb5/keytab_memory.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/keytab_memory.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: keytab_memory.c 16352 2005-12-05 18:39:46Z lha $");
-
 /* memory operations -------------------------------------------- */
=20
 struct mkt_data {
@@ -45,14 +43,14 @@
     struct mkt_data *next;
 };
=20
-/* this mutex protects mkt_head, ->refcount, and ->next=20
+/* this mutex protects mkt_head, ->refcount, and ->next
  * content is not protected (name is static and need no protection)
  */
 static HEIMDAL_MUTEX mkt_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
 static struct mkt_data *mkt_head;
=20
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mkt_resolve(krb5_context context, const char *name, krb5_keytab id)
 {
     struct mkt_data *d;
@@ -75,14 +73,16 @@
     d =3D calloc(1, sizeof(*d));
     if(d =3D=3D NULL) {
 	HEIMDAL_MUTEX_unlock(&mkt_mutex);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     d->name =3D strdup(name);
     if (d->name =3D=3D NULL) {
 	HEIMDAL_MUTEX_unlock(&mkt_mutex);
 	free(d);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     d->entries =3D NULL;
@@ -95,7 +95,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mkt_close(krb5_context context, krb5_keytab id)
 {
     struct mkt_data *d =3D id->data, **dp;
@@ -103,7 +103,7 @@
=20
     HEIMDAL_MUTEX_lock(&mkt_mutex);
     if (d->refcount < 1)
-	krb5_abortx(context,=20
+	krb5_abortx(context,
 		    "krb5 internal error, memory keytab refcount < 1 on close");
=20
     if (--d->refcount > 0) {
@@ -126,10 +126,10 @@
     return 0;
 }
=20
-static krb5_error_code=20
-mkt_get_name(krb5_context context,=20
-	     krb5_keytab id,=20
-	     char *name,=20
+static krb5_error_code KRB5_CALLCONV
+mkt_get_name(krb5_context context,
+	     krb5_keytab id,
+	     char *name,
 	     size_t namesize)
 {
     struct mkt_data *d =3D id->data;
@@ -137,9 +137,9 @@
     return 0;
 }
=20
-static krb5_error_code
-mkt_start_seq_get(krb5_context context,=20
-		  krb5_keytab id,=20
+static krb5_error_code KRB5_CALLCONV
+mkt_start_seq_get(krb5_context context,
+		  krb5_keytab id,
 		  krb5_kt_cursor *c)
 {
     /* XXX */
@@ -147,10 +147,10 @@
     return 0;
 }
=20
-static krb5_error_code
-mkt_next_entry(krb5_context context,=20
-	       krb5_keytab id,=20
-	       krb5_keytab_entry *entry,=20
+static krb5_error_code KRB5_CALLCONV
+mkt_next_entry(krb5_context context,
+	       krb5_keytab id,
+	       krb5_keytab_entry *entry,
 	       krb5_kt_cursor *c)
 {
     struct mkt_data *d =3D id->data;
@@ -159,15 +159,15 @@
     return krb5_kt_copy_entry_contents(context, &d->entries[c->fd++], entr=
y);
 }
=20
-static krb5_error_code
-mkt_end_seq_get(krb5_context context,=20
+static krb5_error_code KRB5_CALLCONV
+mkt_end_seq_get(krb5_context context,
 		krb5_keytab id,
 		krb5_kt_cursor *cursor)
 {
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mkt_add_entry(krb5_context context,
 	      krb5_keytab id,
 	      krb5_keytab_entry *entry)
@@ -176,15 +176,16 @@
     krb5_keytab_entry *tmp;
     tmp =3D realloc(d->entries, (d->num_entries + 1) * sizeof(*d->entries)=
);
     if(tmp =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     d->entries =3D tmp;
-    return krb5_kt_copy_entry_contents(context, entry,=20
+    return krb5_kt_copy_entry_contents(context, entry,
 				       &d->entries[d->num_entries++]);
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mkt_remove_entry(krb5_context context,
 		 krb5_keytab id,
 		 krb5_keytab_entry *entry)
@@ -192,15 +193,15 @@
     struct mkt_data *d =3D id->data;
     krb5_keytab_entry *e, *end;
     int found =3D 0;
-   =20
+
     if (d->num_entries =3D=3D 0) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
         return KRB5_KT_NOTFOUND;
     }
=20
     /* do this backwards to minimize copying */
     for(end =3D d->entries + d->num_entries, e =3D end - 1; e >=3D d->entr=
ies; e--) {
-	if(krb5_kt_compare(context, e, entry->principal,=20
+	if(krb5_kt_compare(context, e, entry->principal,
 			   entry->vno, entry->keyblock.keytype)) {
 	    krb5_kt_free_entry(context, e);
 	    memmove(e, e + 1, (end - e - 1) * sizeof(*e));
@@ -211,7 +212,7 @@
 	}
     }
     if (!found) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_KT_NOTFOUND;
     }
     e =3D realloc(d->entries, d->num_entries * sizeof(*d->entries));
@@ -225,6 +226,7 @@
     mkt_resolve,
     mkt_get_name,
     mkt_close,
+    NULL, /* destroy */
     NULL, /* get */
     mkt_start_seq_get,
     mkt_next_entry,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5-priv=
ate.h
--- a/head/crypto/heimdal/lib/krb5/krb5-private.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/krb5-private.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -4,14 +4,59 @@
=20
 #include <stdarg.h>
=20
-void KRB5_LIB_FUNCTION
-_krb5_aes_cts_encrypt (
-	const unsigned char */*in*/,
-	unsigned char */*out*/,
+#if !defined(__GNUC__) && !defined(__attribute__)
+#define __attribute__(x)
+#endif
+
+#ifndef KRB5_DEPRECATED_FUNCTION
+#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ =3D=3D 3) && (__GNU=
C_MINOR__ >=3D 1 )))
+#define KRB5_DEPRECATED_FUNCTION(X) __attribute__((__deprecated__))
+#else
+#define KRB5_DEPRECATED_FUNCTION(X)
+#endif
+#endif
+
+
+void
+_heim_krb5_ipc_client_clear_target (void);
+
+void
+_heim_krb5_ipc_client_set_target_uid (uid_t /*uid*/);
+
+void
+_krb5_DES3_random_to_key (
+	krb5_context /*context*/,
+	krb5_keyblock */*key*/,
+	const void */*data*/,
+	size_t /*size*/);
+
+krb5_error_code
+_krb5_HMAC_MD5_checksum (
+	krb5_context /*context*/,
+	struct _krb5_key_data */*key*/,
+	const void */*data*/,
 	size_t /*len*/,
-	const AES_KEY */*key*/,
-	unsigned char */*ivec*/,
-	const int /*encryptp*/);
+	unsigned /*usage*/,
+	Checksum */*result*/);
+
+krb5_error_code
+_krb5_SP_HMAC_SHA1_checksum (
+	krb5_context /*context*/,
+	struct _krb5_key_data */*key*/,
+	const void */*data*/,
+	size_t /*len*/,
+	unsigned /*usage*/,
+	Checksum */*result*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_build_authenticator (
+	krb5_context /*context*/,
+	krb5_auth_context /*auth_context*/,
+	krb5_enctype /*enctype*/,
+	krb5_creds */*cred*/,
+	Checksum */*cksum*/,
+	krb5_data */*result*/,
+	krb5_key_usage /*usage*/);
=20
 krb5_error_code
 _krb5_cc_allocate (
@@ -19,6 +64,53 @@
 	const krb5_cc_ops */*ops*/,
 	krb5_ccache */*id*/);
=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_config_copy (
+	krb5_context /*context*/,
+	krb5_config_section */*c*/,
+	krb5_config_section **/*head*/);
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_get (
+	krb5_context /*context*/,
+	const krb5_config_section */*c*/,
+	int /*type*/,
+	...);
+
+krb5_config_section *
+_krb5_config_get_entry (
+	krb5_config_section **/*parent*/,
+	const char */*name*/,
+	int /*type*/);
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_get_next (
+	krb5_context /*context*/,
+	const krb5_config_section */*c*/,
+	const krb5_config_binding **/*pointer*/,
+	int /*type*/,
+	...);
+
+const void *
+_krb5_config_vget (
+	krb5_context /*context*/,
+	const krb5_config_section */*c*/,
+	int /*type*/,
+	va_list /*args*/);
+
+KRB5_LIB_FUNCTION const void * KRB5_LIB_CALL
+_krb5_config_vget_next (
+	krb5_context /*context*/,
+	const krb5_config_section */*c*/,
+	const krb5_config_binding **/*pointer*/,
+	int /*type*/,
+	va_list /*args*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_copy_send_to_kdc_func (
+	krb5_context /*context*/,
+	krb5_context /*to*/);
+
 void
 _krb5_crc_init_table (void);
=20
@@ -28,6 +120,43 @@
 	size_t /*len*/,
 	uint32_t /*res*/);
=20
+void KRB5_LIB_FUNCTION
+_krb5_debug (
+	krb5_context /*context*/,
+	int /*level*/,
+	const char */*fmt*/,
+	...)
+     __attribute__((format (printf, 3, 4)));
+
+void
+_krb5_debug_backtrace (krb5_context /*context*/);
+
+krb5_error_code
+_krb5_derive_key (
+	krb5_context /*context*/,
+	struct _krb5_encryption_type */*et*/,
+	struct _krb5_key_data */*key*/,
+	const void */*constant*/,
+	size_t /*len*/);
+
+krb5_error_code
+_krb5_des_checksum (
+	krb5_context /*context*/,
+	const EVP_MD */*evp_md*/,
+	struct _krb5_key_data */*key*/,
+	const void */*data*/,
+	size_t /*len*/,
+	Checksum */*cksum*/);
+
+krb5_error_code
+_krb5_des_verify (
+	krb5_context /*context*/,
+	const EVP_MD */*evp_md*/,
+	struct _krb5_key_data */*key*/,
+	const void */*data*/,
+	size_t /*len*/,
+	Checksum */*C*/);
+
 krb5_error_code
 _krb5_dh_group_ok (
 	krb5_context /*context*/,
@@ -38,11 +167,47 @@
 	struct krb5_dh_moduli **/*moduli*/,
 	char **/*name*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_enctype_to_oid (
+krb5_error_code
+_krb5_einval (
 	krb5_context /*context*/,
-	krb5_enctype /*etype*/,
-	heim_oid */*oid*/);
+	const char */*func*/,
+	unsigned long /*argn*/);
+
+krb5_error_code
+_krb5_erase_file (
+	krb5_context /*context*/,
+	const char */*filename*/);
+
+void
+_krb5_evp_cleanup (
+	krb5_context /*context*/,
+	struct _krb5_key_data */*kd*/);
+
+krb5_error_code
+_krb5_evp_encrypt (
+	krb5_context /*context*/,
+	struct _krb5_key_data */*key*/,
+	void */*data*/,
+	size_t /*len*/,
+	krb5_boolean /*encryptp*/,
+	int /*usage*/,
+	void */*ivec*/);
+
+krb5_error_code
+_krb5_evp_encrypt_cts (
+	krb5_context /*context*/,
+	struct _krb5_key_data */*key*/,
+	void */*data*/,
+	size_t /*len*/,
+	krb5_boolean /*encryptp*/,
+	int /*usage*/,
+	void */*ivec*/);
+
+void
+_krb5_evp_schedule (
+	krb5_context /*context*/,
+	struct _krb5_key_type */*kt*/,
+	struct _krb5_key_data */*kd*/);
=20
 krb5_error_code
 _krb5_expand_default_cc_name (
@@ -50,6 +215,12 @@
 	const char */*str*/,
 	char **/*res*/);
=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_expand_path_tokens (
+	krb5_context /*context*/,
+	const char */*path_in*/,
+	char **/*ppath_out*/);
+
 int
 _krb5_extract_ticket (
 	krb5_context /*context*/,
@@ -64,6 +235,18 @@
 	krb5_decrypt_proc /*decrypt_proc*/,
 	krb5_const_pointer /*decryptarg*/);
=20
+struct _krb5_checksum_type *
+_krb5_find_checksum (krb5_cksumtype /*type*/);
+
+struct _krb5_encryption_type *
+_krb5_find_enctype (krb5_enctype /*type*/);
+
+void
+_krb5_free_key_data (
+	krb5_context /*context*/,
+	struct _krb5_key_data */*key*/,
+	struct _krb5_encryption_type */*et*/);
+
 void
 _krb5_free_krbhst_info (krb5_krbhst_info */*hi*/);
=20
@@ -71,36 +254,38 @@
 _krb5_free_moduli (struct krb5_dh_moduli **/*moduli*/);
=20
 krb5_error_code
+_krb5_get_cred_kdc_any (
+	krb5_context /*context*/,
+	krb5_kdc_flags /*flags*/,
+	krb5_ccache /*ccache*/,
+	krb5_creds */*in_creds*/,
+	krb5_principal /*impersonate_principal*/,
+	Ticket */*second_ticket*/,
+	krb5_creds **/*out_creds*/,
+	krb5_creds ***/*ret_tgts*/);
+
+char *
+_krb5_get_default_cc_name_from_registry (krb5_context /*context*/);
+
+char *
+_krb5_get_default_config_config_files_from_registry (void);
+
+krb5_error_code
 _krb5_get_default_principal_local (
 	krb5_context /*context*/,
 	krb5_principal */*princ*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_get_host_realm_int (
 	krb5_context /*context*/,
 	const char */*host*/,
 	krb5_boolean /*use_dns*/,
 	krb5_realm **/*realms*/);
=20
-krb5_error_code
-_krb5_get_init_creds_opt_copy (
-	krb5_context /*context*/,
-	const krb5_get_init_creds_opt */*in*/,
-	krb5_get_init_creds_opt **/*out*/);
-
-void KRB5_LIB_FUNCTION
-_krb5_get_init_creds_opt_free_krb5_error (krb5_get_init_creds_opt */*opt*/=
);
-
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 _krb5_get_init_creds_opt_free_pkinit (krb5_get_init_creds_opt */*opt*/);
=20
-void KRB5_LIB_FUNCTION
-_krb5_get_init_creds_opt_set_krb5_error (
-	krb5_context /*context*/,
-	krb5_get_init_creds_opt */*opt*/,
-	const KRB_ERROR */*error*/);
-
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 _krb5_get_int (
 	void */*buffer*/,
 	unsigned long */*value*/,
@@ -113,27 +298,40 @@
 	krb5_realm /*realm*/,
 	krb5_creds **/*cred*/);
=20
-krb5_error_code
-_krb5_kcm_chmod (
+krb5_boolean KRB5_LIB_FUNCTION
+_krb5_have_debug (
 	krb5_context /*context*/,
-	krb5_ccache /*id*/,
-	uint16_t /*mode*/);
+	int /*level*/);
+
+krb5_boolean
+_krb5_homedir_access (krb5_context /*context*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_init_etype (
+	krb5_context /*context*/,
+	krb5_pdu /*pdu_type*/,
+	unsigned */*len*/,
+	krb5_enctype **/*val*/,
+	const krb5_enctype */*etypes*/);
=20
 krb5_error_code
-_krb5_kcm_chown (
+_krb5_internal_hmac (
 	krb5_context /*context*/,
-	krb5_ccache /*id*/,
-	uint32_t /*uid*/,
-	uint32_t /*gid*/);
+	struct _krb5_checksum_type */*cm*/,
+	const void */*data*/,
+	size_t /*len*/,
+	unsigned /*usage*/,
+	struct _krb5_key_data */*keyblock*/,
+	Checksum */*result*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_kcm_get_initial_ticket (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
 	krb5_principal /*server*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_kcm_get_ticket (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
@@ -141,15 +339,15 @@
 	krb5_enctype /*enctype*/,
 	krb5_principal /*server*/);
=20
-krb5_boolean
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 _krb5_kcm_is_running (krb5_context /*context*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_kcm_noop (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/);
=20
-krb5_error_code
+krb5_error_code KRB5_CALLCONV
 _krb5_kdc_retry (
 	krb5_context /*context*/,
 	krb5_sendto_ctx /*ctx*/,
@@ -157,114 +355,33 @@
 	const krb5_data */*reply*/,
 	int */*action*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_cr_err_reply (
-	krb5_context /*context*/,
-	const char */*name*/,
-	const char */*inst*/,
-	const char */*realm*/,
-	uint32_t /*time_ws*/,
-	uint32_t /*e*/,
-	const char */*e_string*/,
-	krb5_data */*data*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_create_auth_reply (
-	krb5_context /*context*/,
-	const char */*pname*/,
-	const char */*pinst*/,
-	const char */*prealm*/,
-	int32_t /*time_ws*/,
-	int /*n*/,
-	uint32_t /*x_date*/,
-	unsigned char /*kvno*/,
-	const krb5_data */*cipher*/,
-	krb5_data */*data*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_create_ciph (
-	krb5_context /*context*/,
-	const krb5_keyblock */*session*/,
-	const char */*service*/,
-	const char */*instance*/,
-	const char */*realm*/,
-	uint32_t /*life*/,
-	unsigned char /*kvno*/,
-	const krb5_data */*ticket*/,
-	uint32_t /*kdc_time*/,
-	const krb5_keyblock */*key*/,
-	krb5_data */*enc_data*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_create_ticket (
-	krb5_context /*context*/,
-	unsigned char /*flags*/,
-	const char */*pname*/,
-	const char */*pinstance*/,
-	const char */*prealm*/,
-	int32_t /*paddress*/,
-	const krb5_keyblock */*session*/,
-	int16_t /*life*/,
-	int32_t /*life_sec*/,
-	const char */*sname*/,
-	const char */*sinstance*/,
-	const krb5_keyblock */*key*/,
-	krb5_data */*enc_data*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_decomp_ticket (
-	krb5_context /*context*/,
-	const krb5_data */*enc_ticket*/,
-	const krb5_keyblock */*key*/,
-	const char */*local_realm*/,
-	char **/*sname*/,
-	char **/*sinstance*/,
-	struct _krb5_krb_auth_data */*ad*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_dest_tkt (
-	krb5_context /*context*/,
-	const char */*tkfile*/);
-
-void KRB5_LIB_FUNCTION
-_krb5_krb_free_auth_data (
-	krb5_context /*context*/,
-	struct _krb5_krb_auth_data */*ad*/);
-
-time_t KRB5_LIB_FUNCTION
-_krb5_krb_life_to_time (
-	int /*start*/,
-	int /*life_*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_rd_req (
-	krb5_context /*context*/,
-	krb5_data */*authent*/,
-	const char */*service*/,
-	const char */*instance*/,
-	const char */*local_realm*/,
-	int32_t /*from_addr*/,
-	const krb5_keyblock */*key*/,
-	struct _krb5_krb_auth_data */*ad*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_krb_tf_setup (
-	krb5_context /*context*/,
-	struct credentials */*v4creds*/,
-	const char */*tkfile*/,
-	int /*append*/);
-
-int KRB5_LIB_FUNCTION
-_krb5_krb_time_to_life (
-	time_t /*start*/,
-	time_t /*end*/);
-
 krb5_error_code
 _krb5_krbhost_info_move (
 	krb5_context /*context*/,
 	krb5_krbhst_info */*from*/,
 	krb5_krbhst_info **/*to*/);
=20
+const char *
+_krb5_krbhst_get_realm (krb5_krbhst_handle /*handle*/);
+
+krb5_error_code
+_krb5_kt_principal_not_found (
+	krb5_context /*context*/,
+	krb5_error_code /*ret*/,
+	krb5_keytab /*id*/,
+	krb5_const_principal /*principal*/,
+	krb5_enctype /*enctype*/,
+	int /*kvno*/);
+
+krb5_error_code
+_krb5_load_ccache_plugins (krb5_context /*context*/);
+
+void
+_krb5_load_plugins (
+	krb5_context /*context*/,
+	const char */*name*/,
+	const char **/*paths*/);
+
 krb5_error_code
 _krb5_mk_req_internal (
 	krb5_context /*context*/,
@@ -276,19 +393,13 @@
 	krb5_key_usage /*checksum_usage*/,
 	krb5_key_usage /*encrypt_usage*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_n_fold (
 	const void */*str*/,
 	size_t /*len*/,
 	void */*key*/,
 	size_t /*size*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_oid_to_enctype (
-	krb5_context /*context*/,
-	const heim_oid */*oid*/,
-	krb5_enctype */*etype*/);
-
 krb5_error_code
 _krb5_pac_sign (
 	krb5_context /*context*/,
@@ -313,15 +424,24 @@
 	char */*p*/,
 	struct krb5_dh_moduli **/*m*/);
=20
-void KRB5_LIB_FUNCTION
-_krb5_pk_allow_proxy_certificate (
-	struct krb5_pk_identity */*id*/,
-	int /*boolean*/);
-
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 _krb5_pk_cert_free (struct krb5_pk_cert */*cert*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+krb5_error_code
+_krb5_pk_kdf (
+	krb5_context /*context*/,
+	const struct AlgorithmIdentifier */*ai*/,
+	const void */*dhdata*/,
+	size_t /*dhsize*/,
+	krb5_const_principal /*client*/,
+	krb5_const_principal /*server*/,
+	krb5_enctype /*enctype*/,
+	const krb5_data */*as_req*/,
+	const krb5_data */*pk_as_rep*/,
+	const Ticket */*ticket*/,
+	krb5_keyblock */*key*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_load_id (
 	krb5_context /*context*/,
 	struct krb5_pk_identity **/*ret_id*/,
@@ -333,17 +453,19 @@
 	void */*prompter_data*/,
 	char */*password*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_mk_ContentInfo (
 	krb5_context /*context*/,
 	const krb5_data */*buf*/,
 	const heim_oid */*oid*/,
 	struct ContentInfo */*content_info*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_mk_padata (
 	krb5_context /*context*/,
 	void */*c*/,
+	int /*ic_flags*/,
+	int /*win2k*/,
 	const KDC_REQ_BODY */*req_body*/,
 	unsigned /*nonce*/,
 	METHOD_DATA */*md*/);
@@ -358,7 +480,7 @@
 	const heim_octet_string */*k_n*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_rd_pa_reply (
 	krb5_context /*context*/,
 	const char */*realm*/,
@@ -370,16 +492,6 @@
 	PA_DATA */*pa*/,
 	krb5_keyblock **/*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_pk_verify_sign (
-	krb5_context /*context*/,
-	const void */*data*/,
-	size_t /*length*/,
-	struct krb5_pk_identity */*id*/,
-	heim_oid */*contentType*/,
-	krb5_data */*content*/,
-	struct krb5_pk_cert **/*signer*/);
-
 krb5_error_code
 _krb5_plugin_find (
 	krb5_context /*context*/,
@@ -396,30 +508,41 @@
 void *
 _krb5_plugin_get_symbol (struct krb5_plugin */*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+krb5_error_code
+_krb5_plugin_run_f (
+	krb5_context /*context*/,
+	const char */*module*/,
+	const char */*name*/,
+	int /*min_version*/,
+	int /*flags*/,
+	void */*userctx*/,
+	krb5_error_code (*/*func*/)(krb5_context, const void *, void *, void *));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_principal2principalname (
 	PrincipalName */*p*/,
 	const krb5_principal /*from*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_principal_compare_PrincipalName (
+	krb5_context /*context*/,
+	krb5_const_principal /*princ1*/,
+	PrincipalName */*princ2*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_principalname2krb5_principal (
 	krb5_context /*context*/,
 	krb5_principal */*principal*/,
 	const PrincipalName /*from*/,
 	const Realm /*realm*/);
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 _krb5_put_int (
 	void */*buffer*/,
 	unsigned long /*value*/,
 	size_t /*size*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_rd_req_out_ctx_alloc (
-	krb5_context /*context*/,
-	krb5_rd_req_out_ctx */*ctx*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_s4u2self_to_checksumdata (
 	krb5_context /*context*/,
 	const PA_S4U2Self */*self*/,
@@ -427,21 +550,44 @@
=20
 int
 _krb5_send_and_recv_tcp (
-	int /*fd*/,
+	krb5_socket_t /*fd*/,
 	time_t /*tmout*/,
 	const krb5_data */*req*/,
 	krb5_data */*rep*/);
=20
 int
+_krb5_set_default_cc_name_to_registry (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/);
+
+void
+_krb5_unload_plugins (
+	krb5_context /*context*/,
+	const char */*name*/);
+
+krb5_error_code
+_krb5_usage2arcfour (
+	krb5_context /*context*/,
+	unsigned */*usage*/);
+
+int
 _krb5_xlock (
 	krb5_context /*context*/,
 	int /*fd*/,
 	krb5_boolean /*exclusive*/,
 	const char */*filename*/);
=20
+void
+_krb5_xor (
+	DES_cblock */*key*/,
+	const unsigned char */*b*/);
+
 int
 _krb5_xunlock (
 	krb5_context /*context*/,
 	int /*fd*/);
=20
+#undef KRB5_DEPRECATED_FUNCTION
+#define KRB5_DEPRECATED_FUNCTION(X)
+
 #endif /* __krb5_private_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5-prot=
os.h
--- a/head/crypto/heimdal/lib/krb5/krb5-protos.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/krb5-protos.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -8,119 +8,98 @@
 #define __attribute__(x)
 #endif
=20
+#ifndef KRB5_DEPRECATED_FUNCTION
+#if defined(__GNUC__) && ((__GNUC__ > 3) || ((__GNUC__ =3D=3D 3) && (__GNU=
C_MINOR__ >=3D 1 )))
+#define KRB5_DEPRECATED_FUNCTION(X) __attribute__((__deprecated__))
+#else
+#define KRB5_DEPRECATED_FUNCTION(X)
+#endif
+#endif
+
+
 #ifdef __cplusplus
 extern "C" {
 #endif
=20
+#ifndef KRB5_LIB
 #ifndef KRB5_LIB_FUNCTION
 #if defined(_WIN32)
-#define KRB5_LIB_FUNCTION _stdcall
+#define KRB5_LIB_FUNCTION __declspec(dllimport)
+#define KRB5_LIB_CALL __stdcall
+#define KRB5_LIB_VARIABLE __declspec(dllimport)
 #else
 #define KRB5_LIB_FUNCTION
+#define KRB5_LIB_CALL
+#define KRB5_LIB_VARIABLE
 #endif
 #endif
-
-krb5_error_code KRB5_LIB_FUNCTION
+#endif
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb524_convert_creds_kdc (
 	krb5_context /*context*/,
 	krb5_creds */*in_cred*/,
-	struct credentials */*v4creds*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	struct credentials */*v4creds*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb524_convert_creds_kdc_ccache (
 	krb5_context /*context*/,
 	krb5_ccache /*ccache*/,
 	krb5_creds */*in_cred*/,
-	struct credentials */*v4creds*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_425_conv_principal (
-	krb5_context /*context*/,
-	const char */*name*/,
-	const char */*instance*/,
-	const char */*realm*/,
-	krb5_principal */*princ*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_425_conv_principal_ext (
-	krb5_context /*context*/,
-	const char */*name*/,
-	const char */*instance*/,
-	const char */*realm*/,
-	krb5_boolean (*/*func*/)(krb5_context, krb5_principal),
-	krb5_boolean /*resolve*/,
-	krb5_principal */*principal*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_425_conv_principal_ext2 (
-	krb5_context /*context*/,
-	const char */*name*/,
-	const char */*instance*/,
-	const char */*realm*/,
-	krb5_boolean (*/*func*/)(krb5_context, void *, krb5_principal),
-	void */*funcctx*/,
-	krb5_boolean /*resolve*/,
-	krb5_principal */*princ*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_524_conv_principal (
-	krb5_context /*context*/,
-	const krb5_principal /*principal*/,
-	char */*name*/,
-	char */*instance*/,
-	char */*realm*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	struct credentials */*v4creds*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_abort (
 	krb5_context /*context*/,
 	krb5_error_code /*code*/,
 	const char */*fmt*/,
 	...)
-    __attribute__ ((noreturn, format (printf, 3, 4)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 3, 4)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_abortx (
 	krb5_context /*context*/,
 	const char */*fmt*/,
 	...)
-    __attribute__ ((noreturn, format (printf, 2, 3)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 2, 3)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_acl_match_file (
 	krb5_context /*context*/,
 	const char */*file*/,
 	const char */*format*/,
 	...);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_acl_match_string (
 	krb5_context /*context*/,
 	const char */*string*/,
 	const char */*format*/,
 	...);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_add_et_list (
 	krb5_context /*context*/,
 	void (*/*func*/)(struct et_list **));
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_add_extra_addresses (
 	krb5_context /*context*/,
 	krb5_addresses */*addresses*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_add_ignore_addresses (
 	krb5_context /*context*/,
 	krb5_addresses */*addresses*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_addlog_dest (
 	krb5_context /*context*/,
 	krb5_log_facility */*f*/,
 	const char */*orig*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_addlog_func (
 	krb5_context /*context*/,
 	krb5_log_facility */*fac*/,
@@ -130,7 +109,7 @@
 	krb5_log_close_func_t /*close_func*/,
 	void */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_addr2sockaddr (
 	krb5_context /*context*/,
 	const krb5_address */*addr*/,
@@ -138,19 +117,19 @@
 	krb5_socklen_t */*sa_size*/,
 	int /*port*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_address_compare (
 	krb5_context /*context*/,
 	const krb5_address */*addr1*/,
 	const krb5_address */*addr2*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_address_order (
 	krb5_context /*context*/,
 	const krb5_address */*addr1*/,
 	const krb5_address */*addr2*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_address_prefixlen_boundary (
 	krb5_context /*context*/,
 	const krb5_address */*inaddr*/,
@@ -158,20 +137,25 @@
 	krb5_address */*low*/,
 	krb5_address */*high*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_address_search (
 	krb5_context /*context*/,
 	const krb5_address */*addr*/,
 	const krb5_addresses */*addrlist*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_allow_weak_crypto (
+	krb5_context /*context*/,
+	krb5_boolean /*enable*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_aname_to_localname (
 	krb5_context /*context*/,
 	krb5_const_principal /*aname*/,
 	size_t /*lnsize*/,
 	char */*lname*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_anyaddr (
 	krb5_context /*context*/,
 	int /*af*/,
@@ -179,7 +163,7 @@
 	krb5_socklen_t */*sa_size*/,
 	int /*port*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_appdefault_boolean (
 	krb5_context /*context*/,
 	const char */*appname*/,
@@ -188,7 +172,7 @@
 	krb5_boolean /*def_val*/,
 	krb5_boolean */*ret_val*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_appdefault_string (
 	krb5_context /*context*/,
 	const char */*appname*/,
@@ -197,7 +181,7 @@
 	const char */*def_val*/,
 	char **/*ret_val*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_appdefault_time (
 	krb5_context /*context*/,
 	const char */*appname*/,
@@ -206,190 +190,221 @@
 	time_t /*def_val*/,
 	time_t */*ret_val*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_append_addresses (
 	krb5_context /*context*/,
 	krb5_addresses */*dest*/,
 	const krb5_addresses */*source*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_addflags (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	int32_t /*addflags*/,
 	int32_t */*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_free (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_genaddrs (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
-	int /*fd*/,
+	krb5_socket_t /*fd*/,
 	int /*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_generatelocalsubkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getaddrs (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_address **/*local_addr*/,
 	krb5_address **/*remote_addr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getauthenticator (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_authenticator */*authenticator*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getcksumtype (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_cksumtype */*cksumtype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getflags (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	int32_t */*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock **/*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getkeytype (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keytype */*keytype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getlocalseqnumber (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	int32_t */*seqnumber*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getlocalsubkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock **/*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_getrcache (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_rcache */*rcache*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_auth_con_getremotesubkey (
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getrecvsubkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock **/*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getremoteseqnumber (
+	krb5_context /*context*/,
+	krb5_auth_context /*auth_context*/,
+	int32_t */*seqnumber*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getremotesubkey (
+	krb5_context /*context*/,
+	krb5_auth_context /*auth_context*/,
+	krb5_keyblock **/*keyblock*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getsendsubkey (
+	krb5_context /*context*/,
+	krb5_auth_context /*auth_context*/,
+	krb5_keyblock **/*keyblock*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_init (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_removeflags (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	int32_t /*removeflags*/,
 	int32_t */*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setaddrs (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_address */*local_addr*/,
 	krb5_address */*remote_addr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setaddrs_from_fd (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	void */*p_fd*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setcksumtype (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_cksumtype /*cksumtype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setflags (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	int32_t /*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock */*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setkeytype (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keytype /*keytype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setlocalseqnumber (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	int32_t /*seqnumber*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setlocalsubkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock */*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setrcache (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_rcache /*rcache*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setrecvsubkey (
+	krb5_context /*context*/,
+	krb5_auth_context /*auth_context*/,
+	krb5_keyblock */*keyblock*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setremoteseqnumber (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	int32_t /*seqnumber*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_con_setremotesubkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock */*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_auth_con_setuserkey (
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setsendsubkey (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_keyblock */*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setuserkey (
+	krb5_context /*context*/,
+	krb5_auth_context /*auth_context*/,
+	krb5_keyblock */*keyblock*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_auth_getremoteseqnumber (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
-	int32_t */*seqnumber*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	int32_t */*seqnumber*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_ap_req (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
@@ -398,18 +413,7 @@
 	krb5_data /*authenticator*/,
 	krb5_data */*retdata*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_build_authenticator (
-	krb5_context /*context*/,
-	krb5_auth_context /*auth_context*/,
-	krb5_enctype /*enctype*/,
-	krb5_creds */*cred*/,
-	Checksum */*cksum*/,
-	Authenticator **/*auth_result*/,
-	krb5_data */*result*/,
-	krb5_key_usage /*usage*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_principal (
 	krb5_context /*context*/,
 	krb5_principal */*principal*/,
@@ -417,7 +421,7 @@
 	krb5_const_realm /*realm*/,
 	...);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_principal_ext (
 	krb5_context /*context*/,
 	krb5_principal */*principal*/,
@@ -425,7 +429,7 @@
 	krb5_const_realm /*realm*/,
 	...);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_principal_va (
 	krb5_context /*context*/,
 	krb5_principal */*principal*/,
@@ -433,7 +437,7 @@
 	krb5_const_realm /*realm*/,
 	va_list /*ap*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_principal_va_ext (
 	krb5_context /*context*/,
 	krb5_principal */*principal*/,
@@ -441,19 +445,19 @@
 	krb5_const_realm /*realm*/,
 	va_list /*ap*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_block_size (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
 	size_t */*blocksize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_checksum_length (
 	krb5_context /*context*/,
 	krb5_cksumtype /*cksumtype*/,
 	size_t */*length*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_decrypt (
 	krb5_context /*context*/,
 	const krb5_keyblock /*key*/,
@@ -462,7 +466,7 @@
 	krb5_enc_data */*input*/,
 	krb5_data */*output*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_encrypt (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
@@ -471,41 +475,42 @@
 	const krb5_data */*input*/,
 	krb5_enc_data */*output*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_encrypt_length (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
 	size_t /*inputlen*/,
 	size_t */*length*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_enctype_compare (
 	krb5_context /*context*/,
 	krb5_enctype /*e1*/,
 	krb5_enctype /*e2*/,
-	krb5_boolean */*similar*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_boolean */*similar*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_get_checksum (
 	krb5_context /*context*/,
 	const krb5_checksum */*cksum*/,
 	krb5_cksumtype */*type*/,
 	krb5_data **/*data*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_is_coll_proof_cksum (krb5_cksumtype /*ctype*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_is_keyed_cksum (krb5_cksumtype /*ctype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_keylengths (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
 	size_t */*ilen*/,
 	size_t */*keylen*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_make_checksum (
 	krb5_context /*context*/,
 	krb5_cksumtype /*cksumtype*/,
@@ -514,39 +519,44 @@
 	const krb5_data */*input*/,
 	krb5_checksum */*cksum*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_make_random_key (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
 	krb5_keyblock */*random_key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_prf (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
 	const krb5_data */*input*/,
 	krb5_data */*output*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_prf_length (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
 	size_t */*length*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_random_make_octets (
+	krb5_context /*context*/,
+	krb5_data * /*data*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_set_checksum (
 	krb5_context /*context*/,
 	krb5_checksum */*cksum*/,
 	krb5_cksumtype /*type*/,
 	const krb5_data */*data*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_valid_cksumtype (krb5_cksumtype /*ctype*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_valid_enctype (krb5_enctype /*etype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_verify_checksum (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
@@ -555,170 +565,205 @@
 	const krb5_checksum */*cksum*/,
 	krb5_boolean */*valid*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_end_seq_get (
 	krb5_context /*context*/,
 	krb5_cc_cache_cursor /*cursor*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_get_first (
 	krb5_context /*context*/,
 	const char */*type*/,
 	krb5_cc_cache_cursor */*cursor*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_match (
 	krb5_context /*context*/,
 	krb5_principal /*client*/,
-	const char */*type*/,
 	krb5_ccache */*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_cache_next (
 	krb5_context /*context*/,
 	krb5_cc_cache_cursor /*cursor*/,
 	krb5_ccache */*id*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_cc_clear_mcred (krb5_creds */*mcred*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_close (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_copy_cache (
 	krb5_context /*context*/,
 	const krb5_ccache /*from*/,
 	krb5_ccache /*to*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cc_copy_cache_match (
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_copy_creds (
+	krb5_context /*context*/,
+	const krb5_ccache /*from*/,
+	krb5_ccache /*to*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_copy_match_f (
 	krb5_context /*context*/,
 	const krb5_ccache /*from*/,
 	krb5_ccache /*to*/,
-	krb5_flags /*whichfields*/,
-	const krb5_creds * /*mcreds*/,
+	krb5_boolean (*/*match*/)(krb5_context, void *, const krb5_creds *),
+	void */*matchctx*/,
 	unsigned int */*matched*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_default (
 	krb5_context /*context*/,
 	krb5_ccache */*id*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_cc_default_name (krb5_context /*context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_destroy (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_end_seq_get (
 	krb5_context /*context*/,
 	const krb5_ccache /*id*/,
 	krb5_cc_cursor */*cursor*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_gen_new (
 	krb5_context /*context*/,
 	const krb5_cc_ops */*ops*/,
-	krb5_ccache */*id*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_ccache */*id*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_config (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	krb5_const_principal /*principal*/,
+	const char */*name*/,
+	krb5_data */*data*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_flags (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	krb5_flags */*flags*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_friendly_name (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	char **/*name*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_get_full_name (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
 	char **/*str*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_kdc_offset (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	krb5_deltat */*offset*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_get_lifetime (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	time_t */*t*/);
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_cc_get_name (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/);
=20
-const krb5_cc_ops *
+KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL
 krb5_cc_get_ops (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/);
=20
-const krb5_cc_ops *
+KRB5_LIB_FUNCTION const krb5_cc_ops * KRB5_LIB_CALL
 krb5_cc_get_prefix_ops (
 	krb5_context /*context*/,
 	const char */*prefix*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_get_principal (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
 	krb5_principal */*principal*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_cc_get_type (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_get_version (
 	krb5_context /*context*/,
 	const krb5_ccache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_initialize (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
 	krb5_principal /*primary_principal*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_last_change_time (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	krb5_timestamp */*mtime*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_move (
 	krb5_context /*context*/,
 	krb5_ccache /*from*/,
 	krb5_ccache /*to*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_new_unique (
 	krb5_context /*context*/,
 	const char */*type*/,
 	const char */*hint*/,
 	krb5_ccache */*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_next_cred (
 	krb5_context /*context*/,
 	const krb5_ccache /*id*/,
 	krb5_cc_cursor */*cursor*/,
 	krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_cc_next_cred_match (
-	krb5_context /*context*/,
-	const krb5_ccache /*id*/,
-	krb5_cc_cursor * /*cursor*/,
-	krb5_creds * /*creds*/,
-	krb5_flags /*whichfields*/,
-	const krb5_creds * /*mcreds*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_register (
 	krb5_context /*context*/,
 	const krb5_cc_ops */*ops*/,
 	krb5_boolean /*override*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_remove_cred (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
 	krb5_flags /*which*/,
 	krb5_creds */*cred*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_resolve (
 	krb5_context /*context*/,
 	const char */*name*/,
 	krb5_ccache */*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_retrieve_cred (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
@@ -726,351 +771,390 @@
 	const krb5_creds */*mcreds*/,
 	krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_config (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	krb5_const_principal /*principal*/,
+	const char */*name*/,
+	krb5_data */*data*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_set_default_name (
 	krb5_context /*context*/,
 	const char */*name*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_set_flags (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
 	krb5_flags /*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_friendly_name (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	const char */*name*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_set_kdc_offset (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/,
+	krb5_deltat /*offset*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_start_seq_get (
 	krb5_context /*context*/,
 	const krb5_ccache /*id*/,
 	krb5_cc_cursor */*cursor*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cc_store_cred (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
 	krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_cc_support_switch (
+	krb5_context /*context*/,
+	const char */*type*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_switch (
+	krb5_context /*context*/,
+	krb5_ccache /*id*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_free (
+	krb5_context /*context*/,
+	krb5_cccol_cursor */*cursor*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_new (
+	krb5_context /*context*/,
+	krb5_cccol_cursor */*cursor*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_cursor_next (
+	krb5_context /*context*/,
+	krb5_cccol_cursor /*cursor*/,
+	krb5_ccache */*cache*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cccol_last_change_time (
+	krb5_context /*context*/,
+	const char */*type*/,
+	krb5_timestamp */*mtime*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_change_password (
 	krb5_context /*context*/,
 	krb5_creds */*creds*/,
 	const char */*newpw*/,
 	int */*result_code*/,
 	krb5_data */*result_code_string*/,
-	krb5_data */*result_string*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_data */*result_string*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_check_transited (
 	krb5_context /*context*/,
 	krb5_const_realm /*client_realm*/,
 	krb5_const_realm /*server_realm*/,
 	krb5_realm */*realms*/,
-	int /*num_realms*/,
+	unsigned int /*num_realms*/,
 	int */*bad_realm*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_check_transited_realms (
 	krb5_context /*context*/,
 	const char *const */*realms*/,
-	int /*num_realms*/,
+	unsigned int /*num_realms*/,
 	int */*bad_realm*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_checksum_disable (
 	krb5_context /*context*/,
 	krb5_cksumtype /*type*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_checksum_free (
 	krb5_context /*context*/,
 	krb5_checksum */*cksum*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_checksum_is_collision_proof (
 	krb5_context /*context*/,
 	krb5_cksumtype /*type*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_checksum_is_keyed (
 	krb5_context /*context*/,
 	krb5_cksumtype /*type*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_checksumsize (
 	krb5_context /*context*/,
 	krb5_cksumtype /*type*/,
 	size_t */*size*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cksumtype_to_enctype (
+	krb5_context /*context*/,
+	krb5_cksumtype /*ctype*/,
+	krb5_enctype */*etype*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_cksumtype_valid (
 	krb5_context /*context*/,
 	krb5_cksumtype /*ctype*/);
=20
-void KRB5_LIB_FUNCTION
-krb5_clear_error_string (krb5_context /*context*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_clear_error_message (krb5_context /*context*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_clear_error_string (krb5_context /*context*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_closelog (
 	krb5_context /*context*/,
 	krb5_log_facility */*fac*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_compare_creds (
 	krb5_context /*context*/,
 	krb5_flags /*whichfields*/,
 	const krb5_creds * /*mcreds*/,
 	const krb5_creds * /*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_config_file_free (
 	krb5_context /*context*/,
 	krb5_config_section */*s*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_config_free_strings (char **/*strings*/);
=20
-const void *
-krb5_config_get (
-	krb5_context /*context*/,
-	const krb5_config_section */*c*/,
-	int /*type*/,
-	...);
-
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_get_bool (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	...);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_get_bool_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	krb5_boolean /*def_value*/,
 	...);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_int (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	...);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_int_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	int /*def_value*/,
 	...);
=20
-const krb5_config_binding *
+KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL
 krb5_config_get_list (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	...);
=20
-const void *
-krb5_config_get_next (
-	krb5_context /*context*/,
-	const krb5_config_section */*c*/,
-	const krb5_config_binding **/*pointer*/,
-	int /*type*/,
-	...);
-
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_get_string (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	...);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_get_string_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	const char */*def_value*/,
 	...);
=20
-char**
+KRB5_LIB_FUNCTION char** KRB5_LIB_CALL
 krb5_config_get_strings (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	...);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_time (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	...);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_get_time_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	int /*def_value*/,
 	...);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_config_parse_file (
 	krb5_context /*context*/,
 	const char */*fname*/,
 	krb5_config_section **/*res*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_config_parse_file_multi (
 	krb5_context /*context*/,
 	const char */*fname*/,
 	krb5_config_section **/*res*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_config_parse_string_multi (
 	krb5_context /*context*/,
 	const char */*string*/,
-	krb5_config_section **/*res*/);
-
-const void *
-krb5_config_vget (
-	krb5_context /*context*/,
-	const krb5_config_section */*c*/,
-	int /*type*/,
-	va_list /*args*/);
-
-krb5_boolean KRB5_LIB_FUNCTION
+	krb5_config_section **/*res*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_vget_bool (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	va_list /*args*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_config_vget_bool_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	krb5_boolean /*def_value*/,
 	va_list /*args*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_int (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	va_list /*args*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_int_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	int /*def_value*/,
 	va_list /*args*/);
=20
-const krb5_config_binding *
+KRB5_LIB_FUNCTION const krb5_config_binding * KRB5_LIB_CALL
 krb5_config_vget_list (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	va_list /*args*/);
=20
-const void *
-krb5_config_vget_next (
-	krb5_context /*context*/,
-	const krb5_config_section */*c*/,
-	const krb5_config_binding **/*pointer*/,
-	int /*type*/,
-	va_list /*args*/);
-
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_vget_string (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	va_list /*args*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_config_vget_string_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	const char */*def_value*/,
 	va_list /*args*/);
=20
-char ** KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION char ** KRB5_LIB_CALL
 krb5_config_vget_strings (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	va_list /*args*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_time (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	va_list /*args*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_config_vget_time_default (
 	krb5_context /*context*/,
 	const krb5_config_section */*c*/,
 	int /*def_value*/,
 	va_list /*args*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_address (
 	krb5_context /*context*/,
 	const krb5_address */*inaddr*/,
 	krb5_address */*outaddr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_addresses (
 	krb5_context /*context*/,
 	const krb5_addresses */*inaddr*/,
 	krb5_addresses */*outaddr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_checksum (
 	krb5_context /*context*/,
 	const krb5_checksum */*old*/,
 	krb5_checksum **/*new*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_copy_context (
+	krb5_context /*context*/,
+	krb5_context */*out*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_creds (
 	krb5_context /*context*/,
 	const krb5_creds */*incred*/,
 	krb5_creds **/*outcred*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_creds_contents (
 	krb5_context /*context*/,
 	const krb5_creds */*incred*/,
 	krb5_creds */*c*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_data (
 	krb5_context /*context*/,
 	const krb5_data */*indata*/,
 	krb5_data **/*outdata*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_host_realm (
 	krb5_context /*context*/,
 	const krb5_realm */*from*/,
 	krb5_realm **/*to*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_keyblock (
 	krb5_context /*context*/,
 	const krb5_keyblock */*inblock*/,
 	krb5_keyblock **/*to*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_keyblock_contents (
 	krb5_context /*context*/,
 	const krb5_keyblock */*inblock*/,
 	krb5_keyblock */*to*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_principal (
 	krb5_context /*context*/,
 	krb5_const_principal /*inprinc*/,
 	krb5_principal */*outprinc*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_ticket (
 	krb5_context /*context*/,
 	const krb5_ticket */*from*/,
 	krb5_ticket **/*to*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_create_checksum (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -1080,164 +1164,213 @@
 	size_t /*len*/,
 	Checksum */*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_create_checksum_iov (
+	krb5_context /*context*/,
+	krb5_crypto /*crypto*/,
+	unsigned /*usage*/,
+	krb5_crypto_iov */*data*/,
+	unsigned int /*num_data*/,
+	krb5_cksumtype */*type*/);
+
+KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL
+krb5_creds_get_ticket_flags (krb5_creds */*creds*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_destroy (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_fx_cf2 (
+	krb5_context /*context*/,
+	const krb5_crypto /*crypto1*/,
+	const krb5_crypto /*crypto2*/,
+	krb5_data */*pepper1*/,
+	krb5_data */*pepper2*/,
+	krb5_enctype /*enctype*/,
+	krb5_keyblock */*res*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_get_checksum_type (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
 	krb5_cksumtype */*type*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getblocksize (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
 	size_t */*blocksize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getconfoundersize (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
 	size_t */*confoundersize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getenctype (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
 	krb5_enctype */*enctype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_getpadsize (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
 	size_t */*padsize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_init (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
 	krb5_enctype /*etype*/,
 	krb5_crypto */*crypto*/);
=20
-size_t
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_length (
+	krb5_context /*context*/,
+	krb5_crypto /*crypto*/,
+	int /*type*/,
+	size_t */*len*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_crypto_length_iov (
+	krb5_context /*context*/,
+	krb5_crypto /*crypto*/,
+	krb5_crypto_iov */*data*/,
+	unsigned int /*num_data*/);
+
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
 krb5_crypto_overhead (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_prf (
 	krb5_context /*context*/,
 	const krb5_crypto /*crypto*/,
 	const krb5_data */*input*/,
 	krb5_data */*output*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_crypto_prf_length (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
 	size_t */*length*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_data_alloc (
 	krb5_data */*p*/,
 	int /*len*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_data_cmp (
 	const krb5_data */*data1*/,
 	const krb5_data */*data2*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_data_copy (
 	krb5_data */*p*/,
 	const void */*data*/,
 	size_t /*len*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_data_ct_cmp (
+	const krb5_data */*data1*/,
+	const krb5_data */*data2*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_data_free (krb5_data */*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_data_realloc (
 	krb5_data */*p*/,
 	int /*len*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_data_zero (krb5_data */*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_Authenticator (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	Authenticator */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_ETYPE_INFO (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	ETYPE_INFO */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_ETYPE_INFO2 (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	ETYPE_INFO2 */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncAPRepPart (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	EncAPRepPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncASRepPart (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	EncASRepPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncKrbCredPart (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	EncKrbCredPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncTGSRepPart (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	EncTGSRepPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_EncTicketPart (
 	krb5_context /*context*/,
 	const void */*data*/,
 	size_t /*length*/,
 	EncTicketPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_ap_req (
 	krb5_context /*context*/,
 	const krb5_data */*inbuf*/,
 	krb5_ap_req */*ap_req*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -1246,7 +1379,7 @@
 	size_t /*len*/,
 	krb5_data */*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt_EncryptedData (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -1254,7 +1387,16 @@
 	const EncryptedData */*e*/,
 	krb5_data */*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_decrypt_iov_ivec (
+	krb5_context /*context*/,
+	krb5_crypto /*crypto*/,
+	unsigned /*usage*/,
+	krb5_crypto_iov */*data*/,
+	unsigned int /*num_data*/,
+	void */*ivec*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt_ivec (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -1264,7 +1406,7 @@
 	krb5_data */*result*/,
 	void */*ivec*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt_ticket (
 	krb5_context /*context*/,
 	Ticket */*ticket*/,
@@ -1272,7 +1414,7 @@
 	EncTicketPart */*out*/,
 	krb5_flags /*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_derive_key (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
@@ -1281,267 +1423,275 @@
 	size_t /*constant_len*/,
 	krb5_keyblock **/*derived_key*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_alloc (
 	krb5_context /*context*/,
 	krb5_digest */*digest*/);
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_digest_free (krb5_digest /*digest*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_get_client_binding (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	char **/*type*/,
 	char **/*binding*/);
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_identifier (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/);
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_opaque (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/);
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_rsp (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/);
=20
-const char *
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
 krb5_digest_get_server_nonce (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_get_session_key (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	krb5_data */*data*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_get_tickets (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	Ticket **/*tickets*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_init_request (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	krb5_realm /*realm*/,
 	krb5_ccache /*ccache*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_probe (
 	krb5_context /*context*/,
 	krb5_realm /*realm*/,
 	krb5_ccache /*ccache*/,
 	unsigned */*flags*/);
=20
-krb5_boolean
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_digest_rep_get_status (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_request (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	krb5_realm /*realm*/,
 	krb5_ccache /*ccache*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_authentication_user (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	krb5_principal /*authentication_user*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_authid (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*authid*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_client_nonce (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*nonce*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_digest (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*dgst*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_hostname (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*hostname*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_identifier (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*id*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_method (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*method*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_nonceCount (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*nonce_count*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_opaque (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*opaque*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_qop (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*qop*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_realm (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*realm*/);
=20
-int
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_digest_set_responseData (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*response*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_server_cb (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*type*/,
 	const char */*binding*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_server_nonce (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*nonce*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_type (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*type*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_uri (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*uri*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_digest_set_username (
 	krb5_context /*context*/,
 	krb5_digest /*digest*/,
 	const char */*username*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_domain_x500_decode (
 	krb5_context /*context*/,
 	krb5_data /*tr*/,
 	char ***/*realms*/,
-	int */*num_realms*/,
+	unsigned int */*num_realms*/,
 	const char */*client_realm*/,
 	const char */*server_realm*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_domain_x500_encode (
 	char **/*realms*/,
-	int /*num_realms*/,
+	unsigned int /*num_realms*/,
 	krb5_data */*encoding*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_eai_to_heim_errno (
 	int /*eai_errno*/,
 	int /*system_error*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_Authenticator (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	Authenticator */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_ETYPE_INFO (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	ETYPE_INFO */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_ETYPE_INFO2 (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	ETYPE_INFO2 */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncAPRepPart (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	EncAPRepPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncASRepPart (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	EncASRepPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncKrbCredPart (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	EncKrbCredPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncTGSRepPart (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	EncTGSRepPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encode_EncTicketPart (
 	krb5_context /*context*/,
 	void */*data*/,
 	size_t /*length*/,
 	EncTicketPart */*t*/,
-	size_t */*len*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	size_t */*len*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encrypt (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -1550,7 +1700,7 @@
 	size_t /*len*/,
 	krb5_data */*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encrypt_EncryptedData (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -1560,7 +1710,16 @@
 	int /*kvno*/,
 	EncryptedData */*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_encrypt_iov_ivec (
+	krb5_context /*context*/,
+	krb5_crypto /*crypto*/,
+	unsigned /*usage*/,
+	krb5_crypto_iov */*data*/,
+	int /*num_data*/,
+	void */*ivec*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_encrypt_ivec (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -1570,93 +1729,99 @@
 	krb5_data */*result*/,
 	void */*ivec*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_disable (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_enctype_enable (
+	krb5_context /*context*/,
+	krb5_enctype /*enctype*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_keybits (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
 	size_t */*keybits*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_keysize (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
 	size_t */*keysize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_to_keytype (
 	krb5_context /*context*/,
 	krb5_enctype /*etype*/,
 	krb5_keytype */*keytype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_to_string (
 	krb5_context /*context*/,
 	krb5_enctype /*etype*/,
 	char **/*string*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_enctype_valid (
 	krb5_context /*context*/,
 	krb5_enctype /*etype*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_enctypes_compatible_keys (
 	krb5_context /*context*/,
 	krb5_enctype /*etype1*/,
-	krb5_enctype /*etype2*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_enctype /*etype2*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+krb5_error_code
+krb5_enomem (krb5_context /*context*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_err (
 	krb5_context /*context*/,
 	int /*eval*/,
 	krb5_error_code /*code*/,
 	const char */*fmt*/,
 	...)
-    __attribute__ ((noreturn, format (printf, 4, 5)));
-
-krb5_error_code KRB5_LIB_FUNCTION=20
-    __attribute__((deprecated)) krb5_free_creds_contents (krb5_context con=
text, krb5_creds *c);
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 4, 5)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_error_from_rd_error (
 	krb5_context /*context*/,
 	const krb5_error */*error*/,
 	const krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_errx (
 	krb5_context /*context*/,
 	int /*eval*/,
 	const char */*fmt*/,
 	...)
-    __attribute__ ((noreturn, format (printf, 3, 4)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 3, 4)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_expand_hostname (
 	krb5_context /*context*/,
 	const char */*orig_hostname*/,
 	char **/*new_hostname*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_expand_hostname_realms (
 	krb5_context /*context*/,
 	const char */*orig_hostname*/,
 	char **/*new_hostname*/,
 	char ***/*realms*/);
=20
-PA_DATA *
+KRB5_LIB_FUNCTION PA_DATA * KRB5_LIB_CALL
 krb5_find_padata (
 	PA_DATA */*val*/,
 	unsigned /*len*/,
 	int /*type*/,
 	int */*idx*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_format_time (
 	krb5_context /*context*/,
 	time_t /*t*/,
@@ -1664,118 +1829,142 @@
 	size_t /*len*/,
 	krb5_boolean /*include_time*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_address (
 	krb5_context /*context*/,
 	krb5_address */*address*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_addresses (
 	krb5_context /*context*/,
 	krb5_addresses */*addresses*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_ap_rep_enc_part (
 	krb5_context /*context*/,
 	krb5_ap_rep_enc_part */*val*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_authenticator (
 	krb5_context /*context*/,
 	krb5_authenticator */*authenticator*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_checksum (
 	krb5_context /*context*/,
 	krb5_checksum */*cksum*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_checksum_contents (
 	krb5_context /*context*/,
 	krb5_checksum */*cksum*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_config_files (char **/*filenames*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_context (krb5_context /*context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_cred_contents (
 	krb5_context /*context*/,
 	krb5_creds */*c*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_creds (
 	krb5_context /*context*/,
 	krb5_creds */*c*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_creds_contents (
+	krb5_context /*context*/,
+	krb5_creds */*c*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_data (
 	krb5_context /*context*/,
 	krb5_data */*p*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_data_contents (
 	krb5_context /*context*/,
-	krb5_data */*data*/);
-
-void KRB5_LIB_FUNCTION
+	krb5_data */*data*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_default_realm (
+	krb5_context /*context*/,
+	krb5_realm /*realm*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_error (
 	krb5_context /*context*/,
 	krb5_error */*error*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_error_contents (
 	krb5_context /*context*/,
 	krb5_error */*error*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_error_message (
+	krb5_context /*context*/,
+	const char */*msg*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_error_string (
 	krb5_context /*context*/,
-	char */*str*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	char */*str*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_host_realm (
 	krb5_context /*context*/,
 	krb5_realm */*realmlist*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_kdc_rep (
 	krb5_context /*context*/,
 	krb5_kdc_rep */*rep*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_keyblock (
 	krb5_context /*context*/,
 	krb5_keyblock */*keyblock*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_keyblock_contents (
 	krb5_context /*context*/,
 	krb5_keyblock */*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_krbhst (
 	krb5_context /*context*/,
 	char **/*hostlist*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_principal (
 	krb5_context /*context*/,
 	krb5_principal /*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_salt (
 	krb5_context /*context*/,
 	krb5_salt /*salt*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_ticket (
 	krb5_context /*context*/,
 	krb5_ticket */*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_free_unparsed_name (
+	krb5_context /*context*/,
+	char */*str*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_fwd_tgt_creds (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
@@ -1786,64 +1975,67 @@
 	int /*forwardable*/,
 	krb5_data */*out_data*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_generate_random_block (
 	void */*buf*/,
 	size_t /*len*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_generate_random_keyblock (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_generate_seq_number (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
 	uint32_t */*seqno*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_generate_subkey (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
-	krb5_keyblock **/*subkey*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_keyblock **/*subkey*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_generate_subkey_extended (
 	krb5_context /*context*/,
 	const krb5_keyblock */*key*/,
 	krb5_enctype /*etype*/,
 	krb5_keyblock **/*subkey*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_all_client_addrs (
 	krb5_context /*context*/,
 	krb5_addresses */*res*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_all_server_addrs (
 	krb5_context /*context*/,
 	krb5_addresses */*res*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_cred_from_kdc (
 	krb5_context /*context*/,
 	krb5_ccache /*ccache*/,
 	krb5_creds */*in_creds*/,
 	krb5_creds **/*out_creds*/,
-	krb5_creds ***/*ret_tgts*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_creds ***/*ret_tgts*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_cred_from_kdc_opt (
 	krb5_context /*context*/,
 	krb5_ccache /*ccache*/,
 	krb5_creds */*in_creds*/,
 	krb5_creds **/*out_creds*/,
 	krb5_creds ***/*ret_tgts*/,
-	krb5_flags /*flags*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_flags /*flags*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_credentials (
 	krb5_context /*context*/,
 	krb5_flags /*options*/,
@@ -1851,7 +2043,7 @@
 	krb5_creds */*in_creds*/,
 	krb5_creds **/*out_creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_credentials_with_flags (
 	krb5_context /*context*/,
 	krb5_flags /*options*/,
@@ -1860,7 +2052,7 @@
 	krb5_creds */*in_creds*/,
 	krb5_creds **/*out_creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds (
 	krb5_context /*context*/,
 	krb5_get_creds_opt /*opt*/,
@@ -1868,96 +2060,98 @@
 	krb5_const_principal /*inprinc*/,
 	krb5_creds **/*out_creds*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_add_options (
 	krb5_context /*context*/,
 	krb5_get_creds_opt /*opt*/,
 	krb5_flags /*options*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds_opt_alloc (
 	krb5_context /*context*/,
 	krb5_get_creds_opt */*opt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_free (
 	krb5_context /*context*/,
 	krb5_get_creds_opt /*opt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_set_enctype (
 	krb5_context /*context*/,
 	krb5_get_creds_opt /*opt*/,
 	krb5_enctype /*enctype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds_opt_set_impersonate (
 	krb5_context /*context*/,
 	krb5_get_creds_opt /*opt*/,
 	krb5_const_principal /*self*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_creds_opt_set_options (
 	krb5_context /*context*/,
 	krb5_get_creds_opt /*opt*/,
 	krb5_flags /*options*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_creds_opt_set_ticket (
 	krb5_context /*context*/,
 	krb5_get_creds_opt /*opt*/,
 	const Ticket */*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_config_files (char ***/*pfilenames*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_in_tkt_etypes (
 	krb5_context /*context*/,
+	krb5_pdu /*pdu_type*/,
 	krb5_enctype **/*etypes*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_principal (
 	krb5_context /*context*/,
 	krb5_principal */*princ*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_realm (
 	krb5_context /*context*/,
 	krb5_realm */*realm*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_default_realms (
 	krb5_context /*context*/,
 	krb5_realm **/*realms*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_get_dns_canonicalize_hostname (krb5_context /*context*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_get_err_text (
 	krb5_context /*context*/,
+	krb5_error_code /*code*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION const char * KRB5_LIB_CALL
+krb5_get_error_message (
+	krb5_context /*context*/,
 	krb5_error_code /*code*/);
=20
-char * KRB5_LIB_FUNCTION
-krb5_get_error_message (
-	krb5_context /*context*/,
-	krb5_error_code /*code*/);
-
-char * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION char * KRB5_LIB_CALL
 krb5_get_error_string (krb5_context /*context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_extra_addresses (
 	krb5_context /*context*/,
 	krb5_addresses */*addresses*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_fcache_version (
 	krb5_context /*context*/,
 	int */*version*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_forwarded_creds (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
@@ -1967,18 +2161,18 @@
 	krb5_creds */*in_creds*/,
 	krb5_data */*out_data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_host_realm (
 	krb5_context /*context*/,
 	const char */*targethost*/,
 	krb5_realm **/*realms*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_ignore_addresses (
 	krb5_context /*context*/,
 	krb5_addresses */*addresses*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_in_cred (
 	krb5_context /*context*/,
 	krb5_flags /*options*/,
@@ -1991,9 +2185,10 @@
 	krb5_decrypt_proc /*decrypt_proc*/,
 	krb5_const_pointer /*decryptarg*/,
 	krb5_creds */*creds*/,
-	krb5_kdc_rep */*ret_as_reply*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_kdc_rep */*ret_as_reply*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_in_tkt (
 	krb5_context /*context*/,
 	krb5_flags /*options*/,
@@ -2006,9 +2201,10 @@
 	krb5_const_pointer /*decryptarg*/,
 	krb5_creds */*creds*/,
 	krb5_ccache /*ccache*/,
-	krb5_kdc_rep */*ret_as_reply*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_kdc_rep */*ret_as_reply*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_in_tkt_with_keytab (
 	krb5_context /*context*/,
 	krb5_flags /*options*/,
@@ -2018,9 +2214,10 @@
 	krb5_keytab /*keytab*/,
 	krb5_ccache /*ccache*/,
 	krb5_creds */*creds*/,
-	krb5_kdc_rep */*ret_as_reply*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_kdc_rep */*ret_as_reply*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_in_tkt_with_password (
 	krb5_context /*context*/,
 	krb5_flags /*options*/,
@@ -2030,9 +2227,10 @@
 	const char */*password*/,
 	krb5_ccache /*ccache*/,
 	krb5_creds */*creds*/,
-	krb5_kdc_rep */*ret_as_reply*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_kdc_rep */*ret_as_reply*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_in_tkt_with_skey (
 	krb5_context /*context*/,
 	krb5_flags /*options*/,
@@ -2042,20 +2240,10 @@
 	const krb5_keyblock */*key*/,
 	krb5_ccache /*ccache*/,
 	krb5_creds */*creds*/,
-	krb5_kdc_rep */*ret_as_reply*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_init_creds (
-	krb5_context /*context*/,
-	krb5_creds */*creds*/,
-	krb5_principal /*client*/,
-	krb5_prompter_fct /*prompter*/,
-	void */*data*/,
-	krb5_deltat /*start_time*/,
-	const char */*in_tkt_service*/,
-	krb5_get_init_creds_opt */*options*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_kdc_rep */*ret_as_reply*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_keyblock (
 	krb5_context /*context*/,
 	krb5_creds */*creds*/,
@@ -2065,7 +2253,7 @@
 	const char */*in_tkt_service*/,
 	krb5_get_init_creds_opt */*options*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_keytab (
 	krb5_context /*context*/,
 	krb5_creds */*creds*/,
@@ -2075,79 +2263,81 @@
 	const char */*in_tkt_service*/,
 	krb5_get_init_creds_opt */*options*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_alloc (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt **/*opt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_free (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_get_error (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/,
-	KRB_ERROR **/*error*/);
-
-void KRB5_LIB_FUNCTION
-krb5_get_init_creds_opt_init (krb5_get_init_creds_opt */*opt*/);
-
-void KRB5_LIB_FUNCTION
+	KRB_ERROR **/*error*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_get_init_creds_opt_init (krb5_get_init_creds_opt */*opt*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_address_list (
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_addresses */*addresses*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_addressless (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_boolean /*addressless*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_anonymous (
 	krb5_get_init_creds_opt */*opt*/,
 	int /*anonymous*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_canonicalize (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_boolean /*req*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_default_flags (
 	krb5_context /*context*/,
 	const char */*appname*/,
 	krb5_const_realm /*realm*/,
 	krb5_get_init_creds_opt */*opt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_etype_list (
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_enctype */*etype_list*/,
 	int /*etype_list_length*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_forwardable (
 	krb5_get_init_creds_opt */*opt*/,
 	int /*forwardable*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_pa_password (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/,
 	const char */*password*/,
 	krb5_s2k_proc /*key_proc*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_pac_request (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_boolean /*req_pac*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_pkinit (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/,
@@ -2161,39 +2351,52 @@
 	void */*prompter_data*/,
 	char */*password*/);
=20
-void KRB5_LIB_FUNCTION
+krb5_error_code KRB5_LIB_FUNCTION
+krb5_get_init_creds_opt_set_pkinit_user_certs (
+	krb5_context /*context*/,
+	krb5_get_init_creds_opt */*opt*/,
+	struct hx509_certs_data */*certs*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_preauth_list (
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_preauthtype */*preauth_list*/,
 	int /*preauth_list_length*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_init_creds_opt_set_process_last_req (
+	krb5_context /*context*/,
+	krb5_get_init_creds_opt */*opt*/,
+	krb5_gic_process_last_req /*func*/,
+	void */*ctx*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_proxiable (
 	krb5_get_init_creds_opt */*opt*/,
 	int /*proxiable*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_renew_life (
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_deltat /*renew_life*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_salt (
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_data */*salt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_tkt_life (
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_deltat /*tkt_life*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_win2k (
 	krb5_context /*context*/,
 	krb5_get_init_creds_opt */*opt*/,
 	krb5_boolean /*req*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_password (
 	krb5_context /*context*/,
 	krb5_creds */*creds*/,
@@ -2203,9 +2406,9 @@
 	void */*data*/,
 	krb5_deltat /*start_time*/,
 	const char */*in_tkt_service*/,
-	krb5_get_init_creds_opt */*in_options*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_get_init_creds_opt */*options*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_kdc_cred (
 	krb5_context /*context*/,
 	krb5_ccache /*id*/,
@@ -2215,46 +2418,51 @@
 	krb5_creds */*in_creds*/,
 	krb5_creds **out_creds );
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_kdc_sec_offset (
 	krb5_context /*context*/,
 	int32_t */*sec*/,
 	int32_t */*usec*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krb524hst (
 	krb5_context /*context*/,
 	const krb5_realm */*realm*/,
 	char ***/*hostlist*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krb_admin_hst (
 	krb5_context /*context*/,
 	const krb5_realm */*realm*/,
 	char ***/*hostlist*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krb_changepw_hst (
 	krb5_context /*context*/,
 	const krb5_realm */*realm*/,
 	char ***/*hostlist*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krbhst (
 	krb5_context /*context*/,
 	const krb5_realm */*realm*/,
 	char ***/*hostlist*/);
=20
-time_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
 krb5_get_max_time_skew (krb5_context /*context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_permitted_enctypes (
+	krb5_context /*context*/,
+	krb5_enctype **/*etypes*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_pw_salt (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
 	krb5_salt */*salt*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_renewed_creds (
 	krb5_context /*context*/,
 	krb5_creds */*creds*/,
@@ -2262,39 +2470,47 @@
 	krb5_ccache /*ccache*/,
 	const char */*in_tkt_service*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_server_rcache (
 	krb5_context /*context*/,
 	const krb5_data */*piece*/,
 	krb5_rcache */*id*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_get_use_admin_kdc (krb5_context /*context*/);
=20
-krb5_log_facility * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_validated_creds (
+	krb5_context /*context*/,
+	krb5_creds */*creds*/,
+	krb5_principal /*client*/,
+	krb5_ccache /*ccache*/,
+	char */*service*/);
+
+KRB5_LIB_FUNCTION krb5_log_facility * KRB5_LIB_CALL
 krb5_get_warn_dest (krb5_context /*context*/);
=20
-size_t
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
 krb5_get_wrapped_length (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
 	size_t /*data_len*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_getportbyname (
 	krb5_context /*context*/,
 	const char */*service*/,
 	const char */*proto*/,
 	int /*default_port*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_h_addr2addr (
 	krb5_context /*context*/,
 	int /*af*/,
 	const char */*haddr*/,
 	krb5_address */*addr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_h_addr2sockaddr (
 	krb5_context /*context*/,
 	int /*af*/,
@@ -2303,13 +2519,13 @@
 	krb5_socklen_t */*sa_size*/,
 	int /*port*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_h_errno_to_heim_errno (int /*eai_errno*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_have_error_string (krb5_context /*context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_hmac (
 	krb5_context /*context*/,
 	krb5_cksumtype /*cktype*/,
@@ -2319,35 +2535,111 @@
 	krb5_keyblock */*key*/,
 	Checksum */*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_init_context (krb5_context */*context*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_init_creds_free (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get_creds (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/,
+	krb5_creds */*cred*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_get_error (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/,
+	KRB_ERROR */*error*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_init (
+	krb5_context /*context*/,
+	krb5_principal /*client*/,
+	krb5_prompter_fct /*prompter*/,
+	void */*prompter_data*/,
+	krb5_deltat /*start_time*/,
+	krb5_get_init_creds_opt */*options*/,
+	krb5_init_creds_context */*rctx*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_keyblock (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/,
+	krb5_keyblock */*keyblock*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_keytab (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/,
+	krb5_keytab /*keytab*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_password (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/,
+	const char */*password*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_set_service (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/,
+	const char */*service*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_init_creds_step (
+	krb5_context /*context*/,
+	krb5_init_creds_context /*ctx*/,
+	krb5_data */*in*/,
+	krb5_data */*out*/,
+	krb5_krbhst_info */*hostinfo*/,
+	unsigned int */*flags*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_init_ets (krb5_context /*context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_init_etype (
-	krb5_context /*context*/,
-	unsigned */*len*/,
-	krb5_enctype **/*val*/,
-	const krb5_enctype */*etypes*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_initlog (
 	krb5_context /*context*/,
 	const char */*program*/,
 	krb5_log_facility **/*fac*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_is_config_principal (
+	krb5_context /*context*/,
+	krb5_const_principal /*principal*/);
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_is_thread_safe (void);
=20
-const krb5_enctype * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kcm_call (
+	krb5_context /*context*/,
+	krb5_storage */*request*/,
+	krb5_storage **/*response_p*/,
+	krb5_data */*response_data_p*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kcm_storage_request (
+	krb5_context /*context*/,
+	uint16_t /*opcode*/,
+	krb5_storage **/*storage_p*/);
+
+KRB5_LIB_FUNCTION const krb5_enctype * KRB5_LIB_CALL
 krb5_kerberos_enctypes (krb5_context /*context*/);
=20
-krb5_enctype
+KRB5_LIB_FUNCTION krb5_enctype KRB5_LIB_CALL
 krb5_keyblock_get_enctype (const krb5_keyblock */*block*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_keyblock_init (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
@@ -2355,7 +2647,7 @@
 	size_t /*size*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_keyblock_key_proc (
 	krb5_context /*context*/,
 	krb5_keytype /*type*/,
@@ -2363,63 +2655,67 @@
 	krb5_const_pointer /*keyseed*/,
 	krb5_keyblock **/*key*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_keyblock_zero (krb5_keyblock */*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV
 krb5_keytab_key_proc (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
 	krb5_salt /*salt*/,
 	krb5_const_pointer /*keyseed*/,
-	krb5_keyblock **/*key*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_keyblock **/*key*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_keytype_to_enctypes (
 	krb5_context /*context*/,
 	krb5_keytype /*keytype*/,
 	unsigned */*len*/,
-	krb5_enctype **/*val*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_enctype **/*val*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_keytype_to_enctypes_default (
 	krb5_context /*context*/,
 	krb5_keytype /*keytype*/,
 	unsigned */*len*/,
-	krb5_enctype **/*val*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_enctype **/*val*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_keytype_to_string (
 	krb5_context /*context*/,
 	krb5_keytype /*keytype*/,
-	char **/*string*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	char **/*string*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_format_string (
 	krb5_context /*context*/,
 	const krb5_krbhst_info */*host*/,
 	char */*hostname*/,
 	size_t /*hostlen*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_krbhst_free (
 	krb5_context /*context*/,
 	krb5_krbhst_handle /*handle*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_get_addrinfo (
 	krb5_context /*context*/,
 	krb5_krbhst_info */*host*/,
 	struct addrinfo **/*ai*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_init (
 	krb5_context /*context*/,
 	const char */*realm*/,
 	unsigned int /*type*/,
 	krb5_krbhst_handle */*handle*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_init_flags (
 	krb5_context /*context*/,
 	const char */*realm*/,
@@ -2427,36 +2723,36 @@
 	int /*flags*/,
 	krb5_krbhst_handle */*handle*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_next (
 	krb5_context /*context*/,
 	krb5_krbhst_handle /*handle*/,
 	krb5_krbhst_info **/*host*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_next_as_string (
 	krb5_context /*context*/,
 	krb5_krbhst_handle /*handle*/,
 	char */*hostname*/,
 	size_t /*hostlen*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_krbhst_reset (
 	krb5_context /*context*/,
 	krb5_krbhst_handle /*handle*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_add_entry (
 	krb5_context /*context*/,
 	krb5_keytab /*id*/,
 	krb5_keytab_entry */*entry*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_close (
 	krb5_context /*context*/,
 	krb5_keytab /*id*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_kt_compare (
 	krb5_context /*context*/,
 	krb5_keytab_entry */*entry*/,
@@ -2464,41 +2760,46 @@
 	krb5_kvno /*vno*/,
 	krb5_enctype /*enctype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_copy_entry_contents (
 	krb5_context /*context*/,
 	const krb5_keytab_entry */*in*/,
 	krb5_keytab_entry */*out*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_default (
 	krb5_context /*context*/,
 	krb5_keytab */*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_default_modify_name (
 	krb5_context /*context*/,
 	char */*name*/,
 	size_t /*namesize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_default_name (
 	krb5_context /*context*/,
 	char */*name*/,
 	size_t /*namesize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_kt_destroy (
+	krb5_context /*context*/,
+	krb5_keytab /*id*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_end_seq_get (
 	krb5_context /*context*/,
 	krb5_keytab /*id*/,
 	krb5_kt_cursor */*cursor*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_free_entry (
 	krb5_context /*context*/,
 	krb5_keytab_entry */*entry*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_get_entry (
 	krb5_context /*context*/,
 	krb5_keytab /*id*/,
@@ -2507,34 +2808,39 @@
 	krb5_enctype /*enctype*/,
 	krb5_keytab_entry */*entry*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_get_full_name (
 	krb5_context /*context*/,
 	krb5_keytab /*keytab*/,
 	char **/*str*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_get_name (
 	krb5_context /*context*/,
 	krb5_keytab /*keytab*/,
 	char */*name*/,
 	size_t /*namesize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_get_type (
 	krb5_context /*context*/,
 	krb5_keytab /*keytab*/,
 	char */*prefix*/,
 	size_t /*prefixsize*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_kt_have_content (
+	krb5_context /*context*/,
+	krb5_keytab /*id*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_next_entry (
 	krb5_context /*context*/,
 	krb5_keytab /*id*/,
 	krb5_keytab_entry */*entry*/,
 	krb5_kt_cursor */*cursor*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_read_service_key (
 	krb5_context /*context*/,
 	krb5_pointer /*keyprocarg*/,
@@ -2543,45 +2849,45 @@
 	krb5_enctype /*enctype*/,
 	krb5_keyblock **/*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_register (
 	krb5_context /*context*/,
 	const krb5_kt_ops */*ops*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_remove_entry (
 	krb5_context /*context*/,
 	krb5_keytab /*id*/,
 	krb5_keytab_entry */*entry*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_resolve (
 	krb5_context /*context*/,
 	const char */*name*/,
 	krb5_keytab */*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_kt_start_seq_get (
 	krb5_context /*context*/,
 	krb5_keytab /*id*/,
 	krb5_kt_cursor */*cursor*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_kuserok (
 	krb5_context /*context*/,
 	krb5_principal /*principal*/,
 	const char */*luser*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_log (
 	krb5_context /*context*/,
 	krb5_log_facility */*fac*/,
 	int /*level*/,
 	const char */*fmt*/,
 	...)
-    __attribute__((format (printf, 4, 5)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__((format (printf, 4, 5)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_log_msg (
 	krb5_context /*context*/,
 	krb5_log_facility */*fac*/,
@@ -2589,26 +2895,26 @@
 	char **/*reply*/,
 	const char */*fmt*/,
 	...)
-    __attribute__((format (printf, 5, 6)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__((format (printf, 5, 6)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_make_addrport (
 	krb5_context /*context*/,
 	krb5_address **/*res*/,
 	const krb5_address */*addr*/,
 	int16_t /*port*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_make_principal (
 	krb5_context /*context*/,
 	krb5_principal */*principal*/,
 	krb5_const_realm /*realm*/,
 	...);
=20
-size_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION size_t KRB5_LIB_CALL
 krb5_max_sockaddr_size (void);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_error (
 	krb5_context /*context*/,
 	krb5_error_code /*error_code*/,
@@ -2620,7 +2926,7 @@
 	int */*client_usec*/,
 	krb5_data */*reply*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_priv (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
@@ -2628,13 +2934,13 @@
 	krb5_data */*outbuf*/,
 	krb5_replay_data */*outdata*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_rep (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_data */*outbuf*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_req (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -2645,7 +2951,7 @@
 	krb5_ccache /*ccache*/,
 	krb5_data */*outbuf*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_req_exact (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -2655,7 +2961,7 @@
 	krb5_ccache /*ccache*/,
 	krb5_data */*outbuf*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_req_extended (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -2664,7 +2970,7 @@
 	krb5_creds */*in_creds*/,
 	krb5_data */*outbuf*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_safe (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
@@ -2672,21 +2978,21 @@
 	krb5_data */*outbuf*/,
 	krb5_replay_data */*outdata*/);
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_net_read (
 	krb5_context /*context*/,
 	void */*p_fd*/,
 	void */*buf*/,
 	size_t /*len*/);
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_net_write (
 	krb5_context /*context*/,
 	void */*p_fd*/,
 	const void */*buf*/,
 	size_t /*len*/);
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_net_write_block (
 	krb5_context /*context*/,
 	void */*p_fd*/,
@@ -2694,47 +3000,47 @@
 	size_t /*len*/,
 	time_t /*timeout*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_alloc (
 	krb5_context /*context*/,
 	krb5_ntlm */*ntlm*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_free (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_challange (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	krb5_data */*challange*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_flags (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	uint32_t */*flags*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_opaque (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	krb5_data */*opaque*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_targetinfo (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	krb5_data */*data*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_get_targetname (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	char **/*name*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_init_request (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
@@ -2744,114 +3050,114 @@
 	const char */*hostname*/,
 	const char */*domainname*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_rep_get_sessionkey (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	krb5_data */*data*/);
=20
-krb5_boolean
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_ntlm_rep_get_status (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_req_set_flags (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	uint32_t /*flags*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_req_set_lm (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	void */*hash*/,
 	size_t /*len*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_req_set_ntlm (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	void */*hash*/,
 	size_t /*len*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_req_set_opaque (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	krb5_data */*opaque*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_req_set_session (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	void */*sessionkey*/,
 	size_t /*length*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_req_set_targetname (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	const char */*targetname*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_req_set_username (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	const char */*username*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ntlm_request (
 	krb5_context /*context*/,
 	krb5_ntlm /*ntlm*/,
 	krb5_realm /*realm*/,
 	krb5_ccache /*ccache*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_openlog (
 	krb5_context /*context*/,
 	const char */*program*/,
 	krb5_log_facility **/*fac*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_add_buffer (
 	krb5_context /*context*/,
 	krb5_pac /*p*/,
 	uint32_t /*type*/,
 	const krb5_data */*data*/);
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_pac_free (
 	krb5_context /*context*/,
 	krb5_pac /*pac*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_get_buffer (
 	krb5_context /*context*/,
 	krb5_pac /*p*/,
 	uint32_t /*type*/,
 	krb5_data */*data*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_get_types (
 	krb5_context /*context*/,
 	krb5_pac /*p*/,
 	size_t */*len*/,
 	uint32_t **/*types*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_init (
 	krb5_context /*context*/,
 	krb5_pac */*pac*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_parse (
 	krb5_context /*context*/,
 	const void */*ptr*/,
 	size_t /*len*/,
 	krb5_pac */*pac*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_verify (
 	krb5_context /*context*/,
 	const krb5_pac /*pac*/,
@@ -2860,7 +3166,7 @@
 	const krb5_keyblock */*server*/,
 	const krb5_keyblock */*privsvr*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_padata_add (
 	krb5_context /*context*/,
 	METHOD_DATA */*md*/,
@@ -2868,130 +3174,165 @@
 	void */*buf*/,
 	size_t /*len*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_address (
 	krb5_context /*context*/,
 	const char */*string*/,
 	krb5_addresses */*addresses*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_name (
 	krb5_context /*context*/,
 	const char */*name*/,
 	krb5_principal */*principal*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_name_flags (
 	krb5_context /*context*/,
 	const char */*name*/,
 	int /*flags*/,
 	krb5_principal */*principal*/);
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_nametype (
 	krb5_context /*context*/,
 	const char */*str*/,
 	int32_t */*nametype*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_passwd_result_to_string (
 	krb5_context /*context*/,
 	int /*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_CALLCONV
 krb5_password_key_proc (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
 	krb5_salt /*salt*/,
 	krb5_const_pointer /*keyseed*/,
-	krb5_keyblock **/*key*/);
-
-krb5_error_code
+	krb5_keyblock **/*key*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pk_enterprise_cert (
+	krb5_context /*context*/,
+	const char */*user_id*/,
+	krb5_const_realm /*realm*/,
+	krb5_principal */*principal*/,
+	struct hx509_certs_data **/*res*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_plugin_register (
 	krb5_context /*context*/,
 	enum krb5_plugin_type /*type*/,
 	const char */*name*/,
 	void */*symbol*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_prepend_config_files (
 	const char */*filelist*/,
 	char **/*pq*/,
 	char ***/*ret_pp*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_prepend_config_files_default (
 	const char */*filelist*/,
 	char ***/*pfilenames*/);
=20
-krb5_realm * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_prepend_error_message (
+	krb5_context /*context*/,
+	krb5_error_code /*ret*/,
+	const char */*fmt*/,
+	...)
+     __attribute__ ((format (printf, 3, 4)));
+
+KRB5_LIB_FUNCTION krb5_realm * KRB5_LIB_CALL
 krb5_princ_realm (
 	krb5_context /*context*/,
-	krb5_principal /*principal*/);
-
-void KRB5_LIB_FUNCTION
+	krb5_principal /*principal*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_princ_set_realm (
 	krb5_context /*context*/,
 	krb5_principal /*principal*/,
-	krb5_realm */*realm*/);
-
-krb5_boolean KRB5_LIB_FUNCTION
+	krb5_realm */*realm*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_principal_compare (
 	krb5_context /*context*/,
 	krb5_const_principal /*princ1*/,
 	krb5_const_principal /*princ2*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_principal_compare_any_realm (
 	krb5_context /*context*/,
 	krb5_const_principal /*princ1*/,
 	krb5_const_principal /*princ2*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_principal_get_comp_string (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
 	unsigned int /*component*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION unsigned int KRB5_LIB_CALL
+krb5_principal_get_num_comp (
+	krb5_context /*context*/,
+	krb5_const_principal /*principal*/);
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_principal_get_realm (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_principal_get_type (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_is_krbtgt (
+	krb5_context /*context*/,
+	krb5_const_principal /*p*/);
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_principal_match (
 	krb5_context /*context*/,
 	krb5_const_principal /*princ*/,
 	krb5_const_principal /*pattern*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_principal_set_realm (
+	krb5_context /*context*/,
+	krb5_principal /*principal*/,
+	krb5_const_realm /*realm*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_principal_set_type (
 	krb5_context /*context*/,
 	krb5_principal /*principal*/,
 	int /*type*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_print_address (
 	const krb5_address */*addr*/,
 	char */*str*/,
 	size_t /*len*/,
 	size_t */*ret_len*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_program_setup (
 	krb5_context */*context*/,
 	int /*argc*/,
 	char **/*argv*/,
 	struct getargs */*args*/,
 	int /*num_args*/,
-	void (*/*usage*/)(int, struct getargs*, int));
-
-int KRB5_LIB_FUNCTION
+	void (KRB5_LIB_CALL *usage)(int, struct getargs*, int));
+
+KRB5_LIB_FUNCTION int KRB5_CALLCONV
 krb5_prompter_posix (
 	krb5_context /*context*/,
 	void */*data*/,
@@ -3000,7 +3341,7 @@
 	int /*num_prompts*/,
 	krb5_prompt prompts[]);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_random_to_key (
 	krb5_context /*context*/,
 	krb5_enctype /*type*/,
@@ -3008,84 +3349,84 @@
 	size_t /*size*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_close (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_default (
 	krb5_context /*context*/,
 	krb5_rcache */*id*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_default_name (krb5_context /*context*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_default_type (krb5_context /*context*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_destroy (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_expunge (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_get_lifespan (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/,
 	krb5_deltat */*auth_lifespan*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_get_name (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/);
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_get_type (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_initialize (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/,
 	krb5_deltat /*auth_lifespan*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_recover (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_resolve (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/,
 	const char */*name*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_resolve_full (
 	krb5_context /*context*/,
 	krb5_rcache */*id*/,
 	const char */*string_name*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_resolve_type (
 	krb5_context /*context*/,
 	krb5_rcache */*id*/,
 	const char */*type*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_store (
 	krb5_context /*context*/,
 	krb5_rcache /*id*/,
 	krb5_donot_replay */*rep*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_cred (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
@@ -3093,20 +3434,20 @@
 	krb5_creds ***/*ret_creds*/,
 	krb5_replay_data */*outdata*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_cred2 (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	krb5_ccache /*ccache*/,
 	krb5_data */*in_data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_error (
 	krb5_context /*context*/,
 	const krb5_data */*msg*/,
 	KRB_ERROR */*result*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_priv (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
@@ -3114,14 +3455,14 @@
 	krb5_data */*outbuf*/,
 	krb5_replay_data */*outdata*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_rep (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
 	const krb5_data */*inbuf*/,
 	krb5_ap_rep_enc_part **/*repl*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3131,7 +3472,7 @@
 	krb5_flags */*ap_req_options*/,
 	krb5_ticket **/*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_ctx (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3140,58 +3481,64 @@
 	krb5_rd_req_in_ctx /*inctx*/,
 	krb5_rd_req_out_ctx */*outctx*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_in_ctx_alloc (
 	krb5_context /*context*/,
 	krb5_rd_req_in_ctx */*ctx*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_rd_req_in_ctx_free (
 	krb5_context /*context*/,
 	krb5_rd_req_in_ctx /*ctx*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_in_set_keyblock (
 	krb5_context /*context*/,
 	krb5_rd_req_in_ctx /*in*/,
 	krb5_keyblock */*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_in_set_keytab (
 	krb5_context /*context*/,
 	krb5_rd_req_in_ctx /*in*/,
 	krb5_keytab /*keytab*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_in_set_pac_check (
 	krb5_context /*context*/,
 	krb5_rd_req_in_ctx /*in*/,
 	krb5_boolean /*flag*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_rd_req_out_ctx_free (
 	krb5_context /*context*/,
 	krb5_rd_req_out_ctx /*ctx*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_out_get_ap_req_options (
 	krb5_context /*context*/,
 	krb5_rd_req_out_ctx /*out*/,
 	krb5_flags */*ap_req_options*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_out_get_keyblock (
 	krb5_context /*context*/,
 	krb5_rd_req_out_ctx /*out*/,
 	krb5_keyblock **/*keyblock*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_server (
+	krb5_context /*context*/,
+	krb5_rd_req_out_ctx /*out*/,
+	krb5_principal */*principal*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_out_get_ticket (
 	krb5_context /*context*/,
 	krb5_rd_req_out_ctx /*out*/,
 	krb5_ticket **/*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_with_keyblock (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3201,7 +3548,7 @@
 	krb5_flags */*ap_req_options*/,
 	krb5_ticket **/*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_safe (
 	krb5_context /*context*/,
 	krb5_auth_context /*auth_context*/,
@@ -3209,33 +3556,33 @@
 	krb5_data */*outbuf*/,
 	krb5_replay_data */*outdata*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_read_message (
 	krb5_context /*context*/,
 	krb5_pointer /*p_fd*/,
 	krb5_data */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_read_priv_message (
 	krb5_context /*context*/,
 	krb5_auth_context /*ac*/,
 	krb5_pointer /*p_fd*/,
 	krb5_data */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_read_safe_message (
 	krb5_context /*context*/,
 	krb5_auth_context /*ac*/,
 	krb5_pointer /*p_fd*/,
 	krb5_data */*data*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_realm_compare (
 	krb5_context /*context*/,
 	krb5_const_principal /*princ1*/,
 	krb5_const_principal /*princ2*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_recvauth (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3246,7 +3593,7 @@
 	krb5_keytab /*keytab*/,
 	krb5_ticket **/*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_recvauth_match_version (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3258,104 +3605,104 @@
 	krb5_keytab /*keytab*/,
 	krb5_ticket **/*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_address (
 	krb5_storage */*sp*/,
 	krb5_address */*adr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_addrs (
 	krb5_storage */*sp*/,
 	krb5_addresses */*adr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_authdata (
 	krb5_storage */*sp*/,
 	krb5_authdata */*auth*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_creds (
 	krb5_storage */*sp*/,
 	krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_creds_tag (
 	krb5_storage */*sp*/,
 	krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_data (
 	krb5_storage */*sp*/,
 	krb5_data */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_int16 (
 	krb5_storage */*sp*/,
 	int16_t */*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_int32 (
 	krb5_storage */*sp*/,
 	int32_t */*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_int8 (
 	krb5_storage */*sp*/,
 	int8_t */*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_keyblock (
 	krb5_storage */*sp*/,
 	krb5_keyblock */*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_principal (
 	krb5_storage */*sp*/,
 	krb5_principal */*princ*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_string (
 	krb5_storage */*sp*/,
 	char **/*string*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_stringnl (
 	krb5_storage */*sp*/,
 	char **/*string*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_stringz (
 	krb5_storage */*sp*/,
 	char **/*string*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_times (
 	krb5_storage */*sp*/,
 	krb5_times */*times*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_uint16 (
 	krb5_storage */*sp*/,
 	uint16_t */*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_uint32 (
 	krb5_storage */*sp*/,
 	uint32_t */*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_uint8 (
 	krb5_storage */*sp*/,
 	uint8_t */*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_salttype_to_string (
 	krb5_context /*context*/,
 	krb5_enctype /*etype*/,
 	krb5_salttype /*stype*/,
 	char **/*string*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendauth (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3371,14 +3718,14 @@
 	krb5_ap_rep_enc_part **/*rep_result*/,
 	krb5_creds **/*out_creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto (
 	krb5_context /*context*/,
 	const krb5_data */*send_data*/,
 	krb5_krbhst_handle /*handle*/,
 	krb5_data */*receive*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_context (
 	krb5_context /*context*/,
 	krb5_sendto_ctx /*ctx*/,
@@ -3386,43 +3733,43 @@
 	const krb5_realm /*realm*/,
 	krb5_data */*receive*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_add_flags (
 	krb5_sendto_ctx /*ctx*/,
 	int /*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_ctx_alloc (
 	krb5_context /*context*/,
 	krb5_sendto_ctx */*ctx*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_free (
 	krb5_context /*context*/,
 	krb5_sendto_ctx /*ctx*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_sendto_ctx_get_flags (krb5_sendto_ctx /*ctx*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_set_func (
 	krb5_sendto_ctx /*ctx*/,
 	krb5_sendto_ctx_func /*func*/,
 	void */*data*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_set_type (
 	krb5_sendto_ctx /*ctx*/,
 	int /*type*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_kdc (
 	krb5_context /*context*/,
 	const krb5_data */*send_data*/,
 	const krb5_realm */*realm*/,
 	krb5_data */*receive*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_kdc_flags (
 	krb5_context /*context*/,
 	const krb5_data */*send_data*/,
@@ -3430,54 +3777,73 @@
 	krb5_data */*receive*/,
 	int /*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_config_files (
 	krb5_context /*context*/,
 	char **/*filenames*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_default_in_tkt_etypes (
 	krb5_context /*context*/,
 	const krb5_enctype */*etypes*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_default_realm (
 	krb5_context /*context*/,
 	const char */*realm*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_set_dns_canonicalize_hostname (
 	krb5_context /*context*/,
 	krb5_boolean /*flag*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_set_error_string (
-	krb5_context /*context*/,
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_set_error_message (
+	krb5_context /*context*/,
+	krb5_error_code /*ret*/,
 	const char */*fmt*/,
 	...)
-    __attribute__((format (printf, 2, 3)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((format (printf, 3, 4)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_error_string (
+	krb5_context /*context*/,
+	const char */*fmt*/,
+	...)
+     __attribute__((format (printf, 2, 3))) KRB5_DEPRECATED_FUNCTION("Use =
X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_extra_addresses (
 	krb5_context /*context*/,
 	const krb5_addresses */*addresses*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_fcache_version (
 	krb5_context /*context*/,
 	int /*version*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_set_home_dir_access (
+	krb5_context /*context*/,
+	krb5_boolean /*allow*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_ignore_addresses (
 	krb5_context /*context*/,
 	const krb5_addresses */*addresses*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_kdc_sec_offset (
+	krb5_context /*context*/,
+	int32_t /*sec*/,
+	int32_t /*usec*/);
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_set_max_time_skew (
 	krb5_context /*context*/,
 	time_t /*t*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_password (
 	krb5_context /*context*/,
 	krb5_creds */*creds*/,
@@ -3487,7 +3853,7 @@
 	krb5_data */*result_code_string*/,
 	krb5_data */*result_string*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_password_using_ccache (
 	krb5_context /*context*/,
 	krb5_ccache /*ccache*/,
@@ -3497,29 +3863,29 @@
 	krb5_data */*result_code_string*/,
 	krb5_data */*result_string*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_real_time (
 	krb5_context /*context*/,
 	krb5_timestamp /*sec*/,
 	int32_t /*usec*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_send_to_kdc_func (
 	krb5_context /*context*/,
 	krb5_send_to_kdc_func /*func*/,
 	void */*data*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_set_use_admin_kdc (
 	krb5_context /*context*/,
 	krb5_boolean /*flag*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_warn_dest (
 	krb5_context /*context*/,
 	krb5_log_facility */*fac*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sname_to_principal (
 	krb5_context /*context*/,
 	const char */*hostname*/,
@@ -3527,7 +3893,7 @@
 	int32_t /*type*/,
 	krb5_principal */*ret_princ*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sock_to_principal (
 	krb5_context /*context*/,
 	int /*sock*/,
@@ -3535,204 +3901,218 @@
 	int32_t /*type*/,
 	krb5_principal */*ret_princ*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sockaddr2address (
 	krb5_context /*context*/,
 	const struct sockaddr */*sa*/,
 	krb5_address */*addr*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sockaddr2port (
 	krb5_context /*context*/,
 	const struct sockaddr */*sa*/,
 	int16_t */*port*/);
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_sockaddr_is_loopback (const struct sockaddr */*sa*/);
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_sockaddr_uninteresting (const struct sockaddr */*sa*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_std_usage (
 	int /*code*/,
 	struct getargs */*args*/,
 	int /*num_args*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_clear_flags (
 	krb5_storage */*sp*/,
 	krb5_flags /*flags*/);
=20
-krb5_storage * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_emem (void);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_storage_free (krb5_storage */*sp*/);
=20
-krb5_storage * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_from_data (krb5_data */*data*/);
=20
-krb5_storage * KRB5_LIB_FUNCTION
-krb5_storage_from_fd (int /*fd*/);
-
-krb5_storage * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_from_fd (krb5_socket_t /*fd_in*/);
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_from_mem (
 	void */*buf*/,
 	size_t /*len*/);
=20
-krb5_storage * KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_from_readonly_mem (
 	const void */*buf*/,
 	size_t /*len*/);
=20
-krb5_flags KRB5_LIB_FUNCTION
-krb5_storage_get_byteorder (
-	krb5_storage */*sp*/,
-	krb5_flags /*byteorder*/);
-
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_flags KRB5_LIB_CALL
+krb5_storage_get_byteorder (krb5_storage */*sp*/);
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_storage_get_eof_code (krb5_storage */*sp*/);
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_storage_is_flags (
 	krb5_storage */*sp*/,
 	krb5_flags /*flags*/);
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_storage_read (
 	krb5_storage */*sp*/,
 	void */*buf*/,
 	size_t /*len*/);
=20
-off_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION off_t KRB5_LIB_CALL
 krb5_storage_seek (
 	krb5_storage */*sp*/,
 	off_t /*offset*/,
 	int /*whence*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_set_byteorder (
 	krb5_storage */*sp*/,
 	krb5_flags /*byteorder*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_set_eof_code (
 	krb5_storage */*sp*/,
 	int /*code*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_set_flags (
 	krb5_storage */*sp*/,
 	krb5_flags /*flags*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_storage_set_max_alloc (
+	krb5_storage */*sp*/,
+	size_t /*size*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_storage_to_data (
 	krb5_storage */*sp*/,
 	krb5_data */*data*/);
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_storage_truncate (
+	krb5_storage */*sp*/,
+	off_t /*offset*/);
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_storage_write (
 	krb5_storage */*sp*/,
 	const void */*buf*/,
 	size_t /*len*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_address (
 	krb5_storage */*sp*/,
 	krb5_address /*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_addrs (
 	krb5_storage */*sp*/,
 	krb5_addresses /*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_authdata (
 	krb5_storage */*sp*/,
 	krb5_authdata /*auth*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_creds (
 	krb5_storage */*sp*/,
 	krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_creds_tag (
 	krb5_storage */*sp*/,
 	krb5_creds */*creds*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_data (
 	krb5_storage */*sp*/,
 	krb5_data /*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_int16 (
 	krb5_storage */*sp*/,
 	int16_t /*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_int32 (
 	krb5_storage */*sp*/,
 	int32_t /*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_int8 (
 	krb5_storage */*sp*/,
 	int8_t /*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_keyblock (
 	krb5_storage */*sp*/,
 	krb5_keyblock /*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_principal (
 	krb5_storage */*sp*/,
 	krb5_const_principal /*p*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_string (
 	krb5_storage */*sp*/,
 	const char */*s*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_stringnl (
 	krb5_storage */*sp*/,
 	const char */*s*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_stringz (
 	krb5_storage */*sp*/,
 	const char */*s*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_times (
 	krb5_storage */*sp*/,
 	krb5_times /*times*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_uint16 (
 	krb5_storage */*sp*/,
 	uint16_t /*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_uint32 (
 	krb5_storage */*sp*/,
 	uint32_t /*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_uint8 (
 	krb5_storage */*sp*/,
 	uint8_t /*value*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_deltat (
 	const char */*string*/,
 	krb5_deltat */*deltat*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_enctype (
 	krb5_context /*context*/,
 	const char */*string*/,
 	krb5_enctype */*etype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_key (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
@@ -3740,7 +4120,7 @@
 	krb5_principal /*principal*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_key_data (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
@@ -3748,7 +4128,7 @@
 	krb5_principal /*principal*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_key_data_salt (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
@@ -3756,7 +4136,7 @@
 	krb5_salt /*salt*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_key_data_salt_opaque (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
@@ -3765,7 +4145,7 @@
 	krb5_data /*opaque*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_key_derived (
 	krb5_context /*context*/,
 	const void */*str*/,
@@ -3773,7 +4153,7 @@
 	krb5_enctype /*etype*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_key_salt (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
@@ -3781,7 +4161,7 @@
 	krb5_salt /*salt*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_key_salt_opaque (
 	krb5_context /*context*/,
 	krb5_enctype /*enctype*/,
@@ -3790,62 +4170,68 @@
 	krb5_data /*opaque*/,
 	krb5_keyblock */*key*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_keytype (
 	krb5_context /*context*/,
 	const char */*string*/,
-	krb5_keytype */*keytype*/);
-
-krb5_error_code KRB5_LIB_FUNCTION
+	krb5_keytype */*keytype*/)
+     KRB5_DEPRECATED_FUNCTION("Use X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_salttype (
 	krb5_context /*context*/,
 	krb5_enctype /*etype*/,
 	const char */*string*/,
 	krb5_salttype */*salttype*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ticket_get_authorization_data_type (
 	krb5_context /*context*/,
 	krb5_ticket */*ticket*/,
 	int /*type*/,
 	krb5_data */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ticket_get_client (
 	krb5_context /*context*/,
 	const krb5_ticket */*ticket*/,
 	krb5_principal */*client*/);
=20
-time_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
 krb5_ticket_get_endtime (
 	krb5_context /*context*/,
 	const krb5_ticket */*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL
+krb5_ticket_get_flags (
+	krb5_context /*context*/,
+	const krb5_ticket */*ticket*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ticket_get_server (
 	krb5_context /*context*/,
 	const krb5_ticket */*ticket*/,
 	krb5_principal */*server*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_timeofday (
 	krb5_context /*context*/,
 	krb5_timestamp */*timeret*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
 	char **/*name*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_fixed (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
 	char */*name*/,
 	size_t /*len*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_fixed_flags (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
@@ -3853,48 +4239,48 @@
 	char */*name*/,
 	size_t /*len*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_fixed_short (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
 	char */*name*/,
 	size_t /*len*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_flags (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
 	int /*flags*/,
 	char **/*name*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_short (
 	krb5_context /*context*/,
 	krb5_const_principal /*principal*/,
 	char **/*name*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_us_timeofday (
 	krb5_context /*context*/,
 	krb5_timestamp */*sec*/,
 	int32_t */*usec*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vabort (
 	krb5_context /*context*/,
 	krb5_error_code /*code*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__ ((noreturn, format (printf, 3, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 3, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vabortx (
 	krb5_context /*context*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__ ((noreturn, format (printf, 2, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 2, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_ap_req (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3905,7 +4291,7 @@
 	krb5_flags */*ap_req_options*/,
 	krb5_ticket **/*ticket*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_ap_req2 (
 	krb5_context /*context*/,
 	krb5_auth_context */*auth_context*/,
@@ -3917,14 +4303,14 @@
 	krb5_ticket **/*ticket*/,
 	krb5_key_usage /*usage*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_authenticator_checksum (
 	krb5_context /*context*/,
 	krb5_auth_context /*ac*/,
 	void */*data*/,
 	size_t /*len*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_checksum (
 	krb5_context /*context*/,
 	krb5_crypto /*crypto*/,
@@ -3933,7 +4319,16 @@
 	size_t /*len*/,
 	Checksum */*cksum*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_checksum_iov (
+	krb5_context /*context*/,
+	krb5_crypto /*crypto*/,
+	unsigned /*usage*/,
+	krb5_crypto_iov */*data*/,
+	unsigned int /*num_data*/,
+	krb5_cksumtype */*type*/);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_init_creds (
 	krb5_context /*context*/,
 	krb5_creds */*creds*/,
@@ -3942,51 +4337,51 @@
 	krb5_ccache */*ccache*/,
 	krb5_verify_init_creds_opt */*options*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_init_creds_opt_init (krb5_verify_init_creds_opt */*options*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_init_creds_opt_set_ap_req_nofail (
 	krb5_verify_init_creds_opt */*options*/,
 	int /*ap_req_nofail*/);
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_verify_opt_alloc (
 	krb5_context /*context*/,
 	krb5_verify_opt **/*opt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_free (krb5_verify_opt */*opt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_init (krb5_verify_opt */*opt*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_ccache (
 	krb5_verify_opt */*opt*/,
 	krb5_ccache /*ccache*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_flags (
 	krb5_verify_opt */*opt*/,
 	unsigned int /*flags*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_keytab (
 	krb5_verify_opt */*opt*/,
 	krb5_keytab /*keytab*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_secure (
 	krb5_verify_opt */*opt*/,
 	krb5_boolean /*secure*/);
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_service (
 	krb5_verify_opt */*opt*/,
 	const char */*service*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_user (
 	krb5_context /*context*/,
 	krb5_principal /*principal*/,
@@ -3995,7 +4390,7 @@
 	krb5_boolean /*secure*/,
 	const char */*service*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_user_lrealm (
 	krb5_context /*context*/,
 	krb5_principal /*principal*/,
@@ -4004,40 +4399,40 @@
 	krb5_boolean /*secure*/,
 	const char */*service*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_user_opt (
 	krb5_context /*context*/,
 	krb5_principal /*principal*/,
 	const char */*password*/,
 	krb5_verify_opt */*opt*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verr (
 	krb5_context /*context*/,
 	int /*eval*/,
 	krb5_error_code /*code*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__ ((noreturn, format (printf, 4, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 4, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verrx (
 	krb5_context /*context*/,
 	int /*eval*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__ ((noreturn, format (printf, 3, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((noreturn, format (printf, 3, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vlog (
 	krb5_context /*context*/,
 	krb5_log_facility */*fac*/,
 	int /*level*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__((format (printf, 4, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__((format (printf, 4, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vlog_msg (
 	krb5_context /*context*/,
 	krb5_log_facility */*fac*/,
@@ -4045,70 +4440,88 @@
 	int /*level*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__((format (printf, 5, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_vset_error_string (
-	krb5_context /*context*/,
+     __attribute__((format (printf, 5, 0)));
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_vprepend_error_message (
+	krb5_context /*context*/,
+	krb5_error_code /*ret*/,
 	const char */*fmt*/,
 	va_list /*args*/)
-    __attribute__ ((format (printf, 2, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((format (printf, 3, 0)));
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_vset_error_message (
+	krb5_context /*context*/,
+	krb5_error_code /*ret*/,
+	const char */*fmt*/,
+	va_list /*args*/)
+     __attribute__ ((format (printf, 3, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vset_error_string (
+	krb5_context /*context*/,
+	const char */*fmt*/,
+	va_list /*args*/)
+     __attribute__ ((format (printf, 2, 0))) KRB5_DEPRECATED_FUNCTION("Use=
 X instead");
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vwarn (
 	krb5_context /*context*/,
 	krb5_error_code /*code*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__ ((format (printf, 3, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((format (printf, 3, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vwarnx (
 	krb5_context /*context*/,
 	const char */*fmt*/,
 	va_list /*ap*/)
-    __attribute__ ((format (printf, 2, 0)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((format (printf, 2, 0)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_warn (
 	krb5_context /*context*/,
 	krb5_error_code /*code*/,
 	const char */*fmt*/,
 	...)
-    __attribute__ ((format (printf, 3, 4)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((format (printf, 3, 4)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_warnx (
 	krb5_context /*context*/,
 	const char */*fmt*/,
 	...)
-    __attribute__ ((format (printf, 2, 3)));
-
-krb5_error_code KRB5_LIB_FUNCTION
+     __attribute__ ((format (printf, 2, 3)));
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_write_message (
 	krb5_context /*context*/,
 	krb5_pointer /*p_fd*/,
 	krb5_data */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_write_priv_message (
 	krb5_context /*context*/,
 	krb5_auth_context /*ac*/,
 	krb5_pointer /*p_fd*/,
 	krb5_data */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_write_safe_message (
 	krb5_context /*context*/,
 	krb5_auth_context /*ac*/,
 	krb5_pointer /*p_fd*/,
 	krb5_data */*data*/);
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_xfree (void */*ptr*/);
=20
 #ifdef __cplusplus
 }
 #endif
=20
+#undef KRB5_DEPRECATED_FUNCTION
+
 #endif /* __krb5_protos_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5-v4co=
mpat.h
--- a/head/crypto/heimdal/lib/krb5/krb5-v4compat.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5-v4compat.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,44 +1,44 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: krb5-v4compat.h 21575 2007-07-16 07:44:54Z lha $ */
+/* $Id$ */
=20
 #ifndef __KRB5_V4COMPAT_H__
 #define __KRB5_V4COMPAT_H__
=20
 #include "krb_err.h"
=20
-/*=20
+/*
  * This file must only be included with v4 compat glue stuff in
  * heimdal sources.
  *
@@ -105,8 +105,12 @@
 #define 	CLOCK_SKEW	5*60
=20
 #ifndef TKT_ROOT
+#ifdef KRB5_USE_PATH_TOKENS
+#define TKT_ROOT "%{TEMP}/tkt"
+#else
 #define TKT_ROOT "/tmp/tkt"
 #endif
+#endif
=20
 struct _krb5_krb_auth_data {
     int8_t  k_flags;		/* Flags from ticket */
@@ -120,11 +124,18 @@
     uint32_t address;		/* Address in ticket */
 };
=20
-time_t		_krb5_krb_life_to_time (int, int);
-int		_krb5_krb_time_to_life (time_t, time_t);
-krb5_error_code	_krb5_krb_tf_setup (krb5_context, struct credentials *,
-				    const char *, int);
-krb5_error_code	_krb5_krb_dest_tkt(krb5_context, const char *);
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
+_krb5_krb_life_to_time (int, int);
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+_krb5_krb_time_to_life (time_t, time_t);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_krb_tf_setup (krb5_context, struct credentials *,
+		    const char *, int);
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_krb_dest_tkt(krb5_context, const char *);
=20
 #define krb_time_to_life	_krb5_krb_time_to_life
 #define krb_life_to_time	_krb5_krb_life_to_time
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5.conf=
.5
--- a/head/crypto/heimdal/lib/krb5/krb5.conf.5	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/krb5.conf.5	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-.\" Copyright (c) 1999 - 2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 1999 - 2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5.conf.5 15514 2005-06-23 18:43:34Z lha $
+.\" $Id$
 .\"
 .Dd May  4, 2005
 .Dt KRB5.CONF 5
@@ -143,6 +143,9 @@
 .Dq local realm .
 The default is the result of
 .Fn krb5_get_host_realm "local hostname" .
+.It Li allow_weak_crypto =3D Va boolean
+is weaks crypto algorithms allowed to be used, among others, DES is
+considered weak.
 .It Li clockskew =3D Va time
 Maximum time differential (in seconds) allowed when comparing
 times.
@@ -160,17 +163,28 @@
 .It ...
 .It Li }
 .El
-This is deprecated, see the=20
+This is deprecated, see the
 .Li capaths
 section below.
+.It Li default_cc_type =3D Va cctype
+sets the default credentials type.
 .It Li default_cc_name =3D Va ccname
 the default credentials cache name.
+If you want to change the type only use
+.Li default_cc_type .
 The string can contain variables that are expanded on runtime.
 Only support variable now is
 .Li %{uid}
 that expands to the current user id.
 .It Li default_etypes =3D Va etypes ...
-A list of default encryption types to use.
+A list of default encryption types to use. (Default: all enctypes if
+allow_weak_crypto =3D TRUE, else all enctypes except single DES enctypes.)
+.It Li default_as_etypes =3D Va etypes ...
+A list of default encryption types to use in AS requests.  (Default: the
+value of default_etypes.)
+.It Li default_tgs_etypes =3D Va etypes ...
+A list of default encryption types to use in TGS requests.  (Default:
+the value of default_etypes.)
 .It Li default_etypes_des =3D Va etypes ...
 A list of default encryption types to use when requesting a DES credential.
 .It Li default_keytab_name =3D Va keytab
@@ -241,6 +255,11 @@
 Setting this flag to
 .Dv TRUE
 make it store the MIT way, this is default for Heimdal 0.7.
+.It Li check-rd-req-server
+If set to "ignore", the framework will ignore any the server input to
+.Xr krb5_rd_req 3,
+this is very useful when the GSS-API server input the
+wrong server name into the gss_accept_sec_context call.
 .El
 .It Li [domain_realm]
 This is a list of mappings from DNS domain to Kerberos realm.
@@ -326,7 +345,7 @@
 .Va server-realm .
 Secondly, it tells the KDC (and other servers) which realms are
 allowed in a multi-hop traversal from
-.Va client-realm=20
+.Va client-realm
 to
 .Va server-realm .
 Except for the client case, the order of the realms are not important.
@@ -351,7 +370,7 @@
 .Bl -tag -width "xxx" -offset indent
 .It Li dbname Li =3D Va DATABASENAME
 Use this database for this realm.
-See the info documetation how to configure diffrent database backends.
+See the info documetation how to configure different database backends.
 .It Li realm Li =3D Va REALM
 Specifies the realm that will be stored in this database.
 It realm isn't set, it will used as the default database, there can
@@ -393,6 +412,27 @@
 Should the kdc answer kdc-requests over http.
 .It Li enable-kaserver =3D Va BOOL
 If this kdc should emulate the AFS kaserver.
+.It Li tgt-use-strongest-session-key =3D Va BOOL
+If this is TRUE then the KDC will prefer the strongest key from the
+client's AS-REQ or TGS-REQ enctype list for the ticket session key that
+is supported by the KDC and the target principal when the target
+principal is a krbtgt principal.  Else it will prefer the first key from
+the client's AS-REQ enctype list that is also supported by the KDC and
+the target principal. Defaults to TRUE.
+.It Li svc-use-strongest-session-key =3D Va BOOL
+Like tgt-use-strongest-session-key, but applies to the session key
+enctype of tickets for services other than krbtgt principals. Defaults
+to TRUE.
+.It Li preauth-use-strongest-session-key =3D Va BOOL
+If TRUE then select the strongest possible enctype from the client's
+AS-REQ for PA-ETYPE-INFO2 (i.e., for password-based pre-authentication).
+Else pick the first supported enctype from the client's AS-REQ. Defaults
+to TRUE.
+.It Li use-strongest-server-key =3D Va BOOL
+If TRUE then the KDC picks, for the ticket encrypted part's key, the
+first supported enctype from the target service principal's hdb entry's
+current keyset. Else the KDC picks the first supported enctype from the
+target service principal's hdb entry's current keyset. Defaults to TRUE.
 .It Li check-ticket-addresses =3D Va BOOL
 Verify the addresses in the tickets used in tgs requests.
 .\" XXX
@@ -425,6 +465,11 @@
 .It Li hdb-ldap-create-base Va creation dn
 is the dn that will be appended to the principal when creating entries.
 Default value is the search dn.
+.It Li enable-digest =3D Va BOOL
+Should the kdc answer digest requests. The default is FALSE.
+.It Li digests_allowed =3D Va list of digests
+Specifies the digests the kdc will reply to. The default is
+.Li ntlm-v2 .
 .El
 .It Li [kadmin]
 .Bl -tag -width "xxx" -offset indent
@@ -462,7 +507,7 @@
 .Pp
 and is only left for backwards compatibility.
 .El
-.It Li [password-quality]
+.It Li [password_quality]
 Check the Password quality assurance in the info documentation for
 more information.
 .Bl -tag -width "xxx" -offset indent
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5.h
--- a/head/crypto/heimdal/lib/krb5/krb5.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,39 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: krb5.h 22100 2007-12-03 17:15:00Z lha $ */
+/* $Id$ */
=20
 #ifndef __KRB5_H__
 #define __KRB5_H__
@@ -51,6 +53,12 @@
 #define KRB5KDC_ERR_KEY_EXP KRB5KDC_ERR_KEY_EXPIRED
 #endif
=20
+#ifdef _WIN32
+#define KRB5_CALLCONV __stdcall
+#else
+#define KRB5_CALLCONV
+#endif
+
 /* simple constants */
=20
 #ifndef TRUE
@@ -62,7 +70,7 @@
=20
 typedef int32_t krb5_error_code;
=20
-typedef int krb5_kvno;
+typedef int32_t krb5_kvno;
=20
 typedef uint32_t krb5_flags;
=20
@@ -92,6 +100,8 @@
=20
 typedef ENCTYPE krb5_enctype;
=20
+typedef struct krb5_get_init_creds_ctx *krb5_init_creds_context;
+
 typedef heim_octet_string krb5_data;
=20
 /* PKINIT related forward declarations */
@@ -108,28 +118,69 @@
=20
 /* alternative names */
 enum {
-    ENCTYPE_NULL		=3D ETYPE_NULL,
-    ENCTYPE_DES_CBC_CRC		=3D ETYPE_DES_CBC_CRC,
-    ENCTYPE_DES_CBC_MD4		=3D ETYPE_DES_CBC_MD4,
-    ENCTYPE_DES_CBC_MD5		=3D ETYPE_DES_CBC_MD5,
-    ENCTYPE_DES3_CBC_MD5	=3D ETYPE_DES3_CBC_MD5,
-    ENCTYPE_OLD_DES3_CBC_SHA1	=3D ETYPE_OLD_DES3_CBC_SHA1,
-    ENCTYPE_SIGN_DSA_GENERATE	=3D ETYPE_SIGN_DSA_GENERATE,
-    ENCTYPE_ENCRYPT_RSA_PRIV	=3D ETYPE_ENCRYPT_RSA_PRIV,
-    ENCTYPE_ENCRYPT_RSA_PUB	=3D ETYPE_ENCRYPT_RSA_PUB,
-    ENCTYPE_DES3_CBC_SHA1	=3D ETYPE_DES3_CBC_SHA1,
-    ENCTYPE_AES128_CTS_HMAC_SHA1_96 =3D ETYPE_AES128_CTS_HMAC_SHA1_96,
-    ENCTYPE_AES256_CTS_HMAC_SHA1_96 =3D ETYPE_AES256_CTS_HMAC_SHA1_96,
-    ENCTYPE_ARCFOUR_HMAC	=3D ETYPE_ARCFOUR_HMAC_MD5,
-    ENCTYPE_ARCFOUR_HMAC_MD5	=3D ETYPE_ARCFOUR_HMAC_MD5,
-    ENCTYPE_ARCFOUR_HMAC_MD5_56	=3D ETYPE_ARCFOUR_HMAC_MD5_56,
-    ENCTYPE_ENCTYPE_PK_CROSS	=3D ETYPE_ENCTYPE_PK_CROSS,
-    ENCTYPE_DES_CBC_NONE	=3D ETYPE_DES_CBC_NONE,
-    ENCTYPE_DES3_CBC_NONE	=3D ETYPE_DES3_CBC_NONE,
-    ENCTYPE_DES_CFB64_NONE	=3D ETYPE_DES_CFB64_NONE,
-    ENCTYPE_DES_PCBC_NONE	=3D ETYPE_DES_PCBC_NONE
+    ENCTYPE_NULL		=3D KRB5_ENCTYPE_NULL,
+    ENCTYPE_DES_CBC_CRC		=3D KRB5_ENCTYPE_DES_CBC_CRC,
+    ENCTYPE_DES_CBC_MD4		=3D KRB5_ENCTYPE_DES_CBC_MD4,
+    ENCTYPE_DES_CBC_MD5		=3D KRB5_ENCTYPE_DES_CBC_MD5,
+    ENCTYPE_DES3_CBC_MD5	=3D KRB5_ENCTYPE_DES3_CBC_MD5,
+    ENCTYPE_OLD_DES3_CBC_SHA1	=3D KRB5_ENCTYPE_OLD_DES3_CBC_SHA1,
+    ENCTYPE_SIGN_DSA_GENERATE	=3D KRB5_ENCTYPE_SIGN_DSA_GENERATE,
+    ENCTYPE_ENCRYPT_RSA_PRIV	=3D KRB5_ENCTYPE_ENCRYPT_RSA_PRIV,
+    ENCTYPE_ENCRYPT_RSA_PUB	=3D KRB5_ENCTYPE_ENCRYPT_RSA_PUB,
+    ENCTYPE_DES3_CBC_SHA1	=3D KRB5_ENCTYPE_DES3_CBC_SHA1,
+    ENCTYPE_AES128_CTS_HMAC_SHA1_96 =3D KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_=
96,
+    ENCTYPE_AES256_CTS_HMAC_SHA1_96 =3D KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_=
96,
+    ENCTYPE_ARCFOUR_HMAC	=3D KRB5_ENCTYPE_ARCFOUR_HMAC_MD5,
+    ENCTYPE_ARCFOUR_HMAC_MD5	=3D KRB5_ENCTYPE_ARCFOUR_HMAC_MD5,
+    ENCTYPE_ARCFOUR_HMAC_MD5_56	=3D KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56,
+    ENCTYPE_ENCTYPE_PK_CROSS	=3D KRB5_ENCTYPE_ENCTYPE_PK_CROSS,
+    ENCTYPE_DES_CBC_NONE	=3D KRB5_ENCTYPE_DES_CBC_NONE,
+    ENCTYPE_DES3_CBC_NONE	=3D KRB5_ENCTYPE_DES3_CBC_NONE,
+    ENCTYPE_DES_CFB64_NONE	=3D KRB5_ENCTYPE_DES_CFB64_NONE,
+    ENCTYPE_DES_PCBC_NONE	=3D KRB5_ENCTYPE_DES_PCBC_NONE,
+    ETYPE_NULL			=3D KRB5_ENCTYPE_NULL,
+    ETYPE_DES_CBC_CRC		=3D KRB5_ENCTYPE_DES_CBC_CRC,
+    ETYPE_DES_CBC_MD4		=3D KRB5_ENCTYPE_DES_CBC_MD4,
+    ETYPE_DES_CBC_MD5		=3D KRB5_ENCTYPE_DES_CBC_MD5,
+    ETYPE_DES3_CBC_MD5		=3D KRB5_ENCTYPE_DES3_CBC_MD5,
+    ETYPE_OLD_DES3_CBC_SHA1	=3D KRB5_ENCTYPE_OLD_DES3_CBC_SHA1,
+    ETYPE_SIGN_DSA_GENERATE	=3D KRB5_ENCTYPE_SIGN_DSA_GENERATE,
+    ETYPE_ENCRYPT_RSA_PRIV	=3D KRB5_ENCTYPE_ENCRYPT_RSA_PRIV,
+    ETYPE_ENCRYPT_RSA_PUB	=3D KRB5_ENCTYPE_ENCRYPT_RSA_PUB,
+    ETYPE_DES3_CBC_SHA1		=3D KRB5_ENCTYPE_DES3_CBC_SHA1,
+    ETYPE_AES128_CTS_HMAC_SHA1_96	=3D KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96,
+    ETYPE_AES256_CTS_HMAC_SHA1_96	=3D KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96,
+    ETYPE_ARCFOUR_HMAC_MD5	=3D KRB5_ENCTYPE_ARCFOUR_HMAC_MD5,
+    ETYPE_ARCFOUR_HMAC_MD5_56	=3D KRB5_ENCTYPE_ARCFOUR_HMAC_MD5_56,
+    ETYPE_ENCTYPE_PK_CROSS	=3D KRB5_ENCTYPE_ENCTYPE_PK_CROSS,
+    ETYPE_ARCFOUR_MD4		=3D KRB5_ENCTYPE_ARCFOUR_MD4,
+    ETYPE_ARCFOUR_HMAC_OLD	=3D KRB5_ENCTYPE_ARCFOUR_HMAC_OLD,
+    ETYPE_ARCFOUR_HMAC_OLD_EXP	=3D KRB5_ENCTYPE_ARCFOUR_HMAC_OLD_EXP,
+    ETYPE_DES_CBC_NONE		=3D KRB5_ENCTYPE_DES_CBC_NONE,
+    ETYPE_DES3_CBC_NONE		=3D KRB5_ENCTYPE_DES3_CBC_NONE,
+    ETYPE_DES_CFB64_NONE	=3D KRB5_ENCTYPE_DES_CFB64_NONE,
+    ETYPE_DES_PCBC_NONE		=3D KRB5_ENCTYPE_DES_PCBC_NONE,
+    ETYPE_DIGEST_MD5_NONE	=3D KRB5_ENCTYPE_DIGEST_MD5_NONE,
+    ETYPE_CRAM_MD5_NONE		=3D KRB5_ENCTYPE_CRAM_MD5_NONE
+
 };
=20
+/* PDU types */
+typedef enum krb5_pdu {
+    KRB5_PDU_ERROR =3D 0,
+    KRB5_PDU_TICKET =3D 1,
+    KRB5_PDU_AS_REQUEST =3D 2,
+    KRB5_PDU_AS_REPLY =3D 3,
+    KRB5_PDU_TGS_REQUEST =3D 4,
+    KRB5_PDU_TGS_REPLY =3D 5,
+    KRB5_PDU_AP_REQUEST =3D 6,
+    KRB5_PDU_AP_REPLY =3D 7,
+    KRB5_PDU_KRB_SAFE =3D 8,
+    KRB5_PDU_KRB_PRIV =3D 9,
+    KRB5_PDU_KRB_CRED =3D 10,
+    KRB5_PDU_NONE =3D 11 /* See krb5_get_permitted_enctypes() */
+} krb5_pdu;
+
 typedef PADATA_TYPE krb5_preauthtype;
=20
 typedef enum krb5_key_usage {
@@ -205,7 +256,7 @@
     /* acceptor sign in GSSAPI CFX krb5 mechanism */
     KRB5_KU_USAGE_ACCEPTOR_SIGN =3D 23,
     /* acceptor seal in GSSAPI CFX krb5 mechanism */
-    KRB5_KU_USAGE_INITIATOR_SEAL =3D 24,      =20
+    KRB5_KU_USAGE_INITIATOR_SEAL =3D 24,
     /* initiator sign in GSSAPI CFX krb5 mechanism */
     KRB5_KU_USAGE_INITIATOR_SIGN =3D 25,
     /* initiator seal in GSSAPI CFX krb5 mechanism */
@@ -219,6 +270,10 @@
     /* Keyusage for the server referral in a TGS req */
     KRB5_KU_SAM_ENC_NONCE_SAD =3D 27,
     /* Encryption of the SAM-NONCE-OR-SAD field */
+    KRB5_KU_PA_PKINIT_KX =3D 44,
+    /* Encryption type of the kdc session contribution in pk-init */
+    KRB5_KU_AS_REQ =3D 56,
+    /* Checksum of over the AS-REQ send by the KDC in PA-REQ-ENC-PA-REP */
     KRB5_KU_DIGEST_ENCRYPT =3D -18,
     /* Encryption key usage used in the digest encryption field */
     KRB5_KU_DIGEST_OPAQUE =3D -19,
@@ -253,7 +308,7 @@
     krb5_preauthdata_entry *val;
 }krb5_preauthdata;
=20
-typedef enum krb5_address_type {=20
+typedef enum krb5_address_type {
     KRB5_ADDRESS_INET     =3D   2,
     KRB5_ADDRESS_NETBIOS  =3D  20,
     KRB5_ADDRESS_INET6    =3D  24,
@@ -271,15 +326,17 @@
=20
 typedef HostAddresses krb5_addresses;
=20
-typedef enum krb5_keytype {=20
-    KEYTYPE_NULL	=3D 0,
-    KEYTYPE_DES		=3D 1,
-    KEYTYPE_DES3	=3D 7,
-    KEYTYPE_AES128	=3D 17,
-    KEYTYPE_AES256	=3D 18,
-    KEYTYPE_ARCFOUR	=3D 23,
-    KEYTYPE_ARCFOUR_56	=3D 24
-} krb5_keytype;
+typedef krb5_enctype krb5_keytype;
+
+enum krb5_keytype_old {
+    KEYTYPE_NULL	=3D ETYPE_NULL,
+    KEYTYPE_DES		=3D ETYPE_DES_CBC_CRC,
+    KEYTYPE_DES3	=3D ETYPE_OLD_DES3_CBC_SHA1,
+    KEYTYPE_AES128	=3D ETYPE_AES128_CTS_HMAC_SHA1_96,
+    KEYTYPE_AES256	=3D ETYPE_AES256_CTS_HMAC_SHA1_96,
+    KEYTYPE_ARCFOUR	=3D ETYPE_ARCFOUR_HMAC_MD5,
+    KEYTYPE_ARCFOUR_56	=3D ETYPE_ARCFOUR_HMAC_MD5_56
+};
=20
 typedef EncryptionKey krb5_keyblock;
=20
@@ -287,7 +344,15 @@
=20
 struct krb5_cc_ops;
=20
+#ifdef _WIN32
+#define KRB5_USE_PATH_TOKENS 1
+#endif
+
+#ifdef KRB5_USE_PATH_TOKENS
+#define KRB5_DEFAULT_CCFILE_ROOT "%{TEMP}/krb5cc_"
+#else
 #define KRB5_DEFAULT_CCFILE_ROOT "/tmp/krb5cc_"
+#endif
=20
 #define KRB5_DEFAULT_CCROOT "FILE:" KRB5_DEFAULT_CCFILE_ROOT
=20
@@ -297,6 +362,7 @@
 				 NULL)
=20
 typedef void *krb5_cc_cursor;
+typedef struct krb5_cccol_cursor_data *krb5_cccol_cursor;
=20
 typedef struct krb5_ccache_data {
     const struct krb5_cc_ops *ops;
@@ -316,6 +382,7 @@
 typedef Principal krb5_principal_data;
 typedef struct Principal *krb5_principal;
 typedef const struct Principal *krb5_const_principal;
+typedef struct Principals *krb5_principals;
=20
 typedef time_t krb5_deltat;
 typedef time_t krb5_timestamp;
@@ -363,6 +430,7 @@
 #define KRB5_GC_FORWARDABLE		(1U << 4)
 #define KRB5_GC_NO_TRANSIT_CHECK	(1U << 5)
 #define KRB5_GC_CONSTRAINED_DELEGATION	(1U << 6)
+#define KRB5_GC_CANONICALIZE		(1U << 7)
=20
 /* constants for compare_creds (and cc_retrieve_cred) */
 #define KRB5_TC_DONT_MATCH_REALM	(1U << 31)
@@ -377,6 +445,10 @@
 #define KRB5_TC_MATCH_2ND_TKT		(1 << 23)
 #define KRB5_TC_MATCH_IS_SKEY		(1 << 22)
=20
+/* constants for get_flags and set_flags */
+#define KRB5_TC_OPENCLOSE 0x00000001
+#define KRB5_TC_NOTICKET  0x00000002
+
 typedef AuthorizationData krb5_authdata;
=20
 typedef KRB_ERROR krb5_error;
@@ -395,31 +467,39 @@
=20
 typedef struct krb5_cc_cache_cursor_data *krb5_cc_cache_cursor;
=20
+#define KRB5_CC_OPS_VERSION 3
+
 typedef struct krb5_cc_ops {
+    int version;
     const char *prefix;
-    const char* (*get_name)(krb5_context, krb5_ccache);
-    krb5_error_code (*resolve)(krb5_context, krb5_ccache *, const char *);
-    krb5_error_code (*gen_new)(krb5_context, krb5_ccache *);
-    krb5_error_code (*init)(krb5_context, krb5_ccache, krb5_principal);
-    krb5_error_code (*destroy)(krb5_context, krb5_ccache);
-    krb5_error_code (*close)(krb5_context, krb5_ccache);
-    krb5_error_code (*store)(krb5_context, krb5_ccache, krb5_creds*);
-    krb5_error_code (*retrieve)(krb5_context, krb5_ccache,=20
-				krb5_flags, const krb5_creds*, krb5_creds *);
-    krb5_error_code (*get_princ)(krb5_context, krb5_ccache, krb5_principal=
*);
-    krb5_error_code (*get_first)(krb5_context, krb5_ccache, krb5_cc_cursor=
 *);
-    krb5_error_code (*get_next)(krb5_context, krb5_ccache,=20
-				krb5_cc_cursor*, krb5_creds*);
-    krb5_error_code (*end_get)(krb5_context, krb5_ccache, krb5_cc_cursor*);
-    krb5_error_code (*remove_cred)(krb5_context, krb5_ccache,=20
-				   krb5_flags, krb5_creds*);
-    krb5_error_code (*set_flags)(krb5_context, krb5_ccache, krb5_flags);
-    int (*get_version)(krb5_context, krb5_ccache);
-    krb5_error_code (*get_cache_first)(krb5_context, krb5_cc_cursor *);
-    krb5_error_code (*get_cache_next)(krb5_context, krb5_cc_cursor, krb5_c=
cache *);
-    krb5_error_code (*end_cache_get)(krb5_context, krb5_cc_cursor);
-    krb5_error_code (*move)(krb5_context, krb5_ccache, krb5_ccache);
-    krb5_error_code (*default_name)(krb5_context, char **);
+    const char* (KRB5_CALLCONV * get_name)(krb5_context, krb5_ccache);
+    krb5_error_code (KRB5_CALLCONV * resolve)(krb5_context, krb5_ccache *,=
 const char *);
+    krb5_error_code (KRB5_CALLCONV * gen_new)(krb5_context, krb5_ccache *);
+    krb5_error_code (KRB5_CALLCONV * init)(krb5_context, krb5_ccache, krb5=
_principal);
+    krb5_error_code (KRB5_CALLCONV * destroy)(krb5_context, krb5_ccache);
+    krb5_error_code (KRB5_CALLCONV * close)(krb5_context, krb5_ccache);
+    krb5_error_code (KRB5_CALLCONV * store)(krb5_context, krb5_ccache, krb=
5_creds*);
+    krb5_error_code (KRB5_CALLCONV * retrieve)(krb5_context, krb5_ccache,
+					       krb5_flags, const krb5_creds*, krb5_creds *);
+    krb5_error_code (KRB5_CALLCONV * get_princ)(krb5_context, krb5_ccache,=
 krb5_principal*);
+    krb5_error_code (KRB5_CALLCONV * get_first)(krb5_context, krb5_ccache,=
 krb5_cc_cursor *);
+    krb5_error_code (KRB5_CALLCONV * get_next)(krb5_context, krb5_ccache,
+					       krb5_cc_cursor*, krb5_creds*);
+    krb5_error_code (KRB5_CALLCONV * end_get)(krb5_context, krb5_ccache, k=
rb5_cc_cursor*);
+    krb5_error_code (KRB5_CALLCONV * remove_cred)(krb5_context, krb5_ccach=
e,
+						  krb5_flags, krb5_creds*);
+    krb5_error_code (KRB5_CALLCONV * set_flags)(krb5_context, krb5_ccache,=
 krb5_flags);
+    int (KRB5_CALLCONV * get_version)(krb5_context, krb5_ccache);
+    krb5_error_code (KRB5_CALLCONV * get_cache_first)(krb5_context, krb5_c=
c_cursor *);
+    krb5_error_code (KRB5_CALLCONV * get_cache_next)(krb5_context, krb5_cc=
_cursor,
+						     krb5_ccache *);
+    krb5_error_code (KRB5_CALLCONV * end_cache_get)(krb5_context, krb5_cc_=
cursor);
+    krb5_error_code (KRB5_CALLCONV * move)(krb5_context, krb5_ccache, krb5=
_ccache);
+    krb5_error_code (KRB5_CALLCONV * get_default_name)(krb5_context, char =
**);
+    krb5_error_code (KRB5_CALLCONV * set_default)(krb5_context, krb5_ccach=
e);
+    krb5_error_code (KRB5_CALLCONV * lastchange)(krb5_context, krb5_ccache=
, krb5_timestamp *);
+    krb5_error_code (KRB5_CALLCONV * set_kdc_offset)(krb5_context, krb5_cc=
ache, krb5_deltat);
+    krb5_error_code (KRB5_CALLCONV * get_kdc_offset)(krb5_context, krb5_cc=
ache, krb5_deltat *);
 } krb5_cc_ops;
=20
 struct krb5_log_facility;
@@ -471,6 +551,8 @@
     krb5_kvno vno;
     krb5_keyblock keyblock;
     uint32_t timestamp;
+    uint32_t flags;
+    krb5_principals aliases;
 } krb5_keytab_entry;
=20
 typedef struct krb5_kt_cursor {
@@ -487,17 +569,18 @@
=20
 struct krb5_keytab_data {
     const char *prefix;
-    krb5_error_code (*resolve)(krb5_context, const char*, krb5_keytab);
-    krb5_error_code (*get_name)(krb5_context, krb5_keytab, char*, size_t);
-    krb5_error_code (*close)(krb5_context, krb5_keytab);
-    krb5_error_code (*get)(krb5_context, krb5_keytab, krb5_const_principal=
,=20
-			   krb5_kvno, krb5_enctype, krb5_keytab_entry*);
-    krb5_error_code (*start_seq_get)(krb5_context, krb5_keytab, krb5_kt_cu=
rsor*);
-    krb5_error_code (*next_entry)(krb5_context, krb5_keytab,=20
-				  krb5_keytab_entry*, krb5_kt_cursor*);
-    krb5_error_code (*end_seq_get)(krb5_context, krb5_keytab, krb5_kt_curs=
or*);
-    krb5_error_code (*add)(krb5_context, krb5_keytab, krb5_keytab_entry*);
-    krb5_error_code (*remove)(krb5_context, krb5_keytab, krb5_keytab_entry=
*);
+    krb5_error_code (KRB5_CALLCONV * resolve)(krb5_context, const char*, k=
rb5_keytab);
+    krb5_error_code (KRB5_CALLCONV * get_name)(krb5_context, krb5_keytab, =
char*, size_t);
+    krb5_error_code (KRB5_CALLCONV * close)(krb5_context, krb5_keytab);
+    krb5_error_code (KRB5_CALLCONV * destroy)(krb5_context, krb5_keytab);
+    krb5_error_code (KRB5_CALLCONV * get)(krb5_context, krb5_keytab, krb5_=
const_principal,
+					  krb5_kvno, krb5_enctype, krb5_keytab_entry*);
+    krb5_error_code (KRB5_CALLCONV * start_seq_get)(krb5_context, krb5_key=
tab, krb5_kt_cursor*);
+    krb5_error_code (KRB5_CALLCONV * next_entry)(krb5_context, krb5_keytab,
+						 krb5_keytab_entry*, krb5_kt_cursor*);
+    krb5_error_code (KRB5_CALLCONV * end_seq_get)(krb5_context, krb5_keyta=
b, krb5_kt_cursor*);
+    krb5_error_code (KRB5_CALLCONV * add)(krb5_context, krb5_keytab, krb5_=
keytab_entry*);
+    krb5_error_code (KRB5_CALLCONV * remove)(krb5_context, krb5_keytab, kr=
b5_keytab_entry*);
     void *data;
     int32_t version;
 };
@@ -551,14 +634,14 @@
     uint32_t remote_seqnumber;
=20
     krb5_authenticator authenticator;
- =20
+
     krb5_pointer i_vector;
- =20
+
     krb5_rcache rcache;
=20
-    krb5_keytype keytype;	/* =BFrequested key type ? */
-    krb5_cksumtype cksumtype;	/* =A1requested checksum type! */
- =20
+    krb5_keytype keytype;	/* =C2=BFrequested key type ? */
+    krb5_cksumtype cksumtype;	/* =C2=A1requested checksum type! */
+
 }krb5_auth_context_data, *krb5_auth_context;
=20
 typedef struct {
@@ -569,8 +652,8 @@
=20
 extern const char *heimdal_version, *heimdal_long_version;
=20
-typedef void (*krb5_log_log_func_t)(const char*, const char*, void*);
-typedef void (*krb5_log_close_func_t)(void*);
+typedef void (KRB5_CALLCONV * krb5_log_log_func_t)(const char*, const char=
*, void*);
+typedef void (KRB5_CALLCONV * krb5_log_close_func_t)(void*);
=20
 typedef struct krb5_log_facility {
     char *program;
@@ -586,14 +669,10 @@
=20
 #define KRB5_TGS_NAME_SIZE (6)
 #define KRB5_TGS_NAME ("krbtgt")
-
+#define KRB5_WELLKNOWN_NAME ("WELLKNOWN")
+#define KRB5_ANON_NAME ("ANONYMOUS")
 #define KRB5_DIGEST_NAME ("digest")
=20
-/* variables */
-
-extern const char *krb5_config_file;
-extern const char *krb5_defkeyname;
-
 typedef enum {
     KRB5_PROMPT_TYPE_PASSWORD		=3D 0x1,
     KRB5_PROMPT_TYPE_NEW_PASSWORD	=3D 0x2,
@@ -609,32 +688,32 @@
     krb5_prompt_type type;
 } krb5_prompt;
=20
-typedef int (*krb5_prompter_fct)(krb5_context /*context*/,
-				 void * /*data*/,
-				 const char * /*name*/,
-				 const char * /*banner*/,
-				 int /*num_prompts*/,
-				 krb5_prompt /*prompts*/[]);
-typedef krb5_error_code (*krb5_key_proc)(krb5_context /*context*/,
-					 krb5_enctype /*type*/,
-					 krb5_salt /*salt*/,
-					 krb5_const_pointer /*keyseed*/,
-					 krb5_keyblock ** /*key*/);
-typedef krb5_error_code (*krb5_decrypt_proc)(krb5_context /*context*/,
-					     krb5_keyblock * /*key*/,
-					     krb5_key_usage /*usage*/,
-					     krb5_const_pointer /*decrypt_arg*/,
-					     krb5_kdc_rep * /*dec_rep*/);
-typedef krb5_error_code (*krb5_s2k_proc)(krb5_context /*context*/,
-					 krb5_enctype /*type*/,
-					 krb5_const_pointer /*keyseed*/,
-					 krb5_salt /*salt*/,
-					 krb5_data * /*s2kparms*/,
-					 krb5_keyblock ** /*key*/);
+typedef int (KRB5_CALLCONV * krb5_prompter_fct)(krb5_context /*context*/,
+						void * /*data*/,
+						const char * /*name*/,
+						const char * /*banner*/,
+						int /*num_prompts*/,
+						krb5_prompt /*prompts*/[]);
+typedef krb5_error_code (KRB5_CALLCONV * krb5_key_proc)(krb5_context /*con=
text*/,
+							krb5_enctype /*type*/,
+							krb5_salt /*salt*/,
+							krb5_const_pointer /*keyseed*/,
+							krb5_keyblock ** /*key*/);
+typedef krb5_error_code (KRB5_CALLCONV * krb5_decrypt_proc)(krb5_context /=
*context*/,
+							    krb5_keyblock * /*key*/,
+							    krb5_key_usage /*usage*/,
+							    krb5_const_pointer /*decrypt_arg*/,
+							    krb5_kdc_rep * /*dec_rep*/);
+typedef krb5_error_code (KRB5_CALLCONV * krb5_s2k_proc)(krb5_context /*con=
text*/,
+							krb5_enctype /*type*/,
+							krb5_const_pointer /*keyseed*/,
+							krb5_salt /*salt*/,
+							krb5_data * /*s2kparms*/,
+							krb5_keyblock ** /*key*/);
=20
 struct _krb5_get_init_creds_opt_private;
=20
-typedef struct _krb5_get_init_creds_opt {
+struct _krb5_get_init_creds_opt {
     krb5_flags flags;
     krb5_deltat tkt_life;
     krb5_deltat renew_life;
@@ -650,7 +729,9 @@
     int preauth_list_length;
     krb5_data *salt;
     struct _krb5_get_init_creds_opt_private *opt_private;
-} krb5_get_init_creds_opt;
+};
+
+typedef struct _krb5_get_init_creds_opt krb5_get_init_creds_opt;
=20
 #define KRB5_GET_INIT_CREDS_OPT_TKT_LIFE	0x0001
 #define KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE	0x0002
@@ -659,10 +740,13 @@
 #define KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST	0x0010
 #define KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST	0x0020
 #define KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST	0x0040
-#define KRB5_GET_INIT_CREDS_OPT_SALT		0x0080
+#define KRB5_GET_INIT_CREDS_OPT_SALT		0x0080 /* no supported */
 #define KRB5_GET_INIT_CREDS_OPT_ANONYMOUS	0x0100
 #define KRB5_GET_INIT_CREDS_OPT_DISABLE_TRANSITED_CHECK	0x0200
=20
+/* krb5_init_creds_step flags argument */
+#define KRB5_INIT_CREDS_STEP_FLAG_CONTINUE	0x0001
+
 typedef struct _krb5_verify_init_creds_opt {
     krb5_flags flags;
     int ap_req_nofail;
@@ -681,20 +765,6 @@
 #define KRB5_VERIFY_LREALMS		1
 #define KRB5_VERIFY_NO_ADDRESSES	2
=20
-extern const krb5_cc_ops krb5_acc_ops;
-extern const krb5_cc_ops krb5_fcc_ops;
-extern const krb5_cc_ops krb5_mcc_ops;
-extern const krb5_cc_ops krb5_kcm_ops;
-
-extern const krb5_kt_ops krb5_fkt_ops;
-extern const krb5_kt_ops krb5_wrfkt_ops;
-extern const krb5_kt_ops krb5_javakt_ops;
-extern const krb5_kt_ops krb5_mkt_ops;
-extern const krb5_kt_ops krb5_akf_ops;
-extern const krb5_kt_ops krb4_fkt_ops;
-extern const krb5_kt_ops krb5_srvtab_fkt_ops;
-extern const krb5_kt_ops krb5_any_ops;
-
 #define KRB5_KPASSWD_VERS_CHANGEPW      1
 #define KRB5_KPASSWD_VERS_SETPW         0xff80
=20
@@ -736,24 +806,22 @@
     KRB5_KRBHST_FLAGS_LARGE_MSG	  =3D 2
 };
=20
-typedef krb5_error_code (*krb5_send_to_kdc_func)(krb5_context,=20
-						 void *,=20
-						 krb5_krbhst_info *,
-						 const krb5_data *,
-						 krb5_data *);
+typedef krb5_error_code
+(KRB5_CALLCONV * krb5_send_to_kdc_func)(krb5_context, void *, krb5_krbhst_=
info *, time_t,
+					const krb5_data *, krb5_data *);
=20
-/* flags for krb5_parse_name_flags */
+/** flags for krb5_parse_name_flags */
 enum {
-    KRB5_PRINCIPAL_PARSE_NO_REALM =3D 1,
-    KRB5_PRINCIPAL_PARSE_MUST_REALM =3D 2,
-    KRB5_PRINCIPAL_PARSE_ENTERPRISE =3D 4
+    KRB5_PRINCIPAL_PARSE_NO_REALM =3D 1, /**< Require that there are no re=
alm */
+    KRB5_PRINCIPAL_PARSE_REQUIRE_REALM =3D 2, /**< Require a realm present=
 */
+    KRB5_PRINCIPAL_PARSE_ENTERPRISE =3D 4 /**< Parse as a NT-ENTERPRISE na=
me */
 };
=20
-/* flags for krb5_unparse_name_flags */
+/** flags for krb5_unparse_name_flags */
 enum {
-    KRB5_PRINCIPAL_UNPARSE_SHORT =3D 1,
-    KRB5_PRINCIPAL_UNPARSE_NO_REALM =3D 2,
-    KRB5_PRINCIPAL_UNPARSE_DISPLAY =3D 4
+    KRB5_PRINCIPAL_UNPARSE_SHORT =3D 1, /**< No realm if it is the default=
 realm */
+    KRB5_PRINCIPAL_UNPARSE_NO_REALM =3D 2, /**< No realm */
+    KRB5_PRINCIPAL_UNPARSE_DISPLAY =3D 4 /**< No quoting */
 };
=20
 typedef struct krb5_sendto_ctx_data *krb5_sendto_ctx;
@@ -762,7 +830,9 @@
 #define KRB5_SENDTO_RESTART	1
 #define KRB5_SENDTO_CONTINUE	2
=20
-typedef krb5_error_code (*krb5_sendto_ctx_func)(krb5_context, krb5_sendto_=
ctx, void *, const krb5_data *, int *);
+typedef krb5_error_code
+(KRB5_CALLCONV * krb5_sendto_ctx_func)(krb5_context, krb5_sendto_ctx, void=
 *,
+				       const krb5_data *, int *);
=20
 struct krb5_plugin;
 enum krb5_plugin_type {
@@ -774,7 +844,73 @@
 struct getargs;
 struct sockaddr;
=20
+/**
+ * Semi private, not stable yet
+ */
+
+typedef struct krb5_crypto_iov {
+    unsigned int flags;
+    /* ignored */
+#define KRB5_CRYPTO_TYPE_EMPTY		0
+    /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_HEADER) */
+#define KRB5_CRYPTO_TYPE_HEADER		1
+    /* IN and OUT */
+#define KRB5_CRYPTO_TYPE_DATA		2
+    /* IN */
+#define KRB5_CRYPTO_TYPE_SIGN_ONLY	3
+   /* (only for encryption) OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_TRAILE=
R) */
+#define KRB5_CRYPTO_TYPE_PADDING	4
+   /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_TRAILER) */
+#define KRB5_CRYPTO_TYPE_TRAILER	5
+   /* OUT krb5_crypto_length(KRB5_CRYPTO_TYPE_CHECKSUM) */
+#define KRB5_CRYPTO_TYPE_CHECKSUM	6
+    krb5_data data;
+} krb5_crypto_iov;
+
+
+/* Glue for MIT */
+
+typedef struct {
+    int32_t lr_type;
+    krb5_timestamp value;
+} krb5_last_req_entry;
+
+typedef krb5_error_code
+(KRB5_CALLCONV * krb5_gic_process_last_req)(krb5_context, krb5_last_req_en=
try **, void *);
+
+/*
+ *
+ */
+
+struct hx509_certs_data;
+
 #include <krb5-protos.h>
=20
+/* variables */
+
+extern KRB5_LIB_VARIABLE const char *krb5_config_file;
+extern KRB5_LIB_VARIABLE const char *krb5_defkeyname;
+
+
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_acc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_fcc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_mcc_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_kcm_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_akcm_ops;
+extern KRB5_LIB_VARIABLE const krb5_cc_ops krb5_scc_ops;
+
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_fkt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_wrfkt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_javakt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_mkt_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_akf_ops;
+extern KRB5_LIB_VARIABLE const krb5_kt_ops krb5_any_ops;
+
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_api;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_file;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_memory;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_kcm;
+extern KRB5_LIB_VARIABLE const char *krb5_cc_type_scc;
+
 #endif /* __KRB5_H__ */
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5.modu=
li
--- a/head/crypto/heimdal/lib/krb5/krb5.moduli	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/krb5.moduli	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,3 +1,3 @@
-# $Id: krb5.moduli 16154 2005-10-08 15:39:42Z lha $
+# $Id$
 # comment security-bits-decimal secure-prime(p)-hex generator(g)-hex (q)-h=
ex
 rfc3526-MODP-group14 1760 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1=
29024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25=
F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386B=
FB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A6=
9163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC=
9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF=
06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FF=
FFFFFFFFFFFFFF 02 7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044=
533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F0=
9AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD=
2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E=
9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA3=
604650C10BE19482F23171B671DF1CF3B960C074301CD93C1D17603D147DAE2AEF837A62964=
EF15E5FB4AAC0B8C1CCAA4BE754AB5728AE9130C4C7D02880AB9472D455655347FFFFFFFFFF=
FFFFF
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb524_co=
nvert_creds_kdc.3
--- a/head/crypto/heimdal/lib/krb5/krb524_convert_creds_kdc.3	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb524_convert_creds_kdc.3	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb524_convert_creds_kdc.3 15239 2005-05-25 13:19:16Z lha $
+.\" $Id$
 .\"
 .Dd March 20, 2004
 .Dt KRB524_CONVERT_CREDS_KDC 3
@@ -66,7 +66,7 @@
 .Fa credentials .
 .Pp
 .Fn krb524_convert_creds_kdc_ccache
-is diffrent from
+is different from
 .Fn krb524_convert_creds_kdc
 in that way that if
 .Fa in_cred
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_425_=
conv_principal.3
--- a/head/crypto/heimdal/lib/krb5/krb5_425_conv_principal.3	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_425_conv_principal.3	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 1997-2003 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 1997-2003 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_425_conv_principal.3 12734 2003-09-03 00:13:07Z lha $
+.\" $Id$
 .\"
 .Dd September  3, 2003
 .Dt KRB5_425_CONV_PRINCIPAL 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_acl_=
match_file.3
--- a/head/crypto/heimdal/lib/krb5/krb5_acl_match_file.3	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_acl_match_file.3	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004, 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004, 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_acl_match_file.3 17534 2006-05-11 22:43:44Z lha $
+.\" $Id$
 .\"
 .Dd May 12, 2006
 .Dt KRB5_ACL_MATCH_FILE 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_anam=
e_to_localname.3
--- a/head/crypto/heimdal/lib/krb5/krb5_aname_to_localname.3	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_aname_to_localname.3	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_aname_to_localname.3 22071 2007-11-14 20:04:50Z lha $
+.\" $Id$
 .\"
 .Dd February 18, 2006
 .Dt KRB5_ANAME_TO_LOCALNAME 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_appd=
efault.3
--- a/head/crypto/heimdal/lib/krb5/krb5_appdefault.3	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_appdefault.3	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_appdefault.3 12329 2003-05-26 14:09:04Z lha $
+.\" $Id$
 .\"
 .Dd July 25, 2000
 .Dt KRB5_APPDEFAULT 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_auth=
_context.3
--- a/head/crypto/heimdal/lib/krb5/krb5_auth_context.3	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_auth_context.3	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2001 - 2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2001 - 2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_auth_context.3 15240 2005-05-25 13:47:58Z lha $
+.\" $Id$
 .\"
 .Dd May 17, 2005
 .Dt KRB5_AUTH_CONTEXT 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_c_ma=
ke_checksum.3
--- a/head/crypto/heimdal/lib/krb5/krb5_c_make_checksum.3	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_c_make_checksum.3	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_c_make_checksum.3 19066 2006-11-17 22:09:25Z lha $
+.\" $Id$
 .\"
 .Dd Nov  17, 2006
 .Dt KRB5_C_MAKE_CHECKSUM 3
@@ -112,7 +112,7 @@
 .Fc
 .Ft krb5_error_code
 .Fo krb5_c_verify_checksum
-.Fa "krb5_context context
+.Fa "krb5_context context"
 .Fa "const krb5_keyblock *key"
 .Fa "krb5_keyusage usage"
 .Fa "const krb5_data *data"
@@ -185,7 +185,7 @@
 .Fa input
 and store the data in
 .Fa output.
-If=20
+If
 .Fa ivec
 is
 .Dv NULL
@@ -257,7 +257,7 @@
 .Fa data
 or
 .Fa checksum
-is not needed for the application,=20
+is not needed for the application,
 .Dv NULL
 can be passed in.
 .Pp
@@ -279,14 +279,14 @@
 .Fn krb5_c_is_coll_proof_cksum
 returns true if
 .Fa ctype
-is a collition proof checksum type.
+is a collision proof checksum type.
 .Pp
 .Fn krb5_c_keylengths
-return the minimum length (
-.Fa inlength )
+return the minimum length
+.Fa ( inlength )
 bytes needed to create a key and the
-length (
-.Fa keylength )
+length
+.Fa ( keylength )
 of the resulting key
 for the
 .Fa enctype .
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_ccap=
i.h
--- a/head/crypto/heimdal/lib/krb5/krb5_ccapi.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/krb5_ccapi.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,43 +1,47 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: krb5_ccapi.h 22090 2007-12-02 23:23:43Z lha $ */
+/* $Id$ */
=20
 #ifndef KRB5_CCAPI_H
 #define KRB5_CCAPI_H 1
=20
 #include <krb5-types.h>
=20
+ #ifdef __APPLE__
+#pragma pack(push,2)
+#endif
+
 enum {
     cc_credentials_v5 =3D 2
 };
@@ -49,7 +53,7 @@
=20
 enum {
     ccNoError						=3D 0,
-   =20
+
     ccIteratorEnd					=3D 201,
     ccErrBadParam,
     ccErrNoMem,
@@ -61,25 +65,25 @@
     ccErrInvalidCCacheIterator,
     ccErrInvalidCredentialsIterator,
     ccErrInvalidLock,
-   =20
+
     ccErrBadName,					/* 211 */
     ccErrBadCredentialsVersion,
     ccErrBadAPIVersion,
     ccErrContextLocked,
     ccErrContextUnlocked,
-   =20
+
     ccErrCCacheLocked,					/* 216 */
     ccErrCCacheUnlocked,
     ccErrBadLockType,
     ccErrNeverDefault,
     ccErrCredentialsNotFound,
-   =20
+
     ccErrCCacheNotFound,				/* 221 */
     ccErrContextNotFound,
     ccErrServerUnavailable,
     ccErrServerInsecure,
     ccErrServerCantBecomeUID,
-   =20
+
     ccErrTimeOffsetNotSet				/* 226 */
 };
=20
@@ -92,7 +96,7 @@
 typedef struct cc_credentials_t *cc_credentials_t;
 typedef struct cc_credentials_iterator_t *cc_credentials_iterator_t;
 typedef struct cc_string_t *cc_string_t;
-typedef time_t cc_time_t;
+typedef cc_uint32 cc_time_t;
=20
 typedef struct cc_data {
     cc_uint32 type;
@@ -224,7 +228,12 @@
     const struct cc_context_functions* func;
 };
=20
-typedef cc_int32=20
+typedef cc_int32
 (*cc_initialize_func)(cc_context_t*, cc_int32, cc_int32 *, char const **);
=20
+#ifdef __APPLE__
+#pragma pack(pop)
+#endif
+
+
 #endif /* KRB5_CCAPI_H */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_chec=
k_transited.3
--- a/head/crypto/heimdal/lib/krb5/krb5_check_transited.3	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_check_transited.3	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004, 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004, 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_check_transited.3 17382 2006-05-01 07:09:16Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_CHECK_TRANSITED 3
@@ -86,7 +86,7 @@
 and
 .Fa num_realms
 is the realms between them.
-If the function returns an error value,=20
+If the function returns an error value,
 .Fa bad_realm
 will be set to the realm in the list causing the error.
 .Fn krb5_check_transited
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_crea=
te_checksum.3
--- a/head/crypto/heimdal/lib/krb5/krb5_create_checksum.3	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_create_checksum.3	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 1999-2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 1999-2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_create_checksum.3 15921 2005-08-12 09:01:22Z lha $
+.\" $Id$
 .\"
 .Dd August 12, 2005
 .Dt NAME 3
@@ -217,7 +217,7 @@
 Note that keyusage is not always used in checksums.
 .Pp
 .Nm krb5_checksum_disable
-globally disables the checksum type.=20
+globally disables the checksum type.
 .\" .Sh EXAMPLE
 .\" .Sh BUGS
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_cred=
s.3
--- a/head/crypto/heimdal/lib/krb5/krb5_creds.3	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/krb5_creds.3	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004, 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004, 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_creds.3 17383 2006-05-01 07:13:03Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_CREDS 3
@@ -104,7 +104,7 @@
 .Fn krb5_free_creds_contents .
 .Pp
 .Fn krb5_free_creds
-frees the content of the=20
+frees the content of the
 .Fa cred
 structure and the structure itself.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_dige=
st.3
--- a/head/crypto/heimdal/lib/krb5/krb5_digest.3	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_digest.3	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_digest.3 20259 2007-02-17 23:49:54Z lha $
+.\" $Id$
 .\"
 .Dd February  18, 2007
 .Dt KRB5_DIGEST 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_eai_=
to_heim_errno.3
--- a/head/crypto/heimdal/lib/krb5/krb5_eai_to_heim_errno.3	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_eai_to_heim_errno.3	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_eai_to_heim_errno.3 14086 2004-08-03 11:13:46Z lha $
+.\" $Id$
 .\"
 .Dd April 13, 2004
 .Dt KRB5_EAI_TO_HEIM_ERRNO 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_encr=
ypt.3
--- a/head/crypto/heimdal/lib/krb5/krb5_encrypt.3	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_encrypt.3	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 1999 - 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 1999 - 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_encrypt.3 22071 2007-11-14 20:04:50Z lha $
+.\" $Id$
 .\"
 .Dd March 20, 2004
 .Dt KRB5_ENCRYPT 3
@@ -141,7 +141,7 @@
 .Ft krb5_error_code
 .Fo krb5_crypto_getconfoundersize
 .Fa "krb5_context context"
-.Fa "krb5_crypto crypto
+.Fa "krb5_crypto crypto"
 .Fa size_t *confoundersize"
 .Fc
 .Ft krb5_error_code
@@ -199,7 +199,7 @@
 .Fa ivec
 is a pointer to a initial IV, it is modified to the end IV at the end of
 the round.
-Ivec should be the size of=20
+Ivec should be the size of
 If
 .Dv NULL
 is passed in, the default IV is used.
@@ -229,7 +229,7 @@
 works similarly.
 .Pp
 .Fn krb5_decrypt_ticket
-decrypts the encrypted part of=20
+decrypts the encrypted part of
 .Fa ticket
 with
 .Fa key .
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_err.=
et
--- a/head/crypto/heimdal/lib/krb5/krb5_err.et	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/krb5_err.et	Tue Apr 17 11:51:51 2012 +03=
00
@@ -3,7 +3,7 @@
 #
 # This might look like a com_err file, but is not
 #
-id "$Id: krb5_err.et 21050 2007-06-12 02:00:40Z lha $"
+id "$Id$"
=20
 error_table krb5
=20
@@ -106,11 +106,17 @@
 #error_code ERR_KDC_NOT_FOUND,	"IAKERB proxy could not find a KDC"
 #error_code ERR_KDC_NO_RESPONSE,	"IAKERB proxy never reeived a response fr=
om a KDC"
=20
-# 82-127 are reserved
+# 82-93 are reserved
+
+index 94
+error_code INVALID_HASH_ALG, "Invalid OTP digest algorithm"
+error_code INVALID_ITERATION_COUNT, "Invalid OTP iteration count"
+
+# 97-127 are reserved
=20
 index 128
 prefix
-error_code KRB5_ERR_RCSID,	"$Id: krb5_err.et 21050 2007-06-12 02:00:40Z lh=
a $"
+error_code KRB5_ERR_RCSID,	"$Id$"
=20
 error_code KRB5_LIBOS_BADLOCKFLAG,	"Invalid flag for file lock mode"
 error_code KRB5_LIBOS_CANTREADPWD,	"Cannot read password"
@@ -262,5 +268,7 @@
 error_code KRB5_ERR_NO_SERVICE,	"Service not available"
 error_code KRB5_CC_NOSUPP,      "Credential cache function not supported"
 error_code KRB5_DELTAT_BADFORMAT,	"Invalid format of Kerberos lifetime or =
clock skew string"
+error_code KRB5_PLUGIN_NO_HANDLE,	"Supplied data not handled by this plugi=
n"
+error_code KRB5_PLUGIN_OP_NOTSUPP,	"Plugin does not support the operaton"
=20
 end
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_find=
_padata.3
--- a/head/crypto/heimdal/lib/krb5/krb5_find_padata.3	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_find_padata.3	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_find_padata.3 13595 2004-03-21 13:17:41Z lha $
+.\" $Id$
 .\"
 .Dd March 21, 2004
 .Dt KRB5_FIND_PADATA 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_gene=
rate_random_block.3
--- a/head/crypto/heimdal/lib/krb5/krb5_generate_random_block.3	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_generate_random_block.3	Tue Apr 17 =
11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_generate_random_block.3 17385 2006-05-01 08:48:55Z lha $
+.\" $Id$
 .\"
 .Dd March 21, 2004
 .Dt KRB5_GENERATE_RANDOM_BLOCK 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_get_=
all_client_addrs.3
--- a/head/crypto/heimdal/lib/krb5/krb5_get_all_client_addrs.3	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_get_all_client_addrs.3	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2001 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2001 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_get_all_client_addrs.3 12329 2003-05-26 14:09:04Z lha $
+.\" $Id$
 .\"
 .Dd July  1, 2001
 .Dt KRB5_GET_ADDRS 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_get_=
credentials.3
--- a/head/crypto/heimdal/lib/krb5/krb5_get_credentials.3	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_get_credentials.3	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 - 2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 - 2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_get_credentials.3 22071 2007-11-14 20:04:50Z lha $
+.\" $Id$
 .\"
 .Dd July 26, 2004
 .Dt KRB5_GET_CREDENTIALS 3
@@ -37,8 +37,6 @@
 .Sh NAME
 .Nm krb5_get_credentials ,
 .Nm krb5_get_credentials_with_flags ,
-.Nm krb5_get_cred_from_kdc ,
-.Nm krb5_get_cred_from_kdc_opt ,
 .Nm krb5_get_kdc_cred ,
 .Nm krb5_get_renewed_creds
 .Nd get credentials from the KDC using krbtgt
@@ -64,23 +62,6 @@
 .Fa "krb5_creds **out_creds"
 .Fc
 .Ft krb5_error_code
-.Fo krb5_get_cred_from_kdc
-.Fa "krb5_context context"
-.Fa "krb5_ccache ccache"
-.Fa "krb5_creds *in_creds"
-.Fa "krb5_creds **out_creds"
-.Fa "krb5_creds ***ret_tgts"
-.Fc
-.Ft krb5_error_code
-.Fo krb5_get_cred_from_kdc_opt
-.Fa "krb5_context context"
-.Fa "krb5_ccache ccache"
-.Fa "krb5_creds *in_creds"
-.Fa "krb5_creds **out_creds"
-.Fa "krb5_creds ***ret_tgts"
-.Fa "krb5_flags flags"
-.Fc
-.Ft krb5_error_code
 .Fo krb5_get_kdc_cred
 .Fa "krb5_context context"
 .Fa "krb5_ccache id"
@@ -121,7 +102,7 @@
 .Fa options
 argument are:
 .Pp
-.Bl -tag -width "KRB5_GC_USER_USER" -compact
+.Bl -tag -width "KRB5_GC_EXPIRED_OK" -compact
 .It KRB5_GC_CACHED
 Only check the
 .Fa ccache ,
@@ -147,14 +128,6 @@
 .Fa flags
 field is missing.
 .Pp
-.Fn krb5_get_cred_from_kdc
-and
-.Fn krb5_get_cred_from_kdc_opt
-fetches the credential from the KDC very much like
-.Fn krb5_get_credentials, but doesn't look in the
-.Fa ccache
-if the credential exists there first.
-.Pp
 .Fn krb5_get_kdc_cred
 does the same as the functions above, but the caller must fill in all
 the information andits closer to the wire protocol.
@@ -185,7 +158,7 @@
     krb5_error_code ret;
     krb5_creds in;
=20
-    ret =3D krb5_parse_name(context, "client at EXAMPLE.COM",=20
+    ret =3D krb5_parse_name(context, "client at EXAMPLE.COM",
 			  &in.client);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_get_=
creds.3
--- a/head/crypto/heimdal/lib/krb5/krb5_get_creds.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_get_creds.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_get_creds.3 22071 2007-11-14 20:04:50Z lha $
+.\" $Id$
 .\"
 .Dd June 15, 2006
 .Dt KRB5_GET_CREDS 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_get_=
forwarded_creds.3
--- a/head/crypto/heimdal/lib/krb5/krb5_get_forwarded_creds.3	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_get_forwarded_creds.3	Tue Apr 17 11=
:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_get_forwarded_creds.3 14068 2004-07-26 13:34:33Z lha $
+.\" $Id$
 .\"
 .Dd July 26, 2004
 .Dt KRB5_GET_FORWARDED_CREDS 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_get_=
in_cred.3
--- a/head/crypto/heimdal/lib/krb5/krb5_get_in_cred.3	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_get_in_cred.3	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_get_in_cred.3 17593 2006-05-29 14:55:18Z lha $
+.\" $Id$
 .\"
 .Dd May 31, 2003
 .Dt KRB5_GET_IN_TKT 3
@@ -169,7 +169,7 @@
 .Nm krb5_get_in_tkt_with_password
 uses the clients password to authenticate.
 If the password argument is
-.DV NULL
+.Dv NULL
 the user user queried with the default password query function.
 .Pp
 .Nm krb5_get_in_tkt_with_keytab
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_get_=
init_creds.3
--- a/head/crypto/heimdal/lib/krb5/krb5_get_init_creds.3	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_get_init_creds.3	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_get_init_creds.3 20266 2007-02-18 10:41:10Z lha $
+.\" $Id$
 .\"
 .Dd Sep  16, 2006
 .Dt KRB5_GET_INIT_CREDS 3
@@ -222,7 +222,7 @@
 That may include changing an expired password, and doing preauthentication.
 This interface that replaces the deprecated
 .Fa krb5_in_tkt
-and=20
+and
 .Fa krb5_in_cred
 functions.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_get_=
krbhst.3
--- a/head/crypto/heimdal/lib/krb5/krb5_get_krbhst.3	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_get_krbhst.3	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2001 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2001 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_get_krbhst.3 14905 2005-04-24 07:46:59Z lha $
+.\" $Id$
 .\"
 .Dd April 24, 2005
 .Dt KRB5_GET_KRBHST 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_getp=
ortbyname.3
--- a/head/crypto/heimdal/lib/krb5/krb5_getportbyname.3	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_getportbyname.3	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_getportbyname.3 22071 2007-11-14 20:04:50Z lha $
+.\" $Id$
 .\"
 .Dd August 15, 2004
 .Dt NAME 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_init=
_context.3
--- a/head/crypto/heimdal/lib/krb5/krb5_init_context.3	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_init_context.3	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2001 - 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2001 - 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_init_context.3 19980 2007-01-17 18:06:33Z lha $
+.\" $Id$
 .\"
 .Dd December  8, 2004
 .Dt KRB5_CONTEXT 3
@@ -156,7 +156,7 @@
 .Fa "const char *filelist"
 .Fa "char ***pfilenames"
 .Fc
-.Ft krb5_error_code=20
+.Ft krb5_error_code
 .Fo krb5_get_default_config_files
 .Fa "char ***pfilenames"
 .Fc
@@ -211,7 +211,7 @@
 This is done by
 .Fn krb5_init_context .
 .Pp
-.Fn krb5_add_et_list=20
+.Fn krb5_add_et_list
 adds a
 .Xr com_err 3
 error-code handler
@@ -219,7 +219,7 @@
 to the specified
 .Fa context .
 The error handler must generated by the the re-rentrant version of the
-.Xr compile_et 3
+.Xr compile_et 1
 program.
 .Fn krb5_add_extra_addresses
 add a list of addresses that should be added when requesting tickets.
@@ -265,7 +265,7 @@
 configuration from the files.
 .Pp
 .Fn krb5_prepend_config_files
-parse the=20
+parse the
 .Fa filelist
 and prepend the result to the already existing list
 .Fa pq
@@ -275,7 +275,7 @@
 .Fn krb5_free_config_files .
 .Pp
 .Fn krb5_prepend_config_files_default
-parse the=20
+parse the
 .Fa filelist
 and append that to the default
 list of configuration files.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_is_t=
hread_safe.3
--- a/head/crypto/heimdal/lib/krb5/krb5_is_thread_safe.3	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_is_thread_safe.3	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_is_thread_safe.3 17462 2006-05-05 13:18:39Z lha $
+.\" $Id$
 .\"
 .Dd May  5, 2006
 .Dt KRB5_IS_THREAD_SAFE 3
@@ -50,7 +50,7 @@
 if the library was compiled with with multithread support.
 If the library isn't compiled, the consumer have to use a global lock
 to make sure Kerboros functions are not called at the same time by
-diffrent threads.
+different threads.
 .\" .Sh EXAMPLE
 .\" .Sh BUGS
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_krbh=
st_init.3
--- a/head/crypto/heimdal/lib/krb5/krb5_krbhst_init.3	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_krbhst_init.3	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2001-2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2001-2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_krbhst_init.3 15110 2005-05-10 09:21:06Z lha $
+.\" $Id$
 .\"
 .Dd May 10, 2005
 .Dt KRB5_KRBHST_INIT 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_locl=
.h
--- a/head/crypto/heimdal/lib/krb5/krb5_locl.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/krb5_locl.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,45 +1,44 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: krb5_locl.h 22226 2007-12-08 21:31:53Z lha $ */
-/* $FreeBSD$ */
+/* $Id$ */
=20
 #ifndef __KRB5_LOCL_H__
 #define __KRB5_LOCL_H__
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #include <errno.h>
 #include <ctype.h>
@@ -48,6 +47,8 @@
 #include <stdlib.h>
 #include <limits.h>
=20
+#include <krb5-types.h>
+
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
@@ -117,6 +118,21 @@
 #include <sys/file.h>
 #endif
=20
+#include <com_err.h>
+
+#include <heimbase.h>
+
+#define HEIMDAL_TEXTDOMAIN "heimdal_krb5"
+
+#ifdef LIBINTL
+#include <libintl.h>
+#define N_(x,y) dgettext(HEIMDAL_TEXTDOMAIN, x)
+#else
+#define N_(x,y) (x)
+#define bindtextdomain(package, localedir)
+#endif
+
+
 #ifdef HAVE_CRYPT_H
 #undef des_encrypt
 #define des_encrypt wingless_pigs_mostly_fail_to_fly
@@ -132,6 +148,9 @@
 #include <parse_time.h>
 #include <base64.h>
=20
+#include <wind.h>
+
+#define HC_DEPRECATED_CRYPTO
 #include "crypto-headers.h"
=20
=20
@@ -140,9 +159,11 @@
 struct send_to_kdc;
=20
 /* XXX glue for pkinit */
+struct hx509_certs_data;
 struct krb5_pk_identity;
 struct krb5_pk_cert;
 struct ContentInfo;
+struct AlgorithmIdentifier;
 typedef struct krb5_pk_init_ctx_data *krb5_pk_init_ctx;
 struct krb5_dh_moduli;
=20
@@ -155,8 +176,11 @@
 #include <krb5_err.h>
 #include <asn1_err.h>
 #ifdef PKINIT
-#include <hx509_err.h>
+#include <hx509.h>
 #endif
+
+#include "crypto.h"
+
 #include <krb5-private.h>
=20
 #include "heim_threads.h"
@@ -164,17 +188,37 @@
 #define ALLOC(X, N) (X) =3D calloc((N), sizeof(*(X)))
 #define ALLOC_SEQ(X, N) do { (X)->len =3D (N); ALLOC((X)->val, (N)); } whi=
le(0)
=20
+#ifndef __func__
+#define __func__ "unknown-function"
+#endif
+
+#define krb5_einval(context, argnum) _krb5_einval((context), __func__, (ar=
gnum))
+
+#ifndef PATH_SEP
+#define PATH_SEP ":"
+#endif
+
 /* should this be public? */
-#define KEYTAB_DEFAULT "ANY:FILE:" SYSCONFDIR "/krb5.keytab,krb4:" SYSCONF=
DIR "/srvtab"
+#define KEYTAB_DEFAULT "FILE:" SYSCONFDIR "/krb5.keytab"
 #define KEYTAB_DEFAULT_MODIFY "FILE:" SYSCONFDIR "/krb5.keytab"
=20
+
 #define MODULI_FILE SYSCONFDIR "/krb5.moduli"
=20
 #ifndef O_BINARY
 #define O_BINARY 0
 #endif
=20
-#define KRB5_BUFSIZ 1024
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+
+#ifndef SOCK_CLOEXEC
+#define SOCK_CLOEXEC 0
+#endif
+
+
+#define KRB5_BUFSIZ 2048
=20
 typedef enum {
     KRB5_INIT_CREDS_TRISTATE_UNSET =3D 0,
@@ -191,16 +235,25 @@
     krb5_get_init_creds_tristate req_pac;
     /* PKINIT */
     krb5_pk_init_ctx pk_init_ctx;
-    KRB_ERROR *error;
     krb5_get_init_creds_tristate addressless;
     int flags;
 #define KRB5_INIT_CREDS_CANONICALIZE		1
 #define KRB5_INIT_CREDS_NO_C_CANON_CHECK	2
+#define KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK	4
+    struct {
+        krb5_gic_process_last_req func;
+        void *ctx;
+    } lr;
 };
=20
+typedef uint32_t krb5_enctype_set;
+
 typedef struct krb5_context_data {
     krb5_enctype *etypes;
-    krb5_enctype *etypes_des;
+    krb5_enctype *etypes_des;/* deprecated */
+    krb5_enctype *as_etypes;
+    krb5_enctype *tgs_etypes;
+    krb5_enctype *permitted_enctypes;
     char **default_realms;
     time_t max_skew;
     time_t kdc_timeout;
@@ -210,7 +263,8 @@
     krb5_config_section *cf;
     struct et_list *et_list;
     struct krb5_log_facility *warn_dest;
-    krb5_cc_ops *cc_ops;
+    struct krb5_log_facility *debug_dest;
+    const krb5_cc_ops **cc_ops;
     int num_cc_ops;
     const char *http_proxy;
     const char *time_fmt;
@@ -228,7 +282,7 @@
     struct krb5_keytab_data *kt_types;  /* registered keytab types */
     const char *date_fmt;
     char *error_string;
-    char error_buf[256];
+    krb5_error_code error_code;
     krb5_addresses *ignore_addresses;
     char *default_cc_name;
     char *default_cc_name_env;
@@ -238,16 +292,29 @@
     int flags;
 #define KRB5_CTX_F_DNS_CANONICALIZE_HOSTNAME	1
 #define KRB5_CTX_F_CHECK_PAC			2
+#define KRB5_CTX_F_HOMEDIR_ACCESS		4
+#define KRB5_CTX_F_SOCKETS_INITIALIZED          8
+#define KRB5_CTX_F_RD_REQ_IGNORE		16
     struct send_to_kdc *send_to_kdc;
+#ifdef PKINIT
+    hx509_context hx509ctx;
+#endif
 } krb5_context_data;
=20
+#ifndef KRB5_USE_PATH_TOKENS
 #define KRB5_DEFAULT_CCNAME_FILE "FILE:/tmp/krb5cc_%{uid}"
+#else
+#define KRB5_DEFAULT_CCNAME_FILE "FILE:%{TEMP}/krb5cc_%{uid}"
+#endif
 #define KRB5_DEFAULT_CCNAME_API "API:"
-#define KRB5_DEFAULT_CCNAME_KCM "KCM:%{uid}"
+#define KRB5_DEFAULT_CCNAME_KCM_KCM "KCM:%{uid}"
+#define KRB5_DEFAULT_CCNAME_KCM_API "API:%{uid}"
=20
 #define EXTRACT_TICKET_ALLOW_CNAME_MISMATCH		1
 #define EXTRACT_TICKET_ALLOW_SERVER_MISMATCH		2
 #define EXTRACT_TICKET_MATCH_REALM			4
+#define EXTRACT_TICKET_AS_REQ				8
+#define EXTRACT_TICKET_TIMESYNC				16
=20
 /*
  * Configurable options
@@ -265,4 +332,28 @@
 #define KRB5_ADDRESSLESS_DEFAULT TRUE
 #endif
=20
+#ifndef KRB5_FORWARDABLE_DEFAULT
+#define KRB5_FORWARDABLE_DEFAULT TRUE
+#endif
+
+#ifdef PKINIT
+
+struct krb5_pk_identity {
+    hx509_verify_ctx verify_ctx;
+    hx509_certs certs;
+    hx509_cert cert;
+    hx509_certs anchors;
+    hx509_certs certpool;
+    hx509_revoke_ctx revokectx;
+    int flags;
+#define PKINIT_BTMM 1
+};
+
+enum krb5_pk_type {
+    PKINIT_WIN2K =3D 1,
+    PKINIT_27 =3D 2
+};
+
+#endif /* PKINIT */
+
 #endif /* __KRB5_LOCL_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_mk_r=
eq.3
--- a/head/crypto/heimdal/lib/krb5/krb5_mk_req.3	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_mk_req.3	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_mk_req.3 16100 2005-09-26 05:38:55Z lha $
+.\" $Id$
 .\"
 .Dd August 27, 2005
 .Dt KRB5_MK_REQ 3
@@ -123,7 +123,7 @@
 .Dv NULL
 passed in, in that case, it will be allocated and freed internally.
 .Pp
-The input data=20
+The input data
 .Fa in_data
 will have a checksum calculated over it and checksum will be
 transported in the message to the server.
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_mk_s=
afe.3
--- a/head/crypto/heimdal/lib/krb5/krb5_mk_safe.3	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_mk_safe.3	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_mk_safe.3 17385 2006-05-01 08:48:55Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_MK_SAFE 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_open=
log.3
--- a/head/crypto/heimdal/lib/krb5/krb5_openlog.3	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_openlog.3	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 1997, 1999, 2001 - 2002 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 1997, 1999, 2001 - 2002 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_openlog.3 12329 2003-05-26 14:09:04Z lha $
+.\" $Id$
 .Dd August 6, 1997
 .Dt KRB5_OPENLOG 3
 .Os HEIMDAL
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_pars=
e_name.3
--- a/head/crypto/heimdal/lib/krb5/krb5_parse_name.3	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_parse_name.3	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_parse_name.3 17385 2006-05-01 08:48:55Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_PARSE_NAME 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_prin=
cipal.3
--- a/head/crypto/heimdal/lib/krb5/krb5_principal.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_principal.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2007 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_principal.3 21255 2007-06-21 04:36:31Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_PRINCIPAL 3
@@ -47,7 +47,6 @@
 .Nm krb5_parse_name ,
 .Nm krb5_parse_name_flags ,
 .Nm krb5_parse_nametype ,
-.Nm krb5_princ_realm ,
 .Nm krb5_princ_set_realm ,
 .Nm krb5_principal_compare ,
 .Nm krb5_principal_compare_any_realm ,
@@ -90,8 +89,6 @@
 .Fn "krb5_unparse_name_short" "krb5_context context" "krb5_const_principal=
 principal" "char **name"
 .Ft krb5_error_code
 .Fn krb5_unparse_name_fixed_short "krb5_context context" "krb5_const_princ=
ipal principal" "char *name" "size_t len"
-.Ft krb5_realm *
-.Fn krb5_princ_realm "krb5_context context" "krb5_principal principal"
 .Ft void
 .Fn krb5_princ_set_realm "krb5_context context" "krb5_principal principal"=
 "krb5_realm *realm"
 .Ft krb5_error_code
@@ -158,12 +155,12 @@
 argument the following flags can be passed in
 .Bl -tag -width Ds
 .It Dv KRB5_PRINCIPAL_PARSE_NO_REALM
-requries the input string to be without a realm, and no realm is
+requires the input string to be without a realm, and no realm is
 stored in the
 .Fa principal
 return argument.
-.It Dv KRB5_PRINCIPAL_PARSE_MUST_REALM
-requries the input string to with a realm.
+.It Dv KRB5_PRINCIPAL_PARSE_REQUIRE_REALM
+requires the input string to with a realm.
 .El
 .Pp
 .Fn krb5_unparse_name
@@ -176,7 +173,7 @@
 .Fa name
 should be freed with
 .Xr free 3 .
-To the=20
+To the
 .Fa flags
 argument the following flags can be passed in
 .Bl -tag -width Ds
@@ -287,7 +284,6 @@
 and
 .Fn krb5_principal_get_comp_string
 are replacements for
-.Fn krb5_princ_realm ,
 .Fn krb5_princ_component
 and related macros, described as internal in the MIT API
 specification.
@@ -309,14 +305,6 @@
 Name type handling is tricky and not often needed,
 don't use this unless you know what you do.
 .Pp
-.Fn krb5_princ_realm
-returns the realm component of the principal.
-The caller must not free realm unless
-.Fn krb5_princ_set_realm
-is called to set a new realm after freeing the realm.
-.Fn krb5_princ_set_realm
-sets the realm component of a principal. The old realm is not freed.
-.Pp
 .Fn krb5_sname_to_principal
 and
 .Fn krb5_sock_to_principal
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_rcac=
he.3
--- a/head/crypto/heimdal/lib/krb5/krb5_rcache.3	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_rcache.3	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_rcache.3 17462 2006-05-05 13:18:39Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_RCACHE 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_rd_e=
rror.3
--- a/head/crypto/heimdal/lib/krb5/krb5_rd_error.3	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_rd_error.3	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_rd_error.3 21059 2007-06-12 17:52:46Z lha $
+.\" $Id$
 .\"
 .Dd July 26, 2004
 .Dt KRB5_RD_ERROR 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_rd_s=
afe.3
--- a/head/crypto/heimdal/lib/krb5/krb5_rd_safe.3	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_rd_safe.3	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_rd_safe.3 17385 2006-05-01 08:48:55Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_RD_SAFE 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_set_=
default_realm.3
--- a/head/crypto/heimdal/lib/krb5/krb5_set_default_realm.3	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_set_default_realm.3	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2005 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2005 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_set_default_realm.3 17462 2006-05-05 13:18:39Z lha $
+.\" $Id$
 .\"
 .Dd April 24, 2005
 .Dt KRB5_SET_DEFAULT_REALM 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_set_=
password.3
--- a/head/crypto/heimdal/lib/krb5/krb5_set_password.3	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_set_password.3	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_set_password.3 14052 2004-07-15 14:39:06Z lha $
+.\" $Id$
 .\"
 .Dd July 15, 2004
 .Dt KRB5_SET_PASSWORD 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_stri=
ng_to_key.3
--- a/head/crypto/heimdal/lib/krb5/krb5_string_to_key.3	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_string_to_key.3	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 - 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 - 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_string_to_key.3 17820 2006-07-10 14:28:01Z lha $
+.\" $Id$
 .\"
 .Dd July 10, 2006
 .Dt KRB5_STRING_TO_KEY 3
@@ -114,7 +114,7 @@
 .Pp
 .Fn krb5_string_to_key_data_salt_opaque
 is the function that does all the work, the rest of the functions are
-just wrapers around
+just wrappers around
 .Fn krb5_string_to_key_data_salt_opaque
 that calls it with default values.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_time=
ofday.3
--- a/head/crypto/heimdal/lib/krb5/krb5_timeofday.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_timeofday.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,6 +1,6 @@
-.\" $Id: krb5_timeofday.3 18093 2006-09-16 09:27:28Z lha $
+.\" $Id$
 .\"
-.\" Copyright (c) 2001, 2003, 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2001, 2003, 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -31,7 +31,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_timeofday.3 18093 2006-09-16 09:27:28Z lha $
+.\" $Id$
 .\"
 .Dd Sepember  16, 2006
 .Dt KRB5_TIMEOFDAY 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_veri=
fy_init_creds.3
--- a/head/crypto/heimdal/lib/krb5/krb5_verify_init_creds.3	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_verify_init_creds.3	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2003 - 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2003 - 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_verify_init_creds.3 22071 2007-11-14 20:04:50Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_VERIFY_INIT_CREDS 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krb5_veri=
fy_user.3
--- a/head/crypto/heimdal/lib/krb5/krb5_verify_user.3	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krb5_verify_user.3	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2001 - 2006 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2001 - 2006 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: krb5_verify_user.3 22071 2007-11-14 20:04:50Z lha $
+.\" $Id$
 .\"
 .Dd May  1, 2006
 .Dt KRB5_VERIFY_USER 3
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krbhst-te=
st.c
--- a/head/crypto/heimdal/lib/krb5/krbhst-test.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/krbhst-test.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2001 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
@@ -36,8 +36,6 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id: krbhst-test.c 15466 2005-06-17 04:21:47Z lha $");
-
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
@@ -67,12 +65,12 @@
 		   KRB5_KRBHST_KRB524};
     const char *type_str[] =3D {"kdc", "admin", "changepw", "krb524"};
     int optidx =3D 0;
-   =20
+
     setprogname (argv[0]);
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -95,7 +93,7 @@
 	    krb5_krbhst_init(context, argv[i], types[j], &handle);
 	    while(krb5_krbhst_next_as_string(context, handle,
 					     host, sizeof(host)) =3D=3D 0)
-		printf("%s\n", host);
+		printf("\thost: %s\n", host);
 	    krb5_krbhst_reset(context, handle);
 	    printf ("\n");
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/krbhst.c
--- a/head/crypto/heimdal/lib/krb5/krbhst.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/krbhst.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,50 +1,48 @@
 /*
- * Copyright (c) 2001 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include <resolve.h>
 #include "locate_plugin.h"
=20
-RCSID("$Id: krbhst.c 21457 2007-07-10 12:53:25Z lha $");
-
 static int
 string_to_proto(const char *string)
 {
     if(strcasecmp(string, "udp") =3D=3D 0)
 	return KRB5_KRBHST_UDP;
-    else if(strcasecmp(string, "tcp") =3D=3D 0)=20
+    else if(strcasecmp(string, "tcp") =3D=3D 0)
 	return KRB5_KRBHST_TCP;
-    else if(strcasecmp(string, "http") =3D=3D 0)=20
+    else if(strcasecmp(string, "http") =3D=3D 0)
 	return KRB5_KRBHST_HTTP;
     return -1;
 }
@@ -56,13 +54,13 @@
  */
=20
 static krb5_error_code
-srv_find_realm(krb5_context context, krb5_krbhst_info ***res, int *count,=20
+srv_find_realm(krb5_context context, krb5_krbhst_info ***res, int *count,
 	       const char *realm, const char *dns_type,
 	       const char *proto, const char *service, int port)
 {
     char domain[1024];
-    struct dns_reply *r;
-    struct resource_record *rr;
+    struct rk_dns_reply *r;
+    struct rk_resource_record *rr;
     int num_srv;
     int proto_num;
     int def_port;
@@ -72,7 +70,9 @@
=20
     proto_num =3D string_to_proto(proto);
     if(proto_num < 0) {
-	krb5_set_error_string(context, "unknown protocol `%s'", proto);
+	krb5_set_error_message(context, EINVAL,
+			       N_("unknown protocol `%s' to lookup", ""),
+			       proto);
 	return EINVAL;
     }
=20
@@ -85,31 +85,35 @@
=20
     snprintf(domain, sizeof(domain), "_%s._%s.%s.", service, proto, realm);
=20
-    r =3D dns_lookup(domain, dns_type);
-    if(r =3D=3D NULL)
+    r =3D rk_dns_lookup(domain, dns_type);
+    if(r =3D=3D NULL) {
+	_krb5_debug(context, 0,
+		    "DNS lookup failed domain: %s", domain);
 	return KRB5_KDC_UNREACH;
+    }
=20
-    for(num_srv =3D 0, rr =3D r->head; rr; rr =3D rr->next)=20
-	if(rr->type =3D=3D T_SRV)
+    for(num_srv =3D 0, rr =3D r->head; rr; rr =3D rr->next)
+	if(rr->type =3D=3D rk_ns_t_srv)
 	    num_srv++;
=20
     *res =3D malloc(num_srv * sizeof(**res));
     if(*res =3D=3D NULL) {
-	dns_free_data(r);
-	krb5_set_error_string(context, "malloc: out of memory");
+	rk_dns_free_data(r);
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
-    dns_srv_order(r);
+    rk_dns_srv_order(r);
=20
-    for(num_srv =3D 0, rr =3D r->head; rr; rr =3D rr->next)=20
-	if(rr->type =3D=3D T_SRV) {
+    for(num_srv =3D 0, rr =3D r->head; rr; rr =3D rr->next)
+	if(rr->type =3D=3D rk_ns_t_srv) {
 	    krb5_krbhst_info *hi;
 	    size_t len =3D strlen(rr->u.srv->target);
=20
 	    hi =3D calloc(1, sizeof(*hi) + len);
 	    if(hi =3D=3D NULL) {
-		dns_free_data(r);
+		rk_dns_free_data(r);
 		while(--num_srv >=3D 0)
 		    free((*res)[num_srv]);
 		free(*res);
@@ -119,7 +123,7 @@
 	    (*res)[num_srv++] =3D hi;
=20
 	    hi->proto =3D proto_num;
-	   =20
+
 	    hi->def_port =3D def_port;
 	    if (port !=3D 0)
 		hi->port =3D port;
@@ -130,8 +134,8 @@
 	}
=20
     *count =3D num_srv;
-	   =20
-    dns_free_data(r);
+
+    rk_dns_free_data(r);
     return 0;
 }
=20
@@ -149,7 +153,7 @@
 #define KD_CONFIG_EXISTS	32
 #define KD_LARGE_MSG		64
 #define KD_PLUGIN	       128
-    krb5_error_code (*get_next)(krb5_context, struct krb5_krbhst_data *,=20
+    krb5_error_code (*get_next)(krb5_context, struct krb5_krbhst_data *,
 				krb5_krbhst_info**);
=20
     unsigned int fallback_count;
@@ -175,6 +179,15 @@
     return KRB5_KRBHST_UDP;
 }
=20
+/*
+ *
+ */
+
+const char *
+_krb5_krbhst_get_realm(krb5_krbhst_handle handle)
+{
+    return handle->realm;
+}
=20
 /*
  * parse `spec' into a krb5_krbhst_info, defaulting the port to `def_port'
@@ -185,13 +198,13 @@
 parse_hostspec(krb5_context context, struct krb5_krbhst_data *kd,
 	       const char *spec, int def_port, int port)
 {
-    const char *p =3D spec;
+    const char *p =3D spec, *q;
     struct krb5_krbhst_info *hi;
-   =20
+
     hi =3D calloc(1, sizeof(*hi) + strlen(spec));
     if(hi =3D=3D NULL)
 	return NULL;
-      =20
+
     hi->proto =3D krbhst_get_default_proto(kd);
=20
     if(strncmp(p, "http://", 7) =3D=3D 0){
@@ -208,7 +221,17 @@
 	p +=3D 4;
     }
=20
-    if(strsep_copy(&p, ":", hi->hostname, strlen(spec) + 1) < 0) {
+    if (p[0] =3D=3D '[' && (q =3D strchr(p, ']')) !=3D NULL) {
+	/* if address looks like [foo:bar] or [foo:bar]: its a ipv6
+	   adress, strip of [] */
+	memcpy(hi->hostname, &p[1], q - p - 1);
+	hi->hostname[q - p - 1] =3D '\0';
+	p =3D q + 1;
+	/* get trailing : */
+	if (p[0] =3D=3D ':')
+	    p++;
+    } else if(strsep_copy(&p, ":", hi->hostname, strlen(spec) + 1) < 0) {
+	/* copy everything before : */
 	free(hi);
 	return NULL;
     }
@@ -217,7 +240,7 @@
     strlwr(hi->hostname);
=20
     hi->port =3D hi->def_port =3D def_port;
-    if(p !=3D NULL) {
+    if(p !=3D NULL && p[0]) {
 	char *end;
 	hi->port =3D strtol(p, &end, 0);
 	if(end =3D=3D p) {
@@ -245,9 +268,10 @@
 {
     size_t hostnamelen =3D strlen(from->hostname);
     /* trailing NUL is included in structure */
-    *to =3D calloc(1, sizeof(**to) + hostnamelen);=20
+    *to =3D calloc(1, sizeof(**to) + hostnamelen);
     if(*to =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -268,8 +292,8 @@
     struct krb5_krbhst_info *h;
=20
     for(h =3D kd->hosts; h; h =3D h->next)
-	if(h->proto =3D=3D host->proto &&=20
-	   h->port =3D=3D host->port &&=20
+	if(h->proto =3D=3D host->proto &&
+	   h->port =3D=3D host->port &&
 	   strcmp(h->hostname, host->hostname) =3D=3D 0) {
 	    _krb5_free_krbhst_info(host);
 	    return;
@@ -287,7 +311,7 @@
     hi =3D parse_hostspec(context, kd, host, def_port, port);
     if(hi =3D=3D NULL)
 	return ENOMEM;
-   =20
+
     append_host_hostinfo(kd, hi);
     return 0;
 }
@@ -296,8 +320,8 @@
  * return a readable representation of `host' in `hostname, hostlen'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_krbhst_format_string(krb5_context context, const krb5_krbhst_info *ho=
st,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_krbhst_format_string(krb5_context context, const krb5_krbhst_info *ho=
st,
 			  char *hostname, size_t hostlen)
 {
     const char *proto =3D "";
@@ -332,28 +356,66 @@
     }
 }
=20
-/*
- * return an `struct addrinfo *' in `ai' corresponding to the information
- * in `host'.  free:ing is handled by krb5_krbhst_free.
+/**
+ * Return an `struct addrinfo *' for a KDC host.
+ *
+ * Returns an the struct addrinfo in in that corresponds to the
+ * information in `host'.  free:ing is handled by krb5_krbhst_free, so
+ * the returned ai must not be released.
+ *
+ * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_get_addrinfo(krb5_context context, krb5_krbhst_info *host,
 			 struct addrinfo **ai)
 {
-    struct addrinfo hints;
-    char portstr[NI_MAXSERV];
-    int ret;
+    int ret =3D 0;
=20
     if (host->ai =3D=3D NULL) {
+	struct addrinfo hints;
+	char portstr[NI_MAXSERV];
+	char *hostname =3D host->hostname;
+
+	snprintf (portstr, sizeof(portstr), "%d", host->port);
 	make_hints(&hints, host->proto);
-	snprintf (portstr, sizeof(portstr), "%d", host->port);
+
+	/**
+	 * First try this as an IP address, this allows us to add a
+	 * dot at the end to stop using the search domains.
+	 */
+
+	hints.ai_flags |=3D AI_NUMERICHOST | AI_NUMERICSERV;
+
 	ret =3D getaddrinfo(host->hostname, portstr, &hints, &host->ai);
-	if (ret)
-	    return krb5_eai_to_heim_errno(ret, errno);
+	if (ret =3D=3D 0)
+	    goto out;
+
+	/**
+	 * If the hostname contains a dot, assumes it's a FQDN and
+	 * don't use search domains since that might be painfully slow
+	 * when machine is disconnected from that network.
+	 */
+
+	hints.ai_flags &=3D ~(AI_NUMERICHOST);
+
+	if (strchr(hostname, '.') && hostname[strlen(hostname) - 1] !=3D '.') {
+	    ret =3D asprintf(&hostname, "%s.", host->hostname);
+	    if (ret < 0 || hostname =3D=3D NULL)
+		return ENOMEM;
+	}
+
+	ret =3D getaddrinfo(hostname, portstr, &hints, &host->ai);
+	if (hostname !=3D host->hostname)
+	    free(hostname);
+	if (ret) {
+	    ret =3D krb5_eai_to_heim_errno(ret, errno);
+	    goto out;
+	}
     }
+ out:
     *ai =3D host->ai;
-    return 0;
+    return ret;
 }
=20
 static krb5_boolean
@@ -369,14 +431,18 @@
 }
=20
 static void
-srv_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,=20
+srv_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
 	      const char *proto, const char *service)
 {
+    krb5_error_code ret;
     krb5_krbhst_info **res;
     int count, i;
=20
-    if (srv_find_realm(context, &res, &count, kd->realm, "SRV", proto, ser=
vice,
-		       kd->port))
+    ret =3D srv_find_realm(context, &res, &count, kd->realm, "SRV", proto,=
 service,
+			 kd->port);
+    _krb5_debug(context, 2, "searching DNS for realm %s %s.%s -> %d",
+		kd->realm, proto, service, ret);
+    if (ret)
 	return;
     for(i =3D 0; i < count; i++)
 	append_host_hostinfo(kd, res[i]);
@@ -389,15 +455,17 @@
  */
=20
 static void
-config_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,=20
+config_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
 		 const char *conf_string)
 {
     int i;
-=09
     char **hostlist;
-    hostlist =3D krb5_config_get_strings(context, NULL,=20
+    hostlist =3D krb5_config_get_strings(context, NULL,
 				       "realms", kd->realm, conf_string, NULL);
=20
+    _krb5_debug(context, 2, "configuration file for realm %s%s found",
+		kd->realm, hostlist ? "" : " not");
+
     if(hostlist =3D=3D NULL)
 	return;
     kd->flags |=3D KD_CONFIG_EXISTS;
@@ -410,21 +478,24 @@
 /*
  * as a fallback, look for `serv_string.kd->realm' (typically
  * kerberos.REALM, kerberos-1.REALM, ...
- * `port' is the default port for the service, and `proto' the=20
+ * `port' is the default port for the service, and `proto' the
  * protocol
  */
=20
 static krb5_error_code
-fallback_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,=20
+fallback_get_hosts(krb5_context context, struct krb5_krbhst_data *kd,
 		   const char *serv_string, int port, int proto)
 {
-    char *host;
+    char *host =3D NULL;
     int ret;
     struct addrinfo *ai;
     struct addrinfo hints;
     char portstr[NI_MAXSERV];
=20
-    /*=20
+    _krb5_debug(context, 2, "fallback lookup %d for realm %s (service %s)",
+		kd->fallback_count, kd->realm, serv_string);
+
+    /*
      * Don't try forever in case the DNS server keep returning us
      * entries (like wildcard entries or the .nu TLD)
      */
@@ -434,14 +505,14 @@
     }
=20
     if(kd->fallback_count =3D=3D 0)
-	asprintf(&host, "%s.%s.", serv_string, kd->realm);
+	ret =3D asprintf(&host, "%s.%s.", serv_string, kd->realm);
     else
-	asprintf(&host, "%s-%d.%s.",=20
-		 serv_string, kd->fallback_count, kd->realm);	   =20
+	ret =3D asprintf(&host, "%s-%d.%s.",
+		       serv_string, kd->fallback_count, kd->realm);
=20
-    if (host =3D=3D NULL)
+    if (ret < 0 || host =3D=3D NULL)
 	return ENOMEM;
-   =20
+
     make_hints(&hints, proto);
     snprintf(portstr, sizeof(portstr), "%d", port);
     ret =3D getaddrinfo(host, portstr, &hints, &ai);
@@ -475,7 +546,7 @@
  * Fetch hosts from plugin
  */
=20
-static krb5_error_code=20
+static krb5_error_code
 add_locate(void *ctx, int type, struct sockaddr *addr)
 {
     struct krb5_krbhst_info *hi;
@@ -503,7 +574,7 @@
     hi =3D calloc(1, sizeof(*hi) + hostlen);
     if(hi =3D=3D NULL)
 	return ENOMEM;
-   =20
+
     hi->proto =3D krbhst_get_default_proto(kd);
     hi->port  =3D hi->def_port =3D socket_get_port(addr);
     hi->ai    =3D ai;
@@ -522,12 +593,11 @@
     struct krb5_plugin *list =3D NULL, *e;
     krb5_error_code ret;
=20
-    ret =3D _krb5_plugin_find(context, PLUGIN_TYPE_DATA, "resolve", &list);
+    ret =3D _krb5_plugin_find(context, PLUGIN_TYPE_DATA,
+			    KRB5_PLUGIN_LOCATE, &list);
     if(ret !=3D 0 || list =3D=3D NULL)
 	return;
=20
-    kd->flags |=3D KD_CONFIG_EXISTS;
-
     for (e =3D list; e !=3D NULL; e =3D _krb5_plugin_get_next(e)) {
 	krb5plugin_service_locate_ftable *service;
 	void *ctx;
@@ -535,14 +605,20 @@
 	service =3D _krb5_plugin_get_symbol(e);
 	if (service->minor_version !=3D 0)
 	    continue;
-=09
+
 	(*service->init)(context, &ctx);
 	ret =3D (*service->lookup)(ctx, type, kd->realm, 0, 0, add_locate, kd);
 	(*service->fini)(ctx);
-	if (ret) {
-	    krb5_set_error_string(context, "Plugin failed to lookup");
+	if (ret && ret !=3D KRB5_PLUGIN_NO_HANDLE) {
+	    krb5_set_error_message(context, ret,
+				   N_("Locate plugin failed to lookup realm %s: %d", ""),
+				   kd->realm, ret);
 	    break;
+	} else if (ret =3D=3D 0) {
+	    _krb5_debug(context, 2, "plugin found result for realm %s", kd->realm=
);
+	    kd->flags |=3D KD_CONFIG_EXISTS;
 	}
+
     }
     _krb5_plugin_free(list);
 }
@@ -572,8 +648,12 @@
 	    return 0;
     }
=20
-    if (kd->flags & KD_CONFIG_EXISTS)
-	return KRB5_KDC_UNREACH; /* XXX */
+    if (kd->flags & KD_CONFIG_EXISTS) {
+	_krb5_debug(context, 1,
+		    "Configuration exists for realm %s, wont go to DNS",
+		    kd->realm);
+	return KRB5_KDC_UNREACH;
+    }
=20
     if(context->srv_lookup) {
 	if((kd->flags & KD_SRV_UDP) =3D=3D 0 && (kd->flags & KD_LARGE_MSG) =3D=3D=
 0) {
@@ -599,7 +679,7 @@
=20
     while((kd->flags & KD_FALLBACK) =3D=3D 0) {
 	ret =3D fallback_get_hosts(context, kd, "kerberos",
-				 kd->def_port,=20
+				 kd->def_port,
 				 krbhst_get_default_proto(kd));
 	if(ret)
 	    return ret;
@@ -607,6 +687,8 @@
 	    return 0;
     }
=20
+    _krb5_debug(context, 0, "No KDC entries found for %s", kd->realm);
+
     return KRB5_KDC_UNREACH; /* XXX */
 }
=20
@@ -631,8 +713,12 @@
 	    return 0;
     }
=20
-    if (kd->flags & KD_CONFIG_EXISTS)
-	return KRB5_KDC_UNREACH; /* XXX */
+    if (kd->flags & KD_CONFIG_EXISTS) {
+	_krb5_debug(context, 1,
+		    "Configuration exists for realm %s, wont go to DNS",
+		    kd->realm);
+	return KRB5_KDC_UNREACH;
+    }
=20
     if(context->srv_lookup) {
 	if((kd->flags & KD_SRV_TCP) =3D=3D 0) {
@@ -655,6 +741,8 @@
 	    return 0;
     }
=20
+    _krb5_debug(context, 0, "No admin entries found for realm %s", kd->rea=
lm);
+
     return KRB5_KDC_UNREACH;	/* XXX */
 }
=20
@@ -679,8 +767,12 @@
 	    return 0;
     }
=20
-    if (kd->flags & KD_CONFIG_EXISTS)
-	return KRB5_KDC_UNREACH; /* XXX */
+    if (kd->flags & KD_CONFIG_EXISTS) {
+	_krb5_debug(context, 1,
+		    "Configuration exists for realm %s, wont go to DNS",
+		    kd->realm);
+	return KRB5_KDC_UNREACH;
+    }
=20
     if(context->srv_lookup) {
 	if((kd->flags & KD_SRV_UDP) =3D=3D 0) {
@@ -709,7 +801,9 @@
 	return ret;
     }
=20
-    return KRB5_KDC_UNREACH; /* XXX */
+    _krb5_debug(context, 0, "No kpasswd entries found for realm %s", kd->r=
ealm);
+
+    return KRB5_KDC_UNREACH;
 }
=20
 static krb5_error_code
@@ -731,8 +825,12 @@
 	kd->flags |=3D KD_CONFIG;
     }
=20
-    if (kd->flags & KD_CONFIG_EXISTS)
-	return KRB5_KDC_UNREACH; /* XXX */
+    if (kd->flags & KD_CONFIG_EXISTS) {
+	_krb5_debug(context, 1,
+		    "Configuration exists for realm %s, wont go to DNS",
+		    kd->realm);
+	return KRB5_KDC_UNREACH;
+    }
=20
     if(context->srv_lookup) {
 	if((kd->flags & KD_SRV_UDP) =3D=3D 0) {
@@ -759,11 +857,14 @@
 	return (*kd->get_next)(context, kd, host);
     }
=20
-    return KRB5_KDC_UNREACH; /* XXX */
+    _krb5_debug(context, 0, "No kpasswd entries found for realm %s", kd->r=
ealm);
+
+    return KRB5_KDC_UNREACH;
 }
=20
 static struct krb5_krbhst_data*
 common_init(krb5_context context,
+	    const char *service,
 	    const char *realm,
 	    int flags)
 {
@@ -777,6 +878,9 @@
 	return NULL;
     }
=20
+    _krb5_debug(context, 2, "Trying to find service %s for realm %s flags =
%x",
+		service, realm, flags);
+
     /* For 'realms' without a . do not even think of going to DNS */
     if (!strchr(realm, '.'))
 	kd->flags |=3D KD_CONFIG_EXISTS;
@@ -791,7 +895,7 @@
  * initialize `handle' to look for hosts of type `type' in realm `realm'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_init(krb5_context context,
 		 const char *realm,
 		 unsigned int type,
@@ -800,7 +904,7 @@
     return krb5_krbhst_init_flags(context, realm, type, 0, handle);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_init_flags(krb5_context context,
 		       const char *realm,
 		       unsigned int type,
@@ -808,34 +912,40 @@
 		       krb5_krbhst_handle *handle)
 {
     struct krb5_krbhst_data *kd;
-    krb5_error_code (*next)(krb5_context, struct krb5_krbhst_data *,=20
+    krb5_error_code (*next)(krb5_context, struct krb5_krbhst_data *,
 			    krb5_krbhst_info **);
     int def_port;
+    const char *service;
=20
     switch(type) {
     case KRB5_KRBHST_KDC:
 	next =3D kdc_get_next;
 	def_port =3D ntohs(krb5_getportbyname (context, "kerberos", "udp", 88));
+	service =3D "kdc";
 	break;
     case KRB5_KRBHST_ADMIN:
 	next =3D admin_get_next;
 	def_port =3D ntohs(krb5_getportbyname (context, "kerberos-adm",
 					     "tcp", 749));
+	service =3D "admin";
 	break;
     case KRB5_KRBHST_CHANGEPW:
 	next =3D kpasswd_get_next;
 	def_port =3D ntohs(krb5_getportbyname (context, "kpasswd", "udp",
 					     KPASSWD_PORT));
+	service =3D "change_password";
 	break;
     case KRB5_KRBHST_KRB524:
 	next =3D krb524_get_next;
 	def_port =3D ntohs(krb5_getportbyname (context, "krb524", "udp", 4444));
+	service =3D "524";
 	break;
     default:
-	krb5_set_error_string(context, "unknown krbhst type (%u)", type);
+	krb5_set_error_message(context, ENOTTY,
+			       N_("unknown krbhst type (%u)", ""), type);
 	return ENOTTY;
     }
-    if((kd =3D common_init(context, realm, flags)) =3D=3D NULL)
+    if((kd =3D common_init(context, service, realm, flags)) =3D=3D NULL)
 	return ENOMEM;
     kd->get_next =3D next;
     kd->def_port =3D def_port;
@@ -847,7 +957,7 @@
  * return the next host information from `handle' in `host'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_next(krb5_context context,
 		 krb5_krbhst_handle handle,
 		 krb5_krbhst_info **host)
@@ -863,7 +973,7 @@
  * in `hostname' (or length `hostlen)
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_krbhst_next_as_string(krb5_context context,
 			   krb5_krbhst_handle handle,
 			   char *hostname,
@@ -878,13 +988,13 @@
 }
=20
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_krbhst_reset(krb5_context context, krb5_krbhst_handle handle)
 {
     handle->index =3D &handle->hosts;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_krbhst_free(krb5_context context, krb5_krbhst_handle handle)
 {
     krb5_krbhst_info *h, *next;
@@ -904,7 +1014,7 @@
 /* backwards compatibility ahead */
=20
 static krb5_error_code
-gethostlist(krb5_context context, const char *realm,=20
+gethostlist(krb5_context context, const char *realm,
 	    unsigned int type, char ***hostlist)
 {
     krb5_error_code ret;
@@ -920,7 +1030,8 @@
     while(krb5_krbhst_next(context, handle, &hostinfo) =3D=3D 0)
 	nhost++;
     if(nhost =3D=3D 0) {
-	krb5_set_error_string(context, "No KDC found for realm %s", realm);
+	krb5_set_error_message(context, KRB5_KDC_UNREACH,
+			       N_("No KDC found for realm %s", ""), realm);
 	return KRB5_KDC_UNREACH;
     }
     *hostlist =3D calloc(nhost + 1, sizeof(**hostlist));
@@ -931,7 +1042,7 @@
=20
     krb5_krbhst_reset(context, handle);
     nhost =3D 0;
-    while(krb5_krbhst_next_as_string(context, handle,=20
+    while(krb5_krbhst_next_as_string(context, handle,
 				     host, sizeof(host)) =3D=3D 0) {
 	if(((*hostlist)[nhost++] =3D strdup(host)) =3D=3D NULL) {
 	    krb5_free_krbhst(context, *hostlist);
@@ -939,7 +1050,7 @@
 	    return ENOMEM;
 	}
     }
-    (*hostlist)[nhost++] =3D NULL;
+    (*hostlist)[nhost] =3D NULL;
     krb5_krbhst_free(context, handle);
     return 0;
 }
@@ -948,7 +1059,7 @@
  * return an malloced list of kadmin-hosts for `realm' in `hostlist'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krb_admin_hst (krb5_context context,
 			const krb5_realm *realm,
 			char ***hostlist)
@@ -960,7 +1071,7 @@
  * return an malloced list of changepw-hosts for `realm' in `hostlist'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krb_changepw_hst (krb5_context context,
 			   const krb5_realm *realm,
 			   char ***hostlist)
@@ -972,7 +1083,7 @@
  * return an malloced list of 524-hosts for `realm' in `hostlist'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krb524hst (krb5_context context,
 		    const krb5_realm *realm,
 		    char ***hostlist)
@@ -985,7 +1096,7 @@
  * return an malloced list of KDC's for `realm' in `hostlist'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_krbhst (krb5_context context,
 		 const krb5_realm *realm,
 		 char ***hostlist)
@@ -997,7 +1108,7 @@
  * free all the memory allocated in `hostlist'
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_krbhst (krb5_context context,
 		  char **hostlist)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/kuserok.c
--- a/head/crypto/heimdal/lib/krb5/kuserok.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/kuserok.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,62 +1,63 @@
 /*
- * Copyright (c) 1997 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include <dirent.h>
=20
-RCSID("$Id: kuserok.c 16048 2005-09-09 10:33:33Z lha $");
+#ifndef _WIN32
=20
 /* see if principal is mentioned in the filename access file, return
    TRUE (in result) if so, FALSE otherwise */
=20
 static krb5_error_code
-check_one_file(krb5_context context,=20
-	       const char *filename,=20
+check_one_file(krb5_context context,
+	       const char *filename,
 	       struct passwd *pwd,
-	       krb5_principal principal,=20
+	       krb5_principal principal,
 	       krb5_boolean *result)
 {
     FILE *f;
     char buf[BUFSIZ];
     krb5_error_code ret;
     struct stat st;
-   =20
+
     *result =3D FALSE;
=20
     f =3D fopen (filename, "r");
     if (f =3D=3D NULL)
 	return errno;
-   =20
+    rk_cloexec_file(f);
+
     /* check type and mode of file */
     if (fstat(fileno(f), &st) !=3D 0) {
 	fclose (f);
@@ -105,10 +106,10 @@
 }
=20
 static krb5_error_code
-check_directory(krb5_context context,=20
-		const char *dirname,=20
+check_directory(krb5_context context,
+		const char *dirname,
 		struct passwd *pwd,
-		krb5_principal principal,=20
+		krb5_principal principal,
 		krb5_boolean *result)
 {
     DIR *d;
@@ -124,16 +125,15 @@
=20
     if (!S_ISDIR(st.st_mode))
 	return ENOTDIR;
-   =20
+
     if (st.st_uid !=3D pwd->pw_uid && st.st_uid !=3D 0)
 	return EACCES;
     if ((st.st_mode & (S_IWGRP | S_IWOTH)) !=3D 0)
 	return EACCES;
=20
-    if((d =3D opendir(dirname)) =3D=3D NULL)=20
+    if((d =3D opendir(dirname)) =3D=3D NULL)
 	return errno;
=20
-#ifdef HAVE_DIRFD
     {
 	int fd;
 	struct stat st2;
@@ -148,7 +148,6 @@
 	    return EACCES;
 	}
     }
-#endif
=20
     while((dent =3D readdir(d)) !=3D NULL) {
 	if(strcmp(dent->d_name, ".") =3D=3D 0 ||
@@ -166,6 +165,8 @@
     return ret;
 }
=20
+#endif  /* !_WIN32 */
+
 static krb5_boolean
 match_local_principals(krb5_context context,
 		       krb5_principal principal,
@@ -174,7 +175,7 @@
     krb5_error_code ret;
     krb5_realm *realms, *r;
     krb5_boolean result =3D FALSE;
-   =20
+
     /* multi-component principals can never match */
     if(krb5_principal_get_comp_string(context, principal, 1) !=3D NULL)
 	return FALSE;
@@ -182,7 +183,7 @@
     ret =3D krb5_get_default_realms (context, &realms);
     if (ret)
 	return FALSE;
-=09
+
     for (r =3D realms; *r !=3D NULL; ++r) {
 	if(strcmp(krb5_principal_get_realm(context, principal),
 		  *r) !=3D 0)
@@ -198,17 +199,50 @@
 }
=20
 /**
- * Return TRUE iff `principal' is allowed to login as `luser'.
+ * This function takes the name of a local user and checks if
+ * principal is allowed to log in as that user.
+ *
+ * The user may have a ~/.k5login file listing principals that are
+ * allowed to login as that user. If that file does not exist, all
+ * principals with a first component identical to the username, and a
+ * realm considered local, are allowed access.
+ *
+ * The .k5login file must contain one principal per line, be owned by
+ * user and not be writable by group or other (but must be readable by
+ * anyone).
+ *
+ * Note that if the file exists, no implicit access rights are given
+ * to user@@LOCALREALM.
+ *
+ * Optionally, a set of files may be put in ~/.k5login.d (a
+ * directory), in which case they will all be checked in the same
+ * manner as .k5login.  The files may be called anything, but files
+ * starting with a hash (#) , or ending with a tilde (~) are
+ * ignored. Subdirectories are not traversed. Note that this directory
+ * may not be checked by other Kerberos implementations.
+ *
+ * If no configuration file exists, match user against local domains,
+ * ie luser@@LOCAL-REALMS-IN-CONFIGURATION-FILES.
+ *
+ * @param context Kerberos 5 context.
+ * @param principal principal to check if allowed to login
+ * @param luser local user id
+ *
+ * @return returns TRUE if access should be granted, FALSE otherwise.
+ *
+ * @ingroup krb5_support
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_kuserok (krb5_context context,
 	      krb5_principal principal,
 	      const char *luser)
 {
+#ifndef _WIN32
     char *buf;
     size_t buflen;
-    struct passwd *pwd;
+    struct passwd *pwd =3D NULL;
+    char *profile_dir =3D NULL;
     krb5_error_code ret;
     krb5_boolean result =3D FALSE;
=20
@@ -225,14 +259,15 @@
 #endif
     if (pwd =3D=3D NULL)
 	return FALSE;
+    profile_dir =3D pwd->pw_dir;
=20
 #define KLOGIN "/.k5login"
-    buflen =3D strlen(pwd->pw_dir) + sizeof(KLOGIN) + 2; /* 2 for .d */
+    buflen =3D strlen(profile_dir) + sizeof(KLOGIN) + 2; /* 2 for .d */
     buf =3D malloc(buflen);
     if(buf =3D=3D NULL)
 	return FALSE;
     /* check user's ~/.k5login */
-    strlcpy(buf, pwd->pw_dir, buflen);
+    strlcpy(buf, profile_dir, buflen);
     strlcat(buf, KLOGIN, buflen);
     ret =3D check_one_file(context, buf, pwd, principal, &result);
=20
@@ -241,7 +276,7 @@
 	return TRUE;
     }
=20
-    if(ret !=3D ENOENT)=20
+    if(ret !=3D ENOENT)
 	found_file =3D TRUE;
=20
     strlcat(buf, ".d", buflen);
@@ -250,7 +285,7 @@
     if(ret =3D=3D 0 && result =3D=3D TRUE)
 	return TRUE;
=20
-    if(ret !=3D ENOENT && ret !=3D ENOTDIR)=20
+    if(ret !=3D ENOENT && ret !=3D ENOTDIR)
 	found_file =3D TRUE;
=20
     /* finally if no files exist, allow all principals matching
@@ -259,4 +294,10 @@
 	return match_local_principals(context, principal, luser);
=20
     return FALSE;
+#else
+    /* The .k5login file may be on a remote profile and we don't have
+       access to the profile until we have a token handle for the
+       user's credentials. */
+    return match_local_principals(context, principal, luser);
+#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/locate_pl=
ugin.h
--- a/head/crypto/heimdal/lib/krb5/locate_plugin.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/locate_plugin.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,42 +1,42 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: locate_plugin.h 18998 2006-11-12 19:00:03Z lha $ */
+/* $Id$ */
=20
 #ifndef HEIMDAL_KRB5_LOCATE_PLUGIN_H
 #define HEIMDAL_KRB5_LOCATE_PLUGIN_H 1
=20
-#include <krb5.h>
+#define KRB5_PLUGIN_LOCATE "service_locator"
=20
 enum locate_service_type {
     locate_service_kdc =3D 1,
@@ -46,9 +46,9 @@
     locate_service_kpasswd
 };
=20
-typedef krb5_error_code=20
+typedef krb5_error_code
 (*krb5plugin_service_locate_lookup) (void *, enum locate_service_type,
-				     const char *, int, int,=20
+				     const char *, int, int,
 				     int (*)(void *,int,struct sockaddr *),
 				     void *);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/log.c
--- a/head/crypto/heimdal/lib/krb5/log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,40 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-
-RCSID("$Id: log.c 19088 2006-11-21 08:08:46Z lha $");
+#include <vis.h>
=20
 struct facility {
     int min;
@@ -114,27 +115,29 @@
     return table->val;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_initlog(krb5_context context,
 	     const char *program,
 	     krb5_log_facility **fac)
 {
     krb5_log_facility *f =3D calloc(1, sizeof(*f));
     if(f =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     f->program =3D strdup(program);
     if(f->program =3D=3D NULL){
 	free(f);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *fac =3D f;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_addlog_func(krb5_context context,
 		 krb5_log_facility *fac,
 		 int min,
@@ -145,7 +148,8 @@
 {
     struct facility *fp =3D log_realloc(fac);
     if(fp =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     fp->min =3D min;
@@ -161,17 +165,17 @@
     int priority;
 };
=20
-static void
+static void KRB5_CALLCONV
 log_syslog(const char *timestr,
 	   const char *msg,
 	   void *data)
-    =20
+
 {
     struct _heimdal_syslog_data *s =3D data;
     syslog(s->priority, "%s", msg);
 }
=20
-static void
+static void KRB5_CALLCONV
 close_syslog(void *data)
 {
     free(data);
@@ -187,7 +191,8 @@
     int i;
=20
     if(sd =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     i =3D find_value(sev, syslogvals);
@@ -210,24 +215,33 @@
     int keep_open;
 };
=20
-static void
+static void KRB5_CALLCONV
 log_file(const char *timestr,
 	 const char *msg,
 	 void *data)
 {
     struct file_data *f =3D data;
+    char *msgclean;
+    size_t len =3D strlen(msg);
     if(f->keep_open =3D=3D 0)
 	f->fd =3D fopen(f->filename, f->mode);
     if(f->fd =3D=3D NULL)
 	return;
-    fprintf(f->fd, "%s %s\n", timestr, msg);
+    /* make sure the log doesn't contain special chars */
+    msgclean =3D malloc((len + 1) * 4);
+    if (msgclean =3D=3D NULL)
+	goto out;
+    strvisx(msgclean, rk_UNCONST(msg), len, VIS_OCTAL);
+    fprintf(f->fd, "%s %s\n", timestr, msgclean);
+    free(msgclean);
+ out:
     if(f->keep_open =3D=3D 0) {
 	fclose(f->fd);
 	f->fd =3D NULL;
     }
 }
=20
-static void
+static void KRB5_CALLCONV
 close_file(void *data)
 {
     struct file_data *f =3D data;
@@ -242,7 +256,8 @@
 {
     struct file_data *fd =3D malloc(sizeof(*fd));
     if(fd =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     fd->filename =3D filename;
@@ -255,7 +270,7 @@
=20
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_addlog_dest(krb5_context context, krb5_log_facility *f, const char *o=
rig)
 {
     krb5_error_code ret =3D 0;
@@ -277,7 +292,8 @@
     if(n){
 	p =3D strchr(p, '/');
 	if(p =3D=3D NULL) {
-	    krb5_set_error_string (context, "failed to parse \"%s\"", orig);
+	    krb5_set_error_message(context, HEIM_ERR_LOG_PARSE,
+				   N_("failed to parse \"%s\"", ""), orig);
 	    return HEIM_ERR_LOG_PARSE;
 	}
 	p++;
@@ -292,25 +308,29 @@
 	int keep_open =3D 0;
 	fn =3D strdup(p + 5);
 	if(fn =3D=3D NULL) {
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
 	    return ENOMEM;
 	}
 	if(p[4] =3D=3D '=3D'){
-	    int i =3D open(fn, O_WRONLY | O_CREAT |=20
+	    int i =3D open(fn, O_WRONLY | O_CREAT |
 			 O_TRUNC | O_APPEND, 0666);
 	    if(i < 0) {
 		ret =3D errno;
-		krb5_set_error_string (context, "open(%s): %s", fn,
+		krb5_set_error_message(context, ret,
+				       N_("open(%s) logile: %s", ""), fn,
 				       strerror(ret));
 		free(fn);
 		return ret;
 	    }
+	    rk_cloexec(i);
 	    file =3D fdopen(i, "a");
 	    if(file =3D=3D NULL){
 		ret =3D errno;
 		close(i);
-		krb5_set_error_string (context, "fdopen(%s): %s", fn,
-				       strerror(ret));
+		krb5_set_error_message(context, ret,
+				       N_("fdopen(%s) logfile: %s", ""),
+				       fn, strerror(ret));
 		free(fn);
 		return ret;
 	    }
@@ -333,14 +353,15 @@
 	    strlcpy(facility, "AUTH", sizeof(facility));
 	ret =3D open_syslog(context, f, min, max, severity, facility);
     }else{
-	krb5_set_error_string (context, "unknown log type: %s", p);
 	ret =3D HEIM_ERR_LOG_PARSE; /* XXX */
+	krb5_set_error_message (context, ret,
+				N_("unknown log type: %s", ""), p);
     }
     return ret;
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_openlog(krb5_context context,
 	     const char *program,
 	     krb5_log_facility **fac)
@@ -356,15 +377,15 @@
     if(p =3D=3D NULL)
 	p =3D krb5_config_get_strings(context, NULL, "logging", "default", NULL);
     if(p){
-	for(q =3D p; *q; q++)
+	for(q =3D p; *q && ret =3D=3D 0; q++)
 	    ret =3D krb5_addlog_dest(context, *fac, *q);
 	krb5_config_free_strings(p);
     }else
 	ret =3D krb5_addlog_dest(context, *fac, "SYSLOG");
-    return 0;
+    return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_closelog(krb5_context context,
 	      krb5_log_facility *fac)
 {
@@ -383,7 +404,7 @@
 #undef __attribute__
 #define __attribute__(X)
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vlog_msg(krb5_context context,
 	      krb5_log_facility *fac,
 	      char **reply,
@@ -392,7 +413,7 @@
 	      va_list ap)
      __attribute__((format (printf, 5, 0)))
 {
-   =20
+
     char *msg =3D NULL;
     const char *actual =3D NULL;
     char buf[64];
@@ -400,15 +421,15 @@
     int i;
=20
     for(i =3D 0; fac && i < fac->len; i++)
-	if(fac->val[i].min <=3D level &&=20
+	if(fac->val[i].min <=3D level &&
 	   (fac->val[i].max < 0 || fac->val[i].max >=3D level)) {
 	    if(t =3D=3D 0) {
 		t =3D time(NULL);
 		krb5_format_time(context, t, buf, sizeof(buf), TRUE);
 	    }
 	    if(actual =3D=3D NULL) {
-		vasprintf(&msg, fmt, ap);
-		if(msg =3D=3D NULL)
+		int ret =3D vasprintf(&msg, fmt, ap);
+		if(ret < 0 || msg =3D=3D NULL)
 		    actual =3D fmt;
 		else
 		    actual =3D msg;
@@ -422,7 +443,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vlog(krb5_context context,
 	  krb5_log_facility *fac,
 	  int level,
@@ -433,7 +454,7 @@
     return krb5_vlog_msg(context, fac, NULL, level, fmt, ap);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_log_msg(krb5_context context,
 	     krb5_log_facility *fac,
 	     int level,
@@ -452,7 +473,7 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_log(krb5_context context,
 	 krb5_log_facility *fac,
 	 int level,
@@ -469,3 +490,27 @@
     return ret;
 }
=20
+void KRB5_LIB_FUNCTION
+_krb5_debug(krb5_context context,
+	    int level,
+	    const char *fmt,
+	    ...)
+    __attribute__((format (printf, 3, 4)))
+{
+    va_list ap;
+
+    if (context =3D=3D NULL || context->debug_dest =3D=3D NULL)
+	return;
+
+    va_start(ap, fmt);
+    krb5_vlog(context, context->debug_dest, level, fmt, ap);
+    va_end(ap);
+}
+
+krb5_boolean KRB5_LIB_FUNCTION
+_krb5_have_debug(krb5_context context, int level)
+{
+    if (context =3D=3D NULL || context->debug_dest =3D=3D NULL)
+	return 0 ;
+    return 1;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mcache.c
--- a/head/crypto/heimdal/lib/krb5/mcache.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/mcache.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: mcache.c 22107 2007-12-03 17:22:51Z lha $");
-
 typedef struct krb5_mcache {
     char *name;
     unsigned int refcnt;
@@ -45,6 +45,8 @@
 	struct link *next;
     } *creds;
     struct krb5_mcache *next;
+    time_t mtime;
+    krb5_deltat kdc_offset;
 } krb5_mcache;
=20
 static HEIMDAL_MUTEX mcc_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
@@ -54,26 +56,27 @@
=20
 #define MISDEAD(X)	((X)->dead)
=20
-static const char*
+static const char* KRB5_CALLCONV
 mcc_get_name(krb5_context context,
 	     krb5_ccache id)
 {
     return MCACHE(id)->name;
 }
=20
-static krb5_mcache *
+static krb5_mcache * KRB5_CALLCONV
 mcc_alloc(const char *name)
 {
     krb5_mcache *m, *m_c;
+    int ret =3D 0;
=20
     ALLOC(m, 1);
     if(m =3D=3D NULL)
 	return NULL;
     if(name =3D=3D NULL)
-	asprintf(&m->name, "%p", m);
+	ret =3D asprintf(&m->name, "%p", m);
     else
 	m->name =3D strdup(name);
-    if(m->name =3D=3D NULL) {
+    if(ret < 0 || m->name =3D=3D NULL) {
 	free(m);
 	return NULL;
     }
@@ -93,13 +96,15 @@
     m->refcnt =3D 1;
     m->primary_principal =3D NULL;
     m->creds =3D NULL;
+    m->mtime =3D time(NULL);
+    m->kdc_offset =3D 0;
     m->next =3D mcc_head;
     mcc_head =3D m;
     HEIMDAL_MUTEX_unlock(&mcc_mutex);
     return m;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_resolve(krb5_context context, krb5_ccache *id, const char *res)
 {
     krb5_mcache *m;
@@ -119,26 +124,8 @@
=20
     m =3D mcc_alloc(res);
     if (m =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
-	return KRB5_CC_NOMEM;
-    }
-   =20
-    (*id)->data.data =3D m;
-    (*id)->data.length =3D sizeof(*m);
-
-    return 0;
-}
-
-
-static krb5_error_code
-mcc_gen_new(krb5_context context, krb5_ccache *id)
-{
-    krb5_mcache *m;
-
-    m =3D mcc_alloc(NULL);
-
-    if (m =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
=20
@@ -148,13 +135,34 @@
     return 0;
 }
=20
-static krb5_error_code
+
+static krb5_error_code KRB5_CALLCONV
+mcc_gen_new(krb5_context context, krb5_ccache *id)
+{
+    krb5_mcache *m;
+
+    m =3D mcc_alloc(NULL);
+
+    if (m =3D=3D NULL) {
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
+	return KRB5_CC_NOMEM;
+    }
+
+    (*id)->data.data =3D m;
+    (*id)->data.length =3D sizeof(*m);
+
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
 mcc_initialize(krb5_context context,
 	       krb5_ccache id,
 	       krb5_principal primary_principal)
 {
     krb5_mcache *m =3D MCACHE(id);
     m->dead =3D 0;
+    m->mtime =3D time(NULL);
     return krb5_copy_principal (context,
 				primary_principal,
 				&m->primary_principal);
@@ -173,7 +181,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_close(krb5_context context,
 	  krb5_ccache id)
 {
@@ -182,7 +190,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_destroy(krb5_context context,
 	    krb5_ccache id)
 {
@@ -212,7 +220,7 @@
 	l =3D m->creds;
 	while (l !=3D NULL) {
 	    struct link *old;
-	   =20
+
 	    krb5_free_cred_contents (context, &l->cred);
 	    old =3D l;
 	    l =3D l->next;
@@ -223,7 +231,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_store_cred(krb5_context context,
 	       krb5_ccache id,
 	       krb5_creds *creds)
@@ -237,7 +245,8 @@
=20
     l =3D malloc (sizeof(*l));
     if (l =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_CC_NOMEM,
+			       N_("malloc: out of memory", ""));
 	return KRB5_CC_NOMEM;
     }
     l->next =3D m->creds;
@@ -249,10 +258,11 @@
 	free (l);
 	return ret;
     }
+    m->mtime =3D time(NULL);
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_get_principal(krb5_context context,
 		  krb5_ccache id,
 		  krb5_principal *principal)
@@ -266,7 +276,7 @@
 				principal);
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_get_first (krb5_context context,
 	       krb5_ccache id,
 	       krb5_cc_cursor *cursor)
@@ -280,7 +290,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_get_next (krb5_context context,
 	      krb5_ccache id,
 	      krb5_cc_cursor *cursor,
@@ -302,7 +312,7 @@
 	return KRB5_CC_END;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_end_get (krb5_context context,
 	     krb5_ccache id,
 	     krb5_cc_cursor *cursor)
@@ -310,7 +320,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_remove_cred(krb5_context context,
 		 krb5_ccache id,
 		 krb5_flags which,
@@ -323,34 +333,36 @@
 	    *q =3D p->next;
 	    krb5_free_cred_contents(context, &p->cred);
 	    free(p);
+	    m->mtime =3D time(NULL);
 	} else
 	    q =3D &p->next;
     }
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_set_flags(krb5_context context,
 	      krb5_ccache id,
 	      krb5_flags flags)
 {
     return 0; /* XXX */
 }
-		   =20
+
 struct mcache_iter {
     krb5_mcache *cache;
 };
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_get_cache_first(krb5_context context, krb5_cc_cursor *cursor)
 {
     struct mcache_iter *iter;
=20
     iter =3D calloc(1, sizeof(*iter));
     if (iter =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
-    }   =20
+    }
=20
     HEIMDAL_MUTEX_lock(&mcc_mutex);
     iter->cache =3D mcc_head;
@@ -362,7 +374,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_get_cache_next(krb5_context context, krb5_cc_cursor cursor, krb5_ccach=
e *id)
 {
     struct mcache_iter *iter =3D cursor;
@@ -389,7 +401,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_end_cache_get(krb5_context context, krb5_cc_cursor cursor)
 {
     struct mcache_iter *iter =3D cursor;
@@ -401,7 +413,7 @@
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_move(krb5_context context, krb5_ccache from, krb5_ccache to)
 {
     krb5_mcache *mfrom =3D MCACHE(from), *mto =3D MCACHE(to);
@@ -428,23 +440,49 @@
     mto->primary_principal =3D mfrom->primary_principal;
     mfrom->primary_principal =3D principal;
=20
+    mto->mtime =3D mfrom->mtime =3D time(NULL);
+
     HEIMDAL_MUTEX_unlock(&mcc_mutex);
     mcc_destroy(context, from);
=20
     return 0;
 }
=20
-static krb5_error_code
+static krb5_error_code KRB5_CALLCONV
 mcc_default_name(krb5_context context, char **str)
 {
     *str =3D strdup("MEMORY:");
     if (*str =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
+static krb5_error_code KRB5_CALLCONV
+mcc_lastchange(krb5_context context, krb5_ccache id, krb5_timestamp *mtime)
+{
+    *mtime =3D MCACHE(id)->mtime;
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_set_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat kdc_o=
ffset)
+{
+    krb5_mcache *m =3D MCACHE(id);
+    m->kdc_offset =3D kdc_offset;
+    return 0;
+}
+
+static krb5_error_code KRB5_CALLCONV
+mcc_get_kdc_offset(krb5_context context, krb5_ccache id, krb5_deltat *kdc_=
offset)
+{
+    krb5_mcache *m =3D MCACHE(id);
+    *kdc_offset =3D m->kdc_offset;
+    return 0;
+}
+
=20
 /**
  * Variable containing the MEMORY based credential cache implemention.
@@ -452,7 +490,8 @@
  * @ingroup krb5_ccache
  */
=20
-const krb5_cc_ops krb5_mcc_ops =3D {
+KRB5_LIB_VARIABLE const krb5_cc_ops krb5_mcc_ops =3D {
+    KRB5_CC_OPS_VERSION,
     "MEMORY",
     mcc_get_name,
     mcc_resolve,
@@ -473,5 +512,9 @@
     mcc_get_cache_next,
     mcc_end_cache_get,
     mcc_move,
-    mcc_default_name
+    mcc_default_name,
+    NULL,
+    mcc_lastchange,
+    mcc_set_kdc_offset,
+    mcc_get_kdc_offset
 };
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/misc.c
--- a/head/crypto/heimdal/lib/krb5/misc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/misc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,54 +1,55 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
+#ifdef HAVE_EXECINFO_H
+#include <execinfo.h>
+#endif
=20
-RCSID("$Id: misc.c 21174 2007-06-19 10:10:58Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_s4u2self_to_checksumdata(krb5_context context,=20
-			       const PA_S4U2Self *self,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_s4u2self_to_checksumdata(krb5_context context,
+			       const PA_S4U2Self *self,
 			       krb5_data *data)
 {
     krb5_error_code ret;
     krb5_ssize_t ssize;
     krb5_storage *sp;
     size_t size;
-    int i;
+    size_t i;
=20
     sp =3D krb5_storage_emem();
     if (sp =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ENOMEM;
     }
     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
@@ -58,20 +59,20 @@
     for (i =3D 0; i < self->name.name_string.len; i++) {
 	size =3D strlen(self->name.name_string.val[i]);
 	ssize =3D krb5_storage_write(sp, self->name.name_string.val[i], size);
-	if (ssize !=3D size) {
+	if (ssize !=3D (krb5_ssize_t)size) {
 	    ret =3D ENOMEM;
 	    goto out;
 	}
     }
     size =3D strlen(self->realm);
     ssize =3D krb5_storage_write(sp, self->realm, size);
-    if (ssize !=3D size) {
+    if (ssize !=3D (krb5_ssize_t)size) {
 	ret =3D ENOMEM;
 	goto out;
     }
     size =3D strlen(self->auth);
     ssize =3D krb5_storage_write(sp, self->auth, size);
-    if (ssize !=3D size) {
+    if (ssize !=3D (krb5_ssize_t)size) {
 	ret =3D ENOMEM;
 	goto out;
     }
@@ -81,6 +82,47 @@
     return ret;
=20
 out:
-    krb5_clear_error_string(context);
+    krb5_clear_error_message(context);
     return ret;
 }
+
+krb5_error_code
+krb5_enomem(krb5_context context)
+{
+    krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""=
));
+    return ENOMEM;
+}
+
+void
+_krb5_debug_backtrace(krb5_context context)
+{
+#if defined(HAVE_BACKTRACE) && !defined(HEIMDAL_SMALLER)
+    void *stack[128];
+    char **strs =3D NULL;
+    int i, frames =3D backtrace(stack, sizeof(stack) / sizeof(stack[0]));
+    if (frames > 0)
+	strs =3D backtrace_symbols(stack, frames);
+    if (strs) {
+	for (i =3D 0; i < frames; i++)
+	    _krb5_debug(context, 10, "frame %d: %s", i, strs[i]);
+	free(strs);
+    }
+#endif
+}
+
+krb5_error_code
+_krb5_einval(krb5_context context, const char *func, unsigned long argn)
+{
+#ifndef HEIMDAL_SMALLER
+    krb5_set_error_message(context, EINVAL,
+			   N_("programmer error: invalid argument to %s argument %lu",
+			      "function:line"),
+			   func, argn);
+    if (_krb5_have_debug(context, 10)) {
+	_krb5_debug(context, 10, "invalid argument to function %s argument %lu",
+		    func, argn);
+	_krb5_debug_backtrace(context);
+    }
+#endif
+    return EINVAL;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mit_glue.c
--- a/head/crypto/heimdal/lib/krb5/mit_glue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/mit_glue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,49 +1,50 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-RCSID("$Id: mit_glue.c 20042 2007-01-23 20:37:43Z lha $");
+
+#ifndef HEIMDAL_SMALLER
=20
 /*
  * Glue for MIT API
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_c_make_checksum(krb5_context context,=20
-		     krb5_cksumtype cksumtype,=20
-		     const krb5_keyblock *key,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_make_checksum(krb5_context context,
+		     krb5_cksumtype cksumtype,
+		     const krb5_keyblock *key,
 		     krb5_keyusage usage,
-		     const krb5_data *input,=20
+		     const krb5_data *input,
 		     krb5_checksum *cksum)
 {
     krb5_error_code ret;
@@ -60,7 +61,7 @@
     return ret ;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_verify_checksum(krb5_context context, const krb5_keyblock *key,
 		       krb5_keyusage usage, const krb5_data *data,
 		       const krb5_checksum *cksum, krb5_boolean *valid)
@@ -76,8 +77,7 @@
 	return ret;
=20
     if (data_cksum.cksumtype =3D=3D cksum->cksumtype
-	&& data_cksum.checksum.length =3D=3D cksum->checksum.length
-	&& memcmp(data_cksum.checksum.data, cksum->checksum.data, cksum->checksum=
.length) =3D=3D 0)
+	&& krb5_data_ct_cmp(&data_cksum.checksum, &cksum->checksum) =3D=3D 0)
 	*valid =3D 1;
=20
     krb5_free_checksum_contents(context, &data_cksum);
@@ -85,7 +85,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_get_checksum(krb5_context context, const krb5_checksum *cksum,
 		    krb5_cksumtype *type, krb5_data **data)
 {
@@ -108,7 +108,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_set_checksum(krb5_context context, krb5_checksum *cksum,
 		    krb5_cksumtype type, const krb5_data *data)
 {
@@ -116,51 +116,51 @@
     return der_copy_octet_string(data, &cksum->checksum);
 }
=20
-void KRB5_LIB_FUNCTION=20
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_checksum (krb5_context context, krb5_checksum *cksum)
 {
     krb5_checksum_free(context, cksum);
     free(cksum);
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_checksum_contents(krb5_context context, krb5_checksum *cksum)
 {
     krb5_checksum_free(context, cksum);
     memset(cksum, 0, sizeof(*cksum));
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_checksum_free(krb5_context context, krb5_checksum *cksum)
 {
     free_Checksum(cksum);
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_valid_enctype (krb5_enctype etype)
 {
-    return krb5_enctype_valid(NULL, etype);
+    return !krb5_enctype_valid(NULL, etype);
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_valid_cksumtype(krb5_cksumtype ctype)
 {
     return krb5_cksumtype_valid(NULL, ctype);
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_is_coll_proof_cksum(krb5_cksumtype ctype)
 {
     return krb5_checksum_is_collision_proof(NULL, ctype);
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_c_is_keyed_cksum(krb5_cksumtype ctype)
 {
     return krb5_checksum_is_keyed(NULL, ctype);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_checksum (krb5_context context,
 		    const krb5_checksum *old,
 		    krb5_checksum **new)
@@ -171,16 +171,16 @@
     return copy_Checksum(old, *new);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_checksum_length (krb5_context context, krb5_cksumtype cksumtype,
 			size_t *length)
 {
     return krb5_checksumsize(context, cksumtype, length);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_c_block_size(krb5_context context,=20
-		  krb5_enctype enctype,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_block_size(krb5_context context,
+		  krb5_enctype enctype,
 		  size_t *blocksize)
 {
     krb5_error_code ret;
@@ -201,12 +201,12 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_c_decrypt(krb5_context context,=20
-	       const krb5_keyblock key,=20
-	       krb5_keyusage usage,=20
-	       const krb5_data *ivec,=20
-	       krb5_enc_data *input,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_decrypt(krb5_context context,
+	       const krb5_keyblock key,
+	       krb5_keyusage usage,
+	       const krb5_data *ivec,
+	       krb5_enc_data *input,
 	       krb5_data *output)
 {
     krb5_error_code ret;
@@ -224,16 +224,16 @@
 	krb5_crypto_destroy(context, crypto);
 	return ret;
 	}
-=09
+
 	if (blocksize > ivec->length) {
 	    krb5_crypto_destroy(context, crypto);
 	    return KRB5_BAD_MSIZE;
 	}
     }
=20
-    ret =3D krb5_decrypt_ivec(context, crypto, usage,=20
-			    input->ciphertext.data, input->ciphertext.length,=20
-			    output,=20
+    ret =3D krb5_decrypt_ivec(context, crypto, usage,
+			    input->ciphertext.data, input->ciphertext.length,
+			    output,
 			    ivec ? ivec->data : NULL);
=20
     krb5_crypto_destroy(context, crypto);
@@ -241,11 +241,11 @@
     return ret ;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_c_encrypt(krb5_context context,=20
-	       const krb5_keyblock *key,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_encrypt(krb5_context context,
+	       const krb5_keyblock *key,
 	       krb5_keyusage usage,
-	       const krb5_data *ivec,=20
+	       const krb5_data *ivec,
 	       const krb5_data *input,
 	       krb5_enc_data *output)
 {
@@ -271,9 +271,9 @@
 	}
     }
=20
-    ret =3D krb5_encrypt_ivec(context, crypto, usage,=20
-			    input->data, input->length,=20
-			    &output->ciphertext,=20
+    ret =3D krb5_encrypt_ivec(context, crypto, usage,
+			    input->data, input->length,
+			    &output->ciphertext,
 			    ivec ? ivec->data : NULL);
     output->kvno =3D 0;
     krb5_crypto_getenctype(context, crypto, &output->enctype);
@@ -283,9 +283,9 @@
     return ret ;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_c_encrypt_length(krb5_context context,=20
-		      krb5_enctype enctype,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_encrypt_length(krb5_context context,
+		      krb5_enctype enctype,
 		      size_t inputlen,
 		      size_t *length)
 {
@@ -308,25 +308,32 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_c_enctype_compare(krb5_context context,=20
+/**
+ * Deprecated: keytypes doesn't exists, they are really enctypes.
+ *
+ * @ingroup krb5_deprecated
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_enctype_compare(krb5_context context,
 		       krb5_enctype e1,
-		       krb5_enctype e2,=20
+		       krb5_enctype e2,
 		       krb5_boolean *similar)
+    KRB5_DEPRECATED_FUNCTION("Use X instead")
 {
-    *similar =3D krb5_enctypes_compatible_keys(context, e1, e2);
+    *similar =3D (e1 =3D=3D e2);
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_make_random_key(krb5_context context,
-		       krb5_enctype enctype,=20
+		       krb5_enctype enctype,
 		       krb5_keyblock *random_key)
 {
     return krb5_generate_random_keyblock(context, enctype, random_key);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_keylengths(krb5_context context,
 		  krb5_enctype enctype,
 		  size_t *ilen,
@@ -341,7 +348,7 @@
     return krb5_enctype_keysize(context, enctype, keylen);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_prf_length(krb5_context context,
 		  krb5_enctype type,
 		  size_t *length)
@@ -349,10 +356,10 @@
     return krb5_crypto_prf_length(context, type, length);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_c_prf(krb5_context context,
 	   const krb5_keyblock *key,
-	   const krb5_data *input,=20
+	   const krb5_data *input,
 	   krb5_data *output)
 {
     krb5_crypto crypto;
@@ -367,3 +374,59 @@
=20
     return ret;
 }
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_c_random_make_octets(krb5_context context, krb5_data * data)
+{
+    return krb5_generate_random_keyblock(context, data->length, data->data=
);
+}
+
+/**
+ * MIT compat glue
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_cc_copy_creds(krb5_context context,
+		   const krb5_ccache from,
+		   krb5_ccache to)
+{
+    return krb5_cc_copy_cache(context, from, to);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getsendsubkey(krb5_context context, krb5_auth_context auth_c=
ontext,
+                            krb5_keyblock **keyblock)
+{
+    return krb5_auth_con_getlocalsubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_getrecvsubkey(krb5_context context, krb5_auth_context auth_c=
ontext,
+                            krb5_keyblock **keyblock)
+{
+    return krb5_auth_con_getremotesubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setsendsubkey(krb5_context context, krb5_auth_context auth_c=
ontext,
+                            krb5_keyblock *keyblock)
+{
+    return krb5_auth_con_setlocalsubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_auth_con_setrecvsubkey(krb5_context context, krb5_auth_context auth_c=
ontext,
+                            krb5_keyblock *keyblock)
+{
+    return krb5_auth_con_setremotesubkey(context, auth_context, keyblock);
+}
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_free_default_realm(krb5_context context, krb5_realm realm)
+{
+    return krb5_xfree(realm);
+}
+
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mk_error.c
--- a/head/crypto/heimdal/lib/krb5/mk_error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/mk_error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: mk_error.c 15457 2005-06-16 21:16:40Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_error(krb5_context context,
 	      krb5_error_code error_code,
 	      const char *e_text,
@@ -46,10 +44,11 @@
 	      int *client_usec,
 	      krb5_data *reply)
 {
+    const char *e_text2 =3D NULL;
     KRB_ERROR msg;
     krb5_timestamp sec;
     int32_t usec;
-    size_t len;
+    size_t len =3D 0;
     krb5_error_code ret =3D 0;
=20
     krb5_us_timeofday (context, &sec, &usec);
@@ -64,7 +63,7 @@
     /* Make sure we only send `protocol' error codes */
     if(error_code < KRB5KDC_ERR_NONE || error_code >=3D KRB5_ERR_RCSID) {
 	if(e_text =3D=3D NULL)
-	    e_text =3D krb5_get_err_text(context, error_code);
+	    e_text =3D e_text2 =3D krb5_get_error_message(context, error_code);
 	error_code =3D KRB5KRB_ERR_GENERIC;
     }
     msg.error_code =3D error_code - KRB5KDC_ERR_NONE;
@@ -76,7 +75,8 @@
 	msg.realm =3D server->realm;
 	msg.sname =3D server->name;
     }else{
-	msg.realm =3D "<unspecified realm>";
+	static char unspec[] =3D "<unspecified realm>";
+	msg.realm =3D unspec;
     }
     if(client){
 	msg.crealm =3D &client->realm;
@@ -84,6 +84,8 @@
     }
=20
     ASN1_MALLOC_ENCODE(KRB_ERROR, reply->data, reply->length, &msg, &len, =
ret);
+    if (e_text2)
+	krb5_free_error_message(context, e_text2);
     if (ret)
 	return ret;
     if(reply->length !=3D len)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mk_priv.c
--- a/head/crypto/heimdal/lib/krb5/mk_priv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/mk_priv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,42 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: mk_priv.c 16680 2006-02-01 12:39:26Z lha $");
-
-     =20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_priv(krb5_context context,
 	     krb5_auth_context auth_context,
 	     const krb5_data *userdata,
@@ -48,12 +45,12 @@
     EncKrbPrivPart part;
     u_char *buf =3D NULL;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     krb5_crypto crypto;
     krb5_keyblock *key;
     krb5_replay_data rdata;
=20
-    if ((auth_context->flags &=20
+    if ((auth_context->flags &
 	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
 	outdata =3D=3D NULL)
 	return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
@@ -92,7 +89,7 @@
=20
     if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_SEQUENCE)
 	outdata->seq =3D auth_context->local_seqnumber;
-   =20
+
     part.s_address =3D auth_context->local_address;
     part.r_address =3D auth_context->remote_address;
=20
@@ -114,10 +111,10 @@
 	free (buf);
 	return ret;
     }
-    ret =3D krb5_encrypt (context,=20
+    ret =3D krb5_encrypt (context,
 			crypto,
 			KRB5_KU_KRB_PRIV,
-			buf + buf_size - len,=20
+			buf + buf_size - len,
 			len,
 			&s.enc_part.cipher);
     krb5_crypto_destroy(context, crypto);
@@ -138,7 +135,8 @@
=20
     ret =3D krb5_data_copy(outbuf, buf + buf_size - len, len);
     if (ret) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	free(buf);
 	return ENOMEM;
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mk_rep.c
--- a/head/crypto/heimdal/lib/krb5/mk_rep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/mk_rep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: mk_rep.c 13863 2004-05-25 21:46:46Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_rep(krb5_context context,
 	    krb5_auth_context auth_context,
 	    krb5_data *outbuf)
@@ -45,7 +43,7 @@
     EncAPRepPart body;
     u_char *buf =3D NULL;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     krb5_crypto crypto;
=20
     ap.pvno =3D 5;
@@ -61,8 +59,6 @@
 						    auth_context,
 						    auth_context->keyblock);
 	    if(ret) {
-		krb5_set_error_string (context,
-				       "krb5_mk_rep: generating subkey");
 		free_EncAPRepPart(&body);
 		return ret;
 	    }
@@ -70,21 +66,21 @@
 	ret =3D krb5_copy_keyblock(context, auth_context->local_subkey,
 				 &body.subkey);
 	if (ret) {
-	    krb5_set_error_string (context,
-				   "krb5_copy_keyblock: out of memory");
 	    free_EncAPRepPart(&body);
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
 	    return ENOMEM;
 	}
     } else
 	body.subkey =3D NULL;
     if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
-	if(auth_context->local_seqnumber =3D=3D 0)=20
+	if(auth_context->local_seqnumber =3D=3D 0)
 	    krb5_generate_seq_number (context,
 				      auth_context->keyblock,
 				      &auth_context->local_seqnumber);
 	ALLOC(body.seq_number, 1);
 	if (body.seq_number =3D=3D NULL) {
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	    free_EncAPRepPart(&body);
 	    return ENOMEM;
 	}
@@ -101,7 +97,7 @@
 	return ret;
     if (buf_size !=3D len)
 	krb5_abortx(context, "internal error in ASN.1 encoder");
-    ret =3D krb5_crypto_init(context, auth_context->keyblock,=20
+    ret =3D krb5_crypto_init(context, auth_context->keyblock,
 			   0 /* ap.enc_part.etype */, &crypto);
     if (ret) {
 	free (buf);
@@ -110,7 +106,7 @@
     ret =3D krb5_encrypt (context,
 			crypto,
 			KRB5_KU_AP_REQ_ENC_PART,
-			buf + buf_size - len,=20
+			buf + buf_size - len,
 			len,
 			&ap.enc_part.cipher);
     krb5_crypto_destroy(context, crypto);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mk_req.c
--- a/head/crypto/heimdal/lib/krb5/mk_req.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/mk_req.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: mk_req.c 13863 2004-05-25 21:46:46Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_req_exact(krb5_context context,
 		  krb5_auth_context *auth_context,
 		  const krb5_flags ap_req_options,
@@ -50,7 +48,7 @@
     memset(&this_cred, 0, sizeof(this_cred));
=20
     ret =3D krb5_cc_get_principal(context, ccache, &this_cred.client);
- =20
+
     if(ret)
 	return ret;
=20
@@ -79,7 +77,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_req(krb5_context context,
 	    krb5_auth_context *auth_context,
 	    const krb5_flags ap_req_options,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mk_req_ex=
t.c
--- a/head/crypto/heimdal/lib/krb5/mk_req_ext.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/mk_req_ext.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
-
-RCSID("$Id: mk_req_ext.c 19511 2006-12-27 12:07:22Z lha $");
+#include "krb5_locl.h"
=20
 krb5_error_code
 _krb5_mk_req_internal(krb5_context context,
@@ -61,10 +59,10 @@
 	ret =3D krb5_auth_con_init(context, &ac);
     if(ret)
 	return ret;
-     =20
+
     if(ac->local_subkey =3D=3D NULL && (ap_req_options & AP_OPTS_USE_SUBKE=
Y)) {
 	ret =3D krb5_auth_con_generatelocalsubkey(context,
-						ac,=20
+						ac,
 						&in_creds->session);
 	if(ret)
 	    goto out;
@@ -74,7 +72,7 @@
     ret =3D krb5_copy_keyblock(context, &in_creds->session, &ac->keyblock);
     if (ret)
 	goto out;
- =20
+
     /* it's unclear what type of checksum we can use.  try the best one, e=
xcept:
      * a) if it's configured differently for the current realm, or
      * b) if the session key is des-cbc-crc
@@ -83,7 +81,7 @@
     if (in_data) {
 	if(ac->keyblock->keytype =3D=3D ETYPE_DES_CBC_CRC) {
 	    /* this is to make DCE secd (and older MIT kdcs?) happy */
-	    ret =3D krb5_create_checksum(context,=20
+	    ret =3D krb5_create_checksum(context,
 				       NULL,
 				       0,
 				       CKSUMTYPE_RSA_MD4,
@@ -94,8 +92,8 @@
 		  ac->keyblock->keytype =3D=3D ETYPE_ARCFOUR_HMAC_MD5_56 ||
 		  ac->keyblock->keytype =3D=3D ETYPE_DES_CBC_MD4 ||
 		  ac->keyblock->keytype =3D=3D ETYPE_DES_CBC_MD5) {
-	    /* this is to make MS kdc happy */=20
-	    ret =3D krb5_create_checksum(context,=20
+	    /* this is to make MS kdc happy */
+	    ret =3D krb5_create_checksum(context,
 				       NULL,
 				       0,
 				       CKSUMTYPE_RSA_MD5,
@@ -108,7 +106,7 @@
 	    ret =3D krb5_crypto_init(context, ac->keyblock, 0, &crypto);
 	    if (ret)
 		goto out;
-	    ret =3D krb5_create_checksum(context,=20
+	    ret =3D krb5_create_checksum(context,
 				       crypto,
 				       checksum_usage,
 				       0,
@@ -124,13 +122,12 @@
=20
     if (ret)
 	goto out;
- =20
-    ret =3D krb5_build_authenticator (context,
+
+    ret =3D _krb5_build_authenticator(context,
 				    ac,
 				    ac->keyblock->keytype,
 				    in_creds,
 				    c_opt,
-				    NULL,
 				    &authenticator,
 				    encrypt_usage);
     if (c_opt)
@@ -138,7 +135,7 @@
     if (ret)
 	goto out;
=20
-    ret =3D krb5_build_ap_req (context, ac->keyblock->keytype,=20
+    ret =3D krb5_build_ap_req (context, ac->keyblock->keytype,
 			     in_creds, ap_req_options, authenticator, outbuf);
 out:
     if(auth_context =3D=3D NULL)
@@ -146,7 +143,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_req_extended(krb5_context context,
 		     krb5_auth_context *auth_context,
 		     const krb5_flags ap_req_options,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/mk_safe.c
--- a/head/crypto/heimdal/lib/krb5/mk_safe.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/mk_safe.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: mk_safe.c 13863 2004-05-25 21:46:46Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_mk_safe(krb5_context context,
 	     krb5_auth_context auth_context,
 	     const krb5_data *userdata,
@@ -46,12 +44,12 @@
     KRB_SAFE s;
     u_char *buf =3D NULL;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     krb5_crypto crypto;
     krb5_keyblock *key;
     krb5_replay_data rdata;
=20
-    if ((auth_context->flags &=20
+    if ((auth_context->flags &
 	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
 	outdata =3D=3D NULL)
 	return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
@@ -79,7 +77,7 @@
 	s.safe_body.timestamp  =3D NULL;
 	s.safe_body.usec       =3D NULL;
     }
-   =20
+
     if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_TIME) {
 	outdata->timestamp =3D rdata.timestamp;
 	outdata->usec =3D rdata.usec;
@@ -88,12 +86,12 @@
     if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_SEQUENCE) {
 	rdata.seq =3D auth_context->local_seqnumber;
 	s.safe_body.seq_number =3D &rdata.seq;
-    } else=20
+    } else
 	s.safe_body.seq_number =3D NULL;
=20
     if (auth_context->flags & KRB5_AUTH_CONTEXT_RET_SEQUENCE)
 	outdata->seq =3D auth_context->local_seqnumber;
-   =20
+
     s.safe_body.s_address =3D auth_context->local_address;
     s.safe_body.r_address =3D auth_context->remote_address;
=20
@@ -111,7 +109,7 @@
 	free (buf);
 	return ret;
     }
-    ret =3D krb5_create_checksum(context,=20
+    ret =3D krb5_create_checksum(context,
 			       crypto,
 			       KRB5_KU_KRB_SAFE_CKSUM,
 			       0,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/n-fold-te=
st.c
--- a/head/crypto/heimdal/lib/krb5/n-fold-test.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/n-fold-test.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,8 +32,6 @@
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: n-fold-test.c 21745 2007-07-31 16:11:25Z lha $");
-
 enum { MAXSIZE =3D 24 };
=20
 static struct testcase {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/n-fold.c
--- a/head/crypto/heimdal/lib/krb5/n-fold.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/n-fold.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,8 +32,6 @@
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: n-fold.c 22190 2007-12-06 16:24:22Z lha $");
-
 static krb5_error_code
 rr13(unsigned char *buf, size_t len)
 {
@@ -45,7 +43,7 @@
     {
 	const int bits =3D 13 % len;
 	const int lbit =3D len % 8;
-   =20
+
 	tmp =3D malloc(bytes);
 	if (tmp =3D=3D NULL)
 	    return ENOMEM;
@@ -66,11 +64,11 @@
 	    /* byte offset and shift count */
 	    b1 =3D bb / 8;
 	    s1 =3D bb % 8;
-=09
-	    if(bb + 8 > bytes * 8)=20
+
+	    if(bb + 8 > bytes * 8)
 		/* watch for wraparound */
 		s2 =3D (len + 8 - s1) % 8;
-	    else=20
+	    else
 		s2 =3D 8 - s1;
 	    b2 =3D (b1 + 1) % bytes;
 	    buf[i] =3D (tmp[b1] << s1) | (tmp[b2] >> s2);
@@ -98,7 +96,7 @@
     }
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_n_fold(const void *str, size_t len, void *key, size_t size)
 {
     /* if len < size we need at most N * len bytes, ie < 2 * size;
@@ -108,9 +106,11 @@
     size_t l =3D 0;
     unsigned char *tmp =3D malloc(maxlen);
     unsigned char *buf =3D malloc(len);
-   =20
-    if (tmp =3D=3D NULL || buf =3D=3D NULL)=20
-	return ENOMEM;
+
+    if (tmp =3D=3D NULL || buf =3D=3D NULL) {
+        ret =3D ENOMEM;
+	goto out;
+    }
=20
     memcpy(buf, str, len);
     memset(key, 0, size);
@@ -129,9 +129,13 @@
 	}
     } while(l !=3D 0);
 out:
-    memset(buf, 0, len);
-    free(buf);
-    memset(tmp, 0, maxlen);
-    free(tmp);
+    if (buf) {
+        memset(buf, 0, len);
+	free(buf);
+    }
+    if (tmp) {
+        memset(tmp, 0, maxlen);
+	free(tmp);
+    }
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/net_read.c
--- a/head/crypto/heimdal/lib/krb5/net_read.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/net_read.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,47 +1,44 @@
 /*
- * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998, 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: net_read.c 13863 2004-05-25 21:46:46Z lha $");
-
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_net_read (krb5_context context,
 	       void *p_fd,
 	       void *buf,
 	       size_t len)
 {
-  int fd =3D *((int *)p_fd);
-
-  return net_read (fd, buf, len);
+    krb5_socket_t fd =3D *((krb5_socket_t *)p_fd);
+    return net_read(fd, buf, len);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/net_write=
.c
--- a/head/crypto/heimdal/lib/krb5/net_write.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/net_write.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,59 +1,56 @@
 /*
- * Copyright (c) 1997, 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: net_write.c 13863 2004-05-25 21:46:46Z lha $");
-
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_net_write (krb5_context context,
 		void *p_fd,
 		const void *buf,
 		size_t len)
 {
-  int fd =3D *((int *)p_fd);
-
-  return net_write (fd, buf, len);
+    krb5_socket_t fd =3D *((krb5_socket_t *)p_fd);
+    return net_write(fd, buf, len);
 }
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_net_write_block(krb5_context context,
 		     void *p_fd,
 		     const void *buf,
 		     size_t len,
 		     time_t timeout)
 {
-  int fd =3D *((int *)p_fd);
+  krb5_socket_t fd =3D *((krb5_socket_t *)p_fd);
   int ret;
   struct timeval tv, *tvp;
   const char *cbuf =3D (const char *)buf;
@@ -64,7 +61,7 @@
   do {
       FD_ZERO(&wfds);
       FD_SET(fd, &wfds);
-     =20
+
       if (timeout !=3D 0) {
 	  tv.tv_sec =3D timeout;
 	  tv.tv_usec =3D 0;
@@ -73,29 +70,45 @@
 	  tvp =3D NULL;
=20
       ret =3D select(fd + 1, NULL, &wfds, NULL, tvp);
-      if (ret < 0) {
-	  if (errno =3D=3D EINTR)
+      if (rk_IS_SOCKET_ERROR(ret)) {
+	  if (rk_SOCK_ERRNO =3D=3D EINTR)
 	      continue;
 	  return -1;
-      } else if (ret =3D=3D 0)
+      }
+
+#ifdef HAVE_WINSOCK
+      if (ret =3D=3D 0) {
+	  WSASetLastError( WSAETIMEDOUT );
 	  return 0;
-     =20
+      }
+
+      count =3D send (fd, cbuf, rem, 0);
+
+      if (rk_IS_SOCKET_ERROR(count)) {
+	  return -1;
+      }
+
+#else
+      if (ret =3D=3D 0) {
+	  return 0;
+      }
+
       if (!FD_ISSET(fd, &wfds)) {
 	  errno =3D ETIMEDOUT;
 	  return -1;
       }
=20
-#ifdef WIN32
-      count =3D send (fd, cbuf, rem, 0);
-#else
       count =3D write (fd, cbuf, rem);
-#endif
+
       if (count < 0) {
 	  if (errno =3D=3D EINTR)
 	      continue;
 	  else
 	      return count;
       }
+
+#endif
+
       cbuf +=3D count;
       rem -=3D count;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/pac.c
--- a/head/crypto/heimdal/lib/krb5/pac.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/pac.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,38 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-
-RCSID("$Id: pac.c 21934 2007-08-27 14:21:04Z lha $");
+#include <wind.h>
=20
 struct PAC_INFO_BUFFER {
     uint32_t type;
@@ -44,7 +43,7 @@
=20
 struct PACTYPE {
     uint32_t numbuffers;
-    uint32_t version;                        =20
+    uint32_t version;
     struct PAC_INFO_BUFFER buffers[1];
 };
=20
@@ -69,7 +68,7 @@
 #define CHECK(r,f,l)						\
 	do {							\
 		if (((r) =3D f ) !=3D 0) {				\
-			krb5_clear_error_string(context);	\
+			krb5_clear_error_message(context);	\
 			goto l;					\
 		}						\
 	} while(0)
@@ -77,10 +76,47 @@
 static const char zeros[PAC_ALIGNMENT] =3D { 0 };
=20
 /*
+ * HMAC-MD5 checksum over any key (needed for the PAC routines)
+ */
+
+static krb5_error_code
+HMAC_MD5_any_checksum(krb5_context context,
+		      const krb5_keyblock *key,
+		      const void *data,
+		      size_t len,
+		      unsigned usage,
+		      Checksum *result)
+{
+    struct _krb5_key_data local_key;
+    krb5_error_code ret;
+
+    memset(&local_key, 0, sizeof(local_key));
+
+    ret =3D krb5_copy_keyblock(context, key, &local_key.key);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_data_alloc (&result->checksum, 16);
+    if (ret) {
+	krb5_free_keyblock(context, local_key.key);
+	return ret;
+    }
+
+    result->cksumtype =3D CKSUMTYPE_HMAC_MD5;
+    ret =3D _krb5_HMAC_MD5_checksum(context, &local_key, data, len, usage,=
 result);
+    if (ret)
+	krb5_data_free(&result->checksum);
+
+    krb5_free_keyblock(context, local_key.key);
+    return ret;
+}
+
+
+/*
  *
  */
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_parse(krb5_context context, const void *ptr, size_t len,
 	       krb5_pac *pac)
 {
@@ -91,15 +127,13 @@
=20
     p =3D calloc(1, sizeof(*p));
     if (p =3D=3D NULL) {
-	ret =3D ENOMEM;
-	krb5_set_error_string(context, "out of memory");
+	ret =3D krb5_enomem(context);
 	goto out;
     }
=20
     sp =3D krb5_storage_from_readonly_mem(ptr, len);
     if (sp =3D=3D NULL) {
-	ret =3D ENOMEM;
-	krb5_set_error_string(context, "out of memory");
+	ret =3D krb5_enomem(context);
 	goto out;
     }
     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
@@ -107,21 +141,22 @@
     CHECK(ret, krb5_ret_uint32(sp, &tmp), out);
     CHECK(ret, krb5_ret_uint32(sp, &tmp2), out);
     if (tmp < 1) {
-	krb5_set_error_string(context, "PAC have too few buffer");
 	ret =3D EINVAL; /* Too few buffers */
+	krb5_set_error_message(context, ret, N_("PAC have too few buffer", ""));
 	goto out;
     }
     if (tmp2 !=3D 0) {
-	krb5_set_error_string(context, "PAC have wrong version");
 	ret =3D EINVAL; /* Wrong version */
+	krb5_set_error_message(context, ret,
+			       N_("PAC have wrong version %d", ""),
+			       (int)tmp2);
 	goto out;
     }
=20
-    p->pac =3D calloc(1,=20
+    p->pac =3D calloc(1,
 		    sizeof(*p->pac) + (sizeof(p->pac->buffers[0]) * (tmp - 1)));
     if (p->pac =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	ret =3D ENOMEM;
+	ret =3D krb5_enomem(context);
 	goto out;
     }
=20
@@ -142,51 +177,59 @@
=20
 	/* consistency checks */
 	if (p->pac->buffers[i].offset_lo & (PAC_ALIGNMENT - 1)) {
-	    krb5_set_error_string(context, "PAC out of allignment");
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret,
+				   N_("PAC out of allignment", ""));
 	    goto out;
 	}
 	if (p->pac->buffers[i].offset_hi) {
-	    krb5_set_error_string(context, "PAC high offset set");
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret,
+				   N_("PAC high offset set", ""));
 	    goto out;
 	}
 	if (p->pac->buffers[i].offset_lo > len) {
-	    krb5_set_error_string(context, "PAC offset off end");
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret,
+				   N_("PAC offset off end", ""));
 	    goto out;
 	}
 	if (p->pac->buffers[i].offset_lo < header_end) {
-	    krb5_set_error_string(context, "PAC offset inside header: %d %d",
-				  p->pac->buffers[i].offset_lo, header_end);
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret,
+				   N_("PAC offset inside header: %lu %lu", ""),
+				   (unsigned long)p->pac->buffers[i].offset_lo,
+				   (unsigned long)header_end);
 	    goto out;
 	}
 	if (p->pac->buffers[i].buffersize > len - p->pac->buffers[i].offset_lo){
-	    krb5_set_error_string(context, "PAC length off end");
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret, N_("PAC length off end", ""));
 	    goto out;
 	}
=20
 	/* let save pointer to data we need later */
 	if (p->pac->buffers[i].type =3D=3D PAC_SERVER_CHECKSUM) {
 	    if (p->server_checksum) {
-		krb5_set_error_string(context, "PAC have two server checksums");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       N_("PAC have two server checksums", ""));
 		goto out;
 	    }
 	    p->server_checksum =3D &p->pac->buffers[i];
 	} else if (p->pac->buffers[i].type =3D=3D PAC_PRIVSVR_CHECKSUM) {
 	    if (p->privsvr_checksum) {
-		krb5_set_error_string(context, "PAC have two KDC checksums");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       N_("PAC have two KDC checksums", ""));
 		goto out;
 	    }
 	    p->privsvr_checksum =3D &p->pac->buffers[i];
 	} else if (p->pac->buffers[i].type =3D=3D PAC_LOGON_NAME) {
 	    if (p->logon_name) {
-		krb5_set_error_string(context, "PAC have two logon names");
 		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       N_("PAC have two logon names", ""));
 		goto out;
 	    }
 	    p->logon_name =3D &p->pac->buffers[i];
@@ -215,7 +258,7 @@
     return ret;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_init(krb5_context context, krb5_pac *pac)
 {
     krb5_error_code ret;
@@ -223,31 +266,27 @@
=20
     p =3D calloc(1, sizeof(*p));
     if (p =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
+	return krb5_enomem(context);
     }
=20
     p->pac =3D calloc(1, sizeof(*p->pac));
     if (p->pac =3D=3D NULL) {
 	free(p);
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
+	return krb5_enomem(context);
     }
=20
     ret =3D krb5_data_alloc(&p->data, PACTYPE_SIZE);
     if (ret) {
 	free (p->pac);
 	free(p);
-	krb5_set_error_string(context, "out of memory");
-	return ret;
+	return krb5_enomem(context);
     }
=20
-
     *pac =3D p;
     return 0;
 }
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_add_buffer(krb5_context context, krb5_pac p,
 		    uint32_t type, const krb5_data *data)
 {
@@ -260,10 +299,9 @@
=20
     ptr =3D realloc(p->pac,
 		  sizeof(*p->pac) + (sizeof(p->pac->buffers[0]) * len));
-    if (ptr =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
-    }
+    if (ptr =3D=3D NULL)
+	return krb5_enomem(context);
+
     p->pac =3D ptr;
=20
     for (i =3D 0; i < len; i++)
@@ -279,20 +317,20 @@
     old_end =3D p->data.length;
     len =3D p->data.length + data->length + PAC_INFO_BUFFER_SIZE;
     if (len < p->data.length) {
-	krb5_set_error_string(context, "integer overrun");
+	krb5_set_error_message(context, EINVAL, "integer overrun");
 	return EINVAL;
     }
-   =20
+
     /* align to PAC_ALIGNMENT */
     len =3D ((len + PAC_ALIGNMENT - 1) / PAC_ALIGNMENT) * PAC_ALIGNMENT;
=20
     ret =3D krb5_data_realloc(&p->data, len);
     if (ret) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	return ret;
     }
=20
-    /*=20
+    /*
      * make place for new PAC INFO BUFFER header
      */
     header_end =3D PACTYPE_SIZE + (PAC_INFO_BUFFER_SIZE * p->pac->numbuffe=
rs);
@@ -315,43 +353,43 @@
     return 0;
 }
=20
-krb5_error_code
+/**
+ * Get the PAC buffer of specific type from the pac.
+ *
+ * @param context Kerberos 5 context.
+ * @param p the pac structure returned by krb5_pac_parse().
+ * @param type type of buffer to get
+ * @param data return data, free with krb5_data_free().
+ *
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5_pac
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_get_buffer(krb5_context context, krb5_pac p,
 		    uint32_t type, krb5_data *data)
 {
     krb5_error_code ret;
     uint32_t i;
=20
-    /*
-     * Hide the checksums from external consumers
-     */
-
-    if (type =3D=3D PAC_PRIVSVR_CHECKSUM || type =3D=3D PAC_SERVER_CHECKSU=
M) {
-	ret =3D krb5_data_alloc(data, 16);
-	if (ret) {
-	    krb5_set_error_string(context, "out of memory");
-	    return ret;
-	}
-	memset(data->data, 0, data->length);
-	return 0;
-    }
-
     for (i =3D 0; i < p->pac->numbuffers; i++) {
-	size_t len =3D p->pac->buffers[i].buffersize;
-	size_t offset =3D p->pac->buffers[i].offset_lo;
+	const size_t len =3D p->pac->buffers[i].buffersize;
+	const size_t offset =3D p->pac->buffers[i].offset_lo;
=20
 	if (p->pac->buffers[i].type !=3D type)
 	    continue;
=20
 	ret =3D krb5_data_copy(data, (unsigned char *)p->data.data + offset, len);
 	if (ret) {
-	    krb5_set_error_string(context, "Out of memory");
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	    return ret;
 	}
 	return 0;
     }
-    krb5_set_error_string(context, "No PAC buffer of type %lu was found",
-			  (unsigned long)type);
+    krb5_set_error_message(context, ENOENT, "No PAC buffer of type %lu was=
 found",
+			   (unsigned long)type);
     return ENOENT;
 }
=20
@@ -359,7 +397,7 @@
  *
  */
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_pac_get_types(krb5_context context,
 		   krb5_pac p,
 		   size_t *len,
@@ -370,8 +408,7 @@
     *types =3D calloc(p->pac->numbuffers, sizeof(*types));
     if (*types =3D=3D NULL) {
 	*len =3D 0;
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
+	return krb5_enomem(context);
     }
     for (i =3D 0; i < p->pac->numbuffers; i++)
 	(*types)[i] =3D p->pac->buffers[i].type;
@@ -384,7 +421,7 @@
  *
  */
=20
-void
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_pac_free(krb5_context context, krb5_pac pac)
 {
     krb5_data_free(&pac->data);
@@ -403,7 +440,6 @@
 		void *ptr, size_t len,
 		const krb5_keyblock *key)
 {
-    krb5_crypto crypto =3D NULL;
     krb5_storage *sp =3D NULL;
     uint32_t type;
     krb5_error_code ret;
@@ -413,44 +449,71 @@
=20
     sp =3D krb5_storage_from_mem((char *)data->data + sig->offset_lo,
 			       sig->buffersize);
-    if (sp =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
-    }
+    if (sp =3D=3D NULL)
+	return krb5_enomem(context);
+
     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
=20
     CHECK(ret, krb5_ret_uint32(sp, &type), out);
     cksum.cksumtype =3D type;
-    cksum.checksum.length =3D=20
+    cksum.checksum.length =3D
 	sig->buffersize - krb5_storage_seek(sp, 0, SEEK_CUR);
     cksum.checksum.data =3D malloc(cksum.checksum.length);
     if (cksum.checksum.data =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	ret =3D ENOMEM;
+	ret =3D krb5_enomem(context);
 	goto out;
     }
     ret =3D krb5_storage_read(sp, cksum.checksum.data, cksum.checksum.leng=
th);
-    if (ret !=3D cksum.checksum.length) {
-	krb5_set_error_string(context, "PAC checksum missing checksum");
+    if (ret !=3D (int)cksum.checksum.length) {
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret, "PAC checksum missing checksum");
 	goto out;
     }
=20
     if (!krb5_checksum_is_keyed(context, cksum.cksumtype)) {
-	krb5_set_error_string (context, "Checksum type %d not keyed",
+	ret =3D EINVAL;
+	krb5_set_error_message(context, ret, "Checksum type %d not keyed",
 			       cksum.cksumtype);
-	ret =3D EINVAL;
 	goto out;
     }
=20
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret)
-	goto out;
+    /* If the checksum is HMAC-MD5, the checksum type is not tied to
+     * the key type, instead the HMAC-MD5 checksum is applied blindly
+     * on whatever key is used for this connection, avoiding issues
+     * with unkeyed checksums on des-cbc-md5 and des-cbc-crc.  See
+     * http://comments.gmane.org/gmane.comp.encryption.kerberos.devel/8743
+     * for the same issue in MIT, and
+     * http://blogs.msdn.com/b/openspecification/archive/2010/01/01/verify=
ing-the-server-signature-in-kerberos-privilege-account-certificate.aspx
+     * for Microsoft's explaination */
=20
-    ret =3D krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM,
-			       ptr, len, &cksum);
+    if (cksum.cksumtype =3D=3D CKSUMTYPE_HMAC_MD5) {
+	Checksum local_checksum;
+
+	memset(&local_checksum, 0, sizeof(local_checksum));
+
+	ret =3D HMAC_MD5_any_checksum(context, key, ptr, len,
+				    KRB5_KU_OTHER_CKSUM, &local_checksum);
+
+	if (ret !=3D 0 || krb5_data_ct_cmp(&local_checksum.checksum, &cksum.check=
sum) !=3D 0) {
+	    ret =3D KRB5KRB_AP_ERR_BAD_INTEGRITY;
+	    krb5_set_error_message(context, ret,
+				   N_("PAC integrity check failed for "
+				      "hmac-md5 checksum", ""));
+	}
+	krb5_data_free(&local_checksum.checksum);
+
+   } else {
+	krb5_crypto crypto =3D NULL;
+
+	ret =3D krb5_crypto_init(context, key, 0, &crypto);
+	if (ret)
+		goto out;
+
+	ret =3D krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM,
+				   ptr, len, &cksum);
+	krb5_crypto_destroy(context, crypto);
+    }
     free(cksum.checksum.data);
-    krb5_crypto_destroy(context, crypto);
     krb5_storage_free(sp);
=20
     return ret;
@@ -460,14 +523,13 @@
 	free(cksum.checksum.data);
     if (sp)
 	krb5_storage_free(sp);
-    if (crypto)
-	krb5_crypto_destroy(context, crypto);
     return ret;
 }
=20
 static krb5_error_code
 create_checksum(krb5_context context,
 		const krb5_keyblock *key,
+		uint32_t cksumtype,
 		void *data, size_t datalen,
 		void *sig, size_t siglen)
 {
@@ -475,18 +537,31 @@
     krb5_error_code ret;
     Checksum cksum;
=20
-    ret =3D krb5_crypto_init(context, key, 0, &crypto);
-    if (ret)
-	return ret;
+    /* If the checksum is HMAC-MD5, the checksum type is not tied to
+     * the key type, instead the HMAC-MD5 checksum is applied blindly
+     * on whatever key is used for this connection, avoiding issues
+     * with unkeyed checksums on des-cbc-md5 and des-cbc-crc.  See
+     * http://comments.gmane.org/gmane.comp.encryption.kerberos.devel/8743
+     * for the same issue in MIT, and
+     * http://blogs.msdn.com/b/openspecification/archive/2010/01/01/verify=
ing-the-server-signature-in-kerberos-privilege-account-certificate.aspx
+     * for Microsoft's explaination */
=20
-    ret =3D krb5_create_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, 0,
-			       data, datalen, &cksum);
-    krb5_crypto_destroy(context, crypto);
-    if (ret)
-	return ret;
+    if (cksumtype =3D=3D (uint32_t)CKSUMTYPE_HMAC_MD5) {
+	ret =3D HMAC_MD5_any_checksum(context, key, data, datalen,
+				    KRB5_KU_OTHER_CKSUM, &cksum);
+    } else {
+	ret =3D krb5_crypto_init(context, key, 0, &crypto);
+	if (ret)
+	    return ret;
=20
+	ret =3D krb5_create_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, 0,
+				   data, datalen, &cksum);
+	krb5_crypto_destroy(context, crypto);
+	if (ret)
+	    return ret;
+    }
     if (cksum.checksum.length !=3D siglen) {
-	krb5_set_error_string(context, "pac checksum wrong length");
+	krb5_set_error_message(context, EINVAL, "pac checksum wrong length");
 	free_Checksum(&cksum);
 	return EINVAL;
     }
@@ -528,10 +603,8 @@
=20
     sp =3D krb5_storage_from_readonly_mem((const char *)data->data + logon=
_name->offset_lo,
 					logon_name->buffersize);
-    if (sp =3D=3D NULL) {
-	krb5_set_error_string(context, "Out of memory");
-	return ENOMEM;
-    }
+    if (sp =3D=3D NULL)
+	return krb5_enomem(context);
=20
     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
=20
@@ -544,79 +617,74 @@
 	t2 =3D ((uint64_t)time2 << 32) | time1;
 	if (t1 !=3D t2) {
 	    krb5_storage_free(sp);
-	    krb5_set_error_string(context, "PAC timestamp mismatch");
+	    krb5_set_error_message(context, EINVAL, "PAC timestamp mismatch");
 	    return EINVAL;
 	}
     }
     CHECK(ret, krb5_ret_uint16(sp, &len), out);
     if (len =3D=3D 0) {
 	krb5_storage_free(sp);
-	krb5_set_error_string(context, "PAC logon name length missing");
+	krb5_set_error_message(context, EINVAL, "PAC logon name length missing");
 	return EINVAL;
     }
=20
     s =3D malloc(len);
     if (s =3D=3D NULL) {
 	krb5_storage_free(sp);
-	krb5_set_error_string(context, "Out of memory");
-	return ENOMEM;
+	return krb5_enomem(context);
     }
     ret =3D krb5_storage_read(sp, s, len);
     if (ret !=3D len) {
 	krb5_storage_free(sp);
-	krb5_set_error_string(context, "Failed to read pac logon name");
+	krb5_set_error_message(context, EINVAL, "Failed to read PAC logon name");
 	return EINVAL;
     }
     krb5_storage_free(sp);
-#if 1 /* cheat for now */
     {
-	size_t i;
+	size_t ucs2len =3D len / 2;
+	uint16_t *ucs2;
+	size_t u8len;
+	unsigned int flags =3D WIND_RW_LE;
=20
-	if (len & 1) {
-	    krb5_set_error_string(context, "PAC logon name malformed");
-	    return EINVAL;
+	ucs2 =3D malloc(sizeof(ucs2[0]) * ucs2len);
+	if (ucs2 =3D=3D NULL)
+	    return krb5_enomem(context);
+
+	ret =3D wind_ucs2read(s, len, &flags, ucs2, &ucs2len);
+	free(s);
+	if (ret) {
+	    free(ucs2);
+	    krb5_set_error_message(context, ret, "Failed to convert string to UCS=
-2");
+	    return ret;
 	}
-
-	for (i =3D 0; i < len / 2; i++) {
-	    if (s[(i * 2) + 1]) {
-		krb5_set_error_string(context, "PAC logon name not ASCII");
-		return EINVAL;
-	    }
-	    s[i] =3D s[i * 2];
+	ret =3D wind_ucs2utf8_length(ucs2, ucs2len, &u8len);
+	if (ret) {
+	    free(ucs2);
+	    krb5_set_error_message(context, ret, "Failed to count length of UCS-2=
 string");
+	    return ret;
 	}
-	s[i] =3D '\0';
+	u8len +=3D 1; /* Add space for NUL */
+	s =3D malloc(u8len);
+	if (s =3D=3D NULL) {
+	    free(ucs2);
+	    return krb5_enomem(context);
+	}
+	ret =3D wind_ucs2utf8(ucs2, ucs2len, s, &u8len);
+	free(ucs2);
+	if (ret) {
+	    free(s);
+	    krb5_set_error_message(context, ret, "Failed to convert to UTF-8");
+	    return ret;
+	}
     }
-#else
-    {
-	uint16_t *ucs2;
-	ssize_t ucs2len;
-	size_t u8len;
-
-	ucs2 =3D malloc(sizeof(ucs2[0]) * len / 2);
-	if (ucs2)
-	    abort();
-	ucs2len =3D wind_ucs2read(s, len / 2, ucs2);
-	free(s);
-	if (len < 0)
-	    return -1;
-	ret =3D wind_ucs2toutf8(ucs2, ucs2len, NULL, &u8len);
-	if (ret < 0)
-	    abort();
-	s =3D malloc(u8len + 1);
-	if (s =3D=3D NULL)
-	    abort();
-	wind_ucs2toutf8(ucs2, ucs2len, s, &u8len);
-	free(ucs2);
-    }
-#endif
     ret =3D krb5_parse_name_flags(context, s, KRB5_PRINCIPAL_PARSE_NO_REAL=
M, &p2);
     free(s);
     if (ret)
 	return ret;
-   =20
+
     if (krb5_principal_compare_any_realm(context, principal, p2) !=3D TRUE=
) {
-	krb5_set_error_string(context, "PAC logon name mismatch");
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret, "PAC logon name mismatch");
     }
     krb5_free_principal(context, p2);
     return ret;
@@ -629,26 +697,25 @@
  */
=20
 static krb5_error_code
-build_logon_name(krb5_context context,=20
+build_logon_name(krb5_context context,
 		 time_t authtime,
-		 krb5_const_principal principal,=20
+		 krb5_const_principal principal,
 		 krb5_data *logon)
 {
     krb5_error_code ret;
     krb5_storage *sp;
     uint64_t t;
     char *s, *s2;
-    size_t i, len;
+    size_t s2_len;
=20
     t =3D unix2nttime(authtime);
=20
     krb5_data_zero(logon);
=20
     sp =3D krb5_storage_emem();
-    if (sp =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
-    }
+    if (sp =3D=3D NULL)
+	return krb5_enomem(context);
+
     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
=20
     CHECK(ret, krb5_store_uint32(sp, t & 0xffffffff), out);
@@ -659,30 +726,61 @@
     if (ret)
 	goto out;
=20
-    len =3D strlen(s);
-   =20
-    CHECK(ret, krb5_store_uint16(sp, len * 2), out);
+    {
+	size_t ucs2_len;
+	uint16_t *ucs2;
+	unsigned int flags;
=20
-#if 1 /* cheat for now */
-    s2 =3D malloc(len * 2);
-    if (s2 =3D=3D NULL) {
-	ret =3D ENOMEM;
+	ret =3D wind_utf8ucs2_length(s, &ucs2_len);
+	if (ret) {
+	    free(s);
+	    krb5_set_error_message(context, ret, "Failed to count length of UTF-8=
 string");
+	    return ret;
+	}
+
+	ucs2 =3D malloc(sizeof(ucs2[0]) * ucs2_len);
+	if (ucs2 =3D=3D NULL) {
+	    free(s);
+	    return krb5_enomem(context);
+	}
+
+	ret =3D wind_utf8ucs2(s, ucs2, &ucs2_len);
 	free(s);
-	goto out;
+	if (ret) {
+	    free(ucs2);
+	    krb5_set_error_message(context, ret, "Failed to convert string to UCS=
-2");
+	    return ret;
+	}
+
+	s2_len =3D (ucs2_len + 1) * 2;
+	s2 =3D malloc(s2_len);
+	if (ucs2 =3D=3D NULL) {
+	    free(ucs2);
+	    return krb5_enomem(context);
+	}
+
+	flags =3D WIND_RW_LE;
+	ret =3D wind_ucs2write(ucs2, ucs2_len,
+			     &flags, s2, &s2_len);
+	free(ucs2);
+	if (ret) {
+	    free(s2);
+	    krb5_set_error_message(context, ret, "Failed to write to UCS-2 buffer=
");
+	    return ret;
+	}
+
+	/*
+	 * we do not want zero termination
+	 */
+	s2_len =3D ucs2_len * 2;
     }
-    for (i =3D 0; i < len; i++) {
-	s2[i * 2] =3D s[i];
-	s2[i * 2 + 1] =3D 0;
-    }
-    free(s);
-#else
-    /* write libwind code here */
-#endif
=20
-    ret =3D krb5_storage_write(sp, s2, len * 2);
+    CHECK(ret, krb5_store_uint16(sp, s2_len), out);
+
+    ret =3D krb5_storage_write(sp, s2, s2_len);
     free(s2);
-    if (ret !=3D len * 2) {
-	ret =3D ENOMEM;
+    if (ret !=3D (int)s2_len) {
+	ret =3D krb5_enomem(context);
 	goto out;
     }
     ret =3D krb5_storage_to_data(sp, logon);
@@ -697,12 +795,24 @@
 }
=20
=20
-/*
+/**
+ * Verify the PAC.
  *
+ * @param context Kerberos 5 context.
+ * @param pac the pac structure returned by krb5_pac_parse().
+ * @param authtime The time of the ticket the PAC belongs to.
+ * @param principal the principal to verify.
+ * @param server The service key, most always be given.
+ * @param privsvr The KDC key, may be given.
+
+ * @return Returns 0 to indicate success. Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5_pac
  */
=20
-krb5_error_code
-krb5_pac_verify(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_pac_verify(krb5_context context,
 		const krb5_pac pac,
 		time_t authtime,
 		krb5_const_principal principal,
@@ -712,19 +822,19 @@
     krb5_error_code ret;
=20
     if (pac->server_checksum =3D=3D NULL) {
-	krb5_set_error_string(context, "PAC missing server checksum");
+	krb5_set_error_message(context, EINVAL, "PAC missing server checksum");
 	return EINVAL;
     }
     if (pac->privsvr_checksum =3D=3D NULL) {
-	krb5_set_error_string(context, "PAC missing kdc checksum");
+	krb5_set_error_message(context, EINVAL, "PAC missing kdc checksum");
 	return EINVAL;
     }
     if (pac->logon_name =3D=3D NULL) {
-	krb5_set_error_string(context, "PAC missing logon name");
+	krb5_set_error_message(context, EINVAL, "PAC missing logon name");
 	return EINVAL;
     }
=20
-    ret =3D verify_logonname(context,=20
+    ret =3D verify_logonname(context,
 			   pac->logon_name,
 			   &pac->data,
 			   authtime,
@@ -732,7 +842,7 @@
     if (ret)
 	return ret;
=20
-    /*=20
+    /*
      * in the service case, clean out data option of the privsvr and
      * server checksum before checking the checksum.
      */
@@ -767,6 +877,7 @@
 	    return ret;
     }
     if (privsvr) {
+	/* The priv checksum covers the server checksum */
 	ret =3D verify_checksum(context,
 			      pac->privsvr_checksum,
 			      &pac->data,
@@ -796,17 +907,16 @@
 	if (l > sizeof(zeros))
 	    l =3D sizeof(zeros);
 	sret =3D krb5_storage_write(sp, zeros, l);
-	if (sret <=3D 0) {
-	    krb5_set_error_string(context, "out of memory");
-	    return ENOMEM;
-	}
+	if (sret <=3D 0)
+	    return krb5_enomem(context);
+
 	len -=3D sret;
     }
     return 0;
 }
=20
 static krb5_error_code
-pac_checksum(krb5_context context,=20
+pac_checksum(krb5_context context,
 	     const krb5_keyblock *key,
 	     uint32_t *cksumtype,
 	     size_t *cksumsize)
@@ -820,19 +930,19 @@
 	return ret;
=20
     ret =3D krb5_crypto_get_checksum_type(context, crypto, &cktype);
-    ret =3D krb5_crypto_destroy(context, crypto);
+    krb5_crypto_destroy(context, crypto);
     if (ret)
 	return ret;
=20
     if (krb5_checksum_is_keyed(context, cktype) =3D=3D FALSE) {
-	krb5_set_error_string(context, "PAC checksum type is not keyed");
-	return EINVAL;
+	*cksumtype =3D CKSUMTYPE_HMAC_MD5;
+	*cksumsize =3D 16;
     }
=20
     ret =3D krb5_checksumsize(context, cktype, cksumsize);
     if (ret)
 	return ret;
-   =20
+
     *cksumtype =3D (uint32_t)cktype;
=20
     return 0;
@@ -853,7 +963,8 @@
     size_t server_size, priv_size;
     uint32_t server_offset =3D 0, priv_offset =3D 0;
     uint32_t server_cksumtype =3D 0, priv_cksumtype =3D 0;
-    int i, num =3D 0;
+    int num =3D 0;
+    size_t i;
     krb5_data logon, d;
=20
     krb5_data_zero(&logon);
@@ -869,10 +980,9 @@
 	void *ptr;
=20
 	ptr =3D realloc(p->pac, sizeof(*p->pac) + (sizeof(p->pac->buffers[0]) * (=
p->pac->numbuffers + num - 1)));
-	if (ptr =3D=3D NULL) {
-	    krb5_set_error_string(context, "out of memory");
-	    return ENOMEM;
-	}
+	if (ptr =3D=3D NULL)
+	    return krb5_enomem(context);
+
 	p->pac =3D ptr;
=20
 	if (p->logon_name =3D=3D NULL) {
@@ -907,17 +1017,15 @@
=20
     /* Encode PAC */
     sp =3D krb5_storage_emem();
-    if (sp =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
-    }
+    if (sp =3D=3D NULL)
+	return krb5_enomem(context);
+
     krb5_storage_set_flags(sp, KRB5_STORAGE_BYTEORDER_LE);
=20
     spdata =3D krb5_storage_emem();
     if (spdata =3D=3D NULL) {
 	krb5_storage_free(sp);
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
+	return krb5_enomem(context);
     }
     krb5_storage_set_flags(spdata, KRB5_STORAGE_BYTEORDER_LE);
=20
@@ -955,8 +1063,7 @@
=20
 	    sret =3D krb5_storage_write(spdata, ptr, len);
 	    if (sret !=3D len) {
-		krb5_set_error_string(context, "out of memory");
-		ret =3D ENOMEM;
+		ret =3D krb5_enomem(context);
 		goto out;
 	    }
 	    /* XXX if not aligned, fill_zeros */
@@ -974,7 +1081,7 @@
=20
 	    end +=3D len;
 	    e =3D ((end + PAC_ALIGNMENT - 1) / PAC_ALIGNMENT) * PAC_ALIGNMENT;
-	    if (end !=3D e) {
+	    if ((int32_t)end !=3D e) {
 		CHECK(ret, fill_zeros(context, spdata, e - end), out);
 	    }
 	    end =3D e;
@@ -987,35 +1094,32 @@
     /* export PAC */
     ret =3D krb5_storage_to_data(spdata, &d);
     if (ret) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto out;
     }
     ret =3D krb5_storage_write(sp, d.data, d.length);
-    if (ret !=3D d.length) {
+    if (ret !=3D (int)d.length) {
 	krb5_data_free(&d);
-	krb5_set_error_string(context, "out of memory");
-	ret =3D ENOMEM;
+	ret =3D krb5_enomem(context);
 	goto out;
     }
     krb5_data_free(&d);
=20
     ret =3D krb5_storage_to_data(sp, &d);
     if (ret) {
-	krb5_set_error_string(context, "out of memory");
+	ret =3D krb5_enomem(context);
 	goto out;
     }
=20
     /* sign */
-
-    ret =3D create_checksum(context, server_key,
+    ret =3D create_checksum(context, server_key, server_cksumtype,
 			  d.data, d.length,
 			  (char *)d.data + server_offset, server_size);
     if (ret) {
 	krb5_data_free(&d);
 	goto out;
     }
-
-    ret =3D create_checksum(context, priv_key,
+    ret =3D create_checksum(context, priv_key, priv_cksumtype,
 			  (char *)d.data + server_offset, server_size,
 			  (char *)d.data + priv_offset, priv_size);
     if (ret) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/padata.c
--- a/head/crypto/heimdal/lib/krb5/padata.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/padata.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,50 +1,48 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: padata.c 15469 2005-06-17 04:28:35Z lha $");
-
-PA_DATA *
+KRB5_LIB_FUNCTION PA_DATA * KRB5_LIB_CALL
 krb5_find_padata(PA_DATA *val, unsigned len, int type, int *idx)
 {
-    for(; *idx < len; (*idx)++)
-	if(val[*idx].padata_type =3D=3D type)
+    for(; *idx < (int)len; (*idx)++)
+	if(val[*idx].padata_type =3D=3D (unsigned)type)
 	    return val + *idx;
-    return NULL;   =20
+    return NULL;
 }
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_padata_add(krb5_context context, METHOD_DATA *md,
 		int type, void *buf, size_t len)
 {
@@ -52,7 +50,8 @@
=20
     pa =3D realloc (md->val, (md->len + 1) * sizeof(*md->val));
     if (pa =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     md->val =3D pa;
@@ -60,7 +59,7 @@
     pa[md->len].padata_type =3D type;
     pa[md->len].padata_value.length =3D len;
     pa[md->len].padata_value.data =3D buf;
-    md->len++;   =20
+    md->len++;
=20
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/parse-nam=
e-test.c
--- a/head/crypto/heimdal/lib/krb5/parse-name-test.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/krb5/parse-name-test.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: parse-name-test.c 16342 2005-12-02 14:14:43Z lha $");
-
 enum { MAX_COMPONENTS =3D 3 };
=20
 static struct testcase {
@@ -63,7 +61,7 @@
     {"a/b/c", "a/b/c@", "", 3, {"a", "b", "c"}, FALSE},
     {NULL, NULL, "", 0, { NULL }, FALSE}};
=20
-int KRB5_LIB_FUNCTION
+int
 main(int argc, char **argv)
 {
     struct testcase *t;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/pkinit.c
--- a/head/crypto/heimdal/lib/krb5/pkinit.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/pkinit.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 2003 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: pkinit.c 22433 2008-01-13 14:11:46Z lha $");
-
 struct krb5_dh_moduli {
     char *name;
     unsigned long bits;
@@ -45,8 +45,6 @@
=20
 #ifdef PKINIT
=20
-#include <heim_asn1.h>
-#include <rfc2459_asn1.h>
 #include <cms_asn1.h>
 #include <pkcs8_asn1.h>
 #include <pkcs9_asn1.h>
@@ -56,53 +54,44 @@
=20
 #include <der.h>
=20
-#include <hx509.h>
-
-enum {
-    COMPAT_WIN2K =3D 1,
-    COMPAT_IETF =3D 2
-};
-
-struct krb5_pk_identity {
-    hx509_context hx509ctx;
-    hx509_verify_ctx verify_ctx;
-    hx509_certs certs;
-    hx509_certs anchors;
-    hx509_certs certpool;
-    hx509_revoke_ctx revokectx;
-};
-
 struct krb5_pk_cert {
     hx509_cert cert;
 };
=20
 struct krb5_pk_init_ctx_data {
     struct krb5_pk_identity *id;
-    DH *dh;
+    enum { USE_RSA, USE_DH, USE_ECDH } keyex;
+    union {
+	DH *dh;
+#ifdef HAVE_OPENSSL
+	EC_KEY *eckey;
+#endif
+    } u;
     krb5_data *clientDHNonce;
     struct krb5_dh_moduli **m;
     hx509_peer_info peer;
-    int type;
+    enum krb5_pk_type type;
     unsigned int require_binding:1;
     unsigned int require_eku:1;
     unsigned int require_krbtgt_otherName:1;
     unsigned int require_hostname_match:1;
     unsigned int trustedCertifiers:1;
+    unsigned int anonymous:1;
 };
=20
 static void
-_krb5_pk_copy_error(krb5_context context,
-		    hx509_context hx509ctx,
-		    int hxret,
-		    const char *fmt,
-		    ...)
+pk_copy_error(krb5_context context,
+	      hx509_context hx509ctx,
+	      int hxret,
+	      const char *fmt,
+	      ...)
     __attribute__ ((format (printf, 4, 5)));
=20
 /*
  *
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 _krb5_pk_cert_free(struct krb5_pk_cert *cert)
 {
     if (cert->cert) {
@@ -117,7 +106,7 @@
     integer->length =3D BN_num_bytes(bn);
     integer->data =3D malloc(integer->length);
     if (integer->data =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ENOMEM;
     }
     BN_bn2bin(bn, integer->data);
@@ -132,60 +121,136 @@
=20
     bn =3D BN_bin2bn((const unsigned char *)f->data, f->length, NULL);
     if (bn =3D=3D NULL) {
-	krb5_set_error_string(context, "PKINIT: parsing BN failed %s", field);
+	krb5_set_error_message(context, ENOMEM,
+			       N_("PKINIT: parsing BN failed %s", ""), field);
 	return NULL;
     }
     BN_set_negative(bn, f->negative);
     return bn;
 }
=20
+static krb5_error_code
+select_dh_group(krb5_context context, DH *dh, unsigned long bits,
+		struct krb5_dh_moduli **moduli)
+{
+    const struct krb5_dh_moduli *m;
+
+    if (bits =3D=3D 0) {
+	m =3D moduli[1]; /* XXX */
+	if (m =3D=3D NULL)
+	    m =3D moduli[0]; /* XXX */
+    } else {
+	int i;
+	for (i =3D 0; moduli[i] !=3D NULL; i++) {
+	    if (bits < moduli[i]->bits)
+		break;
+	}
+	if (moduli[i] =3D=3D NULL) {
+	    krb5_set_error_message(context, EINVAL,
+				   N_("Did not find a DH group parameter "
+				      "matching requirement of %lu bits", ""),
+				   bits);
+	    return EINVAL;
+	}
+	m =3D moduli[i];
+    }
+
+    dh->p =3D integer_to_BN(context, "p", &m->p);
+    if (dh->p =3D=3D NULL)
+	return ENOMEM;
+    dh->g =3D integer_to_BN(context, "g", &m->g);
+    if (dh->g =3D=3D NULL)
+	return ENOMEM;
+    dh->q =3D integer_to_BN(context, "q", &m->q);
+    if (dh->q =3D=3D NULL)
+	return ENOMEM;
+
+    return 0;
+}
+
+struct certfind {
+    const char *type;
+    const heim_oid *oid;
+};
+
+/*
+ * Try searchin the key by to use by first looking for for PK-INIT
+ * EKU, then the Microsoft smart card EKU and last, no special EKU at all.
+ */
=20
 static krb5_error_code
-_krb5_pk_create_sign(krb5_context context,
-		     const heim_oid *eContentType,
-		     krb5_data *eContent,
-		     struct krb5_pk_identity *id,
-		     hx509_peer_info peer,
-		     krb5_data *sd_data)
+find_cert(krb5_context context, struct krb5_pk_identity *id,
+	  hx509_query *q, hx509_cert *cert)
 {
-    hx509_cert cert;
-    hx509_query *q;
-    int ret;
+    struct certfind cf[4] =3D {
+	{ "MobileMe EKU" },
+	{ "PKINIT EKU" },
+	{ "MS EKU" },
+	{ "any (or no)" }
+    };
+    int ret =3D HX509_CERT_NOT_FOUND;
+    size_t i, start =3D 1;
+    unsigned oids[] =3D { 1, 2, 840, 113635, 100, 3, 2, 1 };
+    const heim_oid mobileMe =3D { sizeof(oids)/sizeof(oids[0]), oids };
=20
-    ret =3D hx509_query_alloc(id->hx509ctx, &q);
-    if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,=20
-			    "Allocate query to find signing certificate");
-	return ret;
+
+    if (id->flags & PKINIT_BTMM)
+	start =3D 0;
+
+    cf[0].oid =3D &mobileMe;
+    cf[1].oid =3D &asn1_oid_id_pkekuoid;
+    cf[2].oid =3D &asn1_oid_id_pkinit_ms_eku;
+    cf[3].oid =3D NULL;
+
+    for (i =3D start; i < sizeof(cf)/sizeof(cf[0]); i++) {
+	ret =3D hx509_query_match_eku(q, cf[i].oid);
+	if (ret) {
+	    pk_copy_error(context, context->hx509ctx, ret,
+			  "Failed setting %s OID", cf[i].type);
+	    return ret;
+	}
+
+	ret =3D hx509_certs_find(context->hx509ctx, id->certs, q, cert);
+	if (ret =3D=3D 0)
+	    break;
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed finding certificate with %s OID", cf[i].type);
     }
+    return ret;
+}
=20
-    hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
-    hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
=20
-    ret =3D hx509_certs_find(id->hx509ctx, id->certs, q, &cert);
-    hx509_query_free(id->hx509ctx, q);
-    if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,=20
-			    "Find certificate to signed CMS data");
-	return ret;
-    }
+static krb5_error_code
+create_signature(krb5_context context,
+		 const heim_oid *eContentType,
+		 krb5_data *eContent,
+		 struct krb5_pk_identity *id,
+		 hx509_peer_info peer,
+		 krb5_data *sd_data)
+{
+    int ret, flags =3D 0;
=20
-    ret =3D hx509_cms_create_signed_1(id->hx509ctx,
-				    0,
+    if (id->cert =3D=3D NULL)
+	flags |=3D HX509_CMS_SIGNATURE_NO_SIGNER;
+
+    ret =3D hx509_cms_create_signed_1(context->hx509ctx,
+				    flags,
 				    eContentType,
 				    eContent->data,
 				    eContent->length,
 				    NULL,
-				    cert,
+				    id->cert,
 				    peer,
 				    NULL,
 				    id->certs,
 				    sd_data);
-    if (ret)
-	_krb5_pk_copy_error(context, id->hx509ctx, ret, "create CMS signedData");
-    hx509_cert_free(cert);
+    if (ret) {
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Create CMS signedData");
+	return ret;
+    }
=20
-    return ret;
+    return 0;
 }
=20
 static int
@@ -197,6 +262,9 @@
     void *p;
     int ret;
=20
+    if (ids->len > 10)
+	return 0;
+
     memset(&id, 0, sizeof(id));
=20
     ret =3D hx509_cert_get_subject(c, &subject);
@@ -211,7 +279,7 @@
 	    free_ExternalPrincipalIdentifier(&id);
 	    return ENOMEM;
 	}
-   =20
+
 	ret =3D hx509_name_binary(subject, id.subjectName);
 	if (ret) {
 	    hx509_name_free(&subject);
@@ -231,8 +299,8 @@
     {
 	IssuerAndSerialNumber iasn;
 	hx509_name issuer;
-	size_t size;
-=09
+	size_t size =3D 0;
+
 	memset(&iasn, 0, sizeof(iasn));
=20
 	ret =3D hx509_cert_get_issuer(c, &issuer);
@@ -247,7 +315,7 @@
 	    free_ExternalPrincipalIdentifier(&id);
 	    return ret;
 	}
-=09
+
 	ret =3D hx509_cert_get_serialnumber(c, &iasn.serialNumber);
 	if (ret) {
 	    free_IssuerAndSerialNumber(&iasn);
@@ -256,7 +324,7 @@
 	}
=20
 	ASN1_MALLOC_ENCODE(IssuerAndSerialNumber,
-			   id.issuerAndSerialNumber->data,=20
+			   id.issuerAndSerialNumber->data,
 			   id.issuerAndSerialNumber->length,
 			   &iasn, &size, ret);
 	free_IssuerAndSerialNumber(&iasn);
@@ -268,7 +336,7 @@
=20
     id.subjectKeyIdentifier =3D NULL;
=20
-    p =3D realloc(ids->val, sizeof(ids->val[0]) * (ids->len + 1));=20
+    p =3D realloc(ids->val, sizeof(ids->val[0]) * (ids->len + 1));
     if (p =3D=3D NULL) {
 	free_ExternalPrincipalIdentifier(&id);
 	return ENOMEM;
@@ -287,25 +355,24 @@
 	  hx509_certs certs,
 	  ExternalPrincipalIdentifiers *ids)
 {
-    return hx509_certs_iter(hx509ctx, certs, cert2epi, ids);
+    return hx509_certs_iter_f(hx509ctx, certs, cert2epi, ids);
 }
=20
 static krb5_error_code
 build_auth_pack(krb5_context context,
 		unsigned nonce,
 		krb5_pk_init_ctx ctx,
-		DH *dh,
 		const KDC_REQ_BODY *body,
 		AuthPack *a)
 {
-    size_t buf_size, len;
+    size_t buf_size, len =3D 0;
     krb5_error_code ret;
     void *buf;
     krb5_timestamp sec;
     int32_t usec;
     Checksum checksum;
=20
-    krb5_clear_error_string(context);
+    krb5_clear_error_message(context);
=20
     memset(&checksum, 0, sizeof(checksum));
=20
@@ -327,12 +394,13 @@
 			       len,
 			       &checksum);
     free(buf);
-    if (ret)=20
+    if (ret)
 	return ret;
=20
     ALLOC(a->pkAuthenticator.paChecksum, 1);
     if (a->pkAuthenticator.paChecksum =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -342,25 +410,62 @@
     if (ret)
 	return ret;
=20
-    if (dh) {
-	DomainParameters dp;
-	heim_integer dh_pub_key;
+    if (ctx->keyex =3D=3D USE_DH || ctx->keyex =3D=3D USE_ECDH) {
+	const char *moduli_file;
+	unsigned long dh_min_bits;
 	krb5_data dhbuf;
-	size_t size;
+	size_t size =3D 0;
+
+	krb5_data_zero(&dhbuf);
+
+
+
+	moduli_file =3D krb5_config_get_string(context, NULL,
+					     "libdefaults",
+					     "moduli",
+					     NULL);
+
+	dh_min_bits =3D
+	    krb5_config_get_int_default(context, NULL, 0,
+					"libdefaults",
+					"pkinit_dh_min_bits",
+					NULL);
+
+	ret =3D _krb5_parse_moduli(context, moduli_file, &ctx->m);
+	if (ret)
+	    return ret;
+
+	ctx->u.dh =3D DH_new();
+	if (ctx->u.dh =3D=3D NULL) {
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
+	    return ENOMEM;
+	}
+
+	ret =3D select_dh_group(context, ctx->u.dh, dh_min_bits, ctx->m);
+	if (ret)
+	    return ret;
+
+	if (DH_generate_key(ctx->u.dh) !=3D 1) {
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("pkinit: failed to generate DH key", ""));
+	    return ENOMEM;
+	}
+
=20
 	if (1 /* support_cached_dh */) {
 	    ALLOC(a->clientDHNonce, 1);
 	    if (a->clientDHNonce =3D=3D NULL) {
-		krb5_clear_error_string(context);
+		krb5_clear_error_message(context);
 		return ENOMEM;
 	    }
 	    ret =3D krb5_data_alloc(a->clientDHNonce, 40);
 	    if (a->clientDHNonce =3D=3D NULL) {
-		krb5_clear_error_string(context);
-		return ENOMEM;
+		krb5_clear_error_message(context);
+		return ret;
 	    }
-	    memset(a->clientDHNonce->data, 0, a->clientDHNonce->length);
-	    ret =3D krb5_copy_data(context, a->clientDHNonce,=20
+	    RAND_bytes(a->clientDHNonce->data, a->clientDHNonce->length);
+	    ret =3D krb5_copy_data(context, a->clientDHNonce,
 				 &ctx->clientDHNonce);
 	    if (ret)
 		return ret;
@@ -369,60 +474,131 @@
 	ALLOC(a->clientPublicValue, 1);
 	if (a->clientPublicValue =3D=3D NULL)
 	    return ENOMEM;
-	ret =3D der_copy_oid(oid_id_dhpublicnumber(),
-			   &a->clientPublicValue->algorithm.algorithm);
-	if (ret)
-	    return ret;
-=09
-	memset(&dp, 0, sizeof(dp));
=20
-	ret =3D BN_to_integer(context, dh->p, &dp.p);
-	if (ret) {
+	if (ctx->keyex =3D=3D USE_DH) {
+	    DH *dh =3D ctx->u.dh;
+	    DomainParameters dp;
+	    heim_integer dh_pub_key;
+
+	    ret =3D der_copy_oid(&asn1_oid_id_dhpublicnumber,
+			       &a->clientPublicValue->algorithm.algorithm);
+	    if (ret)
+		return ret;
+
+	    memset(&dp, 0, sizeof(dp));
+
+	    ret =3D BN_to_integer(context, dh->p, &dp.p);
+	    if (ret) {
+		free_DomainParameters(&dp);
+		return ret;
+	    }
+	    ret =3D BN_to_integer(context, dh->g, &dp.g);
+	    if (ret) {
+		free_DomainParameters(&dp);
+		return ret;
+	    }
+	    ret =3D BN_to_integer(context, dh->q, &dp.q);
+	    if (ret) {
+		free_DomainParameters(&dp);
+		return ret;
+	    }
+	    dp.j =3D NULL;
+	    dp.validationParms =3D NULL;
+
+	    a->clientPublicValue->algorithm.parameters =3D
+		malloc(sizeof(*a->clientPublicValue->algorithm.parameters));
+	    if (a->clientPublicValue->algorithm.parameters =3D=3D NULL) {
+		free_DomainParameters(&dp);
+		return ret;
+	    }
+
+	    ASN1_MALLOC_ENCODE(DomainParameters,
+			       a->clientPublicValue->algorithm.parameters->data,
+			       a->clientPublicValue->algorithm.parameters->length,
+			       &dp, &size, ret);
 	    free_DomainParameters(&dp);
-	    return ret;
-	}
-	ret =3D BN_to_integer(context, dh->g, &dp.g);
-	if (ret) {
-	    free_DomainParameters(&dp);
-	    return ret;
-	}
-	ret =3D BN_to_integer(context, dh->q, &dp.q);
-	if (ret) {
-	    free_DomainParameters(&dp);
-	    return ret;
-	}
-	dp.j =3D NULL;
-	dp.validationParms =3D NULL;
+	    if (ret)
+		return ret;
+	    if (size !=3D a->clientPublicValue->algorithm.parameters->length)
+		krb5_abortx(context, "Internal ASN1 encoder error");
=20
-	a->clientPublicValue->algorithm.parameters =3D=20
-	    malloc(sizeof(*a->clientPublicValue->algorithm.parameters));
-	if (a->clientPublicValue->algorithm.parameters =3D=3D NULL) {
-	    free_DomainParameters(&dp);
-	    return ret;
-	}
+	    ret =3D BN_to_integer(context, dh->pub_key, &dh_pub_key);
+	    if (ret)
+		return ret;
=20
-	ASN1_MALLOC_ENCODE(DomainParameters,
-			   a->clientPublicValue->algorithm.parameters->data,
-			   a->clientPublicValue->algorithm.parameters->length,
-			   &dp, &size, ret);
-	free_DomainParameters(&dp);
-	if (ret)
-	    return ret;
-	if (size !=3D a->clientPublicValue->algorithm.parameters->length)
-	    krb5_abortx(context, "Internal ASN1 encoder error");
+	    ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length,
+			       &dh_pub_key, &size, ret);
+	    der_free_heim_integer(&dh_pub_key);
+	    if (ret)
+		return ret;
+	    if (size !=3D dhbuf.length)
+		krb5_abortx(context, "asn1 internal error");
+	} else if (ctx->keyex =3D=3D USE_ECDH) {
+#ifdef HAVE_OPENSSL
+	    ECParameters ecp;
+	    unsigned char *p;
+	    int xlen;
=20
-	ret =3D BN_to_integer(context, dh->pub_key, &dh_pub_key);
-	if (ret)
-	    return ret;
+	    /* copy in public key, XXX find the best curve that the server suppor=
t or use the clients curve if possible */
=20
-	ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length,
-			   &dh_pub_key, &size, ret);
-	der_free_heim_integer(&dh_pub_key);
-	if (ret)
-	    return ret;
-	if (size !=3D dhbuf.length)
-	    krb5_abortx(context, "asn1 internal error");
+	    ecp.element =3D choice_ECParameters_namedCurve;
+	    ret =3D der_copy_oid(&asn1_oid_id_ec_group_secp256r1,
+			       &ecp.u.namedCurve);
+	    if (ret)
+		return ret;
=20
+	    ALLOC(a->clientPublicValue->algorithm.parameters, 1);
+	    if (a->clientPublicValue->algorithm.parameters =3D=3D NULL) {
+		free_ECParameters(&ecp);
+		return ENOMEM;
+	    }
+	    ASN1_MALLOC_ENCODE(ECParameters, p, xlen, &ecp, &size, ret);
+	    free_ECParameters(&ecp);
+	    if (ret)
+		return ret;
+	    if ((int)size !=3D xlen)
+		krb5_abortx(context, "asn1 internal error");
+
+	    a->clientPublicValue->algorithm.parameters->data =3D p;
+	    a->clientPublicValue->algorithm.parameters->length =3D size;
+
+	    /* copy in public key */
+
+	    ret =3D der_copy_oid(&asn1_oid_id_ecPublicKey,
+			       &a->clientPublicValue->algorithm.algorithm);
+	    if (ret)
+		return ret;
+
+	    ctx->u.eckey =3D EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
+	    if (ctx->u.eckey =3D=3D NULL)
+		return ENOMEM;
+
+	    ret =3D EC_KEY_generate_key(ctx->u.eckey);
+	    if (ret !=3D 1)
+		return EINVAL;
+
+	    /* encode onto dhkey */
+
+	    xlen =3D i2o_ECPublicKey(ctx->u.eckey, NULL);
+	    if (xlen <=3D 0)
+		abort();
+
+	    dhbuf.data =3D malloc(xlen);
+	    if (dhbuf.data =3D=3D NULL)
+		abort();
+	    dhbuf.length =3D xlen;
+	    p =3D dhbuf.data;
+
+	    xlen =3D i2o_ECPublicKey(ctx->u.eckey, &p);
+	    if (xlen <=3D 0)
+		abort();
+
+	    /* XXX verify that this is right with RFC3279 */
+#else
+	    return EINVAL;
+#endif
+	} else
+	    krb5_abortx(context, "internal error");
 	a->clientPublicValue->subjectPublicKey.length =3D dhbuf.length * 8;
 	a->clientPublicValue->subjectPublicKey.data =3D dhbuf.data;
     }
@@ -432,7 +608,8 @@
 	if (a->supportedCMSTypes =3D=3D NULL)
 	    return ENOMEM;
=20
-	ret =3D hx509_crypto_available(ctx->id->hx509ctx, HX509_SELECT_ALL, NULL,
+	ret =3D hx509_crypto_available(context->hx509ctx, HX509_SELECT_ALL,
+				     ctx->id->cert,
 				     &a->supportedCMSTypes->val,
 				     &a->supportedCMSTypes->len);
 	if (ret)
@@ -442,9 +619,9 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_mk_ContentInfo(krb5_context context,
-			const krb5_data *buf,=20
+			const krb5_data *buf,
 			const heim_oid *oid,
 			struct ContentInfo *content_info)
 {
@@ -473,16 +650,16 @@
 {
     struct ContentInfo content_info;
     krb5_error_code ret;
-    const heim_oid *oid;
-    size_t size;
+    const heim_oid *oid =3D NULL;
+    size_t size =3D 0;
     krb5_data buf, sd_buf;
-    int pa_type;
+    int pa_type =3D -1;
=20
     krb5_data_zero(&buf);
     krb5_data_zero(&sd_buf);
     memset(&content_info, 0, sizeof(content_info));
=20
-    if (ctx->type =3D=3D COMPAT_WIN2K) {
+    if (ctx->type =3D=3D PKINIT_WIN2K) {
 	AuthPack_Win2k ap;
 	krb5_timestamp sec;
 	int32_t usec;
@@ -493,13 +670,13 @@
 	ret =3D copy_PrincipalName(req_body->sname, &ap.pkAuthenticator.kdcName);
 	if (ret) {
 	    free_AuthPack_Win2k(&ap);
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
 	ret =3D copy_Realm(&req_body->realm, &ap.pkAuthenticator.kdcRealm);
 	if (ret) {
 	    free_AuthPack_Win2k(&ap);
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    goto out;
 	}
=20
@@ -512,19 +689,21 @@
 			   &ap, &size, ret);
 	free_AuthPack_Win2k(&ap);
 	if (ret) {
-	    krb5_set_error_string(context, "AuthPack_Win2k: %d", ret);
+	    krb5_set_error_message(context, ret,
+				   N_("Failed encoding AuthPackWin: %d", ""),
+				   (int)ret);
 	    goto out;
 	}
 	if (buf.length !=3D size)
 	    krb5_abortx(context, "internal ASN1 encoder error");
=20
-	oid =3D oid_id_pkcs7_data();
-    } else if (ctx->type =3D=3D COMPAT_IETF) {
+	oid =3D &asn1_oid_id_pkcs7_data;
+    } else if (ctx->type =3D=3D PKINIT_27) {
 	AuthPack ap;
-=09
+
 	memset(&ap, 0, sizeof(ap));
=20
-	ret =3D build_auth_pack(context, nonce, ctx, ctx->dh, req_body, &ap);
+	ret =3D build_auth_pack(context, nonce, ctx, req_body, &ap);
 	if (ret) {
 	    free_AuthPack(&ap);
 	    goto out;
@@ -533,35 +712,33 @@
 	ASN1_MALLOC_ENCODE(AuthPack, buf.data, buf.length, &ap, &size, ret);
 	free_AuthPack(&ap);
 	if (ret) {
-	    krb5_set_error_string(context, "AuthPack: %d", ret);
+	    krb5_set_error_message(context, ret,
+				   N_("Failed encoding AuthPack: %d", ""),
+				   (int)ret);
 	    goto out;
 	}
 	if (buf.length !=3D size)
 	    krb5_abortx(context, "internal ASN1 encoder error");
=20
-	oid =3D oid_id_pkauthdata();
+	oid =3D &asn1_oid_id_pkauthdata;
     } else
 	krb5_abortx(context, "internal pkinit error");
=20
-    ret =3D _krb5_pk_create_sign(context,
-			       oid,
-			       &buf,
-			       ctx->id,
-			       ctx->peer,
-			       &sd_buf);
+    ret =3D create_signature(context, oid, &buf, ctx->id,
+			   ctx->peer, &sd_buf);
     krb5_data_free(&buf);
     if (ret)
 	goto out;
=20
-    ret =3D hx509_cms_wrap_ContentInfo(oid_id_pkcs7_signedData(), &sd_buf,=
 &buf);
+    ret =3D hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &sd_=
buf, &buf);
     krb5_data_free(&sd_buf);
     if (ret) {
-	krb5_set_error_string(context,
-			      "ContentInfo wrapping of signedData failed");
+	krb5_set_error_message(context, ret,
+			       N_("ContentInfo wrapping of signedData failed",""));
 	goto out;
     }
=20
-    if (ctx->type =3D=3D COMPAT_WIN2K) {
+    if (ctx->type =3D=3D PKINIT_WIN2K) {
 	PA_PK_AS_REQ_Win2k winreq;
=20
 	pa_type =3D KRB5_PADATA_PK_AS_REQ_WIN;
@@ -574,26 +751,30 @@
 			   &winreq, &size, ret);
 	free_PA_PK_AS_REQ_Win2k(&winreq);
=20
-    } else if (ctx->type =3D=3D COMPAT_IETF) {
+    } else if (ctx->type =3D=3D PKINIT_27) {
 	PA_PK_AS_REQ req;
=20
 	pa_type =3D KRB5_PADATA_PK_AS_REQ;
=20
 	memset(&req, 0, sizeof(req));
-	req.signedAuthPack =3D buf;=09
+	req.signedAuthPack =3D buf;
=20
 	if (ctx->trustedCertifiers) {
=20
 	    req.trustedCertifiers =3D calloc(1, sizeof(*req.trustedCertifiers));
 	    if (req.trustedCertifiers =3D=3D NULL) {
-		krb5_set_error_string(context, "malloc: out of memory");
+		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret,
+				       N_("malloc: out of memory", ""));
 		free_PA_PK_AS_REQ(&req);
 		goto out;
 	    }
-	    ret =3D build_edi(context, ctx->id->hx509ctx,=20
+	    ret =3D build_edi(context, context->hx509ctx,
 			    ctx->id->anchors, req.trustedCertifiers);
 	    if (ret) {
-		krb5_set_error_string(context, "pk-init: failed to build trustedCertifie=
rs");
+		krb5_set_error_message(context, ret,
+				       N_("pk-init: failed to build "
+					  "trustedCertifiers", ""));
 		free_PA_PK_AS_REQ(&req);
 		goto out;
 	    }
@@ -608,7 +789,7 @@
     } else
 	krb5_abortx(context, "internal pkinit error");
     if (ret) {
-	krb5_set_error_string(context, "PA-PK-AS-REQ %d", ret);
+	krb5_set_error_message(context, ret, "PA-PK-AS-REQ %d", (int)ret);
 	goto out;
     }
     if (buf.length !=3D size)
@@ -618,19 +799,21 @@
     if (ret)
 	free(buf.data);
=20
-    if (ret =3D=3D 0 && ctx->type =3D=3D COMPAT_WIN2K)
-	krb5_padata_add(context, md, KRB5_PADATA_PK_AS_09_BINDING, NULL, 0);
+    if (ret =3D=3D 0)
+    	krb5_padata_add(context, md, KRB5_PADATA_PK_AS_09_BINDING, NULL, 0);
=20
-out:
+ out:
     free_ContentInfo(&content_info);
=20
     return ret;
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_mk_padata(krb5_context context,
 		   void *c,
+		   int ic_flags,
+		   int win2k,
 		   const KDC_REQ_BODY *req_body,
 		   unsigned nonce,
 		   METHOD_DATA *md)
@@ -638,33 +821,44 @@
     krb5_pk_init_ctx ctx =3D c;
     int win2k_compat;
=20
+    if (ctx->id->certs =3D=3D NULL && ctx->anonymous =3D=3D 0) {
+	krb5_set_error_message(context, HEIM_PKINIT_NO_PRIVATE_KEY,
+			       N_("PKINIT: No user certificate given", ""));
+	return HEIM_PKINIT_NO_PRIVATE_KEY;
+    }
+
     win2k_compat =3D krb5_config_get_bool_default(context, NULL,
-						FALSE,
+						win2k,
 						"realms",
 						req_body->realm,
 						"pkinit_win2k",
 						NULL);
=20
     if (win2k_compat) {
-	ctx->require_binding =3D=20
+	ctx->require_binding =3D
 	    krb5_config_get_bool_default(context, NULL,
-					 FALSE,
+					 TRUE,
 					 "realms",
 					 req_body->realm,
 					 "pkinit_win2k_require_binding",
 					 NULL);
-	ctx->type =3D COMPAT_WIN2K;
+	ctx->type =3D PKINIT_WIN2K;
     } else
-	ctx->type =3D COMPAT_IETF;
+	ctx->type =3D PKINIT_27;
=20
-    ctx->require_eku =3D=20
+    ctx->require_eku =3D
 	krb5_config_get_bool_default(context, NULL,
 				     TRUE,
 				     "realms",
 				     req_body->realm,
 				     "pkinit_require_eku",
 				     NULL);
-    ctx->require_krbtgt_otherName =3D=20
+    if (ic_flags & KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK)
+	ctx->require_eku =3D 0;
+    if (ctx->id->flags & PKINIT_BTMM)
+	ctx->require_eku =3D 0;
+
+    ctx->require_krbtgt_otherName =3D
 	krb5_config_get_bool_default(context, NULL,
 				     TRUE,
 				     "realms",
@@ -672,7 +866,7 @@
 				     "pkinit_require_krbtgt_otherName",
 				     NULL);
=20
-    ctx->require_hostname_match =3D=20
+    ctx->require_hostname_match =3D
 	krb5_config_get_bool_default(context, NULL,
 				     FALSE,
 				     "realms",
@@ -680,7 +874,7 @@
 				     "pkinit_require_hostname_match",
 				     NULL);
=20
-    ctx->trustedCertifiers =3D=20
+    ctx->trustedCertifiers =3D
 	krb5_config_get_bool_default(context, NULL,
 				     TRUE,
 				     "realms",
@@ -691,22 +885,30 @@
     return pk_mk_padata(context, ctx, req_body, nonce, md);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_pk_verify_sign(krb5_context context,
-		     const void *data,
-		     size_t length,
-		     struct krb5_pk_identity *id,
-		     heim_oid *contentType,
-		     krb5_data *content,
-		     struct krb5_pk_cert **signer)
+static krb5_error_code
+pk_verify_sign(krb5_context context,
+	       const void *data,
+	       size_t length,
+	       struct krb5_pk_identity *id,
+	       heim_oid *contentType,
+	       krb5_data *content,
+	       struct krb5_pk_cert **signer)
 {
     hx509_certs signer_certs;
-    int ret;
+    int ret, flags =3D 0;
+
+    /* BTMM is broken in Leo and SnowLeo */
+    if (id->flags & PKINIT_BTMM) {
+	flags |=3D HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH;
+	flags |=3D HX509_CMS_VS_NO_KU_CHECK;
+	flags |=3D HX509_CMS_VS_NO_VALIDATE;
+    }
=20
     *signer =3D NULL;
=20
-    ret =3D hx509_cms_verify_signed(id->hx509ctx,
+    ret =3D hx509_cms_verify_signed(context->hx509ctx,
 				  id->verify_ctx,
+				  flags,
 				  data,
 				  length,
 				  NULL,
@@ -715,26 +917,26 @@
 				  content,
 				  &signer_certs);
     if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,
-			    "CMS verify signed failed");
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "CMS verify signed failed");
 	return ret;
     }
=20
     *signer =3D calloc(1, sizeof(**signer));
     if (*signer =3D=3D NULL) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	ret =3D ENOMEM;
 	goto out;
     }
-=09
-    ret =3D hx509_get_one_cert(id->hx509ctx, signer_certs, &(*signer)->cer=
t);
+
+    ret =3D hx509_get_one_cert(context->hx509ctx, signer_certs, &(*signer)=
->cert);
     if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,
-			    "Failed to get on of the signer certs");
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to get on of the signer certs");
 	goto out;
     }
=20
-out:
+ out:
     hx509_certs_free(&signer_certs);
     if (ret) {
 	if (*signer) {
@@ -762,29 +964,32 @@
 				    &key_pack,
 				    &size);
     if (ret) {
-	krb5_set_error_string(context, "PKINIT decoding reply key failed");
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT decoding reply key failed", ""));
 	free_ReplyKeyPack_Win2k(&key_pack);
 	return ret;
     }
-    =20
-    if (key_pack.nonce !=3D nonce) {
-	krb5_set_error_string(context, "PKINIT enckey nonce is wrong");
+
+    if ((unsigned)key_pack.nonce !=3D nonce) {
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT enckey nonce is wrong", ""));
 	free_ReplyKeyPack_Win2k(&key_pack);
 	return KRB5KRB_AP_ERR_MODIFIED;
     }
=20
     *key =3D malloc (sizeof (**key));
     if (*key =3D=3D NULL) {
-	krb5_set_error_string(context, "PKINIT failed allocating reply key");
 	free_ReplyKeyPack_Win2k(&key_pack);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
     ret =3D copy_EncryptionKey(&key_pack.replyKey, *key);
     free_ReplyKeyPack_Win2k(&key_pack);
     if (ret) {
-	krb5_set_error_string(context, "PKINIT failed copying reply key");
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT failed copying reply key", ""));
 	free(*key);
 	*key =3D NULL;
     }
@@ -807,15 +1012,16 @@
 			      &key_pack,
 			      &size);
     if (ret) {
-	krb5_set_error_string(context, "PKINIT decoding reply key failed");
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT decoding reply key failed", ""));
 	free_ReplyKeyPack(&key_pack);
 	return ret;
     }
-   =20
+
     {
 	krb5_crypto crypto;
=20
-	/*=20
+	/*
 	 * XXX Verify kp.replyKey is a allowed enctype in the
 	 * configuration file
 	 */
@@ -838,16 +1044,17 @@
=20
     *key =3D malloc (sizeof (**key));
     if (*key =3D=3D NULL) {
-	krb5_set_error_string(context, "PKINIT failed allocating reply key");
 	free_ReplyKeyPack(&key_pack);
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
     ret =3D copy_EncryptionKey(&key_pack.replyKey, *key);
     free_ReplyKeyPack(&key_pack);
     if (ret) {
-	krb5_set_error_string(context, "PKINIT failed copying reply key");
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT failed copying reply key", ""));
 	free(*key);
 	*key =3D NULL;
     }
@@ -866,24 +1073,27 @@
     krb5_error_code ret =3D 0;
=20
     if (ctx->require_eku) {
-	ret =3D hx509_cert_check_eku(ctx->id->hx509ctx, host->cert,
-				   oid_id_pkkdcekuoid(), 0);
+	ret =3D hx509_cert_check_eku(context->hx509ctx, host->cert,
+				   &asn1_oid_id_pkkdcekuoid, 0);
 	if (ret) {
-	    krb5_set_error_string(context, "No PK-INIT KDC EKU in kdc certificate=
");
+	    krb5_set_error_message(context, ret,
+				   N_("No PK-INIT KDC EKU in kdc certificate", ""));
 	    return ret;
 	}
     }
     if (ctx->require_krbtgt_otherName) {
 	hx509_octet_string_list list;
-	int i;
+	size_t i;
=20
-	ret =3D hx509_cert_find_subjectAltName_otherName(ctx->id->hx509ctx,
+	ret =3D hx509_cert_find_subjectAltName_otherName(context->hx509ctx,
 						       host->cert,
-						       oid_id_pkinit_san(),
+						       &asn1_oid_id_pkinit_san,
 						       &list);
 	if (ret) {
-	    krb5_set_error_string(context, "Failed to find the PK-INIT "
-				  "subjectAltName in the KDC certificate");
+	    krb5_set_error_message(context, ret,
+				   N_("Failed to find the PK-INIT "
+				      "subjectAltName in the KDC "
+				      "certificate", ""));
=20
 	    return ret;
 	}
@@ -896,8 +1106,10 @@
 					   &r,
 					   NULL);
 	    if (ret) {
-		krb5_set_error_string(context, "Failed to decode the PK-INIT "
-				      "subjectAltName in the KDC certificate");
+		krb5_set_error_message(context, ret,
+				       N_("Failed to decode the PK-INIT "
+					  "subjectAltName in the "
+					  "KDC certificate", ""));
=20
 		break;
 	    }
@@ -906,11 +1118,12 @@
 		strcmp(r.principalName.name_string.val[0], KRB5_TGS_NAME) !=3D 0 ||
 		strcmp(r.principalName.name_string.val[1], realm) !=3D 0 ||
 		strcmp(r.realm, realm) !=3D 0)
-	    {
-		krb5_set_error_string(context, "KDC have wrong realm name in "
-				      "the certificate");
-		ret =3D KRB5_KDC_ERR_INVALID_CERTIFICATE;
-	    }
+		{
+		    ret =3D KRB5_KDC_ERR_INVALID_CERTIFICATE;
+		    krb5_set_error_message(context, ret,
+					   N_("KDC have wrong realm name in "
+					      "the certificate", ""));
+		}
=20
 	    free_KRB5PrincipalName(&r);
 	    if (ret)
@@ -920,17 +1133,18 @@
     }
     if (ret)
 	return ret;
-   =20
+
     if (hi) {
-	ret =3D hx509_verify_hostname(ctx->id->hx509ctx, host->cert,=20
+	ret =3D hx509_verify_hostname(context->hx509ctx, host->cert,
 				    ctx->require_hostname_match,
 				    HX509_HN_HOSTNAME,
 				    hi->hostname,
 				    hi->ai->ai_addr, hi->ai->ai_addrlen);
=20
 	if (ret)
-	    krb5_set_error_string(context, "Address mismatch in "
-				  "the KDC certificate");
+	    krb5_set_error_message(context, ret,
+				   N_("Address mismatch in "
+				      "the KDC certificate", ""));
     }
     return ret;
 }
@@ -947,81 +1161,91 @@
 	       	      unsigned nonce,
 		      const krb5_data *req_buffer,
 	       	      PA_DATA *pa,
-	       	      krb5_keyblock **key)=20
+	       	      krb5_keyblock **key)
 {
     krb5_error_code ret;
     struct krb5_pk_cert *host =3D NULL;
     krb5_data content;
     heim_oid contentType =3D { 0, NULL };
+    int flags =3D HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT;
=20
-    if (der_heim_oid_cmp(oid_id_pkcs7_envelopedData(), dataType)) {
-	krb5_set_error_string(context, "PKINIT: Invalid content type");
+    if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_envelopedData, dataType)) {
+	krb5_set_error_message(context, EINVAL,
+			       N_("PKINIT: Invalid content type", ""));
 	return EINVAL;
     }
=20
-    ret =3D hx509_cms_unenvelope(ctx->id->hx509ctx,
+    if (ctx->type =3D=3D PKINIT_WIN2K)
+	flags |=3D HX509_CMS_UE_ALLOW_WEAK;
+
+    ret =3D hx509_cms_unenvelope(context->hx509ctx,
 			       ctx->id->certs,
-			       HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT,
+			       flags,
 			       indata->data,
 			       indata->length,
 			       NULL,
+			       0,
 			       &contentType,
 			       &content);
     if (ret) {
-	_krb5_pk_copy_error(context, ctx->id->hx509ctx, ret,
-			    "Failed to unenvelope CMS data in PK-INIT reply");
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to unenvelope CMS data in PK-INIT reply");
 	return ret;
     }
     der_free_oid(&contentType);
=20
-#if 0 /* windows LH with interesting CMS packets, leaks memory */
-    {
-	size_t ph =3D 1 + der_length_len (length);
-	unsigned char *ptr =3D malloc(length + ph);
-	size_t l;
-
-	memcpy(ptr + ph, p, length);
-
-	ret =3D der_put_length_and_tag (ptr + ph - 1, ph, length,
-				      ASN1_C_UNIV, CONS, UT_Sequence, &l);
-	if (ret)
-	    return ret;
-	ptr +=3D ph - l;
-	length +=3D l;
-	p =3D ptr;
-    }
-#endif
-
     /* win2k uses ContentInfo */
-    if (type =3D=3D COMPAT_WIN2K) {
-	heim_oid type;
+    if (type =3D=3D PKINIT_WIN2K) {
+	heim_oid type2;
 	heim_octet_string out;
=20
-	ret =3D hx509_cms_unwrap_ContentInfo(&content, &type, &out, NULL);
-	if (der_heim_oid_cmp(&type, oid_id_pkcs7_signedData())) {
+	ret =3D hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL);
+	if (ret) {
+	    /* windows LH with interesting CMS packets */
+	    size_t ph =3D 1 + der_length_len(content.length);
+	    unsigned char *ptr =3D malloc(content.length + ph);
+	    size_t l;
+
+	    memcpy(ptr + ph, content.data, content.length);
+
+	    ret =3D der_put_length_and_tag (ptr + ph - 1, ph, content.length,
+					  ASN1_C_UNIV, CONS, UT_Sequence, &l);
+	    if (ret)
+		return ret;
+	    free(content.data);
+	    content.data =3D ptr;
+	    content.length +=3D ph;
+
+	    ret =3D hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL);
+	    if (ret)
+		goto out;
+	}
+	if (der_heim_oid_cmp(&type2, &asn1_oid_id_pkcs7_signedData)) {
 	    ret =3D EINVAL; /* XXX */
-	    krb5_set_error_string(context, "PKINIT: Invalid content type");
-	    der_free_oid(&type);
+	    krb5_set_error_message(context, ret,
+				   N_("PKINIT: Invalid content type", ""));
+	    der_free_oid(&type2);
 	    der_free_octet_string(&out);
 	    goto out;
 	}
-	der_free_oid(&type);
+	der_free_oid(&type2);
 	krb5_data_free(&content);
 	ret =3D krb5_data_copy(&content, out.data, out.length);
 	der_free_octet_string(&out);
 	if (ret) {
-	    krb5_set_error_string(context, "PKINIT: out of memory");
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto out;
 	}
     }
=20
-    ret =3D _krb5_pk_verify_sign(context,=20
-			       content.data,
-			       content.length,
-			       ctx->id,
-			       &contentType,
-			       &content,
-			       &host);
+    ret =3D pk_verify_sign(context,
+			 content.data,
+			 content.length,
+			 ctx->id,
+			 &contentType,
+			 &content,
+			 &host);
     if (ret)
 	goto out;
=20
@@ -1032,28 +1256,28 @@
     }
=20
 #if 0
-    if (type =3D=3D COMPAT_WIN2K) {
-	if (der_heim_oid_cmp(&contentType, oid_id_pkcs7_data()) !=3D 0) {
-	    krb5_set_error_string(context, "PKINIT: reply key, wrong oid");
+    if (type =3D=3D PKINIT_WIN2K) {
+	if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) !=3D 0) {
 	    ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
+	    krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
 	    goto out;
 	}
     } else {
-	if (der_heim_oid_cmp(&contentType, oid_id_pkrkeydata()) !=3D 0) {
-	    krb5_set_error_string(context, "PKINIT: reply key, wrong oid");
+	if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkrkeydata) !=3D 0) {
 	    ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
+	    krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid");
 	    goto out;
 	}
     }
 #endif
=20
     switch(type) {
-    case COMPAT_WIN2K:
+    case PKINIT_WIN2K:
 	ret =3D get_reply_key(context, &content, req_buffer, key);
 	if (ret !=3D 0 && ctx->require_binding =3D=3D 0)
 	    ret =3D get_reply_key_win(context, &content, nonce, key);
 	break;
-    case COMPAT_IETF:
+    case PKINIT_27:
 	ret =3D get_reply_key(context, &content, req_buffer, key);
 	break;
     }
@@ -1085,31 +1309,33 @@
                   PA_DATA *pa,
                   krb5_keyblock **key)
 {
-    unsigned char *p, *dh_gen_key =3D NULL;
+    const unsigned char *p;
+    unsigned char *dh_gen_key =3D NULL;
     struct krb5_pk_cert *host =3D NULL;
     BIGNUM *kdc_dh_pubkey =3D NULL;
     KDCDHKeyInfo kdc_dh_info;
     heim_oid contentType =3D { 0, NULL };
     krb5_data content;
     krb5_error_code ret;
-    int dh_gen_keylen;
+    int dh_gen_keylen =3D 0;
     size_t size;
=20
     krb5_data_zero(&content);
     memset(&kdc_dh_info, 0, sizeof(kdc_dh_info));
=20
-    if (der_heim_oid_cmp(oid_id_pkcs7_signedData(), dataType)) {
-	krb5_set_error_string(context, "PKINIT: Invalid content type");
+    if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_signedData, dataType)) {
+	krb5_set_error_message(context, EINVAL,
+			       N_("PKINIT: Invalid content type", ""));
 	return EINVAL;
     }
=20
-    ret =3D _krb5_pk_verify_sign(context,=20
-			       indata->data,
-			       indata->length,
-			       ctx->id,
-			       &contentType,
-			       &content,
-			       &host);
+    ret =3D pk_verify_sign(context,
+			 indata->data,
+			 indata->length,
+			 ctx->id,
+			 &contentType,
+			 &content,
+			 &host);
     if (ret)
 	goto out;
=20
@@ -1118,9 +1344,10 @@
     if (ret)
 	goto out;
=20
-    if (der_heim_oid_cmp(&contentType, oid_id_pkdhkeydata())) {
-	krb5_set_error_string(context, "pkinit - dh reply contains wrong oid");
+    if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkdhkeydata)) {
 	ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
+	krb5_set_error_message(context, ret,
+			       N_("pkinit - dh reply contains wrong oid", ""));
 	goto out;
     }
=20
@@ -1130,35 +1357,40 @@
 			      &size);
=20
     if (ret) {
-	krb5_set_error_string(context, "pkinit - "
-			      "failed to decode KDC DH Key Info");
+	krb5_set_error_message(context, ret,
+			       N_("pkinit - failed to decode "
+				  "KDC DH Key Info", ""));
 	goto out;
     }
=20
     if (kdc_dh_info.nonce !=3D nonce) {
-	krb5_set_error_string(context, "PKINIT: DH nonce is wrong");
 	ret =3D KRB5KRB_AP_ERR_MODIFIED;
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT: DH nonce is wrong", ""));
 	goto out;
     }
=20
     if (kdc_dh_info.dhKeyExpiration) {
 	if (k_n =3D=3D NULL) {
-	    krb5_set_error_string(context, "pkinit; got key expiration "
-				  "without server nonce");
 	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   N_("pkinit; got key expiration "
+				      "without server nonce", ""));
 	    goto out;
 	}
 	if (c_n =3D=3D NULL) {
-	    krb5_set_error_string(context, "pkinit; got DH reuse but no "
-				  "client nonce");
 	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   N_("pkinit; got DH reuse but no "
+				      "client nonce", ""));
 	    goto out;
 	}
     } else {
 	if (k_n) {
-	    krb5_set_error_string(context, "pkinit: got server nonce "
-				  "without key expiration");
 	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   N_("pkinit: got server nonce "
+				      "without key expiration", ""));
 	    goto out;
 	}
 	c_n =3D NULL;
@@ -1168,49 +1400,110 @@
     p =3D kdc_dh_info.subjectPublicKey.data;
     size =3D (kdc_dh_info.subjectPublicKey.length + 7) / 8;
=20
-    {
+    if (ctx->keyex =3D=3D USE_DH) {
 	DHPublicKey k;
 	ret =3D decode_DHPublicKey(p, size, &k, NULL);
 	if (ret) {
-	    krb5_set_error_string(context, "pkinit: can't decode "
-				  "without key expiration");
+	    krb5_set_error_message(context, ret,
+				   N_("pkinit: can't decode "
+				      "without key expiration", ""));
 	    goto out;
 	}
=20
 	kdc_dh_pubkey =3D integer_to_BN(context, "DHPublicKey", &k);
 	free_DHPublicKey(&k);
 	if (kdc_dh_pubkey =3D=3D NULL) {
-	    ret =3D KRB5KRB_ERR_GENERIC;
+	    ret =3D ENOMEM;
 	    goto out;
 	}
+
+
+	size =3D DH_size(ctx->u.dh);
+
+	dh_gen_key =3D malloc(size);
+	if (dh_gen_key =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	    goto out;
+	}
+
+	dh_gen_keylen =3D DH_compute_key(dh_gen_key, kdc_dh_pubkey, ctx->u.dh);
+	if (dh_gen_keylen =3D=3D -1) {
+	    ret =3D KRB5KRB_ERR_GENERIC;
+	    dh_gen_keylen =3D 0;
+	    krb5_set_error_message(context, ret,
+				   N_("PKINIT: Can't compute Diffie-Hellman key", ""));
+	    goto out;
+	}
+	if (dh_gen_keylen < (int)size) {
+	    size -=3D dh_gen_keylen;
+	    memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen);
+	    memset(dh_gen_key, 0, size);
+	}
+
+    } else {
+#ifdef HAVE_OPENSSL
+	const EC_GROUP *group;
+	EC_KEY *public =3D NULL;
+
+	group =3D EC_KEY_get0_group(ctx->u.eckey);
+
+	public =3D EC_KEY_new();
+	if (public =3D=3D NULL) {
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+	if (EC_KEY_set_group(public, group) !=3D 1) {
+	    EC_KEY_free(public);
+	    ret =3D ENOMEM;
+	    goto out;
+	}
+
+	if (o2i_ECPublicKey(&public, &p, size) =3D=3D NULL) {
+	    EC_KEY_free(public);
+	    ret =3D KRB5KRB_ERR_GENERIC;
+	    krb5_set_error_message(context, ret,
+				   N_("PKINIT: Can't parse ECDH public key", ""));
+	    goto out;
+	}
+
+	size =3D (EC_GROUP_get_degree(group) + 7) / 8;
+	dh_gen_key =3D malloc(size);
+	if (dh_gen_key =3D=3D NULL) {
+	    EC_KEY_free(public);
+	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
+	    goto out;
+	}
+	dh_gen_keylen =3D ECDH_compute_key(dh_gen_key, size,
+					 EC_KEY_get0_public_key(public), ctx->u.eckey, NULL);
+	EC_KEY_free(public);
+	if (dh_gen_keylen =3D=3D -1) {
+	    ret =3D KRB5KRB_ERR_GENERIC;
+	    dh_gen_keylen =3D 0;
+	    krb5_set_error_message(context, ret,
+				   N_("PKINIT: Can't compute ECDH public key", ""));
+	    goto out;
+	}
+#else
+	ret =3D EINVAL;
+#endif
     }
-   =20
-    dh_gen_keylen =3D DH_size(ctx->dh);
-    size =3D BN_num_bytes(ctx->dh->p);
-    if (size < dh_gen_keylen)
-	size =3D dh_gen_keylen;
=20
-    dh_gen_key =3D malloc(size);
-    if (dh_gen_key =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
-	ret =3D ENOMEM;
-	goto out;
-    }
-    memset(dh_gen_key, 0, size - dh_gen_keylen);
-
-    dh_gen_keylen =3D DH_compute_key(dh_gen_key + (size - dh_gen_keylen),
-				   kdc_dh_pubkey, ctx->dh);
-    if (dh_gen_keylen =3D=3D -1) {
-	krb5_set_error_string(context,=20
-			      "PKINIT: Can't compute Diffie-Hellman key");
-	ret =3D KRB5KRB_ERR_GENERIC;
+    if (dh_gen_keylen <=3D 0) {
+	ret =3D EINVAL;
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT: resulting DH key <=3D 0", ""));
+	dh_gen_keylen =3D 0;
 	goto out;
     }
=20
     *key =3D malloc (sizeof (**key));
     if (*key =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret,
+			       N_("malloc: out of memory", ""));
 	goto out;
     }
=20
@@ -1220,8 +1513,8 @@
 				   c_n, k_n,
 				   *key);
     if (ret) {
-	krb5_set_error_string(context,
-			      "PKINIT: can't create key from DH key");
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT: can't create key from DH key", ""));
 	free(*key);
 	*key =3D NULL;
 	goto out;
@@ -1231,7 +1524,7 @@
     if (kdc_dh_pubkey)
 	BN_free(kdc_dh_pubkey);
     if (dh_gen_key) {
-	memset(dh_gen_key, 0, DH_size(ctx->dh));
+	memset(dh_gen_key, 0, dh_gen_keylen);
 	free(dh_gen_key);
     }
     if (host)
@@ -1244,7 +1537,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_rd_pa_reply(krb5_context context,
 		     const char *realm,
 		     void *c,
@@ -1260,13 +1553,14 @@
     size_t size;
=20
     /* Check for IETF PK-INIT first */
-    if (ctx->type =3D=3D COMPAT_IETF) {
+    if (ctx->type =3D=3D PKINIT_27) {
 	PA_PK_AS_REP rep;
 	heim_octet_string os, data;
 	heim_oid oid;
-=09
+
 	if (pa->padata_type !=3D KRB5_PADATA_PK_AS_REP) {
-	    krb5_set_error_string(context, "PKINIT: wrong padata recv");
+	    krb5_set_error_message(context, EINVAL,
+				   N_("PKINIT: wrong padata recv", ""));
 	    return EINVAL;
 	}
=20
@@ -1275,28 +1569,65 @@
 				  &rep,
 				  &size);
 	if (ret) {
-	    krb5_set_error_string(context, "Failed to decode pkinit AS rep");
+	    krb5_set_error_message(context, ret,
+				   N_("Failed to decode pkinit AS rep", ""));
 	    return ret;
 	}
=20
 	switch (rep.element) {
 	case choice_PA_PK_AS_REP_dhInfo:
+	    _krb5_debug(context, 5, "krb5_get_init_creds: using pkinit dh");
 	    os =3D rep.u.dhInfo.dhSignedData;
 	    break;
 	case choice_PA_PK_AS_REP_encKeyPack:
+	    _krb5_debug(context, 5, "krb5_get_init_creds: using kinit enc reply k=
ey");
 	    os =3D rep.u.encKeyPack;
 	    break;
-	default:
+	default: {
+	    PA_PK_AS_REP_BTMM btmm;
 	    free_PA_PK_AS_REP(&rep);
-	    krb5_set_error_string(context, "PKINIT: -27 reply "
-				  "invalid content type");
-	    return EINVAL;
+	    memset(&rep, 0, sizeof(rep));
+
+	    _krb5_debug(context, 5, "krb5_get_init_creds: using BTMM kinit enc re=
ply key");
+
+	    ret =3D decode_PA_PK_AS_REP_BTMM(pa->padata_value.data,
+					   pa->padata_value.length,
+					   &btmm,
+					   &size);
+	    if (ret) {
+		krb5_set_error_message(context, EINVAL,
+				       N_("PKINIT: -27 reply "
+					  "invalid content type", ""));
+		return EINVAL;
+	    }
+
+	    if (btmm.dhSignedData || btmm.encKeyPack =3D=3D NULL) {
+		free_PA_PK_AS_REP_BTMM(&btmm);
+		ret =3D EINVAL;
+		krb5_set_error_message(context, ret,
+				       N_("DH mode not supported for BTMM mode", ""));
+		return ret;
+	    }
+
+	    /*
+	     * Transform to IETF style PK-INIT reply so that free works below
+	     */
+
+	    rep.element =3D choice_PA_PK_AS_REP_encKeyPack;
+	    rep.u.encKeyPack.data =3D btmm.encKeyPack->data;
+	    rep.u.encKeyPack.length =3D btmm.encKeyPack->length;
+	    btmm.encKeyPack->data =3D NULL;
+	    btmm.encKeyPack->length =3D 0;
+	    free_PA_PK_AS_REP_BTMM(&btmm);
+	    os =3D rep.u.encKeyPack;
+	}
 	}
=20
 	ret =3D hx509_cms_unwrap_ContentInfo(&os, &oid, &data, NULL);
 	if (ret) {
 	    free_PA_PK_AS_REP(&rep);
-	    krb5_set_error_string(context, "PKINIT: failed to unwrap CI");
+	    krb5_set_error_message(context, ret,
+				   N_("PKINIT: failed to unwrap CI", ""));
 	    return ret;
 	}
=20
@@ -1308,7 +1639,7 @@
 				    nonce, pa, key);
 	    break;
 	case choice_PA_PK_AS_REP_encKeyPack:
-	    ret =3D pk_rd_pa_reply_enckey(context, COMPAT_IETF, &data, &oid, real=
m,=20
+	    ret =3D pk_rd_pa_reply_enckey(context, PKINIT_27, &data, &oid, realm,
 					ctx, etype, hi, nonce, req_buffer, pa, key);
 	    break;
 	default:
@@ -1318,46 +1649,49 @@
 	der_free_oid(&oid);
 	free_PA_PK_AS_REP(&rep);
=20
-    } else if (ctx->type =3D=3D COMPAT_WIN2K) {
+    } else if (ctx->type =3D=3D PKINIT_WIN2K) {
 	PA_PK_AS_REP_Win2k w2krep;
=20
-	/* Check for Windows encoding of the AS-REP pa data */=20
+	/* Check for Windows encoding of the AS-REP pa data */
=20
 #if 0 /* should this be ? */
 	if (pa->padata_type !=3D KRB5_PADATA_PK_AS_REP) {
-	    krb5_set_error_string(context, "PKINIT: wrong padata recv");
+	    krb5_set_error_message(context, EINVAL,
+				   "PKINIT: wrong padata recv");
 	    return EINVAL;
 	}
 #endif
=20
 	memset(&w2krep, 0, sizeof(w2krep));
-=09
+
 	ret =3D decode_PA_PK_AS_REP_Win2k(pa->padata_value.data,
 					pa->padata_value.length,
 					&w2krep,
 					&size);
 	if (ret) {
-	    krb5_set_error_string(context, "PKINIT: Failed decoding windows "
-				  "pkinit reply %d", ret);
+	    krb5_set_error_message(context, ret,
+				   N_("PKINIT: Failed decoding windows "
+				      "pkinit reply %d", ""), (int)ret);
 	    return ret;
 	}
=20
-	krb5_clear_error_string(context);
-=09
+	krb5_clear_error_message(context);
+
 	switch (w2krep.element) {
 	case choice_PA_PK_AS_REP_Win2k_encKeyPack: {
 	    heim_octet_string data;
 	    heim_oid oid;
-	   =20
-	    ret =3D hx509_cms_unwrap_ContentInfo(&w2krep.u.encKeyPack,=20
+
+	    ret =3D hx509_cms_unwrap_ContentInfo(&w2krep.u.encKeyPack,
 					       &oid, &data, NULL);
 	    free_PA_PK_AS_REP_Win2k(&w2krep);
 	    if (ret) {
-		krb5_set_error_string(context, "PKINIT: failed to unwrap CI");
+		krb5_set_error_message(context, ret,
+				       N_("PKINIT: failed to unwrap CI", ""));
 		return ret;
 	    }
=20
-	    ret =3D pk_rd_pa_reply_enckey(context, COMPAT_WIN2K, &data, &oid, rea=
lm,
+	    ret =3D pk_rd_pa_reply_enckey(context, PKINIT_WIN2K, &data, &oid, rea=
lm,
 					ctx, etype, hi, nonce, req_buffer, pa, key);
 	    der_free_octet_string(&data);
 	    der_free_oid(&oid);
@@ -1366,15 +1700,17 @@
 	}
 	default:
 	    free_PA_PK_AS_REP_Win2k(&w2krep);
-	    krb5_set_error_string(context, "PKINIT: win2k reply invalid "
-				  "content type");
 	    ret =3D EINVAL;
+	    krb5_set_error_message(context, ret,
+				   N_("PKINIT: win2k reply invalid "
+				      "content type", ""));
 	    break;
 	}
-   =20
+
     } else {
-	krb5_set_error_string(context, "PKINIT: unknown reply type");
 	ret =3D EINVAL;
+	krb5_set_error_message(context, ret,
+			       N_("PKINIT: unknown reply type", ""));
     }
=20
     return ret;
@@ -1386,14 +1722,14 @@
     void *prompter_data;
 };
=20
-static int=20
+static int
 hx_pass_prompter(void *data, const hx509_prompt *prompter)
 {
     krb5_error_code ret;
     krb5_prompt prompt;
     krb5_data password_data;
     struct prompter *p =3D data;
-  =20
+
     password_data.data   =3D prompter->reply.data;
     password_data.length =3D prompter->reply.length;
=20
@@ -1410,8 +1746,8 @@
     default:
 	prompt.type   =3D KRB5_PROMPT_TYPE_PASSWORD;
 	break;
-    }=09
-  =20
+    }
+
     ret =3D (*p->prompter)(p->context, p->prompter_data, NULL, NULL, 1, &p=
rompt);
     if (ret) {
 	memset (prompter->reply.data, 0, prompter->reply.length);
@@ -1420,16 +1756,80 @@
     return 0;
 }
=20
+static krb5_error_code
+_krb5_pk_set_user_id(krb5_context context,
+		     krb5_principal principal,
+		     krb5_pk_init_ctx ctx,
+		     struct hx509_certs_data *certs)
+{
+    hx509_certs c =3D hx509_certs_ref(certs);
+    hx509_query *q =3D NULL;
+    int ret;
=20
-void KRB5_LIB_FUNCTION
-_krb5_pk_allow_proxy_certificate(struct krb5_pk_identity *id,
-				 int boolean)
-{
-    hx509_verify_set_proxy_certificate(id->verify_ctx, boolean);
+    if (ctx->id->certs)
+	hx509_certs_free(&ctx->id->certs);
+    if (ctx->id->cert) {
+	hx509_cert_free(ctx->id->cert);
+	ctx->id->cert =3D NULL;
+    }
+
+    ctx->id->certs =3D c;
+    ctx->anonymous =3D 0;
+
+    ret =3D hx509_query_alloc(context->hx509ctx, &q);
+    if (ret) {
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Allocate query to find signing certificate");
+	return ret;
+    }
+
+    hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+    hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
+
+    if (principal && strncmp("LKDC:SHA1.", krb5_principal_get_realm(contex=
t, principal), 9) =3D=3D 0) {
+	ctx->id->flags |=3D PKINIT_BTMM;
+    }
+
+    ret =3D find_cert(context, ctx->id, q, &ctx->id->cert);
+    hx509_query_free(context->hx509ctx, q);
+
+    if (ret =3D=3D 0 && _krb5_have_debug(context, 2)) {
+	hx509_name name;
+	char *str, *sn;
+	heim_integer i;
+
+	ret =3D hx509_cert_get_subject(ctx->id->cert, &name);
+	if (ret)
+	    goto out;
+
+	ret =3D hx509_name_to_string(name, &str);
+	hx509_name_free(&name);
+	if (ret)
+	    goto out;
+
+	ret =3D hx509_cert_get_serialnumber(ctx->id->cert, &i);
+	if (ret) {
+	    free(str);
+	    goto out;
+	}
+
+	ret =3D der_print_hex_heim_integer(&i, &sn);
+	der_free_heim_integer(&i);
+	if (ret) {
+	    free(name);
+	    goto out;
+	}
+
+	_krb5_debug(context, 2, "using cert: subject: %s sn: %s", str, sn);
+	free(str);
+	free(sn);
+    }
+ out:
+
+    return ret;
 }
=20
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 _krb5_pk_load_id(krb5_context context,
 		 struct krb5_pk_identity **ret_id,
 		 const char *user_id,
@@ -1441,190 +1841,187 @@
 		 char *password)
 {
     struct krb5_pk_identity *id =3D NULL;
-    hx509_lock lock =3D NULL;
     struct prompter p;
     int ret;
=20
     *ret_id =3D NULL;
=20
     if (anchor_id =3D=3D NULL) {
-	krb5_set_error_string(context, "PKINIT: No anchor given");
+	krb5_set_error_message(context, HEIM_PKINIT_NO_VALID_CA,
+			       N_("PKINIT: No anchor given", ""));
 	return HEIM_PKINIT_NO_VALID_CA;
     }
=20
-    if (user_id =3D=3D NULL) {
-	krb5_set_error_string(context,
-			      "PKINIT: No user certificate given");
-	return HEIM_PKINIT_NO_PRIVATE_KEY;
-    }
-
     /* load cert */
=20
     id =3D calloc(1, sizeof(*id));
     if (id =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
-    }=09
-
-    ret =3D hx509_context_init(&id->hx509ctx);
-    if (ret)
-	goto out;
-
-    ret =3D hx509_lock_init(id->hx509ctx, &lock);
-    if (password && password[0])
-	hx509_lock_add_password(lock, password);
-
-    if (prompter) {
-	p.context =3D context;
-	p.prompter =3D prompter;
-	p.prompter_data =3D prompter_data;
-
-	ret =3D hx509_lock_set_prompter(lock, hx_pass_prompter, &p);
-	if (ret)
-	    goto out;
     }
=20
-    ret =3D hx509_certs_init(id->hx509ctx, user_id, 0, lock, &id->certs);
+    if (user_id) {
+	hx509_lock lock;
+
+	ret =3D hx509_lock_init(context->hx509ctx, &lock);
+	if (ret) {
+	    pk_copy_error(context, context->hx509ctx, ret, "Failed init lock");
+	    goto out;
+	}
+
+	if (password && password[0])
+	    hx509_lock_add_password(lock, password);
+
+	if (prompter) {
+	    p.context =3D context;
+	    p.prompter =3D prompter;
+	    p.prompter_data =3D prompter_data;
+
+	    ret =3D hx509_lock_set_prompter(lock, hx_pass_prompter, &p);
+	    if (ret) {
+		hx509_lock_free(lock);
+		goto out;
+	    }
+	}
+
+	ret =3D hx509_certs_init(context->hx509ctx, user_id, 0, lock, &id->certs);
+        hx509_lock_free(lock);
+	if (ret) {
+	    pk_copy_error(context, context->hx509ctx, ret,
+			  "Failed to init cert certs");
+	    goto out;
+	}
+    } else {
+	id->certs =3D NULL;
+    }
+
+    ret =3D hx509_certs_init(context->hx509ctx, anchor_id, 0, NULL, &id->a=
nchors);
     if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,
-			    "Failed to init cert certs");
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to init anchors");
 	goto out;
     }
=20
-    ret =3D hx509_certs_init(id->hx509ctx, anchor_id, 0, NULL, &id->anchor=
s);
-    if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,
-			    "Failed to init anchors");
-	goto out;
-    }
-
-    ret =3D hx509_certs_init(id->hx509ctx, "MEMORY:pkinit-cert-chain",=20
+    ret =3D hx509_certs_init(context->hx509ctx, "MEMORY:pkinit-cert-chain",
 			   0, NULL, &id->certpool);
     if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,
-			    "Failed to init chain");
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to init chain");
 	goto out;
     }
=20
     while (chain_list && *chain_list) {
-	ret =3D hx509_certs_append(id->hx509ctx, id->certpool,
+	ret =3D hx509_certs_append(context->hx509ctx, id->certpool,
 				 NULL, *chain_list);
 	if (ret) {
-	    _krb5_pk_copy_error(context, id->hx509ctx, ret,
-				"Failed to laod chain %s",
-				*chain_list);
+	    pk_copy_error(context, context->hx509ctx, ret,
+			  "Failed to laod chain %s",
+			  *chain_list);
 	    goto out;
 	}
 	chain_list++;
     }
=20
     if (revoke_list) {
-	ret =3D hx509_revoke_init(id->hx509ctx, &id->revokectx);
+	ret =3D hx509_revoke_init(context->hx509ctx, &id->revokectx);
 	if (ret) {
-	    _krb5_pk_copy_error(context, id->hx509ctx, ret,
-				"Failed init revoke list");
+	    pk_copy_error(context, context->hx509ctx, ret,
+			  "Failed init revoke list");
 	    goto out;
 	}
=20
 	while (*revoke_list) {
-	    ret =3D hx509_revoke_add_crl(id->hx509ctx,=20
+	    ret =3D hx509_revoke_add_crl(context->hx509ctx,
 				       id->revokectx,
 				       *revoke_list);
 	    if (ret) {
-		_krb5_pk_copy_error(context, id->hx509ctx, ret,=20
-				    "Failed load revoke list");
+		pk_copy_error(context, context->hx509ctx, ret,
+			      "Failed load revoke list");
 		goto out;
 	    }
 	    revoke_list++;
 	}
     } else
-	hx509_context_set_missing_revoke(id->hx509ctx, 1);
+	hx509_context_set_missing_revoke(context->hx509ctx, 1);
=20
-    ret =3D hx509_verify_init_ctx(id->hx509ctx, &id->verify_ctx);
+    ret =3D hx509_verify_init_ctx(context->hx509ctx, &id->verify_ctx);
     if (ret) {
-	_krb5_pk_copy_error(context, id->hx509ctx, ret,=20
-			    "Failed init verify context");
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed init verify context");
 	goto out;
     }
=20
     hx509_verify_attach_anchors(id->verify_ctx, id->anchors);
     hx509_verify_attach_revoke(id->verify_ctx, id->revokectx);
=20
-out:
+ out:
     if (ret) {
 	hx509_verify_destroy_ctx(id->verify_ctx);
 	hx509_certs_free(&id->certs);
 	hx509_certs_free(&id->anchors);
 	hx509_certs_free(&id->certpool);
 	hx509_revoke_free(&id->revokectx);
-	hx509_context_free(&id->hx509ctx);
 	free(id);
     } else
 	*ret_id =3D id;
=20
-    hx509_lock_free(lock);
-
     return ret;
 }
=20
-static krb5_error_code
-select_dh_group(krb5_context context, DH *dh, unsigned long bits,=20
-		struct krb5_dh_moduli **moduli)
+/*
+ *
+ */
+
+static void
+pk_copy_error(krb5_context context,
+	      hx509_context hx509ctx,
+	      int hxret,
+	      const char *fmt,
+	      ...)
 {
-    const struct krb5_dh_moduli *m;
+    va_list va;
+    char *s, *f;
+    int ret;
=20
-    if (bits =3D=3D 0) {
-	m =3D moduli[1]; /* XXX */
-	if (m =3D=3D NULL)
-	    m =3D moduli[0]; /* XXX */
-    } else {
-	int i;
-	for (i =3D 0; moduli[i] !=3D NULL; i++) {
-	    if (bits < moduli[i]->bits)
-		break;
-	}
-	if (moduli[i] =3D=3D NULL) {
-	    krb5_set_error_string(context,=20
-				  "Did not find a DH group parameter "
-				  "matching requirement of %lu bits",
-				  bits);
-	    return EINVAL;
-	}
-	m =3D moduli[i];
+    va_start(va, fmt);
+    ret =3D vasprintf(&f, fmt, va);
+    va_end(va);
+    if (ret =3D=3D -1 || f =3D=3D NULL) {
+	krb5_clear_error_message(context);
+	return;
     }
=20
-    dh->p =3D integer_to_BN(context, "p", &m->p);
-    if (dh->p =3D=3D NULL)
-	return ENOMEM;
-    dh->g =3D integer_to_BN(context, "g", &m->g);
-    if (dh->g =3D=3D NULL)
-	return ENOMEM;
-    dh->q =3D integer_to_BN(context, "q", &m->q);
-    if (dh->q =3D=3D NULL)
-	return ENOMEM;
-
-    return 0;
+    s =3D hx509_get_error_string(hx509ctx, hxret);
+    if (s =3D=3D NULL) {
+	krb5_clear_error_message(context);
+	free(f);
+	return;
+    }
+    krb5_set_error_message(context, hxret, "%s: %s", f, s);
+    free(s);
+    free(f);
 }
=20
-#endif /* PKINIT */
-
 static int
-parse_integer(krb5_context context, char **p, const char *file, int lineno=
,=20
+parse_integer(krb5_context context, char **p, const char *file, int lineno,
 	      const char *name, heim_integer *integer)
 {
     int ret;
     char *p1;
     p1 =3D strsep(p, " \t");
     if (p1 =3D=3D NULL) {
-	krb5_set_error_string(context, "moduli file %s missing %s on line %d",
-			      file, name, lineno);
+	krb5_set_error_message(context, EINVAL,
+			       N_("moduli file %s missing %s on line %d", ""),
+			       file, name, lineno);
 	return EINVAL;
     }
     ret =3D der_parse_hex_heim_integer(p1, integer);
     if (ret) {
-	krb5_set_error_string(context, "moduli file %s failed parsing %s "
-			      "on line %d",
-			      file, name, lineno);
+	krb5_set_error_message(context, ret,
+			       N_("moduli file %s failed parsing %s "
+				  "on line %d", ""),
+			       file, name, lineno);
 	return ret;
     }
=20
@@ -1632,7 +2029,7 @@
 }
=20
 krb5_error_code
-_krb5_parse_moduli_line(krb5_context context,=20
+_krb5_parse_moduli_line(krb5_context context,
 			const char *file,
 			int lineno,
 			char *p,
@@ -1646,43 +2043,49 @@
=20
     m1 =3D calloc(1, sizeof(*m1));
     if (m1 =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
     while (isspace((unsigned char)*p))
 	p++;
-    if (*p  =3D=3D '#')
+    if (*p  =3D=3D '#') {
+        free(m1);
 	return 0;
+    }
     ret =3D EINVAL;
=20
     p1 =3D strsep(&p, " \t");
     if (p1 =3D=3D NULL) {
-	krb5_set_error_string(context, "moduli file %s missing name "
-			      "on line %d", file, lineno);
+	krb5_set_error_message(context, ret,
+			       N_("moduli file %s missing name on line %d", ""),
+			       file, lineno);
 	goto out;
     }
     m1->name =3D strdup(p1);
-    if (p1 =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc - out of memeory");
+    if (m1->name =3D=3D NULL) {
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret, N_("malloc: out of memeory", ""));
 	goto out;
     }
=20
     p1 =3D strsep(&p, " \t");
     if (p1 =3D=3D NULL) {
-	krb5_set_error_string(context, "moduli file %s missing bits on line %d",
-			      file, lineno);
+	krb5_set_error_message(context, ret,
+			       N_("moduli file %s missing bits on line %d", ""),
+			       file, lineno);
 	goto out;
     }
=20
     m1->bits =3D atoi(p1);
     if (m1->bits =3D=3D 0) {
-	krb5_set_error_string(context, "moduli file %s have un-parsable "
-			      "bits on line %d", file, lineno);
+	krb5_set_error_message(context, ret,
+			       N_("moduli file %s have un-parsable "
+				  "bits on line %d", ""), file, lineno);
 	goto out;
     }
-=09
+
     ret =3D parse_integer(context, &p, file, lineno, "p", &m1->p);
     if (ret)
 	goto out;
@@ -1696,7 +2099,7 @@
     *m =3D m1;
=20
     return 0;
-out:
+ out:
     free(m1->name);
     der_free_heim_integer(&m1->p);
     der_free_heim_integer(&m1->g);
@@ -1788,7 +2191,8 @@
=20
     m =3D calloc(1, sizeof(m[0]) * 3);
     if (m =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -1812,11 +2216,26 @@
     if (file =3D=3D NULL)
 	file =3D MODULI_FILE;
=20
+#ifdef KRB5_USE_PATH_TOKENS
+    {
+        char * exp_file;
+
+        if (_krb5_expand_path_tokens(context, file, &exp_file) =3D=3D 0) {
+            f =3D fopen(exp_file, "r");
+            krb5_xfree(exp_file);
+        } else {
+            f =3D NULL;
+        }
+    }
+#else
     f =3D fopen(file, "r");
+#endif
+
     if (f =3D=3D NULL) {
 	*moduli =3D m;
 	return 0;
     }
+    rk_cloexec_file(f);
=20
     while(fgets(buf, sizeof(buf), f) !=3D NULL) {
 	struct krb5_dh_moduli *element;
@@ -1826,12 +2245,13 @@
=20
 	m2 =3D realloc(m, (n + 2) * sizeof(m[0]));
 	if (m2 =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
 	    _krb5_free_moduli(m);
+	    krb5_set_error_message(context, ENOMEM,
+				   N_("malloc: out of memory", ""));
 	    return ENOMEM;
 	}
 	m =3D m2;
-=09
+
 	m[n] =3D NULL;
=20
 	ret =3D _krb5_parse_moduli_line(context, file, lineno, buf,  &element);
@@ -1865,23 +2285,29 @@
 	if (der_heim_integer_cmp(&moduli[i]->g, g) =3D=3D 0 &&
 	    der_heim_integer_cmp(&moduli[i]->p, p) =3D=3D 0 &&
 	    (q =3D=3D NULL || der_heim_integer_cmp(&moduli[i]->q, q) =3D=3D 0))
-	{
-	    if (bits && bits > moduli[i]->bits) {
-		krb5_set_error_string(context, "PKINIT: DH group parameter %s "
-				      "no accepted, not enough bits generated",
-				      moduli[i]->name);
-		return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
+	    {
+		if (bits && bits > moduli[i]->bits) {
+		    krb5_set_error_message(context,
+					   KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
+					   N_("PKINIT: DH group parameter %s "
+					      "no accepted, not enough bits "
+					      "generated", ""),
+					   moduli[i]->name);
+		    return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
+		}
+		if (name)
+		    *name =3D strdup(moduli[i]->name);
+		return 0;
 	    }
-	    if (name)
-		*name =3D strdup(moduli[i]->name);
-	    return 0;
-	}
     }
-    krb5_set_error_string(context, "PKINIT: DH group parameter no ok");
+    krb5_set_error_message(context,
+			   KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED,
+			   N_("PKINIT: DH group parameter no ok", ""));
     return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
 }
+#endif /* PKINIT */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 _krb5_get_init_creds_opt_free_pkinit(krb5_get_init_creds_opt *opt)
 {
 #ifdef PKINIT
@@ -1890,15 +2316,26 @@
     if (opt->opt_private =3D=3D NULL || opt->opt_private->pk_init_ctx =3D=
=3D NULL)
 	return;
     ctx =3D opt->opt_private->pk_init_ctx;
-    if (ctx->dh)
-	DH_free(ctx->dh);
-	ctx->dh =3D NULL;
+    switch (ctx->keyex) {
+    case USE_DH:
+	if (ctx->u.dh)
+	    DH_free(ctx->u.dh);
+	break;
+    case USE_RSA:
+	break;
+    case USE_ECDH:
+#ifdef HAVE_OPENSSL
+	if (ctx->u.eckey)
+	    EC_KEY_free(ctx->u.eckey);
+#endif
+	break;
+    }
     if (ctx->id) {
 	hx509_verify_destroy_ctx(ctx->id->verify_ctx);
 	hx509_certs_free(&ctx->id->certs);
+	hx509_cert_free(ctx->id->cert);
 	hx509_certs_free(&ctx->id->anchors);
 	hx509_certs_free(&ctx->id->certpool);
-	hx509_context_free(&ctx->id->hx509ctx);
=20
 	if (ctx->clientDHNonce) {
 	    krb5_free_data(NULL, ctx->clientDHNonce);
@@ -1913,8 +2350,8 @@
     opt->opt_private->pk_init_ctx =3D NULL;
 #endif
 }
-   =20
-krb5_error_code KRB5_LIB_FUNCTION
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_get_init_creds_opt_set_pkinit(krb5_context context,
 				   krb5_get_init_creds_opt *opt,
 				   krb5_principal principal,
@@ -1932,19 +2369,18 @@
     char *anchors =3D NULL;
=20
     if (opt->opt_private =3D=3D NULL) {
-	krb5_set_error_string(context, "PKINIT: on non extendable opt");
+	krb5_set_error_message(context, EINVAL,
+			       N_("PKINIT: on non extendable opt", ""));
 	return EINVAL;
     }
=20
-    opt->opt_private->pk_init_ctx =3D=20
+    opt->opt_private->pk_init_ctx =3D
 	calloc(1, sizeof(*opt->opt_private->pk_init_ctx));
     if (opt->opt_private->pk_init_ctx =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
-    opt->opt_private->pk_init_ctx->dh =3D NULL;
-    opt->opt_private->pk_init_ctx->id =3D NULL;
-    opt->opt_private->pk_init_ctx->clientDHNonce =3D NULL;
     opt->opt_private->pk_init_ctx->require_binding =3D 0;
     opt->opt_private->pk_init_ctx->require_eku =3D 1;
     opt->opt_private->pk_init_ctx->require_krbtgt_otherName =3D 1;
@@ -1953,23 +2389,26 @@
     /* XXX implement krb5_appdefault_strings  */
     if (pool =3D=3D NULL)
 	pool =3D krb5_config_get_strings(context, NULL,
-				       "appdefaults",=20
-				       "pkinit_pool",=20
+				       "appdefaults",
+				       "pkinit_pool",
 				       NULL);
=20
     if (pki_revoke =3D=3D NULL)
 	pki_revoke =3D krb5_config_get_strings(context, NULL,
-					     "appdefaults",=20
-					     "pkinit_revoke",=20
+					     "appdefaults",
+					     "pkinit_revoke",
 					     NULL);
=20
     if (x509_anchors =3D=3D NULL) {
 	krb5_appdefault_string(context, "kinit",
-			       krb5_principal_get_realm(context, principal),=20
+			       krb5_principal_get_realm(context, principal),
 			       "pkinit_anchors", NULL, &anchors);
 	x509_anchors =3D anchors;
     }
=20
+    if (flags & 4)
+	opt->opt_private->pk_init_ctx->anonymous =3D 1;
+
     ret =3D _krb5_pk_load_id(context,
 			   &opt->opt_private->pk_init_ctx->id,
 			   user_id,
@@ -1985,86 +2424,218 @@
 	return ret;
     }
=20
+    if (opt->opt_private->pk_init_ctx->id->certs) {
+	_krb5_pk_set_user_id(context,
+			     principal,
+			     opt->opt_private->pk_init_ctx,
+			     opt->opt_private->pk_init_ctx->id->certs);
+    } else
+	opt->opt_private->pk_init_ctx->id->cert =3D NULL;
+
     if ((flags & 2) =3D=3D 0) {
-	const char *moduli_file;
-	unsigned long dh_min_bits;
+	hx509_context hx509ctx =3D context->hx509ctx;
+	hx509_cert cert =3D opt->opt_private->pk_init_ctx->id->cert;
=20
-	moduli_file =3D krb5_config_get_string(context, NULL,
-					     "libdefaults",
-					     "moduli",
-					     NULL);
+	opt->opt_private->pk_init_ctx->keyex =3D USE_DH;
=20
-	dh_min_bits =3D
-	    krb5_config_get_int_default(context, NULL, 0,
-					"libdefaults",
-					"pkinit_dh_min_bits",
-					NULL);
+	/*
+	 * If its a ECDSA certs, lets select ECDSA as the keyex algorithm.
+	 */
+	if (cert) {
+	    AlgorithmIdentifier alg;
=20
-	ret =3D _krb5_parse_moduli(context, moduli_file,=20
-				 &opt->opt_private->pk_init_ctx->m);
-	if (ret) {
-	    _krb5_get_init_creds_opt_free_pkinit(opt);
-	    return ret;
-	}
-=09
-	opt->opt_private->pk_init_ctx->dh =3D DH_new();
-	if (opt->opt_private->pk_init_ctx->dh =3D=3D NULL) {
-	    krb5_set_error_string(context, "malloc: out of memory");
-	    _krb5_get_init_creds_opt_free_pkinit(opt);
-	    return ENOMEM;
+	    ret =3D hx509_cert_get_SPKI_AlgorithmIdentifier(hx509ctx, cert, &alg);
+	    if (ret =3D=3D 0) {
+		if (der_heim_oid_cmp(&alg.algorithm, &asn1_oid_id_ecPublicKey) =3D=3D 0)
+		    opt->opt_private->pk_init_ctx->keyex =3D USE_ECDH;
+		free_AlgorithmIdentifier(&alg);
+	    }
 	}
=20
-	ret =3D select_dh_group(context, opt->opt_private->pk_init_ctx->dh,
-			      dh_min_bits,=20
-			      opt->opt_private->pk_init_ctx->m);
-	if (ret) {
-	    _krb5_get_init_creds_opt_free_pkinit(opt);
-	    return ret;
-	}
+    } else {
+	opt->opt_private->pk_init_ctx->keyex =3D USE_RSA;
=20
-	if (DH_generate_key(opt->opt_private->pk_init_ctx->dh) !=3D 1) {
-	    krb5_set_error_string(context, "pkinit: failed to generate DH key");
-	    _krb5_get_init_creds_opt_free_pkinit(opt);
-	    return ENOMEM;
+	if (opt->opt_private->pk_init_ctx->id->certs =3D=3D NULL) {
+	    krb5_set_error_message(context, EINVAL,
+				   N_("No anonymous pkinit support in RSA mode", ""));
+	    return EINVAL;
 	}
     }
=20
     return 0;
 #else
-    krb5_set_error_string(context, "no support for PKINIT compiled in");
+    krb5_set_error_message(context, EINVAL,
+			   N_("no support for PKINIT compiled in", ""));
     return EINVAL;
 #endif
 }
=20
+krb5_error_code KRB5_LIB_FUNCTION
+krb5_get_init_creds_opt_set_pkinit_user_certs(krb5_context context,
+					      krb5_get_init_creds_opt *opt,
+					      struct hx509_certs_data *certs)
+{
+#ifdef PKINIT
+    if (opt->opt_private =3D=3D NULL) {
+	krb5_set_error_message(context, EINVAL,
+			       N_("PKINIT: on non extendable opt", ""));
+	return EINVAL;
+    }
+    if (opt->opt_private->pk_init_ctx =3D=3D NULL) {
+	krb5_set_error_message(context, EINVAL,
+			       N_("PKINIT: on pkinit context", ""));
+	return EINVAL;
+    }
+
+    _krb5_pk_set_user_id(context, NULL, opt->opt_private->pk_init_ctx, cer=
ts);
+
+    return 0;
+#else
+    krb5_set_error_message(context, EINVAL,
+			   N_("no support for PKINIT compiled in", ""));
+    return EINVAL;
+#endif
+}
+
+#ifdef PKINIT
+
+static int
+get_ms_san(hx509_context context, hx509_cert cert, char **upn)
+{
+    hx509_octet_string_list list;
+    int ret;
+
+    *upn =3D NULL;
+
+    ret =3D hx509_cert_find_subjectAltName_otherName(context,
+						   cert,
+						   &asn1_oid_id_pkinit_ms_san,
+						   &list);
+    if (ret)
+	return 0;
+
+    if (list.len > 0 && list.val[0].length > 0)
+	ret =3D decode_MS_UPN_SAN(list.val[0].data, list.val[0].length,
+				upn, NULL);
+    else
+	ret =3D 1;
+    hx509_free_octet_string_list(&list);
+
+    return ret;
+}
+
+static int
+find_ms_san(hx509_context context, hx509_cert cert, void *ctx)
+{
+    char *upn;
+    int ret;
+
+    ret =3D get_ms_san(context, cert, &upn);
+    if (ret =3D=3D 0)
+	free(upn);
+    return ret;
+}
+
+
+
+#endif
+
 /*
- *
+ * Private since it need to be redesigned using krb5_get_init_creds()
  */
=20
-static void
-_krb5_pk_copy_error(krb5_context context,
-		    hx509_context hx509ctx,
-		    int hxret,
-		    const char *fmt,
-		    ...)
+KRB5_LIB_FUNCTION krb5_error_code  KRB5_LIB_CALL
+krb5_pk_enterprise_cert(krb5_context context,
+			const char *user_id,
+			krb5_const_realm realm,
+			krb5_principal *principal,
+			struct hx509_certs_data **res)
 {
-    va_list va;
-    char *s, *f;
+#ifdef PKINIT
+    krb5_error_code ret;
+    hx509_certs certs, result;
+    hx509_cert cert =3D NULL;
+    hx509_query *q;
+    char *name;
=20
-    va_start(va, fmt);
-    vasprintf(&f, fmt, va);
-    va_end(va);
-    if (f =3D=3D NULL) {
-	krb5_clear_error_string(context);
-	return;
+    *principal =3D NULL;
+    if (res)
+	*res =3D NULL;
+
+    if (user_id =3D=3D NULL) {
+	krb5_set_error_message(context, ENOENT, "no user id");
+	return ENOENT;
     }
=20
-    s =3D hx509_get_error_string(hx509ctx, hxret);
-    if (s =3D=3D NULL) {
-	krb5_clear_error_string(context);
-	free(f);
-	return;
+    ret =3D hx509_certs_init(context->hx509ctx, user_id, 0, NULL, &certs);
+    if (ret) {
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to init cert certs");
+	goto out;
     }
-    krb5_set_error_string(context, "%s: %s", f, s);
-    free(s);
-    free(f);
+
+    ret =3D hx509_query_alloc(context->hx509ctx, &q);
+    if (ret) {
+	krb5_set_error_message(context, ret, "out of memory");
+	hx509_certs_free(&certs);
+	goto out;
+    }
+
+    hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY);
+    hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE);
+    hx509_query_match_eku(q, &asn1_oid_id_pkinit_ms_eku);
+    hx509_query_match_cmp_func(q, find_ms_san, NULL);
+
+    ret =3D hx509_certs_filter(context->hx509ctx, certs, q, &result);
+    hx509_query_free(context->hx509ctx, q);
+    hx509_certs_free(&certs);
+    if (ret) {
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to find PKINIT certificate");
+	return ret;
+    }
+
+    ret =3D hx509_get_one_cert(context->hx509ctx, result, &cert);
+    hx509_certs_free(&result);
+    if (ret) {
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to get one cert");
+	goto out;
+    }
+
+    ret =3D get_ms_san(context->hx509ctx, cert, &name);
+    if (ret) {
+	pk_copy_error(context, context->hx509ctx, ret,
+		      "Failed to get MS SAN");
+	goto out;
+    }
+
+    ret =3D krb5_make_principal(context, principal, realm, name, NULL);
+    free(name);
+    if (ret)
+	goto out;
+
+    krb5_principal_set_type(context, *principal, KRB5_NT_ENTERPRISE_PRINCI=
PAL);
+
+    if (res) {
+	ret =3D hx509_certs_init(context->hx509ctx, "MEMORY:", 0, NULL, res);
+	if (ret)
+	    goto out;
+
+	ret =3D hx509_certs_add(context->hx509ctx, *res, cert);
+	if (ret) {
+	    hx509_certs_free(res);
+	    goto out;
+	}
+    }
+
+ out:
+    hx509_cert_free(cert);
+
+    return ret;
+#else
+    krb5_set_error_message(context, EINVAL,
+			   N_("no support for PKINIT compiled in", ""));
+    return EINVAL;
+#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/plugin.c
--- a/head/crypto/heimdal/lib/krb5/plugin.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/plugin.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-RCSID("$Id: plugin.c 22033 2007-11-10 10:39:47Z lha $");
+
 #ifdef HAVE_DLFCN_H
 #include <dlfcn.h>
 #endif
@@ -40,21 +40,36 @@
=20
 struct krb5_plugin {
     void *symbol;
-    void *dsohandle;
     struct krb5_plugin *next;
 };
=20
 struct plugin {
-    enum krb5_plugin_type type;
-    void *name;
-    void *symbol;
+    enum { DSO, SYMBOL } type;
+    union {
+	struct {
+	    char *path;
+	    void *dsohandle;
+	} dso;
+	struct {
+	    enum krb5_plugin_type type;
+	    char *name;
+	    char *symbol;
+	} symbol;
+    } u;
     struct plugin *next;
 };
=20
 static HEIMDAL_MUTEX plugin_mutex =3D HEIMDAL_MUTEX_INITIALIZER;
 static struct plugin *registered =3D NULL;
+static int plugins_needs_scan =3D 1;
=20
-static const char *plugin_dir =3D LIBDIR "/plugin/krb5";
+static const char *sysplugin_dirs[] =3D  {
+    LIBDIR "/plugin/krb5",
+#ifdef __APPLE__
+    "/System/Library/KerberosPlugins/KerberosFrameworkPlugins",
+#endif
+    NULL
+};
=20
 /*
  *
@@ -79,39 +94,30 @@
 #ifdef HAVE_DLOPEN
=20
 static krb5_error_code
-loadlib(krb5_context context,
-	enum krb5_plugin_type type,
-	const char *name,
-	const char *lib,
-	struct krb5_plugin **e)
+loadlib(krb5_context context, char *path)
 {
-    *e =3D calloc(1, sizeof(**e));
-    if (*e =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+    struct plugin *e;
+
+    e =3D calloc(1, sizeof(*e));
+    if (e =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	free(path);
 	return ENOMEM;
     }
=20
 #ifndef RTLD_LAZY
 #define RTLD_LAZY 0
 #endif
+#ifndef RTLD_LOCAL
+#define RTLD_LOCAL 0
+#endif
+    e->type =3D DSO;
+    /* ignore error from dlopen, and just keep it as negative cache entry =
*/
+    e->u.dso.dsohandle =3D dlopen(path, RTLD_LOCAL|RTLD_LAZY);
+    e->u.dso.path =3D path;
=20
-    (*e)->dsohandle =3D dlopen(lib, RTLD_LAZY);
-    if ((*e)->dsohandle =3D=3D NULL) {
-	free(*e);
-	*e =3D NULL;
-	krb5_set_error_string(context, "Failed to load %s: %s",=20
-			      lib, dlerror());
-	return ENOMEM;
-    }
-
-    /* dlsym doesn't care about the type */
-    (*e)->symbol =3D dlsym((*e)->dsohandle, name);
-    if ((*e)->symbol =3D=3D NULL) {
-	dlclose((*e)->dsohandle);
-	free(*e);
-	krb5_clear_error_string(context);
-	return ENOMEM;
-    }
+    e->next =3D registered;
+    registered =3D e;
=20
     return 0;
 }
@@ -129,29 +135,43 @@
  * @ingroup krb5_support
  */
=20
-krb5_error_code
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_plugin_register(krb5_context context,
 		     enum krb5_plugin_type type,
-		     const char *name,=20
+		     const char *name,
 		     void *symbol)
 {
     struct plugin *e;
=20
+    HEIMDAL_MUTEX_lock(&plugin_mutex);
+
+    /* check for duplicates */
+    for (e =3D registered; e !=3D NULL; e =3D e->next) {
+	if (e->type =3D=3D SYMBOL &&
+	    strcmp(e->u.symbol.name, name) =3D=3D 0 &&
+	    e->u.symbol.type =3D=3D type && e->u.symbol.symbol =3D=3D symbol) {
+	    HEIMDAL_MUTEX_unlock(&plugin_mutex);
+	    return 0;
+	}
+    }
+
     e =3D calloc(1, sizeof(*e));
     if (e =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	HEIMDAL_MUTEX_unlock(&plugin_mutex);
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
-    e->type =3D type;
-    e->name =3D strdup(name);
-    if (e->name =3D=3D NULL) {
+    e->type =3D SYMBOL;
+    e->u.symbol.type =3D type;
+    e->u.symbol.name =3D strdup(name);
+    if (e->u.symbol.name =3D=3D NULL) {
+	HEIMDAL_MUTEX_unlock(&plugin_mutex);
 	free(e);
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
 	return ENOMEM;
     }
-    e->symbol =3D symbol;
+    e->u.symbol.symbol =3D symbol;
=20
-    HEIMDAL_MUTEX_lock(&plugin_mutex);
     e->next =3D registered;
     registered =3D e;
     HEIMDAL_MUTEX_unlock(&plugin_mutex);
@@ -159,95 +179,191 @@
     return 0;
 }
=20
-krb5_error_code
-_krb5_plugin_find(krb5_context context,
-		  enum krb5_plugin_type type,
-		  const char *name,=20
-		  struct krb5_plugin **list)
+static int
+is_valid_plugin_filename(const char * n)
 {
-    struct krb5_plugin *e;
-    struct plugin *p;
+    if (n[0] =3D=3D '.' && (n[1] =3D=3D '\0' || (n[1] =3D=3D '.' && n[2] =
=3D=3D '\0')))
+        return 0;
+
+#ifdef _WIN32
+    /* On Windows, we only attempt to load .dll files as plug-ins. */
+    {
+        const char * ext;
+
+        ext =3D strrchr(n, '.');
+        if (ext =3D=3D NULL)
+            return 0;
+
+        return !stricmp(ext, ".dll");
+    }
+#else
+    return 1;
+#endif
+}
+
+static void
+trim_trailing_slash(char * path)
+{
+    size_t l;
+
+    l =3D strlen(path);
+    while (l > 0 && (path[l - 1] =3D=3D '/'
+#ifdef BACKSLASH_PATH_DELIM
+                     || path[l - 1] =3D=3D '\\'
+#endif
+               )) {
+        path[--l] =3D '\0';
+    }
+}
+
+static krb5_error_code
+load_plugins(krb5_context context)
+{
+    struct plugin *e;
     krb5_error_code ret;
-    char *sysdirs[2] =3D { NULL, NULL };
     char **dirs =3D NULL, **di;
     struct dirent *entry;
     char *path;
     DIR *d =3D NULL;
=20
+    if (!plugins_needs_scan)
+	return 0;
+    plugins_needs_scan =3D 0;
+
+#ifdef HAVE_DLOPEN
+
+    dirs =3D krb5_config_get_strings(context, NULL, "libdefaults",
+				   "plugin_dir", NULL);
+    if (dirs =3D=3D NULL)
+	dirs =3D rk_UNCONST(sysplugin_dirs);
+
+    for (di =3D dirs; *di !=3D NULL; di++) {
+        char * dir =3D *di;
+
+#ifdef KRB5_USE_PATH_TOKENS
+        if (_krb5_expand_path_tokens(context, *di, &dir))
+            goto next_dir;
+#endif
+
+        trim_trailing_slash(dir);
+
+        d =3D opendir(dir);
+
+	if (d =3D=3D NULL)
+	    goto next_dir;
+
+	rk_cloexec_dir(d);
+
+	while ((entry =3D readdir(d)) !=3D NULL) {
+	    char *n =3D entry->d_name;
+
+	    /* skip . and .. */
+            if (!is_valid_plugin_filename(n))
+		continue;
+
+	    path =3D NULL;
+	    ret =3D 0;
+#ifdef __APPLE__
+	    { /* support loading bundles on MacOS */
+		size_t len =3D strlen(n);
+		if (len > 7 && strcmp(&n[len - 7],  ".bundle") =3D=3D 0)
+		    ret =3D asprintf(&path, "%s/%s/Contents/MacOS/%.*s", dir, n, (int)(l=
en - 7), n);
+	    }
+#endif
+	    if (ret < 0 || path =3D=3D NULL)
+		ret =3D asprintf(&path, "%s/%s", dir, n);
+
+	    if (ret < 0 || path =3D=3D NULL) {
+		ret =3D ENOMEM;
+		krb5_set_error_message(context, ret, "malloc: out of memory");
+		return ret;
+	    }
+
+	    /* check if already tried */
+	    for (e =3D registered; e !=3D NULL; e =3D e->next)
+		if (e->type =3D=3D DSO && strcmp(e->u.dso.path, path) =3D=3D 0)
+		    break;
+	    if (e) {
+		free(path);
+	    } else {
+		loadlib(context, path); /* store or frees path */
+	    }
+	}
+	closedir(d);
+
+    next_dir:
+        if (dir !=3D *di)
+            free(dir);
+    }
+    if (dirs !=3D rk_UNCONST(sysplugin_dirs))
+	krb5_config_free_strings(dirs);
+#endif /* HAVE_DLOPEN */
+    return 0;
+}
+
+static krb5_error_code
+add_symbol(krb5_context context, struct krb5_plugin **list, void *symbol)
+{
+    struct krb5_plugin *e;
+
+    e =3D calloc(1, sizeof(*e));
+    if (e =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
+	return ENOMEM;
+    }
+    e->symbol =3D symbol;
+    e->next =3D *list;
+    *list =3D e;
+    return 0;
+}
+
+krb5_error_code
+_krb5_plugin_find(krb5_context context,
+		  enum krb5_plugin_type type,
+		  const char *name,
+		  struct krb5_plugin **list)
+{
+    struct plugin *e;
+    krb5_error_code ret;
+
     *list =3D NULL;
=20
     HEIMDAL_MUTEX_lock(&plugin_mutex);
=20
-    for (p =3D registered; p !=3D NULL; p =3D p->next) {
-	if (p->type !=3D type || strcmp(p->name, name) !=3D 0)
-	    continue;
+    load_plugins(context);
=20
-	e =3D calloc(1, sizeof(*e));
-	if (e =3D=3D NULL) {
-	    HEIMDAL_MUTEX_unlock(&plugin_mutex);
-	    krb5_set_error_string(context, "out of memory");
-	    ret =3D ENOMEM;
-	    goto out;
+    for (ret =3D 0, e =3D registered; e !=3D NULL; e =3D e->next) {
+	switch(e->type) {
+	case DSO: {
+	    void *sym;
+	    if (e->u.dso.dsohandle =3D=3D NULL)
+		continue;
+	    sym =3D dlsym(e->u.dso.dsohandle, name);
+	    if (sym)
+		ret =3D add_symbol(context, list, sym);
+	    break;
 	}
-	e->symbol =3D p->symbol;
-	e->dsohandle =3D NULL;
-	e->next =3D *list;
-	*list =3D e;
-    }
-    HEIMDAL_MUTEX_unlock(&plugin_mutex);
-
-#ifdef HAVE_DLOPEN
-
-    dirs =3D krb5_config_get_strings(context, NULL, "libdefaults",=20
-				   "plugin_dir", NULL);
-    if (dirs =3D=3D NULL) {
-	sysdirs[0] =3D rk_UNCONST(plugin_dir);
-	dirs =3D sysdirs;
+	case SYMBOL:
+	    if (strcmp(e->u.symbol.name, name) =3D=3D 0 && e->u.symbol.type =3D=
=3D type)
+		ret =3D add_symbol(context, list, e->u.symbol.symbol);
+	    break;
+	}
+	if (ret) {
+	    _krb5_plugin_free(*list);
+	    *list =3D NULL;
+	}
     }
=20
-    for (di =3D dirs; *di !=3D NULL; di++) {
-
-	d =3D opendir(*di);
-	if (d =3D=3D NULL)
-	    continue;
-
-	while ((entry =3D readdir(d)) !=3D NULL) {
-	    asprintf(&path, "%s/%s", *di, entry->d_name);
-	    if (path =3D=3D NULL) {
-		krb5_set_error_string(context, "out of memory");
-		ret =3D ENOMEM;
-		goto out;
-	    }
-	    ret =3D loadlib(context, type, name, path, &e);
-	    free(path);
-	    if (ret)
-		continue;
-	   =20
-	    e->next =3D *list;
-	    *list =3D e;
-	}
-	closedir(d);
-    }
-    if (dirs !=3D sysdirs)
-	krb5_config_free_strings(dirs);
-#endif /* HAVE_DLOPEN */
+    HEIMDAL_MUTEX_unlock(&plugin_mutex);
+    if (ret)
+	return ret;
=20
     if (*list =3D=3D NULL) {
-	krb5_set_error_string(context, "Did not find a plugin for %s", name);
+	krb5_set_error_message(context, ENOENT, "Did not find a plugin for %s", n=
ame);
 	return ENOENT;
     }
=20
     return 0;
-
-out:
-    if (dirs && dirs !=3D sysdirs)
-	krb5_config_free_strings(dirs);
-    if (d)
-	closedir(d);
-    _krb5_plugin_free(*list);
-    *list =3D NULL;
-
-    return ret;
 }
=20
 void
@@ -256,9 +372,264 @@
     struct krb5_plugin *next;
     while (list) {
 	next =3D list->next;
-	if (list->dsohandle)
-	    dlclose(list->dsohandle);
 	free(list);
 	list =3D next;
     }
 }
+/*
+ * module - dict of {
+ *      ModuleName =3D [
+ *          plugin =3D object{
+ *              array =3D { ptr, ctx }
+ *          }
+ *      ]
+ * }
+ */
+
+static heim_dict_t modules;
+
+struct plugin2 {
+    heim_string_t path;
+    void *dsohandle;
+    heim_dict_t names;
+};
+
+static void
+plug_dealloc(void *ptr)
+{
+    struct plugin2 *p =3D ptr;
+    heim_release(p->path);
+    heim_release(p->names);
+    if (p->dsohandle)
+	dlclose(p->dsohandle);
+}
+
+
+void
+_krb5_load_plugins(krb5_context context, const char *name, const char **pa=
ths)
+{
+#ifdef HAVE_DLOPEN
+    heim_string_t s =3D heim_string_create(name);
+    heim_dict_t module;
+    struct dirent *entry;
+    krb5_error_code ret;
+    const char **di;
+    DIR *d;
+
+    HEIMDAL_MUTEX_lock(&plugin_mutex);
+
+    if (modules =3D=3D NULL) {
+	modules =3D heim_dict_create(11);
+	if (modules =3D=3D NULL) {
+	    HEIMDAL_MUTEX_unlock(&plugin_mutex);
+	    return;
+	}
+    }
+
+    module =3D heim_dict_copy_value(modules, s);
+    if (module =3D=3D NULL) {
+	module =3D heim_dict_create(11);
+	if (module =3D=3D NULL) {
+	    HEIMDAL_MUTEX_unlock(&plugin_mutex);
+	    heim_release(s);
+	    return;
+	}
+	heim_dict_add_value(modules, s, module);
+    }
+    heim_release(s);
+
+    for (di =3D paths; *di !=3D NULL; di++) {
+	d =3D opendir(*di);
+	if (d =3D=3D NULL)
+	    continue;
+	rk_cloexec_dir(d);
+
+	while ((entry =3D readdir(d)) !=3D NULL) {
+	    char *n =3D entry->d_name;
+	    char *path =3D NULL;
+	    heim_string_t spath;
+	    struct plugin2 *p;
+
+	    /* skip . and .. */
+	    if (n[0] =3D=3D '.' && (n[1] =3D=3D '\0' || (n[1] =3D=3D '.' && n[2] =
=3D=3D '\0')))
+		continue;
+
+	    ret =3D 0;
+#ifdef __APPLE__
+	    { /* support loading bundles on MacOS */
+		size_t len =3D strlen(n);
+		if (len > 7 && strcmp(&n[len - 7],  ".bundle") =3D=3D 0)
+		    ret =3D asprintf(&path, "%s/%s/Contents/MacOS/%.*s", *di, n, (int)(l=
en - 7), n);
+	    }
+#endif
+	    if (ret < 0 || path =3D=3D NULL)
+		ret =3D asprintf(&path, "%s/%s", *di, n);
+
+	    if (ret < 0 || path =3D=3D NULL)
+		continue;
+
+	    spath =3D heim_string_create(n);
+	    if (spath =3D=3D NULL) {
+		free(path);
+		continue;
+	    }
+
+	    /* check if already cached */
+	    p =3D heim_dict_copy_value(module, spath);
+	    if (p =3D=3D NULL) {
+		p =3D heim_alloc(sizeof(*p), "krb5-plugin", plug_dealloc);
+		if (p)
+		    p->dsohandle =3D dlopen(path, RTLD_LOCAL|RTLD_LAZY);
+
+		if (p->dsohandle) {
+		    p->path =3D heim_retain(spath);
+		    p->names =3D heim_dict_create(11);
+		    heim_dict_add_value(module, spath, p);
+		}
+	    }
+	    heim_release(spath);
+	    heim_release(p);
+	    free(path);
+	}
+	closedir(d);
+    }
+    heim_release(module);
+    HEIMDAL_MUTEX_unlock(&plugin_mutex);
+#endif /* HAVE_DLOPEN */
+}
+
+void
+_krb5_unload_plugins(krb5_context context, const char *name)
+{
+    HEIMDAL_MUTEX_lock(&plugin_mutex);
+    heim_release(modules);
+    modules =3D NULL;
+    HEIMDAL_MUTEX_unlock(&plugin_mutex);
+}
+
+/*
+ *
+ */
+
+struct common_plugin_method {
+    int			version;
+    krb5_error_code	(*init)(krb5_context, void **);
+    void		(*fini)(void *);
+};
+
+struct plug {
+    void *dataptr;
+    void *ctx;
+};
+
+static void
+plug_free(void *ptr)
+{
+    struct plug *pl =3D ptr;
+    if (pl->dataptr) {
+	struct common_plugin_method *cpm =3D pl->dataptr;
+	cpm->fini(pl->ctx);
+    }
+}
+
+struct iter_ctx {
+    krb5_context context;
+    heim_string_t n;
+    const char *name;
+    int min_version;
+    heim_array_t result;
+    krb5_error_code (*func)(krb5_context, const void *, void *, void *);
+    void *userctx;
+    krb5_error_code ret;
+};
+
+static void
+search_modules(void *ctx, heim_object_t key, heim_object_t value)
+{
+    struct iter_ctx *s =3D ctx;
+    struct plugin2 *p =3D value;
+    struct plug *pl =3D heim_dict_copy_value(p->names, s->n);
+    struct common_plugin_method *cpm;
+
+    if (pl =3D=3D NULL) {
+	if (p->dsohandle =3D=3D NULL)
+	    return;
+
+	pl =3D heim_alloc(sizeof(*pl), "struct-plug", plug_free);
+
+	cpm =3D pl->dataptr =3D dlsym(p->dsohandle, s->name);
+	if (cpm) {
+	    int ret;
+
+	    ret =3D cpm->init(s->context, &pl->ctx);
+	    if (ret)
+		cpm =3D pl->dataptr =3D NULL;
+	}
+	heim_dict_add_value(p->names, s->n, pl);
+    } else {
+	cpm =3D pl->dataptr;
+    }
+
+    if (cpm && cpm->version >=3D s->min_version)
+	heim_array_append_value(s->result, pl);
+
+    heim_release(pl);
+}
+
+static void
+eval_results(heim_object_t value, void *ctx)
+{
+    struct plug *pl =3D value;
+    struct iter_ctx *s =3D ctx;
+
+    if (s->ret !=3D KRB5_PLUGIN_NO_HANDLE)
+	return;
+
+    s->ret =3D s->func(s->context, pl->dataptr, pl->ctx, s->userctx);
+}
+
+krb5_error_code
+_krb5_plugin_run_f(krb5_context context,
+		   const char *module,
+		   const char *name,
+		   int min_version,
+		   int flags,
+		   void *userctx,
+		   krb5_error_code (*func)(krb5_context, const void *, void *, void *))
+{
+    heim_string_t m =3D heim_string_create(module);
+    heim_dict_t dict;
+    struct iter_ctx s;
+
+    HEIMDAL_MUTEX_lock(&plugin_mutex);
+
+    dict =3D heim_dict_copy_value(modules, m);
+    heim_release(m);
+    if (dict =3D=3D NULL) {
+	HEIMDAL_MUTEX_unlock(&plugin_mutex);
+	return KRB5_PLUGIN_NO_HANDLE;
+    }
+
+    s.context =3D context;
+    s.name =3D name;
+    s.n =3D heim_string_create(name);
+    s.min_version =3D min_version;
+    s.result =3D heim_array_create();
+    s.func =3D func;
+    s.userctx =3D userctx;
+
+    heim_dict_iterate_f(dict, search_modules, &s);
+
+    heim_release(dict);
+
+    HEIMDAL_MUTEX_unlock(&plugin_mutex);
+
+    s.ret =3D KRB5_PLUGIN_NO_HANDLE;
+
+    heim_array_iterate_f(s.result, eval_results, &s);
+
+    heim_release(s.result);
+    heim_release(s.n);
+
+    return s.ret;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/principal=
.c
--- a/head/crypto/heimdal/lib/krb5/principal.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/principal.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,34 +1,50 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/**
+ * @page krb5_principal_intro The principal handing functions.
+ *
+ * A Kerberos principal is a email address looking string that
+ * contains to parts separeted by a @.  The later part is the kerbero
+ * realm the principal belongs to and the former is a list of 0 or
+ * more components. For example
+ * @verbatim
+lha at SU.SE
+host/hummel.it.su.se at SU.SE
+host/admin at H5L.ORG
+ at endverbatim
+ *
+ * See the library functions here: @ref krb5_principal
  */
=20
 #include "krb5_locl.h"
@@ -41,15 +57,26 @@
 #include <fnmatch.h>
 #include "resolve.h"
=20
-RCSID("$Id: principal.c 21741 2007-07-31 16:00:37Z lha $");
-
 #define princ_num_comp(P) ((P)->name.name_string.len)
 #define princ_type(P) ((P)->name.name_type)
 #define princ_comp(P) ((P)->name.name_string.val)
 #define princ_ncomp(P, N) ((P)->name.name_string.val[(N)])
 #define princ_realm(P) ((P)->realm)
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Frees a Kerberos principal allocated by the library with
+ * krb5_parse_name(), krb5_make_principal() or any other related
+ * principal functions.
+ *
+ * @param context A Kerberos context.
+ * @param p a principal to free.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_principal(krb5_context context,
 		    krb5_principal p)
 {
@@ -59,7 +86,19 @@
     }
 }
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Set the type of the principal
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to set the type for
+ * @param type the new type
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_principal_set_type(krb5_context context,
 			krb5_principal principal,
 			int type)
@@ -67,21 +106,43 @@
     princ_type(principal) =3D type;
 }
=20
-int KRB5_LIB_FUNCTION
+/**
+ * Get the type of the principal
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to get the type for
+ *
+ * @return the type of principal
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_principal_get_type(krb5_context context,
 			krb5_const_principal principal)
 {
     return princ_type(principal);
 }
=20
-const char* KRB5_LIB_FUNCTION
+/**
+ * Get the realm of the principal
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to get the realm for
+ *
+ * @return realm of the principal, don't free or use after krb5_principal =
is freed
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_principal_get_realm(krb5_context context,
 			 krb5_const_principal principal)
 {
     return princ_realm(principal);
-}			=20
+}
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_principal_get_comp_string(krb5_context context,
 			       krb5_const_principal principal,
 			       unsigned int component)
@@ -91,7 +152,38 @@
     return princ_ncomp(principal, component);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Get number of component is principal.
+ *
+ * @param context Kerberos 5 context
+ * @param principal principal to query
+ *
+ * @return number of components in string
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION unsigned int KRB5_LIB_CALL
+krb5_principal_get_num_comp(krb5_context context,
+			    krb5_const_principal principal)
+{
+    return princ_num_comp(principal);
+}
+
+/**
+ * Parse a name into a krb5_principal structure, flags controls the behavi=
or.
+ *
+ * @param context Kerberos 5 context
+ * @param name name to parse into a Kerberos principal
+ * @param flags flags to control the behavior
+ * @param principal returned principal, free with krb5_free_principal().
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_name_flags(krb5_context context,
 		      const char *name,
 		      int flags,
@@ -112,14 +204,15 @@
     int got_realm =3D 0;
     int first_at =3D 1;
     int enterprise =3D (flags & KRB5_PRINCIPAL_PARSE_ENTERPRISE);
- =20
+
     *principal =3D NULL;
=20
-#define RFLAGS (KRB5_PRINCIPAL_PARSE_NO_REALM|KRB5_PRINCIPAL_PARSE_MUST_RE=
ALM)
+#define RFLAGS (KRB5_PRINCIPAL_PARSE_NO_REALM|KRB5_PRINCIPAL_PARSE_REQUIRE=
_REALM)
=20
     if ((flags & RFLAGS) =3D=3D RFLAGS) {
-	krb5_set_error_string(context, "Can't require both realm and "
-			      "no realm at the same time");
+	krb5_set_error_message(context, KRB5_ERR_NO_SERVICE,
+			       N_("Can't require both realm and "
+				  "no realm at the same time", ""));
 	return KRB5_ERR_NO_SERVICE;
     }
 #undef RFLAGS
@@ -132,8 +225,8 @@
 	for(p =3D name; *p; p++){
 	    if(*p=3D=3D'\\'){
 		if(!p[1]) {
-		    krb5_set_error_string (context,
-					   "trailing \\ in principal name");
+		    krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
+					   N_("trailing \\ in principal name", ""));
 		    return KRB5_PARSE_MALFORMED;
 		}
 		p++;
@@ -145,15 +238,17 @@
     }
     comp =3D calloc(ncomp, sizeof(*comp));
     if (comp =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
- =20
+
     n =3D 0;
     p =3D start =3D q =3D s =3D strdup(name);
     if (start =3D=3D NULL) {
 	free (comp);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     while(*p){
@@ -169,9 +264,9 @@
 	    else if(c =3D=3D '0')
 		c =3D '\0';
 	    else if(c =3D=3D '\0') {
-		krb5_set_error_string (context,
-				       "trailing \\ in principal name");
 		ret =3D KRB5_PARSE_MALFORMED;
+		krb5_set_error_message(context, ret,
+				       N_("trailing \\ in principal name", ""));
 		goto exit;
 	    }
 	}else if(enterprise && first_at) {
@@ -179,15 +274,16 @@
 		first_at =3D 0;
 	}else if((c =3D=3D '/' && !enterprise) || c =3D=3D '@'){
 	    if(got_realm){
-		krb5_set_error_string (context,
-				       "part after realm in principal name");
 		ret =3D KRB5_PARSE_MALFORMED;
+		krb5_set_error_message(context, ret,
+				       N_("part after realm in principal name", ""));
 		goto exit;
 	    }else{
 		comp[n] =3D malloc(q - start + 1);
 		if (comp[n] =3D=3D NULL) {
-		    krb5_set_error_string (context, "malloc: out of memory");
 		    ret =3D ENOMEM;
+		    krb5_set_error_message(context, ret,
+					   N_("malloc: out of memory", ""));
 		    goto exit;
 		}
 		memcpy(comp[n], start, q - start);
@@ -199,34 +295,37 @@
 	    start =3D q;
 	    continue;
 	}
-	if(got_realm && (c =3D=3D ':' || c =3D=3D '/' || c =3D=3D '\0')) {
-	    krb5_set_error_string (context,
-				   "part after realm in principal name");
+	if(got_realm && (c =3D=3D '/' || c =3D=3D '\0')) {
 	    ret =3D KRB5_PARSE_MALFORMED;
+	    krb5_set_error_message(context, ret,
+				   N_("part after realm in principal name", ""));
 	    goto exit;
 	}
 	*q++ =3D c;
     }
     if(got_realm){
 	if (flags & KRB5_PRINCIPAL_PARSE_NO_REALM) {
-	    krb5_set_error_string (context, "realm found in 'short' principal "
-				   "expected to be without one");
 	    ret =3D KRB5_PARSE_MALFORMED;
+	    krb5_set_error_message(context, ret,
+				   N_("realm found in 'short' principal "
+				      "expected to be without one", ""));
 	    goto exit;
 	}
 	realm =3D malloc(q - start + 1);
 	if (realm =3D=3D NULL) {
-	    krb5_set_error_string (context, "malloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto exit;
 	}
 	memcpy(realm, start, q - start);
 	realm[q - start] =3D 0;
     }else{
-	if (flags & KRB5_PRINCIPAL_PARSE_MUST_REALM) {
-	    krb5_set_error_string (context, "realm NOT found in principal "
-				   "expected to be with one");
+	if (flags & KRB5_PRINCIPAL_PARSE_REQUIRE_REALM) {
 	    ret =3D KRB5_PARSE_MALFORMED;
+	    krb5_set_error_message(context, ret,
+				   N_("realm NOT found in principal "
+				      "expected to be with one", ""));
 	    goto exit;
 	} else if (flags & KRB5_PRINCIPAL_PARSE_NO_REALM) {
 	    realm =3D NULL;
@@ -238,8 +337,9 @@
=20
 	comp[n] =3D malloc(q - start + 1);
 	if (comp[n] =3D=3D NULL) {
-	    krb5_set_error_string (context, "malloc: out of memory");
 	    ret =3D ENOMEM;
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto exit;
 	}
 	memcpy(comp[n], start, q - start);
@@ -248,8 +348,9 @@
     }
     *principal =3D malloc(sizeof(**principal));
     if (*principal =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
 	ret =3D ENOMEM;
+	krb5_set_error_message(context, ret,
+			       N_("malloc: out of memory", ""));
 	goto exit;
     }
     if (enterprise)
@@ -271,7 +372,19 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Parse a name into a krb5_principal structure
+ *
+ * @param context Kerberos 5 context
+ * @param name name to parse into a Kerberos principal
+ * @param principal returned principal, free with krb5_free_principal().
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_name(krb5_context context,
 		const char *name,
 		krb5_principal *principal)
@@ -313,14 +426,15 @@
 		   int flags)
 {
     size_t idx =3D 0;
-    int i;
+    size_t i;
     int short_form =3D (flags & KRB5_PRINCIPAL_UNPARSE_SHORT) !=3D 0;
     int no_realm =3D (flags & KRB5_PRINCIPAL_UNPARSE_NO_REALM) !=3D 0;
     int display =3D (flags & KRB5_PRINCIPAL_UNPARSE_DISPLAY) !=3D 0;
=20
     if (!no_realm && princ_realm(principal) =3D=3D NULL) {
-	krb5_set_error_string(context, "Realm missing from principal, "
-			      "can't unparse");
+	krb5_set_error_message(context, ERANGE,
+			       N_("Realm missing from principal, "
+				  "can't unparse", ""));
 	return ERANGE;
     }
=20
@@ -329,10 +443,11 @@
 	    add_char(name, idx, len, '/');
 	idx =3D quote_string(princ_ncomp(principal, i), name, idx, len, display);
 	if(idx =3D=3D len) {
-	    krb5_set_error_string(context, "Out of space printing principal");
+	    krb5_set_error_message(context, ERANGE,
+				   N_("Out of space printing principal", ""));
 	    return ERANGE;
 	}
-    }=20
+    }
     /* add realm if different from default realm */
     if(short_form && !no_realm) {
 	krb5_realm r;
@@ -348,15 +463,29 @@
 	add_char(name, idx, len, '@');
 	idx =3D quote_string(princ_realm(principal), name, idx, len, display);
 	if(idx =3D=3D len) {
-	    krb5_set_error_string(context,=20
-				  "Out of space printing realm of principal");
+	    krb5_set_error_message(context, ERANGE,
+				   N_("Out of space printing "
+				      "realm of principal", ""));
 	    return ERANGE;
 	}
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Unparse the principal name to a fixed buffer
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param name buffer to write name to
+ * @param len length of buffer
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_fixed(krb5_context context,
 			krb5_const_principal principal,
 			char *name,
@@ -365,17 +494,45 @@
     return unparse_name_fixed(context, principal, name, len, 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Unparse the principal name to a fixed buffer. The realm is skipped
+ * if its a default realm.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param name buffer to write name to
+ * @param len length of buffer
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_fixed_short(krb5_context context,
 			      krb5_const_principal principal,
 			      char *name,
 			      size_t len)
 {
-    return unparse_name_fixed(context, principal, name, len,=20
+    return unparse_name_fixed(context, principal, name, len,
 			      KRB5_PRINCIPAL_UNPARSE_SHORT);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Unparse the principal name with unparse flags to a fixed buffer.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param flags unparse flags
+ * @param name buffer to write name to
+ * @param len length of buffer
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_fixed_flags(krb5_context context,
 			      krb5_const_principal principal,
 			      int flags,
@@ -392,7 +549,7 @@
 	     int flags)
 {
     size_t len =3D 0, plen;
-    int i;
+    size_t i;
     krb5_error_code ret;
     /* count length */
     if (princ_realm(principal)) {
@@ -415,7 +572,8 @@
     len++; /* '\0' */
     *name =3D malloc(len);
     if(*name =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     ret =3D unparse_name_fixed(context, principal, *name, len, flags);
@@ -426,7 +584,19 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Unparse the Kerberos name into a string
+ *
+ * @param context Kerberos 5 context
+ * @param principal principal to query
+ * @param name resulting string, free with krb5_xfree()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name(krb5_context context,
 		  krb5_const_principal principal,
 		  char **name)
@@ -434,7 +604,20 @@
     return unparse_name(context, principal, name, 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Unparse the Kerberos name into a string
+ *
+ * @param context Kerberos 5 context
+ * @param principal principal to query
+ * @param flags flag to determine the behavior
+ * @param name resulting string, free with krb5_xfree()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_flags(krb5_context context,
 			krb5_const_principal principal,
 			int flags,
@@ -443,7 +626,20 @@
     return unparse_name(context, principal, name, flags);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Unparse the principal name to a allocated buffer. The realm is
+ * skipped if its a default realm.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal to unparse
+ * @param name returned buffer, free with krb5_xfree()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_unparse_name_short(krb5_context context,
 			krb5_const_principal principal,
 			char **name)
@@ -451,37 +647,52 @@
     return unparse_name(context, principal, name, KRB5_PRINCIPAL_UNPARSE_S=
HORT);
 }
=20
-#if 0 /* not implemented */
+/**
+ * Set a new realm for a principal, and as a side-effect free the
+ * previous realm.
+ *
+ * @param context A Kerberos context.
+ * @param principal principal set the realm for
+ * @param realm the new realm to set
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_unparse_name_ext(krb5_context context,
-		      krb5_const_principal principal,
-		      char **name,
-		      size_t *size)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_principal_set_realm(krb5_context context,
+			 krb5_principal principal,
+			 krb5_const_realm realm)
 {
-    krb5_abortx(context, "unimplemented krb5_unparse_name_ext called");
+    if (princ_realm(principal))
+	free(princ_realm(principal));
+
+    princ_realm(principal) =3D strdup(realm);
+    if (princ_realm(principal) =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
+    return 0;
 }
=20
-#endif
+#ifndef HEIMDAL_SMALLER
+/**
+ * Build a principal using vararg style building
+ *
+ * @param context A Kerberos context.
+ * @param principal returned principal
+ * @param rlen length of realm
+ * @param realm realm name
+ * @param ... a list of components ended with NULL.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
=20
-krb5_realm * KRB5_LIB_FUNCTION
-krb5_princ_realm(krb5_context context,
-		 krb5_principal principal)
-{
-    return &princ_realm(principal);
-}
-
-
-void KRB5_LIB_FUNCTION
-krb5_princ_set_realm(krb5_context context,
-		     krb5_principal principal,
-		     krb5_realm *realm)
-{
-    princ_realm(principal) =3D *realm;
-}
-
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_principal(krb5_context context,
 		     krb5_principal *principal,
 		     int rlen,
@@ -495,9 +706,46 @@
     va_end(ap);
     return ret;
 }
+#endif
+
+/**
+ * Build a principal using vararg style building
+ *
+ * @param context A Kerberos context.
+ * @param principal returned principal
+ * @param realm realm name
+ * @param ... a list of components ended with NULL.
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_make_principal(krb5_context context,
+		    krb5_principal *principal,
+		    krb5_const_realm realm,
+		    ...)
+{
+    krb5_error_code ret;
+    krb5_realm r =3D NULL;
+    va_list ap;
+    if(realm =3D=3D NULL) {
+	ret =3D krb5_get_default_realm(context, &r);
+	if(ret)
+	    return ret;
+	realm =3D r;
+    }
+    va_start(ap, realm);
+    ret =3D krb5_build_principal_va(context, principal, strlen(realm), rea=
lm, ap);
+    va_end(ap);
+    if(r)
+	free(r);
+    return ret;
+}
=20
 static krb5_error_code
-append_component(krb5_context context, krb5_principal p,=20
+append_component(krb5_context context, krb5_principal p,
 		 const char *comp,
 		 size_t comp_len)
 {
@@ -506,13 +754,15 @@
=20
     tmp =3D realloc(princ_comp(p), (len + 1) * sizeof(*tmp));
     if(tmp =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     princ_comp(p) =3D tmp;
     princ_ncomp(p, len) =3D malloc(comp_len + 1);
     if (princ_ncomp(p, len) =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     memcpy (princ_ncomp(p, len), comp, comp_len);
@@ -547,7 +797,6 @@
     }
 }
=20
-
 static krb5_error_code
 build_principal(krb5_context context,
 		krb5_principal *principal,
@@ -557,10 +806,11 @@
 		va_list ap)
 {
     krb5_principal p;
- =20
+
     p =3D calloc(1, sizeof(*p));
     if (p =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     princ_type(p) =3D KRB5_NT_PRINCIPAL;
@@ -568,41 +818,19 @@
     princ_realm(p) =3D strdup(realm);
     if(p->realm =3D=3D NULL){
 	free(p);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
- =20
+
     (*func)(context, p, ap);
     *principal =3D p;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_make_principal(krb5_context context,
-		    krb5_principal *principal,
-		    krb5_const_realm realm,
-		    ...)
-{
-    krb5_error_code ret;
-    krb5_realm r =3D NULL;
-    va_list ap;
-    if(realm =3D=3D NULL) {
-	ret =3D krb5_get_default_realm(context, &r);
-	if(ret)
-	    return ret;
-	realm =3D r;
-    }
-    va_start(ap, realm);
-    ret =3D krb5_build_principal_va(context, principal, strlen(realm), rea=
lm, ap);
-    va_end(ap);
-    if(r)
-	free(r);
-    return ret;
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_build_principal_va(krb5_context context,=20
-			krb5_principal *principal,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_build_principal_va(krb5_context context,
+			krb5_principal *principal,
 			int rlen,
 			krb5_const_realm realm,
 			va_list ap)
@@ -610,9 +838,9 @@
     return build_principal(context, principal, rlen, realm, va_princ, ap);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_build_principal_va_ext(krb5_context context,=20
-			    krb5_principal *principal,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_build_principal_va_ext(krb5_context context,
+			    krb5_principal *principal,
 			    int rlen,
 			    krb5_const_realm realm,
 			    va_list ap)
@@ -621,7 +849,7 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_build_principal_ext(krb5_context context,
 			 krb5_principal *principal,
 			 int rlen,
@@ -636,36 +864,60 @@
     return ret;
 }
=20
+/**
+ * Copy a principal
+ *
+ * @param context A Kerberos context.
+ * @param inprinc principal to copy
+ * @param outprinc copied principal, free with krb5_free_principal()
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_principal(krb5_context context,
 		    krb5_const_principal inprinc,
 		    krb5_principal *outprinc)
 {
     krb5_principal p =3D malloc(sizeof(*p));
     if (p =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     if(copy_Principal(inprinc, p)) {
 	free(p);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     *outprinc =3D p;
     return 0;
 }
=20
-/*
- * return TRUE iff princ1 =3D=3D princ2 (without considering the realm)
+/**
+ * Return TRUE iff princ1 =3D=3D princ2 (without considering the realm)
+ *
+ * @param context Kerberos 5 context
+ * @param princ1 first principal to compare
+ * @param princ2 second principal to compare
+ *
+ * @return non zero if equal, 0 if not
+ *
+ * @ingroup krb5_principal
+ * @see krb5_principal_compare()
+ * @see krb5_realm_compare()
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_principal_compare_any_realm(krb5_context context,
 				 krb5_const_principal princ1,
 				 krb5_const_principal princ2)
 {
-    int i;
+    size_t i;
     if(princ_num_comp(princ1) !=3D princ_num_comp(princ2))
 	return FALSE;
     for(i =3D 0; i < princ_num_comp(princ1); i++){
@@ -675,11 +927,40 @@
     return TRUE;
 }
=20
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+_krb5_principal_compare_PrincipalName(krb5_context context,
+				      krb5_const_principal princ1,
+				      PrincipalName *princ2)
+{
+    size_t i;
+    if (princ_num_comp(princ1) !=3D princ2->name_string.len)
+	return FALSE;
+    for(i =3D 0; i < princ_num_comp(princ1); i++){
+	if(strcmp(princ_ncomp(princ1, i), princ2->name_string.val[i]) !=3D 0)
+	    return FALSE;
+    }
+    return TRUE;
+}
+
+
+/**
+ * Compares the two principals, including realm of the principals and retu=
rns
+ * TRUE if they are the same and FALSE if not.
+ *
+ * @param context Kerberos 5 context
+ * @param princ1 first principal to compare
+ * @param princ2 second principal to compare
+ *
+ * @ingroup krb5_principal
+ * @see krb5_principal_compare_any_realm()
+ * @see krb5_realm_compare()
+ */
+
 /*
  * return TRUE iff princ1 =3D=3D princ2
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_principal_compare(krb5_context context,
 		       krb5_const_principal princ1,
 		       krb5_const_principal princ2)
@@ -689,11 +970,19 @@
     return krb5_principal_compare_any_realm(context, princ1, princ2);
 }
=20
-/*
+/**
  * return TRUE iff realm(princ1) =3D=3D realm(princ2)
+ *
+ * @param context Kerberos 5 context
+ * @param princ1 first principal to compare
+ * @param princ2 second principal to compare
+ *
+ * @ingroup krb5_principal
+ * @see krb5_principal_compare_any_realm()
+ * @see krb5_principal_compare()
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_realm_compare(krb5_context context,
 		   krb5_const_principal princ1,
 		   krb5_const_principal princ2)
@@ -701,16 +990,18 @@
     return strcmp(princ_realm(princ1), princ_realm(princ2)) =3D=3D 0;
 }
=20
-/*
+/**
  * return TRUE iff princ matches pattern
+ *
+ * @ingroup krb5_principal
  */
=20
-krb5_boolean KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_principal_match(krb5_context context,
 		     krb5_const_principal princ,
 		     krb5_const_principal pattern)
 {
-    int i;
+    size_t i;
     if(princ_num_comp(princ) !=3D princ_num_comp(pattern))
 	return FALSE;
     if(fnmatch(princ_realm(pattern), princ_realm(princ), 0) !=3D 0)
@@ -722,461 +1013,23 @@
     return TRUE;
 }
=20
-
-static struct v4_name_convert {
-    const char *from;
-    const char *to;=20
-} default_v4_name_convert[] =3D {
-    { "ftp",	"ftp" },
-    { "hprop",	"hprop" },
-    { "pop",	"pop" },
-    { "imap",	"imap" },
-    { "rcmd",	"host" },
-    { "smtp",	"smtp" },
-    { NULL, NULL }
-};
-
-/*
- * return the converted instance name of `name' in `realm'.
- * look in the configuration file and then in the default set above.
- * return NULL if no conversion is appropriate.
+/**
+ * Create a principal for the service running on hostname. If
+ * KRB5_NT_SRV_HST is used, the hostname is canonization using DNS (or
+ * some other service), this is potentially insecure.
+ *
+ * @param context A Kerberos context.
+ * @param hostname hostname to use
+ * @param sname Service name to use
+ * @param type name type of pricipal, use KRB5_NT_SRV_HST or KRB5_NT_UNKNO=
WN.
+ * @param ret_princ return principal, free with krb5_free_principal().
+ *
+ * @return An krb5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_principal
  */
=20
-static const char*
-get_name_conversion(krb5_context context, const char *realm, const char *n=
ame)
-{
-    struct v4_name_convert *q;
-    const char *p;
-
-    p =3D krb5_config_get_string(context, NULL, "realms", realm,
-			       "v4_name_convert", "host", name, NULL);
-    if(p =3D=3D NULL)
-	p =3D krb5_config_get_string(context, NULL, "libdefaults",=20
-				   "v4_name_convert", "host", name, NULL);
-    if(p)
-	return p;
-
-    /* XXX should be possible to override default list */
-    p =3D krb5_config_get_string(context, NULL,
-			       "realms",
-			       realm,
-			       "v4_name_convert",
-			       "plain",
-			       name,
-			       NULL);
-    if(p)
-	return NULL;
-    p =3D krb5_config_get_string(context, NULL,
-			       "libdefaults",
-			       "v4_name_convert",
-			       "plain",
-			       name,
-			       NULL);
-    if(p)
-	return NULL;
-    for(q =3D default_v4_name_convert; q->from; q++)
-	if(strcmp(q->from, name) =3D=3D 0)
-	    return q->to;
-    return NULL;
-}
-
-/*
- * convert the v4 principal `name.instance at realm' to a v5 principal in `pr=
inc'.
- * if `resolve', use DNS.
- * if `func', use that function for validating the conversion
- */
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_425_conv_principal_ext2(krb5_context context,
-			     const char *name,
-			     const char *instance,
-			     const char *realm,
-			     krb5_boolean (*func)(krb5_context,=20
-						  void *, krb5_principal),
-			     void *funcctx,
-			     krb5_boolean resolve,
-			     krb5_principal *princ)
-{
-    const char *p;
-    krb5_error_code ret;
-    krb5_principal pr;
-    char host[MAXHOSTNAMELEN];
-    char local_hostname[MAXHOSTNAMELEN];
-
-    /* do the following: if the name is found in the
-       `v4_name_convert:host' part, is assumed to be a `host' type
-       principal, and the instance is looked up in the
-       `v4_instance_convert' part. if not found there the name is
-       (optionally) looked up as a hostname, and if that doesn't yield
-       anything, the `default_domain' is appended to the instance
-       */
-
-    if(instance =3D=3D NULL)
-	goto no_host;
-    if(instance[0] =3D=3D 0){
-	instance =3D NULL;
-	goto no_host;
-    }
-    p =3D get_name_conversion(context, realm, name);
-    if(p =3D=3D NULL)
-	goto no_host;
-    name =3D p;
-    p =3D krb5_config_get_string(context, NULL, "realms", realm,=20
-			       "v4_instance_convert", instance, NULL);
-    if(p){
-	instance =3D p;
-	ret =3D krb5_make_principal(context, &pr, realm, name, instance, NULL);
-	if(func =3D=3D NULL || (*func)(context, funcctx, pr)){
-	    *princ =3D pr;
-	    return 0;
-	}
-	krb5_free_principal(context, pr);
-	*princ =3D NULL;
-	krb5_clear_error_string (context);
-	return HEIM_ERR_V4_PRINC_NO_CONV;
-    }
-    if(resolve){
-	krb5_boolean passed =3D FALSE;
-	char *inst =3D NULL;
-#ifdef USE_RESOLVER
-	struct dns_reply *r;
-
-	r =3D dns_lookup(instance, "aaaa");
-	if (r) {
-	    if (r->head && r->head->type =3D=3D T_AAAA) {
-		inst =3D strdup(r->head->domain);
-		passed =3D TRUE;
-	    }
-	    dns_free_data(r);
-	} else {
-	    r =3D dns_lookup(instance, "a");
-	    if (r) {
-		if(r->head && r->head->type =3D=3D T_A) {
-		    inst =3D strdup(r->head->domain);
-		    passed =3D TRUE;
-		}
-		dns_free_data(r);
-	    }
-	}
-#else
-	struct addrinfo hints, *ai;
-=09
-	memset (&hints, 0, sizeof(hints));
-	hints.ai_flags =3D AI_CANONNAME;
-	ret =3D getaddrinfo(instance, NULL, &hints, &ai);
-	if (ret =3D=3D 0) {
-	    const struct addrinfo *a;
-	    for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
-		if (a->ai_canonname !=3D NULL) {
-		    inst =3D strdup (a->ai_canonname);
-		    passed =3D TRUE;
-		    break;
-		}
-	    }
-	    freeaddrinfo (ai);
-	}
-#endif
-	if (passed) {
-	    if (inst =3D=3D NULL) {
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
-	    }
-	    strlwr(inst);
-	    ret =3D krb5_make_principal(context, &pr, realm, name, inst,
-				      NULL);
-	    free (inst);
-	    if(ret =3D=3D 0) {
-		if(func =3D=3D NULL || (*func)(context, funcctx, pr)){
-		    *princ =3D pr;
-		    return 0;
-		}
-		krb5_free_principal(context, pr);
-	    }
-	}
-    }
-    if(func !=3D NULL) {
-	snprintf(host, sizeof(host), "%s.%s", instance, realm);
-	strlwr(host);
-	ret =3D krb5_make_principal(context, &pr, realm, name, host, NULL);
-	if((*func)(context, funcctx, pr)){
-	    *princ =3D pr;
-	    return 0;
-	}
-	krb5_free_principal(context, pr);
-    }
-
-    /*
-     * if the instance is the first component of the local hostname,
-     * the converted host should be the long hostname.
-     */
-
-    if (func =3D=3D NULL &&=20
-        gethostname (local_hostname, sizeof(local_hostname)) =3D=3D 0 &&
-        strncmp(instance, local_hostname, strlen(instance)) =3D=3D 0 &&=20
-	local_hostname[strlen(instance)] =3D=3D '.') {
-	strlcpy(host, local_hostname, sizeof(host));
-	goto local_host;
-    }
-
-    {
-	char **domains, **d;
-	domains =3D krb5_config_get_strings(context, NULL, "realms", realm,
-					  "v4_domains", NULL);
-	for(d =3D domains; d && *d; d++){
-	    snprintf(host, sizeof(host), "%s.%s", instance, *d);
-	    ret =3D krb5_make_principal(context, &pr, realm, name, host, NULL);
-	    if(func =3D=3D NULL || (*func)(context, funcctx, pr)){
-		*princ =3D pr;
-		krb5_config_free_strings(domains);
-		return 0;
-	    }
-	    krb5_free_principal(context, pr);
-	}
-	krb5_config_free_strings(domains);
-    }
-
-   =20
-    p =3D krb5_config_get_string(context, NULL, "realms", realm,=20
-			       "default_domain", NULL);
-    if(p =3D=3D NULL){
-	/* this should be an error, just faking a name is not good */
-	krb5_clear_error_string (context);
-	return HEIM_ERR_V4_PRINC_NO_CONV;
-    }
-=09
-    if (*p =3D=3D '.')
-	++p;
-    snprintf(host, sizeof(host), "%s.%s", instance, p);
-local_host:
-    ret =3D krb5_make_principal(context, &pr, realm, name, host, NULL);
-    if(func =3D=3D NULL || (*func)(context, funcctx, pr)){
-	*princ =3D pr;
-	return 0;
-    }
-    krb5_free_principal(context, pr);
-    krb5_clear_error_string (context);
-    return HEIM_ERR_V4_PRINC_NO_CONV;
-no_host:
-    p =3D krb5_config_get_string(context, NULL,
-			       "realms",
-			       realm,
-			       "v4_name_convert",
-			       "plain",
-			       name,
-			       NULL);
-    if(p =3D=3D NULL)
-	p =3D krb5_config_get_string(context, NULL,
-				   "libdefaults",
-				   "v4_name_convert",
-				   "plain",
-				   name,
-				   NULL);
-    if(p)
-	name =3D p;
-   =20
-    ret =3D krb5_make_principal(context, &pr, realm, name, instance, NULL);
-    if(func =3D=3D NULL || (*func)(context, funcctx, pr)){
-	*princ =3D pr;
-	return 0;
-    }
-    krb5_free_principal(context, pr);
-    krb5_clear_error_string (context);
-    return HEIM_ERR_V4_PRINC_NO_CONV;
-}
-
-static krb5_boolean
-convert_func(krb5_context conxtext, void *funcctx, krb5_principal principa=
l)
-{
-    krb5_boolean (*func)(krb5_context, krb5_principal) =3D funcctx;
-    return (*func)(conxtext, principal);
-}
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_425_conv_principal_ext(krb5_context context,
-			    const char *name,
-			    const char *instance,
-			    const char *realm,
-			    krb5_boolean (*func)(krb5_context, krb5_principal),
-			    krb5_boolean resolve,
-			    krb5_principal *principal)
-{
-    return krb5_425_conv_principal_ext2(context,
-					name,
-					instance,
-					realm,
-					func ? convert_func : NULL,
-					func,
-					resolve,
-					principal);
-}
-
-
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_425_conv_principal(krb5_context context,
-			const char *name,
-			const char *instance,
-			const char *realm,
-			krb5_principal *princ)
-{
-    krb5_boolean resolve =3D krb5_config_get_bool(context,
-						NULL,
-						"libdefaults",=20
-						"v4_instance_resolve",=20
-						NULL);
-
-    return krb5_425_conv_principal_ext(context, name, instance, realm,=20
-				       NULL, resolve, princ);
-}
-
-
-static int
-check_list(const krb5_config_binding *l, const char *name, const char **ou=
t)
-{
-    while(l){
-	if (l->type !=3D krb5_config_string)
-	    continue;
-	if(strcmp(name, l->u.string) =3D=3D 0) {
-	    *out =3D l->name;
-	    return 1;
-	}
-	l =3D l->next;
-    }
-    return 0;
-}
-
-static int
-name_convert(krb5_context context, const char *name, const char *realm,=20
-	     const char **out)
-{
-    const krb5_config_binding *l;
-    l =3D krb5_config_get_list (context,
-			      NULL,
-			      "realms",
-			      realm,
-			      "v4_name_convert",
-			      "host",
-			      NULL);
-    if(l && check_list(l, name, out))
-	return KRB5_NT_SRV_HST;
-    l =3D krb5_config_get_list (context,
-			      NULL,
-			      "libdefaults",
-			      "v4_name_convert",
-			      "host",
-			      NULL);
-    if(l && check_list(l, name, out))
-	return KRB5_NT_SRV_HST;
-    l =3D krb5_config_get_list (context,
-			      NULL,
-			      "realms",
-			      realm,
-			      "v4_name_convert",
-			      "plain",
-			      NULL);
-    if(l && check_list(l, name, out))
-	return KRB5_NT_UNKNOWN;
-    l =3D krb5_config_get_list (context,
-			      NULL,
-			      "libdefaults",
-			      "v4_name_convert",
-			      "host",
-			      NULL);
-    if(l && check_list(l, name, out))
-	return KRB5_NT_UNKNOWN;
-   =20
-    /* didn't find it in config file, try built-in list */
-    {
-	struct v4_name_convert *q;
-	for(q =3D default_v4_name_convert; q->from; q++) {
-	    if(strcmp(name, q->to) =3D=3D 0) {
-		*out =3D q->from;
-		return KRB5_NT_SRV_HST;
-	    }
-	}
-    }
-    return -1;
-}
-
-/*
- * convert the v5 principal in `principal' into a v4 corresponding one
- * in `name, instance, realm'
- * this is limited interface since there's no length given for these
- * three parameters.  They have to be 40 bytes each (ANAME_SZ).
- */
-
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_524_conv_principal(krb5_context context,
-			const krb5_principal principal,
-			char *name,=20
-			char *instance,
-			char *realm)
-{
-    const char *n, *i, *r;
-    char tmpinst[40];
-    int type =3D princ_type(principal);
-    const int aname_sz =3D 40;
-
-    r =3D principal->realm;
-
-    switch(principal->name.name_string.len){
-    case 1:
-	n =3D principal->name.name_string.val[0];
-	i =3D "";
-	break;
-    case 2:
-	n =3D principal->name.name_string.val[0];
-	i =3D principal->name.name_string.val[1];
-	break;
-    default:
-	krb5_set_error_string (context,
-			       "cannot convert a %d component principal",
-			       principal->name.name_string.len);
-	return KRB5_PARSE_MALFORMED;
-    }
-
-    {
-	const char *tmp;
-	int t =3D name_convert(context, n, r, &tmp);
-	if(t >=3D 0) {
-	    type =3D t;
-	    n =3D tmp;
-	}
-    }
-
-    if(type =3D=3D KRB5_NT_SRV_HST){
-	char *p;
-
-	strlcpy (tmpinst, i, sizeof(tmpinst));
-	p =3D strchr(tmpinst, '.');
-	if(p)
-	    *p =3D 0;
-	i =3D tmpinst;
-    }
-   =20
-    if (strlcpy (name, n, aname_sz) >=3D aname_sz) {
-	krb5_set_error_string (context,
-			       "too long name component to convert");
-	return KRB5_PARSE_MALFORMED;
-    }
-    if (strlcpy (instance, i, aname_sz) >=3D aname_sz) {
-	krb5_set_error_string (context,
-			       "too long instance component to convert");
-	return KRB5_PARSE_MALFORMED;
-    }
-    if (strlcpy (realm, r, aname_sz) >=3D aname_sz) {
-	krb5_set_error_string (context,
-			       "too long realm component to convert");
-	return KRB5_PARSE_MALFORMED;
-    }
-    return 0;
-}
-
-/*
- * Create a principal in `ret_princ' for the service `sname' running
- * on host `hostname'.  */
-		=09
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sname_to_principal (krb5_context context,
 			 const char *hostname,
 			 const char *sname,
@@ -1186,14 +1039,22 @@
     krb5_error_code ret;
     char localhost[MAXHOSTNAMELEN];
     char **realms, *host =3D NULL;
-=09
+
     if(type !=3D KRB5_NT_SRV_HST && type !=3D KRB5_NT_UNKNOWN) {
-	krb5_set_error_string (context, "unsupported name type %d",
-			       type);
+	krb5_set_error_message(context, KRB5_SNAME_UNSUPP_NAMETYPE,
+			       N_("unsupported name type %d", ""),
+			       (int)type);
 	return KRB5_SNAME_UNSUPP_NAMETYPE;
     }
     if(hostname =3D=3D NULL) {
-	gethostname(localhost, sizeof(localhost));
+	ret =3D gethostname(localhost, sizeof(localhost) - 1);
+	if (ret !=3D 0) {
+	    ret =3D errno;
+	    krb5_set_error_message(context, ret,
+				   N_("Failed to get local hostname", ""));
+	    return ret;
+	}
+	localhost[sizeof(localhost) - 1] =3D '\0';
 	hostname =3D localhost;
     }
     if(sname =3D=3D NULL)
@@ -1235,20 +1096,41 @@
     { "ENT_PRINCIPAL_AND_ID", KRB5_NT_ENT_PRINCIPAL_AND_ID },
     { "MS_PRINCIPAL", KRB5_NT_MS_PRINCIPAL },
     { "MS_PRINCIPAL_AND_ID", KRB5_NT_MS_PRINCIPAL_AND_ID },
-    { NULL }
+    { NULL, 0 }
 };
=20
-krb5_error_code
+/**
+ * Parse nametype string and return a nametype integer
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_parse_nametype(krb5_context context, const char *str, int32_t *namety=
pe)
 {
     size_t i;
-   =20
+
     for(i =3D 0; nametypes[i].type; i++) {
 	if (strcasecmp(nametypes[i].type, str) =3D=3D 0) {
 	    *nametype =3D nametypes[i].value;
 	    return 0;
 	}
     }
-    krb5_set_error_string(context, "Failed to find name type %s", str);
+    krb5_set_error_message(context, KRB5_PARSE_MALFORMED,
+			   N_("Failed to find name type %s", ""), str);
     return KRB5_PARSE_MALFORMED;
 }
+
+/**
+ * Check if the cname part of the principal is a krbtgt principal
+ *
+ * @ingroup krb5_principal
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
+krb5_principal_is_krbtgt(krb5_context context, krb5_const_principal p)
+{
+    return p->name.name_string.len =3D=3D 2 &&
+	strcmp(p->name.name_string.val[0], KRB5_TGS_NAME) =3D=3D 0;
+
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/prog_setu=
p.c
--- a/head/crypto/heimdal/lib/krb5/prog_setup.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/prog_setup.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,53 +1,51 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include <getarg.h>
 #include <err.h>
=20
-RCSID("$Id: prog_setup.c 15470 2005-06-17 04:29:41Z lha $");
-
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_std_usage(int code, struct getargs *args, int num_args)
 {
     arg_printusage(args, num_args, NULL, "");
     exit(code);
 }
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_program_setup(krb5_context *context, int argc, char **argv,
-		   struct getargs *args, int num_args,=20
-		   void (*usage)(int, struct getargs*, int))
+		   struct getargs *args, int num_args,
+		   void (KRB5_LIB_CALL *usage)(int, struct getargs*, int))
 {
     krb5_error_code ret;
     int optidx =3D 0;
@@ -59,7 +57,7 @@
     ret =3D krb5_init_context(context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
-   =20
+
     if(getarg(args, num_args, argc, argv, &optidx))
 	(*usage)(1, args, num_args);
     return optidx;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/prompter_=
posix.c
--- a/head/crypto/heimdal/lib/krb5/prompter_posix.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/prompter_posix.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: prompter_posix.c 13863 2004-05-25 21:46:46Z lha $");
-
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_CALLCONV
 krb5_prompter_posix (krb5_context context,
 		     void *data,
 		     const char *name,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/rd_cred.c
--- a/head/crypto/heimdal/lib/krb5/rd_cred.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/rd_cred.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
-
-RCSID("$Id: rd_cred.c 20304 2007-04-11 11:15:05Z lha $");
+#include "krb5_locl.h"
=20
 static krb5_error_code
 compare_addrs(krb5_context context,
@@ -49,11 +47,12 @@
=20
     krb5_print_address (a, a_str, sizeof(a_str), &len);
     krb5_print_address (b, b_str, sizeof(b_str), &len);
-    krb5_set_error_string(context, "%s: %s !=3D %s", message, b_str, a_str=
);
+    krb5_set_error_message(context, KRB5KRB_AP_ERR_BADADDR,
+			   "%s: %s !=3D %s", message, b_str, a_str);
     return KRB5KRB_AP_ERR_BADADDR;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_cred(krb5_context context,
 	     krb5_auth_context auth_context,
 	     krb5_data *in_data,
@@ -66,43 +65,44 @@
     EncKrbCredPart enc_krb_cred_part;
     krb5_data enc_krb_cred_part_data;
     krb5_crypto crypto;
-    int i;
+    size_t i;
=20
     memset(&enc_krb_cred_part, 0, sizeof(enc_krb_cred_part));
+    krb5_data_zero(&enc_krb_cred_part_data);
=20
-    if ((auth_context->flags &=20
+    if ((auth_context->flags &
 	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
 	outdata =3D=3D NULL)
 	return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
=20
     *ret_creds =3D NULL;
=20
-    ret =3D decode_KRB_CRED(in_data->data, in_data->length,=20
+    ret =3D decode_KRB_CRED(in_data->data, in_data->length,
 			  &cred, &len);
     if(ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
=20
     if (cred.pvno !=3D 5) {
 	ret =3D KRB5KRB_AP_ERR_BADVERSION;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto out;
     }
=20
     if (cred.msg_type !=3D krb_cred) {
 	ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto out;
     }
=20
-    if (cred.enc_part.etype =3D=3D ETYPE_NULL) { =20
+    if (cred.enc_part.etype =3D=3D ETYPE_NULL) {
 	/* DK: MIT GSS-API Compatibility */
 	enc_krb_cred_part_data.length =3D cred.enc_part.cipher.length;
 	enc_krb_cred_part_data.data   =3D cred.enc_part.cipher.data;
     } else {
 	/* Try both subkey and session key.
-	 *=20
+	 *
 	 * RFC4120 claims we should use the session key, but Heimdal
 	 * before 0.8 used the remote subkey if it was send in the
 	 * auth_context.
@@ -119,12 +119,12 @@
 					     KRB5_KU_KRB_CRED,
 					     &cred.enc_part,
 					     &enc_krb_cred_part_data);
-	   =20
+
 	    krb5_crypto_destroy(context, crypto);
 	}
=20
-	/*=20
-	 * If there was not subkey, or we failed using subkey,=20
+	/*
+	 * If there was not subkey, or we failed using subkey,
 	 * retry using the session key
 	 */
 	if (auth_context->remote_subkey =3D=3D NULL || ret =3D=3D KRB5KRB_AP_ERR_=
BAD_INTEGRITY)
@@ -135,28 +135,31 @@
=20
 	    if (ret)
 		goto out;
-	   =20
+
 	    ret =3D krb5_decrypt_EncryptedData(context,
 					     crypto,
 					     KRB5_KU_KRB_CRED,
 					     &cred.enc_part,
 					     &enc_krb_cred_part_data);
-	   =20
+
 	    krb5_crypto_destroy(context, crypto);
 	}
 	if (ret)
 	    goto out;
     }
=20
-    ret =3D krb5_decode_EncKrbCredPart (context,
-				      enc_krb_cred_part_data.data,
-				      enc_krb_cred_part_data.length,
-				      &enc_krb_cred_part,
-				      &len);
+    ret =3D decode_EncKrbCredPart(enc_krb_cred_part_data.data,
+				enc_krb_cred_part_data.length,
+				&enc_krb_cred_part,
+				&len);
     if (enc_krb_cred_part_data.data !=3D cred.enc_part.cipher.data)
 	krb5_data_free(&enc_krb_cred_part_data);
-    if (ret)
+    if (ret) {
+	krb5_set_error_message(context, ret,
+			       N_("Failed to decode "
+				  "encrypte credential part", ""));
 	goto out;
+    }
=20
     /* check sender address */
=20
@@ -172,8 +175,9 @@
 	    goto out;
=20
=20
-	ret =3D compare_addrs(context, a, enc_krb_cred_part.s_address,=20
-			    "sender address is wrong in received creds");
+	ret =3D compare_addrs(context, a, enc_krb_cred_part.s_address,
+			    N_("sender address is wrong "
+			       "in received creds", ""));
 	krb5_free_address(context, a);
 	free(a);
 	if(ret)
@@ -192,9 +196,10 @@
 				      auth_context->local_port);
 	    if (ret)
 		goto out;
-	   =20
-	    ret =3D compare_addrs(context, a, enc_krb_cred_part.r_address,=20
-				"receiver address is wrong in received creds");
+
+	    ret =3D compare_addrs(context, a, enc_krb_cred_part.r_address,
+				N_("receiver address is wrong "
+				   "in received creds", ""));
 	    krb5_free_address(context, a);
 	    free(a);
 	    if(ret)
@@ -202,7 +207,8 @@
 	} else {
 	    ret =3D compare_addrs(context, auth_context->local_address,
 				enc_krb_cred_part.r_address,
-				"receiver address is wrong in received creds");
+				N_("receiver address is wrong "
+				   "in received creds", ""));
 	    if(ret)
 		goto out;
 	}
@@ -218,13 +224,13 @@
 	    enc_krb_cred_part.usec      =3D=3D NULL ||
 	    abs(*enc_krb_cred_part.timestamp - sec)
 	    > context->max_skew) {
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    ret =3D KRB5KRB_AP_ERR_SKEW;
 	    goto out;
 	}
     }
=20
-    if ((auth_context->flags &=20
+    if ((auth_context->flags &
 	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) {
 	/* if these fields are not present in the cred-part, silently
            return zero */
@@ -236,15 +242,16 @@
 	if(enc_krb_cred_part.nonce)
 	    outdata->seq =3D *enc_krb_cred_part.nonce;
     }
-   =20
+
     /* Convert to NULL terminated list of creds */
=20
-    *ret_creds =3D calloc(enc_krb_cred_part.ticket_info.len + 1,=20
+    *ret_creds =3D calloc(enc_krb_cred_part.ticket_info.len + 1,
 			sizeof(**ret_creds));
=20
     if (*ret_creds =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ret,
+			       N_("malloc: out of memory", ""));
 	goto out;
     }
=20
@@ -255,11 +262,12 @@
 	creds =3D calloc(1, sizeof(*creds));
 	if(creds =3D=3D NULL) {
 	    ret =3D ENOMEM;
-	    krb5_set_error_string (context, "malloc: out of memory");
+	    krb5_set_error_message(context, ret,
+				   N_("malloc: out of memory", ""));
 	    goto out;
 	}
=20
-	ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,=20
+	ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
 			   &cred.tickets.val[i], &len, ret);
 	if (ret) {
 	    free(creds);
@@ -292,9 +300,9 @@
 	    krb5_copy_addresses (context,
 				 kci->caddr,
 				 &creds->addresses);
-=09
+
 	(*ret_creds)[i] =3D creds;
-=09
+
     }
     (*ret_creds)[i] =3D NULL;
=20
@@ -315,7 +323,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_cred2 (krb5_context      context,
 	       krb5_auth_context auth_context,
 	       krb5_ccache       ccache,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/rd_error.c
--- a/head/crypto/heimdal/lib/krb5/rd_error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/rd_error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,59 +1,57 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: rd_error.c 21057 2007-06-12 17:22:31Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_error(krb5_context context,
 	      const krb5_data *msg,
 	      KRB_ERROR *result)
 {
-   =20
+
     size_t len;
     krb5_error_code ret;
=20
     ret =3D decode_KRB_ERROR(msg->data, msg->length, result, &len);
     if(ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
     result->error_code +=3D KRB5KDC_ERR_NONE;
     return 0;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_error_contents (krb5_context context,
 			  krb5_error *error)
 {
@@ -61,7 +59,7 @@
     memset(error, 0, sizeof(*error));
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_error (krb5_context context,
 		 krb5_error *error)
 {
@@ -69,7 +67,7 @@
     free (error);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_error_from_rd_error(krb5_context context,
 			 const krb5_error *error,
 			 const krb5_creds *creds)
@@ -78,7 +76,7 @@
=20
     ret =3D error->error_code;
     if (error->e_text !=3D NULL) {
-	krb5_set_error_string(context, "%s", *error->e_text);
+	krb5_set_error_message(context, ret, "%s", *error->e_text);
     } else {
 	char clientname[256], servername[256];
=20
@@ -91,31 +89,35 @@
=20
 	switch (ret) {
 	case KRB5KDC_ERR_NAME_EXP :
-	    krb5_set_error_string(context, "Client %s%s%s expired",
-				  creds ? "(" : "",
-				  creds ? clientname : "",
-				  creds ? ")" : "");
+	    krb5_set_error_message(context, ret,
+				   N_("Client %s%s%s expired", ""),
+				   creds ? "(" : "",
+				   creds ? clientname : "",
+				   creds ? ")" : "");
 	    break;
 	case KRB5KDC_ERR_SERVICE_EXP :
-	    krb5_set_error_string(context, "Server %s%s%s expired",
-				  creds ? "(" : "",
-				  creds ? servername : "",
-				  creds ? ")" : "");
+	    krb5_set_error_message(context, ret,
+				   N_("Server %s%s%s expired", ""),
+				   creds ? "(" : "",
+				   creds ? servername : "",
+				   creds ? ")" : "");
 	    break;
 	case KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN :
-	    krb5_set_error_string(context, "Client %s%s%s unknown",
-				  creds ? "(" : "",
-				  creds ? clientname : "",
-				  creds ? ")" : "");
+	    krb5_set_error_message(context, ret,
+				   N_("Client %s%s%s unknown", ""),
+				   creds ? "(" : "",
+				   creds ? clientname : "",
+				   creds ? ")" : "");
 	    break;
 	case KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN :
-	    krb5_set_error_string(context, "Server %s%s%s unknown",
-				  creds ? "(" : "",
-				  creds ? servername : "",
-				  creds ? ")" : "");
+	    krb5_set_error_message(context, ret,
+				   N_("Server %s%s%s unknown", ""),
+				   creds ? "(" : "",
+				   creds ? servername : "",
+				   creds ? ")" : "");
 	    break;
 	default :
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    break;
 	}
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/rd_priv.c
--- a/head/crypto/heimdal/lib/krb5/rd_priv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/rd_priv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: rd_priv.c 21751 2007-07-31 20:42:20Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_priv(krb5_context context,
 	     krb5_auth_context auth_context,
 	     const krb5_data *inbuf,
@@ -50,29 +48,33 @@
     krb5_keyblock *key;
     krb5_crypto crypto;
=20
-    if (outbuf)
-	krb5_data_zero(outbuf);
+    krb5_data_zero(outbuf);
=20
-    if ((auth_context->flags &=20
-	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
-	outdata =3D=3D NULL) {
-	krb5_clear_error_string (context);
-	return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+    if ((auth_context->flags &
+	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)))
+    {
+	if (outdata =3D=3D NULL) {
+	    krb5_clear_error_message (context);
+	    return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+	}
+	/* if these fields are not present in the priv-part, silently
+           return zero */
+	memset(outdata, 0, sizeof(*outdata));
     }
=20
     memset(&priv, 0, sizeof(priv));
     ret =3D decode_KRB_PRIV (inbuf->data, inbuf->length, &priv, &len);
     if (ret) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto failure;
     }
     if (priv.pvno !=3D 5) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	ret =3D KRB5KRB_AP_ERR_BADVERSION;
 	goto failure;
     }
     if (priv.msg_type !=3D krb_priv) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
 	goto failure;
     }
@@ -93,16 +95,16 @@
 				     &priv.enc_part,
 				     &plain);
     krb5_crypto_destroy(context, crypto);
-    if (ret)=20
+    if (ret)
 	goto failure;
=20
     ret =3D decode_EncKrbPrivPart (plain.data, plain.length, &part, &len);
     krb5_data_free (&plain);
     if (ret) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto failure;
     }
- =20
+
     /* check sender address */
=20
     if (part.s_address
@@ -110,7 +112,7 @@
 	&& !krb5_address_compare (context,
 				  auth_context->remote_address,
 				  part.s_address)) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	ret =3D KRB5KRB_AP_ERR_BADADDR;
 	goto failure_part;
     }
@@ -122,7 +124,7 @@
 	&& !krb5_address_compare (context,
 				  auth_context->local_address,
 				  part.r_address)) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	ret =3D KRB5KRB_AP_ERR_BADADDR;
 	goto failure_part;
     }
@@ -135,7 +137,7 @@
 	if (part.timestamp =3D=3D NULL ||
 	    part.usec      =3D=3D NULL ||
 	    abs(*part.timestamp - sec) > context->max_skew) {
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    ret =3D KRB5KRB_AP_ERR_SKEW;
 	    goto failure_part;
 	}
@@ -152,7 +154,7 @@
 	     && auth_context->remote_seqnumber !=3D 0)
 	    || (part.seq_number !=3D NULL
 		&& *part.seq_number !=3D auth_context->remote_seqnumber)) {
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    ret =3D KRB5KRB_AP_ERR_BADORDER;
 	    goto failure_part;
 	}
@@ -163,11 +165,8 @@
     if (ret)
 	goto failure_part;
=20
-    if ((auth_context->flags &=20
+    if ((auth_context->flags &
 	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) {
-	/* if these fields are not present in the priv-part, silently
-           return zero */
-	memset(outdata, 0, sizeof(*outdata));
 	if(part.timestamp)
 	    outdata->timestamp =3D *part.timestamp;
 	if(part.usec)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/rd_rep.c
--- a/head/crypto/heimdal/lib/krb5/rd_rep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/rd_rep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
+#include "krb5_locl.h"
=20
-RCSID("$Id: rd_rep.c 17890 2006-08-21 09:19:22Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_rep(krb5_context context,
 	    krb5_auth_context auth_context,
 	    const krb5_data *inbuf,
@@ -48,27 +46,26 @@
     krb5_crypto crypto;
=20
     krb5_data_zero (&data);
-    ret =3D 0;
=20
     ret =3D decode_AP_REP(inbuf->data, inbuf->length, &ap_rep, &len);
     if (ret)
 	return ret;
     if (ap_rep.pvno !=3D 5) {
 	ret =3D KRB5KRB_AP_ERR_BADVERSION;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto out;
     }
     if (ap_rep.msg_type !=3D krb_ap_rep) {
 	ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto out;
     }
=20
     ret =3D krb5_crypto_init(context, auth_context->keyblock, 0, &crypto);
     if (ret)
 	goto out;
-    ret =3D krb5_decrypt_EncryptedData (context,=20
-				      crypto,=09
+    ret =3D krb5_decrypt_EncryptedData (context,
+				      crypto,
 				      KRB5_KU_AP_REQ_ENC_PART,
 				      &ap_rep.enc_part,
 				      &data);
@@ -79,25 +76,23 @@
     *repl =3D malloc(sizeof(**repl));
     if (*repl =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	goto out;
     }
-    ret =3D krb5_decode_EncAPRepPart(context,
-				   data.data,
-				   data.length,
-				   *repl,=20
-				   &len);
-    if (ret)
+    ret =3D decode_EncAPRepPart(data.data, data.length, *repl, &len);
+    if (ret) {
+	krb5_set_error_message(context, ret, N_("Failed to decode EncAPRepPart", =
""));
 	return ret;
- =20
-    if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {=20
+    }
+
+    if (auth_context->flags & KRB5_AUTH_CONTEXT_DO_TIME) {
 	if ((*repl)->ctime !=3D auth_context->authenticator->ctime ||
-	    (*repl)->cusec !=3D auth_context->authenticator->cusec)=20
+	    (*repl)->cusec !=3D auth_context->authenticator->cusec)
 	{
 	    krb5_free_ap_rep_enc_part(context, *repl);
 	    *repl =3D NULL;
 	    ret =3D KRB5KRB_AP_ERR_MUT_FAIL;
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    goto out;
 	}
     }
@@ -106,14 +101,14 @@
 					 *((*repl)->seq_number));
     if ((*repl)->subkey)
 	krb5_auth_con_setremotesubkey(context, auth_context, (*repl)->subkey);
- =20
+
  out:
     krb5_data_free (&data);
     free_AP_REP (&ap_rep);
     return ret;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_free_ap_rep_enc_part (krb5_context context,
 			   krb5_ap_rep_enc_part *val)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/rd_req.c
--- a/head/crypto/heimdal/lib/krb5/rd_req.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/rd_req.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,38 @@
+
 /*
- * Copyright (c) 1997 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
-
-RCSID("$Id: rd_req.c 22235 2007-12-08 21:52:07Z lha $");
+#include "krb5_locl.h"
=20
 static krb5_error_code
 decrypt_tkt_enc_part (krb5_context context,
@@ -58,8 +57,11 @@
     if (ret)
 	return ret;
=20
-    ret =3D krb5_decode_EncTicketPart(context, plain.data, plain.length,=20
-				    decr_part, &len);
+    ret =3D decode_EncTicketPart(plain.data, plain.length, decr_part, &len=
);
+    if (ret)
+        krb5_set_error_message(context, ret,
+			       N_("Failed to decode encrypted "
+				  "ticket part", ""));
     krb5_data_free (&plain);
     return ret;
 }
@@ -95,13 +97,13 @@
     if (ret)
 	return ret;
=20
-    ret =3D krb5_decode_Authenticator(context, plain.data, plain.length,=20
-				    authenticator, &len);
+    ret =3D decode_Authenticator(plain.data, plain.length,
+			       authenticator, &len);
     krb5_data_free (&plain);
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decode_ap_req(krb5_context context,
 		   const krb5_data *inbuf,
 		   krb5_ap_req *ap_req)
@@ -113,17 +115,17 @@
 	return ret;
     if (ap_req->pvno !=3D 5){
 	free_AP_REQ(ap_req);
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5KRB_AP_ERR_BADVERSION;
     }
     if (ap_req->msg_type !=3D krb_ap_req){
 	free_AP_REQ(ap_req);
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5KRB_AP_ERR_MSG_TYPE;
     }
     if (ap_req->ticket.tkt_vno !=3D 5){
 	free_AP_REQ(ap_req);
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5KRB_AP_ERR_BADVERSION;
     }
     return 0;
@@ -133,10 +135,10 @@
 check_transited(krb5_context context, Ticket *ticket, EncTicketPart *enc)
 {
     char **realms;
-    int num_realms;
+    unsigned int num_realms, n;
     krb5_error_code ret;
-	   =20
-    /*=20
+
+    /*
      * Windows 2000 and 2003 uses this inside their TGT so it's normaly
      * not seen by others, however, samba4 joined with a Windows AD as
      * a Domain Controller gets exposed to this.
@@ -150,15 +152,17 @@
     if(enc->transited.contents.length =3D=3D 0)
 	return 0;
=20
-    ret =3D krb5_domain_x500_decode(context, enc->transited.contents,=20
-				  &realms, &num_realms,=20
+    ret =3D krb5_domain_x500_decode(context, enc->transited.contents,
+				  &realms, &num_realms,
 				  enc->crealm,
 				  ticket->realm);
     if(ret)
 	return ret;
-    ret =3D krb5_check_transited(context, enc->crealm,=20
-			       ticket->realm,=20
+    ret =3D krb5_check_transited(context, enc->crealm,
+			       ticket->realm,
 			       realms, num_realms, NULL);
+    for (n =3D 0; n < num_realms; n++)
+	free(realms[n]);
     free(realms);
     return ret;
 }
@@ -173,7 +177,7 @@
     krb5_authdata adIfRelevant;
     unsigned i;
=20
-    adIfRelevant.len =3D 0;
+    memset(&adIfRelevant, 0, sizeof(adIfRelevant));
=20
     etypes->len =3D 0;
     etypes->val =3D NULL;
@@ -209,14 +213,14 @@
 			   etypes,
 			   NULL);
     if (ret)
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
=20
     free_AD_IF_RELEVANT(&adIfRelevant);
=20
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_decrypt_ticket(krb5_context context,
 		    Ticket *ticket,
 		    krb5_keyblock *key,
@@ -228,7 +232,7 @@
     ret =3D decrypt_tkt_enc_part (context, key, &ticket->enc_part, &t);
     if (ret)
 	return ret;
-   =20
+
     {
 	krb5_timestamp now;
 	time_t start =3D t.authtime;
@@ -240,15 +244,15 @@
 	   || (t.flags.invalid
 	       && !(flags & KRB5_VERIFY_AP_REQ_IGNORE_INVALID))) {
 	    free_EncTicketPart(&t);
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    return KRB5KRB_AP_ERR_TKT_NYV;
 	}
 	if(now - t.endtime > context->max_skew) {
 	    free_EncTicketPart(&t);
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    return KRB5KRB_AP_ERR_TKT_EXPIRED;
 	}
-=09
+
 	if(!t.flags.transited_policy_checked) {
 	    ret =3D check_transited(context, ticket, &t);
 	    if(ret) {
@@ -257,7 +261,7 @@
 	    }
 	}
     }
-   =20
+
     if(out)
 	*out =3D t;
     else
@@ -265,7 +269,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_authenticator_checksum(krb5_context context,
 				   krb5_auth_context ac,
 				   void *data,
@@ -275,7 +279,7 @@
     krb5_keyblock *key;
     krb5_authenticator authenticator;
     krb5_crypto crypto;
-   =20
+
     ret =3D krb5_auth_con_getauthenticator (context,
 				      ac,
 				      &authenticator);
@@ -307,7 +311,7 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_ap_req(krb5_context context,
 		   krb5_auth_context *auth_context,
 		   krb5_ap_req *ap_req,
@@ -328,7 +332,7 @@
 				KRB5_KU_AP_REQ_AUTH);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_ap_req2(krb5_context context,
 		    krb5_auth_context *auth_context,
 		    krb5_ap_req *ap_req,
@@ -343,7 +347,7 @@
     krb5_auth_context ac;
     krb5_error_code ret;
     EtypeList etypes;
-   =20
+
     if (ticket)
 	*ticket =3D NULL;
=20
@@ -358,42 +362,37 @@
     t =3D calloc(1, sizeof(*t));
     if (t =3D=3D NULL) {
 	ret =3D ENOMEM;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto out;
     }
=20
     if (ap_req->ap_options.use_session_key && ac->keyblock){
-	ret =3D krb5_decrypt_ticket(context, &ap_req->ticket,=20
-				  ac->keyblock,=20
+	ret =3D krb5_decrypt_ticket(context, &ap_req->ticket,
+				  ac->keyblock,
 				  &t->ticket,
 				  flags);
 	krb5_free_keyblock(context, ac->keyblock);
 	ac->keyblock =3D NULL;
     }else
-	ret =3D krb5_decrypt_ticket(context, &ap_req->ticket,=20
-				  keyblock,=20
+	ret =3D krb5_decrypt_ticket(context, &ap_req->ticket,
+				  keyblock,
 				  &t->ticket,
 				  flags);
-   =20
+
     if(ret)
 	goto out;
=20
     ret =3D _krb5_principalname2krb5_principal(context,
 					     &t->server,
-					     ap_req->ticket.sname,=20
+					     ap_req->ticket.sname,
 					     ap_req->ticket.realm);
     if (ret) goto out;
     ret =3D _krb5_principalname2krb5_principal(context,
 					     &t->client,
-					     t->ticket.cname,=20
+					     t->ticket.cname,
 					     t->ticket.crealm);
     if (ret) goto out;
=20
-    /* save key */
-
-    ret =3D krb5_copy_keyblock(context, &t->ticket.key, &ac->keyblock);
-    if (ret) goto out;
-
     ret =3D decrypt_authenticator (context,
 				 &t->ticket.key,
 				 &ap_req->authenticator,
@@ -405,13 +404,13 @@
     {
 	krb5_principal p1, p2;
 	krb5_boolean res;
-=09
+
 	_krb5_principalname2krb5_principal(context,
 					   &p1,
 					   ac->authenticator->cname,
 					   ac->authenticator->crealm);
 	_krb5_principalname2krb5_principal(context,
-					   &p2,=20
+					   &p2,
 					   t->ticket.cname,
 					   t->ticket.crealm);
 	res =3D krb5_principal_compare (context, p1, p2);
@@ -419,7 +418,7 @@
 	krb5_free_principal (context, p2);
 	if (!res) {
 	    ret =3D KRB5KRB_AP_ERR_BADMATCH;
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    goto out;
 	}
     }
@@ -432,7 +431,7 @@
 				 ac->remote_address,
 				 t->ticket.caddr)) {
 	ret =3D KRB5KRB_AP_ERR_BADADDR;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto out;
     }
=20
@@ -444,7 +443,7 @@
=20
 	if (abs(ac->authenticator->ctime - now) > context->max_skew) {
 	    ret =3D KRB5KRB_AP_ERR_SKEW;
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    goto out;
 	}
     }
@@ -469,7 +468,7 @@
     ac->keytype =3D ETYPE_NULL;
=20
     if (etypes.val) {
-	int i;
+	size_t i;
=20
 	for (i =3D 0; i < etypes.len; i++) {
 	    if (krb5_enctype_valid(context, etypes.val[i]) =3D=3D 0) {
@@ -479,6 +478,10 @@
 	}
     }
=20
+    /* save key */
+    ret =3D krb5_copy_keyblock(context, &t->ticket.key, &ac->keyblock);
+    if (ret) goto out;
+
     if (ap_req_options) {
 	*ap_req_options =3D 0;
 	if (ac->keytype !=3D ETYPE_NULL)
@@ -507,7 +510,7 @@
 	krb5_auth_con_free (context, ac);
     return ret;
 }
-		  =20
+
 /*
  *
  */
@@ -522,47 +525,72 @@
     krb5_keyblock *keyblock;
     krb5_flags ap_req_options;
     krb5_ticket *ticket;
+    krb5_principal server;
 };
=20
-/*
+/**
+ * Allocate a krb5_rd_req_in_ctx as an input parameter to
+ * krb5_rd_req_ctx(). The caller should free the context with
+ * krb5_rd_req_in_ctx_free() when done with the context.
  *
+ * @param context Keberos 5 context.
+ * @param ctx in ctx to krb5_rd_req_ctx().
+ *
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_auth
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_in_ctx_alloc(krb5_context context, krb5_rd_req_in_ctx *ctx)
 {
     *ctx =3D calloc(1, sizeof(**ctx));
     if (*ctx =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     (*ctx)->check_pac =3D (context->flags & KRB5_CTX_F_CHECK_PAC) ? 1 : 0;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_rd_req_in_set_keytab(krb5_context context,=20
+/**
+ * Set the keytab that krb5_rd_req_ctx() will use.
+ *
+ * @param context Keberos 5 context.
+ * @param in in ctx to krb5_rd_req_ctx().
+ * @param keytab keytab that krb5_rd_req_ctx() will use, only copy the
+ *        pointer, so the caller must free they keytab after
+ *        krb5_rd_req_in_ctx_free() is called.
+ *
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_in_set_keytab(krb5_context context,
 			  krb5_rd_req_in_ctx in,
 			  krb5_keytab keytab)
 {
-    in->keytab =3D keytab; /* XXX should make copy */
+    in->keytab =3D keytab;
     return 0;
 }
=20
 /**
  * Set if krb5_rq_red() is going to check the Windows PAC or not
- *=20
+ *
  * @param context Keberos 5 context.
  * @param in krb5_rd_req_in_ctx to check the option on.
  * @param flag flag to select if to check the pac (TRUE) or not (FALSE).
  *
  * @return Kerberos 5 error code, see krb5_get_error_message().
  *
- * @ingroup krb5
+ * @ingroup krb5_auth
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_rd_req_in_set_pac_check(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_in_set_pac_check(krb5_context context,
 			     krb5_rd_req_in_ctx in,
 			     krb5_boolean flag)
 {
@@ -571,8 +599,8 @@
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_rd_req_in_set_keyblock(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_in_set_keyblock(krb5_context context,
 			    krb5_rd_req_in_ctx in,
 			    krb5_keyblock *keyblock)
 {
@@ -580,8 +608,8 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_rd_req_out_get_ap_req_options(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_ap_req_options(krb5_context context,
 				   krb5_rd_req_out_ctx out,
 				   krb5_flags *ap_req_options)
 {
@@ -589,43 +617,66 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_rd_req_out_get_ticket(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_ticket(krb5_context context,
 			    krb5_rd_req_out_ctx out,
 			    krb5_ticket **ticket)
 {
     return krb5_copy_ticket(context, out->ticket, ticket);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_rd_req_out_get_keyblock(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_keyblock(krb5_context context,
 			    krb5_rd_req_out_ctx out,
 			    krb5_keyblock **keyblock)
 {
     return krb5_copy_keyblock(context, out->keyblock, keyblock);
 }
=20
-void  KRB5_LIB_FUNCTION
+/**
+ * Get the principal that was used in the request from the
+ * client. Might not match whats in the ticket if krb5_rd_req_ctx()
+ * searched in the keytab for a matching key.
+ *
+ * @param context a Kerberos 5 context.
+ * @param out a krb5_rd_req_out_ctx from krb5_rd_req_ctx().
+ * @param principal return principal, free with krb5_free_principal().
+ *
+ * @ingroup krb5_auth
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_rd_req_out_get_server(krb5_context context,
+			    krb5_rd_req_out_ctx out,
+			    krb5_principal *principal)
+{
+    return krb5_copy_principal(context, out->server, principal);
+}
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_rd_req_in_ctx_free(krb5_context context, krb5_rd_req_in_ctx ctx)
 {
     free(ctx);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-_krb5_rd_req_out_ctx_alloc(krb5_context context, krb5_rd_req_out_ctx *ctx)
-{
-    *ctx =3D calloc(1, sizeof(**ctx));
-    if (*ctx =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
-	return ENOMEM;
-    }
-    return 0;
-}
+/**
+ * Free the krb5_rd_req_out_ctx.
+ *
+ * @param context Keberos 5 context.
+ * @param ctx krb5_rd_req_out_ctx context to free.
+ *
+ * @ingroup krb5_auth
+ */
=20
-void  KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_rd_req_out_ctx_free(krb5_context context, krb5_rd_req_out_ctx ctx)
 {
-    krb5_free_keyblock(context, ctx->keyblock);
+    if (ctx->ticket)
+	krb5_free_ticket(context, ctx->ticket);
+    if (ctx->keyblock)
+	krb5_free_keyblock(context, ctx->keyblock);
+    if (ctx->server)
+	krb5_free_principal(context, ctx->server);
     free(ctx);
 }
=20
@@ -633,7 +684,7 @@
  *
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req(krb5_context context,
 	    krb5_auth_context *auth_context,
 	    const krb5_data *inbuf,
@@ -649,7 +700,7 @@
     ret =3D krb5_rd_req_in_ctx_alloc(context, &in);
     if (ret)
 	return ret;
-   =20
+
     ret =3D krb5_rd_req_in_set_keytab(context, in, keytab);
     if (ret) {
 	krb5_rd_req_in_ctx_free(context, in);
@@ -678,7 +729,7 @@
  *
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_with_keyblock(krb5_context context,
 			  krb5_auth_context *auth_context,
 			  const krb5_data *inbuf,
@@ -694,7 +745,7 @@
     ret =3D krb5_rd_req_in_ctx_alloc(context, &in);
     if (ret)
 	return ret;
-   =20
+
     ret =3D krb5_rd_req_in_set_keyblock(context, in, keyblock);
     if (ret) {
 	krb5_rd_req_in_ctx_free(context, in);
@@ -725,7 +776,6 @@
=20
 static krb5_error_code
 get_key_from_keytab(krb5_context context,
-		    krb5_auth_context *auth_context,
 		    krb5_ap_req *ap_req,
 		    krb5_const_principal server,
 		    krb5_keytab keytab,
@@ -740,7 +790,7 @@
 	krb5_kt_default(context, &real_keytab);
     else
 	real_keytab =3D keytab;
-   =20
+
     if (ap_req->ticket.enc_part.kvno)
 	kvno =3D *ap_req->ticket.enc_part.kvno;
     else
@@ -756,18 +806,38 @@
 	goto out;
     ret =3D krb5_copy_keyblock(context, &entry.keyblock, out_key);
     krb5_kt_free_entry (context, &entry);
-out:   =20
+out:
     if(keytab =3D=3D NULL)
 	krb5_kt_close(context, real_keytab);
-   =20
+
     return ret;
 }
=20
-/*
+/**
+ * The core server function that verify application authentication
+ * requests from clients.
  *
+ * @param context Keberos 5 context.
+ * @param auth_context the authentication context, can be NULL, then
+ *        default values for the authentication context will used.
+ * @param inbuf the (AP-REQ) authentication buffer
+ *
+ * @param server the server with authenticate as, if NULL the function
+ *        will try to find any available credential in the keytab
+ *        that will verify the reply. The function will prefer the
+ *        server the server client specified in the AP-REQ, but if
+ *        there is no mach, it will try all keytab entries for a
+ *        match. This have serious performance issues for larger keytabs.
+ *
+ * @param inctx control the behavior of the function, if NULL, the
+ *        default behavior is used.
+ * @param outctx the return outctx, free with krb5_rd_req_out_ctx_free().
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5_auth
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_req_ctx(krb5_context context,
 		krb5_auth_context *auth_context,
 		const krb5_data *inbuf,
@@ -777,12 +847,18 @@
 {
     krb5_error_code ret;
     krb5_ap_req ap_req;
+    krb5_rd_req_out_ctx o =3D NULL;
+    krb5_keytab id =3D NULL, keytab =3D NULL;
     krb5_principal service =3D NULL;
-    krb5_rd_req_out_ctx o =3D NULL;
=20
-    ret =3D _krb5_rd_req_out_ctx_alloc(context, &o);
-    if (ret)
-	goto out;
+    *outctx =3D NULL;
+
+    o =3D calloc(1, sizeof(*o));
+    if (o =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
+	return ENOMEM;
+    }
=20
     if (*auth_context =3D=3D NULL) {
 	ret =3D krb5_auth_con_init(context, auth_context);
@@ -794,66 +870,171 @@
     if(ret)
 	goto out;
=20
-    if(server =3D=3D NULL){
-	ret =3D _krb5_principalname2krb5_principal(context,
-						 &service,
-						 ap_req.ticket.sname,
-						 ap_req.ticket.realm);
-	if (ret)
-	    goto out;
-	server =3D service;
-    }
+    /* Save that principal that was in the request */
+    ret =3D _krb5_principalname2krb5_principal(context,
+					     &o->server,
+					     ap_req.ticket.sname,
+					     ap_req.ticket.realm);
+    if (ret)
+	goto out;
+
     if (ap_req.ap_options.use_session_key &&
 	(*auth_context)->keyblock =3D=3D NULL) {
-	krb5_set_error_string(context, "krb5_rd_req: user to user auth "
-			      "without session key given");
 	ret =3D KRB5KRB_AP_ERR_NOKEY;
+	krb5_set_error_message(context, ret,
+			       N_("krb5_rd_req: user to user auth "
+				  "without session key given", ""));
 	goto out;
     }
=20
+    if (inctx && inctx->keytab)
+	id =3D inctx->keytab;
+
     if((*auth_context)->keyblock){
 	ret =3D krb5_copy_keyblock(context,
 				 (*auth_context)->keyblock,
 				 &o->keyblock);
 	if (ret)
 	    goto out;
-    } else if(inctx->keyblock){
+    } else if(inctx && inctx->keyblock){
 	ret =3D krb5_copy_keyblock(context,
 				 inctx->keyblock,
 				 &o->keyblock);
 	if (ret)
 	    goto out;
     } else {
-	krb5_keytab keytab =3D NULL;
=20
-	if (inctx && inctx->keytab)
-	    keytab =3D inctx->keytab;
+	if(id =3D=3D NULL) {
+	    krb5_kt_default(context, &keytab);
+	    id =3D keytab;
+	}
+	if (id =3D=3D NULL)
+	    goto out;
=20
-	ret =3D get_key_from_keytab(context,=20
-				  auth_context,=20
+	if (server =3D=3D NULL) {
+	    ret =3D _krb5_principalname2krb5_principal(context,
+						     &service,
+						     ap_req.ticket.sname,
+						     ap_req.ticket.realm);
+	    if (ret)
+		goto out;
+	    server =3D service;
+	}
+
+	ret =3D get_key_from_keytab(context,
 				  &ap_req,
 				  server,
-				  keytab,
+				  id,
 				  &o->keyblock);
-	if(ret)
-	    goto out;
+	if (ret) {
+	    /* If caller specified a server, fail. */
+	    if (service =3D=3D NULL && (context->flags & KRB5_CTX_F_RD_REQ_IGNORE=
) =3D=3D 0)
+		goto out;
+	    /* Otherwise, fall back to iterating over the keytab. This
+	     * have serious performace issues for larger keytab.
+	     */
+	    o->keyblock =3D NULL;
+	}
     }
=20
-    ret =3D krb5_verify_ap_req2(context,
-			      auth_context,
-			      &ap_req,
-			      server,
-			      o->keyblock,
-			      0,
-			      &o->ap_req_options,
-			      &o->ticket,
-			      KRB5_KU_AP_REQ_AUTH);
+    if (o->keyblock) {
+	/*
+	 * We got an exact keymatch, use that.
+	 */
=20
-    if (ret)
-	goto out;
+	ret =3D krb5_verify_ap_req2(context,
+				  auth_context,
+				  &ap_req,
+				  server,
+				  o->keyblock,
+				  0,
+				  &o->ap_req_options,
+				  &o->ticket,
+				  KRB5_KU_AP_REQ_AUTH);
+
+	if (ret)
+	    goto out;
+
+    } else {
+	/*
+	 * Interate over keytab to find a key that can decrypt the request.
+	 */
+
+	krb5_keytab_entry entry;
+	krb5_kt_cursor cursor;
+	int done =3D 0, kvno =3D 0;
+
+	memset(&cursor, 0, sizeof(cursor));
+
+	if (ap_req.ticket.enc_part.kvno)
+	    kvno =3D *ap_req.ticket.enc_part.kvno;
+
+	ret =3D krb5_kt_start_seq_get(context, id, &cursor);
+	if (ret)
+	    goto out;
+
+	done =3D 0;
+	while (!done) {
+	    krb5_principal p;
+
+	    ret =3D krb5_kt_next_entry(context, id, &entry, &cursor);
+	    if (ret) {
+		_krb5_kt_principal_not_found(context, ret, id, o->server,
+					     ap_req.ticket.enc_part.etype,
+					     kvno);
+		goto out;
+	    }
+
+	    if (entry.keyblock.keytype !=3D ap_req.ticket.enc_part.etype) {
+		krb5_kt_free_entry (context, &entry);
+		continue;
+	    }
+
+	    ret =3D krb5_verify_ap_req2(context,
+				      auth_context,
+				      &ap_req,
+				      server,
+				      &entry.keyblock,
+				      0,
+				      &o->ap_req_options,
+				      &o->ticket,
+				      KRB5_KU_AP_REQ_AUTH);
+	    if (ret) {
+		krb5_kt_free_entry (context, &entry);
+		continue;
+	    }
+
+	    /*
+	     * Found a match, save the keyblock for PAC processing,
+	     * and update the service principal in the ticket to match
+	     * whatever is in the keytab.
+	     */
+
+	    ret =3D krb5_copy_keyblock(context,
+				     &entry.keyblock,
+				     &o->keyblock);
+	    if (ret) {
+		krb5_kt_free_entry (context, &entry);
+		goto out;
+	    }
+
+	    ret =3D krb5_copy_principal(context, entry.principal, &p);
+	    if (ret) {
+		krb5_kt_free_entry (context, &entry);
+		goto out;
+	    }
+	    krb5_free_principal(context, o->ticket->server);
+	    o->ticket->server =3D p;
+
+	    krb5_kt_free_entry (context, &entry);
+
+	    done =3D 1;
+	}
+	krb5_kt_end_seq_get (context, id, &cursor);
+    }
=20
     /* If there is a PAC, verify its server signature */
-    if (inctx->check_pac) {
+    if (inctx =3D=3D NULL || inctx->check_pac) {
 	krb5_pac pac;
 	krb5_data data;
=20
@@ -866,27 +1047,33 @@
 	    krb5_data_free(&data);
 	    if (ret)
 		goto out;
-=09
+
 	    ret =3D krb5_pac_verify(context,
-				  pac,=20
+				  pac,
 				  o->ticket->ticket.authtime,
-				  o->ticket->client,=20
-				  o->keyblock,=20
+				  o->ticket->client,
+				  o->keyblock,
 				  NULL);
 	    krb5_pac_free(context, pac);
 	    if (ret)
 		goto out;
-	}
-	ret =3D 0;
+	} else
+	  ret =3D 0;
     }
 out:
+
     if (ret || outctx =3D=3D NULL) {
 	krb5_rd_req_out_ctx_free(context, o);
-    } else=20
+    } else
 	*outctx =3D o;
=20
     free_AP_REQ(&ap_req);
-    if(service)
+
+    if (service)
 	krb5_free_principal(context, service);
+
+    if (keytab)
+	krb5_kt_close(context, keytab);
+
     return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/rd_safe.c
--- a/head/crypto/heimdal/lib/krb5/rd_safe.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/rd_safe.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,39 +1,37 @@
 /*
- * Copyright (c) 1997 - 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#include <krb5_locl.h>
-
-RCSID("$Id: rd_safe.c 19827 2007-01-11 02:54:59Z lha $");
+#include "krb5_locl.h"
=20
 static krb5_error_code
 verify_checksum(krb5_context context,
@@ -43,7 +41,7 @@
     krb5_error_code ret;
     u_char *buf;
     size_t buf_size;
-    size_t len;
+    size_t len =3D 0;
     Checksum c;
     krb5_crypto crypto;
     krb5_keyblock *key;
@@ -82,7 +80,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rd_safe(krb5_context context,
 	     krb5_auth_context auth_context,
 	     const krb5_data *inbuf,
@@ -93,33 +91,39 @@
     KRB_SAFE safe;
     size_t len;
=20
-    if (outbuf)
-	krb5_data_zero(outbuf);
+    krb5_data_zero(outbuf);
=20
-    if ((auth_context->flags &=20
-	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)) &&
-	outdata =3D=3D NULL) {
-	krb5_set_error_string(context, "rd_safe: need outdata to return data");
-	return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+    if ((auth_context->flags &
+	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE)))
+    {
+	if (outdata =3D=3D NULL) {
+	    krb5_set_error_message(context, KRB5_RC_REQUIRED,
+				   N_("rd_safe: need outdata "
+				      "to return data", ""));
+	    return KRB5_RC_REQUIRED; /* XXX better error, MIT returns this */
+	}
+	/* if these fields are not present in the safe-part, silently
+           return zero */
+	memset(outdata, 0, sizeof(*outdata));
     }
=20
     ret =3D decode_KRB_SAFE (inbuf->data, inbuf->length, &safe, &len);
-    if (ret)=20
+    if (ret)
 	return ret;
     if (safe.pvno !=3D 5) {
 	ret =3D KRB5KRB_AP_ERR_BADVERSION;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto failure;
     }
     if (safe.msg_type !=3D krb_safe) {
 	ret =3D KRB5KRB_AP_ERR_MSG_TYPE;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto failure;
     }
     if (!krb5_checksum_is_keyed(context, safe.cksum.cksumtype)
 	|| !krb5_checksum_is_collision_proof(context, safe.cksum.cksumtype)) {
 	ret =3D KRB5KRB_AP_ERR_INAPP_CKSUM;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto failure;
     }
=20
@@ -131,7 +135,7 @@
 				  auth_context->remote_address,
 				  safe.safe_body.s_address)) {
 	ret =3D KRB5KRB_AP_ERR_BADADDR;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto failure;
     }
=20
@@ -143,7 +147,7 @@
 				  auth_context->local_address,
 				  safe.safe_body.r_address)) {
 	ret =3D KRB5KRB_AP_ERR_BADADDR;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	goto failure;
     }
=20
@@ -157,7 +161,7 @@
 	    safe.safe_body.usec      =3D=3D NULL ||
 	    abs(*safe.safe_body.timestamp - sec) > context->max_skew) {
 	    ret =3D KRB5KRB_AP_ERR_SKEW;
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    goto failure;
 	}
     }
@@ -174,7 +178,7 @@
 		&& *safe.safe_body.seq_number !=3D
 		auth_context->remote_seqnumber)) {
 	    ret =3D KRB5KRB_AP_ERR_BADORDER;
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    goto failure;
 	}
 	auth_context->remote_seqnumber++;
@@ -183,22 +187,20 @@
     ret =3D verify_checksum (context, auth_context, &safe);
     if (ret)
 	goto failure;
- =20
+
     outbuf->length =3D safe.safe_body.user_data.length;
     outbuf->data   =3D malloc(outbuf->length);
     if (outbuf->data =3D=3D NULL && outbuf->length !=3D 0) {
 	ret =3D ENOMEM;
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
 	krb5_data_zero(outbuf);
 	goto failure;
     }
     memcpy (outbuf->data, safe.safe_body.user_data.data, outbuf->length);
=20
-    if ((auth_context->flags &=20
+    if ((auth_context->flags &
 	 (KRB5_AUTH_CONTEXT_RET_TIME | KRB5_AUTH_CONTEXT_RET_SEQUENCE))) {
-	/* if these fields are not present in the safe-part, silently
-           return zero */
-	memset(outdata, 0, sizeof(*outdata));
+
 	if(safe.safe_body.timestamp)
 	    outdata->timestamp =3D *safe.safe_body.timestamp;
 	if(safe.safe_body.usec)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/read_mess=
age.c
--- a/head/crypto/heimdal/lib/krb5/read_message.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/read_message.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: read_message.c 21750 2007-07-31 20:41:25Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_read_message (krb5_context context,
 		   krb5_pointer p_fd,
 		   krb5_data *data)
@@ -49,29 +47,29 @@
     ret =3D krb5_net_read (context, p_fd, buf, 4);
     if(ret =3D=3D -1) {
 	ret =3D errno;
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return ret;
     }
     if(ret < 4) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return HEIM_ERR_EOF;
     }
     len =3D (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
     ret =3D krb5_data_alloc (data, len);
     if (ret) {
-	krb5_clear_error_string(context);
+	krb5_clear_error_message(context);
 	return ret;
     }
     if (krb5_net_read (context, p_fd, data->data, len) !=3D len) {
 	ret =3D errno;
 	krb5_data_free (data);
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return ret;
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_read_priv_message(krb5_context context,
 		       krb5_auth_context ac,
 		       krb5_pointer p_fd,
@@ -88,7 +86,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_read_safe_message(krb5_context context,
 		       krb5_auth_context ac,
 		       krb5_pointer p_fd,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/recvauth.c
--- a/head/crypto/heimdal/lib/krb5/recvauth.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/recvauth.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: recvauth.c 20306 2007-04-11 11:15:55Z lha $");
-
 /*
  * See `sendauth.c' for the format.
  */
@@ -45,7 +43,7 @@
     return strcmp(data, appl_version) =3D=3D 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_recvauth(krb5_context context,
 	      krb5_auth_context *auth_context,
 	      krb5_pointer p_fd,
@@ -61,11 +59,11 @@
 				       keytab, ticket);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_recvauth_match_version(krb5_context context,
 			    krb5_auth_context *auth_context,
 			    krb5_pointer p_fd,
-			    krb5_boolean (*match_appl_version)(const void *,=20
+			    krb5_boolean (*match_appl_version)(const void *,
 							       const char*),
 			    const void *match_data,
 			    krb5_principal server,
@@ -103,11 +101,12 @@
 	n =3D krb5_net_read (context, p_fd, &len, 4);
 	if (n < 0) {
 	    ret =3D errno;
-	    krb5_set_error_string (context, "read: %s", strerror(errno));
+	    krb5_set_error_message(context, ret, "read: %s", strerror(ret));
 	    return ret;
 	}
 	if (n =3D=3D 0) {
-	    krb5_set_error_string (context, "Failed to receive sendauth data");
+	    krb5_set_error_message(context, KRB5_SENDAUTH_BADAUTHVERS,
+				   N_("Failed to receive sendauth data", ""));
 	    return KRB5_SENDAUTH_BADAUTHVERS;
 	}
 	len =3D ntohl(len);
@@ -116,7 +115,7 @@
 	    || strncmp (version, her_version, len)) {
 	    repl =3D 1;
 	    krb5_net_write (context, p_fd, &repl, 1);
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    return KRB5_SENDAUTH_BADAUTHVERS;
 	}
     }
@@ -124,11 +123,11 @@
     n =3D krb5_net_read (context, p_fd, &len, 4);
     if (n < 0) {
 	ret =3D errno;
-	krb5_set_error_string (context, "read: %s", strerror(errno));
+	krb5_set_error_message(context, ret, "read: %s", strerror(ret));
 	return ret;
     }
     if (n =3D=3D 0) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_SENDAUTH_BADAPPLVERS;
     }
     len =3D ntohl(len);
@@ -136,14 +135,16 @@
     if (her_appl_version =3D=3D NULL) {
 	repl =3D 2;
 	krb5_net_write (context, p_fd, &repl, 1);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     if (krb5_net_read (context, p_fd, her_appl_version, len) !=3D len
 	|| !(*match_appl_version)(match_data, her_appl_version)) {
 	repl =3D 2;
 	krb5_net_write (context, p_fd, &repl, 1);
-	krb5_set_error_string (context, "wrong sendauth version (%s)",
+	krb5_set_error_message(context, KRB5_SENDAUTH_BADAPPLVERS,
+			       N_("wrong sendauth version (%s)", ""),
 			       her_appl_version);
 	free (her_appl_version);
 	return KRB5_SENDAUTH_BADAPPLVERS;
@@ -153,7 +154,7 @@
     repl =3D 0;
     if (krb5_net_write (context, p_fd, &repl, 1) !=3D 1) {
 	ret =3D errno;
-	krb5_set_error_string (context, "write: %s", strerror(errno));
+	krb5_set_error_message(context, ret, "write: %s", strerror(ret));
 	return ret;
     }
=20
@@ -188,23 +189,31 @@
 	    krb5_data_free (&error_data);
 	}
 	return ret;
-    }     =20
+    }
=20
     len =3D 0;
     if (krb5_net_write (context, p_fd, &len, 4) !=3D 4) {
 	ret =3D errno;
-	krb5_set_error_string (context, "write: %s", strerror(errno));
+	krb5_set_error_message(context, ret, "write: %s", strerror(ret));
+	krb5_free_ticket(context, *ticket);
+	*ticket =3D NULL;
 	return ret;
     }
=20
     if (ap_options & AP_OPTS_MUTUAL_REQUIRED) {
 	ret =3D krb5_mk_rep (context, *auth_context, &data);
-	if (ret)
+	if (ret) {
+	    krb5_free_ticket(context, *ticket);
+	    *ticket =3D NULL;
 	    return ret;
+	}
=20
 	ret =3D krb5_write_message (context, p_fd, &data);
-	if (ret)
+	if (ret) {
+	    krb5_free_ticket(context, *ticket);
+	    *ticket =3D NULL;
 	    return ret;
+	}
 	krb5_data_free (&data);
     }
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/replay.c
--- a/head/crypto/heimdal/lib/krb5/replay.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/replay.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,78 +1,79 @@
 /*
- * Copyright (c) 1997-2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include <vis.h>
=20
-RCSID("$Id: replay.c 17047 2006-04-10 17:13:49Z lha $");
-
 struct krb5_rcache_data {
     char *name;
 };
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_resolve(krb5_context context,
 		krb5_rcache id,
 		const char *name)
 {
     id->name =3D strdup(name);
     if(id->name =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_RC_MALLOC,
+			       N_("malloc: out of memory", ""));
 	return KRB5_RC_MALLOC;
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_resolve_type(krb5_context context,
 		     krb5_rcache *id,
 		     const char *type)
 {
     *id =3D NULL;
     if(strcmp(type, "FILE")) {
-	krb5_set_error_string (context, "replay cache type %s not supported",
-			       type);
+	krb5_set_error_message (context, KRB5_RC_TYPE_NOTFOUND,
+				N_("replay cache type %s not supported", ""),
+				type);
 	return KRB5_RC_TYPE_NOTFOUND;
     }
     *id =3D calloc(1, sizeof(**id));
     if(*id =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, KRB5_RC_MALLOC,
+			       N_("malloc: out of memory", ""));
 	return KRB5_RC_MALLOC;
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_resolve_full(krb5_context context,
 		     krb5_rcache *id,
 		     const char *string_name)
@@ -82,7 +83,8 @@
     *id =3D NULL;
=20
     if(strncmp(string_name, "FILE:", 5)) {
-	krb5_set_error_string (context, "replay cache type %s not supported",
+	krb5_set_error_message(context, KRB5_RC_TYPE_NOTFOUND,
+			       N_("replay cache type %s not supported", ""),
 			       string_name);
 	return KRB5_RC_TYPE_NOTFOUND;
     }
@@ -97,19 +99,19 @@
     return ret;
 }
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_default_name(krb5_context context)
 {
     return "FILE:/var/run/default_rcache";
 }
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_default_type(krb5_context context)
 {
     return "FILE";
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_default(krb5_context context,
 		krb5_rcache *id)
 {
@@ -121,7 +123,7 @@
     unsigned char data[16];
 };
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_initialize(krb5_context context,
 		   krb5_rcache id,
 		   krb5_deltat auth_lifespan)
@@ -131,9 +133,10 @@
     int ret;
=20
     if(f =3D=3D NULL) {
+	char buf[128];
 	ret =3D errno;
-	krb5_set_error_string (context, "open(%s): %s", id->name,
-			       strerror(ret));
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret, "open(%s): %s", id->name, buf);
 	return ret;
     }
     tmp.stamp =3D auth_lifespan;
@@ -142,29 +145,30 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_recover(krb5_context context,
 		krb5_rcache id)
 {
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_destroy(krb5_context context,
 		krb5_rcache id)
 {
     int ret;
=20
     if(remove(id->name) < 0) {
+	char buf[128];
 	ret =3D errno;
-	krb5_set_error_string (context, "remove(%s): %s", id->name,
-			       strerror(ret));
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret, "remove(%s): %s", id->name, buf);
 	return ret;
     }
     return krb5_rc_close(context, id);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_close(krb5_context context,
 	      krb5_rcache id)
 {
@@ -176,20 +180,23 @@
 static void
 checksum_authenticator(Authenticator *auth, void *data)
 {
-    MD5_CTX md5;
-    int i;
+    EVP_MD_CTX *m =3D EVP_MD_CTX_create();
+    unsigned i;
=20
-    MD5_Init (&md5);
-    MD5_Update (&md5, auth->crealm, strlen(auth->crealm));
+    EVP_DigestInit_ex(m, EVP_md5(), NULL);
+
+    EVP_DigestUpdate(m, auth->crealm, strlen(auth->crealm));
     for(i =3D 0; i < auth->cname.name_string.len; i++)
-	MD5_Update(&md5, auth->cname.name_string.val[i],=20
+	EVP_DigestUpdate(m, auth->cname.name_string.val[i],
 		   strlen(auth->cname.name_string.val[i]));
-    MD5_Update (&md5, &auth->ctime, sizeof(auth->ctime));
-    MD5_Update (&md5, &auth->cusec, sizeof(auth->cusec));
-    MD5_Final (data, &md5);
+    EVP_DigestUpdate(m, &auth->ctime, sizeof(auth->ctime));
+    EVP_DigestUpdate(m, &auth->cusec, sizeof(auth->cusec));
+
+    EVP_DigestFinal_ex(m, data, NULL);
+    EVP_MD_CTX_destroy(m);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_store(krb5_context context,
 	      krb5_rcache id,
 	      krb5_donot_replay *rep)
@@ -203,11 +210,13 @@
     checksum_authenticator(rep, ent.data);
     f =3D fopen(id->name, "r");
     if(f =3D=3D NULL) {
+	char buf[128];
 	ret =3D errno;
-	krb5_set_error_string (context, "open(%s): %s", id->name,
-			       strerror(ret));
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret, "open(%s): %s", id->name, buf);
 	return ret;
     }
+    rk_cloexec_file(f);
     fread(&tmp, sizeof(ent), 1, f);
     t =3D ent.stamp - tmp.stamp;
     while(fread(&tmp, sizeof(ent), 1, f)){
@@ -215,21 +224,26 @@
 	    continue;
 	if(memcmp(tmp.data, ent.data, sizeof(ent.data)) =3D=3D 0){
 	    fclose(f);
-	    krb5_clear_error_string (context);
+	    krb5_clear_error_message (context);
 	    return KRB5_RC_REPLAY;
 	}
     }
     if(ferror(f)){
+	char buf[128];
 	ret =3D errno;
 	fclose(f);
-	krb5_set_error_string (context, "%s: %s", id->name, strerror(ret));
+	rk_strerror_r(ret, buf, sizeof(buf));
+	krb5_set_error_message(context, ret, "%s: %s",
+			       id->name, buf);
 	return ret;
     }
     fclose(f);
     f =3D fopen(id->name, "a");
     if(f =3D=3D NULL) {
-	krb5_set_error_string (context, "open(%s): %s", id->name,
-			       strerror(errno));
+	char buf[128];
+	rk_strerror_r(errno, buf, sizeof(buf));
+	krb5_set_error_message(context, KRB5_RC_IO_UNKNOWN,
+			       "open(%s): %s", id->name, buf);
 	return KRB5_RC_IO_UNKNOWN;
     }
     fwrite(&ent, 1, sizeof(ent), f);
@@ -237,14 +251,14 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_expunge(krb5_context context,
 		krb5_rcache id)
 {
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_rc_get_lifespan(krb5_context context,
 		     krb5_rcache id,
 		     krb5_deltat *auth_lifespan)
@@ -258,27 +272,27 @@
 	*auth_lifespan =3D ent.stamp;
 	return 0;
     }
-    krb5_clear_error_string (context);
+    krb5_clear_error_message (context);
     return KRB5_RC_IO_UNKNOWN;
 }
=20
-const char* KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_get_name(krb5_context context,
 		 krb5_rcache id)
 {
     return id->name;
 }
-		=20
-const char* KRB5_LIB_FUNCTION
+
+KRB5_LIB_FUNCTION const char* KRB5_LIB_CALL
 krb5_rc_get_type(krb5_context context,
 		 krb5_rcache id)
 {
     return "FILE";
 }
-		=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_get_server_rcache(krb5_context context,=20
-		       const krb5_data *piece,=20
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_server_rcache(krb5_context context,
+		       const krb5_data *piece,
 		       krb5_rcache *id)
 {
     krb5_rcache rcache;
@@ -288,18 +302,20 @@
     char *name;
=20
     if(tmp =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     strvisx(tmp, piece->data, piece->length, VIS_WHITE | VIS_OCTAL);
 #ifdef HAVE_GETEUID
-    asprintf(&name, "FILE:rc_%s_%u", tmp, (unsigned)geteuid());
+    ret =3D asprintf(&name, "FILE:rc_%s_%u", tmp, (unsigned)geteuid());
 #else
-    asprintf(&name, "FILE:rc_%s", tmp);
+    ret =3D asprintf(&name, "FILE:rc_%s", tmp);
 #endif
     free(tmp);
-    if(name =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+    if(ret < 0 || name =3D=3D NULL) {
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/send_to_k=
dc.c
--- a/head/crypto/heimdal/lib/krb5/send_to_kdc.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/send_to_kdc.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,39 +1,38 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
-
-RCSID("$Id: send_to_kdc.c 21934 2007-08-27 14:21:04Z lha $");
+#include "send_to_kdc_plugin.h"
=20
 struct send_to_kdc {
     krb5_send_to_kdc_func func;
@@ -48,7 +47,7 @@
  */
=20
 static int
-recv_loop (int fd,
+recv_loop (krb5_socket_t fd,
 	   time_t tmout,
 	   int udp,
 	   size_t limit,
@@ -59,9 +58,11 @@
      int ret;
      int nbytes;
=20
+#ifndef NO_LIMIT_FD_SETSIZE
      if (fd >=3D FD_SETSIZE) {
 	 return -1;
      }
+#endif
=20
      krb5_data_zero(rep);
      do {
@@ -79,7 +80,7 @@
 	 } else {
 	     void *tmp;
=20
-	     if (ioctl (fd, FIONREAD, &nbytes) < 0) {
+	     if (rk_SOCK_IOCTL (fd, FIONREAD, &nbytes) < 0) {
 		 krb5_data_free (rep);
 		 return -1;
 	     }
@@ -87,7 +88,7 @@
 		 return 0;
=20
 	     if (limit)
-		 nbytes =3D min(nbytes, limit - rep->length);
+		 nbytes =3D min((size_t)nbytes, limit - rep->length);
=20
 	     tmp =3D realloc (rep->data, rep->length + nbytes);
 	     if (tmp =3D=3D NULL) {
@@ -112,7 +113,7 @@
  */
=20
 static int
-send_and_recv_udp(int fd,=20
+send_and_recv_udp(krb5_socket_t fd,
 		  time_t tmout,
 		  const krb5_data *req,
 		  krb5_data *rep)
@@ -131,7 +132,7 @@
  */
=20
 static int
-send_and_recv_tcp(int fd,=20
+send_and_recv_tcp(krb5_socket_t fd,
 		  time_t tmout,
 		  const krb5_data *req,
 		  krb5_data *rep)
@@ -141,9 +142,9 @@
     krb5_data len_data;
=20
     _krb5_put_int(len, req->length, 4);
-    if(net_write(fd, len, sizeof(len)) < 0)
+    if(net_write (fd, len, sizeof(len)) < 0)
 	return -1;
-    if(net_write(fd, req->data, req->length) < 0)
+    if(net_write (fd, req->data, req->length) < 0)
 	return -1;
     if (recv_loop (fd, tmout, 0, 4, &len_data) < 0)
 	return -1;
@@ -163,7 +164,7 @@
 }
=20
 int
-_krb5_send_and_recv_tcp(int fd,
+_krb5_send_and_recv_tcp(krb5_socket_t fd,
 			time_t tmout,
 			const krb5_data *req,
 			krb5_data *rep)
@@ -176,22 +177,22 @@
  */
=20
 static int
-send_and_recv_http(int fd,=20
+send_and_recv_http(krb5_socket_t fd,
 		   time_t tmout,
 		   const char *prefix,
 		   const krb5_data *req,
 		   krb5_data *rep)
 {
-    char *request;
+    char *request =3D NULL;
     char *str;
     int ret;
     int len =3D base64_encode(req->data, req->length, &str);
=20
     if(len < 0)
 	return -1;
-    asprintf(&request, "GET %s%s HTTP/1.0\r\n\r\n", prefix, str);
+    ret =3D asprintf(&request, "GET %s%s HTTP/1.0\r\n\r\n", prefix, str);
     free(str);
-    if (request =3D=3D NULL)
+    if (ret < 0 || request =3D=3D NULL)
 	return -1;
     ret =3D net_write (fd, request, strlen(request));
     free (request);
@@ -260,14 +261,14 @@
 {
     char *proxy2 =3D strdup(context->http_proxy);
     char *proxy  =3D proxy2;
-    char *prefix;
+    char *prefix =3D NULL;
     char *colon;
     struct addrinfo hints;
     struct addrinfo *ai, *a;
     int ret;
-    int s =3D -1;
+    krb5_socket_t s =3D rk_INVALID_SOCKET;
     char portstr[NI_MAXSERV];
-		=20
+
     if (proxy =3D=3D NULL)
 	return ENOMEM;
     if (strncmp (proxy, "http://", 7) =3D=3D 0)
@@ -287,11 +288,12 @@
 	return krb5_eai_to_heim_errno(ret, errno);
=20
     for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
-	s =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
+	s =3D socket (a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_protocol=
);
 	if (s < 0)
 	    continue;
+	rk_cloexec(s);
 	if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
-	    close (s);
+	    rk_closesocket (s);
 	    continue;
 	}
 	break;
@@ -302,34 +304,74 @@
     }
     freeaddrinfo (ai);
=20
-    asprintf(&prefix, "http://%s/", hi->hostname);
-    if(prefix =3D=3D NULL) {
+    ret =3D asprintf(&prefix, "http://%s/", hi->hostname);
+    if(ret < 0 || prefix =3D=3D NULL) {
 	close(s);
 	return 1;
     }
     ret =3D send_and_recv_http(s, context->kdc_timeout,
 			     prefix, send_data, receive);
-    close (s);
+    rk_closesocket (s);
     free(prefix);
     if(ret =3D=3D 0 && receive->length !=3D 0)
 	return 0;
     return 1;
 }
=20
+static krb5_error_code
+send_via_plugin(krb5_context context,
+		krb5_krbhst_info *hi,
+		time_t timeout,
+		const krb5_data *send_data,
+		krb5_data *receive)
+{
+    struct krb5_plugin *list =3D NULL, *e;
+    krb5_error_code ret;
+
+    ret =3D _krb5_plugin_find(context, PLUGIN_TYPE_DATA, KRB5_PLUGIN_SEND_=
TO_KDC, &list);
+    if(ret !=3D 0 || list =3D=3D NULL)
+	return KRB5_PLUGIN_NO_HANDLE;
+
+    for (e =3D list; e !=3D NULL; e =3D _krb5_plugin_get_next(e)) {
+	krb5plugin_send_to_kdc_ftable *service;
+	void *ctx;
+
+	service =3D _krb5_plugin_get_symbol(e);
+	if (service->minor_version !=3D 0)
+	    continue;
+
+	(*service->init)(context, &ctx);
+	ret =3D (*service->send_to_kdc)(context, ctx, hi,
+				      timeout, send_data, receive);
+	(*service->fini)(ctx);
+	if (ret =3D=3D 0)
+	    break;
+	if (ret !=3D KRB5_PLUGIN_NO_HANDLE) {
+	    krb5_set_error_message(context, ret,
+				   N_("Plugin send_to_kdc failed to "
+				      "lookup with error: %d", ""), ret);
+	    break;
+	}
+    }
+    _krb5_plugin_free(list);
+    return KRB5_PLUGIN_NO_HANDLE;
+}
+
+
 /*
  * Send the data `send' to one host from `handle` and get back the reply
  * in `receive'.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto (krb5_context context,
 	     const krb5_data *send_data,
-	     krb5_krbhst_handle handle,	    =20
+	     krb5_krbhst_handle handle,
 	     krb5_data *receive)
 {
      krb5_error_code ret;
-     int fd;
-     int i;
+     krb5_socket_t fd;
+     size_t i;
=20
      krb5_data_zero(receive);
=20
@@ -339,16 +381,27 @@
 	 while (krb5_krbhst_next(context, handle, &hi) =3D=3D 0) {
 	     struct addrinfo *ai, *a;
=20
+	     _krb5_debug(context, 2,
+			 "trying to communicate with host %s in realm %s",
+			 hi->hostname, _krb5_krbhst_get_realm(handle));
+
 	     if (context->send_to_kdc) {
 		 struct send_to_kdc *s =3D context->send_to_kdc;
=20
-		 ret =3D (*s->func)(context, s->data,=20
-				  hi, send_data, receive);
+		 ret =3D (*s->func)(context, s->data, hi,
+				  context->kdc_timeout, send_data, receive);
 		 if (ret =3D=3D 0 && receive->length !=3D 0)
 		     goto out;
 		 continue;
 	     }
=20
+	     ret =3D send_via_plugin(context, hi, context->kdc_timeout,
+				   send_data, receive);
+	     if (ret =3D=3D 0 && receive->length !=3D 0)
+		 goto out;
+	     else if (ret !=3D KRB5_PLUGIN_NO_HANDLE)
+		 continue;
+
 	     if(hi->proto =3D=3D KRB5_KRBHST_HTTP && context->http_proxy) {
 		 if (send_via_proxy (context, hi, send_data, receive) =3D=3D 0) {
 		     ret =3D 0;
@@ -362,11 +415,12 @@
 		 continue;
=20
 	     for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
-		 fd =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
-		 if (fd < 0)
+		 fd =3D socket (a->ai_family, a->ai_socktype | SOCK_CLOEXEC, a->ai_proto=
col);
+		 if (rk_IS_BAD_SOCKET(fd))
 		     continue;
+		 rk_cloexec(fd);
 		 if (connect (fd, a->ai_addr, a->ai_addrlen) < 0) {
-		     close (fd);
+		     rk_closesocket (fd);
 		     continue;
 		 }
 		 switch (hi->proto) {
@@ -383,20 +437,23 @@
 					      send_data, receive);
 		     break;
 		 }
-		 close (fd);
+		 rk_closesocket (fd);
 		 if(ret =3D=3D 0 && receive->length !=3D 0)
 		     goto out;
 	     }
 	 }
 	 krb5_krbhst_reset(context, handle);
      }
-     krb5_clear_error_string (context);
+     krb5_clear_error_message (context);
      ret =3D KRB5_KDC_UNREACH;
 out:
+     _krb5_debug(context, 2,
+		 "result of trying to talk to realm %s =3D %d",
+		 _krb5_krbhst_get_realm(handle), ret);
      return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_kdc(krb5_context context,
 		const krb5_data *send_data,
 		const krb5_realm *realm,
@@ -405,7 +462,7 @@
     return krb5_sendto_kdc_flags(context, send_data, realm, receive, 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_kdc_flags(krb5_context context,
 		      const krb5_data *send_data,
 		      const krb5_realm *realm,
@@ -426,8 +483,8 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_set_send_to_kdc_func(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_set_send_to_kdc_func(krb5_context context,
 			  krb5_send_to_kdc_func func,
 			  void *data)
 {
@@ -439,7 +496,8 @@
=20
     context->send_to_kdc =3D malloc(sizeof(*context->send_to_kdc));
     if (context->send_to_kdc =3D=3D NULL) {
-	krb5_set_error_string(context, "Out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
=20
@@ -448,6 +506,19 @@
     return 0;
 }
=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+_krb5_copy_send_to_kdc_func(krb5_context context, krb5_context to)
+{
+    if (context->send_to_kdc)
+	return krb5_set_send_to_kdc_func(to,
+					 context->send_to_kdc->func,
+					 context->send_to_kdc->data);
+    else
+	return krb5_set_send_to_kdc_func(to, NULL, NULL);
+}
+
+
+
 struct krb5_sendto_ctx_data {
     int flags;
     int type;
@@ -455,37 +526,38 @@
     void *data;
 };
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_ctx_alloc(krb5_context context, krb5_sendto_ctx *ctx)
 {
     *ctx =3D calloc(1, sizeof(**ctx));
     if (*ctx =3D=3D NULL) {
-	krb5_set_error_string(context, "out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     return 0;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_add_flags(krb5_sendto_ctx ctx, int flags)
 {
     ctx->flags |=3D flags;
 }
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_sendto_ctx_get_flags(krb5_sendto_ctx ctx)
 {
     return ctx->flags;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_set_type(krb5_sendto_ctx ctx, int type)
 {
     ctx->type =3D type;
 }
=20
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_set_func(krb5_sendto_ctx ctx,
 			 krb5_sendto_ctx_func func,
 			 void *data)
@@ -494,14 +566,14 @@
     ctx->data =3D data;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_sendto_ctx_free(krb5_context context, krb5_sendto_ctx ctx)
 {
     memset(ctx, 0, sizeof(*ctx));
     free(ctx);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendto_context(krb5_context context,
 		    krb5_sendto_ctx ctx,
 		    const krb5_data *send_data,
@@ -530,7 +602,7 @@
 	    type =3D KRB5_KRBHST_KDC;
     }
=20
-    if (send_data->length > context->large_msg_size)
+    if ((int)send_data->length > context->large_msg_size)
 	ctx->flags |=3D KRB5_KRBHST_FLAGS_LARGE_MSG;
=20
     /* loop until we get back a appropriate response */
@@ -541,7 +613,7 @@
 	krb5_data_free(receive);
=20
 	if (handle =3D=3D NULL) {
-	    ret =3D krb5_krbhst_init_flags(context, realm, type,=20
+	    ret =3D krb5_krbhst_init_flags(context, realm, type,
 					 ctx->flags, &handle);
 	    if (ret) {
 		if (freectx)
@@ -549,7 +621,7 @@
 		return ret;
 	    }
 	}
-   =20
+
 	ret =3D krb5_sendto(context, send_data, handle, receive);
 	if (ret)
 	    break;
@@ -566,8 +638,9 @@
     if (handle)
 	krb5_krbhst_free(context, handle);
     if (ret =3D=3D KRB5_KDC_UNREACH)
-	krb5_set_error_string(context,=20
-			      "unable to reach any KDC in realm %s", realm);
+	krb5_set_error_message(context, ret,
+			       N_("unable to reach any KDC in realm %s", ""),
+			       realm);
     if (ret)
 	krb5_data_free(receive);
     if (freectx)
@@ -575,7 +648,7 @@
     return ret;
 }
=20
-krb5_error_code
+krb5_error_code KRB5_CALLCONV
 _krb5_kdc_retry(krb5_context context, krb5_sendto_ctx ctx, void *data,
 		const krb5_data *reply, int *action)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/sendauth.c
--- a/head/crypto/heimdal/lib/krb5/sendauth.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/sendauth.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: sendauth.c 17442 2006-05-05 09:31:15Z lha $");
-
 /*
  * The format seems to be:
  * client -> server
@@ -62,7 +60,7 @@
  * }
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sendauth(krb5_context context,
 	      krb5_auth_context *auth_context,
 	      krb5_pointer p_fd,
@@ -93,7 +91,7 @@
     if (krb5_net_write (context, p_fd, &net_len, 4) !=3D 4
 	|| krb5_net_write (context, p_fd, version, len) !=3D len) {
 	ret =3D errno;
-	krb5_set_error_string (context, "write: %s", strerror(ret));
+	krb5_set_error_message (context, ret, "write: %s", strerror(ret));
 	return ret;
     }
=20
@@ -102,22 +100,22 @@
     if (krb5_net_write (context, p_fd, &net_len, 4) !=3D 4
 	|| krb5_net_write (context, p_fd, appl_version, len) !=3D len) {
 	ret =3D errno;
-	krb5_set_error_string (context, "write: %s", strerror(ret));
+	krb5_set_error_message (context, ret, "write: %s", strerror(ret));
 	return ret;
     }
=20
     sret =3D krb5_net_read (context, p_fd, &repl, sizeof(repl));
     if (sret < 0) {
 	ret =3D errno;
-	krb5_set_error_string (context, "read: %s", strerror(ret));
+	krb5_set_error_message (context, ret, "read: %s", strerror(ret));
 	return ret;
     } else if (sret !=3D sizeof(repl)) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_SENDAUTH_BADRESPONSE;
     }
=20
     if (repl !=3D 0) {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5_SENDAUTH_REJECTED;
     }
=20
@@ -205,14 +203,15 @@
 	    }
 	    return ret;
 	} else {
-	    krb5_clear_error_string(context);
+	    krb5_clear_error_message(context);
 	    return ret;
 	}
-    }
+    } else
+	krb5_data_free (&error_data);
=20
     if (ap_req_options & AP_OPTS_MUTUAL_REQUIRED) {
 	krb5_data ap_rep;
-	krb5_ap_rep_enc_part *ignore;
+	krb5_ap_rep_enc_part *ignore =3D NULL;
=20
 	krb5_data_zero (&ap_rep);
 	ret =3D krb5_read_message (context,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/set_defau=
lt_realm.c
--- a/head/crypto/heimdal/lib/krb5/set_default_realm.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/set_default_realm.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,42 +1,40 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: set_default_realm.c 13863 2004-05-25 21:46:46Z lha $");
-
 /*
- * Convert the simple string `s' into a NULL-terminated and freshly alloca=
ted=20
+ * Convert the simple string `s' into a NULL-terminated and freshly alloca=
ted
  * list in `list'.  Return an error code.
  */
=20
@@ -46,13 +44,15 @@
=20
     *list =3D malloc (2 * sizeof(**list));
     if (*list =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     (*list)[0] =3D strdup (s);
     if ((*list)[0] =3D=3D NULL) {
 	free (*list);
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     (*list)[1] =3D NULL;
@@ -62,10 +62,10 @@
 /*
  * Set the knowledge of the default realm(s) in `context'.
  * If realm !=3D NULL, that's the new default realm.
- * Otherwise, the realm(s) are figured out from configuration or DNS. =20
+ * Otherwise, the realm(s) are figured out from configuration or DNS.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_default_realm(krb5_context context,
 		       const char *realm)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/sock_prin=
cipal.c
--- a/head/crypto/heimdal/lib/krb5/sock_principal.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/sock_principal.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: sock_principal.c 13863 2004-05-25 21:46:46Z lha $");
-		=09
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_sock_to_principal (krb5_context context,
 			int sock,
 			const char *sname,
@@ -50,15 +48,15 @@
=20
     if (getsockname (sock, sa, &salen) < 0) {
 	ret =3D errno;
-	krb5_set_error_string (context, "getsockname: %s", strerror(ret));
+	krb5_set_error_message (context, ret, "getsockname: %s", strerror(ret));
 	return ret;
     }
     ret =3D getnameinfo (sa, salen, hostname, sizeof(hostname), NULL, 0, 0=
);
     if (ret) {
 	int save_errno =3D errno;
-
-	krb5_set_error_string (context, "getnameinfo: %s", gai_strerror(ret));
-	return krb5_eai_to_heim_errno(ret, save_errno);
+	krb5_error_code ret2 =3D krb5_eai_to_heim_errno(ret, save_errno);
+	krb5_set_error_message (context, ret2, "getnameinfo: %s", gai_strerror(re=
t));
+	return ret2;
     }
=20
     ret =3D krb5_sname_to_principal (context,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/store-int=
.h
--- a/head/crypto/heimdal/lib/krb5/store-int.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/store-int.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,34 +1,34 @@
 /*
- * Copyright (c) 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #ifndef __store_int_h__
@@ -39,9 +39,11 @@
     ssize_t (*fetch)(struct krb5_storage_data*, void*, size_t);
     ssize_t (*store)(struct krb5_storage_data*, const void*, size_t);
     off_t (*seek)(struct krb5_storage_data*, off_t, int);
+    int (*trunc)(struct krb5_storage_data*, off_t);
     void (*free)(struct krb5_storage_data*);
     krb5_flags flags;
     int eof_code;
+    size_t max_alloc;
 };
=20
 #endif /* __store_int_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/store-tes=
t.c
--- a/head/crypto/heimdal/lib/krb5/store-test.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/store-test.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,8 +32,6 @@
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: store-test.c 16344 2005-12-02 15:15:43Z lha $");
-
 static void
 print_data(unsigned char *data, size_t len)
 {
@@ -51,7 +49,8 @@
 {
     int ret =3D 0;
     krb5_data data;
-    krb5_storage_to_data(sp, &data);
+    if (krb5_storage_to_data(sp, &data))
+	errx(1, "krb5_storage_to_data failed");
     krb5_storage_free(sp);
     if(data.length !=3D len || memcmp(data.data, expected, len) !=3D 0) {
 	printf("%s mismatch\n", name);
@@ -72,7 +71,7 @@
     krb5_storage *sp;
     krb5_context context;
     krb5_principal principal;
-=09
+
=20
     krb5_init_context(&context);
=20
@@ -96,9 +95,9 @@
     {
 	int test =3D 1;
 	void *data;
-	if(*(char*)&test)=20
+	if(*(char*)&test)
 	    data =3D "\x4\x3\x2\x1";
-	else=20
+	else
 	    data =3D "\x1\x2\x3\x4";
 	nerr +=3D compare("Integer (host)", sp, data, 4);
     }
@@ -111,7 +110,7 @@
 		    "\x0\x0\x0\x1"
 		    "\x0\x0\x0\x4TEST"
 		    "\x0\x0\x0\x6""foobar", 26);
-   =20
+
     krb5_free_context(context);
=20
     return nerr ? 1 : 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/store.c
--- a/head/crypto/heimdal/lib/krb5/store.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/store.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,127 +1,273 @@
 /*
- * Copyright (c) 1997-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include "store-int.h"
=20
-RCSID("$Id: store.c 22071 2007-11-14 20:04:50Z lha $");
-
 #define BYTEORDER_IS(SP, V) (((SP)->flags & KRB5_STORAGE_BYTEORDER_MASK) =
=3D=3D (V))
 #define BYTEORDER_IS_LE(SP) BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_LE)
 #define BYTEORDER_IS_BE(SP) BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_BE)
 #define BYTEORDER_IS_HOST(SP) (BYTEORDER_IS((SP), KRB5_STORAGE_BYTEORDER_H=
OST) || \
 			       krb5_storage_is_flags((SP), KRB5_STORAGE_HOST_BYTEORDER))
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Add the flags on a storage buffer by or-ing in the flags to the buffer.
+ *
+ * @param sp the storage buffer to set the flags on
+ * @param flags the flags to set
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_set_flags(krb5_storage *sp, krb5_flags flags)
 {
     sp->flags |=3D flags;
 }
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Clear the flags on a storage buffer
+ *
+ * @param sp the storage buffer to clear the flags on
+ * @param flags the flags to clear
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_clear_flags(krb5_storage *sp, krb5_flags flags)
 {
     sp->flags &=3D ~flags;
 }
=20
-krb5_boolean KRB5_LIB_FUNCTION
+/**
+ * Return true or false depending on if the storage flags is set or
+ * not. NB testing for the flag 0 always return true.
+ *
+ * @param sp the storage buffer to check flags on
+ * @param flags The flags to test for
+ *
+ * @return true if all the flags are set, false if not.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_boolean KRB5_LIB_CALL
 krb5_storage_is_flags(krb5_storage *sp, krb5_flags flags)
 {
     return (sp->flags & flags) =3D=3D flags;
 }
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Set the new byte order of the storage buffer.
+ *
+ * @param sp the storage buffer to set the byte order for.
+ * @param byteorder the new byte order.
+ *
+ * The byte order are: KRB5_STORAGE_BYTEORDER_BE,
+ * KRB5_STORAGE_BYTEORDER_LE and KRB5_STORAGE_BYTEORDER_HOST.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_set_byteorder(krb5_storage *sp, krb5_flags byteorder)
 {
     sp->flags &=3D ~KRB5_STORAGE_BYTEORDER_MASK;
     sp->flags |=3D byteorder;
 }
=20
-krb5_flags KRB5_LIB_FUNCTION
-krb5_storage_get_byteorder(krb5_storage *sp, krb5_flags byteorder)
+/**
+ * Return the current byteorder for the buffer. See krb5_storage_set_byteo=
rder() for the list or byte order contants.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_flags KRB5_LIB_CALL
+krb5_storage_get_byteorder(krb5_storage *sp)
 {
     return sp->flags & KRB5_STORAGE_BYTEORDER_MASK;
 }
=20
-off_t KRB5_LIB_FUNCTION
+/**
+ * Set the max alloc value
+ *
+ * @param sp the storage buffer set the max allow for
+ * @param size maximum size to allocate, use 0 to remove limit
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
+krb5_storage_set_max_alloc(krb5_storage *sp, size_t size)
+{
+    sp->max_alloc =3D size;
+}
+
+/* don't allocate unresonable amount of memory */
+static krb5_error_code
+size_too_large(krb5_storage *sp, size_t size)
+{
+    if (sp->max_alloc && sp->max_alloc < size)
+	return HEIM_ERR_TOO_BIG;
+    return 0;
+}
+
+static krb5_error_code
+size_too_large_num(krb5_storage *sp, size_t count, size_t size)
+{
+    if (sp->max_alloc =3D=3D 0 || size =3D=3D 0)
+	return 0;
+    size =3D sp->max_alloc / size;
+    if (size < count)
+	return HEIM_ERR_TOO_BIG;
+    return 0;
+}
+
+/**
+ * Seek to a new offset.
+ *
+ * @param sp the storage buffer to seek in.
+ * @param offset the offset to seek
+ * @param whence relateive searching, SEEK_CUR from the current
+ * position, SEEK_END from the end, SEEK_SET absolute from the start.
+ *
+ * @return The new current offset
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION off_t KRB5_LIB_CALL
 krb5_storage_seek(krb5_storage *sp, off_t offset, int whence)
 {
     return (*sp->seek)(sp, offset, whence);
 }
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+/**
+ * Truncate the storage buffer in sp to offset.
+ *
+ * @param sp the storage buffer to truncate.
+ * @param offset the offset to truncate too.
+ *
+ * @return An Kerberos 5 error code.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_storage_truncate(krb5_storage *sp, off_t offset)
+{
+    return (*sp->trunc)(sp, offset);
+}
+
+/**
+ * Read to the storage buffer.
+ *
+ * @param sp the storage buffer to read from
+ * @param buf the buffer to store the data in
+ * @param len the length to read
+ *
+ * @return The length of data read (can be shorter then len), or negative =
on error.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_storage_read(krb5_storage *sp, void *buf, size_t len)
 {
     return sp->fetch(sp, buf, len);
 }
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
+/**
+ * Write to the storage buffer.
+ *
+ * @param sp the storage buffer to write to
+ * @param buf the buffer to write to the storage buffer
+ * @param len the length to write
+ *
+ * @return The length of data written (can be shorter then len), or negati=
ve on error.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_ssize_t KRB5_LIB_CALL
 krb5_storage_write(krb5_storage *sp, const void *buf, size_t len)
 {
     return sp->store(sp, buf, len);
 }
=20
-void KRB5_LIB_FUNCTION
+/**
+ * Set the return code that will be used when end of storage is reached.
+ *
+ * @param sp the storage
+ * @param code the error code to return on end of storage
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_storage_set_eof_code(krb5_storage *sp, int code)
 {
     sp->eof_code =3D code;
 }
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
-_krb5_put_int(void *buffer, unsigned long value, size_t size)
+/**
+ * Get the return code that will be used when end of storage is reached.
+ *
+ * @param sp the storage
+ *
+ * @return storage error code
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
+krb5_storage_get_eof_code(krb5_storage *sp)
 {
-    unsigned char *p =3D buffer;
-    int i;
-    for (i =3D size - 1; i >=3D 0; i--) {
-	p[i] =3D value & 0xff;
-	value >>=3D 8;
-    }
-    return size;
+    return sp->eof_code;
 }
=20
-krb5_ssize_t KRB5_LIB_FUNCTION
-_krb5_get_int(void *buffer, unsigned long *value, size_t size)
-{
-    unsigned char *p =3D buffer;
-    unsigned long v =3D 0;
-    int i;
-    for (i =3D 0; i < size; i++)
-	v =3D (v << 8) + p[i];
-    *value =3D v;
-    return size;
-}
+/**
+ * Free a krb5 storage.
+ *
+ * @param sp the storage to free.
+ *
+ * @return An Kerberos 5 error code.
+ *
+ * @ingroup krb5_storage
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_storage_free(krb5_storage *sp)
 {
     if(sp->free)
@@ -131,16 +277,31 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Copy the contnent of storage
+ *
+ * @param sp the storage to copy to a data
+ * @param data the copied data, free with krb5_data_free()
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_storage_to_data(krb5_storage *sp, krb5_data *data)
 {
-    off_t pos;
-    size_t size;
+    off_t pos, size;
     krb5_error_code ret;
=20
     pos =3D sp->seek(sp, 0, SEEK_CUR);
-    size =3D (size_t)sp->seek(sp, 0, SEEK_END);
-    ret =3D krb5_data_alloc (data, size);
+    if (pos < 0)
+	return HEIM_ERR_NOT_SEEKABLE;
+    size =3D sp->seek(sp, 0, SEEK_END);
+    ret =3D size_too_large(sp, size);
+    if (ret)
+	return ret;
+    ret =3D krb5_data_alloc(data, size);
     if (ret) {
 	sp->seek(sp, pos, SEEK_SET);
 	return ret;
@@ -165,12 +326,26 @@
 	return EINVAL;
     _krb5_put_int(v, value, len);
     ret =3D sp->store(sp, v, len);
-    if (ret !=3D len)
-	return (ret<0)?errno:sp->eof_code;
+    if (ret < 0)
+	return errno;
+    if ((size_t)ret !=3D len)
+	return sp->eof_code;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a int32 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_int32(krb5_storage *sp,
 		 int32_t value)
 {
@@ -181,7 +356,19 @@
     return krb5_store_int(sp, value, 4);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a uint32 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_uint32(krb5_storage *sp,
 		  uint32_t value)
 {
@@ -197,14 +384,28 @@
     unsigned char v[4];
     unsigned long w;
     ret =3D sp->fetch(sp, v, len);
-    if(ret !=3D len)
-	return (ret<0)?errno:sp->eof_code;
+    if (ret < 0)
+	return errno;
+    if ((size_t)ret !=3D len)
+	return sp->eof_code;
     _krb5_get_int(v, &w, len);
     *value =3D w;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a int32 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_int32(krb5_storage *sp,
 	       int32_t *value)
 {
@@ -218,7 +419,19 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a uint32 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_uint32(krb5_storage *sp,
 		uint32_t *value)
 {
@@ -232,7 +445,19 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a int16 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_int16(krb5_storage *sp,
 		 int16_t value)
 {
@@ -243,14 +468,38 @@
     return krb5_store_int(sp, value, 2);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a uint16 to storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_uint16(krb5_storage *sp,
 		  uint16_t value)
 {
     return krb5_store_int16(sp, (int16_t)value);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a int16 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_int16(krb5_storage *sp,
 	       int16_t *value)
 {
@@ -267,7 +516,19 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a int16 from storage, byte order is controlled by the settings
+ * on the storage, see krb5_storage_set_byteorder().
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_uint16(krb5_storage *sp,
 		uint16_t *value)
 {
@@ -281,7 +542,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a int8 to storage.
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_int8(krb5_storage *sp,
 		int8_t value)
 {
@@ -293,14 +565,36 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a uint8 to storage.
+ *
+ * @param sp the storage to write too
+ * @param value the value to store
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_uint8(krb5_storage *sp,
 		 uint8_t value)
 {
     return krb5_store_int8(sp, (int8_t)value);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a int8 from storage
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_int8(krb5_storage *sp,
 	      int8_t *value)
 {
@@ -312,7 +606,18 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a uint8 from storage
+ *
+ * @param sp the storage to write too
+ * @param value the value read from the buffer
+ *
+ * @return 0 for success, or a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_uint8(krb5_storage *sp,
 	       uint8_t *value)
 {
@@ -326,7 +631,19 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a data to the storage. The data is stored with an int32 as
+ * lenght plus the data (not padded).
+ *
+ * @param sp the storage buffer to write to
+ * @param data the buffer to store.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_data(krb5_storage *sp,
 		krb5_data data)
 {
@@ -335,15 +652,25 @@
     if(ret < 0)
 	return ret;
     ret =3D sp->store(sp, data.data, data.length);
-    if(ret !=3D data.length){
-	if(ret < 0)
-	    return errno;
+    if(ret < 0)
+	return errno;
+    if((size_t)ret !=3D data.length)
 	return sp->eof_code;
-    }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Parse a data from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param data the parsed data
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_data(krb5_storage *sp,
 	      krb5_data *data)
 {
@@ -353,6 +680,9 @@
     ret =3D krb5_ret_int32(sp, &size);
     if(ret)
 	return ret;
+    ret =3D size_too_large(sp, size);
+    if (ret)
+	return ret;
     ret =3D krb5_data_alloc (data, size);
     if (ret)
 	return ret;
@@ -364,7 +694,19 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a string to the buffer. The data is formated as an len:uint32
+ * plus the string itself (not padded).
+ *
+ * @param sp the storage buffer to write to
+ * @param s the string to store.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_string(krb5_storage *sp, const char *s)
 {
     krb5_data data;
@@ -373,7 +715,19 @@
     return krb5_store_data(sp, data);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Parse a string from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param string the parsed string
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_string(krb5_storage *sp,
 		char **string)
 {
@@ -391,23 +745,44 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a zero terminated string to the buffer. The data is stored
+ * one character at a time until a NUL is stored.
+ *
+ * @param sp the storage buffer to write to
+ * @param s the string to store.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_stringz(krb5_storage *sp, const char *s)
 {
     size_t len =3D strlen(s) + 1;
     ssize_t ret;
=20
     ret =3D sp->store(sp, s, len);
-    if(ret !=3D len) {
-	if(ret < 0)
-	    return ret;
-	else
-	    return sp->eof_code;
-    }
+    if(ret < 0)
+	return ret;
+    if((size_t)ret !=3D len)
+	return sp->eof_code;
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Parse zero terminated string from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param string the parsed string
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_stringz(krb5_storage *sp,
 		char **string)
 {
@@ -420,6 +795,9 @@
 	char *tmp;
=20
 	len++;
+	ret =3D size_too_large(sp, len);
+	if (ret)
+	    break;
 	tmp =3D realloc (s, len);
 	if (tmp =3D=3D NULL) {
 	    free (s);
@@ -440,19 +818,17 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_stringnl(krb5_storage *sp, const char *s)
 {
     size_t len =3D strlen(s);
     ssize_t ret;
=20
     ret =3D sp->store(sp, s, len);
-    if(ret !=3D len) {
-	if(ret < 0)
-	    return ret;
-	else
-	    return sp->eof_code;
-    }
+    if(ret < 0)
+	return ret;
+    if((size_t)ret !=3D len)
+	return sp->eof_code;
     ret =3D sp->store(sp, "\n", 1);
     if(ret !=3D 1) {
 	if(ret < 0)
@@ -465,7 +841,7 @@
=20
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_stringnl(krb5_storage *sp,
 		  char **string)
 {
@@ -488,6 +864,9 @@
 	}
=20
 	len++;
+	ret =3D size_too_large(sp, len);
+	if (ret)
+	    break;
 	tmp =3D realloc (s, len);
 	if (tmp =3D=3D NULL) {
 	    free (s);
@@ -510,12 +889,22 @@
     return 0;
 }
=20
+/**
+ * Write a principal block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the principal block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_principal(krb5_storage *sp,
 		     krb5_const_principal p)
 {
-    int i;
+    size_t i;
     int ret;
=20
     if(!krb5_storage_is_flags(sp, KRB5_STORAGE_PRINCIPAL_NO_NAME_TYPE)) {
@@ -526,7 +915,7 @@
 	ret =3D krb5_store_int32(sp, p->name.name_string.len + 1);
     else
 	ret =3D krb5_store_int32(sp, p->name.name_string.len);
-   =20
+
     if(ret) return ret;
     ret =3D krb5_store_string(sp, p->realm);
     if(ret) return ret;
@@ -537,7 +926,18 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Parse principal from the storage.
+ *
+ * @param sp the storage buffer to read from
+ * @param princ the parsed principal
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_principal(krb5_storage *sp,
 		   krb5_principal *princ)
 {
@@ -546,7 +946,7 @@
     krb5_principal p;
     int32_t type;
     int32_t ncomp;
-   =20
+
     p =3D calloc(1, sizeof(*p));
     if(p =3D=3D NULL)
 	return ENOMEM;
@@ -567,6 +967,11 @@
 	free(p);
 	return EINVAL;
     }
+    ret =3D size_too_large_num(sp, ncomp, sizeof(p->name.name_string.val[0=
]));
+    if (ret) {
+	free(p);
+	return ret;
+    }
     p->name.name_type =3D type;
     p->name.name_string.len =3D ncomp;
     ret =3D krb5_ret_string(sp, &p->realm);
@@ -574,7 +979,7 @@
 	free(p);
 	return ret;
     }
-    p->name.name_string.val =3D calloc(ncomp, sizeof(*p->name.name_string.=
val));
+    p->name.name_string.val =3D calloc(ncomp, sizeof(p->name.name_string.v=
al[0]));
     if(p->name.name_string.val =3D=3D NULL && ncomp !=3D 0){
 	free(p->realm);
 	free(p);
@@ -594,7 +999,18 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Store a keyblock to the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the keyblock to write
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_keyblock(krb5_storage *sp, krb5_keyblock p)
 {
     int ret;
@@ -612,7 +1028,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a keyblock from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the keyblock read from storage, free using krb5_free_keyblock()
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_keyblock(krb5_storage *sp, krb5_keyblock *p)
 {
     int ret;
@@ -631,7 +1058,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Write a times block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param times the times block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_times(krb5_storage *sp, krb5_times times)
 {
     int ret;
@@ -645,7 +1083,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a times block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param times the times block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_times(krb5_storage *sp, krb5_times *times)
 {
     int ret;
@@ -664,7 +1113,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Write a address block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the address block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_address(krb5_storage *sp, krb5_address p)
 {
     int ret;
@@ -674,7 +1134,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a address block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param adr the address block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_address(krb5_storage *sp, krb5_address *adr)
 {
     int16_t t;
@@ -686,10 +1157,21 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Write a addresses block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param p the addresses block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_addrs(krb5_storage *sp, krb5_addresses p)
 {
-    int i;
+    size_t i;
     int ret;
     ret =3D krb5_store_int32(sp, p.len);
     if(ret) return ret;
@@ -700,15 +1182,28 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a addresses block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param adr the addresses block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_addrs(krb5_storage *sp, krb5_addresses *adr)
 {
-    int i;
+    size_t i;
     int ret;
     int32_t tmp;
=20
     ret =3D krb5_ret_int32(sp, &tmp);
     if(ret) return ret;
+    ret =3D size_too_large_num(sp, tmp, sizeof(adr->val[0]));
+    if (ret) return ret;
     adr->len =3D tmp;
     ALLOC(adr->val, adr->len);
     if (adr->val =3D=3D NULL && adr->len !=3D 0)
@@ -720,11 +1215,22 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Write a auth data block to storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param auth the auth data block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_authdata(krb5_storage *sp, krb5_authdata auth)
 {
     krb5_error_code ret;
-    int i;
+    size_t i;
     ret =3D krb5_store_int32(sp, auth.len);
     if(ret) return ret;
     for(i =3D 0; i < auth.len; i++){
@@ -736,7 +1242,18 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a auth data from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param auth the auth data block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_authdata(krb5_storage *sp, krb5_authdata *auth)
 {
     krb5_error_code ret;
@@ -745,6 +1262,8 @@
     int i;
     ret =3D krb5_ret_int32(sp, &tmp);
     if(ret) return ret;
+    ret =3D size_too_large_num(sp, tmp, sizeof(auth->val[0]));
+    if (ret) return ret;
     ALLOC_SEQ(auth, tmp);
     if (auth->val =3D=3D NULL && tmp !=3D 0)
 	return ENOMEM;
@@ -770,12 +1289,18 @@
     return r;
 }
=20
-
-/*
+/**
+ * Write a credentials block to storage.
  *
+ * @param sp the storage buffer to write to
+ * @param creds the creds block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_creds(krb5_storage *sp, krb5_creds *creds)
 {
     int ret;
@@ -816,7 +1341,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a credentials block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param creds the credentials block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_creds(krb5_storage *sp, krb5_creds *creds)
 {
     krb5_error_code ret;
@@ -862,7 +1398,7 @@
     ret =3D krb5_ret_data (sp,  &creds->second_ticket);
 cleanup:
     if(ret) {
-#if 0=09
+#if 0
 	krb5_free_cred_contents(context, creds); /* XXX */
 #endif
     }
@@ -877,11 +1413,18 @@
 #define SC_AUTHDATA		    0x0020
 #define SC_ADDRESSES		    0x0040
=20
-/*
+/**
+ * Write a tagged credentials block to storage.
  *
+ * @param sp the storage buffer to write to
+ * @param creds the creds block to write.
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_store_creds_tag(krb5_storage *sp, krb5_creds *creds)
 {
     int ret;
@@ -903,6 +1446,8 @@
 	header |=3D SC_ADDRESSES;
=20
     ret =3D krb5_store_int32(sp, header);
+    if (ret)
+	return ret;
=20
     if (creds->client) {
 	ret =3D krb5_store_principal(sp, creds->client);
@@ -960,7 +1505,18 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Read a tagged credentials block from the storage.
+ *
+ * @param sp the storage buffer to write to
+ * @param creds the credentials block read from storage
+ *
+ * @return 0 on success, a Kerberos 5 error code on failure.
+ *
+ * @ingroup krb5_storage
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ret_creds_tag(krb5_storage *sp,
 		   krb5_creds *creds)
 {
@@ -1027,7 +1583,7 @@
=20
 cleanup:
     if(ret) {
-#if 0=09
+#if 0
 	krb5_free_cred_contents(context, creds); /* XXX */
 #endif
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/store_eme=
m.c
--- a/head/crypto/heimdal/lib/krb5/store_emem.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/store_emem.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include "store-int.h"
=20
-RCSID("$Id: store_emem.c 21745 2007-07-31 16:11:25Z lha $");
-
 typedef struct emem_storage{
     unsigned char *base;
     size_t size;
@@ -47,7 +45,7 @@
 emem_fetch(krb5_storage *sp, void *data, size_t size)
 {
     emem_storage *s =3D (emem_storage*)sp->data;
-    if(s->base + s->len - s->ptr < size)
+    if((size_t)(s->base + s->len - s->ptr) < size)
 	size =3D s->base + s->len - s->ptr;
     memmove(data, s->ptr, size);
     sp->seek(sp, size, SEEK_CUR);
@@ -58,7 +56,7 @@
 emem_store(krb5_storage *sp, const void *data, size_t size)
 {
     emem_storage *s =3D (emem_storage*)sp->data;
-    if(size > s->base + s->size - s->ptr){
+    if(size > (size_t)(s->base + s->size - s->ptr)){
 	void *base;
 	size_t sz, off;
 	off =3D s->ptr - s->base;
@@ -67,7 +65,7 @@
 	    sz *=3D 2;
 	base =3D realloc(s->base, sz);
 	if(base =3D=3D NULL)
-	    return 0;
+	    return -1;
 	s->size =3D sz;
 	s->base =3D base;
 	s->ptr =3D (unsigned char*)base + off;
@@ -83,12 +81,12 @@
     emem_storage *s =3D (emem_storage*)sp->data;
     switch(whence){
     case SEEK_SET:
-	if(offset > s->size)
+	if((size_t)offset > s->size)
 	    offset =3D s->size;
 	if(offset < 0)
 	    offset =3D 0;
 	s->ptr =3D s->base + offset;
-	if(offset > s->len)
+	if((size_t)offset > s->len)
 	    s->len =3D offset;
 	break;
     case SEEK_CUR:
@@ -104,6 +102,39 @@
     return s->ptr - s->base;
 }
=20
+static int
+emem_trunc(krb5_storage *sp, off_t offset)
+{
+    emem_storage *s =3D (emem_storage*)sp->data;
+    /*
+     * If offset is larget then current size, or current size is
+     * shrunk more then half of the current size, adjust buffer.
+     */
+    if (offset =3D=3D 0) {
+	free(s->base);
+	s->size =3D 0;
+	s->base =3D NULL;
+	s->ptr =3D NULL;
+    } else if ((size_t)offset > s->size || (s->size / 2) > (size_t)offset)=
 {
+	void *base;
+	size_t off;
+	off =3D s->ptr - s->base;
+	base =3D realloc(s->base, offset);
+	if(base =3D=3D NULL)
+	    return ENOMEM;
+	if ((size_t)offset > s->size)
+	    memset((char *)base + s->size, 0, offset - s->size);
+	s->size =3D offset;
+	s->base =3D base;
+	s->ptr =3D (unsigned char *)base + off;
+    }
+    s->len =3D offset;
+    if ((s->ptr - s->base) > offset)
+	s->ptr =3D s->base + offset;
+    return 0;
+}
+
+
 static void
 emem_free(krb5_storage *sp)
 {
@@ -112,13 +143,32 @@
     free(s->base);
 }
=20
-krb5_storage * KRB5_LIB_FUNCTION
+/**
+ * Create a elastic (allocating) memory storage backend. Memory is
+ * allocated on demand. Free returned krb5_storage with
+ * krb5_storage_free().
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_fd()
+ * @sa krb5_storage_from_data()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_emem(void)
 {
-    krb5_storage *sp =3D malloc(sizeof(krb5_storage));
+    krb5_storage *sp;
+    emem_storage *s;
+
+    sp =3D malloc(sizeof(krb5_storage));
     if (sp =3D=3D NULL)
 	return NULL;
-    emem_storage *s =3D malloc(sizeof(*s));
+
+    s =3D malloc(sizeof(*s));
     if (s =3D=3D NULL) {
 	free(sp);
 	return NULL;
@@ -138,6 +188,8 @@
     sp->fetch =3D emem_fetch;
     sp->store =3D emem_store;
     sp->seek =3D emem_seek;
+    sp->trunc =3D emem_trunc;
     sp->free =3D emem_free;
+    sp->max_alloc =3D UINT_MAX/8;
     return sp;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/store_fd.c
--- a/head/crypto/heimdal/lib/krb5/store_fd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/store_fd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997 - 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1997 - 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
@@ -34,8 +34,6 @@
 #include "krb5_locl.h"
 #include "store-int.h"
=20
-RCSID("$Id: store_fd.c 17779 2006-06-30 21:23:19Z lha $");
-
 typedef struct fd_storage {
     int fd;
 } fd_storage;
@@ -60,18 +58,53 @@
     return lseek(FD(sp), offset, whence);
 }
=20
+static int
+fd_trunc(krb5_storage * sp, off_t offset)
+{
+    if (ftruncate(FD(sp), offset) =3D=3D -1)
+	return errno;
+    return 0;
+}
+
 static void
 fd_free(krb5_storage * sp)
 {
     close(FD(sp));
 }
=20
-krb5_storage * KRB5_LIB_FUNCTION
-krb5_storage_from_fd(int fd)
+/**
+ *
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_emem()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_data()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
+krb5_storage_from_fd(krb5_socket_t fd_in)
 {
     krb5_storage *sp;
+    int fd;
=20
-    fd =3D dup(fd);
+#ifdef SOCKET_IS_NOT_AN_FD
+#ifdef _MSC_VER
+    if (_get_osfhandle(fd_in) !=3D -1) {
+	fd =3D dup(fd_in);
+    } else {
+	fd =3D _open_osfhandle(fd_in, 0);
+    }
+#else
+#error Dont know how to deal with fd that may or may not be a socket.
+#endif
+#else  /* SOCKET_IS_NOT_AN_FD */
+    fd =3D dup(fd_in);
+#endif
+
     if (fd < 0)
 	return NULL;
=20
@@ -93,6 +126,8 @@
     sp->fetch =3D fd_fetch;
     sp->store =3D fd_store;
     sp->seek =3D fd_seek;
+    sp->trunc =3D fd_trunc;
     sp->free =3D fd_free;
+    sp->max_alloc =3D UINT_MAX/8;
     return sp;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/store_mem=
.c
--- a/head/crypto/heimdal/lib/krb5/store_mem.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/store_mem.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2000, 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2000, 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include "store-int.h"
=20
-RCSID("$Id: store_mem.c 20307 2007-04-11 11:16:28Z lha $");
-
 typedef struct mem_storage{
     unsigned char *base;
     size_t size;
@@ -46,7 +44,7 @@
 mem_fetch(krb5_storage *sp, void *data, size_t size)
 {
     mem_storage *s =3D (mem_storage*)sp->data;
-    if(size > s->base + s->size - s->ptr)
+    if(size > (size_t)(s->base + s->size - s->ptr))
 	size =3D s->base + s->size - s->ptr;
     memmove(data, s->ptr, size);
     sp->seek(sp, size, SEEK_CUR);
@@ -57,7 +55,7 @@
 mem_store(krb5_storage *sp, const void *data, size_t size)
 {
     mem_storage *s =3D (mem_storage*)sp->data;
-    if(size > s->base + s->size - s->ptr)
+    if(size > (size_t)(s->base + s->size - s->ptr))
 	size =3D s->base + s->size - s->ptr;
     memmove(s->ptr, data, size);
     sp->seek(sp, size, SEEK_CUR);
@@ -76,7 +74,7 @@
     mem_storage *s =3D (mem_storage*)sp->data;
     switch(whence){
     case SEEK_SET:
-	if(offset > s->size)
+	if((size_t)offset > s->size)
 	    offset =3D s->size;
 	if(offset < 0)
 	    offset =3D 0;
@@ -93,7 +91,38 @@
     return s->ptr - s->base;
 }
=20
-krb5_storage * KRB5_LIB_FUNCTION
+static int
+mem_trunc(krb5_storage *sp, off_t offset)
+{
+    mem_storage *s =3D (mem_storage*)sp->data;
+    if((size_t)offset > s->size)
+	return ERANGE;
+    s->size =3D offset;
+    if ((s->ptr - s->base) > offset)
+	s->ptr =3D s->base + offset;
+    return 0;
+}
+
+static int
+mem_no_trunc(krb5_storage *sp, off_t offset)
+{
+    return EINVAL;
+}
+
+/**
+ * Create a fixed size memory storage block
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_fd()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_from_mem(void *buf, size_t len)
 {
     krb5_storage *sp =3D malloc(sizeof(krb5_storage));
@@ -114,17 +143,45 @@
     sp->fetch =3D mem_fetch;
     sp->store =3D mem_store;
     sp->seek =3D mem_seek;
+    sp->trunc =3D mem_trunc;
     sp->free =3D NULL;
+    sp->max_alloc =3D UINT_MAX/8;
     return sp;
 }
=20
-krb5_storage * KRB5_LIB_FUNCTION
+/**
+ * Create a fixed size memory storage block
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_mem()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_readonly_mem()
+ * @sa krb5_storage_from_fd()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_from_data(krb5_data *data)
 {
     return krb5_storage_from_mem(data->data, data->length);
 }
=20
-krb5_storage * KRB5_LIB_FUNCTION
+/**
+ * Create a fixed size memory storage block that is read only
+ *
+ * @return A krb5_storage on success, or NULL on out of memory error.
+ *
+ * @ingroup krb5_storage
+ *
+ * @sa krb5_storage_mem()
+ * @sa krb5_storage_from_mem()
+ * @sa krb5_storage_from_data()
+ * @sa krb5_storage_from_fd()
+ */
+
+KRB5_LIB_FUNCTION krb5_storage * KRB5_LIB_CALL
 krb5_storage_from_readonly_mem(const void *buf, size_t len)
 {
     krb5_storage *sp =3D malloc(sizeof(krb5_storage));
@@ -145,6 +202,8 @@
     sp->fetch =3D mem_fetch;
     sp->store =3D mem_no_store;
     sp->seek =3D mem_seek;
+    sp->trunc =3D mem_no_trunc;
     sp->free =3D NULL;
+    sp->max_alloc =3D UINT_MAX/8;
     return sp;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/string-to=
-key-test.c
--- a/head/crypto/heimdal/lib/krb5/string-to-key-test.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/string-to-key-test.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: string-to-key-test.c 16344 2005-12-02 15:15:43Z lha $");
-
 enum { MAXSIZE =3D 24 };
=20
 static struct testcase {
@@ -43,12 +41,26 @@
     krb5_enctype enctype;
     unsigned char res[MAXSIZE];
 } tests[] =3D {
+#ifdef HEIM_WEAK_CRYPTO
     {"@", "", ETYPE_DES_CBC_MD5,
      {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0xf1}},
     {"nisse at FOO.SE", "hej", ETYPE_DES_CBC_MD5,
      {0xfe, 0x67, 0xbf, 0x9e, 0x57, 0x6b, 0xfe, 0x52}},
     {"assar/liten at FOO.SE", "hemligt", ETYPE_DES_CBC_MD5,
      {0x5b, 0x9b, 0xcb, 0xf2, 0x97, 0x43, 0xc8, 0x40}},
+    {"raeburn at ATHENA.MIT.EDU", "password", ETYPE_DES_CBC_MD5,
+     {0xcb, 0xc2, 0x2f, 0xae, 0x23, 0x52, 0x98, 0xe3}},
+    {"danny at WHITEHOUSE.GOV", "potatoe", ETYPE_DES_CBC_MD5,
+     {0xdf, 0x3d, 0x32, 0xa7, 0x4f, 0xd9, 0x2a, 0x01}},
+    {"buckaroo at EXAMPLE.COM", "penny", ETYPE_DES_CBC_MD5,
+     {0x94, 0x43, 0xa2, 0xe5, 0x32, 0xfd, 0xc4, 0xf1}},
+    {"Juri\xc5\xa1i\xc4\x87 at ATHENA.MIT.EDU", "\xc3\x9f", ETYPE_DES_CBC_MD5,
+     {0x62, 0xc8, 0x1a, 0x52, 0x32, 0xb5, 0xe6, 0x9d}},
+    {"AAAAAAAA", "11119999", ETYPE_DES_CBC_MD5,
+     {0x98, 0x40, 0x54, 0xd0, 0xf1, 0xa7, 0x3e, 0x31}},
+    {"FFFFAAAA", "NNNN6666", ETYPE_DES_CBC_MD5,
+     {0xc4, 0xbf, 0x6b, 0x25, 0xad, 0xf7, 0xa4, 0xf8}},
+#endif
 #if 0
     {"@", "", ETYPE_DES3_CBC_SHA1,
      {0xce, 0xa2, 0x2f, 0x9b, 0x52, 0x2c, 0xb0, 0x15, 0x6e, 0x6b, 0x64,
@@ -66,18 +78,6 @@
     {"does/not at MATTER", "foo", ETYPE_ARCFOUR_HMAC_MD5,
      {0xac, 0x8e, 0x65, 0x7f, 0x83, 0xdf, 0x82, 0xbe,
       0xea, 0x5d, 0x43, 0xbd, 0xaf, 0x78, 0x00, 0xcc}},
-    {"raeburn at ATHENA.MIT.EDU", "password", ETYPE_DES_CBC_MD5,
-     {0xcb, 0xc2, 0x2f, 0xae, 0x23, 0x52, 0x98, 0xe3}},
-    {"danny at WHITEHOUSE.GOV", "potatoe", ETYPE_DES_CBC_MD5,
-     {0xdf, 0x3d, 0x32, 0xa7, 0x4f, 0xd9, 0x2a, 0x01}},
-    {"buckaroo at EXAMPLE.COM", "penny", ETYPE_DES_CBC_MD5,
-     {0x94, 0x43, 0xa2, 0xe5, 0x32, 0xfd, 0xc4, 0xf1}},
-    {"Juri\xc5\xa1i\xc4\x87 at ATHENA.MIT.EDU", "\xc3\x9f", ETYPE_DES_CBC_MD5,
-     {0x62, 0xc8, 0x1a, 0x52, 0x32, 0xb5, 0xe6, 0x9d}},
-    {"AAAAAAAA", "11119999", ETYPE_DES_CBC_MD5,
-     {0x98, 0x40, 0x54, 0xd0, 0xf1, 0xa7, 0x3e, 0x31}},
-    {"FFFFAAAA", "NNNN6666", ETYPE_DES_CBC_MD5,
-     {0xc4, 0xbf, 0x6b, 0x25, 0xad, 0xf7, 0xa4, 0xf8}},
     {"raeburn at ATHENA.MIT.EDU", "password", ETYPE_DES3_CBC_SHA1,
      {0x85, 0x0b, 0xb5, 0x13, 0x58, 0x54, 0x8c, 0xd0, 0x5e, 0x86, 0x76, 0x=
8c, 0x31, 0x3e, 0x3b, 0xfe, 0xf7, 0x51, 0x19, 0x37, 0xdc, 0xf7, 0x2c, 0x3e}=
},
     {"danny at WHITEHOUSE.GOV", "potatoe", ETYPE_DES3_CBC_SHA1,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_acl.c
--- a/head/crypto/heimdal/lib/krb5/test_acl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_acl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: test_acl.c 15036 2005-04-30 15:19:58Z lha $");
-
 #define RETVAL(c, r, e, s) \
 	do { if (r !=3D e) krb5_errx(c, 1, "%s", s); } while (0)
 #define STRINGMATCH(c, s, _s1, _s2) \
@@ -72,6 +70,13 @@
     RETVAL(context, ret, 0, "liternal fnmatch");
     ret =3D krb5_acl_match_string(context, "foo/bar", "f", "foo/*");
     RETVAL(context, ret, 0, "foo/*");
+    ret =3D krb5_acl_match_string(context, "foo/bar.example.org", "f",
+				"foo/*.example.org");
+    RETVAL(context, ret, 0, "foo/*.example.org");
+    ret =3D krb5_acl_match_string(context, "foo/bar.example.com", "f",
+				"foo/*.example.org");
+    RETVAL(context, ret, EACCES, "foo/*.example.com");
+
     ret =3D krb5_acl_match_string(context, "foo/bar/baz", "f", "foo/*/baz"=
);
     RETVAL(context, ret, 0, "foo/*/baz");
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_addr=
.c
--- a/head/crypto/heimdal/lib/krb5/test_addr.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/test_addr.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: test_addr.c 15036 2005-04-30 15:19:58Z lha $");
-
 static void
 print_addr(krb5_context context, const char *addr)
 {
@@ -51,20 +49,22 @@
=20
     if (addresses.len < 1)
 	krb5_err(context, 1, ret, "too few addresses");
-   =20
+
     for (i =3D 0; i < addresses.len; i++) {
 	krb5_print_address(&addresses.val[i], buf, sizeof(buf), &len);
 #if 0
-	printf("addr %d: %s (%d/%d)\n", i, buf, (int)len, (int)strlen(buf));=20
+	printf("addr %d: %s (%d/%d)\n", i, buf, (int)len, (int)strlen(buf));
 #endif
 	if (strlen(buf) > sizeof(buf))
-	    abort();
+	    krb5_err(context, 1, ret, "len %d larger then buf %d",
+		     (int)strlen(buf), (int)sizeof(buf));
 	krb5_print_address(&addresses.val[i], buf2, sizeof(buf2), &len);
 #if 0
-	printf("addr %d: %s (%d/%d)\n", i, buf2, (int)len, (int)strlen(buf2));=20
+	printf("addr %d: %s (%d/%d)\n", i, buf2, (int)len, (int)strlen(buf2));
 #endif
 	if (strlen(buf2) > sizeof(buf2))
-	    abort();
+	    krb5_err(context, 1, ret, "len %d larger then buf %d",
+		     (int)strlen(buf2), (int)sizeof(buf2));
=20
     }
     krb5_free_addresses(context, &addresses);
@@ -72,7 +72,7 @@
 }
=20
 static void
-truncated_addr(krb5_context context, const char *addr,=20
+truncated_addr(krb5_context context, const char *addr,
 	       size_t truncate_len, size_t outlen)
 {
     krb5_addresses addresses;
@@ -88,22 +88,25 @@
=20
     if (addresses.len !=3D 1)
 	krb5_err(context, 1, ret, "addresses should be one");
-   =20
+
     krb5_print_address(&addresses.val[0], buf, truncate_len, &len);
-   =20
+
 #if 0
-    printf("addr %s (%d/%d)\n", buf, (int)len, (int)strlen(buf));=20
+    printf("addr %s (%d/%d) should be %d\n", buf, (int)len, (int)strlen(bu=
f), (int)outlen);
 #endif
-   =20
+
     if (truncate_len > strlen(buf) + 1)
-	abort();
+	krb5_err(context, 1, ret, "%s truncate_len %d larger then strlen %d sourc=
e %s",
+		 buf, (int)truncate_len, (int)strlen(buf), addr);
+
     if (outlen !=3D len)
-	abort();
-   =20
+	krb5_err(context, 1, ret, "%s: outlen %d !=3D len %d",
+		 buf, (int)outlen, (int)strlen(buf));
+
     krb5_print_address(&addresses.val[0], buf, outlen + 1, &len);
=20
 #if 0
-    printf("addr %s (%d/%d)\n", buf, (int)len, (int)strlen(buf));=20
+    printf("addr %s (%d/%d)\n", buf, (int)len, (int)strlen(buf));
 #endif
=20
     if (len !=3D outlen)
@@ -120,12 +123,14 @@
 {
     int i, len =3D strlen(addr);
=20
+    truncated_addr(context, addr, len, len);
+
     for (i =3D 0; i < len; i++)
 	truncated_addr(context, addr, i, len);
 }
=20
 static void
-match_addr(krb5_context context, const char *range_addr,=20
+match_addr(krb5_context context, const char *range_addr,
 	   const char *one_addr, int match)
 {
     krb5_addresses range, one;
@@ -137,7 +142,7 @@
=20
     if (range.len !=3D 1)
 	krb5_err(context, 1, ret, "wrong num of addresses");
-   =20
+
     ret =3D krb5_parse_address(context, one_addr, &one);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_address");
@@ -157,12 +162,41 @@
     krb5_free_addresses(context, &one);
 }
=20
+#ifdef _MSC_VER
+
+/* For the truncation tests, calling strcpy_s() or strcat_s() with a
+   size of 0 results in the invalid parameter handler being invoked.
+   For the debug version, the runtime also throws an assert. */
+
+static void
+inv_param_handler(const wchar_t* expression,
+		  const wchar_t* function,
+		  const wchar_t* file,
+		  unsigned int line,
+		  uintptr_t pReserved)
+{
+    printf("Invalid parameter handler invoked for: %S in %S(%d) [%S]\n",
+	   function, file, line, expression);
+}
+
+static _invalid_parameter_handler _inv_old =3D NULL;
+
+#define SET_INVALID_PARAM_HANDLER _inv_old =3D _set_invalid_parameter_hand=
ler(inv_param_handler)
+
+#else
+
+#define SET_INVALID_PARAM_HANDLER ((void) 0)
+
+#endif
+
 int
 main(int argc, char **argv)
 {
     krb5_context context;
     krb5_error_code ret;
=20
+    SET_INVALID_PARAM_HANDLER;
+
     setprogname(argv[0]);
=20
     ret =3D krb5_init_context(&context);
@@ -174,7 +208,7 @@
     print_addr(context, "RANGE:IPv4:127.0.0.0-IPv4:127.0.0.255");
     print_addr(context, "RANGE:130.237.237.4/29");
 #ifdef HAVE_IPV6
-    print_addr(context, "RANGE:fe80::209:6bff:fea0:e522/64");
+    print_addr(context, "RANGE:2001:db8:1:2:3:4:1428:7ab/64");
     print_addr(context, "RANGE:IPv6:fe80::209:6bff:fea0:e522/64");
     print_addr(context, "RANGE:IPv6:fe80::-IPv6:fe80::ffff:ffff:ffff:ffff"=
);
     print_addr(context, "RANGE:fe80::-fe80::ffff:ffff:ffff:ffff");
@@ -183,7 +217,10 @@
     check_truncation(context, "IPv4:127.0.0.0");
     check_truncation(context, "RANGE:IPv4:127.0.0.0-IPv4:127.0.0.255");
 #ifdef HAVE_IPV6
+    check_truncation(context, "IPv6:::");
     check_truncation(context, "IPv6:::1");
+    check_truncation(context, "IPv6:2001:db8:1:2:3:4:1428:7ab");
+    check_truncation(context, "IPv6:fe80::209:0:0:0");
     check_truncation(context, "IPv6:fe80::ffff:ffff:ffff:ffff");
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_alna=
me.c
--- a/head/crypto/heimdal/lib/krb5/test_alname.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/test_alname.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,11 +34,9 @@
 #include <getarg.h>
 #include <err.h>
=20
-RCSID("$Id: test_alname.c 15474 2005-06-17 04:48:02Z lha $");
-
 static void
 test_alname(krb5_context context, krb5_const_realm realm,
-	    const char *user, const char *inst,=20
+	    const char *user, const char *inst,
 	    const char *localuser, int ok)
 {
     krb5_principal p;
@@ -60,20 +58,20 @@
     if (ret) {
 	if (!ok)
 	    return;
-	krb5_err(context, 1, ret, "krb5_aname_to_localname: %s -> %s",=20
+	krb5_err(context, 1, ret, "krb5_aname_to_localname: %s -> %s",
 		 princ, localuser);
     }
=20
     if (strcmp(localname, localuser) !=3D 0) {
 	if (ok)
-	    errx(1, "compared failed %s !=3D %s (should have succeded)",=20
+	    errx(1, "compared failed %s !=3D %s (should have succeded)",
 		 localname, localuser);
     } else {
 	if (!ok)
-	    errx(1, "compared failed %s =3D=3D %s (should have failed)",=20
+	    errx(1, "compared failed %s =3D=3D %s (should have failed)",
 		 localname, localuser);
     }
-   =20
+
 }
=20
 static int version_flag =3D 0;
@@ -109,7 +107,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -140,12 +138,12 @@
     test_alname(context, "FOO.BAR.BAZ.KAKA", user, NULL, user, 0);
     test_alname(context, "FOO.BAR.BAZ.KAKA", user, "root", "root", 0);
=20
-    test_alname(context, realm, user, NULL,=20
+    test_alname(context, realm, user, NULL,
 		"not-same-as-user", 0);
     test_alname(context, realm, user, "root",
 		"not-same-as-user", 0);
=20
-    test_alname(context, "FOO.BAR.BAZ.KAKA", user, NULL,=20
+    test_alname(context, "FOO.BAR.BAZ.KAKA", user, NULL,
 		"not-same-as-user", 0);
     test_alname(context, "FOO.BAR.BAZ.KAKA", user, "root",
 		"not-same-as-user", 0);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_cc.c
--- a/head/crypto/heimdal/lib/krb5/test_cc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_cc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,17 +34,21 @@
 #include <getarg.h>
 #include <err.h>
=20
-RCSID("$Id: test_cc.c 22115 2007-12-03 21:21:42Z lha $");
-
 static int debug_flag	=3D 0;
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
+#ifdef KRB5_USE_PATH_TOKENS
+#define TEST_CC_NAME "%{TEMP}/krb5-cc-test-foo"
+#else
+#define TEST_CC_NAME "/tmp/krb5-cc-test-foo"
+#endif
+
 static void
 test_default_name(krb5_context context)
 {
     krb5_error_code ret;
-    const char *p, *test_cc_name =3D "/tmp/krb5-cc-test-foo";
+    const char *p, *test_cc_name =3D TEST_CC_NAME;
     char *p1, *p2, *p3;
=20
     p =3D krb5_cc_default_name(context);
@@ -63,18 +67,23 @@
=20
     if (strcmp(p1, p2) !=3D 0)
 	krb5_errx (context, 1, "krb5_cc_default_name no longer same");
-=09
+
     ret =3D krb5_cc_set_default_name(context, test_cc_name);
     if (p =3D=3D NULL)
 	krb5_errx (context, 1, "krb5_cc_set_default_name 1 failed");
-   =20
+
     p =3D krb5_cc_default_name(context);
     if (p =3D=3D NULL)
 	krb5_errx (context, 1, "krb5_cc_default_name 2 failed");
     p3 =3D estrdup(p);
-   =20
+
+#ifndef KRB5_USE_PATH_TOKENS
+    /* If we are using path tokens, we don't expect the p3 and
+       test_cc_name to match since p3 is going to have expanded
+       tokens. */
     if (strcmp(p3, test_cc_name) !=3D 0)
 	krb5_errx (context, 1, "krb5_cc_set_default_name 1 failed");
+#endif
=20
     free(p1);
     free(p2);
@@ -99,9 +108,9 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
-    ret =3D krb5_cc_gen_new(context, &krb5_mcc_ops, &id);
+    ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory, NULL, &id);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_cc_gen_new");
+	krb5_err(context, 1, ret, "krb5_cc_new_unique");
=20
     ret =3D krb5_cc_initialize(context, id, p);
     if (ret)
@@ -115,10 +124,11 @@
     if (tc =3D=3D NULL)
 	krb5_errx(context, 1, "krb5_cc_get_name");
=20
-    asprintf(&c, "%s:%s", tc, nc);
-   =20
+    if (asprintf(&c, "%s:%s", tc, nc) < 0 || c =3D=3D NULL)
+	errx(1, "malloc");
+
     krb5_cc_close(context, id);
-   =20
+
     ret =3D krb5_cc_resolve(context, c, &id2);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_cc_resolve");
@@ -151,24 +161,26 @@
  */
=20
 static void
-test_init_vs_destroy(krb5_context context, const krb5_cc_ops *ops)
+test_init_vs_destroy(krb5_context context, const char *type)
 {
     krb5_error_code ret;
     krb5_ccache id, id2;
     krb5_principal p, p2;
-    char *n;
+    char *n =3D NULL;
=20
     ret =3D krb5_parse_name(context, "lha at SU.SE", &p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
-    ret =3D krb5_cc_gen_new(context, ops, &id);
+    ret =3D krb5_cc_new_unique(context, type, NULL, &id);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_cc_gen_new");
+	krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", type);
=20
-    asprintf(&n, "%s:%s",
-	     krb5_cc_get_type(context, id),
-	     krb5_cc_get_name(context, id));
+    if (asprintf(&n, "%s:%s",
+		 krb5_cc_get_type(context, id),
+		 krb5_cc_get_name(context, id)) < 0 || n =3D=3D NULL)
+	errx(1, "malloc");
+
=20
     ret =3D krb5_cc_resolve(context, n, &id2);
     free(n);
@@ -191,7 +203,7 @@
 }
=20
 static void
-test_fcache_remove(krb5_context context)
+test_cache_remove(krb5_context context, const char *type)
 {
     krb5_error_code ret;
     krb5_ccache id;
@@ -202,9 +214,9 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
-    ret =3D krb5_cc_gen_new(context, &krb5_fcc_ops, &id);
+    ret =3D krb5_cc_new_unique(context, type, NULL, &id);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_cc_gen_new");
+	krb5_err(context, 1, ret, "krb5_cc_gen_new: %s", type);
=20
     ret =3D krb5_cc_initialize(context, id, p);
     if (ret)
@@ -280,12 +292,33 @@
     char *res;
 } cc_names[] =3D {
     { "foo", 0, "foo" },
+    { "foo%}", 0, "foo%}" },
     { "%{uid}", 0 },
     { "foo%{null}", 0, "foo" },
     { "foo%{null}bar", 0, "foobar" },
     { "%{", 1 },
     { "%{foo %{", 1 },
     { "%{{", 1 },
+    { "%{{}", 1 },
+    { "%{nulll}", 1 },
+    { "%{does not exist}", 1 },
+    { "%{}", 1 },
+#ifdef KRB5_USE_PATH_TOKENS
+    { "%{APPDATA}", 0 },
+    { "%{COMMON_APPDATA}", 0},
+    { "%{LOCAL_APPDATA}", 0},
+    { "%{SYSTEM}", 0},
+    { "%{WINDOWS}", 0},
+    { "%{TEMP}", 0},
+    { "%{USERID}", 0},
+    { "%{uid}", 0},
+    { "%{USERCONFIG}", 0},
+    { "%{COMMONCONFIG}", 0},
+    { "%{LIBDIR}", 0},
+    { "%{BINDIR}", 0},
+    { "%{LIBEXEC}", 0},
+    { "%{SBINDIR}", 0},
+#endif
 };
=20
 static void
@@ -299,14 +332,14 @@
 	ret =3D _krb5_expand_default_cc_name(context, cc_names[i].str, &str);
 	if (ret) {
 	    if (cc_names[i].fail =3D=3D 0)
-		krb5_errx(context, 1, "test %d \"%s\" failed",=20
+		krb5_errx(context, 1, "test %d \"%s\" failed",
 			  i, cc_names[i].str);
 	} else {
 	    if (cc_names[i].fail)
-		krb5_errx(context, 1, "test %d \"%s\" was successful",=20
+		krb5_errx(context, 1, "test %d \"%s\" was successful",
 			  i, cc_names[i].str);
 	    if (cc_names[i].res && strcmp(cc_names[i].res, str) !=3D 0)
-		krb5_errx(context, 1, "test %d %s !=3D %s",=20
+		krb5_errx(context, 1, "test %d %s !=3D %s",
 			  i, cc_names[i].res, str);
 	    if (debug_flag)
 		printf("%s =3D> %s\n", cc_names[i].str, str);
@@ -316,8 +349,7 @@
 }
=20
 static void
-test_cache_find(krb5_context context, const char *type, const char *princi=
pal,
-		int find)
+test_cache_find(krb5_context context, const char *principal, int find)
 {
     krb5_principal client;
     krb5_error_code ret;
@@ -326,8 +358,8 @@
     ret =3D krb5_parse_name(context, principal, &client);
     if (ret)
 	krb5_err(context, 1, ret, "parse_name for %s failed", principal);
-   =20
-    ret =3D krb5_cc_cache_match(context, client, type, &id);
+
+    ret =3D krb5_cc_cache_match(context, client, &id);
     if (ret && find)
 	krb5_err(context, 1, ret, "cc_cache_match for %s failed", principal);
     if (ret =3D=3D 0 && !find)
@@ -345,7 +377,7 @@
     krb5_cc_cache_cursor cursor;
     krb5_error_code ret;
     krb5_ccache id;
-   =20
+
     ret =3D krb5_cc_cache_get_first (context, type, &cursor);
     if (ret =3D=3D KRB5_CC_NOSUPP)
 	return;
@@ -379,36 +411,62 @@
 }
=20
 static void
-test_copy(krb5_context context, const char *fromtype, const char *totype)
+test_cache_iter_all(krb5_context context)
 {
-    const krb5_cc_ops *from, *to;
+    krb5_cccol_cursor cursor;
+    krb5_error_code ret;
+    krb5_ccache id;
+
+    ret =3D krb5_cccol_cursor_new (context, &cursor);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cccol_cursor_new");
+
+
+    while ((ret =3D krb5_cccol_cursor_next (context, cursor, &id)) =3D=3D =
0 && id !=3D NULL) {
+	krb5_principal principal;
+	char *name;
+
+	if (debug_flag)
+	    printf("name: %s\n", krb5_cc_get_name(context, id));
+	ret =3D krb5_cc_get_principal(context, id, &principal);
+	if (ret =3D=3D 0) {
+	    ret =3D krb5_unparse_name(context, principal, &name);
+	    if (ret =3D=3D 0) {
+		if (debug_flag)
+		    printf("\tprincipal: %s\n", name);
+		free(name);
+	    }
+	    krb5_free_principal(context, principal);
+	}
+	krb5_cc_close(context, id);
+    }
+
+    krb5_cccol_cursor_free(context, &cursor);
+}
+
+
+static void
+test_copy(krb5_context context, const char *from, const char *to)
+{
     krb5_ccache fromid, toid;
     krb5_error_code ret;
     krb5_principal p, p2;
=20
-    from =3D krb5_cc_get_prefix_ops(context, fromtype);
-    if (from =3D=3D NULL)
-	krb5_errx(context, 1, "%s isn't a type", fromtype);
-
-    to =3D krb5_cc_get_prefix_ops(context, totype);
-    if (to =3D=3D NULL)
-	krb5_errx(context, 1, "%s isn't a type", totype);
-
     ret =3D krb5_parse_name(context, "lha at SU.SE", &p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
-    ret =3D krb5_cc_gen_new(context, from, &fromid);
+    ret =3D krb5_cc_new_unique(context, from, NULL, &fromid);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_cc_gen_new");
+	krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", from);
=20
     ret =3D krb5_cc_initialize(context, fromid, p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_cc_initialize");
=20
-    ret =3D krb5_cc_gen_new(context, to, &toid);
+    ret =3D krb5_cc_new_unique(context, to, NULL, &toid);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_cc_gen_new");
+	krb5_err(context, 1, ret, "krb5_cc_gen_new: %s", to);
=20
     ret =3D krb5_cc_copy_cache(context, fromid, toid);
     if (ret)
@@ -429,6 +487,55 @@
 }
=20
 static void
+test_move(krb5_context context, const char *type)
+{
+    const krb5_cc_ops *ops;
+    krb5_ccache fromid, toid;
+    krb5_error_code ret;
+    krb5_principal p, p2;
+
+    ops =3D krb5_cc_get_prefix_ops(context, type);
+    if (ops =3D=3D NULL)
+	return;
+
+    ret =3D krb5_cc_new_unique(context, type, NULL, &fromid);
+    if (ret =3D=3D KRB5_CC_NOSUPP)
+	return;
+    else if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_new_unique: %s", type);
+
+    ret =3D krb5_parse_name(context, "lha at SU.SE", &p);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_parse_name");
+
+    ret =3D krb5_cc_initialize(context, fromid, p);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+    ret =3D krb5_cc_new_unique(context, type, NULL, &toid);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+    ret =3D krb5_cc_initialize(context, toid, p);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+    ret =3D krb5_cc_get_principal(context, toid, &p2);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_get_principal");
+
+    if (krb5_principal_compare(context, p, p2) =3D=3D FALSE)
+	krb5_errx(context, 1, "p !=3D p2");
+
+    krb5_free_principal(context, p);
+    krb5_free_principal(context, p2);
+
+    krb5_cc_destroy(context, toid);
+    krb5_cc_destroy(context, fromid);
+}
+
+
+static void
 test_prefix_ops(krb5_context context, const char *name, const krb5_cc_ops =
*ops)
 {
     const krb5_cc_ops *o;
@@ -441,6 +548,68 @@
 		  "the expected %s !=3D %s", name, o->prefix, ops->prefix);
 }
=20
+static void
+test_cc_config(krb5_context context)
+{
+    krb5_error_code ret;
+    krb5_principal p;
+    krb5_ccache id;
+    unsigned int i;
+
+    ret =3D krb5_cc_new_unique(context, "MEMORY", "bar", &id);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_new_unique");
+
+    ret =3D krb5_parse_name(context, "lha at SU.SE", &p);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_parse_name");
+
+    ret =3D krb5_cc_initialize(context, id, p);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_cc_initialize");
+
+    for (i =3D 0; i < 1000; i++) {
+	krb5_data data, data2;
+	const char *name =3D "foo";
+	krb5_principal p1 =3D NULL;
+
+	if (i & 1)
+	    p1 =3D p;
+
+	data.data =3D rk_UNCONST(name);
+	data.length =3D strlen(name);
+
+	ret =3D krb5_cc_set_config(context, id, p1, "FriendlyName", &data);
+	if (ret)
+	    krb5_errx(context, 1, "krb5_cc_set_config: add");
+
+	ret =3D krb5_cc_get_config(context, id, p1, "FriendlyName", &data2);
+	if (ret)
+	    krb5_errx(context, 1, "krb5_cc_get_config: first");
+	krb5_data_free(&data2);
+
+	ret =3D krb5_cc_set_config(context, id, p1, "FriendlyName", &data);
+	if (ret)
+	    krb5_errx(context, 1, "krb5_cc_set_config: add -second");
+
+	ret =3D krb5_cc_get_config(context, id, p1, "FriendlyName", &data2);
+	if (ret)
+	    krb5_errx(context, 1, "krb5_cc_get_config: second");
+	krb5_data_free(&data2);
+
+	ret =3D krb5_cc_set_config(context, id, p1, "FriendlyName", NULL);
+	if (ret)
+	    krb5_errx(context, 1, "krb5_cc_set_config: delete");
+
+	ret =3D krb5_cc_get_config(context, id, p1, "FriendlyName", &data2);
+	if (ret =3D=3D 0)
+	    krb5_errx(context, 1, "krb5_cc_get_config: non-existant");
+    }
+
+    krb5_cc_destroy(context, id);
+    krb5_free_principal(context, p);
+}
+
=20
 static struct getargs args[] =3D {
     {"debug",	'd',	arg_flag,	&debug_flag,
@@ -470,7 +639,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -486,47 +655,82 @@
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
=20
-    test_fcache_remove(context);
+    test_cache_remove(context, krb5_cc_type_file);
+    test_cache_remove(context, krb5_cc_type_memory);
+#ifdef USE_SQLITE
+    test_cache_remove(context, krb5_cc_type_scc);
+#endif
+
     test_default_name(context);
     test_mcache(context);
-    test_init_vs_destroy(context, &krb5_mcc_ops);
-    test_init_vs_destroy(context, &krb5_fcc_ops);
+    test_init_vs_destroy(context, krb5_cc_type_memory);
+    test_init_vs_destroy(context, krb5_cc_type_file);
+#if 0
+    test_init_vs_destroy(context, krb5_cc_type_api);
+#endif
+    test_init_vs_destroy(context, krb5_cc_type_scc);
     test_mcc_default();
     test_def_cc_name(context);
-    test_cache_iter(context, "MEMORY", 0);
+
+    test_cache_iter_all(context);
+
+    test_cache_iter(context, krb5_cc_type_memory, 0);
     {
 	krb5_principal p;
-	krb5_cc_new_unique(context, "MEMORY", "bar", &id1);
-	krb5_cc_new_unique(context, "MEMORY", "baz", &id2);
+	krb5_cc_new_unique(context, krb5_cc_type_memory, "bar", &id1);
+	krb5_cc_new_unique(context, krb5_cc_type_memory, "baz", &id2);
 	krb5_parse_name(context, "lha at SU.SE", &p);
 	krb5_cc_initialize(context, id1, p);
 	krb5_free_principal(context, p);
     }
=20
-    test_cache_find(context, "MEMORY", "lha at SU.SE", 1);
-    test_cache_find(context, "MEMORY", "hulabundulahotentot at SU.SE", 0);
+    test_cache_find(context, "lha at SU.SE", 1);
+    test_cache_find(context, "hulabundulahotentot at SU.SE", 0);
=20
-    test_cache_iter(context, "MEMORY", 0);
-    test_cache_iter(context, "MEMORY", 1);
-    test_cache_iter(context, "MEMORY", 0);
-    test_cache_iter(context, "FILE", 0);
-    test_cache_iter(context, "API", 0);
+    test_cache_iter(context, krb5_cc_type_memory, 0);
+    test_cache_iter(context, krb5_cc_type_memory, 1);
+    test_cache_iter(context, krb5_cc_type_memory, 0);
+    test_cache_iter(context, krb5_cc_type_file, 0);
+    test_cache_iter(context, krb5_cc_type_api, 0);
+    test_cache_iter(context, krb5_cc_type_scc, 0);
+    test_cache_iter(context, krb5_cc_type_scc, 1);
=20
-    test_copy(context, "FILE", "FILE");
-    test_copy(context, "MEMORY", "MEMORY");
-    test_copy(context, "FILE", "MEMORY");
-    test_copy(context, "MEMORY", "FILE");
+    test_copy(context, krb5_cc_type_file, krb5_cc_type_file);
+    test_copy(context, krb5_cc_type_memory, krb5_cc_type_memory);
+    test_copy(context, krb5_cc_type_file, krb5_cc_type_memory);
+    test_copy(context, krb5_cc_type_memory, krb5_cc_type_file);
+    test_copy(context, krb5_cc_type_scc, krb5_cc_type_file);
+    test_copy(context, krb5_cc_type_file, krb5_cc_type_scc);
+    test_copy(context, krb5_cc_type_scc, krb5_cc_type_memory);
+    test_copy(context, krb5_cc_type_memory, krb5_cc_type_scc);
+
+    test_move(context, krb5_cc_type_file);
+    test_move(context, krb5_cc_type_memory);
+#ifdef HAVE_KCM
+    test_move(context, krb5_cc_type_kcm);
+#endif
+    test_move(context, krb5_cc_type_scc);
=20
     test_prefix_ops(context, "FILE:/tmp/foo", &krb5_fcc_ops);
     test_prefix_ops(context, "FILE", &krb5_fcc_ops);
     test_prefix_ops(context, "MEMORY", &krb5_mcc_ops);
     test_prefix_ops(context, "MEMORY:foo", &krb5_mcc_ops);
     test_prefix_ops(context, "/tmp/kaka", &krb5_fcc_ops);
+#ifdef HAVE_SCC
+    test_prefix_ops(context, "SCC:", &krb5_scc_ops);
+    test_prefix_ops(context, "SCC:foo", &krb5_scc_ops);
+#endif
=20
     krb5_cc_destroy(context, id1);
     krb5_cc_destroy(context, id2);
=20
+    test_cc_config(context);
+
     krb5_free_context(context);
=20
+#if 0
+    sleep(60);
+#endif
+
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_conf=
ig.c
--- a/head/crypto/heimdal/lib/krb5/test_config.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/test_config.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: test_config.c 15036 2005-04-30 15:19:58Z lha $");
-
 static int
 check_config_file(krb5_context context, char *filelist, char **res, int de=
f)
 {
@@ -49,39 +47,39 @@
 	ret =3D krb5_prepend_config_files_default(filelist, &pp);
     else
 	ret =3D krb5_prepend_config_files(filelist, NULL, &pp);
-   =20
+
     if (ret)
 	krb5_err(context, 1, ret, "prepend_config_files");
-   =20
+
     for (i =3D 0; res[i] && pp[i]; i++)
 	if (strcmp(pp[i], res[i]) !=3D 0)
 	    krb5_errx(context, 1, "'%s' !=3D '%s'", pp[i], res[i]);
-   =20
+
     if (res[i] !=3D NULL)
 	krb5_errx(context, 1, "pp ended before res list");
-   =20
+
     if (def) {
 	char **deflist;
 	int j;
-=09
+
 	ret =3D krb5_get_default_config_files(&deflist);
 	if (ret)
 	    krb5_err(context, 1, ret, "get_default_config_files");
-=09
+
 	for (j =3D 0 ; pp[i] && deflist[j]; i++, j++)
 	    if (strcmp(pp[i], deflist[j]) !=3D 0)
 		krb5_errx(context, 1, "'%s' !=3D '%s'", pp[i], deflist[j]);
-=09
+
 	if (deflist[j] !=3D NULL)
 	    krb5_errx(context, 1, "pp ended before def list");
 	krb5_free_config_files(deflist);
     }
-   =20
+
     if (pp[i] !=3D NULL)
 	krb5_errx(context, 1, "pp ended after res (and def) list");
-   =20
+
     krb5_free_config_files(pp);
-   =20
+
     return 0;
 }
=20
@@ -94,12 +92,12 @@
     char **res;
 } test[] =3D {
     { "/tmp/foo", NULL },
-    { "/tmp/foo:/tmp/foo/bar", NULL },
+    { "/tmp/foo" PATH_SEP "/tmp/foo/bar", NULL },
     { "", NULL }
 };
=20
-int
-main(int argc, char **argv)
+static void
+check_config_files(void)
 {
     krb5_context context;
     krb5_error_code ret;
@@ -119,6 +117,130 @@
     }
=20
     krb5_free_context(context);
+}
=20
+const char *config_string_result0[] =3D {
+    "A", "B", "C", "D", NULL
+};
+
+const char *config_string_result1[] =3D {
+    "A", "B", "C D", NULL
+};
+
+const char *config_string_result2[] =3D {
+    "A", "B", "", NULL
+};
+
+const char *config_string_result3[] =3D {
+    "A B;C: D", NULL
+};
+
+const char *config_string_result4[] =3D {
+    "\"\"", "", "\"\"", NULL
+};
+
+const char *config_string_result5[] =3D {
+    "A\"BQd", NULL
+};
+
+const char *config_string_result6[] =3D {
+    "efgh\"", "ABC", NULL
+};
+
+const char *config_string_result7[] =3D {
+    "SnapeKills\\", "Dumbledore", NULL
+};
+
+const char *config_string_result8[] =3D {
+    "\"TownOf Sandwich: Massachusetts\"Oldest", "Town", "In", "Cape Cod", =
NULL
+};
+
+const char *config_string_result9[] =3D {
+    "\"Begins and\"ends", "In", "One", "String", NULL
+};
+
+const char *config_string_result10[] =3D {
+    "Redistribution and use in source and binary forms, with or without mo=
dification, are permitted provided that the following conditions are met:",
+    "1. Redistributions of source code must retain the above copyright not=
ice, this list of conditions and the following disclaimer.",
+    "2. Redistributions in binary form must reproduce the above copyright =
notice, this list of conditions and the following disclaimer in the documen=
tation and/or other materials provided with the distribution.",
+    "3. Neither the name of the Institute nor the names of its contributor=
s may be used to endorse or promote products derived from this software wit=
hout specific prior written permission.",
+    "THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS''=
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE =
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE =
ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE =
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL =
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR =
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER =
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILIT=
Y, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF TH=
E USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.",
+    "Why do we test with such long strings? Because some people have confi=
g files",
+    "That", "look", "Like this.", NULL
+};
+
+const struct {
+    const char * name;
+    const char ** expected;
+} config_strings_tests[] =3D {
+    { "foo", config_string_result0 },
+    { "bar", config_string_result1 },
+    { "baz", config_string_result2 },
+    { "quux", config_string_result3 },
+    { "questionable", config_string_result4 },
+    { "mismatch1", config_string_result5 },
+    { "mismatch2", config_string_result6 },
+    { "internal1", config_string_result7 },
+    { "internal2", config_string_result8 },
+    { "internal3", config_string_result9 },
+    { "longer_strings", config_string_result10 }
+};
+
+static void
+check_escaped_strings(void)
+{
+    krb5_context context;
+    krb5_config_section *c =3D NULL;
+    krb5_error_code ret;
+    int i;
+
+    ret =3D krb5_init_context(&context);
+    if (ret)
+        errx(1, "krb5_init_context %d", ret);
+
+    ret =3D krb5_config_parse_file(context, "test_config_strings.out", &c);
+    if (ret)
+        krb5_errx(context, 1, "krb5_config_parse_file()");
+
+    for (i=3D0; i < sizeof(config_strings_tests)/sizeof(config_strings_tes=
ts[0]); i++) {
+        char **ps;
+        const char **s;
+        const char **e;
+
+        ps =3D krb5_config_get_strings(context, c, "escapes", config_strin=
gs_tests[i].name,
+                                     NULL);
+        if (ps =3D=3D NULL)
+            errx(1, "Failed to read string value %s", config_strings_tests=
[i].name);
+
+        e =3D config_strings_tests[i].expected;
+
+        for (s =3D (const char **)ps; *s && *e; s++, e++) {
+            if (strcmp(*s, *e))
+                errx(1,
+                     "Unexpected configuration string at value [%s].\n"
+                     "Actual=3D[%s]\n"
+                     "Expected=3D[%s]\n",
+                     config_strings_tests[i].name, *s, *e);
+        }
+
+        if (*s || *e)
+            errx(1, "Configuation string list for value [%s] has incorrect=
 length.",
+		 config_strings_tests[i].name);
+
+        krb5_config_free_strings(ps);
+    }
+
+    ret =3D krb5_config_file_free(context, c);
+    if (ret)
+        krb5_errx(context, 1, "krb5_config_file_free()");
+
+    krb5_free_context(context);
+}
+
+int
+main(int argc, char **argv)
+{
+    check_config_files();
+    check_escaped_strings();
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_cryp=
to.c
--- a/head/crypto/heimdal/lib/krb5/test_crypto.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/test_crypto.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003-2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003-2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_crypto.c 16290 2005-11-24 09:57:50Z lha $");
-
 static void
 time_encryption(krb5_context context, size_t size,
 		krb5_enctype etype, int iterations)
@@ -79,7 +77,7 @@
=20
     timevalsub(&tv2, &tv1);
=20
-    printf("%s size: %7lu iterations: %d time: %3ld.%06ld\n",=20
+    printf("%s size: %7lu iterations: %d time: %3ld.%06ld\n",
 	   etype_name, (unsigned long)size, iterations,
 	   (long)tv2.tv_sec, (long)tv2.tv_usec);
=20
@@ -91,7 +89,7 @@
=20
 static void
 time_s2k(krb5_context context,
-	 krb5_enctype etype,=20
+	 krb5_enctype etype,
 	 const char *password,
 	 krb5_salt salt,
 	 int iterations)
@@ -124,7 +122,7 @@
=20
     timevalsub(&tv2, &tv1);
=20
-    printf("%s string2key %d iterations time: %3ld.%06ld\n",=20
+    printf("%s string2key %d iterations time: %3ld.%06ld\n",
 	   etype_name, iterations, (long)tv2.tv_sec, (long)tv2.tv_usec);
     free(etype_name);
=20
@@ -159,7 +157,7 @@
     int optidx =3D 0;
     krb5_salt salt;
=20
-    krb5_enctype enctypes[] =3D {=20
+    krb5_enctype enctypes[] =3D {
 	ETYPE_DES_CBC_CRC,
 	ETYPE_DES3_CBC_SHA1,
 	ETYPE_ARCFOUR_HMAC_MD5,
@@ -171,7 +169,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -180,9 +178,6 @@
 	exit(0);
     }
=20
-    argc -=3D optidx;
-    argv +=3D optidx;
-
     salt.salttype =3D KRB5_PW_SALT;
     salt.saltvalue.data =3D NULL;
     salt.saltvalue.length =3D 0;
@@ -196,6 +191,8 @@
=20
     for (i =3D 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) {
=20
+	krb5_enctype_enable(context, enctypes[i]);
+
 	time_encryption(context, 16, enctypes[i], enciter);
 	time_encryption(context, 32, enctypes[i], enciter);
 	time_encryption(context, 512, enctypes[i], enciter);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_cryp=
to_wrapping.c
--- a/head/crypto/heimdal/lib/krb5/test_crypto_wrapping.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_crypto_wrapping.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_crypto_wrapping.c 18809 2006-10-22 07:11:43Z lha $");
-
 static void
 test_wrapping(krb5_context context,
 	      size_t min_size,
@@ -124,10 +122,12 @@
     krb5_error_code ret;
     int i, optidx =3D 0;
=20
-    krb5_enctype enctypes[] =3D {=20
+    krb5_enctype enctypes[] =3D {
+#ifdef HEIM_WEAK_CRYPTO
 	ETYPE_DES_CBC_CRC,
 	ETYPE_DES_CBC_MD4,
 	ETYPE_DES_CBC_MD5,
+#endif
 	ETYPE_DES3_CBC_SHA1,
 	ETYPE_ARCFOUR_HMAC_MD5,
 	ETYPE_AES128_CTS_HMAC_SHA1_96,
@@ -138,7 +138,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -155,6 +155,8 @@
 	errx (1, "krb5_init_context failed: %d", ret);
=20
     for (i =3D 0; i < sizeof(enctypes)/sizeof(enctypes[0]); i++) {
+	krb5_enctype_enable(context, enctypes[i]);
+
 	test_wrapping(context, 0, 1024, 1, enctypes[i]);
 	test_wrapping(context, 1024, 1024 * 100, 1024, enctypes[i]);
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_forw=
ard.c
--- a/head/crypto/heimdal/lib/krb5/test_forward.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/test_forward.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2008 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id$");
-
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
@@ -72,7 +70,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -97,11 +95,11 @@
=20
     ret =3D krb5_cc_default(context, &id);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_cc_default failed: %d", ret);
+	krb5_err(context, 1, ret, "krb5_cc_default failed");
=20
     ret =3D krb5_auth_con_init(context, &ac);
     if (ret)
-	krb5_err(context, 1, ret, "krb5_auth_con_init failed: %d", ret);
+	krb5_err(context, 1, ret, "krb5_auth_con_init failed");
=20
     krb5_auth_con_addflags(context, ac,
 			   KRB5_AUTH_CONTEXT_CLEAR_FORWARDED_CRED, NULL);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_get_=
addrs.c
--- a/head/crypto/heimdal/lib/krb5/test_get_addrs.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_get_addrs.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2000 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_get_addrs.c 15474 2005-06-17 04:48:02Z lha $");
-
 /* print all addresses that we find */
=20
 static void
@@ -44,7 +42,7 @@
     int i;
     char buf[256];
     size_t len;
-   =20
+
     for (i =3D 0; i < addrs->len; ++i) {
 	krb5_print_address (&addrs->val[i], buf, sizeof(buf), &len);
 	printf ("%s\n", buf);
@@ -83,7 +81,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -92,9 +90,6 @@
 	exit(0);
     }
=20
-    argc -=3D optidx;
-    argv +=3D optidx;
-
     ret =3D krb5_init_context(&context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_host=
name.c
--- a/head/crypto/heimdal/lib/krb5/test_hostname.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_hostname.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_hostname.c 15965 2005-08-23 20:18:55Z lha $");
-
 static int debug_flag	=3D 0;
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
@@ -122,7 +120,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_keyt=
ab.c
--- a/head/crypto/heimdal/lib/krb5/test_keytab.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/test_keytab.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,8 +32,7 @@
=20
 #include "krb5_locl.h"
 #include <err.h>
-
-RCSID("$Id: test_keytab.c 18809 2006-10-22 07:11:43Z lha $");
+#include <getarg.h>
=20
 /*
  * Test that removal entry from of empty keytab doesn't corrupts
@@ -55,6 +54,10 @@
=20
     krb5_kt_remove_entry(context, id, &entry);
=20
+    ret =3D krb5_kt_have_content(context, id);
+    if (ret =3D=3D 0)
+	krb5_errx(context, 1, "supposed to be empty keytab isn't");
+
     ret =3D krb5_kt_close(context, id);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_kt_close");
@@ -167,23 +170,120 @@
     krb5_free_keyblock_contents(context, &entry3.keyblock);
 }
=20
+static void
+perf_add(krb5_context context, krb5_keytab id, int times)
+{
+}
+
+static void
+perf_find(krb5_context context, krb5_keytab id, int times)
+{
+}
+
+static void
+perf_delete(krb5_context context, krb5_keytab id, int forward, int times)
+{
+}
+
+
+static int version_flag =3D 0;
+static int help_flag	=3D 0;
+static char *perf_str   =3D NULL;
+static int times =3D 1000;
+
+static struct getargs args[] =3D {
+    {"performance",	0,	arg_string,	&perf_str,
+     "test performance for named keytab", "keytab" },
+    {"times",	0,	arg_integer,	&times,
+     "number of times to run the perforamce test", "number" },
+    {"version",	0,	arg_flag,	&version_flag,
+     "print version", NULL },
+    {"help",	0,	arg_flag,	&help_flag,
+     NULL, NULL }
+};
+
+static void
+usage (int ret)
+{
+    arg_printusage (args,
+		    sizeof(args)/sizeof(*args),
+		    NULL,
+		    "");
+    exit (ret);
+}
+
 int
 main(int argc, char **argv)
 {
     krb5_context context;
     krb5_error_code ret;
+    int optidx =3D 0;
=20
     setprogname(argv[0]);
=20
+    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
+	usage(1);
+
+    if (help_flag)
+	usage (0);
+
+    if(version_flag){
+	print_version(NULL);
+	exit(0);
+    }
+
+    argc -=3D optidx;
+    argv +=3D optidx;
+
+    if (argc !=3D 0)
+	errx(1, "argc !=3D 0");
+
     ret =3D krb5_init_context(&context);
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
=20
-    test_empty_keytab(context, "MEMORY:foo");
-    test_empty_keytab(context, "FILE:foo");
-    test_empty_keytab(context, "KRB4:foo");
+    if (perf_str) {
+	krb5_keytab id;
=20
-    test_memory_keytab(context, "MEMORY:foo", "MEMORY:foo2");
+	ret =3D krb5_kt_resolve(context, perf_str, &id);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_kt_resolve: %s", perf_str);
+
+	/* add, find, delete on keytab */
+	perf_add(context, id, times);
+	perf_find(context, id, times);
+	perf_delete(context, id, 0, times);
+
+	/* add and find again on used keytab */
+	perf_add(context, id, times);
+	perf_find(context, id, times);
+
+	ret =3D krb5_kt_destroy(context, id);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_kt_destroy: %s", perf_str);
+
+	ret =3D krb5_kt_resolve(context, perf_str, &id);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_kt_resolve: %s", perf_str);
+
+	/* try delete backwards */
+#if 0
+	perf_add(context, id, times);
+	perf_delete(context, id, 1, times);
+#endif
+
+	ret =3D krb5_kt_destroy(context, id);
+	if (ret)
+	    krb5_err(context, 1, ret, "krb5_kt_destroy");
+
+    } else {
+
+	test_empty_keytab(context, "MEMORY:foo");
+	test_empty_keytab(context, "FILE:foo");
+
+	test_memory_keytab(context, "MEMORY:foo", "MEMORY:foo2");
+
+    }
=20
     krb5_free_context(context);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_kuse=
rok.c
--- a/head/crypto/heimdal/lib/krb5/test_kuserok.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/krb5/test_kuserok.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include <getarg.h>
 #include <err.h>
=20
-RCSID("$Id: test_kuserok.c 15033 2005-04-30 15:15:38Z lha $");
-
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
@@ -69,7 +67,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &o))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -91,7 +89,7 @@
     ret =3D krb5_parse_name(context, argv[0], &principal);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
-   =20
+
     ret =3D krb5_unparse_name(context, principal, &p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_unparse_name");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_mem.c
--- a/head/crypto/heimdal/lib/krb5/test_mem.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_mem.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: test_mem.c 15931 2005-08-12 13:43:46Z lha $");
-
 /*
  * Test run functions, to be used with valgrind to detect memoryleaks.
  */
@@ -52,11 +50,11 @@
 	ret =3D krb5_init_context(&context);
 	if (ret)
 	    errx (1, "krb5_init_context failed: %d", ret);
-   =20
+
 	krb5_initlog(context, "test-mem", &logfacility);
 	krb5_addlog_dest(context, logfacility, "0/STDERR:");
 	krb5_set_warn_dest(context, logfacility);
-   =20
+
 	krb5_free_context(context);
     }
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_pac.c
--- a/head/crypto/heimdal/lib/krb5/test_pac.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_pac.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,58 +1,56 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: test_pac.c 21934 2007-08-27 14:21:04Z lha $");
-
 /*
  * This PAC and keys are copied (with permission) from Samba torture
  * regression test suite, they where created by Andrew Bartlet.
  */
=20
 static const unsigned char saved_pac[] =3D {
-	0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0=
xd8, 0x01, 0x00, 0x00,=20
+	0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0=
xd8, 0x01, 0x00, 0x00,
 	0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0=
x20, 0x00, 0x00, 0x00,
 	0x20, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0=
x14, 0x00, 0x00, 0x00,
 	0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0=
x14, 0x00, 0x00, 0x00,
 	0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x08, 0x00, 0=
xcc, 0xcc, 0xcc, 0xcc,
-	0xc8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0=
x30, 0xdf, 0xa6, 0xcb,=20
-	0x4f, 0x7d, 0xc5, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0=
xff, 0xff, 0xff, 0xff,=20
+	0xc8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0=
x30, 0xdf, 0xa6, 0xcb,
+	0x4f, 0x7d, 0xc5, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0=
xff, 0xff, 0xff, 0xff,
 	0xff, 0xff, 0xff, 0x7f, 0xc0, 0x3c, 0x4e, 0x59, 0x62, 0x73, 0xc5, 0x01, 0=
xc0, 0x3c, 0x4e, 0x59,
 	0x62, 0x73, 0xc5, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0=
x16, 0x00, 0x16, 0x00,
 	0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0=
x00, 0x00, 0x00, 0x00,
-	0x0c, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0=
x00, 0x00, 0x00, 0x00,=20
-	0x14, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x02, 0x00, 0=
x65, 0x00, 0x00, 0x00,=20
+	0x0c, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x02, 0x00, 0=
x00, 0x00, 0x00, 0x00,
+	0x14, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x02, 0x00, 0=
x65, 0x00, 0x00, 0x00,
 	0xed, 0x03, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0=
x1c, 0x00, 0x02, 0x00,
 	0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0=
x00, 0x00, 0x00, 0x00,
 	0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x16, 0x00, 0x20, 0x00, 0x02, 0x00, 0=
x16, 0x00, 0x18, 0x00,
@@ -95,7 +93,70 @@
 };
=20
 static time_t authtime =3D 1120440609;
-static const char *user =3D "[email protected]";
+static const char *user =3D "w2003final$";
+
+/*
+ * This pac from Christan Krause
+ */
+
+static const unsigned char saved_pac2[] =3D
+    "\x05\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\xc8\x01\x00\x00"
+    "\x58\x00\x00\x00\x00\x00\x00\x00\x0a\x00\x00\x00\x18\x00\x00\x00"
+    "\x20\x02\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00\x70\x00\x00\x00"
+    "\x38\x02\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x14\x00\x00\x00"
+    "\xa8\x02\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00\x14\x00\x00\x00"
+    "\xc0\x02\x00\x00\x00\x00\x00\x00\x01\x10\x08\x00\xcc\xcc\xcc\xcc"
+    "\xb8\x01\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x7d\xee\x09\x76"
+    "\xf2\x39\xc9\x01\xff\xff\xff\xff\xff\xff\xff\x7f\xff\xff\xff\xff"
+    "\xff\xff\xff\x7f\x6d\x49\x38\x62\xf2\x39\xc9\x01\x6d\x09\xa2\x8c"
+    "\xbb\x3a\xc9\x01\xff\xff\xff\xff\xff\xff\xff\x7f\x0e\x00\x0e\x00"
+    "\x04\x00\x02\x00\x10\x00\x10\x00\x08\x00\x02\x00\x00\x00\x00\x00"
+    "\x0c\x00\x02\x00\x00\x00\x00\x00\x10\x00\x02\x00\x00\x00\x00\x00"
+    "\x14\x00\x02\x00\x00\x00\x00\x00\x18\x00\x02\x00\x02\x01\x00\x00"
+    "\x52\x04\x00\x00\x01\x02\x00\x00\x03\x00\x00\x00\x1c\x00\x02\x00"
+    "\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+    "\x00\x00\x00\x00\x10\x00\x12\x00\x20\x00\x02\x00\x0e\x00\x10\x00"
+    "\x24\x00\x02\x00\x28\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+    "\x10\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+    "\x00\x00\x00\x00\x07\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00"
+    "\x6f\x00\x70\x00\x65\x00\x6e\x00\x6d\x00\x73\x00\x70\x00\x00\x00"
+    "\x08\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x6f\x00\x70\x00"
+    "\x65\x00\x6e\x00\x20\x00\x6d\x00\x73\x00\x70\x00\x00\x00\x00\x00"
+    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
+    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00"
+    "\x60\x04\x00\x00\x07\x00\x00\x00\x01\x02\x00\x00\x07\x00\x00\x00"
+    "\x5e\x04\x00\x00\x07\x00\x00\x00\x09\x00\x00\x00\x00\x00\x00\x00"
+    "\x08\x00\x00\x00\x43\x00\x48\x00\x4b\x00\x52\x00\x2d\x00\x41\x00"
+    "\x44\x00\x53\x00\x08\x00\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00"
+    "\x4d\x00\x53\x00\x50\x00\x2d\x00\x41\x00\x44\x00\x53\x00\x00\x00"
+    "\x04\x00\x00\x00\x01\x04\x00\x00\x00\x00\x00\x05\x15\x00\x00\x00"
+    "\x91\xad\xdc\x4c\x63\xb8\xb5\x48\xd5\x53\xd2\xd1\x00\x00\x00\x00"
+    "\x00\x66\xeb\x75\xf2\x39\xc9\x01\x0e\x00\x6f\x00\x70\x00\x65\x00"
+    "\x6e\x00\x6d\x00\x73\x00\x70\x00\x38\x00\x10\x00\x28\x00\x48\x00"
+    "\x00\x00\x00\x00\x00\x00\x00\x00\x6f\x00\x70\x00\x65\x00\x6e\x00"
+    "\x6d\x00\x73\x00\x70\x00\x40\x00\x6d\x00\x73\x00\x70\x00\x2d\x00"
+    "\x61\x00\x64\x00\x73\x00\x2e\x00\x70\x00\x65\x00\x70\x00\x70\x00"
+    "\x65\x00\x72\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x64\x00\x65\x00"
+    "\x4d\x00\x53\x00\x50\x00\x2d\x00\x41\x00\x44\x00\x53\x00\x2e\x00"
+    "\x50\x00\x45\x00\x50\x00\x50\x00\x45\x00\x52\x00\x43\x00\x4f\x00"
+    "\x4e\x00\x2e\x00\x44\x00\x45\x00\x76\xff\xff\xff\xb3\x56\x15\x29"
+    "\x37\xc6\x5c\xf7\x97\x35\xfa\xec\x59\xe8\x96\xa0\x00\x00\x00\x00"
+    "\x76\xff\xff\xff\x50\x71\xa2\xb1\xa3\x64\x82\x5c\xfd\x23\xea\x3b"
+    "\xb0\x19\x12\xd4\x00\x00\x00\x00";
+
+
+static const krb5_keyblock member_keyblock2 =3D {
+    ETYPE_DES_CBC_MD5,
+    { 8, "\x9e\x37\x83\x25\x4a\x7f\xf2\xf8" }
+};
+
+static time_t authtime2 =3D 1225304188;
+static const char *user2 =3D "openmsp";
+
+
=20
 int
 main(int argc, char **argv)
@@ -104,13 +165,16 @@
     krb5_context context;
     krb5_pac pac;
     krb5_data data;
-    krb5_principal p;
+    krb5_principal p, p2;
=20
     ret =3D krb5_init_context(&context);
     if (ret)
 	errx(1, "krb5_init_contex");
=20
-    ret =3D krb5_parse_name(context, user, &p);
+    krb5_enctype_enable(context, ETYPE_DES_CBC_MD5);
+
+    ret =3D krb5_parse_name_flags(context, user,
+				KRB5_PRINCIPAL_PARSE_NO_REALM, &p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
@@ -123,7 +187,7 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_pac_verify");
=20
-    ret =3D _krb5_pac_sign(context, pac, authtime, p,=20
+    ret =3D _krb5_pac_sign(context, pac, authtime, p,
 			 &member_keyblock, &kdc_keyblock, &data);
     if (ret)
 	krb5_err(context, 1, ret, "_krb5_pac_sign");
@@ -166,10 +230,10 @@
=20
 	    if (list[i] =3D=3D 1) {
 		if (type_1_length !=3D data.length)
-		    krb5_errx(context, 1, "type 1 have wrong length: %lu",=20
+		    krb5_errx(context, 1, "type 1 have wrong length: %lu",
 			      (unsigned long)data.length);
 	    } else
-		krb5_errx(context, 1, "unknown type %lu",=20
+		krb5_errx(context, 1, "unknown type %lu",
 			  (unsigned long)list[i]);
=20
 	    ret =3D krb5_pac_add_buffer(context, pac2, list[i], &data);
@@ -178,29 +242,51 @@
 	    krb5_data_free(&data);
 	}
 	free(list);
-=09
-	ret =3D _krb5_pac_sign(context, pac2, authtime, p,=20
+
+	ret =3D _krb5_pac_sign(context, pac2, authtime, p,
 			     &member_keyblock, &kdc_keyblock, &data);
 	if (ret)
 	    krb5_err(context, 1, ret, "_krb5_pac_sign 4");
-=09
+
 	krb5_pac_free(context, pac2);
=20
 	ret =3D krb5_pac_parse(context, data.data, data.length, &pac2);
+	krb5_data_free(&data);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_pac_parse 4");
-=09
+
 	ret =3D krb5_pac_verify(context, pac2, authtime, p,
 			      &member_keyblock, &kdc_keyblock);
 	if (ret)
 	    krb5_err(context, 1, ret, "krb5_pac_verify 4");
-=09
+
 	krb5_pac_free(context, pac2);
     }
=20
     krb5_pac_free(context, pac);
=20
     /*
+     * check pac from Christian
+     */
+
+    ret =3D krb5_parse_name_flags(context, user2,
+				KRB5_PRINCIPAL_PARSE_NO_REALM, &p2);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_parse_name");
+
+    ret =3D krb5_pac_parse(context, saved_pac2, sizeof(saved_pac2) -1, &pa=
c);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_pac_parse");
+
+    ret =3D krb5_pac_verify(context, pac, authtime2, p2,
+			   &member_keyblock2, NULL);
+    if (ret)
+	krb5_err(context, 1, ret, "krb5_pac_verify c1");
+
+    krb5_pac_free(context, pac);
+    krb5_free_principal(context, p2);
+
+    /*
      * Test empty free
      */
=20
@@ -256,7 +342,7 @@
 	krb5_data_free(&data);
     }
=20
-    ret =3D _krb5_pac_sign(context, pac, authtime, p,=20
+    ret =3D _krb5_pac_sign(context, pac, authtime, p,
 			 &member_keyblock, &kdc_keyblock, &data);
     if (ret)
 	krb5_err(context, 1, ret, "_krb5_pac_sign");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_pkin=
it_dh2key.c
--- a/head/crypto/heimdal/lib/krb5/test_pkinit_dh2key.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_pkinit_dh2key.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,11 +34,9 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_pkinit_dh2key.c 18809 2006-10-22 07:11:43Z lha $");
-
 static void
 test_dh2key(int i,
-	    krb5_context context,=20
+	    krb5_context context,
 	    const heim_octet_string *dh,
 	    const heim_octet_string *c_n,
 	    const heim_octet_string *k_n,
@@ -191,7 +189,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -208,7 +206,7 @@
 	errx (1, "krb5_init_context failed: %d", ret);
=20
     for (i =3D 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
-	test_dh2key(i, context, &tests[i].X, NULL, NULL,=20
+	test_dh2key(i, context, &tests[i].X, NULL, NULL,
 		    tests[i].type, &tests[i].key);
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_plug=
in.c
--- a/head/crypto/heimdal/lib/krb5/test_plugin.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/test_plugin.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include <krb5_locl.h>
-RCSID("$Id: test_plugin.c 22024 2007-11-03 21:36:55Z lha $");
 #include "locate_plugin.h"
=20
 static krb5_error_code
@@ -52,7 +51,7 @@
 	       enum locate_service_type service,
 	       const char *realm,
 	       int domain,
-	       int type,=20
+	       int type,
 	       int (*add)(void *,int,struct sockaddr *),
 	       void *addctx)
 {
@@ -97,7 +96,8 @@
     if (ret)
 	errx(1, "krb5_init_contex");
=20
-    ret =3D krb5_plugin_register(context, PLUGIN_TYPE_DATA, "resolve", &re=
solve);
+    ret =3D krb5_plugin_register(context, PLUGIN_TYPE_DATA,
+			       KRB5_PLUGIN_LOCATE, &resolve);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_plugin_register");
=20
@@ -110,7 +110,7 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_krbhst_init_flags");
=20
-   =20
+
     while(krb5_krbhst_next_as_string(context, handle, host, sizeof(host)) =
=3D=3D 0){
 	found++;
  	if (strcmp(host, "127.0.0.2") !=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_prf.c
--- a/head/crypto/heimdal/lib/krb5/test_prf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/test_prf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: test_prf.c 20843 2007-06-03 14:23:20Z lha $");
-
 #include <hex.h>
 #include <err.h>
=20
@@ -42,7 +40,7 @@
  * key: string2key(aes256, "testkey", "testkey", default_params)
  * input: unhex(1122334455667788)
  * output: 58b594b8a61df6e9439b7baa991ff5c1
- *=20
+ *
  * key: string2key(aes128, "testkey", "testkey", default_params)
  * input: unhex(1122334455667788)
  * output: ffa2f823aa7f83a8ce3c5fb730587129
@@ -93,7 +91,7 @@
     krb5_data_free(&output2);
=20
     krb5_crypto_destroy(context, crypto);
-   =20
+
     krb5_free_keyblock_contents(context, &key);
=20
     krb5_free_context(context);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_prin=
c.c
--- a/head/crypto/heimdal/lib/krb5/test_princ.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/test_princ.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: test_princ.c 22071 2007-11-14 20:04:50Z lha $");
-
 /*
  * Check that a closed cc still keeps it data and that it's no longer
  * there when it's destroyed.
@@ -67,7 +65,7 @@
=20
     free(princ_unparsed);
=20
-    ret =3D krb5_unparse_name_flags(context, p,=20
+    ret =3D krb5_unparse_name_flags(context, p,
 				  KRB5_PRINCIPAL_UNPARSE_NO_REALM,
 				  &princ_unparsed);
     if (ret)
@@ -76,10 +74,11 @@
     if (strcmp(princ_short, princ_unparsed))
 	krb5_errx(context, 1, "%s !=3D %s", princ_short, princ_unparsed);
     free(princ_unparsed);
-   =20
+
     realm =3D krb5_principal_get_realm(context, p);
=20
-    asprintf(&princ_reformed, "%s@%s", princ_short, realm);
+    if (asprintf(&princ_reformed, "%s@%s", princ_short, realm) < 0 || prin=
c_reformed =3D=3D NULL)
+	errx(1, "malloc");
=20
     ret =3D krb5_parse_name(context, princ_reformed, &p2);
     free(princ_reformed);
@@ -88,7 +87,7 @@
=20
     if (!krb5_principal_compare(context, p, p2)) {
 	krb5_errx(context, 1, "p !=3D p2");
-    }   =20
+    }
=20
     krb5_free_principal(context, p2);
=20
@@ -96,7 +95,7 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
-    ret =3D krb5_unparse_name_flags(context, p,=20
+    ret =3D krb5_unparse_name_flags(context, p,
 				  KRB5_PRINCIPAL_UNPARSE_SHORT,
 				  &princ_unparsed);
     if (ret)
@@ -181,20 +180,20 @@
 	krb5_errx(context, 1, "'%s' !=3D '%s'", princ, princ_unparsed);
     free(princ_unparsed);
=20
-    ret =3D krb5_parse_name_flags(context, princ,=20
+    ret =3D krb5_parse_name_flags(context, princ,
 				KRB5_PRINCIPAL_PARSE_NO_REALM,
 				&p2);
     if (!ret)
 	krb5_err(context, 1, ret, "Should have failed to parse %s a "
 		 "short name", princ);
=20
-    ret =3D krb5_parse_name_flags(context, princ_short,=20
+    ret =3D krb5_parse_name_flags(context, princ_short,
 				KRB5_PRINCIPAL_PARSE_NO_REALM,
 				&p2);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
-    ret =3D krb5_unparse_name_flags(context, p2,=20
+    ret =3D krb5_unparse_name_flags(context, p2,
 				  KRB5_PRINCIPAL_UNPARSE_NO_REALM,
 				  &princ_unparsed);
     krb5_free_principal(context, p2);
@@ -205,23 +204,23 @@
 	krb5_errx(context, 1, "'%s' !=3D '%s'", princ_short, princ_unparsed);
     free(princ_unparsed);
=20
-    ret =3D krb5_parse_name_flags(context, princ_short,=20
-				KRB5_PRINCIPAL_PARSE_MUST_REALM,
+    ret =3D krb5_parse_name_flags(context, princ_short,
+				KRB5_PRINCIPAL_PARSE_REQUIRE_REALM,
 				&p2);
     if (!ret)
 	krb5_err(context, 1, ret, "Should have failed to parse %s "
 		 "because it lacked a realm", princ_short);
=20
     ret =3D krb5_parse_name_flags(context, princ,
-				KRB5_PRINCIPAL_PARSE_MUST_REALM,
+				KRB5_PRINCIPAL_PARSE_REQUIRE_REALM,
 				&p2);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
-   =20
+
     if (!krb5_principal_compare(context, p, p2))
 	krb5_errx(context, 1, "p !=3D p2");
=20
-    ret =3D krb5_unparse_name_flags(context, p2,=20
+    ret =3D krb5_unparse_name_flags(context, p2,
 				  KRB5_PRINCIPAL_UNPARSE_NO_REALM,
 				  &princ_unparsed);
     krb5_free_principal(context, p2);
@@ -274,7 +273,7 @@
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name");
=20
-    ret =3D krb5_parse_name_flags(context, "lha at su.se@WIN.SU.SE",=20
+    ret =3D krb5_parse_name_flags(context, "lha at su.se@WIN.SU.SE",
 				KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name_flags");
@@ -293,7 +292,7 @@
      *
      */
=20
-    ret =3D krb5_parse_name_flags(context, "lha\\@su.se at WIN.SU.SE",=20
+    ret =3D krb5_parse_name_flags(context, "lha\\@su.se at WIN.SU.SE",
 				KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name_flags");
@@ -328,7 +327,7 @@
      *
      */
=20
-    ret =3D krb5_parse_name_flags(context, "lha at su.se",=20
+    ret =3D krb5_parse_name_flags(context, "lha at su.se",
 				KRB5_PRINCIPAL_PARSE_ENTERPRISE, &p);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_parse_name_flags");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_rene=
w.c
--- a/head/crypto/heimdal/lib/krb5/test_renew.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/test_renew.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -35,9 +35,6 @@
 #include <err.h>
 #include <getarg.h>
=20
-RCSID("$Id$");
-
-
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
@@ -66,14 +63,14 @@
     const char *in_tkt_service =3D NULL;
     krb5_ccache id;
     krb5_error_code ret;
-    krb5_creds out;;
+    krb5_creds out;
     int optidx =3D 0;
=20
     setprogname(argv[0]);
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -109,7 +106,7 @@
 				 in_tkt_service);
=20
     if(ret)
-	krb5_err(context, 1, ret, "krb5_get_kdc_cred");
+	krb5_err(context, 1, ret, "krb5_get_renewed_creds");
=20
     if (krb5_principal_compare(context, out.client, client) !=3D TRUE)
 	krb5_errx(context, 1, "return principal is not as expected");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_stor=
e.c
--- a/head/crypto/heimdal/lib/krb5/test_store.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/krb5/test_store.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -33,8 +33,6 @@
 #include "krb5_locl.h"
 #include <getarg.h>
=20
-RCSID("$Id: test_store.c 20192 2007-02-05 23:21:03Z lha $");
-
 static void
 test_int8(krb5_context context, krb5_storage *sp)
 {
@@ -44,6 +42,8 @@
 	0, 1, -1, 128, -127
     }, v;
=20
+    krb5_storage_truncate(sp, 0);
+
     for (i =3D 0; i < sizeof(val[0])/sizeof(val); i++) {
=20
 	ret =3D krb5_store_int8(sp, val[i]);
@@ -67,6 +67,8 @@
 	0, 1, -1, 32768, -32767
     }, v;
=20
+    krb5_storage_truncate(sp, 0);
+
     for (i =3D 0; i < sizeof(val[0])/sizeof(val); i++) {
=20
 	ret =3D krb5_store_int16(sp, val[i]);
@@ -90,6 +92,8 @@
 	0, 1, -1, 2147483647, -2147483646
     }, v;
=20
+    krb5_storage_truncate(sp, 0);
+
     for (i =3D 0; i < sizeof(val[0])/sizeof(val); i++) {
=20
 	ret =3D krb5_store_int32(sp, val[i]);
@@ -113,6 +117,8 @@
 	0, 1, 255
     }, v;
=20
+    krb5_storage_truncate(sp, 0);
+
     for (i =3D 0; i < sizeof(val[0])/sizeof(val); i++) {
=20
 	ret =3D krb5_store_uint8(sp, val[i]);
@@ -136,6 +142,8 @@
 	0, 1, 65535
     }, v;
=20
+    krb5_storage_truncate(sp, 0);
+
     for (i =3D 0; i < sizeof(val[0])/sizeof(val); i++) {
=20
 	ret =3D krb5_store_uint16(sp, val[i]);
@@ -159,6 +167,8 @@
 	0, 1, 4294967295UL
     }, v;
=20
+    krb5_storage_truncate(sp, 0);
+
     for (i =3D 0; i < sizeof(val[0])/sizeof(val); i++) {
=20
 	ret =3D krb5_store_uint32(sp, val[i]);
@@ -175,22 +185,54 @@
=20
=20
 static void
-test_storage(krb5_context context)
+test_storage(krb5_context context, krb5_storage *sp)
 {
-    krb5_storage *sp;
-
-    sp =3D krb5_storage_emem();
-    if (sp =3D=3D NULL)
-	krb5_errx(context, 1, "krb5_storage_emem: no mem");
-
     test_int8(context, sp);
     test_int16(context, sp);
     test_int32(context, sp);
     test_uint8(context, sp);
     test_uint16(context, sp);
     test_uint32(context, sp);
+}
=20
-    krb5_storage_free(sp);
+
+static void
+test_truncate(krb5_context context, krb5_storage *sp, int fd)
+{
+    struct stat sb;
+
+    krb5_store_string(sp, "hej");
+    krb5_storage_truncate(sp, 2);
+
+    if (fstat(fd, &sb) !=3D 0)
+	krb5_err(context, 1, errno, "fstat");
+    if (sb.st_size !=3D 2)
+	krb5_errx(context, 1, "length not 2");
+
+    krb5_storage_truncate(sp, 1024);
+
+    if (fstat(fd, &sb) !=3D 0)
+	krb5_err(context, 1, errno, "fstat");
+    if (sb.st_size !=3D 1024)
+	krb5_errx(context, 1, "length not 2");
+}
+
+static void
+check_too_large(krb5_context context, krb5_storage *sp)
+{
+    uint32_t too_big_sizes[] =3D { INT_MAX, INT_MAX / 2, INT_MAX / 4, INT_=
MAX / 8 + 1};
+    krb5_error_code ret;
+    krb5_data data;
+    size_t n;
+
+    for (n =3D 0; n < sizeof(too_big_sizes) / sizeof(too_big_sizes); n++) {
+	krb5_storage_truncate(sp, 0);
+	krb5_store_uint32(sp, too_big_sizes[n]);
+	krb5_storage_seek(sp, 0, SEEK_SET);
+	ret =3D krb5_ret_data(sp, &data);
+	if (ret !=3D HEIM_ERR_TOO_BIG)
+	    errx(1, "not too big: %lu", (unsigned long)n);
+    }
 }
=20
 /*
@@ -222,13 +264,15 @@
 {
     krb5_context context;
     krb5_error_code ret;
-    int optidx =3D 0;
+    int fd, optidx =3D 0;
+    krb5_storage *sp;
+    const char *fn =3D "test-store-data";
=20
     setprogname(argv[0]);
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -244,7 +288,48 @@
     if (ret)
 	errx (1, "krb5_init_context failed: %d", ret);
=20
-    test_storage(context);
+    /*
+     * Test encoding/decoding of primotive types on diffrent backends
+     */
+
+    sp =3D krb5_storage_emem();
+    if (sp =3D=3D NULL)
+	krb5_errx(context, 1, "krb5_storage_emem: no mem");
+
+    test_storage(context, sp);
+    check_too_large(context, sp);
+    krb5_storage_free(sp);
+
+
+    fd =3D open(fn, O_RDWR|O_CREAT|O_TRUNC, 0600);
+    if (fd < 0)
+	krb5_err(context, 1, errno, "open(%s)", fn);
+
+    sp =3D krb5_storage_from_fd(fd);
+    close(fd);
+    if (sp =3D=3D NULL)
+	krb5_errx(context, 1, "krb5_storage_from_fd: %s no mem", fn);
+
+    test_storage(context, sp);
+    krb5_storage_free(sp);
+    unlink(fn);
+
+    /*
+     * test truncate behavior
+     */
+
+    fd =3D open(fn, O_RDWR|O_CREAT|O_TRUNC, 0600);
+    if (fd < 0)
+	krb5_err(context, 1, errno, "open(%s)", fn);
+
+    sp =3D krb5_storage_from_fd(fd);
+    if (sp =3D=3D NULL)
+	krb5_errx(context, 1, "krb5_storage_from_fd: %s no mem", fn);
+
+    test_truncate(context, sp, fd);
+    krb5_storage_free(sp);
+    close(fd);
+    unlink(fn);
=20
     krb5_free_context(context);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/test_time=
.c
--- a/head/crypto/heimdal/lib/krb5/test_time.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/test_time.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -34,8 +34,6 @@
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: test_time.c 18809 2006-10-22 07:11:43Z lha $");
-
 static void
 check_set_time(krb5_context context)
 {
@@ -51,7 +49,7 @@
     ret =3D krb5_set_real_time(context, tv.tv_sec + diff, tv.tv_usec);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_us_timeofday");
-   =20
+
     ret =3D krb5_us_timeofday(context, &sec, &usec);
     if (ret)
 	krb5_err(context, 1, ret, "krb5_us_timeofday");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/ticket.c
--- a/head/crypto/heimdal/lib/krb5/ticket.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/ticket.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,53 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2009 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: ticket.c 19544 2006-12-28 20:49:18Z lha $");
+/**
+ * Free ticket and content
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to free
+ *
+ * @return Returns 0 to indicate success.  Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_free_ticket(krb5_context context,
 		 krb5_ticket *ticket)
 {
@@ -46,7 +58,20 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Copy ticket and content
+ *
+ * @param context a Kerberos 5 context
+ * @param from ticket to copy
+ * @param to new copy of ticket, free with krb5_free_ticket()
+ *
+ * @return Returns 0 to indicate success.  Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_copy_ticket(krb5_context context,
 		 const krb5_ticket *from,
 		 krb5_ticket **to)
@@ -57,7 +82,8 @@
     *to =3D NULL;
     tmp =3D malloc(sizeof(*tmp));
     if(tmp =3D=3D NULL) {
-	krb5_set_error_string (context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     if((ret =3D copy_EncTicketPart(&from->ticket, &tmp->ticket))){
@@ -81,7 +107,20 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Return client principal in ticket
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to copy
+ * @param client client principal, free with krb5_free_principal()
+ *
+ * @return Returns 0 to indicate success.  Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ticket_get_client(krb5_context context,
 		       const krb5_ticket *ticket,
 		       krb5_principal *client)
@@ -89,7 +128,20 @@
     return krb5_copy_principal(context, ticket->client, client);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Return server principal in ticket
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to copy
+ * @param server server principal, free with krb5_free_principal()
+ *
+ * @return Returns 0 to indicate success.  Otherwise an kerberos et
+ * error code is returned, see krb5_get_error_message().
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ticket_get_server(krb5_context context,
 		       const krb5_ticket *ticket,
 		       krb5_principal *server)
@@ -97,16 +149,44 @@
     return krb5_copy_principal(context, ticket->server, server);
 }
=20
-time_t KRB5_LIB_FUNCTION
+/**
+ * Return end time of ticket
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket ticket to copy
+ *
+ * @return end time of ticket
+ *
+ * @ingroup krb5
+ */
+
+KRB5_LIB_FUNCTION time_t KRB5_LIB_CALL
 krb5_ticket_get_endtime(krb5_context context,
 			const krb5_ticket *ticket)
 {
     return ticket->ticket.endtime;
 }
=20
+/**
+ * Get the flags from the Kerberos ticket
+ *
+ * @param context Kerberos context
+ * @param ticket Kerberos ticket
+ *
+ * @return ticket flags
+ *
+ * @ingroup krb5_ticket
+ */
+KRB5_LIB_FUNCTION unsigned long KRB5_LIB_CALL
+krb5_ticket_get_flags(krb5_context context,
+		      const krb5_ticket *ticket)
+{
+    return TicketFlags2int(ticket->ticket.flags);
+}
+
 static int
 find_type_in_ad(krb5_context context,
-		int type,=20
+		int type,
 		krb5_data *data,
 		krb5_boolean *found,
 		krb5_boolean failp,
@@ -115,12 +195,14 @@
 		int level)
 {
     krb5_error_code ret =3D 0;
-    int i;
+    size_t i;
=20
     if (level > 9) {
-	krb5_set_error_string(context, "Authorization data nested deeper "
-			      "then %d levels, stop searching", level);
 	ret =3D ENOENT; /* XXX */
+	krb5_set_error_message(context, ret,
+			       N_("Authorization data nested deeper "
+				  "then %d levels, stop searching", ""),
+			       level);
 	goto out;
     }
=20
@@ -133,7 +215,8 @@
 	if (!*found && ad->val[i].ad_type =3D=3D type) {
 	    ret =3D der_copy_octet_string(&ad->val[i].ad_data, data);
 	    if (ret) {
-		krb5_set_error_string(context, "malloc - out of memory");
+		krb5_set_error_message(context, ret,
+				       N_("malloc: out of memory", ""));
 		goto out;
 	    }
 	    *found =3D TRUE;
@@ -147,8 +230,10 @@
 					   &child,
 					   NULL);
 	    if (ret) {
-		krb5_set_error_string(context, "Failed to decode "
-				      "IF_RELEVANT with %d", ret);
+		krb5_set_error_message(context, ret,
+				       N_("Failed to decode "
+					  "IF_RELEVANT with %d", ""),
+				       (int)ret);
 		goto out;
 	    }
 	    ret =3D find_type_in_ad(context, type, data, found, FALSE,
@@ -167,8 +252,10 @@
 				      &child,
 				      NULL);
 	    if (ret) {
-		krb5_set_error_string(context, "Failed to decode "
-				      "AD_KDCIssued with %d", ret);
+		krb5_set_error_message(context, ret,
+				       N_("Failed to decode "
+					  "AD_KDCIssued with %d", ""),
+				       ret);
 		goto out;
 	    }
 	    if (failp) {
@@ -176,11 +263,11 @@
 		krb5_data buf;
 		size_t len;
=20
-		ASN1_MALLOC_ENCODE(AuthorizationData, buf.data, buf.length,=20
+		ASN1_MALLOC_ENCODE(AuthorizationData, buf.data, buf.length,
 				   &child.elements, &len, ret);
 		if (ret) {
 		    free_AD_KDCIssued(&child);
-		    krb5_clear_error_string(context);
+		    krb5_clear_error_message(context);
 		    goto out;
 		}
 		if(buf.length !=3D len)
@@ -194,7 +281,7 @@
 		    goto out;
 		}
 		if (!valid) {
-		    krb5_clear_error_string(context);
+		    krb5_clear_error_message(context);
 		    ret =3D ENOENT;
 		    free_AD_KDCIssued(&child);
 		    goto out;
@@ -211,17 +298,20 @@
 	case KRB5_AUTHDATA_AND_OR:
 	    if (!failp)
 		break;
-	    krb5_set_error_string(context, "Authorization data contains "
-				  "AND-OR element that is unknown to the "
-				  "application");
 	    ret =3D ENOENT; /* XXX */
+	    krb5_set_error_message(context, ret,
+				   N_("Authorization data contains "
+				      "AND-OR element that is unknown to the "
+				      "application", ""));
 	    goto out;
 	default:
 	    if (!failp)
 		break;
-	    krb5_set_error_string(context, "Authorization data contains "
-				  "unknown type (%d) ", ad->val[i].ad_type);
 	    ret =3D ENOENT; /* XXX */
+	    krb5_set_error_message(context, ret,
+				   N_("Authorization data contains "
+				      "unknown type (%d) ", ""),
+				   ad->val[i].ad_type);
 	    goto out;
 	}
     }
@@ -235,13 +325,20 @@
     return ret;
 }
=20
-/*
- * Extract the authorization data type of `type' from the
- * 'ticket'. Store the field in `data'. This function is to use for
- * kerberos applications.
+/**
+ * Extract the authorization data type of type from the ticket. Store
+ * the field in data. This function is to use for kerberos
+ * applications.
+ *
+ * @param context a Kerberos 5 context
+ * @param ticket Kerberos ticket
+ * @param type type to fetch
+ * @param data returned data, free with krb5_data_free()
+ *
+ * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_ticket_get_authorization_data_type(krb5_context context,
 					krb5_ticket *ticket,
 					int type,
@@ -255,7 +352,8 @@
=20
     ad =3D ticket->ticket.authorization_data;
     if (ticket->ticket.authorization_data =3D=3D NULL) {
-	krb5_set_error_string(context, "Ticket have not authorization data");
+	krb5_set_error_message(context, ENOENT,
+			       N_("Ticket have not authorization data", ""));
 	return ENOENT; /* XXX */
     }
=20
@@ -264,9 +362,489 @@
     if (ret)
 	return ret;
     if (!found) {
-	krb5_set_error_string(context, "Ticket have not authorization "
-			  "data of type %d", type);
+	krb5_set_error_message(context, ENOENT,
+			       N_("Ticket have not "
+				  "authorization data of type %d", ""),
+			       type);
 	return ENOENT; /* XXX */
     }
     return 0;
 }
+
+static krb5_error_code
+check_server_referral(krb5_context context,
+		      krb5_kdc_rep *rep,
+		      unsigned flags,
+		      krb5_const_principal requested,
+		      krb5_const_principal returned,
+		      krb5_keyblock * key)
+{
+    krb5_error_code ret;
+    PA_ServerReferralData ref;
+    krb5_crypto session;
+    EncryptedData ed;
+    size_t len;
+    krb5_data data;
+    PA_DATA *pa;
+    int i =3D 0, cmp;
+
+    if (rep->kdc_rep.padata =3D=3D NULL)
+	goto noreferral;
+
+    pa =3D krb5_find_padata(rep->kdc_rep.padata->val,
+			  rep->kdc_rep.padata->len,
+			  KRB5_PADATA_SERVER_REFERRAL, &i);
+    if (pa =3D=3D NULL)
+	goto noreferral;
+
+    memset(&ed, 0, sizeof(ed));
+    memset(&ref, 0, sizeof(ref));
+
+    ret =3D decode_EncryptedData(pa->padata_value.data,
+			       pa->padata_value.length,
+			       &ed, &len);
+    if (ret)
+	return ret;
+    if (len !=3D pa->padata_value.length) {
+	free_EncryptedData(&ed);
+	krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+			       N_("Referral EncryptedData wrong for realm %s",
+				  "realm"), requested->realm);
+	return KRB5KRB_AP_ERR_MODIFIED;
+    }
+
+    ret =3D krb5_crypto_init(context, key, 0, &session);
+    if (ret) {
+	free_EncryptedData(&ed);
+	return ret;
+    }
+
+    ret =3D krb5_decrypt_EncryptedData(context, session,
+				     KRB5_KU_PA_SERVER_REFERRAL,
+				     &ed, &data);
+    free_EncryptedData(&ed);
+    krb5_crypto_destroy(context, session);
+    if (ret)
+	return ret;
+
+    ret =3D decode_PA_ServerReferralData(data.data, data.length, &ref, &le=
n);
+    if (ret) {
+	krb5_data_free(&data);
+	return ret;
+    }
+    krb5_data_free(&data);
+
+    if (strcmp(requested->realm, returned->realm) !=3D 0) {
+	free_PA_ServerReferralData(&ref);
+	krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+			       N_("server ref realm mismatch, "
+				  "requested realm %s got back %s", ""),
+			       requested->realm, returned->realm);
+	return KRB5KRB_AP_ERR_MODIFIED;
+    }
+
+    if (krb5_principal_is_krbtgt(context, returned)) {
+	const char *realm =3D returned->name.name_string.val[1];
+
+	if (ref.referred_realm =3D=3D NULL
+	    || strcmp(*ref.referred_realm, realm) !=3D 0)
+	{
+	    free_PA_ServerReferralData(&ref);
+	    krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+				   N_("tgt returned with wrong ref", ""));
+	    return KRB5KRB_AP_ERR_MODIFIED;
+	}
+    } else if (krb5_principal_compare(context, returned, requested) =3D=3D=
 0) {
+	free_PA_ServerReferralData(&ref);
+	krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+			       N_("req princ no same as returned", ""));
+	return KRB5KRB_AP_ERR_MODIFIED;
+    }
+
+    if (ref.requested_principal_name) {
+	cmp =3D _krb5_principal_compare_PrincipalName(context,
+						    requested,
+						    ref.requested_principal_name);
+	if (!cmp) {
+	    free_PA_ServerReferralData(&ref);
+	    krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+				   N_("referred principal not same "
+				      "as requested", ""));
+	    return KRB5KRB_AP_ERR_MODIFIED;
+	}
+    } else if (flags & EXTRACT_TICKET_AS_REQ) {
+	free_PA_ServerReferralData(&ref);
+	krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+			       N_("Requested principal missing on AS-REQ", ""));
+	return KRB5KRB_AP_ERR_MODIFIED;
+    }
+
+    free_PA_ServerReferralData(&ref);
+
+    return ret;
+noreferral:
+    /*
+     * Expect excact match or that we got a krbtgt
+     */
+    if (krb5_principal_compare(context, requested, returned) !=3D TRUE &&
+	(krb5_realm_compare(context, requested, returned) !=3D TRUE &&
+	 krb5_principal_is_krbtgt(context, returned) !=3D TRUE))
+    {
+	krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+			       N_("Not same server principal returned "
+				  "as requested", ""));
+	return KRB5KRB_AP_ERR_MODIFIED;
+    }
+    return 0;
+}
+
+
+/*
+ * Verify referral data
+ */
+
+
+static krb5_error_code
+check_client_referral(krb5_context context,
+		      krb5_kdc_rep *rep,
+		      krb5_const_principal requested,
+		      krb5_const_principal mapped,
+		      krb5_keyblock const * key)
+{
+    krb5_error_code ret;
+    PA_ClientCanonicalized canon;
+    krb5_crypto crypto;
+    krb5_data data;
+    PA_DATA *pa;
+    size_t len;
+    int i =3D 0;
+
+    if (rep->kdc_rep.padata =3D=3D NULL)
+	goto noreferral;
+
+    pa =3D krb5_find_padata(rep->kdc_rep.padata->val,
+			  rep->kdc_rep.padata->len,
+			  KRB5_PADATA_CLIENT_CANONICALIZED, &i);
+    if (pa =3D=3D NULL)
+	goto noreferral;
+
+    ret =3D decode_PA_ClientCanonicalized(pa->padata_value.data,
+					pa->padata_value.length,
+					&canon, &len);
+    if (ret) {
+	krb5_set_error_message(context, ret,
+			       N_("Failed to decode ClientCanonicalized "
+				  "from realm %s", ""), requested->realm);
+	return ret;
+    }
+
+    ASN1_MALLOC_ENCODE(PA_ClientCanonicalizedNames, data.data, data.length,
+		       &canon.names, &len, ret);
+    if (ret) {
+	free_PA_ClientCanonicalized(&canon);
+	return ret;
+    }
+    if (data.length !=3D len)
+	krb5_abortx(context, "internal asn.1 error");
+
+    ret =3D krb5_crypto_init(context, key, 0, &crypto);
+    if (ret) {
+	free(data.data);
+	free_PA_ClientCanonicalized(&canon);
+	return ret;
+    }
+
+    ret =3D krb5_verify_checksum(context, crypto, KRB5_KU_CANONICALIZED_NA=
MES,
+			       data.data, data.length,
+			       &canon.canon_checksum);
+    krb5_crypto_destroy(context, crypto);
+    free(data.data);
+    if (ret) {
+	krb5_set_error_message(context, ret,
+			       N_("Failed to verify client canonicalized "
+				  "data from realm %s", ""),
+			       requested->realm);
+	free_PA_ClientCanonicalized(&canon);
+	return ret;
+    }
+
+    if (!_krb5_principal_compare_PrincipalName(context,
+					       requested,
+					       &canon.names.requested_name))
+    {
+	free_PA_ClientCanonicalized(&canon);
+	krb5_set_error_message(context, KRB5_PRINC_NOMATCH,
+			       N_("Requested name doesn't match"
+				  " in client referral", ""));
+	return KRB5_PRINC_NOMATCH;
+    }
+    if (!_krb5_principal_compare_PrincipalName(context,
+					       mapped,
+					       &canon.names.mapped_name))
+    {
+	free_PA_ClientCanonicalized(&canon);
+	krb5_set_error_message(context, KRB5_PRINC_NOMATCH,
+			       N_("Mapped name doesn't match"
+				  " in client referral", ""));
+	return KRB5_PRINC_NOMATCH;
+    }
+
+    return 0;
+
+noreferral:
+    if (krb5_principal_compare(context, requested, mapped) =3D=3D FALSE) {
+	krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED,
+			       N_("Not same client principal returned "
+				  "as requested", ""));
+	return KRB5KRB_AP_ERR_MODIFIED;
+    }
+    return 0;
+}
+
+
+static krb5_error_code KRB5_CALLCONV
+decrypt_tkt (krb5_context context,
+	     krb5_keyblock *key,
+	     krb5_key_usage usage,
+	     krb5_const_pointer decrypt_arg,
+	     krb5_kdc_rep *dec_rep)
+{
+    krb5_error_code ret;
+    krb5_data data;
+    size_t size;
+    krb5_crypto crypto;
+
+    ret =3D krb5_crypto_init(context, key, 0, &crypto);
+    if (ret)
+	return ret;
+
+    ret =3D krb5_decrypt_EncryptedData (context,
+				      crypto,
+				      usage,
+				      &dec_rep->kdc_rep.enc_part,
+				      &data);
+    krb5_crypto_destroy(context, crypto);
+
+    if (ret)
+	return ret;
+
+    ret =3D decode_EncASRepPart(data.data,
+			      data.length,
+			      &dec_rep->enc_part,
+			      &size);
+    if (ret)
+	ret =3D decode_EncTGSRepPart(data.data,
+				   data.length,
+				   &dec_rep->enc_part,
+				   &size);
+    krb5_data_free (&data);
+    if (ret) {
+        krb5_set_error_message(context, ret,
+			       N_("Failed to decode encpart in ticket", ""));
+	return ret;
+    }
+    return 0;
+}
+
+int
+_krb5_extract_ticket(krb5_context context,
+		     krb5_kdc_rep *rep,
+		     krb5_creds *creds,
+		     krb5_keyblock *key,
+		     krb5_const_pointer keyseed,
+		     krb5_key_usage key_usage,
+		     krb5_addresses *addrs,
+		     unsigned nonce,
+		     unsigned flags,
+		     krb5_decrypt_proc decrypt_proc,
+		     krb5_const_pointer decryptarg)
+{
+    krb5_error_code ret;
+    krb5_principal tmp_principal;
+    size_t len =3D 0;
+    time_t tmp_time;
+    krb5_timestamp sec_now;
+
+    /* decrypt */
+
+    if (decrypt_proc =3D=3D NULL)
+	decrypt_proc =3D decrypt_tkt;
+
+    ret =3D (*decrypt_proc)(context, key, key_usage, decryptarg, rep);
+    if (ret)
+	goto out;
+
+    /* save session key */
+
+    creds->session.keyvalue.length =3D 0;
+    creds->session.keyvalue.data   =3D NULL;
+    creds->session.keytype =3D rep->enc_part.key.keytype;
+    ret =3D krb5_data_copy (&creds->session.keyvalue,
+			  rep->enc_part.key.keyvalue.data,
+			  rep->enc_part.key.keyvalue.length);
+    if (ret) {
+	krb5_clear_error_message(context);
+	goto out;
+    }
+
+    /* compare client and save */
+    ret =3D _krb5_principalname2krb5_principal (context,
+					      &tmp_principal,
+					      rep->kdc_rep.cname,
+					      rep->kdc_rep.crealm);
+    if (ret)
+	goto out;
+
+    /* check client referral and save principal */
+    /* anonymous here ? */
+    if((flags & EXTRACT_TICKET_ALLOW_CNAME_MISMATCH) =3D=3D 0) {
+	ret =3D check_client_referral(context, rep,
+				    creds->client,
+				    tmp_principal,
+				    &creds->session);
+	if (ret) {
+	    krb5_free_principal (context, tmp_principal);
+	    goto out;
+	}
+    }
+    krb5_free_principal (context, creds->client);
+    creds->client =3D tmp_principal;
+
+    /* check server referral and save principal */
+    ret =3D _krb5_principalname2krb5_principal (context,
+					      &tmp_principal,
+					      rep->kdc_rep.ticket.sname,
+					      rep->kdc_rep.ticket.realm);
+    if (ret)
+	goto out;
+    if((flags & EXTRACT_TICKET_ALLOW_SERVER_MISMATCH) =3D=3D 0){
+	ret =3D check_server_referral(context,
+				    rep,
+				    flags,
+				    creds->server,
+				    tmp_principal,
+				    &creds->session);
+	if (ret) {
+	    krb5_free_principal (context, tmp_principal);
+	    goto out;
+	}
+    }
+    krb5_free_principal(context, creds->server);
+    creds->server =3D tmp_principal;
+
+    /* verify names */
+    if(flags & EXTRACT_TICKET_MATCH_REALM){
+	const char *srealm =3D krb5_principal_get_realm(context, creds->server);
+	const char *crealm =3D krb5_principal_get_realm(context, creds->client);
+
+	if (strcmp(rep->enc_part.srealm, srealm) !=3D 0 ||
+	    strcmp(rep->enc_part.srealm, crealm) !=3D 0)
+	{
+	    ret =3D KRB5KRB_AP_ERR_MODIFIED;
+	    krb5_clear_error_message(context);
+	    goto out;
+	}
+    }
+
+    /* compare nonces */
+
+    if (nonce !=3D (unsigned)rep->enc_part.nonce) {
+	ret =3D KRB5KRB_AP_ERR_MODIFIED;
+	krb5_set_error_message(context, ret, N_("malloc: out of memory", ""));
+	goto out;
+    }
+
+    /* set kdc-offset */
+
+    krb5_timeofday (context, &sec_now);
+    if (rep->enc_part.flags.initial
+	&& (flags & EXTRACT_TICKET_TIMESYNC)
+	&& context->kdc_sec_offset =3D=3D 0
+	&& krb5_config_get_bool (context, NULL,
+				 "libdefaults",
+				 "kdc_timesync",
+				 NULL)) {
+	context->kdc_sec_offset =3D rep->enc_part.authtime - sec_now;
+	krb5_timeofday (context, &sec_now);
+    }
+
+    /* check all times */
+
+    if (rep->enc_part.starttime) {
+	tmp_time =3D *rep->enc_part.starttime;
+    } else
+	tmp_time =3D rep->enc_part.authtime;
+
+    if (creds->times.starttime =3D=3D 0
+	&& abs(tmp_time - sec_now) > context->max_skew) {
+	ret =3D KRB5KRB_AP_ERR_SKEW;
+	krb5_set_error_message (context, ret,
+				N_("time skew (%d) larger than max (%d)", ""),
+			       abs(tmp_time - sec_now),
+			       (int)context->max_skew);
+	goto out;
+    }
+
+    if (creds->times.starttime !=3D 0
+	&& tmp_time !=3D creds->times.starttime) {
+	krb5_clear_error_message (context);
+	ret =3D KRB5KRB_AP_ERR_MODIFIED;
+	goto out;
+    }
+
+    creds->times.starttime =3D tmp_time;
+
+    if (rep->enc_part.renew_till) {
+	tmp_time =3D *rep->enc_part.renew_till;
+    } else
+	tmp_time =3D 0;
+
+    if (creds->times.renew_till !=3D 0
+	&& tmp_time > creds->times.renew_till) {
+	krb5_clear_error_message (context);
+	ret =3D KRB5KRB_AP_ERR_MODIFIED;
+	goto out;
+    }
+
+    creds->times.renew_till =3D tmp_time;
+
+    creds->times.authtime =3D rep->enc_part.authtime;
+
+    if (creds->times.endtime !=3D 0
+	&& rep->enc_part.endtime > creds->times.endtime) {
+	krb5_clear_error_message (context);
+	ret =3D KRB5KRB_AP_ERR_MODIFIED;
+	goto out;
+    }
+
+    creds->times.endtime  =3D rep->enc_part.endtime;
+
+    if(rep->enc_part.caddr)
+	krb5_copy_addresses (context, rep->enc_part.caddr, &creds->addresses);
+    else if(addrs)
+	krb5_copy_addresses (context, addrs, &creds->addresses);
+    else {
+	creds->addresses.len =3D 0;
+	creds->addresses.val =3D NULL;
+    }
+    creds->flags.b =3D rep->enc_part.flags;
+
+    creds->authdata.len =3D 0;
+    creds->authdata.val =3D NULL;
+
+    /* extract ticket */
+    ASN1_MALLOC_ENCODE(Ticket, creds->ticket.data, creds->ticket.length,
+		       &rep->kdc_rep.ticket, &len, ret);
+    if(ret)
+	goto out;
+    if (creds->ticket.length !=3D len)
+	krb5_abortx(context, "internal error in ASN.1 encoder");
+    creds->second_ticket.length =3D 0;
+    creds->second_ticket.data   =3D NULL;
+
+
+out:
+    memset (rep->enc_part.key.keyvalue.data, 0,
+	    rep->enc_part.key.keyvalue.length);
+    return ret;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/time.c
--- a/head/crypto/heimdal/lib/krb5/time.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/time.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,62 +1,77 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: time.c 14308 2004-10-13 17:57:11Z lha $");
-
-/*
+/**
  * Set the absolute time that the caller knows the kdc has so the
  * kerberos library can calculate the relative diffrence beteen the
  * KDC time and local system time.
+ *
+ * @param context Keberos 5 context.
+ * @param sec The applications new of "now" in seconds
+ * @param usec The applications new of "now" in micro seconds
+
+ * @return Kerberos 5 error code, see krb5_get_error_message().
+ *
+ * @ingroup krb5
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_real_time (krb5_context context,
 		    krb5_timestamp sec,
 		    int32_t usec)
 {
     struct timeval tv;
-   =20
+
     gettimeofday(&tv, NULL);
=20
     context->kdc_sec_offset =3D sec - tv.tv_sec;
-    context->kdc_usec_offset =3D usec - tv.tv_usec;
=20
-    if (context->kdc_usec_offset < 0) {
-	context->kdc_sec_offset--;
-	context->kdc_usec_offset +=3D 1000000;
-    }
+    /**
+     * If the caller passes in a negative usec, its assumed to be
+     * unknown and the function will use the current time usec.
+     */
+    if (usec >=3D 0) {
+	context->kdc_usec_offset =3D usec - tv.tv_usec;
+
+	if (context->kdc_usec_offset < 0) {
+	    context->kdc_sec_offset--;
+	    context->kdc_usec_offset +=3D 1000000;
+	}
+    } else
+	context->kdc_usec_offset =3D tv.tv_usec;
+
     return 0;
 }
=20
@@ -64,7 +79,7 @@
  * return ``corrected'' time in `timeret'.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_timeofday (krb5_context context,
 		krb5_timestamp *timeret)
 {
@@ -76,7 +91,7 @@
  * like gettimeofday but with time correction to the KDC
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_us_timeofday (krb5_context context,
 		   krb5_timestamp *sec,
 		   int32_t *usec)
@@ -90,8 +105,8 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_format_time(krb5_context context, time_t t,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_format_time(krb5_context context, time_t t,
 		 char *s, size_t len, krb5_boolean include_time)
 {
     struct tm *tm;
@@ -105,7 +120,7 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_string_to_deltat(const char *string, krb5_deltat *deltat)
 {
     if((*deltat =3D parse_time(string, "s")) =3D=3D -1)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/transited=
.c
--- a/head/crypto/heimdal/lib/krb5/transited.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/krb5/transited.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001, 2003 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: transited.c 21745 2007-07-31 16:11:25Z lha $");
-
 /* this is an attempt at one of the most horrible `compression'
    schemes that has ever been invented; it's so amazingly brain-dead
    that words can not describe it, and all this just to save a few
@@ -57,16 +55,15 @@
 	r =3D r->next;
 	free(p->realm);
 	free(p);
-    }=09
+    }
 }
=20
 static int
 make_path(krb5_context context, struct tr_realm *r,
 	  const char *from, const char *to)
 {
+    struct tr_realm *tmp;
     const char *p;
-    struct tr_realm *path =3D r->next;
-    struct tr_realm *tmp;
=20
     if(strlen(from) < strlen(to)){
 	const char *str;
@@ -74,71 +71,65 @@
 	from =3D to;
 	to =3D str;
     }
-=09
+
     if(strcmp(from + strlen(from) - strlen(to), to) =3D=3D 0){
 	p =3D from;
 	while(1){
 	    p =3D strchr(p, '.');
 	    if(p =3D=3D NULL) {
-		krb5_clear_error_string (context);
+		krb5_clear_error_message (context);
 		return KRB5KDC_ERR_POLICY;
 	    }
 	    p++;
 	    if(strcmp(p, to) =3D=3D 0)
 		break;
 	    tmp =3D calloc(1, sizeof(*tmp));
-	    if(tmp =3D=3D NULL){
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
-	    }
-	    tmp->next =3D path;
-	    path =3D tmp;
-	    path->realm =3D strdup(p);
-	    if(path->realm =3D=3D NULL){
-		r->next =3D path; /* XXX */
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;;
+	    if(tmp =3D=3D NULL)
+		return krb5_enomem(context);
+	    tmp->next =3D r->next;
+	    r->next =3D tmp;
+	    tmp->realm =3D strdup(p);
+	    if(tmp->realm =3D=3D NULL){
+		r->next =3D tmp->next;
+		free(tmp);
+		return krb5_enomem(context);
 	    }
 	}
     }else if(strncmp(from, to, strlen(to)) =3D=3D 0){
 	p =3D from + strlen(from);
 	while(1){
 	    while(p >=3D from && *p !=3D '/') p--;
-	    if(p =3D=3D from) {
-		r->next =3D path; /* XXX */
+	    if(p =3D=3D from)
 		return KRB5KDC_ERR_POLICY;
-	    }
+
 	    if(strncmp(to, from, p - from) =3D=3D 0)
 		break;
 	    tmp =3D calloc(1, sizeof(*tmp));
-	    if(tmp =3D=3D NULL){
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
+	    if(tmp =3D=3D NULL)
+		return krb5_enomem(context);
+	    tmp->next =3D r->next;
+	    r->next =3D tmp;
+	    tmp->realm =3D malloc(p - from + 1);
+	    if(tmp->realm =3D=3D NULL){
+		r->next =3D tmp->next;
+		free(tmp);
+		return krb5_enomem(context);
 	    }
-	    tmp->next =3D path;
-	    path =3D tmp;
-	    path->realm =3D malloc(p - from + 1);
-	    if(path->realm =3D=3D NULL){
-		r->next =3D path; /* XXX */
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
-	    }
-	    memcpy(path->realm, from, p - from);
-	    path->realm[p - from] =3D '\0';
+	    memcpy(tmp->realm, from, p - from);
+	    tmp->realm[p - from] =3D '\0';
 	    p--;
 	}
     } else {
-	krb5_clear_error_string (context);
+	krb5_clear_error_message (context);
 	return KRB5KDC_ERR_POLICY;
     }
-    r->next =3D path;
-   =20
+
     return 0;
 }
=20
 static int
 make_paths(krb5_context context,
-	   struct tr_realm *realms, const char *client_realm,=20
+	   struct tr_realm *realms, const char *client_realm,
 	   const char *server_realm)
 {
     struct tr_realm *r;
@@ -186,8 +177,7 @@
 	    tmp =3D realloc(r->realm, len);
 	    if(tmp =3D=3D NULL){
 		free_realms(realms);
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
+		return krb5_enomem(context);
 	    }
 	    r->realm =3D tmp;
 	    strlcat(r->realm, prev_realm, len);
@@ -200,8 +190,7 @@
 	    tmp =3D malloc(len);
 	    if(tmp =3D=3D NULL){
 		free_realms(realms);
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
+		return krb5_enomem(context);
 	    }
 	    strlcpy(tmp, prev_realm, len);
 	    strlcat(tmp, r->realm, len);
@@ -285,17 +274,14 @@
 	}
 	if(tr[i] =3D=3D ','){
 	    tmp =3D malloc(tr + i - start + 1);
-	    if(tmp =3D=3D NULL){
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
-	    }
+	    if(tmp =3D=3D NULL)
+		return krb5_enomem(context);
 	    memcpy(tmp, start, tr + i - start);
 	    tmp[tr + i - start] =3D '\0';
 	    r =3D make_realm(tmp);
 	    if(r =3D=3D NULL){
 		free_realms(*realms);
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
+		return krb5_enomem(context);
 	    }
 	    *realms =3D append_realm(*realms, r);
 	    start =3D tr + i + 1;
@@ -304,32 +290,30 @@
     tmp =3D malloc(tr + i - start + 1);
     if(tmp =3D=3D NULL){
 	free(*realms);
-	krb5_set_error_string (context, "malloc: out of memory");
-	return ENOMEM;
+	return krb5_enomem(context);
     }
     memcpy(tmp, start, tr + i - start);
     tmp[tr + i - start] =3D '\0';
     r =3D make_realm(tmp);
     if(r =3D=3D NULL){
 	free_realms(*realms);
-	krb5_set_error_string (context, "malloc: out of memory");
-	return ENOMEM;
+	return krb5_enomem(context);
     }
     *realms =3D append_realm(*realms, r);
-   =20
+
     return 0;
 }
=20
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_domain_x500_decode(krb5_context context,
-			krb5_data tr, char ***realms, int *num_realms,=20
+			krb5_data tr, char ***realms, unsigned int *num_realms,
 			const char *client_realm, const char *server_realm)
 {
     struct tr_realm *r =3D NULL;
     struct tr_realm *p, **q;
     int ret;
-   =20
+
     if(tr.length =3D=3D 0) {
 	*realms =3D NULL;
 	*num_realms =3D 0;
@@ -340,39 +324,37 @@
     ret =3D decode_realms(context, tr.data, tr.length, &r);
     if(ret)
 	return ret;
-   =20
+
     /* apply prefix rule */
     ret =3D expand_realms(context, r, client_realm);
     if(ret)
 	return ret;
-   =20
+
     ret =3D make_paths(context, r, client_realm, server_realm);
     if(ret)
 	return ret;
-   =20
+
     /* remove empty components and count realms */
-    q =3D &r;
     *num_realms =3D 0;
-    for(p =3D r; p; ){
-	if(p->realm[0] =3D=3D '\0'){
+    for(q =3D &r; *q; ){
+	if((*q)->realm[0] =3D=3D '\0'){
+	    p =3D *q;
+	    *q =3D (*q)->next;
 	    free(p->realm);
-	    *q =3D p->next;
 	    free(p);
-	    p =3D *q;
 	}else{
-	    q =3D &p->next;
-	    p =3D p->next;
+	    q =3D &(*q)->next;
 	    (*num_realms)++;
 	}
     }
-    if (*num_realms < 0 || *num_realms + 1 > UINT_MAX/sizeof(**realms))
+    if (*num_realms + 1 > UINT_MAX/sizeof(**realms))
 	return ERANGE;
=20
     {
 	char **R;
 	R =3D malloc((*num_realms + 1) * sizeof(*R));
 	if (R =3D=3D NULL)
-	    return ENOMEM;
+	    return krb5_enomem(context);
 	*realms =3D R;
 	while(r){
 	    *R++ =3D r->realm;
@@ -384,12 +366,13 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_domain_x500_encode(char **realms, int num_realms, krb5_data *encoding)
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_domain_x500_encode(char **realms, unsigned int num_realms,
+			krb5_data *encoding)
 {
     char *s =3D NULL;
     int len =3D 0;
-    int i;
+    unsigned int i;
     krb5_data_zero(encoding);
     if (num_realms =3D=3D 0)
 	return 0;
@@ -404,7 +387,7 @@
 	return ENOMEM;
     *s =3D '\0';
     for(i =3D 0; i < num_realms; i++){
-	if(i && i < num_realms - 1)
+	if(i)
 	    strlcat(s, ",", len + 1);
 	if(realms[i][0] =3D=3D '/')
 	    strlcat(s, " ", len + 1);
@@ -415,25 +398,25 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_check_transited(krb5_context context,
 		     krb5_const_realm client_realm,
 		     krb5_const_realm server_realm,
 		     krb5_realm *realms,
-		     int num_realms,
+		     unsigned int num_realms,
 		     int *bad_realm)
 {
     char **tr_realms;
     char **p;
-    int i;
+    size_t i;
=20
     if(num_realms =3D=3D 0)
 	return 0;
-   =20
-    tr_realms =3D krb5_config_get_strings(context, NULL,=20
-					"capaths",=20
-					client_realm,=20
-					server_realm,=20
+
+    tr_realms =3D krb5_config_get_strings(context, NULL,
+					"capaths",
+					client_realm,
+					server_realm,
 					NULL);
     for(i =3D 0; i < num_realms; i++) {
 	for(p =3D tr_realms; p && *p; p++) {
@@ -442,8 +425,10 @@
 	}
 	if(p =3D=3D NULL || *p =3D=3D NULL) {
 	    krb5_config_free_strings(tr_realms);
-	    krb5_set_error_string (context, "no transit through realm %s",
-				   realms[i]);
+	    krb5_set_error_message (context, KRB5KRB_AP_ERR_ILL_CR_TKT,
+				    N_("no transit allowed "
+				       "through realm %s", ""),
+				    realms[i]);
 	    if(bad_realm)
 		*bad_realm =3D i;
 	    return KRB5KRB_AP_ERR_ILL_CR_TKT;
@@ -453,17 +438,17 @@
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_check_transited_realms(krb5_context context,
-			    const char *const *realms,=20
-			    int num_realms,=20
+			    const char *const *realms,
+			    unsigned int num_realms,
 			    int *bad_realm)
 {
-    int i;
+    size_t i;
     int ret =3D 0;
-    char **bad_realms =3D krb5_config_get_strings(context, NULL,=20
-						"libdefaults",=20
-						"transited_realms_reject",=20
+    char **bad_realms =3D krb5_config_get_strings(context, NULL,
+						"libdefaults",
+						"transited_realms_reject",
 						NULL);
     if(bad_realms =3D=3D NULL)
 	return 0;
@@ -472,9 +457,11 @@
 	char **p;
 	for(p =3D bad_realms; *p; p++)
 	    if(strcmp(*p, realms[i]) =3D=3D 0) {
-		krb5_set_error_string (context, "no transit through realm %s",
-				       *p);
 		ret =3D KRB5KRB_AP_ERR_ILL_CR_TKT;
+		krb5_set_error_message (context, ret,
+					N_("no transit allowed "
+					   "through realm %s", ""),
+					*p);
 		if(bad_realm)
 		    *bad_realm =3D i;
 		break;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/verify_in=
it.c
--- a/head/crypto/heimdal/lib/krb5/verify_init.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/verify_init.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,47 +1,45 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: verify_init.c 15555 2005-07-06 00:48:16Z lha $");
-
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_init_creds_opt_init(krb5_verify_init_creds_opt *options)
 {
     memset (options, 0, sizeof(*options));
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_init_creds_opt_set_ap_req_nofail(krb5_verify_init_creds_opt *o=
ptions,
 					     int ap_req_nofail)
 {
@@ -69,7 +67,7 @@
 	return TRUE;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_init_creds(krb5_context context,
 		       krb5_creds *creds,
 		       krb5_principal ap_req_server,
@@ -92,8 +90,8 @@
=20
 	if (gethostname (local_hostname, sizeof(local_hostname)) < 0) {
 	    ret =3D errno;
-	    krb5_set_error_string (context, "gethostname: %s",
-				   strerror(ret));
+	    krb5_set_error_message (context, ret, "gethostname: %s",
+				    strerror(ret));
 	    return ret;
 	}
=20
@@ -117,7 +115,8 @@
     if (ccache && *ccache)
 	local_ccache =3D *ccache;
     else {
-	ret =3D krb5_cc_gen_new (context, &krb5_mcc_ops, &local_ccache);
+	ret =3D krb5_cc_new_unique(context, krb5_cc_type_memory,
+				 NULL, &local_ccache);
 	if (ret)
 	    goto cleanup;
 	ret =3D krb5_cc_initialize (context,
@@ -159,7 +158,7 @@
 				NULL,
 				creds,
 				&req);
-   =20
+
     krb5_auth_con_free (context, auth_context);
     auth_context =3D NULL;
=20
@@ -197,3 +196,48 @@
=20
     return ret;
 }
+
+/**
+ * Validate the newly fetch credential, see also krb5_verify_init_creds().
+ *
+ * @param context a Kerberos 5 context
+ * @param creds the credentials to verify
+ * @param client the client name to match up
+ * @param ccache the credential cache to use
+ * @param service a service name to use, used with
+ *        krb5_sname_to_principal() to build a hostname to use to
+ *        verify.
+ *
+ * @ingroup krb5_ccache
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_get_validated_creds(krb5_context context,
+			 krb5_creds *creds,
+			 krb5_principal client,
+			 krb5_ccache ccache,
+			 char *service)
+{
+    krb5_verify_init_creds_opt vopt;
+    krb5_principal server;
+    krb5_error_code ret;
+
+    if (krb5_principal_compare(context, creds->client, client) !=3D TRUE) {
+	krb5_set_error_message(context, KRB5_PRINC_NOMATCH,
+			       N_("Validation credentials and client "
+				  "doesn't match", ""));
+	return KRB5_PRINC_NOMATCH;
+    }
+
+    ret =3D krb5_sname_to_principal (context, NULL, service,
+				   KRB5_NT_SRV_HST, &server);
+    if(ret)
+	return ret;
+
+    krb5_verify_init_creds_opt_init(&vopt);
+
+    ret =3D krb5_verify_init_creds(context, creds, server, NULL, NULL, &vo=
pt);
+    krb5_free_principal(context, server);
+
+    return ret;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/verify_kr=
b5_conf.8
--- a/head/crypto/heimdal/lib/krb5/verify_krb5_conf.8	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/verify_krb5_conf.8	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2000 - 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2000 - 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $Id: verify_krb5_conf.8 14375 2004-12-08 17:52:41Z lha $
+.\" $Id$
 .\"
 .Dd December  8, 2004
 .Dt VERIFY_KRB5_CONF 8
@@ -45,7 +45,7 @@
 reads the configuration file
 .Pa krb5.conf ,
 or the file given on the command line,
-and parses it, thereby verifying that the syntax is not correctly wrong.
+parses it, checking verifying that the syntax is not correctly wrong.
 .Pp
 If the file is syntactically correct,
 .Nm
@@ -79,7 +79,7 @@
 is confused.
 .It <path>: unknown entry
 Means that <string> is not known by
-.Nm "" .
+.Nm .
 .El
 .Sh SEE ALSO
 .Xr krb5.conf 5
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/verify_kr=
b5_conf.c
--- a/head/crypto/heimdal/lib/krb5/verify_krb5_conf.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/verify_krb5_conf.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,41 +1,40 @@
 /*
- * Copyright (c) 1999 - 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include <getarg.h>
 #include <parse_bytes.h>
 #include <err.h>
-RCSID("$Id: verify_krb5_conf.c 22233 2007-12-08 21:43:37Z lha $");
=20
 /* verify krb5.conf */
=20
@@ -45,9 +44,9 @@
 static int warn_mit_syntax_flag =3D 0;
=20
 static struct getargs args[] =3D {
-    {"dumpconfig", 0,      arg_flag,       &dumpconfig_flag,=20
+    {"dumpconfig", 0,      arg_flag,       &dumpconfig_flag,
      "show the parsed config files", NULL },
-    {"warn-mit-syntax", 0, arg_flag,       &warn_mit_syntax_flag,=20
+    {"warn-mit-syntax", 0, arg_flag,       &warn_mit_syntax_flag,
      "show the parsed config files", NULL },
     {"version",	0,	arg_flag,	&version_flag,
      "print version", NULL },
@@ -88,11 +87,17 @@
 static int
 check_numeric(krb5_context context, const char *path, char *data)
 {
-    long int v;
+    long v;
     char *end;
     v =3D strtol(data, &end, 0);
+
+    if ((v =3D=3D LONG_MIN || v =3D=3D LONG_MAX) && errno !=3D 0) {
+	krb5_warnx(context, "%s: over/under flow for \"%s\"",
+		   path, data);
+	return 1;
+    }
     if(*end !=3D '\0') {
-	krb5_warnx(context, "%s: failed to parse \"%s\" as a number",=20
+	krb5_warnx(context, "%s: failed to parse \"%s\" as a number",
 		   path, data);
 	return 1;
     }
@@ -111,12 +116,12 @@
 	return 0;
     v =3D strtol(data, &end, 0);
     if(*end !=3D '\0') {
-	krb5_warnx(context, "%s: failed to parse \"%s\" as a boolean",=20
+	krb5_warnx(context, "%s: failed to parse \"%s\" as a boolean",
 		   path, data);
 	return 1;
     }
     if(v !=3D 0 && v !=3D 1)
-	krb5_warnx(context, "%s: numeric value \"%s\" is treated as \"true\"",=20
+	krb5_warnx(context, "%s: numeric value \"%s\" is treated as \"true\"",
 		   path, data);
     return 0;
 }
@@ -130,7 +135,7 @@
        strcasecmp(data, "local") =3D=3D 0)
 	return 0;
=20
-    krb5_warnx(context, "%s: didn't contain a valid option `%s'",=20
+    krb5_warnx(context, "%s: didn't contain a valid option `%s'",
 	       path, data);
     return 1;
 }
@@ -155,7 +160,7 @@
     hints.ai_canonname =3D NULL;
     hints.ai_addr =3D NULL;
     hints.ai_next =3D NULL;
-   =20
+
     /* XXX data could be a list of hosts that this code can't handle */
     /* XXX copied from krbhst.c */
     if(strncmp(p, "http://", 7) =3D=3D 0){
@@ -191,7 +196,7 @@
 	char *end;
 	int tmp =3D strtol(p, &end, 0);
 	if(end =3D=3D p) {
-	    krb5_warnx(context, "%s: failed to parse port number in %s",=20
+	    krb5_warnx(context, "%s: failed to parse port number in %s",
 		       path, data);
 	    return 1;
 	}
@@ -304,7 +309,7 @@
 	}
 	p++;
     }
-    if(strcmp(p, "STDERR") =3D=3D 0 ||=20
+    if(strcmp(p, "STDERR") =3D=3D 0 ||
        strcmp(p, "CONSOLE") =3D=3D 0 ||
        (strncmp(p, "FILE", 4) =3D=3D 0 && (p[4] =3D=3D ':' || p[4] =3D=3D =
'=3D')) ||
        (strncmp(p, "DEVICE", 6) =3D=3D 0 && p[6] =3D=3D '=3D'))
@@ -323,12 +328,12 @@
  	if(*facility =3D=3D '\0')
 	    strlcpy(facility, "AUTH", sizeof(facility));
 	if(find_value(severity, syslogvals) =3D=3D -1) {
-	    krb5_warnx(context, "%s: unknown syslog facility \"%s\"",=20
+	    krb5_warnx(context, "%s: unknown syslog facility \"%s\"",
 		       path, facility);
 	    ret++;
 	}
 	if(find_value(severity, syslogvals) =3D=3D -1) {
-	    krb5_warnx(context, "%s: unknown syslog severity \"%s\"",=20
+	    krb5_warnx(context, "%s: unknown syslog severity \"%s\"",
 		       path, severity);
 	    ret++;
 	}
@@ -344,6 +349,7 @@
     const char *name;
     int type;
     void *check_data;
+    int deprecated;
 };
=20
 struct entry all_strings[] =3D {
@@ -365,7 +371,8 @@
=20
 struct entry libdefaults_entries[] =3D {
     { "accept_null_addresses", krb5_config_string, check_boolean },
-    { "capath", krb5_config_list, all_strings },
+    { "allow_weak_crypto", krb5_config_string, check_boolean },
+    { "capath", krb5_config_list, all_strings, 1 },
     { "check_pac", krb5_config_string, check_boolean },
     { "clockskew", krb5_config_string, check_time },
     { "date_format", krb5_config_string, NULL },
@@ -395,7 +402,7 @@
     { "maxretries", krb5_config_string, check_numeric },
     { "scan_interfaces", krb5_config_string, check_boolean },
     { "srv_lookup", krb5_config_string, check_boolean },
-    { "srv_try_txt", krb5_config_string, check_boolean },=20
+    { "srv_try_txt", krb5_config_string, check_boolean },
     { "ticket_lifetime", krb5_config_string, check_time },
     { "time_format", krb5_config_string, NULL },
     { "transited_realms_reject", krb5_config_string, NULL },
@@ -501,7 +508,7 @@
     { "allow-null-ticket-addresses", krb5_config_string, check_boolean },
     { "allow-anonymous", krb5_config_string, check_boolean },
     { "v4_realm", krb5_config_string, NULL },
-    { "enable-kaserver", krb5_config_string, check_boolean },
+    { "enable-kaserver", krb5_config_string, check_boolean, 1 },
     { "encode_as_rep_as_tgs_rep", krb5_config_string, check_boolean },
     { "kdc_warn_pwexpire", krb5_config_string, check_time },
     { "use_2b", krb5_config_list, NULL },
@@ -571,17 +578,19 @@
=20
=20
 static int
-check_section(krb5_context context, const char *path, krb5_config_section =
*cf,=20
+check_section(krb5_context context, const char *path, krb5_config_section =
*cf,
 	      struct entry *entries)
 {
     int error =3D 0;
     krb5_config_section *p;
     struct entry *e;
-   =20
+
     char *local;
-   =20
+
     for(p =3D cf; p !=3D NULL; p =3D p->next) {
-	asprintf(&local, "%s/%s", path, p->name);
+	local =3D NULL;
+	if (asprintf(&local, "%s/%s", path, p->name) < 0 || local =3D=3D NULL)
+	    errx(1, "out of memory");
 	for(e =3D entries; e->name !=3D NULL; e++) {
 	    if(*e->name =3D=3D '\0' || strcmp(e->name, p->name) =3D=3D 0) {
 		if(e->type !=3D p->type) {
@@ -592,6 +601,10 @@
 		} else if(p->type =3D=3D krb5_config_list && e->check_data !=3D NULL) {
 		    error |=3D check_section(context, local, p->u.list, e->check_data);
 		}
+		if(e->deprecated) {
+		    krb5_warnx(context, "%s: is a deprecated entry", local);
+		    error |=3D 1;
+		}
 		break;
 	    }
 	}
@@ -646,7 +659,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -671,6 +684,6 @@
=20
     if(dumpconfig_flag)
 	dumpconfig(0, tmp_cf);
-   =20
+
     return check_section(context, "", tmp_cf, toplevel_sections);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/verify_us=
er.c
--- a/head/crypto/heimdal/lib/krb5/verify_user.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/krb5/verify_user.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: verify_user.c 19078 2006-11-20 18:12:41Z lha $");
-
 static krb5_error_code
 verify_common (krb5_context context,
 	       krb5_principal principal,
@@ -90,7 +88,7 @@
  * As a side effect, fresh tickets are obtained and stored in `ccache'.
  */
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_init(krb5_verify_opt *opt)
 {
     memset(opt, 0, sizeof(*opt));
@@ -98,49 +96,50 @@
     opt->service =3D "host";
 }
=20
-int KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION int KRB5_LIB_CALL
 krb5_verify_opt_alloc(krb5_context context, krb5_verify_opt **opt)
 {
     *opt =3D calloc(1, sizeof(**opt));
     if ((*opt) =3D=3D NULL) {
-	krb5_set_error_string(context, "malloc: out of memory");
+	krb5_set_error_message(context, ENOMEM,
+			       N_("malloc: out of memory", ""));
 	return ENOMEM;
     }
     krb5_verify_opt_init(*opt);
     return 0;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_free(krb5_verify_opt *opt)
 {
     free(opt);
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_ccache(krb5_verify_opt *opt, krb5_ccache ccache)
 {
     opt->ccache =3D ccache;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_keytab(krb5_verify_opt *opt, krb5_keytab keytab)
 {
     opt->keytab =3D keytab;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_secure(krb5_verify_opt *opt, krb5_boolean secure)
 {
     opt->secure =3D secure;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_service(krb5_verify_opt *opt, const char *service)
 {
     opt->service =3D service;
 }
=20
-void KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION void KRB5_LIB_CALL
 krb5_verify_opt_set_flags(krb5_verify_opt *opt, unsigned int flags)
 {
     opt->flags |=3D flags;
@@ -160,8 +159,8 @@
     ret =3D krb5_get_init_creds_opt_alloc (context, &opt);
     if (ret)
 	return ret;
-    krb5_get_init_creds_opt_set_default_flags(context, NULL,=20
-					      krb5_principal_get_realm(context, principal),=20
+    krb5_get_init_creds_opt_set_default_flags(context, NULL,
+					      krb5_principal_get_realm(context, principal),
 					      opt);
     ret =3D krb5_get_init_creds_password (context,
 					&cred,
@@ -176,13 +175,13 @@
     if(ret)
 	return ret;
 #define OPT(V, D) ((vopt && (vopt->V)) ? (vopt->V) : (D))
-    return verify_common (context, principal, OPT(ccache, NULL),=20
-			  OPT(keytab, NULL), vopt ? vopt->secure : TRUE,=20
+    return verify_common (context, principal, OPT(ccache, NULL),
+			  OPT(keytab, NULL), vopt ? vopt->secure : TRUE,
 			  OPT(service, "host"), cred);
 #undef OPT
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verify_user_opt(krb5_context context,
 		     krb5_principal principal,
 		     const char *password,
@@ -196,18 +195,14 @@
 	if (ret)
 	    return ret;
 	ret =3D KRB5_CONFIG_NODEFREALM;
-=09
+
 	for (r =3D realms; *r !=3D NULL && ret !=3D 0; ++r) {
-	    char *tmp =3D strdup (*r);
-	   =20
-	    if (tmp =3D=3D NULL) {
+	    ret =3D krb5_principal_set_realm(context, principal, *r);
+	    if (ret) {
 		krb5_free_host_realm (context, realms);
-		krb5_set_error_string (context, "malloc: out of memory");
-		return ENOMEM;
+		return ret;
 	    }
-	    free (*krb5_princ_realm (context, principal));
-	    krb5_princ_set_realm (context, principal, &tmp);
-	   =20
+
 	    ret =3D verify_user_opt_int(context, principal, password, opt);
 	}
 	krb5_free_host_realm (context, realms);
@@ -220,8 +215,8 @@
=20
 /* compat function that calls above */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_verify_user(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_user(krb5_context context,
 		 krb5_principal principal,
 		 krb5_ccache ccache,
 		 const char *password,
@@ -229,13 +224,13 @@
 		 const char *service)
 {
     krb5_verify_opt opt;
-   =20
+
     krb5_verify_opt_init(&opt);
-   =20
+
     krb5_verify_opt_set_ccache(&opt, ccache);
     krb5_verify_opt_set_secure(&opt, secure);
     krb5_verify_opt_set_service(&opt, service);
-   =20
+
     return krb5_verify_user_opt(context, principal, password, &opt);
 }
=20
@@ -244,8 +239,8 @@
  * ignored and all the local realms are tried.
  */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_verify_user_lrealm(krb5_context context,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verify_user_lrealm(krb5_context context,
 			krb5_principal principal,
 			krb5_ccache ccache,
 			const char *password,
@@ -253,13 +248,13 @@
 			const char *service)
 {
     krb5_verify_opt opt;
-   =20
+
     krb5_verify_opt_init(&opt);
-   =20
+
     krb5_verify_opt_set_ccache(&opt, ccache);
     krb5_verify_opt_set_secure(&opt, secure);
     krb5_verify_opt_set_service(&opt, service);
     krb5_verify_opt_set_flags(&opt, KRB5_VERIFY_LREALMS);
-   =20
+
     return krb5_verify_user_opt(context, principal, password, &opt);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/version-s=
cript.map
--- a/head/crypto/heimdal/lib/krb5/version-script.map	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/krb5/version-script.map	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,6 +1,4 @@
-# $Id$
-
-HEIMDAL_KRB5_1.0 {
+HEIMDAL_KRB5_2.0 {
 	global:
 		krb524_convert_creds_kdc;
 		krb524_convert_creds_kdc_ccache;
@@ -22,6 +20,7 @@
 		krb5_address_order;
 		krb5_address_prefixlen_boundary;
 		krb5_address_search;
+		krb5_allow_weak_crypto;
 		krb5_aname_to_localname;
 		krb5_anyaddr;
 		krb5_appdefault_boolean;
@@ -41,6 +40,7 @@
 		krb5_auth_con_getlocalseqnumber;
 		krb5_auth_con_getlocalsubkey;
 		krb5_auth_con_getrcache;
+		krb5_auth_con_getremoteseqnumber;
 		krb5_auth_con_getremotesubkey;
 		krb5_auth_con_init;
 		krb5_auth_con_removeflags;
@@ -58,7 +58,6 @@
 		krb5_auth_con_setuserkey;
 		krb5_auth_getremoteseqnumber;
 		krb5_build_ap_req;
-		krb5_build_authenticator;
 		krb5_build_principal;
 		krb5_build_principal_ext;
 		krb5_build_principal_va;
@@ -88,13 +87,17 @@
 		krb5_cc_clear_mcred;
 		krb5_cc_close;
 		krb5_cc_copy_cache;
-		krb5_cc_copy_cache_match;
+		krb5_cc_copy_match_f;
 		krb5_cc_default;
 		krb5_cc_default_name;
 		krb5_cc_destroy;
 		krb5_cc_end_seq_get;
 		krb5_cc_gen_new;
+		krb5_cc_get_config;
+		krb5_cc_get_friendly_name;
 		krb5_cc_get_full_name;
+		krb5_cc_get_kdc_offset;
+		krb5_cc_get_lifetime;
 		krb5_cc_get_name;
 		krb5_cc_get_ops;
 		krb5_cc_get_prefix_ops;
@@ -102,6 +105,7 @@
 		krb5_cc_get_type;
 		krb5_cc_get_version;
 		krb5_cc_initialize;
+		krb5_cc_last_change_time;
 		krb5_cc_move;
 		krb5_cc_new_unique;
 		krb5_cc_next_cred;
@@ -110,10 +114,15 @@
 		krb5_cc_remove_cred;
 		krb5_cc_resolve;
 		krb5_cc_retrieve_cred;
+		krb5_cc_set_config;
 		krb5_cc_set_default_name;
 		krb5_cc_set_flags;
+		krb5_cc_set_kdc_offset;
 		krb5_cc_start_seq_get;
 		krb5_cc_store_cred;
+		krb5_cc_support_switch;
+		krb5_cc_switch;
+ 		krb5_cc_set_friendly_name;
 		krb5_change_password;
 		krb5_check_transited;
 		krb5_check_transited_realms;
@@ -122,19 +131,19 @@
 		krb5_checksum_is_collision_proof;
 		krb5_checksum_is_keyed;
 		krb5_checksumsize;
+		krb5_cksumtype_to_enctype;
 		krb5_cksumtype_valid;
 		krb5_clear_error_string;
+		krb5_clear_error_message;
 		krb5_closelog;
 		krb5_compare_creds;
 		krb5_config_file_free;
 		krb5_config_free_strings;
-		krb5_config_get;
 		krb5_config_get_bool;
 		krb5_config_get_bool_default;
 		krb5_config_get_int;
 		krb5_config_get_int_default;
 		krb5_config_get_list;
-		krb5_config_get_next;
 		krb5_config_get_string;
 		krb5_config_get_string_default;
 		krb5_config_get_strings;
@@ -143,13 +152,11 @@
 		krb5_config_parse_file;
 		krb5_config_parse_file_multi;
 		krb5_config_parse_string_multi;
-		krb5_config_vget;
 		krb5_config_vget_bool;
 		krb5_config_vget_bool_default;
 		krb5_config_vget_int;
 		krb5_config_vget_int_default;
 		krb5_config_vget_list;
-		krb5_config_vget_next;
 		krb5_config_vget_string;
 		krb5_config_vget_string_default;
 		krb5_config_vget_strings;
@@ -160,6 +167,7 @@
 		krb5_copy_checksum;
 		krb5_copy_creds;
 		krb5_copy_creds_contents;
+		krb5_copy_context;
 		krb5_copy_data;
 		krb5_copy_host_realm;
 		krb5_copy_keyblock;
@@ -167,7 +175,9 @@
 		krb5_copy_principal;
 		krb5_copy_ticket;
 		krb5_create_checksum;
+		krb5_create_checksum_iov;
 		krb5_crypto_destroy;
+		krb5_crypto_fx_cf2;
 		krb5_crypto_get_checksum_type;
 		krb5_crypto_getblocksize;
 		krb5_crypto_getconfoundersize;
@@ -177,7 +187,13 @@
 		krb5_crypto_overhead;
 		krb5_crypto_prf;
 		krb5_crypto_prf_length;
+		krb5_crypto_length;
+		krb5_crypto_length_iov;
+		krb5_decrypt_iov_ivec;
+		krb5_encrypt_iov_ivec;
+		krb5_enomem;
 		krb5_data_alloc;
+		krb5_data_ct_cmp;
 		krb5_data_cmp;
 		krb5_data_copy;
 		krb5_data_free;
@@ -241,6 +257,7 @@
 		krb5_encrypt;
 		krb5_encrypt_EncryptedData;
 		krb5_encrypt_ivec;
+		krb5_enctype_enable;
 		krb5_enctype_disable;
 		krb5_enctype_keybits;
 		krb5_enctype_keysize;
@@ -268,9 +285,11 @@
 		krb5_free_creds_contents;
 		krb5_free_data;
 		krb5_free_data_contents;
+		krb5_free_default_realm;
 		krb5_free_error;
 		krb5_free_error_contents;
 		krb5_free_error_string;
+		krb5_free_error_message;
 		krb5_free_host_realm;
 		krb5_free_kdc_rep;
 		krb5_free_keyblock;
@@ -279,6 +298,7 @@
 		krb5_free_principal;
 		krb5_free_salt;
 		krb5_free_ticket;
+		krb5_free_unparsed_name;
 		krb5_fwd_tgt_creds;
 		krb5_generate_random_block;
 		krb5_generate_random_keyblock;
@@ -314,6 +334,7 @@
 		krb5_get_host_realm;
 		krb5_get_ignore_addresses;
 		krb5_get_in_cred;
+		krb5_cccol_last_change_time;
 		krb5_get_in_tkt;
 		krb5_get_in_tkt_with_keytab;
 		krb5_get_in_tkt_with_password;
@@ -336,6 +357,7 @@
 		krb5_get_init_creds_opt_set_pac_request;
 		krb5_get_init_creds_opt_set_pkinit;
 		krb5_get_init_creds_opt_set_preauth_list;
+		krb5_get_init_creds_opt_set_process_last_req;
 		krb5_get_init_creds_opt_set_proxiable;
 		krb5_get_init_creds_opt_set_renew_life;
 		krb5_get_init_creds_opt_set_salt;
@@ -363,9 +385,11 @@
 		krb5_hmac;
 		krb5_init_context;
 		krb5_init_ets;
-		krb5_init_etype;
 		krb5_initlog;
+		krb5_is_config_principal;
 		krb5_is_thread_safe;
+		krb5_kcm_call;
+		krb5_kcm_storage_request;
 		krb5_kerberos_enctypes;
 		krb5_keyblock_get_enctype;
 		krb5_keyblock_init;
@@ -390,12 +414,14 @@
 		krb5_kt_default;
 		krb5_kt_default_modify_name;
 		krb5_kt_default_name;
+		krb5_kt_destroy;
 		krb5_kt_end_seq_get;
 		krb5_kt_free_entry;
 		krb5_kt_get_entry;
 		krb5_kt_get_full_name;
 		krb5_kt_get_name;
 		krb5_kt_get_type;
+		krb5_kt_have_content;
 		krb5_kt_next_entry;
 		krb5_kt_read_service_key;
 		krb5_kt_register;
@@ -451,18 +477,23 @@
 		krb5_parse_nametype;
 		krb5_passwd_result_to_string;
 		krb5_password_key_proc;
+		krb5_get_permitted_enctypes;
 		krb5_plugin_register;
 		krb5_prepend_config_files;
 		krb5_prepend_config_files_default;
+		krb5_prepend_error_message;
 		krb5_princ_realm;
 		krb5_princ_set_realm;
 		krb5_principal_compare;
 		krb5_principal_compare_any_realm;
 		krb5_principal_get_comp_string;
+		krb5_principal_get_num_comp;
 		krb5_principal_get_realm;
 		krb5_principal_get_type;
 		krb5_principal_match;
+		krb5_principal_set_realm;
 		krb5_principal_set_type;
+		krb5_principal_is_krbtgt;
 		krb5_print_address;
 		krb5_program_setup;
 		krb5_prompter_posix;
@@ -540,10 +571,13 @@
 		krb5_set_default_in_tkt_etypes;
 		krb5_set_default_realm;
 		krb5_set_dns_canonicalize_hostname;
+		krb5_set_error_message;
 		krb5_set_error_string;
 		krb5_set_extra_addresses;
 		krb5_set_fcache_version;
+		krb5_set_home_dir_access;
 		krb5_set_ignore_addresses;
+		krb5_set_kdc_sec_offset;
 		krb5_set_max_time_skew;
 		krb5_set_password;
 		krb5_set_password_using_ccache;
@@ -565,13 +599,16 @@
 		krb5_storage_from_mem;
 		krb5_storage_from_readonly_mem;
 		krb5_storage_get_byteorder;
+		krb5_storage_get_eof_code;
 		krb5_storage_is_flags;
 		krb5_storage_read;
 		krb5_storage_seek;
 		krb5_storage_set_byteorder;
 		krb5_storage_set_eof_code;
 		krb5_storage_set_flags;
+		krb5_storage_set_max_alloc;
 		krb5_storage_to_data;
+		krb5_storage_truncate;
 		krb5_storage_write;
 		krb5_store_address;
 		krb5_store_addrs;
@@ -620,6 +657,7 @@
 		krb5_verify_ap_req;
 		krb5_verify_authenticator_checksum;
 		krb5_verify_checksum;
+		krb5_verify_checksum_iov;
 		krb5_verify_init_creds;
 		krb5_verify_init_creds_opt_init;
 		krb5_verify_init_creds_opt_set_ap_req_nofail;
@@ -638,6 +676,8 @@
 		krb5_verrx;
 		krb5_vlog;
 		krb5_vlog_msg;
+		krb5_vprepend_error_message;
+		krb5_vset_error_message;
 		krb5_vset_error_string;
 		krb5_vwarn;
 		krb5_vwarnx;
@@ -647,6 +687,9 @@
 		krb5_write_priv_message;
 		krb5_write_safe_message;
 		krb5_xfree;
+		krb5_cccol_cursor_new;
+		krb5_cccol_cursor_next;
+		krb5_cccol_cursor_free;
=20
 		# com_err error tables
 		initialize_krb5_error_table_r;
@@ -662,22 +705,27 @@
 		krb5_mcc_ops;
 		krb5_acc_ops;
 		krb5_fcc_ops;
+		krb5_scc_ops;
 		krb5_kcm_ops;
-		krb4_fkt_ops;
 		krb5_wrfkt_ops;
 		krb5_mkt_ops;
-		krb5_fkt_ops;
 		krb5_akf_ops;
-		krb5_srvtab_fkt_ops;
 		krb5_any_ops;
 		heimdal_version;
 		heimdal_long_version;
 		krb5_config_file;
 		krb5_defkeyname;
+		krb5_cc_type_api;
+		krb5_cc_type_file;
+		krb5_cc_type_memory;
+		krb5_cc_type_kcm;
+		krb5_cc_type_scc;
=20
 		# Shared with GSSAPI krb5
 		_krb5_crc_init_table;	=09
 		_krb5_crc_update;	=09
+		_krb5_get_krbtgt;
+		_krb5_build_authenticator;
=20
 		# V4 compat glue
 		_krb5_krb_tf_setup;
@@ -694,24 +742,28 @@
 		_krb5_krb_cr_err_reply;
=20
 		# Shared with libkdc
+		_krb5_AES_string_to_default_iterator;
+		_krb5_dh_group_ok;
+		_krb5_get_host_realm_int;
+		_krb5_get_int;
+		_krb5_pac_sign;
+		_krb5_parse_moduli;
+		_krb5_pk_kdf;
+		_krb5_pk_load_id;
+		_krb5_pk_mk_ContentInfo;
+		_krb5_pk_octetstring2key;
+		_krb5_plugin_find;
+		_krb5_plugin_free;
+		_krb5_plugin_get_next;
+		_krb5_plugin_get_symbol;
+		_krb5_principal2principalname;
 		_krb5_principalname2krb5_principal;
-		_krb5_principal2principalname;
+		_krb5_put_int;
 		_krb5_s4u2self_to_checksumdata;
-		_krb5_put_int;
-		_krb5_get_int;
-		_krb5_pk_load_id;
-		_krb5_parse_moduli;
-		_krb5_pk_mk_ContentInfo;
-		_krb5_dh_group_ok;
-		_krb5_pk_octetstring2key;
-		_krb5_pk_allow_proxy_certificate;
-		_krb5_pac_sign;
-		_krb5_plugin_find;
-		_krb5_plugin_get_symbol;
-		_krb5_plugin_get_next;
-		_krb5_plugin_free;
-		_krb5_AES_string_to_default_iterator;
-		_krb5_get_host_realm_int;
+
+		# kinit helper
+		krb5_get_init_creds_opt_set_pkinit_user_certs;
+		krb5_pk_enterprise_cert;
=20
 		# testing
 		_krb5_aes_cts_encrypt;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/version.c
--- a/head/crypto/heimdal/lib/krb5/version.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/version.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,43 +1,39 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: version.c 7464 1999-12-02 17:05:13Z joda $");
-
 /* this is just to get a version stamp in the library file */
=20
-#define heimdal_version __heimdal_version
-#define heimdal_long_version __heimdal_long_version
 #include "version.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/warn.c
--- a/head/crypto/heimdal/lib/krb5/warn.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/krb5/warn.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,88 +1,81 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
 #include <err.h>
=20
-RCSID("$Id: warn.c 19086 2006-11-21 08:06:40Z lha $");
-
-static krb5_error_code _warnerr(krb5_context context, int do_errtext,=20
+static krb5_error_code _warnerr(krb5_context context, int do_errtext,
 	 krb5_error_code code, int level, const char *fmt, va_list ap)
 	__attribute__((__format__(__printf__, 5, 0)));
-=09
+
 static krb5_error_code
-_warnerr(krb5_context context, int do_errtext,=20
+_warnerr(krb5_context context, int do_errtext,
 	 krb5_error_code code, int level, const char *fmt, va_list ap)
 {
     char xfmt[7] =3D "";
     const char *args[2], **arg;
     char *msg =3D NULL;
-    char *err_str =3D NULL;
-   =20
+    const char *err_str =3D NULL;
+    krb5_error_code ret;
+
     args[0] =3D args[1] =3D NULL;
     arg =3D args;
     if(fmt){
 	strlcat(xfmt, "%s", sizeof(xfmt));
 	if(do_errtext)
 	    strlcat(xfmt, ": ", sizeof(xfmt));
-	vasprintf(&msg, fmt, ap);
-	if(msg =3D=3D NULL)
+	ret =3D vasprintf(&msg, fmt, ap);
+	if(ret < 0 || msg =3D=3D NULL)
 	    return ENOMEM;
 	*arg++ =3D msg;
     }
     if(context && do_errtext){
-	const char *err_msg;
-
 	strlcat(xfmt, "%s", sizeof(xfmt));
=20
-	err_str =3D krb5_get_error_string(context);
+	err_str =3D krb5_get_error_message(context, code);
 	if (err_str !=3D NULL) {
-	    *arg++ =3D err_str;
+	    *arg =3D err_str;
 	} else {
-	    err_msg =3D krb5_get_err_text(context, code);
-	    if (err_msg)
-		*arg++ =3D err_msg;
-	    else
-		*arg++ =3D "<unknown error>";
+	    *arg=3D "<unknown error>";
 	}
     }
-=09
+
     if(context && context->warn_dest)
 	krb5_log(context, context->warn_dest, level, xfmt, args[0], args[1]);
     else
 	warnx(xfmt, args[0], args[1]);
     free(msg);
-    free(err_str);
+    krb5_free_error_message(context, err_str);
     return 0;
 }
=20
@@ -96,16 +89,38 @@
 #undef __attribute__
 #define __attribute__(X)
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_vwarn(krb5_context context, krb5_error_code code,=20
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure.
+ *
+ * @param context A Kerberos 5 context.
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vwarn(krb5_context context, krb5_error_code code,
 	   const char *fmt, va_list ap)
      __attribute__ ((format (printf, 3, 0)))
 {
     return _warnerr(context, 1, code, 1, fmt, ap);
 }
=20
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure.
+ *
+ * @param context A Kerberos 5 context.
+ * @param code error code of the last error
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_warn(krb5_context context, krb5_error_code code, const char *fmt, ...)
      __attribute__ ((format (printf, 3, 4)))
 {
@@ -113,14 +128,33 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Log a warning to the log, default stderr.
+ *
+ * @param context A Kerberos 5 context.
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vwarnx(krb5_context context, const char *fmt, va_list ap)
      __attribute__ ((format (printf, 2, 0)))
 {
     return _warnerr(context, 0, 0, 1, fmt, ap);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Log a warning to the log, default stderr.
+ *
+ * @param context A Kerberos 5 context.
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_warnx(krb5_context context, const char *fmt, ...)
      __attribute__ ((format (printf, 2, 3)))
 {
@@ -128,83 +162,185 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_verr(krb5_context context, int eval, krb5_error_code code,=20
+/**
+ * Log a warning to the log, default stderr, include bthe error from
+ * the last failure and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_verr(krb5_context context, int eval, krb5_error_code code,
 	  const char *fmt, va_list ap)
      __attribute__ ((noreturn, format (printf, 4, 0)))
 {
     _warnerr(context, 1, code, 0, fmt, ap);
     exit(eval);
+    UNREACHABLE(return 0);
 }
=20
+/**
+ * Log a warning to the log, default stderr, include bthe error from
+ * the last failure and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param code error code of the last error
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_err(krb5_context context, int eval, krb5_error_code code,=20
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_err(krb5_context context, int eval, krb5_error_code code,
 	 const char *fmt, ...)
      __attribute__ ((noreturn, format (printf, 4, 5)))
 {
     FUNC(1, code, 0);
     exit(eval);
+    UNREACHABLE(return 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Log a warning to the log, default stderr, and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_verrx(krb5_context context, int eval, const char *fmt, va_list ap)
      __attribute__ ((noreturn, format (printf, 3, 0)))
 {
     _warnerr(context, 0, 0, 0, fmt, ap);
     exit(eval);
+    UNREACHABLE(return 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Log a warning to the log, default stderr, and then exit.
+ *
+ * @param context A Kerberos 5 context
+ * @param eval the exit code to exit with
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_errx(krb5_context context, int eval, const char *fmt, ...)
      __attribute__ ((noreturn, format (printf, 3, 4)))
 {
     FUNC(0, 0, 0);
     exit(eval);
+    UNREACHABLE(return 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
-krb5_vabort(krb5_context context, krb5_error_code code,=20
+/**
+ * Log a warning to the log, default stderr, include bthe error from
+ * the last failure and then abort.
+ *
+ * @param context A Kerberos 5 context
+ * @param code error code of the last error
+ * @param fmt message to print
+ * @param ap arguments
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
+krb5_vabort(krb5_context context, krb5_error_code code,
 	    const char *fmt, va_list ap)
      __attribute__ ((noreturn, format (printf, 3, 0)))
 {
     _warnerr(context, 1, code, 0, fmt, ap);
     abort();
+    UNREACHABLE(return 0);
 }
=20
+/**
+ * Log a warning to the log, default stderr, include the error from
+ * the last failure and then abort.
+ *
+ * @param context A Kerberos 5 context
+ * @param code error code of the last error
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_abort(krb5_context context, krb5_error_code code, const char *fmt, ..=
.)
      __attribute__ ((noreturn, format (printf, 3, 4)))
 {
     FUNC(1, code, 0);
     abort();
+    UNREACHABLE(return 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_vabortx(krb5_context context, const char *fmt, va_list ap)
      __attribute__ ((noreturn, format (printf, 2, 0)))
 {
     _warnerr(context, 0, 0, 0, fmt, ap);
     abort();
+    UNREACHABLE(return 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Log a warning to the log, default stderr, and then abort.
+ *
+ * @param context A Kerberos 5 context
+ * @param code error code of the last error
+ * @param fmt message to print
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_abortx(krb5_context context, const char *fmt, ...)
      __attribute__ ((noreturn, format (printf, 2, 3)))
 {
     FUNC(0, 0, 0);
     abort();
+    UNREACHABLE(return 0);
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+/**
+ * Set the default logging facility.
+ *
+ * @param context A Kerberos 5 context
+ * @param fac Facility to use for logging.
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_set_warn_dest(krb5_context context, krb5_log_facility *fac)
 {
     context->warn_dest =3D fac;
     return 0;
 }
=20
-krb5_log_facility * KRB5_LIB_FUNCTION
+/**
+ * Get the default logging facility.
+ *
+ * @param context A Kerberos 5 context
+ *
+ * @ingroup krb5_error
+ */
+
+KRB5_LIB_FUNCTION krb5_log_facility * KRB5_LIB_CALL
 krb5_get_warn_dest(krb5_context context)
 {
     return context->warn_dest;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/krb5/write_mes=
sage.c
--- a/head/crypto/heimdal/lib/krb5/write_message.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/krb5/write_message.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,41 +1,39 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include "krb5_locl.h"
=20
-RCSID("$Id: write_message.c 17442 2006-05-05 09:31:15Z lha $");
-
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_write_message (krb5_context context,
 		    krb5_pointer p_fd,
 		    krb5_data *data)
@@ -49,13 +47,13 @@
     if (krb5_net_write (context, p_fd, buf, 4) !=3D 4
 	|| krb5_net_write (context, p_fd, data->data, len) !=3D len) {
 	ret =3D errno;
-	krb5_set_error_string (context, "write: %s", strerror(ret));
+	krb5_set_error_message (context, ret, "write: %s", strerror(ret));
 	return ret;
     }
     return 0;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_write_priv_message(krb5_context context,
 			krb5_auth_context ac,
 			krb5_pointer p_fd,
@@ -72,7 +70,7 @@
     return ret;
 }
=20
-krb5_error_code KRB5_LIB_FUNCTION
+KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
 krb5_write_safe_message(krb5_context context,
 			krb5_auth_context ac,
 			krb5_pointer p_fd,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/ChangeLog
--- a/head/crypto/heimdal/lib/ntlm/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/ntlm/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,11 +1,19 @@
-2007-12-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-05-14  Love Hornquist Astrand  <lha at kth.se>
+
+	* ntlm.c: replace hashes with keys.
+
+2008-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* ntlm.c: Use DES_set_key_unchecked().
+
+2007-12-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* heimntlm.h: Add NTLM_TARGET_*
=20
 	* ntlm.c: Make heim_ntlm_decode_type3 more useful and provide a
 	username. From Ming Yang.
=20
-2007-11-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-11-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* move doxygen into the main file
=20
@@ -13,18 +21,18 @@
=20
 	* export heim_ntlm_free_buf, start doxygen documentation
 =09
-2007-07-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm.c: Use unsigned char * as argument to HMAC_Update to please
 	OpenSSL and gcc.
=20
 	* test_ntlm.c: more verbose what we are testing.
=20
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: New library version.
=20
-2007-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ntlm.c: heim_ntlm_calculate_ntlm2_sess_resp
=20
@@ -47,31 +55,31 @@
 	* test_ntlm.c: Test heim_ntlm_calculate_ntlm2_sess_resp from
 	Puneet Mehra.
 =09
-2007-06-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: EXTRA_DIST +=3D version-script.map.
 =09
-2007-06-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ntlm.c: Free memory diffrently.
=20
 	* ntlm.c: Make free functions free memory.
 =09
-2007-04-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: symbol versioning.
 =09
 	* version-script.map: symbol versioning.
 =09
-2007-01-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ntlm.c: No need to include <gssapi.h>.
 =09
-2007-01-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: add LIB_roken for test_ntlm
 =09
-2006-12-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_ntlm.c: Verify infotarget.
=20
@@ -83,7 +91,7 @@
=20
 	* ntlm.c: Include <limits.h>.
 =09
-2006-12-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_ntlm.c: add some new tests.
=20
@@ -93,17 +101,17 @@
=20
 	* heimntlm.h: Add NTLM_NEG_NTLM2_SESSION, NTLMv2 session security.
 =09
-2006-12-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ntlm.c (heim_ntlm_build_ntlm1_master): return session master
 	key.
 =09
-2006-12-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ntlm.c (heim_ntlm_build_ntlm1_master): calculate the ntlm
 	version 1 "master" key.
 =09
-2006-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_ntlm.c: Add simple parser test app.
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/Makefile.=
am
--- a/head/crypto/heimdal/lib/ntlm/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/ntlm/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,12 +1,18 @@
-# $Id: Makefile.am 22045 2007-11-11 08:57:47Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-lib_LTLIBRARIES	=3D libheimntlm.la
+AM_CPPFLAGS +=3D $(INCLUDE_hcrypto)
=20
-include_HEADERS =3D heimntlm.h heimntlm-protos.h
+lib_LTLIBRARIES =3D libheimntlm.la
=20
-libheimntlm_la_SOURCES	=3D ntlm.c heimntlm.h
+dist_include_HEADERS =3D heimntlm.h heimntlm-protos.h
+
+nodist_include_HEADERS =3D ntlm_err.h
+
+dist_libheimntlm_la_SOURCES =3D ntlm.c heimntlm.h
+
+nodist_libheimntlm_la_SOURCES =3D ntlm_err.c
=20
 libheimntlm_la_LDFLAGS =3D -version-info 1:0:1
=20
@@ -17,13 +23,13 @@
=20
 libheimntlm_la_LIBADD =3D \
 	../krb5/libkrb5.la \
+	$(LIB_hcrypto) \
 	$(LIBADD_roken)
=20
 $(srcdir)/heimntlm-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o heimntlm-pro=
tos.h $(libheimntlm_la_SOURCES) || rm -f heimntlm-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o heimntlm-pro=
tos.h $(dist_libheimntlm_la_SOURCES) || rm -f heimntlm-protos.h
=20
-$(libheimntlm_la_OBJECTS): $(srcdir)/heimntlm-protos.h
-
+$(libheimntlm_la_OBJECTS): $(srcdir)/heimntlm-protos.h ntlm_err.h
=20
 TESTS =3D test_ntlm
=20
@@ -31,4 +37,14 @@
=20
 LDADD =3D libheimntlm.la $(LIB_roken)
=20
-EXTRA_DIST =3D version-script.map
+EXTRA_DIST =3D \
+	NTMakefile \
+	libheimntlm-version.rc \
+	libheimntlm-exports.def \
+	version-script.map \
+	ntlm_err.et
+
+CLEANFILES =3D \
+	ntlm_err.c ntlm_err.h
+
+ntlm_err.h: ntlm_err.et
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/Makefile.=
in
--- a/head/crypto/heimdal/lib/ntlm/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/ntlm/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,17 +15,18 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22045 2007-11-11 08:57:47Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -39,7 +41,7 @@
 POST_UNINSTALL =3D :
 build_triplet =3D @build@
 host_triplet =3D @host@
-DIST_COMMON =3D $(include_HEADERS) $(srcdir)/Makefile.am \
+DIST_COMMON =3D $(dist_include_HEADERS) $(srcdir)/Makefile.am \
 	$(srcdir)/Makefile.in $(top_srcdir)/Makefile.am.common \
 	$(top_srcdir)/cf/Makefile.am.common ChangeLog
 @versionscript_TRUE at am__append_1 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
@@ -48,7 +50,7 @@
 subdir =3D lib/ntlm
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -63,7 +65,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -77,9 +79,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -87,25 +92,44 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
-am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
+am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" \
+	"$(DESTDIR)$(includedir)"
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
 am__DEPENDENCIES_1 =3D
-libheimntlm_la_DEPENDENCIES =3D ../krb5/libkrb5.la $(am__DEPENDENCIES_1)
-am_libheimntlm_la_OBJECTS =3D ntlm.lo
-libheimntlm_la_OBJECTS =3D $(am_libheimntlm_la_OBJECTS)
+libheimntlm_la_DEPENDENCIES =3D ../krb5/libkrb5.la $(am__DEPENDENCIES_1) \
+	$(am__DEPENDENCIES_1)
+dist_libheimntlm_la_OBJECTS =3D ntlm.lo
+nodist_libheimntlm_la_OBJECTS =3D ntlm_err.lo
+libheimntlm_la_OBJECTS =3D $(dist_libheimntlm_la_OBJECTS) \
+	$(nodist_libheimntlm_la_OBJECTS)
 libheimntlm_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libheimntlm_la_LDFLAGS) $(LDFLAGS) -o $@
@@ -113,9 +137,9 @@
 test_ntlm_OBJECTS =3D test_ntlm.$(OBJEXT)
 test_ntlm_LDADD =3D $(LDADD)
 test_ntlm_DEPENDENCIES =3D libheimntlm.la $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -125,60 +149,71 @@
 LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
-SOURCES =3D $(libheimntlm_la_SOURCES) test_ntlm.c
-DIST_SOURCES =3D $(libheimntlm_la_SOURCES) test_ntlm.c
-includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-HEADERS =3D $(include_HEADERS)
+SOURCES =3D $(dist_libheimntlm_la_SOURCES) \
+	$(nodist_libheimntlm_la_SOURCES) test_ntlm.c
+DIST_SOURCES =3D $(dist_libheimntlm_la_SOURCES) test_ntlm.c
+HEADERS =3D $(dist_include_HEADERS) $(nodist_include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -202,10 +237,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -222,6 +258,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -237,31 +275,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -276,10 +328,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -320,56 +374,73 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(INCLUDE_hcrypto)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 lib_LTLIBRARIES =3D libheimntlm.la
-include_HEADERS =3D heimntlm.h heimntlm-protos.h
-libheimntlm_la_SOURCES =3D ntlm.c heimntlm.h
+dist_include_HEADERS =3D heimntlm.h heimntlm-protos.h
+nodist_include_HEADERS =3D ntlm_err.h
+dist_libheimntlm_la_SOURCES =3D ntlm.c heimntlm.h
+nodist_libheimntlm_la_SOURCES =3D ntlm_err.c
 libheimntlm_la_LDFLAGS =3D -version-info 1:0:1 $(am__append_1)
 libheimntlm_la_LIBADD =3D \
 	../krb5/libkrb5.la \
+	$(LIB_hcrypto) \
 	$(LIBADD_roken)
=20
 LDADD =3D libheimntlm.la $(LIB_roken)
-EXTRA_DIST =3D version-script.map
+EXTRA_DIST =3D \
+	NTMakefile \
+	libheimntlm-version.rc \
+	libheimntlm-exports.def \
+	version-script.map \
+	ntlm_err.et
+
+CLEANFILES =3D \
+	ntlm_err.c ntlm_err.h
+
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/ntlm/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/ntlm/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/ntlm/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/ntlm/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -387,23 +458,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -418,11 +494,13 @@
 	$(libheimntlm_la_LINK) -rpath $(libdir) $(libheimntlm_la_OBJECTS) $(libhe=
imntlm_la_LIBADD) $(LIBS)
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 test_ntlm$(EXEEXT): $(test_ntlm_OBJECTS) $(test_ntlm_DEPENDENCIES)=20
 	@rm -f test_ntlm$(EXEEXT)
 	$(LINK) $(test_ntlm_OBJECTS) $(test_ntlm_LDADD) $(LIBS)
@@ -433,90 +511,134 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ntlm.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/ntlm_err.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_ntlm.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-includeHEADERS: $(include_HEADERS)
+install-dist_includeHEADERS: $(dist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'=
"; \
-	  $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
-uninstall-includeHEADERS:
+uninstall-dist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
+install-nodist_includeHEADERS: $(nodist_include_HEADERS)
+	@$(NORMAL_INSTALL)
+	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
+	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
+uninstall-nodist_includeHEADERS:
+	@$(NORMAL_UNINSTALL)
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
+
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -525,49 +647,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -578,11 +714,15 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
@@ -602,13 +742,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -621,7 +765,7 @@
 check: check-am
 all-am: Makefile $(LTLIBRARIES) $(HEADERS) all-local
 installdirs:
-	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \
+	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" "$(DESTDIR)$(i=
ncludedir)"; do \
 	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
 	done
 install: install-am
@@ -641,9 +785,11 @@
 mostlyclean-generic:
=20
 clean-generic:
+	-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -654,6 +800,7 @@
 	clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -664,33 +811,45 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
=20
-install-data-am: install-includeHEADERS
+install-data-am: install-dist_includeHEADERS \
+	install-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -707,12 +866,12 @@
=20
 ps-am:
=20
-uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES
+uninstall-am: uninstall-dist_includeHEADERS uninstall-libLTLIBRARIES \
+	uninstall-nodist_includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
 	check-local clean clean-checkPROGRAMS clean-generic \
@@ -720,16 +879,18 @@
 	distclean-compile distclean-generic distclean-libtool \
 	distclean-tags distdir dvi dvi-am html html-am info info-am \
 	install install-am install-data install-data-am \
-	install-data-hook install-dvi install-dvi-am install-exec \
-	install-exec-am install-exec-hook install-html install-html-am \
-	install-includeHEADERS install-info install-info-am \
-	install-libLTLIBRARIES install-man install-pdf install-pdf-am \
+	install-data-hook install-dist_includeHEADERS install-dvi \
+	install-dvi-am install-exec install-exec-am install-exec-hook \
+	install-html install-html-am install-info install-info-am \
+	install-libLTLIBRARIES install-man \
+	install-nodist_includeHEADERS install-pdf install-pdf-am \
 	install-ps install-ps-am install-strip installcheck \
 	installcheck-am installdirs maintainer-clean \
 	maintainer-clean-generic mostlyclean mostlyclean-compile \
 	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags uninstall uninstall-am uninstall-hook \
-	uninstall-includeHEADERS uninstall-libLTLIBRARIES
+	tags uninstall uninstall-am uninstall-dist_includeHEADERS \
+	uninstall-hook uninstall-libLTLIBRARIES \
+	uninstall-nodist_includeHEADERS
=20
=20
 install-suid-programs:
@@ -800,6 +961,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -885,7 +1049,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -901,9 +1065,12 @@
 $(libheimntlm_la_OBJECTS): $(srcdir)/version-script.map
=20
 $(srcdir)/heimntlm-protos.h:
-	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o heimntlm-pro=
tos.h $(libheimntlm_la_SOURCES) || rm -f heimntlm-protos.h
+	cd $(srcdir) && perl ../../cf/make-proto.pl -q -P comment -o heimntlm-pro=
tos.h $(dist_libheimntlm_la_SOURCES) || rm -f heimntlm-protos.h
=20
-$(libheimntlm_la_OBJECTS): $(srcdir)/heimntlm-protos.h
+$(libheimntlm_la_OBJECTS): $(srcdir)/heimntlm-protos.h ntlm_err.h
+
+ntlm_err.h: ntlm_err.et
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/heimntlm-=
protos.h
--- a/head/crypto/heimdal/lib/ntlm/heimntlm-protos.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/ntlm/heimntlm-protos.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -16,10 +16,28 @@
 	struct ntlm_buf */*master*/);
=20
 int
+heim_ntlm_build_ntlm2_master (
+	void */*key*/,
+	size_t /*len*/,
+	struct ntlm_buf */*blob*/,
+	struct ntlm_buf */*session*/,
+	struct ntlm_buf */*master*/);
+
+int
+heim_ntlm_calculate_lm2 (
+	const void */*key*/,
+	size_t /*len*/,
+	const char */*username*/,
+	const char */*target*/,
+	const unsigned char serverchallenge[8],
+	unsigned char ntlmv2[16],
+	struct ntlm_buf */*answer*/);
+
+int
 heim_ntlm_calculate_ntlm1 (
 	void */*key*/,
 	size_t /*len*/,
-	unsigned char challange[8],
+	unsigned char challenge[8],
 	struct ntlm_buf */*answer*/);
=20
 int
@@ -28,7 +46,7 @@
 	size_t /*len*/,
 	const char */*username*/,
 	const char */*target*/,
-	const unsigned char serverchallange[8],
+	const unsigned char serverchallenge[8],
 	const struct ntlm_buf */*infotarget*/,
 	unsigned char ntlmv2[16],
 	struct ntlm_buf */*answer*/);
@@ -42,6 +60,12 @@
 	struct ntlm_buf */*ntlm*/);
=20
 int
+heim_ntlm_calculate_ntlm2_sess_hash (
+	const unsigned char clnt_nonce[8],
+	const unsigned char svr_chal[8],
+	unsigned char verifier[8]);
+
+int
 heim_ntlm_decode_targetinfo (
 	const struct ntlm_buf */*data*/,
 	int /*ucs2*/,
@@ -63,6 +87,14 @@
 	int /*ucs2*/,
 	struct ntlm_type3 */*type3*/);
=20
+void
+heim_ntlm_derive_ntlm2_sess (
+	const unsigned char sessionkey[16],
+	const unsigned char */*clnt_nonce*/,
+	size_t /*clnt_nonce_length*/,
+	const unsigned char svr_chal[8],
+	unsigned char derivedkey[16]);
+
 int
 heim_ntlm_encode_targetinfo (
 	const struct ntlm_targetinfo */*ti*/,
@@ -100,11 +132,23 @@
 heim_ntlm_free_type3 (struct ntlm_type3 */*data*/);
=20
 int
+heim_ntlm_keyex_unwrap (
+	struct ntlm_buf */*baseKey*/,
+	struct ntlm_buf */*encryptedSession*/,
+	struct ntlm_buf */*session*/);
+
+int
+heim_ntlm_keyex_wrap (
+	struct ntlm_buf */*base_session*/,
+	struct ntlm_buf */*session*/,
+	struct ntlm_buf */*encryptedSession*/);
+
+int
 heim_ntlm_nt_key (
 	const char */*password*/,
 	struct ntlm_buf */*key*/);
=20
-void
+int
 heim_ntlm_ntlmv2_key (
 	const void */*key*/,
 	size_t /*len*/,
@@ -112,6 +156,25 @@
 	const char */*target*/,
 	unsigned char ntlmv2[16]);
=20
+size_t
+heim_ntlm_unparse_flags (
+	uint32_t /*flags*/,
+	char */*s*/,
+	size_t /*len*/);
+
+int
+heim_ntlm_v1_base_session (
+	void */*key*/,
+	size_t /*len*/,
+	struct ntlm_buf */*session*/);
+
+int
+heim_ntlm_v2_base_session (
+	void */*key*/,
+	size_t /*len*/,
+	struct ntlm_buf */*ntlmResponse*/,
+	struct ntlm_buf */*session*/);
+
 int
 heim_ntlm_verify_ntlm2 (
 	const void */*key*/,
@@ -119,7 +182,7 @@
 	const char */*username*/,
 	const char */*target*/,
 	time_t /*now*/,
-	const unsigned char serverchallange[8],
+	const unsigned char serverchallenge[8],
 	const struct ntlm_buf */*answer*/,
 	struct ntlm_buf */*infotarget*/,
 	unsigned char ntlmv2[16]);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/heimntlm.h
--- a/head/crypto/heimdal/lib/ntlm/heimntlm.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/ntlm/heimntlm.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: heimntlm.h 22376 2007-12-28 18:38:23Z lha $ */
+/* $Id$ */
=20
 #ifndef HEIM_NTLM_H
 #define HEIM_NTLM_H
@@ -46,32 +46,64 @@
 };
=20
 #define NTLM_NEG_UNICODE		0x00000001
+#define NTLM_NEG_OEM                    0x00000002
 #define NTLM_NEG_TARGET			0x00000004
+#define NTLM_MBZ9			0x00000008
+
 #define NTLM_NEG_SIGN			0x00000010
 #define NTLM_NEG_SEAL			0x00000020
+#define NTLM_NEG_DATAGRAM               0x00000040
+#define NTLM_NEG_LM_KEY                 0x00000080
 #define NTLM_NEG_NTLM			0x00000200
+#define NTLM_NEG_ANONYMOUS              0x00000800
=20
-#define NTLM_SUPPLIED_DOMAIN		0x00001000
-#define NTLM_SUPPLIED_WORKSTAION	0x00002000
+#define NTLM_MBZ8			0x00000100
+#define NTLM_NEG_NTLM			0x00000200
+#define NTLM_NEG_NT_ONLY		0x00000400
+#define NTLM_MBZ7			0x00000800 /* anon ? */
=20
+#define NTLM_OEM_SUPPLIED_DOMAIN	0x00001000
+#define NTLM_OEM_SUPPLIED_WORKSTATION	0x00002000
+#define NTLM_MBZ6			0x00004000 /* local call ? */
 #define NTLM_NEG_ALWAYS_SIGN		0x00008000
-#define NTLM_NEG_NTLM2_SESSION		0x00080000
=20
 #define NTLM_TARGET_DOMAIN		0x00010000
 #define NTLM_TARGET_SERVER		0x00020000
+
+#define NTLM_TARGET_SHARE		0x00040000
+#define NTLM_NEG_NTLM2_SESSION		0x00080000
+#define NTLM_NEG_NTLM2			0x00080000
+
+#define NTLM_NEG_IDENTIFY		0x00100000
+#define NTLM_MBZ5			0x00200000
+#define NTLM_NON_NT_SESSION_KEY		0x00400000
+#define NTLM_NEG_TARGET_INFO		0x00800000
+
+#define NTLM_MBZ4			0x01000000
+#define NTLM_NEG_VERSION		0x02000000
+#define NTLM_MBZ3			0x04000000
+#define NTLM_MBZ2			0x08000000
+
+#define NTLM_MBZ1			0x10000000
 #define NTLM_ENC_128			0x20000000
 #define NTLM_NEG_KEYEX			0x40000000
+#define NTLM_ENC_56			0x80000000
=20
 /**
  * Struct for the NTLM target info, the strings is assumed to be in
  * UTF8.  When filled in by the library it should be freed with
  * heim_ntlm_free_targetinfo().
  */
+
+#define NTLM_TI_AV_FLAG_GUEST		0x00000001
+
 struct ntlm_targetinfo {
     char *servername; /**< */
     char *domainname; /**< */
     char *dnsdomainname; /**< */
     char *dnsservername; /**< */
+    char *dnstreename; /**< */
+    uint32_t avflags; /**< */
 };
=20
 /**
@@ -97,7 +129,7 @@
     uint32_t flags; /**< */
     char *targetname; /**< */
     struct ntlm_buf targetinfo; /**< */
-    unsigned char challange[8]; /**< */
+    unsigned char challenge[8]; /**< */
     uint32_t context[2]; /**< */
     uint32_t os[2]; /**< */
 };
@@ -119,6 +151,7 @@
     uint32_t os[2]; /**< */
 };
=20
+#include <ntlm_err.h>
 #include <heimntlm-protos.h>
=20
 #endif /* NTLM_NTLM_H */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/ntlm.c
--- a/head/crypto/heimdal/lib/ntlm/ntlm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/ntlm/ntlm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,40 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2008 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Portions Copyright (c) 2010 Apple Inc. All rights reserved.
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 #include <config.h>
=20
-RCSID("$Id: ntlm.c 22370 2007-12-28 16:12:01Z lha $");
-
 #include <stdio.h>
 #include <stdlib.h>
 #include <assert.h>
@@ -43,8 +43,11 @@
 #include <errno.h>
 #include <limits.h>
=20
+#include <roken.h>
+#include <parse_units.h>
 #include <krb5.h>
-#include <roken.h>
+
+#define HC_DEPRECATED_CRYPTO
=20
 #include "krb5-types.h"
 #include "crypto-headers.h"
@@ -59,7 +62,7 @@
  * protocol, both version 1 and 2. The GSS-API mech that uses this
  * library adds support for transport encryption and integrity
  * checking.
- *=20
+ *
  * NTLM is a protocol for mutual authentication, its still used in
  * many protocol where Kerberos is not support, one example is
  * EAP/X802.1x mechanism LEAP from Microsoft and Cisco.
@@ -68,16 +71,25 @@
  * Heimdal to implement and GSS-API mechanism. There is also support
  * in the KDC to do remote digest authenticiation, this to allow
  * services to authenticate users w/o direct access to the users ntlm
- * hashes (same as Kerberos arcfour enctype hashes).
+ * hashes (same as Kerberos arcfour enctype keys).
  *
  * More information about the NTLM protocol can found here
  * http://davenport.sourceforge.net/ntlm.html .
- *=20
+ *
  * The Heimdal projects web page: http://www.h5l.org/
+ *
+ * @section ntlm_example NTLM Example
+ *
+ * Example to to use @ref test_ntlm.c .
+ *
+ * @example test_ntlm.c
+ *
+ * Example how to use the NTLM primitives.
+ *
  */
=20
-/** @defgroup ntlm_core Heimdal NTLM library=20
- *=20
+/** @defgroup ntlm_core Heimdal NTLM library
+ *
  * The NTLM core functions implement the string2key generation
  * function, message encode and decode function, and the hash function
  * functions.
@@ -96,7 +108,58 @@
  */
=20
 #define CHECK(f, e)							\
-    do { ret =3D f ; if (ret !=3D (e)) { ret =3D EINVAL; goto out; } } whi=
le(0)
+    do {								\
+	ret =3D f;							\
+	if (ret !=3D (ssize_t)(e)) {					\
+	    ret =3D HNTLM_ERR_DECODE;					\
+	    goto out;							\
+	}								\
+    } while(/*CONSTCOND*/0)
+
+static struct units ntlm_flag_units[] =3D {
+#define ntlm_flag(x) { #x, NTLM_##x }
+    ntlm_flag(ENC_56),
+    ntlm_flag(NEG_KEYEX),
+    ntlm_flag(ENC_128),
+    ntlm_flag(MBZ1),
+    ntlm_flag(MBZ2),
+    ntlm_flag(MBZ3),
+    ntlm_flag(NEG_VERSION),
+    ntlm_flag(MBZ4),
+    ntlm_flag(NEG_TARGET_INFO),
+    ntlm_flag(NON_NT_SESSION_KEY),
+    ntlm_flag(MBZ5),
+    ntlm_flag(NEG_IDENTIFY),
+    ntlm_flag(NEG_NTLM2),
+    ntlm_flag(TARGET_SHARE),
+    ntlm_flag(TARGET_SERVER),
+    ntlm_flag(TARGET_DOMAIN),
+    ntlm_flag(NEG_ALWAYS_SIGN),
+    ntlm_flag(MBZ6),
+    ntlm_flag(OEM_SUPPLIED_WORKSTATION),
+    ntlm_flag(OEM_SUPPLIED_DOMAIN),
+    ntlm_flag(NEG_ANONYMOUS),
+    ntlm_flag(NEG_NT_ONLY),
+    ntlm_flag(NEG_NTLM),
+    ntlm_flag(MBZ8),
+    ntlm_flag(NEG_LM_KEY),
+    ntlm_flag(NEG_DATAGRAM),
+    ntlm_flag(NEG_SEAL),
+    ntlm_flag(NEG_SIGN),
+    ntlm_flag(MBZ9),
+    ntlm_flag(NEG_TARGET),
+    ntlm_flag(NEG_OEM),
+    ntlm_flag(NEG_UNICODE),
+#undef ntlm_flag
+    {NULL, 0}
+};
+
+size_t
+heim_ntlm_unparse_flags(uint32_t flags, char *s, size_t len)
+{
+    return unparse_flags(flags, ntlm_flag_units, s, len);
+}
+
=20
 /**
  * heim_ntlm_free_buf frees the ntlm buffer
@@ -114,7 +177,7 @@
     p->data =3D NULL;
     p->length =3D 0;
 }
-   =20
+
=20
 static int
 ascii2ucs2le(const char *string, int up, struct ntlm_buf *buf)
@@ -188,19 +251,25 @@
     return len;
 }
=20
+/*
+ *
+ */
+
 static krb5_error_code
-ret_string(krb5_storage *sp, int ucs2, struct sec_buffer *desc, char **s)
+ret_string(krb5_storage *sp, int ucs2, size_t len, char **s)
 {
     krb5_error_code ret;
=20
-    *s =3D malloc(desc->length + 1);
-    CHECK(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
-    CHECK(krb5_storage_read(sp, *s, desc->length), desc->length);
-    (*s)[desc->length] =3D '\0';
+    *s =3D malloc(len + 1);
+    if (*s =3D=3D NULL)
+	return ENOMEM;
+    CHECK(krb5_storage_read(sp, *s, len), len);
+
+    (*s)[len] =3D '\0';
=20
     if (ucs2) {
 	size_t i;
-	for (i =3D 0; i < desc->length / 2; i++) {
+	for (i =3D 0; i < len / 2; i++) {
 	    (*s)[i] =3D (*s)[i * 2];
 	    if ((*s)[i * 2 + 1]) {
 		free(*s);
@@ -211,10 +280,20 @@
 	(*s)[i] =3D '\0';
     }
     ret =3D 0;
-out:
+ out:
     return ret;
+}
=20
-    return 0;
+
+
+static krb5_error_code
+ret_sec_string(krb5_storage *sp, int ucs2, struct sec_buffer *desc, char *=
*s)
+{
+    krb5_error_code ret =3D 0;
+    CHECK(krb5_storage_seek(sp, desc->offset, SEEK_SET), desc->offset);
+    CHECK(ret_string(sp, ucs2, desc->length, s), 0);
+ out:
+    return ret;
 }
=20
 static krb5_error_code
@@ -283,11 +362,12 @@
     free(ti->domainname);
     free(ti->dnsdomainname);
     free(ti->dnsservername);
+    free(ti->dnstreename);
     memset(ti, 0, sizeof(*ti));
 }
=20
 static int
-encode_ti_blob(krb5_storage *out, uint16_t type, int ucs2, char *s)
+encode_ti_string(krb5_storage *out, uint16_t type, int ucs2, char *s)
 {
     krb5_error_code ret;
     CHECK(krb5_store_uint16(out, type), 0);
@@ -301,7 +381,7 @@
  * Encodes a ntlm_targetinfo message.
  *
  * @param ti the ntlm_targetinfo message to encode.
- * @param ucs2 if the strings should be encoded with ucs2 (selected by fla=
g in message).
+ * @param ucs2 ignored
  * @param data is the return buffer with the encoded message, should be
  * freed with heim_ntlm_free_buf().
  *
@@ -313,7 +393,7 @@
=20
 int
 heim_ntlm_encode_targetinfo(const struct ntlm_targetinfo *ti,
-			    int ucs2,=20
+			    int ucs2,
 			    struct ntlm_buf *data)
 {
     krb5_error_code ret;
@@ -326,14 +406,23 @@
     if (out =3D=3D NULL)
 	return ENOMEM;
=20
+    krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
+
     if (ti->servername)
-	CHECK(encode_ti_blob(out, 1, ucs2, ti->servername), 0);
+	CHECK(encode_ti_string(out, 1, ucs2, ti->servername), 0);
     if (ti->domainname)
-	CHECK(encode_ti_blob(out, 2, ucs2, ti->domainname), 0);
+	CHECK(encode_ti_string(out, 2, ucs2, ti->domainname), 0);
     if (ti->dnsservername)
-	CHECK(encode_ti_blob(out, 3, ucs2, ti->dnsservername), 0);
+	CHECK(encode_ti_string(out, 3, ucs2, ti->dnsservername), 0);
     if (ti->dnsdomainname)
-	CHECK(encode_ti_blob(out, 4, ucs2, ti->dnsdomainname), 0);
+	CHECK(encode_ti_string(out, 4, ucs2, ti->dnsdomainname), 0);
+    if (ti->dnstreename)
+	CHECK(encode_ti_string(out, 5, ucs2, ti->dnstreename), 0);
+    if (ti->avflags) {
+	CHECK(krb5_store_uint16(out, 6), 0);
+	CHECK(krb5_store_uint16(out, 4), 0);
+	CHECK(krb5_store_uint32(out, ti->avflags), 0);
+    }
=20
     /* end tag */
     CHECK(krb5_store_int16(out, 0), 0);
@@ -368,8 +457,55 @@
 			    int ucs2,
 			    struct ntlm_targetinfo *ti)
 {
+    uint16_t type, len;
+    krb5_storage *in;
+    int ret =3D 0, done =3D 0;
+
     memset(ti, 0, sizeof(*ti));
-    return 0;
+
+    if (data->length =3D=3D 0)
+	return 0;
+
+    in =3D krb5_storage_from_readonly_mem(data->data, data->length);
+    if (in =3D=3D NULL)
+	return ENOMEM;
+    krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
+
+    while (!done) {
+	CHECK(krb5_ret_uint16(in, &type), 0);
+	CHECK(krb5_ret_uint16(in, &len), 0);
+
+	switch (type) {
+	case 0:
+	    done =3D 1;
+	    break;
+	case 1:
+	    CHECK(ret_string(in, ucs2, len, &ti->servername), 0);
+	    break;
+	case 2:
+	    CHECK(ret_string(in, ucs2, len, &ti->domainname), 0);
+	    break;
+	case 3:
+	    CHECK(ret_string(in, ucs2, len, &ti->dnsservername), 0);
+	    break;
+	case 4:
+	    CHECK(ret_string(in, ucs2, len, &ti->dnsdomainname), 0);
+	    break;
+	case 5:
+	    CHECK(ret_string(in, ucs2, len, &ti->dnstreename), 0);
+	    break;
+	case 6:
+	    CHECK(krb5_ret_uint32(in, &ti->avflags), 0);
+	    break;
+	default:
+	    krb5_storage_seek(in, len, SEEK_CUR);
+	    break;
+	}
+    }
+ out:
+    if (in)
+	krb5_storage_free(in);
+    return ret;
 }
=20
 /**
@@ -398,12 +534,12 @@
     uint32_t type;
     struct sec_buffer domain, hostname;
     krb5_storage *in;
-   =20
+
     memset(data, 0, sizeof(*data));
=20
     in =3D krb5_storage_from_readonly_mem(buf->data, buf->length);
     if (in =3D=3D NULL) {
-	ret =3D EINVAL;
+	ret =3D ENOMEM;
 	goto out;
     }
     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
@@ -413,9 +549,9 @@
     CHECK(krb5_ret_uint32(in, &type), 0);
     CHECK(type, 1);
     CHECK(krb5_ret_uint32(in, &data->flags), 0);
-    if (data->flags & NTLM_SUPPLIED_DOMAIN)
+    if (data->flags & NTLM_OEM_SUPPLIED_DOMAIN)
 	CHECK(ret_sec_buffer(in, &domain), 0);
-    if (data->flags & NTLM_SUPPLIED_WORKSTAION)
+    if (data->flags & NTLM_OEM_SUPPLIED_WORKSTATION)
 	CHECK(ret_sec_buffer(in, &hostname), 0);
 #if 0
     if (domain.offset > 32) {
@@ -423,13 +559,14 @@
 	CHECK(krb5_ret_uint32(in, &data->os[1]), 0);
     }
 #endif
-    if (data->flags & NTLM_SUPPLIED_DOMAIN)
-	CHECK(ret_string(in, 0, &domain, &data->domain), 0);
-    if (data->flags & NTLM_SUPPLIED_WORKSTAION)
-	CHECK(ret_string(in, 0, &hostname, &data->hostname), 0);
+    if (data->flags & NTLM_OEM_SUPPLIED_DOMAIN)
+	CHECK(ret_sec_string(in, 0, &domain, &data->domain), 0);
+    if (data->flags & NTLM_OEM_SUPPLIED_WORKSTATION)
+	CHECK(ret_sec_string(in, 0, &hostname, &data->hostname), 0);
=20
 out:
-    krb5_storage_free(in);
+    if (in)
+	krb5_storage_free(in);
     if (ret)
 	heim_ntlm_free_type1(data);
=20
@@ -456,30 +593,37 @@
     struct sec_buffer domain, hostname;
     krb5_storage *out;
     uint32_t base, flags;
-   =20
+
     flags =3D type1->flags;
     base =3D 16;
=20
     if (type1->domain) {
 	base +=3D 8;
-	flags |=3D NTLM_SUPPLIED_DOMAIN;
+	flags |=3D NTLM_OEM_SUPPLIED_DOMAIN;
     }
     if (type1->hostname) {
 	base +=3D 8;
-	flags |=3D NTLM_SUPPLIED_WORKSTAION;
+	flags |=3D NTLM_OEM_SUPPLIED_WORKSTATION;
     }
     if (type1->os[0])
 	base +=3D 8;
=20
+    domain.offset =3D base;
     if (type1->domain) {
-	domain.offset =3D base;
 	domain.length =3D len_string(0, type1->domain);
 	domain.allocated =3D domain.length;
+    } else {
+	domain.length =3D 0;
+	domain.allocated =3D 0;
     }
+
+    hostname.offset =3D domain.allocated + domain.offset;
     if (type1->hostname) {
-	hostname.offset =3D domain.allocated + domain.offset;
 	hostname.length =3D len_string(0, type1->hostname);
 	hostname.allocated =3D hostname.length;
+    } else {
+	hostname.length =3D 0;
+	hostname.allocated =3D 0;
     }
=20
     out =3D krb5_storage_emem();
@@ -487,19 +631,17 @@
 	return ENOMEM;
=20
     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
-    CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),=20
+    CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
 	  sizeof(ntlmsigature));
     CHECK(krb5_store_uint32(out, 1), 0);
     CHECK(krb5_store_uint32(out, flags), 0);
-   =20
-    if (type1->domain)
-	CHECK(store_sec_buffer(out, &domain), 0);
-    if (type1->hostname)
-	CHECK(store_sec_buffer(out, &hostname), 0);
-    if (type1->os[0]) {
+
+    CHECK(store_sec_buffer(out, &domain), 0);
+    CHECK(store_sec_buffer(out, &hostname), 0);
+#if 0
 	CHECK(krb5_store_uint32(out, type1->os[0]), 0);
 	CHECK(krb5_store_uint32(out, type1->os[1]), 0);
-    }
+#endif
     if (type1->domain)
 	CHECK(put_string(out, 0, type1->domain), 0);
     if (type1->hostname)
@@ -543,12 +685,12 @@
     struct sec_buffer targetname, targetinfo;
     krb5_storage *in;
     int ucs2 =3D 0;
-   =20
+
     memset(type2, 0, sizeof(*type2));
=20
     in =3D krb5_storage_from_readonly_mem(buf->data, buf->length);
     if (in =3D=3D NULL) {
-	ret =3D EINVAL;
+	ret =3D ENOMEM;
 	goto out;
     }
     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
@@ -562,23 +704,24 @@
     CHECK(krb5_ret_uint32(in, &type2->flags), 0);
     if (type2->flags & NTLM_NEG_UNICODE)
 	ucs2 =3D 1;
-    CHECK(krb5_storage_read(in, type2->challange, sizeof(type2->challange)=
),
-	  sizeof(type2->challange));
+    CHECK(krb5_storage_read(in, type2->challenge, sizeof(type2->challenge)=
),
+	  sizeof(type2->challenge));
     CHECK(krb5_ret_uint32(in, &ctx[0]), 0); /* context */
     CHECK(krb5_ret_uint32(in, &ctx[1]), 0);
     CHECK(ret_sec_buffer(in, &targetinfo), 0);
     /* os version */
-#if 0
-    CHECK(krb5_ret_uint32(in, &type2->os[0]), 0);
-    CHECK(krb5_ret_uint32(in, &type2->os[1]), 0);
-#endif
+    if (type2->flags & NTLM_NEG_VERSION) {
+	CHECK(krb5_ret_uint32(in, &type2->os[0]), 0);
+	CHECK(krb5_ret_uint32(in, &type2->os[1]), 0);
+    }
=20
-    CHECK(ret_string(in, ucs2, &targetname, &type2->targetname), 0);
+    CHECK(ret_sec_string(in, ucs2, &targetname, &type2->targetname), 0);
     CHECK(ret_buf(in, &targetinfo, &type2->targetinfo), 0);
     ret =3D 0;
=20
 out:
-    krb5_storage_free(in);
+    if (in)
+	krb5_storage_free(in);
     if (ret)
 	heim_ntlm_free_type2(type2);
=20
@@ -607,10 +750,10 @@
     uint32_t base;
     int ucs2 =3D 0;
=20
-    if (type2->os[0])
-	base =3D 56;
-    else
-	base =3D 48;
+    base =3D 48;
+
+    if (type2->flags & NTLM_NEG_VERSION)
+	base +=3D 8;
=20
     if (type2->flags & NTLM_NEG_UNICODE)
 	ucs2 =3D 1;
@@ -628,26 +771,26 @@
 	return ENOMEM;
=20
     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
-    CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),=20
+    CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
 	  sizeof(ntlmsigature));
     CHECK(krb5_store_uint32(out, 2), 0);
     CHECK(store_sec_buffer(out, &targetname), 0);
     CHECK(krb5_store_uint32(out, type2->flags), 0);
-    CHECK(krb5_storage_write(out, type2->challange, sizeof(type2->challang=
e)),
-	  sizeof(type2->challange));
+    CHECK(krb5_storage_write(out, type2->challenge, sizeof(type2->challeng=
e)),
+	  sizeof(type2->challenge));
     CHECK(krb5_store_uint32(out, 0), 0); /* context */
     CHECK(krb5_store_uint32(out, 0), 0);
     CHECK(store_sec_buffer(out, &targetinfo), 0);
     /* os version */
-    if (type2->os[0]) {
+    if (type2->flags & NTLM_NEG_VERSION) {
 	CHECK(krb5_store_uint32(out, type2->os[0]), 0);
 	CHECK(krb5_store_uint32(out, type2->os[1]), 0);
     }
     CHECK(put_string(out, ucs2, type2->targetname), 0);
-    CHECK(krb5_storage_write(out, type2->targetinfo.data,=20
+    CHECK(krb5_storage_write(out, type2->targetinfo.data,
 			     type2->targetinfo.length),
 	  type2->targetinfo.length);
-   =20
+
     {
 	krb5_data d;
 	ret =3D krb5_storage_to_data(out, &d);
@@ -698,13 +841,14 @@
     uint32_t type;
     krb5_storage *in;
     struct sec_buffer lm, ntlm, target, username, sessionkey, ws;
+    uint32_t min_offset =3D 72;
=20
     memset(type3, 0, sizeof(*type3));
     memset(&sessionkey, 0, sizeof(sessionkey));
=20
     in =3D krb5_storage_from_readonly_mem(buf->data, buf->length);
     if (in =3D=3D NULL) {
-	ret =3D EINVAL;
+	ret =3D ENOMEM;
 	goto out;
     }
     krb5_storage_set_byteorder(in, KRB5_STORAGE_BYTEORDER_LE);
@@ -714,30 +858,41 @@
     CHECK(krb5_ret_uint32(in, &type), 0);
     CHECK(type, 3);
     CHECK(ret_sec_buffer(in, &lm), 0);
+    if (lm.allocated)
+	min_offset =3D min(min_offset, lm.offset);
     CHECK(ret_sec_buffer(in, &ntlm), 0);
+    if (ntlm.allocated)
+	min_offset =3D min(min_offset, ntlm.offset);
     CHECK(ret_sec_buffer(in, &target), 0);
+    if (target.allocated)
+	min_offset =3D min(min_offset, target.offset);
     CHECK(ret_sec_buffer(in, &username), 0);
+    if (username.allocated)
+	min_offset =3D min(min_offset, username.offset);
     CHECK(ret_sec_buffer(in, &ws), 0);
-    if (lm.offset >=3D 60) {
+    if (ws.allocated)
+	min_offset =3D min(min_offset, ws.offset);
+
+    if (min_offset > 52) {
 	CHECK(ret_sec_buffer(in, &sessionkey), 0);
-    }
-    if (lm.offset >=3D 64) {
+	min_offset =3D max(min_offset, sessionkey.offset);
 	CHECK(krb5_ret_uint32(in, &type3->flags), 0);
     }
-    if (lm.offset >=3D 72) {
+    if (min_offset > 52 + 8 + 4 + 8) {
 	CHECK(krb5_ret_uint32(in, &type3->os[0]), 0);
 	CHECK(krb5_ret_uint32(in, &type3->os[1]), 0);
     }
     CHECK(ret_buf(in, &lm, &type3->lm), 0);
     CHECK(ret_buf(in, &ntlm, &type3->ntlm), 0);
-    CHECK(ret_string(in, ucs2, &target, &type3->targetname), 0);
-    CHECK(ret_string(in, ucs2, &username, &type3->username), 0);
-    CHECK(ret_string(in, ucs2, &ws, &type3->ws), 0);
+    CHECK(ret_sec_string(in, ucs2, &target, &type3->targetname), 0);
+    CHECK(ret_sec_string(in, ucs2, &username, &type3->username), 0);
+    CHECK(ret_sec_string(in, ucs2, &ws, &type3->ws), 0);
     if (sessionkey.offset)
 	CHECK(ret_buf(in, &sessionkey, &type3->sessionkey), 0);
=20
 out:
-    krb5_storage_free(in);
+    if (in)
+	krb5_storage_free(in);
     if (ret)
 	heim_ntlm_free_type3(type3);
=20
@@ -774,10 +929,10 @@
     memset(&sessionkey, 0, sizeof(sessionkey));
=20
     base =3D 52;
-    if (type3->sessionkey.length) {
-	base +=3D 8; /* sessionkey sec buf */
-	base +=3D 4; /* flags */
-    }
+
+    base +=3D 8; /* sessionkey sec buf */
+    base +=3D 4; /* flags */
+
     if (type3->os[0]) {
 	base +=3D 8;
     }
@@ -785,15 +940,7 @@
     if (type3->flags & NTLM_NEG_UNICODE)
 	ucs2 =3D 1;
=20
-    lm.offset =3D base;
-    lm.length =3D type3->lm.length;
-    lm.allocated =3D type3->lm.length;
-
-    ntlm.offset =3D lm.offset + lm.allocated;
-    ntlm.length =3D type3->ntlm.length;
-    ntlm.allocated =3D ntlm.length;
-
-    target.offset =3D ntlm.offset + ntlm.allocated;
+    target.offset =3D base;
     target.length =3D len_string(ucs2, type3->targetname);
     target.allocated =3D target.length;
=20
@@ -805,7 +952,15 @@
     ws.length =3D len_string(ucs2, type3->ws);
     ws.allocated =3D ws.length;
=20
-    sessionkey.offset =3D ws.offset + ws.allocated;
+    lm.offset =3D ws.offset + ws.allocated;
+    lm.length =3D type3->lm.length;
+    lm.allocated =3D type3->lm.length;
+
+    ntlm.offset =3D lm.offset + lm.allocated;
+    ntlm.length =3D type3->ntlm.length;
+    ntlm.allocated =3D ntlm.length;
+
+    sessionkey.offset =3D ntlm.offset + ntlm.allocated;
     sessionkey.length =3D type3->sessionkey.length;
     sessionkey.allocated =3D type3->sessionkey.length;
=20
@@ -814,7 +969,7 @@
 	return ENOMEM;
=20
     krb5_storage_set_byteorder(out, KRB5_STORAGE_BYTEORDER_LE);
-    CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),=20
+    CHECK(krb5_storage_write(out, ntlmsigature, sizeof(ntlmsigature)),
 	  sizeof(ntlmsigature));
     CHECK(krb5_store_uint32(out, 3), 0);
=20
@@ -823,23 +978,21 @@
     CHECK(store_sec_buffer(out, &target), 0);
     CHECK(store_sec_buffer(out, &username), 0);
     CHECK(store_sec_buffer(out, &ws), 0);
-    /* optional */
-    if (type3->sessionkey.length) {
-	CHECK(store_sec_buffer(out, &sessionkey), 0);
-	CHECK(krb5_store_uint32(out, type3->flags), 0);
-    }
+    CHECK(store_sec_buffer(out, &sessionkey), 0);
+    CHECK(krb5_store_uint32(out, type3->flags), 0);
+
 #if 0
     CHECK(krb5_store_uint32(out, 0), 0); /* os0 */
     CHECK(krb5_store_uint32(out, 0), 0); /* os1 */
 #endif
=20
-    CHECK(put_buf(out, &type3->lm), 0);
-    CHECK(put_buf(out, &type3->ntlm), 0);
     CHECK(put_string(out, ucs2, type3->targetname), 0);
     CHECK(put_string(out, ucs2, type3->username), 0);
     CHECK(put_string(out, ucs2, type3->ws), 0);
+    CHECK(put_buf(out, &type3->lm), 0);
+    CHECK(put_buf(out, &type3->ntlm), 0);
     CHECK(put_buf(out, &type3->sessionkey), 0);
-   =20
+
     {
 	krb5_data d;
 	ret =3D krb5_storage_to_data(out, &d);
@@ -859,26 +1012,27 @@
  */
=20
 static void
-splitandenc(unsigned char *hash,=20
-	    unsigned char *challange,
+splitandenc(unsigned char *hash,
+	    unsigned char *challenge,
 	    unsigned char *answer)
 {
-    DES_cblock key;
-    DES_key_schedule sched;
+    EVP_CIPHER_CTX ctx;
+    unsigned char key[8];
=20
-    ((unsigned char*)key)[0] =3D  hash[0];
-    ((unsigned char*)key)[1] =3D (hash[0] << 7) | (hash[1] >> 1);
-    ((unsigned char*)key)[2] =3D (hash[1] << 6) | (hash[2] >> 2);
-    ((unsigned char*)key)[3] =3D (hash[2] << 5) | (hash[3] >> 3);
-    ((unsigned char*)key)[4] =3D (hash[3] << 4) | (hash[4] >> 4);
-    ((unsigned char*)key)[5] =3D (hash[4] << 3) | (hash[5] >> 5);
-    ((unsigned char*)key)[6] =3D (hash[5] << 2) | (hash[6] >> 6);
-    ((unsigned char*)key)[7] =3D (hash[6] << 1);
+    key[0] =3D  hash[0];
+    key[1] =3D (hash[0] << 7) | (hash[1] >> 1);
+    key[2] =3D (hash[1] << 6) | (hash[2] >> 2);
+    key[3] =3D (hash[2] << 5) | (hash[3] >> 3);
+    key[4] =3D (hash[3] << 4) | (hash[4] >> 4);
+    key[5] =3D (hash[4] << 3) | (hash[5] >> 5);
+    key[6] =3D (hash[5] << 2) | (hash[6] >> 6);
+    key[7] =3D (hash[6] << 1);
=20
-    DES_set_odd_parity(&key);
-    DES_set_key(&key, &sched);
-    DES_ecb_encrypt((DES_cblock *)challange, (DES_cblock *)answer, &sched,=
 1);
-    memset(&sched, 0, sizeof(sched));
+    EVP_CIPHER_CTX_init(&ctx);
+
+    EVP_CipherInit_ex(&ctx, EVP_des_cbc(), NULL, key, NULL, 1);
+    EVP_Cipher(&ctx, answer, challenge, 8);
+    EVP_CIPHER_CTX_cleanup(&ctx);
     memset(key, 0, sizeof(key));
 }
=20
@@ -898,7 +1052,7 @@
 heim_ntlm_nt_key(const char *password, struct ntlm_buf *key)
 {
     struct ntlm_buf buf;
-    MD4_CTX ctx;
+    EVP_MD_CTX *m;
     int ret;
=20
     key->data =3D malloc(MD5_DIGEST_LENGTH);
@@ -911,9 +1065,19 @@
 	heim_ntlm_free_buf(key);
 	return ret;
     }
-    MD4_Init(&ctx);
-    MD4_Update(&ctx, buf.data, buf.length);
-    MD4_Final(key->data, &ctx);
+
+    m =3D EVP_MD_CTX_create();
+    if (m =3D=3D NULL) {
+	heim_ntlm_free_buf(key);
+	heim_ntlm_free_buf(&buf);
+	return ENOMEM;
+    }
+
+    EVP_DigestInit_ex(m, EVP_md4(), NULL);
+    EVP_DigestUpdate(m, buf.data, buf.length);
+    EVP_DigestFinal_ex(m, key->data, NULL);
+    EVP_MD_CTX_destroy(m);
+
     heim_ntlm_free_buf(&buf);
     return 0;
 }
@@ -923,7 +1087,7 @@
  *
  * @param key the ntlm v1 key
  * @param len length of key
- * @param challange sent by the server
+ * @param challenge sent by the server
  * @param answer calculated answer, should be freed with heim_ntlm_free_bu=
f().
  *
  * @return In case of success 0 is return, an errors, a errno in what
@@ -934,13 +1098,13 @@
=20
 int
 heim_ntlm_calculate_ntlm1(void *key, size_t len,
-			  unsigned char challange[8],
+			  unsigned char challenge[8],
 			  struct ntlm_buf *answer)
 {
     unsigned char res[21];
=20
     if (len !=3D MD4_DIGEST_LENGTH)
-	return EINVAL;
+	return HNTLM_ERR_INVALID_LENGTH;
=20
     memcpy(res, key, len);
     memset(&res[MD4_DIGEST_LENGTH], 0, sizeof(res) - MD4_DIGEST_LENGTH);
@@ -950,13 +1114,116 @@
 	return ENOMEM;
     answer->length =3D 24;
=20
-    splitandenc(&res[0],  challange, ((unsigned char *)answer->data) + 0);
-    splitandenc(&res[7],  challange, ((unsigned char *)answer->data) + 8);
-    splitandenc(&res[14], challange, ((unsigned char *)answer->data) + 16);
+    splitandenc(&res[0],  challenge, ((unsigned char *)answer->data) + 0);
+    splitandenc(&res[7],  challenge, ((unsigned char *)answer->data) + 8);
+    splitandenc(&res[14], challenge, ((unsigned char *)answer->data) + 16);
=20
     return 0;
 }
=20
+int
+heim_ntlm_v1_base_session(void *key, size_t len,
+			  struct ntlm_buf *session)
+{
+    EVP_MD_CTX *m;
+
+    session->length =3D MD4_DIGEST_LENGTH;
+    session->data =3D malloc(session->length);
+    if (session->data =3D=3D NULL) {
+	session->length =3D 0;
+	return ENOMEM;
+    }
+
+    m =3D EVP_MD_CTX_create();
+    if (m =3D=3D NULL) {
+	heim_ntlm_free_buf(session);
+	return ENOMEM;
+    }
+    EVP_DigestInit_ex(m, EVP_md4(), NULL);
+    EVP_DigestUpdate(m, key, len);
+    EVP_DigestFinal_ex(m, session->data, NULL);
+    EVP_MD_CTX_destroy(m);
+
+    return 0;
+}
+
+int
+heim_ntlm_v2_base_session(void *key, size_t len,
+			  struct ntlm_buf *ntlmResponse,
+			  struct ntlm_buf *session)
+{
+    unsigned int hmaclen;
+    HMAC_CTX c;
+
+    if (ntlmResponse->length <=3D 16)
+        return HNTLM_ERR_INVALID_LENGTH;
+
+    session->data =3D malloc(16);
+    if (session->data =3D=3D NULL)
+	return ENOMEM;
+    session->length =3D 16;
+
+    /* Note: key is the NTLMv2 key */
+    HMAC_CTX_init(&c);
+    HMAC_Init_ex(&c, key, len, EVP_md5(), NULL);
+    HMAC_Update(&c, ntlmResponse->data, 16);
+    HMAC_Final(&c, session->data, &hmaclen);
+    HMAC_CTX_cleanup(&c);
+
+    return 0;
+}
+
+
+int
+heim_ntlm_keyex_wrap(struct ntlm_buf *base_session,
+		     struct ntlm_buf *session,
+		     struct ntlm_buf *encryptedSession)
+{
+    EVP_CIPHER_CTX c;
+    int ret;
+
+    session->length =3D MD4_DIGEST_LENGTH;
+    session->data =3D malloc(session->length);
+    if (session->data =3D=3D NULL) {
+	session->length =3D 0;
+	return ENOMEM;
+    }
+    encryptedSession->length =3D MD4_DIGEST_LENGTH;
+    encryptedSession->data =3D malloc(encryptedSession->length);
+    if (encryptedSession->data =3D=3D NULL) {
+	heim_ntlm_free_buf(session);
+	encryptedSession->length =3D 0;
+	return ENOMEM;
+    }
+
+    EVP_CIPHER_CTX_init(&c);
+
+    ret =3D EVP_CipherInit_ex(&c, EVP_rc4(), NULL, base_session->data, NUL=
L, 1);
+    if (ret !=3D 1) {
+	EVP_CIPHER_CTX_cleanup(&c);
+	heim_ntlm_free_buf(encryptedSession);
+	heim_ntlm_free_buf(session);
+	return HNTLM_ERR_CRYPTO;
+    }
+
+    if (RAND_bytes(session->data, session->length) !=3D 1) {
+	EVP_CIPHER_CTX_cleanup(&c);
+	heim_ntlm_free_buf(encryptedSession);
+	heim_ntlm_free_buf(session);
+	return HNTLM_ERR_RAND;
+    }
+
+    EVP_Cipher(&c, encryptedSession->data, session->data, encryptedSession=
->length);
+    EVP_CIPHER_CTX_cleanup(&c);
+
+    return 0;
+
+
+
+}
+
+
+
 /**
  * Generates an NTLMv1 session random with assosited session master key.
  *
@@ -976,51 +1243,100 @@
 			     struct ntlm_buf *session,
 			     struct ntlm_buf *master)
 {
-    RC4_KEY rc4;
+    struct ntlm_buf sess;
+    int ret;
=20
-    memset(master, 0, sizeof(*master));
+    ret =3D heim_ntlm_v1_base_session(key, len, &sess);
+    if (ret)
+	return ret;
+
+    ret =3D heim_ntlm_keyex_wrap(&sess, session, master);
+    heim_ntlm_free_buf(&sess);
+
+    return ret;
+}
+
+/**
+ * Generates an NTLMv2 session random with associated session master key.
+ *
+ * @param key the NTLMv2 key
+ * @param len length of key
+ * @param blob the NTLMv2 "blob"
+ * @param session generated session nonce, should be freed with heim_ntlm_=
free_buf().
+ * @param master calculated session master key, should be freed with heim_=
ntlm_free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+
+int
+heim_ntlm_build_ntlm2_master(void *key, size_t len,
+			     struct ntlm_buf *blob,
+			     struct ntlm_buf *session,
+			     struct ntlm_buf *master)
+{
+    struct ntlm_buf sess;
+    int ret;
+
+    ret =3D heim_ntlm_v2_base_session(key, len, blob, &sess);
+    if (ret)
+	return ret;
+
+    ret =3D heim_ntlm_keyex_wrap(&sess, session, master);
+    heim_ntlm_free_buf(&sess);
+
+    return ret;
+}
+
+/**
+ * Given a key and encrypted session, unwrap the session key
+ *
+ * @param baseKey the sessionBaseKey
+ * @param encryptedSession encrypted session, type3.session field.
+ * @param session generated session nonce, should be freed with heim_ntlm_=
free_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_keyex_unwrap(struct ntlm_buf *baseKey,
+		       struct ntlm_buf *encryptedSession,
+		       struct ntlm_buf *session)
+{
+    EVP_CIPHER_CTX c;
+
     memset(session, 0, sizeof(*session));
=20
-    if (len !=3D MD4_DIGEST_LENGTH)
-	return EINVAL;
-   =20
+    if (baseKey->length !=3D MD4_DIGEST_LENGTH)
+	return HNTLM_ERR_INVALID_LENGTH;
+
     session->length =3D MD4_DIGEST_LENGTH;
     session->data =3D malloc(session->length);
     if (session->data =3D=3D NULL) {
 	session->length =3D 0;
-	return EINVAL;
-    }   =20
-    master->length =3D MD4_DIGEST_LENGTH;
-    master->data =3D malloc(master->length);
-    if (master->data =3D=3D NULL) {
-	heim_ntlm_free_buf(master);
+	return ENOMEM;
+    }
+    EVP_CIPHER_CTX_init(&c);
+
+    if (EVP_CipherInit_ex(&c, EVP_rc4(), NULL, baseKey->data, NULL, 0) !=
=3D 1) {
+	EVP_CIPHER_CTX_cleanup(&c);
 	heim_ntlm_free_buf(session);
-	return EINVAL;
+	return HNTLM_ERR_CRYPTO;
     }
-   =20
-    {
-	unsigned char sessionkey[MD4_DIGEST_LENGTH];
-	MD4_CTX ctx;
-   =20
-	MD4_Init(&ctx);
-	MD4_Update(&ctx, key, len);
-	MD4_Final(sessionkey, &ctx);
-=09
-	RC4_set_key(&rc4, sizeof(sessionkey), sessionkey);
-    }
-   =20
-    if (RAND_bytes(session->data, session->length) !=3D 1) {
-	heim_ntlm_free_buf(master);
-	heim_ntlm_free_buf(session);
-	return EINVAL;
-    }
-   =20
-    RC4(&rc4, master->length, session->data, master->data);
-    memset(&rc4, 0, sizeof(rc4));
-   =20
+
+    EVP_Cipher(&c, session->data, encryptedSession->data, session->length);
+    EVP_CIPHER_CTX_cleanup(&c);
+
     return 0;
 }
=20
+
 /**
  * Generates an NTLMv2 session key.
  *
@@ -1030,15 +1346,18 @@
  * @param target the name of the target, assumed to be in UTF8.
  * @param ntlmv2 the ntlmv2 session key
  *
+ * @return 0 on success, or an error code on failure.
+ *
  * @ingroup ntlm_core
  */
=20
-void
+int
 heim_ntlm_ntlmv2_key(const void *key, size_t len,
 		     const char *username,
 		     const char *target,
 		     unsigned char ntlmv2[16])
 {
+    int ret;
     unsigned int hmaclen;
     HMAC_CTX c;
=20
@@ -1046,18 +1365,24 @@
     HMAC_Init_ex(&c, key, len, EVP_md5(), NULL);
     {
 	struct ntlm_buf buf;
-	/* uppercase username and turn it inte ucs2-le */
-	ascii2ucs2le(username, 1, &buf);
+	/* uppercase username and turn it into ucs2-le */
+	ret =3D ascii2ucs2le(username, 1, &buf);
+	if (ret)
+	    goto out;
 	HMAC_Update(&c, buf.data, buf.length);
 	free(buf.data);
 	/* uppercase target and turn into ucs2-le */
-	ascii2ucs2le(target, 1, &buf);
+	ret =3D ascii2ucs2le(target, 1, &buf);
+	if (ret)
+	    goto out;
 	HMAC_Update(&c, buf.data, buf.length);
 	free(buf.data);
     }
     HMAC_Final(&c, ntlmv2, &hmaclen);
+ out:
     HMAC_CTX_cleanup(&c);
=20
+    return ret;
 }
=20
 /*
@@ -1078,11 +1403,58 @@
 nt2unixtime(uint64_t t)
 {
     t =3D ((t - (uint64_t)NTTIME_EPOCH) / (uint64_t)10000000);
-    if (t > (((time_t)(~(uint64_t)0)) >> 1))
+    if (t > (((uint64_t)(time_t)(~(uint64_t)0)) >> 1))
 	return 0;
     return (time_t)t;
 }
=20
+/**
+ * Calculate LMv2 response
+ *
+ * @param key the ntlm key
+ * @param len length of key
+ * @param username name of the user, as sent in the message, assumed to be=
 in UTF8.
+ * @param target the name of the target, assumed to be in UTF8.
+ * @param serverchallenge challenge as sent by the server in the type2 mes=
sage.
+ * @param ntlmv2 calculated session key
+ * @param answer ntlm response answer, should be freed with heim_ntlm_free=
_buf().
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_calculate_lm2(const void *key, size_t len,
+			const char *username,
+			const char *target,
+			const unsigned char serverchallenge[8],
+			unsigned char ntlmv2[16],
+			struct ntlm_buf *answer)
+{
+    unsigned char clientchallenge[8];
+
+    if (RAND_bytes(clientchallenge, sizeof(clientchallenge)) !=3D 1)
+	return HNTLM_ERR_RAND;
+
+    /* calculate ntlmv2 key */
+
+    heim_ntlm_ntlmv2_key(key, len, username, target, ntlmv2);
+
+    answer->data =3D malloc(24);
+    if (answer->data =3D=3D NULL)
+        return ENOMEM;
+    answer->length =3D 24;
+
+    heim_ntlm_derive_ntlm2_sess(ntlmv2, clientchallenge, 8,
+				serverchallenge, answer->data);
+
+    memcpy(((uint8_t *)answer->data) + 16, clientchallenge, 8);
+
+    return 0;
+}
+
=20
 /**
  * Calculate NTLMv2 response
@@ -1091,7 +1463,7 @@
  * @param len length of key
  * @param username name of the user, as sent in the message, assumed to be=
 in UTF8.
  * @param target the name of the target, assumed to be in UTF8.
- * @param serverchallange challange as sent by the server in the type2 mes=
sage.
+ * @param serverchallenge challenge as sent by the server in the type2 mes=
sage.
  * @param infotarget infotarget as sent by the server in the type2 message.
  * @param ntlmv2 calculated session key
  * @param answer ntlm response answer, should be freed with heim_ntlm_free=
_buf().
@@ -1106,25 +1478,23 @@
 heim_ntlm_calculate_ntlm2(const void *key, size_t len,
 			  const char *username,
 			  const char *target,
-			  const unsigned char serverchallange[8],
+			  const unsigned char serverchallenge[8],
 			  const struct ntlm_buf *infotarget,
 			  unsigned char ntlmv2[16],
 			  struct ntlm_buf *answer)
 {
     krb5_error_code ret;
     krb5_data data;
-    unsigned int hmaclen;
     unsigned char ntlmv2answer[16];
     krb5_storage *sp;
-    unsigned char clientchallange[8];
-    HMAC_CTX c;
+    unsigned char clientchallenge[8];
     uint64_t t;
-   =20
+
     t =3D unix2nttime(time(NULL));
=20
-    if (RAND_bytes(clientchallange, sizeof(clientchallange)) !=3D 1)
-	return EINVAL;
-   =20
+    if (RAND_bytes(clientchallenge, sizeof(clientchallenge)) !=3D 1)
+	return HNTLM_ERR_RAND;
+
     /* calculate ntlmv2 key */
=20
     heim_ntlm_ntlmv2_key(key, len, username, target, ntlmv2);
@@ -1142,23 +1512,18 @@
     CHECK(krb5_store_uint32(sp, t & 0xffffffff), 0);
     CHECK(krb5_store_uint32(sp, t >> 32), 0);
=20
-    CHECK(krb5_storage_write(sp, clientchallange, 8), 8);
+    CHECK(krb5_storage_write(sp, clientchallenge, 8), 8);
=20
     CHECK(krb5_store_uint32(sp, 0), 0);  /* unknown but zero will work */
-    CHECK(krb5_storage_write(sp, infotarget->data, infotarget->length),=20
+    CHECK(krb5_storage_write(sp, infotarget->data, infotarget->length),
 	  infotarget->length);
     CHECK(krb5_store_uint32(sp, 0), 0); /* unknown but zero will work */
-   =20
+
     CHECK(krb5_storage_to_data(sp, &data), 0);
     krb5_storage_free(sp);
     sp =3D NULL;
=20
-    HMAC_CTX_init(&c);
-    HMAC_Init_ex(&c, ntlmv2, 16, EVP_md5(), NULL);
-    HMAC_Update(&c, serverchallange, 8);
-    HMAC_Update(&c, data.data, data.length);
-    HMAC_Final(&c, ntlmv2answer, &hmaclen);
-    HMAC_CTX_cleanup(&c);
+    heim_ntlm_derive_ntlm2_sess(ntlmv2, data.data, data.length, serverchal=
lenge, ntlmv2answer);
=20
     sp =3D krb5_storage_emem();
     if (sp =3D=3D NULL) {
@@ -1169,7 +1534,7 @@
     CHECK(krb5_storage_write(sp, ntlmv2answer, 16), 16);
     CHECK(krb5_storage_write(sp, data.data, data.length), data.length);
     krb5_data_free(&data);
-   =20
+
     CHECK(krb5_storage_to_data(sp, &data), 0);
     krb5_storage_free(sp);
     sp =3D NULL;
@@ -1194,7 +1559,7 @@
  * @param username name of the user, as sent in the message, assumed to be=
 in UTF8.
  * @param target the name of the target, assumed to be in UTF8.
  * @param now the time now (0 if the library should pick it up itself)
- * @param serverchallange challange as sent by the server in the type2 mes=
sage.
+ * @param serverchallenge challenge as sent by the server in the type2 mes=
sage.
  * @param answer ntlm response answer, should be freed with heim_ntlm_free=
_buf().
  * @param infotarget infotarget as sent by the server in the type2 message.
  * @param ntlmv2 calculated session key
@@ -1210,27 +1575,25 @@
 		       const char *username,
 		       const char *target,
 		       time_t now,
-		       const unsigned char serverchallange[8],
+		       const unsigned char serverchallenge[8],
 		       const struct ntlm_buf *answer,
 		       struct ntlm_buf *infotarget,
 		       unsigned char ntlmv2[16])
 {
     krb5_error_code ret;
-    unsigned int hmaclen;
     unsigned char clientanswer[16];
     unsigned char clientnonce[8];
     unsigned char serveranswer[16];
     krb5_storage *sp;
-    HMAC_CTX c;
-    uint64_t t;
     time_t authtime;
     uint32_t temp;
+    uint64_t t;
=20
-    infotarget->length =3D 0;   =20
-    infotarget->data =3D NULL;   =20
+    infotarget->length =3D 0;
+    infotarget->data =3D NULL;
=20
     if (answer->length < 16)
-	return EINVAL;
+	return HNTLM_ERR_INVALID_LENGTH;
=20
     if (now =3D=3D 0)
 	now =3D time(NULL);
@@ -1261,11 +1624,11 @@
     authtime =3D nt2unixtime(t);
=20
     if (abs((int)(authtime - now)) > authtimediff) {
-	ret =3D EINVAL;
+	ret =3D HNTLM_ERR_TIME_SKEW;
 	goto out;
     }
=20
-    /* client challange */
+    /* client challenge */
     CHECK(krb5_storage_read(sp, clientnonce, 8), 8);
=20
     CHECK(krb5_ret_uint32(sp, &temp), 0); /* unknown */
@@ -1277,22 +1640,25 @@
 	ret =3D ENOMEM;
 	goto out;
     }
-    CHECK(krb5_storage_read(sp, infotarget->data, infotarget->length),=20
+    CHECK(krb5_storage_read(sp, infotarget->data, infotarget->length),
 	  infotarget->length);
     /* XXX remove the unknown ?? */
     krb5_storage_free(sp);
     sp =3D NULL;
=20
-    HMAC_CTX_init(&c);
-    HMAC_Init_ex(&c, ntlmv2, 16, EVP_md5(), NULL);
-    HMAC_Update(&c, serverchallange, 8);
-    HMAC_Update(&c, ((unsigned char *)answer->data) + 16, answer->length -=
 16);
-    HMAC_Final(&c, serveranswer, &hmaclen);
-    HMAC_CTX_cleanup(&c);
+    if (answer->length < 16) {
+	ret =3D HNTLM_ERR_INVALID_LENGTH;
+	goto out;
+    }
+
+    heim_ntlm_derive_ntlm2_sess(ntlmv2,
+				((unsigned char *)answer->data) + 16, answer->length - 16,
+				serverchallenge,
+				serveranswer);
=20
     if (memcmp(serveranswer, clientanswer, 16) !=3D 0) {
 	heim_ntlm_free_buf(infotarget);
-	return EINVAL;
+	return HNTLM_ERR_AUTH;
     }
=20
     return 0;
@@ -1326,13 +1692,20 @@
 			       struct ntlm_buf *lm,
 			       struct ntlm_buf *ntlm)
 {
-    unsigned char ntlm2_sess_hash[MD5_DIGEST_LENGTH];
+    unsigned char ntlm2_sess_hash[8];
     unsigned char res[21], *resp;
-    MD5_CTX md5;
+    int code;
+
+    code =3D heim_ntlm_calculate_ntlm2_sess_hash(clnt_nonce, svr_chal,
+					       ntlm2_sess_hash);
+    if (code) {
+	return code;
+    }
=20
     lm->data =3D malloc(24);
-    if (lm->data =3D=3D NULL)
+    if (lm->data =3D=3D NULL) {
 	return ENOMEM;
+    }
     lm->length =3D 24;
=20
     ntlm->data =3D malloc(24);
@@ -1347,11 +1720,6 @@
     memset(lm->data, 0, 24);
     memcpy(lm->data, clnt_nonce, 8);
=20
-    MD5_Init(&md5);
-    MD5_Update(&md5, svr_chal, 8); /* session nonce part 1 */
-    MD5_Update(&md5, clnt_nonce, 8); /* session nonce part 2 */
-    MD5_Final(ntlm2_sess_hash, &md5); /* will only use first 8 bytes */
-
     memset(res, 0, sizeof(res));
     memcpy(res, ntlm_hash, 16);
=20
@@ -1362,3 +1730,74 @@
=20
     return 0;
 }
+
+
+/*
+ * Calculate the NTLM2 Session "Verifier"
+ *
+ * @param clnt_nonce client nonce
+ * @param svr_chal server challage
+ * @param hash The NTLM session verifier
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+int
+heim_ntlm_calculate_ntlm2_sess_hash(const unsigned char clnt_nonce[8],
+				    const unsigned char svr_chal[8],
+				    unsigned char verifier[8])
+{
+    unsigned char ntlm2_sess_hash[MD5_DIGEST_LENGTH];
+    EVP_MD_CTX *m;
+
+    m =3D EVP_MD_CTX_create();
+    if (m =3D=3D NULL)
+	return ENOMEM;
+
+    EVP_DigestInit_ex(m, EVP_md5(), NULL);
+    EVP_DigestUpdate(m, svr_chal, 8); /* session nonce part 1 */
+    EVP_DigestUpdate(m, clnt_nonce, 8); /* session nonce part 2 */
+    EVP_DigestFinal_ex(m, ntlm2_sess_hash, NULL); /* will only use first 8=
 bytes */
+    EVP_MD_CTX_destroy(m);
+
+    memcpy(verifier, ntlm2_sess_hash, 8);
+
+    return 0;
+}
+
+
+/*
+ * Derive a NTLM2 session key
+ *
+ * @param sessionkey session key from domain controller
+ * @param clnt_nonce client nonce
+ * @param svr_chal server challenge
+ * @param derivedkey salted session key
+ *
+ * @return In case of success 0 is return, an errors, a errno in what
+ * went wrong.
+ *
+ * @ingroup ntlm_core
+ */
+
+void
+heim_ntlm_derive_ntlm2_sess(const unsigned char sessionkey[16],
+			    const unsigned char *clnt_nonce, size_t clnt_nonce_length,
+			    const unsigned char svr_chal[8],
+			    unsigned char derivedkey[16])
+{
+    unsigned int hmaclen;
+    HMAC_CTX c;
+
+    /* HMAC(Ksession, serverchallenge || clientchallenge) */
+    HMAC_CTX_init(&c);
+    HMAC_Init_ex(&c, sessionkey, 16, EVP_md5(), NULL);
+    HMAC_Update(&c, svr_chal, 8);
+    HMAC_Update(&c, clnt_nonce, clnt_nonce_length);
+    HMAC_Final(&c, derivedkey, &hmaclen);
+    HMAC_CTX_cleanup(&c);
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/test_ntlm=
.c
--- a/head/crypto/heimdal/lib/ntlm/test_ntlm.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/ntlm/test_ntlm.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 - 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 - 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -38,15 +38,13 @@
 #include <roken.h>
 #include <getarg.h>
=20
-RCSID("$Id: test_ntlm.c 22377 2007-12-28 18:38:53Z lha $");
-
-#include <krb5.h>
+#include <krb5-types.h> /* or <inttypes.h> */
 #include <heimntlm.h>
=20
 static int
 test_parse(void)
 {
-    const char *user =3D "foo",=20
+    const char *user =3D "foo",
 	*domain =3D "mydomain",
 	*password =3D "digestpassword",
 	*target =3D "DOMAIN";
@@ -54,9 +52,8 @@
     struct ntlm_type2 type2;
     struct ntlm_type3 type3;
     struct ntlm_buf data;
-    krb5_error_code ret;
-    int flags;
-   =20
+    int ret, flags;
+
     memset(&type1, 0, sizeof(type1));
=20
     type1.flags =3D NTLM_NEG_UNICODE|NTLM_NEG_TARGET|NTLM_NEG_NTLM;
@@ -87,7 +84,7 @@
     flags =3D NTLM_NEG_UNICODE | NTLM_NEG_NTLM | NTLM_TARGET_DOMAIN;
     type2.flags =3D flags;
=20
-    memset(type2.challange, 0x7f, sizeof(type2.challange));
+    memset(type2.challenge, 0x7f, sizeof(type2.challenge));
     type2.targetname =3D rk_UNCONST(target);
     type2.targetinfo.data =3D NULL;
     type2.targetinfo.length =3D 0;
@@ -121,7 +118,7 @@
 	heim_ntlm_nt_key(password, &key);
=20
 	heim_ntlm_calculate_ntlm1(key.data, key.length,
-				  type2.challange,
+				  type2.challenge,
 				  &type3.ntlm);
 	free(key.data);
     }
@@ -160,7 +157,7 @@
     flags =3D NTLM_NEG_UNICODE | NTLM_NEG_NTLM | NTLM_TARGET_DOMAIN;
     type2.flags =3D flags;
=20
-    memset(type2.challange, 0x7f, sizeof(type2.challange));
+    memset(type2.challenge, 0x7f, sizeof(type2.challenge));
     type2.targetname =3D rk_UNCONST(target);
     type2.targetinfo.data =3D "\x00\x00";
     type2.targetinfo.length =3D 2;
@@ -188,12 +185,12 @@
 	*username =3D "test",
 	*password =3D "test1234",
 	*target =3D "TESTNT";
-    const unsigned char=20
-	serverchallange[8] =3D "\x67\x7f\x1c\x55\x7a\x5e\xe9\x6c";
+    const unsigned char
+	serverchallenge[8] =3D "\x67\x7f\x1c\x55\x7a\x5e\xe9\x6c";
     struct ntlm_buf infotarget, infotarget2, answer, key;
     unsigned char ntlmv2[16], ntlmv2_1[16];
     int ret;
-   =20
+
     infotarget.length =3D 70;
     infotarget.data =3D
 	"\x02\x00\x0c\x00\x54\x00\x45\x00\x53\x00\x54\x00\x4e\x00\x54\x00"
@@ -212,7 +209,7 @@
 				    key.length,
 				    username,
 				    target,
-				    serverchallange,
+				    serverchallenge,
 				    &infotarget,
 				    ntlmv2,
 				    &answer);
@@ -224,7 +221,7 @@
 				 username,
 				 target,
 				 0,
-				 serverchallange,
+				 serverchallenge,
 				 &answer,
 				 &infotarget2,
 				 ntlmv2_1);
@@ -253,18 +250,18 @@
     int ret;
     struct ntlm_buf lm, ntlm;
=20
-    const unsigned char lm_resp[24] =3D=20
+    const unsigned char lm_resp[24] =3D
 	"\xff\xff\xff\x00\x11\x22\x33\x44"
 	"\x00\x00\x00\x00\x00\x00\x00\x00"
 	"\x00\x00\x00\x00\x00\x00\x00\x00";
-    const unsigned char ntlm2_sess_resp[24] =3D=20
+    const unsigned char ntlm2_sess_resp[24] =3D
 	"\x10\xd5\x50\x83\x2d\x12\xb2\xcc"
 	"\xb7\x9d\x5a\xd1\xf4\xee\xd3\xdf"
 	"\x82\xac\xa4\xc3\x68\x1d\xd4\x55";
-   =20
+
     const unsigned char client_nonce[8] =3D
 	"\xff\xff\xff\x00\x11\x22\x33\x44";
-    const unsigned char server_challange[8] =3D
+    const unsigned char server_challenge[8] =3D
 	"\x01\x23\x45\x67\x89\xab\xcd\xef";
=20
     const unsigned char ntlm_hash[16] =3D
@@ -272,7 +269,7 @@
 	"\x1d\x33\xb7\x48\x5a\x2e\xd8\x08";
=20
     ret =3D heim_ntlm_calculate_ntlm2_sess(client_nonce,
-					 server_challange,
+					 server_challenge,
 					 ntlm_hash,
 					 &lm,
 					 &ntlm);
@@ -283,7 +280,7 @@
 	errx(1, "lm_resp wrong");
     if (ntlm.length !=3D 24 || memcmp(ntlm.data, ntlm2_sess_resp, 24) !=3D=
 0)
 	errx(1, "ntlm2_sess_resp wrong");
-   =20
+
     free(lm.data);
     free(ntlm.data);
=20
@@ -291,10 +288,45 @@
     return 0;
 }
=20
+static int
+test_targetinfo(void)
+{
+    struct ntlm_targetinfo ti;
+    struct ntlm_buf buf;
+    const char *dnsservername =3D "dnsservername";
+    int ret;
+
+    memset(&ti, 0, sizeof(ti));
+
+    ti.dnsservername =3D rk_UNCONST(dnsservername);
+    ti.avflags =3D 1;
+    ret =3D heim_ntlm_encode_targetinfo(&ti, 1, &buf);
+    if (ret)
+	return ret;
+
+    memset(&ti, 0, sizeof(ti));
+
+    ret =3D heim_ntlm_decode_targetinfo(&buf, 1, &ti);
+    if (ret)
+	return ret;
+
+    if (ti.dnsservername =3D=3D NULL ||
+	strcmp(ti.dnsservername, dnsservername) !=3D 0)
+	errx(1, "ti.dnshostname !=3D %s", dnsservername);
+    if (ti.avflags !=3D 1)
+	errx(1, "ti.avflags !=3D 1");
+
+    heim_ntlm_free_targetinfo(&ti);
+
+    return 0;
+}
+
+static int verbose_flag =3D 0;
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
 static struct getargs args[] =3D {
+    {"verbose",	0,	arg_flag,	&verbose_flag, "verbose printing", NULL },
     {"version",	0,	arg_flag,	&version_flag, "print version", NULL },
     {"help",	0,	arg_flag,	&help_flag,  NULL, NULL }
 };
@@ -316,7 +348,7 @@
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optind))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -328,12 +360,21 @@
     argc -=3D optind;
     argv +=3D optind;
=20
-    printf("test_parse\n");
+    if (verbose_flag)
+	printf("test_parse\n");
+
     ret +=3D test_parse();
-    printf("test_keys\n");
+    if (verbose_flag)
+	printf("test_keys\n");
+
     ret +=3D test_keys();
-    printf("test_ntlm2_session_resp\n");
+    if (verbose_flag)
+	printf("test_ntlm2_session_resp\n");
     ret +=3D test_ntlm2_session_resp();
=20
-    return 0;
+    if (verbose_flag)
+	printf("test_targetinfo\n");
+    ret +=3D test_targetinfo();
+
+    return ret;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/ntlm/version-s=
cript.map
--- a/head/crypto/heimdal/lib/ntlm/version-script.map	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/ntlm/version-script.map	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,8 +1,9 @@
-# $Id: version-script.map 22041 2007-11-11 07:43:27Z lha $
+# $Id$
=20
 HEIMDAL_NTLM_1.0 {
 	global:
 		heim_ntlm_build_ntlm1_master;
+		heim_ntlm_calculate_lm2;
 		heim_ntlm_calculate_ntlm1;
 		heim_ntlm_calculate_ntlm2;
 		heim_ntlm_calculate_ntlm2_sess;
@@ -22,6 +23,8 @@
 		heim_ntlm_nt_key;
 		heim_ntlm_ntlmv2_key;
 		heim_ntlm_verify_ntlm2;
+		heim_ntlm_unparse_flags;
+		initialize_ntlm_error_table_r;
 	local:
 		*;
 };
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/ChangeLog
--- a/head/crypto/heimdal/lib/roken/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,41 @@
-2008-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-07-12  Love H=C3=B6rnquist =C3=85strand  <lha at kth.se>
+
+	* rkpty.c: Always print output for status.
+
+2008-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+=09
+	* getaddrinfo-test.c: drop )
+
+	* Makefile.am: Add rkpty.
+
+	* rkpty.c: More includes.
+
+	* rkpty.c: Add timeout, add password command, add diffrent
+	verbosity levels.
+
+2008-04-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* rkpty.c: pty testing application
+
+2008-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* resolve.c: Use unsigned where appropriate.
+
+2008-02-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Makefile.am: make AM_CPPFLAGS +=3D
+
+2008-02-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
+
+	* Makefile.am: Use AM_CPPFLAGS instead, not really right, but
+	definatly better then CPPFLAGS. Thanks to Mike Whitton for
+	pointing this out.
+
+2008-01-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add missing files.
=20
-2007-08-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-08-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* strftime.c: rewrite str[pf]time for testing.
=20
@@ -10,7 +43,7 @@
=20
 	* Makefile.am: add TEST_STRPFTIME
 =09
-2007-07-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ndbm_wrap.c (dbm_get): set dsize to 0 on failure.
=20
@@ -18,7 +51,7 @@
=20
 	* ndbm_wrap.c (dbm_fetch): set dsize to 0 on failure.
=20
-2007-07-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* socket_wrapper.c: Implement swrap_dup too.
=20
@@ -26,19 +59,19 @@
=20
 	* socket_wrapper.h: Add dup(dummy stub) and dup2(real).
=20
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: New library version.
=20
-2007-06-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken_gethostby.c: set proxy_port to 0 to pacify BEAM.
=20
-2007-06-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* use "roken.h" consitantly
=20
-2007-06-03  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-03  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test-readenv.c: Free environment.
=20
@@ -48,20 +81,20 @@
 	* roken-common.h (free_environment): free result of
 	read_environment().
 =09
-2007-05-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-05-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* fnmatch.c: Do recursive call to rk_fnmatch
 =09
-2007-01-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-01-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.c: Try harder to call res_ndestroy().
 =09
-2006-12-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: make sure built headers are copied to the
 	${build_topdir}/include
 =09
-2006-12-15  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-15  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* unvis.c: Use internal version of rk_unvis
=20
@@ -73,11 +106,11 @@
 =09
 	* unvis.c: prefix unvis functions with rk_, and prototypes.
 =09
-2006-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* vis.c: Provide some prototypes for the rk_vis functions.
 =09
-2006-12-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* ifaddrs.hin: Prefix getifaddrs functions with rk_ and do symbol
 	renaming.
@@ -93,11 +126,11 @@
 	* Makefile.am: Install extra posix headers in <roken/...> to avoid
 	dup headers.
 =09
-2006-11-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* socket_wrapper.c (swrap_sendto): fail on to unknown si->type
 =09
-2006-11-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-11-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* socket_wrapper.c: A few fixes to have Heimdal pass the make
 	check under socket_wrapper. The first is a missing 'break' before
@@ -107,11 +140,11 @@
 	unix stream sockets, but not for TCP sockets. The alternate fix
 	would be to have the KDC use 'send()' in this case. Andrew Bartlett.
=20
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: split dist and nondist HEADERS
 =09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* roken.h.in: Add timegm glue.
=20
@@ -123,7 +156,7 @@
 	* socket_wrapper.c: Maybe include <sys/time.h> and/or maybe
 	include <time.h>.
 =09
-2006-10-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken.h.in: Revert prevois for now, the problem is that we have
 	to include symbols unconditionally, even for those that just needs
@@ -133,7 +166,7 @@
=20
 	* socket_wrapper.c: Maybe include <sys/filio.h>.
 =09
-2006-10-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* socket_wrapper.c: more consitity check, remove dead code, add
 	socket length code, add missing break, make diffrent chars of type
@@ -145,7 +178,7 @@
 	* socket_wrapper.c: Force no socket wrapper for socket_wrapper
 	itself.
 =09
-2006-10-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* socket_wrapper.c: Maybe include <config.h>.
=20
@@ -158,7 +191,7 @@
 	* socket_wrapper.[ch]: Include socket wrapper from samba4 (rev
 	19179).
 =09
-2006-10-07 Love H=F6rnquist =C5strand <lha at it.su.se>
+2006-10-07 Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* Makefile.am: Add build_HEADERZ to EXTRA_DIST
=20
@@ -166,13 +199,13 @@
=20
 	* Makefile.am: Add to all objects BUILD_ROKEN_LIB.
 =09
-2006-09-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken.h.in: Add samba socket wrapper fragment.
=20
 	* Makefile.am: Add samba socket wrapper fragment.
 =09
-2006-09-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-09-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* snprintf.c: reapply patch that went away in last commit
 =09
@@ -182,7 +215,7 @@
=20
 	* snprintf-test.c: add tests for size_t printf formater
 =09
-2006-06-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rtbl.h: Add extern "C" for C++.
=20
@@ -190,7 +223,7 @@
=20
 	* rtbl.h: Add rtbl_add_column_entryv functions, printf like
 =09
-2006-06-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-06-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* glob.hin: Add extern "C" for C++. From joerg at britannica dot
 	bec dot de
@@ -198,18 +231,18 @@
 	* fnmatch.hin: Add extern "C" for C++. From joerg at britannica
 	dot bec dot de
 =09
-2006-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* fnmatch.hin (fnmatch): CPP rename to rk_fnmatch
 =09
-2006-04-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* resolve.c (dns_srv_order): change a if (ptr =3D=3D NULL) continue
 	into a assert(ptr !=3D NULL) since it could never happen, found by
 	the IBM code checker (beam).  Thanks to Florian Krohm for
 	explaining it.
 =09
-2006-04-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-04-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken_gethostby.c (roken_gethostby): make addr_list one larger
 	to avoid a off-by-one error. Found by IBM checker.
@@ -217,11 +250,11 @@
 	* resolve.c: Plug memory leak found by IBM checker (and try to
 	please it).
 =09
-2006-02-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-02-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* resolve.c: Spelling, from Alexey Dobriyan, via Jason McIntyre
 =09
-2006-01-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* getcap.c: Don't use db support unless its build into libc but we
 	dont check for that now, so just disable the code. This removes
@@ -231,7 +264,7 @@
 	application calls getpwnamn() and it linked to roken, it craches
 	in the nss functions.
 =09
-2006-01-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-01-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hex.c (hex_decode): support decoding odd number of characters,
 	in the odd len case, the first character ends up in the first byte
@@ -239,12 +272,12 @@
=20
 	* hex-test.c: Check that we can decode single character hex chars.
=20
-2005-12-12  Love H=F6rnquist =C5strand <lha at it.su.se>
+2005-12-12  Love H=C3=B6rnquist =C3=85strand <lha at it.su.se>
=20
 	* getifaddrs.c: Try handle HP/UX 11.nn, its diffrent from Solaris
 	large SIOCGIFCONF.
 =09
-2005-09-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken-common.h: Move rk_UNCONST to roken.h.in since it might use
 	uintptr_t depending on avaibility.
@@ -252,46 +285,46 @@
 	* roken.h.in: Include <stdint.h> if it exists.  If avaiable, use
 	uintptr_t to define rk_UNCONST.
 =09
-2005-09-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken-common.h: Add rk_dumpdata.
 =09
 	* dumpdata.c: Add rk_dumpdata() that write a chunk of data into a
 	file for later processing by some other tool (like asn1_print).
 =09
-2005-09-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* strptime.c: cast to unsigned char to make sure its not negative
 	when passing it to is* functions
 =09
-2005-09-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-09-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* socket.c: Add socket_set_ipv6only.
=20
 	* roken-common.h: Add socket_set_ipv6only, remove some argument
 	names.
 =09
-2005-08-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* strpool.c (rk_strpoolprintf): remove debug printf, plug memory
 	leak
 =09
-2005-08-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* setprogname.c (setprogname): const poision
 =09
 	* print_version.c: Removed, moved to libvers.
=20
-2005-08-22  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-22  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.c (dns_lookup_int): if we have res_ndestroy, prefeer
 	that before res_nclose
=20
-2005-08-12 Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-12 Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* getaddrinfo-test.c: Rename optind to optidx to avoid shadowing.
=20
-2005-08-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-08-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gai_strerror.c: sprinkel more const
 =09
@@ -299,21 +332,21 @@
 	const to match SUSv3.  Prompted by Stefan Metzmacher change to
 	Samba.
=20
-2005-07-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken.h.in: Remove parameter names to avoid shadow warnings.
=20
-2005-07-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* getifaddrs.c (nl_getlist): poll to get messages from kernel, and
 	retry if the message was lost
 	(free_nlmsglist): free all linked elements, not just the first one
=20
-2005-07-08  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-08  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* snprintf-test.c: Check a very simple format string
 =09
-2005-07-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken.h.in: If we have <strings.h> include it, its needed for
 	strcasecmp() on those platforms that are SUS3/iso c99 strict (like
@@ -321,15 +354,15 @@
=20
 	* roken-common.h: remove duplicate ;
 =09
-2005-07-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken-common.h: rk_strpoolprintf first variable identifier is 3
=20
-2005-06-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* base64.h: remove variable names
 =09
-2005-06-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken-common.h: fix format attribute
=20
@@ -341,11 +374,11 @@
 	* strpool.c: add strpool, a printf collector to make it eaiser to
 	collect strings into one string
=20
-2005-06-23  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-23  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* base64.c: Add const, from Andrew Abartlet <abartlet at samba.org>
=20
-2005-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* strpftime-test.c: test for "%Y%m"
=20
@@ -355,7 +388,7 @@
 	to limit that amount of numbers used, with this strptime can
 	handle strptime("200505", "%Y%m", &tm);
=20
-2005-06-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* getaddrinfo.c: avoid shadowing sin
 =09
@@ -376,13 +409,13 @@
 =09
 	* environment.c: rename index to idx to avoid shadowing
=20
-2005-05-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse_reply-test.c: avoid signedness warnings
=20
 	* test-mem.c: avoid signedness warnings
=20
-2005-05-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hex.c: include "roken.h" to avoid undefined size_t/ssize_t
=20
@@ -390,12 +423,12 @@
=20
 	* Makefile.am (snprintf_test_SOURCES): Add snprintf-test.h.
=20
-2005-05-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* environment.c (rk_read_env_file): move assignment to later to
 	make pre c99 compiler happy
=20
-2005-05-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* strptime.c: use english spelling of March
=20
@@ -409,7 +442,7 @@
 =09
 	* environment.c: eliminate duplicates
 =09
-2005-05-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* issuid.c (issuid): change the #ifdef order to avoid unreachable
 	code warning.
@@ -432,7 +465,7 @@
 	* test-mem.c: Add member fd to map.
 	(rk_test_mem_alloc, rk_test_mem_free): Use it.
=20
-2005-04-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* getifaddrs.c: add break on default: statements, from Douglas
 	E. Engert
@@ -445,7 +478,7 @@
=20
 	* parse_time-test.c: Include <err.h>.
 =09
-2005-04-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse_time-test.c: improve testing
 =09
@@ -459,7 +492,7 @@
=20
 	* getusershell.c: Include roken.h
=20
-2005-04-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* unvis.c: cast to unsigned char to make sure its not negative
 	when passing it to is* functions
@@ -467,7 +500,7 @@
 	* strptime.c: cast to unsigned char to make sure its not negative
 	when passing it to to* functions
=20
-2005-04-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* simple_exec.c: don't close stderr, close all fd that is num 3
 	and larger
@@ -476,19 +509,19 @@
=20
 	* add closefrom
=20
-2005-04-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* add ROKEN_LIB_FUNCTION to all exported functions
=20
-2005-04-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve-test.c: print DS
=20
-2005-04-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse_time-test.c: remove unused variable
 =09
-2005-04-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* strpftime-test.c: print size_t by casting to unsigned long
 =09
@@ -498,12 +531,12 @@
 =09
 	* resolve-test.c: print size_t by casting to unsigned long
 =09
-2005-04-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* snprintf-test.c (try): reset va_list argument between reuse,
 	from Peter Kruty <xkruty at fi.muni.cz>
=20
-2005-03-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken_gethostby.c (roken_gethostby): s/sin/addr/ to avoid
 	shadowing
@@ -512,20 +545,20 @@
=20
 	* parse_units.c: avoid shadowing div
=20
-2005-03-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* snprintf.c: use defined(TEST_SNPRINTF) like on all other places
 	in the same file
=20
-2005-03-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* hex.c: check for overflows
=20
-2005-03-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* vis.c: use RCSID instead of __RCSID
=20
-2005-03-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: check_PROGRAMS +=3D hex-test
 =09
@@ -534,13 +567,13 @@
 	* hex.c: fix decodeing, it processed to much data and thus
 	returned the wrong length
=20
-2005-03-04  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-04  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: add hex.[ch]
=20
 	* hex.c: add hex encoder/decoder
=20
-2005-03-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-03-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* daemon.c fnmatch.c fnmatch.hin getcap.c getopt.c getusershell.c
 	glob.c glob.hin iruserok.c unvis.c vis.hin:
@@ -556,7 +589,7 @@
 =09
 	* vis.c: Update new revision from NetBSD (copyright update)
=20
-2005-02-24  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-02-24  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: bump version to 17:0:1
=20
@@ -565,7 +598,7 @@
 	* getusershell.c: Include ctype.h, cast argument to isspace to
 	unsigned char.
=20
-2004-10-31  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-31  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* parse_time.3, parse_units.c: Change the behavior of the
 	parse_unit code to return the number of bytes needed to print the
@@ -574,7 +607,7 @@
=20
 	* parse_time-test.c Makefile.am test-mem.c test-mem.h: test parse_time
=20
-2004-10-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.c: put dns_type_to_string and dns_string_to_type in the
 	abi
@@ -583,20 +616,20 @@
 =09
 	* resolve.h: add ds_record
 =09
-2004-10-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-10-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ndbm_wrap.c: undefine open so this works on solaris with large
 	file support From netbsd's pkgsrc via Gavan Fantom
 =09
-2004-09-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve-test.c: add --version/--help
 =09
-2004-09-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: make resolve-test a noinst program
 =09
-2004-09-11  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-09-11  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve-test.c: test program for libroken resolve from resolve.c
 =09
@@ -614,7 +647,7 @@
=20
 	* Makefile.am: always clean generated headers
=20
-2004-06-26  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-26  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* rtbl.3: use .In for header, remove trailing space
 =09
@@ -630,20 +663,20 @@
 	  - ability to end a row
 	  - don't extend last column to full width
 =09
-2004-06-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.[ch]: add and use and bind9 version of rr type
 	(rk_ns_t_XXX) instead of the old bind4 version (T_XXX)
=20
-2004-05-25  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-05-25  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.c (stot): add AAAA
 =09
-2004-02-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* getarg.c (add_string): catch error from realloc
 =09
-2004-02-12  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-02-12  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* roken-common.h: add simple_execve_timed
 =09
@@ -651,11 +684,11 @@
 =09
 	* simple_exec.c: add timed simple_exec
 =09
-2004-01-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* gai_strerror.c: correct ifdef for EAI_ADDRFAMILY
=20
-2003-12-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.c: parse dns header, add support for SSHFP
 =09
@@ -663,35 +696,35 @@
 =09
 	* resolve.h: add SSHFP, clean up the the dns_header
 =09
-2003-12-14  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-14  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.h: remove HEADER (only used for crays)
 =09
 	* resolve.c: number-of fields no longer stored in network order
 =09
-2003-12-13  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-13  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolve.c: remove depency on c99 types in resolv.h
 =09
 	* resolve.h: remove depency on c99 types
 =09
-2003-12-06  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-06  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* resolv.h: add more T_ types and inline the dns headers, all this
 	for bind9 resolvers
=20
-2003-12-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-12-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* gai_strerror.c: EAI_ADDRFAMILY and EAI_NODATA is deprecated
 =09
 	* roken-common.h: use EAI_NONAME instead of EAI_ADDRFAMILY to
 	check for if we need EAI_ macros
=20
-2003-10-04   Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-10-04   Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* strptime.c: let t and n match zero or more whitespaces
 =09
-2003-08-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2003-08-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* ndbm_wrap.c: patch for working with DB4 on heimdal-discuss
 	From: Luke Howard <lukeh at PADL.COM>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/Makefile=
.am
--- a/head/crypto/heimdal/lib/roken/Makefile.am	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/Makefile.am	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 22409 2008-01-12 05:53:37Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -7,34 +7,41 @@
 CLEANFILES =3D roken.h make-roken.c $(XHEADERS)
=20
 lib_LTLIBRARIES =3D libroken.la
+
 libroken_la_LDFLAGS =3D -version-info 19:0:1
 libroken_la_CPPFLAGS =3D -DBUILD_ROKEN_LIB
=20
-# XXX this is needed for the LIBOBJS objects
-CPPFLAGS =3D $(libroken_la_CPPFLAGS)
+if versionscript
+libroken_la_LDFLAGS +=3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/version-script=
.map
+endif
=20
-noinst_PROGRAMS =3D make-roken snprintf-test resolve-test
+AM_CPPFLAGS +=3D $(libroken_la_CPPFLAGS)
+if HAVE_DBHEADER
+AM_CPPFLAGS +=3D -I$(DBHEADER)
+endif
=20
-nodist_make_roken_SOURCES =3D make-roken.c
+noinst_PROGRAMS =3D snprintf-test resolve-test rkpty
=20
 check_PROGRAMS =3D 				\
 		base64-test			\
 		getaddrinfo-test		\
+		getifaddrs-test			\
 		hex-test			\
 		test-readenv			\
 		parse_bytes-test		\
 		parse_reply-test		\
 		parse_time-test			\
 		snprintf-test			\
-		strpftime-test
+		strpftime-test			\
+		tsearch-test
=20
 TESTS =3D $(check_PROGRAMS)
=20
-LDADD =3D libroken.la $(LIB_crypt)
+LDADD =3D libroken.la
 make_roken_LDADD =3D=20
=20
 noinst_LTLIBRARIES =3D libtest.la
-libtest_la_SOURCES =3D strftime.c strptime.c snprintf.c
+libtest_la_SOURCES =3D strftime.c strptime.c snprintf.c tsearch.c
 libtest_la_CFLAGS =3D -DTEST_SNPRINTF -DTEST_STRPFTIME
=20
 parse_reply_test_SOURCES =3D parse_reply-test.c resolve.c
@@ -42,14 +49,19 @@
=20
 test_readenv_SOURCES =3D test-readenv.c test-mem.c
=20
+rkpty_LDADD =3D $(LIB_openpty) $(LDADD)
+
 parse_time_test_SOURCES =3D parse_time-test.c test-mem.c
=20
 strpftime_test_SOURCES	=3D strpftime-test.c strpftime-test.h
 strpftime_test_LDADD =3D libtest.la $(LDADD)
 strpftime_test_CFLAGS =3D -DTEST_STRPFTIME
-snprintf_test_SOURCES	=3D snprintf-test.c snprintf-test.h
+snprintf_test_SOURCES	=3D snprintf-test.c
 snprintf_test_LDADD =3D libtest.la $(LDADD)
 snprintf_test_CFLAGS	=3D -DTEST_SNPRINTF
+tsearch_test_SOURCES	=3D tsearch-test.c
+tsearch_test_LDADD =3D libtest.la $(LDADD)
+tsearch_test_CFLAGS	=3D -DTEST_TSEARCH
=20
 resolve_test_SOURCES =3D resolve-test.c
=20
@@ -57,6 +69,9 @@
 	base64.c		\
 	bswap.c			\
 	concat.c		\
+	cloexec.c		\
+	ct.c			\
+	doxygen.c		\
 	dumpdata.c		\
 	environment.c		\
 	eread.c			\
@@ -80,6 +95,8 @@
 	parse_bytes.c		\
 	parse_time.c		\
 	parse_units.c		\
+	qsort.c			\
+	rand.c			\
 	realloc.c		\
 	resolve.c		\
 	roken_gethostby.c	\
@@ -91,15 +108,16 @@
 	snprintf.c		\
 	socket.c		\
 	strcollect.c		\
+	strerror_r.c		\
 	strpool.c		\
 	timeval.c		\
 	tm2time.c		\
 	unvis.c			\
 	verify.c		\
 	vis.c			\
-	vis.h			\
 	warnerr.c		\
 	write_pid.c		\
+	xfree.c			\
 	xdbm.h
=20
 EXTRA_libroken_la_SOURCES =3D	\
@@ -107,13 +125,14 @@
 	glob.hin		\
 	fnmatch.hin		\
 	ifaddrs.hin		\
+	search.hin		\
 	vis.hin=09
=20
-libroken_la_LIBADD =3D @LTLIBOBJS@
+libroken_la_LIBADD =3D @LTLIBOBJS@ $(LIB_crypt)
=20
 $(LTLIBOBJS) $(libroken_la_OBJECTS): roken.h $(XHEADERS)
=20
-BUILT_SOURCES =3D make-roken.c roken.h
+BUILT_SOURCES =3D roken.h
=20
 if have_err_h
 err_h =3D
@@ -139,6 +158,12 @@
 ifaddrs_h =3D ifaddrs.h
 endif
=20
+if have_search_h
+search_h =3D=20
+else
+search_h =3D search.h
+endif
+
 if have_vis_h
 vis_h =3D=20
 else
@@ -146,8 +171,8 @@
 endif
=20
 ## these are controlled by configure
-XHEADERS =3D $(err_h) $(fnmatch_h) $(glob_h) $(ifaddrs_h) $(vis_h)
-CLEANFILES +=3D err.h fnmatch.h glob.h ifaddrs.h vis.h
+XHEADERS =3D $(err_h) $(fnmatch_h) $(glob_h) $(ifaddrs_h) $(search_h) $(vi=
s_h)
+CLEANFILES +=3D err.h fnmatch.h glob.h ifaddrs.h search.h vis.h
=20
 dist_include_HEADERS =3D 				\
 	base64.h				\
@@ -178,6 +203,14 @@
 .hin.h:
 	cp $< $@
=20
+# Make make-roken deprecated in 1.4 when we know that roken-h-process.pl w=
orks
+if !CROSS_COMPILE
+
+noinst_PROGRAMS +=3D make-roken
+BUILT_SOURCES +=3D make-roken.c
+
+nodist_make_roken_SOURCES =3D make-roken.c
+
 roken.h: make-roken$(EXEEXT)
 	@./make-roken$(EXEEXT) > tmp.h ;\
 	if [ -f roken.h ] && cmp -s tmp.h roken.h ; then rm -f tmp.h ; \
@@ -186,9 +219,21 @@
 make-roken.c: roken.h.in roken.awk
 	$(AWK) -f $(srcdir)/roken.awk $(srcdir)/roken.h.in > make-roken.c
=20
+else
+
+roken.h: $(top_srcdir)/cf/roken-h-process.pl roken.h.in
+	perl $(top_srcdir)/cf/roken-h-process.pl \
+	-c $(top_builddir)/include/config.h  \
+	-p $(srcdir)/roken.h.in -o roken.h
+
+endif
+
+
 EXTRA_DIST =3D \
+	NTMakefile \
 	roken.awk roken.h.in \
 	$(man_MANS) \
 	test-mem.h \
 	ndbm_wrap.c \
-	ndbm_wrap.h
+	ndbm_wrap.h \
+	version-script.map
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/Makefile=
.in
--- a/head/crypto/heimdal/lib/roken/Makefile.in	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/Makefile.in	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22409 2008-01-12 05:53:37Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -56,21 +58,28 @@
 	seteuid.c strcasecmp.c strdup.c strerror.c strftime.c \
 	strlcat.c strlcpy.c strlwr.c strncasecmp.c strndup.c strnlen.c \
 	strptime.c strsep.c strsep_copy.c strtok_r.c strupr.c swab.c \
-	timegm.c unsetenv.c verr.c verrx.c vsyslog.c vwarn.c vwarnx.c \
-	warn.c warnx.c writev.c
-noinst_PROGRAMS =3D make-roken$(EXEEXT) snprintf-test$(EXEEXT) \
-	resolve-test$(EXEEXT)
+	timegm.c tsearch.c unsetenv.c verr.c verrx.c vsyslog.c vwarn.c \
+	vwarnx.c warn.c warnx.c writev.c
+ at versionscript_TRUE@am__append_1 =3D $(LDFLAGS_VERSION_SCRIPT)$(srcdir)/ve=
rsion-script.map
+ at HAVE_DBHEADER_TRUE@am__append_2 =3D -I$(DBHEADER)
+noinst_PROGRAMS =3D snprintf-test$(EXEEXT) resolve-test$(EXEEXT) \
+	rkpty$(EXEEXT) $(am__EXEEXT_1)
 check_PROGRAMS =3D base64-test$(EXEEXT) getaddrinfo-test$(EXEEXT) \
-	hex-test$(EXEEXT) test-readenv$(EXEEXT) \
-	parse_bytes-test$(EXEEXT) parse_reply-test$(EXEEXT) \
-	parse_time-test$(EXEEXT) snprintf-test$(EXEEXT) \
-	strpftime-test$(EXEEXT)
- at have_socket_wrapper_TRUE@am__append_1 =3D socket_wrapper.c socket_wrapper=
.h
- at have_socket_wrapper_TRUE@am__append_2 =3D socket_wrapper.h
+	getifaddrs-test$(EXEEXT) hex-test$(EXEEXT) \
+	test-readenv$(EXEEXT) parse_bytes-test$(EXEEXT) \
+	parse_reply-test$(EXEEXT) parse_time-test$(EXEEXT) \
+	snprintf-test$(EXEEXT) strpftime-test$(EXEEXT) \
+	tsearch-test$(EXEEXT)
+ at have_socket_wrapper_TRUE@am__append_3 =3D socket_wrapper.c socket_wrapper=
.h
+ at have_socket_wrapper_TRUE@am__append_4 =3D socket_wrapper.h
+
+# Make make-roken deprecated in 1.4 when we know that roken-h-process.pl w=
orks
+ at CROSS_COMPILE_FALSE@am__append_5 =3D make-roken
+ at CROSS_COMPILE_FALSE@am__append_6 =3D make-roken.c
 subdir =3D lib/roken
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -85,7 +94,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -99,9 +108,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -109,39 +121,57 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
 am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(man3dir)" \
 	"$(DESTDIR)$(includedir)" "$(DESTDIR)$(includedir)" \
 	"$(DESTDIR)$(rokenincludedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
 LTLIBRARIES =3D $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES)
-libroken_la_DEPENDENCIES =3D @LTLIBOBJS@
-am__libroken_la_SOURCES_DIST =3D base64.c bswap.c concat.c dumpdata.c \
-	environment.c eread.c esetenv.c ewrite.c \
-	getaddrinfo_hostspec.c get_default_username.c \
+am__DEPENDENCIES_1 =3D
+libroken_la_DEPENDENCIES =3D @LTLIBOBJS@ $(am__DEPENDENCIES_1)
+am__libroken_la_SOURCES_DIST =3D base64.c bswap.c concat.c cloexec.c \
+	ct.c doxygen.c dumpdata.c environment.c eread.c esetenv.c \
+	ewrite.c getaddrinfo_hostspec.c get_default_username.c \
 	get_window_size.c getarg.c getnameinfo_verified.c \
 	getprogname.c h_errno.c hex.c hostent_find_fqdn.c issuid.c \
 	k_getpwnam.c k_getpwuid.c mini_inetd.c net_read.c net_write.c \
-	parse_bytes.c parse_time.c parse_units.c realloc.c resolve.c \
-	roken_gethostby.c rtbl.c rtbl.h setprogname.c signal.c \
-	simple_exec.c snprintf.c socket.c strcollect.c strpool.c \
-	timeval.c tm2time.c unvis.c verify.c vis.c vis.h warnerr.c \
-	write_pid.c xdbm.h socket_wrapper.c socket_wrapper.h
+	parse_bytes.c parse_time.c parse_units.c qsort.c rand.c \
+	realloc.c resolve.c roken_gethostby.c rtbl.c rtbl.h \
+	setprogname.c signal.c simple_exec.c snprintf.c socket.c \
+	strcollect.c strerror_r.c strpool.c timeval.c tm2time.c \
+	unvis.c verify.c vis.c warnerr.c write_pid.c xfree.c xdbm.h \
+	socket_wrapper.c socket_wrapper.h
 @have_socket_wrapper_TRUE at am__objects_1 =3D  \
 @have_socket_wrapper_TRUE@	libroken_la-socket_wrapper.lo
 am_libroken_la_OBJECTS =3D libroken_la-base64.lo libroken_la-bswap.lo \
-	libroken_la-concat.lo libroken_la-dumpdata.lo \
+	libroken_la-concat.lo libroken_la-cloexec.lo libroken_la-ct.lo \
+	libroken_la-doxygen.lo libroken_la-dumpdata.lo \
 	libroken_la-environment.lo libroken_la-eread.lo \
 	libroken_la-esetenv.lo libroken_la-ewrite.lo \
 	libroken_la-getaddrinfo_hostspec.lo \
@@ -154,54 +184,59 @@
 	libroken_la-mini_inetd.lo libroken_la-net_read.lo \
 	libroken_la-net_write.lo libroken_la-parse_bytes.lo \
 	libroken_la-parse_time.lo libroken_la-parse_units.lo \
+	libroken_la-qsort.lo libroken_la-rand.lo \
 	libroken_la-realloc.lo libroken_la-resolve.lo \
 	libroken_la-roken_gethostby.lo libroken_la-rtbl.lo \
 	libroken_la-setprogname.lo libroken_la-signal.lo \
 	libroken_la-simple_exec.lo libroken_la-snprintf.lo \
 	libroken_la-socket.lo libroken_la-strcollect.lo \
-	libroken_la-strpool.lo libroken_la-timeval.lo \
-	libroken_la-tm2time.lo libroken_la-unvis.lo \
-	libroken_la-verify.lo libroken_la-vis.lo \
+	libroken_la-strerror_r.lo libroken_la-strpool.lo \
+	libroken_la-timeval.lo libroken_la-tm2time.lo \
+	libroken_la-unvis.lo libroken_la-verify.lo libroken_la-vis.lo \
 	libroken_la-warnerr.lo libroken_la-write_pid.lo \
-	$(am__objects_1)
+	libroken_la-xfree.lo $(am__objects_1)
 libroken_la_OBJECTS =3D $(am_libroken_la_OBJECTS)
 libroken_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) \
 	$(libroken_la_LDFLAGS) $(LDFLAGS) -o $@
 libtest_la_LIBADD =3D
 am_libtest_la_OBJECTS =3D libtest_la-strftime.lo libtest_la-strptime.lo \
-	libtest_la-snprintf.lo
+	libtest_la-snprintf.lo libtest_la-tsearch.lo
 libtest_la_OBJECTS =3D $(am_libtest_la_OBJECTS)
 libtest_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(libtest_la_CFLAGS) \
 	$(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
+ at CROSS_COMPILE_FALSE@am__EXEEXT_1 =3D make-roken$(EXEEXT)
 PROGRAMS =3D $(noinst_PROGRAMS)
 base64_test_SOURCES =3D base64-test.c
 base64_test_OBJECTS =3D base64-test.$(OBJEXT)
 base64_test_LDADD =3D $(LDADD)
-am__DEPENDENCIES_1 =3D
-base64_test_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
+base64_test_DEPENDENCIES =3D libroken.la
 getaddrinfo_test_SOURCES =3D getaddrinfo-test.c
 getaddrinfo_test_OBJECTS =3D getaddrinfo-test.$(OBJEXT)
 getaddrinfo_test_LDADD =3D $(LDADD)
-getaddrinfo_test_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
+getaddrinfo_test_DEPENDENCIES =3D libroken.la
+getifaddrs_test_SOURCES =3D getifaddrs-test.c
+getifaddrs_test_OBJECTS =3D getifaddrs-test.$(OBJEXT)
+getifaddrs_test_LDADD =3D $(LDADD)
+getifaddrs_test_DEPENDENCIES =3D libroken.la
 hex_test_SOURCES =3D hex-test.c
 hex_test_OBJECTS =3D hex-test.$(OBJEXT)
 hex_test_LDADD =3D $(LDADD)
-hex_test_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
-nodist_make_roken_OBJECTS =3D make-roken.$(OBJEXT)
+hex_test_DEPENDENCIES =3D libroken.la
+ at CROSS_COMPILE_FALSE@nodist_make_roken_OBJECTS =3D make-roken.$(OBJEXT)
 make_roken_OBJECTS =3D $(nodist_make_roken_OBJECTS)
 make_roken_DEPENDENCIES =3D
 parse_bytes_test_SOURCES =3D parse_bytes-test.c
 parse_bytes_test_OBJECTS =3D parse_bytes-test.$(OBJEXT)
 parse_bytes_test_LDADD =3D $(LDADD)
-parse_bytes_test_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
+parse_bytes_test_DEPENDENCIES =3D libroken.la
 am_parse_reply_test_OBJECTS =3D  \
 	parse_reply_test-parse_reply-test.$(OBJEXT) \
 	parse_reply_test-resolve.$(OBJEXT)
 parse_reply_test_OBJECTS =3D $(am_parse_reply_test_OBJECTS)
 parse_reply_test_LDADD =3D $(LDADD)
-parse_reply_test_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
+parse_reply_test_DEPENDENCIES =3D libroken.la
 parse_reply_test_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(parse_reply_test_CFLAGS) \
 	$(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
@@ -209,31 +244,39 @@
 	test-mem.$(OBJEXT)
 parse_time_test_OBJECTS =3D $(am_parse_time_test_OBJECTS)
 parse_time_test_LDADD =3D $(LDADD)
-parse_time_test_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
+parse_time_test_DEPENDENCIES =3D libroken.la
 am_resolve_test_OBJECTS =3D resolve-test.$(OBJEXT)
 resolve_test_OBJECTS =3D $(am_resolve_test_OBJECTS)
 resolve_test_LDADD =3D $(LDADD)
-resolve_test_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
+resolve_test_DEPENDENCIES =3D libroken.la
+rkpty_SOURCES =3D rkpty.c
+rkpty_OBJECTS =3D rkpty.$(OBJEXT)
+rkpty_DEPENDENCIES =3D $(am__DEPENDENCIES_1) $(LDADD)
 am_snprintf_test_OBJECTS =3D snprintf_test-snprintf-test.$(OBJEXT)
 snprintf_test_OBJECTS =3D $(am_snprintf_test_OBJECTS)
-am__DEPENDENCIES_2 =3D libroken.la $(am__DEPENDENCIES_1)
-snprintf_test_DEPENDENCIES =3D libtest.la $(am__DEPENDENCIES_2)
+snprintf_test_DEPENDENCIES =3D libtest.la $(LDADD)
 snprintf_test_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(snprintf_test_CFLAGS) \
 	$(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
 am_strpftime_test_OBJECTS =3D strpftime_test-strpftime-test.$(OBJEXT)
 strpftime_test_OBJECTS =3D $(am_strpftime_test_OBJECTS)
-strpftime_test_DEPENDENCIES =3D libtest.la $(am__DEPENDENCIES_2)
+strpftime_test_DEPENDENCIES =3D libtest.la $(LDADD)
 strpftime_test_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
 	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(strpftime_test_CFLAGS) \
 	$(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
 am_test_readenv_OBJECTS =3D test-readenv.$(OBJEXT) test-mem.$(OBJEXT)
 test_readenv_OBJECTS =3D $(am_test_readenv_OBJECTS)
 test_readenv_LDADD =3D $(LDADD)
-test_readenv_DEPENDENCIES =3D libroken.la $(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+test_readenv_DEPENDENCIES =3D libroken.la
+am_tsearch_test_OBJECTS =3D tsearch_test-tsearch-test.$(OBJEXT)
+tsearch_test_OBJECTS =3D $(am_tsearch_test_OBJECTS)
+tsearch_test_DEPENDENCIES =3D libtest.la $(LDADD)
+tsearch_test_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) \
+	$(LIBTOOLFLAGS) --mode=3Dlink $(CCLD) $(tsearch_test_CFLAGS) \
+	$(CFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -245,78 +288,86 @@
 	$(LDFLAGS) -o $@
 SOURCES =3D $(libroken_la_SOURCES) $(EXTRA_libroken_la_SOURCES) \
 	$(libtest_la_SOURCES) base64-test.c getaddrinfo-test.c \
-	hex-test.c $(nodist_make_roken_SOURCES) parse_bytes-test.c \
-	$(parse_reply_test_SOURCES) $(parse_time_test_SOURCES) \
-	$(resolve_test_SOURCES) $(snprintf_test_SOURCES) \
-	$(strpftime_test_SOURCES) $(test_readenv_SOURCES)
+	getifaddrs-test.c hex-test.c $(nodist_make_roken_SOURCES) \
+	parse_bytes-test.c $(parse_reply_test_SOURCES) \
+	$(parse_time_test_SOURCES) $(resolve_test_SOURCES) rkpty.c \
+	$(snprintf_test_SOURCES) $(strpftime_test_SOURCES) \
+	$(test_readenv_SOURCES) $(tsearch_test_SOURCES)
 DIST_SOURCES =3D $(am__libroken_la_SOURCES_DIST) \
 	$(EXTRA_libroken_la_SOURCES) $(libtest_la_SOURCES) \
-	base64-test.c getaddrinfo-test.c hex-test.c parse_bytes-test.c \
-	$(parse_reply_test_SOURCES) $(parse_time_test_SOURCES) \
-	$(resolve_test_SOURCES) $(snprintf_test_SOURCES) \
-	$(strpftime_test_SOURCES) $(test_readenv_SOURCES)
+	base64-test.c getaddrinfo-test.c getifaddrs-test.c hex-test.c \
+	parse_bytes-test.c $(parse_reply_test_SOURCES) \
+	$(parse_time_test_SOURCES) $(resolve_test_SOURCES) rkpty.c \
+	$(snprintf_test_SOURCES) $(strpftime_test_SOURCES) \
+	$(test_readenv_SOURCES) $(tsearch_test_SOURCES)
 man3dir =3D $(mandir)/man3
 MANS =3D $(man_MANS)
 am__dist_include_HEADERS_DIST =3D base64.h getarg.h hex.h parse_bytes.h \
 	parse_time.h parse_units.h resolve.h roken-common.h rtbl.h \
 	xdbm.h socket_wrapper.h
-dist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-nodist_includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-nodist_rokenincludeHEADERS_INSTALL =3D $(INSTALL_HEADER)
 HEADERS =3D $(dist_include_HEADERS) $(nodist_include_HEADERS) \
 	$(nodist_rokeninclude_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
-
-# XXX this is needed for the LIBOBJS objects
-CPPFLAGS =3D $(libroken_la_CPPFLAGS)
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
+CPPFLAGS =3D @CPPFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -340,10 +391,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -360,6 +412,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -375,31 +429,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -414,10 +482,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -458,74 +528,85 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .hin
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .hin
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(libroken_la_CPPFLAGS) \
+	$(am__append_2)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 ACLOCAL_AMFLAGS =3D -I ../../cf
 CLEANFILES =3D roken.h make-roken.c $(XHEADERS) err.h fnmatch.h glob.h \
-	ifaddrs.h vis.h
+	ifaddrs.h search.h vis.h
 lib_LTLIBRARIES =3D libroken.la
-libroken_la_LDFLAGS =3D -version-info 19:0:1
+libroken_la_LDFLAGS =3D -version-info 19:0:1 $(am__append_1)
 libroken_la_CPPFLAGS =3D -DBUILD_ROKEN_LIB
-nodist_make_roken_SOURCES =3D make-roken.c
 TESTS =3D $(check_PROGRAMS)
-LDADD =3D libroken.la $(LIB_crypt)
+LDADD =3D libroken.la
 make_roken_LDADD =3D=20
 noinst_LTLIBRARIES =3D libtest.la
-libtest_la_SOURCES =3D strftime.c strptime.c snprintf.c
+libtest_la_SOURCES =3D strftime.c strptime.c snprintf.c tsearch.c
 libtest_la_CFLAGS =3D -DTEST_SNPRINTF -DTEST_STRPFTIME
 parse_reply_test_SOURCES =3D parse_reply-test.c resolve.c
 parse_reply_test_CFLAGS =3D -DTEST_RESOLVE
 test_readenv_SOURCES =3D test-readenv.c test-mem.c
+rkpty_LDADD =3D $(LIB_openpty) $(LDADD)
 parse_time_test_SOURCES =3D parse_time-test.c test-mem.c
 strpftime_test_SOURCES =3D strpftime-test.c strpftime-test.h
 strpftime_test_LDADD =3D libtest.la $(LDADD)
 strpftime_test_CFLAGS =3D -DTEST_STRPFTIME
-snprintf_test_SOURCES =3D snprintf-test.c snprintf-test.h
+snprintf_test_SOURCES =3D snprintf-test.c
 snprintf_test_LDADD =3D libtest.la $(LDADD)
 snprintf_test_CFLAGS =3D -DTEST_SNPRINTF
+tsearch_test_SOURCES =3D tsearch-test.c
+tsearch_test_LDADD =3D libtest.la $(LDADD)
+tsearch_test_CFLAGS =3D -DTEST_TSEARCH
 resolve_test_SOURCES =3D resolve-test.c
-libroken_la_SOURCES =3D base64.c bswap.c concat.c dumpdata.c \
-	environment.c eread.c esetenv.c ewrite.c \
+libroken_la_SOURCES =3D base64.c bswap.c concat.c cloexec.c ct.c \
+	doxygen.c dumpdata.c environment.c eread.c esetenv.c ewrite.c \
 	getaddrinfo_hostspec.c get_default_username.c \
 	get_window_size.c getarg.c getnameinfo_verified.c \
 	getprogname.c h_errno.c hex.c hostent_find_fqdn.c issuid.c \
 	k_getpwnam.c k_getpwuid.c mini_inetd.c net_read.c net_write.c \
-	parse_bytes.c parse_time.c parse_units.c realloc.c resolve.c \
-	roken_gethostby.c rtbl.c rtbl.h setprogname.c signal.c \
-	simple_exec.c snprintf.c socket.c strcollect.c strpool.c \
-	timeval.c tm2time.c unvis.c verify.c vis.c vis.h warnerr.c \
-	write_pid.c xdbm.h $(am__append_1)
+	parse_bytes.c parse_time.c parse_units.c qsort.c rand.c \
+	realloc.c resolve.c roken_gethostby.c rtbl.c rtbl.h \
+	setprogname.c signal.c simple_exec.c snprintf.c socket.c \
+	strcollect.c strerror_r.c strpool.c timeval.c tm2time.c \
+	unvis.c verify.c vis.c warnerr.c write_pid.c xfree.c xdbm.h \
+	$(am__append_3)
 EXTRA_libroken_la_SOURCES =3D \
 	err.hin			\
 	glob.hin		\
 	fnmatch.hin		\
 	ifaddrs.hin		\
+	search.hin		\
 	vis.hin=09
=20
-libroken_la_LIBADD =3D @LTLIBOBJS@
-BUILT_SOURCES =3D make-roken.c roken.h
+libroken_la_LIBADD =3D @LTLIBOBJS@ $(LIB_crypt)
+BUILT_SOURCES =3D roken.h $(am__append_6)
 @have_err_h_FALSE at err_h =3D err.h
 @have_err_h_TRUE at err_h =3D=20
 @have_fnmatch_h_FALSE at fnmatch_h =3D fnmatch.h
@@ -534,41 +615,46 @@
 @have_glob_h_TRUE at glob_h =3D=20
 @have_ifaddrs_h_FALSE at ifaddrs_h =3D ifaddrs.h
 @have_ifaddrs_h_TRUE at ifaddrs_h =3D=20
+ at have_search_h_FALSE@search_h =3D search.h
+ at have_search_h_TRUE@search_h =3D=20
 @have_vis_h_FALSE at vis_h =3D vis.h
 @have_vis_h_TRUE at vis_h =3D=20
-XHEADERS =3D $(err_h) $(fnmatch_h) $(glob_h) $(ifaddrs_h) $(vis_h)
+XHEADERS =3D $(err_h) $(fnmatch_h) $(glob_h) $(ifaddrs_h) $(search_h) $(vi=
s_h)
 dist_include_HEADERS =3D base64.h getarg.h hex.h parse_bytes.h \
 	parse_time.h parse_units.h resolve.h roken-common.h rtbl.h \
-	xdbm.h $(am__append_2)
+	xdbm.h $(am__append_4)
 build_HEADERZ =3D test-mem.h $(XHEADERS)
 nodist_include_HEADERS =3D roken.h
 rokenincludedir =3D $(includedir)/roken
 nodist_rokeninclude_HEADERS =3D $(XHEADERS)
 man_MANS =3D getarg.3 parse_time.3 rtbl.3 ecalloc.3
+ at CROSS_COMPILE_FALSE@nodist_make_roken_SOURCES =3D make-roken.c
 EXTRA_DIST =3D \
+	NTMakefile \
 	roken.awk roken.h.in \
 	$(man_MANS) \
 	test-mem.h \
 	ndbm_wrap.c \
-	ndbm_wrap.h
+	ndbm_wrap.h \
+	version-script.map
=20
 all: $(BUILT_SOURCES)
 	$(MAKE) $(AM_MAKEFLAGS) all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .hin .c .lo .o=
 .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .hin .c .l=
o .o .obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/roken=
/Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/roken/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/roken/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/roken/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -586,23 +672,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -628,24 +719,31 @@
 	$(libtest_la_LINK)  $(libtest_la_OBJECTS) $(libtest_la_LIBADD) $(LIBS)
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
=20
 clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 base64-test$(EXEEXT): $(base64_test_OBJECTS) $(base64_test_DEPENDENCIES)=20
 	@rm -f base64-test$(EXEEXT)
 	$(LINK) $(base64_test_OBJECTS) $(base64_test_LDADD) $(LIBS)
 getaddrinfo-test$(EXEEXT): $(getaddrinfo_test_OBJECTS) $(getaddrinfo_test_=
DEPENDENCIES)=20
 	@rm -f getaddrinfo-test$(EXEEXT)
 	$(LINK) $(getaddrinfo_test_OBJECTS) $(getaddrinfo_test_LDADD) $(LIBS)
+getifaddrs-test$(EXEEXT): $(getifaddrs_test_OBJECTS) $(getifaddrs_test_DEP=
ENDENCIES)=20
+	@rm -f getifaddrs-test$(EXEEXT)
+	$(LINK) $(getifaddrs_test_OBJECTS) $(getifaddrs_test_LDADD) $(LIBS)
 hex-test$(EXEEXT): $(hex_test_OBJECTS) $(hex_test_DEPENDENCIES)=20
 	@rm -f hex-test$(EXEEXT)
 	$(LINK) $(hex_test_OBJECTS) $(hex_test_LDADD) $(LIBS)
@@ -664,6 +762,9 @@
 resolve-test$(EXEEXT): $(resolve_test_OBJECTS) $(resolve_test_DEPENDENCIES=
)=20
 	@rm -f resolve-test$(EXEEXT)
 	$(LINK) $(resolve_test_OBJECTS) $(resolve_test_LDADD) $(LIBS)
+rkpty$(EXEEXT): $(rkpty_OBJECTS) $(rkpty_DEPENDENCIES)=20
+	@rm -f rkpty$(EXEEXT)
+	$(LINK) $(rkpty_OBJECTS) $(rkpty_LDADD) $(LIBS)
 snprintf-test$(EXEEXT): $(snprintf_test_OBJECTS) $(snprintf_test_DEPENDENC=
IES)=20
 	@rm -f snprintf-test$(EXEEXT)
 	$(snprintf_test_LINK) $(snprintf_test_OBJECTS) $(snprintf_test_LDADD) $(L=
IBS)
@@ -673,6 +774,9 @@
 test-readenv$(EXEEXT): $(test_readenv_OBJECTS) $(test_readenv_DEPENDENCIES=
)=20
 	@rm -f test-readenv$(EXEEXT)
 	$(LINK) $(test_readenv_OBJECTS) $(test_readenv_LDADD) $(LIBS)
+tsearch-test$(EXEEXT): $(tsearch_test_OBJECTS) $(tsearch_test_DEPENDENCIES=
)=20
+	@rm -f tsearch-test$(EXEEXT)
+	$(tsearch_test_LINK) $(tsearch_test_OBJECTS) $(tsearch_test_LDADD) $(LIBS)
=20
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
@@ -680,337 +784,802 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/chown.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/closefrom.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/copyhostent.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/daemon.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/ecalloc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/emalloc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/erealloc.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/err.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/errx.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/estrdup.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/fchown.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/flock.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/fnmatch.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/freeaddrinfo.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/freehostent.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/gai_strerror.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getaddrinfo.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getcap.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getcwd.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getdtablesize.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getegid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/geteuid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getgid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/gethostname.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getifaddrs.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getipnodebyaddr.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getipnodebyname.Plo at am__quo=
te@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getnameinfo.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getopt.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/gettimeofday.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getuid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/getusershell.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/glob.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/hstrerror.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/inet_aton.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/inet_ntop.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/inet_pton.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/initgroups.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/innetgr.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/iruserok.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/localtime_r.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/lstat.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/memmove.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/mkstemp.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/putenv.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/rcmd.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/readv.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/recvmsg.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/sendmsg.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/setegid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/setenv.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/seteuid.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strcasecmp.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strdup.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strerror.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strftime.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strlcat.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strlcpy.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strlwr.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strncasecmp.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strndup.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strnlen.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strptime.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strsep.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strsep_copy.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strtok_r.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/strupr.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/swab.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/timegm.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/tsearch.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/unsetenv.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/verr.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/verrx.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/vsyslog.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/vwarn.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/vwarnx.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/warn.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/warnx.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote@$(DEPDIR)/writev.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/base64-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/getaddrinfo-test.Po at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/getifaddrs-test.Po at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/hex-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-base64.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-bswap.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-cloexec.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-concat.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-ct.Plo at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-doxygen.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-dumpdata.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-environment.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-eread.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-esetenv.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-ewrite.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-get_default_u=
sername.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-get_window_si=
ze.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-getaddrinfo_h=
ostspec.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-getarg.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-getnameinfo_v=
erified.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-getprogname.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-h_errno.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-hex.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-hostent_find_=
fqdn.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-issuid.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-k_getpwnam.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-k_getpwuid.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-mini_inetd.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-net_read.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-net_write.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-parse_bytes.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-parse_time.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-parse_units.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-qsort.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-rand.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-realloc.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-resolve.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-roken_gethost=
by.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-rtbl.Plo at am__=
quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-setprogname.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-signal.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-simple_exec.P=
lo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-snprintf.Plo@=
am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-socket.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-socket_wrappe=
r.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-strcollect.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-strerror_r.Pl=
o at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-strpool.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-timeval.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-tm2time.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-unvis.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-verify.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-vis.Plo at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-warnerr.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-write_pid.Plo=
@am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libroken_la-xfree.Plo at am_=
_quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libtest_la-snprintf.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libtest_la-strftime.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libtest_la-strptime.Plo at a=
m__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/libtest_la-tsearch.Plo at am=
__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/make-roken.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/parse_bytes-test.Po at am__q=
uote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/parse_reply_test-parse_re=
ply-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/parse_reply_test-resolve.=
Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/parse_time-test.Po at am__qu=
ote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/resolve-test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/rkpty.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/snprintf_test-snprintf-te=
st.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/strpftime_test-strpftime-=
test.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-mem.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test-readenv.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/tsearch_test-tsearch-test=
.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 libroken_la-base64.lo: base64.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-base64.lo `test -f 'base64=
.c' || echo '$(srcdir)/'`base64.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-base64.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-base64.Tpo -c -o libroken_la-base64.lo=
 `test -f 'base64.c' || echo '$(srcdir)/'`base64.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-base64.Tpo $(DEPDIR)/=
libroken_la-base64.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'base64.c' object=3D'libroken_l=
a-base64.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-base=
64.lo `test -f 'base64.c' || echo '$(srcdir)/'`base64.c
=20
 libroken_la-bswap.lo: bswap.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-bswap.lo `test -f 'bswap.c=
' || echo '$(srcdir)/'`bswap.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-bswap.l=
o -MD -MP -MF $(DEPDIR)/libroken_la-bswap.Tpo -c -o libroken_la-bswap.lo `t=
est -f 'bswap.c' || echo '$(srcdir)/'`bswap.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-bswap.Tpo $(DEPDIR)/l=
ibroken_la-bswap.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'bswap.c' object=3D'libroken_la=
-bswap.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-bswa=
p.lo `test -f 'bswap.c' || echo '$(srcdir)/'`bswap.c
=20
 libroken_la-concat.lo: concat.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-concat.lo `test -f 'concat=
.c' || echo '$(srcdir)/'`concat.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-concat.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-concat.Tpo -c -o libroken_la-concat.lo=
 `test -f 'concat.c' || echo '$(srcdir)/'`concat.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-concat.Tpo $(DEPDIR)/=
libroken_la-concat.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'concat.c' object=3D'libroken_l=
a-concat.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-conc=
at.lo `test -f 'concat.c' || echo '$(srcdir)/'`concat.c
+
+libroken_la-cloexec.lo: cloexec.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-cloexec=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-cloexec.Tpo -c -o libroken_la-cloexec=
.lo `test -f 'cloexec.c' || echo '$(srcdir)/'`cloexec.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-cloexec.Tpo $(DEPDIR)=
/libroken_la-cloexec.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'cloexec.c' object=3D'libroken_=
la-cloexec.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-cloe=
xec.lo `test -f 'cloexec.c' || echo '$(srcdir)/'`cloexec.c
+
+libroken_la-ct.lo: ct.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-ct.lo -=
MD -MP -MF $(DEPDIR)/libroken_la-ct.Tpo -c -o libroken_la-ct.lo `test -f 'c=
t.c' || echo '$(srcdir)/'`ct.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-ct.Tpo $(DEPDIR)/libr=
oken_la-ct.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ct.c' object=3D'libroken_la-ct=
.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-ct.l=
o `test -f 'ct.c' || echo '$(srcdir)/'`ct.c
+
+libroken_la-doxygen.lo: doxygen.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-doxygen=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-doxygen.Tpo -c -o libroken_la-doxygen=
.lo `test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-doxygen.Tpo $(DEPDIR)=
/libroken_la-doxygen.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'doxygen.c' object=3D'libroken_=
la-doxygen.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-doxy=
gen.lo `test -f 'doxygen.c' || echo '$(srcdir)/'`doxygen.c
=20
 libroken_la-dumpdata.lo: dumpdata.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-dumpdata.lo `test -f 'dump=
data.c' || echo '$(srcdir)/'`dumpdata.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-dumpdat=
a.lo -MD -MP -MF $(DEPDIR)/libroken_la-dumpdata.Tpo -c -o libroken_la-dumpd=
ata.lo `test -f 'dumpdata.c' || echo '$(srcdir)/'`dumpdata.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-dumpdata.Tpo $(DEPDIR=
)/libroken_la-dumpdata.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'dumpdata.c' object=3D'libroken=
_la-dumpdata.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-dump=
data.lo `test -f 'dumpdata.c' || echo '$(srcdir)/'`dumpdata.c
=20
 libroken_la-environment.lo: environment.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-environment.lo `test -f 'e=
nvironment.c' || echo '$(srcdir)/'`environment.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-environ=
ment.lo -MD -MP -MF $(DEPDIR)/libroken_la-environment.Tpo -c -o libroken_la=
-environment.lo `test -f 'environment.c' || echo '$(srcdir)/'`environment.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-environment.Tpo $(DEP=
DIR)/libroken_la-environment.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'environment.c' object=3D'libro=
ken_la-environment.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-envi=
ronment.lo `test -f 'environment.c' || echo '$(srcdir)/'`environment.c
=20
 libroken_la-eread.lo: eread.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-eread.lo `test -f 'eread.c=
' || echo '$(srcdir)/'`eread.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-eread.l=
o -MD -MP -MF $(DEPDIR)/libroken_la-eread.Tpo -c -o libroken_la-eread.lo `t=
est -f 'eread.c' || echo '$(srcdir)/'`eread.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-eread.Tpo $(DEPDIR)/l=
ibroken_la-eread.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'eread.c' object=3D'libroken_la=
-eread.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-erea=
d.lo `test -f 'eread.c' || echo '$(srcdir)/'`eread.c
=20
 libroken_la-esetenv.lo: esetenv.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-esetenv.lo `test -f 'esete=
nv.c' || echo '$(srcdir)/'`esetenv.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-esetenv=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-esetenv.Tpo -c -o libroken_la-esetenv=
.lo `test -f 'esetenv.c' || echo '$(srcdir)/'`esetenv.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-esetenv.Tpo $(DEPDIR)=
/libroken_la-esetenv.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'esetenv.c' object=3D'libroken_=
la-esetenv.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-eset=
env.lo `test -f 'esetenv.c' || echo '$(srcdir)/'`esetenv.c
=20
 libroken_la-ewrite.lo: ewrite.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-ewrite.lo `test -f 'ewrite=
.c' || echo '$(srcdir)/'`ewrite.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-ewrite.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-ewrite.Tpo -c -o libroken_la-ewrite.lo=
 `test -f 'ewrite.c' || echo '$(srcdir)/'`ewrite.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-ewrite.Tpo $(DEPDIR)/=
libroken_la-ewrite.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'ewrite.c' object=3D'libroken_l=
a-ewrite.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-ewri=
te.lo `test -f 'ewrite.c' || echo '$(srcdir)/'`ewrite.c
=20
 libroken_la-getaddrinfo_hostspec.lo: getaddrinfo_hostspec.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-getaddrinfo_hostspec.lo `t=
est -f 'getaddrinfo_hostspec.c' || echo '$(srcdir)/'`getaddrinfo_hostspec.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-getaddr=
info_hostspec.lo -MD -MP -MF $(DEPDIR)/libroken_la-getaddrinfo_hostspec.Tpo=
 -c -o libroken_la-getaddrinfo_hostspec.lo `test -f 'getaddrinfo_hostspec.c=
' || echo '$(srcdir)/'`getaddrinfo_hostspec.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-getaddrinfo_hostspec.=
Tpo $(DEPDIR)/libroken_la-getaddrinfo_hostspec.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'getaddrinfo_hostspec.c' object=
=3D'libroken_la-getaddrinfo_hostspec.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-geta=
ddrinfo_hostspec.lo `test -f 'getaddrinfo_hostspec.c' || echo '$(srcdir)/'`=
getaddrinfo_hostspec.c
=20
 libroken_la-get_default_username.lo: get_default_username.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-get_default_username.lo `t=
est -f 'get_default_username.c' || echo '$(srcdir)/'`get_default_username.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-get_def=
ault_username.lo -MD -MP -MF $(DEPDIR)/libroken_la-get_default_username.Tpo=
 -c -o libroken_la-get_default_username.lo `test -f 'get_default_username.c=
' || echo '$(srcdir)/'`get_default_username.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-get_default_username.=
Tpo $(DEPDIR)/libroken_la-get_default_username.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_default_username.c' object=
=3D'libroken_la-get_default_username.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-get_=
default_username.lo `test -f 'get_default_username.c' || echo '$(srcdir)/'`=
get_default_username.c
=20
 libroken_la-get_window_size.lo: get_window_size.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-get_window_size.lo `test -=
f 'get_window_size.c' || echo '$(srcdir)/'`get_window_size.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-get_win=
dow_size.lo -MD -MP -MF $(DEPDIR)/libroken_la-get_window_size.Tpo -c -o lib=
roken_la-get_window_size.lo `test -f 'get_window_size.c' || echo '$(srcdir)=
/'`get_window_size.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-get_window_size.Tpo $=
(DEPDIR)/libroken_la-get_window_size.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'get_window_size.c' object=3D'l=
ibroken_la-get_window_size.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-get_=
window_size.lo `test -f 'get_window_size.c' || echo '$(srcdir)/'`get_window=
_size.c
=20
 libroken_la-getarg.lo: getarg.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-getarg.lo `test -f 'getarg=
.c' || echo '$(srcdir)/'`getarg.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-getarg.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-getarg.Tpo -c -o libroken_la-getarg.lo=
 `test -f 'getarg.c' || echo '$(srcdir)/'`getarg.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-getarg.Tpo $(DEPDIR)/=
libroken_la-getarg.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'getarg.c' object=3D'libroken_l=
a-getarg.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-geta=
rg.lo `test -f 'getarg.c' || echo '$(srcdir)/'`getarg.c
=20
 libroken_la-getnameinfo_verified.lo: getnameinfo_verified.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-getnameinfo_verified.lo `t=
est -f 'getnameinfo_verified.c' || echo '$(srcdir)/'`getnameinfo_verified.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-getname=
info_verified.lo -MD -MP -MF $(DEPDIR)/libroken_la-getnameinfo_verified.Tpo=
 -c -o libroken_la-getnameinfo_verified.lo `test -f 'getnameinfo_verified.c=
' || echo '$(srcdir)/'`getnameinfo_verified.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-getnameinfo_verified.=
Tpo $(DEPDIR)/libroken_la-getnameinfo_verified.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'getnameinfo_verified.c' object=
=3D'libroken_la-getnameinfo_verified.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-getn=
ameinfo_verified.lo `test -f 'getnameinfo_verified.c' || echo '$(srcdir)/'`=
getnameinfo_verified.c
=20
 libroken_la-getprogname.lo: getprogname.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-getprogname.lo `test -f 'g=
etprogname.c' || echo '$(srcdir)/'`getprogname.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-getprog=
name.lo -MD -MP -MF $(DEPDIR)/libroken_la-getprogname.Tpo -c -o libroken_la=
-getprogname.lo `test -f 'getprogname.c' || echo '$(srcdir)/'`getprogname.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-getprogname.Tpo $(DEP=
DIR)/libroken_la-getprogname.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'getprogname.c' object=3D'libro=
ken_la-getprogname.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-getp=
rogname.lo `test -f 'getprogname.c' || echo '$(srcdir)/'`getprogname.c
=20
 libroken_la-h_errno.lo: h_errno.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-h_errno.lo `test -f 'h_err=
no.c' || echo '$(srcdir)/'`h_errno.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-h_errno=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-h_errno.Tpo -c -o libroken_la-h_errno=
.lo `test -f 'h_errno.c' || echo '$(srcdir)/'`h_errno.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-h_errno.Tpo $(DEPDIR)=
/libroken_la-h_errno.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'h_errno.c' object=3D'libroken_=
la-h_errno.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-h_er=
rno.lo `test -f 'h_errno.c' || echo '$(srcdir)/'`h_errno.c
=20
 libroken_la-hex.lo: hex.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-hex.lo `test -f 'hex.c' ||=
 echo '$(srcdir)/'`hex.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-hex.lo =
-MD -MP -MF $(DEPDIR)/libroken_la-hex.Tpo -c -o libroken_la-hex.lo `test -f=
 'hex.c' || echo '$(srcdir)/'`hex.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-hex.Tpo $(DEPDIR)/lib=
roken_la-hex.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'hex.c' object=3D'libroken_la-h=
ex.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-hex.=
lo `test -f 'hex.c' || echo '$(srcdir)/'`hex.c
=20
 libroken_la-hostent_find_fqdn.lo: hostent_find_fqdn.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-hostent_find_fqdn.lo `test=
 -f 'hostent_find_fqdn.c' || echo '$(srcdir)/'`hostent_find_fqdn.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-hostent=
_find_fqdn.lo -MD -MP -MF $(DEPDIR)/libroken_la-hostent_find_fqdn.Tpo -c -o=
 libroken_la-hostent_find_fqdn.lo `test -f 'hostent_find_fqdn.c' || echo '$=
(srcdir)/'`hostent_find_fqdn.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-hostent_find_fqdn.Tpo=
 $(DEPDIR)/libroken_la-hostent_find_fqdn.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'hostent_find_fqdn.c' object=3D=
'libroken_la-hostent_find_fqdn.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-host=
ent_find_fqdn.lo `test -f 'hostent_find_fqdn.c' || echo '$(srcdir)/'`hosten=
t_find_fqdn.c
=20
 libroken_la-issuid.lo: issuid.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-issuid.lo `test -f 'issuid=
.c' || echo '$(srcdir)/'`issuid.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-issuid.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-issuid.Tpo -c -o libroken_la-issuid.lo=
 `test -f 'issuid.c' || echo '$(srcdir)/'`issuid.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-issuid.Tpo $(DEPDIR)/=
libroken_la-issuid.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'issuid.c' object=3D'libroken_l=
a-issuid.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-issu=
id.lo `test -f 'issuid.c' || echo '$(srcdir)/'`issuid.c
=20
 libroken_la-k_getpwnam.lo: k_getpwnam.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-k_getpwnam.lo `test -f 'k_=
getpwnam.c' || echo '$(srcdir)/'`k_getpwnam.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-k_getpw=
nam.lo -MD -MP -MF $(DEPDIR)/libroken_la-k_getpwnam.Tpo -c -o libroken_la-k=
_getpwnam.lo `test -f 'k_getpwnam.c' || echo '$(srcdir)/'`k_getpwnam.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-k_getpwnam.Tpo $(DEPD=
IR)/libroken_la-k_getpwnam.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'k_getpwnam.c' object=3D'librok=
en_la-k_getpwnam.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-k_ge=
tpwnam.lo `test -f 'k_getpwnam.c' || echo '$(srcdir)/'`k_getpwnam.c
=20
 libroken_la-k_getpwuid.lo: k_getpwuid.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-k_getpwuid.lo `test -f 'k_=
getpwuid.c' || echo '$(srcdir)/'`k_getpwuid.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-k_getpw=
uid.lo -MD -MP -MF $(DEPDIR)/libroken_la-k_getpwuid.Tpo -c -o libroken_la-k=
_getpwuid.lo `test -f 'k_getpwuid.c' || echo '$(srcdir)/'`k_getpwuid.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-k_getpwuid.Tpo $(DEPD=
IR)/libroken_la-k_getpwuid.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'k_getpwuid.c' object=3D'librok=
en_la-k_getpwuid.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-k_ge=
tpwuid.lo `test -f 'k_getpwuid.c' || echo '$(srcdir)/'`k_getpwuid.c
=20
 libroken_la-mini_inetd.lo: mini_inetd.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-mini_inetd.lo `test -f 'mi=
ni_inetd.c' || echo '$(srcdir)/'`mini_inetd.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-mini_in=
etd.lo -MD -MP -MF $(DEPDIR)/libroken_la-mini_inetd.Tpo -c -o libroken_la-m=
ini_inetd.lo `test -f 'mini_inetd.c' || echo '$(srcdir)/'`mini_inetd.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-mini_inetd.Tpo $(DEPD=
IR)/libroken_la-mini_inetd.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'mini_inetd.c' object=3D'librok=
en_la-mini_inetd.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-mini=
_inetd.lo `test -f 'mini_inetd.c' || echo '$(srcdir)/'`mini_inetd.c
=20
 libroken_la-net_read.lo: net_read.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-net_read.lo `test -f 'net_=
read.c' || echo '$(srcdir)/'`net_read.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-net_rea=
d.lo -MD -MP -MF $(DEPDIR)/libroken_la-net_read.Tpo -c -o libroken_la-net_r=
ead.lo `test -f 'net_read.c' || echo '$(srcdir)/'`net_read.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-net_read.Tpo $(DEPDIR=
)/libroken_la-net_read.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'net_read.c' object=3D'libroken=
_la-net_read.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-net_=
read.lo `test -f 'net_read.c' || echo '$(srcdir)/'`net_read.c
=20
 libroken_la-net_write.lo: net_write.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-net_write.lo `test -f 'net=
_write.c' || echo '$(srcdir)/'`net_write.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-net_wri=
te.lo -MD -MP -MF $(DEPDIR)/libroken_la-net_write.Tpo -c -o libroken_la-net=
_write.lo `test -f 'net_write.c' || echo '$(srcdir)/'`net_write.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-net_write.Tpo $(DEPDI=
R)/libroken_la-net_write.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'net_write.c' object=3D'libroke=
n_la-net_write.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-net_=
write.lo `test -f 'net_write.c' || echo '$(srcdir)/'`net_write.c
=20
 libroken_la-parse_bytes.lo: parse_bytes.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-parse_bytes.lo `test -f 'p=
arse_bytes.c' || echo '$(srcdir)/'`parse_bytes.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-parse_b=
ytes.lo -MD -MP -MF $(DEPDIR)/libroken_la-parse_bytes.Tpo -c -o libroken_la=
-parse_bytes.lo `test -f 'parse_bytes.c' || echo '$(srcdir)/'`parse_bytes.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-parse_bytes.Tpo $(DEP=
DIR)/libroken_la-parse_bytes.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'parse_bytes.c' object=3D'libro=
ken_la-parse_bytes.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-pars=
e_bytes.lo `test -f 'parse_bytes.c' || echo '$(srcdir)/'`parse_bytes.c
=20
 libroken_la-parse_time.lo: parse_time.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-parse_time.lo `test -f 'pa=
rse_time.c' || echo '$(srcdir)/'`parse_time.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-parse_t=
ime.lo -MD -MP -MF $(DEPDIR)/libroken_la-parse_time.Tpo -c -o libroken_la-p=
arse_time.lo `test -f 'parse_time.c' || echo '$(srcdir)/'`parse_time.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-parse_time.Tpo $(DEPD=
IR)/libroken_la-parse_time.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'parse_time.c' object=3D'librok=
en_la-parse_time.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-pars=
e_time.lo `test -f 'parse_time.c' || echo '$(srcdir)/'`parse_time.c
=20
 libroken_la-parse_units.lo: parse_units.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-parse_units.lo `test -f 'p=
arse_units.c' || echo '$(srcdir)/'`parse_units.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-parse_u=
nits.lo -MD -MP -MF $(DEPDIR)/libroken_la-parse_units.Tpo -c -o libroken_la=
-parse_units.lo `test -f 'parse_units.c' || echo '$(srcdir)/'`parse_units.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-parse_units.Tpo $(DEP=
DIR)/libroken_la-parse_units.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'parse_units.c' object=3D'libro=
ken_la-parse_units.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-pars=
e_units.lo `test -f 'parse_units.c' || echo '$(srcdir)/'`parse_units.c
+
+libroken_la-qsort.lo: qsort.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-qsort.l=
o -MD -MP -MF $(DEPDIR)/libroken_la-qsort.Tpo -c -o libroken_la-qsort.lo `t=
est -f 'qsort.c' || echo '$(srcdir)/'`qsort.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-qsort.Tpo $(DEPDIR)/l=
ibroken_la-qsort.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'qsort.c' object=3D'libroken_la=
-qsort.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-qsor=
t.lo `test -f 'qsort.c' || echo '$(srcdir)/'`qsort.c
+
+libroken_la-rand.lo: rand.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-rand.lo=
 -MD -MP -MF $(DEPDIR)/libroken_la-rand.Tpo -c -o libroken_la-rand.lo `test=
 -f 'rand.c' || echo '$(srcdir)/'`rand.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-rand.Tpo $(DEPDIR)/li=
broken_la-rand.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rand.c' object=3D'libroken_la-=
rand.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-rand=
.lo `test -f 'rand.c' || echo '$(srcdir)/'`rand.c
=20
 libroken_la-realloc.lo: realloc.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-realloc.lo `test -f 'reall=
oc.c' || echo '$(srcdir)/'`realloc.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-realloc=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-realloc.Tpo -c -o libroken_la-realloc=
.lo `test -f 'realloc.c' || echo '$(srcdir)/'`realloc.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-realloc.Tpo $(DEPDIR)=
/libroken_la-realloc.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'realloc.c' object=3D'libroken_=
la-realloc.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-real=
loc.lo `test -f 'realloc.c' || echo '$(srcdir)/'`realloc.c
=20
 libroken_la-resolve.lo: resolve.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-resolve.lo `test -f 'resol=
ve.c' || echo '$(srcdir)/'`resolve.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-resolve=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-resolve.Tpo -c -o libroken_la-resolve=
.lo `test -f 'resolve.c' || echo '$(srcdir)/'`resolve.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-resolve.Tpo $(DEPDIR)=
/libroken_la-resolve.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'resolve.c' object=3D'libroken_=
la-resolve.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-reso=
lve.lo `test -f 'resolve.c' || echo '$(srcdir)/'`resolve.c
=20
 libroken_la-roken_gethostby.lo: roken_gethostby.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-roken_gethostby.lo `test -=
f 'roken_gethostby.c' || echo '$(srcdir)/'`roken_gethostby.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-roken_g=
ethostby.lo -MD -MP -MF $(DEPDIR)/libroken_la-roken_gethostby.Tpo -c -o lib=
roken_la-roken_gethostby.lo `test -f 'roken_gethostby.c' || echo '$(srcdir)=
/'`roken_gethostby.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-roken_gethostby.Tpo $=
(DEPDIR)/libroken_la-roken_gethostby.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'roken_gethostby.c' object=3D'l=
ibroken_la-roken_gethostby.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-roke=
n_gethostby.lo `test -f 'roken_gethostby.c' || echo '$(srcdir)/'`roken_geth=
ostby.c
=20
 libroken_la-rtbl.lo: rtbl.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-rtbl.lo `test -f 'rtbl.c' =
|| echo '$(srcdir)/'`rtbl.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-rtbl.lo=
 -MD -MP -MF $(DEPDIR)/libroken_la-rtbl.Tpo -c -o libroken_la-rtbl.lo `test=
 -f 'rtbl.c' || echo '$(srcdir)/'`rtbl.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-rtbl.Tpo $(DEPDIR)/li=
broken_la-rtbl.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'rtbl.c' object=3D'libroken_la-=
rtbl.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-rtbl=
.lo `test -f 'rtbl.c' || echo '$(srcdir)/'`rtbl.c
=20
 libroken_la-setprogname.lo: setprogname.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-setprogname.lo `test -f 's=
etprogname.c' || echo '$(srcdir)/'`setprogname.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-setprog=
name.lo -MD -MP -MF $(DEPDIR)/libroken_la-setprogname.Tpo -c -o libroken_la=
-setprogname.lo `test -f 'setprogname.c' || echo '$(srcdir)/'`setprogname.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-setprogname.Tpo $(DEP=
DIR)/libroken_la-setprogname.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'setprogname.c' object=3D'libro=
ken_la-setprogname.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-setp=
rogname.lo `test -f 'setprogname.c' || echo '$(srcdir)/'`setprogname.c
=20
 libroken_la-signal.lo: signal.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-signal.lo `test -f 'signal=
.c' || echo '$(srcdir)/'`signal.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-signal.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-signal.Tpo -c -o libroken_la-signal.lo=
 `test -f 'signal.c' || echo '$(srcdir)/'`signal.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-signal.Tpo $(DEPDIR)/=
libroken_la-signal.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'signal.c' object=3D'libroken_l=
a-signal.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-sign=
al.lo `test -f 'signal.c' || echo '$(srcdir)/'`signal.c
=20
 libroken_la-simple_exec.lo: simple_exec.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-simple_exec.lo `test -f 's=
imple_exec.c' || echo '$(srcdir)/'`simple_exec.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-simple_=
exec.lo -MD -MP -MF $(DEPDIR)/libroken_la-simple_exec.Tpo -c -o libroken_la=
-simple_exec.lo `test -f 'simple_exec.c' || echo '$(srcdir)/'`simple_exec.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-simple_exec.Tpo $(DEP=
DIR)/libroken_la-simple_exec.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'simple_exec.c' object=3D'libro=
ken_la-simple_exec.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-simp=
le_exec.lo `test -f 'simple_exec.c' || echo '$(srcdir)/'`simple_exec.c
=20
 libroken_la-snprintf.lo: snprintf.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-snprintf.lo `test -f 'snpr=
intf.c' || echo '$(srcdir)/'`snprintf.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-snprint=
f.lo -MD -MP -MF $(DEPDIR)/libroken_la-snprintf.Tpo -c -o libroken_la-snpri=
ntf.lo `test -f 'snprintf.c' || echo '$(srcdir)/'`snprintf.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-snprintf.Tpo $(DEPDIR=
)/libroken_la-snprintf.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'snprintf.c' object=3D'libroken=
_la-snprintf.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-snpr=
intf.lo `test -f 'snprintf.c' || echo '$(srcdir)/'`snprintf.c
=20
 libroken_la-socket.lo: socket.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-socket.lo `test -f 'socket=
.c' || echo '$(srcdir)/'`socket.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-socket.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-socket.Tpo -c -o libroken_la-socket.lo=
 `test -f 'socket.c' || echo '$(srcdir)/'`socket.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-socket.Tpo $(DEPDIR)/=
libroken_la-socket.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'socket.c' object=3D'libroken_l=
a-socket.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-sock=
et.lo `test -f 'socket.c' || echo '$(srcdir)/'`socket.c
=20
 libroken_la-strcollect.lo: strcollect.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-strcollect.lo `test -f 'st=
rcollect.c' || echo '$(srcdir)/'`strcollect.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-strcoll=
ect.lo -MD -MP -MF $(DEPDIR)/libroken_la-strcollect.Tpo -c -o libroken_la-s=
trcollect.lo `test -f 'strcollect.c' || echo '$(srcdir)/'`strcollect.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-strcollect.Tpo $(DEPD=
IR)/libroken_la-strcollect.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strcollect.c' object=3D'librok=
en_la-strcollect.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-strc=
ollect.lo `test -f 'strcollect.c' || echo '$(srcdir)/'`strcollect.c
+
+libroken_la-strerror_r.lo: strerror_r.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-strerro=
r_r.lo -MD -MP -MF $(DEPDIR)/libroken_la-strerror_r.Tpo -c -o libroken_la-s=
trerror_r.lo `test -f 'strerror_r.c' || echo '$(srcdir)/'`strerror_r.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-strerror_r.Tpo $(DEPD=
IR)/libroken_la-strerror_r.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strerror_r.c' object=3D'librok=
en_la-strerror_r.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-stre=
rror_r.lo `test -f 'strerror_r.c' || echo '$(srcdir)/'`strerror_r.c
=20
 libroken_la-strpool.lo: strpool.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-strpool.lo `test -f 'strpo=
ol.c' || echo '$(srcdir)/'`strpool.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-strpool=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-strpool.Tpo -c -o libroken_la-strpool=
.lo `test -f 'strpool.c' || echo '$(srcdir)/'`strpool.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-strpool.Tpo $(DEPDIR)=
/libroken_la-strpool.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strpool.c' object=3D'libroken_=
la-strpool.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-strp=
ool.lo `test -f 'strpool.c' || echo '$(srcdir)/'`strpool.c
=20
 libroken_la-timeval.lo: timeval.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-timeval.lo `test -f 'timev=
al.c' || echo '$(srcdir)/'`timeval.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-timeval=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-timeval.Tpo -c -o libroken_la-timeval=
.lo `test -f 'timeval.c' || echo '$(srcdir)/'`timeval.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-timeval.Tpo $(DEPDIR)=
/libroken_la-timeval.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'timeval.c' object=3D'libroken_=
la-timeval.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-time=
val.lo `test -f 'timeval.c' || echo '$(srcdir)/'`timeval.c
=20
 libroken_la-tm2time.lo: tm2time.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-tm2time.lo `test -f 'tm2ti=
me.c' || echo '$(srcdir)/'`tm2time.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-tm2time=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-tm2time.Tpo -c -o libroken_la-tm2time=
.lo `test -f 'tm2time.c' || echo '$(srcdir)/'`tm2time.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-tm2time.Tpo $(DEPDIR)=
/libroken_la-tm2time.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'tm2time.c' object=3D'libroken_=
la-tm2time.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-tm2t=
ime.lo `test -f 'tm2time.c' || echo '$(srcdir)/'`tm2time.c
=20
 libroken_la-unvis.lo: unvis.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-unvis.lo `test -f 'unvis.c=
' || echo '$(srcdir)/'`unvis.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-unvis.l=
o -MD -MP -MF $(DEPDIR)/libroken_la-unvis.Tpo -c -o libroken_la-unvis.lo `t=
est -f 'unvis.c' || echo '$(srcdir)/'`unvis.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-unvis.Tpo $(DEPDIR)/l=
ibroken_la-unvis.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'unvis.c' object=3D'libroken_la=
-unvis.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-unvi=
s.lo `test -f 'unvis.c' || echo '$(srcdir)/'`unvis.c
=20
 libroken_la-verify.lo: verify.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-verify.lo `test -f 'verify=
.c' || echo '$(srcdir)/'`verify.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-verify.=
lo -MD -MP -MF $(DEPDIR)/libroken_la-verify.Tpo -c -o libroken_la-verify.lo=
 `test -f 'verify.c' || echo '$(srcdir)/'`verify.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-verify.Tpo $(DEPDIR)/=
libroken_la-verify.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'verify.c' object=3D'libroken_l=
a-verify.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-veri=
fy.lo `test -f 'verify.c' || echo '$(srcdir)/'`verify.c
=20
 libroken_la-vis.lo: vis.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-vis.lo `test -f 'vis.c' ||=
 echo '$(srcdir)/'`vis.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-vis.lo =
-MD -MP -MF $(DEPDIR)/libroken_la-vis.Tpo -c -o libroken_la-vis.lo `test -f=
 'vis.c' || echo '$(srcdir)/'`vis.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-vis.Tpo $(DEPDIR)/lib=
roken_la-vis.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'vis.c' object=3D'libroken_la-v=
is.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-vis.=
lo `test -f 'vis.c' || echo '$(srcdir)/'`vis.c
=20
 libroken_la-warnerr.lo: warnerr.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-warnerr.lo `test -f 'warne=
rr.c' || echo '$(srcdir)/'`warnerr.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-warnerr=
.lo -MD -MP -MF $(DEPDIR)/libroken_la-warnerr.Tpo -c -o libroken_la-warnerr=
.lo `test -f 'warnerr.c' || echo '$(srcdir)/'`warnerr.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-warnerr.Tpo $(DEPDIR)=
/libroken_la-warnerr.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'warnerr.c' object=3D'libroken_=
la-warnerr.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-warn=
err.lo `test -f 'warnerr.c' || echo '$(srcdir)/'`warnerr.c
=20
 libroken_la-write_pid.lo: write_pid.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-write_pid.lo `test -f 'wri=
te_pid.c' || echo '$(srcdir)/'`write_pid.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-write_p=
id.lo -MD -MP -MF $(DEPDIR)/libroken_la-write_pid.Tpo -c -o libroken_la-wri=
te_pid.lo `test -f 'write_pid.c' || echo '$(srcdir)/'`write_pid.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-write_pid.Tpo $(DEPDI=
R)/libroken_la-write_pid.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'write_pid.c' object=3D'libroke=
n_la-write_pid.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-writ=
e_pid.lo `test -f 'write_pid.c' || echo '$(srcdir)/'`write_pid.c
+
+libroken_la-xfree.lo: xfree.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-xfree.l=
o -MD -MP -MF $(DEPDIR)/libroken_la-xfree.Tpo -c -o libroken_la-xfree.lo `t=
est -f 'xfree.c' || echo '$(srcdir)/'`xfree.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-xfree.Tpo $(DEPDIR)/l=
ibroken_la-xfree.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'xfree.c' object=3D'libroken_la=
-xfree.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-xfre=
e.lo `test -f 'xfree.c' || echo '$(srcdir)/'`xfree.c
=20
 libroken_la-socket_wrapper.lo: socket_wrapper.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libroken_la_CPPFLAGS) $(CP=
PFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-socket_wrapper.lo `test -f=
 'socket_wrapper.c' || echo '$(srcdir)/'`socket_wrapper.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libro=
ken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT libroken_la-socket_=
wrapper.lo -MD -MP -MF $(DEPDIR)/libroken_la-socket_wrapper.Tpo -c -o libro=
ken_la-socket_wrapper.lo `test -f 'socket_wrapper.c' || echo '$(srcdir)/'`s=
ocket_wrapper.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libroken_la-socket_wrapper.Tpo $(=
DEPDIR)/libroken_la-socket_wrapper.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'socket_wrapper.c' object=3D'li=
broken_la-socket_wrapper.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(libr=
oken_la_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o libroken_la-sock=
et_wrapper.lo `test -f 'socket_wrapper.c' || echo '$(srcdir)/'`socket_wrapp=
er.c
=20
 libtest_la-strftime.lo: strftime.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $=
(libtest_la_CFLAGS) $(CFLAGS) -c -o libtest_la-strftime.lo `test -f 'strfti=
me.c' || echo '$(srcdir)/'`strftime.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -MT libtest_la-strftime.=
lo -MD -MP -MF $(DEPDIR)/libtest_la-strftime.Tpo -c -o libtest_la-strftime.=
lo `test -f 'strftime.c' || echo '$(srcdir)/'`strftime.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libtest_la-strftime.Tpo $(DEPDIR)=
/libtest_la-strftime.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strftime.c' object=3D'libtest_=
la-strftime.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -c -o libtest_la-strfti=
me.lo `test -f 'strftime.c' || echo '$(srcdir)/'`strftime.c
=20
 libtest_la-strptime.lo: strptime.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $=
(libtest_la_CFLAGS) $(CFLAGS) -c -o libtest_la-strptime.lo `test -f 'strpti=
me.c' || echo '$(srcdir)/'`strptime.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -MT libtest_la-strptime.=
lo -MD -MP -MF $(DEPDIR)/libtest_la-strptime.Tpo -c -o libtest_la-strptime.=
lo `test -f 'strptime.c' || echo '$(srcdir)/'`strptime.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libtest_la-strptime.Tpo $(DEPDIR)=
/libtest_la-strptime.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strptime.c' object=3D'libtest_=
la-strptime.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -c -o libtest_la-strpti=
me.lo `test -f 'strptime.c' || echo '$(srcdir)/'`strptime.c
=20
 libtest_la-snprintf.lo: snprintf.c
-	$(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dcompile=
 $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $=
(libtest_la_CFLAGS) $(CFLAGS) -c -o libtest_la-snprintf.lo `test -f 'snprin=
tf.c' || echo '$(srcdir)/'`snprintf.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -MT libtest_la-snprintf.=
lo -MD -MP -MF $(DEPDIR)/libtest_la-snprintf.Tpo -c -o libtest_la-snprintf.=
lo `test -f 'snprintf.c' || echo '$(srcdir)/'`snprintf.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libtest_la-snprintf.Tpo $(DEPDIR)=
/libtest_la-snprintf.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'snprintf.c' object=3D'libtest_=
la-snprintf.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -c -o libtest_la-snprin=
tf.lo `test -f 'snprintf.c' || echo '$(srcdir)/'`snprintf.c
+
+libtest_la-tsearch.lo: tsearch.c
+ at am__fastdepCC_TRUE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFL=
AGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -MT libtest_la-tsearch.l=
o -MD -MP -MF $(DEPDIR)/libtest_la-tsearch.Tpo -c -o libtest_la-tsearch.lo =
`test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/libtest_la-tsearch.Tpo $(DEPDIR)/=
libtest_la-tsearch.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'tsearch.c' object=3D'libtest_l=
a-tsearch.lo' libtool=3Dyes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LIBTOOL)  --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLF=
LAGS) --mode=3Dcompile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(libtest_la_CFLAGS) $(CFLAGS) -c -o libtest_la-tsearc=
h.lo `test -f 'tsearch.c' || echo '$(srcdir)/'`tsearch.c
=20
 parse_reply_test-parse_reply-test.o: parse_reply-test.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply_test-parse_reply-tes=
t.o `test -f 'parse_reply-test.c' || echo '$(srcdir)/'`parse_reply-test.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -MT parse_reply_te=
st-parse_reply-test.o -MD -MP -MF $(DEPDIR)/parse_reply_test-parse_reply-te=
st.Tpo -c -o parse_reply_test-parse_reply-test.o `test -f 'parse_reply-test=
.c' || echo '$(srcdir)/'`parse_reply-test.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/parse_reply_test-parse_reply-test=
.Tpo $(DEPDIR)/parse_reply_test-parse_reply-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'parse_reply-test.c' object=3D'=
parse_reply_test-parse_reply-test.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply=
_test-parse_reply-test.o `test -f 'parse_reply-test.c' || echo '$(srcdir)/'=
`parse_reply-test.c
=20
 parse_reply_test-parse_reply-test.obj: parse_reply-test.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply_test-parse_reply-tes=
t.obj `if test -f 'parse_reply-test.c'; then $(CYGPATH_W) 'parse_reply-test=
.c'; else $(CYGPATH_W) '$(srcdir)/parse_reply-test.c'; fi`
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -MT parse_reply_te=
st-parse_reply-test.obj -MD -MP -MF $(DEPDIR)/parse_reply_test-parse_reply-=
test.Tpo -c -o parse_reply_test-parse_reply-test.obj `if test -f 'parse_rep=
ly-test.c'; then $(CYGPATH_W) 'parse_reply-test.c'; else $(CYGPATH_W) '$(sr=
cdir)/parse_reply-test.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/parse_reply_test-parse_reply-test=
.Tpo $(DEPDIR)/parse_reply_test-parse_reply-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'parse_reply-test.c' object=3D'=
parse_reply_test-parse_reply-test.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply=
_test-parse_reply-test.obj `if test -f 'parse_reply-test.c'; then $(CYGPATH=
_W) 'parse_reply-test.c'; else $(CYGPATH_W) '$(srcdir)/parse_reply-test.c';=
 fi`
=20
 parse_reply_test-resolve.o: resolve.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply_test-resolve.o `test=
 -f 'resolve.c' || echo '$(srcdir)/'`resolve.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -MT parse_reply_te=
st-resolve.o -MD -MP -MF $(DEPDIR)/parse_reply_test-resolve.Tpo -c -o parse=
_reply_test-resolve.o `test -f 'resolve.c' || echo '$(srcdir)/'`resolve.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/parse_reply_test-resolve.Tpo $(DE=
PDIR)/parse_reply_test-resolve.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'resolve.c' object=3D'parse_rep=
ly_test-resolve.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply=
_test-resolve.o `test -f 'resolve.c' || echo '$(srcdir)/'`resolve.c
=20
 parse_reply_test-resolve.obj: resolve.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply_test-resolve.obj `if=
 test -f 'resolve.c'; then $(CYGPATH_W) 'resolve.c'; else $(CYGPATH_W) '$(s=
rcdir)/resolve.c'; fi`
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -MT parse_reply_te=
st-resolve.obj -MD -MP -MF $(DEPDIR)/parse_reply_test-resolve.Tpo -c -o par=
se_reply_test-resolve.obj `if test -f 'resolve.c'; then $(CYGPATH_W) 'resol=
ve.c'; else $(CYGPATH_W) '$(srcdir)/resolve.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/parse_reply_test-resolve.Tpo $(DE=
PDIR)/parse_reply_test-resolve.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'resolve.c' object=3D'parse_rep=
ly_test-resolve.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(parse_reply_test_CFLAGS) $(CFLAGS) -c -o parse_reply=
_test-resolve.obj `if test -f 'resolve.c'; then $(CYGPATH_W) 'resolve.c'; e=
lse $(CYGPATH_W) '$(srcdir)/resolve.c'; fi`
=20
 snprintf_test-snprintf-test.o: snprintf-test.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(snprintf_test_CFLAGS) $(CFLAGS) -c -o snprintf_test-snprintf-test.o `test=
 -f 'snprintf-test.c' || echo '$(srcdir)/'`snprintf-test.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(snprintf_test_CFLAGS) $(CFLAGS) -MT snprintf_test-snp=
rintf-test.o -MD -MP -MF $(DEPDIR)/snprintf_test-snprintf-test.Tpo -c -o sn=
printf_test-snprintf-test.o `test -f 'snprintf-test.c' || echo '$(srcdir)/'=
`snprintf-test.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/snprintf_test-snprintf-test.Tpo $=
(DEPDIR)/snprintf_test-snprintf-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'snprintf-test.c' object=3D'snp=
rintf_test-snprintf-test.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(snprintf_test_CFLAGS) $(CFLAGS) -c -o snprintf_test-=
snprintf-test.o `test -f 'snprintf-test.c' || echo '$(srcdir)/'`snprintf-te=
st.c
=20
 snprintf_test-snprintf-test.obj: snprintf-test.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(snprintf_test_CFLAGS) $(CFLAGS) -c -o snprintf_test-snprintf-test.obj `if=
 test -f 'snprintf-test.c'; then $(CYGPATH_W) 'snprintf-test.c'; else $(CYG=
PATH_W) '$(srcdir)/snprintf-test.c'; fi`
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(snprintf_test_CFLAGS) $(CFLAGS) -MT snprintf_test-snp=
rintf-test.obj -MD -MP -MF $(DEPDIR)/snprintf_test-snprintf-test.Tpo -c -o =
snprintf_test-snprintf-test.obj `if test -f 'snprintf-test.c'; then $(CYGPA=
TH_W) 'snprintf-test.c'; else $(CYGPATH_W) '$(srcdir)/snprintf-test.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/snprintf_test-snprintf-test.Tpo $=
(DEPDIR)/snprintf_test-snprintf-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'snprintf-test.c' object=3D'snp=
rintf_test-snprintf-test.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(snprintf_test_CFLAGS) $(CFLAGS) -c -o snprintf_test-=
snprintf-test.obj `if test -f 'snprintf-test.c'; then $(CYGPATH_W) 'snprint=
f-test.c'; else $(CYGPATH_W) '$(srcdir)/snprintf-test.c'; fi`
=20
 strpftime_test-strpftime-test.o: strpftime-test.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(strpftime_test_CFLAGS) $(CFLAGS) -c -o strpftime_test-strpftime-test.o `t=
est -f 'strpftime-test.c' || echo '$(srcdir)/'`strpftime-test.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(strpftime_test_CFLAGS) $(CFLAGS) -MT strpftime_test-s=
trpftime-test.o -MD -MP -MF $(DEPDIR)/strpftime_test-strpftime-test.Tpo -c =
-o strpftime_test-strpftime-test.o `test -f 'strpftime-test.c' || echo '$(s=
rcdir)/'`strpftime-test.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/strpftime_test-strpftime-test.Tpo=
 $(DEPDIR)/strpftime_test-strpftime-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strpftime-test.c' object=3D'st=
rpftime_test-strpftime-test.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(strpftime_test_CFLAGS) $(CFLAGS) -c -o strpftime_tes=
t-strpftime-test.o `test -f 'strpftime-test.c' || echo '$(srcdir)/'`strpfti=
me-test.c
=20
 strpftime_test-strpftime-test.obj: strpftime-test.c
-	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) =
$(strpftime_test_CFLAGS) $(CFLAGS) -c -o strpftime_test-strpftime-test.obj =
`if test -f 'strpftime-test.c'; then $(CYGPATH_W) 'strpftime-test.c'; else =
$(CYGPATH_W) '$(srcdir)/strpftime-test.c'; fi`
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(strpftime_test_CFLAGS) $(CFLAGS) -MT strpftime_test-s=
trpftime-test.obj -MD -MP -MF $(DEPDIR)/strpftime_test-strpftime-test.Tpo -=
c -o strpftime_test-strpftime-test.obj `if test -f 'strpftime-test.c'; then=
 $(CYGPATH_W) 'strpftime-test.c'; else $(CYGPATH_W) '$(srcdir)/strpftime-te=
st.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/strpftime_test-strpftime-test.Tpo=
 $(DEPDIR)/strpftime_test-strpftime-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'strpftime-test.c' object=3D'st=
rpftime_test-strpftime-test.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(strpftime_test_CFLAGS) $(CFLAGS) -c -o strpftime_tes=
t-strpftime-test.obj `if test -f 'strpftime-test.c'; then $(CYGPATH_W) 'str=
pftime-test.c'; else $(CYGPATH_W) '$(srcdir)/strpftime-test.c'; fi`
+
+tsearch_test-tsearch-test.o: tsearch-test.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(tsearch_test_CFLAGS) $(CFLAGS) -MT tsearch_test-tsear=
ch-test.o -MD -MP -MF $(DEPDIR)/tsearch_test-tsearch-test.Tpo -c -o tsearch=
_test-tsearch-test.o `test -f 'tsearch-test.c' || echo '$(srcdir)/'`tsearch=
-test.c
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/tsearch_test-tsearch-test.Tpo $(D=
EPDIR)/tsearch_test-tsearch-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'tsearch-test.c' object=3D'tsea=
rch_test-tsearch-test.o' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(tsearch_test_CFLAGS) $(CFLAGS) -c -o tsearch_test-ts=
earch-test.o `test -f 'tsearch-test.c' || echo '$(srcdir)/'`tsearch-test.c
+
+tsearch_test-tsearch-test.obj: tsearch-test.c
+ at am__fastdepCC_TRUE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CP=
PFLAGS) $(CPPFLAGS) $(tsearch_test_CFLAGS) $(CFLAGS) -MT tsearch_test-tsear=
ch-test.obj -MD -MP -MF $(DEPDIR)/tsearch_test-tsearch-test.Tpo -c -o tsear=
ch_test-tsearch-test.obj `if test -f 'tsearch-test.c'; then $(CYGPATH_W) 't=
search-test.c'; else $(CYGPATH_W) '$(srcdir)/tsearch-test.c'; fi`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/tsearch_test-tsearch-test.Tpo $(D=
EPDIR)/tsearch_test-tsearch-test.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'tsearch-test.c' object=3D'tsea=
rch_test-tsearch-test.obj' libtool=3Dno @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_C=
PPFLAGS) $(CPPFLAGS) $(tsearch_test_CFLAGS) $(CFLAGS) -c -o tsearch_test-ts=
earch-test.obj `if test -f 'tsearch-test.c'; then $(CYGPATH_W) 'tsearch-tes=
t.c'; else $(CYGPATH_W) '$(srcdir)/tsearch-test.c'; fi`
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man3: $(man3_MANS) $(man_MANS)
+install-man3: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man3dir)" || $(MKDIR_P) "$(DESTDIR)$(man3dir)"
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man3dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man3dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man3:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man3_MANS) $(dist_man3_MANS) $(nodist_man3_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.3*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    3*) ;; \
-	    *) ext=3D'3' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man3dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man3dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man3dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.3[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^3][0-9a-z]*$$,3,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man3dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man3dir)" && rm -f $$files; }
 install-dist_includeHEADERS: $(dist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(dist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)=
/$$f'"; \
-	  $(dist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-dist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(dist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(dist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-nodist_includeHEADERS: $(nodist_include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedi=
r)/$$f'"; \
-	  $(nodist_includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"=
; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
+	@list=3D'$(nodist_include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
 install-nodist_rokenincludeHEADERS: $(nodist_rokeninclude_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(rokenincludedir)" || $(MKDIR_P) "$(DESTDIR)$(rokenincludedir)"
-	@list=3D'$(nodist_rokeninclude_HEADERS)'; for p in $$list; do \
+	@list=3D'$(nodist_rokeninclude_HEADERS)'; test -n "$(rokenincludedir)" ||=
 list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(nodist_rokenincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(roke=
nincludedir)/$$f'"; \
-	  $(nodist_rokenincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(rokeninclud=
edir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(rokenincludedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(rokenincludedir)" || exit $$?; \
 	done
=20
 uninstall-nodist_rokenincludeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(nodist_rokeninclude_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(rokenincludedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(rokenincludedir)/$$f"; \
-	done
+	@list=3D'$(nodist_rokeninclude_HEADERS)'; test -n "$(rokenincludedir)" ||=
 list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(rokenincludedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(rokenincludedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -1019,49 +1588,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -1072,15 +1655,32 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -1096,13 +1696,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -1142,6 +1746,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -1154,6 +1759,7 @@
 	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf $(DEPDIR) ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -1164,6 +1770,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -1173,26 +1781,35 @@
 	install-nodist_rokenincludeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-libLTLIBRARIES
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man3
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf $(DEPDIR) ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -1214,11 +1831,10 @@
 	uninstall-nodist_rokenincludeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man3
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: all check check-am install install-am install-data-am \
+	install-exec-am install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
 	check-local clean clean-checkPROGRAMS clean-generic \
@@ -1311,6 +1927,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1396,7 +2015,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1414,13 +2033,19 @@
 .hin.h:
 	cp $< $@
=20
-roken.h: make-roken$(EXEEXT)
-	@./make-roken$(EXEEXT) > tmp.h ;\
-	if [ -f roken.h ] && cmp -s tmp.h roken.h ; then rm -f tmp.h ; \
-	else rm -f roken.h; mv tmp.h roken.h; fi
+ at CROSS_COMPILE_FALSE@roken.h: make-roken$(EXEEXT)
+ at CROSS_COMPILE_FALSE@	@./make-roken$(EXEEXT) > tmp.h ;\
+ at CROSS_COMPILE_FALSE@	if [ -f roken.h ] && cmp -s tmp.h roken.h ; then rm =
-f tmp.h ; \
+ at CROSS_COMPILE_FALSE@	else rm -f roken.h; mv tmp.h roken.h; fi
=20
-make-roken.c: roken.h.in roken.awk
-	$(AWK) -f $(srcdir)/roken.awk $(srcdir)/roken.h.in > make-roken.c
+ at CROSS_COMPILE_FALSE@make-roken.c: roken.h.in roken.awk
+ at CROSS_COMPILE_FALSE@	$(AWK) -f $(srcdir)/roken.awk $(srcdir)/roken.h.in >=
 make-roken.c
+
+ at CROSS_COMPILE_TRUE@roken.h: $(top_srcdir)/cf/roken-h-process.pl roken.h.in
+ at CROSS_COMPILE_TRUE@	perl $(top_srcdir)/cf/roken-h-process.pl \
+ at CROSS_COMPILE_TRUE@	-c $(top_builddir)/include/config.h  \
+ at CROSS_COMPILE_TRUE@	-p $(srcdir)/roken.h.in -o roken.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/base64-t=
est.c
--- a/head/crypto/heimdal/lib/roken/base64-test.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/base64-test.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: base64-test.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include "roken.h"
 #include <base64.h>
@@ -63,7 +60,7 @@
 	int len;
 	len =3D base64_encode(t->data, t->len, &str);
 	if(strcmp(str, t->result) !=3D 0) {
-	    fprintf(stderr, "failed test %d: %s !=3D %s\n", numtest,=20
+	    fprintf(stderr, "failed test %d: %s !=3D %s\n", numtest,
 		    str, t->result);
 	    numerr++;
 	}
@@ -85,12 +82,12 @@
     {
 	char str[32];
 	if(base64_decode("M=3DM=3D", str) !=3D -1) {
-	    fprintf(stderr, "failed test %d: successful decode of `M=3DM=3D'\n",=20
+	    fprintf(stderr, "failed test %d: successful decode of `M=3DM=3D'\n",
 		    numtest++);
 	    numerr++;
 	}
 	if(base64_decode("MQ=3D=3D=3D", str) !=3D -1) {
-	    fprintf(stderr, "failed test %d: successful decode of `MQ=3D=3D=3D'\n=
",=20
+	    fprintf(stderr, "failed test %d: successful decode of `MQ=3D=3D=3D'\n=
",
 		    numtest++);
 	    numerr++;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/base64.c
--- a/head/crypto/heimdal/lib/roken/base64.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/base64.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995-2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
@@ -31,18 +31,17 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: base64.c 15506 2005-06-23 10:47:57Z lha $");
-#endif
+
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
 #include "base64.h"
=20
-static const char base64_chars[] =3D=20
+static const char base64_chars[] =3D
     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
=20
-static int=20
+static int
 pos(char c)
 {
     const char *p;
@@ -52,7 +51,7 @@
     return -1;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 base64_encode(const void *data, int size, char **str)
 {
     char *s, *p;
@@ -60,11 +59,18 @@
     int c;
     const unsigned char *q;
=20
+    if (size > INT_MAX/4 || size < 0) {
+	*str =3D NULL;
+	return -1;
+    }
+
     p =3D s =3D (char *) malloc(size * 4 / 3 + 4);
-    if (p =3D=3D NULL)
+    if (p =3D=3D NULL) {
+        *str =3D NULL;
 	return -1;
+    }
     q =3D (const unsigned char *) data;
-    i =3D 0;
+
     for (i =3D 0; i < size;) {
 	c =3D q[i++];
 	c *=3D 256;
@@ -87,7 +93,7 @@
     }
     *p =3D 0;
     *str =3D s;
-    return strlen(s);
+    return (int) strlen(s);
 }
=20
 #define DECODE_ERROR 0xffffffff
@@ -114,7 +120,7 @@
     return (marker << 24) | val;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 base64_decode(const char *str, void *data)
 {
     const char *p;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/base64.h
--- a/head/crypto/heimdal/lib/roken/base64.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/base64.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,23 +31,25 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: base64.h 15535 2005-06-30 07:13:33Z lha $ */
+/* $Id$ */
=20
 #ifndef _BASE64_H_
 #define _BASE64_H_
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 base64_encode(const void *, int, char **);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 base64_decode(const char *, void *);
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/bswap.c
--- a/head/crypto/heimdal/lib/roken/bswap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/bswap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,12 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
-RCSID("$Id: bswap.c 14773 2005-04-12 11:29:18Z lha $");
-
 #ifndef HAVE_BSWAP32
=20
-unsigned int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
 bswap32 (unsigned int val)
 {
     return (val & 0xff) << 24 |
@@ -52,7 +48,7 @@
=20
 #ifndef HAVE_BSWAP16
=20
-unsigned short ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION unsigned short ROKEN_LIB_CALL
 bswap16 (unsigned short val)
 {
     return (val & 0xff) << 8 |
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/chown.c
--- a/head/crypto/heimdal/lib/roken/chown.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/chown.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: chown.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 chown(const char *path, uid_t owner, gid_t group)
 {
   return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/closefro=
m.c
--- a/head/crypto/heimdal/lib/roken/closefrom.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/closefrom.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: closefrom.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
@@ -45,7 +42,7 @@
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 closefrom(int fd)
 {
     int num =3D getdtablesize();
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/concat.c
--- a/head/crypto/heimdal/lib/roken/concat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/concat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,13 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: concat.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
+
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 roken_concat (char *s, size_t len, ...)
 {
     int ret;
@@ -49,7 +47,7 @@
     return ret;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 roken_vconcat (char *s, size_t len, va_list args)
 {
     const char *a;
@@ -67,7 +65,7 @@
     return 0;
 }
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 roken_vmconcat (char **s, size_t max_len, va_list args)
 {
     const char *a;
@@ -80,7 +78,7 @@
     len =3D 1;
     while ((a =3D va_arg(args, const char*))) {
 	size_t n =3D strlen (a);
-=09
+
 	if(max_len && len + n > max_len){
 	    free(p);
 	    return 0;
@@ -99,10 +97,10 @@
     return len;
 }
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 roken_mconcat (char **s, size_t max_len, ...)
 {
-    int ret;
+    size_t ret;
     va_list args;
=20
     va_start(args, max_len);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/copyhost=
ent.c
--- a/head/crypto/heimdal/lib/roken/copyhostent.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/copyhostent.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: copyhostent.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -42,7 +39,7 @@
  * return a malloced copy of `h'
  */
=20
-struct hostent * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
 copyhostent (const struct hostent *h)
 {
     struct hostent *res;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/daemon.c
--- a/head/crypto/heimdal/lib/roken/daemon.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/daemon.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,11 +31,7 @@
 static char sccsid[] =3D "@(#)daemon.c	8.1 (Berkeley) 6/4/93";
 #endif /* LIBC_SCCS and not lint */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
-
-RCSID("$Id: daemon.c 14773 2005-04-12 11:29:18Z lha $");
=20
 #ifndef HAVE_DAEMON
=20
@@ -51,7 +47,7 @@
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 daemon(int nochdir, int noclose)
 {
     int fd;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/dumpdata=
.c
--- a/head/crypto/heimdal/lib/roken/dumpdata.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/dumpdata.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,12 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: dumpdata.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-
-#include <unistd.h>
=20
 #include "roken.h"
=20
@@ -44,7 +39,7 @@
  * Write datablob to a filename, don't care about errors.
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rk_dumpdata (const char *filename, const void *buf, size_t size)
 {
     int fd;
@@ -55,3 +50,45 @@
     net_write(fd, buf, size);
     close(fd);
 }
+
+/*
+ * Read all data from a filename, care about errors.
+ */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_undumpdata(const char *filename, void **buf, size_t *size)
+{
+    struct stat sb;
+    int fd, ret;
+    ssize_t sret;
+
+    *buf =3D NULL;
+
+    fd =3D open(filename, O_RDONLY, 0);
+    if (fd < 0)
+	return errno;
+    if (fstat(fd, &sb) !=3D 0){
+	ret =3D errno;
+	goto out;
+    }
+    *buf =3D malloc(sb.st_size);
+    if (*buf =3D=3D NULL) {
+	ret =3D ENOMEM;
+	goto out;
+    }
+    *size =3D sb.st_size;
+
+    sret =3D net_read(fd, *buf, *size);
+    if (sret < 0)
+	ret =3D errno;
+    else if (sret !=3D (ssize_t)*size) {
+	ret =3D EINVAL;
+	free(*buf);
+	*buf =3D NULL;
+    } else
+	ret =3D 0;
+
+ out:
+    close(fd);
+    return ret;
+}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/ecalloc.3
--- a/head/crypto/heimdal/lib/roken/ecalloc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/ecalloc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,34 @@
-.\" Copyright (c) 2001, 2003 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2001, 2003 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\" $Id: ecalloc.3 12527 2003-08-15 12:28:14Z joda $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\" $Id$
 .\"
 .Dd August 14, 2003
 .Dt ECALLOC 3
@@ -61,13 +61,13 @@
 .Ft ssize_t
 .Fn ewrite "int fd" "const void *buf" "size_t nbytes"
 .Sh DESCRIPTION
-These functions do the same as the ones without the=20
+These functions do the same as the ones without the
 .Dq e
-prefix, but if there is an error they will print a message with=20
+prefix, but if there is an error they will print a message with
 .Xr errx 3 ,
 and exit. For
 .Nm eread
-and=20
+and
 .Nm ewrite
 this is also true for partial data.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/ecalloc.c
--- a/head/crypto/heimdal/lib/roken/ecalloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/ecalloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: ecalloc.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdlib.h>
 #include <err.h>
@@ -45,7 +42,7 @@
  * Like calloc but never fails.
  */
=20
-void * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
 ecalloc (size_t number, size_t size)
 {
     void *tmp =3D calloc (number, size);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/emalloc.c
--- a/head/crypto/heimdal/lib/roken/emalloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/emalloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: emalloc.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdlib.h>
 #include <err.h>
@@ -45,7 +42,7 @@
  * Like malloc but never fails.
  */
=20
-void * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
 emalloc (size_t sz)
 {
     void *tmp =3D malloc (sz);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/environm=
ent.c
--- a/head/crypto/heimdal/lib/roken/environment.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/environment.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000, 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000, 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -32,10 +32,7 @@
  */
=20
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: environment.c 20866 2007-06-03 21:00:29Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <string.h>
@@ -43,7 +40,7 @@
 #include "roken.h"
=20
 /* find assignment in env list; len is length of variable including
- * equal=20
+ * equal
  */
=20
 static int
@@ -63,7 +60,7 @@
  */
=20
 static int
-rk_read_env_file(FILE *F, char ***env, int *assigned)
+read_env_file(FILE *F, char ***env, int *assigned)
 {
     int idx =3D 0;
     int i;
@@ -126,11 +123,11 @@
 }
=20
 /*
- * return count of environment assignments from file and=20
+ * return count of environment assignments from file and
  * list of malloced strings in `env'
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 read_environment(const char *file, char ***env)
 {
     int assigned;
@@ -139,12 +136,12 @@
     if ((F =3D fopen(file, "r")) =3D=3D NULL)
 	return 0;
=20
-    rk_read_env_file(F, env, &assigned);
+    read_env_file(F, env, &assigned);
     fclose(F);
     return assigned;
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 free_environment(char **env)
 {
     int i;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/eread.c
--- a/head/crypto/heimdal/lib/roken/eread.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/eread.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,13 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: eread.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-
-#include <unistd.h>
-#include <err.h>
=20
 #include "roken.h"
=20
@@ -45,7 +39,7 @@
  * Like read but never fails (and never returns partial data).
  */
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 eread (int fd, void *buf, size_t nbytes)
 {
     ssize_t ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/erealloc=
.c
--- a/head/crypto/heimdal/lib/roken/erealloc.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/erealloc.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: erealloc.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdlib.h>
 #include <err.h>
@@ -45,7 +42,7 @@
  * Like realloc but never fails.
  */
=20
-void * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
 erealloc (void *ptr, size_t sz)
 {
     void *tmp =3D realloc (ptr, sz);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/err.c
--- a/head/crypto/heimdal/lib/roken/err.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/err.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: err.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "err.h"
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 err(int eval, const char *fmt, ...)
 {
   va_list ap;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/err.hin
--- a/head/crypto/heimdal/lib/roken/err.hin	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/err.hin	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995 - 2004 Kungliga Tekniska H=F6gskolan=20
+ * Copyright (c) 1995 - 2004 Kungliga Tekniska H=C3=B6gskolan=20
  * (Royal Institute of Technology, Stockholm, Sweden). =20
  * All rights reserved.
  *=20
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: err.hin 14773 2005-04-12 11:29:18Z lha $ */
+/* $Id$ */
=20
 #ifndef __ERR_H__
 #define __ERR_H__
@@ -48,40 +48,42 @@
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 verr(int eval, const char *fmt, va_list ap)
      __attribute__ ((noreturn, format (printf, 2, 0)));
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 err(int eval, const char *fmt, ...)
      __attribute__ ((noreturn, format (printf, 2, 3)));
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 verrx(int eval, const char *fmt, va_list ap)
      __attribute__ ((noreturn, format (printf, 2, 0)));
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 errx(int eval, const char *fmt, ...)
      __attribute__ ((noreturn, format (printf, 2, 3)));
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 vwarn(const char *fmt, va_list ap)
      __attribute__ ((format (printf, 1, 0)));
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 warn(const char *fmt, ...)
      __attribute__ ((format (printf, 1, 2)));
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 vwarnx(const char *fmt, va_list ap)
      __attribute__ ((format (printf, 1, 0)));
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 warnx(const char *fmt, ...)
      __attribute__ ((format (printf, 1, 2)));
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/errx.c
--- a/head/crypto/heimdal/lib/roken/errx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/errx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: errx.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "err.h"
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 errx(int eval, const char *fmt, ...)
 {
   va_list ap;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/esetenv.c
--- a/head/crypto/heimdal/lib/roken/esetenv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/esetenv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000, 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000, 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,13 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: esetenv.c 15502 2005-06-21 18:56:15Z lha $");
-#endif
=20
 #include "roken.h"
=20
 #include <err.h>
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 esetenv(const char *var, const char *val, int rewrite)
 {
     if (setenv (rk_UNCONST(var), rk_UNCONST(val), rewrite))
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/estrdup.c
--- a/head/crypto/heimdal/lib/roken/estrdup.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/estrdup.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: estrdup.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdlib.h>
 #include <err.h>
@@ -45,7 +42,7 @@
  * Like strdup but never fails.
  */
=20
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 estrdup (const char *str)
 {
     char *tmp =3D strdup (str);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/ewrite.c
--- a/head/crypto/heimdal/lib/roken/ewrite.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/ewrite.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,13 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: ewrite.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-
-#include <unistd.h>
-#include <err.h>
=20
 #include "roken.h"
=20
@@ -45,7 +39,7 @@
  * Like write but never fails (and never returns partial data).
  */
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 ewrite (int fd, const void *buf, size_t nbytes)
 {
     ssize_t ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/fchown.c
--- a/head/crypto/heimdal/lib/roken/fchown.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/fchown.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: fchown.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 fchown(int fd, uid_t owner, gid_t group)
 {
   return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/flock.c
--- a/head/crypto/heimdal/lib/roken/flock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/flock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,25 +31,22 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #ifndef HAVE_FLOCK
-RCSID("$Id: flock.c 14773 2005-04-12 11:29:18Z lha $");
=20
 #include "roken.h"
=20
-
 #define OP_MASK (LOCK_SH | LOCK_EX | LOCK_UN)
=20
-int ROKEN_LIB_FUNCTION
-flock(int fd, int operation)
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_flock(int fd, int operation)
 {
 #if defined(HAVE_FCNTL) && defined(F_SETLK)
   struct flock arg;
   int code, cmd;
- =20
+
   arg.l_whence =3D SEEK_SET;
   arg.l_start =3D 0;
   arg.l_len =3D 0;		/* means to EOF */
@@ -78,6 +75,76 @@
     break;
   }
   return code;
+
+#elif defined(_WIN32)
+  /* Windows */
+
+#define FLOCK_OFFSET_LOW  0
+#define FLOCK_OFFSET_HIGH 0
+#define FLOCK_LENGTH_LOW  0x00000000
+#define FLOCK_LENGTH_HIGH 0x80000000
+
+  HANDLE hFile;
+  OVERLAPPED ov;
+  BOOL rv =3D FALSE;
+  DWORD f =3D 0;
+
+  hFile =3D (HANDLE) _get_osfhandle(fd);
+  if (hFile =3D=3D NULL || hFile =3D=3D INVALID_HANDLE_VALUE) {
+      _set_errno(EBADF);
+      return -1;
+  }
+
+  ZeroMemory(&ov, sizeof(ov));
+  ov.hEvent =3D NULL;
+  ov.Offset =3D FLOCK_OFFSET_LOW;
+  ov.OffsetHigh =3D FLOCK_OFFSET_HIGH;
+
+  if (operation & LOCK_NB)
+      f =3D LOCKFILE_FAIL_IMMEDIATELY;
+
+  switch (operation & OP_MASK) {
+  case LOCK_UN:			/* Unlock */
+      rv =3D UnlockFileEx(hFile, 0,
+			FLOCK_LENGTH_LOW, FLOCK_LENGTH_HIGH, &ov);
+      break;
+
+  case LOCK_SH:			/* Shared lock */
+      rv =3D LockFileEx(hFile, f, 0,
+		      FLOCK_LENGTH_LOW, FLOCK_LENGTH_HIGH, &ov);
+      break;
+
+  case LOCK_EX:			/* Exclusive lock */
+      rv =3D LockFileEx(hFile, f|LOCKFILE_EXCLUSIVE_LOCK, 0,
+		      FLOCK_LENGTH_LOW, FLOCK_LENGTH_HIGH,
+		      &ov);
+      break;
+
+  default:
+      _set_errno(EINVAL);
+      return -1;
+  }
+
+  if (!rv) {
+      switch (GetLastError()) {
+      case ERROR_SHARING_VIOLATION:
+      case ERROR_LOCK_VIOLATION:
+      case ERROR_IO_PENDING:
+	  _set_errno(EWOULDBLOCK);
+	  break;
+
+      case ERROR_ACCESS_DENIED:
+	  _set_errno(EACCES);
+	  break;
+
+      default:
+	  _set_errno(ENOLCK);
+      }
+      return -1;
+  }
+
+  return 0;
+
 #else
   return -1;
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/fnmatch.c
--- a/head/crypto/heimdal/lib/roken/fnmatch.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/fnmatch.c	Tue Apr 17 11:51:51 2012 +0300
@@ -45,6 +45,12 @@
  * Compares a filename or pathname to a pattern.
  */
=20
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <roken.h>
+
 #include <fnmatch.h>
 #include <string.h>
=20
@@ -52,7 +58,7 @@
=20
 static const char *rangematch (const char *, int, int);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rk_fnmatch(const char *pattern, const char *string, int flags)
 {
 	const char *stringstart;
@@ -147,13 +153,13 @@
 	 */
 	if (negate =3D (*pattern =3D=3D '!' || *pattern =3D=3D '^'))
 		++pattern;
-=09
+
 	for (ok =3D 0; (c =3D *pattern++) !=3D ']';) {
 		if (c =3D=3D '\\' && !(flags & FNM_NOESCAPE))
 			c =3D *pattern++;
 		if (c =3D=3D EOS)
 			return (NULL);
-		if (*pattern =3D=3D '-'=20
+		if (*pattern =3D=3D '-'
 		    && (c2 =3D *(pattern+1)) !=3D EOS && c2 !=3D ']') {
 			pattern +=3D 2;
 			if (c2 =3D=3D '\\' && !(flags & FNM_NOESCAPE))
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/fnmatch.=
hin
--- a/head/crypto/heimdal/lib/roken/fnmatch.hin	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/fnmatch.hin	Tue Apr 17 11:51:51 2012 +0=
300
@@ -36,9 +36,11 @@
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL __stdcall
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/freeaddr=
info.c
--- a/head/crypto/heimdal/lib/roken/freeaddrinfo.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/roken/freeaddrinfo.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: freeaddrinfo.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -42,7 +39,7 @@
  * free the list of `struct addrinfo' starting at `ai'
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 freeaddrinfo(struct addrinfo *ai)
 {
     struct addrinfo *tofree;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/freehost=
ent.c
--- a/head/crypto/heimdal/lib/roken/freehostent.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/freehostent.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: freehostent.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -42,7 +39,7 @@
  * free a malloced hostent
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 freehostent (struct hostent *h)
 {
     char **p;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/gai_stre=
rror.c
--- a/head/crypto/heimdal/lib/roken/gai_strerror.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/roken/gai_strerror.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: gai_strerror.c 15837 2005-08-05 09:31:35Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -65,7 +62,7 @@
  *
  */
=20
-const char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 gai_strerror(int ecode)
 {
     struct gai_error *g;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/get_defa=
ult_username.c
--- a/head/crypto/heimdal/lib/roken/get_default_username.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/get_default_username.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1997 - 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: get_default_username.c 14773 2005-04-12 11:29:18Z lha $");
-#endif /* HAVE_CONFIG_H */
=20
 #include "roken.h"
=20
@@ -43,7 +40,7 @@
  * NULL if we can't guess at all.
  */
=20
-const char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 get_default_username (void)
 {
     const char *user;
@@ -76,5 +73,11 @@
 	    return pwd->pw_name;
     }
 #endif
+#ifdef _WIN32
+    /* TODO: We can call GetUserNameEx() and figure out a
+       username. However, callers do not free the return value of this
+       function. */
+#endif
+
     return user;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/get_wind=
ow_size.c
--- a/head/crypto/heimdal/lib/roken/get_window_size.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/roken/get_window_size.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: get_window_size.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdlib.h>
 #ifdef HAVE_UNISTD_H
@@ -60,43 +57,76 @@
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
-get_window_size(int fd, struct winsize *wp)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+get_window_size(int fd, int *lines, int *columns)
 {
-    int ret =3D -1;
-   =20
-    memset(wp, 0, sizeof(*wp));
+    char *s;
=20
 #if defined(TIOCGWINSZ)
-    ret =3D ioctl(fd, TIOCGWINSZ, wp);
+    {
+	struct winsize ws;
+        int ret;
+	ret =3D ioctl(fd, TIOCGWINSZ, &ws);
+	if (ret !=3D -1) {
+	    if (lines)
+		*lines =3D ws.ws_row;
+	    if (columns)
+		*columns =3D ws.ws_col;
+	    return 0;
+	}
+    }
 #elif defined(TIOCGSIZE)
     {
 	struct ttysize ts;
-=09
+        int ret;
 	ret =3D ioctl(fd, TIOCGSIZE, &ts);
-	if(ret =3D=3D 0) {
-	    wp->ws_row =3D ts.ts_lines;
-	    wp->ws_col =3D ts.ts_cols;
-	}
+	if (ret !=3D -1) {
+	    if (lines)
+		*lines =3D ts.ws_lines;
+	    if (columns)
+		*columns =3D ts.ts_cols;
+	    return 0;
+ 	}
     }
 #elif defined(HAVE__SCRSIZE)
     {
 	int dst[2];
-=09
-	_scrsize(dst);
-	wp->ws_row =3D dst[1];
-	wp->ws_col =3D dst[0];
-	ret =3D 0;
+
+ 	_scrsize(dst);
+	if (lines)
+	    *lines =3D dst[1];
+	if (columns)
+	    *columns =3D dst[0];
+	return 0;
+    }
+#elif defined(_WIN32)
+    {
+        intptr_t fh =3D 0;
+        CONSOLE_SCREEN_BUFFER_INFO sb_info;
+
+        fh =3D _get_osfhandle(fd);
+        if (fh !=3D (intptr_t) INVALID_HANDLE_VALUE &&
+            GetConsoleScreenBufferInfo((HANDLE) fh, &sb_info)) {
+            if (lines)
+                *lines =3D 1 + sb_info.srWindow.Bottom - sb_info.srWindow.=
Top;
+            if (columns)
+                *columns =3D 1 + sb_info.srWindow.Right - sb_info.srWindow=
.Left;
+
+            return 0;
+        }
     }
 #endif
-    if (ret !=3D 0) {
-        char *s;
-        if((s =3D getenv("COLUMNS")))
-	    wp->ws_col =3D atoi(s);
-	if((s =3D getenv("LINES")))
-	    wp->ws_row =3D atoi(s);
-	if(wp->ws_col > 0 && wp->ws_row > 0)
-	    ret =3D 0;
+    if (columns) {
+    	if ((s =3D getenv("COLUMNS")))
+	    *columns =3D atoi(s);
+	else
+	    return -1;
     }
-    return ret;
+    if (lines) {
+	if ((s =3D getenv("LINES")))
+	    *lines =3D atoi(s);
+	else
+	    return -1;
+    }
+    return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getaddri=
nfo-test.c
--- a/head/crypto/heimdal/lib/roken/getaddrinfo-test.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getaddrinfo-test.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getaddrinfo-test.c 15930 2005-08-12 13:42:17Z lha $");
-#endif
=20
 #include "roken.h"
 #include "getarg.h"
@@ -43,10 +40,12 @@
 static int family;
 static int socktype;
=20
+static int verbose_counter;
 static int version_flag;
 static int help_flag;
=20
 static struct getargs args[] =3D {
+    {"verbose",	0,	arg_counter,	&verbose_counter,"verbose",	NULL},
     {"flags",	0,	arg_integer,	&flags,		"flags",	NULL},
     {"family",	0,	arg_integer,	&family,	"family",	NULL},
     {"socktype",0,	arg_integer,	&socktype,	"socktype",	NULL},
@@ -71,7 +70,8 @@
     struct addrinfo *res, *r;
     int ret;
=20
-    printf ("(%s,%s)... ", nodename ? nodename : "null", servname);
+    if (verbose_counter)
+	printf ("(%s,%s)... ", nodename ? nodename : "null", servname);
=20
     memset (&hints, 0, sizeof(hints));
     hints.ai_flags    =3D flags;
@@ -79,29 +79,32 @@
     hints.ai_socktype =3D socktype;
=20
     ret =3D getaddrinfo (nodename, servname, &hints, &res);
-    if (ret) {
-	printf ("error: %s\n", gai_strerror(ret));
-	return;
-    }
-    printf ("\n");
+    if (ret)
+	errx(1, "error: %s\n", gai_strerror(ret));
+
+    if (verbose_counter)
+	printf ("\n");
=20
     for (r =3D res; r !=3D NULL; r =3D r->ai_next) {
 	char addrstr[256];
=20
-	if (inet_ntop (r->ai_family,=20
+	if (inet_ntop (r->ai_family,
 		       socket_get_address (r->ai_addr),
 		       addrstr, sizeof(addrstr)) =3D=3D NULL) {
-	    printf ("\tbad address?\n");
+	    if (verbose_counter)
+		printf ("\tbad address?\n");
 	    continue;
-	}=20
-	printf ("\tfamily =3D %d, socktype =3D %d, protocol =3D %d, "
-		"address =3D \"%s\", port =3D %d",
-		r->ai_family, r->ai_socktype, r->ai_protocol,
-		addrstr,
-		ntohs(socket_get_port (r->ai_addr)));
-	if (r->ai_canonname)
-	    printf (", canonname =3D \"%s\"", r->ai_canonname);
-	printf ("\n");
+	}
+	if (verbose_counter) {
+	    printf ("\tfamily =3D %d, socktype =3D %d, protocol =3D %d, "
+		    "address =3D \"%s\", port =3D %d",
+		    r->ai_family, r->ai_socktype, r->ai_protocol,
+		    addrstr,
+		    ntohs(socket_get_port (r->ai_addr)));
+	    if (r->ai_canonname)
+		printf (", canonname =3D \"%s\"", r->ai_canonname);
+	    printf ("\n");
+	}
     }
     freeaddrinfo (res);
 }
@@ -122,7 +125,7 @@
 	usage (0);
=20
     if (version_flag) {
-	fprintf (stderr, "%s from %s-%s)\n", getprogname(), PACKAGE, VERSION);
+	fprintf (stderr, "%s from %s-%s\n", getprogname(), PACKAGE, VERSION);
 	return 0;
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getaddri=
nfo.c
--- a/head/crypto/heimdal/lib/roken/getaddrinfo.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/getaddrinfo.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getaddrinfo.c 15417 2005-06-16 17:49:29Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -368,7 +365,7 @@
  * };
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getaddrinfo(const char *nodename,
 	    const char *servname,
 	    const struct addrinfo *hints,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getaddri=
nfo_hostspec.c
--- a/head/crypto/heimdal/lib/roken/getaddrinfo_hostspec.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getaddrinfo_hostspec.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getaddrinfo_hostspec.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
 /* getaddrinfo via string specifying host and port */
=20
-int ROKEN_LIB_FUNCTION
-roken_getaddrinfo_hostspec2(const char *hostspec,=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_getaddrinfo_hostspec2(const char *hostspec,
 			    int socktype,
 			    int port,
 			    struct addrinfo **ai)
@@ -60,15 +57,15 @@
     } *hstp, hst[] =3D {
 	{ "http://", SOCK_STREAM, IPPROTO_TCP, 80 },
 	{ "http/", SOCK_STREAM, IPPROTO_TCP, 80 },
-	{ "tcp/", SOCK_STREAM, IPPROTO_TCP },
-	{ "udp/", SOCK_DGRAM, IPPROTO_UDP },
-	{ NULL }
+	{ "tcp/", SOCK_STREAM, IPPROTO_TCP, 0 },
+	{ "udp/", SOCK_DGRAM, IPPROTO_UDP, 0 },
+	{ NULL, 0, 0, 0 }
     };
=20
     memset(&hints, 0, sizeof(hints));
=20
     hints.ai_socktype =3D socktype;
-=09
+
     for(hstp =3D hst; hstp->prefix; hstp++) {
 	if(strncmp(hostspec, hstp->prefix, strlen(hstp->prefix)) =3D=3D 0) {
 	    hints.ai_socktype =3D hstp->socktype;
@@ -79,7 +76,7 @@
 	    break;
 	}
     }
-   =20
+
     p =3D strchr (hostspec, ':');
     if (p !=3D NULL) {
 	char *end;
@@ -90,13 +87,13 @@
 	hostspec_len =3D strlen(hostspec);
     }
     snprintf (portstr, sizeof(portstr), "%u", port);
-   =20
+
     snprintf (host, sizeof(host), "%.*s", hostspec_len, hostspec);
     return getaddrinfo (host, portstr, &hints, ai);
 }
=20
-int ROKEN_LIB_FUNCTION
-roken_getaddrinfo_hostspec(const char *hostspec,=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+roken_getaddrinfo_hostspec(const char *hostspec,
 			   int port,
 			   struct addrinfo **ai)
 {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getarg.3
--- a/head/crypto/heimdal/lib/roken/getarg.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getarg.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,35 @@
-.\" Copyright (c) 1999 - 2002 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 1999 - 2002 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: getarg.3 13380 2004-02-17 12:04:59Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $Id$
 .Dd September 24, 1999
 .Dt GETARG 3
 .Os ROKEN
@@ -246,20 +246,20 @@
 .Pp
 Long option names are prefixed with -- (double dash), and the value
 with a =3D (equal),
-.Fl -foo=3D Ns Ar bar .
+.Fl Fl foo=3D Ns Ar bar .
 Long option flags can either be specified as they are
-.Pf ( Fl -help ) ,
+.Pf ( Fl Fl help ) ,
 or with an (boolean parsable) option
-.Pf ( Fl -help=3D Ns Ar yes ,
-.Fl -help=3D Ns Ar true ,
+.Pf ( Fl Fl help=3D Ns Ar yes ,
+.Fl Fl help=3D Ns Ar true ,
 or similar), or they can also be negated
-.Pf ( Fl -no-help
+.Pf ( Fl Fl no-help
 is the same as
-.Fl -help=3D Ns no ) ,
+.Fl Fl help=3D Ns no ) ,
 and if you're really confused you can do it multiple times
-.Pf ( Fl -no-no-help=3D Ns Ar false ,
+.Pf ( Fl Fl no-no-help=3D Ns Ar false ,
 or even
-.Fl -no-no-help=3D Ns Ar maybe ) .
+.Fl Fl no-no-help=3D Ns Ar maybe ) .
 .Sh EXAMPLE
 .Bd -literal
 #include <stdio.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getarg.c
--- a/head/crypto/heimdal/lib/roken/getarg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getarg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getarg.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -45,7 +42,12 @@
 #define ISFLAG(X) ((X).type =3D=3D arg_flag || (X).type =3D=3D arg_negativ=
e_flag)
=20
 static size_t
-print_arg (char *string, size_t len, int mdoc, int longp, struct getargs *=
arg)
+print_arg (char *string,
+	   size_t len,
+	   int mdoc,
+	   int longp,
+	   struct getargs *arg,
+	   char *(i18n)(const char *))
 {
     const char *s;
=20
@@ -66,7 +68,7 @@
     }
=20
     if (arg->arg_help)
-	s =3D arg->arg_help;
+	s =3D (*i18n)(arg->arg_help);
     else if (arg->type =3D=3D arg_integer || arg->type =3D=3D arg_counter)
 	s =3D "integer";
     else if (arg->type =3D=3D arg_string)
@@ -86,9 +88,10 @@
 mandoc_template(struct getargs *args,
 		size_t num_args,
 		const char *progname,
-		const char *extra_string)
+		const char *extra_string,
+		char *(i18n)(const char *))
 {
-    int i;
+    size_t i;
     char timestr[64], cmd[64];
     char buf[128];
     const char *p;
@@ -106,40 +109,39 @@
     if(p) p++; else p =3D progname;
     strlcpy(cmd, p, sizeof(cmd));
     strupr(cmd);
-      =20
+
     printf(".Dt %s SECTION\n", cmd);
     printf(".Os OPERATING_SYSTEM\n");
     printf(".Sh NAME\n");
     printf(".Nm %s\n", p);
-    printf(".Nd\n");
-    printf("in search of a description\n");
+    printf(".Nd in search of a description\n");
     printf(".Sh SYNOPSIS\n");
     printf(".Nm\n");
     for(i =3D 0; i < num_args; i++){
 	/* we seem to hit a limit on number of arguments if doing
            short and long flags with arguments -- split on two lines */
-	if(ISFLAG(args[i]) ||=20
+	if(ISFLAG(args[i]) ||
 	   args[i].short_name =3D=3D 0 || args[i].long_name =3D=3D NULL) {
 	    printf(".Op ");
=20
 	    if(args[i].short_name) {
-		print_arg(buf, sizeof(buf), 1, 0, args + i);
+		print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
 		printf("Fl %c%s", args[i].short_name, buf);
 		if(args[i].long_name)
 		    printf(" | ");
 	    }
 	    if(args[i].long_name) {
-		print_arg(buf, sizeof(buf), 1, 1, args + i);
-		printf("Fl -%s%s%s",
+		print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
+		printf("Fl Fl %s%s%s",
 		       args[i].type =3D=3D arg_negative_flag ? "no-" : "",
 		       args[i].long_name, buf);
 	    }
 	    printf("\n");
 	} else {
-	    print_arg(buf, sizeof(buf), 1, 0, args + i);
+	    print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
 	    printf(".Oo Fl %c%s \\*(Ba Xo\n", args[i].short_name, buf);
-	    print_arg(buf, sizeof(buf), 1, 1, args + i);
-	    printf(".Fl -%s%s\n.Xc\n.Oc\n", args[i].long_name, buf);
+	    print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
+	    printf(".Fl Fl %s%s\n.Xc\n.Oc\n", args[i].long_name, buf);
 	}
     /*
 	    if(args[i].type =3D=3D arg_strings)
@@ -155,17 +157,17 @@
 	printf(".It Xo\n");
 	if(args[i].short_name){
 	    printf(".Fl %c", args[i].short_name);
-	    print_arg(buf, sizeof(buf), 1, 0, args + i);
+	    print_arg(buf, sizeof(buf), 1, 0, args + i, i18n);
 	    printf("%s", buf);
 	    if(args[i].long_name)
 		printf(" ,");
 	    printf("\n");
 	}
 	if(args[i].long_name){
-	    printf(".Fl -%s%s",
+	    printf(".Fl Fl %s%s",
 		   args[i].type =3D=3D arg_negative_flag ? "no-" : "",
 		   args[i].long_name);
-	    print_arg(buf, sizeof(buf), 1, 1, args + i);
+	    print_arg(buf, sizeof(buf), 1, 1, args + i, i18n);
 	    printf("%s\n", buf);
 	}
 	printf(".Xc\n");
@@ -198,31 +200,48 @@
     return col;
 }
=20
-void ROKEN_LIB_FUNCTION
+static char *
+builtin_i18n(const char *str)
+{
+    return rk_UNCONST(str);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 arg_printusage (struct getargs *args,
 		size_t num_args,
 		const char *progname,
 		const char *extra_string)
 {
-    int i;
-    size_t max_len =3D 0;
+    arg_printusage_i18n(args, num_args, "Usage",
+			progname, extra_string, builtin_i18n);
+}
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+arg_printusage_i18n (struct getargs *args,
+		     size_t num_args,
+		     const char *usage,
+		     const char *progname,
+		     const char *extra_string,
+		     char *(*i18n)(const char *))
+{
+    size_t i, max_len =3D 0;
     char buf[128];
     int col =3D 0, columns;
-    struct winsize ws;
=20
     if (progname =3D=3D NULL)
 	progname =3D getprogname();
=20
+    if (i18n =3D=3D NULL)
+	i18n =3D builtin_i18n;
+
     if(getenv("GETARGMANDOC")){
-	mandoc_template(args, num_args, progname, extra_string);
+	mandoc_template(args, num_args, progname, extra_string, i18n);
 	return;
     }
-    if(get_window_size(2, &ws) =3D=3D 0)
-	columns =3D ws.ws_col;
-    else
+    if(get_window_size(2, NULL, &columns) =3D=3D -1)
 	columns =3D 80;
     col =3D 0;
-    col +=3D fprintf (stderr, "Usage: %s", progname);
+    col +=3D fprintf (stderr, "%s: %s", usage, progname);
     buf[0] =3D '\0';
     for (i =3D 0; i < num_args; ++i) {
 	if(args[i].short_name && ISFLAG(args[i])) {
@@ -253,8 +272,8 @@
 	    }
 	    strlcat(buf, args[i].long_name, sizeof(buf));
 	    len +=3D strlen(args[i].long_name);
-	    len +=3D print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),=20
-			     0, 1, &args[i]);
+	    len +=3D print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
+			     0, 1, &args[i], i18n);
 	    strlcat(buf, "]", sizeof(buf));
 	    if(args[i].type =3D=3D arg_strings)
 		strlcat(buf, "...", sizeof(buf));
@@ -264,8 +283,8 @@
 	if (args[i].short_name && !ISFLAG(args[i])) {
 	    snprintf(buf, sizeof(buf), "[-%c", args[i].short_name);
 	    len +=3D 2;
-	    len +=3D print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),=20
-			     0, 0, &args[i]);
+	    len +=3D print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
+			     0, 0, &args[i], i18n);
 	    strlcat(buf, "]", sizeof(buf));
 	    if(args[i].type =3D=3D arg_strings)
 		strlcat(buf, "...", sizeof(buf));
@@ -277,7 +296,7 @@
 	max_len =3D max(max_len, len);
     }
     if (extra_string) {
-	col =3D check_column(stderr, col, strlen(extra_string) + 1, columns);
+	check_column(stderr, col, strlen(extra_string) + 1, columns);
 	fprintf (stderr, " %s\n", extra_string);
     } else
 	fprintf (stderr, "\n");
@@ -287,7 +306,7 @@
=20
 	    if (args[i].short_name) {
 		count +=3D fprintf (stderr, "-%c", args[i].short_name);
-		print_arg (buf, sizeof(buf), 0, 0, &args[i]);
+		print_arg (buf, sizeof(buf), 0, 0, &args[i], i18n);
 		count +=3D fprintf(stderr, "%s", buf);
 	    }
 	    if (args[i].short_name && args[i].long_name)
@@ -297,12 +316,12 @@
 		if (args[i].type =3D=3D arg_negative_flag)
 		    count +=3D fprintf (stderr, "no-");
 		count +=3D fprintf (stderr, "%s", args[i].long_name);
-		print_arg (buf, sizeof(buf), 0, 1, &args[i]);
+		print_arg (buf, sizeof(buf), 0, 1, &args[i], i18n);
 		count +=3D fprintf(stderr, "%s", buf);
 	    }
 	    while(count++ <=3D max_len)
 		putc (' ', stderr);
-	    fprintf (stderr, "%s\n", args[i].help);
+	    fprintf (stderr, "%s\n", (*i18n)(args[i].help));
 	}
     }
 }
@@ -329,7 +348,7 @@
 arg_match_long(struct getargs *args, size_t num_args,
 	       char *argv, int argc, char **rargv, int *goptind)
 {
-    int i;
+    size_t i;
     char *goptarg =3D NULL;
     int negate =3D 0;
     int partial_match =3D 0;
@@ -378,7 +397,7 @@
 	else
 	    return ARG_ERR_NO_MATCH;
     }
-   =20
+
     if(*goptarg =3D=3D '\0'
        && !ISFLAG(*current)
        && current->type !=3D arg_collect
@@ -407,16 +426,12 @@
     {
 	int *flag =3D current->value;
 	if(*goptarg =3D=3D '\0' ||
-	   strcmp(goptarg + 1, "yes") =3D=3D 0 ||=20
+	   strcmp(goptarg + 1, "yes") =3D=3D 0 ||
 	   strcmp(goptarg + 1, "true") =3D=3D 0){
 	    *flag =3D !negate;
 	    return 0;
 	} else if (*goptarg && strcmp(goptarg + 1, "maybe") =3D=3D 0) {
-#ifdef HAVE_RANDOM
-	    *flag =3D random() & 1;
-#else
-	    *flag =3D rand() & 1;
-#endif
+	    *flag =3D rk_random() & 1;
 	} else {
 	    *flag =3D negate;
 	    return 0;
@@ -450,6 +465,7 @@
=20
     default:
 	abort ();
+	UNREACHABLE(return 0);
     }
 }
=20
@@ -457,7 +473,7 @@
 arg_match_short (struct getargs *args, size_t num_args,
 		 char *argv, int argc, char **rargv, int *goptind)
 {
-    int j, k;
+    size_t j, k;
=20
     for(j =3D 1; j > 0 && j < strlen(rargv[*goptind]); j++) {
 	for(k =3D 0; k < num_args; k++) {
@@ -473,16 +489,18 @@
 		if(args[k].type =3D=3D arg_negative_flag) {
 		    *(int*)args[k].value =3D 0;
 		    break;
-		}=20
+		}
 		if(args[k].type =3D=3D arg_counter) {
 		    ++*(int *)args[k].value;
 		    break;
 		}
 		if(args[k].type =3D=3D arg_collect) {
 		    struct getarg_collect_info *c =3D args[k].value;
+		    int a =3D (int)j;
=20
-		    if((*c->func)(TRUE, argc, rargv, goptind, &j, c->data))
+		    if((*c->func)(TRUE, argc, rargv, goptind, &a, c->data))
 			return ARG_ERR_BAD_ARG;
+		    j =3D a;
 		    break;
 		}
=20
@@ -523,20 +541,14 @@
     return 0;
 }
=20
-int ROKEN_LIB_FUNCTION
-getarg(struct getargs *args, size_t num_args,=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getarg(struct getargs *args, size_t num_args,
        int argc, char **argv, int *goptind)
 {
     int i;
     int ret =3D 0;
=20
-#if defined(HAVE_SRANDOMDEV)
-    srandomdev();
-#elif defined(HAVE_RANDOM)
-    srandom(time(NULL));
-#else
-    srand (time(NULL));
-#endif
+    rk_random_init();
     (*goptind)++;
     for(i =3D *goptind; i < argc; i++) {
 	if(argv[i][0] !=3D '-')
@@ -546,7 +558,7 @@
 		i++;
 		break;
 	    }
-	    ret =3D arg_match_long (args, num_args, argv[i] + 2,=20
+	    ret =3D arg_match_long (args, num_args, argv[i] + 2,
 				  argc, argv, &i);
 	} else {
 	    ret =3D arg_match_short (args, num_args, argv[i],
@@ -559,7 +571,7 @@
     return ret;
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 free_getarg_strings (getarg_strings *s)
 {
     free (s->strings);
@@ -585,9 +597,9 @@
     int goptind =3D 0;
     while(getarg(args, 5, argc, argv, &goptind))
 	printf("Bad arg: %s\n", argv[goptind]);
-    printf("flag1 =3D %d\n", flag1); =20
-    printf("flag2 =3D %d\n", flag2); =20
-    printf("foo_flag =3D %d\n", foo_flag); =20
+    printf("flag1 =3D %d\n", flag1);
+    printf("flag2 =3D %d\n", flag2);
+    printf("foo_flag =3D %d\n", foo_flag);
     printf("bar_int =3D %d\n", bar_int);
     printf("baz_flag =3D %s\n", baz_string);
     arg_printusage (args, 5, argv[0], "nothing here");
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getarg.h
--- a/head/crypto/heimdal/lib/roken/getarg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getarg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: getarg.h 14776 2005-04-13 05:52:27Z lha $ */
+/* $Id$ */
=20
 #ifndef __GETARG_H__
 #define __GETARG_H__
@@ -40,19 +40,21 @@
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
 struct getargs{
     const char *long_name;
     char short_name;
-    enum { arg_integer,=20
-	   arg_string,=20
-	   arg_flag,=20
-	   arg_negative_flag,=20
+    enum { arg_integer,
+	   arg_string,
+	   arg_flag,
+	   arg_negative_flag,
 	   arg_strings,
 	   arg_double,
 	   arg_collect,
@@ -86,17 +88,25 @@
     void *data;
 } getarg_collect_info;
=20
-int ROKEN_LIB_FUNCTION
-getarg(struct getargs *args, size_t num_args,=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getarg(struct getargs *args, size_t num_args,
        int argc, char **argv, int *goptind);
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 arg_printusage (struct getargs *args,
 		size_t num_args,
 		const char *progname,
 		const char *extra_string);
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+arg_printusage_i18n (struct getargs *args,
+		     size_t num_args,
+		     const char *usage,
+		     const char *progname,
+		     const char *extra_string,
+		     char *(*i18n)(const char *));
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 free_getarg_strings (getarg_strings *);
=20
 #endif /* __GETARG_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getcap.c
--- a/head/crypto/heimdal/lib/roken/getcap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getcap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,11 +32,9 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #include "roken.h"
-RCSID("$Id: getcap.c 22071 2007-11-14 20:04:50Z lha $");
=20
 #include <sys/types.h>
 #include <ctype.h>
@@ -45,7 +43,7 @@
 #elif defined(HAVE_DB_H)
 #include <db.h>
 #endif
-#include <errno.h>=09
+#include <errno.h>
 #include <fcntl.h>
 #include <limits.h>
 #include <stdio.h>
@@ -85,24 +83,24 @@
 static int	nfcmp (char *, char *);
=20
=20
-int ROKEN_LIB_FUNCTION cgetset(const char *ent);
-char *ROKEN_LIB_FUNCTION cgetcap(char *buf, const char *cap, int type);
-int ROKEN_LIB_FUNCTION cgetent(char **buf, char **db_array, const char *na=
me);
-int ROKEN_LIB_FUNCTION cgetmatch(const char *buf, const char *name);
-int ROKEN_LIB_FUNCTION cgetclose(void);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetset(const char *ent);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL cgetcap(char *buf, const char *ca=
p, int type);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetent(char **buf, char **db_array,=
 const char *name);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetmatch(const char *buf, const cha=
r *name);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetclose(void);
 #if 0
 int cgetfirst(char **buf, char **db_array);
 int cgetnext(char **bp, char **db_array);
 #endif
-int ROKEN_LIB_FUNCTION cgetstr(char *buf, const char *cap, char **str);
-int ROKEN_LIB_FUNCTION cgetustr(char *buf, const char *cap, char **str);
-int ROKEN_LIB_FUNCTION cgetnum(char *buf, const char *cap, long *num);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetstr(char *buf, const char *cap, =
char **str);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetustr(char *buf, const char *cap,=
 char **str);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetnum(char *buf, const char *cap, =
long *num);
 /*
  * Cgetset() allows the addition of a user specified buffer to be added
  * to the database array, in effect "pushing" the buffer on top of the
  * virtual database. 0 is returned on success, -1 on failure.
  */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 cgetset(const char *ent)
 {
     const char *source, *check;
@@ -155,7 +153,7 @@
  * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminato=
r)
  * return NULL.
  */
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 cgetcap(char *buf, const char *cap, int type)
 {
     char *bp;
@@ -206,7 +204,7 @@
  * encountered (couldn't open/read a file, etc.), and -3 if a potential
  * reference loop is detected.
  */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 cgetent(char **buf, char **db_array, const char *name)
 {
     size_t dummy;
@@ -233,14 +231,14 @@
  *	  MAX_RECURSION.
  */
 static int
-getent(char **cap, size_t *len, char **db_array, int fd,=20
+getent(char **cap, size_t *len, char **db_array, int fd,
        const char *name, int depth, char *nfield)
 {
     char *r_end, *rp =3D NULL, **db_p;	/* pacify gcc */
     int myfd =3D 0, eof, foundit;
     char *record;
     int tc_not_resolved;
-=09
+
     /*
      * Return with ``loop detected'' error if we've recursed more than
      * MAX_RECURSION times.
@@ -358,7 +356,7 @@
 		for (;;) {
 		    if (bp >=3D b_end) {
 			int n;
-	=09
+
 			n =3D read(fd, buf, sizeof(buf));
 			if (n <=3D 0) {
 			    if (myfd)
@@ -375,7 +373,7 @@
 			b_end =3D buf+n;
 			bp =3D buf;
 		    }
-=09
+
 		    c =3D *bp++;
 		    if (c =3D=3D '\n') {
 			if (slash) {
@@ -412,7 +410,7 @@
 		    *rp++ =3D c;
=20
 				/*
-				 * Enforce loop invariant: if no room=20
+				 * Enforce loop invariant: if no room
 				 * left in record buffer, try to get
 				 * some more.
 				 */
@@ -444,13 +442,13 @@
 		 */
 		if (eof)
 		    break;
-			=09
+
 		/*
 		 * Toss blank lines and comments.
 		 */
 		if (*record =3D=3D '\0' || *record =3D=3D '#')
 		    continue;
-=09
+
 		/*
 		 * See if this is the record we want ...
 		 */
@@ -510,7 +508,7 @@
 	    tclen =3D s - tcstart;
 	    tcend =3D s;
=20
-	    iret =3D getent(&icap, &ilen, db_p, fd, tc, depth+1,=20
+	    iret =3D getent(&icap, &ilen, db_p, fd, tc, depth+1,
 			  NULL);
 	    newicap =3D icap;		/* Put into a register. */
 	    newilen =3D ilen;
@@ -526,11 +524,11 @@
 		    tc_not_resolved =3D 1;
 				/* couldn't resolve tc */
 		if (iret =3D=3D -1) {
-		    *(s - 1) =3D ':';		=09
+		    *(s - 1) =3D ':';
 		    scan =3D s - 1;
 		    tc_not_resolved =3D 1;
 		    continue;
-				=09
+
 		}
 	    }
 	    /* not interested in name field of tc'ed record */
@@ -593,7 +591,7 @@
 	     */
 	    scan =3D s-1;
 	}
-=09
+
     }
     /*
      * Close file (if we opened it), give back any extra memory, and
@@ -603,17 +601,17 @@
 	(void)close(fd);
     *len =3D rp - record - 1;	/* don't count NUL */
     if (r_end > rp)
-	if ((record =3D=20
+	if ((record =3D
 	     realloc(record, (size_t)(rp - record))) =3D=3D NULL) {
 	    errno =3D ENOMEM;
 	    return (-2);
 	}
-	=09
+
     *cap =3D record;
     if (tc_not_resolved)
 	return (1);
     return (0);
-}=09
+}
=20
 #ifdef USE_DB
 static int
@@ -642,7 +640,7 @@
 		key.data =3D (char *)data.data + 1;
 		key.size =3D data.size - 1;
 	}
-=09
+
 	*bp =3D (char *)data.data + 1;
 	return (((char *)(data.data))[0] =3D=3D TCERR ? 1 : 0);
 }
@@ -702,7 +700,7 @@
 static int slash;
 static char **dbp;
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 cgetclose(void)
 {
     if (pfp !=3D NULL) {
@@ -717,7 +715,7 @@
=20
 #if 0
 /*
- * Cgetnext() gets either the first or next entry in the logical database=20
+ * Cgetnext() gets either the first or next entry in the logical database
  * specified by db_array.  It returns 0 upon completion of the database, 1
  * upon returning an entry with more remaining, and -1 if an error occurs.
  */
@@ -777,10 +775,10 @@
 		slash =3D 1;
 	    else
 		slash =3D 0;
-	}		=09
+	}
=20
=20
-	/*=20
+	/*
 	 * Line points to a name line.
 	 */
 	done =3D 0;
@@ -822,12 +820,12 @@
 		*rp++ =3D *cp;
=20
 	*rp =3D '\0';
-	/*=20
-	 * XXX=20
+	/*
+	 * XXX
 	 * Last argument of getent here should be nbuf if we want true
-	 * sequential access in the case of duplicates. =20
+	 * sequential access in the case of duplicates.
 	 * With NULL, getent will return the first entry found
-	 * rather than the duplicate entry record.  This is a=20
+	 * rather than the duplicate entry record.  This is a
 	 * matter of semantics that should be resolved.
 	 */
 	status =3D getent(bp, &dummy, db_array, -1, buf, 0, NULL);
@@ -849,14 +847,16 @@
  * couldn't be found, -2 if a system error was encountered (storage
  * allocation failure).
  */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 cgetstr(char *buf, const char *cap, char **str)
 {
     u_int m_room;
     const char *bp;
     char *mp;
     int len;
-    char *mem;
+    char *mem, *nmem;
+
+    *str =3D NULL;
=20
     /*
      * Find string capability cap
@@ -943,8 +943,11 @@
 	if (m_room =3D=3D 0) {
 	    size_t size =3D mp - mem;
=20
-	    if ((mem =3D realloc(mem, size + SFRAG)) =3D=3D NULL)
+	    if ((nmem =3D realloc(mem, size + SFRAG)) =3D=3D NULL) {
+		free(mem);
 		return (-2);
+	    }
+	    mem =3D nmem;
 	    m_room =3D SFRAG;
 	    mp =3D mem + size;
 	}
@@ -956,9 +959,13 @@
     /*
      * Give back any extra memory and return value and success.
      */
-    if (m_room !=3D 0)
-	if ((mem =3D realloc(mem, (size_t)(mp - mem))) =3D=3D NULL)
+    if (m_room !=3D 0) {
+	if ((nmem =3D realloc(mem, (size_t)(mp - mem))) =3D=3D NULL) {
+	    free(mem);
 	    return (-2);
+	}
+	mem =3D nmem;
+    }
     *str =3D mem;
     return (len);
 }
@@ -967,13 +974,13 @@
  * Cgetustr retrieves the value of the string capability cap from the
  * capability record pointed to by buf.  The difference between cgetustr()
  * and cgetstr() is that cgetustr does not decode escapes but rather treats
- * all characters literally.  A pointer to a  NUL terminated malloc'd=20
- * copy of the string is returned in the char pointed to by str.  The=20
+ * all characters literally.  A pointer to a  NUL terminated malloc'd
+ * copy of the string is returned in the char pointed to by str.  The
  * length of the string not including the trailing NUL is returned on succ=
ess,
- * -1 if the requested string capability couldn't be found, -2 if a system=20
+ * -1 if the requested string capability couldn't be found, -2 if a system
  * error was encountered (storage allocation failure).
  */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 cgetustr(char *buf, const char *cap, char **str)
 {
     u_int m_room;
@@ -1042,7 +1049,7 @@
  * the long pointed to by num.  0 is returned on success, -1 if the reques=
ted
  * numeric capability couldn't be found.
  */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 cgetnum(char *buf, const char *cap, long *num)
 {
     long n;
@@ -1109,10 +1116,10 @@
 {
     char *cp, tmp;
     int ret;
-=09
+
     for (cp =3D rec; *cp !=3D ':'; cp++)
 	;
-=09
+
     tmp =3D *(cp + 1);
     *(cp + 1) =3D '\0';
     ret =3D strcmp(nf, rec);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getcwd.c
--- a/head/crypto/heimdal/lib/roken/getcwd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getcwd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getcwd.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
@@ -45,7 +42,7 @@
=20
 #include "roken.h"
=20
-char* ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char* ROKEN_LIB_CALL
 getcwd(char *path, size_t size)
 {
     char xxx[MaxPathLen];
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getdtabl=
esize.c
--- a/head/crypto/heimdal/lib/roken/getdtablesize.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/roken/getdtablesize.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getdtablesize.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -64,7 +61,7 @@
 #include <sys/sysctl.h>
 #endif
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getdtablesize(void)
 {
   int files =3D -1;
@@ -79,7 +76,7 @@
 #if defined(HAVE_SYSCTL) && defined(CTL_KERN) && defined(KERN_MAXFILES)
   int mib[2];
   size_t len;
-   =20
+
   mib[0] =3D CTL_KERN;
   mib[1] =3D KERN_MAXFILES;
   len =3D sizeof(files);
@@ -96,7 +93,7 @@
 #ifdef NOFILE
   if (files < 0)
     files =3D NOFILE;
-#endif   =20
-   =20
+#endif
+
   return files;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getegid.c
--- a/head/crypto/heimdal/lib/roken/getegid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getegid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,13 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #include "roken.h"
=20
 #ifndef HAVE_GETEGID
=20
-RCSID("$Id: getegid.c 14773 2005-04-12 11:29:18Z lha $");
-
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getegid(void)
 {
     return getgid();
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/geteuid.c
--- a/head/crypto/heimdal/lib/roken/geteuid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/geteuid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,13 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #include "roken.h"
=20
 #ifndef HAVE_GETEUID
=20
-RCSID("$Id: geteuid.c 14773 2005-04-12 11:29:18Z lha $");
-
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 geteuid(void)
 {
     return getuid();
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getgid.c
--- a/head/crypto/heimdal/lib/roken/getgid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getgid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,12 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
 #ifndef HAVE_GETGID
=20
-RCSID("$Id: getgid.c 14773 2005-04-12 11:29:18Z lha $");
-
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getgid(void)
 {
     return 17;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/gethostn=
ame.c
--- a/head/crypto/heimdal/lib/roken/gethostname.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/gethostname.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,9 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
 #ifndef HAVE_GETHOSTNAME
@@ -49,7 +47,7 @@
  * interface is identical to gethostname(2).)
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 gethostname(char *name, int namelen)
 {
 #if defined(HAVE_UNAME)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getifadd=
rs.c
--- a/head/crypto/heimdal/lib/roken/getifaddrs.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/getifaddrs.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000 - 2002, 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000 - 2002, 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getifaddrs.c 21745 2007-07-31 16:11:25Z lha $");
-#endif
 #include "roken.h"
=20
 #ifdef __osf__
@@ -95,7 +92,7 @@
  * 3. Neither the name of the author nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -193,9 +190,9 @@
   return size;
 }
=20
-static void=20
-ifa_make_sockaddr(sa_family_t family,=20
-		  struct sockaddr *sa,=20
+static void
+ifa_make_sockaddr(sa_family_t family,
+		  struct sockaddr *sa,
 		  void *p, size_t len,
 		  uint32_t scope, uint32_t scopeid)
 {
@@ -227,8 +224,8 @@
=20
 #ifndef IFA_NETMASK
 static struct sockaddr *
-ifa_make_sockaddr_mask(sa_family_t family,=20
-		       struct sockaddr *sa,=20
+ifa_make_sockaddr_mask(sa_family_t family,
+		       struct sockaddr *sa,
 		       uint32_t prefixlen)
 {
   int i;
@@ -274,7 +271,7 @@
 #endif
=20
 /* =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D */
-static int=20
+static int
 nl_sendreq(int sd, int request, int flags, int *seq)
 {
   char reqbuf[NLMSG_ALIGN(sizeof(struct nlmsghdr)) +
@@ -300,9 +297,9 @@
 		 (struct sockaddr *)&nladdr, sizeof(nladdr)));
 }
=20
-static int=20
-nl_recvmsg(int sd, int request, int seq,=20
-	   void *buf, size_t buflen,=20
+static int
+nl_recvmsg(int sd, int request, int seq,
+	   void *buf, size_t buflen,
 	   int *flags)
 {
   struct msghdr msg;
@@ -327,8 +324,8 @@
   return read_len;
 }
=20
-static int=20
-nl_getmsg(int sd, int request, int seq,=20
+static int
+nl_getmsg(int sd, int request, int seq,
 	  struct nlmsghdr **nlhp,
 	  int *done)
 {
@@ -447,7 +444,7 @@
 }
=20
 /* ---------------------------------------------------------------------- =
*/
-static void=20
+static void
 free_nlmsglist(struct nlmsg_list *nlm0)
 {
   struct nlmsg_list *nlm, *nlm_next;
@@ -464,7 +461,7 @@
   __set_errno(saved_errno);
 }
=20
-static void=20
+static void
 free_data(void *data, void *ifdata)
 {
   int saved_errno =3D errno;
@@ -474,7 +471,7 @@
 }
=20
 /* ---------------------------------------------------------------------- =
*/
-static void=20
+static void
 nl_close(int sd)
 {
   int saved_errno =3D errno;
@@ -483,7 +480,7 @@
 }
=20
 /* ---------------------------------------------------------------------- =
*/
-static int=20
+static int
 nl_open(void)
 {
   struct sockaddr_nl nladdr;
@@ -501,7 +498,7 @@
 }
=20
 /* =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rk_getifaddrs(struct ifaddrs **ifap)
 {
   int sd;
@@ -561,7 +558,7 @@
 		    NLMSG_ALIGN(sizeof(struct ifaddrs[icnt]))
 		    + dlen + xlen + nlen);
       ifa =3D (struct ifaddrs *)data;
-      ifdata =3D calloc(1,=20
+      ifdata =3D calloc(1,
 		      NLMSG_ALIGN(sizeof(char *[max_ifindex+1]))
 		      + NLMSG_ALIGN(sizeof(uint16_t [max_ifindex+1])));
       if (ifap !=3D NULL)
@@ -588,8 +585,8 @@
       int nlmlen =3D nlm->size;
       if (!(nlh0 =3D nlm->nlh))
 	continue;
-      for (nlh =3D nlh0;=20
-	   NLMSG_OK(nlh, nlmlen);=20
+      for (nlh =3D nlh0;
+	   NLMSG_OK(nlh, nlmlen);
 	   nlh=3DNLMSG_NEXT(nlh,nlmlen)){
 	struct ifinfomsg *ifim =3D NULL;
 	struct ifaddrmsg *ifam =3D NULL;
@@ -635,7 +632,7 @@
 	default:
 	  continue;
 	}
-=09
+
 	if (!build){
 	  if (max_ifindex < nlm_index)
 	    max_ifindex =3D nlm_index;
@@ -826,8 +823,8 @@
 	  if (ifa->ifa_name =3D=3D NULL)
 	    ifa->ifa_name =3D iflist[nlm_index];
 #ifndef IFA_NETMASK
-	  if (ifa->ifa_addr &&=20
-	      ifa->ifa_addr->sa_family !=3D AF_UNSPEC &&=20
+	  if (ifa->ifa_addr &&
+	      ifa->ifa_addr->sa_family !=3D AF_UNSPEC &&
 	      ifa->ifa_addr->sa_family !=3D AF_PACKET){
 	    ifa->ifa_netmask =3D (struct sockaddr *)data;
 	    ifa_make_sockaddr_mask(ifa->ifa_addr->sa_family, ifa->ifa_netmask, nl=
m_prefixlen);
@@ -856,6 +853,13 @@
   return 0;
 }
=20
+void ROKEN_LIB_FUNCTION
+rk_freeifaddrs(struct ifaddrs *ifp)
+{
+    /* AF_NETLINK method uses a single allocation for all interfaces */
+    free(ifp);
+}
+
 #else /* !AF_NETLINK */
=20
 /*
@@ -863,7 +867,7 @@
  */
=20
 static int
-getifaddrs2(struct ifaddrs **ifap,=20
+getifaddrs2(struct ifaddrs **ifap,
 	    int af, int siocgifconf, int siocgifflags,
 	    size_t ifreq_sz)
 {
@@ -970,7 +974,7 @@
 		ret =3D ENOMEM;
 		goto error_out;
 	    }
-	    memcpy((*end)->ifa_broadaddr, &ifr->ifr_broadaddr,=20
+	    memcpy((*end)->ifa_broadaddr, &ifr->ifr_broadaddr,
 		   sizeof(ifr->ifr_broadaddr));
 	} else if(ifreq.ifr_flags & IFF_POINTOPOINT) {
 	    (*end)->ifa_dstaddr =3D malloc(sizeof(ifr->ifr_dstaddr));
@@ -978,7 +982,7 @@
 		ret =3D ENOMEM;
 		goto error_out;
 	    }
-	    memcpy((*end)->ifa_dstaddr, &ifr->ifr_dstaddr,=20
+	    memcpy((*end)->ifa_dstaddr, &ifr->ifr_dstaddr,
 		   sizeof(ifr->ifr_dstaddr));
 	} else
 	    (*end)->ifa_dstaddr =3D NULL;
@@ -989,7 +993,7 @@
 	(*end)->ifa_data =3D NULL;
=20
 	end =3D &(*end)->ifa_next;
-=09
+
     }
     *ifap =3D start;
     close(fd);
@@ -1005,7 +1009,7 @@
=20
 #if defined(HAVE_IPV6) && defined(SIOCGLIFCONF) && defined(SIOCGLIFFLAGS)
 static int
-getlifaddrs2(struct ifaddrs **ifap,=20
+getlifaddrs2(struct ifaddrs **ifap,
 	     int af, int siocgifconf, int siocgifflags,
 	     size_t ifreq_sz)
 {
@@ -1035,7 +1039,7 @@
 	    goto error_out;
 	}
 #ifndef __hpux
-	ifconf.lifc_family =3D AF_UNSPEC;
+	ifconf.lifc_family =3D af;
 	ifconf.lifc_flags  =3D 0;
 #endif
 	ifconf.lifc_len    =3D buf_size;
@@ -1116,7 +1120,7 @@
 		ret =3D ENOMEM;
 		goto error_out;
 	    }
-	    memcpy((*end)->ifa_broadaddr, &ifr->ifr_broadaddr,=20
+	    memcpy((*end)->ifa_broadaddr, &ifr->ifr_broadaddr,
 		   sizeof(ifr->ifr_broadaddr));
 	} else if(ifreq.ifr_flags & IFF_POINTOPOINT) {
 	    (*end)->ifa_dstaddr =3D malloc(sizeof(ifr->ifr_dstaddr));
@@ -1124,7 +1128,7 @@
 		ret =3D ENOMEM;
 		goto error_out;
 	    }
-	    memcpy((*end)->ifa_dstaddr, &ifr->ifr_dstaddr,=20
+	    memcpy((*end)->ifa_dstaddr, &ifr->ifr_dstaddr,
 		   sizeof(ifr->ifr_dstaddr));
 	} else
 	    (*end)->ifa_dstaddr =3D NULL;
@@ -1135,7 +1139,7 @@
 	(*end)->ifa_data =3D NULL;
=20
 	end =3D &(*end)->ifa_next;
-=09
+
     }
     *ifap =3D start;
     close(fd);
@@ -1150,8 +1154,29 @@
 }
 #endif /* defined(HAVE_IPV6) && defined(SIOCGLIFCONF) && defined(SIOCGLIFF=
LAGS) */
=20
-int ROKEN_LIB_FUNCTION
-rk_getifaddrs(struct ifaddrs **ifap)=20
+/**
+ * Join two struct ifaddrs lists by appending supp to base.
+ * Either may be NULL. The new list head (usually base) will be
+ * returned.
+ */
+static struct ifaddrs *
+append_ifaddrs(struct ifaddrs *base, struct ifaddrs *supp) {
+    if (!base)
+	return supp;
+
+    if (!supp)
+	return base;
+
+    while (base->ifa_next)
+	base =3D base->ifa_next;
+
+    base->ifa_next =3D supp;
+
+    return base;
+}
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_getifaddrs(struct ifaddrs **ifap)
 {
     int ret =3D -1;
     errno =3D ENXIO;
@@ -1161,9 +1186,43 @@
 			   sizeof(struct in6_ifreq));
 #endif
 #if defined(HAVE_IPV6) && defined(SIOCGLIFCONF) && defined(SIOCGLIFFLAGS)
-    if (ret)
-	ret =3D getlifaddrs2 (ifap, AF_INET6, SIOCGLIFCONF, SIOCGLIFFLAGS,
+    /* Do IPv6 and IPv4 queries separately then join the result.
+     *
+     * HP-UX only returns IPv6 addresses using SIOCGLIFCONF,
+     * SIOCGIFCONF has to be used for IPv4 addresses. The result is then
+     * merged.
+     *
+     * Solaris needs particular care, because a SIOCGLIFCONF lookup using
+     * AF_UNSPEC can fail in a Zone requiring an AF_INET lookup, so we just
+     * do them separately the same as for HP-UX. See
+     * http://repo.or.cz/w/heimdal.git/commitdiff/76afc31e9ba2f37e64c70adc=
006ade9e37e9ef73
+     */
+    if (ret) {
+	int v6err, v4err;
+	struct ifaddrs *v6addrs, *v4addrs;
+
+	v6err =3D getlifaddrs2 (&v6addrs, AF_INET6, SIOCGLIFCONF, SIOCGLIFFLAGS,
 			    sizeof(struct lifreq));
+	v4err =3D getifaddrs2 (&v4addrs, AF_INET, SIOCGIFCONF, SIOCGIFFLAGS,
+			    sizeof(struct ifreq));
+	if (v6err)
+	    v6addrs =3D NULL;
+	if (v4err)
+	    v4addrs =3D NULL;
+
+	if (v6addrs) {
+	    if (v4addrs)
+		*ifap =3D append_ifaddrs(v6addrs, v4addrs);
+	    else
+		*ifap =3D v6addrs;
+	} else if (v4addrs) {
+	    *ifap =3D v4addrs;
+	} else {
+	    *ifap =3D NULL;
+	}
+
+	ret =3D (v6err || v4err) ? -1 : 0;
+    }
 #endif
 #if defined(HAVE_IPV6) && defined(SIOCGIFCONF)
     if (ret)
@@ -1178,20 +1237,18 @@
     return ret;
 }
=20
-#endif /* !AF_NETLINK */
-
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rk_freeifaddrs(struct ifaddrs *ifp)
 {
     struct ifaddrs *p, *q;
-   =20
+
     for(p =3D ifp; p; ) {
 	free(p->ifa_name);
 	if(p->ifa_addr)
 	    free(p->ifa_addr);
-	if(p->ifa_dstaddr)=20
+	if(p->ifa_dstaddr)
 	    free(p->ifa_dstaddr);
-	if(p->ifa_netmask)=20
+	if(p->ifa_netmask)
 	    free(p->ifa_netmask);
 	if(p->ifa_data)
 	    free(p->ifa_data);
@@ -1201,6 +1258,8 @@
     }
 }
=20
+#endif /* !AF_NETLINK */
+
 #ifdef TEST
=20
 void
@@ -1212,25 +1271,25 @@
     for(i =3D 0; i < sa->sa_len - ((long)sa->sa_data - (long)&sa->sa_famil=
y); i++)
 	printf("%02x", ((unsigned char*)sa->sa_data)[i]);
 #else
-    for(i =3D 0; i < sizeof(sa->sa_data); i++)=20
+    for(i =3D 0; i < sizeof(sa->sa_data); i++)
 	printf("%02x", ((unsigned char*)sa->sa_data)[i]);
 #endif
     printf("\n");
 }
=20
-void=20
+void
 print_ifaddrs(struct ifaddrs *x)
 {
     struct ifaddrs *p;
-   =20
+
     for(p =3D x; p; p =3D p->ifa_next) {
 	printf("%s\n", p->ifa_name);
 	printf("  flags=3D%x\n", p->ifa_flags);
 	if(p->ifa_addr)
 	    print_addr("addr", p->ifa_addr);
-	if(p->ifa_dstaddr)=20
+	if(p->ifa_dstaddr)
 	    print_addr("dstaddr", p->ifa_dstaddr);
-	if(p->ifa_netmask)=20
+	if(p->ifa_netmask)
 	    print_addr("netmask", p->ifa_netmask);
 	printf("  %p\n", p->ifa_data);
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getipnod=
ebyaddr.c
--- a/head/crypto/heimdal/lib/roken/getipnodebyaddr.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/roken/getipnodebyaddr.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getipnodebyaddr.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -43,7 +40,7 @@
  * to a malloced struct hostent or NULL.
  */
=20
-struct hostent * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
 getipnodebyaddr (const void *src, size_t len, int af, int *error_num)
 {
     struct hostent *tmp;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getipnod=
ebyname.c
--- a/head/crypto/heimdal/lib/roken/getipnodebyname.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/roken/getipnodebyname.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getipnodebyname.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -47,7 +44,7 @@
  * to a malloced struct hostent or NULL.
  */
=20
-struct hostent * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
 getipnodebyname (const char *name, int af, int flags, int *error_num)
 {
     struct hostent *tmp;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getnamei=
nfo.c
--- a/head/crypto/heimdal/lib/roken/getnameinfo.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/getnameinfo.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getnameinfo.c 15412 2005-06-16 16:53:09Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -94,7 +91,7 @@
  *
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getnameinfo(const struct sockaddr *sa, socklen_t salen,
 	    char *host, size_t hostlen,
 	    char *serv, size_t servlen,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getnamei=
nfo_verified.c
--- a/head/crypto/heimdal/lib/roken/getnameinfo_verified.c	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getnameinfo_verified.c	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2002 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2002 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getnameinfo_verified.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -46,7 +43,7 @@
  * NI_NAMEREQD flag is set or return the numeric address as a string.
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getnameinfo_verified(const struct sockaddr *sa, socklen_t salen,
 		     char *host, size_t hostlen,
 		     char *serv, size_t servlen,
@@ -56,6 +53,8 @@
     struct addrinfo *ai, *a;
     char servbuf[NI_MAXSERV];
     struct addrinfo hints;
+    void *saaddr;
+    size_t sasize;
=20
     if (host =3D=3D NULL)
 	return EAI_NONAME;
@@ -75,9 +74,12 @@
     ret =3D getaddrinfo (host, serv, &hints, &ai);
     if (ret)
 	goto fail;
+
+    saaddr =3D socket_get_address(sa);
+    sasize =3D socket_addr_size(sa);
     for (a =3D ai; a !=3D NULL; a =3D a->ai_next) {
-	if (a->ai_addrlen =3D=3D salen
-	    && memcmp (a->ai_addr, sa, salen) =3D=3D 0) {
+	if (sasize =3D=3D socket_addr_size(a->ai_addr) &&
+	    memcmp(saaddr, socket_get_address(a->ai_addr), sasize) =3D=3D 0) {
 	    freeaddrinfo (ai);
 	    return 0;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getopt.c
--- a/head/crypto/heimdal/lib/roken/getopt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getopt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,6 +34,9 @@
 #ifndef __STDC__
 #define const
 #endif
+#include <config.h>
+#include "roken.h"
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -41,21 +44,18 @@
 /*
  * get option letter from argument vector
  */
-int	opterr =3D 1,		/* if error message should be printed */
-	optind =3D 1,		/* index into parent argv vector */
-	optopt,			/* character checked for validity */
-	optreset;		/* reset getopt */
-char	*optarg;		/* argument associated with option */
+ROKEN_LIB_VARIABLE int opterr =3D 1; /* if error message should be printed=
 */
+ROKEN_LIB_VARIABLE int optind =3D 1; /* index into parent argv vector */
+ROKEN_LIB_VARIABLE int optopt;   /* character checked for validity */
+int	optreset;                /* reset getopt */
+ROKEN_LIB_VARIABLE char	*optarg; /* argument associated with option */
=20
 #define	BADCH	(int)'?'
 #define	BADARG	(int)':'
 #define	EMSG	""
=20
-int ROKEN_LIB_FUNCTION
-getopt(nargc, nargv, ostr)
-	int nargc;
-	char * const *nargv;
-	const char *ostr;
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getopt(int nargc, char * const *nargv, const char *ostr)
 {
 	static char *place =3D EMSG;		/* option letter processing */
 	char *oli;			/* option letter list index */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getprogn=
ame.c
--- a/head/crypto/heimdal/lib/roken/getprogname.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/getprogname.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-2004 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: getprogname.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -43,7 +40,7 @@
 #endif
=20
 #ifndef HAVE_GETPROGNAME
-const char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 getprogname(void)
 {
     return __progname;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/gettimeo=
fday.c
--- a/head/crypto/heimdal/lib/roken/gettimeofday.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/roken/gettimeofday.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,25 +31,48 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
 #ifndef HAVE_GETTIMEOFDAY
=20
-RCSID("$Id: gettimeofday.c 14773 2005-04-12 11:29:18Z lha $");
+#ifdef _WIN32
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+gettimeofday (struct timeval *tp, void *ignore)
+{
+    FILETIME ft;
+    ULARGE_INTEGER li;
+    ULONGLONG ull;
+
+    GetSystemTimeAsFileTime(&ft);
+    li.LowPart =3D ft.dwLowDateTime;
+    li.HighPart =3D ft.dwHighDateTime;
+    ull =3D li.QuadPart;
+
+    ull -=3D 116444736000000000i64;
+    ull /=3D 10i64;               /* ull is now in microseconds */
+
+    tp->tv_usec =3D (ull % 1000000i64);
+    tp->tv_sec  =3D (ull / 1000000i64);
+
+    return 0;
+}
+
+#else
=20
 /*
  * Simple gettimeofday that only returns seconds.
  */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 gettimeofday (struct timeval *tp, void *ignore)
 {
      time_t t;
=20
      t =3D time(NULL);
-     tp->tv_sec  =3D t;
+     tp->tv_sec  =3D (long) t;
      tp->tv_usec =3D 0;
      return 0;
 }
+
+#endif  /* !_WIN32 */
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getuid.c
--- a/head/crypto/heimdal/lib/roken/getuid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/getuid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,12 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
 #ifndef HAVE_GETUID
=20
-RCSID("$Id: getuid.c 14773 2005-04-12 11:29:18Z lha $");
-
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getuid(void)
 {
     return 17;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/getusers=
hell.c
--- a/head/crypto/heimdal/lib/roken/getusershell.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/roken/getusershell.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -27,11 +27,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
-
-RCSID("$Id: getusershell.c 21005 2007-06-08 01:54:35Z lha $");
=20
 #ifndef HAVE_GETUSERSHELL
=20
@@ -85,7 +81,7 @@
 /*
  * Get a list of shells from _PATH_SHELLS, if it exists.
  */
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 getusershell()
 {
     char *ret;
@@ -98,7 +94,7 @@
     return (ret);
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 endusershell()
 {
     if (shells !=3D NULL)
@@ -110,7 +106,7 @@
     curshell =3D NULL;
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 setusershell()
 {
     curshell =3D initshells();
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/glob.c
--- a/head/crypto/heimdal/lib/roken/glob.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/glob.c	Tue Apr 17 11:51:51 2012 +0300
@@ -50,14 +50,12 @@
  * GLOB_TILDE:
  *	expand ~user/foo to the /home/dir/of/user/foo
  * GLOB_BRACE:
- *	expand {1,2}{a,b} to 1a 1b 2a 2b=20
+ *	expand {1,2}{a,b} to 1a 1b 2a 2b
  * gl_matchc:
  *	Number of matches in the current invocation of glob.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #ifdef HAVE_SYS_PARAM_H
 #include <sys/param.h>
@@ -166,10 +164,10 @@
 static void	 qprintf (const char *, Char *);
 #endif
=20
-int ROKEN_LIB_FUNCTION
-glob(const char *pattern,=20
-     int flags,=20
-     int (*errfunc)(const char *, int),=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+glob(const char *pattern,
+     int flags,
+     int (*errfunc)(const char *, int),
      glob_t *pglob)
 {
 	const u_char *patnext;
@@ -191,7 +189,7 @@
 	bufend =3D bufnext + MaxPathLen;
 	if (flags & GLOB_QUOTE) {
 		/* Protect the quoted characters. */
-		while (bufnext < bufend && (c =3D *patnext++) !=3D CHAR_EOS)=20
+		while (bufnext < bufend && (c =3D *patnext++) !=3D CHAR_EOS)
 			if (c =3D=3D CHAR_QUOTE) {
 				if ((c =3D *patnext++) =3D=3D CHAR_EOS) {
 					c =3D CHAR_QUOTE;
@@ -202,8 +200,8 @@
 			else
 				*bufnext++ =3D c;
 	}
-	else=20
-	    while (bufnext < bufend && (c =3D *patnext++) !=3D CHAR_EOS)=20
+	else
+	    while (bufnext < bufend && (c =3D *patnext++) !=3D CHAR_EOS)
 		    *bufnext++ =3D c;
 	*bufnext =3D CHAR_EOS;
=20
@@ -240,7 +238,7 @@
  * If it succeeds then it invokes globexp1 with the new pattern.
  * If it fails then it tries to glob the rest of the pattern and returns.
  */
-static int globexp2(const Char *ptr, const Char *pattern,=20
+static int globexp2(const Char *ptr, const Char *pattern,
 		    glob_t *pglob, int *rv)
 {
 	int     i;
@@ -260,7 +258,7 @@
 			for (pm =3D pe++; *pe !=3D CHAR_RBRACKET && *pe !=3D CHAR_EOS; pe++)
 				continue;
 			if (*pe =3D=3D CHAR_EOS) {
-				/*=20
+				/*
 				 * We could not find a matching CHAR_RBRACKET.
 				 * Ignore and just look for CHAR_RBRACE
 				 */
@@ -288,7 +286,7 @@
 			for (pl =3D pm++; *pm !=3D CHAR_RBRACKET && *pm !=3D CHAR_EOS; pm++)
 				continue;
 			if (*pm =3D=3D CHAR_EOS) {
-				/*=20
+				/*
 				 * We could not find a matching CHAR_RBRACKET.
 				 * Ignore and just look for CHAR_RBRACE
 				 */
@@ -313,7 +311,7 @@
 				/* Append the current string */
 				for (lm =3D ls; (pl < pm); *lm++ =3D *pl++)
 					continue;
-				/*=20
+				/*
 				 * Append the rest of the pattern after the
 				 * closing brace
 				 */
@@ -355,15 +353,15 @@
 		return pattern;
=20
 	/* Copy up to the end of the string or / */
-	for (p =3D pattern + 1, h =3D (char *) patbuf; *p && *p !=3D CHAR_SLASH;=20
+	for (p =3D pattern + 1, h =3D (char *) patbuf; *p && *p !=3D CHAR_SLASH;
 	     *h++ =3D *p++)
 		continue;
=20
 	*h =3D CHAR_EOS;
=20
 	if (((char *) patbuf)[0] =3D=3D CHAR_EOS) {
-		/*=20
-		 * handle a plain ~ or ~/ by expanding $HOME=20
+		/*
+		 * handle a plain ~ or ~/ by expanding $HOME
 		 * first and then trying the password file
 		 */
 		if ((h =3D getenv("HOME")) =3D=3D NULL) {
@@ -386,14 +384,14 @@
 	/* Copy the home directory */
 	for (b =3D patbuf; *h; *b++ =3D *h++)
 		continue;
-=09
+
 	/* Append the rest of the pattern */
 	while ((*b++ =3D *p++) !=3D CHAR_EOS)
 		continue;
=20
 	return patbuf;
 }
-=09
+
=20
 /*
  * The main glob() routine: compiles the pattern (optionally processing
@@ -450,7 +448,7 @@
 			break;
 		case CHAR_STAR:
 			pglob->gl_flags |=3D GLOB_MAGCHAR;
-			/* collapse adjacent stars to one,=20
+			/* collapse adjacent stars to one,
 			 * to avoid exponential behavior
 			 */
 			if (bufnext =3D=3D patbuf || bufnext[-1] !=3D M_ALL)
@@ -470,17 +468,17 @@
 		return(err);
=20
 	/*
-	 * If there was no match we are going to append the pattern=20
+	 * If there was no match we are going to append the pattern
 	 * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
 	 * and the pattern did not contain any magic characters
 	 * GLOB_NOMAGIC is there just for compatibility with csh.
 	 */
-	if (pglob->gl_pathc =3D=3D oldpathc &&=20
-	    ((pglob->gl_flags & GLOB_NOCHECK) ||=20
+	if (pglob->gl_pathc =3D=3D oldpathc &&
+	    ((pglob->gl_flags & GLOB_NOCHECK) ||
 	      ((pglob->gl_flags & GLOB_NOMAGIC) &&
 	       !(pglob->gl_flags & GLOB_MAGCHAR))))
 		return(globextend(pattern, pglob, &limit));
-	else if (!(pglob->gl_flags & GLOB_NOSORT))=20
+	else if (!(pglob->gl_flags & GLOB_NOSORT))
 		qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
 		    pglob->gl_pathc - oldpathc, sizeof(char *), compare);
 	return(0);
@@ -534,7 +532,7 @@
 			*pathend =3D CHAR_EOS;
 			if (g_lstat(pathbuf, &sb, pglob))
 				return(0);
-	=09
+
 			if (((pglob->gl_flags & GLOB_MARK) &&
 			    pathend[-1] !=3D CHAR_SEP) && (S_ISDIR(sb.st_mode)
 			    || (S_ISLNK(sb.st_mode) &&
@@ -569,7 +567,7 @@
 }
=20
 static int
-glob3(Char *pathbuf, Char *pathend, Char *pattern, Char *restpattern,=20
+glob3(Char *pathbuf, Char *pathend, Char *pattern, Char *restpattern,
       glob_t *pglob, size_t *limit)
 {
 	struct dirent *dp;
@@ -587,7 +585,7 @@
=20
 	*pathend =3D CHAR_EOS;
 	errno =3D 0;
-	   =20
+
 	if ((dirp =3D g_opendir(pathbuf, pglob)) =3D=3D NULL) {
 		/* TODO: don't call for ENOENT or ENOTDIR? */
 		if (pglob->gl_errfunc) {
@@ -613,7 +611,7 @@
 		/* Initial CHAR_DOT must be matched literally. */
 		if (dp->d_name[0] =3D=3D CHAR_DOT && *pattern !=3D CHAR_DOT)
 			continue;
-		for (sc =3D (u_char *) dp->d_name, dc =3D pathend;=20
+		for (sc =3D (u_char *) dp->d_name, dc =3D pathend;
 		     (*dc++ =3D *sc++) !=3D CHAR_EOS;)
 			continue;
 		if (!match(pathend, pattern, restpattern)) {
@@ -657,7 +655,7 @@
 	const Char *p;
=20
 	newsize =3D sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs);
-	pathv =3D pglob->gl_pathv ?=20
+	pathv =3D pglob->gl_pathv ?
 		    realloc(pglob->gl_pathv, newsize) :
 		    malloc(newsize);
 	if (pathv =3D=3D NULL)
@@ -706,7 +704,7 @@
 		case M_ALL:
 			if (pat =3D=3D patend)
 				return(1);
-			do=20
+			do
 			    if (match(name, pat, patend))
 				    return(1);
 			while (*name++ !=3D CHAR_EOS);
@@ -741,7 +739,7 @@
 }
=20
 /* Free allocated data belonging to a glob_t structure. */
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 globfree(glob_t *pglob)
 {
 	int i;
@@ -831,7 +829,7 @@
 }
=20
 #ifdef DEBUG
-static void=20
+static void
 qprintf(const Char *str, Char *s)
 {
 	Char *p;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/glob.hin
--- a/head/crypto/heimdal/lib/roken/glob.hin	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/glob.hin	Tue Apr 17 11:51:51 2012 +0300
@@ -37,9 +37,11 @@
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL _stdcall
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/h_errno.c
--- a/head/crypto/heimdal/lib/roken/h_errno.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/h_errno.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: h_errno.c 10442 2001-08-08 03:47:23Z assar $");
-#endif
=20
 #ifndef HAVE_H_ERRNO
 int h_errno =3D -17; /* Some magic number */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/hex-test=
.c
--- a/head/crypto/heimdal/lib/roken/hex-test.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/hex-test.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001, 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001, 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,12 +31,8 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
=20
-RCSID("$Id: hex-test.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-
 #include "roken.h"
 #include <hex.h>
=20
@@ -66,7 +62,7 @@
 	int len;
 	len =3D hex_encode(t->data, t->len, &str);
 	if(strcmp(str, t->result) !=3D 0) {
-	    fprintf(stderr, "failed test %d: %s !=3D %s\n", numtest,=20
+	    fprintf(stderr, "failed test %d: %s !=3D %s\n", numtest,
 		    str, t->result);
 	    numerr++;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/hex.c
--- a/head/crypto/heimdal/lib/roken/hex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/hex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004-2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2004-2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
@@ -31,17 +31,15 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-RCSID("$Id: hex.c 16504 2006-01-09 17:09:29Z lha $");
-#endif
 #include "roken.h"
 #include <ctype.h>
 #include "hex.h"
=20
-const static char hexchar[] =3D "0123456789ABCDEF";
+static const char hexchar[16] =3D "0123456789ABCDEF";
=20
-static int=20
+static int
 pos(char c)
 {
     const char *p;
@@ -52,7 +50,7 @@
     return -1;
 }
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 hex_encode(const void *data, size_t size, char **str)
 {
     const unsigned char *q =3D data;
@@ -60,13 +58,17 @@
     char *p;
=20
     /* check for overflow */
-    if (size * 2 < size)
+    if (size * 2 < size) {
+        *str =3D NULL;
 	return -1;
+    }
=20
     p =3D malloc(size * 2 + 1);
-    if (p =3D=3D NULL)
+    if (p =3D=3D NULL) {
+        *str =3D NULL;
 	return -1;
-   =20
+    }
+
     for (i =3D 0; i < size; i++) {
 	p[i * 2] =3D hexchar[(*q >> 4) & 0xf];
 	p[i * 2 + 1] =3D hexchar[*q & 0xf];
@@ -78,20 +80,19 @@
     return i * 2;
 }
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 hex_decode(const char *str, void *data, size_t len)
 {
     size_t l;
     unsigned char *p =3D data;
     size_t i;
-=09
+
     l =3D strlen(str);
-   =20
+
     /* check for overflow, same as (l+1)/2 but overflow safe */
     if ((l/2) + (l&1) > len)
 	return -1;
=20
-    i =3D 0;
     if (l & 1) {
 	p[0] =3D pos(str[0]);
 	str++;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/hex.h
--- a/head/crypto/heimdal/lib/roken/hex.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/hex.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,25 +31,27 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: hex.h 14773 2005-04-12 11:29:18Z lha $ */
+/* $Id$ */
=20
 #ifndef _rk_HEX_H_
 #define _rk_HEX_H_ 1
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
 #define hex_encode rk_hex_encode
 #define hex_decode rk_hex_decode
=20
-ssize_t	ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 	hex_encode(const void *, size_t, char **);
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 	hex_decode(const char *, void *, size_t);
=20
 #endif /* _rk_HEX_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/hostent_=
find_fqdn.c
--- a/head/crypto/heimdal/lib/roken/hostent_find_fqdn.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/hostent_find_fqdn.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: hostent_find_fqdn.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -42,7 +39,7 @@
  * Try to find a fqdn (with `.') in he if possible, else return h_name
  */
=20
-const char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 hostent_find_fqdn (const struct hostent *he)
 {
     const char *ret =3D he->h_name;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/hstrerro=
r.c
--- a/head/crypto/heimdal/lib/roken/hstrerror.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/hstrerror.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: hstrerror.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #ifndef HAVE_HSTRERROR
=20
@@ -67,7 +64,7 @@
=20
 #endif
=20
-const char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 hstrerror(int herr)
 {
     if (0 <=3D herr && herr < h_nerr)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/ifaddrs.=
hin
--- a/head/crypto/heimdal/lib/roken/ifaddrs.hin	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/ifaddrs.hin	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *=20
@@ -31,16 +31,18 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: ifaddrs.hin 19309 2006-12-11 18:58:15Z lha $ */
+/* $Id$ */
=20
 #ifndef __ifaddrs_h__
 #define __ifaddrs_h__
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL _stdcall
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/inet_ato=
n.c
--- a/head/crypto/heimdal/lib/roken/inet_aton.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/inet_aton.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: inet_aton.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
 /* Minimal implementation of inet_aton.
  * Cannot distinguish between failure and a local broadcast address. */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 inet_aton(const char *cp, struct in_addr *addr)
 {
   addr->s_addr =3D inet_addr(cp);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/inet_nto=
p.c
--- a/head/crypto/heimdal/lib/roken/inet_ntop.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/inet_ntop.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: inet_ntop.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -86,6 +83,7 @@
     const struct in6_addr *addr =3D (struct in6_addr *)src;
     const u_char *ptr =3D addr->s6_addr;
     const char *orig_dst =3D dst;
+    int compressed =3D 0;
=20
     if (size < INET6_ADDRSTRLEN) {
 	errno =3D ENOSPC;
@@ -94,6 +92,26 @@
     for (i =3D 0; i < 8; ++i) {
 	int non_zerop =3D 0;
=20
+        if (compressed =3D=3D 0 &&
+            ptr[0] =3D=3D 0 && ptr[1] =3D=3D 0 &&
+            i <=3D 5 &&
+            ptr[2] =3D=3D 0 && ptr[3] =3D=3D 0 &&
+            ptr[4] =3D=3D 0 && ptr[5] =3D=3D 0) {
+
+            compressed =3D 1;
+
+            if (i =3D=3D 0)
+                *dst++ =3D ':';
+            *dst++ =3D ':';
+
+            for (ptr +=3D 6, i +=3D 3;
+                 i < 8 && ptr[0] =3D=3D 0 && ptr[1] =3D=3D 0;
+                 ++i, ptr +=3D 2);
+
+            if (i >=3D 8)
+                break;
+        }
+
 	if (non_zerop || (ptr[0] >> 4)) {
 	    *dst++ =3D xdigits[ptr[0] >> 4];
 	    non_zerop =3D 1;
@@ -116,7 +134,7 @@
 }
 #endif /* HAVE_IPV6 */
=20
-const char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 inet_ntop(int af, const void *src, char *dst, size_t size)
 {
     switch (af) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/inet_pto=
n.c
--- a/head/crypto/heimdal/lib/roken/inet_pton.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/inet_pton.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,79 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: inet_pton.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+#ifdef HAVE_WINSOCK
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+inet_pton(int af, const char *csrc, void *dst)
+{
+    char * src;
+
+    if (csrc =3D=3D NULL || (src =3D strdup(csrc)) =3D=3D NULL) {
+	_set_errno( ENOMEM );
+	return 0;
+    }
+
+    switch (af) {
+    case AF_INET:
+	{
+	    struct sockaddr_in  si4;
+	    INT r;
+	    INT s =3D sizeof(si4);
+
+	    si4.sin_family =3D AF_INET;
+	    r =3D WSAStringToAddress(src, AF_INET, NULL, (LPSOCKADDR) &si4, &s);
+	    free(src);
+	    src =3D NULL;
+
+	    if (r =3D=3D 0) {
+		memcpy(dst, &si4.sin_addr, sizeof(si4.sin_addr));
+		return 1;
+	    }
+	}
+	break;
+
+    case AF_INET6:
+	{
+	    struct sockaddr_in6 si6;
+	    INT r;
+	    INT s =3D sizeof(si6);
+
+	    si6.sin6_family =3D AF_INET6;
+	    r =3D WSAStringToAddress(src, AF_INET6, NULL, (LPSOCKADDR) &si6, &s);
+	    free(src);
+	    src =3D NULL;
+
+	    if (r =3D=3D 0) {
+		memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
+		return 1;
+	    }
+	}
+	break;
+
+    default:
+	_set_errno( EAFNOSUPPORT );
+	return -1;
+    }
+
+    /* the call failed */
+    {
+	int le =3D WSAGetLastError();
+
+	if (le =3D=3D WSAEINVAL)
+	    return 0;
+
+	_set_errno(le);
+	return -1;
+    }
+}
+
+#else  /* !HAVE_WINSOCK */
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 inet_pton(int af, const char *src, void *dst)
 {
     if (af !=3D AF_INET) {
@@ -47,3 +112,5 @@
     }
     return inet_aton (src, dst);
 }
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/initgrou=
ps.c
--- a/head/crypto/heimdal/lib/roken/initgroups.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/initgroups.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: initgroups.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 initgroups(const char *name, gid_t basegid)
 {
   return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/innetgr.c
--- a/head/crypto/heimdal/lib/roken/innetgr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/innetgr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -30,17 +30,13 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
 #ifndef HAVE_INNETGR
=20
-RCSID("$Id: innetgr.c 14773 2005-04-12 11:29:18Z lha $");
-
-int ROKEN_LIB_FUNCTION
-innetgr(const char *netgroup, const char *machine,=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+innetgr(const char *netgroup, const char *machine,
 	const char *user, const char *domain)
 {
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/iruserok=
.c
--- a/head/crypto/heimdal/lib/roken/iruserok.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/iruserok.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -27,10 +27,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: iruserok.c 17879 2006-08-08 21:50:40Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <ctype.h>
@@ -217,7 +214,7 @@
  *
  * Returns 0 if ok, -1 if not ok.
  */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 iruserok(unsigned raddr, int superuser, const char *ruser, const char *lus=
er)
 {
 	char *cp;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/issuid.c
--- a/head/crypto/heimdal/lib/roken/issuid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/issuid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,44 +1,41 @@
 /*
- * Copyright (c) 1998 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: issuid.c 15131 2005-05-13 07:42:03Z lha $");
-#endif
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 issuid(void)
 {
 #if defined(HAVE_ISSETUGID)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/k_getpwn=
am.c
--- a/head/crypto/heimdal/lib/roken/k_getpwnam.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/k_getpwnam.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: k_getpwnam.c 14773 2005-04-12 11:29:18Z lha $");
-#endif /* HAVE_CONFIG_H */
=20
 #include "roken.h"
 #ifdef HAVE_SHADOW_H
 #include <shadow.h>
 #endif
=20
-struct passwd * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct passwd * ROKEN_LIB_CALL
 k_getpwnam (const char *user)
 {
      struct passwd *p;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/k_getpwu=
id.c
--- a/head/crypto/heimdal/lib/roken/k_getpwuid.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/k_getpwuid.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: k_getpwuid.c 14773 2005-04-12 11:29:18Z lha $");
-#endif /* HAVE_CONFIG_H */
=20
 #include "roken.h"
 #ifdef HAVE_SHADOW_H
 #include <shadow.h>
 #endif
=20
-struct passwd * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct passwd * ROKEN_LIB_CALL
 k_getpwuid (uid_t uid)
 {
      struct passwd *p;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/localtim=
e_r.c
--- a/head/crypto/heimdal/lib/roken/localtime_r.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/localtime_r.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: localtime_r.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <time.h>
@@ -42,16 +39,22 @@
=20
 #ifndef HAVE_LOCALTIME_R
=20
-struct tm * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct tm * ROKEN_LIB_CALL
 localtime_r(const time_t *timer, struct tm *result)
 {
+#ifdef _MSC_VER
+
+    return (localtime_s(result, timer) =3D=3D 0)? result : NULL;
+
+#else
     struct tm *tm;
-   =20
+
     tm =3D localtime((time_t *)timer);
     if (tm =3D=3D NULL)
 	return NULL;
     *result =3D *tm;
     return result;
+#endif
 }
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/lstat.c
--- a/head/crypto/heimdal/lib/roken/lstat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/lstat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: lstat.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 lstat(const char *path, struct stat *buf)
 {
   return stat(path, buf);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/memmove.c
--- a/head/crypto/heimdal/lib/roken/memmove.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/memmove.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,20 +31,17 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: memmove.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
-/*=20
- * memmove for systems that doesn't have it=20
+/*
+ * memmove for systems that doesn't have it
  */
=20
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
=20
-void* ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void* ROKEN_LIB_CALL
 memmove(void *s1, const void *s2, size_t n)
 {
   char *s=3D(char*)s2, *d=3D(char*)s1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/mini_ine=
td.c
--- a/head/crypto/heimdal/lib/roken/mini_inetd.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/mini_inetd.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: mini_inetd.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <err.h>
 #include "roken.h"
@@ -44,62 +41,93 @@
  */
=20
 static void
-accept_it (int s)
+accept_it (rk_socket_t s, rk_socket_t *ret_socket)
 {
-    int s2;
+    rk_socket_t as;
=20
-    s2 =3D accept(s, NULL, NULL);
-    if(s2 < 0)
+    as =3D accept(s, NULL, NULL);
+    if(rk_IS_BAD_SOCKET(as))
 	err (1, "accept");
-    close(s);
-    dup2(s2, STDIN_FILENO);
-    dup2(s2, STDOUT_FILENO);
-    /* dup2(s2, STDERR_FILENO); */
-    close(s2);
+
+    if (ret_socket) {
+
+	*ret_socket =3D as;
+
+    } else {
+	int fd =3D socket_to_fd(as, 0);
+
+	/* We would use _O_RDONLY for the socket_to_fd() call for
+	   STDIN, but there are instances where we assume that STDIN
+	   is a r/w socket. */
+
+	dup2(fd, STDIN_FILENO);
+	dup2(fd, STDOUT_FILENO);
+
+	rk_closesocket(as);
+    }
 }
=20
-/*
- * Listen on a specified port, emulating inetd.
+/**
+ * Listen on a specified addresses
+ *
+ * Listens on the specified addresses for incoming connections.  If
+ * the \a ret_socket parameter is \a NULL, on return STDIN and STDOUT
+ * will be connected to an accepted socket.  If the \a ret_socket
+ * parameter is non-NULL, the accepted socket will be returned in
+ * *ret_socket.  In the latter case, STDIN and STDOUT will be left
+ * unmodified.
+ *
+ * This function does not return if there is an error or if no
+ * connection is established.
+ *
+ * @param[in] ai Addresses to listen on
+ * @param[out] ret_socket If non-NULL receives the accepted socket.
+ *
+ * @see mini_inetd()
  */
-
-void ROKEN_LIB_FUNCTION
-mini_inetd_addrinfo (struct addrinfo *ai)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd_addrinfo (struct addrinfo *ai, rk_socket_t *ret_socket)
 {
     int ret;
     struct addrinfo *a;
     int n, nalloc, i;
-    int *fds;
+    rk_socket_t *fds;
     fd_set orig_read_set, read_set;
-    int max_fd =3D -1;
+    rk_socket_t max_fd =3D (rk_socket_t)-1;
=20
     for (nalloc =3D 0, a =3D ai; a !=3D NULL; a =3D a->ai_next)
 	++nalloc;
=20
     fds =3D malloc (nalloc * sizeof(*fds));
-    if (fds =3D=3D NULL)
+    if (fds =3D=3D NULL) {
 	errx (1, "mini_inetd: out of memory");
+	UNREACHABLE(return);
+    }
=20
     FD_ZERO(&orig_read_set);
=20
     for (i =3D 0, a =3D ai; a !=3D NULL; a =3D a->ai_next) {
 	fds[i] =3D socket (a->ai_family, a->ai_socktype, a->ai_protocol);
-	if (fds[i] < 0) {
-	    warn ("socket af =3D %d", a->ai_family);
+	if (rk_IS_BAD_SOCKET(fds[i]))
+	    continue;
+	socket_set_reuseaddr (fds[i], 1);
+	socket_set_ipv6only(fds[i], 1);
+	if (rk_IS_SOCKET_ERROR(bind (fds[i], a->ai_addr, a->ai_addrlen))) {
+	    warn ("bind af =3D %d", a->ai_family);
+	    rk_closesocket(fds[i]);
+	    fds[i] =3D rk_INVALID_SOCKET;
 	    continue;
 	}
-	socket_set_reuseaddr (fds[i], 1);
-	if (bind (fds[i], a->ai_addr, a->ai_addrlen) < 0) {
-	    warn ("bind af =3D %d", a->ai_family);
-	    close(fds[i]);
+	if (rk_IS_SOCKET_ERROR(listen (fds[i], SOMAXCONN))) {
+	    warn ("listen af =3D %d", a->ai_family);
+	    rk_closesocket(fds[i]);
+	    fds[i] =3D rk_INVALID_SOCKET;
 	    continue;
 	}
-	if (listen (fds[i], SOMAXCONN) < 0) {
-	    warn ("listen af =3D %d", a->ai_family);
-	    close(fds[i]);
-	    continue;
-	}
+#ifndef NO_LIMIT_FD_SETSIZE
 	if (fds[i] >=3D FD_SETSIZE)
 	    errx (1, "fd too large");
+#endif
 	FD_SET(fds[i], &orig_read_set);
 	max_fd =3D max(max_fd, fds[i]);
 	++i;
@@ -112,20 +140,40 @@
 	read_set =3D orig_read_set;
=20
 	ret =3D select (max_fd + 1, &read_set, NULL, NULL, NULL);
-	if (ret < 0 && errno !=3D EINTR)
+	if (rk_IS_SOCKET_ERROR(ret) && rk_SOCK_ERRNO !=3D EINTR)
 	    err (1, "select");
     } while (ret <=3D 0);
=20
     for (i =3D 0; i < n; ++i)
 	if (FD_ISSET (fds[i], &read_set)) {
-	    accept_it (fds[i]);
+	    accept_it (fds[i], ret_socket);
+	    for (i =3D 0; i < n; ++i)
+	      rk_closesocket(fds[i]);
+	    free(fds);
 	    return;
 	}
     abort ();
 }
=20
-void ROKEN_LIB_FUNCTION
-mini_inetd (int port)
+/**
+ * Listen on a specified port
+ *
+ * Listens on the specified port for incoming connections.  If the \a
+ * ret_socket parameter is \a NULL, on return STDIN and STDOUT will be
+ * connected to an accepted socket.  If the \a ret_socket parameter is
+ * non-NULL, the accepted socket will be returned in *ret_socket.  In
+ * the latter case, STDIN and STDOUT will be left unmodified.
+ *
+ * This function does not return if there is an error or if no
+ * connection is established.
+ *
+ * @param[in] port Port to listen on
+ * @param[out] ret_socket If non-NULL receives the accepted socket.
+ *
+ * @see mini_inetd_addrinfo()
+ */
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd(int port, rk_socket_t * ret_socket)
 {
     int error;
     struct addrinfo *ai, hints;
@@ -142,7 +190,8 @@
     if (error)
 	errx (1, "getaddrinfo: %s", gai_strerror (error));
=20
-    mini_inetd_addrinfo(ai);
-   =20
+    mini_inetd_addrinfo(ai, ret_socket);
+
     freeaddrinfo(ai);
 }
+
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/mkstemp.c
--- a/head/crypto/heimdal/lib/roken/mkstemp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/mkstemp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,9 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
=20
 #include <string.h>
 #ifdef HAVE_UNISTD_H
@@ -44,11 +42,11 @@
 #endif
 #include <errno.h>
=20
-RCSID("$Id: mkstemp.c 14773 2005-04-12 11:29:18Z lha $");
+#include <roken.h>
=20
 #ifndef HAVE_MKSTEMP
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 mkstemp(char *template)
 {
     int start, i;
@@ -60,7 +58,7 @@
 	val /=3D 10;
 	start--;
     }
-   =20
+
     do{
 	int fd;
 	fd =3D open(template, O_RDWR | O_CREAT | O_EXCL, 0600);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/ndbm_wra=
p.c
--- a/head/crypto/heimdal/lib/roken/ndbm_wrap.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/ndbm_wrap.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2002 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2002 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,13 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: ndbm_wrap.c 21634 2007-07-17 11:30:36Z lha $");
-#endif
=20
 #include "ndbm_wrap.h"
-#if defined(HAVE_DB4_DB_H)
+#if defined(HAVE_DBHEADER)
+#include <db.h>
+#elif defined(HAVE_DB5_DB_H)
+#include <db5/db.h>
+#elif defined(HAVE_DB4_DB_H)
 #include <db4/db.h>
 #elif defined(HAVE_DB3_DB_H)
 #include <db3/db.h>
@@ -63,7 +64,7 @@
=20
 #define D(X) ((DB*)(X))
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 dbm_close (DBM *db)
 {
 #ifdef HAVE_DB3
@@ -74,7 +75,7 @@
 #endif
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 dbm_delete (DBM *db, datum dkey)
 {
     DBT key;
@@ -92,9 +93,9 @@
     datum dvalue;
     DBT key, value;
     DATUM2DBT(&dkey, &key);
-    if(D(db)->get(D(db),=20
+    if(D(db)->get(D(db),
 #ifdef HAVE_DB3
-	       NULL,=20
+	       NULL,
 #endif
 	       &key, &value, 0) !=3D 0) {
 	dvalue.dptr =3D NULL;
@@ -112,15 +113,16 @@
     DBT key, value;
     datum datum;
 #ifdef HAVE_DB3
-    if(cursor =3D=3D NULL)=20
+    if(cursor =3D=3D NULL)
 	db->cursor(db, NULL, &cursor, 0);
     if(cursor->c_get(cursor, &key, &value, flags) !=3D 0) {
 	datum.dptr =3D NULL;
 	datum.dsize =3D 0;
-    } else=20
+    } else
 	DBT2DATUM(&value, &datum);
 #else
     db->seq(db, &key, &value, flags);
+    DBT2DATUM(&value, &datum);
 #endif
     return datum;
 }
@@ -132,23 +134,25 @@
 #define DB_KEYEXIST	1
 #endif
=20
-datum ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL
 dbm_firstkey (DBM *db)
 {
     return dbm_get(D(db), DB_FIRST);
 }
=20
-datum ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL
 dbm_nextkey (DBM *db)
 {
     return dbm_get(D(db), DB_NEXT);
 }
=20
-DBM* ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION DBM* ROKEN_LIB_CALL
 dbm_open (const char *file, int flags, mode_t mode)
 {
+#ifdef HAVE_DB3
+    int myflags =3D 0;
+#endif
     DB *db;
-    int myflags =3D 0;
     char *fn =3D malloc(strlen(file) + 4);
     if(fn =3D=3D NULL)
 	return NULL;
@@ -187,7 +191,7 @@
     return (DBM*)db;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 dbm_store (DBM *db, datum dkey, datum dvalue, int flags)
 {
     int ret;
@@ -196,10 +200,10 @@
     if((flags & DBM_REPLACE) =3D=3D 0)
 	myflags |=3D DB_NOOVERWRITE;
     DATUM2DBT(&dkey, &key);
-    DATUM2DBT(&dvalue, &value);   =20
-    ret =3D D(db)->put(D(db),=20
+    DATUM2DBT(&dvalue, &value);
+    ret =3D D(db)->put(D(db),
 #ifdef HAVE_DB3
-		     NULL,=20
+		     NULL,
 #endif
 &key, &value, myflags);
     if(ret =3D=3D DB_KEYEXIST)
@@ -207,13 +211,13 @@
     RETURN(ret);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 dbm_error (DBM *db)
 {
     return 0;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 dbm_clearerr (DBM *db)
 {
     return 0;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/ndbm_wra=
p.h
--- a/head/crypto/heimdal/lib/roken/ndbm_wrap.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/ndbm_wrap.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2002 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2002 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: ndbm_wrap.h 14773 2005-04-12 11:29:18Z lha $ */
+/* $Id$ */
=20
 #ifndef __ndbm_wrap_h__
 #define __ndbm_wrap_h__
@@ -41,9 +41,11 @@
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
@@ -78,14 +80,14 @@
 } DBM;
 #endif
=20
-int ROKEN_LIB_FUNCTION dbm_clearerr (DBM*);
-void ROKEN_LIB_FUNCTION dbm_close (DBM*);
-int ROKEN_LIB_FUNCTION dbm_delete (DBM*, datum);
-int ROKEN_LIB_FUNCTION dbm_error (DBM*);
-datum ROKEN_LIB_FUNCTION dbm_fetch (DBM*, datum);
-datum ROKEN_LIB_FUNCTION dbm_firstkey (DBM*);
-datum ROKEN_LIB_FUNCTION dbm_nextkey (DBM*);
-DBM* ROKEN_LIB_FUNCTION dbm_open (const char*, int, mode_t);
-int ROKEN_LIB_FUNCTION dbm_store (DBM*, datum, datum, int);
+ROKEN_LIB_FUNCTION int   ROKEN_LIB_CALL dbm_clearerr (DBM*);
+ROKEN_LIB_FUNCTION void  ROKEN_LIB_CALL dbm_close (DBM*);
+ROKEN_LIB_FUNCTION int   ROKEN_LIB_CALL dbm_delete (DBM*, datum);
+ROKEN_LIB_FUNCTION int   ROKEN_LIB_CALL dbm_error (DBM*);
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL dbm_fetch (DBM*, datum);
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL dbm_firstkey (DBM*);
+ROKEN_LIB_FUNCTION datum ROKEN_LIB_CALL dbm_nextkey (DBM*);
+ROKEN_LIB_FUNCTION DBM*  ROKEN_LIB_CALL dbm_open (const char*, int, mode_t=
);
+ROKEN_LIB_FUNCTION int   ROKEN_LIB_CALL dbm_store (DBM*, datum, datum, int=
);
=20
 #endif /* __ndbm_wrap_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/net_read=
.c
--- a/head/crypto/heimdal/lib/roken/net_read.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/net_read.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: net_read.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-
-#include <sys/types.h>
-#include <unistd.h>
-#include <errno.h>
=20
 #include "roken.h"
=20
@@ -46,19 +39,17 @@
  * Like read but never return partial data.
  */
=20
-ssize_t ROKEN_LIB_FUNCTION
-net_read (int fd, void *buf, size_t nbytes)
+#ifndef _WIN32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_read (rk_socket_t fd, void *buf, size_t nbytes)
 {
     char *cbuf =3D (char *)buf;
     ssize_t count;
     size_t rem =3D nbytes;
=20
     while (rem > 0) {
-#ifdef WIN32
-	count =3D recv (fd, cbuf, rem, 0);
-#else
 	count =3D read (fd, cbuf, rem);
-#endif
 	if (count < 0) {
 	    if (errno =3D=3D EINTR)
 		continue;
@@ -72,3 +63,56 @@
     }
     return nbytes;
 }
+
+#else
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_read(rk_socket_t sock, void *buf, size_t nbytes)
+{
+    char *cbuf =3D (char *)buf;
+    ssize_t count;
+    size_t rem =3D nbytes;
+
+#ifdef SOCKET_IS_NOT_AN_FD
+    int use_read =3D 0;
+#endif
+
+    while (rem > 0) {
+#ifdef SOCKET_IS_NOT_AN_FD
+	if (use_read)
+	    count =3D _read (sock, cbuf, rem);
+	else
+	    count =3D recv (sock, cbuf, rem, 0);
+
+	if (use_read =3D=3D 0 &&
+	    rk_IS_SOCKET_ERROR(count) &&
+            (rk_SOCK_ERRNO =3D=3D WSANOTINITIALISED ||
+             rk_SOCK_ERRNO =3D=3D WSAENOTSOCK)) {
+	    use_read =3D 1;
+
+	    count =3D _read (sock, cbuf, rem);
+	}
+#else
+	count =3D recv (sock, cbuf, rem, 0);
+#endif
+	if (count < 0) {
+
+	    /* With WinSock, the error EINTR (WSAEINTR), is used to
+	       indicate that a blocking call was cancelled using
+	       WSACancelBlockingCall(). */
+
+#ifndef HAVE_WINSOCK
+	    if (rk_SOCK_ERRNO =3D=3D EINTR)
+		continue;
+#endif
+	    return count;
+	} else if (count =3D=3D 0) {
+	    return count;
+	}
+	cbuf +=3D count;
+	rem -=3D count;
+    }
+    return nbytes;
+}
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/net_writ=
e.c
--- a/head/crypto/heimdal/lib/roken/net_write.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/net_write.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: net_write.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-
-#include <sys/types.h>
-#include <unistd.h>
-#include <errno.h>
=20
 #include "roken.h"
=20
@@ -46,18 +39,58 @@
  * Like write but never return partial data.
  */
=20
-ssize_t ROKEN_LIB_FUNCTION
-net_write (int fd, const void *buf, size_t nbytes)
+#ifndef _WIN32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_write (rk_socket_t fd, const void *buf, size_t nbytes)
 {
     const char *cbuf =3D (const char *)buf;
     ssize_t count;
     size_t rem =3D nbytes;
=20
     while (rem > 0) {
-#ifdef WIN32
-	count =3D send (fd, cbuf, rem, 0);
+	count =3D write (fd, cbuf, rem);
+	if (count < 0) {
+	    if (errno =3D=3D EINTR)
+		continue;
+	    else
+		return count;
+	}
+	cbuf +=3D count;
+	rem -=3D count;
+    }
+    return nbytes;
+}
+
 #else
-	count =3D write (fd, cbuf, rem);
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+net_write(rk_socket_t sock, const void *buf, size_t nbytes)
+{
+    const char *cbuf =3D (const char *)buf;
+    ssize_t count;
+    size_t rem =3D nbytes;
+#ifdef SOCKET_IS_NOT_AN_FD
+    int use_write =3D 0;
+#endif
+
+    while (rem > 0) {
+#ifdef SOCKET_IS_NOT_AN_FD
+	if (use_write)
+	    count =3D _write (sock, cbuf, rem);
+	else
+	    count =3D send (sock, cbuf, rem, 0);
+
+	if (use_write =3D=3D 0 &&
+	    rk_IS_SOCKET_ERROR(count) &&
+	    (rk_SOCK_ERRNO =3D=3D WSANOTINITIALISED ||
+             rk_SOCK_ERRNO =3D=3D WSAENOTSOCK)) {
+	    use_write =3D 1;
+
+	    count =3D _write (sock, cbuf, rem);
+	}
+#else
+	count =3D send (sock, cbuf, rem, 0);
 #endif
 	if (count < 0) {
 	    if (errno =3D=3D EINTR)
@@ -70,3 +103,5 @@
     }
     return nbytes;
 }
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_by=
tes-test.c
--- a/head/crypto/heimdal/lib/roken/parse_bytes-test.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/roken/parse_bytes-test.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: parse_bytes-test.c 10655 2001-09-04 09:56:00Z assar $");
-#endif
=20
 #include "roken.h"
 #include "parse_bytes.h"
@@ -82,7 +79,7 @@
 			tests[i].val, buf, tests[i].str);
 		++ret;
 	    }
-	}   =20
+	}
     }
     if (ret) {
 	printf ("%d errors\n", ret);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_by=
tes.c
--- a/head/crypto/heimdal/lib/roken/parse_bytes.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/parse_bytes.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: parse_bytes.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <parse_units.h>
 #include "parse_bytes.h"
@@ -59,19 +56,19 @@
     { NULL, 0 }
 };
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_bytes (const char *s, const char *def_unit)
 {
     return parse_units (s, bytes_units, def_unit);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_bytes (int t, char *s, size_t len)
 {
     return unparse_units (t, bytes_units, s, len);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_bytes_short (int t, char *s, size_t len)
 {
     return unparse_units_approx (t, bytes_short_units, s, len);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_by=
tes.h
--- a/head/crypto/heimdal/lib/roken/parse_bytes.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/parse_bytes.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,56 +1,58 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: parse_bytes.h 14787 2005-04-13 13:19:07Z lha $ */
+/* $Id$ */
=20
 #ifndef __PARSE_BYTES_H__
 #define __PARSE_BYTES_H__
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_bytes (const char *s, const char *def_unit);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_bytes (int t, char *s, size_t len);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_bytes_short (int t, char *s, size_t len);
=20
 #endif /* __PARSE_BYTES_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_re=
ply-test.c
--- a/head/crypto/heimdal/lib/roken/parse_reply-test.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/crypto/heimdal/lib/roken/parse_reply-test.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: parse_reply-test.c 15287 2005-05-29 21:21:12Z lha $");
-#endif
=20
 #include <sys/types.h>
 #ifdef HAVE_SYS_MMAN_H
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_ti=
me-test.c
--- a/head/crypto/heimdal/lib/roken/parse_time-test.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/roken/parse_time-test.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: parse_time-test.c 15028 2005-04-30 14:48:29Z lha $");
-#endif
=20
 #include "roken.h"
 #include "parse_time.h"
@@ -43,8 +40,8 @@
=20
 static struct testcase {
     size_t size;
-    time_t val;
-    char *str;
+    int    val;
+    char  *str;
 } tests[] =3D {
     { 8, 1,		"1 second" },
     { 17, 61,		"1 minute 1 second" },
@@ -69,7 +66,7 @@
 	if  (sz !=3D tests[i].size)
 	    errx(1, "sz (%lu) !=3D tests[%d].size (%lu)",
 		 (unsigned long)sz, i, (unsigned long)tests[i].size);
-=09
+
 	for (buf_sz =3D 0; buf_sz < tests[i].size + 2; buf_sz++) {
=20
 	    buf =3D rk_test_mem_alloc(RK_TM_OVERRUN, "overrun",
@@ -77,7 +74,7 @@
 	    sz =3D unparse_time(tests[i].val, buf, buf_sz);
 	    if (sz !=3D tests[i].size)
 		errx(1, "sz (%lu) !=3D tests[%d].size (%lu) with in size %lu",
-		     (unsigned long)sz, i,=20
+		     (unsigned long)sz, i,
 		     (unsigned long)tests[i].size,
 		     (unsigned long)buf_sz);
 	    if (buf_sz > 0 && memcmp(buf, tests[i].str, buf_sz - 1) !=3D 0)
@@ -86,20 +83,21 @@
 		errx(1, "test %i not zero terminated", i);
 	    rk_test_mem_free("overrun");
=20
-	    buf =3D rk_test_mem_alloc(RK_TM_UNDERRUN, "underrun",=20
+	    buf =3D rk_test_mem_alloc(RK_TM_UNDERRUN, "underrun",
 				    NULL, tests[i].size);
-	    sz =3D unparse_time(tests[i].val, buf, buf_sz);
+	    sz =3D unparse_time(tests[i].val, buf, min(buf_sz, tests[i].size));
 	    if (sz !=3D tests[i].size)
 		errx(1, "sz (%lu) !=3D tests[%d].size (%lu) with insize %lu",
 		     (unsigned long)sz, i,
 		     (unsigned long)tests[i].size,
 		     (unsigned long)buf_sz);
-	    if (buf_sz > 0 && strncmp(buf, tests[i].str, buf_sz - 1) !=3D 0)
+	    if (buf_sz > 0 && strncmp(buf, tests[i].str, min(buf_sz, tests[i].siz=
e) - 1) !=3D 0)
 		errx(1, "test %i wrong result %s vs %s", i, buf, tests[i].str);
-	    if (buf_sz > 0 && buf[buf_sz - 1] !=3D '\0')
+	    if (buf_sz > 0 && buf[min(buf_sz, tests[i].size) - 1] !=3D '\0')
 		errx(1, "test %i not zero terminated", i);
 	    rk_test_mem_free("underrun");
 	}
+
 	buf =3D rk_test_mem_alloc(RK_TM_OVERRUN, "overrun",
 				tests[i].str, tests[i].size + 1);
 	j =3D parse_time(buf, "s");
@@ -113,6 +111,7 @@
 	if (j !=3D tests[i].val)
 	    errx(1, "parse_time failed for test %d", i);
 	rk_test_mem_free("underrun");
+
     }
     return 0;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_ti=
me.3
--- a/head/crypto/heimdal/lib/roken/parse_time.3	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/parse_time.3	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,34 +1,34 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\" $Id: parse_time.3 14325 2004-10-30 22:34:28Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\" $Id$
 .\"
 .Dd October 31, 2004
 .Dt PARSE_TIME 3
@@ -52,13 +52,13 @@
 .Ft size_t
 .Fn unparse_time_approx "int seconds" "char *buf" "size_t len"
 .Sh DESCRIPTION
-The=20
+The
 .Fn parse_time
 function converts a the period of time specified in
 into a number of seconds.
-The=20
+The
 .Fa timespec
-can be any number of=20
+can be any number of
 .Aq number unit
 pairs separated by comma and whitespace. The number can be
 negative. Number without explicit units are taken as being
@@ -68,12 +68,12 @@
 .Fn unparse_time
 and
 .Fn unparse_time_approx
-does the opposite of=20
+does the opposite of
 .Fn parse_time ,
 that is they take a number of seconds and express that as human
-readable string.=20
+readable string.
 .Fa unparse_time
-produces an exact time, while=20
+produces an exact time, while
 .Fa unparse_time_approx
 restricts the result to only include one units.
 .Pp
@@ -99,13 +99,13 @@
 unique).
 .Sh RETURN VALUES
 .Fn parse_time
-returns the number of seconds that represents the expression in=20
+returns the number of seconds that represents the expression in
 .Fa timespec
 or -1 on error.
 .Fn unparse_time
-and=20
-.Fn unparse_time_approx=20
-return the number of characters written to=20
+and
+.Fn unparse_time_approx
+return the number of characters written to
 .Fa buf .
 if the return value is greater than or equal to the
 .Fa len
@@ -140,7 +140,7 @@
 }
 .Ed
 .Bd -literal
-$ ./a.out "1 minute 30 seconds" "90 s" "1 y -1 s"    =20
+$ ./a.out "1 minute 30 seconds" "90 s" "1 y -1 s"
 1   year =3D 365 days
 1  month =3D 30 days
 1   week =3D 7 days
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_ti=
me.c
--- a/head/crypto/heimdal/lib/roken/parse_time.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/parse_time.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1997, 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: parse_time.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <parse_units.h>
 #include "parse_time.h"
@@ -53,25 +50,25 @@
     {NULL, 0},
 };
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_time (const char *s, const char *def_unit)
 {
     return parse_units (s, time_units, def_unit);
 }
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 unparse_time (int t, char *s, size_t len)
 {
     return unparse_units (t, time_units, s, len);
 }
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 unparse_time_approx (int t, char *s, size_t len)
 {
     return unparse_units_approx (t, time_units, s, len);
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 print_time_table (FILE *f)
 {
     print_units_table (time_units, f);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_ti=
me.h
--- a/head/crypto/heimdal/lib/roken/parse_time.h	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/parse_time.h	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,59 +1,61 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: parse_time.h 14773 2005-04-12 11:29:18Z lha $ */
+/* $Id$ */
=20
 #ifndef __PARSE_TIME_H__
 #define __PARSE_TIME_H__
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
-int
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_time (const char *s, const char *def_unit);
=20
-size_t
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 unparse_time (int t, char *s, size_t len);
=20
-size_t
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 unparse_time_approx (int t, char *s, size_t len);
=20
-void
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 print_time_table (FILE *f);
=20
 #endif /* __PARSE_TIME_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_un=
its.c
--- a/head/crypto/heimdal/lib/roken/parse_units.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/parse_units.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: parse_units.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <ctype.h>
@@ -73,7 +70,7 @@
=20
     p =3D s;
     while (*p) {
-	double val;
+	int val;
 	char *next;
 	const struct units *u, *partial_unit;
 	size_t u_len;
@@ -83,7 +80,7 @@
 	while(isspace((unsigned char)*p) || *p =3D=3D ',')
 	    ++p;
=20
-	val =3D strtod (p, &next); /* strtol(p, &next, 0); */
+	val =3D strtol(p, &next, 0);
 	if (p =3D=3D next) {
 	    val =3D 0;
 	    if(!accept_no_val_p)
@@ -152,7 +149,7 @@
     return res + val * mult;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_units (const char *s, const struct units *units,
 	     const char *def_unit)
 {
@@ -178,7 +175,7 @@
 	return -1;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_flags (const char *s, const struct units *units,
 	     int orig)
 {
@@ -211,7 +208,7 @@
 	    tmp =3D (*print) (s, len, divisor, u->name, num);
 	    if (tmp < 0)
 		return tmp;
-	    if (tmp > len) {
+	    if (tmp > (int) len) {
 		len =3D 0;
 		s =3D NULL;
 	    } else {
@@ -248,7 +245,7 @@
 	return update_unit (in, mult);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_units (int num, const struct units *units, char *s, size_t len)
 {
     return unparse_something (num, units, s, len,
@@ -257,7 +254,7 @@
 			      "0");
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_units_approx (int num, const struct units *units, char *s, size_t =
len)
 {
     return unparse_something (num, units, s, len,
@@ -266,11 +263,11 @@
 			      "0");
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 print_units_table (const struct units *units, FILE *f)
 {
     const struct units *u, *u2;
-    unsigned max_sz =3D 0;
+    size_t max_sz =3D 0;
=20
     for (u =3D units; u->name; ++u) {
 	max_sz =3D max(max_sz, strlen(u->name));
@@ -291,7 +288,7 @@
 	    if (u2->name =3D=3D NULL)
 		--u2;
 	    unparse_units (u->mult, u2, buf, sizeof(buf));
-	    fprintf (f, "1 %*s =3D %s\n", max_sz, u->name, buf);
+	    fprintf (f, "1 %*s =3D %s\n", (int)max_sz, u->name, buf);
 	} else {
 	    fprintf (f, "1 %s\n", u->name);
 	}
@@ -311,7 +308,7 @@
     return in - mult;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_flags (int num, const struct units *units, char *s, size_t len)
 {
     return unparse_something (num, units, s, len,
@@ -320,7 +317,7 @@
 			      "");
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 print_flags_table (const struct units *units, FILE *f)
 {
     const struct units *u;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/parse_un=
its.h
--- a/head/crypto/heimdal/lib/roken/parse_units.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/parse_units.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 1997 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: parse_units.h 14773 2005-04-12 11:29:18Z lha $ */
+/* $Id$ */
=20
 #ifndef __PARSE_UNITS_H__
 #define __PARSE_UNITS_H__
@@ -41,9 +41,11 @@
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
@@ -52,28 +54,28 @@
     unsigned mult;
 };
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_units (const char *s, const struct units *units,
 	     const char *def_unit);
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 print_units_table (const struct units *units, FILE *f);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 parse_flags (const char *s, const struct units *units,
 	     int orig);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_units (int num, const struct units *units, char *s, size_t len);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_units_approx (int num, const struct units *units, char *s,
 		      size_t len);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unparse_flags (int num, const struct units *units, char *s, size_t len);
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 print_flags_table (const struct units *units, FILE *f);
=20
 #endif /* __PARSE_UNITS_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/putenv.c
--- a/head/crypto/heimdal/lib/roken/putenv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/putenv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,13 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: putenv.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <stdlib.h>
=20
+#if !HAVE_DECL_ENVIRON
 extern char **environ;
+#endif
=20
 /*
  * putenv --
@@ -48,13 +47,13 @@
  *      value by altering an existing variable or creating a new one.
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 putenv(const char *string)
 {
     int i;
     const char *eq =3D (const char *)strchr(string, '=3D');
     int len;
-   =20
+
     if (eq =3D=3D NULL)
 	return 1;
     len =3D eq - string;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/rcmd.c
--- a/head/crypto/heimdal/lib/roken/rcmd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/rcmd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,15 +31,12 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: rcmd.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
 #include <stdio.h>
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rcmd(char **ahost,
      unsigned short inport,
      const char *locuser,
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/readv.c
--- a/head/crypto/heimdal/lib/roken/readv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/readv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: readv.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 readv(int d, const struct iovec *iov, int iovcnt)
 {
     ssize_t ret, nb;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/realloc.c
--- a/head/crypto/heimdal/lib/roken/realloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/realloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,13 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
 #undef realloc
-#endif
+
 #include <stdlib.h>
 #include "roken.h"
=20
-RCSID("$Id");
-
-
-void * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
 rk_realloc(void *ptr, size_t size)
 {
     if (ptr =3D=3D NULL)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/recvmsg.c
--- a/head/crypto/heimdal/lib/roken/recvmsg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/recvmsg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: recvmsg.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 recvmsg(int s, struct msghdr *msg, int flags)
 {
     ssize_t ret, nb;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/resolve-=
test.c
--- a/head/crypto/heimdal/lib/roken/resolve-test.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/roken/resolve-test.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,9 +31,9 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-#endif
+
 #include "roken.h"
 #include "getarg.h"
 #ifdef HAVE_ARPA_NAMESER_H
@@ -44,12 +44,13 @@
 #endif
 #include "resolve.h"
=20
-RCSID("$Id: resolve-test.c 15415 2005-06-16 16:58:45Z lha $");
-
+static int loop_integer =3D 1;
 static int version_flag =3D 0;
 static int help_flag	=3D 0;
=20
 static struct getargs args[] =3D {
+    {"loop",	0,	arg_integer,	&loop_integer,
+     "loop resolving", NULL },
     {"version",	0,	arg_flag,	&version_flag,
      "print version", NULL },
     {"help",	0,	arg_flag,	&help_flag,
@@ -69,15 +70,15 @@
 int
 main(int argc, char **argv)
 {
-    struct dns_reply *r;
-    struct resource_record *rr;
-    int optidx =3D 0;
+    struct rk_dns_reply *r;
+    struct rk_resource_record *rr;
+    int optidx =3D 0, i, exit_code =3D 0;
=20
     setprogname (argv[0]);
=20
     if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
 	usage(1);
-   =20
+
     if (help_flag)
 	usage (0);
=20
@@ -92,88 +93,93 @@
     if (argc !=3D 2)
 	usage(1);
=20
-    r =3D dns_lookup(argv[0], argv[1]);
-    if(r =3D=3D NULL){
-	printf("No reply.\n");
-	return 1;
-    }
-    if(r->q.type =3D=3D rk_ns_t_srv)
-	dns_srv_order(r);
+    for (i =3D 0; i < loop_integer; i++) {
=20
-    for(rr =3D r->head; rr;rr=3Drr->next){
-	printf("%-30s %-5s %-6d ", rr->domain, dns_type_to_string(rr->type), rr->=
ttl);
-	switch(rr->type){
-	case rk_ns_t_ns:
-	case rk_ns_t_cname:
-	case rk_ns_t_ptr:
-	    printf("%s\n", (char*)rr->u.data);
-	    break;
-	case rk_ns_t_a:
-	    printf("%s\n", inet_ntoa(*rr->u.a));
-	    break;
-	case rk_ns_t_mx:
-	case rk_ns_t_afsdb:{
-	    printf("%d %s\n", rr->u.mx->preference, rr->u.mx->domain);
+	r =3D rk_dns_lookup(argv[0], argv[1]);
+	if(r =3D=3D NULL){
+	    printf("No reply.\n");
+	    exit_code =3D 1;
 	    break;
 	}
-	case rk_ns_t_srv:{
-	    struct srv_record *srv =3D rr->u.srv;
-	    printf("%d %d %d %s\n", srv->priority, srv->weight,=20
-		   srv->port, srv->target);
-	    break;
+	if(r->q.type =3D=3D rk_ns_t_srv)
+	    rk_dns_srv_order(r);
+
+	for(rr =3D r->head; rr;rr=3Drr->next){
+	    printf("%-30s %-5s %-6d ", rr->domain, rk_dns_type_to_string(rr->type=
), rr->ttl);
+	    switch(rr->type){
+	    case rk_ns_t_ns:
+	    case rk_ns_t_cname:
+	    case rk_ns_t_ptr:
+		printf("%s\n", (char*)rr->u.data);
+		break;
+	    case rk_ns_t_a:
+		printf("%s\n", inet_ntoa(*rr->u.a));
+		break;
+	    case rk_ns_t_mx:
+	    case rk_ns_t_afsdb:{
+		printf("%d %s\n", rr->u.mx->preference, rr->u.mx->domain);
+		break;
+	    }
+	    case rk_ns_t_srv:{
+		struct rk_srv_record *srv =3D rr->u.srv;
+		printf("%d %d %d %s\n", srv->priority, srv->weight,
+		       srv->port, srv->target);
+		break;
+	    }
+	    case rk_ns_t_txt: {
+		printf("%s\n", rr->u.txt);
+		break;
+	    }
+	    case rk_ns_t_sig : {
+		struct rk_sig_record *sig =3D rr->u.sig;
+		const char *type_string =3D rk_dns_type_to_string (sig->type);
+
+		printf ("type %u (%s), algorithm %u, labels %u, orig_ttl %u, sig_expirat=
ion %u, sig_inception %u, key_tag %u, signer %s\n",
+			sig->type, type_string ? type_string : "",
+			sig->algorithm, sig->labels, sig->orig_ttl,
+			sig->sig_expiration, sig->sig_inception, sig->key_tag,
+			sig->signer);
+		break;
+	    }
+	    case rk_ns_t_key : {
+		struct rk_key_record *key =3D rr->u.key;
+
+		printf ("flags %u, protocol %u, algorithm %u\n",
+			key->flags, key->protocol, key->algorithm);
+		break;
+	    }
+	    case rk_ns_t_sshfp : {
+		struct rk_sshfp_record *sshfp =3D rr->u.sshfp;
+		size_t i;
+
+		printf ("alg %u type %u length %lu data ", sshfp->algorithm,
+			sshfp->type,  (unsigned long)sshfp->sshfp_len);
+		for (i =3D 0; i < sshfp->sshfp_len; i++)
+		    printf("%02X", sshfp->sshfp_data[i]);
+		printf("\n");
+
+		break;
+	    }
+	    case rk_ns_t_ds : {
+		struct rk_ds_record *ds =3D rr->u.ds;
+		size_t i;
+
+		printf ("key tag %u alg %u type %u length %lu data ",
+			ds->key_tag, ds->algorithm, ds->digest_type,
+			(unsigned long)ds->digest_len);
+		for (i =3D 0; i < ds->digest_len; i++)
+		    printf("%02X", ds->digest_data[i]);
+		printf("\n");
+
+		break;
+	    }
+	    default:
+		printf("\n");
+		break;
+	    }
 	}
-	case rk_ns_t_txt: {
-	    printf("%s\n", rr->u.txt);
-	    break;
-	}
-	case rk_ns_t_sig : {
-	    struct sig_record *sig =3D rr->u.sig;
-	    const char *type_string =3D dns_type_to_string (sig->type);
+	rk_dns_free_data(r);
+    }
=20
-	    printf ("type %u (%s), algorithm %u, labels %u, orig_ttl %u, sig_expi=
ration %u, sig_inception %u, key_tag %u, signer %s\n",
-		    sig->type, type_string ? type_string : "",
-		    sig->algorithm, sig->labels, sig->orig_ttl,
-		    sig->sig_expiration, sig->sig_inception, sig->key_tag,
-		    sig->signer);
-	    break;
-	}
-	case rk_ns_t_key : {
-	    struct key_record *key =3D rr->u.key;
-
-	    printf ("flags %u, protocol %u, algorithm %u\n",
-		    key->flags, key->protocol, key->algorithm);
-	    break;
-	}
-	case rk_ns_t_sshfp : {
-	    struct sshfp_record *sshfp =3D rr->u.sshfp;
-	    int i;
-
-	    printf ("alg %u type %u length %lu data ", sshfp->algorithm,=20
-		    sshfp->type,  (unsigned long)sshfp->sshfp_len);
-	    for (i =3D 0; i < sshfp->sshfp_len; i++)
-		printf("%02X", sshfp->sshfp_data[i]);
-	    printf("\n");
-
-	    break;
-	}
-	case rk_ns_t_ds : {
-	    struct ds_record *ds =3D rr->u.ds;
-	    int i;
-
-	    printf ("key tag %u alg %u type %u length %u data ",
-		    ds->key_tag, ds->algorithm, ds->digest_type,=20
-		    ds->digest_len);
-	    for (i =3D 0; i < ds->digest_len; i++)
-		printf("%02X", ds->digest_data[i]);
-	    printf("\n");
-
-	    break;
-	}
-	default:
-	    printf("\n");
-	    break;
-	}
-    }
-   =20
-    return 0;
+    return exit_code;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/resolve.c
--- a/head/crypto/heimdal/lib/roken/resolve.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/resolve.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2006 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2006 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,9 +31,9 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-#endif
+
 #include "roken.h"
 #ifdef HAVE_ARPA_NAMESER_H
 #include <arpa/nameser.h>
@@ -41,12 +41,13 @@
 #ifdef HAVE_RESOLV_H
 #include <resolv.h>
 #endif
+#ifdef HAVE_DNS_H
+#include <dns.h>
+#endif
 #include "resolve.h"
=20
 #include <assert.h>
=20
-RCSID("$Id: resolve.c 19869 2007-01-12 16:03:14Z lha $");
-
 #ifdef _AIX /* AIX have broken res_nsearch() in 5.1 (5.0 also ?) */
 #undef HAVE_RES_NSEARCH
 #endif
@@ -77,8 +78,8 @@
=20
 int _resolve_debug =3D 0;
=20
-int ROKEN_LIB_FUNCTION
-dns_string_to_type(const char *name)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_dns_string_to_type(const char *name)
 {
     struct stot *p =3D stot;
     for(p =3D stot; p->name; p++)
@@ -87,8 +88,8 @@
     return -1;
 }
=20
-const char * ROKEN_LIB_FUNCTION
-dns_type_to_string(int type)
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+rk_dns_type_to_string(int type)
 {
     struct stot *p =3D stot;
     for(p =3D stot; p->name; p++)
@@ -97,10 +98,10 @@
     return NULL;
 }
=20
-#if (defined(HAVE_RES_SEARCH) || defined(HAVE_RES_NSEARCH)) && defined(HAV=
E_DN_EXPAND)
+#if ((defined(HAVE_RES_SEARCH) || defined(HAVE_RES_NSEARCH)) && defined(HA=
VE_DN_EXPAND)) || defined(HAVE_WINDNS)
=20
 static void
-dns_free_rr(struct resource_record *rr)
+dns_free_rr(struct rk_resource_record *rr)
 {
     if(rr->domain)
 	free(rr->domain);
@@ -109,26 +110,29 @@
     free(rr);
 }
=20
-void ROKEN_LIB_FUNCTION
-dns_free_data(struct dns_reply *r)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_free_data(struct rk_dns_reply *r)
 {
-    struct resource_record *rr;
+    struct rk_resource_record *rr;
     if(r->q.domain)
 	free(r->q.domain);
     for(rr =3D r->head; rr;){
-	struct resource_record *tmp =3D rr;
+	struct rk_resource_record *tmp =3D rr;
 	rr =3D rr->next;
 	dns_free_rr(tmp);
     }
     free (r);
 }
=20
+#ifndef HAVE_WINDNS
+
 static int
-parse_record(const unsigned char *data, const unsigned char *end_data,=20
-	     const unsigned char **pp, struct resource_record **ret_rr)
+parse_record(const unsigned char *data, const unsigned char *end_data,
+	     const unsigned char **pp, struct rk_resource_record **ret_rr)
 {
-    struct resource_record *rr;
-    int type, class, ttl, size;
+    struct rk_resource_record *rr;
+    int type, class, ttl;
+    unsigned size;
     int status;
     char host[MAXDNAME];
     const unsigned char *p =3D *pp;
@@ -136,7 +140,7 @@
     *ret_rr =3D NULL;
=20
     status =3D dn_expand(data, end_data, p, host, sizeof(host));
-    if(status < 0)=20
+    if(status < 0)
 	return -1;
     if (p + status + 10 > end_data)
 	return -1;
@@ -155,7 +159,7 @@
 	return -1;
=20
     rr =3D calloc(1, sizeof(*rr));
-    if(rr =3D=3D NULL)=20
+    if(rr =3D=3D NULL)
 	return -1;
     rr->domain =3D strdup(host);
     if(rr->domain =3D=3D NULL) {
@@ -190,13 +194,13 @@
 	    dns_free_rr(rr);
 	    return -1;
 	}
-	if (status + 2 > size) {
+	if ((size_t)status + 2 > size) {
 	    dns_free_rr(rr);
 	    return -1;
 	}
=20
 	hostlen =3D strlen(host);
-	rr->u.mx =3D (struct mx_record*)malloc(sizeof(struct mx_record) +=20
+	rr->u.mx =3D (struct mx_record*)malloc(sizeof(struct mx_record) +
 						hostlen);
 	if(rr->u.mx =3D=3D NULL) {
 	    dns_free_rr(rr);
@@ -213,14 +217,14 @@
 	    dns_free_rr(rr);
 	    return -1;
 	}
-	if (status + 6 > size) {
+	if ((size_t)status + 6 > size) {
 	    dns_free_rr(rr);
 	    return -1;
 	}
=20
 	hostlen =3D strlen(host);
-	rr->u.srv =3D=20
-	    (struct srv_record*)malloc(sizeof(struct srv_record) +=20
+	rr->u.srv =3D
+	    (struct srv_record*)malloc(sizeof(struct srv_record) +
 				       hostlen);
 	if(rr->u.srv =3D=3D NULL) {
 	    dns_free_rr(rr);
@@ -233,7 +237,7 @@
 	break;
     }
     case rk_ns_t_txt:{
-	if(size =3D=3D 0 || size < *p + 1) {
+	if(size =3D=3D 0 || size < (unsigned)(*p + 1)) {
 	    dns_free_rr(rr);
 	    return -1;
 	}
@@ -280,7 +284,7 @@
 	    dns_free_rr(rr);
 	    return -1;
 	}
-	if (status + 18 > size) {
+	if ((size_t)status + 18 > size) {
 	    dns_free_rr(rr);
 	    return -1;
 	}
@@ -400,17 +404,17 @@
 #ifndef TEST_RESOLVE
 static
 #endif
-struct dns_reply*
+struct rk_dns_reply*
 parse_reply(const unsigned char *data, size_t len)
 {
     const unsigned char *p;
     int status;
-    int i;
+    size_t i;
     char host[MAXDNAME];
     const unsigned char *end_data =3D data + len;
-    struct dns_reply *r;
-    struct resource_record **rr;
-   =20
+    struct rk_dns_reply *r;
+    struct rk_resource_record **rr;
+
     r =3D calloc(1, sizeof(*r));
     if (r =3D=3D NULL)
 	return NULL;
@@ -448,16 +452,16 @@
     }
     status =3D dn_expand(data, end_data, p, host, sizeof(host));
     if(status < 0){
-	dns_free_data(r);
+	rk_dns_free_data(r);
 	return NULL;
     }
     r->q.domain =3D strdup(host);
     if(r->q.domain =3D=3D NULL) {
-	dns_free_data(r);
+	rk_dns_free_data(r);
 	return NULL;
     }
     if (p + status + 4 > end_data) {
-	dns_free_data(r);
+	rk_dns_free_data(r);
 	return NULL;
     }
     p +=3D status;
@@ -465,25 +469,25 @@
     p +=3D 2;
     r->q.class =3D (p[0] << 8 | p[1]);
     p +=3D 2;
-   =20
+
     rr =3D &r->head;
     for(i =3D 0; i < r->h.ancount; i++) {
 	if(parse_record(data, end_data, &p, rr) !=3D 0) {
-	    dns_free_data(r);
+	    rk_dns_free_data(r);
 	    return NULL;
 	}
 	rr =3D &(*rr)->next;
     }
     for(i =3D 0; i < r->h.nscount; i++) {
 	if(parse_record(data, end_data, &p, rr) !=3D 0) {
-	    dns_free_data(r);
+	    rk_dns_free_data(r);
 	    return NULL;
 	}
 	rr =3D &(*rr)->next;
     }
     for(i =3D 0; i < r->h.arcount; i++) {
 	if(parse_record(data, end_data, &p, rr) !=3D 0) {
-	    dns_free_data(r);
+	    rk_dns_free_data(r);
 	    return NULL;
 	}
 	rr =3D &(*rr)->next;
@@ -500,121 +504,135 @@
 #endif
 #endif
=20
-static struct dns_reply *
+#if defined(HAVE_DNS_SEARCH)
+#define resolve_search(h,n,c,t,r,l) \
+    	((int)dns_search(h,n,c,t,r,l,(struct sockaddr *)&from,&fromsize))
+#define resolve_free_handle(h) dns_free(h)
+#elif defined(HAVE_RES_NSEARCH)
+#define resolve_search(h,n,c,t,r,l) res_nsearch(h,n,c,t,r,l)
+#define resolve_free_handle(h) rk_res_free(h);
+#else
+#define resolve_search(h,n,c,t,r,l) res_search(n,c,t,r,l)
+#define handle 0
+#define resolve_free_handle(h)
+#endif
+
+
+static struct rk_dns_reply *
 dns_lookup_int(const char *domain, int rr_class, int rr_type)
 {
-    struct dns_reply *r;
-    unsigned char *reply =3D NULL;
-    int size;
-    int len;
-#ifdef HAVE_RES_NSEARCH
+    struct rk_dns_reply *r;
+    void *reply =3D NULL;
+    int size, len;
+#if defined(HAVE_DNS_SEARCH)
+    struct sockaddr_storage from;
+    uint32_t fromsize =3D sizeof(from);
+    dns_handle_t handle;
+
+    handle =3D dns_open(NULL);
+    if (handle =3D=3D NULL)
+	return NULL;
+#elif defined(HAVE_RES_NSEARCH)
     struct __res_state state;
+    struct __res_state *handle =3D &state;
+
     memset(&state, 0, sizeof(state));
-    if(res_ninit(&state))
+    if(res_ninit(handle))
 	return NULL; /* is this the best we can do? */
-#elif defined(HAVE__RES)
-    u_long old_options =3D 0;
 #endif
-   =20
-    size =3D 0;
-    len =3D 1000;
-    do {
+
+    len =3D 1500;
+    while(1) {
 	if (reply) {
 	    free(reply);
 	    reply =3D NULL;
 	}
-	if (size <=3D len)
-	    size =3D len;
 	if (_resolve_debug) {
-#ifdef HAVE_RES_NSEARCH
+#if defined(HAVE_DNS_SEARCH)
+	    dns_set_debug(handle, 1);
+#elif defined(HAVE_RES_NSEARCH)
 	    state.options |=3D RES_DEBUG;
-#elif defined(HAVE__RES)
-	    old_options =3D _res.options;
-	    _res.options |=3D RES_DEBUG;
 #endif
 	    fprintf(stderr, "dns_lookup(%s, %d, %s), buffer size %d\n", domain,
-		    rr_class, dns_type_to_string(rr_type), size);
+		    rr_class, rk_dns_type_to_string(rr_type), len);
 	}
-	reply =3D malloc(size);
+	reply =3D malloc(len);
 	if (reply =3D=3D NULL) {
-#ifdef HAVE_RES_NSEARCH
-	    rk_res_free(&state);
-#endif
+	    resolve_free_handle(handle);
 	    return NULL;
 	}
-#ifdef HAVE_RES_NSEARCH
-	len =3D res_nsearch(&state, domain, rr_class, rr_type, reply, size);
-#else
-	len =3D res_search(domain, rr_class, rr_type, reply, size);
-#endif
+
+	size =3D resolve_search(handle, domain, rr_class, rr_type, reply, len);
+
 	if (_resolve_debug) {
-#if defined(HAVE__RES) && !defined(HAVE_RES_NSEARCH)
-	    _res.options =3D old_options;
-#endif
 	    fprintf(stderr, "dns_lookup(%s, %d, %s) --> %d\n",
-		    domain, rr_class, dns_type_to_string(rr_type), len);
+		    domain, rr_class, rk_dns_type_to_string(rr_type), size);
 	}
-	if (len < 0) {
-#ifdef HAVE_RES_NSEARCH
-	    rk_res_free(&state);
-#endif
+	if (size > len) {
+	    /* resolver thinks it know better, go for it */
+	    len =3D size;
+	} else if (size > 0) {
+	    /* got a good reply */
+	    break;
+	} else if (size <=3D 0 && len < rk_DNS_MAX_PACKET_SIZE) {
+	    len *=3D 2;
+	    if (len > rk_DNS_MAX_PACKET_SIZE)
+		len =3D rk_DNS_MAX_PACKET_SIZE;
+	} else {
+	    /* the end, leave */
+	    resolve_free_handle(handle);
 	    free(reply);
 	    return NULL;
 	}
-    } while (size < len && len < rk_DNS_MAX_PACKET_SIZE);
-#ifdef HAVE_RES_NSEARCH
-    rk_res_free(&state);
-#endif
+    }
=20
     len =3D min(len, size);
     r =3D parse_reply(reply, len);
     free(reply);
+
+    resolve_free_handle(handle);
+
     return r;
 }
=20
-struct dns_reply * ROKEN_LIB_FUNCTION
-dns_lookup(const char *domain, const char *type_name)
+ROKEN_LIB_FUNCTION struct rk_dns_reply * ROKEN_LIB_CALL
+rk_dns_lookup(const char *domain, const char *type_name)
 {
     int type;
-   =20
-    type =3D dns_string_to_type(type_name);
+
+    type =3D rk_dns_string_to_type(type_name);
     if(type =3D=3D -1) {
 	if(_resolve_debug)
-	    fprintf(stderr, "dns_lookup: unknown resource type: `%s'\n",=20
+	    fprintf(stderr, "dns_lookup: unknown resource type: `%s'\n",
 		    type_name);
 	return NULL;
     }
-    return dns_lookup_int(domain, C_IN, type);
+    return dns_lookup_int(domain, rk_ns_c_in, type);
 }
=20
+#endif	/* !HAVE_WINDNS */
+
 static int
 compare_srv(const void *a, const void *b)
 {
-    const struct resource_record *const* aa =3D a, *const* bb =3D b;
+    const struct rk_resource_record *const* aa =3D a, *const* bb =3D b;
=20
     if((*aa)->u.srv->priority =3D=3D (*bb)->u.srv->priority)
 	return ((*aa)->u.srv->weight - (*bb)->u.srv->weight);
     return ((*aa)->u.srv->priority - (*bb)->u.srv->priority);
 }
=20
-#ifndef HAVE_RANDOM
-#define random() rand()
-#endif
-
 /* try to rearrange the srv-records by the algorithm in RFC2782 */
-void ROKEN_LIB_FUNCTION
-dns_srv_order(struct dns_reply *r)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_srv_order(struct rk_dns_reply *r)
 {
-    struct resource_record **srvs, **ss, **headp;
-    struct resource_record *rr;
+    struct rk_resource_record **srvs, **ss, **headp;
+    struct rk_resource_record *rr;
     int num_srv =3D 0;
=20
-#if defined(HAVE_INITSTATE) && defined(HAVE_SETSTATE)
-    int state[256 / sizeof(int)];
-    char *oldstate;
-#endif
+    rk_random_init();
=20
-    for(rr =3D r->head; rr; rr =3D rr->next)=20
+    for(rr =3D r->head; rr; rr =3D rr->next)
 	if(rr->type =3D=3D rk_ns_t_srv)
 	    num_srv++;
=20
@@ -624,7 +642,7 @@
     srvs =3D malloc(num_srv * sizeof(*srvs));
     if(srvs =3D=3D NULL)
 	return; /* XXX not much to do here */
-   =20
+
     /* unlink all srv-records from the linked list and put them in
        a vector */
     for(ss =3D srvs, headp =3D &r->head; *headp; )
@@ -635,19 +653,15 @@
 	    ss++;
 	} else
 	    headp =3D &(*headp)->next;
-   =20
+
     /* sort them by priority and weight */
     qsort(srvs, num_srv, sizeof(*srvs), compare_srv);
=20
-#if defined(HAVE_INITSTATE) && defined(HAVE_SETSTATE)
-    oldstate =3D initstate(time(NULL), (char*)state, sizeof(state));
-#endif
+    headp =3D &r->head;
=20
-    headp =3D &r->head;
-   =20
     for(ss =3D srvs; ss < srvs + num_srv; ) {
 	int sum, rnd, count;
-	struct resource_record **ee, **tt;
+	struct rk_resource_record **ee, **tt;
 	/* find the last record with the same priority and count the
            sum of all weights */
 	for(sum =3D 0, tt =3D ss; tt < srvs + num_srv; tt++) {
@@ -660,7 +674,7 @@
 	/* ss is now the first record of this priority and ee is the
            first of the next */
 	while(ss < ee) {
-	    rnd =3D random() % (sum + 1);
+	    rnd =3D rk_random() % (sum + 1);
 	    for(count =3D 0, tt =3D ss; ; tt++) {
 		if(*tt =3D=3D NULL)
 		    continue;
@@ -682,29 +696,238 @@
 		ss++;
 	}
     }
-   =20
-#if defined(HAVE_INITSTATE) && defined(HAVE_SETSTATE)
-    setstate(oldstate);
-#endif
+
     free(srvs);
     return;
 }
=20
+#ifdef HAVE_WINDNS
+
+#include <WinDNS.h>
+
+static struct rk_resource_record *
+parse_dns_record(PDNS_RECORD pRec)
+{
+    struct rk_resource_record * rr;
+
+    if (pRec =3D=3D NULL)
+	return NULL;
+
+    rr =3D calloc(1, sizeof(*rr));
+
+    rr->domain =3D strdup(pRec->pName);
+    rr->type =3D pRec->wType;
+    rr->class =3D 0;
+    rr->ttl =3D pRec->dwTtl;
+    rr->size =3D 0;
+
+    switch (rr->type) {
+    case rk_ns_t_ns:
+    case rk_ns_t_cname:
+    case rk_ns_t_ptr:
+	rr->u.txt =3D strdup(pRec->Data.NS.pNameHost);
+	if(rr->u.txt =3D=3D NULL) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+	break;
+
+    case rk_ns_t_mx:
+    case rk_ns_t_afsdb:{
+	size_t hostlen =3D strnlen(pRec->Data.MX.pNameExchange, DNS_MAX_NAME_LENG=
TH);
+
+	rr->u.mx =3D (struct mx_record *)malloc(sizeof(struct mx_record) +
+					      hostlen);
+	if (rr->u.mx =3D=3D NULL) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+
+	strcpy_s(rr->u.mx->domain, hostlen + 1, pRec->Data.MX.pNameExchange);
+	rr->u.mx->preference =3D pRec->Data.MX.wPreference;
+	break;
+    }
+
+    case rk_ns_t_srv:{
+	size_t hostlen =3D strnlen(pRec->Data.SRV.pNameTarget, DNS_MAX_NAME_LENGT=
H);
+
+	rr->u.srv =3D
+	    (struct srv_record*)malloc(sizeof(struct srv_record) +
+				       hostlen);
+	if(rr->u.srv =3D=3D NULL) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+
+	rr->u.srv->priority =3D pRec->Data.SRV.wPriority;
+	rr->u.srv->weight =3D pRec->Data.SRV.wWeight;
+	rr->u.srv->port =3D pRec->Data.SRV.wPort;
+	strcpy_s(rr->u.srv->target, hostlen + 1, pRec->Data.SRV.pNameTarget);
+
+	break;
+    }
+
+    case rk_ns_t_txt:{
+	size_t len;
+
+	if (pRec->Data.TXT.dwStringCount =3D=3D 0) {
+	    rr->u.txt =3D strdup("");
+	    break;
+	}
+
+	len =3D strnlen(pRec->Data.TXT.pStringArray[0], DNS_MAX_TEXT_STRING_LENGT=
H);
+
+	rr->u.txt =3D (char *)malloc(len + 1);
+	strcpy_s(rr->u.txt, len + 1, pRec->Data.TXT.pStringArray[0]);
+
+	break;
+    }
+
+    case rk_ns_t_key : {
+	size_t key_len;
+
+	if (pRec->wDataLength < 4) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+
+	key_len =3D pRec->wDataLength - 4;
+	rr->u.key =3D malloc (sizeof(*rr->u.key) + key_len - 1);
+	if (rr->u.key =3D=3D NULL) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+
+	rr->u.key->flags     =3D pRec->Data.KEY.wFlags;
+	rr->u.key->protocol  =3D pRec->Data.KEY.chProtocol;
+	rr->u.key->algorithm =3D pRec->Data.KEY.chAlgorithm;
+	rr->u.key->key_len   =3D key_len;
+	memcpy_s (rr->u.key->key_data, key_len,
+		  pRec->Data.KEY.Key, key_len);
+	break;
+    }
+
+    case rk_ns_t_sig : {
+	size_t sig_len, hostlen;
+
+	if(pRec->wDataLength <=3D 18) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+
+	sig_len =3D pRec->wDataLength;
+
+	hostlen =3D strnlen(pRec->Data.SIG.pNameSigner, DNS_MAX_NAME_LENGTH);
+
+	rr->u.sig =3D malloc(sizeof(*rr->u.sig)
+			      + hostlen + sig_len);
+	if (rr->u.sig =3D=3D NULL) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+	rr->u.sig->type           =3D pRec->Data.SIG.wTypeCovered;
+	rr->u.sig->algorithm      =3D pRec->Data.SIG.chAlgorithm;
+	rr->u.sig->labels         =3D pRec->Data.SIG.chLabelCount;
+	rr->u.sig->orig_ttl       =3D pRec->Data.SIG.dwOriginalTtl;
+	rr->u.sig->sig_expiration =3D pRec->Data.SIG.dwExpiration;
+	rr->u.sig->sig_inception  =3D pRec->Data.SIG.dwTimeSigned;
+	rr->u.sig->key_tag        =3D pRec->Data.SIG.wKeyTag;
+	rr->u.sig->sig_len        =3D sig_len;
+	memcpy_s (rr->u.sig->sig_data, sig_len,
+		  pRec->Data.SIG.Signature, sig_len);
+	rr->u.sig->signer         =3D &rr->u.sig->sig_data[sig_len];
+	strcpy_s(rr->u.sig->signer, hostlen + 1, pRec->Data.SIG.pNameSigner);
+	break;
+    }
+
+#ifdef DNS_TYPE_DS
+    case rk_ns_t_ds: {
+	rr->u.ds =3D malloc (sizeof(*rr->u.ds) + pRec->Data.DS.wDigestLength - 1);
+	if (rr->u.ds =3D=3D NULL) {
+	    dns_free_rr(rr);
+	    return NULL;
+	}
+
+	rr->u.ds->key_tag     =3D pRec->Data.DS.wKeyTag;
+	rr->u.ds->algorithm   =3D pRec->Data.DS.chAlgorithm;
+	rr->u.ds->digest_type =3D pRec->Data.DS.chDigestType;
+	rr->u.ds->digest_len  =3D pRec->Data.DS.wDigestLength;
+	memcpy_s (rr->u.ds->digest_data, pRec->Data.DS.wDigestLength,
+		  pRec->Data.DS.Digest, pRec->Data.DS.wDigestLength);
+	break;
+    }
+#endif
+
+    default:
+	dns_free_rr(rr);
+	return NULL;
+    }
+
+    rr->next =3D parse_dns_record(pRec->pNext);
+    return rr;
+}
+
+ROKEN_LIB_FUNCTION struct rk_dns_reply * ROKEN_LIB_CALL
+rk_dns_lookup(const char *domain, const char *type_name)
+{
+    DNS_STATUS status;
+    int type;
+    PDNS_RECORD pRec =3D NULL;
+    struct rk_dns_reply * r =3D NULL;
+
+    __try {
+
+	type =3D rk_dns_string_to_type(type_name);
+	if(type =3D=3D -1) {
+	    if(_resolve_debug)
+		fprintf(stderr, "dns_lookup: unknown resource type: `%s'\n",
+			type_name);
+	    return NULL;
+	}
+
+	status =3D DnsQuery_UTF8(domain, type, DNS_QUERY_STANDARD, NULL,
+			       &pRec, NULL);
+	if (status !=3D ERROR_SUCCESS)
+	    return NULL;
+
+	r =3D calloc(1, sizeof(*r));
+	r->q.domain =3D strdup(domain);
+	r->q.type =3D type;
+	r->q.class =3D 0;
+
+	r->head =3D parse_dns_record(pRec);
+
+	if (r->head =3D=3D NULL) {
+	    rk_dns_free_data(r);
+	    return NULL;
+	} else {
+	    return r;
+	}
+
+    } __finally {
+
+	if (pRec)
+	    DnsRecordListFree(pRec, DnsFreeRecordList);
+
+    }
+}
+#endif	/* HAVE_WINDNS */
+
 #else /* NOT defined(HAVE_RES_SEARCH) && defined(HAVE_DN_EXPAND) */
=20
-struct dns_reply * ROKEN_LIB_FUNCTION
-dns_lookup(const char *domain, const char *type_name)
+ROKEN_LIB_FUNCTION struct rk_dns_reply * ROKEN_LIB_CALL
+rk_dns_lookup(const char *domain, const char *type_name)
 {
     return NULL;
 }
=20
-void ROKEN_LIB_FUNCTION
-dns_free_data(struct dns_reply *r)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_free_data(struct rk_dns_reply *r)
 {
 }
=20
-void ROKEN_LIB_FUNCTION
-dns_srv_order(struct dns_reply *r)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dns_srv_order(struct rk_dns_reply *r)
 {
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/resolve.h
--- a/head/crypto/heimdal/lib/roken/resolve.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/resolve.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2002 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2002 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,20 +31,26 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: resolve.h 14773 2005-04-12 11:29:18Z lha $ */
+/* $Id$ */
=20
 #ifndef __RESOLVE_H__
 #define __RESOLVE_H__
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
-typedef enum {
+enum {
+    rk_ns_c_in =3D 1
+};
+
+enum {
 	rk_ns_t_invalid =3D 0,	/* Cookie. */
 	rk_ns_t_a =3D 1,		/* Host address. */
 	rk_ns_t_ns =3D 2,		/* Authoritative server. */
@@ -99,99 +105,38 @@
 	rk_ns_t_any =3D 255,	/* Wildcard match. */
 	rk_ns_t_zxfr =3D 256,	/* BIND-specific, nonstandard. */
 	rk_ns_t_max =3D 65536
-} rk_ns_type;
-
-/* We use these, but they are not always present in <arpa/nameser.h> */
-
-#ifndef C_IN
-#define C_IN		1
-#endif
-
-#ifndef T_A
-#define T_A		1
-#endif
-#ifndef T_NS
-#define T_NS		2
-#endif
-#ifndef T_CNAME
-#define T_CNAME		5
-#endif
-#ifndef T_SOA
-#define T_SOA		5
-#endif
-#ifndef T_PTR
-#define T_PTR		12
-#endif
-#ifndef T_MX
-#define T_MX		15
-#endif
-#ifndef T_TXT
-#define T_TXT		16
-#endif
-#ifndef T_AFSDB
-#define T_AFSDB		18
-#endif
-#ifndef T_SIG
-#define T_SIG		24
-#endif
-#ifndef T_KEY
-#define T_KEY		25
-#endif
-#ifndef T_AAAA
-#define T_AAAA		28
-#endif
-#ifndef T_SRV
-#define T_SRV		33
-#endif
-#ifndef T_NAPTR
-#define T_NAPTR		35
-#endif
-#ifndef T_CERT
-#define T_CERT		37
-#endif
-#ifndef T_SSHFP
-#define T_SSHFP		44
-#endif
+};
=20
 #ifndef MAXDNAME
 #define MAXDNAME	1025
 #endif
=20
-#define dns_query		rk_dns_query
 #define mx_record		rk_mx_record
 #define srv_record		rk_srv_record
 #define key_record		rk_key_record
 #define sig_record		rk_sig_record
 #define cert_record		rk_cert_record
 #define sshfp_record		rk_sshfp_record
-#define resource_record		rk_resource_record
-#define dns_reply		rk_dns_reply
=20
-#define dns_lookup		rk_dns_lookup
-#define dns_free_data		rk_dns_free_data
-#define dns_string_to_type	rk_dns_string_to_type
-#define dns_type_to_string	rk_dns_type_to_string
-#define dns_srv_order		rk_dns_srv_order
-
-struct dns_query{
+struct rk_dns_query{
     char *domain;
     unsigned type;
     unsigned class;
 };
=20
-struct mx_record{
+struct rk_mx_record{
     unsigned  preference;
     char domain[1];
 };
=20
-struct srv_record{
+struct rk_srv_record{
     unsigned priority;
     unsigned weight;
     unsigned port;
     char target[1];
 };
=20
-struct key_record {
+struct rk_key_record {
     unsigned flags;
     unsigned protocol;
     unsigned algorithm;
@@ -199,7 +144,7 @@
     u_char   key_data[1];
 };
=20
-struct sig_record {
+struct rk_sig_record {
     unsigned type;
     unsigned algorithm;
     unsigned labels;
@@ -208,11 +153,11 @@
     unsigned sig_inception;
     unsigned key_tag;
     char     *signer;
-    unsigned sig_len;
+    size_t   sig_len;
     char     sig_data[1];	/* also includes signer */
 };
=20
-struct cert_record {
+struct rk_cert_record {
     unsigned type;
     unsigned tag;
     unsigned algorithm;
@@ -220,22 +165,22 @@
     u_char   cert_data[1];
 };
=20
-struct sshfp_record {
+struct rk_sshfp_record {
     unsigned algorithm;
     unsigned type;
     size_t   sshfp_len;
     u_char   sshfp_data[1];
 };
=20
-struct ds_record {
+struct rk_ds_record {
     unsigned key_tag;
     unsigned algorithm;
     unsigned digest_type;
-    unsigned digest_len;
+    size_t digest_len;
     u_char digest_data[1];
 };
=20
-struct resource_record{
+struct rk_resource_record{
     char *domain;
     unsigned type;
     unsigned class;
@@ -243,23 +188,23 @@
     unsigned size;
     union {
 	void *data;
-	struct mx_record *mx;
-	struct mx_record *afsdb; /* mx and afsdb are identical */
-	struct srv_record *srv;
+	struct rk_mx_record *mx;
+	struct rk_mx_record *afsdb; /* mx and afsdb are identical */
+	struct rk_srv_record *srv;
 	struct in_addr *a;
 	char *txt;
-	struct key_record *key;
-	struct cert_record *cert;
-	struct sig_record *sig;
-	struct sshfp_record *sshfp;
-	struct ds_record *ds;
+	struct rk_key_record *key;
+	struct rk_cert_record *cert;
+	struct rk_sig_record *sig;
+	struct rk_sshfp_record *sshfp;
+	struct rk_ds_record *ds;
     }u;
-    struct resource_record *next;
+    struct rk_resource_record *next;
 };
=20
 #define rk_DNS_MAX_PACKET_SIZE		0xffff
=20
-struct dns_header {
+struct rk_dns_header {
     unsigned id;
     unsigned flags;
 #define rk_DNS_HEADER_RESPONSE_FLAG		1
@@ -277,22 +222,30 @@
     unsigned arcount;
 };
=20
-struct dns_reply{
-    struct dns_header h;
-    struct dns_query q;
-    struct resource_record *head;
+struct rk_dns_reply{
+    struct rk_dns_header h;
+    struct rk_dns_query q;
+    struct rk_resource_record *head;
 };
=20
=20
-struct dns_reply* ROKEN_LIB_FUNCTION
-	dns_lookup(const char *, const char *);
-void ROKEN_LIB_FUNCTION
-	dns_free_data(struct dns_reply *);
-int ROKEN_LIB_FUNCTION
-	dns_string_to_type(const char *name);
-const char *ROKEN_LIB_FUNCTION
-	dns_type_to_string(int type);
-void ROKEN_LIB_FUNCTION
-	dns_srv_order(struct dns_reply*);
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ROKEN_LIB_FUNCTION struct rk_dns_reply* ROKEN_LIB_CALL
+	rk_dns_lookup(const char *, const char *);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+	rk_dns_free_data(struct rk_dns_reply *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_dns_string_to_type(const char *name);
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
+	rk_dns_type_to_string(int type);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+	rk_dns_srv_order(struct rk_dns_reply*);
+
+#ifdef __cplusplus
+}
+#endif
=20
 #endif /* __RESOLVE_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/roken-co=
mmon.h
--- a/head/crypto/heimdal/lib/roken/roken-common.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/roken/roken-common.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,18 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: roken-common.h 20867 2007-06-03 21:00:45Z lha $ */
+/* $Id$ */
=20
 #ifndef __ROKEN_COMMON_H__
 #define __ROKEN_COMMON_H__
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
@@ -120,6 +122,8 @@
 #define O_ACCMODE	003
 #endif
=20
+#ifndef _WIN32
+
 #ifndef _PATH_DEV
 #define _PATH_DEV "/dev/"
 #endif
@@ -144,6 +148,16 @@
 #define MAXPATHLEN (1024+4)
 #endif
=20
+#endif	/* !_WIN32 */
+
+#ifndef PATH_MAX
+#define PATH_MAX MAX_PATH
+#endif
+
+#ifndef RETSIGTYPE
+#define RETSIGTYPE void
+#endif
+
 #ifndef SIG_ERR
 #define SIG_ERR ((RETSIGTYPE (*)(int))-1)
 #endif
@@ -207,6 +221,10 @@
 #define AI_NUMERICHOST	0x04
 #endif
=20
+#ifndef AI_NUMERICSERV
+#define AI_NUMERICSERV  0x08
+#endif
+
 /* flags for getnameinfo() */
=20
 #ifndef NI_DGRAM
@@ -261,144 +279,219 @@
 ROKEN_CPP_START
=20
 #ifndef IRIX4 /* fix for compiler bug */
+#ifndef _WIN32
 #ifdef RETSIGTYPE
 typedef RETSIGTYPE (*SigAction)(int);
 SigAction signal(int iSig, SigAction pAction); /* BSD compatible */
 #endif
 #endif
+#endif
=20
-int ROKEN_LIB_FUNCTION
+#define SE_E_UNSPECIFIED (-1)
+#define SE_E_FORKFAILED  (-2)
+#define SE_E_WAITPIDFAILED (-3)
+#define SE_E_EXECTIMEOUT (-4)
+#define SE_E_NOEXEC   126
+#define SE_E_NOTFOUND 127
+
+#define SE_PROCSTATUS(st) (((st) >=3D 0 && (st) < 126)? st: -1)
+#define SE_PROCSIGNAL(st) (((st) >=3D 128)? (st) - 128: -1)
+#define SE_IS_ERROR(st) ((st) < 0 || (st) >=3D 126)
+
+
+#define simple_execve rk_simple_execve
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execve(const char*, char*const[], char*const[]);
=20
-int ROKEN_LIB_FUNCTION
-simple_execve_timed(const char *, char *const[],=20
-		    char *const [], time_t (*)(void *),=20
+#define simple_execve_timed rk_simple_execve_timed
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execve_timed(const char *, char *const[],
+		    char *const [], time_t (*)(void *),
 		    void *, time_t);
-int ROKEN_LIB_FUNCTION
+
+#define simple_execvp rk_simple_execvp
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execvp(const char*, char *const[]);
=20
-int ROKEN_LIB_FUNCTION
-simple_execvp_timed(const char *, char *const[],=20
+#define simple_execvp_timed rk_simple_execvp_timed
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp_timed(const char *, char *const[],
 		    time_t (*)(void *), void *, time_t);
-int ROKEN_LIB_FUNCTION
+
+#define simple_execlp rk_simple_execlp
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execlp(const char*, ...);
=20
-int ROKEN_LIB_FUNCTION
+#define simple_execle rk_simple_execle
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execle(const char*, ...);
=20
-int ROKEN_LIB_FUNCTION
-simple_execl(const char *file, ...);
-
-int ROKEN_LIB_FUNCTION
+#define wait_for_process rk_wait_for_process
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 wait_for_process(pid_t);
=20
-int ROKEN_LIB_FUNCTION
-wait_for_process_timed(pid_t, time_t (*)(void *),=20
-					      void *, time_t);
-int ROKEN_LIB_FUNCTION
+#define wait_for_process_timed rk_wait_for_process_timed
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process_timed(pid_t, time_t (*)(void *),
+		       void *, time_t);
+
+#define pipe_execv rk_pipe_execv
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 pipe_execv(FILE**, FILE**, FILE**, const char*, ...);
=20
-void ROKEN_LIB_FUNCTION
+#define print_version rk_print_version
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 print_version(const char *);
=20
-ssize_t ROKEN_LIB_FUNCTION
+#define eread rk_eread
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 eread (int fd, void *buf, size_t nbytes);
=20
-ssize_t ROKEN_LIB_FUNCTION
+#define ewrite rk_ewrite
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 ewrite (int fd, const void *buf, size_t nbytes);
=20
 struct hostent;
=20
-const char * ROKEN_LIB_FUNCTION
+#define hostent_find_fqdn rk_hostent_find_fqdn
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 hostent_find_fqdn (const struct hostent *);
=20
-void ROKEN_LIB_FUNCTION
+#define esetenv rk_esetenv
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 esetenv(const char *, const char *, int);
=20
-void ROKEN_LIB_FUNCTION
+#define socket_set_address_and_port rk_socket_set_address_and_port
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 socket_set_address_and_port (struct sockaddr *, const void *, int);
=20
-size_t ROKEN_LIB_FUNCTION
+#define socket_addr_size rk_socket_addr_size
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 socket_addr_size (const struct sockaddr *);
=20
-void ROKEN_LIB_FUNCTION
+#define socket_set_any rk_socket_set_any
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 socket_set_any (struct sockaddr *, int);
=20
-size_t ROKEN_LIB_FUNCTION
+#define socket_sockaddr_size rk_socket_sockaddr_size
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 socket_sockaddr_size (const struct sockaddr *);
=20
-void * ROKEN_LIB_FUNCTION
-socket_get_address (struct sockaddr *);
+#define socket_get_address rk_socket_get_address
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+socket_get_address (const struct sockaddr *);
=20
-int ROKEN_LIB_FUNCTION
+#define socket_get_port rk_socket_get_port
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 socket_get_port (const struct sockaddr *);
=20
-void ROKEN_LIB_FUNCTION
+#define socket_set_port rk_socket_set_port
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 socket_set_port (struct sockaddr *, int);
=20
-void ROKEN_LIB_FUNCTION
-socket_set_portrange (int, int, int);
+#define socket_set_portrange rk_socket_set_portrange
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_portrange (rk_socket_t, int, int);
=20
-void ROKEN_LIB_FUNCTION
-socket_set_debug (int);
+#define socket_set_debug rk_socket_set_debug
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_debug (rk_socket_t);
=20
-void ROKEN_LIB_FUNCTION
-socket_set_tos (int, int);
+#define socket_set_tos rk_socket_set_tos
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_tos (rk_socket_t, int);
=20
-void ROKEN_LIB_FUNCTION
-socket_set_reuseaddr (int, int);
+#define socket_set_reuseaddr rk_socket_set_reuseaddr
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_reuseaddr (rk_socket_t, int);
=20
-void ROKEN_LIB_FUNCTION
-socket_set_ipv6only (int, int);
+#define socket_set_ipv6only rk_socket_set_ipv6only
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_ipv6only (rk_socket_t, int);
=20
-char ** ROKEN_LIB_FUNCTION
+#define socket_to_fd rk_socket_to_fd
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+socket_to_fd(rk_socket_t, int);
+
+#define vstrcollect rk_vstrcollect
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
 vstrcollect(va_list *ap);
=20
-char ** ROKEN_LIB_FUNCTION
+#define strcollect rk_strcollect
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
 strcollect(char *first, ...);
=20
-void ROKEN_LIB_FUNCTION
+#define timevalfix rk_timevalfix
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 timevalfix(struct timeval *t1);
=20
-void ROKEN_LIB_FUNCTION
+#define timevaladd rk_timevaladd
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 timevaladd(struct timeval *t1, const struct timeval *t2);
=20
-void ROKEN_LIB_FUNCTION
+#define timevalsub rk_timevalsub
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 timevalsub(struct timeval *t1, const struct timeval *t2);
=20
-char *ROKEN_LIB_FUNCTION
+#define pid_file_write rk_pid_file_write
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 pid_file_write (const char *progname);
=20
-void ROKEN_LIB_FUNCTION
+#define pid_file_delete rk_pid_file_delete
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 pid_file_delete (char **);
=20
-int ROKEN_LIB_FUNCTION
+#define read_environment rk_read_environment
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 read_environment(const char *file, char ***env);
=20
-void ROKEN_LIB_FUNCTION
+#define free_environment rk_free_environment
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 free_environment(char **);
=20
-void ROKEN_LIB_FUNCTION
-warnerr(int doerrno, const char *fmt, va_list ap)
+#define warnerr rk_warnerr
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_warnerr(int doerrno, const char *fmt, va_list ap)
     __attribute__ ((format (printf, 2, 0)));
=20
-void * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
 rk_realloc(void *, size_t);
=20
 struct rk_strpool;
=20
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 rk_strpoolcollect(struct rk_strpool *);
=20
-struct rk_strpool * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct rk_strpool * ROKEN_LIB_CALL
 rk_strpoolprintf(struct rk_strpool *, const char *, ...)
     __attribute__ ((format (printf, 2, 3)));
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rk_strpoolfree(struct rk_strpool *);
=20
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_dumpdata (const char *, const void *, size_t);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_undumpdata (const char *, void **, size_t *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_xfree (void *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_cloexec(int);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_cloexec_file(FILE *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_cloexec_dir(DIR *);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+ct_memcmp(const void *, const void *, size_t);
+
 void ROKEN_LIB_FUNCTION
-rk_dumpdata (const char *, const void *, size_t);
+rk_random_init(void);
=20
 ROKEN_CPP_END
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/roken.awk
--- a/head/crypto/heimdal/lib/roken/roken.awk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/roken.awk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,14 @@
-# $Id: roken.awk 15409 2005-06-16 16:29:58Z lha $
+# $Id$
=20
 BEGIN {
-	print "#ifdef HAVE_CONFIG_H"
 	print "#include <config.h>"
+	print "#include <stdio.h>"
+	print "#ifdef HAVE_SYS_TYPES_H"
+	print "#include <sys/types.h>"
 	print "#endif"
-	print "#include <stdio.h>"
+	print "#ifdef HAVE_SYS_SOCKET_H"
+	print "#include <sys/socket.h>"
+	print "#endif"
 	print ""
 	print "int main(int argc, char **argv)"
 	print "{"
@@ -32,7 +36,6 @@
 }
=20
 END {
-	print "puts(\"#define ROKEN_VERSION \" VERSION );"
 	print "puts(\"\");"
 	print "puts(\"#endif /* __ROKEN_H__ */\");"
 	print "return 0;"
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/roken.h.=
in
--- a/head/crypto/heimdal/lib/roken/roken.h.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/roken.h.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,6 +1,6 @@
 /* -*- C -*- */
 /*
- * Copyright (c) 1995-2005 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2005 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *=20
@@ -32,8 +32,6 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: roken.h.in 18612 2006-10-19 16:35:16Z lha $ */
-
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdarg.h>
@@ -43,6 +41,148 @@
 #include <string.h>
 #include <signal.h>
=20
+#ifndef ROKEN_LIB_FUNCTION
+#ifdef _WIN32
+#  define ROKEN_LIB_CALL     __cdecl
+#  ifdef ROKEN_LIB_DYNAMIC
+#    define ROKEN_LIB_FUNCTION __declspec(dllimport)
+#    define ROKEN_LIB_VARIABLE __declspec(dllimport)
+#  else
+#    define ROKEN_LIB_FUNCTION
+#    define ROKEN_LIB_VARIABLE
+#  endif
+#else
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#define ROKEN_LIB_VARIABLE
+#endif
+#endif
+
+#ifdef HAVE_WINSOCK
+/* Declarations for Microsoft Windows */
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+/*
+ * error codes for inet_ntop/inet_pton=20
+ */
+#define EAFNOSUPPORT WSAEAFNOSUPPORT
+
+typedef SOCKET rk_socket_t;
+
+#define rk_closesocket(x) closesocket(x)
+#define rk_INVALID_SOCKET INVALID_SOCKET
+#define rk_IS_BAD_SOCKET(s) ((s) =3D=3D INVALID_SOCKET)
+#define rk_IS_SOCKET_ERROR(rv) ((rv) =3D=3D SOCKET_ERROR)
+#define rk_SOCK_ERRNO WSAGetLastError()
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_SOCK_IOCTL(SOCKET s, long cmd, in=
t * argp);
+
+/* Microsoft VC 2010 POSIX definitions */
+#ifndef ENOTSOCK
+#define ENOTSOCK		128
+#endif
+#ifndef ENOTSUP
+#define ENOTSUP                 129
+#endif
+#ifndef EOVERFLOW
+#define EOVERFLOW               132
+#endif
+#ifndef ETIMEDOUT
+#define ETIMEDOUT               138
+#endif
+#ifndef EWOULDBLOCK
+#define EWOULDBLOCK             140
+#endif
+
+#define rk_SOCK_INIT() rk_WSAStartup()
+#define rk_SOCK_EXIT() rk_WSACleanup()
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_WSAStartup(void);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_WSACleanup(void);
+
+#else  /* not WinSock */
+
+typedef int rk_socket_t;
+
+#define rk_closesocket(x) close(x)
+#define rk_SOCK_IOCTL(s,c,a) ioctl((s),(c),(a))
+#define rk_IS_BAD_SOCKET(s) ((s) < 0)
+#define rk_IS_SOCKET_ERROR(rv) ((rv) < 0)
+#define rk_SOCK_ERRNO errno
+#define rk_INVALID_SOCKET (-1)
+
+#define rk_SOCK_INIT() 0
+#define rk_SOCK_EXIT() do { } while(0)
+
+#endif
+
+#ifndef IN_LOOPBACKNET
+#define IN_LOOPBACKNET 127
+#endif
+
+#ifdef _MSC_VER
+/* Declarations for Microsoft Visual C runtime on Windows */
+
+#include<process.h>
+
+#include<io.h>
+
+#ifndef __BIT_TYPES_DEFINED__
+#define __BIT_TYPES_DEFINED__
+
+typedef __int8             int8_t;
+typedef __int16            int16_t;
+typedef __int32            int32_t;
+typedef __int64            int64_t;
+typedef unsigned __int8    uint8_t;
+typedef unsigned __int16   uint16_t;
+typedef unsigned __int32   uint32_t;
+typedef unsigned __int64   uint64_t;
+typedef uint8_t            u_int8_t;
+typedef uint16_t           u_int16_t;
+typedef uint32_t           u_int32_t;
+typedef uint64_t           u_int64_t;
+
+#endif  /* __BIT_TYPES_DEFINED__ */
+
+#define UNREACHABLE(x) x
+#define UNUSED_ARGUMENT(x) ((void) x)
+
+#define RETSIGTYPE void
+
+#define VOID_RETSIGTYPE 1
+
+#ifdef VOID_RETSIGTYPE
+#define SIGRETURN(x) return
+#else
+#define SIGRETURN(x) return (RETSIGTYPE)(x)
+#endif
+
+#ifndef CPP_ONLY
+
+typedef int pid_t;
+
+typedef unsigned int gid_t;
+
+typedef unsigned int uid_t;
+
+typedef unsigned short mode_t;
+
+#endif
+
+#ifndef __cplusplus
+#define inline __inline
+#endif
+
+#else
+
+#define UNREACHABLE(x)
+#define UNUSED_ARGUMENT(x)
+
+#endif
+
 #ifdef _AIX
 struct ether_addr;
 struct sockaddr_dl;
@@ -114,7 +254,7 @@
 #ifdef HAVE_TERMIOS_H
 #include <termios.h>
 #endif
-#if defined(HAVE_SYS_IOCTL_H) && SunOS !=3D 40
+#ifdef HAVE_SYS_IOCTL_H
 #include <sys/ioctl.h>
 #endif
 #ifdef TIME_WITH_SYS_TIME
@@ -125,17 +265,32 @@
 #else
 #include <time.h>
 #endif
-#ifdef HAVE_STRINGS_H
-#include <strings.h>
-#endif
=20
 #ifdef HAVE_PATHS_H
 #include <paths.h>
 #endif
=20
+#ifdef HAVE_DIRENT_H
+#include <dirent.h>
+#endif
+
+#ifdef BACKSLASH_PATH_DELIM
+#define rk_PATH_DELIM '\\'
+#endif
+
 #ifndef HAVE_SSIZE_T
+#ifndef SSIZE_T_DEFINED
+#ifdef ssize_t
+#undef ssize_t
+#endif
+#ifdef _WIN64
+typedef __int64 ssize_t;
+#else
 typedef int ssize_t;
 #endif
+#define SSIZE_T_DEFINED
+#endif  /* SSIZE_T_DEFINED */
+#endif  /* HAVE_SSIZE_T */
=20
 #include <roken-common.h>
=20
@@ -151,118 +306,264 @@
 #define setsid _setsid
 #endif
=20
+#ifdef _MSC_VER
+/* Additional macros for Visual C/C++ runtime */
+
+#define close	_close
+
+#define getpid	_getpid
+
+#define open	_open
+
+#define chdir   _chdir
+
+#define fsync   _commit
+
+/* The MSVC implementation of snprintf is not C99 compliant.  */
+#define snprintf    rk_snprintf
+#define vsnprintf   rk_vsnprintf
+#define vasnprintf  rk_vasnprintf
+#define vasprintf   rk_vasprintf
+#define asnprintf   rk_asnprintf
+#define asprintf    rk_asprintf
+
+#define _PIPE_BUFFER_SZ 8192
+#define pipe(fds) _pipe((fds), _PIPE_BUFFER_SZ, O_BINARY);
+
+#define ftruncate(fd, sz) _chsize((fd), (sz))
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_snprintf (char *str, size_t sz, const char *format, ...);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asprintf (char **ret, const char *format, ...);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asnprintf (char **ret, size_t max_sz, const char *format, ...);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasprintf (char **ret, const char *format, va_list args);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args=
);
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vsnprintf (char *str, size_t sz, const char *format, va_list args);
+
+/* missing stat.h predicates */
+
+#define S_ISREG(m) (((m) & _S_IFREG) =3D=3D _S_IFREG)
+
+#define S_ISDIR(m) (((m) & _S_IFDIR) =3D=3D _S_IFDIR)
+
+#define S_ISCHR(m) (((m) & _S_IFCHR) =3D=3D _S_IFCHR)
+
+#define S_ISFIFO(m) (((m) & _S_IFIFO) =3D=3D _S_IFIFO)
+
+/* The following are not implemented:
+
+ S_ISLNK(m)
+ S_ISSOCK(m)
+ S_ISBLK(m)
+*/
+
+#endif  /* _MSC_VER */
+
+#ifdef HAVE_WINSOCK
+
+/* While we are at it, define WinSock specific scatter gather socket
+   I/O. */
+
+#define iovec    _WSABUF
+#define iov_base buf
+#define iov_len  len
+
+struct msghdr {
+    void           *msg_name;
+    socklen_t       msg_namelen;
+    struct iovec   *msg_iov;
+    size_t          msg_iovlen;
+    void           *msg_control;
+    socklen_t       msg_controllen;
+    int             msg_flags;
+};
+
+#define sendmsg sendmsg_w32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+sendmsg_w32(rk_socket_t s, const struct msghdr * msg, int flags);
+
+#endif	/* HAVE_WINSOCK */
+
 #ifndef HAVE_PUTENV
-int ROKEN_LIB_FUNCTION putenv(const char *);
+#define putenv rk_putenv
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL putenv(const char *);
 #endif
=20
 #if !defined(HAVE_SETENV) || defined(NEED_SETENV_PROTO)
-int ROKEN_LIB_FUNCTION setenv(const char *, const char *, int);
+#ifndef HAVE_SETENV
+#define setenv rk_setenv
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL setenv(const char *, const char *, i=
nt);
 #endif
=20
 #if !defined(HAVE_UNSETENV) || defined(NEED_UNSETENV_PROTO)
-void ROKEN_LIB_FUNCTION unsetenv(const char *);
+#ifndef HAVE_UNSETENV
+#define unsetenv rk_unsetenv
+#endif
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL unsetenv(const char *);
 #endif
=20
 #if !defined(HAVE_GETUSERSHELL) || defined(NEED_GETUSERSHELL_PROTO)
-char * ROKEN_LIB_FUNCTION getusershell(void);
-void ROKEN_LIB_FUNCTION endusershell(void);
+#ifndef HAVE_GETUSERSHELL
+#define getusershell rk_getusershell
+#define endusershell rk_endusershell
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL getusershell(void);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL endusershell(void);
 #endif
=20
 #if !defined(HAVE_SNPRINTF) || defined(NEED_SNPRINTF_PROTO)
-int ROKEN_LIB_FUNCTION snprintf (char *, size_t, const char *, ...)
+#ifndef HAVE_SNPRINTF
+#define snprintf rk_snprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+     rk_snprintf (char *, size_t, const char *, ...)
      __attribute__ ((format (printf, 3, 4)));
 #endif
=20
 #if !defined(HAVE_VSNPRINTF) || defined(NEED_VSNPRINTF_PROTO)
-int ROKEN_LIB_FUNCTION=20
-     vsnprintf (char *, size_t, const char *, va_list)
+#ifndef HAVE_VSNPRINTF
+#define vsnprintf rk_vsnprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL=20
+     rk_vsnprintf (char *, size_t, const char *, va_list)
      __attribute__((format (printf, 3, 0)));
 #endif
=20
 #if !defined(HAVE_ASPRINTF) || defined(NEED_ASPRINTF_PROTO)
-int ROKEN_LIB_FUNCTION
-     asprintf (char **, const char *, ...)
+#ifndef HAVE_ASPRINTF
+#define asprintf rk_asprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+     rk_asprintf (char **, const char *, ...)
      __attribute__ ((format (printf, 2, 3)));
 #endif
=20
 #if !defined(HAVE_VASPRINTF) || defined(NEED_VASPRINTF_PROTO)
-int ROKEN_LIB_FUNCTION
-    vasprintf (char **, const char *, va_list)
+#ifndef HAVE_VASPRINTF
+#define vasprintf rk_vasprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+    rk_vasprintf (char **, const char *, va_list)
      __attribute__((format (printf, 2, 0)));
 #endif
=20
 #if !defined(HAVE_ASNPRINTF) || defined(NEED_ASNPRINTF_PROTO)
-int ROKEN_LIB_FUNCTION
-    asnprintf (char **, size_t, const char *, ...)
+#ifndef HAVE_ASNPRINTF
+#define asnprintf rk_asnprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+    rk_asnprintf (char **, size_t, const char *, ...)
      __attribute__ ((format (printf, 3, 4)));
 #endif
=20
 #if !defined(HAVE_VASNPRINTF) || defined(NEED_VASNPRINTF_PROTO)
-int ROKEN_LIB_FUNCTION
+#ifndef HAVE_VASNPRINTF
+#define vasnprintf rk_vasnprintf
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
     vasnprintf (char **, size_t, const char *, va_list)
      __attribute__((format (printf, 3, 0)));
 #endif
=20
 #ifndef HAVE_STRDUP
-char * ROKEN_LIB_FUNCTION strdup(const char *);
+#define strdup rk_strdup
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strdup(const char *);
 #endif
=20
 #if !defined(HAVE_STRNDUP) || defined(NEED_STRNDUP_PROTO)
-char * ROKEN_LIB_FUNCTION strndup(const char *, size_t);
+#ifndef HAVE_STRNDUP
+#define strndup rk_strndup
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strndup(const char *, size_t);
 #endif
=20
 #ifndef HAVE_STRLWR
-char * ROKEN_LIB_FUNCTION strlwr(char *);
+#define strlwr rk_strlwr
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strlwr(char *);
 #endif
=20
 #ifndef HAVE_STRNLEN
-size_t ROKEN_LIB_FUNCTION strnlen(const char*, size_t);
+#define strnlen rk_strnlen
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL strnlen(const char*, size_t);
 #endif
=20
 #if !defined(HAVE_STRSEP) || defined(NEED_STRSEP_PROTO)
-char * ROKEN_LIB_FUNCTION strsep(char**, const char*);
+#ifndef HAVE_STRSEP
+#define strsep rk_strsep
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strsep(char**, const char*);
 #endif
=20
 #if !defined(HAVE_STRSEP_COPY) || defined(NEED_STRSEP_COPY_PROTO)
-ssize_t ROKEN_LIB_FUNCTION strsep_copy(const char**, const char*, char*, s=
ize_t);
+#ifndef HAVE_STRSEP_COPY
+#define strsep_copy rk_strsep_copy
+#endif
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL strsep_copy(const char**, const =
char*, char*, size_t);
 #endif
=20
 #ifndef HAVE_STRCASECMP
-int ROKEN_LIB_FUNCTION strcasecmp(const char *, const char *);
+#define strcasecmp rk_strcasecmp
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL strcasecmp(const char *, const char =
*);
 #endif
=20
 #ifdef NEED_FCLOSE_PROTO
-int ROKEN_LIB_FUNCTION fclose(FILE *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL fclose(FILE *);
 #endif
=20
 #ifdef NEED_STRTOK_R_PROTO
-char * ROKEN_LIB_FUNCTION strtok_r(char *, const char *, char **);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strtok_r(char *, const char *, ch=
ar **);
 #endif
=20
 #ifndef HAVE_STRUPR
-char * ROKEN_LIB_FUNCTION strupr(char *);
+#define strupr rk_strupr
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strupr(char *);
 #endif
=20
 #ifndef HAVE_STRLCPY
-size_t ROKEN_LIB_FUNCTION strlcpy (char *, const char *, size_t);
+#define strlcpy rk_strlcpy
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL strlcpy (char *, const char *, si=
ze_t);
 #endif
=20
 #ifndef HAVE_STRLCAT
-size_t ROKEN_LIB_FUNCTION strlcat (char *, const char *, size_t);
+#define strlcat rk_strlcat
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL strlcat (char *, const char *, si=
ze_t);
 #endif
=20
 #ifndef HAVE_GETDTABLESIZE
-int ROKEN_LIB_FUNCTION getdtablesize(void);
+#define getdtablesize rk_getdtablesize
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL getdtablesize(void);
 #endif
=20
 #if !defined(HAVE_STRERROR) && !defined(strerror)
-char * ROKEN_LIB_FUNCTION strerror(int);
+#define strerror rk_strerror
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL strerror(int);
+#endif
+
+#if (!defined(HAVE_STRERROR_R) && !defined(strerror_r)) || (!defined(STRER=
ROR_R_PROTO_COMPATIBLE) && defined(HAVE_STRERROR_R))
+int ROKEN_LIB_FUNCTION rk_strerror_r(int, char *, size_t);
+#else
+#define rk_strerror_r strerror_r
 #endif
=20
 #if !defined(HAVE_HSTRERROR) || defined(NEED_HSTRERROR_PROTO)
+#ifndef HAVE_HSTRERROR
+#define hstrerror rk_hstrerror
+#endif
 /* This causes a fatal error under Psoriasis */
-#if !(defined(SunOS) && (SunOS >=3D 50))
-const char * ROKEN_LIB_FUNCTION hstrerror(int);
+#ifndef SunOS
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL hstrerror(int);
 #endif
 #endif
=20
@@ -271,118 +572,151 @@
 #endif
=20
 #if !defined(HAVE_INET_ATON) || defined(NEED_INET_ATON_PROTO)
-int ROKEN_LIB_FUNCTION inet_aton(const char *, struct in_addr *);
+#ifndef HAVE_INET_ATON
+#define inet_aton rk_inet_aton
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL inet_aton(const char *, struct in_ad=
dr *);
 #endif
=20
 #ifndef HAVE_INET_NTOP
-const char * ROKEN_LIB_FUNCTION
+#define inet_ntop rk_inet_ntop
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 inet_ntop(int af, const void *src, char *dst, size_t size);
 #endif
=20
 #ifndef HAVE_INET_PTON
-int ROKEN_LIB_FUNCTION
+#define inet_pton rk_inet_pton
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 inet_pton(int, const char *, void *);
 #endif
=20
-#if !defined(HAVE_GETCWD)
-char* ROKEN_LIB_FUNCTION getcwd(char *, size_t);
+#ifndef HAVE_GETCWD
+#define getcwd rk_getcwd
+ROKEN_LIB_FUNCTION char* ROKEN_LIB_CALL getcwd(char *, size_t);
 #endif
=20
 #ifdef HAVE_PWD_H
 #include <pwd.h>
-struct passwd * ROKEN_LIB_FUNCTION k_getpwnam (const char *);
-struct passwd * ROKEN_LIB_FUNCTION k_getpwuid (uid_t);
+ROKEN_LIB_FUNCTION struct passwd * ROKEN_LIB_CALL k_getpwnam (const char *=
);
+ROKEN_LIB_FUNCTION struct passwd * ROKEN_LIB_CALL k_getpwuid (uid_t);
 #endif
=20
-const char * ROKEN_LIB_FUNCTION get_default_username (void);
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL get_default_username (void);
=20
 #ifndef HAVE_SETEUID
-int ROKEN_LIB_FUNCTION seteuid(uid_t);
+#define seteuid rk_seteuid
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL seteuid(uid_t);
 #endif
=20
 #ifndef HAVE_SETEGID
-int ROKEN_LIB_FUNCTION setegid(gid_t);
+#define setegid rk_setegid
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL setegid(gid_t);
 #endif
=20
 #ifndef HAVE_LSTAT
-int ROKEN_LIB_FUNCTION lstat(const char *, struct stat *);
+#define lstat rk_lstat
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL lstat(const char *, struct stat *);
 #endif
=20
 #if !defined(HAVE_MKSTEMP) || defined(NEED_MKSTEMP_PROTO)
-int ROKEN_LIB_FUNCTION mkstemp(char *);
+#ifndef HAVE_MKSTEMP
+#define mkstemp rk_mkstemp
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL mkstemp(char *);
 #endif
=20
 #ifndef HAVE_CGETENT
-int ROKEN_LIB_FUNCTION cgetent(char **, char **, const char *);
-int ROKEN_LIB_FUNCTION cgetstr(char *, const char *, char **);
+#define cgetent rk_cgetent
+#define cgetstr rk_cgetstr
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetent(char **, char **, const char=
 *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL cgetstr(char *, const char *, char *=
*);
 #endif
=20
 #ifndef HAVE_INITGROUPS
-int ROKEN_LIB_FUNCTION initgroups(const char *, gid_t);
+#define initgroups rk_initgroups
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL initgroups(const char *, gid_t);
 #endif
=20
 #ifndef HAVE_FCHOWN
-int ROKEN_LIB_FUNCTION fchown(int, uid_t, gid_t);
+#define fchown rk_fchown
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL fchown(int, uid_t, gid_t);
+#endif
+
+#ifdef RENAME_DOES_NOT_UNLINK
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL rk_rename(const char *, const char *=
);
+#else
+#define rk_rename(__rk_rn_from,__rk_rn_to) rename(__rk_rn_from,__rk_rn_to)
 #endif
=20
 #if !defined(HAVE_DAEMON) || defined(NEED_DAEMON_PROTO)
-int ROKEN_LIB_FUNCTION daemon(int, int);
+#ifndef HAVE_DAEMON
+#define daemon rk_daemon
 #endif
-
-#ifndef HAVE_INNETGR
-int ROKEN_LIB_FUNCTION innetgr(const char *, const char *,=20
-	    const char *, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL daemon(int, int);
 #endif
=20
 #ifndef HAVE_CHOWN
-int ROKEN_LIB_FUNCTION chown(const char *, uid_t, gid_t);
+#define chown rk_chown
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL chown(const char *, uid_t, gid_t);
 #endif
=20
 #ifndef HAVE_RCMD
-int ROKEN_LIB_FUNCTION
+#define rcmd rk_rcmd
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
     rcmd(char **, unsigned short, const char *,
 	 const char *, const char *, int *);
 #endif
=20
 #if !defined(HAVE_INNETGR) || defined(NEED_INNETGR_PROTO)
-int ROKEN_LIB_FUNCTION innetgr(const char*, const char*,
+#ifndef HAVE_INNETGR
+#define innetgr rk_innetgr
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL innetgr(const char*, const char*,
     const char*, const char*);
 #endif
=20
 #ifndef HAVE_IRUSEROK
-int ROKEN_LIB_FUNCTION iruserok(unsigned, int,=20
+#define iruserok rk_iruserok
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL iruserok(unsigned, int,=20
     const char *, const char *);
 #endif
=20
 #if !defined(HAVE_GETHOSTNAME) || defined(NEED_GETHOSTNAME_PROTO)
-int ROKEN_LIB_FUNCTION gethostname(char *, int);
+#ifndef HAVE_GETHOSTNAME
+#define gethostname rk_gethostname
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL gethostname(char *, int);
 #endif
=20
 #ifndef HAVE_WRITEV
-ssize_t ROKEN_LIB_FUNCTION
+#define writev rk_writev
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 writev(int, const struct iovec *, int);
 #endif
=20
 #ifndef HAVE_READV
-ssize_t ROKEN_LIB_FUNCTION
+#define readv rk_readv
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 readv(int, const struct iovec *, int);
 #endif
=20
-#ifndef HAVE_MKSTEMP
-int ROKEN_LIB_FUNCTION
-mkstemp(char *);
+#ifndef HAVE_PIDFILE
+#ifdef NO_PIDFILES
+#define pidfile(x) ((void) 0)
+#else
+#define pidfile rk_pidfile
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL pidfile (const char*);
 #endif
-
-#ifndef HAVE_PIDFILE
-void ROKEN_LIB_FUNCTION pidfile (const char*);
 #endif
=20
 #ifndef HAVE_BSWAP32
-unsigned int ROKEN_LIB_FUNCTION bswap32(unsigned int);
+#define bswap32 rk_bswap32
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL bswap32(unsigned int);
 #endif
=20
 #ifndef HAVE_BSWAP16
-unsigned short ROKEN_LIB_FUNCTION bswap16(unsigned short);
+#define bswap16 rk_bswap16
+ROKEN_LIB_FUNCTION unsigned short ROKEN_LIB_CALL bswap16(unsigned short);
 #endif
=20
 #ifndef HAVE_FLOCK
@@ -399,27 +733,41 @@
 #define LOCK_UN   8		/* Unlock */
 #endif
=20
-int flock(int fd, int operation);
+#define flock(_x,_y) rk_flock(_x,_y)
+int rk_flock(int fd, int operation);
 #endif /* HAVE_FLOCK */
=20
-time_t ROKEN_LIB_FUNCTION tm2time (struct tm, int);
+#ifndef HAVE_DIRFD
+#ifdef HAVE_DIR_DD_FD
+#define dirfd(x) ((x)->dd_fd)
+#else
+#ifndef _WIN32 /* Windows code never calls dirfd */
+#error Missing dirfd() and ->dd_fd
+#endif
+#endif
+#endif
=20
-int ROKEN_LIB_FUNCTION unix_verify_user(char *, char *);
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL tm2time (struct tm, int);
=20
-int ROKEN_LIB_FUNCTION roken_concat (char *, size_t, ...);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL unix_verify_user(char *, char *);
=20
-size_t ROKEN_LIB_FUNCTION roken_mconcat (char **, size_t, ...);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL roken_concat (char *, size_t, ...);
=20
-int ROKEN_LIB_FUNCTION roken_vconcat (char *, size_t, va_list);
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL roken_mconcat (char **, size_t, .=
..);
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL roken_vconcat (char *, size_t, va_li=
st);
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
     roken_vmconcat (char **, size_t, va_list);
=20
-ssize_t ROKEN_LIB_FUNCTION net_write (int, const void *, size_t);
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+    net_write (rk_socket_t, const void *, size_t);
=20
-ssize_t ROKEN_LIB_FUNCTION net_read (int, void *, size_t);
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+    net_read (rk_socket_t, void *, size_t);
=20
-int ROKEN_LIB_FUNCTION issuid(void);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+    issuid(void);
=20
 #ifndef HAVE_STRUCT_WINSIZE
 struct winsize {
@@ -428,43 +776,53 @@
 };
 #endif
=20
-int ROKEN_LIB_FUNCTION get_window_size(int fd, struct winsize *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL get_window_size(int fd, int *, int *=
);
=20
 #ifndef HAVE_VSYSLOG
-void ROKEN_LIB_FUNCTION vsyslog(int, const char *, va_list);
+#define vsyslog rk_vsyslog
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL vsyslog(int, const char *, va_list);
+#endif
+
+#ifndef HAVE_GETOPT
+#define getopt rk_getopt
+#define optarg rk_optarg
+#define optind rk_optind
+#define opterr rk_opterr
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+getopt(int nargc, char * const *nargv, const char *ostr);
 #endif
=20
 #if !HAVE_DECL_OPTARG
-extern char *optarg;
+ROKEN_LIB_VARIABLE extern char *optarg;
 #endif
 #if !HAVE_DECL_OPTIND
-extern int optind;
+ROKEN_LIB_VARIABLE extern int optind;
 #endif
 #if !HAVE_DECL_OPTERR
-extern int opterr;
-#endif
-
-#if !HAVE_DECL_ENVIRON
-extern char **environ;
+ROKEN_LIB_VARIABLE extern int opterr;
 #endif
=20
 #ifndef HAVE_GETIPNODEBYNAME
-struct hostent * ROKEN_LIB_FUNCTION
+#define getipnodebyname rk_getipnodebyname
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
 getipnodebyname (const char *, int, int, int *);
 #endif
=20
 #ifndef HAVE_GETIPNODEBYADDR
-struct hostent * ROKEN_LIB_FUNCTION
+#define getipnodebyaddr rk_getipnodebyaddr
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
 getipnodebyaddr (const void *, size_t, int, int *);
 #endif
=20
 #ifndef HAVE_FREEHOSTENT
-void ROKEN_LIB_FUNCTION
+#define freehostent rk_freehostent
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 freehostent (struct hostent *);
 #endif
=20
 #ifndef HAVE_COPYHOSTENT
-struct hostent * ROKEN_LIB_FUNCTION
+#define copyhostent rk_copyhostent
+ROKEN_LIB_FUNCTION struct hostent * ROKEN_LIB_CALL
 copyhostent (const struct hostent *);
 #endif
=20
@@ -531,7 +889,8 @@
 #endif
=20
 #ifndef HAVE_GETADDRINFO
-int ROKEN_LIB_FUNCTION
+#define getaddrinfo rk_getaddrinfo
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getaddrinfo(const char *,
 	    const char *,
 	    const struct addrinfo *,
@@ -539,7 +898,8 @@
 #endif
=20
 #ifndef HAVE_GETNAMEINFO
-int ROKEN_LIB_FUNCTION
+#define getnameinfo rk_getnameinfo
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getnameinfo(const struct sockaddr *, socklen_t,
 		char *, size_t,
 		char *, size_t,
@@ -547,73 +907,80 @@
 #endif
=20
 #ifndef HAVE_FREEADDRINFO
-void ROKEN_LIB_FUNCTION
+#define freeaddrinfo rk_freeaddrinfo
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 freeaddrinfo(struct addrinfo *);
 #endif
=20
 #ifndef HAVE_GAI_STRERROR
-const char * ROKEN_LIB_FUNCTION
+#define gai_strerror rk_gai_strerror
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL
 gai_strerror(int);
 #endif
=20
-int ROKEN_LIB_FUNCTION
+#ifdef NO_SLEEP
+
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
+sleep(unsigned int seconds);
+
+#endif
+
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 getnameinfo_verified(const struct sockaddr *, socklen_t,
 		     char *, size_t,
 		     char *, size_t,
 		     int);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 roken_getaddrinfo_hostspec(const char *, int, struct addrinfo **);=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 roken_getaddrinfo_hostspec2(const char *, int, int, struct addrinfo **);
=20
 #ifndef HAVE_STRFTIME
-size_t ROKEN_LIB_FUNCTION
+#define strftime rk_strftime
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 strftime (char *, size_t, const char *, const struct tm *);
 #endif
=20
 #ifndef HAVE_STRPTIME
-char * ROKEN_LIB_FUNCTION
+#define strptime rk_strptime
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strptime (const char *, const char *, struct tm *);
 #endif
=20
+#ifndef HAVE_GETTIMEOFDAY
+#define gettimeofday rk_gettimeofday
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+gettimeofday (struct timeval *, void *);
+#endif
+
 #ifndef HAVE_EMALLOC
-void * ROKEN_LIB_FUNCTION emalloc (size_t);
+#define emalloc rk_emalloc
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL emalloc (size_t);
 #endif
 #ifndef HAVE_ECALLOC
-void * ROKEN_LIB_FUNCTION ecalloc(size_t, size_t);
+#define ecalloc rk_ecalloc
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL ecalloc(size_t, size_t);
 #endif
 #ifndef HAVE_EREALLOC
-void * ROKEN_LIB_FUNCTION erealloc (void *, size_t);
+#define erealloc rk_erealloc
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL erealloc (void *, size_t);
 #endif
 #ifndef HAVE_ESTRDUP
-char * ROKEN_LIB_FUNCTION estrdup (const char *);
+#define estrdup rk_estrdup
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL estrdup (const char *);
 #endif
=20
 /*
  * kludges and such
  */
=20
-#if 1
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 roken_gethostby_setup(const char*, const char*);
-struct hostent* ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL
 roken_gethostbyname(const char*);
-struct hostent* ROKEN_LIB_FUNCTION=20
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL=20
 roken_gethostbyaddr(const void*, size_t, int);
-#else
-#ifdef GETHOSTBYNAME_PROTO_COMPATIBLE
-#define roken_gethostbyname(x) gethostbyname(x)
-#else
-#define roken_gethostbyname(x) gethostbyname((char *)x)
-#endif
-
-#ifdef GETHOSTBYADDR_PROTO_COMPATIBLE
-#define roken_gethostbyaddr(a, l, t) gethostbyaddr(a, l, t)
-#else
-#define roken_gethostbyaddr(a, l, t) gethostbyaddr((char *)a, l, t)
-#endif
-#endif
=20
 #ifdef GETSERVBYNAME_PROTO_COMPATIBLE
 #define roken_getservbyname(x,y) getservbyname(x,y)
@@ -634,71 +1001,140 @@
 #endif
=20
 #ifndef HAVE_SETPROGNAME
-void ROKEN_LIB_FUNCTION setprogname(const char *);
+#define setprogname rk_setprogname
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL setprogname(const char *);
 #endif
=20
 #ifndef HAVE_GETPROGNAME
-const char * ROKEN_LIB_FUNCTION getprogname(void);
+#define getprogname rk_getprogname
+ROKEN_LIB_FUNCTION const char * ROKEN_LIB_CALL getprogname(void);
 #endif
=20
 #if !defined(HAVE_SETPROGNAME) && !defined(HAVE_GETPROGNAME) && !HAVE_DECL=
___PROGNAME
 extern const char *__progname;
 #endif
=20
-void ROKEN_LIB_FUNCTION mini_inetd_addrinfo (struct addrinfo*);
-void ROKEN_LIB_FUNCTION mini_inetd (int);
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd_addrinfo (struct addrinfo*, rk_socket_t *);
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+mini_inetd (int, rk_socket_t *);
=20
 #ifndef HAVE_LOCALTIME_R
-struct tm * ROKEN_LIB_FUNCTION
+#define localtime_r rk_localtime_r
+ROKEN_LIB_FUNCTION struct tm * ROKEN_LIB_CALL
 localtime_r(const time_t *, struct tm *);
 #endif
=20
 #if !defined(HAVE_STRSVIS) || defined(NEED_STRSVIS_PROTO)
-int ROKEN_LIB_FUNCTION
+#ifndef HAVE_STRSVIS
+#define strsvis rk_strsvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 strsvis(char *, const char *, int, const char *);
 #endif
=20
+#if !defined(HAVE_STRSVISX) || defined(NEED_STRSVISX_PROTO)
+#ifndef HAVE_STRSVISX
+#define strsvisx rk_strsvisx
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+strsvisx(char *, const char *, size_t, int, const char *);
+#endif
+
 #if !defined(HAVE_STRUNVIS) || defined(NEED_STRUNVIS_PROTO)
-int ROKEN_LIB_FUNCTION
+#ifndef HAVE_STRUNVIS
+#define strunvis rk_strunvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 strunvis(char *, const char *);
 #endif
=20
 #if !defined(HAVE_STRVIS) || defined(NEED_STRVIS_PROTO)
-int ROKEN_LIB_FUNCTION
+#ifndef HAVE_STRVIS
+#define strvis rk_strvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 strvis(char *, const char *, int);
 #endif
=20
 #if !defined(HAVE_STRVISX) || defined(NEED_STRVISX_PROTO)
-int ROKEN_LIB_FUNCTION
+#ifndef HAVE_STRVISX
+#define strvisx rk_strvisx
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 strvisx(char *, const char *, size_t, int);
 #endif
=20
 #if !defined(HAVE_SVIS) || defined(NEED_SVIS_PROTO)
-char * ROKEN_LIB_FUNCTION
+#ifndef HAVE_SVIS
+#define svis rk_svis
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 svis(char *, int, int, int, const char *);
 #endif
=20
 #if !defined(HAVE_UNVIS) || defined(NEED_UNVIS_PROTO)
-int ROKEN_LIB_FUNCTION
+#ifndef HAVE_UNVIS
+#define unvis rk_unvis
+#endif
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unvis(char *, int, int *, int);
 #endif
=20
 #if !defined(HAVE_VIS) || defined(NEED_VIS_PROTO)
-char * ROKEN_LIB_FUNCTION
+#ifndef HAVE_VIS
+#define vis rk_vis
+#endif
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 vis(char *, int, int, int);
 #endif
=20
 #if !defined(HAVE_CLOSEFROM)
-int ROKEN_LIB_FUNCTION
+#define closefrom rk_closefrom
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 closefrom(int);
 #endif
=20
 #if !defined(HAVE_TIMEGM)
 #define timegm rk_timegm
-time_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
 rk_timegm(struct tm *tm);
 #endif
=20
+#ifdef NEED_QSORT
+#define qsort rk_qsort
+void
+rk_qsort(void *, size_t, size_t, int (*)(const void *, const void *));
+#endif
+
+#if defined(HAVE_ARC4RANDOM)
+#define rk_random() arc4random()
+#elif defined(HAVE_RANDOM)
+#define rk_random() random()
+#else
+#define rk_random() rand()
+#endif
+
+#ifndef HAVE_TDELETE
+#define tdelete(a,b,c) rk_tdelete(a,b,c)
+#endif
+#ifndef HAVE_TFIND
+#define tfind(a,b,c) rk_tfind(a,b,c)
+#endif
+#ifndef HAVE_TSEARCH
+#define tsearch(a,b,c) rk_tsearch(a,b,c)
+#endif
+#ifndef HAVE_TWALK
+#define twalk(a,b) rk_twalk(a,b)
+#endif
+
+#if defined(__linux__) && defined(SOCK_CLOEXEC) && !defined(SOCKET_WRAPPER=
_REPLACE) && !defined(__SOCKET_WRAPPER_H__)
+#undef socket
+#define socket(_fam,_type,_prot) rk_socket(_fam,_type,_prot)
+int ROKEN_LIB_FUNCTION rk_socket(int, int, int);
+#endif
+
 #ifdef SOCKET_WRAPPER_REPLACE
 #include <socket_wrapper.h>
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/roken_ge=
thostby.c
--- a/head/crypto/heimdal/lib/roken/roken_gethostby.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/crypto/heimdal/lib/roken/roken_gethostby.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: roken_gethostby.c 21157 2007-06-18 22:03:13Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -69,11 +66,13 @@
     memset(&dns_addr, 0, sizeof(dns_addr));
     if(dns_req)
 	free(dns_req);
+    dns_req =3D NULL;
     if(proxy_host) {
 	if(make_address(proxy_host, &dns_addr.sin_addr) !=3D 0)
 	    return -1;
 	dns_addr.sin_port =3D htons(proxy_port);
-	asprintf(&dns_req, "http://%s:%d%s", dns_host, dns_port, dns_path);
+	if (asprintf(&dns_req, "http://%s:%d%s", dns_host, dns_port, dns_path) < =
0)
+	    return -1;
     } else {
 	if(make_address(dns_host, &dns_addr.sin_addr) !=3D 0)
 	    return -1;
@@ -98,25 +97,25 @@
 	*port =3D def_port;
     p =3D strchr(p ? p : *host, '/');
     if(p) {
-	if(path)=20
+	if(path)
 	    *path =3D strdup(p);
 	*p =3D '\0';
     }else
-	if(path)=20
+	if(path)
 	    *path =3D NULL;
 }
=20
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 roken_gethostby_setup(const char *proxy_spec, const char *dns_spec)
 {
     char *proxy_host =3D NULL;
     int proxy_port =3D 0;
     char *dns_host, *dns_path;
     int dns_port;
-   =20
+
     int ret =3D -1;
-   =20
+
     split_spec(dns_spec, &dns_host, &dns_port, &dns_path, 80);
     if(dns_path =3D=3D NULL)
 	goto out;
@@ -129,7 +128,7 @@
     free(dns_path);
     return ret;
 }
-   =20
+
=20
 /* Try to lookup a name or an ip-address using http as transport
    mechanism. See the end of this file for an example program. */
@@ -138,16 +137,18 @@
 {
     int s;
     struct sockaddr_in addr;
-    char *request;
+    char *request =3D NULL;
     char buf[1024];
     int offset =3D 0;
     int n;
     char *p, *foo;
-   =20
+    size_t len;
+
     if(dns_addr.sin_family =3D=3D 0)
 	return NULL; /* no configured host */
     addr =3D dns_addr;
-    asprintf(&request, "GET %s?%s HTTP/1.0\r\n\r\n", dns_req, hostname);
+    if (asprintf(&request, "GET %s?%s HTTP/1.0\r\n\r\n", dns_req, hostname=
) < 0)
+	return NULL;
     if(request =3D=3D NULL)
 	return NULL;
     s  =3D socket(AF_INET, SOCK_STREAM, 0);
@@ -160,7 +161,9 @@
 	free(request);
 	return NULL;
     }
-    if(write(s, request, strlen(request)) !=3D strlen(request)) {
+
+    len =3D strlen(request);
+    if(write(s, request, len) !=3D (ssize_t)len) {
 	close(s);
 	free(request);
 	return NULL;
@@ -188,12 +191,12 @@
 	static char addrs[4 * MAX_ADDRS];
 	static char *addr_list[MAX_ADDRS + 1];
 	int num_addrs =3D 0;
-=09
+
 	he.h_name =3D p;
 	he.h_aliases =3D NULL;
 	he.h_addrtype =3D AF_INET;
 	he.h_length =3D 4;
-=09
+
 	while((p =3D strtok_r(NULL, " \t\r\n", &foo)) && num_addrs < MAX_ADDRS) {
 	    struct in_addr ip;
 	    inet_aton(p, &ip);
@@ -210,7 +213,7 @@
     }
 }
=20
-struct hostent*
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL
 roken_gethostbyname(const char *hostname)
 {
     struct hostent *he;
@@ -220,7 +223,7 @@
     return roken_gethostby(hostname);
 }
=20
-struct hostent* ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct hostent* ROKEN_LIB_CALL
 roken_gethostbyaddr(const void *addr, size_t len, int type)
 {
     struct in_addr a;
@@ -253,7 +256,7 @@
     char host[MAXHOSTNAMELEN];
     int i;
     struct hostent *he;
-   =20
+
     printf("Content-type: text/plain\n\n");
     if(query =3D=3D NULL)
 	exit(0);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/rtbl.3
--- a/head/crypto/heimdal/lib/roken/rtbl.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/rtbl.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
+.\" Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
 .\" (Royal Institute of Technology, Stockholm, Sweden).
 .\" All rights reserved.
 .\"
@@ -28,7 +28,7 @@
 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
-.\" $Id: rtbl.3 22088 2007-11-25 14:10:15Z lha $
+.\" $Id$
 .\"
 .Dd June 26, 2004
 .Dt RTBL 3
@@ -89,7 +89,7 @@
 or
 .Xr netstat 1 ,
 where you have a fixed number of columns, but don't know the column
-widthds before hand.
+widths before hand.
 .Pp
 A table is created with
 .Fn rtbl_create
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/rtbl.c
--- a/head/crypto/heimdal/lib/roken/rtbl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/rtbl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000, 2002, 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000, 2002, 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,8 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID ("$Id: rtbl.c 17758 2006-06-30 13:41:40Z lha $");
-#endif
+
 #include "roken.h"
 #include "rtbl.h"
=20
@@ -61,19 +59,19 @@
     char *column_separator;
 };
=20
-rtbl_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION rtbl_t ROKEN_LIB_CALL
 rtbl_create (void)
 {
     return calloc (1, sizeof (struct rtbl_data));
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rtbl_set_flags (rtbl_t table, unsigned int flags)
 {
     table->flags =3D flags;
 }
=20
-unsigned int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
 rtbl_get_flags (rtbl_t table)
 {
     return table->flags;
@@ -82,7 +80,7 @@
 static struct column_data *
 rtbl_get_column_by_id (rtbl_t table, unsigned int id)
 {
-    int i;
+    size_t i;
     for(i =3D 0; i < table->num_columns; i++)
 	if(table->columns[i]->column_id =3D=3D id)
 	    return table->columns[i];
@@ -92,17 +90,17 @@
 static struct column_data *
 rtbl_get_column (rtbl_t table, const char *column)
 {
-    int i;
+    size_t i;
     for(i =3D 0; i < table->num_columns; i++)
 	if(strcmp(table->columns[i]->header, column) =3D=3D 0)
 	    return table->columns[i];
     return NULL;
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rtbl_destroy (rtbl_t table)
 {
-    int i, j;
+    size_t i, j;
=20
     for (i =3D 0; i < table->num_columns; i++) {
 	struct column_data *c =3D table->columns[i];
@@ -121,8 +119,8 @@
     free (table);
 }
=20
-int ROKEN_LIB_FUNCTION
-rtbl_add_column_by_id (rtbl_t table, unsigned int id,=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rtbl_add_column_by_id (rtbl_t table, unsigned int id,
 		       const char *header, unsigned int flags)
 {
     struct column_data *col, **tmp;
@@ -150,13 +148,13 @@
     return 0;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column (rtbl_t table, const char *header, unsigned int flags)
 {
     return rtbl_add_column_by_id(table, 0, header, flags);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_new_row(rtbl_t table)
 {
     size_t max_rows =3D 0;
@@ -169,7 +167,7 @@
=20
 	if(table->columns[c]->num_rows =3D=3D max_rows)
 	    continue;
-	tmp =3D realloc(table->columns[c]->rows,=20
+	tmp =3D realloc(table->columns[c]->rows,
 		      max_rows * sizeof(table->columns[c]->rows));
 	if(tmp =3D=3D NULL)
 	    return ENOMEM;
@@ -185,18 +183,18 @@
 static void
 column_compute_width (rtbl_t table, struct column_data *column)
 {
-    int i;
+    size_t i;
=20
     if(table->flags & RTBL_HEADER_STYLE_NONE)
 	column->width =3D 0;
     else
 	column->width =3D strlen (column->header);
     for (i =3D 0; i < column->num_rows; i++)
-	column->width =3D max (column->width, strlen (column->rows[i].data));
+	column->width =3D max (column->width, (int) strlen (column->rows[i].data)=
);
 }
=20
 /* DEPRECATED */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_prefix (rtbl_t table, const char *prefix)
 {
     if (table->column_prefix)
@@ -207,7 +205,7 @@
     return 0;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_separator (rtbl_t table, const char *separator)
 {
     if (table->column_separator)
@@ -218,7 +216,7 @@
     return 0;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_column_prefix (rtbl_t table, const char *column,
 			const char *prefix)
 {
@@ -234,7 +232,7 @@
     return 0;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_column_affix_by_id(rtbl_t table, unsigned int id,
 			    const char *prefix, const char *suffix)
 {
@@ -303,7 +301,7 @@
     return 0;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entry_by_id (rtbl_t table, unsigned int id, const char *da=
ta)
 {
     struct column_data *c =3D rtbl_get_column_by_id (table, id);
@@ -314,7 +312,7 @@
     return add_column_entry(c, data);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entryv_by_id (rtbl_t table, unsigned int id,
 			      const char *fmt, ...)
 {
@@ -332,7 +330,7 @@
     return ret;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entry (rtbl_t table, const char *column, const char *data)
 {
     struct column_data *c =3D rtbl_get_column (table, column);
@@ -343,7 +341,7 @@
     return add_column_entry(c, data);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entryv (rtbl_t table, const char *column, const char *fmt,=
 ...)
 {
     va_list ap;
@@ -361,10 +359,10 @@
 }
=20
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_format (rtbl_t table, FILE * f)
 {
-    int i, j;
+    size_t i, j;
=20
     for (i =3D 0; i < table->num_columns; i++)
 	column_compute_width (table, table->columns[i]);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/rtbl.h
--- a/head/crypto/heimdal/lib/roken/rtbl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/rtbl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 2000,2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 2000,2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -30,16 +30,18 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-/* $Id: rtbl.h 17760 2006-06-30 13:42:39Z lha $ */
+/* $Id$ */
=20
 #ifndef __rtbl_h__
 #define __rtbl_h__
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
@@ -60,55 +62,55 @@
 /* flags */
 #define RTBL_HEADER_STYLE_NONE	1
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column (rtbl_t, const char*, unsigned int);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_by_id (rtbl_t, unsigned int, const char*, unsigned int);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entryv_by_id (rtbl_t table, unsigned int id,
 			      const char *fmt, ...)
 	__attribute__ ((format (printf, 3, 0)));
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entry (rtbl_t, const char*, const char*);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entryv (rtbl_t, const char*, const char*, ...)
 	__attribute__ ((format (printf, 3, 0)));
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_add_column_entry_by_id (rtbl_t, unsigned int, const char*);
=20
-rtbl_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION rtbl_t ROKEN_LIB_CALL
 rtbl_create (void);
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rtbl_destroy (rtbl_t);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_format (rtbl_t, FILE*);
=20
-unsigned int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION unsigned int ROKEN_LIB_CALL
 rtbl_get_flags (rtbl_t);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_new_row (rtbl_t);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_column_affix_by_id (rtbl_t, unsigned int, const char*, const char=
*);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_column_prefix (rtbl_t, const char*, const char*);
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rtbl_set_flags (rtbl_t, unsigned int);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_prefix (rtbl_t, const char*);
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rtbl_set_separator (rtbl_t, const char*);
=20
 #ifdef __cplusplus
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/sendmsg.c
--- a/head/crypto/heimdal/lib/roken/sendmsg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/sendmsg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,15 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: sendmsg.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-ssize_t ROKEN_LIB_FUNCTION
-sendmsg(int s, const struct msghdr *msg, int flags)
+#ifndef _WIN32
+
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+sendmsg(rk_socket_t s, const struct msghdr *msg, int flags)
 {
     ssize_t ret;
     size_t tot =3D 0;
@@ -63,3 +62,87 @@
     free (buf);
     return ret;
 }
+
+#else /* _WIN32 */
+
+/***********************************************************************
+ * Copyright (c) 2009, Secure Endpoints Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in
+ *   the documentation and/or other materials provided with the
+ *   distribution.
+ *
+ * - Neither the name of Secure Endpoints Inc. nor the names of its
+ *   contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ **********************************************************************/
+
+/**
+ * Implementation of sendmsg() for WIN32
+ *
+ * We are using a contrived definition of msghdr which actually uses
+ * an array of ::_WSABUF structures instead of ::iovec .  This allows
+ * us to call WSASend directly using the given ::msghdr instead of
+ * having to allocate another array of ::_WSABUF and copying data for
+ * each call.
+ *
+ * Limitations:
+ *
+ * - msg->msg_name is ignored.  So is msg->control.
+ * - WSASend() only supports ::MSG_DONTROUTE, ::MSG_OOB and
+ *   ::MSG_PARTIAL.
+ *
+ * @param[in] s The socket to use.
+ * @param[in] msg The message
+ * @param[in] flags Flags.  A combination of ::MSG_DONTROUTE,
+ *  ::MSG_OOB and ::MSG_PARTIAL
+ *
+ * @return The number of bytes sent, on success.  Or -1 on error.
+ */
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
+sendmsg_w32(rk_socket_t s, const struct msghdr * msg, int flags)
+{
+    int srv;
+    DWORD num_bytes_sent =3D 0;
+
+    /* TODO: For _WIN32_WINNT >=3D 0x0600 we can use WSASendMsg using
+       WSAMSG which is a much more direct analogue to sendmsg(). */
+
+    srv =3D WSASend(s, msg->msg_iov, msg->msg_iovlen,
+		  &num_bytes_sent, flags, NULL, NULL);
+
+    if (srv =3D=3D 0)
+	return (int) num_bytes_sent;
+
+    /* srv =3D=3D SOCKET_ERROR and WSAGetLastError() =3D=3D WSA_IO_PENDING
+       indicates that a non-blocking transfer has been scheduled.
+       We'll have to check for that if we ever support non-blocking
+       I/O. */
+
+    return -1;
+}
+
+#endif /* !_WIN32 */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/setegid.c
--- a/head/crypto/heimdal/lib/roken/setegid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/setegid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: setegid.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
@@ -42,7 +39,7 @@
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 setegid(gid_t egid)
 {
 #ifdef HAVE_SETREGID
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/setenv.c
--- a/head/crypto/heimdal/lib/roken/setenv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/setenv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: setenv.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -47,20 +44,31 @@
  * anyway.
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 setenv(const char *var, const char *val, int rewrite)
 {
-    char *t;
+#ifndef _WIN32
+    char *t =3D NULL;
=20
     if (!rewrite && getenv(var) !=3D 0)
 	return 0;
- =20
-    asprintf (&t, "%s=3D%s", var, val);
-    if (t =3D=3D NULL)
+
+    if (asprintf (&t, "%s=3D%s", var, val) < 0 || t =3D=3D NULL)
 	return -1;
=20
     if (putenv(t) =3D=3D 0)
 	return 0;
     else
 	return -1;
+#else  /* Win32 */
+    char dummy[8];
+
+    if (!rewrite && GetEnvironmentVariable(var, dummy, sizeof(dummy)/sizeo=
f(char)) !=3D 0)
+	return 0;
+
+    if (SetEnvironmentVariable(var, val) =3D=3D 0)
+	return -1;
+    else
+	return 0;
+#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/seteuid.c
--- a/head/crypto/heimdal/lib/roken/seteuid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/seteuid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: seteuid.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
@@ -42,7 +39,7 @@
=20
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 seteuid(uid_t euid)
 {
 #ifdef HAVE_SETREUID
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/setprogn=
ame.c
--- a/head/crypto/heimdal/lib/roken/setprogname.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/setprogname.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-2004 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995-2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: setprogname.c 15955 2005-08-23 10:19:20Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -43,19 +40,52 @@
 #endif
=20
 #ifndef HAVE_SETPROGNAME
-void ROKEN_LIB_FUNCTION
+
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 setprogname(const char *argv0)
 {
+
 #ifndef HAVE___PROGNAME
+
     const char *p;
     if(argv0 =3D=3D NULL)
 	return;
     p =3D strrchr(argv0, '/');
+
+#ifdef BACKSLASH_PATH_DELIM
+    {
+        const char * pb;
+
+        pb =3D strrchr((p !=3D NULL)? p : argv0, '\\');
+        if (pb !=3D NULL)
+            p =3D pb;
+    }
+#endif
+
     if(p =3D=3D NULL)
 	p =3D argv0;
     else
 	p++;
+
+#ifdef _WIN32
+    {
+        char * fn =3D strdup(p);
+        char * ext;
+
+        strlwr(fn);
+        ext =3D strrchr(fn, '.');
+        if (ext !=3D NULL && !strcmp(ext, ".exe"))
+            *ext =3D '\0';
+
+        __progname =3D fn;
+    }
+#else
+
     __progname =3D p;
+
 #endif
+
+#endif  /* HAVE___PROGNAME */
 }
+
 #endif /* HAVE_SETPROGNAME */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/signal.c
--- a/head/crypto/heimdal/lib/roken/signal.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/signal.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: signal.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <signal.h>
 #include "roken.h"
@@ -50,7 +47,7 @@
  * Do we need any extra hacks for SIGCLD and/or SIGCHLD?
  */
=20
-SigAction ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION SigAction ROKEN_LIB_CALL
 signal(int iSig, SigAction pAction)
 {
     struct sigaction saNew, saOld;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/simple_e=
xec.c
--- a/head/crypto/heimdal/lib/roken/simple_exec.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/simple_exec.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1998 - 2001, 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2001, 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: simple_exec.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdarg.h>
 #include <stdlib.h>
@@ -55,13 +52,13 @@
 #define EX_NOTFOUND	127
=20
 /* return values:
-   -1   on `unspecified' system errors
-   -2   on fork failures
-   -3   on waitpid errors
-   -4   exec timeout
+   SE_E_UNSPECIFIED   on `unspecified' system errors
+   SE_E_FORKFAILED    on fork failures
+   SE_E_WAITPIDFAILED on waitpid errors
+   SE_E_EXECTIMEOUT   exec timeout
    0-   is return value from subprocess
-   126  if the program couldn't be executed
-   127  if the program couldn't be found
+   SE_E_NOEXEC        if the program couldn't be executed
+   SE_E_NOTFOUND      if the program couldn't be found
    128- is 128 + signal that killed subprocess
=20
    possible values `func' can return:
@@ -81,8 +78,8 @@
     SIGRETURN(0);
 }
=20
-int ROKEN_LIB_FUNCTION
-wait_for_process_timed(pid_t pid, time_t (*func)(void *),=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+wait_for_process_timed(pid_t pid, time_t (*func)(void *),
 		       void *ptr, time_t timeout)
 {
     RETSIGTYPE (*old_func)(int sig) =3D NULL;
@@ -101,7 +98,7 @@
=20
 	while(waitpid(pid, &status, 0) < 0) {
 	    if (errno !=3D EINTR) {
-		ret =3D -3;
+		ret =3D SE_E_WAITPIDFAILED;
 		goto out;
 	    }
 	    if (func =3D=3D NULL)
@@ -113,7 +110,7 @@
 		kill(pid, SIGTERM);
 		continue;
 	    } else if (timeout =3D=3D (time_t)-2) {
-		ret =3D -4;
+		ret =3D SE_E_EXECTIMEOUT;
 		goto out;
 	    }
 	    alarm(timeout);
@@ -137,14 +134,14 @@
     return ret;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 wait_for_process(pid_t pid)
 {
     return wait_for_process_timed(pid, NULL, NULL, 0);
 }
=20
-int ROKEN_LIB_FUNCTION
-pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd,=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd,
 	   const char *file, ...)
 {
     int in_fd[2], out_fd[2], err_fd[2];
@@ -214,7 +211,7 @@
 	    close(err_fd[0]);
 	    close(err_fd[1]);
 	}
-	return -2;
+	return SE_E_FORKFAILED;
     default:
 	if(stdin_fd !=3D NULL) {
 	    close(in_fd[0]);
@@ -232,52 +229,52 @@
     return pid;
 }
=20
-int ROKEN_LIB_FUNCTION
-simple_execvp_timed(const char *file, char *const args[],=20
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+simple_execvp_timed(const char *file, char *const args[],
 		    time_t (*func)(void *), void *ptr, time_t timeout)
 {
     pid_t pid =3D fork();
     switch(pid){
     case -1:
-	return -2;
+	return SE_E_FORKFAILED;
     case 0:
 	execvp(file, args);
 	exit((errno =3D=3D ENOENT) ? EX_NOTFOUND : EX_NOEXEC);
-    default:=20
+    default:
 	return wait_for_process_timed(pid, func, ptr, timeout);
     }
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execvp(const char *file, char *const args[])
 {
     return simple_execvp_timed(file, args, NULL, NULL, 0);
 }
=20
 /* gee, I'd like a execvpe */
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execve_timed(const char *file, char *const args[], char *const envp=
[],
 		    time_t (*func)(void *), void *ptr, time_t timeout)
 {
     pid_t pid =3D fork();
     switch(pid){
     case -1:
-	return -2;
+	return SE_E_FORKFAILED;
     case 0:
 	execve(file, args, envp);
 	exit((errno =3D=3D ENOENT) ? EX_NOTFOUND : EX_NOEXEC);
-    default:=20
+    default:
 	return wait_for_process_timed(pid, func, ptr, timeout);
     }
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execve(const char *file, char *const args[], char *const envp[])
 {
     return simple_execve_timed(file, args, envp, NULL, NULL, 0);
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execlp(const char *file, ...)
 {
     va_list ap;
@@ -288,13 +285,13 @@
     argv =3D vstrcollect(&ap);
     va_end(ap);
     if(argv =3D=3D NULL)
-	return -1;
+	return SE_E_UNSPECIFIED;
     ret =3D simple_execvp(file, argv);
     free(argv);
     return ret;
 }
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 simple_execle(const char *file, ... /* ,char *const envp[] */)
 {
     va_list ap;
@@ -307,25 +304,8 @@
     envp =3D va_arg(ap, char **);
     va_end(ap);
     if(argv =3D=3D NULL)
-	return -1;
+	return SE_E_UNSPECIFIED;
     ret =3D simple_execve(file, argv, envp);
     free(argv);
     return ret;
 }
-
-int ROKEN_LIB_FUNCTION
-simple_execl(const char *file, ...)=20
-{
-    va_list ap;
-    char **argv;
-    int ret;
-
-    va_start(ap, file);
-    argv =3D vstrcollect(&ap);
-    va_end(ap);
-    if(argv =3D=3D NULL)
-	return -1;
-    ret =3D simple_execve(file, argv, environ);
-    free(argv);
-    return ret;
-}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/snprintf=
-test.c
--- a/head/crypto/heimdal/lib/roken/snprintf-test.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/crypto/heimdal/lib/roken/snprintf-test.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2000 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -30,15 +30,10 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
-#include "snprintf-test.h"
 #include "roken.h"
 #include <limits.h>
=20
-RCSID("$Id: snprintf-test.c 21627 2007-07-17 10:53:17Z lha $");
-
 static int
 try (const char *format, ...)
 {
@@ -47,7 +42,7 @@
     char buf1[256], buf2[256];
=20
     va_start (ap, format);
-    ret =3D vsnprintf (buf1, sizeof(buf1), format, ap);
+    ret =3D rk_vsnprintf (buf1, sizeof(buf1), format, ap);
     if (ret >=3D sizeof(buf1))
 	errx (1, "increase buf and try again");
     va_end (ap);
@@ -224,7 +219,7 @@
 static int
 test_null (void)
 {
-    return snprintf (NULL, 0, "foo") !=3D 3;
+    return rk_snprintf (NULL, 0, "foo") !=3D 3;
 }
=20
 static int
@@ -242,7 +237,7 @@
 	tot +=3D try("%zX", sizet_values[i]);
 #else
 	char buf[256];
-	snprintf(buf, sizeof(buf), "%zu", sizet_values[i]);
+	rk_snprintf(buf, sizeof(buf), "%zu", sizet_values[i]);
 	if (strcmp(buf, result[i]) !=3D 0) {
 	    printf("%s !=3D %s", buf, result[i]);
 	    tot++;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/snprintf=
.c
--- a/head/crypto/heimdal/lib/roken/snprintf.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/snprintf.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-2003 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2003 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,13 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: snprintf.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-#if defined(TEST_SNPRINTF)
-#include "snprintf-test.h"
-#endif /* TEST_SNPRINTF */
 #include <stdio.h>
 #include <stdarg.h>
 #include <stdlib.h>
@@ -125,10 +119,10 @@
=20
=20
=20
-static int
+static size_t
 pad(struct snprintf_state *state, int width, char c)
 {
-    int len =3D 0;
+    size_t len =3D 0;
     while(width-- > 0){
 	(*state->append_char)(state,  c);
 	++len;
@@ -186,9 +180,9 @@
 	signchar =3D ' ';
     else
 	signchar =3D '\0';
-   =20
+
     if((flags & alternate_flag) && base =3D=3D 8) {
-	/* if necessary, increase the precision to=20
+	/* if necessary, increase the precision to
 	   make first digit a zero */
=20
 	/* XXX C99 claims (regarding # and %o) that "if the value and
@@ -196,7 +190,7 @@
            no such wording for %x. This would mean that %#.o would
            output "0", but %#.x "". This does not make sense, and is
            also not what other printf implementations are doing. */
-=09
+
 	if(prec <=3D nlen && nstr[nstart] !=3D '0' && nstr[nstart] !=3D '\0')
 	    prec =3D nlen + 1;
     }
@@ -214,13 +208,13 @@
 	    width -=3D prec;
 	else
 	    width -=3D nlen;
-=09
+
 	if(use_alternative(flags, num, base))
 	    width -=3D 2;
-=09
+
 	if(signchar !=3D '\0')
 	    width--;
-=09
+
 	/* pad to width */
 	len +=3D pad(state, width, ' ');
     }
@@ -242,12 +236,12 @@
     } else
 	/* pad to prec with zeros */
 	len +=3D pad(state, prec - nlen, '0');
-=09
+
     while(nstr[nstart] !=3D '\0') {
 	(*state->append_char)(state, nstr[nstart++]);
 	++len;
     }
-=09
+
     if(flags & minus_flag)
 	len +=3D pad(state, width - len, ' ');
=20
@@ -258,14 +252,14 @@
  * return length
  */
=20
-static int
+static size_t
 append_string (struct snprintf_state *state,
 	       const unsigned char *arg,
 	       int width,
 	       int prec,
 	       int flags)
 {
-    int len =3D 0;
+    size_t len =3D 0;
=20
     if(arg =3D=3D NULL)
 	arg =3D (const unsigned char*)"(null)";
@@ -350,12 +344,12 @@
  * zyxprintf - return length, as snprintf
  */
=20
-static int
+static size_t
 xyzprintf (struct snprintf_state *state, const char *char_format, va_list =
ap)
 {
     const unsigned char *format =3D (const unsigned char *)char_format;
     unsigned char c;
-    int len =3D 0;
+    size_t len =3D 0;
=20
     while((c =3D *format++)) {
 	if (c =3D=3D '%') {
@@ -384,7 +378,7 @@
 		else
 		    break;
 	    }
-     =20
+
 	    if((flags & space_flag) && (flags & plus_flag))
 		flags ^=3D space_flag;
=20
@@ -446,7 +440,7 @@
 		len +=3D append_string(state,
 				     va_arg(ap, unsigned char*),
 				     width,
-				     prec,=20
+				     prec,
 				     flags);
 		break;
 	    case 'd' :
@@ -504,7 +498,7 @@
 		break;
 	    }
 	    case 'p' : {
-		unsigned long arg =3D (unsigned long)va_arg(ap, void*);
+		u_longest arg =3D (u_longest)va_arg(ap, void*);
=20
 		len +=3D append_number (state, arg, 0x10, "0123456789ABCDEF",
 				      width, prec, flags, 0);
@@ -537,8 +531,8 @@
 }
=20
 #if !defined(HAVE_SNPRINTF) || defined(TEST_SNPRINTF)
-int ROKEN_LIB_FUNCTION
-snprintf (char *str, size_t sz, const char *format, ...)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_snprintf (char *str, size_t sz, const char *format, ...)
 {
     va_list args;
     int ret;
@@ -570,8 +564,8 @@
 #endif
=20
 #if !defined(HAVE_ASPRINTF) || defined(TEST_SNPRINTF)
-int ROKEN_LIB_FUNCTION
-asprintf (char **ret, const char *format, ...)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asprintf (char **ret, const char *format, ...)
 {
     va_list args;
     int val;
@@ -602,8 +596,8 @@
 #endif
=20
 #if !defined(HAVE_ASNPRINTF) || defined(TEST_SNPRINTF)
-int ROKEN_LIB_FUNCTION
-asnprintf (char **ret, size_t max_sz, const char *format, ...)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_asnprintf (char **ret, size_t max_sz, const char *format, ...)
 {
     va_list args;
     int val;
@@ -632,8 +626,8 @@
 #endif
=20
 #if !defined(HAVE_VASPRINTF) || defined(TEST_SNPRINTF)
-int ROKEN_LIB_FUNCTION
-vasprintf (char **ret, const char *format, va_list args)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasprintf (char **ret, const char *format, va_list args)
 {
     return vasnprintf (ret, 0, format, args);
 }
@@ -641,10 +635,10 @@
=20
=20
 #if !defined(HAVE_VASNPRINTF) || defined(TEST_SNPRINTF)
-int ROKEN_LIB_FUNCTION
-vasnprintf (char **ret, size_t max_sz, const char *format, va_list args)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vasnprintf (char **ret, size_t max_sz, const char *format, va_list args)
 {
-    int st;
+    size_t st;
     struct snprintf_state state;
=20
     state.max_sz =3D max_sz;
@@ -680,8 +674,8 @@
 #endif
=20
 #if !defined(HAVE_VSNPRINTF) || defined(TEST_SNPRINTF)
-int ROKEN_LIB_FUNCTION
-vsnprintf (char *str, size_t sz, const char *format, va_list args)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_vsnprintf (char *str, size_t sz, const char *format, va_list args)
 {
     struct snprintf_state state;
     int ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/socket.c
--- a/head/crypto/heimdal/lib/roken/socket.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/socket.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: socket.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include "roken.h"
 #include <err.h>
@@ -43,7 +40,7 @@
  * Set `sa' to the unitialized address of address family `af'
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 socket_set_any (struct sockaddr *sa, int af)
 {
     switch (af) {
@@ -77,7 +74,7 @@
  * set `sa' to (`ptr', `port')
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 socket_set_address_and_port (struct sockaddr *sa, const void *ptr, int por=
t)
 {
     switch (sa->sa_family) {
@@ -111,7 +108,7 @@
  * Return the size of an address of the type in `sa'
  */
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 socket_addr_size (const struct sockaddr *sa)
 {
     switch (sa->sa_family) {
@@ -122,8 +119,7 @@
 	return sizeof(struct in6_addr);
 #endif
     default :
-	errx (1, "unknown address family %d", sa->sa_family);
-	break;
+	return 0;
     }
 }
=20
@@ -131,7 +127,7 @@
  * Return the size of a `struct sockaddr' in `sa'.
  */
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 socket_sockaddr_size (const struct sockaddr *sa)
 {
     switch (sa->sa_family) {
@@ -141,9 +137,8 @@
     case AF_INET6 :
 	return sizeof(struct sockaddr_in6);
 #endif
-    default :
-	errx (1, "unknown address family %d", sa->sa_family);
-	break;
+    default:
+	return 0;
     }
 }
=20
@@ -151,23 +146,22 @@
  * Return the binary address of `sa'.
  */
=20
-void * ROKEN_LIB_FUNCTION
-socket_get_address (struct sockaddr *sa)
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
+socket_get_address (const struct sockaddr *sa)
 {
     switch (sa->sa_family) {
     case AF_INET : {
-	struct sockaddr_in *sin4 =3D (struct sockaddr_in *)sa;
-	return &sin4->sin_addr;
+	const struct sockaddr_in *sin4 =3D (const struct sockaddr_in *)sa;
+	return rk_UNCONST(&sin4->sin_addr);
     }
 #ifdef HAVE_IPV6
     case AF_INET6 : {
-	struct sockaddr_in6 *sin6 =3D (struct sockaddr_in6 *)sa;
-	return &sin6->sin6_addr;
+	const struct sockaddr_in6 *sin6 =3D (const struct sockaddr_in6 *)sa;
+	return rk_UNCONST(&sin6->sin6_addr);
     }
 #endif
-    default :
-	errx (1, "unknown address family %d", sa->sa_family);
-	break;
+    default:
+	return NULL;
     }
 }
=20
@@ -175,7 +169,7 @@
  * Return the port number from `sa'.
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 socket_get_port (const struct sockaddr *sa)
 {
     switch (sa->sa_family) {
@@ -190,8 +184,7 @@
     }
 #endif
     default :
-	errx (1, "unknown address family %d", sa->sa_family);
-	break;
+	return 0;
     }
 }
=20
@@ -199,7 +192,7 @@
  * Set the port in `sa' to `port'.
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 socket_set_port (struct sockaddr *sa, int port)
 {
     switch (sa->sa_family) {
@@ -224,40 +217,33 @@
 /*
  * Set the range of ports to use when binding with port =3D 0.
  */
-void ROKEN_LIB_FUNCTION
-socket_set_portrange (int sock, int restr, int af)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_portrange (rk_socket_t sock, int restr, int af)
 {
 #if defined(IP_PORTRANGE)
 	if (af =3D=3D AF_INET) {
 		int on =3D restr ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT;
-		if (setsockopt (sock, IPPROTO_IP, IP_PORTRANGE, &on,
-		    sizeof(on)) < 0)
-			warn ("setsockopt IP_PORTRANGE (ignored)");
+		setsockopt (sock, IPPROTO_IP, IP_PORTRANGE, &on, sizeof(on));
 	}
 #endif
 #if defined(IPV6_PORTRANGE)
 	if (af =3D=3D AF_INET6) {
-		int on =3D restr ? IPV6_PORTRANGE_HIGH :=20
-		    IPV6_PORTRANGE_DEFAULT;
-		if (setsockopt (sock, IPPROTO_IPV6, IPV6_PORTRANGE, &on,
-		    sizeof(on)) < 0)
-			warn ("setsockopt IPV6_PORTRANGE (ignored)");
+		int on =3D restr ? IPV6_PORTRANGE_HIGH : IPV6_PORTRANGE_DEFAULT;
+		setsockopt (sock, IPPROTO_IPV6, IPV6_PORTRANGE, &on, sizeof(on));
 	}
 #endif
 }
-=09
+
 /*
  * Enable debug on `sock'.
  */
=20
-void ROKEN_LIB_FUNCTION
-socket_set_debug (int sock)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_debug (rk_socket_t sock)
 {
 #if defined(SO_DEBUG) && defined(HAVE_SETSOCKOPT)
     int on =3D 1;
-
-    if (setsockopt (sock, SOL_SOCKET, SO_DEBUG, (void *) &on, sizeof (on))=
 < 0)
-	warn ("setsockopt SO_DEBUG (ignored)");
+    setsockopt (sock, SOL_SOCKET, SO_DEBUG, (void *) &on, sizeof (on));
 #endif
 }
=20
@@ -265,13 +251,11 @@
  * Set the type-of-service of `sock' to `tos'.
  */
=20
-void ROKEN_LIB_FUNCTION
-socket_set_tos (int sock, int tos)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_tos (rk_socket_t sock, int tos)
 {
 #if defined(IP_TOS) && defined(HAVE_SETSOCKOPT)
-    if (setsockopt (sock, IPPROTO_IP, IP_TOS, (void *) &tos, sizeof (int))=
 < 0)
-	if (errno !=3D EINVAL)
-	    warn ("setsockopt TOS (ignored)");
+    setsockopt (sock, IPPROTO_IP, IP_TOS, (void *) &tos, sizeof(int));
 #endif
 }
=20
@@ -279,13 +263,11 @@
  * set the reuse of addresses on `sock' to `val'.
  */
=20
-void ROKEN_LIB_FUNCTION
-socket_set_reuseaddr (int sock, int val)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_reuseaddr (rk_socket_t sock, int val)
 {
 #if defined(SO_REUSEADDR) && defined(HAVE_SETSOCKOPT)
-    if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&val,
-		  sizeof(val)) < 0)
-	err (1, "setsockopt SO_REUSEADDR");
+    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&val, sizeof(val));
 #endif
 }
=20
@@ -293,10 +275,62 @@
  * Set the that the `sock' should bind to only IPv6 addresses.
  */
=20
-void ROKEN_LIB_FUNCTION
-socket_set_ipv6only (int sock, int val)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+socket_set_ipv6only (rk_socket_t sock, int val)
 {
 #if defined(IPV6_V6ONLY) && defined(HAVE_SETSOCKOPT)
     setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&val, sizeof(val));
 #endif
 }
+
+/**
+ * Create a file descriptor from a socket
+ *
+ * While the socket handle in \a sock can be used with WinSock
+ * functions after calling socket_to_fd(), it should not be closed
+ * with rk_closesocket().  The socket will be closed when the associated
+ * file descriptor is closed.
+ */
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+socket_to_fd(rk_socket_t sock, int flags)
+{
+#ifndef _WIN32
+    return sock;
+#else
+    return _open_osfhandle((intptr_t) sock, flags);
+#endif
+}
+
+#ifdef HAVE_WINSOCK
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_SOCK_IOCTL(SOCKET s, long cmd, int * argp) {
+    u_long ul =3D (argp)? *argp : 0;
+    int rv;
+
+    rv =3D ioctlsocket(s, cmd, &ul);
+    if (argp)
+	*argp =3D (int) ul;
+    return rv;
+}
+#endif
+
+#ifndef HEIMDAL_SMALLER
+#undef socket
+
+int rk_socket(int, int, int);
+
+int
+rk_socket(int domain, int type, int protocol)
+{
+    int s;
+    s =3D socket (domain, type, protocol);
+#ifdef SOCK_CLOEXEC
+    if ((SOCK_CLOEXEC & type) && s < 0 && errno =3D=3D EINVAL) {
+	type &=3D ~SOCK_CLOEXEC;
+	s =3D socket (domain, type, protocol);
+    }
+#endif
+    return s;
+}
+
+#endif /* HEIMDAL_SMALLER */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/socket_w=
rapper.c
--- a/head/crypto/heimdal/lib/roken/socket_wrapper.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/roken/socket_wrapper.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -3,22 +3,22 @@
  * Copyright (C) Stefan Metzmacher 2006 <metze at samba.org>
  *
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the author nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -59,9 +59,7 @@
=20
 #else /* _SAMBA_BUILD_ */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #undef SOCKET_WRAPPER_REPLACE
=20
 #include <sys/types.h>
@@ -131,7 +129,7 @@
=20
 /* LD_PRELOAD doesn't work yet, so REWRITE_CALLS is all we support
  * for now */
-#define REWRITE_CALLS=20
+#define REWRITE_CALLS
=20
 #ifdef REWRITE_CALLS
 #define real_accept accept
@@ -161,8 +159,8 @@
=20
 /* we need to use a very terse format here as IRIX 6.4 silently
    truncates names to 16 chars, so if we use a longer name then we
-   can't tell which port a packet came from with recvfrom()=20
-  =20
+   can't tell which port a packet came from with recvfrom()
+
    with this format we have 8 chars left for the directory name
 */
 #define SOCKET_FORMAT "%c%02X%04X"
@@ -298,7 +296,7 @@
 	case SOCKET_TYPE_CHAR_TCP:
 	case SOCKET_TYPE_CHAR_UDP: {
 		struct sockaddr_in *in2 =3D (struct sockaddr_in *)in;
-	=09
+
 		if ((*len) < sizeof(*in2)) {
 		    errno =3D EINVAL;
 		    return -1;
@@ -316,7 +314,7 @@
 	case SOCKET_TYPE_CHAR_TCP_V6:
 	case SOCKET_TYPE_CHAR_UDP_V6: {
 		struct sockaddr_in6 *in2 =3D (struct sockaddr_in6 *)in;
-	=09
+
 		if ((*len) < sizeof(*in2)) {
 			errno =3D EINVAL;
 			return -1;
@@ -351,7 +349,7 @@
=20
 	switch (si->family) {
 	case AF_INET: {
-		const struct sockaddr_in *in =3D=20
+		const struct sockaddr_in *in =3D
 		    (const struct sockaddr_in *)inaddr;
 		unsigned int addr =3D ntohl(in->sin_addr.s_addr);
 		char u_type =3D '\0';
@@ -394,7 +392,7 @@
 	}
 #ifdef HAVE_IPV6
 	case AF_INET6: {
-		const struct sockaddr_in6 *in =3D=20
+		const struct sockaddr_in6 *in =3D
 		    (const struct sockaddr_in6 *)inaddr;
=20
 		switch (si->type) {
@@ -410,7 +408,7 @@
=20
 		prt =3D ntohs(in->sin6_port);
 		iface =3D SW_IPV6_ADDRESS;
-	=09
+
 		break;
 	}
 #endif
@@ -425,13 +423,13 @@
 	}
=20
 	if (is_bcast) {
-		snprintf(un->sun_path, sizeof(un->sun_path), "%s/EINVAL",=20
+		snprintf(un->sun_path, sizeof(un->sun_path), "%s/EINVAL",
 			 socket_wrapper_dir());
 		/* the caller need to do more processing */
 		return 0;
 	}
=20
-	snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,=20
+	snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,
 		 socket_wrapper_dir(), type, iface, prt);
=20
 	return 0;
@@ -450,7 +448,7 @@
=20
 	switch (si->family) {
 	case AF_INET: {
-		const struct sockaddr_in *in =3D=20
+		const struct sockaddr_in *in =3D
 		    (const struct sockaddr_in *)inaddr;
 		unsigned int addr =3D ntohl(in->sin_addr.s_addr);
 		char u_type =3D '\0';
@@ -501,7 +499,7 @@
 	}
 #ifdef HAVE_IPV6
 	case AF_INET6: {
-		const struct sockaddr_in6 *in =3D=20
+		const struct sockaddr_in6 *in =3D
 		    (const struct sockaddr_in6 *)inaddr;
=20
 		switch (si->type) {
@@ -517,7 +515,7 @@
=20
 		prt =3D ntohs(in->sin6_port);
 		iface =3D SW_IPV6_ADDRESS;
-	=09
+
 		break;
 	}
 #endif
@@ -532,7 +530,7 @@
 	if (prt =3D=3D 0) {
 		/* handle auto-allocation of ephemeral ports */
 		for (prt =3D 5001; prt < 10000; prt++) {
-			snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,=20
+			snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,
 				 socket_wrapper_dir(), type, iface, prt);
 			if (stat(un->sun_path, &st) =3D=3D 0) continue;
=20
@@ -540,7 +538,7 @@
 		}
 	}
=20
-	snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,=20
+	snprintf(un->sun_path, sizeof(un->sun_path), "%s/"SOCKET_FORMAT,
 		 socket_wrapper_dir(), type, iface, prt);
 	return 0;
 }
@@ -549,14 +547,14 @@
 {
 	struct socket_info *i;
 	for (i =3D sockets; i; i =3D i->next) {
-		if (i->fd =3D=3D fd)=20
+		if (i->fd =3D=3D fd)
 			return i;
 	}
=20
 	return NULL;
 }
=20
-static int sockaddr_convert_to_un(struct socket_info *si, const struct soc=
kaddr *in_addr, socklen_t in_len,=20
+static int sockaddr_convert_to_un(struct socket_info *si, const struct soc=
kaddr *in_addr, socklen_t in_len,
 				  struct sockaddr_un *out_addr, int alloc_sock, int *bcast)
 {
 	if (!out_addr)
@@ -585,19 +583,19 @@
 	default:
 		break;
 	}
-=09
+
 	errno =3D EAFNOSUPPORT;
 	return -1;
 }
=20
-static int sockaddr_convert_from_un(const struct socket_info *si,=20
-				    const struct sockaddr_un *in_addr,=20
+static int sockaddr_convert_from_un(const struct socket_info *si,
+				    const struct sockaddr_un *in_addr,
 				    socklen_t un_addrlen,
 				    int family,
 				    struct sockaddr *out_addr,
 				    socklen_t *out_addrlen)
 {
-	if (out_addr =3D=3D NULL || out_addrlen =3D=3D NULL)=20
+	if (out_addr =3D=3D NULL || out_addrlen =3D=3D NULL)
 		return 0;
=20
 	if (un_addrlen =3D=3D 0) {
@@ -650,7 +648,7 @@
=20
 struct swrap_file_hdr {
 	unsigned long	magic;
-	unsigned short	version_major;=09
+	unsigned short	version_major;
 	unsigned short	version_minor;
 	long		timezone;
 	unsigned long	sigfigs;
@@ -732,7 +730,7 @@
 	/*
 	 * TODO: don't use the structs use plain buffer offsets
 	 *       and PUSH_U8(), PUSH_U16() and PUSH_U32()
-	 *=20
+	 *
 	 * for now make sure we disable PCAP support
 	 * if the struct has alignment!
 	 */
@@ -913,7 +911,7 @@
 	if (fd !=3D -1) {
 		struct swrap_file_hdr file_hdr;
 		file_hdr.magic		=3D 0xA1B2C3D4;
-		file_hdr.version_major	=3D 0x0002;=09
+		file_hdr.version_major	=3D 0x0002;
 		file_hdr.version_minor	=3D 0x0004;
 		file_hdr.timezone	=3D 0x00000000;
 		file_hdr.sigfigs	=3D 0x00000000;
@@ -1284,7 +1282,7 @@
 		return real_accept(s, addr, addrlen);
 	}
=20
-	/*=20
+	/*
 	 * assume out sockaddr have the same size as the in parent
 	 * socket family
 	 */
@@ -1412,7 +1410,7 @@
=20
 		memset(&in, 0, sizeof(in));
 		in.sin_family =3D AF_INET;
-		in.sin_addr.s_addr =3D htonl(127<<24 |=20
+		in.sin_addr.s_addr =3D htonl(127<<24 |
 					   socket_wrapper_default_iface());
=20
 		si->myname_len =3D sizeof(in);
@@ -1454,11 +1452,11 @@
=20
 	for (i=3D0;i<1000;i++) {
 		port =3D autobind_start + i;
-		snprintf(un_addr.sun_path, sizeof(un_addr.sun_path),=20
+		snprintf(un_addr.sun_path, sizeof(un_addr.sun_path),
 			 "%s/"SOCKET_FORMAT, socket_wrapper_dir(),
 			 type, socket_wrapper_default_iface(), port);
 		if (stat(un_addr.sun_path, &st) =3D=3D 0) continue;
-	=09
+
 		ret =3D real_bind(si->fd, (struct sockaddr *)&un_addr, sizeof(un_addr));
 		if (ret =3D=3D -1) return ret;
=20
@@ -1503,7 +1501,7 @@
=20
 	swrap_dump_packet(si, serv_addr, SWRAP_CONNECT_SEND, NULL, 0);
=20
-	ret =3D real_connect(s, (struct sockaddr *)&un_addr,=20
+	ret =3D real_connect(s, (struct sockaddr *)&un_addr,
 			   sizeof(struct sockaddr_un));
=20
 	/* to give better errors */
@@ -1610,7 +1608,7 @@
=20
 	if (level =3D=3D SOL_SOCKET) {
 		return real_getsockopt(s, level, optname, optval, optlen);
-	}=20
+	}
=20
 	errno =3D ENOPROTOOPT;
 	return -1;
@@ -1651,7 +1649,7 @@
 	/* irix 6.4 forgets to null terminate the sun_path string :-( */
 	memset(&un_addr, 0, sizeof(un_addr));
 	ret =3D real_recvfrom(s, buf, len, flags, (struct sockaddr *)&un_addr, &u=
n_addrlen);
-	if (ret =3D=3D -1)=20
+	if (ret =3D=3D -1)
 		return ret;
=20
 	if (sockaddr_convert_from_un(si, &un_addr, un_addrlen,
@@ -1685,32 +1683,32 @@
 			ret =3D swrap_auto_bind(si);
 			if (ret =3D=3D -1) return -1;
 		}
-	=09
+
 		ret =3D sockaddr_convert_to_un(si, to, tolen, &un_addr, 0, &bcast);
 		if (ret =3D=3D -1) return -1;
-	=09
+
 		if (bcast) {
 			struct stat st;
 			unsigned int iface;
 			unsigned int prt =3D ntohs(((const struct sockaddr_in *)to)->sin_port);
 			char type;
-		=09
+
 			type =3D SOCKET_TYPE_CHAR_UDP;
-		=09
+
 			for(iface=3D0; iface <=3D MAX_WRAPPED_INTERFACES; iface++) {
-				snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s/"SOCKET_FORMA=
T,=20
+				snprintf(un_addr.sun_path, sizeof(un_addr.sun_path), "%s/"SOCKET_FORMA=
T,
 					 socket_wrapper_dir(), type, iface, prt);
 				if (stat(un_addr.sun_path, &st) !=3D 0) continue;
-			=09
+
 				/* ignore the any errors in broadcast sends */
 				real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, sizeof(un=
_addr));
 			}
-		=09
+
 			swrap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
-		=09
+
 			return len;
 		}
-	=09
+
 		ret =3D real_sendto(s, buf, len, flags, (struct sockaddr *)&un_addr, siz=
eof(un_addr));
 		break;
 	default:
@@ -1718,7 +1716,7 @@
 		errno =3D EHOSTUNREACH;
 		break;
 	}
-	=09
+
 	/* to give better errors */
 	if (ret =3D=3D -1 && errno =3D=3D ENOENT) {
 		errno =3D EHOSTUNREACH;
@@ -1858,7 +1856,7 @@
 	si_newd->myname =3D
 	    sockaddr_dup(si_oldd->myname, si_oldd->myname_len);
 	si_newd->myname_len =3D si_oldd->myname_len;
-	si_newd->peername =3D=20
+	si_newd->peername =3D
 	    sockaddr_dup(si_oldd->peername, si_oldd->peername_len);
 	si_newd->peername_len =3D si_oldd->peername_len;
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/socket_w=
rapper.h
--- a/head/crypto/heimdal/lib/roken/socket_wrapper.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/roken/socket_wrapper.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -3,22 +3,22 @@
  * Copyright (C) Stefan Metzmacher 2006 <metze at samba.org>
  *
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the author nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strcasec=
mp.c
--- a/head/crypto/heimdal/lib/roken/strcasecmp.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/strcasecmp.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strcasecmp.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <string.h>
 #include <ctype.h>
@@ -43,7 +40,7 @@
=20
 #ifndef HAVE_STRCASECMP
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 strcasecmp(const char *s1, const char *s2)
 {
     while(toupper((unsigned char)*s1) =3D=3D toupper((unsigned char)*s2)) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strcolle=
ct.c
--- a/head/crypto/heimdal/lib/roken/strcollect.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/crypto/heimdal/lib/roken/strcollect.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1998, 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998, 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strcollect.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdarg.h>
 #include <stdlib.h>
@@ -69,7 +66,7 @@
  * terminated by NULL.
  */
=20
-char ** ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
 vstrcollect(va_list *ap)
 {
     return sub (NULL, 0, 0, ap);
@@ -79,7 +76,7 @@
  *
  */
=20
-char ** ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char ** ROKEN_LIB_CALL
 strcollect(char *first, ...)
 {
     va_list ap;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strdup.c
--- a/head/crypto/heimdal/lib/roken/strdup.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strdup.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,15 +31,12 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strdup.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
 #include <stdlib.h>
 #include <string.h>
=20
 #ifndef HAVE_STRDUP
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strdup(const char *old)
 {
 	char *t =3D malloc(strlen(old)+1);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strerror=
.c
--- a/head/crypto/heimdal/lib/roken/strerror.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/strerror.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strerror.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <string.h>
@@ -43,7 +40,7 @@
 extern int sys_nerr;
 extern char *sys_errlist[];
=20
-char* ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char* ROKEN_LIB_CALL
 strerror(int eno)
 {
     static char emsg[1024];
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strftime=
.c
--- a/head/crypto/heimdal/lib/roken/strftime.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/strftime.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 - 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -30,15 +30,11 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+#include "roken.h"
 #ifdef TEST_STRPFTIME
 #include "strpftime-test.h"
 #endif
-#include "roken.h"
-
-RCSID("$Id: strftime.c 21896 2007-08-09 08:46:08Z lha $");
=20
 static const char *abb_weekdays[] =3D {
     "Sun",
@@ -155,7 +151,7 @@
     int wday  =3D (tm->tm_wday + 6) % 7;
     int w1day =3D (wday - tm->tm_yday % 7 + 7) % 7;
     int ret;
-   =20
+
     ret =3D (tm->tm_yday + w1day) / 7;
     if (w1day >=3D 4)
 	--ret;
@@ -170,7 +166,7 @@
  *
  */
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 strftime (char *buf, size_t maxsize, const char *format,
 	  const struct tm *tm)
 {
@@ -290,7 +286,7 @@
 				"%02d:%02d",
 				tm->tm_hour,
 				tm->tm_min);
-		   =20
+		break;
 	    case 's' :
 		ret =3D snprintf (buf, maxsize - n,
 				"%d", (int)mktime(rk_UNCONST(tm)));
@@ -358,7 +354,7 @@
 				(long)timezone
 #else
 #error Where in timezone chaos are you?
-#endif   =20
+#endif
 				);
 		break;
 	    case 'Z' :
@@ -386,7 +382,7 @@
 				"%%%c", *format);
 		break;
 	    }
-	    if (ret < 0 || ret >=3D maxsize - n)
+	    if (ret < 0 || ret >=3D (int)(maxsize - n))
 		return 0;
 	    n   +=3D ret;
 	    buf +=3D ret;
@@ -396,6 +392,6 @@
 	    ++n;
 	}
     }
-    *buf++ =3D '\0';
+    *buf =3D '\0';
     return n;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strlcat.c
--- a/head/crypto/heimdal/lib/roken/strlcat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strlcat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995-2002 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2002 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,21 +31,24 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
-RCSID("$Id: strlcat.c 14773 2005-04-12 11:29:18Z lha $");
-
 #ifndef HAVE_STRLCAT
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 strlcat (char *dst, const char *src, size_t dst_sz)
 {
-    size_t len =3D strlen(dst);
+    size_t len;
+#if defined(_MSC_VER) && _MSC_VER >=3D 1400
+    len =3D strnlen_s(dst, dst_sz);
+#elif defined(HAVE_STRNLEN)
+    len =3D strnlen(dst, dst_sz);
+#else
+    len =3D strlen(dst);
+#endif
=20
-    if (dst_sz < len)
+    if (dst_sz <=3D len)
 	/* the total size of dst is less than the string it contains;
            this could be considered bad input, but we might as well
            handle it */
@@ -53,4 +56,5 @@
=20
     return len + strlcpy (dst + len, src, dst_sz - len);
 }
+
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strlcpy.c
--- a/head/crypto/heimdal/lib/roken/strlcpy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strlcpy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995-2002 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995-2002 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
  *
@@ -31,16 +31,27 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
-RCSID("$Id: strlcpy.c 14773 2005-04-12 11:29:18Z lha $");
-
 #ifndef HAVE_STRLCPY
=20
-size_t ROKEN_LIB_FUNCTION
+#if defined(_MSC_VER) && _MSC_VER >=3D 1400
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strlcpy (char *dst, const char *src, size_t dst_cch)
+{
+    errno_t e;
+
+    if (dst_cch > 0)
+        e =3D strncpy_s(dst, dst_cch, src, _TRUNCATE);
+
+    return strlen (src);
+}
+
+#else
+
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 strlcpy (char *dst, const char *src, size_t dst_sz)
 {
     size_t n;
@@ -58,3 +69,5 @@
 }
=20
 #endif
+
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strlwr.c
--- a/head/crypto/heimdal/lib/roken/strlwr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strlwr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strlwr.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
 #include <string.h>
 #include <ctype.h>
=20
 #include "roken.h"
=20
 #ifndef HAVE_STRLWR
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strlwr(char *str)
 {
   char *s;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strncase=
cmp.c
--- a/head/crypto/heimdal/lib/roken/strncasecmp.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/strncasecmp.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1998 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strncasecmp.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <string.h>
 #include <ctype.h>
@@ -42,10 +39,10 @@
=20
 #ifndef HAVE_STRNCASECMP
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 strncasecmp(const char *s1, const char *s2, size_t n)
 {
-    while(n > 0=20
+    while(n > 0
 	  && toupper((unsigned char)*s1) =3D=3D toupper((unsigned char)*s2))
     {
 	if(*s1 =3D=3D '\0')
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strndup.c
--- a/head/crypto/heimdal/lib/roken/strndup.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strndup.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strndup.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
 #include <stdlib.h>
 #include <string.h>
=20
 #include "roken.h"
=20
 #ifndef HAVE_STRNDUP
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strndup(const char *old, size_t sz)
 {
     size_t len =3D strnlen (old, sz);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strnlen.c
--- a/head/crypto/heimdal/lib/roken/strnlen.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strnlen.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strnlen.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-size_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
 strnlen(const char *s, size_t len)
 {
     size_t i;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strpftim=
e-test.c
--- a/head/crypto/heimdal/lib/roken/strpftime-test.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/roken/strpftime-test.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -30,15 +30,11 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+#include <roken.h>
 #ifdef TEST_STRPFTIME
 #include "strpftime-test.h"
 #endif
-#include "roken.h"
-
-RCSID("$Id: strpftime-test.c 21897 2007-08-09 08:46:34Z lha $");
=20
 enum { MAXSIZE =3D 26 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strpftim=
e-test.h
--- a/head/crypto/heimdal/lib/roken/strpftime-test.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/lib/roken/strpftime-test.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2007 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2007 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -45,4 +45,11 @@
 #define strftime test_strftime
 #define strptime test_strptime
=20
+ROKEN_LIB_FUNCTION size_t ROKEN_LIB_CALL
+strftime (char *buf, size_t maxsize, const char *format,
+          const struct tm *tm);
+
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+strptime (const char *buf, const char *format, struct tm *timeptr);
+
 #endif /* __STRFTIME_TEST_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strpool.c
--- a/head/crypto/heimdal/lib/roken/strpool.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strpool.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strpool.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
=20
 #include <stdarg.h>
 #include <stdlib.h>
@@ -49,7 +46,7 @@
  *
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rk_strpoolfree(struct rk_strpool *p)
 {
     if (p->str) {
@@ -63,7 +60,7 @@
  *
  */
=20
-struct rk_strpool * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION struct rk_strpool * ROKEN_LIB_CALL
 rk_strpoolprintf(struct rk_strpool *p, const char *fmt, ...)
 {
     va_list ap;
@@ -100,10 +97,13 @@
  *
  */
=20
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 rk_strpoolcollect(struct rk_strpool *p)
 {
-    char *str =3D p->str;
+    char *str;
+    if (p =3D=3D NULL)
+	return strdup("");
+    str =3D p->str;
     p->str =3D NULL;
     free(p);
     return str;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strptime=
.c
--- a/head/crypto/heimdal/lib/roken/strptime.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/strptime.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 1999, 2003, 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999, 2003, 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -30,16 +30,12 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+#include "roken.h"
 #ifdef TEST_STRPFTIME
 #include "strpftime-test.h"
 #endif
 #include <ctype.h>
-#include "roken.h"
-
-RCSID("$Id: strptime.c 21895 2007-08-09 08:45:54Z lha $");
=20
 static const char *abb_weekdays[] =3D {
     "Sun",
@@ -181,7 +177,7 @@
     int ret =3D 4;
=20
     for (; year > 1970; --year)
-	ret =3D (ret + 365 + is_leap_year (year) ? 1 : 0) % 7;
+	ret =3D (ret + (is_leap_year (year) ? 366 : 365)) % 7;
     return ret;
 }
=20
@@ -241,7 +237,7 @@
  *
  */
=20
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strptime (const char *buf, const char *format, struct tm *timeptr)
 {
     char c;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strsep.c
--- a/head/crypto/heimdal/lib/roken/strsep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strsep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1997 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strsep.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <string.h>
=20
@@ -42,7 +39,7 @@
=20
 #ifndef HAVE_STRSEP
=20
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strsep(char **str, const char *delim)
 {
     char *save =3D *str;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strsep_c=
opy.c
--- a/head/crypto/heimdal/lib/roken/strsep_copy.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/crypto/heimdal/lib/roken/strsep_copy.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 2000, 2002 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2000, 2002 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strsep_copy.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <string.h>
=20
@@ -44,7 +41,7 @@
=20
 /* strsep, but with const stringp, so return string in buf */
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 strsep_copy(const char **stringp, const char *delim, char *buf, size_t len)
 {
     const char *save =3D *stringp;
@@ -52,7 +49,7 @@
     if(save =3D=3D NULL)
 	return -1;
     *stringp =3D *stringp + strcspn(*stringp, delim);
-    l =3D min(len, *stringp - save);
+    l =3D min(len, (size_t)(*stringp - save));
     if(len > 0) {
 	memcpy(buf, save, l);
 	buf[l] =3D '\0';
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strtok_r=
.c
--- a/head/crypto/heimdal/lib/roken/strtok_r.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/strtok_r.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strtok_r.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <string.h>
=20
@@ -42,7 +39,7 @@
=20
 #ifndef HAVE_STRTOK_R
=20
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strtok_r(char *s1, const char *s2, char **lasts)
 {
   char *ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/strupr.c
--- a/head/crypto/heimdal/lib/roken/strupr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/strupr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: strupr.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
 #include <string.h>
 #include <ctype.h>
=20
 #include "roken.h"
=20
 #ifndef HAVE_STRUPR
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 strupr(char *str)
 {
   char *s;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/swab.c
--- a/head/crypto/heimdal/lib/roken/swab.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/swab.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,12 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include "roken.h"
=20
 #ifndef HAVE_SWAB
=20
-RCSID("$Id: swab.c 14773 2005-04-12 11:29:18Z lha $");
-
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 swab (char *from, char *to, int nbytes)
 {
      while(nbytes >=3D 2) {
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/test-mem=
.c
--- a/head/crypto/heimdal/lib/roken/test-mem.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/test-mem.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,39 +1,38 @@
 /*
- * Copyright (c) 1999 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
+
 #ifdef HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #endif
@@ -44,8 +43,6 @@
=20
 #include "test-mem.h"
=20
-RCSID("$Id: test-mem.c 21005 2007-06-08 01:54:35Z lha $");
-
 /* #undef HAVE_MMAP */
=20
 struct {
@@ -57,8 +54,16 @@
     int fd;
 } map;
=20
+#ifdef HAVE_SIGACTION
+
 struct sigaction sa, osa;
=20
+#else
+
+void (* osigh)(int);
+
+#endif
+
 char *testname;
=20
 static RETSIGTYPE
@@ -66,12 +71,12 @@
 {
     int fd;
     char msg[] =3D "SIGSEGV i current test: ";
-   =20
+
     fd =3D open("/dev/stdout", O_WRONLY, 0600);
     if (fd >=3D 0) {
-	write(fd, msg, sizeof(msg) - 1);
-	write(fd, testname, strlen(testname));
-	write(fd, "\n", 1);
+	(void)write(fd, msg, sizeof(msg) - 1);
+	(void)write(fd, testname, strlen(testname));
+	(void)write(fd, "\n", 1);
 	close(fd);
     }
     _exit(1);
@@ -85,13 +90,13 @@
 	errx(1, "malloc");
=20
=20
-void * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
 rk_test_mem_alloc(enum rk_test_mem_type type, const char *name,
 		  void *buf, size_t size)
 {
 #ifndef HAVE_MMAP
     unsigned char *p;
-   =20
+
     TESTREC();
=20
     p =3D malloc(size + 2);
@@ -101,7 +106,7 @@
     map.start =3D p;
     map.size =3D size + 2;
     p[0] =3D 0xff;
-    p[map.size] =3D 0xff;
+    p[map.size-1] =3D 0xff;
     map.data_start =3D p + 1;
 #else
     unsigned char *p;
@@ -152,6 +157,7 @@
 	abort();
     }
 #endif
+#ifdef HAVE_SIGACTION
     sigemptyset (&sa.sa_mask);
     sa.sa_flags =3D 0;
 #ifdef SA_RESETHAND
@@ -159,6 +165,9 @@
 #endif
     sa.sa_handler =3D segv_handler;
     sigaction (SIGSEGV, &sa, &osa);
+#else
+    osigh =3D signal(SIGSEGV, segv_handler);
+#endif
=20
     map.data_size =3D size;
     if (buf)
@@ -166,23 +175,23 @@
     return map.data_start;
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 rk_test_mem_free(const char *map_name)
 {
 #ifndef HAVE_MMAP
     unsigned char *p =3D map.start;
-   =20
+
     if (testname =3D=3D NULL)
 	errx(1, "test_mem_free call on no free");
=20
     if (p[0] !=3D 0xff)
 	errx(1, "%s: %s underrun %x\n", testname, map_name, p[0]);
-    if (p[map.size] !=3D 0xff)
+    if (p[map.size-1] !=3D 0xff)
 	errx(1, "%s: %s overrun %x\n", testname, map_name, p[map.size - 1]);
     free(map.start);
 #else
     int ret;
-   =20
+
     if (testname =3D=3D NULL)
 	errx(1, "test_mem_free call on no free");
=20
@@ -195,5 +204,9 @@
     free(testname);
     testname =3D NULL;
=20
+#ifdef HAVE_SIGACTION
     sigaction (SIGSEGV, &osa, NULL);
+#else
+    signal (SIGSEGV, osigh);
+#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/test-mem=
.h
--- a/head/crypto/heimdal/lib/roken/test-mem.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/test-mem.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,39 +1,39 @@
 /*
- * Copyright (c) 1999 - 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
 enum rk_test_mem_type { RK_TM_OVERRUN, RK_TM_UNDERRUN };
=20
-void * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void * ROKEN_LIB_CALL
 	rk_test_mem_alloc(enum rk_test_mem_type, const char *, void *, size_t);
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 	rk_test_mem_free(const char *);
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/test-rea=
denv.c
--- a/head/crypto/heimdal/lib/roken/test-readenv.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/roken/test-readenv.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 2005 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2005 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: test-readenv.c 20868 2007-06-03 21:02:04Z lha $");
-#endif
=20
 #include "roken.h"
 #include "test-mem.h"
@@ -112,7 +109,7 @@
 	error++;
     }
     free_environment(env);
-   =20
-   =20
+
+
     return error;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/timegm.c
--- a/head/crypto/heimdal/lib/roken/timegm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/timegm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,40 +1,37 @@
 /*
- * Copyright (c) 1997, 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1997, 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: timegm.c 18606 2006-10-19 16:19:10Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -45,7 +42,7 @@
     return (y % 4) =3D=3D 0 && ((y % 100) !=3D 0 || (y % 400) =3D=3D 0);
 }
=20
-/*=20
+/*
  * XXX This is a simplifed version of timegm, it needs to support out of
  * bounds values.
  */
@@ -59,17 +56,17 @@
   time_t res =3D 0;
   unsigned i;
=20
-  if (tm->tm_year < 0)=20
+  if (tm->tm_year < 0)
       return -1;
-  if (tm->tm_mon < 0 || tm->tm_mon > 11)=20
+  if (tm->tm_mon < 0 || tm->tm_mon > 11)
       return -1;
   if (tm->tm_mday < 1 || tm->tm_mday > ndays[is_leap(tm->tm_year)][tm->tm_=
mon])
       return -1;
-  if (tm->tm_hour < 0 || tm->tm_hour > 23)=20
+  if (tm->tm_hour < 0 || tm->tm_hour > 23)
       return -1;
-  if (tm->tm_min < 0 || tm->tm_min > 59)=20
+  if (tm->tm_min < 0 || tm->tm_min > 59)
       return -1;
-  if (tm->tm_sec < 0 || tm->tm_sec > 59)=20
+  if (tm->tm_sec < 0 || tm->tm_sec > 59)
       return -1;
=20
   for (i =3D 70; i < tm->tm_year; ++i)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/timeval.c
--- a/head/crypto/heimdal/lib/roken/timeval.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/timeval.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1999 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -35,10 +35,7 @@
  * Timeval stuff
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: timeval.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
@@ -46,7 +43,7 @@
  * Make `t1' consistent.
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 timevalfix(struct timeval *t1)
 {
     if (t1->tv_usec < 0) {
@@ -58,24 +55,24 @@
         t1->tv_usec -=3D 1000000;
     }
 }
-=20
+
 /*
  * t1 +=3D t2
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 timevaladd(struct timeval *t1, const struct timeval *t2)
 {
     t1->tv_sec  +=3D t2->tv_sec;
     t1->tv_usec +=3D t2->tv_usec;
     timevalfix(t1);
 }
-=20
+
 /*
  * t1 -=3D t2
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 timevalsub(struct timeval *t1, const struct timeval *t2)
 {
     t1->tv_sec  -=3D t2->tv_sec;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/tm2time.c
--- a/head/crypto/heimdal/lib/roken/tm2time.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/tm2time.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: tm2time.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #ifdef TIME_WITH_SYS_TIME
 #include <sys/time.h>
@@ -46,7 +43,7 @@
 #endif
 #include "roken.h"
=20
-time_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION time_t ROKEN_LIB_CALL
 tm2time (struct tm tm, int local)
 {
     time_t t;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/unsetenv=
.c
--- a/head/crypto/heimdal/lib/roken/unsetenv.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/roken/unsetenv.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,22 +31,21 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: unsetenv.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <stdlib.h>
 #include <string.h>
=20
 #include "roken.h"
=20
+#if !HAVE_DECL_ENVIRON
 extern char **environ;
+#endif
=20
 /*
  * unsetenv --
  */
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 unsetenv(const char *name)
 {
   int len;
@@ -59,7 +58,7 @@
   for (np =3D name; *np && *np !=3D '=3D'; np++)
     /* nop */;
   len =3D np - name;
- =20
+
   for (p =3D environ; *p !=3D 0; p++)
     if (strncmp(*p, name, len) =3D=3D 0 && (*p)[len] =3D=3D '=3D')
       break;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/unvis.c
--- a/head/crypto/heimdal/lib/roken/unvis.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/unvis.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,10 +30,7 @@
  */
=20
 #if 1
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: unvis.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
 #include "roken.h"
 #ifndef _DIAGASSERT
 #define _DIAGASSERT(X)
@@ -82,16 +79,16 @@
=20
 #define	isoctal(c)	(((u_char)(c)) >=3D '0' && ((u_char)(c)) <=3D '7')
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 	rk_strunvis (char *, const char *);
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 	rk_unvis (char *, int, int *, int);
=20
 /*
  * unvis - decode characters previously encoded by vis
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rk_unvis(char *cp, int c, int *astate, int flag)
 {
=20
@@ -102,7 +99,7 @@
 		if (*astate =3D=3D S_OCTAL2 || *astate =3D=3D S_OCTAL3) {
 			*astate =3D S_GROUND;
 			return (UNVIS_VALID);
-		}=20
+		}
 		return (*astate =3D=3D S_GROUND ? UNVIS_NOCHAR : UNVIS_SYNBAD);
 	}
=20
@@ -113,7 +110,7 @@
 		if (c =3D=3D '\\') {
 			*astate =3D S_START;
 			return (0);
-		}=20
+		}
 		*cp =3D c;
 		return (UNVIS_VALID);
=20
@@ -129,7 +126,7 @@
 			*astate =3D S_OCTAL2;
 			return (0);
 		case 'M':
-			*cp =3D (char)0200;
+			*cp =3D (u_char)0200;
 			*astate =3D S_META;
 			return (0);
 		case '^':
@@ -186,7 +183,7 @@
 		}
 		*astate =3D S_GROUND;
 		return (UNVIS_SYNBAD);
-		=20
+
 	case S_META:
 		if (c =3D=3D '-')
 			*astate =3D S_META1;
@@ -197,12 +194,12 @@
 			return (UNVIS_SYNBAD);
 		}
 		return (0);
-		=20
+
 	case S_META1:
 		*astate =3D S_GROUND;
 		*cp |=3D c;
 		return (UNVIS_VALID);
-		=20
+
 	case S_CTRL:
 		if (c =3D=3D '?')
 			*cp |=3D 0177;
@@ -213,15 +210,15 @@
=20
 	case S_OCTAL2:	/* second possible octal digit */
 		if (isoctal(c)) {
-			/*=20
-			 * yes - and maybe a third=20
+			/*
+			 * yes - and maybe a third
 			 */
 			*cp =3D (*cp << 3) + (c - '0');
-			*astate =3D S_OCTAL3;=09
+			*astate =3D S_OCTAL3;
 			return (0);
-		}=20
-		/*=20
-		 * no - done with current sequence, push back passed char=20
+		}
+		/*
+		 * no - done with current sequence, push back passed char
 		 */
 		*astate =3D S_GROUND;
 		return (UNVIS_VALIDPUSH);
@@ -236,10 +233,10 @@
 		 * we were done, push back passed char
 		 */
 		return (UNVIS_VALIDPUSH);
-		=09
-	default:=09
-		/*=20
-		 * decoder in unknown state - (probably uninitialized)=20
+
+	default:
+		/*
+		 * decoder in unknown state - (probably uninitialized)
 		 */
 		*astate =3D S_GROUND;
 		return (UNVIS_SYNBAD);
@@ -247,13 +244,13 @@
 }
=20
 /*
- * strunvis - decode src into dst=20
+ * strunvis - decode src into dst
  *
  *	Number of chars decoded into dst is returned, -1 on error.
  *	Dst is null terminated.
  */
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rk_strunvis(char *dst, const char *src)
 {
 	char c;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/verify.c
--- a/head/crypto/heimdal/lib/roken/verify.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/verify.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: verify.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include <stdio.h>
 #ifdef HAVE_UNISTD_H
@@ -45,11 +42,11 @@
 #endif
 #include "roken.h"
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 unix_verify_user(char *user, char *password)
 {
     struct passwd *pw;
-   =20
+
     pw =3D k_getpwnam(user);
     if(pw =3D=3D NULL)
 	return -1;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/verr.c
--- a/head/crypto/heimdal/lib/roken/verr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/verr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: verr.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
 #include <err.h>
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 verr(int eval, const char *fmt, va_list ap)
 {
-    warnerr(1, fmt, ap);
+    rk_warnerr(1, fmt, ap);
     exit(eval);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/verrx.c
--- a/head/crypto/heimdal/lib/roken/verrx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/verrx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: verrx.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
 #include <err.h>
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 verrx(int eval, const char *fmt, va_list ap)
 {
-    warnerr(0, fmt, ap);
+    rk_warnerr(0, fmt, ap);
     exit(eval);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/vis.c
--- a/head/crypto/heimdal/lib/roken/vis.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/vis.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/*	$NetBSD: vis.c,v 1.4 2003/08/07 09:15:32 agc Exp $	*/
+/*	$NetBSD: vis.c,v 1.37 2008/07/25 22:29:23 dsl Exp $	*/
=20
 /*-
  * Copyright (c) 1989, 1993
@@ -30,7 +30,8 @@
  */
=20
 /*-
- * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * Copyright (c) 1999, 2005 The NetBSD Foundation, Inc.
+ * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -40,47 +41,35 @@
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *	This product includes software developed by the University of
- *	California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTO=
RS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIM=
ITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICU=
LAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTO=
RS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF =
THE
+ * POSSIBILITY OF SUCH DAMAGE.
  */
=20
-
 #if 1
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: vis.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
 #include "roken.h"
 #ifndef _DIAGASSERT
 #define _DIAGASSERT(X)
 #endif
-#else
+#else /* heimdal */
 #include <sys/cdefs.h>
-#if !defined(lint)
-__RCSID("$NetBSD: vis.c,v 1.4 2003/08/07 09:15:32 agc Exp $");
-#endif /* not lint */
-#endif
+#if defined(LIBC_SCCS) && !defined(lint)
+__RCSID("$NetBSD: vis.c,v 1.37 2008/07/25 22:29:23 dsl Exp $");
+#endif /* LIBC_SCCS and not lint */
=20
-#if 0
 #include "namespace.h"
-#endif
+#endif /* heimdal */
+
 #include <sys/types.h>
=20
 #include <assert.h>
@@ -89,6 +78,7 @@
 #include <stdio.h>
 #include <string.h>
 #include <vis.h>
+#include <stdlib.h>
=20
 #if 0
 #ifdef __weak_alias
@@ -101,6 +91,14 @@
 #endif
 #endif
=20
+#if !HAVE_VIS || !HAVE_SVIS
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+static char *do_svis(char *, int, int, int, const char *);
+
 #undef BELL
 #if defined(__STDC__)
 #define BELL '\a'
@@ -108,39 +106,64 @@
 #define BELL '\007'
 #endif
=20
-char ROKEN_LIB_FUNCTION
-	*rk_vis (char *, int, int, int);
-char ROKEN_LIB_FUNCTION
-	*rk_svis (char *, int, int, int, const char *);
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+	rk_vis (char *, int, int, int);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+	rk_svis (char *, int, int, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 	rk_strvis (char *, const char *, int);
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 	rk_strsvis (char *, const char *, int, const char *);
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 	rk_strvisx (char *, const char *, size_t, int);
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 	rk_strsvisx (char *, const char *, size_t, int, const char *);
=20
=20
 #define isoctal(c)	(((u_char)(c)) >=3D '0' && ((u_char)(c)) <=3D '7')
 #define iswhite(c)	(c =3D=3D ' ' || c =3D=3D '\t' || c =3D=3D '\n')
 #define issafe(c)	(c =3D=3D '\b' || c =3D=3D BELL || c =3D=3D '\r')
+#define xtoa(c)		"0123456789abcdef"[c]
=20
-#define MAXEXTRAS       5
+#define MAXEXTRAS	5
=20
-
-#define MAKEEXTRALIST(flag, extra)					      \
+#define MAKEEXTRALIST(flag, extra, orig_str)				      \
 do {									      \
-	char *pextra =3D extra;						      \
-	if (flag & VIS_SP) *pextra++ =3D ' ';				      \
-	if (flag & VIS_TAB) *pextra++ =3D '\t';				      \
-	if (flag & VIS_NL) *pextra++ =3D '\n';				      \
-	if ((flag & VIS_NOSLASH) =3D=3D 0) *pextra++ =3D '\\';		      \
-	*pextra =3D '\0';							      \
+	const char *orig =3D orig_str;					      \
+	const char *o =3D orig;						      \
+	char *e;							      \
+	while (*o++)							      \
+		continue;						      \
+	extra =3D malloc((size_t)((o - orig) + MAXEXTRAS));		      \
+	if (!extra) break;						      \
+	for (o =3D orig, e =3D extra; (*e++ =3D *o++) !=3D '\0';)		      \
+		continue;						      \
+	e--;								      \
+	if (flag & VIS_SP) *e++ =3D ' ';					      \
+	if (flag & VIS_TAB) *e++ =3D '\t';				      \
+	if (flag & VIS_NL) *e++ =3D '\n';					      \
+	if ((flag & VIS_NOSLASH) =3D=3D 0) *e++ =3D '\\';			      \
+	*e =3D '\0';							      \
 } while (/*CONSTCOND*/0)
=20
 /*
- * This is SVIS, the central macro of vis.
+ * This is do_hvis, for HTTP style (RFC 1808)
+ */
+static char *
+do_hvis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+	if (!isascii(c) || !isalnum(c) || strchr("$-_.+!*'(),", c) !=3D NULL) {
+		*dst++ =3D '%';
+		*dst++ =3D xtoa(((unsigned int)c >> 4) & 0xf);
+		*dst++ =3D xtoa((unsigned int)c & 0xf);
+	} else {
+		dst =3D do_svis(dst, c, flag, nextc, extra);
+	}
+	return dst;
+}
+
+/*
+ * This is do_vis, the central code of vis.
  * dst:	      Pointer to the destination buffer
  * c:	      Character to encode
  * flag:      Flag word
@@ -148,90 +171,103 @@
  * extra:     Pointer to the list of extra characters to be
  *	      backslash-protected.
  */
-#define SVIS(dst, c, flag, nextc, extra)				   \
-do {									   \
-	int isextra, isc;						   \
-	isextra =3D strchr(extra, c) !=3D NULL;				   \
-	if (!isextra &&							   \
-	    isascii((unsigned char)c) &&				   \
-	    (isgraph((unsigned char)c) || iswhite(c) ||			   \
-	    ((flag & VIS_SAFE) && issafe(c)))) {			   \
-		*dst++ =3D c;						   \
-		break;							   \
-	}								   \
-	isc =3D 0;							   \
-	if (flag & VIS_CSTYLE) {					   \
-		switch (c) {						   \
-		case '\n':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 'n';		   \
-			break;						   \
-		case '\r':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 'r';		   \
-			break;						   \
-		case '\b':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 'b';		   \
-			break;						   \
-		case BELL:						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 'a';		   \
-			break;						   \
-		case '\v':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 'v';		   \
-			break;						   \
-		case '\t':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 't';		   \
-			break;						   \
-		case '\f':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 'f';		   \
-			break;						   \
-		case ' ':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D 's';		   \
-			break;						   \
-		case '\0':						   \
-			isc =3D 1; *dst++ =3D '\\'; *dst++ =3D '0';		   \
-			if (isoctal(nextc)) {				   \
-				*dst++ =3D '0';				   \
-				*dst++ =3D '0';				   \
-			}						   \
-		}							   \
-	}								   \
-	if (isc) break;							   \
-	if (isextra || ((c & 0177) =3D=3D ' ') || (flag & VIS_OCTAL)) {	   \
-		*dst++ =3D '\\';						   \
-		*dst++ =3D (u_char)(((unsigned)(u_char)c >> 6) & 03) + '0';  \
-		*dst++ =3D (u_char)(((unsigned)(u_char)c >> 3) & 07) + '0';  \
-		*dst++ =3D			     (c	      & 07) + '0'; \
-	} else {							   \
-		if ((flag & VIS_NOSLASH) =3D=3D 0) *dst++ =3D '\\';		   \
-		if (c & 0200) {						   \
-			c &=3D 0177; *dst++ =3D 'M';			   \
-		}							   \
-		if (iscntrl((unsigned char)c)) {			   \
-			*dst++ =3D '^';					   \
-			if (c =3D=3D 0177)					   \
-				*dst++ =3D '?';				   \
-			else						   \
-				*dst++ =3D c + '@';			   \
-		} else {						   \
-			*dst++ =3D '-'; *dst++ =3D c;			   \
-		}							   \
-	}								   \
-} while (/*CONSTCOND*/0)
+static char *
+do_svis(char *dst, int c, int flag, int nextc, const char *extra)
+{
+	int isextra;
+	isextra =3D strchr(extra, c) !=3D NULL;
+	if (!isextra && isascii(c) && (isgraph(c) || iswhite(c) ||
+	    ((flag & VIS_SAFE) && issafe(c)))) {
+		*dst++ =3D c;
+		return dst;
+	}
+	if (flag & VIS_CSTYLE) {
+		switch (c) {
+		case '\n':
+			*dst++ =3D '\\'; *dst++ =3D 'n';
+			return dst;
+		case '\r':
+			*dst++ =3D '\\'; *dst++ =3D 'r';
+			return dst;
+		case '\b':
+			*dst++ =3D '\\'; *dst++ =3D 'b';
+			return dst;
+		case BELL:
+			*dst++ =3D '\\'; *dst++ =3D 'a';
+			return dst;
+		case '\v':
+			*dst++ =3D '\\'; *dst++ =3D 'v';
+			return dst;
+		case '\t':
+			*dst++ =3D '\\'; *dst++ =3D 't';
+			return dst;
+		case '\f':
+			*dst++ =3D '\\'; *dst++ =3D 'f';
+			return dst;
+		case ' ':
+			*dst++ =3D '\\'; *dst++ =3D 's';
+			return dst;
+		case '\0':
+			*dst++ =3D '\\'; *dst++ =3D '0';
+			if (isoctal(nextc)) {
+				*dst++ =3D '0';
+				*dst++ =3D '0';
+			}
+			return dst;
+		default:
+			if (isgraph(c)) {
+				*dst++ =3D '\\'; *dst++ =3D c;
+				return dst;
+			}
+		}
+	}
+	if (isextra || ((c & 0177) =3D=3D ' ') || (flag & VIS_OCTAL)) {
+		*dst++ =3D '\\';
+		*dst++ =3D (u_char)(((unsigned int)(u_char)c >> 6) & 03) + '0';
+		*dst++ =3D (u_char)(((unsigned int)(u_char)c >> 3) & 07) + '0';
+		*dst++ =3D (u_char)(			 c       & 07) + '0';
+	} else {
+		if ((flag & VIS_NOSLASH) =3D=3D 0) *dst++ =3D '\\';
+		if (c & 0200) {
+			c &=3D 0177; *dst++ =3D 'M';
+		}
+		if (iscntrl(c)) {
+			*dst++ =3D '^';
+			if (c =3D=3D 0177)
+				*dst++ =3D '?';
+			else
+				*dst++ =3D c + '@';
+		} else {
+			*dst++ =3D '-'; *dst++ =3D c;
+		}
+	}
+	return dst;
+}
=20
=20
 /*
  * svis - visually encode characters, also encoding the characters
- * 	  pointed to by `extra'
+ *	  pointed to by `extra'
  */
-
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 rk_svis(char *dst, int c, int flag, int nextc, const char *extra)
 {
+	char *nextra =3D NULL;
+
 	_DIAGASSERT(dst !=3D NULL);
 	_DIAGASSERT(extra !=3D NULL);
-
-	SVIS(dst, c, flag, nextc, extra);
+	MAKEEXTRALIST(flag, nextra, extra);
+	if (!nextra) {
+		*dst =3D '\0';		/* can't create nextra, return "" */
+		return dst;
+	}
+	if (flag & VIS_HTTPSTYLE)
+		dst =3D do_hvis(dst, c, flag, nextc, nextra);
+	else
+		dst =3D do_svis(dst, c, flag, nextc, nextra);
+	free(nextra);
 	*dst =3D '\0';
-	return(dst);
+	return dst;
 }
=20
=20
@@ -242,94 +278,145 @@
  *	be encoded, too. These functions are useful e. g. to
  *	encode strings in such a way so that they are not interpreted
  *	by a shell.
- *=09
+ *
  *	Dst must be 4 times the size of src to account for possible
  *	expansion.  The length of dst, not including the trailing NULL,
- *	is returned.=20
+ *	is returned.
  *
  *	Strsvisx encodes exactly len bytes from src into dst.
  *	This is useful for encoding a block of data.
  */
=20
-int ROKEN_LIB_FUNCTION
-rk_strsvis(char *dst, const char *src, int flag, const char *extra)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strsvis(char *dst, const char *csrc, int flag, const char *extra)
 {
-	char c;
+	int c;
 	char *start;
+	char *nextra =3D NULL;
+	const unsigned char *src =3D (const unsigned char *)csrc;
=20
 	_DIAGASSERT(dst !=3D NULL);
 	_DIAGASSERT(src !=3D NULL);
 	_DIAGASSERT(extra !=3D NULL);
-
-	for (start =3D dst; (c =3D *src++) !=3D '\0'; /* empty */)
-	    SVIS(dst, c, flag, *src, extra);
+	MAKEEXTRALIST(flag, nextra, extra);
+	if (!nextra) {
+		*dst =3D '\0';		/* can't create nextra, return "" */
+		return 0;
+	}
+	if (flag & VIS_HTTPSTYLE) {
+		for (start =3D dst; (c =3D *src++) !=3D '\0'; /* empty */)
+			dst =3D do_hvis(dst, c, flag, *src, nextra);
+	} else {
+		for (start =3D dst; (c =3D *src++) !=3D '\0'; /* empty */)
+			dst =3D do_svis(dst, c, flag, *src, nextra);
+	}
+	free(nextra);
 	*dst =3D '\0';
 	return (dst - start);
 }
=20
=20
-int ROKEN_LIB_FUNCTION
-rk_strsvisx(char *dst, const char *src, size_t len, int flag, const char *=
extra)
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+rk_strsvisx(char *dst, const char *csrc, size_t len, int flag, const char =
*extra)
 {
-	char c;
+	unsigned char c;
 	char *start;
+	char *nextra =3D NULL;
+	const unsigned char *src =3D (const unsigned char *)csrc;
=20
 	_DIAGASSERT(dst !=3D NULL);
 	_DIAGASSERT(src !=3D NULL);
 	_DIAGASSERT(extra !=3D NULL);
+	MAKEEXTRALIST(flag, nextra, extra);
+	if (! nextra) {
+		*dst =3D '\0';		/* can't create nextra, return "" */
+		return 0;
+	}
=20
-	for (start =3D dst; len > 0; len--) {
-		c =3D *src++;
-		SVIS(dst, c, flag, len ? *src : '\0', extra);
+	if (flag & VIS_HTTPSTYLE) {
+		for (start =3D dst; len > 0; len--) {
+			c =3D *src++;
+			dst =3D do_hvis(dst, c, flag, len ? *src : '\0', nextra);
+		}
+	} else {
+		for (start =3D dst; len > 0; len--) {
+			c =3D *src++;
+			dst =3D do_svis(dst, c, flag, len ? *src : '\0', nextra);
+		}
 	}
+	free(nextra);
 	*dst =3D '\0';
 	return (dst - start);
 }
+#endif
=20
-
+#if !HAVE_VIS
 /*
  * vis - visually encode characters
  */
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 rk_vis(char *dst, int c, int flag, int nextc)
 {
-	char extra[MAXEXTRAS];
+	char *extra =3D NULL;
+	unsigned char uc =3D (unsigned char)c;
=20
 	_DIAGASSERT(dst !=3D NULL);
=20
-	MAKEEXTRALIST(flag, extra);
-	SVIS(dst, c, flag, nextc, extra);
+	MAKEEXTRALIST(flag, extra, "");
+	if (! extra) {
+		*dst =3D '\0';		/* can't create extra, return "" */
+		return dst;
+	}
+	if (flag & VIS_HTTPSTYLE)
+		dst =3D do_hvis(dst, uc, flag, nextc, extra);
+	else
+		dst =3D do_svis(dst, uc, flag, nextc, extra);
+	free(extra);
 	*dst =3D '\0';
-	return (dst);
+	return dst;
 }
=20
=20
 /*
  * strvis, strvisx - visually encode characters from src into dst
- *=09
+ *
  *	Dst must be 4 times the size of src to account for possible
  *	expansion.  The length of dst, not including the trailing NULL,
- *	is returned.=20
+ *	is returned.
  *
  *	Strvisx encodes exactly len bytes from src into dst.
  *	This is useful for encoding a block of data.
  */
-
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rk_strvis(char *dst, const char *src, int flag)
 {
-	char extra[MAXEXTRAS];
+	char *extra =3D NULL;
+	int rv;
=20
-	MAKEEXTRALIST(flag, extra);
-	return (rk_strsvis(dst, src, flag, extra));
+	MAKEEXTRALIST(flag, extra, "");
+	if (!extra) {
+		*dst =3D '\0';		/* can't create extra, return "" */
+		return 0;
+	}
+	rv =3D strsvis(dst, src, flag, extra);
+	free(extra);
+	return rv;
 }
=20
=20
-int ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
 rk_strvisx(char *dst, const char *src, size_t len, int flag)
 {
-	char extra[MAXEXTRAS];
+	char *extra =3D NULL;
+	int rv;
=20
-	MAKEEXTRALIST(flag, extra);
-	return (rk_strsvisx(dst, src, len, flag, extra));
+	MAKEEXTRALIST(flag, extra, "");
+	if (!extra) {
+		*dst =3D '\0';		/* can't create extra, return "" */
+		return 0;
+	}
+	rv =3D strsvisx(dst, src, len, flag, extra);
+	free(extra);
+	return rv;
 }
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/vis.hin
--- a/head/crypto/heimdal/lib/roken/vis.hin	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/vis.hin	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,4 @@
-/*	$NetBSD: vis.h,v 1.11 1999/11/25 16:55:50 wennmach Exp $	*/
-/*	$Id: vis.hin 19341 2006-12-15 11:53:09Z lha $	*/
+/*	$NetBSD: vis.h,v 1.16 2005/09/13 01:44:32 christos Exp $	*/
=20
 /*-
  * Copyright (c) 1990, 1993
@@ -37,12 +36,18 @@
=20
 #ifndef ROKEN_LIB_FUNCTION
 #ifdef _WIN32
-#define ROKEN_LIB_FUNCTION _stdcall
+#define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL     __cdecl
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
 #endif
 #endif
=20
+#include <sys/types.h>
+
+#include <roken.h>
+
 /*
  * to select alternate encoding format
  */
@@ -63,6 +68,7 @@
  * other
  */
 #define	VIS_NOSLASH	0x40	/* inhibit printing '\' */
+#define	VIS_HTTPSTYLE	0x80	/* http-style escape % HEX HEX */
=20
 /*
  * unvis return codes
@@ -78,38 +84,68 @@
  */
 #define	UNVIS_END	1	/* no more characters */
=20
-char ROKEN_LIB_FUNCTION
-	*rk_vis (char *, int, int, int);
-char ROKEN_LIB_FUNCTION
-	*rk_svis (char *, int, int, int, const char *);
-int ROKEN_LIB_FUNCTION
-	rk_strvis (char *, const char *, int);
-int ROKEN_LIB_FUNCTION
-	rk_strsvis (char *, const char *, int, const char *);
-int ROKEN_LIB_FUNCTION
-	rk_strvisx (char *, const char *, size_t, int);
-int ROKEN_LIB_FUNCTION
-	rk_strsvisx (char *, const char *, size_t, int, const char *);
-int ROKEN_LIB_FUNCTION
-	rk_strunvis (char *, const char *);
-int ROKEN_LIB_FUNCTION
-	rk_unvis (char *, int, int *, int);
+ROKEN_CPP_START
=20
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+	rk_vis(char *, int, int, int);
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
+	rk_svis(char *, int, int, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_strvis(char *, const char *, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_strsvis(char *, const char *, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_strvisx(char *, const char *, size_t, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_strsvisx(char *, const char *, size_t, int, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_strunvis(char *, const char *);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_strunvisx(char *, const char *, int);
+ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL
+	rk_unvis(char *, int, int *, int);
+
+ROKEN_CPP_END
+
+#ifndef HAVE_VIS
 #undef vis
 #define vis(a,b,c,d) rk_vis(a,b,c,d)
+#endif
+
+#ifndef HAVE_SVIS
 #undef svis
 #define svis(a,b,c,d,e) rk_svis(a,b,c,d,e)
+#endif
+
+#ifndef HAVE_STRVIS
 #undef strvis
 #define strvis(a,b,c) rk_strvis(a,b,c)
+#endif
+
+#ifndef HAVE_STRSVIS
 #undef strsvis
 #define strsvis(a,b,c,d) rk_strsvis(a,b,c,d)
+#endif
+
+#ifndef HAVE_STRVISX
 #undef strvisx
 #define strvisx(a,b,c,d) rk_strvisx(a,b,c,d)
+#endif
+
+#ifndef HAVE_STRSVISX
 #undef strsvisx
 #define strsvisx(a,b,c,d,e) rk_strsvisx(a,b,c,d,e)
+#endif
+
+#ifndef HAVE_STRUNVIS
 #undef strunvis
 #define strunvis(a,b) rk_strunvis(a,b)
+#endif
+
+
+#ifndef HAVE_UNVIS
 #undef unvis
 #define unvis(a,b,c,d) rk_unvis(a,b,c,d)
+#endif
=20
 #endif /* !_VIS_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/vsyslog.c
--- a/head/crypto/heimdal/lib/roken/vsyslog.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/vsyslog.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: vsyslog.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #ifndef HAVE_VSYSLOG
=20
@@ -61,12 +58,13 @@
  * do like syslog but with a `va_list'
  */
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 vsyslog(int pri, const char *fmt, va_list ap)
 {
     char *fmt2;
     const char *p;
     char *p2;
+    int ret;
     int saved_errno =3D errno;
     int fmt_len  =3D strlen (fmt);
     int fmt2_len =3D fmt_len;
@@ -103,9 +101,9 @@
     }
     *p2 =3D '\0';
=20
-    vasprintf (&buf, fmt2, ap);
+    ret =3D vasprintf (&buf, fmt2, ap);
     free (fmt2);
-    if (buf =3D=3D NULL) {
+    if (ret < 0 || buf =3D=3D NULL) {
 	simple_vsyslog (pri, fmt, ap);
 	return;
     }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/vwarn.c
--- a/head/crypto/heimdal/lib/roken/vwarn.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/vwarn.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,13 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: vwarn.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
 #include <err.h>
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 vwarn(const char *fmt, va_list ap)
 {
-    warnerr(1, fmt, ap);
+    rk_warnerr(1, fmt, ap);
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/vwarnx.c
--- a/head/crypto/heimdal/lib/roken/vwarnx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/vwarnx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,17 +31,14 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: vwarnx.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
 #include <err.h>
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 vwarnx(const char *fmt, va_list ap)
 {
-    warnerr(0, fmt, ap);
+    rk_warnerr(0, fmt, ap);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/warn.c
--- a/head/crypto/heimdal/lib/roken/warn.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/warn.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: warn.c 7463 1999-12-02 16:58:55Z joda $");
-#endif
=20
 #include "err.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/warnerr.c
--- a/head/crypto/heimdal/lib/roken/warnerr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/warnerr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2001 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,16 +31,13 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: warnerr.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
 #include "err.h"
=20
-void ROKEN_LIB_FUNCTION
-warnerr(int doerrno, const char *fmt, va_list ap)
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
+rk_warnerr(int doerrno, const char *fmt, va_list ap)
 {
     int sverrno =3D errno;
     const char *progname =3D getprogname();
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/warnx.c
--- a/head/crypto/heimdal/lib/roken/warnx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/warnx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=F6gskolan=20
- * (Royal Institute of Technology, Stockholm, Sweden). =20
+ * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: warnx.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "err.h"
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 warnx(const char *fmt, ...)
 {
   va_list ap;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/write_pi=
d.c
--- a/head/crypto/heimdal/lib/roken/write_pid.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/roken/write_pid.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,56 +1,47 @@
 /*
- * Copyright (c) 1999 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1999 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: write_pid.c 21005 2007-06-08 01:54:35Z lha $");
-#endif
-
-#include <stdio.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include "roken.h"
=20
 #include "roken.h"
=20
-char * ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION char * ROKEN_LIB_CALL
 pid_file_write (const char *progname)
 {
+    char *ret =3D NULL;
     FILE *fp;
-    char *ret;
=20
-    asprintf (&ret, "%s%s.pid", _PATH_VARRUN, progname);
-    if (ret =3D=3D NULL)
+    if (asprintf (&ret, "%s%s.pid", _PATH_VARRUN, progname) < 0 || ret =3D=
=3D NULL)
 	return NULL;
     fp =3D fopen (ret, "w");
     if (fp =3D=3D NULL) {
@@ -62,7 +53,7 @@
     return ret;
 }
=20
-void ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 pid_file_delete (char **filename)
 {
     if (*filename !=3D NULL) {
@@ -82,7 +73,7 @@
 	pid_file_delete(&pidfile_path);
 }
=20
-void
+ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
 pidfile(const char *basename)
 {
     if(pidfile_path !=3D NULL)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/writev.c
--- a/head/crypto/heimdal/lib/roken/writev.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/writev.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska H=C3=B6gsk=
olan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,14 +31,11 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: writev.c 14773 2005-04-12 11:29:18Z lha $");
-#endif
=20
 #include "roken.h"
=20
-ssize_t ROKEN_LIB_FUNCTION
+ROKEN_LIB_FUNCTION ssize_t ROKEN_LIB_CALL
 writev(int d, const struct iovec *iov, int iovcnt)
 {
     ssize_t ret;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/roken/xdbm.h
--- a/head/crypto/heimdal/lib/roken/xdbm.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/roken/xdbm.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2002 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2002 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: xdbm.h 10986 2002-05-17 16:02:22Z joda $ */
+/* $Id$ */
=20
 /* Generic *dbm include file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/ChangeLog
--- a/head/crypto/heimdal/lib/sl/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,14 +1,18 @@
-2007-07-17  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2008-05-05  Love H=C3=B6rnquist =C3=85strand  <lha at vit.local>
+
+	* drop libss and make_cmds
+
+2007-07-17  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: roken_rename.h is a dist_ source k
=20
 	* Makefile.am: split source files in dist and nodist.
=20
-2007-07-10  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-07-10  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: New library version.
=20
-2007-06-18  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-18  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* sl.c: make compile.
=20
@@ -17,25 +21,25 @@
 	* sl.c (sl_make_argv): use memmove since we are dealing with
 	overlapping strings.
=20
-2007-06-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: don't clean yacc/lex files in CLEANFILES,
 	maintainers clean will do that for us.
 =09
-2007-06-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-06-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* slc-gram.y (main): also fclose yyin.
 =09
-2007-04-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-04-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: Add dependency on slc-gram.h for slc-lex.c, breaks
 	in disttree with make -j
 =09
-2006-12-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* test_sl.c: Fix caseing for case-sensitive filesystems
 =09
-2006-12-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* test_sl.c: catch test that should fail but didn't
=20
@@ -47,32 +51,32 @@
=20
 	* sl.c (sl_make_argv): Add quoting support (both "" and \ style).
 =09
-2006-12-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* sl.c: Use strcspn to remove \n from fgets result. Prompted by
-	change by Ray Lai of OpenBSD via Bj=F6rn Sandell.
+	change by Ray Lai of OpenBSD via Bj=C3=B6rn Sandell.
 =09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am (ES): add roken_rename.h
 =09
-2006-08-30  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-30  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* sl.c (sl_slc_help): remove return
 =09
-2006-08-28  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-08-28  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* sl.h: Add sl_slc_help.
=20
 	* sl.c: Add sl_slc_help.
 =09
-2005-07-27  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-07-27  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* slc-gram.y (gen_wrapper): use the generated version of name for
 	function, if no function is is used, also use the generated name
 	for the structure name.
 =09
-2005-06-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-06-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* slc-gram.y: fix a merge error
 =09
@@ -90,7 +94,7 @@
=20
 	* slc-lex.l: Include <stdlib.h>.
=20
-2005-05-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-05-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* sl.c (sl_command_loop): new return code -2 for EOF
 	(sl_loop): treat all return value from sl_command_loop >=3D 0 as ok, and
@@ -100,7 +104,7 @@
=20
 	* Makefile.am (LDADD): Add libsl.la.
=20
-2005-04-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-04-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* slc-gram.y: include <config.h> since defines _GNU_SOURCE if
 	needed, avoid asprintf warning
@@ -109,7 +113,7 @@
=20
 	* slc-gram.y: include <roken.h>
=20
-2005-01-09  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-09  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* slc-gram.y: cast argument to isalnum to unsigned char
=20
@@ -122,11 +126,11 @@
=20
 	* slc-gram.y: add min_args/max_args checking
 =09
-2004-06-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-06-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* slc-gram.y: pull in <stdlib.h> and <vers.h> to avoid warnings
 =09
-2004-03-02  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-03-02  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* sl.h: make it possible to use libsl from c++
 	From: Mattias Amnefelt <mattiasa at kth.se>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/Makefile.am
--- a/head/crypto/heimdal/lib/sl/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 21625 2007-07-17 07:48:26Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -12,42 +12,28 @@
=20
 include_HEADERS =3D sl.h
=20
-lib_LTLIBRARIES =3D libsl.la libss.la
+lib_LTLIBRARIES =3D libsl.la
 libsl_la_LDFLAGS =3D -version-info 2:1:2
-libss_la_LDFLAGS =3D -version-info 1:6:1
=20
 libsl_la_LIBADD =3D @LIB_readline@
-libss_la_LIBADD =3D @LIB_readline@ @LIB_com_err@
=20
 dist_libsl_la_SOURCES =3D sl_locl.h sl.c roken_rename.h
 nodist_libsl_la_SOURCES =3D $(ES)
-dist_libss_la_SOURCES =3D $(dist_libsl_la_SOURCES) ss.c ss.h
-nodist_libss_la_SOURCES =3D $(ES)
=20
 TESTS =3D test_sl
 check_PROGRAMS =3D $(TESTS)=09
=20
 # install these?
=20
-bin_PROGRAMS =3D mk_cmds
-noinst_PROGRAMS =3D slc
-
-mk_cmds_SOURCES =3D make_cmds.c make_cmds.h parse.y lex.l
-mk_cmds_LDADD =3D libsl.la $(LDADD)
+libexec_heimdal_PROGRAMS =3D slc
=20
 slc_SOURCES =3D slc-gram.y slc-lex.l slc.h
=20
-ssincludedir =3D $(includedir)/ss
-ssinclude_HEADERS =3D ss.h
+CLEANFILES =3D snprintf.c strtok_r.c strdup.c strupr.c getprogname.c slc-l=
ex.c
=20
-CLEANFILES =3D snprintf.c strtok_r.c strdup.c strupr.c getprogname.c
+LDADD =3D	libsl.la $(LIB_roken)
=20
-$(mk_cmds_OBJECTS): parse.h parse.c
-
-LDADD =3D						\
-	libsl.la				\
-	$(LIB_roken)				\
-	$(LEXLIB)
+slc_LDADD =3D $(LEXLIB) $(LDADD)
=20
 strtok_r.c:
 	$(LN_S) $(srcdir)/../roken/strtok_r.c .
@@ -61,3 +47,5 @@
 	$(LN_S) $(srcdir)/../roken/getprogname.c .
=20
 slc-lex.c: slc-gram.h
+
+EXTRA_DIST =3D NTMakefile
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/Makefile.in
--- a/head/crypto/heimdal/lib/sl/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,18 +15,19 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 21625 2007-07-17 07:48:26Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -41,18 +43,16 @@
 build_triplet =3D @build@
 host_triplet =3D @host@
 DIST_COMMON =3D $(include_HEADERS) $(srcdir)/Makefile.am \
-	$(srcdir)/Makefile.in $(ssinclude_HEADERS) \
-	$(top_srcdir)/Makefile.am.common \
-	$(top_srcdir)/cf/Makefile.am.common ChangeLog lex.c parse.c \
-	parse.h slc-gram.c slc-gram.h slc-lex.c
+	$(srcdir)/Makefile.in $(top_srcdir)/Makefile.am.common \
+	$(top_srcdir)/cf/Makefile.am.common ChangeLog slc-gram.c \
+	slc-gram.h slc-lex.c
 TESTS =3D test_sl$(EXEEXT)
 check_PROGRAMS =3D $(am__EXEEXT_1)
-bin_PROGRAMS =3D mk_cmds$(EXEEXT)
-noinst_PROGRAMS =3D slc$(EXEEXT)
+libexec_heimdal_PROGRAMS =3D slc$(EXEEXT)
 subdir =3D lib/sl
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -67,7 +67,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -81,9 +81,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -91,21 +94,36 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
-am__installdirs =3D "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \
-	"$(DESTDIR)$(includedir)" "$(DESTDIR)$(ssincludedir)"
-libLTLIBRARIES_INSTALL =3D $(INSTALL)
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
+am__installdirs =3D "$(DESTDIR)$(libdir)" \
+	"$(DESTDIR)$(libexec_heimdaldir)" "$(DESTDIR)$(includedir)"
 LTLIBRARIES =3D $(lib_LTLIBRARIES)
 libsl_la_DEPENDENCIES =3D
 dist_libsl_la_OBJECTS =3D sl.lo
@@ -116,36 +134,20 @@
 libsl_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS)=
 \
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(libsl_la_LDFLAGS) \
 	$(LDFLAGS) -o $@
-libss_la_DEPENDENCIES =3D
-am__objects_2 =3D sl.lo
-dist_libss_la_OBJECTS =3D $(am__objects_2) ss.lo
-nodist_libss_la_OBJECTS =3D $(am__objects_1)
-libss_la_OBJECTS =3D $(dist_libss_la_OBJECTS) $(nodist_libss_la_OBJECTS)
-libss_la_LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS)=
 \
-	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(libss_la_LDFLAGS) \
-	$(LDFLAGS) -o $@
-binPROGRAMS_INSTALL =3D $(INSTALL_PROGRAM)
 am__EXEEXT_1 =3D test_sl$(EXEEXT)
-PROGRAMS =3D $(bin_PROGRAMS) $(noinst_PROGRAMS)
-am_mk_cmds_OBJECTS =3D make_cmds.$(OBJEXT) parse.$(OBJEXT) lex.$(OBJEXT)
-mk_cmds_OBJECTS =3D $(am_mk_cmds_OBJECTS)
-am__DEPENDENCIES_1 =3D
-am__DEPENDENCIES_2 =3D libsl.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-mk_cmds_DEPENDENCIES =3D libsl.la $(am__DEPENDENCIES_2)
+PROGRAMS =3D $(libexec_heimdal_PROGRAMS)
 am_slc_OBJECTS =3D slc-gram.$(OBJEXT) slc-lex.$(OBJEXT)
 slc_OBJECTS =3D $(am_slc_OBJECTS)
-slc_LDADD =3D $(LDADD)
-slc_DEPENDENCIES =3D libsl.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
+am__DEPENDENCIES_1 =3D
+am__DEPENDENCIES_2 =3D libsl.la $(am__DEPENDENCIES_1)
+slc_DEPENDENCIES =3D $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_2)
 test_sl_SOURCES =3D test_sl.c
 test_sl_OBJECTS =3D test_sl.$(OBJEXT)
 test_sl_LDADD =3D $(LDADD)
-test_sl_DEPENDENCIES =3D libsl.la $(am__DEPENDENCIES_1) \
-	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+test_sl_DEPENDENCIES =3D libsl.la $(am__DEPENDENCIES_1)
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -165,63 +167,70 @@
 LTYACCCOMPILE =3D $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dcompile $(YACC) $(YFLAGS) $(AM_YFLAGS)
 SOURCES =3D $(dist_libsl_la_SOURCES) $(nodist_libsl_la_SOURCES) \
-	$(dist_libss_la_SOURCES) $(nodist_libss_la_SOURCES) \
-	$(mk_cmds_SOURCES) $(slc_SOURCES) test_sl.c
-DIST_SOURCES =3D $(dist_libsl_la_SOURCES) $(dist_libss_la_SOURCES) \
-	$(mk_cmds_SOURCES) $(slc_SOURCES) test_sl.c
-includeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-ssincludeHEADERS_INSTALL =3D $(INSTALL_HEADER)
-HEADERS =3D $(include_HEADERS) $(ssinclude_HEADERS)
+	$(slc_SOURCES) test_sl.c
+DIST_SOURCES =3D $(dist_libsl_la_SOURCES) $(slc_SOURCES) test_sl.c
+HEADERS =3D $(include_HEADERS)
 ETAGS =3D etags
 CTAGS =3D ctags
+am__tty_colors =3D \
+red=3D; grn=3D; lgn=3D; blu=3D; std=3D
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -245,10 +254,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -265,6 +275,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -280,31 +292,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -319,10 +345,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -363,69 +391,63 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken) \
-	$(ROKEN_RENAME)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken) $(ROKEN_RENAME)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 @do_roken_rename_TRUE at ES =3D strtok_r.c snprintf.c strdup.c strupr.c getpr=
ogname.c
 include_HEADERS =3D sl.h
-lib_LTLIBRARIES =3D libsl.la libss.la
+lib_LTLIBRARIES =3D libsl.la
 libsl_la_LDFLAGS =3D -version-info 2:1:2
-libss_la_LDFLAGS =3D -version-info 1:6:1
 libsl_la_LIBADD =3D @LIB_readline@
-libss_la_LIBADD =3D @LIB_readline@ @LIB_com_err@
 dist_libsl_la_SOURCES =3D sl_locl.h sl.c roken_rename.h
 nodist_libsl_la_SOURCES =3D $(ES)
-dist_libss_la_SOURCES =3D $(dist_libsl_la_SOURCES) ss.c ss.h
-nodist_libss_la_SOURCES =3D $(ES)
-mk_cmds_SOURCES =3D make_cmds.c make_cmds.h parse.y lex.l
-mk_cmds_LDADD =3D libsl.la $(LDADD)
 slc_SOURCES =3D slc-gram.y slc-lex.l slc.h
-ssincludedir =3D $(includedir)/ss
-ssinclude_HEADERS =3D ss.h
-CLEANFILES =3D snprintf.c strtok_r.c strdup.c strupr.c getprogname.c
-LDADD =3D \
-	libsl.la				\
-	$(LIB_roken)				\
-	$(LEXLIB)
-
+CLEANFILES =3D snprintf.c strtok_r.c strdup.c strupr.c getprogname.c slc-l=
ex.c
+LDADD =3D libsl.la $(LIB_roken)
+slc_LDADD =3D $(LEXLIB) $(LDADD)
+EXTRA_DIST =3D NTMakefile
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .l .lo .o .=
obj .y
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .l .lo =
.o .obj .y
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/sl/Ma=
kefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/sl/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/sl/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/sl/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -443,23 +465,28 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-libLTLIBRARIES: $(lib_LTLIBRARIES)
 	@$(NORMAL_INSTALL)
 	test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)"
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	list2=3D; for p in $$list; do \
 	  if test -f $$p; then \
-	    f=3D$(am__strip_dir) \
-	    echo " $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTAL=
L_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \
-	    $(LIBTOOL) --mode=3Dinstall $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP=
_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \
+	    list2=3D"$$list2 $$p"; \
 	  else :; fi; \
-	done
+	done; \
+	test -z "$$list2" || { \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $=
(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Dinstall $(INSTAL=
L) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \
+	}
=20
 uninstall-libLTLIBRARIES:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(lib_LTLIBRARIES)'; for p in $$list; do \
-	  p=3D$(am__strip_dir) \
-	  echo " $(LIBTOOL) --mode=3Duninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \
-	  $(LIBTOOL) --mode=3Duninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \
+	@list=3D'$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=3D; \
+	for p in $$list; do \
+	  $(am__strip_dir) \
+	  echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall=
 rm -f '$(DESTDIR)$(libdir)/$$f'"; \
+	  $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=3Duninstall rm -f =
"$(DESTDIR)$(libdir)/$$f"; \
 	done
=20
 clean-libLTLIBRARIES:
@@ -472,58 +499,58 @@
 	done
 libsl.la: $(libsl_la_OBJECTS) $(libsl_la_DEPENDENCIES)=20
 	$(libsl_la_LINK) -rpath $(libdir) $(libsl_la_OBJECTS) $(libsl_la_LIBADD) =
$(LIBS)
-libss.la: $(libss_la_OBJECTS) $(libss_la_DEPENDENCIES)=20
-	$(libss_la_LINK) -rpath $(libdir) $(libss_la_OBJECTS) $(libss_la_LIBADD) =
$(LIBS)
-install-binPROGRAMS: $(bin_PROGRAMS)
-	@$(NORMAL_INSTALL)
-	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  p1=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  if test -f $$p \
-	     || test -f $$p1 \
-	  ; then \
-	    f=3D`echo "$$p1" | sed 's,^.*/,,;$(transform);s/$$/$(EXEEXT)/'`; \
-	   echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAM=
S_INSTALL) '$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	   $(INSTALL_PROGRAM_ENV) $(LIBTOOL) --mode=3Dinstall $(binPROGRAMS_INSTA=
LL) "$$p" "$(DESTDIR)$(bindir)/$$f" || exit 1; \
-	  else :; fi; \
-	done
-
-uninstall-binPROGRAMS:
-	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXE=
EXT)/'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
-
-clean-binPROGRAMS:
-	@list=3D'$(bin_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
=20
 clean-checkPROGRAMS:
-	@list=3D'$(check_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
+	@list=3D'$(check_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
+install-libexec_heimdalPROGRAMS: $(libexec_heimdal_PROGRAMS)
+	@$(NORMAL_INSTALL)
+	test -z "$(libexec_heimdaldir)" || $(MKDIR_P) "$(DESTDIR)$(libexec_heimda=
ldir)"
+	@list=3D'$(libexec_heimdal_PROGRAMS)'; test -n "$(libexec_heimdaldir)" ||=
 list=3D; \
+	for p in $$list; do echo "$$p $$p"; done | \
+	sed 's/$(EXEEXT)$$//' | \
+	while read p p1; do if test -f $$p || test -f $$p1; \
+	  then echo "$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \
+	    -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \
+	sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1 } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) files[d] =3D files[d] " " $$1; \
+	    else { print "f", $$3 "/" $$4, $$1; } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	    if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	    test -z "$$files" || { \
+	    echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOL=
FLAGS) --mode=3Dinstall $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(libexec_hei=
mdaldir)$$dir'"; \
+	    $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) =
--mode=3Dinstall $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(libexec_heimdaldir=
)$$dir" || exit $$?; \
+	    } \
+	; done
=20
-clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
-parse.h: parse.c
-	@if test ! -f $@; then \
-	  rm -f parse.c; \
-	  $(MAKE) $(AM_MAKEFLAGS) parse.c; \
-	else :; fi
-mk_cmds$(EXEEXT): $(mk_cmds_OBJECTS) $(mk_cmds_DEPENDENCIES)=20
-	@rm -f mk_cmds$(EXEEXT)
-	$(LINK) $(mk_cmds_OBJECTS) $(mk_cmds_LDADD) $(LIBS)
+uninstall-libexec_heimdalPROGRAMS:
+	@$(NORMAL_UNINSTALL)
+	@list=3D'$(libexec_heimdal_PROGRAMS)'; test -n "$(libexec_heimdaldir)" ||=
 list=3D; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	  sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \
+	      -e 's/$$/$(EXEEXT)/' `; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(libexec_heimdaldir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(libexec_heimdaldir)" && rm -f $$files
+
+clean-libexec_heimdalPROGRAMS:
+	@list=3D'$(libexec_heimdal_PROGRAMS)'; test -n "$$list" || exit 0; \
+	echo " rm -f" $$list; \
+	rm -f $$list || exit $$?; \
+	test -n "$(EXEEXT)" || exit 0; \
+	list=3D`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \
+	echo " rm -f" $$list; \
+	rm -f $$list
 slc-gram.h: slc-gram.c
 	@if test ! -f $@; then \
 	  rm -f slc-gram.c; \
@@ -542,14 +569,36 @@
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/getprogname.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/sl.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/slc-gram.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/slc-lex.Po at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/snprintf.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/strdup.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/strtok_r.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/strupr.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/test_sl.Po at am__quote@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 .l.c:
 	$(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMP=
ILE)
@@ -565,90 +614,81 @@
 install-includeHEADERS: $(include_HEADERS)
 	@$(NORMAL_INSTALL)
 	test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)"
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(includeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(includedir)/$$f'=
"; \
-	  $(includeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(includedir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \
+	  $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \
 	done
=20
 uninstall-includeHEADERS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(include_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(includedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(includedir)/$$f"; \
-	done
-install-ssincludeHEADERS: $(ssinclude_HEADERS)
-	@$(NORMAL_INSTALL)
-	test -z "$(ssincludedir)" || $(MKDIR_P) "$(DESTDIR)$(ssincludedir)"
-	@list=3D'$(ssinclude_HEADERS)'; for p in $$list; do \
-	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(ssincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(ssincludedir)/=
$$f'"; \
-	  $(ssincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(ssincludedir)/$$f"; \
-	done
-
-uninstall-ssincludeHEADERS:
-	@$(NORMAL_UNINSTALL)
-	@list=3D'$(ssinclude_HEADERS)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(ssincludedir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(ssincludedir)/$$f"; \
-	done
+	@list=3D'$(include_HEADERS)'; test -n "$(includedir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(includedir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(includedir)" && rm -f $$files
=20
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
 	list=3D'$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
=20
 check-TESTS: $(TESTS)
-	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; ws=3D'[	 ]'; \
+	@failed=3D0; all=3D0; xfail=3D0; xpass=3D0; skip=3D0; \
 	srcdir=3D$(srcdir); export srcdir; \
 	list=3D' $(TESTS) '; \
+	$(am__tty_colors); \
 	if test -n "$$list"; then \
 	  for tst in $$list; do \
 	    if test -f ./$$tst; then dir=3D./; \
@@ -657,49 +697,63 @@
 	    if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xpass=3D`expr $$xpass + 1`; \
 		failed=3D`expr $$failed + 1`; \
-		echo "XPASS: $$tst"; \
+		col=3D$$red; res=3DXPASS; \
 	      ;; \
 	      *) \
-		echo "PASS: $$tst"; \
+		col=3D$$grn; res=3DPASS; \
 	      ;; \
 	      esac; \
 	    elif test $$? -ne 77; then \
 	      all=3D`expr $$all + 1`; \
 	      case " $(XFAIL_TESTS) " in \
-	      *$$ws$$tst$$ws*) \
+	      *[\ \	]$$tst[\ \	]*) \
 		xfail=3D`expr $$xfail + 1`; \
-		echo "XFAIL: $$tst"; \
+		col=3D$$lgn; res=3DXFAIL; \
 	      ;; \
 	      *) \
 		failed=3D`expr $$failed + 1`; \
-		echo "FAIL: $$tst"; \
+		col=3D$$red; res=3DFAIL; \
 	      ;; \
 	      esac; \
 	    else \
 	      skip=3D`expr $$skip + 1`; \
-	      echo "SKIP: $$tst"; \
+	      col=3D$$blu; res=3DSKIP; \
 	    fi; \
+	    echo "$${col}$$res$${std}: $$tst"; \
 	  done; \
+	  if test "$$all" -eq 1; then \
+	    tests=3D"test"; \
+	    All=3D""; \
+	  else \
+	    tests=3D"tests"; \
+	    All=3D"All "; \
+	  fi; \
 	  if test "$$failed" -eq 0; then \
 	    if test "$$xfail" -eq 0; then \
-	      banner=3D"All $$all tests passed"; \
+	      banner=3D"$$All$$all $$tests passed"; \
 	    else \
-	      banner=3D"All $$all tests behaved as expected ($$xfail expected fai=
lures)"; \
+	      if test "$$xfail" -eq 1; then failures=3Dfailure; else failures=3Df=
ailures; fi; \
+	      banner=3D"$$All$$all $$tests behaved as expected ($$xfail expected =
$$failures)"; \
 	    fi; \
 	  else \
 	    if test "$$xpass" -eq 0; then \
-	      banner=3D"$$failed of $$all tests failed"; \
+	      banner=3D"$$failed of $$all $$tests failed"; \
 	    else \
-	      banner=3D"$$failed of $$all tests did not behave as expected ($$xpa=
ss unexpected passes)"; \
+	      if test "$$xpass" -eq 1; then passes=3Dpass; else passes=3Dpasses; =
fi; \
+	      banner=3D"$$failed of $$all $$tests did not behave as expected ($$x=
pass unexpected $$passes)"; \
 	    fi; \
 	  fi; \
 	  dashes=3D"$$banner"; \
 	  skipped=3D""; \
 	  if test "$$skip" -ne 0; then \
-	    skipped=3D"($$skip tests were not run)"; \
+	    if test "$$skip" -eq 1; then \
+	      skipped=3D"($$skip test was not run)"; \
+	    else \
+	      skipped=3D"($$skip tests were not run)"; \
+	    fi; \
 	    test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \
 	      dashes=3D"$$skipped"; \
 	  fi; \
@@ -710,11 +764,15 @@
 	      dashes=3D"$$report"; \
 	  fi; \
 	  dashes=3D`echo "$$dashes" | sed s/./=3D/g`; \
-	  echo "$$dashes"; \
+	  if test "$$failed" -eq 0; then \
+	    echo "$$grn$$dashes"; \
+	  else \
+	    echo "$$red$$dashes"; \
+	  fi; \
 	  echo "$$banner"; \
 	  test -z "$$skipped" || echo "$$skipped"; \
 	  test -z "$$report" || echo "$$report"; \
-	  echo "$$dashes"; \
+	  echo "$$dashes$$std"; \
 	  test "$$failed" -eq 0; \
 	else :; fi
=20
@@ -734,13 +792,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -752,10 +814,8 @@
 	$(MAKE) $(AM_MAKEFLAGS) check-TESTS check-local
 check: check-am
 all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) all-local
-install-binPROGRAMS: install-libLTLIBRARIES
-
 installdirs:
-	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(inclu=
dedir)" "$(DESTDIR)$(ssincludedir)"; do \
+	for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(libexec_heimdaldir)" "$(DES=
TDIR)$(includedir)"; do \
 	  test -z "$$dir" || $(MKDIR_P) "$$dir"; \
 	done
 install: install-am
@@ -779,23 +839,21 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
 	@echo "it deletes files that may require special tools to rebuild."
-	-rm -f lex.c
-	-rm -f parse.c
-	-rm -f parse.h
 	-rm -f slc-gram.c
 	-rm -f slc-gram.h
 	-rm -f slc-lex.c
 clean: clean-am
=20
-clean-am: clean-binPROGRAMS clean-checkPROGRAMS clean-generic \
-	clean-libLTLIBRARIES clean-libtool clean-noinstPROGRAMS \
-	mostlyclean-am
+clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \
+	clean-libexec_heimdalPROGRAMS clean-libtool mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -806,33 +864,45 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
=20
-install-data-am: install-includeHEADERS install-ssincludeHEADERS
+install-data-am: install-includeHEADERS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
-
 install-dvi: install-dvi-am
=20
-install-exec-am: install-binPROGRAMS install-libLTLIBRARIES
+install-dvi-am:
+
+install-exec-am: install-libLTLIBRARIES \
+	install-libexec_heimdalPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -849,33 +919,31 @@
=20
 ps-am:
=20
-uninstall-am: uninstall-binPROGRAMS uninstall-includeHEADERS \
-	uninstall-libLTLIBRARIES uninstall-ssincludeHEADERS
+uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES \
+	uninstall-libexec_heimdalPROGRAMS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-TESTS check-am \
-	check-local clean clean-binPROGRAMS clean-checkPROGRAMS \
-	clean-generic clean-libLTLIBRARIES clean-libtool \
-	clean-noinstPROGRAMS ctags dist-hook distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-binPROGRAMS install-data \
-	install-data-am install-data-hook install-dvi install-dvi-am \
-	install-exec install-exec-am install-exec-hook install-html \
-	install-html-am install-includeHEADERS install-info \
-	install-info-am install-libLTLIBRARIES install-man install-pdf \
-	install-pdf-am install-ps install-ps-am \
-	install-ssincludeHEADERS install-strip installcheck \
-	installcheck-am installdirs maintainer-clean \
+	check-local clean clean-checkPROGRAMS clean-generic \
+	clean-libLTLIBRARIES clean-libexec_heimdalPROGRAMS \
+	clean-libtool ctags dist-hook distclean distclean-compile \
+	distclean-generic distclean-libtool distclean-tags distdir dvi \
+	dvi-am html html-am info info-am install install-am \
+	install-data install-data-am install-data-hook install-dvi \
+	install-dvi-am install-exec install-exec-am install-exec-hook \
+	install-html install-html-am install-includeHEADERS \
+	install-info install-info-am install-libLTLIBRARIES \
+	install-libexec_heimdalPROGRAMS install-man install-pdf \
+	install-pdf-am install-ps install-ps-am install-strip \
+	installcheck installcheck-am installdirs maintainer-clean \
 	maintainer-clean-generic mostlyclean mostlyclean-compile \
 	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags uninstall uninstall-am uninstall-binPROGRAMS \
-	uninstall-hook uninstall-includeHEADERS \
-	uninstall-libLTLIBRARIES uninstall-ssincludeHEADERS
+	tags uninstall uninstall-am uninstall-hook \
+	uninstall-includeHEADERS uninstall-libLTLIBRARIES \
+	uninstall-libexec_heimdalPROGRAMS
=20
=20
 install-suid-programs:
@@ -946,6 +1014,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -1031,7 +1102,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -1045,8 +1116,6 @@
 	  fi ; \
 	done
=20
-$(mk_cmds_OBJECTS): parse.h parse.c
-
 strtok_r.c:
 	$(LN_S) $(srcdir)/../roken/strtok_r.c .
 snprintf.c:
@@ -1059,6 +1128,7 @@
 	$(LN_S) $(srcdir)/../roken/getprogname.c .
=20
 slc-lex.c: slc-gram.h
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/roken_renam=
e.h
--- a/head/crypto/heimdal/lib/sl/roken_rename.h	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/crypto/heimdal/lib/sl/roken_rename.h	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,67 +1,67 @@
 /*
- * Copyright (c) 1998 - 2001 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2001 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: roken_rename.h 9842 2001-05-06 21:47:54Z assar $ */
+/* $Id$ */
=20
 #ifndef __roken_rename_h__
 #define __roken_rename_h__
=20
 #ifndef HAVE_STRTOK_R
-#define strtok_r _sl_strtok_r
+#define rk_strtok_r _sl_strtok_r
 #endif
 #ifndef HAVE_SNPRINTF
-#define snprintf _sl_snprintf
+#define rk_snprintf _sl_snprintf
 #endif
 #ifndef HAVE_ASPRINTF
-#define asprintf _sl_asprintf
+#define rk_asprintf _sl_asprintf
 #endif
 #ifndef HAVE_ASNPRINTF
-#define asnprintf _sl_asnprintf
+#define rk_asnprintf _sl_asnprintf
 #endif
 #ifndef HAVE_VASPRINTF
-#define vasprintf _sl_vasprintf
+#define rk_vasprintf _sl_vasprintf
 #endif
 #ifndef HAVE_VASNPRINTF
-#define vasnprintf _sl_vasnprintf
+#define rk_vasnprintf _sl_vasnprintf
 #endif
 #ifndef HAVE_VSNPRINTF
-#define vsnprintf _sl_vsnprintf
+#define rk_vsnprintf _sl_vsnprintf
 #endif
 #ifndef HAVE_STRUPR
-#define strupr _sl_strupr
+#define rk_strupr _sl_strupr
 #endif
 #ifndef HAVE_STRDUP
-#define strdup _sl_strdup
+#define rk_strdup _sl_strdup
 #endif
=20
 #endif /* __roken_rename_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/sl.c
--- a/head/crypto/heimdal/lib/sl/sl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/sl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2006 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2006 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,10 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: sl.c 21160 2007-06-18 22:58:21Z lha $");
-#endif
=20
 #include "sl_locl.h"
 #include <setjmp.h>
@@ -61,7 +58,7 @@
     strncpy(cmd, p, sizeof(cmd));
     cmd[sizeof(cmd)-1] =3D '\0';
     strupr(cmd);
-      =20
+
     printf(".Dt %s SECTION\n", cmd);
     printf(".Os OPERATING_SYSTEM\n");
     printf(".Sh NAME\n");
@@ -75,7 +72,7 @@
 	    continue; */
 	printf(".Op Fl %s", c->name);
 	printf("\n");
-=09
+
     }
     if (extra_string && *extra_string)
 	printf (".Ar %s\n", extra_string);
@@ -156,7 +153,7 @@
 	if(prev_c)
 	    printf ("\n\t%s%s", prev_c->usage ? prev_c->usage : "",
 		    prev_c->usage ? "\n" : "");
-    } else {=20
+    } else {
 	c =3D sl_match (cmds, argv[1], 0);
 	if (c =3D=3D NULL)
 	    printf ("No such command: %s. "
@@ -224,7 +221,7 @@
     int argc, nargv;
     char **argv;
     int quote =3D 0;
-   =20
+
     nargv =3D 10;
     argv =3D malloc(nargv * sizeof(*argv));
     if(argv =3D=3D NULL)
@@ -302,7 +299,7 @@
     return s;
 }
=20
-/* return values:=20
+/* return values:
  * 0 on success,
  * -1 on fatal error,
  * -2 if EOF, or
@@ -314,8 +311,7 @@
     char *buf;
     int argc;
     char **argv;
-=09
-    ret =3D 0;
+
     buf =3D sl_readline(prompt);
     if(buf =3D=3D NULL)
 	return -2;
@@ -340,7 +336,7 @@
     return ret;
 }
=20
-int=20
+int
 sl_loop(SL_cmd *cmds, const char *prompt)
 {
     void *data =3D NULL;
@@ -375,8 +371,11 @@
 		     argv[0]);
 	} else {
 	    if(c->func) {
-		char *fake[] =3D { NULL, "--help", NULL };
+		static char help[] =3D "--help";
+		char *fake[3];
 		fake[0] =3D argv[0];
+		fake[1] =3D help;
+		fake[2] =3D NULL;
 		(*c->func)(2, fake);
 		fprintf(stderr, "\n");
 	    }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/sl.h
--- a/head/crypto/heimdal/lib/sl/sl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/sl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2004 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2004 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: sl.h 17948 2006-08-28 14:16:43Z lha $ */
+/* $Id$ */
=20
 #ifndef _SL_H
 #define _SL_H
@@ -41,10 +41,10 @@
 typedef int (*cmd_func)(int, char **);
=20
 struct sl_cmd {
-  char *name;
+  const char *name;
   cmd_func func;
-  char *usage;
-  char *help;
+  const char *usage;
+  const char *help;
 };
=20
 typedef struct sl_cmd SL_cmd;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/sl_locl.h
--- a/head/crypto/heimdal/lib/sl/sl_locl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/sl_locl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995, 1996, 1997, 1998 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,11 +31,9 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: sl_locl.h 19517 2006-12-27 20:27:00Z lha $ */
+/* $Id$ */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/slc-gram.c
--- a/head/crypto/heimdal/lib/sl/slc-gram.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/slc-gram.c	Tue Apr 17 11:51:51 2012 +0300
@@ -81,42 +81,39 @@
 #line 1 "slc-gram.y"
=20
 /*
- * Copyright (c) 2004-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: slc-gram.y 20767 2007-06-01 11:24:52Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -131,6 +128,12 @@
 extern FILE *yyin;
 extern struct assignment *assignment;
=20
+/* Declarations for Bison:
+ */
+#define YYMALLOC        malloc
+#define YYFREE          free
+
+
=20
 /* Enabling traces.  */
 #ifndef YYDEBUG
@@ -152,13 +155,13 @@
=20
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-#line 54 "slc-gram.y"
+#line 57 "slc-gram.y"
 {
 	char *string;
 	struct assignment *assignment;
 }
 /* Line 193 of yacc.c.  */
-#line 162 "slc-gram.c"
+#line 165 "slc-gram.c"
 	YYSTYPE;
 # define yystype YYSTYPE /* obsolescent; will be withdrawn */
 # define YYSTYPE_IS_DECLARED 1
@@ -171,7 +174,7 @@
=20
=20
 /* Line 216 of yacc.c.  */
-#line 175 "slc-gram.c"
+#line 178 "slc-gram.c"
=20
 #ifdef short
 # undef short
@@ -453,7 +456,7 @@
 /* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
 static const yytype_uint8 yyrline[] =3D
 {
-       0,    67,    67,    73,    78,    81,    90
+       0,    70,    70,    76,    81,    84,    93
 };
 #endif
=20
@@ -1353,14 +1356,14 @@
   switch (yyn)
     {
         case 2:
-#line 68 "slc-gram.y"
+#line 71 "slc-gram.y"
     {
 			assignment =3D (yyvsp[(1) - (1)].assignment);
 		}
     break;
=20
   case 3:
-#line 74 "slc-gram.y"
+#line 77 "slc-gram.y"
     {
 			(yyvsp[(1) - (2)].assignment)->next =3D (yyvsp[(2) - (2)].assignment);
 			(yyval.assignment) =3D (yyvsp[(1) - (2)].assignment);
@@ -1368,7 +1371,7 @@
     break;
=20
   case 5:
-#line 82 "slc-gram.y"
+#line 85 "slc-gram.y"
     {
 			(yyval.assignment) =3D malloc(sizeof(*(yyval.assignment)));
 			(yyval.assignment)->name =3D (yyvsp[(1) - (3)].string);
@@ -1380,7 +1383,7 @@
     break;
=20
   case 6:
-#line 91 "slc-gram.y"
+#line 94 "slc-gram.y"
     {
 			(yyval.assignment) =3D malloc(sizeof(*(yyval.assignment)));
 			(yyval.assignment)->name =3D (yyvsp[(1) - (5)].string);
@@ -1393,7 +1396,7 @@
=20
=20
 /* Line 1267 of yacc.c.  */
-#line 1397 "slc-gram.c"
+#line 1400 "slc-gram.c"
       default: break;
     }
   YY_SYMBOL_PRINT ("-> $$ =3D", yyr1[yyn], &yyval, &yyloc);
@@ -1607,7 +1610,7 @@
 }
=20
=20
-#line 101 "slc-gram.y"
+#line 104 "slc-gram.y"
=20
 char *filename;
 FILE *cfile, *hfile;
@@ -1633,6 +1636,7 @@
 {
     struct assignment *a;
     int seen_long =3D 0;
+    int seen_name =3D 0;
     int seen_short =3D 0;
     int seen_type =3D 0;
     int seen_argument =3D 0;
@@ -1645,6 +1649,8 @@
 	    seen_long++;
 	else if(strcmp(a->name, "short") =3D=3D 0)
 	    seen_short++;
+	else if(strcmp(a->name, "name") =3D=3D 0)
+	    seen_name++;
 	else if(strcmp(a->name, "type") =3D=3D 0)
 	    seen_type++;
 	else if(strcmp(a->name, "argument") =3D=3D 0)
@@ -1654,7 +1660,7 @@
 	else if(strcmp(a->name, "default") =3D=3D 0)
 	    seen_default++;
 	else {
-	    ex(a, "unknown name");
+	    ex(a, "unknown name %s", a->name);
 	    ret++;
 	}
     }
@@ -1662,6 +1668,10 @@
 	ex(as, "neither long nor short option");
 	ret++;
     }
+    if (seen_long =3D=3D 0 && seen_name =3D=3D 0) {
+	ex(as, "either of long or name option must be used");
+	ret++;
+    }
     if(seen_long > 1) {
 	ex(as, "multiple long options");
 	ret++;
@@ -1716,7 +1726,7 @@
 		} else if(strcmp(a->name, "max_args") =3D=3D 0) {
 			seen_maxargs++;
 		} else {
-			ex(a, "unknown name");
+			ex(a, "unknown name: %s", a->name);
 			ret++;
 		}
 	}
@@ -1744,7 +1754,7 @@
 		ex(as, "multiple max_args strings");
 		ret++;
 	}
-=09
+
 	return ret;
 }
=20
@@ -1866,7 +1876,7 @@
 	lopt =3D find(as, "name");
     if(lopt =3D=3D NULL)
 	return NULL;
-   =20
+
     type =3D find(as, "type");
     if(strcmp(type->u.value, "-flag") =3D=3D 0)
 	asprintf(&s, "%s_flag", lopt->u.value);
@@ -1884,10 +1894,17 @@
     else
 	cprint(1, "opt.%s =3D 0;\n", name);
 }
-static void defval_string(const char *name, struct assignment *defval)=20
+static void defval_neg_flag(const char *name, struct assignment *defval)
 {
     if(defval !=3D NULL)
-	cprint(1, "opt.%s =3D \"%s\";\n", name, defval->u.value);
+	cprint(1, "opt.%s =3D %s;\n", name, defval->u.value);
+    else
+	cprint(1, "opt.%s =3D 1;\n", name);
+}
+static void defval_string(const char *name, struct assignment *defval)
+{
+    if(defval !=3D NULL)
+	cprint(1, "opt.%s =3D (char *)(unsigned long)\"%s\";\n", name, defval->u.=
value);
     else
 	cprint(1, "opt.%s =3D NULL;\n", name);
 }
@@ -1936,7 +1953,7 @@
 	{ "-flag",
 	  "int",
 	  "arg_negative_flag",
-	  defval_int,
+	  defval_neg_flag,
 	  NULL
 	},
 	{ NULL }
@@ -1959,13 +1976,13 @@
=20
     hprint(0, "struct %s_options {\n", name);
=20
-    for(tmp =3D opt1;=20
-	tmp !=3D NULL;=20
+    for(tmp =3D opt1;
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	struct assignment *type;
 	struct type_handler *th;
 	char *s;
-=09
+
 	s =3D make_name(tmp->u.assignment);
 	type =3D find(tmp->u.assignment, "type");
 	th =3D find_handler(type);
@@ -1985,19 +2002,22 @@
     struct assignment *tmp;
     char *n, *f;
     int nargs =3D 0;
+    int narguments =3D 0;
=20
     name =3D find(as, "name");
     n =3D strdup(name->u.value);
     gen_name(n);
     arg =3D find(as, "argument");
+    if (arg)
+        narguments++;
     opt1 =3D find(as, "option");
     function =3D find(as, "function");
     if(function)
 	f =3D function->u.value;
     else
 	f =3D n;
-   =20
-      =20
+
+
     if(opt1 !=3D NULL) {
 	gen_options(opt1, n);
 	hprint(0, "int %s(struct %s_options*, int, char **);\n", f, n);
@@ -2013,8 +2033,8 @@
     cprint(1, "int ret;\n");
     cprint(1, "int optidx =3D 0;\n");
     cprint(1, "struct getargs args[] =3D {\n");
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	struct assignment *type =3D find(tmp->u.assignment, "type");
 	struct assignment *lopt =3D find(tmp->u.assignment, "long");
@@ -2023,7 +2043,7 @@
 	struct assignment *help =3D find(tmp->u.assignment, "help");
=20
 	struct type_handler *th;
-=09
+
 	cprint(2, "{ ");
 	if(lopt)
 	    fprintf(cfile, "\"%s\", ", lopt->u.value);
@@ -2040,9 +2060,10 @@
 	    fprintf(cfile, "\"%s\", ", help->u.value);
 	else
 	    fprintf(cfile, "NULL, ");
-	if(aarg)
+	if(aarg) {
 	    fprintf(cfile, "\"%s\"", aarg->u.value);
-	else
+            narguments++;
+	} else
 	    fprintf(cfile, "NULL");
 	fprintf(cfile, " },\n");
     }
@@ -2050,8 +2071,8 @@
     cprint(1, "};\n");
     cprint(1, "int help_flag =3D 0;\n");
=20
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	struct assignment *type =3D find(tmp->u.assignment, "type");
@@ -2059,15 +2080,15 @@
 	struct assignment *defval =3D find(tmp->u.assignment, "default");
=20
 	struct type_handler *th;
-=09
+
 	s =3D make_name(tmp->u.assignment);
 	th =3D find_handler(type);
 	(*th->defval)(s, defval);
 	free(s);
     }
=20
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	s =3D make_name(tmp->u.assignment);
@@ -2082,7 +2103,7 @@
 	int min_args =3D -1;
 	int max_args =3D -1;
 	char *end;
-	if(arg =3D=3D NULL) {
+	if(narguments =3D=3D 0) {
 	    max_args =3D 0;
 	} else {
 	    if((tmp =3D find(as, "min_args")) !=3D NULL) {
@@ -2110,7 +2131,7 @@
 	}
 	if(min_args !=3D -1 || max_args !=3D -1) {
 	    if(min_args =3D=3D max_args) {
-		cprint(1, "if(argc - optidx !=3D %d) {\n",=20
+		cprint(1, "if(argc - optidx !=3D %d) {\n",
 		       min_args);
 		cprint(2, "fprintf(stderr, \"Need exactly %u parameters (%%u given).\\n\=
\n\", argc - optidx);\n", min_args);
 		cprint(2, "goto usage;\n");
@@ -2131,16 +2152,16 @@
 	    }
 	}
     }
-   =20
+
     cprint(1, "if(help_flag)\n");
     cprint(2, "goto usage;\n");
=20
-    cprint(1, "ret =3D %s(%s, argc - optidx, argv + optidx);\n",=20
+    cprint(1, "ret =3D %s(%s, argc - optidx, argv + optidx);\n",
 	   f, opt1 ? "&opt": "NULL");
-   =20
+
     /* free allocated data */
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	struct assignment *type =3D find(tmp->u.assignment, "type");
@@ -2155,11 +2176,11 @@
     cprint(1, "return ret;\n");
=20
     cprint(0, "usage:\n");
-    cprint(1, "arg_printusage (args, %d, \"%s\", \"%s\");\n", nargs,=20
+    cprint(1, "arg_printusage (args, %d, \"%s\", \"%s\");\n", nargs,
 	   name->u.value, arg ? arg->u.value : "");
     /* free allocated data */
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	struct assignment *type =3D find(tmp->u.assignment, "type");
@@ -2236,7 +2257,7 @@
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     if(argc =3D=3D optidx)
 	usage(1);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/slc-gram.h
--- a/head/crypto/heimdal/lib/sl/slc-gram.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/slc-gram.h	Tue Apr 17 11:51:51 2012 +0300
@@ -52,7 +52,7 @@
=20
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
 typedef union YYSTYPE
-#line 54 "slc-gram.y"
+#line 57 "slc-gram.y"
 {
 	char *string;
 	struct assignment *assignment;
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/slc-gram.y
--- a/head/crypto/heimdal/lib/sl/slc-gram.y	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/slc-gram.y	Tue Apr 17 11:51:51 2012 +0300
@@ -1,41 +1,38 @@
 %{
 /*
- * Copyright (c) 2004-2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004-2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-RCSID("$Id: slc-gram.y 20767 2007-06-01 11:24:52Z lha $");
-#endif
=20
 #include <stdio.h>
 #include <stdlib.h>
@@ -50,6 +47,12 @@
 extern FILE *yyin;
 extern struct assignment *assignment;
 extern int yyparse(void);
+
+/* Declarations for Bison:
+ */
+#define YYMALLOC        malloc
+#define YYFREE          free
+
 %}
=20
 %union {
@@ -124,6 +127,7 @@
 {
     struct assignment *a;
     int seen_long =3D 0;
+    int seen_name =3D 0;
     int seen_short =3D 0;
     int seen_type =3D 0;
     int seen_argument =3D 0;
@@ -136,6 +140,8 @@
 	    seen_long++;
 	else if(strcmp(a->name, "short") =3D=3D 0)
 	    seen_short++;
+	else if(strcmp(a->name, "name") =3D=3D 0)
+	    seen_name++;
 	else if(strcmp(a->name, "type") =3D=3D 0)
 	    seen_type++;
 	else if(strcmp(a->name, "argument") =3D=3D 0)
@@ -145,7 +151,7 @@
 	else if(strcmp(a->name, "default") =3D=3D 0)
 	    seen_default++;
 	else {
-	    ex(a, "unknown name");
+	    ex(a, "unknown name %s", a->name);
 	    ret++;
 	}
     }
@@ -153,6 +159,10 @@
 	ex(as, "neither long nor short option");
 	ret++;
     }
+    if (seen_long =3D=3D 0 && seen_name =3D=3D 0) {
+	ex(as, "either of long or name option must be used");
+	ret++;
+    }
     if(seen_long > 1) {
 	ex(as, "multiple long options");
 	ret++;
@@ -207,7 +217,7 @@
 		} else if(strcmp(a->name, "max_args") =3D=3D 0) {
 			seen_maxargs++;
 		} else {
-			ex(a, "unknown name");
+			ex(a, "unknown name: %s", a->name);
 			ret++;
 		}
 	}
@@ -235,7 +245,7 @@
 		ex(as, "multiple max_args strings");
 		ret++;
 	}
-=09
+
 	return ret;
 }
=20
@@ -357,7 +367,7 @@
 	lopt =3D find(as, "name");
     if(lopt =3D=3D NULL)
 	return NULL;
-   =20
+
     type =3D find(as, "type");
     if(strcmp(type->u.value, "-flag") =3D=3D 0)
 	asprintf(&s, "%s_flag", lopt->u.value);
@@ -375,10 +385,17 @@
     else
 	cprint(1, "opt.%s =3D 0;\n", name);
 }
-static void defval_string(const char *name, struct assignment *defval)=20
+static void defval_neg_flag(const char *name, struct assignment *defval)
 {
     if(defval !=3D NULL)
-	cprint(1, "opt.%s =3D \"%s\";\n", name, defval->u.value);
+	cprint(1, "opt.%s =3D %s;\n", name, defval->u.value);
+    else
+	cprint(1, "opt.%s =3D 1;\n", name);
+}
+static void defval_string(const char *name, struct assignment *defval)
+{
+    if(defval !=3D NULL)
+	cprint(1, "opt.%s =3D (char *)(unsigned long)\"%s\";\n", name, defval->u.=
value);
     else
 	cprint(1, "opt.%s =3D NULL;\n", name);
 }
@@ -427,7 +444,7 @@
 	{ "-flag",
 	  "int",
 	  "arg_negative_flag",
-	  defval_int,
+	  defval_neg_flag,
 	  NULL
 	},
 	{ NULL }
@@ -450,13 +467,13 @@
=20
     hprint(0, "struct %s_options {\n", name);
=20
-    for(tmp =3D opt1;=20
-	tmp !=3D NULL;=20
+    for(tmp =3D opt1;
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	struct assignment *type;
 	struct type_handler *th;
 	char *s;
-=09
+
 	s =3D make_name(tmp->u.assignment);
 	type =3D find(tmp->u.assignment, "type");
 	th =3D find_handler(type);
@@ -476,19 +493,22 @@
     struct assignment *tmp;
     char *n, *f;
     int nargs =3D 0;
+    int narguments =3D 0;
=20
     name =3D find(as, "name");
     n =3D strdup(name->u.value);
     gen_name(n);
     arg =3D find(as, "argument");
+    if (arg)
+        narguments++;
     opt1 =3D find(as, "option");
     function =3D find(as, "function");
     if(function)
 	f =3D function->u.value;
     else
 	f =3D n;
-   =20
-      =20
+
+
     if(opt1 !=3D NULL) {
 	gen_options(opt1, n);
 	hprint(0, "int %s(struct %s_options*, int, char **);\n", f, n);
@@ -504,8 +524,8 @@
     cprint(1, "int ret;\n");
     cprint(1, "int optidx =3D 0;\n");
     cprint(1, "struct getargs args[] =3D {\n");
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	struct assignment *type =3D find(tmp->u.assignment, "type");
 	struct assignment *lopt =3D find(tmp->u.assignment, "long");
@@ -514,7 +534,7 @@
 	struct assignment *help =3D find(tmp->u.assignment, "help");
=20
 	struct type_handler *th;
-=09
+
 	cprint(2, "{ ");
 	if(lopt)
 	    fprintf(cfile, "\"%s\", ", lopt->u.value);
@@ -531,9 +551,10 @@
 	    fprintf(cfile, "\"%s\", ", help->u.value);
 	else
 	    fprintf(cfile, "NULL, ");
-	if(aarg)
+	if(aarg) {
 	    fprintf(cfile, "\"%s\"", aarg->u.value);
-	else
+            narguments++;
+	} else
 	    fprintf(cfile, "NULL");
 	fprintf(cfile, " },\n");
     }
@@ -541,8 +562,8 @@
     cprint(1, "};\n");
     cprint(1, "int help_flag =3D 0;\n");
=20
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	struct assignment *type =3D find(tmp->u.assignment, "type");
@@ -550,15 +571,15 @@
 	struct assignment *defval =3D find(tmp->u.assignment, "default");
=20
 	struct type_handler *th;
-=09
+
 	s =3D make_name(tmp->u.assignment);
 	th =3D find_handler(type);
 	(*th->defval)(s, defval);
 	free(s);
     }
=20
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	s =3D make_name(tmp->u.assignment);
@@ -573,7 +594,7 @@
 	int min_args =3D -1;
 	int max_args =3D -1;
 	char *end;
-	if(arg =3D=3D NULL) {
+	if(narguments =3D=3D 0) {
 	    max_args =3D 0;
 	} else {
 	    if((tmp =3D find(as, "min_args")) !=3D NULL) {
@@ -601,7 +622,7 @@
 	}
 	if(min_args !=3D -1 || max_args !=3D -1) {
 	    if(min_args =3D=3D max_args) {
-		cprint(1, "if(argc - optidx !=3D %d) {\n",=20
+		cprint(1, "if(argc - optidx !=3D %d) {\n",
 		       min_args);
 		cprint(2, "fprintf(stderr, \"Need exactly %u parameters (%%u given).\\n\=
\n\", argc - optidx);\n", min_args);
 		cprint(2, "goto usage;\n");
@@ -622,16 +643,16 @@
 	    }
 	}
     }
-   =20
+
     cprint(1, "if(help_flag)\n");
     cprint(2, "goto usage;\n");
=20
-    cprint(1, "ret =3D %s(%s, argc - optidx, argv + optidx);\n",=20
+    cprint(1, "ret =3D %s(%s, argc - optidx, argv + optidx);\n",
 	   f, opt1 ? "&opt": "NULL");
-   =20
+
     /* free allocated data */
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	struct assignment *type =3D find(tmp->u.assignment, "type");
@@ -646,11 +667,11 @@
     cprint(1, "return ret;\n");
=20
     cprint(0, "usage:\n");
-    cprint(1, "arg_printusage (args, %d, \"%s\", \"%s\");\n", nargs,=20
+    cprint(1, "arg_printusage (args, %d, \"%s\", \"%s\");\n", nargs,
 	   name->u.value, arg ? arg->u.value : "");
     /* free allocated data */
-    for(tmp =3D find(as, "option");=20
-	tmp !=3D NULL;=20
+    for(tmp =3D find(as, "option");
+	tmp !=3D NULL;
 	tmp =3D find_next(tmp, "option")) {
 	char *s;
 	struct assignment *type =3D find(tmp->u.assignment, "type");
@@ -727,7 +748,7 @@
 	print_version(NULL);
 	exit(0);
     }
-   =20
+
     if(argc =3D=3D optidx)
 	usage(1);
=20
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/slc-lex.c
--- a/head/crypto/heimdal/lib/sl/slc-lex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/slc-lex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -8,7 +8,7 @@
 #define FLEX_SCANNER
 #define YY_FLEX_MAJOR_VERSION 2
 #define YY_FLEX_MINOR_VERSION 5
-#define YY_FLEX_SUBMINOR_VERSION 33
+#define YY_FLEX_SUBMINOR_VERSION 35
 #if YY_FLEX_SUBMINOR_VERSION > 0
 #define FLEX_BETA
 #endif
@@ -30,7 +30,7 @@
=20
 /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
=20
-#if __STDC_VERSION__ >=3D 199901L
+#if defined (__STDC_VERSION__) && __STDC_VERSION__ >=3D 199901L
=20
 /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
  * if you want the limit (max/min) macros for int types.=20
@@ -93,11 +93,12 @@
=20
 #else	/* ! __cplusplus */
=20
-#if __STDC__
+/* C99 requires __STDC__ to be defined as 1. */
+#if defined (__STDC__)
=20
 #define YY_USE_CONST
=20
-#endif	/* __STDC__ */
+#endif	/* defined (__STDC__) */
 #endif	/* ! __cplusplus */
=20
 #ifdef YY_USE_CONST
@@ -151,7 +152,12 @@
 typedef struct yy_buffer_state *YY_BUFFER_STATE;
 #endif
=20
-extern int yyleng;
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef size_t yy_size_t;
+#endif
+
+extern yy_size_t yyleng;
=20
 extern FILE *yyin, *yyout;
=20
@@ -177,16 +183,6 @@
=20
 #define unput(c) yyunput( c, (yytext_ptr)  )
=20
-/* The following is because we cannot portably get our hands on size_t
- * (without autoconf's help, which isn't available because we want
- * flex-generated scanners to compile on their own).
- */
-
-#ifndef YY_TYPEDEF_YY_SIZE_T
-#define YY_TYPEDEF_YY_SIZE_T
-typedef unsigned int yy_size_t;
-#endif
-
 #ifndef YY_STRUCT_YY_BUFFER_STATE
 #define YY_STRUCT_YY_BUFFER_STATE
 struct yy_buffer_state
@@ -204,7 +200,7 @@
 	/* Number of characters read into yy_ch_buf, not including EOB
 	 * characters.
 	 */
-	int yy_n_chars;
+	yy_size_t yy_n_chars;
=20
 	/* Whether we "own" the buffer - i.e., we know we created it,
 	 * and can realloc() it to grow it, and should free() it to
@@ -274,8 +270,8 @@
=20
 /* yy_hold_char holds the character lost when yytext is formed. */
 static char yy_hold_char;
-static int yy_n_chars;		/* number of characters read into yy_ch_buf */
-int yyleng;
+static yy_size_t yy_n_chars;		/* number of characters read into yy_ch_buf =
*/
+yy_size_t yyleng;
=20
 /* Points to current character in buffer. */
 static char *yy_c_buf_p =3D (char *) 0;
@@ -303,7 +299,7 @@
=20
 YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size  );
 YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str  );
-YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len  );
+YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len  );
=20
 void *yyalloc (yy_size_t  );
 void *yyrealloc (void *,yy_size_t  );
@@ -458,39 +454,39 @@
 #line 1 "slc-lex.l"
 #line 2 "slc-lex.l"
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: slc-lex.l 15118 2005-05-10 22:19:01Z lha $ */
+/* $Id$ */
=20
 #undef ECHO
=20
@@ -509,7 +505,7 @@
=20
 #undef ECHO
=20
-#line 513 "slc-lex.c"
+#line 509 "slc-lex.c"
=20
 #define INITIAL 0
=20
@@ -527,6 +523,35 @@
=20
 static int yy_init_globals (void );
=20
+/* Accessor methods to globals.
+   These are made visible to non-reentrant scanners for convenience. */
+
+int yylex_destroy (void );
+
+int yyget_debug (void );
+
+void yyset_debug (int debug_flag  );
+
+YY_EXTRA_TYPE yyget_extra (void );
+
+void yyset_extra (YY_EXTRA_TYPE user_defined  );
+
+FILE *yyget_in (void );
+
+void yyset_in  (FILE * in_str  );
+
+FILE *yyget_out (void );
+
+void yyset_out  (FILE * out_str  );
+
+yy_size_t yyget_leng (void );
+
+char *yyget_text (void );
+
+int yyget_lineno (void );
+
+void yyset_lineno (int line_number  );
+
 /* Macros after this point can all be overridden by user definitions in
  * section 1.
  */
@@ -539,8 +564,6 @@
 #endif
 #endif
=20
-    static void yyunput (int c,char *buf_ptr  );
-   =20
 #ifndef yytext_ptr
 static void yy_flex_strncpy (char *,yyconst char *,int );
 #endif
@@ -569,7 +592,7 @@
 /* This used to be an fputs(), but since the string might contain NUL's,
  * we now use fwrite().
  */
-#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#define ECHO fwrite( yytext, yyleng, 1, yyout )
 #endif
=20
 /* Gets input and stuffs it into "buf".  number of characters read, or YY_=
NULL,
@@ -580,7 +603,7 @@
 	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
 		{ \
 		int c =3D '*'; \
-		size_t n; \
+		yy_size_t n; \
 		for ( n =3D 0; n < max_size && \
 			     (c =3D getc( yyin )) !=3D EOF && c !=3D '\n'; ++n ) \
 			buf[n] =3D (char) c; \
@@ -662,9 +685,9 @@
 	register char *yy_cp, *yy_bp;
 	register int yy_act;
    =20
-#line 55 "slc-lex.l"
+#line 58 "slc-lex.l"
=20
-#line 668 "slc-lex.c"
+#line 691 "slc-lex.c"
=20
 	if ( !(yy_init) )
 		{
@@ -749,7 +772,7 @@
=20
 case 1:
 YY_RULE_SETUP
-#line 56 "slc-lex.l"
+#line 59 "slc-lex.l"
 {
 			  yylval.string =3D strdup ((const char *)yytext);
 			  return LITERAL;
@@ -757,36 +780,36 @@
 	YY_BREAK
 case 2:
 YY_RULE_SETUP
-#line 60 "slc-lex.l"
+#line 63 "slc-lex.l"
 { yylval.string =3D handle_string(); return STRING; }
 	YY_BREAK
 case 3:
 /* rule 3 can match eol */
 YY_RULE_SETUP
-#line 61 "slc-lex.l"
+#line 64 "slc-lex.l"
 { ++lineno; }
 	YY_BREAK
 case 4:
 YY_RULE_SETUP
-#line 62 "slc-lex.l"
+#line 65 "slc-lex.l"
 { handle_comment(); }
 	YY_BREAK
 case 5:
 YY_RULE_SETUP
-#line 63 "slc-lex.l"
+#line 66 "slc-lex.l"
 { return *yytext; }
 	YY_BREAK
 case 6:
 YY_RULE_SETUP
-#line 64 "slc-lex.l"
+#line 67 "slc-lex.l"
 ;
 	YY_BREAK
 case 7:
 YY_RULE_SETUP
-#line 65 "slc-lex.l"
+#line 68 "slc-lex.l"
 ECHO;
 	YY_BREAK
-#line 790 "slc-lex.c"
+#line 813 "slc-lex.c"
 case YY_STATE_EOF(INITIAL):
 	yyterminate();
=20
@@ -972,7 +995,7 @@
=20
 	else
 		{
-			int num_to_read =3D
+			yy_size_t num_to_read =3D
 			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
=20
 		while ( num_to_read <=3D 0 )
@@ -986,7 +1009,7 @@
=20
 			if ( b->yy_is_our_buffer )
 				{
-				int new_size =3D b->yy_buf_size * 2;
+				yy_size_t new_size =3D b->yy_buf_size * 2;
=20
 				if ( new_size <=3D 0 )
 					b->yy_buf_size +=3D b->yy_buf_size / 8;
@@ -1041,6 +1064,14 @@
 	else
 		ret_val =3D EOB_ACT_CONTINUE_SCAN;
=20
+	if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALU=
E->yy_buf_size) {
+		/* Extend the array by 50%, plus the number we really need. */
+		yy_size_t new_size =3D (yy_n_chars) + number_to_move + ((yy_n_chars) >> =
1);
+		YY_CURRENT_BUFFER_LVALUE->yy_ch_buf =3D (char *) yyrealloc((void *) YY_C=
URRENT_BUFFER_LVALUE->yy_ch_buf,new_size  );
+		if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+	}
+
 	(yy_n_chars) +=3D number_to_move;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] =3D YY_END_OF_BUFFER_CH=
AR;
 	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] =3D YY_END_OF_BUFFE=
R_CHAR;
@@ -1107,43 +1138,6 @@
 	return yy_is_jam ? 0 : yy_current_state;
 }
=20
-    static void yyunput (int c, register char * yy_bp )
-{
-	register char *yy_cp;
-   =20
-    yy_cp =3D (yy_c_buf_p);
-
-	/* undo effects of setting up yytext */
-	*yy_cp =3D (yy_hold_char);
-
-	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
-		{ /* need to shift things up to make room */
-		/* +2 for EOB chars. */
-		register int number_to_move =3D (yy_n_chars) + 2;
-		register char *dest =3D &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
-					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
-		register char *source =3D
-				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
-
-		while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
-			*--dest =3D *--source;
-
-		yy_cp +=3D (int) (dest - source);
-		yy_bp +=3D (int) (dest - source);
-		YY_CURRENT_BUFFER_LVALUE->yy_n_chars =3D
-			(yy_n_chars) =3D YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
-
-		if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
-			YY_FATAL_ERROR( "flex scanner push-back overflow" );
-		}
-
-	*--yy_cp =3D (char) c;
-
-	(yytext_ptr) =3D yy_bp;
-	(yy_hold_char) =3D *yy_cp;
-	(yy_c_buf_p) =3D yy_cp;
-}
-
 #ifndef YY_NO_INPUT
 #ifdef __cplusplus
     static int yyinput (void)
@@ -1168,7 +1162,7 @@
=20
 		else
 			{ /* need more input */
-			int offset =3D (yy_c_buf_p) - (yytext_ptr);
+			yy_size_t offset =3D (yy_c_buf_p) - (yytext_ptr);
 			++(yy_c_buf_p);
=20
 			switch ( yy_get_next_buffer(  ) )
@@ -1444,7 +1438,7 @@
  */
 static void yyensure_buffer_stack (void)
 {
-	int num_to_alloc;
+	yy_size_t num_to_alloc;
    =20
 	if (!(yy_buffer_stack)) {
=20
@@ -1456,7 +1450,9 @@
 		(yy_buffer_stack) =3D (struct yy_buffer_state**)yyalloc
 								(num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
-	=09
+		if ( ! (yy_buffer_stack) )
+			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
+								 =20
 		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_stat=
e*));
 			=09
 		(yy_buffer_stack_max) =3D num_to_alloc;
@@ -1474,6 +1470,8 @@
 								((yy_buffer_stack),
 								num_to_alloc * sizeof(struct yy_buffer_state*)
 								);
+		if ( ! (yy_buffer_stack) )
+			YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
=20
 		/* zero only the new slots.*/
 		memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(=
struct yy_buffer_state*));
@@ -1518,7 +1516,7 @@
=20
 /** Setup the input buffer state to scan a string. The next call to yylex(=
) will
  * scan from a @e copy of @a str.
- * @param str a NUL-terminated string to scan
+ * @param yystr a NUL-terminated string to scan
  *=20
  * @return the newly allocated buffer state object.
  * @note If you want to scan bytes that may contain NUL values, then use
@@ -1537,12 +1535,11 @@
  *=20
  * @return the newly allocated buffer state object.
  */
-YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len )
+YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, yy_size_t  _yybyte=
s_len )
 {
 	YY_BUFFER_STATE b;
 	char *buf;
-	yy_size_t n;
-	int i;
+	yy_size_t n, i;
    =20
 	/* Get memory for full buffer, including space for trailing EOB's. */
 	n =3D _yybytes_len + 2;
@@ -1624,7 +1621,7 @@
 /** Get the length of the current token.
  *=20
  */
-int yyget_leng  (void)
+yy_size_t yyget_leng  (void)
 {
         return yyleng;
 }
@@ -1772,7 +1769,7 @@
=20
 #define YYTABLES_NAME "yytables"
=20
-#line 65 "slc-lex.l"
+#line 68 "slc-lex.l"
=20
=20
=20
@@ -1812,19 +1809,12 @@
 	    }
 	    seen_slash =3D 1;
 	    continue;
-	}
-	if(seen_star && c =3D=3D '/') {
-	    if(--level =3D=3D 0)
-		return;
-	    seen_star =3D 0;
-	    continue;
-	}
-	if(c =3D=3D '*') {
+	} else if(c =3D=3D '*') {
 	    if(seen_slash) {
 		level++;
 		seen_star =3D seen_slash =3D 0;
 		continue;
-	    }=20
+	    }
 	    seen_star =3D 1;
 	    continue;
 	}
@@ -1870,7 +1860,7 @@
 }
=20
 int
-yywrap ()=20
+yywrap ()
 {
      return 1;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/slc-lex.l
--- a/head/crypto/heimdal/lib/sl/slc-lex.l	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/slc-lex.l	Tue Apr 17 11:51:51 2012 +0300
@@ -1,38 +1,38 @@
 %{
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: slc-lex.l 15118 2005-05-10 22:19:01Z lha $ */
+/* $Id$ */
=20
 #undef ECHO
=20
@@ -52,6 +52,9 @@
 #undef ECHO
=20
 %}
+
+%option nounput
+
 %%
 [A-Za-z][-A-Za-z0-9_]*	{
 			  yylval.string =3D strdup ((const char *)yytext);
@@ -100,19 +103,12 @@
 	    }
 	    seen_slash =3D 1;
 	    continue;
-	}
-	if(seen_star && c =3D=3D '/') {
-	    if(--level =3D=3D 0)
-		return;
-	    seen_star =3D 0;
-	    continue;
-	}
-	if(c =3D=3D '*') {
+	} else if(c =3D=3D '*') {
 	    if(seen_slash) {
 		level++;
 		seen_star =3D seen_slash =3D 0;
 		continue;
-	    }=20
+	    }
 	    seen_star =3D 1;
 	    continue;
 	}
@@ -158,7 +154,7 @@
 }
=20
 int
-yywrap ()=20
+yywrap ()
 {
      return 1;
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/slc.h
--- a/head/crypto/heimdal/lib/sl/slc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/slc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,37 +1,37 @@
 /*
- * Copyright (c) 2004 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2004 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-/* $Id: slc.h 13969 2004-06-21 19:10:59Z joda $ */
+/* $Id$ */
 #include <stdio.h>
 #include <string.h>
 #include <stdarg.h>
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/sl/test_sl.c
--- a/head/crypto/heimdal/lib/sl/test_sl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/sl/test_sl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,18 @@
 /*
- * Copyright (c) 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
  * 3. Neither the name of KTH nor the names of its contributors may be
  *    used to endorse or promote products derived from this software witho=
ut
@@ -32,8 +32,6 @@
=20
 #include "sl_locl.h"
=20
-RCSID("$Id: test_sl.c 19555 2006-12-28 23:40:17Z lha $");
-
 struct {
     int ok;
     const char *line;
@@ -82,7 +80,7 @@
 	} else if (!lines[i].ok)
 	    errx(1, "sl_make_argv passed test %d when it shouldn't", i);
 	if (rargc !=3D lines[i].argc)
-	    errx(1, "result argc (%d) !=3D should be argc (%d) for test %d",=20
+	    errx(1, "result argc (%d) !=3D should be argc (%d) for test %d",
 		 rargc, lines[i].argc, i);
 	for (j =3D 0; j < rargc; j++)
 	    if (strcmp(rargv[j], lines[i].argv[j]) !=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/vers/ChangeLog
--- a/head/crypto/heimdal/lib/vers/ChangeLog	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/vers/ChangeLog	Tue Apr 17 11:51:51 2012 +0300
@@ -1,32 +1,32 @@
-2007-10-16  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2007-10-16  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* Makefile.am: don't run local checks.
 =09
-2006-12-29  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-12-29  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* print_version.c: Update (c).
 =09
-2006-10-21  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-21  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* make-print-version.c: include <string.h>
=20
-2006-10-20  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-20  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* make-print-version.c: Avoid creating a file called --version.
 =09
-2006-10-19  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-19  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: fix spelling of build_HEADERZ
=20
-2006-10-07  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2006-10-07  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
 =09
 	* Makefile.am: Add build_HEADERZ to EXTRA_DIST
 =09
-2005-01-01  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2005-01-01  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* print_version.c: Happy New Year
=20
-2004-01-05  Love H=F6rnquist =C5strand  <lha at it.su.se>
+2004-01-05  Love H=C3=B6rnquist =C3=85strand  <lha at it.su.se>
=20
 	* print_version.c: add year 2004
 =09
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/vers/Makefile.=
am
--- a/head/crypto/heimdal/lib/vers/Makefile.am	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/vers/Makefile.am	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,32 +1,13 @@
-# $Id: Makefile.am 21959 2007-10-16 13:25:59Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
-CLEANFILES		=3D print_version.h
-
 noinst_LTLIBRARIES	=3D libvers.la
=20
 build_HEADERZ		=3D vers.h
=20
 CHECK_LOCAL		=3D no-check-local
=20
-noinst_PROGRAMS		=3D make-print-version
+libvers_la_SOURCES      =3D print_version.c
=20
-if KRB4
-if KRB5
-## need to link with des here; otherwise, if krb4 is shared the link
-## will fail with unresolved references
-make_print_version_LDADD =3D $(LIB_krb4) $(LIB_hcrypto)
-endif
-endif
-
-libvers_la_SOURCES	=3D print_version.c
-
-print_version.lo: print_version.h
-
-print_version.h: make-print-version$(EXEEXT)
-	./make-print-version$(EXEEXT) print_version.h
-
-make-print-version.o: $(top_builddir)/include/version.h
-
-EXTRA_DIST =3D $(build_HEADERZ)
+EXTRA_DIST =3D NTMakefile $(build_HEADERZ)
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/vers/Makefile.=
in
--- a/head/crypto/heimdal/lib/vers/Makefile.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/lib/vers/Makefile.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,17 +15,17 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 21959 2007-10-16 13:25:59Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
-
+# $Id$
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -42,11 +43,10 @@
 DIST_COMMON =3D $(srcdir)/Makefile.am $(srcdir)/Makefile.in \
 	$(top_srcdir)/Makefile.am.common \
 	$(top_srcdir)/cf/Makefile.am.common ChangeLog
-noinst_PROGRAMS =3D make-print-version$(EXEEXT)
 subdir =3D lib/vers
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -61,7 +61,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -75,9 +75,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -85,26 +88,20 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
+CONFIG_CLEAN_VPATH_FILES =3D
 LTLIBRARIES =3D $(noinst_LTLIBRARIES)
 libvers_la_LIBADD =3D
 am_libvers_la_OBJECTS =3D print_version.lo
 libvers_la_OBJECTS =3D $(am_libvers_la_OBJECTS)
-PROGRAMS =3D $(noinst_PROGRAMS)
-make_print_version_SOURCES =3D make-print-version.c
-make_print_version_OBJECTS =3D make-print-version.$(OBJEXT)
-am__DEPENDENCIES_1 =3D
- at KRB4_TRUE@@KRB5_TRUE at make_print_version_DEPENDENCIES =3D  \
- at KRB4_TRUE@@KRB5_TRUE@	$(am__DEPENDENCIES_1) \
- at KRB4_TRUE@@KRB5_TRUE@	$(am__DEPENDENCIES_1)
-DEFAULT_INCLUDES =3D -I. -I$(top_builddir)/include at am__isrc@
-depcomp =3D
-am__depfiles_maybe =3D
+depcomp =3D $(SHELL) $(top_srcdir)/depcomp
+am__depfiles_maybe =3D depfiles
+am__mv =3D mv -f
 COMPILE =3D $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
 	$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
 LTCOMPILE =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
@@ -114,8 +111,8 @@
 LINK =3D $(LIBTOOL) --tag=3DCC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \
 	--mode=3Dlink $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
 	$(LDFLAGS) -o $@
-SOURCES =3D $(libvers_la_SOURCES) make-print-version.c
-DIST_SOURCES =3D $(libvers_la_SOURCES) make-print-version.c
+SOURCES =3D $(libvers_la_SOURCES)
+DIST_SOURCES =3D $(libvers_la_SOURCES)
 ETAGS =3D etags
 CTAGS =3D ctags
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
@@ -123,49 +120,58 @@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -189,10 +195,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -209,6 +216,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -224,31 +233,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -263,10 +286,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -307,53 +332,56 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
-CLEANFILES =3D print_version.h
 noinst_LTLIBRARIES =3D libvers.la
 build_HEADERZ =3D vers.h
 CHECK_LOCAL =3D no-check-local
- at KRB4_TRUE@@KRB5_TRUE at make_print_version_LDADD =3D $(LIB_krb4) $(LIB_hcryp=
to)
 libvers_la_SOURCES =3D print_version.c
-EXTRA_DIST =3D $(build_HEADERZ)
+EXTRA_DIST =3D NTMakefile $(build_HEADERZ)
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o .obj
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c .lo .o =
.obj
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps lib/vers/=
Makefile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps lib/vers/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign lib/vers/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign lib/vers/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -371,6 +399,7 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
=20
 clean-noinstLTLIBRARIES:
 	-test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES)
@@ -383,30 +412,34 @@
 libvers.la: $(libvers_la_OBJECTS) $(libvers_la_DEPENDENCIES)=20
 	$(LINK)  $(libvers_la_OBJECTS) $(libvers_la_LIBADD) $(LIBS)
=20
-clean-noinstPROGRAMS:
-	@list=3D'$(noinst_PROGRAMS)'; for p in $$list; do \
-	  f=3D`echo $$p|sed 's/$(EXEEXT)$$//'`; \
-	  echo " rm -f $$p $$f"; \
-	  rm -f $$p $$f ; \
-	done
-make-print-version$(EXEEXT): $(make_print_version_OBJECTS) $(make_print_ve=
rsion_DEPENDENCIES)=20
-	@rm -f make-print-version$(EXEEXT)
-	$(LINK) $(make_print_version_OBJECTS) $(make_print_version_LDADD) $(LIBS)
-
 mostlyclean-compile:
 	-rm -f *.$(OBJEXT)
=20
 distclean-compile:
 	-rm -f *.tab.c
=20
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/print_version.Plo at am__quo=
te@
+
 .c.o:
-	$(COMPILE) -c $<
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c $<
=20
 .c.obj:
-	$(COMPILE) -c `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o =
$@ `$(CYGPATH_W) '$<'`
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dno=
 @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(COMPILE) -c `$(CYGPATH_W) '$<'`
=20
 .c.lo:
-	$(LTCOMPILE) -c -o $@ $<
+ at am__fastdepCC_TRUE@	$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -=
o $@ $<
+ at am__fastdepCC_TRUE@	$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	source=3D'$<' object=3D'$@' libtool=3Dye=
s @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=3D$(DEPDIR) $(CCDEPMODE) $(depcom=
p) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@	$(LTCOMPILE) -c -o $@ $<
=20
 mostlyclean-libtool:
 	-rm -f *.lo
@@ -419,45 +452,49 @@
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
 	mkid -fID $$unique
 tags: TAGS
=20
 TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
+	set x; \
 	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	shift; \
+	if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
 	  test -n "$$unique" || unique=3D$$empty_fix; \
-	  $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-	    $$tags $$unique; \
+	  if test $$# -gt 0; then \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      "$$@" $$unique; \
+	  else \
+	    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+	      $$unique; \
+	  fi; \
 	fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
 		$(TAGS_FILES) $(LISP)
-	tags=3D; \
-	here=3D`pwd`; \
 	list=3D'$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
 	unique=3D`for i in $$list; do \
 	    if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
 	  done | \
-	  $(AWK) '    { files[$$0] =3D 1; } \
-	       END { for (i in files) print i; }'`; \
-	test -z "$(CTAGS_ARGS)$$tags$$unique" \
+	  $(AWK) '{ files[$$0] =3D 1; nonempty =3D 1; } \
+	      END { if (nonempty) { for (i in files) print i; }; }'`; \
+	test -z "$(CTAGS_ARGS)$$unique" \
 	  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
-	     $$tags $$unique
+	     $$unique
=20
 GTAGS:
 	here=3D`$(am__cd) $(top_builddir) && pwd` \
-	  && cd $(top_srcdir) \
-	  && gtags -i $(GTAGS_ARGS) $$here
+	  && $(am__cd) $(top_srcdir) \
+	  && gtags -i $(GTAGS_ARGS) "$$here"
=20
 distclean-tags:
 	-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
@@ -478,13 +515,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -494,7 +535,7 @@
 check-am: all-am
 	$(MAKE) $(AM_MAKEFLAGS) check-local
 check: check-am
-all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) all-local
+all-am: Makefile $(LTLIBRARIES) all-local
 installdirs:
 install: install-am
 install-exec: install-exec-am
@@ -513,10 +554,10 @@
 mostlyclean-generic:
=20
 clean-generic:
-	-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -524,9 +565,10 @@
 clean: clean-am
=20
 clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \
-	clean-noinstPROGRAMS mostlyclean-am
+	mostlyclean-am
=20
 distclean: distclean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 distclean-am: clean-am distclean-compile distclean-generic \
 	distclean-tags
@@ -537,6 +579,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -544,26 +588,35 @@
 install-data-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man:
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
+	-rm -rf ./$(DEPDIR)
 	-rm -f Makefile
 maintainer-clean-am: distclean-am maintainer-clean-generic
=20
@@ -583,24 +636,22 @@
 uninstall-am:
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: CTAGS GTAGS all all-am all-local check check-am check-local \
 	clean clean-generic clean-libtool clean-noinstLTLIBRARIES \
-	clean-noinstPROGRAMS ctags dist-hook distclean \
-	distclean-compile distclean-generic distclean-libtool \
-	distclean-tags distdir dvi dvi-am html html-am info info-am \
-	install install-am install-data install-data-am \
-	install-data-hook install-dvi install-dvi-am install-exec \
-	install-exec-am install-exec-hook install-html install-html-am \
-	install-info install-info-am install-man install-pdf \
-	install-pdf-am install-ps install-ps-am install-strip \
-	installcheck installcheck-am installdirs maintainer-clean \
-	maintainer-clean-generic mostlyclean mostlyclean-compile \
-	mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
-	tags uninstall uninstall-am uninstall-hook
+	ctags dist-hook distclean distclean-compile distclean-generic \
+	distclean-libtool distclean-tags distdir dvi dvi-am html \
+	html-am info info-am install install-am install-data \
+	install-data-am install-data-hook install-dvi install-dvi-am \
+	install-exec install-exec-am install-exec-hook install-html \
+	install-html-am install-info install-info-am install-man \
+	install-pdf install-pdf-am install-ps install-ps-am \
+	install-strip installcheck installcheck-am installdirs \
+	maintainer-clean maintainer-clean-generic mostlyclean \
+	mostlyclean-compile mostlyclean-generic mostlyclean-libtool \
+	pdf pdf-am ps ps-am tags uninstall uninstall-am uninstall-hook
=20
=20
 install-suid-programs:
@@ -671,6 +722,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -756,7 +810,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -770,12 +824,6 @@
 	  fi ; \
 	done
=20
-print_version.lo: print_version.h
-
-print_version.h: make-print-version$(EXEEXT)
-	./make-print-version$(EXEEXT) print_version.h
-
-make-print-version.o: $(top_builddir)/include/version.h
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/vers/print_ver=
sion.c
--- a/head/crypto/heimdal/lib/vers/print_version.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/lib/vers/print_version.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,55 +1,58 @@
 /*
- * Copyright (c) 1998 - 2006 Kungliga Tekniska H=F6gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).=20
- * All rights reserved.=20
+ * Copyright (c) 1998 - 2006 Kungliga Tekniska H=C3=B6gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without=20
- * modification, are permitted provided that the following conditions=20
- * are met:=20
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright=20
- *    notice, this list of conditions and the following disclaimer.=20
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright=20
- *    notice, this list of conditions and the following disclaimer in the=20
- *    documentation and/or other materials provided with the distribution.=20
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors=20
- *    may be used to endorse or promote products derived from this softwar=
e=20
- *    without specific prior written permission.=20
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND=20
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE=20
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE=20
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL=20
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT=20
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY=20
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
- * SUCH DAMAGE.=20
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIA=
BLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
=20
-#ifdef HAVE_CONFIG_H
+
 #include <config.h>
-RCSID("$Id: print_version.c 22428 2008-01-13 09:58:05Z lha $");
-#endif
+
+#define VERSION_HIDDEN static
+
 #include "roken.h"
=20
-#include "print_version.h"
+#include "version.h"
=20
-void
+void ROKEN_LIB_FUNCTION
 print_version(const char *progname)
 {
-    const char *package_list =3D VERSIONLIST;
-   =20
+    const char *package_list =3D heimdal_version;
+
     if(progname =3D=3D NULL)
 	progname =3D getprogname();
-   =20
+
     if(*package_list =3D=3D '\0')
 	package_list =3D "no version information";
     fprintf(stderr, "%s (%s)\n", progname, package_list);
-    fprintf(stderr, "Copyright 1995-2008 Kungliga Tekniska H=F6gskolan\n");
+    fprintf(stderr, "Copyright 1995-2011 Kungliga Tekniska H=C3=B6gskolan\=
n");
+#ifdef PACKAGE_BUGREPORT
     fprintf(stderr, "Send bug-reports to %s\n", PACKAGE_BUGREPORT);
+#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/lib/vers/vers.h
--- a/head/crypto/heimdal/lib/vers/vers.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/lib/vers/vers.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,23 +1,23 @@
 /*
- * Copyright (c) 1995 - 2000 Kungliga Tekniska H=F6gskolan
+ * Copyright (c) 1995 - 2000 Kungliga Tekniska H=C3=B6gskolan
  * (Royal Institute of Technology, Stockholm, Sweden).
  * All rights reserved.
- *=20
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
- *=20
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
- *=20
+ *
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
- *=20
+ *
  * 3. Neither the name of the Institute nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
- *=20
+ *
  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' A=
ND
  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $Id: vers.h 8513 2000-07-01 19:47:36Z assar $ */
+/* $Id$ */
=20
 #ifndef __VERS_H__
 #define __VERS_H__
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/ltmain.sh
--- a/head/crypto/heimdal/ltmain.sh	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/ltmain.sh	Tue Apr 17 11:51:51 2012 +0300
@@ -1,30 +1,129 @@
-# ltmain.sh - Provide generalized library-building support services.
-# NOTE: Changing this file will not affect anything until you rerun config=
ure.
-#
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005
-# Free Software Foundation, Inc.
-# Originally by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
-#
-# This program is free software; you can redistribute it and/or modify
+
+# libtool (GNU libtool) 2.4
+# Written by Gordon Matzigkeit <gord at gnu.ai.mit.edu>, 1996
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,
+# 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
+# This is free software; see the source for copying conditions.  There is =
NO
+# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPO=
SE.
+
+# GNU Libtool is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.
 #
-# This program is distributed in the hope that it will be useful, but
+# As a special exception to the GNU General Public License,
+# if you distribute this file as part of a program or library that
+# is built using GNU Libtool, you may include this file under the
+# same distribution terms that you use for the rest of that program.
+#
+# GNU Libtool is distributed in the hope that it will be useful, but
 # WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 # General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301=
, USA.
+# along with GNU Libtool; see the file COPYING.  If not, a copy
+# can be downloaded from http://www.gnu.org/licenses/gpl.html,
+# or obtained by writing to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+# Usage: $progname [OPTION]... [MODE-ARG]...
 #
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-basename=3D"s,^.*/,,g"
+# Provide generalized library-building support services.
+#
+#       --config             show all configuration variables
+#       --debug              enable verbose shell tracing
+#   -n, --dry-run            display commands without modifying any files
+#       --features           display basic configuration information and e=
xit
+#       --mode=3DMODE          use operation mode MODE
+#       --preserve-dup-deps  don't remove duplicate dependency libraries
+#       --quiet, --silent    don't print informational messages
+#       --no-quiet, --no-silent
+#                            print informational messages (default)
+#       --tag=3DTAG            use configuration variables from tag TAG
+#   -v, --verbose            print more informational messages than default
+#       --no-verbose         don't print the extra informational messages
+#       --version            print version information
+#   -h, --help, --help-all   print short, long, or detailed help message
+#
+# MODE must be one of the following:
+#
+#         clean              remove files from the build directory
+#         compile            compile a source file into a libtool object
+#         execute            automatically set library path, then run a pr=
ogram
+#         finish             complete the installation of libtool libraries
+#         install            install libraries or executables
+#         link               create a library or an executable
+#         uninstall          remove libraries from an installed directory
+#
+# MODE-ARGS vary depending on the MODE.  When passed as first option,
+# `--mode=3DMODE' may be abbreviated as `MODE' or a unique abbreviation of=
 that.
+# Try `$progname --help --mode=3DMODE' for a more detailed description of =
MODE.
+#
+# When reporting a bug, please describe a test case to reproduce it and
+# include the following information:
+#
+#         host-triplet:	$host
+#         shell:		$SHELL
+#         compiler:		$LTCC
+#         compiler flags:		$LTCFLAGS
+#         linker:		$LD (gnu? $with_gnu_ld)
+#         $progname:	(GNU libtool) 2.4
+#         automake:	$automake_version
+#         autoconf:	$autoconf_version
+#
+# Report bugs to <bug-libtool at gnu.org>.
+# GNU libtool home page: <http://www.gnu.org/software/libtool/>.
+# General help using GNU software: <http://www.gnu.org/gethelp/>.
+
+PROGRAM=3Dlibtool
+PACKAGE=3Dlibtool
+VERSION=3D2.4
+TIMESTAMP=3D""
+package_revision=3D1.3293
+
+# Be Bourne compatible
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=3D:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'=3D'"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac
+fi
+BIN_SH=3Dxpg4; export BIN_SH # for Tru64
+DUALCASE=3D1; export DUALCASE # for MKS sh
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+$1
+_LTECHO_EOF'
+}
+
+# NLS nuisances: We save the old values to restore during execute mode.
+lt_user_locale=3D
+lt_safe_locale=3D
+for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+do
+  eval "if test \"\${$lt_var+set}\" =3D set; then
+          save_$lt_var=3D\$$lt_var
+          $lt_var=3DC
+	  export $lt_var
+	  lt_user_locale=3D\"$lt_var=3D\\\$save_\$lt_var; \$lt_user_locale\"
+	  lt_safe_locale=3D\"$lt_var=3DC; \$lt_safe_locale\"
+	fi"
+done
+LC_ALL=3DC
+LANGUAGE=3DC
+export LANGUAGE LC_ALL
+
+$lt_unset CDPATH
+
=20
 # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh
 # is ksh but when the shell is invoked as "sh" and the current value of
@@ -33,113 +132,427 @@
 # function.
 progpath=3D"$0"
=20
-# The name of this program:
-progname=3D`echo "$progpath" | $SED $basename`
-modename=3D"$progname"
+
+
+: ${CP=3D"cp -f"}
+test "${ECHO+set}" =3D set || ECHO=3D${as_echo-'printf %s\n'}
+: ${EGREP=3D"grep -E"}
+: ${FGREP=3D"grep -F"}
+: ${GREP=3D"grep"}
+: ${LN_S=3D"ln -s"}
+: ${MAKE=3D"make"}
+: ${MKDIR=3D"mkdir"}
+: ${MV=3D"mv -f"}
+: ${RM=3D"rm -f"}
+: ${SED=3D"sed"}
+: ${SHELL=3D"${CONFIG_SHELL-/bin/sh}"}
+: ${Xsed=3D"$SED -e 1s/^X//"}
=20
 # Global variables:
 EXIT_SUCCESS=3D0
 EXIT_FAILURE=3D1
-
-PROGRAM=3Dltmain.sh
-PACKAGE=3Dlibtool
-VERSION=3D1.5.22
-TIMESTAMP=3D" (1.1220.2.365 2005/12/18 22:14:06)"
-
-# See if we are running on zsh, and set the options which allow our
-# commands through without removal of \ escapes.
-if test -n "${ZSH_VERSION+set}" ; then
-  setopt NO_GLOB_SUBST
-fi
-
-# Check that we have a working $echo.
-if test "X$1" =3D X--no-reexec; then
-  # Discard the --no-reexec flag, and continue.
-  shift
-elif test "X$1" =3D X--fallback-echo; then
-  # Avoid inline document here, it may be left over
-  :
-elif test "X`($echo '\t') 2>/dev/null`" =3D 'X\t'; then
-  # Yippee, $echo works!
-  :
-else
-  # Restart under the correct shell, and then maybe $echo will work.
-  exec $SHELL "$progpath" --no-reexec ${1+"$@"}
-fi
-
-if test "X$1" =3D X--fallback-echo; then
-  # used as fallback echo
-  shift
-  cat <<EOF
-$*
-EOF
-  exit $EXIT_SUCCESS
-fi
-
-default_mode=3D
-help=3D"Try \`$progname --help' for more information."
-magic=3D"%%%MAGIC variable%%%"
-mkdir=3D"mkdir"
-mv=3D"mv -f"
-rm=3D"rm -f"
-
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed=3D"${SED}"' -e 1s/^X//'
-sed_quote_subst=3D's/\([\\`\\"$\\\\]\)/\\\1/g'
-# test EBCDIC or ASCII
-case `echo X|tr X '\101'` in
- A) # ASCII based system
-    # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr
-  SP2NL=3D'tr \040 \012'
-  NL2SP=3D'tr \015\012 \040\040'
-  ;;
- *) # EBCDIC based system
-  SP2NL=3D'tr \100 \n'
-  NL2SP=3D'tr \r\n \100\100'
-  ;;
-esac
-
-# NLS nuisances.
-# Only set LANG and LC_ALL to C if already set.
-# These must not be set unconditionally because not all systems understand
-# e.g. LANG=3DC (notably SCO).
-# We save the old values to restore during execute mode.
-if test "${LC_ALL+set}" =3D set; then
-  save_LC_ALL=3D"$LC_ALL"; LC_ALL=3DC; export LC_ALL
-fi
-if test "${LANG+set}" =3D set; then
-  save_LANG=3D"$LANG"; LANG=3DC; export LANG
-fi
+EXIT_MISMATCH=3D63  # $? =3D 63 is used to indicate version mismatch to mi=
ssing.
+EXIT_SKIP=3D77	  # $? =3D 77 is used to indicate a skipped test to automak=
e.
+
+exit_status=3D$EXIT_SUCCESS
=20
 # Make sure IFS has a sensible default
 lt_nl=3D'
 '
 IFS=3D" 	$lt_nl"
=20
-if test "$build_libtool_libs" !=3D yes && test "$build_old_libs" !=3D yes;=
 then
-  $echo "$modename: not configured to build any kind of library" 1>&2
-  $echo "Fatal configuration error.  See the $PACKAGE docs for more inform=
ation." 1>&2
-  exit $EXIT_FAILURE
-fi
-
-# Global variables.
-mode=3D$default_mode
-nonopt=3D
-prev=3D
-prevopt=3D
-run=3D
-show=3D"$echo"
-show_help=3D
-execute_dlfiles=3D
-duplicate_deps=3Dno
-preserve_args=3D
-lo2o=3D"s/\\.lo\$/.${objext}/"
-o2lo=3D"s/\\.${objext}\$/.lo/"
-
-#####################################
-# Shell function definitions:
-# This seems to be the best place for them
+dirname=3D"s,/[^/]*$,,"
+basename=3D"s,^.*/,,"
+
+# func_dirname file append nondir_replacement
+# Compute the dirname of FILE.  If nonempty, add APPEND to the result,
+# otherwise set result to NONDIR_REPLACEMENT.
+func_dirname ()
+{
+    func_dirname_result=3D`$ECHO "${1}" | $SED "$dirname"`
+    if test "X$func_dirname_result" =3D "X${1}"; then
+      func_dirname_result=3D"${3}"
+    else
+      func_dirname_result=3D"$func_dirname_result${2}"
+    fi
+} # func_dirname may be replaced by extended shell implementation
+
+
+# func_basename file
+func_basename ()
+{
+    func_basename_result=3D`$ECHO "${1}" | $SED "$basename"`
+} # func_basename may be replaced by extended shell implementation
+
+
+# func_dirname_and_basename file append nondir_replacement
+# perform func_basename and func_dirname in a single function
+# call:
+#   dirname:  Compute the dirname of FILE.  If nonempty,
+#             add APPEND to the result, otherwise set result
+#             to NONDIR_REPLACEMENT.
+#             value returned in "$func_dirname_result"
+#   basename: Compute filename of FILE.
+#             value retuned in "$func_basename_result"
+# Implementation must be kept synchronized with func_dirname
+# and func_basename. For efficiency, we do not delegate to
+# those functions but instead duplicate the functionality here.
+func_dirname_and_basename ()
+{
+    # Extract subdirectory from the argument.
+    func_dirname_result=3D`$ECHO "${1}" | $SED -e "$dirname"`
+    if test "X$func_dirname_result" =3D "X${1}"; then
+      func_dirname_result=3D"${3}"
+    else
+      func_dirname_result=3D"$func_dirname_result${2}"
+    fi
+    func_basename_result=3D`$ECHO "${1}" | $SED -e "$basename"`
+} # func_dirname_and_basename may be replaced by extended shell implementa=
tion
+
+
+# func_stripname prefix suffix name
+# strip PREFIX and SUFFIX off of NAME.
+# PREFIX and SUFFIX must not contain globbing or regex special
+# characters, hashes, percent signs, but SUFFIX may contain a leading
+# dot (in which case that matches only a dot).
+# func_strip_suffix prefix name
+func_stripname ()
+{
+    case ${2} in
+      .*) func_stripname_result=3D`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\$=
{2}\$%%"`;;
+      *)  func_stripname_result=3D`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\=
$%%"`;;
+    esac
+} # func_stripname may be replaced by extended shell implementation
+
+
+# These SED scripts presuppose an absolute path with a trailing slash.
+pathcar=3D's,^/\([^/]*\).*$,\1,'
+pathcdr=3D's,^/[^/]*,,'
+removedotparts=3D':dotsl
+		s@/\./@/@g
+		t dotsl
+		s,/\.$,/,'
+collapseslashes=3D's@/\{1,\}@/@g'
+finalslash=3D's,/*$,/,'
+
+# func_normal_abspath PATH
+# Remove doubled-up and trailing slashes, "." path components,
+# and cancel out any ".." path components in PATH after making
+# it an absolute path.
+#             value returned in "$func_normal_abspath_result"
+func_normal_abspath ()
+{
+  # Start from root dir and reassemble the path.
+  func_normal_abspath_result=3D
+  func_normal_abspath_tpath=3D$1
+  func_normal_abspath_altnamespace=3D
+  case $func_normal_abspath_tpath in
+    "")
+      # Empty path, that just means $cwd.
+      func_stripname '' '/' "`pwd`"
+      func_normal_abspath_result=3D$func_stripname_result
+      return
+    ;;
+    # The next three entries are used to spot a run of precisely
+    # two leading slashes without using negated character classes;
+    # we take advantage of case's first-match behaviour.
+    ///*)
+      # Unusual form of absolute path, do nothing.
+    ;;
+    //*)
+      # Not necessarily an ordinary path; POSIX reserves leading '//'
+      # and for example Cygwin uses it to access remote file shares
+      # over CIFS/SMB, so we conserve a leading double slash if found.
+      func_normal_abspath_altnamespace=3D/
+    ;;
+    /*)
+      # Absolute path, do nothing.
+    ;;
+    *)
+      # Relative path, prepend $cwd.
+      func_normal_abspath_tpath=3D`pwd`/$func_normal_abspath_tpath
+    ;;
+  esac
+  # Cancel out all the simple stuff to save iterations.  We also want
+  # the path to end with a slash for ease of parsing, so make sure
+  # there is one (and only one) here.
+  func_normal_abspath_tpath=3D`$ECHO "$func_normal_abspath_tpath" | $SED \
+        -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"`
+  while :; do
+    # Processed it all yet?
+    if test "$func_normal_abspath_tpath" =3D / ; then
+      # If we ascended to the root using ".." the result may be empty now.
+      if test -z "$func_normal_abspath_result" ; then
+        func_normal_abspath_result=3D/
+      fi
+      break
+    fi
+    func_normal_abspath_tcomponent=3D`$ECHO "$func_normal_abspath_tpath" |=
 $SED \
+        -e "$pathcar"`
+    func_normal_abspath_tpath=3D`$ECHO "$func_normal_abspath_tpath" | $SED=
 \
+        -e "$pathcdr"`
+    # Figure out what to do with it
+    case $func_normal_abspath_tcomponent in
+      "")
+        # Trailing empty path component, ignore it.
+      ;;
+      ..)
+        # Parent dir; strip last assembled component from result.
+        func_dirname "$func_normal_abspath_result"
+        func_normal_abspath_result=3D$func_dirname_result
+      ;;
+      *)
+        # Actual path component, append it.
+        func_normal_abspath_result=3D$func_normal_abspath_result/$func_nor=
mal_abspath_tcomponent
+      ;;
+    esac
+  done
+  # Restore leading double-slash if one was found on entry.
+  func_normal_abspath_result=3D$func_normal_abspath_altnamespace$func_norm=
al_abspath_result
+}
+
+# func_relative_path SRCDIR DSTDIR
+# generates a relative path from SRCDIR to DSTDIR, with a trailing
+# slash if non-empty, suitable for immediately appending a filename
+# without needing to append a separator.
+#             value returned in "$func_relative_path_result"
+func_relative_path ()
+{
+  func_relative_path_result=3D
+  func_normal_abspath "$1"
+  func_relative_path_tlibdir=3D$func_normal_abspath_result
+  func_normal_abspath "$2"
+  func_relative_path_tbindir=3D$func_normal_abspath_result
+
+  # Ascend the tree starting from libdir
+  while :; do
+    # check if we have found a prefix of bindir
+    case $func_relative_path_tbindir in
+      $func_relative_path_tlibdir)
+        # found an exact match
+        func_relative_path_tcancelled=3D
+        break
+        ;;
+      $func_relative_path_tlibdir*)
+        # found a matching prefix
+        func_stripname "$func_relative_path_tlibdir" '' "$func_relative_pa=
th_tbindir"
+        func_relative_path_tcancelled=3D$func_stripname_result
+        if test -z "$func_relative_path_result"; then
+          func_relative_path_result=3D.
+        fi
+        break
+        ;;
+      *)
+        func_dirname $func_relative_path_tlibdir
+        func_relative_path_tlibdir=3D${func_dirname_result}
+        if test "x$func_relative_path_tlibdir" =3D x ; then
+          # Have to descend all the way to the root!
+          func_relative_path_result=3D../$func_relative_path_result
+          func_relative_path_tcancelled=3D$func_relative_path_tbindir
+          break
+        fi
+        func_relative_path_result=3D../$func_relative_path_result
+        ;;
+    esac
+  done
+
+  # Now calculate path; take care to avoid doubling-up slashes.
+  func_stripname '' '/' "$func_relative_path_result"
+  func_relative_path_result=3D$func_stripname_result
+  func_stripname '/' '/' "$func_relative_path_tcancelled"
+  if test "x$func_stripname_result" !=3D x ; then
+    func_relative_path_result=3D${func_relative_path_result}/${func_stripn=
ame_result}
+  fi
+
+  # Normalisation. If bindir is libdir, return empty string,
+  # else relative path ending with a slash; either way, target
+  # file name can be directly appended.
+  if test ! -z "$func_relative_path_result"; then
+    func_stripname './' '' "$func_relative_path_result/"
+    func_relative_path_result=3D$func_stripname_result
+  fi
+}
+
+# The name of this program:
+func_dirname_and_basename "$progpath"
+progname=3D$func_basename_result
+
+# Make sure we have an absolute path for reexecution:
+case $progpath in
+  [\\/]*|[A-Za-z]:\\*) ;;
+  *[\\/]*)
+     progdir=3D$func_dirname_result
+     progdir=3D`cd "$progdir" && pwd`
+     progpath=3D"$progdir/$progname"
+     ;;
+  *)
+     save_IFS=3D"$IFS"
+     IFS=3D:
+     for progdir in $PATH; do
+       IFS=3D"$save_IFS"
+       test -x "$progdir/$progname" && break
+     done
+     IFS=3D"$save_IFS"
+     test -n "$progdir" || progdir=3D`pwd`
+     progpath=3D"$progdir/$progname"
+     ;;
+esac
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+Xsed=3D"${SED}"' -e 1s/^X//'
+sed_quote_subst=3D's/\([`"$\\]\)/\\\1/g'
+
+# Same as above, but do not quote variable references.
+double_quote_subst=3D's/\(["`\\]\)/\\\1/g'
+
+# Sed substitution that turns a string into a regex matching for the
+# string literally.
+sed_make_literal_regex=3D's,[].[^$\\*\/],\\&,g'
+
+# Sed substitution that converts a w32 file name or path
+# which contains forward slashes, into one that contains
+# (escaped) backslashes.  A very naive implementation.
+lt_sed_naive_backslashify=3D's|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g'
+
+# Re-`\' parameter expansions in output of double_quote_subst that were
+# `\'-ed in input to the same.  If an odd number of `\' preceded a '$'
+# in input to double_quote_subst, that '$' was protected from expansion.
+# Since each input `\' is now two `\'s, look for any number of runs of
+# four `\'s followed by two `\'s and then a '$'.  `\' that '$'.
+bs=3D'\\'
+bs2=3D'\\\\'
+bs4=3D'\\\\\\\\'
+dollar=3D'\$'
+sed_double_backslash=3D"\
+  s/$bs4/&\\
+/g
+  s/^$bs2$dollar/$bs&/
+  s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g
+  s/\n//g"
+
+# Standard options:
+opt_dry_run=3Dfalse
+opt_help=3Dfalse
+opt_quiet=3Dfalse
+opt_verbose=3Dfalse
+opt_warning=3D:
+
+# func_echo arg...
+# Echo program name prefixed message, along with the current mode
+# name if it has been set yet.
+func_echo ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }$*"
+}
+
+# func_verbose arg...
+# Echo program name prefixed message in verbose mode only.
+func_verbose ()
+{
+    $opt_verbose && func_echo ${1+"$@"}
+
+    # A bug in bash halts the script if the last line of a function
+    # fails when set -e is in force, so we need another command to
+    # work around that:
+    :
+}
+
+# func_echo_all arg...
+# Invoke $ECHO with all args, space-separated.
+func_echo_all ()
+{
+    $ECHO "$*"
+}
+
+# func_error arg...
+# Echo program name prefixed message to standard error.
+func_error ()
+{
+    $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2
+}
+
+# func_warning arg...
+# Echo program name prefixed warning message to standard error.
+func_warning ()
+{
+    $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1=
+"$@"} 1>&2
+
+    # bash bug again:
+    :
+}
+
+# func_fatal_error arg...
+# Echo program name prefixed message to standard error, and exit.
+func_fatal_error ()
+{
+    func_error ${1+"$@"}
+    exit $EXIT_FAILURE
+}
+
+# func_fatal_help arg...
+# Echo program name prefixed message to standard error, followed by
+# a help hint, and exit.
+func_fatal_help ()
+{
+    func_error ${1+"$@"}
+    func_fatal_error "$help"
+}
+help=3D"Try \`$progname --help' for more information."  ## default
+
+
+# func_grep expression filename
+# Check whether EXPRESSION matches any line of FILENAME, without output.
+func_grep ()
+{
+    $GREP "$1" "$2" >/dev/null 2>&1
+}
+
+
+# func_mkdir_p directory-path
+# Make sure the entire path to DIRECTORY-PATH is available.
+func_mkdir_p ()
+{
+    my_directory_path=3D"$1"
+    my_dir_list=3D
+
+    if test -n "$my_directory_path" && test "$opt_dry_run" !=3D ":"; then
+
+      # Protect directory names starting with `-'
+      case $my_directory_path in
+        -*) my_directory_path=3D"./$my_directory_path" ;;
+      esac
+
+      # While some portion of DIR does not yet exist...
+      while test ! -d "$my_directory_path"; do
+        # ...make a list in topmost first order.  Use a colon delimited
+	# list incase some portion of path contains whitespace.
+        my_dir_list=3D"$my_directory_path:$my_dir_list"
+
+        # If the last portion added has no slash in it, the list is done
+        case $my_directory_path in */*) ;; *) break ;; esac
+
+        # ...otherwise throw away the child directory and loop
+        my_directory_path=3D`$ECHO "$my_directory_path" | $SED -e "$dirnam=
e"`
+      done
+      my_dir_list=3D`$ECHO "$my_dir_list" | $SED 's,:*$,,'`
+
+      save_mkdir_p_IFS=3D"$IFS"; IFS=3D':'
+      for my_dir in $my_dir_list; do
+	IFS=3D"$save_mkdir_p_IFS"
+        # mkdir can fail with a `File exist' error if two processes
+        # try to create one of the directories concurrently.  Don't
+        # stop in that case!
+        $MKDIR "$my_dir" 2>/dev/null || :
+      done
+      IFS=3D"$save_mkdir_p_IFS"
+
+      # Bail out if we (or some other process) failed to create a director=
y.
+      test -d "$my_directory_path" || \
+        func_fatal_error "Failed to create \`$1'"
+    fi
+}
+
=20
 # func_mktempdir [string]
 # Make a temporary directory that won't clash with other running
@@ -149,7 +562,7 @@
 {
     my_template=3D"${TMPDIR-/tmp}/${1-$progname}"
=20
-    if test "$run" =3D ":"; then
+    if test "$opt_dry_run" =3D ":"; then
       # Return a directory name, but don't create it in dry-run mode
       my_tmpdir=3D"${my_template}-$$"
     else
@@ -158,25 +571,2963 @@
       my_tmpdir=3D`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null`
=20
       if test ! -d "$my_tmpdir"; then
-	# Failing that, at least try and use $RANDOM to avoid a race
-	my_tmpdir=3D"${my_template}-${RANDOM-0}$$"
-
-	save_mktempdir_umask=3D`umask`
-	umask 0077
-	$mkdir "$my_tmpdir"
-	umask $save_mktempdir_umask
+        # Failing that, at least try and use $RANDOM to avoid a race
+        my_tmpdir=3D"${my_template}-${RANDOM-0}$$"
+
+        save_mktempdir_umask=3D`umask`
+        umask 0077
+        $MKDIR "$my_tmpdir"
+        umask $save_mktempdir_umask
       fi
=20
       # If we're not in dry-run mode, bomb out on failure
-      test -d "$my_tmpdir" || {
-        $echo "cannot create temporary directory \`$my_tmpdir'" 1>&2
+      test -d "$my_tmpdir" || \
+        func_fatal_error "cannot create temporary directory \`$my_tmpdir'"
+    fi
+
+    $ECHO "$my_tmpdir"
+}
+
+
+# func_quote_for_eval arg
+# Aesthetically quote ARG to be evaled later.
+# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT
+# is double-quoted, suitable for a subsequent eval, whereas
+# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters
+# which are still active within double quotes backslashified.
+func_quote_for_eval ()
+{
+    case $1 in
+      *[\\\`\"\$]*)
+	func_quote_for_eval_unquoted_result=3D`$ECHO "$1" | $SED "$sed_quote_subs=
t"` ;;
+      *)
+        func_quote_for_eval_unquoted_result=3D"$1" ;;
+    esac
+
+    case $func_quote_for_eval_unquoted_result in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting, command substitution and and variable
+      # expansion for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        func_quote_for_eval_result=3D"\"$func_quote_for_eval_unquoted_resu=
lt\""
+        ;;
+      *)
+        func_quote_for_eval_result=3D"$func_quote_for_eval_unquoted_result"
+    esac
+}
+
+
+# func_quote_for_expand arg
+# Aesthetically quote ARG to be evaled later; same as above,
+# but do not quote variable references.
+func_quote_for_expand ()
+{
+    case $1 in
+      *[\\\`\"]*)
+	my_arg=3D`$ECHO "$1" | $SED \
+	    -e "$double_quote_subst" -e "$sed_double_backslash"` ;;
+      *)
+        my_arg=3D"$1" ;;
+    esac
+
+    case $my_arg in
+      # Double-quote args containing shell metacharacters to delay
+      # word splitting and command substitution for a subsequent eval.
+      # Many Bourne shells cannot handle close brackets correctly
+      # in scan sets, so we specify it separately.
+      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
+        my_arg=3D"\"$my_arg\""
+        ;;
+    esac
+
+    func_quote_for_expand_result=3D"$my_arg"
+}
+
+
+# func_show_eval cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.
+func_show_eval ()
+{
+    my_cmd=3D"$1"
+    my_fail_exp=3D"${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$my_cmd"
+      my_status=3D$?
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+
+# func_show_eval_locale cmd [fail_exp]
+# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is
+# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP
+# is given, then evaluate it.  Use the saved locale for evaluation.
+func_show_eval_locale ()
+{
+    my_cmd=3D"$1"
+    my_fail_exp=3D"${2-:}"
+
+    ${opt_silent-false} || {
+      func_quote_for_expand "$my_cmd"
+      eval "func_echo $func_quote_for_expand_result"
+    }
+
+    if ${opt_dry_run-false}; then :; else
+      eval "$lt_user_locale
+	    $my_cmd"
+      my_status=3D$?
+      eval "$lt_safe_locale"
+      if test "$my_status" -eq 0; then :; else
+	eval "(exit $my_status); $my_fail_exp"
+      fi
+    fi
+}
+
+# func_tr_sh
+# Turn $1 into a string suitable for a shell variable name.
+# Result is stored in $func_tr_sh_result.  All characters
+# not in the set a-zA-Z0-9_ are replaced with '_'. Further,
+# if $1 begins with a digit, a '_' is prepended as well.
+func_tr_sh ()
+{
+  case $1 in
+  [0-9]* | *[!a-zA-Z0-9_]*)
+    func_tr_sh_result=3D`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0=
-9_]/_/g'`
+    ;;
+  * )
+    func_tr_sh_result=3D$1
+    ;;
+  esac
+}
+
+
+# func_version
+# Echo version message to standard output and exit.
+func_version ()
+{
+    $opt_debug
+
+    $SED -n '/(C)/!b go
+	:more
+	/\./!{
+	  N
+	  s/\n# / /
+	  b more
+	}
+	:go
+	/^# '$PROGRAM' (GNU /,/# warranty; / {
+        s/^# //
+	s/^# *$//
+        s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/
+        p
+     }' < "$progpath"
+     exit $?
+}
+
+# func_usage
+# Echo short help message to standard output and exit.
+func_usage ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/^#  *.*--help/ {
+        s/^# //
+	s/^# *$//
+	s/\$progname/'$progname'/
+	p
+    }' < "$progpath"
+    echo
+    $ECHO "run \`$progname --help | more' for full usage"
+    exit $?
+}
+
+# func_help [NOEXIT]
+# Echo long help message to standard output and exit,
+# unless 'noexit' is passed as argument.
+func_help ()
+{
+    $opt_debug
+
+    $SED -n '/^# Usage:/,/# Report bugs to/ {
+	:print
+        s/^# //
+	s/^# *$//
+	s*\$progname*'$progname'*
+	s*\$host*'"$host"'*
+	s*\$SHELL*'"$SHELL"'*
+	s*\$LTCC*'"$LTCC"'*
+	s*\$LTCFLAGS*'"$LTCFLAGS"'*
+	s*\$LD*'"$LD"'*
+	s/\$with_gnu_ld/'"$with_gnu_ld"'/
+	s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/
+	s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/
+	p
+	d
+     }
+     /^# .* home page:/b print
+     /^# General help using/b print
+     ' < "$progpath"
+    ret=3D$?
+    if test -z "$1"; then
+      exit $ret
+    fi
+}
+
+# func_missing_arg argname
+# Echo program name prefixed message to standard error and set global
+# exit_cmd.
+func_missing_arg ()
+{
+    $opt_debug
+
+    func_error "missing argument for $1."
+    exit_cmd=3Dexit
+}
+
+
+# func_split_short_opt shortopt
+# Set func_split_short_opt_name and func_split_short_opt_arg shell
+# variables after splitting SHORTOPT after the 2nd character.
+func_split_short_opt ()
+{
+    my_sed_short_opt=3D'1s/^\(..\).*$/\1/;q'
+    my_sed_short_rest=3D'1s/^..\(.*\)$/\1/;q'
+
+    func_split_short_opt_name=3D`$ECHO "$1" | $SED "$my_sed_short_opt"`
+    func_split_short_opt_arg=3D`$ECHO "$1" | $SED "$my_sed_short_rest"`
+} # func_split_short_opt may be replaced by extended shell implementation
+
+
+# func_split_long_opt longopt
+# Set func_split_long_opt_name and func_split_long_opt_arg shell
+# variables after splitting LONGOPT at the `=3D' sign.
+func_split_long_opt ()
+{
+    my_sed_long_opt=3D'1s/^\(--[^=3D]*\)=3D.*/\1/;q'
+    my_sed_long_arg=3D'1s/^--[^=3D]*=3D//'
+
+    func_split_long_opt_name=3D`$ECHO "$1" | $SED "$my_sed_long_opt"`
+    func_split_long_opt_arg=3D`$ECHO "$1" | $SED "$my_sed_long_arg"`
+} # func_split_long_opt may be replaced by extended shell implementation
+
+exit_cmd=3D:
+
+
+
+
+
+magic=3D"%%%MAGIC variable%%%"
+magic_exe=3D"%%%MAGIC EXE variable%%%"
+
+# Global variables.
+nonopt=3D
+preserve_args=3D
+lo2o=3D"s/\\.lo\$/.${objext}/"
+o2lo=3D"s/\\.${objext}\$/.lo/"
+extracted_archives=3D
+extracted_serial=3D0
+
+# If this variable is set in any of the actions, the command in it
+# will be execed at the end.  This prevents here-documents from being
+# left over by shells.
+exec_cmd=3D
+
+# func_append var value
+# Append VALUE to the end of shell variable VAR.
+func_append ()
+{
+    eval "${1}=3D\$${1}\${2}"
+} # func_append may be replaced by extended shell implementation
+
+# func_append_quoted var value
+# Quote VALUE and append to the end of shell variable VAR, separated
+# by a space.
+func_append_quoted ()
+{
+    func_quote_for_eval "${2}"
+    eval "${1}=3D\$${1}\\ \$func_quote_for_eval_result"
+} # func_append_quoted may be replaced by extended shell implementation
+
+
+# func_arith arithmetic-term...
+func_arith ()
+{
+    func_arith_result=3D`expr "${@}"`
+} # func_arith may be replaced by extended shell implementation
+
+
+# func_len string
+# STRING may not start with a hyphen.
+func_len ()
+{
+    func_len_result=3D`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len`
+} # func_len may be replaced by extended shell implementation
+
+
+# func_lo2o object
+func_lo2o ()
+{
+    func_lo2o_result=3D`$ECHO "${1}" | $SED "$lo2o"`
+} # func_lo2o may be replaced by extended shell implementation
+
+
+# func_xform libobj-or-source
+func_xform ()
+{
+    func_xform_result=3D`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'`
+} # func_xform may be replaced by extended shell implementation
+
+
+# func_fatal_configuration arg...
+# Echo program name prefixed message to standard error, followed by
+# a configuration failure hint, and exit.
+func_fatal_configuration ()
+{
+    func_error ${1+"$@"}
+    func_error "See the $PACKAGE documentation for more information."
+    func_fatal_error "Fatal configuration error."
+}
+
+
+# func_config
+# Display the configuration for all the tags in this script.
+func_config ()
+{
+    re_begincf=3D'^# ### BEGIN LIBTOOL'
+    re_endcf=3D'^# ### END LIBTOOL'
+
+    # Default configuration.
+    $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath"
+
+    # Now print the configurations for the tags.
+    for tagname in $taglist; do
+      $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG:=
 $tagname\$/p" < "$progpath"
+    done
+
+    exit $?
+}
+
+# func_features
+# Display the features supported by this script.
+func_features ()
+{
+    echo "host: $host"
+    if test "$build_libtool_libs" =3D yes; then
+      echo "enable shared libraries"
+    else
+      echo "disable shared libraries"
+    fi
+    if test "$build_old_libs" =3D yes; then
+      echo "enable static libraries"
+    else
+      echo "disable static libraries"
+    fi
+
+    exit $?
+}
+
+# func_enable_tag tagname
+# Verify that TAGNAME is valid, and either flag an error and exit, or
+# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist
+# variable here.
+func_enable_tag ()
+{
+  # Global variable:
+  tagname=3D"$1"
+
+  re_begincf=3D"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$"
+  re_endcf=3D"^# ### END LIBTOOL TAG CONFIG: $tagname\$"
+  sed_extractcf=3D"/$re_begincf/,/$re_endcf/p"
+
+  # Validate tagname.
+  case $tagname in
+    *[!-_A-Za-z0-9,/]*)
+      func_fatal_error "invalid tag name: $tagname"
+      ;;
+  esac
+
+  # Don't test for the "default" C tag, as we know it's
+  # there but not specially marked.
+  case $tagname in
+    CC) ;;
+    *)
+      if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then
+	taglist=3D"$taglist $tagname"
+
+	# Evaluate the configuration.  Be careful to quote the path
+	# and the sed script, to avoid splitting on whitespace, but
+	# also don't use non-portable quotes within backquotes within
+	# quotes we have to do it in 2 steps:
+	extractedcf=3D`$SED -n -e "$sed_extractcf" < "$progpath"`
+	eval "$extractedcf"
+      else
+	func_error "ignoring unknown tag $tagname"
+      fi
+      ;;
+  esac
+}
+
+# func_check_version_match
+# Ensure that we are using m4 macros, and libtool script from the same
+# release of libtool.
+func_check_version_match ()
+{
+  if test "$package_revision" !=3D "$macro_revision"; then
+    if test "$VERSION" !=3D "$macro_version"; then
+      if test -z "$macro_version"; then
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from an older release.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSI=
ON
+$progname: and run autoconf again.
+_LT_EOF
+      else
+        cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the
+$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.
+$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSI=
ON
+$progname: and run autoconf again.
+_LT_EOF
+      fi
+    else
+      cat >&2 <<_LT_EOF
+$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $p=
ackage_revision,
+$progname: but the definition of this LT_INIT comes from revision $macro_r=
evision.
+$progname: You should recreate aclocal.m4 with macros from revision $packa=
ge_revision
+$progname: of $PACKAGE $VERSION and run autoconf again.
+_LT_EOF
+    fi
+
+    exit $EXIT_MISMATCH
+  fi
+}
+
+
+# Shorthand for --mode=3Dfoo, only valid as the first argument
+case $1 in
+clean|clea|cle|cl)
+  shift; set dummy --mode clean ${1+"$@"}; shift
+  ;;
+compile|compil|compi|comp|com|co|c)
+  shift; set dummy --mode compile ${1+"$@"}; shift
+  ;;
+execute|execut|execu|exec|exe|ex|e)
+  shift; set dummy --mode execute ${1+"$@"}; shift
+  ;;
+finish|finis|fini|fin|fi|f)
+  shift; set dummy --mode finish ${1+"$@"}; shift
+  ;;
+install|instal|insta|inst|ins|in|i)
+  shift; set dummy --mode install ${1+"$@"}; shift
+  ;;
+link|lin|li|l)
+  shift; set dummy --mode link ${1+"$@"}; shift
+  ;;
+uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)
+  shift; set dummy --mode uninstall ${1+"$@"}; shift
+  ;;
+esac
+
+
+
+# Option defaults:
+opt_debug=3D:
+opt_dry_run=3Dfalse
+opt_config=3Dfalse
+opt_preserve_dup_deps=3Dfalse
+opt_features=3Dfalse
+opt_finish=3Dfalse
+opt_help=3Dfalse
+opt_help_all=3Dfalse
+opt_silent=3D:
+opt_verbose=3D:
+opt_silent=3Dfalse
+opt_verbose=3Dfalse
+
+
+# Parse options once, thoroughly.  This comes as soon as possible in the
+# script to make things like `--version' happen as quickly as we can.
+{
+  # this just eases exit handling
+  while test $# -gt 0; do
+    opt=3D"$1"
+    shift
+    case $opt in
+      --debug|-x)	opt_debug=3D'set -x'
+			func_echo "enabling shell trace mode"
+			$opt_debug
+			;;
+      --dry-run|--dryrun|-n)
+			opt_dry_run=3D:
+			;;
+      --config)
+			opt_config=3D:
+func_config
+			;;
+      --dlopen|-dlopen)
+			optarg=3D"$1"
+			opt_dlopen=3D"${opt_dlopen+$opt_dlopen
+}$optarg"
+			shift
+			;;
+      --preserve-dup-deps)
+			opt_preserve_dup_deps=3D:
+			;;
+      --features)
+			opt_features=3D:
+func_features
+			;;
+      --finish)
+			opt_finish=3D:
+set dummy --mode finish ${1+"$@"}; shift
+			;;
+      --help)
+			opt_help=3D:
+			;;
+      --help-all)
+			opt_help_all=3D:
+opt_help=3D': help-all'
+			;;
+      --mode)
+			test $# =3D 0 && func_missing_arg $opt && break
+			optarg=3D"$1"
+			opt_mode=3D"$optarg"
+case $optarg in
+  # Valid mode arguments:
+  clean|compile|execute|finish|install|link|relink|uninstall) ;;
+
+  # Catch anything else as an error
+  *) func_error "invalid argument for $opt"
+     exit_cmd=3Dexit
+     break
+     ;;
+esac
+			shift
+			;;
+      --no-silent|--no-quiet)
+			opt_silent=3Dfalse
+func_append preserve_args " $opt"
+			;;
+      --no-verbose)
+			opt_verbose=3Dfalse
+func_append preserve_args " $opt"
+			;;
+      --silent|--quiet)
+			opt_silent=3D:
+func_append preserve_args " $opt"
+        opt_verbose=3Dfalse
+			;;
+      --verbose|-v)
+			opt_verbose=3D:
+func_append preserve_args " $opt"
+opt_silent=3Dfalse
+			;;
+      --tag)
+			test $# =3D 0 && func_missing_arg $opt && break
+			optarg=3D"$1"
+			opt_tag=3D"$optarg"
+func_append preserve_args " $opt $optarg"
+func_enable_tag "$optarg"
+			shift
+			;;
+
+      -\?|-h)		func_usage				;;
+      --help)		func_help				;;
+      --version)	func_version				;;
+
+      # Separate optargs to long options:
+      --*=3D*)
+			func_split_long_opt "$opt"
+			set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$=
@"}
+			shift
+			;;
+
+      # Separate non-argument short options:
+      -\?*|-h*|-n*|-v*)
+			func_split_short_opt "$opt"
+			set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1=
+"$@"}
+			shift
+			;;
+
+      --)		break					;;
+      -*)		func_fatal_help "unrecognized option \`$opt'" ;;
+      *)		set dummy "$opt" ${1+"$@"};	shift; break  ;;
+    esac
+  done
+
+  # Validate options:
+
+  # save first non-option argument
+  if test "$#" -gt 0; then
+    nonopt=3D"$opt"
+    shift
+  fi
+
+  # preserve --debug
+  test "$opt_debug" =3D : || func_append preserve_args " --debug"
+
+  case $host in
+    *cygwin* | *mingw* | *pw32* | *cegcc*)
+      # don't eliminate duplications in $postdeps and $predeps
+      opt_duplicate_compiler_generated_deps=3D:
+      ;;
+    *)
+      opt_duplicate_compiler_generated_deps=3D$opt_preserve_dup_deps
+      ;;
+  esac
+
+  $opt_help || {
+    # Sanity checks first:
+    func_check_version_match
+
+    if test "$build_libtool_libs" !=3D yes && test "$build_old_libs" !=3D =
yes; then
+      func_fatal_configuration "not configured to build any kind of librar=
y"
+    fi
+
+    # Darwin sucks
+    eval std_shrext=3D\"$shrext_cmds\"
+
+    # Only execute mode is allowed to have -dlopen flags.
+    if test -n "$opt_dlopen" && test "$opt_mode" !=3D execute; then
+      func_error "unrecognized option \`-dlopen'"
+      $ECHO "$help" 1>&2
+      exit $EXIT_FAILURE
+    fi
+
+    # Change the help message to a mode-specific one.
+    generic_help=3D"$help"
+    help=3D"Try \`$progname --help --mode=3D$opt_mode' for more informatio=
n."
+  }
+
+
+  # Bail if the options were screwed
+  $exit_cmd $EXIT_FAILURE
+}
+
+
+
+
+## ----------- ##
+##    Main.    ##
+## ----------- ##
+
+# func_lalib_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_lalib_p ()
+{
+    test -f "$1" &&
+      $SED -e 4q "$1" 2>/dev/null \
+        | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1
+}
+
+# func_lalib_unsafe_p file
+# True iff FILE is a libtool `.la' library or `.lo' object file.
+# This function implements the same check as func_lalib_p without
+# resorting to external programs.  To this end, it redirects stdin and
+# closes it afterwards, without saving the original file descriptor.
+# As a safety measure, use it only where a negative result would be
+# fatal anyway.  Works if `file' does not exist.
+func_lalib_unsafe_p ()
+{
+    lalib_p=3Dno
+    if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then
+	for lalib_p_l in 1 2 3 4
+	do
+	    read lalib_p_line
+	    case "$lalib_p_line" in
+		\#\ Generated\ by\ *$PACKAGE* ) lalib_p=3Dyes; break;;
+	    esac
+	done
+	exec 0<&5 5<&-
+    fi
+    test "$lalib_p" =3D yes
+}
+
+# func_ltwrapper_script_p file
+# True iff FILE is a libtool wrapper script
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_script_p ()
+{
+    func_lalib_p "$1"
+}
+
+# func_ltwrapper_executable_p file
+# True iff FILE is a libtool wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_executable_p ()
+{
+    func_ltwrapper_exec_suffix=3D
+    case $1 in
+    *.exe) ;;
+    *) func_ltwrapper_exec_suffix=3D.exe ;;
+    esac
+    $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1
+}
+
+# func_ltwrapper_scriptname file
+# Assumes file is an ltwrapper_executable
+# uses $file to determine the appropriate filename for a
+# temporary ltwrapper_script.
+func_ltwrapper_scriptname ()
+{
+    func_dirname_and_basename "$1" "" "."
+    func_stripname '' '.exe' "$func_basename_result"
+    func_ltwrapper_scriptname_result=3D"$func_dirname_result/$objdir/${fun=
c_stripname_result}_ltshwrapper"
+}
+
+# func_ltwrapper_p file
+# True iff FILE is a libtool wrapper script or wrapper executable
+# This function is only a basic sanity check; it will hardly flush out
+# determined imposters.
+func_ltwrapper_p ()
+{
+    func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1"
+}
+
+
+# func_execute_cmds commands fail_cmd
+# Execute tilde-delimited COMMANDS.
+# If FAIL_CMD is given, eval that upon failure.
+# FAIL_CMD may read-access the current command in variable CMD!
+func_execute_cmds ()
+{
+    $opt_debug
+    save_ifs=3D$IFS; IFS=3D'~'
+    for cmd in $1; do
+      IFS=3D$save_ifs
+      eval cmd=3D\"$cmd\"
+      func_show_eval "$cmd" "${2-:}"
+    done
+    IFS=3D$save_ifs
+}
+
+
+# func_source file
+# Source FILE, adding directory component if necessary.
+# Note that it is not necessary on cygwin/mingw to append a dot to
+# FILE even if both FILE and FILE.exe exist: automatic-append-.exe
+# behavior happens only for exec(3), not for open(2)!  Also, sourcing
+# `FILE.' does not work on cygwin managed mounts.
+func_source ()
+{
+    $opt_debug
+    case $1 in
+    */* | *\\*)	. "$1" ;;
+    *)		. "./$1" ;;
+    esac
+}
+
+
+# func_resolve_sysroot PATH
+# Replace a leading =3D in PATH with a sysroot.  Store the result into
+# func_resolve_sysroot_result
+func_resolve_sysroot ()
+{
+  func_resolve_sysroot_result=3D$1
+  case $func_resolve_sysroot_result in
+  =3D*)
+    func_stripname '=3D' '' "$func_resolve_sysroot_result"
+    func_resolve_sysroot_result=3D$lt_sysroot$func_stripname_result
+    ;;
+  esac
+}
+
+# func_replace_sysroot PATH
+# If PATH begins with the sysroot, replace it with =3D and
+# store the result into func_replace_sysroot_result.
+func_replace_sysroot ()
+{
+  case "$lt_sysroot:$1" in
+  ?*:"$lt_sysroot"*)
+    func_stripname "$lt_sysroot" '' "$1"
+    func_replace_sysroot_result=3D"=3D$func_stripname_result"
+    ;;
+  *)
+    # Including no sysroot.
+    func_replace_sysroot_result=3D$1
+    ;;
+  esac
+}
+
+# func_infer_tag arg
+# Infer tagged configuration to use if any are available and
+# if one wasn't chosen via the "--tag" command line option.
+# Only attempt this if the compiler in the base compile
+# command doesn't match the default compiler.
+# arg is usually of the form 'gcc ...'
+func_infer_tag ()
+{
+    $opt_debug
+    if test -n "$available_tags" && test -z "$tagname"; then
+      CC_quoted=3D
+      for arg in $CC; do
+	func_append_quoted CC_quoted "$arg"
+      done
+      CC_expanded=3D`func_echo_all $CC`
+      CC_quoted_expanded=3D`func_echo_all $CC_quoted`
+      case $@ in
+      # Blanks in the command may have been stripped by the calling shell,
+      # but not from the CC environment variable when configure was run.
+      " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+      " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_qu=
oted_expanded "*) ;;
+      # Blanks at the start of $base_compile will cause this to fail
+      # if we don't check for them as well.
+      *)
+	for z in $available_tags; do
+	  if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/nu=
ll; then
+	    # Evaluate the configuration.
+	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ###=
 END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
+	    CC_quoted=3D
+	    for arg in $CC; do
+	      # Double-quote args containing other shell metacharacters.
+	      func_append_quoted CC_quoted "$arg"
+	    done
+	    CC_expanded=3D`func_echo_all $CC`
+	    CC_quoted_expanded=3D`func_echo_all $CC_quoted`
+	    case "$@ " in
+	    " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \
+	    " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quo=
ted_expanded "*)
+	      # The compiler in the base compile command matches
+	      # the one in the tagged configuration.
+	      # Assume this is the tagged configuration we want.
+	      tagname=3D$z
+	      break
+	      ;;
+	    esac
+	  fi
+	done
+	# If $tagname still isn't set, then no tagged configuration
+	# was found and let the user know that the "--tag" command
+	# line option must be used.
+	if test -z "$tagname"; then
+	  func_echo "unable to infer tagged configuration"
+	  func_fatal_error "specify a tag with \`--tag'"
+#	else
+#	  func_verbose "using $tagname tagged configuration"
+	fi
+	;;
+      esac
+    fi
+}
+
+
+
+# func_write_libtool_object output_name pic_name nonpic_name
+# Create a libtool object file (analogous to a ".la" file),
+# but don't create it if we're doing a dry run.
+func_write_libtool_object ()
+{
+    write_libobj=3D${1}
+    if test "$build_libtool_libs" =3D yes; then
+      write_lobj=3D\'${2}\'
+    else
+      write_lobj=3Dnone
+    fi
+
+    if test "$build_old_libs" =3D yes; then
+      write_oldobj=3D\'${3}\'
+    else
+      write_oldobj=3Dnone
+    fi
+
+    $opt_dry_run || {
+      cat >${write_libobj}T <<EOF
+# $write_libobj - a libtool object file
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# Please DO NOT delete this file!
+# It is necessary for linking the library.
+
+# Name of the PIC object.
+pic_object=3D$write_lobj
+
+# Name of the non-PIC object
+non_pic_object=3D$write_oldobj
+
+EOF
+      $MV "${write_libobj}T" "${write_libobj}"
+    }
+}
+
+
+##################################################
+# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #
+##################################################
+
+# func_convert_core_file_wine_to_w32 ARG
+# Helper function used by file name conversion functions when $build is *n=
ix,
+# and $host is mingw, cygwin, or some other w32 environment. Relies on a
+# correctly configured wine environment available, with the winepath progr=
am
+# in $build's $PATH.
+#
+# ARG is the $build file name to be converted to w32 format.
+# Result is available in $func_convert_core_file_wine_to_w32_result, and w=
ill
+# be empty on error (or when ARG is empty)
+func_convert_core_file_wine_to_w32 ()
+{
+  $opt_debug
+  func_convert_core_file_wine_to_w32_result=3D"$1"
+  if test -n "$1"; then
+    # Unfortunately, winepath does not exit with a non-zero error code, so=
 we
+    # are forced to check the contents of stdout. On the other hand, if the
+    # command is not found, the shell will set an exit code of 127 and pri=
nt
+    # *an error message* to stdout. So we must check for both error code of
+    # zero AND non-empty stdout, which explains the odd construction:
+    func_convert_core_file_wine_to_w32_tmp=3D`winepath -w "$1" 2>/dev/null`
+    if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tm=
p}"; then
+      func_convert_core_file_wine_to_w32_result=3D`$ECHO "$func_convert_co=
re_file_wine_to_w32_tmp" |
+        $SED -e "$lt_sed_naive_backslashify"`
+    else
+      func_convert_core_file_wine_to_w32_result=3D
+    fi
+  fi
+}
+# end: func_convert_core_file_wine_to_w32
+
+
+# func_convert_core_path_wine_to_w32 ARG
+# Helper function used by path conversion functions when $build is *nix, a=
nd
+# $host is mingw, cygwin, or some other w32 environment. Relies on a corre=
ctly
+# configured wine environment available, with the winepath program in $bui=
ld's
+# $PATH. Assumes ARG has no leading or trailing path separator characters.
+#
+# ARG is path to be converted from $build format to win32.
+# Result is available in $func_convert_core_path_wine_to_w32_result.
+# Unconvertible file (directory) names in ARG are skipped; if no directory=
 names
+# are convertible, then the result may be empty.
+func_convert_core_path_wine_to_w32 ()
+{
+  $opt_debug
+  # unfortunately, winepath doesn't convert paths, only file names
+  func_convert_core_path_wine_to_w32_result=3D""
+  if test -n "$1"; then
+    oldIFS=3D$IFS
+    IFS=3D:
+    for func_convert_core_path_wine_to_w32_f in $1; do
+      IFS=3D$oldIFS
+      func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_=
w32_f"
+      if test -n "$func_convert_core_file_wine_to_w32_result" ; then
+        if test -z "$func_convert_core_path_wine_to_w32_result"; then
+          func_convert_core_path_wine_to_w32_result=3D"$func_convert_core_=
file_wine_to_w32_result"
+        else
+          func_append func_convert_core_path_wine_to_w32_result ";$func_co=
nvert_core_file_wine_to_w32_result"
+        fi
+      fi
+    done
+    IFS=3D$oldIFS
+  fi
+}
+# end: func_convert_core_path_wine_to_w32
+
+
+# func_cygpath ARGS...
+# Wrapper around calling the cygpath program via LT_CYGPATH. This is used =
when
+# when (1) $build is *nix and Cygwin is hosted via a wine environment; or =
(2)
+# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1)=
 or
+# (2), returns the Cygwin file name or path in func_cygpath_result (input
+# file name or path is assumed to be in w32 format, as previously converted
+# from $build's *nix or MSYS format). In case (3), returns the w32 file na=
me
+# or path in func_cygpath_result (input file name or path is assumed to be=
 in
+# Cygwin format). Returns an empty string on error.
+#
+# ARGS are passed to cygpath, with the last one being the file name or pat=
h to
+# be converted.
+#
+# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH
+# environment variable; do not put it in $PATH.
+func_cygpath ()
+{
+  $opt_debug
+  if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then
+    func_cygpath_result=3D`$LT_CYGPATH "$@" 2>/dev/null`
+    if test "$?" -ne 0; then
+      # on failure, ensure result is empty
+      func_cygpath_result=3D
+    fi
+  else
+    func_cygpath_result=3D
+    func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_=
CYGPATH'"
+  fi
+}
+#end: func_cygpath
+
+
+# func_convert_core_msys_to_w32 ARG
+# Convert file name or path ARG from MSYS format to w32 format.  Return
+# result in func_convert_core_msys_to_w32_result.
+func_convert_core_msys_to_w32 ()
+{
+  $opt_debug
+  # awkward: cmd appends spaces to result
+  func_convert_core_msys_to_w32_result=3D`( cmd //c echo "$1" ) 2>/dev/nul=
l |
+    $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"`
+}
+#end: func_convert_core_msys_to_w32
+
+
+# func_convert_file_check ARG1 ARG2
+# Verify that ARG1 (a file name in $build format) was converted to $host
+# format in ARG2. Otherwise, emit an error message, but continue (resetting
+# func_to_host_file_result to ARG1).
+func_convert_file_check ()
+{
+  $opt_debug
+  if test -z "$2" && test -n "$1" ; then
+    func_error "Could not determine host file name corresponding to"
+    func_error "  \`$1'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback:
+    func_to_host_file_result=3D"$1"
+  fi
+}
+# end func_convert_file_check
+
+
+# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH
+# Verify that FROM_PATH (a path in $build format) was converted to $host
+# format in TO_PATH. Otherwise, emit an error message, but continue, reset=
ting
+# func_to_host_file_result to a simplistic fallback value (see below).
+func_convert_path_check ()
+{
+  $opt_debug
+  if test -z "$4" && test -n "$3"; then
+    func_error "Could not determine the host path corresponding to"
+    func_error "  \`$3'"
+    func_error "Continuing, but uninstalled executables may not work."
+    # Fallback.  This is a deliberately simplistic "conversion" and
+    # should not be "improved".  See libtool.info.
+    if test "x$1" !=3D "x$2"; then
+      lt_replace_pathsep_chars=3D"s|$1|$2|g"
+      func_to_host_path_result=3D`echo "$3" |
+        $SED -e "$lt_replace_pathsep_chars"`
+    else
+      func_to_host_path_result=3D"$3"
+    fi
+  fi
+}
+# end func_convert_path_check
+
+
+# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG
+# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRO=
NTPAT
+# and appending REPL if ORIG matches BACKPAT.
+func_convert_path_front_back_pathsep ()
+{
+  $opt_debug
+  case $4 in
+  $1 ) func_to_host_path_result=3D"$3$func_to_host_path_result"
+    ;;
+  esac
+  case $4 in
+  $2 ) func_append func_to_host_path_result "$3"
+    ;;
+  esac
+}
+# end func_convert_path_front_back_pathsep
+
+
+##################################################
+# $build to $host FILE NAME CONVERSION FUNCTIONS #
+##################################################
+# invoked via `$to_host_file_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host forma=
t.
+# Result will be available in $func_to_host_file_result.
+
+
+# func_to_host_file ARG
+# Converts the file name ARG from $build format to $host format. Return re=
sult
+# in func_to_host_file_result.
+func_to_host_file ()
+{
+  $opt_debug
+  $to_host_file_cmd "$1"
+}
+# end func_to_host_file
+
+
+# func_to_tool_file ARG LAZY
+# converts the file name ARG from $build format to toolchain format. Return
+# result in func_to_tool_file_result.  If the conversion in use is listed
+# in (the comma separated) LAZY, no conversion takes place.
+func_to_tool_file ()
+{
+  $opt_debug
+  case ,$2, in
+    *,"$to_tool_file_cmd",*)
+      func_to_tool_file_result=3D$1
+      ;;
+    *)
+      $to_tool_file_cmd "$1"
+      func_to_tool_file_result=3D$func_to_host_file_result
+      ;;
+  esac
+}
+# end func_to_tool_file
+
+
+# func_convert_file_noop ARG
+# Copy ARG to func_to_host_file_result.
+func_convert_file_noop ()
+{
+  func_to_host_file_result=3D"$1"
+}
+# end func_convert_file_noop
+
+
+# func_convert_file_msys_to_w32 ARG
+# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result =
in
+# func_to_host_file_result.
+func_convert_file_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result=3D"$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_to_host_file_result=3D"$func_convert_core_msys_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_w32
+
+
+# func_convert_file_cygwin_to_w32 ARG
+# Convert file name ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_file_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result=3D"$1"
+  if test -n "$1"; then
+    # because $build is cygwin, we call "the" cygpath in $PATH; no need to=
 use
+    # LT_CYGPATH in this case.
+    func_to_host_file_result=3D`cygpath -m "$1"`
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_cygwin_to_w32
+
+
+# func_convert_file_nix_to_w32 ARG
+# Convert file name ARG from *nix to w32 format.  Requires a wine environm=
ent
+# and a working winepath. Returns result in func_to_host_file_result.
+func_convert_file_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_file_result=3D"$1"
+  if test -n "$1"; then
+    func_convert_core_file_wine_to_w32 "$1"
+    func_to_host_file_result=3D"$func_convert_core_file_wine_to_w32_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_w32
+
+
+# func_convert_file_msys_to_cygwin ARG
+# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH s=
et.
+# Returns result in func_to_host_file_result.
+func_convert_file_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result=3D"$1"
+  if test -n "$1"; then
+    func_convert_core_msys_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_msys_to_w32_result"
+    func_to_host_file_result=3D"$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_msys_to_cygwin
+
+
+# func_convert_file_nix_to_cygwin ARG
+# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin insta=
lled
+# in a wine environment, working winepath, and LT_CYGPATH set.  Returns re=
sult
+# in func_to_host_file_result.
+func_convert_file_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_file_result=3D"$1"
+  if test -n "$1"; then
+    # convert from *nix to w32, then use cygpath to convert from w32 to cy=
gwin.
+    func_convert_core_file_wine_to_w32 "$1"
+    func_cygpath -u "$func_convert_core_file_wine_to_w32_result"
+    func_to_host_file_result=3D"$func_cygpath_result"
+  fi
+  func_convert_file_check "$1" "$func_to_host_file_result"
+}
+# end func_convert_file_nix_to_cygwin
+
+
+#############################################
+# $build to $host PATH CONVERSION FUNCTIONS #
+#############################################
+# invoked via `$to_host_path_cmd ARG'
+#
+# In each case, ARG is the path to be converted from $build to $host forma=
t.
+# The result will be available in $func_to_host_path_result.
+#
+# Path separators are also converted from $build format to $host format.  =
If
+# ARG begins or ends with a path separator character, it is preserved (but
+# converted to $host format) on output.
+#
+# All path conversion functions are named using the following convention:
+#   file name conversion function    : func_convert_file_X_to_Y ()
+#   path conversion function         : func_convert_path_X_to_Y ()
+# where, for any given $build/$host combination the 'X_to_Y' value is the
+# same.  If conversion functions are added for new $build/$host combinatio=
ns,
+# the two new functions must follow this pattern, or func_init_to_host_pat=
h_cmd
+# will break.
+
+
+# func_init_to_host_path_cmd
+# Ensures that function "pointer" variable $to_host_path_cmd is set to the
+# appropriate value, based on the value of $to_host_file_cmd.
+to_host_path_cmd=3D
+func_init_to_host_path_cmd ()
+{
+  $opt_debug
+  if test -z "$to_host_path_cmd"; then
+    func_stripname 'func_convert_file_' '' "$to_host_file_cmd"
+    to_host_path_cmd=3D"func_convert_path_${func_stripname_result}"
+  fi
+}
+
+
+# func_to_host_path ARG
+# Converts the path ARG from $build format to $host format. Return result
+# in func_to_host_path_result.
+func_to_host_path ()
+{
+  $opt_debug
+  func_init_to_host_path_cmd
+  $to_host_path_cmd "$1"
+}
+# end func_to_host_path
+
+
+# func_convert_path_noop ARG
+# Copy ARG to func_to_host_path_result.
+func_convert_path_noop ()
+{
+  func_to_host_path_result=3D"$1"
+}
+# end func_convert_path_noop
+
+
+# func_convert_path_msys_to_w32 ARG
+# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic
+# conversion to w32 is not available inside the cwrapper.  Returns result =
in
+# func_to_host_path_result.
+func_convert_path_msys_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result=3D"$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from ARG.  MSYS
+    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';
+    # and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=3D$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result=3D"$func_convert_core_msys_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_msys_to_w32
+
+
+# func_convert_path_cygwin_to_w32 ARG
+# Convert path ARG from Cygwin to w32 format.  Returns result in
+# func_to_host_file_result.
+func_convert_path_cygwin_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result=3D"$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=3D$func_stripname_result
+    func_to_host_path_result=3D`cygpath -m -p "$func_to_host_path_tmp1"`
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_cygwin_to_w32
+
+
+# func_convert_path_nix_to_w32 ARG
+# Convert path ARG from *nix to w32 format.  Requires a wine environment a=
nd
+# a working winepath.  Returns result in func_to_host_file_result.
+func_convert_path_nix_to_w32 ()
+{
+  $opt_debug
+  func_to_host_path_result=3D"$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=3D$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_to_host_path_result=3D"$func_convert_core_path_wine_to_w32_result"
+    func_convert_path_check : ";" \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" ";" "$1"
+  fi
+}
+# end func_convert_path_nix_to_w32
+
+
+# func_convert_path_msys_to_cygwin ARG
+# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.
+# Returns result in func_to_host_file_result.
+func_convert_path_msys_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result=3D"$1"
+  if test -n "$1"; then
+    # See func_convert_path_msys_to_w32:
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=3D$func_stripname_result
+    func_convert_core_msys_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_msys_to_w32_result"
+    func_to_host_path_result=3D"$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_msys_to_cygwin
+
+
+# func_convert_path_nix_to_cygwin ARG
+# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed =
in a
+# a wine environment, working winepath, and LT_CYGPATH set.  Returns resul=
t in
+# func_to_host_file_result.
+func_convert_path_nix_to_cygwin ()
+{
+  $opt_debug
+  func_to_host_path_result=3D"$1"
+  if test -n "$1"; then
+    # Remove leading and trailing path separator characters from
+    # ARG. msys behavior is inconsistent here, cygpath turns them
+    # into '.;' and ';.', and winepath ignores them completely.
+    func_stripname : : "$1"
+    func_to_host_path_tmp1=3D$func_stripname_result
+    func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1"
+    func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result"
+    func_to_host_path_result=3D"$func_cygpath_result"
+    func_convert_path_check : : \
+      "$func_to_host_path_tmp1" "$func_to_host_path_result"
+    func_convert_path_front_back_pathsep ":*" "*:" : "$1"
+  fi
+}
+# end func_convert_path_nix_to_cygwin
+
+
+# func_mode_compile arg...
+func_mode_compile ()
+{
+    $opt_debug
+    # Get the compilation command and the source file.
+    base_compile=3D
+    srcfile=3D"$nonopt"  #  always keep a non-empty value in "srcfile"
+    suppress_opt=3Dyes
+    suppress_output=3D
+    arg_mode=3Dnormal
+    libobj=3D
+    later=3D
+    pie_flag=3D
+
+    for arg
+    do
+      case $arg_mode in
+      arg  )
+	# do not "continue".  Instead, add this to base_compile
+	lastarg=3D"$arg"
+	arg_mode=3Dnormal
+	;;
+
+      target )
+	libobj=3D"$arg"
+	arg_mode=3Dnormal
+	continue
+	;;
+
+      normal )
+	# Accept any command-line options.
+	case $arg in
+	-o)
+	  test -n "$libobj" && \
+	    func_fatal_error "you cannot specify \`-o' more than once"
+	  arg_mode=3Dtarget
+	  continue
+	  ;;
+
+	-pie | -fpie | -fPIE)
+          func_append pie_flag " $arg"
+	  continue
+	  ;;
+
+	-shared | -static | -prefer-pic | -prefer-non-pic)
+	  func_append later " $arg"
+	  continue
+	  ;;
+
+	-no-suppress)
+	  suppress_opt=3Dno
+	  continue
+	  ;;
+
+	-Xcompiler)
+	  arg_mode=3Darg  #  the next one goes into the "base_compile" arg list
+	  continue      #  The current "srcfile" will either be retained or
+	  ;;            #  replaced later.  I would guess that would be a bug.
+
+	-Wc,*)
+	  func_stripname '-Wc,' '' "$arg"
+	  args=3D$func_stripname_result
+	  lastarg=3D
+	  save_ifs=3D"$IFS"; IFS=3D','
+	  for arg in $args; do
+	    IFS=3D"$save_ifs"
+	    func_append_quoted lastarg "$arg"
+	  done
+	  IFS=3D"$save_ifs"
+	  func_stripname ' ' '' "$lastarg"
+	  lastarg=3D$func_stripname_result
+
+	  # Add the arguments to base_compile.
+	  func_append base_compile " $lastarg"
+	  continue
+	  ;;
+
+	*)
+	  # Accept the current argument as the source file.
+	  # The previous "srcfile" becomes the current argument.
+	  #
+	  lastarg=3D"$srcfile"
+	  srcfile=3D"$arg"
+	  ;;
+	esac  #  case $arg
+	;;
+      esac    #  case $arg_mode
+
+      # Aesthetically quote the previous argument.
+      func_append_quoted base_compile "$lastarg"
+    done # for arg
+
+    case $arg_mode in
+    arg)
+      func_fatal_error "you must specify an argument for -Xcompile"
+      ;;
+    target)
+      func_fatal_error "you must specify a target with \`-o'"
+      ;;
+    *)
+      # Get the name of the library object.
+      test -z "$libobj" && {
+	func_basename "$srcfile"
+	libobj=3D"$func_basename_result"
+      }
+      ;;
+    esac
+
+    # Recognize several different file suffixes.
+    # If the user specifies -o file.o, it is replaced with file.lo
+    case $libobj in
+    *.[cCFSifmso] | \
+    *.ada | *.adb | *.ads | *.asm | \
+    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \
+    *.[fF][09]? | *.for | *.java | *.obj | *.sx | *.cu | *.cup)
+      func_xform "$libobj"
+      libobj=3D$func_xform_result
+      ;;
+    esac
+
+    case $libobj in
+    *.lo) func_lo2o "$libobj"; obj=3D$func_lo2o_result ;;
+    *)
+      func_fatal_error "cannot determine name of library object from \`$li=
bobj'"
+      ;;
+    esac
+
+    func_infer_tag $base_compile
+
+    for arg in $later; do
+      case $arg in
+      -shared)
+	test "$build_libtool_libs" !=3D yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=3Dno
+	continue
+	;;
+
+      -static)
+	build_libtool_libs=3Dno
+	build_old_libs=3Dyes
+	continue
+	;;
+
+      -prefer-pic)
+	pic_mode=3Dyes
+	continue
+	;;
+
+      -prefer-non-pic)
+	pic_mode=3Dno
+	continue
+	;;
+      esac
+    done
+
+    func_quote_for_eval "$libobj"
+    test "X$libobj" !=3D "X$func_quote_for_eval_result" \
+      && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"'	 &()|`$[]' \
+      && func_warning "libobj name \`$libobj' may not contain shell specia=
l characters."
+    func_dirname_and_basename "$obj" "/" ""
+    objname=3D"$func_basename_result"
+    xdir=3D"$func_dirname_result"
+    lobj=3D${xdir}$objdir/$objname
+
+    test -z "$base_compile" && \
+      func_fatal_help "you must specify a compilation command"
+
+    # Delete any leftover library objects.
+    if test "$build_old_libs" =3D yes; then
+      removelist=3D"$obj $lobj $libobj ${libobj}T"
+    else
+      removelist=3D"$lobj $libobj ${libobj}T"
+    fi
+
+    # On Cygwin there's no "real" PIC flag so we must build both object ty=
pes
+    case $host_os in
+    cygwin* | mingw* | pw32* | os2* | cegcc*)
+      pic_mode=3Ddefault
+      ;;
+    esac
+    if test "$pic_mode" =3D no && test "$deplibs_check_method" !=3D pass_a=
ll; then
+      # non-PIC code in shared libraries is not supported
+      pic_mode=3Ddefault
+    fi
+
+    # Calculate the filename of the output object if compiler does
+    # not support -o with -c
+    if test "$compiler_c_o" =3D no; then
+      output_obj=3D`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${ob=
jext}
+      lockfile=3D"$output_obj.lock"
+    else
+      output_obj=3D
+      need_locks=3Dno
+      lockfile=3D
+    fi
+
+    # Lock this critical section if it is needed
+    # We use this script file to make the link, it avoids creating a new f=
ile
+    if test "$need_locks" =3D yes; then
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    elif test "$need_locks" =3D warn; then
+      if test -f "$lockfile"; then
+	$ECHO "\
+*** ERROR, $lockfile exists and contains:
+`cat $lockfile 2>/dev/null`
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
 	exit $EXIT_FAILURE
+      fi
+      func_append removelist " $output_obj"
+      $ECHO "$srcfile" > "$lockfile"
+    fi
+
+    $opt_dry_run || $RM $removelist
+    func_append removelist " $lockfile"
+    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15
+
+    func_to_tool_file "$srcfile" func_convert_file_msys_to_w32
+    srcfile=3D$func_to_tool_file_result
+    func_quote_for_eval "$srcfile"
+    qsrcfile=3D$func_quote_for_eval_result
+
+    # Only build a PIC object if we are building libtool libraries.
+    if test "$build_libtool_libs" =3D yes; then
+      # Without this assignment, base_compile gets emptied.
+      fbsd_hideous_sh_bug=3D$base_compile
+
+      if test "$pic_mode" !=3D no; then
+	command=3D"$base_compile $qsrcfile $pic_flag"
+      else
+	# Don't build PIC code
+	command=3D"$base_compile $qsrcfile"
+      fi
+
+      func_mkdir_p "$xdir$objdir"
+
+      if test -z "$output_obj"; then
+	# Place PIC objects in $objdir
+	func_append command " -o $lobj"
+      fi
+
+      func_show_eval_locale "$command"	\
+          'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" =3D warn &&
+	 test "X`cat $lockfile 2>/dev/null`" !=3D "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed, then go on to compile the next one
+      if test -n "$output_obj" && test "X$output_obj" !=3D "X$lobj"; then
+	func_show_eval '$MV "$output_obj" "$lobj"' \
+	  'error=3D$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+
+      # Allow error messages only from the first compilation.
+      if test "$suppress_opt" =3D yes; then
+	suppress_output=3D' >/dev/null 2>&1'
+      fi
+    fi
+
+    # Only build a position-dependent object if we build old libraries.
+    if test "$build_old_libs" =3D yes; then
+      if test "$pic_mode" !=3D yes; then
+	# Don't build PIC code
+	command=3D"$base_compile $qsrcfile$pie_flag"
+      else
+	command=3D"$base_compile $qsrcfile $pic_flag"
+      fi
+      if test "$compiler_c_o" =3D yes; then
+	func_append command " -o $obj"
+      fi
+
+      # Suppress compiler output if we already did a PIC compilation.
+      func_append command "$suppress_output"
+      func_show_eval_locale "$command" \
+        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'
+
+      if test "$need_locks" =3D warn &&
+	 test "X`cat $lockfile 2>/dev/null`" !=3D "X$srcfile"; then
+	$ECHO "\
+*** ERROR, $lockfile contains:
+`cat $lockfile 2>/dev/null`
+
+but it should contain:
+$srcfile
+
+This indicates that another process is trying to use the same
+temporary object file, and libtool could not work around it because
+your compiler does not support \`-c' and \`-o' together.  If you
+repeat this compilation, it may succeed, by chance, but you had better
+avoid parallel builds (make -j) in this platform, or get a better
+compiler."
+
+	$opt_dry_run || $RM $removelist
+	exit $EXIT_FAILURE
+      fi
+
+      # Just move the object if needed
+      if test -n "$output_obj" && test "X$output_obj" !=3D "X$obj"; then
+	func_show_eval '$MV "$output_obj" "$obj"' \
+	  'error=3D$?; $opt_dry_run || $RM $removelist; exit $error'
+      fi
+    fi
+
+    $opt_dry_run || {
+      func_write_libtool_object "$libobj" "$objdir/$objname" "$objname"
+
+      # Unlock the critical section if it was locked
+      if test "$need_locks" !=3D no; then
+	removelist=3D$lockfile
+        $RM "$lockfile"
+      fi
+    }
+
+    exit $EXIT_SUCCESS
+}
+
+$opt_help || {
+  test "$opt_mode" =3D compile && func_mode_compile ${1+"$@"}
+}
+
+func_mode_help ()
+{
+    # We need to display help for each of the modes.
+    case $opt_mode in
+      "")
+        # Generic help is extracted from the usage comments
+        # at the start of this file.
+        func_help
+        ;;
+
+      clean)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=3Dclean RM [RM-OPTION]... FILE...
+
+Remove files from the build directory.
+
+RM is the name of the program to use to delete files associated with each =
FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be pass=
ed
+to RM.
+
+If FILE is a libtool library, object or program, all the files associated
+with it are deleted. Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      compile)
+      $ECHO \
+"Usage: $progname [OPTION]... --mode=3Dcompile COMPILE-COMMAND... SOURCEFI=
LE
+
+Compile a source file into a libtool library object.
+
+This mode accepts the following additional options:
+
+  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
+  -no-suppress      do not suppress compiler output for multiple passes
+  -prefer-pic       try to build PIC objects only
+  -prefer-non-pic   try to build non-PIC objects only
+  -shared           do not build a \`.o' file suitable for static linking
+  -static           only build a \`.o' file suitable for static linking
+  -Wc,FLAG          pass FLAG directly to the compiler
+
+COMPILE-COMMAND is a command to be used in creating a \`standard' object f=
ile
+from the given SOURCEFILE.
+
+The output file name is determined by removing the directory component from
+SOURCEFILE, then substituting the C source code suffix \`.c' with the
+library object suffix, \`.lo'."
+        ;;
+
+      execute)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=3Dexecute COMMAND [ARGS]...
+
+Automatically set library path, then run a program.
+
+This mode accepts the following additional options:
+
+  -dlopen FILE      add the directory containing FILE to the library path
+
+This mode sets the library path environment variable according to \`-dlope=
n'
+flags.
+
+If any of the ARGS are libtool executable wrappers, then they are translat=
ed
+into their corresponding uninstalled binary, and any of their required lib=
rary
+directories are added to the library path.
+
+Then, COMMAND is executed, with ARGS as arguments."
+        ;;
+
+      finish)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=3Dfinish [LIBDIR]...
+
+Complete the installation of libtool libraries.
+
+Each LIBDIR is a directory that contains libtool libraries.
+
+The commands that this mode executes may require superuser privileges.  Use
+the \`--dry-run' option if you just want to see what would be executed."
+        ;;
+
+      install)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=3Dinstall INSTALL-COMMAND...
+
+Install executables or libraries.
+
+INSTALL-COMMAND is the installation command.  The first component should be
+either the \`install' or \`cp' program.
+
+The following components of INSTALL-COMMAND are treated specially:
+
+  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for instal=
lation
+
+The rest of the components are interpreted as arguments to that command (o=
nly
+BSD-compatible install options are recognized)."
+        ;;
+
+      link)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=3Dlink LINK-COMMAND...
+
+Link object files or libraries together to form another library, or to
+create an executable program.
+
+LINK-COMMAND is a command using the C compiler that you would use to create
+a program from several object files.
+
+The following components of LINK-COMMAND are treated specially:
+
+  -all-static       do not do any dynamic linking at all
+  -avoid-version    do not add a version suffix if possible
+  -bindir BINDIR    specify path to binaries directory (for systems where
+                    libraries must be found in the PATH setting at runtime)
+  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
+  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbo=
ls
+  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dls=
ym(3)
+  -export-symbols SYMFILE
+                    try to export only the symbols listed in SYMFILE
+  -export-symbols-regex REGEX
+                    try to export only the symbols matching REGEX
+  -LLIBDIR          search LIBDIR for required installed libraries
+  -lNAME            OUTPUT-FILE requires the installed library libNAME
+  -module           build a library that can dlopened
+  -no-fast-install  disable the fast-install mode
+  -no-install       link a not-installable executable
+  -no-undefined     declare that a library does not refer to external symb=
ols
+  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
+  -objectlist FILE  Use a list of object files found in FILE to specify ob=
jects
+  -precious-files-regex REGEX
+                    don't remove output files matching REGEX
+  -release RELEASE  specify package release information
+  -rpath LIBDIR     the created library will eventually be installed in LI=
BDIR
+  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and librari=
es
+  -shared           only do dynamic linking of libtool libraries
+  -shrext SUFFIX    override the standard shared library file extension
+  -static           do not do any dynamic linking of uninstalled libtool l=
ibraries
+  -static-libtool-libs
+                    do not do any dynamic linking of libtool libraries
+  -version-info CURRENT[:REVISION[:AGE]]
+                    specify library version info [each variable defaults t=
o 0]
+  -weak LIBNAME     declare that the target provides the LIBNAME interface
+  -Wc,FLAG
+  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler
+  -Wl,FLAG
+  -Xlinker FLAG     pass linker-specific FLAG directly to the linker
+  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)
+
+All other options (arguments beginning with \`-') are ignored.
+
+Every other argument is treated as a filename.  Files ending in \`.la' are
+treated as uninstalled libtool libraries, other files are standard or libr=
ary
+object files.
+
+If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
+only library objects (\`.lo' files) may be specified, and \`-rpath' is
+required, except when creating a convenience library.
+
+If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
+using \`ar' and \`ranlib', or on Windows using \`lib'.
+
+If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object f=
ile
+is created, otherwise an executable program is created."
+        ;;
+
+      uninstall)
+        $ECHO \
+"Usage: $progname [OPTION]... --mode=3Duninstall RM [RM-OPTION]... FILE...
+
+Remove libraries from an installation directory.
+
+RM is the name of the program to use to delete files associated with each =
FILE
+(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be pass=
ed
+to RM.
+
+If FILE is a libtool library, all the files associated with it are deleted.
+Otherwise, only FILE itself is deleted using RM."
+        ;;
+
+      *)
+        func_fatal_help "invalid operation mode \`$opt_mode'"
+        ;;
+    esac
+
+    echo
+    $ECHO "Try \`$progname --help' for more information about other modes."
+}
+
+# Now that we've collected a possible --mode arg, show help if necessary
+if $opt_help; then
+  if test "$opt_help" =3D :; then
+    func_mode_help
+  else
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean;=
 do
+	func_mode_help
+      done
+    } | sed -n '1p; 2,$s/^Usage:/  or: /p'
+    {
+      func_help noexit
+      for opt_mode in compile link execute install finish uninstall clean;=
 do
+	echo
+	func_mode_help
+      done
+    } |
+    sed '1d
+      /^When reporting/,/^Report/{
+	H
+	d
       }
+      $x
+      /information about other modes/d
+      /more detailed .*MODE/d
+      s/^Usage:.*--mode=3D\([^ ]*\) .*/Description of \1 mode:/'
+  fi
+  exit $?
+fi
+
+
+# func_mode_execute arg...
+func_mode_execute ()
+{
+    $opt_debug
+    # The first argument is the command name.
+    cmd=3D"$nonopt"
+    test -z "$cmd" && \
+      func_fatal_help "you must specify a COMMAND"
+
+    # Handle -dlopen flags immediately.
+    for file in $opt_dlopen; do
+      test -f "$file" \
+	|| func_fatal_help "\`$file' is not a file"
+
+      dir=3D
+      case $file in
+      *.la)
+	func_resolve_sysroot "$file"
+	file=3D$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$lib' is not a valid libtool archive"
+
+	# Read the libtool library.
+	dlname=3D
+	library_names=3D
+	func_source "$file"
+
+	# Skip this library if it cannot be dlopened.
+	if test -z "$dlname"; then
+	  # Warn if it was a shared library.
+	  test -n "$library_names" && \
+	    func_warning "\`$file' was not linked with \`-export-dynamic'"
+	  continue
+	fi
+
+	func_dirname "$file" "" "."
+	dir=3D"$func_dirname_result"
+
+	if test -f "$dir/$objdir/$dlname"; then
+	  func_append dir "/$objdir"
+	else
+	  if test ! -f "$dir/$dlname"; then
+	    func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir=
'"
+	  fi
+	fi
+	;;
+
+      *.lo)
+	# Just add the directory containing the .lo file.
+	func_dirname "$file" "" "."
+	dir=3D"$func_dirname_result"
+	;;
+
+      *)
+	func_warning "\`-dlopen' is ignored for non-libtool libraries and objects"
+	continue
+	;;
+      esac
+
+      # Get the absolute pathname.
+      absdir=3D`cd "$dir" && pwd`
+      test -n "$absdir" && dir=3D"$absdir"
+
+      # Now add the directory to shlibpath_var.
+      if eval "test -z \"\$$shlibpath_var\""; then
+	eval "$shlibpath_var=3D\"\$dir\""
+      else
+	eval "$shlibpath_var=3D\"\$dir:\$$shlibpath_var\""
+      fi
+    done
+
+    # This variable tells wrapper scripts just to set shlibpath_var
+    # rather than running their programs.
+    libtool_execute_magic=3D"$magic"
+
+    # Check if any of the arguments is a wrapper script.
+    args=3D
+    for file
+    do
+      case $file in
+      -* | *.la | *.lo ) ;;
+      *)
+	# Do a test to see if this is really a libtool program.
+	if func_ltwrapper_script_p "$file"; then
+	  func_source "$file"
+	  # Transform arg to wrapped name.
+	  file=3D"$progdir/$program"
+	elif func_ltwrapper_executable_p "$file"; then
+	  func_ltwrapper_scriptname "$file"
+	  func_source "$func_ltwrapper_scriptname_result"
+	  # Transform arg to wrapped name.
+	  file=3D"$progdir/$program"
+	fi
+	;;
+      esac
+      # Quote arguments (to preserve shell metacharacters).
+      func_append_quoted args "$file"
+    done
+
+    if test "X$opt_dry_run" =3D Xfalse; then
+      if test -n "$shlibpath_var"; then
+	# Export the shlibpath_var.
+	eval "export $shlibpath_var"
+      fi
+
+      # Restore saved environment variables
+      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES
+      do
+	eval "if test \"\${save_$lt_var+set}\" =3D set; then
+                $lt_var=3D\$save_$lt_var; export $lt_var
+	      else
+		$lt_unset $lt_var
+	      fi"
+      done
+
+      # Now prepare to actually exec the command.
+      exec_cmd=3D"\$cmd$args"
+    else
+      # Display what would be done.
+      if test -n "$shlibpath_var"; then
+	eval "\$ECHO \"\$shlibpath_var=3D\$$shlibpath_var\""
+	echo "export $shlibpath_var"
+      fi
+      $ECHO "$cmd$args"
+      exit $EXIT_SUCCESS
     fi
-
-    $echo "X$my_tmpdir" | $Xsed
-}
-
+}
+
+test "$opt_mode" =3D execute && func_mode_execute ${1+"$@"}
+
+
+# func_mode_finish arg...
+func_mode_finish ()
+{
+    $opt_debug
+    libs=3D
+    libdirs=3D
+    admincmds=3D
+
+    for opt in "$nonopt" ${1+"$@"}
+    do
+      if test -d "$opt"; then
+	func_append libdirs " $opt"
+
+      elif test -f "$opt"; then
+	if func_lalib_unsafe_p "$opt"; then
+	  func_append libs " $opt"
+	else
+	  func_warning "\`$opt' is not a valid libtool archive"
+	fi
+
+      else
+	func_fatal_error "invalid argument \`$opt'"
+      fi
+    done
+
+    if test -n "$libs"; then
+      if test -n "$lt_sysroot"; then
+        sysroot_regex=3D`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_reg=
ex"`
+        sysroot_cmd=3D"s/\([ ']\)$sysroot_regex/\1/g;"
+      else
+        sysroot_cmd=3D
+      fi
+
+      # Remove sysroot references
+      if $opt_dry_run; then
+        for lib in $libs; do
+          echo "removing references to $lt_sysroot and \`=3D' prefixes fro=
m $lib"
+        done
+      else
+        tmpdir=3D`func_mktempdir`
+        for lib in $libs; do
+	  sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=3D/\1/g; s/\([ ']\)=3D/\1/g" $li=
b \
+	    > $tmpdir/tmp-la
+	  mv -f $tmpdir/tmp-la $lib
+	done
+        ${RM}r "$tmpdir"
+      fi
+    fi
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      for libdir in $libdirs; do
+	if test -n "$finish_cmds"; then
+	  # Do each command in the finish commands.
+	  func_execute_cmds "$finish_cmds" 'admincmds=3D"$admincmds
+'"$cmd"'"'
+	fi
+	if test -n "$finish_eval"; then
+	  # Do the single finish_eval.
+	  eval cmds=3D\"$finish_eval\"
+	  $opt_dry_run || eval "$cmds" || func_append admincmds "
+       $cmds"
+	fi
+      done
+    fi
+
+    # Exit here if they wanted silent mode.
+    $opt_silent && exit $EXIT_SUCCESS
+
+    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
+      echo "--------------------------------------------------------------=
--------"
+      echo "Libraries have been installed in:"
+      for libdir in $libdirs; do
+	$ECHO "   $libdir"
+      done
+      echo
+      echo "If you ever happen to want to link against installed libraries"
+      echo "in a given directory, LIBDIR, you must either use libtool, and"
+      echo "specify the full pathname of the library, or use the \`-LLIBDI=
R'"
+      echo "flag during linking and do at least one of the following:"
+      if test -n "$shlibpath_var"; then
+	echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
+	echo "     during execution"
+      fi
+      if test -n "$runpath_var"; then
+	echo "   - add LIBDIR to the \`$runpath_var' environment variable"
+	echo "     during linking"
+      fi
+      if test -n "$hardcode_libdir_flag_spec"; then
+	libdir=3DLIBDIR
+	eval flag=3D\"$hardcode_libdir_flag_spec\"
+
+	$ECHO "   - use the \`$flag' linker flag"
+      fi
+      if test -n "$admincmds"; then
+	$ECHO "   - have your system administrator run these commands:$admincmds"
+      fi
+      if test -f /etc/ld.so.conf; then
+	echo "   - have your system administrator add LIBDIR to \`/etc/ld.so.conf=
'"
+      fi
+      echo
+
+      echo "See any operating system documentation about shared libraries =
for"
+      case $host in
+	solaris2.[6789]|solaris2.1[0-9])
+	  echo "more information, such as the ld(1), crle(1) and ld.so(8) manual"
+	  echo "pages."
+	  ;;
+	*)
+	  echo "more information, such as the ld(1) and ld.so(8) manual pages."
+	  ;;
+      esac
+      echo "--------------------------------------------------------------=
--------"
+    fi
+    exit $EXIT_SUCCESS
+}
+
+test "$opt_mode" =3D finish && func_mode_finish ${1+"$@"}
+
+
+# func_mode_install arg...
+func_mode_install ()
+{
+    $opt_debug
+    # There may be an optional sh(1) argument at the beginning of
+    # install_prog (especially on Windows NT).
+    if test "$nonopt" =3D "$SHELL" || test "$nonopt" =3D /bin/sh ||
+       # Allow the use of GNU shtool's install command.
+       case $nonopt in *shtool*) :;; *) false;; esac; then
+      # Aesthetically quote it.
+      func_quote_for_eval "$nonopt"
+      install_prog=3D"$func_quote_for_eval_result "
+      arg=3D$1
+      shift
+    else
+      install_prog=3D
+      arg=3D$nonopt
+    fi
+
+    # The real first argument should be the name of the installation progr=
am.
+    # Aesthetically quote it.
+    func_quote_for_eval "$arg"
+    func_append install_prog "$func_quote_for_eval_result"
+    install_shared_prog=3D$install_prog
+    case " $install_prog " in
+      *[\\\ /]cp\ *) install_cp=3D: ;;
+      *) install_cp=3Dfalse ;;
+    esac
+
+    # We need to accept at least all the BSD install flags.
+    dest=3D
+    files=3D
+    opts=3D
+    prev=3D
+    install_type=3D
+    isdir=3Dno
+    stripme=3D
+    no_mode=3D:
+    for arg
+    do
+      arg2=3D
+      if test -n "$dest"; then
+	func_append files " $dest"
+	dest=3D$arg
+	continue
+      fi
+
+      case $arg in
+      -d) isdir=3Dyes ;;
+      -f)
+	if $install_cp; then :; else
+	  prev=3D$arg
+	fi
+	;;
+      -g | -m | -o)
+	prev=3D$arg
+	;;
+      -s)
+	stripme=3D" -s"
+	continue
+	;;
+      -*)
+	;;
+      *)
+	# If the previous option needed an argument, then skip it.
+	if test -n "$prev"; then
+	  if test "x$prev" =3D x-m && test -n "$install_override_mode"; then
+	    arg2=3D$install_override_mode
+	    no_mode=3Dfalse
+	  fi
+	  prev=3D
+	else
+	  dest=3D$arg
+	  continue
+	fi
+	;;
+      esac
+
+      # Aesthetically quote the argument.
+      func_quote_for_eval "$arg"
+      func_append install_prog " $func_quote_for_eval_result"
+      if test -n "$arg2"; then
+	func_quote_for_eval "$arg2"
+      fi
+      func_append install_shared_prog " $func_quote_for_eval_result"
+    done
+
+    test -z "$install_prog" && \
+      func_fatal_help "you must specify an install program"
+
+    test -n "$prev" && \
+      func_fatal_help "the \`$prev' option requires an argument"
+
+    if test -n "$install_override_mode" && $no_mode; then
+      if $install_cp; then :; else
+	func_quote_for_eval "$install_override_mode"
+	func_append install_shared_prog " -m $func_quote_for_eval_result"
+      fi
+    fi
+
+    if test -z "$files"; then
+      if test -z "$dest"; then
+	func_fatal_help "no file or destination specified"
+      else
+	func_fatal_help "you must specify a destination"
+      fi
+    fi
+
+    # Strip any trailing slash from the destination.
+    func_stripname '' '/' "$dest"
+    dest=3D$func_stripname_result
+
+    # Check to see that the destination is a directory.
+    test -d "$dest" && isdir=3Dyes
+    if test "$isdir" =3D yes; then
+      destdir=3D"$dest"
+      destname=3D
+    else
+      func_dirname_and_basename "$dest" "" "."
+      destdir=3D"$func_dirname_result"
+      destname=3D"$func_basename_result"
+
+      # Not a directory, so check to see that there is only one file speci=
fied.
+      set dummy $files; shift
+      test "$#" -gt 1 && \
+	func_fatal_help "\`$dest' is not a directory"
+    fi
+    case $destdir in
+    [\\/]* | [A-Za-z]:[\\/]*) ;;
+    *)
+      for file in $files; do
+	case $file in
+	*.lo) ;;
+	*)
+	  func_fatal_help "\`$destdir' must be an absolute directory name"
+	  ;;
+	esac
+      done
+      ;;
+    esac
+
+    # This variable tells wrapper scripts just to set variables rather
+    # than running their programs.
+    libtool_install_magic=3D"$magic"
+
+    staticlibs=3D
+    future_libdirs=3D
+    current_libdirs=3D
+    for file in $files; do
+
+      # Do each installation.
+      case $file in
+      *.$libext)
+	# Do the static libraries later.
+	func_append staticlibs " $file"
+	;;
+
+      *.la)
+	func_resolve_sysroot "$file"
+	file=3D$func_resolve_sysroot_result
+
+	# Check to see that this really is a libtool archive.
+	func_lalib_unsafe_p "$file" \
+	  || func_fatal_help "\`$file' is not a valid libtool archive"
+
+	library_names=3D
+	old_library=3D
+	relink_command=3D
+	func_source "$file"
+
+	# Add the libdir to current_libdirs if it is the destination.
+	if test "X$destdir" =3D "X$libdir"; then
+	  case "$current_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append current_libdirs " $libdir" ;;
+	  esac
+	else
+	  # Note the libdir as a future libdir.
+	  case "$future_libdirs " in
+	  *" $libdir "*) ;;
+	  *) func_append future_libdirs " $libdir" ;;
+	  esac
+	fi
+
+	func_dirname "$file" "/" ""
+	dir=3D"$func_dirname_result"
+	func_append dir "$objdir"
+
+	if test -n "$relink_command"; then
+	  # Determine the prefix the user has applied to our future dir.
+	  inst_prefix_dir=3D`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"`
+
+	  # Don't allow the user to place us outside of our expected
+	  # location b/c this prevents finding dependent libraries that
+	  # are installed to the same prefix.
+	  # At present, this check doesn't affect windows .dll's that
+	  # are installed into $libdir/../bin (currently, that works fine)
+	  # but it's something to keep an eye on.
+	  test "$inst_prefix_dir" =3D "$destdir" && \
+	    func_fatal_error "error: cannot install \`$file' to a directory not e=
nding in $libdir"
+
+	  if test -n "$inst_prefix_dir"; then
+	    # Stick the inst_prefix_dir data into the link command.
+	    relink_command=3D`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@=
%-inst-prefix-dir $inst_prefix_dir%"`
+	  else
+	    relink_command=3D`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@=
%%"`
+	  fi
+
+	  func_warning "relinking \`$file'"
+	  func_show_eval "$relink_command" \
+	    'func_fatal_error "error: relink \`$file'\'' with the above command b=
efore installing it"'
+	fi
+
+	# See the names of the shared library.
+	set dummy $library_names; shift
+	if test -n "$1"; then
+	  realname=3D"$1"
+	  shift
+
+	  srcname=3D"$realname"
+	  test -n "$relink_command" && srcname=3D"$realname"T
+
+	  # Install the shared library and build the symlinks.
+	  func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \
+	      'exit $?'
+	  tstripme=3D"$stripme"
+	  case $host_os in
+	  cygwin* | mingw* | pw32* | cegcc*)
+	    case $realname in
+	    *.dll.a)
+	      tstripme=3D""
+	      ;;
+	    esac
+	    ;;
+	  esac
+	  if test -n "$tstripme" && test -n "$striplib"; then
+	    func_show_eval "$striplib $destdir/$realname" 'exit $?'
+	  fi
+
+	  if test "$#" -gt 0; then
+	    # Delete the old symlinks, and create new ones.
+	    # Try `ln -sf' first, because the `ln' binary might depend on
+	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
+	    # so we also need to try rm && ln -s.
+	    for linkname
+	    do
+	      test "$linkname" !=3D "$realname" \
+		&& func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $=
RM $linkname && $LN_S $realname $linkname; }; })"
+	    done
+	  fi
+
+	  # Do each command in the postinstall commands.
+	  lib=3D"$destdir/$realname"
+	  func_execute_cmds "$postinstall_cmds" 'exit $?'
+	fi
+
+	# Install the pseudo-library for information purposes.
+	func_basename "$file"
+	name=3D"$func_basename_result"
+	instname=3D"$dir/$name"i
+	func_show_eval "$install_prog $instname $destdir/$name" 'exit $?'
+
+	# Maybe install the static library, too.
+	test -n "$old_library" && func_append staticlibs " $dir/$old_library"
+	;;
+
+      *.lo)
+	# Install (i.e. copy) a libtool object.
+
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile=3D"$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile=3D"$func_basename_result"
+	  destfile=3D"$destdir/$destfile"
+	fi
+
+	# Deduce the name of the destination old-style object file.
+	case $destfile in
+	*.lo)
+	  func_lo2o "$destfile"
+	  staticdest=3D$func_lo2o_result
+	  ;;
+	*.$objext)
+	  staticdest=3D"$destfile"
+	  destfile=3D
+	  ;;
+	*)
+	  func_fatal_help "cannot copy a libtool object to \`$destfile'"
+	  ;;
+	esac
+
+	# Install the libtool object if requested.
+	test -n "$destfile" && \
+	  func_show_eval "$install_prog $file $destfile" 'exit $?'
+
+	# Install the old object if enabled.
+	if test "$build_old_libs" =3D yes; then
+	  # Deduce the name of the old-style object file.
+	  func_lo2o "$file"
+	  staticobj=3D$func_lo2o_result
+	  func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?'
+	fi
+	exit $EXIT_SUCCESS
+	;;
+
+      *)
+	# Figure out destination file name, if it wasn't already specified.
+	if test -n "$destname"; then
+	  destfile=3D"$destdir/$destname"
+	else
+	  func_basename "$file"
+	  destfile=3D"$func_basename_result"
+	  destfile=3D"$destdir/$destfile"
+	fi
+
+	# If the file is missing, and there is a .exe on the end, strip it
+	# because it is most likely a libtool script we actually want to
+	# install
+	stripped_ext=3D""
+	case $file in
+	  *.exe)
+	    if test ! -f "$file"; then
+	      func_stripname '' '.exe' "$file"
+	      file=3D$func_stripname_result
+	      stripped_ext=3D".exe"
+	    fi
+	    ;;
+	esac
+
+	# Do a test to see if this is really a libtool program.
+	case $host in
+	*cygwin* | *mingw*)
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      wrapper=3D$func_ltwrapper_scriptname_result
+	    else
+	      func_stripname '' '.exe' "$file"
+	      wrapper=3D$func_stripname_result
+	    fi
+	    ;;
+	*)
+	    wrapper=3D$file
+	    ;;
+	esac
+	if func_ltwrapper_script_p "$wrapper"; then
+	  notinst_deplibs=3D
+	  relink_command=3D
+
+	  func_source "$wrapper"
+
+	  # Check the variables that should have been set.
+	  test -z "$generated_by_libtool_version" && \
+	    func_fatal_error "invalid libtool wrapper script \`$wrapper'"
+
+	  finalize=3Dyes
+	  for lib in $notinst_deplibs; do
+	    # Check to see that each library is installed.
+	    libdir=3D
+	    if test -f "$lib"; then
+	      func_source "$lib"
+	    fi
+	    libfile=3D"$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: =
skip nested quoting test
+	    if test -n "$libdir" && test ! -f "$libfile"; then
+	      func_warning "\`$lib' has not been installed in \`$libdir'"
+	      finalize=3Dno
+	    fi
+	  done
+
+	  relink_command=3D
+	  func_source "$wrapper"
+
+	  outputname=3D
+	  if test "$fast_install" =3D no && test -n "$relink_command"; then
+	    $opt_dry_run || {
+	      if test "$finalize" =3D yes; then
+	        tmpdir=3D`func_mktempdir`
+		func_basename "$file$stripped_ext"
+		file=3D"$func_basename_result"
+	        outputname=3D"$tmpdir/$file"
+	        # Replace the output file specification.
+	        relink_command=3D`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$o=
utputname"'%g'`
+
+	        $opt_silent || {
+	          func_quote_for_expand "$relink_command"
+		  eval "func_echo $func_quote_for_expand_result"
+	        }
+	        if eval "$relink_command"; then :
+	          else
+		  func_error "error: relink \`$file' with the above command before insta=
lling it"
+		  $opt_dry_run || ${RM}r "$tmpdir"
+		  continue
+	        fi
+	        file=3D"$outputname"
+	      else
+	        func_warning "cannot relink \`$file'"
+	      fi
+	    }
+	  else
+	    # Install the binary that we compiled earlier.
+	    file=3D`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"`
+	  fi
+	fi
+
+	# remove .exe since cygwin /usr/bin/install will append another
+	# one anyway
+	case $install_prog,$host in
+	*/usr/bin/install*,*cygwin*)
+	  case $file:$destfile in
+	  *.exe:*.exe)
+	    # this is ok
+	    ;;
+	  *.exe:*)
+	    destfile=3D$destfile.exe
+	    ;;
+	  *:*.exe)
+	    func_stripname '' '.exe' "$destfile"
+	    destfile=3D$func_stripname_result
+	    ;;
+	  esac
+	  ;;
+	esac
+	func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?'
+	$opt_dry_run || if test -n "$outputname"; then
+	  ${RM}r "$tmpdir"
+	fi
+	;;
+      esac
+    done
+
+    for file in $staticlibs; do
+      func_basename "$file"
+      name=3D"$func_basename_result"
+
+      # Set up the ranlib parameters.
+      oldlib=3D"$destdir/$name"
+
+      func_show_eval "$install_prog \$file \$oldlib" 'exit $?'
+
+      if test -n "$stripme" && test -n "$old_striplib"; then
+	func_show_eval "$old_striplib $oldlib" 'exit $?'
+      fi
+
+      # Do each command in the postinstall commands.
+      func_execute_cmds "$old_postinstall_cmds" 'exit $?'
+    done
+
+    test -n "$future_libdirs" && \
+      func_warning "remember to run \`$progname --finish$future_libdirs'"
+
+    if test -n "$current_libdirs"; then
+      # Maybe just do a dry run.
+      $opt_dry_run && current_libdirs=3D" -n$current_libdirs"
+      exec_cmd=3D'$SHELL $progpath $preserve_args --finish$current_libdirs'
+    else
+      exit $EXIT_SUCCESS
+    fi
+}
+
+test "$opt_mode" =3D install && func_mode_install ${1+"$@"}
+
+
+# func_generate_dlsyms outputname originator pic_p
+# Extract symbols from dlprefiles and create ${outputname}S.o with
+# a dlpreopen symbol table.
+func_generate_dlsyms ()
+{
+    $opt_debug
+    my_outputname=3D"$1"
+    my_originator=3D"$2"
+    my_pic_p=3D"${3-no}"
+    my_prefix=3D`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'`
+    my_dlsyms=3D
+
+    if test -n "$dlfiles$dlprefiles" || test "$dlself" !=3D no; then
+      if test -n "$NM" && test -n "$global_symbol_pipe"; then
+	my_dlsyms=3D"${my_outputname}S.c"
+      else
+	func_error "not configured to extract global symbols from dlpreopened fil=
es"
+      fi
+    fi
+
+    if test -n "$my_dlsyms"; then
+      case $my_dlsyms in
+      "") ;;
+      *.c)
+	# Discover the nlist of each of the dlfiles.
+	nlist=3D"$output_objdir/${my_outputname}.nm"
+
+	func_show_eval "$RM $nlist ${nlist}S ${nlist}T"
+
+	# Parse the name list into a source file.
+	func_verbose "creating $output_objdir/$my_dlsyms"
+
+	$opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\
+/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulat=
ion. */
+/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */
+
+#ifdef __cplusplus
+extern \"C\" {
+#endif
+
+#if defined(__GNUC__) && (((__GNUC__ =3D=3D 4) && (__GNUC_MINOR__ >=3D 4))=
 || (__GNUC__ > 4))
+#pragma GCC diagnostic ignored \"-Wstrict-prototypes\"
+#endif
+
+/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tes=
ts.  */
+#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)
+/* DATA imports from DLLs on WIN32 con't be const, because runtime
+   relocations are performed -- see ld's documentation on pseudo-relocs.  =
*/
+# define LT_DLSYM_CONST
+#elif defined(__osf__)
+/* This system does not cope well with relocations in const data.  */
+# define LT_DLSYM_CONST
+#else
+# define LT_DLSYM_CONST const
+#endif
+
+/* External symbol declarations for the compiler. */\
+"
+
+	if test "$dlself" =3D yes; then
+	  func_verbose "generating symbol list for \`$output'"
+
+	  $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist"
+
+	  # Add our own program objects to the symbol list.
+	  progfiles=3D`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP`
+	  for progfile in $progfiles; do
+	    func_to_tool_file "$progfile" func_convert_file_msys_to_w32
+	    func_verbose "extracting global C symbols from \`$func_to_tool_file_r=
esult'"
+	    $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_=
pipe >> '$nlist'"
+	  done
+
+	  if test -n "$exclude_expsyms"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  if test -n "$export_symbols_regex"; then
+	    $opt_dry_run || {
+	      eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	    }
+	  fi
+
+	  # Prepare the list of exported symbols
+	  if test -z "$export_symbols"; then
+	    export_symbols=3D"$output_objdir/$outputname.exp"
+	    $opt_dry_run || {
+	      $RM $export_symbols
+	      eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< =
"$nlist" > "$export_symbols"'
+	      case $host in
+	      *cygwin* | *mingw* | *cegcc* )
+                eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+                eval 'cat "$export_symbols" >> "$output_objdir/$outputname=
.def"'
+	        ;;
+	      esac
+	    }
+	  else
+	    $opt_dry_run || {
+	      eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"'=
 < "$export_symbols" > "$output_objdir/$outputname.exp"'
+	      eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlis=
t"T'
+	      eval '$MV "$nlist"T "$nlist"'
+	      case $host in
+	        *cygwin* | *mingw* | *cegcc* )
+	          eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
+	          eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
+	          ;;
+	      esac
+	    }
+	  fi
+	fi
+
+	for dlprefile in $dlprefiles; do
+	  func_verbose "extracting global C symbols from \`$dlprefile'"
+	  func_basename "$dlprefile"
+	  name=3D"$func_basename_result"
+          case $host in
+	    *cygwin* | *mingw* | *cegcc* )
+	      # if an import library, we need to obtain dlname
+	      if func_win32_import_lib_p "$dlprefile"; then
+	        func_tr_sh "$dlprefile"
+	        eval "curr_lafile=3D\$libfile_$func_tr_sh_result"
+	        dlprefile_dlbasename=3D""
+	        if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then
+	          # Use subshell, to avoid clobbering current variable values
+	          dlprefile_dlname=3D`source "$curr_lafile" && echo "$dlname"`
+	          if test -n "$dlprefile_dlname" ; then
+	            func_basename "$dlprefile_dlname"
+	            dlprefile_dlbasename=3D"$func_basename_result"
+	          else
+	            # no lafile. user explicitly requested -dlpreopen <import lib=
rary>.
+	            $sharedlib_from_linklib_cmd "$dlprefile"
+	            dlprefile_dlbasename=3D$sharedlib_from_linklib_result
+	          fi
+	        fi
+	        $opt_dry_run || {
+	          if test -n "$dlprefile_dlbasename" ; then
+	            eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"'
+	          else
+	            func_warning "Could not compute DLL name from $name"
+	            eval '$ECHO ": $name " >> "$nlist"'
+	          fi
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_s=
ymbol_pipe |
+	            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'"
+	        }
+	      else # not an import lib
+	        $opt_dry_run || {
+	          eval '$ECHO ": $name " >> "$nlist"'
+	          func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	          eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_s=
ymbol_pipe >> '$nlist'"
+	        }
+	      fi
+	    ;;
+	    *)
+	      $opt_dry_run || {
+	        eval '$ECHO ": $name " >> "$nlist"'
+	        func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32
+	        eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_sym=
bol_pipe >> '$nlist'"
+	      }
+	    ;;
+          esac
+	done
+
+	$opt_dry_run || {
+	  # Make sure we have at least an empty file.
+	  test -f "$nlist" || : > "$nlist"
+
+	  if test -n "$exclude_expsyms"; then
+	    $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
+	    $MV "$nlist"T "$nlist"
+	  fi
+
+	  # Try sorting and uniquifying the output.
+	  if $GREP -v "^: " < "$nlist" |
+	      if sort -k 3 </dev/null >/dev/null 2>&1; then
+		sort -k 3
+	      else
+		sort +2
+	      fi |
+	      uniq > "$nlist"S; then
+	    :
+	  else
+	    $GREP -v "^: " < "$nlist" > "$nlist"S
+	  fi
+
+	  if test -f "$nlist"S; then
+	    eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dl=
syms"'
+	  else
+	    echo '/* NONE */' >> "$output_objdir/$my_dlsyms"
+	  fi
+
+	  echo >> "$output_objdir/$my_dlsyms" "\
+
+/* The mapping between symbol names and symbols.  */
+typedef struct {
+  const char *name;
+  void *address;
+} lt_dlsymlist;
+extern LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[];
+LT_DLSYM_CONST lt_dlsymlist
+lt_${my_prefix}_LTX_preloaded_symbols[] =3D
+{\
+  { \"$my_originator\", (void *) 0 },"
+
+	  case $need_lib_prefix in
+	  no)
+	    eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir=
/$my_dlsyms"
+	    ;;
+	  *)
+	    eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$ou=
tput_objdir/$my_dlsyms"
+	    ;;
+	  esac
+	  echo >> "$output_objdir/$my_dlsyms" "\
+  {0, (void *) 0}
+};
+
+/* This works around a problem in FreeBSD linker */
+#ifdef FREEBSD_WORKAROUND
+static const void *lt_preloaded_setup() {
+  return lt_${my_prefix}_LTX_preloaded_symbols;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif\
+"
+	} # !$opt_dry_run
+
+	pic_flag_for_symtable=3D
+	case "$compile_command " in
+	*" -static "*) ;;
+	*)
+	  case $host in
+	  # compiling the symbol table file with pic_flag works around
+	  # a FreeBSD bug that causes programs to crash when -lm is
+	  # linked before any other PIC object.  But we must not use
+	  # pic_flag when linking with -static.  The problem exists in
+	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
+	  *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
+	    pic_flag_for_symtable=3D" $pic_flag -DFREEBSD_WORKAROUND" ;;
+	  *-*-hpux*)
+	    pic_flag_for_symtable=3D" $pic_flag"  ;;
+	  *)
+	    if test "X$my_pic_p" !=3D Xno; then
+	      pic_flag_for_symtable=3D" $pic_flag"
+	    fi
+	    ;;
+	  esac
+	  ;;
+	esac
+	symtab_cflags=3D
+	for arg in $LTCFLAGS; do
+	  case $arg in
+	  -pie | -fpie | -fPIE) ;;
+	  *) func_append symtab_cflags " $arg" ;;
+	  esac
+	done
+
+	# Now compile the dynamic symbol file.
+	func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_f=
lag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?'
+
+	# Clean up the generated files.
+	func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${n=
list}T"'
+
+	# Transform the symbol file into the correct name.
+	symfileobj=3D"$output_objdir/${my_outputname}S.$objext"
+	case $host in
+	*cygwin* | *mingw* | *cegcc* )
+	  if test -f "$output_objdir/$my_outputname.def"; then
+	    compile_command=3D`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$outp=
ut_objdir/$my_outputname.def $symfileobj%"`
+	    finalize_command=3D`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$ou=
tput_objdir/$my_outputname.def $symfileobj%"`
+	  else
+	    compile_command=3D`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symf=
ileobj%"`
+	    finalize_command=3D`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$sy=
mfileobj%"`
+	  fi
+	  ;;
+	*)
+	  compile_command=3D`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfil=
eobj%"`
+	  finalize_command=3D`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symf=
ileobj%"`
+	  ;;
+	esac
+	;;
+      *)
+	func_fatal_error "unknown suffix for \`$my_dlsyms'"
+	;;
+      esac
+    else
+      # We keep going just in case the user didn't refer to
+      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe
+      # really was required.
+
+      # Nullify the symbol file.
+      compile_command=3D`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"`
+      finalize_command=3D`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%=
"`
+    fi
+}
=20
 # func_win32_libid arg
 # return the library type of file 'arg'
@@ -184,8 +3535,10 @@
 # Need a lot of goo to handle *both* DLLs and import libs
 # Has to be a shell function in order to 'eat' the argument
 # that is supplied when $file_magic_command is called.
+# Despite the name, also deal with 64 bit binaries.
 func_win32_libid ()
 {
+  $opt_debug
   win32_libid_type=3D"unknown"
   win32_fileres=3D`file -L $1 2>/dev/null`
   case $win32_fileres in
@@ -193,10 +3546,19 @@
     win32_libid_type=3D"x86 archive import"
     ;;
   *ar\ archive*) # could be an import, or static
-    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | \
-      $EGREP -e 'file format pe-i386(.*architecture: i386)?' >/dev/null ; =
then
-      win32_nmres=3D`eval $NM -f posix -A $1 | \
-	$SED -n -e '1,100{/ I /{s,.*,import,;p;q;};}'`
+    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHO=
D.
+    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |
+       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|=
pe-x86-64)' >/dev/null; then
+      func_to_tool_file "$1" func_convert_file_msys_to_w32
+      win32_nmres=3D`eval $NM -f posix -A \"$func_to_tool_file_result\" |
+	$SED -n -e '
+	    1,100{
+		/ I /{
+		    s,.*,import,
+		    p
+		    q
+		}
+	    }'`
       case $win32_nmres in
       import*)  win32_libid_type=3D"x86 archive import";;
       *)        win32_libid_type=3D"x86 archive static";;
@@ -214,111 +3576,172 @@
     esac
     ;;
   esac
-  $echo $win32_libid_type
-}
-
-
-# func_infer_tag arg
-# Infer tagged configuration to use if any are available and
-# if one wasn't chosen via the "--tag" command line option.
-# Only attempt this if the compiler in the base compile
-# command doesn't match the default compiler.
-# arg is usually of the form 'gcc ...'
-func_infer_tag ()
-{
-    if test -n "$available_tags" && test -z "$tagname"; then
-      CC_quoted=3D
-      for arg in $CC; do
-	case $arg in
-	  *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	  arg=3D"\"$arg\""
-	  ;;
-	esac
-	CC_quoted=3D"$CC_quoted $arg"
-      done
-      case $@ in
-      # Blanks in the command may have been stripped by the calling shell,
-      # but not from the CC environment variable when configure was run.
-      " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quot=
ed"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*) ;;
-      # Blanks at the start of $base_compile will cause this to fail
-      # if we don't check for them as well.
-      *)
-	for z in $available_tags; do
-	  if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/nul=
l; then
-	    # Evaluate the configuration.
-	    eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ###=
 END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`"
-	    CC_quoted=3D
-	    for arg in $CC; do
-	    # Double-quote args containing other shell metacharacters.
-	    case $arg in
-	      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	      arg=3D"\"$arg\""
-	      ;;
-	    esac
-	    CC_quoted=3D"$CC_quoted $arg"
-	  done
-	    case "$@ " in
-	      " $CC "* | "$CC "* | " `$echo $CC` "* | "`$echo $CC` "* | " $CC_quo=
ted"* | "$CC_quoted "* | " `$echo $CC_quoted` "* | "`$echo $CC_quoted` "*)
-	      # The compiler in the base compile command matches
-	      # the one in the tagged configuration.
-	      # Assume this is the tagged configuration we want.
-	      tagname=3D$z
-	      break
-	      ;;
-	    esac
-	  fi
-	done
-	# If $tagname still isn't set, then no tagged configuration
-	# was found and let the user know that the "--tag" command
-	# line option must be used.
-	if test -z "$tagname"; then
-	  $echo "$modename: unable to infer tagged configuration"
-	  $echo "$modename: specify a tag with \`--tag'" 1>&2
-	  exit $EXIT_FAILURE
-#        else
-#          $echo "$modename: using $tagname tagged configuration"
-	fi
-	;;
-      esac
-    fi
+  $ECHO "$win32_libid_type"
+}
+
+# func_cygming_dll_for_implib ARG
+#
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib ()
+{
+  $opt_debug
+  sharedlib_from_linklib_result=3D`$DLLTOOL --identify-strict --identify "=
$1"`
+}
+
+# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs
+#
+# The is the core of a fallback implementation of a
+# platform-specific function to extract the name of the
+# DLL associated with the specified import library LIBNAME.
+#
+# SECTION_NAME is either .idata$6 or .idata$7, depending
+# on the platform and compiler that created the implib.
+#
+# Echos the name of the DLL associated with the
+# specified import library.
+func_cygming_dll_for_implib_fallback_core ()
+{
+  $opt_debug
+  match_literal=3D`$ECHO "$1" | $SED "$sed_make_literal_regex"`
+  $OBJDUMP -s --section "$1" "$2" 2>/dev/null |
+    $SED '/^Contents of section '"$match_literal"':/{
+      # Place marker at beginning of archive member dllname section
+      s/.*/=3D=3D=3D=3DMARK=3D=3D=3D=3D/
+      p
+      d
+    }
+    # These lines can sometimes be longer than 43 characters, but
+    # are always uninteresting
+    /:[	 ]*file format pe[i]\{,1\}-/d
+    /^In archive [^:]*:/d
+    # Ensure marker is printed
+    /^=3D=3D=3D=3DMARK=3D=3D=3D=3D/p
+    # Remove all lines with less than 43 characters
+    /^.\{43\}/!d
+    # From remaining lines, remove first 43 characters
+    s/^.\{43\}//' |
+    $SED -n '
+      # Join marker and all lines until next marker into a single line
+      /^=3D=3D=3D=3DMARK=3D=3D=3D=3D/ b para
+      H
+      $ b para
+      b
+      :para
+      x
+      s/\n//g
+      # Remove the marker
+      s/^=3D=3D=3D=3DMARK=3D=3D=3D=3D//
+      # Remove trailing dots and whitespace
+      s/[\. \t]*$//
+      # Print
+      /./p' |
+    # we now have a list, one entry per line, of the stringified
+    # contents of the appropriate section of all members of the
+    # archive which possess that section. Heuristic: eliminate
+    # all those which have a first or second character that is
+    # a '.' (that is, objdump's representation of an unprintable
+    # character.) This should work for all archives with less than
+    # 0x302f exports -- but will fail for DLLs whose name actually
+    # begins with a literal '.' or a single character followed by
+    # a '.'.
+    #
+    # Of those that remain, print the first one.
+    $SED -e '/^\./d;/^.\./d;q'
+}
+
+# func_cygming_gnu_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is a GNU/binutils-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_gnu_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_gnu_implib_tmp=3D`$NM "$func_to_tool_file_result" | eval "$=
global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[a=
d]l*_iname)$'`
+  test -n "$func_cygming_gnu_implib_tmp"
+}
+
+# func_cygming_ms_implib_p ARG
+# This predicate returns with zero status (TRUE) if
+# ARG is an MS-style import library. Returns
+# with nonzero status (FALSE) otherwise.
+func_cygming_ms_implib_p ()
+{
+  $opt_debug
+  func_to_tool_file "$1" func_convert_file_msys_to_w32
+  func_cygming_ms_implib_tmp=3D`$NM "$func_to_tool_file_result" | eval "$g=
lobal_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'`
+  test -n "$func_cygming_ms_implib_tmp"
+}
+
+# func_cygming_dll_for_implib_fallback ARG
+# Platform-specific function to extract the
+# name of the DLL associated with the specified
+# import library ARG.
+#
+# This fallback implementation is for use when $DLLTOOL
+# does not support the --identify-strict option.
+# Invoked by eval'ing the libtool variable
+#    $sharedlib_from_linklib_cmd
+# Result is available in the variable
+#    $sharedlib_from_linklib_result
+func_cygming_dll_for_implib_fallback ()
+{
+  $opt_debug
+  if func_cygming_gnu_implib_p "$1" ; then
+    # binutils import library
+    sharedlib_from_linklib_result=3D`func_cygming_dll_for_implib_fallback_=
core '.idata$7' "$1"`
+  elif func_cygming_ms_implib_p "$1" ; then
+    # ms-generated import library
+    sharedlib_from_linklib_result=3D`func_cygming_dll_for_implib_fallback_=
core '.idata$6' "$1"`
+  else
+    # unknown
+    sharedlib_from_linklib_result=3D""
+  fi
 }
=20
=20
 # func_extract_an_archive dir oldlib
 func_extract_an_archive ()
 {
+    $opt_debug
     f_ex_an_ar_dir=3D"$1"; shift
     f_ex_an_ar_oldlib=3D"$1"
-
-    $show "(cd $f_ex_an_ar_dir && $AR x $f_ex_an_ar_oldlib)"
-    $run eval "(cd \$f_ex_an_ar_dir && $AR x \$f_ex_an_ar_oldlib)" || exit=
 $?
+    if test "$lock_old_archive_extraction" =3D yes; then
+      lockfile=3D$f_ex_an_ar_oldlib.lock
+      until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do
+	func_echo "Waiting for $lockfile to be removed"
+	sleep 2
+      done
+    fi
+    func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")=
" \
+		   'stat=3D$?; rm -f "$lockfile"; exit $stat'
+    if test "$lock_old_archive_extraction" =3D yes; then
+      $opt_dry_run || rm -f "$lockfile"
+    fi
     if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then
      :
     else
-      $echo "$modename: ERROR: object name conflicts: $f_ex_an_ar_dir/$f_e=
x_an_ar_oldlib" 1>&2
-      exit $EXIT_FAILURE
+      func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/=
$f_ex_an_ar_oldlib"
     fi
 }
=20
+
 # func_extract_archives gentop oldlib ...
 func_extract_archives ()
 {
+    $opt_debug
     my_gentop=3D"$1"; shift
     my_oldlibs=3D${1+"$@"}
     my_oldobjs=3D""
     my_xlib=3D""
     my_xabs=3D""
     my_xdir=3D""
-    my_status=3D""
-
-    $show "${rm}r $my_gentop"
-    $run ${rm}r "$my_gentop"
-    $show "$mkdir $my_gentop"
-    $run $mkdir "$my_gentop"
-    my_status=3D$?
-    if test "$my_status" -ne 0 && test ! -d "$my_gentop"; then
-      exit $my_status
-    fi
=20
     for my_xlib in $my_oldlibs; do
       # Extract the objects.
@@ -326,747 +3749,1340 @@
 	[\\/]* | [A-Za-z]:[\\/]*) my_xabs=3D"$my_xlib" ;;
 	*) my_xabs=3D`pwd`"/$my_xlib" ;;
       esac
-      my_xlib=3D`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'`
-      my_xdir=3D"$my_gentop/$my_xlib"
-
-      $show "${rm}r $my_xdir"
-      $run ${rm}r "$my_xdir"
-      $show "$mkdir $my_xdir"
-      $run $mkdir "$my_xdir"
-      exit_status=3D$?
-      if test "$exit_status" -ne 0 && test ! -d "$my_xdir"; then
-	exit $exit_status
-      fi
+      func_basename "$my_xlib"
+      my_xlib=3D"$func_basename_result"
+      my_xlib_u=3D$my_xlib
+      while :; do
+        case " $extracted_archives " in
+	*" $my_xlib_u "*)
+	  func_arith $extracted_serial + 1
+	  extracted_serial=3D$func_arith_result
+	  my_xlib_u=3Dlt$extracted_serial-$my_xlib ;;
+	*) break ;;
+	esac
+      done
+      extracted_archives=3D"$extracted_archives $my_xlib_u"
+      my_xdir=3D"$my_gentop/$my_xlib_u"
+
+      func_mkdir_p "$my_xdir"
+
       case $host in
       *-darwin*)
-	$show "Extracting $my_xabs"
+	func_verbose "Extracting $my_xabs"
 	# Do not bother doing anything if just a dry run
-	if test -z "$run"; then
+	$opt_dry_run || {
 	  darwin_orig_dir=3D`pwd`
 	  cd $my_xdir || exit $?
 	  darwin_archive=3D$my_xabs
 	  darwin_curdir=3D`pwd`
-	  darwin_base_archive=3D`$echo "X$darwin_archive" | $Xsed -e 's%^.*/%%'`
-	  darwin_arches=3D`lipo -info "$darwin_archive" 2>/dev/null | $EGREP Arch=
itectures 2>/dev/null`
-	  if test -n "$darwin_arches"; then=20
-	    darwin_arches=3D`echo "$darwin_arches" | $SED -e 's/.*are://'`
+	  darwin_base_archive=3D`basename "$darwin_archive"`
+	  darwin_arches=3D`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Arch=
itectures 2>/dev/null || true`
+	  if test -n "$darwin_arches"; then
+	    darwin_arches=3D`$ECHO "$darwin_arches" | $SED -e 's/.*are://'`
 	    darwin_arch=3D
-	    $show "$darwin_base_archive has multiple architectures $darwin_arches"
+	    func_verbose "$darwin_base_archive has multiple architectures $darwin=
_arches"
 	    for darwin_arch in  $darwin_arches ; do
-	      mkdir -p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
-	      lipo -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${=
darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
+	      func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}"
+	      $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-$=
{darwin_arch}/${darwin_base_archive}" "${darwin_archive}"
 	      cd "unfat-$$/${darwin_base_archive}-${darwin_arch}"
 	      func_extract_an_archive "`pwd`" "${darwin_base_archive}"
 	      cd "$darwin_curdir"
-	      $rm "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_a=
rchive}"
+	      $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_a=
rchive}"
 	    done # $darwin_arches
-      ## Okay now we have a bunch of thin objects, gotta fatten them up :)
-	    darwin_filelist=3D`find unfat-$$ -type f -name \*.o -print -o -name \=
*.lo -print| xargs basename | sort -u | $NL2SP`
+            ## Okay now we've a bunch of thin objects, gotta fatten them u=
p :)
+	    darwin_filelist=3D`find unfat-$$ -type f -name \*.o -print -o -name \=
*.lo -print | $SED -e "$basename" | sort -u`
 	    darwin_file=3D
 	    darwin_files=3D
 	    for darwin_file in $darwin_filelist; do
-	      darwin_files=3D`find unfat-$$ -name $darwin_file -print | $NL2SP`
-	      lipo -create -output "$darwin_file" $darwin_files
+	      darwin_files=3D`find unfat-$$ -name $darwin_file -print | sort | $N=
L2SP`
+	      $LIPO -create -output "$darwin_file" $darwin_files
 	    done # $darwin_filelist
-	    ${rm}r unfat-$$
+	    $RM -rf unfat-$$
 	    cd "$darwin_orig_dir"
 	  else
-	    cd "$darwin_orig_dir"
- 	    func_extract_an_archive "$my_xdir" "$my_xabs"
+	    cd $darwin_orig_dir
+	    func_extract_an_archive "$my_xdir" "$my_xabs"
 	  fi # $darwin_arches
-	fi # $run
+	} # !$opt_dry_run
 	;;
       *)
         func_extract_an_archive "$my_xdir" "$my_xabs"
-        ;;
-      esac
-      my_oldobjs=3D"$my_oldobjs "`find $my_xdir -name \*.$objext -print -o=
 -name \*.lo -print | $NL2SP`
-    done
-    func_extract_archives_result=3D"$my_oldobjs"
-}
-# End of Shell function definitions
-#####################################
-
-# Darwin sucks
-eval std_shrext=3D\"$shrext_cmds\"
-
-disable_libs=3Dno
-
-# Parse our command line options once, thoroughly.
-while test "$#" -gt 0
-do
-  arg=3D"$1"
-  shift
-
-  case $arg in
-  -*=3D*) optarg=3D`$echo "X$arg" | $Xsed -e 's/[-_a-zA-Z0-9]*=3D//'` ;;
-  *) optarg=3D ;;
-  esac
-
-  # If the previous option needs an argument, assign it.
-  if test -n "$prev"; then
-    case $prev in
-    execute_dlfiles)
-      execute_dlfiles=3D"$execute_dlfiles $arg"
-      ;;
-    tag)
-      tagname=3D"$arg"
-      preserve_args=3D"${preserve_args}=3D$arg"
-
-      # Check whether tagname contains only valid characters
-      case $tagname in
-      *[!-_A-Za-z0-9,/]*)
-	$echo "$progname: invalid tag name: $tagname" 1>&2
-	exit $EXIT_FAILURE
 	;;
       esac
-
-      case $tagname in
-      CC)
-	# Don't test for the "default" C tag, as we know, it's there, but
-	# not specially marked.
-	;;
-      *)
-	if grep "^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$" < "$progpath" > /dev=
/null; then
-	  taglist=3D"$taglist $tagname"
-	  # Evaluate the configuration.
-	  eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$tagname'$/,/^#=
 ### END LIBTOOL TAG CONFIG: '$tagname'$/p' < $progpath`"
-	else
-	  $echo "$progname: ignoring unknown tag $tagname" 1>&2
-	fi
-	;;
-      esac
+      my_oldobjs=3D"$my_oldobjs "`find $my_xdir -name \*.$objext -print -o=
 -name \*.lo -print | sort | $NL2SP`
+    done
+
+    func_extract_archives_result=3D"$my_oldobjs"
+}
+
+
+# func_emit_wrapper [arg=3Dno]
+#
+# Emit a libtool wrapper script on stdout.
+# Don't directly open a file because we may want to
+# incorporate the script contents within a cygwin/mingw
+# wrapper executable.  Must ONLY be called from within
+# func_mode_link because it depends on a number of variables
+# set therein.
+#
+# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR
+# variable will take.  If 'yes', then the emitted script
+# will assume that the directory in which it is stored is
+# the $objdir directory.  This is a cygwin/mingw-specific
+# behavior.
+func_emit_wrapper ()
+{
+	func_emit_wrapper_arg1=3D${1-no}
+
+	$ECHO "\
+#! $SHELL
+
+# $output - temporary wrapper script for $objdir/$outputname
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+#
+# The $output program cannot be directly executed until all the libtool
+# libraries that it depends on are installed.
+#
+# This wrapper script should never be moved out of the build directory.
+# If it is, it will not operate correctly.
+
+# Sed substitution that helps us do robust quoting.  It backslashifies
+# metacharacters that are still active within double-quoted strings.
+sed_quote_subst=3D'$sed_quote_subst'
+
+# Be Bourne compatible
+if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=3D:
+  # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'=3D'\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac
+fi
+BIN_SH=3Dxpg4; export BIN_SH # for Tru64
+DUALCASE=3D1; export DUALCASE # for MKS sh
+
+# The HP-UX ksh and POSIX shell print the target directory to stdout
+# if CDPATH is set.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+relink_command=3D\"$relink_command\"
+
+# This environment variable determines our operation mode.
+if test \"\$libtool_install_magic\" =3D \"$magic\"; then
+  # install mode needs the following variables:
+  generated_by_libtool_version=3D'$macro_version'
+  notinst_deplibs=3D'$notinst_deplibs'
+else
+  # When we are sourced in execute mode, \$file and \$ECHO are already set.
+  if test \"\$libtool_execute_magic\" !=3D \"$magic\"; then
+    file=3D\"\$0\""
+
+    qECHO=3D`$ECHO "$ECHO" | $SED "$sed_quote_subst"`
+    $ECHO "\
+
+# A function that is used when there is no print builtin or printf.
+func_fallback_echo ()
+{
+  eval 'cat <<_LTECHO_EOF
+\$1
+_LTECHO_EOF'
+}
+    ECHO=3D\"$qECHO\"
+  fi
+
+# Very basic option parsing. These options are (a) specific to
+# the libtool wrapper, (b) are identical between the wrapper
+# /script/ and the wrapper /executable/ which is used only on
+# windows platforms, and (c) all begin with the string "--lt-"
+# (application programs are unlikely to have options which match
+# this pattern).
+#
+# There are only two supported options: --lt-debug and
+# --lt-dump-script. There is, deliberately, no --lt-help.
+#
+# The first argument to this parsing function should be the
+# script's $0 value, followed by "$@".
+lt_option_debug=3D
+func_parse_lt_options ()
+{
+  lt_script_arg0=3D\$0
+  shift
+  for lt_opt
+  do
+    case \"\$lt_opt\" in
+    --lt-debug) lt_option_debug=3D1 ;;
+    --lt-dump-script)
+        lt_dump_D=3D\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e '=
s%/[^/]*$%%'\`
+        test \"X\$lt_dump_D\" =3D \"X\$lt_script_arg0\" && lt_dump_D=3D.
+        lt_dump_F=3D\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e '=
s%^.*/%%'\`
+        cat \"\$lt_dump_D/\$lt_dump_F\"
+        exit 0
       ;;
-    *)
-      eval "$prev=3D\$arg"
+    --lt-*)
+        \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2
+        exit 1
       ;;
     esac
-
-    prev=3D
-    prevopt=3D
-    continue
+  done
+
+  # Print the debug banner immediately:
+  if test -n \"\$lt_option_debug\"; then
+    echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKA=
GE$TIMESTAMP) $VERSION\" 1>&2
   fi
-
-  # Have we seen a non-optional argument yet?
-  case $arg in
-  --help)
-    show_help=3Dyes
+}
+
+# Used when --lt-debug. Prints its arguments to stdout
+# (redirection is the responsibility of the caller)
+func_lt_dump_args ()
+{
+  lt_dump_args_N=3D1;
+  for lt_arg
+  do
+    \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]=
: \$lt_arg\"
+    lt_dump_args_N=3D\`expr \$lt_dump_args_N + 1\`
+  done
+}
+
+# Core function for launching the target application
+func_exec_program_core ()
+{
+"
+  case $host in
+  # Backslashes separate directories on plain windows
+  *-*-mingw | *-*-os2* | *-cegcc*)
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir=
\\\\\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
+"
     ;;
=20
-  --version)
-    $echo "$PROGRAM (GNU $PACKAGE) $VERSION$TIMESTAMP"
-    $echo
-    $echo "Copyright (C) 2005  Free Software Foundation, Inc."
-    $echo "This is free software; see the source for copying conditions.  =
There is NO"
-    $echo "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICU=
LAR PURPOSE."
-    exit $?
-    ;;
-
-  --config)
-    ${SED} -e '1,/^# ### BEGIN LIBTOOL CONFIG/d' -e '/^# ### END LIBTOOL C=
ONFIG/,$d' $progpath
-    # Now print the configurations for the tags.
-    for tagname in $taglist; do
-      ${SED} -n -e "/^# ### BEGIN LIBTOOL TAG CONFIG: $tagname$/,/^# ### E=
ND LIBTOOL TAG CONFIG: $tagname$/p" < "$progpath"
-    done
-    exit $?
-    ;;
-
-  --debug)
-    $echo "$progname: enabling shell trace mode"
-    set -x
-    preserve_args=3D"$preserve_args $arg"
-    ;;
-
-  --dry-run | -n)
-    run=3D:
-    ;;
-
-  --features)
-    $echo "host: $host"
-    if test "$build_libtool_libs" =3D yes; then
-      $echo "enable shared libraries"
-    else
-      $echo "disable shared libraries"
-    fi
-    if test "$build_old_libs" =3D yes; then
-      $echo "enable static libraries"
-    else
-      $echo "disable static libraries"
-    fi
-    exit $?
-    ;;
-
-  --finish) mode=3D"finish" ;;
-
-  --mode) prevopt=3D"--mode" prev=3Dmode ;;
-  --mode=3D*) mode=3D"$optarg" ;;
-
-  --preserve-dup-deps) duplicate_deps=3D"yes" ;;
-
-  --quiet | --silent)
-    show=3D:
-    preserve_args=3D"$preserve_args $arg"
-    ;;
-
-  --tag)
-    prevopt=3D"--tag"
-    prev=3Dtag
-    preserve_args=3D"$preserve_args --tag"
-    ;;
-  --tag=3D*)
-    set tag "$optarg" ${1+"$@"}
-    shift
-    prev=3Dtag
-    preserve_args=3D"$preserve_args --tag"
-    ;;
-
-  -dlopen)
-    prevopt=3D"-dlopen"
-    prev=3Dexecute_dlfiles
-    ;;
-
-  -*)
-    $echo "$modename: unrecognized option \`$arg'" 1>&2
-    $echo "$help" 1>&2
-    exit $EXIT_FAILURE
-    ;;
-
   *)
-    nonopt=3D"$arg"
-    break
+    $ECHO "\
+      if test -n \"\$lt_option_debug\"; then
+        \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir=
/\$program\" 1>&2
+        func_lt_dump_args \${1+\"\$@\"} 1>&2
+      fi
+      exec \"\$progdir/\$program\" \${1+\"\$@\"}
+"
     ;;
   esac
-done
-
-if test -n "$prevopt"; then
-  $echo "$modename: option \`$prevopt' requires an argument" 1>&2
-  $echo "$help" 1>&2
-  exit $EXIT_FAILURE
-fi
-
-case $disable_libs in
-no)=20
-  ;;
-shared)
-  build_libtool_libs=3Dno
-  build_old_libs=3Dyes
-  ;;
-static)
-  build_old_libs=3D`case $build_libtool_libs in yes) echo no;; *) echo yes=
;; esac`
-  ;;
-esac
-
-# If this variable is set in any of the actions, the command in it
-# will be execed at the end.  This prevents here-documents from being
-# left over by shells.
-exec_cmd=3D
-
-if test -z "$show_help"; then
-
-  # Infer the operation mode.
-  if test -z "$mode"; then
-    $echo "*** Warning: inferring the mode of operation is deprecated." 1>=
&2
-    $echo "*** Future versions of Libtool will require --mode=3DMODE be sp=
ecified." 1>&2
-    case $nonopt in
-    *cc | cc* | *++ | gcc* | *-gcc* | g++* | xlc*)
-      mode=3Dlink
-      for arg
-      do
-	case $arg in
-	-c)
-	   mode=3Dcompile
-	   break
-	   ;;
-	esac
-      done
-      ;;
-    *db | *dbx | *strace | *truss)
-      mode=3Dexecute
-      ;;
-    *install*|cp|mv)
-      mode=3Dinstall
-      ;;
-    *rm)
-      mode=3Duninstall
-      ;;
-    *)
-      # If we have no mode, but dlfiles were specified, then do execute mo=
de.
-      test -n "$execute_dlfiles" && mode=3Dexecute
-
-      # Just use the default operation mode.
-      if test -z "$mode"; then
-	if test -n "$nonopt"; then
-	  $echo "$modename: warning: cannot infer operation mode from \`$nonopt'"=
 1>&2
-	else
-	  $echo "$modename: warning: cannot infer operation mode without MODE-ARG=
S" 1>&2
-	fi
-      fi
-      ;;
+  $ECHO "\
+      \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2
+      exit 1
+}
+
+# A function to encapsulate launching the target application
+# Strips options in the --lt-* namespace from \$@ and
+# launches target application with the remaining arguments.
+func_exec_program ()
+{
+  for lt_wr_arg
+  do
+    case \$lt_wr_arg in
+    --lt-*) ;;
+    *) set x \"\$@\" \"\$lt_wr_arg\"; shift;;
+    esac
+    shift
+  done
+  func_exec_program_core \${1+\"\$@\"}
+}
+
+  # Parse options
+  func_parse_lt_options \"\$0\" \${1+\"\$@\"}
+
+  # Find the directory that this script lives in.
+  thisdir=3D\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\`
+  test \"x\$thisdir\" =3D \"x\$file\" && thisdir=3D.
+
+  # Follow symbolic links until we get to the real thisdir.
+  file=3D\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\`
+  while test -n \"\$file\"; do
+    destdir=3D\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\`
+
+    # If there was a directory component, then change thisdir.
+    if test \"x\$destdir\" !=3D \"x\$file\"; then
+      case \"\$destdir\" in
+      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=3D\"\$destdir\" ;;
+      *) thisdir=3D\"\$thisdir/\$destdir\" ;;
+      esac
+    fi
+
+    file=3D\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\`
+    file=3D\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\`
+  done
+
+  # Usually 'no', except on cygwin/mingw when embedded into
+  # the cwrapper.
+  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=3D$func_emit_wrapper_arg1
+  if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" =3D \"yes\"; then
+    # special case for '.'
+    if test \"\$thisdir\" =3D \".\"; then
+      thisdir=3D\`pwd\`
+    fi
+    # remove .libs from thisdir
+    case \"\$thisdir\" in
+    *[\\\\/]$objdir ) thisdir=3D\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^=
\\\\/]*$%%'\` ;;
+    $objdir )   thisdir=3D. ;;
     esac
   fi
=20
-  # Only execute mode is allowed to have -dlopen flags.
-  if test -n "$execute_dlfiles" && test "$mode" !=3D execute; then
-    $echo "$modename: unrecognized option \`-dlopen'" 1>&2
-    $echo "$help" 1>&2
-    exit $EXIT_FAILURE
+  # Try to get the absolute directory name.
+  absdir=3D\`cd \"\$thisdir\" && pwd\`
+  test -n \"\$absdir\" && thisdir=3D\"\$absdir\"
+"
+
+	if test "$fast_install" =3D yes; then
+	  $ECHO "\
+  program=3Dlt-'$outputname'$exeext
+  progdir=3D\"\$thisdir/$objdir\"
+
+  if test ! -f \"\$progdir/\$program\" ||
+     { file=3D\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\"=
 2>/dev/null | ${SED} 1q\`; \\
+       test \"X\$file\" !=3D \"X\$progdir/\$program\"; }; then
+
+    file=3D\"\$\$-\$program\"
+
+    if test ! -d \"\$progdir\"; then
+      $MKDIR \"\$progdir\"
+    else
+      $RM \"\$progdir/\$file\"
+    fi"
+
+	  $ECHO "\
+
+    # relink executable if necessary
+    if test -n \"\$relink_command\"; then
+      if relink_command_output=3D\`eval \$relink_command 2>&1\`; then :
+      else
+	$ECHO \"\$relink_command_output\" >&2
+	$RM \"\$progdir/\$file\"
+	exit 1
+      fi
+    fi
+
+    $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
+    { $RM \"\$progdir/\$program\";
+      $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; }
+    $RM \"\$progdir/\$file\"
+  fi"
+	else
+	  $ECHO "\
+  program=3D'$outputname'
+  progdir=3D\"\$thisdir/$objdir\"
+"
+	fi
+
+	$ECHO "\
+
+  if test -f \"\$progdir/\$program\"; then"
+
+	# fixup the dll searchpath if we need to.
+	#
+	# Fix the DLL searchpath if we need to.  Do this before prepending
+	# to shlibpath, because on Windows, both are PATH and uninstalled
+	# libraries must come first.
+	if test -n "$dllsearchpath"; then
+	  $ECHO "\
+    # Add the dll search path components to the executable PATH
+    PATH=3D$dllsearchpath:\$PATH
+"
+	fi
+
+	# Export our shlibpath_var if we have one.
+	if test "$shlibpath_overrides_runpath" =3D yes && test -n "$shlibpath_var=
" && test -n "$temp_rpath"; then
+	  $ECHO "\
+    # Add our own library path to $shlibpath_var
+    $shlibpath_var=3D\"$temp_rpath\$$shlibpath_var\"
+
+    # Some systems cannot cope with colon-terminated $shlibpath_var
+    # The second colon is a workaround for a bug in BeOS R4 sed
+    $shlibpath_var=3D\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\`
+
+    export $shlibpath_var
+"
+	fi
+
+	$ECHO "\
+    if test \"\$libtool_execute_magic\" !=3D \"$magic\"; then
+      # Run the actual program with our arguments.
+      func_exec_program \${1+\"\$@\"}
+    fi
+  else
+    # The program doesn't exist.
+    \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
+    \$ECHO \"This script is just a wrapper for \$program.\" 1>&2
+    \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2
+    exit 1
   fi
-
-  # Change the help message to a mode-specific one.
-  generic_help=3D"$help"
-  help=3D"Try \`$modename --help --mode=3D$mode' for more information."
-
-  # These modes are in order of execution frequency so that they run quick=
ly.
-  case $mode in
-  # libtool compile mode
-  compile)
-    modename=3D"$modename: compile"
-    # Get the compilation command and the source file.
-    base_compile=3D
-    srcfile=3D"$nonopt"  #  always keep a non-empty value in "srcfile"
-    suppress_opt=3Dyes
-    suppress_output=3D
-    arg_mode=3Dnormal
-    libobj=3D
-    later=3D
-
-    for arg
-    do
-      case $arg_mode in
-      arg  )
-	# do not "continue".  Instead, add this to base_compile
-	lastarg=3D"$arg"
-	arg_mode=3Dnormal
-	;;
-
-      target )
-	libobj=3D"$arg"
-	arg_mode=3Dnormal
-	continue
-	;;
-
-      normal )
-	# Accept any command-line options.
-	case $arg in
-	-o)
-	  if test -n "$libobj" ; then
-	    $echo "$modename: you cannot specify \`-o' more than once" 1>&2
-	    exit $EXIT_FAILURE
-	  fi
-	  arg_mode=3Dtarget
-	  continue
-	  ;;
-
-	-static | -prefer-pic | -prefer-non-pic)
-	  later=3D"$later $arg"
-	  continue
-	  ;;
-
-	-no-suppress)
-	  suppress_opt=3Dno
-	  continue
-	  ;;
-
-	-Xcompiler)
-	  arg_mode=3Darg  #  the next one goes into the "base_compile" arg list
-	  continue      #  The current "srcfile" will either be retained or
-	  ;;            #  replaced later.  I would guess that would be a bug.
-
-	-Wc,*)
-	  args=3D`$echo "X$arg" | $Xsed -e "s/^-Wc,//"`
-	  lastarg=3D
-	  save_ifs=3D"$IFS"; IFS=3D','
- 	  for arg in $args; do
-	    IFS=3D"$save_ifs"
-
-	    # Double-quote args containing other shell metacharacters.
-	    # Many Bourne shells cannot handle close brackets correctly
-	    # in scan sets, so we specify it separately.
-	    case $arg in
-	      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	      arg=3D"\"$arg\""
-	      ;;
+fi\
+"
+}
+
+
+# func_emit_cwrapperexe_src
+# emit the source code for a wrapper executable on stdout
+# Must ONLY be called from within func_mode_link because
+# it depends on a number of variable set therein.
+func_emit_cwrapperexe_src ()
+{
+	cat <<EOF
+
+/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
+   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
+
+   The $output program cannot be directly executed until all the libtool
+   libraries that it depends on are installed.
+
+   This wrapper executable should never be moved out of the build director=
y.
+   If it is, it will not operate correctly.
+*/
+EOF
+	    cat <<"EOF"
+#ifdef _MSC_VER
+# define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef _MSC_VER
+# include <direct.h>
+# include <process.h>
+# include <io.h>
+#else
+# include <unistd.h>
+# include <stdint.h>
+# ifdef __CYGWIN__
+#  include <io.h>
+# endif
+#endif
+#include <malloc.h>
+#include <stdarg.h>
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+/* declarations of non-ANSI functions */
+#if defined(__MINGW32__)
+# ifdef __STRICT_ANSI__
+int _putenv (const char *);
+# endif
+#elif defined(__CYGWIN__)
+# ifdef __STRICT_ANSI__
+char *realpath (const char *, char *);
+int putenv (char *);
+int setenv (const char *, const char *, int);
+# endif
+/* #elif defined (other platforms) ... */
+#endif
+
+/* portability defines, excluding path handling macros */
+#if defined(_MSC_VER)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+# define S_IXUSR _S_IEXEC
+# ifndef _INTPTR_T_DEFINED
+#  define _INTPTR_T_DEFINED
+#  define intptr_t int
+# endif
+#elif defined(__MINGW32__)
+# define setmode _setmode
+# define stat    _stat
+# define chmod   _chmod
+# define getcwd  _getcwd
+# define putenv  _putenv
+#elif defined(__CYGWIN__)
+# define HAVE_SETENV
+# define FOPEN_WB "wb"
+/* #elif defined (other platforms) ... */
+#endif
+
+#if defined(PATH_MAX)
+# define LT_PATHMAX PATH_MAX
+#elif defined(MAXPATHLEN)
+# define LT_PATHMAX MAXPATHLEN
+#else
+# define LT_PATHMAX 1024
+#endif
+
+#ifndef S_IXOTH
+# define S_IXOTH 0
+#endif
+#ifndef S_IXGRP
+# define S_IXGRP 0
+#endif
+
+/* path handling portability macros */
+#ifndef DIR_SEPARATOR
+# define DIR_SEPARATOR '/'
+# define PATH_SEPARATOR ':'
+#endif
+
+#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
+  defined (__OS2__)
+# define HAVE_DOS_BASED_FILE_SYSTEM
+# define FOPEN_WB "wb"
+# ifndef DIR_SEPARATOR_2
+#  define DIR_SEPARATOR_2 '\\'
+# endif
+# ifndef PATH_SEPARATOR_2
+#  define PATH_SEPARATOR_2 ';'
+# endif
+#endif
+
+#ifndef DIR_SEPARATOR_2
+# define IS_DIR_SEPARATOR(ch) ((ch) =3D=3D DIR_SEPARATOR)
+#else /* DIR_SEPARATOR_2 */
+# define IS_DIR_SEPARATOR(ch) \
+	(((ch) =3D=3D DIR_SEPARATOR) || ((ch) =3D=3D DIR_SEPARATOR_2))
+#endif /* DIR_SEPARATOR_2 */
+
+#ifndef PATH_SEPARATOR_2
+# define IS_PATH_SEPARATOR(ch) ((ch) =3D=3D PATH_SEPARATOR)
+#else /* PATH_SEPARATOR_2 */
+# define IS_PATH_SEPARATOR(ch) ((ch) =3D=3D PATH_SEPARATOR_2)
+#endif /* PATH_SEPARATOR_2 */
+
+#ifndef FOPEN_WB
+# define FOPEN_WB "w"
+#endif
+#ifndef _O_BINARY
+# define _O_BINARY 0
+#endif
+
+#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
+#define XFREE(stale) do { \
+  if (stale) { free ((void *) stale); stale =3D 0; } \
+} while (0)
+
+#if defined(LT_DEBUGWRAPPER)
+static int lt_debug =3D 1;
+#else
+static int lt_debug =3D 0;
+#endif
+
+const char *program_name =3D "libtool-wrapper"; /* in case xstrdup fails */
+
+void *xmalloc (size_t num);
+char *xstrdup (const char *string);
+const char *base_name (const char *name);
+char *find_executable (const char *wrapper);
+char *chase_symlinks (const char *pathspec);
+int make_executable (const char *path);
+int check_executable (const char *path);
+char *strendzap (char *str, const char *pat);
+void lt_debugprintf (const char *file, int line, const char *fmt, ...);
+void lt_fatal (const char *file, int line, const char *message, ...);
+static const char *nonnull (const char *s);
+static const char *nonempty (const char *s);
+void lt_setenv (const char *name, const char *value);
+char *lt_extend_str (const char *orig_value, const char *add, int to_end);
+void lt_update_exe_path (const char *name, const char *value);
+void lt_update_lib_path (const char *name, const char *value);
+char **prepare_spawn (char **argv);
+void lt_dump_script (FILE *f);
+EOF
+
+	    cat <<EOF
+volatile const char * MAGIC_EXE =3D "$magic_exe";
+const char * LIB_PATH_VARNAME =3D "$shlibpath_var";
+EOF
+
+	    if test "$shlibpath_overrides_runpath" =3D yes && test -n "$shlibpath=
_var" && test -n "$temp_rpath"; then
+              func_to_host_path "$temp_rpath"
+	      cat <<EOF
+const char * LIB_PATH_VALUE   =3D "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * LIB_PATH_VALUE   =3D "";
+EOF
+	    fi
+
+	    if test -n "$dllsearchpath"; then
+              func_to_host_path "$dllsearchpath:"
+	      cat <<EOF
+const char * EXE_PATH_VARNAME =3D "PATH";
+const char * EXE_PATH_VALUE   =3D "$func_to_host_path_result";
+EOF
+	    else
+	      cat <<"EOF"
+const char * EXE_PATH_VARNAME =3D "";
+const char * EXE_PATH_VALUE   =3D "";
+EOF
+	    fi
+
+	    if test "$fast_install" =3D yes; then
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME =3D "lt-$outputname"; /* hopefully, no .e=
xe */
+EOF
+	    else
+	      cat <<EOF
+const char * TARGET_PROGRAM_NAME =3D "$outputname"; /* hopefully, no .exe =
*/
+EOF
+	    fi
+
+
+	    cat <<"EOF"
+
+#define LTWRAPPER_OPTION_PREFIX         "--lt-"
+
+static const char *ltwrapper_option_prefix =3D LTWRAPPER_OPTION_PREFIX;
+static const char *dumpscript_opt       =3D LTWRAPPER_OPTION_PREFIX "dump-=
script";
+static const char *debug_opt            =3D LTWRAPPER_OPTION_PREFIX "debug=
";
+
+int
+main (int argc, char *argv[])
+{
+  char **newargz;
+  int  newargc;
+  char *tmp_pathspec;
+  char *actual_cwrapper_path;
+  char *actual_cwrapper_name;
+  char *target_name;
+  char *lt_argv_zero;
+  intptr_t rval =3D 127;
+
+  int i;
+
+  program_name =3D (char *) xstrdup (base_name (argv[0]));
+  newargz =3D XMALLOC (char *, argc + 1);
+
+  /* very simple arg parsing; don't want to rely on getopt
+   * also, copy all non cwrapper options to newargz, except
+   * argz[0], which is handled differently
+   */
+  newargc=3D0;
+  for (i =3D 1; i < argc; i++)
+    {
+      if (strcmp (argv[i], dumpscript_opt) =3D=3D 0)
+	{
+EOF
+	    case "$host" in
+	      *mingw* | *cygwin* )
+		# make stdout use "unix" line endings
+		echo "          setmode(1,_O_BINARY);"
+		;;
+	      esac
+
+	    cat <<"EOF"
+	  lt_dump_script (stdout);
+	  return 0;
+	}
+      if (strcmp (argv[i], debug_opt) =3D=3D 0)
+	{
+          lt_debug =3D 1;
+          continue;
+	}
+      if (strcmp (argv[i], ltwrapper_option_prefix) =3D=3D 0)
+        {
+          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX
+             namespace, but it is not one of the ones we know about and
+             have already dealt with, above (inluding dump-script), then
+             report an error. Otherwise, targets might begin to believe
+             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX
+             namespace. The first time any user complains about this, we'll
+             need to make LTWRAPPER_OPTION_PREFIX a configure-time option
+             or a configure.ac-settable value.
+           */
+          lt_fatal (__FILE__, __LINE__,
+		    "unrecognized %s option: '%s'",
+                    ltwrapper_option_prefix, argv[i]);
+        }
+      /* otherwise ... */
+      newargz[++newargc] =3D xstrdup (argv[i]);
+    }
+  newargz[++newargc] =3D NULL;
+
+EOF
+	    cat <<EOF
+  /* The GNU banner must be the first non-error debug message */
+  lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMES=
TAMP) $VERSION\n");
+EOF
+	    cat <<"EOF"
+  lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program=
_name);
+
+  tmp_pathspec =3D find_executable (argv[0]);
+  if (tmp_pathspec =3D=3D NULL)
+    lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (before symlink chase) at: %s\n",
+		  tmp_pathspec);
+
+  actual_cwrapper_path =3D chase_symlinks (tmp_pathspec);
+  lt_debugprintf (__FILE__, __LINE__,
+                  "(main) found exe (after symlink chase) at: %s\n",
+		  actual_cwrapper_path);
+  XFREE (tmp_pathspec);
+
+  actual_cwrapper_name =3D xstrdup (base_name (actual_cwrapper_path));
+  strendzap (actual_cwrapper_path, actual_cwrapper_name);
+
+  /* wrapper name transforms */
+  strendzap (actual_cwrapper_name, ".exe");
+  tmp_pathspec =3D lt_extend_str (actual_cwrapper_name, ".exe", 1);
+  XFREE (actual_cwrapper_name);
+  actual_cwrapper_name =3D tmp_pathspec;
+  tmp_pathspec =3D 0;
+
+  /* target_name transforms -- use actual target program name; might have =
lt- prefix */
+  target_name =3D xstrdup (base_name (TARGET_PROGRAM_NAME));
+  strendzap (target_name, ".exe");
+  tmp_pathspec =3D lt_extend_str (target_name, ".exe", 1);
+  XFREE (target_name);
+  target_name =3D tmp_pathspec;
+  tmp_pathspec =3D 0;
+
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(main) libtool target name: %s\n",
+		  target_name);
+EOF
+
+	    cat <<EOF
+  newargz[0] =3D
+    XMALLOC (char, (strlen (actual_cwrapper_path) +
+		    strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1));
+  strcpy (newargz[0], actual_cwrapper_path);
+  strcat (newargz[0], "$objdir");
+  strcat (newargz[0], "/");
+EOF
+
+	    cat <<"EOF"
+  /* stop here, and copy so we don't have to do this twice */
+  tmp_pathspec =3D xstrdup (newargz[0]);
+
+  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */
+  strcat (newargz[0], actual_cwrapper_name);
+
+  /* DO want the lt- prefix here if it exists, so use target_name */
+  lt_argv_zero =3D lt_extend_str (tmp_pathspec, target_name, 1);
+  XFREE (tmp_pathspec);
+  tmp_pathspec =3D NULL;
+EOF
+
+	    case $host_os in
+	      mingw*)
+	    cat <<"EOF"
+  {
+    char* p;
+    while ((p =3D strchr (newargz[0], '\\')) !=3D NULL)
+      {
+	*p =3D '/';
+      }
+    while ((p =3D strchr (lt_argv_zero, '\\')) !=3D NULL)
+      {
+	*p =3D '/';
+      }
+  }
+EOF
+	    ;;
 	    esac
-	    lastarg=3D"$lastarg $arg"
-	  done
-	  IFS=3D"$save_ifs"
-	  lastarg=3D`$echo "X$lastarg" | $Xsed -e "s/^ //"`
-
-	  # Add the arguments to base_compile.
-	  base_compile=3D"$base_compile $lastarg"
-	  continue
-	  ;;
-
-	* )
-	  # Accept the current argument as the source file.
-	  # The previous "srcfile" becomes the current argument.
-	  #
-	  lastarg=3D"$srcfile"
-	  srcfile=3D"$arg"
-	  ;;
-	esac  #  case $arg
-	;;
-      esac    #  case $arg_mode
-
-      # Aesthetically quote the previous argument.
-      lastarg=3D`$echo "X$lastarg" | $Xsed -e "$sed_quote_subst"`
-
-      case $lastarg in
-      # Double-quote args containing other shell metacharacters.
-      # Many Bourne shells cannot handle close brackets correctly
-      # in scan sets, and some SunOS ksh mistreat backslash-escaping
-      # in scan sets (worked around with variable expansion),
-      # and furthermore cannot handle '|' '&' '(' ')' in scan sets=20
-      # at all, so we specify them separately.
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	lastarg=3D"\"$lastarg\""
-	;;
-      esac
-
-      base_compile=3D"$base_compile $lastarg"
-    done # for arg
-
-    case $arg_mode in
-    arg)
-      $echo "$modename: you must specify an argument for -Xcompile"
-      exit $EXIT_FAILURE
-      ;;
-    target)
-      $echo "$modename: you must specify a target with \`-o'" 1>&2
-      exit $EXIT_FAILURE
-      ;;
-    *)
-      # Get the name of the library object.
-      [ -z "$libobj" ] && libobj=3D`$echo "X$srcfile" | $Xsed -e 's%^.*/%%=
'`
-      ;;
+
+	    cat <<"EOF"
+  XFREE (target_name);
+  XFREE (actual_cwrapper_path);
+  XFREE (actual_cwrapper_name);
+
+  lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */
+  lt_setenv ("DUALCASE", "1");  /* for MSK sh */
+  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must
+     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpa=
th)
+     because on Windows, both *_VARNAMEs are PATH but uninstalled
+     libraries must come first. */
+  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);
+  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);
+
+  lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n",
+		  nonnull (lt_argv_zero));
+  for (i =3D 0; i < newargc; i++)
+    {
+      lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n",
+		      i, nonnull (newargz[i]));
+    }
+
+EOF
+
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+  /* execv doesn't actually work on mingw as expected on unix */
+  newargz =3D prepare_spawn (newargz);
+  rval =3D _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);
+  if (rval =3D=3D -1)
+    {
+      /* failed to start process */
+      lt_debugprintf (__FILE__, __LINE__,
+		      "(main) failed to launch target \"%s\": %s\n",
+		      lt_argv_zero, nonnull (strerror (errno)));
+      return 127;
+    }
+  return rval;
+EOF
+		;;
+	      *)
+		cat <<"EOF"
+  execv (lt_argv_zero, newargz);
+  return rval; /* =3D127, but avoids unused variable warning */
+EOF
+		;;
+	    esac
+
+	    cat <<"EOF"
+}
+
+void *
+xmalloc (size_t num)
+{
+  void *p =3D (void *) malloc (num);
+  if (!p)
+    lt_fatal (__FILE__, __LINE__, "memory exhausted");
+
+  return p;
+}
+
+char *
+xstrdup (const char *string)
+{
+  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),
+			  string) : NULL;
+}
+
+const char *
+base_name (const char *name)
+{
+  const char *base;
+
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  /* Skip over the disk name in MSDOS pathnames. */
+  if (isalpha ((unsigned char) name[0]) && name[1] =3D=3D ':')
+    name +=3D 2;
+#endif
+
+  for (base =3D name; *name; name++)
+    if (IS_DIR_SEPARATOR (*name))
+      base =3D name + 1;
+  return base;
+}
+
+int
+check_executable (const char *path)
+{
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if ((stat (path, &st) >=3D 0)
+      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
+    return 1;
+  else
+    return 0;
+}
+
+int
+make_executable (const char *path)
+{
+  int rval =3D 0;
+  struct stat st;
+
+  lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n",
+                  nonempty (path));
+  if ((!path) || (!*path))
+    return 0;
+
+  if (stat (path, &st) >=3D 0)
+    {
+      rval =3D chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);
+    }
+  return rval;
+}
+
+/* Searches for the full path of the wrapper.  Returns
+   newly allocated full path name if found, NULL otherwise
+   Does not chase symlinks, even on platforms that support them.
+*/
+char *
+find_executable (const char *wrapper)
+{
+  int has_slash =3D 0;
+  const char *p;
+  const char *p_next;
+  /* static buffer for getcwd */
+  char tmp[LT_PATHMAX + 1];
+  int tmp_len;
+  char *concat_name;
+
+  lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n",
+                  nonempty (wrapper));
+
+  if ((wrapper =3D=3D NULL) || (*wrapper =3D=3D '\0'))
+    return NULL;
+
+  /* Absolute path? */
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] =3D=3D ':')
+    {
+      concat_name =3D xstrdup (wrapper);
+      if (check_executable (concat_name))
+	return concat_name;
+      XFREE (concat_name);
+    }
+  else
+    {
+#endif
+      if (IS_DIR_SEPARATOR (wrapper[0]))
+	{
+	  concat_name =3D xstrdup (wrapper);
+	  if (check_executable (concat_name))
+	    return concat_name;
+	  XFREE (concat_name);
+	}
+#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
+    }
+#endif
+
+  for (p =3D wrapper; *p; p++)
+    if (*p =3D=3D '/')
+      {
+	has_slash =3D 1;
+	break;
+      }
+  if (!has_slash)
+    {
+      /* no slashes; search PATH */
+      const char *path =3D getenv ("PATH");
+      if (path !=3D NULL)
+	{
+	  for (p =3D path; *p; p =3D p_next)
+	    {
+	      const char *q;
+	      size_t p_len;
+	      for (q =3D p; *q; q++)
+		if (IS_PATH_SEPARATOR (*q))
+		  break;
+	      p_len =3D q - p;
+	      p_next =3D (*q =3D=3D '\0' ? q : q + 1);
+	      if (p_len =3D=3D 0)
+		{
+		  /* empty path: current directory */
+		  if (getcwd (tmp, LT_PATHMAX) =3D=3D NULL)
+		    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+                              nonnull (strerror (errno)));
+		  tmp_len =3D strlen (tmp);
+		  concat_name =3D
+		    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, tmp, tmp_len);
+		  concat_name[tmp_len] =3D '/';
+		  strcpy (concat_name + tmp_len + 1, wrapper);
+		}
+	      else
+		{
+		  concat_name =3D
+		    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);
+		  memcpy (concat_name, p, p_len);
+		  concat_name[p_len] =3D '/';
+		  strcpy (concat_name + p_len + 1, wrapper);
+		}
+	      if (check_executable (concat_name))
+		return concat_name;
+	      XFREE (concat_name);
+	    }
+	}
+      /* not found in PATH; assume curdir */
+    }
+  /* Relative path | not found in path: prepend cwd */
+  if (getcwd (tmp, LT_PATHMAX) =3D=3D NULL)
+    lt_fatal (__FILE__, __LINE__, "getcwd failed: %s",
+              nonnull (strerror (errno)));
+  tmp_len =3D strlen (tmp);
+  concat_name =3D XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);
+  memcpy (concat_name, tmp, tmp_len);
+  concat_name[tmp_len] =3D '/';
+  strcpy (concat_name + tmp_len + 1, wrapper);
+
+  if (check_executable (concat_name))
+    return concat_name;
+  XFREE (concat_name);
+  return NULL;
+}
+
+char *
+chase_symlinks (const char *pathspec)
+{
+#ifndef S_ISLNK
+  return xstrdup (pathspec);
+#else
+  char buf[LT_PATHMAX];
+  struct stat s;
+  char *tmp_pathspec =3D xstrdup (pathspec);
+  char *p;
+  int has_symlinks =3D 0;
+  while (strlen (tmp_pathspec) && !has_symlinks)
+    {
+      lt_debugprintf (__FILE__, __LINE__,
+		      "checking path component for symlinks: %s\n",
+		      tmp_pathspec);
+      if (lstat (tmp_pathspec, &s) =3D=3D 0)
+	{
+	  if (S_ISLNK (s.st_mode) !=3D 0)
+	    {
+	      has_symlinks =3D 1;
+	      break;
+	    }
+
+	  /* search backwards for last DIR_SEPARATOR */
+	  p =3D tmp_pathspec + strlen (tmp_pathspec) - 1;
+	  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    p--;
+	  if ((p =3D=3D tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))
+	    {
+	      /* no more DIR_SEPARATORS left */
+	      break;
+	    }
+	  *p =3D '\0';
+	}
+      else
+	{
+	  lt_fatal (__FILE__, __LINE__,
+		    "error accessing file \"%s\": %s",
+		    tmp_pathspec, nonnull (strerror (errno)));
+	}
+    }
+  XFREE (tmp_pathspec);
+
+  if (!has_symlinks)
+    {
+      return xstrdup (pathspec);
+    }
+
+  tmp_pathspec =3D realpath (pathspec, buf);
+  if (tmp_pathspec =3D=3D 0)
+    {
+      lt_fatal (__FILE__, __LINE__,
+		"could not follow symlinks for %s", pathspec);
+    }
+  return xstrdup (tmp_pathspec);
+#endif
+}
+
+char *
+strendzap (char *str, const char *pat)
+{
+  size_t len, patlen;
+
+  assert (str !=3D NULL);
+  assert (pat !=3D NULL);
+
+  len =3D strlen (str);
+  patlen =3D strlen (pat);
+
+  if (patlen <=3D len)
+    {
+      str +=3D len - patlen;
+      if (strcmp (str, pat) =3D=3D 0)
+	*str =3D '\0';
+    }
+  return str;
+}
+
+void
+lt_debugprintf (const char *file, int line, const char *fmt, ...)
+{
+  va_list args;
+  if (lt_debug)
+    {
+      (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line);
+      va_start (args, fmt);
+      (void) vfprintf (stderr, fmt, args);
+      va_end (args);
+    }
+}
+
+static void
+lt_error_core (int exit_status, const char *file,
+	       int line, const char *mode,
+	       const char *message, va_list ap)
+{
+  fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode);
+  vfprintf (stderr, message, ap);
+  fprintf (stderr, ".\n");
+
+  if (exit_status >=3D 0)
+    exit (exit_status);
+}
+
+void
+lt_fatal (const char *file, int line, const char *message, ...)
+{
+  va_list ap;
+  va_start (ap, message);
+  lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap);
+  va_end (ap);
+}
+
+static const char *
+nonnull (const char *s)
+{
+  return s ? s : "(null)";
+}
+
+static const char *
+nonempty (const char *s)
+{
+  return (s && !*s) ? "(empty)" : nonnull (s);
+}
+
+void
+lt_setenv (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_setenv) setting '%s' to '%s'\n",
+                  nonnull (name), nonnull (value));
+  {
+#ifdef HAVE_SETENV
+    /* always make a copy, for consistency with !HAVE_SETENV */
+    char *str =3D xstrdup (value);
+    setenv (name, str, 1);
+#else
+    int len =3D strlen (name) + 1 + strlen (value) + 1;
+    char *str =3D XMALLOC (char, len);
+    sprintf (str, "%s=3D%s", name, value);
+    if (putenv (str) !=3D EXIT_SUCCESS)
+      {
+        XFREE (str);
+      }
+#endif
+  }
+}
+
+char *
+lt_extend_str (const char *orig_value, const char *add, int to_end)
+{
+  char *new_value;
+  if (orig_value && *orig_value)
+    {
+      int orig_value_len =3D strlen (orig_value);
+      int add_len =3D strlen (add);
+      new_value =3D XMALLOC (char, add_len + orig_value_len + 1);
+      if (to_end)
+        {
+          strcpy (new_value, orig_value);
+          strcpy (new_value + orig_value_len, add);
+        }
+      else
+        {
+          strcpy (new_value, add);
+          strcpy (new_value + add_len, orig_value);
+        }
+    }
+  else
+    {
+      new_value =3D xstrdup (add);
+    }
+  return new_value;
+}
+
+void
+lt_update_exe_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_exe_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value =3D lt_extend_str (getenv (name), value, 0);
+      /* some systems can't cope with a ':'-terminated path #' */
+      int len =3D strlen (new_value);
+      while (((len =3D strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_=
value[len-1]))
+        {
+          new_value[len-1] =3D '\0';
+        }
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+void
+lt_update_lib_path (const char *name, const char *value)
+{
+  lt_debugprintf (__FILE__, __LINE__,
+		  "(lt_update_lib_path) modifying '%s' by prepending '%s'\n",
+                  nonnull (name), nonnull (value));
+
+  if (name && *name && value && *value)
+    {
+      char *new_value =3D lt_extend_str (getenv (name), value, 0);
+      lt_setenv (name, new_value);
+      XFREE (new_value);
+    }
+}
+
+EOF
+	    case $host_os in
+	      mingw*)
+		cat <<"EOF"
+
+/* Prepares an argument vector before calling spawn().
+   Note that spawn() does not by itself call the command interpreter
+     (getenv ("COMSPEC") !=3D NULL ? getenv ("COMSPEC") :
+      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize =3D sizeof(OSVERSIONINFO);
+         GetVersionEx(&v);
+         v.dwPlatformId =3D=3D VER_PLATFORM_WIN32_NT;
+      }) ? "cmd.exe" : "command.com").
+   Instead it simply concatenates the arguments, separated by ' ', and cal=
ls
+   CreateProcess().  We must quote the arguments since Win32 CreateProcess=
()
+   interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') i=
n a
+   special way:
+   - Space and tab are interpreted as delimiters. They are not treated as
+     delimiters if they are surrounded by double quotes: "...".
+   - Unescaped double quotes are removed from the input. Their only effect=
 is
+     that within double quotes, space and tab are treated like normal
+     characters.
+   - Backslashes not followed by double quotes are not special.
+   - But 2*n+1 backslashes followed by a double quote become
+     n backslashes followed by a double quote (n >=3D 0):
+       \" -> "
+       \\\" -> \"
+       \\\\\" -> \\"
+ */
+#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012=
\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\03=
5\036\037"
+#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\0=
14\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\=
037"
+char **
+prepare_spawn (char **argv)
+{
+  size_t argc;
+  char **new_argv;
+  size_t i;
+
+  /* Count number of arguments.  */
+  for (argc =3D 0; argv[argc] !=3D NULL; argc++)
+    ;
+
+  /* Allocate new argument vector.  */
+  new_argv =3D XMALLOC (char *, argc + 1);
+
+  /* Put quoted arguments into the new argument vector.  */
+  for (i =3D 0; i < argc; i++)
+    {
+      const char *string =3D argv[i];
+
+      if (string[0] =3D=3D '\0')
+	new_argv[i] =3D xstrdup ("\"\"");
+      else if (strpbrk (string, SHELL_SPECIAL_CHARS) !=3D NULL)
+	{
+	  int quote_around =3D (strpbrk (string, SHELL_SPACE_CHARS) !=3D NULL);
+	  size_t length;
+	  unsigned int backslashes;
+	  const char *s;
+	  char *quoted_string;
+	  char *p;
+
+	  length =3D 0;
+	  backslashes =3D 0;
+	  if (quote_around)
+	    length++;
+	  for (s =3D string; *s !=3D '\0'; s++)
+	    {
+	      char c =3D *s;
+	      if (c =3D=3D '"')
+		length +=3D backslashes + 1;
+	      length++;
+	      if (c =3D=3D '\\')
+		backslashes++;
+	      else
+		backslashes =3D 0;
+	    }
+	  if (quote_around)
+	    length +=3D backslashes + 1;
+
+	  quoted_string =3D XMALLOC (char, length + 1);
+
+	  p =3D quoted_string;
+	  backslashes =3D 0;
+	  if (quote_around)
+	    *p++ =3D '"';
+	  for (s =3D string; *s !=3D '\0'; s++)
+	    {
+	      char c =3D *s;
+	      if (c =3D=3D '"')
+		{
+		  unsigned int j;
+		  for (j =3D backslashes + 1; j > 0; j--)
+		    *p++ =3D '\\';
+		}
+	      *p++ =3D c;
+	      if (c =3D=3D '\\')
+		backslashes++;
+	      else
+		backslashes =3D 0;
+	    }
+	  if (quote_around)
+	    {
+	      unsigned int j;
+	      for (j =3D backslashes; j > 0; j--)
+		*p++ =3D '\\';
+	      *p++ =3D '"';
+	    }
+	  *p =3D '\0';
+
+	  new_argv[i] =3D quoted_string;
+	}
+      else
+	new_argv[i] =3D (char *) string;
+    }
+  new_argv[argc] =3D NULL;
+
+  return new_argv;
+}
+EOF
+		;;
+	    esac
+
+            cat <<"EOF"
+void lt_dump_script (FILE* f)
+{
+EOF
+	    func_emit_wrapper yes |
+              $SED -e 's/\([\\"]\)/\\\1/g' \
+	           -e 's/^/  fputs ("/' -e 's/$/\\n", f);/'
+
+            cat <<"EOF"
+}
+EOF
+}
+# end: func_emit_cwrapperexe_src
+
+# func_win32_import_lib_p ARG
+# True if ARG is an import lib, as indicated by $file_magic_cmd
+func_win32_import_lib_p ()
+{
+    $opt_debug
+    case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in
+    *import*) : ;;
+    *) false ;;
     esac
-
-    # Recognize several different file suffixes.
-    # If the user specifies -o file.o, it is replaced with file.lo
-    xform=3D'[cCFSifmso]'
-    case $libobj in
-    *.ada) xform=3Dada ;;
-    *.adb) xform=3Dadb ;;
-    *.ads) xform=3Dads ;;
-    *.asm) xform=3Dasm ;;
-    *.c++) xform=3Dc++ ;;
-    *.cc) xform=3Dcc ;;
-    *.ii) xform=3Dii ;;
-    *.class) xform=3Dclass ;;
-    *.cpp) xform=3Dcpp ;;
-    *.cxx) xform=3Dcxx ;;
-    *.f90) xform=3Df90 ;;
-    *.for) xform=3Dfor ;;
-    *.java) xform=3Djava ;;
-    esac
-
-    libobj=3D`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"`
-
-    case $libobj in
-    *.lo) obj=3D`$echo "X$libobj" | $Xsed -e "$lo2o"` ;;
-    *)
-      $echo "$modename: cannot determine name of library object from \`$li=
bobj'" 1>&2
-      exit $EXIT_FAILURE
-      ;;
-    esac
-
-    func_infer_tag $base_compile
-
-    for arg in $later; do
-      case $arg in
-      -static)
-	build_old_libs=3Dyes
-	continue
-	;;
-
-      -prefer-pic)
-	pic_mode=3Dyes
-	continue
-	;;
-
-      -prefer-non-pic)
-	pic_mode=3Dno
-	continue
-	;;
-      esac
-    done
-
-    qlibobj=3D`$echo "X$libobj" | $Xsed -e "$sed_quote_subst"`
-    case $qlibobj in
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	qlibobj=3D"\"$qlibobj\"" ;;
-    esac
-    test "X$libobj" !=3D "X$qlibobj" \
-	&& $echo "X$libobj" | grep '[]~#^*{};<>?"'"'"' 	&()|`$[]' \
-	&& $echo "$modename: libobj name \`$libobj' may not contain shell special=
 characters."
-    objname=3D`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
-    xdir=3D`$echo "X$obj" | $Xsed -e 's%/[^/]*$%%'`
-    if test "X$xdir" =3D "X$obj"; then
-      xdir=3D
-    else
-      xdir=3D$xdir/
-    fi
-    lobj=3D${xdir}$objdir/$objname
-
-    if test -z "$base_compile"; then
-      $echo "$modename: you must specify a compilation command" 1>&2
-      $echo "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
-
-    # Delete any leftover library objects.
-    if test "$build_old_libs" =3D yes; then
-      removelist=3D"$obj $lobj $libobj ${libobj}T"
-    else
-      removelist=3D"$lobj $libobj ${libobj}T"
-    fi
-
-    $run $rm $removelist
-    trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
-
-    # On Cygwin there's no "real" PIC flag so we must build both object ty=
pes
-    case $host_os in
-    cygwin* | mingw* | pw32* | os2*)
-      pic_mode=3Ddefault
-      ;;
-    esac
-    if test "$pic_mode" =3D no && test "$deplibs_check_method" !=3D pass_a=
ll; then
-      # non-PIC code in shared libraries is not supported
-      pic_mode=3Ddefault
-    fi
-
-    # Calculate the filename of the output object if compiler does
-    # not support -o with -c
-    if test "$compiler_c_o" =3D no; then
-      output_obj=3D`$echo "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$=
%%'`.${objext}
-      lockfile=3D"$output_obj.lock"
-      removelist=3D"$removelist $output_obj $lockfile"
-      trap "$run $rm $removelist; exit $EXIT_FAILURE" 1 2 15
-    else
-      output_obj=3D
-      need_locks=3Dno
-      lockfile=3D
-    fi
-
-    # Lock this critical section if it is needed
-    # We use this script file to make the link, it avoids creating a new f=
ile
-    if test "$need_locks" =3D yes; then
-      until $run ln "$progpath" "$lockfile" 2>/dev/null; do
-	$show "Waiting for $lockfile to be removed"
-	sleep 2
-      done
-    elif test "$need_locks" =3D warn; then
-      if test -f "$lockfile"; then
-	$echo "\
-*** ERROR, $lockfile exists and contains:
-`cat $lockfile 2>/dev/null`
-
-This indicates that another process is trying to use the same
-temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
-repeat this compilation, it may succeed, by chance, but you had better
-avoid parallel builds (make -j) in this platform, or get a better
-compiler."
-
-	$run $rm $removelist
-	exit $EXIT_FAILURE
-      fi
-      $echo "$srcfile" > "$lockfile"
-    fi
-
-    if test -n "$fix_srcfile_path"; then
-      eval srcfile=3D\"$fix_srcfile_path\"
-    fi
-    qsrcfile=3D`$echo "X$srcfile" | $Xsed -e "$sed_quote_subst"`
-    case $qsrcfile in
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-      qsrcfile=3D"\"$qsrcfile\"" ;;
-    esac
-
-    $run $rm "$libobj" "${libobj}T"
-
-    # Create a libtool object file (analogous to a ".la" file),
-    # but don't create it if we're doing a dry run.
-    test -z "$run" && cat > ${libobj}T <<EOF
-# $libobj - a libtool object file
-# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
-#
-# Please DO NOT delete this file!
-# It is necessary for linking the library.
-
-# Name of the PIC object.
-EOF
-
-    # Only build a PIC object if we are building libtool libraries.
-    if test "$build_libtool_libs" =3D yes; then
-      # Without this assignment, base_compile gets emptied.
-      fbsd_hideous_sh_bug=3D$base_compile
-
-      if test "$pic_mode" !=3D no; then
-	command=3D"$base_compile $qsrcfile $pic_flag"
-      else
-	# Don't build PIC code
-	command=3D"$base_compile $qsrcfile"
-      fi
-
-      if test ! -d "${xdir}$objdir"; then
-	$show "$mkdir ${xdir}$objdir"
-	$run $mkdir ${xdir}$objdir
-	exit_status=3D$?
-	if test "$exit_status" -ne 0 && test ! -d "${xdir}$objdir"; then
-	  exit $exit_status
-	fi
-      fi
-
-      if test -z "$output_obj"; then
-	# Place PIC objects in $objdir
-	command=3D"$command -o $lobj"
-      fi
-
-      $run $rm "$lobj" "$output_obj"
-
-      $show "$command"
-      if $run eval "$command"; then :
-      else
-	test -n "$output_obj" && $run $rm $removelist
-	exit $EXIT_FAILURE
-      fi
-
-      if test "$need_locks" =3D warn &&
-	 test "X`cat $lockfile 2>/dev/null`" !=3D "X$srcfile"; then
-	$echo "\
-*** ERROR, $lockfile contains:
-`cat $lockfile 2>/dev/null`
-
-but it should contain:
-$srcfile
-
-This indicates that another process is trying to use the same
-temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
-repeat this compilation, it may succeed, by chance, but you had better
-avoid parallel builds (make -j) in this platform, or get a better
-compiler."
-
-	$run $rm $removelist
-	exit $EXIT_FAILURE
-      fi
-
-      # Just move the object if needed, then go on to compile the next one
-      if test -n "$output_obj" && test "X$output_obj" !=3D "X$lobj"; then
-	$show "$mv $output_obj $lobj"
-	if $run $mv $output_obj $lobj; then :
-	else
-	  error=3D$?
-	  $run $rm $removelist
-	  exit $error
-	fi
-      fi
-
-      # Append the name of the PIC object to the libtool object file.
-      test -z "$run" && cat >> ${libobj}T <<EOF
-pic_object=3D'$objdir/$objname'
-
-EOF
-
-      # Allow error messages only from the first compilation.
-      if test "$suppress_opt" =3D yes; then
-        suppress_output=3D' >/dev/null 2>&1'
-      fi
-    else
-      # No PIC object so indicate it doesn't exist in the libtool
-      # object file.
-      test -z "$run" && cat >> ${libobj}T <<EOF
-pic_object=3Dnone
-
-EOF
-    fi
-
-    # Only build a position-dependent object if we build old libraries.
-    if test "$build_old_libs" =3D yes; then
-      if test "$pic_mode" !=3D yes; then
-	# Don't build PIC code
-	command=3D"$base_compile $qsrcfile"
-      else
-	command=3D"$base_compile $qsrcfile $pic_flag"
-      fi
-      if test "$compiler_c_o" =3D yes; then
-	command=3D"$command -o $obj"
-      fi
-
-      # Suppress compiler output if we already did a PIC compilation.
-      command=3D"$command$suppress_output"
-      $run $rm "$obj" "$output_obj"
-      $show "$command"
-      if $run eval "$command"; then :
-      else
-	$run $rm $removelist
-	exit $EXIT_FAILURE
-      fi
-
-      if test "$need_locks" =3D warn &&
-	 test "X`cat $lockfile 2>/dev/null`" !=3D "X$srcfile"; then
-	$echo "\
-*** ERROR, $lockfile contains:
-`cat $lockfile 2>/dev/null`
-
-but it should contain:
-$srcfile
-
-This indicates that another process is trying to use the same
-temporary object file, and libtool could not work around it because
-your compiler does not support \`-c' and \`-o' together.  If you
-repeat this compilation, it may succeed, by chance, but you had better
-avoid parallel builds (make -j) in this platform, or get a better
-compiler."
-
-	$run $rm $removelist
-	exit $EXIT_FAILURE
-      fi
-
-      # Just move the object if needed
-      if test -n "$output_obj" && test "X$output_obj" !=3D "X$obj"; then
-	$show "$mv $output_obj $obj"
-	if $run $mv $output_obj $obj; then :
-	else
-	  error=3D$?
-	  $run $rm $removelist
-	  exit $error
-	fi
-      fi
-
-      # Append the name of the non-PIC object the libtool object file.
-      # Only append if the libtool object file exists.
-      test -z "$run" && cat >> ${libobj}T <<EOF
-# Name of the non-PIC object.
-non_pic_object=3D'$objname'
-
-EOF
-    else
-      # Append the name of the non-PIC object the libtool object file.
-      # Only append if the libtool object file exists.
-      test -z "$run" && cat >> ${libobj}T <<EOF
-# Name of the non-PIC object.
-non_pic_object=3Dnone
-
-EOF
-    fi
-
-    $run $mv "${libobj}T" "${libobj}"
-
-    # Unlock the critical section if it was locked
-    if test "$need_locks" !=3D no; then
-      $run $rm "$lockfile"
-    fi
-
-    exit $EXIT_SUCCESS
-    ;;
-
-  # libtool link mode
-  link | relink)
-    modename=3D"$modename: link"
+}
+
+# func_mode_link arg...
+func_mode_link ()
+{
+    $opt_debug
     case $host in
-    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
       # It is impossible to link a dll without this setting, and
       # we shouldn't force the makefile maintainer to figure out
       # which system we are compiling for in order to pass an extra
@@ -1084,10 +5100,10 @@
       allow_undefined=3Dyes
       ;;
     esac
-    libtool_args=3D"$nonopt"
+    libtool_args=3D$nonopt
     base_compile=3D"$nonopt $@"
-    compile_command=3D"$nonopt"
-    finalize_command=3D"$nonopt"
+    compile_command=3D$nonopt
+    finalize_command=3D$nonopt
=20
     compile_rpath=3D
     finalize_rpath=3D
@@ -1102,8 +5118,10 @@
     dllsearchpath=3D
     lib_search_path=3D`pwd`
     inst_prefix_dir=3D
+    new_inherited_linker_flags=3D
=20
     avoid_version=3Dno
+    bindir=3D
     dlfiles=3D
     dlprefiles=3D
     dlself=3Dno
@@ -1117,7 +5135,6 @@
     no_install=3Dno
     objs=3D
     non_pic_objects=3D
-    notinst_path=3D # paths that contain not-installed libtool libraries
     precious_files_regex=3D
     prefer_static_libs=3Dno
     preload=3Dno
@@ -1131,28 +5148,44 @@
     thread_safe=3Dno
     vinfo=3D
     vinfo_number=3Dno
-
+    weak_libs=3D
+    single_module=3D"${wl}-single_module"
     func_infer_tag $base_compile
=20
     # We need to know -static, to get the right output filenames.
     for arg
     do
       case $arg in
-      -all-static | -static)
-	if test "X$arg" =3D "X-all-static"; then
+      -shared)
+	test "$build_libtool_libs" !=3D yes && \
+	  func_fatal_configuration "can not build a shared library"
+	build_old_libs=3Dno
+	break
+	;;
+      -all-static | -static | -static-libtool-libs)
+	case $arg in
+	-all-static)
 	  if test "$build_libtool_libs" =3D yes && test -z "$link_static_flag"; t=
hen
-	    $echo "$modename: warning: complete static linking is impossible in t=
his configuration" 1>&2
+	    func_warning "complete static linking is impossible in this configura=
tion"
 	  fi
 	  if test -n "$link_static_flag"; then
 	    dlopen_self=3D$dlopen_self_static
 	  fi
 	  prefer_static_libs=3Dyes
-	else
+	  ;;
+	-static)
 	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
 	    dlopen_self=3D$dlopen_self_static
 	  fi
 	  prefer_static_libs=3Dbuilt
-	fi
+	  ;;
+	-static-libtool-libs)
+	  if test -z "$pic_flag" && test -n "$link_static_flag"; then
+	    dlopen_self=3D$dlopen_self_static
+	  fi
+	  prefer_static_libs=3Dyes
+	  ;;
+	esac
 	build_libtool_libs=3Dno
 	build_old_libs=3Dyes
 	break
@@ -1167,29 +5200,30 @@
     while test "$#" -gt 0; do
       arg=3D"$1"
       shift
-      case $arg in
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	qarg=3D\"`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`\" ### testsuite: s=
kip nested quoting test
-	;;
-      *) qarg=3D$arg ;;
-      esac
-      libtool_args=3D"$libtool_args $qarg"
+      func_quote_for_eval "$arg"
+      qarg=3D$func_quote_for_eval_unquoted_result
+      func_append libtool_args " $func_quote_for_eval_result"
=20
       # If the previous option needs an argument, assign it.
       if test -n "$prev"; then
 	case $prev in
 	output)
-	  compile_command=3D"$compile_command @OUTPUT@"
-	  finalize_command=3D"$finalize_command @OUTPUT@"
+	  func_append compile_command " @OUTPUT@"
+	  func_append finalize_command " @OUTPUT@"
 	  ;;
 	esac
=20
 	case $prev in
+	bindir)
+	  bindir=3D"$arg"
+	  prev=3D
+	  continue
+	  ;;
 	dlfiles|dlprefiles)
 	  if test "$preload" =3D no; then
 	    # Add the symbol object into the linking commands.
-	    compile_command=3D"$compile_command @SYMFILE@"
-	    finalize_command=3D"$finalize_command @SYMFILE@"
+	    func_append compile_command " @SYMFILE@"
+	    func_append finalize_command " @SYMFILE@"
 	    preload=3Dyes
 	  fi
 	  case $arg in
@@ -1216,9 +5250,9 @@
 	    ;;
 	  *)
 	    if test "$prev" =3D dlfiles; then
-	      dlfiles=3D"$dlfiles $arg"
+	      func_append dlfiles " $arg"
 	    else
-	      dlprefiles=3D"$dlprefiles $arg"
+	      func_append dlprefiles " $arg"
 	    fi
 	    prev=3D
 	    continue
@@ -1227,10 +5261,8 @@
 	  ;;
 	expsyms)
 	  export_symbols=3D"$arg"
-	  if test ! -f "$arg"; then
-	    $echo "$modename: symbol file \`$arg' does not exist"
-	    exit $EXIT_FAILURE
-	  fi
+	  test -f "$arg" \
+	    || func_fatal_error "symbol file \`$arg' does not exist"
 	  prev=3D
 	  continue
 	  ;;
@@ -1239,11 +5271,120 @@
 	  prev=3D
 	  continue
 	  ;;
+	framework)
+	  case $host in
+	    *-*-darwin*)
+	      case "$deplibs " in
+		*" $qarg.ltframework "*) ;;
+		*) func_append deplibs " $qarg.ltframework" # this is fixed later
+		   ;;
+	      esac
+	      ;;
+	  esac
+	  prev=3D
+	  continue
+	  ;;
 	inst_prefix)
 	  inst_prefix_dir=3D"$arg"
 	  prev=3D
 	  continue
 	  ;;
+	objectlist)
+	  if test -f "$arg"; then
+	    save_arg=3D$arg
+	    moreargs=3D
+	    for fil in `cat "$save_arg"`
+	    do
+#	      func_append moreargs " $fil"
+	      arg=3D$fil
+	      # A libtool-controlled object.
+
+	      # Check to see that this really is a libtool object.
+	      if func_lalib_unsafe_p "$arg"; then
+		pic_object=3D
+		non_pic_object=3D
+
+		# Read the .lo file
+		func_source "$arg"
+
+		if test -z "$pic_object" ||
+		   test -z "$non_pic_object" ||
+		   test "$pic_object" =3D none &&
+		   test "$non_pic_object" =3D none; then
+		  func_fatal_error "cannot find name of object for \`$arg'"
+		fi
+
+		# Extract subdirectory from the argument.
+		func_dirname "$arg" "/" ""
+		xdir=3D"$func_dirname_result"
+
+		if test "$pic_object" !=3D none; then
+		  # Prepend the subdirectory the object is found in.
+		  pic_object=3D"$xdir$pic_object"
+
+		  if test "$prev" =3D dlfiles; then
+		    if test "$build_libtool_libs" =3D yes && test "$dlopen_support" =3D =
yes; then
+		      func_append dlfiles " $pic_object"
+		      prev=3D
+		      continue
+		    else
+		      # If libtool objects are unsupported, then we need to preload.
+		      prev=3Ddlprefiles
+		    fi
+		  fi
+
+		  # CHECK ME:  I think I busted this.  -Ossama
+		  if test "$prev" =3D dlprefiles; then
+		    # Preload the old-style object.
+		    func_append dlprefiles " $pic_object"
+		    prev=3D
+		  fi
+
+		  # A PIC object.
+		  func_append libobjs " $pic_object"
+		  arg=3D"$pic_object"
+		fi
+
+		# Non-PIC object.
+		if test "$non_pic_object" !=3D none; then
+		  # Prepend the subdirectory the object is found in.
+		  non_pic_object=3D"$xdir$non_pic_object"
+
+		  # A standard non-PIC object
+		  func_append non_pic_objects " $non_pic_object"
+		  if test -z "$pic_object" || test "$pic_object" =3D none ; then
+		    arg=3D"$non_pic_object"
+		  fi
+		else
+		  # If the PIC object exists, use it instead.
+		  # $xdir was prepended to $pic_object above.
+		  non_pic_object=3D"$pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+		fi
+	      else
+		# Only an error if not doing a dry-run.
+		if $opt_dry_run; then
+		  # Extract subdirectory from the argument.
+		  func_dirname "$arg" "/" ""
+		  xdir=3D"$func_dirname_result"
+
+		  func_lo2o "$arg"
+		  pic_object=3D$xdir$objdir/$func_lo2o_result
+		  non_pic_object=3D$xdir$func_lo2o_result
+		  func_append libobjs " $pic_object"
+		  func_append non_pic_objects " $non_pic_object"
+	        else
+		  func_fatal_error "\`$arg' is not a valid libtool object"
+		fi
+	      fi
+	    done
+	  else
+	    func_fatal_error "link input file \`$arg' does not exist"
+	  fi
+	  arg=3D$save_arg
+	  prev=3D
+	  continue
+	  ;;
 	precious_regex)
 	  precious_files_regex=3D"$arg"
 	  prev=3D
@@ -1254,174 +5395,59 @@
 	  prev=3D
 	  continue
 	  ;;
-	objectlist)
-	  if test -f "$arg"; then
-	    save_arg=3D$arg
-	    moreargs=3D
-	    for fil in `cat $save_arg`
-	    do
-#	      moreargs=3D"$moreargs $fil"
-	      arg=3D$fil
-	      # A libtool-controlled object.
-
-	      # Check to see that this really is a libtool object.
-	      if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/=
null 2>&1; then
-		pic_object=3D
-		non_pic_object=3D
-
-		# Read the .lo file
-		# If there is no directory component, then add one.
-		case $arg in
-		*/* | *\\*) . $arg ;;
-		*) . ./$arg ;;
-		esac
-
-		if test -z "$pic_object" || \
-		   test -z "$non_pic_object" ||
-		   test "$pic_object" =3D none && \
-		   test "$non_pic_object" =3D none; then
-		  $echo "$modename: cannot find name of object for \`$arg'" 1>&2
-		  exit $EXIT_FAILURE
-		fi
-
-		# Extract subdirectory from the argument.
-		xdir=3D`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
-		if test "X$xdir" =3D "X$arg"; then
-		  xdir=3D
-		else
-		  xdir=3D"$xdir/"
-		fi
-
-		if test "$pic_object" !=3D none; then
-		  # Prepend the subdirectory the object is found in.
-		  pic_object=3D"$xdir$pic_object"
-
-		  if test "$prev" =3D dlfiles; then
-		    if test "$build_libtool_libs" =3D yes && test "$dlopen_support" =3D =
yes; then
-		      dlfiles=3D"$dlfiles $pic_object"
-		      prev=3D
-		      continue
-		    else
-		      # If libtool objects are unsupported, then we need to preload.
-		      prev=3Ddlprefiles
-		    fi
-		  fi
-
-		  # CHECK ME:  I think I busted this.  -Ossama
-		  if test "$prev" =3D dlprefiles; then
-		    # Preload the old-style object.
-		    dlprefiles=3D"$dlprefiles $pic_object"
-		    prev=3D
-		  fi
-
-		  # A PIC object.
-		  libobjs=3D"$libobjs $pic_object"
-		  arg=3D"$pic_object"
-		fi
-
-		# Non-PIC object.
-		if test "$non_pic_object" !=3D none; then
-		  # Prepend the subdirectory the object is found in.
-		  non_pic_object=3D"$xdir$non_pic_object"
-
-		  # A standard non-PIC object
-		  non_pic_objects=3D"$non_pic_objects $non_pic_object"
-		  if test -z "$pic_object" || test "$pic_object" =3D none ; then
-		    arg=3D"$non_pic_object"
-		  fi
-		else
-		  # If the PIC object exists, use it instead.
-		  # $xdir was prepended to $pic_object above.
-		  non_pic_object=3D"$pic_object"
-		  non_pic_objects=3D"$non_pic_objects $non_pic_object"
-		fi
-	      else
-		# Only an error if not doing a dry-run.
-		if test -z "$run"; then
-		  $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
-		  exit $EXIT_FAILURE
-		else
-		  # Dry-run case.
-
-		  # Extract subdirectory from the argument.
-		  xdir=3D`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
-		  if test "X$xdir" =3D "X$arg"; then
-		    xdir=3D
-		  else
-		    xdir=3D"$xdir/"
-		  fi
-
-		  pic_object=3D`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
-		  non_pic_object=3D`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
-		  libobjs=3D"$libobjs $pic_object"
-		  non_pic_objects=3D"$non_pic_objects $non_pic_object"
-		fi
-	      fi
-	    done
-	  else
-	    $echo "$modename: link input file \`$save_arg' does not exist"
-	    exit $EXIT_FAILURE
-	  fi
-	  arg=3D$save_arg
-	  prev=3D
-	  continue
-	  ;;
 	rpath | xrpath)
 	  # We need an absolute path.
 	  case $arg in
 	  [\\/]* | [A-Za-z]:[\\/]*) ;;
 	  *)
-	    $echo "$modename: only absolute run-paths are allowed" 1>&2
-	    exit $EXIT_FAILURE
+	    func_fatal_error "only absolute run-paths are allowed"
 	    ;;
 	  esac
 	  if test "$prev" =3D rpath; then
 	    case "$rpath " in
 	    *" $arg "*) ;;
-	    *) rpath=3D"$rpath $arg" ;;
+	    *) func_append rpath " $arg" ;;
 	    esac
 	  else
 	    case "$xrpath " in
 	    *" $arg "*) ;;
-	    *) xrpath=3D"$xrpath $arg" ;;
+	    *) func_append xrpath " $arg" ;;
 	    esac
 	  fi
 	  prev=3D
 	  continue
 	  ;;
+	shrext)
+	  shrext_cmds=3D"$arg"
+	  prev=3D
+	  continue
+	  ;;
+	weak)
+	  func_append weak_libs " $arg"
+	  prev=3D
+	  continue
+	  ;;
+	xcclinker)
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $qarg"
+	  prev=3D
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
+	  continue
+	  ;;
 	xcompiler)
-	  compiler_flags=3D"$compiler_flags $qarg"
+	  func_append compiler_flags " $qarg"
 	  prev=3D
-	  compile_command=3D"$compile_command $qarg"
-	  finalize_command=3D"$finalize_command $qarg"
+	  func_append compile_command " $qarg"
+	  func_append finalize_command " $qarg"
 	  continue
 	  ;;
 	xlinker)
-	  linker_flags=3D"$linker_flags $qarg"
-	  compiler_flags=3D"$compiler_flags $wl$qarg"
+	  func_append linker_flags " $qarg"
+	  func_append compiler_flags " $wl$qarg"
 	  prev=3D
-	  compile_command=3D"$compile_command $wl$qarg"
-	  finalize_command=3D"$finalize_command $wl$qarg"
-	  continue
-	  ;;
-	xcclinker)
-	  linker_flags=3D"$linker_flags $qarg"
-	  compiler_flags=3D"$compiler_flags $qarg"
-	  prev=3D
-	  compile_command=3D"$compile_command $qarg"
-	  finalize_command=3D"$finalize_command $qarg"
-	  continue
-	  ;;
-	shrext)
-  	  shrext_cmds=3D"$arg"
-	  prev=3D
-	  continue
-	  ;;
-	darwin_framework|darwin_framework_skip)
-	  test "$prev" =3D "darwin_framework" && compiler_flags=3D"$compiler_flag=
s $arg"
-	  compile_command=3D"$compile_command $arg"
-	  finalize_command=3D"$finalize_command $arg"
-	  prev=3D
+	  func_append compile_command " $wl$qarg"
+	  func_append finalize_command " $wl$qarg"
 	  continue
 	  ;;
 	*)
@@ -1437,16 +5463,16 @@
       case $arg in
       -all-static)
 	if test -n "$link_static_flag"; then
-	  compile_command=3D"$compile_command $link_static_flag"
-	  finalize_command=3D"$finalize_command $link_static_flag"
+	  # See comment for -static flag below, for more details.
+	  func_append compile_command " $link_static_flag"
+	  func_append finalize_command " $link_static_flag"
 	fi
 	continue
 	;;
=20
       -allow-undefined)
 	# FIXME: remove this flag sometime in the future.
-	$echo "$modename: \`-allow-undefined' is deprecated because it is the def=
ault" 1>&2
-	continue
+	func_fatal_error "\`-allow-undefined' must not be used because it is the =
default"
 	;;
=20
       -avoid-version)
@@ -1454,6 +5480,11 @@
 	continue
 	;;
=20
+      -bindir)
+	prev=3Dbindir
+	continue
+	;;
+
       -dlopen)
 	prev=3Ddlfiles
 	continue
@@ -1471,8 +5502,7 @@
=20
       -export-symbols | -export-symbols-regex)
 	if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
-	  $echo "$modename: more than one -exported-symbols argument is not allow=
ed"
-	  exit $EXIT_FAILURE
+	  func_fatal_error "more than one -exported-symbols argument is not allow=
ed"
 	fi
 	if test "X$arg" =3D "X-export-symbols"; then
 	  prev=3Dexpsyms
@@ -1482,15 +5512,8 @@
 	continue
 	;;
=20
-      -framework|-arch|-isysroot)
-	case " $CC " in
-	  *" ${arg} ${1} "* | *" ${arg}	${1} "*)=20
-		prev=3Ddarwin_framework_skip ;;
-	  *) compiler_flags=3D"$compiler_flags $arg"
-	     prev=3Ddarwin_framework ;;
-	esac
-	compile_command=3D"$compile_command $arg"
-	finalize_command=3D"$finalize_command $arg"
+      -framework)
+	prev=3Dframework
 	continue
 	;;
=20
@@ -1504,45 +5527,59 @@
       -L[A-Z][A-Z]*:*)
 	case $with_gcc/$host in
 	no/*-*-irix* | /*-*-irix*)
-	  compile_command=3D"$compile_command $arg"
-	  finalize_command=3D"$finalize_command $arg"
+	  func_append compile_command " $arg"
+	  func_append finalize_command " $arg"
 	  ;;
 	esac
 	continue
 	;;
=20
       -L*)
-	dir=3D`$echo "X$arg" | $Xsed -e 's/^-L//'`
+	func_stripname "-L" '' "$arg"
+	if test -z "$func_stripname_result"; then
+	  if test "$#" -gt 0; then
+	    func_fatal_error "require no space between \`-L' and \`$1'"
+	  else
+	    func_fatal_error "need path for \`-L' option"
+	  fi
+	fi
+	func_resolve_sysroot "$func_stripname_result"
+	dir=3D$func_resolve_sysroot_result
 	# We need an absolute path.
 	case $dir in
 	[\\/]* | [A-Za-z]:[\\/]*) ;;
 	*)
 	  absdir=3D`cd "$dir" && pwd`
-	  if test -z "$absdir"; then
-	    $echo "$modename: cannot determine absolute directory name of \`$dir'=
" 1>&2
-	    absdir=3D"$dir"
-	    notinst_path=3D"$notinst_path $dir"
-	  fi
+	  test -z "$absdir" && \
+	    func_fatal_error "cannot determine absolute directory name of \`$dir'"
 	  dir=3D"$absdir"
 	  ;;
 	esac
 	case "$deplibs " in
-	*" -L$dir "*) ;;
+	*" -L$dir "* | *" $arg "*)
+	  # Will only happen for absolute or sysroot arguments
+	  ;;
 	*)
-	  deplibs=3D"$deplibs -L$dir"
-	  lib_search_path=3D"$lib_search_path $dir"
+	  # Preserve sysroot, but never include relative directories
+	  case $dir in
+	    [\\/]* | [A-Za-z]:[\\/]* | =3D*) func_append deplibs " $arg" ;;
+	    *) func_append deplibs " -L$dir" ;;
+	  esac
+	  func_append lib_search_path " $dir"
 	  ;;
 	esac
 	case $host in
-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
-	  testbindir=3D`$echo "X$dir" | $Xsed -e 's*/lib$*/bin*'`
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=3D`$ECHO "$dir" | $SED 's*/lib$*/bin*'`
 	  case :$dllsearchpath: in
 	  *":$dir:"*) ;;
-	  *) dllsearchpath=3D"$dllsearchpath:$dir";;
+	  ::) dllsearchpath=3D$dir;;
+	  *) func_append dllsearchpath ":$dir";;
 	  esac
 	  case :$dllsearchpath: in
 	  *":$testbindir:"*) ;;
-	  *) dllsearchpath=3D"$dllsearchpath:$testbindir";;
+	  ::) dllsearchpath=3D$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
 	  esac
 	  ;;
 	esac
@@ -1552,7 +5589,7 @@
       -l*)
 	if test "X$arg" =3D "X-lc" || test "X$arg" =3D "X-lm"; then
 	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*)
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku=
*)
 	    # These systems don't actually have a C or math library (as such)
 	    continue
 	    ;;
@@ -1566,7 +5603,7 @@
 	    ;;
 	  *-*-rhapsody* | *-*-darwin1.[012])
 	    # Rhapsody C and math libraries are in the System framework
-	    deplibs=3D"$deplibs -framework System"
+	    func_append deplibs " System.ltframework"
 	    continue
 	    ;;
 	  *-*-sco3.2v5* | *-*-sco5v6*)
@@ -1586,24 +5623,7 @@
 	   ;;
 	 esac
 	fi
-	deplibs=3D"$deplibs $arg"
-	continue
-	;;
-
-      # Tru64 UNIX uses -model [arg] to determine the layout of C++
-      # classes, name mangling, and exception handling.
-      -model)
-	compile_command=3D"$compile_command $arg"
-	compiler_flags=3D"$compiler_flags $arg"
-	finalize_command=3D"$finalize_command $arg"
-	prev=3Dxcompiler
-	continue
-	;;
-
-     -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
-	compiler_flags=3D"$compiler_flags $arg"
-	compile_command=3D"$compile_command $arg"
-	finalize_command=3D"$finalize_command $arg"
+	func_append deplibs " $arg"
 	continue
 	;;
=20
@@ -1612,35 +5632,30 @@
 	continue
 	;;
=20
-      # -64, -mips[0-9] enable 64-bit mode on the SGI compiler
-      # -r[0-9][0-9]* specifies the processor on the SGI compiler
-      # -xarch=3D*, -xtarget=3D* enable 64-bit mode on the Sun compiler
-      # +DA*, +DD* enable 64-bit mode on the HP compiler
-      # -q* pass through compiler args for the IBM compiler
-      # -m* pass through architecture-specific compiler args for GCC
-      # -m*, -t[45]*, -txscale* pass through architecture-specific
-      # compiler args for GCC
-      # -pg pass through profiling flag for GCC
-      # @file GCC response files
-      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=3D*|-xtarget=3D*|+DA*|+DD*|-q*|-=
m*|-pg| \
-      -t[45]*|-txscale*|@*)
-
-	# Unknown arguments in both finalize_command and compile_command need
-	# to be aesthetically quoted because they are evaled later.
-	arg=3D`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
-	case $arg in
-	*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	  arg=3D"\"$arg\""
-	  ;;
+      # Tru64 UNIX uses -model [arg] to determine the layout of C++
+      # classes, name mangling, and exception handling.
+      # Darwin uses the -arch flag to determine output architecture.
+      -model|-arch|-isysroot|--sysroot)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	prev=3Dxcompiler
+	continue
+	;;
+
+      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-th=
reads)
+	func_append compiler_flags " $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
+	case "$new_inherited_linker_flags " in
+	    *" $arg "*) ;;
+	    * ) func_append new_inherited_linker_flags " $arg" ;;
 	esac
-        compile_command=3D"$compile_command $arg"
-        finalize_command=3D"$finalize_command $arg"
-        compiler_flags=3D"$compiler_flags $arg"
-        continue
-        ;;
-
-      -shrext)
-	prev=3Dshrext
+	continue
+	;;
+
+      -multi_module)
+	single_module=3D"${wl}-multi_module"
 	continue
 	;;
=20
@@ -1651,11 +5666,11 @@
=20
       -no-install)
 	case $host in
-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)
 	  # The PATH hackery in wrapper scripts is required on Windows
-	  # in order for the loader to find any dlls it needs.
-	  $echo "$modename: warning: \`-no-install' is ignored for $host" 1>&2
-	  $echo "$modename: warning: assuming \`-no-fast-install' instead" 1>&2
+	  # and Darwin in order for the loader to find any dlls it needs.
+	  func_warning "\`-no-install' is ignored for $host"
+	  func_warning "assuming \`-no-fast-install' instead"
 	  fast_install=3Dno
 	  ;;
 	*) no_install=3Dyes ;;
@@ -1696,23 +5711,37 @@
 	;;
=20
       -R*)
-	dir=3D`$echo "X$arg" | $Xsed -e 's/^-R//'`
+	func_stripname '-R' '' "$arg"
+	dir=3D$func_stripname_result
 	# We need an absolute path.
 	case $dir in
 	[\\/]* | [A-Za-z]:[\\/]*) ;;
+	=3D*)
+	  func_stripname '=3D' '' "$dir"
+	  dir=3D$lt_sysroot$func_stripname_result
+	  ;;
 	*)
-	  $echo "$modename: only absolute run-paths are allowed" 1>&2
-	  exit $EXIT_FAILURE
+	  func_fatal_error "only absolute run-paths are allowed"
 	  ;;
 	esac
 	case "$xrpath " in
 	*" $dir "*) ;;
-	*) xrpath=3D"$xrpath $dir" ;;
+	*) func_append xrpath " $dir" ;;
 	esac
 	continue
 	;;
=20
-      -static)
+      -shared)
+	# The effects of -shared are defined in a previous loop.
+	continue
+	;;
+
+      -shrext)
+	prev=3Dshrext
+	continue
+	;;
+
+      -static | -static-libtool-libs)
 	# The effects of -static are defined in a previous loop.
 	# We used to do the same as -all-static on platforms that
 	# didn't have a PIC flag, but the assumption that the effects
@@ -1730,47 +5759,49 @@
 	prev=3Dvinfo
 	continue
 	;;
+
       -version-number)
 	prev=3Dvinfo
 	vinfo_number=3Dyes
 	continue
 	;;
=20
+      -weak)
+        prev=3Dweak
+	continue
+	;;
+
       -Wc,*)
-	args=3D`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wc,//'`
+	func_stripname '-Wc,' '' "$arg"
+	args=3D$func_stripname_result
 	arg=3D
 	save_ifs=3D"$IFS"; IFS=3D','
 	for flag in $args; do
 	  IFS=3D"$save_ifs"
-	  case $flag in
-	    *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	    flag=3D"\"$flag\""
-	    ;;
-	  esac
-	  arg=3D"$arg $wl$flag"
-	  compiler_flags=3D"$compiler_flags $flag"
+          func_quote_for_eval "$flag"
+	  func_append arg " $func_quote_for_eval_result"
+	  func_append compiler_flags " $func_quote_for_eval_result"
 	done
 	IFS=3D"$save_ifs"
-	arg=3D`$echo "X$arg" | $Xsed -e "s/^ //"`
+	func_stripname ' ' '' "$arg"
+	arg=3D$func_stripname_result
 	;;
=20
       -Wl,*)
-	args=3D`$echo "X$arg" | $Xsed -e "$sed_quote_subst" -e 's/^-Wl,//'`
+	func_stripname '-Wl,' '' "$arg"
+	args=3D$func_stripname_result
 	arg=3D
 	save_ifs=3D"$IFS"; IFS=3D','
 	for flag in $args; do
 	  IFS=3D"$save_ifs"
-	  case $flag in
-	    *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	    flag=3D"\"$flag\""
-	    ;;
-	  esac
-	  arg=3D"$arg $wl$flag"
-	  compiler_flags=3D"$compiler_flags $wl$flag"
-	  linker_flags=3D"$linker_flags $flag"
+          func_quote_for_eval "$flag"
+	  func_append arg " $wl$func_quote_for_eval_result"
+	  func_append compiler_flags " $wl$func_quote_for_eval_result"
+	  func_append linker_flags " $func_quote_for_eval_result"
 	done
 	IFS=3D"$save_ifs"
-	arg=3D`$echo "X$arg" | $Xsed -e "s/^ //"`
+	func_stripname ' ' '' "$arg"
+	arg=3D$func_stripname_result
 	;;
=20
       -Xcompiler)
@@ -1788,53 +5819,68 @@
 	continue
 	;;
=20
+      # -msg_* for osf cc
+      -msg_*)
+	func_quote_for_eval "$arg"
+	arg=3D"$func_quote_for_eval_result"
+	;;
+
+      # Flags to be passed through unchanged, with rationale:
+      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler
+      # -r[0-9][0-9]*        specify processor for the SGI compiler
+      # -xarch=3D*, -xtarget=3D* enable 64-bit mode for the Sun compiler
+      # +DA*, +DD*           enable 64-bit mode for the HP compiler
+      # -q*                  compiler args for the IBM compiler
+      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC
+      # -F/path              path to uninstalled frameworks, gcc on darwin
+      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC
+      # @file                GCC response files
+      # -tp=3D*                Portland pgcc target processor selection
+      # --sysroot=3D*          for sysroot support
+      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimizat=
ion
+      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=3D*|-xtarget=3D*|+DA*|+DD*|-q*|-=
m*| \
+      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=3D*|--sys=
root=3D*| \
+      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)
+        func_quote_for_eval "$arg"
+	arg=3D"$func_quote_for_eval_result"
+        func_append compile_command " $arg"
+        func_append finalize_command " $arg"
+        func_append compiler_flags " $arg"
+        continue
+        ;;
+
       # Some other compiler flag.
       -* | +*)
-	# Unknown arguments in both finalize_command and compile_command need
-	# to be aesthetically quoted because they are evaled later.
-	arg=3D`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
-	case $arg in
-	*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	  arg=3D"\"$arg\""
-	  ;;
-	esac
+        func_quote_for_eval "$arg"
+	arg=3D"$func_quote_for_eval_result"
 	;;
=20
       *.$objext)
 	# A standard object.
-	objs=3D"$objs $arg"
+	func_append objs " $arg"
 	;;
=20
       *.lo)
 	# A libtool-controlled object.
=20
 	# Check to see that this really is a libtool object.
-	if (${SED} -e '2q' $arg | grep "^# Generated by .*$PACKAGE") >/dev/null 2=
>&1; then
+	if func_lalib_unsafe_p "$arg"; then
 	  pic_object=3D
 	  non_pic_object=3D
=20
 	  # Read the .lo file
-	  # If there is no directory component, then add one.
-	  case $arg in
-	  */* | *\\*) . $arg ;;
-	  *) . ./$arg ;;
-	  esac
-
-	  if test -z "$pic_object" || \
+	  func_source "$arg"
+
+	  if test -z "$pic_object" ||
 	     test -z "$non_pic_object" ||
-	     test "$pic_object" =3D none && \
+	     test "$pic_object" =3D none &&
 	     test "$non_pic_object" =3D none; then
-	    $echo "$modename: cannot find name of object for \`$arg'" 1>&2
-	    exit $EXIT_FAILURE
+	    func_fatal_error "cannot find name of object for \`$arg'"
 	  fi
=20
 	  # Extract subdirectory from the argument.
-	  xdir=3D`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
-	  if test "X$xdir" =3D "X$arg"; then
-	    xdir=3D
- 	  else
-	    xdir=3D"$xdir/"
-	  fi
+	  func_dirname "$arg" "/" ""
+	  xdir=3D"$func_dirname_result"
=20
 	  if test "$pic_object" !=3D none; then
 	    # Prepend the subdirectory the object is found in.
@@ -1842,7 +5888,7 @@
=20
 	    if test "$prev" =3D dlfiles; then
 	      if test "$build_libtool_libs" =3D yes && test "$dlopen_support" =3D=
 yes; then
-		dlfiles=3D"$dlfiles $pic_object"
+		func_append dlfiles " $pic_object"
 		prev=3D
 		continue
 	      else
@@ -1854,12 +5900,12 @@
 	    # CHECK ME:  I think I busted this.  -Ossama
 	    if test "$prev" =3D dlprefiles; then
 	      # Preload the old-style object.
-	      dlprefiles=3D"$dlprefiles $pic_object"
+	      func_append dlprefiles " $pic_object"
 	      prev=3D
 	    fi
=20
 	    # A PIC object.
-	    libobjs=3D"$libobjs $pic_object"
+	    func_append libobjs " $pic_object"
 	    arg=3D"$pic_object"
 	  fi
=20
@@ -1869,7 +5915,7 @@
 	    non_pic_object=3D"$xdir$non_pic_object"
=20
 	    # A standard non-PIC object
-	    non_pic_objects=3D"$non_pic_objects $non_pic_object"
+	    func_append non_pic_objects " $non_pic_object"
 	    if test -z "$pic_object" || test "$pic_object" =3D none ; then
 	      arg=3D"$non_pic_object"
 	    fi
@@ -1877,52 +5923,47 @@
 	    # If the PIC object exists, use it instead.
 	    # $xdir was prepended to $pic_object above.
 	    non_pic_object=3D"$pic_object"
-	    non_pic_objects=3D"$non_pic_objects $non_pic_object"
+	    func_append non_pic_objects " $non_pic_object"
 	  fi
 	else
 	  # Only an error if not doing a dry-run.
-	  if test -z "$run"; then
-	    $echo "$modename: \`$arg' is not a valid libtool object" 1>&2
-	    exit $EXIT_FAILURE
+	  if $opt_dry_run; then
+	    # Extract subdirectory from the argument.
+	    func_dirname "$arg" "/" ""
+	    xdir=3D"$func_dirname_result"
+
+	    func_lo2o "$arg"
+	    pic_object=3D$xdir$objdir/$func_lo2o_result
+	    non_pic_object=3D$xdir$func_lo2o_result
+	    func_append libobjs " $pic_object"
+	    func_append non_pic_objects " $non_pic_object"
 	  else
-	    # Dry-run case.
-
-	    # Extract subdirectory from the argument.
-	    xdir=3D`$echo "X$arg" | $Xsed -e 's%/[^/]*$%%'`
-	    if test "X$xdir" =3D "X$arg"; then
-	      xdir=3D
-	    else
-	      xdir=3D"$xdir/"
-	    fi
-
-	    pic_object=3D`$echo "X${xdir}${objdir}/${arg}" | $Xsed -e "$lo2o"`
-	    non_pic_object=3D`$echo "X${xdir}${arg}" | $Xsed -e "$lo2o"`
-	    libobjs=3D"$libobjs $pic_object"
-	    non_pic_objects=3D"$non_pic_objects $non_pic_object"
+	    func_fatal_error "\`$arg' is not a valid libtool object"
 	  fi
 	fi
 	;;
=20
       *.$libext)
 	# An archive.
-	deplibs=3D"$deplibs $arg"
-	old_deplibs=3D"$old_deplibs $arg"
+	func_append deplibs " $arg"
+	func_append old_deplibs " $arg"
 	continue
 	;;
=20
       *.la)
 	# A libtool-controlled library.
=20
+	func_resolve_sysroot "$arg"
 	if test "$prev" =3D dlfiles; then
 	  # This library was specified with -dlopen.
-	  dlfiles=3D"$dlfiles $arg"
+	  func_append dlfiles " $func_resolve_sysroot_result"
 	  prev=3D
 	elif test "$prev" =3D dlprefiles; then
 	  # The library was specified with -dlpreopen.
-	  dlprefiles=3D"$dlprefiles $arg"
+	  func_append dlprefiles " $func_resolve_sysroot_result"
 	  prev=3D
 	else
-	  deplibs=3D"$deplibs $arg"
+	  func_append deplibs " $func_resolve_sysroot_result"
 	fi
 	continue
 	;;
@@ -1931,70 +5972,53 @@
       *)
 	# Unknown arguments in both finalize_command and compile_command need
 	# to be aesthetically quoted because they are evaled later.
-	arg=3D`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
-	case $arg in
-	*[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	  arg=3D"\"$arg\""
-	  ;;
-	esac
+	func_quote_for_eval "$arg"
+	arg=3D"$func_quote_for_eval_result"
 	;;
       esac # arg
=20
       # Now actually substitute the argument into the commands.
       if test -n "$arg"; then
-	compile_command=3D"$compile_command $arg"
-	finalize_command=3D"$finalize_command $arg"
+	func_append compile_command " $arg"
+	func_append finalize_command " $arg"
       fi
     done # argument parsing loop
=20
-    if test -n "$prev"; then
-      $echo "$modename: the \`$prevarg' option requires an argument" 1>&2
-      $echo "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
+    test -n "$prev" && \
+      func_fatal_help "the \`$prevarg' option requires an argument"
=20
     if test "$export_dynamic" =3D yes && test -n "$export_dynamic_flag_spe=
c"; then
       eval arg=3D\"$export_dynamic_flag_spec\"
-      compile_command=3D"$compile_command $arg"
-      finalize_command=3D"$finalize_command $arg"
+      func_append compile_command " $arg"
+      func_append finalize_command " $arg"
     fi
=20
     oldlibs=3D
     # calculate the name of the file, without its directory
-    outputname=3D`$echo "X$output" | $Xsed -e 's%^.*/%%'`
+    func_basename "$output"
+    outputname=3D"$func_basename_result"
     libobjs_save=3D"$libobjs"
=20
     if test -n "$shlibpath_var"; then
       # get the directories listed in $shlibpath_var
-      eval shlib_search_path=3D\`\$echo \"X\${$shlibpath_var}\" \| \$Xsed =
-e \'s/:/ /g\'\`
+      eval shlib_search_path=3D\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'=
s/:/ /g\'\`
     else
       shlib_search_path=3D
     fi
     eval sys_lib_search_path=3D\"$sys_lib_search_path_spec\"
     eval sys_lib_dlsearch_path=3D\"$sys_lib_dlsearch_path_spec\"
=20
-    output_objdir=3D`$echo "X$output" | $Xsed -e 's%/[^/]*$%%'`
-    if test "X$output_objdir" =3D "X$output"; then
-      output_objdir=3D"$objdir"
-    else
-      output_objdir=3D"$output_objdir/$objdir"
-    fi
+    func_dirname "$output" "/" ""
+    output_objdir=3D"$func_dirname_result$objdir"
+    func_to_tool_file "$output_objdir/"
+    tool_output_objdir=3D$func_to_tool_file_result
     # Create the object directory.
-    if test ! -d "$output_objdir"; then
-      $show "$mkdir $output_objdir"
-      $run $mkdir $output_objdir
-      exit_status=3D$?
-      if test "$exit_status" -ne 0 && test ! -d "$output_objdir"; then
-	exit $exit_status
-      fi
-    fi
+    func_mkdir_p "$output_objdir"
=20
     # Determine the type of output
     case $output in
     "")
-      $echo "$modename: you must specify an output file" 1>&2
-      $echo "$help" 1>&2
-      exit $EXIT_FAILURE
+      func_fatal_help "you must specify an output file"
       ;;
     *.$libext) linkmode=3Doldlib ;;
     *.lo | *.$objext) linkmode=3Dobj ;;
@@ -2002,27 +6026,18 @@
     *) linkmode=3Dprog ;; # Anything else should be a program.
     esac
=20
-    case $host in
-    *cygwin* | *mingw* | *pw32*)
-      # don't eliminate duplications in $postdeps and $predeps
-      duplicate_compiler_generated_deps=3Dyes
-      ;;
-    *)
-      duplicate_compiler_generated_deps=3D$duplicate_deps
-      ;;
-    esac
     specialdeplibs=3D
=20
     libs=3D
     # Find all interdependent deplibs by searching for libraries
     # that are linked more than once (e.g. -la -lb -la)
     for deplib in $deplibs; do
-      if test "X$duplicate_deps" =3D "Xyes" ; then
+      if $opt_preserve_dup_deps ; then
 	case "$libs " in
-	*" $deplib "*) specialdeplibs=3D"$specialdeplibs $deplib" ;;
+	*" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	esac
       fi
-      libs=3D"$libs $deplib"
+      func_append libs " $deplib"
     done
=20
     if test "$linkmode" =3D lib; then
@@ -2032,12 +6047,12 @@
       # $postdeps and mark them as special (i.e., whose duplicates are
       # not to be eliminated).
       pre_post_deps=3D
-      if test "X$duplicate_compiler_generated_deps" =3D "Xyes" ; then
+      if $opt_duplicate_compiler_generated_deps; then
 	for pre_post_dep in $predeps $postdeps; do
 	  case "$pre_post_deps " in
-	  *" $pre_post_dep "*) specialdeplibs=3D"$specialdeplibs $pre_post_deps" =
;;
+	  *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;;
 	  esac
-	  pre_post_deps=3D"$pre_post_deps $pre_post_dep"
+	  func_append pre_post_deps " $pre_post_dep"
 	done
       fi
       pre_post_deps=3D
@@ -2048,15 +6063,16 @@
     newlib_search_path=3D
     need_relink=3Dno # whether we're linking any uninstalled libtool libra=
ries
     notinst_deplibs=3D # not-installed libtool libraries
+    notinst_path=3D # paths that contain not-installed libtool libraries
+
     case $linkmode in
     lib)
-	passes=3D"conv link"
+	passes=3D"conv dlpreopen link"
 	for file in $dlfiles $dlprefiles; do
 	  case $file in
 	  *.la) ;;
 	  *)
-	    $echo "$modename: libraries can \`-dlopen' only libtool libraries: $f=
ile" 1>&2
-	    exit $EXIT_FAILURE
+	    func_fatal_help "libraries can \`-dlopen' only libtool libraries: $fi=
le"
 	    ;;
 	  esac
 	done
@@ -2072,7 +6088,20 @@
     *)  passes=3D"conv"
 	;;
     esac
+
     for pass in $passes; do
+      # The preopen pass in lib mode reverses $deplibs; put it back here
+      # so that -L comes before libs that need it for instance...
+      if test "$linkmode,$pass" =3D "lib,link"; then
+	## FIXME: Find the place where the list is rebuilt in the wrong
+	##        order, and fix it there properly
+        tmp_deplibs=3D
+	for deplib in $deplibs; do
+	  tmp_deplibs=3D"$deplib $tmp_deplibs"
+	done
+	deplibs=3D"$tmp_deplibs"
+      fi
+
       if test "$linkmode,$pass" =3D "lib,link" ||
 	 test "$linkmode,$pass" =3D "prog,scan"; then
 	libs=3D"$deplibs"
@@ -2085,31 +6114,67 @@
 	link) libs=3D"$deplibs %DEPLIBS% $dependency_libs" ;;
 	esac
       fi
+      if test "$linkmode,$pass" =3D "lib,dlpreopen"; then
+	# Collect and forward deplibs of preopened libtool libs
+	for lib in $dlprefiles; do
+	  # Ignore non-libtool-libs
+	  dependency_libs=3D
+	  func_resolve_sysroot "$lib"
+	  case $lib in
+	  *.la)	func_source "$func_resolve_sysroot_result" ;;
+	  esac
+
+	  # Collect preopened libtool deplibs, except any this library
+	  # has declared as weak libs
+	  for deplib in $dependency_libs; do
+	    func_basename "$deplib"
+            deplib_base=3D$func_basename_result
+	    case " $weak_libs " in
+	    *" $deplib_base "*) ;;
+	    *) func_append deplibs " $deplib" ;;
+	    esac
+	  done
+	done
+	libs=3D"$dlprefiles"
+      fi
       if test "$pass" =3D dlopen; then
 	# Collect dlpreopened libraries
 	save_deplibs=3D"$deplibs"
 	deplibs=3D
       fi
+
       for deplib in $libs; do
 	lib=3D
 	found=3Dno
 	case $deplib in
-	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe)
+	-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)
 	  if test "$linkmode,$pass" =3D "prog,link"; then
 	    compile_deplibs=3D"$deplib $compile_deplibs"
 	    finalize_deplibs=3D"$deplib $finalize_deplibs"
 	  else
-	    compiler_flags=3D"$compiler_flags $deplib"
+	    func_append compiler_flags " $deplib"
+	    if test "$linkmode" =3D lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
 	  fi
 	  continue
 	  ;;
 	-l*)
 	  if test "$linkmode" !=3D lib && test "$linkmode" !=3D prog; then
-	    $echo "$modename: warning: \`-l' is ignored for archives/objects" 1>&2
+	    func_warning "\`-l' is ignored for archives/objects"
 	    continue
 	  fi
-	  name=3D`$echo "X$deplib" | $Xsed -e 's/^-l//'`
-	  for searchdir in $newlib_search_path $lib_search_path $sys_lib_search_p=
ath $shlib_search_path; do
+	  func_stripname '-l' '' "$deplib"
+	  name=3D$func_stripname_result
+	  if test "$linkmode" =3D lib; then
+	    searchdirs=3D"$newlib_search_path $lib_search_path $compiler_lib_sear=
ch_dirs $sys_lib_search_path $shlib_search_path"
+	  else
+	    searchdirs=3D"$newlib_search_path $lib_search_path $sys_lib_search_pa=
th $shlib_search_path"
+	  fi
+	  for searchdir in $searchdirs; do
 	    for search_ext in .la $std_shrext .so .a; do
 	      # Search the libtool library
 	      lib=3D"$searchdir/lib${name}${search_ext}"
@@ -2139,21 +6204,17 @@
 	    if test "X$allow_libtool_libs_with_static_runtimes" =3D "Xyes" ; then
 	      case " $predeps $postdeps " in
 	      *" $deplib "*)
-		if (${SED} -e '2q' $lib |
-                    grep "^# Generated by .*$PACKAGE") >/dev/null 2>&1; th=
en
+		if func_lalib_p "$lib"; then
 		  library_names=3D
 		  old_library=3D
-		  case $lib in
-		  */* | *\\*) . $lib ;;
-		  *) . ./$lib ;;
-		  esac
+		  func_source "$lib"
 		  for l in $old_library $library_names; do
 		    ll=3D"$l"
 		  done
 		  if test "X$ll" =3D "X$old_library" ; then # only static version availa=
ble
 		    found=3Dno
-		    ladir=3D`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
-		    test "X$ladir" =3D "X$lib" && ladir=3D"."
+		    func_dirname "$lib" "" "."
+		    ladir=3D"$func_dirname_result"
 		    lib=3D$ladir/$old_library
 		    if test "$linkmode,$pass" =3D "prog,link"; then
 		      compile_deplibs=3D"$deplib $compile_deplibs"
@@ -2165,19 +6226,36 @@
 		    continue
 		  fi
 		fi
-	        ;;
+		;;
 	      *) ;;
 	      esac
 	    fi
 	  fi
 	  ;; # -l
+	*.ltframework)
+	  if test "$linkmode,$pass" =3D "prog,link"; then
+	    compile_deplibs=3D"$deplib $compile_deplibs"
+	    finalize_deplibs=3D"$deplib $finalize_deplibs"
+	  else
+	    deplibs=3D"$deplib $deplibs"
+	    if test "$linkmode" =3D lib ; then
+		case "$new_inherited_linker_flags " in
+		    *" $deplib "*) ;;
+		    * ) func_append new_inherited_linker_flags " $deplib" ;;
+		esac
+	    fi
+	  fi
+	  continue
+	  ;;
 	-L*)
 	  case $linkmode in
 	  lib)
 	    deplibs=3D"$deplib $deplibs"
 	    test "$pass" =3D conv && continue
 	    newdependency_libs=3D"$deplib $newdependency_libs"
-	    newlib_search_path=3D"$newlib_search_path "`$echo "X$deplib" | $Xsed =
-e 's/^-L//'`
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  prog)
 	    if test "$pass" =3D conv; then
@@ -2190,27 +6268,34 @@
 	      compile_deplibs=3D"$deplib $compile_deplibs"
 	      finalize_deplibs=3D"$deplib $finalize_deplibs"
 	    fi
-	    newlib_search_path=3D"$newlib_search_path "`$echo "X$deplib" | $Xsed =
-e 's/^-L//'`
+	    func_stripname '-L' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    func_append newlib_search_path " $func_resolve_sysroot_result"
 	    ;;
 	  *)
-	    $echo "$modename: warning: \`-L' is ignored for archives/objects" 1>&2
+	    func_warning "\`-L' is ignored for archives/objects"
 	    ;;
 	  esac # linkmode
 	  continue
 	  ;; # -L
 	-R*)
 	  if test "$pass" =3D link; then
-	    dir=3D`$echo "X$deplib" | $Xsed -e 's/^-R//'`
+	    func_stripname '-R' '' "$deplib"
+	    func_resolve_sysroot "$func_stripname_result"
+	    dir=3D$func_resolve_sysroot_result
 	    # Make sure the xrpath contains only unique directories.
 	    case "$xrpath " in
 	    *" $dir "*) ;;
-	    *) xrpath=3D"$xrpath $dir" ;;
+	    *) func_append xrpath " $dir" ;;
 	    esac
 	  fi
 	  deplibs=3D"$deplib $deplibs"
 	  continue
 	  ;;
-	*.la) lib=3D"$deplib" ;;
+	*.la)
+	  func_resolve_sysroot "$deplib"
+	  lib=3D$func_resolve_sysroot_result
+	  ;;
 	*.$libext)
 	  if test "$pass" =3D conv; then
 	    deplibs=3D"$deplib $deplibs"
@@ -2218,35 +6303,41 @@
 	  fi
 	  case $linkmode in
 	  lib)
-	    valid_a_lib=3Dno
-	    case $deplibs_check_method in
-	      match_pattern*)
-		set dummy $deplibs_check_method
-	        match_pattern_regex=3D`expr "$deplibs_check_method" : "$2 \(.*\)"`
-		if eval $echo \"$deplib\" 2>/dev/null \
-		    | $SED 10q \
+	    # Linking convenience modules into shared libraries is allowed,
+	    # but linking other static libraries is non-portable.
+	    case " $dlpreconveniencelibs " in
+	    *" $deplib "*) ;;
+	    *)
+	      valid_a_lib=3Dno
+	      case $deplibs_check_method in
+		match_pattern*)
+		  set dummy $deplibs_check_method; shift
+		  match_pattern_regex=3D`expr "$deplibs_check_method" : "$1 \(.*\)"`
+		  if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \
 		    | $EGREP "$match_pattern_regex" > /dev/null; then
+		    valid_a_lib=3Dyes
+		  fi
+		;;
+		pass_all)
 		  valid_a_lib=3Dyes
-		fi
 		;;
-	      pass_all)
-		valid_a_lib=3Dyes
-		;;
-            esac
-	    if test "$valid_a_lib" !=3D yes; then
-	      $echo
-	      $echo "*** Warning: Trying to link with static lib archive $deplib."
-	      $echo "*** I have the capability to make that library automatically=
 link in when"
-	      $echo "*** you link to this library.  But I can only do this if you=
 have a"
-	      $echo "*** shared version of the library, which you do not appear t=
o have"
-	      $echo "*** because the file extensions .$libext of this argument ma=
kes me believe"
-	      $echo "*** that it is just a static archive that I should not used =
here."
-	    else
-	      $echo
-	      $echo "*** Warning: Linking the shared library $output against the"
-	      $echo "*** static library $deplib is not portable!"
-	      deplibs=3D"$deplib $deplibs"
-	    fi
+	      esac
+	      if test "$valid_a_lib" !=3D yes; then
+		echo
+		$ECHO "*** Warning: Trying to link with static lib archive $deplib."
+		echo "*** I have the capability to make that library automatically link =
in when"
+		echo "*** you link to this library.  But I can only do this if you have =
a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because the file extensions .$libext of this argument makes me=
 believe"
+		echo "*** that it is just a static archive that I should not use here."
+	      else
+		echo
+		$ECHO "*** Warning: Linking the shared library $output against the"
+		$ECHO "*** static library $deplib is not portable!"
+		deplibs=3D"$deplib $deplibs"
+	      fi
+	      ;;
+	    esac
 	    continue
 	    ;;
 	  prog)
@@ -2267,11 +6358,11 @@
 	    if test "$pass" =3D dlpreopen || test "$dlopen_support" !=3D yes || t=
est "$build_libtool_libs" =3D no; then
 	      # If there is no dlopen support or we're linking statically,
 	      # we need to preload.
-	      newdlprefiles=3D"$newdlprefiles $deplib"
+	      func_append newdlprefiles " $deplib"
 	      compile_deplibs=3D"$deplib $compile_deplibs"
 	      finalize_deplibs=3D"$deplib $finalize_deplibs"
 	    else
-	      newdlfiles=3D"$newdlfiles $deplib"
+	      func_append newdlfiles " $deplib"
 	    fi
 	  fi
 	  continue
@@ -2281,21 +6372,18 @@
 	  continue
 	  ;;
 	esac # case $deplib
+
 	if test "$found" =3D yes || test -f "$lib"; then :
 	else
-	  $echo "$modename: cannot find the library \`$lib' or unhandled argument=
 \`$deplib'" 1>&2
-	  exit $EXIT_FAILURE
+	  func_fatal_error "cannot find the library \`$lib' or unhandled argument=
 \`$deplib'"
 	fi
=20
 	# Check to see that this really is a libtool archive.
-	if (${SED} -e '2q' $lib | grep "^# Generated by .*$PACKAGE") >/dev/null 2=
>&1; then :
-	else
-	  $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
-	  exit $EXIT_FAILURE
-	fi
-
-	ladir=3D`$echo "X$lib" | $Xsed -e 's%/[^/]*$%%'`
-	test "X$ladir" =3D "X$lib" && ladir=3D"."
+	func_lalib_unsafe_p "$lib" \
+	  || func_fatal_error "\`$lib' is not a valid libtool archive"
+
+	func_dirname "$lib" "" "."
+	ladir=3D"$func_dirname_result"
=20
 	dlname=3D
 	dlopen=3D
@@ -2303,6 +6391,7 @@
 	libdir=3D
 	library_names=3D
 	old_library=3D
+	inherited_linker_flags=3D
 	# If the library was installed with an old release of libtool,
 	# it will not redefine variables installed, or shouldnotlink
 	installed=3Dyes
@@ -2311,16 +6400,24 @@
=20
=20
 	# Read the .la file
-	case $lib in
-	*/* | *\\*) . $lib ;;
-	*) . ./$lib ;;
-	esac
-
+	func_source "$lib"
+
+	# Convert "-framework foo" to "foo.ltframework"
+	if test -n "$inherited_linker_flags"; then
+	  tmp_inherited_linker_flags=3D`$ECHO "$inherited_linker_flags" | $SED 's=
/-framework \([^ $]*\)/\1.ltframework/g'`
+	  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do
+	    case " $new_inherited_linker_flags " in
+	      *" $tmp_inherited_linker_flag "*) ;;
+	      *) func_append new_inherited_linker_flags " $tmp_inherited_linker_f=
lag";;
+	    esac
+	  done
+	fi
+	dependency_libs=3D`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltfram=
ework% -framework \1%g'`
 	if test "$linkmode,$pass" =3D "lib,link" ||
 	   test "$linkmode,$pass" =3D "prog,scan" ||
 	   { test "$linkmode" !=3D prog && test "$linkmode" !=3D lib; }; then
-	  test -n "$dlopen" && dlfiles=3D"$dlfiles $dlopen"
-	  test -n "$dlpreopen" && dlprefiles=3D"$dlprefiles $dlpreopen"
+	  test -n "$dlopen" && func_append dlfiles " $dlopen"
+	  test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen"
 	fi
=20
 	if test "$pass" =3D conv; then
@@ -2328,45 +6425,47 @@
 	  deplibs=3D"$lib $deplibs"
 	  if test -z "$libdir"; then
 	    if test -z "$old_library"; then
-	      $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
-	      exit $EXIT_FAILURE
+	      func_fatal_error "cannot find name of link library for \`$lib'"
 	    fi
 	    # It is a libtool convenience library, so add in its objects.
-	    convenience=3D"$convenience $ladir/$objdir/$old_library"
-	    old_convenience=3D"$old_convenience $ladir/$objdir/$old_library"
-	    tmp_libs=3D
-	    for deplib in $dependency_libs; do
-	      deplibs=3D"$deplib $deplibs"
-              if test "X$duplicate_deps" =3D "Xyes" ; then
-	        case "$tmp_libs " in
-	        *" $deplib "*) specialdeplibs=3D"$specialdeplibs $deplib" ;;
-	        esac
-              fi
-	      tmp_libs=3D"$tmp_libs $deplib"
-	    done
+	    func_append convenience " $ladir/$objdir/$old_library"
+	    func_append old_convenience " $ladir/$objdir/$old_library"
 	  elif test "$linkmode" !=3D prog && test "$linkmode" !=3D lib; then
-	    $echo "$modename: \`$lib' is not a convenience library" 1>&2
-	    exit $EXIT_FAILURE
+	    func_fatal_error "\`$lib' is not a convenience library"
 	  fi
+	  tmp_libs=3D
+	  for deplib in $dependency_libs; do
+	    deplibs=3D"$deplib $deplibs"
+	    if $opt_preserve_dup_deps ; then
+	      case "$tmp_libs " in
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
+	      esac
+	    fi
+	    func_append tmp_libs " $deplib"
+	  done
 	  continue
 	fi # $pass =3D conv
=20
=20
 	# Get the name of the library we link against.
 	linklib=3D
-	for l in $old_library $library_names; do
-	  linklib=3D"$l"
-	done
+	if test -n "$old_library" &&
+	   { test "$prefer_static_libs" =3D yes ||
+	     test "$prefer_static_libs,$installed" =3D "built,no"; }; then
+	  linklib=3D$old_library
+	else
+	  for l in $old_library $library_names; do
+	    linklib=3D"$l"
+	  done
+	fi
 	if test -z "$linklib"; then
-	  $echo "$modename: cannot find name of link library for \`$lib'" 1>&2
-	  exit $EXIT_FAILURE
+	  func_fatal_error "cannot find name of link library for \`$lib'"
 	fi
=20
 	# This library was specified with -dlopen.
 	if test "$pass" =3D dlopen; then
 	  if test -z "$libdir"; then
-	    $echo "$modename: cannot -dlopen a convenience library: \`$lib'" 1>&2
-	    exit $EXIT_FAILURE
+	    func_fatal_error "cannot -dlopen a convenience library: \`$lib'"
 	  fi
 	  if test -z "$dlname" ||
 	     test "$dlopen_support" !=3D yes ||
@@ -2375,9 +6474,9 @@
 	    # statically, we need to preload.  We also need to preload any
 	    # dependent libraries so libltdl's deplib preloader doesn't
 	    # bomb out in the load deplibs phase.
-	    dlprefiles=3D"$dlprefiles $lib $dependency_libs"
+	    func_append dlprefiles " $lib $dependency_libs"
 	  else
-	    newdlfiles=3D"$newdlfiles $lib"
+	    func_append newdlfiles " $lib"
 	  fi
 	  continue
 	fi # $pass =3D dlopen
@@ -2388,24 +6487,25 @@
 	*)
 	  abs_ladir=3D`cd "$ladir" && pwd`
 	  if test -z "$abs_ladir"; then
-	    $echo "$modename: warning: cannot determine absolute directory name o=
f \`$ladir'" 1>&2
-	    $echo "$modename: passing it literally to the linker, although it mig=
ht fail" 1>&2
+	    func_warning "cannot determine absolute directory name of \`$ladir'"
+	    func_warning "passing it literally to the linker, although it might f=
ail"
 	    abs_ladir=3D"$ladir"
 	  fi
 	  ;;
 	esac
-	laname=3D`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
+	func_basename "$lib"
+	laname=3D"$func_basename_result"
=20
 	# Find the relevant object directory and library name.
 	if test "X$installed" =3D Xyes; then
-	  if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then
-	    $echo "$modename: warning: library \`$lib' was moved." 1>&2
+	  if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$link=
lib"; then
+	    func_warning "library \`$lib' was moved."
 	    dir=3D"$ladir"
 	    absdir=3D"$abs_ladir"
 	    libdir=3D"$abs_ladir"
 	  else
-	    dir=3D"$libdir"
-	    absdir=3D"$libdir"
+	    dir=3D"$lt_sysroot$libdir"
+	    absdir=3D"$lt_sysroot$libdir"
 	  fi
 	  test "X$hardcode_automatic" =3D Xyes && avoidtemprpath=3Dyes
 	else
@@ -2413,32 +6513,62 @@
 	    dir=3D"$ladir"
 	    absdir=3D"$abs_ladir"
 	    # Remove this search path later
-	    notinst_path=3D"$notinst_path $abs_ladir"
+	    func_append notinst_path " $abs_ladir"
 	  else
 	    dir=3D"$ladir/$objdir"
 	    absdir=3D"$abs_ladir/$objdir"
 	    # Remove this search path later
-	    notinst_path=3D"$notinst_path $abs_ladir"
+	    func_append notinst_path " $abs_ladir"
 	  fi
 	fi # $installed =3D yes
-	name=3D`$echo "X$laname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+	func_stripname 'lib' '.la' "$laname"
+	name=3D$func_stripname_result
=20
 	# This library was specified with -dlpreopen.
 	if test "$pass" =3D dlpreopen; then
-	  if test -z "$libdir"; then
-	    $echo "$modename: cannot -dlpreopen a convenience library: \`$lib'" 1=
>&2
-	    exit $EXIT_FAILURE
+	  if test -z "$libdir" && test "$linkmode" =3D prog; then
+	    func_fatal_error "only libraries may -dlpreopen a convenience library=
: \`$lib'"
 	  fi
-	  # Prefer using a static library (so that no silly _DYNAMIC symbols
-	  # are required to link).
-	  if test -n "$old_library"; then
-	    newdlprefiles=3D"$newdlprefiles $dir/$old_library"
-	  # Otherwise, use the dlname, so that lt_dlopen finds it.
-	  elif test -n "$dlname"; then
-	    newdlprefiles=3D"$newdlprefiles $dir/$dlname"
-	  else
-	    newdlprefiles=3D"$newdlprefiles $dir/$linklib"
-	  fi
+	  case "$host" in
+	    # special handling for platforms with PE-DLLs.
+	    *cygwin* | *mingw* | *cegcc* )
+	      # Linker will automatically link against shared library if both
+	      # static and shared are present.  Therefore, ensure we extract
+	      # symbols from the import library if a shared library is present
+	      # (otherwise, the dlopen module name will be incorrect).  We do
+	      # this by putting the import library name into $newdlprefiles.
+	      # We recover the dlopen module name by 'saving' the la file
+	      # name in a special purpose variable, and (later) extracting the
+	      # dlname from the la file.
+	      if test -n "$dlname"; then
+	        func_tr_sh "$dir/$linklib"
+	        eval "libfile_$func_tr_sh_result=3D\$abs_ladir/\$laname"
+	        func_append newdlprefiles " $dir/$linklib"
+	      else
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      fi
+	    ;;
+	    * )
+	      # Prefer using a static library (so that no silly _DYNAMIC symbols
+	      # are required to link).
+	      if test -n "$old_library"; then
+	        func_append newdlprefiles " $dir/$old_library"
+	        # Keep a list of preopened convenience libraries to check
+	        # that they are being used correctly in the link pass.
+	        test -z "$libdir" && \
+	          func_append dlpreconveniencelibs " $dir/$old_library"
+	      # Otherwise, use the dlname, so that lt_dlopen finds it.
+	      elif test -n "$dlname"; then
+	        func_append newdlprefiles " $dir/$dlname"
+	      else
+	        func_append newdlprefiles " $dir/$linklib"
+	      fi
+	    ;;
+	  esac
 	fi # $pass =3D dlpreopen
=20
 	if test -z "$libdir"; then
@@ -2456,7 +6586,7 @@
=20
=20
 	if test "$linkmode" =3D prog && test "$pass" !=3D link; then
-	  newlib_search_path=3D"$newlib_search_path $ladir"
+	  func_append newlib_search_path " $ladir"
 	  deplibs=3D"$lib $deplibs"
=20
 	  linkalldeplibs=3Dno
@@ -2468,7 +6598,10 @@
 	  tmp_libs=3D
 	  for deplib in $dependency_libs; do
 	    case $deplib in
-	    -L*) newlib_search_path=3D"$newlib_search_path "`$echo "X$deplib" | $=
Xsed -e 's/^-L//'`;; ### testsuite: skip nested quoting test
+	    -L*) func_stripname '-L' '' "$deplib"
+	         func_resolve_sysroot "$func_stripname_result"
+	         func_append newlib_search_path " $func_resolve_sysroot_result"
+		 ;;
 	    esac
 	    # Need to link against all dependency_libs?
 	    if test "$linkalldeplibs" =3D yes; then
@@ -2478,26 +6611,27 @@
 	      # or/and link against static libraries
 	      newdependency_libs=3D"$deplib $newdependency_libs"
 	    fi
-	    if test "X$duplicate_deps" =3D "Xyes" ; then
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs=3D"$specialdeplibs $deplib" ;;
+	      *" $deplib "*) func_append specialdeplibs " $deplib" ;;
 	      esac
 	    fi
-	    tmp_libs=3D"$tmp_libs $deplib"
+	    func_append tmp_libs " $deplib"
 	  done # for deplib
 	  continue
 	fi # $linkmode =3D prog...
=20
 	if test "$linkmode,$pass" =3D "prog,link"; then
 	  if test -n "$library_names" &&
-	     { test "$prefer_static_libs" =3D no || test -z "$old_library"; }; th=
en
+	     { { test "$prefer_static_libs" =3D no ||
+	         test "$prefer_static_libs,$installed" =3D "built,yes"; } ||
+	       test -z "$old_library"; }; then
 	    # We need to hardcode the library path
 	    if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then
 	      # Make sure the rpath contains only unique directories.
-	      case "$temp_rpath " in
-	      *" $dir "*) ;;
-	      *" $absdir "*) ;;
-	      *) temp_rpath=3D"$temp_rpath $absdir" ;;
+	      case "$temp_rpath:" in
+	      *"$absdir:"*) ;;
+	      *) func_append temp_rpath "$absdir:" ;;
 	      esac
 	    fi
=20
@@ -2509,7 +6643,7 @@
 	    *)
 	      case "$compile_rpath " in
 	      *" $absdir "*) ;;
-	      *) compile_rpath=3D"$compile_rpath $absdir"
+	      *) func_append compile_rpath " $absdir" ;;
 	      esac
 	      ;;
 	    esac
@@ -2518,7 +6652,7 @@
 	    *)
 	      case "$finalize_rpath " in
 	      *" $libdir "*) ;;
-	      *) finalize_rpath=3D"$finalize_rpath $libdir"
+	      *) func_append finalize_rpath " $libdir" ;;
 	      esac
 	      ;;
 	    esac
@@ -2535,27 +6669,43 @@
=20
 	link_static=3Dno # Whether the deplib will be linked statically
 	use_static_libs=3D$prefer_static_libs
-	if test "$use_static_libs" =3D built && test "$installed" =3D yes ; then
+	if test "$use_static_libs" =3D built && test "$installed" =3D yes; then
 	  use_static_libs=3Dno
 	fi
 	if test -n "$library_names" &&
 	   { test "$use_static_libs" =3D no || test -z "$old_library"; }; then
-	  if test "$installed" =3D no; then
-	    notinst_deplibs=3D"$notinst_deplibs $lib"
-	    need_relink=3Dyes
-	  fi
+	  case $host in
+	  *cygwin* | *mingw* | *cegcc*)
+	      # No point in relinking DLLs because paths are not encoded
+	      func_append notinst_deplibs " $lib"
+	      need_relink=3Dno
+	    ;;
+	  *)
+	    if test "$installed" =3D no; then
+	      func_append notinst_deplibs " $lib"
+	      need_relink=3Dyes
+	    fi
+	    ;;
+	  esac
 	  # This is a shared library
=20
-	  # Warn about portability, can't link against -module's on
-	  # some systems (darwin)
-	  if test "$shouldnotlink" =3D yes && test "$pass" =3D link ; then
-	    $echo
+	  # Warn about portability, can't link against -module's on some
+	  # systems (darwin).  Don't bleat about dlopened modules though!
+	  dlopenmodule=3D""
+	  for dlpremoduletest in $dlprefiles; do
+	    if test "X$dlpremoduletest" =3D "X$lib"; then
+	      dlopenmodule=3D"$dlpremoduletest"
+	      break
+	    fi
+	  done
+	  if test -z "$dlopenmodule" && test "$shouldnotlink" =3D yes && test "$p=
ass" =3D link; then
+	    echo
 	    if test "$linkmode" =3D prog; then
-	      $echo "*** Warning: Linking the executable $output against the load=
able module"
+	      $ECHO "*** Warning: Linking the executable $output against the load=
able module"
 	    else
-	      $echo "*** Warning: Linking the shared library $output against the =
loadable module"
+	      $ECHO "*** Warning: Linking the shared library $output against the =
loadable module"
 	    fi
-	    $echo "*** $linklib is not portable!"
+	    $ECHO "*** $linklib is not portable!"
 	  fi
 	  if test "$linkmode" =3D lib &&
 	     test "$hardcode_into_libs" =3D yes; then
@@ -2567,7 +6717,7 @@
 	    *)
 	      case "$compile_rpath " in
 	      *" $absdir "*) ;;
-	      *) compile_rpath=3D"$compile_rpath $absdir"
+	      *) func_append compile_rpath " $absdir" ;;
 	      esac
 	      ;;
 	    esac
@@ -2576,7 +6726,7 @@
 	    *)
 	      case "$finalize_rpath " in
 	      *" $libdir "*) ;;
-	      *) finalize_rpath=3D"$finalize_rpath $libdir"
+	      *) func_append finalize_rpath " $libdir" ;;
 	      esac
 	      ;;
 	    esac
@@ -2585,17 +6735,19 @@
 	  if test -n "$old_archive_from_expsyms_cmds"; then
 	    # figure out the soname
 	    set dummy $library_names
-	    realname=3D"$2"
-	    shift; shift
-	    libname=3D`eval \\$echo \"$libname_spec\"`
+	    shift
+	    realname=3D"$1"
+	    shift
+	    libname=3D`eval "\\$ECHO \"$libname_spec\""`
 	    # use dlname if we got it. it's perfectly good, no?
 	    if test -n "$dlname"; then
 	      soname=3D"$dlname"
 	    elif test -n "$soname_spec"; then
 	      # bleh windows
 	      case $host in
-	      *cygwin* | mingw*)
-		major=3D`expr $current - $age`
+	      *cygwin* | mingw* | *cegcc*)
+	        func_arith $current - $age
+		major=3D$func_arith_result
 		versuffix=3D"-$major"
 		;;
 	      esac
@@ -2606,43 +6758,29 @@
=20
 	    # Make a new name for the extract_expsyms_cmds to use
 	    soroot=3D"$soname"
-	    soname=3D`$echo $soroot | ${SED} -e 's/^.*\///'`
-	    newlib=3D"libimp-`$echo $soname | ${SED} 's/^lib//;s/\.dll$//'`.a"
+	    func_basename "$soroot"
+	    soname=3D"$func_basename_result"
+	    func_stripname 'lib' '.dll' "$soname"
+	    newlib=3Dlibimp-$func_stripname_result.a
=20
 	    # If the library has no export list, then create one now
 	    if test -f "$output_objdir/$soname-def"; then :
 	    else
-	      $show "extracting exported symbol list from \`$soname'"
-	      save_ifs=3D"$IFS"; IFS=3D'~'
-	      cmds=3D$extract_expsyms_cmds
-	      for cmd in $cmds; do
-		IFS=3D"$save_ifs"
-		eval cmd=3D\"$cmd\"
-		$show "$cmd"
-		$run eval "$cmd" || exit $?
-	      done
-	      IFS=3D"$save_ifs"
+	      func_verbose "extracting exported symbol list from \`$soname'"
+	      func_execute_cmds "$extract_expsyms_cmds" 'exit $?'
 	    fi
=20
 	    # Create $newlib
 	    if test -f "$output_objdir/$newlib"; then :; else
-	      $show "generating import library for \`$soname'"
-	      save_ifs=3D"$IFS"; IFS=3D'~'
-	      cmds=3D$old_archive_from_expsyms_cmds
-	      for cmd in $cmds; do
-		IFS=3D"$save_ifs"
-		eval cmd=3D\"$cmd\"
-		$show "$cmd"
-		$run eval "$cmd" || exit $?
-	      done
-	      IFS=3D"$save_ifs"
+	      func_verbose "generating import library for \`$soname'"
+	      func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?'
 	    fi
 	    # make sure the library variables are pointing to the new library
 	    dir=3D$output_objdir
 	    linklib=3D$newlib
 	  fi # test -n "$old_archive_from_expsyms_cmds"
=20
-	  if test "$linkmode" =3D prog || test "$mode" !=3D relink; then
+	  if test "$linkmode" =3D prog || test "$opt_mode" !=3D relink; then
 	    add_shlibpath=3D
 	    add_dir=3D
 	    add=3D
@@ -2657,17 +6795,21 @@
 		  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \
 		    *-*-unixware7*) add_dir=3D"-L$dir" ;;
 		  *-*-darwin* )
-		    # if the lib is a module then we can not link against
-		    # it, someone is ignoring the new warnings I added
+		    # if the lib is a (non-dlopened) module then we can not
+		    # link against it, someone is ignoring the earlier warnings
 		    if /usr/bin/file -L $add 2> /dev/null |
-                      $EGREP ": [^:]* bundle" >/dev/null ; then
-		      $echo "** Warning, lib $linklib is a module, not a shared library"
-		      if test -z "$old_library" ; then
-		        $echo
-		        $echo "** And there doesn't seem to be a static archive availabl=
e"
-		        $echo "** The link will probably fail, sorry"
-		      else
-		        add=3D"$dir/$old_library"
+			 $GREP ": [^:]* bundle" >/dev/null ; then
+		      if test "X$dlopenmodule" !=3D "X$lib"; then
+			$ECHO "*** Warning: lib $linklib is a module, not a shared library"
+			if test -z "$old_library" ; then
+			  echo
+			  echo "*** And there doesn't seem to be a static archive available"
+			  echo "*** The link will probably fail, sorry"
+			else
+			  add=3D"$dir/$old_library"
+			fi
+		      elif test -n "$old_library"; then
+			add=3D"$dir/$old_library"
 		      fi
 		    fi
 		esac
@@ -2685,7 +6827,8 @@
 	      fi
 	      ;;
 	    relink)
-	      if test "$hardcode_direct" =3D yes; then
+	      if test "$hardcode_direct" =3D yes &&
+	         test "$hardcode_direct_absolute" =3D no; then
 		add=3D"$dir/$linklib"
 	      elif test "$hardcode_minus_L" =3D yes; then
 		add_dir=3D"-L$dir"
@@ -2693,7 +6836,7 @@
 		if test -n "$inst_prefix_dir"; then
 		  case $libdir in
 		    [\\/]*)
-		      add_dir=3D"$add_dir -L$inst_prefix_dir$libdir"
+		      func_append add_dir " -L$inst_prefix_dir$libdir"
 		      ;;
 		  esac
 		fi
@@ -2709,14 +6852,13 @@
 	    esac
=20
 	    if test "$lib_linked" !=3D yes; then
-	      $echo "$modename: configuration error: unsupported hardcode propert=
ies"
-	      exit $EXIT_FAILURE
+	      func_fatal_configuration "unsupported hardcode properties"
 	    fi
=20
 	    if test -n "$add_shlibpath"; then
 	      case :$compile_shlibpath: in
 	      *":$add_shlibpath:"*) ;;
-	      *) compile_shlibpath=3D"$compile_shlibpath$add_shlibpath:" ;;
+	      *) func_append compile_shlibpath "$add_shlibpath:" ;;
 	      esac
 	    fi
 	    if test "$linkmode" =3D prog; then
@@ -2725,23 +6867,24 @@
 	    else
 	      test -n "$add_dir" && deplibs=3D"$add_dir $deplibs"
 	      test -n "$add" && deplibs=3D"$add $deplibs"
-	      if test "$hardcode_direct" !=3D yes && \
-		 test "$hardcode_minus_L" !=3D yes && \
+	      if test "$hardcode_direct" !=3D yes &&
+		 test "$hardcode_minus_L" !=3D yes &&
 		 test "$hardcode_shlibpath_var" =3D yes; then
 		case :$finalize_shlibpath: in
 		*":$libdir:"*) ;;
-		*) finalize_shlibpath=3D"$finalize_shlibpath$libdir:" ;;
+		*) func_append finalize_shlibpath "$libdir:" ;;
 		esac
 	      fi
 	    fi
 	  fi
=20
-	  if test "$linkmode" =3D prog || test "$mode" =3D relink; then
+	  if test "$linkmode" =3D prog || test "$opt_mode" =3D relink; then
 	    add_shlibpath=3D
 	    add_dir=3D
 	    add=3D
 	    # Finalize command for both is simple: just hardcode it.
-	    if test "$hardcode_direct" =3D yes; then
+	    if test "$hardcode_direct" =3D yes &&
+	       test "$hardcode_direct_absolute" =3D no; then
 	      add=3D"$libdir/$linklib"
 	    elif test "$hardcode_minus_L" =3D yes; then
 	      add_dir=3D"-L$libdir"
@@ -2749,15 +6892,15 @@
 	    elif test "$hardcode_shlibpath_var" =3D yes; then
 	      case :$finalize_shlibpath: in
 	      *":$libdir:"*) ;;
-	      *) finalize_shlibpath=3D"$finalize_shlibpath$libdir:" ;;
+	      *) func_append finalize_shlibpath "$libdir:" ;;
 	      esac
 	      add=3D"-l$name"
 	    elif test "$hardcode_automatic" =3D yes; then
 	      if test -n "$inst_prefix_dir" &&
 		 test -f "$inst_prefix_dir$libdir/$linklib" ; then
-	        add=3D"$inst_prefix_dir$libdir/$linklib"
+		add=3D"$inst_prefix_dir$libdir/$linklib"
 	      else
-	        add=3D"$libdir/$linklib"
+		add=3D"$libdir/$linklib"
 	      fi
 	    else
 	      # We cannot seem to hardcode it, guess we'll fake it.
@@ -2766,7 +6909,7 @@
 	      if test -n "$inst_prefix_dir"; then
 		case $libdir in
 		  [\\/]*)
-		    add_dir=3D"$add_dir -L$inst_prefix_dir$libdir"
+		    func_append add_dir " -L$inst_prefix_dir$libdir"
 		    ;;
 		esac
 	      fi
@@ -2801,21 +6944,21 @@
=20
 	    # Just print a warning and add the library to dependency_libs so
 	    # that the program can be linked against the static library.
-	    $echo
-	    $echo "*** Warning: This system can not link to static lib archive $l=
ib."
-	    $echo "*** I have the capability to make that library automatically l=
ink in when"
-	    $echo "*** you link to this library.  But I can only do this if you h=
ave a"
-	    $echo "*** shared version of the library, which you do not appear to =
have."
+	    echo
+	    $ECHO "*** Warning: This system can not link to static lib archive $l=
ib."
+	    echo "*** I have the capability to make that library automatically li=
nk in when"
+	    echo "*** you link to this library.  But I can only do this if you ha=
ve a"
+	    echo "*** shared version of the library, which you do not appear to h=
ave."
 	    if test "$module" =3D yes; then
-	      $echo "*** But as you try to build a module library, libtool will s=
till create "
-	      $echo "*** a static module, that should work as long as the dlopeni=
ng application"
-	      $echo "*** is linked with the -dlopen flag to resolve symbols at ru=
ntime."
+	      echo "*** But as you try to build a module library, libtool will st=
ill create "
+	      echo "*** a static module, that should work as long as the dlopenin=
g application"
+	      echo "*** is linked with the -dlopen flag to resolve symbols at run=
time."
 	      if test -z "$global_symbol_pipe"; then
-		$echo
-		$echo "*** However, this would only work if libtool was able to extract =
symbol"
-		$echo "*** lists from a program, using \`nm' or equivalent, but libtool =
could"
-		$echo "*** not find such a program.  So, this module is probably useless=
."
-		$echo "*** \`nm' from GNU binutils and a full rebuild may help."
+		echo
+		echo "*** However, this would only work if libtool was able to extract s=
ymbol"
+		echo "*** lists from a program, using \`nm' or equivalent, but libtool c=
ould"
+		echo "*** not find such a program.  So, this module is probably useless."
+		echo "*** \`nm' from GNU binutils and a full rebuild may help."
 	      fi
 	      if test "$build_old_libs" =3D no; then
 		build_libtool_libs=3Dmodule
@@ -2839,120 +6982,113 @@
 	    temp_deplibs=3D
 	    for libdir in $dependency_libs; do
 	      case $libdir in
-	      -R*) temp_xrpath=3D`$echo "X$libdir" | $Xsed -e 's/^-R//'`
+	      -R*) func_stripname '-R' '' "$libdir"
+	           temp_xrpath=3D$func_stripname_result
 		   case " $xrpath " in
 		   *" $temp_xrpath "*) ;;
-		   *) xrpath=3D"$xrpath $temp_xrpath";;
+		   *) func_append xrpath " $temp_xrpath";;
 		   esac;;
-	      *) temp_deplibs=3D"$temp_deplibs $libdir";;
+	      *) func_append temp_deplibs " $libdir";;
 	      esac
 	    done
 	    dependency_libs=3D"$temp_deplibs"
 	  fi
=20
-	  newlib_search_path=3D"$newlib_search_path $absdir"
+	  func_append newlib_search_path " $absdir"
 	  # Link against this library
 	  test "$link_static" =3D no && newdependency_libs=3D"$abs_ladir/$laname =
$newdependency_libs"
 	  # ... and its dependency_libs
 	  tmp_libs=3D
 	  for deplib in $dependency_libs; do
 	    newdependency_libs=3D"$deplib $newdependency_libs"
-	    if test "X$duplicate_deps" =3D "Xyes" ; then
+	    case $deplib in
+              -L*) func_stripname '-L' '' "$deplib"
+                   func_resolve_sysroot "$func_stripname_result";;
+              *) func_resolve_sysroot "$deplib" ;;
+            esac
+	    if $opt_preserve_dup_deps ; then
 	      case "$tmp_libs " in
-	      *" $deplib "*) specialdeplibs=3D"$specialdeplibs $deplib" ;;
+	      *" $func_resolve_sysroot_result "*)
+                func_append specialdeplibs " $func_resolve_sysroot_result"=
 ;;
 	      esac
 	    fi
-	    tmp_libs=3D"$tmp_libs $deplib"
+	    func_append tmp_libs " $func_resolve_sysroot_result"
 	  done
=20
 	  if test "$link_all_deplibs" !=3D no; then
 	    # Add the search paths of all dependency libraries
 	    for deplib in $dependency_libs; do
+	      path=3D
 	      case $deplib in
 	      -L*) path=3D"$deplib" ;;
 	      *.la)
-		dir=3D`$echo "X$deplib" | $Xsed -e 's%/[^/]*$%%'`
-		test "X$dir" =3D "X$deplib" && dir=3D"."
+	        func_resolve_sysroot "$deplib"
+	        deplib=3D$func_resolve_sysroot_result
+	        func_dirname "$deplib" "" "."
+		dir=3D$func_dirname_result
 		# We need an absolute path.
 		case $dir in
 		[\\/]* | [A-Za-z]:[\\/]*) absdir=3D"$dir" ;;
 		*)
 		  absdir=3D`cd "$dir" && pwd`
 		  if test -z "$absdir"; then
-		    $echo "$modename: warning: cannot determine absolute directory name =
of \`$dir'" 1>&2
+		    func_warning "cannot determine absolute directory name of \`$dir'"
 		    absdir=3D"$dir"
 		  fi
 		  ;;
 		esac
-		if grep "^installed=3Dno" $deplib > /dev/null; then
-		  path=3D"$absdir/$objdir"
-		else
-		  eval libdir=3D`${SED} -n -e 's/^libdir=3D\(.*\)$/\1/p' $deplib`
-		  if test -z "$libdir"; then
-		    $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
-		    exit $EXIT_FAILURE
-		  fi
-		  if test "$absdir" !=3D "$libdir"; then
-		    $echo "$modename: warning: \`$deplib' seems to be moved" 1>&2
-		  fi
-		  path=3D"$absdir"
-		fi
-		depdepl=3D
+		if $GREP "^installed=3Dno" $deplib > /dev/null; then
 		case $host in
 		*-*-darwin*)
-		  # we do not want to link against static libs,
-		  # but need to link against shared
+		  depdepl=3D
 		  eval deplibrary_names=3D`${SED} -n -e 's/^library_names=3D\(.*\)$/\1/p=
' $deplib`
 		  if test -n "$deplibrary_names" ; then
 		    for tmp in $deplibrary_names ; do
 		      depdepl=3D$tmp
 		    done
-		    if test -f "$path/$depdepl" ; then
-		      depdepl=3D"$path/$depdepl"
+		    if test -f "$absdir/$objdir/$depdepl" ; then
+		      depdepl=3D"$absdir/$objdir/$depdepl"
+		      darwin_install_name=3D`${OTOOL} -L $depdepl | awk '{if (NR =3D=3D =
2) {print $1;exit}}'`
+                      if test -z "$darwin_install_name"; then
+                          darwin_install_name=3D`${OTOOL64} -L $depdepl  |=
 awk '{if (NR =3D=3D 2) {print $1;exit}}'`
+                      fi
+		      func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_instal=
l_name}:${depdepl}"
+		      func_append linker_flags " -dylib_file ${darwin_install_name}:${de=
pdepl}"
+		      path=3D
 		    fi
-		    # do not add paths which are already there
-		    case " $newlib_search_path " in
-		    *" $path "*) ;;
-		    *) newlib_search_path=3D"$newlib_search_path $path";;
-		    esac
 		  fi
-		  path=3D""
 		  ;;
 		*)
-		  path=3D"-L$path"
+		  path=3D"-L$absdir/$objdir"
 		  ;;
 		esac
+		else
+		  eval libdir=3D`${SED} -n -e 's/^libdir=3D\(.*\)$/\1/p' $deplib`
+		  test -z "$libdir" && \
+		    func_fatal_error "\`$deplib' is not a valid libtool archive"
+		  test "$absdir" !=3D "$libdir" && \
+		    func_warning "\`$deplib' seems to be moved"
+
+		  path=3D"-L$absdir"
+		fi
 		;;
-	      -l*)
-		case $host in
-		*-*-darwin*)
-		  # Again, we only want to link against shared libraries
-		  eval tmp_libs=3D`$echo "X$deplib" | $Xsed -e "s,^\-l,,"`
-		  for tmp in $newlib_search_path ; do
-		    if test -f "$tmp/lib$tmp_libs.dylib" ; then
-		      eval depdepl=3D"$tmp/lib$tmp_libs.dylib"
-		      break
-		    fi
-		  done
-		  path=3D""
-		  ;;
-		*) continue ;;
-		esac
-		;;
-	      *) continue ;;
 	      esac
 	      case " $deplibs " in
 	      *" $path "*) ;;
 	      *) deplibs=3D"$path $deplibs" ;;
 	      esac
-	      case " $deplibs " in
-	      *" $depdepl "*) ;;
-	      *) deplibs=3D"$depdepl $deplibs" ;;
-	      esac
 	    done
 	  fi # link_all_deplibs !=3D no
 	fi # linkmode =3D lib
       done # for deplib in $libs
+      if test "$pass" =3D link; then
+	if test "$linkmode" =3D "prog"; then
+	  compile_deplibs=3D"$new_inherited_linker_flags $compile_deplibs"
+	  finalize_deplibs=3D"$new_inherited_linker_flags $finalize_deplibs"
+	else
+	  compiler_flags=3D"$compiler_flags "`$ECHO " $new_inherited_linker_flags=
" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	fi
+      fi
       dependency_libs=3D"$newdependency_libs"
       if test "$pass" =3D dlpreopen; then
 	# Link the dlpreopened libraries before other libraries
@@ -2967,7 +7103,7 @@
 	  for dir in $newlib_search_path; do
 	    case "$lib_search_path " in
 	    *" $dir "*) ;;
-	    *) lib_search_path=3D"$lib_search_path $dir" ;;
+	    *) func_append lib_search_path " $dir" ;;
 	    esac
 	  done
 	  newlib_search_path=3D
@@ -3025,10 +7161,10 @@
 	    -L*)
 	      case " $tmp_libs " in
 	      *" $deplib "*) ;;
-	      *) tmp_libs=3D"$tmp_libs $deplib" ;;
+	      *) func_append tmp_libs " $deplib" ;;
 	      esac
 	      ;;
-	    *) tmp_libs=3D"$tmp_libs $deplib" ;;
+	    *) func_append tmp_libs " $deplib" ;;
 	    esac
 	  done
 	  eval $var=3D\"$tmp_libs\"
@@ -3044,98 +7180,96 @@
 	  ;;
 	esac
 	if test -n "$i" ; then
-	  tmp_libs=3D"$tmp_libs $i"
+	  func_append tmp_libs " $i"
 	fi
       done
       dependency_libs=3D$tmp_libs
     done # for pass
     if test "$linkmode" =3D prog; then
       dlfiles=3D"$newdlfiles"
+    fi
+    if test "$linkmode" =3D prog || test "$linkmode" =3D lib; then
       dlprefiles=3D"$newdlprefiles"
     fi
=20
     case $linkmode in
     oldlib)
-      if test -n "$deplibs"; then
-	$echo "$modename: warning: \`-l' and \`-L' are ignored for archives" 1>&2
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" !=3D no; then
+	func_warning "\`-dlopen' is ignored for archives"
       fi
=20
-      if test -n "$dlfiles$dlprefiles" || test "$dlself" !=3D no; then
-	$echo "$modename: warning: \`-dlopen' is ignored for archives" 1>&2
-      fi
-
-      if test -n "$rpath"; then
-	$echo "$modename: warning: \`-rpath' is ignored for archives" 1>&2
-      fi
-
-      if test -n "$xrpath"; then
-	$echo "$modename: warning: \`-R' is ignored for archives" 1>&2
-      fi
-
-      if test -n "$vinfo"; then
-	$echo "$modename: warning: \`-version-info/-version-number' is ignored fo=
r archives" 1>&2
-      fi
-
-      if test -n "$release"; then
-	$echo "$modename: warning: \`-release' is ignored for archives" 1>&2
-      fi
-
-      if test -n "$export_symbols" || test -n "$export_symbols_regex"; then
-	$echo "$modename: warning: \`-export-symbols' is ignored for archives" 1>=
&2
-      fi
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for archives" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for archives"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for archives"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info/-version-number' is ignored for archives"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for archives"
+
+      test -n "$export_symbols$export_symbols_regex" && \
+	func_warning "\`-export-symbols' is ignored for archives"
=20
       # Now set the variables for building old libraries.
       build_libtool_libs=3Dno
       oldlibs=3D"$output"
-      objs=3D"$objs$old_deplibs"
+      func_append objs "$old_deplibs"
       ;;
=20
     lib)
       # Make sure we only generate libraries of the form `libNAME.la'.
       case $outputname in
       lib*)
-	name=3D`$echo "X$outputname" | $Xsed -e 's/\.la$//' -e 's/^lib//'`
+	func_stripname 'lib' '.la' "$outputname"
+	name=3D$func_stripname_result
 	eval shared_ext=3D\"$shrext_cmds\"
 	eval libname=3D\"$libname_spec\"
 	;;
       *)
-	if test "$module" =3D no; then
-	  $echo "$modename: libtool library \`$output' must begin with \`lib'" 1>=
&2
-	  $echo "$help" 1>&2
-	  exit $EXIT_FAILURE
-	fi
+	test "$module" =3D no && \
+	  func_fatal_help "libtool library \`$output' must begin with \`lib'"
+
 	if test "$need_lib_prefix" !=3D no; then
 	  # Add the "lib" prefix for modules if required
-	  name=3D`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+	  func_stripname '' '.la' "$outputname"
+	  name=3D$func_stripname_result
 	  eval shared_ext=3D\"$shrext_cmds\"
 	  eval libname=3D\"$libname_spec\"
 	else
-	  libname=3D`$echo "X$outputname" | $Xsed -e 's/\.la$//'`
+	  func_stripname '' '.la' "$outputname"
+	  libname=3D$func_stripname_result
 	fi
 	;;
       esac
=20
       if test -n "$objs"; then
 	if test "$deplibs_check_method" !=3D pass_all; then
-	  $echo "$modename: cannot build libtool library \`$output' from non-libt=
ool objects on this host:$objs" 2>&1
-	  exit $EXIT_FAILURE
+	  func_fatal_error "cannot build libtool library \`$output' from non-libt=
ool objects on this host:$objs"
 	else
-	  $echo
-	  $echo "*** Warning: Linking the shared library $output against the non-=
libtool"
-	  $echo "*** objects $objs is not portable!"
-	  libobjs=3D"$libobjs $objs"
+	  echo
+	  $ECHO "*** Warning: Linking the shared library $output against the non-=
libtool"
+	  $ECHO "*** objects $objs is not portable!"
+	  func_append libobjs " $objs"
 	fi
       fi
=20
-      if test "$dlself" !=3D no; then
-	$echo "$modename: warning: \`-dlopen self' is ignored for libtool librari=
es" 1>&2
-      fi
+      test "$dlself" !=3D no && \
+	func_warning "\`-dlopen self' is ignored for libtool libraries"
=20
       set dummy $rpath
-      if test "$#" -gt 2; then
-	$echo "$modename: warning: ignoring multiple \`-rpath's for a libtool lib=
rary" 1>&2
-      fi
-      install_libdir=3D"$2"
+      shift
+      test "$#" -gt 1 && \
+	func_warning "ignoring multiple \`-rpath's for a libtool library"
+
+      install_libdir=3D"$1"
=20
       oldlibs=3D
       if test -z "$rpath"; then
@@ -3149,25 +7283,21 @@
 	  build_old_libs=3Dyes
 	fi
=20
-	if test -n "$vinfo"; then
-	  $echo "$modename: warning: \`-version-info/-version-number' is ignored =
for convenience libraries" 1>&2
-	fi
-
-	if test -n "$release"; then
-	  $echo "$modename: warning: \`-release' is ignored for convenience libra=
ries" 1>&2
-	fi
+	test -n "$vinfo" && \
+	  func_warning "\`-version-info/-version-number' is ignored for convenien=
ce libraries"
+
+	test -n "$release" && \
+	  func_warning "\`-release' is ignored for convenience libraries"
       else
=20
 	# Parse the version information argument.
 	save_ifs=3D"$IFS"; IFS=3D':'
 	set dummy $vinfo 0 0 0
+	shift
 	IFS=3D"$save_ifs"
=20
-	if test -n "$8"; then
-	  $echo "$modename: too many parameters to \`-version-info'" 1>&2
-	  $echo "$help" 1>&2
-	  exit $EXIT_FAILURE
-	fi
+	test -n "$7" && \
+	  func_fatal_help "too many parameters to \`-version-info'"
=20
 	# convert absolute version numbers to libtool ages
 	# this retains compatibility with .la files and attempts
@@ -3175,9 +7305,9 @@
=20
 	case $vinfo_number in
 	yes)
-	  number_major=3D"$2"
-	  number_minor=3D"$3"
-	  number_revision=3D"$4"
+	  number_major=3D"$1"
+	  number_minor=3D"$2"
+	  number_revision=3D"$3"
 	  #
 	  # There are really only two kinds -- those that
 	  # use the current revision as the major version
@@ -3186,27 +7316,30 @@
 	  # which has an extra 1 added just for fun
 	  #
 	  case $version_type in
-	  darwin|linux|osf|windows)
-	    current=3D`expr $number_major + $number_minor`
+	  darwin|linux|osf|windows|none)
+	    func_arith $number_major + $number_minor
+	    current=3D$func_arith_result
 	    age=3D"$number_minor"
 	    revision=3D"$number_revision"
 	    ;;
-	  freebsd-aout|freebsd-elf|sunos)
+	  freebsd-aout|freebsd-elf|qnx|sunos)
 	    current=3D"$number_major"
 	    revision=3D"$number_minor"
 	    age=3D"0"
 	    ;;
 	  irix|nonstopux)
-	    current=3D`expr $number_major + $number_minor - 1`
+	    func_arith $number_major + $number_minor
+	    current=3D$func_arith_result
 	    age=3D"$number_minor"
 	    revision=3D"$number_minor"
+	    lt_irix_increment=3Dno
 	    ;;
 	  esac
 	  ;;
 	no)
-	  current=3D"$2"
-	  revision=3D"$3"
-	  age=3D"$4"
+	  current=3D"$1"
+	  revision=3D"$2"
+	  age=3D"$3"
 	  ;;
 	esac
=20
@@ -3214,34 +7347,30 @@
 	case $current in
 	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0=
-9][0-9]) ;;
 	*)
-	  $echo "$modename: CURRENT \`$current' must be a nonnegative integer" 1>=
&2
-	  $echo "$modename: \`$vinfo' is not valid version information" 1>&2
-	  exit $EXIT_FAILURE
+	  func_error "CURRENT \`$current' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
 	  ;;
 	esac
=20
 	case $revision in
 	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0=
-9][0-9]) ;;
 	*)
-	  $echo "$modename: REVISION \`$revision' must be a nonnegative integer" =
1>&2
-	  $echo "$modename: \`$vinfo' is not valid version information" 1>&2
-	  exit $EXIT_FAILURE
+	  func_error "REVISION \`$revision' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
 	  ;;
 	esac
=20
 	case $age in
 	0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0=
-9][0-9]) ;;
 	*)
-	  $echo "$modename: AGE \`$age' must be a nonnegative integer" 1>&2
-	  $echo "$modename: \`$vinfo' is not valid version information" 1>&2
-	  exit $EXIT_FAILURE
+	  func_error "AGE \`$age' must be a nonnegative integer"
+	  func_fatal_error "\`$vinfo' is not valid version information"
 	  ;;
 	esac
=20
 	if test "$age" -gt "$current"; then
-	  $echo "$modename: AGE \`$age' is greater than the current interface num=
ber \`$current'" 1>&2
-	  $echo "$modename: \`$vinfo' is not valid version information" 1>&2
-	  exit $EXIT_FAILURE
+	  func_error "AGE \`$age' is greater than the current interface number \`=
$current'"
+	  func_fatal_error "\`$vinfo' is not valid version information"
 	fi
=20
 	# Calculate the version variables.
@@ -3254,11 +7383,14 @@
 	darwin)
 	  # Like Linux, but with the current version available in
 	  # verstring for coding it into the library header
-	  major=3D.`expr $current - $age`
+	  func_arith $current - $age
+	  major=3D.$func_arith_result
 	  versuffix=3D"$major.$age.$revision"
 	  # Darwin ld doesn't like 0 for these options...
-	  minor_current=3D`expr $current + 1`
-	  verstring=3D"${wl}-compatibility_version ${wl}$minor_current ${wl}-curr=
ent_version ${wl}$minor_current.$revision"
+	  func_arith $current + 1
+	  minor_current=3D$func_arith_result
+	  xlcverstring=3D"${wl}-compatibility_version ${wl}$minor_current ${wl}-c=
urrent_version ${wl}$minor_current.$revision"
+	  verstring=3D"-compatibility_version $minor_current -current_version $mi=
nor_current.$revision"
 	  ;;
=20
 	freebsd-aout)
@@ -3268,11 +7400,16 @@
=20
 	freebsd-elf)
 	  major=3D".$current"
-	  versuffix=3D".$current";
+	  versuffix=3D".$current"
 	  ;;
=20
 	irix | nonstopux)
-	  major=3D`expr $current - $age + 1`
+	  if test "X$lt_irix_increment" =3D "Xno"; then
+	    func_arith $current - $age
+	  else
+	    func_arith $current - $age + 1
+	  fi
+	  major=3D$func_arith_result
=20
 	  case $version_type in
 	    nonstopux) verstring_prefix=3Dnonstopux ;;
@@ -3283,8 +7420,10 @@
 	  # Add in all the interfaces that we are compatible with.
 	  loop=3D$revision
 	  while test "$loop" -ne 0; do
-	    iface=3D`expr $revision - $loop`
-	    loop=3D`expr $loop - 1`
+	    func_arith $revision - $loop
+	    iface=3D$func_arith_result
+	    func_arith $loop - 1
+	    loop=3D$func_arith_result
 	    verstring=3D"$verstring_prefix$major.$iface:$verstring"
 	  done
=20
@@ -3294,25 +7433,34 @@
 	  ;;
=20
 	linux)
-	  major=3D.`expr $current - $age`
+	  func_arith $current - $age
+	  major=3D.$func_arith_result
 	  versuffix=3D"$major.$age.$revision"
 	  ;;
=20
 	osf)
-	  major=3D.`expr $current - $age`
+	  func_arith $current - $age
+	  major=3D.$func_arith_result
 	  versuffix=3D".$current.$age.$revision"
 	  verstring=3D"$current.$age.$revision"
=20
 	  # Add in all the interfaces that we are compatible with.
 	  loop=3D$age
 	  while test "$loop" -ne 0; do
-	    iface=3D`expr $current - $loop`
-	    loop=3D`expr $loop - 1`
+	    func_arith $current - $loop
+	    iface=3D$func_arith_result
+	    func_arith $loop - 1
+	    loop=3D$func_arith_result
 	    verstring=3D"$verstring:${iface}.0"
 	  done
=20
 	  # Make executables depend on our current version.
-	  verstring=3D"$verstring:${current}.0"
+	  func_append verstring ":${current}.0"
+	  ;;
+
+	qnx)
+	  major=3D".$current"
+	  versuffix=3D".$current"
 	  ;;
=20
 	sunos)
@@ -3323,14 +7471,13 @@
 	windows)
 	  # Use '-' rather than '.', since we only want one
 	  # extension on DOS 8.3 filesystems.
-	  major=3D`expr $current - $age`
+	  func_arith $current - $age
+	  major=3D$func_arith_result
 	  versuffix=3D"-$major"
 	  ;;
=20
 	*)
-	  $echo "$modename: unknown library version type \`$version_type'" 1>&2
-	  $echo "Fatal configuration error.  See the $PACKAGE docs for more infor=
mation." 1>&2
-	  exit $EXIT_FAILURE
+	  func_fatal_configuration "unknown library version type \`$version_type'"
 	  ;;
 	esac
=20
@@ -3364,7 +7511,7 @@
 	# Check to see if the archive will have undefined symbols.
 	if test "$allow_undefined" =3D yes; then
 	  if test "$allow_undefined_flag" =3D unsupported; then
-	    $echo "$modename: warning: undefined symbols not allowed in $host sha=
red libraries" 1>&2
+	    func_warning "undefined symbols not allowed in $host shared libraries"
 	    build_libtool_libs=3Dno
 	    build_old_libs=3Dyes
 	  fi
@@ -3372,58 +7519,62 @@
 	  # Don't allow undefined symbols.
 	  allow_undefined_flag=3D"$no_undefined_flag"
 	fi
+
       fi
=20
-      if test "$mode" !=3D relink; then
+      func_generate_dlsyms "$libname" "$libname" "yes"
+      func_append libobjs " $symfileobj"
+      test "X$libobjs" =3D "X " && libobjs=3D
+
+      if test "$opt_mode" !=3D relink; then
 	# Remove our outputs, but don't remove object files since they
 	# may have been created when compiling PIC objects.
 	removelist=3D
-	tempremovelist=3D`$echo "$output_objdir/*"`
+	tempremovelist=3D`$ECHO "$output_objdir/*"`
 	for p in $tempremovelist; do
 	  case $p in
-	    *.$objext)
+	    *.$objext | *.gcno)
 	       ;;
 	    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objd=
ir/${libname}${release}.*)
 	       if test "X$precious_files_regex" !=3D "X"; then
-	         if echo $p | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
-	         then
+		 if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1
+		 then
 		   continue
 		 fi
 	       fi
-	       removelist=3D"$removelist $p"
+	       func_append removelist " $p"
 	       ;;
 	    *) ;;
 	  esac
 	done
-	if test -n "$removelist"; then
-	  $show "${rm}r $removelist"
-	  $run ${rm}r $removelist
-	fi
+	test -n "$removelist" && \
+	  func_show_eval "${RM}r \$removelist"
       fi
=20
       # Now set the variables for building old libraries.
       if test "$build_old_libs" =3D yes && test "$build_libtool_libs" !=3D=
 convenience ; then
-	oldlibs=3D"$oldlibs $output_objdir/$libname.$libext"
+	func_append oldlibs " $output_objdir/$libname.$libext"
=20
 	# Transform .lo files to .o files.
-	oldobjs=3D"$objs "`$echo "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$=
/d' -e "$lo2o" | $NL2SP`
+	oldobjs=3D"$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo=
2o" | $NL2SP`
       fi
=20
       # Eliminate all temporary directories.
-      for path in $notinst_path; do
-	lib_search_path=3D`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"`
-	deplibs=3D`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"`
-	dependency_libs=3D`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g=
"`
-      done
+      #for path in $notinst_path; do
+      #	lib_search_path=3D`$ECHO "$lib_search_path " | $SED "s% $path % %g=
"`
+      #	deplibs=3D`$ECHO "$deplibs " | $SED "s% -L$path % %g"`
+      #	dependency_libs=3D`$ECHO "$dependency_libs " | $SED "s% -L$path % =
%g"`
+      #done
=20
       if test -n "$xrpath"; then
 	# If the user specified any rpath flags, then add them.
 	temp_xrpath=3D
 	for libdir in $xrpath; do
-	  temp_xrpath=3D"$temp_xrpath -R$libdir"
+	  func_replace_sysroot "$libdir"
+	  func_append temp_xrpath " -R$func_replace_sysroot_result"
 	  case "$finalize_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_rpath=3D"$finalize_rpath $libdir" ;;
+	  *) func_append finalize_rpath " $libdir" ;;
 	  esac
 	done
 	if test "$hardcode_into_libs" !=3D yes || test "$build_old_libs" =3D yes;=
 then
@@ -3437,7 +7588,7 @@
       for lib in $old_dlfiles; do
 	case " $dlprefiles $dlfiles " in
 	*" $lib "*) ;;
-	*) dlfiles=3D"$dlfiles $lib" ;;
+	*) func_append dlfiles " $lib" ;;
 	esac
       done
=20
@@ -3447,19 +7598,19 @@
       for lib in $old_dlprefiles; do
 	case "$dlprefiles " in
 	*" $lib "*) ;;
-	*) dlprefiles=3D"$dlprefiles $lib" ;;
+	*) func_append dlprefiles " $lib" ;;
 	esac
       done
=20
       if test "$build_libtool_libs" =3D yes; then
 	if test -n "$rpath"; then
 	  case $host in
-	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*)
+	  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* =
| *-*-haiku*)
 	    # these systems don't actually have a c library (as such)!
 	    ;;
 	  *-*-rhapsody* | *-*-darwin1.[012])
 	    # Rhapsody C library is in the System framework
-	    deplibs=3D"$deplibs -framework System"
+	    func_append deplibs " System.ltframework"
 	    ;;
 	  *-*-netbsd*)
 	    # Don't link with libc until the a.out ld.so is fixed.
@@ -3473,10 +7624,10 @@
 	  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)
 	    # Compiler inserts libc in the correct place for threads to work
 	    ;;
- 	  *)
+	  *)
 	    # Add libc to deplibs on all other systems if necessary.
 	    if test "$build_libtool_need_lc" =3D "yes"; then
-	      deplibs=3D"$deplibs -lc"
+	      func_append deplibs " -lc"
 	    fi
 	    ;;
 	  esac
@@ -3510,123 +7661,139 @@
 	  # limits. Maybe even breaks it.  We compile a program, linking it
 	  # against the deplibs as a proxy for the library.  Then we can check
 	  # whether they linked in statically or dynamically with ldd.
-	  $rm conftest.c
+	  $opt_dry_run || $RM conftest.c
 	  cat > conftest.c <<EOF
 	  int main() { return 0; }
 EOF
-	  $rm conftest
-	  $LTCC $LTCFLAGS -o conftest conftest.c $deplibs
-	  if test "$?" -eq 0 ; then
+	  $opt_dry_run || $RM conftest
+	  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then
 	    ldd_output=3D`ldd conftest`
 	    for i in $deplibs; do
-	      name=3D`expr $i : '-l\(.*\)'`
-	      # If $name is empty we are operating on a -L argument.
-              if test "$name" !=3D "" && test "$name" -ne "0"; then
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=3D$func_stripname_result
 		if test "X$allow_libtool_libs_with_static_runtimes" =3D "Xyes" ; then
 		  case " $predeps $postdeps " in
 		  *" $i "*)
-		    newdeplibs=3D"$newdeplibs $i"
+		    func_append newdeplibs " $i"
 		    i=3D""
 		    ;;
 		  esac
-	        fi
+		fi
 		if test -n "$i" ; then
-		  libname=3D`eval \\$echo \"$libname_spec\"`
-		  deplib_matches=3D`eval \\$echo \"$library_names_spec\"`
-		  set dummy $deplib_matches
-		  deplib_match=3D$2
+		  libname=3D`eval "\\$ECHO \"$libname_spec\""`
+		  deplib_matches=3D`eval "\\$ECHO \"$library_names_spec\""`
+		  set dummy $deplib_matches; shift
+		  deplib_match=3D$1
 		  if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		    newdeplibs=3D"$newdeplibs $i"
+		    func_append newdeplibs " $i"
 		  else
 		    droppeddeps=3Dyes
-		    $echo
-		    $echo "*** Warning: dynamic linker does not accept needed library $i=
."
-		    $echo "*** I have the capability to make that library automatically =
link in when"
-		    $echo "*** you link to this library.  But I can only do this if you =
have a"
-		    $echo "*** shared version of the library, which I believe you do not=
 have"
-		    $echo "*** because a test_compile did reveal that the linker did not=
 use it for"
-		    $echo "*** its dynamic dependency list that programs get resolved wi=
th at runtime."
+		    echo
+		    $ECHO "*** Warning: dynamic linker does not accept needed library $i=
."
+		    echo "*** I have the capability to make that library automatically l=
ink in when"
+		    echo "*** you link to this library.  But I can only do this if you h=
ave a"
+		    echo "*** shared version of the library, which I believe you do not =
have"
+		    echo "*** because a test_compile did reveal that the linker did not =
use it for"
+		    echo "*** its dynamic dependency list that programs get resolved wit=
h at runtime."
 		  fi
 		fi
-	      else
-		newdeplibs=3D"$newdeplibs $i"
-	      fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
 	    done
 	  else
 	    # Error occurred in the first compile.  Let's try to salvage
 	    # the situation: Compile a separate program for each library.
 	    for i in $deplibs; do
-	      name=3D`expr $i : '-l\(.*\)'`
-	      # If $name is empty we are operating on a -L argument.
-              if test "$name" !=3D "" && test "$name" !=3D "0"; then
-		$rm conftest
-		$LTCC $LTCFLAGS -o conftest conftest.c $i
-		# Did it work?
-		if test "$?" -eq 0 ; then
+	      case $i in
+	      -l*)
+		func_stripname -l '' "$i"
+		name=3D$func_stripname_result
+		$opt_dry_run || $RM conftest
+		if $LTCC $LTCFLAGS -o conftest conftest.c $i; then
 		  ldd_output=3D`ldd conftest`
 		  if test "X$allow_libtool_libs_with_static_runtimes" =3D "Xyes" ; then
 		    case " $predeps $postdeps " in
 		    *" $i "*)
-		      newdeplibs=3D"$newdeplibs $i"
+		      func_append newdeplibs " $i"
 		      i=3D""
 		      ;;
 		    esac
 		  fi
 		  if test -n "$i" ; then
-		    libname=3D`eval \\$echo \"$libname_spec\"`
-		    deplib_matches=3D`eval \\$echo \"$library_names_spec\"`
-		    set dummy $deplib_matches
-		    deplib_match=3D$2
+		    libname=3D`eval "\\$ECHO \"$libname_spec\""`
+		    deplib_matches=3D`eval "\\$ECHO \"$library_names_spec\""`
+		    set dummy $deplib_matches; shift
+		    deplib_match=3D$1
 		    if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then
-		      newdeplibs=3D"$newdeplibs $i"
+		      func_append newdeplibs " $i"
 		    else
 		      droppeddeps=3Dyes
-		      $echo
-		      $echo "*** Warning: dynamic linker does not accept needed library =
$i."
-		      $echo "*** I have the capability to make that library automaticall=
y link in when"
-		      $echo "*** you link to this library.  But I can only do this if yo=
u have a"
-		      $echo "*** shared version of the library, which you do not appear =
to have"
-		      $echo "*** because a test_compile did reveal that the linker did n=
ot use this one"
-		      $echo "*** as a dynamic dependency that programs can get resolved =
with at runtime."
+		      echo
+		      $ECHO "*** Warning: dynamic linker does not accept needed library =
$i."
+		      echo "*** I have the capability to make that library automatically=
 link in when"
+		      echo "*** you link to this library.  But I can only do this if you=
 have a"
+		      echo "*** shared version of the library, which you do not appear t=
o have"
+		      echo "*** because a test_compile did reveal that the linker did no=
t use this one"
+		      echo "*** as a dynamic dependency that programs can get resolved w=
ith at runtime."
 		    fi
 		  fi
 		else
 		  droppeddeps=3Dyes
-		  $echo
-		  $echo "*** Warning!  Library $i is needed by this library but I was no=
t able to"
-		  $echo "***  make it link in!  You will probably need to install it or =
some"
-		  $echo "*** library that it depends on before this library will be full=
y"
-		  $echo "*** functional.  Installing it before continuing would be even =
better."
+		  echo
+		  $ECHO "*** Warning!  Library $i is needed by this library but I was no=
t able to"
+		  echo "*** make it link in!  You will probably need to install it or so=
me"
+		  echo "*** library that it depends on before this library will be fully"
+		  echo "*** functional.  Installing it before continuing would be even b=
etter."
 		fi
-	      else
-		newdeplibs=3D"$newdeplibs $i"
-	      fi
+		;;
+	      *)
+		func_append newdeplibs " $i"
+		;;
+	      esac
 	    done
 	  fi
 	  ;;
 	file_magic*)
-	  set dummy $deplibs_check_method
-	  file_magic_regex=3D`expr "$deplibs_check_method" : "$2 \(.*\)"`
+	  set dummy $deplibs_check_method; shift
+	  file_magic_regex=3D`expr "$deplibs_check_method" : "$1 \(.*\)"`
 	  for a_deplib in $deplibs; do
-	    name=3D`expr $a_deplib : '-l\(.*\)'`
-	    # If $name is empty we are operating on a -L argument.
-            if test "$name" !=3D "" && test  "$name" !=3D "0"; then
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=3D$func_stripname_result
 	      if test "X$allow_libtool_libs_with_static_runtimes" =3D "Xyes" ; th=
en
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
-		  newdeplibs=3D"$newdeplibs $a_deplib"
+		  func_append newdeplibs " $a_deplib"
 		  a_deplib=3D""
 		  ;;
 		esac
 	      fi
 	      if test -n "$a_deplib" ; then
-		libname=3D`eval \\$echo \"$libname_spec\"`
+		libname=3D`eval "\\$ECHO \"$libname_spec\""`
+		if test -n "$file_magic_glob"; then
+		  libnameglob=3D`func_echo_all "$libname" | $SED -e $file_magic_glob`
+		else
+		  libnameglob=3D$libname
+		fi
+		test "$want_nocaseglob" =3D yes && nocaseglob=3D`shopt -p nocaseglob`
 		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
-		  potential_libs=3D`ls $i/$libname[.-]* 2>/dev/null`
+		  if test "$want_nocaseglob" =3D yes; then
+		    shopt -s nocaseglob
+		    potential_libs=3D`ls $i/$libnameglob[.-]* 2>/dev/null`
+		    $nocaseglob
+		  else
+		    potential_libs=3D`ls $i/$libnameglob[.-]* 2>/dev/null`
+		  fi
 		  for potent_lib in $potential_libs; do
 		      # Follow soft links.
-		      if ls -lLd "$potent_lib" 2>/dev/null \
-			 | grep " -> " >/dev/null; then
+		      if ls -lLd "$potent_lib" 2>/dev/null |
+			 $GREP " -> " >/dev/null; then
 			continue
 		      fi
 		      # The statement above tries to avoid entering an
@@ -3639,13 +7806,13 @@
 			potliblink=3D`ls -ld $potlib | ${SED} 's/.* -> //'`
 			case $potliblink in
 			[\\/]* | [A-Za-z]:[\\/]*) potlib=3D"$potliblink";;
-			*) potlib=3D`$echo "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";;
+			*) potlib=3D`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";;
 			esac
 		      done
-		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null \
-			 | ${SED} 10q \
-			 | $EGREP "$file_magic_regex" > /dev/null; then
-			newdeplibs=3D"$newdeplibs $a_deplib"
+		      if eval $file_magic_cmd \"\$potlib\" 2>/dev/null |
+			 $SED -e 10q |
+			 $EGREP "$file_magic_regex" > /dev/null; then
+			func_append newdeplibs " $a_deplib"
 			a_deplib=3D""
 			break 2
 		      fi
@@ -3654,50 +7821,52 @@
 	      fi
 	      if test -n "$a_deplib" ; then
 		droppeddeps=3Dyes
-		$echo
-		$echo "*** Warning: linker path does not have real file for library $a_d=
eplib."
-		$echo "*** I have the capability to make that library automatically link=
 in when"
-		$echo "*** you link to this library.  But I can only do this if you have=
 a"
-		$echo "*** shared version of the library, which you do not appear to hav=
e"
-		$echo "*** because I did check the linker path looking for a file starti=
ng"
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_d=
eplib."
+		echo "*** I have the capability to make that library automatically link =
in when"
+		echo "*** you link to this library.  But I can only do this if you have =
a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file startin=
g"
 		if test -z "$potlib" ; then
-		  $echo "*** with $libname but no candidates were found. (...for file ma=
gic test)"
+		  $ECHO "*** with $libname but no candidates were found. (...for file ma=
gic test)"
 		else
-		  $echo "*** with $libname and none of the candidates passed a file form=
at test"
-		  $echo "*** using a file magic. Last file checked: $potlib"
+		  $ECHO "*** with $libname and none of the candidates passed a file form=
at test"
+		  $ECHO "*** using a file magic. Last file checked: $potlib"
 		fi
 	      fi
-	    else
+	      ;;
+	    *)
 	      # Add a -L argument.
-	      newdeplibs=3D"$newdeplibs $a_deplib"
-	    fi
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
 	  done # Gone through all deplibs.
 	  ;;
 	match_pattern*)
-	  set dummy $deplibs_check_method
-	  match_pattern_regex=3D`expr "$deplibs_check_method" : "$2 \(.*\)"`
+	  set dummy $deplibs_check_method; shift
+	  match_pattern_regex=3D`expr "$deplibs_check_method" : "$1 \(.*\)"`
 	  for a_deplib in $deplibs; do
-	    name=3D`expr $a_deplib : '-l\(.*\)'`
-	    # If $name is empty we are operating on a -L argument.
-	    if test -n "$name" && test "$name" !=3D "0"; then
+	    case $a_deplib in
+	    -l*)
+	      func_stripname -l '' "$a_deplib"
+	      name=3D$func_stripname_result
 	      if test "X$allow_libtool_libs_with_static_runtimes" =3D "Xyes" ; th=
en
 		case " $predeps $postdeps " in
 		*" $a_deplib "*)
-		  newdeplibs=3D"$newdeplibs $a_deplib"
+		  func_append newdeplibs " $a_deplib"
 		  a_deplib=3D""
 		  ;;
 		esac
 	      fi
 	      if test -n "$a_deplib" ; then
-		libname=3D`eval \\$echo \"$libname_spec\"`
+		libname=3D`eval "\\$ECHO \"$libname_spec\""`
 		for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do
 		  potential_libs=3D`ls $i/$libname[.-]* 2>/dev/null`
 		  for potent_lib in $potential_libs; do
 		    potlib=3D"$potent_lib" # see symlink-check above in file_magic test
-		    if eval $echo \"$potent_lib\" 2>/dev/null \
-		        | ${SED} 10q \
-		        | $EGREP "$match_pattern_regex" > /dev/null; then
-		      newdeplibs=3D"$newdeplibs $a_deplib"
+		    if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \
+		       $EGREP "$match_pattern_regex" > /dev/null; then
+		      func_append newdeplibs " $a_deplib"
 		      a_deplib=3D""
 		      break 2
 		    fi
@@ -3706,46 +7875,48 @@
 	      fi
 	      if test -n "$a_deplib" ; then
 		droppeddeps=3Dyes
-		$echo
-		$echo "*** Warning: linker path does not have real file for library $a_d=
eplib."
-		$echo "*** I have the capability to make that library automatically link=
 in when"
-		$echo "*** you link to this library.  But I can only do this if you have=
 a"
-		$echo "*** shared version of the library, which you do not appear to hav=
e"
-		$echo "*** because I did check the linker path looking for a file starti=
ng"
+		echo
+		$ECHO "*** Warning: linker path does not have real file for library $a_d=
eplib."
+		echo "*** I have the capability to make that library automatically link =
in when"
+		echo "*** you link to this library.  But I can only do this if you have =
a"
+		echo "*** shared version of the library, which you do not appear to have"
+		echo "*** because I did check the linker path looking for a file startin=
g"
 		if test -z "$potlib" ; then
-		  $echo "*** with $libname but no candidates were found. (...for regex p=
attern test)"
+		  $ECHO "*** with $libname but no candidates were found. (...for regex p=
attern test)"
 		else
-		  $echo "*** with $libname and none of the candidates passed a file form=
at test"
-		  $echo "*** using a regex pattern. Last file checked: $potlib"
+		  $ECHO "*** with $libname and none of the candidates passed a file form=
at test"
+		  $ECHO "*** using a regex pattern. Last file checked: $potlib"
 		fi
 	      fi
-	    else
+	      ;;
+	    *)
 	      # Add a -L argument.
-	      newdeplibs=3D"$newdeplibs $a_deplib"
-	    fi
+	      func_append newdeplibs " $a_deplib"
+	      ;;
+	    esac
 	  done # Gone through all deplibs.
 	  ;;
 	none | unknown | *)
 	  newdeplibs=3D""
-	  tmp_deplibs=3D`$echo "X $deplibs" | $Xsed -e 's/ -lc$//' \
-	    -e 's/ -[LR][^ ]*//g'`
+	  tmp_deplibs=3D`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`
 	  if test "X$allow_libtool_libs_with_static_runtimes" =3D "Xyes" ; then
 	    for i in $predeps $postdeps ; do
 	      # can't use Xsed below, because $i might contain '/'
-	      tmp_deplibs=3D`$echo "X $tmp_deplibs" | ${SED} -e "1s,^X,," -e "s,$=
i,,"`
+	      tmp_deplibs=3D`$ECHO " $tmp_deplibs" | $SED "s,$i,,"`
 	    done
 	  fi
-	  if $echo "X $tmp_deplibs" | $Xsed -e 's/[ 	]//g' \
-	    | grep . >/dev/null; then
-	    $echo
+	  case $tmp_deplibs in
+	  *[!\	\ ]*)
+	    echo
 	    if test "X$deplibs_check_method" =3D "Xnone"; then
-	      $echo "*** Warning: inter-library dependencies are not supported in=
 this platform."
+	      echo "*** Warning: inter-library dependencies are not supported in =
this platform."
 	    else
-	      $echo "*** Warning: inter-library dependencies are not known to be =
supported."
+	      echo "*** Warning: inter-library dependencies are not known to be s=
upported."
 	    fi
-	    $echo "*** All declared inter-library dependencies are being dropped."
+	    echo "*** All declared inter-library dependencies are being dropped."
 	    droppeddeps=3Dyes
-	  fi
+	    ;;
+	  esac
 	  ;;
 	esac
 	versuffix=3D$versuffix_save
@@ -3756,24 +7927,24 @@
=20
 	case $host in
 	*-*-rhapsody* | *-*-darwin1.[012])
-	  # On Rhapsody replace the C library is the System framework
-	  newdeplibs=3D`$echo "X $newdeplibs" | $Xsed -e 's/ -lc / -framework Sys=
tem /'`
+	  # On Rhapsody replace the C library with the System framework
+	  newdeplibs=3D`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework =
/'`
 	  ;;
 	esac
=20
 	if test "$droppeddeps" =3D yes; then
 	  if test "$module" =3D yes; then
-	    $echo
-	    $echo "*** Warning: libtool could not satisfy all declared inter-libr=
ary"
-	    $echo "*** dependencies of module $libname.  Therefore, libtool will =
create"
-	    $echo "*** a static module, that should work as long as the dlopening"
-	    $echo "*** application is linked with the -dlopen flag."
+	    echo
+	    echo "*** Warning: libtool could not satisfy all declared inter-libra=
ry"
+	    $ECHO "*** dependencies of module $libname.  Therefore, libtool will =
create"
+	    echo "*** a static module, that should work as long as the dlopening"
+	    echo "*** application is linked with the -dlopen flag."
 	    if test -z "$global_symbol_pipe"; then
-	      $echo
-	      $echo "*** However, this would only work if libtool was able to ext=
ract symbol"
-	      $echo "*** lists from a program, using \`nm' or equivalent, but lib=
tool could"
-	      $echo "*** not find such a program.  So, this module is probably us=
eless."
-	      $echo "*** \`nm' from GNU binutils and a full rebuild may help."
+	      echo
+	      echo "*** However, this would only work if libtool was able to extr=
act symbol"
+	      echo "*** lists from a program, using \`nm' or equivalent, but libt=
ool could"
+	      echo "*** not find such a program.  So, this module is probably use=
less."
+	      echo "*** \`nm' from GNU binutils and a full rebuild may help."
 	    fi
 	    if test "$build_old_libs" =3D no; then
 	      oldlibs=3D"$output_objdir/$libname.$libext"
@@ -3783,16 +7954,16 @@
 	      build_libtool_libs=3Dno
 	    fi
 	  else
-	    $echo "*** The inter-library dependencies that have been dropped here=
 will be"
-	    $echo "*** automatically added whenever a program is linked with this=
 library"
-	    $echo "*** or is declared to -dlopen it."
+	    echo "*** The inter-library dependencies that have been dropped here =
will be"
+	    echo "*** automatically added whenever a program is linked with this =
library"
+	    echo "*** or is declared to -dlopen it."
=20
 	    if test "$allow_undefined" =3D no; then
-	      $echo
-	      $echo "*** Since this library must not contain undefined symbols,"
-	      $echo "*** because either the platform does not support them or"
-	      $echo "*** it was explicitly requested with -no-undefined,"
-	      $echo "*** libtool will only create a static version of it."
+	      echo
+	      echo "*** Since this library must not contain undefined symbols,"
+	      echo "*** because either the platform does not support them or"
+	      echo "*** it was explicitly requested with -no-undefined,"
+	      echo "*** libtool will only create a static version of it."
 	      if test "$build_old_libs" =3D no; then
 		oldlibs=3D"$output_objdir/$libname.$libext"
 		build_libtool_libs=3Dmodule
@@ -3806,7 +7977,14 @@
 	# Done checking deplibs!
 	deplibs=3D$newdeplibs
       fi
-
+      # Time to change all our "foo.ltframework" stuff back to "-framework=
 foo"
+      case $host in
+	*-*-darwin*)
+	  newdeplibs=3D`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -=
framework \1%g'`
+	  new_inherited_linker_flags=3D`$ECHO " $new_inherited_linker_flags" | $S=
ED 's% \([^ $]*\).ltframework% -framework \1%g'`
+	  deplibs=3D`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framew=
ork \1%g'`
+	  ;;
+      esac
=20
       # move library search paths that coincide with paths to not yet
       # installed libraries to the beginning of the library search list
@@ -3817,7 +7995,7 @@
 	*)
 	  case " $deplibs " in
 	  *" -L$path/$objdir "*)
-	    new_libs=3D"$new_libs -L$path/$objdir" ;;
+	    func_append new_libs " -L$path/$objdir" ;;
 	  esac
 	  ;;
 	esac
@@ -3827,15 +8005,14 @@
 	-L*)
 	  case " $new_libs " in
 	  *" $deplib "*) ;;
-	  *) new_libs=3D"$new_libs $deplib" ;;
+	  *) func_append new_libs " $deplib" ;;
 	  esac
 	  ;;
-	*) new_libs=3D"$new_libs $deplib" ;;
+	*) func_append new_libs " $deplib" ;;
 	esac
       done
       deplibs=3D"$new_libs"
=20
-
       # All the library-specific variables (install_libdir is set above).
       library_names=3D
       old_library=3D
@@ -3848,10 +8025,12 @@
 	  hardcode_libdirs=3D
 	  dep_rpath=3D
 	  rpath=3D"$finalize_rpath"
-	  test "$mode" !=3D relink && rpath=3D"$compile_rpath$rpath"
+	  test "$opt_mode" !=3D relink && rpath=3D"$compile_rpath$rpath"
 	  for libdir in $rpath; do
 	    if test -n "$hardcode_libdir_flag_spec"; then
 	      if test -n "$hardcode_libdir_separator"; then
+		func_replace_sysroot "$libdir"
+		libdir=3D$func_replace_sysroot_result
 		if test -z "$hardcode_libdirs"; then
 		  hardcode_libdirs=3D"$libdir"
 		else
@@ -3860,18 +8039,18 @@
 		  *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
 		    ;;
 		  *)
-		    hardcode_libdirs=3D"$hardcode_libdirs$hardcode_libdir_separator$libd=
ir"
+		    func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		    ;;
 		  esac
 		fi
 	      else
 		eval flag=3D\"$hardcode_libdir_flag_spec\"
-		dep_rpath=3D"$dep_rpath $flag"
+		func_append dep_rpath " $flag"
 	      fi
 	    elif test -n "$runpath_var"; then
 	      case "$perm_rpath " in
 	      *" $libdir "*) ;;
-	      *) perm_rpath=3D"$perm_rpath $libdir" ;;
+	      *) func_apped perm_rpath " $libdir" ;;
 	      esac
 	    fi
 	  done
@@ -3889,7 +8068,7 @@
 	    # We should set the runpath_var.
 	    rpath=3D
 	    for dir in $perm_rpath; do
-	      rpath=3D"$rpath$dir:"
+	      func_append rpath "$dir:"
 	    done
 	    eval "$runpath_var=3D'$rpath\$$runpath_var'; export $runpath_var"
 	  fi
@@ -3897,7 +8076,7 @@
 	fi
=20
 	shlibpath=3D"$finalize_shlibpath"
-	test "$mode" !=3D relink && shlibpath=3D"$compile_shlibpath$shlibpath"
+	test "$opt_mode" !=3D relink && shlibpath=3D"$compile_shlibpath$shlibpath"
 	if test -n "$shlibpath"; then
 	  eval "$shlibpath_var=3D'$shlibpath\$$shlibpath_var'; export $shlibpath_=
var"
 	fi
@@ -3906,8 +8085,9 @@
 	eval shared_ext=3D\"$shrext_cmds\"
 	eval library_names=3D\"$library_names_spec\"
 	set dummy $library_names
-	realname=3D"$2"
-	shift; shift
+	shift
+	realname=3D"$1"
+	shift
=20
 	if test -n "$soname_spec"; then
 	  eval soname=3D\"$soname_spec\"
@@ -3922,83 +8102,166 @@
 	linknames=3D
 	for link
 	do
-	  linknames=3D"$linknames $link"
+	  func_append linknames " $link"
 	done
=20
 	# Use standard objects if they are pic
-	test -z "$pic_flag" && libobjs=3D`$echo "X$libobjs" | $SP2NL | $Xsed -e "=
$lo2o" | $NL2SP`
+	test -z "$pic_flag" && libobjs=3D`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o=
" | $NL2SP`
+	test "X$libobjs" =3D "X " && libobjs=3D
+
+	delfiles=3D
+	if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	  $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp"
+	  export_symbols=3D"$output_objdir/$libname.uexp"
+	  func_append delfiles " $export_symbols"
+	fi
+
+	orig_export_symbols=3D
+	case $host_os in
+	cygwin* | mingw* | cegcc*)
+	  if test -n "$export_symbols" && test -z "$export_symbols_regex"; then
+	    # exporting using user supplied symfile
+	    if test "x`$SED 1q $export_symbols`" !=3D xEXPORTS; then
+	      # and it's NOT already a .def file. Must figure out
+	      # which of the given symbols are data symbols and tag
+	      # them as such. So, trigger use of export_symbols_cmds.
+	      # export_symbols gets reassigned inside the "prepare
+	      # the list of exported symbols" if statement, so the
+	      # include_expsyms logic still works.
+	      orig_export_symbols=3D"$export_symbols"
+	      export_symbols=3D
+	      always_export_symbols=3Dyes
+	    fi
+	  fi
+	  ;;
+	esac
=20
 	# Prepare the list of exported symbols
 	if test -z "$export_symbols"; then
 	  if test "$always_export_symbols" =3D yes || test -n "$export_symbols_re=
gex"; then
-	    $show "generating symbol list for \`$libname.la'"
+	    func_verbose "generating symbol list for \`$libname.la'"
 	    export_symbols=3D"$output_objdir/$libname.exp"
-	    $run $rm $export_symbols
+	    $opt_dry_run || $RM $export_symbols
 	    cmds=3D$export_symbols_cmds
 	    save_ifs=3D"$IFS"; IFS=3D'~'
-	    for cmd in $cmds; do
+	    for cmd1 in $cmds; do
 	      IFS=3D"$save_ifs"
-	      eval cmd=3D\"$cmd\"
-	      if len=3D`expr "X$cmd" : ".*"` &&
-	       test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
-	        $show "$cmd"
-	        $run eval "$cmd" || exit $?
-	        skipped_export=3Dfalse
+	      # Take the normal branch if the nm_file_list_spec branch
+	      # doesn't work or if tool conversion is not needed.
+	      case $nm_file_list_spec~$to_tool_file_cmd in
+		*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)
+		  try_normal_branch=3Dyes
+		  eval cmd=3D\"$cmd1\"
+		  func_len " $cmd"
+		  len=3D$func_len_result
+		  ;;
+		*)
+		  try_normal_branch=3Dno
+		  ;;
+	      esac
+	      if test "$try_normal_branch" =3D yes \
+		 && { test "$len" -lt "$max_cmd_len" \
+		      || test "$max_cmd_len" -le -1; }
+	      then
+		func_show_eval "$cmd" 'exit $?'
+		skipped_export=3Dfalse
+	      elif test -n "$nm_file_list_spec"; then
+		func_basename "$output"
+		output_la=3D$func_basename_result
+		save_libobjs=3D$libobjs
+		save_output=3D$output
+		output=3D${output_objdir}/${output_la}.nm
+		func_to_tool_file "$output"
+		libobjs=3D$nm_file_list_spec$func_to_tool_file_result
+		func_append delfiles " $output"
+		func_verbose "creating $NM input file list: $output"
+		for obj in $save_libobjs; do
+		  func_to_tool_file "$obj"
+		  $ECHO "$func_to_tool_file_result"
+		done > "$output"
+		eval cmd=3D\"$cmd1\"
+		func_show_eval "$cmd" 'exit $?'
+		output=3D$save_output
+		libobjs=3D$save_libobjs
+		skipped_export=3Dfalse
 	      else
-	        # The command line is too long to execute in one step.
-	        $show "using reloadable object file for export list..."
-	        skipped_export=3D:
+		# The command line is too long to execute in one step.
+		func_verbose "using reloadable object file for export list..."
+		skipped_export=3D:
 		# Break out early, otherwise skipped_export may be
 		# set to false by a later but shorter cmd.
 		break
 	      fi
 	    done
 	    IFS=3D"$save_ifs"
-	    if test -n "$export_symbols_regex"; then
-	      $show "$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"=
${export_symbols}T\""
-	      $run eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "$=
{export_symbols}T"'
-	      $show "$mv \"${export_symbols}T\" \"$export_symbols\""
-	      $run eval '$mv "${export_symbols}T" "$export_symbols"'
+	    if test -n "$export_symbols_regex" && test "X$skipped_export" !=3D "X=
:"; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols"=
 > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
 	    fi
 	  fi
 	fi
=20
 	if test -n "$export_symbols" && test -n "$include_expsyms"; then
-	  $run eval '$echo "X$include_expsyms" | $SP2NL >> "$export_symbols"'
+	  tmp_export_symbols=3D"$export_symbols"
+	  test -n "$orig_export_symbols" && tmp_export_symbols=3D"$orig_export_sy=
mbols"
+	  $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export=
_symbols"'
+	fi
+
+	if test "X$skipped_export" !=3D "X:" && test -n "$orig_export_symbols"; t=
hen
+	  # The given exports_symbols file has to be filtered, so filter it.
+	  func_verbose "filter symbol list for \`$libname.la' to tag DATA exports"
+	  # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	  # 's' commands which not all seds can handle. GNU sed should be fine
+	  # though. Also, the filter scales superlinearly with the number of
+	  # global variables. join(1) would be nice here, but unfortunately
+	  # isn't a blessed tool.
+	  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,=
' < $export_symbols > $output_objdir/$libname.filter
+	  func_append delfiles " $export_symbols $output_objdir/$libname.filter"
+	  export_symbols=3D$output_objdir/$libname.def
+	  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_s=
ymbols > $export_symbols
 	fi
=20
 	tmp_deplibs=3D
 	for test_deplib in $deplibs; do
-		case " $convenience " in
-		*" $test_deplib "*) ;;
-		*)
-			tmp_deplibs=3D"$tmp_deplibs $test_deplib"
-			;;
-		esac
+	  case " $convenience " in
+	  *" $test_deplib "*) ;;
+	  *)
+	    func_append tmp_deplibs " $test_deplib"
+	    ;;
+	  esac
 	done
 	deplibs=3D"$tmp_deplibs"
=20
 	if test -n "$convenience"; then
+	  if test -n "$whole_archive_flag_spec" &&
+	    test "$compiler_needs_object" =3D yes &&
+	    test -z "$libobjs"; then
+	    # extract the archives, so we have objects to list.
+	    # TODO: could optimize this to just extract one archive.
+	    whole_archive_flag_spec=3D
+	  fi
 	  if test -n "$whole_archive_flag_spec"; then
 	    save_libobjs=3D$libobjs
 	    eval libobjs=3D\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" =3D "X " && libobjs=3D
 	  else
 	    gentop=3D"$output_objdir/${outputname}x"
-	    generated=3D"$generated $gentop"
+	    func_append generated " $gentop"
=20
 	    func_extract_archives $gentop $convenience
-	    libobjs=3D"$libobjs $func_extract_archives_result"
+	    func_append libobjs " $func_extract_archives_result"
+	    test "X$libobjs" =3D "X " && libobjs=3D
 	  fi
 	fi
-=09
+
 	if test "$thread_safe" =3D yes && test -n "$thread_safe_flag_spec"; then
 	  eval flag=3D\"$thread_safe_flag_spec\"
-	  linker_flags=3D"$linker_flags $flag"
+	  func_append linker_flags " $flag"
 	fi
=20
 	# Make a backup of the uninstalled library when relinking
-	if test "$mode" =3D relink; then
-	  $run eval '(cd $output_objdir && $rm ${realname}U && $mv $realname ${re=
alname}U)' || exit $?
+	if test "$opt_mode" =3D relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $re=
alname ${realname}U)' || exit $?
 	fi
=20
 	# Do each of the archive commands.
@@ -4011,22 +8274,24 @@
 	    cmds=3D$module_cmds
 	  fi
 	else
-	if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
-	  eval test_cmds=3D\"$archive_expsym_cmds\"
-	  cmds=3D$archive_expsym_cmds
-	else
-	  eval test_cmds=3D\"$archive_cmds\"
-	  cmds=3D$archive_cmds
+	  if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	    eval test_cmds=3D\"$archive_expsym_cmds\"
+	    cmds=3D$archive_expsym_cmds
+	  else
+	    eval test_cmds=3D\"$archive_cmds\"
+	    cmds=3D$archive_cmds
 	  fi
 	fi
=20
 	if test "X$skipped_export" !=3D "X:" &&
-	   len=3D`expr "X$test_cmds" : ".*" 2>/dev/null` &&
-	   test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	   func_len " $test_cmds" &&
+	   len=3D$func_len_result &&
+	   test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
 	  :
 	else
-	  # The command line is too long to link in one step, link piecewise.
-	  $echo "creating reloadable object files..."
+	  # The command line is too long to link in one step, link piecewise
+	  # or, if using GNU ld and skipped_export is not :, use a linker
+	  # script.
=20
 	  # Save the value of $output and $libobjs because we want to
 	  # use them later.  If we have whole_archive_flag_spec, we
@@ -4040,77 +8305,171 @@
 	    save_libobjs=3D$libobjs
 	  fi
 	  save_output=3D$output
-	  output_la=3D`$echo "X$output" | $Xsed -e "$basename"`
+	  func_basename "$output"
+	  output_la=3D$func_basename_result
=20
 	  # Clear the reloadable object creation command queue and
 	  # initialize k to one.
 	  test_cmds=3D
 	  concat_cmds=3D
 	  objlist=3D
-	  delfiles=3D
 	  last_robj=3D
 	  k=3D1
-	  output=3D$output_objdir/$output_la-${k}.$objext
-	  # Loop over the list of objects to be linked.
-	  for obj in $save_libobjs
-	  do
-	    eval test_cmds=3D\"$reload_cmds $objlist $last_robj\"
-	    if test "X$objlist" =3D X ||
-	       { len=3D`expr "X$test_cmds" : ".*" 2>/dev/null` &&
-		 test "$len" -le "$max_cmd_len"; }; then
-	      objlist=3D"$objlist $obj"
+
+	  if test -n "$save_libobjs" && test "X$skipped_export" !=3D "X:" && test=
 "$with_gnu_ld" =3D yes; then
+	    output=3D${output_objdir}/${output_la}.lnkscript
+	    func_verbose "creating GNU ld script: $output"
+	    echo 'INPUT (' > $output
+	    for obj in $save_libobjs
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    echo ')' >> $output
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=3D$func_to_tool_file_result
+	  elif test -n "$save_libobjs" && test "X$skipped_export" !=3D "X:" && te=
st "X$file_list_spec" !=3D X; then
+	    output=3D${output_objdir}/${output_la}.lnk
+	    func_verbose "creating linker input file list: $output"
+	    : > $output
+	    set x $save_libobjs
+	    shift
+	    firstobj=3D
+	    if test "$compiler_needs_object" =3D yes; then
+	      firstobj=3D"$1 "
+	      shift
+	    fi
+	    for obj
+	    do
+	      func_to_tool_file "$obj"
+	      $ECHO "$func_to_tool_file_result" >> $output
+	    done
+	    func_append delfiles " $output"
+	    func_to_tool_file "$output"
+	    output=3D$firstobj\"$file_list_spec$func_to_tool_file_result\"
+	  else
+	    if test -n "$save_libobjs"; then
+	      func_verbose "creating reloadable object files..."
+	      output=3D$output_objdir/$output_la-${k}.$objext
+	      eval test_cmds=3D\"$reload_cmds\"
+	      func_len " $test_cmds"
+	      len0=3D$func_len_result
+	      len=3D$len0
+
+	      # Loop over the list of objects to be linked.
+	      for obj in $save_libobjs
+	      do
+		func_len " $obj"
+		func_arith $len + $func_len_result
+		len=3D$func_arith_result
+		if test "X$objlist" =3D X ||
+		   test "$len" -lt "$max_cmd_len"; then
+		  func_append objlist " $obj"
+		else
+		  # The command $test_cmds is almost too long, add a
+		  # command to the queue.
+		  if test "$k" -eq 1 ; then
+		    # The first file doesn't have a previous command to add.
+		    reload_objs=3D$objlist
+		    eval concat_cmds=3D\"$reload_cmds\"
+		  else
+		    # All subsequent reloadable object files will link in
+		    # the last one created.
+		    reload_objs=3D"$objlist $last_robj"
+		    eval concat_cmds=3D\"\$concat_cmds~$reload_cmds~\$RM $last_robj\"
+		  fi
+		  last_robj=3D$output_objdir/$output_la-${k}.$objext
+		  func_arith $k + 1
+		  k=3D$func_arith_result
+		  output=3D$output_objdir/$output_la-${k}.$objext
+		  objlist=3D" $obj"
+		  func_len " $last_robj"
+		  func_arith $len0 + $func_len_result
+		  len=3D$func_arith_result
+		fi
+	      done
+	      # Handle the remaining objects by creating one last
+	      # reloadable object file.  All subsequent reloadable object
+	      # files will link in the last one created.
+	      test -z "$concat_cmds" || concat_cmds=3D$concat_cmds~
+	      reload_objs=3D"$objlist $last_robj"
+	      eval concat_cmds=3D\"\${concat_cmds}$reload_cmds\"
+	      if test -n "$last_robj"; then
+	        eval concat_cmds=3D\"\${concat_cmds}~\$RM $last_robj\"
+	      fi
+	      func_append delfiles " $output"
+
 	    else
-	      # The command $test_cmds is almost too long, add a
-	      # command to the queue.
-	      if test "$k" -eq 1 ; then
-		# The first file doesn't have a previous command to add.
-		eval concat_cmds=3D\"$reload_cmds $objlist $last_robj\"
-	      else
-		# All subsequent reloadable object files will link in
-		# the last one created.
-		eval concat_cmds=3D\"\$concat_cmds~$reload_cmds $objlist $last_robj\"
+	      output=3D
+	    fi
+
+	    if ${skipped_export-false}; then
+	      func_verbose "generating symbol list for \`$libname.la'"
+	      export_symbols=3D"$output_objdir/$libname.exp"
+	      $opt_dry_run || $RM $export_symbols
+	      libobjs=3D$output
+	      # Append the command to create the export file.
+	      test -z "$concat_cmds" || concat_cmds=3D$concat_cmds~
+	      eval concat_cmds=3D\"\$concat_cmds$export_symbols_cmds\"
+	      if test -n "$last_robj"; then
+		eval concat_cmds=3D\"\$concat_cmds~\$RM $last_robj\"
 	      fi
-	      last_robj=3D$output_objdir/$output_la-${k}.$objext
-	      k=3D`expr $k + 1`
-	      output=3D$output_objdir/$output_la-${k}.$objext
-	      objlist=3D$obj
-	      len=3D1
 	    fi
-	  done
-	  # Handle the remaining objects by creating one last
-	  # reloadable object file.  All subsequent reloadable object
-	  # files will link in the last one created.
-	  test -z "$concat_cmds" || concat_cmds=3D$concat_cmds~
-	  eval concat_cmds=3D\"\${concat_cmds}$reload_cmds $objlist $last_robj\"
-
-	  if ${skipped_export-false}; then
-	    $show "generating symbol list for \`$libname.la'"
-	    export_symbols=3D"$output_objdir/$libname.exp"
-	    $run $rm $export_symbols
-	    libobjs=3D$output
-	    # Append the command to create the export file.
-	    eval concat_cmds=3D\"\$concat_cmds~$export_symbols_cmds\"
-          fi
-
-	  # Set up a command to remove the reloadable object files
-	  # after they are used.
-	  i=3D0
-	  while test "$i" -lt "$k"
-	  do
-	    i=3D`expr $i + 1`
-	    delfiles=3D"$delfiles $output_objdir/$output_la-${i}.$objext"
-	  done
-
-	  $echo "creating a temporary reloadable object file: $output"
-
-	  # Loop through the commands generated above and execute them.
-	  save_ifs=3D"$IFS"; IFS=3D'~'
-	  for cmd in $concat_cmds; do
+
+	    test -n "$save_libobjs" &&
+	      func_verbose "creating a temporary reloadable object file: $output"
+
+	    # Loop through the commands generated above and execute them.
+	    save_ifs=3D"$IFS"; IFS=3D'~'
+	    for cmd in $concat_cmds; do
+	      IFS=3D"$save_ifs"
+	      $opt_silent || {
+		  func_quote_for_expand "$cmd"
+		  eval "func_echo $func_quote_for_expand_result"
+	      }
+	      $opt_dry_run || eval "$cmd" || {
+		lt_exit=3D$?
+
+		# Restore the uninstalled library and exit
+		if test "$opt_mode" =3D relink; then
+		  ( cd "$output_objdir" && \
+		    $RM "${realname}T" && \
+		    $MV "${realname}U" "$realname" )
+		fi
+
+		exit $lt_exit
+	      }
+	    done
 	    IFS=3D"$save_ifs"
-	    $show "$cmd"
-	    $run eval "$cmd" || exit $?
-	  done
-	  IFS=3D"$save_ifs"
+
+	    if test -n "$export_symbols_regex" && ${skipped_export-false}; then
+	      func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols"=
 > "${export_symbols}T"'
+	      func_show_eval '$MV "${export_symbols}T" "$export_symbols"'
+	    fi
+	  fi
+
+          if ${skipped_export-false}; then
+	    if test -n "$export_symbols" && test -n "$include_expsyms"; then
+	      tmp_export_symbols=3D"$export_symbols"
+	      test -n "$orig_export_symbols" && tmp_export_symbols=3D"$orig_expor=
t_symbols"
+	      $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_ex=
port_symbols"'
+	    fi
+
+	    if test -n "$orig_export_symbols"; then
+	      # The given exports_symbols file has to be filtered, so filter it.
+	      func_verbose "filter symbol list for \`$libname.la' to tag DATA exp=
orts"
+	      # FIXME: $output_objdir/$libname.filter potentially contains lots of
+	      # 's' commands which not all seds can handle. GNU sed should be fine
+	      # though. Also, the filter scales superlinearly with the number of
+	      # global variables. join(1) would be nice here, but unfortunately
+	      # isn't a blessed tool.
+	      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1=
\2|,' < $export_symbols > $output_objdir/$libname.filter
+	      func_append delfiles " $export_symbols $output_objdir/$libname.filt=
er"
+	      export_symbols=3D$output_objdir/$libname.def
+	      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_expo=
rt_symbols > $export_symbols
+	    fi
+	  fi
=20
 	  libobjs=3D$output
 	  # Restore the value of output.
@@ -4118,6 +8477,7 @@
=20
 	  if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then
 	    eval libobjs=3D\"\$libobjs $whole_archive_flag_spec\"
+	    test "X$libobjs" =3D "X " && libobjs=3D
 	  fi
 	  # Expand the library linking commands again to reset the
 	  # value of $libobjs for piecewise linking.
@@ -4130,28 +8490,45 @@
 	      cmds=3D$module_cmds
 	    fi
 	  else
-	  if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
-	    cmds=3D$archive_expsym_cmds
-	  else
-	    cmds=3D$archive_cmds
+	    if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then
+	      cmds=3D$archive_expsym_cmds
+	    else
+	      cmds=3D$archive_cmds
 	    fi
 	  fi
-
-	  # Append the command to remove the reloadable object files
-	  # to the just-reset $cmds.
-	  eval cmds=3D\"\$cmds~\$rm $delfiles\"
 	fi
+
+	if test -n "$delfiles"; then
+	  # Append the command to remove temporary files to $cmds.
+	  eval cmds=3D\"\$cmds~\$RM $delfiles\"
+	fi
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop=3D"$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append libobjs " $func_extract_archives_result"
+	  test "X$libobjs" =3D "X " && libobjs=3D
+	fi
+
 	save_ifs=3D"$IFS"; IFS=3D'~'
 	for cmd in $cmds; do
 	  IFS=3D"$save_ifs"
 	  eval cmd=3D\"$cmd\"
-	  $show "$cmd"
-	  $run eval "$cmd" || {
+	  $opt_silent || {
+	    func_quote_for_expand "$cmd"
+	    eval "func_echo $func_quote_for_expand_result"
+	  }
+	  $opt_dry_run || eval "$cmd" || {
 	    lt_exit=3D$?
=20
 	    # Restore the uninstalled library and exit
-	    if test "$mode" =3D relink; then
-	      $run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname=
}U $realname)'
+	    if test "$opt_mode" =3D relink; then
+	      ( cd "$output_objdir" && \
+	        $RM "${realname}T" && \
+		$MV "${realname}U" "$realname" )
 	    fi
=20
 	    exit $lt_exit
@@ -4160,13 +8537,12 @@
 	IFS=3D"$save_ifs"
=20
 	# Restore the uninstalled library and exit
-	if test "$mode" =3D relink; then
-	  $run eval '(cd $output_objdir && $rm ${realname}T && $mv $realname ${re=
alname}T && $mv "$realname"U $realname)' || exit $?
+	if test "$opt_mode" =3D relink; then
+	  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $re=
alname ${realname}T && $MV ${realname}U $realname)' || exit $?
=20
 	  if test -n "$convenience"; then
 	    if test -z "$whole_archive_flag_spec"; then
-	      $show "${rm}r $gentop"
-	      $run ${rm}r "$gentop"
+	      func_show_eval '${RM}r "$gentop"'
 	    fi
 	  fi
=20
@@ -4176,8 +8552,7 @@
 	# Create links to the real library.
 	for linkname in $linknames; do
 	  if test "$realname" !=3D "$linkname"; then
-	    $show "(cd $output_objdir && $rm $linkname && $LN_S $realname $linkna=
me)"
-	    $run eval '(cd $output_objdir && $rm $linkname && $LN_S $realname $li=
nkname)' || exit $?
+	    func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$re=
alname" "$linkname")' 'exit $?'
 	  fi
 	done
=20
@@ -4190,38 +8565,35 @@
       ;;
=20
     obj)
-      if test -n "$deplibs"; then
-	$echo "$modename: warning: \`-l' and \`-L' are ignored for objects" 1>&2
+      if test -n "$dlfiles$dlprefiles" || test "$dlself" !=3D no; then
+	func_warning "\`-dlopen' is ignored for objects"
       fi
=20
-      if test -n "$dlfiles$dlprefiles" || test "$dlself" !=3D no; then
-	$echo "$modename: warning: \`-dlopen' is ignored for objects" 1>&2
-      fi
-
-      if test -n "$rpath"; then
-	$echo "$modename: warning: \`-rpath' is ignored for objects" 1>&2
-      fi
-
-      if test -n "$xrpath"; then
-	$echo "$modename: warning: \`-R' is ignored for objects" 1>&2
-      fi
-
-      if test -n "$vinfo"; then
-	$echo "$modename: warning: \`-version-info' is ignored for objects" 1>&2
-      fi
-
-      if test -n "$release"; then
-	$echo "$modename: warning: \`-release' is ignored for objects" 1>&2
-      fi
+      case " $deplibs" in
+      *\ -l* | *\ -L*)
+	func_warning "\`-l' and \`-L' are ignored for objects" ;;
+      esac
+
+      test -n "$rpath" && \
+	func_warning "\`-rpath' is ignored for objects"
+
+      test -n "$xrpath" && \
+	func_warning "\`-R' is ignored for objects"
+
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for objects"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for objects"
=20
       case $output in
       *.lo)
-	if test -n "$objs$old_deplibs"; then
-	  $echo "$modename: cannot build library object \`$output' from non-libto=
ol objects" 1>&2
-	  exit $EXIT_FAILURE
-	fi
-	libobj=3D"$output"
-	obj=3D`$echo "X$output" | $Xsed -e "$lo2o"`
+	test -n "$objs$old_deplibs" && \
+	  func_fatal_error "cannot build library object \`$output' from non-libto=
ol objects"
+
+	libobj=3D$output
+	func_lo2o "$libobj"
+	obj=3D$func_lo2o_result
 	;;
       *)
 	libobj=3D
@@ -4230,7 +8602,7 @@
       esac
=20
       # Delete the old objects.
-      $run $rm $obj $libobj
+      $opt_dry_run || $RM $obj $libobj
=20
       # Objects from convenience libraries.  This assumes
       # single-version convenience libraries.  Whenever we create
@@ -4239,40 +8611,36 @@
       reload_conv_objs=3D
       gentop=3D
       # reload_cmds runs $LD directly, so let us get rid of
-      # -Wl from whole_archive_flag_spec
+      # -Wl from whole_archive_flag_spec and hope we can get by with
+      # turning comma into space..
       wl=3D
=20
       if test -n "$convenience"; then
 	if test -n "$whole_archive_flag_spec"; then
-	  eval reload_conv_objs=3D\"\$reload_objs $whole_archive_flag_spec\"
+	  eval tmp_whole_archive_flags=3D\"$whole_archive_flag_spec\"
+	  reload_conv_objs=3D$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $S=
ED 's|,| |g'`
 	else
 	  gentop=3D"$output_objdir/${obj}x"
-	  generated=3D"$generated $gentop"
+	  func_append generated " $gentop"
=20
 	  func_extract_archives $gentop $convenience
 	  reload_conv_objs=3D"$reload_objs $func_extract_archives_result"
 	fi
       fi
=20
+      # If we're not building shared, we need to use non_pic_objs
+      test "$build_libtool_libs" !=3D yes && libobjs=3D"$non_pic_objects"
+
       # Create the old-style object.
-      reload_objs=3D"$objs$old_deplibs "`$echo "X$libobjs" | $SP2NL | $Xse=
d -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_=
objs" ### testsuite: skip nested quoting test
+      reload_objs=3D"$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED =
"/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### tests=
uite: skip nested quoting test
=20
       output=3D"$obj"
-      cmds=3D$reload_cmds
-      save_ifs=3D"$IFS"; IFS=3D'~'
-      for cmd in $cmds; do
-	IFS=3D"$save_ifs"
-	eval cmd=3D\"$cmd\"
-	$show "$cmd"
-	$run eval "$cmd" || exit $?
-      done
-      IFS=3D"$save_ifs"
+      func_execute_cmds "$reload_cmds" 'exit $?'
=20
       # Exit if we aren't doing a library object file.
       if test -z "$libobj"; then
 	if test -n "$gentop"; then
-	  $show "${rm}r $gentop"
-	  $run ${rm}r $gentop
+	  func_show_eval '${RM}r "$gentop"'
 	fi
=20
 	exit $EXIT_SUCCESS
@@ -4280,14 +8648,13 @@
=20
       if test "$build_libtool_libs" !=3D yes; then
 	if test -n "$gentop"; then
-	  $show "${rm}r $gentop"
-	  $run ${rm}r $gentop
+	  func_show_eval '${RM}r "$gentop"'
 	fi
=20
 	# Create an invalid libtool object if no PIC, so that we don't
 	# accidentally link it into a program.
 	# $show "echo timestamp > $libobj"
-	# $run eval "echo timestamp > $libobj" || exit $?
+	# $opt_dry_run || eval "echo timestamp > $libobj" || exit $?
 	exit $EXIT_SUCCESS
       fi
=20
@@ -4295,20 +8662,11 @@
 	# Only do commands if we really have different PIC objects.
 	reload_objs=3D"$libobjs $reload_conv_objs"
 	output=3D"$libobj"
-	cmds=3D$reload_cmds
-	save_ifs=3D"$IFS"; IFS=3D'~'
-	for cmd in $cmds; do
-	  IFS=3D"$save_ifs"
-	  eval cmd=3D\"$cmd\"
-	  $show "$cmd"
-	  $run eval "$cmd" || exit $?
-	done
-	IFS=3D"$save_ifs"
+	func_execute_cmds "$reload_cmds" 'exit $?'
       fi
=20
       if test -n "$gentop"; then
-	$show "${rm}r $gentop"
-	$run ${rm}r $gentop
+	func_show_eval '${RM}r "$gentop"'
       fi
=20
       exit $EXIT_SUCCESS
@@ -4316,39 +8674,45 @@
=20
     prog)
       case $host in
-	*cygwin*) output=3D`$echo $output | ${SED} -e 's,.exe$,,;s,$,.exe,'` ;;
+	*cygwin*) func_stripname '' '.exe' "$output"
+	          output=3D$func_stripname_result.exe;;
       esac
-      if test -n "$vinfo"; then
-	$echo "$modename: warning: \`-version-info' is ignored for programs" 1>&2
-      fi
-
-      if test -n "$release"; then
-	$echo "$modename: warning: \`-release' is ignored for programs" 1>&2
-      fi
-
-      if test "$preload" =3D yes; then
-	if test "$dlopen_support" =3D unknown && test "$dlopen_self" =3D unknown =
&&
-	   test "$dlopen_self_static" =3D unknown; then
-	  $echo "$modename: warning: \`AC_LIBTOOL_DLOPEN' not used. Assuming no d=
lopen support."
-	fi
-      fi
+      test -n "$vinfo" && \
+	func_warning "\`-version-info' is ignored for programs"
+
+      test -n "$release" && \
+	func_warning "\`-release' is ignored for programs"
+
+      test "$preload" =3D yes \
+        && test "$dlopen_support" =3D unknown \
+	&& test "$dlopen_self" =3D unknown \
+	&& test "$dlopen_self_static" =3D unknown && \
+	  func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support=
."
=20
       case $host in
       *-*-rhapsody* | *-*-darwin1.[012])
 	# On Rhapsody replace the C library is the System framework
-	compile_deplibs=3D`$echo "X $compile_deplibs" | $Xsed -e 's/ -lc / -frame=
work System /'`
-	finalize_deplibs=3D`$echo "X $finalize_deplibs" | $Xsed -e 's/ -lc / -fra=
mework System /'`
+	compile_deplibs=3D`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltfr=
amework /'`
+	finalize_deplibs=3D`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.lt=
framework /'`
 	;;
       esac
=20
       case $host in
-      *darwin*)
-        # Don't allow lazy linking, it breaks C++ global constructors
-        if test "$tagname" =3D CXX ; then
-        compile_command=3D"$compile_command ${wl}-bind_at_load"
-        finalize_command=3D"$finalize_command ${wl}-bind_at_load"
-        fi
-        ;;
+      *-*-darwin*)
+	# Don't allow lazy linking, it breaks C++ global constructors
+	# But is supposedly fixed on 10.4 or later (yay!).
+	if test "$tagname" =3D CXX ; then
+	  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in
+	    10.[0123])
+	      func_append compile_command " ${wl}-bind_at_load"
+	      func_append finalize_command " ${wl}-bind_at_load"
+	    ;;
+	  esac
+	fi
+	# Time to change all our "foo.ltframework" stuff back to "-framework foo"
+	compile_deplibs=3D`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltfram=
ework% -framework \1%g'`
+	finalize_deplibs=3D`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltfr=
amework% -framework \1%g'`
+	;;
       esac
=20
=20
@@ -4361,7 +8725,7 @@
 	*)
 	  case " $compile_deplibs " in
 	  *" -L$path/$objdir "*)
-	    new_libs=3D"$new_libs -L$path/$objdir" ;;
+	    func_append new_libs " -L$path/$objdir" ;;
 	  esac
 	  ;;
 	esac
@@ -4371,17 +8735,17 @@
 	-L*)
 	  case " $new_libs " in
 	  *" $deplib "*) ;;
-	  *) new_libs=3D"$new_libs $deplib" ;;
+	  *) func_append new_libs " $deplib" ;;
 	  esac
 	  ;;
-	*) new_libs=3D"$new_libs $deplib" ;;
+	*) func_append new_libs " $deplib" ;;
 	esac
       done
       compile_deplibs=3D"$new_libs"
=20
=20
-      compile_command=3D"$compile_command $compile_deplibs"
-      finalize_command=3D"$finalize_command $finalize_deplibs"
+      func_append compile_command " $compile_deplibs"
+      func_append finalize_command " $finalize_deplibs"
=20
       if test -n "$rpath$xrpath"; then
 	# If the user specified any rpath flags, then add them.
@@ -4389,7 +8753,7 @@
 	  # This is the magic to use -rpath.
 	  case "$finalize_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_rpath=3D"$finalize_rpath $libdir" ;;
+	  *) func_append finalize_rpath " $libdir" ;;
 	  esac
 	done
       fi
@@ -4408,30 +8772,32 @@
 	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
 		;;
 	      *)
-		hardcode_libdirs=3D"$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		;;
 	      esac
 	    fi
 	  else
 	    eval flag=3D\"$hardcode_libdir_flag_spec\"
-	    rpath=3D"$rpath $flag"
+	    func_append rpath " $flag"
 	  fi
 	elif test -n "$runpath_var"; then
 	  case "$perm_rpath " in
 	  *" $libdir "*) ;;
-	  *) perm_rpath=3D"$perm_rpath $libdir" ;;
+	  *) func_append perm_rpath " $libdir" ;;
 	  esac
 	fi
 	case $host in
-	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*)
-	  testbindir=3D`$echo "X$libdir" | $Xsed -e 's*/lib$*/bin*'`
+	*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)
+	  testbindir=3D`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'`
 	  case :$dllsearchpath: in
 	  *":$libdir:"*) ;;
-	  *) dllsearchpath=3D"$dllsearchpath:$libdir";;
+	  ::) dllsearchpath=3D$libdir;;
+	  *) func_append dllsearchpath ":$libdir";;
 	  esac
 	  case :$dllsearchpath: in
 	  *":$testbindir:"*) ;;
-	  *) dllsearchpath=3D"$dllsearchpath:$testbindir";;
+	  ::) dllsearchpath=3D$testbindir;;
+	  *) func_append dllsearchpath ":$testbindir";;
 	  esac
 	  ;;
 	esac
@@ -4457,18 +8823,18 @@
 	      *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*)
 		;;
 	      *)
-		hardcode_libdirs=3D"$hardcode_libdirs$hardcode_libdir_separator$libdir"
+		func_append hardcode_libdirs "$hardcode_libdir_separator$libdir"
 		;;
 	      esac
 	    fi
 	  else
 	    eval flag=3D\"$hardcode_libdir_flag_spec\"
-	    rpath=3D"$rpath $flag"
+	    func_append rpath " $flag"
 	  fi
 	elif test -n "$runpath_var"; then
 	  case "$finalize_perm_rpath " in
 	  *" $libdir "*) ;;
-	  *) finalize_perm_rpath=3D"$finalize_perm_rpath $libdir" ;;
+	  *) func_append finalize_perm_rpath " $libdir" ;;
 	  esac
 	fi
       done
@@ -4482,281 +8848,57 @@
=20
       if test -n "$libobjs" && test "$build_old_libs" =3D yes; then
 	# Transform all the library objects into standard objects.
-	compile_command=3D`$echo "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" =
| $NL2SP`
-	finalize_command=3D`$echo "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o=
" | $NL2SP`
+	compile_command=3D`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL=
2SP`
+	finalize_command=3D`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $=
NL2SP`
       fi
=20
-      dlsyms=3D
-      if test -n "$dlfiles$dlprefiles" || test "$dlself" !=3D no; then
-	if test -n "$NM" && test -n "$global_symbol_pipe"; then
-	  dlsyms=3D"${outputname}S.c"
-	else
-	  $echo "$modename: not configured to extract global symbols from dlpreop=
ened files" 1>&2
+      func_generate_dlsyms "$outputname" "@PROGRAM@" "no"
+
+      # template prelinking step
+      if test -n "$prelink_cmds"; then
+	func_execute_cmds "$prelink_cmds" 'exit $?'
+      fi
+
+      wrappers_required=3Dyes
+      case $host in
+      *cegcc* | *mingw32ce*)
+        # Disable wrappers for cegcc and mingw32ce hosts, we are cross com=
piling anyway.
+        wrappers_required=3Dno
+        ;;
+      *cygwin* | *mingw* )
+        if test "$build_libtool_libs" !=3D yes; then
+          wrappers_required=3Dno
+        fi
+        ;;
+      *)
+        if test "$need_relink" =3D no || test "$build_libtool_libs" !=3D y=
es; then
+          wrappers_required=3Dno
+        fi
+        ;;
+      esac
+      if test "$wrappers_required" =3D no; then
+	# Replace the output file specification.
+	compile_command=3D`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"=
'%g'`
+	link_command=3D"$compile_command$compile_rpath"
+
+	# We have no uninstalled library dependencies, so finalize right now.
+	exit_status=3D0
+	func_show_eval "$link_command" 'exit_status=3D$?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=3D`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'=
"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
 	fi
-      fi
-
-      if test -n "$dlsyms"; then
-	case $dlsyms in
-	"") ;;
-	*.c)
-	  # Discover the nlist of each of the dlfiles.
-	  nlist=3D"$output_objdir/${outputname}.nm"
-
-	  $show "$rm $nlist ${nlist}S ${nlist}T"
-	  $run $rm "$nlist" "${nlist}S" "${nlist}T"
-
-	  # Parse the name list into a source file.
-	  $show "creating $output_objdir/$dlsyms"
-
-	  test -z "$run" && $echo > "$output_objdir/$dlsyms" "\
-/* $dlsyms - symbol resolution table for \`$outputname' dlsym emulation. */
-/* Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP */
-
-#ifdef __cplusplus
-extern \"C\" {
-#endif
-
-/* Prevent the only kind of declaration conflicts we can make. */
-#define lt_preloaded_symbols some_other_symbol
-
-/* External symbol declarations for the compiler. */\
-"
-
-	  if test "$dlself" =3D yes; then
-	    $show "generating symbol list for \`$output'"
-
-	    test -z "$run" && $echo ': @PROGRAM@ ' > "$nlist"
-
-	    # Add our own program objects to the symbol list.
-	    progfiles=3D`$echo "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" |=
 $NL2SP`
-	    for arg in $progfiles; do
-	      $show "extracting global C symbols from \`$arg'"
-	      $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
-	    done
-
-	    if test -n "$exclude_expsyms"; then
-	      $run eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T'
-	      $run eval '$mv "$nlist"T "$nlist"'
-	    fi
-
-	    if test -n "$export_symbols_regex"; then
-	      $run eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T'
-	      $run eval '$mv "$nlist"T "$nlist"'
-	    fi
-
-	    # Prepare the list of exported symbols
-	    if test -z "$export_symbols"; then
-	      export_symbols=3D"$output_objdir/$outputname.exp"
-	      $run $rm $export_symbols
-	      $run eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p'=
 "'< "$nlist" > "$export_symbols"'
-              case $host in
-              *cygwin* | *mingw* )
-	        $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
-		$run eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"'
-                ;;
-              esac
-	    else
-	      $run eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/=
$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"'
-	      $run eval 'grep -f "$output_objdir/$outputname.exp" < "$nlist" > "$=
nlist"T'
-	      $run eval 'mv "$nlist"T "$nlist"'
-              case $host in
-              *cygwin* | *mingw* )
-	        $run eval "echo EXPORTS "'> "$output_objdir/$outputname.def"'
-		$run eval 'cat "$nlist" >> "$output_objdir/$outputname.def"'
-                ;;
-              esac
-	    fi
-	  fi
-
-	  for arg in $dlprefiles; do
-	    $show "extracting global C symbols from \`$arg'"
-	    name=3D`$echo "$arg" | ${SED} -e 's%^.*/%%'`
-	    $run eval '$echo ": $name " >> "$nlist"'
-	    $run eval "$NM $arg | $global_symbol_pipe >> '$nlist'"
-	  done
-
-	  if test -z "$run"; then
-	    # Make sure we have at least an empty file.
-	    test -f "$nlist" || : > "$nlist"
-
-	    if test -n "$exclude_expsyms"; then
-	      $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T
-	      $mv "$nlist"T "$nlist"
-	    fi
-
-	    # Try sorting and uniquifying the output.
-	    if grep -v "^: " < "$nlist" |
-		if sort -k 3 </dev/null >/dev/null 2>&1; then
-		  sort -k 3
-		else
-		  sort +2
-		fi |
-		uniq > "$nlist"S; then
-	      :
-	    else
-	      grep -v "^: " < "$nlist" > "$nlist"S
-	    fi
-
-	    if test -f "$nlist"S; then
-	      eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$dls=
yms"'
-	    else
-	      $echo '/* NONE */' >> "$output_objdir/$dlsyms"
-	    fi
-
-	    $echo >> "$output_objdir/$dlsyms" "\
-
-#undef lt_preloaded_symbols
-
-#if defined (__STDC__) && __STDC__
-# define lt_ptr void *
-#else
-# define lt_ptr char *
-# define const
-#endif
-
-/* The mapping between symbol names and symbols. */
-"
-
-	    case $host in
-	    *cygwin* | *mingw* )
-	  $echo >> "$output_objdir/$dlsyms" "\
-/* DATA imports from DLLs on WIN32 can't be const, because
-   runtime relocations are performed -- see ld's documentation
-   on pseudo-relocs */
-struct {
-"
-	      ;;
-	    * )
-	  $echo >> "$output_objdir/$dlsyms" "\
-const struct {
-"
-	      ;;
-	    esac
-
-
-	  $echo >> "$output_objdir/$dlsyms" "\
-  const char *name;
-  lt_ptr address;
-}
-lt_preloaded_symbols[] =3D
-{\
-"
-
-	    eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir=
/$dlsyms"
-
-	    $echo >> "$output_objdir/$dlsyms" "\
-  {0, (lt_ptr) 0}
-};
-
-/* This works around a problem in FreeBSD linker */
-#ifdef FREEBSD_WORKAROUND
-static const void *lt_preloaded_setup() {
-  return lt_preloaded_symbols;
-}
-#endif
-
-#ifdef __cplusplus
-}
-#endif\
-"
-	  fi
-
-	  pic_flag_for_symtable=3D
-	  case $host in
-	  # compiling the symbol table file with pic_flag works around
-	  # a FreeBSD bug that causes programs to crash when -lm is
-	  # linked before any other PIC object.  But we must not use
-	  # pic_flag when linking with -static.  The problem exists in
-	  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.
-	  *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)
-	    case "$compile_command " in
-	    *" -static "*) ;;
-	    *) pic_flag_for_symtable=3D" $pic_flag -DFREEBSD_WORKAROUND";;
-	    esac;;
-	  *-*-hpux*)
-	    case "$compile_command " in
-	    *" -static "*) ;;
-	    *) pic_flag_for_symtable=3D" $pic_flag";;
-	    esac
-	  esac
-
-	  # Now compile the dynamic symbol file.
-	  $show "(cd $output_objdir && $LTCC  $LTCFLAGS -c$no_builtin_flag$pic_fl=
ag_for_symtable \"$dlsyms\")"
-	  $run eval '(cd $output_objdir && $LTCC  $LTCFLAGS -c$no_builtin_flag$pi=
c_flag_for_symtable "$dlsyms")' || exit $?
-
-	  # Clean up the generated files.
-	  $show "$rm $output_objdir/$dlsyms $nlist ${nlist}S ${nlist}T"
-	  $run $rm "$output_objdir/$dlsyms" "$nlist" "${nlist}S" "${nlist}T"
-
-	  # Transform the symbol file into the correct name.
-          case $host in
-          *cygwin* | *mingw* )
-            if test -f "$output_objdir/${outputname}.def" ; then
-              compile_command=3D`$echo "X$compile_command" | $Xsed -e "s%@=
SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${o=
bjext}%"`
-              finalize_command=3D`$echo "X$finalize_command" | $Xsed -e "s=
%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.$=
{objext}%"`
-            else
-              compile_command=3D`$echo "X$compile_command" | $Xsed -e "s%@=
SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
-              finalize_command=3D`$echo "X$finalize_command" | $Xsed -e "s=
%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
-             fi
-            ;;
-          * )
-            compile_command=3D`$echo "X$compile_command" | $Xsed -e "s%@SY=
MFILE@%$output_objdir/${outputname}S.${objext}%"`
-            finalize_command=3D`$echo "X$finalize_command" | $Xsed -e "s%@=
SYMFILE@%$output_objdir/${outputname}S.${objext}%"`
-            ;;
-          esac
-	  ;;
-	*)
-	  $echo "$modename: unknown suffix for \`$dlsyms'" 1>&2
-	  exit $EXIT_FAILURE
-	  ;;
-	esac
-      else
-	# We keep going just in case the user didn't refer to
-	# lt_preloaded_symbols.  The linker will fail if global_symbol_pipe
-	# really was required.
-
-	# Nullify the symbol file.
-	compile_command=3D`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"`
-	finalize_command=3D`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%=
"`
-      fi
-
-      if test "$need_relink" =3D no || test "$build_libtool_libs" !=3D yes=
; then
-	# Replace the output file specification.
-	compile_command=3D`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$ou=
tput"'%g'`
-	link_command=3D"$compile_command$compile_rpath"
-
-	# We have no uninstalled library dependencies, so finalize right now.
-	$show "$link_command"
-	$run eval "$link_command"
-	exit_status=3D$?
=20
 	# Delete the generated files.
-	if test -n "$dlsyms"; then
-	  $show "$rm $output_objdir/${outputname}S.${objext}"
-	  $run $rm "$output_objdir/${outputname}S.${objext}"
+	if test -f "$output_objdir/${outputname}S.${objext}"; then
+	  func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"'
 	fi
=20
 	exit $exit_status
       fi
=20
-      if test -n "$shlibpath_var"; then
-	# We should set the shlibpath_var
-	rpath=3D
-	for dir in $temp_rpath; do
-	  case $dir in
-	  [\\/]* | [A-Za-z]:[\\/]*)
-	    # Absolute path.
-	    rpath=3D"$rpath$dir:"
-	    ;;
-	  *)
-	    # Relative path: add a thisdir entry.
-	    rpath=3D"$rpath\$thisdir/$dir:"
-	    ;;
-	  esac
-	done
-	temp_rpath=3D"$rpath"
-      fi
-
       if test -n "$compile_shlibpath$finalize_shlibpath"; then
 	compile_command=3D"$shlibpath_var=3D\"$compile_shlibpath$finalize_shlibpa=
th\$$shlibpath_var\" $compile_command"
       fi
@@ -4771,7 +8913,7 @@
 	  # We should set the runpath_var.
 	  rpath=3D
 	  for dir in $perm_rpath; do
-	    rpath=3D"$rpath$dir:"
+	    func_append rpath "$dir:"
 	  done
 	  compile_var=3D"$runpath_var=3D\"$rpath\$$runpath_var\" "
 	fi
@@ -4779,7 +8921,7 @@
 	  # We should set the runpath_var.
 	  rpath=3D
 	  for dir in $finalize_perm_rpath; do
-	    rpath=3D"$rpath$dir:"
+	    func_append rpath "$dir:"
 	  done
 	  finalize_var=3D"$runpath_var=3D\"$rpath\$$runpath_var\" "
 	fi
@@ -4789,12 +8931,18 @@
 	# We don't need to create a wrapper script.
 	link_command=3D"$compile_var$compile_command$compile_rpath"
 	# Replace the output file specification.
-	link_command=3D`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'=
%g'`
+	link_command=3D`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'`
 	# Delete the old output file.
-	$run $rm $output
+	$opt_dry_run || $RM $output
 	# Link the executable and exit
-	$show "$link_command"
-	$run eval "$link_command" || exit $?
+	func_show_eval "$link_command" 'exit $?'
+
+	if test -n "$postlink_cmds"; then
+	  func_to_tool_file "$output"
+	  postlink_cmds=3D`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'=
"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'`
+	  func_execute_cmds "$postlink_cmds" 'exit $?'
+	fi
+
 	exit $EXIT_SUCCESS
       fi
=20
@@ -4803,13 +8951,13 @@
 	link_command=3D"$compile_var$compile_command$compile_rpath"
 	relink_command=3D"$finalize_var$finalize_command$finalize_rpath"
=20
-	$echo "$modename: warning: this platform does not like uninstalled shared=
 libraries" 1>&2
-	$echo "$modename: \`$output' will be relinked during installation" 1>&2
+	func_warning "this platform does not like uninstalled shared libraries"
+	func_warning "\`$output' will be relinked during installation"
       else
 	if test "$fast_install" !=3D no; then
 	  link_command=3D"$finalize_var$compile_command$finalize_rpath"
 	  if test "$fast_install" =3D yes; then
-	    relink_command=3D`$echo "X$compile_var$compile_command$compile_rpath"=
 | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'`
+	    relink_command=3D`$ECHO "$compile_var$compile_command$compile_rpath" =
| $SED 's%@OUTPUT@%\$progdir/\$file%g'`
 	  else
 	    # fast_install is set to needless
 	    relink_command=3D
@@ -4821,594 +8969,98 @@
       fi
=20
       # Replace the output file specification.
-      link_command=3D`$echo "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$out=
put_objdir/$outputname"'%g'`
+      link_command=3D`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_o=
bjdir/$outputname"'%g'`
=20
       # Delete the old output files.
-      $run $rm $output $output_objdir/$outputname $output_objdir/lt-$outpu=
tname
-
-      $show "$link_command"
-      $run eval "$link_command" || exit $?
+      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdi=
r/lt-$outputname
+
+      func_show_eval "$link_command" 'exit $?'
+
+      if test -n "$postlink_cmds"; then
+	func_to_tool_file "$output_objdir/$outputname"
+	postlink_cmds=3D`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$=
output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_res=
ult"'%g'`
+	func_execute_cmds "$postlink_cmds" 'exit $?'
+      fi
=20
       # Now create the wrapper script.
-      $show "creating $output"
+      func_verbose "creating $output"
=20
       # Quote the relink command for shipping.
       if test -n "$relink_command"; then
 	# Preserve any variables that may affect compiler behavior
 	for var in $variables_saved_for_relink; do
 	  if eval test -z \"\${$var+set}\"; then
-	    relink_command=3D"{ test -z \"\${$var+set}\" || unset $var || { $var=
=3D; export $var; }; }; $relink_command"
+	    relink_command=3D"{ test -z \"\${$var+set}\" || $lt_unset $var || { $=
var=3D; export $var; }; }; $relink_command"
 	  elif eval var_value=3D\$$var; test -z "$var_value"; then
 	    relink_command=3D"$var=3D; export $var; $relink_command"
 	  else
-	    var_value=3D`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
-	    relink_command=3D"$var=3D\"$var_value\"; export $var; $relink_command"
+	    func_quote_for_eval "$var_value"
+	    relink_command=3D"$var=3D$func_quote_for_eval_result; export $var; $r=
elink_command"
 	  fi
 	done
 	relink_command=3D"(cd `pwd`; $relink_command)"
-	relink_command=3D`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"`
+	relink_command=3D`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
       fi
=20
-      # Quote $echo for shipping.
-      if test "X$echo" =3D "X$SHELL $progpath --fallback-echo"; then
-	case $progpath in
-	[\\/]* | [A-Za-z]:[\\/]*) qecho=3D"$SHELL $progpath --fallback-echo";;
-	*) qecho=3D"$SHELL `pwd`/$progpath --fallback-echo";;
-	esac
-	qecho=3D`$echo "X$qecho" | $Xsed -e "$sed_quote_subst"`
-      else
-	qecho=3D`$echo "X$echo" | $Xsed -e "$sed_quote_subst"`
-      fi
-
-      # Only actually do things if our run command is non-null.
-      if test -z "$run"; then
+      # Only actually do things if not in dry run mode.
+      $opt_dry_run || {
 	# win32 will think the script is a binary if it has
 	# a .exe suffix, so we strip it off here.
 	case $output in
-	  *.exe) output=3D`$echo $output|${SED} 's,.exe$,,'` ;;
+	  *.exe) func_stripname '' '.exe' "$output"
+	         output=3D$func_stripname_result ;;
 	esac
 	# test for cygwin because mv fails w/o .exe extensions
 	case $host in
 	  *cygwin*)
 	    exeext=3D.exe
-	    outputname=3D`$echo $outputname|${SED} 's,.exe$,,'` ;;
+	    func_stripname '' '.exe' "$outputname"
+	    outputname=3D$func_stripname_result ;;
 	  *) exeext=3D ;;
 	esac
 	case $host in
 	  *cygwin* | *mingw* )
-            output_name=3D`basename $output`
-            output_path=3D`dirname $output`
-            cwrappersource=3D"$output_path/$objdir/lt-$output_name.c"
-            cwrapper=3D"$output_path/$output_name.exe"
-            $rm $cwrappersource $cwrapper
-            trap "$rm $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
-
-	    cat > $cwrappersource <<EOF
-
-/* $cwrappersource - temporary wrapper executable for $objdir/$outputname
-   Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
-
-   The $output program cannot be directly executed until all the libtool
-   libraries that it depends on are installed.
-
-   This wrapper executable should never be moved out of the build director=
y.
-   If it is, it will not operate correctly.
-
-   Currently, it simply execs the wrapper *script* "/bin/sh $output",
-   but could eventually absorb all of the scripts functionality and
-   exec $objdir/$outputname directly.
-*/
-EOF
-	    cat >> $cwrappersource<<"EOF"
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <malloc.h>
-#include <stdarg.h>
-#include <assert.h>
-#include <string.h>
-#include <ctype.h>
-#include <sys/stat.h>
-
-#if defined(PATH_MAX)
-# define LT_PATHMAX PATH_MAX
-#elif defined(MAXPATHLEN)
-# define LT_PATHMAX MAXPATHLEN
-#else
-# define LT_PATHMAX 1024
-#endif
-
-#ifndef DIR_SEPARATOR
-# define DIR_SEPARATOR '/'
-# define PATH_SEPARATOR ':'
-#endif
-
-#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \
-  defined (__OS2__)
-# define HAVE_DOS_BASED_FILE_SYSTEM
-# ifndef DIR_SEPARATOR_2
-#  define DIR_SEPARATOR_2 '\\'
-# endif
-# ifndef PATH_SEPARATOR_2
-#  define PATH_SEPARATOR_2 ';'
-# endif
-#endif
-
-#ifndef DIR_SEPARATOR_2
-# define IS_DIR_SEPARATOR(ch) ((ch) =3D=3D DIR_SEPARATOR)
-#else /* DIR_SEPARATOR_2 */
-# define IS_DIR_SEPARATOR(ch) \
-        (((ch) =3D=3D DIR_SEPARATOR) || ((ch) =3D=3D DIR_SEPARATOR_2))
-#endif /* DIR_SEPARATOR_2 */
-
-#ifndef PATH_SEPARATOR_2
-# define IS_PATH_SEPARATOR(ch) ((ch) =3D=3D PATH_SEPARATOR)
-#else /* PATH_SEPARATOR_2 */
-# define IS_PATH_SEPARATOR(ch) ((ch) =3D=3D PATH_SEPARATOR_2)
-#endif /* PATH_SEPARATOR_2 */
-
-#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))
-#define XFREE(stale) do { \
-  if (stale) { free ((void *) stale); stale =3D 0; } \
-} while (0)
-
-/* -DDEBUG is fairly common in CFLAGS.  */
-#undef DEBUG
-#if defined DEBUGWRAPPER
-# define DEBUG(format, ...) fprintf(stderr, format, __VA_ARGS__)
-#else
-# define DEBUG(format, ...)
-#endif
-
-const char *program_name =3D NULL;
-
-void * xmalloc (size_t num);
-char * xstrdup (const char *string);
-const char * base_name (const char *name);
-char * find_executable(const char *wrapper);
-int    check_executable(const char *path);
-char * strendzap(char *str, const char *pat);
-void lt_fatal (const char *message, ...);
-
-int
-main (int argc, char *argv[])
-{
-  char **newargz;
-  int i;
-
-  program_name =3D (char *) xstrdup (base_name (argv[0]));
-  DEBUG("(main) argv[0]      : %s\n",argv[0]);
-  DEBUG("(main) program_name : %s\n",program_name);
-  newargz =3D XMALLOC(char *, argc+2);
-EOF
-
-            cat >> $cwrappersource <<EOF
-  newargz[0] =3D (char *) xstrdup("$SHELL");
-EOF
-
-            cat >> $cwrappersource <<"EOF"
-  newargz[1] =3D find_executable(argv[0]);
-  if (newargz[1] =3D=3D NULL)
-    lt_fatal("Couldn't find %s", argv[0]);
-  DEBUG("(main) found exe at : %s\n",newargz[1]);
-  /* we know the script has the same name, without the .exe */
-  /* so make sure newargz[1] doesn't end in .exe */
-  strendzap(newargz[1],".exe");
-  for (i =3D 1; i < argc; i++)
-    newargz[i+1] =3D xstrdup(argv[i]);
-  newargz[argc+1] =3D NULL;
-
-  for (i=3D0; i<argc+1; i++)
-  {
-    DEBUG("(main) newargz[%d]   : %s\n",i,newargz[i]);
-    ;
-  }
-
-EOF
-
-            case $host_os in
-              mingw*)
-                cat >> $cwrappersource <<EOF
-  execv("$SHELL",(char const **)newargz);
-EOF
-              ;;
-              *)
-                cat >> $cwrappersource <<EOF
-  execv("$SHELL",newargz);
-EOF
-              ;;
-            esac
-
-            cat >> $cwrappersource <<"EOF"
-  return 127;
-}
-
-void *
-xmalloc (size_t num)
-{
-  void * p =3D (void *) malloc (num);
-  if (!p)
-    lt_fatal ("Memory exhausted");
-
-  return p;
-}
-
-char *
-xstrdup (const char *string)
-{
-  return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) =
: NULL
-;
-}
-
-const char *
-base_name (const char *name)
-{
-  const char *base;
-
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
-  /* Skip over the disk name in MSDOS pathnames. */
-  if (isalpha ((unsigned char)name[0]) && name[1] =3D=3D ':')
-    name +=3D 2;
-#endif
-
-  for (base =3D name; *name; name++)
-    if (IS_DIR_SEPARATOR (*name))
-      base =3D name + 1;
-  return base;
-}
-
-int
-check_executable(const char * path)
-{
-  struct stat st;
-
-  DEBUG("(check_executable)  : %s\n", path ? (*path ? path : "EMPTY!") : "=
NULL!");
-  if ((!path) || (!*path))
-    return 0;
-
-  if ((stat (path, &st) >=3D 0) &&
-      (
-        /* MinGW & native WIN32 do not support S_IXOTH or S_IXGRP */
-#if defined (S_IXOTH)
-       ((st.st_mode & S_IXOTH) =3D=3D S_IXOTH) ||
-#endif
-#if defined (S_IXGRP)
-       ((st.st_mode & S_IXGRP) =3D=3D S_IXGRP) ||
-#endif
-       ((st.st_mode & S_IXUSR) =3D=3D S_IXUSR))
-      )
-    return 1;
-  else
-    return 0;
-}
-
-/* Searches for the full path of the wrapper.  Returns
-   newly allocated full path name if found, NULL otherwise */
-char *
-find_executable (const char* wrapper)
-{
-  int has_slash =3D 0;
-  const char* p;
-  const char* p_next;
-  /* static buffer for getcwd */
-  char tmp[LT_PATHMAX + 1];
-  int tmp_len;
-  char* concat_name;
-
-  DEBUG("(find_executable)  : %s\n", wrapper ? (*wrapper ? wrapper : "EMPT=
Y!") : "NULL!");
-
-  if ((wrapper =3D=3D NULL) || (*wrapper =3D=3D '\0'))
-    return NULL;
-
-  /* Absolute path? */
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
-  if (isalpha ((unsigned char)wrapper[0]) && wrapper[1] =3D=3D ':')
-  {
-    concat_name =3D xstrdup (wrapper);
-    if (check_executable(concat_name))
-      return concat_name;
-    XFREE(concat_name);
-  }
-  else
-  {
-#endif
-    if (IS_DIR_SEPARATOR (wrapper[0]))
-    {
-      concat_name =3D xstrdup (wrapper);
-      if (check_executable(concat_name))
-        return concat_name;
-      XFREE(concat_name);
-    }
-#if defined (HAVE_DOS_BASED_FILE_SYSTEM)
-  }
-#endif
-
-  for (p =3D wrapper; *p; p++)
-    if (*p =3D=3D '/')
-    {
-      has_slash =3D 1;
-      break;
-    }
-  if (!has_slash)
-  {
-    /* no slashes; search PATH */
-    const char* path =3D getenv ("PATH");
-    if (path !=3D NULL)
-    {
-      for (p =3D path; *p; p =3D p_next)
-      {
-        const char* q;
-        size_t p_len;
-        for (q =3D p; *q; q++)
-          if (IS_PATH_SEPARATOR(*q))
-            break;
-        p_len =3D q - p;
-        p_next =3D (*q =3D=3D '\0' ? q : q + 1);
-        if (p_len =3D=3D 0)
-        {
-          /* empty path: current directory */
-          if (getcwd (tmp, LT_PATHMAX) =3D=3D NULL)
-            lt_fatal ("getcwd failed");
-          tmp_len =3D strlen(tmp);
-          concat_name =3D XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
-          memcpy (concat_name, tmp, tmp_len);
-          concat_name[tmp_len] =3D '/';
-          strcpy (concat_name + tmp_len + 1, wrapper);
-        }
-        else
-        {
-          concat_name =3D XMALLOC(char, p_len + 1 + strlen(wrapper) + 1);
-          memcpy (concat_name, p, p_len);
-          concat_name[p_len] =3D '/';
-          strcpy (concat_name + p_len + 1, wrapper);
-        }
-        if (check_executable(concat_name))
-          return concat_name;
-        XFREE(concat_name);
-      }
-    }
-    /* not found in PATH; assume curdir */
-  }
-  /* Relative path | not found in path: prepend cwd */
-  if (getcwd (tmp, LT_PATHMAX) =3D=3D NULL)
-    lt_fatal ("getcwd failed");
-  tmp_len =3D strlen(tmp);
-  concat_name =3D XMALLOC(char, tmp_len + 1 + strlen(wrapper) + 1);
-  memcpy (concat_name, tmp, tmp_len);
-  concat_name[tmp_len] =3D '/';
-  strcpy (concat_name + tmp_len + 1, wrapper);
-
-  if (check_executable(concat_name))
-    return concat_name;
-  XFREE(concat_name);
-  return NULL;
-}
-
-char *
-strendzap(char *str, const char *pat)
-{
-  size_t len, patlen;
-
-  assert(str !=3D NULL);
-  assert(pat !=3D NULL);
-
-  len =3D strlen(str);
-  patlen =3D strlen(pat);
-
-  if (patlen <=3D len)
-  {
-    str +=3D len - patlen;
-    if (strcmp(str, pat) =3D=3D 0)
-      *str =3D '\0';
-  }
-  return str;
-}
-
-static void
-lt_error_core (int exit_status, const char * mode,
-          const char * message, va_list ap)
-{
-  fprintf (stderr, "%s: %s: ", program_name, mode);
-  vfprintf (stderr, message, ap);
-  fprintf (stderr, ".\n");
-
-  if (exit_status >=3D 0)
-    exit (exit_status);
-}
-
-void
-lt_fatal (const char *message, ...)
-{
-  va_list ap;
-  va_start (ap, message);
-  lt_error_core (EXIT_FAILURE, "FATAL", message, ap);
-  va_end (ap);
-}
-EOF
-          # we should really use a build-platform specific compiler
-          # here, but OTOH, the wrappers (shell script and this C one)
-          # are only useful if you want to execute the "real" binary.
-          # Since the "real" binary is built for $host, then this
-          # wrapper might as well be built for $host, too.
-          $run $LTCC $LTCFLAGS -s -o $cwrapper $cwrappersource
-          ;;
-        esac
-        $rm $output
-        trap "$rm $output; exit $EXIT_FAILURE" 1 2 15
-
-	$echo > $output "\
-#! $SHELL
-
-# $output - temporary wrapper script for $objdir/$outputname
-# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
-#
-# The $output program cannot be directly executed until all the libtool
-# libraries that it depends on are installed.
-#
-# This wrapper script should never be moved out of the build directory.
-# If it is, it will not operate correctly.
-
-# Sed substitution that helps us do robust quoting.  It backslashifies
-# metacharacters that are still active within double-quoted strings.
-Xsed=3D'${SED} -e 1s/^X//'
-sed_quote_subst=3D'$sed_quote_subst'
-
-# The HP-UX ksh and POSIX shell print the target directory to stdout
-# if CDPATH is set.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-relink_command=3D\"$relink_command\"
-
-# This environment variable determines our operation mode.
-if test \"\$libtool_install_magic\" =3D \"$magic\"; then
-  # install mode needs the following variable:
-  notinst_deplibs=3D'$notinst_deplibs'
-else
-  # When we are sourced in execute mode, \$file and \$echo are already set.
-  if test \"\$libtool_execute_magic\" !=3D \"$magic\"; then
-    echo=3D\"$qecho\"
-    file=3D\"\$0\"
-    # Make sure echo works.
-    if test \"X\$1\" =3D X--no-reexec; then
-      # Discard the --no-reexec flag, and continue.
-      shift
-    elif test \"X\`(\$echo '\t') 2>/dev/null\`\" =3D 'X\t'; then
-      # Yippee, \$echo works!
-      :
-    else
-      # Restart under the correct shell, and then maybe \$echo will work.
-      exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"}
-    fi
-  fi\
-"
-	$echo >> $output "\
-
-  # Find the directory that this script lives in.
-  thisdir=3D\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\`
-  test \"x\$thisdir\" =3D \"x\$file\" && thisdir=3D.
-
-  # Follow symbolic links until we get to the real thisdir.
-  file=3D\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\`
-  while test -n \"\$file\"; do
-    destdir=3D\`\$echo \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\`
-
-    # If there was a directory component, then change thisdir.
-    if test \"x\$destdir\" !=3D \"x\$file\"; then
-      case \"\$destdir\" in
-      [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=3D\"\$destdir\" ;;
-      *) thisdir=3D\"\$thisdir/\$destdir\" ;;
-      esac
-    fi
-
-    file=3D\`\$echo \"X\$file\" | \$Xsed -e 's%^.*/%%'\`
-    file=3D\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\`
-  done
-
-  # Try to get the absolute directory name.
-  absdir=3D\`cd \"\$thisdir\" && pwd\`
-  test -n \"\$absdir\" && thisdir=3D\"\$absdir\"
-"
-
-	if test "$fast_install" =3D yes; then
-	  $echo >> $output "\
-  program=3Dlt-'$outputname'$exeext
-  progdir=3D\"\$thisdir/$objdir\"
-
-  if test ! -f \"\$progdir/\$program\" || \\
-     { file=3D\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\"=
 2>/dev/null | ${SED} 1q\`; \\
-       test \"X\$file\" !=3D \"X\$progdir/\$program\"; }; then
-
-    file=3D\"\$\$-\$program\"
-
-    if test ! -d \"\$progdir\"; then
-      $mkdir \"\$progdir\"
-    else
-      $rm \"\$progdir/\$file\"
-    fi"
-
-	  $echo >> $output "\
-
-    # relink executable if necessary
-    if test -n \"\$relink_command\"; then
-      if relink_command_output=3D\`eval \$relink_command 2>&1\`; then :
-      else
-	$echo \"\$relink_command_output\" >&2
-	$rm \"\$progdir/\$file\"
-	exit $EXIT_FAILURE
-      fi
-    fi
-
-    $mv \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null ||
-    { $rm \"\$progdir/\$program\";
-      $mv \"\$progdir/\$file\" \"\$progdir/\$program\"; }
-    $rm \"\$progdir/\$file\"
-  fi"
-	else
-	  $echo >> $output "\
-  program=3D'$outputname'
-  progdir=3D\"\$thisdir/$objdir\"
-"
-	fi
-
-	$echo >> $output "\
-
-  if test -f \"\$progdir/\$program\"; then"
-
-	# Export our shlibpath_var if we have one.
-	if test "$shlibpath_overrides_runpath" =3D yes && test -n "$shlibpath_var=
" && test -n "$temp_rpath"; then
-	  $echo >> $output "\
-    # Add our own library path to $shlibpath_var
-    $shlibpath_var=3D\"$temp_rpath\$$shlibpath_var\"
-
-    # Some systems cannot cope with colon-terminated $shlibpath_var
-    # The second colon is a workaround for a bug in BeOS R4 sed
-    $shlibpath_var=3D\`\$echo \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//=
'\`
-
-    export $shlibpath_var
-"
-	fi
-
-	# fixup the dll searchpath if we need to.
-	if test -n "$dllsearchpath"; then
-	  $echo >> $output "\
-    # Add the dll search path components to the executable PATH
-    PATH=3D$dllsearchpath:\$PATH
-"
-	fi
-
-	$echo >> $output "\
-    if test \"\$libtool_execute_magic\" !=3D \"$magic\"; then
-      # Run the actual program with our arguments.
-"
-	case $host in
-	# Backslashes separate directories on plain windows
-	*-*-mingw | *-*-os2*)
-	  $echo >> $output "\
-      exec \"\$progdir\\\\\$program\" \${1+\"\$@\"}
-"
+	    func_dirname_and_basename "$output" "" "."
+	    output_name=3D$func_basename_result
+	    output_path=3D$func_dirname_result
+	    cwrappersource=3D"$output_path/$objdir/lt-$output_name.c"
+	    cwrapper=3D"$output_path/$output_name.exe"
+	    $RM $cwrappersource $cwrapper
+	    trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_cwrapperexe_src > $cwrappersource
+
+	    # The wrapper executable is built using the $host compiler,
+	    # because it contains $host paths and files. If cross-
+	    # compiling, it, like the target executable, must be
+	    # executed on the $host or under an emulation environment.
+	    $opt_dry_run || {
+	      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource
+	      $STRIP $cwrapper
+	    }
+
+	    # Now, create the wrapper script for func_source use:
+	    func_ltwrapper_scriptname $cwrapper
+	    $RM $func_ltwrapper_scriptname_result
+	    trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 =
15
+	    $opt_dry_run || {
+	      # note: this script will not be executed, so do not chmod.
+	      if test "x$build" =3D "x$host" ; then
+		$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result
+	      else
+		func_emit_wrapper no > $func_ltwrapper_scriptname_result
+	      fi
+	    }
 	  ;;
-
-	*)
-	  $echo >> $output "\
-      exec \"\$progdir/\$program\" \${1+\"\$@\"}
-"
+	  * )
+	    $RM $output
+	    trap "$RM $output; exit $EXIT_FAILURE" 1 2 15
+
+	    func_emit_wrapper no > $output
+	    chmod +x $output
 	  ;;
 	esac
-	$echo >> $output "\
-      \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\"
-      exit $EXIT_FAILURE
-    fi
-  else
-    # The program doesn't exist.
-    \$echo \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2
-    \$echo \"This script is just a wrapper for \$program.\" 1>&2
-    $echo \"See the $PACKAGE documentation for more information.\" 1>&2
-    exit $EXIT_FAILURE
-  fi
-fi\
-"
-	chmod +x $output
-      fi
+      }
       exit $EXIT_SUCCESS
       ;;
     esac
@@ -5417,7 +9069,7 @@
     for oldlib in $oldlibs; do
=20
       if test "$build_libtool_libs" =3D convenience; then
-	oldobjs=3D"$libobjs_save"
+	oldobjs=3D"$libobjs_save $symfileobj"
 	addlibs=3D"$convenience"
 	build_libtool_libs=3Dno
       else
@@ -5426,22 +9078,35 @@
 	  build_libtool_libs=3Dno
 	else
 	  oldobjs=3D"$old_deplibs $non_pic_objects"
+	  if test "$preload" =3D yes && test -f "$symfileobj"; then
+	    func_append oldobjs " $symfileobj"
+	  fi
 	fi
 	addlibs=3D"$old_convenience"
       fi
=20
       if test -n "$addlibs"; then
 	gentop=3D"$output_objdir/${outputname}x"
-	generated=3D"$generated $gentop"
+	func_append generated " $gentop"
=20
 	func_extract_archives $gentop $addlibs
-	oldobjs=3D"$oldobjs $func_extract_archives_result"
+	func_append oldobjs " $func_extract_archives_result"
       fi
=20
       # Do each command in the archive commands.
       if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs=
" =3D yes; then
-       cmds=3D$old_archive_from_new_cmds
+	cmds=3D$old_archive_from_new_cmds
       else
+
+	# Add any objects from preloaded convenience libraries
+	if test -n "$dlprefiles"; then
+	  gentop=3D"$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+
+	  func_extract_archives $gentop $dlprefiles
+	  func_append oldobjs " $func_extract_archives_result"
+	fi
+
 	# POSIX demands no paths to be encoded in archives.  We have
 	# to avoid creating archives with duplicate basenames if we
 	# might have to extract them afterwards, e.g., when creating a
@@ -5450,32 +9115,22 @@
 	# not supported by libtool).
 	if (for obj in $oldobjs
 	    do
-	      $echo "X$obj" | $Xsed -e 's%^.*/%%'
+	      func_basename "$obj"
+	      $ECHO "$func_basename_result"
 	    done | sort | sort -uc >/dev/null 2>&1); then
 	  :
 	else
-	  $echo "copying selected object files to avoid basename conflicts..."
-
-	  if test -z "$gentop"; then
-	    gentop=3D"$output_objdir/${outputname}x"
-	    generated=3D"$generated $gentop"
-
-	    $show "${rm}r $gentop"
-	    $run ${rm}r "$gentop"
-	    $show "$mkdir $gentop"
-	    $run $mkdir "$gentop"
-	    exit_status=3D$?
-	    if test "$exit_status" -ne 0 && test ! -d "$gentop"; then
-	      exit $exit_status
-	    fi
-	  fi
-
+	  echo "copying selected object files to avoid basename conflicts..."
+	  gentop=3D"$output_objdir/${outputname}x"
+	  func_append generated " $gentop"
+	  func_mkdir_p "$gentop"
 	  save_oldobjs=3D$oldobjs
 	  oldobjs=3D
 	  counter=3D1
 	  for obj in $save_oldobjs
 	  do
-	    objbase=3D`$echo "X$obj" | $Xsed -e 's%^.*/%%'`
+	    func_basename "$obj"
+	    objbase=3D"$func_basename_result"
 	    case " $oldobjs " in
 	    " ") oldobjs=3D$obj ;;
 	    *[\ /]"$objbase "*)
@@ -5483,58 +9138,72 @@
 		# Make sure we don't pick an alternate name that also
 		# overlaps.
 		newobj=3Dlt$counter-$objbase
-		counter=3D`expr $counter + 1`
+		func_arith $counter + 1
+		counter=3D$func_arith_result
 		case " $oldobjs " in
 		*[\ /]"$newobj "*) ;;
 		*) if test ! -f "$gentop/$newobj"; then break; fi ;;
 		esac
 	      done
-	      $show "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
-	      $run ln "$obj" "$gentop/$newobj" ||
-	      $run cp "$obj" "$gentop/$newobj"
-	      oldobjs=3D"$oldobjs $gentop/$newobj"
+	      func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj"
+	      func_append oldobjs " $gentop/$newobj"
 	      ;;
-	    *) oldobjs=3D"$oldobjs $obj" ;;
+	    *) func_append oldobjs " $obj" ;;
 	    esac
 	  done
 	fi
-
 	eval cmds=3D\"$old_archive_cmds\"
=20
-	if len=3D`expr "X$cmds" : ".*"` &&
-	     test "$len" -le "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	func_len " $cmds"
+	len=3D$func_len_result
+	if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then
+	  cmds=3D$old_archive_cmds
+	elif test -n "$archiver_list_spec"; then
+	  func_verbose "using command file archive linking..."
+	  for obj in $oldobjs
+	  do
+	    func_to_tool_file "$obj"
+	    $ECHO "$func_to_tool_file_result"
+	  done > $output_objdir/$libname.libcmd
+	  func_to_tool_file "$output_objdir/$libname.libcmd"
+	  oldobjs=3D" $archiver_list_spec$func_to_tool_file_result"
 	  cmds=3D$old_archive_cmds
 	else
 	  # the command line is too long to link in one step, link in parts
-	  $echo "using piecewise archive linking..."
+	  func_verbose "using piecewise archive linking..."
 	  save_RANLIB=3D$RANLIB
 	  RANLIB=3D:
 	  objlist=3D
 	  concat_cmds=3D
 	  save_oldobjs=3D$oldobjs
-
+	  oldobjs=3D
 	  # Is there a better way of finding the last object in the list?
 	  for obj in $save_oldobjs
 	  do
 	    last_oldobj=3D$obj
 	  done
+	  eval test_cmds=3D\"$old_archive_cmds\"
+	  func_len " $test_cmds"
+	  len0=3D$func_len_result
+	  len=3D$len0
 	  for obj in $save_oldobjs
 	  do
-	    oldobjs=3D"$objlist $obj"
-	    objlist=3D"$objlist $obj"
-	    eval test_cmds=3D\"$old_archive_cmds\"
-	    if len=3D`expr "X$test_cmds" : ".*" 2>/dev/null` &&
-	       test "$len" -le "$max_cmd_len"; then
+	    func_len " $obj"
+	    func_arith $len + $func_len_result
+	    len=3D$func_arith_result
+	    func_append objlist " $obj"
+	    if test "$len" -lt "$max_cmd_len"; then
 	      :
 	    else
 	      # the above command should be used before it gets too long
 	      oldobjs=3D$objlist
 	      if test "$obj" =3D "$last_oldobj" ; then
-	        RANLIB=3D$save_RANLIB
+		RANLIB=3D$save_RANLIB
 	      fi
 	      test -z "$concat_cmds" || concat_cmds=3D$concat_cmds~
 	      eval concat_cmds=3D\"\${concat_cmds}$old_archive_cmds\"
 	      objlist=3D
+	      len=3D$len0
 	    fi
 	  done
 	  RANLIB=3D$save_RANLIB
@@ -5546,49 +9215,39 @@
 	  fi
 	fi
       fi
-      save_ifs=3D"$IFS"; IFS=3D'~'
-      for cmd in $cmds; do
-        eval cmd=3D\"$cmd\"
-	IFS=3D"$save_ifs"
-	$show "$cmd"
-	$run eval "$cmd" || exit $?
-      done
-      IFS=3D"$save_ifs"
+      func_execute_cmds "$cmds" 'exit $?'
     done
=20
-    if test -n "$generated"; then
-      $show "${rm}r$generated"
-      $run ${rm}r$generated
-    fi
+    test -n "$generated" && \
+      func_show_eval "${RM}r$generated"
=20
     # Now create the libtool archive.
     case $output in
     *.la)
       old_library=3D
       test "$build_old_libs" =3D yes && old_library=3D"$libname.$libext"
-      $show "creating $output"
+      func_verbose "creating $output"
=20
       # Preserve any variables that may affect compiler behavior
       for var in $variables_saved_for_relink; do
 	if eval test -z \"\${$var+set}\"; then
-	  relink_command=3D"{ test -z \"\${$var+set}\" || unset $var || { $var=3D=
; export $var; }; }; $relink_command"
+	  relink_command=3D"{ test -z \"\${$var+set}\" || $lt_unset $var || { $va=
r=3D; export $var; }; }; $relink_command"
 	elif eval var_value=3D\$$var; test -z "$var_value"; then
 	  relink_command=3D"$var=3D; export $var; $relink_command"
 	else
-	  var_value=3D`$echo "X$var_value" | $Xsed -e "$sed_quote_subst"`
-	  relink_command=3D"$var=3D\"$var_value\"; export $var; $relink_command"
+	  func_quote_for_eval "$var_value"
+	  relink_command=3D"$var=3D$func_quote_for_eval_result; export $var; $rel=
ink_command"
 	fi
       done
       # Quote the link command for shipping.
       relink_command=3D"(cd `pwd`; $SHELL $progpath $preserve_args --mode=
=3Drelink $libtool_args @inst_prefix_dir@)"
-      relink_command=3D`$echo "X$relink_command" | $Xsed -e "$sed_quote_su=
bst"`
+      relink_command=3D`$ECHO "$relink_command" | $SED "$sed_quote_subst"`
       if test "$hardcode_automatic" =3D yes ; then
 	relink_command=3D
       fi
=20
-
       # Only create the output if not a dry run.
-      if test -z "$run"; then
+      $opt_dry_run || {
 	for installed in no yes; do
 	  if test "$installed" =3D yes; then
 	    if test -z "$install_libdir"; then
@@ -5600,38 +9259,59 @@
 	    for deplib in $dependency_libs; do
 	      case $deplib in
 	      *.la)
-		name=3D`$echo "X$deplib" | $Xsed -e 's%^.*/%%'`
+		func_basename "$deplib"
+		name=3D"$func_basename_result"
 		eval libdir=3D`${SED} -n -e 's/^libdir=3D\(.*\)$/\1/p' $deplib`
-		if test -z "$libdir"; then
-		  $echo "$modename: \`$deplib' is not a valid libtool archive" 1>&2
-		  exit $EXIT_FAILURE
-		fi
-		newdependency_libs=3D"$newdependency_libs $libdir/$name"
+		test -z "$libdir" && \
+		  func_fatal_error "\`$deplib' is not a valid libtool archive"
+		func_append newdependency_libs " ${lt_sysroot:+=3D}$libdir/$name"
 		;;
-	      *) newdependency_libs=3D"$newdependency_libs $deplib" ;;
+	      -L*)
+		func_stripname -L '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -L$func_replace_sysroot_result"
+		;;
+	      -R*)
+		func_stripname -R '' "$deplib"
+		func_replace_sysroot "$func_stripname_result"
+		func_append newdependency_libs " -R$func_replace_sysroot_result"
+		;;
+	      *) func_append newdependency_libs " $deplib" ;;
 	      esac
 	    done
 	    dependency_libs=3D"$newdependency_libs"
 	    newdlfiles=3D
+
 	    for lib in $dlfiles; do
-	      name=3D`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
-	      eval libdir=3D`${SED} -n -e 's/^libdir=3D\(.*\)$/\1/p' $lib`
-	      if test -z "$libdir"; then
-		$echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
-		exit $EXIT_FAILURE
-	      fi
-	      newdlfiles=3D"$newdlfiles $libdir/$name"
+	      case $lib in
+	      *.la)
+	        func_basename "$lib"
+		name=3D"$func_basename_result"
+		eval libdir=3D`${SED} -n -e 's/^libdir=3D\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlfiles " ${lt_sysroot:+=3D}$libdir/$name"
+		;;
+	      *) func_append newdlfiles " $lib" ;;
+	      esac
 	    done
 	    dlfiles=3D"$newdlfiles"
 	    newdlprefiles=3D
 	    for lib in $dlprefiles; do
-	      name=3D`$echo "X$lib" | $Xsed -e 's%^.*/%%'`
-	      eval libdir=3D`${SED} -n -e 's/^libdir=3D\(.*\)$/\1/p' $lib`
-	      if test -z "$libdir"; then
-		$echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
-		exit $EXIT_FAILURE
-	      fi
-	      newdlprefiles=3D"$newdlprefiles $libdir/$name"
+	      case $lib in
+	      *.la)
+		# Only pass preopened files to the pseudo-archive (for
+		# eventual linking with the app. that links it) if we
+		# didn't already link the preopened objects directly into
+		# the library:
+		func_basename "$lib"
+		name=3D"$func_basename_result"
+		eval libdir=3D`${SED} -n -e 's/^libdir=3D\(.*\)$/\1/p' $lib`
+		test -z "$libdir" && \
+		  func_fatal_error "\`$lib' is not a valid libtool archive"
+		func_append newdlprefiles " ${lt_sysroot:+=3D}$libdir/$name"
+		;;
+	      esac
 	    done
 	    dlprefiles=3D"$newdlprefiles"
 	  else
@@ -5641,7 +9321,7 @@
 		[\\/]* | [A-Za-z]:[\\/]*) abs=3D"$lib" ;;
 		*) abs=3D`pwd`"/$lib" ;;
 	      esac
-	      newdlfiles=3D"$newdlfiles $abs"
+	      func_append newdlfiles " $abs"
 	    done
 	    dlfiles=3D"$newdlfiles"
 	    newdlprefiles=3D
@@ -5650,19 +9330,37 @@
 		[\\/]* | [A-Za-z]:[\\/]*) abs=3D"$lib" ;;
 		*) abs=3D`pwd`"/$lib" ;;
 	      esac
-	      newdlprefiles=3D"$newdlprefiles $abs"
+	      func_append newdlprefiles " $abs"
 	    done
 	    dlprefiles=3D"$newdlprefiles"
 	  fi
-	  $rm $output
+	  $RM $output
 	  # place dlname in correct position for cygwin
+	  # In fact, it would be nice if we could use this code for all target
+	  # systems that can't hard-code library paths into their executables
+	  # and that have no shared library path variable independent of PATH,
+	  # but it turns out we can't easily determine that from inspecting
+	  # libtool variables, so we have to hard-code the OSs to which it
+	  # applies here; at the moment, that means platforms that use the PE
+	  # object format with DLL files.  See the long comment at the top of
+	  # tests/bindir.at for full details.
 	  tdlname=3D$dlname
 	  case $host,$output,$installed,$module,$dlname in
-	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=3D../=
bin/$dlname ;;
+	    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai=
,yes,no,*.dll)
+	      # If a -bindir argument was supplied, place the dll there.
+	      if test "x$bindir" !=3D x ;
+	      then
+		func_relative_path "$install_libdir" "$bindir"
+		tdlname=3D$func_relative_path_result$dlname
+	      else
+		# Otherwise fall back on heuristic.
+		tdlname=3D../bin/$dlname
+	      fi
+	      ;;
 	  esac
-	  $echo > $output "\
+	  $ECHO > $output "\
 # $outputname - a libtool library file
-# Generated by $PROGRAM - GNU $PACKAGE $VERSION$TIMESTAMP
+# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION
 #
 # Please DO NOT delete this file!
 # It is necessary for linking the library.
@@ -5676,9 +9374,15 @@
 # The name of the static archive.
 old_library=3D'$old_library'
=20
+# Linker flags that can not go in dependency_libs.
+inherited_linker_flags=3D'$new_inherited_linker_flags'
+
 # Libraries that this one depends upon.
 dependency_libs=3D'$dependency_libs'
=20
+# Names of additional weak libraries provided by this library
+weak_library_names=3D'$weak_libs'
+
 # Version information for $libname.
 current=3D$current
 age=3D$age
@@ -5697,795 +9401,75 @@
 # Directory that this library needs to be installed in:
 libdir=3D'$install_libdir'"
 	  if test "$installed" =3D no && test "$need_relink" =3D yes; then
-	    $echo >> $output "\
+	    $ECHO >> $output "\
 relink_command=3D\"$relink_command\""
 	  fi
 	done
-      fi
+      }
=20
       # Do a symbolic link so that the libtool archive can be found in
       # LD_LIBRARY_PATH before the program is installed.
-      $show "(cd $output_objdir && $rm $outputname && $LN_S ../$outputname=
 $outputname)"
-      $run eval '(cd $output_objdir && $rm $outputname && $LN_S ../$output=
name $outputname)' || exit $?
+      func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S =
"../$outputname" "$outputname" )' 'exit $?'
       ;;
     esac
     exit $EXIT_SUCCESS
-    ;;
-
-  # libtool install mode
-  install)
-    modename=3D"$modename: install"
-
-    # There may be an optional sh(1) argument at the beginning of
-    # install_prog (especially on Windows NT).
-    if test "$nonopt" =3D "$SHELL" || test "$nonopt" =3D /bin/sh ||
-       # Allow the use of GNU shtool's install command.
-       $echo "X$nonopt" | grep shtool > /dev/null; then
-      # Aesthetically quote it.
-      arg=3D`$echo "X$nonopt" | $Xsed -e "$sed_quote_subst"`
-      case $arg in
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	arg=3D"\"$arg\""
-	;;
-      esac
-      install_prog=3D"$arg "
-      arg=3D"$1"
-      shift
-    else
-      install_prog=3D
-      arg=3D$nonopt
-    fi
-
-    # The real first argument should be the name of the installation progr=
am.
-    # Aesthetically quote it.
-    arg=3D`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
-    case $arg in
-    *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-      arg=3D"\"$arg\""
-      ;;
-    esac
-    install_prog=3D"$install_prog$arg"
-
-    # We need to accept at least all the BSD install flags.
-    dest=3D
+}
+
+{ test "$opt_mode" =3D link || test "$opt_mode" =3D relink; } &&
+    func_mode_link ${1+"$@"}
+
+
+# func_mode_uninstall arg...
+func_mode_uninstall ()
+{
+    $opt_debug
+    RM=3D"$nonopt"
     files=3D
-    opts=3D
-    prev=3D
-    install_type=3D
-    isdir=3Dno
-    stripme=3D
-    for arg
-    do
-      if test -n "$dest"; then
-	files=3D"$files $dest"
-	dest=3D$arg
-	continue
-      fi
-
-      case $arg in
-      -d) isdir=3Dyes ;;
-      -f)=20
-      	case " $install_prog " in
-	*[\\\ /]cp\ *) ;;
-	*) prev=3D$arg ;;
-	esac
-	;;
-      -g | -m | -o) prev=3D$arg ;;
-      -s)
-	stripme=3D" -s"
-	continue
-	;;
-      -*)
-	;;
-      *)
-	# If the previous option needed an argument, then skip it.
-	if test -n "$prev"; then
-	  prev=3D
-	else
-	  dest=3D$arg
-	  continue
-	fi
-	;;
-      esac
-
-      # Aesthetically quote the argument.
-      arg=3D`$echo "X$arg" | $Xsed -e "$sed_quote_subst"`
-      case $arg in
-      *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \	]*|*]*|"")
-	arg=3D"\"$arg\""
-	;;
-      esac
-      install_prog=3D"$install_prog $arg"
-    done
-
-    if test -z "$install_prog"; then
-      $echo "$modename: you must specify an install program" 1>&2
-      $echo "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
-
-    if test -n "$prev"; then
-      $echo "$modename: the \`$prev' option requires an argument" 1>&2
-      $echo "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
-
-    if test -z "$files"; then
-      if test -z "$dest"; then
-	$echo "$modename: no file or destination specified" 1>&2
-      else
-	$echo "$modename: you must specify a destination" 1>&2
-      fi
-      $echo "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
-
-    # Strip any trailing slash from the destination.
-    dest=3D`$echo "X$dest" | $Xsed -e 's%/$%%'`
-
-    # Check to see that the destination is a directory.
-    test -d "$dest" && isdir=3Dyes
-    if test "$isdir" =3D yes; then
-      destdir=3D"$dest"
-      destname=3D
-    else
-      destdir=3D`$echo "X$dest" | $Xsed -e 's%/[^/]*$%%'`
-      test "X$destdir" =3D "X$dest" && destdir=3D.
-      destname=3D`$echo "X$dest" | $Xsed -e 's%^.*/%%'`
-
-      # Not a directory, so check to see that there is only one file speci=
fied.
-      set dummy $files
-      if test "$#" -gt 2; then
-	$echo "$modename: \`$dest' is not a directory" 1>&2
-	$echo "$help" 1>&2
-	exit $EXIT_FAILURE
-      fi
-    fi
-    case $destdir in
-    [\\/]* | [A-Za-z]:[\\/]*) ;;
-    *)
-      for file in $files; do
-	case $file in
-	*.lo) ;;
-	*)
-	  $echo "$modename: \`$destdir' must be an absolute directory name" 1>&2
-	  $echo "$help" 1>&2
-	  exit $EXIT_FAILURE
-	  ;;
-	esac
-      done
-      ;;
-    esac
+    rmforce=3D
+    exit_status=3D0
=20
     # This variable tells wrapper scripts just to set variables rather
     # than running their programs.
     libtool_install_magic=3D"$magic"
=20
-    staticlibs=3D
-    future_libdirs=3D
-    current_libdirs=3D
-    for file in $files; do
-
-      # Do each installation.
-      case $file in
-      *.$libext)
-	# Do the static libraries later.
-	staticlibs=3D"$staticlibs $file"
-	;;
-
-      *.la)
-	# Check to see that this really is a libtool archive.
-	if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null =
2>&1; then :
-	else
-	  $echo "$modename: \`$file' is not a valid libtool archive" 1>&2
-	  $echo "$help" 1>&2
-	  exit $EXIT_FAILURE
-	fi
-
-	library_names=3D
-	old_library=3D
-	relink_command=3D
-	# If there is no directory component, then add one.
-	case $file in
-	*/* | *\\*) . $file ;;
-	*) . ./$file ;;
-	esac
-
-	# Add the libdir to current_libdirs if it is the destination.
-	if test "X$destdir" =3D "X$libdir"; then
-	  case "$current_libdirs " in
-	  *" $libdir "*) ;;
-	  *) current_libdirs=3D"$current_libdirs $libdir" ;;
-	  esac
-	else
-	  # Note the libdir as a future libdir.
-	  case "$future_libdirs " in
-	  *" $libdir "*) ;;
-	  *) future_libdirs=3D"$future_libdirs $libdir" ;;
-	  esac
-	fi
-
-	dir=3D`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`/
-	test "X$dir" =3D "X$file/" && dir=3D
-	dir=3D"$dir$objdir"
-
-	if test -n "$relink_command"; then
-	  # Determine the prefix the user has applied to our future dir.
-	  inst_prefix_dir=3D`$echo "$destdir" | $SED "s%$libdir\$%%"`
-
-	  # Don't allow the user to place us outside of our expected
-	  # location b/c this prevents finding dependent libraries that
-	  # are installed to the same prefix.
-	  # At present, this check doesn't affect windows .dll's that
-	  # are installed into $libdir/../bin (currently, that works fine)
-	  # but it's something to keep an eye on.
-	  if test "$inst_prefix_dir" =3D "$destdir"; then
-	    $echo "$modename: error: cannot install \`$file' to a directory not e=
nding in $libdir" 1>&2
-	    exit $EXIT_FAILURE
-	  fi
-
-	  if test -n "$inst_prefix_dir"; then
-	    # Stick the inst_prefix_dir data into the link command.
-	    relink_command=3D`$echo "$relink_command" | $SED "s%@inst_prefix_dir@=
%-inst-prefix-dir $inst_prefix_dir%"`
-	  else
-	    relink_command=3D`$echo "$relink_command" | $SED "s%@inst_prefix_dir@=
%%"`
-	  fi
-
-	  $echo "$modename: warning: relinking \`$file'" 1>&2
-	  $show "$relink_command"
-	  if $run eval "$relink_command"; then :
-	  else
-	    $echo "$modename: error: relink \`$file' with the above command befor=
e installing it" 1>&2
-	    exit $EXIT_FAILURE
-	  fi
-	fi
-
-	# See the names of the shared library.
-	set dummy $library_names
-	if test -n "$2"; then
-	  realname=3D"$2"
-	  shift
-	  shift
-
-	  srcname=3D"$realname"
-	  test -n "$relink_command" && srcname=3D"$realname"T
-
-	  # Install the shared library and build the symlinks.
-	  $show "$install_prog $dir/$srcname $destdir/$realname"
-	  $run eval "$install_prog $dir/$srcname $destdir/$realname" || exit $?
-	  if test -n "$stripme" && test -n "$striplib"; then
-	    $show "$striplib $destdir/$realname"
-	    $run eval "$striplib $destdir/$realname" || exit $?
-	  fi
-
-	  if test "$#" -gt 0; then
-	    # Delete the old symlinks, and create new ones.
-	    # Try `ln -sf' first, because the `ln' binary might depend on
-	    # the symlink we replace!  Solaris /bin/ln does not understand -f,
-	    # so we also need to try rm && ln -s.
-	    for linkname
-	    do
-	      if test "$linkname" !=3D "$realname"; then
-                $show "(cd $destdir && { $LN_S -f $realname $linkname || {=
 $rm $linkname && $LN_S $realname $linkname; }; })"
-                $run eval "(cd $destdir && { $LN_S -f $realname $linkname =
|| { $rm $linkname && $LN_S $realname $linkname; }; })"
-	      fi
-	    done
-	  fi
-
-	  # Do each command in the postinstall commands.
-	  lib=3D"$destdir/$realname"
-	  cmds=3D$postinstall_cmds
-	  save_ifs=3D"$IFS"; IFS=3D'~'
-	  for cmd in $cmds; do
-	    IFS=3D"$save_ifs"
-	    eval cmd=3D\"$cmd\"
-	    $show "$cmd"
-	    $run eval "$cmd" || {
-	      lt_exit=3D$?
-
-	      # Restore the uninstalled library and exit
-	      if test "$mode" =3D relink; then
-		$run eval '(cd $output_objdir && $rm ${realname}T && $mv ${realname}U $r=
ealname)'
-	      fi
-
-	      exit $lt_exit
-	    }
-	  done
-	  IFS=3D"$save_ifs"
-	fi
-
-	# Install the pseudo-library for information purposes.
-	name=3D`$echo "X$file" | $Xsed -e 's%^.*/%%'`
-	instname=3D"$dir/$name"i
-	$show "$install_prog $instname $destdir/$name"
-	$run eval "$install_prog $instname $destdir/$name" || exit $?
-
-	# Maybe install the static library, too.
-	test -n "$old_library" && staticlibs=3D"$staticlibs $dir/$old_library"
-	;;
-
-      *.lo)
-	# Install (i.e. copy) a libtool object.
-
-	# Figure out destination file name, if it wasn't already specified.
-	if test -n "$destname"; then
-	  destfile=3D"$destdir/$destname"
-	else
-	  destfile=3D`$echo "X$file" | $Xsed -e 's%^.*/%%'`
-	  destfile=3D"$destdir/$destfile"
-	fi
-
-	# Deduce the name of the destination old-style object file.
-	case $destfile in
-	*.lo)
-	  staticdest=3D`$echo "X$destfile" | $Xsed -e "$lo2o"`
-	  ;;
-	*.$objext)
-	  staticdest=3D"$destfile"
-	  destfile=3D
-	  ;;
-	*)
-	  $echo "$modename: cannot copy a libtool object to \`$destfile'" 1>&2
-	  $echo "$help" 1>&2
-	  exit $EXIT_FAILURE
-	  ;;
-	esac
-
-	# Install the libtool object if requested.
-	if test -n "$destfile"; then
-	  $show "$install_prog $file $destfile"
-	  $run eval "$install_prog $file $destfile" || exit $?
-	fi
-
-	# Install the old object if enabled.
-	if test "$build_old_libs" =3D yes; then
-	  # Deduce the name of the old-style object file.
-	  staticobj=3D`$echo "X$file" | $Xsed -e "$lo2o"`
-
-	  $show "$install_prog $staticobj $staticdest"
-	  $run eval "$install_prog \$staticobj \$staticdest" || exit $?
-	fi
-	exit $EXIT_SUCCESS
-	;;
-
-      *)
-	# Figure out destination file name, if it wasn't already specified.
-	if test -n "$destname"; then
-	  destfile=3D"$destdir/$destname"
-	else
-	  destfile=3D`$echo "X$file" | $Xsed -e 's%^.*/%%'`
-	  destfile=3D"$destdir/$destfile"
-	fi
-
-	# If the file is missing, and there is a .exe on the end, strip it
-	# because it is most likely a libtool script we actually want to
-	# install
-	stripped_ext=3D""
-	case $file in
-	  *.exe)
-	    if test ! -f "$file"; then
-	      file=3D`$echo $file|${SED} 's,.exe$,,'`
-	      stripped_ext=3D".exe"
-	    fi
-	    ;;
-	esac
-
-	# Do a test to see if this is really a libtool program.
-	case $host in
-	*cygwin*|*mingw*)
-	    wrapper=3D`$echo $file | ${SED} -e 's,.exe$,,'`
-	    ;;
-	*)
-	    wrapper=3D$file
-	    ;;
-	esac
-	if (${SED} -e '4q' $wrapper | grep "^# Generated by .*$PACKAGE")>/dev/nul=
l 2>&1; then
-	  notinst_deplibs=3D
-	  relink_command=3D
-
-	  # Note that it is not necessary on cygwin/mingw to append a dot to
-	  # foo even if both foo and FILE.exe exist: automatic-append-.exe
-	  # behavior happens only for exec(3), not for open(2)!  Also, sourcing
-	  # `FILE.' does not work on cygwin managed mounts.
-	  #
-	  # If there is no directory component, then add one.
-	  case $wrapper in
-	  */* | *\\*) . ${wrapper} ;;
-	  *) . ./${wrapper} ;;
-	  esac
-
-	  # Check the variables that should have been set.
-	  if test -z "$notinst_deplibs"; then
-	    $echo "$modename: invalid libtool wrapper script \`$wrapper'" 1>&2
-	    exit $EXIT_FAILURE
-	  fi
-
-	  finalize=3Dyes
-	  for lib in $notinst_deplibs; do
-	    # Check to see that each library is installed.
-	    libdir=3D
-	    if test -f "$lib"; then
-	      # If there is no directory component, then add one.
-	      case $lib in
-	      */* | *\\*) . $lib ;;
-	      *) . ./$lib ;;
-	      esac
-	    fi
-	    libfile=3D"$libdir/"`$echo "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsu=
ite: skip nested quoting test
-	    if test -n "$libdir" && test ! -f "$libfile"; then
-	      $echo "$modename: warning: \`$lib' has not been installed in \`$lib=
dir'" 1>&2
-	      finalize=3Dno
-	    fi
-	  done
-
-	  relink_command=3D
-	  # Note that it is not necessary on cygwin/mingw to append a dot to
-	  # foo even if both foo and FILE.exe exist: automatic-append-.exe
-	  # behavior happens only for exec(3), not for open(2)!  Also, sourcing
-	  # `FILE.' does not work on cygwin managed mounts.
-	  #
-	  # If there is no directory component, then add one.
-	  case $wrapper in
-	  */* | *\\*) . ${wrapper} ;;
-	  *) . ./${wrapper} ;;
-	  esac
-
-	  outputname=3D
-	  if test "$fast_install" =3D no && test -n "$relink_command"; then
-	    if test "$finalize" =3D yes && test -z "$run"; then
-	      tmpdir=3D`func_mktempdir`
-	      file=3D`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'`
-	      outputname=3D"$tmpdir/$file"
-	      # Replace the output file specification.
-	      relink_command=3D`$echo "X$relink_command" | $Xsed -e 's%@OUTPUT@%'=
"$outputname"'%g'`
-
-	      $show "$relink_command"
-	      if $run eval "$relink_command"; then :
-	      else
-		$echo "$modename: error: relink \`$file' with the above command before i=
nstalling it" 1>&2
-		${rm}r "$tmpdir"
-		continue
-	      fi
-	      file=3D"$outputname"
-	    else
-	      $echo "$modename: warning: cannot relink \`$file'" 1>&2
-	    fi
-	  else
-	    # Install the binary that we compiled earlier.
-	    file=3D`$echo "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/=
\1%"`
-	  fi
-	fi
-
-	# remove .exe since cygwin /usr/bin/install will append another
-	# one anyway=20
-	case $install_prog,$host in
-	*/usr/bin/install*,*cygwin*)
-	  case $file:$destfile in
-	  *.exe:*.exe)
-	    # this is ok
-	    ;;
-	  *.exe:*)
-	    destfile=3D$destfile.exe
-	    ;;
-	  *:*.exe)
-	    destfile=3D`$echo $destfile | ${SED} -e 's,.exe$,,'`
-	    ;;
-	  esac
-	  ;;
-	esac
-	$show "$install_prog$stripme $file $destfile"
-	$run eval "$install_prog\$stripme \$file \$destfile" || exit $?
-	test -n "$outputname" && ${rm}r "$tmpdir"
-	;;
-      esac
-    done
-
-    for file in $staticlibs; do
-      name=3D`$echo "X$file" | $Xsed -e 's%^.*/%%'`
-
-      # Set up the ranlib parameters.
-      oldlib=3D"$destdir/$name"
-
-      $show "$install_prog $file $oldlib"
-      $run eval "$install_prog \$file \$oldlib" || exit $?
-
-      if test -n "$stripme" && test -n "$old_striplib"; then
-	$show "$old_striplib $oldlib"
-	$run eval "$old_striplib $oldlib" || exit $?
-      fi
-
-      # Do each command in the postinstall commands.
-      cmds=3D$old_postinstall_cmds
-      save_ifs=3D"$IFS"; IFS=3D'~'
-      for cmd in $cmds; do
-	IFS=3D"$save_ifs"
-	eval cmd=3D\"$cmd\"
-	$show "$cmd"
-	$run eval "$cmd" || exit $?
-      done
-      IFS=3D"$save_ifs"
-    done
-
-    if test -n "$future_libdirs"; then
-      $echo "$modename: warning: remember to run \`$progname --finish$futu=
re_libdirs'" 1>&2
-    fi
-
-    if test -n "$current_libdirs"; then
-      # Maybe just do a dry run.
-      test -n "$run" && current_libdirs=3D" -n$current_libdirs"
-      exec_cmd=3D'$SHELL $progpath $preserve_args --finish$current_libdirs'
-    else
-      exit $EXIT_SUCCESS
-    fi
-    ;;
-
-  # libtool finish mode
-  finish)
-    modename=3D"$modename: finish"
-    libdirs=3D"$nonopt"
-    admincmds=3D
-
-    if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then
-      for dir
-      do
-	libdirs=3D"$libdirs $dir"
-      done
-
-      for libdir in $libdirs; do
-	if test -n "$finish_cmds"; then
-	  # Do each command in the finish commands.
-	  cmds=3D$finish_cmds
-	  save_ifs=3D"$IFS"; IFS=3D'~'
-	  for cmd in $cmds; do
-	    IFS=3D"$save_ifs"
-	    eval cmd=3D\"$cmd\"
-	    $show "$cmd"
-	    $run eval "$cmd" || admincmds=3D"$admincmds
-       $cmd"
-	  done
-	  IFS=3D"$save_ifs"
-	fi
-	if test -n "$finish_eval"; then
-	  # Do the single finish_eval.
-	  eval cmds=3D\"$finish_eval\"
-	  $run eval "$cmds" || admincmds=3D"$admincmds
-       $cmds"
-	fi
-      done
-    fi
-
-    # Exit here if they wanted silent mode.
-    test "$show" =3D : && exit $EXIT_SUCCESS
-
-    $echo "X--------------------------------------------------------------=
--------" | $Xsed
-    $echo "Libraries have been installed in:"
-    for libdir in $libdirs; do
-      $echo "   $libdir"
-    done
-    $echo
-    $echo "If you ever happen to want to link against installed libraries"
-    $echo "in a given directory, LIBDIR, you must either use libtool, and"
-    $echo "specify the full pathname of the library, or use the \`-LLIBDIR=
'"
-    $echo "flag during linking and do at least one of the following:"
-    if test -n "$shlibpath_var"; then
-      $echo "   - add LIBDIR to the \`$shlibpath_var' environment variable"
-      $echo "     during execution"
-    fi
-    if test -n "$runpath_var"; then
-      $echo "   - add LIBDIR to the \`$runpath_var' environment variable"
-      $echo "     during linking"
-    fi
-    if test -n "$hardcode_libdir_flag_spec"; then
-      libdir=3DLIBDIR
-      eval flag=3D\"$hardcode_libdir_flag_spec\"
-
-      $echo "   - use the \`$flag' linker flag"
-    fi
-    if test -n "$admincmds"; then
-      $echo "   - have your system administrator run these commands:$admin=
cmds"
-    fi
-    if test -f /etc/ld.so.conf; then
-      $echo "   - have your system administrator add LIBDIR to \`/etc/ld.s=
o.conf'"
-    fi
-    $echo
-    $echo "See any operating system documentation about shared libraries f=
or"
-    $echo "more information, such as the ld(1) and ld.so(8) manual pages."
-    $echo "X--------------------------------------------------------------=
--------" | $Xsed
-    exit $EXIT_SUCCESS
-    ;;
-
-  # libtool execute mode
-  execute)
-    modename=3D"$modename: execute"
-
-    # The first argument is the command name.
-    cmd=3D"$nonopt"
-    if test -z "$cmd"; then
-      $echo "$modename: you must specify a COMMAND" 1>&2
-      $echo "$help"
-      exit $EXIT_FAILURE
-    fi
-
-    # Handle -dlopen flags immediately.
-    for file in $execute_dlfiles; do
-      if test ! -f "$file"; then
-	$echo "$modename: \`$file' is not a file" 1>&2
-	$echo "$help" 1>&2
-	exit $EXIT_FAILURE
-      fi
-
-      dir=3D
-      case $file in
-      *.la)
-	# Check to see that this really is a libtool archive.
-	if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null =
2>&1; then :
-	else
-	  $echo "$modename: \`$lib' is not a valid libtool archive" 1>&2
-	  $echo "$help" 1>&2
-	  exit $EXIT_FAILURE
-	fi
-
-	# Read the libtool library.
-	dlname=3D
-	library_names=3D
-
-	# If there is no directory component, then add one.
-	case $file in
-	*/* | *\\*) . $file ;;
-	*) . ./$file ;;
-	esac
-
-	# Skip this library if it cannot be dlopened.
-	if test -z "$dlname"; then
-	  # Warn if it was a shared library.
-	  test -n "$library_names" && $echo "$modename: warning: \`$file' was not=
 linked with \`-export-dynamic'"
-	  continue
-	fi
-
-	dir=3D`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
-	test "X$dir" =3D "X$file" && dir=3D.
-
-	if test -f "$dir/$objdir/$dlname"; then
-	  dir=3D"$dir/$objdir"
-	else
-	  $echo "$modename: cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'"=
 1>&2
-	  exit $EXIT_FAILURE
-	fi
-	;;
-
-      *.lo)
-	# Just add the directory containing the .lo file.
-	dir=3D`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
-	test "X$dir" =3D "X$file" && dir=3D.
-	;;
-
-      *)
-	$echo "$modename: warning \`-dlopen' is ignored for non-libtool libraries=
 and objects" 1>&2
-	continue
-	;;
-      esac
-
-      # Get the absolute pathname.
-      absdir=3D`cd "$dir" && pwd`
-      test -n "$absdir" && dir=3D"$absdir"
-
-      # Now add the directory to shlibpath_var.
-      if eval "test -z \"\$$shlibpath_var\""; then
-	eval "$shlibpath_var=3D\"\$dir\""
-      else
-	eval "$shlibpath_var=3D\"\$dir:\$$shlibpath_var\""
-      fi
-    done
-
-    # This variable tells wrapper scripts just to set shlibpath_var
-    # rather than running their programs.
-    libtool_execute_magic=3D"$magic"
-
-    # Check if any of the arguments is a wrapper script.
-    args=3D
-    for file
-    do
-      case $file in
-      -*) ;;
-      *)
-	# Do a test to see if this is really a libtool program.
-	if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null =
2>&1; then
-	  # If there is no directory component, then add one.
-	  case $file in
-	  */* | *\\*) . $file ;;
-	  *) . ./$file ;;
-	  esac
-
-	  # Transform arg to wrapped name.
-	  file=3D"$progdir/$program"
-	fi
-	;;
-      esac
-      # Quote arguments (to preserve shell metacharacters).
-      file=3D`$echo "X$file" | $Xsed -e "$sed_quote_subst"`
-      args=3D"$args \"$file\""
-    done
-
-    if test -z "$run"; then
-      if test -n "$shlibpath_var"; then
-	# Export the shlibpath_var.
-	eval "export $shlibpath_var"
-      fi
-
-      # Restore saved environment variables
-      if test "${save_LC_ALL+set}" =3D set; then
-	LC_ALL=3D"$save_LC_ALL"; export LC_ALL
-      fi
-      if test "${save_LANG+set}" =3D set; then
-	LANG=3D"$save_LANG"; export LANG
-      fi
-
-      # Now prepare to actually exec the command.
-      exec_cmd=3D"\$cmd$args"
-    else
-      # Display what would be done.
-      if test -n "$shlibpath_var"; then
-	eval "\$echo \"\$shlibpath_var=3D\$$shlibpath_var\""
-	$echo "export $shlibpath_var"
-      fi
-      $echo "$cmd$args"
-      exit $EXIT_SUCCESS
-    fi
-    ;;
-
-  # libtool clean and uninstall mode
-  clean | uninstall)
-    modename=3D"$modename: $mode"
-    rm=3D"$nonopt"
-    files=3D
-    rmforce=3D
-    exit_status=3D0
-
-    # This variable tells wrapper scripts just to set variables rather
-    # than running their programs.
-    libtool_install_magic=3D"$magic"
-
     for arg
     do
       case $arg in
-      -f) rm=3D"$rm $arg"; rmforce=3Dyes ;;
-      -*) rm=3D"$rm $arg" ;;
-      *) files=3D"$files $arg" ;;
+      -f) func_append RM " $arg"; rmforce=3Dyes ;;
+      -*) func_append RM " $arg" ;;
+      *) func_append files " $arg" ;;
       esac
     done
=20
-    if test -z "$rm"; then
-      $echo "$modename: you must specify an RM program" 1>&2
-      $echo "$help" 1>&2
-      exit $EXIT_FAILURE
-    fi
+    test -z "$RM" && \
+      func_fatal_help "you must specify an RM program"
=20
     rmdirs=3D
=20
-    origobjdir=3D"$objdir"
     for file in $files; do
-      dir=3D`$echo "X$file" | $Xsed -e 's%/[^/]*$%%'`
-      if test "X$dir" =3D "X$file"; then
-	dir=3D.
-	objdir=3D"$origobjdir"
+      func_dirname "$file" "" "."
+      dir=3D"$func_dirname_result"
+      if test "X$dir" =3D X.; then
+	odir=3D"$objdir"
       else
-	objdir=3D"$dir/$origobjdir"
+	odir=3D"$dir/$objdir"
       fi
-      name=3D`$echo "X$file" | $Xsed -e 's%^.*/%%'`
-      test "$mode" =3D uninstall && objdir=3D"$dir"
-
-      # Remember objdir for removal later, being careful to avoid duplicat=
es
-      if test "$mode" =3D clean; then
+      func_basename "$file"
+      name=3D"$func_basename_result"
+      test "$opt_mode" =3D uninstall && odir=3D"$dir"
+
+      # Remember odir for removal later, being careful to avoid duplicates
+      if test "$opt_mode" =3D clean; then
 	case " $rmdirs " in
-	  *" $objdir "*) ;;
-	  *) rmdirs=3D"$rmdirs $objdir" ;;
+	  *" $odir "*) ;;
+	  *) func_append rmdirs " $odir" ;;
 	esac
       fi
=20
       # Don't error if the file doesn't exist and rm -f was used.
-      if (test -L "$file") >/dev/null 2>&1 \
-	|| (test -h "$file") >/dev/null 2>&1 \
-	|| test -f "$file"; then
+      if { test -L "$file"; } >/dev/null 2>&1 ||
+	 { test -h "$file"; } >/dev/null 2>&1 ||
+	 test -f "$file"; then
 	:
       elif test -d "$file"; then
 	exit_status=3D1
@@ -6499,55 +9483,32 @@
       case $name in
       *.la)
 	# Possibly a libtool archive, so verify it.
-	if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null =
2>&1; then
-	  . $dir/$name
+	if func_lalib_p "$file"; then
+	  func_source $dir/$name
=20
 	  # Delete the libtool libraries and symlinks.
 	  for n in $library_names; do
-	    rmfiles=3D"$rmfiles $objdir/$n"
+	    func_append rmfiles " $odir/$n"
 	  done
-	  test -n "$old_library" && rmfiles=3D"$rmfiles $objdir/$old_library"
-
-	  case "$mode" in
+	  test -n "$old_library" && func_append rmfiles " $odir/$old_library"
+
+	  case "$opt_mode" in
 	  clean)
-	    case "  $library_names " in
-	    # "  " in the beginning catches empty $dlname
+	    case " $library_names " in
 	    *" $dlname "*) ;;
-	    *) rmfiles=3D"$rmfiles $objdir/$dlname" ;;
+	    *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;;
 	    esac
-	     test -n "$libdir" && rmfiles=3D"$rmfiles $objdir/$name $objdir/${nam=
e}i"
+	    test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i"
 	    ;;
 	  uninstall)
 	    if test -n "$library_names"; then
 	      # Do each command in the postuninstall commands.
-	      cmds=3D$postuninstall_cmds
-	      save_ifs=3D"$IFS"; IFS=3D'~'
-	      for cmd in $cmds; do
-		IFS=3D"$save_ifs"
-		eval cmd=3D\"$cmd\"
-		$show "$cmd"
-		$run eval "$cmd"
-		if test "$?" -ne 0 && test "$rmforce" !=3D yes; then
-		  exit_status=3D1
-		fi
-	      done
-	      IFS=3D"$save_ifs"
+	      func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" =3D yes ||=
 exit_status=3D1'
 	    fi
=20
 	    if test -n "$old_library"; then
 	      # Do each command in the old_postuninstall commands.
-	      cmds=3D$old_postuninstall_cmds
-	      save_ifs=3D"$IFS"; IFS=3D'~'
-	      for cmd in $cmds; do
-		IFS=3D"$save_ifs"
-		eval cmd=3D\"$cmd\"
-		$show "$cmd"
-		$run eval "$cmd"
-		if test "$?" -ne 0 && test "$rmforce" !=3D yes; then
-		  exit_status=3D1
-		fi
-	      done
-	      IFS=3D"$save_ifs"
+	      func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" =3D ye=
s || exit_status=3D1'
 	    fi
 	    # FIXME: should reinstall the best remaining shared library.
 	    ;;
@@ -6557,286 +9518,95 @@
=20
       *.lo)
 	# Possibly a libtool object, so verify it.
-	if (${SED} -e '2q' $file | grep "^# Generated by .*$PACKAGE") >/dev/null =
2>&1; then
+	if func_lalib_p "$file"; then
=20
 	  # Read the .lo file
-	  . $dir/$name
+	  func_source $dir/$name
=20
 	  # Add PIC object to the list of files to remove.
-	  if test -n "$pic_object" \
-	     && test "$pic_object" !=3D none; then
-	    rmfiles=3D"$rmfiles $dir/$pic_object"
+	  if test -n "$pic_object" &&
+	     test "$pic_object" !=3D none; then
+	    func_append rmfiles " $dir/$pic_object"
 	  fi
=20
 	  # Add non-PIC object to the list of files to remove.
-	  if test -n "$non_pic_object" \
-	     && test "$non_pic_object" !=3D none; then
-	    rmfiles=3D"$rmfiles $dir/$non_pic_object"
+	  if test -n "$non_pic_object" &&
+	     test "$non_pic_object" !=3D none; then
+	    func_append rmfiles " $dir/$non_pic_object"
 	  fi
 	fi
 	;;
=20
       *)
-	if test "$mode" =3D clean ; then
+	if test "$opt_mode" =3D clean ; then
 	  noexename=3D$name
 	  case $file in
 	  *.exe)
-	    file=3D`$echo $file|${SED} 's,.exe$,,'`
-	    noexename=3D`$echo $name|${SED} 's,.exe$,,'`
+	    func_stripname '' '.exe' "$file"
+	    file=3D$func_stripname_result
+	    func_stripname '' '.exe' "$name"
+	    noexename=3D$func_stripname_result
 	    # $file with .exe has already been added to rmfiles,
 	    # add $file without .exe
-	    rmfiles=3D"$rmfiles $file"
+	    func_append rmfiles " $file"
 	    ;;
 	  esac
 	  # Do a test to see if this is a libtool program.
-	  if (${SED} -e '4q' $file | grep "^# Generated by .*$PACKAGE") >/dev/nul=
l 2>&1; then
-	    relink_command=3D
-	    . $dir/$noexename
+	  if func_ltwrapper_p "$file"; then
+	    if func_ltwrapper_executable_p "$file"; then
+	      func_ltwrapper_scriptname "$file"
+	      relink_command=3D
+	      func_source $func_ltwrapper_scriptname_result
+	      func_append rmfiles " $func_ltwrapper_scriptname_result"
+	    else
+	      relink_command=3D
+	      func_source $dir/$noexename
+	    fi
=20
 	    # note $name still contains .exe if it was in $file originally
 	    # as does the version of $file that was added into $rmfiles
-	    rmfiles=3D"$rmfiles $objdir/$name $objdir/${name}S.${objext}"
+	    func_append rmfiles " $odir/$name $odir/${name}S.${objext}"
 	    if test "$fast_install" =3D yes && test -n "$relink_command"; then
-	      rmfiles=3D"$rmfiles $objdir/lt-$name"
+	      func_append rmfiles " $odir/lt-$name"
 	    fi
 	    if test "X$noexename" !=3D "X$name" ; then
-	      rmfiles=3D"$rmfiles $objdir/lt-${noexename}.c"
+	      func_append rmfiles " $odir/lt-${noexename}.c"
 	    fi
 	  fi
 	fi
 	;;
       esac
-      $show "$rm $rmfiles"
-      $run $rm $rmfiles || exit_status=3D1
+      func_show_eval "$RM $rmfiles" 'exit_status=3D1'
     done
-    objdir=3D"$origobjdir"
=20
     # Try to remove the ${objdir}s in the directories where we deleted fil=
es
     for dir in $rmdirs; do
       if test -d "$dir"; then
-	$show "rmdir $dir"
-	$run rmdir $dir >/dev/null 2>&1
+	func_show_eval "rmdir $dir >/dev/null 2>&1"
       fi
     done
=20
     exit $exit_status
-    ;;
-
-  "")
-    $echo "$modename: you must specify a MODE" 1>&2
-    $echo "$generic_help" 1>&2
-    exit $EXIT_FAILURE
-    ;;
-  esac
-
-  if test -z "$exec_cmd"; then
-    $echo "$modename: invalid operation mode \`$mode'" 1>&2
-    $echo "$generic_help" 1>&2
-    exit $EXIT_FAILURE
-  fi
-fi # test -z "$show_help"
+}
+
+{ test "$opt_mode" =3D uninstall || test "$opt_mode" =3D clean; } &&
+    func_mode_uninstall ${1+"$@"}
+
+test -z "$opt_mode" && {
+  help=3D"$generic_help"
+  func_fatal_help "you must specify a MODE"
+}
+
+test -z "$exec_cmd" && \
+  func_fatal_help "invalid operation mode \`$opt_mode'"
=20
 if test -n "$exec_cmd"; then
-  eval exec $exec_cmd
+  eval exec "$exec_cmd"
   exit $EXIT_FAILURE
 fi
=20
-# We need to display help for each of the modes.
-case $mode in
-"") $echo \
-"Usage: $modename [OPTION]... [MODE-ARG]...
-
-Provide generalized library-building support services.
-
-    --config          show all configuration variables
-    --debug           enable verbose shell tracing
--n, --dry-run         display commands without modifying any files
-    --features        display basic configuration information and exit
-    --finish          same as \`--mode=3Dfinish'
-    --help            display this help message and exit
-    --mode=3DMODE       use operation mode MODE [default=3Dinferred from M=
ODE-ARGS]
-    --quiet           same as \`--silent'
-    --silent          don't print informational messages
-    --tag=3DTAG         use configuration variables from tag TAG
-    --version         print version information
-
-MODE must be one of the following:
-
-      clean           remove files from the build directory
-      compile         compile a source file into a libtool object
-      execute         automatically set library path, then run a program
-      finish          complete the installation of libtool libraries
-      install         install libraries or executables
-      link            create a library or an executable
-      uninstall       remove libraries from an installed directory
-
-MODE-ARGS vary depending on the MODE.  Try \`$modename --help --mode=3DMOD=
E' for
-a more detailed description of MODE.
-
-Report bugs to <bug-libtool at gnu.org>."
-  exit $EXIT_SUCCESS
-  ;;
-
-clean)
-  $echo \
-"Usage: $modename [OPTION]... --mode=3Dclean RM [RM-OPTION]... FILE...
-
-Remove files from the build directory.
-
-RM is the name of the program to use to delete files associated with each =
FILE
-(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be pass=
ed
-to RM.
-
-If FILE is a libtool library, object or program, all the files associated
-with it are deleted. Otherwise, only FILE itself is deleted using RM."
-  ;;
-
-compile)
-  $echo \
-"Usage: $modename [OPTION]... --mode=3Dcompile COMPILE-COMMAND... SOURCEFI=
LE
-
-Compile a source file into a libtool library object.
-
-This mode accepts the following additional options:
-
-  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE
-  -prefer-pic       try to building PIC objects only
-  -prefer-non-pic   try to building non-PIC objects only
-  -static           always build a \`.o' file suitable for static linking
-
-COMPILE-COMMAND is a command to be used in creating a \`standard' object f=
ile
-from the given SOURCEFILE.
-
-The output file name is determined by removing the directory component from
-SOURCEFILE, then substituting the C source code suffix \`.c' with the
-library object suffix, \`.lo'."
-  ;;
-
-execute)
-  $echo \
-"Usage: $modename [OPTION]... --mode=3Dexecute COMMAND [ARGS]...
-
-Automatically set library path, then run a program.
-
-This mode accepts the following additional options:
-
-  -dlopen FILE      add the directory containing FILE to the library path
-
-This mode sets the library path environment variable according to \`-dlope=
n'
-flags.
-
-If any of the ARGS are libtool executable wrappers, then they are translat=
ed
-into their corresponding uninstalled binary, and any of their required lib=
rary
-directories are added to the library path.
-
-Then, COMMAND is executed, with ARGS as arguments."
-  ;;
-
-finish)
-  $echo \
-"Usage: $modename [OPTION]... --mode=3Dfinish [LIBDIR]...
-
-Complete the installation of libtool libraries.
-
-Each LIBDIR is a directory that contains libtool libraries.
-
-The commands that this mode executes may require superuser privileges.  Use
-the \`--dry-run' option if you just want to see what would be executed."
-  ;;
-
-install)
-  $echo \
-"Usage: $modename [OPTION]... --mode=3Dinstall INSTALL-COMMAND...
-
-Install executables or libraries.
-
-INSTALL-COMMAND is the installation command.  The first component should be
-either the \`install' or \`cp' program.
-
-The rest of the components are interpreted as arguments to that command (o=
nly
-BSD-compatible install options are recognized)."
-  ;;
-
-link)
-  $echo \
-"Usage: $modename [OPTION]... --mode=3Dlink LINK-COMMAND...
-
-Link object files or libraries together to form another library, or to
-create an executable program.
-
-LINK-COMMAND is a command using the C compiler that you would use to create
-a program from several object files.
-
-The following components of LINK-COMMAND are treated specially:
-
-  -all-static       do not do any dynamic linking at all
-  -avoid-version    do not add a version suffix if possible
-  -dlopen FILE      \`-dlpreopen' FILE if it cannot be dlopened at runtime
-  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbo=
ls
-  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dls=
ym(3)
-  -export-symbols SYMFILE
-		    try to export only the symbols listed in SYMFILE
-  -export-symbols-regex REGEX
-		    try to export only the symbols matching REGEX
-  -LLIBDIR          search LIBDIR for required installed libraries
-  -lNAME            OUTPUT-FILE requires the installed library libNAME
-  -module           build a library that can dlopened
-  -no-fast-install  disable the fast-install mode
-  -no-install       link a not-installable executable
-  -no-undefined     declare that a library does not refer to external symb=
ols
-  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects
-  -objectlist FILE  Use a list of object files found in FILE to specify ob=
jects
-  -precious-files-regex REGEX
-                    don't remove output files matching REGEX
-  -release RELEASE  specify package release information
-  -rpath LIBDIR     the created library will eventually be installed in LI=
BDIR
-  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and librari=
es
-  -static           do not do any dynamic linking of libtool libraries
-  -version-info CURRENT[:REVISION[:AGE]]
-		    specify library version info [each variable defaults to 0]
-
-All other options (arguments beginning with \`-') are ignored.
-
-Every other argument is treated as a filename.  Files ending in \`.la' are
-treated as uninstalled libtool libraries, other files are standard or libr=
ary
-object files.
-
-If the OUTPUT-FILE ends in \`.la', then a libtool library is created,
-only library objects (\`.lo' files) may be specified, and \`-rpath' is
-required, except when creating a convenience library.
-
-If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created
-using \`ar' and \`ranlib', or on Windows using \`lib'.
-
-If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object f=
ile
-is created, otherwise an executable program is created."
-  ;;
-
-uninstall)
-  $echo \
-"Usage: $modename [OPTION]... --mode=3Duninstall RM [RM-OPTION]... FILE...
-
-Remove libraries from an installation directory.
-
-RM is the name of the program to use to delete files associated with each =
FILE
-(typically \`/bin/rm').  RM-OPTIONS are options (such as \`-f') to be pass=
ed
-to RM.
-
-If FILE is a libtool library, all the files associated with it are deleted.
-Otherwise, only FILE itself is deleted using RM."
-  ;;
-
-*)
-  $echo "$modename: invalid operation mode \`$mode'" 1>&2
-  $echo "$help" 1>&2
-  exit $EXIT_FAILURE
-  ;;
-esac
-
-$echo
-$echo "Try \`$modename --help' for more information about other modes."
-
-exit $?
+exit $exit_status
+
=20
 # The TAGs below are defined such that we never get into a situation
 # in which we disable both kinds of libraries.  Given conflicting
@@ -6850,14 +9620,17 @@
 # configuration.  But we'll never go from static-only to shared-only.
=20
 # ### BEGIN LIBTOOL TAG CONFIG: disable-shared
-disable_libs=3Dshared
+build_libtool_libs=3Dno
+build_old_libs=3Dyes
 # ### END LIBTOOL TAG CONFIG: disable-shared
=20
 # ### BEGIN LIBTOOL TAG CONFIG: disable-static
-disable_libs=3Dstatic
+build_old_libs=3D`case $build_libtool_libs in yes) echo no;; *) echo yes;;=
 esac`
 # ### END LIBTOOL TAG CONFIG: disable-static
=20
 # Local Variables:
 # mode:shell-script
 # sh-indentation:2
 # End:
+# vi:sw=3D2
+
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/missing
--- a/head/crypto/heimdal/missing	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/missing	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
 #! /bin/sh
 # Common stub for a few missing GNU programs while installing.
=20
-scriptversion=3D2006-05-10.23
+scriptversion=3D2009-04-28.21; # UTC
=20
-# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006
-#   Free Software Foundation, Inc.
+# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006,
+# 2008, 2009 Free Software Foundation, Inc.
 # Originally by Fran,cois Pinard <pinard at iro.umontreal.ca>, 1996.
=20
 # This program is free software; you can redistribute it and/or modify
@@ -18,9 +18,7 @@
 # GNU General Public License for more details.
=20
 # You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-# 02110-1301, USA.
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
=20
 # As a special exception to the GNU General Public License, if you
 # distribute this file as part of a program that contains a
@@ -89,6 +87,9 @@
   tar          try tar, gnutar, gtar, then tar without non-portable flags
   yacc         create \`y.tab.[ch]', if possible, from existing .[ch]
=20
+Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and
+\`g' are ignored when checking the name.
+
 Send bug reports to <bug-automake at gnu.org>."
     exit $?
     ;;
@@ -106,15 +107,22 @@
=20
 esac
=20
+# normalize program name to check for.
+program=3D`echo "$1" | sed '
+  s/^gnu-//; t
+  s/^gnu//; t
+  s/^g//; t'`
+
 # Now exit if we have it, but it failed.  Also exit now if we
 # don't have it and --version was passed (most likely to detect
-# the program).
+# the program).  This is about non-GNU programs, so use $1 not
+# $program.
 case $1 in
-  lex|yacc)
+  lex*|yacc*)
     # Not GNU programs, they don't have --version.
     ;;
=20
-  tar)
+  tar*)
     if test -n "$run"; then
        echo 1>&2 "ERROR: \`tar' requires --run"
        exit 1
@@ -138,7 +146,7 @@
=20
 # If it does not exist, or fails to run (possibly an outdated version),
 # try to emulate it.
-case $1 in
+case $program in
   aclocal*)
     echo 1>&2 "\
 WARNING: \`$1' is $msg.  You should only need it if
@@ -148,7 +156,7 @@
     touch aclocal.m4
     ;;
=20
-  autoconf)
+  autoconf*)
     echo 1>&2 "\
 WARNING: \`$1' is $msg.  You should only need it if
          you modified \`${configure_ac}'.  You might want to install the
@@ -157,7 +165,7 @@
     touch configure
     ;;
=20
-  autoheader)
+  autoheader*)
     echo 1>&2 "\
 WARNING: \`$1' is $msg.  You should only need it if
          you modified \`acconfig.h' or \`${configure_ac}'.  You might want
@@ -187,7 +195,7 @@
 	   while read f; do touch "$f"; done
     ;;
=20
-  autom4te)
+  autom4te*)
     echo 1>&2 "\
 WARNING: \`$1' is needed, but is $msg.
          You might have modified some files without having the
@@ -210,7 +218,7 @@
     fi
     ;;
=20
-  bison|yacc)
+  bison*|yacc*)
     echo 1>&2 "\
 WARNING: \`$1' $msg.  You should only need it if
          you modified a \`.y' file.  You may need the \`Bison' package
@@ -240,7 +248,7 @@
     fi
     ;;
=20
-  lex|flex)
+  lex*|flex*)
     echo 1>&2 "\
 WARNING: \`$1' is $msg.  You should only need it if
          you modified a \`.l' file.  You may need the \`Flex' package
@@ -263,7 +271,7 @@
     fi
     ;;
=20
-  help2man)
+  help2man*)
     echo 1>&2 "\
 WARNING: \`$1' is $msg.  You should only need it if
 	 you modified a dependency of a manual page.  You may need the
@@ -277,11 +285,11 @@
     else
 	test -z "$file" || exec >$file
 	echo ".ab help2man is required to generate this page"
-	exit 1
+	exit $?
     fi
     ;;
=20
-  makeinfo)
+  makeinfo*)
     echo 1>&2 "\
 WARNING: \`$1' is $msg.  You should only need it if
          you modified a \`.texi' or \`.texinfo' file, or any other file
@@ -310,7 +318,7 @@
     touch $file
     ;;
=20
-  tar)
+  tar*)
     shift
=20
     # We have already tried tar in the generic part.
@@ -363,5 +371,6 @@
 # eval: (add-hook 'write-file-hooks 'time-stamp)
 # time-stamp-start: "scriptversion=3D"
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-end: "$"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
 # End:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/tools/Makefile.am
--- a/head/crypto/heimdal/tools/Makefile.am	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/tools/Makefile.am	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $Id: Makefile.am 22413 2008-01-12 05:58:14Z lha $
+# $Id$
=20
 include $(top_srcdir)/Makefile.am.common
=20
@@ -20,6 +20,7 @@
 		-e "s!@exec_prefix\@!$(exec_prefix)!g" \
 		-e "s!@libdir\@!$(libdir)!g" \
 		-e "s!@includedir\@!$(includedir)!g" \
+		-e "s!@PTHREAD_LIBADD\@!$(PTHREAD_LIBADD)!g" \
 		-e "s!@LIB_crypt\@!$(LIB_crypt)!g" \
 		-e "s!@LIB_dbopen\@!$(LIB_dbopen)!g" \
 		-e "s!@INCLUDE_hcrypto\@!$(INCLUDE_hcrypto)!g" \
@@ -39,8 +40,8 @@
 	mv [email protected] $@
=20
 EXTRA_DIST =3D \
+	NTMakefile \
 	$(man_MANS) \
-	heimdal-build.sh \
 	krb5-config.in \
 	heimdal-gssapi.pc.in \
 	kdc-log-analyze.pl
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/tools/Makefile.in
--- a/head/crypto/heimdal/tools/Makefile.in	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/tools/Makefile.in	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,9 @@
-# Makefile.in generated by automake 1.10 from Makefile.am.
+# Makefile.in generated by automake 1.11.1 from Makefile.am.
 # @configure_input@
=20
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,
+# Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
@@ -14,17 +15,18 @@
=20
 @SET_MAKE@
=20
-# $Id: Makefile.am 22413 2008-01-12 05:58:14Z lha $
+# $Id$
=20
-# $Id: Makefile.am.common 10998 2002-05-19 18:35:37Z joda $
+# $Id$
=20
-# $Id: Makefile.am.common 22488 2008-01-21 11:47:22Z lha $
+# $Id$
=20
=20
 VPATH =3D @srcdir@
 pkgdatadir =3D $(datadir)/@PACKAGE@
+pkgincludedir =3D $(includedir)/@PACKAGE@
 pkglibdir =3D $(libdir)/@PACKAGE@
-pkgincludedir =3D $(includedir)/@PACKAGE@
+pkglibexecdir =3D $(libexecdir)/@PACKAGE@
 am__cd =3D CDPATH=3D"$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
 install_sh_DATA =3D $(install_sh) -c -m 644
 install_sh_PROGRAM =3D $(install_sh) -c
@@ -45,7 +47,7 @@
 subdir =3D tools
 ACLOCAL_M4 =3D $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps =3D $(top_srcdir)/cf/aix.m4 \
-	$(top_srcdir)/cf/auth-modules.m4 $(top_srcdir)/cf/autobuild.m4 \
+	$(top_srcdir)/cf/auth-modules.m4 \
 	$(top_srcdir)/cf/broken-getaddrinfo.m4 \
 	$(top_srcdir)/cf/broken-glob.m4 \
 	$(top_srcdir)/cf/broken-realloc.m4 \
@@ -60,7 +62,7 @@
 	$(top_srcdir)/cf/check-var.m4 $(top_srcdir)/cf/check-x.m4 \
 	$(top_srcdir)/cf/check-xau.m4 $(top_srcdir)/cf/crypto.m4 \
 	$(top_srcdir)/cf/db.m4 $(top_srcdir)/cf/destdirs.m4 \
-	$(top_srcdir)/cf/dlopen.m4 \
+	$(top_srcdir)/cf/dispatch.m4 $(top_srcdir)/cf/dlopen.m4 \
 	$(top_srcdir)/cf/find-func-no-libs.m4 \
 	$(top_srcdir)/cf/find-func-no-libs2.m4 \
 	$(top_srcdir)/cf/find-func.m4 \
@@ -74,9 +76,12 @@
 	$(top_srcdir)/cf/krb-readline.m4 \
 	$(top_srcdir)/cf/krb-struct-spwd.m4 \
 	$(top_srcdir)/cf/krb-struct-winsize.m4 \
-	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/mips-abi.m4 \
-	$(top_srcdir)/cf/misc.m4 $(top_srcdir)/cf/need-proto.m4 \
-	$(top_srcdir)/cf/osfc2.m4 $(top_srcdir)/cf/otp.m4 \
+	$(top_srcdir)/cf/largefile.m4 $(top_srcdir)/cf/libtool.m4 \
+	$(top_srcdir)/cf/ltoptions.m4 $(top_srcdir)/cf/ltsugar.m4 \
+	$(top_srcdir)/cf/ltversion.m4 $(top_srcdir)/cf/lt~obsolete.m4 \
+	$(top_srcdir)/cf/mips-abi.m4 $(top_srcdir)/cf/misc.m4 \
+	$(top_srcdir)/cf/need-proto.m4 $(top_srcdir)/cf/osfc2.m4 \
+	$(top_srcdir)/cf/otp.m4 $(top_srcdir)/cf/pkg.m4 \
 	$(top_srcdir)/cf/proto-compat.m4 $(top_srcdir)/cf/pthreads.m4 \
 	$(top_srcdir)/cf/resolv.m4 $(top_srcdir)/cf/retsigtype.m4 \
 	$(top_srcdir)/cf/roken-frag.m4 \
@@ -84,78 +89,99 @@
 	$(top_srcdir)/cf/telnet.m4 $(top_srcdir)/cf/test-package.m4 \
 	$(top_srcdir)/cf/version-script.m4 $(top_srcdir)/cf/wflags.m4 \
 	$(top_srcdir)/cf/win32.m4 $(top_srcdir)/cf/with-all.m4 \
-	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.in
+	$(top_srcdir)/acinclude.m4 $(top_srcdir)/configure.ac
 am__configure_deps =3D $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
 	$(ACLOCAL_M4)
 mkinstalldirs =3D $(install_sh) -d
 CONFIG_HEADER =3D $(top_builddir)/include/config.h
 CONFIG_CLEAN_FILES =3D
-am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" \
-	"$(DESTDIR)$(pkgconfigdir)"
-binSCRIPT_INSTALL =3D $(INSTALL_SCRIPT)
-SCRIPTS =3D $(bin_SCRIPTS)
-depcomp =3D
-am__depfiles_maybe =3D
-SOURCES =3D
-DIST_SOURCES =3D
-man1dir =3D $(mandir)/man1
-MANS =3D $(man_MANS)
+CONFIG_CLEAN_VPATH_FILES =3D
 am__vpath_adj_setup =3D srcdirstrip=3D`echo "$(srcdir)" | sed 's|.|.|g'`;
 am__vpath_adj =3D case $$p in \
     $(srcdir)/*) f=3D`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
     *) f=3D$$p;; \
   esac;
-am__strip_dir =3D `echo $$p | sed -e 's|^.*/||'`;
-pkgconfigDATA_INSTALL =3D $(INSTALL_DATA)
+am__strip_dir =3D f=3D`echo $$p | sed -e 's|^.*/||'`;
+am__install_max =3D 40
+am__nobase_strip_setup =3D \
+  srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
+am__nobase_strip =3D \
+  for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
+am__nobase_list =3D $(am__nobase_strip_setup); \
+  for p in $$list; do echo "$$p $$p"; done | \
+  sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' |=
 \
+  $(AWK) 'BEGIN { files["."] =3D "" } { files[$$2] =3D files[$$2] " " $$1;=
 \
+    if (++n[$$2] =3D=3D $(am__install_max)) \
+      { print $$2, files[$$2]; n[$$2] =3D 0; files[$$2] =3D "" } } \
+    END { for (dir in files) print dir, files[dir] }'
+am__base_list =3D \
+  sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
+  sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
+am__installdirs =3D "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" \
+	"$(DESTDIR)$(pkgconfigdir)"
+SCRIPTS =3D $(bin_SCRIPTS)
+SOURCES =3D
+DIST_SOURCES =3D
+man1dir =3D $(mandir)/man1
+MANS =3D $(man_MANS)
 DATA =3D $(pkgconfig_DATA)
 DISTFILES =3D $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL =3D @ACLOCAL@
 AIX_EXTRA_KAFS =3D @AIX_EXTRA_KAFS@
 AMTAR =3D @AMTAR@
 AR =3D @AR@
+ASN1_COMPILE =3D @ASN1_COMPILE@
+ASN1_COMPILE_DEP =3D @ASN1_COMPILE_DEP@
 AUTOCONF =3D @AUTOCONF@
 AUTOHEADER =3D @AUTOHEADER@
 AUTOMAKE =3D @AUTOMAKE@
 AWK =3D @AWK@
 CANONICAL_HOST =3D @CANONICAL_HOST@
+CAPNG_CFLAGS =3D @CAPNG_CFLAGS@
+CAPNG_LIBS =3D @CAPNG_LIBS@
 CATMAN =3D @CATMAN@
 CATMANEXT =3D @CATMANEXT@
 CC =3D @CC@
+CCDEPMODE =3D @CCDEPMODE@
 CFLAGS =3D @CFLAGS@
 COMPILE_ET =3D @COMPILE_ET@
 CPP =3D @CPP@
 CPPFLAGS =3D @CPPFLAGS@
-CXX =3D @CXX@
-CXXCPP =3D @CXXCPP@
-CXXFLAGS =3D @CXXFLAGS@
 CYGPATH_W =3D @CYGPATH_W@
+DBHEADER =3D @DBHEADER@
 DBLIB =3D @DBLIB@
 DEFS =3D @DEFS@
+DEPDIR =3D @DEPDIR@
 DIR_com_err =3D @DIR_com_err@
 DIR_hcrypto =3D @DIR_hcrypto@
 DIR_hdbdir =3D @DIR_hdbdir@
 DIR_roken =3D @DIR_roken@
-ECHO =3D @ECHO@
+DLLTOOL =3D @DLLTOOL@
+DSYMUTIL =3D @DSYMUTIL@
+DUMPBIN =3D @DUMPBIN@
 ECHO_C =3D @ECHO_C@
 ECHO_N =3D @ECHO_N@
 ECHO_T =3D @ECHO_T@
 EGREP =3D @EGREP@
 EXEEXT =3D @EXEEXT@
-F77 =3D @F77@
-FFLAGS =3D @FFLAGS@
+FGREP =3D @FGREP@
 GREP =3D @GREP@
 GROFF =3D @GROFF@
 INCLUDES_roken =3D @INCLUDES_roken@
 INCLUDE_hcrypto =3D @INCLUDE_hcrypto@
 INCLUDE_hesiod =3D @INCLUDE_hesiod@
 INCLUDE_krb4 =3D @INCLUDE_krb4@
+INCLUDE_libedit =3D @INCLUDE_libedit@
+INCLUDE_libintl =3D @INCLUDE_libintl@
 INCLUDE_openldap =3D @INCLUDE_openldap@
 INCLUDE_readline =3D @INCLUDE_readline@
+INCLUDE_sqlite3 =3D @INCLUDE_sqlite3@
 INSTALL =3D @INSTALL@
 INSTALL_DATA =3D @INSTALL_DATA@
 INSTALL_PROGRAM =3D @INSTALL_PROGRAM@
 INSTALL_SCRIPT =3D @INSTALL_SCRIPT@
 INSTALL_STRIP_PROGRAM =3D @INSTALL_STRIP_PROGRAM@
+LD =3D @LD@
 LDFLAGS =3D @LDFLAGS@
 LDFLAGS_VERSION_SCRIPT =3D @LDFLAGS_VERSION_SCRIPT@
 LEX =3D @LEX@
@@ -179,10 +205,11 @@
 LIB_db_create =3D @LIB_db_create@
 LIB_dbm_firstkey =3D @LIB_dbm_firstkey@
 LIB_dbopen =3D @LIB_dbopen@
+LIB_dispatch_async_f =3D @LIB_dispatch_async_f@
 LIB_dlopen =3D @LIB_dlopen@
 LIB_dn_expand =3D @LIB_dn_expand@
+LIB_dns_search =3D @LIB_dns_search@
 LIB_door_create =3D @LIB_door_create@
-LIB_el_init =3D @LIB_el_init@
 LIB_freeaddrinfo =3D @LIB_freeaddrinfo@
 LIB_gai_strerror =3D @LIB_gai_strerror@
 LIB_getaddrinfo =3D @LIB_getaddrinfo@
@@ -199,6 +226,8 @@
 LIB_hstrerror =3D @LIB_hstrerror@
 LIB_kdb =3D @LIB_kdb@
 LIB_krb4 =3D @LIB_krb4@
+LIB_libedit =3D @LIB_libedit@
+LIB_libintl =3D @LIB_libintl@
 LIB_loadquery =3D @LIB_loadquery@
 LIB_logout =3D @LIB_logout@
 LIB_logwtmp =3D @LIB_logwtmp@
@@ -214,31 +243,45 @@
 LIB_security =3D @LIB_security@
 LIB_setsockopt =3D @LIB_setsockopt@
 LIB_socket =3D @LIB_socket@
+LIB_sqlite3 =3D @LIB_sqlite3@
 LIB_syslog =3D @LIB_syslog@
 LIB_tgetent =3D @LIB_tgetent@
+LIPO =3D @LIPO@
 LN_S =3D @LN_S@
 LTLIBOBJS =3D @LTLIBOBJS@
 MAINT =3D @MAINT@
 MAKEINFO =3D @MAKEINFO@
+MANIFEST_TOOL =3D @MANIFEST_TOOL@
 MKDIR_P =3D @MKDIR_P@
+NM =3D @NM@
+NMEDIT =3D @NMEDIT@
+NO_AFS =3D @NO_AFS@
 NROFF =3D @NROFF@
+OBJDUMP =3D @OBJDUMP@
 OBJEXT =3D @OBJEXT@
+OTOOL =3D @OTOOL@
+OTOOL64 =3D @OTOOL64@
 PACKAGE =3D @PACKAGE@
 PACKAGE_BUGREPORT =3D @PACKAGE_BUGREPORT@
 PACKAGE_NAME =3D @PACKAGE_NAME@
 PACKAGE_STRING =3D @PACKAGE_STRING@
 PACKAGE_TARNAME =3D @PACKAGE_TARNAME@
+PACKAGE_URL =3D @PACKAGE_URL@
 PACKAGE_VERSION =3D @PACKAGE_VERSION@
 PATH_SEPARATOR =3D @PATH_SEPARATOR@
-PTHREADS_CFLAGS =3D @PTHREADS_CFLAGS@
-PTHREADS_LIBS =3D @PTHREADS_LIBS@
+PKG_CONFIG =3D @PKG_CONFIG@
+PTHREAD_CFLAGS =3D @PTHREAD_CFLAGS@
+PTHREAD_LDADD =3D @PTHREAD_LDADD@
+PTHREAD_LIBADD =3D @PTHREAD_LIBADD@
 RANLIB =3D @RANLIB@
+SED =3D @SED@
 SET_MAKE =3D @SET_MAKE@
 SHELL =3D @SHELL@
+SLC =3D @SLC@
+SLC_DEP =3D @SLC_DEP@
 STRIP =3D @STRIP@
 VERSION =3D @VERSION@
 VERSIONING =3D @VERSIONING@
-VOID_RETSIGTYPE =3D @VOID_RETSIGTYPE@
 WFLAGS =3D @WFLAGS@
 WFLAGS_NOIMPLICITINT =3D @WFLAGS_NOIMPLICITINT@
 WFLAGS_NOUNUSED =3D @WFLAGS_NOUNUSED@
@@ -253,10 +296,12 @@
 abs_srcdir =3D @abs_srcdir@
 abs_top_builddir =3D @abs_top_builddir@
 abs_top_srcdir =3D @abs_top_srcdir@
+ac_ct_AR =3D @ac_ct_AR@
 ac_ct_CC =3D @ac_ct_CC@
-ac_ct_CXX =3D @ac_ct_CXX@
-ac_ct_F77 =3D @ac_ct_F77@
+ac_ct_DUMPBIN =3D @ac_ct_DUMPBIN@
+am__include =3D @am__include@
 am__leading_dot =3D @am__leading_dot@
+am__quote =3D @am__quote@
 am__tar =3D @am__tar@
 am__untar =3D @am__untar@
 bindir =3D @bindir@
@@ -297,29 +342,34 @@
 sbindir =3D @sbindir@
 sharedstatedir =3D @sharedstatedir@
 srcdir =3D @srcdir@
+subdirs =3D @subdirs@
 sysconfdir =3D @sysconfdir@
 target_alias =3D @target_alias@
+top_build_prefix =3D @top_build_prefix@
 top_builddir =3D @top_builddir@
 top_srcdir =3D @top_srcdir@
-SUFFIXES =3D .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
-AM_CPPFLAGS =3D -I$(top_builddir)/include $(INCLUDES_roken)
+SUFFIXES =3D .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8
+DEFAULT_INCLUDES =3D -I. -I$(srcdir) -I$(top_builddir)/include -I$(top_src=
dir)/include
+AM_CPPFLAGS =3D $(INCLUDES_roken)
 @do_roken_rename_TRUE at ROKEN_RENAME =3D -DROKEN_RENAME
 AM_CFLAGS =3D $(WFLAGS)
 CP =3D cp
 buildinclude =3D $(top_builddir)/include
+LIB_el_init =3D @LIB_el_init@
 LIB_getattr =3D @LIB_getattr@
 LIB_getpwent_r =3D @LIB_getpwent_r@
 LIB_odm_initialize =3D @LIB_odm_initialize@
 LIB_setpcred =3D @LIB_setpcred@
 HESIODLIB =3D @HESIODLIB@
 HESIODINCLUDE =3D @HESIODINCLUDE@
+libexec_heimdaldir =3D $(libexecdir)/heimdal
 NROFF_MAN =3D groff -mandoc -Tascii
 LIB_kafs =3D $(top_builddir)/lib/kafs/libkafs.la $(AIX_EXTRA_KAFS)
 @KRB5_TRUE at LIB_krb5 =3D $(top_builddir)/lib/krb5/libkrb5.la \
 @KRB5_TRUE@	$(top_builddir)/lib/asn1/libasn1.la
=20
 @KRB5_TRUE at LIB_gssapi =3D $(top_builddir)/lib/gssapi/libgssapi.la
- at KRB5_TRUE@LIB_tsasl =3D $(top_builddir)/lib/tsasl/libtsasl.la
+LIB_heimbase =3D $(top_builddir)/base/libheimbase.la
 @DCE_TRUE at LIB_kdfs =3D $(top_builddir)/lib/kdfs/libkdfs.la
 bin_SCRIPTS =3D krb5-config
 pkgconfigdir =3D $(libdir)/pkgconfig
@@ -332,6 +382,7 @@
 		-e "s!@exec_prefix\@!$(exec_prefix)!g" \
 		-e "s!@libdir\@!$(libdir)!g" \
 		-e "s!@includedir\@!$(includedir)!g" \
+		-e "s!@PTHREAD_LIBADD\@!$(PTHREAD_LIBADD)!g" \
 		-e "s!@LIB_crypt\@!$(LIB_crypt)!g" \
 		-e "s!@LIB_dbopen\@!$(LIB_dbopen)!g" \
 		-e "s!@INCLUDE_hcrypto\@!$(INCLUDE_hcrypto)!g" \
@@ -342,8 +393,8 @@
 		-e "s!@LIBS\@!$(LIBS)!g"
=20
 EXTRA_DIST =3D \
+	NTMakefile \
 	$(man_MANS) \
-	heimdal-build.sh \
 	krb5-config.in \
 	heimdal-gssapi.pc.in \
 	kdc-log-analyze.pl
@@ -357,19 +408,19 @@
 all: all-am
=20
 .SUFFIXES:
-.SUFFIXES: .et .h .x .z .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
+.SUFFIXES: .et .h .x .z .hx .1 .3 .5 .8 .cat1 .cat3 .cat5 .cat8 .c
 $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_=
srcdir)/Makefile.am.common $(top_srcdir)/cf/Makefile.am.common $(am__config=
ure_deps)
 	@for dep in $?; do \
 	  case '$(am__configure_deps)' in \
 	    *$$dep*) \
-	      cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
-		&& exit 0; \
+	      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
+	        && { if test -f $@; then exit 0; else break; fi; }; \
 	      exit 1;; \
 	  esac; \
 	done; \
-	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign  --ignore-deps tools/Mak=
efile'; \
-	cd $(top_srcdir) && \
-	  $(AUTOMAKE) --foreign  --ignore-deps tools/Makefile
+	echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign tools/Makefile'; \
+	$(am__cd) $(top_srcdir) && \
+	  $(AUTOMAKE) --foreign tools/Makefile
 .PRECIOUS: Makefile
 Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
 	@case '$?' in \
@@ -387,93 +438,105 @@
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)
 	cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
+$(am__aclocal_m4_deps):
 install-binSCRIPTS: $(bin_SCRIPTS)
 	@$(NORMAL_INSTALL)
 	test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
-	@list=3D'$(bin_SCRIPTS)'; for p in $$list; do \
+	@list=3D'$(bin_SCRIPTS)'; test -n "$(bindir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  if test -f $$d$$p; then \
-	    f=3D`echo "$$p" | sed 's|^.*/||;$(transform)'`; \
-	    echo " $(binSCRIPT_INSTALL) '$$d$$p' '$(DESTDIR)$(bindir)/$$f'"; \
-	    $(binSCRIPT_INSTALL) "$$d$$p" "$(DESTDIR)$(bindir)/$$f"; \
-	  else :; fi; \
-	done
+	  if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \
+	done | \
+	sed -e 'p;s,.*/,,;n' \
+	    -e 'h;s|.*|.|' \
+	    -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \
+	$(AWK) 'BEGIN { files["."] =3D ""; dirs["."] =3D 1; } \
+	  { d=3D$$3; if (dirs[d] !=3D 1) { print "d", d; dirs[d] =3D 1 } \
+	    if ($$2 =3D=3D $$4) { files[d] =3D files[d] " " $$1; \
+	      if (++n[d] =3D=3D $(am__install_max)) { \
+		print "f", d, files[d]; n[d] =3D 0; files[d] =3D "" } } \
+	    else { print "f", d "/" $$4, $$1 } } \
+	  END { for (d in files) print "f", d, files[d] }' | \
+	while read type dir files; do \
+	     if test "$$dir" =3D .; then dir=3D; else dir=3D/$$dir; fi; \
+	     test -z "$$files" || { \
+	       echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \
+	       $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \
+	     } \
+	; done
=20
 uninstall-binSCRIPTS:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(bin_SCRIPTS)'; for p in $$list; do \
-	  f=3D`echo "$$p" | sed 's|^.*/||;$(transform)'`; \
-	  echo " rm -f '$(DESTDIR)$(bindir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(bindir)/$$f"; \
-	done
+	@list=3D'$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \
+	files=3D`for p in $$list; do echo "$$p"; done | \
+	       sed -e 's,.*/,,;$(transform)'`; \
+	test -n "$$list" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(bindir)" && rm -f $$files
=20
 mostlyclean-libtool:
 	-rm -f *.lo
=20
 clean-libtool:
 	-rm -rf .libs _libs
-install-man1: $(man1_MANS) $(man_MANS)
+install-man1: $(man_MANS)
 	@$(NORMAL_INSTALL)
 	test -z "$(man1dir)" || $(MKDIR_P) "$(DESTDIR)$(man1dir)"
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | while read p; do \
+	  if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	  echo "$$d$$p"; echo "$$p"; \
+	done | \
+	sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \
+	sed 'N;N;s,\n, ,g' | { \
+	list=3D; while read file base inst; do \
+	  if test "$$base" =3D "$$inst"; then list=3D"$$list $$file"; else \
+	    echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
+	    $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \
+	  fi; \
 	done; \
-	for i in $$list; do \
-	  if test -f $(srcdir)/$$i; then file=3D$(srcdir)/$$i; \
-	  else file=3D$$i; fi; \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	for i in $$list; do echo "$$i"; done | $(am__base_list) | \
+	while read files; do \
+	  test -z "$$files" || { \
+	    echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \
+	    $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \
+	done; }
+
 uninstall-man1:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(man1_MANS) $(dist_man1_MANS) $(nodist_man1_MANS)'; \
-	l2=3D'$(man_MANS) $(dist_man_MANS) $(nodist_man_MANS)'; \
-	for i in $$l2; do \
-	  case "$$i" in \
-	    *.1*) list=3D"$$list $$i" ;; \
-	  esac; \
-	done; \
-	for i in $$list; do \
-	  ext=3D`echo $$i | sed -e 's/^.*\\.//'`; \
-	  case "$$ext" in \
-	    1*) ;; \
-	    *) ext=3D'1' ;; \
-	  esac; \
-	  inst=3D`echo $$i | sed -e 's/\\.[0-9a-z]*$$//'`; \
-	  inst=3D`echo $$inst | sed -e 's/^.*\///'`; \
-	  inst=3D`echo $$inst | sed '$(transform)'`.$$ext; \
-	  echo " rm -f '$(DESTDIR)$(man1dir)/$$inst'"; \
-	  rm -f "$(DESTDIR)$(man1dir)/$$inst"; \
-	done
+	@list=3D''; test -n "$(man1dir)" || exit 0; \
+	files=3D`{ for i in $$list; do echo "$$i"; done; \
+	l2=3D'$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \
+	  sed -n '/\.1[a-z]*$$/p'; \
+	} | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \
+	      -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \
+	test -z "$$files" || { \
+	  echo " ( cd '$(DESTDIR)$(man1dir)' && rm -f" $$files ")"; \
+	  cd "$(DESTDIR)$(man1dir)" && rm -f $$files; }
 install-pkgconfigDATA: $(pkgconfig_DATA)
 	@$(NORMAL_INSTALL)
 	test -z "$(pkgconfigdir)" || $(MKDIR_P) "$(DESTDIR)$(pkgconfigdir)"
-	@list=3D'$(pkgconfig_DATA)'; for p in $$list; do \
+	@list=3D'$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=3D; \
+	for p in $$list; do \
 	  if test -f "$$p"; then d=3D; else d=3D"$(srcdir)/"; fi; \
-	  f=3D$(am__strip_dir) \
-	  echo " $(pkgconfigDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(pkgconfigdir)/$$f=
'"; \
-	  $(pkgconfigDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(pkgconfigdir)/$$f"; \
+	  echo "$$d$$p"; \
+	done | $(am__base_list) | \
+	while read files; do \
+	  echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(pkgconfigdir)'"; \
+	  $(INSTALL_DATA) $$files "$(DESTDIR)$(pkgconfigdir)" || exit $$?; \
 	done
=20
 uninstall-pkgconfigDATA:
 	@$(NORMAL_UNINSTALL)
-	@list=3D'$(pkgconfig_DATA)'; for p in $$list; do \
-	  f=3D$(am__strip_dir) \
-	  echo " rm -f '$(DESTDIR)$(pkgconfigdir)/$$f'"; \
-	  rm -f "$(DESTDIR)$(pkgconfigdir)/$$f"; \
-	done
+	@list=3D'$(pkgconfig_DATA)'; test -n "$(pkgconfigdir)" || list=3D; \
+	files=3D`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
+	test -n "$$files" || exit 0; \
+	echo " ( cd '$(DESTDIR)$(pkgconfigdir)' && rm -f" $$files ")"; \
+	cd "$(DESTDIR)$(pkgconfigdir)" && rm -f $$files
 tags: TAGS
 TAGS:
=20
@@ -482,6 +545,19 @@
=20
=20
 distdir: $(DISTFILES)
+	@list=3D'$(MANS)'; if test -n "$$list"; then \
+	  list=3D`for p in $$list; do \
+	    if test -f $$p; then d=3D; else d=3D"$(srcdir)/"; fi; \
+	    if test -f "$$d$$p"; then echo "$$d$$p"; else :; fi; done`; \
+	  if test -n "$$list" && \
+	    grep 'ab help2man is required to generate this page' $$list >/dev/nul=
l; then \
+	    echo "error: found man pages containing the \`missing help2man' repla=
cement text:" >&2; \
+	    grep -l 'ab help2man is required to generate this page' $$list | sed =
's/^/         /' >&2; \
+	    echo "       to fix them, install help2man, remove and regenerate the=
 man pages;" >&2; \
+	    echo "       typically \`make maintainer-clean' will remove them" >&2=
; \
+	    exit 1; \
+	  else :; fi; \
+	else :; fi
 	@srcdirstrip=3D`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	topsrcdirstrip=3D`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
 	list=3D'$(DISTFILES)'; \
@@ -497,13 +573,17 @@
 	  if test -f $$file || test -d $$file; then d=3D.; else d=3D$(srcdir); fi=
; \
 	  if test -d $$d/$$file; then \
 	    dir=3D`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
+	    if test -d "$(distdir)/$$file"; then \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
+	    fi; \
 	    if test -d $(srcdir)/$$file && test $$d !=3D $(srcdir); then \
-	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	      cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
+	      find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} =
\;; \
 	    fi; \
-	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	    cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
 	  else \
-	    test -f $(distdir)/$$file \
-	    || cp -p $$d/$$file $(distdir)/$$file \
+	    test -f "$(distdir)/$$file" \
+	    || cp -p $$d/$$file "$(distdir)/$$file" \
 	    || exit 1; \
 	  fi; \
 	done
@@ -539,6 +619,7 @@
=20
 distclean-generic:
 	-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
+	-test . =3D "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f=
 $(CONFIG_CLEAN_VPATH_FILES)
=20
 maintainer-clean-generic:
 	@echo "This command is intended for maintainers to use"
@@ -557,6 +638,8 @@
=20
 html: html-am
=20
+html-am:
+
 info: info-am
=20
 info-am:
@@ -564,23 +647,31 @@
 install-data-am: install-man install-pkgconfigDATA
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-data-hook
+install-dvi: install-dvi-am
=20
-install-dvi: install-dvi-am
+install-dvi-am:
=20
 install-exec-am: install-binSCRIPTS
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) install-exec-hook
-
 install-html: install-html-am
=20
+install-html-am:
+
 install-info: install-info-am
=20
+install-info-am:
+
 install-man: install-man1
=20
 install-pdf: install-pdf-am
=20
+install-pdf-am:
+
 install-ps: install-ps-am
=20
+install-ps-am:
+
 installcheck-am:
=20
 maintainer-clean: maintainer-clean-am
@@ -603,11 +694,10 @@
 	uninstall-pkgconfigDATA
 	@$(NORMAL_INSTALL)
 	$(MAKE) $(AM_MAKEFLAGS) uninstall-hook
-
 uninstall-man: uninstall-man1
=20
-.MAKE: install-am install-data-am install-exec-am install-strip \
-	uninstall-am
+.MAKE: check-am install-am install-data-am install-exec-am \
+	install-strip uninstall-am
=20
 .PHONY: all all-am all-local check check-am check-local clean \
 	clean-generic clean-libtool dist-hook distclean \
@@ -693,6 +783,9 @@
=20
 .x.c:
 	@cmp -s $< $@ 2> /dev/null || cp $< $@
+
+.hx.h:
+	@cmp -s $< $@ 2> /dev/null || cp $< $@
 #NROFF_MAN =3D nroff -man
 .1.cat1:
 	$(NROFF_MAN) $< > $@
@@ -778,7 +871,7 @@
 check-valgrind:
 	tobjdir=3D`cd $(top_builddir) && pwd` ; \
 	tsrcdir=3D`cd $(top_srcdir) && pwd` ; \
-	env TESTS_ENVIRONMENT=3D"$${tobjdir}/libtool --mode execute valgrind --le=
ak-check=3Dfull --trace-children=3Dyes --quiet -q --num-callers=3D30 --supp=
ressions=3D$${tsrcdir}/cf/valgrind-suppressions" make check
+	env TESTS_ENVIRONMENT=3D"$${tsrcdir}/cf/maybe-valgrind.sh -s $${tsrcdir} =
-o $${tobjdir}" make check
=20
 #
 # Target to please samba build farm, builds distfiles in-tree.
@@ -800,6 +893,7 @@
 heimdal-gssapi.pc: heimdal-gssapi.pc.in
 	$(subst) $(srcdir)/heimdal-gssapi.pc.in > [email protected]
 	mv [email protected] $@
+
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
 .NOEXPORT:
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/tools/heimdal-gssa=
pi.pc.in
--- a/head/crypto/heimdal/tools/heimdal-gssapi.pc.in	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/crypto/heimdal/tools/heimdal-gssapi.pc.in	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,5 +1,5 @@
 # $Id$
-prefix=3D at PREFIX@
+prefix=3D at prefix@
 exec_prefix=3D${prefix}
 libdir=3D${exec_prefix}/lib
 includedir=3D${prefix}/include
@@ -10,5 +10,5 @@
 URL: http://www.pdc.kth.se/heimdal/
 #Requires: foo =3D 1.3.1
 #Conflicts: bar <=3D 4.5
-Libs: -L${libdir} -lgssapi -lheimntlm -lkrb5 @LIB_pkinit@ -lcom_err @LIB_h=
crypto_appl@ -lasn1 -lroken @LIB_crypt@ @LIB_dlopen@ @LIB_door_create@ @LIB=
S@
+Libs: -L${libdir} -lgssapi -lheimntlm -lkrb5 @LIB_pkinit@ -lcom_err @LIB_h=
crypto_appl@ -lasn1 -lwind -lroken @LIB_crypt@ @LIB_dlopen@ @LIB_door_creat=
e@ @LIBS@
 Cflags: -I${includedir}
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/tools/kdc-log-anal=
yze.pl
--- a/head/crypto/heimdal/tools/kdc-log-analyze.pl	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/crypto/heimdal/tools/kdc-log-analyze.pl	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,7 +1,7 @@
 #! /usr/pkg/bin/perl
 # -*- mode: perl; perl-indent-level: 8 -*-
 #=20
-# Copyright (c) 2003 Kungliga Tekniska H=F6gskolan
+# Copyright (c) 2003 Kungliga Tekniska H=C3=B6gskolan
 # (Royal Institute of Technology, Stockholm, Sweden).=20
 # All rights reserved.=20
 #=20
@@ -32,7 +32,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
 # SUCH DAMAGE.=20
 #
-# $Id: kdc-log-analyze.pl 17173 2006-04-23 13:19:21Z lha $
+# $Id$
 #
 # kdc-log-analyze - Analyze a KDC log file and give a report on the conten=
ts
 #
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/tools/krb5-config.1
--- a/head/crypto/heimdal/tools/krb5-config.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/crypto/heimdal/tools/krb5-config.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,33 @@
-.\" Copyright (c) 2000 - 2001 Kungliga Tekniska H=F6gskolan
-.\" (Royal Institute of Technology, Stockholm, Sweden).=20
-.\" All rights reserved.=20
+.\" Copyright (c) 2000 - 2001 Kungliga Tekniska H=C3=B6gskolan
+.\" (Royal Institute of Technology, Stockholm, Sweden).
+.\" All rights reserved.
 .\"
-.\" Redistribution and use in source and binary forms, with or without=20
-.\" modification, are permitted provided that the following conditions=20
-.\" are met:=20
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
 .\"
-.\" 1. Redistributions of source code must retain the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer.=20
+.\" 1. Redistributions of source code must retain the above copyright
+.\"    notice, this list of conditions and the following disclaimer.
 .\"
-.\" 2. Redistributions in binary form must reproduce the above copyright=20
-.\"    notice, this list of conditions and the following disclaimer in the=20
-.\"    documentation and/or other materials provided with the distribution=
.=20
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    notice, this list of conditions and the following disclaimer in the
+.\"    documentation and/or other materials provided with the distribution.
 .\"
-.\" 3. Neither the name of the Institute nor the names of its contributors=20
-.\"    may be used to endorse or promote products derived from this softwa=
re=20
-.\"    without specific prior written permission.=20
+.\" 3. Neither the name of the Institute nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this softwa=
re
+.\"    without specific prior written permission.
 .\"
-.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND=20
-.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
-.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE=20
-.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE=20
-.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL=20
-.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD=
S=20
-.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
-.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT=20
-.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY=20
-.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
-.\" SUCH DAMAGE.=20
-.\"=20
-.\" $Id: krb5-config.1 11648 2003-02-16 21:10:32Z lha $
+.\" THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' =
AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LI=
ABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUEN=
TIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, ST=
RICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
 .\"
 .Dd November 30, 2000
 .Dt KRB5-CONFIG 1
@@ -39,10 +37,10 @@
 .Nd "give information on how to link code against Heimdal libraries"
 .Sh SYNOPSIS
 .Nm
-.Op Fl -prefix Ns Op =3D Ns Ar dir
-.Op Fl -exec-prefix Ns Op =3D Ns Ar dir
-.Op Fl -libs
-.Op Fl -cflags
+.Op Fl Fl prefix Ns Op =3D Ns Ar dir
+.Op Fl Fl exec-prefix Ns Op =3D Ns Ar dir
+.Op Fl Fl libs
+.Op Fl Fl cflags
 .Op Ar libraries
 .Sh DESCRIPTION
 .Nm
@@ -51,19 +49,19 @@
 .Pp
 Options supported:
 .Bl -tag -width Ds
-.It Fl -prefix Ns Op =3D Ns Ar dir
+.It Fl Fl prefix Ns Op =3D Ns Ar dir
 Print the prefix if no
 .Ar dir
 is specified, otherwise set prefix to
 .Ar dir .
-.It Fl -exec-prefix Ns Op =3D Ns Ar dir
+.It Fl Fl exec-prefix Ns Op =3D Ns Ar dir
 Print the exec-prefix if no
 .Ar dir
 is specified, otherwise set exec-prefix to
 .Ar dir .
-.It Fl -libs
+.It Fl Fl libs
 Output the set of libraries that should be linked against.
-.It Fl -cflags
+.It Fl Fl cflags
 Output the set of flags to give to the C compiler when using the
 Heimdal libraries.
 .El
diff -r 428842767fa6 -r f2935497fa04 head/crypto/heimdal/tools/krb5-config.=
in
--- a/head/crypto/heimdal/tools/krb5-config.in	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/crypto/heimdal/tools/krb5-config.in	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,5 +1,36 @@
 #!/bin/sh
-# $Id: krb5-config.in 20528 2007-04-22 13:22:16Z lha $
+#
+# Copyright (c) 2000 - 2008 Kungliga Tekniska H=F6gskolan
+# (Royal Institute of Technology, Stockholm, Sweden).=20
+# All rights reserved.=20
+#
+# Redistribution and use in source and binary forms, with or without=20
+# modification, are permitted provided that the following conditions=20
+# are met:=20
+#
+# 1. Redistributions of source code must retain the above copyright=20
+#    notice, this list of conditions and the following disclaimer.=20
+#
+# 2. Redistributions in binary form must reproduce the above copyright=20
+#    notice, this list of conditions and the following disclaimer in the=20
+#    documentation and/or other materials provided with the distribution.=20
+#
+# 3. Neither the name of the Institute nor the names of its contributors=20
+#    may be used to endorse or promote products derived from this software=20
+#    without specific prior written permission.=20
+#
+# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AN=
D=20
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE=20
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPO=
SE=20
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIAB=
LE=20
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTI=
AL=20
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS=20
+# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)=20
+# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRI=
CT=20
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WA=
Y=20
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=20
+# SUCH DAMAGE.=20
+#
=20
 do_libs=3Dno
 do_cflags=3Dno
@@ -21,7 +52,6 @@
     ;;
   --version)
     echo "@PACKAGE@ @VERSION@"
-    echo '$Id: krb5-config.in 20528 2007-04-22 13:22:16Z lha $'
     exit 0
     ;;
   --prefix=3D*)
@@ -106,8 +136,8 @@
 	;;
     esac
     lib_flags=3D"$lib_flags -lkrb5 @LIB_pkinit@ -lcom_err"
-    lib_flags=3D"$lib_flags @LIB_hcrypto_appl@ -lasn1 -lroken"
-    lib_flags=3D"$lib_flags @LIB_crypt@ @LIB_dlopen@"
+    lib_flags=3D"$lib_flags @LIB_hcrypto_appl@ -lasn1 -lwind -lheimbase -l=
roken"
+    lib_flags=3D"$lib_flags @LIB_crypt@ @PTHREAD_LIBADD@ @LIB_dlopen@"
     lib_flags=3D"$lib_flags @LIB_door_create@ @LIBS@"
     echo $lib_flags
 fi
diff -r 428842767fa6 -r f2935497fa04 head/etc/defaults/rc.conf
--- a/head/etc/defaults/rc.conf	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/etc/defaults/rc.conf	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # For a more detailed explanation of all the rc.conf variables, please
 # refer to the rc.conf(5) manual page.
 #
-# $FreeBSD: head/etc/defaults/rc.conf 231862 2012-02-17 07:59:37Z dougb $
+# $FreeBSD: head/etc/defaults/rc.conf 234093 2012-04-10 09:27:41Z stas $
=20
 ##############################################################
 ###  Important initial Boot-time options  ####################
@@ -297,6 +297,8 @@
 kadmind5_server=3D"/usr/libexec/kadmind"	# path to kerberos 5 admin daemon
 kpasswdd_server_enable=3D"NO"	# Run kpasswdd (or NO)
 kpasswdd_server=3D"/usr/libexec/kpasswdd"	# path to kerberos 5 passwd daem=
on
+kfd_server_enable=3D"NO"		# Run kfd (or NO)
+kfd_server=3D"/usr/libexec/kfd"	# path to kerberos 5 kfd daemon
=20
 gssd_enable=3D"NO"		# Run the gssd daemon (or NO).
 gssd_flags=3D""			# Flags for gssd.
diff -r 428842767fa6 -r f2935497fa04 head/etc/mtree/BSD.include.dist
--- a/head/etc/mtree/BSD.include.dist	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/etc/mtree/BSD.include.dist	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/etc/mtree/BSD.include.dist 232498 2012-03-04 15:31:13Z th=
eraven $
+# $FreeBSD: head/etc/mtree/BSD.include.dist 234353 2012-04-16 21:23:25Z di=
m $
 #
 # Please see the file src/etc/mtree/README before making changes to this f=
ile.
 #
@@ -88,7 +88,7 @@
         ..
     ..
     clang
-        3.0
+        3.1
         ..
     ..
     crypto
@@ -152,8 +152,6 @@
         ..
         fdescfs
         ..
-        fifofs
-        ..
         msdosfs
         ..
         nfs
@@ -235,6 +233,8 @@
     ..
     kadm5
     ..
+    krb5
+    ..
     libmilter
     ..
     lwres
diff -r 428842767fa6 -r f2935497fa04 head/etc/mtree/BSD.usr.dist
--- a/head/etc/mtree/BSD.usr.dist	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/etc/mtree/BSD.usr.dist	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/etc/mtree/BSD.usr.dist 225880 2011-09-29 18:12:40Z dim $
+# $FreeBSD: head/etc/mtree/BSD.usr.dist 233435 2012-03-24 21:10:19Z eadler=
 $
 #
 # Please see the file src/etc/mtree/README before making changes to this f=
ile.
 #
@@ -209,6 +209,8 @@
             ..
             bootforth
             ..
+	    csh
+	    	..
             cvs
                 contrib
                 ..
diff -r 428842767fa6 -r f2935497fa04 head/etc/rc.d/Makefile
--- a/head/etc/rc.d/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/etc/rc.d/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/etc/rc.d/Makefile 231534 2012-02-11 20:47:16Z ed $
+# $FreeBSD: head/etc/rc.d/Makefile 234093 2012-04-10 09:27:41Z stas $
=20
 .include <bsd.own.mk>
=20
@@ -66,6 +66,7 @@
 	kadmind \
 	kerberos \
 	keyserv \
+	kfd \
 	kld \
 	kldxref \
 	kpasswdd \
diff -r 428842767fa6 -r f2935497fa04 head/etc/root/dot.cshrc
--- a/head/etc/root/dot.cshrc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/etc/root/dot.cshrc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,15 +1,16 @@
-# $FreeBSD$
+# $FreeBSD: head/etc/root/dot.cshrc 234133 2012-04-11 14:13:22Z eadler $
 #
 # .cshrc - csh resource script, read at beginning of execution by each she=
ll
 #
 # see also csh(1), environ(7).
+# more examples available at /usr/share/examples/csh/
 #
=20
 alias h		history 25
 alias j		jobs -l
-alias la	ls -a
+alias la	ls -aF
 alias lf	ls -FA
-alias ll	ls -lA
+alias ll	ls -lAF
=20
 # A righteous umask
 umask 22
@@ -17,19 +18,29 @@
 set path =3D (/sbin /bin /usr/sbin /usr/bin /usr/games /usr/local/sbin /us=
r/local/bin $HOME/bin)
=20
 setenv	EDITOR	vi
-setenv	PAGER	more
+setenv	PAGER	less
 setenv	BLOCKSIZE	K
=20
 if ($?prompt) then
 	# An interactive shell -- set some stuff up
-	set prompt =3D "`/bin/hostname -s`# "
+	if ($uid =3D=3D 0) then
+		set user =3D root
+	endif
+	set prompt =3D "%n@%m:%/ %# "
+	set promptchars =3D "%#"
+
 	set filec
-	set history =3D 100
-	set savehist =3D 100
+	set history =3D 1000
+	set savehist =3D (1000 merge)
+	set autolist =3D ambiguous
+	# Use history to aid expansion
+	set autoexpand
+	set autorehash
 	set mail =3D (/var/mail/$USER)
 	if ( $?tcsh ) then
 		bindkey "^W" backward-delete-word
 		bindkey -k up history-search-backward
 		bindkey -k down history-search-forward
 	endif
+
 endif
diff -r 428842767fa6 -r f2935497fa04 head/etc/services
--- a/head/etc/services	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/etc/services	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # Kerberos services are for Kerberos v4, and are unofficial.  Sites running
 # v5 should uncomment v5 entries and comment v4 entries.
 #
-# $FreeBSD: head/etc/services 229783 2012-01-07 16:10:32Z uqs $
+# $FreeBSD: head/etc/services 233506 2012-03-26 11:48:47Z ivoras $
 #	From: @(#)services	5.8 (Berkeley) 5/9/91
 #
 # WELL KNOWN PORT NUMBERS
@@ -2219,6 +2219,8 @@
 iscsi-target	3260/udp   # iSCSI port
 ccmail		3264/tcp   #cc:mail/lotus
 ccmail		3264/udp   #cc:mail/lotus
+mysql		3306/tcp   #MySQL
+mysql		3306/udp   #MySQL
 dec-notes	3333/tcp   #DEC Notes
 dec-notes	3333/udp   #DEC Notes
 rdp		3389/tcp   #Microsoft Remote Desktop Protocol
diff -r 428842767fa6 -r f2935497fa04 head/games/pom/pom.6
--- a/head/games/pom/pom.6	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/games/pom/pom.6	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)pom.6	8.1 (Berkeley) 5/31/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/games/pom/pom.6 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd July 14, 2010
 .Dt POM 6
@@ -35,7 +35,7 @@
 .Nm pom
 .Nd display the phase of the moon
 .Sh SYNOPSIS
-.Nm=20
+.Nm
 .Op Fl p
 .Op Fl d Ar yyyy.mm.dd
 .Op Fl t Ar hh:mm:ss
diff -r 428842767fa6 -r f2935497fa04 head/gnu/lib/csu/Makefile
--- a/head/gnu/lib/csu/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/lib/csu/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/lib/csu/Makefile 234356 2012-04-16 21:36:55Z dim $
=20
 .include <bsd.own.mk>
 MK_SSP=3D		no
@@ -34,6 +34,7 @@
 .if ${MACHINE_CPUARCH} =3D=3D "powerpc"
 TGTOBJS=3D	crtsavres.o
 SRCS+=3D		crtsavres.asm
+CFLAGS+=3D	-mlongcall
 .endif
 .if ${MACHINE_CPUARCH} =3D=3D "sparc64"
 TGTOBJS=3D	crtfastmath.o
diff -r 428842767fa6 -r f2935497fa04 head/gnu/lib/libgcc/Makefile
--- a/head/gnu/lib/libgcc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/lib/libgcc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/lib/libgcc/Makefile 233644 2012-03-29 02:54:35Z jmall=
ett $
=20
 GCCDIR=3D	${.CURDIR}/../../../contrib/gcc
 GCCLIB=3D	${.CURDIR}/../../../contrib/gcclibs
@@ -122,7 +122,7 @@
 .if ${TARGET_CPUARCH} =3D=3D mips
 LIB2FUNCS_EXTRA =3D floatunsidf.c floatunsisf.c
 # ABIs other than o32 need this
-.if ${TARGET_ARCH:Mmipse[lb]} =3D=3D ""
+.if ${TARGET_ARCH} !=3D "mips" && ${TARGET_ARCH} !=3D "mipsel"
 LIB2FUNCS_EXTRA+=3D floatdidf.c fixunsdfsi.c
 LIB2FUNCS_EXTRA+=3D floatdisf.c floatundidf.c
 LIB2FUNCS_EXTRA+=3D fixsfdi.c floatundisf.c
diff -r 428842767fa6 -r f2935497fa04 head/gnu/lib/libstdc++/Makefile
--- a/head/gnu/lib/libstdc++/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/lib/libstdc++/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/lib/libstdc++/Makefile 233749 2012-03-31 14:25:12Z th=
eraven $
=20
 GCCVER=3D	4.2
 GCCDIR=3D	${.CURDIR}/../../../contrib/gcc
@@ -25,7 +25,7 @@
 PO_CXXFLAGS=3D	${CXXFLAGS:N-ffunction-sections}
=20
 DPADD=3D		${LIBM}
-LDADD=3D		-lm
+LDADD=3D		-lm  -Wl,-f,libsupc++.so.1
=20
 # libstdc++ sources
 SRCS+=3D	bitmap_allocator.cc pool_allocator.cc \
diff -r 428842767fa6 -r f2935497fa04 head/gnu/lib/libsupc++/Makefile
--- a/head/gnu/lib/libsupc++/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/lib/libsupc++/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/lib/libsupc++/Makefile 233749 2012-03-31 14:25:12Z th=
eraven $
=20
 GCCVER=3D	4.2
 GCCDIR=3D	${.CURDIR}/../../../contrib/gcc
@@ -7,8 +7,8 @@
=20
 .PATH: ${SRCDIR} ${GCCLIB}/libiberty
=20
-# Static only.
 LIB=3D	supc++
+SHLIB_MAJOR=3D1
 SRCS+=3D	del_op.cc del_opnt.cc del_opv.cc del_opvnt.cc eh_alloc.cc eh_arm.=
cc \
 	eh_aux_runtime.cc eh_call.cc eh_catch.cc eh_exception.cc eh_globals.cc \
 	eh_personality.cc eh_term_handler.cc eh_terminate.cc eh_throw.cc \
@@ -36,4 +36,9 @@
 SRCS+=3D		unwind.h
 CLEANFILES+=3D	unwind.h
=20
+# Symbol versioning
+
+VERSION_MAP=3D	${.CURDIR}/Version.map
+
+
 .include <bsd.lib.mk>
diff -r 428842767fa6 -r f2935497fa04 head/gnu/usr.bin/binutils/Makefile.inc0
--- a/head/gnu/usr.bin/binutils/Makefile.inc0	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/usr.bin/binutils/Makefile.inc0	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/usr.bin/binutils/Makefile.inc0 233644 2012-03-29 02:5=
4:35Z jmallett $
 #
 # This is included explicitly at the top of each sub-Makefile.  We can't
 # use the normal "Makefile.inc" mechanism, because we need some of these
@@ -7,7 +7,7 @@
 VERSION=3D	"2.17.50 [FreeBSD] 2007-07-03"
=20
 .if defined(TARGET_ARCH)
-TARGET_CPUARCH=3D${TARGET_ARCH:C/mips.*e[bl]/mips/:C/armeb/arm/:C/powerpc6=
4/powerpc/}
+TARGET_CPUARCH=3D${TARGET_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/:C/p=
owerpc64/powerpc/}
 .else
 TARGET_CPUARCH=3D${MACHINE_CPUARCH}
 .endif
@@ -16,7 +16,8 @@
 TARGET_OS?=3D	freebsd
 BINUTILS_ARCH=3D${TARGET_ARCH:C/amd64/x86_64/}
 TARGET_TUPLE?=3D	${BINUTILS_ARCH}-${TARGET_VENDOR}-${TARGET_OS}
-.if ${TARGET_ARCH} =3D=3D "armeb" || ${TARGET_ARCH:Mmips*eb} !=3D ""
+.if ${TARGET_ARCH} =3D=3D "armeb" || \
+	(${TARGET_CPUARCH} =3D=3D "mips" && ${TARGET_ARCH:Mmips*el} =3D=3D "")
 TARGET_BIG_ENDIAN=3Dt
 .endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/gnu/usr.bin/binutils/as/Makefile
--- a/head/gnu/usr.bin/binutils/as/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/usr.bin/binutils/as/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/usr.bin/binutils/as/Makefile 233388 2012-03-23 19:37:=
45Z gonzo $
=20
=20
 # BINDIR
@@ -43,6 +43,13 @@
=20
 .if ${TARGET_CPUARCH} =3D=3D "mips"
 SRCS+=3D	itbl-ops.c itbl-parse.y itbl-lex.l
+.if ${TARGET_ARCH:Mmips64*} !=3D ""
+CFLAGS+=3D	-DMIPS_DEFAULT_ABI=3DN64_ABI -DMIPS_DEFAULT_64BIT=3D1
+.elif ${TARGET_ARCH:Mmipsn32*} !=3D ""
+CFLAGS+=3D	-DMIPS_DEFAULT_ABI=3DN32_ABI
+.else
+MIPS_ABI_DEFAULT=3DABI_32
+.endif
 .endif
=20
 .if ${TARGET_ARCH} =3D=3D "amd64"
diff -r 428842767fa6 -r f2935497fa04 head/gnu/usr.bin/binutils/as/mips-free=
bsd/itbl-cpu.h
--- a/head/gnu/usr.bin/binutils/as/mips-freebsd/itbl-cpu.h	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/gnu/usr.bin/binutils/as/mips-freebsd/itbl-cpu.h	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,16 +1,19 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/gnu/usr.bin/binutils/as/mips-freebsd/itbl-cpu.h 233388 2=
012-03-23 19:37:45Z gonzo $ */
=20
 #include "itbl-mips.h"
=20
 /* Choose a default ABI for MIPS targets.  */
-/* XXX: Where should this be ? */
+#ifndef	MIPS_DEFAULT_ABI
 #define MIPS_DEFAULT_ABI NO_ABI
+#endif
=20
 /* Default CPU for MIPS targets.  */
 #define MIPS_CPU_STRING_DEFAULT "from-abi"
=20
 /* Generate 64-bit code by default on MIPS targets.  */
+#ifndef	MIPS_DEFAULT_64BIT
 #define MIPS_DEFAULT_64BIT 0
+#endif
=20
 /* Allow use of E_MIPS_ABI_O32 on MIPS targets.  */
 #define USE_E_MIPS_ABI_O32 1
diff -r 428842767fa6 -r f2935497fa04 head/gnu/usr.bin/cc/Makefile.tgt
--- a/head/gnu/usr.bin/cc/Makefile.tgt	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/usr.bin/cc/Makefile.tgt	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/usr.bin/cc/Makefile.tgt 233644 2012-03-29 02:54:35Z j=
mallett $
=20
 # These assignments duplicate much of the functionality of
 # MACHINE_CPUARCH, but there's no easy way to export make functions...
=20
 .if defined(TARGET_ARCH)
-TARGET_CPUARCH=3D${TARGET_ARCH:C/mips.*e[bl]/mips/:C/armeb/arm/:C/powerpc6=
4/powerpc/}
+TARGET_CPUARCH=3D${TARGET_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/:C/p=
owerpc64/powerpc/}
 .else
 TARGET_CPUARCH=3D${MACHINE_CPUARCH}
 .endif
@@ -17,7 +17,8 @@
 .if ${TARGET_ARCH} =3D=3D "sparc64"
 TARGET_CPU_DEFAULT=3D TARGET_CPU_ultrasparc
 .endif
-.if ${TARGET_ARCH} =3D=3D "armeb" || ${TARGET_ARCH:Mmips*eb} !=3D ""
+.if ${TARGET_ARCH} =3D=3D "armeb" || \
+	(${TARGET_CPUARCH} =3D=3D "mips" && ${TARGET_ARCH:Mmips*el} =3D=3D "")
 TARGET_BIG_ENDIAN=3Dt
 .endif
 .if ${TARGET_ARCH} =3D=3D "powerpc64"
diff -r 428842767fa6 -r f2935497fa04 head/gnu/usr.bin/gdb/Makefile.inc
--- a/head/gnu/usr.bin/gdb/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/usr.bin/gdb/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/usr.bin/gdb/Makefile.inc 233644 2012-03-29 02:54:35Z =
jmallett $
=20
 VERSION=3D "6.1.1 [FreeBSD]"
 VENDOR=3D marcel
@@ -20,7 +20,7 @@
 # MACHINE_CPUARCH, but there's no easy way to export make functions...
=20
 .if defined(TARGET_ARCH)
-TARGET_CPUARCH=3D${TARGET_ARCH:C/mips.*e[bl]/mips/:C/armeb/arm/:C/powerpc6=
4/powerpc/}
+TARGET_CPUARCH=3D${TARGET_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/:C/p=
owerpc64/powerpc/}
 .else
 TARGET_CPUARCH=3D${MACHINE_CPUARCH}
 .endif
diff -r 428842767fa6 -r f2935497fa04 head/gnu/usr.bin/gdb/libgdb/Makefile
--- a/head/gnu/usr.bin/gdb/libgdb/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/gnu/usr.bin/gdb/libgdb/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/usr.bin/gdb/libgdb/Makefile 233644 2012-03-29 02:54:3=
5Z jmallett $
=20
 # These assignments duplicate much of the functionality of
 # MACHINE_CPUARCH, but there's no easy way to export make functions...
=20
 .if defined(TARGET_ARCH)
-TARGET_CPUARCH=3D${TARGET_ARCH:C/mips.*e[bl]/mips/:C/armeb/arm/:C/powerpc6=
4/powerpc/}
+TARGET_CPUARCH=3D${TARGET_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/:C/p=
owerpc64/powerpc/}
 .else
 TARGET_CPUARCH=3D${MACHINE_CPUARCH}
 .endif
diff -r 428842767fa6 -r f2935497fa04 head/include/ctype.h
--- a/head/include/ctype.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/ctype.h	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)ctype.h	8.4 (Berkeley) 1/21/94
- *      $FreeBSD: head/include/ctype.h 232498 2012-03-04 15:31:13Z therave=
n $
+ *      $FreeBSD: head/include/ctype.h 233600 2012-03-28 12:11:54Z therave=
n $
  */
=20
 #ifndef _CTYPE_H_
@@ -79,7 +79,7 @@
 int	isspecial(int);
 #endif
=20
-#if __POSIX_VISIBLE >=3D 200809
+#if __POSIX_VISIBLE >=3D 200809 || defined(_XLOCALE_H_)
 #include <xlocale/_ctype.h>
 #endif
 __END_DECLS
diff -r 428842767fa6 -r f2935497fa04 head/include/inttypes.h
--- a/head/include/inttypes.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/inttypes.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/include/inttypes.h 233600 2012-03-28 12:11:54Z theraven $
  */
=20
 #ifndef _INTTYPES_H_
@@ -45,6 +45,9 @@
 } imaxdiv_t;
=20
 __BEGIN_DECLS
+#ifdef _XLOCALE_H_
+#include <xlocale/_inttypes.h>
+#endif
 intmax_t	imaxabs(intmax_t) __pure2;
 imaxdiv_t	imaxdiv(intmax_t, intmax_t) __pure2;
=20
diff -r 428842767fa6 -r f2935497fa04 head/include/langinfo.h
--- a/head/include/langinfo.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/langinfo.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/include/langinfo.h 232498 2012-03-04 15:31:13Z theraven $
+ * $FreeBSD: head/include/langinfo.h 233600 2012-03-28 12:11:54Z theraven $
  */
=20
 #ifndef _LANGINFO_H_
@@ -131,7 +131,7 @@
 __BEGIN_DECLS
 char	*nl_langinfo(nl_item);
=20
-#if __POSIX_VISIBLE >=3D 200809
+#if __POSIX_VISIBLE >=3D 200809 || defined(_XLOCALE_H_)
 #include <xlocale/_langinfo.h>
 #endif
 __END_DECLS
diff -r 428842767fa6 -r f2935497fa04 head/include/malloc_np.h
--- a/head/include/malloc_np.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/malloc_np.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,16 +26,43 @@
  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/include/malloc_np.h 234370 2012-04-17 07:22:14Z jasone $
  */
=20
 #ifndef _MALLOC_NP_H_
 #define	_MALLOC_NP_H_
 #include <sys/cdefs.h>
 #include <sys/types.h>
+#include <strings.h>
=20
 __BEGIN_DECLS
 size_t	malloc_usable_size(const void *ptr);
+
+void	malloc_stats_print(void (*write_cb)(void *, const char *),
+    void *cbopaque, const char *opts);
+int	mallctl(const char *name, void *oldp, size_t *oldlenp, void *newp,
+    size_t newlen);
+int	mallctlnametomib(const char *name, size_t *mibp, size_t *miblenp);
+int	mallctlbymib(const size_t *mib, size_t miblen, void *oldp,
+    size_t *oldlenp, void *newp, size_t newlen);
+
+#define	ALLOCM_LG_ALIGN(la)	(la)
+#define	ALLOCM_ALIGN(a)	(ffsl(a)-1)
+#define	ALLOCM_ZERO	((int)0x40)
+#define	ALLOCM_NO_MOVE	((int)0x80)
+
+#define	ALLOCM_SUCCESS		0
+#define	ALLOCM_ERR_OOM		1
+#define	ALLOCM_ERR_NOT_MOVED	2
+
+int	allocm(void **ptr, size_t *rsize, size_t size, int flags)
+    __attribute__(nonnull(1));
+int	rallocm(void **ptr, size_t *rsize, size_t size, size_t extra,
+    int flags) __attribute__(nonnull(1));
+int	sallocm(const void *ptr, size_t *rsize, int flags)
+    __attribute__(nonnull(1));
+int	dallocm(void *ptr, int flags) __attribute__(nonnull(1));
+int	nallocm(size_t *rsize, size_t size, int flags);
 __END_DECLS
=20
 #endif /* _MALLOC_NP_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/include/monetary.h
--- a/head/include/monetary.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/monetary.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/include/monetary.h 233600 2012-03-28 12:11:54Z theraven $
  */
=20
 #ifndef _MONETARY_H_
@@ -43,6 +43,9 @@
 #endif
=20
 __BEGIN_DECLS
+#ifdef _XLOCALE_H_
+#include <xlocale/_monetary.h>
+#endif
 ssize_t	strfmon(char * __restrict, size_t, const char * __restrict, ...);
 __END_DECLS
=20
diff -r 428842767fa6 -r f2935497fa04 head/include/stdio.h
--- a/head/include/stdio.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/stdio.h	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)stdio.h	8.5 (Berkeley) 4/29/95
- * $FreeBSD: head/include/stdio.h 228924 2011-12-28 05:35:33Z delphij $
+ * $FreeBSD: head/include/stdio.h 233600 2012-03-28 12:11:54Z theraven $
  */
=20
 #ifndef	_STDIO_H_
@@ -225,6 +225,9 @@
 #define	stderr	__stderrp
=20
 __BEGIN_DECLS
+#ifdef _XLOCALE_H_
+#include <xlocale/_stdio.h>
+#endif
 /*
  * Functions defined in ANSI C standard.
  */
diff -r 428842767fa6 -r f2935497fa04 head/include/stdlib.h
--- a/head/include/stdlib.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/stdlib.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)stdlib.h	8.5 (Berkeley) 5/19/95
- * $FreeBSD: head/include/stdlib.h 232971 2012-03-14 14:39:07Z theraven $
+ * $FreeBSD: head/include/stdlib.h 234370 2012-04-17 07:22:14Z jasone $
  */
=20
 #ifndef _STDLIB_H_
@@ -72,6 +72,9 @@
 #define	RAND_MAX	0x7fffffff
=20
 __BEGIN_DECLS
+#ifdef _XLOCALE_H_
+#include <xlocale/_stdlib.h>
+#endif
 extern int __mb_cur_max;
 extern int ___mb_cur_max(void);
 #define	MB_CUR_MAX	(___mb_cur_max())
@@ -152,7 +155,7 @@
  * If we're in a mode greater than C99, expose C11 functions.
  */
 #if __ISO_C_VISIBLE >=3D 2011 || __cplusplus >=3D 201103L
-void *	aligned_alloc(size_t, size_t);
+void *	aligned_alloc(size_t, size_t) __malloc_like;
 int	at_quick_exit(void (*)(void));
 _Noreturn void
 	quick_exit(int);
@@ -225,9 +228,8 @@
 #endif /* __XSI_VISIBLE */
=20
 #if __BSD_VISIBLE
-extern const char *_malloc_options;
-extern void (*_malloc_message)(const char *, const char *, const char *,
-	    const char *);
+extern const char *malloc_conf;
+extern void (*malloc_message)(void *, const char *);
=20
 /*
  * The alloca() function can't be implemented in C, and on some
diff -r 428842767fa6 -r f2935497fa04 head/include/string.h
--- a/head/include/string.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/string.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)string.h	8.1 (Berkeley) 6/2/93
- * $FreeBSD: head/include/string.h 232498 2012-03-04 15:31:13Z theraven $
+ * $FreeBSD: head/include/string.h 233600 2012-03-28 12:11:54Z theraven $
  */
=20
 #ifndef _STRING_H_
@@ -133,7 +133,7 @@
=20
 #endif /* __BSD_VISIBLE */
=20
-#if __POSIX_VISIBLE >=3D 200809
+#if __POSIX_VISIBLE >=3D 200809 || defined(_XLOCALE_H_)
 #include <xlocale/_string.h>
 #endif
 __END_DECLS
diff -r 428842767fa6 -r f2935497fa04 head/include/time.h
--- a/head/include/time.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/time.h	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 /*
- * $FreeBSD: head/include/time.h 232498 2012-03-04 15:31:13Z theraven $
+ * $FreeBSD: head/include/time.h 233600 2012-03-28 12:11:54Z theraven $
  */
=20
 #ifndef _TIME_H_
@@ -184,7 +184,7 @@
 time_t timegm(struct tm * const);
 #endif /* __BSD_VISIBLE */
=20
-#if __POSIX_VISIBLE >=3D 200809
+#if __POSIX_VISIBLE >=3D 200809 || defined(_XLOCALE_H_)
 #include <xlocale/_time.h>
 #endif
 __END_DECLS
diff -r 428842767fa6 -r f2935497fa04 head/include/wchar.h
--- a/head/include/wchar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/include/wchar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/include/wchar.h 232498 2012-03-04 15:31:13Z theraven $
+ * $FreeBSD: head/include/wchar.h 233600 2012-03-28 12:11:54Z theraven $
  */
=20
 /*-
@@ -225,7 +225,7 @@
 size_t	wcslcpy(wchar_t *, const wchar_t *, size_t);
 #endif
=20
-#if __POSIX_VISIBLE >=3D 200809
+#if __POSIX_VISIBLE >=3D 200809 || defined(_XLOCALE_H_)
 #include <xlocale/_wchar.h>
 #endif
 __END_DECLS
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/Makefile.inc
--- a/head/kerberos5/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/kerberos5/Makefile.inc 228308 2011-12-06 12:03:01Z ume $
+# $FreeBSD: head/kerberos5/Makefile.inc 233294 2012-03-22 08:48:42Z stas $
=20
 NO_LINT=3D
=20
@@ -14,6 +14,8 @@
 LDAPLDFLAGS=3D	-L${OPENLDAPBASE}/lib -Wl,-rpath,${OPENLDAPBASE}/lib
 .endif
=20
+LIBHEIMIPCC=3D	${.OBJDIR}/../../lib/libheimipcc/libheimipcc.a
+LIBHEIMIPCS=3D	${.OBJDIR}/../../lib/libheimipcs/libheimipcs.a
 LIBVERS=3D	${.OBJDIR}/../../lib/libvers/libvers.a
 LIBSL=3D		${.OBJDIR}/../../lib/libsl/libsl.a
=20
@@ -28,7 +30,9 @@
 	${KRB5DIR}/lib/krb5/krb5_err.et \
 	${KRB5DIR}/lib/krb5/krb_err.et \
 	${KRB5DIR}/lib/gssapi/krb5/gkrb5_err.et \
-	${KRB5DIR}/lib/hx509/hx509_err.et
+	${KRB5DIR}/lib/hx509/hx509_err.et \
+	${KRB5DIR}/lib/wind/wind_err.et \
+	${KRB5DIR}/lib/ntlm/ntlm_err.et
=20
 .for ET in ${ETSRCS}
 .for _ET in ${ET:T:R}
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/include/config.h
--- a/head/kerberos5/include/config.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/include/config.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,7 @@
 /* include/config.h.  Generated from config.h.in by configure.  */
-/* include/config.h.in.  Generated from configure.in by autoheader.  */
+/* include/config.h.in.  Generated from configure.ac by autoheader.  */
=20
-/* $FreeBSD$ */
-
-#include <osreldate.h>
+/* $FreeBSD: head/kerberos5/include/config.h 234027 2012-04-08 08:19:17Z s=
tas $ */
=20
 #ifndef RCSID
 #define RCSID(msg) \
@@ -17,22 +15,45 @@
=20
=20
 #ifdef BUILD_KRB5_LIB
-#ifndef KRB5_LIB_FUNCTION
+#ifndef KRB5_LIB
 #ifdef _WIN32_
-#define KRB5_LIB_FUNCTION _export _stdcall
+#define KRB5_LIB_FUNCTION __declspec(dllexport)
+#define KRB5_LIB_CALL __stdcall
+#define KRB5_LIB_VARIABLE __declspec(dllexport)
 #else
 #define KRB5_LIB_FUNCTION
+#define KRB5_LIB_CALL
+#define KRB5_LIB_VARIABLE
 #endif
 #endif
 #endif
=20
=20
 #ifdef BUILD_ROKEN_LIB
-#ifndef ROKEN_LIB_FUNCTION
+#ifndef ROKEN_LIB
 #ifdef _WIN32_
-#define ROKEN_LIB_FUNCTION _export _stdcall
+#define ROKEN_LIB_FUNCTION __declspec(dllexport)
+#define ROKEN_LIB_CALL __stdcall
+#define ROKEN_LIB_VARIABLE __declspec(dllexport)
 #else
 #define ROKEN_LIB_FUNCTION
+#define ROKEN_LIB_CALL
+#define ROKEN_LIB_VARIABLE
+#endif
+#endif
+#endif
+
+
+#ifdef BUILD_GSSAPI_LIB
+#ifndef GSSAPI_LIB
+#ifdef _WIN32_
+#define GSSAPI_LIB_FUNCTION __declspec(dllexport)
+#define GSSAPI_LIB_CALL __stdcall
+#define GSSAPI_LIB_VARIABLE __declspec(dllexport)
+#else
+#define GSSAPI_LIB_FUNCTION
+#define GSSAPI_LIB_CALL
+#define GSSAPI_LIB_VARIABLE
 #endif
 #endif
 #endif
@@ -56,11 +77,14 @@
 /* Define this to enable diagnostics in telnet. */
 #define DIAGNOSTICS 1
=20
+/* Define to enable DIGEST. */
+#define DIGEST 1
+
 /* Define if want to use the weak AFS string to key functions. */
 #define ENABLE_AFS_STRING_TO_KEY 1
=20
 /* Define if you want have a thread safe libraries */
-/* #undef ENABLE_PTHREAD_SUPPORT */
+#define ENABLE_PTHREAD_SUPPORT 1
=20
 /* Define if you want encryption support in telnet. */
 #define ENCRYPTION 1
@@ -73,7 +97,7 @@
=20
 /* define if prototype of gethostbyaddr is compatible with struct hostent
    *gethostbyaddr(const void *, size_t, int) */
-#define GETHOSTBYADDR_PROTO_COMPATIBLE 1
+/* #undef GETHOSTBYADDR_PROTO_COMPATIBLE */
=20
 /* define if prototype of gethostbyname is compatible with struct hostent
    *gethostbyname(const char *) */
@@ -105,6 +129,9 @@
 /* Define to 1 if you have the <arpa/telnet.h> header file. */
 #define HAVE_ARPA_TELNET_H 1
=20
+/* Define to 1 if you have the <asl.h> header file. */
+/* #undef HAVE_ASL_H */
+
 /* Define to 1 if you have the `asnprintf' function. */
 /* #undef HAVE_ASNPRINTF */
=20
@@ -114,6 +141,9 @@
 /* Define to 1 if you have the `atexit' function. */
 #define HAVE_ATEXIT 1
=20
+/* Define to 1 if you have the `backtrace' function. */
+/* #undef HAVE_BACKTRACE */
+
 /* Define to 1 if you have the <bind/bitypes.h> header file. */
 /* #undef HAVE_BIND_BITYPES_H */
=20
@@ -129,6 +159,9 @@
 /* Define to 1 if you have the <capability.h> header file. */
 /* #undef HAVE_CAPABILITY_H */
=20
+/* whether capng is available for privilege reduction */
+/* #undef HAVE_CAPNG */
+
 /* Define to 1 if you have the `cap_set_proc' function. */
 /* #undef HAVE_CAP_SET_PROC */
=20
@@ -139,7 +172,13 @@
 #define HAVE_CHOWN 1
=20
 /* Define if you have the function `closefrom'. */
-#define HAVE_CLOSEFROM
+#define HAVE_CLOSEFROM 1
+
+/* Define to 1 if you have the <CommonCrypto/CommonCryptor.h> header file.=
 */
+/* #undef HAVE_COMMONCRYPTO_COMMONCRYPTOR_H */
+
+/* Define to 1 if you have the <CommonCrypto/CommonDigest.h> header file. =
*/
+/* #undef HAVE_COMMONCRYPTO_COMMONDIGEST_H */
=20
 /* Define to 1 if you have the <config.h> header file. */
 /* #undef HAVE_CONFIG_H */
@@ -162,7 +201,7 @@
 /* define if you have a berkeley db1/2 library */
 #define HAVE_DB1 1
=20
-/* define if you have a berkeley db3/4 library */
+/* define if you have a berkeley db3/4/5 library */
 /* #undef HAVE_DB3 */
=20
 /* Define to 1 if you have the <db3/db.h> header file. */
@@ -171,6 +210,12 @@
 /* Define to 1 if you have the <db4/db.h> header file. */
 /* #undef HAVE_DB4_DB_H */
=20
+/* Define to 1 if you have the <db5/db.h> header file. */
+/* #undef HAVE_DB5_DB_H */
+
+/* Define if you have user supplied header location */
+/* #undef HAVE_DBHEADER */
+
 /* Define to 1 if you have the `dbm_firstkey' function. */
 #define HAVE_DBM_FIRSTKEY 1
=20
@@ -180,9 +225,6 @@
 /* Define to 1 if you have the `dbopen' function. */
 #define HAVE_DBOPEN 1
=20
-/* Define to 1 if you have the <db_185.h> header file. */
-/* #undef HAVE_DB_185_H */
-
 /* Define to 1 if you have the `db_create' function. */
 /* #undef HAVE_DB_CREATE */
=20
@@ -243,12 +285,30 @@
 /* Define to 1 if you have the <dirent.h> header file. */
 #define HAVE_DIRENT_H 1
=20
+/* have a dirfd function/macro */
+#define HAVE_DIRFD 1
+
+/* Define if DIR has field dd_fd. */
+#define HAVE_DIR_DD_FD 1
+
+/* Define to 1 if you have the `dispatch_async_f' function. */
+/* #undef HAVE_DISPATCH_ASYNC_F */
+
+/* Define to 1 if you have the <dispatch/dispatch.h> header file. */
+/* #undef HAVE_DISPATCH_DISPATCH_H */
+
 /* Define to 1 if you have the <dlfcn.h> header file. */
 #define HAVE_DLFCN_H 1
=20
 /* Define to 1 if you have the `dlopen' function. */
 #define HAVE_DLOPEN 1
=20
+/* Define to 1 if you have the <dns.h> header file. */
+/* #undef HAVE_DNS_H */
+
+/* Define to 1 if you have the `dns_search' function. */
+/* #undef HAVE_DNS_SEARCH */
+
 /* Define to 1 if you have the `dn_expand' function. */
 #define HAVE_DN_EXPAND 1
=20
@@ -258,9 +318,6 @@
 /* Define if you have the function `ecalloc'. */
 /* #undef HAVE_ECALLOC */
=20
-/* Define to 1 if you have the `el_init' function. */
-#define HAVE_EL_INIT 1
-
 /* Define if you have the function `emalloc'. */
 /* #undef HAVE_EMALLOC */
=20
@@ -282,6 +339,9 @@
 /* Define if you have the function `estrdup'. */
 /* #undef HAVE_ESTRDUP */
=20
+/* Define to 1 if you have the <execinfo.h> header file. */
+/* #undef HAVE_EXECINFO_H */
+
 /* Define if you have the function `fchown'. */
 #define HAVE_FCHOWN 1
=20
@@ -300,9 +360,6 @@
 /* Define to 1 if you have the <fnmatch.h> header file. */
 #define HAVE_FNMATCH_H 1
=20
-/* Define if el_init takes four arguments. */
-#define HAVE_FOUR_VALUED_EL_INIT 1
-
 /* Have -framework Security */
 /* #undef HAVE_FRAMEWORK_SECURITY */
=20
@@ -315,6 +372,9 @@
 /* Define to 1 if you have the `gai_strerror' function. */
 #define HAVE_GAI_STRERROR 1
=20
+/* Define if os support gcd. */
+/* #undef HAVE_GCD */
+
 /* Define to 1 if you have the <gdbm/ndbm.h> header file. */
 /* #undef HAVE_GDBM_NDBM_H */
=20
@@ -445,9 +505,6 @@
 /* Define if you have the function `initgroups'. */
 #define HAVE_INITGROUPS 1
=20
-/* Define to 1 if you have the `initstate' function. */
-#define HAVE_INITSTATE 1
-
 /* Define if you have the function `innetgr'. */
 #define HAVE_INNETGR 1
=20
@@ -490,14 +547,17 @@
 /* Define to 1 if you have the `loadquery' function. */
 /* #undef HAVE_LOADQUERY */
=20
+/* Define to 1 if you have the <locale.h> header file. */
+#define HAVE_LOCALE_H 1
+
 /* Define if you have the function `localtime_r'. */
 #define HAVE_LOCALTIME_R 1
=20
 /* Define to 1 if you have the `logout' function. */
-#define HAVE_LOGOUT 1
+/* #undef HAVE_LOGOUT */
=20
 /* Define to 1 if you have the `logwtmp' function. */
-#define HAVE_LOGWTMP 1
+/* #undef HAVE_LOGWTMP */
=20
 /* Define to 1 if the system has the type `long long'. */
 #define HAVE_LONG_LONG 1
@@ -559,12 +619,6 @@
 /* Define to 1 if you have the <netinet/tcp.h> header file. */
 #define HAVE_NETINET_TCP_H 1
=20
-/* Define if you want to use Netinfo instead of krb5.conf. */
-/* #undef HAVE_NETINFO */
-
-/* Define to 1 if you have the <netinfo/ni.h> header file. */
-/* #undef HAVE_NETINFO_NI_H */
-
 /* Define to 1 if you have the <net/if.h> header file. */
 #define HAVE_NET_IF_H 1
=20
@@ -622,6 +676,13 @@
 /* Define if you have a readline compatible library. */
 #define HAVE_READLINE 1
=20
+/* Define to 1 if you have the
+   <[readline.h])[][]_AH_CHECK_HEADER([readline/readline.h]> header file. =
*/
+/* #undef HAVE_READLINE_H */
+
+/* Define to 1 if you have the <readline/readline.h > header file. */
+/* #undef HAVE_READLINE_READLINE_H_ */
+
 /* Define if you have the function `readv'. */
 #define HAVE_READV 1
=20
@@ -652,6 +713,12 @@
 /* Define to 1 if the system has the type `sa_family_t'. */
 #define HAVE_SA_FAMILY_T 1
=20
+/* Define if you want support for cache in sqlite. */
+#undef HAVE_SCC
+
+/* Define to 1 if you have the <search.h> header file. */
+#define HAVE_SEARCH_H 1
+
 /* Define to 1 if you have the <security/pam_modules.h> header file. */
 #define HAVE_SECURITY_PAM_MODULES_H 1
=20
@@ -709,9 +776,6 @@
 /* Define to 1 if you have the `setsockopt' function. */
 #define HAVE_SETSOCKOPT 1
=20
-/* Define to 1 if you have the `setstate' function. */
-#define HAVE_SETSTATE 1
-
 /* Define to 1 if you have the `setutent' function. */
 /* #undef HAVE_SETUTENT */
=20
@@ -719,7 +783,7 @@
 /* #undef HAVE_SGI_GETCAPABILITYBYNAME */
=20
 /* Define to 1 if you have the <sgtty.h> header file. */
-#define HAVE_SGTTY_H 1
+/* #undef HAVE_SGTTY_H */
=20
 /* Define to 1 if you have the <shadow.h> header file. */
 /* #undef HAVE_SHADOW_H */
@@ -742,6 +806,9 @@
 /* Define to 1 if the system has the type `socklen_t'. */
 #define HAVE_SOCKLEN_T 1
=20
+/* Define if you want support for sqlite in Heimdal. */
+#define HAVE_SQLITE3 1
+
 /* Define to 1 if the system has the type `ssize_t'. */
 #define HAVE_SSIZE_T 1
=20
@@ -763,6 +830,9 @@
 /* Define if you have the function `strerror'. */
 #define HAVE_STRERROR 1
=20
+/* Define if you have the function strerror_r. */
+#define HAVE_STRERROR_R 1
+
 /* Define if you have the function `strftime'. */
 #define HAVE_STRFTIME 1
=20
@@ -788,7 +858,7 @@
 #define HAVE_STRNDUP 1
=20
 /* Define if you have the function `strnlen'. */
-/* #undef HAVE_STRNLEN */
+#define HAVE_STRNLEN 1
=20
 /* Define to 1 if you have the <stropts.h> header file. */
 /* #undef HAVE_STROPTS_H */
@@ -808,6 +878,9 @@
 /* Define to 1 if you have the `strsvis' function. */
 /* #undef HAVE_STRSVIS */
=20
+/* Define to 1 if you have the `strsvisx' function. */
+/* #undef HAVE_STRSVISX */
+
 /* Define if you have the function `strtok_r'. */
 #define HAVE_STRTOK_R 1
=20
@@ -844,9 +917,30 @@
 /* Define if struct utmpx has field ut_exit. */
 /* #undef HAVE_STRUCT_UTMPX_UT_EXIT */
=20
+/* Define if struct utmpx has field ut_host. */
+#define HAVE_STRUCT_UTMPX_UT_HOST 1
+
+/* Define if struct utmpx has field ut_id. */
+#define HAVE_STRUCT_UTMPX_UT_ID 1
+
+/* Define if struct utmpx has field ut_line. */
+#define HAVE_STRUCT_UTMPX_UT_LINE 1
+
+/* Define if struct utmpx has field ut_pid. */
+#define HAVE_STRUCT_UTMPX_UT_PID 1
+
 /* Define if struct utmpx has field ut_syslen. */
 /* #undef HAVE_STRUCT_UTMPX_UT_SYSLEN */
=20
+/* Define if struct utmpx has field ut_tv. */
+#define HAVE_STRUCT_UTMPX_UT_TV 1
+
+/* Define if struct utmpx has field ut_type. */
+#define HAVE_STRUCT_UTMPX_UT_TYPE 1
+
+/* Define if struct utmpx has field ut_user. */
+#define HAVE_STRUCT_UTMPX_UT_USER 1
+
 /* Define if struct utmp has field ut_addr. */
 /* #undef HAVE_STRUCT_UTMP_UT_ADDR */
=20
@@ -905,7 +999,7 @@
 /* #undef HAVE_SYS_BSWAP_H */
=20
 /* Define to 1 if you have the <sys/capability.h> header file. */
-/* #undef HAVE_SYS_CAPABILITY_H */
+#define HAVE_SYS_CAPABILITY_H 1
=20
 /* Define to 1 if you have the <sys/category.h> header file. */
 /* #undef HAVE_SYS_CATEGORY_H */
@@ -1006,6 +1100,9 @@
 /* Define to 1 if you have the <sys/wait.h> header file. */
 #define HAVE_SYS_WAIT_H 1
=20
+/* Define to 1 if you have the `tdelete' function. */
+#define HAVE_TDELETE 1
+
 /* Define to 1 if you have the <termcap.h> header file. */
 #define HAVE_TERMCAP_H 1
=20
@@ -1018,6 +1115,9 @@
 /* Define to 1 if you have the <term.h> header file. */
 #define HAVE_TERM_H 1
=20
+/* Define to 1 if you have the `tfind' function. */
+#define HAVE_TFIND 1
+
 /* Define to 1 if you have the `tgetent' function. */
 #define HAVE_TGETENT 1
=20
@@ -1033,11 +1133,17 @@
 /* Define to 1 if you have the <tmpdir.h> header file. */
 /* #undef HAVE_TMPDIR_H */
=20
+/* Define if you have the function `tsearch'. */
+#define HAVE_TSEARCH 1
+
 /* Define to 1 if you have the `ttyname' function. */
 #define HAVE_TTYNAME 1
=20
 /* Define to 1 if you have the `ttyslot' function. */
-#define HAVE_TTYSLOT 1
+/* #undef HAVE_TTYSLOT */
+
+/* Define to 1 if you have the `twalk' function. */
+#define HAVE_TWALK 1
=20
 /* Define to 1 if you have the <udb.h> header file. */
 /* #undef HAVE_UDB_H */
@@ -1085,10 +1191,10 @@
 /* #undef HAVE_UTIL_H */
=20
 /* Define to 1 if you have the <utmpx.h> header file. */
-/* #undef HAVE_UTMPX_H */
+#define HAVE_UTMPX_H 1
=20
 /* Define to 1 if you have the <utmp.h> header file. */
-#define HAVE_UTMP_H 1
+/* #undef HAVE_UTMP_H */
=20
 /* Define to 1 if the system has the type `u_int16_t'. */
 #define HAVE_U_INT16_T 1
@@ -1141,9 +1247,15 @@
 /* Define if you have the function `warnx'. */
 #define HAVE_WARNX 1
=20
+/* Define to 1 if you have the <winsock2.h> header file. */
+/* #undef HAVE_WINSOCK2_H */
+
 /* Define if you have the function `writev'. */
 #define HAVE_WRITEV 1
=20
+/* Define to 1 if you have the <ws2tcpip.h> header file. */
+/* #undef HAVE_WS2TCPIP_H */
+
 /* define if struct winsize has ws_xpixel */
 #define HAVE_WS_XPIXEL 1
=20
@@ -1177,24 +1289,44 @@
 /* Define if you have the `__progname' variable. */
 #define HAVE___PROGNAME 1
=20
+/* have __sync_add_and_fetch */
+#if defined(__FreeBSD__) && (defined(__arm__) || defined(__mips__))
+#undef HAVE___SYNC_ADD_AND_FETCH	/* Not supported on FreeBSD/arm */
+#else
+#define HAVE___SYNC_ADD_AND_FETCH 1
+#endif
+
+/* Define if you want support for weak crypto */
+#define HEIM_WEAK_CRYPTO 1
+
 /* Define if you have the hesiod package. */
 /* #undef HESIOD */
=20
-/* Define if you are running IRIX 4. */
-/* #undef IRIX4 */
-
 /* Enable Kerberos 5 support in applications. */
 #define KRB5 1
=20
+/* Define to enable kx509. */
+#define KX509 1
+
 /* path to lib */
 #define LIBDIR "/usr/lib"
=20
+/* Define if you have the libedit package. */
+/* #undef LIBEDIT */
+
 /* path to libexec */
 #define LIBEXECDIR "/usr/libexec"
=20
+/* Define if you have the libintl package. */
+/* #undef LIBINTL */
+
 /* path to localstate */
 #define LOCALSTATEDIR "/var/heimdal"
=20
+/* Define to the sub-directory in which libtool stores uninstalled librari=
es.
+   */
+#define LT_OBJDIR ".libs/"
+
 /* define if the system is missing a prototype for asnprintf() */
 #define NEED_ASNPRINTF_PROTO 1
=20
@@ -1228,6 +1360,9 @@
 /* define if the system is missing a prototype for mkstemp() */
 /* #undef NEED_MKSTEMP_PROTO */
=20
+/* if your qsort is not a stable sort */
+/* #undef NEED_QSORT */
+
 /* define if the system is missing a prototype for SecKeyGetCSPHandle() */
 /* #undef NEED_SECKEYGETCSPHANDLE_PROTO */
=20
@@ -1238,11 +1373,14 @@
 /* #undef NEED_SNPRINTF_PROTO */
=20
 /* define if the system is missing a prototype for strndup() */
-#define NEED_STRNDUP_PROTO 1
+/* #undef NEED_STRNDUP_PROTO */
=20
 /* define if the system is missing a prototype for strsep() */
 /* #undef NEED_STRSEP_PROTO */
=20
+/* define if the system is missing a prototype for strsvisx() */
+#define NEED_STRSVISX_PROTO 1
+
 /* define if the system is missing a prototype for strsvis() */
 #define NEED_STRSVIS_PROTO 1
=20
@@ -1314,13 +1452,16 @@
 #define PACKAGE_NAME "Heimdal"
=20
 /* Define to the full name and version of this package. */
-#define PACKAGE_STRING "Heimdal 1.1"
+#define PACKAGE_STRING "Heimdal 1.5.2"
=20
 /* Define to the one symbol short name of this package. */
 #define PACKAGE_TARNAME "heimdal"
=20
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
 /* Define to the version of this package. */
-#define PACKAGE_VERSION "1.1"
+#define PACKAGE_VERSION "1.5.2"
=20
 /* Define to enable PKINIT. */
 #define PKINIT 1
@@ -1329,7 +1470,7 @@
 /* #undef POSIX_GETLOGIN */
=20
 /* Define if getpwnam_r has POSIX flavour. */
-/* #undef POSIX_GETPWNAM_R */
+#define POSIX_GETPWNAM_R 1
=20
 /* Define if you have the readline package. */
 /* #undef READLINE */
@@ -1343,12 +1484,25 @@
 /* Define if you want to use samba socket wrappers. */
 /* #undef SOCKET_WRAPPER_REPLACE */
=20
+/* Define if you have the sqlite3 package. */
+/* #undef SQLITE3 */
+
 /* Define to 1 if you have the ANSI C header files. */
 #define STDC_HEADERS 1
=20
 /* Define if you have streams ptys. */
 /* #undef STREAMSPTY */
=20
+/* define if prototype of strerror_r is compatible with int strerror_r(int,
+   char *, size_t) */
+#define STRERROR_R_PROTO_COMPATIBLE 1
+
+/* Define if os support want to detach is daemonens. */
+#define SUPPORT_DETACH 1
+
+/* Enable use of inetd style startup. */
+#define SUPPORT_INETD 1
+
 /* path to sysconf */
 #define SYSCONFDIR "/etc"
=20
@@ -1362,7 +1516,7 @@
 /* #undef TM_IN_SYS_TIME */
=20
 /* Version number of package */
-#define VERSION "1.1"
+#define VERSION "1.5.2"
=20
 /* Define if signal handlers return void. */
 #define VOID_RETSIGTYPE 1
@@ -1377,6 +1531,9 @@
    `char[]'. */
 #define YYTEXT_POINTER 1
=20
+/* Required for functional/sane headers on AIX */
+/* #undef _ALL_SOURCE */
+
 /* Number of bits in a file offset, on hosts where this is settable. */
 /* #undef _FILE_OFFSET_BITS */
=20
@@ -1386,6 +1543,9 @@
 /* Define for large files, on AIX-style hosts. */
 /* #undef _LARGE_FILES */
=20
+/* Define to get POSIX getpwnam_r in some systems. */
+/* #undef _POSIX_PTHREAD_SEMANTICS */
+
 /* Define to empty if `const' does not conform to ANSI C. */
 /* #undef const */
=20
@@ -1407,6 +1567,9 @@
 /* Define to `int' if <sys/types.h> does not define. */
 /* #undef pid_t */
=20
+/* Path name delimiter */
+#define rk_PATH_DELIM '/'
+
 /* Define this to what the type sig_atomic_t should be. */
 /* #undef sig_atomic_t */
=20
@@ -1416,6 +1579,18 @@
 /* Define to `int' if <sys/types.h> doesn't define. */
 /* #undef uid_t */
=20
+#if _AIX
+/* XXX this is gross, but kills about a gazillion warnings */
+struct ether_addr;
+struct sockaddr;
+struct sockaddr_dl;
+struct sockaddr_in;
+#endif
+
+#ifdef __APPLE__
+#include <AvailabilityMacros.h>
+#endif
+
 #ifdef ROKEN_RENAME
 #include "roken_rename.h"
 #endif
@@ -1431,7 +1606,7 @@
 #endif
=20
=20
-#if ENDIANESS_IN_SYS_PARAM_H
+#ifdef ENDIANESS_IN_SYS_PARAM_H
 #  include <sys/types.h>
 #  include <sys/param.h>
 #  if BYTE_ORDER =3D=3D BIG_ENDIAN
@@ -1440,27 +1615,8 @@
 #endif
=20
=20
-#if _AIX
-#define _ALL_SOURCE
-/* XXX this is gross, but kills about a gazillion warnings */
-struct ether_addr;
-struct sockaddr;
-struct sockaddr_dl;
-struct sockaddr_in;
-#endif
=20
=20
-/* IRIX 4 braindamage */
-#if IRIX =3D=3D 4 && !defined(__STDC__)
-#define __STDC__ 0
-#endif
-
-
-
-#if defined(ENCRYPTION) && !defined(AUTHENTICATION)
-#define AUTHENTICATION 1
-#endif
-
 /* Set this to the default system lead string for telnetd=20
  * can contain %-escapes: %s=3Dsysname, %m=3Dmachine, %r=3Dos-release
  * %v=3Dos-version, %t=3Dtty, %h=3Dhostname, %d=3Ddate and time
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/include/crypto-headers.h
--- a/head/kerberos5/include/crypto-headers.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/include/crypto-headers.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,18 +1,26 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/kerberos5/include/crypto-headers.h 233294 2012-03-22 08:=
48:42Z stas $ */
 #ifndef __crypto_headers_h__
 #define __crypto_headers_h__
-#define OPENSSL_DES_LIBDES_COMPATIBILITY
+
 #include <openssl/evp.h>
 #include <openssl/des.h>
 #include <openssl/rc4.h>
-#include <openssl/md2.h>
+#include <openssl/rc2.h>
 #include <openssl/md4.h>
 #include <openssl/md5.h>
 #include <openssl/sha.h>
-#include <openssl/aes.h>
 #include <openssl/ui.h>
 #include <openssl/rand.h>
 #include <openssl/engine.h>
 #include <openssl/pkcs12.h>
+#include <openssl/pem.h>
 #include <openssl/hmac.h>
+#include <openssl/ec.h>
+#include <openssl/ecdsa.h>
+#include <openssl/ecdh.h>
+#ifndef BN_is_negative
+#define BN_set_negative(bn, flag) ((bn)->neg=3D(flag)?1:0)
+#define BN_is_negative(bn) ((bn)->neg !=3D 0)
+#endif
+
 #endif /* __crypto_headers_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/include/krb5-types.h
--- a/head/kerberos5/include/krb5-types.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/include/krb5-types.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,8 @@
-/* krb5-types.h -- this file was generated for i386-unknown-freebsd5.0 by
-                   $Id: bits.c,v 1.22 2002/08/28 16:08:44 joda Exp $ */
+/*
+ * generic krb5-types.h for cross compiling, assume system is posix/sus
+ */
=20
-/* $FreeBSD$ */
+/* $FreeBSD: head/kerberos5/include/krb5-types.h 233294 2012-03-22 08:48:4=
2Z stas $ */
=20
 #ifndef __krb5_types_h__
 #define __krb5_types_h__
@@ -14,4 +15,49 @@
 #include <unistd.h>
 typedef ssize_t krb5_ssize_t;
=20
+#if !defined(__has_extension)
+#define __has_extension(x) 0
+#endif
+
+#define KRB5TYPES_REQUIRE_GNUC(m,n,p) \
+    (((__GNUC__ * 10000) + (__GNUC_MINOR__ * 100) + __GNUC_PATCHLEVEL__) >=
=3D \
+     (((m) * 10000) + ((n) * 100) + (p)))
+
+
+#ifndef HEIMDAL_DEPRECATED
+#if __has_extension(deprecated) || KRB5TYPES_REQUIRE_GNUC(3,1,0)
+#define HEIMDAL_DEPRECATED __attribute__((deprecated))
+#elif defined(_MSC_VER) && (_MSC_VER>1200)
+#define HEIMDAL_DEPRECATED __declspec(deprecated)
+#else
+#define HEIMDAL_DEPRECATED
+#endif
+#endif
+
+#ifndef HEIMDAL_PRINTF_ATTRIBUTE
+#if __has_extension(format) || KRB5TYPES_REQUIRE_GNUC(3,1,0)
+#define HEIMDAL_PRINTF_ATTRIBUTE(x) __attribute__((format x))
+#else
+#define HEIMDAL_PRINTF_ATTRIBUTE(x)
+#endif
+#endif
+
+#ifndef HEIMDAL_NORETURN_ATTRIBUTE
+#if __has_extension(noreturn) || KRB5TYPES_REQUIRE_GNUC(3,1,0)
+#define HEIMDAL_NORETURN_ATTRIBUTE __attribute__((noreturn))
+#else
+#define HEIMDAL_NORETURN_ATTRIBUTE
+#endif
+#endif
+
+#ifndef HEIMDAL_UNUSED_ATTRIBUTE
+#if __has_extension(unused) || KRB5TYPES_REQUIRE_GNUC(3,1,0)
+#define HEIMDAL_UNUSED_ATTRIBUTE __attribute__((unused))
+#else
+#define HEIMDAL_UNUSED_ATTRIBUTE
+#endif
+#endif
+
+typedef int krb5_socket_t;
+
 #endif /* __krb5_types_h__ */
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/include/version.h
--- a/head/kerberos5/include/version.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/include/version.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,6 @@
-/* $FreeBSD$ */
-const char *heimdal_long_version =3D "@(#)$Version: Heimdal 1.1.0 (FreeBSD=
) $";
-const char *heimdal_version =3D "Heimdal 1.1.0";
+/* $FreeBSD: head/kerberos5/include/version.h 234027 2012-04-08 08:19:17Z =
stas $ */
+#ifndef VERSION_HIDDEN
+#define VERSION_HIDDEN
+#endif
+VERSION_HIDDEN const char *heimdal_long_version =3D "@(#)$Version: Heimdal=
 1.5.2 (FreeBSD) $";
+VERSION_HIDDEN const char *heimdal_version =3D "Heimdal 1.5.2";
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/Makefile
--- a/head/kerberos5/lib/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,8 @@
=20
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/lib/Makefile 233294 2012-03-22 08:48:42Z stas $
=20
 SUBDIR=3D	libasn1 libgssapi_krb5 libgssapi_ntlm libgssapi_spnego libhdb \
 	libheimntlm libhx509 libkadm5clnt libkadm5srv libkafs5 libkrb5 \
-	libroken libsl libvers
+	libroken libsl libvers libkdc libwind libheimsqlite libheimbase libheimip=
cc libheimipcs
=20
 .include <bsd.subdir.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/Makefile.inc
--- a/head/kerberos5/lib/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/lib/Makefile.inc 233294 2012-03-22 08:48:42Z st=
as $
=20
-SHLIB_MAJOR?=3D	10
+SHLIB_MAJOR?=3D	11
=20
 .include "../Makefile.inc"
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libasn1/Makefile
--- a/head/kerberos5/lib/libasn1/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libasn1/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,13 +1,15 @@
-# $FreeBSD: head/kerberos5/lib/libasn1/Makefile 225778 2011-09-27 07:14:12=
Z stas $
+# $FreeBSD: head/kerberos5/lib/libasn1/Makefile 234013 2012-04-08 04:22:09=
Z stas $
=20
 LIB=3D	asn1
 LDFLAGS=3D	-Wl,--no-undefined
-INCS=3D	asn1_err.h heim_asn1.h
+INCS=3D	asn1_err.h asn1-common.h heim_asn1.h der.h der-protos.h der-privat=
e.h
 LDADD=3D	-lcom_err -lroken
 DPADD=3D	${LIBCOM_ERR} ${LIBROKEN}
+VERSION_MAP=3D	${.CURDIR}/version.map
=20
 SRCS=3D	asn1_err.c \
 	asn1_err.h \
+	der.c \
 	der_copy.c \
 	der_cmp.c \
 	der_free.c \
@@ -16,401 +18,21 @@
 	der_length.c \
 	der_put.c \
 	extra.c \
+	template.c \
 	timegm.c \
-	${GEN:S/.x$/.c/}
+	${GEN:S/.x$/.c/:S/.hx$/.h/}
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/roken -I.
=20
-GEN_RFC2459 =3D \
-	asn1_Version.x \
-	asn1_id_pkcs_1.x \
-	asn1_id_pkcs1_rsaEncryption.x \
-	asn1_id_pkcs1_md2WithRSAEncryption.x \
-	asn1_id_pkcs1_md5WithRSAEncryption.x \
-	asn1_id_pkcs1_sha1WithRSAEncryption.x \
-	asn1_id_pkcs1_sha256WithRSAEncryption.x \
-	asn1_id_pkcs1_sha384WithRSAEncryption.x \
-	asn1_id_pkcs1_sha512WithRSAEncryption.x \
-	asn1_id_heim_rsa_pkcs1_x509.x \
-	asn1_id_pkcs_2.x \
-	asn1_id_pkcs2_md2.x \
-	asn1_id_pkcs2_md4.x \
-	asn1_id_pkcs2_md5.x \
-	asn1_id_rsa_digestAlgorithm.x \
-	asn1_id_rsa_digest_md2.x \
-	asn1_id_rsa_digest_md4.x \
-	asn1_id_rsa_digest_md5.x \
-	asn1_id_pkcs_3.x \
-	asn1_id_pkcs3_rc2_cbc.x \
-	asn1_id_pkcs3_rc4.x \
-	asn1_id_pkcs3_des_ede3_cbc.x \
-	asn1_id_rsadsi_encalg.x \
-	asn1_id_rsadsi_rc2_cbc.x \
-	asn1_id_rsadsi_des_ede3_cbc.x \
-	asn1_id_secsig_sha_1.x \
-	asn1_id_nistAlgorithm.x \
-	asn1_id_nist_aes_algs.x \
-	asn1_id_aes_128_cbc.x \
-	asn1_id_aes_192_cbc.x \
-	asn1_id_aes_256_cbc.x \
-	asn1_id_nist_sha_algs.x \
-	asn1_id_sha256.x \
-	asn1_id_sha224.x \
-	asn1_id_sha384.x \
-	asn1_id_sha512.x \
-	asn1_id_dhpublicnumber.x \
-	asn1_id_x9_57.x \
-	asn1_id_dsa.x \
-	asn1_id_dsa_with_sha1.x \
-	asn1_id_x520_at.x \
-	asn1_id_at_commonName.x \
-	asn1_id_at_surname.x \
-	asn1_id_at_serialNumber.x \
-	asn1_id_at_countryName.x \
-	asn1_id_at_localityName.x \
-	asn1_id_at_streetAddress.x \
-	asn1_id_at_stateOrProvinceName.x \
-	asn1_id_at_organizationName.x \
-	asn1_id_at_organizationalUnitName.x \
-	asn1_id_at_name.x \
-	asn1_id_at_givenName.x \
-	asn1_id_at_initials.x \
-	asn1_id_at_generationQualifier.x \
-	asn1_id_at_pseudonym.x \
-	asn1_id_Userid.x \
-	asn1_id_domainComponent.x \
-	asn1_id_x509_ce.x \
-	asn1_id_uspkicommon_card_id.x \
-	asn1_id_uspkicommon_piv_interim.x \
-	asn1_id_netscape.x \
-	asn1_id_netscape_cert_comment.x \
-	asn1_id_ms_cert_enroll_domaincontroller.x \
-	asn1_id_ms_client_authentication.x \
-	asn1_AlgorithmIdentifier.x \
-	asn1_AttributeType.x \
-	asn1_AttributeValue.x \
-	asn1_TeletexStringx.x \
-	asn1_DirectoryString.x \
-	asn1_Attribute.x \
-	asn1_AttributeTypeAndValue.x \
-	asn1_AuthorityInfoAccessSyntax.x \
-	asn1_AccessDescription.x \
-	asn1_RelativeDistinguishedName.x \
-	asn1_RDNSequence.x \
-	asn1_Name.x \
-	asn1_CertificateSerialNumber.x \
-	asn1_Time.x \
-	asn1_Validity.x \
-	asn1_UniqueIdentifier.x \
-	asn1_SubjectPublicKeyInfo.x \
-	asn1_Extension.x \
-	asn1_Extensions.x \
-	asn1_TBSCertificate.x \
-	asn1_Certificate.x \
-	asn1_Certificates.x \
-	asn1_ValidationParms.x \
-	asn1_DomainParameters.x \
-	asn1_DHPublicKey.x \
-	asn1_OtherName.x \
-	asn1_GeneralName.x \
-	asn1_GeneralNames.x \
-	asn1_id_x509_ce_keyUsage.x \
-	asn1_KeyUsage.x \
-	asn1_id_x509_ce_authorityKeyIdentifier.x \
-	asn1_KeyIdentifier.x \
-	asn1_AuthorityKeyIdentifier.x \
-	asn1_id_x509_ce_subjectKeyIdentifier.x \
-	asn1_SubjectKeyIdentifier.x \
-	asn1_id_x509_ce_basicConstraints.x \
-	asn1_BasicConstraints.x \
-	asn1_id_x509_ce_nameConstraints.x \
-	asn1_BaseDistance.x \
-	asn1_GeneralSubtree.x \
-	asn1_GeneralSubtrees.x \
-	asn1_NameConstraints.x \
-	asn1_id_x509_ce_privateKeyUsagePeriod.x \
-	asn1_id_x509_ce_certificatePolicies.x \
-	asn1_id_x509_ce_policyMappings.x \
-	asn1_id_x509_ce_subjectAltName.x \
-	asn1_id_x509_ce_issuerAltName.x \
-	asn1_id_x509_ce_subjectDirectoryAttributes.x \
-	asn1_id_x509_ce_policyConstraints.x \
-	asn1_id_x509_ce_extKeyUsage.x \
-	asn1_ExtKeyUsage.x \
-	asn1_id_x509_ce_cRLDistributionPoints.x \
-	asn1_id_x509_ce_deltaCRLIndicator.x \
-	asn1_id_x509_ce_issuingDistributionPoint.x \
-	asn1_id_x509_ce_holdInstructionCode.x \
-	asn1_id_x509_ce_invalidityDate.x \
-	asn1_id_x509_ce_certificateIssuer.x \
-	asn1_id_x509_ce_inhibitAnyPolicy.x \
-	asn1_DistributionPointReasonFlags.x \
-	asn1_DistributionPointName.x \
-	asn1_DistributionPoint.x \
-	asn1_CRLDistributionPoints.x \
-	asn1_DSASigValue.x \
-	asn1_DSAPublicKey.x \
-	asn1_DSAParams.x \
-	asn1_RSAPublicKey.x \
-	asn1_RSAPrivateKey.x \
-	asn1_DigestInfo.x \
-	asn1_TBSCRLCertList.x \
-	asn1_CRLCertificateList.x \
-	asn1_id_x509_ce_cRLNumber.x \
-	asn1_id_x509_ce_freshestCRL.x \
-	asn1_id_x509_ce_cRLReason.x \
-	asn1_CRLReason.x \
-	asn1_PKIXXmppAddr.x \
-	asn1_id_pkix.x \
-	asn1_id_pkix_on.x \
-	asn1_id_pkix_on_dnsSRV.x \
-	asn1_id_pkix_on_xmppAddr.x \
-	asn1_id_pkix_kp.x \
-	asn1_id_pkix_kp_serverAuth.x \
-	asn1_id_pkix_kp_clientAuth.x \
-	asn1_id_pkix_kp_emailProtection.x \
-	asn1_id_pkix_kp_timeStamping.x \
-	asn1_id_pkix_kp_OCSPSigning.x \
-	asn1_id_pkix_pe.x \
-	asn1_id_pkix_pe_authorityInfoAccess.x \
-	asn1_id_pkix_pe_proxyCertInfo.x \
-	asn1_id_pkix_ppl.x \
-	asn1_id_pkix_ppl_anyLanguage.x \
-	asn1_id_pkix_ppl_inheritAll.x \
-	asn1_id_pkix_ppl_independent.x \
-	asn1_ProxyPolicy.x \
-	asn1_ProxyCertInfo.x=20
-
-GEN_CMS =3D \
-	asn1_CMSAttributes.x \
-	asn1_CMSCBCParameter.x \
-	asn1_CMSEncryptedData.x \
-	asn1_CMSIdentifier.x \
-	asn1_CMSRC2CBCParameter.x \
-	asn1_CMSVersion.x \
-	asn1_CertificateList.x \
-	asn1_CertificateRevocationLists.x \
-	asn1_CertificateSet.x \
-	asn1_ContentEncryptionAlgorithmIdentifier.x \
-	asn1_ContentInfo.x \
-	asn1_ContentType.x \
-	asn1_DigestAlgorithmIdentifier.x \
-	asn1_DigestAlgorithmIdentifiers.x \
-	asn1_EncapsulatedContentInfo.x \
-	asn1_EncryptedContent.x \
-	asn1_EncryptedContentInfo.x \
-	asn1_EncryptedKey.x \
-	asn1_EnvelopedData.x \
-	asn1_IssuerAndSerialNumber.x \
-	asn1_KeyEncryptionAlgorithmIdentifier.x \
-	asn1_KeyTransRecipientInfo.x \
-	asn1_MessageDigest.x \
-	asn1_OriginatorInfo.x \
-	asn1_RecipientIdentifier.x \
-	asn1_RecipientInfo.x \
-	asn1_RecipientInfos.x \
-	asn1_SignatureAlgorithmIdentifier.x \
-	asn1_SignatureValue.x \
-	asn1_SignedData.x \
-	asn1_SignerIdentifier.x \
-	asn1_SignerInfo.x \
-	asn1_SignerInfos.x \
-	asn1_id_pkcs7.x \
-	asn1_id_pkcs7_data.x \
-	asn1_id_pkcs7_digestedData.x \
-	asn1_id_pkcs7_encryptedData.x \
-	asn1_id_pkcs7_envelopedData.x \
-	asn1_id_pkcs7_signedAndEnvelopedData.x \
-	asn1_id_pkcs7_signedData.x \
-	asn1_UnprotectedAttributes.x
-
-GEN_K5=3D	asn1_AD_AND_OR.x \
-	asn1_AD_IF_RELEVANT.x \
-	asn1_AD_KDCIssued.x \
-	asn1_AD_MANDATORY_FOR_KDC.x \
-	asn1_AD_LoginAlias.x \
-	asn1_APOptions.x \
-	asn1_AP_REP.x \
-	asn1_AP_REQ.x \
-	asn1_AS_REP.x \
-	asn1_AS_REQ.x \
-	asn1_AUTHDATA_TYPE.x \
-	asn1_Authenticator.x \
-	asn1_AuthorizationData.x \
-	asn1_AuthorizationDataElement.x \
-	asn1_CKSUMTYPE.x \
-	asn1_ChangePasswdDataMS.x \
-	asn1_Checksum.x \
-	asn1_ENCTYPE.x \
-	asn1_ETYPE_INFO.x \
-	asn1_ETYPE_INFO2.x \
-	asn1_ETYPE_INFO2_ENTRY.x \
-	asn1_ETYPE_INFO_ENTRY.x \
-	asn1_EncAPRepPart.x \
-	asn1_EncASRepPart.x \
-	asn1_EncKDCRepPart.x \
-	asn1_EncKrbCredPart.x \
-	asn1_EncKrbPrivPart.x \
-	asn1_EncTGSRepPart.x \
-	asn1_EncTicketPart.x \
-	asn1_EncryptedData.x \
-	asn1_EncryptionKey.x \
-	asn1_EtypeList.x \
-	asn1_HostAddress.x \
-	asn1_HostAddresses.x \
-	asn1_KDCOptions.x \
-	asn1_KDC_REP.x \
-	asn1_KDC_REQ.x \
-	asn1_KDC_REQ_BODY.x \
-	asn1_KRB_CRED.x \
-	asn1_KRB_ERROR.x \
-	asn1_KRB_PRIV.x \
-	asn1_KRB_SAFE.x \
-	asn1_KRB_SAFE_BODY.x \
-	asn1_KerberosString.x \
-	asn1_KerberosTime.x \
-	asn1_KrbCredInfo.x \
-	asn1_LR_TYPE.x \
-	asn1_LastReq.x \
-	asn1_MESSAGE_TYPE.x \
-	asn1_METHOD_DATA.x \
-	asn1_NAME_TYPE.x \
-	asn1_PADATA_TYPE.x \
-	asn1_PA_DATA.x \
-	asn1_PA_ENC_SAM_RESPONSE_ENC.x \
-	asn1_PA_ENC_TS_ENC.x \
-	asn1_PA_PAC_REQUEST.x \
-	asn1_PA_S4U2Self.x \
-	asn1_PA_SAM_CHALLENGE_2.x \
-	asn1_PA_SAM_CHALLENGE_2_BODY.x  \
-	asn1_PA_SAM_REDIRECT.x \
-	asn1_PA_SAM_RESPONSE_2.x \
-	asn1_PA_SAM_TYPE.x \
-	asn1_PA_ClientCanonicalized.x \
-	asn1_PA_ClientCanonicalizedNames.x \
-	asn1_PA_SvrReferralData.x \
-	asn1_PROV_SRV_LOCATION.x \
-	asn1_Principal.x \
-	asn1_PrincipalName.x \
-	asn1_Realm.x \
-	asn1_SAMFlags.x \
-	asn1_TGS_REP.x \
-	asn1_TGS_REQ.x \
-	asn1_TYPED_DATA.x \
-	asn1_Ticket.x \
-	asn1_TicketFlags.x \
-	asn1_TransitedEncoding.x \
-	asn1_TypedData.x \
-	asn1_krb5int32.x \
-	asn1_krb5uint32.x \
-	asn1_KRB5SignedPathData.x \
-	asn1_KRB5SignedPathPrincipals.x \
-	asn1_KRB5SignedPath.x
-
-GEN_PKINIT =3D \
-	asn1_id_pkinit.x \
-	asn1_id_pkauthdata.x \
-	asn1_id_pkdhkeydata.x \
-	asn1_id_pkrkeydata.x \
-	asn1_id_pkekuoid.x \
-	asn1_id_pkkdcekuoid.x \
-	asn1_id_pkinit_san.x \
-	asn1_id_pkinit_ms_eku.x \
-	asn1_id_pkinit_ms_san.x \
-	asn1_MS_UPN_SAN.x \
-	asn1_DHNonce.x \
-	asn1_KDFAlgorithmId.x \
-	asn1_TrustedCA.x \
-	asn1_ExternalPrincipalIdentifier.x \
-	asn1_ExternalPrincipalIdentifiers.x \
-	asn1_PA_PK_AS_REQ.x \
-	asn1_PKAuthenticator.x \
-	asn1_AuthPack.x \
-	asn1_TD_TRUSTED_CERTIFIERS.x \
-	asn1_TD_INVALID_CERTIFICATES.x \
-	asn1_KRB5PrincipalName.x \
-	asn1_AD_INITIAL_VERIFIED_CAS.x \
-	asn1_DHRepInfo.x \
-	asn1_PA_PK_AS_REP.x \
-	asn1_KDCDHKeyInfo.x \
-	asn1_ReplyKeyPack.x \
-	asn1_TD_DH_PARAMETERS.x \
-	asn1_PKAuthenticator_Win2k.x \
-	asn1_AuthPack_Win2k.x \
-	asn1_TrustedCA_Win2k.x \
-	asn1_PA_PK_AS_REQ_Win2k.x \
-	asn1_PA_PK_AS_REP_Win2k.x \
-	asn1_KDCDHKeyInfo_Win2k.x \
-	asn1_ReplyKeyPack_Win2k.x \
-	asn1_PkinitSuppPubInfo.x=20
-
-GEN_PKCS8 =3D \
-	asn1_PKCS8PrivateKeyAlgorithmIdentifier.x \
-	asn1_PKCS8PrivateKey.x \
-	asn1_PKCS8PrivateKeyInfo.x \
-	asn1_PKCS8Attributes.x \
-	asn1_PKCS8EncryptedPrivateKeyInfo.x \
-	asn1_PKCS8EncryptedData.x
-
-GEN_PKCS9 =3D \
-	asn1_id_pkcs_9.x \
-	asn1_id_pkcs9_contentType.x \
-	asn1_id_pkcs9_emailAddress.x \
-	asn1_id_pkcs9_messageDigest.x \
-	asn1_id_pkcs9_signingTime.x \
-	asn1_id_pkcs9_countersignature.x \
-	asn1_id_pkcs_9_at_friendlyName.x \
-	asn1_id_pkcs_9_at_localKeyId.x \
-	asn1_id_pkcs_9_at_certTypes.x \
-	asn1_id_pkcs_9_at_certTypes_x509.x \
-	asn1_PKCS9_BMPString.x \
-	asn1_PKCS9_friendlyName.x
-
-GEN_PKCS12 =3D \
-	asn1_id_pkcs_12.x \
-	asn1_id_pkcs_12PbeIds.x \
-	asn1_id_pbeWithSHAAnd128BitRC4.x \
-	asn1_id_pbeWithSHAAnd40BitRC4.x \
-	asn1_id_pbeWithSHAAnd3_KeyTripleDES_CBC.x \
-	asn1_id_pbeWithSHAAnd2_KeyTripleDES_CBC.x \
-	asn1_id_pbeWithSHAAnd128BitRC2_CBC.x \
-	asn1_id_pbewithSHAAnd40BitRC2_CBC.x \
-	asn1_id_pkcs12_bagtypes.x \
-	asn1_id_pkcs12_keyBag.x \
-	asn1_id_pkcs12_pkcs8ShroudedKeyBag.x \
-	asn1_id_pkcs12_certBag.x \
-	asn1_id_pkcs12_crlBag.x \
-	asn1_id_pkcs12_secretBag.x \
-	asn1_id_pkcs12_safeContentsBag.x \
-	asn1_PKCS12_MacData.x \
-	asn1_PKCS12_PFX.x \
-	asn1_PKCS12_AuthenticatedSafe.x \
-	asn1_PKCS12_CertBag.x \
-	asn1_PKCS12_Attribute.x \
-	asn1_PKCS12_Attributes.x \
-	asn1_PKCS12_SafeBag.x \
-	asn1_PKCS12_SafeContents.x \
-	asn1_PKCS12_OctetString.x \
-	asn1_PKCS12_PBEParams.x
-
-GEN_DIGEST=3D asn1_DigestError.x \
-	asn1_DigestInit.x \
-	asn1_DigestInitReply.x \
-	asn1_DigestREP.x \
-	asn1_DigestREQ.x \
-	asn1_DigestRepInner.x \
-	asn1_DigestReqInner.x \
-	asn1_DigestRequest.x \
-	asn1_DigestResponse.x \
-	asn1_DigestTypes.x \
-	asn1_NTLMInit.x \
-	asn1_NTLMInitReply.x \
-	asn1_NTLMRequest.x \
-	asn1_NTLMResponse.x
-
-GEN_KX509 =3D \
-	asn1_Kx509Response.x \
-	asn1_Kx509Request.x
+GEN_RFC2459=3D	asn1_rfc2459_asn1.x rfc2459_asn1.hx rfc2459_asn1-priv.hx
+GEN_CMS=3D 	asn1_cms_asn1.x cms_asn1.hx cms_asn1-priv.hx
+GEN_K5=3D		asn1_krb5_asn1.x krb5_asn1.hx krb5_asn1-priv.hx
+GEN_PKINIT=3D 	asn1_pkinit_asn1.x pkinit_asn1.hx pkinit_asn1-priv.hx
+GEN_PKCS8=3D	asn1_pkcs8_asn1.x pkcs8_asn1.hx pkcs8_asn1-priv.hx
+GEN_PKCS9=3D	asn1_pkcs9_asn1.x pkcs9_asn1.hx pkcs9_asn1-priv.hx
+GEN_PKCS12=3D	asn1_pkcs12_asn1.x pkcs12_asn1.hx pkcs12_asn1-priv.hx
+GEN_DIGEST=3D	asn1_digest_asn1.x digest_asn1.hx digest_asn1-priv.hx
+GEN_KX509=3D	asn1_kx509_asn1.x kx509_asn1.hx kx509_asn1-priv.hx
=20
 GEN+=3D	${GEN_RFC2459}
 GEN+=3D	${GEN_CMS}
@@ -422,21 +44,27 @@
 GEN+=3D	${GEN_DIGEST}
 GEN+=3D	${GEN_KX509}
=20
-CLEANFILES=3D ${GEN} ${GEN:S/.x$/.c/} *_asn1_files
+CLEANFILES=3D ${GEN} ${GEN:S/.x$/.c/:S/.hx$/.h/} *_asn1_files
=20
-GEN_ASN1=3Dcms_asn1.h rfc2459_asn1.h krb5_asn1.h pkinit_asn1.h
-GEN_ASN1+=3Dpkcs8_asn1.h pkcs9_asn1.h pkcs12_asn1.h digest_asn1.h kx509_as=
n1.h=20
-SRCS+=3D ${GEN_ASN1}
-INCS+=3D ${GEN_ASN1}
-CLEANFILES+=3D${GEN_ASN1}
+INCS+=3D	krb5_asn1.h \
+	pkinit_asn1.h \
+	cms_asn1.h \
+	rfc2459_asn1.h \
+	pkcs8_asn1.h \
+	pkcs9_asn1.h \
+	pkcs12_asn1.h \
+	digest_asn1.h \
+	kx509_asn1.h
=20
-.ORDER: ${GEN} ${GEN_ASN1}
+ASN1_COMPILE=3D	asn1_compile
=20
-${GEN_CMS} cms_asn1.h: CMS.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} cms_asn1
+${GEN_CMS}: cms.asn1 cms.opt
+	${ASN1_COMPILE} --one-code-file \
+		--option-file=3D${.ALLSRC:M*.opt} ${.ALLSRC:M*.asn1} cms_asn1
=20
-${GEN_RFC2459} rfc2459_asn1.h: rfc2459.asn1 ../../tools/asn1_compile/asn1_=
compile
-	../../tools/asn1_compile/asn1_compile \
+${GEN_RFC2459}: rfc2459.asn1
+	${ASN1_COMPILE} \
+		--one-code-file \
 		--preserve-binary=3DTBSCertificate \
 		--preserve-binary=3DTBSCRLCertList \
 		--preserve-binary=3DName \
@@ -444,41 +72,46 @@
 		--sequence=3DExtensions \
 		--sequence=3DCRLDistributionPoints ${.ALLSRC:M*.asn1} rfc2459_asn1
=20
-${GEN_K5} krb5_asn1.h: k5.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile \
-		--encode-rfc1510-bit-string \
-		--sequence=3DKRB5SignedPathPrincipals \
-		--sequence=3DAuthorizationData \
-		--sequence=3DMETHOD-DATA \
-		--sequence=3DETYPE-INFO \
-		--sequence=3DETYPE-INFO2 ${.ALLSRC:M*.asn1} krb5_asn1
+${GEN_K5}: krb5.asn1 krb5.opt
+	${ASN1_COMPILE} \
+		--one-code-file \
+		--option-file=3D${.ALLSRC:M*.opt} \
+		${.ALLSRC:M*.asn1} krb5_asn1
=20
-${GEN_PKINIT} pkinit_asn1.h: pkinit.asn1 ../../tools/asn1_compile/asn1_com=
pile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} pkinit_asn1
+${GEN_PKINIT}: pkinit.asn1
+	${ASN1_COMPILE} --one-code-file \
+		${.ALLSRC:M*.asn1} pkinit_asn1
=20
-${GEN_PKCS8} pkcs8_asn1.h: pkcs8.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} pkcs8_asn1
+${GEN_PKCS8}: pkcs8.asn1
+	${ASN1_COMPILE} --one-code-file \
+		${.ALLSRC:M*.asn1} pkcs8_asn1
=20
-${GEN_PKCS9} pkcs9_asn1.h: pkcs9.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} pkcs9_asn1
+${GEN_PKCS9}: pkcs9.asn1
+	${ASN1_COMPILE} --one-code-file \
+		${.ALLSRC:M*.asn1} pkcs9_asn1
=20
-${GEN_PKCS12} pkcs12_asn1.h: pkcs12.asn1 ../../tools/asn1_compile/asn1_com=
pile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} pkcs12_asn1
+${GEN_PKCS12}: pkcs12.asn1
+	${ASN1_COMPILE} --one-code-file \
+		${.ALLSRC:M*.asn1} pkcs12_asn1
=20
-${GEN_DIGEST} digest_asn1.h: digest.asn1 ../../tools/asn1_compile/asn1_com=
pile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} digest_asn1
+${GEN_DIGEST}: digest.asn1
+	${ASN1_COMPILE} --one-code-file \
+		${.ALLSRC:M*.asn1} digest_asn1
=20
-${GEN_KX509} kx509_asn1.h: kx509.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} kx509_asn1
+${GEN_KX509}: kx509.asn1
+	${ASN1_COMPILE} --one-code-file \
+		${.ALLSRC:M*.asn1} kx509_asn1
=20
-../../tools/asn1_compile/asn1_compile:
-	cd ${.CURDIR}/../../tools/asn1_compile && ${MAKE}
+.SUFFIXES: .h .c .x .hx
=20
-.for I in ${GEN}
-${I:R}.c: ${I}
-	cat ${.ALLSRC} > ${.TARGET}
-.endfor
+.x.c:
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
=20
+.hx.h:
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
+=09
 .include <bsd.lib.mk>
=20
+.SUFFIXES: .h .c .x .hx
+
 .PATH: ${KRB5DIR}/lib/asn1
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libgssapi_krb5/Make=
file
--- a/head/kerberos5/lib/libgssapi_krb5/Makefile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/kerberos5/lib/libgssapi_krb5/Makefile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,10 +1,11 @@
-# $FreeBSD: head/kerberos5/lib/libgssapi_krb5/Makefile 225778 2011-09-27 0=
7:14:12Z stas $
+# $FreeBSD: head/kerberos5/lib/libgssapi_krb5/Makefile 233294 2012-03-22 0=
8:48:42Z stas $
=20
 LIB=3D	gssapi_krb5
 LDFLAGS=3D -Wl,-Bsymbolic -Wl,--no-undefined
 LDADD=3D	-lgssapi -lkrb5 -lhx509 -lcrypto -lroken -lasn1 -lcom_err -lcrypt
 DPADD=3D	${LIBGSSAPI} ${LIBKRB5} ${LIBHX509} ${LIBCRYPTO} ${LIBROKEN} ${LI=
BASN1} \
 	${LIBCOM_ERR} ${LIBCRYPT}
+SHLIB_MAJOR=3D	10
=20
 INCS=3D	${KRB5DIR}/lib/gssapi/gssapi/gssapi_krb5.h
 INCSDIR=3D ${INCLUDEDIR}/gssapi
@@ -14,7 +15,9 @@
 	acquire_cred.c \
 	add_cred.c \
 	address_to_krb5addr.c \
+	aeap.c \
 	arcfour.c \
+	authorize_localname.c \
 	canonicalize_name.c \
 	ccache_name.c \
 	cfx.c \
@@ -22,6 +25,7 @@
 	compat.c \
 	context_time.c \
 	copy_ccache.c \
+	creds.c \
 	decapsulate.c \
 	delete_sec_context.c \
 	display_name.c \
@@ -34,6 +38,8 @@
 	get_mic.c \
 	gkrb5_err.c \
 	gkrb5_err.h \
+	gsskrb5-private.h \
+	gsskrb5_locl.h \
 	import_name.c \
 	import_sec_context.c \
 	indicate_mechs.c \
@@ -56,11 +62,13 @@
 	sequence.c \
 	set_cred_option.c \
 	set_sec_context_option.c \
+	store_cred.c \
+	ticket_flags.c \
 	unwrap.c \
-	v1.c \
 	verify_mic.c \
 	wrap.c \
-	gss_krb5.c
+	gss_krb5.c \
+	gss_oid.c
=20
 #SRCS+=3D	gss_add_oid_set_member.c \
 #	gss_create_empty_oid_set.c \
@@ -71,6 +79,7 @@
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/gssapi
 CFLAGS+=3D-I${KRB5DIR}/lib/gssapi/krb5
+CFLAGS+=3D-I${KRB5DIR}/lib/gssapi/gssapi
 CFLAGS+=3D-I${KRB5DIR}/lib/krb5
 CFLAGS+=3D-I${KRB5DIR}/lib/asn1
 CFLAGS+=3D-I${KRB5DIR}/lib/roken -I.
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libgssapi_krb5/gss_=
krb5.c
--- a/head/kerberos5/lib/libgssapi_krb5/gss_krb5.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/kerberos5/lib/libgssapi_krb5/gss_krb5.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	$FreeBSD$
+ *	$FreeBSD: head/kerberos5/lib/libgssapi_krb5/gss_krb5.c 233294 2012-03-2=
2 08:48:42Z stas $
  */
=20
 #include <gssapi/gssapi.h>
@@ -33,6 +33,7 @@
=20
 #include <krb5.h>
 #include <roken.h>
+#include <der.h>
=20
 OM_uint32
 gss_krb5_copy_ccache(OM_uint32 *minor_status,
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libgssapi_ntlm/Make=
file
--- a/head/kerberos5/lib/libgssapi_ntlm/Makefile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/kerberos5/lib/libgssapi_ntlm/Makefile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,9 +1,10 @@
-# $FreeBSD: head/kerberos5/lib/libgssapi_ntlm/Makefile 225778 2011-09-27 0=
7:14:12Z stas $
+# $FreeBSD: head/kerberos5/lib/libgssapi_ntlm/Makefile 233294 2012-03-22 0=
8:48:42Z stas $
=20
 LIB=3D	gssapi_ntlm
 LDFLAGS=3D -Wl,-Bsymbolic -Wl,--no-undefined
 LDADD=3D	-lcrypto -lgssapi -lkrb5 -lhx509 -lheimntlm -lroken
 DPADD=3D	${LIBCRYPTO} ${LIBGSSAPI} ${LIBKRB5} ${LIBHX509} ${LIBHEIMNTLM} $=
{LIBROKEN}
+SHLIB_MAJOR=3D	10
=20
 SRCS=3D	accept_sec_context.c \
 	acquire_cred.c \
@@ -11,6 +12,7 @@
 	canonicalize_name.c \
 	compare_name.c \
 	context_time.c \
+	creds.c \
 	crypto.c \
 	delete_sec_context.c \
 	display_name.c \
@@ -26,19 +28,24 @@
 	indicate_mechs.c \
 	init_sec_context.c \
 	inquire_context.c \
-	inquire_cred.c \
 	inquire_cred_by_mech.c \
 	inquire_mechs_for_name.c \
 	inquire_names_for_mech.c \
+	inquire_sec_context_by_oid.c \
+	iter_cred.c \
+	kdc.c \
 	prefix.c \
 	process_context_token.c \
 	release_cred.c \
 	release_name.c \
-	digest.c
+	gss_oid.c
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/gssapi
+CFLAGS+=3D-I${KRB5DIR}/lib/gssapi/gssapi
+CFLAGS+=3D-I${KRB5DIR}/lib/gssapi/ntlm
+CFLAGS+=3D-I${KRB5DIR}/lib/krb5
 CFLAGS+=3D-I${KRB5DIR}/lib/ntlm
=20
 .include <bsd.lib.mk>
=20
-.PATH: ${KRB5DIR}/lib/gssapi/ntlm ${.CURDIR}/../../../lib/libgssapi
+.PATH: ${KRB5DIR}/lib/gssapi/ntlm ${.CURDIR}/../../../lib/libgssapi ${.CUR=
DIR}/../libgssapi_krb5
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libgssapi_ntlm/pref=
ix.c
--- a/head/kerberos5/lib/libgssapi_ntlm/prefix.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/kerberos5/lib/libgssapi_ntlm/prefix.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -23,9 +23,16 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/kerberos5/lib/libgssapi_ntlm/prefix.c 233294 2012-03-22 =
08:48:42Z stas $
  */
=20
+#include <gssapi/gssapi.h>
+
+gss_OID_desc __gss_c_nt_user_name_oid_desc =3D
+    {10, (void *)("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x01")};
+gss_OID_desc __gss_c_nt_hostbased_service_oid_desc =3D
+    {10, (void *)("\x2a\x86\x48\x86\xf7\x12" "\x01\x02\x01\x04")};
+
 const char *
 _gss_name_prefix(void)
 {
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libgssapi_spnego/Ma=
kefile
--- a/head/kerberos5/lib/libgssapi_spnego/Makefile	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/kerberos5/lib/libgssapi_spnego/Makefile	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,9 +1,10 @@
-# $FreeBSD: head/kerberos5/lib/libgssapi_spnego/Makefile 225778 2011-09-27=
 07:14:12Z stas $
+# $FreeBSD: head/kerberos5/lib/libgssapi_spnego/Makefile 233294 2012-03-22=
 08:48:42Z stas $
=20
 LIB=3D	gssapi_spnego
 LDFLAGS=3D -Wl,-Bsymbolic -Wl,--no-undefined
-LDADD=3D	-lgssapi -lasn1 -lroken
-DPADD=3D	${LIBGSSAPI} ${LIBASN1} ${LIBROKEN}
+LDADD=3D	-lgssapi -lheimbase -lasn1 -lroken
+DPADD=3D	${LIBGSSAPI} ${LIBHEIMBASE} ${LIBASN1} ${LIBROKEN}
+SHLIB_MAJOR=3D	10
=20
 SRCS=3D	accept_sec_context.c \
 	compat.c \
@@ -11,9 +12,12 @@
 	cred_stubs.c \
 	external.c \
 	init_sec_context.c \
-	prefix.c \
+	freebsd_compat.c \
+	spnego-private.h \
+	spnego_locl.h \
 	spnego_asn1.h \
-	${GEN:S/.x$/.c/}
+	${GEN:S/.x$/.c/:S/.hx$/.h/} \
+	gss_oid.c
=20
 GEN=3D	asn1_ContextFlags.x \
 	asn1_MechType.x \
@@ -23,26 +27,36 @@
 	asn1_NegHints.x \
 	asn1_NegTokenInit.x \
 	asn1_NegTokenInitWin.x \
-	asn1_NegTokenResp.x
+	asn1_NegTokenResp.x \
+	spnego_asn1.hx \
+	spnego_asn1-priv.hx
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/gssapi
+CFLAGS+=3D-I${KRB5DIR}/lib/gssapi/gssapi
+CFLAGS+=3D-I${KRB5DIR}/lib/gssapi/spnego
 CFLAGS+=3D-I${KRB5DIR}/lib/asn1
+CFLAGS+=3D-I${.CURDIR}/../../../lib/libgssapi
 CFLAGS+=3D-I${KRB5DIR}/lib/roken -I.
=20
-CLEANFILES=3D ${GEN} ${GEN:S/.x$/.c/} spnego_asn1.h asn1_files
+CLEANFILES=3D	${GEN} ${GEN:S/.x$/.c/:S/.hx$/.h/} \
+		spnego_asn1_files spnego_asn1-template.c
=20
-.ORDER: ${GEN} spnego_asn1.h
-${GEN} spnego_asn1.h: spnego.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile --sequence=3DMechTypeList ${.ALLSRC=
:M*.asn1} spnego_asn1
+ASN1_COMPILE=3D	asn1_compile
=20
-../../tools/asn1_compile/asn1_compile:
-	cd ${.CURDIR}/../../tools/asn1_compile && ${MAKE}
+${GEN}: spnego.asn1 spnego.opt
+	${ASN1_COMPILE} --option-file=3D${.ALLSRC:M*.opt} \
+		${.ALLSRC:M*.asn1} spnego_asn1
=20
-.for I in ${GEN}
-${I:R}.c: ${I}
-	cat ${.ALLSRC} > ${.TARGET}
-.endfor
+.SUFFIXES: .h .c .x .hx
+
+.x.c:  =20
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
+
+.hx.h:
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
=20
 .include <bsd.lib.mk>
=20
-.PATH: ${KRB5DIR}/lib/gssapi/spnego ${.CURDIR}/../../../lib/libgssapi
+.SUFFIXES: .h .c .x .hx
+
+.PATH: ${KRB5DIR}/lib/gssapi/spnego ${.CURDIR}/../../../lib/libgssapi ${.C=
URDIR}/../libgssapi_krb5
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libhdb/Makefile
--- a/head/kerberos5/lib/libhdb/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libhdb/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,37 @@
-# $FreeBSD: head/kerberos5/lib/libhdb/Makefile 228284 2011-12-05 16:38:52Z=
 ume $
+# $FreeBSD: head/kerberos5/lib/libhdb/Makefile 233294 2012-03-22 08:48:42Z=
 stas $
=20
 LIB=3D	hdb
-LDFLAGS=3D	-Wl,--no-undefined ${LDAPLDFLAGS}
-LDADD=3D	-lasn1 -lcom_err -lkrb5 -lroken ${LDAPLDADD}
-DPADD=3D	${LIBASN1} ${LIBCOM_ERR} ${LIBKRB5} ${LIBROKEN} ${LDAPDPADD}
+LDFLAGS=3D	-Wl,--no-undefined
+VERSION_MAP=3D	${KRB5DIR}/lib/hdb/version-script.map
+LDADD=3D	-lasn1 -lcom_err -lkrb5 -lroken -lheimsqlite
+DPADD=3D	${LIBASN1} ${LIBCOM_ERR} ${LIBKRB5} ${LIBROKEN} ${LIBHEIMSQLITE} =
${LDAPDPADD}
=20
-INCS=3D	hdb-private.h \
-	hdb-protos.h \
+MAN=3D	HDB.3 hdb_entry_ex.3
+
+MLINKS=3D	HDB.3 hdb__del.3 \
+	HDB.3 hdb__get.3 \
+	HDB.3 hdb__put.3 \
+	HDB.3 hdb_auth_status.3 \
+	HDB.3 hdb_check_constrained_delegation.3 \
+	HDB.3 hdb_check_pkinit_ms_upn_match.3 \
+	HDB.3 hdb_check_s4u2self.3 \
+	HDB.3 hdb_close.3 \
+	HDB.3 hdb_destroy.3 \
+	HDB.3 hdb_fetch_kvno.3 \
+	HDB.3 hdb_firstkey.3 \
+	HDB.3 hdb_free.3 \
+	HDB.3 hdb_get_realms.3 \
+	HDB.3 hdb_lock.3 \
+	HDB.3 hdb_name.3 \
+	HDB.3 hdb_nextkey.3 \
+	HDB.3 hdb_open.3 \
+	HDB.3 hdb_password.3 \
+	HDB.3 hdb_remove.3 \
+	HDB.3 hdb_rename.3 \
+	HDB.3 hdb_store.3 \
+	HDB.3 hdb_unlock.3
+
+INCS=3D	hdb-protos.h \
 	hdb.h \
 	hdb_asn1.h \
 	hdb_err.h
@@ -18,18 +43,24 @@
 	ext.c \
 	hdb-ldap.c \
 	hdb.c \
-	hdb_asn1.h \
 	hdb_err.c \
 	hdb_err.h \
+	hdb-sqlite.c \
+	hdb-keytab.c \
+	hdb-mitdb.c \
+	hdb_locl.h \
+	hdb-private.h \
 	keys.c \
 	keytab.c \
 	mkey.c \
 	ndbm.c \
 	print.c \
-	${GEN:S/.x$/.c/}
+	${GEN:S/.x$/.c/:S/.hx$/.h/}
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/hdb -I${KRB5DIR}/lib/asn1 \
-	-I${KRB5DIR}/lib/roken -I. ${LDAPCFLAGS}
+	-I${KRB5DIR}/lib/roken -I${KRB5DIR}/lib/sqlite \
+	-I${KRB5DIR}/lib/krb5 \
+	-I. ${LDAPCFLAGS}
 CFLAGS+=3D-DHDB_DB_DIR=3D"\"/var/heimdal\""
=20
 GEN=3D	asn1_Salt.x \
@@ -38,6 +69,7 @@
 	asn1_HDBFlags.x \
 	asn1_GENERATION.x \
 	asn1_HDB_Ext_PKINIT_acl.x \
+	asn1_HDB_Ext_PKINIT_cert.x \
 	asn1_HDB_Ext_PKINIT_hash.x \
 	asn1_HDB_Ext_Constrained_delegation_acl.x \
 	asn1_HDB_Ext_Lan_Manager_OWF.x \
@@ -46,22 +78,29 @@
 	asn1_HDB_extension.x \
 	asn1_HDB_extensions.x \
 	asn1_hdb_entry.x \
-	asn1_hdb_entry_alias.x
+	asn1_hdb_entry_alias.x \
+	asn1_hdb_keyset.x \
+	hdb_asn1.hx \
+	hdb_asn1-priv.hx
=20
-CLEANFILES=3D ${GEN} ${GEN:S/.x$/.c/} hdb_asn1.h asn1_files
+CLEANFILES=3D	${GEN} ${GEN:S/.x$/.c/:S/.hx$/.h/} hdb_asn1_files \
+		hdb_asn1-template.[ch]*
=20
-.ORDER: ${GEN} hdb_asn1.h
-${GEN} hdb_asn1.h: hdb.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} hdb_asn1
+ASN1_COMPILE=3D	asn1_compile
=20
-../../tools/asn1_compile/asn1_compile:
-	cd ${.CURDIR}/../../tools/asn1_compile && ${MAKE}
+${GEN}: hdb.asn1
+	${ASN1_COMPILE} ${.ALLSRC:M*.asn1} hdb_asn1
=20
-.for I in ${GEN}
-${I:R}.c: ${I}
-	cat ${.ALLSRC} > ${.TARGET}
-.endfor
+.SUFFIXES: .h .c .x .hx
+
+.x.c:  =20
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
+
+.hx.h:
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
=20
 .include <bsd.lib.mk>
=20
-.PATH: ${KRB5DIR}/lib/hdb
+.SUFFIXES: .h .c .x .hx
+
+.PATH: ${KRB5DIR}/lib/hdb ${KRB5DIR}/doc/doxyout/hdb/man/man3/
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libheimntlm/Makefile
--- a/head/kerberos5/lib/libheimntlm/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libheimntlm/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,14 +1,40 @@
-# $FreeBSD: head/kerberos5/lib/libheimntlm/Makefile 225778 2011-09-27 07:1=
4:12Z stas $
+# $FreeBSD: head/kerberos5/lib/libheimntlm/Makefile 233294 2012-03-22 08:4=
8:42Z stas $
=20
 LIB=3D	heimntlm
 LDFLAGS=3D	-Wl,--no-undefined
-LDADD=3D	-lcrypto -lkrb5
-DPADD=3D	${LIBCRYPTO} ${LIBKRB5}
-SRCS=3D	ntlm.c
-INCS=3D	heimntlm.h heimntlm-protos.h
-CFLAGS+=3D-I${KRB5DIR}/lib/ntlm
+LDADD=3D	-lcrypto -lcom_err -lkrb5 -lroken
+DPADD=3D	${LIBCRYPTO} ${LIBCOM_ERR} ${LIBKRB5} ${LIBROKEN}
+SRCS=3D	ntlm.c ntlm_err.c
+INCS=3D	heimntlm.h heimntlm-protos.h ntlm_err.h
+CFLAGS+=3D-I${KRB5DIR}/lib/ntlm -I${KRB5DIR}/lib/roken
 VERSION_MAP=3D ${KRB5DIR}/lib/ntlm/version-script.map
=20
+MAN=3D	ntlm_buf.3 \
+	ntlm_core.3 \
+	ntlm_type1.3 \
+	ntlm_type2.3 \
+	ntlm_type3.3
+
+MLINKS=3D	ntlm_core.3 heim_ntlm_build_ntlm1_master.3 \
+	ntlm_core.3 heim_ntlm_build_ntlm2_master.3 \
+	ntlm_core.3 heim_ntlm_calculate_lm2.3 \
+	ntlm_core.3 heim_ntlm_calculate_ntlm1.3 \
+	ntlm_core.3 heim_ntlm_calculate_ntlm2.3 \
+	ntlm_core.3 heim_ntlm_decode_targetinfo.3 \
+	ntlm_core.3 heim_ntlm_encode_targetinfo.3 \
+	ntlm_core.3 heim_ntlm_encode_type1.3 \
+	ntlm_core.3 heim_ntlm_encode_type2.3 \
+	ntlm_core.3 heim_ntlm_encode_type3.3 \
+	ntlm_core.3 heim_ntlm_free_buf.3 \
+	ntlm_core.3 heim_ntlm_free_targetinfo.3 \
+	ntlm_core.3 heim_ntlm_free_type1.3 \
+	ntlm_core.3 heim_ntlm_free_type2.3 \
+	ntlm_core.3 heim_ntlm_free_type3.3 \
+	ntlm_core.3 heim_ntlm_keyex_unwrap.3 \
+	ntlm_core.3 heim_ntlm_nt_key.3 \
+	ntlm_core.3 heim_ntlm_ntlmv2_key.3 \
+	ntlm_core.3 heim_ntlm_verify_ntlm2.3
+
 .include <bsd.lib.mk>
=20
-.PATH: ${KRB5DIR}/lib/ntlm
+.PATH: ${KRB5DIR}/lib/ntlm ${KRB5DIR}/doc/doxyout/ntlm/man/man3
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libhx509/Makefile
--- a/head/kerberos5/lib/libhx509/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libhx509/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,173 @@
-# $FreeBSD: head/kerberos5/lib/libhx509/Makefile 225778 2011-09-27 07:14:1=
2Z stas $
+# $FreeBSD: head/kerberos5/lib/libhx509/Makefile 233294 2012-03-22 08:48:4=
2Z stas $
=20
 LIB=3D	hx509
 LDFLAGS=3D	-Wl,--no-undefined
 VERSION_MAP=3D ${KRB5DIR}/lib/hx509/version-script.map
-LDADD=3D	-lasn1 -lcom_err -lcrypto -lroken
-DPADD=3D	${LIBASN1} ${LIBCOM_ERR} ${LIBCRYPTO} ${LIBROKEN}
+LDADD=3D	-lasn1 -lcom_err -lcrypto -lroken -lwind
+DPADD=3D	${LIBASN1} ${LIBCOM_ERR} ${LIBCRYPTO} ${LIBROKEN} ${LIBWIND}
+
+MAN=3D	hx509.3 \
+	hx509_ca.3 \
+	hx509_cert.3 \
+	hx509_cms.3 \
+	hx509_crypto.3 \
+	hx509_env.3 \
+	hx509_error.3 \
+	hx509_keyset.3 \
+	hx509_lock.3 \
+	hx509_misc.3 \
+	hx509_name.3 \
+	hx509_peer.3 \
+	hx509_print.3 \
+	hx509_query.3 \
+	hx509_revoke.3 \
+	hx509_verify.3
+
+MLINKS=3D	hx509.3 hx509_context_free.3 \
+	hx509.3 hx509_context_init.3 \
+	hx509_ca.3 hx509_ca_sign.3 \
+	hx509_ca.3 hx509_ca_sign_self.3 \
+	hx509_ca.3 hx509_ca_tbs_add_crl_dp_uri.3 \
+	hx509_ca.3 hx509_ca_tbs_add_eku.3 \
+	hx509_ca.3 hx509_ca_tbs_add_san_hostname.3 \
+	hx509_ca.3 hx509_ca_tbs_add_san_jid.3 \
+	hx509_ca.3 hx509_ca_tbs_add_san_ms_upn.3 \
+	hx509_ca.3 hx509_ca_tbs_add_san_otherName.3 \
+	hx509_ca.3 hx509_ca_tbs_add_san_pkinit.3 \
+	hx509_ca.3 hx509_ca_tbs_add_san_rfc822name.3 \
+	hx509_ca.3 hx509_ca_tbs_free.3 \
+	hx509_ca.3 hx509_ca_tbs_init.3 \
+	hx509_ca.3 hx509_ca_tbs_set_ca.3 \
+	hx509_ca.3 hx509_ca_tbs_set_domaincontroller.3 \
+	hx509_ca.3 hx509_ca_tbs_set_notAfter.3 \
+	hx509_ca.3 hx509_ca_tbs_set_notAfter_lifetime.3 \
+	hx509_ca.3 hx509_ca_tbs_set_notBefore.3 \
+	hx509_ca.3 hx509_ca_tbs_set_proxy.3 \
+	hx509_ca.3 hx509_ca_tbs_set_serialnumber.3 \
+	hx509_ca.3 hx509_ca_tbs_set_spki.3 \
+	hx509_ca.3 hx509_ca_tbs_set_subject.3 \
+	hx509_ca.3 hx509_ca_tbs_set_template.3 \
+	hx509_ca.3 hx509_ca_tbs_set_unique.3 \
+	hx509_ca.3 hx509_ca_tbs_subject_expand.3 \
+	hx509_ca.3 hx509_ca_tbs_template_units.3 \
+	hx509_cert.3 hx509_cert_binary.3 \
+	hx509_cert.3 hx509_cert_check_eku.3 \
+	hx509_cert.3 hx509_cert_cmp.3 \
+	hx509_cert.3 hx509_cert_find_subjectAltName_otherName.3 \
+	hx509_cert.3 hx509_cert_free.3 \
+	hx509_cert.3 hx509_cert_get_SPKI.3 \
+	hx509_cert.3 hx509_cert_get_SPKI_AlgorithmIdentifier.3 \
+	hx509_cert.3 hx509_cert_get_attribute.3 \
+	hx509_cert.3 hx509_cert_get_base_subject.3 \
+	hx509_cert.3 hx509_cert_get_friendly_name.3 \
+	hx509_cert.3 hx509_cert_get_issuer.3 \
+	hx509_cert.3 hx509_cert_get_issuer_unique_id.3 \
+	hx509_cert.3 hx509_cert_get_notAfter.3 \
+	hx509_cert.3 hx509_cert_get_notBefore.3 \
+	hx509_cert.3 hx509_cert_get_serialnumber.3 \
+	hx509_cert.3 hx509_cert_get_subject.3 \
+	hx509_cert.3 hx509_cert_get_subject_unique_id.3 \
+	hx509_cert.3 hx509_cert_init.3 \
+	hx509_cert.3 hx509_cert_init_data.3 \
+	hx509_cert.3 hx509_cert_ref.3 \
+	hx509_cert.3 hx509_cert_set_friendly_name.3 \
+	hx509_cert.3 hx509_print_cert.3 \
+	hx509_cert.3 hx509_query_alloc.3 \
+	hx509_cert.3 hx509_query_free.3 \
+	hx509_cert.3 hx509_query_match_cmp_func.3 \
+	hx509_cert.3 hx509_query_match_eku.3 \
+	hx509_cert.3 hx509_query_match_friendly_name.3 \
+	hx509_cert.3 hx509_query_match_issuer_serial.3 \
+	hx509_cert.3 hx509_query_match_option.3 \
+	hx509_cert.3 hx509_query_statistic_file.3 \
+	hx509_cert.3 hx509_query_unparse_stats.3 \
+	hx509_cert.3 hx509_verify_ctx_f_allow_default_trustanchors.3 \
+	hx509_cert.3 hx509_verify_hostname.3 \
+	hx509_cms.3 hx509_cms_create_signed_1.3 \
+	hx509_cms.3 hx509_cms_envelope_1.3 \
+	hx509_cms.3 hx509_cms_unenvelope.3 \
+	hx509_cms.3 hx509_cms_unwrap_ContentInfo.3 \
+	hx509_cms.3 hx509_cms_verify_signed.3 \
+	hx509_cms.3 hx509_cms_wrap_ContentInfo.3 \
+	hx509_crypto.3 hx509_verify_signature.3 \
+	hx509_env.3 hx509_env_add.3 \
+	hx509_env.3 hx509_env_add_binding.3 \
+	hx509_env.3 hx509_env_find.3 \
+	hx509_env.3 hx509_env_find_binding.3 \
+	hx509_env.3 hx509_env_free.3 \
+	hx509_env.3 hx509_env_lfind.3 \
+	hx509_error.3 hx509_clear_error_string.3 \
+	hx509_error.3 hx509_err.3 \
+	hx509_error.3 hx509_free_error_string.3 \
+	hx509_error.3 hx509_get_error_string.3 \
+	hx509_error.3 hx509_set_error_string.3 \
+	hx509_error.3 hx509_set_error_stringv.3 \
+	hx509_keyset.3 hx509_certs_add.3 \
+	hx509_keyset.3 hx509_certs_append.3 \
+	hx509_keyset.3 hx509_certs_end_seq.3 \
+	hx509_keyset.3 hx509_certs_filter.3 \
+	hx509_keyset.3 hx509_certs_find.3 \
+	hx509_keyset.3 hx509_certs_free.3 \
+	hx509_keyset.3 hx509_certs_info.3 \
+	hx509_keyset.3 hx509_certs_init.3 \
+	hx509_keyset.3 hx509_certs_iter_f.3 \
+	hx509_keyset.3 hx509_certs_merge.3 \
+	hx509_keyset.3 hx509_certs_next_cert.3 \
+	hx509_keyset.3 hx509_certs_start_seq.3 \
+	hx509_keyset.3 hx509_certs_store.3 \
+	hx509_keyset.3 hx509_ci_print_names.3 \
+	hx509_keyset.3 hx509_get_one_cert.3 \
+	hx509_misc.3 hx509_free_octet_string_list.3 \
+	hx509_misc.3 hx509_xfree.3 \
+	hx509_name.3 hx509_general_name_unparse.3 \
+	hx509_name.3 hx509_name_binary.3 \
+	hx509_name.3 hx509_name_cmp.3 \
+	hx509_name.3 hx509_name_copy.3 \
+	hx509_name.3 hx509_name_expand.3 \
+	hx509_name.3 hx509_name_free.3 \
+	hx509_name.3 hx509_name_is_null_p.3 \
+	hx509_name.3 hx509_name_to_Name.3 \
+	hx509_name.3 hx509_name_to_string.3 \
+	hx509_name.3 hx509_parse_name.3 \
+	hx509_name.3 hx509_unparse_der_name.3 \
+	hx509_peer.3 hx509_peer_info_add_cms_alg.3 \
+	hx509_peer.3 hx509_peer_info_alloc.3 \
+	hx509_peer.3 hx509_peer_info_free.3 \
+	hx509_peer.3 hx509_peer_info_set_cert.3 \
+	hx509_peer.3 hx509_peer_info_set_cms_algs.3 \
+	hx509_print.3 hx509_bitstring_print.3 \
+	hx509_print.3 hx509_cert_keyusage_print.3 \
+	hx509_print.3 hx509_oid_print.3 \
+	hx509_print.3 hx509_oid_sprint.3 \
+	hx509_print.3 hx509_print_stdout.3 \
+	hx509_print.3 hx509_validate_cert.3 \
+	hx509_print.3 hx509_validate_ctx_add_flags.3 \
+	hx509_print.3 hx509_validate_ctx_free.3 \
+	hx509_print.3 hx509_validate_ctx_init.3 \
+	hx509_print.3 hx509_validate_ctx_set_print.3 \
+	hx509_revoke.3 hx509_ocsp_request.3 \
+	hx509_revoke.3 hx509_revoke_add_crl.3 \
+	hx509_revoke.3 hx509_revoke_add_ocsp.3 \
+	hx509_revoke.3 hx509_revoke_free.3 \
+	hx509_revoke.3 hx509_revoke_init.3 \
+	hx509_revoke.3 hx509_revoke_ocsp_print.3 \
+	hx509_revoke.3 hx509_revoke_verify.3 \
+	hx509_verify.3 hx509_context_set_missing_revoke.3 \
+	hx509_verify.3 hx509_crl_add_revoked_certs.3 \
+	hx509_verify.3 hx509_crl_alloc.3 \
+	hx509_verify.3 hx509_crl_free.3 \
+	hx509_verify.3 hx509_crl_lifetime.3 \
+	hx509_verify.3 hx509_crl_sign.3 \
+	hx509_verify.3 hx509_ocsp_verify.3 \
+	hx509_verify.3 hx509_verify_attach_anchors.3 \
+	hx509_verify.3 hx509_verify_attach_revoke.3 \
+	hx509_verify.3 hx509_verify_destroy_ctx.3 \
+	hx509_verify.3 hx509_verify_init_ctx.3 \
+	hx509_verify.3 hx509_verify_path.3 \
+	hx509_verify.3 hx509_verify_set_max_depth.3 \
+	hx509_verify.3 hx509_verify_set_proxy_certificate.3 \
+	hx509_verify.3 hx509_verify_set_strict_rfc3280_verification.3 \
+	hx509_verify.3 hx509_verify_set_time.3
=20
 INCS=3D	hx509-private.h \
 	hx509-protos.h \
@@ -13,6 +176,7 @@
=20
 SRCS=3D	ca.c \
 	cert.c \
+	char_map.h \
 	cms.c \
 	collector.c \
 	crypto.c \
@@ -24,6 +188,10 @@
 	hx509-protos.h \
 	hx509.h \
 	hx_locl.h \
+	sel.c \
+	sel.h \
+	sel-gram.y \
+	sel-lex.l \
 	keyset.c \
 	ks_dir.c \
 	ks_file.c \
@@ -44,11 +212,13 @@
 SRCS+=3D	hx509_err.c \
 	hx509_err.h
=20
-SRCS+=3D	${GEN:S/.x$/.c/}
+SRCS+=3D	${GEN_OCSP:S/.x$/.c/:S/.hx$/.h/} \
+	${GEN_PKCS10:S/.x$/.c/:S/.hx$/.h/}
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/hx509
 CFLAGS+=3D-I${KRB5DIR}/lib/hx509/ref
 CFLAGS+=3D-I${KRB5DIR}/lib/asn1
+CFLAGS+=3D-I${KRB5DIR}/lib/wind
 CFLAGS+=3D-I${KRB5DIR}/lib/roken -I.
=20
 GEN_OCSP=3D \
@@ -69,38 +239,66 @@
 	asn1_OCSPVersion.x \
 	asn1_id_pkix_ocsp.x \
 	asn1_id_pkix_ocsp_basic.x \
-	asn1_id_pkix_ocsp_nonce.x
+	asn1_id_pkix_ocsp_nonce.x \
+	ocsp_asn1.hx \
+	ocsp_asn1-priv.hx
=20
 GEN_PKCS10=3D \
 	asn1_CertificationRequestInfo.x \
-	asn1_CertificationRequest.x
+	asn1_CertificationRequest.x \
+	pkcs10_asn1.hx \
+	pkcs10_asn1-priv.hx
+
+GEN_CRMF=3D \
+	asn1_CRMFRDNSequence.x \
+	asn1_CertReqMessages.x \
+	asn1_CertReqMsg.x \
+	asn1_CertRequest.x \
+	asn1_CertTemplate.x \
+	asn1_Controls.x \
+	asn1_PBMParameter.x \
+	asn1_PKMACValue.x \
+	asn1_POPOPrivKey.x \
+	asn1_POPOSigningKey.x \
+	asn1_POPOSigningKeyInput.x \
+	asn1_ProofOfPossession.x \
+	asn1_SubsequentMessage.x \
+	crmf_asn1.hx \
+	crmf_asn1-priv.hx
=20
 GEN+=3D	${GEN_OCSP}
 GEN+=3D	${GEN_PKCS10}
+GEN+=3D	${GEN_CRMF}
=20
-CLEANFILES=3D ${GEN} ${GEN:S/.x$/.c/} asn1_files
+CLEANFILES=3D ${GEN} ${GEN:S/.x$/.c/:S/.hx$/.h/} ocsp_asn1_files \
+	pkcs10_asn1_files crmf_asn1_files ocsp_asn1-template.[ch]* \
+	pkcs10_asn1-template.[ch]* crmf_asn1-template.[ch]*
=20
-GEN_ASN1=3Docsp_asn1.h pkcs10_asn1.h
-CLEANFILES+=3D${GEN_ASN1}
-SRCS+=3D${GEN_ASN1}
-INCS+=3D${GEN_ASN1}
+INCS+=3D	ocsp_asn1.h pkcs10_asn1.h crmf_asn1.h
=20
-.ORDER: ${GEN} ${GEN_ASN1}
+ASN1_COMPILE=3D	asn1_compile
=20
-${GEN_OCSP} ocsp_asn1.h: ocsp.asn1 ../../tools/asn1_compile/asn1_compile
-	../../tools/asn1_compile/asn1_compile --preserve-binary=3DOCSPTBSRequest =
--preserve-binary=3DOCSPResponseData ${.ALLSRC:M*.asn1} ocsp_asn1
+${GEN_OCSP}: ocsp.asn1 ocsp.opt
+	${ASN1_COMPILE} --option-file=3D${.ALLSRC:M*.opt} \
+	 ${.ALLSRC:M*.asn1} ocsp_asn1
=20
-${GEN_PKCS10} pkcs10_asn1.h: pkcs10.asn1 ../../tools/asn1_compile/asn1_com=
pile
-	../../tools/asn1_compile/asn1_compile ${.ALLSRC:M*.asn1} pkcs10_asn1
+${GEN_PKCS10}: pkcs10.asn1 pkcs10.opt
+	${ASN1_COMPILE} --option-file=3D${.ALLSRC:M*.opt} \
+	${.ALLSRC:M*.asn1} pkcs10_asn1
=20
-../../tools/asn1_compile/asn1_compile:
-	cd ${.CURDIR}/../../tools/asn1_compile && ${MAKE}
+${GEN_CRMF}: crmf.asn1
+	${ASN1_COMPILE} ${.ALLSRC:M*.asn1} crmf_asn1
=20
-.for I in ${GEN}
-${I:R}.c: ${I}
-	cat ${.ALLSRC} > ${.TARGET}
-.endfor
+.SUFFIXES: .h .c .x .hx
+
+.x.c:  =20
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
+
+.hx.h:
+	cmp -s ${.IMPSRC} ${.TARGET} 2> /dev/null || cp ${.IMPSRC} ${.TARGET}
=20
 .include <bsd.lib.mk>
=20
-.PATH: ${KRB5DIR}/lib/hx509 ${KRB5DIR}/lib/asn1
+.SUFFIXES: .h .c .x .hx
+
+.PATH: ${KRB5DIR}/lib/hx509 ${KRB5DIR}/lib/asn1 ${KRB5DIR}/doc/doxyout/hx5=
09/man/man3
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libkadm5clnt/Makefi=
le
--- a/head/kerberos5/lib/libkadm5clnt/Makefile	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/kerberos5/lib/libkadm5clnt/Makefile	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-# $FreeBSD: head/kerberos5/lib/libkadm5clnt/Makefile 225778 2011-09-27 07:=
14:12Z stas $
+# $FreeBSD: head/kerberos5/lib/libkadm5clnt/Makefile 233294 2012-03-22 08:=
48:42Z stas $
=20
 LIB=3D	kadm5clnt
 LDFLAGS=3D	-Wl,--no-undefined
@@ -8,6 +8,7 @@
 INCS=3D	admin.h \
 	kadm5-private.h \
 	kadm5-protos.h \
+	kadm5-pwcheck.h \
 	kadm5_err.h \
 	private.h
=20
@@ -25,14 +26,17 @@
 	get_c.c \
 	get_princs_c.c \
 	init_c.c \
+	kadm5_locl.h \
 	kadm5_err.c \
 	kadm5_err.h \
 	marshall.c \
 	modify_c.c \
+	private.h \
 	privs_c.c \
 	randkey_c.c \
 	rename_c.c \
-	send_recv.c
+	send_recv.c \
+	admin.h
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/kadm5 -I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/ro=
ken -I.
=20
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libkadm5srv/Makefile
--- a/head/kerberos5/lib/libkadm5srv/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libkadm5srv/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,15 @@
-# $FreeBSD: head/kerberos5/lib/libkadm5srv/Makefile 225778 2011-09-27 07:1=
4:12Z stas $
+# $FreeBSD: head/kerberos5/lib/libkadm5srv/Makefile 233294 2012-03-22 08:4=
8:42Z stas $
=20
 LIB=3D	kadm5srv
 LDFLAGS=3D	-Wl,--no-undefined
 LDADD=3D	-lcom_err -lhdb -lkrb5 -lroken
 DPADD=3D	${LIBCOM_ERR} ${LIBHDB} ${LIBKRB5} ${LIBROKEN}
 VERSION_MAP=3D ${KRB5DIR}/lib/kadm5/version-script.map
+MAN=3D	kadm5_pwcheck.3
=20
 SRCS=3D	acl.c \
+	admin.h \
+	admin.h \
 	bump_pw_expire.c \
 	chpass_s.c \
 	common_glue.c \
@@ -23,11 +26,13 @@
 	init_s.c \
 	kadm5_err.c \
 	kadm5_err.h \
+	kadm5_locl.h \
 	keys.c \
 	log.c \
 	marshall.c \
 	modify_s.c \
 	password_quality.c \
+	private.h \
 	privs_s.c \
 	randkey_s.c \
 	rename_s.c \
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libkafs5/Makefile
--- a/head/kerberos5/lib/libkafs5/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libkafs5/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,11 +1,12 @@
-# $FreeBSD: head/kerberos5/lib/libkafs5/Makefile 225778 2011-09-27 07:14:1=
2Z stas $
+# $FreeBSD: head/kerberos5/lib/libkafs5/Makefile 234013 2012-04-08 04:22:0=
9Z stas $
=20
 LIB=3D	kafs5
+LDADD=3D	-lasn1 -lroken -lkrb5
 LDFLAGS=3D	-Wl,--no-undefined
-LDADD=3D	-lasn1 -lkrb5 -lroken
 DPADD=3D	${LIBASN1} ${LIBKRB5} ${LIBROKEN}
 INCS=3D	kafs.h
 MAN=3D	kafs5.3
+VERSION_MAP=3D	${.CURDIR}/version.map
=20
 MLINKS=3D	kafs5.3 k_afs_cell_of_file.3 \
 	kafs5.3 k_hasafs.3 \
@@ -23,7 +24,16 @@
 	kafs5.3 krb_afslog_uid.3
=20
 SRCS=3D	afssys.c afskrb5.c common.c krb5_err.h
-CFLAGS+=3D-I${KRB5DIR}/lib/kafs -I${KRB5DIR}/lib/krb5 -I${KRB5DIR}/lib/rok=
en
+SRCS=3D	afssys.c \
+	afskrb5.c \
+	common.c \
+	kafs_locl.h \
+	afssysdefs.h \
+	roken_rename.h
+CFLAGS+=3D	-I${KRB5DIR}/lib/kafs \
+		-I${KRB5DIR}/lib/krb5 \
+		-I${.OBJDIR}/../libkrb5/ \
+		-I${KRB5DIR}/lib/roken
=20
 CLEANFILES=3D kafs5.3
=20
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libkrb5/Makefile
--- a/head/kerberos5/lib/libkrb5/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libkrb5/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,20 +1,26 @@
-# $FreeBSD: head/kerberos5/lib/libkrb5/Makefile 225778 2011-09-27 07:14:12=
Z stas $
+# $FreeBSD: head/kerberos5/lib/libkrb5/Makefile 233294 2012-03-22 08:48:42=
Z stas $
=20
 LIB=3D	krb5
 LDFLAGS=3D	-Wl,--no-undefined
 VERSION_MAP=3D ${KRB5DIR}/lib/krb5/version-script.map
-LDADD=3D	-lasn1 -lcom_err -lcrypt -lcrypto -lhx509 -lroken
-DPADD=3D	${LIBASN1} ${LIBCOM_ERR} ${LIBCRYPT} ${LIBCRYPTO} ${LIBHX509} ${L=
IBROKEN}
+LDADD=3D	-lasn1 -lcom_err -lcrypt -lcrypto -lhx509 -lroken -lwind -lheimba=
se ${LIBHEIMIPCC}
+DPADD=3D	${LIBASN1} ${LIBCOM_ERR} ${LIBCRYPT} ${LIBCRYPTO} ${LIBHX509} ${L=
IBROKEN} ${LIBWIND} ${LIBHEIMBASE} ${LIBHEIMIPCC}
=20
 INCS=3D	heim_err.h \
 	heim_threads.h \
 	k524_err.h \
 	krb5-protos.h \
+	krb5-private.h \
 	krb5-types.h \
 	krb5.h \
 	krb5_err.h \
-	krb5-v4compat.h \
-	krb_err.h
+	krb5_ccapi.h
+
+KRB5INCS=3D	locate_plugin.h \
+		send_to_kdc_plugin.h \
+		ccache_plugin.h
+KRB5INCSDIR=3D	${INCLUDEDIR}/krb5
+INCSGROUPS=3D	INCS KRB5INCS
=20
 MAN=3D	krb5.3 \
 	krb524_convert_creds_kdc.3 \
@@ -23,21 +29,23 @@
 	krb5_address.3 \
 	krb5_aname_to_localname.3 \
 	krb5_appdefault.3 \
+	krb5_auth.3 \
 	krb5_auth_context.3 \
 	krb5_c_make_checksum.3 \
 	krb5_ccache.3 \
+	krb5_ccache_intro.3 \
 	krb5_check_transited.3 \
-	krb5_compare_creds.3 \
-	krb5_config.3 \
-	krb5_context.3 \
 	krb5_create_checksum.3 \
+	krb5_credential.3 \
 	krb5_creds.3 \
-	krb5_crypto_init.3 \
-	krb5_data.3 \
+	krb5_crypto.3 \
+	krb5_crypto_iov.3 \
+	krb5_deprecated.3 \
 	krb5_digest.3 \
 	krb5_eai_to_heim_errno.3 \
 	krb5_encrypt.3 \
-	krb5_expand_hostname.3 \
+	krb5_error.3 \
+	krb5_fileformats.3 \
 	krb5_find_padata.3 \
 	krb5_generate_random_block.3 \
 	krb5_get_all_client_addrs.3 \
@@ -49,16 +57,19 @@
 	krb5_get_krbhst.3 \
 	krb5_getportbyname.3 \
 	krb5_init_context.3 \
+	krb5_init_creds_intro.3 \
+	krb5_introduction.3 \
 	krb5_is_thread_safe.3 \
-	krb5_keyblock.3 \
 	krb5_keytab.3 \
+	krb5_keytab_intro.3 \
 	krb5_krbhst_init.3 \
-	krb5_kuserok.3 \
 	krb5_mk_req.3 \
 	krb5_mk_safe.3 \
 	krb5_openlog.3 \
+	krb5_pac.3 \
 	krb5_parse_name.3 \
 	krb5_principal.3 \
+	krb5_principal_intro.3 \
 	krb5_rcache.3 \
 	krb5_rd_error.3 \
 	krb5_rd_safe.3 \
@@ -66,24 +77,76 @@
 	krb5_set_password.3 \
 	krb5_storage.3 \
 	krb5_string_to_key.3 \
+	krb5_support.3 \
 	krb5_ticket.3 \
 	krb5_timeofday.3 \
-	krb5_unparse_name.3 \
+	krb5_v4compat.3 \
 	krb5_verify_init_creds.3 \
 	krb5_verify_user.3 \
-	krb5_warn.3 \
 	verify_krb5_conf.8
=20
 MAN+=3D	krb5.conf.5
 MAN+=3D	kerberos.8
=20
-MLINKS=3D	krb5_425_conv_principal.3 krb5_425_conv_principal_ext.3 \
+MLINKS=3D	krb5.3 krb5_add_et_list.3 \
+	krb5.3 krb5_add_extra_addresses.3 \
+	krb5.3 krb5_add_ignore_addresses.3 \
+	krb5.3 krb5_compare_creds.3 \
+	krb5.3 krb5_copy_context.3 \
+	krb5.3 krb5_copy_creds.3 \
+	krb5.3 krb5_copy_creds_contents.3 \
+	krb5.3 krb5_copy_data.3 \
+	krb5.3 krb5_copy_host_realm.3 \
+	krb5.3 krb5_copy_ticket.3 \
+	krb5.3 krb5_creds_get_ticket_flags.3 \
+	krb5.3 krb5_data_alloc.3 \
+	krb5.3 krb5_data_cmp.3 \
+	krb5.3 krb5_data_copy.3 \
+	krb5.3 krb5_data_ct_cmp.3 \
+	krb5.3 krb5_data_free.3 \
+	krb5.3 krb5_data_realloc.3 \
+	krb5.3 krb5_data_zero.3 \
+	krb5.3 krb5_free_config_files.3 \
+	krb5.3 krb5_free_context.3 \
+	krb5.3 krb5_free_cred_contents.3 \
+	krb5.3 krb5_free_creds.3 \
+	krb5.3 krb5_free_data.3 \
+	krb5.3 krb5_free_ticket.3 \
+	krb5.3 krb5_get_default_config_files.3 \
+	krb5.3 krb5_get_default_in_tkt_etypes.3 \
+	krb5.3 krb5_get_dns_canonicalize_hostname.3 \
+	krb5.3 krb5_get_extra_addresses.3 \
+	krb5.3 krb5_get_fcache_version.3 \
+	krb5.3 krb5_get_ignore_addresses.3 \
+	krb5.3 krb5_get_kdc_sec_offset.3 \
+	krb5.3 krb5_get_max_time_skew.3 \
+	krb5.3 krb5_get_use_admin_kdc.3 \
+	krb5.3 krb5_init_ets.3 \
+	krb5.3 krb5_kerberos_enctypes.3 \
+	krb5.3 krb5_krbhst_get_addrinfo.3 \
+	krb5.3 krb5_prepend_config_files_default.3 \
+	krb5.3 krb5_set_config_files.3 \
+	krb5.3 krb5_set_default_in_tkt_etypes.3 \
+	krb5.3 krb5_set_dns_canonicalize_hostname.3 \
+	krb5.3 krb5_set_extra_addresses.3 \
+	krb5.3 krb5_set_fcache_version.3 \
+	krb5.3 krb5_set_home_dir_access.3 \
+	krb5.3 krb5_set_ignore_addresses.3 \
+	krb5.3 krb5_set_kdc_sec_offset.3 \
+	krb5.3 krb5_set_max_time_skew.3 \
+	krb5.3 krb5_set_real_time.3 \
+	krb5.3 krb5_set_use_admin_kdc.3 \
+	krb5.3 krb5_ticket_get_authorization_data_type.3 \
+	krb5.3 krb5_ticket_get_client.3 \
+	krb5.3 krb5_ticket_get_endtime.3 \
+	krb5.3 krb5_ticket_get_server.3 \
+	krb5_425_conv_principal.3 krb5_425_conv_principal_ext.3 \
 	krb5_425_conv_principal.3 krb5_524_conv_principal.3 \
 	krb5_address.3 krb5_addr2sockaddr.3 \
 	krb5_address.3 krb5_address_compare.3 \
 	krb5_address.3 krb5_address_order.3 \
+	krb5_address.3 krb5_address_prefixlen_boundary.3 \
 	krb5_address.3 krb5_address_search.3 \
-	krb5_address.3 krb5_addresses.3 \
 	krb5_address.3 krb5_anyaddr.3 \
 	krb5_address.3 krb5_append_addresses.3 \
 	krb5_address.3 krb5_copy_address.3 \
@@ -102,6 +165,12 @@
 	krb5_appdefault.3 krb5_appdefault_boolean.3 \
 	krb5_appdefault.3 krb5_appdefault_string.3 \
 	krb5_appdefault.3 krb5_appdefault_time.3 \
+	krb5_auth.3 krb5_rd_req_ctx.3 \
+	krb5_auth.3 krb5_rd_req_in_ctx_alloc.3 \
+	krb5_auth.3 krb5_rd_req_in_set_keytab.3 \
+	krb5_auth.3 krb5_rd_req_in_set_pac_check.3 \
+	krb5_auth.3 krb5_rd_req_out_ctx_free.3 \
+	krb5_auth.3 krb5_rd_req_out_get_server.3 \
 	krb5_auth_context.3 krb5_auth_con_free.3 \
 	krb5_auth_context.3 krb5_auth_con_genaddrs.3 \
 	krb5_auth_context.3 krb5_auth_con_getaddrs.3 \
@@ -131,72 +200,160 @@
 	krb5_auth_context.3 krb5_auth_setkeytype.3 \
 	krb5_auth_context.3 krb5_auth_setlocalseqnumber.3 \
 	krb5_auth_context.3 krb5_auth_setremoteseqnumber.3 \
+	krb5_ccache.3 krb5_acc_ops.3 \
+	krb5_ccache.3 krb5_cc_cache_end_seq_get.3 \
+	krb5_ccache.3 krb5_cc_cache_get_first.3 \
+	krb5_ccache.3 krb5_cc_cache_match.3 \
+	krb5_ccache.3 krb5_cc_cache_next.3 \
+	krb5_ccache.3 krb5_cc_clear_mcred.3 \
 	krb5_ccache.3 krb5_cc_close.3 \
 	krb5_ccache.3 krb5_cc_copy_cache.3 \
-	krb5_ccache.3 krb5_cc_cursor.3 \
+	krb5_ccache.3 krb5_cc_copy_creds.3 \
+	krb5_ccache.3 krb5_cc_copy_match_f.3 \
 	krb5_ccache.3 krb5_cc_default.3 \
 	krb5_ccache.3 krb5_cc_default_name.3 \
 	krb5_ccache.3 krb5_cc_destroy.3 \
 	krb5_ccache.3 krb5_cc_end_seq_get.3 \
 	krb5_ccache.3 krb5_cc_gen_new.3 \
+	krb5_ccache.3 krb5_cc_get_config.3 \
+	krb5_ccache.3 krb5_cc_get_flags.3 \
+	krb5_ccache.3 krb5_cc_get_friendly_name.3 \
+	krb5_ccache.3 krb5_cc_get_full_name.3 \
+	krb5_ccache.3 krb5_cc_get_kdc_offset.3 \
+	krb5_ccache.3 krb5_cc_get_lifetime.3 \
 	krb5_ccache.3 krb5_cc_get_name.3 \
 	krb5_ccache.3 krb5_cc_get_ops.3 \
+	krb5_ccache.3 krb5_cc_get_prefix_ops.3 \
 	krb5_ccache.3 krb5_cc_get_principal.3 \
 	krb5_ccache.3 krb5_cc_get_type.3 \
 	krb5_ccache.3 krb5_cc_get_version.3 \
 	krb5_ccache.3 krb5_cc_initialize.3 \
+	krb5_ccache.3 krb5_cc_last_change_time.3 \
+	krb5_ccache.3 krb5_cc_move.3 \
+	krb5_ccache.3 krb5_cc_new_unique.3 \
 	krb5_ccache.3 krb5_cc_next_cred.3 \
-	krb5_ccache.3 krb5_cc_ops.3 \
 	krb5_ccache.3 krb5_cc_register.3 \
 	krb5_ccache.3 krb5_cc_remove_cred.3 \
 	krb5_ccache.3 krb5_cc_resolve.3 \
 	krb5_ccache.3 krb5_cc_retrieve_cred.3 \
+	krb5_ccache.3 krb5_cc_set_config.3 \
 	krb5_ccache.3 krb5_cc_set_default_name.3 \
 	krb5_ccache.3 krb5_cc_set_flags.3 \
+	krb5_ccache.3 krb5_cc_set_friendly_name.3 \
+	krb5_ccache.3 krb5_cc_set_kdc_offset.3 \
+	krb5_ccache.3 krb5_cc_start_seq_get.3 \
 	krb5_ccache.3 krb5_cc_store_cred.3 \
+	krb5_ccache.3 krb5_cc_support_switch.3 \
+	krb5_ccache.3 krb5_cc_switch.3 \
+	krb5_ccache.3 krb5_cccol_cursor_free.3 \
+	krb5_ccache.3 krb5_cccol_cursor_new.3 \
+	krb5_ccache.3 krb5_cccol_cursor_next.3 \
+	krb5_ccache.3 krb5_cccol_last_change_time.3 \
 	krb5_ccache.3 krb5_fcc_ops.3 \
+	krb5_ccache.3 krb5_get_validated_creds.3 \
+	krb5_ccache.3 krb5_is_config_principal.3 \
 	krb5_ccache.3 krb5_mcc_ops.3 \
-	krb5_config.3 krb5_config_get_bool_default.3 \
-	krb5_config.3 krb5_config_get_int_default.3 \
-	krb5_config.3 krb5_config_get_string_default.3 \
-	krb5_config.3 krb5_config_get_time_default.3 \
 	krb5_create_checksum.3 krb5_checksum_is_collision_proof.3 \
 	krb5_create_checksum.3 krb5_checksum_is_keyed.3 \
 	krb5_create_checksum.3 krb5_checksumsize.3 \
 	krb5_create_checksum.3 krb5_verify_checksum.3 \
-	krb5_crypto_init.3 krb5_crypto_destroy.3 \
-	krb5_data.3 krb5_copy_data.3 \
-	krb5_data.3 krb5_data_alloc.3 \
-	krb5_data.3 krb5_data_copy.3 \
-	krb5_data.3 krb5_data_free.3 \
-	krb5_data.3 krb5_data_realloc.3 \
-	krb5_data.3 krb5_data_zero.3 \
-	krb5_data.3 krb5_free_data.3 \
-	krb5_data.3 krb5_free_data_contents.3 \
+	krb5_credential.3 krb5_fwd_tgt_creds.3 \
+	krb5_credential.3 krb5_get_init_creds_keyblock.3 \
+	krb5_credential.3 krb5_get_init_creds_keytab.3 \
+	krb5_credential.3 krb5_get_init_creds_opt_alloc.3 \
+	krb5_credential.3 krb5_get_init_creds_opt_free.3 \
+	krb5_credential.3 krb5_get_init_creds_password.3 \
+	krb5_credential.3 krb5_init_creds_free.3 \
+	krb5_credential.3 krb5_init_creds_get.3 \
+	krb5_credential.3 krb5_init_creds_get_error.3 \
+	krb5_credential.3 krb5_init_creds_init.3 \
+	krb5_credential.3 krb5_init_creds_set_keytab.3 \
+	krb5_credential.3 krb5_init_creds_set_password.3 \
+	krb5_credential.3 krb5_init_creds_set_service.3 \
+	krb5_credential.3 krb5_init_creds_step.3 \
+	krb5_crypto.3 krb5_allow_weak_crypto.3 \
+	krb5_crypto.3 krb5_cksumtype_to_enctype.3 \
+	krb5_crypto.3 krb5_copy_keyblock.3 \
+	krb5_crypto.3 krb5_copy_keyblock_contents.3 \
+	krb5_crypto.3 krb5_create_checksum_iov.3 \
+	krb5_crypto.3 krb5_crypto_destroy.3 \
+	krb5_crypto.3 krb5_crypto_fx_cf2.3 \
+	krb5_crypto.3 krb5_crypto_getblocksize.3 \
+	krb5_crypto.3 krb5_crypto_getconfoundersize.3 \
+	krb5_crypto.3 krb5_crypto_getenctype.3 \
+	krb5_crypto.3 krb5_crypto_getpadsize.3 \
+	krb5_crypto.3 krb5_crypto_init.3 \
+	krb5_crypto.3 krb5_decrypt_iov_ivec.3 \
+	krb5_crypto.3 krb5_encrypt_iov_ivec.3 \
+	krb5_crypto.3 krb5_enctype_disable.3 \
+	krb5_crypto.3 krb5_enctype_enable.3 \
+	krb5_crypto.3 krb5_enctype_valid.3 \
+	krb5_crypto.3 krb5_free_keyblock.3 \
+	krb5_crypto.3 krb5_free_keyblock_contents.3 \
+	krb5_crypto.3 krb5_generate_subkey_extended.3 \
+	krb5_crypto.3 krb5_keyblock_get_enctype.3 \
+	krb5_crypto.3 krb5_keyblock_init.3 \
+	krb5_crypto.3 krb5_keyblock_zero.3 \
+	krb5_crypto.3 krb5_random_to_key.3 \
+	krb5_crypto.3 krb5_verify_checksum_iov.3 \
+	krb5_deprecated.3 krb5_auth_getremoteseqnumber.3 \
+	krb5_deprecated.3 krb5_c_enctype_compare.3 \
+	krb5_deprecated.3 krb5_change_password.3 \
+	krb5_deprecated.3 krb5_clear_error_string.3 \
+	krb5_deprecated.3 krb5_config_parse_string_multi.3 \
+	krb5_deprecated.3 krb5_enctypes_compatible_keys.3 \
+	krb5_deprecated.3 krb5_free_creds_contents.3 \
+	krb5_deprecated.3 krb5_free_data_contents.3 \
+	krb5_deprecated.3 krb5_free_error_string.3 \
+	krb5_deprecated.3 krb5_free_unparsed_name.3 \
+	krb5_deprecated.3 krb5_generate_subkey.3 \
+	krb5_deprecated.3 krb5_get_cred_from_kdc.3 \
+	krb5_deprecated.3 krb5_get_cred_from_kdc_opt.3 \
+	krb5_deprecated.3 krb5_get_in_tkt_with_keytab.3 \
+	krb5_deprecated.3 krb5_get_in_tkt_with_password.3 \
+	krb5_deprecated.3 krb5_get_in_tkt_with_skey.3 \
+	krb5_deprecated.3 krb5_get_init_creds_opt_get_error.3 \
+	krb5_deprecated.3 krb5_get_init_creds_opt_init.3 \
+	krb5_deprecated.3 krb5_keytab_key_proc.3 \
+	krb5_deprecated.3 krb5_keytype_to_enctypes.3 \
+	krb5_deprecated.3 krb5_keytype_to_enctypes_default.3 \
+	krb5_deprecated.3 krb5_keytype_to_string.3 \
+	krb5_deprecated.3 krb5_password_key_proc.3 \
+	krb5_deprecated.3 krb5_princ_realm.3 \
+	krb5_deprecated.3 krb5_princ_set_realm.3 \
+	krb5_deprecated.3 krb5_set_error_string.3 \
+	krb5_deprecated.3 krb5_string_to_keytype.3 \
+	krb5_deprecated.3 krb5_vset_error_string.3 \
+	krb5_digest.3 krb5_digest_probe.3 \
 	krb5_encrypt.3 krb5_decrypt.3 \
 	krb5_encrypt.3 krb5_decrypt_EncryptedData.3 \
 	krb5_encrypt.3 krb5_encrypt_EncryptedData.3 \
+	krb5_error.3 krb5_clear_error_message.3 \
+	krb5_error.3 krb5_h_errno_to_heim_errno.3 \
+	krb5_error.3 krb5_set_error_message.3 \
+	krb5_error.3 krb5_vwarn.3 \
 	krb5_get_all_client_addrs.3 krb5_get_all_server_addrs.3 \
 	krb5_get_krbhst.3 krb5_free_krbhst.3 \
 	krb5_get_krbhst.3 krb5_get_krb524hst.3 \
 	krb5_get_krbhst.3 krb5_get_krb_admin_hst.3 \
 	krb5_get_krbhst.3 krb5_get_krb_changepw_hst.3 \
 	krb5_init_context.3 krb5_free_context.3 \
-	krb5_keytab.3 krb5_keytab_entry.3 \
 	krb5_keytab.3 krb5_kt_add_entry.3 \
 	krb5_keytab.3 krb5_kt_close.3 \
 	krb5_keytab.3 krb5_kt_compare.3 \
 	krb5_keytab.3 krb5_kt_copy_entry_contents.3 \
-	krb5_keytab.3 krb5_kt_cursor.3 \
 	krb5_keytab.3 krb5_kt_default.3 \
+	krb5_keytab.3 krb5_kt_default_modify_name.3 \
 	krb5_keytab.3 krb5_kt_default_name.3 \
+	krb5_keytab.3 krb5_kt_destroy.3 \
 	krb5_keytab.3 krb5_kt_end_seq_get.3 \
 	krb5_keytab.3 krb5_kt_free_entry.3 \
 	krb5_keytab.3 krb5_kt_get_entry.3 \
+	krb5_keytab.3 krb5_kt_get_full_name.3 \
 	krb5_keytab.3 krb5_kt_get_name.3 \
 	krb5_keytab.3 krb5_kt_get_type.3 \
+	krb5_keytab.3 krb5_kt_have_content.3 \
 	krb5_keytab.3 krb5_kt_next_entry.3 \
-	krb5_keytab.3 krb5_kt_ops.3 \
 	krb5_keytab.3 krb5_kt_read_service_key.3 \
 	krb5_keytab.3 krb5_kt_register.3 \
 	krb5_keytab.3 krb5_kt_remove_entry.3 \
@@ -216,13 +373,15 @@
 	krb5_openlog.3 krb5_log_msg.3 \
 	krb5_openlog.3 krb5_vlog.3 \
 	krb5_openlog.3 krb5_vlog_msg.3 \
-	krb5_principal.3 krb5_get_default_principal.3 \
+	krb5_pac.3 krb5_pac_get_buffer.3 \
+	krb5_pac.3 krb5_pac_verify.3 \
 	krb5_principal.3 krb5_build_principal.3 \
 	krb5_principal.3 krb5_build_principal_ext.3 \
 	krb5_principal.3 krb5_build_principal_va.3 \
 	krb5_principal.3 krb5_build_principal_va_ext.3 \
 	krb5_principal.3 krb5_copy_principal.3 \
 	krb5_principal.3 krb5_free_principal.3 \
+	krb5_principal.3 krb5_get_default_principal.3 \
 	krb5_principal.3 krb5_make_principal.3 \
 	krb5_principal.3 krb5_parse_name.3 \
 	krb5_principal.3 krb5_parse_name_flags.3 \
@@ -232,39 +391,114 @@
 	krb5_principal.3 krb5_principal_compare.3 \
 	krb5_principal.3 krb5_principal_compare_any_realm.3 \
 	krb5_principal.3 krb5_principal_get_comp_string.3 \
+	krb5_principal.3 krb5_principal_get_num_comp.3 \
 	krb5_principal.3 krb5_principal_get_realm.3 \
 	krb5_principal.3 krb5_principal_get_type.3 \
+	krb5_principal.3 krb5_principal_is_krbtgt.3 \
 	krb5_principal.3 krb5_principal_match.3 \
+	krb5_principal.3 krb5_principal_set_realm.3 \
 	krb5_principal.3 krb5_principal_set_type.3 \
 	krb5_principal.3 krb5_realm_compare.3 \
 	krb5_principal.3 krb5_sname_to_principal.3 \
 	krb5_principal.3 krb5_sock_to_principal.3 \
 	krb5_principal.3 krb5_unparse_name.3 \
-	krb5_principal.3 krb5_unparse_name_flags.3 \
 	krb5_principal.3 krb5_unparse_name_fixed.3 \
 	krb5_principal.3 krb5_unparse_name_fixed_flags.3 \
 	krb5_principal.3 krb5_unparse_name_fixed_short.3 \
+	krb5_principal.3 krb5_unparse_name_flags.3 \
 	krb5_principal.3 krb5_unparse_name_short.3 \
 	krb5_set_default_realm.3 krb5_free_host_realm.3 \
 	krb5_set_default_realm.3 krb5_get_default_realm.3 \
 	krb5_set_default_realm.3 krb5_get_default_realms.3 \
 	krb5_set_default_realm.3 krb5_get_host_realm.3 \
+	krb5_storage.3 krb5_ret_address.3 \
+	krb5_storage.3 krb5_ret_addrs.3 \
+	krb5_storage.3 krb5_ret_authdata.3 \
+	krb5_storage.3 krb5_ret_creds.3 \
+	krb5_storage.3 krb5_ret_creds_tag.3 \
+	krb5_storage.3 krb5_ret_data.3 \
+	krb5_storage.3 krb5_ret_int16.3 \
+	krb5_storage.3 krb5_ret_int32.3 \
+	krb5_storage.3 krb5_ret_int8.3 \
+	krb5_storage.3 krb5_ret_keyblock.3 \
+	krb5_storage.3 krb5_ret_principal.3 \
+	krb5_storage.3 krb5_ret_string.3 \
+	krb5_storage.3 krb5_ret_stringz.3 \
+	krb5_storage.3 krb5_ret_times.3 \
+	krb5_storage.3 krb5_ret_uint16.3 \
+	krb5_storage.3 krb5_ret_uint32.3 \
+	krb5_storage.3 krb5_ret_uint8.3 \
+	krb5_storage.3 krb5_storage_clear_flags.3 \
+	krb5_storage.3 krb5_storage_emem.3 \
+	krb5_storage.3 krb5_storage_free.3 \
+	krb5_storage.3 krb5_storage_from_data.3 \
+	krb5_storage.3 krb5_storage_from_fd.3 \
+	krb5_storage.3 krb5_storage_from_mem.3 \
+	krb5_storage.3 krb5_storage_from_readonly_mem.3 \
+	krb5_storage.3 krb5_storage_get_byteorder.3 \
+	krb5_storage.3 krb5_storage_get_eof_code.3 \
+	krb5_storage.3 krb5_storage_is_flags.3 \
+	krb5_storage.3 krb5_storage_read.3 \
+	krb5_storage.3 krb5_storage_seek.3 \
+	krb5_storage.3 krb5_storage_set_byteorder.3 \
+	krb5_storage.3 krb5_storage_set_eof_code.3 \
+	krb5_storage.3 krb5_storage_set_flags.3 \
+	krb5_storage.3 krb5_storage_set_max_alloc.3 \
+	krb5_storage.3 krb5_storage_to_data.3 \
+	krb5_storage.3 krb5_storage_truncate.3 \
+	krb5_storage.3 krb5_storage_write.3 \
+	krb5_storage.3 krb5_store_address.3 \
+	krb5_storage.3 krb5_store_addrs.3 \
+	krb5_storage.3 krb5_store_authdata.3 \
+	krb5_storage.3 krb5_store_creds.3 \
+	krb5_storage.3 krb5_store_creds_tag.3 \
+	krb5_storage.3 krb5_store_data.3 \
+	krb5_storage.3 krb5_store_int16.3 \
+	krb5_storage.3 krb5_store_int32.3 \
+	krb5_storage.3 krb5_store_int8.3 \
+	krb5_storage.3 krb5_store_keyblock.3 \
+	krb5_storage.3 krb5_store_principal.3 \
+	krb5_storage.3 krb5_store_string.3 \
+	krb5_storage.3 krb5_store_stringz.3 \
+	krb5_storage.3 krb5_store_times.3 \
+	krb5_storage.3 krb5_store_uint16.3 \
+	krb5_storage.3 krb5_store_uint32.3 \
+	krb5_storage.3 krb5_store_uint8.3 \
+	krb5_support.3 krb5_acl_match_string.3 \
+	krb5_support.3 krb5_config_file_free.3 \
+	krb5_support.3 krb5_config_free_strings.3 \
+	krb5_support.3 krb5_config_get_bool.3 \
+	krb5_support.3 krb5_config_get_bool_default.3 \
+	krb5_support.3 krb5_config_get_list.3 \
+	krb5_support.3 krb5_config_get_string.3 \
+	krb5_support.3 krb5_config_get_string_default.3 \
+	krb5_support.3 krb5_config_get_strings.3 \
+	krb5_support.3 krb5_config_get_time.3 \
+	krb5_support.3 krb5_config_get_time_default.3 \
+	krb5_support.3 krb5_config_parse_file_multi.3 \
+	krb5_support.3 krb5_config_vget_bool.3 \
+	krb5_support.3 krb5_config_vget_bool_default.3 \
+	krb5_support.3 krb5_config_vget_list.3 \
+	krb5_support.3 krb5_config_vget_string.3 \
+	krb5_support.3 krb5_config_vget_string_default.3 \
+	krb5_support.3 krb5_config_vget_strings.3 \
+	krb5_support.3 krb5_config_vget_time.3 \
+	krb5_support.3 krb5_config_vget_time_default.3 \
+	krb5_support.3 krb5_expand_hostname.3 \
+	krb5_support.3 krb5_expand_hostname_realms.3 \
+	krb5_support.3 krb5_free_host_realm.3 \
+	krb5_support.3 krb5_kuserok.3 \
+	krb5_support.3 krb5_plugin_register.3 \
+	krb5_ticket.3 krb5_ticket_get_flags.3 \
 	krb5_timeofday.3 krb5_us_timeofday.3 \
+	krb5_v4compat.3 krb524_convert_creds_kdc_ccache.3 \
 	krb5_verify_user.3 krb5_verify_opt_init.3 \
 	krb5_verify_user.3 krb5_verify_opt_set_flags.3 \
 	krb5_verify_user.3 krb5_verify_opt_set_keytab.3 \
 	krb5_verify_user.3 krb5_verify_opt_set_secure.3 \
 	krb5_verify_user.3 krb5_verify_opt_set_service.3 \
 	krb5_verify_user.3 krb5_verify_user_lrealm.3 \
-	krb5_verify_user.3 krb5_verify_user_opt.3 \
-	krb5_warn.3 krb5_err.3 \
-	krb5_warn.3 krb5_errx.3 \
-	krb5_warn.3 krb5_set_warn_dest.3 \
-	krb5_warn.3 krb5_verr.3 \
-	krb5_warn.3 krb5_verrx.3 \
-	krb5_warn.3 krb5_vwarn.3 \
-	krb5_warn.3 krb5_vwarnx.3 \
-	krb5_warn.3 krb5_warnx.3
+	krb5_verify_user.3 krb5_verify_user_opt.3
=20
 SRCS=3D	acache.c \
 	acl.c \
@@ -280,19 +514,32 @@
 	changepw.c \
 	codec.c \
 	config_file.c \
-	config_file_netinfo.c \
 	constants.c \
 	context.c \
 	convert_creds.c \
 	copy_host_realm.c \
 	crc.c \
 	creds.c \
+	crypto-aes.c \
+	crypto-algs.c \
+	crypto-arcfour.c \
+	crypto-des-common.c \
+	crypto-des.c \
+	crypto-des3.c \
+	crypto-evp.c \
+	crypto-null.c \
+	crypto-pk.c \
+	crypto-rand.c \
 	crypto.c \
+	crypto.h \
 	data.c \
+	deprecated.c \
 	digest.c \
+	doxygen.c \
 	eai_to_heim_errno.c \
 	error_string.c \
 	expand_hostname.c \
+	expand_path.c \
 	fcache.c \
 	free.c \
 	free_host_realm.c \
@@ -305,42 +552,38 @@
 	get_for_creds.c \
 	get_host_realm.c \
 	get_in_tkt.c \
-	get_in_tkt_pw.c \
-	get_in_tkt_with_keytab.c \
-	get_in_tkt_with_skey.c \
 	get_port.c \
-	heim_threads.h \
 	init_creds.c \
 	init_creds_pw.c \
 	kcm.c \
-	kcm.h \
 	keyblock.c \
 	keytab.c \
 	keytab_any.c \
 	keytab_file.c \
 	keytab_keyfile.c \
-	keytab_krb4.c \
 	keytab_memory.c \
+	krb5-v4compat.h \
 	krb5_locl.h \
-	krb5-v4compat.h \
 	krbhst.c \
 	kuserok.c \
 	log.c \
 	mcache.c \
 	misc.c \
+	mit_glue.c \
 	mk_error.c \
 	mk_priv.c \
 	mk_rep.c \
 	mk_req.c \
 	mk_req_ext.c \
 	mk_safe.c \
-	mit_glue.c \
 	n-fold.c \
 	net_read.c \
 	net_write.c \
 	pac.c \
 	padata.c \
+	pcache.c \
 	pkinit.c \
+	plugin.c \
 	principal.c \
 	prog_setup.c \
 	prompter_posix.c \
@@ -353,20 +596,24 @@
 	read_message.c \
 	recvauth.c \
 	replay.c \
+	salt-aes.c \
+	salt-arcfour.c \
+	salt-des.c \
+	salt-des3.c \
+	salt.c \
+	scache.c \
 	send_to_kdc.c \
 	sendauth.c \
 	set_default_realm.c \
 	sock_principal.c \
+	store-int.c \
 	store.c \
-	store-int.h \
 	store_emem.c \
 	store_fd.c \
 	store_mem.c \
-	plugin.c \
 	ticket.c \
 	time.c \
 	transited.c \
-	v4_glue.c \
 	verify_init.c \
 	verify_user.c \
 	version.c \
@@ -375,8 +622,6 @@
=20
 SRCS+=3D	heim_err.c \
 	heim_err.h \
-	hx509_err.c \
-	hx509_err.h \
 	k524_err.c \
 	k524_err.h \
 	krb5_err.c \
@@ -384,8 +629,12 @@
 	krb_err.c \
 	krb_err.h
=20
-CFLAGS+=3D-I${KRB5DIR}/lib/krb5 -I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/rok=
en -I.
+CFLAGS+=3D	-I${KRB5DIR}/lib/krb5 \
+		-I${KRB5DIR}/lib/asn1 \
+		-I${KRB5DIR}/lib/roken \
+		-I${KRB5DIR}/lib/ipc \
+		-I${KRB5DIR}/base -I.
=20
 .include <bsd.lib.mk>
=20
-.PATH: ${KRB5DIR}/lib/krb5 ${KRB5DIR}/lib/asn1 ${.CURDIR}/../../include
+.PATH: ${KRB5DIR}/lib/krb5 ${KRB5DIR}/lib/asn1 ${KRB5DIR}/include ${.CURDI=
R}/../../include ${KRB5DIR}/doc/doxyout/krb5/man/man3/
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libroken/Makefile
--- a/head/kerberos5/lib/libroken/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libroken/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,71 +1,91 @@
-# $FreeBSD: head/kerberos5/lib/libroken/Makefile 225778 2011-09-27 07:14:1=
2Z stas $
+# $FreeBSD: head/kerberos5/lib/libroken/Makefile 233294 2012-03-22 08:48:4=
2Z stas $
=20
 LIB=3D	roken
 LDADD=3D	-lcrypt
 DPADD=3D	${LIBCRYPT}
-INCS=3D	roken.h roken-common.h
+VERSION_MAP=3D	${KRB5DIR}/lib/roken/version-script.map
+INCS=3D	roken.h \
+	roken-common.h \
+	base64.h \
+	getarg.h \
+	hex.h \
+	parse_bytes.h \
+	parse_time.h \
+	parse_units.h \
+	resolve.h \
+	rtbl.h \
+	xdbm.h
=20
 SRCS=3D	base64.c \
-	bswap.c \
-	concat.c \
 	copyhostent.c \
-	dumpdata.c \
 	ecalloc.c \
 	emalloc.c \
+	erealloc.c \
+	estrdup.c \
+	strlwr.c \
+	strsep_copy.c \
+	strupr.c \
+	bswap.c \
+	cloexec.c \
+	concat.c \
+	ct.c \
+	doxygen.c \
+	dumpdata.c \
 	environment.c \
 	eread.c \
-	erealloc.c \
 	esetenv.c \
-	estrdup.c \
 	ewrite.c \
 	get_default_username.c \
 	get_window_size.c \
 	getaddrinfo_hostspec.c \
 	getarg.c \
 	getnameinfo_verified.c \
+	getprogname.c \
+	h_errno.c \
 	hex.c \
 	hostent_find_fqdn.c \
 	issuid.c \
 	k_getpwnam.c \
 	k_getpwuid.c \
 	mini_inetd.c \
-	ndbm_wrap.c \
 	net_read.c \
 	net_write.c \
 	parse_bytes.c \
 	parse_time.c \
 	parse_units.c \
+	qsort.c \
+	rand.c \
+	realloc.c \
 	resolve.c \
 	roken.h \
 	roken_gethostby.c \
 	rtbl.c \
+	setprogname.c \
+	signal.c \
 	simple_exec.c \
 	snprintf.c \
 	socket.c \
 	strcollect.c \
-	strlwr.c \
-	strndup.c \
-	strnlen.c \
+	strerror_r.c \
 	strpool.c \
-	strsep_copy.c \
-	strupr.c \
 	timeval.c \
 	tm2time.c \
 	unvis.c \
 	verify.c \
 	vis.c \
 	warnerr.c \
-	write_pid.c
+	write_pid.c \
+	xfree.c
=20
+CPPFLAGS+=3D	-DBUILD_ROKEN_LIB
 CFLAGS+=3D-I${KRB5DIR}/lib/roken -I.
=20
 CLEANFILES=3D roken.h
=20
-roken.h: ../../tools/make-roken/make-roken
-	../../tools/make-roken/make-roken > ${.TARGET}
+MAKE_ROKEN=3D	make-roken
=20
-../../tools/make-roken/make-roken:
-	cd ${.CURDIR}/../../tools/make-roken && ${MAKE}
+roken.h:
+	${MAKE_ROKEN} > ${.TARGET}
=20
 .include <bsd.lib.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/lib/libvers/Makefile
--- a/head/kerberos5/lib/libvers/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/lib/libvers/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,17 +1,16 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/lib/libvers/Makefile 233294 2012-03-22 08:48:42=
Z stas $
=20
 LIB=3D	vers
 INTERNALLIB=3D
-SRCS=3D	print_version.c print_version.h
-CFLAGS+=3D-I.
+SRCS=3D	print_version.c roken.h
+CFLAGS+=3D-I. -I${KRB5DIR}/lib/roken
=20
-CLEANFILES=3D print_version.h
+CLEANFILES=3D roken.h print_version.h
=20
-print_version.h: ../../tools/make-print-version/make-print-version
-	../../tools/make-print-version/make-print-version ${.TARGET}
+MAKE_ROKEN=3D	make-roken
=20
-../../tools/make-print-version/make-print-version:
-	cd ${.CURDIR}/../../tools/make-print-version && ${MAKE}
+roken.h:
+	${MAKE_ROKEN} > ${.TARGET}
=20
 .include <bsd.lib.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/libexec/Makefile
--- a/head/kerberos5/libexec/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/libexec/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,6 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/libexec/Makefile 233294 2012-03-22 08:48:42Z st=
as $
=20
-SUBDIR=3D	ipropd-master ipropd-slave hprop hpropd kadmind kdc kpasswdd kcm
+SUBDIR=3D	digest-service ipropd-master ipropd-slave hprop hpropd kadmind k=
dc \
+	kdigest kfd kimpersonate kpasswdd kcm
=20
 .include <bsd.subdir.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/libexec/hprop/Makefile
--- a/head/kerberos5/libexec/hprop/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/libexec/hprop/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,8 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/libexec/hprop/Makefile 233294 2012-03-22 08:48:=
42Z stas $
=20
 PROG=3D	hprop
 MAN=3D	hprop.8
-SRCS=3D	hprop.c mit_dump.c v4_dump.c
+SRCS=3D	hprop.c mit_dump.c hprop.h
 CFLAGS+=3D-I${KRB5DIR}/lib/roken
 CFLAGS+=3D-I${KRB5DIR}/lib/krb5
 CFLAGS+=3D-I${KRB5DIR}/lib/asn1
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/libexec/ipropd-master/M=
akefile
--- a/head/kerberos5/libexec/ipropd-master/Makefile	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/kerberos5/libexec/ipropd-master/Makefile	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,7 +1,7 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/libexec/ipropd-master/Makefile 233294 2012-03-2=
2 08:48:42Z stas $
=20
 PROG=3D	ipropd-master
-NO_MAN=3D
+MAN=3D	iprop.8
 SRCS=3D	ipropd_common.c ipropd_master.c kadm5_err.h
 CFLAGS+=3D-I${KRB5DIR}/lib/krb5 -I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/rok=
en \
 	-I. ${LDAPCFLAGS}
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/libexec/kadmind/Makefile
--- a/head/kerberos5/libexec/kadmind/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/libexec/kadmind/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,14 +1,19 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/libexec/kadmind/Makefile 233294 2012-03-22 08:4=
8:42Z stas $
=20
 PROG=3D	kadmind
 MAN=3D	kadmind.8
-SRCS=3D	kadm_conn.c kadmind.c server.c
+SRCS=3D	rpc.c \
+	server.c \
+	kadmind.c \
+	kadmin_locl.h \
+	kadm_conn.c
+
 CFLAGS+=3D-I${KRB5DIR}/lib/krb5 -I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/rok=
en \
 	${LDAPCFLAGS}
-DPADD=3D	${LIBKADM5SRV} ${LIBHDB} ${LIBKRB5} ${LIBHX509} ${LIBROKEN} ${LIB=
VERS} \
-	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR} ${LDAPDPADD}
-LDADD=3D	-lkadm5srv -lhdb -lkrb5 -lhx509 -lroken ${LIBVERS} \
-	-lasn1 -lcrypto -lcrypt -lcom_err ${LDAPLDADD}
+DPADD=3D	${LIBKADM5SRV} ${LIBGSSAPI} ${LIBHDB} ${LIBKRB5} ${LIBROKEN} \
+	${LIBASN1} ${LIBVERS} ${LIBCRYPTO} ${LIBCRYPT} ${LDAPDPADD}
+LDADD=3D	-lkadm5srv -lgssapi -lhdb -lkrb5 -lroken \
+	-lasn1 ${LIBVERS} -lcrypto -lcrypt ${LDAPLDADD}
 LDFLAGS=3D${LDAPLDFLAGS}
=20
 .include <bsd.prog.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/libexec/kcm/Makefile
--- a/head/kerberos5/libexec/kcm/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/libexec/kcm/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/libexec/kcm/Makefile 233294 2012-03-22 08:48:42=
Z stas $
=20
 PROG=3D	kcm
 MAN=3D	kcm.8
@@ -9,23 +9,23 @@
 	client.c \
 	config.c \
 	connect.c \
-	cursor.c \
 	events.c \
 	glue.c \
 	headers.h \
 	kcm_locl.h \
-	kcm_protos.h \
+	kcm-protos.h \
 	log.c \
 	main.c \
 	protocol.c \
+	sessions.c \
 	renew.c
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/krb5 -I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/rok=
en \
-	-I${KRB5DIR}/kcm ${LDAPCFLAGS}
-DPADD=3D	${LIBKRB5} ${LIBHX509} ${LIBROKEN} ${LIBVERS} \
-	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR} ${LDAPDPADD}
-LDADD=3D	-lkrb5 -lhx509 -lroken ${LIBVERS} \
-	-lasn1 -lcrypto -lcrypt -lcom_err ${LDAPLDADD}
+	-I${KRB5DIR}/kcm -I${KRB5DIR}/lib/ipc ${LDAPCFLAGS}
+DPADD=3D	${LIBHDB} ${LIBKRB5} ${LIBROKEN} ${LIBASN1} ${LIBHEIMNTLM} \
+	${LIBHEIMIPCS} ${LIBCRYPTO} ${LIBCRYPT} ${LIBVERS} ${LDAPDPADD}
+LDADD=3D	-lhdb -lkrb5 -lroken -lasn1 -lheimntlm ${LIBHEIMIPCS} \
+	-lcrypto -lcrypt ${LIBVERS} ${LDAPLDADD}
 LDFLAGS=3D${LDAPLDFLAGS}
=20
 .include <bsd.prog.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/libexec/kdc/Makefile
--- a/head/kerberos5/libexec/kdc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/libexec/kdc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,33 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/libexec/kdc/Makefile 233294 2012-03-22 08:48:42=
Z stas $
=20
 PROG=3D	kdc
 MAN=3D	kdc.8
=20
-SRCS=3D	524.c \
-	config.c \
+SRCS=3D	config.c \
 	connect.c \
-	default_config.c \
-	digest.c \
-	kaserver.c \
-	kerberos4.c \
-	kerberos5.c \
-	krb5tgs.c \
-	kx509.c \
-	log.c \
-	main.c \
-	misc.c \
-	pkinit.c \
-	process.c \
-	set_dbinfo.c \
-	windc.c
+	announce.c \
+	main.c
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/krb5 -I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/rok=
en \
 	-I${KRB5DIR}/kdc ${LDAPCFLAGS}
-DPADD=3D	${LIBHDB} ${LIBKRB5} ${LIBHX509} ${LIBHEIMNTLM} ${LIBROKEN} ${LIB=
VERS} \
-	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR} ${LDAPDPADD}
-LDADD=3D	-lhdb -lkrb5 -lhx509 -lheimntlm -lroken ${LIBVERS} \
-	-lasn1 -lcrypto -lcrypt -lcom_err ${LDAPLDADD}
-LDFLAGS=3D${LDAPLDFLAGS}
+DPADD=3D	${LIBKDC} ${LIBHDB} ${LIBKRB5} ${LIBROKEN} ${LIBASN1} \
+	${LIBCRYPTO} ${LIBCRYPT} ${LIBVERS}
+LDADD=3D	-lkdc -lhdb -lkrb5 -lroken -lasn1 -lcrypto -lcrypt ${LIBVERS}
=20
 .include <bsd.prog.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/tools/Makefile
--- a/head/kerberos5/tools/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/tools/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/tools/Makefile 233294 2012-03-22 08:48:42Z stas=
 $
=20
-SUBDIR=3D	make-print-version make-roken asn1_compile slc
+SUBDIR=3D	make-roken asn1_compile slc
=20
 .include <bsd.subdir.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/tools/Makefile.inc
--- a/head/kerberos5/tools/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/tools/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/tools/Makefile.inc 233294 2012-03-22 08:48:42Z =
stas $
=20
-realinstall:
+BINDIR?=3D	/usr/bin
=20
 .include "../Makefile.inc"
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/tools/asn1_compile/Make=
file
--- a/head/kerberos5/tools/asn1_compile/Makefile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/kerberos5/tools/asn1_compile/Makefile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,55 +1,41 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/tools/asn1_compile/Makefile 233294 2012-03-22 0=
8:48:42Z stas $
=20
 PROG=3D	asn1_compile
 NO_MAN=3D
+LIBROKEN_A=3D	${.OBJDIR}/../../lib/libroken/libroken.a
+LDADD=3D	${LIBROKEN_A} ${LIBVERS}
+DPADD=3D	${LIBROKEN_A} ${LIBVERS}
=20
-SRCS=3D	gen.c \
+SRCS=3D	asn1_queue.h \
+	asn1parse.y \
+	der.h \
+	gen.c \
 	gen_copy.c \
 	gen_decode.c \
 	gen_encode.c \
 	gen_free.c \
-	gen_glue-fixed.c \
+	gen_glue.c \
 	gen_length.c \
+	gen_locl.h \
 	gen_seq.c \
+	gen_template.c \
 	hash.c \
-	ecalloc.c \
-	emalloc.c \
-	estrdup.c \
+	hash.h \
+	lex.l \
+	lex.h \
 	main.c \
+	asn1-template.h \
+	roken.h \
 	symbol.c \
-	getarg.c \
-	warnerr.c \
-	lex.l \
-	parse.y \
-	print_version.c \
-	print_version.h \
-	roken.h \
-	get_window_size.c \
-	strupr.c
+	symbol.h
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/roken -I${KRB5DIR}/lib/asn1 -I.
=20
-CLEANFILES=3D print_version.h roken.h
+CLEANFILES=3D roken.h
=20
-print_version.h: ../make-print-version/make-print-version
-	../make-print-version/make-print-version ${.TARGET}
-
-../make-print-version/make-print-version: .PHONY
-	cd ${.CURDIR}/../make-print-version && ${MAKE}
-
-roken.h: ../make-roken/make-roken
-	../make-roken/make-roken > ${.TARGET}
-
-../make-roken/make-roken: .PHONY
-	cd ${.CURDIR}/../make-roken && ${MAKE}
-
-gen_glue-fixed.c: gen_glue.c
-	 sed -e '96s/"/"#ifdef __PARSE_UNITS_H__\\n/;'\
-	     -e '96s/",/\\n#endif\\n",/' ${.ALLSRC} > ${.TARGET}
-CLEANFILES+=3D gen_glue-fixed.c
+roken.h:
+	 make-roken > ${.TARGET}
=20
 .include <bsd.prog.mk>
=20
-# There are two print_version.c's, the one we need is in ${KRB5DIR}/lib/ve=
rs,
-# so the order of paths is important here.
-.PATH: ${KRB5DIR}/lib/vers ${KRB5DIR}/lib/roken ${KRB5DIR}/lib/asn1
+.PATH: ${KRB5DIR}/lib/asn1
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/tools/make-roken/Makefi=
le
--- a/head/kerberos5/tools/make-roken/Makefile	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/kerberos5/tools/make-roken/Makefile	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,11 +1,13 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/tools/make-roken/Makefile 233294 2012-03-22 08:=
48:42Z stas $
=20
 PROG=3D	make-roken
 NO_MAN=3D
=20
 CLEANFILES=3D make-roken.c
=20
-.include <bsd.prog.mk>
+.include "../Makefile.inc"
=20
 make-roken.c: ${KRB5DIR}/lib/roken/roken.awk ${KRB5DIR}/lib/roken/roken.h.=
in
 	awk -f ${.ALLSRC} > ${.TARGET}
+
+.include <bsd.prog.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/tools/slc/Makefile
--- a/head/kerberos5/tools/slc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/tools/slc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,35 +1,24 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/tools/slc/Makefile 233294 2012-03-22 08:48:42Z =
stas $
=20
 PROG=3D	slc
+LIBROKEN_A=3D     ${.OBJDIR}/../../lib/libroken/libroken.a
+LDADD=3D  ${LIBROKEN_A} ${LIBVERS}
+DPADD=3D  ${LIBROKEN_A} ${LIBVERS}
 NO_MAN=3D
=20
-SRCS=3D	get_window_size.c \
-	getarg.c \
-	roken.h \
+SRCS=3D	roken.h \
 	slc-gram.y \
-	slc-lex.l \
-	slc.h \
-	strupr.c
-
-SRCS+=3D	print_version.c \
-	print_version.h
+	slc-lex.l
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/roken -I${KRB5DIR}/lib/sl -I${KRB5DIR}/lib/vers=
 -I.
=20
-CLEANFILES=3D print_version.h roken.h
+CLEANFILES=3D roken.h
=20
-print_version.h: ../make-print-version/make-print-version
-	../make-print-version/make-print-version ${.TARGET}
+roken.h:
+	make-roken > ${.TARGET}
=20
-../make-print-version/make-print-version: .PHONY
-	cd ${.CURDIR}/../make-print-version && ${MAKE}
-
-roken.h: ../make-roken/make-roken
-	../make-roken/make-roken > ${.TARGET}
-
-../make-roken/make-roken: .PHONY
-	cd ${.CURDIR}/../make-roken && ${MAKE}
+#	${.OBJDIR}/../make-roken/make-roken > ${.TARGET}
=20
 .include <bsd.prog.mk>
=20
-.PATH: ${KRB5DIR}/lib/vers ${KRB5DIR}/lib/roken ${KRB5DIR}/lib/sl
+.PATH: ${KRB5DIR}/lib/roken ${KRB5DIR}/lib/sl
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.bin/Makefile
--- a/head/kerberos5/usr.bin/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/usr.bin/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.bin/Makefile 233294 2012-03-22 08:48:42Z st=
as $
=20
-SUBDIR=3D	kadmin kdestroy kinit klist kpasswd krb5-config ksu \
-	verify_krb5_conf
+SUBDIR=3D	hxtool kadmin kcc kdestroy kgetcred kf kinit kpasswd krb5-config=
 ksu \
+	string2key verify_krb5_conf
=20
 .include <bsd.subdir.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.bin/kadmin/Makefile
--- a/head/kerberos5/usr.bin/kadmin/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/usr.bin/kadmin/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/kerberos5/usr.bin/kadmin/Makefile 228113 2011-11-29 03:49=
:03Z fjoe $
+# $FreeBSD: head/kerberos5/usr.bin/kadmin/Makefile 233294 2012-03-22 08:48=
:42Z stas $
=20
 PROG=3D	kadmin
 MAN=3D	kadmin.8
@@ -38,11 +38,8 @@
=20
 .include <bsd.prog.mk>
=20
-kadmin-commands.c kadmin-commands.h: ${KRB5DIR}/kadmin/kadmin-commands.in =
../../tools/slc/slc
-	../../tools/slc/slc ${.ALLSRC:M*.in}
-
-../../tools/slc/slc:
-	cd ${.CURDIR}/../../tools/slc && ${MAKE}
+kadmin-commands.c kadmin-commands.h: ${KRB5DIR}/kadmin/kadmin-commands.in
+	slc ${.ALLSRC:M*.in}
=20
 .PATH: ${KRB5DIR}/kadmin
=20
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.bin/kdestroy/Makefi=
le
--- a/head/kerberos5/usr.bin/kdestroy/Makefile	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/kerberos5/usr.bin/kdestroy/Makefile	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,11 +1,12 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.bin/kdestroy/Makefile 233294 2012-03-22 08:=
48:42Z stas $
=20
 PROG=3D	kdestroy
 CFLAGS+=3D-I${KRB5DIR}/lib/roken
-DPADD=3D	${LIBKAFS5} ${LIBKRB5} ${LIBHX509} ${LIBROKEN} ${LIBVERS} \
-	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR}
-LDADD=3D	-lkafs5 -lkrb5 -lhx509 -lroken ${LIBVERS} \
-	-lasn1 -lcrypto -lcrypt -lcom_err
+DPADD=3D	${LIBKAFS5} ${LIBKRB5} ${LIBHEIMNTLM} ${LIBROKEN} ${LIBVERS} \
+	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT}
+LDADD=3D	-lkafs5 -lkrb5 -lheimntlm -lroken ${LIBVERS} \
+	-lasn1 -lcrypto -lcrypt
+MAN=3D	kdestroy.1
=20
 .include <bsd.prog.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.bin/kinit/Makefile
--- a/head/kerberos5/usr.bin/kinit/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/usr.bin/kinit/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,10 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.bin/kinit/Makefile 233294 2012-03-22 08:48:=
42Z stas $
=20
 PROG=3D	kinit
 CFLAGS+=3D-I${KRB5DIR}/lib/roken
-DPADD=3D	${LIBKAFS5} ${LIBKRB5} ${LIBHX509} ${LIBHEIMNTLM} ${LIBROKEN} ${L=
IBVERS} \
-	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR}
-LDADD=3D	-lkafs5 -lkrb5 -lhx509 -lheimntlm -lroken ${LIBVERS} \
+DPADD=3D	${LIBKAFS5} ${LIBKRB5} ${LIBHEIMNTLM} ${LIBROKEN} ${LIBVERS} \
+	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT}
+LDADD=3D	-lkafs5 -lkrb5 -lheimntlm -lroken ${LIBVERS} \
 	-lasn1 -lcrypto -lcrypt -lcom_err
=20
 .include <bsd.prog.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.bin/krb5-config/Mak=
efile
--- a/head/kerberos5/usr.bin/krb5-config/Makefile	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/kerberos5/usr.bin/krb5-config/Makefile	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.bin/krb5-config/Makefile 233294 2012-03-22 =
08:48:42Z stas $
=20
 SCRIPTS=3Dkrb5-config
 MAN=3D	krb5-config.1
@@ -18,6 +18,7 @@
 	    -e "s, at LIB_pkinit\@,-lhx509,g" \
 	    -e "s, at LIB_dlopen\@,,g" \
 	    -e "s, at LIB_door_create\@,,g" \
+	    -e "s, at PTHREAD_LIBADD\@,-pthread,g" \
 	    -e "s, at LIBS\@,,g" \
 	    -e "s, at INCLUDE_hcrypto@,,g" \
 	    ${.ALLSRC} > ${.TARGET}
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.sbin/Makefile
--- a/head/kerberos5/usr.sbin/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/usr.sbin/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.sbin/Makefile 233294 2012-03-22 08:48:42Z s=
tas $
=20
-SUBDIR=3D	kstash ktutil
+SUBDIR=3D	iprop-log kstash ktutil
=20
 .include <bsd.subdir.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.sbin/kstash/Makefile
--- a/head/kerberos5/usr.sbin/kstash/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/usr.sbin/kstash/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,13 +1,13 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.sbin/kstash/Makefile 233294 2012-03-22 08:4=
8:42Z stas $
=20
 PROG=3D	kstash
 MAN=3D	kstash.8
 CFLAGS+=3D-I${KRB5DIR}/lib/asn1 -I${KRB5DIR}/lib/krb5 -I${KRB5DIR}/lib/rok=
en \
 	-I${KRB5DIR}/kdc ${LDAPCFLAGS}
-DPADD=3D	${LIBHDB} ${LIBKRB5} ${LIBHX509} ${LIBROKEN} ${LIBVERS} \
-	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR} ${LDAPDPADD}
-LDADD=3D	-lhdb -lkrb5 -lhx509 -lroken ${LIBVERS} \
-	-lasn1 -lcrypto -lcrypt -lcom_err ${LDAPLDADD}
+DPADD=3D	${LIBHDB} ${LIBKRB5} ${LIBROKEN} ${LIBVERS} \
+	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LDAPDPADD}
+LDADD=3D	-lhdb -lkrb5 -lroken ${LIBVERS} \
+	-lasn1 -lcrypto -lcrypt ${LDAPLDADD}
 LDFLAGS=3D${LDAPLDFLAGS}
=20
 .include <bsd.prog.mk>
diff -r 428842767fa6 -r f2935497fa04 head/kerberos5/usr.sbin/ktutil/Makefile
--- a/head/kerberos5/usr.sbin/ktutil/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/kerberos5/usr.sbin/ktutil/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/kerberos5/usr.sbin/ktutil/Makefile 228113 2011-11-29 03:4=
9:03Z fjoe $
+# $FreeBSD: head/kerberos5/usr.sbin/ktutil/Makefile 233294 2012-03-22 08:4=
8:42Z stas $
=20
 PROG=3D	ktutil
 MAN=3D	ktutil.8
@@ -6,8 +6,10 @@
 SRCS=3D	add.c \
 	change.c \
 	copy.c \
+	destroy.c \
 	get.c \
 	ktutil.c \
+	ktutil_locl.h \
 	ktutil-commands.c \
 	ktutil-commands.h \
 	list.c \
@@ -16,19 +18,14 @@
 	rename.c
=20
 CFLAGS+=3D-I${KRB5DIR}/lib/roken -I${KRB5DIR}/lib/sl -I.
-DPADD=3D	${LIBKADM5CLNT} ${LIBKRB5} ${LIBHX509} ${LIBSL} ${LIBROKEN} ${LIB=
VERS} \
-	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR} \
-	${LIBEDIT} ${LIBNCURSES}
-LDADD=3D	-lkadm5clnt -lkrb5 -lhx509 ${LIBSL} -lroken ${LIBVERS} \
-	-lasn1 -lcrypto -lcrypt -lcom_err \
-	-ledit -lncurses
+DPADD=3D	${LIBKADM5CLNT} ${LIBKRB5} ${LIBSL} ${LIBROKEN} ${LIBVERS} \
+	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBEDIT}
+LDADD=3D	-lkadm5clnt -lkrb5 ${LIBSL} -lroken ${LIBVERS} \
+	-lasn1 -lcrypto -lcrypt -ledit
=20
 .include <bsd.prog.mk>
=20
-ktutil-commands.c ktutil-commands.h: ${KRB5DIR}/admin/ktutil-commands.in .=
./../tools/slc/slc
-	../../tools/slc/slc ${.ALLSRC:M*.in}
-
-../../tools/slc/slc:
-	cd ${.CURDIR}/../../tools/slc && ${MAKE}
+ktutil-commands.c ktutil-commands.h: ${KRB5DIR}/admin/ktutil-commands.in
+	slc ${.ALLSRC:M*.in}
=20
 .PATH: ${KRB5DIR}/admin
diff -r 428842767fa6 -r f2935497fa04 head/lib/Makefile
--- a/head/lib/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	@(#)Makefile	8.1 (Berkeley) 6/4/93
-# $FreeBSD: head/lib/Makefile 228989 2011-12-30 10:45:00Z rwatson $
+# $FreeBSD: head/lib/Makefile 233413 2012-03-24 05:18:27Z gonzo $
=20
 .include <bsd.own.mk>
=20
@@ -33,7 +33,6 @@
 	libc \
 	libbsm \
 	libauditd \
-	libcom_err \
 	libcompiler_rt \
 	libcrypt \
 	libelf \
@@ -52,6 +51,10 @@
 	${_libcxxrt} \
 	${_libcplusplus}
=20
+.if ${MK_KERBEROS_SUPPORT} !=3D "no"
+SUBDIR_ORDERED+=3D	libcom_err
+.endif
+
 SUBDIR=3D	${SUBDIR_ORDERED} \
 	libalias \
 	libarchive \
@@ -194,6 +197,11 @@
 _libsmb=3D	libsmb
 .endif
=20
+.if ${MACHINE_CPUARCH} =3D=3D "mips"
+_libproc=3D	libproc
+_librtld_db=3D	librtld_db
+.endif
+
 .if ${MACHINE_CPUARCH} =3D=3D "powerpc"
 _libsmb=3D	libsmb
 .endif
diff -r 428842767fa6 -r f2935497fa04 head/lib/bind/config.h
--- a/head/lib/bind/config.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/bind/config.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/bind/config.h 225361 2011-09-03 07:13:45Z dougb $ */
+/* $FreeBSD: head/lib/bind/config.h 233914 2012-04-05 04:29:35Z dougb $ */
=20
 /* config.h.  Generated from config.h.in by configure.  */
 /* config.h.in.  Generated from configure.in by autoheader.  */
@@ -19,7 +19,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: acconfig.h,v 1.53 2008-12-01 23:47:44 tbox Exp $ */
+/* $Id: acconfig.h,v 1.53 2008/12/01 23:47:44 tbox Exp $ */
=20
 /*! \file */
=20
@@ -397,6 +397,9 @@
    (O_NDELAY/O_NONBLOCK). */
 #define PORT_NONBLOCK O_NONBLOCK
=20
+/* The size of `void *', as computed by sizeof. */
+#define SIZEOF_VOID_P 8
+
 /* Define to 1 if you have the ANSI C header files. */
 #define STDC_HEADERS 1
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/bind/dns/code.h
--- a/head/lib/bind/dns/code.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/bind/dns/code.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-/* $FreeBSD: head/lib/bind/dns/code.h 224093 2011-07-16 11:20:54Z dougb $ =
*/
+/* $FreeBSD: head/lib/bind/dns/code.h 233914 2012-04-05 04:29:35Z dougb $ =
*/
=20
 /*
- * Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003 Internet Software Consortium.
  *
  * Permission to use, copy, modify, and distribute this software for any
diff -r 428842767fa6 -r f2935497fa04 head/lib/bind/dns/dns/enumclass.h
--- a/head/lib/bind/dns/dns/enumclass.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/bind/dns/dns/enumclass.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/lib/bind/dns/dns/enumclass.h 233914 2012-04-05 04:29:35Z=
 dougb $ */
=20
 /*
- * Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003 Internet Software Consortium.
  *
  * Permission to use, copy, modify, and distribute this software for any
diff -r 428842767fa6 -r f2935497fa04 head/lib/bind/dns/dns/enumtype.h
--- a/head/lib/bind/dns/dns/enumtype.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/bind/dns/dns/enumtype.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-/* $FreeBSD: head/lib/bind/dns/dns/enumtype.h 224093 2011-07-16 11:20:54Z =
dougb $ */
+/* $FreeBSD: head/lib/bind/dns/dns/enumtype.h 233914 2012-04-05 04:29:35Z =
dougb $ */
=20
 /*
- * Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003 Internet Software Consortium.
  *
  * Permission to use, copy, modify, and distribute this software for any
diff -r 428842767fa6 -r f2935497fa04 head/lib/bind/dns/dns/rdatastruct.h
--- a/head/lib/bind/dns/dns/rdatastruct.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/bind/dns/dns/rdatastruct.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-/* $FreeBSD: head/lib/bind/dns/dns/rdatastruct.h 224093 2011-07-16 11:20:5=
4Z dougb $ */
+/* $FreeBSD: head/lib/bind/dns/dns/rdatastruct.h 233914 2012-04-05 04:29:3=
5Z dougb $ */
=20
 /*
- * Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC")
  * Copyright (C) 1998-2003 Internet Software Consortium.
  *
  * Permission to use, copy, modify, and distribute this software for any
@@ -43,7 +43,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatastructpre.h,v 1.16 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rdatastructpre.h,v 1.16 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef DNS_RDATASTRUCT_H
 #define DNS_RDATASTRUCT_H 1
@@ -89,7 +89,7 @@
 #ifndef IN_1_A_1_H
 #define IN_1_A_1_H 1
=20
-/* $Id: a_1.h,v 1.28 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a_1.h,v 1.28 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_in_a {
 	dns_rdatacommon_t	common;
@@ -113,7 +113,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: a_1.h,v 1.5 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a_1.h,v 1.5 2007/06/19 23:47:17 tbox Exp $ */
=20
 /* by Bjorn.Victor at it.uu.se, 2005-05-07 */
 /* Based on generic/mx_15.h */
@@ -152,7 +152,7 @@
 #ifndef HS_4_A_1_H
 #define HS_4_A_1_H 1
=20
-/* $Id: a_1.h,v 1.12 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a_1.h,v 1.12 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_hs_a {
 	dns_rdatacommon_t	common;
@@ -181,7 +181,7 @@
 #ifndef GENERIC_NS_2_H
 #define GENERIC_NS_2_H 1
=20
-/* $Id: ns_2.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ns_2.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_ns {
 	dns_rdatacommon_t	common;
@@ -212,7 +212,7 @@
 #ifndef GENERIC_MD_3_H
 #define GENERIC_MD_3_H 1
=20
-/* $Id: md_3.h,v 1.28 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: md_3.h,v 1.28 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_md {
 	dns_rdatacommon_t	common;
@@ -243,7 +243,7 @@
 #ifndef GENERIC_MF_4_H
 #define GENERIC_MF_4_H 1
=20
-/* $Id: mf_4.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mf_4.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mf {
 	dns_rdatacommon_t	common;
@@ -269,7 +269,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cname_5.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: cname_5.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_CNAME_5_H
 #define GENERIC_CNAME_5_H 1
@@ -302,7 +302,7 @@
 #ifndef GENERIC_SOA_6_H
 #define GENERIC_SOA_6_H 1
=20
-/* $Id: soa_6.h,v 1.32 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: soa_6.h,v 1.32 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_soa {
 	dns_rdatacommon_t	common;
@@ -339,7 +339,7 @@
 #ifndef GENERIC_MB_7_H
 #define GENERIC_MB_7_H 1
=20
-/* $Id: mb_7.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mb_7.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mb {
 	dns_rdatacommon_t	common;
@@ -369,7 +369,7 @@
 #ifndef GENERIC_MG_8_H
 #define GENERIC_MG_8_H 1
=20
-/* $Id: mg_8.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mg_8.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mg {
 	dns_rdatacommon_t	common;
@@ -399,7 +399,7 @@
 #ifndef GENERIC_MR_9_H
 #define GENERIC_MR_9_H 1
=20
-/* $Id: mr_9.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mr_9.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mr {
 	dns_rdatacommon_t	common;
@@ -429,7 +429,7 @@
 #ifndef GENERIC_NULL_10_H
 #define GENERIC_NULL_10_H 1
=20
-/* $Id: null_10.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: null_10.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_null {
 	dns_rdatacommon_t	common;
@@ -460,7 +460,7 @@
 #ifndef IN_1_WKS_11_H
 #define IN_1_WKS_11_H 1
=20
-/* $Id: wks_11.h,v 1.22 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: wks_11.h,v 1.22 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef	struct dns_rdata_in_wks {
 	dns_rdatacommon_t	common;
@@ -493,7 +493,7 @@
 #ifndef GENERIC_PTR_12_H
 #define GENERIC_PTR_12_H 1
=20
-/* $Id: ptr_12.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ptr_12.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_ptr {
         dns_rdatacommon_t       common;
@@ -522,7 +522,7 @@
 #ifndef GENERIC_HINFO_13_H
 #define GENERIC_HINFO_13_H 1
=20
-/* $Id: hinfo_13.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: hinfo_13.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_hinfo {
 	dns_rdatacommon_t	common;
@@ -555,7 +555,7 @@
 #ifndef GENERIC_MINFO_14_H
 #define GENERIC_MINFO_14_H 1
=20
-/* $Id: minfo_14.h,v 1.27 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: minfo_14.h,v 1.27 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_minfo {
 	dns_rdatacommon_t	common;
@@ -586,7 +586,7 @@
 #ifndef GENERIC_MX_15_H
 #define GENERIC_MX_15_H 1
=20
-/* $Id: mx_15.h,v 1.29 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: mx_15.h,v 1.29 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_mx {
 	dns_rdatacommon_t	common;
@@ -617,7 +617,7 @@
 #ifndef GENERIC_TXT_16_H
 #define GENERIC_TXT_16_H 1
=20
-/* $Id: txt_16.h,v 1.28 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: txt_16.h,v 1.28 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_txt_string {
                 isc_uint8_t    length;
@@ -668,7 +668,7 @@
 #ifndef GENERIC_RP_17_H
 #define GENERIC_RP_17_H 1
=20
-/* $Id: rp_17.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rp_17.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
@@ -702,7 +702,7 @@
 #ifndef GENERIC_AFSDB_18_H
 #define GENERIC_AFSDB_18_H 1
=20
-/* $Id: afsdb_18.h,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: afsdb_18.h,v 1.20 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
@@ -736,7 +736,7 @@
 #ifndef GENERIC_X25_19_H
 #define GENERIC_X25_19_H 1
=20
-/* $Id: x25_19.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: x25_19.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
@@ -769,7 +769,7 @@
 #ifndef GENERIC_ISDN_20_H
 #define GENERIC_ISDN_20_H 1
=20
-/* $Id: isdn_20.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: isdn_20.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  * \brief Per RFC1183 */
@@ -804,7 +804,7 @@
 #ifndef GENERIC_RT_21_H
 #define GENERIC_RT_21_H 1
=20
-/* $Id: rt_21.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rt_21.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC1183 */
@@ -837,7 +837,7 @@
 #ifndef IN_1_NSAP_22_H
 #define IN_1_NSAP_22_H 1
=20
-/* $Id: nsap_22.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: nsap_22.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC1706 */
@@ -870,7 +870,7 @@
 #ifndef IN_1_NSAP_PTR_23_H
 #define IN_1_NSAP_PTR_23_H 1
=20
-/* $Id: nsap-ptr_23.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: nsap-ptr_23.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC1348.  Obsoleted in RFC 1706 - use PTR instead. */
@@ -902,7 +902,7 @@
 #ifndef GENERIC_SIG_24_H
 #define GENERIC_SIG_24_H 1
=20
-/* $Id: sig_24.h,v 1.26 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: sig_24.h,v 1.26 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC2535 */
@@ -944,7 +944,7 @@
 #ifndef GENERIC_KEY_25_H
 #define GENERIC_KEY_25_H 1
=20
-/* $Id: key_25.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: key_25.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  * \brief Per RFC2535 */
@@ -981,7 +981,7 @@
 #ifndef IN_1_PX_26_H
 #define IN_1_PX_26_H 1
=20
-/* $Id: px_26.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: px_26.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC2163 */
@@ -1015,7 +1015,7 @@
 #ifndef GENERIC_GPOS_27_H
 #define GENERIC_GPOS_27_H 1
=20
-/* $Id: gpos_27.h,v 1.17 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: gpos_27.h,v 1.17 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief per RFC1712 */
@@ -1052,7 +1052,7 @@
 #ifndef IN_1_AAAA_28_H
 #define IN_1_AAAA_28_H 1
=20
-/* $Id: aaaa_28.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: aaaa_28.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC1886 */
@@ -1083,7 +1083,7 @@
 #ifndef GENERIC_LOC_29_H
 #define GENERIC_LOC_29_H 1
=20
-/* $Id: loc_29.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: loc_29.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  * \brief Per RFC1876 */
@@ -1126,7 +1126,7 @@
 #ifndef GENERIC_NXT_30_H
 #define GENERIC_NXT_30_H 1
=20
-/* $Id: nxt_30.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: nxt_30.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief RFC2535 */
@@ -1160,7 +1160,7 @@
 #ifndef IN_1_SRV_33_H
 #define IN_1_SRV_33_H 1
=20
-/* $Id: srv_33.h,v 1.19 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: srv_33.h,v 1.19 2007/06/19 23:47:17 tbox Exp $ */
=20
 /* Reviewed: Fri Mar 17 13:01:00 PST 2000 by bwelling */
=20
@@ -1178,7 +1178,7 @@
=20
 #endif /* IN_1_SRV_33_H */
 /*
- * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
+ * Copyright (C) 2004, 2005, 2007, 2012  Internet Systems Consortium, Inc.=
 ("ISC")
  * Copyright (C) 1999-2001  Internet Software Consortium.
  *
  * Permission to use, copy, modify, and/or distribute this software for any
@@ -1197,9 +1197,9 @@
 #ifndef IN_1_NAPTR_35_H
 #define IN_1_NAPTR_35_H 1
=20
-/* $Id: naptr_35.h,v 1.23 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id$ */
=20
-/*!=20
+/*!
  *  \brief Per RFC2915 */
=20
 typedef struct dns_rdata_in_naptr {
@@ -1237,7 +1237,7 @@
 #ifndef IN_1_KX_36_H
 #define IN_1_KX_36_H 1
=20
-/* $Id: kx_36.h,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: kx_36.h,v 1.20 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC2230 */
@@ -1267,7 +1267,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: cert_37.h,v 1.20 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: cert_37.h,v 1.20 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_CERT_37_H
 #define GENERIC_CERT_37_H 1
@@ -1304,7 +1304,7 @@
 #ifndef IN_1_A6_38_H
 #define IN_1_A6_38_H 1
=20
-/* $Id: a6_38.h,v 1.24 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: a6_38.h,v 1.24 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief Per RFC2874 */
@@ -1338,7 +1338,7 @@
 #ifndef GENERIC_DNAME_39_H
 #define GENERIC_DNAME_39_H 1
=20
-/* $Id: dname_39.h,v 1.21 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dname_39.h,v 1.21 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!=20
  *  \brief per RFC2672 */
@@ -1370,7 +1370,7 @@
 #ifndef GENERIC_OPT_41_H
 #define GENERIC_OPT_41_H 1
=20
-/* $Id: opt_41.h,v 1.18 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: opt_41.h,v 1.18 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC2671 */
@@ -1426,7 +1426,7 @@
 #ifndef IN_1_APL_42_H
 #define IN_1_APL_42_H 1
=20
-/* $Id: apl_42.h,v 1.6 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: apl_42.h,v 1.6 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_apl_ent {
 	isc_boolean_t	negative;
@@ -1478,7 +1478,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ds_43.h,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ds_43.h,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_DS_43_H
 #define GENERIC_DS_43_H 1
@@ -1513,7 +1513,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: sshfp_44.h,v 1.8 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: sshfp_44.h,v 1.8 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC 4255 */
@@ -1547,7 +1547,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: ipseckey_45.h,v 1.4 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: ipseckey_45.h,v 1.4 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef GENERIC_IPSECKEY_45_H
 #define GENERIC_IPSECKEY_45_H 1
@@ -1586,7 +1586,7 @@
 #ifndef GENERIC_DNSSIG_46_H
 #define GENERIC_DNSSIG_46_H 1
=20
-/* $Id: rrsig_46.h,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rrsig_46.h,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per RFC2535 */
@@ -1627,7 +1627,7 @@
 #ifndef GENERIC_NSEC_47_H
 #define GENERIC_NSEC_47_H 1
=20
-/* $Id: nsec_47.h,v 1.10 2008-07-15 23:47:21 tbox Exp $ */
+/* $Id: nsec_47.h,v 1.10 2008/07/15 23:47:21 tbox Exp $ */
=20
 /*!
  * \brief Per RFC 3845 */
@@ -1661,7 +1661,7 @@
 #ifndef GENERIC_DNSKEY_48_H
 #define GENERIC_DNSKEY_48_H 1
=20
-/* $Id: dnskey_48.h,v 1.7 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dnskey_48.h,v 1.7 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief per RFC2535 */
@@ -1698,7 +1698,7 @@
 #ifndef IN_1_DHCID_49_H
 #define IN_1_DHCID_49_H 1
=20
-/* $Id: dhcid_49.h,v 1.5 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dhcid_49.h,v 1.5 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_in_dhcid {
 	dns_rdatacommon_t	common;
@@ -1709,7 +1709,7 @@
=20
 #endif /* IN_1_DHCID_49_H */
 /*
- * Copyright (C) 2008  Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (C) 2008, 2012  Internet Systems Consortium, Inc. ("ISC")
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -1728,7 +1728,7 @@
 #ifndef GENERIC_NSEC3_50_H
 #define GENERIC_NSEC3_50_H 1
=20
-/* $Id: nsec3_50.h,v 1.4 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id$ */
=20
 /*!
  * \brief Per RFC 5155 */
@@ -1821,7 +1821,7 @@
 #ifndef GENERIC_NSEC3PARAM_51_H
 #define GENERIC_NSEC3PARAM_51_H 1
=20
-/* $Id: nsec3param_51.h,v 1.4 2008-09-25 04:02:39 tbox Exp $ */
+/* $Id: nsec3param_51.h,v 1.4 2008/09/25 04:02:39 tbox Exp $ */
=20
 /*!
  * \brief Per RFC 5155 */
@@ -1855,7 +1855,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: hip_55.h,v 1.2 2009-02-26 06:09:19 marka Exp $ */
+/* $Id: hip_55.h,v 1.2 2009/02/26 06:09:19 marka Exp $ */
=20
 #ifndef GENERIC_HIP_5_H
 #define GENERIC_HIP_5_H 1
@@ -1906,7 +1906,7 @@
 #ifndef GENERIC_SPF_99_H
 #define GENERIC_SPF_99_H 1
=20
-/* $Id: spf_99.h,v 1.4 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: spf_99.h,v 1.4 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_spf_string {
                 isc_uint8_t    length;
@@ -1958,7 +1958,7 @@
 #ifndef GENERIC_UNSPEC_103_H
 #define GENERIC_UNSPEC_103_H 1
=20
-/* $Id: unspec_103.h,v 1.17 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: unspec_103.h,v 1.17 2007/06/19 23:47:17 tbox Exp $ */
=20
 typedef struct dns_rdata_unspec_t {
 	dns_rdatacommon_t	common;
@@ -1988,7 +1988,7 @@
 #ifndef GENERIC_TKEY_249_H
 #define GENERIC_TKEY_249_H 1
=20
-/* $Id: tkey_249.h,v 1.24 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: tkey_249.h,v 1.24 2007/06/19 23:47:17 tbox Exp $ */
=20
 /*!
  *  \brief Per draft-ietf-dnsind-tkey-00.txt */
@@ -2026,7 +2026,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: tsig_250.h,v 1.25 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: tsig_250.h,v 1.25 2007/06/19 23:47:17 tbox Exp $ */
=20
 #ifndef ANY_255_TSIG_250_H
 #define ANY_255_TSIG_250_H 1
@@ -2063,7 +2063,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: dlv_32769.h,v 1.5 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: dlv_32769.h,v 1.5 2007/06/19 23:47:17 tbox Exp $ */
=20
 /* draft-ietf-dnsext-delegation-signer-05.txt */
 #ifndef GENERIC_DLV_32769_H
@@ -2099,7 +2099,7 @@
 #ifndef GENERIC_KEYDATA_65533_H
 #define GENERIC_KEYDATA_65533_H 1
=20
-/* $Id: keydata_65533.h,v 1.2 2009-06-30 02:52:32 each Exp $ */
+/* $Id: keydata_65533.h,v 1.2 2009/06/30 02:52:32 each Exp $ */
=20
 typedef struct dns_rdata_keydata {
 	dns_rdatacommon_t	common;
@@ -2132,7 +2132,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: rdatastructsuf.h,v 1.10 2007-06-19 23:47:17 tbox Exp $ */
+/* $Id: rdatastructsuf.h,v 1.10 2007/06/19 23:47:17 tbox Exp $ */
=20
 ISC_LANG_ENDDECLS
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/bind/lwres/lwres/netdb.h
--- a/head/lib/bind/lwres/lwres/netdb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/bind/lwres/lwres/netdb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/bind/lwres/lwres/netdb.h 224093 2011-07-16 11:20:54Z=
 dougb $ */
+/* $FreeBSD: head/lib/bind/lwres/lwres/netdb.h 233914 2012-04-05 04:29:35Z=
 dougb $ */
=20
 /*
  * Copyright (C) 2004, 2005, 2007, 2009  Internet Systems Consortium, Inc.=
 ("ISC")
@@ -17,7 +17,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: netdb.h.in,v 1.41 2009-01-18 23:48:14 tbox Exp $ */
+/* $Id: netdb.h.in,v 1.41 2009/01/18 23:48:14 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/bind/lwres/lwres/platform.h
--- a/head/lib/bind/lwres/lwres/platform.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/bind/lwres/lwres/platform.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/bind/lwres/lwres/platform.h 224093 2011-07-16 11:20:=
54Z dougb $ */
+/* $FreeBSD: head/lib/bind/lwres/lwres/platform.h 233914 2012-04-05 04:29:=
35Z dougb $ */
=20
 /*
  * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC=
")
@@ -17,7 +17,7 @@
  * PERFORMANCE OF THIS SOFTWARE.
  */
=20
-/* $Id: platform.h.in,v 1.21 2007-06-19 23:47:23 tbox Exp $ */
+/* $Id: platform.h.in,v 1.21 2007/06/19 23:47:23 tbox Exp $ */
=20
 /*! \file */
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/Makefile
--- a/head/lib/clang/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/Makefile 231057 2012-02-05 23:56:22Z dim $
+# $FreeBSD: head/lib/clang/Makefile 234353 2012-04-16 21:23:25Z dim $
=20
 .include <bsd.own.mk>
=20
@@ -9,6 +9,7 @@
 	libclangbasic \
 	libclangcodegen \
 	libclangdriver \
+	libclangedit \
 	libclangfrontend \
 	libclangfrontendtool \
 	libclangindex \
@@ -22,6 +23,7 @@
 	libclangstaticanalyzerfrontend \
 	\
 	libllvmanalysis \
+	libllvmarchive \
 	libllvmasmparser \
 	libllvmasmprinter \
 	libllvmbitreader \
@@ -32,14 +34,17 @@
 	libllvminstrumentation \
 	libllvmipa \
 	libllvmipo \
+	libllvmlinker \
 	libllvmmc \
 	libllvmmcparser \
+	libllvmobject \
 	libllvmscalaropts \
 	libllvmselectiondag \
 	libllvmsupport \
 	libllvmtablegen \
 	libllvmtarget \
 	libllvmtransformutils \
+	libllvmvectorize \
 	\
 	libllvmarmasmparser \
 	libllvmarmcodegen \
@@ -47,6 +52,7 @@
 	libllvmarmdisassembler \
 	libllvmarminfo \
 	libllvmarminstprinter \
+	libllvmmipsasmparser \
 	libllvmmipscodegen \
 	libllvmmipsdesc \
 	libllvmmipsinfo \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/clang.build.mk
--- a/head/lib/clang/clang.build.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/clang.build.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/clang.build.mk 229169 2012-01-01 15:56:15Z nwhi=
tehorn $
+# $FreeBSD: head/lib/clang/clang.build.mk 234356 2012-04-16 21:36:55Z dim $
=20
 CLANG_SRCS=3D${LLVM_SRCS}/tools/clang
=20
@@ -11,8 +11,14 @@
 # LLVM is not strict aliasing safe as of 12/31/2011
 CFLAGS+=3D -fno-strict-aliasing
=20
+# Work around an issue on 32-bit PowerPC, where the clang executable can g=
et
+# too big, causing 'relocation truncated to fit' errors at link time.
+.if ${MACHINE_ARCH} =3D=3D "powerpc"
+CFLAGS+=3D-mlongcall
+.endif
+
 TARGET_ARCH?=3D	${MACHINE_ARCH}
-CFLAGS+=3D-DLLVM_HOSTTRIPLE=3D\"${TARGET_ARCH:C/amd64/x86_64/}-unknown-fre=
ebsd10.0\"
+CFLAGS+=3D-DLLVM_DEFAULT_TARGET_TRIPLE=3D\"${TARGET_ARCH:C/amd64/x86_64/}-=
unknown-freebsd10.0\"
=20
 .ifndef LLVM_REQUIRES_EH
 CXXFLAGS+=3D-fno-exceptions
@@ -82,6 +88,16 @@
 	    -gen-clang-attr-list -o ${.TARGET} \
 	    -I ${CLANG_SRCS}/include ${.ALLSRC}
=20
+AttrParsedAttrKinds.inc.h: ${CLANG_SRCS}/include/clang/Basic/Attr.td
+	${CLANG_TBLGEN} -I ${CLANG_SRCS}/include/clang/Basic ${TBLINC} \
+	    -gen-clang-attr-parsed-attr-kinds -o ${.TARGET} \
+	    -I ${CLANG_SRCS}/include ${.ALLSRC}
+
+AttrParsedAttrList.inc.h: ${CLANG_SRCS}/include/clang/Basic/Attr.td
+	${CLANG_TBLGEN} -I ${CLANG_SRCS}/include/clang/Basic ${TBLINC} \
+	    -gen-clang-attr-parsed-attr-list -o ${.TARGET} \
+	    -I ${CLANG_SRCS}/include ${.ALLSRC}
+
 AttrPCHRead.inc.h: ${CLANG_SRCS}/include/clang/Basic/Attr.td
 	${CLANG_TBLGEN} -I ${CLANG_SRCS}/include/clang/Serialization \
 	    ${TBLINC} -gen-clang-attr-pch-read -o ${.TARGET} \
@@ -97,6 +113,11 @@
 	    -gen-clang-attr-spelling-list -o ${.TARGET} \
 	    -I ${CLANG_SRCS}/include ${.ALLSRC}
=20
+AttrTemplateInstantiate.inc.h: ${CLANG_SRCS}/include/clang/Basic/Attr.td
+	${CLANG_TBLGEN} -I ${CLANG_SRCS}/include/clang/Basic ${TBLINC} \
+	    -gen-clang-attr-template-instantiate -o ${.TARGET} \
+	    -I ${CLANG_SRCS}/include ${.ALLSRC}
+
 DeclNodes.inc.h: ${CLANG_SRCS}/include/clang/Basic/DeclNodes.td
 	${CLANG_TBLGEN} -I ${CLANG_SRCS}/include/clang/AST ${TBLINC} \
 	    -gen-clang-decl-nodes -o ${.TARGET} ${.ALLSRC}
@@ -117,7 +138,7 @@
 	${CLANG_TBLGEN} -I ${CLANG_SRCS}/include/clang/Basic ${TBLINC} \
 	    -gen-clang-diags-index-name -o ${.TARGET} ${.ALLSRC}
=20
-.for hdr in AST Analysis Common Driver Frontend Lex Parse Sema
+.for hdr in AST Analysis Common Driver Frontend Lex Parse Sema Serializati=
on
 Diagnostic${hdr}Kinds.inc.h: ${CLANG_SRCS}/include/clang/Basic/Diagnostic.=
td
 	${CLANG_TBLGEN} -I ${CLANG_SRCS}/include/clang/Basic ${TBLINC} \
 	    -gen-clang-diags-defs -clang-component=3D${hdr} \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/include/Makefile
--- a/head/lib/clang/include/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/include/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,11 +1,12 @@
-# $FreeBSD: head/lib/clang/include/Makefile 221345 2011-05-02 21:04:37Z di=
m $
+# $FreeBSD: head/lib/clang/include/Makefile 234353 2012-04-16 21:23:25Z di=
m $
=20
 .PATH: ${.CURDIR}/../../../contrib/llvm/tools/clang/lib/Headers
=20
-INCSDIR=3D${INCLUDEDIR}/clang/3.0
+INCSDIR=3D${INCLUDEDIR}/clang/3.1
=20
 INCS=3D	altivec.h \
 	avxintrin.h \
+	cpuid.h \
 	emmintrin.h \
 	immintrin.h \
 	mm3dnow.h \
@@ -14,7 +15,9 @@
 	nmmintrin.h \
 	pmmintrin.h \
 	smmintrin.h \
+	stdalign.h \
 	tmmintrin.h \
+	unwind.h \
 	wmmintrin.h \
 	x86intrin.h \
 	xmmintrin.h
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/include/clang/Basic/Ver=
sion.inc
--- a/head/lib/clang/include/clang/Basic/Version.inc	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/lib/clang/include/clang/Basic/Version.inc	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,10 +1,10 @@
-/* $FreeBSD: head/lib/clang/include/clang/Basic/Version.inc 228383 2011-12=
-10 01:01:44Z dim $ */
+/* $FreeBSD: head/lib/clang/include/clang/Basic/Version.inc 234353 2012-04=
-16 21:23:25Z dim $ */
=20
-#define	CLANG_VERSION		3.0
+#define	CLANG_VERSION		3.1
 #define	CLANG_VERSION_MAJOR	3
-#define	CLANG_VERSION_MINOR	0
+#define	CLANG_VERSION_MINOR	1
=20
 #define	CLANG_VENDOR		"FreeBSD "
-#define	CLANG_VENDOR_SUFFIX	" 20111210"
+#define	CLANG_VENDOR_SUFFIX	" 20120413"
=20
-#define	SVN_REVISION		"145349"
+#define	SVN_REVISION		"154661"
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/include/llvm/Config/con=
fig.h
--- a/head/lib/clang/include/llvm/Config/config.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/lib/clang/include/llvm/Config/config.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/clang/include/llvm/Config/config.h 227636 2011-11-17=
 21:06:53Z dim $ */
+/* $FreeBSD: head/lib/clang/include/llvm/Config/config.h 234353 2012-04-16=
 21:23:25Z dim $ */
 /* include/llvm/Config/config.h.  Generated from config.h.in by configure.=
  */
 /* include/llvm/Config/config.h.in.  Generated from autoconf/configure.ac =
by autoheader.  */
=20
@@ -11,33 +11,18 @@
 /* Relative directory for resource files */
 #define CLANG_RESOURCE_DIR ""
=20
-/* 32 bit multilib directory. */
-#define CXX_INCLUDE_32BIT_DIR ""
-
-/* 64 bit multilib directory. */
-#define CXX_INCLUDE_64BIT_DIR ""
-
-/* Arch the libstdc++ headers. */
-#define CXX_INCLUDE_ARCH ""
-
-/* Directory with the libstdc++ headers. */
-#define CXX_INCLUDE_ROOT ""
-
 /* Directories clang will search for headers */
 #define C_INCLUDE_DIRS ""
=20
-/* Define if CBE is enabled for printf %a output */
-#define ENABLE_CBE_PRINTF_A 1
-
 /* Define if position independent code is enabled */
 #define ENABLE_PIC 0
=20
-/* Define if threads enabled */
-#define ENABLE_THREADS 0
-
 /* Define if timestamp information (e.g., __DATE___) is allowed */
 #define ENABLE_TIMESTAMPS 0
=20
+/* Directory where gcc is installed. */
+#define GCC_INSTALL_PREFIX ""
+
 /* Define to 1 if you have the `argz_append' function. */
 /* #undef HAVE_ARGZ_APPEND */
=20
@@ -297,6 +282,9 @@
 /* Define to 1 if you have the `powf' function. */
 #define HAVE_POWF 1
=20
+/* Define to 1 if you have the `pread' function. */
+#define HAVE_PREAD 1
+
 /* Define if libtool can extract symbol lists from object files. */
 #define HAVE_PRELOADED_SYMBOLS 1
=20
@@ -373,7 +361,7 @@
 #define HAVE_STDLIB_H 1
=20
 /* Set to 1 if the std::isinf function is found in <cmath> */
-/* #undef HAVE_STD_ISINF_IN_CMATH */
+#define HAVE_STD_ISINF_IN_CMATH 1
=20
 /* Set to 1 if the std::isnan function is found in <cmath> */
 #define HAVE_STD_ISNAN_IN_CMATH 1
@@ -545,18 +533,21 @@
 /* Installation directory for data files */
 /* #undef LLVM_DATADIR */
=20
+/* Target triple LLVM will generate code for by default */
+/* #undef LLVM_DEFAULT_TARGET_TRIPLE */
+
 /* Installation directory for documentation */
 /* #undef LLVM_DOCSDIR */
=20
+/* Define if threads enabled */
+#define LLVM_ENABLE_THREADS 0
+
 /* Installation directory for config files */
 /* #undef LLVM_ETCDIR */
=20
 /* Has gcc/MSVC atomic intrinsics */
 #define LLVM_HAS_ATOMICS 0
=20
-/* Host triple we were built on */
-/* #undef LLVM_HOSTTRIPLE */
-
 /* Installation directory for include files */
 /* #undef LLVM_INCLUDEDIR */
=20
@@ -578,6 +569,9 @@
 /* LLVM name for the native AsmPrinter init function, if available */
 #define LLVM_NATIVE_ASMPRINTER LLVMInitializeX86AsmPrinter
=20
+/* LLVM name for the native Disassembler init function, if available */
+#define LLVM_NATIVE_DISASSEMBLER LLVMInitializeX86Disassembler
+
 /* LLVM name for the native Target init function, if available */
 #define LLVM_NATIVE_TARGET LLVMInitializeX86Target
=20
@@ -623,6 +617,18 @@
 /* Installation prefix directory */
 /* #undef LLVM_PREFIX */
=20
+/* Define if we have the Intel JIT API runtime support library */
+#define LLVM_USE_INTEL_JITEVENTS 0
+
+/* Define if we have the oprofile JIT-support library */
+#define LLVM_USE_OPROFILE 0
+
+/* Major version of the LLVM API */
+#define LLVM_VERSION_MAJOR 3
+
+/* Minor version of the LLVM API */
+#define LLVM_VERSION_MINOR 1
+
 /* Define if the OS needs help to load dependent libraries for dlopen(). */
 #define LTDL_DLOPEN_DEPLIBS 1
=20
@@ -648,19 +654,19 @@
 /* #undef NEED_USCORE */
=20
 /* Define to the address where bug reports for this package should be sent=
. */
-#define PACKAGE_BUGREPORT "llvmbugs at cs.uiuc.edu"
+#define PACKAGE_BUGREPORT "http://llvm.org/bugs/"
=20
 /* Define to the full name of this package. */
-#define PACKAGE_NAME "llvm"
+#define PACKAGE_NAME "LLVM"
=20
 /* Define to the full name and version of this package. */
-#define PACKAGE_STRING "llvm 3.0"
+#define PACKAGE_STRING "LLVM 3.1svn"
=20
 /* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "-llvm-"
+#define PACKAGE_TARNAME "llvm"
=20
 /* Define to the version of this package. */
-#define PACKAGE_VERSION "3.0"
+#define PACKAGE_VERSION "3.1svn"
=20
 /* Define as the return type of signal handlers (`int' or `void'). */
 #define RETSIGTYPE void
@@ -677,9 +683,6 @@
 /* Define to 1 if your <sys/time.h> declares `struct tm'. */
 /* #undef TM_IN_SYS_TIME */
=20
-/* Define if we have the oprofile JIT-support library */
-#define USE_OPROFILE 0
-
 /* Define if use udis86 library */
 #define USE_UDIS86 0
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/include/llvm/Config/llv=
m-config.h
--- a/head/lib/clang/include/llvm/Config/llvm-config.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/lib/clang/include/llvm/Config/llvm-config.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/clang/include/llvm/Config/llvm-config.h 227636 2011-=
11-17 21:06:53Z dim $ */
+/* $FreeBSD: head/lib/clang/include/llvm/Config/llvm-config.h 234353 2012-=
04-16 21:23:25Z dim $ */
 /* include/llvm/Config/llvm-config.h.  Generated from llvm-config.h.in by =
configure.  */
 /*=3D=3D=3D-- llvm/config/llvm-config.h - llvm configure variable -------*=
- C -*-=3D=3D=3D*/
 /*                                                                        =
    */
@@ -27,18 +27,21 @@
 /* Installation directory for data files */
 /* #undef LLVM_DATADIR */
=20
+/* Target triple LLVM will generate code for by default */
+/* #undef LLVM_DEFAULT_TARGET_TRIPLE */
+
 /* Installation directory for documentation */
 /* #undef LLVM_DOCSDIR */
=20
+/* Define if threads enabled */
+#define LLVM_ENABLE_THREADS 0
+
 /* Installation directory for config files */
 /* #undef LLVM_ETCDIR */
=20
 /* Has gcc/MSVC atomic intrinsics */
 #define LLVM_HAS_ATOMICS 0
=20
-/* Host triple we were built on */
-/* #undef LLVM_HOSTTRIPLE */
-
 /* Installation directory for include files */
 /* #undef LLVM_INCLUDEDIR */
=20
@@ -60,6 +63,9 @@
 /* LLVM name for the native AsmPrinter init function, if available */
 #define LLVM_NATIVE_ASMPRINTER LLVMInitializeX86AsmPrinter
=20
+/* LLVM name for the native Disassembler init function, if available */
+#define LLVM_NATIVE_DISASSEMBLER LLVMInitializeX86Disassembler
+
 /* LLVM name for the native Target init function, if available */
 #define LLVM_NATIVE_TARGET LLVMInitializeX86Target
=20
@@ -105,4 +111,10 @@
 /* Installation prefix directory */
 /* #undef LLVM_PREFIX */
=20
+/* Major version of the LLVM API */
+#define LLVM_VERSION_MAJOR 3
+
+/* Minor version of the LLVM API */
+#define LLVM_VERSION_MINOR 1
+
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclanganalysis/Makefi=
le
--- a/head/lib/clang/libclanganalysis/Makefile	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/lib/clang/libclanganalysis/Makefile	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,15 +1,18 @@
-# $FreeBSD: head/lib/clang/libclanganalysis/Makefile 226633 2011-10-22 14:=
08:43Z dim $
+# $FreeBSD: head/lib/clang/libclanganalysis/Makefile 234353 2012-04-16 21:=
23:25Z dim $
=20
 LIB=3D	clanganalysis
=20
 SRCDIR=3D	tools/clang/lib/Analysis
-SRCS=3D	AnalysisContext.cpp \
+SRCS=3D	AnalysisDeclContext.cpp \
+	CallGraph.cpp \
 	CFG.cpp \
 	CFGReachabilityAnalysis.cpp \
 	CFGStmtMap.cpp \
 	CocoaConventions.cpp \
+	Dominators.cpp \
 	FormatString.cpp \
 	LiveVariables.cpp \
+	PostOrderCFGView.cpp \
 	PrintfFormatString.cpp \
 	ProgramPoint.cpp \
 	PseudoConstantAnalysis.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangarcmigrate/Make=
file
--- a/head/lib/clang/libclangarcmigrate/Makefile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/lib/clang/libclangarcmigrate/Makefile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangarcmigrate/Makefile 226633 2011-10-22 1=
4:08:43Z dim $
+# $FreeBSD: head/lib/clang/libclangarcmigrate/Makefile 234353 2012-04-16 2=
1:23:25Z dim $
=20
 LIB=3D	clangarcmigrate
=20
@@ -6,6 +6,7 @@
 SRCS=3D	ARCMT.cpp \
 	ARCMTActions.cpp \
 	FileRemapper.cpp \
+	ObjCMT.cpp \
 	PlistReporter.cpp \
 	TransAPIUses.cpp \
 	TransARCAssign.cpp \
@@ -14,6 +15,8 @@
 	TransEmptyStatementsAndDealloc.cpp \
 	TransformActions.cpp \
 	Transforms.cpp \
+	TransGCAttrs.cpp \
+	TransGCCalls.cpp \
 	TransProperties.cpp \
 	TransRetainReleaseDealloc.cpp \
 	TransUnbridgedCasts.cpp \
@@ -21,6 +24,7 @@
 	TransZeroOutPropsInDealloc.cpp
=20
 TGHDRS=3D	AttrList \
+	AttrParsedAttrList \
 	Attrs \
 	DeclNodes \
 	DiagnosticCommonKinds \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangast/Makefile
--- a/head/lib/clang/libclangast/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangast/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangast/Makefile 226633 2011-10-22 14:08:43=
Z dim $
+# $FreeBSD: head/lib/clang/libclangast/Makefile 234353 2012-04-16 21:23:25=
Z dim $
=20
 LIB=3D	clangast
=20
@@ -28,10 +28,12 @@
 	InheritViz.cpp \
 	ItaniumCXXABI.cpp \
 	ItaniumMangle.cpp \
+	LambdaMangleContext.cpp \
 	Mangle.cpp \
 	MicrosoftCXXABI.cpp \
 	MicrosoftMangle.cpp \
 	NestedNameSpecifier.cpp \
+	NSAPI.cpp \
 	ParentMap.cpp \
 	RecordLayout.cpp \
 	RecordLayoutBuilder.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangbasic/Makefile
--- a/head/lib/clang/libclangbasic/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangbasic/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangbasic/Makefile 226633 2011-10-22 14:08:=
43Z dim $
+# $FreeBSD: head/lib/clang/libclangbasic/Makefile 234353 2012-04-16 21:23:=
25Z dim $
=20
 LIB=3D	clangbasic
=20
@@ -11,6 +11,7 @@
 	FileSystemStatCache.cpp \
 	IdentifierTable.cpp \
 	LangOptions.cpp \
+	Module.cpp \
 	SourceLocation.cpp \
 	SourceManager.cpp \
 	TargetInfo.cpp \
@@ -29,6 +30,7 @@
 	DiagnosticLexKinds \
 	DiagnosticParseKinds \
 	DiagnosticSemaKinds \
+	DiagnosticSerializationKinds \
 	arm_neon
=20
 .include "../clang.lib.mk"
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangcodegen/Makefile
--- a/head/lib/clang/libclangcodegen/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangcodegen/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangcodegen/Makefile 226633 2011-10-22 14:0=
8:43Z dim $
+# $FreeBSD: head/lib/clang/libclangcodegen/Makefile 234353 2012-04-16 21:2=
3:25Z dim $
=20
 LIB=3D	clangcodegen
=20
@@ -31,7 +31,6 @@
 	CGRTTI.cpp \
 	CGRecordLayoutBuilder.cpp \
 	CGStmt.cpp \
-	CGTemporaries.cpp \
 	CGVTT.cpp \
 	CGVTables.cpp \
 	CodeGenAction.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangdriver/Makefile
--- a/head/lib/clang/libclangdriver/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangdriver/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/lib/clang/libclangdriver/Makefile 234353 2012-04-16 21:23=
:25Z dim $
=20
 LIB=3D	clangdriver
=20
@@ -11,7 +11,6 @@
 	Compilation.cpp \
 	Driver.cpp \
 	DriverOptions.cpp \
-	HostInfo.cpp \
 	Job.cpp \
 	OptTable.cpp \
 	Option.cpp \
@@ -20,7 +19,8 @@
 	ToolChain.cpp \
 	ToolChains.cpp \
 	Tools.cpp \
-	Types.cpp
+	Types.cpp \
+	WindowsToolChain.cpp
=20
 TGHDRS=3D	CC1AsOptions \
 	CC1Options \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangfrontend/Makefi=
le
--- a/head/lib/clang/libclangfrontend/Makefile	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/lib/clang/libclangfrontend/Makefile	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangfrontend/Makefile 226633 2011-10-22 14:=
08:43Z dim $
+# $FreeBSD: head/lib/clang/libclangfrontend/Makefile 234353 2012-04-16 21:=
23:25Z dim $
=20
 LIB=3D	clangfrontend
=20
@@ -7,10 +7,14 @@
 	ASTMerge.cpp \
 	ASTUnit.cpp \
 	CacheTokens.cpp \
+	ChainedDiagnosticConsumer.cpp \
+	ChainedIncludesSource.cpp \
 	CompilerInstance.cpp \
 	CompilerInvocation.cpp \
 	CreateInvocationFromCommandLine.cpp \
 	DependencyFile.cpp \
+	DependencyGraph.cpp \
+	DiagnosticRenderer.cpp \
 	FrontendAction.cpp \
 	FrontendActions.cpp \
 	FrontendOptions.cpp \
@@ -18,15 +22,19 @@
 	InitHeaderSearch.cpp \
 	InitPreprocessor.cpp \
 	LangStandards.cpp \
+	LayoutOverrideSource.cpp \
 	LogDiagnosticPrinter.cpp \
 	MultiplexConsumer.cpp \
 	PrintPreprocessedOutput.cpp \
+	SerializedDiagnosticPrinter.cpp \
+	TextDiagnostic.cpp \
 	TextDiagnosticBuffer.cpp \
 	TextDiagnosticPrinter.cpp \
 	VerifyDiagnosticConsumer.cpp \
 	Warnings.cpp
=20
 TGHDRS=3D	AttrList \
+	AttrParsedAttrList \
 	Attrs \
 	CC1Options \
 	DeclNodes \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangindex/Makefile
--- a/head/lib/clang/libclangindex/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangindex/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,11 +1,10 @@
-# $FreeBSD$
+# $FreeBSD: head/lib/clang/libclangindex/Makefile 234353 2012-04-16 21:23:=
25Z dim $
=20
 LIB=3D	clangindex
=20
 SRCDIR=3D	tools/clang/lib/Index
 SRCS=3D	ASTLocation.cpp \
 	Analyzer.cpp \
-	CallGraph.cpp \
 	DeclReferenceMap.cpp \
 	Entity.cpp \
 	GlobalSelector.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclanglex/Makefile
--- a/head/lib/clang/libclanglex/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclanglex/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/lib/clang/libclanglex/Makefile 234353 2012-04-16 21:23:25=
Z dim $
=20
 LIB=3D	clanglex
=20
@@ -9,7 +9,9 @@
 	LiteralSupport.cpp \
 	MacroArgs.cpp \
 	MacroInfo.cpp \
+	ModuleMap.cpp \
 	PPCaching.cpp \
+	PPCallbacks.cpp \
 	PPDirectives.cpp \
 	PPExpressions.cpp \
 	PPLexerChange.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangparse/Makefile
--- a/head/lib/clang/libclangparse/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangparse/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangparse/Makefile 226633 2011-10-22 14:08:=
43Z dim $
+# $FreeBSD: head/lib/clang/libclangparse/Makefile 234353 2012-04-16 21:23:=
25Z dim $
=20
 LIB=3D	clangparse
=20
@@ -19,6 +19,7 @@
=20
 TGHDRS=3D	AttrLateParsed \
 	AttrList \
+	AttrParsedAttrList \
 	Attrs \
 	DeclNodes \
 	DiagnosticCommonKinds \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangrewrite/Makefile
--- a/head/lib/clang/libclangrewrite/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangrewrite/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/lib/clang/libclangrewrite/Makefile 234353 2012-04-16 21:2=
3:25Z dim $
=20
 LIB=3D	clangrewrite
=20
@@ -9,6 +9,7 @@
 	HTMLPrint.cpp \
 	HTMLRewrite.cpp \
 	RewriteMacros.cpp \
+	RewriteModernObjC.cpp \
 	RewriteObjC.cpp \
 	RewriteRope.cpp \
 	RewriteTest.cpp \
@@ -16,6 +17,7 @@
 	TokenRewriter.cpp
=20
 TGHDRS=3D	AttrList \
+	AttrParsedAttrList \
 	Attrs \
 	DeclNodes \
 	DiagnosticCommonKinds \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangsema/Makefile
--- a/head/lib/clang/libclangsema/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libclangsema/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangsema/Makefile 226633 2011-10-22 14:08:4=
3Z dim $
+# $FreeBSD: head/lib/clang/libclangsema/Makefile 234353 2012-04-16 21:23:2=
5Z dim $
=20
 LIB=3D	clangsema
=20
@@ -10,7 +10,6 @@
 	DelayedDiagnostic.cpp \
 	IdentifierResolver.cpp \
 	JumpDiagnostics.cpp \
-	MultiInitializer.cpp \
 	Scope.cpp \
 	Sema.cpp \
 	SemaAccess.cpp \
@@ -19,20 +18,23 @@
 	SemaCast.cpp \
 	SemaChecking.cpp \
 	SemaCodeComplete.cpp \
+	SemaConsumer.cpp \
 	SemaDecl.cpp \
 	SemaDeclAttr.cpp \
 	SemaDeclCXX.cpp \
-	SemaExprMember.cpp \
 	SemaDeclObjC.cpp \
 	SemaExceptionSpec.cpp \
 	SemaExpr.cpp \
 	SemaExprCXX.cpp \
+	SemaExprMember.cpp \
 	SemaExprObjC.cpp \
 	SemaFixItUtils.cpp \
 	SemaInit.cpp \
+	SemaLambda.cpp \
 	SemaLookup.cpp \
 	SemaObjCProperty.cpp \
 	SemaOverload.cpp \
+	SemaPseudoObject.cpp \
 	SemaStmt.cpp \
 	SemaTemplate.cpp \
 	SemaTemplateDeduction.cpp \
@@ -43,6 +45,9 @@
 	TargetAttributesSema.cpp
=20
 TGHDRS=3D	AttrList \
+	AttrParsedAttrKinds \
+	AttrParsedAttrList \
+	AttrTemplateInstantiate \
 	Attrs \
 	DeclNodes \
 	DiagnosticASTKinds \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangserialization/M=
akefile
--- a/head/lib/clang/libclangserialization/Makefile	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/lib/clang/libclangserialization/Makefile	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangserialization/Makefile 226633 2011-10-2=
2 14:08:43Z dim $
+# $FreeBSD: head/lib/clang/libclangserialization/Makefile 234353 2012-04-1=
6 21:23:25Z dim $
=20
 LIB=3D	clangserialization
=20
@@ -10,7 +10,6 @@
 	ASTWriter.cpp \
 	ASTWriterDecl.cpp \
 	ASTWriterStmt.cpp \
-	ChainedIncludesSource.cpp \
 	GeneratePCH.cpp \
 	Module.cpp \
 	ModuleManager.cpp
@@ -18,11 +17,13 @@
 TGHDRS=3D	AttrList \
 	AttrPCHRead \
 	AttrPCHWrite \
+	AttrParsedAttrList \
 	Attrs \
 	DeclNodes \
 	DiagnosticCommonKinds \
 	DiagnosticFrontendKinds \
 	DiagnosticSemaKinds \
+	DiagnosticSerializationKinds \
 	StmtNodes
=20
 .include "../clang.lib.mk"
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangstaticanalyzerc=
heckers/Makefile
--- a/head/lib/clang/libclangstaticanalyzercheckers/Makefile	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/lib/clang/libclangstaticanalyzercheckers/Makefile	Tue Apr 17 11:=
51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libclangstaticanalyzercheckers/Makefile 226633 =
2011-10-22 14:08:43Z dim $
+# $FreeBSD: head/lib/clang/libclangstaticanalyzercheckers/Makefile 234353 =
2012-04-16 21:23:25Z dim $
=20
 LIB=3D	clangstaticanalyzercheckers
=20
@@ -9,8 +9,10 @@
 	ArrayBoundCheckerV2.cpp \
 	AttrNonNullChecker.cpp \
 	BasicObjCFoundationChecks.cpp \
+	BoolAssignmentChecker.cpp \
 	BuiltinFunctionChecker.cpp \
 	CStringChecker.cpp \
+	CStringSyntaxChecker.cpp \
 	CallAndMessageChecker.cpp \
 	CastSizeChecker.cpp \
 	CastToStructChecker.cpp \
@@ -18,13 +20,16 @@
 	CheckObjCInstMethSignature.cpp \
 	CheckSecuritySyntaxOnly.cpp \
 	CheckSizeofPointer.cpp \
+	CheckerDocumentation.cpp \
 	ChrootChecker.cpp \
 	ClangCheckers.cpp \
+	CommonBugCategories.cpp \
 	DeadStoresChecker.cpp \
 	DebugCheckers.cpp \
 	DereferenceChecker.cpp \
 	DivZeroChecker.cpp \
 	FixedAddressChecker.cpp \
+	GenericTaintChecker.cpp \
 	IdempotentOperationChecker.cpp \
 	IteratorsChecker.cpp \
 	LLVMConventionsChecker.cpp \
@@ -32,11 +37,14 @@
 	MacOSXAPIChecker.cpp \
 	MallocChecker.cpp \
 	MallocOverflowSecurityChecker.cpp \
+	MallocSizeofChecker.cpp \
 	NSAutoreleasePoolChecker.cpp \
 	NSErrorChecker.cpp \
 	NoReturnFunctionChecker.cpp \
 	OSAtomicChecker.cpp \
 	ObjCAtSyncChecker.cpp \
+	ObjCContainersASTChecker.cpp \
+	ObjCContainersChecker.cpp \
 	ObjCSelfInitChecker.cpp \
 	ObjCUnusedIVarsChecker.cpp \
 	PointerArithChecker.cpp \
@@ -47,6 +55,7 @@
 	ReturnUndefChecker.cpp \
 	StackAddrEscapeChecker.cpp \
 	StreamChecker.cpp \
+	TaintTesterChecker.cpp \
 	UndefBranchChecker.cpp \
 	UndefCapturedBlockVarChecker.cpp \
 	UndefResultChecker.cpp \
@@ -54,7 +63,8 @@
 	UndefinedAssignmentChecker.cpp \
 	UnixAPIChecker.cpp \
 	UnreachableCodeChecker.cpp \
-	VLASizeChecker.cpp
+	VLASizeChecker.cpp \
+	VirtualCallChecker.cpp
=20
 TGHDRS=3D	AttrList \
 	Attrs \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libclangstaticanalyzerc=
ore/Makefile
--- a/head/lib/clang/libclangstaticanalyzercore/Makefile	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/lib/clang/libclangstaticanalyzercore/Makefile	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,10 +1,9 @@
-# $FreeBSD: head/lib/clang/libclangstaticanalyzercore/Makefile 226633 2011=
-10-22 14:08:43Z dim $
+# $FreeBSD: head/lib/clang/libclangstaticanalyzercore/Makefile 234353 2012=
-04-16 21:23:25Z dim $
=20
 LIB=3D	clangstaticanalyzercore
=20
 SRCDIR=3D	tools/clang/lib/StaticAnalyzer/Core
-SRCS=3D	AggExprVisitor.cpp \
-	AnalysisManager.cpp \
+SRCS=3D	AnalysisManager.cpp \
 	BasicConstraintManager.cpp \
 	BasicValueFactory.cpp \
 	BlockCounter.cpp \
@@ -23,6 +22,7 @@
 	ExprEngineCXX.cpp \
 	ExprEngineCallAndReturn.cpp \
 	ExprEngineObjC.cpp \
+	FunctionSummary.cpp \
 	HTMLDiagnostics.cpp \
 	MemRegion.cpp \
 	ObjCMessage.cpp \
@@ -36,6 +36,7 @@
 	SimpleConstraintManager.cpp \
 	SimpleSValBuilder.cpp \
 	Store.cpp \
+	SubEngine.cpp \
 	SymbolManager.cpp \
 	TextPathDiagnostics.cpp
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmanalysis/Makefile
--- a/head/lib/clang/libllvmanalysis/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmanalysis/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmanalysis/Makefile 231057 2012-02-05 23:5=
6:22Z dim $
+# $FreeBSD: head/lib/clang/libllvmanalysis/Makefile 234353 2012-04-16 21:2=
3:25Z dim $
=20
 .include <bsd.own.mk>
=20
@@ -12,13 +12,15 @@
 	AliasSetTracker.cpp \
 	Analysis.cpp \
 	BasicAliasAnalysis.cpp \
+	BlockFrequencyInfo.cpp \
 	BranchProbabilityInfo.cpp \
 	CFGPrinter.cpp \
 	CaptureTracking.cpp \
+	CodeMetrics.cpp \
 	ConstantFolding.cpp \
+	DIBuilder.cpp \
 	DbgInfoPrinter.cpp \
 	DebugInfo.cpp \
-	DIBuilder.cpp \
 	DomPrinter.cpp \
 	DominanceFrontier.cpp \
 	IVUsers.cpp \
@@ -29,6 +31,7 @@
 	IntervalPartition.cpp \
 	LazyValueInfo.cpp \
 	LibCallAliasAnalysis.cpp \
+	LibCallSemantics.cpp \
 	Lint.cpp \
 	Loads.cpp \
 	LoopDependenceAnalysis.cpp \
@@ -40,6 +43,9 @@
 	ModuleDebugInfoPrinter.cpp \
 	NoAliasAnalysis.cpp \
 	PHITransAddr.cpp \
+	PathNumbering.cpp \
+	PathProfileInfo.cpp \
+	PathProfileVerifier.cpp \
 	PostDominators.cpp \
 	ProfileEstimatorPass.cpp \
 	ProfileInfo.cpp \
@@ -54,6 +60,7 @@
 	ScalarEvolutionExpander.cpp \
 	ScalarEvolutionNormalization.cpp \
 	SparsePropagation.cpp \
+	Trace.cpp \
 	TypeBasedAliasAnalysis.cpp \
 	ValueTracking.cpp
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmarmcodegen/Makef=
ile
--- a/head/lib/clang/libllvmarmcodegen/Makefile	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/lib/clang/libllvmarmcodegen/Makefile	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmarmcodegen/Makefile 226633 2011-10-22 14=
:08:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmarmcodegen/Makefile 234353 2012-04-16 21=
:23:25Z dim $
=20
 LIB=3D	llvmarmcodegen
=20
@@ -13,7 +13,6 @@
 	ARMExpandPseudoInsts.cpp \
 	ARMFastISel.cpp \
 	ARMFrameLowering.cpp \
-	ARMGlobalMerge.cpp \
 	ARMHazardRecognizer.cpp \
 	ARMISelDAGToDAG.cpp \
 	ARMISelLowering.cpp \
@@ -21,6 +20,7 @@
 	ARMJITInfo.cpp \
 	ARMLoadStoreOptimizer.cpp \
 	ARMMCInstLower.cpp \
+	ARMMachineFunctionInfo.cpp \
 	ARMRegisterInfo.cpp \
 	ARMSelectionDAGInfo.cpp \
 	ARMSubtarget.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmarmdesc/Makefile
--- a/head/lib/clang/libllvmarmdesc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmarmdesc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,10 @@
-# $FreeBSD: head/lib/clang/libllvmarmdesc/Makefile 226633 2011-10-22 14:08=
:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmarmdesc/Makefile 234353 2012-04-16 21:23=
:25Z dim $
=20
 LIB=3D	llvmarmdesc
=20
 SRCDIR=3D	lib/Target/ARM/MCTargetDesc
 SRCS=3D	ARMAsmBackend.cpp \
+	ARMELFObjectWriter.cpp \
 	ARMMachObjectWriter.cpp \
 	ARMMCAsmInfo.cpp \
 	ARMMCCodeEmitter.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmasmprinter/Makef=
ile
--- a/head/lib/clang/libllvmasmprinter/Makefile	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/lib/clang/libllvmasmprinter/Makefile	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmasmprinter/Makefile 223017 2011-06-12 18=
:01:31Z dim $
+# $FreeBSD: head/lib/clang/libllvmasmprinter/Makefile 234353 2012-04-16 21=
:23:25Z dim $
=20
 LIB=3D	llvmasmprinter
=20
@@ -8,6 +8,7 @@
 	AsmPrinterDwarf.cpp \
 	AsmPrinterInlineAsm.cpp \
 	DIE.cpp \
+	DwarfAccelTable.cpp \
 	DwarfCFIException.cpp \
 	DwarfCompileUnit.cpp \
 	DwarfDebug.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmcodegen/Makefile
--- a/head/lib/clang/libllvmcodegen/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmcodegen/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmcodegen/Makefile 226633 2011-10-22 14:08=
:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmcodegen/Makefile 234353 2012-04-16 21:23=
:25Z dim $
=20
 LIB=3D	llvmcodegen
=20
@@ -13,9 +13,8 @@
 	CodePlacementOpt.cpp \
 	CriticalAntiDepBreaker.cpp \
 	DeadMachineInstructionElim.cpp \
+	DFAPacketizer.cpp \
 	DwarfEHPrepare.cpp \
-	ELFCodeEmitter.cpp \
-	ELFWriter.cpp \
 	EdgeBundles.cpp \
 	ExecutionDepsFix.cpp \
 	ExpandISelPseudos.cpp \
@@ -27,6 +26,7 @@
 	InlineSpiller.cpp \
 	InterferenceCache.cpp \
 	IntrinsicLowering.cpp \
+	JITCodeEmitter.cpp \
 	LLVMTargetMachine.cpp \
 	LatencyPriorityQueue.cpp \
 	LexicalScopes.cpp \
@@ -40,7 +40,11 @@
 	LiveRangeEdit.cpp \
 	LocalStackSlotAllocation.cpp \
 	MachineBasicBlock.cpp \
+	MachineBlockFrequencyInfo.cpp \
+	MachineBlockPlacement.cpp \
 	MachineBranchProbabilityInfo.cpp \
+	MachineCodeEmitter.cpp \
+	MachineCopyPropagation.cpp \
 	MachineCSE.cpp \
 	MachineDominators.cpp \
 	MachineFunction.cpp \
@@ -48,6 +52,7 @@
 	MachineFunctionPass.cpp \
 	MachineFunctionPrinterPass.cpp \
 	MachineInstr.cpp \
+	MachineInstrBundle.cpp \
 	MachineLICM.cpp \
 	MachineLoopInfo.cpp \
 	MachineLoopRanges.cpp \
@@ -56,9 +61,9 @@
 	MachinePassRegistry.cpp \
 	MachineRegisterInfo.cpp \
 	MachineSSAUpdater.cpp \
+	MachineScheduler.cpp \
 	MachineSink.cpp \
 	MachineVerifier.cpp \
-	ObjectCodeEmitter.cpp \
 	OcamlGC.cpp \
 	OptimizePHIs.cpp \
 	PHIElimination.cpp \
@@ -69,17 +74,16 @@
 	ProcessImplicitDefs.cpp \
 	PrologEpilogInserter.cpp \
 	PseudoSourceValue.cpp \
+	RegAllocBase.cpp \
 	RegAllocBasic.cpp \
 	RegAllocFast.cpp \
 	RegAllocGreedy.cpp \
-	RegAllocLinearScan.cpp \
 	RegAllocPBQP.cpp \
 	RegisterClassInfo.cpp \
 	RegisterCoalescer.cpp \
 	RegisterScavenging.cpp \
 	RenderMachineFunction.cpp \
 	ScheduleDAG.cpp \
-	ScheduleDAGEmit.cpp \
 	ScheduleDAGInstrs.cpp \
 	ScheduleDAGPrinter.cpp \
 	ScoreboardHazardRecognizer.cpp \
@@ -90,17 +94,17 @@
 	Spiller.cpp \
 	SpillPlacement.cpp \
 	SplitKit.cpp \
-	Splitter.cpp \
 	StackProtector.cpp \
 	StackSlotColoring.cpp \
 	StrongPHIElimination.cpp \
 	TailDuplication.cpp \
+	TargetFrameLoweringImpl.cpp \
 	TargetInstrInfoImpl.cpp \
 	TargetLoweringObjectFileImpl.cpp \
+	TargetOptionsImpl.cpp \
 	TwoAddressInstructionPass.cpp \
 	UnreachableBlockElim.cpp \
-	VirtRegMap.cpp \
-	VirtRegRewriter.cpp
+	VirtRegMap.cpp
=20
 TGHDRS=3D	Intrinsics
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmcore/Makefile
--- a/head/lib/clang/libllvmcore/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmcore/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmcore/Makefile 224145 2011-07-17 19:51:40=
Z dim $
+# $FreeBSD: head/lib/clang/libllvmcore/Makefile 234353 2012-04-16 21:23:25=
Z dim $
=20
 LIB=3D	llvmcore
=20
@@ -10,7 +10,6 @@
 	ConstantFold.cpp \
 	Constants.cpp \
 	Core.cpp \
-	DebugInfoProbe.cpp \
 	DebugLoc.cpp \
 	Dominators.cpp \
 	Function.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvminstrumentation/=
Makefile
--- a/head/lib/clang/libllvminstrumentation/Makefile	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/lib/clang/libllvminstrumentation/Makefile	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,15 +1,18 @@
-# $FreeBSD: head/lib/clang/libllvminstrumentation/Makefile 221345 2011-05-=
02 21:04:37Z dim $
+# $FreeBSD: head/lib/clang/libllvminstrumentation/Makefile 234353 2012-04-=
16 21:23:25Z dim $
=20
 LIB=3D	llvminstrumentation
=20
 SRCDIR=3D	lib/Transforms/Instrumentation
-SRCS=3D	EdgeProfiling.cpp \
+SRCS=3D	AddressSanitizer.cpp \
+	EdgeProfiling.cpp \
+	FunctionBlackList.cpp \
 	GCOVProfiling.cpp \
 	Instrumentation.cpp \
 	OptimalEdgeProfiling.cpp \
 	PathProfiling.cpp \
 	ProfilingUtils.cpp \
+	ThreadSanitizer.cpp
=20
-#TGHDRS=3D	Intrinsics
+TGHDRS=3D	Intrinsics
=20
 .include "../clang.lib.mk"
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmjit/Makefile
--- a/head/lib/clang/libllvmjit/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmjit/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,14 +1,11 @@
-# $FreeBSD: head/lib/clang/libllvmjit/Makefile 231057 2012-02-05 23:56:22Z=
 dim $
+# $FreeBSD: head/lib/clang/libllvmjit/Makefile 234353 2012-04-16 21:23:25Z=
 dim $
=20
 LIB=3D	llvmjit
=20
 SRCDIR=3D	lib/ExecutionEngine/JIT
-SRCS=3D	Intercept.cpp \
-	JIT.cpp \
-	JITDebugRegisterer.cpp \
+SRCS=3D	JIT.cpp \
 	JITDwarfEmitter.cpp \
 	JITEmitter.cpp \
-	JITMemoryManager.cpp \
-	OProfileJITEventListener.cpp
+	JITMemoryManager.cpp
=20
 .include "../clang.lib.mk"
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmmc/Makefile
--- a/head/lib/clang/libllvmmc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmmc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmmc/Makefile 231057 2012-02-05 23:56:22Z =
dim $
+# $FreeBSD: head/lib/clang/libllvmmc/Makefile 234353 2012-04-16 21:23:25Z =
dim $
=20
 .include <bsd.own.mk>
=20
@@ -23,7 +23,6 @@
 	MCInst.cpp \
 	MCInstPrinter.cpp \
 	MCInstrAnalysis.cpp \
-	MCLoggingStreamer.cpp \
 	MCMachOStreamer.cpp \
 	MCMachObjectTargetWriter.cpp \
 	MCNullStreamer.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmmcjit/Makefile
--- a/head/lib/clang/libllvmmcjit/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmmcjit/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,14 @@
-# $FreeBSD: head/lib/clang/libllvmmcjit/Makefile 231057 2012-02-05 23:56:2=
2Z dim $
+# $FreeBSD: head/lib/clang/libllvmmcjit/Makefile 234353 2012-04-16 21:23:2=
5Z dim $
+
+.include <bsd.own.mk>
=20
 LIB=3D	llvmmcjit
=20
 SRCDIR=3D	lib/ExecutionEngine/MCJIT
-SRCS=3D	Intercept.cpp \
-	MCJIT.cpp
+SRCS=3D	MCJIT.cpp
+
+.if ${MK_CLANG_EXTRAS} !=3D "no"
+SRCS+=3D	MCJITMemoryManager.cpp
+.endif
=20
 .include "../clang.lib.mk"
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmmipscodegen/Make=
file
--- a/head/lib/clang/libllvmmipscodegen/Makefile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/lib/clang/libllvmmipscodegen/Makefile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,9 +1,10 @@
-# $FreeBSD: head/lib/clang/libllvmmipscodegen/Makefile 228379 2011-12-09 2=
2:23:45Z dim $
+# $FreeBSD: head/lib/clang/libllvmmipscodegen/Makefile 234353 2012-04-16 2=
1:23:25Z dim $
=20
 LIB=3D	llvmmipscodegen
=20
 SRCDIR=3D	lib/Target/Mips
-SRCS=3D	MipsAsmPrinter.cpp \
+SRCS=3D	MipsAnalyzeImmediate.cpp \
+	MipsAsmPrinter.cpp \
 	MipsCodeEmitter.cpp \
 	MipsDelaySlotFiller.cpp \
 	MipsEmitGPRestore.cpp \
@@ -14,7 +15,7 @@
 	MipsInstrInfo.cpp \
 	MipsJITInfo.cpp \
 	MipsMCInstLower.cpp \
-	MipsMCSymbolRefExpr.cpp \
+	MipsMachineFunction.cpp \
 	MipsRegisterInfo.cpp \
 	MipsSelectionDAGInfo.cpp \
 	MipsSubtarget.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmmipsdesc/Makefile
--- a/head/lib/clang/libllvmmipsdesc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmmipsdesc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,15 +1,17 @@
-# $FreeBSD: head/lib/clang/libllvmmipsdesc/Makefile 226633 2011-10-22 14:0=
8:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmmipsdesc/Makefile 234353 2012-04-16 21:2=
3:25Z dim $
=20
 LIB=3D	llvmmipsdesc
=20
 SRCDIR=3D	lib/Target/Mips/MCTargetDesc
 SRCS=3D	MipsAsmBackend.cpp \
+	MipsELFObjectWriter.cpp \
 	MipsMCAsmInfo.cpp \
 	MipsMCCodeEmitter.cpp \
 	MipsMCTargetDesc.cpp
 CFLAGS+=3D -I${LLVM_SRCS}/${SRCDIR}/..
=20
 TGHDRS=3D	MipsGenInstrInfo \
+	MipsGenMCCodeEmitter \
 	MipsGenRegisterInfo \
 	MipsGenSubtargetInfo
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmpowerpccodegen/M=
akefile
--- a/head/lib/clang/libllvmpowerpccodegen/Makefile	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/lib/clang/libllvmpowerpccodegen/Makefile	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmpowerpccodegen/Makefile 226633 2011-10-2=
2 14:08:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmpowerpccodegen/Makefile 234353 2012-04-1=
6 21:23:25Z dim $
=20
 LIB=3D	llvmpowerpccodegen
=20
@@ -13,6 +13,7 @@
 	PPCInstrInfo.cpp \
 	PPCJITInfo.cpp \
 	PPCMCInstLower.cpp \
+	PPCMachineFunctionInfo.cpp \
 	PPCRegisterInfo.cpp \
 	PPCSelectionDAGInfo.cpp \
 	PPCSubtarget.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmpowerpcdesc/Make=
file
--- a/head/lib/clang/libllvmpowerpcdesc/Makefile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/lib/clang/libllvmpowerpcdesc/Makefile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmpowerpcdesc/Makefile 226633 2011-10-22 1=
4:08:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmpowerpcdesc/Makefile 234353 2012-04-16 2=
1:23:25Z dim $
=20
 LIB=3D	llvmpowerpcdesc
=20
@@ -7,7 +7,8 @@
 	PPCMCAsmInfo.cpp \
 	PPCMCCodeEmitter.cpp \
 	PPCMCTargetDesc.cpp \
-	PPCPredicates.cpp
+	PPCPredicates.cpp \
+	PPCELFObjectWriter.cpp
 CFLAGS+=3D -I${LLVM_SRCS}/${SRCDIR}/..
=20
 TGHDRS=3D	PPCGenInstrInfo \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmruntimedyld/Make=
file
--- a/head/lib/clang/libllvmruntimedyld/Makefile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/lib/clang/libllvmruntimedyld/Makefile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,9 +1,10 @@
-# $FreeBSD: head/lib/clang/libllvmruntimedyld/Makefile 231057 2012-02-05 2=
3:56:22Z dim $
+# $FreeBSD: head/lib/clang/libllvmruntimedyld/Makefile 234353 2012-04-16 2=
1:23:25Z dim $
=20
 LIB=3D	llvmruntimedyld
=20
 SRCDIR=3D	lib/ExecutionEngine/RuntimeDyld
 SRCS=3D	RuntimeDyld.cpp \
+	RuntimeDyldELF.cpp \
 	RuntimeDyldMachO.cpp
=20
 .include "../clang.lib.mk"
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmscalaropts/Makef=
ile
--- a/head/lib/clang/libllvmscalaropts/Makefile	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/lib/clang/libllvmscalaropts/Makefile	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmscalaropts/Makefile 231057 2012-02-05 23=
:56:22Z dim $
+# $FreeBSD: head/lib/clang/libllvmscalaropts/Makefile 234353 2012-04-16 21=
:23:25Z dim $
=20
 .include <bsd.own.mk>
=20
@@ -13,6 +13,7 @@
 	DCE.cpp \
 	DeadStoreElimination.cpp \
 	EarlyCSE.cpp \
+	GlobalMerge.cpp \
 	GVN.cpp \
 	IndVarSimplify.cpp \
 	JumpThreading.cpp \
@@ -23,9 +24,11 @@
 	LoopStrengthReduce.cpp \
 	LoopUnrollPass.cpp \
 	LoopUnswitch.cpp \
+	LowerAtomic.cpp \
 	MemCpyOptimizer.cpp \
 	ObjCARC.cpp \
 	Reassociate.cpp \
+	Reg2Mem.cpp \
 	SCCP.cpp \
 	ScalarReplAggregates.cpp \
 	SimplifyCFGPass.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmselectiondag/Mak=
efile
--- a/head/lib/clang/libllvmselectiondag/Makefile	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/lib/clang/libllvmselectiondag/Makefile	Tue Apr 17 11:51:51 2012 =
+0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/lib/clang/libllvmselectiondag/Makefile 234353 2012-04-16 =
21:23:25Z dim $
=20
 LIB=3D	llvmselectiondag
=20
@@ -14,12 +14,14 @@
 	LegalizeTypesGeneric.cpp \
 	LegalizeVectorOps.cpp \
 	LegalizeVectorTypes.cpp \
+	ResourcePriorityQueue.cpp \
 	ScheduleDAGFast.cpp \
-	ScheduleDAGList.cpp \
 	ScheduleDAGRRList.cpp \
 	ScheduleDAGSDNodes.cpp \
+	ScheduleDAGVLIW.cpp \
 	SelectionDAG.cpp \
 	SelectionDAGBuilder.cpp \
+	SelectionDAGDumper.cpp \
 	SelectionDAGISel.cpp \
 	SelectionDAGPrinter.cpp \
 	TargetLowering.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmsupport/Makefile
--- a/head/lib/clang/libllvmsupport/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmsupport/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmsupport/Makefile 231057 2012-02-05 23:56=
:22Z dim $
+# $FreeBSD: head/lib/clang/libllvmsupport/Makefile 234353 2012-04-16 21:23=
:25Z dim $
=20
 .include <bsd.own.mk>
=20
@@ -10,6 +10,7 @@
 	APSInt.cpp \
 	Allocator.cpp \
 	Atomic.cpp \
+	BlockFrequency.cpp \
 	BranchProbability.cpp \
 	CommandLine.cpp \
 	ConstantRange.cpp \
@@ -24,12 +25,16 @@
 	FoldingSet.cpp \
 	FormattedStream.cpp \
 	GraphWriter.cpp \
+	Hashing.cpp \
 	Host.cpp \
 	IntervalMap.cpp \
 	IntEqClasses.cpp \
+	IntrusiveRefCntPtr.cpp \
+	LockFileManager.cpp \
 	ManagedStatic.cpp \
 	Memory.cpp \
 	MemoryBuffer.cpp \
+	MemoryObject.cpp \
 	Mutex.cpp \
 	Path.cpp \
 	PathV2.cpp \
@@ -45,6 +50,7 @@
 	SmallVector.cpp \
 	SourceMgr.cpp \
 	Statistic.cpp \
+	StreamableMemoryObject.cpp \
 	StringExtras.cpp \
 	StringMap.cpp \
 	StringPool.cpp \
@@ -73,6 +79,7 @@
 SRCS+=3D	BlockFrequency.cpp \
 	BranchProbability.cpp \
 	DataExtractor.cpp \
+	DataStream.cpp \
 	Disassembler.cpp \
 	FileUtilities.cpp \
 	MemoryObject.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmtablegen/Makefile
--- a/head/lib/clang/libllvmtablegen/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmtablegen/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmtablegen/Makefile 226633 2011-10-22 14:0=
8:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmtablegen/Makefile 234353 2012-04-16 21:2=
3:25Z dim $
=20
 LIB=3D	llvmtablegen
=20
@@ -6,6 +6,7 @@
 SRCS=3D	Error.cpp \
 	Main.cpp \
 	Record.cpp \
+	TableGenAction.cpp \
 	TableGenBackend.cpp \
 	TGLexer.cpp \
 	TGParser.cpp
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmtarget/Makefile
--- a/head/lib/clang/libllvmtarget/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmtarget/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmtarget/Makefile 226633 2011-10-22 14:08:=
43Z dim $
+# $FreeBSD: head/lib/clang/libllvmtarget/Makefile 234353 2012-04-16 21:23:=
25Z dim $
=20
 LIB=3D	llvmtarget
=20
@@ -7,8 +7,9 @@
 	Target.cpp \
 	TargetData.cpp \
 	TargetELFWriterInfo.cpp \
-	TargetFrameLowering.cpp \
 	TargetInstrInfo.cpp \
+	TargetIntrinsicInfo.cpp \
+	TargetJITInfo.cpp \
 	TargetLibraryInfo.cpp \
 	TargetLoweringObjectFile.cpp \
 	TargetMachine.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmtransformutils/M=
akefile
--- a/head/lib/clang/libllvmtransformutils/Makefile	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/lib/clang/libllvmtransformutils/Makefile	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmtransformutils/Makefile 231057 2012-02-0=
5 23:56:22Z dim $
+# $FreeBSD: head/lib/clang/libllvmtransformutils/Makefile 234353 2012-04-1=
6 21:23:25Z dim $
=20
 .include <bsd.own.mk>
=20
@@ -7,11 +7,11 @@
 SRCDIR=3D	lib/Transforms/Utils
 SRCS=3D	AddrModeMatcher.cpp \
 	BasicBlockUtils.cpp \
-	BasicInliner.cpp \
 	BreakCriticalEdges.cpp \
 	BuildLibCalls.cpp \
 	CloneFunction.cpp \
 	CloneModule.cpp \
+	CmpInstAnalysis.cpp \
 	CodeExtractor.cpp \
 	DemoteRegToStack.cpp \
 	InlineFunction.cpp \
@@ -20,14 +20,17 @@
 	Local.cpp \
 	LoopSimplify.cpp \
 	LoopUnroll.cpp \
+	LoopUnrollRuntime.cpp \
 	LowerExpectIntrinsic.cpp \
 	LowerInvoke.cpp \
 	LowerSwitch.cpp \
 	Mem2Reg.cpp \
+	ModuleUtils.cpp \
 	PromoteMemoryToRegister.cpp \
 	SSAUpdater.cpp \
 	SimplifyCFG.cpp \
 	SimplifyIndVar.cpp \
+	SimplifyInstructions.cpp \
 	UnifyFunctionExitNodes.cpp \
 	ValueMapper.cpp
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmx86codegen/Makef=
ile
--- a/head/lib/clang/libllvmx86codegen/Makefile	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/lib/clang/libllvmx86codegen/Makefile	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/clang/libllvmx86codegen/Makefile 226633 2011-10-22 14=
:08:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmx86codegen/Makefile 234353 2012-04-16 21=
:23:25Z dim $
=20
 LIB=3D	llvmx86codegen
=20
@@ -15,6 +15,7 @@
 	X86InstrInfo.cpp \
 	X86JITInfo.cpp \
 	X86MCInstLower.cpp \
+	X86MachineFunctionInfo.cpp \
 	X86RegisterInfo.cpp \
 	X86SelectionDAGInfo.cpp \
 	X86Subtarget.cpp \
diff -r 428842767fa6 -r f2935497fa04 head/lib/clang/libllvmx86desc/Makefile
--- a/head/lib/clang/libllvmx86desc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/clang/libllvmx86desc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,13 +1,15 @@
-# $FreeBSD: head/lib/clang/libllvmx86desc/Makefile 226633 2011-10-22 14:08=
:43Z dim $
+# $FreeBSD: head/lib/clang/libllvmx86desc/Makefile 234353 2012-04-16 21:23=
:25Z dim $
=20
 LIB=3D	llvmx86desc
=20
 SRCDIR=3D	lib/Target/X86/MCTargetDesc
 SRCS=3D	X86AsmBackend.cpp \
+	X86ELFObjectWriter.cpp \
 	X86MachObjectWriter.cpp \
 	X86MCAsmInfo.cpp \
 	X86MCCodeEmitter.cpp \
-	X86MCTargetDesc.cpp
+	X86MCTargetDesc.cpp \
+	X86WinCOFFObjectWriter.cpp
 CFLAGS+=3D -I${LLVM_SRCS}/${SRCDIR}/..
=20
 TGHDRS=3D	X86GenInstrInfo \
diff -r 428842767fa6 -r f2935497fa04 head/lib/csu/powerpc/Makefile
--- a/head/lib/csu/powerpc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/csu/powerpc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/csu/powerpc/Makefile 232832 2012-03-11 20:04:09Z kib $
+# $FreeBSD: head/lib/csu/powerpc/Makefile 234356 2012-04-16 21:36:55Z dim $
=20
 .PATH: ${.CURDIR}/../common
=20
@@ -6,7 +6,8 @@
 OBJS=3D		${SRCS:N*.h:R:S/$/.o/g}
 OBJS+=3D		Scrt1.o gcrt1.o
 CFLAGS+=3D	-I${.CURDIR}/../common \
-		-I${.CURDIR}/../../libc/include
+		-I${.CURDIR}/../../libc/include \
+		-mlongcall
=20
 all: ${OBJS}
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/libarchive/Makefile
--- a/head/lib/libarchive/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libarchive/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/libarchive/Makefile 232153 2012-02-25 10:58:02Z mm $
+# $FreeBSD: head/lib/libarchive/Makefile 233352 2012-03-23 11:18:07Z dim $
 .include <bsd.own.mk>
=20
 LIBARCHIVEDIR=3D	${.CURDIR}/../../contrib/libarchive
@@ -45,6 +45,7 @@
 CFLAGS+=3D	-DPPMD_32BIT
 .endif
 .endif
+NO_WCAST_ALIGN.clang=3D
=20
 .PATH: ${LIBARCHIVEDIR}/libarchive
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/libbluetooth/bluetooth.3
--- a/head/lib/libbluetooth/bluetooth.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libbluetooth/bluetooth.3	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\" $Id: bluetooth.3,v 1.5 2003/05/20 23:04:30 max Exp $
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libbluetooth/bluetooth.3 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd April 9, 2009
 .Dt BLUETOOTH 3
@@ -511,7 +511,7 @@
 .Pp
 The
 .Fn bt_devfilter_pkt_set ,
-.Fn bt_devfilter_pkt_clr=20
+.Fn bt_devfilter_pkt_clr
 and
 .Fn bt_devfilter_pkt_tst
 functions can be used to modify and test the
@@ -526,7 +526,7 @@
 .Pp
 The
 .Fn bt_devfilter_evt_set ,
-.Fn bt_devfilter_evt_clr=20
+.Fn bt_devfilter_evt_clr
 and
 .Fn bt_devfilter_evt_tst
 functions can be used to modify and test the
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/Makefile
--- a/head/lib/libc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	@(#)Makefile	8.2 (Berkeley) 2/3/94
-# $FreeBSD: head/lib/libc/Makefile 229368 2012-01-03 07:14:01Z ed $
+# $FreeBSD: head/lib/libc/Makefile 234370 2012-04-17 07:22:14Z jasone $
=20
 SHLIBDIR?=3D /lib
=20
@@ -79,6 +79,7 @@
 .include "${.CURDIR}/resolv/Makefile.inc"
 .include "${.CURDIR}/stdio/Makefile.inc"
 .include "${.CURDIR}/stdlib/Makefile.inc"
+.include "${.CURDIR}/stdlib/jemalloc/Makefile.inc"
 .include "${.CURDIR}/stdtime/Makefile.inc"
 .include "${.CURDIR}/string/Makefile.inc"
 .include "${.CURDIR}/sys/Makefile.inc"
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/arm/gen/Makefile.inc
--- a/head/lib/libc/arm/gen/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/arm/gen/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 #	@(#)Makefile.inc	8.1 (Berkeley) 6/4/93
-# $FreeBSD: head/lib/libc/arm/gen/Makefile.inc 231616 2012-02-14 00:12:15Z=
 gonzo $
+# $FreeBSD: head/lib/libc/arm/gen/Makefile.inc 234337 2012-04-16 09:38:20Z=
 andrew $
=20
 SRCS+=3D	_ctx_start.S _setjmp.S _set_tp.c alloca.S fabs.c \
 	getcontextx.c infinity.c ldexp.c makecontext.c \
-	__aeabi_read_tp.c setjmp.S signalcontext.c sigsetjmp.S divsi3.S flt_round=
s.c
+	__aeabi_read_tp.S setjmp.S signalcontext.c sigsetjmp.S divsi3.S flt_round=
s.c
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/fstab.c
--- a/head/lib/libc/gen/fstab.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/fstab.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
 static char sccsid[] =3D "@(#)fstab.c	8.1 (Berkeley) 6/4/93";
 #endif /* LIBC_SCCS and not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/gen/fstab.c 233300 2012-03-22 09:51:31Z =
pluknet $");
=20
 #include "namespace.h"
 #include <sys/param.h>
@@ -91,7 +91,7 @@
 	struct stat sb;
 	struct statfs sf;
=20
-	if (strcmp(_fs_fstab.fs_file, "/") !=3D 0)
+	if (_fs_fstab.fs_file !=3D NULL && strcmp(_fs_fstab.fs_file, "/") !=3D 0)
 		return;
 	if (statfs("/", &sf) !=3D 0)
 		return;
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/fts.3
--- a/head/lib/libc/gen/fts.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/fts.3	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)fts.3	8.5 (Berkeley) 4/16/94
-.\" $FreeBSD: head/lib/libc/gen/fts.3 233132 2012-03-18 21:46:27Z jilles $
+.\" $FreeBSD: head/lib/libc/gen/fts.3 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd March 18, 2012
 .Dt FTS 3
@@ -802,12 +802,12 @@
 .Nm
 functionality using different data structures.
 .Sh BUGS
-The=20
+The
 .Fn fts_open
 function will automatically set the
 .Dv FTS_NOCHDIR
-option if the=20
+option if the
 .Dv FTS_LOGICAL
-option is provided, or if it cannot=20
+option is provided, or if it cannot
 .Xr open 2
 the current directory.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/getpagesizes.3
--- a/head/lib/libc/gen/getpagesizes.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/getpagesizes.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/gen/getpagesizes.3 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd September 21, 2009
 .Dt GETPAGESIZES 3
@@ -56,7 +56,7 @@
 These page sizes are expressed in bytes.
 In this case,
 .Fn getpagesizes
-returns the number of such page sizes that it assigned to the array.=20
+returns the number of such page sizes that it assigned to the array.
 .Sh RETURN VALUES
 If successful, the
 .Fn getpagesizes
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/getutxent.c
--- a/head/lib/libc/gen/getutxent.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/getutxent.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/gen/getutxent.c 231514 2012-02-11 11:11:=
13Z ed $");
+__FBSDID("$FreeBSD: head/lib/libc/gen/getutxent.c 233345 2012-03-23 08:26:=
31Z ed $");
=20
 #include "namespace.h"
 #include <sys/endian.h>
@@ -38,8 +38,13 @@
 #include "utxdb.h"
 #include "un-namespace.h"
=20
+#ifdef __NO_TLS
 static FILE *uf =3D NULL;
 static int udb;
+#else
+static _Thread_local FILE *uf =3D NULL;
+static _Thread_local int udb;
+#endif
=20
 int
 setutxdb(int db, const char *file)
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/psignal.3
--- a/head/lib/libc/gen/psignal.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/psignal.3	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)psignal.3	8.2 (Berkeley) 2/27/95
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/gen/psignal.3 233510 2012-03-26 15:18:14Z joel=
 $
 .\"
 .Dd February 4, 2011
 .Dt PSIGNAL 3
@@ -79,7 +79,7 @@
 If the signal number is not recognized
 .Pq Xr sigaction 2 ,
 the string
-.Dq "Unknown signal
+.Dq "Unknown signal"
 is produced.
 .Pp
 The message strings can be accessed directly
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/sem_new.c
--- a/head/lib/libc/gen/sem_new.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/sem_new.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/lib/libc/gen/sem_new.c 232144 2012-02-25 02:12:17Z david=
xu $
+ * $FreeBSD: head/lib/libc/gen/sem_new.c 234057 2012-04-09 14:17:22Z jille=
s $
  */
=20
 #include "namespace.h"
@@ -162,10 +162,16 @@
 	_pthread_mutex_lock(&sem_llock);
 	LIST_FOREACH(ni, &sem_list, next) {
 		if (strcmp(name, ni->name) =3D=3D 0) {
-			ni->open_count++;
-			sem =3D ni->sem;
-			_pthread_mutex_unlock(&sem_llock);
-			return (sem);
+			if ((flags & (O_CREAT|O_EXCL)) =3D=3D (O_CREAT|O_EXCL)) {
+				_pthread_mutex_unlock(&sem_llock);
+				errno =3D EEXIST;
+				return (SEM_FAILED);
+			} else {
+				ni->open_count++;
+				sem =3D ni->sem;
+				_pthread_mutex_unlock(&sem_llock);
+				return (sem);
+			}
 		}
 	}
=20
@@ -332,9 +338,6 @@
 static __inline int
 usem_wake(struct _usem *sem)
 {
-	rmb();
-	if (!sem->_has_waiters)
-		return (0);
 	return _umtx_op(sem, UMTX_OP_SEM_WAKE, 0, NULL, NULL);
 }
=20
@@ -374,17 +377,6 @@
 	return (-1);
 }
=20
-#define TIMESPEC_SUB(dst, src, val)                             \
-        do {                                                    \
-                (dst)->tv_sec =3D (src)->tv_sec - (val)->tv_sec;  \
-                (dst)->tv_nsec =3D (src)->tv_nsec - (val)->tv_nsec; \
-                if ((dst)->tv_nsec < 0) {                       \
-                        (dst)->tv_sec--;                        \
-                        (dst)->tv_nsec +=3D 1000000000;           \
-                }                                               \
-        } while (0)
-
-
 int
 _sem_timedwait(sem_t * __restrict sem,
 	const struct timespec * __restrict abstime)
@@ -438,10 +430,16 @@
 int
 _sem_post(sem_t *sem)
 {
+	unsigned int count;
=20
 	if (sem_check_validity(sem) !=3D 0)
 		return (-1);
=20
-	atomic_add_rel_int(&sem->_kern._count, 1);
-	return usem_wake(&sem->_kern);
+	do {
+		count =3D sem->_kern._count;
+		if (count + 1 > SEM_VALUE_MAX)
+			return (EOVERFLOW);
+	} while(!atomic_cmpset_rel_int(&sem->_kern._count, count, count+1));
+	(void)usem_wake(&sem->_kern);
+	return (0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/sysconf.3
--- a/head/lib/libc/gen/sysconf.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/sysconf.3	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)sysconf.3	8.3 (Berkeley) 4/19/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/gen/sysconf.3 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd February 13, 2011
 .Dt SYSCONF 3
@@ -211,7 +211,7 @@
 .It Li _SC_XOPEN_VERSION
 An integer value greater than or equal to 4,
 indicating the version of the X/Open Portability Guide to which this
-system conforms.=20
+system conforms.
 .It Li _SC_XOPEN_XCU_VERSION
 An integer value indicating the version of the XCU Specification to which
 this system conforms.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/tls.c
--- a/head/lib/libc/gen/tls.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/tls.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	$FreeBSD: head/lib/libc/gen/tls.c 232582 2012-03-06 03:42:54Z gonzo $
+ *	$FreeBSD: head/lib/libc/gen/tls.c 234370 2012-04-17 07:22:14Z jasone $
  */
=20
 /*
@@ -39,6 +39,11 @@
=20
 #include "libc_private.h"
=20
+/* Provided by jemalloc to avoid bootstrapping issues. */
+void	*a0malloc(size_t size);
+void	*a0calloc(size_t num, size_t size);
+void	a0free(void *ptr);
+
 __weak_reference(__libc_allocate_tls, _rtld_allocate_tls);
 __weak_reference(__libc_free_tls, _rtld_free_tls);
=20
@@ -120,8 +125,8 @@
=20
 	tls =3D (Elf_Addr **)((Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE);
 	dtv =3D tls[0];
-	free(dtv);
-	free(tcb);
+	a0free(dtv);
+	a0free(tcb);
 }
=20
 /*
@@ -137,18 +142,18 @@
 	if (oldtcb !=3D NULL && tcbsize =3D=3D TLS_TCB_SIZE)
 		return (oldtcb);
=20
-	tcb =3D calloc(1, tls_static_space + tcbsize - TLS_TCB_SIZE);
+	tcb =3D a0calloc(1, tls_static_space + tcbsize - TLS_TCB_SIZE);
 	tls =3D (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
=20
 	if (oldtcb !=3D NULL) {
 		memcpy(tls, oldtcb, tls_static_space);
-		free(oldtcb);
+		a0free(oldtcb);
=20
 		/* Adjust the DTV. */
 		dtv =3D tls[0];
 		dtv[2] =3D (Elf_Addr)tls + TLS_TCB_SIZE;
 	} else {
-		dtv =3D malloc(3 * sizeof(Elf_Addr));
+		dtv =3D a0malloc(3 * sizeof(Elf_Addr));
 		tls[0] =3D dtv;
 		dtv[0] =3D 1;
 		dtv[1] =3D 1;
@@ -189,8 +194,8 @@
 	dtv =3D ((Elf_Addr**)tcb)[1];
 	tlsend =3D (Elf_Addr) tcb;
 	tlsstart =3D tlsend - size;
-	free((void*) tlsstart);
-	free(dtv);
+	a0free((void*) tlsstart);
+	a0free(dtv);
 }
=20
 /*
@@ -208,8 +213,8 @@
=20
 	if (tcbsize < 2 * sizeof(Elf_Addr))
 		tcbsize =3D 2 * sizeof(Elf_Addr);
-	tls =3D calloc(1, size + tcbsize);
-	dtv =3D malloc(3 * sizeof(Elf_Addr));
+	tls =3D a0calloc(1, size + tcbsize);
+	dtv =3D a0malloc(3 * sizeof(Elf_Addr));
=20
 	segbase =3D (Elf_Addr)(tls + size);
 	((Elf_Addr*)segbase)[0] =3D segbase;
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/gen/utxdb.c
--- a/head/lib/libc/gen/utxdb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/gen/utxdb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/gen/utxdb.c 233345 2012-03-23 08:26:31Z =
ed $");
=20
 #include "namespace.h"
 #include <sys/endian.h>
@@ -126,7 +126,11 @@
 struct utmpx *
 futx_to_utx(const struct futx *fu)
 {
+#ifdef __NO_TLS
 	static struct utmpx *ut;
+#else
+	static _Thread_local struct utmpx *ut;
+#endif
=20
 	if (ut =3D=3D NULL) {
 		ut =3D calloc(1, sizeof *ut);
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/i386/sys/i386_get_ioperm=
.2
--- a/head/lib/libc/i386/sys/i386_get_ioperm.2	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/lib/libc/i386/sys/i386_get_ioperm.2	Tue Apr 17 11:51:51 2012 +03=
00
@@ -22,11 +22,11 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/i386/sys/i386_get_ioperm.2 233520 2012-03-26 1=
9:23:57Z joel $
 .\"
 .Dd July 27, 1998
+.Dt I386_GET_IOPERM 2
 .Os
-.Dt I386_GET_IOPERM 2
 .Sh NAME
 .Nm i386_get_ioperm ,
 .Nm i386_set_ioperm
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/i386/sys/i386_set_watch.3
--- a/head/lib/libc/i386/sys/i386_set_watch.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/i386/sys/i386_set_watch.3	Tue Apr 17 11:51:51 2012 +0300
@@ -25,11 +25,11 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/i386/sys/i386_set_watch.3 233520 2012-03-26 19=
:23:57Z joel $
 .\"
 .Dd August 24, 2000
+.Dt I386_SET_WATCH 3
 .Os
-.Dt I386_SET_WATCH 3
 .Sh NAME
 .Nm i386_clr_watch ,
 .Nm i386_set_watch
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/i386/sys/i386_vm86.2
--- a/head/lib/libc/i386/sys/i386_vm86.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/i386/sys/i386_vm86.2	Tue Apr 17 11:51:51 2012 +0300
@@ -22,11 +22,11 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/i386/sys/i386_vm86.2 233520 2012-03-26 19:23:5=
7Z joel $
 .\"
 .Dd July 27, 1998
+.Dt I386_VM86 2
 .Os
-.Dt I386_VM86 2
 .Sh NAME
 .Nm i386_vm86
 .Nd control vm86-related functions
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/iconv/iconv.3
--- a/head/lib/libc/iconv/iconv.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/iconv/iconv.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/iconv/iconv.3 233509 2012-03-26 14:56:23Z joel=
 $
 .\" $NetBSD: iconv.3,v 1.12 2004/08/02 13:38:21 tshiozak Exp $
 .\"
 .\" Copyright (c) 2003 Citrus Project,
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.Dd Juny 16, 2010
+.Dd June 16, 2010
 .Dt ICONV 3
 .Os
 .Sh NAME
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/iconv/iconvctl.3
--- a/head/lib/libc/iconv/iconvctl.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/iconv/iconvctl.3	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
 .\" the referee document.  The original Standard can be obtained online at
 .\"	http://www.opengroup.org/unix/online.html.
 .\"
-.\" $FreeBSD: head/lib/libc/iconv/iconvctl.3 222600 2011-06-02 09:56:53Z u=
qs $
+.\" $FreeBSD: head/lib/libc/iconv/iconvctl.3 233577 2012-03-27 20:50:14Z j=
oel $
 .\"
 .Dd November 7, 2009
 .Dt ICONVCTL 3
@@ -61,7 +61,7 @@
 is an operation-specific argument.
 .Pp
 The possible operations are the following:
-.Bl -tag -width -indent
+.Bl -tag -width indent
 .It ICONV_TRIVIALP
 In this case
 .Fa argument
@@ -110,6 +110,7 @@
 via
 .Fa argument
 by its address.
+.El
 .\" XXX: fallbacks are unimplemented and trying to set them will always
 .\"      return EOPNOTSUPP but definitions are provided for source-level
 .\"      compatibility.
@@ -140,6 +141,7 @@
 The conversion descriptor specified by
 .Fa cd
 is invalid.
+.El
 .Sh SEE ALSO
 .Xr iconv 1 ,
 .Xr iconv 3
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/iconv/iconvlist.3
--- a/head/lib/libc/iconv/iconvlist.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/iconv/iconvlist.3	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
 .\" the referee document.  The original Standard can be obtained online at
 .\"	http://www.opengroup.org/unix/online.html.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/iconv/iconvlist.3 233625 2012-03-28 19:20:28Z =
joel $
 .\"
 .Dd October 20, 2009
 .Dt ICONVLIST 3
@@ -46,7 +46,7 @@
 .Sh SYNOPSIS
 .In iconv.h
 .Ft void
-.Fo iconvlist "char ***names" "size_t count" "bool paired"
+.Fo iconvlist
 .Fa "int \*[lp]*do_one\*[rp]\*[lp]unsigned int *count, const char * const =
*names, void *arg\*[rp]"
 .Fa "void *arg"
 .Fc
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/ctype.3
--- a/head/lib/libc/locale/ctype.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/ctype.3	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)ctype.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/ctype.3 232935 2012-03-13 20:02:41Z the=
raven $
+.\" $FreeBSD: head/lib/libc/locale/ctype.3 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd March 30, 2004
 .Dt CTYPE 3
@@ -55,7 +55,7 @@
 .Nm toascii ,
 .Nm tolower ,
 .Nm toupper
-.Nd character classification functions=20
+.Nd character classification functions
 .Sh LIBRARY
 .Lb libc
 .Sh SYNOPSIS
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/ctype_l.3
--- a/head/lib/libc/locale/ctype_l.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/ctype_l.3	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/ctype_l.3 232935 2012-03-13 20:02:41Z t=
heraven $
+.\" $FreeBSD: head/lib/libc/locale/ctype_l.3 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd March 6, 2012
 .Dt CTYPE_L 3
@@ -102,11 +102,11 @@
 .Fn toupper_l "int c" "locale_t loc"
 .Sh DESCRIPTION
 The above functions perform character tests and conversions on the integer
-.Fa c=20
+.Fa c
 in the locale
 .Fa loc .
 They behave in the same way as the versions without the _l suffix, but use=
 the
-specified locale rather than the global or per-thread locale. =20
+specified locale rather than the global or per-thread locale.
 .In ctype.h ,
 or as true functions in the C library.
 See the specific manual pages for more information.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/digittoint.3
--- a/head/lib/libc/locale/digittoint.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/digittoint.3	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)digittoint.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/digittoint.3 232935 2012-03-13 20:02:41=
Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/digittoint.3 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd April 6, 2001
 .Dt DIGITTOINT 3
@@ -49,7 +49,7 @@
 The character can be any decimal digit or hexadecimal digit.
 With hexadecimal characters, the case of the values does not matter.
 .Pp
-The=20
+The
 .Fn digittoint_l
 function takes an explicit locale argument, whereas the
 .Fn digittoint
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/duplocale.3
--- a/head/lib/libc/locale/duplocale.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/duplocale.3	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/duplocale.3 228199 2011-12-02 11:55:09Z=
 obrien $
+.\" $FreeBSD: head/lib/libc/locale/duplocale.3 233518 2012-03-26 19:06:59Z=
 joel $
 .\"
 .Dd September 17 2011
 .Dt DUPLOCALE 3
@@ -56,18 +56,8 @@
 .Xr uselocale 3 .
 These calls are therefore only thread safe on threads with a unique per-th=
read
 locale.
-.Pt
 The locale returned by this call must be freed with
 .Xr freelocale 3 .
-.Sh BUGS
-Ideally,
-.Xr uselocale 3
-should make a copy of the
-.Fa locale_t
-implicitly to ensure thread safety,
-and a copy of the global locale should be installed lazily on each thread.
-The FreeBSD implementation does not do this,
-for compatibility with Darwin.
 .Sh SEE ALSO
 .Xr freelocale 3 ,
 .Xr localeconv 3 ,
@@ -78,3 +68,12 @@
 .Sh STANDARDS
 This function, conforms to
 .St -p1003.1-2008
+.Sh BUGS
+Ideally,
+.Xr uselocale 3
+should make a copy of the
+.Fa locale_t
+implicitly to ensure thread safety,
+and a copy of the global locale should be installed lazily on each thread.
+The FreeBSD implementation does not do this,
+for compatibility with Darwin.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isalnum.3
--- a/head/lib/libc/locale/isalnum.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isalnum.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isalnum.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/isalnum.3 232935 2012-03-13 20:02:41Z t=
heraven $
+.\" $FreeBSD: head/lib/libc/locale/isalnum.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISALNUM 3
@@ -62,22 +62,22 @@
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&060\ ``0'' \t061\ ``1'' \t062\ ``2'' \t063\ ``3'' \t064\ ``4''"
-.It "\&065\ ``5'' \t066\ ``6'' \t067\ ``7'' \t070\ ``8'' \t071\ ``9''"
-.It "\&101\ ``A'' \t102\ ``B'' \t103\ ``C'' \t104\ ``D'' \t105\ ``E''"
-.It "\&106\ ``F'' \t107\ ``G'' \t110\ ``H'' \t111\ ``I'' \t112\ ``J''"
-.It "\&113\ ``K'' \t114\ ``L'' \t115\ ``M'' \t116\ ``N'' \t117\ ``O''"
-.It "\&120\ ``P'' \t121\ ``Q'' \t122\ ``R'' \t123\ ``S'' \t124\ ``T''"
-.It "\&125\ ``U'' \t126\ ``V'' \t127\ ``W'' \t130\ ``X'' \t131\ ``Y''"
-.It "\&132\ ``Z'' \t141\ ``a'' \t142\ ``b'' \t143\ ``c'' \t144\ ``d''"
-.It "\&145\ ``e'' \t146\ ``f'' \t147\ ``g'' \t150\ ``h'' \t151\ ``i''"
-.It "\&152\ ``j'' \t153\ ``k'' \t154\ ``l'' \t155\ ``m'' \t156\ ``n''"
-.It "\&157\ ``o'' \t160\ ``p'' \t161\ ``q'' \t162\ ``r'' \t163\ ``s''"
-.It "\&164\ ``t'' \t165\ ``u'' \t166\ ``v'' \t167\ ``w'' \t170\ ``x''"
-.It "\&171\ ``y'' \t172\ ``z''"
+.It "\&060\ ``0''" Ta "061\ ``1''" Ta "062\ ``2''" Ta "063\ ``3''" Ta "064=
\ ``4''"
+.It "\&065\ ``5''" Ta "066\ ``6''" Ta "067\ ``7''" Ta "070\ ``8''" Ta "071=
\ ``9''"
+.It "\&101\ ``A''" Ta "102\ ``B''" Ta "103\ ``C''" Ta "104\ ``D''" Ta "105=
\ ``E''"
+.It "\&106\ ``F''" Ta "107\ ``G''" Ta "110\ ``H''" Ta "111\ ``I''" Ta "112=
\ ``J''"
+.It "\&113\ ``K''" Ta "114\ ``L''" Ta "115\ ``M''" Ta "116\ ``N''" Ta "117=
\ ``O''"
+.It "\&120\ ``P''" Ta "121\ ``Q''" Ta "122\ ``R''" Ta "123\ ``S''" Ta "124=
\ ``T''"
+.It "\&125\ ``U''" Ta "126\ ``V''" Ta "127\ ``W''" Ta "130\ ``X''" Ta "131=
\ ``Y''"
+.It "\&132\ ``Z''" Ta "141\ ``a''" Ta "142\ ``b''" Ta "143\ ``c''" Ta "144=
\ ``d''"
+.It "\&145\ ``e''" Ta "146\ ``f''" Ta "147\ ``g''" Ta "150\ ``h''" Ta "151=
\ ``i''"
+.It "\&152\ ``j''" Ta "153\ ``k''" Ta "154\ ``l''" Ta "155\ ``m''" Ta "156=
\ ``n''"
+.It "\&157\ ``o''" Ta "160\ ``p''" Ta "161\ ``q''" Ta "162\ ``r''" Ta "163=
\ ``s''"
+.It "\&164\ ``t''" Ta "165\ ``u''" Ta "166\ ``v''" Ta "167\ ``w''" Ta "170=
\ ``x''"
+.It "\&171\ ``y''" Ta "172\ ``z''" Ta \& Ta \& Ta \&
 .El
 .Pp
-The=20
+The
 .Fn isalnum_l
 function takes an explicit locale argument, whereas the
 .Fn isalnum
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isalpha.3
--- a/head/lib/libc/locale/isalpha.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isalpha.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isalpha.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/isalpha.3 232935 2012-03-13 20:02:41Z t=
heraven $
+.\" $FreeBSD: head/lib/libc/locale/isalpha.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISALPHA 3
@@ -62,19 +62,20 @@
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&101\ ``A'' \t102\ ``B'' \t103\ ``C'' \t104\ ``D'' \t105\ ``E''"
-.It "\&106\ ``F'' \t107\ ``G'' \t110\ ``H'' \t111\ ``I'' \t112\ ``J''"
-.It "\&113\ ``K'' \t114\ ``L'' \t115\ ``M'' \t116\ ``N'' \t117\ ``O''"
-.It "\&120\ ``P'' \t121\ ``Q'' \t122\ ``R'' \t123\ ``S'' \t124\ ``T''"
-.It "\&125\ ``U'' \t126\ ``V'' \t127\ ``W'' \t130\ ``X'' \t131\ ``Y''"
-.It "\&132\ ``Z'' \t141\ ``a'' \t142\ ``b'' \t143\ ``c'' \t144\ ``d''"
-.It "\&145\ ``e'' \t146\ ``f'' \t147\ ``g'' \t150\ ``h'' \t151\ ``i''"
-.It "\&152\ ``j'' \t153\ ``k'' \t154\ ``l'' \t155\ ``m'' \t156\ ``n''"
-.It "\&157\ ``o'' \t160\ ``p'' \t161\ ``q'' \t162\ ``r'' \t163\ ``s''"
-.It "\&164\ ``t'' \t165\ ``u'' \t166\ ``v'' \t167\ ``w'' \t170\ ``x''"
-.It "\&171\ ``y'' \t172\ ``z''"
+.It "\&101\ ``A''" Ta "102\ ``B''" Ta "103\ ``C''" Ta "104\ ``D''" Ta "105=
\ ``E''"
+.It "\&106\ ``F''" Ta "107\ ``G''" Ta "110\ ``H''" Ta "111\ ``I''" Ta "112=
\ ``J''"
+.It "\&113\ ``K''" Ta "114\ ``L''" Ta "115\ ``M''" Ta "116\ ``N''" Ta "117=
\ ``O''"
+.It "\&120\ ``P''" Ta "121\ ``Q''" Ta "122\ ``R''" Ta "123\ ``S''" Ta "124=
\ ``T''"
+.It "\&125\ ``U''" Ta "126\ ``V''" Ta "127\ ``W''" Ta "130\ ``X''" Ta "131=
\ ``Y''"
+.It "\&132\ ``Z''" Ta "141\ ``a''" Ta "142\ ``b''" Ta "143\ ``c''" Ta "144=
\ ``d''"
+.It "\&145\ ``e''" Ta "146\ ``f''" Ta "147\ ``g''" Ta "150\ ``h''" Ta "151=
\ ``i''"
+.It "\&152\ ``j''" Ta "153\ ``k''" Ta "154\ ``l''" Ta "155\ ``m''" Ta "156=
\ ``n''"
+.It "\&157\ ``o''" Ta "160\ ``p''" Ta "161\ ``q''" Ta "162\ ``r''" Ta "163=
\ ``s''"
+.It "\&164\ ``t''" Ta "165\ ``u''" Ta "166\ ``v''" Ta "167\ ``w''" Ta "170=
\ ``x''"
+.It "\&171\ ``y''" Ta "172\ ``z''" Ta \& Ta \& Ta \&
 .El
-The=20
+.Pp
+The
 .Fn isalpha_l
 function takes an explicit locale argument, whereas the
 .Fn isalpha
@@ -110,4 +111,3 @@
 .Fn isalpha_l
 function conforms to
 .St -p1003.1-2008 .
-
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isblank.3
--- a/head/lib/libc/locale/isblank.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isblank.3	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isblank.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/isblank.3 232935 2012-03-13 20:02:41Z t=
heraven $
+.\" $FreeBSD: head/lib/libc/locale/isblank.3 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd July 17, 2005
 .Dt ISBLANK 3
@@ -59,7 +59,7 @@
 or the value of
 .Dv EOF .
 .Pp
-The=20
+The
 .Fn isblank_l
 function takes an explicit locale argument, whereas the
 .Fn isblank
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/iscntrl.3
--- a/head/lib/libc/locale/iscntrl.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/iscntrl.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)iscntrl.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/iscntrl.3 232935 2012-03-13 20:02:41Z t=
heraven $
+.\" $FreeBSD: head/lib/libc/locale/iscntrl.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISCNTRL 3
@@ -57,18 +57,17 @@
 .Pp
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
-.Pp
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&000\ NUL \t001\ SOH \t002\ STX \t003\ ETX \t004\ EOT"
-.It "\&005\ ENQ \t006\ ACK \t007\ BEL \t010\ BS \t011\ HT"
-.It "\&012\ NL \t013\ VT \t014\ NP \t015\ CR \t016\ SO"
-.It "\&017\ SI \t020\ DLE \t021\ DC1 \t022\ DC2 \t023\ DC3"
-.It "\&024\ DC4 \t025\ NAK \t026\ SYN \t027\ ETB \t030\ CAN"
-.It "\&031\ EM \t032\ SUB \t033\ ESC \t034\ FS \t035\ GS"
-.It "\&036\ RS \t037\ US \t177\ DEL"
+.It "\&000\ NUL" Ta "001\ SOH" Ta "002\ STX" Ta "003\ ETX" Ta "004\ EOT"
+.It "\&005\ ENQ" Ta "006\ ACK" Ta "007\ BEL" Ta "010\ BS" Ta "011\ HT"
+.It "\&012\ NL" Ta "013\ VT" Ta "014\ NP" Ta "015\ CR" Ta "016\ SO"
+.It "\&017\ SI" Ta "020\ DLE" Ta "021\ DC1" Ta "022\ DC2" Ta "023\ DC3"
+.It "\&024\ DC4" Ta "025\ NAK" Ta "026\ SYN" Ta "027\ ETB" Ta "030\ CAN"
+.It "\&031\ EM" Ta "032\ SUB" Ta "033\ ESC" Ta "034\ FS" Ta "035\ GS"
+.It "\&036\ RS" Ta "037\ US" Ta "177\ DEL" Ta \& Ta \&
 .El
 .Pp
-The=20
+The
 .Fn iscntrl_l
 function takes an explicit locale argument, whereas the
 .Fn iscntrl
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isdigit.3
--- a/head/lib/libc/locale/isdigit.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isdigit.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isdigit.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/isdigit.3 232935 2012-03-13 20:02:41Z t=
heraven $
+.\" $FreeBSD: head/lib/libc/locale/isdigit.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd May 4, 2007
 .Dt ISDIGIT 3
@@ -55,10 +55,9 @@
 .Fn isdigit
 function tests for a decimal digit character.
 Regardless of locale, this includes the following characters only:
-.Pp
 .Bl -column \&``0''______ \&``0''______ \&``0''______ \&``0''______ \&``0'=
'______
-.It "\&``0''\t``1''\t``2''\t``3''\t``4''"
-.It "\&``5''\t``6''\t``7''\t``8''\t``9''"
+.It "\&``0''" Ta "``1''" Ta "``2''" Ta "``3''" Ta "``4''"
+.It "\&``5''" Ta "``6''" Ta "``7''" Ta "``8''" Ta "``9''"
 .El
 .Pp
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isgraph.3
--- a/head/lib/libc/locale/isgraph.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isgraph.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isgraph.3	8.2 (Berkeley) 12/11/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/locale/isgraph.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISGRAPH 3
@@ -58,27 +58,26 @@
 .Pp
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
-.Pp
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&041\ ``!'' \t042\ ``""'' \t043\ ``#'' \t044\ ``$'' \t045\ ``%''"
-.It "\&046\ ``&'' \t047\ ``''' \t050\ ``('' \t051\ ``)'' \t052\ ``*''"
-.It "\&053\ ``+'' \t054\ ``,'' \t055\ ``-'' \t056\ ``.'' \t057\ ``/''"
-.It "\&060\ ``0'' \t061\ ``1'' \t062\ ``2'' \t063\ ``3'' \t064\ ``4''"
-.It "\&065\ ``5'' \t066\ ``6'' \t067\ ``7'' \t070\ ``8'' \t071\ ``9''"
-.It "\&072\ ``:'' \t073\ ``;'' \t074\ ``<'' \t075\ ``=3D'' \t076\ ``>''"
-.It "\&077\ ``?'' \t100\ ``@'' \t101\ ``A'' \t102\ ``B'' \t103\ ``C''"
-.It "\&104\ ``D'' \t105\ ``E'' \t106\ ``F'' \t107\ ``G'' \t110\ ``H''"
-.It "\&111\ ``I'' \t112\ ``J'' \t113\ ``K'' \t114\ ``L'' \t115\ ``M''"
-.It "\&116\ ``N'' \t117\ ``O'' \t120\ ``P'' \t121\ ``Q'' \t122\ ``R''"
-.It "\&123\ ``S'' \t124\ ``T'' \t125\ ``U'' \t126\ ``V'' \t127\ ``W''"
-.It "\&130\ ``X'' \t131\ ``Y'' \t132\ ``Z'' \t133\ ``['' \t134\ ``\e\|''"
-.It "\&135\ ``]'' \t136\ ``^'' \t137\ ``_'' \t140\ ```'' \t141\ ``a''"
-.It "\&142\ ``b'' \t143\ ``c'' \t144\ ``d'' \t145\ ``e'' \t146\ ``f''"
-.It "\&147\ ``g'' \t150\ ``h'' \t151\ ``i'' \t152\ ``j'' \t153\ ``k''"
-.It "\&154\ ``l'' \t155\ ``m'' \t156\ ``n'' \t157\ ``o'' \t160\ ``p''"
-.It "\&161\ ``q'' \t162\ ``r'' \t163\ ``s'' \t164\ ``t'' \t165\ ``u''"
-.It "\&166\ ``v'' \t167\ ``w'' \t170\ ``x'' \t171\ ``y'' \t172\ ``z''"
-.It "\&173\ ``{'' \t174\ ``|'' \t175\ ``}'' \t176\ ``~''"
+.It "\&041\ ``!''" Ta "042\ ``""''" Ta "043\ ``#''" Ta "044\ ``$''" Ta "04=
5\ ``%''"
+.It "\&046\ ``&''" Ta "047\ ``'''" Ta "050\ ``(''" Ta "051\ ``)''" Ta "052=
\ ``*''"
+.It "\&053\ ``+''" Ta "054\ ``,''" Ta "055\ ``-''" Ta "056\ ``.''" Ta "057=
\ ``/''"
+.It "\&060\ ``0''" Ta "061\ ``1''" Ta "062\ ``2''" Ta "063\ ``3''" Ta "064=
\ ``4''"
+.It "\&065\ ``5''" Ta "066\ ``6''" Ta "067\ ``7''" Ta "070\ ``8''" Ta "071=
\ ``9''"
+.It "\&072\ ``:''" Ta "073\ ``;''" Ta "074\ ``<''" Ta "075\ ``=3D''" Ta "0=
76\ ``>''"
+.It "\&077\ ``?''" Ta "100\ ``@''" Ta "101\ ``A''" Ta "102\ ``B''" Ta "103=
\ ``C''"
+.It "\&104\ ``D''" Ta "105\ ``E''" Ta "106\ ``F''" Ta "107\ ``G''" Ta "110=
\ ``H''"
+.It "\&111\ ``I''" Ta "112\ ``J''" Ta "113\ ``K''" Ta "114\ ``L''" Ta "115=
\ ``M''"
+.It "\&116\ ``N''" Ta "117\ ``O''" Ta "120\ ``P''" Ta "121\ ``Q''" Ta "122=
\ ``R''"
+.It "\&123\ ``S''" Ta "124\ ``T''" Ta "125\ ``U''" Ta "126\ ``V''" Ta "127=
\ ``W''"
+.It "\&130\ ``X''" Ta "131\ ``Y''" Ta "132\ ``Z''" Ta "133\ ``[''" Ta "134=
\ ``\e\|''"
+.It "\&135\ ``]''" Ta "136\ ``^''" Ta "137\ ``_''" Ta "140\ ```''" Ta "141=
\ ``a''"
+.It "\&142\ ``b''" Ta "143\ ``c''" Ta "144\ ``d''" Ta "145\ ``e''" Ta "146=
\ ``f''"
+.It "\&147\ ``g''" Ta "150\ ``h''" Ta "151\ ``i''" Ta "152\ ``j''" Ta "153=
\ ``k''"
+.It "\&154\ ``l''" Ta "155\ ``m''" Ta "156\ ``n''" Ta "157\ ``o''" Ta "160=
\ ``p''"
+.It "\&161\ ``q''" Ta "162\ ``r''" Ta "163\ ``s''" Ta "164\ ``t''" Ta "165=
\ ``u''"
+.It "\&166\ ``v''" Ta "167\ ``w''" Ta "170\ ``x''" Ta "171\ ``y''" Ta "172=
\ ``z''"
+.It "\&173\ ``{''" Ta "174\ ``|''" Ta "175\ ``}''" Ta "176\ ``~''" Ta \&
 .El
 .Sh RETURN VALUES
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/islower.3
--- a/head/lib/libc/locale/islower.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/islower.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)islower.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/locale/islower.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISLOWER 3
@@ -55,14 +55,13 @@
 .Pp
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
-.Pp
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&141\ ``a'' \t142\ ``b'' \t143\ ``c'' \t144\ ``d'' \t145\ ``e''"
-.It "\&146\ ``f'' \t147\ ``g'' \t150\ ``h'' \t151\ ``i'' \t152\ ``j''"
-.It "\&153\ ``k'' \t154\ ``l'' \t155\ ``m'' \t156\ ``n'' \t157\ ``o''"
-.It "\&160\ ``p'' \t161\ ``q'' \t162\ ``r'' \t163\ ``s'' \t164\ ``t''"
-.It "\&165\ ``u'' \t166\ ``v'' \t167\ ``w'' \t170\ ``x'' \t171\ ``y''"
-.It "\&172\ ``z''"
+.It "\&141\ ``a''" Ta "142\ ``b''" Ta "143\ ``c''" Ta "144\ ``d''" Ta "145=
\ ``e''"
+.It "\&146\ ``f''" Ta "147\ ``g''" Ta "150\ ``h''" Ta "151\ ``i''" Ta "152=
\ ``j''"
+.It "\&153\ ``k''" Ta "154\ ``l''" Ta "155\ ``m''" Ta "156\ ``n''" Ta "157=
\ ``o''"
+.It "\&160\ ``p''" Ta "161\ ``q''" Ta "162\ ``r''" Ta "163\ ``s''" Ta "164=
\ ``t''"
+.It "\&165\ ``u''" Ta "166\ ``v''" Ta "167\ ``w''" Ta "170\ ``x''" Ta "171=
\ ``y''"
+.It "\&172\ ``z''" Ta \& Ta \& Ta \& Ta \&
 .El
 .Sh RETURN VALUES
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isprint.3
--- a/head/lib/libc/locale/isprint.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isprint.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isprint.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/locale/isprint.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISPRINT 3
@@ -56,27 +56,26 @@
 .Pp
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
-.Pp
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&040\ sp \t041\ ``!'' \t042\ ``""'' \t043\ ``#'' \t044\ ``$''"
-.It "\&045\ ``%'' \t046\ ``&'' \t047\ ``''' \t050\ ``('' \t051\ ``)''"
-.It "\&052\ ``*'' \t053\ ``+'' \t054\ ``,'' \t055\ ``-'' \t056\ ``.''"
-.It "\&057\ ``/'' \t060\ ``0'' \t061\ ``1'' \t062\ ``2'' \t063\ ``3''"
-.It "\&064\ ``4'' \t065\ ``5'' \t066\ ``6'' \t067\ ``7'' \t070\ ``8''"
-.It "\&071\ ``9'' \t072\ ``:'' \t073\ ``;'' \t074\ ``<'' \t075\ ``=3D''"
-.It "\&076\ ``>'' \t077\ ``?'' \t100\ ``@'' \t101\ ``A'' \t102\ ``B''"
-.It "\&103\ ``C'' \t104\ ``D'' \t105\ ``E'' \t106\ ``F'' \t107\ ``G''"
-.It "\&110\ ``H'' \t111\ ``I'' \t112\ ``J'' \t113\ ``K'' \t114\ ``L''"
-.It "\&115\ ``M'' \t116\ ``N'' \t117\ ``O'' \t120\ ``P'' \t121\ ``Q''"
-.It "\&122\ ``R'' \t123\ ``S'' \t124\ ``T'' \t125\ ``U'' \t126\ ``V''"
-.It "\&127\ ``W'' \t130\ ``X'' \t131\ ``Y'' \t132\ ``Z'' \t133\ ``[''"
-.It "\&134\ ``\e\|'' \t135\ ``]'' \t136\ ``^'' \t137\ ``_'' \t140\ ```''"
-.It "\&141\ ``a'' \t142\ ``b'' \t143\ ``c'' \t144\ ``d'' \t145\ ``e''"
-.It "\&146\ ``f'' \t147\ ``g'' \t150\ ``h'' \t151\ ``i'' \t152\ ``j''"
-.It "\&153\ ``k'' \t154\ ``l'' \t155\ ``m'' \t156\ ``n'' \t157\ ``o''"
-.It "\&160\ ``p'' \t161\ ``q'' \t162\ ``r'' \t163\ ``s'' \t164\ ``t''"
-.It "\&165\ ``u'' \t166\ ``v'' \t167\ ``w'' \t170\ ``x'' \t171\ ``y''"
-.It "\&172\ ``z'' \t173\ ``{'' \t174\ ``|'' \t175\ ``}'' \t176\ ``~''"
+.It "\&040\ sp" Ta "041\ ``!''" Ta "042\ ``""''" Ta "043\ ``#''" Ta "044\ =
``$''"
+.It "\&045\ ``%''" Ta "046\ ``&''" Ta "047\ ``'''" Ta "050\ ``(''" Ta "051=
\ ``)''"
+.It "\&052\ ``*''" Ta "053\ ``+''" Ta "054\ ``,''" Ta "055\ ``-''" Ta "056=
\ ``.''"
+.It "\&057\ ``/''" Ta "060\ ``0''" Ta "061\ ``1''" Ta "062\ ``2''" Ta "063=
\ ``3''"
+.It "\&064\ ``4''" Ta "065\ ``5''" Ta "066\ ``6''" Ta "067\ ``7''" Ta "070=
\ ``8''"
+.It "\&071\ ``9''" Ta "072\ ``:''" Ta "073\ ``;''" Ta "074\ ``<''" Ta "075=
\ ``=3D''"
+.It "\&076\ ``>''" Ta "077\ ``?''" Ta "100\ ``@''" Ta "101\ ``A''" Ta "102=
\ ``B''"
+.It "\&103\ ``C''" Ta "104\ ``D''" Ta "105\ ``E''" Ta "106\ ``F''" Ta "107=
\ ``G''"
+.It "\&110\ ``H''" Ta "111\ ``I''" Ta "112\ ``J''" Ta "113\ ``K''" Ta "114=
\ ``L''"
+.It "\&115\ ``M''" Ta "116\ ``N''" Ta "117\ ``O''" Ta "120\ ``P''" Ta "121=
\ ``Q''"
+.It "\&122\ ``R''" Ta "123\ ``S''" Ta "124\ ``T''" Ta "125\ ``U''" Ta "126=
\ ``V''"
+.It "\&127\ ``W''" Ta "130\ ``X''" Ta "131\ ``Y''" Ta "132\ ``Z''" Ta "133=
\ ``[''"
+.It "\&134\ ``\e\|''" Ta "135\ ``]''" Ta "136\ ``^''" Ta "137\ ``_''" Ta "=
140\ ```''"
+.It "\&141\ ``a''" Ta "142\ ``b''" Ta "143\ ``c''" Ta "144\ ``d''" Ta "145=
\ ``e''"
+.It "\&146\ ``f''" Ta "147\ ``g''" Ta "150\ ``h''" Ta "151\ ``i''" Ta "152=
\ ``j''"
+.It "\&153\ ``k''" Ta "154\ ``l''" Ta "155\ ``m''" Ta "156\ ``n''" Ta "157=
\ ``o''"
+.It "\&160\ ``p''" Ta "161\ ``q''" Ta "162\ ``r''" Ta "163\ ``s''" Ta "164=
\ ``t''"
+.It "\&165\ ``u''" Ta "166\ ``v''" Ta "167\ ``w''" Ta "170\ ``x''" Ta "171=
\ ``y''"
+.It "\&172\ ``z''" Ta "173\ ``{''" Ta "174\ ``|''" Ta "175\ ``}''" Ta "176=
\ ``~''"
 .El
 .Sh RETURN VALUES
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/ispunct.3
--- a/head/lib/libc/locale/ispunct.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/ispunct.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)ispunct.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/locale/ispunct.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISPUNCT 3
@@ -60,15 +60,14 @@
 .Pp
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
-.Pp
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&041\ ``!'' \t042\ ``""'' \t043\ ``#'' \t044\ ``$'' \t045\ ``%''"
-.It "\&046\ ``&'' \t047\ ``''' \t050\ ``('' \t051\ ``)'' \t052\ ``*''"
-.It "\&053\ ``+'' \t054\ ``,'' \t055\ ``-'' \t056\ ``.'' \t057\ ``/''"
-.It "\&072\ ``:'' \t073\ ``;'' \t074\ ``<'' \t075\ ``=3D'' \t076\ ``>''"
-.It "\&077\ ``?'' \t100\ ``@'' \t133\ ``['' \t134\ ``\e\|'' \t135\ ``]''"
-.It "\&136\ ``^'' \t137\ ``_'' \t140\ ```'' \t173\ ``{'' \t174\ ``|''"
-.It "\&175\ ``}'' \t176\ ``~''"
+.It "\&041\ ``!''" Ta "042\ ``""''" Ta "043\ ``#''" Ta "044\ ``$''" Ta "04=
5\ ``%''"
+.It "\&046\ ``&''" Ta "047\ ``'''" Ta "050\ ``(''" Ta "051\ ``)''" Ta "052=
\ ``*''"
+.It "\&053\ ``+''" Ta "054\ ``,''" Ta "055\ ``-''" Ta "056\ ``.''" Ta "057=
\ ``/''"
+.It "\&072\ ``:''" Ta "073\ ``;''" Ta "074\ ``<''" Ta "075\ ``=3D''" Ta "0=
76\ ``>''"
+.It "\&077\ ``?''" Ta "100\ ``@''" Ta "133\ ``[''" Ta "134\ ``\e\|''" Ta "=
135\ ``]''"
+.It "\&136\ ``^''" Ta "137\ ``_''" Ta "140\ ```''" Ta "173\ ``{''" Ta "174=
\ ``|''"
+.It "\&175\ ``}''" Ta "176\ ``~''" Ta \& Ta \& Ta \&
 .El
 .Sh RETURN VALUES
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isspace.3
--- a/head/lib/libc/locale/isspace.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isspace.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isspace.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/locale/isspace.3 225808 2011-09-27 17:54:10Z s=
chweikh $
+.\" $FreeBSD: head/lib/libc/locale/isspace.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISSPACE 3
@@ -49,9 +49,8 @@
 .Fn isspace
 function tests for white-space characters.
 For any locale, this includes the following standard characters:
-.Pp
 .Bl -column \&`\et''___ \&``\et''___ \&``\et''___ \&``\et''___ \&``\et''__=
_ \&``\et''___
-.It "\&``\et''\t``\en''\t``\ev''\t``\ef''\t``\er''\t`` ''"
+.It "\&``\et''" Ta "``\en''" Ta "``\ev''" Ta "``\ef''" Ta "``\er''" Ta "``=
 ''"
 .El
 .Pp
 In the "C" locale,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isupper.3
--- a/head/lib/libc/locale/isupper.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isupper.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isupper.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/locale/isupper.3 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd July 17, 2005
 .Dt ISUPPER 3
@@ -55,14 +55,13 @@
 .Pp
 In the ASCII character set, this includes the following characters
 (with their numeric values shown in octal):
-.Pp
 .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_=
``0''__
-.It "\&101\ ``A'' \t102\ ``B'' \t103\ ``C'' \t104\ ``D'' \t105\ ``E''"
-.It "\&106\ ``F'' \t107\ ``G'' \t110\ ``H'' \t111\ ``I'' \t112\ ``J''"
-.It "\&113\ ``K'' \t114\ ``L'' \t115\ ``M'' \t116\ ``N'' \t117\ ``O''"
-.It "\&120\ ``P'' \t121\ ``Q'' \t122\ ``R'' \t123\ ``S'' \t124\ ``T''"
-.It "\&125\ ``U'' \t126\ ``V'' \t127\ ``W'' \t130\ ``X'' \t131\ ``Y''"
-.It "\&132\ ``Z''"
+.It "\&101\ ``A''" Ta "102\ ``B''" Ta "103\ ``C''" Ta "104\ ``D''" Ta "105=
\ ``E''"
+.It "\&106\ ``F''" Ta "107\ ``G''" Ta "110\ ``H''" Ta "111\ ``I''" Ta "112=
\ ``J''"
+.It "\&113\ ``K''" Ta "114\ ``L''" Ta "115\ ``M''" Ta "116\ ``N''" Ta "117=
\ ``O''"
+.It "\&120\ ``P''" Ta "121\ ``Q''" Ta "122\ ``R''" Ta "123\ ``S''" Ta "124=
\ ``T''"
+.It "\&125\ ``U''" Ta "126\ ``V''" Ta "127\ ``W''" Ta "130\ ``X''" Ta "131=
\ ``Y''"
+.It "\&132\ ``Z''" Ta \& Ta \& Ta \& Ta \&
 .El
 .Sh RETURN VALUES
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/isxdigit.3
--- a/head/lib/libc/locale/isxdigit.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/isxdigit.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)isxdigit.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/locale/isxdigit.3 233992 2012-04-07 09:05:30Z =
joel $
 .\"
 .Dd July 17, 2005
 .Dt ISXDIGIT 3
@@ -51,13 +51,12 @@
 .Fn isxdigit
 function tests for any hexadecimal-digit character.
 Regardless of locale, this includes the following characters only:
-.Pp
 .Bl -column \&``0''______ \&``0''______ \&``0''______ \&``0''______ \&``0'=
'______
-.It "\&``0''\t``1''\t``2''\t``3''\t``4''"
-.It "\&``5''\t``6''\t``7''\t``8''\t``9''"
-.It "\&``A''\t``B''\t``C''\t``D''\t``E''"
-.It "\&``F''\t``a''\t``b''\t``c''\t``d''"
-.It "\&``e''\t``f''"
+.It "\&``0''" Ta "``1''" Ta "``2''" Ta "``3''" Ta "``4''"
+.It "\&``5''" Ta "``6''" Ta "``7''" Ta "``8''" Ta "``9''"
+.It "\&``A''" Ta "``B''" Ta "``C''" Ta "``D''" Ta "``E''"
+.It "\&``F''" Ta "``a''" Ta "``b''" Ta "``c''" Ta "``d''"
+.It "\&``e''" Ta "``f''" Ta \& Ta \& Ta \&
 .El
 .Pp
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/newlocale.3
--- a/head/lib/libc/locale/newlocale.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/newlocale.3	Tue Apr 17 11:51:51 2012 +0300
@@ -25,9 +25,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/newlocale.3 228199 2011-12-02 11:55:09Z=
 obrien $
+.\" $FreeBSD: head/lib/libc/locale/newlocale.3 233994 2012-04-07 09:26:21Z=
 joel $
 .Dd September 17 2011
-.Dt newlocale 3
+.Dt NEWLOCALE 3
 .Os
 .Sh NAME
 .Nm newlocale
@@ -36,7 +36,7 @@
 .Lb libc
 .Sh SYNOPSIS
 .In xlocale
-.Ft
+.Ft locale_t
 .Fn newlocale "int mask" "const char * locale" "locale_t base"
 .Sh DESCRIPTION
 Creates a new locale, inheriting some properties from an existing locale.
@@ -48,7 +48,6 @@
 parameter.
 Any other components will be inherited from
 .Fa base .
-.Pt
 The
 .Fa mask
 is either
@@ -93,7 +92,6 @@
 .Xr strftime 3
 function.
 .El
-
 This function uses the same rules for loading locale components as
 .Xr setlocale 3 .
 .Sh RETURN VALUES
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/locale/xlocale.3
--- a/head/lib/libc/locale/xlocale.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/locale/xlocale.3	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/xlocale.3 228199 2011-12-02 11:55:09Z o=
brien $
+.\" $FreeBSD: head/lib/libc/locale/xlocale.3 233466 2012-03-25 16:00:56Z j=
oel $
 .\"
 .Dd September 17 2011
 .Dt XLOCALE 3
@@ -65,21 +65,6 @@
 The global locale is the locale set with the
 .Xr setlocale 3
 function.
-.Sh CAVEATS
-The
-.Xr setlocale 3
-function, and others in the family, refer to the global locale.
-Other functions that depend on the locale, however,
-will take the thread-local locale if one has been set.
-This means that the idiom of setting the locale using
-.Xr setlocale 3 ,
-calling a locale-dependent function,
-and then restoring the locale will not
-have the expected behavior if the current thread has had a locale set using
-.Xr uselocale 3 .
-You should avoid this idiom and prefer to use the
-.Fa _l
-suffixed versions instead.
 .Sh SEE ALSO
 .Xr duplocale 3 ,
 .Xr freelocale 3 ,
@@ -118,7 +103,6 @@
 For reference,
 a complete list of the locale-aware functions that are available in this f=
orm,
 along with the headers that expose them, is provided here:
-.Pp
 .Bl -tag -width "<monetary.h> "
 .It In wctype.h
 .Xr iswalnum_l 3 ,
@@ -279,3 +263,18 @@
 This implementation was written by David Chisnall,
 under sponsorship from the FreeBSD Foundation and first appeared in
 .Fx 9.1 .
+.Sh CAVEATS
+The
+.Xr setlocale 3
+function, and others in the family, refer to the global locale.
+Other functions that depend on the locale, however,
+will take the thread-local locale if one has been set.
+This means that the idiom of setting the locale using
+.Xr setlocale 3 ,
+calling a locale-dependent function,
+and then restoring the locale will not
+have the expected behavior if the current thread has had a locale set using
+.Xr uselocale 3 .
+You should avoid this idiom and prefer to use the
+.Fa _l
+suffixed versions instead.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/getaddrinfo.c
--- a/head/lib/libc/net/getaddrinfo.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/getaddrinfo.c	Tue Apr 17 11:51:51 2012 +0300
@@ -54,7 +54,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/net/getaddrinfo.c 229766 2012-01-07 09:0=
1:19Z ume $");
+__FBSDID("$FreeBSD: head/lib/libc/net/getaddrinfo.c 233770 2012-04-02 07:4=
2:17Z delphij $");
=20
 #include "namespace.h"
 #include <sys/types.h>
@@ -847,8 +847,6 @@
 		struct in6_ifreq ifr6;
 		u_int32_t flags6;
=20
-		/* XXX: interface name should not be hardcoded */
-		strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name));
 		memset(&ifr6, 0, sizeof(ifr6));
 		memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
 		if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) =3D=3D 0) {
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/getipnodebyname.3
--- a/head/lib/libc/net/getipnodebyname.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/getipnodebyname.3	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)gethostbyname.3	8.4 (Berkeley) 5/25/95
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/getipnodebyname.3 233522 2012-03-26 21:22:=
53Z joel $
 .\"
 .Dd August 6, 2004
 .Dt GETIPNODEBYNAME 3
@@ -108,13 +108,13 @@
 (defined below)
 should handle most applications.
 That is, porting simple applications to use IPv6 replaces the call
-.Bd -literal -offset
-   hptr =3D gethostbyname(name);
+.Bd -literal -offset indent
+hptr =3D gethostbyname(name);
 .Ed
 .Pp
 with
-.Bd -literal -offset
-   hptr =3D getipnodebyname(name, AF_INET6, AI_DEFAULT, &error_num);
+.Bd -literal -offset indent
+hptr =3D getipnodebyname(name, AF_INET6, AI_DEFAULT, &error_num);
 .Ed
 .Pp
 Applications desiring finer control over the types of addresses
@@ -270,8 +270,8 @@
 The special flags value of
 .Dv AI_DEFAULT
 is defined as
-.Bd -literal -offset
-   #define  AI_DEFAULT  (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
+.Bd -literal -offset indent
+#define  AI_DEFAULT  (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
 .Ed
 .Pp
 We noted that the
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/if_nametoindex.c
--- a/head/lib/libc/net/if_nametoindex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/if_nametoindex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/net/if_nametoindex.c 234329 2012-04-15 2=
3:56:03Z eadler $");
=20
 #include "namespace.h"
 #include <sys/types.h>
@@ -70,6 +70,9 @@
=20
 	s =3D _socket(AF_INET, SOCK_DGRAM, 0);
 	if (s !=3D -1) {
+#ifdef PURIFY
+		memset(&ifr, 0, sizeof(ifr));
+#endif
 		strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
 		if (_ioctl(s, SIOCGIFINDEX, &ifr) !=3D -1) {
 			_close(s);
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/inet_net.3
--- a/head/lib/libc/net/inet_net.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/inet_net.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/inet_net.3 233462 2012-03-25 12:13:24Z joe=
l $
 .\"
 .Dd February 26, 2006
 .Dt INET_NET 3
@@ -95,7 +95,6 @@
 argument
 is the size of the result buffer
 .Fa dst .
-.Pp
 .Sh NETWORK NUMBERS (IP VERSION 4)
 Internet network numbers may be specified in one of the following forms:
 .Bd -literal -offset indent
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/name6.c
--- a/head/lib/libc/net/name6.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/name6.c	Tue Apr 17 11:51:51 2012 +0300
@@ -88,7 +88,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/net/name6.c 233770 2012-04-02 07:42:17Z =
delphij $");
=20
 #include "namespace.h"
 #include <sys/param.h>
@@ -884,8 +884,6 @@
 		struct in6_ifreq ifr6;
 		u_int32_t flags6;
=20
-		/* XXX: interface name should not be hardcoded */
-		strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name));
 		memset(&ifr6, 0, sizeof(ifr6));
 		memcpy(&ifr6.ifr_addr, &ss, ss.ss_len);
 		if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) =3D=3D 0) {
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/nsdispatch.3
--- a/head/lib/libc/net/nsdispatch.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/nsdispatch.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/net/nsdispatch.3 231564 2012-02-12 18:29:56Z e=
d $
+.\" $FreeBSD: head/lib/libc/net/nsdispatch.3 233576 2012-03-27 20:39:49Z j=
oel $
 .\"
 .Dd April 4, 2010
 .Dt NSDISPATCH 3
@@ -85,7 +85,7 @@
 	void		*mdata;
 } ns_dtab;
 .Ed
-.Bd -ragged -offset indent
+.Pp
 The
 .Fa dtab
 array should consist of one entry for each source type that is
@@ -105,7 +105,6 @@
 .Va method ,
 and
 .Va mdata .
-.Ed
 .Pp
 Additionally, methods may be implemented in NSS modules, in
 which case they are selected using the
@@ -132,7 +131,7 @@
 	uint32_t	 flags;
 } ns_src;
 .Ed
-.Bd -ragged -offset indent
+.Pp
 The
 .Fa defaults
 array should consist of one entry for each source to be configured by
@@ -157,12 +156,13 @@
 set to 0.
 .Pp
 For convenience, a global variable defined as:
+.Pp
 .Dl extern const ns_src __nsdefaultsrc[];
+.Pp
 exists which contains a single default entry for the source
 .Sq files
 that may be used by callers which do not require complicated default
 rules.
-.Ed
 .Pp
 .Sq Va ...
 are optional extra arguments, which are passed to the appropriate method
@@ -183,7 +183,6 @@
 Refer to
 .Xr nsswitch.conf 5
 for a complete description of what each source type is.
-.Pp
 .Ss Method return values
 The
 .Vt nss_method
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_bindx.3
--- a/head/lib/libc/net/sctp_bindx.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_bindx.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)send.2	8.2 (Berkeley) 2/21/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_bindx.3 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd December 15, 2006
 .Dt SCTP_BINDX 3
@@ -55,7 +55,7 @@
 addresses.
 The
 .Fn sctp_bindx
-call operates similarly to=20
+call operates similarly to
 .Fn bind
 but allows a list of addresses and also allows a bind or an
 unbind.
@@ -98,7 +98,7 @@
 field is not one of the allowed values (see above).
 .It Bq Er ENOMEM
 This value is returned if the number of addresses
-being added causes a memory allocation failure in=20
+being added causes a memory allocation failure in
 the call.
 .It Bq Er EBADF
 The argument
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_connectx.3
--- a/head/lib/libc/net/sctp_connectx.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_connectx.3	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_connectx.3 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd June 19, 2007
 .Dt SCTP_CONNECTX 3
@@ -58,18 +58,18 @@
 of initiating an association.
 When one of the peers addresses
 is unreachable, the subsequent listed addresses will also be used
-to set up the association with the peer.=20
+to set up the association with the peer.
 .Pp
-The user also needs to consider that any address listed in an=20
+The user also needs to consider that any address listed in an
 .Fn sctp_connectx
 call is also considered "confirmed".
 A confirmed address is one in
 which the SCTP transport will trust is a part of the association
 and it will not send a confirmation heartbeat to it with
-a random nonce.=20
+a random nonce.
 .Pp
 If the peer SCTP stack does not list one or more of
-the provided addresses in its response message then=20
+the provided addresses in its response message then
 the extra addresses sent in the
 .Fn sctp_connectx
 call will be silently discarded from the association.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_freepaddrs.3
--- a/head/lib/libc/net/sctp_freepaddrs.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_freepaddrs.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)send.2	8.2 (Berkeley) 2/21/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_freepaddrs.3 233648 2012-03-29 05:02:=
12Z eadler $
 .\"
 .Dd December 15, 2006
 .Dt SCTP_FREEPADDRS 3
@@ -46,9 +46,9 @@
 .In sys/socket.h
 .In netinet/sctp.h
 .Ft void
-.Fn sctp_freepaddrs "struct sockaddr *"=20
+.Fn sctp_freepaddrs "struct sockaddr *"
 .Ft void
-.Fn sctp_freeladdrs "struct sockaddr *"=20
+.Fn sctp_freeladdrs "struct sockaddr *"
 .Sh DESCRIPTION
 The
 .Fn sctp_freepaddrs
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_getaddrlen.3
--- a/head/lib/libc/net/sctp_getaddrlen.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_getaddrlen.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)send.2	8.2 (Berkeley) 2/21/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_getaddrlen.3 233648 2012-03-29 05:02:=
12Z eadler $
 .\"
 .Dd December 15, 2006
 .Dt SCTP_GETADDRLEN 3
@@ -62,7 +62,7 @@
 If for some reason a SCTP socket cannot
 be created or the
 .Fn getsockopt
-call fails, an error will be returned=20
+call fails, an error will be returned
 with
 .Va errno
 set as specified in the
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_getassocid.3
--- a/head/lib/libc/net/sctp_getassocid.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_getassocid.3	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_getassocid.3 233648 2012-03-29 05:02:=
12Z eadler $
 .\"
 .Dd December 15, 2006
 .Dt SCTP_GETASSOCID 3
@@ -50,8 +50,7 @@
 .Fn sctp_getassocid
 call attempts to look up the specified socket address
 .Fa addr
-and find the respective association identification.=20
-.Pp
+and find the respective association identification.
 .Sh RETURN VALUES
 The call returns the association id upon success and
 0 is returned upon failure.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_getpaddrs.3
--- a/head/lib/libc/net/sctp_getpaddrs.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_getpaddrs.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)send.2	8.2 (Berkeley) 2/21/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_getpaddrs.3 233648 2012-03-29 05:02:1=
2Z eadler $
 .\"
 .Dd December 15, 2006
 .Dt SCTP_GETPADDRS 3
@@ -53,7 +53,7 @@
 The
 .Fn sctp_getpaddrs
 function is used to get the list of the peers addresses.
-The=20
+The
 .Fn sctp_getladdrs
 function is used to get the list of the local addresses.
 The association of interest is identified by the
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_opt_info.3
--- a/head/lib/libc/net/sctp_opt_info.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_opt_info.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)send.2	8.2 (Berkeley) 2/21/94
-.\" $FreeBSD: head/lib/libc/net/sctp_opt_info.3 223225 2011-06-18 10:36:05=
Z tuexen $
+.\" $FreeBSD: head/lib/libc/net/sctp_opt_info.3 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd June 18, 2011
 .Dt SCTP_OPT_INFO 3
@@ -50,7 +50,7 @@
 The
 .Fn sctp_opt_info
 call provides a multi-os compatible method for getting
-specific=20
+specific
 .Fn getsockopt
 data where an association identification needs to be passed
 into the operating system.
@@ -70,7 +70,7 @@
 this call should be used for the following SCTP
 socket options.
 .Pp
-.Dv SCTP_RTOINFO=20
+.Dv SCTP_RTOINFO
 .Pp
 .Dv SCTP_ASSOCINFO
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_recvmsg.3
--- a/head/lib/libc/net/sctp_recvmsg.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_recvmsg.3	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_recvmsg.3 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd August 13, 2007
 .Dt SCTP_RECVMSG 3
@@ -56,11 +56,11 @@
 The
 .Fn sctp_recvmsg
 call is used by one-to-one (SOCK_STREAM) type sockets after a
-successful=20
+successful
 .Fn connect
-call or after the application has performed a=20
-.Fn listen=20
-followed by a successful=20
+call or after the application has performed a
+.Fn listen
+followed by a successful
 .Fn accept .
 For a one-to-many (SOCK_SEQPACKET) type socket, an endpoint may call
 .Fn sctp_recvmsg
@@ -77,7 +77,7 @@
 .Pp
 The address of the sender is held in the
 .Fa from
-argument with=20
+argument with
 .Fa fromlen
 specifying its size.
 At the completion of a successful
@@ -88,16 +88,16 @@
 .Fa fromlen
 will hold the length of that address.
 Note that
-the address is bounded by the initial value of=20
+the address is bounded by the initial value of
 .Fa fromlen
 which is used as an in/out variable.
 .Pp
-The length of the message=20
+The length of the message
 .Fa msg
 to be received is bounded by
 .Fa len .
 If the message is too long to fit in the users
-receive buffer, then the=20
+receive buffer, then the
 .Fa flags
 argument will
 .Em not
@@ -105,16 +105,16 @@
 .Dv MSG_EOF
 flag applied.
 If the message is a complete message then
-the=20
+the
 .Fa flags
 argument will have
 .Dv MSG_EOF
 set.
-Locally detected errors are=20
+Locally detected errors are
 indicated by a return value of -1 with
 .Va errno
 set accordingly.
-The=20
+The
 .Fa flags
 argument may also hold the value
 .Dv MSG_NOTIFICATION .
@@ -141,7 +141,7 @@
 system call may be used to determine when it is possible to
 receive a message.
 .Pp
-The=20
+The
 .Fa sinfo
 argument is defined as follows.
 .Bd -literal
@@ -161,7 +161,7 @@
 The
 .Fa sinfo->sinfo_ppid
 field is an opaque 32 bit value that is passed transparently
-through the stack from the peer endpoint.=20
+through the stack from the peer endpoint.
 Note that the stack passes this value without regard to byte
 order.
 .Pp
@@ -182,7 +182,7 @@
 .Pp
 The
 .Fa sinfo->sinfo_stream
-field is the SCTP stream that the message was received on.=20
+field is the SCTP stream that the message was received on.
 Streams in SCTP are reliable (or partially reliable) flows of ordered
 messages.
 .Pp
@@ -194,7 +194,7 @@
 socket option.
 Optionally a user process can use this value to index some application
 specific data structure for all data coming from a specific
-association.=20
+association.
 .Pp
 The
 .Fa sinfo->sinfo_ssn
@@ -230,12 +230,12 @@
 the use of an address field.
 It is also quite useful in
 setting various socket options on the specific association
-(see=20
+(see
 .Xr sctp 4 ) .
 .Pp
 The
 .Fa sinfo->info_timetolive
-field is not used by=20
+field is not used by
 .Fn sctp_recvmsg .
 .Sh RETURN VALUES
 The call returns the number of bytes received, or -1
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_send.3
--- a/head/lib/libc/net/sctp_send.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_send.3	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_send.3 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd December 15, 2006
 .Dt SCTP_SEND 3
@@ -62,14 +62,14 @@
 .Fn sctp_send
 may be used to send data to an existing association for both
 one-to-many (SOCK_SEQPACKET) and one-to-one (SOCK_STREAM) socket types.
-The length of the message=20
+The length of the message
 .Fa msg
 is given by
 .Fa len .
 If the message is too long to pass atomically through the
 underlying protocol,
 .Va errno
-is set to=20
+is set to
 .Er EMSGSIZE ,
 -1 is returned, and
 the message is not transmitted.
@@ -88,7 +88,7 @@
 system call may be used to determine when it is possible to
 send more data on one-to-one type (SOCK_STREAM) sockets.
 .Pp
-The=20
+The
 .Fa sinfo
 structure is used to control various SCTP features
 and has the following format:
@@ -106,7 +106,7 @@
 };
 .Ed
 .Pp
-The=20
+The
 .Fa sinfo->sinfo_ppid
 argument is an opaque 32 bit value that is passed transparently
 through the stack to the peer endpoint. It will be available on
@@ -131,7 +131,7 @@
 #define SCTP_PR_SCTP_RTX  0x0003	/* Number of retransmissions based PR-SCT=
P */
 .Ed
 .Pp
-The flag=20
+The flag
 .Dv SCTP_EOF
 is used to instruct the SCTP stack to queue this message
 and then start a graceful shutdown of the association.
@@ -158,7 +158,7 @@
 Normally
 SCTP will use only one of a multi-homed peers addresses as the primary
 address to send to.
-By default, no matter what the=20
+By default, no matter what the
 .Fa to
 argument is, this primary address is used to send data.
 By specifying
@@ -193,14 +193,14 @@
 Note that this policy does
 not even assure that the data will ever be sent.
 In times of a congestion
-with large amounts of data being queued, the=20
+with large amounts of data being queued, the
 .Fa sinfo->sinfo_timetolive
 may expire before the first transmission is ever made.
 .Pp
 The
 .Dv SCTP_PR_SCTP_BUF
 based policy transforms the
-.Fa sinfo->sinfo_timetolive=20
+.Fa sinfo->sinfo_timetolive
 field into a total number of bytes allowed on the outbound
 send queue.
 If that number or more bytes are in queue, then
@@ -208,19 +208,19 @@
 skipped.
 Note that this policy may also result in the data
 never being sent if no buffer based sends are in queue and
-the maximum specified by=20
-.Fa timetolive=20
+the maximum specified by
+.Fa timetolive
 bytes is in queue.
 .Pp
 The
 .Dv SCTP_PR_SCTP_RTX
 policy transforms the
-.Fa sinfo->sinfo_timetolive=20
+.Fa sinfo->sinfo_timetolive
 into a number of retransmissions to allow.
 This policy
 always assures that at a minimum one send attempt is
 made of the data.
-After which no more than=20
+After which no more than
 .Fa sinfo->sinfo_timetolive
 retransmissions will be made before the data is skipped.
 .Pp
@@ -228,11 +228,11 @@
 is the SCTP stream that you wish to send the
 message on.
 Streams in SCTP are reliable (or partially reliable) flows of ordered
-messages.=20
+messages.
 .Pp
 The
 .Fa sinfo->sinfo_assoc_id
-field is used to=20
+field is used to
 select the association to send to on a one-to-many socket.
 For a one-to-one socket, this field is ignored.
 .Pp
@@ -256,16 +256,16 @@
 .Fa sinfo->sinfo_ssn ,
 .Fa sinfo->sinfo_tsn ,
 and
-.Fa sinfo->sinfo_cumtsn=20
+.Fa sinfo->sinfo_cumtsn
 are used only when receiving messages and are thus ignored by
 .Fn sctp_send .
 The function
-.Fn sctp_sendx=20
-has the same properties as=20
+.Fn sctp_sendx
+has the same properties as
 .Fn sctp_send
 with the additional arguments of an array of sockaddr structures
 passed in.
-With the=20
+With the
 .Fa addrs
 argument being given as an array of addresses to be sent to and
 the
@@ -277,7 +277,7 @@
 This allows the
 user the equivalent behavior as doing a
 .Fn sctp_connectx
-followed by a=20
+followed by a
 .Fn sctp_send
 to the association.
 Note that if the
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sctp_sendmsg.3
--- a/head/lib/libc/net/sctp_sendmsg.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sctp_sendmsg.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)send.2	8.2 (Berkeley) 2/21/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sctp_sendmsg.3 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd December 15, 2006
 .Dt SCTP_SENDMSG 3
@@ -72,10 +72,10 @@
 the data being sent on the third leg of the SCTP four-way handshake.
 Note that if
 the socket is a one-to-one type (SOCK_STREAM) socket then an association m=
ust
-be in existence (by use of the=20
+be in existence (by use of the
 .Xr connect 2
 system call).
-Calling=20
+Calling
 .Fn sctp_sendmsg
 or
 .Fn sctp_sendmsgx
@@ -90,14 +90,14 @@
 with
 .Fa tolen
 specifying its size.
-The length of the message=20
+The length of the message
 .Fa msg
 is given by
 .Fa len .
 If the message is too long to pass atomically through the
 underlying protocol,
 .Va errno
-is set to=20
+is set to
 .Er EMSGSIZE ,
 -1 is returned, and
 the message is not transmitted.
@@ -117,7 +117,7 @@
 system call may be used to determine when it is possible to
 send more data on one-to-one type (SOCK_STREAM) sockets.
 .Pp
-The=20
+The
 .Fa ppid
 argument is an opaque 32 bit value that is passed transparently
 through the stack to the peer endpoint.
@@ -143,7 +143,7 @@
 #define SCTP_PR_SCTP_RTX  0x0003	/* Number of retransmissions based PR-SCT=
P */
 .Ed
 .Pp
-The flag=20
+The flag
 .Dv SCTP_EOF
 is used to instruct the SCTP stack to queue this message
 and then start a graceful shutdown of the association.
@@ -170,7 +170,7 @@
 Normally
 SCTP will use only one of a multi-homed peers addresses as the primary
 address to send to.
-By default, no matter what the=20
+By default, no matter what the
 .Fa to
 argument is, this primary address is used to send data.
 By specifying
@@ -205,14 +205,14 @@
 Note that this policy does
 not even assure that the data will ever be sent.
 In times of a congestion
-with large amounts of data being queued, the=20
+with large amounts of data being queued, the
 .Fa timetolive
 may expire before the first transmission is ever made.
 .Pp
 The
 .Dv SCTP_PR_SCTP_BUF
 based policy transforms the
-.Fa timetolive=20
+.Fa timetolive
 field into a total number of bytes allowed on the outbound
 send queue.
 If that number or more bytes are in queue, then
@@ -220,19 +220,19 @@
 skipped.
 Note that this policy may also result in the data
 never being sent if no buffer based sends are in queue and
-the maximum specified by=20
-.Fa timetolive=20
+the maximum specified by
+.Fa timetolive
 bytes is in queue.
 .Pp
 The
 .Dv SCTP_PR_SCTP_RTX
 policy transforms the
-.Fa timetolive=20
+.Fa timetolive
 into a number of retransmissions to allow.
 This policy
 always assures that at a minimum one send attempt is
 made of the data.
-After which no more than=20
+After which no more than
 .Fa timetolive
 retransmissions will be made before the data is skipped.
 .Pp
@@ -241,7 +241,7 @@
 message on.
 Streams in SCTP are reliable (or partially reliable) flows of ordered
 messages.
-The=20
+The
 .Fa context
 field is used only in the event the message cannot be sent.
 This is an opaque
@@ -251,7 +251,7 @@
 Normally a user process can use this value to index some application
 specific data structure when a send cannot be fulfilled.
 .Fn sctp_sendmsgx
-is identical to=20
+is identical to
 .Fn sctp_sendmsg
 with the exception that it takes an array of sockaddr structures in the
 argument
@@ -262,7 +262,7 @@
 This allows a
 caller to implicitly set up an association passing multiple addresses
 as if
-.Fn sctp_connectx=20
+.Fn sctp_connectx
 had been called to set up the association.
 .Sh RETURN VALUES
 The call returns the number of characters sent, or -1
@@ -325,7 +325,7 @@
 .Xr sctp 4
 .Sh BUGS
 Because in the one-to-many style socket
-.Fn sctp_sendmsg=20
+.Fn sctp_sendmsg
 or
 .Fn sctp_sendmsgx
 may have multiple associations under one endpoint, a
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/net/sourcefilter.3
--- a/head/lib/libc/net/sourcefilter.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/net/sourcefilter.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/net/sourcefilter.3 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd February 13, 2009
 .Dt SOURCEFILTER 3
@@ -220,7 +220,7 @@
 .Sh SEE ALSO
 .Xr ip 4 ,
 .Xr ip6 4 ,
-.Xr multicast 4,=20
+.Xr multicast 4,
 .Xr ifmcstat 8
 .Rs
 .%A D. Thaler
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/posix1e/acl_add_flag_np.3
--- a/head/lib/libc/posix1e/acl_add_flag_np.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/posix1e/acl_add_flag_np.3	Tue Apr 17 11:51:51 2012 +0300
@@ -23,14 +23,14 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/posix1e/acl_add_flag_np.3 233665 2012-03-29 16=
:02:40Z joel $
 .\"
 .Dd June 25, 2009
 .Dt ACL_ADD_FLAG_NP 3
 .Os
 .Sh NAME
 .Nm acl_add_flag_np
-.Nd add flags to a flagset=20
+.Nd add flags to a flagset
 .Sh LIBRARY
 .Lb libc
 .Sh SYNOPSIS
@@ -52,10 +52,10 @@
 .Pp
 Valid values are:
 .Bl -column -offset 3n "ACL_ENTRY_NO_PROPAGATE_INHERIT"
-.It ACL_ENTRY_FILE_INHERIT		Will be inherited by files.
-.It ACL_ENTRY_DIRECTORY_INHERIT	Will be inherited by directories.
-.It ACL_ENTRY_NO_PROPAGATE_INHERIT	Will not propagate.
-.It ACL_ENTRY_INHERIT_ONLY		Inherit-only.
+.It ACL_ENTRY_FILE_INHERIT Ta "Will be inherited by files."
+.It ACL_ENTRY_DIRECTORY_INHERIT Ta "Will be inherited by directories."
+.It ACL_ENTRY_NO_PROPAGATE_INHERIT Ta "Will not propagate."
+.It ACL_ENTRY_INHERIT_ONLY Ta "Inherit-only."
 .El
 .Sh RETURN VALUES
 .Rv -std acl_add_flag_np
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/posix1e/acl_add_perm.3
--- a/head/lib/libc/posix1e/acl_add_perm.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/posix1e/acl_add_perm.3	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/posix1e/acl_add_perm.3 233665 2012-03-29 16:02=
:40Z joel $
 .\"
 .Dd June 25, 2009
 .Dt ACL_ADD_PERM 3
@@ -59,22 +59,22 @@
 .Pp
 For NFSv4 ACLs, valid values are:
 .Bl -column -offset 3n "ACL_WRITE_NAMED_ATTRS"
-.It ACL_READ_DATA		Read permission
-.It ACL_LIST_DIRECTORY		Same as ACL_READ_DATA
-.It ACL_WRITE_DATA		Write permission, or permission to create files
-.It ACL_ADD_FILE		Same as ACL_READ_DATA
-.It ACL_APPEND_DATA		Permission to create directories.  Ignored for files
-.It ACL_ADD_SUBDIRECTORY	Same as ACL_APPEND_DATA
-.It ACL_READ_NAMED_ATTRS	Ignored
-.It ACL_WRITE_NAMED_ATTRS	Ignored
-.It ACL_EXECUTE			Execute permission
-.It ACL_DELETE_CHILD		Permission to delete files and subdirectories
-.It ACL_READ_ATTRIBUTES		Permission to read basic attributes
-.It ACL_WRITE_ATTRIBUTES	Permission to change basic attributes
-.It ACL_DELETE			Permission to delete the object this ACL is placed on
-.It ACL_READ_ACL		Permission to read ACL
-.It ACL_WRITE_ACL		Permission to change the ACL and file mode
-.It ACL_SYNCHRONIZE		Ignored
+.It ACL_READ_DATA Ta "Read permission"
+.It ACL_LIST_DIRECTORY Ta "Same as ACL_READ_DATA"
+.It ACL_WRITE_DATA Ta "Write permission, or permission to create files"
+.It ACL_ADD_FILE Ta "Same as ACL_READ_DATA"
+.It ACL_APPEND_DATA Ta "Permission to create directories.  Ignored for fil=
es"
+.It ACL_ADD_SUBDIRECTORY Ta "Same as ACL_APPEND_DATA"
+.It ACL_READ_NAMED_ATTRS Ta "Ignored"
+.It ACL_WRITE_NAMED_ATTRS Ta "Ignored"
+.It ACL_EXECUTE Ta "Execute permission"
+.It ACL_DELETE_CHILD Ta "Permission to delete files and subdirectories"
+.It ACL_READ_ATTRIBUTES Ta "Permission to read basic attributes"
+.It ACL_WRITE_ATTRIBUTES Ta "Permission to change basic attributes"
+.It ACL_DELETE Ta "Permission to delete the object this ACL is placed on"
+.It ACL_READ_ACL Ta "Permission to read ACL"
+.It ACL_WRITE_ACL Ta "Permission to change the ACL and file mode"
+.It ACL_SYNCHRONIZE Ta "Ignored"
 .El
 .Pp
 Calling
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/posix1e/acl_create_entry=
.3
--- a/head/lib/libc/posix1e/acl_create_entry.3	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/lib/libc/posix1e/acl_create_entry.3	Tue Apr 17 11:51:51 2012 +03=
00
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/posix1e/acl_create_entry.3 233648 2012-03-29 0=
5:02:12Z eadler $
 .\"
 .Dd June 25, 2009
 .Dt ACL_CREATE_ENTRY 3
@@ -39,7 +39,7 @@
 .In sys/acl.h
 .Ft int
 .Fn acl_create_entry "acl_t *acl_p" "acl_entry_t *entry_p"
-.Ft int=20
+.Ft int
 .Fn acl_create_entry_np "acl_t *acl_p" "acl_entry_t *entry_p" "int index"
 .Sh DESCRIPTION
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/posix1e/acl_set_entry_ty=
pe_np.3
--- a/head/lib/libc/posix1e/acl_set_entry_type_np.3	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/lib/libc/posix1e/acl_set_entry_type_np.3	Tue Apr 17 11:51:51 201=
2 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/posix1e/acl_set_entry_type_np.3 233665 2012-03=
-29 16:02:40Z joel $
 .\"
 .Dd June 25, 2009
 .Dt ACL_SET_ENTRY_TYPE_NP 3
@@ -49,8 +49,8 @@
 .Pp
 Valid values are:
 .Bl -column -offset 3n "ACL_ENTRY_TYPE_ALLOW"
-.It ACL_ENTRY_TYPE_ALLOW	"allow" type entry
-.It ACL_ENTRY_TYPE_DENY		"deny" type entry
+.It ACL_ENTRY_TYPE_ALLOW Ta "allow" type entry
+.It ACL_ENTRY_TYPE_DENY Ta "deny" type entry
 .El
 .Pp
 This call brands the ACL as NFSv4.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/posix1e/acl_set_tag_type=
.3
--- a/head/lib/libc/posix1e/acl_set_tag_type.3	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/lib/libc/posix1e/acl_set_tag_type.3	Tue Apr 17 11:51:51 2012 +03=
00
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/posix1e/acl_set_tag_type.3 233665 2012-03-29 1=
6:02:40Z joel $
 .\"
 .Dd June 25, 2009
 .Dt ACL_SET_TAG_TYPE 3
@@ -49,14 +49,14 @@
 .Pp
 Valid values are:
 .Bl -column -offset 3n "ACL_OTHER_OBJ"
-.It ACL_USER_OBJ	Permissions apply to file owner
-.It ACL_USER		Permissions apply to additional user specified by qualifier
-.It ACL_GROUP_OBJ	Permissions apply to file group
-.It ACL_GROUP		Permissions apply to additional group specified by qualifier
-.It ACL_MASK		Permissions specify mask
-.It ACL_OTHER		Permissions apply to "other"
-.It ACL_OTHER_OBJ	Same as ACL_OTHER
-.It ACL_EVERYONE	Permissions apply to "everyone@"
+.It ACL_USER_OBJ Ta "Permissions apply to file owner"
+.It ACL_USER Ta "Permissions apply to additional user specified by qualifi=
er"
+.It ACL_GROUP_OBJ Ta "Permissions apply to file group"
+.It ACL_GROUP Ta "Permissions apply to additional group specified by quali=
fier"
+.It ACL_MASK Ta "Permissions specify mask"
+.It ACL_OTHER Ta Permissions apply to "other"
+.It ACL_OTHER_OBJ Ta "Same as ACL_OTHER"
+.It ACL_EVERYONE Ta Permissions apply to "everyone@"
 .El
 .Pp
 Calling
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/posix1e/acl_to_text.3
--- a/head/lib/libc/posix1e/acl_to_text.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/posix1e/acl_to_text.3	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/posix1e/acl_to_text.3 233665 2012-03-29 16:02:=
40Z joel $
 .\"
 .Dd June 25, 2009
 .Dt ACL_TO_TEXT 3
@@ -66,11 +66,10 @@
 The flags specified are formed by
 .Em or Ns 'ing
 the following values
-.Pp
 .Bl -column -offset 3n "ACL_TEXT_NUMERIC_IDS"
-.It ACL_TEXT_VERBOSE		Format ACL using verbose form
-.It ACL_TEXT_NUMERIC_IDS	Do not resolve IDs into user or group names
-.It ACL_TEXT_APPEND_ID		In addition to user and group names, append numeri=
c IDs
+.It ACL_TEXT_VERBOSE Ta "Format ACL using verbose form"
+.It ACL_TEXT_NUMERIC_IDS Ta "Do not resolve IDs into user or group names"
+.It ACL_TEXT_APPEND_ID Ta "In addition to user and group names, append num=
eric IDs"
 .El
 .Pp
 This function allocates any memory necessary to contain the string and
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/powerpc/gen/_setjmp.S
--- a/head/lib/libc/powerpc/gen/_setjmp.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/powerpc/gen/_setjmp.S	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 /*      $NetBSD: _setjmp.S,v 1.1 1997/03/29 20:55:53 thorpej Exp $      */
=20
 #include <machine/asm.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/powerpc/gen/_setjmp.S 234115 2012-04-11 =
00:00:40Z nwhitehorn $");
=20
 /*
  * C library -- _setjmp, _longjmp
@@ -63,7 +63,6 @@
 	lmw	%r9,20(%r3)
 	mtlr	%r11
 	mtcr	%r12
-	mr	%r2,%r9
 	mr	%r1,%r10
 	or.	%r3,%r4,%r4
 	bnelr
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/powerpc/gen/setjmp.S
--- a/head/lib/libc/powerpc/gen/setjmp.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/powerpc/gen/setjmp.S	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 /*      $NetBSD: setjmp.S,v 1.3 1998/10/03 12:30:38 tsubai Exp $        */
=20
 #include <machine/asm.h>
-__FBSDID("$FreeBSD: head/lib/libc/powerpc/gen/setjmp.S 231044 2012-02-05 2=
0:04:43Z andreast $");
+__FBSDID("$FreeBSD: head/lib/libc/powerpc/gen/setjmp.S 234115 2012-04-11 0=
0:00:40Z nwhitehorn $");
=20
 #include <sys/syscall.h>
 =09
@@ -75,7 +75,6 @@
 	mr	%r6,%r4			/* save val param */
 	mtlr	%r11			/* r11 -> link reg */
 	mtcr	%r12			/* r12 -> condition reg */
-	mr	%r2,%r9			/* r9  -> global ptr */
 	mr	%r1,%r10		/* r10 -> stackptr */
 	mr	%r4,%r3
 	li	%r3,3			/* SIG_SETMASK */
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/powerpc/gen/sigsetjmp.S
--- a/head/lib/libc/powerpc/gen/sigsetjmp.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/powerpc/gen/sigsetjmp.S	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 /*      $NetBSD: sigsetjmp.S,v 1.4 1998/10/03 12:30:38 tsubai Exp $     */
=20
 #include <machine/asm.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/powerpc/gen/sigsetjmp.S 234115 2012-04-1=
1 00:00:40Z nwhitehorn $");
=20
 /*
  * C library -- sigsetjmp, siglongjmp
@@ -80,7 +80,6 @@
 	mr	%r6,%r4
 	mtlr	%r11
 	mtcr	%r12
-	mr	%r2,%r9
 	mr	%r1,%r10
 	or.	%r7,%r7,%r7
 	beq	1f
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/powerpc64/gen/_setjmp.S
--- a/head/lib/libc/powerpc64/gen/_setjmp.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/powerpc64/gen/_setjmp.S	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 /*      $NetBSD: _setjmp.S,v 1.1 1997/03/29 20:55:53 thorpej Exp $      */
=20
 #include <machine/asm.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/powerpc64/gen/_setjmp.S 234115 2012-04-1=
1 00:00:40Z nwhitehorn $");
=20
 /*
  * C library -- _setjmp, _longjmp
@@ -86,7 +86,6 @@
 	ld	%r10,40 + 1*8(%r3)
 	ld	%r11,40 + 2*8(%r3)
 	ld	%r12,40 + 3*8(%r3)
-	ld	%r13,40 + 4*8(%r3)
 	ld	%r14,40 + 5*8(%r3)
 	ld	%r15,40 + 6*8(%r3)
 	ld	%r16,40 + 7*8(%r3)
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/powerpc64/gen/makecontex=
t.c
--- a/head/lib/libc/powerpc64/gen/makecontext.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/lib/libc/powerpc64/gen/makecontext.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/powerpc64/gen/makecontext.c 234003 2012-=
04-07 22:28:50Z nwhitehorn $");
=20
 #include <sys/param.h>
=20
@@ -111,7 +111,7 @@
 	 * Use caller-saved regs 14/15 to hold params that _ctx_start
 	 * will use to invoke the user-supplied func
 	 */
-	mc->mc_srr0 =3D (uintptr_t) _ctx_start;
+	mc->mc_srr0 =3D *(uintptr_t *)_ctx_start;
 	mc->mc_gpr[1] =3D (uintptr_t) sp;		/* new stack pointer */
 	mc->mc_gpr[14] =3D (uintptr_t) start;	/* r14 <- start */
 	mc->mc_gpr[15] =3D (uintptr_t) ucp;	/* r15 <- ucp */
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/powerpc64/gen/setjmp.S
--- a/head/lib/libc/powerpc64/gen/setjmp.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/powerpc64/gen/setjmp.S	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 /*      $NetBSD: setjmp.S,v 1.3 1998/10/03 12:30:38 tsubai Exp $        */
=20
 #include <machine/asm.h>
-__FBSDID("$FreeBSD: head/lib/libc/powerpc64/gen/setjmp.S 231044 2012-02-05=
 20:04:43Z andreast $");
+__FBSDID("$FreeBSD: head/lib/libc/powerpc64/gen/setjmp.S 234115 2012-04-11=
 00:00:40Z nwhitehorn $");
=20
 #include <sys/syscall.h>
 =09
@@ -99,7 +99,6 @@
 	ld	%r10,40 + 1*8(%r3)
 	ld	%r11,40 + 2*8(%r3)
 	ld	%r12,40 + 3*8(%r3)
-	ld	%r13,40 + 4*8(%r3)
 	ld	%r14,40 + 5*8(%r3)
 	ld	%r15,40 + 6*8(%r3)
 	ld	%r16,40 + 7*8(%r3)
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/powerpc64/gen/sigsetjmp.S
--- a/head/lib/libc/powerpc64/gen/sigsetjmp.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/powerpc64/gen/sigsetjmp.S	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 /*      $NetBSD: sigsetjmp.S,v 1.4 1998/10/03 12:30:38 tsubai Exp $     */
=20
 #include <machine/asm.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/powerpc64/gen/sigsetjmp.S 234115 2012-04=
-11 00:00:40Z nwhitehorn $");
=20
 /*
  * C library -- sigsetjmp, siglongjmp
@@ -103,7 +103,6 @@
 	ld	%r10,40 + 1*8(%r3)
 	ld	%r11,40 + 2*8(%r3)
 	ld	%r12,40 + 3*8(%r3)
-	ld	%r13,40 + 4*8(%r3)
 	ld	%r14,40 + 5*8(%r3)
 	ld	%r15,40 + 6*8(%r3)
 	ld	%r16,40 + 7*8(%r3)
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/rpc/rpc_soc.3
--- a/head/lib/libc/rpc/rpc_soc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/rpc/rpc_soc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 .\" @(#)rpc.3n	2.4 88/08/08 4.0 RPCSRC; from 1.19 88/06/24 SMI
 .\" $NetBSD: rpc_soc.3,v 1.2 2000/06/07 13:39:43 simonb Exp $
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/rpc/rpc_soc.3 233680 2012-03-29 20:23:35Z joel=
 $
 .\"
 .Dd February 16, 1988
 .Dt RPC_SOC 3
@@ -111,8 +111,8 @@
 can be used only if
 .Tn DES
 encryption is available.
+.Pp
 .Bl -tag -width indent -compact
-.Pp
 .It Xo
 .Ft void
 .Xc
@@ -394,12 +394,10 @@
 .Fa req
 and their argument types and what they do are:
 .Bl -column "CLSET_RETRY_TIMEOUT" "struct sockaddr_in"
-.It Dv CLSET_TIMEOUT Ta Xo
+.It Dv CLSET_TIMEOUT Ta
 .Vt "struct timeval" Ta "set total timeout"
-.Xc
-.It Dv CLGET_TIMEOUT Ta Xo
+.It Dv CLGET_TIMEOUT Ta
 .Vt "struct timeval" Ta "get total timeout"
-.Xc
 .El
 .Pp
 Note: if you set the timeout using
@@ -408,21 +406,18 @@
 .Fn clnt_call
 will be ignored in all future calls.
 .Bl -column "CLSET_RETRY_TIMEOUT" "struct sockaddr_in"
-.It Dv CLGET_SERVER_ADDR Ta Xo
+.It Dv CLGET_SERVER_ADDR Ta
 .Vt "struct sockaddr_in" Ta "get server's address"
-.Xc
 .El
 .Pp
 The following operations are valid for
 .Tn UDP
 only:
 .Bl -column "CLSET_RETRY_TIMEOUT" "struct sockaddr_in"
-.It Dv CLSET_RETRY_TIMEOUT Ta Xo
+.It Dv CLSET_RETRY_TIMEOUT Ta
 .Vt "struct timeval" Ta "set the retry timeout"
-.Xc
-.It Dv CLGET_RETRY_TIMEOUT Ta Xo
+.It Dv CLGET_RETRY_TIMEOUT Ta
 .Vt "struct timeval" Ta "get the retry timeout"
-.Xc
 .El
 .Pp
 The retry timeout is the time that
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/stdio/getline.3
--- a/head/lib/libc/stdio/getline.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/stdio/getline.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/stdio/getline.3 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd November 30, 2010
 .Dt GETLINE 3
@@ -78,7 +78,7 @@
 .Fn getline
 functions return the number of characters written, excluding the
 terminating
-.Dv NUL=20
+.Dv NUL
 character.
 The value \-1 is returned if an error occurs, or if end-of-file is reached.
 .Sh EXAMPLES
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/stdlib/Makefile.inc
--- a/head/lib/libc/stdlib/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/stdlib/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	from @(#)Makefile.inc	8.3 (Berkeley) 2/4/95
-# $FreeBSD: head/lib/libc/stdlib/Makefile.inc 229848 2012-01-09 06:36:28Z =
ed $
+# $FreeBSD: head/lib/libc/stdlib/Makefile.inc 234370 2012-04-17 07:22:14Z =
jasone $
=20
 # machine-independent stdlib sources
 .PATH: ${.CURDIR}/${LIBC_ARCH}/stdlib ${.CURDIR}/stdlib
@@ -7,7 +7,7 @@
 MISRCS+=3D_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll=
.c \
 	bsearch.c div.c exit.c getenv.c getopt.c getopt_long.c \
 	getsubopt.c hcreate.c heapsort.c imaxabs.c imaxdiv.c \
-	insque.c l64a.c labs.c ldiv.c llabs.c lldiv.c lsearch.c malloc.c \
+	insque.c l64a.c labs.c ldiv.c llabs.c lldiv.c lsearch.c \
 	merge.c ptsname.c qsort.c qsort_r.c quick_exit.c radixsort.c rand.c \
 	random.c reallocf.c realpath.c remque.c strfmon.c strtoimax.c \
 	strtol.c strtoll.c strtoq.c strtoul.c strtonum.c strtoull.c \
@@ -18,18 +18,17 @@
 # machine-dependent stdlib sources
 .sinclude "${.CURDIR}/${LIBC_ARCH}/stdlib/Makefile.inc"
=20
-MAN+=3D	a64l.3 abort.3 abs.3 aligned_alloc.3 alloca.3 atexit.3 atof.3 \
+MAN+=3D	a64l.3 abort.3 abs.3 alloca.3 atexit.3 atof.3 \
 	atoi.3 atol.3 at_quick_exit.3 bsearch.3 \
 	div.3 exit.3 getenv.3 getopt.3 getopt_long.3 getsubopt.3 \
 	hcreate.3 imaxabs.3 imaxdiv.3 insque.3 labs.3 ldiv.3 llabs.3 lldiv.3 \
-	lsearch.3 malloc.3 memory.3 ptsname.3 qsort.3 \
+	lsearch.3 memory.3 ptsname.3 qsort.3 \
 	quick_exit.3 \
-	radixsort.3 rand.3 random.3 \
+	radixsort.3 rand.3 random.3 reallocf.3 \
 	realpath.3 strfmon.3 strtod.3 strtol.3 strtonum.3 strtoul.3 system.3 \
 	tsearch.3
=20
 MLINKS+=3Da64l.3 l64a.3 a64l.3 l64a_r.3
-MLINKS+=3Daligned_alloc.3 posix_memalign.3
 MLINKS+=3Datol.3 atoll.3
 MLINKS+=3Dexit.3 _Exit.3
 MLINKS+=3Dgetenv.3 putenv.3 getenv.3 setenv.3 getenv.3 unsetenv.3
@@ -46,11 +45,4 @@
 MLINKS+=3Dstrtod.3 strtof.3 strtod.3 strtold.3
 MLINKS+=3Dstrtol.3 strtoll.3 strtol.3 strtoq.3 strtol.3 strtoimax.3
 MLINKS+=3Dstrtoul.3 strtoull.3 strtoul.3 strtouq.3 strtoul.3 strtoumax.3
-MLINKS+=3Dmalloc.3 calloc.3 malloc.3 free.3 malloc.3 malloc.conf.5 \
-	malloc.3 realloc.3 malloc.3 reallocf.3 malloc.3 malloc_usable_size.3
 MLINKS+=3Dtsearch.3 tdelete.3 tsearch.3 tfind.3 tsearch.3 twalk.3
-
-.if defined(MALLOC_PRODUCTION)
-CFLAGS+=3D	-DMALLOC_PRODUCTION
-.endif
-
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/stdlib/Symbol.map
--- a/head/lib/libc/stdlib/Symbol.map	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/stdlib/Symbol.map	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD: head/lib/libc/stdlib/Symbol.map 229848 2012-01-09 06:36:28Z e=
d $
+ * $FreeBSD: head/lib/libc/stdlib/Symbol.map 234370 2012-04-17 07:22:14Z j=
asone $
  */
=20
 FBSD_1.0 {
@@ -47,14 +47,6 @@
 	lldiv;
 	lsearch;
 	lfind;
-	_malloc_options;
-	_malloc_message;
-	malloc;
-	posix_memalign;
-	calloc;
-	realloc;
-	free;
-	malloc_usable_size;
 	mergesort;
 	putenv;
 	qsort_r;
@@ -93,7 +85,6 @@
 };
=20
 FBSD_1.3 {
-	aligned_alloc;
 	at_quick_exit;
 	atof_l;
 	atoi_l;
@@ -114,9 +105,6 @@
 };
=20
 FBSDprivate_1.0 {
-	_malloc_thread_cleanup;
-	_malloc_prefork;
-	_malloc_postfork;
 	__system;
 	_system;
 };
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/stdlib/at_quick_exit.3
--- a/head/lib/libc/stdlib/at_quick_exit.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/stdlib/at_quick_exit.3	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 .\"  Copyright (c) 2011 David Chisnall
 .\"  All rights reserved.
-.\"=20
+.\"
 .\"  Redistribution and use in source and binary forms, with or without
 .\"  modification, are permitted provided that the following conditions
 .\"  are met:
@@ -9,7 +9,7 @@
 .\"  2. Redistributions in binary form must reproduce the above copyright
 .\"     notice, this list of conditions and the following disclaimer in the
 .\"     documentation and/or other materials provided with the distributio=
n.
-.\"=20
+.\"
 .\"  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 .\"  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 .\"  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PU=
RPOSE
@@ -21,8 +21,8 @@
 .\"  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY=
 WAY
 .\"  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\"  SUCH DAMAGE.
-.\"=20
-.\"  $FreeBSD: head/lib/libc/stdlib/at_quick_exit.3 228329 2011-12-07 21:0=
2:35Z theraven $
+.\"
+.\"  $FreeBSD: head/lib/libc/stdlib/at_quick_exit.3 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd December 7, 2011
 .Dt AT_QUICK_EXIT 3
@@ -40,16 +40,16 @@
 The
 .Fn at_quick_exit
 function registers a cleanup function to be called when the program exits =
as a
-result of calling=20
+result of calling
 .Xr quick_exit 3 .
 The cleanup functions are called in the reverse order and will not be call=
ed if
-the program exits by calling=20
+the program exits by calling
 .Xr exit 3 ,
 .Xr _Exit 3 ,
 or
 .Xr abort 3 .
 .Sh RETURN VALUES
-The=20
+The
 .Fn at_quick_exit
 function returns the value 0 if successful and a non-zero value on failure.
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/stdlib/getenv.3
--- a/head/lib/libc/stdlib/getenv.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/stdlib/getenv.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)getenv.3	8.2 (Berkeley) 12/11/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/stdlib/getenv.3 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd June 20, 2007
 .Dt GETENV 3
@@ -201,7 +201,7 @@
 Until
 .Fx 7.0 ,
 .Fn putenv
-would make a copy of=20
+would make a copy of
 .Fa string
 and insert it into the environment using
 .Fn setenv .
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/string/memchr.3
--- a/head/lib/libc/string/memchr.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/string/memchr.3	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)memchr.3	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/string/memchr.3 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd April 9, 2008
 .Dt MEMCHR 3
@@ -94,7 +94,7 @@
 .St -isoC .
 .Pp
 The
-.Fn memrchr      =20
+.Fn memrchr
 function is a GNU extension and conforms to no standard.
 .Sh HISTORY
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/cap_new.2
--- a/head/lib/libc/sys/cap_new.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/cap_new.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/sys/cap_new.2 228970 2011-12-29 21:12:22Z pluk=
net $
+.\" $FreeBSD: head/lib/libc/sys/cap_new.2 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd July 20, 2011
 .Dt CAP_NEW 2
@@ -462,14 +462,14 @@
 Support for capabilities and capabilities mode was developed as part of the
 .Tn TrustedBSD
 Project.
+.Sh AUTHORS
+These functions and the capability facility were created by
+.An "Robert N. M. Watson"
+at the University of Cambridge Computer Laboratory with support from a gra=
nt
+from Google, Inc.
 .Sh BUGS
 This man page should list the set of permitted system calls more specifica=
lly
 for each capability right.
 .Pp
 Capability rights sometimes have unclear indirect impacts, which should be
 documented, or at least hinted at.
-.Sh AUTHORS
-These functions and the capability facility were created by
-.An "Robert N. M. Watson"=20
-at the University of Cambridge Computer Laboratory with support from a gra=
nt
-from Google, Inc.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/chflags.2
--- a/head/lib/libc/sys/chflags.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/chflags.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,9 +26,9 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)chflags.2	8.3 (Berkeley) 5/2/95
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/chflags.2 234202 2012-04-13 05:40:26Z jh $
 .\"
-.Dd Oct 29, 2010
+.Dd Apr 13, 2012
 .Dt CHFLAGS 2
 .Os
 .Sh NAME
@@ -114,8 +114,7 @@
 and
 .Dv SF_ARCHIVED
 flags may only be set or unset by the super-user.
-Attempts to set these flags by non-super-users are rejected, attempts by
-non-superusers to clear flags that are already unset are silently ignored.
+Attempts to toggle these flags by non-super-users are rejected.
 These flags may be set at any time, but normally may only be unset when
 the system is in single-user mode.
 (See
@@ -124,7 +123,7 @@
 .Pp
 The
 .Dv SF_SNAPSHOT
-flag is maintained by the system and cannot be changed by any user.
+flag is maintained by the system and cannot be toggled.
 .Sh RETURN VALUES
 .Rv -std
 .Sh ERRORS
@@ -154,12 +153,12 @@
 is set and the user is either not the super-user or
 securelevel is greater than 0.
 .It Bq Er EPERM
-A non-super-user tries to set one of
+A non-super-user attempted to toggle one of
 .Dv SF_ARCHIVED , SF_IMMUTABLE , SF_APPEND ,
 or
 .Dv SF_NOUNLINK .
 .It Bq Er EPERM
-User tries to set or remove the
+An attempt was made to toggle the
 .Dv SF_SNAPSHOT
 flag.
 .It Bq Er EROFS
@@ -174,7 +173,9 @@
 .Tn I/O
 error occurred while reading from or writing to the file system.
 .It Bq Er EOPNOTSUPP
-The underlying file system does not support file flags.
+The underlying file system does not support file flags, or
+does not support all of the flags set in
+.Fa flags .
 .El
 .Pp
 The
@@ -199,12 +200,12 @@
 is set and the user is either not the super-user or
 securelevel is greater than 0.
 .It Bq Er EPERM
-A non-super-user tries to set one of
+A non-super-user attempted to toggle one of
 .Dv SF_ARCHIVED , SF_IMMUTABLE , SF_APPEND ,
 or
 .Dv SF_NOUNLINK .
 .It Bq Er EPERM
-User tries to set or remove the
+An attempt was made to toggle the
 .Dv SF_SNAPSHOT
 flag.
 .It Bq Er EROFS
@@ -214,7 +215,9 @@
 .Tn I/O
 error occurred while reading from or writing to the file system.
 .It Bq Er EOPNOTSUPP
-The underlying file system does not support file flags.
+The underlying file system does not support file flags, or
+does not support all of the flags set in
+.Fa flags .
 .El
 .Sh SEE ALSO
 .Xr chflags 1 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/cpuset.2
--- a/head/lib/libc/sys/cpuset.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/cpuset.2	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/cpuset.2 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd January 8, 2010
 .Dt CPUSET 2
@@ -77,7 +77,7 @@
 To select the correct set a value of type
 .Ft cpulevel_t
 is used.
-The following values for=20
+The following values for
 .Fa level
 are supported:
 .Bl -column CPU_LEVEL_CPUSET -offset indent
@@ -137,7 +137,7 @@
 .Xr fork 2 .
 .Pp
 .Fn cpuset_setid
-attempts to set the id of the object specified by the=20
+attempts to set the id of the object specified by the
 .Fa which
 argument.
 Currently
@@ -149,12 +149,12 @@
 be running on CPUs permitted by the set.
 .Pp
 .Fn cpuset_getid
-retrieves a set id from the object indicated by=20
+retrieves a set id from the object indicated by
 .Fa which
 and stores it in the space pointed to by
 .Fa setid .
 The retrieved id may be that of either the root or assigned set
-depending on the value of=20
+depending on the value of
 .Fa level .
 .Fa level
 should be
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/cpuset_getaffinity.2
--- a/head/lib/libc/sys/cpuset_getaffinity.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/cpuset_getaffinity.2	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/cpuset_getaffinity.2 233648 2012-03-29 05:=
02:12Z eadler $
 .\"
 .Dd September 10, 2010
 .Dt CPUSET 2
@@ -45,7 +45,7 @@
 .Fn cpuset_getaffinity
 and
 .Fn cpuset_setaffinity
-allow the manipulation of sets of CPUs available to processes, threads,=20
+allow the manipulation of sets of CPUs available to processes, threads,
 interrupts, jails and other resources.
 These functions may manipulate sets of CPUs that contain many processes
 or per-object anonymous masks that effect only a single object.
@@ -108,7 +108,6 @@
 .Fa id
 to the value in
 .Fa mask .
-.Pp
 .Sh RETURN VALUES
 .Rv -std
 .Sh ERRORS
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/dup.2
--- a/head/lib/libc/sys/dup.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/dup.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)dup.2	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/sys/dup.2 224864 2011-08-14 12:41:44Z rwatson $
+.\" $FreeBSD: head/lib/libc/sys/dup.2 234131 2012-04-11 14:08:09Z eadler $
 .\"
 .Dd August 14, 2011
 .Dt DUP 2
@@ -128,20 +128,27 @@
 .Sh ERRORS
 The
 .Fn dup
-and
-.Fn dup2
-system calls fail if:
+system call fails if:
 .Bl -tag -width Er
 .It Bq Er EBADF
 The
 .Fa oldd
-or
-.Fa newd
 argument
 is not a valid active descriptor
 .It Bq Er EMFILE
 Too many descriptors are active.
 .El
+The
+.Fn dup2
+system call fails if:
+.Bl -tag -width Er
+.It Bq Er EBADF
+The
+.Fa oldd
+argument is not a valid active descriptor or the
+.Fa newd
+argument is negative or exceeds the maximum allowable descriptor number
+.El
 .Sh SEE ALSO
 .Xr accept 2 ,
 .Xr cap_new 2 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/fcntl.2
--- a/head/lib/libc/sys/fcntl.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/fcntl.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)fcntl.2	8.2 (Berkeley) 1/12/94
-.\" $FreeBSD: head/lib/libc/sys/fcntl.2 230648 2012-01-28 18:35:10Z tijl $
+.\" $FreeBSD: head/lib/libc/sys/fcntl.2 234131 2012-04-11 14:08:09Z eadler=
 $
 .\"
 .Dd January 28, 2012
 .Dt FCNTL 2
@@ -539,8 +539,6 @@
 .Fa cmd
 is
 .Dv F_DUPFD
-or
-.Dv F_DUP2FD
 and the maximum number of file descriptors permitted for the
 process are already in use,
 or no file descriptors greater than or equal to
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/jail.2
--- a/head/lib/libc/sys/jail.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/jail.2	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/sys/jail.2 231564 2012-02-12 18:29:56Z ed $
+.\" $FreeBSD: head/lib/libc/sys/jail.2 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd February 8, 2012
 .Dt JAIL 2
@@ -334,7 +334,7 @@
 The jail referred to by a
 .Va jid
 is not accessible by the process, because the process is in a different
-jail.=20
+jail.
 .It Bq Er EEXIST
 The jail referred to by a
 .Va jid
@@ -382,7 +382,7 @@
 The jail referred to by a
 .Va jid
 is not accessible by the process, because the process is in a different
-jail.=20
+jail.
 .It Bq Er ENOENT
 The
 .Va lastjid
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/kldstat.2
--- a/head/lib/libc/sys/kldstat.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/kldstat.2	Tue Apr 17 11:51:51 2012 +0300
@@ -23,9 +23,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/sys/kldstat.2 220975 2011-04-23 20:59:58Z gjb $
+.\" $FreeBSD: head/lib/libc/sys/kldstat.2 233631 2012-03-28 23:51:06Z jimh=
arris $
 .\"
-.Dd April 23, 2011
+.Dd March 28, 2012
 .Dt KLDSTAT 2
 .Os
 .Sh NAME
@@ -47,7 +47,7 @@
 .Fa stat .
 .Bd -literal
 struct kld_file_stat {
-	int         version;        /* set to sizeof(linker_file_stat) */
+	int         version;    /* set to sizeof(struct kld_file_stat) */
 	char        name[MAXPATHLEN];
 	int         refs;
 	int         id;
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/kqueue.2
--- a/head/lib/libc/sys/kqueue.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/kqueue.2	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/sys/kqueue.2 231777 2012-02-15 18:34:57Z delph=
ij $
+.\" $FreeBSD: head/lib/libc/sys/kqueue.2 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd February 15, 2012
 .Dt KQUEUE 2
@@ -203,7 +203,7 @@
 The filter itself is not disabled.
 .It EV_DISPATCH
 Disable the event source immediately after delivery of an event.
-See=20
+See
 .Dv EV_DISABLE
 above.
 .It EV_DELETE
@@ -217,7 +217,7 @@
 When passed as input, it forces
 .Dv EV_ERROR
 to always be returned.
-When a filter is successfully added the=20
+When a filter is successfully added the
 .Va data
 field will be zero.
 .It EV_ONESHOT
@@ -449,10 +449,10 @@
 .Va ident
 which is not associated with any kernel mechanism but is triggered by
 user level code.
-The lower 24 bits of the=20
+The lower 24 bits of the
 .Va fflags
 may be used for user defined flags and manipulated using the following:
-.Bl -tag -width XXNOTE_FFLAGSMASK=20
+.Bl -tag -width XXNOTE_FFLAGSMASK
 .It Dv NOTE_FFNOP
 Ignore the input
 .Va fflags .
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/kse.2
--- a/head/lib/libc/sys/kse.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/kse.2	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 .\" THE USE OF THIS SOFTWARE, EVEN IF PACKET DESIGN IS ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/kse.2 233669 2012-03-29 16:20:20Z joel $
 .\"
 .Dd February 13, 2007
 .Dt KSE 2
@@ -676,4 +676,4 @@
 .An "Archie Cobbs" Aq archie at FreeBSD.org .
 .Sh BUGS
 The KSE code is
-.Ud .
+.Ud
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/ktrace.2
--- a/head/lib/libc/sys/ktrace.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/ktrace.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)ktrace.2	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/lib/libc/sys/ktrace.2 226269 2011-10-11 20:37:10Z des $
+.\" $FreeBSD: head/lib/libc/sys/ktrace.2 233665 2012-03-29 16:02:40Z joel $
 .\"
 .Dd October 10, 2011
 .Dt KTRACE 2
@@ -67,12 +67,12 @@
 argument specifies the requested ktrace operation.
 The defined operations are:
 .Bl -column KTRFLAG_DESCENDXXX -offset indent
-.It "KTROP_SET		Enable trace points specified in"
+.It KTROP_SET Ta "Enable trace points specified in"
 .Fa trpoints .
-.It "KTROP_CLEAR	Disable trace points specified in"
+.It KTROP_CLEAR Ta "Disable trace points specified in"
 .Fa trpoints .
-.It "KTROP_CLEARFILE	Stop all tracing."
-.It "KTRFLAG_DESCEND	The tracing change should apply to the"
+.It KTROP_CLEARFILE Ta "Stop all tracing."
+.It KTRFLAG_DESCEND Ta "The tracing change should apply to the"
 specified process and all its current children.
 .El
 .Pp
@@ -81,20 +81,20 @@
 argument specifies the trace points of interest.
 The defined trace points are:
 .Bl -column KTRFAC_PROCCTORXXX -offset indent
-.It "KTRFAC_SYSCALL	Trace system calls."
-.It "KTRFAC_SYSRET	Trace return values from system calls."
-.It "KTRFAC_NAMEI	Trace name lookup operations."
-.It "KTRFAC_GENIO	Trace all I/O (note that this option can"
+.It KTRFAC_SYSCALL Ta "Trace system calls."
+.It KTRFAC_SYSRET Ta "Trace return values from system calls."
+.It KTRFAC_NAMEI Ta "Trace name lookup operations."
+.It KTRFAC_GENIO Ta "Trace all I/O (note that this option can"
 generate much output).
-.It "KTRFAC_PSIG	Trace posted signals."
-.It "KTRFAC_CSW	Trace context switch points."
-.It "KTRFAC_USER	Trace application-specific events."
-.It "KTRFAC_STRUCT	Trace certain data structures."
-.It "KTRFAC_SYSCTL	Trace sysctls."
-.It "KTRFAC_PROCCTOR	Trace process construction."
-.It "KTRFAC_PROCDTOR	Trace process destruction."
-.It "KTRFAC_CAPFAIL	Trace capability failures."
-.It "KTRFAC_INHERIT	Inherit tracing to future children."
+.It KTRFAC_PSIG Ta "Trace posted signals."
+.It KTRFAC_CSW Ta "Trace context switch points."
+.It KTRFAC_USER Ta "Trace application-specific events."
+.It KTRFAC_STRUCT Ta "Trace certain data structures."
+.It KTRFAC_SYSCTL Ta "Trace sysctls."
+.It KTRFAC_PROCCTOR Ta "Trace process construction."
+.It KTRFAC_PROCDTOR Ta "Trace process destruction."
+.It KTRFAC_CAPFAIL Ta "Trace capability failures."
+.It KTRFAC_INHERIT Ta "Inherit tracing to future children."
 .El
 .Pp
 Each tracing event outputs a record composed of a generic header
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/pathconf.2
--- a/head/lib/libc/sys/pathconf.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/pathconf.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)pathconf.2	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/pathconf.2 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd July 7, 2009
 .Dt PATHCONF 2
@@ -87,7 +87,6 @@
 returns information about the file the link references.
 .Pp
 The available values are as follows:
-.Pp
 .Bl -tag -width 6n
 .It Li _PC_LINK_MAX
 The maximum file link count.
@@ -174,7 +173,7 @@
 bytes.
 The offsets of holes returned will be aligned to this same value.
 A special value of 1 is returned if the file system does not specify the m=
inimum
-hole size but still reports holes. =20
+hole size but still reports holes.
 .El
 .Sh RETURN VALUES
 If the call to
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/posix_fadvise.2
--- a/head/lib/libc/sys/posix_fadvise.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/posix_fadvise.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)madvise.2	8.1 (Berkeley) 6/9/93
-.\" $FreeBSD: head/lib/libc/sys/posix_fadvise.2 232157 2012-02-25 14:31:25=
Z gjb $
+.\" $FreeBSD: head/lib/libc/sys/posix_fadvise.2 233462 2012-03-25 12:13:24=
Z joel $
 .\"
 .Dd February 25, 2012
 .Dt POSIX_FADVISE 2
@@ -89,7 +89,6 @@
 .Dv O_DIRECT
 flag enabled.
 .El
-.Pp
 .Sh RETURN VALUES
 .Rv -std posix_fadvise
 .Sh ERRORS
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/posix_fallocate.2
--- a/head/lib/libc/sys/posix_fallocate.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/posix_fallocate.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)open.2	8.2 (Berkeley) 11/16/93
-.\" $FreeBSD: head/lib/libc/sys/posix_fallocate.2 232157 2012-02-25 14:31:=
25Z gjb $
+.\" $FreeBSD: head/lib/libc/sys/posix_fallocate.2 233462 2012-03-25 12:13:=
24Z joel $
 .\"
 .Dd February 25, 2012
 .Dt POSIX_FALLOCATE 2
@@ -79,7 +79,6 @@
 that reduces the file size to a size smaller than
 .Fa offset +
 .Fa len .
-.Pp
 .Sh RETURN VALUES
 If successful,
 .Fn posix_fallocate
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/ptrace.2
--- a/head/lib/libc/sys/ptrace.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/ptrace.2	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/lib/libc/sys/ptrace.2 231902 2012-02-18 22:26:32Z kib $
+.\" $FreeBSD: head/lib/libc/sys/ptrace.2 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"	$NetBSD: ptrace.2,v 1.2 1995/02/27 12:35:37 cgd Exp $
 .\"
 .\" This file is in the public domain.
@@ -441,7 +441,7 @@
 process.
 The
 .Fa addr
-argument specifies a pointer to a=20
+argument specifies a pointer to a
 .Vt "struct ptrace_vm_entry" ,
 which is defined as follows:
 .Bd -literal
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/quotactl.2
--- a/head/lib/libc/sys/quotactl.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/quotactl.2	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)quotactl.2	8.2 (Berkeley) 3/10/95
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/quotactl.2 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd March 5, 1999
 .Dt QUOTACTL 2
@@ -113,7 +113,7 @@
 .It Dv Q_GETQUOTASIZE
 Get the wordsize used to represent the quotas for the user or group
 (as determined by the command type).
-Possible values are 32 for the old-style quota file=20
+Possible values are 32 for the old-style quota file
 and 64 for the new-style quota file.
 The
 .Fa addr
@@ -199,7 +199,7 @@
 .Fa id
 argument to
 .Dv Q_GETQUOTA ,
-.Dv Q_SETQUOTA=20
+.Dv Q_SETQUOTA
 or
 .Dv Q_SETUSE
 is a negative value.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/sctp_generic_sendmsg=
.2
--- a/head/lib/libc/sys/sctp_generic_sendmsg.2	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/lib/libc/sys/sctp_generic_sendmsg.2	Tue Apr 17 11:51:51 2012 +03=
00
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/sctp_generic_sendmsg.2 233648 2012-03-29 0=
5:02:12Z eadler $
 .\"
 .Dd October 30, 2007
 .Dt SCTP_GENERIC_SENDMSG 2
@@ -54,7 +54,7 @@
 .Fn sctp_generic_sendmsg_iov
 are the true system calls used by the
 .Xr sctp_sendmsg 3
-and=20
+and
 .Xr sctp_send 3
 function calls.
 These are more efficient since they are
@@ -68,7 +68,7 @@
 .Xr sctp_send 3
 or
 .Xr sctp_sendmsg 3
-function calls.=20
+function calls.
 .Sh RETURN VALUES
 The call returns the number of bytes written on success and -1 upon failur=
e.
 .Sh ERRORS
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/sctp_peeloff.2
--- a/head/lib/libc/sys/sctp_peeloff.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/sctp_peeloff.2	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/sctp_peeloff.2 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd October 30, 2007
 .Dt SCTP_PEELOFF 2
@@ -51,7 +51,6 @@
 system call attempts detach the association specified by
 .Fa id
 into its own separate socket.
-.Pp
 .Sh RETURN VALUES
 The call returns -1 on failure and the new socket descriptor
 upon success.
@@ -61,7 +60,7 @@
 system call can return the following errors:
 .Bl -tag -width Er
 .It Bq Er ENOTCONN
-The=20
+The
 .Fa id
 given to the call does not map to a valid
 association.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/select.2
--- a/head/lib/libc/sys/select.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/select.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)select.2	8.2 (Berkeley) 3/25/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/select.2 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd November 17, 2002
 .Dt SELECT 2
@@ -222,6 +222,6 @@
 by the
 .Fn select
 system call.
-.Fx=20
+.Fx
 does not modify the return value, which can cause problems for applications
 ported from other systems.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/sendfile.2
--- a/head/lib/libc/sys/sendfile.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/sendfile.2	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/sendfile.2 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd January 7, 2010
 .Dt SENDFILE 2
@@ -104,7 +104,7 @@
 The
 .Fa flags
 argument is a bitmap of these values:
-.Bl -item -offset indent=20
+.Bl -item -offset indent
 .It
 .Dv SF_NODISKIO .
 This flag causes any
diff -r 428842767fa6 -r f2935497fa04 head/lib/libc/sys/shm_open.2
--- a/head/lib/libc/sys/shm_open.2	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libc/sys/shm_open.2	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/shm_open.2 233462 2012-03-25 12:13:24Z joe=
l $
 .\"
 .Dd March 20, 2007
 .Dt SHM_OPEN 2
@@ -139,7 +139,6 @@
 .Fn shm_unlink
 system call removes a shared memory object named
 .Fa path .
-.Pp
 .Sh RETURN VALUES
 If successful,
 .Fn shm_open
diff -r 428842767fa6 -r f2935497fa04 head/lib/libcom_err/Makefile
--- a/head/lib/libcom_err/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libcom_err/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/lib/libcom_err/Makefile 233294 2012-03-22 08:48:42Z stas $
=20
 LIB=3D	com_err
 SRCS=3D	com_err.c error.c
@@ -7,6 +7,9 @@
 COM_ERRDIR=3D	${.CURDIR}/../../contrib/com_err
 CFLAGS+=3D	-I${COM_ERRDIR}
=20
+LDFLAGS=3D	-Wl,--no-undefined
+VERSION_MAP=3D	${COM_ERRDIR}/version-script.map
+
 SUBDIR=3D	doc
=20
 .include <bsd.lib.mk>
diff -r 428842767fa6 -r f2935497fa04 head/lib/libcrypt/crypt.3
--- a/head/lib/libcrypt/crypt.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libcrypt/crypt.3	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libcrypt/crypt.3 220498 2011-04-09 14:09:46Z markm $
+.\" $FreeBSD: head/lib/libcrypt/crypt.3 234132 2012-04-11 14:12:28Z eadler=
 $
 .\"
 .Dd April 9, 2011
 .Dt CRYPT 3
@@ -107,7 +107,6 @@
 crypt to do approximately 2640 crypts
 a CPU second and MD5 to do about 62 crypts a CPU second.
 .Ss DES Extended Format:
-.Pp
 The
 .Ar key
 is divided into groups of 8 characters (the last group is null-padded)
@@ -163,7 +162,6 @@
 .Ar salt
 followed by the encoded 64-bit encryption.
 .Ss "Modular" crypt:
-.Pp
 If the salt begins with the string
 .Fa $digit$
 then the Modular Crypt Format is used.
@@ -189,6 +187,8 @@
 .It
 NT-Hash
 .It
+(unused)
+.It
 SHA-256
 .It
 SHA-512
@@ -199,9 +199,7 @@
 .Bl -tag -offset indent
 .It Cm "$4$thesalt$rest"
 .El
-.Pp
 .Ss "Traditional" crypt:
-.Pp
 The algorithm used will depend upon whether
 .Fn crypt_set_format
 has been called and whether a global default format has been specified.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libcxxrt/Version.map
--- a/head/lib/libcxxrt/Version.map	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libcxxrt/Version.map	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/libcxxrt/Version.map 233174 2012-03-19 11:53:33Z ther=
aven $
+# $FreeBSD: head/lib/libcxxrt/Version.map 233235 2012-03-20 17:58:15Z ther=
aven $
 # Define the same version as the libsupc++ from gcc 4.2.1 so that we can u=
se
 # libcxxrt as a drop-in replacement.
=20
@@ -301,6 +301,11 @@
         "typeinfo name for std::exception";
         "typeinfo name for std::type_info";
=20
+        "std::type_info::__is_function_p() const";
+        "std::type_info::__do_upcast(__cxxabiv1::__class_type_info const*,=
 void**) const";
+        "std::type_info::__is_pointer_p() const";
+
+
         "operator delete[](void*)";
         "operator delete(void*)";
         "operator new[](unsigned long)";
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf.3
--- a/head/lib/libelf/elf.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libelf/elf.3 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd October 21, 2007
 .Dt ELF 3
@@ -523,7 +523,7 @@
 .Xr elf_flagelf 3 ,
 following which the library will use the data offsets and alignments
 specified by the application when laying out the file.
-Application control of file layout is described further in the=20
+Application control of file layout is described further in the
 .Xr elf_update 3
 manual page.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf_getdata.3
--- a/head/lib/libelf/elf_getdata.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf_getdata.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD: head/lib/libelf/elf_getdata.3 221598 2011-05-07 11:29:48Z ka=
iw $
+.\" $FreeBSD: head/lib/libelf/elf_getdata.3 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd January 26, 2011
 .Dt ELF_GETDATA 3
@@ -174,7 +174,7 @@
 NULL if an error occurs.
 .Sh ERRORS
 These functions may fail with the following errors:
-.Bl -tag -width "[ELF_E_RESOURCE]"=20
+.Bl -tag -width "[ELF_E_RESOURCE]"
 .It Bq Er ELF_E_ARGUMENT
 Arguments
 .Ar scn
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf_getphdrnum.3
--- a/head/lib/libelf/elf_getphdrnum.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf_getphdrnum.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,11 +21,11 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libelf/elf_getphdrnum.3 233520 2012-03-26 19:23:57Z=
 joel $
 .\"
 .Dd August 5, 2009
+.Dt ELF_GETPHDRNUM 3
 .Os
-.Dt ELF_GETPHDRNUM 3
 .Sh NAME
 .Nm elf_getphdrnum
 .Nd return the number of program headers in an ELF file
@@ -45,7 +45,6 @@
 .Pp
 This routine allows applications to uniformly process both normal ELF
 objects and ELF objects that use extended numbering.
-.Pp
 .Sh RETURN VALUES
 Function
 .Fn elf_getphdrnum
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf_getphnum.3
--- a/head/lib/libelf/elf_getphnum.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf_getphnum.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libelf/elf_getphnum.3 233462 2012-03-25 12:13:24Z j=
oel $
 .\"
 .Dd August 5, 2009
 .Dt ELF_GETPHNUM 3
@@ -50,7 +50,6 @@
 .Pp
 This routine allows applications to uniformly process both normal ELF
 objects and ELF objects that use extended numbering.
-.Pp
 .Sh RETURN VALUES
 Function
 .Fn elf_getphnum
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf_getshdrnum.3
--- a/head/lib/libelf/elf_getshdrnum.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf_getshdrnum.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,11 +21,11 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libelf/elf_getshdrnum.3 233520 2012-03-26 19:23:57Z=
 joel $
 .\"
 .Dd August 4, 2009
+.Dt ELF_GETSHDRNUM 3
 .Os
-.Dt ELF_GETSHDRNUM 3
 .Sh NAME
 .Nm elf_getshdrnum
 .Nd return the number of sections in an ELF file
@@ -45,7 +45,6 @@
 .Pp
 This routine allows applications to uniformly process both normal ELF
 objects, and ELF objects that use extended section numbering.
-.Pp
 .Sh RETURN VALUES
 Function
 .Fn elf_getshdrnum
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf_getshdrstrndx.3
--- a/head/lib/libelf/elf_getshdrstrndx.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf_getshdrstrndx.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,11 +21,11 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libelf/elf_getshdrstrndx.3 233520 2012-03-26 19:23:=
57Z joel $
 .\"
 .Dd August 5, 2009
+.Dt ELF_GETSHDRSTRNDX 3
 .Os
-.Dt ELF_GETSHDRSTRNDX 3
 .Sh NAME
 .Nm elf_getshdrstrndx
 .Nd retrieve the index of the section name string table
@@ -46,7 +46,6 @@
 .Pp
 This function allow applications to process both normal ELF
 objects and ELF objects that use extended section numbering uniformly.
-.Pp
 .Sh RETURN VALUES
 These functions return zero if successful, or -1 in case of an error.
 .Sh ERRORS
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf_getshnum.3
--- a/head/lib/libelf/elf_getshnum.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf_getshnum.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libelf/elf_getshnum.3 233462 2012-03-25 12:13:24Z j=
oel $
 .\"
 .Dd August 5, 2009
 .Dt ELF_GETSHNUM 3
@@ -50,7 +50,6 @@
 .Pp
 This routine allows applications to uniformly process both normal ELF
 objects, and ELF objects that use extended section numbering.
-.Pp
 .Sh RETURN VALUES
 Function
 .Fn elf_getshnum
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/elf_getshstrndx.3
--- a/head/lib/libelf/elf_getshstrndx.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/elf_getshstrndx.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libelf/elf_getshstrndx.3 233462 2012-03-25 12:13:24=
Z joel $
 .\"
 .Dd August 5, 2009
 .Dt ELF_GETSHSTRNDX 3
@@ -60,7 +60,6 @@
 .Pp
 These routines allow applications to process both normal ELF
 objects and ELF objects that use extended section numbering uniformly.
-.Pp
 .Sh RETURN VALUES
 These functions return a non-zero value if successful, or zero in case
 of an error.
diff -r 428842767fa6 -r f2935497fa04 head/lib/libelf/libelf_data.c
--- a/head/lib/libelf/libelf_data.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libelf/libelf_data.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libelf/libelf_data.c 221569 2011-05-07 01:05:=
31Z obrien $");
+__FBSDID("$FreeBSD: head/lib/libelf/libelf_data.c 233524 2012-03-26 21:31:=
57Z gonzo $");
=20
 #include <libelf.h>
 #include <osreldate.h>
@@ -86,6 +86,10 @@
 #endif
 	case SHT_MIPS_DWARF:
 		/* FALLTHROUGH */
+	case SHT_MIPS_REGINFO:
+		/* FALLTHROUGH */
+	case SHT_MIPS_OPTIONS:
+		/* FALLTHROUGH */
 	case SHT_AMD64_UNWIND:	/* =3D=3D SHT_IA_64_UNWIND */
 		return (ELF_T_BYTE);
 	default:
diff -r 428842767fa6 -r f2935497fa04 head/lib/libfetch/fetch.3
--- a/head/lib/libfetch/fetch.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libfetch/fetch.3	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libfetch/fetch.3 226537 2011-10-19 11:43:51Z des $
+.\" $FreeBSD: head/lib/libfetch/fetch.3 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd September 27, 2011
 .Dt FETCH 3
@@ -375,7 +375,7 @@
 (if-modified-since) flag is specified, and
 the
 .Va ims_time
-field is set in=20
+field is set in
 .Vt "struct url" ,
 then
 .Fn fetchXGetHTTP
diff -r 428842767fa6 -r f2935497fa04 head/lib/libfetch/fetch.c
--- a/head/lib/libfetch/fetch.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libfetch/fetch.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libfetch/fetch.c 226537 2011-10-19 11:43:51Z =
des $");
+__FBSDID("$FreeBSD: head/lib/libfetch/fetch.c 234138 2012-04-11 15:42:02Z =
emaste $");
=20
 #include <sys/param.h>
 #include <sys/errno.h>
@@ -289,6 +289,49 @@
 }
=20
 /*
+ * Return value of the given hex digit.
+ */
+static int
+fetch_hexval(char ch)
+{
+
+	if (ch >=3D '0' && ch <=3D '9')
+		return (ch - '0');
+	else if (ch >=3D 'a' && ch <=3D 'f')
+		return (ch - 'a' + 10);
+	else if (ch >=3D 'A' && ch <=3D 'F')
+		return (ch - 'A' + 10);
+	return (-1);
+}
+
+/*
+ * Decode percent-encoded URL component from src into dst, stopping at end
+ * of string, or at @ or : separators.  Returns a pointer to the unhandled
+ * part of the input string (null terminator, @, or :).  No terminator is
+ * written to dst (it is the caller's responsibility).
+ */
+static const char *
+fetch_pctdecode(char *dst, const char *src, size_t dlen)
+{
+	int d1, d2;
+	char c;
+	const char *s;
+
+	for (s =3D src; *s !=3D '\0' && *s !=3D '@' && *s !=3D ':'; s++) {
+		if (s[0] =3D=3D '%' && (d1 =3D fetch_hexval(s[1])) >=3D 0 &&
+		    (d2 =3D fetch_hexval(s[2])) >=3D 0 && (d1 > 0 || d2 > 0)) {
+			c =3D d1 << 4 | d2;
+			s +=3D 2;
+		} else {
+			c =3D *s;
+		}
+		if (dlen-- > 0)
+			*dst++ =3D c;
+	}
+	return (s);
+}
+
+/*
  * Split an URL into components. URL syntax is:
  * [method:/][/[user[:pwd]@]host[:port]/][document]
  * This almost, but not quite, RFC1738 URL syntax.
@@ -329,15 +372,11 @@
 	p =3D strpbrk(URL, "/@");
 	if (p && *p =3D=3D '@') {
 		/* username */
-		for (q =3D URL, i =3D 0; (*q !=3D ':') && (*q !=3D '@'); q++)
-			if (i < URL_USERLEN)
-				u->user[i++] =3D *q;
+		q =3D fetch_pctdecode(u->user, URL, URL_USERLEN);
=20
 		/* password */
 		if (*q =3D=3D ':')
-			for (q++, i =3D 0; (*q !=3D ':') && (*q !=3D '@'); q++)
-				if (i < URL_PWDLEN)
-					u->pwd[i++] =3D *q;
+			q =3D fetch_pctdecode(u->pwd, ++q, URL_PWDLEN);
=20
 		p++;
 	} else {
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgpib/gpib.3
--- a/head/lib/libgpib/gpib.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libgpib/gpib.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libgpib/gpib.3 233462 2012-03-25 12:13:24Z joel $
 .\"
 .Dd February 1, 2010
 .Dt GPIB 3
@@ -279,7 +279,6 @@
 Device clear state
 .El
 .Ss Function Description
-.Pp
 The function
 .Fn ibdev
 is used to open the GPIB device, and establish the parameters to
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgssapi/Symbol.map
--- a/head/lib/libgssapi/Symbol.map	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libgssapi/Symbol.map	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD: head/lib/libgssapi/Symbol.map 226111 2011-10-07 15:05:24Z ed $
+ * $FreeBSD: head/lib/libgssapi/Symbol.map 233294 2012-03-22 08:48:42Z sta=
s $
  */
=20
 FBSD_1.1 {
@@ -73,4 +73,5 @@
 	_gss_copy_oid;
 	_gss_copy_buffer;
 	_gss_free_oid;
+	_gss_mg_collect_error;
 };
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgssapi/gss_accept_sec_cont=
ext.3
--- a/head/lib/libgssapi/gss_accept_sec_context.3	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/lib/libgssapi/gss_accept_sec_context.3	Tue Apr 17 11:51:51 2012 =
+0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\"	$FreeBSD$
+.\"	$FreeBSD: head/lib/libgssapi/gss_accept_sec_context.3 233510 2012-03-2=
6 15:18:14Z joel $
 .\"
 .\" The following commands are required for all man pages.
 .Dd January 26, 2010
@@ -39,7 +39,7 @@
 .In "gssapi/gssapi.h"
 .Ft OM_uint32
 .Fo gss_accept_sec_context
-.Fa "OM_uint32 *minor_status
+.Fa "OM_uint32 *minor_status"
 .Fa "gss_ctx_id_t *context_handle"
 .Fa "const gss_cred_id_t acceptor_cred_handle"
 .Fa "const gss_buffer_t input_token_buffer"
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgssapi/gss_display_status.c
--- a/head/lib/libgssapi/gss_display_status.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libgssapi/gss_display_status.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	$FreeBSD: head/lib/libgssapi/gss_display_status.c 229784 2012-01-07 16:=
13:56Z uqs $
+ *	$FreeBSD: head/lib/libgssapi/gss_display_status.c 234011 2012-04-08 03:=
55:25Z stas $
  */
 /*
  * Copyright (c) 1998 - 2005 Kungliga Tekniska H=C3=B6gskolan
@@ -173,7 +173,7 @@
 	return msgs[v];
 }
=20
-#if defined(__sparc64__) || defined(__arm__) || defined(__mips__)
+#if defined(__NO_TLS)
=20
 /*
  * These platforms don't support TLS on FreeBSD - threads will just
@@ -338,3 +338,13 @@
 	_gss_buffer_zero(status_string);
 	return (GSS_S_BAD_STATUS);
 }
+
+void
+_gss_mg_collect_error(gss_OID mech, OM_uint32 maj, OM_uint32 min)
+{
+	struct _gss_mech_switch *m;
+
+	m =3D _gss_find_mech_switch(mech);
+	if (m !=3D NULL)
+		_gss_mg_error(m, maj, min);
+}
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgssapi/gss_release_buffer.3
--- a/head/lib/libgssapi/gss_release_buffer.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libgssapi/gss_release_buffer.3	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\"	$FreeBSD$
+.\"	$FreeBSD: head/lib/libgssapi/gss_release_buffer.3 233648 2012-03-29 05=
:02:12Z eadler $
 .\"
 .\" The following commands are required for all man pages.
 .Dd January 26, 2010
@@ -53,7 +53,7 @@
 .Dv NULL .
 Any buffer object returned by a GSS-API routine may be passed to
 .Fn gss_release_buffer
-(even if there is no storage associated with the buffer).=20
+(even if there is no storage associated with the buffer).
 .Sh PARAMETERS
 .Bl -tag
 .It minor_status
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgssapi/gss_release_oid_set=
.3
--- a/head/lib/libgssapi/gss_release_oid_set.3	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/lib/libgssapi/gss_release_oid_set.3	Tue Apr 17 11:51:51 2012 +03=
00
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\"	$FreeBSD$
+.\"	$FreeBSD: head/lib/libgssapi/gss_release_oid_set.3 233648 2012-03-29 0=
5:02:12Z eadler $
 .\"
 .\" The following commands are required for all man pages.
 .Dd January 26, 2010
@@ -53,7 +53,7 @@
 .Pp
 Implementations are encouraged to set the gss_OID_set parameter to
 .Dv GSS_C_NO_OID_SET
-on successful completion of this routine.=20
+on successful completion of this routine.
 .Sh PARAMETERS
 .Bl -tag
 .It minor_status
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgssapi/mech.5
--- a/head/lib/libgssapi/mech.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libgssapi/mech.5	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libgssapi/mech.5 233648 2012-03-29 05:02:12Z eadler=
 $
 .Dd January 26, 2010
 .Dt MECH 5
 .Os
@@ -62,10 +62,10 @@
 .Xr gss_init_sec_context 3
 if the user doesn't specify a specific mechanism.
 .Pp
-The=20
+The
 .Pa "/etc/gss/qop"
 file contains a list of Quality of Protection values for use with
-GSS-API.=20
+GSS-API.
 Each line of the file either contains a comment if the first character
 is '#' or it contains three fields with the following meanings:
 .Bl -tag
diff -r 428842767fa6 -r f2935497fa04 head/lib/libgssapi/mech_switch.h
--- a/head/lib/libgssapi/mech_switch.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libgssapi/mech_switch.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	$FreeBSD$
+ *	$FreeBSD: head/lib/libgssapi/mech_switch.h 233294 2012-03-22 08:48:42Z =
stas $
  */
=20
 #include <unistd.h>
@@ -360,3 +360,4 @@
 extern struct _gss_mech_switch *_gss_find_mech_switch(gss_OID);
 extern void _gss_mg_error(struct _gss_mech_switch *m, OM_uint32 maj,
     OM_uint32 min);
+extern void _gss_mg_collect_error(gss_OID mech, OM_uint32 maj, OM_uint32 m=
in);
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpam/modules/pam_exec/pam_e=
xec.8
--- a/head/lib/libpam/modules/pam_exec/pam_exec.8	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/lib/libpam/modules/pam_exec/pam_exec.8	Tue Apr 17 11:51:51 2012 =
+0300
@@ -30,9 +30,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libpam/modules/pam_exec/pam_exec.8 233507 2012-03-2=
6 12:18:15Z dumbbell $
 .\"
-.Dd February 1, 2005
+.Dd February 8, 2012
 .Dt PAM_EXEC 8
 .Os
 .Sh NAME
@@ -45,9 +45,25 @@
 .Pa pam_exec
 .Op Ar arguments
 .Sh DESCRIPTION
-The exec service module for PAM executes the program designated by its
-first argument, with its remaining arguments as command-line
-arguments.
+The exec service module for PAM executes the program designated by
+its first argument if no options are specified, with its remaining
+arguments as command-line arguments.
+If options are specified, the program and its arguments follow the last
+option or
+.Cm --
+if the program name conflicts with an option name.
+.Pp
+The following options may be passed before the program and its
+arguments:
+.Bl -tag -width ".Cm return_prog_exit_status"
+.It Cm return_prog_exit_status
+Use the program exit status as the return code of the pam_sm_* function.
+It must be a valid return value for this function.
+.It Cm --
+Stop options parsing;
+program and its arguments follow.
+.El
+.Pp
 The child's environment is set to the current PAM environment list,
 as returned by
 .Xr pam_getenvlist 3 .
@@ -56,13 +72,69 @@
 .Ev PAM_RHOST ,
 .Ev PAM_RUSER ,
 .Ev PAM_SERVICE ,
-.Ev PAM_TTY ,
+.Ev PAM_SM_FUNC ,
+.Ev PAM_TTY
 and
 .Ev PAM_USER .
+.Pp
+The
+.Ev PAM_SM_FUNC
+variable contains the name of the PAM service module function being
+called.
+It may be:
+.Bl -dash -offset indent -compact
+.It
+pam_sm_acct_mgmt
+.It
+pam_sm_authenticate
+.It
+pam_sm_chauthtok
+.It
+pam_sm_close_session
+.It
+pam_sm_open_session
+.It
+pam_sm_setcred
+.El
+.Pp
+If
+.Cm return_prog_exit_status
+is not set (default), the
+.Ev PAM_SM_FUNC
+function returns
+.Er PAM_SUCCESS
+if the program exit status is 0,
+.Er PAM_PERM_DENIED
+otherwise.
+.Pp
+If
+.Cm return_prog_exit_status
+is set, the program exit status is used.
+It should be
+.Er PAM_SUCCESS
+or one of the error codes allowed by the calling
+.Ev PAM_SM_FUNC
+function.
+The valid codes are documented in each function man page.
+If the exit status is not a valid return code,
+.Er PAM_SERVICE_ERR
+is returned.
+Each valid codes numerical value is available as an environment variable
+(eg.\&
+.Ev PAM_SUCESS ,
+.Ev PAM_USER_UNKNOWN ,
+etc).
+This is useful in shell scripts for instance.
 .Sh SEE ALSO
 .Xr pam_get_item 3 ,
 .Xr pam.conf 5 ,
-.Xr pam 8
+.Xr pam 8 ,
+.Xr pam_sm_acct_mgmt 8 ,
+.Xr pam_sm_authenticate 8 ,
+.Xr pam_sm_chauthtok 8,
+.Xr pam_sm_close_session 8 ,
+.Xr pam_sm_open_session 8 ,
+.Xr pam_sm_setcred 8 .
 .Sh AUTHORS
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpam/modules/pam_exec/pam_e=
xec.c
--- a/head/lib/libpam/modules/pam_exec/pam_exec.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/lib/libpam/modules/pam_exec/pam_exec.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -33,7 +33,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libpam/modules/pam_exec/pam_exec.c 234184 201=
2-04-12 14:02:59Z dumbbell $");
=20
 #include <sys/types.h>
 #include <sys/wait.h>
@@ -60,32 +60,86 @@
 	ENV_ITEM(PAM_RUSER),
 };
=20
+struct pe_opts {
+	int	return_prog_exit_status;
+};
+
+#define	PAM_RV_COUNT 24
+
 static int
-_pam_exec(pam_handle_t *pamh __unused, int flags __unused,
-    int argc, const char *argv[])
+parse_options(const char *func, int *argc, const char **argv[],
+    struct pe_opts *options)
+{
+	int i;
+
+	/*
+	 * Parse options:
+	 *   return_prog_exit_status:
+	 *     use the program exit status as the return code of pam_exec
+	 *   --:
+	 *     stop options parsing; what follows is the command to execute
+	 */
+	options->return_prog_exit_status =3D 0;
+
+	for (i =3D 0; i < *argc; ++i) {
+		if (strcmp((*argv)[i], "return_prog_exit_status") =3D=3D 0) {
+			openpam_log(PAM_LOG_DEBUG,
+			    "%s: Option \"return_prog_exit_status\" enabled",
+			    func);
+			options->return_prog_exit_status =3D 1;
+		} else {
+			if (strcmp((*argv)[i], "--") =3D=3D 0) {
+				(*argc)--;
+				(*argv)++;
+			}
+
+			break;
+		}
+	}
+
+	(*argc) -=3D i;
+	(*argv) +=3D i;
+
+	return (0);
+}
+
+static int
+_pam_exec(pam_handle_t *pamh __unused,
+    const char *func, int flags __unused, int argc, const char *argv[],
+    struct pe_opts *options)
 {
 	int envlen, i, nitems, pam_err, status;
-	char *env, **envlist, **tmp;
+	int nitems_rv;
+	char **envlist, **tmp, *envstr;
 	volatile int childerr;
 	pid_t pid;
=20
-	if (argc < 1)
-		return (PAM_SERVICE_ERR);
-
 	/*
 	 * XXX For additional credit, divert child's stdin/stdout/stderr
 	 * to the conversation function.
 	 */
=20
+	/* Check there's a program name left after parsing options. */
+	if (argc < 1) {
+		openpam_log(PAM_LOG_ERROR, "%s: No program specified: aborting",
+		    func);
+		return (PAM_SERVICE_ERR);
+	}
+
 	/*
-	 * Set up the child's environment list.  It consists of the PAM
-	 * environment, plus a few hand-picked PAM items.
+	 * Set up the child's environment list. It consists of the PAM
+	 * environment, plus a few hand-picked PAM items, the pam_sm_*
+	 * function name calling it and, if return_prog_exit_status is
+	 * set, the valid return codes numerical values.
 	 */
 	envlist =3D pam_getenvlist(pamh);
 	for (envlen =3D 0; envlist[envlen] !=3D NULL; ++envlen)
 		/* nothing */ ;
 	nitems =3D sizeof(env_items) / sizeof(*env_items);
-	tmp =3D realloc(envlist, (envlen + nitems + 1) * sizeof(*envlist));
+	/* Count PAM return values put in the environment. */
+	nitems_rv =3D options->return_prog_exit_status ? PAM_RV_COUNT : 0;
+	tmp =3D realloc(envlist, (envlen + nitems + 1 + nitems_rv + 1) *
+	    sizeof(*envlist));
 	if (tmp =3D=3D NULL) {
 		openpam_free_envlist(envlist);
 		return (PAM_BUF_ERR);
@@ -93,12 +147,12 @@
 	envlist =3D tmp;
 	for (i =3D 0; i < nitems; ++i) {
 		const void *item;
-		char *envstr;
=20
 		pam_err =3D pam_get_item(pamh, env_items[i].item, &item);
 		if (pam_err !=3D PAM_SUCCESS || item =3D=3D NULL)
 			continue;
-		asprintf(&envstr, "%s=3D%s", env_items[i].name, item);
+		asprintf(&envstr, "%s=3D%s", env_items[i].name,
+		    (const char *)item);
 		if (envstr =3D=3D NULL) {
 			openpam_free_envlist(envlist);
 			return (PAM_BUF_ERR);
@@ -107,10 +161,59 @@
 		envlist[envlen] =3D NULL;
 	}
=20
+	/* Add the pam_sm_* function name to the environment. */
+	asprintf(&envstr, "PAM_SM_FUNC=3D%s", func);
+	if (envstr =3D=3D NULL) {
+		openpam_free_envlist(envlist);
+		return (PAM_BUF_ERR);
+	}
+	envlist[envlen++] =3D envstr;
+
+	/* Add the PAM return values to the environment. */
+	if (options->return_prog_exit_status) {
+#define	ADD_PAM_RV_TO_ENV(name)						\
+		asprintf(&envstr, #name "=3D%d", name);			\
+		if (envstr =3D=3D NULL) {					\
+			openpam_free_envlist(envlist);			\
+			return (PAM_BUF_ERR);				\
+		}							\
+		envlist[envlen++] =3D envstr
+		/*
+		 * CAUTION: When adding/removing an item in the list
+		 * below, be sure to update the value of PAM_RV_COUNT.
+		 */
+		ADD_PAM_RV_TO_ENV(PAM_ABORT);
+		ADD_PAM_RV_TO_ENV(PAM_ACCT_EXPIRED);
+		ADD_PAM_RV_TO_ENV(PAM_AUTHINFO_UNAVAIL);
+		ADD_PAM_RV_TO_ENV(PAM_AUTHTOK_DISABLE_AGING);
+		ADD_PAM_RV_TO_ENV(PAM_AUTHTOK_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_AUTHTOK_LOCK_BUSY);
+		ADD_PAM_RV_TO_ENV(PAM_AUTHTOK_RECOVERY_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_AUTH_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_BUF_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_CONV_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_CRED_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_CRED_EXPIRED);
+		ADD_PAM_RV_TO_ENV(PAM_CRED_INSUFFICIENT);
+		ADD_PAM_RV_TO_ENV(PAM_CRED_UNAVAIL);
+		ADD_PAM_RV_TO_ENV(PAM_IGNORE);
+		ADD_PAM_RV_TO_ENV(PAM_MAXTRIES);
+		ADD_PAM_RV_TO_ENV(PAM_NEW_AUTHTOK_REQD);
+		ADD_PAM_RV_TO_ENV(PAM_PERM_DENIED);
+		ADD_PAM_RV_TO_ENV(PAM_SERVICE_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_SESSION_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_SUCCESS);
+		ADD_PAM_RV_TO_ENV(PAM_SYSTEM_ERR);
+		ADD_PAM_RV_TO_ENV(PAM_TRY_AGAIN);
+		ADD_PAM_RV_TO_ENV(PAM_USER_UNKNOWN);
+	}
+
+	envlist[envlen] =3D NULL;
+
 	/*
 	 * Fork and run the command.  By using vfork() instead of fork(),
 	 * we can distinguish between an execve() failure and a non-zero
-	 * exit code from the command.
+	 * exit status from the command.
 	 */
 	childerr =3D 0;
 	if ((pid =3D vfork()) =3D=3D 0) {
@@ -120,81 +223,276 @@
 	}
 	openpam_free_envlist(envlist);
 	if (pid =3D=3D -1) {
-		openpam_log(PAM_LOG_ERROR, "vfork(): %m");
+		openpam_log(PAM_LOG_ERROR, "%s: vfork(): %m", func);
 		return (PAM_SYSTEM_ERR);
 	}
-	if (waitpid(pid, &status, 0) =3D=3D -1) {
-		openpam_log(PAM_LOG_ERROR, "waitpid(): %m");
+	while (waitpid(pid, &status, 0) =3D=3D -1) {
+		if (errno =3D=3D EINTR)
+			continue;
+		openpam_log(PAM_LOG_ERROR, "%s: waitpid(): %m", func);
 		return (PAM_SYSTEM_ERR);
 	}
 	if (childerr !=3D 0) {
-		openpam_log(PAM_LOG_ERROR, "execve(): %m");
+		openpam_log(PAM_LOG_ERROR, "%s: execve(): %m", func);
 		return (PAM_SYSTEM_ERR);
 	}
 	if (WIFSIGNALED(status)) {
-		openpam_log(PAM_LOG_ERROR, "%s caught signal %d%s",
-		    argv[0], WTERMSIG(status),
+		openpam_log(PAM_LOG_ERROR, "%s: %s caught signal %d%s",
+		    func, argv[0], WTERMSIG(status),
 		    WCOREDUMP(status) ? " (core dumped)" : "");
-		return (PAM_SYSTEM_ERR);
+		return (PAM_SERVICE_ERR);
 	}
 	if (!WIFEXITED(status)) {
-		openpam_log(PAM_LOG_ERROR, "unknown status 0x%x", status);
-		return (PAM_SYSTEM_ERR);
+		openpam_log(PAM_LOG_ERROR, "%s: unknown status 0x%x",
+		    func, status);
+		return (PAM_SERVICE_ERR);
 	}
-	if (WEXITSTATUS(status) !=3D 0) {
-		openpam_log(PAM_LOG_ERROR, "%s returned code %d",
-		    argv[0], WEXITSTATUS(status));
-		return (PAM_SYSTEM_ERR);
+
+	if (options->return_prog_exit_status) {
+		openpam_log(PAM_LOG_DEBUG,
+		    "%s: Use program exit status as return value: %d",
+		    func, WEXITSTATUS(status));
+		return (WEXITSTATUS(status));
+	} else {
+		return (WEXITSTATUS(status) =3D=3D 0 ?
+		    PAM_SUCCESS : PAM_PERM_DENIED);
 	}
-	return (PAM_SUCCESS);
 }
=20
 PAM_EXTERN int
 pam_sm_authenticate(pam_handle_t *pamh, int flags,
     int argc, const char *argv[])
 {
+	int ret;
+	struct pe_opts options;
=20
-	return (_pam_exec(pamh, flags, argc, argv));
+	ret =3D parse_options(__func__, &argc, &argv, &options);
+	if (ret !=3D 0)
+		return (PAM_SERVICE_ERR);
+
+	ret =3D _pam_exec(pamh, __func__, flags, argc, argv, &options);
+
+	/*
+	 * We must check that the program returned a valid code for this
+	 * function.
+	 */
+	switch (ret) {
+	case PAM_SUCCESS:
+	case PAM_ABORT:
+	case PAM_AUTHINFO_UNAVAIL:
+	case PAM_AUTH_ERR:
+	case PAM_BUF_ERR:
+	case PAM_CONV_ERR:
+	case PAM_CRED_INSUFFICIENT:
+	case PAM_IGNORE:
+	case PAM_MAXTRIES:
+	case PAM_PERM_DENIED:
+	case PAM_SERVICE_ERR:
+	case PAM_SYSTEM_ERR:
+	case PAM_USER_UNKNOWN:
+		break;
+	default:
+		openpam_log(PAM_LOG_ERROR, "%s returned invalid code %d",
+		    argv[0], ret);
+		ret =3D PAM_SERVICE_ERR;
+	}
+
+	return (ret);
 }
=20
 PAM_EXTERN int
 pam_sm_setcred(pam_handle_t *pamh, int flags,
     int argc, const char *argv[])
 {
+	int ret;
+	struct pe_opts options;
=20
-	return (_pam_exec(pamh, flags, argc, argv));
+	ret =3D parse_options(__func__, &argc, &argv, &options);
+	if (ret !=3D 0)
+		return (PAM_SERVICE_ERR);
+
+	ret =3D _pam_exec(pamh, __func__, flags, argc, argv, &options);
+
+	/*
+	 * We must check that the program returned a valid code for this
+	 * function.
+	 */
+	switch (ret) {
+	case PAM_SUCCESS:
+	case PAM_ABORT:
+	case PAM_BUF_ERR:
+	case PAM_CONV_ERR:
+	case PAM_CRED_ERR:
+	case PAM_CRED_EXPIRED:
+	case PAM_CRED_UNAVAIL:
+	case PAM_IGNORE:
+	case PAM_PERM_DENIED:
+	case PAM_SERVICE_ERR:
+	case PAM_SYSTEM_ERR:
+	case PAM_USER_UNKNOWN:
+		break;
+	default:
+		openpam_log(PAM_LOG_ERROR, "%s returned invalid code %d",
+		    argv[0], ret);
+		ret =3D PAM_SERVICE_ERR;
+	}
+
+	return (ret);
 }
=20
 PAM_EXTERN int
 pam_sm_acct_mgmt(pam_handle_t *pamh, int flags,
     int argc, const char *argv[])
 {
+	int ret;
+	struct pe_opts options;
=20
-	return (_pam_exec(pamh, flags, argc, argv));
+	ret =3D parse_options(__func__, &argc, &argv, &options);
+	if (ret !=3D 0)
+		return (PAM_SERVICE_ERR);
+
+	ret =3D _pam_exec(pamh, __func__, flags, argc, argv, &options);
+
+	/*
+	 * We must check that the program returned a valid code for this
+	 * function.
+	 */
+	switch (ret) {
+	case PAM_SUCCESS:
+	case PAM_ABORT:
+	case PAM_ACCT_EXPIRED:
+	case PAM_AUTH_ERR:
+	case PAM_BUF_ERR:
+	case PAM_CONV_ERR:
+	case PAM_IGNORE:
+	case PAM_NEW_AUTHTOK_REQD:
+	case PAM_PERM_DENIED:
+	case PAM_SERVICE_ERR:
+	case PAM_SYSTEM_ERR:
+	case PAM_USER_UNKNOWN:
+		break;
+	default:
+		openpam_log(PAM_LOG_ERROR, "%s returned invalid code %d",
+		    argv[0], ret);
+		ret =3D PAM_SERVICE_ERR;
+	}
+
+	return (ret);
 }
=20
 PAM_EXTERN int
 pam_sm_open_session(pam_handle_t *pamh, int flags,
     int argc, const char *argv[])
 {
+	int ret;
+	struct pe_opts options;
=20
-	return (_pam_exec(pamh, flags, argc, argv));
+	ret =3D parse_options(__func__, &argc, &argv, &options);
+	if (ret !=3D 0)
+		return (PAM_SERVICE_ERR);
+
+	ret =3D _pam_exec(pamh, __func__, flags, argc, argv, &options);
+
+	/*
+	 * We must check that the program returned a valid code for this
+	 * function.
+	 */
+	switch (ret) {
+	case PAM_SUCCESS:
+	case PAM_ABORT:
+	case PAM_BUF_ERR:
+	case PAM_CONV_ERR:
+	case PAM_IGNORE:
+	case PAM_PERM_DENIED:
+	case PAM_SERVICE_ERR:
+	case PAM_SESSION_ERR:
+	case PAM_SYSTEM_ERR:
+		break;
+	default:
+		openpam_log(PAM_LOG_ERROR, "%s returned invalid code %d",
+		    argv[0], ret);
+		ret =3D PAM_SERVICE_ERR;
+	}
+
+	return (ret);
 }
=20
 PAM_EXTERN int
 pam_sm_close_session(pam_handle_t *pamh, int flags,
     int argc, const char *argv[])
 {
+	int ret;
+	struct pe_opts options;
=20
-	return (_pam_exec(pamh, flags, argc, argv));
+	ret =3D parse_options(__func__, &argc, &argv, &options);
+	if (ret !=3D 0)
+		return (PAM_SERVICE_ERR);
+
+	ret =3D _pam_exec(pamh, __func__, flags, argc, argv, &options);
+
+	/*
+	 * We must check that the program returned a valid code for this
+	 * function.
+	 */
+	switch (ret) {
+	case PAM_SUCCESS:
+	case PAM_ABORT:
+	case PAM_BUF_ERR:
+	case PAM_CONV_ERR:
+	case PAM_IGNORE:
+	case PAM_PERM_DENIED:
+	case PAM_SERVICE_ERR:
+	case PAM_SESSION_ERR:
+	case PAM_SYSTEM_ERR:
+		break;
+	default:
+		openpam_log(PAM_LOG_ERROR, "%s returned invalid code %d",
+		    argv[0], ret);
+		ret =3D PAM_SERVICE_ERR;
+	}
+
+	return (ret);
 }
=20
 PAM_EXTERN int
 pam_sm_chauthtok(pam_handle_t *pamh, int flags,
     int argc, const char *argv[])
 {
+	int ret;
+	struct pe_opts options;
=20
-	return (_pam_exec(pamh, flags, argc, argv));
+	ret =3D parse_options(__func__, &argc, &argv, &options);
+	if (ret !=3D 0)
+		return (PAM_SERVICE_ERR);
+
+	ret =3D _pam_exec(pamh, __func__, flags, argc, argv, &options);
+
+	/*
+	 * We must check that the program returned a valid code for this
+	 * function.
+	 */
+	switch (ret) {
+	case PAM_SUCCESS:
+	case PAM_ABORT:
+	case PAM_AUTHTOK_DISABLE_AGING:
+	case PAM_AUTHTOK_ERR:
+	case PAM_AUTHTOK_LOCK_BUSY:
+	case PAM_AUTHTOK_RECOVERY_ERR:
+	case PAM_BUF_ERR:
+	case PAM_CONV_ERR:
+	case PAM_IGNORE:
+	case PAM_PERM_DENIED:
+	case PAM_SERVICE_ERR:
+	case PAM_SYSTEM_ERR:
+	case PAM_TRY_AGAIN:
+		break;
+	default:
+		openpam_log(PAM_LOG_ERROR, "%s returned invalid code %d",
+		    argv[0], ret);
+		ret =3D PAM_SERVICE_ERR;
+	}
+
+	return (ret);
 }
=20
 PAM_MODULE_ENTRY("pam_exec");
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpam/modules/pam_krb5/pam_k=
rb5.c
--- a/head/lib/libpam/modules/pam_krb5/pam_krb5.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/lib/libpam/modules/pam_krb5/pam_krb5.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -48,7 +48,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libpam/modules/pam_krb5/pam_krb5.c 233406 201=
2-03-24 01:02:03Z stas $");
=20
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -92,6 +92,13 @@
 #define PAM_OPT_NO_USER_CHECK	"no_user_check"
 #define PAM_OPT_REUSE_CCACHE	"reuse_ccache"
=20
+#define	PAM_LOG_KRB5_ERR(ctx, rv, fmt, ...)				\
+	do {								\
+		const char *krb5msg =3D krb5_get_error_message(ctx, rv);	\
+		PAM_LOG(fmt ": %s", ##__VA_ARGS__, krb5msg);		\
+		krb5_free_error_message(ctx, krb5msg);			\
+	} while (0)
+
 /*
  * authentication management
  */
@@ -104,7 +111,7 @@
 	krb5_creds creds;
 	krb5_principal princ;
 	krb5_ccache ccache;
-	krb5_get_init_creds_opt opts;
+	krb5_get_init_creds_opt *opts;
 	struct passwd *pwd;
 	int retval;
 	const void *ccache_data;
@@ -139,13 +146,6 @@
=20
 	PAM_LOG("Context initialised");
=20
-	krb5_get_init_creds_opt_init(&opts);
-
-	if (openpam_get_option(pamh, PAM_OPT_FORWARDABLE))
-		krb5_get_init_creds_opt_set_forwardable(&opts, 1);
-
-	PAM_LOG("Credentials initialised");
-
 	krbret =3D krb5_cc_register(pam_context, &krb5_mcc_ops, FALSE);
 	if (krbret !=3D 0 && krbret !=3D KRB5_CC_TYPE_EXISTS) {
 		PAM_VERBOSE_ERROR("Kerberos 5 error");
@@ -166,8 +166,7 @@
 	krbret =3D krb5_parse_name(pam_context, principal, &princ);
 	free(principal);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_parse_name(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret, "Error krb5_parse_name()");
 		PAM_VERBOSE_ERROR("Kerberos 5 error");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup3;
@@ -179,8 +178,8 @@
 	princ_name =3D NULL;
 	krbret =3D krb5_unparse_name(pam_context, princ, &princ_name);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_unparse_name(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_unparse_name()");
 		PAM_VERBOSE_ERROR("Kerberos 5 error");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup2;
@@ -206,8 +205,8 @@
 			    sizeof(luser), luser);
 			if (krbret !=3D 0) {
 				PAM_VERBOSE_ERROR("Kerberos 5 error");
-				PAM_LOG("Error krb5_aname_to_localname(): %s",
-				    krb5_get_err_text(pam_context, krbret));
+				PAM_LOG_KRB5_ERR(pam_context, krbret,
+				    "Error krb5_aname_to_localname()");
 				retval =3D PAM_USER_UNKNOWN;
 				goto cleanup2;
 			}
@@ -228,14 +227,30 @@
 		PAM_LOG("Done getpwnam()");
 	}
=20
+	/* Initialize credentials request options. */
+	krbret =3D krb5_get_init_creds_opt_alloc(pam_context, &opts);
+	if (krbret !=3D 0) {
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_get_init_creds_opt_alloc()");
+		PAM_VERBOSE_ERROR("Kerberos 5 error");
+		retval =3D PAM_SERVICE_ERR;
+		goto cleanup2;
+	}
+
+	if (openpam_get_option(pamh, PAM_OPT_FORWARDABLE))
+		krb5_get_init_creds_opt_set_forwardable(opts, 1);
+
+	PAM_LOG("Credential options initialised");
+
 	/* Get a TGT */
 	memset(&creds, 0, sizeof(krb5_creds));
 	krbret =3D krb5_get_init_creds_password(pam_context, &creds, princ,
-	    pass, NULL, pamh, 0, NULL, &opts);
+	    pass, NULL, pamh, 0, NULL, opts);
+	krb5_get_init_creds_opt_free(pam_context, opts);
 	if (krbret !=3D 0) {
 		PAM_VERBOSE_ERROR("Kerberos 5 error");
-		PAM_LOG("Error krb5_get_init_creds_password(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_get_init_creds_password()");
 		retval =3D PAM_AUTH_ERR;
 		goto cleanup2;
 	}
@@ -243,27 +258,27 @@
 	PAM_LOG("Got TGT");
=20
 	/* Generate a temporary cache */
-	krbret =3D krb5_cc_gen_new(pam_context, &krb5_mcc_ops, &ccache);
+	krbret =3D krb5_cc_new_unique(pam_context, krb5_cc_type_memory, NULL, &cc=
ache);
 	if (krbret !=3D 0) {
 		PAM_VERBOSE_ERROR("Kerberos 5 error");
-		PAM_LOG("Error krb5_cc_gen_new(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_new_unique()");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup;
 	}
 	krbret =3D krb5_cc_initialize(pam_context, ccache, princ);
 	if (krbret !=3D 0) {
 		PAM_VERBOSE_ERROR("Kerberos 5 error");
-		PAM_LOG("Error krb5_cc_initialize(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_initialize()");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup;
 	}
 	krbret =3D krb5_cc_store_cred(pam_context, ccache, &creds);
 	if (krbret !=3D 0) {
 		PAM_VERBOSE_ERROR("Kerberos 5 error");
-		PAM_LOG("Error krb5_cc_store_cred(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_store_cred()");
 		krb5_cc_destroy(pam_context, ccache);
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup;
@@ -406,8 +421,8 @@
 	}
 	krbret =3D krb5_cc_resolve(pam_context, cache_data, &ccache_temp);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_cc_resolve(\"%s\"): %s", (const char *)cache_data,
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_resolve(\"%s\")", (const char *)cache_data);
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup3;
 	}
@@ -479,22 +494,21 @@
 	/* Initialize the new ccache */
 	krbret =3D krb5_cc_get_principal(pam_context, ccache_temp, &princ);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_cc_get_principal(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_get_principal()");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup3;
 	}
 	krbret =3D krb5_cc_resolve(pam_context, cache_name, &ccache_perm);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_cc_resolve(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret, "Error krb5_cc_resolve()");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup2;
 	}
 	krbret =3D krb5_cc_initialize(pam_context, ccache_perm, princ);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_cc_initialize(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_initialize()");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup2;
 	}
@@ -504,8 +518,8 @@
 	/* Prepare for iteration over creds */
 	krbret =3D krb5_cc_start_seq_get(pam_context, ccache_temp, &cursor);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_cc_start_seq_get(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_start_seq_get()");
 		krb5_cc_destroy(pam_context, ccache_perm);
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup2;
@@ -518,8 +532,8 @@
 				&cursor, &creds) =3D=3D 0)) {
 		krbret =3D krb5_cc_store_cred(pam_context, ccache_perm, &creds);
 		if (krbret !=3D 0) {
-			PAM_LOG("Error krb5_cc_store_cred(): %s",
-			    krb5_get_err_text(pam_context, krbret));
+			PAM_LOG_KRB5_ERR(pam_context, krbret,
+			    "Error krb5_cc_store_cred()");
 			krb5_cc_destroy(pam_context, ccache_perm);
 			krb5_free_cred_contents(pam_context, &creds);
 			retval =3D PAM_SERVICE_ERR;
@@ -620,8 +634,8 @@
=20
 	krbret =3D krb5_cc_resolve(pam_context, (const char *)ccache_name, &ccach=
e);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_cc_resolve(\"%s\"): %s", (const char *)ccache_name,
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_resolve(\"%s\")", (const char *)ccache_name);
 		krb5_free_context(pam_context);
 		return (PAM_PERM_DENIED);
 	}
@@ -631,8 +645,8 @@
=20
 	krbret =3D krb5_cc_get_principal(pam_context, ccache, &princ);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_cc_get_principal(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_cc_get_principal()");
 		retval =3D PAM_PERM_DENIED;;
 		goto cleanup;
 	}
@@ -666,7 +680,7 @@
 	krb5_context pam_context;
 	krb5_creds creds;
 	krb5_principal princ;
-	krb5_get_init_creds_opt opts;
+	krb5_get_init_creds_opt *opts;
 	krb5_data result_code_string, result_string;
 	int result_code, retval;
 	const char *pass;
@@ -690,15 +704,11 @@
=20
 	PAM_LOG("Context initialised");
=20
-	krb5_get_init_creds_opt_init(&opts);
-
-	PAM_LOG("Credentials options initialised");
-
 	/* Get principal name */
 	krbret =3D krb5_parse_name(pam_context, (const char *)user, &princ);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_parse_name(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_parse_name()");
 		retval =3D PAM_USER_UNKNOWN;
 		goto cleanup3;
 	}
@@ -707,8 +717,8 @@
 	princ_name =3D NULL;
 	krbret =3D krb5_unparse_name(pam_context, princ, &princ_name);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_unparse_name(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_unparse_name()");
 		retval =3D PAM_SERVICE_ERR;
 		goto cleanup2;
 	}
@@ -722,12 +732,25 @@
=20
 	PAM_LOG("Got password");
=20
+	/* Initialize credentials request options. */
+	krbret =3D krb5_get_init_creds_opt_alloc(pam_context, &opts);
+	if (krbret !=3D 0) {
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_get_init_creds_opt_alloc()");
+		PAM_VERBOSE_ERROR("Kerberos 5 error");
+		retval =3D PAM_SERVICE_ERR;
+		goto cleanup2;
+	}
+
+	PAM_LOG("Credentials options initialised");
+
 	memset(&creds, 0, sizeof(krb5_creds));
 	krbret =3D krb5_get_init_creds_password(pam_context, &creds, princ,
-	    pass, NULL, pamh, 0, "kadmin/changepw", &opts);
+	    pass, NULL, pamh, 0, "kadmin/changepw", opts);
+	krb5_get_init_creds_opt_free(pam_context, opts);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_get_init_creds_password(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_get_init_creds_password()");
 		retval =3D PAM_AUTH_ERR;
 		goto cleanup2;
 	}
@@ -752,12 +775,12 @@
 		retval =3D PAM_BUF_ERR;
 		goto cleanup;
 	}
-	krbret =3D krb5_change_password(pam_context, &creds, passdup,
+	krbret =3D krb5_set_password(pam_context, &creds, passdup, NULL,
 	    &result_code, &result_code_string, &result_string);
 	free(passdup);
 	if (krbret !=3D 0) {
-		PAM_LOG("Error krb5_change_password(): %s",
-		    krb5_get_err_text(pam_context, krbret));
+		PAM_LOG_KRB5_ERR(pam_context, krbret,
+		    "Error krb5_change_password()");
 		retval =3D PAM_AUTHTOK_ERR;
 		goto cleanup;
 	}
@@ -840,11 +863,14 @@
 		retval =3D krb5_sname_to_principal(context, NULL, *service,
 		    KRB5_NT_SRV_HST, &princ);
 		if (retval !=3D 0) {
-			if (debug)
+			if (debug) {
+				const char *msg =3D krb5_get_error_message(
+				    context, retval);
 				syslog(LOG_DEBUG,
 				    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
-				    "krb5_sname_to_principal()",
-				    krb5_get_err_text(context, retval));
+				    "krb5_sname_to_principal()", msg);
+				krb5_free_error_message(context, msg);
+			}
 			return -1;
 		}
=20
@@ -866,11 +892,14 @@
 	}
 	if (retval !=3D 0) {	/* failed to find key */
 		/* Keytab or service key does not exist */
-		if (debug)
+		if (debug) {
+			const char *msg =3D krb5_get_error_message(context,
+			    retval);
 			syslog(LOG_DEBUG,
 			    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
-			    "krb5_kt_read_service_key()",
-			    krb5_get_err_text(context, retval));
+			    "krb5_kt_read_service_key()", msg);
+			krb5_free_error_message(context, msg);
+		}
 		retval =3D 0;
 		goto cleanup;
 	}
@@ -886,11 +915,14 @@
 		auth_context =3D NULL;	/* setup for rd_req */
 	}
 	if (retval) {
-		if (debug)
+		if (debug) {
+			const char *msg =3D krb5_get_error_message(context,
+			    retval);
 			syslog(LOG_DEBUG,
 			    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
-			    "krb5_mk_req()",
-			    krb5_get_err_text(context, retval));
+			    "krb5_mk_req()", msg);
+			krb5_free_error_message(context, msg);
+		}
 		retval =3D -1;
 		goto cleanup;
 	}
@@ -899,11 +931,14 @@
 	retval =3D krb5_rd_req(context, &auth_context, &packet, princ, NULL,
 	    NULL, NULL);
 	if (retval) {
-		if (debug)
+		if (debug) {
+			const char *msg =3D krb5_get_error_message(context,
+			    retval);
 			syslog(LOG_DEBUG,
 			    "pam_krb5: verify_krb_v5_tgt(): %s: %s",
-			    "krb5_rd_req()",
-			    krb5_get_err_text(context, retval));
+			    "krb5_rd_req()", msg);
+			krb5_free_error_message(context, msg);
+		}
 		retval =3D -1;
 	}
 	else
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpam/modules/pam_ksu/pam_ks=
u.c
--- a/head/lib/libpam/modules/pam_ksu/pam_ksu.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/lib/libpam/modules/pam_ksu/pam_ksu.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -24,7 +24,7 @@
  * SUCH DAMAGE.
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libpam/modules/pam_ksu/pam_ksu.c 233302 2012-=
03-22 11:18:14Z stas $");
=20
 #include <sys/param.h>
 #include <errno.h>
@@ -70,8 +70,9 @@
 	PAM_LOG("Got ruser: %s", (const char *)ruser);
 	rv =3D krb5_init_context(&context);
 	if (rv !=3D 0) {
-		PAM_LOG("krb5_init_context failed: %s",
-			krb5_get_err_text(context, rv));
+		const char *msg =3D krb5_get_error_message(context, rv);
+		PAM_LOG("krb5_init_context failed: %s", msg);
+		krb5_free_error_message(context, msg);
 		return (PAM_SERVICE_ERR);
 	}
 	rv =3D get_su_principal(context, user, ruser, &su_principal_name, &su_pri=
ncipal);
@@ -112,7 +113,7 @@
     krb5_principal su_principal)
 {
 	krb5_creds	 creds;
-	krb5_get_init_creds_opt gic_opt;
+	krb5_get_init_creds_opt *gic_opt;
 	krb5_verify_init_creds_opt vic_opt;
 	const char	*pass;
 	char		*prompt;
@@ -120,7 +121,6 @@
 	int		 pamret;
=20
 	prompt =3D NULL;
-	krb5_get_init_creds_opt_init(&gic_opt);
 	krb5_verify_init_creds_opt_init(&vic_opt);
 	if (su_principal_name !=3D NULL)
 		(void)asprintf(&prompt, "Password for %s:", su_principal_name);
@@ -133,11 +133,20 @@
 	free(prompt);
 	if (pamret !=3D PAM_SUCCESS)
 		return (pamret);
+	rv =3D krb5_get_init_creds_opt_alloc(context, &gic_opt);
+	if (rv !=3D 0) {
+		const char *msg =3D krb5_get_error_message(context, rv);
+		PAM_LOG("krb5_get_init_creds_opt_alloc: %s", msg);
+		krb5_free_error_message(context, msg);
+		return (PAM_AUTH_ERR);
+	}
 	rv =3D krb5_get_init_creds_password(context, &creds, su_principal,
-	    pass, NULL, NULL, 0, NULL, &gic_opt);
+	    pass, NULL, NULL, 0, NULL, gic_opt);
+	krb5_get_init_creds_opt_free(context, gic_opt);
 	if (rv !=3D 0) {
-		PAM_LOG("krb5_get_init_creds_password: %s",
-			krb5_get_err_text(context, rv));
+		const char *msg =3D krb5_get_error_message(context, rv);
+		PAM_LOG("krb5_get_init_creds_password: %s", msg);
+		krb5_free_error_message(context, msg);
 		return (PAM_AUTH_ERR);
 	}
 	krb5_verify_init_creds_opt_set_ap_req_nofail(&vic_opt, 1);
@@ -145,8 +154,9 @@
 	    &vic_opt);
 	krb5_free_cred_contents(context, &creds);
 	if (rv !=3D 0) {
-		PAM_LOG("krb5_verify_init_creds: %s",
-		       krb5_get_err_text(context, rv));
+		const char *msg =3D krb5_get_error_message(context, rv);
+		PAM_LOG("krb5_verify_init_creds: %s", msg);
+		krb5_free_error_message(context, msg);
 		return (PAM_AUTH_ERR);
 	}
 	return (PAM_SUCCESS);
@@ -220,8 +230,9 @@
 	rv =3D krb5_unparse_name(context, default_principal, &principal_name);
 	krb5_free_principal(context, default_principal);
 	if (rv !=3D 0) {
-		PAM_LOG("krb5_unparse_name: %s",
-		    krb5_get_err_text(context, rv));
+		const char *msg =3D krb5_get_error_message(context, rv);
+		PAM_LOG("krb5_unparse_name: %s", msg);
+		krb5_free_error_message(context, msg);
 		return (rv);
 	}
 	PAM_LOG("Default principal name: %s", principal_name);
@@ -243,8 +254,9 @@
 		return (errno);
 	rv =3D krb5_parse_name(context, *su_principal_name, &default_principal);
 	if (rv !=3D 0) {
-		PAM_LOG("krb5_parse_name `%s': %s", *su_principal_name,
-		    krb5_get_err_text(context, rv));
+		const char *msg =3D krb5_get_error_message(context, rv);
+		PAM_LOG("krb5_parse_name `%s': %s", *su_principal_name, msg);
+		krb5_free_error_message(context, msg);
 		free(*su_principal_name);
 		return (rv);
 	}
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpam/modules/pam_nologin/pa=
m_nologin.8
--- a/head/lib/libpam/modules/pam_nologin/pam_nologin.8	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/lib/libpam/modules/pam_nologin/pam_nologin.8	Tue Apr 17 11:51:51=
 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libpam/modules/pam_nologin/pam_nologin.8 233648 201=
2-03-29 05:02:12Z eadler $
 .\"
 .Dd June 10, 2007
 .Dt PAM_NOLOGIN 8
@@ -48,7 +48,7 @@
 feature.
 .Ss NoLogin Account Management Module
 The NoLogin account management component,
-.Fn pam_sm_acct_mgmt ,=20
+.Fn pam_sm_acct_mgmt ,
 verifies whether logins are administratively disabled via
 .Xr nologin 5 .
 It returns success if the user's login class has an "ignorenologin"
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/Makefile
--- a/head/lib/libpmc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/lib/libpmc/Makefile 232366 2012-03-01 21:23:26Z davide $
+# $FreeBSD: head/lib/libpmc/Makefile 233628 2012-03-28 20:58:30Z fabient $
=20
 LIB=3D	pmc
=20
@@ -20,6 +20,7 @@
 MAN+=3D	pmc_set.3
 MAN+=3D	pmc_start.3
 MAN+=3D	pmclog.3
+MAN+=3D	pmc.soft.3
=20
 # PMC-dependent manual pages
 .if ${MACHINE_CPUARCH} =3D=3D "i386" || ${MACHINE_CPUARCH} =3D=3D "amd64"
@@ -42,6 +43,9 @@
 MAN+=3D	pmc.tsc.3
 .elif ${MACHINE_CPUARCH} =3D=3D "arm" && ${CPUTYPE} =3D=3D "xscale"
 MAN+=3D	pmc.xscale.3
+.elif ${MACHINE_CPUARCH} =3D=3D "mips"
+MAN+=3D	pmc.mips24k.3
+MAN+=3D	pmc.octeon.3
 .endif
=20
 MLINKS+=3D \
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/libpmc.c
--- a/head/lib/libpmc/libpmc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/libpmc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libpmc/libpmc.c 232366 2012-03-01 21:23:26Z d=
avide $");
+__FBSDID("$FreeBSD: head/lib/libpmc/libpmc.c 233628 2012-03-28 20:58:30Z f=
abient $");
=20
 #include <sys/types.h>
 #include <sys/module.h>
@@ -77,11 +77,12 @@
 static int xscale_allocate_pmc(enum pmc_event _pe, char *_ctrspec,
     struct pmc_op_pmcallocate *_pmc_config);
 #endif
-
 #if defined(__mips__)
-static int mips24k_allocate_pmc(enum pmc_event _pe, char* ctrspec,
+static int mips_allocate_pmc(enum pmc_event _pe, char* ctrspec,
 			     struct pmc_op_pmcallocate *_pmc_config);
 #endif /* __mips__ */
+static int soft_allocate_pmc(enum pmc_event _pe, char *_ctrspec,
+    struct pmc_op_pmcallocate *_pmc_config);
=20
 #if defined(__powerpc__)
 static int ppc7450_allocate_pmc(enum pmc_event _pe, char* ctrspec,
@@ -152,9 +153,12 @@
 PMC_CLASSDEP_TABLE(p6, P6);
 PMC_CLASSDEP_TABLE(xscale, XSCALE);
 PMC_CLASSDEP_TABLE(mips24k, MIPS24K);
+PMC_CLASSDEP_TABLE(octeon, OCTEON);
 PMC_CLASSDEP_TABLE(ucf, UCF);
 PMC_CLASSDEP_TABLE(ppc7450, PPC7450);
=20
+static struct pmc_event_descr soft_event_table[PMC_EV_DYN_COUNT];
+
 #undef	__PMC_EV_ALIAS
 #define	__PMC_EV_ALIAS(N,CODE) 	{ N, PMC_EV_##CODE },
=20
@@ -214,20 +218,22 @@
 		PMC_CLASS_##C, __VA_ARGS__			\
 	}
=20
-PMC_MDEP_TABLE(atom, IAP, PMC_CLASS_IAF, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(core, IAP, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(core2, IAP, PMC_CLASS_IAF, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(corei7, IAP, PMC_CLASS_IAF, PMC_CLASS_TSC, PMC_CLASS_UCF, P=
MC_CLASS_UCP);
-PMC_MDEP_TABLE(sandybridge, IAP, PMC_CLASS_IAF, PMC_CLASS_TSC, PMC_CLASS_U=
CF, PMC_CLASS_UCP);
-PMC_MDEP_TABLE(westmere, IAP, PMC_CLASS_IAF, PMC_CLASS_TSC, PMC_CLASS_UCF,=
 PMC_CLASS_UCP);
-PMC_MDEP_TABLE(k7, K7, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(k8, K8, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(p4, P4, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(p5, P5, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(p6, P6, PMC_CLASS_TSC);
-PMC_MDEP_TABLE(xscale, XSCALE, PMC_CLASS_XSCALE);
-PMC_MDEP_TABLE(mips24k, MIPS24K, PMC_CLASS_MIPS24K);
-PMC_MDEP_TABLE(ppc7450, PPC7450, PMC_CLASS_PPC7450);
+PMC_MDEP_TABLE(atom, IAP, PMC_CLASS_SOFT, PMC_CLASS_IAF, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(core, IAP, PMC_CLASS_SOFT, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(core2, IAP, PMC_CLASS_SOFT, PMC_CLASS_IAF, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(corei7, IAP, PMC_CLASS_SOFT, PMC_CLASS_IAF, PMC_CLASS_TSC, =
PMC_CLASS_UCF, PMC_CLASS_UCP);
+PMC_MDEP_TABLE(sandybridge, IAP, PMC_CLASS_SOFT, PMC_CLASS_IAF, PMC_CLASS_=
TSC, PMC_CLASS_UCF, PMC_CLASS_UCP);
+PMC_MDEP_TABLE(westmere, IAP, PMC_CLASS_SOFT, PMC_CLASS_IAF, PMC_CLASS_TSC=
, PMC_CLASS_UCF, PMC_CLASS_UCP);
+PMC_MDEP_TABLE(k7, K7, PMC_CLASS_SOFT, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(k8, K8, PMC_CLASS_SOFT, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(p4, P4, PMC_CLASS_SOFT, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(p5, P5, PMC_CLASS_SOFT, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(p6, P6, PMC_CLASS_SOFT, PMC_CLASS_TSC);
+PMC_MDEP_TABLE(xscale, XSCALE, PMC_CLASS_SOFT, PMC_CLASS_XSCALE);
+PMC_MDEP_TABLE(mips24k, MIPS24K, PMC_CLASS_SOFT, PMC_CLASS_MIPS24K);
+PMC_MDEP_TABLE(octeon, OCTEON, PMC_CLASS_SOFT, PMC_CLASS_OCTEON);
+PMC_MDEP_TABLE(ppc7450, PPC7450, PMC_CLASS_SOFT, PMC_CLASS_PPC7450);
+PMC_MDEP_TABLE(generic, SOFT, PMC_CLASS_SOFT);
=20
 static const struct pmc_event_descr tsc_event_table[] =3D
 {
@@ -277,15 +283,24 @@
 #if	defined(__XSCALE__)
 PMC_CLASS_TABLE_DESC(xscale, XSCALE, xscale, xscale);
 #endif
-
 #if defined(__mips__)
-PMC_CLASS_TABLE_DESC(mips24k, MIPS24K, mips24k, mips24k);
+PMC_CLASS_TABLE_DESC(mips24k, MIPS24K, mips24k, mips);
+PMC_CLASS_TABLE_DESC(octeon, OCTEON, octeon, mips);
 #endif /* __mips__ */
-
 #if defined(__powerpc__)
 PMC_CLASS_TABLE_DESC(ppc7450, PPC7450, ppc7450, ppc7450);
 #endif
=20
+static struct pmc_class_descr soft_class_table_descr =3D
+{
+	.pm_evc_name  =3D "SOFT-",
+	.pm_evc_name_size =3D sizeof("SOFT-") - 1,
+	.pm_evc_class =3D PMC_CLASS_SOFT,
+	.pm_evc_event_table =3D NULL,
+	.pm_evc_event_table_size =3D 0,
+	.pm_evc_allocate_pmc =3D soft_allocate_pmc
+};
+
 #undef	PMC_CLASS_TABLE_DESC
=20
 static const struct pmc_class_descr **pmc_class_table;
@@ -340,9 +355,12 @@
 	__PMC_STATES()
 };
=20
-static int pmc_syscall =3D -1;		/* filled in by pmc_init() */
-
-static struct pmc_cpuinfo cpu_info;	/* filled in by pmc_init() */
+/*
+ * Filled in by pmc_init().
+ */
+static int pmc_syscall =3D -1;
+static struct pmc_cpuinfo cpu_info;
+static struct pmc_op_getdyneventinfo soft_event_info;
=20
 /* Event masks for events */
 struct pmc_masks {
@@ -2176,6 +2194,25 @@
 }
 #endif
=20
+static struct pmc_event_alias generic_aliases[] =3D {
+	EV_ALIAS("instructions",		"SOFT-CLOCK.HARD"),
+	EV_ALIAS(NULL, NULL)
+};
+
+static int
+soft_allocate_pmc(enum pmc_event pe, char *ctrspec,
+    struct pmc_op_pmcallocate *pmc_config)
+{
+	(void)ctrspec;
+	(void)pmc_config;
+
+	if (pe < PMC_EV_SOFT_FIRST || pe > PMC_EV_SOFT_LAST)
+		return (-1);
+
+	pmc_config->pm_caps |=3D (PMC_CAP_READ | PMC_CAP_WRITE);
+	return (0);
+}
+
 #if	defined(__XSCALE__)
=20
 static struct pmc_event_alias xscale_aliases[] =3D {
@@ -2208,12 +2245,19 @@
 	EV_ALIAS(NULL, NULL)
 };
=20
-#define	MIPS24K_KW_OS		"os"
-#define	MIPS24K_KW_USR		"usr"
-#define	MIPS24K_KW_ANYTHREAD	"anythread"
+static struct pmc_event_alias octeon_aliases[] =3D {
+	EV_ALIAS("instructions",	"RET"),
+	EV_ALIAS("branches",		"BR"),
+	EV_ALIAS("branch-mispredicts",	"BRMIS"),
+	EV_ALIAS(NULL, NULL)
+};
+
+#define	MIPS_KW_OS		"os"
+#define	MIPS_KW_USR		"usr"
+#define	MIPS_KW_ANYTHREAD	"anythread"
=20
 static int
-mips24k_allocate_pmc(enum pmc_event pe, char *ctrspec __unused,
+mips_allocate_pmc(enum pmc_event pe, char *ctrspec __unused,
 		  struct pmc_op_pmcallocate *pmc_config __unused)
 {
 	char *p;
@@ -2223,11 +2267,11 @@
 	pmc_config->pm_caps |=3D (PMC_CAP_READ | PMC_CAP_WRITE);
 =09
 	while ((p =3D strsep(&ctrspec, ",")) !=3D NULL) {
-		if (KWMATCH(p, MIPS24K_KW_OS))
+		if (KWMATCH(p, MIPS_KW_OS))
 			pmc_config->pm_caps |=3D PMC_CAP_SYSTEM;
-		else if (KWMATCH(p, MIPS24K_KW_USR))
+		else if (KWMATCH(p, MIPS_KW_USR))
 			pmc_config->pm_caps |=3D PMC_CAP_USER;
-		else if (KWMATCH(p, MIPS24K_KW_ANYTHREAD))
+		else if (KWMATCH(p, MIPS_KW_ANYTHREAD))
 			pmc_config->pm_caps |=3D (PMC_CAP_USER | PMC_CAP_SYSTEM);
 		else
 			return (-1);
@@ -2235,6 +2279,7 @@
=20
 	return (0);
 }
+
 #endif /* __mips__ */
=20
 #if defined(__powerpc__)
@@ -2644,10 +2689,18 @@
 		ev =3D mips24k_event_table;
 		count =3D PMC_EVENT_TABLE_SIZE(mips24k);
 		break;
+	case PMC_CLASS_OCTEON:
+		ev =3D octeon_event_table;
+		count =3D PMC_EVENT_TABLE_SIZE(octeon);
+		break;
 	case PMC_CLASS_PPC7450:
 		ev =3D ppc7450_event_table;
 		count =3D PMC_EVENT_TABLE_SIZE(ppc7450);
 		break;
+	case PMC_CLASS_SOFT:
+		ev =3D soft_event_table;
+		count =3D soft_event_info.pm_nevent;
+		break;
 	default:
 		errno =3D EINVAL;
 		return (-1);
@@ -2661,6 +2714,7 @@
=20
 	for (;count--; ev++, names++)
 		*names =3D ev->pm_ev_name;
+
 	return (0);
 }
=20
@@ -2765,11 +2819,34 @@
 		pmc_class_table[n] =3D NULL;
=20
 	/*
+	 * Get soft events list.
+	 */
+	soft_event_info.pm_class =3D PMC_CLASS_SOFT;
+	if (PMC_CALL(GETDYNEVENTINFO, &soft_event_info) < 0)
+		return (pmc_syscall =3D -1);
+
+	/* Map soft events to static list. */
+	for (n =3D 0; n < soft_event_info.pm_nevent; n++) {
+		soft_event_table[n].pm_ev_name =3D
+		    soft_event_info.pm_events[n].pm_ev_name;
+		soft_event_table[n].pm_ev_code =3D
+		    soft_event_info.pm_events[n].pm_ev_code;
+	}
+	soft_class_table_descr.pm_evc_event_table_size =3D \
+	    soft_event_info.pm_nevent;
+	soft_class_table_descr.pm_evc_event_table =3D \
+	    soft_event_table;
+
+	/*
 	 * Fill in the class table.
 	 */
 	n =3D 0;
+
+	/* Fill soft events information. */
+	pmc_class_table[n++] =3D &soft_class_table_descr;
 #if defined(__amd64__) || defined(__i386__)
-	pmc_class_table[n++] =3D &tsc_class_table_descr;
+	if (cpu_info.pm_cputype !=3D PMC_CPU_GENERIC)
+		pmc_class_table[n++] =3D &tsc_class_table_descr;
=20
 	/*
  	 * Check if this CPU has fixed function counters.
@@ -2852,6 +2929,9 @@
 		pmc_class_table[n] =3D &p4_class_table_descr;
 		break;
 #endif
+	case PMC_CPU_GENERIC:
+		PMC_MDEP_INIT(generic);
+		break;
 #if defined(__XSCALE__)
 	case PMC_CPU_INTEL_XSCALE:
 		PMC_MDEP_INIT(xscale);
@@ -2863,6 +2943,10 @@
 		PMC_MDEP_INIT(mips24k);
 		pmc_class_table[n] =3D &mips24k_class_table_descr;
 		break;
+	case PMC_CPU_MIPS_OCTEON:
+		PMC_MDEP_INIT(octeon);
+		pmc_class_table[n] =3D &octeon_class_table_descr;
+		break;
 #endif /* __mips__ */
 #if defined(__powerpc__)
 	case PMC_CPU_PPC_7450:
@@ -3016,15 +3100,19 @@
 		evfence =3D xscale_event_table + PMC_EVENT_TABLE_SIZE(xscale);
 	} else if (pe >=3D PMC_EV_MIPS24K_FIRST && pe <=3D PMC_EV_MIPS24K_LAST) {
 		ev =3D mips24k_event_table;
-		evfence =3D mips24k_event_table + PMC_EVENT_TABLE_SIZE(mips24k
-);
+		evfence =3D mips24k_event_table + PMC_EVENT_TABLE_SIZE(mips24k);
+	} else if (pe >=3D PMC_EV_OCTEON_FIRST && pe <=3D PMC_EV_OCTEON_LAST) {
+		ev =3D octeon_event_table;
+		evfence =3D octeon_event_table + PMC_EVENT_TABLE_SIZE(octeon);
 	} else if (pe >=3D PMC_EV_PPC7450_FIRST && pe <=3D PMC_EV_PPC7450_LAST) {
 		ev =3D ppc7450_event_table;
-		evfence =3D ppc7450_event_table + PMC_EVENT_TABLE_SIZE(ppc7450
-);
+		evfence =3D ppc7450_event_table + PMC_EVENT_TABLE_SIZE(ppc7450);
 	} else if (pe =3D=3D PMC_EV_TSC_TSC) {
 		ev =3D tsc_event_table;
 		evfence =3D tsc_event_table + PMC_EVENT_TABLE_SIZE(tsc);
+	} else if (pe >=3D PMC_EV_SOFT_FIRST && pe <=3D PMC_EV_SOFT_LAST) {
+		ev =3D soft_event_table;
+		evfence =3D soft_event_table + soft_event_info.pm_nevent;
 	}
=20
 	for (; ev !=3D evfence; ev++)
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.3
--- a/head/lib/libpmc/pmc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.3 231871 2012-02-17 11:09:51Z brueffer $
+.\" $FreeBSD: head/lib/libpmc/pmc.3 233628 2012-03-28 20:58:30Z fabient $
 .\"
 .Dd November 24, 2008
 .Dt PMC 3
@@ -223,9 +223,10 @@
 CPUs.
 .It Li PMC_CLASS_TSC
 The timestamp counter on i386 and amd64 architecture CPUs.
+.It Li PMC_CLASS_SOFT
+Software events.
 .El
 .Ss PMC Capabilities
-.Pp
 Capabilities of performance monitoring hardware are denoted using
 the
 .Vt "enum pmc_caps"
@@ -526,6 +527,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.atom.3
--- a/head/lib/libpmc/pmc.atom.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.atom.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.atom.3 231871 2012-02-17 11:09:51Z bruef=
fer $
+.\" $FreeBSD: head/lib/libpmc/pmc.atom.3 233628 2012-03-28 20:58:30Z fabie=
nt $
 .\"
 .Dd November 12, 2008
 .Dt PMC.ATOM 3
@@ -1176,6 +1176,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.core.3
--- a/head/lib/libpmc/pmc.core.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.core.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.core.3 231871 2012-02-17 11:09:51Z bruef=
fer $
+.\" $FreeBSD: head/lib/libpmc/pmc.core.3 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd November 12, 2008
 .Dt PMC.CORE 3
@@ -180,7 +180,7 @@
 The following event names are case insensitive.
 Whitespace, hyphens and underscore characters in these names are
 ignored.
-.Pp=20
+.Pp
 Core PMCs support the following events:
 .Bl -tag -width indent
 .It Li BAClears
@@ -193,7 +193,7 @@
 .It Li Br_BAC_Missp_Exec
 .Pq Event 8AH , Umask 00H
 The number of branch instructions executed that were mispredicted at
-the front end.=20
+the front end.
 .It Li Br_Bogus
 .Pq Event E4H , Umask 00H
 The number of bogus branches.
@@ -792,6 +792,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.core2.3
--- a/head/lib/libpmc/pmc.core2.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.core2.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.core2.3 231871 2012-02-17 11:09:51Z brue=
ffer $
+.\" $FreeBSD: head/lib/libpmc/pmc.core2.3 233628 2012-03-28 20:58:30Z fabi=
ent $
 .\"
 .Dd June 8, 2009
 .Dt PMC.CORE2 3
@@ -1107,6 +1107,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.corei7.3
--- a/head/lib/libpmc/pmc.corei7.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.corei7.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.corei7.3 231871 2012-02-17 11:09:51Z bru=
effer $
+.\" $FreeBSD: head/lib/libpmc/pmc.corei7.3 233628 2012-03-28 20:58:30Z fab=
ient $
 .\"
 .Dd March 24, 2010
 .Dt PMC.COREI7 3
@@ -1559,6 +1559,7 @@
 .Xr pmc.corei7uc 3 ,
 .Xr pmc.westmere 3 ,
 .Xr pmc.westmereuc 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.corei7uc.3
--- a/head/lib/libpmc/pmc.corei7uc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.corei7uc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.corei7uc.3 231871 2012-02-17 11:09:51Z b=
rueffer $
+.\" $FreeBSD: head/lib/libpmc/pmc.corei7uc.3 233628 2012-03-28 20:58:30Z f=
abient $
 .\"
 .Dd March 24, 2010
 .Dt PMC.COREI7UC 3
@@ -863,6 +863,7 @@
 .Xr pmc.corei7 3 ,
 .Xr pmc.westmere 3 ,
 .Xr pmc.westmereuc 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.h
--- a/head/lib/libpmc/pmc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/lib/libpmc/pmc.h 226514 2011-10-18 15:25:43Z fabient $
+ * $FreeBSD: head/lib/libpmc/pmc.h 233321 2012-03-22 19:04:22Z jkoshy $
  */
=20
 #ifndef _PMC_H_
@@ -98,7 +98,7 @@
 int	pmc_cpuinfo(const struct pmc_cpuinfo **_cpu_info);
 int	pmc_pmcinfo(int _cpu, struct pmc_pmcinfo **_pmc_info);
=20
-const char	*pmc_name_of_capability(uint32_t _c);
+const char	*pmc_name_of_capability(enum pmc_caps _c);
 const char	*pmc_name_of_class(enum pmc_class _pc);
 const char	*pmc_name_of_cputype(enum pmc_cputype _cp);
 const char	*pmc_name_of_disposition(enum pmc_disp _pd);
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.iaf.3
--- a/head/lib/libpmc/pmc.iaf.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.iaf.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.iaf.3 231871 2012-02-17 11:09:51Z brueff=
er $
+.\" $FreeBSD: head/lib/libpmc/pmc.iaf.3 233628 2012-03-28 20:58:30Z fabien=
t $
 .\"
 .Dd November 14, 2008
 .Dt PMC.IAF 3
@@ -132,6 +132,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.k7.3
--- a/head/lib/libpmc/pmc.k7.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.k7.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.k7.3 231871 2012-02-17 11:09:51Z brueffe=
r $
+.\" $FreeBSD: head/lib/libpmc/pmc.k7.3 233628 2012-03-28 20:58:30Z fabient=
 $
 .\"
 .Dd October 4, 2008
 .Dt PMC.K7 3
@@ -64,7 +64,6 @@
 .It PMC_CAP_WRITE Ta Yes
 .El
 .Ss Event Qualifiers
-.Pp
 Event specifiers for AMD K7 PMCs can have the following optional
 qualifiers:
 .Bl -tag -width indent
@@ -250,6 +249,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.k8.3
--- a/head/lib/libpmc/pmc.k8.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.k8.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.k8.3 231871 2012-02-17 11:09:51Z brueffe=
r $
+.\" $FreeBSD: head/lib/libpmc/pmc.k8.3 233628 2012-03-28 20:58:30Z fabient=
 $
 .\"
 .Dd October 4, 2008
 .Dt PMC.K8 3
@@ -67,7 +67,6 @@
 .It PMC_CAP_WRITE Ta Yes
 .El
 .Ss Event Qualifiers
-.Pp
 Event specifiers for AMD K8 PMCs can have the following optional
 qualifiers:
 .Bl -tag -width indent
@@ -784,6 +783,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.p4.3
--- a/head/lib/libpmc/pmc.p4.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.p4.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.p4.3 231871 2012-02-17 11:09:51Z brueffe=
r $
+.\" $FreeBSD: head/lib/libpmc/pmc.p4.3 233628 2012-03-28 20:58:30Z fabient=
 $
 .\"
 .Dd October 4, 2008
 .Dt PMC.P4 3
@@ -90,7 +90,6 @@
 .It PMC_CAP_WRITE Ta Yes
 .El
 .Ss Event Qualifiers
-.Pp
 Event specifiers for Intel P4 PMCs can have the following common
 qualifiers:
 .Bl -tag -width indent
@@ -1209,6 +1208,7 @@
 .Xr pmc.k8 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.p5.3
--- a/head/lib/libpmc/pmc.p5.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.p5.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.p5.3 231871 2012-02-17 11:09:51Z brueffe=
r $
+.\" $FreeBSD: head/lib/libpmc/pmc.p5.3 233628 2012-03-28 20:58:30Z fabient=
 $
 .\"
 .Dd October 4, 2008
 .Dt PMC 3
@@ -444,6 +444,7 @@
 .Xr pmc.k8 3 ,
 .Xr pmc.p4 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.p6.3
--- a/head/lib/libpmc/pmc.p6.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.p6.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.p6.3 231871 2012-02-17 11:09:51Z brueffe=
r $
+.\" $FreeBSD: head/lib/libpmc/pmc.p6.3 233628 2012-03-28 20:58:30Z fabient=
 $
 .\"
 .Dd October 4, 2008
 .Dt PMC.P6 3
@@ -1010,6 +1010,7 @@
 .Xr pmc.k8 3 ,
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.sandybridge.3
--- a/head/lib/libpmc/pmc.sandybridge.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.sandybridge.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.sandybridge.3 232377 2012-03-02 05:55:45=
Z pluknet $
+.\" $FreeBSD: head/lib/libpmc/pmc.sandybridge.3 233628 2012-03-28 20:58:30=
Z fabient $
 .\"
 .Dd February 12, 2012
 .Dt PMC.SANDYBRIDGE 3
@@ -907,6 +907,7 @@
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
 .Xr pmc.sandybridgeuc 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc.ucf 3 ,
 .Xr pmc.westmere 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.sandybridgeuc.3
--- a/head/lib/libpmc/pmc.sandybridgeuc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.sandybridgeuc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.sandybridgeuc.3 232377 2012-03-02 05:55:=
45Z pluknet $
+.\" $FreeBSD: head/lib/libpmc/pmc.sandybridgeuc.3 233628 2012-03-28 20:58:=
30Z fabient $
 .\"
 .Dd February 12, 2012
 .Dt PMC.SANDYBRIDGEUC 3
@@ -208,6 +208,7 @@
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
 .Xr pmc.sandybridge 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc.ucf 3 ,
 .Xr pmc.westmere 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.tsc.3
--- a/head/lib/libpmc/pmc.tsc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.tsc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.tsc.3 231871 2012-02-17 11:09:51Z brueff=
er $
+.\" $FreeBSD: head/lib/libpmc/pmc.tsc.3 233628 2012-03-28 20:58:30Z fabien=
t $
 .\"
 .Dd October 4, 2008
 .Dt PMC.TSC 3
@@ -68,6 +68,7 @@
 .Xr pmc.p4 3 ,
 .Xr pmc.p5 3 ,
 .Xr pmc.p6 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmclog 3 ,
 .Xr hwpmc 4
 .Sh HISTORY
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.ucf.3
--- a/head/lib/libpmc/pmc.ucf.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.ucf.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.ucf.3 231871 2012-02-17 11:09:51Z brueff=
er $
+.\" $FreeBSD: head/lib/libpmc/pmc.ucf.3 233628 2012-03-28 20:58:30Z fabien=
t $
 .\"
 .Dd March 30, 2010
 .Dt PMC.UCF 3
@@ -96,6 +96,7 @@
 .Xr pmc.corei7uc 3 ,
 .Xr pmc.westmere 3 ,
 .Xr pmc.westmereuc 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.westmere.3
--- a/head/lib/libpmc/pmc.westmere.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.westmere.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.westmere.3 232159 2012-02-25 16:02:12Z g=
jb $
+.\" $FreeBSD: head/lib/libpmc/pmc.westmere.3 233628 2012-03-28 20:58:30Z f=
abient $
 .\"
 .Dd February 25, 2012
 .Dt PMC.WESTMERE 3
@@ -1381,6 +1381,7 @@
 .Xr pmc.corei7 3 ,
 .Xr pmc.corei7uc 3 ,
 .Xr pmc.westmereuc 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.westmereuc.3
--- a/head/lib/libpmc/pmc.westmereuc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.westmereuc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.westmereuc.3 231871 2012-02-17 11:09:51Z=
 brueffer $
+.\" $FreeBSD: head/lib/libpmc/pmc.westmereuc.3 233628 2012-03-28 20:58:30Z=
 fabient $
 .\"
 .Dd March 24, 2010
 .Dt PMC.WESTMEREUC 3
@@ -1066,6 +1066,7 @@
 .Xr pmc.corei7 3 ,
 .Xr pmc.corei7uc 3 ,
 .Xr pmc.westmere 3 ,
+.Xr pmc.soft 3 ,
 .Xr pmc.tsc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc.xscale.3
--- a/head/lib/libpmc/pmc.xscale.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc.xscale.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc.xscale.3 231871 2012-02-17 11:09:51Z bru=
effer $
+.\" $FreeBSD: head/lib/libpmc/pmc.xscale.3 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd December 23, 2009
 .Dt PMC.XSCALE 3
@@ -45,7 +45,7 @@
 Third generation cores also have an increased number of PMC events.
 .Pp
 .Tn Intel XScale
-PMCs are documented in=20
+PMCs are documented in
 .Rs
 .%B "3rd Generation Intel XScale Microarchitecture Developer's Manual"
 .%D May 2007
@@ -117,23 +117,24 @@
 .It Li DATA_BUS_TRANS
 Data bus transaction.
 .El
-.Ss Event Name Aliases =20
+.Ss Event Name Aliases
 The following table shows the mapping between the PMC-independent
 aliases supported by
 .Lb libpmc
 and the underlying hardware events used.
 .Bl -column "branch-mispredicts" "BRANCH_MISPRED"
-.It Em Alias Ta Em Event Ta
-.It Li branches Ta Li BRANCH_RETIRED Ta
-.It Li branch-mispredicts Ta Li BRANCH_MISPRED Ta
-.It Li dc-misses Ta Li DC_MISS Ta
-.It Li ic-misses Ta Li IC_MISS Ta
-.It Li instructions Ta Li INSTR_RETIRED Ta
+.It Em Alias Ta Em Event
+.It Li branches Ta Li BRANCH_RETIRED
+.It Li branch-mispredicts Ta Li BRANCH_MISPRED
+.It Li dc-misses Ta Li DC_MISS
+.It Li ic-misses Ta Li IC_MISS
+.It Li instructions Ta Li INSTR_RETIRED
 .El
 .Sh SEE ALSO
 .Xr pmc 3 ,
 .Xr pmc_cpuinfo 3 ,
 .Xr pmclog 3 ,
+.Xr pmc.soft 3 ,
 .Xr hwpmc 4
 .Sh HISTORY
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmc_capabilities.3
--- a/head/lib/libpmc/pmc_capabilities.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmc_capabilities.3	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libpmc/pmc_capabilities.3 231871 2012-02-17 11:09:5=
1Z brueffer $
+.\" $FreeBSD: head/lib/libpmc/pmc_capabilities.3 233648 2012-03-29 05:02:1=
2Z eadler $
 .\"
 .Dd September 22, 2008
 .Dt PMC_CAPABILITIES 3
@@ -51,7 +51,7 @@
 .Ft int
 .Fn pmc_width "pmc_id_t pmc" "uint32_t *width"
 .Sh DESCRIPTION
-These functions retrieve information about performance monitoring=20
+These functions retrieve information about performance monitoring
 hardware.
 .Pp
 Function
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmclog.c
--- a/head/lib/libpmc/pmclog.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmclog.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libpmc/pmclog.c 233628 2012-03-28 20:58:30Z f=
abient $");
=20
 #include <sys/param.h>
 #include <sys/pmc.h>
@@ -369,6 +369,12 @@
 		    =3D=3D NULL)
 			goto error;
 		break;
+	case PMCLOG_TYPE_PMCALLOCATEDYN:
+		PMCLOG_READ32(le,ev->pl_u.pl_ad.pl_pmcid);
+		PMCLOG_READ32(le,ev->pl_u.pl_ad.pl_event);
+		PMCLOG_READ32(le,ev->pl_u.pl_ad.pl_flags);
+		PMCLOG_READSTRING(le,ev->pl_u.pl_ad.pl_evname,PMC_NAME_MAX);
+		break;
 	case PMCLOG_TYPE_PMCATTACH:
 		PMCLOG_GET_PATHLEN(pathlen,evlen,pmclog_pmcattach);
 		PMCLOG_READ32(le,ev->pl_u.pl_t.pl_pmcid);
diff -r 428842767fa6 -r f2935497fa04 head/lib/libpmc/pmclog.h
--- a/head/lib/libpmc/pmclog.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libpmc/pmclog.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/lib/libpmc/pmclog.h 233628 2012-03-28 20:58:30Z fabient $
  */
=20
 #ifndef	_PMCLOG_H_
@@ -88,6 +88,13 @@
 	pmc_id_t	pl_pmcid;
 };
=20
+struct pmclog_ev_pmcallocatedyn {
+	uint32_t	pl_event;
+	char 		pl_evname[PMC_NAME_MAX];
+	uint32_t	pl_flags;
+	pmc_id_t	pl_pmcid;
+};
+
 struct pmclog_ev_pmcattach {
 	pmc_id_t	pl_pmcid;
 	pid_t		pl_pid;
@@ -146,6 +153,7 @@
 		struct pmclog_ev_map_out	pl_mo;
 		struct pmclog_ev_pcsample	pl_s;
 		struct pmclog_ev_pmcallocate	pl_a;
+		struct pmclog_ev_pmcallocatedyn	pl_ad;
 		struct pmclog_ev_pmcattach	pl_t;
 		struct pmclog_ev_pmcdetach	pl_d;
 		struct pmclog_ev_proccsw	pl_c;
diff -r 428842767fa6 -r f2935497fa04 head/lib/libproc/proc_bkpt.c
--- a/head/lib/libproc/proc_bkpt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libproc/proc_bkpt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */=20
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libproc/proc_bkpt.c 233402 2012-03-23 23:07:0=
2Z gonzo $");
=20
 #include <sys/types.h>
 #include <sys/ptrace.h>
@@ -44,6 +44,9 @@
 #if defined(__i386__) || defined(__amd64__)
 #define BREAKPOINT_INSTR	0xcc	/* int 0x3 */
 #define	BREAKPOINT_INSTR_SZ	1
+#elif defined(__mips__)
+#define BREAKPOINT_INSTR	0xd	/* break */
+#define	BREAKPOINT_INSTR_SZ	4
 #else
 #error "Add support for your architecture"
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/lib/libproc/proc_regs.c
--- a/head/lib/libproc/proc_regs.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libproc/proc_regs.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */=20
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libproc/proc_regs.c 233402 2012-03-23 23:07:0=
2Z gonzo $");
=20
 #include <sys/types.h>
 #include <sys/ptrace.h>
@@ -58,6 +58,8 @@
 		*regvalue =3D regs.r_rip;
 #elif defined(__i386__)
 		*regvalue =3D regs.r_eip;
+#elif defined(__mips__)
+		*regvalue =3D regs.r_regs[PC];
 #endif
 		break;
 	case REG_SP:
@@ -65,6 +67,8 @@
 		*regvalue =3D regs.r_rsp;
 #elif defined(__i386__)
 		*regvalue =3D regs.r_esp;
+#elif defined(__mips__)
+		*regvalue =3D regs.r_regs[SP];
 #endif
 		break;
 	default:
@@ -93,6 +97,8 @@
 		regs.r_rip =3D regvalue;
 #elif defined(__i386__)
 		regs.r_eip =3D regvalue;
+#elif defined(__mips__)
+		regs.r_regs[PC] =3D regvalue;
 #endif
 		break;
 	case REG_SP:
@@ -100,6 +106,8 @@
 		regs.r_rsp =3D regvalue;
 #elif defined(__i386__)
 		regs.r_esp =3D regvalue;
+#elif defined(__mips__)
+		regs.r_regs[PC] =3D regvalue;
 #endif
 		break;
 	default:
diff -r 428842767fa6 -r f2935497fa04 head/lib/libprocstat/Symbol.map
--- a/head/lib/libprocstat/Symbol.map	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libprocstat/Symbol.map	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD: head/lib/libprocstat/Symbol.map 221931 2011-05-14 22:15:38Z s=
tas $
+ * $FreeBSD: head/lib/libprocstat/Symbol.map 233760 2012-04-01 18:22:48Z j=
hb $
  */
 FBSD_1.2 {
 	procstat_close;
@@ -14,3 +14,7 @@
 	procstat_open_kvm;
 	procstat_open_sysctl;
 };
+
+FBSD_1.3 {
+	procstat_get_shm_info;
+};
diff -r 428842767fa6 -r f2935497fa04 head/lib/libprocstat/Versions.def
--- a/head/lib/libprocstat/Versions.def	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libprocstat/Versions.def	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,10 @@
-# $FreeBSD: head/lib/libprocstat/Versions.def 221931 2011-05-14 22:15:38Z =
stas $
+# $FreeBSD: head/lib/libprocstat/Versions.def 233760 2012-04-01 18:22:48Z =
jhb $
=20
 # This version was first added to 9.0-current.
 FBSD_1.2 {
 };
+
+# This version was first added to 10.0-current.
+FBSD_1.3 {
+} FBSD_1.2;
+
diff -r 428842767fa6 -r f2935497fa04 head/lib/libprocstat/libprocstat.3
--- a/head/lib/libprocstat/libprocstat.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libprocstat/libprocstat.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,9 +22,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libprocstat/libprocstat.3 223964 2011-07-12 19:48:2=
1Z pluknet $
+.\" $FreeBSD: head/lib/libprocstat/libprocstat.3 233760 2012-04-01 18:22:4=
8Z jhb $
 .\"
-.Dd July 12, 2011
+.Dd April 1, 2012
 .Dt LIBPROCSTAT 3
 .Os
 .Sh NAME
@@ -37,6 +37,7 @@
 .Nm procstat_freeprocs ,
 .Nm procstat_get_pipe_info ,
 .Nm procstat_get_pts_info ,
+.Nm procstat_get_shm_info ,
 .Nm procstat_get_socket_info ,
 .Nm procstat_get_vnode_info
 .Nd library interface for file and process information retrieval
@@ -70,6 +71,13 @@
 .Fa "char *errbuf"
 .Fc
 .Ft int
+.Fo procstat_get_shm_info
+.Fa "struct procstat *procstat"
+.Fa "struct filestat *fst"
+.Fa "struct shmstat *shm"
+.Fa "char *errbuf"
+.Fc
+.Ft int
 .Fo procstat_get_socket_info
 .Fa "struct procstat *procstat"
 .Fa "struct filestat *fst"
@@ -191,10 +199,12 @@
 The
 .Fn procstat_get_pipe_info ,
 .Fn procstat_get_pts_info ,
+.Fn procstat_get_shm_info ,
 .Fn procstat_get_socket_info
 and
 .Fn procstat_get_vnode_info
 functions are used to retrive information about pipes, pseudo-terminals,
+shared memory objects,
 sockets, and vnodes, respectively.
 Each of them have a similar interface API.
 The
@@ -231,11 +241,14 @@
 .Nm procstat_get_pipe_info
 .It Li PS_FST_TYPE_PTS
 .Nm procstat_get_pts_info
+.It Li PS_FST_TYPE_SHM
+.Nm procstat_get_shm_info
 .El
 .Sh SEE ALSO
 .Xr fstat 1 ,
 .Xr fuser 1 ,
 .Xr pipe 2 ,
+.Xr shm_open 2 ,
 .Xr socket 2 ,
 .Xr kvm 3 ,
 .Xr queue 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/lib/libprocstat/libprocstat.c
--- a/head/lib/libprocstat/libprocstat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libprocstat/libprocstat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libprocstat/libprocstat.c 224859 2011-08-14 0=
0:42:09Z rwatson $");
+__FBSDID("$FreeBSD: head/lib/libprocstat/libprocstat.c 233760 2012-04-01 1=
8:22:48Z jhb $");
=20
 #include <sys/param.h>
 #include <sys/time.h>
@@ -54,6 +54,7 @@
 #define	_WANT_FILE
 #include <sys/file.h>
 #include <sys/conf.h>
+#include <sys/mman.h>
 #define	_KERNEL
 #include <sys/mount.h>
 #include <sys/pipe.h>
@@ -114,6 +115,10 @@
     struct ptsstat *pts, char *errbuf);
 static int	procstat_get_pts_info_kvm(kvm_t *kd, struct filestat *fst,
     struct ptsstat *pts, char *errbuf);
+static int	procstat_get_shm_info_sysctl(struct filestat *fst,
+    struct shmstat *shm, char *errbuf);
+static int	procstat_get_shm_info_kvm(kvm_t *kd, struct filestat *fst,
+    struct shmstat *shm, char *errbuf);
 static int	procstat_get_socket_info_sysctl(struct filestat *fst,
     struct sockstat *sock, char *errbuf);
 static int	procstat_get_socket_info_kvm(kvm_t *kd, struct filestat *fst,
@@ -469,6 +474,10 @@
 			data =3D file.f_data;
 			break;
 #endif
+		case DTYPE_SHM:
+			type =3D PS_FST_TYPE_SHM;
+			data =3D file.f_data;
+			break;
 		default:
 			continue;
 		}
@@ -849,6 +858,69 @@
 }
=20
 int
+procstat_get_shm_info(struct procstat *procstat, struct filestat *fst,
+    struct shmstat *shm, char *errbuf)
+{
+
+	assert(shm);
+	if (procstat->type =3D=3D PROCSTAT_KVM) {
+		return (procstat_get_shm_info_kvm(procstat->kd, fst, shm,
+		    errbuf));
+	} else if (procstat->type =3D=3D PROCSTAT_SYSCTL) {
+		return (procstat_get_shm_info_sysctl(fst, shm, errbuf));
+	} else {
+		warnx("unknown access method: %d", procstat->type);
+		snprintf(errbuf, _POSIX2_LINE_MAX, "error");
+		return (1);
+	}
+}
+
+static int
+procstat_get_shm_info_kvm(kvm_t *kd, struct filestat *fst,
+    struct shmstat *shm, char *errbuf)
+{
+	struct shmfd shmfd;
+	void *shmfdp;
+
+	assert(kd);
+	assert(shm);
+	assert(fst);
+	bzero(shm, sizeof(*shm));
+	shmfdp =3D fst->fs_typedep;
+	if (shmfdp =3D=3D NULL)
+		goto fail;
+	if (!kvm_read_all(kd, (unsigned long)shmfdp, &shmfd,
+	    sizeof(struct shmfd))) {
+		warnx("can't read shmfd at %p", (void *)shmfdp);
+		goto fail;
+	}
+	shm->mode =3D S_IFREG | shmfd.shm_mode;
+	shm->size =3D shmfd.shm_size;
+	return (0);
+
+fail:
+	snprintf(errbuf, _POSIX2_LINE_MAX, "error");
+	return (1);
+}
+
+static int
+procstat_get_shm_info_sysctl(struct filestat *fst, struct shmstat *shm,
+    char *errbuf __unused)
+{
+	struct kinfo_file *kif;
+
+	assert(shm);
+	assert(fst);
+	bzero(shm, sizeof(*shm));
+	kif =3D fst->fs_typedep;
+	if (kif =3D=3D NULL)
+		return (0);
+	shm->size =3D kif->kf_un.kf_file.kf_file_size;
+	shm->mode =3D kif->kf_un.kf_file.kf_file_mode;
+	return (0);
+}
+
+int
 procstat_get_vnode_info(struct procstat *procstat, struct filestat *fst,
     struct vnstat *vn, char *errbuf)
 {
diff -r 428842767fa6 -r f2935497fa04 head/lib/libprocstat/libprocstat.h
--- a/head/lib/libprocstat/libprocstat.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libprocstat/libprocstat.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/lib/libprocstat/libprocstat.h 224859 2011-08-14 00:42:09=
Z rwatson $
+ * $FreeBSD: head/lib/libprocstat/libprocstat.h 233760 2012-04-01 18:22:48=
Z jhb $
  */
=20
 #ifndef _LIBPROCSTAT_H_
@@ -123,6 +123,10 @@
 	uint64_t	addr;
 	uint64_t	peer;
 };
+struct shmstat {
+	uint64_t	size;
+	uint16_t	mode;
+};
 struct sockstat {
 	uint64_t	inp_ppcb;
 	uint64_t	so_addr;
@@ -152,6 +156,8 @@
     struct pipestat *pipe, char *errbuf);
 int	procstat_get_pts_info(struct procstat *procstat, struct filestat *fst,
     struct ptsstat *pts, char *errbuf);
+int	procstat_get_shm_info(struct procstat *procstat, struct filestat *fst,
+    struct shmstat *shm, char *errbuf);
 int	procstat_get_socket_info(struct procstat *procstat, struct filestat *f=
st,
     struct sockstat *sock, char *errbuf);
 int	procstat_get_vnode_info(struct procstat *procstat, struct filestat *fs=
t,
diff -r 428842767fa6 -r f2935497fa04 head/lib/librpcsec_gss/rpc_gss_seccrea=
te.3
--- a/head/lib/librpcsec_gss/rpc_gss_seccreate.3	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/lib/librpcsec_gss/rpc_gss_seccreate.3	Tue Apr 17 11:51:51 2012 +=
0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/librpcsec_gss/rpc_gss_seccreate.3 233648 2012-03-29=
 05:02:12Z eadler $
 .Dd January 26, 2010
 .Dt RPC_GSS_SECCREATE 3
 .Os
@@ -70,7 +70,7 @@
 RPC headers only are integrity protected by a checksum.
 .It rpc_gss_svc_integrity
 RPC headers and data are integrity protected by a checksum.
-.It rpc_gss_svc_privacy=20
+.It rpc_gss_svc_privacy
 RPC headers are integrity protected by a checksum and data is encrypted.
 .El
 .It qop
diff -r 428842767fa6 -r f2935497fa04 head/lib/librt/sigev_thread.c
--- a/head/lib/librt/sigev_thread.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/librt/sigev_thread.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/lib/librt/sigev_thread.c 233519 2012-03-26 19:12:09Z rmh=
 $
  *
  */
=20
@@ -224,11 +224,11 @@
 	sigev_id_t id)
 {
 	/*
-	 * Build a new sigevent, and tell kernel to deliver SIGSERVICE
+	 * Build a new sigevent, and tell kernel to deliver SIGLIBRT
 	 * signal to the new thread.
 	 */
 	newevp->sigev_notify =3D SIGEV_THREAD_ID;
-	newevp->sigev_signo  =3D SIGSERVICE;
+	newevp->sigev_signo  =3D SIGLIBRT;
 	newevp->sigev_notify_thread_id =3D (lwpid_t)sn->sn_tn->tn_lwpid;
 	newevp->sigev_value.sival_ptr =3D (void *)id;
 }
@@ -279,7 +279,7 @@
 	LIST_REMOVE(sn, sn_link);
=20
 	if (--sn->sn_tn->tn_refcount =3D=3D 0)
-		_pthread_kill(sn->sn_tn->tn_thread, SIGSERVICE);
+		_pthread_kill(sn->sn_tn->tn_thread, SIGLIBRT);
 	if (sn->sn_flags & SNF_WORKING)
 		sn->sn_flags |=3D SNF_REMOVED;
 	else
@@ -326,7 +326,7 @@
 	LIST_INSERT_HEAD(&sigev_threads, tn, tn_link);
 	__sigev_list_unlock();
=20
-	sigfillset(&set);	/* SIGSERVICE is masked. */
+	sigfillset(&set);	/* SIGLIBRT is masked. */
 	sigdelset(&set, SIGBUS);
 	sigdelset(&set, SIGILL);
 	sigdelset(&set, SIGFPE);
@@ -378,7 +378,7 @@
 	__sigev_list_unlock();
=20
 	sigemptyset(&set);
-	sigaddset(&set, SIGSERVICE);
+	sigaddset(&set, SIGLIBRT);
 	for (;;) {
 		ret =3D sigwaitinfo(&set, &si);
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/librt/sigev_thread.h
--- a/head/lib/librt/sigev_thread.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/librt/sigev_thread.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/lib/librt/sigev_thread.h 233519 2012-03-26 19:12:09Z rmh=
 $
  *
  */
=20
@@ -67,8 +67,6 @@
 #define	SNF_REMOVED		0x02
 #define	SNF_SYNC		0x04
=20
-#define	SIGSERVICE		(SIGTHR+1)
-
 int	__sigev_check_init();
 struct sigev_node *__sigev_alloc(int, const struct sigevent *,
 	struct sigev_node *, int);
diff -r 428842767fa6 -r f2935497fa04 head/lib/libtacplus/libtacplus.3
--- a/head/lib/libtacplus/libtacplus.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libtacplus/libtacplus.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libtacplus/libtacplus.3 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd December 11, 2009
 .Dt LIBTACPLUS 3
@@ -380,7 +380,7 @@
 On failure,
 .Fn tac_send_acct
 returns \-1.
-Otherwise, it returns the TACACS+ status code=20
+Otherwise, it returns the TACACS+ status code
 Possible status codes, defined in
 .In taclib.h ,
 include:
@@ -393,7 +393,6 @@
 .It
 .Dv TAC_ACCT_STATUS_FOLLOW
 .El
-.Pp
 .Sh EXTRACTING INFORMATION FROM THE SERVER'S AUTHORIZATION RESPONSE
 Like an authentication response packet, an authorization
 response packet from the
diff -r 428842767fa6 -r f2935497fa04 head/lib/libthr/thread/thr_private.h
--- a/head/lib/libthr/thread/thr_private.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libthr/thread/thr_private.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/lib/libthr/thread/thr_private.h 233022 2012-03-16 04:35:=
52Z davidxu $
+ * $FreeBSD: head/lib/libthr/thread/thr_private.h 233912 2012-04-05 02:24:=
08Z davidxu $
  */
=20
 #ifndef _THR_PRIVATE_H
@@ -834,8 +834,6 @@
 void	__sys_exit(int);
 #endif
=20
-int	_umtx_op_err(void *, int op, u_long, void *, void *) __hidden;
-
 static inline int
 _thr_isthreaded(void)
 {
diff -r 428842767fa6 -r f2935497fa04 head/lib/libthr/thread/thr_sig.c
--- a/head/lib/libthr/thread/thr_sig.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libthr/thread/thr_sig.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/lib/libthr/thread/thr_sig.c 230430 2012-01-21 18:06:18Z =
kib $
+ * $FreeBSD: head/lib/libthr/thread/thr_sig.c 233516 2012-03-26 17:05:26Z =
jilles $
  */
=20
 #include "namespace.h"
@@ -458,7 +458,7 @@
 {
 	int i;
=20
-	for (i =3D 1; i < _SIG_MAXSIG; ++i)
+	for (i =3D 1; i <=3D _SIG_MAXSIG; ++i)
 		_thr_rwl_rdlock(&_thr_sigact[i-1].lock);
 }
=20
@@ -467,7 +467,7 @@
 {
 	int i;
=20
-	for (i =3D 1; i < _SIG_MAXSIG; ++i)
+	for (i =3D 1; i <=3D _SIG_MAXSIG; ++i)
 		_thr_rwl_unlock(&_thr_sigact[i-1].lock);
 }
=20
@@ -476,7 +476,7 @@
 {
 	int i;
=20
-	for (i =3D 1; i < _SIG_MAXSIG; ++i)
+	for (i =3D 1; i <=3D _SIG_MAXSIG; ++i)
 		bzero(&_thr_sigact[i-1].lock, sizeof(struct urwlock));
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/lib/libthr/thread/thr_umtx.h
--- a/head/lib/libthr/thread/thr_umtx.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libthr/thread/thr_umtx.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/lib/libthr/thread/thr_umtx.h 232209 2012-02-27 13:38:52Z=
 davidxu $
+ * $FreeBSD: head/lib/libthr/thread/thr_umtx.h 233912 2012-04-05 02:24:08Z=
 davidxu $
  */
=20
 #ifndef _THR_FBSD_UMTX_H_
@@ -35,6 +35,7 @@
 #define DEFAULT_UMUTEX	{0,0,{0,0},{0,0,0,0}}
 #define DEFAULT_URWLOCK {0,0,0,0,{0,0,0,0}}
=20
+int _umtx_op_err(void *, int op, u_long, void *, void *) __hidden;
 int __thr_umutex_lock(struct umutex *mtx, uint32_t id) __hidden;
 int __thr_umutex_lock_spin(struct umutex *mtx, uint32_t id) __hidden;
 int __thr_umutex_timedlock(struct umutex *mtx, uint32_t id,
@@ -121,9 +122,23 @@
 static inline int
 _thr_umutex_unlock(struct umutex *mtx, uint32_t id)
 {
-    if (atomic_cmpset_rel_32(&mtx->m_owner, id, UMUTEX_UNOWNED))
-	return (0);
-    return (__thr_umutex_unlock(mtx, id));
+	uint32_t flags =3D mtx->m_flags;
+
+	if ((flags & (UMUTEX_PRIO_PROTECT | UMUTEX_PRIO_INHERIT)) =3D=3D 0) {
+		uint32_t owner;
+		do {
+			owner =3D mtx->m_owner;
+			if (__predict_false((owner & ~UMUTEX_CONTESTED) !=3D id))
+				return (EPERM);
+		} while (__predict_false(!atomic_cmpset_rel_32(&mtx->m_owner,
+					 owner, UMUTEX_UNOWNED)));
+		if ((owner & UMUTEX_CONTESTED))
+			(void)_umtx_op_err(mtx, UMTX_OP_MUTEX_WAKE2, flags, 0, 0);
+		return (0);
+	}
+    	if (atomic_cmpset_rel_32(&mtx->m_owner, id, UMUTEX_UNOWNED))
+		return (0);
+	return (__thr_umutex_unlock(mtx, id));
 }
=20
 static inline int
diff -r 428842767fa6 -r f2935497fa04 head/lib/libulog/utempter_add_record.3
--- a/head/lib/libulog/utempter_add_record.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libulog/utempter_add_record.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libulog/utempter_add_record.3 233648 2012-03-29 05:=
02:12Z eadler $
 .\"
 .Dd December 6, 2009
 .Dt UTEMPTER_ADD_RECORD 3
@@ -85,7 +85,7 @@
 .Pp
 The
 .Fa pty
-arguments of=20
+arguments of
 .Fn addToUtmp
 and
 .Fn removeLineFromUtmp
diff -r 428842767fa6 -r f2935497fa04 head/lib/libusb/Makefile
--- a/head/lib/libusb/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libusb/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/lib/libusb/Makefile 227404 2011-11-09 19:03:26Z hselasky $
+# $FreeBSD: head/lib/libusb/Makefile 234193 2012-04-12 18:06:30Z hselasky $
 #
 # Makefile for the FreeBSD specific LibUSB 2.0
 #
@@ -48,6 +48,7 @@
 MLINKS +=3D libusb.3 libusb_get_device_address.3
 MLINKS +=3D libusb.3 libusb_get_device_speed.3
 MLINKS +=3D libusb.3 libusb_get_max_packet_size.3
+MLINKS +=3D libusb.3 libusb_get_max_iso_packet_size.3
 MLINKS +=3D libusb.3 libusb_ref_device.3
 MLINKS +=3D libusb.3 libusb_unref_device.3
 MLINKS +=3D libusb.3 libusb_open.3
diff -r 428842767fa6 -r f2935497fa04 head/lib/libusb/libusb.3
--- a/head/lib/libusb/libusb.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libusb/libusb.3	Tue Apr 17 11:51:51 2012 +0300
@@ -24,9 +24,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libusb/libusb.3 232157 2012-02-25 14:31:25Z gjb $
+.\" $FreeBSD: head/lib/libusb/libusb.3 234193 2012-04-12 18:06:30Z hselask=
y $
 .\"
-.Dd February 25, 2012
+.Dd April 12, 2012
 .Dt LIBUSB 3
 .Os
 .Sh NAME
@@ -43,7 +43,6 @@
 library contains interfaces for directly managing a usb device.
 The current implementation supports v1.0 of the libusb API.
 .Sh LIBRARY INITIALISATION / DEINITIALISATION
-.Pp
 .Ft int
 .Fn libusb_init libusb_context **ctx
 This function initialises libusb.
@@ -119,6 +118,12 @@
 Returns the wMaxPacketSize value on success, LIBUSB_ERROR_NOT_FOUND if the
 endpoint does not exist and LIBUSB_ERROR_OTHERS on other failure.
 .Pp
+.Ft int
+.Fn libusb_get_max_iso_packet_size "libusb_device *dev" "unsigned char end=
point"
+Returns the packet size multiplied by the packet multiplier on success,
+LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist and
+LIBUSB_ERROR_OTHERS on other failure.
+.Pp
 .Ft libusb_device *
 .Fn libusb_ref_device "libusb_device *dev"
 Increment the reference counter of the device
@@ -270,9 +275,7 @@
 if the device has been disconnected, LIBUSB_ERROR_BUSY if the driver canno=
t be
 attached because the interface is claimed by a program or driver and a
 LIBUSB_ERROR code on failure.
-.Pp
 .Sh USB DESCRIPTORS
-.Pp
 .Ft int
 .Fn libusb_get_device_descriptor "libusb_device *dev" "libusb_device_descr=
iptor *desc"
 Get the USB device descriptor for the device
@@ -349,9 +352,7 @@
 .Ft void
 .Fn libusb_free_bos_descriptor "libusb_bos_descriptor *bos"
 This function is NULL safe and frees a parsed BOS descriptor.
-.Pp
 .Sh USB ASYNCHRONOUS I/O
-.Pp
 .Ft struct libusb_transfer *
 .Fn libusb_alloc_transfer "int iso_packets"
 Allocate a transfer with the number of isochronous packet descriptors
@@ -374,9 +375,7 @@
 .Fn libusb_cancel_transfer "struct libusb_transfer *tr"
 This function asynchronously cancels a transfer.
 Returns 0 on success and a LIBUSB_ERROR code on failure.
-.Pp
 .Sh USB SYNCHRONOUS I/O
-.Pp
 .Ft int
 .Fn libusb_control_transfer "libusb_device_handle *devh" "uint8_t bmReques=
tType" "uint8_t bRequest" "uint16_t wValue" "uint16_t wIndex" "unsigned cha=
r *data" "uint16_t wLength" "unsigned int timeout"
 Perform a USB control transfer.
@@ -411,9 +410,7 @@
 supported, LIBUSB_ERROR_OVERFLOW if the device offered more data,
 LIBUSB_ERROR_NO_DEVICE if the device has been disconnected and
 a LIBUSB_ERROR code on other failure.
-.Pp
 .Sh USB EVENTS
-.Pp
 .Ft int
 .Fn libusb_try_lock_events "libusb_context *ctx"
 Try to acquire the event handling lock.
@@ -429,7 +426,7 @@
 Release the event handling lock.
 This will wake up any thread blocked
 on
-.B libusb_wait_for_event() .
+.Fn libusb_wait_for_event .
 .Pp
 .Ft int
 .Fn libusb_event_handling_ok "libusb_context *ctx"
@@ -506,7 +503,6 @@
 libusb event sources.
 Returns a NULL-terminated list on success or NULL on failure.
 .Sh LIBUSB VERSION 0.1 COMPATIBILITY
-.Pp
 The library is also compliant with LibUSB version 0.1.12.
 .Pp
 .Fn usb_open
diff -r 428842767fa6 -r f2935497fa04 head/lib/libusb/libusb.h
--- a/head/lib/libusb/libusb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libusb/libusb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/libusb/libusb.h 227404 2011-11-09 19:03:26Z hselasky=
 $ */
+/* $FreeBSD: head/lib/libusb/libusb.h 234193 2012-04-12 18:06:30Z hselasky=
 $ */
 /*-
  * Copyright (c) 2009 Sylvestre Gallon. All rights reserved.
  *
@@ -371,6 +371,7 @@
 enum libusb_speed libusb_get_device_speed(libusb_device * dev);
 int	libusb_clear_halt(libusb_device_handle *devh, uint8_t endpoint);
 int	libusb_get_max_packet_size(libusb_device * dev, uint8_t endpoint);
+int	libusb_get_max_iso_packet_size(libusb_device * dev, uint8_t endpoint);
 libusb_device *libusb_ref_device(libusb_device * dev);
 void	libusb_unref_device(libusb_device * dev);
 int	libusb_open(libusb_device * dev, libusb_device_handle ** devh);
diff -r 428842767fa6 -r f2935497fa04 head/lib/libusb/libusb10.c
--- a/head/lib/libusb/libusb10.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libusb/libusb10.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/libusb/libusb10.c 228236 2011-12-03 16:30:47Z hselas=
ky $ */
+/* $FreeBSD: head/lib/libusb/libusb10.c 234193 2012-04-12 18:06:30Z hselas=
ky $ */
 /*-
  * Copyright (c) 2009 Sylvestre Gallon. All rights reserved.
  * Copyright (c) 2009 Hans Petter Selasky. All rights reserved.
@@ -331,6 +331,30 @@
 	return (ret);
 }
=20
+int
+libusb_get_max_iso_packet_size(libusb_device *dev, uint8_t endpoint)
+{
+	int multiplier;
+	int ret;
+
+	ret =3D libusb_get_max_packet_size(dev, endpoint);
+
+	switch (libusb20_dev_get_speed(dev->os_priv)) {
+	case LIBUSB20_SPEED_LOW:
+	case LIBUSB20_SPEED_FULL:
+		break;
+	default:
+		if (ret > -1) {
+			multiplier =3D (1 + ((ret >> 11) & 3));
+			if (multiplier > 3)
+				multiplier =3D 3;
+			ret =3D (ret & 0x7FF) * multiplier;
+		}
+		break;
+	}
+	return (ret);
+}
+
 libusb_device *
 libusb_ref_device(libusb_device *dev)
 {
diff -r 428842767fa6 -r f2935497fa04 head/lib/libusb/libusb20.3
--- a/head/lib/libusb/libusb20.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libusb/libusb20.3	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libusb/libusb20.3 226220 2011-10-10 16:13:33Z hsela=
sky $
+.\" $FreeBSD: head/lib/libusb/libusb20.3 233667 2012-03-29 16:07:22Z joel $
 .\"
 .Dd October 14, 2010
 .Dt LIBUSB20 3
@@ -235,7 +235,6 @@
 .
 .Sh USB TRANSFER OPERATIONS
 .
-.Pp
 .
 .Fn libusb20_tr_close
 will release all kernel resources associated with an USB
@@ -534,7 +533,6 @@
 .
 .Sh USB DEVICE OPERATIONS
 .
-.Pp
 .
 .Fn libusb20_dev_get_backend_name
 returns a zero terminated string describing the backend used.
@@ -542,7 +540,7 @@
 .Pp
 .
 .Fn libusb20_dev_get_info
-retrieves the BSD specific usb_device_info structure into the memory locat=
ion given by=20
+retrieves the BSD specific usb_device_info structure into the memory locat=
ion given by
 .Fa pinfo .
 The USB device given by
 .Fa pdev
@@ -1000,7 +998,6 @@
 .
 .
 .Sh USB DEBUGGING
-.Pp
 .Ft const char *
 .Fn libusb20_strerror "int code"
 Get the ASCII representation of the error given by the
diff -r 428842767fa6 -r f2935497fa04 head/lib/libutil/kinfo_getallproc.3
--- a/head/lib/libutil/kinfo_getallproc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libutil/kinfo_getallproc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -23,11 +23,11 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libutil/kinfo_getallproc.3 221807 2011-05-12 10:11:=
39Z stas $
+.\" $FreeBSD: head/lib/libutil/kinfo_getallproc.3 233520 2012-03-26 19:23:=
57Z joel $
 .\"
 .Dd July 9, 2009
+.Dt KINFO_GETALLPROC 3
 .Os
-.Dt KINFO_GETALLPROC 3
 .Sh NAME
 .Nm kinfo_getallproc
 .Nd function for getting process information of all processes from kernel
diff -r 428842767fa6 -r f2935497fa04 head/lib/libutil/kinfo_getproc.3
--- a/head/lib/libutil/kinfo_getproc.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libutil/kinfo_getproc.3	Tue Apr 17 11:51:51 2012 +0300
@@ -23,11 +23,11 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libutil/kinfo_getproc.3 232157 2012-02-25 14:31:25Z=
 gjb $
+.\" $FreeBSD: head/lib/libutil/kinfo_getproc.3 233520 2012-03-26 19:23:57Z=
 joel $
 .\"
 .Dd February 25, 2012
+.Dt KINFO_GETPROC 3
 .Os
-.Dt KINFO_GETPROC 3
 .Sh NAME
 .Nm kinfo_getproc
 .Nd function for getting process information from kernel
diff -r 428842767fa6 -r f2935497fa04 head/lib/libutil/login.conf.5
--- a/head/lib/libutil/login.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libutil/login.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
 .\" 5. Modifications may be freely made to this file providing the above
 .\"    conditions are met.
 .\"
-.\" $FreeBSD: head/lib/libutil/login.conf.5 223878 2011-07-09 08:42:23Z tr=
asz $
+.\" $FreeBSD: head/lib/libutil/login.conf.5 233698 2012-03-30 12:34:34Z jo=
el $
 .\"
 .Dd July 8, 2011
 .Dt LOGIN.CONF 5
@@ -177,20 +177,20 @@
 notation may be used.
 .Sh RESOURCE LIMITS
 .Bl -column pseudoterminals indent indent
-.It Sy "Name	Type	Notes	Description
-.It "coredumpsize	size		Maximum coredump size limit.
-.It "cputime	time		CPU usage limit.
-.It "datasize	size		Maximum data size limit.
-.It "filesize	size		Maximum file size limit.
-.It "maxproc	number		Maximum number of processes.
-.It "memorylocked	size		Maximum locked in core memory size limit.
-.It "memoryuse	size		Maximum of core memory use size limit.
-.It "openfiles	number		Maximum number of open files per process.
-.It "sbsize	size		Maximum permitted socketbuffer size.
-.It "vmemoryuse	size		Maximum permitted total VM usage per process.
-.It "stacksize	size		Maximum stack size limit.
-.It "pseudoterminals	number		Maximum number of pseudo-terminals.
-.It "swapuse	size		Maximum swap space size limit.
+.It Sy "Name	Type	Notes	Description"
+.It "coredumpsize	size		Maximum coredump size limit."
+.It "cputime	time		CPU usage limit."
+.It "datasize	size		Maximum data size limit."
+.It "filesize	size		Maximum file size limit."
+.It "maxproc	number		Maximum number of processes."
+.It "memorylocked	size		Maximum locked in core memory size limit."
+.It "memoryuse	size		Maximum of core memory use size limit."
+.It "openfiles	number		Maximum number of open files per process."
+.It "sbsize	size		Maximum permitted socketbuffer size."
+.It "vmemoryuse	size		Maximum permitted total VM usage per process."
+.It "stacksize	size		Maximum stack size limit."
+.It "pseudoterminals	number		Maximum number of pseudo-terminals."
+.It "swapuse	size		Maximum swap space size limit."
 .El
 .Pp
 These resource limit entries actually specify both the maximum
@@ -202,10 +202,10 @@
 -max or -cur to the capability name.
 .Sh ENVIRONMENT
 .Bl -column ignorenologin indent xbinxxusrxbin
-.It Sy "Name	Type	Notes	Description
-.It "charset	string		Set $MM_CHARSET environment variable to the specified
+.It Sy "Name	Type	Notes	Description"
+.It "charset	string		Set $MM_CHARSET environment variable to the specified"
 value.
-.It "cpumask	string		List of cpus to bind the user to.
+.It "cpumask	string		List of cpus to bind the user to."
 The syntax is the same as for the
 .Fl l
 argument of
@@ -214,9 +214,9 @@
 If set to
 .Ql default
 no action is taken.
-.It "hushlogin	bool	false	Same as having a ~/.hushlogin file.
-.It "ignorenologin	bool	false	Login not prevented by nologin.
-.It "ftp-chroot	bool	false	Limit FTP access with
+.It "hushlogin	bool	false	Same as having a ~/.hushlogin file."
+.It "ignorenologin	bool	false	Login not prevented by nologin."
+.It "ftp-chroot	bool	false	Limit FTP access with"
 .Xr chroot 2
 to the
 .Ev HOME
@@ -224,66 +224,66 @@
 See
 .Xr ftpd 8
 for details.
-.It "label	string			Default MAC policy; see
+.It "label	string		Default MAC policy; see"
 .Xr maclabel 7 .
-.It "lang	string		Set $LANG environment variable to the specified value.
-.It "manpath	path		Default search path for manpages.
-.It "nocheckmail	bool	false	Display mail status at login.
-.It "nologin	file		If the file exists it will be displayed and
+.It "lang	string		Set $LANG environment variable to the specified value."
+.It "manpath	path		Default search path for manpages."
+.It "nocheckmail	bool	false	Display mail status at login."
+.It "nologin	file		If the file exists it will be displayed and"
 the login session will be terminated.
-.It "path	path	/bin /usr/bin	Default search path.
-.It "priority	number		Initial priority (nice) level.
-.It "requirehome 	bool	false	Require a valid home directory to login.
-.It "setenv	list		A comma-separated list of environment variables and
+.It "path	path	/bin /usr/bin	Default search path."
+.It "priority	number		Initial priority (nice) level."
+.It "requirehome 	bool	false	Require a valid home directory to login."
+.It "setenv	list		A comma-separated list of environment variables and"
 values to which they are to be set.
-.It "shell	prog		Session shell to execute rather than the
+.It "shell	prog		Session shell to execute rather than the"
 shell specified in the passwd file.
 The SHELL environment variable will
 contain the shell specified in the password file.
-.It "term	string		Default terminal type if not able to determine
+.It "term	string		Default terminal type if not able to determine"
 from other means.
-.It "timezone	string		Default value of $TZ environment variable.
-.It "umask	number	022	Initial umask. Should always have a leading 0 to
+.It "timezone	string		Default value of $TZ environment variable."
+.It "umask	number	022	Initial umask. Should always have a leading 0 to"
 ensure octal interpretation.
-.It "welcome	file	/etc/motd	File containing welcome message.
+.It "welcome	file	/etc/motd	File containing welcome message."
 .El
 .Sh AUTHENTICATION
 .Bl -column passwd_prompt indent indent
-.It Sy "Name	Type	Notes	Description
+.It Sy "Name	Type	Notes	Description"
 .\" .It "approve	program 	Program to approve login.
-.It "copyright	file		File containing additional copyright information
-.It "host.allow	list		List of remote host wildcards from which users in
+.It "copyright	file		File containing additional copyright information"
+.It "host.allow	list		List of remote host wildcards from which users in"
 the class may access.
-.It "host.deny	list		List of remote host wildcards from which users
+.It "host.deny	list		List of remote host wildcards from which users"
 in the class may not access.
-.It "login_prompt	string		The login prompt given by
+.It "login_prompt	string		The login prompt given by"
 .Xr login 1
-.It "login-backoff	number	3	The number of login attempts
+.It "login-backoff	number	3	The number of login attempts"
 allowed before the backoff delay is inserted after each subsequent
 attempt.
 The backoff delay is the number of tries above
 .Em login-backoff
 multiplied by 5 seconds.
-.It "login-retries	number	10	The number of login attempts
+.It "login-retries	number	10	The number of login attempts"
 allowed before the login fails.
-.It "passwd_format	string	md5	The encryption format that new or
+.It "passwd_format	string	md5	The encryption format that new or"
 changed passwords will use.
 Valid values include "des", "md5" and "blf".
 NIS clients using a
 .No non- Ns Fx
 NIS server should probably use "des".
-.It "passwd_prompt	string		The password prompt presented by
+.It "passwd_prompt	string		The password prompt presented by"
 .Xr login 1
-.It "times.allow 	list		List of time periods during which
+.It "times.allow 	list		List of time periods during which"
 logins are allowed.
-.It "times.deny	list		List of time periods during which logins are
+.It "times.deny	list		List of time periods during which logins are"
 disallowed.
-.It "ttys.allow	list		List of ttys and ttygroups which users
+.It "ttys.allow	list		List of ttys and ttygroups which users"
 in the class may use for access.
-.It "ttys.deny	list		List of ttys and ttygroups which users
+.It "ttys.deny	list		List of ttys and ttygroups which users"
 in the class may not use for access.
-.It "warnexpire	time		Advance notice for pending account expiry.
-.It "warnpassword	time		Advance notice for pending password expiry.
+.It "warnexpire	time		Advance notice for pending account expiry."
+.It "warnpassword	time		Advance notice for pending password expiry."
 .\".It "widepasswords	bool	false	Use the wide password format. The wide pa=
ssword
 .\" format allows up to 128 significant characters in the password.
 .El
@@ -388,46 +388,46 @@
 may be supported by third-party software.
 They are not implemented in the base system.
 .Bl -column host.accounted indent indent
-.It Sy "Name	Type	Notes	Description
-.It "accounted	bool	false	Enable session time accounting for all users
+.It Sy "Name	Type	Notes	Description"
+.It "accounted	bool	false	Enable session time accounting for all users"
 in this class.
-.It "auth	list	passwd	Allowed authentication styles.
+.It "auth	list	passwd	Allowed authentication styles."
 The first item is the default style.
-.It "auth-" Ns Ar type Ta "list		Allowed authentication styles for the
+.It "auth-" Ns Ar type Ta "list		Allowed authentication styles for the"
 authentication
 .Ar type .
-.It "autodelete	time		Time after expiry when account is auto-deleted.
-.It "bootfull	bool	false	Enable 'boot only if ttygroup is full' strategy
+.It "autodelete	time		Time after expiry when account is auto-deleted."
+.It "bootfull	bool	false	Enable 'boot only if ttygroup is full' strategy"
 when terminating sessions.
-.It "daytime	time		Maximum login time per day.
-.It "expireperiod	time		Time for expiry allocation.
-.It "graceexpire 	time		Grace days for expired account.
-.It "gracetime	time		Additional grace login time allowed.
-.It "host.accounted	list		List of remote host wildcards from which
+.It "daytime	time		Maximum login time per day."
+.It "expireperiod	time		Time for expiry allocation."
+.It "graceexpire 	time		Grace days for expired account."
+.It "gracetime	time		Additional grace login time allowed."
+.It "host.accounted	list		List of remote host wildcards from which"
 login sessions will be accounted.
-.It "host.exempt 	list		List of remote host wildcards from which
+.It "host.exempt 	list		List of remote host wildcards from which"
 login session accounting is exempted.
-.It "idletime	time		Maximum idle time before logout.
-.It "minpasswordlen	number	6	The minimum length a local
+.It "idletime	time		Maximum idle time before logout."
+.It "minpasswordlen	number	6	The minimum length a local"
 password may be.
-.It "mixpasswordcase	bool	true	Whether
+.It "mixpasswordcase	bool	true	Whether"
 .Xr passwd 1
 will warn the user if an all lower case password is entered.
-.It "monthtime 	time		Maximum login time per month.
-.It "passwordtime	time		Used by
+.It "monthtime 	time		Maximum login time per month."
+.It "passwordtime	time		Used by"
 .Xr passwd 1
 to set next password expiry date.
-.It "refreshtime 	time		New time allowed on account refresh.
-.It "refreshperiod	str		How often account time is refreshed.
-.It "sessiontime 	time		Maximum login time per session.
-.It "sessionlimit	number		Maximum number of concurrent
+.It "refreshtime 	time		New time allowed on account refresh."
+.It "refreshperiod	str		How often account time is refreshed."
+.It "sessiontime 	time		Maximum login time per session."
+.It "sessionlimit	number		Maximum number of concurrent"
 login sessions on ttys in any group.
-.It "ttys.accounted	list		List of ttys and ttygroups for which
+.It "ttys.accounted	list		List of ttys and ttygroups for which"
 login accounting is active.
-.It "ttys.exempt	list		List of ttys and ttygroups for which login accounti=
ng
+.It "ttys.exempt	list		List of ttys and ttygroups for which login accounti=
ng"
 is exempt.
-.It "warntime	time		Advance notice for pending out-of-time.
-.It "weektime	time		Maximum login time per week.
+.It "warntime	time		Advance notice for pending out-of-time."
+.It "weektime	time		Maximum login time per week."
 .El
 .Pp
 The
diff -r 428842767fa6 -r f2935497fa04 head/lib/libutil/login_cap.3
--- a/head/lib/libutil/login_cap.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libutil/login_cap.3	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
 .\" 5. Modifications may be freely made to this file providing the above
 .\"    conditions are met.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libutil/login_cap.3 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd June 14, 2007
 .Dt LOGIN_CAP 3
@@ -509,7 +509,7 @@
 these rules.
 .Bl -bullet
 .It
-If=20
+If
 .Fa auth
 is neither
 .Dv NULL
@@ -524,7 +524,7 @@
 .Ql passwd
 as the authorisation list.
 .It
-If=20
+If
 .Fa style
 is not
 .Dv NULL
diff -r 428842767fa6 -r f2935497fa04 head/lib/libutil/quotafile.3
--- a/head/lib/libutil/quotafile.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/libutil/quotafile.3	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libutil/quotafile.3 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd December 28, 2009
 .Dt QUOTAFILE 3
@@ -242,7 +242,7 @@
 .Sh RETURN VALUES
 If the filesystem has quotas associated with it,
 .Fn quota_open
-returns a pointer to a=20
+returns a pointer to a
 .Vt quotafile
 structure used in subsequent quota access calls.
 If the filesystem has no quotas, or access permission is denied
@@ -285,6 +285,6 @@
 The
 .Nm quotafile
 functions and this manual page were written by
-.An Dag-Erling Sm\(/orgrav Aq des at FreeBSD.org=20
+.An Dag-Erling Sm\(/orgrav Aq des at FreeBSD.org
 and
 .An Marshall Kirk McKusick Aq mckusick at mckusick.com .
diff -r 428842767fa6 -r f2935497fa04 head/lib/msun/man/csqrt.3
--- a/head/lib/msun/man/csqrt.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/msun/man/csqrt.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/msun/man/csqrt.3 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd March 30, 2008
 .Dt CSQRT 3
@@ -66,14 +66,14 @@
 For infinities and \*(Nas, the following rules apply, with the
 earlier rules having precedence:
 .Bl -column -offset indent "-\*(If + \*(Na*I" "\*(If \*(Pm \*(If*I  " "(fo=
r all k)"
-.Em Input	Result
+.Em "Input" Ta Em "Result" Ta \&
 k + \*(If*I	\*(If + \*(If*I	(for all k)
--\*(If + \*(Na*I	\*(Na \*(Pm \*(If*I
-\*(If + \*(Na*I	\*(If + \*(Na*I
-k + \*(Na*I	\*(Na + \*(Na*I
-\*(Na + k*I	\*(Na + \*(Na*I
--\*(If + k*I	+0 + \*(If*I
-\*(If + k*I	\*(If + 0*I
+-\*(If + \*(Na*I	\*(Na \*(Pm \*(If*I	\&
+\*(If + \*(Na*I	\*(If + \*(Na*I	\&
+k + \*(Na*I	\*(Na + \*(Na*I	\&
+\*(Na + k*I	\*(Na + \*(Na*I	\&
+-\*(If + k*I	+0 + \*(If*I	\&
+\*(If + k*I	\*(If + 0*I	\&
 .El
 .Pp
 For numbers with negative imaginary parts, the above special cases
diff -r 428842767fa6 -r f2935497fa04 head/lib/msun/man/ieee.3
--- a/head/lib/msun/man/ieee.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/msun/man/ieee.3	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     from: @(#)ieee.3	6.4 (Berkeley) 5/6/91
-.\" $FreeBSD: head/lib/msun/man/ieee.3 226436 2011-10-16 14:30:28Z eadler $
+.\" $FreeBSD: head/lib/msun/man/ieee.3 233462 2012-03-25 12:13:24Z joel $
 .\"
 .Dd January 26, 2005
 .Dt IEEE 3
@@ -271,7 +271,6 @@
 .Ed
 .Ed
 .Ss Additional Information Regarding Exceptions
-.Pp
 For each kind of floating-point exception, IEEE 754
 provides a Flag that is raised each time its exception
 is signaled, and stays raised until the program resets
diff -r 428842767fa6 -r f2935497fa04 head/lib/msun/src/s_remquo.c
--- a/head/lib/msun/src/s_remquo.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/msun/src/s_remquo.c	Tue Apr 17 11:51:51 2012 +0300
@@ -11,7 +11,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/msun/src/s_remquo.c 233973 2012-04-07 03:59:1=
2Z das $");
=20
 #include <float.h>
=20
@@ -51,7 +51,7 @@
 		goto fixup;	/* |x|<|y| return x or x-y */
 	    }
 	    if(lx=3D=3Dly) {
-		*quo =3D 1;
+		*quo =3D (sxy ? -1 : 1);
 		return Zero[(u_int32_t)sx>>31];	/* |x|=3D|y| return x*0*/
 	    }
 	}
@@ -114,6 +114,7 @@
=20
     /* convert back to floating value and restore the sign */
 	if((hx|lx)=3D=3D0) {			/* return sign(x)*0 */
+	    q &=3D 0x7fffffff;
 	    *quo =3D (sxy ? -q : q);
 	    return Zero[(u_int32_t)sx>>31];
 	}
@@ -129,9 +130,9 @@
 		lx =3D (lx>>n)|((u_int32_t)hx<<(32-n));
 		hx >>=3D n;
 	    } else if (n<=3D31) {
-		lx =3D (hx<<(32-n))|(lx>>n); hx =3D sx;
+		lx =3D (hx<<(32-n))|(lx>>n); hx =3D 0;
 	    } else {
-		lx =3D hx>>(n-32); hx =3D sx;
+		lx =3D hx>>(n-32); hx =3D 0;
 	    }
 	}
 fixup:
diff -r 428842767fa6 -r f2935497fa04 head/lib/msun/src/s_remquof.c
--- a/head/lib/msun/src/s_remquof.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/msun/src/s_remquof.c	Tue Apr 17 11:51:51 2012 +0300
@@ -11,7 +11,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/msun/src/s_remquof.c 233973 2012-04-07 03:59:=
12Z das $");
=20
 #include "math.h"
 #include "math_private.h"
@@ -46,7 +46,7 @@
 	    q =3D 0;
 	    goto fixup;	/* |x|<|y| return x or x-y */
 	} else if(hx=3D=3Dhy) {
-	    *quo =3D 1;
+	    *quo =3D (sxy ? -1 : 1);
 	    return Zero[(u_int32_t)sx>>31];	/* |x|=3D|y| return x*0*/
 	}
=20
@@ -88,6 +88,7 @@
=20
     /* convert back to floating value and restore the sign */
 	if(hx=3D=3D0) {				/* return sign(x)*0 */
+	    q &=3D 0x7fffffff;
 	    *quo =3D (sxy ? -q : q);
 	    return Zero[(u_int32_t)sx>>31];
 	}
diff -r 428842767fa6 -r f2935497fa04 head/lib/msun/src/s_remquol.c
--- a/head/lib/msun/src/s_remquol.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/lib/msun/src/s_remquol.c	Tue Apr 17 11:51:51 2012 +0300
@@ -11,7 +11,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/msun/src/s_remquol.c 233973 2012-04-07 03:59:=
12Z das $");
=20
 #include <float.h>
 #include <stdint.h>
@@ -96,7 +96,7 @@
 		goto fixup;	/* |x|<|y| return x or x-y */
 	    }
 	    if(ux.bits.manh=3D=3Duy.bits.manh && ux.bits.manl=3D=3Duy.bits.manl) {
-		*quo =3D 1;
+		*quo =3D (sxy ? -1 : 1);
 		return Zero[sx];	/* |x|=3D|y| return x*0*/
 	    }
 	}
@@ -138,6 +138,7 @@
=20
     /* convert back to floating value and restore the sign */
 	if((hx|lx)=3D=3D0) {			/* return sign(x)*0 */
+	    q &=3D 0x7fffffff;
 	    *quo =3D (sxy ? -q : q);
 	    return Zero[sx];
 	}
diff -r 428842767fa6 -r f2935497fa04 head/libexec/bootpd/bootpd.8
--- a/head/libexec/bootpd/bootpd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/bootpd/bootpd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 .\" Copyright (c) 1988, 1989, 1991 Carnegie Mellon University
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/libexec/bootpd/bootpd.8 233466 2012-03-25 16:00:56Z joe=
l $
 .\"
 .Dd February 10, 2004
 .Dt BOOTPD 8
@@ -263,9 +263,21 @@
 Current directory typically used by the TFTP server and
 .Nm .
 .El
-.Sh BUGS
-Individual host entries must not exceed 1024 characters.
-.Sh CREDITS
+.Sh "SEE ALSO"
+.Xr bootptab 5 ,
+.Xr inetd 8 ,
+.Xr tftpd 8
+.Pp
+DARPA Internet Request For Comments:
+.Bl -tag -width RFC1533 -compact
+.It RFC951
+Bootstrap Protocol
+.It RFC1532
+Clarifications and Extensions for the Bootstrap Protocol
+.It RFC1533
+DHCP Options and BOOTP Vendor Extensions
+.El
+.Sh AUTHORS
 This distribution is currently maintained by
 .An Walter L. Wimer Aq walt+ at cmu.edu .
 .Pp
@@ -294,17 +306,5 @@
 .An Jim McKim Aq mckim at lerc.nasa.gov
 .An Gordon W. Ross Aq gwr at mc.com
 .An Jason Zions Aq jazz at hal.com .
-.Sh "SEE ALSO"
-.Xr bootptab 5 ,
-.Xr inetd 8 ,
-.Xr tftpd 8
-.Pp
-DARPA Internet Request For Comments:
-.Bl -tag -width RFC1533 -compact
-.It RFC951
-Bootstrap Protocol
-.It RFC1532
-Clarifications and Extensions for the Bootstrap Protocol
-.It RFC1533
-DHCP Options and BOOTP Vendor Extensions
-.El
+.Sh BUGS
+Individual host entries must not exceed 1024 characters.
diff -r 428842767fa6 -r f2935497fa04 head/libexec/getty/gettytab.5
--- a/head/libexec/getty/gettytab.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/getty/gettytab.5	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     from: @(#)gettytab.5	8.4 (Berkeley) 4/19/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/libexec/getty/gettytab.5 233510 2012-03-26 15:18:14Z jo=
el $
 .\" "
 .Dd April 19, 1994
 .Dt GETTYTAB 5
@@ -75,7 +75,7 @@
 .Va default
 table.
 .Bl -column Name Type /usr/bin/login
-.It Sy "Name	Type	Default	Description
+.It Sy "Name	Type	Default	Description"
 .It "ac	str	unused	expect-send chat script for modem answer"
 .It "al	str	unused	user to auto-login instead of prompting"
 .It "ap	bool	false	terminal uses any parity"
@@ -188,7 +188,7 @@
 .It "ub	bool	false	do unbuffered output (of prompts etc)"
 .It "we	str" Ta So Li ^W Sc Ta
 .No "word erase character"
-.It "xc	bool	false	do
+.It "xc	bool	false	do"
 .Em NOT
 echo control chars as
 .Ql ^X
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/Makefile
--- a/head/libexec/rtld-elf/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/libexec/rtld-elf/Makefile 232831 2012-03-11 20:03:09Z kib=
 $
+# $FreeBSD: head/libexec/rtld-elf/Makefile 233431 2012-03-24 19:14:44Z kib=
 $
=20
 .include <bsd.own.mk>
 MK_SSP=3D		no
@@ -9,8 +9,9 @@
 		malloc.c xmalloc.c debug.c libmap.c
 MAN=3D		rtld.1
 CSTD?=3D		gnu99
+TOPSRCDIR=3D	${.CURDIR}/../..
 CFLAGS+=3D	-Wall -DFREEBSD_ELF -DIN_RTLD
-CFLAGS+=3D	-I${.CURDIR}/../../lib/csu/common
+CFLAGS+=3D	-I${TOPSRCDIR}/lib/csu/common
 .if exists(${.CURDIR}/${MACHINE_ARCH})
 RTLD_ARCH=3D	${MACHINE_ARCH}
 .else
@@ -39,10 +40,10 @@
 CFLAGS+=3D	-DPIC $(DEBUG)
 LDFLAGS+=3D	-shared -Wl,-Bsymbolic
 DPADD=3D		${LIBC_PIC}
-LDADD=3D		-lc_pic -lssp_nonshared
+LDADD=3D		-lc_pic
=20
 .if ${MK_SYMVER} =3D=3D "yes"
-LIBCDIR=3D	${.CURDIR}/../../lib/libc
+LIBCDIR=3D	${TOPSRCDIR}/lib/libc
 VERSION_DEF=3D	${LIBCDIR}/Versions.def
 SYMBOL_MAPS=3D	${.CURDIR}/Symbol.map
 VERSION_MAP=3D	Version.map
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/amd64/reloc.c
--- a/head/libexec/rtld-elf/amd64/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/amd64/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/amd64/reloc.c 230281 2012-01-17 21:55:2=
0Z ed $
+ * $FreeBSD: head/libexec/rtld-elf/amd64/reloc.c 233231 2012-03-20 13:20:4=
9Z kib $
  */
=20
 /*
@@ -82,6 +82,7 @@
 	    size =3D dstsym->st_size;
 	    symlook_init(&req, name);
 	    req.ventry =3D fetch_ventry(dstobj, ELF_R_SYM(rela->r_info));
+	    req.flags =3D SYMLOOK_EARLY;
=20
 	    for (srcobj =3D dstobj->next;  srcobj !=3D NULL;  srcobj =3D srcobj->=
next) {
 		res =3D symlook_obj(&req, srcobj);
@@ -118,7 +119,8 @@
=20
 /* Process the non-PLT relocations. */
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rela *relalim;
 	const Elf_Rela *rela;
@@ -151,7 +153,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -170,7 +172,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -200,7 +202,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -214,7 +216,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -245,7 +247,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -277,7 +279,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -291,7 +293,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -305,7 +307,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -330,7 +332,7 @@
 done:
 	if (cache !=3D NULL)
 	    free(cache);
-	return(r);
+	return (r);
 }
=20
 /* Process the PLT relocations. */
@@ -366,7 +368,7 @@
=20
 /* Relocate the jump slots in an object. */
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
     const Elf_Rela *relalim;
     const Elf_Rela *rela;
@@ -382,8 +384,8 @@
 	switch (ELF_R_TYPE(rela->r_info)) {
 	case R_X86_64_JMP_SLOT:
 	  where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
-	  def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj, true, NULL,
-	      lockstate);
+	  def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
+		SYMLOOK_IN_PLT | flags, NULL, lockstate);
 	  if (def =3D=3D NULL)
 	      return (-1);
 	  if (ELF_ST_TYPE(def->st_info) =3D=3D STT_GNU_IFUNC) {
@@ -438,7 +440,7 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
     const Elf_Rela *relalim;
     const Elf_Rela *rela;
@@ -454,8 +456,8 @@
 	switch (ELF_R_TYPE(rela->r_info)) {
 	case R_X86_64_JMP_SLOT:
 	  where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
-	  def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj, true, NULL,
-	      lockstate);
+	  def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
+		SYMLOOK_IN_PLT | flags, NULL, lockstate);
 	  if (def =3D=3D NULL)
 	      return (-1);
 	  if (ELF_ST_TYPE(def->st_info) !=3D STT_GNU_IFUNC)
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/arm/reloc.c
--- a/head/libexec/rtld-elf/arm/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/arm/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 /*	$NetBSD: mdreloc.c,v 1.23 2003/07/26 15:04:38 mrg Exp $	*/
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/libexec/rtld-elf/arm/reloc.c 231618 2012-02-14 00=
:16:34Z gonzo $");
+__FBSDID("$FreeBSD: head/libexec/rtld-elf/arm/reloc.c 233231 2012-03-20 13=
:20:49Z kib $");
 #include <sys/param.h>
 #include <sys/mman.h>
=20
@@ -54,6 +54,8 @@
 			symlook_init(&req, name);
 			req.ventry =3D fetch_ventry(dstobj,
 			    ELF_R_SYM(rel->r_info));
+			req.flags =3D SYMLOOK_EARLY;
+
 			for (srcobj =3D dstobj->next;  srcobj !=3D NULL;=20
 			     srcobj =3D srcobj->next) {
 				res =3D symlook_obj(&req, srcobj);
@@ -135,7 +137,7 @@
=20
 static int
 reloc_nonplt_object(Obj_Entry *obj, const Elf_Rel *rel, SymCache *cache,
-    RtldLockState *lockstate)
+    int flags, RtldLockState *lockstate)
 {
 	Elf_Addr        *where;
 	const Elf_Sym   *def;
@@ -161,7 +163,7 @@
 		if (addend & 0x00800000)
 			addend |=3D 0xff000000;
 	=09
-		def =3D find_symdef(symnum, obj, &defobj, false, cache,
+		def =3D find_symdef(symnum, obj, &defobj, flags, cache,
 		    lockstate);
 		if (def =3D=3D NULL)
 				return -1;
@@ -188,7 +190,7 @@
=20
 		case R_ARM_ABS32:	/* word32 B + S + A */
 		case R_ARM_GLOB_DAT:	/* word32 B + S */
-			def =3D find_symdef(symnum, obj, &defobj, false, cache,
+			def =3D find_symdef(symnum, obj, &defobj, flags, cache,
 			    lockstate);
 			if (def =3D=3D NULL)
 				return -1;
@@ -237,7 +239,7 @@
 			break;
=20
 		case R_ARM_TLS_DTPOFF32:
-			def =3D find_symdef(symnum, obj, &defobj, false, cache,
+			def =3D find_symdef(symnum, obj, &defobj, flags, cache,
 			    lockstate);
 			if (def =3D=3D NULL)
 				return -1;
@@ -254,7 +256,7 @@
=20
 			break;
 		case R_ARM_TLS_DTPMOD32:
-			def =3D find_symdef(symnum, obj, &defobj, false, cache,
+			def =3D find_symdef(symnum, obj, &defobj, flags, cache,
 			    lockstate);
 			if (def =3D=3D NULL)
 				return -1;
@@ -272,7 +274,7 @@
 			break;
=20
 		case R_ARM_TLS_TPOFF32:
-			def =3D find_symdef(symnum, obj, &defobj, false, cache,
+			def =3D find_symdef(symnum, obj, &defobj, flags, cache,
 			    lockstate);
 			if (def =3D=3D NULL)
 				return -1;
@@ -311,7 +313,8 @@
  *  * Process non-PLT relocations
  *   */
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rel *rellim;
 	const Elf_Rel *rel;
@@ -330,7 +333,7 @@
=20
 	rellim =3D (const Elf_Rel *)((caddr_t)obj->rel + obj->relsize);
 	for (rel =3D obj->rel; rel < rellim; rel++) {
-		if (reloc_nonplt_object(obj, rel, cache, lockstate) < 0)
+		if (reloc_nonplt_object(obj, rel, cache, flags, lockstate) < 0)
 			goto done;
 	}
 	r =3D 0;
@@ -367,7 +370,7 @@
  *  * LD_BIND_NOW was set - force relocation for all jump slots
  *   */
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
 	const Obj_Entry *defobj;
 	const Elf_Rel *rellim;
@@ -381,7 +384,7 @@
 		assert(ELF_R_TYPE(rel->r_info) =3D=3D R_ARM_JUMP_SLOT);
 		where =3D (Elf_Addr *)(obj->relocbase + rel->r_offset);
 		def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
-		    true, NULL, lockstate);
+		    SYMLOOK_IN_PLT | flags, NULL, lockstate);
 		if (def =3D=3D NULL) {
 			dbg("reloc_jmpslots: sym not found");
 			return (-1);
@@ -406,7 +409,8 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags,
+    struct Struct_RtldLockState *lockstate)
 {
=20
 	/* XXX not implemented */
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/i386/reloc.c
--- a/head/libexec/rtld-elf/i386/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/i386/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/i386/reloc.c 230281 2012-01-17 21:55:20=
Z ed $
+ * $FreeBSD: head/libexec/rtld-elf/i386/reloc.c 233231 2012-03-20 13:20:49=
Z kib $
  */
=20
 /*
@@ -83,6 +83,7 @@
 	    size =3D dstsym->st_size;
 	    symlook_init(&req, name);
 	    req.ventry =3D fetch_ventry(dstobj, ELF_R_SYM(rel->r_info));
+	    req.flags =3D SYMLOOK_EARLY;
=20
 	    for (srcobj =3D dstobj->next;  srcobj !=3D NULL;  srcobj =3D srcobj->=
next) {
 		res =3D symlook_obj(&req, srcobj);
@@ -119,7 +120,8 @@
=20
 /* Process the non-PLT relocations. */
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rel *rellim;
 	const Elf_Rel *rel;
@@ -151,7 +153,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -170,7 +172,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -200,7 +202,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -220,7 +222,7 @@
 		    Elf_Addr add;
=20
 		    def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -253,7 +255,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -267,7 +269,7 @@
 		    const Obj_Entry *defobj;
=20
 		    def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
-		      false, cache, lockstate);
+		      flags, cache, lockstate);
 		    if (def =3D=3D NULL)
 			goto done;
=20
@@ -286,7 +288,7 @@
 done:
 	if (cache !=3D NULL)
 	    free(cache);
-	return(r);
+	return (r);
 }
=20
 /* Process the PLT relocations. */
@@ -322,7 +324,7 @@
=20
 /* Relocate the jump slots in an object. */
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
     const Elf_Rel *rellim;
     const Elf_Rel *rel;
@@ -338,8 +340,8 @@
 	switch (ELF_R_TYPE(rel->r_info)) {
 	case R_386_JMP_SLOT:
 	  where =3D (Elf_Addr *)(obj->relocbase + rel->r_offset);
-	  def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
-	      lockstate);
+	  def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
+		SYMLOOK_IN_PLT | flags, NULL, lockstate);
 	  if (def =3D=3D NULL)
 	      return (-1);
 	  if (ELF_ST_TYPE(def->st_info) =3D=3D STT_GNU_IFUNC) {
@@ -390,7 +392,7 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
     const Elf_Rel *rellim;
     const Elf_Rel *rel;
@@ -406,8 +408,8 @@
 	switch (ELF_R_TYPE(rel->r_info)) {
 	case R_386_JMP_SLOT:
 	  where =3D (Elf_Addr *)(obj->relocbase + rel->r_offset);
-	  def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL,
-	      lockstate);
+	  def =3D find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj,
+		SYMLOOK_IN_PLT | flags, NULL, lockstate);
 	  if (def =3D=3D NULL)
 	      return (-1);
 	  if (ELF_ST_TYPE(def->st_info) !=3D STT_GNU_IFUNC)
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/ia64/reloc.c
--- a/head/libexec/rtld-elf/ia64/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/ia64/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/ia64/reloc.c 232831 2012-03-11 20:03:09=
Z kib $
+ * $FreeBSD: head/libexec/rtld-elf/ia64/reloc.c 233307 2012-03-22 14:20:51=
Z kib $
  */
=20
 /*
@@ -87,7 +87,7 @@
 	struct fptr* fptr;
=20
 	if (next_fptr =3D=3D last_fptr) {
-		current_chunk =3D malloc(sizeof(struct fptr_chunk));
+		current_chunk =3D xmalloc(sizeof(struct fptr_chunk));
 		next_fptr =3D &current_chunk->fptrs[0];
 		last_fptr =3D &current_chunk->fptrs[FPTR_CHUNK_SIZE];
 	}
@@ -116,9 +116,7 @@
 		if (fptrs =3D=3D MAP_FAILED)
 			fptrs =3D NULL;
 	} else {
-		fptrs =3D malloc(fbytes);
-		if (fptrs !=3D NULL)
- 			memset(fptrs, 0, fbytes);
+		fptrs =3D xcalloc(1, fbytes);
 	}
=20
 	/*
@@ -151,7 +149,7 @@
 /* Relocate a non-PLT object with addend. */
 static int
 reloc_non_plt_obj(Obj_Entry *obj_rtld, Obj_Entry *obj, const Elf_Rela *rel=
a,
-    SymCache *cache, RtldLockState *lockstate)
+    SymCache *cache, int flags, RtldLockState *lockstate)
 {
 	struct fptr **fptrs;
 	Elf_Addr *where =3D (Elf_Addr *) (obj->relocbase + rela->r_offset);
@@ -172,7 +170,7 @@
 		Elf_Addr target;
=20
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL)
 			return -1;
=20
@@ -195,7 +193,7 @@
 		int sym_index;
=20
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    true, cache, lockstate);
+		    SYMLOOK_IN_PLT | flags, cache, lockstate);
 		if (def =3D=3D NULL) {
 			/*
 			 * XXX r_debug_state is problematic and find_symdef()
@@ -254,7 +252,7 @@
 		Elf_Addr target, gp;
=20
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL)
 			return -1;
=20
@@ -277,7 +275,7 @@
 		const Obj_Entry *defobj;
=20
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL)
 			return -1;
=20
@@ -290,7 +288,7 @@
 		const Obj_Entry *defobj;
=20
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL)
 			return -1;
=20
@@ -303,7 +301,7 @@
 		const Obj_Entry *defobj;
=20
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL)
 			return -1;
=20
@@ -342,7 +340,8 @@
=20
 /* Process the non-PLT relocations. */
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rel *rellim;
 	const Elf_Rel *rel;
@@ -368,7 +367,7 @@
 		locrela.r_info =3D rel->r_info;
 		locrela.r_offset =3D rel->r_offset;
 		locrela.r_addend =3D 0;
-		if (reloc_non_plt_obj(obj_rtld, obj, &locrela, cache,
+		if (reloc_non_plt_obj(obj_rtld, obj, &locrela, cache, flags,
 		    lockstate))
 			goto done;
 	}
@@ -376,7 +375,8 @@
 	/* Perform relocations with addend if there are any: */
 	relalim =3D (const Elf_Rela *) ((caddr_t) obj->rela + obj->relasize);
 	for (rela =3D obj->rela;  obj->rela !=3D NULL && rela < relalim;  rela++)=
 {
-		if (reloc_non_plt_obj(obj_rtld, obj, rela, cache, lockstate))
+		if (reloc_non_plt_obj(obj_rtld, obj, rela, cache, flags,
+		    lockstate))
 			goto done;
 	}
=20
@@ -444,7 +444,8 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags,
+    struct Struct_RtldLockState *lockstate)
 {
=20
 	/* XXX not implemented */
@@ -453,7 +454,7 @@
=20
 /* Relocate the jump slots in an object. */
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
 	if (obj->jmpslots_done)
 		return 0;
@@ -472,7 +473,7 @@
 			assert(ELF_R_TYPE(rel->r_info) =3D=3D R_IA_64_IPLTLSB);
 			where =3D (Elf_Addr *)(obj->relocbase + rel->r_offset);
 			def =3D find_symdef(ELF_R_SYM(rel->r_info), obj,
-			    &defobj, true, NULL, lockstate);
+			    &defobj, SYMLOOK_IN_PLT | flags, NULL, lockstate);
 			if (def =3D=3D NULL)
 				return -1;
 			reloc_jmpslot(where,
@@ -493,7 +494,7 @@
=20
 			where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
 			def =3D find_symdef(ELF_R_SYM(rela->r_info), obj,
-			    &defobj, true, NULL, lockstate);
+			    &defobj, SYMLOOK_IN_PLT | flags, NULL, lockstate);
 			if (def =3D=3D NULL)
 				return -1;
 			reloc_jmpslot(where,
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/malloc.c
--- a/head/libexec/rtld-elf/malloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/malloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
=20
 #if defined(LIBC_SCCS) && !defined(lint)
 /*static char *sccsid =3D "from: @(#)malloc.c	5.11 (Berkeley) 2/23/91";*/
-static char *rcsid =3D "$FreeBSD: head/libexec/rtld-elf/malloc.c 225152 20=
11-08-24 20:05:13Z kib $";
+static char *rcsid =3D "$FreeBSD: head/libexec/rtld-elf/malloc.c 233306 20=
12-03-22 14:11:10Z kib $";
 #endif /* LIBC_SCCS and not lint */
=20
 /*
@@ -59,15 +59,6 @@
 #include <sys/param.h>
 #include <sys/mman.h>
 #include "rtld_printf.h"
-#ifndef BSD
-#define MAP_COPY	MAP_PRIVATE
-#define MAP_FILE	0
-#define MAP_ANON	0
-#endif
-
-#ifndef BSD		/* Need do better than this */
-#define NEED_DEV_ZERO	1
-#endif
=20
 static void morecore();
 static int findbucket();
@@ -492,12 +483,6 @@
 	int	fd =3D -1;
 	int	offset;
=20
-#ifdef NEED_DEV_ZERO
-	fd =3D open(_PATH_DEVZERO, O_RDWR, 0);
-	if (fd =3D=3D -1)
-		perror(_PATH_DEVZERO);
-#endif
-
 	if (pagepool_end - pagepool_start > pagesz) {
 		caddr_t	addr =3D (caddr_t)
 			(((long)pagepool_start + pagesz - 1) & ~(pagesz - 1));
@@ -517,8 +502,5 @@
 	pagepool_end =3D pagepool_start + n * pagesz;
 	pagepool_start +=3D offset;
=20
-#ifdef NEED_DEV_ZERO
-	close(fd);
-#endif
 	return n;
 }
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/mips/reloc.c
--- a/head/libexec/rtld-elf/mips/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/mips/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/libexec/rtld-elf/mips/reloc.c 232578 2012-03-06 0=
3:27:08Z gonzo $");
+__FBSDID("$FreeBSD: head/libexec/rtld-elf/mips/reloc.c 233231 2012-03-20 1=
3:20:49Z kib $");
=20
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -258,7 +258,8 @@
 }
=20
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rel *rel;
 	const Elf_Rel *rellim;
@@ -317,7 +318,7 @@
 			 * to 0 if there are non-PLT references, but older
 			 * versions of GNU ld do not do this.
 			 */
-			def =3D find_symdef(i, obj, &defobj, false, NULL,
+			def =3D find_symdef(i, obj, &defobj, flags, NULL,
 			    lockstate);
 			if (def =3D=3D NULL)
 				return -1;
@@ -359,7 +360,7 @@
 			}
 		} else {
 			/* TODO: add cache here */
-			def =3D find_symdef(i, obj, &defobj, false, NULL,
+			def =3D find_symdef(i, obj, &defobj, flags, NULL,
 			    lockstate);
 			if (def =3D=3D NULL) {
 				dbg("Warning4, can't find symbole %d", i);
@@ -458,7 +459,7 @@
 			Elf_Addr old =3D load_ptr(where, rlen);
 			Elf_Addr val =3D old;
=20
-        		def =3D find_symdef(r_symndx, obj, &defobj, false, NULL,
+        		def =3D find_symdef(r_symndx, obj, &defobj, flags, NULL,
 	    			lockstate);
 			if (def =3D=3D NULL)
 				return -1;
@@ -482,7 +483,7 @@
 			Elf_Addr old =3D load_ptr(where, rlen);
 			Elf_Addr val =3D old;
=20
-        		def =3D find_symdef(r_symndx, obj, &defobj, false, NULL,
+        		def =3D find_symdef(r_symndx, obj, &defobj, flags, NULL,
 	    			lockstate);
 			if (def =3D=3D NULL)
 				return -1;
@@ -509,7 +510,7 @@
 			Elf_Addr old =3D load_ptr(where, rlen);
 			Elf_Addr val =3D old;
=20
-        		def =3D find_symdef(r_symndx, obj, &defobj, false, NULL,
+        		def =3D find_symdef(r_symndx, obj, &defobj, flags, NULL,
 	    			lockstate);
=20
 			if (def =3D=3D NULL)
@@ -577,7 +578,7 @@
  * LD_BIND_NOW was set - force relocation for all jump slots
  */
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
 	/* Do nothing */
 	obj->jmpslots_done =3D true;
@@ -594,7 +595,8 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags,
+    struct Struct_RtldLockState *lockstate)
 {
=20
 	/* XXX not implemented */
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/mips/rtld_start.S
--- a/head/libexec/rtld-elf/mips/rtld_start.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/mips/rtld_start.S	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/mips/rtld_start.S 232893 2012-03-12 20:=
59:18Z gonzo $
+ * $FreeBSD: head/libexec/rtld-elf/mips/rtld_start.S 233378 2012-03-23 17:=
54:06Z gonzo $
  */
=20
 #include <machine/asm.h>
@@ -80,7 +80,8 @@
 	move	a0, s0			/* stack pointer */
 	move	t9, v0
 	PTR_SUBU sp, 4*SZREG		/* ABI requires to reserve memory for 4 regs */
-	jr	t9			/* _start(sp, cleanup, obj); */
+	move	ra,t9			/* RA =3D=3D PC signals backtrace routine to stop */
+	j	t9			/* _start(sp, cleanup, obj); */
 	move	a3, s3			/* restore ps_strings */
 END(rtld_start)
=20
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/powerpc/reloc.c
--- a/head/libexec/rtld-elf/powerpc/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/powerpc/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/powerpc/reloc.c 228646 2011-12-17 16:20=
:27Z nwhitehorn $
+ * $FreeBSD: head/libexec/rtld-elf/powerpc/reloc.c 233231 2012-03-20 13:20=
:49Z kib $
  */
=20
 #include <sys/param.h>
@@ -92,6 +92,7 @@
 		size =3D dstsym->st_size;
 		symlook_init(&req, name);
 		req.ventry =3D fetch_ventry(dstobj, ELF_R_SYM(rela->r_info));
+		req.flags =3D SYMLOOK_EARLY;
=20
 		for (srcobj =3D dstobj->next;  srcobj !=3D NULL;
 		     srcobj =3D srcobj->next) {
@@ -159,7 +160,7 @@
  */
 static int
 reloc_nonplt_object(Obj_Entry *obj_rtld, Obj_Entry *obj, const Elf_Rela *r=
ela,
-    SymCache *cache, RtldLockState *lockstate)
+    SymCache *cache, int flags, RtldLockState *lockstate)
 {
 	Elf_Addr        *where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
 	const Elf_Sym   *def;
@@ -174,7 +175,7 @@
         case R_PPC_ADDR32:    /* word32 S + A */
         case R_PPC_GLOB_DAT:  /* word32 S + A */
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL) {
 			return (-1);
 		}
@@ -221,7 +222,7 @@
=20
 	case R_PPC_DTPMOD32:
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
=20
 		if (def =3D=3D NULL)
 			return (-1);
@@ -232,7 +233,7 @@
=20
 	case R_PPC_TPREL32:
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
=20
 		if (def =3D=3D NULL)
 			return (-1);
@@ -261,7 +262,7 @@
 	=09
 	case R_PPC_DTPREL32:
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
=20
 		if (def =3D=3D NULL)
 			return (-1);
@@ -285,7 +286,8 @@
  * Process non-PLT relocations
  */
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rela *relalim;
 	const Elf_Rela *rela;
@@ -309,8 +311,8 @@
 	 */
 	relalim =3D (const Elf_Rela *)((caddr_t)obj->rela + obj->relasize);
 	for (rela =3D obj->rela; rela < relalim; rela++) {
-		if (reloc_nonplt_object(obj_rtld, obj, rela, cache, lockstate)
-		    < 0)
+		if (reloc_nonplt_object(obj_rtld, obj, rela, cache, flags,
+		    lockstate) < 0)
 			goto done;
 	}
 	r =3D 0;
@@ -416,7 +418,7 @@
  * LD_BIND_NOW was set - force relocation for all jump slots
  */
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
 	const Obj_Entry *defobj;
 	const Elf_Rela *relalim;
@@ -430,7 +432,7 @@
 		assert(ELF_R_TYPE(rela->r_info) =3D=3D R_PPC_JMP_SLOT);
 		where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    true, NULL, lockstate);
+		    SYMLOOK_IN_PLT | flags, NULL, lockstate);
 		if (def =3D=3D NULL) {
 			dbg("reloc_jmpslots: sym not found");
 			return (-1);
@@ -525,7 +527,8 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags,
+    struct Struct_RtldLockState *lockstate)
 {
=20
 	/* XXX not implemented */
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/powerpc64/reloc.c
--- a/head/libexec/rtld-elf/powerpc64/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/powerpc64/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/powerpc64/reloc.c 228646 2011-12-17 16:=
20:27Z nwhitehorn $
+ * $FreeBSD: head/libexec/rtld-elf/powerpc64/reloc.c 233307 2012-03-22 14:=
20:51Z kib $
  */
=20
 #include <sys/param.h>
@@ -86,6 +86,7 @@
 		size =3D dstsym->st_size;
 		symlook_init(&req, name);
 		req.ventry =3D fetch_ventry(dstobj, ELF_R_SYM(rela->r_info));
+		req.flags =3D SYMLOOK_EARLY;
=20
 		for (srcobj =3D dstobj->next;  srcobj !=3D NULL;
 		     srcobj =3D srcobj->next) {
@@ -153,7 +154,7 @@
  */
 static int
 reloc_nonplt_object(Obj_Entry *obj_rtld, Obj_Entry *obj, const Elf_Rela *r=
ela,
-    SymCache *cache, RtldLockState *lockstate)
+    SymCache *cache, int flags, RtldLockState *lockstate)
 {
 	Elf_Addr        *where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
 	const Elf_Sym   *def;
@@ -169,7 +170,7 @@
         case R_PPC64_ADDR64:
         case R_PPC_GLOB_DAT:
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL) {
 			return (-1);
 		}
@@ -216,7 +217,7 @@
=20
 	case R_PPC64_DTPMOD64:
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
=20
 		if (def =3D=3D NULL)
 			return (-1);
@@ -227,7 +228,7 @@
=20
 	case R_PPC64_TPREL64:
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
=20
 		if (def =3D=3D NULL)
 			return (-1);
@@ -256,7 +257,7 @@
 	=09
 	case R_PPC64_DTPREL64:
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
=20
 		if (def =3D=3D NULL)
 			return (-1);
@@ -280,7 +281,8 @@
  * Process non-PLT relocations
  */
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rela *relalim;
 	const Elf_Rela *rela;
@@ -307,8 +309,8 @@
 	 */
 	relalim =3D (const Elf_Rela *)((caddr_t)obj->rela + obj->relasize);
 	for (rela =3D obj->rela; rela < relalim; rela++) {
-		if (reloc_nonplt_object(obj_rtld, obj, rela, cache, lockstate)
-		    < 0)
+		if (reloc_nonplt_object(obj_rtld, obj, rela, cache, flags,
+		    lockstate) < 0)
 			goto done;
 	}
 	r =3D 0;
@@ -336,7 +338,7 @@
 	reloff =3D rela - obj->pltrela;
=20
 	if (obj->priv =3D=3D NULL)
-		obj->priv =3D malloc(obj->pltrelasize);
+		obj->priv =3D xmalloc(obj->pltrelasize);
 	glink =3D obj->priv + reloff*sizeof(Elf_Addr)*2;
=20
 	dbg(" reloc_plt_object: where=3D%p,reloff=3D%lx,glink=3D%p", (void *)wher=
e, reloff, glink);
@@ -379,7 +381,7 @@
  * LD_BIND_NOW was set - force relocation for all jump slots
  */
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
 	const Obj_Entry *defobj;
 	const Elf_Rela *relalim;
@@ -393,7 +395,7 @@
 		assert(ELF_R_TYPE(rela->r_info) =3D=3D R_PPC_JMP_SLOT);
 		where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    true, NULL, lockstate);
+		    SYMLOOK_IN_PLT | flags, NULL, lockstate);
 		if (def =3D=3D NULL) {
 			dbg("reloc_jmpslots: sym not found");
 			return (-1);
@@ -468,7 +470,8 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags,
+    struct Struct_RtldLockState *lockstate)
 {
=20
 	/* XXX not implemented */
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/rtld.c
--- a/head/libexec/rtld-elf/rtld.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/rtld.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/rtld.c 232974 2012-03-14 15:39:59Z kib $
+ * $FreeBSD: head/libexec/rtld-elf/rtld.c 234170 2012-04-12 10:32:22Z kib $
  */
=20
 /*
@@ -85,7 +85,7 @@
 static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *=
);
 static Obj_Entry *dlcheck(void *);
 static Obj_Entry *dlopen_object(const char *name, int fd, Obj_Entry *refob=
j,
-    int lo_flags, int mode);
+    int lo_flags, int mode, RtldLockState *lockstate);
 static Obj_Entry *do_load_object(int, const char *, char *, struct stat *,=
 int);
 static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *);
 static bool donelist_check(DoneList *, const Obj_Entry *);
@@ -116,9 +116,10 @@
 static void objlist_push_tail(Objlist *, Obj_Entry *);
 static void objlist_remove(Objlist *, Obj_Entry *);
 static void *path_enumerate(const char *, path_enum_proc, void *);
-static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, RtldLockState =
*);
+static int relocate_objects(Obj_Entry *, bool, Obj_Entry *, int,
+    RtldLockState *);
 static int resolve_objects_ifunc(Obj_Entry *first, bool bind_now,
-    RtldLockState *lockstate);
+    int flags, RtldLockState *lockstate);
 static int rtld_dirname(const char *, char *);
 static int rtld_dirname_abs(const char *, char *);
 static void *rtld_dlopen(const char *name, int fd, int mode);
@@ -350,7 +351,8 @@
     main_argc =3D argc;
     main_argv =3D argv;
=20
-    if (aux_info[AT_CANARY]->a_un.a_ptr !=3D NULL) {
+    if (aux_info[AT_CANARY] !=3D NULL &&
+	aux_info[AT_CANARY]->a_un.a_ptr !=3D NULL) {
 	    i =3D aux_info[AT_CANARYLEN]->a_un.a_val;
 	    if (i > sizeof(__stack_chk_guard))
 		    i =3D sizeof(__stack_chk_guard);
@@ -545,7 +547,8 @@
     }
=20
     if (relocate_objects(obj_main,
-      ld_bind_now !=3D NULL && *ld_bind_now !=3D '\0', &obj_rtld, NULL) =
=3D=3D -1)
+      ld_bind_now !=3D NULL && *ld_bind_now !=3D '\0',
+      &obj_rtld, SYMLOOK_EARLY, NULL) =3D=3D -1)
 	die();
=20
     dbg("doing copy relocations");
@@ -580,7 +583,8 @@
=20
     dbg("resolving ifuncs");
     if (resolve_objects_ifunc(obj_main,
-      ld_bind_now !=3D NULL && *ld_bind_now !=3D '\0', NULL) =3D=3D -1)
+      ld_bind_now !=3D NULL && *ld_bind_now !=3D '\0', SYMLOOK_EARLY,
+      NULL) =3D=3D -1)
 	die();
=20
     if (!obj_main->crt_no_init) {
@@ -1552,7 +1556,7 @@
 	 * that symbols can be found.
 	 */
=20
-	relocate_objects(&objtmp, true, &objtmp, NULL);
+	relocate_objects(&objtmp, true, &objtmp, 0, NULL);
     }
=20
     /* Initialize the object list. */
@@ -1605,6 +1609,7 @@
 static void
 initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list)
 {
+
     if (obj->init_scanned || obj->init_done)
 	return;
     obj->init_scanned =3D true;
@@ -1616,6 +1621,10 @@
     /* Recursively process the needed objects. */
     if (obj->needed !=3D NULL)
 	initlist_add_neededs(obj->needed, list);
+    if (obj->needed_filtees !=3D NULL)
+	initlist_add_neededs(obj->needed_filtees, list);
+    if (obj->needed_aux_filtees !=3D NULL)
+	initlist_add_neededs(obj->needed_aux_filtees, list);
=20
     /* Add the object to the init list. */
     if (obj->preinit_array !=3D (Elf_Addr)NULL || obj->init !=3D (Elf_Addr=
)NULL ||
@@ -1663,13 +1672,14 @@
 }
=20
 static void
-load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags)
+load_filtee1(Obj_Entry *obj, Needed_Entry *needed, int flags,
+    RtldLockState *lockstate)
 {
=20
     for (; needed !=3D NULL; needed =3D needed->next) {
 	needed->obj =3D dlopen_object(obj->strtab + needed->name, -1, obj,
 	  flags, ((ld_loadfltr || obj->z_loadfltr) ? RTLD_NOW : RTLD_LAZY) |
-	  RTLD_LOCAL);
+	  RTLD_LOCAL, lockstate);
     }
 }
=20
@@ -1679,8 +1689,8 @@
=20
     lock_restart_for_upgrade(lockstate);
     if (!obj->filtees_loaded) {
-	load_filtee1(obj, obj->needed_filtees, flags);
-	load_filtee1(obj, obj->needed_aux_filtees, flags);
+	load_filtee1(obj, obj->needed_filtees, flags, lockstate);
+	load_filtee1(obj, obj->needed_aux_filtees, flags, lockstate);
 	obj->filtees_loaded =3D true;
     }
 }
@@ -2144,13 +2154,17 @@
  */
 static int
 relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj,
-    RtldLockState *lockstate)
+    int flags, RtldLockState *lockstate)
 {
     Obj_Entry *obj;
=20
     for (obj =3D first;  obj !=3D NULL;  obj =3D obj->next) {
+	if (obj->relocated)
+	    continue;
+	obj->relocated =3D true;
 	if (obj !=3D rtldobj)
 	    dbg("relocating \"%s\"", obj->path);
+
 	if (obj->nbuckets =3D=3D 0 || obj->nchains =3D=3D 0 || obj->buckets =3D=
=3D NULL ||
 	    obj->symtab =3D=3D NULL || obj->strtab =3D=3D NULL) {
 	    _rtld_error("%s: Shared object has no run-time symbol table",
@@ -2169,7 +2183,7 @@
 	}
=20
 	/* Process the non-PLT relocations. */
-	if (reloc_non_plt(obj, rtldobj, lockstate))
+	if (reloc_non_plt(obj, rtldobj, flags, lockstate))
 		return -1;
=20
 	if (obj->textrel) {	/* Re-protected the text segment. */
@@ -2190,7 +2204,7 @@
 	    return -1;
 	/* Relocate the jump slots if we are doing immediate binding. */
 	if (obj->bind_now || bind_now)
-	    if (reloc_jmpslots(obj, lockstate) =3D=3D -1)
+	    if (reloc_jmpslots(obj, flags, lockstate) =3D=3D -1)
 		return -1;
=20
 	if (obj->relro_size > 0) {
@@ -2225,35 +2239,39 @@
  * consistent with how GNU does it.
  */
 static int
-resolve_object_ifunc(Obj_Entry *obj, bool bind_now, RtldLockState *locksta=
te)
+resolve_object_ifunc(Obj_Entry *obj, bool bind_now, int flags,
+    RtldLockState *lockstate)
 {
 	if (obj->irelative && reloc_iresolve(obj, lockstate) =3D=3D -1)
 		return (-1);
 	if ((obj->bind_now || bind_now) && obj->gnu_ifunc &&
-	    reloc_gnu_ifunc(obj, lockstate) =3D=3D -1)
+	    reloc_gnu_ifunc(obj, flags, lockstate) =3D=3D -1)
 		return (-1);
 	return (0);
 }
=20
 static int
-resolve_objects_ifunc(Obj_Entry *first, bool bind_now, RtldLockState *lock=
state)
+resolve_objects_ifunc(Obj_Entry *first, bool bind_now, int flags,
+    RtldLockState *lockstate)
 {
 	Obj_Entry *obj;
=20
 	for (obj =3D first;  obj !=3D NULL;  obj =3D obj->next) {
-		if (resolve_object_ifunc(obj, bind_now, lockstate) =3D=3D -1)
+		if (resolve_object_ifunc(obj, bind_now, flags, lockstate) =3D=3D -1)
 			return (-1);
 	}
 	return (0);
 }
=20
 static int
-initlist_objects_ifunc(Objlist *list, bool bind_now, RtldLockState *lockst=
ate)
+initlist_objects_ifunc(Objlist *list, bool bind_now, int flags,
+    RtldLockState *lockstate)
 {
 	Objlist_Entry *elm;
=20
 	STAILQ_FOREACH(elm, list, link) {
-		if (resolve_object_ifunc(elm->obj, bind_now, lockstate) =3D=3D -1)
+		if (resolve_object_ifunc(elm->obj, bind_now, flags,
+		    lockstate) =3D=3D -1)
 			return (-1);
 	}
 	return (0);
@@ -2472,7 +2490,7 @@
 	    lo_flags |=3D RTLD_LO_TRACE;
=20
     return (dlopen_object(name, fd, obj_main, lo_flags,
-      mode & (RTLD_MODEMASK | RTLD_GLOBAL)));
+      mode & (RTLD_MODEMASK | RTLD_GLOBAL), NULL));
 }
=20
 static void
@@ -2487,17 +2505,20 @@
=20
 static Obj_Entry *
 dlopen_object(const char *name, int fd, Obj_Entry *refobj, int lo_flags,
-    int mode)
+    int mode, RtldLockState *lockstate)
 {
     Obj_Entry **old_obj_tail;
     Obj_Entry *obj;
     Objlist initlist;
-    RtldLockState lockstate;
+    RtldLockState mlockstate;
     int result;
=20
     objlist_init(&initlist);
=20
-    wlock_acquire(rtld_bind_lock, &lockstate);
+    if (lockstate =3D=3D NULL && !(lo_flags & RTLD_LO_EARLY)) {
+	wlock_acquire(rtld_bind_lock, &mlockstate);
+	lockstate =3D &mlockstate;
+    }
     GDB_STATE(RT_ADD,NULL);
=20
     old_obj_tail =3D obj_tail;
@@ -2515,17 +2536,30 @@
 	    objlist_push_tail(&list_global, obj);
 	if (*old_obj_tail !=3D NULL) {		/* We loaded something new. */
 	    assert(*old_obj_tail =3D=3D obj);
-	    result =3D load_needed_objects(obj, lo_flags & RTLD_LO_DLOPEN);
+	    result =3D load_needed_objects(obj,
+		lo_flags & (RTLD_LO_DLOPEN | RTLD_LO_EARLY));
 	    init_dag(obj);
 	    ref_dag(obj);
 	    if (result !=3D -1)
 		result =3D rtld_verify_versions(&obj->dagmembers);
 	    if (result !=3D -1 && ld_tracing)
 		goto trace;
-	    if (result =3D=3D -1 || (relocate_objects(obj, (mode & RTLD_MODEMASK)
-	      =3D=3D RTLD_NOW, &obj_rtld, &lockstate)) =3D=3D -1) {
+	    if (result =3D=3D -1 || (relocate_objects(obj,
+	     (mode & RTLD_MODEMASK) =3D=3D RTLD_NOW, &obj_rtld,
+	      (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
+	      lockstate)) =3D=3D -1) {
 		dlopen_cleanup(obj);
 		obj =3D NULL;
+	    } else if (lo_flags & RTLD_LO_EARLY) {
+		/*
+		 * Do not call the init functions for early loaded
+		 * filtees.  The image is still not initialized enough
+		 * for them to work.
+		 *
+		 * Our object is found by the global object list and
+		 * will be ordered among all init calls done right
+		 * before transferring control to main.
+		 */
 	    } else {
 		/* Make list of init functions to call. */
 		initlist_add_objects(obj, &obj->next, &initlist);
@@ -2556,24 +2590,32 @@
 	name);
     GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL);
=20
-    map_stacks_exec(&lockstate);
+    if (!(lo_flags & RTLD_LO_EARLY)) {
+	map_stacks_exec(lockstate);
+    }
=20
     if (initlist_objects_ifunc(&initlist, (mode & RTLD_MODEMASK) =3D=3D RT=
LD_NOW,
-      &lockstate) =3D=3D -1) {
+      (lo_flags & RTLD_LO_EARLY) ? SYMLOOK_EARLY : 0,
+      lockstate) =3D=3D -1) {
 	objlist_clear(&initlist);
 	dlopen_cleanup(obj);
-	lock_release(rtld_bind_lock, &lockstate);
+	if (lockstate =3D=3D &mlockstate)
+	    lock_release(rtld_bind_lock, lockstate);
 	return (NULL);
     }
=20
-    /* Call the init functions. */
-    objlist_call_init(&initlist, &lockstate);
+    if (!(lo_flags & RTLD_LO_EARLY)) {
+	/* Call the init functions. */
+	objlist_call_init(&initlist, lockstate);
+    }
     objlist_clear(&initlist);
-    lock_release(rtld_bind_lock, &lockstate);
+    if (lockstate =3D=3D &mlockstate)
+	lock_release(rtld_bind_lock, lockstate);
     return obj;
 trace:
     trace_loaded_objects(obj);
-    lock_release(rtld_bind_lock, &lockstate);
+    if (lockstate =3D=3D &mlockstate)
+	lock_release(rtld_bind_lock, lockstate);
     exit(0);
 }
=20
@@ -2586,6 +2628,9 @@
     const Elf_Sym *def;
     SymLook req;
     RtldLockState lockstate;
+#ifndef __ia64__
+    tls_index ti;
+#endif
     int res;
=20
     def =3D NULL;
@@ -2700,7 +2745,15 @@
 	    return (make_function_pointer(def, defobj));
 	else if (ELF_ST_TYPE(def->st_info) =3D=3D STT_GNU_IFUNC)
 	    return (rtld_resolve_ifunc(defobj, def));
-	else
+	else if (ELF_ST_TYPE(def->st_info) =3D=3D STT_TLS) {
+#ifdef __ia64__
+	    return (__tls_get_addr(defobj->tlsindex, def->st_value));
+#else
+	    ti.ti_module =3D defobj->tlsindex;
+	    ti.ti_offset =3D def->st_value;
+	    return (__tls_get_addr(&ti));
+#endif
+	} else
 	    return (defobj->relocbase + def->st_value);
     }
=20
@@ -3354,12 +3407,13 @@
 {
     DoneList donelist;
     SymLook req1;
-    int res, mres;
+    int flags, res, mres;
=20
     mres =3D symlook_obj1(req, obj);
     if (mres =3D=3D 0) {
 	if (obj->needed_filtees !=3D NULL) {
-	    load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
+	    flags =3D (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
+	    load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
 	    donelist_init(&donelist);
 	    symlook_init_from_req(&req1, req);
 	    res =3D symlook_needed(&req1, obj->needed_filtees, &donelist);
@@ -3370,7 +3424,8 @@
 	    return (res);
 	}
 	if (obj->needed_aux_filtees !=3D NULL) {
-	    load_filtees(__DECONST(Obj_Entry *, obj), 0, req->lockstate);
+	    flags =3D (req->flags & SYMLOOK_EARLY) ? RTLD_LO_EARLY : 0;
+	    load_filtees(__DECONST(Obj_Entry *, obj), flags, req->lockstate);
 	    donelist_init(&donelist);
 	    symlook_init_from_req(&req1, req);
 	    res =3D symlook_needed(&req1, obj->needed_aux_filtees, &donelist);
@@ -3699,7 +3754,7 @@
     /* Check dtv generation in case new modules have arrived */
     if (dtv[0] !=3D tls_dtv_generation) {
 	wlock_acquire(rtld_bind_lock, &lockstate);
-	newdtv =3D calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
+	newdtv =3D xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
 	to_copy =3D dtv[1];
 	if (to_copy > tls_max_index)
 	    to_copy =3D tls_max_index;
@@ -3754,7 +3809,7 @@
 	return (oldtcb);
=20
     assert(tcbsize >=3D TLS_TCB_SIZE);
-    tcb =3D calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
+    tcb =3D xcalloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize);
     tls =3D (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE);
=20
     if (oldtcb !=3D NULL) {
@@ -3770,7 +3825,7 @@
 	    }
 	}
     } else {
-	dtv =3D calloc(tls_max_index + 2, sizeof(Elf_Addr));
+	dtv =3D xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
 	tls[0] =3D dtv;
 	dtv[0] =3D tls_dtv_generation;
 	dtv[1] =3D tls_max_index;
@@ -3834,8 +3889,8 @@
     size =3D round(tls_static_space, tcbalign);
=20
     assert(tcbsize >=3D 2*sizeof(Elf_Addr));
-    tls =3D calloc(1, size + tcbsize);
-    dtv =3D calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr));
+    tls =3D xcalloc(1, size + tcbsize);
+    dtv =3D xcalloc(tls_max_index + 2, sizeof(Elf_Addr));
=20
     segbase =3D (Elf_Addr)(tls + size);
     ((Elf_Addr*)segbase)[0] =3D segbase;
@@ -4124,6 +4179,10 @@
     const Obj_Entry *depobj;
     int maxvernum, vernum;
=20
+    if (obj->ver_checked)
+	return (0);
+    obj->ver_checked =3D true;
+
     maxvernum =3D 0;
     /*
      * Walk over defined and required version records and figure out
@@ -4175,7 +4234,7 @@
      * way.
      */
     obj->vernum =3D maxvernum + 1;
-    obj->vertab =3D calloc(obj->vernum, sizeof(Ver_Entry));
+    obj->vertab =3D xcalloc(obj->vernum, sizeof(Ver_Entry));
=20
     vd =3D obj->verdef;
     while (vd !=3D NULL) {
@@ -4330,6 +4389,17 @@
 	return (osreldate);
 }
=20
+void
+exit(int status)
+{
+
+	_exit(status);
+}
+
+void (*__cleanup)(void);
+int __isthreaded =3D 0;
+int _thread_autoinit_dummy_decl =3D 1;
+
 /*
  * No unresolved symbols for rtld.
  */
@@ -4345,6 +4415,7 @@
 	_rtld_error("stack overflow detected; terminated");
 	die();
 }
+__weak_reference(__stack_chk_fail, __stack_chk_fail_local);
=20
 void
 __chk_fail(void)
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/rtld.h
--- a/head/libexec/rtld-elf/rtld.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/rtld.h	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/rtld.h 232974 2012-03-14 15:39:59Z kib $
+ * $FreeBSD: head/libexec/rtld-elf/rtld.h 233546 2012-03-27 14:10:15Z kib $
  */
=20
 #ifndef RTLD_H /* { */
@@ -58,7 +58,7 @@
 #endif
=20
 #define NEW(type)	((type *) xmalloc(sizeof(type)))
-#define CNEW(type)	((type *) xcalloc(sizeof(type)))
+#define CNEW(type)	((type *) xcalloc(1, sizeof(type)))
=20
 /* We might as well do booleans like C++. */
 typedef unsigned char bool;
@@ -229,6 +229,8 @@
=20
     bool mainprog : 1;		/* True if this is the main program */
     bool rtld : 1;		/* True if this is the dynamic linker */
+    bool relocated : 1;		/* True if processed by relocate_objects() */
+    bool ver_checked : 1;	/* True if processed by rtld_verify_object_versi=
ons */
     bool textrel : 1;		/* True if there are relocations to text seg */
     bool symbolic : 1;		/* True if generated with "-Bsymbolic" */
     bool bind_now : 1;		/* True if all relocations should be made first */
@@ -267,6 +269,7 @@
 #define SYMLOOK_IN_PLT	0x01	/* Lookup for PLT symbol */
 #define SYMLOOK_DLSYM	0x02	/* Return newest versioned symbol. Used by
 				   dlsym. */
+#define	SYMLOOK_EARLY	0x04	/* Symlook is done during initialization. */
=20
 /* Flags for load_object(). */
 #define	RTLD_LO_NOLOAD	0x01	/* dlopen() specified RTLD_NOLOAD. */
@@ -274,6 +277,8 @@
 #define	RTLD_LO_TRACE	0x04	/* Only tracing. */
 #define	RTLD_LO_NODELETE 0x08	/* Loaded object cannot be closed. */
 #define	RTLD_LO_FILTEES 0x10	/* Loading filtee. */
+#define	RTLD_LO_EARLY	0x20	/* Do not call ctors, postpone it to the
+				   initialization during the image start. */
=20
 /*
  * Symbol cache entry used during relocation to avoid multiple lookups
@@ -312,19 +317,19 @@
     struct Struct_RtldLockState *lockstate;
 } SymLook;
=20
-extern void _rtld_error(const char *, ...) __printflike(1, 2);
-extern const char *rtld_strerror(int);
-extern Obj_Entry *map_object(int, const char *, const struct stat *);
-extern void *xcalloc(size_t);
-extern void *xmalloc(size_t);
-extern char *xstrdup(const char *);
+void _rtld_error(const char *, ...) __printflike(1, 2);
+const char *rtld_strerror(int);
+Obj_Entry *map_object(int, const char *, const struct stat *);
+void *xcalloc(size_t, size_t);
+void *xmalloc(size_t);
+char *xstrdup(const char *);
 extern Elf_Addr _GLOBAL_OFFSET_TABLE_[];
 extern Elf_Sym sym_zero;	/* For resolving undefined weak refs. */
=20
-extern void dump_relocations (Obj_Entry *);
-extern void dump_obj_relocations (Obj_Entry *);
-extern void dump_Elf_Rel (Obj_Entry *, const Elf_Rel *, u_long);
-extern void dump_Elf_Rela (Obj_Entry *, const Elf_Rela *, u_long);
+void dump_relocations(Obj_Entry *);
+void dump_obj_relocations(Obj_Entry *);
+void dump_Elf_Rel(Obj_Entry *, const Elf_Rel *, u_long);
+void dump_Elf_Rela(Obj_Entry *, const Elf_Rela *, u_long);
=20
 /*
  * Function declarations.
@@ -353,11 +358,12 @@
  * MD function declarations.
  */
 int do_copy_relocations(Obj_Entry *);
-int reloc_non_plt(Obj_Entry *, Obj_Entry *, struct Struct_RtldLockState *);
+int reloc_non_plt(Obj_Entry *, Obj_Entry *, int flags,
+    struct Struct_RtldLockState *);
 int reloc_plt(Obj_Entry *);
-int reloc_jmpslots(Obj_Entry *, struct Struct_RtldLockState *);
+int reloc_jmpslots(Obj_Entry *, int flags, struct Struct_RtldLockState *);
 int reloc_iresolve(Obj_Entry *, struct Struct_RtldLockState *);
-int reloc_gnu_ifunc(Obj_Entry *, struct Struct_RtldLockState *);
+int reloc_gnu_ifunc(Obj_Entry *, int flags, struct Struct_RtldLockState *);
 void allocate_initial_tls(Obj_Entry *);
=20
 #endif /* } */
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/sparc64/reloc.c
--- a/head/libexec/rtld-elf/sparc64/reloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/sparc64/reloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/libexec/rtld-elf/sparc64/reloc.c 229780 2012-01-0=
7 16:09:54Z uqs $");
+__FBSDID("$FreeBSD: head/libexec/rtld-elf/sparc64/reloc.c 233231 2012-03-2=
0 13:20:49Z kib $");
=20
 #include <sys/param.h>
 #include <sys/mman.h>
@@ -231,7 +231,7 @@
 	__asm __volatile("flush %0 + %1" : : "r" (va), "I" (offs));
=20
 static int reloc_nonplt_object(Obj_Entry *obj, const Elf_Rela *rela,
-    SymCache *cache, RtldLockState *lockstate);
+    SymCache *cache, int flags, RtldLockState *lockstate);
 static void install_plt(Elf_Word *pltgot, Elf_Addr proc);
=20
 extern char _rtld_bind_start_0[];
@@ -264,6 +264,7 @@
 			symlook_init(&req, name);
 			req.ventry =3D fetch_ventry(dstobj,
 			    ELF_R_SYM(rela->r_info));
+			req.flags =3D SYMLOOK_EARLY;
=20
 			for (srcobj =3D dstobj->next; srcobj !=3D NULL;
 			    srcobj =3D srcobj->next) {
@@ -291,7 +292,8 @@
 }
=20
 int
-reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, RtldLockState *lockstat=
e)
+reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags,
+    RtldLockState *lockstate)
 {
 	const Elf_Rela *relalim;
 	const Elf_Rela *rela;
@@ -310,7 +312,7 @@
=20
 	relalim =3D (const Elf_Rela *)((caddr_t)obj->rela + obj->relasize);
 	for (rela =3D obj->rela; rela < relalim; rela++) {
-		if (reloc_nonplt_object(obj, rela, cache, lockstate) < 0)
+		if (reloc_nonplt_object(obj, rela, cache, flags, lockstate) < 0)
 			goto done;
 	}
 	r =3D 0;
@@ -322,7 +324,7 @@
=20
 static int
 reloc_nonplt_object(Obj_Entry *obj, const Elf_Rela *rela, SymCache *cache,
-    RtldLockState *lockstate)
+    int flags, RtldLockState *lockstate)
 {
 	const Obj_Entry *defobj;
 	const Elf_Sym *def;
@@ -385,7 +387,7 @@
 	if (RELOC_RESOLVE_SYMBOL(type)) {
 		/* Find the symbol. */
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    false, cache, lockstate);
+		    flags, cache, lockstate);
 		if (def =3D=3D NULL)
 			return (-1);
=20
@@ -526,7 +528,7 @@
 #define	LOVAL(v)	((v) & 0x000003ff)
=20
 int
-reloc_jmpslots(Obj_Entry *obj, RtldLockState *lockstate)
+reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate)
 {
 	const Obj_Entry *defobj;
 	const Elf_Rela *relalim;
@@ -540,7 +542,7 @@
 		assert(ELF64_R_TYPE_ID(rela->r_info) =3D=3D R_SPARC_JMP_SLOT);
 		where =3D (Elf_Addr *)(obj->relocbase + rela->r_offset);
 		def =3D find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj,
-		    true, NULL, lockstate);
+		    SYMLOOK_IN_PLT | flags, NULL, lockstate);
 		if (def =3D=3D NULL)
 			return -1;
 		target =3D (Elf_Addr)(defobj->relocbase + def->st_value);
@@ -559,7 +561,8 @@
 }
=20
 int
-reloc_gnu_ifunc(Obj_Entry *obj, struct Struct_RtldLockState *lockstate)
+reloc_gnu_ifunc(Obj_Entry *obj, int flags,
+    struct Struct_RtldLockState *lockstate)
 {
=20
 	/* XXX not implemented */
diff -r 428842767fa6 -r f2935497fa04 head/libexec/rtld-elf/xmalloc.c
--- a/head/libexec/rtld-elf/xmalloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/rtld-elf/xmalloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/libexec/rtld-elf/xmalloc.c 225152 2011-08-24 20:05:13Z k=
ib $
+ * $FreeBSD: head/libexec/rtld-elf/xmalloc.c 233357 2012-03-23 12:04:44Z k=
ib $
  */
=20
 #include <stddef.h>
@@ -32,14 +32,17 @@
 #include "rtld.h"
 #include "rtld_printf.h"
=20
-void *xcalloc(size_t);
-void *xmalloc(size_t);
-char *xstrdup(const char *);
+void *
+xcalloc(size_t number, size_t size)
+{
+	void *p;
=20
-void *
-xcalloc(size_t size)
-{
-    return memset(xmalloc(size), 0, size);
+	p =3D calloc(number, size);
+	if (p =3D=3D NULL) {
+		rtld_fdputstr(STDERR_FILENO, "Out of memory\n");
+		_exit(1);
+	}
+	return (p);
 }
=20
 void *
@@ -54,12 +57,13 @@
 }
=20
 char *
-xstrdup(const char *s)
+xstrdup(const char *str)
 {
-    char *p =3D strdup(s);
-    if (p =3D=3D NULL) {
-	 rtld_fdputstr(STDERR_FILENO, "Out of memory\n");
-	 _exit(1);
-    }
-    return p;
+	char *copy;
+	size_t len;
+
+	len =3D strlen(str) + 1;
+	copy =3D xmalloc(len);
+	memcpy(copy, str, len);
+	return (copy);
 }
diff -r 428842767fa6 -r f2935497fa04 head/libexec/tftpd/tftpd.8
--- a/head/libexec/tftpd/tftpd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/libexec/tftpd/tftpd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)tftpd.8	8.1 (Berkeley) 6/4/93
-.\" $FreeBSD: head/libexec/tftpd/tftpd.8 224537 2011-07-31 03:18:36Z rodri=
gc $
+.\" $FreeBSD: head/libexec/tftpd/tftpd.8 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd June 22, 2011
 .Dt TFTPD 8
@@ -161,9 +161,9 @@
 .Pp
 If
 .Ar value
-is specified, then the debug level is set to=20
+is specified, then the debug level is set to
 .Ar value .
-The debug level is a bitmask implemented in=20
+The debug level is a bitmask implemented in
 .Pa src/libexec/tftpd/tftp-utils.h .
 Valid values are 0 (DEBUG_NONE), 1 (DEBUG_PACKETS), 2, (DEBUG_SIMPLE),
 4 (DEBUG_OPTIONS), and 8 (DEBUG_ACCESS).  Multiple debug values can be com=
bined
@@ -262,7 +262,7 @@
 .Rs
 .%T Extending TFTP
 .%U http://www.compuphase.com/tftp.htm
-.Re=20
+.Re
 .Sh HISTORY
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/sbin/bsdlabel/bsdlabel.c
--- a/head/sbin/bsdlabel/bsdlabel.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/bsdlabel/bsdlabel.c	Tue Apr 17 11:51:51 2012 +0300
@@ -53,7 +53,7 @@
 #endif /* not lint */
 #endif
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/bsdlabel/bsdlabel.c 229778 2012-01-07 16:09:=
33Z uqs $");
+__FBSDID("$FreeBSD: head/sbin/bsdlabel/bsdlabel.c 234122 2012-04-11 06:35:=
13Z ae $");
=20
 #include <sys/param.h>
 #include <stdint.h>
@@ -1194,7 +1194,8 @@
 			lp->d_interleave =3D vl->d_interleave;
 		if (lp->d_secpercyl =3D=3D 0)
 			lp->d_secpercyl =3D vl->d_secpercyl;
-		if (lp->d_secperunit =3D=3D 0)
+		if (lp->d_secperunit =3D=3D 0 ||
+		    lp->d_secperunit > vl->d_secperunit)
 			lp->d_secperunit =3D vl->d_secperunit;
 		if (lp->d_bbsize =3D=3D 0)
 			lp->d_bbsize =3D vl->d_bbsize;
diff -r 428842767fa6 -r f2935497fa04 head/sbin/camcontrol/camcontrol.8
--- a/head/sbin/camcontrol/camcontrol.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/camcontrol/camcontrol.8	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/camcontrol/camcontrol.8 227961 2011-11-25 04:03:37=
Z emaste $
+.\" $FreeBSD: head/sbin/camcontrol/camcontrol.8 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd November 24, 2011
 .Dt CAMCONTROL 8
@@ -599,7 +599,7 @@
 11 result registers will be written to standard output in hex.
 .El
 .It Ic smpcmd
-Allows the user to send an arbitrary Serial=20
+Allows the user to send an arbitrary Serial
 Management Protocol (SMP) command to a device.
 The
 .Ic smpcmd
@@ -660,7 +660,7 @@
 .Bl -tag -width 17n
 .It Fl p Ar phy
 Specify the PHY to operate on.
-This argument is required.=20
+This argument is required.
 .It Fl l
 Request the long request/response format.
 Not all SMP targets support the long response format.
@@ -1228,7 +1228,6 @@
 Negotiate a sync rate of 20MHz and an offset of 15 with da3.
 Then send a
 Test Unit Ready command to make the settings take effect.
-.Pp
 .Bd -literal -offset indent
 camcontrol smpcmd ses0 -v -r 4 "40 0 00 0" -R 1020 "s9 i1"
 .Ed
diff -r 428842767fa6 -r f2935497fa04 head/sbin/devfs/devfs.8
--- a/head/sbin/devfs/devfs.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/devfs/devfs.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/devfs/devfs.8 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd February 21, 2010
 .Dt DEVFS 8
@@ -247,8 +247,8 @@
 Local
 .Nm
 configuration file.  Rulesets in here override those in
-.Pa /etc/defaults/devfs.rules=20
-with the same ruleset number, otherwise the two files are effectively merg=
ed.=20
+.Pa /etc/defaults/devfs.rules
+with the same ruleset number, otherwise the two files are effectively merg=
ed.
 .It Pa /etc/devfs.conf
 Boot-time
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/sbin/fdisk/fdisk.c
--- a/head/sbin/fdisk/fdisk.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/fdisk/fdisk.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/fdisk/fdisk.c 227295 2011-11-07 07:50:35Z ae=
 $");
+__FBSDID("$FreeBSD: head/sbin/fdisk/fdisk.c 234345 2012-04-16 17:30:19Z ma=
rck $");
=20
 #include <sys/disk.h>
 #include <sys/disklabel.h>
@@ -218,6 +218,7 @@
 	[0xF1] =3D "SpeedStor",
 	[0xF2] =3D "DOS 3.3+ Secondary",
 	[0xF4] =3D "SpeedStor large partition",
+	[0xFB] =3D "VMware VMFS",
 	[0xFE] =3D "SpeedStor >1024 cyl. or LANstep",
 	[0xFF] =3D "Xenix bad blocks table",
 };
diff -r 428842767fa6 -r f2935497fa04 head/sbin/geom/class/eli/geli.8
--- a/head/sbin/geom/class/eli/geli.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/geom/class/eli/geli.8	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/geom/class/eli/geli.8 232502 2012-03-04 16:37:44Z =
eadler $
+.\" $FreeBSD: head/sbin/geom/class/eli/geli.8 233458 2012-03-25 09:21:09Z =
joel $
 .\"
 .Dd March 4, 2012
 .Dt GELI 8
@@ -946,7 +946,6 @@
 Highest
 .Nm GELI
 metadata version supported by the given FreeBSD version:
-.Pp
 .Bl -column -offset indent ".Sy FreeBSD" ".Sy version"
 .It Sy FreeBSD Ta Sy GELI
 .It Sy version Ta Sy version
@@ -969,6 +968,5 @@
 .Pp
 .It Li 9.0 Ta 6
 .El
-.Pp
 .Sh AUTHORS
 .An Pawel Jakub Dawidek Aq pjd at FreeBSD.org
diff -r 428842767fa6 -r f2935497fa04 head/sbin/geom/class/multipath/gmultip=
ath.8
--- a/head/sbin/geom/class/multipath/gmultipath.8	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sbin/geom/class/multipath/gmultipath.8	Tue Apr 17 11:51:51 2012 =
+0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/geom/class/multipath/gmultipath.8 227464 2011-11-1=
2 09:52:27Z mav $
+.\" $FreeBSD: head/sbin/geom/class/multipath/gmultipath.8 233458 2012-03-2=
5 09:21:09Z joel $
 .\"
 .Dd October 31, 2011
 .Dt GMULTIPATH 8
@@ -176,7 +176,6 @@
 See
 .Xr geom 8 .
 .El
-.Pp
 .Sh SYSCTL VARIABLES
 The following
 .Xr sysctl 8
@@ -196,7 +195,6 @@
 .Sh EXIT STATUS
 Exit status is 0 on success, and 1 if the command fails.
 .Sh MULTIPATH ARCHITECTURE
-.Pp
 This is a multiple path architecture with no device knowledge or
 presumptions other than size matching built in.
 Therefore the user must exercise some care
diff -r 428842767fa6 -r f2935497fa04 head/sbin/geom/class/sched/gsched.8
--- a/head/sbin/geom/class/sched/gsched.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/geom/class/sched/gsched.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/geom/class/sched/gsched.8 231992 2012-02-22 04:51:=
17Z eadler $
+.\" $FreeBSD: head/sbin/geom/class/sched/gsched.8 233458 2012-03-25 09:21:=
09Z joel $
 .\"
 .Dd August 29, 2010
 .Dt GSCHED 8
@@ -149,7 +149,6 @@
 # Remove the scheduler on the device:
 geom sched destroy -v ad0.sched.
 .Ed
-.Pp
 .Sh SEE ALSO
 .Xr geom 4 ,
 .Xr geom 8
diff -r 428842767fa6 -r f2935497fa04 head/sbin/growfs/debug.c
--- a/head/sbin/growfs/debug.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/growfs/debug.c	Tue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
=20
 #ifndef lint
 static const char rcsid[] =3D
-  "$FreeBSD: head/sbin/growfs/debug.c 232548 2012-03-05 16:37:51Z trasz $";
+  "$FreeBSD: head/sbin/growfs/debug.c 234312 2012-04-15 15:13:29Z trasz $";
 #endif /* not lint */
=20
 #include <sys/param.h>
@@ -127,9 +127,7 @@
 void
 dbg_dump_fs(struct fs *sb, const char *comment)
 {
-#ifdef FSMAXSNAP
 	int j;
-#endif /* FSMAXSNAP */
=20
 	if (!dbg_log)
 		return;
@@ -299,7 +297,6 @@
 	fprintf(dbg_log, "pendinginodes     int32_t          0x%08x\n",
 	    sb->fs_pendinginodes);
=20
-#ifdef FSMAXSNAP
 	for (j =3D 0; j < FSMAXSNAP; j++) {
 		fprintf(dbg_log, "snapinum          int32_t[%2d]      0x%08x\n",
 		    j, sb->fs_snapinum[j]);
@@ -307,7 +304,6 @@
 			break;
 		}
 	}
-#endif /* FSMAXSNAP */
 	fprintf(dbg_log, "avgfilesize       int32_t          0x%08x\n",
 	    sb->fs_avgfilesize);
 	fprintf(dbg_log, "avgfpdir          int32_t          0x%08x\n",
diff -r 428842767fa6 -r f2935497fa04 head/sbin/growfs/growfs.c
--- a/head/sbin/growfs/growfs.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/growfs/growfs.c	Tue Apr 17 11:51:51 2012 +0300
@@ -47,10 +47,9 @@
 #endif /* not lint */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/growfs/growfs.c 232858 2012-03-12 11:15:44Z =
dim $");
+__FBSDID("$FreeBSD: head/sbin/growfs/growfs.c 234314 2012-04-15 15:15:16Z =
trasz $");
=20
 #include <sys/param.h>
-#include <sys/disklabel.h>
 #include <sys/ioctl.h>
 #include <sys/stat.h>
 #include <sys/disk.h>
@@ -77,7 +76,7 @@
=20
 static union {
 	struct fs	fs;
-	char	pad[SBLOCKSIZE];
+	char		pad[SBLOCKSIZE];
 } fsun1, fsun2;
 #define	sblock	fsun1.fs	/* the new superblock */
 #define	osblock	fsun2.fs	/* the old superblock */
@@ -90,51 +89,16 @@
=20
 static union {
 	struct cg	cg;
-	char	pad[MAXBSIZE];
+	char		pad[MAXBSIZE];
 } cgun1, cgun2;
 #define	acg	cgun1.cg	/* a cylinder cgroup (new) */
 #define	aocg	cgun2.cg	/* an old cylinder group */
=20
-static char	ablk[MAXBSIZE];	/* a block */
-
 static struct csum	*fscs;	/* cylinder summary */
=20
-union dinode {
-	struct ufs1_dinode dp1;
-	struct ufs2_dinode dp2;
-};
-#define	DIP(dp, field) \
-	((sblock.fs_magic =3D=3D FS_UFS1_MAGIC) ? \
-	(uint32_t)(dp)->dp1.field : (dp)->dp2.field)
-#define	DIP_SET(dp, field, val) do { \
-	if (sblock.fs_magic =3D=3D FS_UFS1_MAGIC) \
-		(dp)->dp1.field =3D (val); \
-	else \
-		(dp)->dp2.field =3D (val); \
-	} while (0)
-static ufs2_daddr_t 	inoblk;			/* inode block address */
-static char		inobuf[MAXBSIZE];	/* inode block */
-static ino_t		maxino;			/* last valid inode */
-static int		unlabeled; /* unlabeled partition, e.g. vinum volume */
-
-/*
- * An array of elements of type struct gfs_bpp describes all blocks to
- * be relocated in order to free the space needed for the cylinder group
- * summary for all cylinder groups located in the first cylinder group.
- */
-struct gfs_bpp {
-	ufs2_daddr_t	old;		/* old block number */
-	ufs2_daddr_t	new;		/* new block number */
-#define GFS_FL_FIRST	1
-#define GFS_FL_LAST	2
-	unsigned int	flags;	/* special handling required */
-	int		found;	/* how many references were updated */
-};
-
 static void	growfs(int, int, unsigned int);
 static void	rdfs(ufs2_daddr_t, size_t, void *, int);
 static void	wtfs(ufs2_daddr_t, size_t, void *, int, unsigned int);
-static ufs2_daddr_t alloc(void);
 static int	charsperline(void);
 static void	usage(void);
 static int	isblock(struct fs *, unsigned char *, int);
@@ -143,16 +107,8 @@
 static void	initcg(int, time_t, int, unsigned int);
 static void	updjcg(int, time_t, int, int, unsigned int);
 static void	updcsloc(time_t, int, int, unsigned int);
-static struct disklabel	*get_disklabel(int);
-static void	return_disklabel(int, struct disklabel *, unsigned int);
-static union dinode *ginode(ino_t, int, int);
 static void	frag_adjust(ufs2_daddr_t, int);
-static int	cond_bl_upd(ufs2_daddr_t *, struct gfs_bpp *, int, int,
-		    unsigned int);
 static void	updclst(int);
-static void	updrefs(int, ino_t, struct gfs_bpp *, int, int, unsigned int);
-static void	indirchk(ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t, ufs_lbn_t,
-		    struct gfs_bpp *, int, int, unsigned int);
 static void	get_dev_size(int, int *);
=20
 /*
@@ -174,8 +130,7 @@
 	uint cylno;
 	int i, j, width;
 	char tmpbuf[100];
-#ifdef FSIRAND
-	static int randinit=3D0;
+	static int randinit =3D 0;
=20
 	DBG_ENTER;
=20
@@ -183,11 +138,6 @@
 		randinit =3D 1;
 		srandomdev();
 	}
-#else /* not FSIRAND */
-
-	DBG_ENTER;
-
-#endif /* FSIRAND */
 	time(&modtime);
=20
 	/*
@@ -227,7 +177,7 @@
 	/*
 	 * Dump out summary information about file system.
 	 */
-#	define B2MBFACTOR (1 / (1024.0 * 1024.0))
+#define B2MBFACTOR (1 / (1024.0 * 1024.0))
 	printf("growfs: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
 	    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
 	    (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
@@ -237,7 +187,7 @@
 	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
 	if (sblock.fs_flags & FS_DOSOFTDEP)
 		printf("\twith soft updates\n");
-#	undef B2MBFACTOR
+#undef B2MBFACTOR
=20
 	/*
 	 * Now build the cylinders group blocks and
@@ -363,11 +313,9 @@
 	static caddr_t iobuf;
 	long blkno, start;
 	ufs2_daddr_t i, cbase, dmax;
-#ifdef FSIRAND
 	struct ufs1_dinode *dp1;
-#endif
 	struct csum *cs;
-	uint d, dupper, dlower;
+	uint j, d, dupper, dlower;
=20
 	if (iobuf =3D=3D NULL && (iobuf =3D malloc(sblock.fs_bsize * 3)) =3D=3D N=
ULL)
 		errx(37, "panic: cannot allocate I/O buffer");
@@ -443,13 +391,11 @@
 		bzero(iobuf, sblock.fs_bsize);
 		for (i =3D 0; i < sblock.fs_ipg / INOPF(&sblock);
 		    i +=3D sblock.fs_frag) {
-#ifdef FSIRAND
 			dp1 =3D (struct ufs1_dinode *)(void *)iobuf;
 			for (j =3D 0; j < INOPB(&sblock); j++) {
 				dp1->di_gen =3D random();
 				dp1++;
 			}
-#endif
 			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
 			    sblock.fs_bsize, iobuf, fso, Nflag);
 		}
@@ -553,7 +499,7 @@
=20
 	DBG_ENTER;
=20
-	fragsize=3D0;
+	fragsize =3D 0;
 	/*
 	 * Here frag only needs to point to any fragment in the block we want
 	 * to examine.
@@ -570,7 +516,7 @@
 				/*
 				 * We found something in between.
 				 */
-				acg.cg_frsum[fragsize]+=3Dsign;
+				acg.cg_frsum[fragsize] +=3D sign;
 				DBG_PRINT2("frag_adjust [%d]+=3D%d\n",
 				    fragsize, sign);
 			}
@@ -591,64 +537,6 @@
 }
=20
 /*
- * Here we conditionally update a pointer to a fragment. We check for all
- * relocated blocks if any of its fragments is referenced by the current
- * field, and update the pointer to the respective fragment in our new
- * block.  If we find a reference we write back the block immediately,
- * as there is no easy way for our general block reading engine to figure
- * out if a write back operation is needed.
- */
-static int
-cond_bl_upd(ufs2_daddr_t *block, struct gfs_bpp *field, int fsi, int fso,
-    unsigned int Nflag)
-{
-	DBG_FUNC("cond_bl_upd")
-	struct gfs_bpp *f;
-	ufs2_daddr_t src, dst;
-	int fragnum;
-	void *ibuf;
-
-	DBG_ENTER;
-
-	for (f =3D field; f->old !=3D 0; f++) {
-		src =3D *block;
-		if (fragstoblks(&sblock, src) !=3D f->old)
-			continue;
-		/*
-		 * The fragment is part of the block, so update.
-		 */
-		dst =3D blkstofrags(&sblock, f->new);
-		fragnum =3D fragnum(&sblock, src);
-		*block =3D dst + fragnum;
-		f->found++;
-		DBG_PRINT3("scg (%jd->%jd)[%d] reference updated\n",
-		    (intmax_t)f->old, (intmax_t)f->new, fragnum);
-
-		/*
-		 * Copy the block back immediately.
-		 *
-		 * XXX	If src is from an indirect block we have
-		 *	to implement copy on write here in case of
-		 *	active snapshots.
-		 */
-		ibuf =3D malloc(sblock.fs_bsize);
-		if (!ibuf)
-			errx(1, "malloc failed");
-		src -=3D fragnum;
-		rdfs(fsbtodb(&sblock, src), (size_t)sblock.fs_bsize, ibuf, fsi);
-		wtfs(dst, (size_t)sblock.fs_bsize, ibuf, fso, Nflag);
-		free(ibuf);
-		/*
-		 * The same block can't be found again in this loop.
-		 */
-		return (1);
-	}
-
-	DBG_LEAVE;
-	return (0);
-}
-
-/*
  * Here we do all needed work for the former last cylinder group. It has t=
o be
  * changed in any case, even if the file system ended exactly on the end of
  * this group, as there is some slightly inconsistent handling of the numb=
er
@@ -691,7 +579,7 @@
=20
 	if (cgbase(&osblock, cylno + 1) =3D=3D osblock.fs_size) {
 		if (sblock.fs_magic =3D=3D FS_UFS1_MAGIC)
-			acg.cg_old_ncyl=3Dsblock.fs_old_cpg;
+			acg.cg_old_ncyl =3D sblock.fs_old_cpg;
=20
 		wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
 		    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
@@ -894,11 +782,8 @@
  *	longer in the beginning of the first cylinder group you should never
  *	use a version of fsck which is not aware of the possibility to have
  *	this structure in a non standard place.
- * Option (1) is considered to be less intrusive to the structure of the f=
ile-
- * system. So we try to stick to that whenever possible. If there is not e=
nough
- * space in the cylinder group containing the cylinder summary we have to =
use
- * method (2). In case of active snapshots in the file system we probably =
can
- * completely avoid implementing copy on write if we stick to method (2) o=
nly.
+ * Option (2) is considered to be less intrusive to the structure of the f=
ile-
+ * system, so that's the one being used.
  */
 static void
 updcsloc(time_t modtime, int fsi, int fso, unsigned int Nflag)
@@ -907,11 +792,7 @@
 	struct csum *cs;
 	int ocscg, ncscg;
 	int blocks;
-	ufs2_daddr_t cbase, dupper, odupper, d, f, g;
-	int ind, inc;
-	uint cylno;
-	struct gfs_bpp *bp;
-	int i, l;
+	ufs2_daddr_t d;
 	int lcs =3D 0;
 	int block;
=20
@@ -955,117 +836,84 @@
 	 *	also up to 8*3 blocks for indirect blocks for all possible
 	 *	references.
 	 */
-	if (/*((int)sblock.fs_time&0x3)>0||*/ cs->cs_nbfree < blocks) {
+	/*
+	 * There is not enough space in the old cylinder group to
+	 * relocate all blocks as needed, so we relocate the whole
+	 * cylinder group summary to a new group. We try to use the
+	 * first complete new cylinder group just created. Within the
+	 * cylinder group we align the area immediately after the
+	 * cylinder group information location in order to be as
+	 * close as possible to the original implementation of ffs.
+	 *
+	 * First we have to make sure we'll find enough space in the
+	 * new cylinder group. If not, then we currently give up.
+	 * We start with freeing everything which was used by the
+	 * fragments of the old cylinder summary in the current group.
+	 * Now we write back the group meta data, read in the needed
+	 * meta data from the new cylinder group, and start allocating
+	 * within that group. Here we can assume, the group to be
+	 * completely empty. Which makes the handling of fragments and
+	 * clusters a lot easier.
+	 */
+	DBG_TRC;
+	if (sblock.fs_ncg - osblock.fs_ncg < 2)
+		errx(2, "panic: not enough space");
+
+	/*
+	 * Point "d" to the first fragment not used by the cylinder
+	 * summary.
+	 */
+	d =3D osblock.fs_csaddr + (osblock.fs_cssize / osblock.fs_fsize);
+
+	/*
+	 * Set up last cluster size ("lcs") already here. Calculate
+	 * the size for the trailing cluster just behind where "d"
+	 * points to.
+	 */
+	if (sblock.fs_contigsumsize > 0) {
+		for (block =3D howmany(d % sblock.fs_fpg, sblock.fs_frag),
+		    lcs =3D 0; lcs < sblock.fs_contigsumsize; block++, lcs++) {
+			if (isclr(cg_clustersfree(&acg), block))
+				break;
+		}
+	}
+
+	/*
+	 * Point "d" to the last frag used by the cylinder summary.
+	 */
+	d--;
+
+	DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
+	if ((d + 1) % sblock.fs_frag) {
 		/*
-		 * There is not enough space in the old cylinder group to
-		 * relocate all blocks as needed, so we relocate the whole
-		 * cylinder group summary to a new group. We try to use the
-		 * first complete new cylinder group just created. Within the
-		 * cylinder group we align the area immediately after the
-		 * cylinder group information location in order to be as
-		 * close as possible to the original implementation of ffs.
-		 *
-		 * First we have to make sure we'll find enough space in the
-		 * new cylinder group. If not, then we currently give up.
-		 * We start with freeing everything which was used by the
-		 * fragments of the old cylinder summary in the current group.
-		 * Now we write back the group meta data, read in the needed
-		 * meta data from the new cylinder group, and start allocating
-		 * within that group. Here we can assume, the group to be
-		 * completely empty. Which makes the handling of fragments and
-		 * clusters a lot easier.
+		 * The end of the cylinder summary is not a complete
+		 * block.
 		 */
 		DBG_TRC;
-		if (sblock.fs_ncg - osblock.fs_ncg < 2)
-			errx(2, "panic: not enough space");
+		frag_adjust(d % sblock.fs_fpg, -1);
+		for (; (d + 1) % sblock.fs_frag; d--) {
+			DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
+			setbit(cg_blksfree(&acg), d % sblock.fs_fpg);
+			acg.cg_cs.cs_nffree++;
+			sblock.fs_cstotal.cs_nffree++;
+		}
+		/*
+		 * Point "d" to the last fragment of the last
+		 * (incomplete) block of the cylinder summary.
+		 */
+		d++;
+		frag_adjust(d % sblock.fs_fpg, 1);
=20
-		/*
-		 * Point "d" to the first fragment not used by the cylinder
-		 * summary.
-		 */
-		d =3D osblock.fs_csaddr + (osblock.fs_cssize / osblock.fs_fsize);
-
-		/*
-		 * Set up last cluster size ("lcs") already here. Calculate
-		 * the size for the trailing cluster just behind where "d"
-		 * points to.
-		 */
-		if (sblock.fs_contigsumsize > 0) {
-			for (block =3D howmany(d % sblock.fs_fpg, sblock.fs_frag),
-			    lcs =3D 0; lcs < sblock.fs_contigsumsize;
-			    block++, lcs++) {
-				if (isclr(cg_clustersfree(&acg), block))
-					break;
-			}
-		}
-
-		/*
-		 * Point "d" to the last frag used by the cylinder summary.
-		 */
-		d--;
-
-		DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
-		if ((d + 1) % sblock.fs_frag) {
-			/*
-			 * The end of the cylinder summary is not a complete
-			 * block.
-			 */
-			DBG_TRC;
-			frag_adjust(d % sblock.fs_fpg, -1);
-			for (; (d + 1) % sblock.fs_frag; d--) {
-				DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
-				setbit(cg_blksfree(&acg), d % sblock.fs_fpg);
-				acg.cg_cs.cs_nffree++;
-				sblock.fs_cstotal.cs_nffree++;
-			}
-			/*
-			 * Point "d" to the last fragment of the last
-			 * (incomplete) block of the cylinder summary.
-			 */
-			d++;
-			frag_adjust(d%sblock.fs_fpg, 1);
-
-			if (isblock(&sblock, cg_blksfree(&acg),
-			    (d % sblock.fs_fpg) / sblock.fs_frag)) {
-				DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
-				acg.cg_cs.cs_nffree -=3D sblock.fs_frag;
-				acg.cg_cs.cs_nbfree++;
-				sblock.fs_cstotal.cs_nffree -=3D sblock.fs_frag;
-				sblock.fs_cstotal.cs_nbfree++;
-				if (sblock.fs_contigsumsize > 0) {
-					setbit(cg_clustersfree(&acg),
-					    (d % sblock.fs_fpg) /
-					    sblock.fs_frag);
-					if (lcs < sblock.fs_contigsumsize) {
-						if (lcs)
-							cg_clustersum(&acg)[lcs]--;
-						lcs++;
-						cg_clustersum(&acg)[lcs]++;
-					}
-				}
-			}
-			/*
-			 * Point "d" to the first fragment of the block before
-			 * the last incomplete block.
-			 */
-			d--;
-		}
-
-		DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
-		for (d =3D rounddown(d, sblock.fs_frag); d >=3D osblock.fs_csaddr;
-		    d -=3D sblock.fs_frag) {
-			DBG_TRC;
+		if (isblock(&sblock, cg_blksfree(&acg),
+		    (d % sblock.fs_fpg) / sblock.fs_frag)) {
 			DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
-			setblock(&sblock, cg_blksfree(&acg),
-			    (d % sblock.fs_fpg) / sblock.fs_frag);
+			acg.cg_cs.cs_nffree -=3D sblock.fs_frag;
 			acg.cg_cs.cs_nbfree++;
+			sblock.fs_cstotal.cs_nffree -=3D sblock.fs_frag;
 			sblock.fs_cstotal.cs_nbfree++;
 			if (sblock.fs_contigsumsize > 0) {
 				setbit(cg_clustersfree(&acg),
 				    (d % sblock.fs_fpg) / sblock.fs_frag);
-				/*
-				 * The last cluster size is already set up.
-				 */
 				if (lcs < sblock.fs_contigsumsize) {
 					if (lcs)
 						cg_clustersum(&acg)[lcs]--;
@@ -1074,392 +922,137 @@
 				}
 			}
 		}
-		*cs =3D acg.cg_cs;
+		/*
+		 * Point "d" to the first fragment of the block before
+		 * the last incomplete block.
+		 */
+		d--;
+	}
=20
-		/*
-		 * Now write the former cylinder group containing the cylinder
-		 * summary back to disk.
-		 */
-		wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)),
-		    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
-		DBG_PRINT0("oscg written\n");
-		DBG_DUMP_CG(&sblock, "old summary cg", &acg);
-
-		/*
-		 * Find the beginning of the new cylinder group containing the
-		 * cylinder summary.
-		 */
-		sblock.fs_csaddr =3D cgdmin(&sblock, osblock.fs_ncg);
-		ncscg =3D dtog(&sblock, sblock.fs_csaddr);
-		cs =3D fscs + ncscg;
-
-		/*
-		 * If Nflag is specified, we would now read random data instead
-		 * of an empty cg structure from disk. So we can't simulate that
-		 * part for now.
-		 */
-		if (Nflag) {
-			DBG_PRINT0("nscg update skipped\n");
-			DBG_LEAVE;
-			return;
-		}
-
-		/*
-		 * Read the future cylinder group containing the cylinder
-		 * summary from disk, and make a copy.
-		 */
-		rdfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
-		    (size_t)sblock.fs_cgsize, (void *)&aocg, fsi);
-		DBG_PRINT0("nscg read\n");
-		DBG_DUMP_CG(&sblock, "new summary cg", &aocg);
-
-		memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
-
-		/*
-		 * Allocate all complete blocks used by the new cylinder
-		 * summary.
-		 */
-		for (d =3D sblock.fs_csaddr; d + sblock.fs_frag <=3D
-		    sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize);
-		    d +=3D sblock.fs_frag) {
-			clrblock(&sblock, cg_blksfree(&acg),
+	DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
+	for (d =3D rounddown(d, sblock.fs_frag); d >=3D osblock.fs_csaddr;
+	    d -=3D sblock.fs_frag) {
+		DBG_TRC;
+		DBG_PRINT1("d=3D%jd\n", (intmax_t)d);
+		setblock(&sblock, cg_blksfree(&acg),
+		    (d % sblock.fs_fpg) / sblock.fs_frag);
+		acg.cg_cs.cs_nbfree++;
+		sblock.fs_cstotal.cs_nbfree++;
+		if (sblock.fs_contigsumsize > 0) {
+			setbit(cg_clustersfree(&acg),
 			    (d % sblock.fs_fpg) / sblock.fs_frag);
-			acg.cg_cs.cs_nbfree--;
-			sblock.fs_cstotal.cs_nbfree--;
-			if (sblock.fs_contigsumsize > 0) {
-				clrbit(cg_clustersfree(&acg),
-				    (d % sblock.fs_fpg) / sblock.fs_frag);
+			/*
+			 * The last cluster size is already set up.
+			 */
+			if (lcs < sblock.fs_contigsumsize) {
+				if (lcs)
+					cg_clustersum(&acg)[lcs]--;
+				lcs++;
+				cg_clustersum(&acg)[lcs]++;
 			}
 		}
+	}
+	*cs =3D acg.cg_cs;
=20
-		/*
-		 * Allocate all fragments used by the cylinder summary in the
-		 * last block.
-		 */
-		if (d <
-		    sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize)) {
-			for (; d - sblock.fs_csaddr <
-			    sblock.fs_cssize/sblock.fs_fsize; d++) {
-				clrbit(cg_blksfree(&acg), d % sblock.fs_fpg);
-				acg.cg_cs.cs_nffree--;
-				sblock.fs_cstotal.cs_nffree--;
-			}
-			acg.cg_cs.cs_nbfree--;
-			acg.cg_cs.cs_nffree +=3D sblock.fs_frag;
-			sblock.fs_cstotal.cs_nbfree--;
-			sblock.fs_cstotal.cs_nffree +=3D sblock.fs_frag;
-			if (sblock.fs_contigsumsize > 0)
-				clrbit(cg_clustersfree(&acg),
-				    (d % sblock.fs_fpg) / sblock.fs_frag);
+	/*
+	 * Now write the former cylinder group containing the cylinder
+	 * summary back to disk.
+	 */
+	wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)),
+	    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
+	DBG_PRINT0("oscg written\n");
+	DBG_DUMP_CG(&sblock, "old summary cg", &acg);
=20
-			frag_adjust(d % sblock.fs_fpg, 1);
-		}
-		/*
-		 * XXX	Handle the cluster statistics here in the case this
-		 *	cylinder group is now almost full, and the remaining
-		 *	space is less then the maximum cluster size. This is
-		 *	probably not needed, as you would hardly find a file
-		 *	system which has only MAXCSBUFS+FS_MAXCONTIG of free
-		 *	space right behind the cylinder group information in
-		 *	any new cylinder group.
-		 */
+	/*
+	 * Find the beginning of the new cylinder group containing the
+	 * cylinder summary.
+	 */
+	sblock.fs_csaddr =3D cgdmin(&sblock, osblock.fs_ncg);
+	ncscg =3D dtog(&sblock, sblock.fs_csaddr);
+	cs =3D fscs + ncscg;
=20
-		/*
-		 * Update our statistics in the cylinder summary.
-		 */
-		*cs =3D acg.cg_cs;
-
-		/*
-		 * Write the new cylinder group containing the cylinder summary
-		 * back to disk.
-		 */
-		wtfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
-		    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
-		DBG_PRINT0("nscg written\n");
-		DBG_DUMP_CG(&sblock, "new summary cg", &acg);
-
+	/*
+	 * If Nflag is specified, we would now read random data instead
+	 * of an empty cg structure from disk. So we can't simulate that
+	 * part for now.
+	 */
+	if (Nflag) {
+		DBG_PRINT0("nscg update skipped\n");
 		DBG_LEAVE;
 		return;
 	}
-	/*
-	 * We have got enough of space in the current cylinder group, so we
-	 * can relocate just a few blocks, and let the summary information
-	 * grow in place where it is right now.
-	 */
-	DBG_TRC;
-
-	cbase =3D cgbase(&osblock, ocscg);	/* old and new are equal */
-	dupper =3D sblock.fs_csaddr - cbase +
-	    howmany(sblock.fs_cssize, sblock.fs_fsize);
-	odupper =3D osblock.fs_csaddr - cbase +
-	    howmany(osblock.fs_cssize, osblock.fs_fsize);
-
-	sblock.fs_dsize -=3D dupper - odupper;
=20
 	/*
-	 * Allocate the space for the array of blocks to be relocated.
+	 * Read the future cylinder group containing the cylinder
+	 * summary from disk, and make a copy.
 	 */
-	bp =3D (struct gfs_bpp *)malloc(((dupper - odupper) /
-	    sblock.fs_frag + 2) * sizeof(struct gfs_bpp));
-	if (bp =3D=3D NULL)
-		errx(1, "malloc failed");
-	memset((char *)bp, 0, ((dupper - odupper) / sblock.fs_frag + 2) *
-	    sizeof(struct gfs_bpp));
+	rdfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
+	    (size_t)sblock.fs_cgsize, (void *)&aocg, fsi);
+	DBG_PRINT0("nscg read\n");
+	DBG_DUMP_CG(&sblock, "new summary cg", &aocg);
+
+	memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
=20
 	/*
-	 * Lock all new frags needed for the cylinder group summary. This is
-	 * done per fragment in the first and last block of the new required
-	 * area, and per block for all other blocks.
-	 *
-	 * Handle the first new block here (but only if some fragments where
-	 * already used for the cylinder summary).
+	 * Allocate all complete blocks used by the new cylinder
+	 * summary.
 	 */
-	ind =3D 0;
-	frag_adjust(odupper, -1);
-	for (d =3D odupper; ((d < dupper) && (d % sblock.fs_frag)); d++) {
-		DBG_PRINT1("scg first frag check loop d=3D%jd\n", (intmax_t)d);
-		if (isclr(cg_blksfree(&acg), d)) {
-			if (!ind) {
-				bp[ind].old =3D d / sblock.fs_frag;
-				bp[ind].flags |=3D GFS_FL_FIRST;
-				if (roundup(d, sblock.fs_frag) >=3D dupper)
-					bp[ind].flags |=3D GFS_FL_LAST;
-				ind++;
-			}
-		} else {
-			clrbit(cg_blksfree(&acg), d);
+	for (d =3D sblock.fs_csaddr; d + sblock.fs_frag <=3D
+	    sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize);
+	    d +=3D sblock.fs_frag) {
+		clrblock(&sblock, cg_blksfree(&acg),
+		    (d % sblock.fs_fpg) / sblock.fs_frag);
+		acg.cg_cs.cs_nbfree--;
+		sblock.fs_cstotal.cs_nbfree--;
+		if (sblock.fs_contigsumsize > 0) {
+			clrbit(cg_clustersfree(&acg),
+			    (d % sblock.fs_fpg) / sblock.fs_frag);
+		}
+	}
+
+	/*
+	 * Allocate all fragments used by the cylinder summary in the
+	 * last block.
+	 */
+	if (d < sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize)) {
+		for (; d - sblock.fs_csaddr <
+		    sblock.fs_cssize/sblock.fs_fsize; d++) {
+			clrbit(cg_blksfree(&acg), d % sblock.fs_fpg);
 			acg.cg_cs.cs_nffree--;
 			sblock.fs_cstotal.cs_nffree--;
 		}
-		/*
-		 * No cluster handling is needed here, as there was at least
-		 * one fragment in use by the cylinder summary in the old
-		 * file system.
-		 * No block-free counter handling here as this block was not
-		 * a free block.
-		 */
+		acg.cg_cs.cs_nbfree--;
+		acg.cg_cs.cs_nffree +=3D sblock.fs_frag;
+		sblock.fs_cstotal.cs_nbfree--;
+		sblock.fs_cstotal.cs_nffree +=3D sblock.fs_frag;
+		if (sblock.fs_contigsumsize > 0)
+			clrbit(cg_clustersfree(&acg),
+			    (d % sblock.fs_fpg) / sblock.fs_frag);
+
+		frag_adjust(d % sblock.fs_fpg, 1);
 	}
-	frag_adjust(odupper, 1);
+	/*
+	 * XXX	Handle the cluster statistics here in the case this
+	 *	cylinder group is now almost full, and the remaining
+	 *	space is less then the maximum cluster size. This is
+	 *	probably not needed, as you would hardly find a file
+	 *	system which has only MAXCSBUFS+FS_MAXCONTIG of free
+	 *	space right behind the cylinder group information in
+	 *	any new cylinder group.
+	 */
=20
 	/*
-	 * Handle all needed complete blocks here.
+	 * Update our statistics in the cylinder summary.
 	 */
-	for (; d + sblock.fs_frag <=3D dupper; d +=3D sblock.fs_frag) {
-		DBG_PRINT1("scg block check loop d=3D%jd\n", (intmax_t)d);
-		if (!isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag)) {
-			for (f =3D d; f < d + sblock.fs_frag; f++) {
-				if (isset(cg_blksfree(&aocg), f)) {
-					acg.cg_cs.cs_nffree--;
-					sblock.fs_cstotal.cs_nffree--;
-				}
-			}
-			clrblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag);
-			bp[ind].old =3D d / sblock.fs_frag;
-			ind++;
-		} else {
-			clrblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag);
-			acg.cg_cs.cs_nbfree--;
-			sblock.fs_cstotal.cs_nbfree--;
-			if (sblock.fs_contigsumsize > 0) {
-				clrbit(cg_clustersfree(&acg), d / sblock.fs_frag);
-				for (lcs =3D 0, l =3D (d / sblock.fs_frag) + 1;
-				    lcs < sblock.fs_contigsumsize; l++, lcs++ ) {
-					if (isclr(cg_clustersfree(&acg), l))
-						break;
-				}
-				if (lcs < sblock.fs_contigsumsize) {
-					cg_clustersum(&acg)[lcs + 1]--;
-					if (lcs)
-						cg_clustersum(&acg)[lcs]++;
-				}
-			}
-		}
-		/*
-		 * No fragment counter handling is needed here, as this finally
-		 * doesn't change after the relocation.
-		 */
-	}
-
-	/*
-	 * Handle all fragments needed in the last new affected block.
-	 */
-	if (d < dupper) {
-		frag_adjust(dupper - 1, -1);
-
-		if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag)) {
-			acg.cg_cs.cs_nbfree--;
-			sblock.fs_cstotal.cs_nbfree--;
-			acg.cg_cs.cs_nffree +=3D sblock.fs_frag;
-			sblock.fs_cstotal.cs_nffree +=3D sblock.fs_frag;
-			if (sblock.fs_contigsumsize > 0) {
-				clrbit(cg_clustersfree(&acg), d / sblock.fs_frag);
-				for (lcs =3D 0, l =3D(d / sblock.fs_frag) + 1;
-				    lcs < sblock.fs_contigsumsize; l++, lcs++ ) {
-					if (isclr(cg_clustersfree(&acg),l))
-						break;
-				}
-				if (lcs < sblock.fs_contigsumsize) {
-					cg_clustersum(&acg)[lcs + 1]--;
-					if (lcs)
-						cg_clustersum(&acg)[lcs]++;
-				}
-			}
-		}
-
-		for (; d < dupper; d++) {
-			DBG_PRINT1("scg second frag check loop d=3D%jd\n",
-			    (intmax_t)d);
-			if (isclr(cg_blksfree(&acg), d)) {
-				bp[ind].old =3D d / sblock.fs_frag;
-				bp[ind].flags |=3D GFS_FL_LAST;
-			} else {
-				clrbit(cg_blksfree(&acg), d);
-				acg.cg_cs.cs_nffree--;
-				sblock.fs_cstotal.cs_nffree--;
-			}
-		}
-		if (bp[ind].flags & GFS_FL_LAST) /* we have to advance here */
-			ind++;
-		frag_adjust(dupper - 1, 1);
-	}
-
-	/*
-	 * If we found a block to relocate just do so.
-	 */
-	if (ind) {
-		for (i =3D 0; i < ind; i++) {
-			if (!bp[i].old) { /* no more blocks listed */
-				/*
-				 * XXX	A relative blocknumber should not be
-				 *	zero, which is not explicitly
-				 *	guaranteed by our code.
-				 */
-				break;
-			}
-			/*
-			 * Allocate a complete block in the same (current)
-			 * cylinder group.
-			 */
-			bp[i].new =3D alloc() / sblock.fs_frag;
-
-			/*
-			 * There is no frag_adjust() needed for the new block
-			 * as it will have no fragments yet :-).
-			 */
-			for (f =3D bp[i].old * sblock.fs_frag,
-			    g =3D bp[i].new * sblock.fs_frag;
-			    f < (bp[i].old + 1) * sblock.fs_frag;
-			    f++, g++) {
-				if (isset(cg_blksfree(&aocg), f)) {
-					setbit(cg_blksfree(&acg), g);
-					acg.cg_cs.cs_nffree++;
-					sblock.fs_cstotal.cs_nffree++;
-				}
-			}
-
-			/*
-			 * Special handling is required if this was the first
-			 * block. We have to consider the fragments which were
-			 * used by the cylinder summary in the original block
-			 * which re to be free in the copy of our block.  We
-			 * have to be careful if this first block happens to
-			 * be also the last block to be relocated.
-			 */
-			if (bp[i].flags & GFS_FL_FIRST) {
-				for (f =3D bp[i].old * sblock.fs_frag,
-				    g =3Dbp[i].new * sblock.fs_frag;
-				    f < odupper; f++, g++) {
-					setbit(cg_blksfree(&acg), g);
-					acg.cg_cs.cs_nffree++;
-					sblock.fs_cstotal.cs_nffree++;
-				}
-				if (!(bp[i].flags & GFS_FL_LAST))
-					frag_adjust(bp[i].new * sblock.fs_frag, 1);
-			}
-
-			/*
-			 * Special handling is required if this is the last
-			 * block to be relocated.
-			 */
-			if (bp[i].flags & GFS_FL_LAST) {
-				frag_adjust(bp[i].new * sblock.fs_frag, 1);
-				frag_adjust(bp[i].old * sblock.fs_frag, -1);
-				for (f =3D dupper;
-				    f < roundup(dupper, sblock.fs_frag); f++) {
-					if (isclr(cg_blksfree(&acg), f)) {
-						setbit(cg_blksfree(&acg), f);
-						acg.cg_cs.cs_nffree++;
-						sblock.fs_cstotal.cs_nffree++;
-					}
-				}
-				frag_adjust(bp[i].old * sblock.fs_frag, 1);
-			}
-
-			/*
-			 * !!! Attach the cylindergroup offset here.
-			 */
-			bp[i].old +=3D cbase / sblock.fs_frag;
-			bp[i].new +=3D cbase / sblock.fs_frag;
-
-			/*
-			 * Copy the content of the block.
-			 */
-			/*
-			 * XXX	Here we will have to implement a copy on write
-			 *	in the case we have any active snapshots.
-			 */
-			rdfs(fsbtodb(&sblock, bp[i].old * sblock.fs_frag),
-			    (size_t)sblock.fs_bsize, (void *)&ablk, fsi);
-			wtfs(fsbtodb(&sblock, bp[i].new * sblock.fs_frag),
-			    (size_t)sblock.fs_bsize, (void *)&ablk, fso, Nflag);
-			DBG_DUMP_HEX(&sblock, "copied full block",
-			    (unsigned char *)&ablk);
-			DBG_PRINT2("scg (%jd->%jd) block relocated\n",
-			    (intmax_t)bp[i].old, (intmax_t)bp[i].new);
-		}
-
-		/*
-		 * Now we have to update all references to any fragment which
-		 * belongs to any block relocated. We iterate now over all
-		 * cylinder groups, within those over all non zero length
-		 * inodes.
-		 */
-		for (cylno =3D 0; cylno < osblock.fs_ncg; cylno++) {
-			DBG_PRINT1("scg doing cg (%d)\n", cylno);
-			for (inc =3D osblock.fs_ipg - 1 ; inc > 0 ; inc--)
-				updrefs(cylno, (ino_t)inc, bp, fsi, fso, Nflag);
-		}
-
-		/*
-		 * All inodes are checked, now make sure the number of
-		 * references found make sense.
-		 */
-		for (i =3D 0; i < ind; i++) {
-			if (!bp[i].found || (bp[i].found > sblock.fs_frag)) {
-				warnx("error: %jd refs found for block %jd.",
-				    (intmax_t)bp[i].found, (intmax_t)bp[i].old);
-			}
-		}
-	}
-	/*
-	 * The following statistics are not changed here:
-	 *     sblock.fs_cstotal.cs_ndir
-	 *     sblock.fs_cstotal.cs_nifree
-	 * The following statistics were already updated on the fly:
-	 *     sblock.fs_cstotal.cs_nffree
-	 *     sblock.fs_cstotal.cs_nbfree
-	 * As the statistics for this cylinder group are ready, copy it to
-	 * the summary information array.
-	 */
-
 	*cs =3D acg.cg_cs;
=20
 	/*
-	 * Write summary cylinder group back to disk.
+	 * Write the new cylinder group containing the cylinder summary
+	 * back to disk.
 	 */
-	wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)), (size_t)sblock.fs_cgsize,
-	    (void *)&acg, fso, Nflag);
-	DBG_PRINT0("scg written\n");
+	wtfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
+	    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
+	DBG_PRINT0("nscg written\n");
 	DBG_DUMP_CG(&sblock, "new summary cg", &acg);
=20
 	DBG_LEAVE;
@@ -1515,126 +1108,6 @@
 }
=20
 /*
- * Here we allocate a free block in the current cylinder group. It is assu=
med,
- * that acg contains the current cylinder group. As we may take a block fr=
om
- * somewhere in the file system we have to handle cluster summary here.
- */
-static ufs2_daddr_t
-alloc(void)
-{
-	DBG_FUNC("alloc")
-	ufs2_daddr_t d, blkno;
-	int lcs1, lcs2;
-	int l;
-	int csmin, csmax;
-	int dlower, dupper, dmax;
-
-	DBG_ENTER;
-
-	if (acg.cg_magic !=3D CG_MAGIC) {
-		warnx("acg: bad magic number");
-		DBG_LEAVE;
-		return (0);
-	}
-	if (acg.cg_cs.cs_nbfree =3D=3D 0) {
-		warnx("error: cylinder group ran out of space");
-		DBG_LEAVE;
-		return (0);
-	}
-	/*
-	 * We start seeking for free blocks only from the space available after
-	 * the end of the new grown cylinder summary. Otherwise we allocate a
-	 * block here which we have to relocate a couple of seconds later again
-	 * again, and we are not prepared to to this anyway.
-	 */
-	blkno =3D -1;
-	dlower =3D cgsblock(&sblock, acg.cg_cgx) - cgbase(&sblock, acg.cg_cgx);
-	dupper =3D cgdmin(&sblock, acg.cg_cgx) - cgbase(&sblock, acg.cg_cgx);
-	dmax =3D cgbase(&sblock, acg.cg_cgx) + sblock.fs_fpg;
-	if (dmax > sblock.fs_size)
-		dmax =3D sblock.fs_size;
-	dmax -=3D cgbase(&sblock, acg.cg_cgx); /* retransform into cg */
-	csmin =3D sblock.fs_csaddr - cgbase(&sblock, acg.cg_cgx);
-	csmax =3D csmin + howmany(sblock.fs_cssize, sblock.fs_fsize);
-	DBG_PRINT3("seek range: dl=3D%d, du=3D%d, dm=3D%d\n", dlower, dupper, dma=
x);
-	DBG_PRINT2("range cont: csmin=3D%d, csmax=3D%d\n", csmin, csmax);
-
-	for (d =3D 0; (d < dlower && blkno =3D=3D -1); d +=3D sblock.fs_frag) {
-		if (d >=3D csmin && d <=3D csmax)
-			continue;
-		if (isblock(&sblock, cg_blksfree(&acg), fragstoblks(&sblock, d))) {
-			blkno =3D fragstoblks(&sblock, d);/* Yeah found a block */
-			break;
-		}
-	}
-	for (d =3D dupper; (d < dmax && blkno =3D=3D -1); d +=3D sblock.fs_frag) {
-		if (d >=3D csmin && d <=3D csmax) {
-			continue;
-		}
-		if (isblock(&sblock, cg_blksfree(&acg), fragstoblks(&sblock, d))) {
-			blkno =3D fragstoblks(&sblock, d);/* Yeah found a block */
-			break;
-		}
-	}
-	if (blkno =3D=3D -1) {
-		warnx("internal error: couldn't find promised block in cg");
-		DBG_LEAVE;
-		return (0);
-	}
-
-	/*
-	 * This is needed if the block was found already in the first loop.
-	 */
-	d =3D blkstofrags(&sblock, blkno);
-
-	clrblock(&sblock, cg_blksfree(&acg), blkno);
-	if (sblock.fs_contigsumsize > 0) {
-		/*
-		 * Handle the cluster allocation bitmap.
-		 */
-		clrbit(cg_clustersfree(&acg), blkno);
-		/*
-		 * We possibly have split a cluster here, so we have to do
-		 * recalculate the sizes of the remaining cluster halves now,
-		 * and use them for updating the cluster summary information.
-		 *
-		 * Lets start with the blocks before our allocated block ...
-		 */
-		for (lcs1 =3D 0, l =3D blkno - 1; lcs1 < sblock.fs_contigsumsize;
-				l--, lcs1++ ) {
-			if (isclr(cg_clustersfree(&acg), l))
-				break;
-		}
-		/*
-		 * ... and continue with the blocks right after our allocated
-		 * block.
-		 */
-		for (lcs2 =3D 0, l =3D blkno + 1; lcs2 < sblock.fs_contigsumsize;
-		    l++, lcs2++ ) {
-			if (isclr(cg_clustersfree(&acg), l))
-				break;
-		}
-
-		/*
-		 * Now update all counters.
-		 */
-		cg_clustersum(&acg)[MIN(lcs1 + lcs2 + 1, sblock.fs_contigsumsize)]--;
-		if (lcs1)
-			cg_clustersum(&acg)[lcs1]++;
-		if (lcs2)
-			cg_clustersum(&acg)[lcs2]++;
-	}
-	/*
-	 * Update all statistics based on blocks.
-	 */
-	acg.cg_cs.cs_nbfree--;
-	sblock.fs_cstotal.cs_nbfree--;
-
-	DBG_LEAVE;
-	return (d);
-}
-
-/*
  * Here we check if all frags of a block are free. For more details again
  * please see the source of newfs(8), as this function is taken over almost
  * unchanged.
@@ -1739,54 +1212,6 @@
 }
=20
 /*
- * This function provides access to an individual inode. We find out in wh=
ich
- * block the requested inode is located, read it from disk if needed, and
- * return the pointer into that block. We maintain a cache of one block to
- * not read the same block again and again if we iterate linearly over all
- * inodes.
- */
-static union dinode *
-ginode(ino_t inumber, int fsi, int cg)
-{
-	DBG_FUNC("ginode")
-	static ino_t startinum =3D 0;	/* first inode in cached block */
-
-	DBG_ENTER;
-
-	/*
-	 * The inumber passed in is relative to the cg, so use it here to see
-	 * if the inode has been allocated yet.
-	 */
-	if (isclr(cg_inosused(&aocg), inumber)) {
-		DBG_LEAVE;
-		return NULL;
-	}
-	/*
-	 * Now make the inumber relative to the entire inode space so it can
-	 * be sanity checked.
-	 */
-	inumber +=3D (cg * sblock.fs_ipg);
-	if (inumber < ROOTINO) {
-		DBG_LEAVE;
-		return NULL;
-	}
-	if (inumber > maxino)
-		errx(8, "bad inode number %d to ginode", inumber);
-	if (startinum =3D=3D 0 ||
-	    inumber < startinum || inumber >=3D startinum + INOPB(&sblock)) {
-		inoblk =3D fsbtodb(&sblock, ino_to_fsba(&sblock, inumber));
-		rdfs(inoblk, (size_t)sblock.fs_bsize, inobuf, fsi);
-		startinum =3D (inumber / INOPB(&sblock)) * INOPB(&sblock);
-	}
-	DBG_LEAVE;
-	if (sblock.fs_magic =3D=3D FS_UFS1_MAGIC)
-		return (union dinode *)((uintptr_t)inobuf +
-		    (inumber % INOPB(&sblock)) * sizeof(struct ufs1_dinode));
-	return (union dinode *)((uintptr_t)inobuf +
-	    (inumber % INOPB(&sblock)) * sizeof(struct ufs2_dinode));
-}
-
-/*
  * Figure out how many lines our current terminal has. For more details ag=
ain
  * please see the source of newfs(8), as this function is taken over almost
  * unchanged.
@@ -1814,8 +1239,7 @@
 }
=20
 /*
- * Get the size of the partition if we can't figure it out from the diskla=
bel,
- * e.g. from vinum volumes.
+ * Get the size of the partition.
  */
 static void
 get_dev_size(int fd, int *size)
@@ -1841,8 +1265,7 @@
  * and it does some basic checkings. The old file system size is determined
  * and after some more checks like we can really access the new last block
  * on the disk etc. we calculate the new parameters for the superblock. Af=
ter
- * having done this we just call growfs() which will do the work.  Before
- * we finish the only thing left is to update the disklabel.
+ * having done this we just call growfs() which will do the work.
  * We still have to provide support for snapshots. Therefore we first have=
 to
  * understand what data structures are always replicated in the snapshot on
  * creation, for all other blocks we touch during our procedure, we have to
@@ -1860,21 +1283,17 @@
 main(int argc, char **argv)
 {
 	DBG_FUNC("main")
-	char *device, *special, *cp;
+	char *device, *special;
 	int ch;
 	unsigned int size =3D 0;
 	size_t len;
 	unsigned int Nflag =3D 0;
 	int ExpertFlag =3D 0;
 	struct stat st;
-	struct disklabel *lp;
-	struct partition *pp;
 	int i, fsi, fso;
 	u_int32_t p_size;
 	char reply[5];
-#ifdef FSMAXSNAP
 	int j;
-#endif /* FSMAXSNAP */
=20
 	DBG_ENTER;
=20
@@ -1960,24 +1379,11 @@
 		err(1, "%s", device);
=20
 	/*
-	 * Try to read a label and guess the slice if not specified. This
-	 * code should guess the right thing and avoid to bother the user
-	 * with the task of specifying the option -v on vinum volumes.
+	 * Try to guess the slice if not specified. This code should guess
+	 * the right thing and avoid to bother the user with the task
+	 * of specifying the option -v on vinum volumes.
 	 */
-	cp =3D device + strlen(device) - 1;
-	lp =3D get_disklabel(fsi);
-	pp =3D NULL;
-	if (lp !=3D NULL) {
-		if (isdigit(*cp))
-			pp =3D &lp->d_partitions[2];
-		else if (*cp>=3D'a' && *cp<=3D'h')
-			pp =3D &lp->d_partitions[*cp - 'a'];
-		else
-			errx(1, "unknown device");
-		p_size =3D pp->p_size;
-	} else {
-		get_dev_size(fsi, &p_size);
-	}
+	get_dev_size(fsi, &p_size);
=20
 	/*
 	 * Check if that partition is suitable for growing a file system.
@@ -2001,14 +1407,12 @@
 	if (sblock_try[i] =3D=3D -1)
 		errx(1, "superblock not recognized");
 	memcpy((void *)&fsun1, (void *)&fsun2, sizeof(fsun2));
-	maxino =3D sblock.fs_ncg * sblock.fs_ipg;
=20
 	DBG_OPEN("/tmp/growfs.debug"); /* already here we need a superblock */
 	DBG_DUMP_FS(&sblock, "old sblock");
=20
 	/*
-	 * Determine size to grow to. Default to the full size specified in
-	 * the disk label.
+	 * Determine size to grow to. Default to the device size.
 	 */
 	sblock.fs_size =3D dbtofsb(&osblock, p_size);
 	if (size !=3D 0) {
@@ -2026,8 +1430,6 @@
 		    (intmax_t)osblock.fs_size, (intmax_t)sblock.fs_size);
 	}
=20
-
-#ifdef FSMAXSNAP
 	/*
 	 * Check if we find an active snapshot.
 	 */
@@ -2042,7 +1444,6 @@
 				break;
 		}
 	}
-#endif
=20
 	if (ExpertFlag =3D=3D 0 && Nflag =3D=3D 0) {
 		printf("We strongly recommend you to make a backup "
@@ -2068,7 +1469,7 @@
 	/*
 	 * Now calculate new superblock values and check for reasonable
 	 * bound for new file system size:
-	 *     fs_size:    is derived from label or user input
+	 *     fs_size:    is derived from user input
 	 *     fs_dsize:   should get updated in the routines creating or
 	 *                 updating the cylinder groups on the fly
 	 *     fs_cstotal: should get updated in the routines creating or
@@ -2086,7 +1487,6 @@
 			sblock.fs_old_ncyl++;
 	}
 	sblock.fs_ncg =3D howmany(sblock.fs_size, sblock.fs_fpg);
-	maxino =3D sblock.fs_ncg * sblock.fs_ipg;
=20
 	if (sblock.fs_size % sblock.fs_fpg !=3D 0 &&
 	    sblock.fs_size % sblock.fs_fpg < cgdmin(&sblock, sblock.fs_ncg)) {
@@ -2100,7 +1500,6 @@
 		printf("Warning: %jd sector(s) cannot be allocated.\n",
 		    (intmax_t)fsbtodb(&sblock, sblock.fs_size % sblock.fs_fpg));
 		sblock.fs_size =3D sblock.fs_ncg * sblock.fs_fpg;
-		maxino -=3D sblock.fs_ipg;
 	}
=20
 	/*
@@ -2120,18 +1519,6 @@
 	 */
 	growfs(fsi, fso, Nflag);
=20
-	/*
-	 * Update the disk label.
-	 */
-	if (!unlabeled) {
-		pp->p_fsize =3D sblock.fs_fsize;
-		pp->p_frag =3D sblock.fs_frag;
-		pp->p_cpg =3D sblock.fs_fpg;
-
-		return_disklabel(fso, lp, Nflag);
-		DBG_PRINT0("label rewritten\n");
-	}
-
 	close(fsi);
 	if (fso > -1)
 		close(fso);
@@ -2143,68 +1530,6 @@
 }
=20
 /*
- * Write the updated disklabel back to disk.
- */
-static void
-return_disklabel(int fd, struct disklabel *lp, unsigned int Nflag)
-{
-	DBG_FUNC("return_disklabel")
-	u_short	sum;
-	u_short	*ptr;
-
-	DBG_ENTER;
-
-	if (!lp) {
-		DBG_LEAVE;
-		return;
-	}
-	if (!Nflag) {
-		lp->d_checksum =3D 0;
-		sum =3D 0;
-		ptr =3D (u_short *)lp;
-
-		/*
-		 * recalculate checksum
-		 */
-		while (ptr < (u_short *)&lp->d_partitions[lp->d_npartitions])
-			sum ^=3D *ptr++;
-		lp->d_checksum=3Dsum;
-
-		if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0)
-			errx(1, "DIOCWDINFO failed");
-	}
-	free(lp);
-
-	DBG_LEAVE;
-	return ;
-}
-
-/*
- * Read the disklabel from disk.
- */
-static struct disklabel *
-get_disklabel(int fd)
-{
-	DBG_FUNC("get_disklabel")
-	static struct disklabel *lab;
-
-	DBG_ENTER;
-
-	lab =3D (struct disklabel *)malloc(sizeof(struct disklabel));
-	if (!lab)
-		errx(1, "malloc failed");
-
-	if (!ioctl(fd, DIOCGDINFO, (char *)lab))
-		return (lab);
-
-	unlabeled++;
-
-	DBG_LEAVE;
-	return (NULL);
-}
-
-
-/*
  * Dump a line of usage.
  */
 static void
@@ -2261,131 +1586,3 @@
 	DBG_LEAVE;
 	return;
 }
-
-/*
- * This updates all references to relocated blocks for the given inode.  T=
he
- * inode is given as number within the cylinder group, and the number of t=
he
- * cylinder group.
- */
-static void
-updrefs(int cg, ino_t in, struct gfs_bpp *bp, int fsi, int fso, unsigned i=
nt
-    Nflag)
-{
-	DBG_FUNC("updrefs")
-	ufs_lbn_t len, lbn, numblks;
-	ufs2_daddr_t iptr, blksperindir;
-	union dinode *ino;
-	int i, mode, inodeupdated;
-
-	DBG_ENTER;
-
-	ino =3D ginode(in, fsi, cg);
-	if (ino =3D=3D NULL) {
-		DBG_LEAVE;
-		return;
-	}
-	mode =3D DIP(ino, di_mode) & IFMT;
-	if (mode !=3D IFDIR && mode !=3D IFREG && mode !=3D IFLNK) {
-		DBG_LEAVE;
-		return; /* only check DIR, FILE, LINK */
-	}
-	if (mode =3D=3D IFLNK &&=20
-	    DIP(ino, di_size) < (u_int64_t) sblock.fs_maxsymlinklen) {
-		DBG_LEAVE;
-		return;	/* skip short symlinks */
-	}
-	numblks =3D howmany(DIP(ino, di_size), sblock.fs_bsize);
-	if (numblks =3D=3D 0) {
-		DBG_LEAVE;
-		return;	/* skip empty file */
-	}
-	if (DIP(ino, di_blocks) =3D=3D 0) {
-		DBG_LEAVE;
-		return;	/* skip empty swiss cheesy file or old fastlink */
-	}
-	DBG_PRINT2("scg checking inode (%d in %d)\n", in, cg);
-
-	/*
-	 * Check all the blocks.
-	 */
-	inodeupdated =3D 0;
-	len =3D numblks < NDADDR ? numblks : NDADDR;
-	for (i =3D 0; i < len; i++) {
-		iptr =3D DIP(ino, di_db[i]);
-		if (iptr =3D=3D 0)
-			continue;
-		if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
-			DIP_SET(ino, di_db[i], iptr);
-			inodeupdated++;
-		}
-	}
-	DBG_PRINT0("~~scg direct blocks checked\n");
-
-	blksperindir =3D 1;
-	len =3D numblks - NDADDR;
-	lbn =3D NDADDR;
-	for (i =3D 0; len > 0 && i < NIADDR; i++) {
-		iptr =3D DIP(ino, di_ib[i]);
-		if (iptr =3D=3D 0)
-			continue;
-		if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
-			DIP_SET(ino, di_ib[i], iptr);
-			inodeupdated++;
-		}
-		indirchk(blksperindir, lbn, iptr, numblks, bp, fsi, fso, Nflag);
-		blksperindir *=3D NINDIR(&sblock);
-		lbn +=3D blksperindir;
-		len -=3D blksperindir;
-		DBG_PRINT1("scg indirect_%d blocks checked\n", i + 1);
-	}
-	if (inodeupdated)
-		wtfs(inoblk, sblock.fs_bsize, inobuf, fso, Nflag);
-
-	DBG_LEAVE;
-	return;
-}
-
-/*
- * Recursively check all the indirect blocks.
- */
-static void
-indirchk(ufs_lbn_t blksperindir, ufs_lbn_t lbn, ufs2_daddr_t blkno,
-    ufs_lbn_t lastlbn, struct gfs_bpp *bp, int fsi, int fso, unsigned int =
Nflag)
-{
-	DBG_FUNC("indirchk")
-	void *ibuf;
-	int i, last;
-	ufs2_daddr_t iptr;
-
-	DBG_ENTER;
-
-	/* read in the indirect block. */
-	ibuf =3D malloc(sblock.fs_bsize);
-	if (!ibuf)
-		errx(1, "malloc failed");
-	rdfs(fsbtodb(&sblock, blkno), (size_t)sblock.fs_bsize, ibuf, fsi);
-	last =3D howmany(lastlbn - lbn, blksperindir) < NINDIR(&sblock) ?
-	    howmany(lastlbn - lbn, blksperindir) : NINDIR(&sblock);
-	for (i =3D 0; i < last; i++) {
-		if (sblock.fs_magic =3D=3D FS_UFS1_MAGIC)
-			iptr =3D ((ufs1_daddr_t *)ibuf)[i];
-		else
-			iptr =3D ((ufs2_daddr_t *)ibuf)[i];
-		if (iptr =3D=3D 0)
-			continue;
-		if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
-			if (sblock.fs_magic =3D=3D FS_UFS1_MAGIC)
-				((ufs1_daddr_t *)ibuf)[i] =3D iptr;
-			else
-				((ufs2_daddr_t *)ibuf)[i] =3D iptr;
-		}
-		if (blksperindir =3D=3D 1)
-			continue;
-		indirchk(blksperindir / NINDIR(&sblock), lbn + blksperindir * i,
-		    iptr, lastlbn, bp, fsi, fso, Nflag);
-	}
-	free(ibuf);
-
-	DBG_LEAVE;
-	return;
-}
diff -r 428842767fa6 -r f2935497fa04 head/sbin/gvinum/gvinum.8
--- a/head/sbin/gvinum/gvinum.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/gvinum/gvinum.8	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/gvinum/gvinum.8 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd April 10, 2009
 .Dt GVINUM 8
@@ -42,7 +42,7 @@
 .Bl -tag -width indent
 .It Ic attach Ar plex volume Op Cm rename
 .It Ic attach Ar subdisk plex Oo Ar offset Oc Op Cm rename
-Attach a plex to a volume, or a subdisk to a plex.=20
+Attach a plex to a volume, or a subdisk to a plex.
 If offset is specified, the subdisk will be attached to the given offset w=
ithin
 the plex.
 If rename is specified, the subdisk or plex will change name according to =
the
@@ -103,10 +103,10 @@
 .Fl V
 flags provide progressively more detailed output.
 .It Ic mirror Oo Fl fsv Oc Oo Fl n Ar name Oc Ar drives
-Create a mirrored volume from the specified drives.=20
+Create a mirrored volume from the specified drives.
 It requires at least a multiple of 2 drives.
 If no name is specified, a unique name will be set by gvinum.
-If the=20
+If the
 .Fl s
 flag is specified, a striped mirror will be created, and thus requires a
 multiple of 4 drives.
@@ -149,7 +149,7 @@
 .It Ic raid5 Oo Fl fv Oc Oo Fl s Ar stripesize Oc Oo Fl n Ar name Oc Ar dr=
ives
 Create a RAID-5 volume from the specified drives.
 If no name is specified,a unique name will be set by
-.Ic gvinum.=20
+.Ic gvinum.
 This organization requires at least three drives.
 .It Ic rename Oo Fl r Oc Ar drive | subdisk | plex | volume newname
 Change the name of the specified object.
@@ -282,7 +282,7 @@
 .Pp
 .Dl "gvinum mirror /dev/ad1 /dev/ad2"
 .Dl "newfs /dev/gvinum/gvinumvolume0"
-.Dl "mount /dev/gvinum/gvinumvolume0 /mnt"=20
+.Dl "mount /dev/gvinum/gvinumvolume0 /mnt"
 .Dl "..."
 .Dl "unmount /mnt"
 .Dl "gvinum stop"
@@ -356,7 +356,6 @@
 .Pp
 For a more advanced usage and detailed explanation of gvinum, the
 handbook is recommended.
-.Pp
 .Sh SEE ALSO
 .Xr geom 4 ,
 .Xr geom 8
diff -r 428842767fa6 -r f2935497fa04 head/sbin/hastd/hastd.c
--- a/head/sbin/hastd/hastd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/hastd/hastd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 230457 2012-01-22 11:20:42Z pj=
d $");
+__FBSDID("$FreeBSD: head/sbin/hastd/hastd.c 233679 2012-03-29 20:11:16Z tr=
ociny $");
=20
 #include <sys/param.h>
 #include <sys/linker.h>
@@ -66,6 +66,8 @@
 static struct hastd_config *cfg;
 /* Was SIGINT or SIGTERM signal received? */
 bool sigexit_received =3D false;
+/* Path to pidfile. */
+static const char *pidfile;
 /* PID file handle. */
 struct pidfh *pfh;
 /* Do we run in foreground? */
@@ -537,7 +539,8 @@
 	/*
 	 * Check if pidfile's path has changed.
 	 */
-	if (!foreground && strcmp(cfg->hc_pidfile, newcfg->hc_pidfile) !=3D 0) {
+	if (!foreground && pidfile =3D=3D NULL &&
+	    strcmp(cfg->hc_pidfile, newcfg->hc_pidfile) !=3D 0) {
 		newpfh =3D pidfile_open(newcfg->hc_pidfile, 0600, &otherpid);
 		if (newpfh =3D=3D NULL) {
 			if (errno =3D=3D EEXIST) {
@@ -1163,14 +1166,12 @@
 main(int argc, char *argv[])
 {
 	struct hastd_listen *lst;
-	const char *pidfile;
 	pid_t otherpid;
 	int debuglevel;
 	sigset_t mask;
=20
 	foreground =3D false;
 	debuglevel =3D 0;
-	pidfile =3D NULL;
=20
 	for (;;) {
 		int ch;
@@ -1230,7 +1231,7 @@
 		}
 	}
=20
-	if (!foreground) {
+	if (pidfile !=3D NULL || !foreground) {
 		pfh =3D pidfile_open(cfg->hc_pidfile, 0600, &otherpid);
 		if (pfh =3D=3D NULL) {
 			if (errno =3D=3D EEXIST) {
@@ -1291,7 +1292,8 @@
=20
 		/* Start logging to syslog. */
 		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
-
+	}
+	if (pidfile !=3D NULL || !foreground) {
 		/* Write PID to a file. */
 		if (pidfile_write(pfh) =3D=3D -1) {
 			pjdlog_errno(LOG_WARNING,
diff -r 428842767fa6 -r f2935497fa04 head/sbin/hastd/nv.c
--- a/head/sbin/hastd/nv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/hastd/nv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/hastd/nv.c 229945 2012-01-10 22:39:07Z pjd $=
");
+__FBSDID("$FreeBSD: head/sbin/hastd/nv.c 233392 2012-03-23 20:18:48Z troci=
ny $");
=20
 #include <sys/param.h>
 #include <sys/endian.h>
@@ -263,17 +263,17 @@
 		case NV_TYPE_UINT8:
 			if (vsize =3D=3D 0)
 				vsize =3D 1;
-			/* FALLTHOUGH */
+			/* FALLTHROUGH */
 		case NV_TYPE_INT16:
 		case NV_TYPE_UINT16:
 			if (vsize =3D=3D 0)
 				vsize =3D 2;
-			/* FALLTHOUGH */
+			/* FALLTHROUGH */
 		case NV_TYPE_INT32:
 		case NV_TYPE_UINT32:
 			if (vsize =3D=3D 0)
 				vsize =3D 4;
-			/* FALLTHOUGH */
+			/* FALLTHROUGH */
 		case NV_TYPE_INT64:
 		case NV_TYPE_UINT64:
 			if (vsize =3D=3D 0)
@@ -290,12 +290,12 @@
 		case NV_TYPE_UINT16_ARRAY:
 			if (vsize =3D=3D 0)
 				vsize =3D 2;
-			/* FALLTHOUGH */
+			/* FALLTHROUGH */
 		case NV_TYPE_INT32_ARRAY:
 		case NV_TYPE_UINT32_ARRAY:
 			if (vsize =3D=3D 0)
 				vsize =3D 4;
-			/* FALLTHOUGH */
+			/* FALLTHROUGH */
 		case NV_TYPE_INT64_ARRAY:
 		case NV_TYPE_UINT64_ARRAY:
 			if (vsize =3D=3D 0)
@@ -906,14 +906,14 @@
 	case NV_TYPE_UINT16_ARRAY:
 		if (vsize =3D=3D 0)
 			vsize =3D 2;
-		/* FALLTHOUGH */
+		/* FALLTHROUGH */
 	case NV_TYPE_INT32:
 	case NV_TYPE_UINT32:
 	case NV_TYPE_INT32_ARRAY:
 	case NV_TYPE_UINT32_ARRAY:
 		if (vsize =3D=3D 0)
 			vsize =3D 4;
-		/* FALLTHOUGH */
+		/* FALLTHROUGH */
 	case NV_TYPE_INT64:
 	case NV_TYPE_UINT64:
 	case NV_TYPE_INT64_ARRAY:
diff -r 428842767fa6 -r f2935497fa04 head/sbin/ifconfig/ifconfig.8
--- a/head/sbin/ifconfig/ifconfig.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/ifconfig/ifconfig.8	Tue Apr 17 11:51:51 2012 +0300
@@ -26,9 +26,9 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)ifconfig.8	8.3 (Berkeley) 1/5/94
-.\" $FreeBSD: head/sbin/ifconfig/ifconfig.8 232638 2012-03-07 06:25:17Z th=
ompsa $
+.\" $FreeBSD: head/sbin/ifconfig/ifconfig.8 233993 2012-04-07 09:11:07Z jo=
el $
 .\"
-.Dd March 7, 2012
+.Dd April 3, 2012
 .Dt IFCONFIG 8
 .Os
 .Sh NAME
@@ -675,7 +675,7 @@
 .It Cm -ifdisabled
 Clear a flag
 .Cm ifdisabled .
-When this flag is cleared and=20
+When this flag is cleared and
 .Cm auto_linklocal
 flag is enabled, automatic configuration of a link-local address is
 performed.
@@ -706,7 +706,7 @@
 .Ar mode
 is one of
 .Cm sta ,
-.Cm ahdemo=20
+.Cm ahdemo
 (or
 .Cm adhoc-demo ),
 .Cm ibss ,
@@ -744,7 +744,7 @@
 Mark a
 .Cm wds
 device as operating in ``legacy mode''.
-Legacy=20
+Legacy
 .Cm wds
 devices have a fixed peer relationship and do not, for example, roam
 if their peer stops communicating.
@@ -760,9 +760,9 @@
 track received beacons.
 To have beacons tracked in software use
 .Fl beacons .
-For=20
+For
 .Cm hostap
-mode=20
+mode
 .Fl beacons
 can also be used to indicate no beacons should
 be transmitted; this can be useful when creating a WDS configuration but
@@ -897,7 +897,7 @@
 .Ar interval
 parameter is specified in seconds.
 By default a background scan is considered every 300 seconds (5 minutes).
-The=20
+The
 .Ar interval
 may not be set to less than 15 seconds.
 .It Cm bintval Ar interval
@@ -998,19 +998,19 @@
 .Cm t
 (Atheros Dynamic Turbo mode, or appended to ``st'' and ``dt'').
 The full set of channel widths following a '/' are:
-.Cm 5=20
+.Cm 5
 (5MHz aka quarter-rate channel),
-.Cm 10=20
+.Cm 10
 (10MHz aka half-rate channel),
-.Cm 20=20
+.Cm 20
 (20MHz mostly for use in specifying ht20),
 and
-.Cm 40=20
+.Cm 40
 (40MHz mostly for use in specifying ht40).
 In addition,
 a 40MHz HT channel specification may include the location
 of the extension channel by appending ``+'' or ``-'' for above and below,
-respectively; e.g. ``2437:ht/40+'' specifies 40MHz wide HT operation=20
+respectively; e.g. ``2437:ht/40+'' specifies 40MHz wide HT operation
 with the center channel at frequency 2437 and the extension channel above.
 .It Cm country Ar name
 Set the country code to use in calculating the regulatory constraints
@@ -2021,7 +2021,7 @@
 discover a path to us.
 .El
 By default
-.Cm hwmprootmode=20
+.Cm hwmprootmode
 is set to
 .Ar DISABLED .
 .It Cm hwmpmaxhops Ar cnt
@@ -2380,10 +2380,28 @@
 .Xr pfsync 4
 interfaces:
 .Bl -tag -width indent
+.It Cm syncdev Ar iface
+Use the specified interface
+to send and receive pfsync state synchronisation messages.
+.It Fl syncdev
+Stop sending pfsync state synchronisation messages over the network.
+.It Cm syncpeer Ar peer_address
+Make the pfsync link point-to-point rather than using
+multicast to broadcast the state synchronisation messages.
+The peer_address is the IP address of the other host taking part in
+the pfsync cluster.
+.It Fl syncpeer
+Broadcast the packets using multicast.
 .It Cm maxupd Ar n
 Set the maximum number of updates for a single state which
 can be collapsed into one.
 This is an 8-bit number; the default value is 128.
+.It Cm defer
+Defer transmission of the first packet in a state until a peer has
+acknowledged that the associated state has been inserted.
+.It Fl defer
+Do not defer the first packet in a state.
+This is the default.
 .El
 .Pp
 The following parameters are specific to
@@ -2569,7 +2587,7 @@
 passphrases will be printed, if accessible to the current user.
 This information is not printed by default, as it may be considered
 sensitive.
-.Pp=20
+.Pp
 If the network interface driver is not present in the kernel then
 .Nm
 will attempt to load it.
diff -r 428842767fa6 -r f2935497fa04 head/sbin/ifconfig/ifieee80211.c
--- a/head/sbin/ifconfig/ifieee80211.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/ifconfig/ifieee80211.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sbin/ifconfig/ifieee80211.c 229914 2012-01-10 02:59:18Z =
eadler $
+ * $FreeBSD: head/sbin/ifconfig/ifieee80211.c 233382 2012-03-23 18:12:25Z =
bschmidt $
  */
=20
 /*-
@@ -1879,13 +1879,13 @@
 static
 DECL_CMD_FUNC(set80211meshforward, val, d)
 {
-	set80211(s, IEEE80211_IOC_MESH_FWRD, atoi(val), 0, NULL);
+	set80211(s, IEEE80211_IOC_MESH_FWRD, d, 0, NULL);
 }
=20
 static
 DECL_CMD_FUNC(set80211meshpeering, val, d)
 {
-	set80211(s, IEEE80211_IOC_MESH_AP, atoi(val), 0, NULL);
+	set80211(s, IEEE80211_IOC_MESH_AP, d, 0, NULL);
 }
=20
 static
diff -r 428842767fa6 -r f2935497fa04 head/sbin/ifconfig/ifpfsync.c
--- a/head/sbin/ifconfig/ifpfsync.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/ifconfig/ifpfsync.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sbin/ifconfig/ifpfsync.c 233847 2012-04-03 18:10:48Z gle=
bius $
  */
=20
 #include <sys/types.h>
@@ -52,6 +52,7 @@
 void unsetpfsync_syncpeer(const char *, int, int, const struct afswtch *);
 void setpfsync_syncpeer(const char *, int, int, const struct afswtch *);
 void setpfsync_maxupd(const char *, int, int, const struct afswtch *);
+void setpfsync_defer(const char *, int, int, const struct afswtch *);
 void pfsync_status(int);
=20
 void
@@ -162,6 +163,23 @@
 		err(1, "SIOCSETPFSYNC");
 }
=20
+/* ARGSUSED */
+void
+setpfsync_defer(const char *val, int d, int s, const struct afswtch *rafp)
+{
+	struct pfsyncreq preq;
+
+	memset((char *)&preq, 0, sizeof(struct pfsyncreq));
+	ifr.ifr_data =3D (caddr_t)&preq;
+
+	if (ioctl(s, SIOCGETPFSYNC, (caddr_t)&ifr) =3D=3D -1)
+		err(1, "SIOCGETPFSYNC");
+
+	preq.pfsyncr_defer =3D d;
+	if (ioctl(s, SIOCSETPFSYNC, (caddr_t)&ifr) =3D=3D -1)
+		err(1, "SIOCSETPFSYNC");
+}
+
 void
 pfsync_status(int s)
 {
@@ -183,8 +201,10 @@
 		printf("syncpeer: %s ", inet_ntoa(preq.pfsyncr_syncpeer));
=20
 	if (preq.pfsyncr_syncdev[0] !=3D '\0' ||
-	    preq.pfsyncr_syncpeer.s_addr !=3D INADDR_PFSYNC_GROUP)
-		printf("maxupd: %d\n", preq.pfsyncr_maxupdates);
+	    preq.pfsyncr_syncpeer.s_addr !=3D INADDR_PFSYNC_GROUP) {
+		printf("maxupd: %d ", preq.pfsyncr_maxupdates);
+		printf("defer: %s\n", preq.pfsyncr_defer ? "on" : "off");
+	}
 }
=20
 static struct cmd pfsync_cmds[] =3D {
@@ -194,7 +214,9 @@
 	DEF_CMD("-syncif",	1,	unsetpfsync_syncdev),
 	DEF_CMD_ARG("syncpeer",		setpfsync_syncpeer),
 	DEF_CMD("-syncpeer",	1,	unsetpfsync_syncpeer),
-	DEF_CMD_ARG("maxupd",		setpfsync_maxupd)
+	DEF_CMD_ARG("maxupd",		setpfsync_maxupd),
+	DEF_CMD("defer",	1,	setpfsync_defer),
+	DEF_CMD("-defer",	0,	setpfsync_defer),
 };
 static struct afswtch af_pfsync =3D {
 	.af_name	=3D "af_pfsync",
diff -r 428842767fa6 -r f2935497fa04 head/sbin/init/init.8
--- a/head/sbin/init/init.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/init/init.8	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)init.8	8.3 (Berkeley) 4/18/94
-.\" $FreeBSD: head/sbin/init/init.8 232977 2012-03-14 16:22:09Z ed $
+.\" $FreeBSD: head/sbin/init/init.8 233510 2012-03-26 15:18:14Z joel $
 .\"
 .Dd March 14, 2012
 .Dt INIT 8
@@ -283,7 +283,7 @@
 .Nm
 as follows:
 .Bl -column Run-level SIGTERM
-.It Sy "Run-level	Signal	Action
+.It Sy "Run-level	Signal	Action"
 .It Cm 0 Ta Dv SIGUSR2 Ta "Halt and turn the power off"
 .It Cm 1 Ta Dv SIGTERM Ta "Go to single-user mode"
 .It Cm 6 Ta Dv SIGINT Ta "Reboot the machine"
diff -r 428842767fa6 -r f2935497fa04 head/sbin/init/init.c
--- a/head/sbin/init/init.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/init/init.c	Tue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
 static char sccsid[] =3D "@(#)init.c	8.1 (Berkeley) 7/15/93";
 #endif
 static const char rcsid[] =3D
-  "$FreeBSD: head/sbin/init/init.c 232977 2012-03-14 16:22:09Z ed $";
+  "$FreeBSD: head/sbin/init/init.c 233945 2012-04-06 13:06:01Z ed $";
 #endif /* not lint */
=20
 #include <sys/param.h>
@@ -572,9 +572,13 @@
 {
 	int fd;
=20
-	/* Try to open /dev/console. */
+	/*
+	 * Try to open /dev/console.  Open the device with O_NONBLOCK to
+	 * prevent potential blocking on a carrier.
+	 */
 	revoke(_PATH_CONSOLE);
 	if ((fd =3D open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) !=3D -1) {
+		(void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
 		if (login_tty(fd) =3D=3D 0)
 			return;
 		close(fd);
diff -r 428842767fa6 -r f2935497fa04 head/sbin/ipfw/ipfw.8
--- a/head/sbin/ipfw/ipfw.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/ipfw/ipfw.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 .\"
-.\" $FreeBSD: head/sbin/ipfw/ipfw.8 232865 2012-03-12 14:07:57Z melifaro $
+.\" $FreeBSD: head/sbin/ipfw/ipfw.8 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd March 9, 2012
 .Dt IPFW 8
@@ -40,14 +40,12 @@
 .Nm
 .Cm set show
 .Ss SYSCTL SHORTCUTS
-.Pp
 .Nm
 .Cm enable
 .Brq Cm firewall | altq | one_pass | debug | verbose | dyn_keepalive
 .Nm
 .Cm disable
 .Brq Cm firewall | altq | one_pass | debug | verbose | dyn_keepalive
-.Pp
 .Ss LOOKUP TABLES
 .Nm
 .Cm table Ar number Cm add Ar addr Ns Oo / Ns Ar masklen Oc Op Ar value
@@ -61,7 +59,6 @@
 .Cm table
 .Brq Ar number | all
 .Cm list
-.Pp
 .Ss DUMMYNET CONFIGURATION (TRAFFIC SHAPER AND PACKET SCHEDULER)
 .Nm
 .Brq Cm pipe | queue | sched
@@ -73,7 +70,6 @@
 .Brq Cm pipe | queue | sched
 .Brq Cm delete | list | show
 .Op Ar number ...
-.Pp
 .Ss IN-KERNEL NAT
 .Nm
 .Op Fl q
@@ -285,7 +281,6 @@
 When listing, show last match timestamp as seconds from the epoch.
 This form can be more convenient for postprocessing by scripts.
 .El
-.Pp
 .Ss LIST OF RULES AND PREPROCESSING
 To ease configuration, rules can be put into a file which is
 processed using
@@ -325,7 +320,6 @@
 This allows for flexible configuration files (like conditionalizing
 them on the local hostname) and the use of macros to centralize
 frequently required arguments like IP addresses.
-.Pp
 .Ss TRAFFIC SHAPER CONFIGURATION
 The
 .Nm
@@ -566,7 +560,7 @@
 .Xr bpf 4
 attached to the
 .Li ipfw0
-pseudo interface. There is no overhead if no=20
+pseudo interface. There is no overhead if no
 .Xr bpf 4
 is attached to the pseudo interface.
 .Pp
@@ -814,13 +808,13 @@
 The search continues with the first rule numbered
 .Ar number
 or higher.
-It is possible to use the=20
+It is possible to use the
 .Cm tablearg
-keyword with a skipto for a=20
+keyword with a skipto for a
 .Em computed
 skipto, but care should be used, as no destination caching
 is possible in this case so the rules are always walked to find it,
-starting from the=20
+starting from the
 .Cm skipto .
 .It Cm call Ar number | tablearg
 The current rule number is saved in the internal stack and
@@ -884,7 +878,6 @@
 A workaround for this is to use new syntax and
 .Fl c
 switch:
-.Pp
 .Bd -literal -offset indent
 # Add a rule without actual body
 ipfw add 2999 return via any
@@ -950,7 +943,7 @@
 Initially this is limited to the values 0 through 15, see
 .Xr setfib 1 .
 Processing continues at the next rule.
-It is possible to use the=20
+It is possible to use the
 .Cm tablearg
 keyword with a setfib. If tablearg value is not within compiled FIB range =
packet fib is set to 0.
 .It Cm reass
@@ -971,7 +964,7 @@
 NOTA BENE: since fragments do not contain port numbers, they should be avo=
ided with the
 .Nm reass
 rule.
-Alternatively, direction-based (like=20
+Alternatively, direction-based (like
 .Nm in
 /
 .Nm out
@@ -1806,7 +1799,7 @@
 .Cm skipto
 action, the user should be aware that the code will walk the ruleset
 up to a rule equal to, or past, the given number, and should therefore try=
 keep the
-ruleset compact between the skipto and the target rules.=20
+ruleset compact between the skipto and the target rules.
 .Sh SETS OF RULES
 Each rule belongs to one of 32 different
 .Em sets
@@ -2471,7 +2464,6 @@
 not loaded, or if the kernel was not compiled with divert socket support,
 the packets are dropped.
 .Sh NETWORK ADDRESS TRANSLATION (NAT)
-.Pp
 .Nm
 support in-kernel NAT using the kernel version of
 .Xr libalias 3 .
@@ -2479,9 +2471,9 @@
 The nat configuration command is the following:
 .Bd -ragged -offset indent
 .Bk -words
-.Cm nat=20
-.Ar nat_number=20
-.Cm config=20
+.Cm nat
+.Ar nat_number
+.Cm config
 .Ar nat-configuration
 .Ek
 .Ed
@@ -2533,7 +2525,7 @@
 .El
 .Pp
 To let the packet continue after being (de)aliased, set the sysctl variable
-.Va net.inet.ip.fw.one_pass=20
+.Va net.inet.ip.fw.one_pass
 to 0.
 For more information about aliasing modes, refer to
 .Xr libalias 3 .
@@ -2542,7 +2534,7 @@
 for some examples about nat usage.
 .Ss REDIRECT AND LSNAT SUPPORT IN IPFW
 Redirect and LSNAT support follow closely the syntax used in
-.Xr natd 8 .=20
+.Xr natd 8 .
 See Section
 .Sx EXAMPLES
 for some examples on how to do redirect and lsnat.
@@ -2550,16 +2542,16 @@
 SCTP nat can be configured in a similar manner to TCP through the
 .Nm
 command line tool.
-The main difference is that=20
-.Nm sctp nat=20
+The main difference is that
+.Nm sctp nat
 does not do port translation.
 Since the local and global side ports will be the same,
 there is no need to specify both.
 Ports are redirected as follows:
 .Bd -ragged -offset indent
 .Bk -words
-.Cm nat=20
-.Ar nat_number=20
+.Cm nat
+.Ar nat_number
 .Cm config if
 .Ar nic
 .Cm redirect_port sctp
@@ -2577,9 +2569,9 @@
 .Nm nat
 instances.
 See
-.Sx SYSCTL VARIABLES=20
+.Sx SYSCTL VARIABLES
 for more info.
-.Sh LOADER TUNABLES=20
+.Sh LOADER TUNABLES
 Tunables can be set in
 .Xr loader 8
 prompt,
@@ -2607,15 +2599,15 @@
 command what value is actually in use) and meaning:
 .Bl -tag -width indent
 .It Va net.inet.ip.alias.sctp.accept_global_ootb_addip: No 0
-Defines how the=20
-.Nm nat=20
+Defines how the
+.Nm nat
 responds to receipt of global OOTB ASCONF-AddIP:
 .Bl -tag -width indent
 .It Cm 0
 No response (unless a partially matching association exists -
 ports and vtags match but global address does not)
 .It Cm 1
-.Nm nat=20
+.Nm nat
 will accept and process all OOTB global AddIP messages.
 .El
 .Pp
@@ -2625,18 +2617,18 @@
 .It Va net.inet.ip.alias.sctp.chunk_proc_limit: No 5
 Defines the maximum number of chunks in an SCTP packet that will be parsed=
 for a
 packet that matches an existing association.
-This value is enforced to be greater or equal than=20
-.Cm net.inet.ip.alias.sctp.initialising_chunk_proc_limit .=20
+This value is enforced to be greater or equal than
+.Cm net.inet.ip.alias.sctp.initialising_chunk_proc_limit .
 A high value is
 a DoS risk yet setting too low a value may result in important control chu=
nks in
 the packet not being located and parsed.
 .It Va net.inet.ip.alias.sctp.error_on_ootb: No 1
 Defines when the
-.Nm nat=20
+.Nm nat
 responds to any Out-of-the-Blue (OOTB) packets with ErrorM packets.
 An OOTB packet is a packet that arrives with no existing association
 registered in the
-.Nm nat=20
+.Nm nat
 and is not an INIT or ASCONF-AddIP packet:
 .Bl -tag -width indent
 .It Cm 0
@@ -2646,8 +2638,8 @@
 .It Cm 2
 ErrorM is sent to the local side and on the global side ONLY if there is a
 partial match (ports and vtags match but the source global IP does not).
-This value is only useful if the=20
-.Nm nat=20
+This value is only useful if the
+.Nm nat
 is tracking global IP addresses.
 .It Cm 3
 ErrorM is sent in response to all OOTB packets on both the local and globa=
l side
@@ -2658,24 +2650,24 @@
 supported by most SCTP stacks.
 When it is supported, and if not tracking
 global addresses, we recommend setting this value to 1 to allow
-multi-homed local hosts to function with the=20
+multi-homed local hosts to function with the
 .Nm nat .
 To track global addresses, we recommend setting this value to 2 to
 allow global hosts to be informed when they need to (re)send an
 ASCONF-AddIP.
 Value 3 should never be chosen (except for debugging) as the
-.Nm nat=20
+.Nm nat
 will respond to all OOTB global packets (a DoS risk).
 .It Va net.inet.ip.alias.sctp.hashtable_size: No 2003
-Size of hash tables used for=20
-.Nm nat=20
+Size of hash tables used for
+.Nm nat
 lookups (100 < prime_number > 1000001).
-This value sets the=20
-.Nm hash table=20
-size for any future created=20
+This value sets the
+.Nm hash table
+size for any future created
 .Nm nat
-instance and therefore must be set prior to creating a=20
-.Nm nat=20
+instance and therefore must be set prior to creating a
+.Nm nat
 instance.
 The table sizes may be changed to suit specific needs.
 If there will be few
@@ -2704,7 +2696,7 @@
 Defines the maximum number of parameters within a chunk that will be parse=
d in a
 packet.
 As for other similar sysctl variables, larger values pose a DoS risk.
-.It Va net.inet.ip.alias.sctp.log_level: No 0=20
+.It Va net.inet.ip.alias.sctp.log_level: No 0
 Level of detail in the system log messages (0 \- minimal, 1 \- event,
 2 \- info, 3 \- detail, 4 \- debug, 5 \- max debug). May be a good
 option in high loss environments.
@@ -2712,8 +2704,8 @@
 Timeout value while waiting for SHUTDOWN-COMPLETE.
 This value cannot be 0.
 .It Va net.inet.ip.alias.sctp.track_global_addresses: No 0
-Enables/disables global IP address tracking within the=20
-.Nm nat=20
+Enables/disables global IP address tracking within the
+.Nm nat
 and places an
 upper limit on the number of addresses tracked for each association:
 .Bl -tag -width indent
@@ -2726,16 +2718,16 @@
 .Pp
 This variable is fully dynamic, the new value will be adopted for all newly
 arriving associations, existing associations are treated as they were prev=
iously.
-Global tracking will decrease the number of collisions within the=20
-.Nm nat=20
+Global tracking will decrease the number of collisions within the
+.Nm nat
 at a cost
-of increased processing load, memory usage, complexity, and possible=20
-.Nm nat=20
+of increased processing load, memory usage, complexity, and possible
+.Nm nat
 state
-problems in complex networks with multiple=20
-.Nm nats .=20
+problems in complex networks with multiple
+.Nm nats .
 We recommend not tracking
-global IP addresses, this will still result in a fully functional=20
+global IP addresses, this will still result in a fully functional
 .Nm nat .
 .It Va net.inet.ip.alias.sctp.up_timer: No 300
 Timeout value to keep an association up with no traffic.
@@ -2853,7 +2845,7 @@
 Otherwise, after an action, the packet is
 reinjected into the firewall at the next rule.
 .It Va net.inet.ip.fw.tables_max : No 128
-Maximum number of tables (read-only).
+Maximum number of tables.
 .It Va net.inet.ip.fw.verbose : No 1
 Enables verbose messages.
 .It Va net.inet.ip.fw.verbose_limit : No 0
@@ -2869,7 +2861,6 @@
 .Nm .
 Default is no.
 .El
-.Pp
 .Sh EXAMPLES
 There are far too many possible uses of
 .Nm
@@ -3007,7 +2998,6 @@
 to divert port 5000:
 .Pp
 .Dl ipfw divert 5000 ip from 192.168.2.0/24 to any in
-.Pp
 .Ss TRAFFIC SHAPING
 The following rules show some of the applications of
 .Nm
@@ -3183,7 +3173,7 @@
 .Pp
 Then to configure nat instance 123 to alias all the outgoing traffic with =
ip
 192.168.0.123, blocking all incoming connections, trying to keep
-same ports on both sides, clearing aliasing table on address change=20
+same ports on both sides, clearing aliasing table on address change
 and keeping a log of traffic/link statistics:
 .Pp
 .Dl "ipfw nat 123 config ip 192.168.0.123 log deny_in reset same_ports"
@@ -3212,7 +3202,7 @@
 .Dl "			 redirect_proto udp 192.168.1.43 192.168.1.1"
 .Dl "			 redirect_addr 192.168.0.10,192.168.0.11"
 .Dl "			 	    10.0.0.100	# LSNAT"
-.Dl "			 redirect_port tcp 192.168.0.1:80,192.168.0.10:22"=20
+.Dl "			 redirect_port tcp 192.168.0.1:80,192.168.0.10:22"
 .Dl "			 	    500		# LSNAT"
 .Pp
 or it could be split in:
@@ -3220,11 +3210,10 @@
 .Dl "ipfw nat 1 config redirect_addr 10.0.0.1 10.0.0.66"
 .Dl "ipfw nat 2 config redirect_port tcp 192.168.0.1:80 500"
 .Dl "ipfw nat 3 config redirect_proto udp 192.168.1.43 192.168.1.1"
-.Dl "ipfw nat 4 config redirect_addr 192.168.0.10,192.168.0.11,192.168.0.1=
2"=20
+.Dl "ipfw nat 4 config redirect_addr 192.168.0.10,192.168.0.11,192.168.0.1=
2"
 .Dl "				         10.0.0.100"
 .Dl "ipfw nat 5 config redirect_port tcp"
 .Dl "			192.168.0.1:80,192.168.0.10:22,192.168.0.20:25 500"
-.Pp
 .Sh SEE ALSO
 .Xr cpp 1 ,
 .Xr m4 1 ,
@@ -3341,8 +3330,8 @@
 may need to be escaped with the backslash character
 or quoted appropriately.
 .Pp
-Due to the architecture of=20
-.Xr libalias 3 ,=20
+Due to the architecture of
+.Xr libalias 3 ,
 ipfw nat is not compatible with the TCP segmentation offloading (TSO).
 Thus, to reliably nat your network traffic, please disable TSO
 on your NICs using
diff -r 428842767fa6 -r f2935497fa04 head/sbin/ipfw/ipfw2.c
--- a/head/sbin/ipfw/ipfw2.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/ipfw/ipfw2.c	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
  *
  * NEW command line interface for IP firewall facility
  *
- * $FreeBSD: head/sbin/ipfw/ipfw2.c 232865 2012-03-12 14:07:57Z melifaro $
+ * $FreeBSD: head/sbin/ipfw/ipfw2.c 233478 2012-03-25 20:37:59Z melifaro $
  */
=20
 #include <sys/types.h>
@@ -3932,15 +3932,9 @@
=20
 	len =3D sizeof(tables_max);
 	if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
-		NULL, 0) =3D=3D -1) {
-#ifdef IPFW_TABLES_MAX
-		warn("Warn: Failed to get the max tables number via sysctl. "
-		     "Using the compiled in defaults. \nThe reason was");
-		tables_max =3D IPFW_TABLES_MAX;
-#else
-		errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
-#endif
-	}
+		NULL, 0) =3D=3D -1)
+		errx(1, "Can't determine maximum number of ipfw tables. "
+		    "Perhaps you forgot to load ipfw module?");
=20
 	memset(&xent, 0, sizeof(xent));
=20
diff -r 428842767fa6 -r f2935497fa04 head/sbin/iscontrol/Makefile
--- a/head/sbin/iscontrol/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/iscontrol/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sbin/iscontrol/Makefile 234233 2012-04-13 18:21:56Z jpaet=
zel $
=20
 SRCS=3D iscontrol.c pdu.c fsm.c config.c login.c auth_subr.c misc.c
 PROG=3D iscontrol
@@ -8,7 +8,7 @@
=20
 WARNS?=3D	3
 CFLAGS +=3D -I$S
-#CFLAGS +=3D -g -DDEBUG
+CFLAGS +=3D -g -DDEBUG
=20
 MAN=3D iscsi.conf.5 iscontrol.8
=20
diff -r 428842767fa6 -r f2935497fa04 head/sbin/iscontrol/iscontrol.8
--- a/head/sbin/iscontrol/iscontrol.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/iscontrol/iscontrol.8	Tue Apr 17 11:51:51 2012 +0300
@@ -22,9 +22,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/iscontrol/iscontrol.8 234233 2012-04-13 18:21:56Z =
jpaetzel $
 .\"
-.Dd February 22, 2007
+.Dd August 9, 2010
 .Dt ISCONTROL 8
 .Os
 .Sh NAME
diff -r 428842767fa6 -r f2935497fa04 head/sbin/iscontrol/iscontrol.c
--- a/head/sbin/iscontrol/iscontrol.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/iscontrol/iscontrol.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sbin/iscontrol/iscontrol.c 234233 2012-04-13 18:2=
1:56Z jpaetzel $");
=20
 #include <sys/param.h>
 #include <sys/types.h>
@@ -56,6 +56,8 @@
 #include <dev/iscsi/initiator/iscsi.h>
 #include "iscontrol.h"
=20
+static char version[] =3D "2.3.1"; // keep in sync with iscsi_initiator
+
 #define USAGE "[-v] [-d] [-c config] [-n name] [-t target] [-p pidfile]"
 #define OPTIONS	"vdc:t:n:p:"
=20
@@ -124,9 +126,10 @@
 main(int cc, char **vv)
 {
      int	ch, disco;
-     char	*pname, *pidfile, *p, *q, *ta, *kw;
+     char	*pname, *pidfile, *p, *q, *ta, *kw, *v;
      isc_opt_t	*op;
      FILE	*fd;
+     size_t	n;
=20
      op =3D &opvals;
      iscsidev =3D "/dev/"ISCSIDEV;
@@ -138,6 +141,21 @@
      kw =3D ta =3D 0;
      disco =3D 0;
      pidfile =3D NULL;
+     /*
+      | check for driver & controller version match
+      */
+     n =3D 0;
+     if(sysctlbyname("net.iscsi_initiator.driver_version", 0, &n, 0, 0) !=
=3D 0)
+	  perror("sysctlbyname");
+     v =3D malloc(n+1);
+     if(sysctlbyname("net.iscsi_initiator.driver_version", v, &n, 0, 0) !=
=3D 0)
+	  perror("sysctlbyname");
+
+     if(strncmp(version, v, 3)) {
+	  fprintf(stderr, "versions missmatch\n");
+	  exit(1);
+     }
+
=20
      while((ch =3D getopt(cc, vv, OPTIONS)) !=3D -1) {
 	  switch(ch) {
diff -r 428842767fa6 -r f2935497fa04 head/sbin/iscontrol/iscsi.conf.5
--- a/head/sbin/iscontrol/iscsi.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/iscontrol/iscsi.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -22,9 +22,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/iscontrol/iscsi.conf.5 232158 2012-02-25 15:21:43Z=
 gjb $
+.\" $FreeBSD: head/sbin/iscontrol/iscsi.conf.5 234233 2012-04-13 18:21:56Z=
 jpaetzel $
 .\"
-.Dd February 25, 2012
+.Dd June 5, 2007
 .Dt ISCSI.CONF 5
 .Os
 .Sh NAME
diff -r 428842767fa6 -r f2935497fa04 head/sbin/kldload/kldload.8
--- a/head/sbin/kldload/kldload.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/kldload/kldload.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/kldload/kldload.8 233109 2012-03-18 09:45:43Z hsel=
asky $
+.\" $FreeBSD: head/sbin/kldload/kldload.8 233458 2012-03-25 09:21:09Z joel=
 $
 .\"
 .Dd March 18, 2012
 .Dt KLDLOAD 8
@@ -70,7 +70,6 @@
 Silence any extraneous warnings.
 .El
 .Sh NOTES
-.Pp
 The kernel security level settings may prevent a module from being
 loaded or unloaded by giving
 .Em "Operation not permitted" .
diff -r 428842767fa6 -r f2935497fa04 head/sbin/mdconfig/mdconfig.8
--- a/head/sbin/mdconfig/mdconfig.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/mdconfig/mdconfig.8	Tue Apr 17 11:51:51 2012 +0300
@@ -39,9 +39,9 @@
 .\"     @(#)vnconfig.8	8.1 (Berkeley) 6/5/93
 .\" from: src/usr.sbin/vnconfig/vnconfig.8,v 1.19 2000/12/27 15:30:29
 .\"
-.\" $FreeBSD: head/sbin/mdconfig/mdconfig.8 221232 2011-04-29 22:40:11Z de=
s $
+.\" $FreeBSD: head/sbin/mdconfig/mdconfig.8 234047 2012-04-09 01:20:50Z bj=
k $
 .\"
-.Dd June 21, 2008
+.Dd March 21, 2012
 .Dt MDCONFIG 8
 .Os
 .Sh NAME
@@ -87,7 +87,7 @@
 Detach a memory disk from the system and release all resources.
 .It Fl t Ar type
 Select the type of the memory disk.
-.Bl -tag -width "preload"
+.Bl -tag -width "malloc"
 .It Cm malloc
 Storage for this type of memory disk is allocated with
 .Xr malloc 9 .
@@ -104,31 +104,35 @@
 .It Cm swap
 Storage for this type of memory disk is allocated from buffer
 memory.
-Pages get pushed out to the swap when the system is under memory
+Pages get pushed out to swap when the system is under memory
 pressure, otherwise they stay in the operating memory.
 Using
 .Cm swap
-backing is generally preferable over
+backing is generally preferred instead of using
 .Cm malloc
 backing.
 .El
 .It Fl f Ar file
-Filename to use for the vnode type memory disk. Options
+Filename to use for the vnode type memory disk.
+The
 .Fl a
 and
 .Fl t Ar vnode
-are implied if not specified.
+options are implied if not specified.
 .It Fl l
 List configured devices.
 If given with
 .Fl u ,
 display details about that particular device.
-If
+If the
 .Fl v
-option specified, show all details.
+option is specified, show all details.
 .It Fl n
-When printing md device names, print only the unit number without the
-md prefix.
+When printing=20
+.Xr md 4
+device names, print only the unit number without the
+.Xr md 4
+prefix.
 .It Fl s Ar size
 Size of the memory disk.
 .Ar Size
@@ -137,11 +141,12 @@
 or
 .Cm t
 which
-denotes byte, kilobyte, megabyte, gigabyte and terabyte respectively. Opti=
ons
+denotes byte, kilobyte, megabyte, gigabyte and terabyte respectively.
+The
 .Fl a
 and
 .Fl t Ar swap
-are implied if not specified.
+options are implied if not specified.
 .It Fl S Ar sectorsize
 Sectorsize to use for malloc backed device.
 .It Fl x Ar sectors/track
@@ -175,12 +180,12 @@
 .It Oo Cm no Oc Ns Cm cluster
 Enable clustering on this disk.
 .It Oo Cm no Oc Ns Cm compress
-Enable/Disable compression features to reduce memory usage.
+Enable/disable compression features to reduce memory usage.
 .It Oo Cm no Oc Ns Cm force
-Disable/Enable extra sanity checks to prevent the user from doing something
+Disable/enable extra sanity checks to prevent the user from doing something
 that might adversely affect the system.
 .It Oo Cm no Oc Ns Cm readonly
-Enable/Disable readonly mode.
+Enable/disable readonly mode.
 .El
 .It Fl u Ar unit
 Request a specific unit number for the
@@ -197,15 +202,15 @@
 .Fl t Ar vnode
 .Fl f Ar file .
 .Sh EXAMPLES
-To create a 4 megabyte
+Create a 4 megabyte
 .Xr malloc 9
 backed memory disk.
-The name of the allocated unit will be output on stdout like
+The name of the allocated unit will be printed on stdout, such as
 .Dq Li md3 :
 .Pp
 .Dl mdconfig -a -t malloc -s 4m
 .Pp
-To create a disk named
+Create a disk named
 .Pa /dev/md4
 with
 .Pa /tmp/boot.flp
@@ -213,12 +218,12 @@
 .Pp
 .Dl mdconfig -a -t vnode -f /tmp/boot.flp -u 4
 .Pp
-To detach and free all resources used by
+Detach and free all resources used by
 .Pa /dev/md4 :
 .Pp
 .Dl mdconfig -d -u 4
 .Pp
-To create a 128MByte swap backed disk, initialize an
+Create a 128MByte swap backed disk, initialize an
 .Xr ffs 7
 file system on it, and mount it on
 .Pa /tmp :
@@ -229,7 +234,7 @@
 chmod 1777 /tmp
 .Ed
 .Pp
-To create a 5MB file-backed disk
+Create a 5MB file-backed disk
 .Ns ( Fl a
 and
 .Fl t Ar vnode
@@ -242,7 +247,7 @@
 mount /dev/md0c /mnt
 .Ed
 .Pp
-To create an
+Create an
 .Xr md 4
 device out of an ISO 9660 CD image file
 .Ns ( Fl a
diff -r 428842767fa6 -r f2935497fa04 head/sbin/mdmfs/mdmfs.8
--- a/head/sbin/mdmfs/mdmfs.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/mdmfs/mdmfs.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/mdmfs/mdmfs.8 225416 2011-09-06 10:19:01Z kib $
+.\" $FreeBSD: head/sbin/mdmfs/mdmfs.8 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd September 4, 2011
 .Dt MDMFS 8
@@ -40,7 +40,7 @@
 .Op Fl a Ar maxcontig
 .Op Fl b Ar block-size
 .Op Fl c Ar blocks-per-cylinder-group
-.Op Fl d Ar max-extent-size=20
+.Op Fl d Ar max-extent-size
 .Op Fl E Ar path-mdconfig
 .Op Fl e Ar maxbpg
 .Op Fl F Ar file
@@ -75,8 +75,8 @@
 .Xr newfs 8 ,
 and mounts it using
 .Xr mount 8 .
-It can handle=20
-.Xr geom_uzip 4=20
+It can handle
+.Xr geom_uzip 4
 compressed disk images, as long as the kernel supports this GEOM class.
 All the command line options are passed to the appropriate program
 at the appropriate stage in order to achieve the desired effect.
@@ -318,7 +318,7 @@
 .Pp
 .Dl "mdmfs -M -S -o async -s 16m md1 /tmp"
 .Pp
-Create and mount a=20
+Create and mount a
 .Xr geom_uzip 4
 based compressed disk image:
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/sbin/mount_unionfs/mount_unionfs.8
--- a/head/sbin/mount_unionfs/mount_unionfs.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/mount_unionfs/mount_unionfs.8	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)mount_union.8	8.6 (Berkeley) 3/27/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/mount_unionfs/mount_unionfs.8 233648 2012-03-29 05=
:02:12Z eadler $
 .\"
 .Dd November 30, 2006
 .Dt MOUNT_UNIONFS 8
@@ -366,7 +366,7 @@
 objects can be done.
 .Er EOPNOTSUPP
 is returned for this kind of operations as generated by VOP_WHITEOUT()
-along with any others which would make modifications to the lower=20
+along with any others which would make modifications to the lower
 layer, such as
 .Xr chmod 1 .
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/sbin/ping6/ping6.8
--- a/head/sbin/ping6/ping6.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/ping6/ping6.8	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/ping6/ping6.8 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd April 20, 2010
 .Dt PING6 8
@@ -428,8 +428,8 @@
 .Nm
 utility returns 0 on success (the host is alive),
 2 if the transmission was successful but no responses were received,
-any other non-zero value if the arguments are incorrect or                =
                                           =20
-another error has occurred.                                               =
                                            =20
+any other non-zero value if the arguments are incorrect or
+another error has occurred.
 .Sh EXAMPLES
 Normally,
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/sbin/quotacheck/quotacheck.8
--- a/head/sbin/quotacheck/quotacheck.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/quotacheck/quotacheck.8	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)quotacheck.8	8.1 (Berkeley) 6/5/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/quotacheck/quotacheck.8 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd January 25, 2007
 .Dt QUOTACHECK 8
@@ -158,7 +158,7 @@
 .Ar enable_quotas
 in
 .Pa /etc/rc.conf .
-The kernel must also be built with=20
+The kernel must also be built with
 .Cd "options QUOTA" .
 .Pp
 The
diff -r 428842767fa6 -r f2935497fa04 head/sbin/rcorder/rcorder.8
--- a/head/sbin/rcorder/rcorder.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/rcorder/rcorder.8	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/rcorder/rcorder.8 224673 2011-08-06 09:13:09Z doug=
b $
+.\" $FreeBSD: head/sbin/rcorder/rcorder.8 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd August 5, 2011
 .Dt RCORDER 8
@@ -181,7 +181,7 @@
 .Dq Li REQUIRE
 on
 .Dq Li named ,
-it means the script must be placed after the=20
+it means the script must be placed after the
 .Dq Li named
 script in the dependency ordering,
 not necessarily that it requires
diff -r 428842767fa6 -r f2935497fa04 head/sbin/route/route.8
--- a/head/sbin/route/route.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/route/route.8	Tue Apr 17 11:51:51 2012 +0300
@@ -26,9 +26,9 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)route.8	8.3 (Berkeley) 3/19/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/route/route.8 233458 2012-03-25 09:21:09Z joel $
 .\"
-.Dd October 2, 2005
+.Dd March 24, 2012
 .Dt ROUTE 8
 .Os
 .Sh NAME
@@ -107,6 +107,10 @@
 .It Cm monitor
 Continuously report any changes to the routing information base,
 routing lookup misses, or suspected network partitionings.
+.It Cm show
+Another name for the
+.Cm get
+command.
 .El
 .Pp
 The monitor command has the syntax:
@@ -344,6 +348,36 @@
 the routing tables.
 .Sh EXIT STATUS
 .Ex -std
+.Sh EXAMPLES
+Add a default route to the network routing table.
+This will send all packets for destinations not available in the routing t=
able
+to the default gateway at 192.168.1.1:
+.Pp
+.Dl route add -net 0.0.0.0/0 192.168.1.1
+.Pp
+A shorter version of adding a default route can also be written as:
+.Pp
+.Dl route add default 192.168.1.1
+.Pp
+Add a static route to the 172.16.10.0/24 network via the 172.16.1.1 gatewa=
y:
+.Pp
+.Dl route add -net 172.16.10.0/24 172.16.1.1
+.Pp
+Change the gateway of an already established static route in the routing t=
able:
+.Pp
+.Dl route change -net 172.16.10.0/24 172.16.1.2
+.Pp
+Display the route for a destination network:
+.Pp
+.Dl route show 172.16.10.0
+.Pp
+Delete a static route from the routing table:
+.Pp
+.Dl route delete -net 172.16.10.0/24 172.16.1.2
+.Pp
+Remove all routes from the routing table:
+.Pp
+.Dl route flush
 .Sh DIAGNOSTICS
 .Bl -diag
 .It "add [host \&| network ] %s: gateway %s flags %x"
diff -r 428842767fa6 -r f2935497fa04 head/sbin/savecore/savecore.c
--- a/head/sbin/savecore/savecore.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/savecore/savecore.c	Tue Apr 17 11:51:51 2012 +0300
@@ -61,7 +61,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/savecore/savecore.c 223494 2011-06-24 07:29:=
04Z kevlo $");
+__FBSDID("$FreeBSD: head/sbin/savecore/savecore.c 234069 2012-04-09 20:55:=
23Z rmh $");
=20
 #include <sys/param.h>
 #include <sys/disk.h>
@@ -72,6 +72,7 @@
 #include <fcntl.h>
 #include <fstab.h>
 #include <paths.h>
+#include <signal.h>
 #include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
diff -r 428842767fa6 -r f2935497fa04 head/sbin/setkey/setkey.8
--- a/head/sbin/setkey/setkey.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/setkey/setkey.8	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sbin/setkey/setkey.8 222599 2011-06-02 09:56:42Z uqs $
+.\" $FreeBSD: head/sbin/setkey/setkey.8 233522 2012-03-26 21:22:53Z joel $
 .\"
 .Dd May 13, 2006
 .Dt SETKEY 8
@@ -567,7 +567,6 @@
 .Xr ipsec_set_policy 3
 for details.
 .El
-.Pp
 .\"
 .Sh ALGORITHMS
 The following list shows the supported algorithms.
@@ -652,48 +651,48 @@
 .Sh EXAMPLES
 Add an ESP SA between two IPv6 addresses using the
 des-cbc encryption algorithm.
-.Bd -literal -offset
+.Bd -literal -offset indent
 add 3ffe:501:4819::1 3ffe:501:481d::1 esp 123457
 	-E des-cbc 0x3ffe05014819ffff ;
=20
 .Ed
 .\"
 Add an authentication SA between two FQDN specified hosts:
-.Bd -literal -offset
+.Bd -literal -offset indent
 add -6 myhost.example.com yourhost.example.com ah 123456
 	-A hmac-sha1 "AH SA configuration!" ;
=20
 .Ed
 Use both ESP and AH between two numerically specified hosts:
-.Bd -literal -offset
+.Bd -literal -offset indent
 add 10.0.11.41 10.0.11.33 esp 0x10001
 	-E des-cbc 0x3ffe05014819ffff
 	-A hmac-md5 "authentication!!" ;
=20
 .Ed
 Get the SA information associated with first example above:
-.Bd -literal -offset
+.Bd -literal -offset indent
 get 3ffe:501:4819::1 3ffe:501:481d::1 ah 123456 ;
=20
 .Ed
 Flush all entries from the database:
-.Bd -literal -offset
+.Bd -literal -offset indent
 flush ;
=20
 .Ed
 Dump the ESP entries from the database:
-.Bd -literal -offset
+.Bd -literal -offset indent
 dump esp ;
=20
 .Ed
 Add a security policy between two networks that uses ESP in tunnel mode:
-.Bd -literal -offset
+.Bd -literal -offset indent
 spdadd 10.0.11.41/32[21] 10.0.11.33/32[any] any
 	-P out ipsec esp/tunnel/192.168.0.1-192.168.1.2/require ;
=20
 .Ed
 Use TCP MD5 between two numerically specified hosts:
-.Bd -literal -offset
+.Bd -literal -offset indent
 add 10.1.10.34 10.1.10.36 tcp 0x1000 -A tcp-md5 "TCP-MD5 BGP secret" ;
=20
 .Ed
diff -r 428842767fa6 -r f2935497fa04 head/sbin/sunlabel/sunlabel.8
--- a/head/sbin/sunlabel/sunlabel.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/sunlabel/sunlabel.8	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/sunlabel/sunlabel.8 233992 2012-04-07 09:05:30Z jo=
el $
 .\"
 .Dd March 30, 2005
 .Dt SUNLABEL 8
@@ -318,15 +318,15 @@
 The following VTOC tag names are known:
 .Bl -column -offset indent ".Li unassigned" ".Sy value" ".Sy comment"
 .It Sy name Ta Sy value Ta Sy comment
-.It Li unassigned Ta No 0x00
-.It Li boot Ta No 0x01
-.It Li root Ta No 0x02
-.It Li swap Ta No 0x03
-.It Li usr Ta No 0x04
+.It Li unassigned Ta No 0x00 Ta \&
+.It Li boot Ta No 0x01 Ta \&
+.It Li root Ta No 0x02 Ta \&
+.It Li swap Ta No 0x03 Ta \&
+.It Li usr Ta No 0x04 Ta \&
 .It Li backup Ta No 0x05 Ta c partition, entire disk
-.It Li stand Ta No 0x06
-.It Li var Ta No 0x07
-.It Li home Ta No 0x08
+.It Li stand Ta No 0x06 Ta \&
+.It Li var Ta No 0x07 Ta \&
+.It Li home Ta No 0x08 Ta \&
 .It Li altsctr Ta No 0x09 Ta alternate sector partition
 .It Li cache Ta No 0x0a Ta Solaris cachefs partition
 .It Li VxVM_pub Ta No 0x0e Ta VxVM public region
diff -r 428842767fa6 -r f2935497fa04 head/sbin/sysctl/sysctl.8
--- a/head/sbin/sysctl/sysctl.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/sysctl/sysctl.8	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	From: @(#)sysctl.8	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/sysctl/sysctl.8 233510 2012-03-26 15:18:14Z joel $
 .\"
 .Dd January 17, 2011
 .Dt SYSCTL 8
@@ -166,72 +166,72 @@
 String and integer values can be set using
 .Nm .
 .Bl -column security.bsd.unprivileged_read_msgbuf integerxxx
-.It Sy "Name	Type	Changeable
-.It "kern.ostype	string	no
-.It "kern.osrelease	string	no
-.It "kern.osrevision	integer	no
-.It "kern.version	string	no
-.It "kern.maxvnodes	integer	yes
-.It "kern.maxproc	integer	no
-.It "kern.maxprocperuid	integer	yes
-.It "kern.maxfiles	integer	yes
-.It "kern.maxfilesperproc	integer	yes
-.It "kern.argmax	integer	no
-.It "kern.securelevel	integer	raise only
-.It "kern.hostname	string	yes
-.It "kern.hostid	integer	yes
-.It "kern.clockrate	struct	no
-.It "kern.posix1version	integer	no
-.It "kern.ngroups	integer	no
-.It "kern.job_control	integer	no
-.It "kern.saved_ids	integer	no
-.It "kern.boottime	struct	no
-.It "kern.domainname	string	yes
-.It "kern.filedelay	integer	yes
-.It "kern.dirdelay	integer	yes
-.It "kern.metadelay	integer	yes
-.It "kern.osreldate	string	no
-.It "kern.bootfile	string	yes
-.It "kern.corefile	string	yes
-.It "kern.logsigexit	integer	yes
-.It "security.bsd.suser_enabled	integer	yes
-.It "security.bsd.see_other_uids	integer	yes
-.It "security.bsd.unprivileged_proc_debug	integer	yes
-.It "security.bsd.unprivileged_read_msgbuf	integer	yes
-.It "vm.loadavg	struct	no
-.It "hw.machine	string	no
-.It "hw.model	string	no
-.It "hw.ncpu	integer	no
-.It "hw.byteorder	integer	no
-.It "hw.physmem	integer	no
-.It "hw.usermem	integer	no
-.It "hw.pagesize	integer	no
-.It "hw.floatingpoint	integer	no
-.It "hw.machine_arch	string	no
-.It "hw.realmem	integer	no
-.It "machdep.adjkerntz	integer	yes
-.It "machdep.disable_rtc_set	integer	yes
-.It "machdep.guessed_bootdev	string	no
-.It "user.cs_path	string	no
-.It "user.bc_base_max	integer	no
-.It "user.bc_dim_max	integer	no
-.It "user.bc_scale_max	integer	no
-.It "user.bc_string_max	integer	no
-.It "user.coll_weights_max	integer	no
-.It "user.expr_nest_max	integer	no
-.It "user.line_max	integer	no
-.It "user.re_dup_max	integer	no
-.It "user.posix2_version	integer	no
-.It "user.posix2_c_bind	integer	no
-.It "user.posix2_c_dev	integer	no
-.It "user.posix2_char_term	integer	no
-.It "user.posix2_fort_dev	integer	no
-.It "user.posix2_fort_run	integer	no
-.It "user.posix2_localedef	integer	no
-.It "user.posix2_sw_dev	integer	no
-.It "user.posix2_upe	integer	no
-.It "user.stream_max	integer	no
-.It "user.tzname_max	integer	no
+.It Sy "Name	Type	Changeable"
+.It "kern.ostype	string	no"
+.It "kern.osrelease	string	no"
+.It "kern.osrevision	integer	no"
+.It "kern.version	string	no"
+.It "kern.maxvnodes	integer	yes"
+.It "kern.maxproc	integer	no"
+.It "kern.maxprocperuid	integer	yes"
+.It "kern.maxfiles	integer	yes"
+.It "kern.maxfilesperproc	integer	yes"
+.It "kern.argmax	integer	no"
+.It "kern.securelevel	integer	raise only"
+.It "kern.hostname	string	yes"
+.It "kern.hostid	integer	yes"
+.It "kern.clockrate	struct	no"
+.It "kern.posix1version	integer	no"
+.It "kern.ngroups	integer	no"
+.It "kern.job_control	integer	no"
+.It "kern.saved_ids	integer	no"
+.It "kern.boottime	struct	no"
+.It "kern.domainname	string	yes"
+.It "kern.filedelay	integer	yes"
+.It "kern.dirdelay	integer	yes"
+.It "kern.metadelay	integer	yes"
+.It "kern.osreldate	string	no"
+.It "kern.bootfile	string	yes"
+.It "kern.corefile	string	yes"
+.It "kern.logsigexit	integer	yes"
+.It "security.bsd.suser_enabled	integer	yes"
+.It "security.bsd.see_other_uids	integer	yes"
+.It "security.bsd.unprivileged_proc_debug	integer	yes"
+.It "security.bsd.unprivileged_read_msgbuf	integer	yes"
+.It "vm.loadavg	struct	no"
+.It "hw.machine	string	no"
+.It "hw.model	string	no"
+.It "hw.ncpu	integer	no"
+.It "hw.byteorder	integer	no"
+.It "hw.physmem	integer	no"
+.It "hw.usermem	integer	no"
+.It "hw.pagesize	integer	no"
+.It "hw.floatingpoint	integer	no"
+.It "hw.machine_arch	string	no"
+.It "hw.realmem	integer	no"
+.It "machdep.adjkerntz	integer	yes"
+.It "machdep.disable_rtc_set	integer	yes"
+.It "machdep.guessed_bootdev	string	no"
+.It "user.cs_path	string	no"
+.It "user.bc_base_max	integer	no"
+.It "user.bc_dim_max	integer	no"
+.It "user.bc_scale_max	integer	no"
+.It "user.bc_string_max	integer	no"
+.It "user.coll_weights_max	integer	no"
+.It "user.expr_nest_max	integer	no"
+.It "user.line_max	integer	no"
+.It "user.re_dup_max	integer	no"
+.It "user.posix2_version	integer	no"
+.It "user.posix2_c_bind	integer	no"
+.It "user.posix2_c_dev	integer	no"
+.It "user.posix2_char_term	integer	no"
+.It "user.posix2_fort_dev	integer	no"
+.It "user.posix2_fort_run	integer	no"
+.It "user.posix2_localedef	integer	no"
+.It "user.posix2_sw_dev	integer	no"
+.It "user.posix2_upe	integer	no"
+.It "user.stream_max	integer	no"
+.It "user.tzname_max	integer	no"
 .El
 .Sh FILES
 .Bl -tag -width ".In netinet/icmp_var.h" -compact
diff -r 428842767fa6 -r f2935497fa04 head/sbin/sysctl/sysctl.c
--- a/head/sbin/sysctl/sysctl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sbin/sysctl/sysctl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -38,7 +38,7 @@
 static char sccsid[] =3D "@(#)from: sysctl.c	8.1 (Berkeley) 6/6/93";
 #endif
 static const char rcsid[] =3D
-  "$FreeBSD: head/sbin/sysctl/sysctl.c 228181 2011-12-01 15:01:23Z jhb $";
+  "$FreeBSD: head/sbin/sysctl/sysctl.c 234134 2012-04-11 14:18:18Z eadler =
$";
 #endif /* not lint */
=20
 #include <sys/param.h>
@@ -419,7 +419,7 @@
 	    v->t_vmshr * pageKilo, v->t_avmshr * pageKilo);
 	printf("Shared Real Memory:\t(Total: %dK Active: %dK)\n",
 	    v->t_rmshr * pageKilo, v->t_armshr * pageKilo);
-	printf("Free Memory Pages:\t%dK\n", v->t_free * pageKilo);
+	printf("Free Memory:\t%dK\n", v->t_free * pageKilo);
=20
 	return (0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/secure/usr.bin/ssh/Makefile
--- a/head/secure/usr.bin/ssh/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/secure/usr.bin/ssh/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/secure/usr.bin/ssh/Makefile 233136 2012-03-19 00:41:40Z e=
adler $
+# $FreeBSD: head/secure/usr.bin/ssh/Makefile 233432 2012-03-24 19:41:43Z e=
adler $
 #
=20
 .include <bsd.own.mk>
@@ -28,6 +28,10 @@
 DPADD+=3D	${LIBCRYPT} ${LIBCRYPTO}
 LDADD+=3D	-lcrypt -lcrypto
=20
+.if defined(LOCALBASE)
+CFLAGS+=3D -DXAUTH_PATH=3D\"${LOCALBASE}/bin/xauth\"
+.endif
+
 .include <bsd.prog.mk>
=20
 .PATH:	${SSHDIR}
diff -r 428842767fa6 -r f2935497fa04 head/secure/usr.sbin/sshd/Makefile
--- a/head/secure/usr.sbin/sshd/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/secure/usr.sbin/sshd/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/secure/usr.sbin/sshd/Makefile 233136 2012-03-19 00:41:40Z=
 eadler $
+# $FreeBSD: head/secure/usr.sbin/sshd/Makefile 233432 2012-03-24 19:41:43Z=
 eadler $
 #
=20
 .include <bsd.own.mk>
@@ -43,6 +43,10 @@
 DPADD+=3D	${LIBCRYPTO} ${LIBCRYPT}
 LDADD+=3D	-lcrypto -lcrypt
=20
+.if defined(LOCALBASE)
+CFLAGS+=3D -DXAUTH_PATH=3D\"${LOCALBASE}/bin/xauth\"
+.endif
+
 .include <bsd.prog.mk>
=20
 .PATH:	${SSHDIR}
diff -r 428842767fa6 -r f2935497fa04 head/share/doc/bind9/Makefile
--- a/head/share/doc/bind9/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/doc/bind9/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/doc/bind9/Makefile 225361 2011-09-03 07:13:45Z doug=
b $
+# $FreeBSD: head/share/doc/bind9/Makefile 234165 2012-04-12 01:53:33Z doug=
b $
=20
 BIND_DIR=3D	${.CURDIR}/../../../contrib/bind9
 SRCDIR=3D		${BIND_DIR}/doc
@@ -8,14 +8,12 @@
 NO_OBJ=3D
=20
 FILESGROUPS=3D	TOP ARM MISC
-TOP=3D		CHANGES COPYRIGHT FAQ HISTORY README \
-		RELEASE-NOTES-BIND-9.8.1.pdf RELEASE-NOTES-BIND-9.8.1.txt \
-		RELEASE-NOTES-BIND-9.8.1.html release-notes.css
+TOP=3D		CHANGES COPYRIGHT FAQ HISTORY README
 TOPDIR=3D		${DOCDIR}/bind9
 ARM=3D		Bv9ARM.ch01.html Bv9ARM.ch02.html Bv9ARM.ch03.html \
 		Bv9ARM.ch04.html Bv9ARM.ch05.html Bv9ARM.ch06.html \
 		Bv9ARM.ch07.html Bv9ARM.ch08.html Bv9ARM.ch09.html \
-		Bv9ARM.ch10.html Bv9ARM.html \
+		Bv9ARM.ch10.html Bv9ARM.html Bv9ARM.pdf \
 		man.arpaname.html man.ddns-confgen.html man.dig.html \
 		man.dnssec-dsfromkey.html man.dnssec-keyfromlabel.html \
 		man.dnssec-keygen.html man.dnssec-revoke.html \
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/Makefile
--- a/head/share/examples/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/examples/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/examples/Makefile 222337 2011-05-27 03:27:28Z mav $
+# $FreeBSD: head/share/examples/Makefile 233429 2012-03-24 18:43:18Z eadle=
r $
 #
 # Doing a make install builds /usr/share/examples
=20
@@ -8,6 +8,7 @@
 	FreeBSD_version \
 	IPv6 \
 	bootforth \
+	csh \
 	cvsup \
 	diskless \
 	drivers \
@@ -49,6 +50,7 @@
 	bootforth/menu.4th \
 	bootforth/menuconf.4th \
 	bootforth/screen.4th \
+	csh/dot.cshrc \
 	cvsup/README \
 	cvsup/cvs-supfile \
 	cvsup/doc-supfile \
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/cvsup/cvs-supfile
--- a/head/share/examples/cvsup/cvs-supfile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/examples/cvsup/cvs-supfile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,21 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/share/examples/cvsup/cvs-supfile 233428 2012-03-24 18:25:=
16Z eadler $
 #
 # This file contains all of the "CVSup collections" that make up the
 # CVS development tree of the FreeBSD system.
 #
-# CVSup (CVS Update Protocol) allows you to download the latest CVS
+# csup (CVS Update Protocol) allows you to download the latest CVS
 # tree (or any branch of development therefrom) to your system easily
-# and efficiently (far more so than with sup, which CVSup is aimed
-# at replacing).  If you're running CVSup interactively, and are
-# currently using an X display server, you should run CVSup as follows
-# to keep your CVS tree up-to-date:
+# and efficiently
 #
-#	cvsup cvs-supfile
+# To keep your CVS tree up-to-date run:
 #
-# If not running X, or invoking cvsup from a non-interactive script, then
-# run it as follows:
+#	csup cvs-supfile
 #
-#	cvsup -g -L 2 cvs-supfile
+# Note that this only updates the tree contents and does not
+# update what is actually installed.
 #
 # You may wish to change some of the settings in this file to better
 # suit your system:
@@ -29,7 +26,7 @@
 #		with cvsup's "-h host" option.
 #
 # base=3D/var/db
-#		This specifies the root where CVSup will store information
+#		This specifies the root where csup will store information
 #		about the collections you have transferred to your system.
 #		A setting of "/var/db" will generate this information in
 #		/var/db/sup.  You can override the "base" setting on the
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/cvsup/doc-supfile
--- a/head/share/examples/cvsup/doc-supfile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/examples/cvsup/doc-supfile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,21 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/share/examples/cvsup/doc-supfile 233428 2012-03-24 18:25:=
16Z eadler $
 #
 # This file contains all of the "CVSup collections" that make up the
 # source of the FreeBSD doc tree
 #
-# CVSup (CVS Update Protocol) allows you to download the latest CVS
+# csup (CVS Update Protocol) allows you to download the latest CVS
 # tree (or any branch of development therefrom) to your system easily
-# and efficiently (far more so than with sup, which CVSup is aimed
-# at replacing).  If you're running CVSup interactively, and are
-# currently using an X display server, you should run CVSup as follows
-# to keep your CVS tree up-to-date:
+# and efficiently
 #
-#	cvsup doc-supfile
+# To keep your CVS tree up-to-date run:
 #
-# If not running X, or invoking cvsup from a non-interactive script, then
-# run it as follows:
+#	csup doc-supfile
 #
-#	cvsup -g -L 2 doc-supfile
+# Note that this only updates the tree contents and does not
+# update what is actually installed.
 #
 # You may wish to change some of the settings in this file to better
 # suit your system:
@@ -29,7 +26,7 @@
 #		with cvsup's "-h host" option.
 #
 # base=3D/var/db
-#		This specifies the root where CVSup will store information
+#		This specifies the root where csup will store information
 #		about the collections you have transferred to your system.
 #		A setting of "/var/db" will generate this information in
 #		/var/db/sup.  You can override the "base" setting on the
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/cvsup/gnats-supfile
--- a/head/share/examples/cvsup/gnats-supfile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/examples/cvsup/gnats-supfile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,21 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/share/examples/cvsup/gnats-supfile 233428 2012-03-24 18:2=
5:16Z eadler $
 #
 # This file contains all of the "CVSup collections" that make up the
 # FreeBSD GNATS bug report database.
 #
-# CVSup (CVS Update Protocol) allows you to download the latest CVS
+# csup (CVS Update Protocol) allows you to download the latest CVS
 # tree (or any branch of development therefrom) to your system easily
-# and efficiently (far more so than with sup, which CVSup is aimed
-# at replacing).  If you're running CVSup interactively, and are
-# currently using an X display server, you should run CVSup as follows
-# to keep your CVS tree up-to-date:
+# and efficiently
 #
-#	cvsup gnats-supfile
+# To keep your CVS tree up-to-date run:
 #
-# If not running X, or invoking cvsup from a non-interactive script, then
-# run it as follows:
+#	csup gnats-supfile
 #
-#	cvsup -g -L 2 gnats-supfile
+# Note that this only updates the tree contents and does not
+# update what is actually installed.
 #
 # You may wish to change some of the settings in this file to better
 # suit your system:
@@ -29,7 +26,7 @@
 #		with cvsup's "-h host" option.
 #
 # base=3D/var/db
-#		This specifies the root where CVSup will store information
+#		This specifies the root where csup will store information
 #		about the collections you have transferred to your system.
 #		A setting of "/var/db" will generate this information in
 #		/var/db/sup.  You can override the "base" setting on the
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/cvsup/ports-supfile
--- a/head/share/examples/cvsup/ports-supfile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/examples/cvsup/ports-supfile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,21 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/share/examples/cvsup/ports-supfile 233428 2012-03-24 18:2=
5:16Z eadler $
 #
 # This file contains all of the "CVSup collections" that make up the
 # FreeBSD-current ports collection.
 #
-# CVSup (CVS Update Protocol) allows you to download the latest CVS
+# csup (CVS Update Protocol) allows you to download the latest CVS
 # tree (or any branch of development therefrom) to your system easily
-# and efficiently (far more so than with sup, which CVSup is aimed
-# at replacing).  If you're running CVSup interactively, and are
-# currently using an X display server, you should run CVSup as follows
-# to keep your CVS tree up-to-date:
+# and efficiently
 #
-#	cvsup ports-supfile
+# To keep your CVS tree up-to-date run:
 #
-# If not running X, or invoking cvsup from a non-interactive script, then
-# run it as follows:
+#	csup ports-supfile
 #
-#	cvsup -g -L 2 ports-supfile
+# Note that this only updates the tree contents and does not
+# update what is actually installed.
 #
 # You may wish to change some of the settings in this file to better
 # suit your system:
@@ -29,7 +26,7 @@
 #		with cvsup's "-h host" option.
 #
 # base=3D/var/db
-#		This specifies the root where CVSup will store information
+#		This specifies the root where csup will store information
 #		about the collections you have transferred to your system.
 #		A setting of "/var/db" will generate this information in
 #		/var/db/sup.  You can override the "base" setting on the
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/cvsup/stable-supfi=
le
--- a/head/share/examples/cvsup/stable-supfile	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/share/examples/cvsup/stable-supfile	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,21 +1,18 @@
-# $FreeBSD: head/share/examples/cvsup/stable-supfile 225764 2011-09-26 11:=
57:48Z kensmith $
+# $FreeBSD: head/share/examples/cvsup/stable-supfile 233428 2012-03-24 18:=
25:16Z eadler $
 #
 # This file contains all of the "CVSup collections" that make up the
 # FreeBSD-stable source tree.
 #
-# CVSup (CVS Update Protocol) allows you to download the latest CVS
+# csup (CVS Update Protocol) allows you to download the latest CVS
 # tree (or any branch of development therefrom) to your system easily
-# and efficiently (far more so than with sup, which CVSup is aimed
-# at replacing).  If you're running CVSup interactively, and are
-# currently using an X display server, you should run CVSup as follows
-# to keep your CVS tree up-to-date:
+# and efficiently
 #
-#	cvsup stable-supfile
+# To keep your CVS tree up-to-date run:
 #
-# If not running X, or invoking cvsup from a non-interactive script, then
-# run it as follows:
+#	csup stable-supfile
 #
-#	cvsup -g -L 2 stable-supfile
+# Note that this only updates the tree contents and does not
+# update what is actually installed.
 #
 # You may wish to change some of the settings in this file to better
 # suit your system:
@@ -29,7 +26,7 @@
 #		with cvsup's "-h host" option.
 #
 # base=3D/var/db
-#		This specifies the root where CVSup will store information
+#		This specifies the root where csup will store information
 #		about the collections you have transferred to your system.
 #		A setting of "/var/db" will generate this information in
 #		/var/db/sup.  You can override the "base" setting on the
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/cvsup/standard-sup=
file
--- a/head/share/examples/cvsup/standard-supfile	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/share/examples/cvsup/standard-supfile	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,21 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/share/examples/cvsup/standard-supfile 233428 2012-03-24 1=
8:25:16Z eadler $
 #
 # This file contains all of the "CVSup collections" that make up the
 # FreeBSD-current source tree.
 #
-# CVSup (CVS Update Protocol) allows you to download the latest CVS
+# csup (CVS Update Protocol) allows you to download the latest CVS
 # tree (or any branch of development therefrom) to your system easily
-# and efficiently (far more so than with sup, which CVSup is aimed
-# at replacing).  If you're running CVSup interactively, and are
-# currently using an X display server, you should run CVSup as follows
-# to keep your CVS tree up-to-date:
+# and efficiently
 #
-#	cvsup standard-supfile
+# To keep your CVS tree up-to-date run:
 #
-# If not running X, or invoking cvsup from a non-interactive script, then
-# run it as follows:
+#	csup standard-supfile
 #
-#	cvsup -g -L 2 standard-supfile
+# Note that this only updates the tree contents and does not
+# update what is actually installed.
 #
 # You may wish to change some of the settings in this file to better
 # suit your system:
@@ -29,7 +26,7 @@
 #		with cvsup's "-h host" option.
 #
 # base=3D/var/db
-#		This specifies the root where CVSup will store information
+#		This specifies the root where csup will store information
 #		about the collections you have transferred to your system.
 #		A setting of "/var/db" will generate this information in
 #		/var/db/sup.  You can override the "base" setting on the
diff -r 428842767fa6 -r f2935497fa04 head/share/examples/cvsup/www-supfile
--- a/head/share/examples/cvsup/www-supfile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/examples/cvsup/www-supfile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,21 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/share/examples/cvsup/www-supfile 233428 2012-03-24 18:25:=
16Z eadler $
 #
 # This file contains all of the "CVSup collections" that make up the
 # source of the FreeBSD www tree
 #
-# CVSup (CVS Update Protocol) allows you to download the latest CVS
+# csup (CVS Update Protocol) allows you to download the latest CVS
 # tree (or any branch of development therefrom) to your system easily
-# and efficiently (far more so than with sup, which CVSup is aimed
-# at replacing).  If you're running CVSup interactively, and are
-# currently using an X display server, you should run CVSup as follows
-# to keep your CVS tree up-to-date:
+# and efficiently
 #
-#	cvsup www-supfile
+# To keep your CVS tree up-to-date run:
 #
-# If not running X, or invoking cvsup from a non-interactive script, then
-# run it as follows:
+#	csup www-supfile
 #
-#	cvsup -g -L 2 www-supfile
+# Note that this only updates the tree contents and does not
+# update what is actually installed.
 #
 # You may wish to change some of the settings in this file to better
 # suit your system:
@@ -29,7 +26,7 @@
 #		with cvsup's "-h host" option.
 #
 # base=3D/var/db
-#		This specifies the root where CVSup will store information
+#		This specifies the root where csup will store information
 #		about the collections you have transferred to your system.
 #		A setting of "/var/db" will generate this information in
 #		/var/db/sup.  You can override the "base" setting on the
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man3/pthread_attr_affin=
ity_np.3
--- a/head/share/man/man3/pthread_attr_affinity_np.3	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/share/man/man3/pthread_attr_affinity_np.3	Tue Apr 17 11:51:51 20=
12 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man3/pthread_attr_affinity_np.3 233648 2012-0=
3-29 05:02:12Z eadler $
 .\"
 .Dd January 8, 2010
 .Dt PTHREAD_ATTR_AFFINITY_NP 3
@@ -119,7 +119,7 @@
 .It Bq Er EINVAL
 The
 .Fa cpusetp
-specified a CPU that was outside the set supported by the kernel.=20
+specified a CPU that was outside the set supported by the kernel.
 .It Bq Er ERANGE
 The
 .Fa cpusetsize
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man3/pthread_cond_destr=
oy.3
--- a/head/share/man/man3/pthread_cond_destroy.3	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/share/man/man3/pthread_cond_destroy.3	Tue Apr 17 11:51:51 2012 +=
0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man3/pthread_cond_destroy.3 233023 2012-03-16=
 05:05:37Z davidxu $
+.\" $FreeBSD: head/share/man/man3/pthread_cond_destroy.3 233466 2012-03-25=
 16:00:56Z joel $
 .\"
 .Dd July 28, 1998
 .Dt PTHREAD_COND_DESTROY 3
@@ -44,6 +44,9 @@
 .Fn pthread_cond_destroy
 function frees the resources allocated by the condition variable
 .Fa cond .
+.Sh IMPLEMENTATION NOTES
+A condition variable can be destroyed immediately after all the threads th=
at
+are blocked on it are awakened.
 .Sh RETURN VALUES
 If successful, the
 .Fn pthread_cond_destroy
@@ -63,9 +66,6 @@
 .Fa cond
 is locked by another thread.
 .El
-.Sh IMPLEMENTATION NOTES
-A condition variable can be destroyed immediately after all the threads th=
at
-are blocked on it are awakened.
 .Sh SEE ALSO
 .Xr pthread_cond_broadcast 3 ,
 .Xr pthread_cond_init 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man3/pthread_cond_timed=
wait.3
--- a/head/share/man/man3/pthread_cond_timedwait.3	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/share/man/man3/pthread_cond_timedwait.3	Tue Apr 17 11:51:51 2012=
 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man3/pthread_cond_timedwait.3 233648 2012-03-=
29 05:02:12Z eadler $
 .\"
 .Dd May 9, 2010
 .Dt PTHREAD_COND_TIMEDWAIT 3
@@ -83,8 +83,8 @@
 The system time has reached or exceeded the time specified in
 .Fa abstime .
 .It Bq Er EPERM
-The specified=20
-.Fa mutex=20
+The specified
+.Fa mutex
 was not locked by the calling thread.
 .El
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man3/pthread_cond_wait.3
--- a/head/share/man/man3/pthread_cond_wait.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man3/pthread_cond_wait.3	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man3/pthread_cond_wait.3 233648 2012-03-29 05=
:02:12Z eadler $
 .\"
 .Dd February 16, 2006
 .Dt PTHREAD_COND_WAIT 3
@@ -72,8 +72,8 @@
 .Fa mutex
 is invalid.
 .It Bq Er EPERM
-The specified=20
-.Fa mutex=20
+The specified
+.Fa mutex
 was not locked by the calling thread.
 .El
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man3/tgmath.3
--- a/head/share/man/man3/tgmath.3	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man3/tgmath.3	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man3/tgmath.3 229651 2012-01-05 21:36:12Z uqs=
 $
+.\" $FreeBSD: head/share/man/man3/tgmath.3 233992 2012-04-07 09:05:30Z joe=
l $
 .\"
 .Dd January 4, 2012
 .Dt TGMATH 3
@@ -116,8 +116,8 @@
 .It Fn erfc Ta Fn hypot Ta Fn lrint Ta Fn scalbln
 .It Fn exp2 Ta Fn ilogb Ta Fn lround Ta Fn tgamma
 .It Fn expm1 Ta Fn ldexp Ta Fn nextbyint Ta Fn trunc
-.It Fn fdim Ta Fn lgamma Ta Fn nextafter
-.It Fn floor Ta Fn llrint Ta Fn nexttoward
+.It Fn fdim Ta Fn lgamma Ta Fn nextafter Ta \&
+.It Fn floor Ta Fn llrint Ta Fn nexttoward Ta \&
 .El
 .Pp
 The following macros always expand to a complex function:
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/acpi.4
--- a/head/share/man/man4/acpi.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/acpi.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,9 +23,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/acpi.4 233313 2012-03-22 17:01:25Z jkim $
 .\"
-.Dd October 26, 2010
+.Dd March 22, 2012
 .Dt ACPI 4
 .Os
 .Sh NAME
@@ -214,6 +214,14 @@
 Beep the PC speaker on resume.
 This can help diagnose suspend/resume problems.
 Default is 0 (disabled).
+.It Va debug.acpi.sleep_flags
+Execute optional ACPI methods for suspend/resume.
+If the bit 0 is set (1), it will try to execute _GTS (Going To Sleep) meth=
od
+when entering suspend state.
+If the bit 1 is set (2), it will try to execute _BFS (Back From Sleep) met=
hod
+when leaving suspend state.
+If both the bits are set (3), both the methods will be tried.
+Default is 0 (disabled).
 .It Va hint.acpi.0.disabled
 Set this to 1 to disable all of ACPI.
 If ACPI has been disabled on your system due to a blacklist entry for your
@@ -483,6 +491,8 @@
 Stores to objects
 .It Li ACPI_LV_INFO
 General information and progress
+.It Li ACPI_LV_REPAIR
+Repair a common problem with predefined methods
 .It Li ACPI_LV_ALL_EXCEPTIONS
 All the previous levels
 .It Li ACPI_LV_PARSE
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/acpi_hp.4
--- a/head/share/man/man4/acpi_hp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/acpi_hp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/acpi_hp.4 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd February 8, 2010
 .Dt ACPI_HP 4
@@ -93,7 +93,7 @@
 .El
 .Ss Xr devfs 8 Ss Device
 You can read /dev/hpcmi to see your current BIOS settings.
-The detail level can be adjusted by setting the sysctl=20
+The detail level can be adjusted by setting the sysctl
 .Va cmi_detail
 as described below.
 .Sh SYSCTL VARIABLES
@@ -101,7 +101,7 @@
 .Ss WLAN:
 .Bl -tag -width indent
 .It Va dev.acpi_hp.0.wlan_enabled
-Toggle WLAN chip activity.=20
+Toggle WLAN chip activity.
 .It Va dev.acpi_hp.0.wlan_radio
 (read-only)
 WLAN radio status (controlled by hardware switch)
@@ -116,7 +116,7 @@
 .Ss Bluetooth:
 .Bl -tag -width indent
 .It Va dev.acpi_hp.0.bt_enabled
-Toggle Bluetooth chip activity.=20
+Toggle Bluetooth chip activity.
 .It Va dev.acpi_hp.0.bt_radio
 (read-only)
 Bluetooth radio status (controlled by hardware switch)
@@ -131,7 +131,7 @@
 .Ss WWAN:
 .Bl -tag -width indent
 .It Va dev.acpi_hp.0.wwan_enabled
-Toggle WWAN chip activity.=20
+Toggle WWAN chip activity.
 .It Va dev.acpi_hp.0.wwan_radio
 (read-only)
 WWAN radio status (controlled by hardware switch)
@@ -229,14 +229,14 @@
 .Bd -literal -offset indent
 cat /dev/hpcmi
=20
-Serial Port                                Disable             =20
-Infrared Port                              Enable              =20
-Parallel Port                              Disable             =20
-Flash Media Reader                         Disable             =20
-USB Ports including Express Card slot      Enable              =20
-1394 Port                                  Enable              =20
-Cardbus Slot                               Disable             =20
-Express Card Slot                          Disable  =20
+Serial Port                                Disable
+Infrared Port                              Enable
+Parallel Port                              Disable
+Flash Media Reader                         Disable
+USB Ports including Express Card slot      Enable
+1394 Port                                  Enable
+Cardbus Slot                               Disable
+Express Card Slot                          Disable
 (...)
 .Ed
 .Pp
@@ -244,7 +244,6 @@
 .Bd -literal -offset indent
 sysctl dev.acpi_hp.0.cmi_detail=3D7
 .Ed
-.Pp
 .Sh SEE ALSO
 .Xr acpi 4 ,
 .Xr acpi_wmi 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/acpi_wmi.4
--- a/head/share/man/man4/acpi_wmi.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/acpi_wmi.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/acpi_wmi.4 227823 2011-11-22 16:44:50Z j=
h $
+.\" $FreeBSD: head/share/man/man4/acpi_wmi.4 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd November 22, 2011
 .Dt ACPI_WMI 4
@@ -47,7 +47,7 @@
 .Sh DESCRIPTION
 The
 .Nm
-driver provides an interface for vendor specific WMI implementations=20
+driver provides an interface for vendor specific WMI implementations
 (e.g. HP and Acer laptops).
 It creates /dev/wmistat%d, which can be read to get
 information about GUIDs found in the system.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ada.4
--- a/head/share/man/man4/ada.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ada.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/ada.4 231244 2012-02-09 04:37:30Z gjb $
+.\" $FreeBSD: head/share/man/man4/ada.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd February 8, 2012
 .Dt ADA 4
@@ -121,7 +121,7 @@
 .It Va kern.cam.ada.spindown_shutdown
 .Pp
 This variable determines whether to spin-down disks when shutting down.
-Set to 1 to enable spin-down, 0 to disable. =20
+Set to 1 to enable spin-down, 0 to disable.
 The default is currently enabled.
 .It Va kern.cam.ada.write_cache
 .It Va kern.cam.ada. Ns Ar X Ns Va .write_cache
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/adv.4
--- a/head/share/man/man4/adv.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/adv.4	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/adv.4 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd August 8, 2004
 .Dt ADV 4
@@ -66,26 +66,24 @@
 The following tables list the AdvanSys products using these chips,
 their bus attachment type, maximum sync rate, and the maximum number of
 commands that can be handled by the adapter concurrently.
-.Pp
 .Bd -ragged -offset indent
-.Bl -column "ABP510/5150 " "ISA PnP " "Yes " "10MHz " "Commands " Footnotes
 Connectivity Products:
-.Pp
-.Em "Adapter       Bus   Floppy      MaxSync   Commands  Footnotes"
-ABP510/5150   ISA     No         10MHz       240    1
-ABP5140     ISA PnP   No         10MHz       16     1, 3
-ABP5142     ISA PnP   Yes        10MHz       16     4
-ABP[3]902     PCI     No         10MHz       16
-ABP3905       PCI     No         10MHz       16
-ABP915        PCI     No         10MHz       16
-ABP920        PCI     No         10MHz       16
-ABP3922       PCI     No         10MHz       16
-ABP3925       PCI     No         10MHz       16
-ABP930        PCI     No         10MHz       16     5
-ABP930U       PCI     No         20MHz       16
-ABP930UA      PCI     No         20MHz       16
-ABP960        PCI     No         10MHz       16
-ABP960U       PCI     No         20MHz       16
+.Bl -column "ABP510/5150 " "ISA PnP " "Floppy " "MaxSync " "Commands " "Fo=
otnotes "
+.Em "Adapter" Ta Em "Bus" Ta Em "Floppy" Ta Em "MaxSync" Ta Em "Commands" =
Ta Em "Footnotes"
+.It "ABP510/5150" Ta "ISA" Ta "\&No" Ta "10MHz" Ta "240" Ta "1"
+.It "ABP5140" Ta "ISA PnP" Ta "\&No" Ta "10MHz" Ta "16" Ta "1, 3"
+.It "ABP5142" Ta "ISA PnP" Ta "Yes" Ta "10MHz" Ta "16" Ta "4"
+.It "ABP[3]902" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta ""
+.It "ABP3905" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta ""
+.It "ABP915" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta ""
+.It "ABP920" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta ""
+.It "ABP3922" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta ""
+.It "ABP3925" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta ""
+.It "ABP930" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta "5"
+.It "ABP930U" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "16" Ta ""
+.It "ABP930UA" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "16" Ta ""
+.It "ABP960" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "16" Ta ""
+.It "ABP960U" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "16" Ta ""
 .El
 .Pp
 Footnotes:
@@ -104,35 +102,31 @@
 This board has been sold by SIIG as the Fast SCSI Pro PCI.
 .El
 .Ed
-.Pp
 .Bd -ragged -offset indent
-.Bl -column "ABP510/5150 " "ISA PnP " "Yes " "10MHz " Commands
 Single Channel Products:
-.Pp
-.Em "Adapter       Bus   Floppy      MaxSync   Commands"
-ABP542        ISA     Yes        10MHz       240
-ABP742        EISA    Yes        10MHz       240
-ABP842        VL      Yes        10MHz       240
-ABP940        PCI     No         10MHz       240
-ABP[3]940UA   PCI     No         20MHz       240
-ABP940U       PCI     No         20MHz       240
-ABP3960UA     PCI     No         20MHz       240
-ABP970        PCI     No         10MHz       240
-ABP970U       PCI     No         20MHz       240
+.Bl -column "ABPX3X940UA " "EISA " "Floppy " "MaxSync " "Commands"
+.Em "Adapter" Ta Em "Bus" Ta Em "Floppy" Ta Em "MaxSync" Ta Em "Commands"
+.It "ABP542" Ta "ISA" Ta "Yes" Ta "10MHz" Ta "240"
+.It "ABP742" Ta "EISA" Ta "Yes" Ta "10MHz" Ta "240"
+.It "ABP842" Ta "VL" Ta "Yes" Ta "10MHz" Ta "240"
+.It "ABP940" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "240"
+.It "ABP[3]940UA" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "240"
+.It "ABP940U" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "240"
+.It "ABP3960UA" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "240"
+.It "ABP970" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "240"
+.It "ABP970U" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "240"
 .El
 .Ed
-.Pp
 .Bd -ragged -offset indent
-.Bl -column "ABP510/5150 " "ISA PnP " "Yes " "10MHz " "Commands " "Channel=
s "
 Multi Channel Products (Commands are per-channel):
-.Pp
-.Em "Adapter       Bus   Floppy      MaxSync   Commands  Channels"
-ABP752       EISA     Yes        10MHz       240      2
-ABP852        VL      Yes        10MHz       240      2
-ABP950        PCI     No         10MHz       240      2
-ABP980        PCI     No         10MHz       240      4
-ABP980U       PCI     No         20MHz       240      4
-ABP[3]980UA   PCI     No         20MHz       16       4
+.Bl -column "ABPX3X980UA " "EISA " "Floppy " "MaxSync " "Commands " "Chann=
els"
+.Em "Adapter" Ta Em "Bus" Ta Em "Floppy" Ta Em "MaxSync" Ta Em "Commands" =
Ta Em "Channels"
+.It "ABP752" Ta "EISA" Ta "Yes" Ta "10MHz" Ta "240" Ta "2"
+.It "ABP852" Ta "VL" Ta "Yes" Ta "10MHz" Ta "240" Ta "2"
+.It "ABP950" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "240" Ta "2"
+.It "ABP980" Ta "PCI" Ta "\&No" Ta "10MHz" Ta "240" Ta "4"
+.It "ABP980U" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "240" Ta "4"
+.It "ABP[3]980UA" Ta "PCI" Ta "\&No" Ta "20MHz" Ta "16" Ta "4"
 .El
 .Ed
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ahc.4
--- a/head/share/man/man4/ahc.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ahc.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ahc.4 233733 2012-03-31 07:08:35Z joel $
 .\"
 .Dd July 13, 2008
 .Dt AHC 4
@@ -146,23 +146,22 @@
 Note that wide and twin channel features, although always supported
 by a particular chip, may be disabled in a particular motherboard or card
 design.
-.Pp
 .Bd -ragged -offset indent
-.Bl -column "aic7770 " "10 " "EISA/VL  " "10MHz " "16bit " "SCBs " Features
-.Em "Chip       MIPS    Bus      MaxSync   MaxWidth  SCBs  Features"
-aic7770     10    EISA/VL    10MHz     16Bit     4    1
-aic7850     10    PCI/32     10MHz      8Bit     3
-aic7860     10    PCI/32     20MHz      8Bit     3
-aic7870     10    PCI/32     10MHz     16Bit    16
-aic7880     10    PCI/32     20MHz     16Bit    16
-aic7890     20    PCI/32     40MHz     16Bit    16        3 4 5 6 7 8
-aic7891     20    PCI/64     40MHz     16Bit    16        3 4 5 6 7 8
-aic7892     20    PCI/64     80MHz     16Bit    16        3 4 5 6 7 8
-aic7895     15    PCI/32     20MHz     16Bit    16      2 3 4 5
-aic7895C    15    PCI/32     20MHz     16Bit    16      2 3 4 5     8
-aic7896     20    PCI/32     40MHz     16Bit    16      2 3 4 5 6 7 8
-aic7897     20    PCI/64     40MHz     16Bit    16      2 3 4 5 6 7 8
-aic7899     20    PCI/64     80MHz     16Bit    16      2 3 4 5 6 7 8
+.Bl -column "aic7895CX" "MIPSX" "EISA/VLX" "MaxSyncX" "MaxWidthX" "SCBsX" =
"2 3 4 5 6 7 8X"
+.It Em "Chip" Ta "MIPS" Ta "Bus" Ta "MaxSync" Ta "MaxWidth" Ta "SCBs" Ta "=
Features"
+.It "aic7770" Ta "10" Ta "EISA/VL" Ta "10MHz" Ta "16Bit" Ta "4" Ta "1"
+.It "aic7850" Ta "10" Ta "PCI/32" Ta "10MHz" Ta "8Bit" Ta "3" Ta ""
+.It "aic7860" Ta "10" Ta "PCI/32" Ta "20MHz" Ta "8Bit" Ta "3" Ta ""
+.It "aic7870" Ta "10" Ta "PCI/32" Ta "10MHz" Ta "16Bit" Ta "16" Ta ""
+.It "aic7880" Ta "10" Ta "PCI/32" Ta "20MHz" Ta "16Bit" Ta "16" Ta ""
+.It "aic7890" Ta "20" Ta "PCI/32" Ta "40MHz" Ta "16Bit" Ta "16" Ta "3 4 5 =
6 7 8"
+.It "aic7891" Ta "20" Ta "PCI/64" Ta "40MHz" Ta "16Bit" Ta "16" Ta "3 4 5 =
6 7 8"
+.It "aic7892" Ta "20" Ta "PCI/64" Ta "80MHz" Ta "16Bit" Ta "16" Ta "3 4 5 =
6 7 8"
+.It "aic7895" Ta "15" Ta "PCI/32" Ta "20MHz" Ta "16Bit" Ta "16" Ta "2 3 4 =
5"
+.It "aic7895C" Ta "15" Ta "PCI/32" Ta "20MHz" Ta "16Bit" Ta "16" Ta "2 3 4=
 5 8"
+.It "aic7896" Ta "20" Ta "PCI/32" Ta "40MHz" Ta "16Bit" Ta "16" Ta "2 3 4 =
5 6 7 8"
+.It "aic7897" Ta "20" Ta "PCI/64" Ta "40MHz" Ta "16Bit" Ta "16" Ta "2 3 4 =
5 6 7 8"
+.It "aic7899" Ta "20" Ta "PCI/64" Ta "80MHz" Ta "16Bit" Ta "16" Ta "2 3 4 =
5 6 7 8"
 .El
 .Pp
 .Bl -enum -compact
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/aibs.4
--- a/head/share/man/man4/aibs.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/aibs.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\"	$FreeBSD$
+.\"	$FreeBSD: head/share/man/man4/aibs.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"	$NetBSD: aibs.4,v 1.2 2010/02/09 05:37:25 cnst Exp $
 .\"	$OpenBSD: aibs.4,v 1.4 2009/07/30 06:30:45 jmc Exp $
 .\"
@@ -90,15 +90,15 @@
 dev.aibs.0.fan.1: 0 700 7200
 .Pp
 > sysctl -d dev.aibs.0.{volt,temp,fan}
-dev.aibs.0.volt:=20
+dev.aibs.0.volt:
 dev.aibs.0.volt.0: Vcore Voltage
 dev.aibs.0.volt.1:  +3.3 Voltage
 dev.aibs.0.volt.2:  +5 Voltage
 dev.aibs.0.volt.3:  +12 Voltage
-dev.aibs.0.temp:=20
+dev.aibs.0.temp:
 dev.aibs.0.temp.0: CPU Temperature
 dev.aibs.0.temp.1: MB Temperature
-dev.aibs.0.fan:=20
+dev.aibs.0.fan:
 dev.aibs.0.fan.0: CPU FAN Speed
 dev.aibs.0.fan.1: CHASSIS FAN Speed
 .Ed
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/amdsmb.4
--- a/head/share/man/man4/amdsmb.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/amdsmb.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/amdsmb.4 233510 2012-03-26 15:18:14Z joe=
l $
 .\"
 .Dd December 31, 2005
 .Dt AMDSMB 4
@@ -33,7 +33,7 @@
 .Sh SYNOPSIS
 .Cd "device smbus"
 .Cd "device smb"
-.Cd "device amdsmb
+.Cd "device amdsmb"
 .Sh DESCRIPTION
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ath.4
--- a/head/share/man/man4/ath.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ath.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGES.
 .\"
-.\" $FreeBSD: head/share/man/man4/ath.4 232250 2012-02-28 13:19:34Z gavin $
+.\" $FreeBSD: head/share/man/man4/ath.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"/
 .Dd August 28, 2011
 .Dt ATH 4
@@ -129,14 +129,14 @@
 When multiple interfaces are configured each may have a separate
 mac address that is formed by setting the U/L bits in the mac
 address assigned to the underlying device.
-Any number of=20
+Any number of
 .Cm wds
 virtual interfaces may be configured together with
 .Cm hostap
 interfaces.
 Multiple
 .Cm station
-interfaces may be operated together with=20
+interfaces may be operated together with
 .Cm hostap
 interfaces to construct a wireless repeater device.
 The driver also support
@@ -191,7 +191,7 @@
 .Bd -literal -offset indent
 ifconfig wlan0 create wlandev ath0 wlanmode hostap \e
 	ssid paying-customers wepmode on wepkey 0x1234567890 \e
-	mode 11a up=20
+	mode 11a up
 ifconfig wlan1 create wlandev ath0 wlanmode hostap bssid \e
 	ssid freeloaders up
 ifconfig bridge0 create addm wlan0 addm wlan1 addm fxp0 up
@@ -202,7 +202,7 @@
 .Bd -literal -offset indent
 ifconfig wlan0 create wlandev ath0 wlanmode tdma \e
 	ssid tdma-test tmdaslot 0 tdmaslotlen 2500 \e
-	channel 36 up=20
+	channel 36 up
 .Ed
 .Sh DIAGNOSTICS
 .Bl -diag
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/atkbd.4
--- a/head/share/man/man4/atkbd.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/atkbd.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/atkbd.4 222793 2011-06-06 22:18:40Z jkim=
 $
+.\" $FreeBSD: head/share/man/man4/atkbd.4 233422 2012-03-24 13:37:57Z joel=
 $
 .\"
 .Dd January 29, 2008
 .Dt ATKBD 4
@@ -144,7 +144,6 @@
 This option will disable this feature and prevent the user from
 changing key assignment.
 .El
-.Pp
 .Ss Driver Flags
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/atp.4
--- a/head/share/man/man4/atp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/atp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/atp.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd November 12, 2009
 .Dt ATP 4
@@ -98,7 +98,7 @@
 .El
 .Pp
 To discover the product\-id of a touchpad, search for 'Trackpad' in the
-output of=20
+output of
 .Xr lshal 1
 and look up the property
 .Nm usb_device.product_id .
@@ -108,7 +108,7 @@
 .Pa /dev/atp0 ,
 which presents the mouse as a
 .Ar sysmouse
-or=20
+or
 .Ar mousesystems
 type device\-\-see
 .Xr moused 8
@@ -117,7 +117,7 @@
 .Xr moused 8
 can be configured to read touchpad data from
 .Pa /dev/atp0
-and pass it along to the=20
+and pass it along to the
 .Xr sysmouse 4
 driver so that any process wanting to utilize mouse operation (such as
 an X server) may fetch it from
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/bce.4
--- a/head/share/man/man4/bce.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/bce.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/bce.4 229585 2012-01-05 11:16:42Z brueff=
er $
+.\" $FreeBSD: head/share/man/man4/bce.4 233510 2012-03-26 15:18:14Z joel $
 .\"
 .Dd October 7, 2009
 .Dt BCE 4
@@ -266,7 +266,7 @@
 .It "bce%d: Could not allocate TX descriptor chain DMA tag!"
 The driver could not allocate a DMA tag for the controller's
 TX chain.
-.It "bce%d: Could not allocate TX descriptor chain DMA memory!
+.It "bce%d: Could not allocate TX descriptor chain DMA memory!"
 The driver could not allocate DMA addressable memory for the controller's
 TX chain.
 .It "bce%d: Could not map TX descriptor chain DMA memory!"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/bpf.4
--- a/head/share/man/man4/bpf.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/bpf.4	Tue Apr 17 11:51:51 2012 +0300
@@ -47,7 +47,7 @@
 .\" This document is derived in part from the enet man page (enet.4)
 .\" distributed with 4.3BSD Unix.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/bpf.4 233938 2012-04-06 06:55:21Z melifa=
ro $
 .\"
 .Dd June 15, 2010
 .Dt BPF 4
@@ -952,10 +952,33 @@
 .Fn BPF_STMT opcode operand
 and
 .Fn BPF_JUMP opcode operand true_offset false_offset .
-.Sh FILES
-.Bl -tag -compact -width /dev/bpf
-.It Pa /dev/bpf
-the packet filter device
+.Sh SYSCTL VARIABLES
+A set of
+.Xr sysctl 8
+variables controls the behaviour of the
+.Nm
+subsystem
+.Bl -tag -width indent
+.It Va net.bpf.optimize_writers: No 0
+Various programs use BPF to send (but not receive) raw packets
+(cdpd, lldpd, dhcpd, dhcp relays, etc. are good examples of such programs).
+They do not need incoming packets to be send to them. Turning this option =
on
+makes new BPF users to be attached to write-only interface list until prog=
ram
+explicitly specifies read filter via
+.Cm pcap_set_filter() .
+This removes any performance degradation for high-speed interfaces.
+.It Va net.bpf.stats:
+Binary interface for retrieving general statistics.
+.It Va net.bpf.zerocopy_enable: No 0
+Permits zero-copy to be used with net BPF readers. Use with caution.
+.It Va net.bpf.maxinsns: No 512
+Maximum number of instructions that BPF program can contain. Use
+.Xr tcpdump 1
+-d option to determine approximate number of instruction for any filter.
+.It Va net.bpf.maxbufsize: No 524288
+Maximum buffer size to allocate for packets buffer.
+.It Va net.bpf.bufsize: No 4096
+Default buffer size to allocate for packets buffer.
 .El
 .Sh EXAMPLES
 The following filter is taken from the Reverse ARP Daemon.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/bridge.4
--- a/head/share/man/man4/bridge.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/bridge.4	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/bridge.4 233422 2012-03-24 13:37:57Z joe=
l $
 .\"
 .Dd January 9, 2010
 .Dt IF_BRIDGE 4
@@ -167,7 +167,6 @@
 .Va net.link.bridge.log_stp
 variable using
 .Xr sysctl 8 .
-.Pp
 .Sh PACKET FILTERING
 Packet filtering can be used with any firewall package that hooks in via t=
he
 .Xr pfil 9
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/bt.4
--- a/head/share/man/man4/bt.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/bt.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/bt.4 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd June 18, 2006
 .Dt BT 4
@@ -51,48 +51,47 @@
 .Tn SCSI
 bus connected to a Buslogic/Mylex MultiMaster or compatible controller:
 .Bd -ragged -offset indent
-.Bl -column "BT-956CD " "ISA " "Commands " Description
 MultiMaster "W" Series Host Adapters:
+.Bl -column "BT-956CD " "ISA " "Commands " "Description"
+.Em "Adapter" Ta Em "Bus" Ta Em "Commands" Ta Em "Description"
+BT-948	PCI	192	Ultra SCSI-3
+BT-958	PCI	192	Wide Ultra SCSI-3
+BT-958D	PCI	192	Wide Differential Ultra SCSI-3
+.El
 .Pp
-.Em "Adapter   Bus   Commands  Description"
-BT-948    PCI     192     Ultra SCSI-3
-BT-958    PCI     192     Wide Ultra SCSI-3
-BT-958D   PCI     192     Wide Differential Ultra SCSI-3
+MultiMaster "C" Series Host Adapters:
+.Bl -column "BT-956CD " "ISA " "Commands " "Description"
+.Em "Adapter" Ta Em "Bus" Ta Em "Commands" Ta Em "Description"
+BT-946C	PCI	100	Fast SCSI-2
+BT-956C	PCI	100	Wide Fast SCSI-2
+BT-956CD	PCI	100	Wide Differential Fast SCSI-2
+BT-445C	VLB	100	Fast SCSI-2
+BT-747C	EISA	100	Fast SCSI-2
+BT-757C	EISA	100	Wide Fast SCSI-2
+BT-757CD	EISA	100	Wide Differential Fast SCSI-2
+BT-545C	ISA	50	Fast SCSI-2
+BT-540CF	ISA	50	Fast SCSI-2
 .El
-.Bl -column "BT-956CD " "ISA " "Commands " Description
-MultiMaster "C" Series Host Adapters:
 .Pp
-.Em "Adapter   Bus   Commands  Description"
-BT-946C   PCI     100     Fast SCSI-2
-BT-956C   PCI     100     Wide Fast SCSI-2
-BT-956CD  PCI     100     Wide Differential Fast SCSI-2
-BT-445C   VLB     100     Fast SCSI-2
-BT-747C   EISA    100     Fast SCSI-2
-BT-757C   EISA    100     Wide Fast SCSI-2
-BT-757CD  EISA    100     Wide Differential Fast SCSI-2
-BT-545C   ISA      50     Fast SCSI-2
-BT-540CF  ISA      50     Fast SCSI-2
+MultiMaster "S" Series Host Adapters:
+.Bl -column "BT-956CD " "ISA " "Commands " "Description"
+.Em "Adapter" Ta Em "Bus" Ta Em "Commands" Ta Em "Description"
+BT-445S	VLB	30	Fast SCSI-2
+BT-747S	EISA	30	Fast SCSI-2
+BT-747D	EISA	30	Differential Fast SCSI-2
+BT-757S	EISA	30	Wide Fast SCSI-2
+BT-757D	EISA	30	Wide Differential Fast SCSI-2
+BT-545S	ISA	30	Fast SCSI-2
+BT-542D	ISA	30	Differential Fast SCSI-2
+BT-742A	EISA	30	SCSI-2 (742A revision H)
+BT-542B	ISA	30	SCSI-2 (542B revision H)
 .El
-.Bl -column "BT-956CD " "ISA " "Commands " Description
-MultiMaster "S" Series Host Adapters:
 .Pp
-.Em "Adapter   Bus   Commands  Description"
-BT-445S   VLB      30     Fast SCSI-2
-BT-747S   EISA     30     Fast SCSI-2
-BT-747D   EISA     30     Differential Fast SCSI-2
-BT-757S   EISA     30     Wide Fast SCSI-2
-BT-757D   EISA     30     Wide Differential Fast SCSI-2
-BT-545S   ISA      30     Fast SCSI-2
-BT-542D   ISA      30     Differential Fast SCSI-2
-BT-742A   EISA     30     SCSI-2 (742A revision H)
-BT-542B   ISA      30     SCSI-2 (542B revision H)
-.El
-.Bl -column "BT-956CD " "ISA " "Commands " Description
 MultiMaster "A" Series Host Adapters:
-.Pp
-.Em "Adapter   Bus   Commands  Description"
-BT-742A   EISA     30     SCSI-2 (742A revisions A - G)
-BT-542B   ISA      30     SCSI-2 (542B revisions A - G)
+.Bl -column "BT-956CD " "ISA " "Commands " "Description"
+.Em "Adapter" Ta Em "Bus" Ta Em "Commands" Ta Em "Description"
+BT-742A	EISA	30	SCSI-2 (742A revisions A - G)
+BT-542B	ISA	30	SCSI-2 (542B revisions A - G)
 .El
 .Ed
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/bwi.4
--- a/head/share/man/man4/bwi.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/bwi.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/bwi.4 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd February 6, 2011
 .Dt BWI 4
@@ -72,16 +72,15 @@
 The
 .Nm
 driver supports Broadcom BCM43xx based wireless devices, including:
-.Pp
-.Bl -column -compact "Apple Airport Extreme" "BCM4306" "Mini PCI" "a/b/g" =
-offset 6n
-.It Em "Card	Chip	Bus	Standard"
+.Bl -column "Apple Airport Extreme" "BCM4306" "Mini PCI" "a/b/g" -offset 6n
+.It Em "Card" Ta Em "Chip" Ta Em "Bus" Ta Em "Standard"
 .It "Apple Airport Extreme	BCM4306	PCI	b/g"
 .It "Apple Airport Extreme	BCM4318	PCI	b/g"
 .It "ASUS WL-138g	BCM4318	PCI	b/g"
 .It "Buffalo WLI-CB-G54S	BCM4318	CardBus	b/g"
 .It "Buffalo WLI-PCI-G54S	BCM4306	PCI	b/g"
 .It "Compaq R4035 onboard	BCM4306	PCI	b/g"
-.It "Dell Wireless 1390 BCM4311 Mini PCI	b/g"
+.It "Dell Wireless 1390	BCM4311	Mini PCI	b/g"
 .It "Dell Wireless 1470	BCM4318	Mini PCI	b/g"
 .It "Dell Truemobile 1300 r2	BCM4306	Mini PCI	b/g"
 .It "Dell Truemobile 1400	BCM4309	Mini PCI	b/g"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/bwn.4
--- a/head/share/man/man4/bwn.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/bwn.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/bwn.4 222600 2011-06-02 09:56:53Z uqs $
+.\" $FreeBSD: head/share/man/man4/bwn.4 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd February 15, 2011
 .Dt BWN 4
@@ -75,13 +75,12 @@
 The
 .Nm
 driver supports Broadcom BCM43xx based wireless devices, including:
-.Pp
-.Bl -column -compact "Apple Airport Extreme" "BCM4306" "Mini PCI" "a/b/g" =
-offset 6n
-.It Em "Card	Chip	Bus	Standard"
+.Bl -column "Apple Airport Extreme" "BCM4306" "Mini PCI" "a/b/g"
+.It Em "Card" Ta Em "Chip" Ta Em "Bus" Ta Em "Standard"
 .It "Apple Airport Extreme	BCM4318	PCI	b/g"
 .It "ASUS WL-138g	BCM4318	PCI	b/g"
 .It "Buffalo WLI-CB-G54S	BCM4318	CardBus	b/g"
-.It "Dell Wireless 1390 BCM4311 Mini PCI	b/g"
+.It "Dell Wireless 1390	BCM4311	Mini PCI	b/g"
 .It "Dell Wireless 1470	BCM4318	Mini PCI	b/g"
 .It "Dell Truemobile 1400	BCM4309	Mini PCI	b/g"
 .It "HP Compaq 6715b	BCM4312	PCI	b/g"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/carp.4
--- a/head/share/man/man4/carp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/carp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/carp.4 230594 2012-01-26 19:11:08Z glebi=
us $
+.\" $FreeBSD: head/share/man/man4/carp.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd January 26, 2012
 .Dt CARP 4
@@ -187,7 +187,7 @@
 Type of the message displays new state of vhid.
 Please see
 .Xr devd.conf 5
-and=20
+and
 .Sx EXAMPLES
 section for more information.
 .Sh EXAMPLES
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/cas.4
--- a/head/share/man/man4/cas.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/cas.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,9 +23,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/cas.4 233426 2012-03-24 18:06:48Z marius=
 $
 .\"
-.Dd May 3, 2010
+.Dd March 24, 2012
 .Dt CAS 4
 .Os
 .Sh NAME
@@ -70,7 +70,6 @@
 .Xr ifconfig 8
 utility configures the adapter to receive and transmit Jumbo Frames.
 .Sh HARDWARE
-.Pp
 The chips supported by the
 .Nm
 driver are:
@@ -102,6 +101,9 @@
 .It
 Sun Quad GigaSwift Ethernet UTP (QGE)
 (part no.\& 501-6522)
+.It
+Sun Quad GigaSwift Ethernet PCI-X (QGE-X)
+(part no.\& 501-6738)
 .El
 .Sh NOTES
 On sparc64 the
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/cc_vegas.4
--- a/head/share/man/man4/cc_vegas.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/cc_vegas.4	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/cc_vegas.4 225583 2011-09-15 12:15:36Z l=
stewart $
+.\" $FreeBSD: head/share/man/man4/cc_vegas.4 233422 2012-03-24 13:37:57Z j=
oel $
 .\"
 .Dd September 15, 2011
 .Dt CC_VEGAS 4
@@ -39,7 +39,6 @@
 The Vegas congestion control algorithm uses what the authors term the actu=
al and
 expected transmission rates to determine whether there is congestion along=
 the
 network path i.e.
-.Pp
 .Bl -item -offset indent
 .It
 actual rate =3D (total data sent in a RTT) / RTT
@@ -54,7 +53,6 @@
 .Pp
 The algorithm aims to keep diff between two parameters alpha and beta, such
 that:
-.Pp
 .Bl -item -offset indent
 .It
 alpha < diff < beta
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/cd.4
--- a/head/share/man/man4/cd.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/cd.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/cd.4 231244 2012-02-09 04:37:30Z gjb $
+.\" $FreeBSD: head/share/man/man4/cd.4 233510 2012-03-26 15:18:14Z joel $
 .\"
 .Dd February 8, 2012
 .Dt CD 4
@@ -34,7 +34,7 @@
 .Sh SYNOPSIS
 .Cd device cd
 .Cd "options ""CHANGER_MIN_BUSY_SECONDS=3D3"""
-.Cd "options ""CHANGER_MAX_BUSY_SECONDS=3D11""
+.Cd "options ""CHANGER_MAX_BUSY_SECONDS=3D11"""
 .Sh DESCRIPTION
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/coda.4
--- a/head/share/man/man4/coda.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/coda.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,13 +22,13 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/coda.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd January 21, 2008
 .Dt CODA 4
 .Os
 .Sh NAME
-.Nm coda=20
+.Nm coda
 .Nd Coda Distributed File System
 .Sh SYNOPSIS
 To compile this driver into the kernel,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/cy.4
--- a/head/share/man/man4/cy.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/cy.4	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
 .\"     from: @(#)dca.4	5.2 (Berkeley) 3/27/91
 .\"	from: com.4,v 1.1 1993/08/06 11:19:07 cgd Exp
 .\"	from: sio.4,v 1.16 1995/06/26 06:05:30 bde Exp $
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/cy.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd May 24, 2004
 .Dt CY 4
@@ -44,7 +44,6 @@
 .Nm cy
 .Nd Cyclades Cyclom-Y serial driver
 .Sh SYNOPSIS
-.Pp
 For one ISA card:
 .Bd -ragged -offset indent -compact
 .Cd "device cy"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/dpms.4
--- a/head/share/man/man4/dpms.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/dpms.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/dpms.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd August 23, 2008
 .Dt DPMS 4
@@ -50,7 +50,6 @@
 .Sh SEE ALSO
 .Xr acpi_video 4
 .Sh BUGS
-.Pp
 The VESA BIOS DPMS calls do not provide any way to identify a particular
 display or adapter to manipulate.
 As a result,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ed.4
--- a/head/share/man/man4/ed.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ed.4	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/ed.4 232158 2012-02-25 15:21:43Z gjb $
+.\" $FreeBSD: head/share/man/man4/ed.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd February 25, 2012
 .Dt ED 4
@@ -414,7 +414,6 @@
 The Mitsubishi B8895 PC Card uses a DP83902, but its ASIC part is
 undocumented.
 Neither the NE2000 nor the WD83x0 drivers work with this card.
-.Pp
 .Sh BUGS
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/em.4
--- a/head/share/man/man4/em.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/em.4	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\"
 .\" * Other names and brands may be claimed as the property of others.
 .\"
-.\" $FreeBSD: head/share/man/man4/em.4 226264 2011-10-11 18:26:31Z glebius=
 $
+.\" $FreeBSD: head/share/man/man4/em.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd October 11, 2011
 .Dt EM 4
@@ -242,7 +242,6 @@
 Turn the identification LED of em0 off again:
 .Pp
 .Dl "echo 0 > /dev/led/em0"
-.Pp
 .Sh DIAGNOSTICS
 .Bl -diag
 .It "em%d: Unable to allocate bus resource: memory"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/epair.4
--- a/head/share/man/man4/epair.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/epair.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/epair.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd July 26, 2009
 .Dt EPAIR 4
@@ -97,14 +97,13 @@
 As with any other Ethernet interface one can configure
 .Xr vlan 4
 support on top of it.
-.Pp
 .Sh SEE ALSO
 .Xr ioctl 2 ,
 .Xr altq 4 ,
 .Xr bpf 4 ,
 .Xr if_bridge 4 ,
 .Xr vlan 4 ,
-.Xr loader.conf 5 ,=20
+.Xr loader.conf 5 ,
 .Xr rc.conf 5 ,
 .Xr ifconfig 8
 .Sh HISTORY
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/fdc.4
--- a/head/share/man/man4/fdc.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/fdc.4	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/fdc.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd May 11, 2006
 .Dt FDC 4
@@ -173,7 +173,6 @@
 per-drive device flags value of
 .Ar 0x20
 needs to be specified.
-.Pp
 .Ss Programming Interface
 In addition to the normal read and write functionality, the
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/fwohci.4
--- a/head/share/man/man4/fwohci.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/fwohci.4	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/fwohci.4 233422 2012-03-24 13:37:57Z joe=
l $
 .\"
 .\"
 .Dd March 3, 2008
@@ -60,7 +60,6 @@
 .Bd -literal -offset indent
 hw.firewire.phydma_enable=3D0
 .Ed
-.Pp
 .Sh HARDWARE
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/gem.4
--- a/head/share/man/man4/gem.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/gem.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/gem.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd December 25, 2009
 .Dt GEM 4
@@ -53,15 +53,14 @@
 driver provides support for the GMAC Ethernet hardware found mostly in
 the last Apple PowerBooks G3s and most G4-based Apple hardware, as
 well as Sun UltraSPARC machines.
-.Pp                                                                       =
    =20
-All controllers supported by the                                          =
    =20
-.Nm                                                                       =
    =20
-driver have TCP checksum offload capability for both receive and transmit,=
    =20
-support for the reception and transmission of extended frames for         =
    =20
-.Xr vlan 4                                                                =
    =20
-and a 512-bit multicast hash filter.                                      =
    =20
+.Pp
+All controllers supported by the
+.Nm
+driver have TCP checksum offload capability for both receive and transmit,
+support for the reception and transmission of extended frames for
+.Xr vlan 4
+and a 512-bit multicast hash filter.
 .Sh HARDWARE
-.Pp
 Chips supported by the
 .Nm
 driver include:
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/geom_fox.4
--- a/head/share/man/man4/geom_fox.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/geom_fox.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/geom_fox.4 233422 2012-03-24 13:37:57Z j=
oel $
 .\"
 .Dd January 2, 2005
 .Dt GEOM_FOX 4
@@ -85,7 +85,6 @@
 driver will disallow write operations to the underlying devices once the
 fox device has been opened for writing.
 .Sh EXAMPLES
-.Pp
 .Bl -bullet -compact
 .It
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/geom_uzip.4
--- a/head/share/man/man4/geom_uzip.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/geom_uzip.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/geom_uzip.4 233422 2012-03-24 13:37:57Z =
joel $
 .\"
 .Dd October 9, 2006
 .Dt GEOM_UZIP 4
@@ -90,7 +90,6 @@
    Sectorsize: 512
    Mode: r1w0e1
 .Ed
-.Pp
 .Sh SEE ALSO
 .Xr GEOM 4 ,
 .Xr md 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/gre.4
--- a/head/share/man/man4/gre.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/gre.4	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/gre.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd June 20, 2008
 .Dt GRE 4
@@ -337,4 +337,4 @@
 would belong to this interface.
 .Pp
 RFC1701 is not fully supported, however all unsupported features have been
-deprecated in RFC2784.=20
+deprecated in RFC2784.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/hptiop.4
--- a/head/share/man/man4/hptiop.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/hptiop.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/hptiop.4 224583 2011-08-01 21:12:41Z del=
phij $
+.\" $FreeBSD: head/share/man/man4/hptiop.4 233422 2012-03-24 13:37:57Z joe=
l $
 .\"
 .Dd August 1, 2011
 .Dt HPTIOP 4
@@ -100,7 +100,6 @@
 .Nm
 device driver first appeared in
 .Fx 7.0 .
-.Pp
 .Sh AUTHORS
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/igb.4
--- a/head/share/man/man4/igb.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/igb.4	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\"
 .\" * Other names and brands may be claimed as the property of others.
 .\"
-.\" $FreeBSD: head/share/man/man4/igb.4 226263 2011-10-11 15:41:07Z glebiu=
s $
+.\" $FreeBSD: head/share/man/man4/igb.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd October 11, 2011
 .Dt IGB 4
@@ -174,7 +174,6 @@
 Turn the identification LED of igb0 off again:
 .Pp
 .Dl "echo 0 > /dev/led/igb0"
-.Pp
 .Sh DIAGNOSTICS
 .Bl -diag
 .It "igb%d: Unable to allocate bus resource: memory"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ip.4
--- a/head/share/man/man4/ip.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ip.4	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)ip.4	8.2 (Berkeley) 11/30/93
-.\" $FreeBSD: head/share/man/man4/ip.4 227501 2011-11-14 15:57:03Z andre $
+.\" $FreeBSD: head/share/man/man4/ip.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd November 14, 2011
 .Dt IP 4
@@ -392,7 +392,6 @@
 .Va net.inet.ip.portrange.randomtime
 are 10 port allocations per second and 45 seconds correspondingly.
 .Ss "Multicast Options"
-.Pp
 .Tn IP
 multicasting is supported only on
 .Dv AF_INET
@@ -682,7 +681,6 @@
 source filter entries which the kernel may allocate.
 .\"-----------------------
 .Ss "Raw IP Sockets"
-.Pp
 Raw
 .Tn IP
 sockets are connectionless,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ipmi.4
--- a/head/share/man/man4/ipmi.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ipmi.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ipmi.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd July 10, 2007
 .Dt IPMI 4
@@ -63,7 +63,7 @@
 .Ar port
 and
 .Ar spacing
-are not specified the interface type default will be used.  Only specify=20
+are not specified the interface type default will be used.  Only specify
 either the
 .Ar port
 for I/O access or
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ipw.4
--- a/head/share/man/man4/ipw.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ipw.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ipw.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd April 13, 2008
 .Dt IPW 4
@@ -127,7 +127,7 @@
 The driver failed to load the firmware image using the
 .Xr firmware 9
 subsystem.
-Verify the=20
+Verify the
 .Xr ipwfw 4
 firmware module is installed and the license agreement
 .Xr loader 8
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/isci.4
--- a/head/share/man/man4/isci.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/isci.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-.\"=20
+.\"
 .\" Copyright (c) 2012 Intel Corporation
 .\" All rights reserved.
-.\"=20
+.\"
 .\" Redistribution and use in source and binary forms, with or without
 .\" modification, are permitted provided that the following conditions
 .\" are met:
@@ -13,7 +13,7 @@
 .\"    ("Disclaimer") and any redistribution must be conditioned upon
 .\"    including a substantially similar Disclaimer requirement for further
 .\"    binary redistribution.
-.\"=20
+.\"
 .\" NO WARRANTY
 .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 .\" "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -26,12 +26,12 @@
 .\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 .\" IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGES.
-.\"=20
+.\"
 .\" isci driver man page.
 .\"
 .\" Author: Jim Harris <jimharris at FreeBSD.org>
 .\"
-.\" $FreeBSD: head/share/man/man4/isci.4 232056 2012-02-23 18:48:02Z bruef=
fer $
+.\" $FreeBSD: head/share/man/man4/isci.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd January 23, 2012
 .Dt ISCI 4
@@ -86,7 +86,7 @@
 options ISCI_LOGGING
 .Ed
 .Pp
-to the kernel configuration file.=20
+to the kernel configuration file.
 .Sh SEE ALSO
 .Xr cd 4 ,
 .Xr ch 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/iscsi_initiator.4
--- a/head/share/man/man4/iscsi_initiator.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/iscsi_initiator.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" Copyright (c) 2007 Daniel Braniss <danny at cs.huji.ac.il>
+.\" Copyright (c) 2007-2010 Daniel Braniss <danny at cs.huji.ac.il>
 .\" All rights reserved.
 .\"
 .\" Redistribution and use in source and binary forms, with or without
@@ -22,11 +22,11 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/iscsi_initiator.4 234233 2012-04-13 18:2=
1:56Z jpaetzel $
 .\"
-.Dd May 9, 2010
+.Dd August 3, 2010
+.Os
 .Dt ISCSI_INITIATOR 4
-.Os
 .Sh NAME
 .Nm iscsi_initiator
 .Nd kernel driver for the iSCSI protocol
@@ -48,38 +48,36 @@
 The
 .Nm
 implements the kernel side of the Internet SCSI (iSCSI) network
-protocol standard.
-The userland companion is
+protocol standard, the user land companion is
 .Xr iscontrol 8 ,
 and permits access to remote
 .Em virtual
 SCSI devices via
 .Xr cam 4 .
 .Sh SYSCTL VARIABLES
-.Bl -tag -width "net.iscsi.n.targedaddress"
+.Bl -tag -width ".Va net.iscsi.n.targeaddress"
 .It Va debug.iscsi_initiator
 set the debug-level, 0 means no debugging, 9 for maximum.
 .It Va net.iscsi.isid
 the initiator part of the Session Identifier.
-.El
-.Pp
-The following are informative only:
-.Bl -tag -width "net.iscsi.n.targedaddress"
+.It Va "kern.cam.cam_srch_hi=3D1"
+allow search above LUN 7 for SCSI3 and greater devices.
+.It "the following are informative only:"
 .It Va net.iscsi.driver_version
 the current version of the driver.
 .It Va net.iscsi.sessions
 the number of current active sessions.
 .It Va net.iscsi.n.targetname
-the target name of session
+is the targe name of session
 .Em n .
-.It Va net.iscsi.n.targedaddress
-the IP address of the target of session
+.It Va net.iscsi.n.targeaddress
+is the IP address of the target of session
 .Em n .
 .It Va net.iscsi.n.stats
-statistics for session
-.Em n
+are some statistics for session
+.EM n
 .It Va net.iscsi.n.pid
-the=20
+is the=20
 .Em "process id"
 of the userland side of session
 .Em n ,
@@ -90,8 +88,8 @@
 The=20
 .Nm
 driver creates the following:
+.Bl -tag -width ".Pa /dev/iscsi%dxx" -compact
 .Pp
-.Bl -tag -width ".Pa /dev/iscsi%dxx" -compact
 .It Pa /dev/iscsi
 used to create new sessions.
 .It Pa /dev/iscsi%d
@@ -105,5 +103,6 @@
 iSCSI RFC 3720
 .\" .Sh HISTORY
 .\" .Sh AUTHORS
+This software was written by Daniel Braniss <danny at cs.huji.ac.il>
 .Sh BUGS
 The lun discovery method is old-fashioned.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/isp.4
--- a/head/share/man/man4/isp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/isp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\"
 .\" Additional Copyright (c) 2006 by Marcus Alves Grando
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/isp.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd February 28, 2007
 .Dt ISP 4
@@ -138,7 +138,6 @@
 Qlogic 2432 Optical Fibre Channel PCIe cards (4 Gigabit)
 .El
 .Sh CONFIGURATION OPTIONS
-.Pp
 Target mode support may be enabled with the
 .Pp
 .Cd options ISP_TARGET_MODE
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/iwi.4
--- a/head/share/man/man4/iwi.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/iwi.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/iwi.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd April 13, 2008
 .Dt IWI 4
@@ -127,7 +127,7 @@
 The driver failed to load the firmware image using the
 .Xr firmware 9
 subsystem.
-Verify the=20
+Verify the
 .Xr iwifw 4
 firmware module is installed and the license agreement
 .Xr loader 8
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/iwn.4
--- a/head/share/man/man4/iwn.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/iwn.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,15 +23,14 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/iwn.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
-.Dd July 20, 2010
+.Dd March 27, 2012
 .Dt IWN 4
 .Os
 .Sh NAME
 .Nm iwn
-.Nd Intel Wireless WiFi Link 4965/1000/5000/5150/5300/6000/6050=20
-IEEE 802.11n driver
+.Nd Intel IEEE 802.11n wireless network driver
 .Sh SYNOPSIS
 To compile this driver into the kernel,
 include the following lines in your
@@ -51,6 +50,8 @@
 .Cd "device iwn5000fw"
 .Cd "device iwn5150fw"
 .Cd "device iwn6000fw"
+.Cd "device iwn6000g2afw"
+.Cd "device iwn6000g2bfw"
 .Cd "device iwn6050fw"
 .Ed
 .Pp
@@ -71,15 +72,32 @@
 iwn5000fw_load=3D"YES"
 iwn5150fw_load=3D"YES"
 iwn6000fw_load=3D"YES"
+iwn6000g2afw_load=3D"YES"
+iwn6000g2bfw_load=3D"YES"
 iwn6050fw_load=3D"YES"
 .Ed
 .Sh DESCRIPTION
 The
 .Nm
-driver provides support for
-.Tn Intel
-Wireless WiFi Link 4965, 1000, 5000 and 6000 series of=20
-PCI-Express network adapters.
+driver provides support for:
+.Pp
+.Bl -tag -width Ds -offset indent -compact
+.It Intel Centrino Advanced-N 6200
+.It Intel Centrino Advanced-N 6205
+.It Intel Centrino Advanced-N 6230
+.It Intel Centrino Advanced-N + WiMAX 6250
+.It Intel Centrino Ultimate-N 6300
+.It Intel Centrino Wireless-N 130
+.It Intel Centrino Wireless-N 1000
+.It Intel Centrino Wireless-N 1030
+.It Intel Centrino Wireless-N + WiMAX 6150
+.It Intel Ultimate N WiFi Link 5300
+.It Intel Wireless WiFi Link 4965
+.It Intel WiFi Link 5100
+.It Intel WiMAX/WiFi Link 5150
+.It Intel WiMAX/WiFi Link 5350
+.El
+.Pp
 .Nm
 supports
 .Cm station ,
@@ -133,7 +151,7 @@
 The driver failed to load the firmware image using the
 .Xr firmware 9
 subsystem.
-Verify the=20
+Verify the
 .Xr iwnfw 4
 firmware module is present.
 .It "iwn%d: could not load boot firmware"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/iwnfw.4
--- a/head/share/man/man4/iwnfw.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/iwnfw.4	Tue Apr 17 11:51:51 2012 +0300
@@ -20,7 +20,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/iwnfw.4 220896 2011-04-20 17:53:39Z bsch=
midt $
+.\" $FreeBSD: head/share/man/man4/iwnfw.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd April 20, 2011
 .Dt IWNFW 4
@@ -65,7 +65,7 @@
 .Ed
 .Sh DESCRIPTION
 This module provides access to firmware sets for the
-Intel Wireless WiFi Link 4965, 1000, 5000 and 6000 series of=20
+Intel Wireless WiFi Link 4965, 1000, 5000 and 6000 series of
 IEEE 802.11n adapters.
 It may be
 statically linked into the kernel, or loaded as a module.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ixgbe.4
--- a/head/share/man/man4/ixgbe.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ixgbe.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 .\" Copyright (c) 2001-2008, Intel Corporation
 .\" All rights reserved.
-.\"=20
+.\"
 .\" Redistribution and use in source and binary forms, with or without
 .\" modification, are permitted provided that the following conditions are=
 met:
 .\"
@@ -29,7 +29,7 @@
 .\"
 .\" * Other names and brands may be claimed as the property of others.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ixgbe.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd December 19, 2010
 .Dt IXGBE 4
@@ -79,13 +79,13 @@
 .Pp
 .Bl -bullet -compact
 .It
-Intel(R) 10 Gigabit XF SR/AF Dual Port Server Adapter=20
+Intel(R) 10 Gigabit XF SR/AF Dual Port Server Adapter
 .It
 Intel(R) 10 Gigabit XF SR/LR Server Adapter
 .It
 Intel(R) 82598EB 10 Gigabit AF Network Connection
 .It
-Intel(R) 82598EB 10 Gigabit AT CX4 Network Connection                 =20
+Intel(R) 82598EB 10 Gigabit AT CX4 Network Connection
 .El
 .Sh DIAGNOSTICS
 .Bl -diag
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ksyms.4
--- a/head/share/man/man4/ksyms.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ksyms.4	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ksyms.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd April 5, 2009
 .Dt KSYMS 4
@@ -42,15 +42,15 @@
 .Sh DESCRIPTION
 The
 .Pa /dev/ksyms
-character device provides a read-only interface to a snapshot of the kerne=
l=20
+character device provides a read-only interface to a snapshot of the kernel
 symbol table.  The in-kernel symbol manager is designed to be able to hand=
le
-many types of symbols tables, however, only=20
+many types of symbols tables, however, only
 .Xr elf 5
 symbol tables are supported by this device.  The ELF format image contains=
 two
-sections: a symbol table and a corresponding string table. =20
+sections: a symbol table and a corresponding string table.
 .Bl -tag -width indent -offset indent
 .It Dv Symbol Table
-The SYMTAB section contains the symbol table entries present in the curren=
t=20
+The SYMTAB section contains the symbol table entries present in the current
 running kernel, including the symbol table entries of any loaded modules. =
The
 symbols are ordered by the kernel module load time starting with kernel fi=
le
 symbols first, followed by the first loaded module's symbols and so on.
@@ -65,10 +65,10 @@
 Since
 .Pa /dev/ksyms
 has no text or data, most of the fields are initialized to NULL.
-The=20
-.Nm=20
+The
+.Nm
 driver does not block the loading or unloading of modules into the kernel
-while the=20
+while the
 .Pa /dev/ksyms
 file is open but may contain stale data.
 .Sh IOCTLS
@@ -87,29 +87,29 @@
 the kernel symbol table.
 .It Dv KIOCGADDR (void *)
 Returns the address of the kernel symbol table mapped in
-the process memory. =20
+the process memory.
 .El
 .Sh FILES
 .Bl -tag -width /dev/ksymsX
 .It Pa /dev/ksyms
 .El
 .Sh ERRORS
-An=20
+An
 .Xr open 2
 of
 .Pa /dev/ksyms
-will fail if:=20
+will fail if:
 .Bl -tag -width Er
 .It Bq Er EBUSY
-The device is already open.  A process must close=20
+The device is already open.  A process must close
 .Pa /dev/ksyms
-before it can be opened again.=20
+before it can be opened again.
 .It Bq Er ENOMEM
 There is a resource shortage in the kernel.
 .It Bq Er ENXIO
 The driver was unsuccessful in creating a snapshot of the kernel symbol
 table.  This may occur if the kernel was in the process of loading or
-unloading a module.=20
+unloading a module.
 .El
 .Sh SEE ALSO
 .Xr ioctl 2 ,
@@ -128,7 +128,7 @@
 .Nm
 driver first appeared in
 .Fx 8.0
-to support=20
+to support
 .Xr lockstat 1 .
 .Sh AUTHORS
 The
@@ -137,7 +137,7 @@
 .An Stacey Son
 .Aq sson at FreeBSD.org .
 .Sh BUGS
-Because files can be dynamically linked into the kernel at any time the sy=
mbol=20
+Because files can be dynamically linked into the kernel at any time the sy=
mbol
 information can vary.  When you open the
 .Pa /dev/ksyms
 file, you have access to an ELF image which represents a snapshot of the s=
tate of the kernel symbol information at that instant in time. Keeping the =
device open does not block the loading or unloading of kernel modules.  To =
get a new snapshot you must close and re-open the device.
@@ -147,12 +147,12 @@
 file once at a time.  The process must close the
 .Pa /dev/ksyms
 before it is allowed to open it again.
-.Pp=20
+.Pp
 The
 .Nm
-driver uses the calling process' memory address space to store the snapsho=
t. =20
+driver uses the calling process' memory address space to store the snapsho=
t.
 .Xr ioctl 2
 can be used to get the memory address where the symbol table is stored to
-save kernel memory.=20
+save kernel memory.
 .Xr mmap 2
-may also be used but it will map it to another address.=20
+may also be used but it will map it to another address.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ktr.4
--- a/head/share/man/man4/ktr.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ktr.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ktr.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd January 25, 2005
 .Dt KTR 4
@@ -171,7 +171,7 @@
 enables logging of
 .Nm
 entries to disk if it is set to one.
-Setting this to 0 will terminate logging to disk and revert to=20
+Setting this to 0 will terminate logging to disk and revert to
 logging to the normal ktr ring buffer.
 Data is not sent to the ring buffer while logging to disk.
 .It Va debug.ktr.alq_max
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/lmc.4
--- a/head/share/man/man4/lmc.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/lmc.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 .\"
-.\" $FreeBSD: head/share/man/man4/lmc.4 231244 2012-02-09 04:37:30Z gjb $
+.\" $FreeBSD: head/share/man/man4/lmc.4 233510 2012-03-26 15:18:14Z joel $
 .\"
 .\" Copyright (c) 2002-2005 David Boggs. (boggs at boggs.palo-alto.ca.us)
 .\" All rights reserved.
@@ -407,7 +407,7 @@
 with
 .Xr lmcconfig 8 :
 .Pp
-.Dl "lmcconfig lmc0 -a 2
+.Dl "lmcconfig lmc0 -a 2"
 .Pp
 .Dq Fl a Li 2
 selects the PCI bus clock as the transmit clock.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/malo.4
--- a/head/share/man/man4/malo.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/malo.4	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGES.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/malo.4 233992 2012-04-07 09:05:30Z joel $
 .\"/
 .Dd October 21, 2009
 .Dt MALO 4
@@ -88,12 +88,11 @@
 The following cards are among those supported by the
 .Nm
 driver:
-.Pp
-.Bl -column -compact "Microcom Travelcard" "MALO111" "CardBus" "a/b/g" -of=
fset 6n
-.Em "Card	Chip	Bus	Standard"
-Netgear WG311v3	88W8335	PCI	b/g
-Tenda TWL542P	88W8335	PCI	b/g
-U-Khan UW-2054i	88W8335	PCI	b/g
+.Bl -column "Netgear WG311v3" "88W8335" "PCI" "b/g"
+.Em "Card" Ta Em "Chip" Ta Em "Bus" Ta Em "Standard"
+.It "Netgear WG311v3" Ta "88W8335" Ta "PCI" Ta "b/g"
+.It "Tenda TWL542P" Ta "88W8335" Ta "PCI" Ta "b/g"
+.It "U-Khan UW-2054i" Ta "88W8335" Ta "PCI" Ta "b/g"
 .El
 .Sh EXAMPLES
 Join an existing BSS network (i.e., connect to an access point):
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.i386/apm.4
--- a/head/share/man/man4/man4.i386/apm.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/man4.i386/apm.4	Tue Apr 17 11:51:51 2012 +0300
@@ -9,7 +9,7 @@
 .\" the author assume any responsibility for damages incurred with its
 .\" use.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/man4.i386/apm.4 233992 2012-04-07 09:05:=
30Z joel $
 .\"
 .Dd November 1, 1994
 .Dt APM 4 i386
@@ -104,17 +104,17 @@
 .It
 .Nm
 polls APM events and handles the following events.
-.Bl -column PMEV_POWERSTATECHANGEXXX "suspend system xxxxx"
-.It Sy "Name                  " "Action          " "Description"
-.It Dv "PMEV_STANDBYREQ       " No "suspend system  " "standby request"
-.It Dv "PMEV_SUSPENDREQ       " No "suspend system  " "suspend request"
-.It Dv "PMEV_USERSUSPENDREQ   " No "suspend system  " "user suspend reques=
t"
-.It Dv "PMEV_CRITSUSPEND      " No "suspend system  " "critical suspend re=
quest"
-.It Dv "PMEV_NORMRESUME       " No "resume system   " "normal resume"
-.It Dv "PMEV_CRITRESUME       " No "resume system   " "critical resume"
-.It Dv "PMEV_STANDBYRESUME    " No "resume system   " "standby resume"
-.It Dv "PMEV_BATTERYLOW       " No "notify message  " "battery low"
-.It Dv "PMEV_UPDATETIME       " No "adjust clock    " "update time"
+.Bl -column "xxxxxxxxxxxxxxxxx" "xxxxxxxxxxxxx" "xxxxxxxx"
+.It Sy "Name" Ta Sy "Action" Ta Sy "Description"
+.It Dv "PMEV_STANDBYREQ" Ta No "suspend system" Ta "standby request"
+.It Dv "PMEV_SUSPENDREQ" Ta No "suspend system" Ta "suspend request"
+.It Dv "PMEV_USERSUSPENDREQ" Ta No "suspend system" Ta "user suspend reque=
st"
+.It Dv "PMEV_CRITSUSPEND" Ta No "suspend system" Ta "critical suspend requ=
est"
+.It Dv "PMEV_NORMRESUME" Ta No "resume system" Ta "normal resume"
+.It Dv "PMEV_CRITRESUME" Ta No "resume system" Ta "critical resume"
+.It Dv "PMEV_STANDBYRESUME" Ta No "resume system" Ta "standby resume"
+.It Dv "PMEV_BATTERYLOW" Ta No "notify message" Ta "battery low"
+.It Dv "PMEV_UPDATETIME" Ta No "adjust clock" Ta "update time"
 .El
 .El
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.i386/glxsb.4
--- a/head/share/man/man4/man4.i386/glxsb.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/man4.i386/glxsb.4	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
 .\"ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\"OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/man4.i386/glxsb.4 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd June 8, 2008
 .Dt GLXSB 4 i386
@@ -66,7 +66,7 @@
 key's length is !=3D 128 bits.
 This prevents the use of the
 .Nm
-device driver with AES keys of length !=3D 128 bits.=20
+device driver with AES keys of length !=3D 128 bits.
 .Sh SEE ALSO
 .Xr crypto 4 ,
 .Xr intro 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.powerpc/abtn.4
--- a/head/share/man/man4/man4.powerpc/abtn.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/man4.powerpc/abtn.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/man4.powerpc/abtn.4 226648 2011-10-23 02=
:52:20Z nwhitehorn $
+.\" $FreeBSD: head/share/man/man4/man4.powerpc/abtn.4 233648 2012-03-29 05=
:02:12Z eadler $
 .\"
 .Dd October 16, 2011
 .Dt ABTN 4
@@ -60,7 +60,7 @@
 .Nm
 driver sends events to
 .Xr devd 8
-for the following events under the=20
+for the following events under the
 .Cd PMU
 system, and
 .Cd keys
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.powerpc/akbd.4
--- a/head/share/man/man4/man4.powerpc/akbd.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/man4.powerpc/akbd.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/man4.powerpc/akbd.4 226449 2011-10-16 21=
:01:42Z nwhitehorn $
+.\" $FreeBSD: head/share/man/man4/man4.powerpc/akbd.4 233648 2012-03-29 05=
:02:12Z eadler $
 .\"
 .Dd December 3, 2009
 .Dt AKBD 4
@@ -63,15 +63,15 @@
 .Nm
 driver sends events to
 .Xr devd 8
-for the following events under the=20
+for the following events under the
 .Cd PMU
 system:
 .Pp
 .Bl -bullet -compact
 .It
-Power button -=20
+Power button -
 .Cd "Button"
-subsystem,=20
+subsystem,
 .Cd "pressed"
 type.
 .El
@@ -81,7 +81,7 @@
 driver supports the following sysctl variable for configuring the Fn keys:
 .Bl -tag -width indent
 .It Va dev.akbd.%d.fn_keys_function_as_primary
-Set the Fn keys to be their F-key type as default.  A value of 0 causes th=
e=20
+Set the Fn keys to be their F-key type as default.  A value of 0 causes the
 F-keys keys to work as special keys by default (
 .Xr abtn 4 )
 and a value of 1 sets them to behave as F-keys by default.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.powerpc/bm.4
--- a/head/share/man/man4/man4.powerpc/bm.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/man4.powerpc/bm.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/man4.powerpc/bm.4 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd July 3, 2008
 .Dt BM 4
@@ -50,11 +50,10 @@
 The
 .Nm
 driver provides support for the BMac ethernet hardware found mostly in
-G3-based Apple hardware.=20
-It is a close relative of the Sun HME controller found in contemporary=20
+G3-based Apple hardware.
+It is a close relative of the Sun HME controller found in contemporary
 Sun workstations.
 .Sh HARDWARE
-.Pp
 Chips supported by the
 .Nm
 driver include:
@@ -65,7 +64,6 @@
 .It
 Apple BMAC+ Onboard Ethernet
 .El
-.Pp
 .Sh SEE ALSO
 .Xr altq 4 ,
 .Xr hme 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.powerpc/cuda.4
--- a/head/share/man/man4/man4.powerpc/cuda.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/man4.powerpc/cuda.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/man4.powerpc/cuda.4 233648 2012-03-29 05=
:02:12Z eadler $
 .\"
 .Dd December 3, 2009
 .Dt CUDA 4
@@ -46,7 +46,7 @@
 chip found in pre-Core99 Apple hardware, such as the Power Macintosh G3.
 .Pp
 The Apple CUDA controller is a multi-purpose ASIC that provides power
-control and an=20
+control and an
 .Xr adb 4
 interface.
 .Sh HARDWARE
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.powerpc/smu.4
--- a/head/share/man/man4/man4.powerpc/smu.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/man4.powerpc/smu.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/man4.powerpc/smu.4 233648 2012-03-29 05:=
02:12Z eadler $
 .\"
 .Dd February 22, 2010
 .Dt SMU 4
@@ -103,7 +103,7 @@
 .Sh LED INTERFACE
 The
 .Nm
-driver provides an=20
+driver provides an
 .Xr led 4
 annunciator interface at
 .Pa /dev/led/sleepled .
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.powerpc/snd_a=
i2s.4
--- a/head/share/man/man4/man4.powerpc/snd_ai2s.4	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/share/man/man4/man4.powerpc/snd_ai2s.4	Tue Apr 17 11:51:51 2012 =
+0300
@@ -23,7 +23,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/man4.powerpc/snd_ai2s.4 233648 2012-03-2=
9 05:02:12Z eadler $
 .\"
 .Dd January 20, 2009
 .Dt SND_AI2S 4
@@ -49,12 +49,11 @@
 .Sh DESCRIPTION
 The
 .Nm
-driver provides support for the Apple I2S audio controllers found=20
+driver provides support for the Apple I2S audio controllers found
 predominantly in G4 and G5 machines, along with the snapper and tumbler
 codecs. Some machines (e.g. the Mac Mini) do not have configurable
 codecs and so lack hardware volume control.
 .Sh HARDWARE
-.Pp
 Chips supported by the
 .Nm
 driver include:
@@ -65,7 +64,6 @@
 .It
 Apple Snapper Audio
 .El
-.Pp
 .Sh SEE ALSO
 .Xr sound 4 ,
 .Xr snd_davbus 4
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/man4.powerpc/snd_d=
avbus.4
--- a/head/share/man/man4/man4.powerpc/snd_davbus.4	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/share/man/man4/man4.powerpc/snd_davbus.4	Tue Apr 17 11:51:51 201=
2 +0300
@@ -23,7 +23,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/man4.powerpc/snd_davbus.4 233422 2012-03=
-24 13:37:57Z joel $
 .\"
 .Dd January 20, 2009
 .Dt SND_DAVBUS 4
@@ -52,7 +52,6 @@
 driver provides support for the Apple Davbus audio controllers found in
 many G3-era Apple machines.
 .Sh HARDWARE
-.Pp
 Chips supported by the
 .Nm
 driver include:
@@ -63,7 +62,6 @@
 .It
 Apple Screamer Audio
 .El
-.Pp
 .Sh SEE ALSO
 .Xr sound 4 ,
 .Xr snd_ai2s 4
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/md.4
--- a/head/share/man/man4/md.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/md.4	Tue Apr 17 11:51:51 2012 +0300
@@ -5,7 +5,7 @@
 .\" this stuff is worth it, you can buy me a beer in return.   Poul-Hennin=
g Kamp
 .\" ----------------------------------------------------------------------=
------
 .\"
-.\" $FreeBSD: head/share/man/man4/md.4 220617 2011-04-14 08:53:04Z pluknet=
 $
+.\" $FreeBSD: head/share/man/man4/md.4 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd October 30, 2007
 .Dt MD 4
@@ -76,7 +76,7 @@
 .Pa /h/foo/ARM-MD
 will be loaded as the initial image each boot.
 To create the image to use, please follow the steps to create a file-backed
-disk found in the=20
+disk found in the
 .Xr mdconfig 8
 man page.
 Other tools will also create these images, such as NanoBSD.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/mld.4
--- a/head/share/man/man4/mld.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/mld.4	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/mld.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd May 27, 2009
 .Dt MLD 4
@@ -52,7 +52,7 @@
 applications.
 Multicast routing protocol daemons may open a raw socket to directly
 interact with
-.Nm=20
+.Nm
 and receive membership reports.
 .Pp
 As of
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/mmc.4
--- a/head/share/man/man4/mmc.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/mmc.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/mmc.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd October 8, 2008
 .Dt MMC 4
@@ -42,7 +42,7 @@
 All SD or MMC cards in the system attach to an instance of
 .Nm .
 The
-.Nm=20
+.Nm
 bus typically has only one slot, and only memory cards.
 MultiMediaCards exist only in memory.
 SD Cards exist as memory, I/O, or combination cards.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/mos.4
--- a/head/share/man/man4/mos.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/mos.4	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD: head/share/man/man4/mos.4 232257 2012-02-28 15:45:42Z kevlo $
+.\" $FreeBSD: head/share/man/man4/mos.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd February 14, 2011
 .Dt MOS 4
@@ -43,7 +43,7 @@
 .Sh DESCRIPTION
 The
 .Nm
-driver provides support for USB Ethernet adapters based on the=20
+driver provides support for USB Ethernet adapters based on the
 Moschip MCS7730/MCS7830/MCS7832 chipset.
 .Pp
 The adapters that contain the Moschip MCS7730/MCS7830/MCS7832 chipset
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/mps.4
--- a/head/share/man/man4/mps.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/mps.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-.\"=20
+.\"
 .\" Copyright (c) 2010 Spectra Logic Corporation
 .\" All rights reserved.
-.\"=20
+.\"
 .\" Redistribution and use in source and binary forms, with or without
 .\" modification, are permitted provided that the following conditions
 .\" are met:
@@ -13,7 +13,7 @@
 .\"    ("Disclaimer") and any redistribution must be conditioned upon
 .\"    including a substantially similar Disclaimer requirement for further
 .\"    binary redistribution.
-.\"=20
+.\"
 .\" NO WARRANTY
 .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 .\" "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -26,13 +26,13 @@
 .\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 .\" IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGES.
-.\"=20
+.\"
 .\" mps driver man page.
 .\"
 .\" Author: Ken Merry <ken at FreeBSD.org>
 .\"
 .\" $Id: //depot/SpectraBSD/head/share/man/man4/mps.4#6 $
-.\" $FreeBSD: head/share/man/man4/mps.4 231170 2012-02-07 23:43:29Z ken $
+.\" $FreeBSD: head/share/man/man4/mps.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd February 7, 2012
 .Dt MPS 4
@@ -117,7 +117,7 @@
 .Ed
 .Pp
 To set the maximum number of DMA chains allocated for all adapters,
-set the following variable in=20
+set the following variable in
 .Xr loader.conf 5 :
 .Bd -literal -offset indent
 hw.mps.max_chains=3DNNNN
@@ -207,7 +207,7 @@
 .It
 Not endian safe.
 It only works on little endian machines (e.g. amd64 and i386).
-.It=20
+.It
 No userland utility available (e.g.
 .Xr mptutil 8)
 .It
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/mwl.4
--- a/head/share/man/man4/mwl.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/mwl.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGES.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/mwl.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"/
 .Dd July 8, 2009
 .Dt MWL 4
@@ -93,14 +93,14 @@
 When multiple interfaces are configured each may have a separate
 mac address that is formed by setting the U/L bits in the mac
 address assigned to the underlying device.
-Any number of=20
+Any number of
 .Cm wds
 virtual interfaces may be configured together with
 .Cm hostap
 interfaces.
 Multiple
 .Cm station
-interfaces may be operated together with=20
+interfaces may be operated together with
 .Cm hostap
 interfaces to construct a wireless repeater device.
 For more information on configuring this device, see
@@ -150,7 +150,7 @@
 .Bd -literal -offset indent
 ifconfig wlan0 create wlandev mwl0 wlanmode hostap \e
 	ssid paying-customers wepmode on wepkey 0x1234567890 \e
-	mode 11a up=20
+	mode 11a up
 ifconfig wlan1 create wlandev mwl0 wlanmode hostap bssid \e
 	ssid freeloaders up
 ifconfig bridge0 create addm wlan0 addm wlan1 addm fxp0 up
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/net80211.4
--- a/head/share/man/man4/net80211.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/net80211.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGES.
 .\"
-.\" $FreeBSD: head/share/man/man4/net80211.4 232250 2012-02-28 13:19:34Z g=
avin $
+.\" $FreeBSD: head/share/man/man4/net80211.4 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd July 10, 2009
 .Dt NET80211 4
@@ -199,7 +199,7 @@
 .It Dv IEEE80211_IOC_BGSCAN
 Return whether background scanning is enabled in
 .Va i_val .
-When this value is non-zero and operating in station mode=20
+When this value is non-zero and operating in station mode
 the station will periodically leave
 the current channel and scan for neighboring stations.
 See also
@@ -343,7 +343,7 @@
 .Va i_val ,
 whether SSID hiding/cloaking is enabled.
 SSID hiding is only meaningful when operating as an access point.
-When this is enabled Beacon frames do not include the SSID and=20
+When this is enabled Beacon frames do not include the SSID and
 ProbeRequest frames are not answered unless they include the AP's SSID.
 This value will be non-zero when SSID hiding is enabled and otherwise zero.
 .It Dv IEEE80211_IOC_HTCOMPAT
@@ -464,7 +464,7 @@
 a station will sleep before waking to retrieve packets buffered by
 an access point.
 .It Dv IEEE80211_IOC_PRIVACY
-Return the current MLME setting for PRIVACY in=20
+Return the current MLME setting for PRIVACY in
 .Va i_val .
 When PRIVACY is enabled all data packets must be encrypted.
 This value will be zero if PRIVACY is disabled and
@@ -1093,7 +1093,7 @@
 .Va i_val .
 This request causes a running interface to be reset.
 .It Dv IEEE80211_IOC_PRIVACY
-Set the current MLME setting for PRIVACY using the value in=20
+Set the current MLME setting for PRIVACY using the value in
 .Va i_val .
 See
 .Dv IEEE80211_IOC_PRIVACY
@@ -1205,7 +1205,7 @@
 Set the current TDMA slot to the value in
 .Va i_val .
 Values must be in the range [0-slotcnt].
-Slot 0 identifies the master in the TDMA network; if it running it will=20
+Slot 0 identifies the master in the TDMA network; if it running it will
 immediately start sending Beacon frames.
 .It Dv IEEE80211_IOC_TDMA_SLOTCNT
 Set the number of slots in the TDMA network to the value in
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/netmap.4
--- a/head/share/man/man4/netmap.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/netmap.4	Tue Apr 17 11:51:51 2012 +0300
@@ -21,11 +21,11 @@
 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY =
WAY
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
-.\"=20
+.\"
 .\" This document is derived in part from the enet man page (enet.4)
 .\" distributed with 4.3BSD Unix.
 .\"
-.\" $FreeBSD: head/share/man/man4/netmap.4 232238 2012-02-27 19:05:01Z lui=
gi $
+.\" $FreeBSD: head/share/man/man4/netmap.4 233648 2012-03-29 05:02:12Z ead=
ler $
 .\" $Id: netmap.4 9662 2011-11-16 13:18:06Z luigi $: stable/8/share/man/ma=
n4/bpf.4 181694 2008-08-13 17:45:06Z ed $
 .\"
 .Dd February 27, 2012
@@ -43,7 +43,7 @@
 .Nm
 uses memory mapped buffers and metadata
 (buffer indexes and lengths) to communicate with the kernel,
-which is in charge of validating information through=20
+which is in charge of validating information through
 .Pa ioctl()
 and
 .Pa select()/poll().
@@ -51,7 +51,6 @@
 can exploit the parallelism in multiqueue devices and
 multicore systems.
 .Pp
-.Pp
 .Nm
 requires explicit support in device drivers.
 For a list of supported devices, see the end of this manual page.
@@ -66,7 +65,7 @@
 When a device is put in
 .Nm
 mode, its data path is disconnected from the host stack.
-The processes owning the file descriptor=20
+The processes owning the file descriptor
 can exchange packets with the device, or with the host stack,
 through an mmapped memory region that contains pre-allocated
 buffers and metadata.
@@ -89,7 +88,6 @@
 them into actual pointers.
 .Pp
 The data structures in shared memory are the following:
-.Pp
 .Bl -tag -width XXX
 .It Dv struct netmap_if (one per interface)
 indicates the number of rings supported by an interface, their
@@ -162,7 +160,6 @@
 char *buf =3D NETMAP_BUF(txring, i);
 .Ed
 .Ss IOCTLS
-.Pp
 .Nm
 supports some ioctl() to synchronize the state of the rings
 between the kernel and the user processes, plus some
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_car.4
--- a/head/share/man/man4/ng_car.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_car.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/ng_car.4 231564 2012-02-12 18:29:56Z ed $
+.\" $FreeBSD: head/share/man/man4/ng_car.4 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd March 11, 2007
 .Dt NG_CAR 4
@@ -150,7 +150,7 @@
=20
 /* mode options (opt) */
 #define NG_CAR_COUNT_PACKETS	2
- =20
+
 struct ng_car_bulkconf {
 	struct ng_car_hookconf upstream;
 	struct ng_car_hookconf downstream;
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_deflate.4
--- a/head/share/man/man4/ng_deflate.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_deflate.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ng_deflate.4 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd December 23, 2006
 .Dt NG_DEFLATE 4
@@ -40,7 +40,7 @@
 .Sh DESCRIPTION
 The
 .Nm deflate
-node type implements the Deflate sub-protocols of the Compression Control=20
+node type implements the Deflate sub-protocols of the Compression Control
 Protocol (CCP).
 .Pp
 The node has two hooks,
@@ -111,7 +111,7 @@
 .Pp
 This message may also be received by this node type when a CCP Reset-Reque=
st
 or Reset-Ack is received by the local PPP entity.
-The node will respond by flushing its compression state so the sides=20
+The node will respond by flushing its compression state so the sides
 can resynchronize.
 .It Dv NGM_DEFLATE_GET_STATS Pq Li getstats
 This control message obtains statistics for a given hook.
@@ -154,5 +154,5 @@
 .An Alexander Motin Aq mav at alkar.net
 .Sh BUGS
 Due to nature of netgraph PPP implementation there are possible race condi=
tions
-between data packet and ResetAck CCP packet in case of packet loss. As res=
ult,=20
+between data packet and ResetAck CCP packet in case of packet loss. As res=
ult,
 packet loss can produce bigger performance degradation than supposed by pr=
otocol.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_nat.4
--- a/head/share/man/man4/ng_nat.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_nat.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ng_nat.4 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd March 1, 2008
 .Dt NG_NAT 4
@@ -60,7 +60,7 @@
 After both hooks have been connected and aliasing address was configured,
 a node is ready for aliasing operation.
 .It Dv NGM_NAT_SET_MODE Pq Li setmode
-Set node's operation mode using supplied=20
+Set node's operation mode using supplied
 .Vt "struct ng_nat_mode".
 .Bd -literal
 struct ng_nat_mode {
@@ -78,7 +78,7 @@
 .Ed
 .It Dv NGM_NAT_SET_TARGET Pq Li settarget
 Configure target address for a node.
-When an incoming packet not associated with any pre-existing aliasing=20
+When an incoming packet not associated with any pre-existing aliasing
 link arrives at the host machine, it will be sent to the specified address.
 .It Dv NGM_NAT_REDIRECT_PORT Pq Li redirectport
 Redirect incoming connections arriving to given port(s) to
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_netflow.4
--- a/head/share/man/man4/ng_netflow.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_netflow.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/ng_netflow.4 231564 2012-02-12 18:29:56Z=
 ed $
+.\" $FreeBSD: head/share/man/man4/ng_netflow.4 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd March 2, 2011
 .Dt NG_NETFLOW 4
@@ -61,7 +61,6 @@
 .Pp
 Node supports IPv6 accounting (NetFlow v9 only) and is aware of multiple f=
ibs.
 Different fibs are mapped to different domain_id in NetFlow V9 and differe=
nt engine_id in NetFlow V5.
-.Pp
 .Sh HOOKS
 This node type supports up to
 .Dv NG_NETFLOW_MAXIFACES
@@ -72,9 +71,9 @@
 .Va out0 , out1 ,
 etc.,
 plus two export hooks:
-.Va export=20
+.Va export
 (for NetFlow version 5) and
-.Va export9=20
+.Va export9
 (for NetFlow version 9). Export can be done simultaneously for all support=
ed
 export hooks. By default (ingress NetFlow enabled) node does NetFlow accou=
nting of data
 received on
@@ -194,7 +193,7 @@
 important to avoid duplicate accounting when both ingress and egress NetFl=
ow
 are enabled.
 .It Dv NGM_NETFLOW_SETTEMPLATE
-Sets various timeouts to announce data flow templates=20
+Sets various timeouts to announce data flow templates
 (NetFlow v9-specific). This message requires
 .Vt "struct ng_netflow_settemplate"
 as an argument:
@@ -209,7 +208,7 @@
 Value of packets field represents maximum packets count between
 re-announcing data templates.
 .It Dv NGM_NETFLOW_SETMTU
-Sets export interface MTU to build packets of specified size (NetFlow v9-s=
pecific).=20
+Sets export interface MTU to build packets of specified size (NetFlow v9-s=
pecific).
 This message requires
 .Vt "struct ng_netflow_setmtu"
 as an argument:
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_patch.4
--- a/head/share/man/man4/ng_patch.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_patch.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/ng_patch.4 232538 2012-03-05 06:12:15Z g=
lebius $
+.\" $FreeBSD: head/share/man/man4/ng_patch.4 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd March 5, 2012
 .Dt NG_PATCH 4
@@ -164,7 +164,7 @@
 .Dq Li ttl_add
 node of type
 .Nm
-configured to add (mode=20
+configured to add (mode
 .Dv NG_PATCH_MODE_ADD )
 a
 .Va value
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_ppp.4
--- a/head/share/man/man4/ng_ppp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_ppp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
 .\"
 .\" Author: Archie Cobbs <archie at FreeBSD.org>
 .\"
-.\" $FreeBSD: head/share/man/man4/ng_ppp.4 231564 2012-02-12 18:29:56Z ed $
+.\" $FreeBSD: head/share/man/man4/ng_ppp.4 233648 2012-03-29 05:02:12Z ead=
ler $
 .\" $Whistle: ng_ppp.8,v 1.3 1999/01/25 23:46:27 archie Exp $
 .\"
 .Dd December 28, 2006
@@ -132,9 +132,9 @@
 .Dv compress
 and
 .Dv decompress .
-Compression and decompression can be enabled by toggling the=20
+Compression and decompression can be enabled by toggling the
 .Vt enableCompression
-and=20
+and
 .Vt enableDecompression
 fields of the node configuration structure.
 (See below.)
@@ -143,23 +143,23 @@
 is set to
 .Dv NG_PPP_COMPRESS_SIMPLE ,
 then all outgoing frames are sent to the
-.Dv compress    =20
+.Dv compress
 hook and all packets received on this hook are expected to be
 compressed, so the COMPD tag is put on them unconditionally.
 If
 .Vt enableCompression
 is set to
 .Dv NG_PPP_COMPRESS_FULL ,
-then packets received on the=20
-.Dv compress   =20
+then packets received on the
+.Dv compress
 hook are resent as is.
 The compressor node should put the tag, if the packet was compressed.
-If=20
+If
 .Vt enableDecompression
-is set to=20
+is set to
 .Dv NG_PPP_DECOMPRESS_SIMPLE ,
 then the node will sent to the
-.Dv decompress=20
+.Dv decompress
 hook only those frames, that are marked with the COMPD tag.
 If
 .Vt enableDecompression
@@ -396,7 +396,7 @@
 .Dv NG_PPP_BUNDLE_LINKNUM
 is a valid link number corresponding to the multi-link bundle.
 .It Dv NGM_PPP_GET_LINK_STATS64
-Same as NGM_PPP_GET_LINK_STATS but returns=20
+Same as NGM_PPP_GET_LINK_STATS but returns
 .Dv "struct ng_ppp_link_stat64"
 containing 64bit counters.
 .It Dv NGM_PPP_CLR_LINK_STATS
@@ -407,7 +407,7 @@
 .Dv NGM_PPP_GET_LINK_STATS ,
 but also atomically clears the statistics as well.
 .It Dv NGM_PPP_GETCLR_LINK_STATS64
-Same as NGM_PPP_GETCLR_LINK_STATS but returns=20
+Same as NGM_PPP_GETCLR_LINK_STATS but returns
 .Dv "struct ng_ppp_link_stat64"
 containing 64bit counters.
 .El
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_pred1.4
--- a/head/share/man/man4/ng_pred1.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_pred1.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ng_pred1.4 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd December 24, 2006
 .Dt NG_PRED1 4
@@ -38,7 +38,7 @@
 .Sh DESCRIPTION
 The
 .Nm pred1
-node type implements the Predictor-1 sub-protocols of the Compression Cont=
rol=20
+node type implements the Predictor-1 sub-protocols of the Compression Cont=
rol
 Protocol (CCP).
 .Pp
 The node has two hooks,
@@ -98,7 +98,7 @@
 .Pp
 This message may also be received by this node type when a CCP Reset-Reque=
st
 or Reset-Ack is received by the local PPP entity.
-The node will respond by flushing its compression state so the sides=20
+The node will respond by flushing its compression state so the sides
 can resynchronize.
 .It Dv NGM_PRED1_GET_STATS Pq Li getstats
 This control message obtains statistics for a given hook.
@@ -141,5 +141,5 @@
 .An Alexander Motin Aq mav at alkar.net
 .Sh BUGS
 Due to nature of netgraph PPP implementation there are possible race condi=
tions
-between data packet and ResetAck CCP packet in case of packet loss. As res=
ult,=20
+between data packet and ResetAck CCP packet in case of packet loss. As res=
ult,
 packet loss can produce bigger performance degradation than supposed by pr=
otocol.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ng_tty.4
--- a/head/share/man/man4/ng_tty.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ng_tty.4	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
 .\"
 .\" Author: Archie Cobbs <archie at FreeBSD.org>
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ng_tty.4 233648 2012-03-29 05:02:12Z ead=
ler $
 .\" $Whistle: ng_tty.8,v 1.5 1999/01/25 23:46:28 archie Exp $
 .\"
 .Dd December 25, 2008
@@ -57,7 +57,7 @@
 .Dv hook
 are transmitted out on the tty device.
 No modification to the data is performed in either direction.
-While the hook is installed on a tty, the normal read and write=20
+While the hook is installed on a tty, the normal read and write
 operations are unavailable, returning
 .Er EIO .
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/nvram2env.4
--- a/head/share/man/man4/nvram2env.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/nvram2env.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/nvram2env.4 222286 2011-05-25 14:13:53Z =
ru $
+.\" $FreeBSD: head/share/man/man4/nvram2env.4 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd April 3, 2011
 .Dt NVRAM2ENV 4
@@ -31,7 +31,7 @@
 .Nm nvram2env
 .Nd "copy nvram-like data into kernel environment"
 .Sh SYNOPSIS
-.Cd "device	nvram2env"
+.Cd "device nvram2env"
 .Sh DESCRIPTION
 .Nm
 implements a simple method of reading the NVRAM-like data and information
@@ -44,7 +44,7 @@
 .Nm
 copies the environment values into kernel environment using the kernel set=
env call.
 .Pp
-Configuration of=20
+Configuration of
 .Nm
 is done in
 .Xr device.hints 5
@@ -69,7 +69,7 @@
 Use format "Generic", skip uint32_t field, then zero terminating array of
 strings.
 .It Fa 0x0004
-Use Broadcom CFE format. uint32_t signature "FLSH", uint32_t size,=20
+Use Broadcom CFE format. uint32_t signature "FLSH", uint32_t size,
 three unused fields uint32_t, then data.
 .It Fa 0x0008
 Use U-Boot format, uint32_t crc, then zero terminating array of strings.
@@ -101,7 +101,6 @@
 .Ed
 .Pp
 Dynamic, editable form CFE, override values from first
-.Pp
 .Bd -literal -offset indent
 hint.nvram.1.flags=3D0x05 # Broadcom + nocheck
 hint.nvram.1.base=3D0x1cff8000
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/nxge.4
--- a/head/share/man/man4/nxge.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/nxge.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/nxge.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd October 16, 2007
 .Dt NXGE 4
@@ -48,8 +48,8 @@
 The
 .Nm
 driver provides support for Neterion Xframe-I and Xframe-II adapters.
-The driver supports TCP Segmentation Offload (TSO/LSO),=20
-Large Receive Offload (LRO), Jumbo Frames (5 buffer mode),=20
+The driver supports TCP Segmentation Offload (TSO/LSO),
+Large Receive Offload (LRO), Jumbo Frames (5 buffer mode),
 Header Separation (Rx 2 buffer mode), VLAN, and Promiscuous mode.
 .Pp
 For general information and support, please visit the Neterion support page
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/oce.4
--- a/head/share/man/man4/oce.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/oce.4	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
 .\" 3333 Susan Street
 .\" Costa Mesa, CA 92626
 .\"
-.\" $FreeBSD: head/share/man/man4/oce.4 231937 2012-02-20 13:22:00Z brueff=
er $
+.\" $FreeBSD: head/share/man/man4/oce.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd February 19, 2012
 .Dt OCE 4
@@ -90,7 +90,6 @@
 .Bl -enum
 .It
 Copy the below code to a Makefile:
-.Pp
 .Bd -literal -offset indent
 \&.KMOD=3Delxflash
 FIRMWS=3Dimagename.ufi:elxflash
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/pcm.4
--- a/head/share/man/man4/pcm.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/pcm.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,9 +23,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/pcm.4 232337 2012-03-01 13:10:18Z mav $
+.\" $FreeBSD: head/share/man/man4/pcm.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
-.Dd January 22, 2012
+.Dd March 22, 2012
 .Dt SOUND 4
 .Os
 .Sh NAME
@@ -85,11 +85,11 @@
 .It
 .Xr snd_audiocs 4 (enabled by default on sparc64)
 .It
-.Xr snd_cmi 4
+.Xr snd_cmi 4 (enabled by default on amd64, i386)
 .It
 .Xr snd_cs4281 4
 .It
-.Xr snd_csa 4
+.Xr snd_csa 4 (enabled by default on amd64, i386)
 .It
 .Xr snd_davbus 4 (enabled by default on powerpc)
 .It
@@ -97,7 +97,7 @@
 .It
 .Xr snd_emu10k1 4
 .It
-.Xr snd_emu10kx 4
+.Xr snd_emu10kx 4 (enabled by default on amd64, i386)
 .It
 .Xr snd_envy24 4
 .It
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ppbus.4
--- a/head/share/man/man4/ppbus.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ppbus.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ppbus.4 233422 2012-03-24 13:37:57Z joel=
 $
 .\"
 .Dd March 1, 1998
 .Dt PPBUS 4
@@ -61,7 +61,6 @@
 with kernel-in drivers.
 .El
 .Ss Developing new drivers
-.Pp
 The ppbus system has been designed to support the development of standard
 and non-standard software:
 .Pp
@@ -74,7 +73,6 @@
 .It Sy lpbb Ta "Philips official parallel port I2C bit-banging interface"
 .El
 .Ss Porting existing drivers
-.Pp
 Another approach to the ppbus system is to port existing drivers.
 Various drivers have already been ported:
 .Pp
@@ -274,7 +272,6 @@
 Finally, the
 .Em device
 layer gathers the parallel peripheral device drivers.
-.Pp
 .Ss Parallel modes management
 We have to differentiate operating modes at various ppbus system layers.
 Actually, ppbus and adapter operating modes on one hands and for each
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/psm.4
--- a/head/share/man/man4/psm.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/psm.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,9 +24,9 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/psm.4 233580 2012-03-27 23:43:01Z jkim $
 .\"
-.Dd April 8, 2008
+.Dd March 27, 2012
 .Dt PSM 4
 .Os
 .Sh NAME
@@ -329,9 +329,6 @@
 .Nm
 driver to reset and re-initialize the pointing device
 after the `resume' event.
-It has no effect unless the
-.Em HOOKRESUME
-flag is set as well.
 .El
 .Sh LOADER TUNABLES
 Extended support for Synaptics touchpads can be enabled by setting
@@ -445,10 +442,8 @@
 .El
 .Pp
 .It Dv MOUSE_SYN_GETHWINFO Ar synapticshw_t *synhw
-Retrieves extra information associated with Synaptics Touchpads.
-Only available when
-.Va hw.psm.synaptics_support
-has been enabled.
+Retrieves extra information associated with Synaptics Touchpad.
+Only available when a supported device has been detected.
 .Bd -literal
 typedef struct synapticshw {
     int infoMajor;	/* major hardware revision */
@@ -837,12 +832,11 @@
 and Interlink VersaPad, treat the tapping action
 as fourth button events.
 .Pp
-It is reported that Interlink VersaPad requires both
-.Em HOOKRESUME
-and
+It is reported that ALPS GlidePoint, Synaptics Touchpad, and
+Interlink VersaPad require
 .Em INITAFTERSUSPEND
-flags in order to recover from suspended state.
-These flags are automatically set when VersaPad is detected by the
+flag in order to recover from suspended state.
+This flag is automatically set when one of these devices is detected by the
 .Nm
 driver.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/pts.4
--- a/head/share/man/man4/pts.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/pts.4	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)pty.4	8.2 (Berkeley) 11/30/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/pts.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd August 20, 2008
 .Dt PTS 4
@@ -131,7 +131,7 @@
 .It Dv TIOCPTMASTER
 Determine whether the file descriptor is pointing to a pseudo-terminal
 master device.
-This=20
+This
 .Xr ioctl 2
 should not be used directly. It is used to implement routines like
 .Xr grantpt 3 .
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ral.4
--- a/head/share/man/man4/ral.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ral.4	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ral.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd July 8, 2009
 .Dt RAL 4
@@ -82,7 +82,7 @@
 or
 .Cm mesh
 virtual interface may be configured at a time.
-Any number of=20
+Any number of
 .Cm wds
 virtual interfaces may be configured together with a
 .Cm hostap
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/run.4
--- a/head/share/man/man4/run.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/run.4	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/run.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd January 12, 2011
 .Dt RUN 4
@@ -105,7 +105,7 @@
 driver can be configured at runtime with
 .Xr ifconfig 8 .
 .Sh HARDWARE
-The=20
+The
 .Nm
 driver supports the following wireless adapters:
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/runfw.4
--- a/head/share/man/man4/runfw.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/runfw.4	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/runfw.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd January 12, 2011
 .Dt RUNFW 4
@@ -32,7 +32,7 @@
 .Ed
 .Pp
 This will include two firmware images, RT2870 and RT3071, inside the kerne=
l.
-.Xr run 4=20
+.Xr run 4
 will load the appropriate image into the chip.
 .Pp
 Alternatively, to load the firmware images as a module at boot time, place
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/sfxge.4
--- a/head/share/man/man4/sfxge.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/sfxge.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/sfxge.4 231244 2012-02-09 04:37:30Z gjb $
+.\" $FreeBSD: head/share/man/man4/sfxge.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd February 8, 2012
 .Dt SFXGE 4
@@ -52,7 +52,7 @@
 The driver supports jumbo
 frames, transmit/receive checksum offload, TCP Segmentation Offload
 (TSO), Large Receive Offload (LRO), VLAN checksum offload, VLAN TSO,
-and Receive Side Scaling (RSS) using MSI-X interrupts. =20
+and Receive Side Scaling (RSS) using MSI-X interrupts.
 .Pp
 The driver allocates 1 receive queue, transmit queue, event queue and
 IRQ per CPU up to a maximum of 64.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/smp.4
--- a/head/share/man/man4/smp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/smp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/smp.4 225775 2011-09-27 07:00:24Z gabor $
+.\" $FreeBSD: head/share/man/man4/smp.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd May 7, 2008
 .Dt SMP 4
@@ -123,7 +123,7 @@
 Because using logical CPUs can cause performance penalties under certain l=
oads,
 the logical CPUs can be disabled by setting the
 .Va machdep.hyperthreading_allowed
-tunable to zero.=20
+tunable to zero.
 .Sh SEE ALSO
 .Xr cpuset 1 ,
 .Xr mptable 1 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/snd_emu10kx.4
--- a/head/share/man/man4/snd_emu10kx.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/snd_emu10kx.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/snd_emu10kx.4 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd May 28, 2008
 .Dt SND_EMU10KX 4
@@ -119,7 +119,7 @@
 .Xr loader.conf 5
 configuration file you will get up to five DSP devices, one for each
 sound card output.
-You can use additional software (like=20
+You can use additional software (like
 .Em audio/pulseaudio
 from
 .Em The Ports Collection )
@@ -164,7 +164,6 @@
 .It +0x3E
 sync substream (0xc0de)
 .El
-.Pp
 .Ss Audigy substream map (in byte offsets, each substream is 2 bytes LE)
 .Bl -tag -width ".Dv +0x00..+0x3E"
 .It Dv Offset
@@ -286,7 +285,6 @@
 device driver and this manual page were written by
 .An Yuriy Tsibizov .
 .Sh BUGS
-.Pp
 The driver does not detect lost S/PDIF signals and produces noise when
 S/PDIF is not connected and S/PDIF volume is not zero.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/snd_hda.4
--- a/head/share/man/man4/snd_hda.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/snd_hda.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/snd_hda.4 230551 2012-01-25 20:46:10Z ma=
v $
+.\" $FreeBSD: head/share/man/man4/snd_hda.4 233422 2012-03-24 13:37:57Z jo=
el $
 .\"
 .Dd January 25, 2012
 .Dt SND_HDA 4
@@ -480,7 +480,6 @@
 will go from two external microphones and line-in jacks.
 .Li pcm1
 playback will go to the internal speaker.
-.Pp
 .Ss Example 2
 Setting the
 .Xr device.hints 5
@@ -503,7 +502,6 @@
 .Li pcm1
 device will be completely dedicated to a headset (headphones and mic)
 connected to the front connectors.
-.Pp
 .Ss Example 3
 Setting the
 .Xr device.hints 5
@@ -527,7 +525,6 @@
 and
 .Li pcm3
 .Pq internal speaker .
-.Pp
 .Ss Example 4
 Setting the
 .Xr device.hints 5
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/snd_ich.4
--- a/head/share/man/man4/snd_ich.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/snd_ich.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/snd_ich.4 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd January 6, 2009
 .Dt SND_ICH 4
@@ -52,7 +52,7 @@
 to attach to Intel ICH AC'97 and compatible audio devices.
 .Pp
 Some later chips, like ICH6/ICH7, depending on wiring can instead implement
-newer Intel HD Audio specification, which is supported by=20
+newer Intel HD Audio specification, which is supported by
 .Xr snd_hda 4
 driver.
 .Sh HARDWARE
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/syscons.4
--- a/head/share/man/man4/syscons.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/syscons.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/syscons.4 233510 2012-03-26 15:18:14Z jo=
el $
 .\"
 .Dd September 11, 2009
 .Dt SYSCONS 4
@@ -501,15 +501,15 @@
 because of the current implementation of
 .Xr config 8 .
 .Pp
-.Dl "options SC_NORM_ATTR=3D(FG_GREEN|BG_BLACK)
-.Dl "options SC_NORM_REV_ATTR=3D(FG_YELLOW|BG_GREEN)
+.Dl "options SC_NORM_ATTR=3D(FG_GREEN|BG_BLACK)"
+.Dl "options SC_NORM_REV_ATTR=3D(FG_YELLOW|BG_GREEN)"
 .Pp
 The following lines will set the default colors of the kernel message.
 The kernel message will be printed bright red on black background.
 The reversed message will be black on red background.
 .Pp
-.Dl "options SC_KERNEL_CONS_ATTR=3D(FG_LIGHTRED|BG_BLACK)
-.Dl "options SC_KERNEL_CONS_REV_ATTR=3D(FG_BLACK|BG_RED)
+.Dl "options SC_KERNEL_CONS_ATTR=3D(FG_LIGHTRED|BG_BLACK)"
+.Dl "options SC_KERNEL_CONS_REV_ATTR=3D(FG_BLACK|BG_RED)"
 .Pp
 The following example adds the font files
 .Pa cp850-8x16.fnt ,
@@ -519,7 +519,7 @@
 to the kernel.
 .Pp
 .Dl "options SC_DFLT_FONT"
-.Dl "makeoptions SC_DFLT_FONT=3Dcp850
+.Dl "makeoptions SC_DFLT_FONT=3Dcp850"
 .Dl "device sc"
 .\".Sh DIAGNOSTICS
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/tcp.4
--- a/head/share/man/man4/tcp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/tcp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)tcp.4	8.1 (Berkeley) 6/5/93
-.\" $FreeBSD: head/share/man/man4/tcp.4 233196 2012-03-19 19:25:22Z maxim $
+.\" $FreeBSD: head/share/man/man4/tcp.4 233229 2012-03-20 12:24:36Z maxim $
 .\"
 .Dd March 7, 2012
 .Dt TCP 4
@@ -562,6 +562,7 @@
 .Xr intro 4 ,
 .Xr ip 4 ,
 .Xr mod_cc 4 ,
+.Xr siftr 4 ,
 .Xr syncache 4 ,
 .Xr setkey 8
 .Rs
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/tpm.4
--- a/head/share/man/man4/tpm.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/tpm.4	Tue Apr 17 11:51:51 2012 +0300
@@ -13,7 +13,7 @@
 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/tpm.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd August 15, 2010
 .Dt TPM 4
@@ -48,7 +48,7 @@
 The
 .Nm
 driver provides support for various trusted platform modules (TPM) that can
-store cryptographic keys.=20
+store cryptographic keys.
 .Pp
 Supported modules:
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/u3g.4
--- a/head/share/man/man4/u3g.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/u3g.4	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD: head/share/man/man4/u3g.4 232684 2012-03-08 07:22:41Z hselas=
ky $
+.\" $FreeBSD: head/share/man/man4/u3g.4 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd February 8, 2012
 .Dt U3G 4
@@ -93,7 +93,6 @@
 .Xr usbconfig 8
 and
 .Xr usb_quirk 4 .
-.Pp
 .Sh SEE ALSO
 .Xr tty 4 ,
 .Xr ucom 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/uark.4
--- a/head/share/man/man4/uark.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/uark.4	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD: head/share/man/man4/uark.4 227750 2011-11-20 12:18:21Z miwi $
+.\" $FreeBSD: head/share/man/man4/uark.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd November 20, 2011
 .Dt UARK 4
@@ -43,7 +43,7 @@
 .Nm
 driver supports Arkmicro Technologies ARK3116 based serial adapters.
 .Sh HARDWARE
-The=20
+The
 .Nm
 driver supports the following adapters:
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/uath.4
--- a/head/share/man/man4/uath.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/uath.4	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
 .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/uath.4 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd April 7, 2009
 .Dt UATH 4
@@ -76,16 +76,15 @@
 utility that is launched by
 .Xr devd 8
 when the device is inserted.
-.Xr uathload=20
+.Xr uathload
 includes the firmware in the binary program.
 This firmware is licensed for general use and is included in the base syst=
em.
 .Sh HARDWARE
 The
 .Nm
 driver should work with the following adapters:
-.Pp
-.Bl -column -compact "TRENDware International TEW-444UB" "AR5005UX" -offse=
t 6n
-.It Em "Adapter	Chipset"
+.Bl -column "TRENDware International TEW-444UB" "AR5005UX"
+.It Em "Adapter" Ta Em "Chipset"
 .\".It Belkin F6D3050	AR5005UX
 .It Li "Compex WLU108AG" Ta AR5005UX
 .It Li "Compex WLU108G" Ta AR5005UG
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ufoma.4
--- a/head/share/man/man4/ufoma.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ufoma.4	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/ufoma.4 227750 2011-11-20 12:18:21Z miwi=
 $
+.\" $FreeBSD: head/share/man/man4/ufoma.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd November 20, 2011
 .Dt UFOMA 4
@@ -99,7 +99,7 @@
 will be set to this mode.
 .It Li unlinked
 When an interface is not yet negotiated, the interface is in this mode.
-.El=20
+.El
 .Sh HARDWARE
 Devices supported by the
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/uipaq.4
--- a/head/share/man/man4/uipaq.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/uipaq.4	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/uipaq.4 227750 2011-11-20 12:18:21Z miwi=
 $
+.\" $FreeBSD: head/share/man/man4/uipaq.4 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd November 20, 2011
 .Dt UIPAQ 4
@@ -86,10 +86,10 @@
 .Xr usb 4
 .Sh HISTORY
 The
-.Fx=20
+.Fx
 support was imported from
-.Nx=20
-for=20
+.Nx
+for
 .Fx 7.0 .
 .Nx
 added support in
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/ulpt.4
--- a/head/share/man/man4/ulpt.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/ulpt.4	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/ulpt.4 233672 2012-03-29 17:04:04Z joel $
 .\"
 .Dd November 22, 2006
 .Dt ULPT 4
@@ -57,7 +57,7 @@
 The bits in the minor number select various features of the driver.
 .Bl -column "Minor Bit" "Functionxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -offset ind=
ent
 .Em "Minor Bit	Function"
-64	Do not initialize (reset) the device on the port.
+64	"Do not initialize (reset) the device on the port."
 .El
 .Pp
 Some printers cannot handle the reset on open; in case of problems try the
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/umcs.4
--- a/head/share/man/man4/umcs.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/umcs.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/umcs.4 232158 2012-02-25 15:21:43Z gjb $
+.\" $FreeBSD: head/share/man/man4/umcs.4 233466 2012-03-25 16:00:56Z joel $
 .\"
 .Dd February 25, 2012
 .Dt UMCS 4
@@ -84,9 +84,6 @@
 .Xr tty 4 ,
 .Xr ucom 4 ,
 .Xr usb 4
-.Sh BUGS
-This driver doesn't support access to any fine tunes of
-chip, like RS522/RS485 mode, non-standard baudrates, etc.
 .Sh HISTORY
 The
 .Nm
@@ -99,3 +96,6 @@
 driver was written by
 .An Lev Serebryakov
 .Aq lev at FreeBSD.org .
+.Sh BUGS
+This driver doesn't support access to any fine tunes of
+chip, like RS522/RS485 mode, non-standard baudrates, etc.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/upgt.4
--- a/head/share/man/man4/upgt.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/upgt.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 .\" $OpenBSD: upgt.4,v 1.6 2008/04/17 14:01:22 jmc Exp $
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/upgt.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .\" Copyright (c) 2007 Marcus Glocker <mglocker at openbsd.org>
 .\" Copyright (c) 2005-2007
@@ -181,13 +181,13 @@
 .Bd -literal -offset indent
 ifconfig wlan create wlandev upgt0 inet 192.168.0.20 \e
     netmask 0xffffff00
-.Ed=20
-.Pp=20
+.Ed
+.Pp
 Join a specific BSS network with network name
-.Dq Li my_net :=20
-.Pp=20
+.Dq Li my_net :
+.Pp
 .Dl "ifconfig wlan create wlandev upgt0 ssid my_net up"
-.Pp=20
+.Pp
 Join a specific BSS network with 64-bit WEP encryption:
 .Bd -literal -offset indent
 ifconfig wlan create wlandev upgt0 ssid my_net \e
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/vge.4
--- a/head/share/man/man4/vge.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/vge.4	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/vge.4 222447 2011-05-29 11:10:56Z bcr $
+.\" $FreeBSD: head/share/man/man4/vge.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd May 29, 2011
 .Dt VGE 4
@@ -82,7 +82,7 @@
 The jumbo frame support can be enabled by setting the interface MTU
 to any value larger than the default of 1500 bytes, up to a maximum
 of 9000 bytes.
-Jumbo frames are disabled on the VT6130/VT6132 controllers because the TX=20
+Jumbo frames are disabled on the VT6130/VT6132 controllers because the TX
 MAC will hang when trying to send a frame that is larger than 4K.
 The receive and transmit checksum offload support
 can be toggled on and off using the
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/virtio.4
--- a/head/share/man/man4/virtio.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/virtio.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,13 +22,13 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/virtio.4 230450 2012-01-22 10:16:24Z bru=
effer $
+.\" $FreeBSD: head/share/man/man4/virtio.4 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd January 22, 2012
 .Dt VIRTIO 4
 .Os
 .Sh NAME
-.Nm virtio=20
+.Nm virtio
 .Nd VirtIO Device Support
 .Sh SYNOPSIS
 To compile VirtIO device support into the kernel, place the following lines
@@ -59,7 +59,7 @@
 .Xr virtio_pci 4
 device driver represents an emulated PCI device that the hypervisor makes
 available to the VM.
-This device provides the probing, configuration, and=20
+This device provides the probing, configuration, and
 interrupt notifications needed to interact with the hypervisor.
 .Fx
 supports the following VirtIO devices:
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/vxge.4
--- a/head/share/man/man4/vxge.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/vxge.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/vxge.4 225196 2011-08-26 17:35:22Z bruef=
fer $
+.\" $FreeBSD: head/share/man/man4/vxge.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd March 16, 2011
 .Dt VXGE 4
@@ -48,7 +48,7 @@
 The
 .Nm
 driver provides support for Neterion X3100 adapters.
-The driver supports TCP Segmentation Offload (TSO/LSO),=20
+The driver supports TCP Segmentation Offload (TSO/LSO),
 Large Receive Offload (LRO), Jumbo Frames, Receive Traffic Hash (RTH),
 VLAN, Promiscuous mode and Multi function mode.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/wbwd.4
--- a/head/share/man/man4/wbwd.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/wbwd.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,10 +23,10 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/wbwd.4 232614 2012-03-06 18:44:52Z bz $
+.\" $FreeBSD: head/share/man/man4/wbwd.4 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd March 6, 2012
-.Dt wbwd 4
+.Dt WBWD 4
 .Os
 .Sh NAME
 .Nm wbwd
@@ -72,7 +72,7 @@
 driver provides the following options as
 .Xr sysctl 8
 variables.
-.Bl -tag -width "xxxxxx" =20
+.Bl -tag -width "xxxxxx"
 .It Va dev.wbwd.0.timeout_override
 This variable allows to program the timer to a value independent on the one
 provided by the
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/wi.4
--- a/head/share/man/man4/wi.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/wi.4	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/wi.4 224284 2011-07-23 22:55:32Z gjb $
+.\" $FreeBSD: head/share/man/man4/wi.4 233648 2012-03-29 05:02:12Z eadler $
 .\"	$OpenBSD: wi.4tbl,v 1.14 2002/04/29 19:53:50 jsyn Exp $
 .\"
 .Dd July 23, 2011
@@ -355,7 +355,7 @@
 mode and are not supported.
 .Pp
 Prior versions of
-.Nm=20
+.Nm
 supported Symbol firmware.
 That support has been removed due to persistent problems with this
 firmware as well as getting proper documentation on this firmware.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/wlan_acl.4
--- a/head/share/man/man4/wlan_acl.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/wlan_acl.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/wlan_acl.4 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd December 7, 2004
 .Dt WLAN_ACL 4
@@ -40,7 +40,7 @@
 with 802.11 devices operating as an access point.
 The
 .Nm
-must be loaded for=20
+must be loaded for
 .Xr ifconfig 8
 to handle the
 .Cm mac:*
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/wlan_amrr.4
--- a/head/share/man/man4/wlan_amrr.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/wlan_amrr.4	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/wlan_amrr.4 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd April 13, 2008
 .Dt WLAN_AMRR 4
@@ -48,7 +48,7 @@
 .Xr wpi 4 ,
 .Xr zyd 4
 .Sh STANDARDS
-More information can be found in the paper describing the=20
+More information can be found in the paper describing the
 .Em AMRR
 algorithm at
 .Pa http://hal.inria.fr/inria-00070784/en/ .
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/wpi.4
--- a/head/share/man/man4/wpi.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/wpi.4	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/wpi.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd October 5, 2008
 .Dt WPI 4
@@ -106,14 +106,14 @@
 The driver failed to load the firmware image using the
 .Xr firmware 9
 subsystem.
-Verify the=20
+Verify the
 .Xr wpifw
 firmware module is installed.
 .It "wpi%d: fatal firmware error"
 An unknown error has occurred in the uploaded firmware, you may have to
 unload/reload the driver to continue.
 .It "wpi%d: Radio transmitter is switched off"
-The hardware switch controlling the radio is currently turned off.=20
+The hardware switch controlling the radio is currently turned off.
 Data transmission is not possible in this state.
 .El
 .Sh SEE ALSO
@@ -133,8 +133,8 @@
 .Ox
 by
 .An Damien Bergamini Aq damien.bergamini at free.fr .
-.An Benjamin Close Aq benjsc at FreeBSD.org=20
-ported=20
+.An Benjamin Close Aq benjsc at FreeBSD.org
+ported
 .Nm
 to
 .Fx .
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/xen.4
--- a/head/share/man/man4/xen.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/xen.4	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 .\" Copyright (c) 2010 Robert N. M. Watson
 .\" All rights reserved.
 .\"
-.\" This software was developed by SRI International and the University of=20
+.\" This software was developed by SRI International and the University of
 .\" Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-02=
37
 .\" ("CTSRD"), as part of the DARPA CRASH research program.
 .\"
@@ -26,13 +26,13 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/xen.4 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd December 17, 2010
 .Dt XEN 4
 .Os
 .Sh NAME
-.Nm xen=20
+.Nm xen
 .Nd Xen Hypervisor Guest (DomU) Support
 .Sh SYNOPSIS
 To compile para-virtualized (PV) Xen guest support into an i386 kernel, pl=
ace
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man4/xnb.4
--- a/head/share/man/man4/xnb.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man4/xnb.4	Tue Apr 17 11:51:51 2012 +0300
@@ -12,7 +12,7 @@
 .\"    ("Disclaimer") and any redistribution must be conditioned upon
 .\"    including a substantially similar Disclaimer requirement for further
 .\"    binary redistribution.
-.\"=20
+.\"
 .\" NO WARRANTY
 .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 .\" "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -25,14 +25,14 @@
 .\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 .\" IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGES.
-.\"=20
+.\"
 .\" Authors: Alan Somers         (Spectra Logic Corporation)
-.\"=20
-.\" $FreeBSD: head/share/man/man4/xnb.4 230593 2012-01-26 18:18:47Z ken $
-.\"=20
+.\"
+.\" $FreeBSD: head/share/man/man4/xnb.4 233648 2012-03-29 05:02:12Z eadler=
 $
+.\"
 .Dd January 6, 2012
 .Dt XNB 4
-.Os=20
+.Os
 .Sh NAME
 .Nm xnb
 .Nd "Xen Paravirtualized Backend Ethernet Driver"
@@ -84,6 +84,27 @@
 Does not affect the operation of the driver in any way.
 Note that the test suite simulates error conditions; this will result in
 error messages being printed to the system system log.
+.El
+.Sh SEE ALSO
+.Xr arp 4 ,
+.Xr netintro 4 ,
+.Xr ng_ether 4 ,
+.Xr xen 4 ,
+.Xr ifconfig 8
+.Sh HISTORY
+The
+.Nm
+device driver first appeared in
+.Fx 10.0 .
+.Sh AUTHORS
+The
+.Nm
+driver was written by
+.An Alan Somers
+.Aq alans at spectralogic.com
+and
+.An John Suykerbuyk
+.Aq johns at spectralogic.com
 .Sh CAVEATS
 Packets sent through Xennet pass over shared memory, so the protocol inclu=
des
 no form of link-layer checksum or CRC.
@@ -110,26 +131,6 @@
 disabled on the netfront.
 The Xennet protocol does not have any mechanism for the netback to request
 the netfront to do this; the operator must do it manually.
-.Sh SEE ALSO
-.Xr arp 4 ,
-.Xr netintro 4 ,
-.Xr ng_ether 4 ,
-.Xr xen 4 ,
-.Xr ifconfig 8
-.Sh HISTORY
-The
-.Nm
-device driver first appeared in
-.Fx 10.0 .
-.Sh AUTHORS
-The
-.Nm
-driver was written by
-.An Alan Somers
-.Aq alans at spectralogic.com
-and
-.An John Suykerbuyk
-.Aq johns at spectralogic.com
 .Sh BUGS
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/ar.5
--- a/head/share/man/man5/ar.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/ar.5	Tue Apr 17 11:51:51 2012 +0300
@@ -21,11 +21,11 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man5/ar.5 229657 2012-01-05 21:43:33Z uqs $
+.\" $FreeBSD: head/share/man/man5/ar.5 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd November 28, 2010
+.Dt AR 5
 .Os
-.Dt AR 5
 .Sh NAME
 .Nm ar
 .Nd archive file format for
@@ -237,7 +237,7 @@
 No padding is used to separate adjacent file names.
 .Ss "Archive Symbol Tables"
 Archive symbol tables are used to speed up link editing by providing a
-mapping between the program symbols defined in the archive=20
+mapping between the program symbols defined in the archive
 and the corresponding archive members.
 Archive symbol tables are managed by the
 .Xr ranlib 1
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/fdescfs.5
--- a/head/share/man/man5/fdescfs.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/fdescfs.5	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man5/fdescfs.5 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd September 18, 2010
 .Dt FDESCFS 5
@@ -101,7 +101,7 @@
 .It Pa /dev/fd/#
 .El
 .Sh EXAMPLES
-To mount a =20
+To mount a
 .Nm
 volume located on
 .Pa /dev/fd :
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/fs.5
--- a/head/share/man/man5/fs.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/fs.5	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)fs.5	8.2 (Berkeley) 4/19/94
-.\" $FreeBSD: head/share/man/man5/fs.5 231564 2012-02-12 18:29:56Z ed $
+.\" $FreeBSD: head/share/man/man5/fs.5 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd October 31, 2006
 .Dt FS 5
@@ -408,10 +408,10 @@
 Returns a pointer to the next extended attribute following
 .Fa eap .
 .It Dv EXTATTR_CONTENT(eap)
-Returns a pointer to the extended attribute content referenced by=20
+Returns a pointer to the extended attribute content referenced by
 .Fa eap .
 .It Dv EXTATTR_CONTENT_SIZE(eap)
-Returns the size of the extended attribute content referenced by=20
+Returns the size of the extended attribute content referenced by
 .Fa eap .
 .It Dv EXTATTR_SET_LENGTHS(eap, size)
 Called with the size of the attribute content after initializing
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/fstab.5
--- a/head/share/man/man5/fstab.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/fstab.5	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)fstab.5	8.1 (Berkeley) 6/5/93
-.\" $FreeBSD: head/share/man/man5/fstab.5 222841 2011-06-08 00:31:10Z delp=
hij $
+.\" $FreeBSD: head/share/man/man5/fstab.5 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd June 7, 2011
 .Dt FSTAB 5
@@ -235,7 +235,7 @@
 checks are done at reboot time.
 The
 .Fa fs_passno
-field can be any value between 0 and=20
+field can be any value between 0 and
 .Ql INT_MAX Ns -1 .
 .Pp
 The root file system should be specified with a
@@ -245,7 +245,7 @@
 of 2 or greater.
 A file system with a
 .Fa fs_passno
-value of 1 is always checked sequentially and be completed before=20
+value of 1 is always checked sequentially and be completed before
 another file system is processed, and it will be processed before
 all file systems with a larger
 .Fa fs_passno .
@@ -269,7 +269,7 @@
 .Pp
 The
 .Fa fs_passno
-field can be used to implement finer control when=20
+field can be used to implement finer control when
 the system utilities may determine that the file system resides
 on a different physical device, when it actually does not, as with a
 .Xr ccd 4
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/nsmb.conf.5
--- a/head/share/man/man5/nsmb.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/nsmb.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man5/nsmb.conf.5 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd October 19, 2010
 .Dt NSMB.CONF 5
@@ -133,7 +133,7 @@
 .Dq Li FSERVER:USER ,
 defines the user settings and is useful for saving the password used
 during a specific connection.
-The password may be plaintext or obfuscated using simple encryption. =20
+The password may be plaintext or obfuscated using simple encryption.
 The simple encrypted password starts with the `$$1' symbols.
 Warning: the encryption function is very weak and intended only to hide
 clear text passwords.
@@ -141,7 +141,7 @@
 used on a password:
 .Bd -literal -offset indent
 smbutil crypt
-.Ed=20
+.Ed
 .Sh COMPATIBILITY
 At the time of this writing, the
 .Tn IPX
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/quota.user.5
--- a/head/share/man/man5/quota.user.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/quota.user.5	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man5/quota.user.5 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd October 30, 2007
 .Dt QUOTA.USER 5
@@ -44,7 +44,7 @@
 and
 .Dq Li groupquota
 options in the
-.Xr fstab 5=20
+.Xr fstab 5
 file.
 .Pp
 The data files contain the following information:
@@ -72,9 +72,9 @@
 .Xr edquota 8
 for an explanation on the various limits and grace periods.
 .Pp
-During normal quota operations the=20
+During normal quota operations the
 .Xr quotactl 2
-interface is used to query or set quota information and the kernel=20
+interface is used to query or set quota information and the kernel
 will maintain the data files as needed.
 If quotas are disabled on
 a file system, but marked as having quotas enabled in
@@ -104,8 +104,8 @@
 .Dq Dv dbq_itime
 fields are non-zero, they are used to indicate the grace period on
 that file system for users who have exceeded their soft limit.
-These times can be set by=20
-.Xr edquota 8=20
+These times can be set by
+.Xr edquota 8
 with the
 .Fl t
 flag.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/services.5
--- a/head/share/man/man5/services.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/services.5	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)services.5	8.1 (Berkeley) 6/5/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man5/services.5 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd April 4, 2010
 .Dt SERVICES 5
@@ -66,7 +66,7 @@
 character other than a field delimiter, newline,
 or comment character.
 .Pp
-If=20
+If
 .Dq db
 is specified as source in the
 .Xr nsswitch.conf 5 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/src.conf.5
--- a/head/share/man/man5/src.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/src.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 .\" DO NOT EDIT-- this file is automatically generated.
 .\" from FreeBSD: head/tools/build/options/makeman 221733 2011-05-10 13:01=
:11Z ru
-.\" $FreeBSD: head/share/man/man5/src.conf.5 232323 2012-02-29 23:06:48Z d=
im $
-.Dd February 29, 2012
+.\" $FreeBSD: head/share/man/man5/src.conf.5 233645 2012-03-29 03:04:59Z j=
mallett $
+.Dd March 25, 2012
 .Dt SRC.CONF 5
 .Os
 .Sh NAME
@@ -270,7 +270,7 @@
 Set to not build the Clang C/C++ compiler.
 .Pp
 It is a default setting on
-arm/arm, arm/armeb, ia64/ia64, mips/mipsel, mips/mipseb, mips/mips64el, mi=
ps/mips64eb, mips/mipsn32eb and sparc64/sparc64.
+arm/arm, arm/armeb, ia64/ia64, mips/mipsel, mips/mips, mips/mips64el, mips=
/mips64, mips/mipsn32 and sparc64/sparc64.
 When set, it also enforces the following options:
 .Pp
 .Bl -item -compact
@@ -384,7 +384,7 @@
 This includes the device tree compiler (dtc) and libfdt support library.
 .Pp
 It is a default setting on
-arm/arm, arm/armeb, mips/mipsel, mips/mipseb, mips/mips64el, mips/mips64eb=
, mips/mipsn32eb, powerpc/powerpc and powerpc/powerpc64.
+arm/arm, arm/armeb, mips/mipsel, mips/mips, mips/mips64el, mips/mips64, mi=
ps/mipsn32, powerpc/powerpc and powerpc/powerpc64.
 .It Va WITHOUT_FLOPPY
 .\" from FreeBSD: head/tools/build/options/WITHOUT_FLOPPY 221540 2011-05-0=
6 19:13:03Z ru
 Set to not build or install programs
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man5/style.Makefile.5
--- a/head/share/man/man5/style.Makefile.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man5/style.Makefile.5	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man5/style.Makefile.5 233515 2012-03-26 16:40=
:45Z joel $
 .\"
 .Dd January 8, 2005
 .Dt STYLE.MAKEFILE 5
@@ -143,7 +143,7 @@
 The usage of
 .Va WARNS
 is spelled
-.Dq Li "WARNS?=3D	" ,
+.Dq Li "WARNS?=3D " ,
 so that it may be overridden on the command line or in
 .Xr make.conf 5 .
 .It
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man7/mailaddr.7
--- a/head/share/man/man7/mailaddr.7	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man7/mailaddr.7	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)mailaddr.7	8.1 (Berkeley) 6/16/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man7/mailaddr.7 233422 2012-03-24 13:37:57Z j=
oel $
 .\"
 .Dd June 16, 1993
 .Dt MAILADDR 7
@@ -66,7 +66,6 @@
 without adding the ``berkeley.edu'' since it is the same on both sending
 and receiving hosts.
 .Ss Compatibility.
-.Pp
 Certain old address formats are converted to the new format to provide
 compatibility with the previous mail system.
 In particular,
@@ -94,16 +93,13 @@
 .Pp
 This is normally converted back to the ``host!user'' form before being sent
 on for compatibility with older UUCP hosts.
-.Pp
 .Ss Case Distinctions.
-.Pp
 Domain names (i.e., anything after the ``@'' sign) may be given in any mix=
ture
 of upper and lower case with the exception of UUCP hostnames.
 Most hosts
 accept any combination of case in user names, with the notable exception of
 MULTICS sites.
 .Ss Route-addrs.
-.Pp
 Under some circumstances it may be necessary to route a message through
 several hosts to get it to the final destination.
 Normally this routing
@@ -134,11 +130,9 @@
 .Pp
 is routed as indicated in the previous example.
 .Ss Postmaster.
-.Pp
 Every site is required to have a user or user alias designated ``postmaste=
r''
 to which problems with the mail system may be addressed.
 .Ss Other Networks.
-.Pp
 Some other networks can be reached by giving the name of the network as the
 last component of the domain.
 .Em This is not a standard feature
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man7/operator.7
--- a/head/share/man/man7/operator.7	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man7/operator.7	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)operator.7	8.1 (Berkeley) 6/9/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man7/operator.7 233510 2012-03-26 15:18:14Z j=
oel $
 .\"
 .Dd April 8, 2009
 .Dt OPERATOR 7
@@ -45,7 +45,7 @@
 .It "--------	-------------"
 .It "() [] -> .	left to right"
 .It "! ~ ++ -- - (type) * & sizeof new delete	right to left"
-.It "->* .*	left to right
+.It "->* .*	left to right"
 .It "* / %	left to right"
 .It "+ -	left to right"
 .It "<< >>	left to right"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man7/release.7
--- a/head/share/man/man7/release.7	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man7/release.7	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man7/release.7 230110 2012-01-14 18:16:10Z gl=
ebius $
+.\" $FreeBSD: head/share/man/man7/release.7 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd January 14, 2012
 .Dt RELEASE 7
@@ -53,7 +53,7 @@
 trees. For this purpose, a script
 .Pq Pa src/release/generate-release.sh
 is provided to automate these checkouts and then execute
-.Dq Li "make release"=20
+.Dq Li "make release"
 in a clean
 .Xr chroot 8 .
 .Pp
@@ -65,7 +65,7 @@
 The release build process requires that
 .Pa /usr/obj
 be populated with the output of
-.Dq Li "make buildworld"=20
+.Dq Li "make buildworld"
 and
 .Dq Li "make buildkernel" .
 This is necessary to provide the object files for the release or, when
@@ -139,7 +139,7 @@
 .It Ev CVS_TAG
 If the variable
 .Ev CVS_TAG
-is set, that tag will be used for CVS checkouts (doc and ports), otherwise=20
+is set, that tag will be used for CVS checkouts (doc and ports), otherwise
 .Ic generate-release.sh
 will use HEAD.
 .It Ev MAKE_FLAGS
@@ -151,7 +151,7 @@
 .Pa svn://svn.freebsd.org/base .
 .It Ev RELSTRING
 Optional base name for generated media images (e.g. FreeBSD-9.0-RC2-amd64).
-Defaults to the output of=20
+Defaults to the output of
 .Ic `uname -s`-`uname -r`-`uname -p`
 within the chroot.
 .El
@@ -170,12 +170,12 @@
 Meta-target to build all release media and distributions applicable to this
 platform.
 .It Cm install
-Copy all produced release media to=20
+Copy all produced release media to
 .Pa ${DESTDIR} .
 .It Cm cdrom
 Builds installation CD-ROM images. On some systems, this may require that
 .Xr mkisofs 8
-be installed=20
+be installed
 .Pq Pa sysutils/cdrtools
 and possibly that the
 .Xr md 4
@@ -239,7 +239,7 @@
 .Pa /usr/doc .
 If it is unset or cannot be found, most documentation will not be included=
 in
 the release; see
-.Ev NODOC=20
+.Ev NODOC
 below.
 .It Va NOPORTS
 If defined, the Ports Collection will be omitted from the release.
@@ -369,7 +369,7 @@
 .Pp
 For the
 .Fx 9.0
-release,=20
+release,
 .Pa src/release/Makefile
 was overhauled and the wrapper script
 .Pa src/release/generate-release.sh
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man8/picobsd.8
--- a/head/share/man/man8/picobsd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man8/picobsd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 .\" -*- nroff-fill -*-
-.\" $FreeBSD: head/share/man/man8/picobsd.8 223955 2011-07-12 14:18:54Z iv=
oras $
+.\" $FreeBSD: head/share/man/man8/picobsd.8 233648 2012-03-29 05:02:12Z ea=
dler $
 .Dd June 25, 2009
 .Dt PICOBSD 8
 .Os
@@ -648,7 +648,7 @@
 .Xr crunchgen 1 ,
 .Xr mdconfig 8 ,
 .Xr nanobsd 8 ,
-.Xr swapon 8=20
+.Xr swapon 8
 .Sh AUTHORS
 .An -nosplit
 .An Andrzej Bialecki Aq abial at FreeBSD.org ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/BUS_DESCRIBE_INTR.9
--- a/head/share/man/man9/BUS_DESCRIBE_INTR.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/BUS_DESCRIBE_INTR.9	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/BUS_DESCRIBE_INTR.9 233648 2012-03-29 05=
:02:12Z eadler $
 .\"
 .Dd October 14, 2009
 .Dt BUS_DESCRIBE_INTR 9
@@ -45,7 +45,7 @@
 .Ft int
 .Fo bus_describe_intr
 .Fa "device_t dev" "struct resource *irq" "void *cookie" "const char *fmt"
-.Fa ...=20
+.Fa ...
 .Fc
 .Sh DESCRIPTION
 The
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/BUS_SETUP_INTR.9
--- a/head/share/man/man9/BUS_SETUP_INTR.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/BUS_SETUP_INTR.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/BUS_SETUP_INTR.9 233648 2012-03-29 05:02=
:12Z eadler $
 .\"
 .Dd November 3, 2010
 .Dt BUS_SETUP_INTR 9
@@ -130,8 +130,8 @@
 A filter runs in primary interrupt context.
 In this context, normal mutexes cannot be used.
 Only the spin lock version of these can be used (specified by passing
-.Dv MTX_SPIN=20
-to=20
+.Dv MTX_SPIN
+to
 .Fn mtx_init
 when initializing the mutex).
 .Xr wakeup 9
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/DB_COMMAND.9
--- a/head/share/man/man9/DB_COMMAND.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/DB_COMMAND.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/DB_COMMAND.9 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd August 27, 2008
 .Dt DB_COMMAND 9
@@ -38,19 +38,18 @@
 .Fo DB_COMMAND
 .Fa command_name
 .Fa command_function
-.Fc=20
-.Fn DB_SHOW_COMMAND "command_name" "command_function"=20
-.Fn DB_SHOW_ALL_COMMAND "command_name" "command_function"=20
+.Fc
+.Fn DB_SHOW_COMMAND "command_name" "command_function"
+.Fn DB_SHOW_ALL_COMMAND "command_name" "command_function"
 .Sh DESCRIPTION
-.Pp
 The
 .Fn DB_COMMAND
 macro adds
 .Fa command_name
 to the list of top-level commands.
-Invoking=20
+Invoking
 .Fa command_name
-from ddb will call=20
+from ddb will call
 .Fa command_function .
 .Pp
 The
@@ -61,14 +60,14 @@
 .Fn DB_COMMAND
 but in these cases,
 .Fa command_name
-is a sub-command of the ddb=20
+is a sub-command of the ddb
 .Sy show
 command and
 .Sy show all
 command, respectively.
 .Pp
 The general command syntax:
-.Cm command Ns Op Li \&/ Ns Ar modifier=20
+.Cm command Ns Op Li \&/ Ns Ar modifier
 .Ar address Ns Op Li , Ns Ar count ,
 translates into the following parameters for
 .Fa command_function :
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/DEVICE_PROBE.9
--- a/head/share/man/man9/DEVICE_PROBE.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/DEVICE_PROBE.9	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/DEVICE_PROBE.9 231244 2012-02-09 04:37:3=
0Z gjb $
+.\" $FreeBSD: head/share/man/man9/DEVICE_PROBE.9 233648 2012-03-29 05:02:1=
2Z eadler $
 .\"
 .Dd February 8, 2012
 .Dt DEVICE_PROBE 9
@@ -96,7 +96,7 @@
 .It BUS_PROBE_VENDOR
 The device is supported by a vendor driver.
 This is for source or binary drivers that are not yet integrated into the
-.Fx=20
+.Fx
 tree.
 Its use in the base OS is prohibited.
 .It BUS_PROBE_DEFAULT
@@ -119,8 +119,8 @@
 treatment for some reason.
 .It BUS_PROBE_HOOVER
 The driver matches all unclaimed devices on a bus.
-The=20
-.Xr ugen 4=20
+The
+.Xr ugen 4
 device is one example.
 .It BUS_PROBE_NOWILDCARD
 The driver expects its parent to tell it which children to manage
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/Makefile
--- a/head/share/man/man9/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/man/man9/Makefile 232516 2012-03-04 18:55:33Z jhb $
+# $FreeBSD: head/share/man/man9/Makefile 233505 2012-03-26 09:34:17Z melif=
aro $
=20
 MAN=3D	accept_filter.9 \
 	accf_data.9 \
@@ -773,6 +773,8 @@
 	kqueue.9 knlist_destroy.9 \
 	kqueue.9 knlist_empty.9 \
 	kqueue.9 knlist_init.9 \
+	kqueue.9 knlist_init_mtx.9 \
+	kqueue.9 knlist_init_rw_reader.9 \
 	kqueue.9 knlist_remove.9 \
 	kqueue.9 knlist_remove_inevent.9 \
 	kqueue.9 knote_fdclose.9 \
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/SYSINIT.9
--- a/head/share/man/man9/SYSINIT.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/SYSINIT.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,14 +22,14 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/SYSINIT.9 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd December 1, 2010
 .Dt SYSINIT 9
 .Os
 .Sh NAME
 .Nm SYSINIT ,
-.Nm SYSUNINIT=20
+.Nm SYSUNINIT
 .Nd a framework for dynamic kernel initialization
 .Sh SYNOPSIS
 .In sys/param.h
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/buf_ring.9
--- a/head/share/man/man9/buf_ring.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/buf_ring.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/buf_ring.9 230787 2012-01-30 21:02:25Z b=
rueffer $
+.\" $FreeBSD: head/share/man/man9/buf_ring.9 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd January 30, 2012
 .Dt BUF_RING 9
@@ -68,7 +68,7 @@
 The
 .Nm
 functions provide a lock-less multi-producer and lock-less multi-consumer =
as
-well as single-consumer ring buffer.=20
+well as single-consumer ring buffer.
 .Pp
 The
 .Fn buf_ring_alloc
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/condvar.9
--- a/head/share/man/man9/condvar.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/condvar.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=
 SUCH
 .\" DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/condvar.9 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd June 5, 2007
 .Dt CONDVAR 9
@@ -117,10 +117,10 @@
 or
 .Xr sx 9
 lock.
-A=20
+A
 .Xr mutex 9
 argument must be initialized with
-.Dv MTX_DEF=20
+.Dv MTX_DEF
 and not
 .Dv MTX_SPIN .
 A thread must hold
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/crypto.9
--- a/head/share/man/man9/crypto.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/crypto.9	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 .\" MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
 .\" PURPOSE.
 .\"
-.\" $FreeBSD: head/share/man/man9/crypto.9 231564 2012-02-12 18:29:56Z ed $
+.\" $FreeBSD: head/share/man/man9/crypto.9 233510 2012-03-26 15:18:14Z joe=
l $
 .\"
 .Dd September 19, 2007
 .Dt CRYPTO 9
@@ -450,7 +450,7 @@
 The various fields in the
 .Vt cryptkop
 structure are:
-.Bl -tag -width ".Va krp_callback'
+.Bl -tag -width ".Va krp_callback"
 .It Va krp_op
 Operation code, such as
 .Dv CRK_MOD_EXP .
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/devclass_get_maxun=
it.9
--- a/head/share/man/man9/devclass_get_maxunit.9	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/share/man/man9/devclass_get_maxunit.9	Tue Apr 17 11:51:51 2012 +=
0300
@@ -26,7 +26,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/devclass_get_maxunit.9 233648 2012-03-29=
 05:02:12Z eadler $
 .\"
 .Dd September 10, 2010
 .Dt DEVCLASS_GET_MAXUNIT 9
@@ -48,7 +48,7 @@
 .Fn devclass_get_maxunit
 function returns -1 if
 .Fa dc
-is=20
+is
 .Dv NULL;
 otherwise it returns the next unit
 number in
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/device_get_childre=
n.9
--- a/head/share/man/man9/device_get_children.9	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/share/man/man9/device_get_children.9	Tue Apr 17 11:51:51 2012 +0=
300
@@ -26,7 +26,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/device_get_children.9 233648 2012-03-29 =
05:02:12Z eadler $
 .\"
 .Dd August 23, 2008
 .Dt DEVICE_GET_CHILDREN 9
@@ -48,9 +48,9 @@
 .Fa *devcountp .
 The memory allocated for the list should be freed using
 .Fn free "*devlistp" "M_TEMP" .
-.Fa devlistp=20
+.Fa devlistp
 and
-.Fa devcountp=20
+.Fa devcountp
 are not changed when an error is returned.
 .Sh RETURN VALUES
 Zero is returned on success, otherwise an appropriate error is returned.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/drbr.9
--- a/head/share/man/man9/drbr.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/drbr.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/drbr.9 230787 2012-01-30 21:02:25Z bruef=
fer $
+.\" $FreeBSD: head/share/man/man9/drbr.9 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd January 30, 2012
 .Dt DRBR 9
@@ -76,7 +76,7 @@
 will assert that the tx queue lock is held when it is called.
 .Pp
 The
-.Fn drbr_free=20
+.Fn drbr_free
 function frees all the enqueued mbufs and then frees the buf_ring.
 .Pp
 The
@@ -106,7 +106,7 @@
 .Fn drbr_flush
 function frees all mbufs enqueued in the buf_ring and the ifnet's IFQ.
 .Pp
-The=20
+The
 .Fn drbr_empty
 function returns
 .Dv TRUE
@@ -118,7 +118,7 @@
 .Fn drbr_inuse
 function returns the number of mbufs enqueued.
 Note to users that this is intrinsically racy as there is no guarantee that
-there will not be more mbufs when=20
+there will not be more mbufs when
 .Fn drbr_dequeue
 is actually called.
 Provided the tx queue lock is held there will not be less.
@@ -137,7 +137,7 @@
 .Pp
 The
 .Fn drbr_dequeue
-and=20
+and
 .Fn drbr_dequeue_cond
 functions return an mbuf on success and
 .Dv NULL
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/eventtimers.9
--- a/head/share/man/man9/eventtimers.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/eventtimers.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/eventtimers.9 231564 2012-02-12 18:29:56=
Z ed $
+.\" $FreeBSD: head/share/man/man9/eventtimers.9 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd December 14, 2011
 .Dt EVENTTIMERS 9
@@ -213,7 +213,7 @@
 It releases the event timer for other consumers use.
 .Pp
 .Fn ET_LOCK
-and=20
+and
 .Fn ET_UNLOCK
 macros should be used to manage
 .Xr mutex 9
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/fail.9
--- a/head/share/man/man9/fail.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/fail.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=
 SUCH
 .\" DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/fail.9 223876 2011-07-08 20:41:12Z mdf $
+.\" $FreeBSD: head/share/man/man9/fail.9 233422 2012-03-24 13:37:57Z joel $
 .\"
 .Dd May 10, 2009
 .Dt FAIL 9
@@ -165,7 +165,6 @@
 A pid can optionally be specified.
 The fail point term is only executed when invoked by a process with a
 matching p_pid.
-.Pp
 .Sh EXAMPLES
 .Bl -tag
 .It Sy sysctl debug.fail_point.foobar=3D"2.1%return(5)"
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/firmware.9
--- a/head/share/man/man9/firmware.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/firmware.9	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/firmware.9 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd August 2, 2008
 .Dt FIRMWARE 9
@@ -157,7 +157,7 @@
 to indicate that
 firmware_put is free to reclaim resources associated with
 the firmware image if this is the last reference.
-By default a firmware image will be deferred to a=20
+By default a firmware image will be deferred to a
 .Xr taskqueue 9
 thread so the call may be done while holding a lock.
 In certain cases, such as on driver detach, this cannot be allowed.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211.9
--- a/head/share/man/man9/ieee80211.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,13 +23,13 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211.9 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd April 28, 2010
 .Dt IEEE80211 9
 .Os
 .Sh NAME
-.Nm IEEE80211=20
+.Nm IEEE80211
 .Nd 802.11 network layer
 .Sh SYNOPSIS
 .In net80211/ieee80211_var.h
@@ -164,7 +164,7 @@
 This is initially provided by the driver but may be changed
 through calls that change the regulatory state.
 .It Dv ic_nchan
-Number of entries in=20
+Number of entries in
 .Dv ic_channels .
 .El
 .Pp
@@ -221,7 +221,7 @@
 it will not be used.
 .It Dv ic_node_alloc
 Allocate and initialize a
-.Vt ieee80211_node=20
+.Vt ieee80211_node
 structure.
 This method cannot sleep.
 The default method allocates zero'd memory using
@@ -232,7 +232,7 @@
 .Dv M_80211_NODE
 to balance the memory allocation statistics.
 .It Dv ic_node_free
-Reclaim storage of a node allocated by=20
+Reclaim storage of a node allocated by
 .Dv ic_node_alloc  .
 Drivers are expected to
 .Em interpose
@@ -302,7 +302,7 @@
 to advance to the next channel in the scan list.
 This callback is done in a sleepable context.
 The default method handles active scan work (e.g. sending ProbeRequest
-frames), and schedules a call to=20
+frames), and schedules a call to
 .Xr ieee80211_scan_next 9
 according to the maximum dwell time for the channel.
 Drivers that off-load scan work to firmware typically use this method
@@ -354,7 +354,7 @@
 .El
 .Pp
 Once the
-.Nm=20
+.Nm
 layer is attached to a driver there are two more steps typically done
 to complete the work:
 .Bl -enum
@@ -405,7 +405,7 @@
 Device is capable of operating in station (aka Infrastructure) mode.
 .It Dv IEEE80211_C_8023ENCAP
 Device requires 802.3-encapsulated frames be passed for transmit.
-By default=20
+By default
 .Nm
 will encapsulate all outbound frames as 802.11 frames (without a PLCP head=
er).
 .It Dv IEEE80211_C_FF
@@ -529,16 +529,16 @@
 .It Dv IEEE80211_HTC_AMPDU
 Device supports A-MPDU aggregation.
 Note that any 802.11n compliant device must support A-MPDU receive
-so this implicitly means support for=20
+so this implicitly means support for
 .Em transmit
 of A-MPDU frames.
 .It Dv IEEE80211_HTC_AMSDU
 Device supports A-MSDU aggregation.
 Note that any 802.11n compliant device must support A-MSDU receive
-so this implicitly means support for=20
+so this implicitly means support for
 .Em transmit
 of A-MSDU frames.
-.It Dv IEEE80211_HTC_HT=20
+.It Dv IEEE80211_HTC_HT
 Device supports High Throughput (HT) operation.
 This capability must be set to enable 802.11n functionality
 in
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_amrr.9
--- a/head/share/man/man9/ieee80211_amrr.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_amrr.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_amrr.9 233648 2012-03-29 05:02=
:12Z eadler $
 .\"
 .Dd August 4, 2009
 .Dt IEEE8021_AMRR 9
@@ -86,7 +86,7 @@
 To maximize throughput algorithms try to use the highest rate that
 is appropriate for the operating conditions.
 The rate will vary as conditions change; the distance between two stations
-may change, transient noise may be present that affects signal quality,=20
+may change, transient noise may be present that affects signal quality,
 etc.
 .Nm
 uses very simple information from a driver to do it's job:
@@ -119,8 +119,8 @@
 .Vt amrr
 structure member holds the per-vap state for
 .Nm
-and=20
-.Xr ral 4=20
+and
+.Xr ral 4
 initializes it in the vap create method with:
 .Bd -literal -offset indent
 ieee80211_amrr_init(&rvp->amrr, vap,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_bmiss.9
--- a/head/share/man/man9/ieee80211_bmiss.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_bmiss.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_bmiss.9 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd August 4, 2009
 .Dt IEEE80211_BMISS 9
@@ -56,9 +56,9 @@
 access point to check if the association is still alive.
 If no response is received and roaming mode is set to
 .Dv IEEE80211_ROAMING_AUTO
-then=20
+then
 .Nm net80211
-will try to re-associate and if that fails=20
+will try to re-associate and if that fails
 trigger a scan to look for the access point or another suitable AP.
 When the
 .Nm net80211
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_crypto.9
--- a/head/share/man/man9/ieee80211_crypto.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_crypto.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_crypto.9 233734 2012-03-31 07:=
10:16Z joel $
 .\" $Id: ieee80211_crypto.9,v 1.3 2004/03/04 10:42:56 bruce Exp $
 .\"
 .Dd March 29, 2010
@@ -127,7 +127,7 @@
 cipher modules register their services using
 .Fn ieee80211_crypto_register
 and supply a template that describes their operation.
-This=20
+This
 .Vt ieee80211_cipher
 structure defines protocol-related state such as the number of bytes
 of space in the 802.11 header to reserve/remove during encap/decap
@@ -153,7 +153,7 @@
 .Sh CRYPTO KEY MANAGEMENT
 The
 .Nm net80211
-layer implements a per-vap 4-element=20
+layer implements a per-vap 4-element
 .Dq global key table
 and a per-station
 .Dq unicast key
@@ -235,7 +235,7 @@
 For receive, drivers mark frames with the
 .Dv M_WEP
 mbuf flag to indicate the hardware has decrypted the payload.
-If frames have the=20
+If frames have the
 .Dv IEEE80211_FC1_WEP
 bit marked in their 802.11 header and are not tagged with
 .Dv M_WEP
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_input.9
--- a/head/share/man/man9/ieee80211_input.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_input.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_input.9 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd August 4, 2009
 .Dt IEEE80211_INPUT 9
@@ -110,7 +110,7 @@
 layer to make scanning and roaming decisions in station mode
 and to do auto channel selection for hostap and similar modes.
 Otherwise the values are made available to user applications
-(with the rssi presented as a filtered average over the last ten values=20
+(with the rssi presented as a filtered average over the last ten values
 and the noise floor the last reported value).
 .Sh SEE ALSO
 .Xr ieee80211 9
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_node.9
--- a/head/share/man/man9/ieee80211_node.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_node.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_node.9 233648 2012-03-29 05:02=
:12Z eadler $
 .\"
 .Dd April 28, 2010
 .Dt IEEE80211_NODE 9
@@ -67,18 +67,18 @@
 .Ft void
 .Fo ieee80211_dump_nodes
 .Fa "struct ieee80211_node_table *"
-.Fc=20
+.Fc
 .\"
 .Ft void
 .Fo ieee80211_dump_node
 .Fa "struct ieee80211_node *"
-.Fc=20
+.Fc
 .Sh DESCRIPTION
 The
 .Nm net80211
 layer that supports 802.11 device drivers maintains a database of
 peer stations called the
-.Dq node table=20
+.Dq node table
 in the
 .Vt ic_sta
 entry of the
@@ -125,7 +125,7 @@
 This reference must be reclaimed by the driver when transmit processing
 is done.
 For each frame received the driver must lookup the table entry to
-use in dispatching the frame=20
+use in dispatching the frame
 .Dq up the stack .
 This lookup implicitly obtains a reference to the table entry and
 the driver must reclaim the reference when frame processing is completed.
@@ -139,7 +139,7 @@
 .Fn ieee80211_iterate_nodes
 call may be used to iterate through all entries to do per-node
 processing or implement some non-standard search mechanism.
-Note that=20
+Note that
 .Fn ieee80211_iterate_nodes
 is single-threaded per-device
 and the effort processing involved is fairly
@@ -206,7 +206,7 @@
         struct ieee80211com *ic =3D ni->ni_ic;
         struct iwi_softc *sc =3D ic->ic_ifp->if_softc;
         struct iwi_node *in =3D (struct iwi_node *)ni;
-       =20
+
         if (in->in_station !=3D -1)
                 free_unr(sc->sc_unr, in->in_station);
         sc->sc_node_free(ni);	/* invoke net80211 free handler */
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_output.9
--- a/head/share/man/man9/ieee80211_output.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_output.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_output.9 233648 2012-03-29 05:=
02:12Z eadler $
 .\" $Id: ieee80211_output.9,v 1.5 2004/03/04 12:31:18 bruce Exp $
 .\"
 .Dd March 29, 2010
@@ -110,13 +110,13 @@
 field.
 The node is associated with the frame destination.
 Typically it is the receiver's entry but in some situations it may be
-a placeholder entry or the=20
+a placeholder entry or the
 .Dq next hop station
 (such as in a mesh network).
 In all cases the reference must be reclaimed with
 .Fn ieee80211_free_node
 when the transmit work is completed.
-The rule to remember is:=20
+The rule to remember is:
 .Nm net80211
 passes responsibility for the
 .Vt mbuf
@@ -131,7 +131,7 @@
 in an IP or IPv6 header.
 If both vlan and Diffserv priority are present the higher of the
 two is used.
-If WME/WMM is being used then any ACM policy (in station mode) is=20
+If WME/WMM is being used then any ACM policy (in station mode) is
 also enforced.
 The resulting AC is attached to the mbuf and may be read back using the
 .Fn M_WME_GETAC
@@ -182,7 +182,7 @@
 .Fn ieee80211_process_callback
 with the last parameter set to a non-zero value if an error occurred
 and zero otherwise.
-Note=20
+Note
 .Nm net80211
 understands that drivers may be incapable of determining status;
 a device may not report if an ACK frame is received and/or a device may qu=
eue
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_proto.9
--- a/head/share/man/man9/ieee80211_proto.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_proto.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_proto.9 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd August 4, 2009
 .Dt IEEE80211_PROTO 9
@@ -108,7 +108,7 @@
 .Dq port
 is authorized.
 When WPA/802.11i/802.1x is operational authorization may happen separately;
-e.g. in station mode=20
+e.g. in station mode
 .Xr wpa_supplicant 8
 must complete the handshakes and plumb the necessary keys before a port
 is authorized.
@@ -143,14 +143,14 @@
 .Nm net80211
 data are valid only in certain states; e.g. the
 .Vt iv_bsschan
-that specifies the channel for the operating BSS should never be used=20
+that specifies the channel for the operating BSS should never be used
 except in
 .Dv IEEE80211_S_RUN
 or greater.
 .Sh STATE CHANGES
 State machine changes are typically handled internal to the
 .Nm net80211
-layer in response to=20
+layer in response to
 .Xr ioctl 2
 requests, received frames, or external events such as a beacon miss.
 The
@@ -161,7 +161,7 @@
 For example, only one vap at a time can be scanning, if multiple vaps
 request a change to
 .Dv IEEE80211_S_SCAN
-the first will be permitted to run and the others will be=20
+the first will be permitted to run and the others will be
 .Em deferred
 until the scan operation completes at which time the selected channel
 will be adopted.
@@ -197,12 +197,12 @@
 handles two state changes specially.
 On transition to
 .Dv IEEE80211_S_RUN
-the=20
+the
 .Dv IFF_DRV_OACTIVE
 bit on the vap's transmit queue is cleared so traffic can flow.
 On transition to
 .Dv IEEE80211_S_INIT
-any state in the scan cache associated with the vap is flushed=20
+any state in the scan cache associated with the vap is flushed
 and any frames pending on the transmit queue are flushed.
 .Sh DRIVER INTEGRATION
 Drivers are expected to override the
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_radiotap=
.9
--- a/head/share/man/man9/ieee80211_radiotap.9	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/share/man/man9/ieee80211_radiotap.9	Tue Apr 17 11:51:51 2012 +03=
00
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_radiotap.9 233648 2012-03-29 0=
5:02:12Z eadler $
 .\"
 .Dd August 4, 2009
 .Dt IEEE80211_RADIOTAP 9
@@ -61,7 +61,7 @@
 .Nm net80211
 layer used by 802.11 drivers includes support for a device-independent
 packet capture format called
-.Nm radiotap=20
+.Nm radiotap
 that is understood by tools such as
 .Xr tcpdump 1 .
 This facility is designed for capturing 802.11 traffic,
@@ -257,7 +257,7 @@
         uint16_t       wr_chan_flags;
         uint8_t        wr_antsignal;
         uint8_t        wr_antnoise;
-} __packed;=20
+} __packed;
 .Ed
 .Pp
 and transmit definitions for the Atheros driver:
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_regdomai=
n.9
--- a/head/share/man/man9/ieee80211_regdomain.9	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/share/man/man9/ieee80211_regdomain.9	Tue Apr 17 11:51:51 2012 +0=
300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_regdomain.9 233648 2012-03-29 =
05:02:12Z eadler $
 .\"
 .Dd August 4, 2009
 .Dt IEEE80211_REGDOMAIN 9
@@ -56,7 +56,7 @@
 software layer provides a support framework for drivers that includes
 comprehensive regulatory support.
 .Nm net80211
-provides mechanisms that enforce=20
+provides mechanisms that enforce
 .Em "regulatory policy"
 by privileged user applications.
 .Pp
@@ -102,7 +102,7 @@
 If default settings are known they can be installed and/or an event
 can be dispatched to user space using
 .Fn ieee80211_notify_country
-so that=20
+so that
 .Xr devd 8
 will do the appropriate setup work at system boot (or device insertion).
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_scan.9
--- a/head/share/man/man9/ieee80211_scan.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_scan.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_scan.9 233648 2012-03-29 05:02=
:12Z eadler $
 .\"
 .Dd March 29, 2010
 .Dt IEEE80211_SCAN 9
@@ -322,7 +322,7 @@
 though some information such as RSSI and noise floor readings may be
 combined to present an average.
 .Pp
-The cache contents is aged through=20
+The cache contents is aged through
 .Fn ieee80211_scan_timeout
 calls.
 Typically these happen together with other station table activity; every
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ieee80211_vap.9
--- a/head/share/man/man9/ieee80211_vap.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ieee80211_vap.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/ieee80211_vap.9 233648 2012-03-29 05:02:=
12Z eadler $
 .\"
 .Dd August 4, 2009
 .Dt IEEE8021_VAP 9
@@ -93,7 +93,7 @@
 structure at the front but is usually extended with driver-private state.
 Next the vap is setup with a call to
 .Fn ieee80211_vap_setup .
-This request initializes=20
+This request initializes
 .Nm net80211
 state but does not activate the interface.
 The driver can then override methods setup by
@@ -108,7 +108,7 @@
 .Dv SIOCIFDESTROY
 ioctl request is made or when the device detaches (causing all
 associated vaps to automatically be deleted).
-Delete requests cause the=20
+Delete requests cause the
 .Vt ic_vap_delete
 method to be called.
 Drivers must quiesce the device before calling
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/ifnet.9
--- a/head/share/man/man9/ifnet.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/ifnet.9	Tue Apr 17 11:51:51 2012 +0300
@@ -26,9 +26,9 @@
 .\" OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/ifnet.9 232659 2012-03-07 14:53:53Z pluk=
net $
+.\" $FreeBSD: head/share/man/man9/ifnet.9 233370 2012-03-23 16:24:07Z pluk=
net $
 .\"
-.Dd March 7, 2012
+.Dd March 23, 2012
 .Dt IFNET 9
 .Os
 .Sh NAME
@@ -229,6 +229,18 @@
 A pointer to the common data for the interface's layer 2 protocol.
 (Initialized by
 .Fn if_alloc . )
+.It Va if_vnet
+.Pq Vt "struct vnet *"
+A pointer to the virtual network stack instance.
+(Initialized by
+.Fn if_attach . )
+.It Va if_home_vnet
+.Pq Vt "struct vnet *"
+A pointer to the parent virtual network stack, where this
+.Vt "struct ifnet"
+originates from.
+(Initialized by
+.Fn if_attach . )
 .It Va if_link
 .Pq Fn TAILQ_ENTRY ifnet
 .Xr queue 3
@@ -276,6 +288,13 @@
 reference-count the
 .Dv IFF_PROMISC
 flag.
+.It Va if_carp
+.Pq Vt "struct carp_if *"
+A pointer to the CARP interface structure,
+.Xr carp 4 .
+(Initialized by the driver-specific
+.Fn if_ioctl
+routine.)
 .It Va if_bpf
 .Pq Vt "struct bpf_if *"
 Opaque per-interface data for the packet filter,
@@ -293,6 +312,13 @@
 .Xr link_addr 3 ) .
 (Initialized by
 .Fn if_alloc . )
+.It Va if_vlantrunk
+.Pq Vt struct ifvlantrunk *
+A pointer to 802.1Q trunk structure,
+.Xr vlan 4 .
+(Initialized by the driver-specific
+.Fn if_ioctl
+routine.)
 .It Va if_flags
 .Pq Vt int
 Flags describing operational parameters of this interface (see below).
@@ -307,17 +333,6 @@
 .It Va if_capenable
 .Pq Vt int
 Flags describing the enabled capabilities of the interface (see below).
-.\" .It Va if_ipending
-.\" Interrupt-pending bits for polled operation:
-.\" .Dv IFI_XMIT
-.\" (transmit complete interrupt)
-.\" and
-.\" .Dv IFI_RECV
-.\" (received packet ready interrupt).
-.\" See the
-.\" .Sx Polling
-.\" section, below.
-.\" (Manipulated by driver.)
 .It Va if_linkmib
 .Pq Vt "void *"
 A pointer to an interface-specific MIB structure exported by
@@ -334,18 +349,97 @@
 below.
 (Initialized by driver, manipulated by both driver and generic
 code.)
+.It Va if_multiaddrs
+.Pq Vt struct ifmultihead
+The head of the
+.Xr queue 3
+.Li TAILQ
+containing the list of multicast addresses assigned to this interface.
+.It Va if_amcount
+.Pq Vt int
+A number of multicast requests on this interface, used to
+reference-count the
+.Dv IFF_ALLMULTI
+flag.
+.It Va if_addr
+.Pq Vt "struct ifaddr *"
+A pointer to the link-level interface address.
+(Initialized by
+.Fn if_alloc . )
+.\" .It Va if_llsoftc
+.\" .Pq Vt "void *"
+.\" The purpose of the field is unclear.
 .It Va if_snd
-.Pq Vt "struct ifqueue"
+.Pq Vt "struct ifaltq"
 The output queue.
 (Manipulated by driver.)
-.\".It Va if_poll_slowq
-.\".Pq Vt "struct ifqueue *"
-.\"A pointer to the input queue for devices which do not support polling
-.\"well.
-.\"See the
-.\".Sx Polling
-.\"section, below.
-.\"(Initialized by driver.)
+.It Va if_broadcastaddr
+.Pq Vt "const u_int8_t *"
+A link-level broadcast bytestring for protocols with variable address
+length.
+.It Va if_bridge
+.Pq Vt "void *"
+A pointer to the bridge interface structure,
+.Xr if_bridge 4 .
+(Initialized by the driver-specific
+.Fn if_ioctl
+routine.)
+.It Va if_label
+.Pq Vt "struct label *"
+A pointer to the MAC Framework label structure,
+.Xr mac 4 .
+(Initialized by
+.Fn if_alloc . )
+.It Va if_afdata
+.Pq Vt "void *"
+An address family dependent data region.
+.It Va if_afdata_initialized
+.Pq Vt int
+Used to track the current state of address family initialization.
+.It Va if_afdata_lock
+.Pq Vt "struct rwlock"
+An
+.Xr rwlock 9
+lock used to protect
+.Va if_afdata
+internals.
+.It Va if_linktask
+.Pq Vt "struct task"
+A
+.Xr taskqueue 9
+task scheduled for link state change events of the interface.
+.It Va if_addr_lock
+.Pq Vt "struct rwlock"
+An
+.Xr rwlock 9
+lock used to protect interface-related address lists.
+.It Va if_clones
+.Pq Fn LIST_ENTRY ifnet
+.Xr queue 3
+macro glue for the list of clonable network interfaces.
+.It Va if_groups
+.Pq Fn TAILQ_HEAD ", ifg_list"
+The head of the
+.Xr queue 3
+.Li TAILQ
+containing the list of groups per interface.
+.It Va if_pf_kif
+.Pq Vt "void *"
+A pointer to the structure used for interface abstraction by
+.Xr pf 4 .
+.It Va if_lagg
+.Pq Vt "void *"
+A pointer to the
+.Xr lagg 4
+interface structure.
+.It Va if_alloctype
+.Pq Vt u_char
+The type of the interface as it was at the time of its allocation.
+It is used to cache the type passed to
+.Fn if_alloc ,
+but unlike
+.Va if_type ,
+it would not be changed by drivers.
 .El
 .Pp
 References to
@@ -416,10 +510,6 @@
 does not literally mean that output is active, but rather that the
 device's internal output queue is full.) Please note that this function
 will soon be deprecated.
-.It Fn if_done
-Not used.
-We are not even sure what it was ever for.
-The prototype is faked.
 .It Fn if_ioctl
 Process interface-related
 .Xr ioctl 2
@@ -434,13 +524,6 @@
 See the description of
 .Fn ifioctl
 below for more information.
-.\" .It Fn if_poll_recv
-.\" .It Fn if_poll_xmit
-.\" .It Fn if_poll_slowinput
-.\" .It Fn if_poll_intren
-.\" See the
-.\" .Sx Polling
-.\" section, below.
 .It Fn if_init
 Initialize and bring up the hardware,
 e.g., reset the chip and enable the receiver unit.
@@ -500,6 +583,14 @@
 The interface is point-to-point;
 .Dq broadcast
 address is actually the address of the other end.
+.It Dv IFF_SMART
+.Aq S*
+The interface manages its own routes, rather than using the generic
+code in
+.Fn if_up
+and
+.Fn if_down .
+This is probably useful for serial lines.
 .It Dv IFF_DRV_RUNNING
 .Aq D*
 The interface has been configured and dynamic resources were
@@ -536,14 +627,31 @@
 .It Dv IFF_MULTICAST
 .Aq S*
 This interface supports multicast.
-.It Dv IFF_POLLING
+.It Dv IFF_CANTCONFIG
+.Aq S*
+The interface is not configurable in a meaningful way.
+Primarily useful for
+.Dv IFT_USB
+interfaces registered at the interface list.
+.It Dv IFF_MONITOR
+.Aq D
+This interface blocks transmission of packets and discards incoming
+packets after BPF processing.
+Used to monitor network trafic but not interact
+with the network in question.
+.It Dv IFF_STATICARP
+.Aq D
+Used to enable/disable ARP requests on this interface.
+.It Dv IFF_DYING
 .Aq D*
-The interface is in
-.Xr polling 4
-mode.
-See
-.Sx Interface Capabilities Flags
-for details.
+Set when the
+.Vt ifnet
+structure of this interface is being released and still has
+.Va if_refcount
+references.
+.It Dv IFF_RENAMING
+.Aq D*
+Set when this interface is being renamed.
 .El
 .Ss "Interface Capabilities Flags"
 Interface capabilities are specialized features an interface may
@@ -577,13 +685,7 @@
 .Xr ioctl 2 .
 .Pp
 The following capabilities are currently supported by the system:
-.Bl -tag -width ".Dv IFCAP_VLAN_HWTAGGING" -offset indent
-.It Dv IFCAP_NETCONS
-This interface can be a network console.
-.It Dv IFCAP_POLLING
-This interface supports
-.Xr polling 4 .
-See below for details.
+.Bl -tag -width ".Dv IFCAP_POLLING_NOCOUNT" -offset indent
 .It Dv IFCAP_RXCSUM
 This interface can do checksum validation on receiving data.
 Some interfaces do not have sufficient buffer storage to store frames
@@ -595,9 +697,8 @@
 .It Dv IFCAP_HWCSUM
 A shorthand for
 .Pq Dv IFCAP_RXCSUM | IFCAP_TXCSUM .
-.It Dv IFCAP_VLAN_HWTAGGING
-This interface can do VLAN tagging on output and
-demultiplex frames by their VLAN tag on input.
+.It Dv IFCAP_NETCONS
+This interface can be a network console.
 .It Dv IFCAP_VLAN_MTU
 The
 .Xr vlan 4
@@ -607,11 +708,24 @@
 interfaces below 1500 bytes.
 This implies the ability of this interface to cope with frames somewhat
 longer than permitted by the Ethernet specification.
+.It Dv IFCAP_VLAN_HWTAGGING
+This interface can do VLAN tagging on output and
+demultiplex frames by their VLAN tag on input.
 .It Dv IFCAP_JUMBO_MTU
 This Ethernet interface can transmit and receive frames up to
 9000 bytes long.
+.It Dv IFCAP_POLLING
+This interface supports
+.Xr polling 4 .
+See below for details.
+.It Dv IFCAP_VLAN_HWCSUM
+This interface can do checksum calculation on both transmitting
+and receiving data on
+.Xr vlan 4
+interfaces (implies
+.Dv IFCAP_HWCSUM ) .
 .It Dv IFCAP_TSO4
-This Ethernet interface supports TCP Segmentation offloading.
+This Ethernet interface supports TCP4 Segmentation offloading.
 .It Dv IFCAP_TSO6
 This Ethernet interface supports TCP6 Segmentation offloading.
 .It Dv IFCAP_TSO
@@ -621,7 +735,7 @@
 This Ethernet interface supports TCP offloading.
 .It Dv IFCAP_TOE6
 This Ethernet interface supports TCP6 offloading.
-.It Dv ICAP_TOE
+.It Dv IFCAP_TOE
 A shorthand for
 .Pq Dv IFCAP_TOE4 | IFCAP_TOE6 .
 .It Dv IFCAP_WOL_UCAST
@@ -635,6 +749,27 @@
 .It Dv IFCAP_WOL
 A shorthand for
 .Pq Dv IFCAP_WOL_UCAST | IFCAP_WOL_MCAST | IFCAP_WOL_MAGIC .
+.It Dv IFCAP_TOE4
+This Ethernet interface supports TCP4 Offload Engine.
+.It Dv IFCAP_TOE6
+This Ethernet interface supports TCP6 Offload Engine.
+.It Dv IFCAP_TOE
+A shorthand for
+.Pq Dv IFCAP_TOE4 | IFCAP_TOE6 .
+.It Dv IFCAP_VLAN_HWFILTER
+This interface supports frame filtering in hardware on
+.Xr vlan 4
+interfaces.
+.It Dv IFCAP_POLLING_NOCOUNT
+The return value for the number of processed packets should be
+skipped for this interface.
+.It Dv IFCAP_VLAN_HWTSO
+This interface supports TCP Segmentation offloading on
+.Xr vlan 4
+interfaces (implies
+.Dv IFCAP_TSO ) .
+.It Dv IFCAP_LINKSTATE
+This Ethernet interface supports dynamic link state changes.
 .El
 .Pp
 The ability of advanced network interfaces to offload certain
@@ -690,20 +825,7 @@
 .Xr polling 4
 mode involves several flags in different
 global variables and per-interface fields.
-First, there is a system-wide
-.Xr sysctl 8
-master switch named
-.Va kern.polling.enable ,
-which can toggle
-.Xr polling 4
-globally.
-If that variable is set to non-zero,
-.Xr polling 4
-will be used on those devices where it is enabled individually.
-Otherwise,
-.Xr polling 4
-will not be used in the system.
-Second, the capability flag
+The capability flag
 .Dv IFCAP_POLLING
 set in interface's
 .Va if_capabilities
@@ -713,20 +835,19 @@
 If set in
 .Va if_capabilities ,
 the same flag can be marked or cleared in the interface's
-.Va if_capenable ,
+.Va if_capenable
+within
+.Fn ifioctl ,
 thus initiating switch of the interface to
 .Xr polling 4
 mode or interrupt
 mode, respectively.
-The actual mode change will occur at an implementation-specific moment
-in the future, e.g., during the next interrupt or
-.Xr polling 4
-cycle.
-And finally, if the mode transition has been successful, the flag
-.Dv IFF_POLLING
-is marked or cleared in the interface's
-.Va if_flags
-to indicate the current mode of the interface.
+The actual mode change is managed by the driver-specific
+.Fn if_ioctl
+routine.
+The
+.Xr polling
+handler returns the number of packets processed.
 .Ss The Vt if_data Ss Structure
 The
 .Vt if_data
@@ -772,18 +893,6 @@
 sufficient space to prepend a link-layer header without allocating an
 additional
 .Vt mbuf .
-.\" (See
-.\" .Xr mbuf 9 . )
-.\" .It Va ifi_recvquota
-.\" .Pq Vt u_char
-.\" Number of packets the interface is permitted to receive at one time
-.\" when in polled mode.
-.\" .It Va ifi_xmitquota
-.\" .Pq Vt u_char
-.\" Number of packets the interface is permitted to queue for transmission
-.\" at one time when in polled mode.
-.\" There is some controversy over
-.\" whether such a restriction makes any sense at all.
 .It Va ifi_datalen
 .Pq Vt u_char
 Length of the
@@ -864,18 +973,6 @@
 Rarely implemented.
 .It Va ifi_noproto
 Number of packets received for unknown network-layer protocol.
-.\" .It Va ifi_recvtiming
-.\" Amount of time, in microseconds, spent to receive an average packet on
-.\" this interface.
-.\" See the
-.\" .Sx Polling
-.\" section, below.
-.\" .It Va ifi_xmittiming
-.\" Amount of time, in microseconds, spent to service a transmit-complete
-.\" interrupt on this interface.
-.\" See the
-.\" .Sx Polling
-.\" section, below.
 .It Va ifi_lastchange
 .Pq Vt "struct timeval"
 The time of the last administrative change to the interface (as required
@@ -918,6 +1015,8 @@
 .Pq Dq Tn PLIP
 .It Dv IFT_ATM
 Asynchronous Transfer Mode
+.It Dv IFT_USB
+USB Interface
 .El
 .Ss Interface Link States
 The following link states are currently defined:
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/kproc.9
--- a/head/share/man/man9/kproc.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/kproc.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/kproc.9 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd October 19, 2007
 .Dt KPROC 9
@@ -77,8 +77,8 @@
 .Fn kthread_* 9
 functions was added to produce
 .Em real
-kernel=20
-.Em threads .=20
+kernel
+.Em threads .
 See the
 .Xr kthread 9
 man page for more information on those calls.
@@ -227,7 +227,7 @@
 .Pp
 The
 .Fn kproc_kthread_add
-function is much like the=20
+function is much like the
 .Fn kproc_create
 function above except that if the kproc already exists,
 then only a new thread (see
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/kqueue.9
--- a/head/share/man/man9/kqueue.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/kqueue.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,16 +22,16 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/kqueue.9 232157 2012-02-25 14:31:25Z gjb=
 $
+.\" $FreeBSD: head/share/man/man9/kqueue.9 233505 2012-03-26 09:34:17Z mel=
ifaro $
 .\"
-.Dd February 25, 2012
+.Dd March 26, 2012
 .Dt KQUEUE 9
 .Os
 .Sh NAME
 .Nm kqueue_add_filteropts , kqueue_del_filteropts ,
 .Nm kqfd_register ,
 .Nm knote_fdclose ,
-.Nm knlist_init , knlist_init_mtx ,
+.Nm knlist_init , knlist_init_mtx , knlist_init_rw_reader ,
 .Nm knlist_add , knlist_remove , knlist_remove_inevent , knlist_empty ,
 .Nm knlist_clear , knlist_delete , knlist_destroy ,
 .Nm KNOTE_LOCKED , KNOTE_UNLOCKED
@@ -57,6 +57,8 @@
 .Ft void
 .Fn knlist_init_mtx "struct knlist *knl" "struct mtx *lock"
 .Ft void
+.Fn knlist_init_rw_reader "struct knlist *knl" "struct rwlock *lock"
+.Ft void
 .Fn knlist_add "struct knlist *knl" "struct knote *kn" "int islocked"
 .Ft void
 .Fn knlist_remove "struct knlist *knl" "struct knote *kn" "int islocked"
@@ -259,8 +261,10 @@
 .Vt knlist
 must be initialized with either
 .Fn knlist_init
+,
+.Fn knlist_init_mtx
 or
-.Fn knlist_init_mtx .
+.Fn knlist_init_rw_reader .
 The
 .Vt knlist
 structure may be embedded into the object structure.
@@ -305,6 +309,19 @@
 lock.
 .Pp
 The function
+.Fn knlist_init_rw_reader
+may be used to initialize a
+.Vt knlist
+when
+.Fa lock
+is a
+.Xr rwlock 9
+read lock.
+Lock is acquired via
+.Fn rw_rlock
+function.
+.Pp
+The function
 .Fn knlist_empty
 returns true when there are no
 .Vt knotes
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/kthread.9
--- a/head/share/man/man9/kthread.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/kthread.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/kthread.9 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd January 24, 2010
 .Dt KTHREAD 9
@@ -82,7 +82,7 @@
 See the
 .Xr kproc 9
 man page for more information on the renamed calls.
-Also note that the=20
+Also note that the
 .Fn kproc_kthread_add 9
 function appears in both pages as its functionality is split.
 .Pp
@@ -184,11 +184,11 @@
 .Pp
 The
 .Fn kproc_kthread_add
-function is much like the=20
+function is much like the
 .Fn kthread_add
 function above except that if the kproc does not already
-exist, it is created.=20
-This function is better documented in the=20
+exist, it is created.
+This function is better documented in the
 .Xr kproc 9
 manual page.
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/lock.9
--- a/head/share/man/man9/lock.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/lock.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF=
 SUCH
 .\" DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/lock.9 227588 2011-11-16 21:51:17Z pjd $
+.\" $FreeBSD: head/share/man/man9/lock.9 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd November 16, 2011
 .Dt LOCK 9
@@ -299,7 +299,6 @@
 Assert that the current thread does not have a recursed lock on
 .Fa lkp .
 .El
-.Pp
 .Sh RETURN VALUES
 The
 .Fn lockmgr
@@ -364,7 +363,7 @@
 the
 .Fa ilk
 must be held prior to calling
-.Fn lockmgr=20
+.Fn lockmgr
 or
 .Fn lockmgr_rw ,
 and will be returned unlocked.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/locking.9
--- a/head/share/man/man9/locking.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/locking.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/locking.9 233681 2012-03-29 20:55:45Z jo=
el $
 .\"
 .Dd November 3, 2010
 .Dt LOCKING 9
@@ -82,7 +82,7 @@
 Reader/writer locks can be treated as mutexes (see above and
 .Xr mutex 9 )
 with shared/exclusive semantics.
-More specifically, regular mutexes can be=20
+More specifically, regular mutexes can be
 considered to be equivalent to a write-lock on an
 .Em rw_lock.
 The
@@ -94,7 +94,7 @@
 Another important property is that shared holders of
 .Em rw_lock
 can recurse, but exclusive locks are not allowed to recurse.
-This ability should not be used lightly and=20
+This ability should not be used lightly and
 .Em may go away.
 .Pp
 See
@@ -122,7 +122,7 @@
 They don't support priority propagation.
 They should be considered to be closely related to
 .Xr sleep 9 .
-In fact it could in some cases be=20
+In fact it could in some cases be
 considered a conditional sleep.
 .Pp
 See
@@ -235,7 +235,6 @@
 See
 .Xr sleep 9
 for details.
-.Pp
 .Ss Lockmanager locks
 Shared/exclusive locks, used mostly in
 .Xr VFS 9 ,
@@ -294,9 +293,7 @@
 The following table shows what you can and can not do while holding
 one of the synchronization primitives discussed:
 .Bl -column ".Ic xxxxxxxxxxxxxxxxxxx" ".Xr XXXXXXXXX" ".Xr XXXXXXX" ".Xr X=
XXXXXX" ".Xr XXXXXXX" ".Xr XXXXXX" -offset indent
-.It Xo
-.Em "You have: You want:" Ta spin mtx Ta mutex Ta sx Ta rwlock Ta rmlock T=
a sleep
-.Xc
+.It Em "You have: You want:" Ta spin mtx Ta mutex Ta sx Ta rwlock Ta rmloc=
k Ta sleep
 .It spin mtx  Ta \&ok-1 Ta \&no Ta \&no Ta \&no Ta \&no Ta \&no-3
 .It mutex     Ta \&ok Ta \&ok-1 Ta \&no Ta \&ok Ta \&ok Ta \&no-3
 .It sx        Ta \&ok Ta \&ok Ta \&ok-2 Ta \&ok Ta \&ok Ta \&ok-4
@@ -337,13 +334,11 @@
 The next table shows what can be used in different contexts.
 At this time this is a rather easy to remember table.
 .Bl -column ".Ic Xxxxxxxxxxxxxxxxxxx" ".Xr XXXXXXXXX" ".Xr XXXXXXX" ".Xr X=
XXXXXX" ".Xr XXXXXXX" ".Xr XXXXXX" -offset indent
-.It Xo
-.Em "Context:"  Ta spin mtx Ta mutex Ta sx Ta rwlock Ta rmlock Ta sleep
-.Xc
-.It interrupt filter:  Ta \&ok Ta \&no Ta \&no Ta \&no Ta \&no Ta \&no=20
-.It interrupt thread:  Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&ok Ta \&no=20
-.It callout:    Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&no Ta \&no=20
-.It syscall:    Ta \&ok Ta \&ok Ta \&ok Ta \&ok Ta \&ok Ta \&ok=20
+.It Em "Context:"  Ta spin mtx Ta mutex Ta sx Ta rwlock Ta rmlock Ta sleep
+.It interrupt filter:  Ta \&ok Ta \&no Ta \&no Ta \&no Ta \&no Ta \&no
+.It interrupt thread:  Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&ok Ta \&no
+.It callout:    Ta \&ok Ta \&ok Ta \&no Ta \&ok Ta \&no Ta \&no
+.It syscall:    Ta \&ok Ta \&ok Ta \&ok Ta \&ok Ta \&ok Ta \&ok
 .El
 .Sh SEE ALSO
 .Xr witness 4 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/make_dev.9
--- a/head/share/man/man9/make_dev.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/make_dev.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/make_dev.9 221490 2011-05-05 09:55:55Z a=
e $
+.\" $FreeBSD: head/share/man/man9/make_dev.9 233422 2012-03-24 13:37:57Z j=
oel $
 .\"
 .Dd May 3, 2011
 .Dt MAKE_DEV 9
@@ -369,7 +369,6 @@
 .Dv MAKEDEV_CHECKNAME
 flag was specified and the provided device name already exists.
 .El
-.Pp
 .Sh SEE ALSO
 .Xr devctl 4 ,
 .Xr devfs 5 ,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/malloc.9
--- a/head/share/man/man9/malloc.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/malloc.9	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
 .\" $NetBSD: malloc.9,v 1.3 1996/11/11 00:05:11 lukem Exp $
-.\" $FreeBSD: head/share/man/man9/malloc.9 230679 2012-01-28 23:30:39Z kma=
cy $
+.\" $FreeBSD: head/share/man/man9/malloc.9 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd January 28, 2012
 .Dt MALLOC 9
@@ -124,7 +124,7 @@
 .It Dv M_ZERO
 Causes the allocated memory to be set to all zeros.
 .It Dv M_NODUMP
-For allocations greater than page size, causes the allocated=20
+For allocations greater than page size, causes the allocated
 memory to be excluded from kernel core dumps.
 .It Dv M_NOWAIT
 Causes
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/mi_switch.9
--- a/head/share/man/man9/mi_switch.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/mi_switch.9	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/mi_switch.9 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd November 24, 1996
 .Dt MI_SWITCH 9
@@ -62,7 +62,7 @@
 .Xr cv_wait 9 ,
 .Xr mtx_lock ,
 or
-.Xr tsleep 9=20
+.Xr tsleep 9
 when the current thread
 voluntarily relinquishes the CPU to wait for some resource or lock to beco=
me
 available.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/osd.9
--- a/head/share/man/man9/osd.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/osd.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/osd.9 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd January 5, 2011
 .Dt OSD 9
@@ -125,7 +125,7 @@
 .Ss Functions
 The
 .Fn osd_register
-function registers a type/slot identifier pair with the=20
+function registers a type/slot identifier pair with the
 .Nm
 framework for use with a new data type.
 The function may sleep and therefore cannot be called from a non-sleepable
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/rmlock.9
--- a/head/share/man/man9/rmlock.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/rmlock.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/rmlock.9 227588 2011-11-16 21:51:17Z pjd=
 $
+.\" $FreeBSD: head/share/man/man9/rmlock.9 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .\" Based on rwlock.9 man page
 .Dd November 16, 2011
@@ -80,7 +80,7 @@
 used as reader locks and as such should be used for protecting data that
 rarely changes.
 Acquiring an exclusive lock after the lock had been locked for shared acce=
ss
-is an expensive operation.=20
+is an expensive operation.
 .Pp
 Although reader/writer locks look very similar to
 .Xr sx 9
@@ -196,9 +196,9 @@
 .Fn rm_rlock .
 The
 .Fa tracker
-argument must match the=20
-.Fa tracker=20
-argument used for acquiring the shared lock=20
+argument must match the
+.Fa tracker
+argument used for acquiring the shared lock
 .It Fn rm_wunlock "struct rmlock *rm"
 This function releases an exclusive lock previously acquired by
 .Fn rm_wlock .
@@ -248,7 +248,7 @@
 implementation uses a single per CPU list shared by all
 rmlocks in the system.
 If rmlocks become popular, hashing to multiple per CPU queues may
-be needed to speed up the writer lock process.=20
+be needed to speed up the writer lock process.
 .Pp
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/shm_map.9
--- a/head/share/man/man9/shm_map.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/shm_map.9	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/shm_map.9 228620 2011-12-17 06:57:35Z ru=
 $
+.\" $FreeBSD: head/share/man/man9/shm_map.9 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd December 14, 2011
 .Dt SHM_MAP 9
@@ -125,7 +125,7 @@
 		fdrop(fp, curthread);
 		return (error);
 	}
-=09
+
 	/* Do something with 'mem'. */
=20
 	error =3D shm_unmap(fp, mem, 16384);
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/sleep.9
--- a/head/share/man/man9/sleep.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/sleep.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/sleep.9 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd December 12, 2009
 .Dt SLEEP 9
@@ -93,7 +93,7 @@
 runnable with the specified
 .Fa priority
 when it resumes.
-.Dv PZERO=20
+.Dv PZERO
 should never be used, as it is for compatibility only.
 A new priority of 0 means to use the thread's current priority when
 it is made runnable again.
@@ -243,7 +243,7 @@
 value.
 The older
 .Fn wakeup
-function did not require this, though it was never good practice=20
+function did not require this, though it was never good practice
 for threads to share a
 .Fa chan
 value.
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/spl.9
--- a/head/share/man/man9/spl.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/spl.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/spl.9 233648 2012-03-29 05:02:12Z eadler=
 $
 .\"
 .Dd July 21, 1996
 .Dt SPL 9
@@ -80,8 +80,8 @@
 kernel prior to
 .Fx 5.0 .
 The examples in this man page are also obsolete and should not be viewed
-as documenting=20
-.Fx 5.0=20
+as documenting
+.Fx 5.0
 and newer.
 .Ef
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/swi.9
--- a/head/share/man/man9/swi.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/swi.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,9 +22,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/swi.9 234188 2012-04-12 16:02:45Z plukne=
t $
 .\"
-.Dd October 30, 2000
+.Dd April 12, 2012
 .Dt SWI 9
 .Os
 .Sh NAME
@@ -42,7 +42,7 @@
 .Vt "extern void *vm_ih" ;
 .Ft int
 .Fo swi_add
-.Fa "struct ithd **ithdp"
+.Fa "struct intr_event **eventp"
 .Fa "const char *name"
 .Fa "driver_intr_t handler"
 .Fa "void *arg"
@@ -67,20 +67,21 @@
 .Pp
 The
 .Fn swi_add
-function is used to register a new software interrupt handler.
+function is used to add a new software interrupt handler to a specified
+interrupt event.
 The
-.Fa ithdp
+.Fa eventp
 argument is an optional pointer to a
-.Vt struct ithd
+.Vt struct intr_event
 pointer.
-If this argument points to an existing software interrupt thread, then this
-handler will be attached to that thread.
-Otherwise a new thread will be created, and if
-.Fa ithdp
+If this argument points to an existing event that holds a list of
+interrupt handlers, then this handler will be attached to that event.
+Otherwise a new event will be created, and if
+.Fa eventp
 is not
 .Dv NULL ,
 then the pointer at that address to will be modified to point to the
-newly created thread.
+newly created event.
 The
 .Fa name
 argument is used to associate a name with a specific handler.
@@ -99,7 +100,7 @@
 .Fa pri
 value specifies the priority of this interrupt handler relative to other
 software interrupt handlers.
-If an interrupt thread is created, then this value is used as the vector,
+If an interrupt event is created, then this value is used as the vector,
 and the
 .Fa flags
 argument is used to specify the attributes of a handler such as
@@ -183,7 +184,7 @@
 .Dv INTR_ENTROPY .
 .It Bq Er EINVAL
 The
-.Fa ithdp
+.Fa eventp
 argument points to a hardware interrupt thread.
 .It Bq Er EINVAL
 Either of the
@@ -195,9 +196,9 @@
 .It Bq Er EINVAL
 The
 .Dv INTR_EXCL
-flag is specified and the interrupt thread pointed to by
-.Fa ithdp
-already has at least one handler, or the interrupt thread already has an
+flag is specified and the interrupt event pointed to by
+.Fa eventp
+already has at least one handler, or the interrupt event already has an
 exclusive handler.
 .El
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/sysctl_ctx_init.9
--- a/head/share/man/man9/sysctl_ctx_init.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/sysctl_ctx_init.9	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/sysctl_ctx_init.9 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd July 15, 2000
 .Dt SYSCTL_CTX_INIT 9
@@ -135,7 +135,7 @@
 as the oid number when creating an oid.
 However, during registration of the oid in the tree,
 this number is changed to the first available number
-greater than or equal to=20
+greater than or equal to
 .Dv CTL_AUTO_START .
 If the first step of context deletion fails,
 re-registration of the oid does not change the already assigned oid number
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/taskqueue.9
--- a/head/share/man/man9/taskqueue.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/taskqueue.9	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man9/taskqueue.9 228715 2011-12-19 18:55:13Z =
jhb $
+.\" $FreeBSD: head/share/man/man9/taskqueue.9 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd April 26, 2011
 .Dt TASKQUEUE 9
@@ -116,8 +116,8 @@
 The memory location where the thread identity is recorded is used
 to signal the service thread(s) to terminate--when this value is set to
 zero and the thread is signaled it will terminate.
-If the queue is intended for use in fast interrupt handlers=20
-.Fn taskqueue_create_fast=20
+If the queue is intended for use in fast interrupt handlers
+.Fn taskqueue_create_fast
 should be used in place of
 .Fn taskqueue_create .
 .Pp
@@ -296,9 +296,9 @@
 is used to enqueue tasks onto the queue.
 .Pp
 .Fn TASKQUEUE_FAST_DEFINE
-and=20
+and
 .Fn TASKQUEUE_FAST_DEFINE_THREAD
-act just like=20
+act just like
 .Fn TASKQUEUE_DEFINE
 and
 .Fn TASKQUEUE_DEFINE_THREAD
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/timeout.9
--- a/head/share/man/man9/timeout.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/timeout.9	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/timeout.9 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd August 2, 2008
 .Dt TIMEOUT 9
@@ -197,9 +197,9 @@
 initializes a callout so it can be passed to
 .Fn callout_stop ,
 .Fn callout_drain ,
-.Fn callout_reset=20
+.Fn callout_reset
 or
-.Fn callout_schedule=20
+.Fn callout_schedule
 without any side effects.
 If the
 .Fa mpsafe
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/usbdi.9
--- a/head/share/man/man9/usbdi.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/usbdi.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\"	$FreeBSD$
+.\"	$FreeBSD: head/share/man/man9/usbdi.9 233648 2012-03-29 05:02:12Z eadl=
er $
 .Dd June 24, 2009
 .Dt USBDI 9
 .Os
@@ -179,7 +179,7 @@
 .
 .Fn usbd_transfer_unsetup
 This function will release the given USB transfers and all allocated
-resources associated with these USB transfers.=20
+resources associated with these USB transfers.
 .Fa pxfer
 is a pointer to an array of USB transfer pointers, that may be NULL,
 that should be freed by the USB system.
@@ -283,15 +283,15 @@
 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
=20
 	switch (USB_GET_STATE(xfer)) {
-	case USB_ST_SETUP:=20
+	case USB_ST_SETUP:
 		/*
 		 * Setup xfer frame lengths/count and data
 		 */
 		usbd_transfer_submit(xfer);
 		break;
=20
-	case USB_ST_TRANSFERRED:=20
-		/*=20
+	case USB_ST_TRANSFERRED:
+		/*
 		 * Read	usb frame data, if any.
 		 * "actlen" has the total length for all frames
 		 * transferred.
@@ -300,13 +300,13 @@
=20
 	default: /* Error */
 		/*
-		 * Print error message and clear stall=20
+		 * Print error message and clear stall
 		 * for example.
 		 */
 		break;
 	}
-	/*=20
-	 * Here it is safe to do something without the private=20
+	/*
+	 * Here it is safe to do something without the private
 	 * USB mutex locked.
 	 */
 	return;
@@ -320,7 +320,7 @@
 packet.
 .
 The SETUP packet is always pointed to by frame 0 and the
-length is set by=20
+length is set by
 .Fn usbd_xfer_frame_len
 also if there should not be
 sent any SETUP packet! If an USB control transfer has no DATA stage,
@@ -375,7 +375,7 @@
 the characteristics of the wanted endpoint.
 .Bd -literal -offset indent
=20
-struct usb_config {=20
+struct usb_config {
 	bufsize,
 	callback
 	direction,
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/vm_map_find.9
--- a/head/share/man/man9/vm_map_find.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/vm_map_find.9	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/vm_map_find.9 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd May 10, 2008
 .Dt VM_MAP_FIND 9
@@ -71,7 +71,7 @@
 If
 .Fa find_space
 is either
-.Dv VMFS_ALIGNED_SPACE=20
+.Dv VMFS_ALIGNED_SPACE
 or
 .Dv VMFS_ANY_SPACE ,
 the function will call
diff -r 428842767fa6 -r f2935497fa04 head/share/man/man9/watchdog.9
--- a/head/share/man/man9/watchdog.9	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/man/man9/watchdog.9	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man9/watchdog.9 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd February 28, 2004
 .Dt WATCHDOG 9
@@ -53,7 +53,7 @@
 argument left untouched.
 If the watchdog cannot be disabled, the
 .Fa error
-argument must be set to=20
+argument must be set to
 .Dv EOPNOTSUPP .
 .Pp
 Else the watchdog should be reset and configured to a timeout of
diff -r 428842767fa6 -r f2935497fa04 head/share/misc/committers-ports.dot
--- a/head/share/misc/committers-ports.dot	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/misc/committers-ports.dot	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/misc/committers-ports.dot 232357 2012-03-01 20:03:4=
4Z ak $
+# $FreeBSD: head/share/misc/committers-ports.dot 234343 2012-04-16 15:08:0=
1Z sperber $
=20
 # This file is meant to list all FreeBSD ports committers and describe the
 # mentor-mentee relationships between them.
@@ -128,6 +128,7 @@
 lth [label=3D"Lars Thegler\nlth at FreeBSD.org\n2004/05/04"]
 lwhsu [label=3D"Li-Wen Hsu\nlwhsu at FreeBSD.org\n2007/04/03"]
 lx [label=3D"David Thiel\nlx at FreeBSD.org\n2006/11/29"]
+madpilot [label=3D"Guido Falsi\nmadpilot at FreeBSD.org\n2012/04/12"]
 maho [label=3D"Maho Nakata\nmaho at FreeBSD.org\n2002/10/17"]
 makc [label=3D"Max Brazhnikov\nmakc at FreeBSD.org\n2008/08/25"]
 mandree [label=3D"Matthias Andree\nmandree at FreeBSD.org\n2009/11/18"]
@@ -172,6 +173,7 @@
 simon [label=3D"Simon L. Nielsen\nsimon at FreeBSD.org\n2005/01/08"]
 skreuzer [label=3D"Steven Kreuzer\nskreuzer at FreeBSD.org\n2009/03/25"]
 sobomax[label=3D"Maxim Sobolev\nsobomax at FreeBSD.org\n2000/05/17"]
+sperber[label=3D"Armin Pirkovitsch\nsperber at FreeBSD.org\n2012/04/15"]
 stas [label=3D"Stanislav Sedov\nstas at FreeBSD.org\n2006/09/18"]
 stefan [label=3D"Stefan Walter\nstefan at FreeBSD.org\n2006/05/07"]
 stephen [label=3D"Stephen Montgomery-Smith\nstephen at FreeBSD.org\n2011/06/1=
3"]
@@ -223,6 +225,7 @@
 bapt -> jlaffaye
=20
 beat -> decke
+beat -> sperber
 beat -> uqs
=20
 beech -> glarkin
@@ -240,6 +243,9 @@
 clsung -> tabthorpe
=20
 crees -> jgh
+crees -> madpilot
+
+decke -> sperber
=20
 delphij -> nemoliu
 delphij -> rafan
@@ -368,6 +374,7 @@
 miwi -> pawel
 miwi -> rm
 miwi -> sbz
+miwi -> sperber
 miwi -> sylvio
 miwi -> tabthorpe
 miwi -> trasz
@@ -440,6 +447,7 @@
 tabthorpe -> jacula
 tabthorpe -> jadawin
 tabthorpe -> jlaffaye
+tabthorpe -> madpilot
 tabthorpe -> pgj
 tabthorpe -> rene
 tabthorpe -> zi
diff -r 428842767fa6 -r f2935497fa04 head/share/misc/committers-src.dot
--- a/head/share/misc/committers-src.dot	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/misc/committers-src.dot	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/misc/committers-src.dot 230876 2012-02-01 19:46:12Z=
 davide $
+# $FreeBSD: head/share/misc/committers-src.dot 234236 2012-04-13 20:58:01Z=
 jasone $
=20
 # This file is meant to list all FreeBSD src committers and describe the
 # mentor-mentee relationships between them.
@@ -156,6 +156,7 @@
 imp [label=3D"Warner Losh\nimp at FreeBSD.org\n1996/09/20"]
 ivoras [label=3D"Ivan Voras\nivoras at FreeBSD.org\n2008/06/10"]
 jamie [label=3D"Jamie Gritton\njamie at FreeBSD.org\n2009/01/28"]
+jasone [label=3D"Jason Evans\njasone at FreeBSD.org\n1999/03/03"]
 jceel [label=3D"Jakub Klama\njceel at FreeBSD.org\n2011/09/25"]
 jchandra [label=3D"Jayachandran C.\njchandra at FreeBSD.org\n2010/05/19"]
 jeff [label=3D"Jeff Roberson\njeff at FreeBSD.org\n2002/02/21"]
@@ -195,6 +196,7 @@
 melifaro [label=3D"Alexander V. Chernikov\nmelifaro at FreeBSD.org\n2011/10/0=
4"]
 mjacob [label=3D"Matt Jacob\nmjacob at FreeBSD.org\n1997/08/13"]
 mlaier [label=3D"Max Laier\nmlaier at FreeBSD.org\n2004/02/10"]
+monthadar [label=3D"Monthadar Al Jaberi\nmonthadar at FreeBSD.org\n2012/04/02=
"]
 mr [label=3D"Michael Reifenberger\nmr at FreeBSD.org\n2001/09/30"]
 mux [label=3D"Maxime Henrion\nmux at FreeBSD.org\n2002/03/03"]
 neel [label=3D"Neel Natu\nneel at FreeBSD.org\n2009/09/20"]
@@ -280,6 +282,7 @@
 day1 -> alm
 day1 -> dg
=20
+adrian -> monthadar
 adrian -> ray
 adrian -> rmh
=20
@@ -476,6 +479,7 @@
 marcel -> marius
 marcel -> nwhitehorn
=20
+markm -> jasone
 markm -> sheldonh
=20
 mav -> ae
@@ -492,6 +496,7 @@
 mlaier -> eri
=20
 msmith -> cokane
+msmith -> jasone
 msmith -> scottl
=20
 murray -> delphij
diff -r 428842767fa6 -r f2935497fa04 head/share/mk/bsd.endian.mk
--- a/head/share/mk/bsd.endian.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/mk/bsd.endian.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/share/mk/bsd.endian.mk 233644 2012-03-29 02:54:35Z jmalle=
tt $
=20
 .if ${MACHINE_ARCH} =3D=3D "amd64" || \
     ${MACHINE_ARCH} =3D=3D "i386" || \
@@ -10,6 +10,6 @@
     ${MACHINE_ARCH} =3D=3D "powerpc64" || \
     ${MACHINE_ARCH} =3D=3D "sparc64" || \
     ${MACHINE_ARCH} =3D=3D "armeb" || \
-    ${MACHINE_ARCH:Mmips*eb} !=3D ""
+    ${MACHINE_ARCH:Mmips*} !=3D ""
 TARGET_ENDIANNESS=3D 4321
 .endif
diff -r 428842767fa6 -r f2935497fa04 head/share/mk/bsd.libnames.mk
--- a/head/share/mk/bsd.libnames.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/mk/bsd.libnames.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/mk/bsd.libnames.mk 227983 2011-11-25 20:59:04Z ther=
aven $
+# $FreeBSD: head/share/mk/bsd.libnames.mk 233294 2012-03-22 08:48:42Z stas=
 $
=20
 # The include file <bsd.libnames.mk> define library names.
 # Other include files (e.g. bsd.prog.mk, bsd.lib.mk) include this
@@ -60,7 +60,9 @@
 LIBGSSAPI_KRB5?=3D ${DESTDIR}${LIBDIR}/libgssapi_krb5.a
 LIBHDB?=3D	${DESTDIR}${LIBDIR}/libhdb.a
 LIBHISTORY?=3D	${DESTDIR}${LIBDIR}/libhistory.a
+LIBHEIMBASE?=3D	${DESTDIR}${LIBDIR}/libheimbase.a
 LIBHEIMNTLM?=3D	${DESTDIR}${LIBDIR}/libheimntlm.a
+LIBHEIMSQLITE?=3D	${DESTDIR}${LIBDIR}/libheimsqlite.a
 LIBHX509?=3D	${DESTDIR}${LIBDIR}/libhx509.a
 LIBIPSEC?=3D	${DESTDIR}${LIBDIR}/libipsec.a
 .if ${MK_IPX} !=3D "no"
@@ -75,6 +77,7 @@
 LIBKADM5CLNT?=3D	${DESTDIR}${LIBDIR}/libkadm5clnt.a
 LIBKADM5SRV?=3D	${DESTDIR}${LIBDIR}/libkadm5srv.a
 LIBKAFS5?=3D	${DESTDIR}${LIBDIR}/libkafs5.a
+LIBKDC?=3D	${DESTDIR}${LIBDIR}/libkdc.a
 LIBKEYCAP?=3D	${DESTDIR}${LIBDIR}/libkeycap.a
 LIBKICONV?=3D	${DESTDIR}${LIBDIR}/libkiconv.a
 LIBKRB5?=3D	${DESTDIR}${LIBDIR}/libkrb5.a
@@ -160,6 +163,7 @@
 LIBUTIL?=3D	${DESTDIR}${LIBDIR}/libutil.a
 LIBUUTIL?=3D	${DESTDIR}${LIBDIR}/libuutil.a
 LIBVGL?=3D	${DESTDIR}${LIBDIR}/libvgl.a
+LIBWIND?=3D	${DESTDIR}${LIBDIR}/libwind.a
 LIBWRAP?=3D	${DESTDIR}${LIBDIR}/libwrap.a
 LIBXPG4?=3D	${DESTDIR}${LIBDIR}/libxpg4.a
 LIBY?=3D		${DESTDIR}${LIBDIR}/liby.a
diff -r 428842767fa6 -r f2935497fa04 head/share/mk/bsd.sys.mk
--- a/head/share/mk/bsd.sys.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/mk/bsd.sys.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/mk/bsd.sys.mk 233052 2012-03-16 23:19:45Z dim $
+# $FreeBSD: head/share/mk/bsd.sys.mk 234353 2012-04-16 21:23:25Z dim $
 #
 # This file contains common settings used for building FreeBSD
 # sources.
@@ -62,12 +62,15 @@
 # Clang has more warnings enabled by default, and when using -Wall, so if =
WARNS
 # is set to low values, these have to be disabled explicitly.
 .if ${MK_CLANG_IS_CC} !=3D "no" || ${CC:T:Mclang} =3D=3D "clang"
+.if ${WARNS} <=3D 6
+CWARNFLAGS+=3D	-Wno-empty-body -Wno-string-plus-int
+.endif # WARNS <=3D 6
 .if ${WARNS} <=3D 3
 CWARNFLAGS+=3D	-Wno-tautological-compare -Wno-unused-value\
 		-Wno-parentheses-equality -Wno-unused-function -Wno-conversion
 .endif # WARNS <=3D 3
 .if ${WARNS} <=3D 2
-CWARNFLAGS+=3D	-Wno-switch-enum -Wno-empty-body
+CWARNFLAGS+=3D	-Wno-switch -Wno-switch-enum
 .endif # WARNS <=3D 2
 .if ${WARNS} <=3D 1
 CWARNFLAGS+=3D	-Wno-parentheses
@@ -85,6 +88,11 @@
 .if ${WFORMAT} > 0
 #CWARNFLAGS+=3D	-Wformat-nonliteral -Wformat-security -Wno-format-extra-ar=
gs
 CWARNFLAGS+=3D	-Wformat=3D2 -Wno-format-extra-args
+.if ${MK_CLANG_IS_CC} !=3D "no" || ${CC:T:Mclang} =3D=3D "clang"
+.if ${WARNS} <=3D 3
+CWARNFLAGS+=3D	-Wno-format-nonliteral
+.endif # WARNS <=3D 3
+.endif # CLANG
 .if !defined(NO_WERROR) && ((${MK_CLANG_IS_CC} =3D=3D "no" && \
     ${CC:T:Mclang} !=3D "clang") || !defined(NO_WERROR.clang))
 CWARNFLAGS+=3D	-Werror
@@ -103,8 +111,9 @@
=20
 .if ${MK_CLANG_IS_CC} !=3D "no" || ${CC:T:Mclang} =3D=3D "clang"
 CLANG_NO_IAS=3D	 -no-integrated-as
-CLANG_OPT_SMALL=3D -mllvm -stack-alignment=3D8 -mllvm -inline-threshold=3D=
3\
+CLANG_OPT_SMALL=3D -mstack-alignment=3D8 -mllvm -inline-threshold=3D3\
 		 -mllvm -enable-load-pre=3Dfalse -mllvm -simplifycfg-dup-ret
+CFLAGS+=3D	 -Qunused-arguments
 .endif # CLANG
=20
 .if ${MK_SSP} !=3D "no" && ${MACHINE_CPUARCH} !=3D "ia64" && \
diff -r 428842767fa6 -r f2935497fa04 head/share/mk/sys.mk
--- a/head/share/mk/sys.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/mk/sys.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	from: @(#)sys.mk	8.2 (Berkeley) 3/21/94
-# $FreeBSD: head/share/mk/sys.mk 228137 2011-11-29 16:34:44Z fjoe $
+# $FreeBSD: head/share/mk/sys.mk 233644 2012-03-29 02:54:35Z jmallett $
=20
 unix		?=3D	We run FreeBSD, not UNIX.
 .FreeBSD	?=3D	true
@@ -13,7 +13,7 @@
 # and/or endian.  This is called MACHINE_CPU in NetBSD, but that's used
 # for something different in FreeBSD.
 #
-MACHINE_CPUARCH=3D${MACHINE_ARCH:C/mips.*e[lb]/mips/:C/armeb/arm/:C/powerp=
c64/powerpc/}
+MACHINE_CPUARCH=3D${MACHINE_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/:C=
/powerpc64/powerpc/}
 .endif
=20
 # If the special target .POSIX appears (without prerequisites or
diff -r 428842767fa6 -r f2935497fa04 head/share/termcap/termcap.5
--- a/head/share/termcap/termcap.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/share/termcap/termcap.5	Tue Apr 17 11:51:51 2012 +0300
@@ -51,7 +51,7 @@
 .\" *                                                                     =
     *
 .\" **********************************************************************=
*****/
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/termcap/termcap.5 233459 2012-03-25 09:23:10Z joe=
l $
 .\"
 .Dd December 13, 2009
 .Dt TERMCAP 5
@@ -1157,7 +1157,6 @@
 .Sy \&cm ,
 such as the Tektronix 4025.
 .Ss Cursor Motions
-.Pp
 If the terminal has a fast way to home the cursor
 (to the very upper left corner of the screen), this can be given as
 .Sy \&ho .
diff -r 428842767fa6 -r f2935497fa04 head/sys/Makefile
--- a/head/sys/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/Makefile 229400 2012-01-03 17:31:27Z jhb $
+# $FreeBSD: head/sys/Makefile 233236 2012-03-20 18:05:15Z jhb $
=20
 .include <bsd.own.mk>
=20
@@ -11,7 +11,7 @@
 CSCOPEDIRS=3D	boot bsm cam cddl compat conf contrib crypto ddb dev fs gdb \
 		geom gnu isa kern libkern modules net net80211 netatalk \
 		netgraph netinet netinet6 netipsec netipx netnatm netncp \
-		netsmb nfs nfsclient nfsserver nlm opencrypto \
+		netsmb nfs nfsclient nfsserver nlm ofed opencrypto \
 		pci rpc security sys ufs vm xdr xen ${CSCOPE_ARCHDIR}
 .if !defined(CSCOPE_ARCHDIR)
 .if defined(ALL_ARCH)
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/acpica/acpi_wakeup.c
--- a/head/sys/amd64/acpica/acpi_wakeup.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/acpica/acpi_wakeup.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/acpica/acpi_wakeup.c 233208 2012-03-19 =
21:47:50Z jkim $");
+__FBSDID("$FreeBSD: head/sys/amd64/acpica/acpi_wakeup.c 233704 2012-03-30 =
17:03:06Z jkim $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -223,6 +223,7 @@
 #ifdef SMP
 	cpuset_t	wakeup_cpus;
 #endif
+	register_t	rf;
 	ACPI_STATUS	status;
 	int		ret;
=20
@@ -241,8 +242,8 @@
=20
 	AcpiSetFirmwareWakingVector(WAKECODE_PADDR(sc));
=20
+	rf =3D intr_disable();
 	intr_suspend();
-	spinlock_enter();
=20
 	if (savectx(susppcbs[0])) {
 		ctx_fpusave(suspfpusave[0]);
@@ -269,7 +270,7 @@
 		if (state =3D=3D ACPI_STATE_S4 && sc->acpi_s4bios)
 			status =3D AcpiEnterSleepStateS4bios();
 		else
-			status =3D AcpiEnterSleepState(state);
+			status =3D AcpiEnterSleepState(state, acpi_sleep_flags);
=20
 		if (status !=3D AE_OK) {
 			device_printf(sc->acpi_dev,
@@ -283,6 +284,7 @@
 	} else {
 		pmap_init_pat();
 		load_cr3(susppcbs[0]->pcb_cr3);
+		initializecpu();
 		PCPU_SET(switchtime, 0);
 		PCPU_SET(switchticks, ticks);
 #ifdef SMP
@@ -299,8 +301,8 @@
 #endif
=20
 	mca_resume();
-	spinlock_exit();
 	intr_resume();
+	intr_restore(rf);
=20
 	AcpiSetFirmwareWakingVector(0);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/amd64/identcpu.c
--- a/head/sys/amd64/amd64/identcpu.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/amd64/identcpu.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/amd64/identcpu.c 222043 2011-05-17 22:3=
6:16Z jkim $");
+__FBSDID("$FreeBSD: head/sys/amd64/amd64/identcpu.c 234059 2012-04-09 15:2=
0:16Z jhb $");
=20
 #include "opt_cpu.h"
=20
@@ -303,7 +303,7 @@
 				"\034OSXSAVE"	/* OS-Enabled State Management*/
 				"\035AVX"	/* Advanced Vector Extensions */
 				"\036F16C"	/* Half-precision conversions */
-				"\037<b30>"
+				"\037RDRAND"	/* RDRAND Instruction */
 				"\040HV"	/* Hypervisor */
 				);
 			}
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/amd64/initcpu.c
--- a/head/sys/amd64/amd64/initcpu.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/amd64/initcpu.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/amd64/initcpu.c 230426 2012-01-21 17:45=
:27Z kib $");
+__FBSDID("$FreeBSD: head/sys/amd64/amd64/initcpu.c 233702 2012-03-30 16:32=
:41Z jkim $");
=20
 #include "opt_cpu.h"
=20
@@ -79,6 +79,27 @@
 SYSCTL_UINT(_hw, OID_AUTO, via_feature_xcrypt, CTLFLAG_RD,
 	&via_feature_xcrypt, 0, "VIA xcrypt feature available in CPU");
=20
+static void
+init_amd(void)
+{
+
+	/*
+	 * Work around Erratum 721 for Family 10h and 12h processors.
+	 * These processors may incorrectly update the stack pointer
+	 * after a long series of push and/or near-call instructions,
+	 * or a long series of pop and/or near-return instructions.
+	 *
+	 * http://support.amd.com/us/Processor_TechDocs/41322_10h_Rev_Gd.pdf
+	 * http://support.amd.com/us/Processor_TechDocs/44739_12h_Rev_Gd.pdf
+	 */
+	switch (CPUID_TO_FAMILY(cpu_id)) {
+	case 0x10:
+	case 0x12:
+		wrmsr(0xc0011029, rdmsr(0xc0011029) | 1);
+		break;
+	}
+}
+
 /*
  * Initialize special VIA features
  */
@@ -135,8 +156,14 @@
 		wrmsr(MSR_EFER, msr);
 		pg_nx =3D PG_NX;
 	}
-	if (cpu_vendor_id =3D=3D CPU_VENDOR_CENTAUR)
+	switch (cpu_vendor_id) {
+	case CPU_VENDOR_AMD:
+		init_amd();
+		break;
+	case CPU_VENDOR_CENTAUR:
 		init_via();
+		break;
+	}
 }
=20
 void
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/amd64/machdep.c
--- a/head/sys/amd64/amd64/machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/amd64/machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/amd64/machdep.c 231781 2012-02-15 21:32=
:05Z jkim $");
+__FBSDID("$FreeBSD: head/sys/amd64/amd64/machdep.c 234105 2012-04-10 16:08=
:46Z marius $");
=20
 #include "opt_atalk.h"
 #include "opt_atpic.h"
@@ -295,6 +295,13 @@
 	vm_pager_bufferinit();
=20
 	cpu_setregs();
+
+#ifdef SMP
+	/*
+	 * Add BSP as an interrupt target.
+	 */
+	intr_add_cpu(0);
+#endif
 }
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/amd64/mp_machdep.c
--- a/head/sys/amd64/amd64/mp_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/amd64/mp_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/amd64/mp_machdep.c 231797 2012-02-15 23=
:33:22Z jkim $");
+__FBSDID("$FreeBSD: head/sys/amd64/amd64/mp_machdep.c 234208 2012-04-13 07=
:18:19Z avg $");
=20
 #include "opt_cpu.h"
 #include "opt_kstack_pages.h"
@@ -785,8 +785,6 @@
  * We tell the I/O APIC code about all the CPUs we want to receive
  * interrupts.  If we don't want certain CPUs to receive IRQs we
  * can simply not tell the I/O APIC code about them in this function.
- * We also do not tell it about the BSP since it tells itself about
- * the BSP internally to work with UP kernels and on UP machines.
  */
 static void
 set_interrupt_apic_ids(void)
@@ -797,8 +795,6 @@
 		apic_id =3D cpu_apic_ids[i];
 		if (apic_id =3D=3D -1)
 			continue;
-		if (cpu_info[apic_id].cpu_bsp)
-			continue;
 		if (cpu_info[apic_id].cpu_disabled)
 			continue;
=20
@@ -1425,6 +1421,7 @@
 	} else {
 		pmap_init_pat();
 		load_cr3(susppcbs[cpu]->pcb_cr3);
+		initializecpu();
 		PCPU_SET(switchtime, 0);
 		PCPU_SET(switchticks, ticks);
 	}
@@ -1474,6 +1471,8 @@
 		intrcnt_add(buf, &ipi_invlrng_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
 		intrcnt_add(buf, &ipi_invlpg_counts[i]);
+		snprintf(buf, sizeof(buf), "cpu%d:invlcache", i);
+		intrcnt_add(buf, &ipi_invlcache_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
 		intrcnt_add(buf, &ipi_preempt_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:ast", i);
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/amd64/pmap.c
--- a/head/sys/amd64/amd64/pmap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/amd64/pmap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -77,7 +77,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/amd64/pmap.c 233185 2012-03-19 15:50:14=
Z kib $");
+__FBSDID("$FreeBSD: head/sys/amd64/amd64/pmap.c 233954 2012-04-06 16:41:19=
Z alc $");
=20
 /*
  *	Manages physical address maps.
@@ -148,10 +148,6 @@
 #include <machine/smp.h>
 #endif
=20
-#ifndef PMAP_SHPGPERPROC
-#define PMAP_SHPGPERPROC 200
-#endif
-
 #if !defined(DIAGNOSTIC)
 #ifdef __GNUC_GNU_INLINE__
 #define PMAP_INLINE	__attribute__((__gnu_inline__)) inline
@@ -162,7 +158,6 @@
 #define PMAP_INLINE
 #endif
=20
-#define PV_STATS
 #ifdef PV_STATS
 #define PV_STAT(x)	do { x ; } while (0)
 #else
@@ -206,9 +201,8 @@
 /*
  * Data for the pv entry allocation mechanism
  */
-static int pv_entry_count =3D 0, pv_entry_max =3D 0, pv_entry_high_water =
=3D 0;
+static long pv_entry_count;
 static struct md_page *pv_table;
-static int shpgperproc =3D PMAP_SHPGPERPROC;
=20
 /*
  * All those kernel PT submaps that BSD is so fond of
@@ -222,7 +216,7 @@
 static caddr_t crashdumpmap;
=20
 static void	free_pv_entry(pmap_t pmap, pv_entry_t pv);
-static pv_entry_t get_pv_entry(pmap_t locked_pmap, int try);
+static pv_entry_t get_pv_entry(pmap_t locked_pmap, boolean_t try);
 static void	pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_=
t pa);
 static void	pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa=
);
@@ -731,16 +725,6 @@
 	}
=20
 	/*
-	 * Initialize the address space (zone) for the pv entries.  Set a
-	 * high water mark so that the system can recover from excessive
-	 * numbers of pv entries.
-	 */
-	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
-	pv_entry_max =3D shpgperproc * maxproc + cnt.v_page_count;
-	TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
-	pv_entry_high_water =3D 9 * (pv_entry_max / 10);
-
-	/*
 	 * If the kernel is running in a virtual machine on an AMD Family 10h
 	 * processor, then it must assume that MCA is enabled by the virtual
 	 * machine monitor.
@@ -775,36 +759,6 @@
 		TAILQ_INIT(&pv_table[i].pv_list);
 }
=20
-static int
-pmap_pventry_proc(SYSCTL_HANDLER_ARGS)
-{
-	int error;
-
-	error =3D sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
-	if (error =3D=3D 0 && req->newptr) {
-		shpgperproc =3D (pv_entry_max - cnt.v_page_count) / maxproc;
-		pv_entry_high_water =3D 9 * (pv_entry_max / 10);
-	}
-	return (error);
-}
-SYSCTL_PROC(_vm_pmap, OID_AUTO, pv_entry_max, CTLTYPE_INT|CTLFLAG_RW,=20
-    &pv_entry_max, 0, pmap_pventry_proc, "IU", "Max number of PV entries");
-
-static int
-pmap_shpgperproc_proc(SYSCTL_HANDLER_ARGS)
-{
-	int error;
-
-	error =3D sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
-	if (error =3D=3D 0 && req->newptr) {
-		pv_entry_max =3D shpgperproc * maxproc + cnt.v_page_count;
-		pv_entry_high_water =3D 9 * (pv_entry_max / 10);
-	}
-	return (error);
-}
-SYSCTL_PROC(_vm_pmap, OID_AUTO, shpgperproc, CTLTYPE_INT|CTLFLAG_RW,=20
-    &shpgperproc, 0, pmap_shpgperproc_proc, "IU", "Page share factor per p=
roc");
-
 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
     "2MB page mapping counters");
=20
@@ -2050,7 +2004,7 @@
=20
 static uint64_t pc_freemask[_NPCM] =3D { PC_FREE0, PC_FREE1, PC_FREE2 };
=20
-SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count=
, 0,
+SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_coun=
t, 0,
 	"Current number of pv entries");
=20
 #ifdef PV_STATS
@@ -2141,7 +2095,6 @@
 	}
 }
=20
-
 /*
  * free the pv_entry back to the free list
  */
@@ -2162,13 +2115,16 @@
 	field =3D idx / 64;
 	bit =3D idx % 64;
 	pc->pc_map[field] |=3D 1ul << bit;
-	/* move to head of list */
-	TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 	if (pc->pc_map[0] !=3D PC_FREE0 || pc->pc_map[1] !=3D PC_FREE1 ||
 	    pc->pc_map[2] !=3D PC_FREE2) {
-		TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
+		/* 98% of the time, pc is already at the head of the list. */
+		if (__predict_false(pc !=3D TAILQ_FIRST(&pmap->pm_pvchunk))) {
+			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
+			TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
+		}
 		return;
 	}
+	TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 	PV_STAT(pv_entry_spare -=3D _NPCPV);
 	PV_STAT(pc_chunk_count--);
 	PV_STAT(pc_chunk_frees++);
@@ -2184,10 +2140,8 @@
  * when needed.
  */
 static pv_entry_t
-get_pv_entry(pmap_t pmap, int try)
+get_pv_entry(pmap_t pmap, boolean_t try)
 {
-	static const struct timeval printinterval =3D { 60, 0 };
-	static struct timeval lastprint;
 	struct vpgqueues *pq;
 	int bit, field;
 	pv_entry_t pv;
@@ -2197,12 +2151,6 @@
 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 	PV_STAT(pv_entry_allocs++);
-	pv_entry_count++;
-	if (pv_entry_count > pv_entry_high_water)
-		if (ratecheck(&lastprint, &printinterval))
-			printf("Approaching the limit on PV entries, consider "
-			    "increasing either the vm.pmap.shpgperproc or the "
-			    "vm.pmap.pv_entry_max sysctl.\n");
 	pq =3D NULL;
 retry:
 	pc =3D TAILQ_FIRST(&pmap->pm_pvchunk);
@@ -2220,8 +2168,10 @@
 			if (pc->pc_map[0] =3D=3D 0 && pc->pc_map[1] =3D=3D 0 &&
 			    pc->pc_map[2] =3D=3D 0) {
 				TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
-				TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
+				TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
+				    pc_list);
 			}
+			pv_entry_count++;
 			PV_STAT(pv_entry_spare--);
 			return (pv);
 		}
@@ -2232,7 +2182,6 @@
 	    VM_ALLOC_WIRED);
 	if (m =3D=3D NULL) {
 		if (try) {
-			pv_entry_count--;
 			PV_STAT(pc_chunk_tryfail++);
 			return (NULL);
 		}
@@ -2248,7 +2197,7 @@
 			PV_STAT(pmap_collect_active++);
 			pq =3D &vm_page_queues[PQ_ACTIVE];
 		} else
-			panic("get_pv_entry: increase vm.pmap.shpgperproc");
+			panic("get_pv_entry: allocation failed");
 		pmap_collect(pmap, pq);
 		goto retry;
 	}
@@ -2262,6 +2211,7 @@
 	pc->pc_map[2] =3D PC_FREE2;
 	pv =3D &pc->pc_pventry[0];
 	TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
+	pv_entry_count++;
 	PV_STAT(pv_entry_spare +=3D _NPCPV - 1);
 	return (pv);
 }
@@ -2419,8 +2369,7 @@
=20
 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
-	if (pv_entry_count < pv_entry_high_water &&=20
-	    (pv =3D get_pv_entry(pmap, TRUE)) !=3D NULL) {
+	if ((pv =3D get_pv_entry(pmap, TRUE)) !=3D NULL) {
 		pv->pv_va =3D va;
 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
 		return (TRUE);
@@ -2438,8 +2387,7 @@
 	pv_entry_t pv;
=20
 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
-	if (pv_entry_count < pv_entry_high_water &&=20
-	    (pv =3D get_pv_entry(pmap, TRUE)) !=3D NULL) {
+	if ((pv =3D get_pv_entry(pmap, TRUE)) !=3D NULL) {
 		pv->pv_va =3D va;
 		pvh =3D pa_to_pvh(pa);
 		TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_list);
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/amd64/trap.c
--- a/head/sys/amd64/amd64/trap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/amd64/trap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -38,7 +38,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/amd64/trap.c 232842 2012-03-12 00:47:13=
Z alc $");
+__FBSDID("$FreeBSD: head/sys/amd64/amd64/trap.c 233781 2012-04-02 15:07:22=
Z jhb $");
=20
 /*
  * AMD64 Trap and System call handling
@@ -71,6 +71,9 @@
 #include <sys/vmmeter.h>
 #ifdef HWPMC_HOOKS
 #include <sys/pmckern.h>
+PMC_SOFT_DEFINE( , , page_fault, all);
+PMC_SOFT_DEFINE( , , page_fault, read);
+PMC_SOFT_DEFINE( , , page_fault, write);
 #endif
=20
 #include <vm/vm.h>
@@ -230,8 +233,7 @@
 #endif
=20
 	if (type =3D=3D T_MCHK) {
-		if (!mca_intr())
-			trap_fatal(frame, 0);
+		mca_intr();
 		goto out;
 	}
=20
@@ -301,26 +303,6 @@
 	}
=20
 	code =3D frame->tf_err;
-	if (type =3D=3D T_PAGEFLT) {
-		/*
-		 * If we get a page fault while in a critical section, then
-		 * it is most likely a fatal kernel page fault.  The kernel
-		 * is already going to panic trying to get a sleep lock to
-		 * do the VM lookup, so just consider it a fatal trap so the
-		 * kernel can print out a useful trap message and even get
-		 * to the debugger.
-		 *
-		 * If we get a page fault while holding a non-sleepable
-		 * lock, then it is most likely a fatal kernel page fault.
-		 * If WITNESS is enabled, then it's going to whine about
-		 * bogus LORs with various VM locks, so just skip to the
-		 * fatal trap handling directly.
-		 */
-		if (td->td_critnest !=3D 0 ||
-		    WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
-		    "Kernel page fault") !=3D 0)
-			trap_fatal(frame, frame->tf_addr);
-	}
=20
         if (ISPL(frame->tf_cs) =3D=3D SEL_UPL) {
 		/* user trap */
@@ -653,6 +635,50 @@
 	struct proc *p =3D td->td_proc;
 	vm_offset_t eva =3D frame->tf_addr;
=20
+	if (__predict_false((td->td_pflags & TDP_NOFAULTING) !=3D 0)) {
+		/*
+		 * Due to both processor errata and lazy TLB invalidation when
+		 * access restrictions are removed from virtual pages, memory
+		 * accesses that are allowed by the physical mapping layer may
+		 * nonetheless cause one spurious page fault per virtual page.=20
+		 * When the thread is executing a "no faulting" section that
+		 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
+		 * every page fault is treated as a spurious page fault,
+		 * unless it accesses the same virtual address as the most
+		 * recent page fault within the same "no faulting" section.
+		 */
+		if (td->td_md.md_spurflt_addr !=3D eva ||
+		    (td->td_pflags & TDP_RESETSPUR) !=3D 0) {
+			/*
+			 * Do nothing to the TLB.  A stale TLB entry is
+			 * flushed automatically by a page fault.
+			 */
+			td->td_md.md_spurflt_addr =3D eva;
+			td->td_pflags &=3D ~TDP_RESETSPUR;
+			return (0);
+		}
+	} else {
+		/*
+		 * If we get a page fault while in a critical section, then
+		 * it is most likely a fatal kernel page fault.  The kernel
+		 * is already going to panic trying to get a sleep lock to
+		 * do the VM lookup, so just consider it a fatal trap so the
+		 * kernel can print out a useful trap message and even get
+		 * to the debugger.
+		 *
+		 * If we get a page fault while holding a non-sleepable
+		 * lock, then it is most likely a fatal kernel page fault.
+		 * If WITNESS is enabled, then it's going to whine about
+		 * bogus LORs with various VM locks, so just skip to the
+		 * fatal trap handling directly.
+		 */
+		if (td->td_critnest !=3D 0 ||
+		    WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
+		    "Kernel page fault") !=3D 0) {
+			trap_fatal(frame, eva);
+			return (-1);
+		}
+	}
 	va =3D trunc_page(eva);
 	if (va >=3D VM_MIN_KERNEL_ADDRESS) {
 		/*
@@ -719,8 +745,20 @@
 		 */
 		rv =3D vm_fault(map, va, ftype, VM_FAULT_NORMAL);
 	}
-	if (rv =3D=3D KERN_SUCCESS)
+	if (rv =3D=3D KERN_SUCCESS) {
+#ifdef HWPMC_HOOKS
+		if (ftype =3D=3D VM_PROT_READ || ftype =3D=3D VM_PROT_WRITE) {
+			PMC_SOFT_CALL_TF( , , page_fault, all, frame);
+			if (ftype =3D=3D VM_PROT_READ)
+				PMC_SOFT_CALL_TF( , , page_fault, read,
+				    frame);
+			else
+				PMC_SOFT_CALL_TF( , , page_fault, write,
+				    frame);
+		}
+#endif
 		return (0);
+	}
 nogo:
 	if (!usermode) {
 		if (td->td_intr_nesting_level =3D=3D 0 &&
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/conf/GENERIC
--- a/head/sys/amd64/conf/GENERIC	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/conf/GENERIC	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check first
 # in NOTES.
 #
-# $FreeBSD: head/sys/amd64/conf/GENERIC 232561 2012-03-05 18:47:42Z jkim $
+# $FreeBSD: head/sys/amd64/conf/GENERIC 233427 2012-03-24 18:08:28Z marius=
 $
=20
 cpu		HAMMER
 ident		GENERIC
@@ -218,9 +218,12 @@
 device		bce		# Broadcom BCM5706/BCM5708 Gigabit Ethernet
 device		bfe		# Broadcom BCM440x 10/100 Ethernet
 device		bge		# Broadcom BCM570xx Gigabit Ethernet
+device		cas		# Sun Cassini/Cassini+ and NS DP83065 Saturn
 device		dc		# DEC/Intel 21143 and various workalikes
 device		et		# Agere ET1310 10/100/Gigabit Ethernet
 device		fxp		# Intel EtherExpress PRO/100B (82557, 82558)
+device		gem		# Sun GEM/Sun ERI/Apple GMAC
+device		hme		# Sun HME (Happy Meal Ethernet)
 device		jme		# JMicron JMC250 Gigabit/JMC260 Fast Ethernet
 device		lge		# Level 1 LXT1001 gigabit Ethernet
 device		msk		# Marvell/SysKonnect Yukon II Gigabit Ethernet
@@ -285,7 +288,6 @@
 device		ether		# Ethernet support
 device		vlan		# 802.1Q VLAN support
 device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 device		md		# Memory "disks"
 device		gif		# IPv6 and IPv4 tunneling
 device		faith		# IPv6-to-IPv4 relaying (translation)
@@ -317,6 +319,9 @@
=20
 # Sound support
 device		sound		# Generic sound driver (required)
+device		snd_cmi		# CMedia CMI8338/CMI8738
+device		snd_csa		# Crystal Semiconductor CS461x/428x
+device		snd_emu10kx	# Creative SoundBlaster Live! and Audigy
 device		snd_es137x	# Ensoniq AudioPCI ES137x
 device		snd_hda		# Intel High Definition Audio
 device		snd_ich		# Intel, NVidia and other ICH AC'97 Audio
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/conf/NOTES
--- a/head/sys/amd64/conf/NOTES	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/conf/NOTES	Tue Apr 17 11:51:51 2012 +0300
@@ -4,7 +4,7 @@
 # This file contains machine dependent kernel configuration notes.  For
 # machine independent notes, look in /sys/conf/NOTES.
 #
-# $FreeBSD: head/sys/amd64/conf/NOTES 232614 2012-03-06 18:44:52Z bz $
+# $FreeBSD: head/sys/amd64/conf/NOTES 234183 2012-04-12 14:01:06Z jhb $
 #
=20
 #
@@ -90,6 +90,19 @@
=20
 options 	BPF_JITTER
=20
+# OpenFabrics Enterprise Distribution (Infiniband).
+options 	OFED
+options 	OFED_DEBUG_INIT
+
+# Sockets Direct Protocol
+options 	SDP
+options 	SDP_DEBUG
+
+# IP over Inifiband
+options 	IPOIB
+options 	IPOIB_DEBUG
+options 	IPOIB_CM
+
 =0C
 #####################################################################
 # CLOCK OPTIONS
@@ -290,6 +303,9 @@
 #	Requires the iwi firmware module
 # iwn:	Intel Wireless WiFi Link 4965/1000/5000/6000 802.11 network adapters
 #	Requires the iwn firmware module
+# mlx4ib: Mellanox ConnectX HCA InfiniBand
+# mlxen: Mellanox ConnectX HCA Ethernet
+# mthca: Mellanox HCA InfiniBand
 # mwl:	Marvell 88W8363 IEEE 802.11 adapter
 #	Requires the mwl firmware module
 # nfe:	nVidia nForce MCP on-board Ethernet Networking (BSD open source)
@@ -298,18 +314,21 @@
 # wpi:	Intel 3945ABG Wireless LAN controller
 #	Requires the wpi firmware module
=20
-device		ed
+device		ed		# NE[12]000, SMC Ultra, 3c503, DS8390 cards
 options 	ED_3C503
 options 	ED_HPP
 options 	ED_SIC
-device		ipw
-device		iwi
-device		iwn
-device		mwl
-device		nfe
-device		nve
+device		ipw		# Intel 2100 wireless NICs.
+device		iwi		# Intel 2200BG/2225BG/2915ABG wireless NICs.
+device		iwn		# Intel 4965/1000/5000/6000 wireless NICs.
+device  	mlx4ib		# Mellanox ConnectX HCA InfiniBand
+device  	mlxen		# Mellanox ConnectX HCA Ethernet
+device  	mthca		# Mellanox HCA InfiniBand
+device		mwl		# Marvell 88W8363 802.11n wireless NICs.
+device		nfe		# nVidia nForce MCP on-board Ethernet
+device		nve		# nVidia nForce MCP on-board Ethernet Networking
 device		sfxge
-device		wpi
+device		wpi		# Intel 3945ABG wireless NICs.
=20
 # IEEE 802.11 adapter firmware modules
=20
@@ -493,19 +512,6 @@
 options 	ENABLE_ALART		# Control alarm on Intel intpm driver
=20
 #
-# Set the number of PV entries per process.  Increasing this can
-# stop panics related to heavy use of shared memory.  However, that can
-# (combined with large amounts of physical memory) cause panics at
-# boot time due the kernel running out of VM space.
-#
-# If you're tweaking this, you might also want to increase the sysctls
-# "vm.v_free_min", "vm.v_free_reserved", and "vm.v_free_target".
-#
-# The value below is the one more than the default.
-#
-options 	PMAP_SHPGPERPROC=3D201
-
-#
 # Number of initial kernel page table pages used for early bootstrap.
 # This number should include enough pages to map the kernel and any
 # modules or other data loaded with the kernel by the loader.  Each
@@ -572,6 +578,10 @@
=20
 options 	KSTACK_PAGES=3D5
=20
+# Enable detailed accounting by the PV entry allocator.
+
+options 	PV_STATS
+
 #####################################################################
=20
 # More undocumented options for linting.
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/include/intr_machdep.h
--- a/head/sys/amd64/include/intr_machdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/include/intr_machdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/amd64/include/intr_machdep.h 234207 2012-04-13 07:15=
:40Z avg $
  */
=20
 #ifndef __MACHINE_INTR_MACHDEP_H__
@@ -60,10 +60,10 @@
  * - 1 ??? dummy counter.
  * - 2 counters for each I/O interrupt.
  * - 1 counter for each CPU for lapic timer.
- * - 7 counters for each CPU for IPI counters for SMP.
+ * - 8 counters for each CPU for IPI counters for SMP.
  */
 #ifdef SMP
-#define	INTRCNT_COUNT	(1 + NUM_IO_INTS * 2 + (1 + 7) * MAXCPU)
+#define	INTRCNT_COUNT	(1 + NUM_IO_INTS * 2 + (1 + 8) * MAXCPU)
 #else
 #define	INTRCNT_COUNT	(1 + NUM_IO_INTS * 2 + 1)
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/include/pmc_mdep.h
--- a/head/sys/amd64/include/pmc_mdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/include/pmc_mdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/amd64/include/pmc_mdep.h 233628 2012-03-28 20:58:30Z=
 fabient $
  */
=20
 /* Machine dependent interfaces */
@@ -50,13 +50,13 @@
  * measurement architecture have PMCs of the following classes: TSC,
  * IAF, IAP, UCF and UCP.
  */
-#define	PMC_MDEP_CLASS_INDEX_TSC	0
-#define	PMC_MDEP_CLASS_INDEX_K8		1
-#define	PMC_MDEP_CLASS_INDEX_P4		1
-#define	PMC_MDEP_CLASS_INDEX_IAP	1
-#define	PMC_MDEP_CLASS_INDEX_IAF	2
-#define	PMC_MDEP_CLASS_INDEX_UCP	3
-#define	PMC_MDEP_CLASS_INDEX_UCF	4
+#define	PMC_MDEP_CLASS_INDEX_TSC	1
+#define	PMC_MDEP_CLASS_INDEX_K8		2
+#define	PMC_MDEP_CLASS_INDEX_P4		2
+#define	PMC_MDEP_CLASS_INDEX_IAP	2
+#define	PMC_MDEP_CLASS_INDEX_IAF	3
+#define	PMC_MDEP_CLASS_INDEX_UCP	4
+#define	PMC_MDEP_CLASS_INDEX_UCF	5
=20
 /*
  * On the amd64 platform we support the following PMCs.
@@ -119,6 +119,15 @@
=20
 #define	PMC_IN_USERSPACE(va) ((va) <=3D VM_MAXUSER_ADDRESS)
=20
+/* Build a fake kernel trapframe from current instruction pointer. */
+#define PMC_FAKE_TRAPFRAME(TF)						\
+	do {								\
+	(TF)->tf_cs =3D 0; (TF)->tf_rflags =3D 0;				\
+	__asm __volatile("movq %%rbp,%0" : "=3Dr" ((TF)->tf_rbp));	\
+	__asm __volatile("movq %%rsp,%0" : "=3Dr" ((TF)->tf_rsp));	\
+	__asm __volatile("call 1f \n\t1: pop %0" : "=3Dr"((TF)->tf_rip));	\
+	} while (0)
+
 /*
  * Prototypes
  */
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/include/proc.h
--- a/head/sys/amd64/include/proc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/include/proc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	from: @(#)proc.h	7.1 (Berkeley) 5/15/91
- * $FreeBSD: head/sys/amd64/include/proc.h 226112 2011-10-07 16:09:44Z kib=
 $
+ * $FreeBSD: head/sys/amd64/include/proc.h 233291 2012-03-22 04:52:51Z alc=
 $
  */
=20
 #ifndef _MACHINE_PROC_H_
@@ -46,6 +46,7 @@
 struct mdthread {
 	int	md_spinlock_count;	/* (k) */
 	register_t md_saved_flags;	/* (k) */
+	register_t md_spurflt_addr;	/* (k) Spurious page fault address. */
 };
=20
 struct mdproc {
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/include/vm.h
--- a/head/sys/amd64/include/vm.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/include/vm.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/amd64/include/vm.h 233671 2012-03-29 16:51:22Z jhb $
  */
=20
 #ifndef _MACHINE_VM_H_
@@ -38,7 +38,7 @@
 #define	VM_MEMATTR_WRITE_THROUGH	((vm_memattr_t)PAT_WRITE_THROUGH)
 #define	VM_MEMATTR_WRITE_PROTECTED	((vm_memattr_t)PAT_WRITE_PROTECTED)
 #define	VM_MEMATTR_WRITE_BACK		((vm_memattr_t)PAT_WRITE_BACK)
-#define	VM_MEMATTR_UNCACHED		((vm_memattr_t)PAT_UNCACHED)
+#define	VM_MEMATTR_WEAK_UNCACHEABLE	((vm_memattr_t)PAT_UNCACHED)
=20
 #define	VM_MEMATTR_DEFAULT		VM_MEMATTR_WRITE_BACK
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/linux32_dummy.c
--- a/head/sys/amd64/linux32/linux32_dummy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/linux32/linux32_dummy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/linux32/linux32_dummy.c 232799 2012-03-=
10 23:10:18Z netchild $");
+__FBSDID("$FreeBSD: head/sys/amd64/linux32/linux32_dummy.c 234352 2012-04-=
16 21:22:02Z jkim $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -122,7 +122,6 @@
 DUMMY(eventfd2);
 DUMMY(epoll_create1);
 DUMMY(dup3);
-DUMMY(pipe2);
 DUMMY(inotify_init1);
 /* linux 2.6.30: */
 DUMMY(preadv);
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/linux32_machdep=
.c
--- a/head/sys/amd64/linux32/linux32_machdep.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/amd64/linux32/linux32_machdep.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/amd64/linux32/linux32_machdep.c 225617 2011-0=
9-16 13:58:51Z kmacy $");
+__FBSDID("$FreeBSD: head/sys/amd64/linux32/linux32_machdep.c 234352 2012-0=
4-16 21:22:02Z jkim $");
=20
 #include <sys/param.h>
 #include <sys/kernel.h>
@@ -698,25 +698,6 @@
 }
=20
 int
-linux_pipe(struct thread *td, struct linux_pipe_args *args)
-{
-	int error;
-	int fildes[2];
-
-#ifdef DEBUG
-	if (ldebug(pipe))
-		printf(ARGS(pipe, "*"));
-#endif
-
-	error =3D kern_pipe(td, fildes);
-	if (error)
-		return (error);
-
-	/* XXX: Close descriptors on error. */
-	return (copyout(fildes, args->pipefds, sizeof fildes));
-}
-
-int
 linux_sigaction(struct thread *td, struct linux_sigaction_args *args)
 {
 	l_osigaction_t osa;
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/linux32_proto.h
--- a/head/sys/amd64/linux32/linux32_proto.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/linux32/linux32_proto.h	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,8 @@
  * System call prototypes.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/amd64/linux32/linux32_proto.h 232800 2012-03-10 23:1=
1:21Z netchild $
- * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 232799 201=
2-03-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/amd64/linux32/linux32_proto.h 234360 2012-04-16 23:1=
7:29Z jkim $
+ * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 234359 201=
2-04-16 23:16:18Z jkim=20
  */
=20
 #ifndef _LINUX_SYSPROTO_H_
@@ -153,7 +153,7 @@
 	char path_l_[PADL_(char *)]; char * path; char path_r_[PADR_(char *)];
 };
 struct linux_pipe_args {
-	char pipefds_l_[PADL_(l_ulong *)]; l_ulong * pipefds; char pipefds_r_[PAD=
R_(l_ulong *)];
+	char pipefds_l_[PADL_(l_int *)]; l_int * pipefds; char pipefds_r_[PADR_(l=
_int *)];
 };
 struct linux_times_args {
 	char buf_l_[PADL_(struct l_times_argv *)]; struct l_times_argv * buf; cha=
r buf_r_[PADR_(struct l_times_argv *)];
@@ -344,7 +344,7 @@
 	register_t dummy;
 };
 struct linux_iopl_args {
-	char level_l_[PADL_(l_ulong)]; l_ulong level; char level_r_[PADR_(l_ulong=
)];
+	char level_l_[PADL_(l_int)]; l_int level; char level_r_[PADR_(l_int)];
 };
 struct linux_vhangup_args {
 	register_t dummy;
@@ -628,19 +628,16 @@
 	char length_l_[PADL_(l_loff_t)]; l_loff_t length; char length_r_[PADR_(l_=
loff_t)];
 };
 struct linux_stat64_args {
-	char filename_l_[PADL_(char *)]; char * filename; char filename_r_[PADR_(=
char *)];
+	char filename_l_[PADL_(const char *)]; const char * filename; char filena=
me_r_[PADR_(const char *)];
 	char statbuf_l_[PADL_(struct l_stat64 *)]; struct l_stat64 * statbuf; cha=
r statbuf_r_[PADR_(struct l_stat64 *)];
-	char flags_l_[PADL_(l_long)]; l_long flags; char flags_r_[PADR_(l_long)];
 };
 struct linux_lstat64_args {
-	char filename_l_[PADL_(char *)]; char * filename; char filename_r_[PADR_(=
char *)];
+	char filename_l_[PADL_(const char *)]; const char * filename; char filena=
me_r_[PADR_(const char *)];
 	char statbuf_l_[PADL_(struct l_stat64 *)]; struct l_stat64 * statbuf; cha=
r statbuf_r_[PADR_(struct l_stat64 *)];
-	char flags_l_[PADL_(l_long)]; l_long flags; char flags_r_[PADR_(l_long)];
 };
 struct linux_fstat64_args {
-	char fd_l_[PADL_(l_ulong)]; l_ulong fd; char fd_r_[PADR_(l_ulong)];
+	char fd_l_[PADL_(l_int)]; l_int fd; char fd_r_[PADR_(l_int)];
 	char statbuf_l_[PADL_(struct l_stat64 *)]; struct l_stat64 * statbuf; cha=
r statbuf_r_[PADR_(struct l_stat64 *)];
-	char flags_l_[PADL_(l_long)]; l_long flags; char flags_r_[PADR_(l_long)];
 };
 struct linux_lchown_args {
 	char path_l_[PADL_(char *)]; char * path; char path_r_[PADR_(char *)];
@@ -1046,7 +1043,8 @@
 	register_t dummy;
 };
 struct linux_pipe2_args {
-	register_t dummy;
+	char pipefds_l_[PADL_(l_int *)]; l_int * pipefds; char pipefds_r_[PADR_(l=
_int *)];
+	char flags_l_[PADL_(l_int)]; l_int flags; char flags_r_[PADR_(l_int)];
 };
 struct linux_inotify_init1_args {
 	register_t dummy;
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/linux32_syscall=
.h
--- a/head/sys/amd64/linux32/linux32_syscall.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/amd64/linux32/linux32_syscall.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -2,8 +2,8 @@
  * System call numbers.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/amd64/linux32/linux32_syscall.h 232800 2012-03-10 23=
:11:21Z netchild $
- * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 232799 201=
2-03-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/amd64/linux32/linux32_syscall.h 234360 2012-04-16 23=
:17:29Z jkim $
+ * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 234359 201=
2-04-16 23:16:18Z jkim=20
  */
=20
 #define	LINUX_SYS_exit	1
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/linux32_syscall=
s.c
--- a/head/sys/amd64/linux32/linux32_syscalls.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/sys/amd64/linux32/linux32_syscalls.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -2,8 +2,8 @@
  * System call names.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/amd64/linux32/linux32_syscalls.c 232800 2012-03-10 2=
3:11:21Z netchild $
- * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 232799 201=
2-03-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/amd64/linux32/linux32_syscalls.c 234360 2012-04-16 2=
3:17:29Z jkim $
+ * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 234359 201=
2-04-16 23:16:18Z jkim=20
  */
=20
 const char *linux_syscallnames[] =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/linux32_sysent.c
--- a/head/sys/amd64/linux32/linux32_sysent.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/linux32/linux32_sysent.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,8 @@
  * System call switch table.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/amd64/linux32/linux32_sysent.c 232800 2012-03-10 23:=
11:21Z netchild $
- * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 232799 201=
2-03-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/amd64/linux32/linux32_sysent.c 234360 2012-04-16 23:=
17:29Z jkim $
+ * created from FreeBSD: head/sys/amd64/linux32/syscalls.master 234359 201=
2-04-16 23:16:18Z jkim=20
  */
=20
 #include "opt_compat.h"
@@ -350,7 +350,7 @@
 	{ 0, (sy_call_t *)linux_eventfd2, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC =
},	/* 328 =3D linux_eventfd2 */
 	{ 0, (sy_call_t *)linux_epoll_create1, AUE_NULL, NULL, 0, 0, 0, SY_THR_ST=
ATIC },	/* 329 =3D linux_epoll_create1 */
 	{ 0, (sy_call_t *)linux_dup3, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	/=
* 330 =3D linux_dup3 */
-	{ 0, (sy_call_t *)linux_pipe2, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	=
/* 331 =3D linux_pipe2 */
+	{ AS(linux_pipe2_args), (sy_call_t *)linux_pipe2, AUE_NULL, NULL, 0, 0, 0=
, SY_THR_STATIC },	/* 331 =3D linux_pipe2 */
 	{ 0, (sy_call_t *)linux_inotify_init1, AUE_NULL, NULL, 0, 0, 0, SY_THR_ST=
ATIC },	/* 332 =3D linux_inotify_init1 */
 	{ 0, (sy_call_t *)linux_preadv, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },=
	/* 333 =3D linux_preadv */
 	{ 0, (sy_call_t *)linux_pwritev, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC }=
,	/* 334 =3D linux_pwritev */
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/linux32_systrac=
e_args.c
--- a/head/sys/amd64/linux32/linux32_systrace_args.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/sys/amd64/linux32/linux32_systrace_args.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -2,7 +2,7 @@
  * System call argument to DTrace register array converstion.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/amd64/linux32/linux32_systrace_args.c 232800 2012-03=
-10 23:11:21Z netchild $
+ * $FreeBSD: head/sys/amd64/linux32/linux32_systrace_args.c 234360 2012-04=
-16 23:17:29Z jkim $
  * This file is part of the DTrace syscall provider.
  */
=20
@@ -287,7 +287,7 @@
 	/* linux_pipe */
 	case 42: {
 		struct linux_pipe_args *p =3D params;
-		uarg[0] =3D (intptr_t) p->pipefds; /* l_ulong * */
+		uarg[0] =3D (intptr_t) p->pipefds; /* l_int * */
 		*n_args =3D 1;
 		break;
 	}
@@ -748,7 +748,7 @@
 	/* linux_iopl */
 	case 110: {
 		struct linux_iopl_args *p =3D params;
-		iarg[0] =3D p->level; /* l_ulong */
+		iarg[0] =3D p->level; /* l_int */
 		*n_args =3D 1;
 		break;
 	}
@@ -1355,28 +1355,25 @@
 	/* linux_stat64 */
 	case 195: {
 		struct linux_stat64_args *p =3D params;
-		uarg[0] =3D (intptr_t) p->filename; /* char * */
+		uarg[0] =3D (intptr_t) p->filename; /* const char * */
 		uarg[1] =3D (intptr_t) p->statbuf; /* struct l_stat64 * */
-		iarg[2] =3D p->flags; /* l_long */
-		*n_args =3D 3;
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_lstat64 */
 	case 196: {
 		struct linux_lstat64_args *p =3D params;
-		uarg[0] =3D (intptr_t) p->filename; /* char * */
+		uarg[0] =3D (intptr_t) p->filename; /* const char * */
 		uarg[1] =3D (intptr_t) p->statbuf; /* struct l_stat64 * */
-		iarg[2] =3D p->flags; /* l_long */
-		*n_args =3D 3;
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_fstat64 */
 	case 197: {
 		struct linux_fstat64_args *p =3D params;
-		iarg[0] =3D p->fd; /* l_ulong */
+		iarg[0] =3D p->fd; /* l_int */
 		uarg[1] =3D (intptr_t) p->statbuf; /* struct l_stat64 * */
-		iarg[2] =3D p->flags; /* l_long */
-		*n_args =3D 3;
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_lchown */
@@ -2172,7 +2169,10 @@
 	}
 	/* linux_pipe2 */
 	case 331: {
-		*n_args =3D 0;
+		struct linux_pipe2_args *p =3D params;
+		uarg[0] =3D (intptr_t) p->pipefds; /* l_int * */
+		iarg[1] =3D p->flags; /* l_int */
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_inotify_init1 */
@@ -2689,7 +2689,7 @@
 	case 42:
 		switch(ndx) {
 		case 0:
-			p =3D "l_ulong *";
+			p =3D "l_int *";
 			break;
 		default:
 			break;
@@ -3392,7 +3392,7 @@
 	case 110:
 		switch(ndx) {
 		case 0:
-			p =3D "l_ulong";
+			p =3D "l_int";
 			break;
 		default:
 			break;
@@ -4339,14 +4339,11 @@
 	case 195:
 		switch(ndx) {
 		case 0:
-			p =3D "char *";
+			p =3D "const char *";
 			break;
 		case 1:
 			p =3D "struct l_stat64 *";
 			break;
-		case 2:
-			p =3D "l_long";
-			break;
 		default:
 			break;
 		};
@@ -4355,14 +4352,11 @@
 	case 196:
 		switch(ndx) {
 		case 0:
-			p =3D "char *";
+			p =3D "const char *";
 			break;
 		case 1:
 			p =3D "struct l_stat64 *";
 			break;
-		case 2:
-			p =3D "l_long";
-			break;
 		default:
 			break;
 		};
@@ -4371,14 +4365,11 @@
 	case 197:
 		switch(ndx) {
 		case 0:
-			p =3D "l_ulong";
+			p =3D "l_int";
 			break;
 		case 1:
 			p =3D "struct l_stat64 *";
 			break;
-		case 2:
-			p =3D "l_long";
-			break;
 		default:
 			break;
 		};
@@ -5368,6 +5359,16 @@
 		break;
 	/* linux_pipe2 */
 	case 331:
+		switch(ndx) {
+		case 0:
+			p =3D "l_int *";
+			break;
+		case 1:
+			p =3D "l_int";
+			break;
+		default:
+			break;
+		};
 		break;
 	/* linux_inotify_init1 */
 	case 332:
@@ -6621,6 +6622,9 @@
 	case 330:
 	/* linux_pipe2 */
 	case 331:
+		if (ndx =3D=3D 0 || ndx =3D=3D 1)
+			p =3D "int";
+		break;
 	/* linux_inotify_init1 */
 	case 332:
 	/* linux_preadv */
diff -r 428842767fa6 -r f2935497fa04 head/sys/amd64/linux32/syscalls.master
--- a/head/sys/amd64/linux32/syscalls.master	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/amd64/linux32/syscalls.master	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
- $FreeBSD: head/sys/amd64/linux32/syscalls.master 232799 2012-03-10 23:10:=
18Z netchild $
+ $FreeBSD: head/sys/amd64/linux32/syscalls.master 234359 2012-04-16 23:16:=
18Z jkim $
=20
 ;	@(#)syscalls.master	8.1 (Berkeley) 7/19/93
 ; System call name/number master file (or rather, slave, from LINUX).
@@ -95,7 +95,7 @@
 39	AUE_MKDIR	STD	{ int linux_mkdir(char *path, l_int mode); }
 40	AUE_RMDIR	STD	{ int linux_rmdir(char *path); }
 41	AUE_DUP		NOPROTO	{ int dup(u_int fd); }
-42	AUE_PIPE	STD	{ int linux_pipe(l_ulong *pipefds); }
+42	AUE_PIPE	STD	{ int linux_pipe(l_int *pipefds); }
 43	AUE_NULL	STD	{ int linux_times(struct l_times_argv *buf); }
 44	AUE_NULL	UNIMPL	prof
 45	AUE_NULL	STD	{ int linux_brk(l_ulong dsend); }
@@ -202,7 +202,7 @@
 				    struct l_newstat *buf); }
 ; 109: olduname
 109	AUE_NULL	STD	{ int linux_uname(void); }
-110	AUE_NULL	STD	{ int linux_iopl(l_ulong level); }
+110	AUE_NULL	STD	{ int linux_iopl(l_int level); }
 111	AUE_NULL	STD	{ int linux_vhangup(void); }
 112	AUE_NULL	UNIMPL	idle
 113	AUE_NULL	UNIMPL	vm86old
@@ -351,12 +351,12 @@
 				    l_loff_t length); }
 194	AUE_FTRUNCATE	STD	{ int linux_ftruncate64(l_uint fd, \
 				    l_loff_t length); }
-195	AUE_STAT	STD	{ int linux_stat64(char *filename, \
-				    struct l_stat64 *statbuf, l_long flags); }
-196	AUE_LSTAT	STD	{ int linux_lstat64(char *filename, \
-				    struct l_stat64 *statbuf, l_long flags); }
-197	AUE_FSTAT	STD	{ int linux_fstat64(l_ulong fd, \
-				    struct l_stat64 *statbuf, l_long flags); }
+195	AUE_STAT	STD	{ int linux_stat64(const char *filename, \
+				    struct l_stat64 *statbuf); }
+196	AUE_LSTAT	STD	{ int linux_lstat64(const char *filename, \
+				    struct l_stat64 *statbuf); }
+197	AUE_FSTAT	STD	{ int linux_fstat64(l_int fd, \
+				    struct l_stat64 *statbuf); }
 198	AUE_LCHOWN	STD	{ int linux_lchown(char *path, l_uid_t uid, \
 				    l_gid_t gid); }
 199	AUE_GETUID	STD	{ int linux_getuid(void); }
@@ -536,7 +536,7 @@
 328	AUE_NULL	STD	{ int linux_eventfd2(void); }
 329	AUE_NULL	STD	{ int linux_epoll_create1(void); }
 330	AUE_NULL	STD	{ int linux_dup3(void); }
-331	AUE_NULL	STD	{ int linux_pipe2(void); }
+331	AUE_NULL	STD	{ int linux_pipe2(l_int *pipefds, l_int flags); }
 332	AUE_NULL	STD	{ int linux_inotify_init1(void); }
 ; linux 2.6.30:
 333	AUE_NULL	STD	{ int linux_preadv(void); }
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_pio.c
--- a/head/sys/arm/at91/at91_pio.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_pio.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/arm/at91/at91_pio.c 225882 2011-09-30 04:55:2=
3Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/arm/at91/at91_pio.c 234281 2012-04-14 11:29:3=
2Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -52,30 +52,32 @@
 	struct mtx sc_mtx;		/* basically a perimeter lock */
 	struct cdev *cdev;
 	int flags;
-#define OPENED 1
+#define	OPENED 1
 };
=20
 static inline uint32_t
 RD4(struct at91_pio_softc *sc, bus_size_t off)
 {
+
 	return (bus_read_4(sc->mem_res, off));
 }
=20
 static inline void
 WR4(struct at91_pio_softc *sc, bus_size_t off, uint32_t val)
 {
+
 	bus_write_4(sc->mem_res, off, val);
 }
=20
-#define AT91_PIO_LOCK(_sc)		mtx_lock_spin(&(_sc)->sc_mtx)
+#define	AT91_PIO_LOCK(_sc)		mtx_lock_spin(&(_sc)->sc_mtx)
 #define	AT91_PIO_UNLOCK(_sc)		mtx_unlock_spin(&(_sc)->sc_mtx)
-#define AT91_PIO_LOCK_INIT(_sc) \
+#define	AT91_PIO_LOCK_INIT(_sc) \
 	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev), \
 	    "pio", MTX_SPIN)
-#define AT91_PIO_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
-#define AT91_PIO_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED);
-#define AT91_PIO_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED=
);
-#define CDEV2SOFTC(dev)		((dev)->si_drv1)
+#define	AT91_PIO_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
+#define	AT91_PIO_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED);
+#define	AT91_PIO_ASSERT_UNLOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_NOTOWNED=
);
+#define	CDEV2SOFTC(dev)			((dev)->si_drv1)
=20
 static devclass_t at91_pio_devclass;
=20
@@ -132,9 +134,10 @@
 static int
 at91_pio_attach(device_t dev)
 {
-	struct at91_pio_softc *sc =3D device_get_softc(dev);
+	struct at91_pio_softc *sc;
 	int err;
=20
+	sc =3D device_get_softc(dev);
 	sc->dev =3D dev;
 	err =3D at91_pio_activate(dev);
 	if (err)
@@ -146,7 +149,7 @@
 	AT91_PIO_LOCK_INIT(sc);
=20
 	/*
-	 * Activate the interrupt, but disable all interrupts in the hardware
+	 * Activate the interrupt, but disable all interrupts in the hardware.
 	 */
 	WR4(sc, PIO_IDR, 0xffffffff);
 	err =3D bus_setup_intr(dev, sc->irq_res, INTR_TYPE_MISC,
@@ -171,6 +174,7 @@
 static int
 at91_pio_detach(device_t dev)
 {
+
 	return (EBUSY);	/* XXX */
 }
=20
@@ -215,7 +219,6 @@
 		bus_release_resource(dev, SYS_RES_IRQ,
 		    rman_get_rid(sc->irq_res), sc->irq_res);
 	sc->irq_res =3D 0;
-	return;
 }
=20
 static int
@@ -225,7 +228,7 @@
 #if 0
 	uint32_t status;
=20
-	/* Reading the status also clears the interrupt */
+	/* Reading the status also clears the interrupt. */
 	status =3D RD4(sc, PIO_SR);
 	if (status =3D=3D 0)
 		return;
@@ -236,7 +239,7 @@
 	return (FILTER_HANDLED);
 }
=20
-static int=20
+static int
 at91_pio_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
 {
 	struct at91_pio_softc *sc;
@@ -246,11 +249,11 @@
 	if (!(sc->flags & OPENED)) {
 		sc->flags |=3D OPENED;
 #if 0
-	// Enable interrupts
+	/* Enable interrupts. */
 #endif
 	}
 	AT91_PIO_UNLOCK(sc);
-    	return (0);
+	return (0);
 }
=20
 static int
@@ -262,7 +265,7 @@
 	AT91_PIO_LOCK(sc);
 	sc->flags &=3D ~OPENED;
 #if 0
-	// Disable interrupts
+	/* Disable interrupts. */
 #endif
 	AT91_PIO_UNLOCK(sc);
 	return (0);
@@ -272,6 +275,7 @@
 at91_pio_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
     struct thread *td)
 {
+
 	return (ENXIO);
 }
=20
@@ -280,6 +284,7 @@
  * don't use bus_space, as that isn't yet available when we need to use
  * them.
  */
+
 void
 at91_pio_use_periph_a(uint32_t pio, uint32_t periph_a_mask, int use_pullup)
 {
@@ -369,11 +374,10 @@
 		PIO[PIO_IFER / 4] =3D data_mask;
 	else
 		PIO[PIO_IFDR / 4] =3D data_mask;
-	return;
 }
=20
 void
-at91_pio_gpio_set_interrupt(uint32_t pio, uint32_t data_mask,=20
+at91_pio_gpio_set_interrupt(uint32_t pio, uint32_t data_mask,
 	int enable_interrupt)
 {
 	uint32_t *PIO =3D (uint32_t *)(AT91_BASE + pio);
@@ -382,14 +386,14 @@
 		PIO[PIO_IER / 4] =3D data_mask;
 	else
 		PIO[PIO_IDR / 4] =3D data_mask;
-	return;
 }
=20
 uint32_t
 at91_pio_gpio_clear_interrupt(uint32_t pio)
 {
 	uint32_t *PIO =3D (uint32_t *)(AT91_BASE + pio);
-	/* reading this register will clear the interrupts */
+
+	/* Reading this register will clear the interrupts. */
 	return (PIO[PIO_ISR / 4]);
 }
=20
@@ -399,7 +403,7 @@
 	DEVMETHOD(device_attach,	at91_pio_attach),
 	DEVMETHOD(device_detach,	at91_pio_detach),
=20
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t at91_pio_driver =3D {
@@ -408,4 +412,5 @@
 	sizeof(struct at91_pio_softc),
 };
=20
-DRIVER_MODULE(at91_pio, atmelarm, at91_pio_driver, at91_pio_devclass, 0, 0=
);
+DRIVER_MODULE(at91_pio, atmelarm, at91_pio_driver, at91_pio_devclass, NULL,
+    NULL);
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_piovar.h
--- a/head/sys/arm/at91/at91_piovar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_piovar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,22 +23,26 @@
  * SUCH DAMAGE.
  */
=20
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/arm/at91/at91_piovar.h 234281 2012-04-14 11:29:32Z m=
arius $ */
=20
 #ifndef ARM_AT91_AT91_PIOVAR_H
-#define ARM_AT91_AT91_PIOVAR_H
+#define	ARM_AT91_AT91_PIOVAR_H
=20
-void at91_pio_use_periph_a(uint32_t pio, uint32_t periph_a_mask, int use_p=
ullup);
-void at91_pio_use_periph_b(uint32_t pio, uint32_t periph_b_mask, int use_p=
ullup);
+void at91_pio_use_periph_a(uint32_t pio, uint32_t periph_a_mask,
+    int use_pullup);
+void at91_pio_use_periph_b(uint32_t pio, uint32_t periph_b_mask,
+    int use_pullup);
 void at91_pio_use_gpio(uint32_t pio, uint32_t gpio_mask);
 void at91_pio_gpio_input(uint32_t pio, uint32_t input_enable_mask);
 void at91_pio_gpio_output(uint32_t pio, uint32_t output_enable_mask,
-	int use_pullup);
+    int use_pullup);
 void at91_pio_gpio_set(uint32_t pio, uint32_t data_mask);
 void at91_pio_gpio_clear(uint32_t pio, uint32_t data_mask);
 uint8_t at91_pio_gpio_get(uint32_t pio, uint32_t data_mask);
-void at91_pio_gpio_set_deglitch(uint32_t pio, uint32_t data_mask, int use_=
deglitch);
-void at91_pio_gpio_set_interrupt(uint32_t pio, uint32_t data_mask, int ena=
ble_interrupt);
+void at91_pio_gpio_set_deglitch(uint32_t pio, uint32_t data_mask,
+    int use_deglitch);
+void at91_pio_gpio_set_interrupt(uint32_t pio, uint32_t data_mask,
+    int enable_interrupt);
 uint32_t at91_pio_gpio_clear_interrupt(uint32_t pio);
=20
 #endif /* ARM_AT91_AT91_PIOVAR_H */
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_pit.c
--- a/head/sys/arm/at91/at91_pit.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_pit.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/arm/at91/at91_pit.c 234291 2012-04-14 17:09:3=
8Z marius $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -59,12 +59,14 @@
 static inline uint32_t
 RD4(struct pit_softc *sc, bus_size_t off)
 {
+
 	return (bus_read_4(sc->mem_res, off));
 }
=20
 static inline void
 WR4(struct pit_softc *sc, bus_size_t off, uint32_t val)
 {
+
 	bus_write_4(sc->mem_res, off, val);
 }
=20
@@ -88,7 +90,7 @@
 at91pit_probe(device_t dev)
 {
=20
-	if (at91_is_sam9()) {
+	if (at91_is_sam9() || at91_is_sam9xe()) {
 		device_set_desc(dev, "AT91SAM9 PIT");
 		return (0);
 	}
@@ -112,11 +114,11 @@
 	    RF_ACTIVE);
=20
 	if (sc->mem_res =3D=3D NULL)
-	       panic("couldn't allocate register resources");
+		panic("couldn't allocate register resources");
=20
 	rid =3D 0;
 	irq =3D bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 1, 1, 1,
-	  RF_ACTIVE | RF_SHAREABLE);
+	    RF_ACTIVE | RF_SHAREABLE);
 	if (!irq) {
 		device_printf(dev, "could not allocate interrupt resources.\n");
 		err =3D ENOMEM;
@@ -124,16 +126,15 @@
 	}
=20
 	/* Activate the interrupt. */
-	err =3D bus_setup_intr(dev, irq, INTR_TYPE_CLK, pit_intr,
-		NULL, NULL, &ih);
-=09
+	err =3D bus_setup_intr(dev, irq, INTR_TYPE_CLK, pit_intr, NULL, NULL,
+	    &ih);
+
 	at91pit_timecounter.tc_frequency =3D  at91_master_clock / PIT_PRESCALE;
 	tc_init(&at91pit_timecounter);
=20
-	//Enable the PIT here.
-	WR4(sc, PIT_MR,
-		PIT_PIV(at91_master_clock / PIT_PRESCALE / hz) |
-		PIT_EN | PIT_IEN);
+	/* Enable the PIT here. */
+	WR4(sc, PIT_MR, PIT_PIV(at91_master_clock / PIT_PRESCALE / hz) |
+	    PIT_EN | PIT_IEN);
 out:
 	return (err);
 }
@@ -141,7 +142,7 @@
 static device_method_t at91pit_methods[] =3D {
 	DEVMETHOD(device_probe, at91pit_probe),
 	DEVMETHOD(device_attach, at91pit_attach),
-	{0,0},
+	DEVMETHOD_END
 };
=20
 static driver_t at91pit_driver =3D {
@@ -152,7 +153,8 @@
=20
 static devclass_t at91pit_devclass;
=20
-DRIVER_MODULE(at91_pit, atmelarm, at91pit_driver, at91pit_devclass, 0, 0);
+DRIVER_MODULE(at91_pit, atmelarm, at91pit_driver, at91pit_devclass, NULL,
+    NULL);
=20
 static int
 pit_intr(void *arg)
@@ -175,7 +177,7 @@
 static unsigned
 at91pit_get_timecount(struct timecounter *tc)
 {
-	uint32_t piir, icnt;=09
+	uint32_t piir, icnt;
=20
 	piir =3D RD4(sc, PIT_PIIR); /* Current  count | over flows */
 	icnt =3D piir >> 20;	/* Overflows */
@@ -192,7 +194,7 @@
 	last =3D PIT_PIV(RD4(sc, PIT_PIIR));
=20
 	/* Max delay ~=3D 260s. @ 133Mhz */
-        pit_freq =3D at91_master_clock / PIT_PRESCALE;
+	pit_freq =3D at91_master_clock / PIT_PRESCALE;
 	cnt  =3D ((pit_freq * us) + (mhz -1)) / mhz;
 	cnt  =3D (cnt <=3D 0) ? 1 : cnt;
=20
@@ -211,14 +213,17 @@
 void
 cpu_startprofclock(void)
 {
+
 }
=20
 void
 cpu_stopprofclock(void)
 {
+
 }
=20
 void
 cpu_initclocks(void)
 {
+
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_pmc.c
--- a/head/sys/arm/at91/at91_pmc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_pmc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/arm/at91/at91_pmc.c 234292 2012-04-14 17:17:5=
5Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -162,12 +162,14 @@
 static inline uint32_t
 RD4(struct at91_pmc_softc *sc, bus_size_t off)
 {
+
 	return (bus_read_4(sc->mem_res, off));
 }
=20
 static inline void
 WR4(struct at91_pmc_softc *sc, bus_size_t off, uint32_t val)
 {
+
 	bus_write_4(sc->mem_res, off, val);
 }
=20
@@ -180,9 +182,8 @@
 	if (on) {
 		on =3D PMC_IER_LOCKB;
 		value =3D sc->pllb_init;
-	} else {
+	} else
 		value =3D 0;
-	}
=20
 	/* Workaround RM9200 Errata #26 */
 	if (at91_is_rm92() &&
@@ -226,18 +227,19 @@
 }
=20
 struct at91_pmc_clock *
-at91_pmc_clock_add(const char *name, uint32_t irq, struct at91_pmc_clock *=
parent)
+at91_pmc_clock_add(const char *name, uint32_t irq,
+    struct at91_pmc_clock *parent)
 {
 	struct at91_pmc_clock *clk;
 	int i, buflen;
=20
 	clk =3D malloc(sizeof(*clk), M_PMC, M_NOWAIT | M_ZERO);
-	if (clk =3D=3D NULL)=20
+	if (clk =3D=3D NULL)
 		goto err;
=20
 	buflen =3D strlen(name) + 1;
 	clk->name =3D malloc(buflen, M_PMC, M_NOWAIT);
-	if (clk->name =3D=3D NULL)=20
+	if (clk->name =3D=3D NULL)
 		goto err;
=20
 	strlcpy(clk->name, name, buflen);
@@ -256,7 +258,7 @@
 	}
 err:
 	if (clk !=3D NULL) {
-		if (clk->name !=3D NULL)=20
+		if (clk->name !=3D NULL)
 			free(clk->name, M_PMC);
 		free(clk, M_PMC);
 	}
@@ -300,11 +302,13 @@
 void
 at91_pmc_clock_deref(struct at91_pmc_clock *clk)
 {
+
 }
=20
 void
 at91_pmc_clock_enable(struct at91_pmc_clock *clk)
 {
+
 	/* XXX LOCKING? XXX */
 	if (clk->parent)
 		at91_pmc_clock_enable(clk->parent);
@@ -315,6 +319,7 @@
 void
 at91_pmc_clock_disable(struct at91_pmc_clock *clk)
 {
+
 	/* XXX LOCKING? XXX */
 	if (--clk->refcnt =3D=3D 0 && clk->set_mode)
 		clk->set_mode(clk, 0);
@@ -331,18 +336,18 @@
 	div =3D (reg >> clk->pll_div_shift) & clk->pll_div_mask;
 	mul =3D (reg >> clk->pll_mul_shift) & clk->pll_mul_mask;
=20
-//	printf("pll =3D (%d /  %d) * %d =3D %d\n",
-//	    freq, div ,mul + 1, (freq/div) * (mul+1));
+#if 0
+	printf("pll =3D (%d /  %d) * %d =3D %d\n",
+	    freq, div, mul + 1, (freq/div) * (mul+1));
+#endif
=20
 	if (div !=3D 0 && mul !=3D 0) {
 		freq /=3D div;
 		freq *=3D mul + 1;
-	} else {
+	} else
 		freq =3D 0;
-	}
 	clk->hz =3D freq;
=20
-
 	return (freq);
 }
=20
@@ -402,7 +407,7 @@
 	uint32_t mckr;
 	uint32_t mdiv;
=20
-	if (at91_is_sam9()) {
+	if (at91_is_sam9() || at91_is_sam9xe()) {
 		uhpck.pmc_mask =3D PMC_SCER_UHP_SAM9;
 		udpck.pmc_mask =3D PMC_SCER_UDP_SAM9;
 	}
@@ -431,9 +436,8 @@
 	if (at91_is_rm92()) {
 		WR4(sc, PMC_SCDR, PMC_SCER_UHP | PMC_SCER_UDP);
 		WR4(sc, PMC_SCER, PMC_SCER_MCKUDP);
-	} else {
+	} else
 		WR4(sc, PMC_SCDR, PMC_SCER_UHP_SAM9 | PMC_SCER_UDP_SAM9);
-	}
 	WR4(sc, CKGR_PLLBR, 0);
=20
 	/*
@@ -443,15 +447,14 @@
 	mck.parent =3D clock_list[mckr & 0x3];
 	mck.parent->refcnt++;
=20
-	cpu.hz =3D=20
-	mck.hz =3D mck.parent->hz /
-  	     (1 << ((mckr & PMC_MCKR_PRES_MASK) >> 2));
+	cpu.hz =3D mck.hz =3D mck.parent->hz /
+	    (1 << ((mckr & PMC_MCKR_PRES_MASK) >> 2));
=20
 	mdiv =3D (mckr & PMC_MCKR_MDIV_MASK) >> 8;
-	if (at91_is_sam9()) {
+	if (at91_is_sam9() || at91_is_sam9xe()) {
 		if (mdiv > 0)
 			mck.hz /=3D mdiv * 2;
-	} else=20
+	} else
 		mck.hz /=3D (1 + mdiv);
=20
 	/* Only found on SAM9G20 */
@@ -488,7 +491,6 @@
 		bus_release_resource(dev, SYS_RES_IOPORT,
 		    rman_get_rid(sc->mem_res), sc->mem_res);
 	sc->mem_res =3D 0;
-	return;
 }
=20
 static int
@@ -574,7 +576,7 @@
 static device_method_t at91_pmc_methods[] =3D {
 	DEVMETHOD(device_probe, at91_pmc_probe),
 	DEVMETHOD(device_attach, at91_pmc_attach),
-	{0, 0},
+	DEVMETHOD_END
 };
=20
 static driver_t at91_pmc_driver =3D {
@@ -584,4 +586,5 @@
 };
 static devclass_t at91_pmc_devclass;
=20
-DRIVER_MODULE(at91_pmc, atmelarm, at91_pmc_driver, at91_pmc_devclass, 0, 0=
);
+DRIVER_MODULE(at91_pmc, atmelarm, at91_pmc_driver, at91_pmc_devclass, NULL,
+    NULL);
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_rst.c
--- a/head/sys/arm/at91/at91_rst.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_rst.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/arm/at91/at91_rst.c 234291 2012-04-14 17:09:3=
8Z marius $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -40,7 +40,7 @@
 #include <arm/at91/at91board.h>
=20
 #define RST_TIMEOUT (5)	/* Seconds to hold NRST for hard reset */
-#define RST_TICK (20) 	/* sample NRST at hz/RST_TICK intervals */
+#define RST_TICK (20)	/* sample NRST at hz/RST_TICK intervals */
=20
 static int rst_intr(void *arg);
=20
@@ -71,7 +71,7 @@
 at91_rst_probe(device_t dev)
 {
=20
-	if (at91_is_sam9()) {
+	if (at91_is_sam9() || at91_is_sam9xe()) {
 		device_set_desc(dev, "AT91SAM9 Reset Controller");
 		return (0);
 	}
@@ -122,7 +122,7 @@
 		case	RST_SR_RST_WAKE:
 			cause =3D "Wake Up";
 			break;
-		case	RST_SR_RST_WDT:=09
+		case	RST_SR_RST_WDT:
 			cause =3D "Watchdog";
 			break;
 		case	RST_SR_RST_SOFT:
@@ -153,7 +153,7 @@
 		cpu_reset();
 	} else if ((RD4(sc, RST_SR) & RST_SR_NRSTL)) {
 		/* User released the button in less than RST_TIMEOUT */
-		sc->shutdown =3D 0;=20
+		sc->shutdown =3D 0;
 		device_printf(sc->sc_dev, "shutting down...\n");
 		shutdown_nice(0);
 	} else {
@@ -167,7 +167,7 @@
 	struct rst_softc *sc =3D argp;
=20
 	if (RD4(sc, RST_SR) & RST_SR_URSTS) {
-		if (sc->shutdown =3D=3D 0)=20
+		if (sc->shutdown =3D=3D 0)
 			callout_reset(&sc->tick_ch, hz/RST_TICK, rst_tick, sc);
 		return (FILTER_HANDLED);
 	}
@@ -177,7 +177,7 @@
 static device_method_t at91_rst_methods[] =3D {
 	DEVMETHOD(device_probe, at91_rst_probe),
 	DEVMETHOD(device_attach, at91_rst_attach),
-	{0,0},
+	DEVMETHOD_END
 };
=20
 static driver_t at91_rst_driver =3D {
@@ -188,7 +188,8 @@
=20
 static devclass_t at91_rst_devclass;
=20
-DRIVER_MODULE(at91_rst, atmelarm, at91_rst_driver, at91_rst_devclass, 0, 0=
);
+DRIVER_MODULE(at91_rst, atmelarm, at91_rst_driver, at91_rst_devclass, NULL,
+    NULL);
=20
 void cpu_reset_sam9g20(void) __attribute__((weak));
 void cpu_reset_sam9g20(void) {}
@@ -198,7 +199,6 @@
 {
=20
 	if (rst_sc) {
-
 		cpu_reset_sam9g20(); /* May be null */
=20
 		WR4(rst_sc, RST_MR,
@@ -211,5 +211,6 @@
 		    RST_CR_KEY);
 	}
=20
-	for(;;) ;
+	for(;;)
+		;
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_twi.c
--- a/head/sys/arm/at91/at91_twi.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_twi.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/arm/at91/at91_twi.c 225882 2011-09-30 04:55:2=
3Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/arm/at91/at91_twi.c 234293 2012-04-14 17:27:3=
4Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -46,9 +46,9 @@
 #include <dev/iicbus/iicbus.h>
 #include "iicbus_if.h"
=20
-#define TWI_SLOW_CLOCK		 1500
-#define TWI_FAST_CLOCK 		45000
-#define TWI_FASTEST_CLOCK	90000
+#define	TWI_SLOW_CLOCK		 1500
+#define	TWI_FAST_CLOCK		45000
+#define	TWI_FASTEST_CLOCK	90000
=20
 struct at91_twi_softc
 {
@@ -67,24 +67,26 @@
 static inline uint32_t
 RD4(struct at91_twi_softc *sc, bus_size_t off)
 {
+
 	return bus_read_4(sc->mem_res, off);
 }
=20
 static inline void
 WR4(struct at91_twi_softc *sc, bus_size_t off, uint32_t val)
 {
+
 	bus_write_4(sc->mem_res, off, val);
 }
=20
-#define AT91_TWI_LOCK(_sc)		mtx_lock(&(_sc)->sc_mtx)
+#define	AT91_TWI_LOCK(_sc)		mtx_lock(&(_sc)->sc_mtx)
 #define	AT91_TWI_UNLOCK(_sc)		mtx_unlock(&(_sc)->sc_mtx)
-#define AT91_TWI_LOCK_INIT(_sc) \
+#define	AT91_TWI_LOCK_INIT(_sc) \
 	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->dev), \
 	    "twi", MTX_DEF)
-#define AT91_TWI_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
-#define AT91_TWI_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED);
-#define AT91_TWI_ASSERT_UNLOCKED(_sc) mtx_assert(&_sc->sc_mtx, MA_NOTOWNED=
);
-#define TWI_DEF_CLK	100000
+#define	AT91_TWI_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx);
+#define	AT91_TWI_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED);
+#define	AT91_TWI_ASSERT_UNLOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_NOTOWNED=
);
+#define	TWI_DEF_CLK	100000
=20
 static devclass_t at91_twi_devclass;
=20
@@ -102,6 +104,7 @@
 static int
 at91_twi_probe(device_t dev)
 {
+
 	device_set_desc(dev, "TWI");
 	return (0);
 }
@@ -361,6 +364,7 @@
 					goto out;
 				WR4(sc, TWI_THR, *buf++);
 			}
+			WR4(sc, TWI_CR, TWI_CR_STOP);
 		}
 		if ((err =3D at91_twi_wait(sc, TWI_SR_TXCOMP)))
 			break;
@@ -385,7 +389,7 @@
 	DEVMETHOD(iicbus_callback,	at91_twi_callback),
 	DEVMETHOD(iicbus_reset,		at91_twi_rst_card),
 	DEVMETHOD(iicbus_transfer,	at91_twi_transfer),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t at91_twi_driver =3D {
@@ -394,6 +398,7 @@
 	sizeof(struct at91_twi_softc),
 };
=20
-DRIVER_MODULE(at91_twi, atmelarm, at91_twi_driver, at91_twi_devclass, 0, 0=
);
-DRIVER_MODULE(iicbus, at91_twi, iicbus_driver, iicbus_devclass, 0, 0);
+DRIVER_MODULE(at91_twi, atmelarm, at91_twi_driver, at91_twi_devclass, NULL,
+    NULL);
+DRIVER_MODULE(iicbus, at91_twi, iicbus_driver, iicbus_devclass, NULL, NULL=
);
 MODULE_DEPEND(at91_twi, iicbus, 1, 1, 1);
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_twireg.h
--- a/head/sys/arm/at91/at91_twireg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_twireg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,64 +23,64 @@
  * SUCH DAMAGE.
  */
=20
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/arm/at91/at91_twireg.h 234291 2012-04-14 17:09:38Z m=
arius $ */
=20
 #ifndef ARM_AT91_AT91_TWIREG_H
-#define ARM_AT91_AT91_TWIREG_H
+#define	ARM_AT91_AT91_TWIREG_H
=20
-#define TWI_CR		0x00		/* TWI Control Register */
-#define TWI_MMR		0x04		/* TWI Master Mode Register */
-#define TWI_SMR		0x08		/* TWI Master Mode Register */
-#define TWI_IADR	0x0c		/* TWI Internal Address Register */
-#define TWI_CWGR	0x10		/* TWI Clock Waveform Generator Reg */
+#define	TWI_CR		0x00		/* TWI Control Register */
+#define	TWI_MMR		0x04		/* TWI Master Mode Register */
+#define	TWI_SMR		0x08		/* TWI Master Mode Register */
+#define	TWI_IADR	0x0c		/* TWI Internal Address Register */
+#define	TWI_CWGR	0x10		/* TWI Clock Waveform Generator Reg */
 		/*	0x14		   reserved */
 		/*	0x18		   reserved */
 		/*	0x1c		   reserved */
-#define TWI_SR		0x20		/* TWI Status Register */
-#define TWI_IER		0x24		/* TWI Interrupt Enable Register */
-#define TWI_IDR		0x28		/* TWI Interrupt Disable Register */
-#define TWI_IMR		0x2c		/* TWI Interrupt Mask Register */
-#define TWI_RHR		0x30		/* TWI Receiver Holding Register */
-#define TWI_THR		0x34		/* TWI Transmit Holding Register */
+#define	TWI_SR		0x20		/* TWI Status Register */
+#define	TWI_IER		0x24		/* TWI Interrupt Enable Register */
+#define	TWI_IDR		0x28		/* TWI Interrupt Disable Register */
+#define	TWI_IMR		0x2c		/* TWI Interrupt Mask Register */
+#define	TWI_RHR		0x30		/* TWI Receiver Holding Register */
+#define	TWI_THR		0x34		/* TWI Transmit Holding Register */
=20
 /* TWI_CR */
-#define TWI_CR_START	(1U << 0)	/* Send a start */
-#define TWI_CR_STOP	(1U << 1)	/* Send a stop */
-#define TWI_CR_MSEN	(1U << 2)	/* Master Transfer Enable */
-#define TWI_CR_MSDIS	(1U << 3)	/* Master Transfer Disable */
-#define TWI_CR_SVEN	(1U << 4)	/* Slave Transfer Enable */
-#define TWI_CR_SVDIS	(1U << 5)	/* Slave Transfer Disable */
-#define TWI_CR_SWRST	(1U << 7)	/* Software Reset */
+#define	TWI_CR_START	(1U << 0)	/* Send a start */
+#define	TWI_CR_STOP	(1U << 1)	/* Send a stop */
+#define	TWI_CR_MSEN	(1U << 2)	/* Master Transfer Enable */
+#define	TWI_CR_MSDIS	(1U << 3)	/* Master Transfer Disable */
+#define	TWI_CR_SVEN	(1U << 4)	/* Slave Transfer Enable */
+#define	TWI_CR_SVDIS	(1U << 5)	/* Slave Transfer Disable */
+#define	TWI_CR_SWRST	(1U << 7)	/* Software Reset */
=20
 /* TWI_MMR */
 /* TWI_SMR */
-#define TWI_MMR_IADRSZ(n) ((n) << 8)	/* Set size of transfer */
-#define TWI_MMR_MWRITE	0U		/* Master Read Direction */
-#define TWI_MMR_MREAD	(1U << 12)	/* Master Read Direction */
-#define TWI_MMR_DADR(n)	((n) << 15)	/* Device Address */
+#define	TWI_MMR_IADRSZ(n) ((n) << 8)	/* Set size of transfer */
+#define	TWI_MMR_MWRITE	0U		/* Master Read Direction */
+#define	TWI_MMR_MREAD	(1U << 12)	/* Master Read Direction */
+#define	TWI_MMR_DADR(n)	((n) << 15)	/* Device Address */
=20
 /* TWI_CWGR */
-#define TWI_CWGR_CKDIV(x) ((x) << 16)	/* Clock Divider */
-#define TWI_CWGR_CHDIV(x) ((x) << 8)	/* Clock High Divider */
-#define TWI_CWGR_CLDIV(x) ((x) << 0)	/* Clock Low Divider */
-#define TWI_CWGR_DIV(rate) 		 		\
-	(at91_is_sam9() ? 				\
-	    ((at91_master_clock /(4*(rate))) - 3) :	\
-	    ((at91_master_clock /(4*(rate))) - 2))
+#define	TWI_CWGR_CKDIV(x) ((x) << 16)	/* Clock Divider */
+#define	TWI_CWGR_CHDIV(x) ((x) << 8)	/* Clock High Divider */
+#define	TWI_CWGR_CLDIV(x) ((x) << 0)	/* Clock Low Divider */
+#define	TWI_CWGR_DIV(rate) 		 		\
+	(at91_is_sam9() || at91_is_sam9xe() ?		\
+	    ((at91_master_clock / (4 * (rate))) - 3) :	\
+	    ((at91_master_clock / (4 * (rate))) - 2))
=20
 /* TWI_SR */
 /* TWI_IER */
 /* TWI_IDR */
 /* TWI_IMR */
-#define TWI_SR_TXCOMP	(1U << 0)	/* Transmission Completed */
-#define TWI_SR_RXRDY	(1U << 1)	/* Receive Holding Register Ready */
-#define TWI_SR_TXRDY	(1U << 2)	/* Transmit Holding Register Ready */
-#define TWI_SR_SVREAD	(1U << 3)	/* Slave Read */
-#define TWI_SR_SVACC	(1U << 4)	/* Slave Access */
-#define TWI_SR_GCACC	(1U << 5)	/* General Call Access */
-#define TWI_SR_OVRE	(1U << 6)	/* Overrun error */
-#define TWI_SR_UNRE	(1U << 7)	/* Underrun Error */
-#define TWI_SR_NACK	(1U << 8)	/* Not Acknowledged */
-#define TWI_SR_ARBLST	(1U << 9)	/* Arbitration Lost */
+#define	TWI_SR_TXCOMP	(1U << 0)	/* Transmission Completed */
+#define	TWI_SR_RXRDY	(1U << 1)	/* Receive Holding Register Ready */
+#define	TWI_SR_TXRDY	(1U << 2)	/* Transmit Holding Register Ready */
+#define	TWI_SR_SVREAD	(1U << 3)	/* Slave Read */
+#define	TWI_SR_SVACC	(1U << 4)	/* Slave Access */
+#define	TWI_SR_GCACC	(1U << 5)	/* General Call Access */
+#define	TWI_SR_OVRE	(1U << 6)	/* Overrun error */
+#define	TWI_SR_UNRE	(1U << 7)	/* Underrun Error */
+#define	TWI_SR_NACK	(1U << 8)	/* Not Acknowledged */
+#define	TWI_SR_ARBLST	(1U << 9)	/* Arbitration Lost */
=20
 #endif /* ARM_AT91_AT91_TWIREG_H */
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91_wdt.c
--- a/head/sys/arm/at91/at91_wdt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91_wdt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,13 +24,13 @@
  */
=20
 /*
- * The sam9 watchdog hardware can be programed only once. So we set the ha=
rdware
- * watchdog to 16s in wdt_attach and only reset it in the wdt_tick
- * handler. The watchdog is halted in processor debug mode.
+ * The SAM9 watchdog hardware can be programed only once. So we set the
+ * hardware watchdog to 16 s in wdt_attach and only reset it in the wdt_ti=
ck
+ * handler.  The watchdog is halted in processor debug mode.
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/arm/at91/at91_wdt.c 221025 2011-04-25 18:15:4=
5Z cognet $");
+__FBSDID("$FreeBSD: head/sys/arm/at91/at91_wdt.c 234291 2012-04-14 17:09:3=
8Z marius $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -52,19 +52,21 @@
 	struct callout	tick_ch;
 	eventhandler_tag sc_wet;
 	void		*intrhand;
-	u_int 		cmd;
-	u_int 		interval;
+	u_int		cmd;
+	u_int		interval;
 };
=20
 static inline uint32_t
 RD4(struct wdt_softc *sc, bus_size_t off)
 {
+
 	return (bus_read_4(sc->mem_res, off));
 }
=20
 static inline void
 WR4(struct wdt_softc *sc, bus_size_t off, uint32_t val)
 {
+
 	bus_write_4(sc->mem_res, off, val);
 }
=20
@@ -130,7 +132,7 @@
 wdt_probe(device_t dev)
 {
=20
-	if (at91_is_sam9()) {
+	if (at91_is_sam9() || at91_is_sam9xe()) {
 		device_set_desc(dev, "WDT");
 		return (0);
 	}
@@ -157,7 +159,7 @@
 	    RF_ACTIVE);
=20
 	if (sc->mem_res =3D=3D NULL)
-	       panic("couldn't allocate wdt register resources");
+		panic("couldn't allocate wdt register resources");
=20
 	wdt_mr =3D RD4(sc, WDT_MR);
 	if ((wdt_mr & WDT_WDRSTEN) =3D=3D 0)
@@ -172,9 +174,11 @@
 		WR4(sc, WDT_MR, WDT_WDDBGHLT | WDT_WDD(0xC00)|
 		    WDT_WDFIEN| WDT_WDV(0xFFF));
 #endif
-		/* This may have been set by Boot ROM so register value
-		 * may not be  what we just requested since this is a
-		 * write once register. */
+		/*
+		 * This may have been set by Boot ROM so register value may
+		 * not be what we just requested since this is a write once
+		 * register.
+		 */
 		wdt_mr =3D RD4(sc, WDT_MR);
 		if (wdt_mr & WDT_WDFIEN) {
 			rid =3D 0;
@@ -184,15 +188,15 @@
 				panic("could not allocate interrupt.\n");
=20
 			err =3D bus_setup_intr(dev, irq, INTR_TYPE_CLK, wdt_intr,
-				NULL, sc, &sc->intrhand);
+			    NULL, sc, &sc->intrhand);
 		}
=20
 		/* interval * hz */
 		sc->interval =3D (((wdt_mr & WDT_WDV(~0)) + 1) * WDT_DIV) /
-			(WDT_CLOCK/hz);
+		    (WDT_CLOCK/hz);
=20
 		device_printf(dev, "watchdog timeout: %d seconds\n",
-		     sc->interval/hz);
+		    sc->interval / hz);
=20
 		/* Slightly less than 1/2 of watchdog hardware timeout */
 		sc->interval =3D (sc->interval/2) - (sc->interval/20);
@@ -208,7 +212,7 @@
 static device_method_t wdt_methods[] =3D {
 	DEVMETHOD(device_probe, wdt_probe),
 	DEVMETHOD(device_attach, wdt_attach),
-	{0,0},
+	DEVMETHOD_END
 };
=20
 static driver_t wdt_driver =3D {
@@ -219,4 +223,4 @@
=20
 static devclass_t wdt_devclass;
=20
-DRIVER_MODULE(at91_wdt, atmelarm, wdt_driver, wdt_devclass, 0, 0);
+DRIVER_MODULE(at91_wdt, atmelarm, wdt_driver, wdt_devclass, NULL, NULL);
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91reg.h
--- a/head/sys/arm/at91/at91reg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91reg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,47 +24,51 @@
  */
=20
 /*
- * $FreeBSD$
+ * $FreeBSD: head/sys/arm/at91/at91reg.h 234291 2012-04-14 17:09:38Z mariu=
s $
  */
=20
 #ifndef _AT91REG_H_
-#define _AT91REG_H_
+#define	_AT91REG_H_
=20
 #include "opt_at91.h"
=20
 /* Where builtin peripherals start in KVM */
-#define AT91_BASE		0xd0000000
+#define	AT91_BASE		0xd0000000
=20
 /* A few things that we count on being the same
  * throught the whole family of SOCs */
=20
 /* SYSC System Controler */
 /* System Registers */
-#define AT91_SYS_BASE	0xffff000
-#define AT91_SYS_SIZE	0x1000
+#define	AT91_SYS_BASE	0xffff000
+#define	AT91_SYS_SIZE	0x1000
=20
 #if defined(AT91SAM9G45) || defined(AT91SAM9263)
-#define AT91_DBGU_BASE	0xfffee00
+#define	AT91_DBGU_BASE	0xfffee00
 #else
-#define AT91_DBGU_BASE	0xffff200
+#define	AT91_DBGU_BASE	0xffff200
 #endif
-#define AT91_DBGU_SIZE	0x200
-#define DBGU_C1R		(64) /* Chip ID1 Register */
-#define DBGU_C2R		(68) /* Chip ID2 Register */
-#define DBGU_FNTR		(72) /* Force NTRST Register */
+#define	AT91_DBGU_SIZE	0x200
+#define	DBGU_C1R		(64) /* Chip ID1 Register */
+#define	DBGU_C2R		(68) /* Chip ID2 Register */
+#define	DBGU_FNTR		(72) /* Force NTRST Register */
=20
-#define AT91_CPU_VERSION_MASK 0x0000001f
-#define AT91_CPU_RM9200   0x09290780
-#define AT91_CPU_SAM9260  0x019803a0
-#define AT91_CPU_SAM9261  0x019703a0
-#define AT91_CPU_SAM9263  0x019607a0
-#define AT91_CPU_SAM9G10  0x819903a0
-#define AT91_CPU_SAM9G20  0x019905a0
-#define AT91_CPU_SAM9G45  0x819b05a0
+#define	AT91_CPU_VERSION_MASK	0x0000001f
+#define	AT91_CPU_RM9200   	0x09290780
+#define	AT91_CPU_SAM9260  	0x019803a0
+#define	AT91_CPU_SAM9261  	0x019703a0
+#define	AT91_CPU_SAM9263  	0x019607a0
+#define	AT91_CPU_SAM9G10  	0x819903a0
+#define	AT91_CPU_SAM9G20  	0x019905a0
+#define	AT91_CPU_SAM9G45  	0x819b05a0
+#define	AT91_CPU_SAM9XE128	0x329973a0
+#define	AT91_CPU_SAM9XE256	0x329a93a0
+#define	AT91_CPU_SAM9XE512	0x329aa3a0
=20
-#define AT91_ARCH(chipid)  ((chipid >> 20) & 0xff)
-#define AT91_CPU(chipid)   (chipid & ~AT91_CPU_VERSION_MASK)
-#define AT91_ARCH_SAM9  (0x19)
-#define AT91_ARCH_RM92  (0x92)
+#define	AT91_ARCH(chipid)	((chipid >> 20) & 0xff)
+#define	AT91_CPU(chipid)	(chipid & ~AT91_CPU_VERSION_MASK)
+#define	AT91_ARCH_SAM9		(0x19)
+#define	AT91_ARCH_SAM9XE	(0x29)
+#define	AT91_ARCH_RM92		(0x92)
=20
 #endif /* _AT91REG_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91sam9260.c
--- a/head/sys/arm/at91/at91sam9260.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91sam9260.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/arm/at91/at91sam9260.c 234291 2012-04-14 17:0=
9:38Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -93,7 +93,7 @@
 	0,	/* Advanced Interrupt Controller IRQ2 */
 };
=20
-#define DEVICE(_name, _id, _unit)		\
+#define	DEVICE(_name, _id, _unit)		\
 	{					\
 		_name, _unit,			\
 		AT91SAM9260_ ## _id ##_BASE,	\
@@ -157,7 +157,7 @@
 		bus_set_resource(kid, SYS_RES_IRQ, 1, irq1, 1);
 	if (irq2 !=3D 0)
 		bus_set_resource(kid, SYS_RES_IRQ, 2, irq2, 1);
-	if (addr !=3D 0 && addr < AT91SAM9260_BASE)=20
+	if (addr !=3D 0 && addr < AT91SAM9260_BASE)
 		addr +=3D AT91SAM9260_BASE;
 	if (addr !=3D 0)
 		bus_set_resource(kid, SYS_RES_MEMORY, 0, addr, size);
@@ -182,13 +182,14 @@
=20
 	if (freq > 195000000)
 		return (0x20000000);
-	else=20
+	else
 		return (0x20008000);
 }
=20
 static uint32_t
 at91_pll_outb(int freq)
 {
+
 	return (0x4000);
 }
=20
@@ -196,21 +197,40 @@
 at91_identify(driver_t *drv, device_t parent)
 {
=20
-	if (at91_cpu_is(AT91_CPU_SAM9260)) {
+	switch (AT91_CPU(at91_chip_id)) {
+	case AT91_CPU_SAM9260:
+	case AT91_CPU_SAM9XE128:
+	case AT91_CPU_SAM9XE256:
+	case AT91_CPU_SAM9XE512:
 		at91_add_child(parent, 0, "at91sam9260", 0, 0, 0, -1, 0, 0);
 		at91_cpu_add_builtin_children(parent);
+		break;
 	}
 }
=20
 static int
 at91_probe(device_t dev)
 {
+	const char *desc;
=20
-	if (at91_cpu_is(AT91_CPU_SAM9260)) {
-		device_set_desc(dev, "AT91SAM9260");
-		return (0);
+	switch (AT91_CPU(at91_chip_id)) {
+	case AT91_CPU_SAM9260:
+		desc =3D "AT91SAM9260";
+		break;
+	case AT91_CPU_SAM9XE128:
+		desc =3D "AT91SAM9XE128";
+		break;
+	case AT91_CPU_SAM9XE256:
+		desc =3D "AT91SAM9XE256";
+		break;
+	case AT91_CPU_SAM9XE512:
+		desc =3D "AT91SAM9XE512";
+		break;
+	default:
+		return (ENXIO);
 	}
-	return (ENXIO);
+	device_set_desc(dev, desc);
+	return (0);
 }
=20
 static int
@@ -226,10 +246,6 @@
 	sc->sc_sh =3D at91sc->sc_sh;
 	sc->dev =3D dev;
=20
-	/*=20
-	 * XXX These values work for the RM9200, SAM926[01], and SAM9260
-	 * will have to fix this when we want to support anything else. XXX
-	 */
 	if (bus_space_subregion(sc->sc_st, sc->sc_sh, AT91SAM9260_SYS_BASE,
 	    AT91SAM9260_SYS_SIZE, &sc->sc_sys_sh) !=3D 0)
 		panic("Enable to map system registers");
@@ -247,7 +263,7 @@
 	at91sc->sc_irq_system =3D AT91SAM9260_IRQ_SYSTEM;
=20
 	for (i =3D 0; i < 32; i++) {
-		bus_space_write_4(sc->sc_st, sc->sc_aic_sh, IC_SVR +=20
+		bus_space_write_4(sc->sc_st, sc->sc_aic_sh, IC_SVR +
 		    i * 4, i);
 		/* Priority. */
 		bus_space_write_4(sc->sc_st, sc->sc_aic_sh, IC_SMR + i * 4,
@@ -276,10 +292,9 @@
 	i =3D bus_space_read_4(sc->sc_st, sc->sc_matrix_sh,
 	    AT91SAM9260_EBICSA);
 	bus_space_write_4(sc->sc_st, sc->sc_matrix_sh,
-	    AT91SAM9260_EBICSA,=20
+	    AT91SAM9260_EBICSA,
 	    i | AT91_MATRIX_EBI_CS3A_SMC_SMARTMEDIA);
=20
-
 	/* Update USB device port clock info */
 	clk =3D at91_pmc_clock_ref("udpck");
 	clk->pmc_mask  =3D PMC_SCER_UDP_SAM9;
@@ -304,11 +319,12 @@
 	at91_pmc_clock_deref(clk);
=20
 	/*
-	 * Fudge MAX pll in frequence down below 3.0 Mhz to ensure=20
-	 * PMC alogrithm choose the divisor that causes the input clock=20
-	 * to be near the optimal 2 Mhz per datasheet. We know
-	 * we are going to be using this for the USB clock at 96 Mhz.
-	 * Causes no extra frequency deviation for all recomended crystal values.
+	 * Fudge MAX pll in frequence down below 3.0 MHz to ensure
+	 * PMC alogrithm choose the divisor that causes the input clock
+	 * to be near the optimal 2 MHz per datasheet.  We know
+	 * we are going to be using this for the USB clock at 96 MHz.
+	 * Causes no extra frequency deviation for all recomended crystal
+	 * values.
 	 */
 	clk =3D at91_pmc_clock_ref("pllb");
 	clk->pll_min_in    =3D SAM9260_PLL_B_MIN_IN_FREQ;		/*   1 MHz */
@@ -329,7 +345,7 @@
 	DEVMETHOD(device_probe, at91_probe),
 	DEVMETHOD(device_attach, at91_attach),
 	DEVMETHOD(device_identify, at91_identify),
-	{0, 0},
+	DEVMETHOD_END
 };
=20
 static driver_t at91sam9260_driver =3D {
@@ -340,4 +356,5 @@
=20
 static devclass_t at91sam9260_devclass;
=20
-DRIVER_MODULE(at91sam9260, atmelarm, at91sam9260_driver, at91sam9260_devcl=
ass, 0, 0);
+DRIVER_MODULE(at91sam9260, atmelarm, at91sam9260_driver, at91sam9260_devcl=
ass,
+    NULL, NULL);
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/at91var.h
--- a/head/sys/arm/at91/at91var.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/at91var.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/arm/at91/at91var.h 234291 2012-04-14 17:09:38Z mariu=
s $ */
=20
 #ifndef _AT91VAR_H_
 #define _AT91VAR_H_
@@ -62,24 +62,35 @@
 extern uint32_t at91_chip_id;
=20
 static inline int at91_is_rm92(void);
-static inline int at91_is_sam9(void) ;
+static inline int at91_is_sam9(void);
+static inline int at91_is_sam9xe(void);
 static inline int at91_cpu_is(u_int cpu);
=20
-static inline int=20
-at91_is_rm92(void)=20
+static inline int
+at91_is_rm92(void)
 {
+
 	return (AT91_ARCH(at91_chip_id) =3D=3D AT91_ARCH_RM92);
 }
=20
-static inline int=20
-at91_is_sam9(void)=20
+static inline int
+at91_is_sam9(void)
 {
+
 	return (AT91_ARCH(at91_chip_id) =3D=3D AT91_ARCH_SAM9);
 }
=20
-static inline int=20
+static inline int
+at91_is_sam9xe(void)
+{
+
+	return (AT91_ARCH(at91_chip_id) =3D=3D AT91_ARCH_SAM9XE);
+}
+
+static inline int
 at91_cpu_is(u_int cpu)
 {
+
 	return (AT91_CPU(at91_chip_id) =3D=3D cpu);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/at91/if_ate.c
--- a/head/sys/arm/at91/if_ate.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/at91/if_ate.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/arm/at91/if_ate.c 234291 2012-04-14 17:09:38Z=
 marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -120,38 +120,38 @@
=20
 struct ate_softc
 {
-	struct ifnet    *ifp;           /* ifnet pointer */
-	struct mtx      sc_mtx;         /* Basically a perimeter lock */
-	device_t        dev;            /* Myself */
-	device_t        miibus;         /* My child miibus */
-	struct resource *irq_res;       /* IRQ resource */
-	struct resource	*mem_res;       /* Memory resource */
-	struct callout  tick_ch;        /* Tick callout */
+	struct ifnet	*ifp;		/* ifnet pointer */
+	struct mtx	sc_mtx;		/* Basically a perimeter lock */
+	device_t	dev;		/* Myself */
+	device_t	miibus;		/* My child miibus */
+	struct resource *irq_res;	/* IRQ resource */
+	struct resource	*mem_res;	/* Memory resource */
+	struct callout  tick_ch;	/* Tick callout */
 	struct ifmib_iso_8802_3 mibdata; /* Stuff for network mgmt */
-	bus_dma_tag_t   mtag;           /* bus dma tag for mbufs */
+	bus_dma_tag_t   mtag;		/* bus dma tag for mbufs */
 	bus_dma_tag_t   rx_tag;
 	bus_dma_tag_t   rx_desc_tag;
 	bus_dmamap_t    rx_desc_map;
 	bus_dmamap_t    rx_map[ATE_MAX_RX_DESCR];
-	bus_addr_t      rx_desc_phys;   /* PA of rx descriptors */
-	eth_rx_desc_t   *rx_descs;      /* VA of rx descriptors */
-	void            *rx_buf[ATE_NUM_RX_DESCR]; /* RX buffer space */
-	int             rxhead;         /* Current RX map/desc index */
-	uint32_t        rx_buf_size;    /* Size of Rx buffers */
+	bus_addr_t	rx_desc_phys;   /* PA of rx descriptors */
+	eth_rx_desc_t   *rx_descs;	/* VA of rx descriptors */
+	void		*rx_buf[ATE_NUM_RX_DESCR]; /* RX buffer space */
+	int		rxhead;		/* Current RX map/desc index */
+	uint32_t	rx_buf_size;    /* Size of Rx buffers */
=20
 	bus_dma_tag_t   tx_desc_tag;
 	bus_dmamap_t    tx_desc_map;
 	bus_dmamap_t    tx_map[ATE_MAX_TX_BUFFERS];
-	bus_addr_t      tx_desc_phys;   /* PA of tx descriptors */
-	eth_tx_desc_t   *tx_descs;      /* VA of tx descriptors */
-	int             txhead;         /* Current TX map/desc index */
-	int             txtail;         /* Current TX map/desc index */
-	struct mbuf     *sent_mbuf[ATE_MAX_TX_BUFFERS]; /* Sent mbufs */
-	void            *intrhand;      /* Interrupt handle */
-	int             flags;
-	int             if_flags;
-	int             use_rmii;
-	int              is_emacb;       /* SAM9x hardware version */
+	bus_addr_t	tx_desc_phys;   /* PA of tx descriptors */
+	eth_tx_desc_t   *tx_descs;	/* VA of tx descriptors */
+	int		txhead;		/* Current TX map/desc index */
+	int		txtail;		/* Current TX map/desc index */
+	struct mbuf	*sent_mbuf[ATE_MAX_TX_BUFFERS]; /* Sent mbufs */
+	void		*intrhand;	/* Interrupt handle */
+	int		flags;
+	int		if_flags;
+	int		use_rmii;
+	int		is_emacb;	/* SAM9x hardware version */
 };
=20
 static inline uint32_t
@@ -247,7 +247,7 @@
 	sc =3D device_get_softc(dev);
 	sc->dev =3D dev;
 	ATE_LOCK_INIT(sc);
-=09
+
 	rid =3D 0;
 	sc->mem_res =3D bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
 	    RF_ACTIVE);
@@ -266,7 +266,7 @@
 	}
=20
 	/* New or old version, chooses buffer size. */
-	sc->is_emacb    =3D at91_is_sam9();
+	sc->is_emacb =3D at91_is_sam9() || at91_is_sam9xe();
 	sc->rx_buf_size =3D RX_BUF_SIZE(sc);
=20
 	err =3D ate_activate(dev);
@@ -325,8 +325,8 @@
 		goto out;
 	}
 	/*
-	 * XXX: Clear the isolate bit, or we won't get up,=20
-	 * at least on the HL201=20
+	 * XXX: Clear the isolate bit, or we won't get up,
+	 * at least on the HL201
 	 */
 	ate_miibus_writereg(dev, 0, 0, 0x3000);
=20
@@ -750,7 +750,7 @@
 		active =3D mii->mii_media_active;
 		mii_tick(mii);
 		if (mii->mii_media_status & IFM_ACTIVE &&
-		     active !=3D mii->mii_media_active)
+		    active !=3D mii->mii_media_active)
 			ate_stat_update(sc, mii->mii_media_active);
 	}
=20
@@ -966,7 +966,7 @@
=20
 		ATE_LOCK(sc);
 		/* XXX TSR register should be cleared */
-		if (!sc->is_emacb) {=09
+		if (!sc->is_emacb) {
 			/* Simulate Transmit descriptor table */
=20
 			/* First packet done */
@@ -1055,7 +1055,7 @@
 	} else  {
 		/* SAM9 */
 		reg =3D ETHB_UIO_CLKE;
-		reg |=3D (sc->use_rmii) ?  ETHB_UIO_RMII : 0;
+		reg |=3D (sc->use_rmii) ? ETHB_UIO_RMII : 0;
 		WR4(sc, ETHB_UIO, reg);
 	}
=20
@@ -1170,7 +1170,7 @@
 			WR4(sc, ETH_CTL, RD4(sc, ETH_CTL) | ETHB_CTL_TGO);
 		}
 		sc->txhead =3D NEXT_TX_IDX(sc, sc->txhead);
-=09
+
 		/* Tap off here if there is a bpf listener. */
 		BPF_MTAP(ifp, m);
 	}
@@ -1315,7 +1315,7 @@
 {
 	struct ate_softc *sc =3D ifp->if_softc;
 	struct mii_data *mii;
-	struct ifreq *ifr =3D (struct ifreq *)data;=09
+	struct ifreq *ifr =3D (struct ifreq *)data;
 	int drv_flags, flags;
 	int mask, error, enabled;
=20
@@ -1416,7 +1416,7 @@
 ate_miibus_writereg(device_t dev, int phy, int reg, int data)
 {
 	struct ate_softc *sc;
-=09
+
 	/*
 	 * XXX if we implement agressive power savings, then we need
 	 * XXX to make sure that the clock to the emac is on here
@@ -1442,7 +1442,7 @@
 	DEVMETHOD(miibus_readreg,	ate_miibus_readreg),
 	DEVMETHOD(miibus_writereg,	ate_miibus_writereg),
=20
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t ate_driver =3D {
@@ -1451,7 +1451,7 @@
 	sizeof(struct ate_softc),
 };
=20
-DRIVER_MODULE(ate, atmelarm, ate_driver, ate_devclass, 0, 0);
-DRIVER_MODULE(miibus, ate, miibus_driver, miibus_devclass, 0, 0);
+DRIVER_MODULE(ate, atmelarm, ate_driver, ate_devclass, NULL, NULL);
+DRIVER_MODULE(miibus, ate, miibus_driver, miibus_devclass, NULL, NULL);
 MODULE_DEPEND(ate, miibus, 1, 1, 1);
 MODULE_DEPEND(ate, ether, 1, 1, 1);
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/AVILA
--- a/head/sys/arm/conf/AVILA	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/AVILA	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/AVILA 224699 2011-08-07 20:16:46Z rmacklem $
+# $FreeBSD: head/sys/arm/conf/AVILA 233271 2012-03-21 08:38:42Z ed $
=20
 ident		AVILA
=20
@@ -103,7 +103,6 @@
 device		ether
 device		bpf
=20
-device		pty
 device		loop
 device		if_bridge
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/BWCT
--- a/head/sys/arm/conf/BWCT	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/BWCT	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/BWCT 224699 2011-08-07 20:16:46Z rmacklem $
+# $FreeBSD: head/sys/arm/conf/BWCT 233271 2012-03-21 08:38:42Z ed $
=20
 ident		BWCT
=20
@@ -72,7 +72,6 @@
 device		random
 device		ether
 device		vlan
-device		pty
 device		uart
 device		ate
 device		mii
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/CAMBRIA
--- a/head/sys/arm/conf/CAMBRIA	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/CAMBRIA	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/CAMBRIA 224699 2011-08-07 20:16:46Z rmacklem=
 $
+# $FreeBSD: head/sys/arm/conf/CAMBRIA 233271 2012-03-21 08:38:42Z ed $
=20
 ident		CAMBRIA
=20
@@ -106,7 +106,6 @@
 device		ether
 device		bpf
=20
-device		pty
 device		loop
 device		if_bridge
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/CNS11XXNAS
--- a/head/sys/arm/conf/CNS11XXNAS	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/CNS11XXNAS	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/CNS11XXNAS 224699 2011-08-07 20:16:46Z rmack=
lem $
+# $FreeBSD: head/sys/arm/conf/CNS11XXNAS 233271 2012-03-21 08:38:42Z ed $
=20
 ident		CNS11XXNAS
=20
@@ -98,7 +98,6 @@
 device		ether
 device		bpf
=20
-device		pty
 device		loop
=20
 device		md
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/CRB
--- a/head/sys/arm/conf/CRB	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/CRB	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/CRB 224699 2011-08-07 20:16:46Z rmacklem $
+# $FreeBSD: head/sys/arm/conf/CRB 233271 2012-03-21 08:38:42Z ed $
=20
 ident		CRB
=20
@@ -85,7 +85,6 @@
=20
 # SCSI Controllers
=20
-device		pty
 #options 	AHC_REG_PRETTY_PRINT	# Print register bitfields in debug
 					# output.  Adds ~128k to driver.
 #options 	AHD_REG_PRETTY_PRINT	# Print register bitfields in debug
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/DB-78XXX
--- a/head/sys/arm/conf/DB-78XXX	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/DB-78XXX	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # Custom kernel for Marvell DB-78xx boards.
 #
-# $FreeBSD: head/sys/arm/conf/DB-78XXX 224699 2011-08-07 20:16:46Z rmackle=
m $
+# $FreeBSD: head/sys/arm/conf/DB-78XXX 233271 2012-03-21 08:38:42Z ed $
 #
=20
 ident		DB-88F78XX
@@ -53,7 +53,6 @@
 # Pseudo devices
 device		loop
 device		md
-device		pty
 device		random
=20
 # Serial ports
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/DB-88F5XXX
--- a/head/sys/arm/conf/DB-88F5XXX	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/DB-88F5XXX	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # Custom kernel for Marvell DB-88F5xxx boards.
 #
-# $FreeBSD: head/sys/arm/conf/DB-88F5XXX 224699 2011-08-07 20:16:46Z rmack=
lem $
+# $FreeBSD: head/sys/arm/conf/DB-88F5XXX 233271 2012-03-21 08:38:42Z ed $
 #
=20
 ident		DB-88F5XXX
@@ -53,7 +53,6 @@
 # Pseudo devices
 device		md
 device		loop
-device		pty
 device		random
=20
 # Serial ports
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/DB-88F6XXX
--- a/head/sys/arm/conf/DB-88F6XXX	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/DB-88F6XXX	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # Custom kernel for Marvell DB-88F6xxx boards.
 #
-# $FreeBSD: head/sys/arm/conf/DB-88F6XXX 227730 2011-11-19 16:30:06Z raj $
+# $FreeBSD: head/sys/arm/conf/DB-88F6XXX 233271 2012-03-21 08:38:42Z ed $
 #
=20
 ident		DB-88F6XXX
@@ -53,7 +53,6 @@
 # Pseudo devices
 device		loop
 device		md
-device		pty
 device		random
=20
 # Serial ports
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/DOCKSTAR
--- a/head/sys/arm/conf/DOCKSTAR	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/DOCKSTAR	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # Custom kernel for Seagate DockStar (Marvell SheevaPlug based) devices.
 #
-# $FreeBSD: head/sys/arm/conf/DOCKSTAR 224699 2011-08-07 20:16:46Z rmackle=
m $
+# $FreeBSD: head/sys/arm/conf/DOCKSTAR 233271 2012-03-21 08:38:42Z ed $
 #
=20
 ident		DOCKSTAR
@@ -46,7 +46,6 @@
 # Pseudo devices
 device		md
 device		random
-device		pty
 device		loop
=20
 # Serial ports
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/EP80219
--- a/head/sys/arm/conf/EP80219	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/EP80219	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/EP80219 224699 2011-08-07 20:16:46Z rmacklem=
 $
+# $FreeBSD: head/sys/arm/conf/EP80219 233271 2012-03-21 08:38:42Z ed $
=20
 ident		EP80219
=20
@@ -83,7 +83,6 @@
=20
 # SCSI Controllers
=20
-device		pty
 device		iopwdog			# I80321 Watchdog
 device		dma			# I80321 DMA Controller
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/GUMSTIX
--- a/head/sys/arm/conf/GUMSTIX	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/GUMSTIX	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/GUMSTIX 226995 2011-11-01 16:13:59Z marius $
+# $FreeBSD: head/sys/arm/conf/GUMSTIX 233271 2012-03-21 08:38:42Z ed $
=20
 ident		GUMSTIX
 cpu		CPU_XSCALE_PXA2X0
@@ -76,8 +76,6 @@
 device		uart
 device		uart_ns8250
=20
-device		pty
-
 # Debugging for use in -current
 options 	KDB
 options 	DDB			#Enable the kernel debugger
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/HL200
--- a/head/sys/arm/conf/HL200	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/HL200	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/HL200 225482 2011-09-11 17:39:51Z brueffer $
+# $FreeBSD: head/sys/arm/conf/HL200 233271 2012-03-21 08:38:42Z ed $
=20
 ident		HL200
=20
@@ -65,7 +65,6 @@
 options 	NO_FFS_SNAPSHOT
 options 	NO_SWAPPING
 device		random
-device		pty
 device		loop
 device		ether
 device		uart
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/HL201
--- a/head/sys/arm/conf/HL201	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/HL201	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/HL201 225482 2011-09-11 17:39:51Z brueffer $
+# $FreeBSD: head/sys/arm/conf/HL201 233271 2012-03-21 08:38:42Z ed $
=20
 ident		HL201
=20
@@ -67,7 +67,6 @@
 options 	NO_FFS_SNAPSHOT
 options 	NO_SWAPPING
 device		random
-device		pty
 device		loop
 device		ether
 device		uart
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/IQ31244
--- a/head/sys/arm/conf/IQ31244	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/IQ31244	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/IQ31244 224699 2011-08-07 20:16:46Z rmacklem=
 $
+# $FreeBSD: head/sys/arm/conf/IQ31244 233271 2012-03-21 08:38:42Z ed $
=20
 ident		IQ31244
=20
@@ -82,7 +82,6 @@
=20
 # SCSI Controllers
=20
-device		pty
 device		iopwdog			# I80321 Watchdog
 device		dma			# I80321 DMA Controller
 device		aau			# I80321 Application Accelerator Unit
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/KB920X
--- a/head/sys/arm/conf/KB920X	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/KB920X	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/KB920X 229639 2012-01-05 20:18:01Z adrian $
+# $FreeBSD: head/sys/arm/conf/KB920X 233271 2012-03-21 08:38:42Z ed $
=20
 ident		KB920X
=20
@@ -66,7 +66,6 @@
 options 	NO_FFS_SNAPSHOT
 options 	NO_SWAPPING
 device		random
-device		pty
 device		loop
 device		ether
 device		uart
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/LN2410SBC
--- a/head/sys/arm/conf/LN2410SBC	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/LN2410SBC	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/LN2410SBC 224699 2011-08-07 20:16:46Z rmackl=
em $
+# $FreeBSD: head/sys/arm/conf/LN2410SBC 233271 2012-03-21 08:38:42Z ed $
=20
 machine		arm
 ident		LN2410SBC
@@ -63,7 +63,6 @@
 options 	NO_FFS_SNAPSHOT
 options 	NO_SWAPPING
 device		random
-device		pty
=20
 device		loop
 device		ether
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/NSLU
--- a/head/sys/arm/conf/NSLU	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/NSLU	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/NSLU 224699 2011-08-07 20:16:46Z rmacklem $
+# $FreeBSD: head/sys/arm/conf/NSLU 233271 2012-03-21 08:38:42Z ed $
=20
 ident		NSLU
=20
@@ -101,7 +101,6 @@
 device		ether
 device		bpf
=20
-device		pty
 device		loop
=20
 device		md
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/QILA9G20
--- a/head/sys/arm/conf/QILA9G20	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/QILA9G20	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/QILA9G20 225482 2011-09-11 17:39:51Z brueffe=
r $
+# $FreeBSD: head/sys/arm/conf/QILA9G20 233271 2012-03-21 08:38:42Z ed $
=20
 ident		QILA9G20
=20
@@ -77,7 +77,6 @@
 #options 	DIAGNOSTIC
=20
 device		random
-device		pty
 device		loop
 device		bpf
 device		ether
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/SAM9G20EK
--- a/head/sys/arm/conf/SAM9G20EK	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/SAM9G20EK	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/arm/conf/SAM9G20EK 225482 2011-09-11 17:39:51Z brueff=
er $
+# $FreeBSD: head/sys/arm/conf/SAM9G20EK 233271 2012-03-21 08:38:42Z ed $
=20
 ident		SAM9G20EK
=20
@@ -76,7 +76,6 @@
 #options 	DIAGNOSTIC
=20
 device		random
-device		pty
 device		loop
 device		bpf
 device		ether
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/SHEEVAPLUG
--- a/head/sys/arm/conf/SHEEVAPLUG	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/SHEEVAPLUG	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # Custom kernel for Marvell SheevaPlug devices.
 #
-# $FreeBSD: head/sys/arm/conf/SHEEVAPLUG 227730 2011-11-19 16:30:06Z raj $
+# $FreeBSD: head/sys/arm/conf/SHEEVAPLUG 233271 2012-03-21 08:38:42Z ed $
 #
=20
 ident		SHEEVAPLUG
@@ -44,7 +44,6 @@
=20
 # Pseudo devices
 device		random
-device		pty
 device		loop
=20
 # Serial ports
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/conf/TS7800
--- a/head/sys/arm/conf/TS7800	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/conf/TS7800	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # Custom kernel for the TS-7800 board.
 #
-# $FreeBSD: head/sys/arm/conf/TS7800 224699 2011-08-07 20:16:46Z rmacklem $
+# $FreeBSD: head/sys/arm/conf/TS7800 233271 2012-03-21 08:38:42Z ed $
 #
=20
 ident		TS7800
@@ -47,7 +47,6 @@
 # Pseudo devices
 device		md
 device		loop
-device		pty
 device		random
=20
 # Serial ports
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/include/armreg.h
--- a/head/sys/arm/include/armreg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/include/armreg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/arm/include/armreg.h 234337 2012-04-16 09:38:20Z and=
rew $
  */
=20
 #ifndef MACHINE_ARMREG_H
@@ -316,8 +316,13 @@
 /*
  * Address of the vector page, low and high versions.
  */
+#ifndef __ASSEMBLER__
 #define	ARM_VECTORS_LOW		0x00000000U
 #define	ARM_VECTORS_HIGH	0xffff0000U
+#else
+#define	ARM_VECTORS_LOW		0
+#define	ARM_VECTORS_HIGH	0xffff0000
+#endif
=20
 /*
  * ARM Instructions
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/include/pmc_mdep.h
--- a/head/sys/arm/include/pmc_mdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/include/pmc_mdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,13 +23,13 @@
  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  * POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/arm/include/pmc_mdep.h 233628 2012-03-28 20:58:30Z f=
abient $
  */
=20
 #ifndef _MACHINE_PMC_MDEP_H_
 #define	_MACHINE_PMC_MDEP_H_
=20
-#define	PMC_MDEP_CLASS_INDEX_XSCALE	0
+#define	PMC_MDEP_CLASS_INDEX_XSCALE	1
 /*
  * On the ARM platform we support the following PMCs.
  *
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/include/sysarch.h
--- a/head/sys/arm/include/sysarch.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/include/sysarch.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  * SUCH DAMAGE.
  */
=20
-/* $FreeBSD: head/sys/arm/include/sysarch.h 226443 2011-10-16 17:59:28Z co=
gnet $ */
+/* $FreeBSD: head/sys/arm/include/sysarch.h 234337 2012-04-16 09:38:20Z an=
drew $ */
=20
 #ifndef _ARM_SYSARCH_H_
 #define _ARM_SYSARCH_H_
@@ -55,6 +55,7 @@
 #define ARM_RAS_END		(ARM_TP_ADDRESS + 8)
=20
 #ifndef LOCORE
+#ifndef __ASSEMBLER__
=20
 #include <sys/cdefs.h>
=20
@@ -85,6 +86,7 @@
 __END_DECLS
 #endif
=20
+#endif /* __ASSEMBLER__ */
 #endif /* LOCORE */
=20
 #endif /* !_ARM_SYSARCH_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/arm/xscale/pxa/uart_bus_pxa.c
--- a/head/sys/arm/xscale/pxa/uart_bus_pxa.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/arm/xscale/pxa/uart_bus_pxa.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/arm/xscale/pxa/uart_bus_pxa.c 234004 2012-04-=
07 23:47:08Z stas $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -72,12 +72,28 @@
 	bus_space_handle_t	base;
 	struct			uart_softc *sc;
=20
+	base =3D (bus_space_handle_t)pxa_get_base(dev);
+#ifdef QEMU_WORKAROUNDS
+	/*
+	 * QEMU really exposes only the first uart unless
+	 * you specify several of them in the configuration.
+	 * Otherwise all the rest of UARTs stay unconnected,
+	 * which causes problems in the ns16550 attach routine.
+	 * Unfortunately, even if you provide qemu with 4 uarts
+	 * on the command line, it has a bug where it segfaults
+	 * trying to enable bluetooth on the HWUART.  So we just
+	 * allow the FFUART to be attached.
+	 * Also, don't check the UUE (UART Unit Enable) bit, as
+	 * the gumstix bootloader doesn't set it.
+	 */
+	if (base !=3D PXA2X0_FFUART_BASE)
+		return (ENXIO);
+#else
 	/* Check to see if the enable bit's on. */
-	base =3D (bus_space_handle_t)pxa_get_base(dev);
 	if ((bus_space_read_4(obio_tag, base,
 	    (REG_IER << 2)) & PXA_UART_UUE) =3D=3D 0)
 		return (ENXIO);
-
+#endif
 	sc =3D device_get_softc(dev);
 	sc->sc_class =3D &uart_ns8250_class;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/common/crc32.c
--- a/head/sys/boot/common/crc32.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/common/crc32.c	Tue Apr 17 11:51:51 2012 +0300
@@ -43,13 +43,13 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/boot/common/crc32.c 233517 2012-03-26 18:22:0=
4Z marius $");
=20
 #include <sys/types.h>
=20
 #include "crc32.h"
=20
-static uint32_t crc32_tab[] =3D {
+static const uint32_t crc32_tab[] =3D {
 	0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
 	0xe963a535, 0x9e6495a3,	0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
 	0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/common/gpt.c
--- a/head/sys/boot/common/gpt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/common/gpt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/boot/common/gpt.c 234176 2012-04-12 12:37:53Z=
 ae $");
=20
 #include <sys/param.h>
 #include <sys/gpt.h>
@@ -337,16 +337,16 @@
 		gpttable =3D table_primary;
 	}
=20
-	altlba =3D drvsize(dskp);
-	if (altlba > 0)
-		altlba--;
-	else if (hdr_primary_lba > 0) {
+	if (hdr_primary_lba > 0) {
 		/*
-		 * If we cannot obtain disk size, but primary header
-		 * is valid, we can get backup header location from
-		 * there.
+		 * If primary header is valid, we can get backup
+		 * header location from there.
 		 */
 		altlba =3D hdr_primary.hdr_lba_alt;
+	} else {
+		altlba =3D drvsize(dskp);
+		if (altlba > 0)
+			altlba--;
 	}
 	if (altlba =3D=3D 0)
 		printf("%s: unable to locate backup GPT header\n", BOOTPROG);
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/common/loader.8
--- a/head/sys/boot/common/loader.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/common/loader.8	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sys/boot/common/loader.8 229771 2012-01-07 11:16:23Z ki=
b $
+.\" $FreeBSD: head/sys/boot/common/loader.8 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd January 7, 2012
 .Dt LOADER 8
@@ -223,7 +223,7 @@
 .Xr geli 8
 encryption keyfile for the given provider name.
 The key index can be specified via
-.Ar keyno=20
+.Ar keyno
 or will default to zero.
 .Pp
 .It Ic ls Xo
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/fdt/fdt_loader_cmd.c
--- a/head/sys/boot/fdt/fdt_loader_cmd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/fdt/fdt_loader_cmd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,11 +28,14 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/boot/fdt/fdt_loader_cmd.c 233323 2012-03-22 2=
0:34:26Z raj $");
=20
 #include <stand.h>
 #include <fdt.h>
 #include <libfdt.h>
+#include <sys/param.h>
+#include <sys/linker.h>
+#include <machine/elf.h>
=20
 #include "bootstrap.h"
 #include "glue.h"
@@ -54,7 +57,9 @@
 #define STR(number) #number
 #define STRINGIFY(number) STR(number)
=20
-#define MIN(num1, num2)	(((num1) < (num2)) ? (num1):(num2))
+#define COPYOUT(s,d,l)	archsw.arch_copyout((vm_offset_t)(s), d, l)
+
+#define FDT_STATIC_DTB_SYMBOL	"fdt_static_dtb"
=20
 static struct fdt_header *fdtp =3D NULL;
=20
@@ -92,6 +97,91 @@
=20
 static char cwd[FDT_CWD_LEN] =3D "/";
=20
+static vm_offset_t
+fdt_find_static_dtb(void)
+{
+	Elf_Sym sym;
+	vm_offset_t dyntab, esym;
+	uint64_t offs;
+	struct preloaded_file *kfp;
+	struct file_metadata *md;
+	Elf_Sym *symtab;
+	Elf_Dyn *dyn;
+	char *strtab, *strp;
+	int i, sym_count;
+
+	symtab =3D NULL;
+	dyntab =3D esym =3D 0;
+	strtab =3D strp =3D NULL;
+
+	offs =3D __elfN(relocation_offset);
+
+	kfp =3D file_findfile(NULL, NULL);
+	if (kfp =3D=3D NULL)
+		return (0);
+
+	md =3D file_findmetadata(kfp, MODINFOMD_ESYM);
+	if (md =3D=3D NULL)
+		return (0);
+	COPYOUT(md->md_data, &esym, sizeof(esym));
+
+	md =3D file_findmetadata(kfp, MODINFOMD_DYNAMIC);
+	if (md =3D=3D NULL)
+		return (0);
+	COPYOUT(md->md_data, &dyntab, sizeof(dyntab));
+
+	dyntab +=3D offs;
+
+	/* Locate STRTAB and DYNTAB */
+	for (dyn =3D (Elf_Dyn *)dyntab; dyn->d_tag !=3D DT_NULL; dyn++) {
+		if (dyn->d_tag =3D=3D DT_STRTAB) {
+			strtab =3D (char *)(uintptr_t)(dyn->d_un.d_ptr + offs);
+			continue;
+		} else if (dyn->d_tag =3D=3D DT_SYMTAB) {
+			symtab =3D (Elf_Sym *)(uintptr_t)
+			    (dyn->d_un.d_ptr + offs);
+			continue;
+		}
+	}
+
+	if (symtab =3D=3D NULL || strtab =3D=3D NULL) {
+		/*
+		 * No symtab? No strtab? That should not happen here,
+		 * and should have been verified during __elfN(loadimage).
+		 * This must be some kind of a bug.
+		 */
+		return (0);
+	}
+
+	sym_count =3D (int)((Elf_Sym *)esym - symtab) / sizeof(Elf_Sym);
+
+	/*
+	 * The most efficent way to find a symbol would be to calculate a
+	 * hash, find proper bucket and chain, and thus find a symbol.
+	 * However, that would involve code duplication (e.g. for hash
+	 * function). So we're using simpler and a bit slower way: we're
+	 * iterating through symbols, searching for the one which name is
+	 * 'equal' to 'fdt_static_dtb'. To speed up the process a little bit,
+	 * we are eliminating symbols type of which is not STT_NOTYPE, or(and)
+	 * those which binding attribute is not STB_GLOBAL.
+	 */
+	for (i =3D 0; i < sym_count; i++) {
+		COPYOUT(symtab + i, &sym, sizeof(sym));
+		if (ELF_ST_BIND(sym.st_info) !=3D STB_GLOBAL ||
+		    ELF_ST_TYPE(sym.st_info) !=3D STT_NOTYPE)
+			continue;
+
+		strp =3D strdupout((vm_offset_t)(strtab + sym.st_name));
+		if (strcmp(strp, FDT_STATIC_DTB_SYMBOL) =3D=3D 0) {
+			/* Found a match ! */
+			free(strp);
+			return ((vm_offset_t)(sym.st_value + offs));
+		}
+		free(strp);
+	}
+	return (0);
+}
+
 static int
 fdt_setup_fdtp()
 {
@@ -103,10 +193,14 @@
 	 */
 	bfp =3D file_findfile(NULL, "dtb");
 	if (bfp =3D=3D NULL) {
-		command_errmsg =3D "no device tree blob loaded";
-		return (CMD_ERROR);
+		if ((fdtp =3D (struct fdt_header *)fdt_find_static_dtb()) =3D=3D 0) {
+			command_errmsg =3D "no device tree blob found!";
+			return (CMD_ERROR);
+		}
+	} else {
+		/* Dynamic blob has precedence over static. */
+		fdtp =3D (struct fdt_header *)bfp->f_addr;
 	}
-	fdtp =3D (struct fdt_header *)bfp->f_addr;
=20
 	/*
 	 * Validate the blob.
@@ -448,7 +542,10 @@
 	}
 }
=20
-int
+/*
+ * Locate the blob, fix it up and return its location.
+ */
+void *
 fdt_fixup(void)
 {
 	const char *env;
@@ -461,13 +558,10 @@
 	ethstr =3D NULL;
 	len =3D 0;
=20
-	if (!fdtp) {
-		err =3D fdt_setup_fdtp();
-		if (err) {
-			sprintf(command_errbuf, "Could not perform blob "
-			    "fixups. Error code: %d\n", err);
-			return (err);
-		}
+	err =3D fdt_setup_fdtp();
+	if (err) {
+		sprintf(command_errbuf, "No valid device tree blob found!");
+		return (NULL);
 	}
=20
 	/* Create /chosen node (if not exists) */
@@ -477,7 +571,7 @@
=20
 	/* Value assigned to fixup-applied does not matter. */
 	if (fdt_getprop(fdtp, chosen, "fixup-applied", NULL))
-		return (CMD_OK);
+		goto success;
=20
 	/* Acquire sys_info */
 	si =3D ub_get_sys_info();
@@ -521,7 +615,8 @@
=20
 	fdt_setprop(fdtp, chosen, "fixup-applied", NULL, 0);
=20
-	return (CMD_OK);
+success:
+	return (fdtp);
 }
=20
 int
@@ -539,7 +634,8 @@
 	/*
 	 * Check if uboot env vars were parsed already. If not, do it now.
 	 */
-	fdt_fixup();
+	if (fdt_fixup() =3D=3D NULL)
+		return (CMD_ERROR);
=20
 	/*
 	 * Validate fdt <command>.
@@ -560,10 +656,6 @@
 		return (CMD_ERROR);
 	}
=20
-	if (!fdtp)
-		if (fdt_setup_fdtp())
-			return (CMD_ERROR);
-
 	/*
 	 * Call command handler.
 	 */
@@ -753,32 +845,41 @@
 static int
 fdt_data_str(const void *data, int len, int count, char **buf)
 {
-	char tmp[80], *b;
+	char *b, *tmp;
 	const char *d;
-	int i, l;
+	int buf_len, i, l;
=20
 	/*
 	 * Calculate the length for the string and allocate memory.
 	 *
-	 * Note len already includes at least one terminator.
+	 * Note that 'len' already includes at least one terminator.
 	 */
-	l =3D len;
+	buf_len =3D len;
 	if (count > 1) {
 		/*
 		 * Each token had already a terminator buried in 'len', but we
 		 * only need one eventually, don't count space for these.
 		 */
-		l -=3D count - 1;
+		buf_len -=3D count - 1;
=20
 		/* Each consecutive token requires a ", " separator. */
-		l +=3D count * 2;
+		buf_len +=3D count * 2;
 	}
-	/* Space for surrounding double quotes. */
-	l +=3D count * 2;
=20
-	b =3D (char *)malloc(l);
+	/* Add some space for surrounding double quotes. */
+	buf_len +=3D count * 2;
+
+	/* Note that string being put in 'tmp' may be as big as 'buf_len'. */
+	b =3D (char *)malloc(buf_len);
+	tmp =3D (char *)malloc(buf_len);
 	if (b =3D=3D NULL)
-		return (1);
+		goto error;
+
+	if (tmp =3D=3D NULL) {
+		free(b);
+		goto error;
+	}
+
 	b[0] =3D '\0';
=20
 	/*
@@ -798,13 +899,17 @@
 	} while (i < len);
 	*buf =3D b;
=20
+	free(tmp);
+
 	return (0);
+error:
+	return (1);
 }
=20
 static int
 fdt_data_cell(const void *data, int len, char **buf)
 {
-	char tmp[80], *b;
+	char *b, *tmp;
 	const uint32_t *c;
 	int count, i, l;
=20
@@ -827,8 +932,14 @@
 	l +=3D 3;
=20
 	b =3D (char *)malloc(l);
+	tmp =3D (char *)malloc(l);
 	if (b =3D=3D NULL)
-		return (1);
+		goto error;
+
+	if (tmp =3D=3D NULL) {
+		free(b);
+		goto error;
+	}
=20
 	b[0] =3D '\0';
 	strcat(b, "<");
@@ -842,13 +953,17 @@
 	strcat(b, ">");
 	*buf =3D b;
=20
+	free(tmp);
+
 	return (0);
+error:
+	return (1);
 }
=20
 static int
 fdt_data_bytes(const void *data, int len, char **buf)
 {
-	char tmp[80], *b;
+	char *b, *tmp;
 	const char *d;
 	int i, l;
=20
@@ -867,8 +982,14 @@
 	l +=3D 3;
=20
 	b =3D (char *)malloc(l);
+	tmp =3D (char *)malloc(l);
 	if (b =3D=3D NULL)
-		return (1);
+		goto error;
+
+	if (tmp =3D=3D NULL) {
+		free(b);
+		goto error;
+	}
=20
 	b[0] =3D '\0';
 	strcat(b, "[");
@@ -880,7 +1001,11 @@
 	strcat(b, "]");
 	*buf =3D b;
=20
+	free(tmp);
+
 	return (0);
+error:
+	return (1);
 }
=20
 static int
@@ -1019,6 +1144,14 @@
 		break;
 	}
=20
+	if (rv !=3D 0) {
+		if (rv =3D=3D -FDT_ERR_NOSPACE)
+			sprintf(command_errbuf,
+			    "Device tree blob is too small!\n");
+		else
+			sprintf(command_errbuf,
+			    "Could not add/modify property!\n");
+	}
 	return (rv);
 }
=20
@@ -1261,9 +1394,12 @@
 	rv =3D fdt_add_subnode(fdtp, o, nodename);
=20
 	if (rv < 0) {
-		sprintf(command_errbuf, "could not delete node %s\n",
-		    (rv =3D=3D -FDT_ERR_NOTFOUND) ?
-		    "(node does not exist)" : "");
+		if (rv =3D=3D -FDT_ERR_NOSPACE)
+			sprintf(command_errbuf,
+			    "Device tree blob is too small!\n");
+		else
+			sprintf(command_errbuf,
+			    "Could not add node!\n");
 		return (CMD_ERROR);
 	}
 	return (CMD_OK);
@@ -1272,7 +1408,7 @@
 static int
 fdt_cmd_pwd(int argc, char *argv[])
 {
-	char line[80];
+	char line[FDT_CWD_LEN];
=20
 	pager_open();
 	sprintf(line, "%s\n", cwd);
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/forth/loader.conf.5
--- a/head/sys/boot/forth/loader.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/forth/loader.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/sys/boot/forth/loader.conf.5 224228 2011-07-20 15:18:24=
Z jhb $
+.\" $FreeBSD: head/sys/boot/forth/loader.conf.5 233648 2012-03-29 05:02:12=
Z eadler $
 .Dd July 20, 2011
 .Dt LOADER.CONF 5
 .Os
@@ -266,7 +266,7 @@
 stops reading
 .Nm
 when it encounters a syntax error, so any options which are vital for
-booting a particular system (i.e.\&=20
+booting a particular system (i.e.\&
 .Dq Va hw.ata.ata_dma Ns "=3D0" )
 should precede any experimental additions to
 .Nm .
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/forth/menu-commands.4th
--- a/head/sys/boot/forth/menu-commands.4th	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/forth/menu-commands.4th	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 \ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 \ SUCH DAMAGE.
 \=20
-\ $FreeBSD: head/sys/boot/forth/menu-commands.4th 222417 2011-05-28 08:50:=
38Z julian $
+\ $FreeBSD: head/sys/boot/forth/menu-commands.4th 233941 2012-04-06 09:36:=
22Z avg $
=20
 marker task-menu-commands.4th
=20
@@ -62,30 +62,21 @@
 	-rot 2dup 12 + c! rot    \ replace 'N' with ASCII numeral
=20
 	evaluate 0=3D if
-		s" hint.apic.0.disabled" unsetenv
+		s" kern.smp.disabled" unsetenv
 		s" hw.ata.ata_dma" unsetenv
 		s" hw.ata.atapi_dma" unsetenv
 		s" hw.ata.wc" unsetenv
 		s" hw.eisa_slots" unsetenv
-		s" hint.kbdmux.0.disabled" unsetenv
+		s" kern.eventtimer.periodic" unsetenv
+		s" kern.geom.part.check_integrity" unsetenv
 	else
-		\=20
-		\ Toggle ACPI elements if necessary
-		\=20
-		acpipresent? if acpienabled? if
-			menuacpi @ dup 0<> if
-				toggle_menuitem ( N -- N )
-			then
-			drop
-			acpi_disable
-		then then
-
-		s" set hint.apic.0.disabled=3D1" evaluate
+		s" set kern.smp.disabled=3D1" evaluate
 		s" set hw.ata.ata_dma=3D0" evaluate
 		s" set hw.ata.atapi_dma=3D0" evaluate
 		s" set hw.ata.wc=3D0" evaluate
 		s" set hw.eisa_slots=3D0" evaluate
-		s" set hint.kbdmux.0.disabled=3D1" evaluate
+		s" set kern.eventtimer.periodic=3D1" evaluate
+		s" set kern.geom.part.check_integrity=3D0" evaluate
 	then
=20
 	menu-redraw
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/i386/zfsboot/zfsboot.c
--- a/head/sys/boot/i386/zfsboot/zfsboot.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/i386/zfsboot/zfsboot.c	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/boot/i386/zfsboot/zfsboot.c 228267 2011-12-04=
 21:32:18Z avg $");
+__FBSDID("$FreeBSD: head/sys/boot/i386/zfsboot/zfsboot.c 234339 2012-04-16=
 10:43:06Z avg $");
=20
 #include <sys/param.h>
 #include <sys/errno.h>
@@ -93,6 +93,7 @@
 static const unsigned char dev_maj[NDEV] =3D {30, 4, 2};
=20
 static char cmd[512];
+static char cmddup[512];
 static char kname[1024];
 static int comspeed =3D SIOSPD;
 static struct bootinfo bootinfo;
@@ -541,10 +542,15 @@
     }
=20
     if (*cmd) {
-	if (!OPT_CHECK(RBX_QUIET))
-	    printf("%s: %s", PATH_CONFIG, cmd);
+	/*
+	 * Note that parse() is destructive to cmd[] and we also want
+	 * to honor RBX_QUIET option that could be present in cmd[].
+	 */
+	memcpy(cmddup, cmd, sizeof(cmd));
 	if (parse())
 	    autoboot =3D 0;
+	if (!OPT_CHECK(RBX_QUIET))
+	    printf("%s: %s", PATH_CONFIG, cmddup);
 	/* Do not process this command twice */
 	*cmd =3D 0;
     }
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/powerpc/ps3/start.S
--- a/head/sys/boot/powerpc/ps3/start.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/powerpc/ps3/start.S	Tue Apr 17 11:51:51 2012 +0300
@@ -22,9 +22,11 @@
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/boot/powerpc/ps3/start.S 233666 2012-03-29 16:04:42Z=
 nwhitehorn $
  */
=20
+#define LOCORE
+
 #include <machine/trap_aim.h>
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/uboot/common/metadata.c
--- a/head/sys/boot/uboot/common/metadata.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/uboot/common/metadata.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/boot/uboot/common/metadata.c 233230 2012-03-2=
0 13:08:57Z raj $");
=20
 #include <stand.h>
 #include <sys/param.h>
@@ -333,13 +333,12 @@
=20
 #if defined(LOADER_FDT_SUPPORT)
 	/* Handle device tree blob */
-	fdt_fixup();
-	if ((bfp =3D file_findfile(NULL, "dtb")) =3D=3D NULL &&
-	    (howto & RB_VERBOSE))
-		printf("**WARNING** Booting with no DTB loaded!\n");
-
-	dtbp =3D bfp =3D=3D NULL ? 0 : bfp->f_addr;
-	file_addmetadata(kfp, MODINFOMD_DTBP, sizeof dtbp, &dtbp);
+	dtbp =3D fdt_fixup();
+	if (dtbp !=3D (vm_offset_t)NULL)
+		file_addmetadata(kfp, MODINFOMD_DTBP, sizeof dtbp, &dtbp);
+	else
+		pager_output("WARNING! Trying to fire up the kernel, but no "
+		    "device tree blob found!\n");
 #endif
=20
 	file_addmetadata(kfp, MODINFOMD_KERNEND, sizeof kernend, &kernend);
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/uboot/lib/Makefile
--- a/head/sys/boot/uboot/lib/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/uboot/lib/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,11 +1,13 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/boot/uboot/lib/Makefile 233287 2012-03-21 20:53:47Z m=
arius $
+
+.PATH: ${.CURDIR}/../../common
=20
 LIB=3D		uboot
 INTERNALLIB=3D
 WARNS?=3D		2
=20
-SRCS=3D	devicename.c elf_freebsd.c console.c copy.c disk.c \
-	module.c net.c reboot.c time.c glue.c
+SRCS=3D	crc32.c console.c copy.c devicename.c disk.c elf_freebsd.c glue.c
+SRCS+=3D	module.c net.c reboot.c time.c
=20
 CFLAGS+=3D	-ffreestanding -msoft-float
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/boot/uboot/lib/glue.c
--- a/head/sys/boot/uboot/lib/glue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/boot/uboot/lib/glue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,8 +25,11 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/boot/uboot/lib/glue.c 233287 2012-03-21 20:53=
:47Z marius $");
=20
+#include <sys/types.h>
+
+#include <crc32.h>
 #include <stand.h>
 #include "api_public.h"
 #include "glue.h"
@@ -43,69 +46,6 @@
 /* Some random address used by U-Boot. */
 extern long uboot_address;
=20
-/* crc32 stuff stolen from lib/libdisk/write_ia64_disk.c */
-static uint32_t crc32_tab[] =3D {
-	0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
-	0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
-	0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
-	0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
-	0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
-	0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
-	0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
-	0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
-	0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
-	0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
-	0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
-	0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
-	0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
-	0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
-	0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
-	0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
-	0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
-	0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
-	0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
-	0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
-	0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
-	0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
-	0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
-	0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
-	0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
-	0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
-	0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
-	0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
-	0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
-	0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
-	0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
-	0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
-	0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
-	0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
-	0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
-	0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
-	0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
-	0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
-	0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
-	0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
-	0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
-	0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
-	0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
-};
-
-static uint32_t
-crc32(const void *buf, size_t size)
-{
-	const uint8_t *p;
-	uint32_t crc;
-
-	p =3D buf;
-	crc =3D ~0U;
-
-	while (size--)
-		crc =3D crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
-
-	return (crc ^ ~0U);
-}
-
-
 static int
 valid_sig(struct api_signature *sig)
 {
@@ -235,7 +175,6 @@
 	return ((err) ? NULL : &si);
 }
=20
-
 /****************************************
  *
  * timing
@@ -260,7 +199,6 @@
 	return (cur);
 }
=20
-
 /*************************************************************************=
***
  *
  * devices
@@ -314,7 +252,6 @@
 	return (n);
 }
=20
-
 /*
  * handle:	0-based id of the device
  *
@@ -559,7 +496,6 @@
 	syscall(API_ENV_SET, NULL, (uint32_t)name, (uint32_t)value);
 }
=20
-
 static char env_name[256];
=20
 const char *
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/ctl/ctl.c
--- a/head/sys/cam/ctl/ctl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cam/ctl/ctl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -42,7 +42,7 @@
 #define _CTL_C
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl.c 232604 2012-03-06 13:43:57Z tra=
sz $");
+__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl.c 233963 2012-04-06 22:23:13Z ken=
 $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -959,6 +959,33 @@
=20
 	softc->dev->si_drv1 =3D softc;
=20
+	/*
+	 * By default, return a "bad LUN" peripheral qualifier for unknown
+	 * LUNs.  The user can override this default using the tunable or
+	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
+	 */
+	softc->inquiry_pq_no_lun =3D 1;
+	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
+			  &softc->inquiry_pq_no_lun);
+	sysctl_ctx_init(&softc->sysctl_ctx);
+	softc->sysctl_tree =3D SYSCTL_ADD_NODE(&softc->sysctl_ctx,
+		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
+		CTLFLAG_RD, 0, "CAM Target Layer");
+
+	if (softc->sysctl_tree =3D=3D NULL) {
+		printf("%s: unable to allocate sysctl tree\n", __func__);
+		destroy_dev(softc->dev);
+		free(control_softc, M_DEVBUF);
+		control_softc =3D NULL;
+		return;
+	}
+
+	SYSCTL_ADD_INT(&softc->sysctl_ctx,
+		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
+		       "inquiry_pq_no_lun", CTLFLAG_RW,
+		       &softc->inquiry_pq_no_lun, 0,
+		       "Report no lun possible for invalid LUNs");
+
 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
 	softc->open_count =3D 0;
=20
@@ -1150,6 +1177,11 @@
=20
 	destroy_dev(softc->dev);
=20
+	sysctl_ctx_free(&softc->sysctl_ctx);
+
+	free(control_softc, M_DEVBUF);
+	control_softc =3D NULL;
+
 	printf("ctl: CAM Target Layer unloaded\n");
 }
=20
@@ -9369,15 +9401,55 @@
 	memset(inq_ptr, 0, sizeof(*inq_ptr));
=20
 	/*
-	 * The control device is always connected.  The disk device, on the
-	 * other hand, may not be online all the time.  If we don't have a
-	 * LUN mapping, we'll just say it's offline.
+	 * If we have a LUN configured, report it as connected.  Otherwise,
+	 * report that it is offline or no device is supported, depending=20
+	 * on the value of inquiry_pq_no_lun.
+	 *
+	 * According to the spec (SPC-4 r34), the peripheral qualifier
+	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
+	 *
+	 * "A peripheral device having the specified peripheral device type=20
+	 * is not connected to this logical unit. However, the device
+	 * server is capable of supporting the specified peripheral device
+	 * type on this logical unit."
+	 *
+	 * According to the same spec, the peripheral qualifier
+	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
+	 *
+	 * "The device server is not capable of supporting a peripheral
+	 * device on this logical unit. For this peripheral qualifier the
+	 * peripheral device type shall be set to 1Fh. All other peripheral
+	 * device type values are reserved for this peripheral qualifier."
+	 *
+	 * Given the text, it would seem that we probably want to report that
+	 * the LUN is offline here.  There is no LUN connected, but we can
+	 * support a LUN at the given LUN number.
+	 *
+	 * In the real world, though, it sounds like things are a little
+	 * different:
+	 *
+	 * - Linux, when presented with a LUN with the offline peripheral
+	 *   qualifier, will create an sg driver instance for it.  So when
+	 *   you attach it to CTL, you wind up with a ton of sg driver
+	 *   instances.  (One for every LUN that Linux bothered to probe.)
+	 *   Linux does this despite the fact that it issues a REPORT LUNs
+	 *   to LUN 0 to get the inventory of supported LUNs.
+	 *
+	 * - There is other anecdotal evidence (from Emulex folks) about
+	 *   arrays that use the offline peripheral qualifier for LUNs that
+	 *   are on the "passive" path in an active/passive array.
+	 *
+	 * So the solution is provide a hopefully reasonable default
+	 * (return bad/no LUN) and allow the user to change the behavior
+	 * with a tunable/sysctl variable.
 	 */
 	if (lun !=3D NULL)
 		inq_ptr->device =3D (SID_QUAL_LU_CONNECTED << 5) |
 				  lun->be_lun->lun_type;
+	else if (ctl_softc->inquiry_pq_no_lun =3D=3D 0)
+		inq_ptr->device =3D (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
 	else
-		inq_ptr->device =3D (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
+		inq_ptr->device =3D (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
=20
 	/* RMB in byte 2 is 0 */
 	inq_ptr->version =3D SCSI_REV_SPC3;
@@ -9491,8 +9563,6 @@
 			break;
 		}
 	}
-	sprintf((char *)inq_ptr->vendor_specific1, "Copyright (C) 2004, COPAN "
-		"Systems, Inc.  All Rights Reserved.");
=20
 	ctsio->scsi_status =3D SCSI_STATUS_OK;
 	if (ctsio->kern_data_len > 0) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/ctl/ctl_backend.c
--- a/head/sys/cam/ctl/ctl_backend.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cam/ctl/ctl_backend.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_backend.c 229997 2012-01-12 00:34=
:33Z ken $");
+__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_backend.c 233963 2012-04-06 22:23=
:13Z ken $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -47,6 +47,7 @@
 #include <sys/mutex.h>
 #include <sys/condvar.h>
 #include <sys/queue.h>
+#include <sys/sysctl.h>
=20
 #include <cam/scsi/scsi_all.h>
 #include <cam/scsi/scsi_da.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/ctl/ctl_cmd_table.c
--- a/head/sys/cam/ctl/ctl_cmd_table.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cam/ctl/ctl_cmd_table.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * POSSIBILITY OF SUCH DAMAGES.
  *
  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl_cmd_table.c#4 $
- * $FreeBSD: head/sys/cam/ctl/ctl_cmd_table.c 229997 2012-01-12 00:34:33Z =
ken $
+ * $FreeBSD: head/sys/cam/ctl/ctl_cmd_table.c 233963 2012-04-06 22:23:13Z =
ken $
  */
 /*
  * CAM Target Layer command table.
@@ -44,6 +44,7 @@
 #include <sys/malloc.h>
 #include <sys/condvar.h>
 #include <sys/queue.h>
+#include <sys/sysctl.h>
=20
 #include <cam/scsi/scsi_all.h>
 #include <cam/scsi/scsi_da.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/ctl/ctl_error.c
--- a/head/sys/cam/ctl/ctl_error.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cam/ctl/ctl_error.c	Tue Apr 17 11:51:51 2012 +0300
@@ -37,7 +37,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_error.c 232604 2012-03-06 13:43:5=
7Z trasz $");
+__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_error.c 233963 2012-04-06 22:23:1=
3Z ken $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -49,6 +49,7 @@
 #include <sys/condvar.h>
 #include <sys/stddef.h>
 #include <sys/ctype.h>
+#include <sys/sysctl.h>
 #include <machine/stdarg.h>
=20
 #include <cam/scsi/scsi_all.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/ctl/ctl_frontend.c
--- a/head/sys/cam/ctl/ctl_frontend.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cam/ctl/ctl_frontend.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_frontend.c 229997 2012-01-12 00:3=
4:33Z ken $");
+__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_frontend.c 233963 2012-04-06 22:2=
3:13Z ken $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -48,6 +48,7 @@
 #include <sys/condvar.h>
 #include <sys/endian.h>
 #include <sys/queue.h>
+#include <sys/sysctl.h>
=20
 #include <cam/scsi/scsi_all.h>
 #include <cam/scsi/scsi_da.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/ctl/ctl_frontend_internal=
.c
--- a/head/sys/cam/ctl/ctl_frontend_internal.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/cam/ctl/ctl_frontend_internal.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -48,7 +48,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_frontend_internal.c 229997 2012-0=
1-12 00:34:33Z ken $");
+__FBSDID("$FreeBSD: head/sys/cam/ctl/ctl_frontend_internal.c 233963 2012-0=
4-06 22:23:13Z ken $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -60,6 +60,7 @@
 #include <sys/condvar.h>
 #include <sys/queue.h>
 #include <sys/sbuf.h>
+#include <sys/sysctl.h>
 #include <cam/scsi/scsi_all.h>
 #include <cam/scsi/scsi_da.h>
 #include <cam/ctl/ctl_io.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/ctl/ctl_private.h
--- a/head/sys/cam/ctl/ctl_private.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cam/ctl/ctl_private.h	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * POSSIBILITY OF SUCH DAMAGES.
  *
  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl_private.h#7 $
- * $FreeBSD: head/sys/cam/ctl/ctl_private.h 232074 2012-02-23 21:34:14Z di=
m $
+ * $FreeBSD: head/sys/cam/ctl/ctl_private.h 233963 2012-04-06 22:23:13Z ke=
n $
  */
 /*
  * CAM Target Layer driver private data structures/definitions.
@@ -421,6 +421,9 @@
 	int num_luns;
 	ctl_gen_flags flags;
 	ctl_ha_mode ha_mode;
+	int inquiry_pq_no_lun;
+	struct sysctl_ctx_list sysctl_ctx;
+	struct sysctl_oid *sysctl_tree;
 	struct ctl_ioctl_info ioctl_info;
 	struct ctl_lun lun;
 	struct ctl_io_pool *internal_pool;
diff -r 428842767fa6 -r f2935497fa04 head/sys/cam/scsi/scsi_da.c
--- a/head/sys/cam/scsi/scsi_da.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cam/scsi/scsi_da.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/cam/scsi/scsi_da.c 230921 2012-02-02 19:02:15=
Z mav $");
+__FBSDID("$FreeBSD: head/sys/cam/scsi/scsi_da.c 234177 2012-04-12 12:58:14=
Z trasz $");
=20
 #include <sys/param.h>
=20
@@ -83,7 +83,8 @@
 	DA_FLAG_RETRY_UA	=3D 0x080,
 	DA_FLAG_OPEN		=3D 0x100,
 	DA_FLAG_SCTX_INIT	=3D 0x200,
-	DA_FLAG_CAN_RC16	=3D 0x400
+	DA_FLAG_CAN_RC16	=3D 0x400,
+	DA_FLAG_PROBED		=3D 0x800	=09
 } da_flags;
=20
 typedef enum {
@@ -829,7 +830,7 @@
 static  int		daerror(union ccb *ccb, u_int32_t cam_flags,
 				u_int32_t sense_flags);
 static void		daprevent(struct cam_periph *periph, int action);
-static int		dagetcapacity(struct cam_periph *periph);
+static void		dareprobe(struct cam_periph *periph);
 static void		dasetgeom(struct cam_periph *periph, uint32_t block_len,
 				  uint64_t maxsector,
 				  struct scsi_read_capacity_data_long *rcaplong,
@@ -929,36 +930,29 @@
 		softc->flags &=3D ~DA_FLAG_PACK_INVALID;
 	}
=20
-	error =3D dagetcapacity(periph);
+	dareprobe(periph);
=20
-	if (error =3D=3D 0) {
+	/* Wait for the disk size update.  */
+	error =3D msleep(&softc->disk->d_mediasize, periph->sim->mtx, PRIBIO,
+	    "dareprobe", 0);
+	if (error !=3D 0)
+		xpt_print(periph->path, "unable to retrieve capacity data");
=20
-		softc->disk->d_sectorsize =3D softc->params.secsize;
-		softc->disk->d_mediasize =3D softc->params.secsize * (off_t)softc->param=
s.sectors;
-		softc->disk->d_stripesize =3D softc->params.stripesize;
-		softc->disk->d_stripeoffset =3D softc->params.stripeoffset;
-		/* XXX: these are not actually "firmware" values, so they may be wrong */
-		softc->disk->d_fwsectors =3D softc->params.secs_per_track;
-		softc->disk->d_fwheads =3D softc->params.heads;
-		softc->disk->d_devstat->block_size =3D softc->params.secsize;
-		softc->disk->d_devstat->flags &=3D ~DEVSTAT_BS_UNAVAILABLE;
-		if (softc->delete_method > DA_DELETE_DISABLE)
-			softc->disk->d_flags |=3D DISKFLAG_CANDELETE;
-		else
-			softc->disk->d_flags &=3D ~DISKFLAG_CANDELETE;
+	if (periph->flags & CAM_PERIPH_INVALID)
+		error =3D ENXIO;
=20
-		if ((softc->flags & DA_FLAG_PACK_REMOVABLE) !=3D 0 &&
-		    (softc->quirks & DA_Q_NO_PREVENT) =3D=3D 0)
-			daprevent(periph, PR_PREVENT);
-	} else
-		softc->flags &=3D ~DA_FLAG_OPEN;
+	if (error =3D=3D 0 && (softc->flags & DA_FLAG_PACK_REMOVABLE) !=3D 0 &&
+	    (softc->quirks & DA_Q_NO_PREVENT) =3D=3D 0)
+		daprevent(periph, PR_PREVENT);
=20
 	cam_periph_unhold(periph);
 	cam_periph_unlock(periph);
=20
 	if (error !=3D 0) {
+		softc->flags &=3D ~DA_FLAG_OPEN;
 		cam_periph_release(periph);
 	}
+
 	return (error);
 }
=20
@@ -1631,9 +1625,7 @@
 		softc->minimum_cmd_size =3D 16;
=20
 	/* Predict whether device may support READ CAPACITY(16). */
-	if (SID_ANSI_REV(&cgd->inq_data) >=3D SCSI_REV_SPC3 ||
-	    (SID_ANSI_REV(&cgd->inq_data) >=3D SCSI_REV_SPC &&
-	     (cgd->inq_data.spc3_flags & SPC3_SID_PROTECT))) {
+	if (SID_ANSI_REV(&cgd->inq_data) >=3D SCSI_REV_SPC3) {
 		softc->flags |=3D DA_FLAG_CAN_RC16;
 		softc->state =3D DA_STATE_PROBE2;
 	}
@@ -2366,7 +2358,7 @@
 			}
 		}
 		free(csio->data_ptr, M_SCSIDA);
-		if (announce_buf[0] !=3D '\0') {
+		if (announce_buf[0] !=3D '\0' && ((softc->flags & DA_FLAG_PROBED) =3D=3D=
 0)) {
 			/*
 			 * Create our sysctl variables, now that we know
 			 * we have successfully attached.
@@ -2380,9 +2372,7 @@
 				xpt_print(periph->path, "fatal error, "
 				    "could not acquire reference count\n");
 			}
-			=09
 		}
-		softc->state =3D DA_STATE_NORMAL;=09
 		/*
 		 * Since our peripheral may be invalidated by an error
 		 * above or an external event, we must release our CCB
@@ -2392,7 +2382,13 @@
 		 * operation.
 		 */
 		xpt_release_ccb(done_ccb);
-		cam_periph_unhold(periph);
+		softc->state =3D DA_STATE_NORMAL;=09
+		wakeup(&softc->disk->d_mediasize);
+		if ((softc->flags & DA_FLAG_PROBED) =3D=3D 0) {
+			softc->flags |=3D DA_FLAG_PROBED;
+			cam_periph_unhold(periph);
+		} else
+			cam_periph_release_locked(periph);
 		return;
 	}
 	case DA_CCB_WAITING:
@@ -2410,6 +2406,30 @@
 	xpt_release_ccb(done_ccb);
 }
=20
+static void
+dareprobe(struct cam_periph *periph)
+{
+	struct da_softc	  *softc;
+	cam_status status;
+
+	softc =3D (struct da_softc *)periph->softc;
+
+	/* Probe in progress; don't interfere. */
+	if ((softc->flags & DA_FLAG_PROBED) =3D=3D 0)
+		return;
+
+	status =3D cam_periph_acquire(periph);
+	KASSERT(status =3D=3D CAM_REQ_CMP,
+	    ("dareprobe: cam_periph_acquire failed"));
+
+	if (softc->flags & DA_FLAG_CAN_RC16)
+		softc->state =3D DA_STATE_PROBE2;
+	else
+		softc->state =3D DA_STATE_PROBE;
+
+	xpt_schedule(periph, CAM_PRIORITY_DEV);
+}
+
 static int
 daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
 {
@@ -2439,6 +2459,16 @@
 				   &error_code, &sense_key, &asc, &ascq);
 		if (sense_key =3D=3D SSD_KEY_ILLEGAL_REQUEST)
  			error =3D cmd6workaround(ccb);
+		/*
+		 * If the target replied with CAPACITY DATA HAS CHANGED UA,
+		 * query the capacity and notify upper layers.
+		 */
+		else if (sense_key =3D=3D SSD_KEY_UNIT_ATTENTION &&
+		    asc =3D=3D 0x2A && ascq =3D=3D 0x09) {
+			xpt_print(periph->path, "capacity data has changed\n");
+			dareprobe(periph);
+			sense_flags |=3D SF_NO_PRINT;
+		}
 	}
 	if (error =3D=3D ERESTART)
 		return (ERESTART);
@@ -2492,164 +2522,6 @@
 	xpt_release_ccb(ccb);
 }
=20
-static int
-dagetcapacity(struct cam_periph *periph)
-{
-	struct da_softc *softc;
-	union ccb *ccb;
-	struct scsi_read_capacity_data *rcap;
-	struct scsi_read_capacity_data_long *rcaplong;
-	uint32_t block_len;
-	uint64_t maxsector;
-	int error, rc16failed;
-	u_int32_t sense_flags;
-	u_int lbppbe;	/* Logical blocks per physical block exponent. */
-	u_int lalba;	/* Lowest aligned LBA. */
-
-	softc =3D (struct da_softc *)periph->softc;
-	block_len =3D 0;
-	maxsector =3D 0;
-	lbppbe =3D 0;
-	lalba =3D 0;
-	error =3D 0;
-	rc16failed =3D 0;
-	rcaplong =3D NULL;
-	sense_flags =3D SF_RETRY_UA;
-	if (softc->flags & DA_FLAG_PACK_REMOVABLE)
-		sense_flags |=3D SF_NO_PRINT;
-
-	/* Do a read capacity */
-	rcap =3D (struct scsi_read_capacity_data *)malloc(sizeof(*rcaplong),
-							M_SCSIDA,
-							M_NOWAIT | M_ZERO);
-	if (rcap =3D=3D NULL)
-		return (ENOMEM);
-	rcaplong =3D (struct scsi_read_capacity_data_long *)rcap;
-
-	ccb =3D cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
-
-	/* Try READ CAPACITY(16) first if we think it should work. */
-	if (softc->flags & DA_FLAG_CAN_RC16) {
-		scsi_read_capacity_16(&ccb->csio,
-				      /*retries*/ 4,
-				      /*cbfcnp*/ dadone,
-				      /*tag_action*/ MSG_SIMPLE_Q_TAG,
-				      /*lba*/ 0,
-				      /*reladr*/ 0,
-				      /*pmi*/ 0,
-				      /*rcap_buf*/ (uint8_t *)rcaplong,
-				      /*rcap_buf_len*/ sizeof(*rcaplong),
-				      /*sense_len*/ SSD_FULL_SIZE,
-				      /*timeout*/ 60000);
-		ccb->ccb_h.ccb_bp =3D NULL;
-
-		error =3D cam_periph_runccb(ccb, daerror,
-					  /*cam_flags*/CAM_RETRY_SELTO,
-					  sense_flags, softc->disk->d_devstat);
-		if (error =3D=3D 0)
-			goto rc16ok;
-
-		/* If we got ILLEGAL REQUEST, do not prefer RC16 any more. */
-		if ((ccb->ccb_h.status & CAM_STATUS_MASK) =3D=3D CAM_REQ_INVALID) {
-			softc->flags &=3D ~DA_FLAG_CAN_RC16;
-		} else if (((ccb->ccb_h.status & CAM_STATUS_MASK) =3D=3D
-			     CAM_SCSI_STATUS_ERROR)
-			&& (ccb->csio.scsi_status =3D=3D SCSI_STATUS_CHECK_COND)
-			&& (ccb->ccb_h.status & CAM_AUTOSNS_VALID)
-			&& ((ccb->ccb_h.flags & CAM_SENSE_PHYS) =3D=3D 0)
-			&& ((ccb->ccb_h.flags & CAM_SENSE_PTR) =3D=3D 0)) {
-			int sense_key, error_code, asc, ascq;
-
-			scsi_extract_sense_len(&ccb->csio.sense_data,
-					       ccb->csio.sense_len -
-					       ccb->csio.sense_resid,
-					       &error_code, &sense_key,
-					       &asc, &ascq, /*show_errors*/1);
-			/*
-			 * If we don't have enough sense to get the sense
-			 * key, or if it's illegal request, turn off
-			 * READ CAPACITY (16).
-			 */
-			if ((sense_key =3D=3D -1)
-			 || (sense_key =3D=3D SSD_KEY_ILLEGAL_REQUEST))
-				softc->flags &=3D ~DA_FLAG_CAN_RC16;
-		}
-		rc16failed =3D 1;
-	}
-
-	/* Do READ CAPACITY(10). */
-	scsi_read_capacity(&ccb->csio,
-			   /*retries*/4,
-			   /*cbfncp*/dadone,
-			   MSG_SIMPLE_Q_TAG,
-			   rcap,
-			   SSD_FULL_SIZE,
-			   /*timeout*/60000);
-	ccb->ccb_h.ccb_bp =3D NULL;
-
-	error =3D cam_periph_runccb(ccb, daerror,
-				  /*cam_flags*/CAM_RETRY_SELTO,
-				  sense_flags,
-				  softc->disk->d_devstat);
-	if (error =3D=3D 0) {
-		block_len =3D scsi_4btoul(rcap->length);
-		maxsector =3D scsi_4btoul(rcap->addr);
-
-		if (maxsector !=3D 0xffffffff || rc16failed)
-			goto done;
-	} else
-		goto done;
-
-	/* If READ CAPACITY(10) returned overflow, use READ CAPACITY(16) */
-	scsi_read_capacity_16(&ccb->csio,
-			      /*retries*/ 4,
-			      /*cbfcnp*/ dadone,
-			      /*tag_action*/ MSG_SIMPLE_Q_TAG,
-			      /*lba*/ 0,
-			      /*reladr*/ 0,
-			      /*pmi*/ 0,
-			      /*rcap_buf*/ (uint8_t *)rcaplong,
-			      /*rcap_buf_len*/ sizeof(*rcaplong),
-			      /*sense_len*/ SSD_FULL_SIZE,
-			      /*timeout*/ 60000);
-	ccb->ccb_h.ccb_bp =3D NULL;
-
-	error =3D cam_periph_runccb(ccb, daerror,
-				  /*cam_flags*/CAM_RETRY_SELTO,
-				  sense_flags,
-				  softc->disk->d_devstat);
-	if (error =3D=3D 0) {
-rc16ok:
-		block_len =3D scsi_4btoul(rcaplong->length);
-		maxsector =3D scsi_8btou64(rcaplong->addr);
-		lbppbe =3D rcaplong->prot_lbppbe & SRC16_LBPPBE;
-		lalba =3D scsi_2btoul(rcaplong->lalba_lbp);
-	}
-
-done:
-
-	if (error =3D=3D 0) {
-		if (block_len >=3D MAXPHYS || block_len =3D=3D 0) {
-			xpt_print(periph->path,
-			    "unsupportable block size %ju\n",
-			    (uintmax_t) block_len);
-			error =3D EINVAL;
-		} else {
-			dasetgeom(periph, block_len, maxsector,
-				  rcaplong, sizeof(*rcaplong));
-			if ((lalba & SRC16_LBPME)
-			 && softc->delete_method =3D=3D DA_DELETE_NONE)
-				softc->delete_method =3D DA_DELETE_UNMAP;
-		}
-	}
-
-	xpt_release_ccb(ccb);
-
-	free(rcap, M_SCSIDA);
-
-	return (error);
-}
-
 static void
 dasetgeom(struct cam_periph *periph, uint32_t block_len, uint64_t maxsecto=
r,
 	  struct scsi_read_capacity_data_long *rcaplong, size_t rcap_len)
@@ -2749,6 +2621,20 @@
 			      min(sizeof(softc->rcaplong), rcap_len));
 		}
 	}
+
+	softc->disk->d_sectorsize =3D softc->params.secsize;
+	softc->disk->d_mediasize =3D softc->params.secsize * (off_t)softc->params=
.sectors;
+	softc->disk->d_stripesize =3D softc->params.stripesize;
+	softc->disk->d_stripeoffset =3D softc->params.stripeoffset;
+	/* XXX: these are not actually "firmware" values, so they may be wrong */
+	softc->disk->d_fwsectors =3D softc->params.secs_per_track;
+	softc->disk->d_fwheads =3D softc->params.heads;
+	softc->disk->d_devstat->block_size =3D softc->params.secsize;
+	softc->disk->d_devstat->flags &=3D ~DEVSTAT_BS_UNAVAILABLE;
+	if (softc->delete_method > DA_DELETE_DISABLE)
+		softc->disk->d_flags |=3D DISKFLAG_CANDELETE;
+	else
+		softc->disk->d_flags &=3D ~DISKFLAG_CANDELETE;
 }
=20
 static void
diff -r 428842767fa6 -r f2935497fa04 head/sys/cddl/contrib/opensolaris/uts/=
common/dtrace/dtrace.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c	Tue Apr =
17 11:36:47 2012 +0300
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c	Tue Apr =
17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
  *
  * CDDL HEADER END
  *
- * $FreeBSD: head/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c =
228448 2011-12-12 23:29:32Z attilio $
+ * $FreeBSD: head/sys/cddl/contrib/opensolaris/uts/common/dtrace/dtrace.c =
233408 2012-03-24 04:52:18Z gonzo $
  */
=20
 /*
@@ -235,7 +235,7 @@
 static struct mtx	dtrace_unr_mtx;
 MTX_SYSINIT(dtrace_unr_mtx, &dtrace_unr_mtx, "Unique resource identifier",=
 MTX_DEF);
 int		dtrace_in_probe;	/* non-zero if executing a probe */
-#if defined(__i386__) || defined(__amd64__)
+#if defined(__i386__) || defined(__amd64__) || defined(__mips__)
 uintptr_t	dtrace_in_probe_addr;	/* Address of invop when already in probe =
*/
 #endif
 #endif
@@ -10659,7 +10659,7 @@
 #else
 	int i;
=20
-#if defined(__amd64__)
+#if defined(__amd64__) || defined(__mips__)
 	/*
 	 * FreeBSD isn't good at limiting the amount of memory we
 	 * ask to malloc, so let's place a limit here before trying
diff -r 428842767fa6 -r f2935497fa04 head/sys/cddl/contrib/opensolaris/uts/=
common/fs/zfs/zfs_vnops.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c	Tue A=
pr 17 11:36:47 2012 +0300
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c	Tue A=
pr 17 11:51:51 2012 +0300
@@ -293,9 +293,12 @@
=20
 	case _FIO_SEEK_DATA:
 	case _FIO_SEEK_HOLE:
+#ifdef sun
 		if (ddi_copyin((void *)data, &off, sizeof (off), flag))
 			return (EFAULT);
-
+#else
+		off =3D *(offset_t *)data;
+#endif
 		zp =3D VTOZ(vp);
 		zfsvfs =3D zp->z_zfsvfs;
 		ZFS_ENTER(zfsvfs);
@@ -306,8 +309,12 @@
 		ZFS_EXIT(zfsvfs);
 		if (error)
 			return (error);
+#ifdef sun
 		if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
 			return (EFAULT);
+#else
+		*(offset_t *)data =3D off;
+#endif
 		return (0);
 	}
 	return (ENOTTY);
@@ -338,10 +345,9 @@
 			vm_page_busy(pp);
 			vm_page_undirty(pp);
 		} else {
-			if (__predict_false(obj->cache !=3D NULL)) {
+			if (vm_page_is_cached(obj, OFF_TO_IDX(start)))
 				vm_page_cache_free(obj, OFF_TO_IDX(start),
 				    OFF_TO_IDX(start) + 1);
-			}
 			pp =3D NULL;
 		}
 		break;
diff -r 428842767fa6 -r f2935497fa04 head/sys/cddl/dev/dtrace/dtrace_ioctl.c
--- a/head/sys/cddl/dev/dtrace/dtrace_ioctl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cddl/dev/dtrace/dtrace_ioctl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
  *
  * CDDL HEADER END
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/cddl/dev/dtrace/dtrace_ioctl.c 233521 2012-03-26 21:=
22:51Z gonzo $
  *
  */
=20
@@ -39,11 +39,7 @@
 	case DTRACEHIOC_ADDDOF:
 		dhp =3D (dof_helper_t *)addr;
 		/* XXX all because dofhp_dof is 64 bit */
-#ifdef __i386
-		addr =3D (caddr_t)(uint32_t)dhp->dofhp_dof;
-#else
-		addr =3D (caddr_t)dhp->dofhp_dof;
-#endif
+		addr =3D (caddr_t)(vm_offset_t)dhp->dofhp_dof;
 		/* FALLTHROUGH */
 	case DTRACEHIOC_ADD:
 		dof =3D dtrace_dof_copyin((intptr_t)addr, &rval);
diff -r 428842767fa6 -r f2935497fa04 head/sys/cddl/dev/lockstat/lockstat.c
--- a/head/sys/cddl/dev/lockstat/lockstat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cddl/dev/lockstat/lockstat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -20,7 +20,7 @@
  *
  * Portions Copyright (c) 2008-2009 Stacey Son <sson at FreeBSD.org>=20
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/cddl/dev/lockstat/lockstat.c 233409 2012-03-24 05:14=
:37Z gonzo $
  *
  */
=20
@@ -45,7 +45,7 @@
 #include <sys/dtrace.h>
 #include <sys/lockstat.h>
=20
-#if defined(__i386__) || defined(__amd64__)
+#if defined(__i386__) || defined(__amd64__) || defined(__mips__)
 #define LOCKSTAT_AFRAMES 1
 #else
 #error "architecture not supported"
diff -r 428842767fa6 -r f2935497fa04 head/sys/cddl/dev/profile/profile.c
--- a/head/sys/cddl/dev/profile/profile.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cddl/dev/profile/profile.c	Tue Apr 17 11:51:51 2012 +0300
@@ -20,7 +20,7 @@
  *
  * Portions Copyright 2006-2008 John Birrell jb at freebsd.org
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/cddl/dev/profile/profile.c 233409 2012-03-24 05:14:3=
7Z gonzo $
  *
  */
=20
@@ -112,6 +112,13 @@
 #endif
 #endif
=20
+#ifdef __mips
+/*
+ * This value is bogus just to make module compilable on mips
+ */
+#define	PROF_ARTIFICIAL_FRAMES	3
+#endif
+
 typedef struct profile_probe {
 	char		prof_name[PROF_NAMELEN];
 	dtrace_id_t	prof_id;
diff -r 428842767fa6 -r f2935497fa04 head/sys/cddl/dev/sdt/sdt.c
--- a/head/sys/cddl/dev/sdt/sdt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/cddl/dev/sdt/sdt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -20,7 +20,7 @@
  *
  * Portions Copyright 2006-2008 John Birrell jb at freebsd.org
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/cddl/dev/sdt/sdt.c 233552 2012-03-27 15:07:43Z rston=
e $
  *
  */
=20
@@ -52,6 +52,8 @@
 static void	sdt_enable(void *, dtrace_id_t, void *);
 static void	sdt_disable(void *, dtrace_id_t, void *);
 static void	sdt_load(void *);
+static int	sdt_provider_unreg_callback(struct sdt_provider *prov,=20
+		    void *arg);
=20
 static struct cdevsw sdt_cdevsw =3D {
 	.d_version	=3D D_VERSION,
@@ -190,7 +192,8 @@
=20
 	sdt_probe_func =3D dtrace_probe;
=20
-	(void) sdt_provider_listall(sdt_provider_reg_callback, NULL);
+	sdt_register_callbacks(sdt_provider_reg_callback, NULL,
+	    sdt_provider_unreg_callback, NULL, sdt_probe_callback, NULL);
 }
=20
 static int
@@ -206,7 +209,7 @@
=20
 	sdt_probe_func =3D sdt_probe_stub;
=20
-	(void) sdt_provider_listall(sdt_provider_unreg_callback, NULL);
+	sdt_deregister_callbacks();
 =09
 	destroy_dev(sdt_cdev);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/compat/linux/linux_file.c
--- a/head/sys/compat/linux/linux_file.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/compat/linux/linux_file.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/compat/linux/linux_file.c 230132 2012-01-15 1=
3:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/compat/linux/linux_file.c 234352 2012-04-16 2=
1:22:02Z jkim $");
=20
 #include "opt_compat.h"
=20
@@ -69,6 +69,9 @@
 #include <compat/linux/linux_util.h>
 #include <compat/linux/linux_file.h>
=20
+/* XXX */
+int	do_pipe(struct thread *td, int fildes[2], int flags);
+
 int
 linux_creat(struct thread *td, struct linux_creat_args *args)
 {
@@ -1575,3 +1578,49 @@
 	return (kern_posix_fadvise(td, args->fd, args->offset, args->len,
 	    advice));
 }
+
+int
+linux_pipe(struct thread *td, struct linux_pipe_args *args)
+{
+	int fildes[2];
+	int error;
+
+#ifdef DEBUG
+	if (ldebug(pipe))
+		printf(ARGS(pipe, "*"));
+#endif
+
+	error =3D do_pipe(td, fildes, 0);
+	if (error)
+		return (error);
+
+	/* XXX: Close descriptors on error. */
+	return (copyout(fildes, args->pipefds, sizeof(fildes)));
+}
+
+int
+linux_pipe2(struct thread *td, struct linux_pipe2_args *args)
+{
+	int fildes[2];
+	int error, flags;
+
+#ifdef DEBUG
+	if (ldebug(pipe2))
+		printf(ARGS(pipe2, "*, %d"), args->flags);
+#endif
+
+	if ((args->flags & ~(LINUX_O_NONBLOCK | LINUX_O_CLOEXEC)) !=3D 0)
+		return (EINVAL);
+
+	flags =3D 0;
+	if ((args->flags & LINUX_O_NONBLOCK) !=3D 0)
+		flags |=3D O_NONBLOCK;
+	if ((args->flags & LINUX_O_CLOEXEC) !=3D 0)
+		flags |=3D O_CLOEXEC;
+	error =3D do_pipe(td, fildes, flags);
+	if (error)
+		return (error);
+
+	/* XXX: Close descriptors on error. */
+	return (copyout(fildes, args->pipefds, sizeof(fildes)));
+}
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/NOTES
--- a/head/sys/conf/NOTES	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/NOTES	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/NOTES 233178 2012-03-19 13:16:46Z ae $
+# $FreeBSD: head/sys/conf/NOTES 234302 2012-04-14 23:53:31Z davide $
 #
 # NOTES -- Lines that can be cut/pasted into kernel and hints configs.
 #
@@ -300,7 +300,8 @@
 # Profiling for internal hash tables.
 options 	SLEEPQUEUE_PROFILING
 options 	TURNSTILE_PROFILING
-options		UMTX_PROFILING
+options 	UMTX_PROFILING
+
=20
 #####################################################################
 # COMPATIBILITY OPTIONS
@@ -1715,12 +1716,12 @@
 # For example to build a system which only supports a VIA chipset,
 # omit 'ata' and include the 'atacore', 'atapci' and 'atavia' drivers.
 device		ata
-device		atadisk		# ATA disk drives
-device		ataraid		# ATA RAID drives
-device		atapicd		# ATAPI CDROM drives
-device		atapifd		# ATAPI floppy drives
-device		atapist		# ATAPI tape drives
-device		atapicam	# emulate ATAPI devices as SCSI ditto via CAM
+#device		atadisk		# ATA disk drives
+#device		ataraid		# ATA RAID drives
+#device		atapicd		# ATAPI CDROM drives
+#device		atapifd		# ATAPI floppy drives
+#device		atapist		# ATAPI tape drives
+#device		atapicam	# emulate ATAPI devices as SCSI ditto via CAM
 				# needs CAM to be present (scbus & pass)
=20
 # Modular ATA
@@ -2530,6 +2531,7 @@
 # ic	i2c network interface
 # iic	i2c standard io
 # iicsmb i2c to smb bridge. Allow i2c i/o with smb commands.
+# iicoc simple polling driver for OpenCores I2C controller
 #
 # Supported interfaces:
 # bktr	brooktree848 I2C software interface
@@ -2543,13 +2545,16 @@
 device		ic
 device		iic
 device		iicsmb		# smb over i2c bridge
+device		iicoc		# OpenCores I2C controller support
=20
 # I2C peripheral devices
 #
 # ds133x	Dallas Semiconductor DS1337, DS1338 and DS1339 RTC
+# ds1374	Dallas Semiconductor DS1374 RTC
 # ds1672	Dallas Semiconductor DS1672 RTC
 #
 device		ds133x
+device		ds1374
 device		ds1672
=20
 # Parallel-Port Bus
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files
--- a/head/sys/conf/files	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/files 233178 2012-03-19 13:16:46Z ae $
+# $FreeBSD: head/sys/conf/files 234248 2012-04-13 23:07:32Z marius $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -139,6 +139,131 @@
 cam/scsi/scsi_targ_bh.c		optional targbh
 cam/scsi/scsi_target.c		optional targ
 cam/scsi/smp_all.c		optional scbus
+# shared between zfs and dtrace
+cddl/compat/opensolaris/kern/opensolaris.c				optional zfs compile-with "$=
{ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_cmn_err.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_kmem.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_misc.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_sunddi.c			optional zfs compile-w=
ith "${ZFS_C}"
+# zfs specific
+cddl/compat/opensolaris/kern/opensolaris_acl.c				optional zfs compile-wit=
h "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_kobj.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_kstat.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_lookup.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_policy.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_string.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_sysevent.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_taskq.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_uio.c				optional zfs compile-wit=
h "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_vfs.c				optional zfs compile-wit=
h "${ZFS_C}"
+cddl/compat/opensolaris/kern/opensolaris_zone.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/common/acl/acl_common.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/common/avl/avl.c				optional zfs compile-with "${=
ZFS_C}"
+cddl/contrib/opensolaris/common/nvpair/nvpair.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/common/nvpair/nvpair_alloc_fixed.c		optional zfs =
compile-with "${ZFS_C}"
+cddl/contrib/opensolaris/common/unicode/u8_textprep.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zfs_comutil.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zfs_deleg.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zfs_fletcher.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zfs_ioctl_compat.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zfs_namecheck.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zfs_prop.c				optional zfs compile-wit=
h "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zpool_prop.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/common/zfs/zprop_common.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/gfs.c				optional zfs compile-with =
"${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/vnode.c				optional zfs compile-wit=
h "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/bplist.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/bpobj.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dbuf.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/ddt.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/ddt_zap.c			optional zfs compil=
e-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_diff.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_object.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_objset.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_send.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_traverse.c		optional zfs co=
mpile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_tx.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_zfetch.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dnode.c			optional zfs compile-=
with "${ZFS_C}" \
+	warning "kernel contains CDDL licensed ZFS filesystem"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dnode_sync.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dataset.c		optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deadlist.c		optional zfs co=
mpile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deleg.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dir.c			optional zfs compil=
e-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_prop.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_scan.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_synctask.c		optional zfs co=
mpile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/gzip.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/lzjb.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/metaslab.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/refcount.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/rrwlock.c			optional zfs compil=
e-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/sa.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/sha256.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/spa_config.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/spa_errlog.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/spa_history.c		optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/space_map.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/txg.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/uberblock.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/unique.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_cache.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_file.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_label.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_mirror.c		optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_missing.c		optional zfs co=
mpile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_queue.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_raidz.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_root.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zap.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zap_leaf.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zap_micro.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_acl.c			optional zfs compil=
e-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_byteswap.c		optional zfs co=
mpile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ctldir.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_debug.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_dir.c			optional zfs compil=
e-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_fm.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_fuid.c			optional zfs compi=
le-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_log.c			optional zfs compil=
e-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_onexit.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_replay.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_rlock.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_sa.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vfsops.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_vnops.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_znode.c			optional zfs comp=
ile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zil.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zio.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zio_checksum.c		optional zfs co=
mpile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zio_compress.c		optional zfs co=
mpile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zio_inject.c			optional zfs com=
pile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zle.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zrlock.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/fs/zfs/zvol.c			optional zfs compile-w=
ith "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/os/callb.c				optional zfs compile-wit=
h "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/os/fm.c				optional zfs compile-with "=
${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/os/list.c				optional zfs compile-with=
 "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/os/nvpair_alloc_system.c		optional zfs=
 compile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/adler32.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/deflate.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/inffast.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/inflate.c			optional zfs compile-=
with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/inftrees.c			optional zfs compile=
-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/opensolaris_crc32.c		optional zfs=
 compile-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/trees.c			optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/zmod.c				optional zfs compile-wi=
th "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/zmod_subr.c			optional zfs compil=
e-with "${ZFS_C}"
+cddl/contrib/opensolaris/uts/common/zmod/zutil.c			optional zfs compile-wi=
th "${ZFS_C}"
 contrib/altq/altq/altq_cbq.c	optional altq \
 	compile-with "${NORMAL_C} -I$S/contrib/pf"
 contrib/altq/altq/altq_cdnr.c	optional altq
@@ -415,7 +540,7 @@
 crypto/sha1.c			optional carp | crypto | ipsec | \
 					 netgraph_mppc_encryption | sctp
 crypto/sha2/sha2.c		optional crypto | geom_bde | ipsec | random | \
-					 sctp
+					 sctp | zfs
 ddb/db_access.c			optional	ddb
 ddb/db_break.c			optional	ddb
 ddb/db_capture.c		optional	ddb
@@ -553,7 +678,6 @@
 dev/ata/chipsets/ata-adaptec.c	optional ata pci | ataadaptec
 dev/ata/chipsets/ata-amd.c	optional ata pci | ataamd
 dev/ata/chipsets/ata-ati.c	optional ata pci | ataati
-dev/ata/chipsets/ata-atp8620.c	optional ata pci | atp8620
 dev/ata/chipsets/ata-cenatek.c	optional ata pci | atacenatek
 dev/ata/chipsets/ata-cypress.c	optional ata pci | atacypress
 dev/ata/chipsets/ata-cyrix.c	optional ata pci | atacyrix
@@ -868,8 +992,6 @@
 #=20
 dev/bce/if_bce.c		optional bce
 dev/bfe/if_bfe.c		optional bfe
-dev/bfe/if_bfe_pci.c		optional bfe pci
-dev/bfe/if_bfe_siba.c		optional bfe siba
 dev/bge/if_bge.c		optional bge
 dev/bktr/bktr_audio.c		optional bktr pci
 dev/bktr/bktr_card.c		optional bktr pci
@@ -1126,8 +1248,6 @@
 dev/gpio/gpioled.c		optional gpioled
 dev/gpio/gpio_if.m		optional gpio
 dev/gpio/gpiobus_if.m		optional gpio
-dev/gpio/gpiospi.c		optional gpiospi
-dev/gpio/gpioreset.c		optional gpioreset
 dev/hatm/if_hatm.c		optional hatm pci
 dev/hatm/if_hatm_intr.c		optional hatm pci
 dev/hatm/if_hatm_ioctl.c	optional hatm pci
@@ -1140,6 +1260,7 @@
 dev/hptiop/hptiop.c		optional hptiop scbus
 dev/hwpmc/hwpmc_logging.c	optional hwpmc
 dev/hwpmc/hwpmc_mod.c		optional hwpmc
+dev/hwpmc/hwpmc_soft.c		optional hwpmc
 dev/ichsmb/ichsmb.c		optional ichsmb
 dev/ichsmb/ichsmb_pci.c		optional ichsmb pci
 dev/ida/ida.c			optional ida
@@ -1154,6 +1275,7 @@
 dev/ieee488/upd7210.c		optional pcii | tnt4882
 dev/iicbus/ad7418.c		optional ad7418
 dev/iicbus/ds133x.c		optional ds133x
+dev/iicbus/ds1374.c		optional ds1374
 dev/iicbus/ds1672.c		optional ds1672
 dev/iicbus/icee.c		optional icee
 dev/iicbus/if_ic.c		optional ic
@@ -1165,6 +1287,8 @@
 dev/iicbus/iiconf.c		optional iicbus
 dev/iicbus/iicsmb.c		optional iicsmb				\
 	dependency	"iicbus_if.h"
+dev/iicbus/iicoc.c		optional iicoc
+dev/iicbus/pcf8563.c		optional pcf8563
 dev/iir/iir.c			optional iir
 dev/iir/iir_ctrl.c		optional iir
 dev/iir/iir_pci.c		optional iir pci
@@ -1435,13 +1559,14 @@
 dev/mfi/mfi_debug.c		optional mfi
 dev/mfi/mfi_pci.c		optional mfi pci
 dev/mfi/mfi_disk.c		optional mfi
+dev/mfi/mfi_syspd.c		optional mfi
+dev/mfi/mfi_tbolt.c		optional mfi
 dev/mfi/mfi_linux.c		optional mfi compat_linux
 dev/mfi/mfi_cam.c		optional mfip scbus
 dev/mii/acphy.c			optional miibus | acphy
 dev/mii/amphy.c			optional miibus | amphy
 dev/mii/atphy.c			optional miibus | atphy
 dev/mii/axphy.c			optional miibus | axphy
-dev/mii/bfeswitch.c		optional miibus | bfeswitch
 dev/mii/bmtphy.c		optional miibus | bmtphy
 dev/mii/brgphy.c		optional miibus | brgphy
 dev/mii/ciphy.c			optional miibus | ciphy
@@ -1486,7 +1611,8 @@
 dev/mps/mps_config.c		optional mps
 dev/mps/mps_mapping.c		optional mps
 dev/mps/mps_pci.c		optional mps pci
-dev/mps/mps_sas.c		optional mps
+dev/mps/mps_sas.c		optional mps \
+	compile-with "${NORMAL_C} ${NO_WUNNEEDED_INTERNAL_DECL}"
 dev/mps/mps_sas_lsi.c		optional mps
 dev/mps/mps_table.c		optional mps
 dev/mps/mps_user.c		optional mps
@@ -1633,6 +1759,7 @@
 dev/quicc/quicc_core.c		optional quicc
 dev/ral/rt2560.c		optional ral
 dev/ral/rt2661.c		optional ral
+dev/ral/rt2860.c		optional ral
 dev/ral/if_ral_pci.c		optional ral pci
 rt2561fw.c			optional rt2561fw | ralfw		\
 	compile-with	"${AWK} -f $S/tools/fw_stub.awk rt2561.fw:rt2561fw -mrt2561 =
-c${.TARGET}" \
@@ -1702,13 +1829,6 @@
 dev/rp/rp.c			optional rp
 dev/rp/rp_isa.c			optional rp isa
 dev/rp/rp_pci.c			optional rp pci
-dev/rt2860/rt2860_io.c		optional rt2860
-dev/rt2860/rt2860_read_eeprom.c	optional rt2860
-dev/rt2860/rt2860_led.c		optional rt2860
-dev/rt2860/rt2860_rf.c		optional rt2860
-dev/rt2860/rt2860_amrr.c	optional rt2860
-dev/rt2860/rt2860.c		optional rt2860
-dev/rt2860/rt2860_pci.c		optional rt2860 pci
 dev/safe/safe.c			optional safe
 dev/scc/scc_if.m		optional scc
 dev/scc/scc_bfe_ebus.c		optional scc ebus
@@ -1922,8 +2042,6 @@
 dev/usb/controller/musb_otg.c		optional musb
 dev/usb/controller/musb_otg_atmelarm.c	optional musb at91rm9200
 dev/usb/controller/dotg.c		optional dotg
-# XXX octe is ether, should depend on something like ciu
-dev/usb/controller/dotg_octeon.c	optional dotg usb octe
 dev/usb/controller/ehci.c		optional ehci
 dev/usb/controller/ehci_pci.c		optional ehci pci
 dev/usb/controller/ohci.c		optional ohci
@@ -2285,7 +2403,6 @@
 geom/part/g_part_bsd.c		optional geom_part_bsd
 geom/part/g_part_ebr.c		optional geom_part_ebr
 geom/part/g_part_gpt.c		optional geom_part_gpt
-geom/part/g_part_ldm.c		optional geom_part_ldm
 geom/part/g_part_mbr.c		optional geom_part_mbr
 geom/part/g_part_pc98.c		optional geom_part_pc98
 geom/part/g_part_vtoc8.c	optional geom_part_vtoc8
@@ -2449,8 +2566,8 @@
 kern/serdev_if.m		standard
 kern/stack_protector.c		standard \
 	compile-with "${NORMAL_C:N-fstack-protector*}"
-kern/subr_acl_nfs4.c		optional ufs_acl
-kern/subr_acl_posix1e.c		optional ufs_acl
+kern/subr_acl_nfs4.c		standard
+kern/subr_acl_posix1e.c		standard
 kern/subr_autoconf.c		standard
 kern/subr_blist.c		standard
 kern/subr_bus.c			standard
@@ -2836,7 +2953,7 @@
 netinet/ip_gre.c		optional gre inet
 netinet/ip_id.c			optional inet
 netinet/in_mcast.c		optional inet
-netinet/in_pcb.c		optional inet
+netinet/in_pcb.c		optional inet | inet6
 netinet/in_pcbgroup.c		optional inet pcbgroup | inet6 pcbgroup
 netinet/in_proto.c		optional inet | inet6 \
 	compile-with "${NORMAL_C} -I$S/contrib/pf"
@@ -3113,19 +3230,19 @@
 #	no-depend							\
 #	compile-with "${OFED_C} -I$S/ofed/drivers/infiniband/ulp/ipoib/"
=20
-ofed/drivers/infiniband/ulp/sdp/sdp_bcopy.c	optional sdp		\
+ofed/drivers/infiniband/ulp/sdp/sdp_bcopy.c	optional sdp inet	\
 	no-depend							\
 	compile-with "${OFED_C} -I$S/ofed/drivers/infiniband/ulp/sdp/"
-ofed/drivers/infiniband/ulp/sdp/sdp_main.c	optional sdp		\
+ofed/drivers/infiniband/ulp/sdp/sdp_main.c	optional sdp inet 	\
 	no-depend							\
 	compile-with "${OFED_C} -I$S/ofed/drivers/infiniband/ulp/sdp/"
-ofed/drivers/infiniband/ulp/sdp/sdp_rx.c	optional sdp		\
+ofed/drivers/infiniband/ulp/sdp/sdp_rx.c	optional sdp inet 	\
 	no-depend							\
 	compile-with "${OFED_C} -I$S/ofed/drivers/infiniband/ulp/sdp/"
-ofed/drivers/infiniband/ulp/sdp/sdp_cma.c	optional sdp		\
+ofed/drivers/infiniband/ulp/sdp/sdp_cma.c	optional sdp inet 	\
 	no-depend							\
 	compile-with "${OFED_C} -I$S/ofed/drivers/infiniband/ulp/sdp/"
-ofed/drivers/infiniband/ulp/sdp/sdp_tx.c	optional sdp		\
+ofed/drivers/infiniband/ulp/sdp/sdp_tx.c	optional sdp inet 	\
 	no-depend							\
 	compile-with "${OFED_C} -I$S/ofed/drivers/infiniband/ulp/sdp/"
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.amd64
--- a/head/sys/conf/files.amd64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.amd64	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 # This file tells config what files go into building a kernel,
 # files marked standard are always included.
 #
-# $FreeBSD: head/sys/conf/files.amd64 232747 2012-03-09 20:43:29Z jhb $
+# $FreeBSD: head/sys/conf/files.amd64 234118 2012-04-11 02:42:01Z marcel $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -113,7 +113,6 @@
 amd64/amd64/in_cksum.c		optional	inet | inet6
 amd64/amd64/initcpu.c		standard
 amd64/amd64/io.c		optional	io
-amd64/amd64/legacy.c		standard
 amd64/amd64/locore.S		standard	no-obj
 amd64/amd64/machdep.c		standard
 amd64/amd64/mem.c		optional	mem
@@ -133,6 +132,7 @@
 amd64/amd64/uma_machdep.c	standard
 amd64/amd64/vm_machdep.c	standard
 amd64/pci/pci_cfgreg.c		optional	pci
+cddl/contrib/opensolaris/common/atomic/amd64/opensolaris_atomic.S	optional=
 zfs compile-with "${ZFS_S}"
 crypto/aesni/aesencdec_amd64.S	optional aesni
 crypto/aesni/aeskeys_amd64.S	optional aesni
 crypto/aesni/aesni.c		optional aesni
@@ -267,7 +267,7 @@
 dev/tpm/tpm.c			optional	tpm
 dev/tpm/tpm_acpi.c		optional	tpm acpi
 dev/tpm/tpm_isa.c		optional	tpm isa
-dev/uart/uart_cpu_amd64.c	optional	uart
+dev/uart/uart_cpu_x86.c		optional	uart
 dev/viawd/viawd.c		optional	viawd
 dev/wbwd/wbwd.c			optional	wbwd
 dev/wpi/if_wpi.c		optional	wpi
@@ -476,6 +476,7 @@
 x86/x86/dump_machdep.c		standard
 x86/x86/intr_machdep.c		standard
 x86/x86/io_apic.c		standard
+x86/x86/legacy.c		standard
 x86/x86/local_apic.c		standard
 x86/x86/mca.c			standard
 x86/x86/mptable.c		optional	mptable
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.arm
--- a/head/sys/conf/files.arm	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.arm	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/files.arm 226808 2011-10-26 19:07:36Z cognet $
+# $FreeBSD: head/sys/conf/files.arm 233578 2012-03-27 21:23:56Z peter $
 crypto/blowfish/bf_enc.c	optional	crypto | ipsec=20
 crypto/des/des_enc.c		optional	crypto | ipsec | netsmb
 arm/arm/autoconf.c		standard
@@ -47,6 +47,7 @@
 arm/fpe-arm/armfpe_glue.S	optional	armfpe
 arm/fpe-arm/armfpe_init.c	optional	armfpe
 arm/fpe-arm/armfpe.S		optional	armfpe
+cddl/compat/opensolaris/kern/opensolaris_atomic.c	optional zfs compile-wit=
h "${ZFS_C}"
 dev/hwpmc/hwpmc_arm.c		optional	hwpmc
 dev/ofw/openfirm.c		optional	fdt
 dev/ofw/openfirmio.c		optional	fdt
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.i386
--- a/head/sys/conf/files.i386	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.i386	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 # This file tells config what files go into building a kernel,
 # files marked standard are always included.
 #
-# $FreeBSD: head/sys/conf/files.i386 232747 2012-03-09 20:43:29Z jhb $
+# $FreeBSD: head/sys/conf/files.i386 234118 2012-04-11 02:42:01Z marcel $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -71,6 +71,7 @@
 	compile-with	"uudecode < $S/dev/hptrr/i386-elf.hptrr_lib.o.uu" \
 	no-implicit-rule
 #
+cddl/contrib/opensolaris/common/atomic/i386/opensolaris_atomic.S	optional =
zfs compile-with "${ZFS_S}"
 compat/linprocfs/linprocfs.c	optional linprocfs
 compat/linsysfs/linsysfs.c	optional linsysfs
 compat/linux/linux_emul.c	optional compat_linux
@@ -243,7 +244,7 @@
 dev/tpm/tpm.c			optional tpm
 dev/tpm/tpm_acpi.c		optional tpm acpi
 dev/tpm/tpm_isa.c		optional tpm isa
-dev/uart/uart_cpu_i386.c	optional uart
+dev/uart/uart_cpu_x86.c		optional uart
 dev/viawd/viawd.c		optional viawd
 dev/acpica/acpi_if.m		standard
 dev/acpi_support/acpi_wmi_if.m	standard
@@ -407,7 +408,6 @@
 i386/i386/initcpu.c		standard
 i386/i386/io.c			optional io
 i386/i386/k6_mem.c		optional mem
-i386/i386/legacy.c		optional native
 i386/i386/locore.s		optional native	no-obj
 i386/xen/locore.s		optional xen	no-obj
 i386/i386/longrun.c		optional cpu_enable_longrun
@@ -528,6 +528,7 @@
 x86/x86/dump_machdep.c		standard
 x86/x86/intr_machdep.c		standard
 x86/x86/io_apic.c		optional apic
+x86/x86/legacy.c		optional native
 x86/x86/local_apic.c		optional apic
 x86/x86/mca.c			standard
 x86/x86/mptable.c		optional apic native
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.ia64
--- a/head/sys/conf/files.ia64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.ia64	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 # This file tells config what files go into building a kernel,
 # files marked standard are always included.
 #
-# $FreeBSD: head/sys/conf/files.ia64 223526 2011-06-25 02:15:14Z marcel $
+# $FreeBSD: head/sys/conf/files.ia64 233578 2012-03-27 21:23:56Z peter $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -28,6 +28,7 @@
 	no-obj no-implicit-rule before-depend				\
 	clean		"ukbdmap.h"
 #
+cddl/contrib/opensolaris/common/atomic/ia64/opensolaris_atomic.S	optional =
zfs compile-with "${ZFS_S}"
 compat/freebsd32/freebsd32_ioctl.c	optional	compat_freebsd32
 compat/freebsd32/freebsd32_misc.c	optional	compat_freebsd32
 compat/freebsd32/freebsd32_syscalls.c	optional	compat_freebsd32
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.mips
--- a/head/sys/conf/files.mips	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.mips	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
 # Copyright (c) 2001, 2004-2005, Juniper Networks, Inc.
 # All rights reserved.
 # JNPR: files.mips,v 1.11 2007/08/09 12:25:35 katta
-# $FreeBSD: head/sys/conf/files.mips 232896 2012-03-12 21:25:32Z jmallett $
+# $FreeBSD: head/sys/conf/files.mips 233578 2012-03-27 21:23:56Z peter $
 #
 # ----------------------------------------------------------------------
 # Phase 2
@@ -85,6 +85,7 @@
 #libkern/mips/strcmp.S		standard
 #libkern/mips/strncmp.S		standard
=20
+cddl/compat/opensolaris/kern/opensolaris_atomic.c	optional zfs compile-wit=
h "${ZFS_C}"
 compat/freebsd32/freebsd32_ioctl.c	optional	compat_freebsd32
 compat/freebsd32/freebsd32_misc.c	optional	compat_freebsd32
 compat/freebsd32/freebsd32_syscalls.c	optional	compat_freebsd32
@@ -112,9 +113,9 @@
 #mips/sentry5/siba_mips.c			optional siba # not yet
=20
 dev/hwpmc/hwpmc_mips.c		optional hwpmc
-dev/hwpmc/hwpmc_mips24k.c	optional hwpmc
=20
 dev/rt2860/rt2860_nexus.c	optional 	rt2860
+dev/ral/if_ral_nexus.c		optional 	ral
 dev/rt/if_rt.c			optional 	rt
 dev/nvram2env/nvram2env.c	optional	nvram2env
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.pc98
--- a/head/sys/conf/files.pc98	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.pc98	Tue Apr 17 11:51:51 2012 +0300
@@ -3,7 +3,7 @@
 #
 # modified for PC-9801/PC-9821
 #
-# $FreeBSD: head/sys/conf/files.pc98 233031 2012-03-16 12:13:44Z nyan $
+# $FreeBSD: head/sys/conf/files.pc98 233707 2012-03-30 19:10:14Z jhb $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -38,6 +38,7 @@
 	no-obj no-implicit-rule before-depend				\
 	clean		"ukbdmap.h"
 #
+cddl/contrib/opensolaris/common/atomic/i386/opensolaris_atomic.S	optional =
zfs compile-with "${ZFS_S}"
 compat/linprocfs/linprocfs.c	optional linprocfs
 compat/linsysfs/linsysfs.c	optional linsysfs
 compat/linux/linux_emul.c	optional compat_linux
@@ -146,7 +147,6 @@
 i386/i386/initcpu.c		standard
 i386/i386/io.c			optional io
 i386/i386/k6_mem.c		optional mem
-i386/i386/legacy.c		standard
 i386/i386/locore.s		standard	no-obj
 i386/i386/mem.c			optional mem
 i386/i386/minidump_machdep.c	standard
@@ -204,7 +204,6 @@
 	dependency	"svr4_assym.h"	\
 	warning "COMPAT_SVR4 is broken and should be avoided"
 i386/svr4/svr4_machdep.c	optional compat_svr4
-#
 kern/kern_clocksource.c		standard
 kern/imgact_aout.c		optional compat_aout
 kern/imgact_gzip.c		optional gzip
@@ -252,6 +251,7 @@
 x86/x86/dump_machdep.c		standard
 x86/x86/intr_machdep.c		standard
 x86/x86/io_apic.c		optional apic
+x86/x86/legacy.c		standard
 x86/x86/local_apic.c		optional apic
 x86/x86/mca.c			standard
 x86/x86/mptable.c		optional apic
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.powerpc
--- a/head/sys/conf/files.powerpc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.powerpc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 # This file tells config what files go into building a kernel,
 # files marked standard are always included.
 #
-# $FreeBSD: head/sys/conf/files.powerpc 232177 2012-02-26 13:45:25Z jhibbi=
ts $
+# $FreeBSD: head/sys/conf/files.powerpc 233578 2012-03-27 21:23:56Z peter $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -14,6 +14,9 @@
 	no-obj no-implicit-rule before-depend				\
 	clean	"font.h ${SC_DFLT_FONT}-8x14 ${SC_DFLT_FONT}-8x16 ${SC_DFLT_FONT}-8=
x8"
 #
+# There is only an asm version on ppc64.
+cddl/compat/opensolaris/kern/opensolaris_atomic.c			optional zfs powerpc c=
ompile-with "${ZFS_C}"
+cddl/contrib/opensolaris/common/atomic/powerpc64/opensolaris_atomic.S	opti=
onal zfs powerpc64 compile-with "${ZFS_S}"
 crypto/blowfish/bf_enc.c	optional	crypto | ipsec
 crypto/des/des_enc.c		optional	crypto | ipsec | netsmb
 dev/bm/if_bm.c			optional	bm powermac
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/files.sparc64
--- a/head/sys/conf/files.sparc64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/files.sparc64	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 # This file tells config what files go into building a kernel,
 # files marked standard are always included.
 #
-# $FreeBSD: head/sys/conf/files.sparc64 228022 2011-11-27 15:43:40Z marius=
 $
+# $FreeBSD: head/sys/conf/files.sparc64 233578 2012-03-27 21:23:56Z peter $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -22,6 +22,7 @@
 	no-obj no-implicit-rule before-depend				\
 	clean		"ukbdmap.h"
 #
+cddl/contrib/opensolaris/common/atomic/sparc64/opensolaris_atomic.S	option=
al zfs compile-with "${ZFS_S}"
 crypto/blowfish/bf_enc.c	optional	crypto | ipsec
 crypto/des/des_enc.c		optional	crypto | ipsec | netsmb
 dev/atkbdc/atkbd.c		optional	atkbd atkbdc
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/kern.mk
--- a/head/sys/conf/kern.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/kern.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/kern.mk 232933 2012-03-13 19:18:34Z dim $
+# $FreeBSD: head/sys/conf/kern.mk 233354 2012-03-23 11:35:01Z dim $
=20
 #
 # Warning flags for compiling the kernel and components of the kernel:
@@ -23,6 +23,7 @@
 NO_WUNUSED_VALUE=3D		-Wno-unused-value
 NO_WSELF_ASSIGN=3D		-Wno-self-assign
 NO_WFORMAT_SECURITY=3D		-Wno-format-security
+NO_WUNNEEDED_INTERNAL_DECL=3D	-Wno-unneeded-internal-declaration
 # Several other warnings which might be useful in some cases, but not seve=
re
 # enough to error out the whole kernel build.  Display them anyway, so the=
re is
 # some incentive to fix them eventually.
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/kern.post.mk
--- a/head/sys/conf/kern.post.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/kern.post.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/kern.post.mk 228158 2011-11-30 18:11:49Z fjoe $
+# $FreeBSD: head/sys/conf/kern.post.mk 233578 2012-03-27 21:23:56Z peter $
=20
 # Part of a unified Makefile for building kernels.  This part includes all
 # the definitions that need to be after all the % directives except %RULES
@@ -152,6 +152,12 @@
=20
 ${SYSTEM_OBJS} genassym.o vers.o: opt_global.h
=20
+# We have "special" -I include paths for opensolaris/zfs files in 'depend'.
+CFILES_NOZFS=3D	${CFILES:N*/opensolaris/*}
+SFILES_NOZFS=3D	${SFILES:N*/opensolaris/*}
+CFILES_ZFS=3D	${CFILES:M*/opensolaris/*}
+SFILES_ZFS=3D	${SFILES:M*/opensolaris/*}
+
 kernel-depend: .depend
 # The argument list can be very long, so use make -V and xargs to
 # pass it to mkdep.
@@ -160,10 +166,14 @@
 	${MFILES:T:S/.m$/.h/}
 .depend: .PRECIOUS ${SRCS}
 	rm -f .newdep
-	${MAKE} -V CFILES -V SYSTEM_CFILES -V GEN_CFILES | \
+	${MAKE} -V CFILES_NOZFS -V SYSTEM_CFILES -V GEN_CFILES | \
 	    MKDEP_CPP=3D"${CC} -E" CC=3D"${CC}" xargs mkdep -a -f .newdep ${CFLAG=
S}
-	${MAKE} -V SFILES | \
+	${MAKE} -V CFILES_ZFS | \
+	    MKDEP_CPP=3D"${CC} -E" CC=3D"${CC}" xargs mkdep -a -f .newdep ${ZFS_C=
FLAGS}
+	${MAKE} -V SFILES_NOZFS | \
 	    MKDEP_CPP=3D"${CC} -E" xargs mkdep -a -f .newdep ${ASM_CFLAGS}
+	${MAKE} -V SFILES_ZFS | \
+	    MKDEP_CPP=3D"${CC} -E" xargs mkdep -a -f .newdep ${ZFS_ASM_CFLAGS}
 	rm -f .depend
 	mv .newdep .depend
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/kern.pre.mk
--- a/head/sys/conf/kern.pre.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/kern.pre.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/kern.pre.mk 232477 2012-03-04 00:42:18Z dim $
+# $FreeBSD: head/sys/conf/kern.pre.mk 233644 2012-03-29 02:54:35Z jmallett=
 $
=20
 # Part of a unified Makefile for building kernels.  This part contains all
 # of the definitions that need to be before %BEFORE_DEPEND.
@@ -6,7 +6,7 @@
 .include <bsd.own.mk>
=20
 # backwards compat option for older systems.
-MACHINE_CPUARCH?=3D${MACHINE_ARCH:C/mipse[lb]/mips/:C/armeb/arm/:C/powerpc=
64/powerpc/}
+MACHINE_CPUARCH?=3D${MACHINE_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/:=
C/powerpc64/powerpc/}
=20
 # Can be overridden by makeoptions or /etc/make.conf
 KERNEL_KO?=3D	kernel
@@ -131,6 +131,12 @@
 NORMAL_M=3D ${AWK} -f $S/tools/makeobjops.awk ${.IMPSRC} -c ; \
 	  ${CC} -c ${CFLAGS} ${WERROR} ${PROF} ${.PREFIX}.c
=20
+# Special flags for managing the compat compiles for ZFS
+ZFS_CFLAGS=3D	-DFREEBSD_NAMECACHE -DBUILDING_ZFS -nostdinc -I$S/cddl/compa=
t/opensolaris -I$S/cddl/contrib/opensolaris/uts/common/fs/zfs -I$S/cddl/con=
trib/opensolaris/uts/common/zmod -I$S/cddl/contrib/opensolaris/uts/common -=
I$S -I$S/cddl/contrib/opensolaris/common/zfs -I$S/cddl/contrib/opensolaris/=
common ${CFLAGS} -Wno-unknown-pragmas -Wno-missing-prototypes -Wno-undef -W=
no-strict-prototypes -Wno-cast-qual -Wno-parentheses -Wno-redundant-decls -=
Wno-missing-braces -Wno-uninitialized -Wno-unused -Wno-inline -Wno-switch -=
Wno-pointer-arith -Wno-unknown-pragmas
+ZFS_ASM_CFLAGS=3D -x assembler-with-cpp -DLOCORE ${ZFS_CFLAGS}
+ZFS_C=3D		${CC} -c ${ZFS_CFLAGS} ${WERROR} ${PROF} ${.IMPSRC}
+ZFS_S=3D		${CC} -c ${ZFS_ASM_CFLAGS} ${WERROR} ${.IMPSRC}
+
 .if ${MK_CTF} !=3D "no"
 NORMAL_CTFCONVERT=3D	${CTFCONVERT} ${CTFFLAGS} ${.TARGET}
 .elif ${MAKE_VERSION} >=3D 5201111300
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/kmod.mk
--- a/head/sys/conf/kmod.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/kmod.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	From: @(#)bsd.prog.mk	5.26 (Berkeley) 6/25/91
-# $FreeBSD: head/sys/conf/kmod.mk 232476 2012-03-03 23:49:53Z dim $
+# $FreeBSD: head/sys/conf/kmod.mk 233644 2012-03-29 02:54:35Z jmallett $
 #
 # The include file <bsd.kmod.mk> handles building and installing loadable
 # kernel modules.
@@ -61,7 +61,7 @@
 #
=20
 # backwards compat option for older systems.
-MACHINE_CPUARCH?=3D${MACHINE_ARCH:C/mipse[lb]/mips/:C/armeb/arm/:C/powerpc=
64/powerpc/}
+MACHINE_CPUARCH?=3D${MACHINE_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/:=
C/powerpc64/powerpc/}
=20
 AWK?=3D		awk
 KMODLOAD?=3D	/sbin/kldload
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/makeLINT.mk
--- a/head/sys/conf/makeLINT.mk	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/makeLINT.mk	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/makeLINT.mk 228021 2011-11-27 13:53:36Z jh $
+# $FreeBSD: head/sys/conf/makeLINT.mk 233893 2012-04-04 21:31:20Z jhb $
=20
 all:
 	@echo "make LINT only"
@@ -23,6 +23,7 @@
 	echo "nodevice gre"		>> ${.TARGET}-NOINET
 	echo "include ${.TARGET}"	>  ${.TARGET}-NOINET6
 	echo "ident ${.TARGET}-NOINET6"	>> ${.TARGET}-NOINET6
+	echo 'makeoptions MKMODULESENV+=3D"WITHOUT_INET6_SUPPORT=3D"' >> ${.TARGE=
T}-NOINET6
 	echo "nooptions INET6"		>> ${.TARGET}-NOINET6
 	echo "include ${.TARGET}"	>  ${.TARGET}-NOIP
 	echo "ident ${.TARGET}-NOIP"	>> ${.TARGET}-NOIP
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/options
--- a/head/sys/conf/options	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/options	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/options 233178 2012-03-19 13:16:46Z ae $
+# $FreeBSD: head/sys/conf/options 234231 2012-04-13 18:00:48Z adrian $
 #
 #        On the handling of kernel options
 #
@@ -783,6 +783,7 @@
 ATH_TX99_DIAG		opt_ath.h
 ATH_ENABLE_11N		opt_ath.h
 ATH_ENABLE_DFS		opt_ath.h
+ATH_EEPROM_FIRMWARE	opt_ath.h
=20
 # options for the Atheros hal
 AH_SUPPORT_AR5416	opt_ah.h
@@ -835,6 +836,7 @@
=20
 # HWPMC options
 HWPMC_HOOKS
+HWPMC_MIPS_BACKTRACE 	opt_hwpmc_hooks.h
=20
 # XBOX options for FreeBSD/i386, but some files are MI
 XBOX			opt_xbox.h
@@ -842,6 +844,8 @@
 # XFS
 XFS
=20
+ZFS			opt_dontuse.h
+
 # Interrupt filtering
 INTR_FILTER
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/options.amd64
--- a/head/sys/conf/options.amd64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/options.amd64	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/options.amd64 230843 2012-01-31 19:38:18Z jimhar=
ris $
+# $FreeBSD: head/sys/conf/options.amd64 233433 2012-03-24 19:43:49Z alc $
 # Options specific to AMD64 platform kernels
=20
 AUTO_EOI_1		opt_auto_eoi.h
@@ -7,10 +7,10 @@
 COUNT_IPIS		opt_smp.h
 MAXMEM
 PERFMON
-PMAP_SHPGPERPROC	opt_pmap.h
 MPTABLE_FORCE_HTT
 MP_WATCHDOG
 NKPT			opt_pmap.h
+PV_STATS		opt_pmap.h
=20
 # Options for emulators.  These should only be used at config time, so
 # they are handled like options for static filesystems
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/options.arm
--- a/head/sys/conf/options.arm	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/options.arm	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-#$FreeBSD$
+#$FreeBSD: head/sys/conf/options.arm 234004 2012-04-07 23:47:08Z stas $
 ARM9_CACHE_WRITE_THROUGH	opt_global.h
 ARM_CACHE_LOCK_ENABLE	opt_global.h
 ARMFPE			opt_global.h
@@ -23,6 +23,7 @@
 KERNVIRTADDR		opt_global.h
 LOADERRAMADDR		opt_global.h
 PHYSADDR		opt_global.h
+QEMU_WORKAROUNDS	opt_global.h
 SKYEYE_WORKAROUNDS	opt_global.h
 SOC_MV_DISCOVERY	opt_global.h
 SOC_MV_KIRKWOOD		opt_global.h
diff -r 428842767fa6 -r f2935497fa04 head/sys/conf/options.i386
--- a/head/sys/conf/options.i386	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/conf/options.i386	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/options.i386 230843 2012-01-31 19:38:18Z jimharr=
is $
+# $FreeBSD: head/sys/conf/options.i386 233433 2012-03-24 19:43:49Z alc $
 # Options specific to the i386 platform kernels
=20
 AUTO_EOI_1		opt_auto_eoi.h
@@ -16,6 +16,7 @@
 PERFMON
 PMAP_SHPGPERPROC	opt_pmap.h
 POWERFAIL_NMI		opt_trap.h
+PV_STATS		opt_pmap.h
=20
 # Options for emulators.  These should only be used at config time, so
 # they are handled like options for static filesystems
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/acpica_pre=
p.sh
--- a/head/sys/contrib/dev/acpica/acpica_prep.sh	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/sys/contrib/dev/acpica/acpica_prep.sh	Tue Apr 17 11:51:51 2012 +=
0300
@@ -1,5 +1,5 @@
 #!/bin/sh
-# $FreeBSD: head/sys/contrib/dev/acpica/acpica_prep.sh 231844 2012-02-16 2=
2:59:29Z jkim $
+# $FreeBSD: head/sys/contrib/dev/acpica/acpica_prep.sh 233250 2012-03-20 2=
1:37:52Z jkim $
 #
 # Unpack an ACPI CA drop and restructure it to fit the FreeBSD layout
 #
@@ -31,7 +31,7 @@
 	actbl2.h actbl3.h actypes.h acutils.h amlcode.h amlresrc.h	\
 	platform/acenv.h platform/acfreebsd.h platform/acgcc.h"
 comp_headers=3D"aslcompiler.h asldefine.h aslglobal.h aslmessages.h	\
-	asltypes.h dtcompiler.h dttemplate.h"
+	asltypes.h dtcompiler.h dttemplate.h preprocess.h"
 platform_headers=3D"acfreebsd.h acgcc.h"
=20
 # pre-clean
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/changes.txt
--- a/head/sys/contrib/dev/acpica/changes.txt	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/changes.txt	Tue Apr 17 11:51:51 2012 +0300
@@ -1,3 +1,95 @@
+----------------------------------------
+20 March 2012. Summary of changes for version 20120320:
+
+This release is available at www.acpica.org/downloads.
+The ACPI 5.0 specification is available at www.acpi.info.
+
+1) ACPICA Core Subsystem:
+
+Enhanced the sleep/wake interfaces to optionally execute the _GTS method=20
+(Going To Sleep) and the _BFS method (Back From Sleep). Windows apparently=20
+does not execute these methods, and therefore these methods are often=20
+untested. It has been seen on some systems where the execution of these=20
+methods causes errors and also prevents the machine from entering S5. It i=
s=20
+therefore suggested that host operating systems do not execute these metho=
ds=20
+by default. In the future, perhaps these methods can be optionally execute=
d=20
+based on the age of the system and/or what is the newest version of Window=
s=20
+that the BIOS asks for via _OSI. Changed interfaces: AcpiEnterSleepState a=
nd=20
+AcpileaveSleepStatePrep. See the ACPICA reference and Linux BZ 13041. Lin=20
+Ming.
+
+Fixed a problem where the length of the local/common FADT was set too earl=
y.=20
+The local FADT table length cannot be set to the common length until the=20
+original length has been examined. There is code that checks the table len=
gth=20
+and sets various fields appropriately. This can affect older machines with=20
+early FADT versions. For example, this can cause inadvertent writes to the=20
+CST_CNT register. Julian Anastasov.
+
+Fixed a mapping issue related to a physical table override. Use the deferr=
ed=20
+mapping mechanism for tables loaded via the physical override OSL interfac=
e.=20
+This allows for early mapping before the virtual memory manager is availab=
le.=20
+Thomas Renninger, Bob Moore.
+
+Enhanced the automatic return-object repair code: Repair a common problem =
with=20
+predefined methods that are defined to return a variable-length Package of=20
+sub-objects. If there is only one sub-object, some BIOS ASL code mistakenl=
y=20
+simply returns the single object instead of a Package with one sub-object.=20
+This new support will repair this error by wrapping a Package object aroun=
d=20
+the original object, creating the correct and expected Package with one su=
b-
+object. Names that can be repaired in this manner include: _ALR, _CSD, _HP=
X,=20
+_MLS, _PLD, _PRT, _PSS, _TRT, _TSS, _BCL, _DOD, _FIX, and _Sx. ACPICA BZ 9=
39.
+
+Changed the exception code returned for invalid ACPI paths passed as=20
+parameters to external interfaces such as AcpiEvaluateObject. Was=20
+AE_BAD_PARAMETER, now is the more sensible AE_BAD_PATHNAME.
+
+Example Code and Data Size: These are the sizes for the OS-independent=20
+acpica.lib produced by the Microsoft Visual C++ 9.0 32-bit compiler. The d=
ebug=20
+version of the code includes the debug output trace mechanism and has a mu=
ch=20
+larger code and data size.
+
+  Previous Release:
+    Non-Debug Version:  93.0K Code, 25.0K Data, 118.0K Total
+    Debug Version:     172.5K Code, 73.2K Data, 245.7K Total
+  Current Release:
+    Non-Debug Version:  92.9K Code, 25.0K Data, 117.9K Total
+    Debug Version:     172.5K Code, 73.2K Data, 245.7K Total
+
+
+2) iASL Compiler/Disassembler and Tools:
+
+iASL: Added the infrastructure and initial implementation of a integrated =
C-
+like preprocessor. This will simplify BIOS development process by eliminat=
ing=20
+the need for a separate preprocessing step during builds. On Windows, it a=
lso=20
+eliminates the need to install a separate C compiler. ACPICA BZ 761. Some=20
+features including full #define() macro support are still under developmen=
t.=20
+These preprocessor directives are supported:
+    #define
+    #elif
+    #else
+    #endif
+    #error
+    #if
+    #ifdef
+    #ifndef
+    #include
+    #pragma message
+    #undef
+    #warning
+In addition, these new command line options are supported:
+    -D <symbol> Define symbol for preprocessor use
+    -li         Create preprocessed output file (*.i)
+    -P          Preprocess only and create preprocessor output file (*.i)
+
+Table Compiler: Fixed a problem where the equals operator within an expres=
sion=20
+did not work properly.
+
+Updated iASL to use the current versions of Bison/Flex. Updated the Window=
s=20
+project file to invoke these tools from the standard location. ACPICA BZ 9=
04.=20
+Versions supported:
+    Flex for Windows:  V2.5.4
+    Bison for Windows: V2.4.1
+
 ----------------------------------------
 15 February 2012. Summary of changes for version 20120215:
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/common/adi=
sasm.c
--- a/head/sys/contrib/dev/acpica/common/adisasm.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/sys/contrib/dev/acpica/common/adisasm.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -75,6 +75,10 @@
=20
 /* Local prototypes */
=20
+static UINT32
+AdGetFileSize (
+    FILE                    *File);
+
 static void
 AdCreateTableHeader (
     char                    *Filename,
@@ -160,6 +164,38 @@
=20
 /*************************************************************************=
******
  *
+ * FUNCTION:    AdGetFileSize
+ *
+ * PARAMETERS:  File                - Open file handle
+ *
+ * RETURN:      File Size
+ *
+ * DESCRIPTION: Get current file size. Uses seek-to-EOF. File must be open.
+ *
+ *************************************************************************=
*****/
+
+static UINT32
+AdGetFileSize (
+    FILE                    *File)
+{
+    UINT32                  FileSize;
+    long                    Offset;
+
+
+    Offset =3D ftell (File);
+
+    fseek (File, 0, SEEK_END);
+    FileSize =3D (UINT32) ftell (File);
+
+    /* Restore file pointer */
+
+    fseek (File, Offset, SEEK_SET);
+    return (FileSize);
+}
+
+
+/*************************************************************************=
******
+ *
  * FUNCTION:    AdInitialize
  *
  * PARAMETERS:  None
@@ -380,8 +416,10 @@
             "FieldName : FieldValue\n */\n\n");
=20
         AcpiDmDumpDataTable (Table);
-        fprintf (stderr, "Acpi Data Table [%4.4s] decoded, written to \"%s=
\"\n",
-            Table->Signature, DisasmFilename);
+        fprintf (stderr, "Acpi Data Table [%4.4s] decoded\n",
+            Table->Signature);
+        fprintf (stderr, "Formatted output:  %s - %u bytes\n",
+            DisasmFilename, AdGetFileSize (File));
     }
     else
     {
@@ -490,9 +528,9 @@
         if (AcpiGbl_DbOpt_disasm)
         {
             AdDisplayTables (Filename, Table);
-            fprintf (stderr,
-                "Disassembly completed, written to \"%s\"\n",
-                DisasmFilename);
+            fprintf (stderr, "Disassembly completed\n");
+            fprintf (stderr, "ASL Output:    %s - %u bytes\n",
+                DisasmFilename, AdGetFileSize (File));
         }
     }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/common/get=
opt.c
--- a/head/sys/contrib/dev/acpica/common/getopt.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sys/contrib/dev/acpica/common/getopt.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -49,7 +49,8 @@
 #include <contrib/dev/acpica/include/accommon.h>
 #include <contrib/dev/acpica/include/acapps.h>
=20
-#define ERR(szz,czz) if(AcpiGbl_Opterr){fprintf(stderr,"%s%s%c\n",argv[0],=
szz,czz);}
+#define ACPI_OPTION_ERROR(msg, badchar) \
+    if (AcpiGbl_Opterr) {fprintf (stderr, "%s%c\n", msg, badchar);}
=20
=20
 int   AcpiGbl_Opterr =3D 1;
@@ -87,12 +88,12 @@
             argv[AcpiGbl_Optind][0] !=3D '-' ||
             argv[AcpiGbl_Optind][1] =3D=3D '\0')
         {
-            return(EOF);
+            return (EOF);
         }
         else if (strcmp (argv[AcpiGbl_Optind], "--") =3D=3D 0)
         {
             AcpiGbl_Optind++;
-            return(EOF);
+            return (EOF);
         }
     }
=20
@@ -105,7 +106,7 @@
     if (CurrentChar =3D=3D ':' ||
        (OptsPtr =3D strchr (opts, CurrentChar)) =3D=3D NULL)
     {
-        ERR (": illegal option -- ", CurrentChar);
+        ACPI_OPTION_ERROR ("Illegal option: -", CurrentChar);
=20
         if (argv[AcpiGbl_Optind][++CurrentCharPtr] =3D=3D '\0')
         {
@@ -126,7 +127,7 @@
         }
         else if (++AcpiGbl_Optind >=3D argc)
         {
-            ERR (": option requires an argument -- ", CurrentChar);
+            ACPI_OPTION_ERROR ("Option requires an argument: -", CurrentCh=
ar);
=20
             CurrentCharPtr =3D 1;
             return ('?');
@@ -156,6 +157,26 @@
         CurrentCharPtr =3D 1;
     }
=20
+    /* Option has a required single-char argument? */
+
+    else if (*OptsPtr =3D=3D '|')
+    {
+        if (argv[AcpiGbl_Optind][(int) (CurrentCharPtr+1)] !=3D '\0')
+        {
+            AcpiGbl_Optarg =3D &argv[AcpiGbl_Optind][(int) (CurrentCharPtr=
+1)];
+        }
+        else
+        {
+            ACPI_OPTION_ERROR ("Option requires a single-character subopti=
on: -", CurrentChar);
+
+            CurrentCharPtr =3D 1;
+            return ('?');
+        }
+
+        AcpiGbl_Optind++;
+        CurrentCharPtr =3D 1;
+    }
+
     /* Option with no arguments */
=20
     else
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slcodegen.c
--- a/head/sys/contrib/dev/acpica/compiler/aslcodegen.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslcodegen.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -264,7 +264,7 @@
         /* These opcodes should not get here */
=20
         printf ("Found a node with an unassigned AML opcode\n");
-        fprintf (stderr, "Found a node with an unassigned AML opcode\n");
+        FlPrintFile (ASL_FILE_STDERR, "Found a node with an unassigned AML=
 opcode\n");
         return;
=20
     case AML_INT_RESERVEDFIELD_OP:
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slcompile.c
--- a/head/sys/contrib/dev/acpica/compiler/aslcompile.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslcompile.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -457,6 +457,17 @@
     Event =3D UtBeginEvent ("Open input and output files");
     UtEndEvent (Event);
=20
+    /* Preprocessor */
+
+    Event =3D UtBeginEvent ("Preprocess input file");
+    PrDoPreprocess ();
+    UtEndEvent (Event);
+    if (Gbl_PreprocessOnly)
+    {
+        CmCleanupAndExit ();
+        return 0;
+    }
+
     /* Build the parse tree */
=20
     Event =3D UtBeginEvent ("Parse source code and build parse tree");
@@ -474,8 +485,7 @@
     {
         AslError (ASL_ERROR, ASL_MSG_COMPILER_INTERNAL,
             NULL, "- Could not resolve parse tree root node");
-        CmCleanupAndExit ();
-        return -1;
+        goto ErrorExit;
     }
=20
     /* Optional parse tree dump, compiler debug output only */
@@ -508,12 +518,12 @@
      */
     Event =3D UtBeginEvent ("Open AML output file");
     Status =3D FlOpenAmlOutputFile (Gbl_OutputFilenamePrefix);
+    UtEndEvent (Event);
     if (ACPI_FAILURE (Status))
     {
         AePrintErrorLog (ASL_FILE_STDERR);
         return -1;
     }
-    UtEndEvent (Event);
=20
     /* Interpret and generate all compile-time constants */
=20
@@ -552,6 +562,7 @@
             AePrintErrorLog (ASL_FILE_STDERR);
             UtDisplaySummary (ASL_FILE_STDERR);
         }
+        UtEndEvent (FullCompile);
         return 0;
     }
=20
@@ -566,7 +577,7 @@
     UtEndEvent (Event);
     if (ACPI_FAILURE (Status))
     {
-        return -1;
+        goto ErrorExit;
     }
=20
     /* Namespace cross-reference */
@@ -575,7 +586,7 @@
     Status =3D LkCrossReferenceNamespace ();
     if (ACPI_FAILURE (Status))
     {
-        return -1;
+        goto ErrorExit;
     }
=20
     /* Namespace - Check for non-referenced objects */
@@ -646,6 +657,11 @@
     UtEndEvent (FullCompile);
     CmCleanupAndExit ();
     return 0;
+
+ErrorExit:
+    UtEndEvent (FullCompile);
+    CmCleanupAndExit ();
+    return (-1);
 }
=20
=20
@@ -799,7 +815,9 @@
=20
     /* Close all open files */
=20
-    for (i =3D 2; i < ASL_MAX_FILE_TYPE; i++)
+    Gbl_Files[ASL_FILE_PREPROCESSOR].Handle =3D NULL; /* the .i file is sa=
me as source file */
+
+    for (i =3D ASL_FILE_INPUT; i < ASL_MAX_FILE_TYPE; i++)
     {
         FlCloseFile (i);
     }
@@ -817,6 +835,18 @@
         }
     }
=20
+    /* Delete the preprocessor output file (.i) unless -li flag is set */
+
+    if (!Gbl_PreprocessorOutputFlag && Gbl_Files[ASL_FILE_PREPROCESSOR].Fi=
lename)
+    {
+        if (remove (Gbl_Files[ASL_FILE_PREPROCESSOR].Filename))
+        {
+            printf ("%s: ",
+                Gbl_Files[ASL_FILE_PREPROCESSOR].Filename);
+            perror ("Could not delete preprocessor .i file");
+        }
+    }
+
     /*
      * Delete intermediate ("combined") source file (if -ls flag not set)
      * This file is created during normal ASL/AML compiles. It is not
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slcompiler.h
--- a/head/sys/contrib/dev/acpica/compiler/aslcompiler.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslcompiler.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -75,6 +75,7 @@
 #include <contrib/dev/acpica/compiler/asltypes.h>
 #include <contrib/dev/acpica/compiler/aslmessages.h>
 #include <contrib/dev/acpica/compiler/aslglobal.h>
+#include <contrib/dev/acpica/compiler/preprocess.h>
=20
=20
 /*************************************************************************=
******
@@ -84,7 +85,7 @@
  *************************************************************************=
*****/
=20
 /*
- * parser - generated from flex/bison, lex/yacc, etc.
+ * Main ASL parser - generated from flex/bison, lex/yacc, etc.
  */
 int
 AslCompilerparse(
@@ -303,6 +304,16 @@
     char                    *ExtraMessage);
=20
 void
+AslCommonError2 (
+    UINT8                   Level,
+    UINT8                   MessageId,
+    UINT32                  LineNumber,
+    UINT32                  Column,
+    char                    *SourceLine,
+    char                    *Filename,
+    char                    *ExtraMessage);
+
+void
 AePrintException (
     UINT32                  FileId,
     ASL_ERROR_MSG           *Enode,
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slcompiler.y
--- a/head/sys/contrib/dev/acpica/compiler/aslcompiler.y	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslcompiler.y	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -78,6 +78,11 @@
 #define YYDEBUG             1               /* Enable debug output */
 #define YYERROR_VERBOSE     1               /* Verbose error messages */
=20
+/* Define YYMALLOC/YYFREE to prevent redefinition errors  */
+
+#define YYMALLOC            malloc
+#define YYFREE              free
+
 /*
  * The windows version of bison defines this incorrectly as "32768" (Not n=
egative).
  * We use a custom (edited binary) version of bison that defines YYFLAG as=
 YYFBAD
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slerror.c
--- a/head/sys/contrib/dev/acpica/compiler/aslerror.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslerror.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -55,6 +55,18 @@
     ASL_ERROR_MSG           *Enode);
=20
=20
+/*************************************************************************=
******
+ *
+ * FUNCTION:    AeClearErrorLog
+ *
+ * PARAMETERS:  None
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Empty the error list
+ *
+ *************************************************************************=
*****/
+
 void
 AeClearErrorLog (
     void)
@@ -168,7 +180,7 @@
     UINT32                  SourceColumn;
     UINT32                  ErrorColumn;
     FILE                    *OutputFile;
-    FILE                    *SourceFile;
+    FILE                    *SourceFile =3D NULL;
     long                    FileSize;
     BOOLEAN                 PrematureEOF =3D FALSE;
=20
@@ -211,24 +223,28 @@
=20
     OutputFile =3D Gbl_Files[FileId].Handle;
=20
-    /* Use the merged header/source file if present, otherwise use input f=
ile */
=20
-    SourceFile =3D Gbl_Files[ASL_FILE_SOURCE_OUTPUT].Handle;
-    if (!SourceFile)
+    if (!Enode->SourceLine)
     {
-        SourceFile =3D Gbl_Files[ASL_FILE_INPUT].Handle;
-    }
+        /* Use the merged header/source file if present, otherwise use inp=
ut file */
=20
-    if (SourceFile)
-    {
-        /* Determine if the error occurred at source file EOF */
+        SourceFile =3D Gbl_Files[ASL_FILE_SOURCE_OUTPUT].Handle;
+        if (!SourceFile)
+        {
+            SourceFile =3D Gbl_Files[ASL_FILE_INPUT].Handle;
+        }
=20
-        fseek (SourceFile, 0, SEEK_END);
-        FileSize =3D ftell (SourceFile);
+        if (SourceFile)
+        {
+            /* Determine if the error occurred at source file EOF */
=20
-        if ((long) Enode->LogicalByteOffset >=3D FileSize)
-        {
-            PrematureEOF =3D TRUE;
+            fseek (SourceFile, 0, SEEK_END);
+            FileSize =3D ftell (SourceFile);
+
+            if ((long) Enode->LogicalByteOffset >=3D FileSize)
+            {
+                PrematureEOF =3D TRUE;
+            }
         }
     }
=20
@@ -247,46 +263,59 @@
=20
             if (Enode->LineNumber)
             {
-                fprintf (OutputFile, " %6u: ", Enode->LineNumber);
+                if (Enode->SourceLine)
+                {
+                    fprintf (OutputFile, " %6u: %s",
+                        Enode->LineNumber, Enode->SourceLine);
+                }
+                else
+                {
+                    if (Gbl_FileType =3D=3D ASL_INPUT_TYPE_ASCII_ASL)
+                        fprintf (OutputFile, " %6u: ",
+                            PrGetLineNumber (Enode->LineNumber));
+                    else
+                        fprintf (OutputFile, " %6u: ",
+                            Enode->LineNumber);
=20
-                /*
-                 * If not at EOF, get the corresponding source code line a=
nd
-                 * display it. Don't attempt this if we have a premature E=
OF
-                 * condition.
-                 */
-                if (!PrematureEOF)
-                {
                     /*
-                     * Seek to the offset in the combined source file, read
-                     * the source line, and write it to the output.
+                     * If not at EOF, get the corresponding source code li=
ne and
+                     * display it. Don't attempt this if we have a prematu=
re EOF
+                     * condition.
                      */
-                    Actual =3D fseek (SourceFile, (long) Enode->LogicalByt=
eOffset,
-                                (int) SEEK_SET);
-                    if (Actual)
+                    if (!PrematureEOF)
                     {
-                        fprintf (OutputFile,
-                            "[*** iASL: Seek error on source code temp fil=
e %s ***]",
-                            Gbl_Files[ASL_FILE_SOURCE_OUTPUT].Filename);
-                    }
-                    else
-                    {
-                        RActual =3D fread (&SourceByte, 1, 1, SourceFile);
-                        if (!RActual)
+                        /*
+                         * Seek to the offset in the combined source file,=
 read
+                         * the source line, and write it to the output.
+                         */
+                        Actual =3D fseek (SourceFile, (long) Enode->Logica=
lByteOffset,
+                                    (int) SEEK_SET);
+                        if (Actual)
                         {
                             fprintf (OutputFile,
-                                "[*** iASL: Read error on source code temp=
 file %s ***]",
+                                "[*** iASL: Seek error on source code temp=
 file %s ***]",
                                 Gbl_Files[ASL_FILE_SOURCE_OUTPUT].Filename=
);
                         }
+                        else
+                        {
+                            RActual =3D fread (&SourceByte, 1, 1, SourceFi=
le);
+                            if (!RActual)
+                            {
+                                fprintf (OutputFile,
+                                    "[*** iASL: Read error on source code =
temp file %s ***]",
+                                    Gbl_Files[ASL_FILE_SOURCE_OUTPUT].File=
name);
+                            }
=20
-                        else while (RActual && SourceByte && (SourceByte !=
=3D '\n'))
-                        {
-                            fwrite (&SourceByte, 1, 1, OutputFile);
-                            RActual =3D fread (&SourceByte, 1, 1, SourceFi=
le);
+                            else while (RActual && SourceByte && (SourceBy=
te !=3D '\n'))
+                            {
+                                fwrite (&SourceByte, 1, 1, OutputFile);
+                                RActual =3D fread (&SourceByte, 1, 1, Sour=
ceFile);
+                            }
                         }
                     }
+
+                    fprintf (OutputFile, "\n");
                 }
-
-                fprintf (OutputFile, "\n");
             }
         }
         else
@@ -295,7 +324,16 @@
=20
             if (Enode->LineNumber)
             {
-                fprintf (OutputFile, "(%u) : ", Enode->LineNumber);
+                if (Gbl_FileType =3D=3D ASL_INPUT_TYPE_ASCII_ASL)
+                {
+                    fprintf (OutputFile, "(%u) i:%6u : ",
+                        PrGetLineNumber (Enode->LineNumber), Enode->LineNu=
mber);
+                }
+                else
+                {
+                    fprintf (OutputFile, "(%u) i:%6u : ",
+                        Enode->LineNumber, Enode->LineNumber);
+                }
             }
         }
     }
@@ -421,6 +459,91 @@
=20
 /*************************************************************************=
******
  *
+ * FUNCTION:    AslCommonError2
+ *
+ * PARAMETERS:  Level               - Seriousness (Warning/error, etc.)
+ *              MessageId           - Index into global message buffer
+ *              LineNumber          - Actual file line number
+ *              Column              - Column in current line
+ *              SourceLine          - Actual source code line
+ *              Filename            - source filename
+ *              ExtraMessage        - additional error message
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Create a new error node and add it to the error log
+ *
+ *************************************************************************=
*****/
+
+void
+AslCommonError2 (
+    UINT8                   Level,
+    UINT8                   MessageId,
+    UINT32                  LineNumber,
+    UINT32                  Column,
+    char                    *SourceLine,
+    char                    *Filename,
+    char                    *ExtraMessage)
+{
+    char                    *MessageBuffer =3D NULL;
+    char                    *LineBuffer;
+    ASL_ERROR_MSG           *Enode;
+
+
+    Enode =3D UtLocalCalloc (sizeof (ASL_ERROR_MSG));
+
+    if (ExtraMessage)
+    {
+        /* Allocate a buffer for the message and a new error node */
+
+        MessageBuffer =3D UtLocalCalloc (strlen (ExtraMessage) + 1);
+
+        /* Keep a copy of the extra message */
+
+        ACPI_STRCPY (MessageBuffer, ExtraMessage);
+    }
+
+    LineBuffer =3D UtLocalCalloc (strlen (SourceLine) + 1);
+    ACPI_STRCPY (LineBuffer, SourceLine);
+
+    /* Initialize the error node */
+
+    if (Filename)
+    {
+        Enode->Filename       =3D Filename;
+        Enode->FilenameLength =3D strlen (Filename);
+        if (Enode->FilenameLength < 6)
+        {
+            Enode->FilenameLength =3D 6;
+        }
+    }
+
+    Enode->MessageId            =3D MessageId;
+    Enode->Level                =3D Level;
+    Enode->LineNumber           =3D LineNumber;
+    Enode->LogicalLineNumber    =3D LineNumber;
+    Enode->LogicalByteOffset    =3D 0;
+    Enode->Column               =3D Column;
+    Enode->Message              =3D MessageBuffer;
+    Enode->SourceLine           =3D LineBuffer;
+
+    /* Add the new node to the error node list */
+
+    AeAddToErrorLog (Enode);
+
+    if (Gbl_DebugFlag)
+    {
+        /* stderr is a file, send error to it immediately */
+
+        AePrintException (ASL_FILE_STDERR, Enode, NULL);
+    }
+
+    Gbl_ExceptionCount[Level]++;
+}
+
+
+/*************************************************************************=
******
+ *
  * FUNCTION:    AslCommonError
  *
  * PARAMETERS:  Level               - Seriousness (Warning/error, etc.)
@@ -487,6 +610,7 @@
     Enode->LogicalByteOffset    =3D LogicalByteOffset;
     Enode->Column               =3D Column;
     Enode->Message              =3D MessageBuffer;
+    Enode->SourceLine           =3D NULL;
=20
     /* Add the new node to the error node list */
=20
@@ -553,7 +677,6 @@
         break;
     }
=20
-
     if (Op)
     {
         AslCommonError (Level, MessageId, Op->Asl.LineNumber,
@@ -643,5 +766,3 @@
=20
     return 0;
 }
-
-
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slfiles.c
--- a/head/sys/contrib/dev/acpica/compiler/aslfiles.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslfiles.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -50,7 +50,7 @@
=20
 /* Local prototypes */
=20
-static FILE *
+FILE *
 FlOpenIncludeWithPrefix (
     char                    *PrefixDir,
     char                    *Filename);
@@ -363,14 +363,13 @@
     }
=20
     Error =3D fclose (Gbl_Files[FileId].Handle);
-    Gbl_Files[FileId].Handle =3D NULL;
-
     if (Error)
     {
         FlFileError (FileId, ASL_MSG_CLOSE);
         AslAbort ();
     }
=20
+    Gbl_Files[FileId].Handle =3D NULL;
     return;
 }
=20
@@ -478,7 +477,7 @@
  *
  *************************************************************************=
*****/
=20
-static FILE *
+FILE *
 FlOpenIncludeWithPrefix (
     char                    *PrefixDir,
     char                    *Filename)
@@ -740,6 +739,13 @@
         Gbl_Files[ASL_FILE_DEBUG_OUTPUT].Handle =3D
             freopen (Filename, "w+t", stderr);
=20
+        if (!Gbl_Files[ASL_FILE_DEBUG_OUTPUT].Handle)
+        {
+            AslCommonError (ASL_ERROR, ASL_MSG_DEBUG_FILENAME,
+                0, 0, 0, 0, NULL, NULL);
+            return (AE_ERROR);
+        }
+
         AslCompilerSignon (ASL_FILE_DEBUG_OUTPUT);
         AslCompilerFileHeader (ASL_FILE_DEBUG_OUTPUT);
     }
@@ -764,12 +770,26 @@
         AslCompilerFileHeader (ASL_FILE_LISTING_OUTPUT);
     }
=20
+    /* Create the preprocessor output file */
+
+    Filename =3D FlGenerateFilename (FilenamePrefix, FILE_SUFFIX_PREPROCES=
SOR);
+    if (!Filename)
+    {
+        AslCommonError (ASL_ERROR, ASL_MSG_PREPROCESSOR_FILENAME,
+            0, 0, 0, 0, NULL, NULL);
+        return (AE_ERROR);
+    }
+
+    FlOpenFile (ASL_FILE_PREPROCESSOR, Filename, "w+b");
+
+    /* All done for data table compiler */
+
     if (Gbl_FileType =3D=3D ASL_INPUT_TYPE_ASCII_DATA)
     {
         return (AE_OK);
     }
=20
-    /* Create/Open a combined source output file */
+   /* Create/Open a combined source output file */
=20
     Filename =3D FlGenerateFilename (FilenamePrefix, FILE_SUFFIX_SOURCE);
     if (!Filename)
@@ -786,6 +806,10 @@
      */
     FlOpenFile (ASL_FILE_SOURCE_OUTPUT, Filename, "w+b");
=20
+/*
+// TBD: TEMP
+//    AslCompilerin =3D Gbl_Files[ASL_FILE_SOURCE_OUTPUT].Handle;
+*/
     /* Create/Open a assembly code source output file if asked */
=20
     if (Gbl_AsmOutputFlag)
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slglobal.h
--- a/head/sys/contrib/dev/acpica/compiler/aslglobal.h	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslglobal.h	Tue Apr 17 11:51:51 =
2012 +0300
@@ -70,10 +70,11 @@
 extern FILE                         *AslCompilerin;
 extern int                          AslCompilerdebug;
 extern int                          DtParserdebug;
+extern int                          PrParserdebug;
 extern const ASL_MAPPING_ENTRY      AslKeywordMapping[];
 extern char                         *AslCompilertext;
=20
-#define ASL_LINE_BUFFER_SIZE        1024
+#define ASL_LINE_BUFFER_SIZE        4096
 #define ASL_MSG_BUFFER_SIZE         4096
 #define HEX_TABLE_LINE_SIZE         8
 #define HEX_LISTING_LINE_SIZE       8
@@ -88,22 +89,22 @@
 ASL_EXTERN UINT32                   ASL_INIT_GLOBAL (Gbl_CurrentLineOffset=
, 0);
 ASL_EXTERN char                     ASL_INIT_GLOBAL (*Gbl_LineBufPtr, Gbl_=
CurrentLineBuffer);
=20
-
 /* Exception reporting */
=20
 ASL_EXTERN ASL_ERROR_MSG            ASL_INIT_GLOBAL (*Gbl_ErrorLog,NULL);
 ASL_EXTERN ASL_ERROR_MSG            ASL_INIT_GLOBAL (*Gbl_NextError,NULL);
=20
-
 /* Option flags */
=20
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_DoCompile, TRUE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_DoSignon, TRUE);
+ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_PreprocessOnly, F=
ALSE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_DisassembleAll, F=
ALSE);
=20
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_Acpi2, FALSE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_UseDefaultAmlFile=
name, TRUE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_NsOutputFlag, FAL=
SE);
+ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_PreprocessorOutpu=
tFlag, FALSE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_DebugFlag, FALSE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_AsmOutputFlag, FA=
LSE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_C_OutputFlag, FAL=
SE);
@@ -203,7 +204,7 @@
=20
 /* Event timing */
=20
-#define ASL_NUM_EVENTS              19
+#define ASL_NUM_EVENTS              20
 ASL_EXTERN ASL_EVENT_INFO           AslGbl_Events[ASL_NUM_EVENTS];
 ASL_EXTERN UINT8                    AslGbl_NextEvent;
 ASL_EXTERN UINT8                    AslGbl_NamespaceEvent;
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slmain.c
--- a/head/sys/contrib/dev/acpica/compiler/aslmain.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslmain.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -96,7 +96,7 @@
=20
=20
 #define ASL_TOKEN_SEPARATORS    " \t\n"
-#define ASL_SUPPORTED_OPTIONS   "@:2b:c:d^e:fgh^i^I:l^mno:p:r:s:t:T:G^v:w:=
x:z"
+#define ASL_SUPPORTED_OPTIONS   "@:2b|c|d^D:e:fgh^i|I:l^mno|p:Pr:s|t|T:G^v=
|w|x:z"
=20
=20
 /*************************************************************************=
******
@@ -120,6 +120,11 @@
     ACPI_OPTION ("-@ <file>",       "Specify command file");
     ACPI_OPTION ("-I <dir>",        "Specify additional include directory"=
);
=20
+    printf ("\nPreprocessor:\n");
+    ACPI_OPTION ("-D <symbol>",     "Define symbol for preprocessor use");
+    ACPI_OPTION ("-li",             "Create preprocessed output file (*.i)=
");
+    ACPI_OPTION ("-P",              "Preprocess only and create preprocess=
or output file (*.i)");
+
     printf ("\nGeneral Output:\n");
     ACPI_OPTION ("-p <prefix>",     "Specify path/filename prefix for all =
output files");
     ACPI_OPTION ("-va",             "Disable all errors and warnings (summ=
ary only)");
@@ -127,12 +132,12 @@
     ACPI_OPTION ("-vo",             "Enable optimization comments");
     ACPI_OPTION ("-vr",             "Disable remarks");
     ACPI_OPTION ("-vs",             "Disable signon");
-    ACPI_OPTION ("-w <1|2|3>",      "Set warning reporting level");
+    ACPI_OPTION ("-w1 -w2 -w3",     "Set warning reporting level");
=20
     printf ("\nAML Output Files:\n");
-    ACPI_OPTION ("-s <a|c>",        "Create AML in assembler or C source f=
ile (*.asm or *.c)");
-    ACPI_OPTION ("-i <a|c>",        "Create assembler or C include file (*=
.inc or *.h)");
-    ACPI_OPTION ("-t <a|c|s>",      "Create AML in assembler, C, or ASL he=
x table (*.hex)");
+    ACPI_OPTION ("-sa -sc",         "Create AML in assembler or C source f=
ile (*.asm or *.c)");
+    ACPI_OPTION ("-ia -ic",         "Create assembler or C include file (*=
.inc or *.h)");
+    ACPI_OPTION ("-ta -tc -ts",     "Create AML in assembler, C, or ASL he=
x table (*.hex)");
=20
     printf ("\nAML Code Generation:\n");
     ACPI_OPTION ("-oa",             "Disable all optimizations (compatibil=
ity mode)");
@@ -199,12 +204,12 @@
     Options ();
=20
     printf ("\nCompiler/Disassembler Debug Options:\n");
-    ACPI_OPTION ("-b<p|t|b>",       "Create compiler debug/trace file (*.t=
xt)");
+    ACPI_OPTION ("-bb -bp -bt",     "Create compiler debug/trace file (*.t=
xt)");
     ACPI_OPTION ("",                "Types: Parse/Tree/Both");
     ACPI_OPTION ("-f",              "Ignore errors, force creation of AML =
output file(s)");
     ACPI_OPTION ("-n",              "Parse only, no output generation");
     ACPI_OPTION ("-ot",             "Display compile times");
-    ACPI_OPTION ("-x<level>",       "Set debug level for trace output");
+    ACPI_OPTION ("-x <level>",      "Set debug level for trace output");
     ACPI_OPTION ("-z",              "Do not insert new compiler ID for Dat=
aTables");
 }
=20
@@ -405,34 +410,34 @@
         if (IsResponseFile)
         {
             printf ("Nested command files are not supported\n");
-            return -1;
+            return (-1);
         }
=20
         if (AslDoResponseFile (AcpiGbl_Optarg))
         {
-            return -1;
+            return (-1);
         }
         break;
=20
=20
-    case '2':
-
+    case '2':   /* ACPI 2.0 compatibility mode */
         Gbl_Acpi2 =3D TRUE;
         break;
=20
=20
-    case 'b':
-
+    case 'b':   /* Debug output options */
         switch (AcpiGbl_Optarg[0])
         {
         case 'b':
             AslCompilerdebug =3D 1; /* same as yydebug */
             DtParserdebug =3D 1;
+            PrParserdebug =3D 1;
             break;
=20
         case 'p':
             AslCompilerdebug =3D 1; /* same as yydebug */
             DtParserdebug =3D 1;
+            PrParserdebug =3D 1;
             break;
=20
         case 't':
@@ -463,7 +468,7 @@
         break;
=20
=20
-    case 'd':
+    case 'd':   /* Disassembler */
         switch (AcpiGbl_Optarg[0])
         {
         case '^':
@@ -487,7 +492,12 @@
         break;
=20
=20
-    case 'e':
+    case 'D':   /* Define a symbol */
+        PrAddDefine (AcpiGbl_Optarg, NULL, TRUE);
+        break;
+
+
+    case 'e':   /* External files for disassembler */
         Status =3D AcpiDmAddToExternalFileList (AcpiGbl_Optarg);
         if (ACPI_FAILURE (Status))
         {
@@ -497,17 +507,17 @@
         break;
=20
=20
-    case 'f':
-
-        /* Ignore errors and force creation of aml file */
-
+    case 'f':   /* Ignore errors and force creation of aml file */
         Gbl_IgnoreErrors =3D TRUE;
         break;
=20
=20
-    case 'g':
+    case 'G':
+        Gbl_CompileGeneric =3D TRUE;
+        break;
=20
-        /* Get all ACPI tables */
+
+    case 'g':   /* Get all ACPI tables */
=20
         Gbl_GetAllTables =3D TRUE;
         Gbl_DoCompile =3D FALSE;
@@ -515,7 +525,6 @@
=20
=20
     case 'h':
-
         switch (AcpiGbl_Optarg[0])
         {
         case '^':
@@ -542,14 +551,12 @@
         }
=20
=20
-    case 'I': /* Add an include file search directory */
-
+    case 'I':   /* Add an include file search directory */
         FlAddIncludeDirectory (AcpiGbl_Optarg);
         break;
=20
=20
-    case 'i':
-
+    case 'i':   /* Output AML as an include file */
         switch (AcpiGbl_Optarg[0])
         {
         case 'a':
@@ -567,14 +574,13 @@
             break;
=20
         default:
-            printf ("Unknown option: -s%s\n", AcpiGbl_Optarg);
+            printf ("Unknown option: -i%s\n", AcpiGbl_Optarg);
             return (-1);
         }
         break;
=20
=20
-    case 'l':
-
+    case 'l':   /* Listing files */
         switch (AcpiGbl_Optarg[0])
         {
         case '^':
@@ -583,6 +589,12 @@
             Gbl_ListingFlag =3D TRUE;
             break;
=20
+        case 'i':
+            /* Produce preprocessor output file */
+
+            Gbl_PreprocessorOutputFlag =3D TRUE;
+            break;
+
         case 'n':
             /* Produce namespace file */
=20
@@ -602,22 +614,17 @@
         break;
=20
=20
-    case 'm':
-
+    case 'm':   /* Do not convert buffers to resource descriptors */
         AcpiGbl_NoResourceDisassembly =3D TRUE;
         break;
=20
=20
-    case 'n':
-
-        /* Parse only */
-
+    case 'n':   /* Parse only */
         Gbl_ParseOnlyFlag =3D TRUE;
         break;
=20
=20
-    case 'o':
-
+    case 'o':   /* Control compiler AML optimizations */
         switch (AcpiGbl_Optarg[0])
         {
         case 'a':
@@ -664,22 +671,24 @@
         break;
=20
=20
-    case 'p':
+    case 'P':   /* Preprocess (plus .i file) only */
+        Gbl_PreprocessOnly =3D TRUE;
+        Gbl_PreprocessorOutputFlag =3D TRUE;
+        break;
=20
-        /* Override default AML output filename */
=20
+    case 'p':   /* Override default AML output filename */
         Gbl_OutputFilenamePrefix =3D AcpiGbl_Optarg;
         Gbl_UseDefaultAmlFilename =3D FALSE;
         break;
=20
=20
-    case 'r':
+    case 'r':   /* Override revision found in table header */
         Gbl_RevisionOverride =3D (UINT8) strtoul (AcpiGbl_Optarg, NULL, 0);
         break;
=20
=20
-    case 's':
-
+    case 's':   /* Create AML in a source code file */
         switch (AcpiGbl_Optarg[0])
         {
         case 'a':
@@ -703,10 +712,7 @@
         break;
=20
=20
-    case 't':
-
-        /* Produce hex table output file */
-
+    case 't':   /* Produce hex table output file */
         switch (AcpiGbl_Optarg[0])
         {
         case 'a':
@@ -728,19 +734,13 @@
         break;
=20
=20
-    case 'G':
-        Gbl_CompileGeneric =3D TRUE;
-        break;
-
-
-    case 'T':
+    case 'T':   /* Create a ACPI table template file */
         Gbl_DoTemplates =3D TRUE;
         Gbl_TemplateSignature =3D AcpiGbl_Optarg;
         break;
=20
=20
-    case 'v':
-
+    case 'v':   /* Verbosity settings */
         switch (AcpiGbl_Optarg[0])
         {
         case 'a':
@@ -779,7 +779,6 @@
=20
=20
     case 'w': /* Set warning levels */
-
         switch (AcpiGbl_Optarg[0])
         {
         case '1':
@@ -801,20 +800,17 @@
         break;
=20
=20
-    case 'x':
-
+    case 'x':   /* Set debug print output level */
         AcpiDbgLevel =3D strtoul (AcpiGbl_Optarg, NULL, 16);
         break;
=20
=20
     case 'z':
-
         Gbl_UseOriginalCompilerId =3D TRUE;
         break;
=20
=20
     default:
-
         return (-1);
     }
=20
@@ -931,6 +927,7 @@
     /* Init and command line */
=20
     AslInitialize ();
+    PrInitializePreprocessor ();
     Index1 =3D Index2 =3D AslCommandLine (argc, argv);
=20
     /* Options that have no additional parameters or pathnames */
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slmessages.h
--- a/head/sys/contrib/dev/acpica/compiler/aslmessages.h	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslmessages.h	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -157,6 +157,7 @@
     ASL_MSG_OUTPUT_FILE_OPEN,
     ASL_MSG_OUTPUT_FILENAME,
     ASL_MSG_PACKAGE_LENGTH,
+    ASL_MSG_PREPROCESSOR_FILENAME,
     ASL_MSG_READ,
     ASL_MSG_RECURSION,
     ASL_MSG_REGION_BUFFER_ACCESS,
@@ -197,7 +198,20 @@
     ASL_MSG_VENDOR_LIST,
     ASL_MSG_WRITE,
=20
-/* These messages are used by the data table compiler only */
+    /* These messages are used by the Preprocessor only */
+
+    ASL_MSG_DIRECTIVE_SYNTAX,
+    ASL_MSG_ENDIF_MISMATCH,
+    ASL_MSG_ERROR_DIRECTIVE,
+    ASL_MSG_EXISTING_NAME,
+    ASL_MSG_INVALID_INVOCATION,
+    ASL_MSG_MACRO_SYNTAX,
+    ASL_MSG_TOO_MANY_ARGUMENTS,
+    ASL_MSG_UNKNOWN_DIRECTIVE,
+    ASL_MSG_UNKNOWN_PRAGMA,
+
+
+    /* These messages are used by the data table compiler only */
=20
     ASL_MSG_BUFFER_ELEMENT,
     ASL_MSG_DIVIDE_BY_ZERO,
@@ -317,6 +331,7 @@
 /*    ASL_MSG_OUTPUT_FILE_OPEN */           "Could not open output AML fil=
e",
 /*    ASL_MSG_OUTPUT_FILENAME */            "Could not create output filen=
ame",
 /*    ASL_MSG_PACKAGE_LENGTH */             "Effective AML package length =
is zero",
+/*    ASL_MSG_PREPROCESSOR_FILENAME */      "Could not create preprocessor=
 filename",
 /*    ASL_MSG_READ */                       "Could not read file",
 /*    ASL_MSG_RECURSION */                  "Recursive method call",
 /*    ASL_MSG_REGION_BUFFER_ACCESS */       "Host Operation Region require=
s BufferAcc access",
@@ -357,7 +372,19 @@
 /*    ASL_MSG_VENDOR_LIST */                "Too many vendor data bytes (7=
 max)",
 /*    ASL_MSG_WRITE */                      "Could not write file",
=20
-/* These messages are used by the data table compiler only */
+/* Preprocessor */
+
+/*    ASL_MSG_DIRECTIVE_SYNTAX */           "Invalid directive syntax",
+/*    ASL_MSG_ENDIF_MISMATCH */             "Mismatched #endif",
+/*    ASL_MSG_ERROR_DIRECTIVE */            "#error",
+/*    ASL_MSG_EXISTING_NAME */              "Name is already defined",
+/*    ASL_MSG_INVALID_INVOCATION */         "Invalid macro invocation",
+/*    ASL_MSG_MACRO_SYNTAX */               "Invalid macro syntax",
+/*    ASL_MSG_TOO_MANY_ARGUMENTS */         "Too many macro arguments",
+/*    ASL_MSG_UNKNOWN_DIRECTIVE */          "Unknown directive",
+/*    ASL_MSG_UNKNOWN_PRAGMA */             "Unknown pragma",
+
+/* Table compiler */
=20
 /*    ASL_MSG_BUFFER_ELEMENT */             "Invalid element in buffer ini=
tializer list",
 /*    ASL_MSG_DIVIDE_BY_ZERO */             "Expression contains divide-by=
-zero",
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slstartup.c
--- a/head/sys/contrib/dev/acpica/compiler/aslstartup.c	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslstartup.c	Tue Apr 17 11:51:51=
 2012 +0300
@@ -95,6 +95,8 @@
     Gbl_LogicalLineNumber =3D 1;
     Gbl_CurrentLineOffset =3D 0;
     Gbl_InputFieldCount =3D 0;
+    Gbl_InputByteCount =3D 0;
+    Gbl_NsLookupCount =3D 0;
     Gbl_LineBufPtr =3D Gbl_CurrentLineBuffer;
=20
     Gbl_ErrorLog =3D NULL;
@@ -102,17 +104,26 @@
     Gbl_Signature =3D NULL;
     Gbl_FileType =3D 0;
=20
+    TotalExecutableOpcodes =3D 0;
+    TotalNamedObjects =3D 0;
+    TotalKeywords =3D 0;
+    TotalParseNodes =3D 0;
+    TotalMethods =3D 0;
+    TotalAllocations =3D 0;
+    TotalAllocated =3D 0;
+    TotalFolds =3D 0;
+
     AslGbl_NextEvent =3D 0;
     for (i =3D 0; i < ASL_NUM_REPORT_LEVELS; i++)
     {
         Gbl_ExceptionCount[i] =3D 0;
     }
=20
-    Gbl_Files[ASL_FILE_AML_OUTPUT].Filename =3D NULL;
-    Gbl_Files[ASL_FILE_AML_OUTPUT].Handle =3D NULL;
-
-    Gbl_Files[ASL_FILE_SOURCE_OUTPUT].Filename =3D NULL;
-    Gbl_Files[ASL_FILE_SOURCE_OUTPUT].Handle =3D NULL;
+    for (i =3D ASL_FILE_INPUT; i <=3D ASL_MAX_FILE_TYPE; i++)
+    {
+        Gbl_Files[i].Handle =3D NULL;
+        Gbl_Files[i].Filename =3D NULL;
+    }
 }
=20
=20
@@ -282,11 +293,12 @@
     ACPI_STATUS             Status;
=20
=20
-    Gbl_Files[ASL_FILE_INPUT].Filename =3D Filename;
-
-    /* Re-initialize "some" compiler globals */
+    /* Re-initialize "some" compiler/preprocessor globals */
=20
     AslInitializeGlobals ();
+    PrInitializeGlobals ();
+
+    Gbl_Files[ASL_FILE_INPUT].Filename =3D Filename;
=20
     /*
      * AML Disassembly (Optional)
@@ -399,6 +411,7 @@
             Gbl_Signature =3D NULL;
         }
         AeClearErrorLog ();
+        PrTerminatePreprocessor ();
         return (Status);
=20
     /*
@@ -427,6 +440,7 @@
         }
=20
         AeClearErrorLog ();
+        PrTerminatePreprocessor ();
         return (AE_OK);
=20
     case ASL_INPUT_TYPE_BINARY:
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
sltypes.h
--- a/head/sys/contrib/dev/acpica/compiler/asltypes.h	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/asltypes.h	Tue Apr 17 11:51:51 2=
012 +0300
@@ -152,9 +152,10 @@
 {
     ASL_FILE_STDOUT             =3D 0,
     ASL_FILE_STDERR,
-    ASL_FILE_INPUT,
+    ASL_FILE_INPUT,             /* Don't move these first 3 file types */
     ASL_FILE_AML_OUTPUT,
     ASL_FILE_SOURCE_OUTPUT,
+    ASL_FILE_PREPROCESSOR,
     ASL_FILE_LISTING_OUTPUT,
     ASL_FILE_HEX_OUTPUT,
     ASL_FILE_NAMESPACE_OUTPUT,
@@ -167,7 +168,7 @@
 } ASL_FILE_TYPES;
=20
=20
-#define ASL_MAX_FILE_TYPE       12
+#define ASL_MAX_FILE_TYPE       13
 #define ASL_NUM_FILES           (ASL_MAX_FILE_TYPE + 1)
=20
=20
@@ -190,6 +191,7 @@
     char                        *Message;
     struct asl_error_msg        *Next;
     char                        *Filename;
+    char                        *SourceLine;
     UINT32                      FilenameLength;
     UINT8                       MessageId;
     UINT8                       Level;
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/a=
slutils.c
--- a/head/sys/contrib/dev/acpica/compiler/aslutils.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/aslutils.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -68,6 +68,7 @@
     "Table Input:  ",
     "Binary Output:",
     "Source Output:",
+    "Preprocessor: ",
     "Listing File: ",
     "Hex Dump:     ",
     "Namespace:    ",
@@ -536,6 +537,13 @@
             continue;
         }
=20
+        /* .I is a temp file unless specifically requested */
+
+        if ((i =3D=3D ASL_FILE_PREPROCESSOR) && (!Gbl_PreprocessorOutputFl=
ag))
+        {
+            continue;
+        }
+
         FlPrintFile (FileId, "%14s %s - %u bytes\n",
             AslFileTypeNames [i],
             Gbl_Files[i].Filename, FlGetFileSize (i));
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/d=
tcompile.c
--- a/head/sys/contrib/dev/acpica/compiler/dtcompile.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/dtcompile.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -101,6 +101,17 @@
         return (Status);
     }
=20
+    /* Preprocessor */
+
+    Event =3D UtBeginEvent ("Preprocess input file");
+    PrDoPreprocess ();
+    UtEndEvent (Event);
+
+    if (Gbl_PreprocessOnly)
+    {
+        return AE_OK;
+    }
+
     /*
      * Scan the input file (file is already open) and
      * build the parse tree
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/d=
tcompiler.h
--- a/head/sys/contrib/dev/acpica/compiler/dtcompiler.h	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/dtcompiler.h	Tue Apr 17 11:51:51=
 2012 +0300
@@ -155,6 +155,10 @@
=20
 /* dtio - binary and text input/output */
=20
+UINT32
+DtGetNextLine (
+    FILE                    *Handle);
+
 DT_FIELD *
 DtScanFile (
     FILE                    *Handle);
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/d=
texpress.c
--- a/head/sys/contrib/dev/acpica/compiler/dtexpress.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/dtexpress.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -142,7 +142,7 @@
         if (!RightValue)
         {
             DtError (ASL_ERROR, ASL_MSG_DIVIDE_BY_ZERO,
-                Gbl_CurrentField, Gbl_CurrentField->Value);
+                Gbl_CurrentField, NULL);
             return (0);
         }
         Result =3D LeftValue / RightValue;
@@ -152,7 +152,7 @@
         if (!RightValue)
         {
             DtError (ASL_ERROR, ASL_MSG_DIVIDE_BY_ZERO,
-                Gbl_CurrentField, Gbl_CurrentField->Value);
+                Gbl_CurrentField, NULL);
             return (0);
         }
         Result =3D LeftValue % RightValue;
@@ -191,7 +191,7 @@
         break;
=20
     case EXPOP_EQUAL:
-        Result =3D LeftValue =3D RightValue;
+        Result =3D LeftValue =3D=3D RightValue;
         break;
=20
     case EXPOP_NOT_EQUAL:
@@ -223,13 +223,12 @@
         /* Unknown operator */
=20
         DtFatal (ASL_MSG_INVALID_EXPRESSION,
-            Gbl_CurrentField, Gbl_CurrentField->Value);
+            Gbl_CurrentField, NULL);
         return (0);
     }
=20
     DbgPrint (ASL_DEBUG_OUTPUT,
-        "IntegerEval: %s (%8.8X%8.8X %s %8.8X%8.8X) =3D %8.8X%8.8X\n",
-        Gbl_CurrentField->Value,
+        "IntegerEval: (%8.8X%8.8X %s %8.8X%8.8X) =3D %8.8X%8.8X\n",
         ACPI_FORMAT_UINT64 (LeftValue),
         DtGetOpName (Operator),
         ACPI_FORMAT_UINT64 (RightValue),
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/d=
tio.c
--- a/head/sys/contrib/dev/acpica/compiler/dtio.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sys/contrib/dev/acpica/compiler/dtio.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -66,10 +66,6 @@
     UINT32                  Line,
     UINT32                  Offset);
=20
-UINT32
-DtGetNextLine (
-    FILE                    *Handle);
-
 static void
 DtWriteBinary (
     DT_SUBTABLE             *Subtable,
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/compiler/d=
tparser.y
--- a/head/sys/contrib/dev/acpica/compiler/dtparser.y	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/sys/contrib/dev/acpica/compiler/dtparser.y	Tue Apr 17 11:51:51 2=
012 +0300
@@ -63,6 +63,10 @@
 #define YYERROR_VERBOSE     1               /* Verbose error messages */
 #define YYFLAG              -32768
=20
+/* Define YYMALLOC/YYFREE to prevent redefinition errors  */
+
+#define YYMALLOC            malloc
+#define YYFREE              free
 %}
=20
 %union
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/debugger/dbcmds.c
--- a/head/sys/contrib/dev/acpica/components/debugger/dbcmds.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/debugger/dbcmds.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -174,14 +174,14 @@
     }
=20
     AcpiOsPrintf ("**** Going to sleep ****\n");
-    Status =3D AcpiEnterSleepState (SleepState);
+    Status =3D AcpiEnterSleepState (SleepState, ACPI_NO_OPTIONAL_METHODS);
     if (ACPI_FAILURE (Status))
     {
         goto ErrorExit;
     }
=20
     AcpiOsPrintf ("**** Prepare to return from sleep ****\n");
-    Status =3D AcpiLeaveSleepStatePrep (SleepState);
+    Status =3D AcpiLeaveSleepStatePrep (SleepState, ACPI_NO_OPTIONAL_METHO=
DS);
     if (ACPI_FAILURE (Status))
     {
         goto ErrorExit;
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/hardware/hwesleep.c
--- a/head/sys/contrib/dev/acpica/components/hardware/hwesleep.c	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/hardware/hwesleep.c	Tue Apr 17=
 11:51:51 2012 +0300
@@ -53,7 +53,7 @@
  *
  * FUNCTION:    AcpiHwExecuteSleepMethod
  *
- * PARAMETERS:  MethodName          - Pathname of method to execute
+ * PARAMETERS:  MethodPathname      - Pathname of method to execute
  *              IntegerArgument     - Argument to pass to the method
  *
  * RETURN:      None
@@ -65,7 +65,7 @@
=20
 void
 AcpiHwExecuteSleepMethod (
-    char                    *MethodName,
+    char                    *MethodPathname,
     UINT32                  IntegerArgument)
 {
     ACPI_OBJECT_LIST        ArgList;
@@ -83,11 +83,11 @@
     Arg.Type =3D ACPI_TYPE_INTEGER;
     Arg.Integer.Value =3D (UINT64) IntegerArgument;
=20
-    Status =3D AcpiEvaluateObject (NULL, MethodName, &ArgList, NULL);
+    Status =3D AcpiEvaluateObject (NULL, MethodPathname, &ArgList, NULL);
     if (ACPI_FAILURE (Status) && Status !=3D AE_NOT_FOUND)
     {
         ACPI_EXCEPTION ((AE_INFO, Status, "While executing method %s",
-            MethodName));
+            MethodPathname));
     }
=20
     return_VOID;
@@ -99,6 +99,7 @@
  * FUNCTION:    AcpiHwExtendedSleep
  *
  * PARAMETERS:  SleepState          - Which sleep state to enter
+ *              Flags               - ACPI_EXECUTE_GTS to run optional met=
hod
  *
  * RETURN:      Status
  *
@@ -110,7 +111,8 @@
=20
 ACPI_STATUS
 AcpiHwExtendedSleep (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_STATUS             Status;
     UINT8                   SleepTypeValue;
@@ -138,9 +140,12 @@
=20
     AcpiGbl_SystemAwakeAndRunning =3D FALSE;
=20
-    /* Execute the _GTS method (Going To Sleep) */
+    /* Optionally execute _GTS (Going To Sleep) */
=20
-    AcpiHwExecuteSleepMethod (METHOD_NAME__GTS, SleepState);
+    if (Flags & ACPI_EXECUTE_GTS)
+    {
+        AcpiHwExecuteSleepMethod (METHOD_PATHNAME__GTS, SleepState);
+    }
=20
     /* Flush caches, as per ACPI specification */
=20
@@ -186,6 +191,7 @@
  * FUNCTION:    AcpiHwExtendedWakePrep
  *
  * PARAMETERS:  SleepState          - Which sleep state we just exited
+ *              Flags               - ACPI_EXECUTE_BFS to run optional met=
hod
  *
  * RETURN:      Status
  *
@@ -196,7 +202,8 @@
=20
 ACPI_STATUS
 AcpiHwExtendedWakePrep (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_STATUS             Status;
     UINT8                   SleepTypeValue;
@@ -216,7 +223,12 @@
             &AcpiGbl_FADT.SleepControl);
     }
=20
-    AcpiHwExecuteSleepMethod (METHOD_NAME__BFS, SleepState);
+    /* Optionally execute _BFS (Back From Sleep) */
+
+    if (Flags & ACPI_EXECUTE_BFS)
+    {
+        AcpiHwExecuteSleepMethod (METHOD_PATHNAME__BFS, SleepState);
+    }
     return_ACPI_STATUS (AE_OK);
 }
=20
@@ -226,6 +238,7 @@
  * FUNCTION:    AcpiHwExtendedWake
  *
  * PARAMETERS:  SleepState          - Which sleep state we just exited
+ *              Flags               - Reserved, set to zero
  *
  * RETURN:      Status
  *
@@ -236,7 +249,8 @@
=20
 ACPI_STATUS
 AcpiHwExtendedWake (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_FUNCTION_TRACE (HwExtendedWake);
=20
@@ -247,8 +261,8 @@
=20
     /* Execute the wake methods */
=20
-    AcpiHwExecuteSleepMethod (METHOD_NAME__SST, ACPI_SST_WAKING);
-    AcpiHwExecuteSleepMethod (METHOD_NAME__WAK, SleepState);
+    AcpiHwExecuteSleepMethod (METHOD_PATHNAME__SST, ACPI_SST_WAKING);
+    AcpiHwExecuteSleepMethod (METHOD_PATHNAME__WAK, SleepState);
=20
     /*
      * Some BIOS code assumes that WAK_STS will be cleared on resume
@@ -258,6 +272,6 @@
     (void) AcpiWrite (ACPI_X_WAKE_STATUS, &AcpiGbl_FADT.SleepStatus);
     AcpiGbl_SystemAwakeAndRunning =3D TRUE;
=20
-    AcpiHwExecuteSleepMethod (METHOD_NAME__SST, ACPI_SST_WORKING);
+    AcpiHwExecuteSleepMethod (METHOD_PATHNAME__SST, ACPI_SST_WORKING);
     return_ACPI_STATUS (AE_OK);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/hardware/hwsleep.c
--- a/head/sys/contrib/dev/acpica/components/hardware/hwsleep.c	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/hardware/hwsleep.c	Tue Apr 17 =
11:51:51 2012 +0300
@@ -55,6 +55,7 @@
  * FUNCTION:    AcpiHwLegacySleep
  *
  * PARAMETERS:  SleepState          - Which sleep state to enter
+ *              Flags               - ACPI_EXECUTE_GTS to run optional met=
hod
  *
  * RETURN:      Status
  *
@@ -65,7 +66,8 @@
=20
 ACPI_STATUS
 AcpiHwLegacySleep (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_BIT_REGISTER_INFO  *SleepTypeRegInfo;
     ACPI_BIT_REGISTER_INFO  *SleepEnableRegInfo;
@@ -129,9 +131,12 @@
         return_ACPI_STATUS (Status);
     }
=20
-    /* Execute the _GTS method (Going To Sleep) */
+    /* Optionally execute _GTS (Going To Sleep) */
=20
-    AcpiHwExecuteSleepMethod (METHOD_NAME__GTS, SleepState);
+    if (Flags & ACPI_EXECUTE_GTS)
+    {
+        AcpiHwExecuteSleepMethod (METHOD_PATHNAME__GTS, SleepState);
+    }
=20
     /* Get current value of PM1A control */
=20
@@ -242,6 +247,7 @@
  * FUNCTION:    AcpiHwLegacyWakePrep
  *
  * PARAMETERS:  SleepState          - Which sleep state we just exited
+ *              Flags               - ACPI_EXECUTE_BFS to run optional met=
hod
  *
  * RETURN:      Status
  *
@@ -253,7 +259,8 @@
=20
 ACPI_STATUS
 AcpiHwLegacyWakePrep (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_STATUS             Status;
     ACPI_BIT_REGISTER_INFO  *SleepTypeRegInfo;
@@ -303,7 +310,12 @@
         }
     }
=20
-    AcpiHwExecuteSleepMethod (METHOD_NAME__BFS, SleepState);
+    /* Optionally execute _BFS (Back From Sleep) */
+
+    if (Flags & ACPI_EXECUTE_BFS)
+    {
+        AcpiHwExecuteSleepMethod (METHOD_PATHNAME__BFS, SleepState);
+    }
     return_ACPI_STATUS (Status);
 }
=20
@@ -313,6 +325,7 @@
  * FUNCTION:    AcpiHwLegacyWake
  *
  * PARAMETERS:  SleepState          - Which sleep state we just exited
+ *              Flags               - Reserved, set to zero
  *
  * RETURN:      Status
  *
@@ -323,7 +336,8 @@
=20
 ACPI_STATUS
 AcpiHwLegacyWake (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_STATUS             Status;
=20
@@ -334,7 +348,7 @@
     /* Ensure EnterSleepStatePrep -> EnterSleepState ordering */
=20
     AcpiGbl_SleepTypeA =3D ACPI_SLEEP_TYPE_INVALID;
-    AcpiHwExecuteSleepMethod (METHOD_NAME__SST, ACPI_SST_WAKING);
+    AcpiHwExecuteSleepMethod (METHOD_PATHNAME__SST, ACPI_SST_WAKING);
=20
     /*
      * GPEs must be enabled before _WAK is called as GPEs
@@ -360,7 +374,7 @@
      * Now we can execute _WAK, etc. Some machines require that the GPEs
      * are enabled before the wake methods are executed.
      */
-    AcpiHwExecuteSleepMethod (METHOD_NAME__WAK, SleepState);
+    AcpiHwExecuteSleepMethod (METHOD_PATHNAME__WAK, SleepState);
=20
     /*
      * Some BIOS code assumes that WAK_STS will be cleared on resume
@@ -391,7 +405,7 @@
         return_ACPI_STATUS (Status);
     }
=20
-    AcpiHwExecuteSleepMethod (METHOD_NAME__SST, ACPI_SST_WORKING);
+    AcpiHwExecuteSleepMethod (METHOD_PATHNAME__SST, ACPI_SST_WORKING);
     return_ACPI_STATUS (Status);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/hardware/hwxfsleep.c
--- a/head/sys/contrib/dev/acpica/components/hardware/hwxfsleep.c	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/hardware/hwxfsleep.c	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -52,6 +52,7 @@
 static ACPI_STATUS
 AcpiHwSleepDispatch (
     UINT8                   SleepState,
+    UINT8                   Flags,
     UINT32                  FunctionId);
=20
 /*
@@ -252,6 +253,7 @@
 static ACPI_STATUS
 AcpiHwSleepDispatch (
     UINT8                   SleepState,
+    UINT8                   Flags,
     UINT32                  FunctionId)
 {
     ACPI_STATUS             Status;
@@ -267,13 +269,13 @@
     if (AcpiGbl_ReducedHardware ||
         AcpiGbl_FADT.SleepControl.Address)
     {
-        Status =3D SleepFunctions->ExtendedFunction (SleepState);
+        Status =3D SleepFunctions->ExtendedFunction (SleepState, Flags);
     }
     else
     {
         /* Legacy sleep */
=20
-        Status =3D SleepFunctions->LegacyFunction (SleepState);
+        Status =3D SleepFunctions->LegacyFunction (SleepState, Flags);
     }
=20
     return (Status);
@@ -283,7 +285,7 @@
      * For the case where reduced-hardware-only code is being generated,
      * we know that only the extended sleep registers are available
      */
-    Status =3D SleepFunctions->ExtendedFunction (SleepState);
+    Status =3D SleepFunctions->ExtendedFunction (SleepState, Flags);
     return (Status);
=20
 #endif /* !ACPI_REDUCED_HARDWARE */
@@ -318,8 +320,6 @@
     ACPI_FUNCTION_TRACE (AcpiEnterSleepStatePrep);
=20
=20
-    /* _PSW methods could be run here to enable wake-on keyboard, LAN, etc=
. */
-
     Status =3D AcpiGetSleepTypeData (SleepState,
                     &AcpiGbl_SleepTypeA, &AcpiGbl_SleepTypeB);
     if (ACPI_FAILURE (Status))
@@ -334,7 +334,7 @@
     Arg.Type =3D ACPI_TYPE_INTEGER;
     Arg.Integer.Value =3D SleepState;
=20
-    Status =3D AcpiEvaluateObject (NULL, METHOD_NAME__PTS, &ArgList, NULL);
+    Status =3D AcpiEvaluateObject (NULL, METHOD_PATHNAME__PTS, &ArgList, N=
ULL);
     if (ACPI_FAILURE (Status) && Status !=3D AE_NOT_FOUND)
     {
         return_ACPI_STATUS (Status);
@@ -367,7 +367,7 @@
      * Set the system indicators to show the desired sleep state.
      * _SST is an optional method (return no error if not found)
      */
-    AcpiHwExecuteSleepMethod (METHOD_NAME__SST, SstValue);
+    AcpiHwExecuteSleepMethod (METHOD_PATHNAME__SST, SstValue);
     return_ACPI_STATUS (AE_OK);
 }
=20
@@ -379,6 +379,7 @@
  * FUNCTION:    AcpiEnterSleepState
  *
  * PARAMETERS:  SleepState          - Which sleep state to enter
+ *              Flags               - ACPI_EXECUTE_GTS to run optional met=
hod
  *
  * RETURN:      Status
  *
@@ -389,7 +390,8 @@
=20
 ACPI_STATUS
 AcpiEnterSleepState (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_STATUS             Status;
=20
@@ -405,7 +407,7 @@
         return_ACPI_STATUS (AE_AML_OPERAND_VALUE);
     }
=20
-    Status =3D AcpiHwSleepDispatch (SleepState, ACPI_SLEEP_FUNCTION_ID);
+    Status =3D AcpiHwSleepDispatch (SleepState, Flags, ACPI_SLEEP_FUNCTION=
_ID);
     return_ACPI_STATUS (Status);
 }
=20
@@ -417,6 +419,7 @@
  * FUNCTION:    AcpiLeaveSleepStatePrep
  *
  * PARAMETERS:  SleepState          - Which sleep state we are exiting
+ *              Flags               - ACPI_EXECUTE_BFS to run optional met=
hod
  *
  * RETURN:      Status
  *
@@ -429,7 +432,8 @@
=20
 ACPI_STATUS
 AcpiLeaveSleepStatePrep (
-    UINT8                   SleepState)
+    UINT8                   SleepState,
+    UINT8                   Flags)
 {
     ACPI_STATUS             Status;
=20
@@ -437,7 +441,7 @@
     ACPI_FUNCTION_TRACE (AcpiLeaveSleepStatePrep);
=20
=20
-    Status =3D AcpiHwSleepDispatch (SleepState, ACPI_WAKE_PREP_FUNCTION_ID=
);
+    Status =3D AcpiHwSleepDispatch (SleepState, Flags, ACPI_WAKE_PREP_FUNC=
TION_ID);
     return_ACPI_STATUS (Status);
 }
=20
@@ -467,7 +471,7 @@
     ACPI_FUNCTION_TRACE (AcpiLeaveSleepState);
=20
=20
-    Status =3D AcpiHwSleepDispatch (SleepState, ACPI_WAKE_FUNCTION_ID);
+    Status =3D AcpiHwSleepDispatch (SleepState, 0, ACPI_WAKE_FUNCTION_ID);
     return_ACPI_STATUS (Status);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/namespace/nsdump.c
--- a/head/sys/contrib/dev/acpica/components/namespace/nsdump.c	Tue Apr 17 =
11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/namespace/nsdump.c	Tue Apr 17 =
11:51:51 2012 +0300
@@ -270,7 +270,21 @@
=20
         if (!ObjDesc)
         {
-            /* No attached object, we are done */
+            /* No attached object. Some types should always have an object=
 */
+
+            switch (Type)
+            {
+            case ACPI_TYPE_INTEGER:
+            case ACPI_TYPE_PACKAGE:
+            case ACPI_TYPE_BUFFER:
+            case ACPI_TYPE_STRING:
+            case ACPI_TYPE_METHOD:
+                AcpiOsPrintf ("<No attached object>");
+                break;
+
+            default:
+                break;
+            }
=20
             AcpiOsPrintf ("\n");
             return (AE_OK);
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/namespace/nsdumpdv.c
--- a/head/sys/contrib/dev/acpica/components/namespace/nsdumpdv.c	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/namespace/nsdumpdv.c	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -141,7 +141,7 @@
         return;
     }
=20
-    Status =3D AcpiGetHandle (NULL, ACPI_NS_SYSTEM_BUS, &SysBusHandle);
+    Status =3D AcpiGetHandle (NULL, METHOD_NAME__SB_, &SysBusHandle);
     if (ACPI_FAILURE (Status))
     {
         return;
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/namespace/nspredef.c
--- a/head/sys/contrib/dev/acpica/components/namespace/nspredef.c	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/namespace/nspredef.c	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -681,7 +681,7 @@
         {
             /* Create the new outer package and populate it */
=20
-            Status =3D AcpiNsRepairPackageList (Data, ReturnObjectPtr);
+            Status =3D AcpiNsWrapWithPackage (Data, *Elements, ReturnObjec=
tPtr);
             if (ACPI_FAILURE (Status))
             {
                 return (Status);
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/namespace/nsrepair.c
--- a/head/sys/contrib/dev/acpica/components/namespace/nsrepair.c	Tue Apr 1=
7 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/namespace/nsrepair.c	Tue Apr 1=
7 11:51:51 2012 +0300
@@ -74,11 +74,10 @@
  * Buffer  -> String
  * Buffer  -> Package of Integers
  * Package -> Package of one Package
+ * An incorrect standalone object is wrapped with required outer package
  *
  * Additional possible repairs:
- *
  * Required package elements that are NULL replaced by Integer/String/Buff=
er
- * Incorrect standalone package wrapped with required outer package
  *
  *************************************************************************=
*****/
=20
@@ -100,11 +99,6 @@
     ACPI_OPERAND_OBJECT     *OriginalObject,
     ACPI_OPERAND_OBJECT     **ReturnObject);
=20
-static ACPI_STATUS
-AcpiNsConvertToPackage (
-    ACPI_OPERAND_OBJECT     *OriginalObject,
-    ACPI_OPERAND_OBJECT     **ReturnObject);
-
=20
 /*************************************************************************=
******
  *
@@ -172,10 +166,24 @@
     }
     if (ExpectedBtypes & ACPI_RTYPE_PACKAGE)
     {
-        Status =3D AcpiNsConvertToPackage (ReturnObject, &NewObject);
+        /*
+         * A package is expected. We will wrap the existing object with a
+         * new package object. It is often the case that if a variable-len=
gth
+         * package is required, but there is only a single object needed, =
the
+         * BIOS will return that object instead of wrapping it with a Pack=
age
+         * object. Note: after the wrapping, the package will be validated
+         * for correct contents (expected object type or types).
+         */
+        Status =3D AcpiNsWrapWithPackage (Data, ReturnObject, &NewObject);
         if (ACPI_SUCCESS (Status))
         {
-            goto ObjectRepaired;
+            /*
+             * The original object just had its reference count
+             * incremented for being inserted into the new package.
+             */
+            *ReturnObjectPtr =3D NewObject;       /* New Package object */
+            Data->Flags |=3D ACPI_OBJECT_REPAIRED;
+            return (AE_OK);
         }
     }
=20
@@ -188,24 +196,30 @@
=20
     /* Object was successfully repaired */
=20
-    /*
-     * If the original object is a package element, we need to:
-     * 1. Set the reference count of the new object to match the
-     *    reference count of the old object.
-     * 2. Decrement the reference count of the original object.
-     */
     if (PackageIndex !=3D ACPI_NOT_PACKAGE_ELEMENT)
     {
-        NewObject->Common.ReferenceCount =3D
-            ReturnObject->Common.ReferenceCount;
+        /*
+         * The original object is a package element. We need to
+         * decrement the reference count of the original object,
+         * for removing it from the package.
+         *
+         * However, if the original object was just wrapped with a
+         * package object as part of the repair, we don't need to
+         * change the reference count.
+         */
+        if (!(Data->Flags & ACPI_OBJECT_WRAPPED))
+        {
+            NewObject->Common.ReferenceCount =3D
+                ReturnObject->Common.ReferenceCount;
=20
-        if (ReturnObject->Common.ReferenceCount > 1)
-        {
-            ReturnObject->Common.ReferenceCount--;
+            if (ReturnObject->Common.ReferenceCount > 1)
+            {
+                ReturnObject->Common.ReferenceCount--;
+            }
         }
=20
         ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR,
-            "%s: Converted %s to expected %s at index %u\n",
+            "%s: Converted %s to expected %s at Package index %u\n",
             Data->Pathname, AcpiUtGetObjectTypeName (ReturnObject),
             AcpiUtGetObjectTypeName (NewObject), PackageIndex));
     }
@@ -498,71 +512,6 @@
=20
 /*************************************************************************=
******
  *
- * FUNCTION:    AcpiNsConvertToPackage
- *
- * PARAMETERS:  OriginalObject      - Object to be converted
- *              ReturnObject        - Where the new converted object is re=
turned
- *
- * RETURN:      Status. AE_OK if conversion was successful.
- *
- * DESCRIPTION: Attempt to convert a Buffer object to a Package. Each byte=
 of
- *              the buffer is converted to a single integer package elemen=
t.
- *
- *************************************************************************=
*****/
-
-static ACPI_STATUS
-AcpiNsConvertToPackage (
-    ACPI_OPERAND_OBJECT     *OriginalObject,
-    ACPI_OPERAND_OBJECT     **ReturnObject)
-{
-    ACPI_OPERAND_OBJECT     *NewObject;
-    ACPI_OPERAND_OBJECT     **Elements;
-    UINT32                  Length;
-    UINT8                   *Buffer;
-
-
-    switch (OriginalObject->Common.Type)
-    {
-    case ACPI_TYPE_BUFFER:
-
-        /* Buffer-to-Package conversion */
-
-        Length =3D OriginalObject->Buffer.Length;
-        NewObject =3D AcpiUtCreatePackageObject (Length);
-        if (!NewObject)
-        {
-            return (AE_NO_MEMORY);
-        }
-
-        /* Convert each buffer byte to an integer package element */
-
-        Elements =3D NewObject->Package.Elements;
-        Buffer =3D OriginalObject->Buffer.Pointer;
-
-        while (Length--)
-        {
-            *Elements =3D AcpiUtCreateIntegerObject ((UINT64) *Buffer);
-            if (!*Elements)
-            {
-                AcpiUtRemoveReference (NewObject);
-                return (AE_NO_MEMORY);
-            }
-            Elements++;
-            Buffer++;
-        }
-        break;
-
-    default:
-        return (AE_AML_OPERAND_TYPE);
-    }
-
-    *ReturnObject =3D NewObject;
-    return (AE_OK);
-}
-
-
-/*************************************************************************=
******
- *
  * FUNCTION:    AcpiNsRepairNullElement
  *
  * PARAMETERS:  Data                - Pointer to validation data structure
@@ -745,42 +694,43 @@
=20
 /*************************************************************************=
******
  *
- * FUNCTION:    AcpiNsRepairPackageList
+ * FUNCTION:    AcpiNsWrapWithPackage
  *
  * PARAMETERS:  Data                - Pointer to validation data structure
- *              ObjDescPtr          - Pointer to the object to repair. The=
 new
- *                                    package object is returned here,
- *                                    overwriting the old object.
+ *              OriginalObject      - Pointer to the object to repair.
+ *              ObjDescPtr          - The new package object is returned h=
ere
  *
  * RETURN:      Status, new object in *ObjDescPtr
  *
- * DESCRIPTION: Repair a common problem with objects that are defined to r=
eturn
- *              a variable-length Package of Packages. If the variable-len=
gth
- *              is one, some BIOS code mistakenly simply declares a single
- *              Package instead of a Package with one sub-Package. This
- *              function attempts to repair this error by wrapping a Packa=
ge
- *              object around the original Package, creating the correct
- *              Package with one sub-Package.
+ * DESCRIPTION: Repair a common problem with objects that are defined to
+ *              return a variable-length Package of sub-objects. If there =
is
+ *              only one sub-object, some BIOS code mistakenly simply decl=
ares
+ *              the single object instead of a Package with one sub-object.
+ *              This function attempts to repair this error by wrapping a
+ *              Package object around the original object, creating the
+ *              correct and expected Package with one sub-object.
  *
  *              Names that can be repaired in this manner include:
- *              _ALR, _CSD, _HPX, _MLS, _PRT, _PSS, _TRT, TSS
+ *              _ALR, _CSD, _HPX, _MLS, _PLD, _PRT, _PSS, _TRT, _TSS,
+ *              _BCL, _DOD, _FIX, _Sx
  *
  *************************************************************************=
*****/
=20
 ACPI_STATUS
-AcpiNsRepairPackageList (
+AcpiNsWrapWithPackage (
     ACPI_PREDEFINED_DATA    *Data,
+    ACPI_OPERAND_OBJECT     *OriginalObject,
     ACPI_OPERAND_OBJECT     **ObjDescPtr)
 {
     ACPI_OPERAND_OBJECT     *PkgObjDesc;
=20
=20
-    ACPI_FUNCTION_NAME (NsRepairPackageList);
+    ACPI_FUNCTION_NAME (NsWrapWithPackage);
=20
=20
     /*
      * Create the new outer package and populate it. The new package will
-     * have a single element, the lone subpackage.
+     * have a single element, the lone sub-object.
      */
     PkgObjDesc =3D AcpiUtCreatePackageObject (1);
     if (!PkgObjDesc)
@@ -788,15 +738,15 @@
         return (AE_NO_MEMORY);
     }
=20
-    PkgObjDesc->Package.Elements[0] =3D *ObjDescPtr;
+    PkgObjDesc->Package.Elements[0] =3D OriginalObject;
+
+    ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR,
+        "%s: Wrapped %s with expected Package object\n",
+        Data->Pathname, AcpiUtGetObjectTypeName (OriginalObject)));
=20
     /* Return the new object in the object pointer */
=20
     *ObjDescPtr =3D PkgObjDesc;
-    Data->Flags |=3D ACPI_OBJECT_REPAIRED;
-
-    ACPI_DEBUG_PRINT ((ACPI_DB_REPAIR,
-        "%s: Repaired incorrectly formed Package\n", Data->Pathname));
-
+    Data->Flags |=3D ACPI_OBJECT_REPAIRED | ACPI_OBJECT_WRAPPED;
     return (AE_OK);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/namespace/nsutils.c
--- a/head/sys/contrib/dev/acpica/components/namespace/nsutils.c	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/namespace/nsutils.c	Tue Apr 17=
 11:51:51 2012 +0300
@@ -405,7 +405,7 @@
         if (!AcpiNsValidPathSeparator (*ExternalName) &&
             (*ExternalName !=3D 0))
         {
-            return_ACPI_STATUS (AE_BAD_PARAMETER);
+            return_ACPI_STATUS (AE_BAD_PATHNAME);
         }
=20
         /* Move on the next segment */
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/parser/psargs.c
--- a/head/sys/contrib/dev/acpica/components/parser/psargs.c	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/parser/psargs.c	Tue Apr 17 11:=
51:51 2012 +0300
@@ -672,6 +672,7 @@
                 Arg =3D AcpiPsAllocOp (AML_INT_BYTELIST_OP);
                 if (!Arg)
                 {
+                    AcpiPsFreeOp (Field);
                     return_PTR (NULL);
                 }
=20
@@ -717,6 +718,7 @@
             Arg =3D AcpiPsAllocOp (AML_INT_NAMEPATH_OP);
             if (!Arg)
             {
+                AcpiPsFreeOp (Field);
                 return_PTR (NULL);
             }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/tables/tbfadt.c
--- a/head/sys/contrib/dev/acpica/components/tables/tbfadt.c	Tue Apr 17 11:=
36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/tables/tbfadt.c	Tue Apr 17 11:=
51:51 2012 +0300
@@ -400,10 +400,6 @@
     UINT32                  i;
=20
=20
-    /* Update the local FADT table header length */
-
-    AcpiGbl_FADT.Header.Length =3D sizeof (ACPI_TABLE_FADT);
-
     /*
      * Expand the 32-bit FACS and DSDT addresses to 64-bit as necessary.
      * Later code will always use the X 64-bit field.
@@ -437,6 +433,13 @@
     }
=20
     /*
+     * Now we can update the local FADT length to the length of the
+     * current FADT version as defined by the ACPI specification.
+     * Thus, we will have a common FADT internally.
+     */
+    AcpiGbl_FADT.Header.Length =3D sizeof (ACPI_TABLE_FADT);
+
+    /*
      * Expand the ACPI 1.0 32-bit addresses to the ACPI 2.0 64-bit "X"
      * generic address structures as necessary. Later code will always use
      * the 64-bit address structures.
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/tables/tbinstal.c
--- a/head/sys/contrib/dev/acpica/components/tables/tbinstal.c	Tue Apr 17 1=
1:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/tables/tbinstal.c	Tue Apr 17 1=
1:51:51 2012 +0300
@@ -510,8 +510,10 @@
         ACPI_FREE (TableDesc->Pointer);
         break;
=20
+    /* Not mapped or allocated, there is nothing we can do */
+
     default:
-        break;
+        return;
     }
=20
     TableDesc->Pointer =3D NULL;
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/components=
/tables/tbutils.c
--- a/head/sys/contrib/dev/acpica/components/tables/tbutils.c	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/sys/contrib/dev/acpica/components/tables/tbutils.c	Tue Apr 17 11=
:51:51 2012 +0300
@@ -507,8 +507,9 @@
      *
      * NOTE: If the table is overridden, then FinalTable will contain a
      * mapped pointer to the full new table. If the table is not overridde=
n,
-     * then the table will be fully mapped elsewhere (in verify table).
-     * In any case, we must unmap the header that was mapped above.
+     * or if there has been a physical override, then the table will be
+     * fully mapped later (in verify table). In any case, we must
+     * unmap the header that was mapped above.
      */
     FinalTable =3D AcpiTbTableOverride (Table, TableDesc);
     if (!FinalTable)
@@ -525,6 +526,20 @@
         AcpiUtSetIntegerWidth (FinalTable->Revision);
     }
=20
+    /*
+     * If we have a physical override during this early loading of the ACPI
+     * tables, unmap the table for now. It will be mapped again later when
+     * it is actually used. This supports very early loading of ACPI table=
s,
+     * before virtual memory is fully initialized and running within the
+     * host OS. Note: A logical override has the ACPI_TABLE_ORIGIN_OVERRIDE
+     * flag set and will not be deleted below.
+     */
+    if (FinalTable !=3D Table)
+    {
+        AcpiTbDeleteTable (TableDesc);
+    }
+
+
 UnmapAndExit:
=20
     /* Always unmap the table header that we mapped above */
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/include/ac=
hware.h
--- a/head/sys/contrib/dev/acpica/include/achware.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/sys/contrib/dev/acpica/include/achware.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -114,15 +114,18 @@
  */
 ACPI_STATUS
 AcpiHwLegacySleep (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
 ACPI_STATUS
 AcpiHwLegacyWakePrep (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
 ACPI_STATUS
 AcpiHwLegacyWake (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
=20
 /*
@@ -135,15 +138,18 @@
=20
 ACPI_STATUS
 AcpiHwExtendedSleep (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
 ACPI_STATUS
 AcpiHwExtendedWakePrep (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
 ACPI_STATUS
 AcpiHwExtendedWake (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/include/ac=
local.h
--- a/head/sys/contrib/dev/acpica/include/aclocal.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/sys/contrib/dev/acpica/include/aclocal.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -424,6 +424,7 @@
 /* Defines for Flags field above */
=20
 #define ACPI_OBJECT_REPAIRED    1
+#define ACPI_OBJECT_WRAPPED     2
=20
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/include/ac=
names.h
--- a/head/sys/contrib/dev/acpica/include/acnames.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/sys/contrib/dev/acpica/include/acnames.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -46,6 +46,7 @@
=20
 /* Method names - these methods can appear anywhere in the namespace */
=20
+#define METHOD_NAME__SB_        "_SB_"
 #define METHOD_NAME__HID        "_HID"
 #define METHOD_NAME__CID        "_CID"
 #define METHOD_NAME__UID        "_UID"
@@ -64,11 +65,11 @@
=20
 /* Method names - these methods must appear at the namespace root */
=20
-#define METHOD_NAME__BFS        "\\_BFS"
-#define METHOD_NAME__GTS        "\\_GTS"
-#define METHOD_NAME__PTS        "\\_PTS"
-#define METHOD_NAME__SST        "\\_SI._SST"
-#define METHOD_NAME__WAK        "\\_WAK"
+#define METHOD_PATHNAME__BFS    "\\_BFS"
+#define METHOD_PATHNAME__GTS    "\\_GTS"
+#define METHOD_PATHNAME__PTS    "\\_PTS"
+#define METHOD_PATHNAME__SST    "\\_SI._SST"
+#define METHOD_PATHNAME__WAK    "\\_WAK"
=20
 /* Definitions of the predefined namespace names  */
=20
@@ -79,7 +80,6 @@
 #define ACPI_PREFIX_LOWER       (UINT32) 0x69706361     /* "acpi" */
=20
 #define ACPI_NS_ROOT_PATH       "\\"
-#define ACPI_NS_SYSTEM_BUS      "_SB_"
=20
 #endif  /* __ACNAMES_H__  */
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/include/ac=
namesp.h
--- a/head/sys/contrib/dev/acpica/include/acnamesp.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/sys/contrib/dev/acpica/include/acnamesp.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -368,8 +368,9 @@
     ACPI_OPERAND_OBJECT     **ReturnObjectPtr);
=20
 ACPI_STATUS
-AcpiNsRepairPackageList (
+AcpiNsWrapWithPackage (
     ACPI_PREDEFINED_DATA    *Data,
+    ACPI_OPERAND_OBJECT     *OriginalObject,
     ACPI_OPERAND_OBJECT     **ObjDescPtr);
=20
 ACPI_STATUS
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/include/ac=
output.h
--- a/head/sys/contrib/dev/acpica/include/acoutput.h	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/sys/contrib/dev/acpica/include/acoutput.h	Tue Apr 17 11:51:51 20=
12 +0300
@@ -72,6 +72,7 @@
 #define ACPI_EXAMPLE                0x00004000
 #define ACPI_DRIVER                 0x00008000
 #define DT_COMPILER                 0x00010000
+#define ASL_PREPROCESSOR            0x00020000
=20
 #define ACPI_ALL_COMPONENTS         0x0001FFFF
 #define ACPI_COMPONENT_DEFAULT      (ACPI_ALL_COMPONENTS)
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/include/ac=
pixf.h
--- a/head/sys/contrib/dev/acpica/include/acpixf.h	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/sys/contrib/dev/acpica/include/acpixf.h	Tue Apr 17 11:51:51 2012=
 +0300
@@ -48,7 +48,7 @@
=20
 /* Current ACPICA subsystem version in YYYYMMDD format */
=20
-#define ACPI_CA_VERSION                 0x20120215
+#define ACPI_CA_VERSION                 0x20120320
=20
 #include <contrib/dev/acpica/include/acconfig.h>
 #include <contrib/dev/acpica/include/actypes.h>
@@ -674,7 +674,8 @@
=20
 ACPI_STATUS
 AcpiEnterSleepState (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
 ACPI_HW_DEPENDENT_RETURN_STATUS (
 ACPI_STATUS
@@ -683,7 +684,8 @@
=20
 ACPI_STATUS
 AcpiLeaveSleepStatePrep (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
 ACPI_STATUS
 AcpiLeaveSleepState (
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/acpica/include/ac=
types.h
--- a/head/sys/contrib/dev/acpica/include/actypes.h	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/sys/contrib/dev/acpica/include/actypes.h	Tue Apr 17 11:51:51 201=
2 +0300
@@ -520,6 +520,13 @@
 #define ACPI_SLEEP_TYPE_INVALID         0xFF
=20
 /*
+ * Sleep/Wake flags
+ */
+#define ACPI_NO_OPTIONAL_METHODS        0x00 /* Do not execute any optiona=
l methods */
+#define ACPI_EXECUTE_GTS                0x01 /* For enter sleep interface =
*/
+#define ACPI_EXECUTE_BFS                0x02 /* For leave sleep prep inter=
face */
+
+/*
  * Standard notify values
  */
 #define ACPI_NOTIFY_BUS_CHECK           (UINT8) 0x00
@@ -797,7 +804,8 @@
 /* Sleep function dispatch */
=20
 typedef ACPI_STATUS (*ACPI_SLEEP_FUNCTION) (
-    UINT8                   SleepState);
+    UINT8                   SleepState,
+    UINT8                   Flags);
=20
 typedef struct acpi_sleep_functions
 {
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/ral/LICENSE
--- a/head/sys/contrib/dev/ral/LICENSE	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/ral/LICENSE	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-$FreeBSD$
+$FreeBSD: head/sys/contrib/dev/ral/LICENSE 178354 2008-04-20 20:35:46Z sam=
 $
=20
 Copyright (c) 2005-2008, Ralink Technology Corp.
 	Paul Lin <paul_lin at ralinktech.com.tw>
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/ral/rt2561.fw.uu
--- a/head/sys/contrib/dev/ral/rt2561.fw.uu	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/ral/rt2561.fw.uu	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/contrib/dev/ral/LICENSE 178354 2008-04-20 20:35:46Z s=
am $
 #=20
 # Copyright (c) 2005-2008, Ralink Technology Corp.
 # 	Paul Lin <paul_lin at ralinktech.com.tw>
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/ral/rt2561s.fw.uu
--- a/head/sys/contrib/dev/ral/rt2561s.fw.uu	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/ral/rt2561s.fw.uu	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/contrib/dev/ral/LICENSE 178354 2008-04-20 20:35:46Z s=
am $
 #=20
 # Copyright (c) 2005-2008, Ralink Technology Corp.
 # 	Paul Lin <paul_lin at ralinktech.com.tw>
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/ral/rt2661.fw.uu
--- a/head/sys/contrib/dev/ral/rt2661.fw.uu	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/ral/rt2661.fw.uu	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/contrib/dev/ral/LICENSE 178354 2008-04-20 20:35:46Z s=
am $
 #=20
 # Copyright (c) 2005-2008, Ralink Technology Corp.
 # 	Paul Lin <paul_lin at ralinktech.com.tw>
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/ral/rt2860.fw.uu
--- a/head/sys/contrib/dev/ral/rt2860.fw.uu	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/ral/rt2860.fw.uu	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/contrib/dev/ral/rt2860.fw.uu 232946 2012-03-13 21:25:=
25Z bschmidt $
+# $FreeBSD: head/sys/contrib/dev/ral/LICENSE 178354 2008-04-20 20:35:46Z s=
am $
 #=20
 # Copyright (c) 2005-2008, Ralink Technology Corp.
 # 	Paul Lin <paul_lin at ralinktech.com.tw>
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/dev/run/rt2870.fw.uu
--- a/head/sys/contrib/dev/run/rt2870.fw.uu	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/dev/run/rt2870.fw.uu	Tue Apr 17 11:51:51 2012 +0300
@@ -39,70 +39,77 @@
 # DAMAGE.
 #
 # This file contains two 4KB firmware, first half is RT2870 and last half
-# is RT3071. On each 4KB firmware, 3rd last byte is major version number a=
nd
-# 2nd last byte is minor version number.
+# is RT3071. On each 4KB firmware, the last 2 bytes are CRC, 3rd last byte
+# is minor version number and 4th last byte is major version number.
 # This file comes with
-#  RT2870 v. 0.17
-#  RT3071 v. 0.17
+#  RT2870 v. 0.236
+#  RT3071 v. 0.236
 begin 644 rt2870.fw.uu
-M____`A`H`A`R`A!X`A,J`A,K`A-*`A-/$A-+(@(7N0(8\`(42`(3 at S`%!B`-
-M`Q(9R"*0`8S@,.,;Y4PPX`1_0(`"?P"0$"_O\)`!C'0(\.20`:?PD`&,X##@
-M')`!@."T`A6CX+0!$)`!A."T at 0F0`8QT`?`2#<@BD`04X"#G`P(3*9!P$N#U
-M5I`$!.`2"IT0V3$0O381`E`1.5$10E(10E,10E01 at U41TE82,'`26W$2B7(2
-MX',3`8```!,ID'`1X/4\Y)!P$_"0!!1T@/#E5O1P`P(3*0(3(B`"`S`#'7T"
-MKU82"Y&0!!1T@/#DD'`3\.56]'`#`A,I`A,BA59!T@(BD'`0X%1__[\*#9!P
-M$>"T"`9U3@%U3X20<!#@5'__OP(2D'`1X&0(8`3 at M"`&=3D4X#=3D4\@Y/4G(I!P
-M$>`D_Y)'(I`$!.`EX"1=3D]5>0<!#@_W1')5?XQN_&D'`1X/]T2"57^,;OQN3]
-MKU82"Y&0!!1T@/#DD'`3\.56]'`#`A,I`A,BY4=3DD!V`=3DY4=3DD"&`7Y4=3DD"6`1
-MY4=3DD"F`+Y4=3DD"V`%Y4>T#`B0<!'@5`_U.N5'M`D(Y3JT`P/D]4;E1[0*".4Z
-MM`$#Y/5&Y/VO5A(+D=3D($(I!P$>#T_Y!P$.!?_Y!P$>!5)T^0<!CPD'`1X)!P
-M&?#D_:]6$@N1,!4$TA2`)I!P&.#U)Y`"*>#_D'`9X/[O7I`"*?`P1P2O)X`$
-MY2?T_Y`"*._PY5;T<`,"$RD"$R*0<!#@_I!P$>#][?CF]5?]KU82"Y&0!!1T
-M@/#DD'`3\.56]'`#`A,I`A,BD'`0X/Z0<!'@_>WU at HZ#X/57_:]6$@N1D`04
-M=3D(#PY)!P$_#E5O1P`P(3*0(3(I`0`.#U5Y`0`N#U6*/@]5GE6+1P'N59M#`9
-MD`4(X$0!\/V0!07 at 5/OP1`3P[53^D`4(\.3U3O5/=3D3K_=3D3S_K5>O5A(+D9`$
-M%'2`\.20<!/PY5;T8$N`0I!P$.`D_Y*3Y/VO5A(+D9`$%'2`\.20<!/PY5;T
-M8"J`(9!P$.`D_Y)*T at 6M5Z]6$@N1D`04=3D(#PY)!P$_#E5O1@!Y!P)>!$`?`B
-M(N53<!HP8`FR33!-!`5&P at 3E3T5.8`CE3Q5/<`(53B(BPD+3(C`4,)!P&>!5
-M)_^0<!C at 3_4GD`(IX/^0<!G at _N]>D`(I\#!'!*\G@`3E)_3_D`(H[_#"%"+"
-M2\),Y402"IT3I0`4,P04+P at 4#Q`3N2`3V6`3ZJ```!0UA4A#A4I"A4Q>Y4=3DD
-M!F`#`A0U@!OE2,14#_5#Y4K$5`_U0N5,Q%0/]5[E1V0&<&%30P^`7(5)0X5+
-M0H5-7N5'9`9P38`;Y4G$5`_U0^5+Q%0/]4+E3<14#_5>Y4=3DD!G`PY4-4#T00
-M]4.`)N5'9`1@!>5'M`4&0UX$=3D4()Y4>T!A#E0U0/1##U0X`&TDN``M),Y/4E
-MY4+$5/#_Y4-4#T_U7])@(M(5Y4<D]6`+),M@!R1`<`;"%2(2%X02%&K"%<*O
-MP at 32KR+"KY`$%.!4#F`$TAB`".5.14\D_Y(8TJ^0!!3 at HN22&70>\.5?5`_U
-M+>4E<!,P&`7E7R#E"S`9&>5?5##_OS`1Y25P!74E#(`"%272;-)M@`_E7S#F
-M!L)LTFV`!-)LPFWE1V0#<"$P2P;";-)M@!CE)7`#,$P1PDSE)7`%=3D24'@`(5
-M)=3D)LTFWE1[0)%.5$(.,+Y3ID`F`%Y3JT`P3";-)MY4>T"A/E.K0!!L)LTFV`
-M".4Z<`32;,)M(&D'Y5X at X`*R:"!K!^5>(.$"LFH@;0?E7B#B`K)L=3D2Y`(&D$
-MHFB`)C!H!N5&HN*`'>5>(.($?P&``G\`Y494\/Z^\`1^`8`"?@#N;R3_DG.2
-M<B!K!*)J@"8P:@;E1J+B@!WE7B#@!'\!@`)_`.5&5/#^OO`$?@&``GX`[F\D
-M_Y)UDG0@;02B;(`FY4=3DD"G`B,&P&Y4:BXX`7Y3JT`0;E1J+C@#3E1B#D`S#E
-M`].``<.`)C!L!N5&HN*`'>5>(.$$?P&``G\`Y494\/Z^\`1^`8`"?@#N;R3_
-MDG&2<)`0`."0$"SPD!`#X,.4,$`4HG&2=3DZ)PDG;E+A,35#_U+L)WTG:0$"_E
-M+O#E1V0&<#F0`BG at 5/[PY4/$5`\48`PD_F`,)`-P$\(X@`_2.(`+Y48PX@/3
-M@`'#DC at P1P6O)P(7?N4G]/\"%W[E1V0'8`_E1V0(8`GE1V0)8`,"%OV0`BG@
-M5/SPY3H48"(48"448"TD_&!))/E@%"0.<%#E1A,35#]U\`.$Y?`D_X`ZTCG"
-M.(`^Y48PX@/3@!W#@!KE1C#B#50XPY0P4`9^`'\!@`1^`'\`[D\D_Y(XPCF`
-M$^5&,.(#TX`!PY(YPCB`!,(XPCDP1P2O)X`$Y2?T_P(7?N5'9`Q@!N5'9`MP
-M>I`"*>!4_?#E.A1@(!1@(11@*R3\8$4D^6`2)`YP2N5&$Q-4/W7P`X3E\(`I
-MTCF`.N5&,.(#TX`!PY(Y@"WE1C#B#50XPY0P4`9^`'\!@`1^`'\`[D\D_Y(Y
-M@`_E1C#B`].``<.2.8`"PCDP1P2O)X`$Y2?T_Y`"*._P(N5'M`L0D`(IX%3K
-M\.4G5.M%1?4G(N20`BGP,$<$KT6`!.5%]/^0`BCO\"*/4-)9(H]4TE at BY/5B
-MPJ_E411 at 2!1 at 9B0"8`,"&-326755`9`"HN!4?_"CX"#G(Y`$-."T`ARCX+0"
-M%Z/@M`(2?R`2%Z^0$`3 at 5//P=3D5$!`AC4Y5!P!G5B`P(8U)`2`.!4`W`2?R`2
-M%Z^0`J+ at 5+_P=3D5$"`AC4Y5!P`P(8SY`"H^`PY@,"&,N0!#?@9")@`P(8RY`!
-MBG1^\)`!EO"0$@1T"O#E6+1R%>59M#40Y)`%`/"C=3D`CPHW0!\'0#\'\!$@TJ
-MD!,HX)!P&O"0$RG at D'`;\)`3*.!4\/"CX%3P\.59M#44Y3ST8`:CX%3S@!20
-M$RK at 5/OP@!3E//20$RI@".!4\D4\\(`$X%3Z\)`$`>!4_?!U8@%U50+D]5&`
-M">50<`5U8@/U4>5B8!7"`>3U4<)9K6*O0!(9E.5BM`,"T@/2KR+"KS`!$N20
-M`9;P]5'"6<(!?0*O0!(9E.52%&`,!&`#`AF1=3D5(!=3D54#D`0!X$0.\)!P&N"0
-M$RCPD'`;X)`3*?#E//1@".4\1`&C\(`&D!,J=3D`7PD!($=3D`/PY5BT<A;E6;0U
-M$9`%`'3B\*-T"/"C=3D`'P=3D`/P?P$2#2J0`J+ at 1,#PD!`$X$0,\.3U4O55,`()
-MP@)]`:]!$AF4,`,"P@/DD`&6\-*O(N_T8"WD_G04+O6"Y#1P]8/@M/\9=3D!0N
-M]8+D-'#U@^_P=3D!PN]8+D-'#U@^WP(@Z^!-4B(B*0<"K@,.%-PJ^0<"C at D!`<
-M\)!P*>"0$!WPD'`JX)`0'O"0$!S@]6*0$![@(.'SD!`<X)!P*/"0$!W at D'`I
-M\)`0'N"0<"KP,$H'D'`DX$0!\,(%TJ\B(B(`````````````````````````
+M____`A`H`A`R`A!]`A.[`A.\`A/;`A/@$A/<(@(8V@(:&@(5/`(4=3DS`%!B`-
+M`Q(:_R*0`8S@,., at Y5@PX!#E3##@!']`@`)_`)`0+^_PD`&,=3D`CPY)`!I_"0
+M`8S@,.`<D`&`X+0"%:/@M`$0D`&$X+2!"9`!C'0!\!(-R"*0!!3@(.<#`A.Z
+MD'`2X/56D`0$X!(*G1#A,1#%-A$*4!%!41%*4A%*4Q%*5!&+51':5A(X<!)C
+M<1*1<A,\<Q-=3D@!.`D```$[J0<!'@]3SDD'`3\)`$%'2`\.56]'`#`A.Z`A.S
+M(`(#,`,=3D?0*O5A(+D9`$%'2`\.20<!/PY5;T<`,"$[H"$[.%5D'2`B*0<!#@
+M5'__OPH-D'`1X+0(!G5.`75/A)!P$.!4?_^_`A*0<!'@9`A@!."T(`9U3 at -U
+M3R#D]2<BD'`1X"3_DD<BD`0$X"7@)%WU5Y!P$.#_=3D$<E5_C&[\:0<!'@_W1(
+M)5?XQN_&Y/VO5A(+D9`$%'2`\.20<!/PY5;T<`,"$[H"$[/E1V0'8!WE1V0(
+M8!?E1V0)8!'E1V0*8`OE1V0+8`7E1[0,")!P$>!4#_4ZY4>T"0CE.K0#`^3U
+M1N5'M`H(Y3JT`0/D]4;D_:]6$@N1T at 0BD'`1X/3_D'`0X%__D'`1X%4G3Y!P
+M&/"0<!'@D'`9\.3]KU82"Y$P%032%(`FD'`8X/4GD`(IX/^0<!G at _N]>D`(I
+M\#!'!*\G@`3E)_3_D`(H[_#E5O1P`P(3N@(3LY!P$.#^D'`1X/WM^.;U5_VO
+M5A(+D9`$%'2`\.20<!/PY5;T<`,"$[H"$[.0<!#@_I!P$>#][?6"CH/@]5?]
+MKU82"Y&0!!1T@/#DD'`3\.56]'`#`A.Z`A.SD!``X/57Y/58]5F0$`/@M"@%
+M=3D5@!@#R0$`/@M#`%=3D5@"@#"0$`/@M#,%=3D5@$@"20$`/@M#4,D!`"X+1R!758
+M"(`1D!`#X+0U"I`0`N"TDP-U6!#E6##A&9`%".!$`?#]D`4%X%3[\$0$\.U4
+M_I`%"/#D]4[U3W4Z_W4\_ZU7KU82"Y'DD'`R\,(6]5SU6O5;D'`P\*/PD`04
+M=3D(#PY)!P$_#E5O1P`P(3NH!WD'`0X"3_DI/D_:]6$@N1D`04=3D(#PY)!P$_#E
+M5O1 at 7X!6D'`0X"3_DDK2!:U7KU82"Y&0!!1T@/#DD'`3\.56]&`\@#.0<!#@
+M)/^2%I!P$>#U7*U7KU82"Y&0!!1T@/"0<##E6O"CY5OPY/5:]5N0<!/PY5;T
+M8`>0<"7 at 1`'P(B+E4W`:,&`)LDTP300%1L($Y4]%3F`(Y4\53W`"%4XB(L)"
+MTR(P%#"0<!G at 52?_D'`8X$_U)Y`"*>#_D'`9X/[O7I`"*?`P1P2O)X`$Y2?T
+M_Y`"*._PPA0P%F#"KY`0!.#U5Y`"*.!4!?57Y5QD`7`AY5>0$`0PX`;@5/OP
+M@`3 at 1`3PY5<PXC$%6^5;<"L%6H`GY5<PX!OE7)`0!'`&X%3[\(`$X$0$\`5;
+MY5MP"P5:@`>0$`3 at 1`3PTJ\BPDO"3.5$$@J=3D%)D`%2<$%2,(%0,0%*T@%,U@
+M%-Z@```5*85(0X5*0H5,7N5'9`9@`P(5*8`;Y4C$5`_U0^5*Q%0/]4+E3,14
+M#_5>Y4=3DD!G!A4T,/@%R%24.%2T*%35[E1V0&<$V`&^5)Q%0/]4/E2\14#_5"
+MY4W$5`_U7N5'9`9P,.5#5`]$$/5#@";E1V0$8`7E1[0%!D->!'5"">5'M`80
+MY4-4#T0P]4.`!M)+@`+23.3U)>5"Q%3P_^5#5`]/]5_28"+2%>5')/5@"R3+
+M8`<D0'`&PA4B$ABE$A5>PA7"K\($TJ\BPJ^0!!3 at 5`Y@!-(8@`CE3D5/)/^2
+M&-*OD`04X*+DDAET'O#E7U0/]2WE)7`3,!@%Y5\@Y0LP&1GE7U0P_[\P$>4E
+M<`5U)0R``A4ETFS2;8`/Y5\PY@;";-)M@`32;,)MY4=3DD`W`A,$L&PFS2;8`8
+MY25P`S!,$<),Y25P!74E!X`"%272;-)MY4>T"13E1"#C"^4Z9`)@!>4ZM`,$
+MPFS2;>5'M`H3Y3JT`0;";-)M@`CE.G`$TFS";2!I!^5>(.`"LF@@:P?E7B#A
+M`K)J(&T'Y5X at X@*R;'4N0"!I!*)H@"8P:`;E1J+B@!WE7B#@!'\!@`)_`.5&
+M5/#^OO`$?@&``GX`[F\D_Y)SDG(@:P2B:H`F,&H&Y4:BXH`=3DY5X at X01_`8`"
+M?P#E1E3P_K[P!'X!@`)^`.YO)/^2=3D9)T(&T$HFR`)N5'9`IP(C!L!N5&HN.`
+M%^4ZM`$&Y4:BXX`TY48 at Y`,PY0/3@`'#@"8P;`;E1J+B@!WE7B#B!'\!@`)_
+M`.5&5/#^OO`$?@&``GX`[F\D_Y)QDG"0$`#@D!`L\)`0`^##E#!`%*)QDG>B
+M<))VY2X3$U0_]2["=3D])VD!`OY2[PY4=3DD!G!'D`(HX#!'`_^``O3_CR>0`BG@
+M5/[PY4/$5`\48`PD_F`,)`-P$\(X@`_2.(`+Y48PX@/3@`'#DC at P1P6O)P(8
+MG^4G]/\"&)_E1V0'8`_E1V0(8`GE1V0)8`,"&`V0`BC@,$<#_X`"]/^/)Y`"
+M*>!4_/#E.A1@(A1@)11 at +23\8$DD^6`4)`YP4.5&$Q-4/W7P`X3E\"3_@#K2
+M.<(X@#[E1C#B`].`'<.`&N5&,.(-5#C#E#!0!GX`?P&`!'X`?P#N3R3_DCC"
+M.8`3Y48PX@/3@`'#DCG".(`$PCC".3!'!*\G@`3E)_3_`AB?Y4=3DD#&`)Y4=3DD
+M"V`#`ABDD`(HX#!'`_^``O3_CR>0`BG at 5/WPY3H48"`48"$48"LD_&!%)/E@
+M$B0.<$KE1A,35#]U\`.$Y?"`*=3D(Y@#KE1C#B`].``<.2.8`MY48PX at U4.,.4
+M,%`&?@!_`8`$?@!_`.Y/)/^2.8`/Y48PX@/3@`'#DCF``L(Y,$<$KR>`!.4G
+M]/^0`BCO\"+E1[0+$)`"*>!4Z_#E)U3K147U)R+DD`(I\#!'!*]%@`3E1?3_
+MD`(H[_`BCU#262*/5-)8(N3U8L*OY5$48$@48&8D`F`#`AG^TEEU50&0`J+@
+M5'_PH^`@YR.0!#3 at M`(<H^"T`A>CX+0"$G\@$AC0D!`$X%3S\'51`0(9_N50
+M<`9U8@,"&?Z0$@#@5`-P$G\@$AC0D`*BX%2_\'51`@(9_N50<`,"&?F0`J/@
+M,.8#`AGUD`0WX&0B8`,"&?60`8IT?O"0`9;PD!($=3D`KPY5 at PXQ7DD`4`\*-T
+M"/"C=3D`'P=3D`/P?P$2#2J0$RC at D'`:\)`3*>"0<!OPD!,KX)!P(O"0$RC at 5/#P
+MH^!4\/"0$RO at 5,SPY5 at PXQ/E//20$RI@!>!4\X`1X%3[\(`4Y3STD!,J8`C@
+M5/)%//"`!.!4^O"0!`'@5/WP=3D6(!=3D54"Y/51@`GE4'`%=3D6(#]5'E8F`5P@'D
+M]5'"6:UBKT`2&LOE8K0#`M(#TJ\BPJ\P`1+DD`&6\/51PEG"`7T"KT`2&LOE
+M4A1@#`1@`P(:R'52`755`Y`$`>!$#O#E6%088!Z0<!K at D!,H\)!P&^"0$RGP
+MHW0%\)!P(N"0$ROP@!&0$RC at 1`_PH^!$#_"CX$0%\)`2!'0#\.58,.,6D`4`
+M=3D.+PHW0(\*-T`?!T`_!_`1(-*I`"HN!$P/"0$`3 at 1`SPY/52]54P`@G"`GT!
+MKT$2&LLP`P+"`^20`9;PTJ\B[_1 at +>3^=3D!0N]8+D-'#U@^"T_QET%"[U at N0T
+M</6#[_!T'"[U at N0T</6#[?`B#KX$U2(B(I!P*N`PX4W"KY!P*."0$!SPD'`I
+MX)`0'?"0<"K at D!`>\)`0'.#U8I`0'N`@X?.0$!S at D'`H\)`0'>"0<"GPD!`>
+MX)!P*O`P2@>0<"3 at 1`'PP at 72KR(B(@``````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
@@ -128,6 +135,72 @@
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
+M`````````````````````````````````````````````````````````.SQ
+M2O___P(0*`(0,@(0?0(3NP(3O`(3VP(3X!(3W"("&-H"&AH"%3P"%'<P!08@
+M#0,2&O\BD`&,X##C(.58,.`0Y4PPX`1_0(`"?P"0$"_O\)`!C'0(\.20`:?P
+MD`&,X##@')`!@."T`A6CX+0!$)`!A."T at 0F0`8QT`?`2#=3DTBD`04X"#G`P(3
+MNI!P$N#U5I`$!.`2"K80X3$0Q381"E`105$12E(12E,12E01BU41VE82.'`2
+M8W$2D7(3/',378`3@)```!.ZD'`1X/4\Y)!P$_"0!!1T@/#E5O1P`P(3N@(3
+MLR`"`S`#'7T"KU82"ZJ0!!1T@/#DD'`3\.56]'`#`A.Z`A.SA59!T@(BD'`0
+MX%1__[\*#9!P$>"T"`9U3@%U3X20<!#@5'__OP(2D'`1X&0(8`3 at M"`&=3D4X#
+M=3D4\@Y/4G(I!P$>`D_Y)'(I`$!.`EX"1=3D]5>0<!#@_W1')5?XQN_&D'`1X/]T
+M2"57^,;OQN3]KU82"ZJ0!!1T@/#DD'`3\.56]'`#`A.Z`A.SY4=3DD!V`=3DY4=3DD
+M"&`7Y4=3DD"6`1Y4=3DD"F`+Y4=3DD"V`%Y4>T#`B0<!'@5`_U.N5'M`D(Y3JT`P/D
+M]4;E1[0*".4ZM`$#Y/5&Y/VO5A(+JM($(I!P$>#T_Y!P$.!?_Y!P$>!5)T^0
+M<!CPD'`1X)!P&?#D_:]6$@NJ,!4$TA2`)I!P&.#U)Y`"*>#_D'`9X/[O7I`"
+M*?`P1P2O)X`$Y2?T_Y`"*._PY5;T<`,"$[H"$[.0<!#@_I!P$>#][?CF]5?]
+MKU82"ZJ0!!1T@/#DD'`3\.56]'`#`A.Z`A.SD'`0X/Z0<!'@_>WU at HZ#X/57
+M_:]6$@NJD`04=3D(#PY)!P$_#E5O1P`P(3N@(3LY`0`.#U5^3U6/59D!`#X+0H
+M!758`8`\D!`#X+0P!758`H`PD!`#X+0S!758!(`DD!`#X+0U#)`0`N"T<@5U
+M6`B`$9`0`^"T-0J0$`+ at M),#=3D5 at 0Y5@PX1F0!0C at 1`'P_9`%!>!4^_!$!/#M
+M5/Z0!0CPY/5.]4]U.O]U//^M5Z]6$@NJY)!P,O#"%O5<]5KU6Y!P,/"C\)`$
+M%'2`\.20<!/PY5;T<`,"$[J`=3DY!P$.`D_Y*3Y/VO5A(+JI`$%'2`\.20<!/P
+MY5;T8%^`5I!P$.`D_Y)*T at 6M5Z]6$@NJD`04=3D(#PY)!P$_#E5O1@/(`SD'`0
+MX"3_DA:0<!'@]5RM5Z]6$@NJD`04=3D(#PD'`PY5KPH^5;\.3U6O5;D'`3\.56
+M]&`'D'`EX$0!\"(BY5-P&C!@";)-,$T$!4;"!.5/14Y@".5/%4]P`A5.(B+"
+M0M,B,!0PD'`9X%4G_Y!P&.!/]2>0`BG at _Y!P&>#^[UZ0`BGP,$<$KR>`!.4G
+M]/^0`BCO\,(4,!9 at PJ^0$`3@]5>0`BC at 5`7U5^5<9`%P(>57D!`$,.`&X%3[
+M\(`$X$0$\.57,.(Q!5OE6W`K!5J`)^57,.`;Y5R0$`1P!N!4^_"`!.!$!/`%
+M6^5;<`L%6H`'D!`$X$0$\-*O(L)+PDSE1!(*MA29`!4G!!4C"!4#$!2M(!3-
+M8!3>H```%2F%2$.%2D*%3%[E1V0&8`,"%2F`&^5(Q%0/]4/E2L14#_5"Y4S$
+M5`_U7N5'9`9P85-##X!<A4E#A4M"A4U>Y4=3DD!G!-@!OE2<14#_5#Y4O$5`_U
+M0N5-Q%0/]5[E1V0&<##E0U0/1!#U0X`FY4=3DD!&`%Y4>T!09#7 at 1U0@GE1[0&
+M$.5#5`]$,/5#@`;22X`"TDSD]27E0L14\/_E0U0/3_5?TF`BTA7E1R3U8`LD
+MRV`')$!P!L(5(A(8I1(57L(5PJ_"!-*O(L*OD`04X%0.8`32&(`(Y4Y%3R3_
+MDAC2KY`$%."BY)(9=3D![PY5]4#_4MY25P$S`8!>5?(.4+,!D9Y5]4,/^_,!'E
+M)7`%=3D24,@`(5)=3D)LTFV`#^5?,.8&PFS2;8`$TFS";>5'9`-P(3!+!L)LTFV`
+M&.4E<`,P3!'"3.4E<`5U)0>``A4ETFS2;>5'M`D4Y40 at XPOE.F0"8`7E.K0#
+M!,)LTFWE1[0*$^4ZM`$&PFS2;8`(Y3IP!-)LPFT@:0?E7B#@`K)H(&L'Y5X@
+MX0*R:B!M!^5>(.("LFQU+D`@:02B:(`F,&@&Y4:BXH`=3DY5X at X`1_`8`"?P#E
+M1E3P_K[P!'X!@`)^`.YO)/^2<Y)R(&L$HFJ`)C!J!N5&HN*`'>5>(.$$?P&`
+M`G\`Y494\/Z^\`1^`8`"?@#N;R3_DG62=3D"!M!*)L@";E1V0*<"(P;`;E1J+C
+M@!?E.K0!!N5&HN.`-.5&(.0#,.4#TX`!PX`F,&P&Y4:BXH`=3DY5X at X@1_`8`"
+M?P#E1E3P_K[P!'X!@`)^`.YO)/^2<9)PD!``X)`0+/"0$`/@PY0P0!2B<9)W
+MHG"2=3DN4N$Q-4/_4NPG?2=3DI`0+^4N\.5'9`9P1Y`"*.`P1P/_@`+T_X\GD`(I
+MX%3^\.5#Q%0/%&`,)/Y@#"0#<!/".(`/TCB`"^5&,.(#TX`!PY(X,$<%KR<"
+M&)_E)_3_`AB?Y4=3DD!V`/Y4=3DD"&`)Y4=3DD"6`#`A at -D`(HX#!'`_^``O3_CR>0
+M`BG at 5/SPY3H48"(48"448"TD_&!))/E@%"0.<%#E1A,35#]U\`.$Y?`D_X`Z
+MTCG".(`^Y48PX@/3@!W#@!KE1C#B#50XPY0P4`9^`'\!@`1^`'\`[D\D_Y(X
+MPCF`$^5&,.(#TX`!PY(YPCB`!,(XPCDP1P2O)X`$Y2?T_P(8G^5'9`Q@">5'
+M9`M@`P(8I)`"*.`P1P/_@`+T_X\GD`(IX%3]\.4Z%&`@%&`A%&`K)/Q at 123Y
+M8!(D#G!*Y483$U0_=3D?`#A.7P@"G2.8`ZY48PX@/3@`'#DCF`+>5&,.(-5#C#
+ME#!0!GX`?P&`!'X`?P#N3R3_DCF`#^5&,.(#TX`!PY(Y@`+".3!'!*\G@`3E
+M)_3_D`(H[_`BY4>T"Q"0`BG at 5.OPY2=3D4ZT5%]2<BY)`"*?`P1P2O18`$Y47T
+M_Y`"*._P(H]0TEDBCU326"+D]6+"K^51%&!(%&!F)`)@`P(9_M)9=3D54!D`*B
+MX%1_\*/@(.<CD`0TX+0"'*/@M`(7H^"T`A)_(!(8T)`0!.!4\_!U40$"&?[E
+M4'`&=3D6(#`AG^D!(`X%0#<!)_(!(8T)`"HN!4O_!U40("&?[E4'`#`AGYD`*C
+MX##F`P(9]9`$-^!D(F`#`AGUD`&*=3D'[PD`&6\)`2!'0*\.58,.,5Y)`%`/"C
+M=3D`CPHW0!\'0#\'\!$@U(D!,HX)!P&O"0$RG at D'`;\)`3*^"0<"+PD!,HX%3P
+M\*/@5/#PD!,KX%3,\.58,.,3Y3STD!,J8`7 at 5/.`$>!4^_"`%.4\])`3*F`(
+MX%3R13SP@`3 at 5/KPD`0!X%3]\'5B`755`N3U48`)Y5!P!75B`_51Y6)@%<(!
+MY/51PEFM8J]`$AK+Y6*T`P+2`]*O(L*O,`$2Y)`!EO#U4<)9P@%]`J]`$AK+
+MY5(48`P$8`,"&LAU4@%U50.0!`'@1`[PY5A4&&`>D'`:X)`3*/"0<!O at D!,I
+M\*-T!?"0<"+ at D!,K\(`1D!,HX$0/\*/@1`_PH^!$!?"0$@1T`_#E6##C%I`%
+M`'3B\*-T"/"C=3D`'P=3D`/P?P$2#4B0`J+ at 1,#PD!`$X$0,\.3U4O55,`()P@)]
+M`:]!$AK+,`,"P@/DD`&6\-*O(N_T8"WD_G04+O6"Y#1P]8/@M/\9=3D!0N]8+D
+M-'#U@^_P=3D!PN]8+D-'#U@^WP(@Z^!-4B(B*0<"K@,.%-PJ^0<"C at D!`<\)!P
+M*>"0$!WPD'`JX)`0'O"0$!S@]6*0$![@(.'SD!`<X)!P*/"0$!W at D'`I\)`0
+M'N"0<"KP,$H'D'`DX$0!\,(%TJ\B(B(`````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
@@ -135,65 +208,6 @@
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
-M`````````````````````````````````````````````````````````!'"
-M>O___P(0*`(0,@(0>`(3*@(3*P(32@(33Q(32R("%[D"&/`"%$@"$X,P!08@
-M#0,2&<@BD`&,X##C&^5,,.`$?T"``G\`D!`O[_"0`8QT"/#DD`&G\)`!C.`P
-MX!R0`8#@M`(5H^"T`1"0`83 at M($)D`&,=3D`'P$@W=3D(I`$%.`@YP,"$RF0<!+@
-M]5:0!`3@$@JV$-DQ$+TV$0)0$3E1$4)2$4)3$4)4$8-5$=3D)6$C!P$EMQ$HER
-M$N!S$P&````3*9!P$>#U/.20<!/PD`04=3D(#PY5;T<`,"$RD"$R(@`@,P`QU]
-M`J]6$@NJD`04=3D(#PY)!P$_#E5O1P`P(3*0(3(H560=3D("(I!P$.!4?_^_"@V0
-M<!'@M`@&=3D4X!=3D4^$D'`0X%1__[\"$I!P$>!D"&`$X+0@!G5.`W5/(.3U)R*0
-M<!'@)/^21R*0!`3@)>`D7?57D'`0X/]T1R57^,;OQI!P$>#_=3D$@E5_C&[\;D
-M_:]6$@NJD`04=3D(#PY)!P$_#E5O1P`P(3*0(3(N5'9`=3D@'>5'9`A@%^5'9`E@
-M$>5'9`I@"^5'9`M@!>5'M`P(D'`1X%0/]3KE1[0)".4ZM`,#Y/5&Y4>T"@CE
-M.K0!`^3U1N3]KU82"ZK2!"*0<!'@]/^0<!#@7_^0<!'@52=3D/D'`8\)!P$>"0
-M<!GPY/VO5A(+JC`5!-(4@":0<!C@]2>0`BG at _Y!P&>#^[UZ0`BGP,$<$KR>`
-M!.4G]/^0`BCO\.56]'`#`A,I`A,BD'`0X/Z0<!'@_>WXYO57_:]6$@NJD`04
-M=3D(#PY)!P$_#E5O1P`P(3*0(3(I!P$.#^D'`1X/WM]8*.@^#U5_VO5A(+JI`$
-M%'2`\.20<!/PY5;T<`,"$RD"$R*0$`#@]5>0$`+@]5BCX/59Y5BT<![E6;0P
-M&9`%".!$`?#]D`4%X%3[\$0$\.U4_I`%"/#D]4[U3W4Z_W4\_ZU7KU82"ZJ0
-M!!1T@/#DD'`3\.56]&!+@$*0<!#@)/^2D^3]KU82"ZJ0!!1T@/#DD'`3\.56
-M]&`J@"&0<!#@)/^22M(%K5>O5A(+JI`$%'2`\.20<!/PY5;T8`>0<"7 at 1`'P
-M(B+E4W`:,&`)LDTP300%1L($Y4]%3F`(Y4\53W`"%4XB(L)"TR(P%#"0<!G@
-M52?_D'`8X$_U)Y`"*>#_D'`9X/[O7I`"*?`P1P2O)X`$Y2?T_Y`"*._PPA0B
-MPDO"3.5$$@JV$Z4`%#,$%"\(%`\0$[D@$]E@$^J@```4-85(0X5*0H5,7N5'
-M9`9@`P(4-8`;Y4C$5`_U0^5*Q%0/]4+E3,14#_5>Y4=3DD!G!A4T,/@%R%24.%
-M2T*%35[E1V0&<$V`&^5)Q%0/]4/E2\14#_5"Y4W$5`_U7N5'9`9P,.5#5`]$
-M$/5#@";E1V0$8`7E1[0%!D->!'5"">5'M`80Y4-4#T0P]4.`!M)+@`+23.3U
-M)>5"Q%3P_^5#5`]/]5_28"+2%>5')/5@"R3+8`<D0'`&PA4B$A>$$A1JPA7"
-MK\($TJ\BPJ^0!!3 at 5`Y@!-(8@`CE3D5/)/^2&-*OD`04X*+DDAET'O#E7U0/
-M]2WE)7`3,!@%Y5\@Y0LP&1GE7U0P_[\P$>4E<`5U)0R``A4ETFS2;8`/Y5\P
-MY@;";-)M@`32;,)MY4=3DD`W`A,$L&PFS2;8`8Y25P`S!,$<),Y25P!74E!X`"
-M%272;-)MY4>T"13E1"#C"^4Z9`)@!>4ZM`,$PFS2;>5'M`H3Y3JT`0;";-)M
-M@`CE.G`$TFS";2!I!^5>(.`"LF@@:P?E7B#A`K)J(&T'Y5X at X@*R;'4N0"!I
-M!*)H@"8P:`;E1J+B@!WE7B#B!'\!@`)_`.5&5/#^OO`$?@&``GX`[F\D_Y)S
-MDG(@:P2B:H`F,&H&Y4:BXH`=3DY5X at X`1_`8`"?P#E1E3P_K[P!'X!@`)^`.YO
-M)/^2=3D9)T(&T$HFR`)N5'9`IP(C!L!N5&HN.`%^4ZM`$&Y4:BXX`TY48 at Y`,P
-MY0/3@`'#@"8P;`;E1J+B@!WE7B#A!'\!@`)_`.5&5/#^OO`$?@&``GX`[F\D
-M_Y)QDG"0$`#@D!`L\)`0`^##E#!`%*)QDG>B<))VY2X3$U0_]2["=3D])VD!`O
-MY2[PY4=3DD!G`YD`(IX%3^\.5#Q%0/%&`,)/Y@#"0#<!/".(`/TCB`"^5&,.(#
-MTX`!PY(X,$<%KR<"%W[E)_3_`A=3D^Y4=3DD!V`/Y4=3DD"&`)Y4=3DD"6`#`A;]D`(I
-MX%3\\.4Z%&`B%&`E%&`M)/Q at 223Y8!0D#G!0Y483$U0_=3D?`#A.7P)/^`.M(Y
-MPCB`/N5&,.(#TX`=3DPX`:Y48PX at U4.,.4,%`&?@!_`8`$?@!_`.Y/)/^2.,(Y
-M@!/E1C#B`].``<.2.<(X@`3".,(Y,$<$KR>`!.4G]/\"%W[E1V0,8`;E1V0+
-M<'J0`BG at 5/WPY3H48"`48"$48"LD_&!%)/E@$B0.<$KE1A,35#]U\`.$Y?"`
-M*=3D(Y@#KE1C#B`].``<.2.8`MY48PX at U4.,.4,%`&?@!_`8`$?@!_`.Y/)/^2
-M.8`/Y48PX@/3@`'#DCF``L(Y,$<$KR>`!.4G]/^0`BCO\"+E1[0+$)`"*>!4
-MZ_#E)U3K147U)R+DD`(I\#!'!*]%@`3E1?3_D`(H[_`BCU#262*/5-)8(N3U
-M8L*OY5$48$@48&8D`F`#`AC4TEEU50&0`J+ at 5'_PH^`@YR.0!#3 at M`(<H^"T
-M`A>CX+0"$G\@$A>OD!`$X%3S\'51`0(8U.50<`9U8@,"&-20$@#@5`-P$G\@
-M$A>OD`*BX%2_\'51`@(8U.50<`,"&,^0`J/@,.8#`AC+D`0WX&0B8`,"&,N0
-M`8IT?O"0`9;PD!($=3D`KPY5BT<A7E6;0U$.20!0#PHW0(\*-T`?!T`_!_`1(-
-M2)`3*."0<!KPD!,IX)!P&_"0$RC at 5/#PH^!4\/#E6;0U%.4\]&`&H^!4\X`4
-MD!,JX%3[\(`4Y3STD!,J8`C at 5/)%//"`!.!4^O"0!`'@5/WP=3D6(!=3D54"Y/51
-M@`GE4'`%=3D6(#]5'E8F`5P@'D]5'"6:UBKT`2&93E8K0#`M(#TJ\BPJ\P`1+D
-MD`&6\/51PEG"`7T"KT`2&93E4A1@#`1@`P(9D752`755`Y`$`>!$#O"0<!K@
-MD!,H\)!P&^"0$RGPY3ST8`CE/$0!H_"`!I`3*G0%\)`2!'0#\.58M'(6Y5FT
-M-1&0!0!TXO"C=3D`CPHW0!\'0#\'\!$@U(D`*BX$3`\)`0!.!$#/#D]5+U53`"
-M"<("?0&O01(9E#`#`L(#Y)`!EO#2KR+O]&`MY/YT%"[U at N0T</6#X+3_&704
-M+O6"Y#1P]8/O\'0<+O6"Y#1P]8/M\"(.O at 35(B(BD'`JX##A3<*OD'`HX)`0
-M'/"0<"G at D!`=3D\)!P*N"0$![PD!`<X/5BD!`>X"#A\Y`0'."0<"CPD!`=3DX)!P
-M*?"0$![@D'`J\#!*!Y!P).!$`?#"!=3D*O(B(B````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
@@ -212,21 +226,7 @@
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
 M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M````````````````````````````````````````````````````````````
-M```````````````````````````````````````````````````````````1
-"=3DX$`
+M``````````````````````````````````````````````````````````#L
+"*=3D(`
 `
 end
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/pf/net/if_pfsync.c
--- a/head/sys/contrib/pf/net/if_pfsync.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/pf/net/if_pfsync.c	Tue Apr 17 11:51:51 2012 +0300
@@ -50,6 +50,8 @@
  * 1.128 - cleanups
  * 1.146 - bzero() mbuf before sparsely filling it with data
  * 1.170 - SIOCSIFMTU checks
+ * 1.126, 1.142 - deferred packets processing
+ * 1.173 - correct expire time processing
  */
=20
 #ifdef __FreeBSD__
@@ -58,7 +60,7 @@
 #include "opt_pf.h"
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/contrib/pf/net/if_pfsync.c 232685 2012-03-08 =
09:20:00Z glebius $");
+__FBSDID("$FreeBSD: head/sys/contrib/pf/net/if_pfsync.c 233917 2012-04-05 =
04:41:06Z ae $");
=20
 #define	NBPFILTER	1
 #endif /* __FreeBSD__ */
@@ -262,6 +264,7 @@
=20
 	struct pfsync_upd_reqs	 sc_upd_req_list;
=20
+	int			 sc_defer;
 	struct pfsync_deferrals	 sc_deferrals;
 	u_int			 sc_deferred;
=20
@@ -787,11 +790,20 @@
 	st->creation =3D time_uptime - ntohl(sp->creation);
 	st->expire =3D time_second;
 	if (sp->expire) {
-		/* XXX No adaptive scaling. */
-		st->expire -=3D r->timeout[sp->timeout] - ntohl(sp->expire);
+		uint32_t timeout;
+
+		timeout =3D r->timeout[sp->timeout];
+		if (!timeout)
+#ifdef __FreeBSD__
+			timeout =3D V_pf_default_rule.timeout[sp->timeout];
+#else
+			timeout =3D pf_default_rule.timeout[sp->timeout];
+#endif
+
+		/* sp->expire may have been adaptively scaled by export. */
+		st->expire -=3D timeout - ntohl(sp->expire);
 	}
=20
-	st->expire =3D ntohl(sp->expire) + time_second;
 	st->direction =3D sp->direction;
 	st->log =3D sp->log;
 	st->timeout =3D sp->timeout;
@@ -1289,7 +1301,7 @@
 		pfsync_alloc_scrub_memory(&sp->dst, &st->dst);
 		pf_state_peer_ntoh(&sp->src, &st->src);
 		pf_state_peer_ntoh(&sp->dst, &st->dst);
-		st->expire =3D ntohl(sp->expire) + time_second;
+		st->expire =3D time_second;
 		st->timeout =3D sp->timeout;
 		st->pfsync_time =3D time_uptime;
 	}
@@ -1395,7 +1407,7 @@
 		pfsync_alloc_scrub_memory(&up->dst, &st->dst);
 		pf_state_peer_ntoh(&up->src, &st->src);
 		pf_state_peer_ntoh(&up->dst, &st->dst);
-		st->expire =3D ntohl(up->expire) + time_second;
+		st->expire =3D time_second;
 		st->timeout =3D up->timeout;
 		st->pfsync_time =3D time_uptime;
 	}
@@ -1805,6 +1817,7 @@
 		}
 		pfsyncr.pfsyncr_syncpeer =3D sc->sc_sync_peer;
 		pfsyncr.pfsyncr_maxupdates =3D sc->sc_maxupdates;
+		pfsyncr.pfsyncr_defer =3D sc->sc_defer;
 		return (copyout(&pfsyncr, ifr->ifr_data, sizeof(pfsyncr)));
=20
 	case SIOCSETPFSYNC:
@@ -1840,6 +1853,7 @@
 		}
 #endif
 		sc->sc_maxupdates =3D pfsyncr.pfsyncr_maxupdates;
+		sc->sc_defer =3D pfsyncr.pfsyncr_defer;
=20
 		if (pfsyncr.pfsyncr_syncdev[0] =3D=3D 0) {
 			sc->sc_sync_if =3D NULL;
@@ -2017,12 +2031,6 @@
 	pf_state_peer_hton(&st->src, &up->src);
 	pf_state_peer_hton(&st->dst, &up->dst);
 	up->creatorid =3D st->creatorid;
-
-	up->expire =3D pf_state_expires(st);
-	if (up->expire <=3D time_second)
-		up->expire =3D htonl(0);
-	else
-		up->expire =3D htonl(up->expire - time_second);
 	up->timeout =3D st->timeout;
=20
 	return (sizeof(*up));
@@ -2378,10 +2386,7 @@
=20
 	pfsync_q_ins(st, PFSYNC_S_INS);
=20
-	if (ISSET(st->state_flags, PFSTATE_ACK))
-		schednetisr(NETISR_PFSYNC);
-	else
-		st->sync_updates =3D 0;
+	st->sync_updates =3D 0;
 }
=20
 int defer =3D 10;
@@ -2402,6 +2407,9 @@
 	splassert(IPL_SOFTNET);
 #endif
=20
+	if (!sc->sc_defer || m->m_flags & (M_BCAST|M_MCAST))
+		return (0);
+
 	if (sc->sc_deferred >=3D 128)
 		pfsync_undefer(TAILQ_FIRST(&sc->sc_deferrals), 0);
=20
@@ -2430,6 +2438,8 @@
 	timeout_add(&pd->pd_tmo, defer);
 #endif
=20
+	swi_sched(V_pfsync_swi_cookie, 0);
+
 	return (1);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/contrib/pf/net/if_pfsync.h
--- a/head/sys/contrib/pf/net/if_pfsync.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/contrib/pf/net/if_pfsync.h	Tue Apr 17 11:51:51 2012 +0300
@@ -265,7 +265,7 @@
 	char		 pfsyncr_syncdev[IFNAMSIZ];
 	struct in_addr	 pfsyncr_syncpeer;
 	int		 pfsyncr_maxupdates;
-	int		 pfsyncr_authlevel;
+	int		 pfsyncr_defer;
 };
=20
 #ifdef __FreeBSD__
diff -r 428842767fa6 -r f2935497fa04 head/sys/ddb/db_main.c
--- a/head/sys/ddb/db_main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ddb/db_main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/ddb/db_main.c 234196 2012-04-12 21:34:58Z jhb=
 $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -51,8 +51,10 @@
 static dbbe_init_f db_init;
 static dbbe_trap_f db_trap;
 static dbbe_trace_f db_trace_self_wrapper;
+static dbbe_trace_thread_f db_trace_thread_wrapper;
=20
-KDB_BACKEND(ddb, db_init, db_trace_self_wrapper, db_trap);
+KDB_BACKEND(ddb, db_init, db_trace_self_wrapper, db_trace_thread_wrapper,
+    db_trap);
=20
 vm_offset_t ksym_start, ksym_end;
=20
@@ -246,3 +248,15 @@
 		db_trace_self();
 	(void)kdb_jmpbuf(prev_jb);
 }
+
+static void
+db_trace_thread_wrapper(struct thread *td)
+{
+	jmp_buf jb;
+	void *prev_jb;
+
+	prev_jb =3D kdb_jmpbuf(jb);
+	if (setjmp(jb) =3D=3D 0)
+		db_trace_thread(td, -1);
+	(void)kdb_jmpbuf(prev_jb);
+}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/acpica/acpi.c
--- a/head/sys/dev/acpica/acpi.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/acpica/acpi.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/acpica/acpi.c 231844 2012-02-16 22:59:29Z=
 jkim $");
+__FBSDID("$FreeBSD: head/sys/dev/acpica/acpi.c 233579 2012-03-27 23:26:58Z=
 jkim $");
=20
 #include "opt_acpi.h"
 #include <sys/param.h>
@@ -97,6 +97,9 @@
 /* Bitmap of device quirks. */
 int		acpi_quirks;
=20
+/* Optional ACPI methods for suspend and resume, e.g., _GTS and _BFS. */
+int		acpi_sleep_flags;
+
 /* Supported sleep states. */
 static BOOLEAN	acpi_sleep_states[ACPI_S_STATE_COUNT];
=20
@@ -289,6 +292,11 @@
 /* Allow users to override quirks. */
 TUNABLE_INT("debug.acpi.quirks", &acpi_quirks);
=20
+/* Execute optional ACPI methods for suspend and resume. */
+TUNABLE_INT("debug.acpi.sleep_flags", &acpi_sleep_flags);
+SYSCTL_INT(_debug_acpi, OID_AUTO, sleep_flags, CTLFLAG_RW | CTLFLAG_TUN,
+    &acpi_sleep_flags, 0, "Execute optional ACPI methods for suspend/resum=
e.");
+
 static int acpi_susp_bounce;
 SYSCTL_INT(_debug_acpi, OID_AUTO, suspend_bounce, CTLFLAG_RW,
     &acpi_susp_bounce, 0, "Don't actually suspend, just test devices.");
@@ -1960,6 +1968,7 @@
 acpi_shutdown_final(void *arg, int howto)
 {
     struct acpi_softc *sc =3D (struct acpi_softc *)arg;
+    register_t intr;
     ACPI_STATUS status;
=20
     /*
@@ -1975,13 +1984,15 @@
 	    return;
 	}
 	device_printf(sc->acpi_dev, "Powering system off\n");
-	ACPI_DISABLE_IRQS();
-	status =3D AcpiEnterSleepState(ACPI_STATE_S5);
-	if (ACPI_FAILURE(status))
+	intr =3D intr_disable();
+	status =3D AcpiEnterSleepState(ACPI_STATE_S5, acpi_sleep_flags);
+	if (ACPI_FAILURE(status)) {
+	    intr_restore(intr);
 	    device_printf(sc->acpi_dev, "power-off failed - %s\n",
 		AcpiFormatException(status));
-	else {
+	} else {
 	    DELAY(1000000);
+	    intr_restore(intr);
 	    device_printf(sc->acpi_dev, "power-off failed - timeout\n");
 	}
     } else if ((howto & RB_HALT) =3D=3D 0 && sc->acpi_handle_reboot) {
@@ -2633,7 +2644,8 @@
 static ACPI_STATUS
 acpi_EnterSleepState(struct acpi_softc *sc, int state)
 {
-    ACPI_STATUS	status;
+    register_t intr;
+    ACPI_STATUS status;
     enum acpi_sleep_state slp_state;
=20
     ACPI_FUNCTION_TRACE_U32((char *)(uintptr_t)__func__, state);
@@ -2722,8 +2734,9 @@
 	if (state =3D=3D ACPI_STATE_S4)
 	    AcpiEnable();
     } else {
-	ACPI_DISABLE_IRQS();
-	status =3D AcpiEnterSleepState(state);
+	intr =3D intr_disable();
+	status =3D AcpiEnterSleepState(state, acpi_sleep_flags);
+	intr_restore(intr);
 	if (ACPI_FAILURE(status)) {
 	    device_printf(sc->acpi_dev, "AcpiEnterSleepState failed - %s\n",
 			  AcpiFormatException(status));
@@ -2742,7 +2755,7 @@
 	sc->acpi_sstate =3D ACPI_STATE_S0;
     }
     if (slp_state >=3D ACPI_SS_SLP_PREP) {
-	AcpiLeaveSleepStatePrep(state);
+	AcpiLeaveSleepStatePrep(state, acpi_sleep_flags);
 	AcpiLeaveSleepState(state);
     }
     if (slp_state >=3D ACPI_SS_DEV_SUSPEND)
@@ -3532,6 +3545,7 @@
     {"ACPI_LV_INIT",		ACPI_LV_INIT},
     {"ACPI_LV_DEBUG_OBJECT",	ACPI_LV_DEBUG_OBJECT},
     {"ACPI_LV_INFO",		ACPI_LV_INFO},
+    {"ACPI_LV_REPAIR",		ACPI_LV_REPAIR},
     {"ACPI_LV_ALL_EXCEPTIONS",	ACPI_LV_ALL_EXCEPTIONS},
=20
     /* Trace verbosity level 1 [Standard Trace Level] */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/acpica/acpi_pcib_acpi.c
--- a/head/sys/dev/acpica/acpi_pcib_acpi.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/acpica/acpi_pcib_acpi.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/acpica/acpi_pcib_acpi.c 228961 2011-12-29=
 16:23:14Z jhb $");
+__FBSDID("$FreeBSD: head/sys/dev/acpica/acpi_pcib_acpi.c 233676 2012-03-29=
 19:03:22Z jhb $");
=20
 #include "opt_acpi.h"
 #include <sys/param.h>
@@ -59,8 +59,9 @@
     ACPI_HANDLE		ap_handle;
     int			ap_flags;
=20
-    int			ap_segment;	/* analagous to Alpha 'hose' */
+    int			ap_segment;	/* PCI domain */
     int			ap_bus;		/* bios-assigned bus number */
+    int			ap_addr;	/* device/func of PCI-Host bridge */
=20
     ACPI_BUFFER		ap_prt;		/* interrupt routing table */
 #ifdef NEW_PCIB
@@ -276,7 +277,7 @@
     struct acpi_hpcib_softc	*sc;
     ACPI_STATUS			status;
     static int bus0_seen =3D 0;
-    u_int addr, slot, func, busok;
+    u_int slot, func, busok;
     uint8_t busno;
=20
     ACPI_FUNCTION_TRACE((char *)(uintptr_t)__func__);
@@ -286,7 +287,7 @@
     sc->ap_handle =3D acpi_get_handle(dev);
=20
     /*
-     * Get our segment number by evaluating _SEG
+     * Get our segment number by evaluating _SEG.
      * It's OK for this to not exist.
      */
     status =3D acpi_GetInteger(sc->ap_handle, "_SEG", &sc->ap_segment);
@@ -300,6 +301,18 @@
 	sc->ap_segment =3D 0;
     }
=20
+    /*
+     * Get the address (device and function) of the associated
+     * PCI-Host bridge device from _ADR.  Assume we don't have one if
+     * it doesn't exist.
+     */
+    status =3D acpi_GetInteger(sc->ap_handle, "_ADR", &sc->ap_addr);
+    if (ACPI_FAILURE(status)) {
+	device_printf(dev, "could not evaluate _ADR - %s\n",
+	    AcpiFormatException(status));
+	sc->ap_addr =3D -1;
+    }
+
 #ifdef NEW_PCIB
     /*
      * Determine which address ranges this bridge decodes and setup
@@ -354,18 +367,10 @@
     busok =3D 1;
     if (sc->ap_segment =3D=3D 0 && sc->ap_bus =3D=3D 0 && bus0_seen) {
 	busok =3D 0;
-	status =3D acpi_GetInteger(sc->ap_handle, "_ADR", &addr);
-	if (ACPI_FAILURE(status)) {
-	    if (status !=3D AE_NOT_FOUND) {
-		device_printf(dev, "could not evaluate _ADR - %s\n",
-		    AcpiFormatException(status));
-		return_VALUE (ENXIO);
-	    } else
-		device_printf(dev, "couldn't find _ADR\n");
-	} else {
+	if (sc->ap_addr !=3D -1) {
 	    /* XXX: We assume bus 0. */
-	    slot =3D ACPI_ADR_PCI_SLOT(addr);
-	    func =3D ACPI_ADR_PCI_FUNC(addr);
+	    slot =3D ACPI_ADR_PCI_SLOT(sc->ap_addr);
+	    func =3D ACPI_ADR_PCI_FUNC(sc->ap_addr);
 	    if (bootverbose)
 		device_printf(dev, "reading config registers from 0:%d:%d\n",
 		    slot, func);
@@ -488,10 +493,24 @@
 acpi_pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
     uint32_t *data)
 {
-	device_t bus;
+	struct acpi_hpcib_softc *sc;
+	device_t bus, hostb;
+	int error;
=20
 	bus =3D device_get_parent(pcib);
-	return (PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data));
+	error =3D PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data);
+	if (error)
+		return (error);
+
+	sc =3D device_get_softc(dev);
+	if (sc->ap_addr =3D=3D -1)
+		return (0);
+	/* XXX: Assumes all bridges are on bus 0. */
+	hostb =3D pci_find_dbsf(sc->ap_segment, 0, ACPI_ADR_PCI_SLOT(sc->ap_addr),
+	    ACPI_ADR_PCI_FUNC(sc->ap_addr));
+	if (hostb !=3D NULL)
+		pci_ht_map_msi(hostb, *addr);
+	return (0);
 }
=20
 struct resource *
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/acpica/acpivar.h
--- a/head/sys/dev/acpica/acpivar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/acpica/acpivar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/acpica/acpivar.h 231227 2012-02-08 21:23:20Z jki=
m $
+ * $FreeBSD: head/sys/dev/acpica/acpivar.h 233250 2012-03-20 21:37:52Z jki=
m $
  */
=20
 #ifndef _ACPIVAR_H_
@@ -217,6 +217,11 @@
 #define ACPI_Q_MADT_IRQ0	(1 << 2)
=20
 /*
+ * Sleep flags.  See actypes.h for available flags.
+ */
+extern int	acpi_sleep_flags;
+
+/*
  * Note that the low ivar values are reserved to provide
  * interface compatibility with ISA drivers which can also
  * attach to ACPI.
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/aic7xxx/aicasm/aicasm_sym=
bol.c
--- a/head/sys/dev/aic7xxx/aicasm/aicasm_symbol.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sys/dev/aic7xxx/aicasm/aicasm_symbol.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -39,12 +39,12 @@
  *
  * $Id: //depot/aic7xxx/aic7xxx/aicasm/aicasm_symbol.c#24 $
  *
- * $FreeBSD: head/sys/dev/aic7xxx/aicasm/aicasm_symbol.c 224046 2011-07-15=
 00:36:47Z emaste $
+ * $FreeBSD: head/sys/dev/aic7xxx/aicasm/aicasm_symbol.c 233479 2012-03-25=
 21:54:36Z rmh $
  */
=20
 #include <sys/types.h>
 #include <sys/param.h>
-#ifdef BSD
+#if defined(BSD) && !defined(__GNU__)
 #include <db.h>
 #else
 #include <db_185.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ale/if_ale.c
--- a/head/sys/dev/ale/if_ale.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ale/if_ale.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 /* Driver for Atheros AR8121/AR8113/AR8114 PCIe Ethernet. */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ale/if_ale.c 226478 2011-10-17 19:49:00Z =
yongari $");
+__FBSDID("$FreeBSD: head/sys/dev/ale/if_ale.c 233888 2012-04-04 21:09:02Z =
marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -91,11 +91,11 @@
 /*
  * Devices supported by this driver.
  */
-static struct ale_dev {
+static const struct ale_dev {
 	uint16_t	ale_vendorid;
 	uint16_t	ale_deviceid;
 	const char	*ale_name;
-} ale_devs[] =3D {
+} const ale_devs[] =3D {
     { VENDORID_ATHEROS, DEVICEID_ATHEROS_AR81XX,
     "Atheros AR8121/AR8113/AR8114 PCIe Ethernet" },
 };
@@ -115,7 +115,6 @@
 static void	ale_int_task(void *, int);
 static int	ale_intr(void *);
 static int	ale_ioctl(struct ifnet *, u_long, caddr_t);
-static void	ale_link_task(void *, int);
 static void	ale_mac_config(struct ale_softc *);
 static int	ale_miibus_readreg(device_t, int, int);
 static void	ale_miibus_statchg(device_t);
@@ -164,7 +163,7 @@
 	DEVMETHOD(miibus_writereg,	ale_miibus_writereg),
 	DEVMETHOD(miibus_statchg,	ale_miibus_statchg),
=20
-	{ NULL, NULL }
+	DEVMETHOD_END
 };
=20
 static driver_t ale_driver =3D {
@@ -175,8 +174,8 @@
=20
 static devclass_t ale_devclass;
=20
-DRIVER_MODULE(ale, pci, ale_driver, ale_devclass, 0, 0);
-DRIVER_MODULE(miibus, ale, miibus_driver, miibus_devclass, 0, 0);
+DRIVER_MODULE(ale, pci, ale_driver, ale_devclass, NULL, NULL);
+DRIVER_MODULE(miibus, ale, miibus_driver, miibus_devclass, NULL, NULL);
=20
 static struct resource_spec ale_res_spec_mem[] =3D {
 	{ SYS_RES_MEMORY,	PCIR_BAR(0),	RF_ACTIVE },
@@ -253,10 +252,45 @@
 ale_miibus_statchg(device_t dev)
 {
 	struct ale_softc *sc;
+	struct mii_data *mii;
+	struct ifnet *ifp;
+	uint32_t reg;
=20
 	sc =3D device_get_softc(dev);
+	mii =3D device_get_softc(sc->ale_miibus);
+	ifp =3D sc->ale_ifp;
+	if (mii =3D=3D NULL || ifp =3D=3D NULL ||
+	    (ifp->if_drv_flags & IFF_DRV_RUNNING) =3D=3D 0)
+		return;
=20
-	taskqueue_enqueue(taskqueue_swi, &sc->ale_link_task);
+	sc->ale_flags &=3D ~ALE_FLAG_LINK;
+	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) =3D=3D
+	    (IFM_ACTIVE | IFM_AVALID)) {
+		switch (IFM_SUBTYPE(mii->mii_media_active)) {
+		case IFM_10_T:
+		case IFM_100_TX:
+			sc->ale_flags |=3D ALE_FLAG_LINK;
+			break;
+		case IFM_1000_T:
+			if ((sc->ale_flags & ALE_FLAG_FASTETHER) =3D=3D 0)
+				sc->ale_flags |=3D ALE_FLAG_LINK;
+			break;
+		default:
+			break;
+		}
+	}
+
+	/* Stop Rx/Tx MACs. */
+	ale_stop_mac(sc);
+
+	/* Program MACs with resolved speed/duplex/flow-control. */
+	if ((sc->ale_flags & ALE_FLAG_LINK) !=3D 0) {
+		ale_mac_config(sc);
+		/* Reenable Tx/Rx MACs. */
+		reg =3D CSR_READ_4(sc, ALE_MAC_CFG);
+		reg |=3D MAC_CFG_TX_ENB | MAC_CFG_RX_ENB;
+		CSR_WRITE_4(sc, ALE_MAC_CFG, reg);
+	}
 }
=20
 static void
@@ -267,6 +301,10 @@
=20
 	sc =3D ifp->if_softc;
 	ALE_LOCK(sc);
+	if ((ifp->if_flags & IFF_UP) =3D=3D 0) {
+		ALE_UNLOCK(sc);
+		return;
+	}
 	mii =3D device_get_softc(sc->ale_miibus);
=20
 	mii_pollstat(mii);
@@ -297,7 +335,7 @@
 static int
 ale_probe(device_t dev)
 {
-	struct ale_dev *sp;
+	const struct ale_dev *sp;
 	int i;
 	uint16_t vendor, devid;
=20
@@ -425,7 +463,6 @@
 	    MTX_DEF);
 	callout_init_mtx(&sc->ale_tick_ch, &sc->ale_mtx, 0);
 	TASK_INIT(&sc->ale_int_task, 0, ale_int_task, sc);
-	TASK_INIT(&sc->ale_link_task, 0, ale_link_task, sc);
=20
 	/* Map the device. */
 	pci_enable_busmaster(dev);
@@ -598,7 +635,7 @@
 	/* Set up MII bus. */
 	error =3D mii_attach(dev, &sc->ale_miibus, ifp, ale_mediachange,
 	    ale_mediastatus, BMSR_DEFCAPMASK, sc->ale_phyaddr, MII_OFFSET_ANY,
-	    0);
+	    MIIF_DOPAUSE);
 	if (error !=3D 0) {
 		device_printf(dev, "attaching PHYs failed\n");
 		goto fail;
@@ -679,7 +716,6 @@
 		ALE_UNLOCK(sc);
 		callout_drain(&sc->ale_tick_ch);
 		taskqueue_drain(sc->ale_tq, &sc->ale_int_task);
-		taskqueue_drain(taskqueue_swi, &sc->ale_link_task);
 	}
=20
 	if (sc->ale_tq !=3D NULL) {
@@ -2065,68 +2101,15 @@
 	}
 	if ((IFM_OPTIONS(mii->mii_media_active) & IFM_FDX) !=3D 0) {
 		reg |=3D MAC_CFG_FULL_DUPLEX;
-#ifdef notyet
 		if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_TXPAUSE) !=3D 0)
 			reg |=3D MAC_CFG_TX_FC;
 		if ((IFM_OPTIONS(mii->mii_media_active) & IFM_ETH_RXPAUSE) !=3D 0)
 			reg |=3D MAC_CFG_RX_FC;
-#endif
 	}
 	CSR_WRITE_4(sc, ALE_MAC_CFG, reg);
 }
=20
 static void
-ale_link_task(void *arg, int pending)
-{
-	struct ale_softc *sc;
-	struct mii_data *mii;
-	struct ifnet *ifp;
-	uint32_t reg;
-
-	sc =3D (struct ale_softc *)arg;
-
-	ALE_LOCK(sc);
-	mii =3D device_get_softc(sc->ale_miibus);
-	ifp =3D sc->ale_ifp;
-	if (mii =3D=3D NULL || ifp =3D=3D NULL ||
-	    (ifp->if_drv_flags & IFF_DRV_RUNNING) =3D=3D 0) {
-		ALE_UNLOCK(sc);
-		return;
-	}
-
-	sc->ale_flags &=3D ~ALE_FLAG_LINK;
-	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) =3D=3D
-	    (IFM_ACTIVE | IFM_AVALID)) {
-		switch (IFM_SUBTYPE(mii->mii_media_active)) {
-		case IFM_10_T:
-		case IFM_100_TX:
-			sc->ale_flags |=3D ALE_FLAG_LINK;
-			break;
-		case IFM_1000_T:
-			if ((sc->ale_flags & ALE_FLAG_FASTETHER) =3D=3D 0)
-				sc->ale_flags |=3D ALE_FLAG_LINK;
-			break;
-		default:
-			break;
-		}
-	}
-
-	/* Stop Rx/Tx MACs. */
-	ale_stop_mac(sc);
-
-	/* Program MACs with resolved speed/duplex/flow-control. */
-	if ((sc->ale_flags & ALE_FLAG_LINK) !=3D 0) {
-		ale_mac_config(sc);
-		/* Reenable Tx/Rx MACs. */
-		reg =3D CSR_READ_4(sc, ALE_MAC_CFG);
-		reg |=3D MAC_CFG_TX_ENB | MAC_CFG_RX_ENB;
-		CSR_WRITE_4(sc, ALE_MAC_CFG, reg);
-	}
-
-	ALE_UNLOCK(sc);
-}
-
-static void
 ale_stats_clear(struct ale_softc *sc)
 {
 	struct smb sb;
@@ -2813,7 +2796,7 @@
 		    ((rxf_lo << RX_FIFO_PAUSE_THRESH_LO_SHIFT) &
 		    RX_FIFO_PAUSE_THRESH_LO_MASK) |
 		    ((rxf_hi << RX_FIFO_PAUSE_THRESH_HI_SHIFT) &
-		     RX_FIFO_PAUSE_THRESH_HI_MASK));
+		    RX_FIFO_PAUSE_THRESH_HI_MASK));
 	}
=20
 	/* Disable RSS. */
@@ -2876,14 +2859,14 @@
 	CSR_WRITE_4(sc, ALE_INTR_STATUS, 0xFFFFFFFF);
 	CSR_WRITE_4(sc, ALE_INTR_STATUS, 0);
=20
+	ifp->if_drv_flags |=3D IFF_DRV_RUNNING;
+	ifp->if_drv_flags &=3D ~IFF_DRV_OACTIVE;
+
 	sc->ale_flags &=3D ~ALE_FLAG_LINK;
 	/* Switch to the current media. */
 	mii_mediachg(mii);
=20
 	callout_reset(&sc->ale_tick_ch, hz, ale_tick, sc);
-
-	ifp->if_drv_flags |=3D IFF_DRV_RUNNING;
-	ifp->if_drv_flags &=3D ~IFF_DRV_OACTIVE;
 }
=20
 static void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ale/if_alevar.h
--- a/head/sys/dev/ale/if_alevar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ale/if_alevar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/dev/ale/if_alevar.h 233688 2012-03-30 04:46:39Z yong=
ari $
  */
=20
 #ifndef	_IF_ALEVAR_H
@@ -221,7 +221,6 @@
 	int			ale_pagesize;
=20
 	struct task		ale_int_task;
-	struct task		ale_link_task;
 	struct taskqueue	*ale_tq;
 	struct mtx		ale_mtx;
 };
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-all.c
--- a/head/sys/dev/ata/ata-all.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-all.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/ata-all.c 230132 2012-01-15 13:23:18Z=
 uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/ata-all.c 233282 2012-03-21 16:59:39Z=
 marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -79,9 +79,11 @@
 static void atapoll(struct cam_sim *sim);
 #endif
 static void ata_conn_event(void *, int);
+#ifndef ATA_CAM
 static void bswap(int8_t *, int);
 static void btrim(int8_t *, int);
 static void bpack(int8_t *, int8_t *, int);
+#endif
 static void ata_interrupt_locked(void *data);
 #ifdef ATA_CAM
 static void ata_periodic_poll(void *data);
@@ -90,27 +92,36 @@
 /* global vars */
 MALLOC_DEFINE(M_ATA, "ata_generic", "ATA driver generic layer");
 int (*ata_raid_ioctl_func)(u_long cmd, caddr_t data) =3D NULL;
+#ifndef ATA_CAM
 struct intr_config_hook *ata_delayed_attach =3D NULL;
+#endif
 devclass_t ata_devclass;
 uma_zone_t ata_request_zone;
 uma_zone_t ata_composite_zone;
+#ifndef ATA_CAM
 int ata_wc =3D 1;
 int ata_setmax =3D 0;
+#endif
 int ata_dma_check_80pin =3D 1;
=20
 /* local vars */
+#ifndef ATA_CAM
 static int ata_dma =3D 1;
 static int atapi_dma =3D 1;
+#endif
=20
 /* sysctl vars */
 static SYSCTL_NODE(_hw, OID_AUTO, ata, CTLFLAG_RD, 0, "ATA driver paramete=
rs");
+#ifndef ATA_CAM
 TUNABLE_INT("hw.ata.ata_dma", &ata_dma);
 SYSCTL_INT(_hw_ata, OID_AUTO, ata_dma, CTLFLAG_RDTUN, &ata_dma, 0,
 	   "ATA disk DMA mode control");
+#endif
 TUNABLE_INT("hw.ata.ata_dma_check_80pin", &ata_dma_check_80pin);
 SYSCTL_INT(_hw_ata, OID_AUTO, ata_dma_check_80pin,
 	   CTLFLAG_RW, &ata_dma_check_80pin, 1,
 	   "Check for 80pin cable before setting ATA DMA mode");
+#ifndef ATA_CAM
 TUNABLE_INT("hw.ata.atapi_dma", &atapi_dma);
 SYSCTL_INT(_hw_ata, OID_AUTO, atapi_dma, CTLFLAG_RDTUN, &atapi_dma, 0,
 	   "ATAPI device DMA mode control");
@@ -120,6 +131,7 @@
 TUNABLE_INT("hw.ata.setmax", &ata_setmax);
 SYSCTL_INT(_hw_ata, OID_AUTO, setmax, CTLFLAG_RDTUN, &ata_setmax, 0,
 	   "ATA disk set max native address");
+#endif
 #ifdef ATA_CAM
 FEATURE(ata_cam, "ATA devices are accessed through the cam(4) driver");
 #endif
@@ -186,13 +198,13 @@
 	callout_init(&ch->poll_callout, 1);
 #endif
=20
+#ifndef ATA_CAM
     /* reset the controller HW, the channel and device(s) */
     while (ATA_LOCKING(dev, ATA_LF_LOCK) !=3D ch->unit)
 	pause("ataatch", 1);
-#ifndef ATA_CAM
     ATA_RESET(dev);
+    ATA_LOCKING(dev, ATA_LF_UNLOCK);
 #endif
-    ATA_LOCKING(dev, ATA_LF_UNLOCK);
=20
     /* allocate DMA resources if DMA HW present*/
     if (ch->dma.alloc)
@@ -606,6 +618,7 @@
                   "DMA limited to UDMA33, %s found non-ATA66 cable\n", who=
);
 }
=20
+#ifndef ATA_CAM
 int
 ata_check_80pin(device_t dev, int mode)
 {
@@ -623,7 +636,9 @@
     }
     return mode;
 }
+#endif
=20
+#ifndef ATA_CAM
 void
 ata_setmode(device_t dev)
 {
@@ -644,6 +659,7 @@
 		    (error) ? "FAILURE " : "", ata_mode2str(mode));
 	atadev->mode =3D mode;
 }
+#endif
=20
 /*
  * device related interfaces
@@ -732,6 +748,7 @@
 }
 #endif
=20
+#ifndef ATA_CAM
 int
 ata_device_ioctl(device_t dev, u_long cmd, caddr_t data)
 {
@@ -830,6 +847,7 @@
 	return ENOTTY;
     }
 }
+#endif
=20
 #ifndef ATA_CAM
 static void
@@ -878,6 +896,7 @@
 }
 #endif
=20
+#ifndef ATA_CAM
 int
 ata_getparam(struct ata_device *atadev, int init)
 {
@@ -983,6 +1002,7 @@
     }
     return error;
 }
+#endif
=20
 #ifndef ATA_CAM
 int
@@ -1188,7 +1208,8 @@
 	pause("ataslp", interval/(1000000/hz));
 }
=20
-char *
+#ifndef ATA_CAM
+const char *
 ata_unit2str(struct ata_device *atadev)
 {
     struct ata_channel *ch =3D device_get_softc(device_get_parent(atadev->=
dev));
@@ -1200,6 +1221,7 @@
 	sprintf(str, "%s", atadev->unit =3D=3D ATA_MASTER ? "master" : "slave");
     return str;
 }
+#endif
=20
 const char *
 ata_mode2str(int mode)
@@ -1260,6 +1282,7 @@
 	return (-1);
 }
=20
+#ifndef ATA_CAM
 const char *
 ata_satarev2str(int rev)
 {
@@ -1272,6 +1295,7 @@
 	default: return "???";
 	}
 }
+#endif
=20
 int
 ata_atapi(device_t dev, int target)
@@ -1281,6 +1305,7 @@
     return (ch->devices & (ATA_ATAPI_MASTER << target));
 }
=20
+#ifndef ATA_CAM
 int
 ata_pmode(struct ata_params *ap)
 {
@@ -1304,7 +1329,9 @@
 	return ATA_PIO0;
     return ATA_PIO0;
 }
+#endif
=20
+#ifndef ATA_CAM
 int
 ata_wmode(struct ata_params *ap)
 {
@@ -1316,7 +1343,9 @@
 	return ATA_WDMA0;
     return -1;
 }
+#endif
=20
+#ifndef ATA_CAM
 int
 ata_umode(struct ata_params *ap)
 {
@@ -1338,7 +1367,9 @@
     }
     return -1;
 }
+#endif
=20
+#ifndef ATA_CAM
 int
 ata_limit_mode(device_t dev, int mode, int maxmode)
 {
@@ -1358,7 +1389,9 @@
=20
     return mode;
 }
+#endif
=20
+#ifndef ATA_CAM
 static void
 bswap(int8_t *buf, int len)
 {
@@ -1367,7 +1400,9 @@
     while (--ptr >=3D (u_int16_t*)buf)
 	*ptr =3D ntohs(*ptr);
 }
+#endif
=20
+#ifndef ATA_CAM
 static void
 btrim(int8_t *buf, int len)
 {
@@ -1379,7 +1414,9 @@
     for (ptr =3D buf + len - 1; ptr >=3D buf && *ptr =3D=3D ' '; --ptr)
 	*ptr =3D 0;
 }
+#endif
=20
+#ifndef ATA_CAM
 static void
 bpack(int8_t *src, int8_t *dst, int len)
 {
@@ -1402,6 +1439,7 @@
     if (j < len)
 	dst[j] =3D 0x00;
 }
+#endif
=20
 #ifdef ATA_CAM
 void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-all.h
--- a/head/sys/dev/ata/ata-all.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-all.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/ata/ata-all.h 230132 2012-01-15 13:23:18Z uqs $
+ * $FreeBSD: head/sys/dev/ata/ata-all.h 233282 2012-03-21 16:59:39Z marius=
 $
  */
=20
 #include "opt_ata.h"
@@ -622,7 +622,7 @@
 void ata_default_registers(device_t dev);
 void ata_modify_if_48bit(struct ata_request *request);
 void ata_udelay(int interval);
-char *ata_unit2str(struct ata_device *atadev);
+const char *ata_unit2str(struct ata_device *atadev);
 const char *ata_mode2str(int mode);
 int ata_str2mode(const char *str);
 const char *ata_satarev2str(int rev);
@@ -649,7 +649,7 @@
 void ata_catch_inflight(device_t dev);
 void ata_fail_requests(device_t dev);
 void ata_drop_requests(device_t dev);
-char *ata_cmd2str(struct ata_request *request);
+const char *ata_cmd2str(struct ata_request *request);
=20
 /* ata-lowlevel.c: */
 void ata_generic_hw(device_t dev);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-card.c
--- a/head/sys/dev/ata/ata-card.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-card.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/ata-card.c 230132 2012-01-15 13:23:18=
Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/ata-card.c 233282 2012-03-21 16:59:39=
Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -49,7 +49,7 @@
=20
 #include "pccarddevs.h"
=20
-static const struct pccard_product ata_pccard_products[] =3D {
+static const struct pccard_product const ata_pccard_products[] =3D {
 	PCMCIA_CARD(FREECOM, PCCARDIDE),
 	PCMCIA_CARD(EXP, EXPMULTIMEDIA),
 	PCMCIA_CARD(IODATA3, CBIDE2),
@@ -172,7 +172,7 @@
     DEVMETHOD(device_attach,            ata_pccard_attach),
     DEVMETHOD(device_detach,            ata_pccard_detach),
=20
-    { 0, 0 }
+    DEVMETHOD_END
 };
=20
 static driver_t ata_pccard_driver =3D {
@@ -181,5 +181,5 @@
     sizeof(struct ata_channel),
 };
=20
-DRIVER_MODULE(ata, pccard, ata_pccard_driver, ata_devclass, 0, 0);
+DRIVER_MODULE(ata, pccard, ata_pccard_driver, ata_devclass, NULL, NULL);
 MODULE_DEPEND(ata, ata, 1, 1, 1);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-cbus.c
--- a/head/sys/dev/ata/ata-cbus.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-cbus.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/ata-cbus.c 230132 2012-01-15 13:23:18=
Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/ata-cbus.c 233282 2012-03-21 16:59:39=
Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -248,7 +248,7 @@
     DEVMETHOD(bus_setup_intr,           ata_cbus_setup_intr),
     DEVMETHOD(bus_print_child,          ata_cbus_print_child),
=20
-    { 0, 0 }
+    DEVMETHOD_END
 };
=20
 static driver_t ata_cbus_driver =3D {
@@ -339,11 +339,14 @@
 ata_cbuschannel_banking(device_t dev, int flags)
 {
     struct ata_cbus_controller *ctlr =3D device_get_softc(device_get_paren=
t(dev));
+#ifndef ATA_CAM
     struct ata_channel *ch =3D device_get_softc(dev);
+#endif
     int res;
=20
     mtx_lock(&ctlr->bank_mtx);
     switch (flags) {
+#ifndef ATA_CAM
     case ATA_LF_LOCK:
 	if (ctlr->locked_bank =3D=3D -1)
 	    ctlr->locked_bank =3D ch->unit;
@@ -368,6 +371,7 @@
 	    }
 	}
 	break;
+#endif
=20
     case ATA_LF_WHICH:
 	break;
@@ -385,9 +389,11 @@
     DEVMETHOD(device_suspend,   ata_cbuschannel_suspend),
     DEVMETHOD(device_resume,    ata_cbuschannel_resume),
=20
+#ifndef ATA_CAM
     /* ATA methods */
     DEVMETHOD(ata_locking,      ata_cbuschannel_banking),
-    { 0, 0 }
+#endif
+    DEVMETHOD_END
 };
=20
 static driver_t ata_cbuschannel_driver =3D {
@@ -396,5 +402,5 @@
     sizeof(struct ata_channel),
 };
=20
-DRIVER_MODULE(ata, atacbus, ata_cbuschannel_driver, ata_devclass, 0, 0);
+DRIVER_MODULE(ata, atacbus, ata_cbuschannel_driver, ata_devclass, NULL, NU=
LL);
 MODULE_DEPEND(ata, ata, 1, 1, 1);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-disk.c
--- a/head/sys/dev/ata/ata-disk.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-disk.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/ata-disk.c 230132 2012-01-15 13:23:18=
Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/ata-disk.c 233282 2012-03-21 16:59:39=
Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -591,7 +591,7 @@
     /* ATA methods */
     DEVMETHOD(ata_reinit,       ad_reinit),
=20
-    { 0, 0 }
+    DEVMETHOD_END
 };
=20
 static driver_t ad_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-pci.c
--- a/head/sys/dev/ata/ata-pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/ata-pci.c 230132 2012-01-15 13:23:18Z=
 uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/ata-pci.c 233282 2012-03-21 16:59:39Z=
 marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -595,7 +595,7 @@
     DEVMETHOD(bus_print_child,		ata_pci_print_child),
     DEVMETHOD(bus_child_location_str,	ata_pci_child_location_str),
=20
-    { 0, 0 }
+    DEVMETHOD_END
 };
=20
 devclass_t ata_pci_devclass;
@@ -606,7 +606,7 @@
     sizeof(struct ata_pci_controller),
 };
=20
-DRIVER_MODULE(atapci, pci, ata_pci_driver, ata_pci_devclass, 0, 0);
+DRIVER_MODULE(atapci, pci, ata_pci_driver, ata_pci_devclass, NULL, NULL);
 MODULE_VERSION(atapci, 1);
 MODULE_DEPEND(atapci, ata, 1, 1, 1);
=20
@@ -699,6 +699,7 @@
 }
=20
=20
+#ifndef ATA_CAM
 static int
 ata_pcichannel_locking(device_t dev, int mode)
 {
@@ -710,6 +711,7 @@
     else
 	return ch->unit;
 }
+#endif
=20
 static void
 ata_pcichannel_reset(device_t dev)
@@ -766,10 +768,12 @@
     /* ATA methods */
     DEVMETHOD(ata_setmode,      ata_pcichannel_setmode),
     DEVMETHOD(ata_getrev,       ata_pcichannel_getrev),
+#ifndef ATA_CAM
     DEVMETHOD(ata_locking,      ata_pcichannel_locking),
+#endif
     DEVMETHOD(ata_reset,        ata_pcichannel_reset),
=20
-    { 0, 0 }
+    DEVMETHOD_END
 };
=20
 driver_t ata_pcichannel_driver =3D {
@@ -778,7 +782,7 @@
     sizeof(struct ata_channel),
 };
=20
-DRIVER_MODULE(ata, atapci, ata_pcichannel_driver, ata_devclass, 0, 0);
+DRIVER_MODULE(ata, atapci, ata_pcichannel_driver, ata_devclass, NULL, NULL=
);
=20
 /*
  * misc support fucntions
@@ -859,8 +863,8 @@
     device_set_desc_copy(dev, buffer);
 }
=20
-struct ata_chip_id *
-ata_match_chip(device_t dev, struct ata_chip_id *index)
+const struct ata_chip_id *
+ata_match_chip(device_t dev, const struct ata_chip_id *index)
 {
     uint32_t devid;
     uint8_t revid;
@@ -875,10 +879,10 @@
     return (NULL);
 }
=20
-struct ata_chip_id *
-ata_find_chip(device_t dev, struct ata_chip_id *index, int slot)
+const struct ata_chip_id *
+ata_find_chip(device_t dev, const struct ata_chip_id *index, int slot)
 {
-    struct ata_chip_id *idx;
+    const struct ata_chip_id *idx;
     device_t *children;
     int nchildren, i;
     uint8_t s;
@@ -900,7 +904,7 @@
     return (NULL);
 }
=20
-char *
+const char *
 ata_pcivendor2str(device_t dev)
 {
     switch (pci_get_vendor(dev)) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-pci.h
--- a/head/sys/dev/ata/ata-pci.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-pci.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/ata/ata-pci.h 232380 2012-03-02 08:49:07Z mav $
+ * $FreeBSD: head/sys/dev/ata/ata-pci.h 233282 2012-03-21 16:59:39Z marius=
 $
  */
=20
 /* structure holding chipset config info */
@@ -33,7 +33,7 @@
     int                 cfg1;
     int                 cfg2;
     u_int8_t            max_dma;
-    char                *text;
+    const char          *text;
 };
=20
 #define ATA_PCI_MAX_CH	8
@@ -50,7 +50,7 @@
     int                 r_irq_rid;
     struct resource     *r_irq;
     void                *handle;
-    struct ata_chip_id  *chip;
+    const struct ata_chip_id *chip;
     int			legacy;
     int                 channels;
     int			ichannels;
@@ -62,7 +62,9 @@
     int                 (*ch_detach)(device_t);
     int                 (*ch_suspend)(device_t);
     int                 (*ch_resume)(device_t);
+#ifndef ATA_CAM
     int                 (*locking)(device_t, int);
+#endif
     void                (*reset)(device_t);
     int                 (*setmode)(device_t, int, int);
     int                 (*getrev)(device_t, int);
@@ -568,15 +570,15 @@
 void ata_pci_hw(device_t dev);
 void ata_pci_dmainit(device_t dev);
 void ata_pci_dmafini(device_t dev);
-char *ata_pcivendor2str(device_t dev);
+const char *ata_pcivendor2str(device_t dev);
 int ata_legacy(device_t);
 void ata_generic_intr(void *data);
 int ata_generic_chipinit(device_t dev);
 int ata_generic_setmode(device_t dev, int target, int mode);
 int ata_setup_interrupt(device_t dev, void *intr_func);
 void ata_set_desc(device_t dev);
-struct ata_chip_id *ata_match_chip(device_t dev, struct ata_chip_id *index=
);
-struct ata_chip_id *ata_find_chip(device_t dev, struct ata_chip_id *index,=
 int slot);
+const struct ata_chip_id *ata_match_chip(device_t dev, const struct ata_ch=
ip_id *index);
+const struct ata_chip_id *ata_find_chip(device_t dev, const struct ata_chi=
p_id *index, int slot);
 int ata_mode2idx(int mode);
=20
 /* global prototypes from chipsets/ata-*.c */
@@ -610,15 +612,14 @@
     DEVMETHOD(pci_write_config,		ata_pci_write_config), \
     DEVMETHOD(bus_print_child,		ata_pci_print_child), \
     DEVMETHOD(bus_child_location_str,	ata_pci_child_location_str), \
-    { 0, 0 } \
+    DEVMETHOD_END \
 }; \
 static driver_t __CONCAT(dname,_driver) =3D { \
         "atapci", \
         __CONCAT(dname,_methods), \
         sizeof(struct ata_pci_controller) \
 }; \
-DRIVER_MODULE(dname, pci, __CONCAT(dname,_driver), ata_pci_devclass, 0, 0)=
; \
+DRIVER_MODULE(dname, pci, __CONCAT(dname,_driver), ata_pci_devclass, NULL,=
 NULL); \
 MODULE_VERSION(dname, 1); \
 MODULE_DEPEND(dname, ata, 1, 1, 1); \
 MODULE_DEPEND(dname, atapci, 1, 1, 1);
-
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-queue.c
--- a/head/sys/dev/ata/ata-queue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-queue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/ata-queue.c 231573 2012-02-13 01:44:1=
2Z emaste $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/ata-queue.c 233282 2012-03-21 16:59:3=
9Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -43,11 +43,14 @@
 #include <dev/ata/ata-all.h>
 #include <ata_if.h>
=20
+#ifndef ATA_CAM
 /* prototypes */
 static void ata_completed(void *, int);
 static void ata_sort_queue(struct ata_channel *ch, struct ata_request *req=
uest);
-static char *ata_skey2str(u_int8_t);
+static const char *ata_skey2str(u_int8_t);
+#endif
=20
+#ifndef ATA_CAM
 void
 ata_queue_request(struct ata_request *request)
 {
@@ -123,7 +126,9 @@
 	sema_destroy(&request->done);
     }
 }
+#endif
=20
+#ifndef ATA_CAM
 int
 ata_controlcmd(device_t dev, u_int8_t command, u_int16_t feature,
 	       u_int64_t lba, u_int16_t count)
@@ -153,7 +158,9 @@
     }
     return error;
 }
+#endif
=20
+#ifndef ATA_CAM
 int
 ata_atapicmd(device_t dev, u_int8_t *ccb, caddr_t data,
 	     int count, int flags, int timeout)
@@ -176,7 +183,9 @@
     }
     return error;
 }
+#endif
=20
+#ifndef ATA_CAM
 void
 ata_start(device_t dev)
 {
@@ -235,7 +244,9 @@
 	}
     }
 }
+#endif
=20
+#ifndef ATA_CAM
 void
 ata_finish(struct ata_request *request)
 {
@@ -263,7 +274,9 @@
 	}
     }
 }
+#endif
=20
+#ifndef ATA_CAM
 static void
 ata_completed(void *context, int dummy)
 {
@@ -495,6 +508,7 @@
     if (ch)
 	ata_start(ch->dev);
 }
+#endif
=20
 void
 ata_timeout(struct ata_request *request)
@@ -520,8 +534,8 @@
 	ata_cam_end_transaction(ch->dev, request);
 #endif
 	mtx_unlock(&ch->state_mtx);
+#ifndef ATA_CAM
 	ATA_LOCKING(ch->dev, ATA_LF_UNLOCK);
-#ifndef ATA_CAM
 	ata_finish(request);
 #endif
     }
@@ -530,6 +544,7 @@
     }
 }
=20
+#ifndef ATA_CAM
 void
 ata_fail_requests(device_t dev)
 {
@@ -568,7 +583,9 @@
         ata_finish(request);
     }
 }
+#endif
=20
+#ifndef ATA_CAM
 /*
  * Rudely drop all requests queued to the channel of specified device.
  * XXX: The requests are leaked, use only in fatal case.
@@ -586,7 +603,9 @@
     }
     mtx_unlock(&ch->queue_mtx);
 }
+#endif
=20
+#ifndef ATA_CAM
 static u_int64_t
 ata_get_lba(struct ata_request *request)
 {
@@ -608,7 +627,9 @@
     else
 	return request->u.ata.lba;
 }
+#endif
=20
+#ifndef ATA_CAM
 static void
 ata_sort_queue(struct ata_channel *ch, struct ata_request *request)
 {
@@ -661,8 +682,9 @@
 	ch->freezepoint =3D request;
     TAILQ_INSERT_AFTER(&ch->ata_queue, this, request, chain);
 }
+#endif
=20
-char *
+const char *
 ata_cmd2str(struct ata_request *request)
 {
     static char buffer[20];
@@ -776,7 +798,8 @@
     return buffer;
 }
=20
-static char *
+#ifndef ATA_CAM
+static const char *
 ata_skey2str(u_int8_t skey)
 {
     switch (skey) {
@@ -799,3 +822,4 @@
     default: return("UNKNOWN");
     }
 }
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/ata-raid.c
--- a/head/sys/dev/ata/ata-raid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/ata-raid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/ata-raid.c 230132 2012-01-15 13:23:18=
Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/ata-raid.c 233282 2012-03-21 16:59:39=
Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -4546,7 +4546,7 @@
     DEVMETHOD(device_probe,     ata_raid_subdisk_probe),
     DEVMETHOD(device_attach,    ata_raid_subdisk_attach),
     DEVMETHOD(device_detach,    ata_raid_subdisk_detach),
-    { 0, 0 }
+    DEVMETHOD_END
 };
=20
 static driver_t ata_raid_sub_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/atapi-cam.c
--- a/head/sys/dev/ata/atapi-cam.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/atapi-cam.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-cam.c 229997 2012-01-12 00:34:3=
3Z ken $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-cam.c 233282 2012-03-21 16:59:3=
9Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -122,7 +122,7 @@
 	DEVMETHOD(device_attach,        atapi_cam_attach),
 	DEVMETHOD(device_detach,        atapi_cam_detach),
 	DEVMETHOD(ata_reinit,           atapi_cam_reinit),
-	{0, 0}
+	DEVMETHOD_END
 };
=20
 static driver_t atapi_cam_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/atapi-cd.c
--- a/head/sys/dev/ata/atapi-cd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/atapi-cd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-cd.c 230132 2012-01-15 13:23:18=
Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-cd.c 233282 2012-03-21 16:59:39=
Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -1899,7 +1899,7 @@
     /* ATA methods */
     DEVMETHOD(ata_reinit,       acd_reinit),
    =20
-    { 0, 0 }
+    DEVMETHOD_END
 };
    =20
 static driver_t acd_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/atapi-fd.c
--- a/head/sys/dev/ata/atapi-fd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/atapi-fd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-fd.c 230132 2012-01-15 13:23:18=
Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-fd.c 233282 2012-03-21 16:59:39=
Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -423,7 +423,7 @@
     /* ATA methods */
     DEVMETHOD(ata_reinit,       afd_reinit),
    =20
-    { 0, 0 }
+    DEVMETHOD_END
 };
    =20
 static driver_t afd_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/atapi-tape.c
--- a/head/sys/dev/ata/atapi-tape.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/atapi-tape.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-tape.c 230132 2012-01-15 13:23:=
18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/atapi-tape.c 233282 2012-03-21 16:59:=
39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -723,7 +723,7 @@
     /* ATA methods */
     DEVMETHOD(ata_reinit,       ast_reinit),
=20
-    { 0, 0 }
+    DEVMETHOD_END
 };
 	   =20
 static driver_t ast_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-acard.c
--- a/head/sys/dev/ata/chipsets/ata-acard.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-acard.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-acard.c 230132 2012-01-1=
5 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-acard.c 233282 2012-03-2=
1 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -51,26 +51,29 @@
 #include <dev/ata/ata-pci.h>
 #include <ata_if.h>
=20
+#ifndef ATA_CAM
 struct ata_serialize {
     struct mtx  locked_mtx;
     int         locked_ch;
     int         restart_ch;
 };
+#endif
=20
 /* local prototypes */
 static int ata_acard_chipinit(device_t dev);
-static int ata_acard_chipdeinit(device_t dev);
 static int ata_acard_ch_attach(device_t dev);
 static int ata_acard_status(device_t dev);
 static int ata_acard_850_setmode(device_t dev, int target, int mode);
 static int ata_acard_86X_setmode(device_t dev, int target, int mode);
+#ifndef ATA_CAM
+static int ata_acard_chipdeinit(device_t dev);
 static int ata_serialize(device_t dev, int flags);
 static void ata_serialize_init(struct ata_serialize *serial);
+#endif
=20
 /* misc defines */
 #define ATP_OLD		1
=20
-
 /*
  * Acard chipset support functions
  */
@@ -78,7 +81,7 @@
 ata_acard_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_ATP850R, 0, ATP_OLD, 0x00, ATA_UDMA2, "ATP850" },
      { ATA_ATP860A, 0, 0,       0x00, ATA_UDMA4, "ATP860A" },
      { ATA_ATP860R, 0, 0,       0x00, ATA_UDMA4, "ATP860R" },
@@ -94,7 +97,9 @@
=20
     ata_set_desc(dev);
     ctlr->chipinit =3D ata_acard_chipinit;
+#ifndef ATA_CAM
     ctlr->chipdeinit =3D ata_acard_chipdeinit;
+#endif
     return (BUS_PROBE_DEFAULT);
 }
=20
@@ -102,7 +107,9 @@
 ata_acard_chipinit(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
+#ifndef ATA_CAM
     struct ata_serialize *serial;
+#endif
=20
     if (ata_setup_interrupt(dev, ata_generic_intr))
 	return ENXIO;
@@ -111,17 +118,20 @@
     ctlr->ch_detach =3D ata_pci_ch_detach;
     if (ctlr->chip->cfg1 =3D=3D ATP_OLD) {
 	ctlr->setmode =3D ata_acard_850_setmode;
+#ifndef ATA_CAM
 	ctlr->locking =3D ata_serialize;
 	serial =3D malloc(sizeof(struct ata_serialize),
 			      M_ATAPCI, M_WAITOK | M_ZERO);
 	ata_serialize_init(serial);
 	ctlr->chipset_data =3D serial;
+#endif
     }
     else
 	ctlr->setmode =3D ata_acard_86X_setmode;
     return 0;
 }
=20
+#ifndef ATA_CAM
 static int
 ata_acard_chipdeinit(device_t dev)
 {
@@ -136,6 +146,7 @@
 	}
 	return (0);
 }
+#endif
=20
 static int
 ata_acard_ch_attach(device_t dev)
@@ -228,6 +239,7 @@
 	return (mode);
 }
=20
+#ifndef ATA_CAM
 static void
 ata_serialize_init(struct ata_serialize *serial)
 {
@@ -277,5 +289,6 @@
     mtx_unlock(&serial->locked_mtx);
     return res;
 }
+#endif
=20
 ATA_DECLARE_DRIVER(ata_acard);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-acerlabs=
.c
--- a/head/sys/dev/ata/chipsets/ata-acerlabs.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/dev/ata/chipsets/ata-acerlabs.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-acerlabs.c 230627 2012-0=
1-27 21:52:59Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-acerlabs.c 233282 2012-0=
3-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -75,7 +75,7 @@
 ata_ali_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_ALI_5289, 0x00, 2, ALI_SATA, ATA_SA150, "M5289" },
      { ATA_ALI_5288, 0x00, 4, ALI_SATA, ATA_SA300, "M5288" },
      { ATA_ALI_5287, 0x00, 4, ALI_SATA, ATA_SA150, "M5287" },
@@ -304,11 +304,12 @@
 	struct ata_channel *ch =3D device_get_softc(dev);
 	int devno =3D (ch->unit << 1) + target;
 	int piomode;
-	u_int32_t piotimings[] =3D
+	static const uint32_t piotimings[] =3D
 		{ 0x006d0003, 0x00580002, 0x00440001, 0x00330001,
 		  0x00310001, 0x006d0003, 0x00330001, 0x00310001 };
-	u_int8_t udma[] =3D {0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0d};
-	u_int32_t word54;
+	static const uint8_t udma[] =3D {0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x0f,
+	    0x0d};
+	uint32_t word54;
=20
         mode =3D min(mode, ctlr->chip->max_dma);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-adaptec.c
--- a/head/sys/dev/ata/chipsets/ata-adaptec.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-adaptec.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-adaptec.c 230132 2012-01=
-15 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-adaptec.c 233282 2012-03=
-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -55,7 +55,6 @@
 #define MV_60XX		60		//must match ata_marvell.c's definition
 #define MV_7042		72		//must match ata_marvell.c's definition
=20
-
 /*
  * Adaptec chipset support functions
  */
@@ -63,7 +62,7 @@
 ata_adaptec_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_ADAPTEC_1420, 0, 4, MV_60XX, ATA_SA300, "1420SA" },
      { ATA_ADAPTEC_1430, 0, 4, MV_7042, ATA_SA300, "1430SA" },
      { 0, 0, 0, 0, 0, 0}};
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-ahci.c
--- a/head/sys/dev/ata/chipsets/ata-ahci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-ahci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ahci.c 232380 2012-03-02=
 08:49:07Z mav $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ahci.c 233282 2012-03-21=
 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -1056,11 +1056,12 @@
     DEVMETHOD(bus_deactivate_resource,  bus_generic_deactivate_resource),
     DEVMETHOD(bus_setup_intr,           ata_pci_setup_intr),
     DEVMETHOD(bus_teardown_intr,        ata_pci_teardown_intr),
-    { 0, 0 }
+    DEVMETHOD_END
 };
 static driver_t ata_ahci_ata_driver =3D {
         "atapci",
         ata_ahci_ata_methods,
         sizeof(struct ata_pci_controller)
 };
-DRIVER_MODULE(ata_ahci_ata, atapci, ata_ahci_ata_driver, ata_pci_devclass,=
 0, 0);
+DRIVER_MODULE(ata_ahci_ata, atapci, ata_ahci_ata_driver, ata_pci_devclass,
+    NULL, NULL);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-amd.c
--- a/head/sys/dev/ata/chipsets/ata-amd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-amd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-amd.c 230132 2012-01-15 =
13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-amd.c 233282 2012-03-21 =
16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -67,7 +67,7 @@
 ata_amd_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_AMD756,  0x00, 0x00,              0, ATA_UDMA4, "756" },
      { ATA_AMD766,  0x00, AMD_CABLE|AMD_BUG, 0, ATA_UDMA5, "766" },
      { ATA_AMD768,  0x00, AMD_CABLE,         0, ATA_UDMA5, "768" },
@@ -113,8 +113,10 @@
 	struct ata_channel *ch =3D device_get_softc(dev);
         int devno =3D (ch->unit << 1) + target;
 	int piomode;
-	u_int8_t timings[] =3D { 0xa8, 0x65, 0x42, 0x22, 0x20, 0xa8, 0x22, 0x20 };
-	int modes[7] =3D { 0xc2, 0xc1, 0xc0, 0xc4, 0xc5, 0xc6, 0xc7 };
+	static const uint8_t timings[] =3D
+	    { 0xa8, 0x65, 0x42, 0x22, 0x20, 0xa8, 0x22, 0x20 };
+	static const uint8_t modes[] =3D
+	    { 0xc2, 0xc1, 0xc0, 0xc4, 0xc5, 0xc6, 0xc7 };
 	int reg =3D 0x53 - devno;
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-ati.c
--- a/head/sys/dev/ata/chipsets/ata-ati.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-ati.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ati.c 230132 2012-01-15 =
13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ati.c 233282 2012-03-21 =
16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -58,11 +58,12 @@
 static int ata_ati_setmode(device_t dev, int target, int mode);
=20
 /* misc defines */
-#define ATI_PATA	0x01
-#define ATI_SATA	0x02
+#define SII_MEMIO       1	/* must match ata_siliconimage.c's definition */
+#define SII_BUG         0x04	/* must match ata_siliconimage.c's definition=
 */
+
+#define ATI_SATA	SII_MEMIO
+#define ATI_PATA	0x02
 #define ATI_AHCI	0x04
-#define SII_MEMIO       1
-#define SII_BUG         0x04
=20
 static int force_ahci =3D 1;
 TUNABLE_INT("hw.ahci.force", &force_ahci);
@@ -74,13 +75,13 @@
 ata_ati_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_ATI_IXP200,    0x00, ATI_PATA, 0, ATA_UDMA5, "IXP200" },
      { ATA_ATI_IXP300,    0x00, ATI_PATA, 0, ATA_UDMA6, "IXP300" },
-     { ATA_ATI_IXP300_S1, 0x00, ATI_SATA, 0, ATA_SA150, "IXP300" },
+     { ATA_ATI_IXP300_S1, 0x00, ATI_SATA, SII_BUG, ATA_SA150, "IXP300" },
      { ATA_ATI_IXP400,    0x00, ATI_PATA, 0, ATA_UDMA6, "IXP400" },
-     { ATA_ATI_IXP400_S1, 0x00, ATI_SATA, 0, ATA_SA150, "IXP400" },
-     { ATA_ATI_IXP400_S2, 0x00, ATI_SATA, 0, ATA_SA150, "IXP400" },
+     { ATA_ATI_IXP400_S1, 0x00, ATI_SATA, SII_BUG, ATA_SA150, "IXP400" },
+     { ATA_ATI_IXP400_S2, 0x00, ATI_SATA, SII_BUG, ATA_SA150, "IXP400" },
      { ATA_ATI_IXP600,    0x00, ATI_PATA, 0, ATA_UDMA6, "IXP600" },
      { ATA_ATI_IXP600_S1, 0x00, ATI_AHCI, 0, ATA_SA300, "IXP600" },
      { ATA_ATI_IXP700,    0x00, ATI_PATA, 0, ATA_UDMA6, "IXP700/800" },
@@ -107,10 +108,7 @@
     case ATI_SATA:
 	/*
 	 * the ATI SATA controller is actually a SiI 3112 controller
-	 * cfg values below much match those in ata-siliconimage.c
 	 */
-	ctlr->chip->cfg1 =3D SII_MEMIO;
-	ctlr->chip->cfg2 =3D SII_BUG;
 	ctlr->chipinit =3D ata_sii_chipinit;
 	break;
     case ATI_AHCI:
@@ -212,8 +210,8 @@
 	int devno =3D (ch->unit << 1) + target;
 	int offset =3D (devno ^ 0x01) << 3;
 	int piomode;
-	u_int8_t piotimings[] =3D { 0x5d, 0x47, 0x34, 0x22, 0x20 };
-	u_int8_t dmatimings[] =3D { 0x77, 0x21, 0x20 };
+	static const uint8_t piotimings[] =3D { 0x5d, 0x47, 0x34, 0x22, 0x20 };
+	static const uint8_t dmatimings[] =3D { 0x77, 0x21, 0x20 };
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
 	if (mode >=3D ATA_UDMA0) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-cyrix.c
--- a/head/sys/dev/ata/chipsets/ata-cyrix.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-cyrix.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-cyrix.c 230132 2012-01-1=
5 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-cyrix.c 233282 2012-03-2=
1 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -101,10 +101,12 @@
 	struct ata_channel *ch =3D device_get_softc(dev);
 	int devno =3D (ch->unit << 1) + target;
 	int piomode;
-	u_int32_t piotiming[] =3D=20
+	static const uint32_t piotiming[] =3D=20
 	    { 0x00009172, 0x00012171, 0x00020080, 0x00032010, 0x00040010 };
-	u_int32_t dmatiming[] =3D { 0x00077771, 0x00012121, 0x00002020 };
-	u_int32_t udmatiming[] =3D { 0x00921250, 0x00911140, 0x00911030 };
+	static const uint32_t dmatiming[] =3D
+	    { 0x00077771, 0x00012121, 0x00002020 };
+	static const uint32_t udmatiming[] =3D
+	    { 0x00921250, 0x00911140, 0x00911030 };
=20
 	mode =3D min(mode, ATA_UDMA2);
 	/* dont try to set the mode if we dont have the resource */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-highpoin=
t.c
--- a/head/sys/dev/ata/chipsets/ata-highpoint.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/sys/dev/ata/chipsets/ata-highpoint.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-highpoint.c 230132 2012-=
01-15 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-highpoint.c 233282 2012-=
03-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -72,8 +72,8 @@
 ata_highpoint_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    struct ata_chip_id *idx;
-    static struct ata_chip_id ids[] =3D
+    const struct ata_chip_id *idx;
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_HPT374, 0x07, HPT_374, 0,       ATA_UDMA6, "HPT374" },
      { ATA_HPT372, 0x02, HPT_372, 0,       ATA_UDMA6, "HPT372N" },
      { ATA_HPT372, 0x01, HPT_372, 0,       ATA_UDMA6, "HPT372" },
@@ -163,8 +163,8 @@
 	struct ata_pci_controller *ctlr =3D device_get_softc(parent);
 	struct ata_channel *ch =3D device_get_softc(dev);
 	int devno =3D (ch->unit << 1) + target;
-	u_int32_t timings33[][4] =3D {
-    /*    HPT366      HPT370      HPT372      HPT374               mode */
+	static const uint32_t timings33[][4] =3D {
+	/*    HPT366      HPT370      HPT372      HPT374           mode */
 	{ 0x40d0a7aa, 0x06914e57, 0x0d029d5e, 0x0ac1f48a },     /* PIO 0 */
 	{ 0x40d0a7a3, 0x06914e43, 0x0d029d26, 0x0ac1f465 },     /* PIO 1 */
 	{ 0x40d0a753, 0x06514e33, 0x0c829ca6, 0x0a81f454 },     /* PIO 2 */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-intel.c
--- a/head/sys/dev/ata/chipsets/ata-intel.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-intel.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-intel.c 230132 2012-01-1=
5 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-intel.c 233282 2012-03-2=
1 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -105,7 +105,7 @@
 ata_intel_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_I82371FB,     0,          0, 2, ATA_WDMA2, "PIIX" },
      { ATA_I82371SB,     0,          0, 2, ATA_WDMA2, "PIIX3" },
      { ATA_I82371AB,     0,          0, 2, ATA_UDMA2, "PIIX4" },
@@ -519,8 +519,10 @@
 	u_int16_t reg54 =3D pci_read_config(parent, 0x54, 2);
 	u_int32_t mask40 =3D 0, new40 =3D 0;
 	u_int8_t mask44 =3D 0, new44 =3D 0;
-	u_int8_t timings[] =3D { 0x00, 0x00, 0x10, 0x21, 0x23, 0x00, 0x21, 0x23 };
-	u_int8_t utimings[] =3D { 0x00, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02 };
+	static const uint8_t timings[] =3D
+	    { 0x00, 0x00, 0x10, 0x21, 0x23, 0x00, 0x21, 0x23 };
+	static const uint8_t utimings[] =3D
+	    { 0x00, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02 };
=20
 	/* In combined mode, skip PATA stuff for SATA channel. */
 	if (ch->flags & ATA_SATA)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-ite.c
--- a/head/sys/dev/ata/chipsets/ata-ite.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-ite.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ite.c 230132 2012-01-15 =
13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ite.c 233282 2012-03-21 =
16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -57,7 +57,6 @@
 static int ata_ite_821x_setmode(device_t dev, int target, int mode);
 static int ata_ite_8213_setmode(device_t dev, int target, int mode);
=20
-
 /*
  * Integrated Technology Express Inc. (ITE) chipset support functions
  */
@@ -65,7 +64,7 @@
 ata_ite_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_IT8213F, 0x00, 0x00, 0x00, ATA_UDMA6, "IT8213F" },
      { ATA_IT8212F, 0x00, 0x00, 0x00, ATA_UDMA6, "IT8212F" },
      { ATA_IT8211F, 0x00, 0x00, 0x00, ATA_UDMA6, "IT8211F" },
@@ -132,9 +131,9 @@
 	int devno =3D (ch->unit << 1) + target;
 	int piomode;
 	uint8_t *timings =3D (uint8_t*)(&ctlr->chipset_data);
-	u_int8_t udmatiming[] =3D
+	static const uint8_t udmatiming[] =3D
 		{ 0x44, 0x42, 0x31, 0x21, 0x11, 0xa2, 0x91 };
-	u_int8_t chtiming[] =3D
+	static const uint8_t chtiming[] =3D
 		{ 0xaa, 0xa3, 0xa1, 0x33, 0x31, 0x88, 0x32, 0x31 };
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
@@ -182,8 +181,10 @@
 	u_int16_t reg54 =3D pci_read_config(parent, 0x54, 2);
 	u_int16_t mask40 =3D 0, new40 =3D 0;
 	u_int8_t mask44 =3D 0, new44 =3D 0;
-	u_int8_t timings[] =3D { 0x00, 0x00, 0x10, 0x21, 0x23, 0x00, 0x21, 0x23 };
-	u_int8_t utimings[] =3D { 0x00, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02 };
+	static const uint8_t timings[] =3D
+	    { 0x00, 0x00, 0x10, 0x21, 0x23, 0x00, 0x21, 0x23 };
+	static const uint8_t utimings[] =3D
+	    { 0x00, 0x01, 0x02, 0x01, 0x02, 0x01, 0x02 };
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-jmicron.c
--- a/head/sys/dev/ata/chipsets/ata-jmicron.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-jmicron.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-jmicron.c 230132 2012-01=
-15 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-jmicron.c 233282 2012-03=
-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -63,8 +63,8 @@
 ata_jmicron_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    struct ata_chip_id *idx;
-    static struct ata_chip_id ids[] =3D
+    const struct ata_chip_id *idx;
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_JMB360, 0, 1, 0, ATA_SA300, "JMB360" },
      { ATA_JMB361, 0, 1, 1, ATA_UDMA6, "JMB361" },
      { ATA_JMB363, 0, 2, 1, ATA_UDMA6, "JMB363" },
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-marvell.c
--- a/head/sys/dev/ata/chipsets/ata-marvell.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-marvell.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-marvell.c 232380 2012-03=
-02 08:49:07Z mav $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-marvell.c 233282 2012-03=
-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -99,7 +99,7 @@
 ata_marvell_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_M88SX5040, 0, 4, MV_50XX, ATA_SA150, "88SX5040" },
      { ATA_M88SX5041, 0, 4, MV_50XX, ATA_SA150, "88SX5041" },
      { ATA_M88SX5080, 0, 8, MV_50XX, ATA_SA150, "88SX5080" },
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-national=
.c
--- a/head/sys/dev/ata/chipsets/ata-national.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/dev/ata/chipsets/ata-national.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-national.c 230132 2012-0=
1-15 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-national.c 233282 2012-0=
3-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -103,11 +103,13 @@
 	struct ata_channel *ch =3D device_get_softc(dev);
 	int devno =3D (ch->unit << 1) + target;
 	int piomode;
-	u_int32_t piotiming[] =3D
+	static const uint32_t piotiming[] =3D
 	    { 0x9172d132, 0x21717121, 0x00803020, 0x20102010, 0x00100010,
 	      0x9172d132, 0x20102010, 0x00100010 };
-	u_int32_t dmatiming[] =3D { 0x80077771, 0x80012121, 0x80002020 };
-	u_int32_t udmatiming[] =3D { 0x80921250, 0x80911140, 0x80911030 };
+	static const uint32_t dmatiming[] =3D
+	    { 0x80077771, 0x80012121, 0x80002020 };
+	static const uint32_t udmatiming[] =3D
+	    { 0x80921250, 0x80911140, 0x80911030 };
=20
 	mode =3D min(mode, ATA_UDMA2);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-nvidia.c
--- a/head/sys/dev/ata/chipsets/ata-nvidia.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-nvidia.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-nvidia.c 230132 2012-01-=
15 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-nvidia.c 233282 2012-03-=
21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -75,7 +75,7 @@
 ata_nvidia_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_NFORCE1,         0, 0,       0, ATA_UDMA5, "nForce" },
      { ATA_NFORCE2,         0, 0,       0, ATA_UDMA6, "nForce2" },
      { ATA_NFORCE2_PRO,     0, 0,       0, ATA_UDMA6, "nForce2 Pro" },
@@ -332,8 +332,10 @@
 	struct ata_channel *ch =3D device_get_softc(dev);
 	int devno =3D (ch->unit << 1) + target;
 	int piomode;
-	u_int8_t timings[] =3D { 0xa8, 0x65, 0x42, 0x22, 0x20, 0xa8, 0x22, 0x20 };
-        int modes[7] =3D { 0xc2, 0xc1, 0xc0, 0xc4, 0xc5, 0xc6, 0xc7 };
+	static const uint8_t timings[] =3D
+	    { 0xa8, 0x65, 0x42, 0x22, 0x20, 0xa8, 0x22, 0x20 };
+	static const uint8_t modes[] =3D
+	    { 0xc2, 0xc1, 0xc0, 0xc4, 0xc5, 0xc6, 0xc7 };
 	int reg =3D 0x63 - devno;
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-promise.c
--- a/head/sys/dev/ata/chipsets/ata-promise.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-promise.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-promise.c 230132 2012-01=
-15 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-promise.c 233282 2012-03=
-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -129,8 +129,8 @@
 ata_promise_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    struct ata_chip_id *idx;
-    static struct ata_chip_id ids[] =3D
+    const struct ata_chip_id *idx;
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_PDC20246,  0, PR_OLD, 0x00,     ATA_UDMA2, "PDC20246" },
      { ATA_PDC20262,  0, PR_NEW, 0x00,     ATA_UDMA4, "PDC20262" },
      { ATA_PDC20263,  0, PR_NEW, 0x00,     ATA_UDMA4, "PDC20263" },
@@ -454,7 +454,7 @@
     struct ata_pci_controller *ctlr =3D device_get_softc(parent);
     struct ata_channel *ch =3D device_get_softc(dev);
     int devno =3D (ch->unit << 1) + target;
-    u_int32_t timings[][2] =3D {
+    static const uint32_t timings[][2] =3D {
     /*    PR_OLD      PR_NEW               mode */
 	{ 0x004ff329, 0x004fff2f },     /* PIO 0 */
 	{ 0x004fec25, 0x004ff82a },     /* PIO 1 */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-serverwo=
rks.c
--- a/head/sys/dev/ata/chipsets/ata-serverworks.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sys/dev/ata/chipsets/ata-serverworks.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-serverworks.c 230132 201=
2-01-15 13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-serverworks.c 233282 201=
2-03-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -75,7 +75,7 @@
 ata_serverworks_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_ROSB4,     0x00, SWKS_33,  0, ATA_WDMA2, "ROSB4" },
      { ATA_CSB5,      0x92, SWKS_100, 0, ATA_UDMA5, "CSB5" },
      { ATA_CSB5,      0x00, SWKS_66,  0, ATA_UDMA4, "CSB5" },
@@ -350,8 +350,8 @@
         int devno =3D (ch->unit << 1) + target;
         int offset =3D (devno ^ 0x01) << 3;
 	int piomode;
-	u_int8_t piotimings[] =3D { 0x5d, 0x47, 0x34, 0x22, 0x20 };
-	u_int8_t dmatimings[] =3D { 0x77, 0x21, 0x20 };
+	static const uint8_t piotimings[] =3D { 0x5d, 0x47, 0x34, 0x22, 0x20 };
+	static const uint8_t dmatimings[] =3D { 0x77, 0x21, 0x20 };
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
 	if (mode >=3D ATA_UDMA0) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-siliconi=
mage.c
--- a/head/sys/dev/ata/chipsets/ata-siliconimage.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/sys/dev/ata/chipsets/ata-siliconimage.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-siliconimage.c 230627 20=
12-01-27 21:52:59Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-siliconimage.c 233282 20=
12-03-21 16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -87,7 +87,7 @@
 ata_sii_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_SII3114,   0x00, SII_MEMIO, SII_4CH,    ATA_SA150, "3114" },
      { ATA_SII3512,   0x02, SII_MEMIO, 0,          ATA_SA150, "3512" },
      { ATA_SII3112,   0x02, SII_MEMIO, 0,          ATA_SA150, "3112" },
@@ -272,10 +272,11 @@
 	int treg =3D 0x54 + ((devno < 3) ? (devno << 1) : 7);
 	int ureg =3D ch->unit ? 0x7b : 0x73;
 	int piomode;
-	uint8_t piotimings[] =3D { 0xa9, 0x57, 0x44, 0x32, 0x3f, 0x87, 0x32, 0x3f=
 };
-	uint8_t udmatimings[][2] =3D { { 0x31,  0xc2 }, { 0x21,  0x82 },
-				     { 0x11,  0x42 }, { 0x25,  0x8a },
-				     { 0x15,  0x4a }, { 0x05,  0x0a } };
+	static const uint8_t piotimings[] =3D
+	    { 0xa9, 0x57, 0x44, 0x32, 0x3f, 0x87, 0x32, 0x3f };
+	static const uint8_t udmatimings[][2] =3D
+	    { { 0x31,  0xc2 }, { 0x21,  0x82 }, { 0x11,  0x42 },
+	      { 0x25,  0x8a }, { 0x15,  0x4a }, { 0x05,  0x0a } };
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
 	if (mode >=3D ATA_UDMA0) {       =20
@@ -410,9 +411,11 @@
 	u_int8_t preg =3D 0xa4 + rego;
 	u_int8_t dreg =3D 0xa8 + rego;
 	u_int8_t ureg =3D 0xac + rego;
-	u_int16_t piotimings[] =3D { 0x328a, 0x2283, 0x1104, 0x10c3, 0x10c1 };
-	u_int16_t dmatimings[] =3D { 0x2208, 0x10c2, 0x10c1 };
-	u_int8_t udmatimings[] =3D { 0xf, 0xb, 0x7, 0x5, 0x3, 0x2, 0x1 };
+	static const uint16_t piotimings[] =3D
+	    { 0x328a, 0x2283, 0x1104, 0x10c3, 0x10c1 };
+	static const uint16_t dmatimings[] =3D { 0x2208, 0x10c2, 0x10c1 };
+	static const uint8_t udmatimings[] =3D
+	    { 0xf, 0xb, 0x7, 0x5, 0x3, 0x2, 0x1 };
=20
 	mode =3D min(mode, ctlr->chip->max_dma);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-sis.c
--- a/head/sys/dev/ata/chipsets/ata-sis.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-sis.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-sis.c 230132 2012-01-15 =
13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-sis.c 233282 2012-03-21 =
16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -66,7 +66,6 @@
 #define SIS_133OLD	6
 #define SIS_SATA	7
=20
-
 /*
  * Silicon Integrated Systems Corp. (SiS) chipset support functions
  */
@@ -74,8 +73,8 @@
 ata_sis_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    struct ata_chip_id *idx;
-    static struct ata_chip_id ids[] =3D
+    const struct ata_chip_id *idx;
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_SIS182,  0x00, SIS_SATA,   0, ATA_SA150, "182" }, /* south */
      { ATA_SIS181,  0x00, SIS_SATA,   0, ATA_SA150, "181" }, /* south */
      { ATA_SIS180,  0x00, SIS_SATA,   0, ATA_SA150, "180" }, /* south */
@@ -102,6 +101,8 @@
      { ATA_SIS5513, 0xc2, SIS_33,     1, ATA_UDMA2, "5513" },
      { ATA_SIS5513, 0x00, SIS_33,     1, ATA_WDMA2, "5513" },
      { 0, 0, 0, 0, 0, 0 }};
+    static struct ata_chip_id id[] =3D
+    {{ ATA_SISSOUTH, 0x10, 0, 0, 0, "" }, { 0, 0, 0, 0, 0, 0 }};
     char buffer[64];
     int found =3D 0;
=20
@@ -114,14 +115,15 @@
     if (!(idx =3D ata_find_chip(dev, ids, -pci_get_slot(dev))))=20
 	return ENXIO;
=20
-    if (idx->cfg2 && !found) {
+    if (idx->cfg2) {
 	u_int8_t reg57 =3D pci_read_config(dev, 0x57, 1);
=20
 	pci_write_config(dev, 0x57, (reg57 & 0x7f), 1);
 	if (pci_read_config(dev, PCIR_DEVVENDOR, 4) =3D=3D ATA_SIS5518) {
 	    found =3D 1;
-	    idx->cfg1 =3D SIS_133NEW;
-	    idx->max_dma =3D ATA_UDMA6;
+    	    memcpy(&id[0], idx, sizeof(id[0]));
+	    id[0].cfg1 =3D SIS_133NEW;
+	    id[0].max_dma =3D ATA_UDMA6;
 	    sprintf(buffer, "SiS 962/963 %s controller",
 		    ata_mode2str(idx->max_dma));
 	}
@@ -132,17 +134,13 @@
=20
 	pci_write_config(dev, 0x4a, (reg4a | 0x10), 1);
 	if (pci_read_config(dev, PCIR_DEVVENDOR, 4) =3D=3D ATA_SIS5517) {
-	    struct ata_chip_id id[] =3D
-		{{ ATA_SISSOUTH, 0x10, 0, 0, 0, "" }, { 0, 0, 0, 0, 0, 0 }};
-
 	    found =3D 1;
 	    if (ata_find_chip(dev, id, pci_get_slot(dev))) {
-		idx->cfg1 =3D SIS_133OLD;
-		idx->max_dma =3D ATA_UDMA6;
-	    }
-	    else {
-		idx->cfg1 =3D SIS_100NEW;
-		idx->max_dma =3D ATA_UDMA5;
+		id[0].cfg1 =3D SIS_133OLD;
+		id[0].max_dma =3D ATA_UDMA6;
+	    } else {
+		id[0].cfg1 =3D SIS_100NEW;
+		id[0].max_dma =3D ATA_UDMA5;
 	    }
 	    sprintf(buffer, "SiS 961 %s controller",ata_mode2str(idx->max_dma));
 	}
@@ -151,6 +149,8 @@
     if (!found)
 	sprintf(buffer,"SiS %s %s controller",
 		idx->text, ata_mode2str(idx->max_dma));
+    else
+	idx =3D &id[0];
=20
     device_set_desc_copy(dev, buffer);
     ctlr->chip =3D idx;
@@ -262,7 +262,7 @@
=20
 	switch (ctlr->chip->cfg1) {
 	case SIS_133NEW: {
-	    u_int32_t timings[] =3D=20
+	    static const uint32_t timings[] =3D=20
 		{ 0x28269008, 0x0c266008, 0x04263008, 0x0c0a3008, 0x05093008,
 		  0x22196008, 0x0c0a3008, 0x05093008, 0x050939fc, 0x050936ac,
 		  0x0509347c, 0x0509325c, 0x0509323c, 0x0509322c, 0x0509321c};
@@ -273,7 +273,7 @@
 	    break;
 	    }
 	case SIS_133OLD: {
-	    u_int16_t timings[] =3D
+	    static const uint16_t timings[] =3D
 	     { 0x00cb, 0x0067, 0x0044, 0x0033, 0x0031, 0x0044, 0x0033, 0x0031,
 	       0x8f31, 0x8a31, 0x8731, 0x8531, 0x8331, 0x8231, 0x8131 };
 		 =20
@@ -283,7 +283,7 @@
 	    break;
 	    }
 	case SIS_100NEW: {
-	    u_int16_t timings[] =3D
+	    static const uint16_t timings[] =3D
 		{ 0x00cb, 0x0067, 0x0044, 0x0033, 0x0031, 0x0044, 0x0033,
 		  0x0031, 0x8b31, 0x8731, 0x8531, 0x8431, 0x8231, 0x8131 };
 	    u_int16_t reg =3D 0x40 + (devno << 1);
@@ -294,7 +294,7 @@
 	case SIS_100OLD:
 	case SIS_66:
 	case SIS_33: {
-	    u_int16_t timings[] =3D
+	    static const uint16_t timings[] =3D
 		{ 0x0c0b, 0x0607, 0x0404, 0x0303, 0x0301, 0x0404, 0x0303,
 		  0x0301, 0xf301, 0xd301, 0xb301, 0xa301, 0x9301, 0x8301 };
 	    u_int16_t reg =3D 0x40 + (devno << 1);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ata/chipsets/ata-via.c
--- a/head/sys/dev/ata/chipsets/ata-via.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ata/chipsets/ata-via.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-via.c 230132 2012-01-15 =
13:23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-via.c 233282 2012-03-21 =
16:59:39Z marius $");
=20
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -82,7 +82,6 @@
 #define VIAAHCI         0x08
 #define VIASATA         0x10
=20
-
 /*
  * VIA Technologies Inc. chipset support functions
  */
@@ -90,7 +89,7 @@
 ata_via_probe(device_t dev)
 {
     struct ata_pci_controller *ctlr =3D device_get_softc(dev);
-    static struct ata_chip_id ids[] =3D
+    static const struct ata_chip_id const ids[] =3D
     {{ ATA_VIA82C586, 0x02, VIA33,  0x00,    ATA_UDMA2, "82C586B" },
      { ATA_VIA82C586, 0x00, VIA33,  0x00,    ATA_WDMA2, "82C586" },
      { ATA_VIA82C596, 0x12, VIA66,  VIACLK,  ATA_UDMA4, "82C596B" },
@@ -114,7 +113,7 @@
      { ATA_VIAVX855,  0x00, VIA133, 0x00,    ATA_UDMA6, "VX855" },
      { ATA_VIAVX900,  0x00, VIA133, VIASATA, ATA_SA300, "VX900" },
      { 0, 0, 0, 0, 0, 0 }};
-    static struct ata_chip_id new_ids[] =3D
+    static const struct ata_chip_id const new_ids[] =3D
     {{ ATA_VIA6410,   0x00, 0,      0x00,    ATA_UDMA6, "6410" },
      { ATA_VIA6420,   0x00, 7,      0x00,    ATA_SA150, "6420" },
      { ATA_VIA6421,   0x00, 6,      VIABAR,  ATA_SA150, "6421" },
@@ -328,8 +327,10 @@
=20
 	if ((ctlr->chip->cfg2 & VIABAR) && (ch->unit > 1)) {
 	    int piomode;
-    	    u_int8_t pio_timings[] =3D { 0xa8, 0x65, 0x65, 0x32, 0x20 };
-	    u_int8_t dma_timings[] =3D { 0xee, 0xe8, 0xe6, 0xe4, 0xe2, 0xe1, 0xe0=
 };
+    	    static const uint8_t pio_timings[] =3D
+		{ 0xa8, 0x65, 0x65, 0x32, 0x20 };
+	    static const uint8_t dma_timings[] =3D
+		{ 0xee, 0xe8, 0xe6, 0xe4, 0xe2, 0xe1, 0xe0 };
=20
 	    /* This chip can't do WDMA. */
 	    if (mode >=3D ATA_WDMA0 && mode < ATA_UDMA0)
@@ -355,8 +356,9 @@
 	int devno =3D (ch->unit << 1) + target;
 	int reg =3D 0x53 - devno;
 	int piomode;
-	uint8_t timings[] =3D { 0xa8, 0x65, 0x42, 0x22, 0x20, 0xa8, 0x22, 0x20 };
-	uint8_t modes[][7] =3D {
+	static const uint8_t timings[] =3D
+	    { 0xa8, 0x65, 0x42, 0x22, 0x20, 0xa8, 0x22, 0x20 };
+	static const uint8_t modes[][7] =3D {
 	    { 0xc2, 0xc1, 0xc0, 0x00, 0x00, 0x00, 0x00 },   /* VIA ATA33 */
 	    { 0xee, 0xec, 0xea, 0xe9, 0xe8, 0x00, 0x00 },   /* VIA ATA66 */
 	    { 0xf7, 0xf6, 0xf4, 0xf2, 0xf1, 0xf0, 0x00 },   /* VIA ATA100 */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ah_osdep.c
--- a/head/sys/dev/ath/ah_osdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/ah_osdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: head/sys/dev/ath/ah_osdep.c 227410 2011-11-09 22:39:44Z adria=
n $
+ * $FreeBSD: head/sys/dev/ath/ah_osdep.c 233887 2012-04-04 20:46:20Z adria=
n $
  */
 #include "opt_ah.h"
=20
@@ -38,6 +38,7 @@
 #include <sys/bus.h>
 #include <sys/malloc.h>
 #include <sys/proc.h>
+#include <sys/pcpu.h>
 #include <sys/lock.h>
 #include <sys/mutex.h>
=20
@@ -257,6 +258,7 @@
 		struct ale *ale =3D ath_hal_alq_get(ah);
 		if (ale) {
 			struct athregrec *r =3D (struct athregrec *) ale->ae_data;
+			r->threadid =3D curthread->td_tid;
 			r->op =3D OP_WRITE;
 			r->reg =3D reg;
 			r->val =3D val;
@@ -296,6 +298,7 @@
 		struct ale *ale =3D ath_hal_alq_get(ah);
 		if (ale) {
 			struct athregrec *r =3D (struct athregrec *) ale->ae_data;
+			r->threadid =3D curthread->td_tid;
 			r->op =3D OP_READ;
 			r->reg =3D reg;
 			r->val =3D val;
@@ -312,6 +315,7 @@
 		struct ale *ale =3D ath_hal_alq_get(ah);
 		if (ale) {
 			struct athregrec *r =3D (struct athregrec *) ale->ae_data;
+			r->threadid =3D curthread->td_tid;
 			r->op =3D OP_MARK;
 			r->reg =3D id;
 			r->val =3D v;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ah.h
--- a/head/sys/dev/ath/ath_hal/ah.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/ath_hal/ah.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ah.h 231708 2012-02-14 20:05:28Z adr=
ian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ah.h 234088 2012-04-10 07:11:33Z adr=
ian $
  */
=20
 #ifndef _ATH_AH_H_
@@ -815,6 +815,7 @@
 	uint16_t	*ah_eepromdata;	/* eeprom buffer, if needed */
=20
 	uint32_t	ah_intrstate[8];	/* last int state */
+	uint32_t	ah_syncstate;		/* last sync intr state */
=20
 	HAL_OPS_CONFIG ah_config;
 	const HAL_RATE_TABLE *__ahdecl(*ah_getRateTable)(struct ath_hal *,
@@ -1010,7 +1011,7 @@
 	HAL_BOOL  __ahdecl(*ah_chainTxDesc)(struct ath_hal *,
 				struct ath_desc *, u_int, u_int, HAL_PKT_TYPE,
 				u_int, HAL_CIPHER, uint8_t, u_int, HAL_BOOL,
-				HAL_BOOL);
+				HAL_BOOL, HAL_BOOL);
 	HAL_BOOL  __ahdecl(*ah_setupFirstTxDesc)(struct ath_hal *,
 				struct ath_desc *, u_int, u_int, u_int,
 				u_int, u_int, u_int, u_int, u_int);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ah_decode.h
--- a/head/sys/dev/ath/ath_hal/ah_decode.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/ath_hal/ah_decode.h	Tue Apr 17 11:51:51 2012 +0300
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ah_decode.h 220423 2011-04-07 13:14:=
51Z adrian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ah_decode.h 233887 2012-04-04 20:46:=
20Z adrian $
  */
 #ifndef _ATH_AH_DECODE_H_
 #define _ATH_AH_DECODE_H_
@@ -29,6 +29,7 @@
  * existing file.
  */
 struct athregrec {
+	uint32_t	threadid;
 	uint32_t	op	: 8,
 			reg	: 24;
 	uint32_t	val;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ar5416/ar5416=
.h
--- a/head/sys/dev/ath/ath_hal/ar5416/ar5416.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/dev/ath/ath_hal/ar5416/ar5416.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416.h 231927 2012-02-20 03=
:07:07Z adrian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416.h 233895 2012-04-04 21=
:49:49Z adrian $
  */
 #ifndef _ATH_AR5416_H_
 #define _ATH_AR5416_H_
@@ -336,8 +336,8 @@
=20
 extern	HAL_BOOL ar5416ChainTxDesc(struct ath_hal *ah, struct ath_desc *ds,
 		u_int pktLen, u_int hdrLen, HAL_PKT_TYPE type, u_int keyIx,
-		HAL_CIPHER cipher, uint8_t delims, u_int segLen, HAL_BOOL firstSeg,
-		HAL_BOOL lastSeg);
+		HAL_CIPHER cipher, uint8_t delims, u_int segLen,
+		HAL_BOOL firstSeg, HAL_BOOL lastSeg, HAL_BOOL lastAggr);
 extern	HAL_BOOL ar5416SetupFirstTxDesc(struct ath_hal *ah, struct ath_desc=
 *ds,
 		u_int aggrLen, u_int flags, u_int txPower, u_int txRate0, u_int txTries0,
 		u_int antMode, u_int rtsctsRate, u_int rtsctsDuration);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ar5416/ar5416=
_interrupts.c
--- a/head/sys/dev/ath/ath_hal/ar5416/ar5416_interrupts.c	Tue Apr 17 11:36:=
47 2012 +0300
+++ b/head/sys/dev/ath/ath_hal/ar5416/ar5416_interrupts.c	Tue Apr 17 11:51:=
51 2012 +0300
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_interrupts.c 227365 20=
11-11-08 22:50:28Z adrian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_interrupts.c 234088 20=
12-04-10 07:11:33Z adrian $
  */
 #include "opt_ah.h"
=20
@@ -67,7 +67,7 @@
 HAL_BOOL
 ar5416GetPendingInterrupts(struct ath_hal *ah, HAL_INT *masked)
 {
-	uint32_t isr, isr0, isr1, sync_cause =3D 0;
+	uint32_t isr, isr0, isr1, sync_cause =3D 0, o_sync_cause =3D 0;
 	HAL_CAPABILITIES *pCap =3D &AH_PRIVATE(ah)->ah_caps;
=20
 #ifdef	AH_INTERRUPT_DEBUGGING
@@ -75,6 +75,7 @@
 	 * Blank the interrupt debugging area regardless.
 	 */
 	bzero(&ah->ah_intrstate, sizeof(ah->ah_intrstate));
+	ah->ah_syncstate =3D 0;
 #endif
=20
 	/*
@@ -89,7 +90,10 @@
 			isr =3D OS_REG_READ(ah, AR_ISR);
 		else
 			isr =3D 0;
-		sync_cause =3D OS_REG_READ(ah, AR_INTR_SYNC_CAUSE);
+#ifdef	AH_INTERRUPT_DEBUGGING
+		ah->ah_syncstate =3D
+#endif
+		o_sync_cause =3D sync_cause =3D OS_REG_READ(ah, AR_INTR_SYNC_CAUSE);
 		sync_cause &=3D AR_INTR_SYNC_DEFAULT;
 		*masked =3D 0;
=20
@@ -221,6 +225,9 @@
 		return AH_TRUE;
=20
 	if (sync_cause !=3D 0) {
+		HALDEBUG(ah, HAL_DEBUG_INTERRUPT, "%s: sync_cause=3D0x%x\n",
+		    __func__,
+		    o_sync_cause);
 		if (sync_cause & (AR_INTR_SYNC_HOST1_FATAL | AR_INTR_SYNC_HOST1_PERR)) {
 			*masked |=3D HAL_INT_FATAL;
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ar5416/ar5416=
_power.c
--- a/head/sys/dev/ath/ath_hal/ar5416/ar5416_power.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/sys/dev/ath/ath_hal/ar5416/ar5416_power.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_power.c 221800 2011-05=
-12 03:15:21Z adrian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_power.c 234269 2012-04=
-14 04:40:11Z adrian $
  */
 #include "opt_ah.h"
=20
@@ -50,6 +50,7 @@
 			& AR_RTC_PM_STATUS_M) =3D=3D AR_RTC_STATUS_SHUTDOWN) {
 			if (!ar5416SetResetReg(ah, HAL_RESET_POWER_ON))
 				goto bad;		=09
+			AH5416(ah)->ah_initPLL(ah, AH_NULL);
 		}
=20
 		if (AR_SREV_HOWL(ah))
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ar5416/ar5416=
_reset.c
--- a/head/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c	Tue Apr 17 11:51:51 20=
12 +0300
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c 227741 2011-11=
-19 21:12:35Z adrian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_reset.c 233329 2012-03=
-22 21:47:14Z adrian $
  */
 #include "opt_ah.h"
=20
@@ -689,7 +689,8 @@
=20
 	/* Restore user-specified settings */
 	if (ahp->ah_miscMode !=3D 0)
-		OS_REG_WRITE(ah, AR_MISC_MODE, OS_REG_READ(ah, AR_MISC_MODE) | ahp->ah_m=
iscMode);
+		OS_REG_WRITE(ah, AR_MISC_MODE, OS_REG_READ(ah, AR_MISC_MODE)
+		    | ahp->ah_miscMode);
 	if (ahp->ah_sifstime !=3D (u_int) -1)
 		ar5212SetSifsTime(ah, ahp->ah_sifstime);
 	if (ahp->ah_slottime !=3D (u_int) -1)
@@ -1188,7 +1189,8 @@
 HAL_RFGAIN
 ar5416GetRfgain(struct ath_hal *ah)
 {
-	return HAL_RFGAIN_INACTIVE;
+
+	return (HAL_RFGAIN_INACTIVE);
 }
=20
 /*
@@ -1197,13 +1199,14 @@
 HAL_BOOL
 ar5416Disable(struct ath_hal *ah)
 {
+
 	if (!ar5416SetPowerMode(ah, HAL_PM_AWAKE, AH_TRUE))
 		return AH_FALSE;
 	if (! ar5416SetResetReg(ah, HAL_RESET_COLD))
 		return AH_FALSE;
=20
 	AH5416(ah)->ah_initPLL(ah, AH_NULL);
-	return AH_TRUE;
+	return (AH_TRUE);
 }
=20
 /*
@@ -1215,11 +1218,12 @@
 HAL_BOOL
 ar5416PhyDisable(struct ath_hal *ah)
 {
+
 	if (! ar5416SetResetReg(ah, HAL_RESET_WARM))
 		return AH_FALSE;
=20
 	AH5416(ah)->ah_initPLL(ah, AH_NULL);
-	return AH_TRUE;
+	return (AH_TRUE);
 }
=20
 /*
@@ -1509,6 +1513,7 @@
     const struct ar5416eeprom *eep,
     uint8_t txRxAttenLocal, int regChainOffset, int i)
 {
+
 	if (IS_EEP_MINOR_V3(ah)) {
 		txRxAttenLocal =3D pModal->txRxAttenCh[i];
=20
@@ -1705,7 +1710,7 @@
 		    eep->baseEepHeader.desiredScaleCCK);
         }
=20
-    return AH_TRUE;
+    return (AH_TRUE);
 }
=20
 /*
@@ -1739,7 +1744,8 @@
=20
 	/* Set rates Array from collected data */
 	ratesArray[rate6mb] =3D ratesArray[rate9mb] =3D ratesArray[rate12mb] =3D
-	    ratesArray[rate18mb] =3D ratesArray[rate24mb] =3D targetPowerOfdm->tP=
ow2x[0];
+	ratesArray[rate18mb] =3D ratesArray[rate24mb] =3D
+	    targetPowerOfdm->tPow2x[0];
 	ratesArray[rate36mb] =3D targetPowerOfdm->tPow2x[1];
 	ratesArray[rate48mb] =3D targetPowerOfdm->tPow2x[2];
 	ratesArray[rate54mb] =3D targetPowerOfdm->tPow2x[3];
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ar5416/ar5416=
_xmit.c
--- a/head/sys/dev/ath/ath_hal/ar5416/ar5416_xmit.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/sys/dev/ath/ath_hal/ar5416/ar5416_xmit.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_xmit.c 226764 2011-10-=
25 23:24:05Z adrian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416_xmit.c 233895 2012-04-=
04 21:49:49Z adrian $
  */
 #include "opt_ah.h"
=20
@@ -338,13 +338,15 @@
 	uint8_t delims,
 	u_int segLen,
 	HAL_BOOL firstSeg,
-	HAL_BOOL lastSeg)
+	HAL_BOOL lastSeg,
+	HAL_BOOL lastAggr)
 {
 	struct ar5416_desc *ads =3D AR5416DESC(ds);
 	uint32_t *ds_txstatus =3D AR5416_DS_TXSTATUS(ah,ads);
 	struct ath_hal_5416 *ahp =3D AH5416(ah);
=20
 	int isaggr =3D 0;
+	uint32_t last_aggr =3D 0;
 =09
 	(void) hdrLen;
 	(void) ah;
@@ -355,6 +357,8 @@
 	if (type =3D=3D HAL_PKT_TYPE_AMPDU) {
 		type =3D HAL_PKT_TYPE_NORMAL;
 		isaggr =3D 1;
+		if (lastAggr =3D=3D AH_FALSE)
+			last_aggr =3D AR_MoreAggr;
 	}
=20
 	/*
@@ -372,8 +376,19 @@
 	 * Note: VEOL should only be for the last descriptor in the chain.
 	 */
 	ads->ds_ctl0 =3D (pktLen & AR_FrameLen);
+
+	/*
+	 * For aggregates:
+	 * + IsAggr must be set for all descriptors of all subframes of
+	 *   the aggregate
+	 * + MoreAggr must be set for all descriptors of all subframes
+	 *   of the aggregate EXCEPT the last subframe;
+	 * + MoreAggr must be _CLEAR_ for all descrpitors of the last
+	 *   subframe of the aggregate.
+	 */
 	ads->ds_ctl1 =3D (type << AR_FrameType_S)
-			| (isaggr ? (AR_IsAggr | AR_MoreAggr) : 0);
+			| (isaggr ? (AR_IsAggr | last_aggr) : 0);
+
 	ads->ds_ctl2 =3D 0;
 	ads->ds_ctl3 =3D 0;
 	if (keyIx !=3D HAL_TXKEYIX_INVALID) {
@@ -483,7 +498,6 @@
 	ads->ds_ctl2 =3D AR5416DESC_CONST(ds0)->ds_ctl2;
 	ads->ds_ctl3 =3D AR5416DESC_CONST(ds0)->ds_ctl3;
 #endif
-=09
 	return AH_TRUE;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/ath_hal/ar5416/ar5416=
reg.h
--- a/head/sys/dev/ath/ath_hal/ar5416/ar5416reg.h	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sys/dev/ath/ath_hal/ar5416/ar5416reg.h	Tue Apr 17 11:51:51 2012 =
+0300
@@ -14,7 +14,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416reg.h 228834 2011-12-23=
 08:32:53Z adrian $
+ * $FreeBSD: head/sys/dev/ath/ath_hal/ar5416/ar5416reg.h 233885 2012-04-04=
 20:42:32Z adrian $
  */
 #ifndef _DEV_ATH_AR5416REG_H
 #define	_DEV_ATH_AR5416REG_H
@@ -212,9 +212,10 @@
 #define	AR_WA_RESET_EN		0x00040000	/* ena AR_WA_UNTIE_RESET_EN */
 #define	AR_WA_ANALOG_SHIFT	0x00100000
 #define	AR_WA_POR_SHORT		0x00200000	/* PCIE phy reset control */
+#define	AR_WA_D3_L1_DISABLE	0x00800000	/* bit 23 */
=20
 #define	AR_WA_DEFAULT		0x0000073f
-#define	AR9280_WA_DEFAULT	0x0040073f
+#define	AR9280_WA_DEFAULT	0x0040073b	/* disable bit 2, see commit */
 #define	AR9285_WA_DEFAULT	0x004a05cb
=20
 #define	AR_PCIE_PM_CTRL_ENA	0x00080000
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_ath.c
--- a/head/sys/dev/ath/if_ath.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_ath.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 233053 2012-03-16 23:24:27Z =
adrian $");
+__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 234369 2012-04-17 06:02:41Z =
adrian $");
=20
 /*
  * Driver for the Atheros Wireless LAN controller.
@@ -191,6 +191,7 @@
 static void	ath_tx_proc_q0(void *, int);
 static void	ath_tx_proc_q0123(void *, int);
 static void	ath_tx_proc(void *, int);
+static void	ath_txq_sched_tasklet(void *, int);
 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
 static void	ath_draintxq(struct ath_softc *, ATH_RESET_TYPE reset_type);
 static void	ath_stoprecv(struct ath_softc *, int);
@@ -199,6 +200,9 @@
 static void	ath_scan_start(struct ieee80211com *);
 static void	ath_scan_end(struct ieee80211com *);
 static void	ath_set_channel(struct ieee80211com *);
+#ifdef	ATH_ENABLE_11N
+static void	ath_update_chw(struct ieee80211com *);
+#endif	/* ATH_ENABLE_11N */
 static void	ath_calibrate(void *);
 static int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
 static void	ath_setup_stationkey(struct ieee80211_node *);
@@ -397,6 +401,8 @@
 	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
 	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
 	TASK_INIT(&sc->sc_resettask,0, ath_reset_proc, sc);
+	TASK_INIT(&sc->sc_txqtask,0, ath_txq_sched_tasklet, sc);
+	TASK_INIT(&sc->sc_fataltask,0, ath_fatal_proc, sc);
=20
 	/*
 	 * Allocate hardware transmit queues: one queue for
@@ -729,6 +735,13 @@
 		ic->ic_txstream =3D txs;
 		ic->ic_rxstream =3D rxs;
=20
+		(void) ath_hal_getcapability(ah, HAL_CAP_RTS_AGGR_LIMIT, 1,
+		    &sc->sc_rts_aggr_limit);
+		if (sc->sc_rts_aggr_limit !=3D (64 * 1024))
+			device_printf(sc->sc_dev,
+			    "[HT] RTS aggregates limited to %d KiB\n",
+			    sc->sc_rts_aggr_limit / 1024);
+
 		device_printf(sc->sc_dev,
 		    "[HT] %d RX streams; %d TX streams\n", rxs, txs);
 	}
@@ -794,7 +807,7 @@
 	ic->ic_scan_start =3D ath_scan_start;
 	ic->ic_scan_end =3D ath_scan_end;
 	ic->ic_set_channel =3D ath_set_channel;
-
+#ifdef	ATH_ENABLE_11N
 	/* 802.11n specific - but just override anyway */
 	sc->sc_addba_request =3D ic->ic_addba_request;
 	sc->sc_addba_response =3D ic->ic_addba_response;
@@ -808,6 +821,9 @@
 	ic->ic_addba_stop =3D ath_addba_stop;
 	ic->ic_bar_response =3D ath_bar_response;
=20
+	ic->ic_update_chw =3D ath_update_chw;
+#endif	/* ATH_ENABLE_11N */
+
 	ieee80211_radiotap_attach(ic,
 	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
 		ATH_TX_RADIOTAP_PRESENT,
@@ -1480,6 +1496,15 @@
 	    ah->ah_intrstate[3],
 	    ah->ah_intrstate[6]);
 #endif
+
+	/* Squirrel away SYNC interrupt debugging */
+	if (ah->ah_syncstate !=3D 0) {
+		int i;
+		for (i =3D 0; i < 32; i++)
+			if (ah->ah_syncstate & (i << i))
+				sc->sc_intr_stats.sync_intr[i]++;
+	}
+
 	status &=3D sc->sc_imask;			/* discard unasked for bits */
=20
 	/* Short-circuit un-handled interrupts */
@@ -1503,7 +1528,7 @@
 	if (status & HAL_INT_FATAL) {
 		sc->sc_stats.ast_hardware++;
 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
-		ath_fatal_proc(sc, 0);
+		taskqueue_enqueue(sc->sc_tq, &sc->sc_fataltask);
 	} else {
 		if (status & HAL_INT_SWBA) {
 			/*
@@ -2269,7 +2294,6 @@
 	/* Copy basics */
 	tbf->bf_next =3D NULL;
 	tbf->bf_nseg =3D bf->bf_nseg;
-	tbf->bf_txflags =3D bf->bf_txflags;
 	tbf->bf_flags =3D bf->bf_flags & ~ATH_BUF_BUSY;
 	tbf->bf_status =3D bf->bf_status;
 	tbf->bf_m =3D bf->bf_m;
@@ -4743,7 +4767,7 @@
 		pri =3D M_WME_GETAC(bf->bf_m);
 		if (pri >=3D WME_AC_VO)
 			ic->ic_wme.wme_hipri_traffic++;
-		if ((bf->bf_txflags & HAL_TXDESC_NOACK) =3D=3D 0)
+		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) =3D=3D 0)
 			ni->ni_inact =3D ni->ni_inact_reload;
 	} else {
 		if (ts->ts_status & HAL_TXERR_XRETRY)
@@ -4790,7 +4814,7 @@
 	if (fail =3D=3D 1)
 		st =3D -1;
 	else
-		st =3D ((bf->bf_txflags & HAL_TXDESC_NOACK) =3D=3D 0) ?
+		st =3D ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) =3D=3D 0) ?
 		    ts->ts_status : HAL_TXERR_XRETRY;
=20
 	if (bf->bf_state.bfs_dobaw)
@@ -4883,6 +4907,9 @@
 	struct ath_tx_status *ts;
 	struct ieee80211_node *ni;
 	struct ath_node *an;
+#ifdef	IEEE80211_SUPPORT_SUPERG
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
+#endif	/* IEEE80211_SUPPORT_SUPERG */
 	int nacked;
 	HAL_STATUS status;
=20
@@ -4906,6 +4933,10 @@
 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
 			    status =3D=3D HAL_OK);
+		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched =3D=3D 0)) {
+			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
+			    status =3D=3D HAL_OK);
+		}
 #endif
 		if (status =3D=3D HAL_EINPROGRESS) {
 			ATH_TXQ_UNLOCK(txq);
@@ -4939,7 +4970,7 @@
 		 * workaround phantom bmiss interrupts.
 		 */
 		if (ni !=3D NULL && ts->ts_status =3D=3D 0 &&
-		    ((bf->bf_txflags & HAL_TXDESC_NOACK) =3D=3D 0)) {
+		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) =3D=3D 0)) {
 			nacked++;
 			sc->sc_stats.ast_tx_rssi =3D ts->ts_rssi;
 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
@@ -4964,7 +4995,7 @@
 		 */
 		if (bf->bf_comp =3D=3D NULL) {
 			if ((ts->ts_status & HAL_TXERR_FILT) =3D=3D 0 &&
-			    (bf->bf_txflags & HAL_TXDESC_NOACK) =3D=3D 0) {
+			    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) =3D=3D 0) {
 				/*
 				 * XXX assume this isn't an aggregate
 				 * frame.
@@ -5130,6 +5161,41 @@
 #undef	TXQACTIVE
=20
 /*
+ * Deferred processing of TXQ rescheduling.
+ */
+static void
+ath_txq_sched_tasklet(void *arg, int npending)
+{
+	struct ath_softc *sc =3D arg;
+	int i;
+
+	/* XXX is skipping ok? */
+	ATH_PCU_LOCK(sc);
+#if 0
+	if (sc->sc_inreset_cnt > 0) {
+		device_printf(sc->sc_dev,
+		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
+		ATH_PCU_UNLOCK(sc);
+		return;
+	}
+#endif
+	sc->sc_txproc_cnt++;
+	ATH_PCU_UNLOCK(sc);
+
+	for (i =3D 0; i < HAL_NUM_TX_QUEUES; i++) {
+		if (ATH_TXQ_SETUP(sc, i)) {
+			ATH_TXQ_LOCK(&sc->sc_txq[i]);
+			ath_txq_sched(sc, &sc->sc_txq[i]);
+			ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
+		}
+	}
+
+	ATH_PCU_LOCK(sc);
+	sc->sc_txproc_cnt--;
+	ATH_PCU_UNLOCK(sc);
+}
+
+/*
  * Return a buffer to the pool and update the 'busy' flag on the
  * previous 'tail' entry.
  *
@@ -5717,6 +5783,33 @@
 		 sc->sc_curaid);
 }
=20
+#ifdef	ATH_ENABLE_11N
+/*
+ * For now, just do a channel change.
+ *
+ * Later, we'll go through the hard slog of suspending tx/rx, changing rate
+ * control state and resetting the hardware without dropping frames out
+ * of the queue.
+ *
+ * The unfortunate trouble here is making absolutely sure that the
+ * channel width change has propagated enough so the hardware
+ * absolutely isn't handed bogus frames for it's current operating
+ * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
+ * does occur in parallel, we need to make certain we've blocked
+ * any further ongoing TX (and RX, that can cause raw TX)
+ * before we do this.
+ */
+static void
+ath_update_chw(struct ieee80211com *ic)
+{
+	struct ifnet *ifp =3D ic->ic_ifp;
+	struct ath_softc *sc =3D ifp->if_softc;
+
+	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
+	ath_set_channel(ic);
+}
+#endif	/* ATH_ENABLE_11N */
+
 static void
 ath_set_channel(struct ieee80211com *ic)
 {
@@ -6396,8 +6489,13 @@
 		    ifr->ifr_data, sizeof (sc->sc_stats));
 	case SIOCZATHSTATS:
 		error =3D priv_check(curthread, PRIV_DRIVER);
-		if (error =3D=3D 0)
+		if (error =3D=3D 0) {
 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
+			memset(&sc->sc_aggr_stats, 0,
+			    sizeof(sc->sc_aggr_stats));
+			memset(&sc->sc_intr_stats, 0,
+			    sizeof(sc->sc_intr_stats));
+		}
 		break;
 #ifdef ATH_DIAGAPI
 	case SIOCGATHDIAG:
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_ath_debug.c
--- a/head/sys/dev/ath/if_ath_debug.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_ath_debug.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_debug.c 233227 2012-03-20 04:5=
0:25Z adrian $");
+__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_debug.c 233966 2012-04-07 02:0=
1:26Z adrian $");
=20
 #include "opt_inet.h"
 #include "opt_ath.h"
@@ -137,10 +137,9 @@
 		for (i =3D 0, ds =3D bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
 			printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:%04x%s\n",
 			    ds, (const struct ath_desc *)bf->bf_daddr + i,
-			    ds->ds_link, ds->ds_data, bf->bf_txflags,
+			    ds->ds_link, ds->ds_data, bf->bf_state.bfs_txflags,
 			    !done ? "" : (ts->ts_status =3D=3D 0) ? " *" : " !");
-			printf("        TXF: %04x Seq: %d swtry: %d ADDBAW?: %d DOBAW?: %d\n",
-			    bf->bf_state.bfs_flags,
+			printf("        Seq: %d swtry: %d ADDBAW?: %d DOBAW?: %d\n",
 			    bf->bf_state.bfs_seqno,
 			    bf->bf_state.bfs_retries,
 			    bf->bf_state.bfs_addedbaw,
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_ath_pci.c
--- a/head/sys/dev/ath/if_ath_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_ath_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,11 +28,12 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_pci.c 227350 2011-11-08 18:37:=
52Z adrian $");
+__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_pci.c 234304 2012-04-15 00:04:=
23Z adrian $");
=20
 /*
  * PCI/Cardbus front-end for the Atheros Wireless LAN controller driver.
  */
+#include "opt_ath.h"
=20
 #include <sys/param.h>
 #include <sys/systm.h>=20
@@ -56,10 +57,18 @@
 #include <net80211/ieee80211_var.h>
=20
 #include <dev/ath/if_athvar.h>
+#include <dev/ath/ath_hal/ah_devid.h>
=20
+#include <sys/pciio.h>
 #include <dev/pci/pcivar.h>
 #include <dev/pci/pcireg.h>
=20
+/* For EEPROM firmware */
+#ifdef	ATH_EEPROM_FIRMWARE
+#include <sys/linker.h>
+#include <sys/firmware.h>
+#endif	/* ATH_EEPROM_FIRMWARE */
+
 /*
  * PCI glue.
  */
@@ -74,14 +83,31 @@
 #define	BS_BAR	0x10
 #define	PCIR_RETRY_TIMEOUT	0x41
 #define	PCIR_CFG_PMCSR		0x48
+/* number of 16 bit words */
+#define	ATH_EEPROM_DATA_SIZE	2048
+#define	AR5416_EEPROM_MAGIC	0xa55a
+
+#define	DEFAULT_CACHESIZE	32
=20
 static void
 ath_pci_setup(device_t dev)
 {
-#ifdef	ATH_PCI_LATENCY_WAR
+	uint8_t cz;
+
+	/* XXX TODO: need to override the _system_ saved copies of this */
+
+	/*
+	 * If the cache line size is 0, force it to a reasonable
+	 * value.
+	 */
+	cz =3D pci_read_config(dev, PCIR_CACHELNSZ, 1);
+	if (cz =3D=3D 0) {
+		pci_write_config(dev, PCIR_CACHELNSZ,
+		    DEFAULT_CACHESIZE / 4, 1);
+	}
+
 	/* Override the system latency timer */
-	pci_write_config(dev, PCIR_LATTIMER, 0x80, 1);
-#endif
+	pci_write_config(dev, PCIR_LATTIMER, 0xa8, 1);
=20
 	/* If a PCI NIC, force wakeup */
 #ifdef	ATH_PCI_WAKEUP_WAR
@@ -103,11 +129,139 @@
 	pci_write_config(dev, PCIR_RETRY_TIMEOUT, 0, 1);
 }
=20
+/*
+ * Fix PCI configuration space and preload EEPROM data.
+ */
+static int
+ar724x_load_eeprom_data(device_t dev)
+{
+	uint32_t	bar0, hint, reg, val;
+	uint16_t	*data =3D NULL;
+	struct resource	*memres;
+	int		rid;
+	bus_space_tag_t	bst;
+	bus_space_handle_t bsh;
+	struct pci_devinfo *dinfo;
+	struct ath_pci_softc *psc =3D device_get_softc(dev);
+	struct ath_softc *sc =3D &psc->sc_sc;
+
+	if (bootverbose)
+		device_printf(dev, "Fetching eeprom address hint\n");
+
+	/* Search for a hint of eeprom data offset */
+	if (resource_int_value(device_get_name(dev),
+	    device_get_unit(dev), "eepromdata", &hint) !=3D 0)
+		return (ENXIO);
+
+	device_printf(dev, "Loading the eeprom fixup data from %#x\n", hint);
+	data =3D (uint16_t *)MIPS_PHYS_TO_KSEG1(hint);
+
+	if (*data !=3D AR5416_EEPROM_MAGIC) {
+		device_printf(dev, "Invalid calibration data from %#x\n",
+		    hint);
+		return (EIO);
+	}
+
+	rid =3D 0x10;
+	memres =3D bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
+					    RF_ACTIVE);
+	if (memres =3D=3D NULL) {
+		device_printf(dev, "cannot map register space\n");
+		return (EIO);
+	}
+
+	bst =3D rman_get_bustag(memres);
+	bsh =3D rman_get_bushandle(memres);
+
+	/* Save bar(0) address - just to flush bar(0) (SoC WAR) ? */
+	bar0 =3D pci_read_config(dev, PCIR_BAR(0), 4);
+	/*
+	 * XXX Access to PCI internal regs=20
+	 * AR7240 - 0xffff
+	 * AR7241, AR7242 - 0x1000ffff
+	 */
+	pci_write_config(dev, PCIR_BAR(0), 0x1000ffff, 4);
+
+	val =3D pci_read_config(dev, PCIR_COMMAND, 4);
+	val |=3D (PCIM_CMD_BUSMASTEREN | PCIM_CMD_MEMEN);
+	pci_write_config(dev, PCIR_COMMAND, val, 4);
+
+	if (bootverbose)
+		printf("Load PCI config space fix up\n");
+	/* set pointer to first reg address */
+	data +=3D 3;
+	while (*data !=3D 0xffff) {
+		reg =3D *data++;
+		val =3D *data++;
+		val |=3D (*data++) << 16;
+
+		/* Write eeprom fixup data to device memory */
+		if (bootverbose)
+			printf("\t%08x: %08x\n", reg, val);
+		bus_space_write_4(bst, bsh, reg, val);
+		DELAY(100);
+	}
+	DELAY(1000);
+
+	val =3D pci_read_config(dev, PCIR_COMMAND, 4);
+	val &=3D ~(PCIM_CMD_BUSMASTEREN | PCIM_CMD_MEMEN);
+	pci_write_config(dev, PCIR_COMMAND, val, 4);
+
+	/* Write the saved bar(0) address */
+	pci_write_config(dev, PCIR_BAR(0), bar0, 4);
+
+	DELAY(10000);
+
+	bus_release_resource(dev, SYS_RES_MEMORY, rid, memres);
+
+	/* Update IDs */
+	pci_save_state(dev);
+	pci_restore_state(dev);
+
+	dinfo =3D device_get_ivars(dev);
+
+	dinfo->conf.pc_subvendor =3D dinfo->cfg.subvendor;
+	dinfo->conf.pc_subdevice =3D dinfo->cfg.subdevice;
+	dinfo->conf.pc_vendor =3D dinfo->cfg.vendor;
+	dinfo->conf.pc_device =3D dinfo->cfg.device;
+
+	dinfo->conf.pc_class =3D dinfo->cfg.baseclass;
+	dinfo->conf.pc_subclass =3D dinfo->cfg.subclass;
+	dinfo->conf.pc_progif =3D dinfo->cfg.progif;
+	dinfo->conf.pc_revid =3D dinfo->cfg.revid;
+
+	sc->sc_eepromdata =3D malloc(ATH_EEPROM_DATA_SIZE * 2, M_TEMP,
+	    M_NOWAIT | M_ZERO);
+	if (sc->sc_eepromdata =3D=3D NULL) {
+		device_printf(dev,
+		    "cannot allocate memory for eeprom data\n");
+		return (ENOMEM);
+	}
+
+	/* Copy the EEPROM data out */
+	/* Restore pointer */
+	data =3D (uint16_t *)MIPS_PHYS_TO_KSEG1(hint);
+	memcpy(sc->sc_eepromdata, data, ATH_EEPROM_DATA_SIZE * 2);
+
+	return (0);
+}
+
 static int
 ath_pci_probe(device_t dev)
 {
 	const char* devname;
=20
+	if (pci_get_vendor(dev) !=3D ATHEROS_VENDOR_ID)
+		return (ENXIO);
+
+	switch (pci_get_device(dev)) {
+	case AR9287_DEVID_PCIE_WOEE:
+		/* EEPROMless Kiwi */
+		device_set_desc(dev, "Atheros 9227/9287");
+		return BUS_PROBE_DEFAULT;
+	}
+
+	/* Now probe normal device */
 	devname =3D ath_hal_probe(pci_get_vendor(dev), pci_get_device(dev));
 	if (devname !=3D NULL) {
 		device_set_desc(dev, devname);
@@ -123,9 +277,21 @@
 	struct ath_softc *sc =3D &psc->sc_sc;
 	int error =3D ENXIO;
 	int rid;
+#ifdef	ATH_EEPROM_FIRMWARE
+	const struct firmware *fw =3D NULL;
+	const char *buf;
+#endif
=20
 	sc->sc_dev =3D dev;
=20
+	switch (pci_get_device(dev)) {
+	case AR9287_DEVID_PCIE_WOEE:
+		/* EEPROMless Kiwi */
+		error =3D ar724x_load_eeprom_data(dev);
+		if (error)
+			return (error);
+	}
+
 	/*
 	 * Enable bus mastering.
 	 */
@@ -191,6 +357,37 @@
 		goto bad3;
 	}
=20
+#ifdef	ATH_EEPROM_FIRMWARE
+	/*
+	 * If there's an EEPROM firmware image, load that in.
+	 */
+	if (resource_string_value(device_get_name(dev), device_get_unit(dev),
+	    "eeprom_firmware", &buf) =3D=3D 0) {
+		if (bootverbose)
+			device_printf(dev, "%s: looking up firmware @ '%s'\n",
+			    __func__, buf);
+
+		fw =3D firmware_get(buf);
+		if (fw =3D=3D NULL) {
+			device_printf(dev, "%s: couldn't find firmware\n",
+			    __func__);
+			goto bad3;
+		}
+
+		device_printf(dev, "%s: EEPROM firmware @ %p\n",
+		    __func__, fw->data);
+		sc->sc_eepromdata =3D
+		    malloc(fw->datasize, M_TEMP, M_WAITOK | M_ZERO);
+		if (! sc->sc_eepromdata) {
+			device_printf(dev, "%s: can't malloc eepromdata\n",
+			    __func__);
+			goto bad3;
+		}
+		memcpy(sc->sc_eepromdata, fw->data, fw->datasize);
+		firmware_put(fw, 0);
+	}
+#endif /* ATH_EEPROM_FIRMWARE */
+
 	ATH_LOCK_INIT(sc);
 	ATH_PCU_LOCK_INIT(sc);
=20
@@ -234,6 +431,9 @@
 	bus_dma_tag_destroy(sc->sc_dmat);
 	bus_release_resource(dev, SYS_RES_MEMORY, BS_BAR, psc->sc_sr);
=20
+	if (sc->sc_eepromdata)
+		free(sc->sc_eepromdata, M_TEMP);
+
 	ATH_PCU_LOCK_DESTROY(sc);
 	ATH_LOCK_DESTROY(sc);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_ath_sysctl.c
--- a/head/sys/dev/ath/if_ath_sysctl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_ath_sysctl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_sysctl.c 232764 2012-03-10 04:=
14:04Z adrian $");
+__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_sysctl.c 234090 2012-04-10 07:=
23:37Z adrian $");
=20
 /*
  * Driver for the Atheros Wireless LAN controller.
@@ -344,6 +344,8 @@
 	    sc->sc_aggr_stats.aggr_aggr_pkt);
 	printf("aggr single packet low hwq: %d\n",
 	    sc->sc_aggr_stats.aggr_low_hwq_single_pkt);
+	printf("aggr single packet RTS aggr limited: %d\n",
+	    sc->sc_aggr_stats.aggr_rts_aggr_limited);
 	printf("aggr sched, no work: %d\n",
 	    sc->sc_aggr_stats.aggr_sched_nopkt);
 	for (i =3D 0; i < 64; i++) {
@@ -653,6 +655,7 @@
 		return 0;       /* Not clearing the stats is still valid */
 	memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
 	memset(&sc->sc_aggr_stats, 0, sizeof(sc->sc_aggr_stats));
+	memset(&sc->sc_intr_stats, 0, sizeof(sc->sc_intr_stats));
=20
 	val =3D 0;
 	return 0;
@@ -675,6 +678,26 @@
 	}
 }
=20
+static void
+ath_sysctl_stats_attach_intr(struct ath_softc *sc,
+    struct sysctl_oid_list *parent)
+{
+	struct sysctl_ctx_list *ctx =3D device_get_sysctl_ctx(sc->sc_dev);
+	struct sysctl_oid *tree =3D device_get_sysctl_tree(sc->sc_dev);
+	struct sysctl_oid_list *child =3D SYSCTL_CHILDREN(tree);
+	int i;
+	char sn[8];
+
+	tree =3D SYSCTL_ADD_NODE(ctx, parent, OID_AUTO, "sync_intr",
+	    CTLFLAG_RD, NULL, "Sync interrupt statistics");
+	child =3D SYSCTL_CHILDREN(tree);
+	for (i =3D 0; i < 32; i++) {
+		snprintf(sn, sizeof(sn), "%d", i);
+		SYSCTL_ADD_UINT(ctx, child, OID_AUTO, sn, CTLFLAG_RD,
+		    &sc->sc_intr_stats.sync_intr[i], 0, "");
+	}
+}
+
 void
 ath_sysctl_stats_attach(struct ath_softc *sc)
 {
@@ -902,6 +925,9 @@
 =09
 	/* Attach the RX phy error array */
 	ath_sysctl_stats_attach_rxphyerr(sc, child);
+
+	/* Attach the interrupt statistics array */
+	ath_sysctl_stats_attach_intr(sc, child);
 }
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_ath_tx.c
--- a/head/sys/dev/ath/if_ath_tx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_ath_tx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_tx.c 233227 2012-03-20 04:50:2=
5Z adrian $");
+__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_tx.c 234324 2012-04-15 20:29:3=
9Z adrian $");
=20
 /*
  * Driver for the Atheros Wireless LAN controller.
@@ -205,6 +205,8 @@
 	for (m =3D m0->m_nextpkt; m !=3D NULL; m =3D m->m_nextpkt) {
 		bf =3D _ath_getbuf_locked(sc);
 		if (bf =3D=3D NULL) {	/* out of buffers, cleanup */
+			device_printf(sc->sc_dev, "%s: no buffer?\n",
+			    __func__);
 			ath_txfrag_cleanup(sc, frags, ni);
 			break;
 		}
@@ -322,6 +324,7 @@
 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
 		bf->bf_lastds =3D ds;
 	}
+	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
 }
=20
 /*
@@ -363,7 +366,8 @@
 		    bf->bf_state.bfs_ndelim,
 		    bf->bf_segs[i].ds_len,	/* segment length */
 		    i =3D=3D 0,		/* first segment */
-		    i =3D=3D bf->bf_nseg - 1	/* last segment */
+		    i =3D=3D bf->bf_nseg - 1,	/* last segment */
+		    bf->bf_next =3D=3D NULL		/* last sub-frame in aggr */
 		);
=20
 		DPRINTF(sc, ATH_DEBUG_XMIT,
@@ -371,6 +375,8 @@
 			__func__, i, ds->ds_link, ds->ds_data,
 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
 		bf->bf_lastds =3D ds;
+		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
+		    BUS_DMASYNC_PREWRITE);
 	}
 }
=20
@@ -423,7 +429,7 @@
 	ath_hal_setupfirsttxdesc(sc->sc_ah,
 	    bf_first->bf_desc,
 	    bf_first->bf_state.bfs_al,
-	    bf_first->bf_state.bfs_flags | HAL_TXDESC_INTREQ,
+	    bf_first->bf_state.bfs_txflags | HAL_TXDESC_INTREQ,
 	    bf_first->bf_state.bfs_txpower,
 	    bf_first->bf_state.bfs_txrate0,
 	    bf_first->bf_state.bfs_try0,
@@ -663,6 +669,15 @@
     struct mbuf *m0, int iswep, int isfrag, int *hdrlen, int *pktlen,
     int *keyix)
 {
+	DPRINTF(sc, ATH_DEBUG_XMIT,
+	    "%s: hdrlen=3D%d, pktlen=3D%d, isfrag=3D%d, iswep=3D%d, m0=3D%p\n",
+	    __func__,
+	    *hdrlen,
+	    *pktlen,
+	    isfrag,
+	    iswep,
+	    m0);
+
 	if (iswep) {
 		const struct ieee80211_cipher *cip;
 		struct ieee80211_key *k;
@@ -710,6 +725,133 @@
 	return (1);
 }
=20
+/*
+ * Calculate whether interoperability protection is required for
+ * this frame.
+ *
+ * This requires the rate control information be filled in,
+ * as the protection requirement depends upon the current
+ * operating mode / PHY.
+ */
+static void
+ath_tx_calc_protection(struct ath_softc *sc, struct ath_buf *bf)
+{
+	struct ieee80211_frame *wh;
+	uint8_t rix;
+	uint16_t flags;
+	int shortPreamble;
+	const HAL_RATE_TABLE *rt =3D sc->sc_currates;
+	struct ifnet *ifp =3D sc->sc_ifp;
+	struct ieee80211com *ic =3D ifp->if_l2com;
+
+	flags =3D bf->bf_state.bfs_txflags;
+	rix =3D bf->bf_state.bfs_rc[0].rix;
+	shortPreamble =3D bf->bf_state.bfs_shpream;
+	wh =3D mtod(bf->bf_m, struct ieee80211_frame *);
+
+	/*
+	 * If 802.11g protection is enabled, determine whether
+	 * to use RTS/CTS or just CTS.  Note that this is only
+	 * done for OFDM unicast frames.
+	 */
+	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
+	    rt->info[rix].phy =3D=3D IEEE80211_T_OFDM &&
+	    (flags & HAL_TXDESC_NOACK) =3D=3D 0) {
+		bf->bf_state.bfs_doprot =3D 1;
+		/* XXX fragments must use CCK rates w/ protection */
+		if (ic->ic_protmode =3D=3D IEEE80211_PROT_RTSCTS) {
+			flags |=3D HAL_TXDESC_RTSENA;
+		} else if (ic->ic_protmode =3D=3D IEEE80211_PROT_CTSONLY) {
+			flags |=3D HAL_TXDESC_CTSENA;
+		}
+		/*
+		 * For frags it would be desirable to use the
+		 * highest CCK rate for RTS/CTS.  But stations
+		 * farther away may detect it at a lower CCK rate
+		 * so use the configured protection rate instead
+		 * (for now).
+		 */
+		sc->sc_stats.ast_tx_protect++;
+	}
+
+	/*
+	 * If 11n protection is enabled and it's a HT frame,
+	 * enable RTS.
+	 *
+	 * XXX ic_htprotmode or ic_curhtprotmode?
+	 * XXX should it_htprotmode only matter if ic_curhtprotmode=20
+	 * XXX indicates it's not a HT pure environment?
+	 */
+	if ((ic->ic_htprotmode =3D=3D IEEE80211_PROT_RTSCTS) &&
+	    rt->info[rix].phy =3D=3D IEEE80211_T_HT &&
+	    (flags & HAL_TXDESC_NOACK) =3D=3D 0) {
+		flags |=3D HAL_TXDESC_RTSENA;
+		sc->sc_stats.ast_tx_htprotect++;
+	}
+	bf->bf_state.bfs_txflags =3D flags;
+}
+
+/*
+ * Update the frame duration given the currently selected rate.
+ *
+ * This also updates the frame duration value, so it will require
+ * a DMA flush.
+ */
+static void
+ath_tx_calc_duration(struct ath_softc *sc, struct ath_buf *bf)
+{
+	struct ieee80211_frame *wh;
+	uint8_t rix;
+	uint16_t flags;
+	int shortPreamble;
+	struct ath_hal *ah =3D sc->sc_ah;
+	const HAL_RATE_TABLE *rt =3D sc->sc_currates;
+	int isfrag =3D bf->bf_m->m_flags & M_FRAG;
+
+	flags =3D bf->bf_state.bfs_txflags;
+	rix =3D bf->bf_state.bfs_rc[0].rix;
+	shortPreamble =3D bf->bf_state.bfs_shpream;
+	wh =3D mtod(bf->bf_m, struct ieee80211_frame *);
+
+	/*
+	 * Calculate duration.  This logically belongs in the 802.11
+	 * layer but it lacks sufficient information to calculate it.
+	 */
+	if ((flags & HAL_TXDESC_NOACK) =3D=3D 0 &&
+	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) !=3D IEEE80211_FC0_TYPE_CTL) {
+		u_int16_t dur;
+		if (shortPreamble)
+			dur =3D rt->info[rix].spAckDuration;
+		else
+			dur =3D rt->info[rix].lpAckDuration;
+		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
+			dur +=3D dur;		/* additional SIFS+ACK */
+			KASSERT(bf->bf_m->m_nextpkt !=3D NULL, ("no fragment"));
+			/*
+			 * Include the size of next fragment so NAV is
+			 * updated properly.  The last fragment uses only
+			 * the ACK duration
+			 */
+			dur +=3D ath_hal_computetxtime(ah, rt,
+					bf->bf_m->m_nextpkt->m_pkthdr.len,
+					rix, shortPreamble);
+		}
+		if (isfrag) {
+			/*
+			 * Force hardware to use computed duration for next
+			 * fragment by disabling multi-rate retry which updates
+			 * duration based on the multi-rate duration table.
+			 */
+			bf->bf_state.bfs_ismrr =3D 0;
+			bf->bf_state.bfs_try0 =3D ATH_TXMGTTRY;
+			/* XXX update bfs_rc[0].try? */
+		}
+
+		/* Update the duration field itself */
+		*(u_int16_t *)wh->i_dur =3D htole16(dur);
+	}
+}
+
 static uint8_t
 ath_tx_get_rtscts_rate(struct ath_hal *ah, const HAL_RATE_TABLE *rt,
     int cix, int shortPreamble)
@@ -802,7 +944,7 @@
 	/*
 	 * No RTS/CTS enabled? Don't bother.
 	 */
-	if ((bf->bf_state.bfs_flags &
+	if ((bf->bf_state.bfs_txflags &
 	    (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA)) =3D=3D 0) {
 		/* XXX is this really needed? */
 		bf->bf_state.bfs_ctsrate =3D 0;
@@ -837,7 +979,7 @@
 	if (! ath_tx_is_11n(sc))
 		ctsduration =3D ath_tx_calc_ctsduration(sc->sc_ah, rix, cix,
 		    bf->bf_state.bfs_shpream, bf->bf_state.bfs_pktlen,
-		    rt, bf->bf_state.bfs_flags);
+		    rt, bf->bf_state.bfs_txflags);
=20
 	/* Squirrel away in ath_buf */
 	bf->bf_state.bfs_ctsrate =3D ctsrate;
@@ -871,7 +1013,7 @@
 		, bf->bf_state.bfs_try0		/* series 0 rate/tries */
 		, bf->bf_state.bfs_keyix	/* key cache index */
 		, bf->bf_state.bfs_txantenna	/* antenna mode */
-		, bf->bf_state.bfs_flags	/* flags */
+		, bf->bf_state.bfs_txflags	/* flags */
 		, bf->bf_state.bfs_ctsrate	/* rts/cts rate */
 		, bf->bf_state.bfs_ctsduration	/* rts/cts duration */
 	);
@@ -994,8 +1136,10 @@
=20
 	/* Setup the descriptor before handoff */
 	ath_tx_do_ratelookup(sc, bf);
+	ath_tx_calc_duration(sc, bf);
+	ath_tx_calc_protection(sc, bf);
+	ath_tx_set_rtscts(sc, bf);
 	ath_tx_rate_fill_rcflags(sc, bf);
-	ath_tx_set_rtscts(sc, bf);
 	ath_tx_setds(sc, bf);
 	ath_tx_set_ratectrl(sc, bf->bf_node, bf);
 	ath_tx_chaindesclist(sc, bf);
@@ -1008,10 +1152,9 @@
=20
 static int
 ath_tx_normal_setup(struct ath_softc *sc, struct ieee80211_node *ni,
-    struct ath_buf *bf, struct mbuf *m0)
+    struct ath_buf *bf, struct mbuf *m0, struct ath_txq *txq)
 {
 	struct ieee80211vap *vap =3D ni->ni_vap;
-	struct ath_vap *avp =3D ATH_VAP(vap);
 	struct ath_hal *ah =3D sc->sc_ah;
 	struct ifnet *ifp =3D sc->sc_ifp;
 	struct ieee80211com *ic =3D ifp->if_l2com;
@@ -1020,7 +1163,6 @@
 	int keyix, hdrlen, pktlen, try0 =3D 0;
 	u_int8_t rix =3D 0, txrate =3D 0;
 	struct ath_desc *ds;
-	struct ath_txq *txq;
 	struct ieee80211_frame *wh;
 	u_int subtype, flags;
 	HAL_PKT_TYPE atype;
@@ -1155,21 +1297,6 @@
 		ath_freetx(m0);
 		return EIO;
 	}
-	txq =3D sc->sc_ac2q[pri];
-
-	/*
-	 * When servicing one or more stations in power-save mode
-	 * (or) if there is some mcast data waiting on the mcast
-	 * queue (to prevent out of order delivery) multicast
-	 * frames must be buffered until after the beacon.
-	 *
-	 * XXX This likely means that if there's a station in power
-	 * save mode, we won't be doing any kind of aggregation towards
-	 * anyone.  This is likely a very suboptimal way of dealing
-	 * with things.
-	 */
-	if (ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
-		txq =3D &avp->av_mcastq;
=20
 	/*
 	 * Calculate miscellaneous flags.
@@ -1194,84 +1321,6 @@
 #endif
=20
 	/*
-	 * If 802.11g protection is enabled, determine whether
-	 * to use RTS/CTS or just CTS.  Note that this is only
-	 * done for OFDM unicast frames.
-	 */
-	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
-	    rt->info[rix].phy =3D=3D IEEE80211_T_OFDM &&
-	    (flags & HAL_TXDESC_NOACK) =3D=3D 0) {
-		bf->bf_state.bfs_doprot =3D 1;
-		/* XXX fragments must use CCK rates w/ protection */
-		if (ic->ic_protmode =3D=3D IEEE80211_PROT_RTSCTS) {
-			flags |=3D HAL_TXDESC_RTSENA;
-		} else if (ic->ic_protmode =3D=3D IEEE80211_PROT_CTSONLY) {
-			flags |=3D HAL_TXDESC_CTSENA;
-		}
-		/*
-		 * For frags it would be desirable to use the
-		 * highest CCK rate for RTS/CTS.  But stations
-		 * farther away may detect it at a lower CCK rate
-		 * so use the configured protection rate instead
-		 * (for now).
-		 */
-		sc->sc_stats.ast_tx_protect++;
-	}
-
-#if 0
-	/*
-	 * If 11n protection is enabled and it's a HT frame,
-	 * enable RTS.
-	 *
-	 * XXX ic_htprotmode or ic_curhtprotmode?
-	 * XXX should it_htprotmode only matter if ic_curhtprotmode=20
-	 * XXX indicates it's not a HT pure environment?
-	 */
-	if ((ic->ic_htprotmode =3D=3D IEEE80211_PROT_RTSCTS) &&
-	    rt->info[rix].phy =3D=3D IEEE80211_T_HT &&
-	    (flags & HAL_TXDESC_NOACK) =3D=3D 0) {
-		cix =3D rt->info[sc->sc_protrix].controlRate;
-	    	flags |=3D HAL_TXDESC_RTSENA;
-		sc->sc_stats.ast_tx_htprotect++;
-	}
-#endif
-
-	/*
-	 * Calculate duration.  This logically belongs in the 802.11
-	 * layer but it lacks sufficient information to calculate it.
-	 */
-	if ((flags & HAL_TXDESC_NOACK) =3D=3D 0 &&
-	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) !=3D IEEE80211_FC0_TYPE_CTL) {
-		u_int16_t dur;
-		if (shortPreamble)
-			dur =3D rt->info[rix].spAckDuration;
-		else
-			dur =3D rt->info[rix].lpAckDuration;
-		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
-			dur +=3D dur;		/* additional SIFS+ACK */
-			KASSERT(m0->m_nextpkt !=3D NULL, ("no fragment"));
-			/*
-			 * Include the size of next fragment so NAV is
-			 * updated properly.  The last fragment uses only
-			 * the ACK duration
-			 */
-			dur +=3D ath_hal_computetxtime(ah, rt,
-					m0->m_nextpkt->m_pkthdr.len,
-					rix, shortPreamble);
-		}
-		if (isfrag) {
-			/*
-			 * Force hardware to use computed duration for next
-			 * fragment by disabling multi-rate retry which updates
-			 * duration based on the multi-rate duration table.
-			 */
-			ismrr =3D 0;
-			try0 =3D ATH_TXMGTTRY;	/* XXX? */
-		}
-		*(u_int16_t *)wh->i_dur =3D htole16(dur);
-	}
-
-	/*
 	 * Determine if a tx interrupt should be generated for
 	 * this descriptor.  We take a tx interrupt to reap
 	 * descriptors when the h/w hits an EOL condition or
@@ -1342,8 +1391,7 @@
 	bf->bf_state.bfs_try0 =3D try0;
 	bf->bf_state.bfs_keyix =3D keyix;
 	bf->bf_state.bfs_txantenna =3D sc->sc_txantenna;
-	bf->bf_state.bfs_flags =3D flags;
-	bf->bf_txflags =3D flags;
+	bf->bf_state.bfs_txflags =3D flags;
 	bf->bf_state.bfs_shpream =3D shortPreamble;
=20
 	/* XXX this should be done in ath_tx_setrate() */
@@ -1382,8 +1430,8 @@
 	/*
 	 * Determine the target hardware queue.
 	 *
-	 * For multicast frames, the txq gets overridden to be the
-	 * software TXQ and it's done via direct-dispatch.
+	 * For multicast frames, the txq gets overridden appropriately
+	 * depending upon the state of PS.
 	 *
 	 * For any other frame, we do a TID/QoS lookup inside the frame
 	 * to see what the TID should be. If it's a non-QoS frame, the
@@ -1432,17 +1480,15 @@
 	    "%s: bf=3D%p, tid=3D%d, ac=3D%d, is_ampdu=3D%d\n",
 	    __func__, bf, tid, pri, is_ampdu);
=20
-	/* Multicast frames go onto the software multicast queue */
-	if (ismcast)
-		txq =3D &avp->av_mcastq;
-
 	/*
-	 * XXX This likely means that if there's a station in power
-	 * save mode, we won't be doing any kind of aggregation towards
-	 * anyone.  This is likely a very suboptimal way of dealing
-	 * with things.
+	 * When servicing one or more stations in power-save mode
+	 * (or) if there is some mcast data waiting on the mcast
+	 * queue (to prevent out of order delivery) multicast frames
+	 * must be bufferd until after the beacon.
+	 *
+	 * TODO: we should lock the mcastq before we check the length.
 	 */
-	if ((! is_ampdu) && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
+	if (ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
 		txq =3D &avp->av_mcastq;
=20
 	/* Do the generic frame setup */
@@ -1473,6 +1519,7 @@
 		/* No AMPDU TX, we've been assigned a sequence number. */
 		if (IEEE80211_QOS_HAS_SEQ(wh)) {
 			bf->bf_state.bfs_seqno_assigned =3D 1;
+			/* XXX we should store the frag+seqno in bfs_seqno */
 			bf->bf_state.bfs_seqno =3D
 			    M_SEQNO_GET(m0) << IEEE80211_SEQ_SEQ_SHIFT;
 		}
@@ -1491,7 +1538,7 @@
 		    __func__, tid, M_SEQNO_GET(m0));
=20
 	/* This also sets up the DMA map */
-	r =3D ath_tx_normal_setup(sc, ni, bf, m0);
+	r =3D ath_tx_normal_setup(sc, ni, bf, m0, txq);
=20
 	if (r !=3D 0)
 		return r;
@@ -1687,8 +1734,7 @@
 	bf->bf_state.bfs_try0 =3D try0;
 	bf->bf_state.bfs_keyix =3D keyix;
 	bf->bf_state.bfs_txantenna =3D txantenna;
-	bf->bf_state.bfs_flags =3D flags;
-	bf->bf_txflags =3D flags;
+	bf->bf_state.bfs_txflags =3D flags;
 	bf->bf_state.bfs_shpream =3D
 	    !! (params->ibp_flags & IEEE80211_BPF_SHORTPRE);
=20
@@ -2338,7 +2384,6 @@
 	struct ath_tid *tid =3D &an->an_tid[bf->bf_state.bfs_tid];
 	struct ath_txq *txq =3D bf->bf_state.bfs_txq;
 	struct ieee80211_tx_ampdu *tap;
-	int seqno;
=20
 	ATH_TXQ_LOCK_ASSERT(txq);
=20
@@ -2347,6 +2392,7 @@
 	/* paused? queue */
 	if (tid->paused) {
 		ATH_TXQ_INSERT_TAIL(tid, bf, bf_list);
+		/* XXX don't sched - we're paused! */
 		return;
 	}
=20
@@ -2373,13 +2419,31 @@
 	 * the TIDs that map to it.  Ugh.
 	 */
 	if (bf->bf_state.bfs_dobaw) {
-		if (! BAW_WITHIN(tap->txa_start, tap->txa_wnd,
-		    ni->ni_txseqs[bf->bf_state.bfs_tid])) {
+		ieee80211_seq seqno;
+
+		/*
+		 * If the sequence number is allocated, use it.
+		 * Otherwise, use the sequence number we WOULD
+		 * allocate.
+		 */
+		if (bf->bf_state.bfs_seqno_assigned)
+			seqno =3D SEQNO(bf->bf_state.bfs_seqno);
+		else
+			seqno =3D ni->ni_txseqs[bf->bf_state.bfs_tid];
+
+		/*
+		 * Check whether either the currently allocated
+		 * sequence number _OR_ the to-be allocated
+		 * sequence number is inside the BAW.
+		 */
+		if (! BAW_WITHIN(tap->txa_start, tap->txa_wnd, seqno)) {
 			ATH_TXQ_INSERT_TAIL(tid, bf, bf_list);
 			ath_tx_tid_sched(sc, tid);
 			return;
 		}
 		if (! bf->bf_state.bfs_seqno_assigned) {
+			int seqno;
+
 			seqno =3D ath_tx_tid_seqno_assign(sc, ni, bf, bf->bf_m);
 			if (seqno < 0) {
 				device_printf(sc->sc_dev,
@@ -2414,8 +2478,10 @@
=20
 	/* Direct dispatch to hardware */
 	ath_tx_do_ratelookup(sc, bf);
+	ath_tx_calc_duration(sc, bf);
+	ath_tx_calc_protection(sc, bf);
+	ath_tx_set_rtscts(sc, bf);
 	ath_tx_rate_fill_rcflags(sc, bf);
-	ath_tx_set_rtscts(sc, bf);
 	ath_tx_setds(sc, bf);
 	ath_tx_set_ratectrl(sc, bf->bf_node, bf);
 	ath_tx_chaindesclist(sc, bf);
@@ -2569,11 +2635,11 @@
 static void
 ath_tx_tid_pause(struct ath_softc *sc, struct ath_tid *tid)
 {
-	ATH_TXQ_LOCK(sc->sc_ac2q[tid->ac]);
+
+	ATH_TXQ_LOCK_ASSERT(sc->sc_ac2q[tid->ac]);
 	tid->paused++;
 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: paused =3D %d\n",
 	    __func__, tid->paused);
-	ATH_TXQ_UNLOCK(sc->sc_ac2q[tid->ac]);
 }
=20
 /*
@@ -2595,10 +2661,163 @@
=20
 	ath_tx_tid_sched(sc, tid);
 	/* Punt some frames to the hardware if needed */
-	ath_txq_sched(sc, sc->sc_ac2q[tid->ac]);
+	//ath_txq_sched(sc, sc->sc_ac2q[tid->ac]);
+	taskqueue_enqueue(sc->sc_tq, &sc->sc_txqtask);
 }
=20
 /*
+ * Suspend the queue because we need to TX a BAR.
+ */
+static void
+ath_tx_tid_bar_suspend(struct ath_softc *sc, struct ath_tid *tid)
+{
+	ATH_TXQ_LOCK_ASSERT(sc->sc_ac2q[tid->ac]);
+
+	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
+	    "%s: tid=3D%p, called\n",
+	    __func__,
+	    tid);
+
+	/* We shouldn't be called when bar_tx is 1 */
+	if (tid->bar_tx) {
+		device_printf(sc->sc_dev, "%s: bar_tx is 1?!\n",
+		    __func__);
+	}
+
+	/* If we've already been called, just be patient. */
+	if (tid->bar_wait)
+		return;
+
+	/* Wait! */
+	tid->bar_wait =3D 1;
+
+	/* Only one pause, no matter how many frames fail */
+	ath_tx_tid_pause(sc, tid);
+}
+
+/*
+ * We've finished with BAR handling - either we succeeded or
+ * failed. Either way, unsuspend TX.
+ */
+static void
+ath_tx_tid_bar_unsuspend(struct ath_softc *sc, struct ath_tid *tid)
+{
+	ATH_TXQ_LOCK_ASSERT(sc->sc_ac2q[tid->ac]);
+
+	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
+	    "%s: tid=3D%p, called\n",
+	    __func__,
+	    tid);
+
+	if (tid->bar_tx =3D=3D 0 || tid->bar_wait =3D=3D 0) {
+		device_printf(sc->sc_dev, "%s: bar_tx=3D%d, bar_wait=3D%d: ?\n",
+		    __func__, tid->bar_tx, tid->bar_wait);
+	}
+
+	tid->bar_tx =3D tid->bar_wait =3D 0;
+	ath_tx_tid_resume(sc, tid);
+}
+
+/*
+ * Return whether we're ready to TX a BAR frame.
+ *
+ * Requires the TID lock be held.
+ */
+static int
+ath_tx_tid_bar_tx_ready(struct ath_softc *sc, struct ath_tid *tid)
+{
+
+	ATH_TXQ_LOCK_ASSERT(sc->sc_ac2q[tid->ac]);
+
+	if (tid->bar_wait =3D=3D 0 || tid->hwq_depth > 0)
+		return (0);
+
+	return (1);
+}
+
+/*
+ * Check whether the current TID is ready to have a BAR
+ * TXed and if so, do the TX.
+ *
+ * Since the TID/TXQ lock can't be held during a call to
+ * ieee80211_send_bar(), we have to do the dirty thing of unlocking it,
+ * sending the BAR and locking it again.
+ *
+ * Eventually, the code to send the BAR should be broken out
+ * from this routine so the lock doesn't have to be reacquired
+ * just to be immediately dropped by the caller.
+ */
+static void
+ath_tx_tid_bar_tx(struct ath_softc *sc, struct ath_tid *tid)
+{
+	struct ieee80211_tx_ampdu *tap;
+
+	ATH_TXQ_LOCK_ASSERT(sc->sc_ac2q[tid->ac]);
+
+	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
+	    "%s: tid=3D%p, called\n",
+	    __func__,
+	    tid);
+
+	tap =3D ath_tx_get_tx_tid(tid->an, tid->tid);
+
+	/*
+	 * This is an error condition!
+	 */
+	if (tid->bar_wait =3D=3D 0 || tid->bar_tx =3D=3D 1) {
+		device_printf(sc->sc_dev,
+		    "%s: tid=3D%p, bar_tx=3D%d, bar_wait=3D%d: ?\n",
+		    __func__,
+		    tid,
+		    tid->bar_tx,
+		    tid->bar_wait);
+		return;
+	}
+
+	/* Don't do anything if we still have pending frames */
+	if (tid->hwq_depth > 0) {
+		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
+		    "%s: tid=3D%p, hwq_depth=3D%d, waiting\n",
+		    __func__,
+		    tid,
+		    tid->hwq_depth);
+		return;
+	}
+
+	/* We're now about to TX */
+	tid->bar_tx =3D 1;
+
+	/*
+	 * Calculate new BAW left edge, now that all frames have either
+	 * succeeded or failed.
+	 *
+	 * XXX verify this is _actually_ the valid value to begin at!
+	 */
+	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
+	    "%s: tid=3D%p, new BAW left edge=3D%d\n",
+	    __func__,
+	    tid,
+	    tap->txa_start);
+
+	/* Try sending the BAR frame */
+	/* We can't hold the lock here! */
+
+	ATH_TXQ_UNLOCK(sc->sc_ac2q[tid->ac]);
+	if (ieee80211_send_bar(&tid->an->an_node, tap, tap->txa_start) =3D=3D 0) {
+		/* Success? Now we wait for notification that it's done */
+		ATH_TXQ_LOCK(sc->sc_ac2q[tid->ac]);
+		return;
+	}
+
+	/* Failure? For now, warn loudly and continue */
+	ATH_TXQ_LOCK(sc->sc_ac2q[tid->ac]);
+	device_printf(sc->sc_dev, "%s: tid=3D%p, failed to TX BAR, continue!\n",
+	    __func__, tid);
+	ath_tx_tid_bar_unsuspend(sc, tid);
+}
+
+
+/*
  * Free any packets currently pending in the software TX queue.
  *
  * This will be called when a node is being deleted.
@@ -2636,6 +2855,21 @@
=20
 		if (t =3D=3D 0) {
 			device_printf(sc->sc_dev,
+			    "%s: node %p: bf=3D%p: addbaw=3D%d, dobaw=3D%d, "
+			    "seqno_assign=3D%d, seqno_required=3D%d, seqno=3D%d, retry=3D%d\n",
+			    __func__, ni, bf,
+			    bf->bf_state.bfs_addedbaw,
+			    bf->bf_state.bfs_dobaw,
+			    bf->bf_state.bfs_need_seqno,
+			    bf->bf_state.bfs_seqno_assigned,
+			    SEQNO(bf->bf_state.bfs_seqno),
+			    bf->bf_state.bfs_retries);
+			device_printf(sc->sc_dev,
+			    "%s: node %p: bf=3D%p: tid txq_depth=3D%d hwq_depth=3D%d\n",
+			    __func__, ni, bf,
+			    tid->axq_depth,
+			    tid->hwq_depth);
+			device_printf(sc->sc_dev,
 			    "%s: node %p: bf=3D%p: tid %d: txq_depth=3D%d, "
 			    "txq_aggr_depth=3D%d, sched=3D%d, paused=3D%d, "
 			    "hwq_depth=3D%d, incomp=3D%d, baw_head=3D%d, "
@@ -2651,7 +2885,7 @@
 			    mtod(bf->bf_m, const uint8_t *),
 			    bf->bf_m->m_len, 0, -1);
=20
-			//t =3D 1;
+			t =3D 1;
 		}
=20
=20
@@ -2802,7 +3036,7 @@
 	 * punt to rate control if we're not being cleaned up
 	 * during a hw queue drain and the frame wanted an ACK.
 	 */
-	if (fail =3D=3D 0 && ((bf->bf_txflags & HAL_TXDESC_NOACK) =3D=3D 0))
+	if (fail =3D=3D 0 && ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) =3D=
=3D 0))
 		ath_tx_update_ratectrl(sc, ni, bf->bf_state.bfs_rc,
 		    ts, bf->bf_state.bfs_pktlen,
 		    1, (ts->ts_status =3D=3D 0) ? 0 : 1);
@@ -3032,7 +3266,6 @@
 	int tid =3D bf->bf_state.bfs_tid;
 	struct ath_tid *atid =3D &an->an_tid[tid];
 	struct ieee80211_tx_ampdu *tap;
-	int txseq;
=20
 	ATH_TXQ_LOCK(sc->sc_ac2q[atid->ac]);
=20
@@ -3073,19 +3306,15 @@
 		}
 		bf->bf_state.bfs_dobaw =3D 0;
=20
-		/* Send BAR frame */
-		/*
-		 * This'll end up going into net80211 and back out
-		 * again, via ic->ic_raw_xmit().
-		 */
-		txseq =3D tap->txa_start;
+		/* Suspend the TX queue and get ready to send the BAR */
+		ath_tx_tid_bar_suspend(sc, atid);
+
+		/* Send the BAR if there are no other frames waiting */
+		if (ath_tx_tid_bar_tx_ready(sc, atid))
+			ath_tx_tid_bar_tx(sc, atid);
+
 		ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->ac]);
=20
-		device_printf(sc->sc_dev,
-		    "%s: TID %d: send BAR; seq %d\n", __func__, tid, txseq);
-
-		/* XXX TODO: send BAR */
-
 		/* Free buffer, bf is free after this call */
 		ath_tx_default_comp(sc, bf, 0);
 		return;
@@ -3104,6 +3333,9 @@
 	 */
 	ATH_TXQ_INSERT_HEAD(atid, bf, bf_list);
 	ath_tx_tid_sched(sc, atid);
+	/* Send the BAR if there are no other frames waiting */
+	if (ath_tx_tid_bar_tx_ready(sc, atid))
+		ath_tx_tid_bar_tx(sc, atid);
=20
 	ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->ac]);
 }
@@ -3233,17 +3465,20 @@
 	 * in the ifnet TX context or raw TX context.)
 	 */
 	if (drops) {
-		int txseq =3D tap->txa_start;
-		ATH_TXQ_UNLOCK(sc->sc_ac2q[tid->ac]);
-		device_printf(sc->sc_dev,
-		    "%s: TID %d: send BAR; seq %d\n",
-		    __func__, tid->tid, txseq);
-
-		/* XXX TODO: send BAR */
-	} else {
-		ATH_TXQ_UNLOCK(sc->sc_ac2q[tid->ac]);
+		/* Suspend the TX queue and get ready to send the BAR */
+		ath_tx_tid_bar_suspend(sc, tid);
 	}
=20
+	ATH_TXQ_UNLOCK(sc->sc_ac2q[tid->ac]);
+
+	/*
+	 * Send BAR if required
+	 */
+	ATH_TXQ_LOCK(sc->sc_ac2q[tid->ac]);
+	if (ath_tx_tid_bar_tx_ready(sc, tid))
+		ath_tx_tid_bar_tx(sc, tid);
+	ATH_TXQ_UNLOCK(sc->sc_ac2q[tid->ac]);
+
 	/* Complete frames which errored out */
 	while ((bf =3D TAILQ_FIRST(&bf_cq)) !=3D NULL) {
 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
@@ -3283,6 +3518,10 @@
 		atid->cleanup_inprogress =3D 0;
 		ath_tx_tid_resume(sc, atid);
 	}
+
+	/* Send BAR if required */
+	if (ath_tx_tid_bar_tx_ready(sc, atid))
+		ath_tx_tid_bar_tx(sc, atid);
 	ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->ac]);
=20
 	/* Handle frame completion */
@@ -3497,9 +3736,10 @@
 	 * send bar if we dropped any frames
 	 */
 	if (drops) {
-		device_printf(sc->sc_dev,
-		    "%s: TID %d: send BAR; seq %d\n", __func__, tid, txseq);
-		/* XXX TODO: send BAR */
+		/* Suspend the TX queue and get ready to send the BAR */
+		ATH_TXQ_LOCK(sc->sc_ac2q[atid->ac]);
+		ath_tx_tid_bar_suspend(sc, atid);
+		ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->ac]);
 	}
=20
 	/* Prepend all frames to the beginning of the queue */
@@ -3514,6 +3754,14 @@
 	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
 	    "%s: txa_start now %d\n", __func__, tap->txa_start);
=20
+	/*
+	 * Send BAR if required
+	 */
+	ATH_TXQ_LOCK(sc->sc_ac2q[atid->ac]);
+	if (ath_tx_tid_bar_tx_ready(sc, atid))
+		ath_tx_tid_bar_tx(sc, atid);
+	ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->ac]);
+
 	/* Do deferred completion */
 	while ((bf =3D TAILQ_FIRST(&bf_cq)) !=3D NULL) {
 		TAILQ_REMOVE(&bf_cq, bf, bf_list);
@@ -3543,7 +3791,7 @@
 	 *
 	 * Do it outside of the TXQ lock.
 	 */
-	if (fail =3D=3D 0 && ((bf->bf_txflags & HAL_TXDESC_NOACK) =3D=3D 0))
+	if (fail =3D=3D 0 && ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) =3D=
=3D 0))
 		ath_tx_update_ratectrl(sc, ni, bf->bf_state.bfs_rc,
 		    &bf->bf_status.ds_txstat,
 		    bf->bf_state.bfs_pktlen,
@@ -3607,6 +3855,12 @@
 			    __func__, SEQNO(bf->bf_state.bfs_seqno));
 	}
=20
+	/*
+	 * Send BAR if required
+	 */
+	if (ath_tx_tid_bar_tx_ready(sc, atid))
+		ath_tx_tid_bar_tx(sc, atid);
+
 	ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->ac]);
=20
 	ath_tx_default_comp(sc, bf, fail);
@@ -3677,8 +3931,10 @@
 			ATH_TXQ_REMOVE(tid, bf, bf_list);
 			bf->bf_state.bfs_aggr =3D 0;
 			ath_tx_do_ratelookup(sc, bf);
+			ath_tx_calc_duration(sc, bf);
+			ath_tx_calc_protection(sc, bf);
+			ath_tx_set_rtscts(sc, bf);
 			ath_tx_rate_fill_rcflags(sc, bf);
-			ath_tx_set_rtscts(sc, bf);
 			ath_tx_setds(sc, bf);
 			ath_tx_chaindesclist(sc, bf);
 			ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);
@@ -3703,6 +3959,11 @@
 		ath_tx_do_ratelookup(sc, bf);
 		bf->bf_state.bfs_rc[3].rix =3D 0;
 		bf->bf_state.bfs_rc[3].tries =3D 0;
+
+		ath_tx_calc_duration(sc, bf);
+		ath_tx_calc_protection(sc, bf);
+
+		ath_tx_set_rtscts(sc, bf);
 		ath_tx_rate_fill_rcflags(sc, bf);
=20
 		status =3D ath_tx_form_aggr(sc, an, tid, &bf_q);
@@ -3722,6 +3983,9 @@
 		 */
 		bf =3D TAILQ_FIRST(&bf_q);
=20
+		if (status =3D=3D ATH_AGGR_8K_LIMITED)
+			sc->sc_aggr_stats.aggr_rts_aggr_limited++;
+
 		/*
 		 * If it's the only frame send as non-aggregate
 		 * assume that ath_tx_form_aggr() has checked
@@ -3731,7 +3995,6 @@
 			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
 			    "%s: single-frame aggregate\n", __func__);
 			bf->bf_state.bfs_aggr =3D 0;
-			ath_tx_set_rtscts(sc, bf);
 			ath_tx_setds(sc, bf);
 			ath_tx_chaindesclist(sc, bf);
 			ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);
@@ -3751,6 +4014,12 @@
 			sc->sc_aggr_stats.aggr_aggr_pkt++;
=20
 			/*
+			 * Calculate the duration/protection as required.
+			 */
+			ath_tx_calc_duration(sc, bf);
+			ath_tx_calc_protection(sc, bf);
+
+			/*
 			 * Update the rate and rtscts information based on the
 			 * rate decision made by the rate control code;
 			 * the first frame in the aggregate needs it.
@@ -3851,8 +4120,10 @@
=20
 		/* Program descriptors + rate control */
 		ath_tx_do_ratelookup(sc, bf);
+		ath_tx_calc_duration(sc, bf);
+		ath_tx_calc_protection(sc, bf);
+		ath_tx_set_rtscts(sc, bf);
 		ath_tx_rate_fill_rcflags(sc, bf);
-		ath_tx_set_rtscts(sc, bf);
 		ath_tx_setds(sc, bf);
 		ath_tx_chaindesclist(sc, bf);
 		ath_tx_set_ratectrl(sc, ni, bf);
@@ -3943,14 +4214,11 @@
 {
 	struct ieee80211_node *ni =3D &an->an_node;
 	struct ieee80211_tx_ampdu *tap;
-	int ac;
=20
 	if (tid =3D=3D IEEE80211_NONQOS_TID)
 		return NULL;
=20
-	ac =3D TID_TO_WME_AC(tid);
-
-	tap =3D &ni->ni_tx_ampdu[ac];
+	tap =3D &ni->ni_tx_ampdu[tid];
 	return tap;
 }
=20
@@ -4008,7 +4276,7 @@
     int dialogtoken, int baparamset, int batimeout)
 {
 	struct ath_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
-	int tid =3D WME_AC_TO_TID(tap->txa_ac);
+	int tid =3D tap->txa_tid;
 	struct ath_node *an =3D ATH_NODE(ni);
 	struct ath_tid *atid =3D &an->an_tid[tid];
=20
@@ -4035,7 +4303,9 @@
 	 * it'll be "after" the left edge of the BAW and thus it'll
 	 * fall within it.
 	 */
+	ATH_TXQ_LOCK(sc->sc_ac2q[atid->tid]);
 	ath_tx_tid_pause(sc, atid);
+	ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->tid]);
=20
 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
 	    "%s: called; dialogtoken=3D%d, baparamset=3D%d, batimeout=3D%d\n",
@@ -4073,7 +4343,7 @@
     int status, int code, int batimeout)
 {
 	struct ath_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
-	int tid =3D WME_AC_TO_TID(tap->txa_ac);
+	int tid =3D tap->txa_tid;
 	struct ath_node *an =3D ATH_NODE(ni);
 	struct ath_tid *atid =3D &an->an_tid[tid];
 	int r;
@@ -4114,14 +4384,16 @@
 ath_addba_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
 {
 	struct ath_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
-	int tid =3D WME_AC_TO_TID(tap->txa_ac);
+	int tid =3D tap->txa_tid;
 	struct ath_node *an =3D ATH_NODE(ni);
 	struct ath_tid *atid =3D &an->an_tid[tid];
=20
 	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: called\n", __func__);
=20
 	/* Pause TID traffic early, so there aren't any races */
+	ATH_TXQ_LOCK(sc->sc_ac2q[atid->tid]);
 	ath_tx_tid_pause(sc, atid);
+	ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->tid]);
=20
 	/* There's no need to hold the TXQ lock here */
 	sc->sc_addba_stop(ni, tap);
@@ -4149,7 +4421,7 @@
     int status)
 {
 	struct ath_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
-	int tid =3D WME_AC_TO_TID(tap->txa_ac);
+	int tid =3D tap->txa_tid;
 	struct ath_node *an =3D ATH_NODE(ni);
 	struct ath_tid *atid =3D &an->an_tid[tid];
 	int attempts =3D tap->txa_attempts;
@@ -4168,7 +4440,7 @@
 	 */
 	if (status =3D=3D 0 || attempts =3D=3D 50) {
 		ATH_TXQ_LOCK(sc->sc_ac2q[atid->ac]);
-		ath_tx_tid_resume(sc, atid);
+		ath_tx_tid_bar_unsuspend(sc, atid);
 		ATH_TXQ_UNLOCK(sc->sc_ac2q[atid->ac]);
 	}
 }
@@ -4182,7 +4454,7 @@
     struct ieee80211_tx_ampdu *tap)
 {
 	struct ath_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
-	int tid =3D WME_AC_TO_TID(tap->txa_ac);
+	int tid =3D tap->txa_tid;
 	struct ath_node *an =3D ATH_NODE(ni);
 	struct ath_tid *atid =3D &an->an_tid[tid];
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_ath_tx_ht.c
--- a/head/sys/dev/ath/if_ath_tx_ht.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_ath_tx_ht.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_tx_ht.c 233227 2012-03-20 04:5=
0:25Z adrian $");
+__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath_tx_ht.c 233988 2012-04-07 05:4=
6:00Z adrian $");
=20
 #include "opt_inet.h"
 #include "opt_ath.h"
@@ -245,7 +245,7 @@
 		 */
 		rc[i].ratecode =3D rate;
=20
-		if (bf->bf_state.bfs_flags &
+		if (bf->bf_state.bfs_txflags &
 		    (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA))
 			rc[i].flags |=3D ATH_RC_RTSCTS_FLAG;
=20
@@ -445,7 +445,7 @@
 	const HAL_RATE_TABLE *rt =3D sc->sc_currates;
 	int i;
 	int pktlen;
-	int flags =3D bf->bf_state.bfs_flags;
+	int flags =3D bf->bf_state.bfs_txflags;
 	struct ath_rc_series *rc =3D bf->bf_state.bfs_rc;
=20
 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
@@ -566,7 +566,7 @@
 	struct ath_hal *ah =3D sc->sc_ah;
 	int is_pspoll =3D (bf->bf_state.bfs_atype =3D=3D HAL_PKT_TYPE_PSPOLL);
 	int ctsrate =3D bf->bf_state.bfs_ctsrate;
-	int flags =3D bf->bf_state.bfs_flags;
+	int flags =3D bf->bf_state.bfs_txflags;
=20
 	/* Setup rate scenario */
 	memset(&series, 0, sizeof(series));
@@ -652,7 +652,6 @@
 	int status =3D ATH_AGGR_DONE;
 	int prev_frames =3D 0;	/* XXX for AR5416 burst, not done here */
 	int prev_al =3D 0;	/* XXX also for AR5416 burst */
-	int seqno;
=20
 	ATH_TXQ_LOCK_ASSERT(sc->sc_ac2q[tid->ac]);
=20
@@ -708,14 +707,6 @@
 		 */
=20
 		/*
-		 * XXX TODO: AR5416 has an 8K aggregation size limit
-		 * when RTS is enabled, and RTS is required for dual-stream
-		 * rates.
-		 *
-		 * For now, limit all aggregates for the AR5416 to be 8K.
-		 */
-
-		/*
 		 * do not exceed aggregation limit
 		 */
 		al_delta =3D ATH_AGGR_DELIM_SZ + bf->bf_state.bfs_pktlen;
@@ -726,6 +717,20 @@
 		}
=20
 		/*
+		 * If RTS/CTS is set on the first frame, enforce
+		 * the RTS aggregate limit.
+		 */
+		if (bf_first->bf_state.bfs_txflags &
+		    (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
+			if (nframes &&
+			   (sc->sc_rts_aggr_limit <
+			     (al + bpad + al_delta + prev_al))) {
+				status =3D ATH_AGGR_8K_LIMITED;
+				break;
+			}
+		}
+
+		/*
 		 * Do not exceed subframe limit.
 		 */
 		if ((nframes + prev_frames) >=3D MIN((h_baw),
@@ -735,7 +740,20 @@
 		}
=20
 		/*
-		 * TODO: If it's _before_ the BAW left edge, complain very loudly.
+		 * If the current frame has an RTS/CTS configuration
+		 * that differs from the first frame, override the
+		 * subsequent frame with this config.
+		 */
+		bf->bf_state.bfs_txflags &=3D
+		    (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA);
+		bf->bf_state.bfs_txflags |=3D
+		    bf_first->bf_state.bfs_txflags &
+		    (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA);
+
+		/*
+		 * TODO: If it's _before_ the BAW left edge, complain very
+		 * loudly.
+		 *
 		 * This means something (else) has slid the left edge along
 		 * before we got a chance to be TXed.
 		 */
@@ -747,13 +765,32 @@
 		 * see ath_tx_xmit_aggr() for more info.
 		 */
 		if (bf->bf_state.bfs_dobaw) {
+			ieee80211_seq seqno;
+
+			/*
+			 * If the sequence number is allocated, use it.
+			 * Otherwise, use the sequence number we WOULD
+			 * allocate.
+			 */
+			if (bf->bf_state.bfs_seqno_assigned)
+				seqno =3D SEQNO(bf->bf_state.bfs_seqno);
+			else
+				seqno =3D ni->ni_txseqs[bf->bf_state.bfs_tid];
+
+			/*
+			 * Check whether either the currently allocated
+			 * sequence number _OR_ the to-be allocated
+			 * sequence number is inside the BAW.
+			 */
 			if (! BAW_WITHIN(tap->txa_start, tap->txa_wnd,
-			    ni->ni_txseqs[bf->bf_state.bfs_tid])) {
+			    seqno)) {
 				status =3D ATH_AGGR_BAW_CLOSED;
 				break;
 			}
+
 			/* XXX check for bfs_need_seqno? */
 			if (! bf->bf_state.bfs_seqno_assigned) {
+				int seqno;
 				seqno =3D ath_tx_tid_seqno_assign(sc, ni, bf, bf->bf_m);
 				if (seqno < 0) {
 					device_printf(sc->sc_dev,
@@ -796,19 +833,14 @@
 		bf->bf_state.bfs_addedbaw =3D 1;
=20
 		/*
-		 * XXX TODO: If any frame in the aggregate requires RTS/CTS,
-		 * set the first frame.
-		 */
-
-		/*
 		 * XXX enforce ACK for aggregate frames (this needs to be
 		 * XXX handled more gracefully?
 		 */
-		if (bf->bf_state.bfs_flags & HAL_TXDESC_NOACK) {
+		if (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) {
 			device_printf(sc->sc_dev,
 			    "%s: HAL_TXDESC_NOACK set for an aggregate frame?\n",
 			    __func__);
-			bf->bf_state.bfs_flags &=3D (~HAL_TXDESC_NOACK);
+			bf->bf_state.bfs_txflags &=3D (~HAL_TXDESC_NOACK);
 		}
=20
 		/*
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_athioctl.h
--- a/head/sys/dev/ath/if_athioctl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_athioctl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: head/sys/dev/ath/if_athioctl.h 232764 2012-03-10 04:14:04Z ad=
rian $
+ * $FreeBSD: head/sys/dev/ath/if_athioctl.h 234090 2012-04-10 07:23:37Z ad=
rian $
  */
=20
 /*
@@ -43,6 +43,11 @@
 	u_int32_t	aggr_baw_closed_single_pkt;
 	u_int32_t	aggr_low_hwq_single_pkt;
 	u_int32_t	aggr_sched_nopkt;
+	u_int32_t	aggr_rts_aggr_limited;
+};
+
+struct ath_intr_stats {
+	u_int32_t	sync_intr[32];
 };
=20
 struct ath_stats {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ath/if_athvar.h
--- a/head/sys/dev/ath/if_athvar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ath/if_athvar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: head/sys/dev/ath/if_athvar.h 233227 2012-03-20 04:50:25Z adri=
an $
+ * $FreeBSD: head/sys/dev/ath/if_athvar.h 234369 2012-04-17 06:02:41Z adri=
an $
  */
=20
 /*
@@ -47,7 +47,7 @@
  * 802.11n requires more TX and RX buffers to do AMPDU.
  */
 #ifdef	ATH_ENABLE_11N
-#define	ATH_TXBUF	512
+#define	ATH_TXBUF	128
 #define	ATH_RXBUF	512
 #endif
=20
@@ -106,6 +106,8 @@
 	TAILQ_ENTRY(ath_tid)	axq_qelem;
 	int			sched;
 	int			paused;	/* >0 if the TID has been paused */
+	int			bar_wait;	/* waiting for BAR */
+	int			bar_tx;		/* BAR TXed */
=20
 	/*
 	 * Is the TID being cleaned up after a transition
@@ -173,7 +175,6 @@
 	TAILQ_ENTRY(ath_buf)	bf_list;
 	struct ath_buf *	bf_next;	/* next buffer in the aggregate */
 	int			bf_nseg;
-	uint16_t		bf_txflags;	/* tx descriptor flags */
 	uint16_t		bf_flags;	/* status flags (below) */
 	struct ath_desc		*bf_desc;	/* virtual addr of desc */
 	struct ath_desc_status	bf_status;	/* tx/rx status */
@@ -205,18 +206,19 @@
 		uint16_t bfs_nframes;	/* number of frames in aggregate */
 		uint16_t bfs_ndelim;	/* number of delims for padding */
=20
-		int bfs_aggr:1;		/* part of aggregate? */
-		int bfs_aggrburst:1;	/* part of aggregate burst? */
-		int bfs_isretried:1;	/* retried frame? */
-		int bfs_dobaw:1;	/* actually check against BAW? */
-		int bfs_addedbaw:1;	/* has been added to the BAW */
-		int bfs_shpream:1;	/* use short preamble */
-		int bfs_istxfrag:1;	/* is fragmented */
-		int bfs_ismrr:1;	/* do multi-rate TX retry */
-		int bfs_doprot:1;	/* do RTS/CTS based protection */
-		int bfs_doratelookup:1;	/* do rate lookup before each TX */
-		int bfs_need_seqno:1;	/* need to assign a seqno for aggregation */
-		int bfs_seqno_assigned:1;	/* seqno has been assigned */
+		u_int32_t bfs_aggr:1,		/* part of aggregate? */
+		    bfs_aggrburst:1,	/* part of aggregate burst? */
+		    bfs_isretried:1,	/* retried frame? */
+		    bfs_dobaw:1,	/* actually check against BAW? */
+		    bfs_addedbaw:1,	/* has been added to the BAW */
+		    bfs_shpream:1,	/* use short preamble */
+		    bfs_istxfrag:1,	/* is fragmented */
+		    bfs_ismrr:1,	/* do multi-rate TX retry */
+		    bfs_doprot:1,	/* do RTS/CTS based protection */
+		    bfs_doratelookup:1,	/* do rate lookup before each TX */
+		    bfs_need_seqno:1,	/* need to assign a seqno for aggr */
+		    bfs_seqno_assigned:1;	/* seqno has been assigned */
+
 		int bfs_nfl;		/* next fragment length */
=20
 		/*
@@ -227,7 +229,7 @@
 		int bfs_pktlen;		/* length of this packet */
 		int bfs_hdrlen;		/* length of this packet header */
 		uint16_t bfs_al;	/* length of aggregate */
-		int bfs_flags;		/* HAL descriptor flags */
+		int bfs_txflags;	/* HAL (tx) descriptor flags */
 		int bfs_txrate0;	/* first TX rate */
 		int bfs_try0;		/* first try count */
 		uint8_t bfs_ctsrate0;	/* Non-zero - use this as ctsrate */
@@ -348,6 +350,7 @@
 	struct ifnet		*sc_ifp;	/* interface common */
 	struct ath_stats	sc_stats;	/* interface statistics */
 	struct ath_tx_aggr_stats	sc_aggr_stats;
+	struct ath_intr_stats	sc_intr_stats;
 	int			sc_debug;
 	int			sc_nvaps;	/* # vaps */
 	int			sc_nstavaps;	/* # station vaps */
@@ -490,6 +493,7 @@
 	struct ath_txq		sc_txq[HAL_NUM_TX_QUEUES];
 	struct ath_txq		*sc_ac2q[5];	/* WME AC -> h/w q map */=20
 	struct task		sc_txtask;	/* tx int processing */
+	struct task		sc_txqtask;	/* tx proc processing */
 	int			sc_wd_timer;	/* count down for wd timer */
 	struct callout		sc_wd_ch;	/* tx watchdog timer */
 	struct ath_tx_radiotap_header sc_tx_th;
@@ -504,6 +508,7 @@
 	struct task		sc_bmisstask;	/* bmiss int processing */
 	struct task		sc_bstucktask;	/* stuck beacon processing */
 	struct task		sc_resettask;	/* interface reset task */
+	struct task		sc_fataltask;	/* fatal task */
 	enum {
 		OK,				/* no change needed */
 		UPDATE,				/* update pending */
@@ -531,6 +536,7 @@
 	uint16_t		*sc_eepromdata;	/* Local eeprom data, if AR9100 */
 	int			sc_txchainmask;	/* currently configured TX chainmask */
 	int			sc_rxchainmask;	/* currently configured RX chainmask */
+	int			sc_rts_aggr_limit;	/* TX limit on RTS aggregates */
=20
 	/* Queue limits */
=20
@@ -956,10 +962,10 @@
 	((*(_ah)->ah_setupFirstTxDesc)((_ah), (_ds), (_aggrlen), (_flags), \
 	(_txpower), (_txr0), (_txtr0), (_antm), (_rcr), (_rcd)))
 #define	ath_hal_chaintxdesc(_ah, _ds, _pktlen, _hdrlen, _type, _keyix, \
-	_cipher, _delims, _seglen, _first, _last) \
+	_cipher, _delims, _seglen, _first, _last, _lastaggr) \
 	((*(_ah)->ah_chainTxDesc)((_ah), (_ds), (_pktlen), (_hdrlen), \
 	(_type), (_keyix), (_cipher), (_delims), (_seglen), \
-	(_first), (_last)))
+	(_first), (_last), (_lastaggr)))
 #define	ath_hal_setuplasttxdesc(_ah, _ds, _ds0) \
 	((*(_ah)->ah_setupLastTxDesc)((_ah), (_ds), (_ds0)))
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/atkbdc/atkbdc_isa.c
--- a/head/sys/dev/atkbdc/atkbdc_isa.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/atkbdc/atkbdc_isa.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/atkbdc/atkbdc_isa.c 233619 2012-03-28 17:=
58:37Z jkim $");
=20
 #include "opt_kbd.h"
=20
@@ -87,6 +87,7 @@
=20
 static struct isa_pnp_id atkbdc_ids[] =3D {
 	{ 0x0303d041, "Keyboard controller (i8042)" },	/* PNP0303 */
+	{ 0x2003d041, "Keyboard controller (i8042)" },	/* PNP0320 */
 	{ 0 }
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/atkbdc/psm.c
--- a/head/sys/dev/atkbdc/psm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/atkbdc/psm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -59,7 +59,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/atkbdc/psm.c 227309 2011-11-07 15:43:11Z =
ed $");
+__FBSDID("$FreeBSD: head/sys/dev/atkbdc/psm.c 233580 2012-03-27 23:43:01Z =
jkim $");
=20
 #include "opt_isa.h"
 #include "opt_psm.h"
@@ -318,13 +318,11 @@
 #define	PSM_CONFIG_IGNPORTERROR	0x1000  /* ignore error in aux port test */
 #define	PSM_CONFIG_HOOKRESUME	0x2000	/* hook the system resume event */
 #define	PSM_CONFIG_INITAFTERSUSPEND 0x4000 /* init the device at the resum=
e event */
-#define	PSM_CONFIG_SYNCHACK	0x8000	/* enable `out-of-sync' hack */
=20
 #define	PSM_CONFIG_FLAGS	\
     (PSM_CONFIG_RESOLUTION |	\
     PSM_CONFIG_ACCEL |		\
     PSM_CONFIG_NOCHECKSYNC |	\
-    PSM_CONFIG_SYNCHACK |	\
     PSM_CONFIG_NOIDPROBE |	\
     PSM_CONFIG_NORESET |	\
     PSM_CONFIG_FORCETAP |	\
@@ -415,7 +413,7 @@
 		    u_char *);
=20
 /* vendor specific features */
-typedef int	probefunc_t(struct psm_softc *);
+typedef int	probefunc_t(KBDC, struct psm_softc *);
=20
 static int	mouse_id_proc1(KBDC, int, int, int *);
 static int	mouse_ext_command(KBDC, int);
@@ -822,24 +820,10 @@
 	}
 	empty_both_buffers(kbdc, 10);	/* remove stray data if any */
=20
-	if (sc->config & PSM_CONFIG_NOIDPROBE)
-		i =3D GENERIC_MOUSE_ENTRY;
-	else {
-		/* FIXME: hardware ID, mouse buttons? */
-
-		/* other parameters */
-		for (i =3D 0; vendortype[i].probefunc !=3D NULL; ++i)
-			if ((*vendortype[i].probefunc)(sc)) {
-				if (verbose >=3D 2)
-					log(LOG_ERR, "psm%d: found %s\n",
-					    sc->unit,
-					    model_name(vendortype[i].model));
-				break;
-			}
-	}
-
-	sc->hw.model =3D vendortype[i].model;
-	sc->mode.packetsize =3D vendortype[i].packetsize;
+	/* Re-enable the mouse. */
+	for (i =3D 0; vendortype[i].probefunc !=3D NULL; ++i)
+		if (vendortype[i].model =3D=3D sc->hw.model)
+			(*vendortype[i].probefunc)(sc->kbdc, NULL);
=20
 	/* set mouse parameters */
 	if (mode !=3D (mousemode_t *)NULL) {
@@ -1149,7 +1133,7 @@
 #if defined(PSM_HOOKRESUME) || defined(PSM_HOOKAPM)
 	sc->config |=3D
 #ifdef PSM_RESETAFTERSUSPEND
-	PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
+	PSM_CONFIG_INITAFTERSUSPEND;
 #else
 	PSM_CONFIG_HOOKRESUME;
 #endif
@@ -1338,7 +1322,7 @@
=20
 		/* other parameters */
 		for (i =3D 0; vendortype[i].probefunc !=3D NULL; ++i)
-			if ((*vendortype[i].probefunc)(sc)) {
+			if ((*vendortype[i].probefunc)(sc->kbdc, sc)) {
 				if (verbose >=3D 2)
 					printf("psm%d: found %s\n", unit,
 					    model_name(vendortype[i].model));
@@ -1454,6 +1438,19 @@
 	sc->bdev =3D make_dev(&psm_cdevsw, 0, 0, 0, 0666, "bpsm%d", unit);
 	sc->bdev->si_drv1 =3D sc;
=20
+	/* Some touchpad devices need full reinitialization after suspend. */
+	switch (sc->hw.model) {
+	case MOUSE_MODEL_SYNAPTICS:
+	case MOUSE_MODEL_GLIDEPOINT:
+	case MOUSE_MODEL_VERSAPAD:
+		sc->config |=3D PSM_CONFIG_INITAFTERSUSPEND;
+		break;
+	default:
+		if (sc->synhw.infoMajor >=3D 4)
+			sc->config |=3D PSM_CONFIG_INITAFTERSUSPEND;
+		break;
+	}
+
 	if (!verbose)
 		printf("psm%d: model %s, device ID %d\n",
 		    unit, model_name(sc->hw.model), sc->hw.hwid & 0x00ff);
@@ -1952,7 +1949,7 @@
=20
 	case MOUSE_SYN_GETHWINFO:
 		s =3D spltty();
-		if (synaptics_support && sc->hw.model =3D=3D MOUSE_MODEL_SYNAPTICS)
+		if (sc->synhw.infoMajor >=3D 4)
 			*(synapticshw_t *)addr =3D sc->synhw;
 		else
 			error =3D EINVAL;
@@ -3566,12 +3563,12 @@
 #ifdef notyet
 /* Logitech MouseMan Cordless II */
 static int
-enable_lcordless(struct psm_softc *sc)
+enable_lcordless(KDBC kbdc, struct psm_softc *sc)
 {
 	int status[3];
 	int ch;
=20
-	if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 2, status))
+	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 2, status))
 		return (FALSE);
 	if (status[1] =3D=3D PSMD_RES_HIGH)
 		return (FALSE);
@@ -3588,7 +3585,7 @@
=20
 /* Genius NetScroll Mouse, MouseSystems SmartScroll Mouse */
 static int
-enable_groller(struct psm_softc *sc)
+enable_groller(KBDC kbdc, struct psm_softc *sc)
 {
 	int status[3];
=20
@@ -3613,18 +3610,19 @@
 	 * byte 3 report rate (?)
 	 */
=20
-	if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
+	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
 		return (FALSE);
 	if ((status[1] !=3D '3') || (status[2] !=3D 'D'))
 		return (FALSE);
 	/* FIXME: SmartScroll Mouse has 5 buttons! XXX */
-	sc->hw.buttons =3D 4;
+	if (sc !=3D NULL)
+		sc->hw.buttons =3D 4;
 	return (TRUE);
 }
=20
 /* Genius NetMouse/NetMouse Pro, ASCII Mie Mouse, NetScroll Optical */
 static int
-enable_gmouse(struct psm_softc *sc)
+enable_gmouse(KBDC kbdc, struct psm_softc *sc)
 {
 	int status[3];
=20
@@ -3638,7 +3636,7 @@
 	 * say they have three buttons too and they do have a button on the
 	 * side...
 	 */
-	if (!mouse_id_proc1(sc->kbdc, PSMD_RES_HIGH, 1, status))
+	if (!mouse_id_proc1(kbdc, PSMD_RES_HIGH, 1, status))
 		return (FALSE);
 	if ((status[1] !=3D '3') || (status[2] !=3D 'U'))
 		return (FALSE);
@@ -3647,7 +3645,7 @@
=20
 /* ALPS GlidePoint */
 static int
-enable_aglide(struct psm_softc *sc)
+enable_aglide(KBDC kbdc, struct psm_softc *sc)
 {
 	int status[3];
=20
@@ -3658,9 +3656,9 @@
 	 * NOTE: ALPS produces several models of GlidePoint. Some of those
 	 * do not respond to this sequence, thus, cannot be detected this way.
 	 */
-	if (set_mouse_sampling_rate(sc->kbdc, 100) !=3D 100)
+	if (set_mouse_sampling_rate(kbdc, 100) !=3D 100)
 		return (FALSE);
-	if (!mouse_id_proc1(sc->kbdc, PSMD_RES_LOW, 2, status))
+	if (!mouse_id_proc1(kbdc, PSMD_RES_LOW, 2, status))
 		return (FALSE);
 	if ((status[1] =3D=3D PSMD_RES_LOW) || (status[2] =3D=3D 100))
 		return (FALSE);
@@ -3669,10 +3667,9 @@
=20
 /* Kensington ThinkingMouse/Trackball */
 static int
-enable_kmouse(struct psm_softc *sc)
+enable_kmouse(KBDC kbdc, struct psm_softc *sc)
 {
 	static u_char rate[] =3D { 20, 60, 40, 20, 20, 60, 40, 20, 20 };
-	KBDC kbdc =3D sc->kbdc;
 	int status[3];
 	int id1;
 	int id2;
@@ -3723,9 +3720,8 @@
=20
 /* Logitech MouseMan+/FirstMouse+, IBM ScrollPoint Mouse */
 static int
-enable_mmanplus(struct psm_softc *sc)
+enable_mmanplus(KBDC kbdc, struct psm_softc *sc)
 {
-	KBDC kbdc =3D sc->kbdc;
 	int data[3];
=20
 	/* the special sequence to enable the fourth button and the roller. */
@@ -3766,8 +3762,10 @@
 	if (MOUSE_PS2PLUS_PACKET_TYPE(data) !=3D 0)
 		return (FALSE);
=20
-	sc->hw.hwid &=3D 0x00ff;
-	sc->hw.hwid |=3D data[2] << 8;	/* save model ID */
+	if (sc !=3D NULL) {
+		sc->hw.hwid &=3D 0x00ff;
+		sc->hw.hwid |=3D data[2] << 8;	/* save model ID */
+	}
=20
 	/*
 	 * MouseMan+ (or FirstMouse+) is now in its native mode, in which
@@ -3780,11 +3778,10 @@
=20
 /* MS IntelliMouse Explorer */
 static int
-enable_msexplorer(struct psm_softc *sc)
+enable_msexplorer(KBDC kbdc, struct psm_softc *sc)
 {
 	static u_char rate0[] =3D { 200, 100, 80, };
 	static u_char rate1[] =3D { 200, 200, 80, };
-	KBDC kbdc =3D sc->kbdc;
 	int id;
 	int i;
=20
@@ -3793,7 +3790,7 @@
 	 * straight to Explorer mode, but need to be set to Intelli mode
 	 * first.
 	 */
-	enable_msintelli(sc);
+	enable_msintelli(kbdc, sc);
=20
 	/* the special sequence to enable the extra buttons and the roller. */
 	for (i =3D 0; i < sizeof(rate1)/sizeof(rate1[0]); ++i)
@@ -3804,8 +3801,10 @@
 	if (id !=3D PSM_EXPLORER_ID)
 		return (FALSE);
=20
-	sc->hw.hwid =3D id;
-	sc->hw.buttons =3D 5;		/* IntelliMouse Explorer XXX */
+	if (sc !=3D NULL) {
+		sc->hw.buttons =3D 5;	/* IntelliMouse Explorer XXX */
+		sc->hw.hwid =3D id;
+	}
=20
 	/*
 	 * XXX: this is a kludge to fool some KVM switch products
@@ -3820,14 +3819,14 @@
 	for (i =3D 0; i < sizeof(rate0)/sizeof(rate0[0]); ++i)
 		if (set_mouse_sampling_rate(kbdc, rate0[i]) !=3D rate0[i])
 			break;
-	id =3D get_aux_id(kbdc);
+	get_aux_id(kbdc);
=20
 	return (TRUE);
 }
=20
 /* MS IntelliMouse */
 static int
-enable_msintelli(struct psm_softc *sc)
+enable_msintelli(KBDC kbdc, struct psm_softc *sc)
 {
 	/*
 	 * Logitech MouseMan+ and FirstMouse+ will also respond to this
@@ -3835,7 +3834,6 @@
 	 */
=20
 	static u_char rate[] =3D { 200, 100, 80, };
-	KBDC kbdc =3D sc->kbdc;
 	int id;
 	int i;
=20
@@ -3848,22 +3846,23 @@
 	if (id !=3D PSM_INTELLI_ID)
 		return (FALSE);
=20
-	sc->hw.hwid =3D id;
-	sc->hw.buttons =3D 3;
+	if (sc !=3D NULL) {
+		sc->hw.buttons =3D 3;
+		sc->hw.hwid =3D id;
+	}
=20
 	return (TRUE);
 }
=20
 /* A4 Tech 4D Mouse */
 static int
-enable_4dmouse(struct psm_softc *sc)
+enable_4dmouse(KBDC kbdc, struct psm_softc *sc)
 {
 	/*
 	 * Newer wheel mice from A4 Tech may use the 4D+ protocol.
 	 */
=20
 	static u_char rate[] =3D { 200, 100, 80, 60, 40, 20 };
-	KBDC kbdc =3D sc->kbdc;
 	int id;
 	int i;
=20
@@ -3879,21 +3878,22 @@
 	if (id !=3D PSM_4DMOUSE_ID)
 		return (FALSE);
=20
-	sc->hw.hwid =3D id;
-	sc->hw.buttons =3D 3;		/* XXX some 4D mice have 4? */
+	if (sc !=3D NULL) {
+		sc->hw.buttons =3D 3;	/* XXX some 4D mice have 4? */
+		sc->hw.hwid =3D id;
+	}
=20
 	return (TRUE);
 }
=20
 /* A4 Tech 4D+ Mouse */
 static int
-enable_4dplus(struct psm_softc *sc)
+enable_4dplus(KBDC kbdc, struct psm_softc *sc)
 {
 	/*
 	 * Newer wheel mice from A4 Tech seem to use this protocol.
 	 * Older models are recognized as either 4D Mouse or IntelliMouse.
 	 */
-	KBDC kbdc =3D sc->kbdc;
 	int id;
=20
 	/*
@@ -3909,16 +3909,17 @@
 	id =3D get_aux_id(kbdc);
 	switch (id) {
 	case PSM_4DPLUS_ID:
-		sc->hw.buttons =3D 4;
 		break;
 	case PSM_4DPLUS_RFSW35_ID:
-		sc->hw.buttons =3D 3;
 		break;
 	default:
 		return (FALSE);
 	}
=20
-	sc->hw.hwid =3D id;
+	if (sc !=3D NULL) {
+		sc->hw.buttons =3D (id =3D=3D PSM_4DPLUS_ID) ? 4 : 3;
+		sc->hw.hwid =3D id;
+	}
=20
 	return (TRUE);
 }
@@ -4307,18 +4308,13 @@
 }
=20
 static int
-enable_synaptics(struct psm_softc *sc)
+enable_synaptics(KBDC kbdc, struct psm_softc *sc)
 {
+	synapticshw_t synhw;
 	int status[3];
-	KBDC kbdc;
-
-	if (!synaptics_support)
-		return (FALSE);
-
-	kbdc =3D sc->kbdc;
+	int buttons;
+
 	VLOG(3, (LOG_DEBUG, "synaptics: BEGIN init\n"));
-	sc->hw.buttons =3D 3;
-	sc->squelch =3D 0;
=20
 	/*
 	 * Just to be on the safe side: this avoids troubles with
@@ -4336,14 +4332,15 @@
 	if (status[1] !=3D 0x47)
 		return (FALSE);
=20
-	sc->synhw.infoMinor =3D status[0];
-	sc->synhw.infoMajor =3D status[2] & 0x0f;
+	bzero(&synhw, sizeof(synhw));
+	synhw.infoMinor =3D status[0];
+	synhw.infoMajor =3D status[2] & 0x0f;
=20
 	if (verbose >=3D 2)
-		printf("Synaptics Touchpad v%d.%d\n", sc->synhw.infoMajor,
-		    sc->synhw.infoMinor);
-
-	if (sc->synhw.infoMajor < 4) {
+		printf("Synaptics Touchpad v%d.%d\n", synhw.infoMajor,
+		    synhw.infoMinor);
+
+	if (synhw.infoMajor < 4) {
 		printf("  Unsupported (pre-v4) Touchpad detected\n");
 		return (FALSE);
 	}
@@ -4358,25 +4355,25 @@
 		return (FALSE);
 	}
=20
-	sc->synhw.infoRot180   =3D (status[0] & 0x80) >> 7;
-	sc->synhw.infoPortrait =3D (status[0] & 0x40) >> 6;
-	sc->synhw.infoSensor   =3D  status[0] & 0x3f;
-	sc->synhw.infoHardware =3D (status[1] & 0xfe) >> 1;
-	sc->synhw.infoNewAbs   =3D (status[2] & 0x80) >> 7;
-	sc->synhw.capPen       =3D (status[2] & 0x40) >> 6;
-	sc->synhw.infoSimplC   =3D (status[2] & 0x20) >> 5;
-	sc->synhw.infoGeometry =3D  status[2] & 0x0f;
+	synhw.infoRot180   =3D (status[0] & 0x80) !=3D 0;
+	synhw.infoPortrait =3D (status[0] & 0x40) !=3D 0;
+	synhw.infoSensor   =3D  status[0] & 0x3f;
+	synhw.infoHardware =3D (status[1] & 0xfe) >> 1;
+	synhw.infoNewAbs   =3D (status[2] & 0x80) !=3D 0;
+	synhw.capPen       =3D (status[2] & 0x40) !=3D 0;
+	synhw.infoSimplC   =3D (status[2] & 0x20) !=3D 0;
+	synhw.infoGeometry =3D  status[2] & 0x0f;
=20
 	if (verbose >=3D 2) {
 		printf("  Model information:\n");
-		printf("   infoRot180: %d\n", sc->synhw.infoRot180);
-		printf("   infoPortrait: %d\n", sc->synhw.infoPortrait);
-		printf("   infoSensor: %d\n", sc->synhw.infoSensor);
-		printf("   infoHardware: %d\n", sc->synhw.infoHardware);
-		printf("   infoNewAbs: %d\n", sc->synhw.infoNewAbs);
-		printf("   capPen: %d\n", sc->synhw.capPen);
-		printf("   infoSimplC: %d\n", sc->synhw.infoSimplC);
-		printf("   infoGeometry: %d\n", sc->synhw.infoGeometry);
+		printf("   infoRot180: %d\n", synhw.infoRot180);
+		printf("   infoPortrait: %d\n", synhw.infoPortrait);
+		printf("   infoSensor: %d\n", synhw.infoSensor);
+		printf("   infoHardware: %d\n", synhw.infoHardware);
+		printf("   infoNewAbs: %d\n", synhw.infoNewAbs);
+		printf("   capPen: %d\n", synhw.capPen);
+		printf("   infoSimplC: %d\n", synhw.infoSimplC);
+		printf("   infoGeometry: %d\n", synhw.infoGeometry);
 	}
=20
 	/* Read the extended capability bits. */
@@ -4390,46 +4387,42 @@
 	}
=20
 	/* Set the different capabilities when they exist. */
-	if ((status[0] & 0x80) >> 7) {
-		sc->synhw.capExtended    =3D (status[0] & 0x80) >> 7;
-		sc->synhw.capPassthrough =3D (status[2] & 0x80) >> 7;
-		sc->synhw.capSleep       =3D (status[2] & 0x10) >> 4;
-		sc->synhw.capFourButtons =3D (status[2] & 0x08) >> 3;
-		sc->synhw.capMultiFinger =3D (status[2] & 0x02) >> 1;
-		sc->synhw.capPalmDetect  =3D (status[2] & 0x01);
+	buttons =3D 0;
+	synhw.capExtended =3D (status[0] & 0x80) !=3D 0;
+	if (synhw.capExtended) {
+		synhw.capPassthrough =3D (status[2] & 0x80) !=3D 0;
+		synhw.capSleep       =3D (status[2] & 0x10) !=3D 0;
+		synhw.capFourButtons =3D (status[2] & 0x08) !=3D 0;
+		synhw.capMultiFinger =3D (status[2] & 0x02) !=3D 0;
+		synhw.capPalmDetect  =3D (status[2] & 0x01) !=3D 0;
=20
 		if (verbose >=3D 2) {
 			printf("  Extended capabilities:\n");
-			printf("   capExtended: %d\n", sc->synhw.capExtended);
-			printf("   capPassthrough: %d\n",
-			    sc->synhw.capPassthrough);
-			printf("   capSleep: %d\n", sc->synhw.capSleep);
-			printf("   capFourButtons: %d\n",
-			    sc->synhw.capFourButtons);
-			printf("   capMultiFinger: %d\n",
-			    sc->synhw.capMultiFinger);
-			printf("   capPalmDetect: %d\n",
-			    sc->synhw.capPalmDetect);
+			printf("   capExtended: %d\n", synhw.capExtended);
+			printf("   capPassthrough: %d\n", synhw.capPassthrough);
+			printf("   capSleep: %d\n", synhw.capSleep);
+			printf("   capFourButtons: %d\n", synhw.capFourButtons);
+			printf("   capMultiFinger: %d\n", synhw.capMultiFinger);
+			printf("   capPalmDetect: %d\n", synhw.capPalmDetect);
 		}
=20
 		/*
 		 * If we have bits set in status[0] & 0x70, then we can load
 		 * more information about buttons using query 0x09.
 		 */
-		if (status[0] & 0x70) {
+		if ((status[0] & 0x70) !=3D 0) {
 			if (mouse_ext_command(kbdc, 0x09) =3D=3D 0)
 				return (FALSE);
 			if (get_mouse_status(kbdc, status, 0, 3) !=3D 3)
 				return (FALSE);
-			sc->hw.buttons =3D ((status[1] & 0xf0) >> 4) + 3;
-			if (verbose >=3D 2)
-				printf("  Additional Buttons: %d\n",
-				    sc->hw.buttons -3);
-		}
-	} else {
-		sc->synhw.capExtended =3D 0;
-
-		if (verbose >=3D 2)
+			buttons =3D (status[1] & 0xf0) >> 4;
+		} else
+			buttons =3D synhw.capFourButtons ? 1 : 0;
+	}
+	if (verbose >=3D 2) {
+		if (synhw.capExtended)
+			printf("  Additional Buttons: %d\n", buttons);
+		else
 			printf("  No extended capabilities\n");
 	}
=20
@@ -4449,43 +4442,34 @@
 		return (FALSE);
 	}
=20
+	if (sc !=3D NULL)
+		sc->synhw =3D synhw;
+	if (!synaptics_support)
+		return (FALSE);
+
 	/* Set the mode byte; request wmode where available. */
-	if (sc->synhw.capExtended)
-		mouse_ext_command(kbdc, 0xc1);
-	else
-		mouse_ext_command(kbdc, 0xc0);
+	mouse_ext_command(kbdc, synhw.capExtended ? 0xc1 : 0xc0);
=20
 	/* "Commit" the Set Mode Byte command sent above. */
 	set_mouse_sampling_rate(kbdc, 20);
=20
-	/*
-	 * Report the correct number of buttons
-	 *
-	 * XXX: I'm not sure this is used anywhere.
-	 */
-	if (sc->synhw.capExtended && sc->synhw.capFourButtons)
-		sc->hw.buttons =3D 4;
-
-	VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n",
-	    sc->hw.buttons));
-
-	/* Create sysctl tree. */
-	synaptics_sysctl_create_tree(sc);
-
-	/*
-	 * The touchpad will have to be reinitialized after
-	 * suspend/resume.
-	 */
-	sc->config |=3D PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
+	buttons +=3D 3;
+	VLOG(3, (LOG_DEBUG, "synaptics: END init (%d buttons)\n", buttons));
+
+	if (sc !=3D NULL) {
+		/* Create sysctl tree. */
+		synaptics_sysctl_create_tree(sc);
+
+		sc->hw.buttons =3D buttons;
+	}
=20
 	return (TRUE);
 }
=20
 /* Interlink electronics VersaPad */
 static int
-enable_versapad(struct psm_softc *sc)
+enable_versapad(KBDC kbdc, struct psm_softc *sc)
 {
-	KBDC kbdc =3D sc->kbdc;
 	int data[3];
=20
 	set_mouse_resolution(kbdc, PSMD_RES_MEDIUM_HIGH); /* set res. 2 */
@@ -4500,8 +4484,6 @@
 		return (FALSE);
 	set_mouse_scaling(kbdc, 1);			/* set scale 1:1 */
=20
-	sc->config |=3D PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND;
-
 	return (TRUE);				/* PS/2 absolute mode */
 }
=20
@@ -4539,7 +4521,8 @@
=20
 	VLOG(2, (LOG_NOTICE, "psm%d: system resume hook called.\n", unit));
=20
-	if (!(sc->config & PSM_CONFIG_HOOKRESUME))
+	if ((sc->config &
+	    (PSM_CONFIG_HOOKRESUME | PSM_CONFIG_INITAFTERSUSPEND)) =3D=3D 0)
 		return (0);
=20
 	err =3D reinitialize(sc, sc->config & PSM_CONFIG_INITAFTERSUSPEND);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/bce/if_bce.c
--- a/head/sys/dev/bce/if_bce.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/bce/if_bce.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/bce/if_bce.c 228476 2011-12-13 18:11:25Z =
yongari $");
+__FBSDID("$FreeBSD: head/sys/dev/bce/if_bce.c 234121 2012-04-11 06:34:25Z =
yongari $");
=20
 /*
  * The following controllers are supported by this driver:
@@ -1982,7 +1982,6 @@
 bce_miibus_statchg(device_t dev)
 {
 	struct bce_softc *sc;
-	struct ifnet *ifp;
 	struct mii_data *mii;
 	int val;
=20
@@ -1990,56 +1989,41 @@
=20
 	DBENTER(BCE_VERBOSE_PHY);
=20
-	ifp =3D sc->bce_ifp;
 	mii =3D device_get_softc(sc->bce_miibus);
-	if (mii =3D=3D NULL || ifp =3D=3D NULL ||
-	    (ifp->if_drv_flags & IFF_DRV_RUNNING) =3D=3D 0)
-		return;
-
-	sc->bce_link_up =3D FALSE;
+
 	val =3D REG_RD(sc, BCE_EMAC_MODE);
 	val &=3D ~(BCE_EMAC_MODE_PORT | BCE_EMAC_MODE_HALF_DUPLEX |
 	    BCE_EMAC_MODE_MAC_LOOP | BCE_EMAC_MODE_FORCE_LINK |
 	    BCE_EMAC_MODE_25G);
=20
 	/* Set MII or GMII interface based on the PHY speed. */
-	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) =3D=3D
-	    (IFM_ACTIVE | IFM_AVALID)) {
-		switch (IFM_SUBTYPE(mii->mii_media_active)) {
-		case IFM_10_T:
-			if (BCE_CHIP_NUM(sc) !=3D BCE_CHIP_NUM_5706) {
-				DBPRINT(sc, BCE_INFO_PHY,
-				    "Enabling 10Mb interface.\n");
-				val |=3D BCE_EMAC_MODE_PORT_MII_10;
-				sc->bce_link_up =3D TRUE;
-				break;
-			}
-			/* FALLTHROUGH */
-		case IFM_100_TX:
-			DBPRINT(sc, BCE_INFO_PHY, "Enabling MII interface.\n");
-			val |=3D BCE_EMAC_MODE_PORT_MII;
-			sc->bce_link_up =3D TRUE;
+	switch (IFM_SUBTYPE(mii->mii_media_active)) {
+	case IFM_10_T:
+		if (BCE_CHIP_NUM(sc) !=3D BCE_CHIP_NUM_5706) {
+			DBPRINT(sc, BCE_INFO_PHY,
+			    "Enabling 10Mb interface.\n");
+			val |=3D BCE_EMAC_MODE_PORT_MII_10;
 			break;
-		case IFM_2500_SX:
-			DBPRINT(sc, BCE_INFO_PHY, "Enabling 2.5G MAC mode.\n");
-			val |=3D BCE_EMAC_MODE_25G;
-			/* FALLTHROUGH */
-		case IFM_1000_T:
-		case IFM_1000_SX:
-			DBPRINT(sc, BCE_INFO_PHY, "Enabling GMII interface.\n");
-			val |=3D BCE_EMAC_MODE_PORT_GMII;
-			sc->bce_link_up =3D TRUE;
-			if (bce_verbose || bootverbose)
-				BCE_PRINTF("Gigabit link up!\n");
-			break;
-		default:
-			DBPRINT(sc, BCE_INFO_PHY, "Unknown link speed.\n");
-			break;
-		}
-	}
-
-	if (sc->bce_link_up =3D=3D FALSE)
-		return;
+		}
+		/* fall-through */
+	case IFM_100_TX:
+		DBPRINT(sc, BCE_INFO_PHY, "Enabling MII interface.\n");
+		val |=3D BCE_EMAC_MODE_PORT_MII;
+		break;
+	case IFM_2500_SX:
+		DBPRINT(sc, BCE_INFO_PHY, "Enabling 2.5G MAC mode.\n");
+		val |=3D BCE_EMAC_MODE_25G;
+		/* fall-through */
+	case IFM_1000_T:
+	case IFM_1000_SX:
+		DBPRINT(sc, BCE_INFO_PHY, "Enabling GMII interface.\n");
+		val |=3D BCE_EMAC_MODE_PORT_GMII;
+		break;
+	default:
+		DBPRINT(sc, BCE_INFO_PHY, "Unknown link speed, enabling "
+		    "default GMII interface.\n");
+		val |=3D BCE_EMAC_MODE_PORT_GMII;
+	}
=20
 	/* Set half or full duplex based on PHY settings. */
 	if ((mii->mii_media_active & IFM_GMASK) =3D=3D IFM_HDX) {
@@ -2052,7 +2036,7 @@
=20
 	REG_WR(sc, BCE_EMAC_MODE, val);
=20
-	if ((mii->mii_media_active & IFM_ETH_RXPAUSE) !=3D 0) {
+ 	if ((mii->mii_media_active & IFM_ETH_RXPAUSE) !=3D 0) {
 		DBPRINT(sc, BCE_INFO_PHY,
 		    "%s(): Enabling RX flow control.\n", __FUNCTION__);
 		BCE_SETBIT(sc, BCE_EMAC_RX_MODE, BCE_EMAC_RX_MODE_FLOW_EN);
@@ -2062,7 +2046,7 @@
 		BCE_CLRBIT(sc, BCE_EMAC_RX_MODE, BCE_EMAC_RX_MODE_FLOW_EN);
 	}
=20
-	if ((mii->mii_media_active & IFM_ETH_TXPAUSE) !=3D 0) {
+ 	if ((mii->mii_media_active & IFM_ETH_TXPAUSE) !=3D 0) {
 		DBPRINT(sc, BCE_INFO_PHY,
 		    "%s(): Enabling TX flow control.\n", __FUNCTION__);
 		BCE_SETBIT(sc, BCE_EMAC_TX_MODE, BCE_EMAC_TX_MODE_FLOW_EN);
@@ -6222,11 +6206,15 @@
 			DBPRINT(sc, BCE_INFO_PHY, "%s(): Link is now DOWN.\n",
 			    __FUNCTION__);
 		}
+
 		/*
-		 * Link state changed, allow tick routine to update
-		 * the state baased on actual media state.
+		 * Assume link is down and allow
+		 * tick routine to update the state
+		 * based on the actual media state.
 		 */
-		sc->bce_link_tick =3D TRUE;
+		sc->bce_link_up =3D FALSE;
+		callout_stop(&sc->bce_tick_callout);
+		bce_tick(sc);
 	}
=20
 	/* Acknowledge the link change interrupt. */
@@ -6910,13 +6898,12 @@
 	/* Enable host interrupts. */
 	bce_enable_intr(sc, 1);
=20
+	bce_ifmedia_upd_locked(ifp);
+
 	/* Let the OS know the driver is up and running. */
 	ifp->if_drv_flags |=3D IFF_DRV_RUNNING;
 	ifp->if_drv_flags &=3D ~IFF_DRV_OACTIVE;
=20
-	sc->bce_link_tick =3D TRUE;
-	bce_ifmedia_upd_locked(ifp);
-
 	callout_reset(&sc->bce_tick_callout, hz, bce_tick, sc);
=20
 bce_init_locked_exit:
@@ -8212,19 +8199,31 @@
 	bce_watchdog(sc);
=20
 	/* If link is up already up then we're done. */
-	if (sc->bce_link_tick =3D=3D FALSE && sc->bce_link_up =3D=3D TRUE)
+	if (sc->bce_link_up =3D=3D TRUE)
 		goto bce_tick_exit;
=20
 	/* Link is down.  Check what the PHY's doing. */
 	mii =3D device_get_softc(sc->bce_miibus);
 	mii_tick(mii);
=20
-	sc->bce_link_tick =3D FALSE;
-	/* Now that link is up, handle any outstanding TX traffic. */
-	if (sc->bce_link_up =3D=3D TRUE && !IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
+	/* Check if the link has come up. */
+	if ((mii->mii_media_status & IFM_ACTIVE) &&
+	    (IFM_SUBTYPE(mii->mii_media_active) !=3D IFM_NONE)) {
 		DBPRINT(sc, BCE_VERBOSE_MISC,
-		    "%s(): Found pending TX traffic.\n", __FUNCTION__);
-		bce_start_locked(ifp);
+		    "%s(): Link up!\n", __FUNCTION__);
+		sc->bce_link_up =3D TRUE;
+		if ((IFM_SUBTYPE(mii->mii_media_active) =3D=3D IFM_1000_T ||
+		    IFM_SUBTYPE(mii->mii_media_active) =3D=3D IFM_1000_SX ||
+		    IFM_SUBTYPE(mii->mii_media_active) =3D=3D IFM_2500_SX) &&
+		    (bce_verbose || bootverbose))
+			BCE_PRINTF("Gigabit link up!\n");
+
+		/* Now that link is up, handle any outstanding TX traffic. */
+		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
+			DBPRINT(sc, BCE_VERBOSE_MISC, "%s(): Found "
+			    "pending TX traffic.\n", __FUNCTION__);
+			bce_start_locked(ifp);
+		}
 	}
=20
 bce_tick_exit:
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/bce/if_bcereg.h
--- a/head/sys/dev/bce/if_bcereg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/bce/if_bcereg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/bce/if_bcereg.h 228476 2011-12-13 18:11:25Z yong=
ari $
+ * $FreeBSD: head/sys/dev/bce/if_bcereg.h 234121 2012-04-11 06:34:25Z yong=
ari $
  */
=20
 #ifndef	_BCEREG_H_DEFINED
@@ -6560,7 +6560,6 @@
 	u16			pg_prod;
 	u16			pg_cons;
=20
-	int			bce_link_tick;
 	int			bce_link_up;
 	struct		callout bce_tick_callout;
 	struct		callout bce_pulse_callout;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/cfi/cfi_core.c
--- a/head/sys/dev/cfi/cfi_core.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/cfi/cfi_core.c	Tue Apr 17 11:51:51 2012 +0300
@@ -604,6 +604,8 @@
=20
 	sc =3D device_get_softc(dev);
=20
+	/* Reset chip to ARRAY mode */
+	cfi_array_write(sc, 0, 0, sc->sc_rstcmd);
 	destroy_dev(sc->sc_nod);
 	free(sc->sc_region, M_TEMP);
 	if (sc->sc_res)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/e1000/e1000_osdep.h
--- a/head/sys/dev/e1000/e1000_osdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/e1000/e1000_osdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
=20
 **************************************************************************=
****/
-/*$FreeBSD: head/sys/dev/e1000/e1000_osdep.h 228441 2011-12-12 18:27:34Z m=
df $*/
+/*$FreeBSD: head/sys/dev/e1000/e1000_osdep.h 233423 2012-03-24 15:15:34Z m=
arius $*/
=20
=20
 #ifndef _FREEBSD_OS_H_
@@ -84,7 +84,8 @@
 /* Mutex used in the shared code */
 #define E1000_MUTEX                     struct mtx
 #define E1000_MUTEX_INIT(mutex)         mtx_init((mutex), #mutex, \
-                                            MTX_NETWORK_LOCK, MTX_DEF)
+                                            MTX_NETWORK_LOCK, \
+                                            MTX_DEF | MTX_DUPOK)
 #define E1000_MUTEX_DESTROY(mutex)      mtx_destroy(mutex)
 #define E1000_MUTEX_LOCK(mutex)         mtx_lock(mutex)
 #define E1000_MUTEX_TRYLOCK(mutex)      mtx_trylock(mutex)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/e1000/if_em.c
--- a/head/sys/dev/e1000/if_em.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/e1000/if_em.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
=20
 **************************************************************************=
****/
-/*$FreeBSD: head/sys/dev/e1000/if_em.c 232238 2012-02-27 19:05:01Z luigi $=
*/
+/*$FreeBSD: head/sys/dev/e1000/if_em.c 233708 2012-03-30 19:54:48Z jhb $*/
=20
 #ifdef HAVE_KERNEL_OPTION_HEADERS
 #include "opt_device_polling.h"
@@ -193,13 +193,14 @@
 static int	em_shutdown(device_t);
 static int	em_suspend(device_t);
 static int	em_resume(device_t);
-static void	em_start(struct ifnet *);
-static void	em_start_locked(struct ifnet *, struct tx_ring *);
 #ifdef EM_MULTIQUEUE
 static int	em_mq_start(struct ifnet *, struct mbuf *);
 static int	em_mq_start_locked(struct ifnet *,
 		    struct tx_ring *, struct mbuf *);
 static void	em_qflush(struct ifnet *);
+#else
+static void	em_start(struct ifnet *);
+static void	em_start_locked(struct ifnet *, struct tx_ring *);
 #endif
 static int	em_ioctl(struct ifnet *, u_long, caddr_t);
 static void	em_init(void *);
@@ -234,7 +235,7 @@
 static void	em_disable_intr(struct adapter *);
 static void	em_update_stats_counters(struct adapter *);
 static void	em_add_hw_stats(struct adapter *adapter);
-static bool	em_txeof(struct tx_ring *);
+static void	em_txeof(struct tx_ring *);
 static bool	em_rxeof(struct rx_ring *, int, int *);
 #ifndef __NO_STRICT_ALIGNMENT
 static int	em_fixup_rx(struct rx_ring *);
@@ -847,6 +848,7 @@
 em_resume(device_t dev)
 {
 	struct adapter *adapter =3D device_get_softc(dev);
+	struct tx_ring	*txr =3D adapter->tx_rings;
 	struct ifnet *ifp =3D adapter->ifp;
=20
 	EM_CORE_LOCK(adapter);
@@ -854,8 +856,22 @@
 		e1000_resume_workarounds_pchlan(&adapter->hw);
 	em_init_locked(adapter);
 	em_init_manageability(adapter);
+
+	if ((ifp->if_flags & IFF_UP) &&
+	    (ifp->if_drv_flags & IFF_DRV_RUNNING) && adapter->link_active) {
+		for (int i =3D 0; i < adapter->num_queues; i++, txr++) {
+			EM_TX_LOCK(txr);
+#ifdef EM_MULTIQUEUE
+			if (!drbr_empty(ifp, txr->br))
+				em_mq_start_locked(ifp, txr, NULL);
+#else
+			if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+				em_start_locked(ifp, txr);
+#endif
+			EM_TX_UNLOCK(txr);
+		}
+	}
 	EM_CORE_UNLOCK(adapter);
-	em_start(ifp);
=20
 	return bus_generic_resume(dev);
 }
@@ -959,7 +975,7 @@
 	}
 	if_qflush(ifp);
 }
-#endif /* EM_MULTIQUEUE */
+#else  /* !EM_MULTIQUEUE */
=20
 static void
 em_start_locked(struct ifnet *ifp, struct tx_ring *txr)
@@ -1020,14 +1036,9 @@
 		em_start_locked(ifp, txr);
 		EM_TX_UNLOCK(txr);
 	}
-	/*
-	** If we went inactive schedule
-	** a task to clean up.
-	*/
-	if (ifp->if_drv_flags & IFF_DRV_OACTIVE)
-		taskqueue_enqueue(txr->tq, &txr->tx_task);
 	return;
 }
+#endif /* EM_MULTIQUEUE */
=20
 /*********************************************************************
  *  Ioctl entry point
@@ -1424,7 +1435,8 @@
 	if (!drbr_empty(ifp, txr->br))
 		em_mq_start_locked(ifp, txr, NULL);
 #else
-	em_start_locked(ifp, txr);
+	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+		em_start_locked(ifp, txr);
 #endif
 	EM_TX_UNLOCK(txr);
=20
@@ -1497,10 +1509,11 @@
 		if (!drbr_empty(ifp, txr->br))
 			em_mq_start_locked(ifp, txr, NULL);
 #else
-		em_start_locked(ifp, txr);
+		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+			em_start_locked(ifp, txr);
 #endif
 		EM_TX_UNLOCK(txr);
-		if (more || (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
+		if (more) {
 			taskqueue_enqueue(adapter->tq, &adapter->que_task);
 			return;
 		}
@@ -1521,17 +1534,21 @@
 {
 	struct tx_ring *txr =3D arg;
 	struct adapter *adapter =3D txr->adapter;
-	bool		more;
+	struct ifnet	*ifp =3D adapter->ifp;
=20
 	++txr->tx_irq;
 	EM_TX_LOCK(txr);
-	more =3D em_txeof(txr);
+	em_txeof(txr);
+#ifdef EM_MULTIQUEUE
+	if (!drbr_empty(ifp, txr->br))
+		em_mq_start_locked(ifp, txr, NULL);
+#else
+	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+		em_start_locked(ifp, txr);
+#endif
+	/* Reenable this interrupt */
+	E1000_WRITE_REG(&adapter->hw, E1000_IMS, txr->ims);
 	EM_TX_UNLOCK(txr);
-	if (more)
-		taskqueue_enqueue(txr->tq, &txr->tx_task);
-	else
-		/* Reenable this interrupt */
-		E1000_WRITE_REG(&adapter->hw, E1000_IMS, txr->ims);
 	return;
 }
=20
@@ -1609,7 +1626,8 @@
 	if (!drbr_empty(ifp, txr->br))
 		em_mq_start_locked(ifp, txr, NULL);
 #else
-	em_start_locked(ifp, txr);
+	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+		em_start_locked(ifp, txr);
 #endif
 	E1000_WRITE_REG(&adapter->hw, E1000_IMS, txr->ims);
 	EM_TX_UNLOCK(txr);
@@ -1619,6 +1637,7 @@
 em_handle_link(void *context, int pending)
 {
 	struct adapter	*adapter =3D context;
+	struct tx_ring	*txr =3D adapter->tx_rings;
 	struct ifnet *ifp =3D adapter->ifp;
=20
 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
@@ -1630,6 +1649,19 @@
 	callout_reset(&adapter->timer, hz, em_local_timer, adapter);
 	E1000_WRITE_REG(&adapter->hw, E1000_IMS,
 	    EM_MSIX_LINK | E1000_IMS_LSC);
+	if (adapter->link_active) {
+		for (int i =3D 0; i < adapter->num_queues; i++, txr++) {
+			EM_TX_LOCK(txr);
+#ifdef EM_MULTIQUEUE
+			if (!drbr_empty(ifp, txr->br))
+				em_mq_start_locked(ifp, txr, NULL);
+#else
+			if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+				em_start_locked(ifp, txr);
+#endif
+			EM_TX_UNLOCK(txr);
+		}
+	}
 	EM_CORE_UNLOCK(adapter);
 }
=20
@@ -2902,20 +2934,21 @@
 	ifp->if_softc =3D adapter;
 	ifp->if_flags =3D IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
 	ifp->if_ioctl =3D em_ioctl;
+#ifdef EM_MULTIQUEUE
+	/* Multiqueue stack interface */
+	ifp->if_transmit =3D em_mq_start;
+	ifp->if_qflush =3D em_qflush;
+#else
 	ifp->if_start =3D em_start;
 	IFQ_SET_MAXLEN(&ifp->if_snd, adapter->num_tx_desc - 1);
 	ifp->if_snd.ifq_drv_maxlen =3D adapter->num_tx_desc - 1;
 	IFQ_SET_READY(&ifp->if_snd);
+#endif=09
=20
 	ether_ifattach(ifp, adapter->hw.mac.addr);
=20
 	ifp->if_capabilities =3D ifp->if_capenable =3D 0;
=20
-#ifdef EM_MULTIQUEUE
-	/* Multiqueue stack interface */
-	ifp->if_transmit =3D em_mq_start;
-	ifp->if_qflush =3D em_qflush;
-#endif=09
=20
 	ifp->if_capabilities |=3D IFCAP_HWCSUM | IFCAP_VLAN_HWCSUM;
 	ifp->if_capabilities |=3D IFCAP_TSO4;
@@ -3742,7 +3775,7 @@
  *  tx_buffer is put back on the free queue.
  *
  **********************************************************************/
-static bool
+static void
 em_txeof(struct tx_ring *txr)
 {
 	struct adapter	*adapter =3D txr->adapter;
@@ -3762,14 +3795,14 @@
 		selwakeuppri(&na->tx_si, PI_NET);
 		EM_CORE_UNLOCK(adapter);
 		EM_TX_LOCK(txr);
-		return (FALSE);
+		return;
 	}
 #endif /* DEV_NETMAP */
=20
 	/* No work, make sure watchdog is off */
         if (txr->tx_avail =3D=3D adapter->num_tx_desc) {
 		txr->queue_status =3D EM_QUEUE_IDLE;
-                return (FALSE);
+                return;
 	}
=20
 	processed =3D 0;
@@ -3858,10 +3891,7 @@
 	/* Disable watchdog if all clean */
 	if (txr->tx_avail =3D=3D adapter->num_tx_desc) {
 		txr->queue_status =3D EM_QUEUE_IDLE;
-		return (FALSE);
 	}=20
-
-	return (TRUE);
 }
=20
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/e1000/if_igb.c
--- a/head/sys/dev/e1000/if_igb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/e1000/if_igb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
=20
 **************************************************************************=
****/
-/*$FreeBSD: head/sys/dev/e1000/if_igb.c 232367 2012-03-01 22:13:10Z jhb $*/
+/*$FreeBSD: head/sys/dev/e1000/if_igb.c 234154 2012-04-11 21:33:45Z jhb $*/
=20
=20
 #ifdef HAVE_KERNEL_OPTION_HEADERS
@@ -171,13 +171,15 @@
 static int	igb_shutdown(device_t);
 static int	igb_suspend(device_t);
 static int	igb_resume(device_t);
-static void	igb_start(struct ifnet *);
-static void	igb_start_locked(struct tx_ring *, struct ifnet *ifp);
 #if __FreeBSD_version >=3D 800000
 static int	igb_mq_start(struct ifnet *, struct mbuf *);
 static int	igb_mq_start_locked(struct ifnet *,
 		    struct tx_ring *, struct mbuf *);
 static void	igb_qflush(struct ifnet *);
+static void	igb_deferred_mq_start(void *, int);
+#else
+static void	igb_start(struct ifnet *);
+static void	igb_start_locked(struct tx_ring *, struct ifnet *ifp);
 #endif
 static int	igb_ioctl(struct ifnet *, u_long, caddr_t);
 static void	igb_init(void *);
@@ -261,6 +263,7 @@
 static void	igb_msix_link(void *);
 static void	igb_handle_que(void *context, int pending);
 static void	igb_handle_link(void *context, int pending);
+static void	igb_handle_link_locked(struct adapter *);
=20
 static void	igb_set_sysctl_value(struct adapter *, const char *,
 		    const char *, int *, int);
@@ -713,6 +716,8 @@
 		return (EBUSY);
 	}
=20
+	ether_ifdetach(adapter->ifp);
+
 	if (adapter->led_dev !=3D NULL)
 		led_destroy(adapter->led_dev);
=20
@@ -744,8 +749,6 @@
 	if (adapter->vlan_detach !=3D NULL)
 		EVENTHANDLER_DEREGISTER(vlan_unconfig, adapter->vlan_detach);
=20
-	ether_ifdetach(adapter->ifp);
-
 	callout_drain(&adapter->timer);
=20
 #ifdef DEV_NETMAP
@@ -807,6 +810,7 @@
 igb_resume(device_t dev)
 {
 	struct adapter *adapter =3D device_get_softc(dev);
+	struct tx_ring	*txr =3D adapter->tx_rings;
 	struct ifnet *ifp =3D adapter->ifp;
=20
 	IGB_CORE_LOCK(adapter);
@@ -814,9 +818,21 @@
 	igb_init_manageability(adapter);
=20
 	if ((ifp->if_flags & IFF_UP) &&
-	    (ifp->if_drv_flags & IFF_DRV_RUNNING))
-		igb_start(ifp);
-
+	    (ifp->if_drv_flags & IFF_DRV_RUNNING) && adapter->link_active) {
+		for (int i =3D 0; i < adapter->num_queues; i++, txr++) {
+			IGB_TX_LOCK(txr);
+#if __FreeBSD_version >=3D 800000
+			/* Process the stack queue only if not depleted */
+			if (((txr->queue_status & IGB_QUEUE_DEPLETED) =3D=3D 0) &&
+			    !drbr_empty(ifp, txr->br))
+				igb_mq_start_locked(ifp, txr, NULL);
+#else
+			if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+				igb_start_locked(txr, ifp);
+#endif
+			IGB_TX_UNLOCK(txr);
+		}
+	}
 	IGB_CORE_UNLOCK(adapter);
=20
 	return bus_generic_resume(dev);
@@ -928,7 +944,7 @@
 		IGB_TX_UNLOCK(txr);
 	} else {
 		err =3D drbr_enqueue(ifp, txr->br, m);
-		taskqueue_enqueue(que->tq, &que->que_task);
+		taskqueue_enqueue(que->tq, &txr->txq_task);
 	}
=20
 	return (err);
@@ -988,6 +1004,22 @@
 }
=20
 /*
+ * Called from a taskqueue to drain queued transmit packets.
+ */
+static void
+igb_deferred_mq_start(void *arg, int pending)
+{
+	struct tx_ring *txr =3D arg;
+	struct adapter *adapter =3D txr->adapter;
+	struct ifnet *ifp =3D adapter->ifp;
+
+	IGB_TX_LOCK(txr);
+	if (!drbr_empty(ifp, txr->br))
+		igb_mq_start_locked(ifp, txr, NULL);
+	IGB_TX_UNLOCK(txr);
+}
+
+/*
 ** Flush all ring buffers
 */
 static void
@@ -1330,19 +1362,19 @@
 		more =3D igb_rxeof(que, adapter->rx_process_limit, NULL);
=20
 		IGB_TX_LOCK(txr);
-		if (igb_txeof(txr))
-			more =3D TRUE;
+		igb_txeof(txr);
 #if __FreeBSD_version >=3D 800000
 		/* Process the stack queue only if not depleted */
 		if (((txr->queue_status & IGB_QUEUE_DEPLETED) =3D=3D 0) &&
 		    !drbr_empty(ifp, txr->br))
 			igb_mq_start_locked(ifp, txr, NULL);
 #else
-		igb_start_locked(txr, ifp);
+		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+			igb_start_locked(txr, ifp);
 #endif
 		IGB_TX_UNLOCK(txr);
 		/* Do we need another? */
-		if (more || (ifp->if_drv_flags & IFF_DRV_OACTIVE)) {
+		if (more) {
 			taskqueue_enqueue(que->tq, &que->que_task);
 			return;
 		}
@@ -1365,8 +1397,35 @@
 {
 	struct adapter *adapter =3D context;
=20
+	IGB_CORE_LOCK(adapter);
+	igb_handle_link_locked(adapter);
+	IGB_CORE_UNLOCK(adapter);
+}
+
+static void
+igb_handle_link_locked(struct adapter *adapter)
+{
+	struct tx_ring	*txr =3D adapter->tx_rings;
+	struct ifnet *ifp =3D adapter->ifp;
+
+	IGB_CORE_LOCK_ASSERT(adapter);
 	adapter->hw.mac.get_link_status =3D 1;
 	igb_update_link_status(adapter);
+	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) && adapter->link_active) {
+		for (int i =3D 0; i < adapter->num_queues; i++, txr++) {
+			IGB_TX_LOCK(txr);
+#if __FreeBSD_version >=3D 800000
+			/* Process the stack queue only if not depleted */
+			if (((txr->queue_status & IGB_QUEUE_DEPLETED) =3D=3D 0) &&
+			    !drbr_empty(ifp, txr->br))
+				igb_mq_start_locked(ifp, txr, NULL);
+#else
+			if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+				igb_start_locked(txr, ifp);
+#endif
+			IGB_TX_UNLOCK(txr);
+		}
+	}
 }
=20
 /*********************************************************************
@@ -1446,7 +1505,7 @@
 		reg_icr =3D E1000_READ_REG(&adapter->hw, E1000_ICR);
 		/* Link status change */
 		if (reg_icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC))
-			igb_handle_link(adapter, 0);
+			igb_handle_link_locked(adapter);
=20
 		if (reg_icr & E1000_ICR_RXO)
 			adapter->rx_overruns++;
@@ -1463,7 +1522,8 @@
 	if (!drbr_empty(ifp, txr->br))
 		igb_mq_start_locked(ifp, txr, NULL);
 #else
-	igb_start_locked(txr, ifp);
+	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+		igb_start_locked(txr, ifp);
 #endif
 	IGB_TX_UNLOCK(txr);
 	return POLL_RETURN_COUNT(rx_done);
@@ -1480,16 +1540,26 @@
 {
 	struct igb_queue *que =3D arg;
 	struct adapter *adapter =3D que->adapter;
+	struct ifnet   *ifp =3D adapter->ifp;
 	struct tx_ring *txr =3D que->txr;
 	struct rx_ring *rxr =3D que->rxr;
 	u32		newitr =3D 0;
-	bool		more_tx, more_rx;
+	bool		more_rx;
=20
 	E1000_WRITE_REG(&adapter->hw, E1000_EIMC, que->eims);
 	++que->irqs;
=20
 	IGB_TX_LOCK(txr);
-	more_tx =3D igb_txeof(txr);
+	igb_txeof(txr);
+#if __FreeBSD_version >=3D 800000
+	/* Process the stack queue only if not depleted */
+	if (((txr->queue_status & IGB_QUEUE_DEPLETED) =3D=3D 0) &&
+	    !drbr_empty(ifp, txr->br))
+		igb_mq_start_locked(ifp, txr, NULL);
+#else
+	if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
+		igb_start_locked(txr, ifp);
+#endif
 	IGB_TX_UNLOCK(txr);
=20
 	more_rx =3D igb_rxeof(que, adapter->rx_process_limit, NULL);
@@ -1547,7 +1617,7 @@
=20
 no_calc:
 	/* Schedule a clean task if needed*/
-	if (more_tx || more_rx)
+	if (more_rx)
 		taskqueue_enqueue(que->tq, &que->que_task);
 	else
 		/* Reenable this interrupt */
@@ -2329,6 +2399,7 @@
 {
 	device_t		dev =3D adapter->dev;
 	struct igb_queue	*que =3D adapter->queues;
+	struct tx_ring		*txr =3D adapter->tx_rings;
 	int			error, rid =3D 0;
=20
 	/* Turn off all interrupts */
@@ -2347,6 +2418,10 @@
 		return (ENXIO);
 	}
=20
+#if __FreeBSD_version >=3D 800000
+	TASK_INIT(&txr->txq_task, 0, igb_deferred_mq_start, txr);
+#endif
+
 	/*
 	 * Try allocating a fast interrupt and the associated deferred
 	 * processing contexts.
@@ -2420,9 +2495,13 @@
 		*/
 		if (adapter->num_queues > 1)
 			bus_bind_intr(dev, que->res, i);
+#if __FreeBSD_version >=3D 800000
+		TASK_INIT(&que->txr->txq_task, 0, igb_deferred_mq_start,
+		    que->txr);
+#endif
 		/* Make tasklet for deferred handling */
 		TASK_INIT(&que->que_task, 0, igb_handle_que, que);
-		que->tq =3D taskqueue_create_fast("igb_que", M_NOWAIT,
+		que->tq =3D taskqueue_create("igb_que", M_NOWAIT,
 		    taskqueue_thread_enqueue, &que->tq);
 		taskqueue_start_threads(&que->tq, 1, PI_NET, "%s que",
 		    device_get_nameunit(adapter->dev));
@@ -2629,13 +2708,24 @@
 	else
 		(adapter->msix !=3D 0) ? (rid =3D 1):(rid =3D 0);
=20
+	que =3D adapter->queues;
 	if (adapter->tag !=3D NULL) {
+		taskqueue_drain(que->tq, &adapter->link_task);
 		bus_teardown_intr(dev, adapter->res, adapter->tag);
 		adapter->tag =3D NULL;
 	}
 	if (adapter->res !=3D NULL)
 		bus_release_resource(dev, SYS_RES_IRQ, rid, adapter->res);
=20
+	for (int i =3D 0; i < adapter->num_queues; i++, que++) {
+		if (que->tq !=3D NULL) {
+#if __FreeBSD_version >=3D 800000
+			taskqueue_drain(que->tq, &que->txr->txq_task);
+#endif
+			taskqueue_drain(que->tq, &que->que_task);
+			taskqueue_free(que->tq);
+		}
+	}
 mem:
 	if (adapter->msix)
 		pci_release_msi(dev);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/e1000/if_igb.h
--- a/head/sys/dev/e1000/if_igb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/e1000/if_igb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
=20
 **************************************************************************=
****/
-/*$FreeBSD: head/sys/dev/e1000/if_igb.h 228788 2011-12-21 20:10:11Z jhb $*/
+/*$FreeBSD: head/sys/dev/e1000/if_igb.h 234154 2012-04-11 21:33:45Z jhb $*/
=20
 #ifndef _IGB_H_DEFINED_
 #define _IGB_H_DEFINED_
@@ -301,6 +301,7 @@
 	struct buf_ring		*br;
 #endif
 	bus_dma_tag_t		txtag;
+	struct task		txq_task;
=20
 	u32			bytes;
 	u32			packets;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/fb/s3_pci.c
--- a/head/sys/dev/fb/s3_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/fb/s3_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/fb/s3_pci.c 234362 2012-04-16 23:29:12Z j=
kim $");
=20
 /* Enable LFB on S3 cards that has only VESA 1.2 BIOS */
=20
@@ -513,7 +513,7 @@
 	/* Attach the driver to the VGA/VESA framework
 	 */
 	for (i =3D 0; (adp =3D vid_get_adapter(i)) !=3D NULL; ++i) {
-		if ((adp->va_type =3D=3D KD_VGA))
+		if (adp->va_type =3D=3D KD_VGA)
 			break;
 	}
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/fb/vesa.c
--- a/head/sys/dev/fb/vesa.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/fb/vesa.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/fb/vesa.c 233187 2012-03-19 17:14:12Z jki=
m $");
+__FBSDID("$FreeBSD: head/sys/dev/fb/vesa.c 233896 2012-04-04 22:02:54Z jki=
m $");
=20
 #include "opt_vga.h"
 #include "opt_vesa.h"
@@ -542,7 +542,8 @@
 	switch (code) {
 	case STATE_SAVE:
 		x86bios_intr(&regs, 0x10);
-		bcopy(vesa_state_buf, p, vesa_state_buf_size);
+		if (regs.R_AX =3D=3D 0x004f)
+			bcopy(vesa_state_buf, p, vesa_state_buf_size);
 		break;
 	case STATE_LOAD:
 		bcopy(p, vesa_state_buf, vesa_state_buf_size);
@@ -1464,24 +1465,31 @@
 	vm_offset_t buf;
 	size_t bsize;
=20
-	if (adp !=3D vesa_adp || vesa_state_buf_size =3D=3D 0)
+	if (adp !=3D vesa_adp || (size =3D=3D 0 && vesa_state_buf_size =3D=3D 0))
 		return ((*prevvidsw->save_state)(adp, p, size));
=20
+	bsize =3D offsetof(adp_state_t, regs) + vesa_state_buf_size;
 	if (size =3D=3D 0)
-		return (offsetof(adp_state_t, regs) + vesa_state_buf_size);
-	if (size < (offsetof(adp_state_t, regs) + vesa_state_buf_size))
+		return (bsize);
+	if (vesa_state_buf_size > 0 && size < bsize)
 		return (EINVAL);
=20
-	buf =3D adp->va_buffer;
+	if (VESA_MODE(adp->va_mode) && adp->va_buffer !=3D 0) {
+		buf =3D adp->va_buffer;
+		bsize =3D adp->va_buffer_size;
+	} else {
+		buf =3D adp->va_window;
+		bsize =3D adp->va_window_size;
+	}
 	if (buf !=3D 0) {
-		bsize =3D adp->va_buffer_size;
 		vesa_vmem_buf =3D malloc(bsize, M_DEVBUF, M_NOWAIT);
 		if (vesa_vmem_buf !=3D NULL)
 			bcopy((void *)buf, vesa_vmem_buf, bsize);
 	} else
 		vesa_vmem_buf =3D NULL;
+	if (vesa_state_buf_size =3D=3D 0)
+		return ((*prevvidsw->save_state)(adp, p, size));
 	((adp_state_t *)p)->sig =3D V_STATE_SIG;
-	bzero(((adp_state_t *)p)->regs, vesa_state_buf_size);
 	return (vesa_bios_save_restore(STATE_SAVE, ((adp_state_t *)p)->regs));
 }
=20
@@ -1490,27 +1498,34 @@
 {
 	vm_offset_t buf;
 	size_t bsize;
-	int mode;
+	int error, mode;
=20
 	if (adp !=3D vesa_adp)
 		return ((*prevvidsw->load_state)(adp, p));
=20
 	/* Try BIOS POST to restore a sane state. */
 	(void)vesa_bios_post();
-	bsize =3D adp->va_buffer_size;
 	mode =3D adp->va_mode;
-	(void)vesa_set_mode(adp, adp->va_initial_mode);
+	error =3D vesa_set_mode(adp, adp->va_initial_mode);
 	if (mode !=3D adp->va_initial_mode)
-		(void)vesa_set_mode(adp, mode);
+		error =3D vesa_set_mode(adp, mode);
=20
+	if (vesa_vmem_buf !=3D NULL) {
+		if (error =3D=3D 0) {
+			if (VESA_MODE(mode) && adp->va_buffer !=3D 0) {
+				buf =3D adp->va_buffer;
+				bsize =3D adp->va_buffer_size;
+			} else {
+				buf =3D adp->va_window;
+				bsize =3D adp->va_window_size;
+			}
+			if (buf !=3D 0)
+				bcopy(vesa_vmem_buf, (void *)buf, bsize);
+		}
+		free(vesa_vmem_buf, M_DEVBUF);
+	}
 	if (((adp_state_t *)p)->sig !=3D V_STATE_SIG)
 		return ((*prevvidsw->load_state)(adp, p));
-	if (vesa_vmem_buf !=3D NULL) {
-		buf =3D adp->va_buffer;
-		if (buf !=3D 0)
-			bcopy(vesa_vmem_buf, (void *)buf, bsize);
-		free(vesa_vmem_buf, M_DEVBUF);
-	}
 	return (vesa_bios_save_restore(STATE_LOAD, ((adp_state_t *)p)->regs));
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/fb/vga.c
--- a/head/sys/dev/fb/vga.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/fb/vga.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/fb/vga.c 230132 2012-01-15 13:23:18Z uqs =
$");
+__FBSDID("$FreeBSD: head/sys/dev/fb/vga.c 233892 2012-04-04 21:19:55Z jkim=
 $");
=20
 #include "opt_vga.h"
 #include "opt_fb.h"
@@ -2160,10 +2160,6 @@
 	    buf[1] =3D info.vi_height - 1;	/* ROWS */
 	}
 	buf[2] =3D info.vi_cheight;		/* POINTS */
-    } else {
-	/* XXX: shouldn't be happening... */
-	printf("vga%d: %s: failed to obtain mode info. (vga_save_state())\n",
-	       adp->va_unit, adp->va_name);
     }
 #else
     buf[0] =3D readb(BIOS_PADDRTOVADDR(0x44a));	/* COLS */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/fxp/if_fxp.c
--- a/head/sys/dev/fxp/if_fxp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/fxp/if_fxp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/fxp/if_fxp.c 233158 2012-03-19 02:10:40Z =
yongari $");
+__FBSDID("$FreeBSD: head/sys/dev/fxp/if_fxp.c 233587 2012-03-28 01:52:38Z =
yongari $");
=20
 /*
  * Intel EtherExpress Pro/100B PCI Fast Ethernet driver
@@ -194,7 +194,7 @@
     { 0x1229,	0x08,	0, "Intel 82559 Pro/100 Ethernet" },
     { 0x1229,	0x09,	0, "Intel 82559ER Pro/100 Ethernet" },
     { 0x1229,	0x0c,	0, "Intel 82550 Pro/100 Ethernet" },
-    { 0x1229,	0x0d,	0, "Intel 82550 Pro/100 Ethernet" },
+    { 0x1229,	0x0d,	0, "Intel 82550C Pro/100 Ethernet" },
     { 0x1229,	0x0e,	0, "Intel 82550 Pro/100 Ethernet" },
     { 0x1229,	0x0f,	0, "Intel 82551 Pro/100 Ethernet" },
     { 0x1229,	0x10,	0, "Intel 82551 Pro/100 Ethernet" },
@@ -248,6 +248,7 @@
 static void 		fxp_eeprom_putword(struct fxp_softc *sc, int offset,
 			    uint16_t data);
 static void		fxp_autosize_eeprom(struct fxp_softc *sc);
+static void		fxp_load_eeprom(struct fxp_softc *sc);
 static void		fxp_read_eeprom(struct fxp_softc *sc, u_short *data,
 			    int offset, int words);
 static void		fxp_write_eeprom(struct fxp_softc *sc, u_short *data,
@@ -426,7 +427,7 @@
 	struct fxp_rx *rxp;
 	struct ifnet *ifp;
 	uint32_t val;
-	uint16_t data, myea[ETHER_ADDR_LEN / 2];
+	uint16_t data;
 	u_char eaddr[ETHER_ADDR_LEN];
 	int error, flags, i, pmc, prefer_iomap;
=20
@@ -498,6 +499,7 @@
 	 * Find out how large of an SEEPROM we have.
 	 */
 	fxp_autosize_eeprom(sc);
+	fxp_load_eeprom(sc);
=20
 	/*
 	 * Find out the chip revision; lump all 82557 revs together.
@@ -507,7 +509,7 @@
 		/* Assume ICH controllers are 82559. */
 		sc->revision =3D FXP_REV_82559_A0;
 	} else {
-		fxp_read_eeprom(sc, &data, 5, 1);
+		data =3D sc->eeprom[FXP_EEPROM_MAP_CNTR];
 		if ((data >> 8) =3D=3D 1)
 			sc->revision =3D FXP_REV_82557;
 		else
@@ -519,15 +521,27 @@
 	 */
 	if (sc->revision >=3D FXP_REV_82558_A4 &&
 	    sc->revision !=3D FXP_REV_82559S_A) {
-		fxp_read_eeprom(sc, &data, 10, 1);
+		data =3D sc->eeprom[FXP_EEPROM_MAP_ID];
 		if ((data & 0x20) !=3D 0 &&
 		    pci_find_cap(sc->dev, PCIY_PMG, &pmc) =3D=3D 0)
 			sc->flags |=3D FXP_FLAG_WOLCAP;
 	}
=20
+	if (sc->revision =3D=3D FXP_REV_82550_C) {
+		/*
+		 * 82550C with server extension requires microcode to
+		 * receive fragmented UDP datagrams.  However if the
+		 * microcode is used for client-only featured 82550C
+		 * it locks up controller.
+		 */
+		data =3D sc->eeprom[FXP_EEPROM_MAP_COMPAT];
+		if ((data & 0x0400) =3D=3D 0)
+			sc->flags |=3D FXP_FLAG_NO_UCODE;
+	}
+
 	/* Receiver lock-up workaround detection. */
 	if (sc->revision < FXP_REV_82558_A4) {
-		fxp_read_eeprom(sc, &data, 3, 1);
+		data =3D sc->eeprom[FXP_EEPROM_MAP_COMPAT];
 		if ((data & 0x03) !=3D 0x03) {
 			sc->flags |=3D FXP_FLAG_RXBUG;
 			device_printf(dev, "Enabling Rx lock-up workaround\n");
@@ -537,7 +551,7 @@
 	/*
 	 * Determine whether we must use the 503 serial interface.
 	 */
-	fxp_read_eeprom(sc, &data, 6, 1);
+	data =3D sc->eeprom[FXP_EEPROM_MAP_PRI_PHY];
 	if (sc->revision =3D=3D FXP_REV_82557 && (data & FXP_PHY_DEVICE_MASK) !=
=3D 0
 	    && (data & FXP_PHY_SERIAL_ONLY))
 		sc->flags |=3D FXP_FLAG_SERIAL_MEDIA;
@@ -557,7 +571,7 @@
 	 */
 	if ((sc->ident->ich >=3D 2 && sc->ident->ich <=3D 3) ||
 	    (sc->ident->ich =3D=3D 0 && sc->revision >=3D FXP_REV_82559_A0)) {
-		fxp_read_eeprom(sc, &data, 10, 1);
+		data =3D sc->eeprom[FXP_EEPROM_MAP_ID];
 		if (data & 0x02) {			/* STB enable */
 			uint16_t cksum;
 			int i;
@@ -565,27 +579,24 @@
 			device_printf(dev,
 			    "Disabling dynamic standby mode in EEPROM\n");
 			data &=3D ~0x02;
-			fxp_write_eeprom(sc, &data, 10, 1);
+			sc->eeprom[FXP_EEPROM_MAP_ID] =3D data;
+			fxp_write_eeprom(sc, &data, FXP_EEPROM_MAP_ID, 1);
 			device_printf(dev, "New EEPROM ID: 0x%x\n", data);
 			cksum =3D 0;
-			for (i =3D 0; i < (1 << sc->eeprom_size) - 1; i++) {
-				fxp_read_eeprom(sc, &data, i, 1);
-				cksum +=3D data;
-			}
+			for (i =3D 0; i < (1 << sc->eeprom_size) - 1; i++)
+				cksum +=3D sc->eeprom[i];
 			i =3D (1 << sc->eeprom_size) - 1;
 			cksum =3D 0xBABA - cksum;
-			fxp_read_eeprom(sc, &data, i, 1);
 			fxp_write_eeprom(sc, &cksum, i, 1);
 			device_printf(dev,
 			    "EEPROM checksum @ 0x%x: 0x%x -> 0x%x\n",
-			    i, data, cksum);
-#if 1
+			    i, sc->eeprom[i], cksum);
+			sc->eeprom[i] =3D cksum;
 			/*
 			 * If the user elects to continue, try the software
 			 * workaround, as it is better than nothing.
 			 */
 			sc->flags |=3D FXP_FLAG_CU_RESUME_BUG;
-#endif
 		}
 	}
=20
@@ -779,21 +790,20 @@
 	/*
 	 * Read MAC address.
 	 */
-	fxp_read_eeprom(sc, myea, 0, 3);
-	eaddr[0] =3D myea[0] & 0xff;
-	eaddr[1] =3D myea[0] >> 8;
-	eaddr[2] =3D myea[1] & 0xff;
-	eaddr[3] =3D myea[1] >> 8;
-	eaddr[4] =3D myea[2] & 0xff;
-	eaddr[5] =3D myea[2] >> 8;
+	eaddr[0] =3D sc->eeprom[FXP_EEPROM_MAP_IA0] & 0xff;
+	eaddr[1] =3D sc->eeprom[FXP_EEPROM_MAP_IA0] >> 8;
+	eaddr[2] =3D sc->eeprom[FXP_EEPROM_MAP_IA1] & 0xff;
+	eaddr[3] =3D sc->eeprom[FXP_EEPROM_MAP_IA1] >> 8;
+	eaddr[4] =3D sc->eeprom[FXP_EEPROM_MAP_IA2] & 0xff;
+	eaddr[5] =3D sc->eeprom[FXP_EEPROM_MAP_IA2] >> 8;
 	if (bootverbose) {
 		device_printf(dev, "PCI IDs: %04x %04x %04x %04x %04x\n",
 		    pci_get_vendor(dev), pci_get_device(dev),
 		    pci_get_subvendor(dev), pci_get_subdevice(dev),
 		    pci_get_revid(dev));
-		fxp_read_eeprom(sc, &data, 10, 1);
 		device_printf(dev, "Dynamic Standby mode is %s\n",
-		    data & 0x02 ? "enabled" : "disabled");
+		    sc->eeprom[FXP_EEPROM_MAP_ID] & 0x02 ? "enabled" :
+		    "disabled");
 	}
=20
 	/*
@@ -1289,6 +1299,23 @@
 		fxp_eeprom_putword(sc, offset + i, data[i]);
 }
=20
+static void
+fxp_load_eeprom(struct fxp_softc *sc)
+{
+	int i;
+	uint16_t cksum;
+
+	fxp_read_eeprom(sc, sc->eeprom, 0, 1 << sc->eeprom_size);
+	cksum =3D 0;
+	for (i =3D 0; i < (1 << sc->eeprom_size) - 1; i++)
+		cksum +=3D sc->eeprom[i];
+	cksum =3D 0xBABA - cksum;
+	if (cksum !=3D sc->eeprom[(1 << sc->eeprom_size) - 1])
+		device_printf(sc->dev,
+		    "EEPROM checksum mismatch! (0x%04x -> 0x%04x)\n",
+		    cksum, sc->eeprom[(1 << sc->eeprom_size) - 1]);
+}
+
 /*
  * Grab the softc lock and call the real fxp_start_body() routine
  */
@@ -2582,12 +2609,6 @@
 	mii_pollstat(mii);
 	ifmr->ifm_active =3D mii->mii_media_active;
 	ifmr->ifm_status =3D mii->mii_media_status;
-
-	if (IFM_SUBTYPE(ifmr->ifm_active) =3D=3D IFM_10_T &&
-	    sc->flags & FXP_FLAG_CU_RESUME_BUG)
-		sc->cu_resume_bug =3D 1;
-	else
-		sc->cu_resume_bug =3D 0;
 	FXP_UNLOCK(sc);
 }
=20
@@ -2780,6 +2801,11 @@
 	    (IFM_AVALID | IFM_ACTIVE))
 		return;
=20
+	if (IFM_SUBTYPE(mii->mii_media_active) =3D=3D IFM_10_T &&
+	    sc->flags & FXP_FLAG_CU_RESUME_BUG)
+		sc->cu_resume_bug =3D 1;
+	else
+		sc->cu_resume_bug =3D 0;
 	/*
 	 * Call fxp_init_body in order to adjust the flow control settings.
 	 * Note that the 82557 doesn't support hardware flow control.
@@ -3014,10 +3040,8 @@
 static uint32_t fxp_ucode_d101b0[] =3D D101_B0_RCVBUNDLE_UCODE;
 static uint32_t fxp_ucode_d101ma[] =3D D101M_B_RCVBUNDLE_UCODE;
 static uint32_t fxp_ucode_d101s[] =3D D101S_RCVBUNDLE_UCODE;
-#ifdef notyet
 static uint32_t fxp_ucode_d102[] =3D D102_B_RCVBUNDLE_UCODE;
 static uint32_t fxp_ucode_d102c[] =3D D102_C_RCVBUNDLE_UCODE;
-#endif
 static uint32_t fxp_ucode_d102e[] =3D D102_E_RCVBUNDLE_UCODE;
=20
 #define UCODE(x)	x, sizeof(x)/sizeof(uint32_t)
@@ -3035,12 +3059,10 @@
 	    D101M_CPUSAVER_DWORD, D101M_CPUSAVER_BUNDLE_MAX_DWORD },
 	{ FXP_REV_82559S_A, UCODE(fxp_ucode_d101s),
 	    D101S_CPUSAVER_DWORD, D101S_CPUSAVER_BUNDLE_MAX_DWORD },
-#ifdef notyet
 	{ FXP_REV_82550, UCODE(fxp_ucode_d102),
 	    D102_B_CPUSAVER_DWORD, D102_B_CPUSAVER_BUNDLE_MAX_DWORD },
 	{ FXP_REV_82550_C, UCODE(fxp_ucode_d102c),
 	    D102_C_CPUSAVER_DWORD, D102_C_CPUSAVER_BUNDLE_MAX_DWORD },
-#endif
 	{ FXP_REV_82551_F, UCODE(fxp_ucode_d102e),
 	    D102_E_CPUSAVER_DWORD, D102_E_CPUSAVER_BUNDLE_MAX_DWORD },
 	{ FXP_REV_82551_10, UCODE(fxp_ucode_d102e),
@@ -3055,6 +3077,9 @@
 	struct fxp_cb_ucode *cbp;
 	int i;
=20
+	if (sc->flags & FXP_FLAG_NO_UCODE)
+		return;
+
 	for (uc =3D ucode_table; uc->ucode !=3D NULL; uc++)
 		if (sc->revision =3D=3D uc->revision)
 			break;
@@ -3087,6 +3112,7 @@
 	    sc->tunable_int_delay,
 	    uc->bundle_max_offset =3D=3D 0 ? 0 : sc->tunable_bundle_max);
 	sc->flags |=3D FXP_FLAG_UCODE;
+	bzero(cbp, FXP_TXCB_SZ);
 }
=20
 #define FXP_SYSCTL_STAT_ADD(c, h, n, p, d)	\
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/fxp/if_fxpreg.h
--- a/head/sys/dev/fxp/if_fxpreg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/fxp/if_fxpreg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/dev/fxp/if_fxpreg.h 233586 2012-03-28 01:27:27Z yong=
ari $
  */
=20
 #define FXP_VENDORID_INTEL	0x8086
@@ -448,6 +448,24 @@
 #define FXP_EEPROM_OPC_READ	0x6
=20
 /*
+ * EEPROM map
+ */
+#define	FXP_EEPROM_MAP_IA0	0x00		/* Station address */
+#define	FXP_EEPROM_MAP_IA1	0x01
+#define	FXP_EEPROM_MAP_IA2	0x02
+#define	FXP_EEPROM_MAP_COMPAT	0x03		/* Compatibility */
+#define	FXP_EEPROM_MAP_CNTR	0x05		/* Controller/connector type */
+#define	FXP_EEPROM_MAP_PRI_PHY	0x06		/* Primary PHY record */
+#define	FXP_EEPROM_MAP_SEC_PHY	0x07		/* Secondary PHY record */
+#define	FXP_EEPROM_MAP_PWA0	0x08		/* Printed wire assembly num. */
+#define	FXP_EEPROM_MAP_PWA1	0x09		/* Printed wire assembly num. */
+#define	FXP_EEPROM_MAP_ID	0x0A		/* EEPROM ID */
+#define	FXP_EEPROM_MAP_SUBSYS	0x0B		/* Subsystem ID */
+#define	FXP_EEPROM_MAP_SUBVEN	0x0C		/* Subsystem vendor ID */
+#define	FXP_EEPROM_MAP_CKSUM64	0x3F		/* 64-word EEPROM checksum */
+#define	FXP_EEPROM_MAP_CKSUM256	0xFF		/* 256-word EEPROM checksum */
+
+/*
  * Management Data Interface opcodes
  */
 #define FXP_MDI_WRITE		0x1
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/fxp/if_fxpvar.h
--- a/head/sys/dev/fxp/if_fxpvar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/fxp/if_fxpvar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/dev/fxp/if_fxpvar.h 233586 2012-03-28 01:27:27Z yong=
ari $
  */
=20
 /*
@@ -219,6 +219,7 @@
 	int if_flags;
 	uint8_t rfa_size;
 	uint32_t tx_cmd;
+	uint16_t eeprom[256];
 };
=20
 #define FXP_FLAG_MWI_ENABLE	0x0001	/* MWI enable */
@@ -236,6 +237,7 @@
 #define FXP_FLAG_WOLCAP		0x2000	/* WOL capability */
 #define FXP_FLAG_WOL		0x4000	/* WOL active */
 #define FXP_FLAG_RXBUG		0x8000	/* Rx lock-up bug */
+#define FXP_FLAG_NO_UCODE	0x10000	/* ucode is not applicable */
=20
 /* Macros to ease CSR access. */
 #define	CSR_READ_1(sc, reg)		bus_read_1(sc->fxp_res[0], reg)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/gpio/gpioc.c
--- a/head/sys/dev/gpio/gpioc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/gpio/gpioc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/gpio/gpioc.c 226500 2011-10-18 08:09:44Z =
ed $");
+__FBSDID("$FreeBSD: head/sys/dev/gpio/gpioc.c 233767 2012-04-02 00:11:26Z =
gonzo $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -102,7 +102,7 @@
 	struct gpioc_softc *sc =3D device_get_softc(dev);
 	int err;
=20
-	if (sc->sc_ctl_dev);
+	if (sc->sc_ctl_dev)
 		destroy_dev(sc->sc_ctl_dev);
=20
 	if ((err =3D bus_generic_detach(dev)) !=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_amd.c
--- a/head/sys/dev/hwpmc/hwpmc_amd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_amd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_amd.c 229076 2011-12-31 12:37=
:07Z dim $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_amd.c 233628 2012-03-28 20:58=
:30Z fabient $");
=20
 /* Support for the AMD K7 and later processors */
=20
@@ -687,7 +687,8 @@
 		wrmsr(perfctr, AMD_RELOAD_COUNT_TO_PERFCTR_VALUE(v));
=20
 		/* Restart the counter if logging succeeded. */
-		error =3D pmc_process_interrupt(cpu, pm, tf, TRAPF_USERMODE(tf));
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
+		    TRAPF_USERMODE(tf));
 		if (error =3D=3D 0)
 			wrmsr(evsel, config | AMD_PMC_ENABLE);
 	}
@@ -874,7 +875,7 @@
 struct pmc_mdep *
 pmc_amd_initialize(void)
 {
-	int classindex, error, i, nclasses, ncpus;
+	int classindex, error, i, ncpus;
 	struct pmc_classdep *pcd;
 	enum pmc_cputype cputype;
 	struct pmc_mdep *pmc_mdep;
@@ -926,12 +927,9 @@
 	 * These processors have two classes of PMCs: the TSC and
 	 * programmable PMCs.
 	 */
-	nclasses =3D 2;
-	pmc_mdep =3D malloc(sizeof(struct pmc_mdep) + nclasses * sizeof (struct p=
mc_classdep),
-	    M_PMC, M_WAITOK|M_ZERO);
+	pmc_mdep =3D pmc_mdep_alloc(2);
=20
 	pmc_mdep->pmd_cputype =3D cputype;
-	pmc_mdep->pmd_nclass  =3D nclasses;
=20
 	ncpus =3D pmc_cpu_max();
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_core.c
--- a/head/sys/dev/hwpmc/hwpmc_core.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_core.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_core.c 232612 2012-03-06 17:1=
7:03Z gnn $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_core.c 233628 2012-03-28 20:5=
8:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -2239,7 +2239,7 @@
 		if (pm->pm_state !=3D PMC_STATE_RUNNING)
 			continue;
=20
-		error =3D pmc_process_interrupt(cpu, pm, tf,
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
 		    TRAPF_USERMODE(tf));
=20
 		v =3D pm->pm_sc.pm_reloadcount;
@@ -2326,7 +2326,7 @@
 		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
 			continue;
=20
-		error =3D pmc_process_interrupt(cpu, pm, tf,
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
 		    TRAPF_USERMODE(tf));
 		if (error)
 			intrenable &=3D ~flag;
@@ -2354,7 +2354,7 @@
 		    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
 			continue;
=20
-		error =3D pmc_process_interrupt(cpu, pm, tf,
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
 		    TRAPF_USERMODE(tf));
 		if (error)
 			intrenable &=3D ~flag;
@@ -2406,8 +2406,12 @@
 	PMCDBG(MDP,INI,1,"core-init cputype=3D%d ncpu=3D%d ipa-version=3D%d",
 	    md->pmd_cputype, maxcpu, ipa_version);
=20
-	if (ipa_version < 1 || ipa_version > 3)	/* Unknown PMC architecture. */
+	if (ipa_version < 1 || ipa_version > 3) {
+		/* Unknown PMC architecture. */
+		printf("hwpc_core: unknown PMC architecture: %d\n",
+		    ipa_version);
 		return (EPROGMISMATCH);
+	}
=20
 	core_cputype =3D md->pmd_cputype;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_intel.c
--- a/head/sys/dev/hwpmc/hwpmc_intel.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_intel.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_intel.c 232366 2012-03-01 21:=
23:26Z davide $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_intel.c 233628 2012-03-28 20:=
58:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/pmc.h>
@@ -162,12 +162,10 @@
 		return (NULL);
 	}
=20
-	pmc_mdep =3D malloc(sizeof(struct pmc_mdep) + nclasses *
-	    sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
+	/* Allocate base class and initialize machine dependent struct */
+	pmc_mdep =3D pmc_mdep_alloc(nclasses);
=20
 	pmc_mdep->pmd_cputype 	 =3D cputype;
-	pmc_mdep->pmd_nclass	 =3D nclasses;
-
 	pmc_mdep->pmd_switch_in	 =3D intel_switch_in;
 	pmc_mdep->pmd_switch_out =3D intel_switch_out;
=20
@@ -239,6 +237,9 @@
 		KASSERT(0, ("[intel,%d] Unknown CPU type", __LINE__));
 	}
=20
+	if (error)
+		goto error;
+
 	/*
 	 * Init the uncore class.
 	 */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_logging.c
--- a/head/sys/dev/hwpmc/hwpmc_logging.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_logging.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_logging.c 226514 2011-10-18 1=
5:25:43Z fabient $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_logging.c 233628 2012-03-28 2=
0:58:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/capability.h>
@@ -129,6 +129,7 @@
=20
 /* Emit a string.  Caution: does NOT update _le, so needs to be last */
 #define	PMCLOG_EMITSTRING(S,L)	do { bcopy((S), _le, (L)); } while (0)
+#define	PMCLOG_EMITNULLSTRING(L) do { bzero(_le, (L)); } while (0)
=20
 #define	PMCLOG_DESPATCH(PO)						\
 		pmclog_release((PO));					\
@@ -285,6 +286,7 @@
 			if ((lb =3D TAILQ_FIRST(&po->po_logbuffers)) =3D=3D NULL) {
 				mtx_unlock_spin(&po->po_mtx);
=20
+				/* No more buffers and shutdown required. */
 				if (po->po_flags & PMC_PO_SHUTDOWN) {
 					mtx_unlock(&pmc_kthread_mtx);
 					/*
@@ -293,6 +295,7 @@
 					 */
 					fo_close(po->po_file, curthread);
 					mtx_lock(&pmc_kthread_mtx);
+					break;
 				}
=20
 				(void) msleep(po, &pmc_kthread_mtx, PWAIT,
@@ -355,6 +358,7 @@
 		lb =3D NULL;
 	}
=20
+	wakeup_one(po->po_kthread);
 	po->po_kthread =3D NULL;
=20
 	mtx_unlock(&pmc_kthread_mtx);
@@ -653,8 +657,7 @@
 	    ("[pmclog,%d] po=3D%p no log file", __LINE__, po));
=20
 	/* stop the kthread, this will reset the 'OWNS_LOGFILE' flag */
-	if (po->po_kthread)
-		pmclog_stop_kthread(po);
+	pmclog_stop_kthread(po);
=20
 	KASSERT(po->po_kthread =3D=3D NULL,
 	    ("[pmclog,%d] po=3D%p kthread not stopped", __LINE__, po));
@@ -833,16 +836,33 @@
 pmclog_process_pmcallocate(struct pmc *pm)
 {
 	struct pmc_owner *po;
+	struct pmc_soft *ps;
=20
 	po =3D pm->pm_owner;
=20
 	PMCDBG(LOG,ALL,1, "pm=3D%p", pm);
=20
-	PMCLOG_RESERVE(po, PMCALLOCATE, sizeof(struct pmclog_pmcallocate));
-	PMCLOG_EMIT32(pm->pm_id);
-	PMCLOG_EMIT32(pm->pm_event);
-	PMCLOG_EMIT32(pm->pm_flags);
-	PMCLOG_DESPATCH(po);
+	if (PMC_TO_CLASS(pm) =3D=3D PMC_CLASS_SOFT) {
+		PMCLOG_RESERVE(po, PMCALLOCATEDYN,
+		    sizeof(struct pmclog_pmcallocatedyn));
+		PMCLOG_EMIT32(pm->pm_id);
+		PMCLOG_EMIT32(pm->pm_event);
+		PMCLOG_EMIT32(pm->pm_flags);
+		ps =3D pmc_soft_ev_acquire(pm->pm_event);
+		if (ps !=3D NULL)
+			PMCLOG_EMITSTRING(ps->ps_ev.pm_ev_name,PMC_NAME_MAX);
+		else
+			PMCLOG_EMITNULLSTRING(PMC_NAME_MAX);
+		pmc_soft_ev_release(ps);
+		PMCLOG_DESPATCH(po);
+	} else {
+		PMCLOG_RESERVE(po, PMCALLOCATE,
+		    sizeof(struct pmclog_pmcallocate));
+		PMCLOG_EMIT32(pm->pm_id);
+		PMCLOG_EMIT32(pm->pm_event);
+		PMCLOG_EMIT32(pm->pm_flags);
+		PMCLOG_DESPATCH(po);
+	}
 }
=20
 void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_mips.c
--- a/head/sys/dev/hwpmc/hwpmc_mips.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_mips.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,10 +26,13 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mips.c 232992 2012-03-14 23:4=
6:07Z gonzo $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mips.c 233628 2012-03-28 20:5=
8:30Z fabient $");
+
+#include "opt_hwpmc_hooks.h"
=20
 #include <sys/param.h>
 #include <sys/pmc.h>
+#include <sys/pmckern.h>
 #include <sys/systm.h>
=20
 #include <machine/pmc_mdep.h>
@@ -37,6 +40,17 @@
 #include <machine/mips_opcode.h>
 #include <machine/vmparam.h>
=20
+int mips_npmcs;
+
+/*
+ * Per-processor information.
+ */
+struct mips_cpu {
+	struct pmc_hw	*pc_mipspmcs;
+};
+
+static struct mips_cpu **mips_pcpu;
+
 #if defined(__mips_n64)
 #	define	MIPS_IS_VALID_KERNELADDR(reg)	((((reg) & 3) =3D=3D 0) && \
 					((vm_offset_t)(reg) >=3D MIPS_XKPHYS_START))
@@ -53,6 +67,413 @@
 #define	MAX_PROLOGUE_SIZE 0x100
=20
 static int
+mips_allocate_pmc(int cpu, int ri, struct pmc *pm,
+  const struct pmc_op_pmcallocate *a)
+{
+	enum pmc_event pe;
+	uint32_t caps, config, counter;
+	uint32_t event;
+	int i;
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
+	KASSERT(ri >=3D 0 && ri < mips_npmcs,
+	    ("[mips,%d] illegal row index %d", __LINE__, ri));
+
+	caps =3D a->pm_caps;
+	if (a->pm_class !=3D mips_pmc_spec.ps_cpuclass)
+		return (EINVAL);
+	pe =3D a->pm_ev;
+	counter =3D MIPS_CTR_ALL;
+	event =3D 0;
+	for (i =3D 0; i < mips_event_codes_size; i++) {
+		if (mips_event_codes[i].pe_ev =3D=3D pe) {
+			event =3D mips_event_codes[i].pe_code;
+			counter =3D  mips_event_codes[i].pe_counter;
+			break;
+		}
+	}
+
+	if (i =3D=3D mips_event_codes_size)
+		return (EINVAL);
+
+	if ((counter !=3D MIPS_CTR_ALL) && (counter !=3D ri))
+		return (EINVAL);
+
+	config =3D mips_get_perfctl(cpu, ri, event, caps);
+
+	pm->pm_md.pm_mips_evsel =3D config;
+
+	PMCDBG(MDP,ALL,2,"mips-allocate ri=3D%d -> config=3D0x%x", ri, config);
+
+	return 0;
+}
+
+
+static int
+mips_read_pmc(int cpu, int ri, pmc_value_t *v)
+{
+	struct pmc *pm;
+	pmc_value_t tmp;
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
+	KASSERT(ri >=3D 0 && ri < mips_npmcs,
+	    ("[mips,%d] illegal row index %d", __LINE__, ri));
+
+	pm  =3D mips_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
+	tmp =3D mips_pmcn_read(ri);
+	PMCDBG(MDP,REA,2,"mips-read id=3D%d -> %jd", ri, tmp);
+
+	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
+		*v =3D tmp - (1UL << (mips_pmc_spec.ps_counter_width - 1));
+	else
+		*v =3D tmp;
+
+	return 0;
+}
+
+static int
+mips_write_pmc(int cpu, int ri, pmc_value_t v)
+{
+	struct pmc *pm;
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
+	KASSERT(ri >=3D 0 && ri < mips_npmcs,
+	    ("[mips,%d] illegal row-index %d", __LINE__, ri));
+
+	pm  =3D mips_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
+
+	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
+		v =3D (1UL << (mips_pmc_spec.ps_counter_width - 1)) - v;
+=09
+	PMCDBG(MDP,WRI,1,"mips-write cpu=3D%d ri=3D%d v=3D%jx", cpu, ri, v);
+
+	mips_pmcn_write(ri, v);
+
+	return 0;
+}
+
+static int
+mips_config_pmc(int cpu, int ri, struct pmc *pm)
+{
+	struct pmc_hw *phw;
+
+	PMCDBG(MDP,CFG,1, "cpu=3D%d ri=3D%d pm=3D%p", cpu, ri, pm);
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
+	KASSERT(ri >=3D 0 && ri < mips_npmcs,
+	    ("[mips,%d] illegal row-index %d", __LINE__, ri));
+
+	phw =3D &mips_pcpu[cpu]->pc_mipspmcs[ri];
+
+	KASSERT(pm =3D=3D NULL || phw->phw_pmc =3D=3D NULL,
+	    ("[mips,%d] pm=3D%p phw->pm=3D%p hwpmc not unconfigured",
+	    __LINE__, pm, phw->phw_pmc));
+
+	phw->phw_pmc =3D pm;
+
+	return 0;
+}
+
+static int
+mips_start_pmc(int cpu, int ri)
+{
+	uint32_t config;
+        struct pmc *pm;
+        struct pmc_hw *phw;
+
+	phw    =3D &mips_pcpu[cpu]->pc_mipspmcs[ri];
+	pm     =3D phw->phw_pmc;
+	config =3D pm->pm_md.pm_mips_evsel;
+
+	/* Enable the PMC. */
+	switch (ri) {
+	case 0:
+		mips_wr_perfcnt0(config);
+		break;
+	case 1:
+		mips_wr_perfcnt2(config);
+		break;
+	default:
+		break;
+	}
+
+	return 0;
+}
+
+static int
+mips_stop_pmc(int cpu, int ri)
+{
+        struct pmc *pm;
+        struct pmc_hw *phw;
+
+	phw    =3D &mips_pcpu[cpu]->pc_mipspmcs[ri];
+	pm     =3D phw->phw_pmc;
+
+	/*
+	 * Disable the PMCs.
+	 *
+	 * Clearing the entire register turns the counter off as well
+	 * as removes the previously sampled event.
+	 */
+	switch (ri) {
+	case 0:
+		mips_wr_perfcnt0(0);
+		break;
+	case 1:
+		mips_wr_perfcnt2(0);
+		break;
+	default:
+		break;
+	}
+	return 0;
+}
+
+static int
+mips_release_pmc(int cpu, int ri, struct pmc *pmc)
+{
+	struct pmc_hw *phw;
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
+	KASSERT(ri >=3D 0 && ri < mips_npmcs,
+	    ("[mips,%d] illegal row-index %d", __LINE__, ri));
+
+	phw =3D &mips_pcpu[cpu]->pc_mipspmcs[ri];
+	KASSERT(phw->phw_pmc =3D=3D NULL,
+	    ("[mips,%d] PHW pmc %p non-NULL", __LINE__, phw->phw_pmc));
+
+	return 0;
+}
+
+static int
+mips_pmc_intr(int cpu, struct trapframe *tf)
+{
+	int error;
+	int retval, ri;
+	struct pmc *pm;
+	struct mips_cpu *pc;
+	uint32_t r0, r2;
+	pmc_value_t r;
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d] CPU %d out of range", __LINE__, cpu));
+
+	retval =3D 0;
+	pc =3D mips_pcpu[cpu];
+
+	/* Stop PMCs without clearing the counter */
+	r0 =3D mips_rd_perfcnt0();
+	mips_wr_perfcnt0(r0 & ~(0x1f));
+	r2 =3D mips_rd_perfcnt2();
+	mips_wr_perfcnt2(r2 & ~(0x1f));
+
+	for (ri =3D 0; ri < mips_npmcs; ri++) {
+		pm =3D mips_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
+		if (pm =3D=3D NULL)
+			continue;
+		if (! PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
+			continue;
+
+		r =3D mips_pmcn_read(ri);
+
+		/* If bit 31 is set, the counter has overflowed */
+		if ((r & (1UL << (mips_pmc_spec.ps_counter_width - 1))) =3D=3D 0)
+			continue;
+
+		retval =3D 1;
+		if (pm->pm_state !=3D PMC_STATE_RUNNING)
+			continue;
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
+		    TRAPF_USERMODE(tf));
+		if (error) {
+			/* Clear/disable the relevant counter */
+			if (ri =3D=3D 0)
+				r0 =3D 0;
+			else if (ri =3D=3D 1)
+				r2 =3D 0;
+			mips_stop_pmc(cpu, ri);
+		}
+
+		/* Reload sampling count */
+		mips_write_pmc(cpu, ri, pm->pm_sc.pm_reloadcount);
+	}
+
+	/*
+	 * Re-enable the PMC counters where they left off.
+	 *
+	 * Any counter which overflowed will have its sample count
+	 * reloaded in the loop above.
+	 */
+	mips_wr_perfcnt0(r0);
+	mips_wr_perfcnt2(r2);
+
+	return retval;
+}
+
+static int
+mips_describe(int cpu, int ri, struct pmc_info *pi, struct pmc **ppmc)
+{
+	int error;
+	struct pmc_hw *phw;
+	char mips_name[PMC_NAME_MAX];
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d], illegal CPU %d", __LINE__, cpu));
+	KASSERT(ri >=3D 0 && ri < mips_npmcs,
+	    ("[mips,%d] row-index %d out of range", __LINE__, ri));
+
+	phw =3D &mips_pcpu[cpu]->pc_mipspmcs[ri];
+	snprintf(mips_name, sizeof(mips_name), "MIPS-%d", ri);
+	if ((error =3D copystr(mips_name, pi->pm_name, PMC_NAME_MAX,
+	    NULL)) !=3D 0)
+		return error;
+	pi->pm_class =3D mips_pmc_spec.ps_cpuclass;
+	if (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) {
+		pi->pm_enabled =3D TRUE;
+		*ppmc          =3D phw->phw_pmc;
+	} else {
+		pi->pm_enabled =3D FALSE;
+		*ppmc	       =3D NULL;
+	}
+
+	return (0);
+}
+
+static int
+mips_get_config(int cpu, int ri, struct pmc **ppm)
+{
+	*ppm =3D mips_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
+
+	return 0;
+}
+
+/*
+ * XXX don't know what we should do here.
+ */
+static int
+mips_pmc_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
+{
+	return 0;
+}
+
+static int
+mips_pmc_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
+{
+	return 0;
+}
+
+static int
+mips_pcpu_init(struct pmc_mdep *md, int cpu)
+{
+	int first_ri, i;
+	struct pmc_cpu *pc;
+	struct mips_cpu *pac;
+	struct pmc_hw  *phw;
+
+	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
+	    ("[mips,%d] wrong cpu number %d", __LINE__, cpu));
+	PMCDBG(MDP,INI,1,"mips-init cpu=3D%d", cpu);
+
+	mips_pcpu[cpu] =3D pac =3D malloc(sizeof(struct mips_cpu), M_PMC,
+	    M_WAITOK|M_ZERO);
+	pac->pc_mipspmcs =3D malloc(sizeof(struct pmc_hw) * mips_npmcs,
+	    M_PMC, M_WAITOK|M_ZERO);
+	pc =3D pmc_pcpu[cpu];
+	first_ri =3D md->pmd_classdep[PMC_MDEP_CLASS_INDEX_MIPS].pcd_ri;
+	KASSERT(pc !=3D NULL, ("[mips,%d] NULL per-cpu pointer", __LINE__));
+
+	for (i =3D 0, phw =3D pac->pc_mipspmcs; i < mips_npmcs; i++, phw++) {
+		phw->phw_state    =3D PMC_PHW_FLAG_IS_ENABLED |
+		    PMC_PHW_CPU_TO_STATE(cpu) | PMC_PHW_INDEX_TO_STATE(i);
+		phw->phw_pmc      =3D NULL;
+		pc->pc_hwpmcs[i + first_ri] =3D phw;
+	}
+
+	/*
+	 * Clear the counter control register which has the effect
+	 * of disabling counting.
+	 */
+	for (i =3D 0; i < mips_npmcs; i++)
+		mips_pmcn_write(i, 0);
+
+	return 0;
+}
+
+static int
+mips_pcpu_fini(struct pmc_mdep *md, int cpu)
+{
+	return 0;
+}
+
+struct pmc_mdep *
+pmc_mips_initialize()
+{
+	struct pmc_mdep *pmc_mdep;
+	struct pmc_classdep *pcd;
+=09
+	/*
+	 * TODO: Use More bit of PerfCntlX register to detect actual=20
+	 * number of counters
+	 */
+	mips_npmcs =3D 2;
+=09
+	PMCDBG(MDP,INI,1,"mips-init npmcs=3D%d", mips_npmcs);
+
+	/*
+	 * Allocate space for pointers to PMC HW descriptors and for
+	 * the MDEP structure used by MI code.
+	 */
+	mips_pcpu =3D malloc(sizeof(struct mips_cpu *) * pmc_cpu_max(), M_PMC,
+			   M_WAITOK|M_ZERO);
+
+	/* Just one class */
+	pmc_mdep =3D malloc(sizeof(struct pmc_mdep) + sizeof(struct pmc_classdep),
+			  M_PMC, M_WAITOK|M_ZERO);
+
+	pmc_mdep->pmd_cputype =3D mips_pmc_spec.ps_cputype;
+	pmc_mdep->pmd_nclass  =3D 1;
+
+	pcd =3D &pmc_mdep->pmd_classdep[PMC_MDEP_CLASS_INDEX_MIPS];
+	pcd->pcd_caps  =3D mips_pmc_spec.ps_capabilities;
+	pcd->pcd_class =3D mips_pmc_spec.ps_cpuclass;
+	pcd->pcd_num   =3D mips_npmcs;
+	pcd->pcd_ri    =3D pmc_mdep->pmd_npmc;
+	pcd->pcd_width =3D mips_pmc_spec.ps_counter_width;
+
+	pcd->pcd_allocate_pmc   =3D mips_allocate_pmc;
+	pcd->pcd_config_pmc     =3D mips_config_pmc;
+	pcd->pcd_pcpu_fini      =3D mips_pcpu_fini;
+	pcd->pcd_pcpu_init      =3D mips_pcpu_init;
+	pcd->pcd_describe       =3D mips_describe;
+	pcd->pcd_get_config	=3D mips_get_config;
+	pcd->pcd_read_pmc       =3D mips_read_pmc;
+	pcd->pcd_release_pmc    =3D mips_release_pmc;
+	pcd->pcd_start_pmc      =3D mips_start_pmc;
+	pcd->pcd_stop_pmc       =3D mips_stop_pmc;
+ 	pcd->pcd_write_pmc      =3D mips_write_pmc;
+
+	pmc_mdep->pmd_intr       =3D mips_pmc_intr;
+	pmc_mdep->pmd_switch_in  =3D mips_pmc_switch_in;
+	pmc_mdep->pmd_switch_out =3D mips_pmc_switch_out;
+=09
+	pmc_mdep->pmd_npmc   +=3D mips_npmcs;
+
+	return (pmc_mdep);
+}
+
+void
+pmc_mips_finalize(struct pmc_mdep *md)
+{
+	(void) md;
+}
+
+#ifdef	HWPMC_MIPS_BACKTRACE
+
+static int
 pmc_next_frame(register_t *pc, register_t *sp)
 {
 	InstFmt i;
@@ -310,23 +731,18 @@
 	return (0);
 }
=20
+#endif /* HWPMC_MIPS_BACKTRACE */
+
 struct pmc_mdep *
 pmc_md_initialize()
 {
-  /*	if (cpu_class =3D=3D CPU_CLASS_MIPS24K)*/
-		return pmc_mips24k_initialize();
-		/*	else
-			return NULL;*/
+	return pmc_mips_initialize();
 }
=20
 void
 pmc_md_finalize(struct pmc_mdep *md)
 {
-  /*	if (cpu_class =3D=3D CPU_CLASS_MIPS24K) */
-		pmc_mips24k_finalize(md);
-		/*	else
-		KASSERT(0, ("[mips,%d] Unknown CPU Class 0x%x", __LINE__,
-		cpu_class));*/
+	return pmc_mips_finalize(md);
 }
=20
 int
@@ -340,17 +756,22 @@
 	sp =3D tf->sp;
 	ra =3D tf->ra;
=20
+	cc[frames++] =3D pc;
+
+#ifdef	HWPMC_MIPS_BACKTRACE
 	/*
 	 * Unwind, and unwind, and unwind
 	 */
 	while (1) {
-		cc[frames++] =3D pc;
 		if (frames >=3D nframes)
 			break;
=20
 		if (pmc_next_frame(&pc, &sp) < 0)
 			break;
+
+		cc[frames++] =3D pc;
 	}
+#endif
=20
 	return (frames);
 }
@@ -366,17 +787,23 @@
 	sp =3D tf->sp;
 	ra =3D tf->ra;
=20
+	cc[frames++] =3D pc;
+
+#ifdef	HWPMC_MIPS_BACKTRACE
+
 	/*
 	 * Unwind, and unwind, and unwind
 	 */
 	while (1) {
-		cc[frames++] =3D pc;
 		if (frames >=3D nframes)
 			break;
=20
 		if (pmc_next_uframe(&pc, &sp, &ra) < 0)
 			break;
+
+		cc[frames++] =3D pc;
 	}
+#endif
=20
 	return (frames);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_mips24k.c
--- a/head/sys/dev/hwpmc/hwpmc_mips24k.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_mips24k.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mips24k.c 232869 2012-03-12 1=
7:25:35Z adrian $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mips24k.c 233319 2012-03-22 1=
8:01:23Z gonzo $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -37,147 +37,137 @@
 #include <machine/cpufunc.h>
 #include <machine/pmc_mdep.h>
=20
-/*
- * Support for MIPS CPUs
- *
- */
-static int mips24k_npmcs;
+#define	MIPS24K_PMC_CAPS	(PMC_CAP_INTERRUPT | PMC_CAP_USER |     \
+				 PMC_CAP_SYSTEM | PMC_CAP_EDGE |	\
+				 PMC_CAP_THRESHOLD | PMC_CAP_READ |	\
+				 PMC_CAP_WRITE | PMC_CAP_INVERT |	\
+				 PMC_CAP_QUALIFIER)
=20
-struct mips24k_event_code_map {
-	enum pmc_event	pe_ev;       /* enum value */
-	uint8_t         pe_counter;  /* Which counter this can be counted in. */
-	uint8_t		pe_code;     /* numeric code */
-};
+#define MIPS24K_PMC_INTERRUPT_ENABLE      0x10 /* Enable interrupts */
+#define MIPS24K_PMC_USER_ENABLE           0x08 /* Count in USER mode */
+#define MIPS24K_PMC_SUPER_ENABLE          0x04 /* Count in SUPERVISOR mode=
 */
+#define MIPS24K_PMC_KERNEL_ENABLE         0x02 /* Count in KERNEL mode */
+#define MIPS24K_PMC_ENABLE (MIPS24K_PMC_USER_ENABLE |	   \
+			    MIPS24K_PMC_SUPER_ENABLE |	   \
+			    MIPS24K_PMC_KERNEL_ENABLE)
=20
-/*
- * MIPS event codes are encoded with a select bit.  The
- * select bit is used when writing to CP0 so that we=20
- * can select either counter 0/2 or 1/3.  The cycle
- * and instruction counters are special in that they
- * can be counted on either 0/2 or 1/3.
- */
+#define MIPS24K_PMC_SELECT 5 /* Which bit position the event starts at. */
=20
-#define MIPS24K_ALL 255 /* Count events in any counter. */
-#define MIPS24K_CTR_0 0 /* Counter 0 Event */
-#define MIPS24K_CTR_1 1 /* Counter 1 Event */
-
-const struct mips24k_event_code_map mips24k_event_codes[] =3D {
-	{ PMC_EV_MIPS24K_CYCLE, MIPS24K_ALL, 0},
-	{ PMC_EV_MIPS24K_INSTR_EXECUTED, MIPS24K_ALL, 1},
-	{ PMC_EV_MIPS24K_BRANCH_COMPLETED, MIPS24K_CTR_0, 2},
-	{ PMC_EV_MIPS24K_BRANCH_MISPRED, MIPS24K_CTR_1, 2},
-	{ PMC_EV_MIPS24K_RETURN, MIPS24K_CTR_0, 3},
-	{ PMC_EV_MIPS24K_RETURN_MISPRED, MIPS24K_CTR_1, 3},
-	{ PMC_EV_MIPS24K_RETURN_NOT_31, MIPS24K_CTR_0, 4},
-	{ PMC_EV_MIPS24K_RETURN_NOTPRED, MIPS24K_CTR_1, 4},
-	{ PMC_EV_MIPS24K_ITLB_ACCESS, MIPS24K_CTR_0, 5},
-	{ PMC_EV_MIPS24K_ITLB_MISS, MIPS24K_CTR_1, 5},
-	{ PMC_EV_MIPS24K_DTLB_ACCESS, MIPS24K_CTR_0, 6},
-	{ PMC_EV_MIPS24K_DTLB_MISS, MIPS24K_CTR_1, 6},
-	{ PMC_EV_MIPS24K_JTLB_IACCESS, MIPS24K_CTR_0, 7},
-	{ PMC_EV_MIPS24K_JTLB_IMISS, MIPS24K_CTR_1, 7},
-	{ PMC_EV_MIPS24K_JTLB_DACCESS, MIPS24K_CTR_0, 8},
-	{ PMC_EV_MIPS24K_JTLB_DMISS, MIPS24K_CTR_1, 8},
-	{ PMC_EV_MIPS24K_IC_FETCH, MIPS24K_CTR_0, 9},
-	{ PMC_EV_MIPS24K_IC_MISS, MIPS24K_CTR_1, 9},
-	{ PMC_EV_MIPS24K_DC_LOADSTORE, MIPS24K_CTR_0, 10},
-	{ PMC_EV_MIPS24K_DC_WRITEBACK, MIPS24K_CTR_1, 10},
-	{ PMC_EV_MIPS24K_DC_MISS, MIPS24K_ALL, 11}, =20
+const struct mips_event_code_map mips_event_codes[] =3D {
+	{ PMC_EV_MIPS24K_CYCLE, MIPS_CTR_ALL, 0},
+	{ PMC_EV_MIPS24K_INSTR_EXECUTED, MIPS_CTR_ALL, 1},
+	{ PMC_EV_MIPS24K_BRANCH_COMPLETED, MIPS_CTR_0, 2},
+	{ PMC_EV_MIPS24K_BRANCH_MISPRED, MIPS_CTR_1, 2},
+	{ PMC_EV_MIPS24K_RETURN, MIPS_CTR_0, 3},
+	{ PMC_EV_MIPS24K_RETURN_MISPRED, MIPS_CTR_1, 3},
+	{ PMC_EV_MIPS24K_RETURN_NOT_31, MIPS_CTR_0, 4},
+	{ PMC_EV_MIPS24K_RETURN_NOTPRED, MIPS_CTR_1, 4},
+	{ PMC_EV_MIPS24K_ITLB_ACCESS, MIPS_CTR_0, 5},
+	{ PMC_EV_MIPS24K_ITLB_MISS, MIPS_CTR_1, 5},
+	{ PMC_EV_MIPS24K_DTLB_ACCESS, MIPS_CTR_0, 6},
+	{ PMC_EV_MIPS24K_DTLB_MISS, MIPS_CTR_1, 6},
+	{ PMC_EV_MIPS24K_JTLB_IACCESS, MIPS_CTR_0, 7},
+	{ PMC_EV_MIPS24K_JTLB_IMISS, MIPS_CTR_1, 7},
+	{ PMC_EV_MIPS24K_JTLB_DACCESS, MIPS_CTR_0, 8},
+	{ PMC_EV_MIPS24K_JTLB_DMISS, MIPS_CTR_1, 8},
+	{ PMC_EV_MIPS24K_IC_FETCH, MIPS_CTR_0, 9},
+	{ PMC_EV_MIPS24K_IC_MISS, MIPS_CTR_1, 9},
+	{ PMC_EV_MIPS24K_DC_LOADSTORE, MIPS_CTR_0, 10},
+	{ PMC_EV_MIPS24K_DC_WRITEBACK, MIPS_CTR_1, 10},
+	{ PMC_EV_MIPS24K_DC_MISS, MIPS_CTR_ALL, 11},
 	/* 12 reserved */
-	{ PMC_EV_MIPS24K_STORE_MISS, MIPS24K_CTR_0, 13},
-	{ PMC_EV_MIPS24K_LOAD_MISS, MIPS24K_CTR_1, 13},
-	{ PMC_EV_MIPS24K_INTEGER_COMPLETED, MIPS24K_CTR_0, 14},
-	{ PMC_EV_MIPS24K_FP_COMPLETED, MIPS24K_CTR_1, 14},
-	{ PMC_EV_MIPS24K_LOAD_COMPLETED, MIPS24K_CTR_0, 15},
-	{ PMC_EV_MIPS24K_STORE_COMPLETED, MIPS24K_CTR_1, 15},
-	{ PMC_EV_MIPS24K_BARRIER_COMPLETED, MIPS24K_CTR_0, 16},
-	{ PMC_EV_MIPS24K_MIPS16_COMPLETED, MIPS24K_CTR_1, 16},
-	{ PMC_EV_MIPS24K_NOP_COMPLETED, MIPS24K_CTR_0, 17},
-	{ PMC_EV_MIPS24K_INTEGER_MULDIV_COMPLETED, MIPS24K_CTR_1, 17},
-	{ PMC_EV_MIPS24K_RF_STALL, MIPS24K_CTR_0, 18},
-	{ PMC_EV_MIPS24K_INSTR_REFETCH, MIPS24K_CTR_1, 18},
-	{ PMC_EV_MIPS24K_STORE_COND_COMPLETED, MIPS24K_CTR_0, 19},
-	{ PMC_EV_MIPS24K_STORE_COND_FAILED, MIPS24K_CTR_1, 19},
-	{ PMC_EV_MIPS24K_ICACHE_REQUESTS, MIPS24K_CTR_0, 20},
-	{ PMC_EV_MIPS24K_ICACHE_HIT, MIPS24K_CTR_1, 20},
-	{ PMC_EV_MIPS24K_L2_WRITEBACK, MIPS24K_CTR_0, 21},
-	{ PMC_EV_MIPS24K_L2_ACCESS, MIPS24K_CTR_1, 21},
-	{ PMC_EV_MIPS24K_L2_MISS, MIPS24K_CTR_0, 22},
-	{ PMC_EV_MIPS24K_L2_ERR_CORRECTED, MIPS24K_CTR_1, 22},
-	{ PMC_EV_MIPS24K_EXCEPTIONS, MIPS24K_CTR_0, 23},
+	{ PMC_EV_MIPS24K_STORE_MISS, MIPS_CTR_0, 13},
+	{ PMC_EV_MIPS24K_LOAD_MISS, MIPS_CTR_1, 13},
+	{ PMC_EV_MIPS24K_INTEGER_COMPLETED, MIPS_CTR_0, 14},
+	{ PMC_EV_MIPS24K_FP_COMPLETED, MIPS_CTR_1, 14},
+	{ PMC_EV_MIPS24K_LOAD_COMPLETED, MIPS_CTR_0, 15},
+	{ PMC_EV_MIPS24K_STORE_COMPLETED, MIPS_CTR_1, 15},
+	{ PMC_EV_MIPS24K_BARRIER_COMPLETED, MIPS_CTR_0, 16},
+	{ PMC_EV_MIPS24K_MIPS16_COMPLETED, MIPS_CTR_1, 16},
+	{ PMC_EV_MIPS24K_NOP_COMPLETED, MIPS_CTR_0, 17},
+	{ PMC_EV_MIPS24K_INTEGER_MULDIV_COMPLETED, MIPS_CTR_1, 17},
+	{ PMC_EV_MIPS24K_RF_STALL, MIPS_CTR_0, 18},
+	{ PMC_EV_MIPS24K_INSTR_REFETCH, MIPS_CTR_1, 18},
+	{ PMC_EV_MIPS24K_STORE_COND_COMPLETED, MIPS_CTR_0, 19},
+	{ PMC_EV_MIPS24K_STORE_COND_FAILED, MIPS_CTR_1, 19},
+	{ PMC_EV_MIPS24K_ICACHE_REQUESTS, MIPS_CTR_0, 20},
+	{ PMC_EV_MIPS24K_ICACHE_HIT, MIPS_CTR_1, 20},
+	{ PMC_EV_MIPS24K_L2_WRITEBACK, MIPS_CTR_0, 21},
+	{ PMC_EV_MIPS24K_L2_ACCESS, MIPS_CTR_1, 21},
+	{ PMC_EV_MIPS24K_L2_MISS, MIPS_CTR_0, 22},
+	{ PMC_EV_MIPS24K_L2_ERR_CORRECTED, MIPS_CTR_1, 22},
+	{ PMC_EV_MIPS24K_EXCEPTIONS, MIPS_CTR_0, 23},
 	/* Event 23 on COP0 1/3 is undefined */
-	{ PMC_EV_MIPS24K_RF_CYCLES_STALLED, MIPS24K_CTR_0, 24},
-	{ PMC_EV_MIPS24K_IFU_CYCLES_STALLED, MIPS24K_CTR_0, 25},
-	{ PMC_EV_MIPS24K_ALU_CYCLES_STALLED, MIPS24K_CTR_1, 25},
+	{ PMC_EV_MIPS24K_RF_CYCLES_STALLED, MIPS_CTR_0, 24},
+	{ PMC_EV_MIPS24K_IFU_CYCLES_STALLED, MIPS_CTR_0, 25},
+	{ PMC_EV_MIPS24K_ALU_CYCLES_STALLED, MIPS_CTR_1, 25},
 	/* Events 26 through 32 undefined or reserved to customers */
-	{ PMC_EV_MIPS24K_UNCACHED_LOAD, MIPS24K_CTR_0, 33},
-	{ PMC_EV_MIPS24K_UNCACHED_STORE, MIPS24K_CTR_1, 33},
-	{ PMC_EV_MIPS24K_CP2_REG_TO_REG_COMPLETED, MIPS24K_CTR_0, 35},
-	{ PMC_EV_MIPS24K_MFTC_COMPLETED, MIPS24K_CTR_1, 35},
+	{ PMC_EV_MIPS24K_UNCACHED_LOAD, MIPS_CTR_0, 33},
+	{ PMC_EV_MIPS24K_UNCACHED_STORE, MIPS_CTR_1, 33},
+	{ PMC_EV_MIPS24K_CP2_REG_TO_REG_COMPLETED, MIPS_CTR_0, 35},
+	{ PMC_EV_MIPS24K_MFTC_COMPLETED, MIPS_CTR_1, 35},
 	/* Event 36 reserved */
-	{ PMC_EV_MIPS24K_IC_BLOCKED_CYCLES, MIPS24K_CTR_0, 37},
-	{ PMC_EV_MIPS24K_DC_BLOCKED_CYCLES, MIPS24K_CTR_1, 37},
-	{ PMC_EV_MIPS24K_L2_IMISS_STALL_CYCLES, MIPS24K_CTR_0, 38},
-	{ PMC_EV_MIPS24K_L2_DMISS_STALL_CYCLES, MIPS24K_CTR_1, 38},
-	{ PMC_EV_MIPS24K_DMISS_CYCLES, MIPS24K_CTR_0, 39},
-	{ PMC_EV_MIPS24K_L2_MISS_CYCLES, MIPS24K_CTR_1, 39},
-	{ PMC_EV_MIPS24K_UNCACHED_BLOCK_CYCLES, MIPS24K_CTR_0, 40},
-	{ PMC_EV_MIPS24K_MDU_STALL_CYCLES, MIPS24K_CTR_0, 41},
-	{ PMC_EV_MIPS24K_FPU_STALL_CYCLES, MIPS24K_CTR_1, 41},
-	{ PMC_EV_MIPS24K_CP2_STALL_CYCLES, MIPS24K_CTR_0, 42},
-	{ PMC_EV_MIPS24K_COREXTEND_STALL_CYCLES, MIPS24K_CTR_1, 42},
-	{ PMC_EV_MIPS24K_ISPRAM_STALL_CYCLES, MIPS24K_CTR_0, 43},
-	{ PMC_EV_MIPS24K_DSPRAM_STALL_CYCLES, MIPS24K_CTR_1, 43},
-	{ PMC_EV_MIPS24K_CACHE_STALL_CYCLES, MIPS24K_CTR_0, 44},
+	{ PMC_EV_MIPS24K_IC_BLOCKED_CYCLES, MIPS_CTR_0, 37},
+	{ PMC_EV_MIPS24K_DC_BLOCKED_CYCLES, MIPS_CTR_1, 37},
+	{ PMC_EV_MIPS24K_L2_IMISS_STALL_CYCLES, MIPS_CTR_0, 38},
+	{ PMC_EV_MIPS24K_L2_DMISS_STALL_CYCLES, MIPS_CTR_1, 38},
+	{ PMC_EV_MIPS24K_DMISS_CYCLES, MIPS_CTR_0, 39},
+	{ PMC_EV_MIPS24K_L2_MISS_CYCLES, MIPS_CTR_1, 39},
+	{ PMC_EV_MIPS24K_UNCACHED_BLOCK_CYCLES, MIPS_CTR_0, 40},
+	{ PMC_EV_MIPS24K_MDU_STALL_CYCLES, MIPS_CTR_0, 41},
+	{ PMC_EV_MIPS24K_FPU_STALL_CYCLES, MIPS_CTR_1, 41},
+	{ PMC_EV_MIPS24K_CP2_STALL_CYCLES, MIPS_CTR_0, 42},
+	{ PMC_EV_MIPS24K_COREXTEND_STALL_CYCLES, MIPS_CTR_1, 42},
+	{ PMC_EV_MIPS24K_ISPRAM_STALL_CYCLES, MIPS_CTR_0, 43},
+	{ PMC_EV_MIPS24K_DSPRAM_STALL_CYCLES, MIPS_CTR_1, 43},
+	{ PMC_EV_MIPS24K_CACHE_STALL_CYCLES, MIPS_CTR_0, 44},
 	/* Event 44 undefined on 1/3 */
-	{ PMC_EV_MIPS24K_LOAD_TO_USE_STALLS, MIPS24K_CTR_0, 45},
-	{ PMC_EV_MIPS24K_BASE_MISPRED_STALLS, MIPS24K_CTR_1, 45},
-	{ PMC_EV_MIPS24K_CPO_READ_STALLS, MIPS24K_CTR_0, 46},
-	{ PMC_EV_MIPS24K_BRANCH_MISPRED_CYCLES, MIPS24K_CTR_1, 46},
+	{ PMC_EV_MIPS24K_LOAD_TO_USE_STALLS, MIPS_CTR_0, 45},
+	{ PMC_EV_MIPS24K_BASE_MISPRED_STALLS, MIPS_CTR_1, 45},
+	{ PMC_EV_MIPS24K_CPO_READ_STALLS, MIPS_CTR_0, 46},
+	{ PMC_EV_MIPS24K_BRANCH_MISPRED_CYCLES, MIPS_CTR_1, 46},
 	/* Event 47 reserved */
-	{ PMC_EV_MIPS24K_IFETCH_BUFFER_FULL, MIPS24K_CTR_0, 48},
-	{ PMC_EV_MIPS24K_FETCH_BUFFER_ALLOCATED, MIPS24K_CTR_1, 48},
-	{ PMC_EV_MIPS24K_EJTAG_ITRIGGER, MIPS24K_CTR_0, 49},
-	{ PMC_EV_MIPS24K_EJTAG_DTRIGGER, MIPS24K_CTR_1, 49},
-	{ PMC_EV_MIPS24K_FSB_LT_QUARTER, MIPS24K_CTR_0, 50},
-	{ PMC_EV_MIPS24K_FSB_QUARTER_TO_HALF, MIPS24K_CTR_1, 50},
-	{ PMC_EV_MIPS24K_FSB_GT_HALF, MIPS24K_CTR_0, 51},
-	{ PMC_EV_MIPS24K_FSB_FULL_PIPELINE_STALLS, MIPS24K_CTR_1, 51},
-	{ PMC_EV_MIPS24K_LDQ_LT_QUARTER, MIPS24K_CTR_0, 52},
-	{ PMC_EV_MIPS24K_LDQ_QUARTER_TO_HALF, MIPS24K_CTR_1, 52},
-	{ PMC_EV_MIPS24K_LDQ_GT_HALF, MIPS24K_CTR_0, 53},
-	{ PMC_EV_MIPS24K_LDQ_FULL_PIPELINE_STALLS, MIPS24K_CTR_1, 53},
-	{ PMC_EV_MIPS24K_WBB_LT_QUARTER, MIPS24K_CTR_0, 54},
-	{ PMC_EV_MIPS24K_WBB_QUARTER_TO_HALF, MIPS24K_CTR_1, 54},
-	{ PMC_EV_MIPS24K_WBB_GT_HALF, MIPS24K_CTR_0, 55},
-	{ PMC_EV_MIPS24K_WBB_FULL_PIPELINE_STALLS, MIPS24K_CTR_1, 55},
+	{ PMC_EV_MIPS24K_IFETCH_BUFFER_FULL, MIPS_CTR_0, 48},
+	{ PMC_EV_MIPS24K_FETCH_BUFFER_ALLOCATED, MIPS_CTR_1, 48},
+	{ PMC_EV_MIPS24K_EJTAG_ITRIGGER, MIPS_CTR_0, 49},
+	{ PMC_EV_MIPS24K_EJTAG_DTRIGGER, MIPS_CTR_1, 49},
+	{ PMC_EV_MIPS24K_FSB_LT_QUARTER, MIPS_CTR_0, 50},
+	{ PMC_EV_MIPS24K_FSB_QUARTER_TO_HALF, MIPS_CTR_1, 50},
+	{ PMC_EV_MIPS24K_FSB_GT_HALF, MIPS_CTR_0, 51},
+	{ PMC_EV_MIPS24K_FSB_FULL_PIPELINE_STALLS, MIPS_CTR_1, 51},
+	{ PMC_EV_MIPS24K_LDQ_LT_QUARTER, MIPS_CTR_0, 52},
+	{ PMC_EV_MIPS24K_LDQ_QUARTER_TO_HALF, MIPS_CTR_1, 52},
+	{ PMC_EV_MIPS24K_LDQ_GT_HALF, MIPS_CTR_0, 53},
+	{ PMC_EV_MIPS24K_LDQ_FULL_PIPELINE_STALLS, MIPS_CTR_1, 53},
+	{ PMC_EV_MIPS24K_WBB_LT_QUARTER, MIPS_CTR_0, 54},
+	{ PMC_EV_MIPS24K_WBB_QUARTER_TO_HALF, MIPS_CTR_1, 54},
+	{ PMC_EV_MIPS24K_WBB_GT_HALF, MIPS_CTR_0, 55},
+	{ PMC_EV_MIPS24K_WBB_FULL_PIPELINE_STALLS, MIPS_CTR_1, 55},
 	/* Events 56-63 reserved */
-	{ PMC_EV_MIPS24K_REQUEST_LATENCY, MIPS24K_CTR_0, 61},
-	{ PMC_EV_MIPS24K_REQUEST_COUNT, MIPS24K_CTR_1, 61}
+	{ PMC_EV_MIPS24K_REQUEST_LATENCY, MIPS_CTR_0, 61},
+	{ PMC_EV_MIPS24K_REQUEST_COUNT, MIPS_CTR_1, 61}
=20
 };
=20
-const int mips24k_event_codes_size =3D
-	sizeof(mips24k_event_codes) / sizeof(mips24k_event_codes[0]);
+const int mips_event_codes_size =3D
+	sizeof(mips_event_codes) / sizeof(mips_event_codes[0]);
=20
-/*
- * Per-processor information.
- */
-struct mips24k_cpu {
-	struct pmc_hw   *pc_mipspmcs;
+struct mips_pmc_spec mips_pmc_spec =3D {
+	.ps_cpuclass =3D PMC_CLASS_MIPS24K,
+	.ps_cputype =3D PMC_CPU_MIPS_24K,
+	.ps_capabilities =3D MIPS24K_PMC_CAPS,
+	.ps_counter_width =3D 32
 };
=20
-static struct mips24k_cpu **mips24k_pcpu;
-
 /*
  * Performance Count Register N
  */
-static uint32_t
-mips24k_pmcn_read(unsigned int pmc)
+uint64_t
+mips_pmcn_read(unsigned int pmc)
 {
 	uint32_t reg =3D 0;
=20
-	KASSERT(pmc < mips24k_npmcs, ("[mips,%d] illegal PMC number %d",=20
+	KASSERT(pmc < mips_npmcs, ("[mips24k,%d] illegal PMC number %d",
 				   __LINE__, pmc));
=20
 	/* The counter value is the next value after the control register. */
@@ -194,13 +184,13 @@
 	return (reg);
 }
=20
-static uint32_t
-mips24k_pmcn_write(unsigned int pmc, uint32_t reg)
+uint64_t
+mips_pmcn_write(unsigned int pmc, uint64_t reg)
 {
=20
-	KASSERT(pmc < mips24k_npmcs, ("[mips,%d] illegal PMC number %d",=20
+	KASSERT(pmc < mips_npmcs, ("[mips24k,%d] illegal PMC number %d",
 				   __LINE__, pmc));
-=09
+
 	switch (pmc) {
 	case 0:
 		mips_wr_perfcnt1(reg);
@@ -214,40 +204,17 @@
 	return (reg);
 }
=20
-static int
-mips24k_allocate_pmc(int cpu, int ri, struct pmc *pm,
-  const struct pmc_op_pmcallocate *a)
+uint32_t
+mips_get_perfctl(int cpu, int ri, uint32_t event, uint32_t caps)
 {
-	enum pmc_event pe;
-	uint32_t caps, config, counter;
-	int i;
+	uint32_t config;
=20
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
-	KASSERT(ri >=3D 0 && ri < mips24k_npmcs,
-	    ("[mips,%d] illegal row index %d", __LINE__, ri));
-
-	caps =3D a->pm_caps;
-	if (a->pm_class !=3D PMC_CLASS_MIPS24K)
-		return (EINVAL);
-	pe =3D a->pm_ev;
-	for (i =3D 0; i < mips24k_event_codes_size; i++) {
-		if (mips24k_event_codes[i].pe_ev =3D=3D pe) {
-			config =3D mips24k_event_codes[i].pe_code;
-			counter =3D  mips24k_event_codes[i].pe_counter;
-			break;
-		}
-	}
-	if (i =3D=3D mips24k_event_codes_size)
-		return (EINVAL);
-
-	if ((counter !=3D MIPS24K_ALL) && (counter !=3D ri))
-		return (EINVAL);
+	config =3D event;
=20
 	config <<=3D MIPS24K_PMC_SELECT;
=20
 	if (caps & PMC_CAP_SYSTEM)
-		config |=3D (MIPS24K_PMC_SUPER_ENABLE |=20
+		config |=3D (MIPS24K_PMC_SUPER_ENABLE |
 			   MIPS24K_PMC_KERNEL_ENABLE);
 	if (caps & PMC_CAP_USER)
 		config |=3D MIPS24K_PMC_USER_ENABLE;
@@ -256,374 +223,7 @@
 	if (caps & PMC_CAP_INTERRUPT)
 		config |=3D MIPS24K_PMC_INTERRUPT_ENABLE;
=20
-	pm->pm_md.pm_mips24k.pm_mips24k_evsel =3D config;
+	PMCDBG(MDP,ALL,2,"mips24k-get_perfctl ri=3D%d -> config=3D0x%x", ri, conf=
ig);
=20
-	PMCDBG(MDP,ALL,2,"mips-allocate ri=3D%d -> config=3D0x%x", ri, config);
-
-	return 0;
+	return (config);
 }
-
-
-static int
-mips24k_read_pmc(int cpu, int ri, pmc_value_t *v)
-{
-	struct pmc *pm;
-	pmc_value_t tmp;
-
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
-	KASSERT(ri >=3D 0 && ri < mips24k_npmcs,
-	    ("[mips,%d] illegal row index %d", __LINE__, ri));
-
-	pm  =3D mips24k_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
-	tmp =3D mips24k_pmcn_read(ri);
-	PMCDBG(MDP,REA,2,"mips-read id=3D%d -> %jd", ri, tmp);
-	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
-		*v =3D MIPS24K_PERFCTR_VALUE_TO_RELOAD_COUNT(tmp);
-	else
-		*v =3D tmp;
-
-	return 0;
-}
-
-static int
-mips24k_write_pmc(int cpu, int ri, pmc_value_t v)
-{
-	struct pmc *pm;
-
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
-	KASSERT(ri >=3D 0 && ri < mips24k_npmcs,
-	    ("[mips,%d] illegal row-index %d", __LINE__, ri));
-
-	pm  =3D mips24k_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
-
-	if (PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
-		v =3D MIPS24K_RELOAD_COUNT_TO_PERFCTR_VALUE(v);
-=09
-	PMCDBG(MDP,WRI,1,"mips-write cpu=3D%d ri=3D%d v=3D%jx", cpu, ri, v);
-
-	mips24k_pmcn_write(ri, v);
-
-	return 0;
-}
-
-static int
-mips24k_config_pmc(int cpu, int ri, struct pmc *pm)
-{
-	struct pmc_hw *phw;
-
-	PMCDBG(MDP,CFG,1, "cpu=3D%d ri=3D%d pm=3D%p", cpu, ri, pm);
-
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
-	KASSERT(ri >=3D 0 && ri < mips24k_npmcs,
-	    ("[mips,%d] illegal row-index %d", __LINE__, ri));
-
-	phw =3D &mips24k_pcpu[cpu]->pc_mipspmcs[ri];
-
-	KASSERT(pm =3D=3D NULL || phw->phw_pmc =3D=3D NULL,
-	    ("[mips,%d] pm=3D%p phw->pm=3D%p hwpmc not unconfigured",
-	    __LINE__, pm, phw->phw_pmc));
-
-	phw->phw_pmc =3D pm;
-
-	return 0;
-}
-
-static int
-mips24k_start_pmc(int cpu, int ri)
-{
-	uint32_t config;
-        struct pmc *pm;
-        struct pmc_hw *phw;
-
-	phw    =3D &mips24k_pcpu[cpu]->pc_mipspmcs[ri];
-	pm     =3D phw->phw_pmc;
-	config =3D pm->pm_md.pm_mips24k.pm_mips24k_evsel;
-
-	/* Enable the PMC. */
-	switch (ri) {
-	case 0:
-		mips_wr_perfcnt0(config);
-		break;
-	case 1:
-		mips_wr_perfcnt2(config);
-		break;
-	default:
-		break;
-	}
-
-	return 0;
-}
-
-static int
-mips24k_stop_pmc(int cpu, int ri)
-{
-        struct pmc *pm;
-        struct pmc_hw *phw;
-
-	phw    =3D &mips24k_pcpu[cpu]->pc_mipspmcs[ri];
-	pm     =3D phw->phw_pmc;
-
-	/*
-	 * Disable the PMCs.
-	 *
-	 * Clearing the entire register turns the counter off as well
-	 * as removes the previously sampled event.
-	 */
-	switch (ri) {
-	case 0:
-		mips_wr_perfcnt0(0);
-		break;
-	case 1:
-		mips_wr_perfcnt2(0);
-		break;
-	default:
-		break;
-	}
-	return 0;
-}
-
-static int
-mips24k_release_pmc(int cpu, int ri, struct pmc *pmc)
-{
-	struct pmc_hw *phw;
-
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips,%d] illegal CPU value %d", __LINE__, cpu));
-	KASSERT(ri >=3D 0 && ri < mips24k_npmcs,
-	    ("[mips,%d] illegal row-index %d", __LINE__, ri));
-
-	phw =3D &mips24k_pcpu[cpu]->pc_mipspmcs[ri];
-	KASSERT(phw->phw_pmc =3D=3D NULL,
-	    ("[mips,%d] PHW pmc %p non-NULL", __LINE__, phw->phw_pmc));
-
-	return 0;
-}
-
-static int
-mips24k_intr(int cpu, struct trapframe *tf)
-{
-	int error;
-	int retval, ri;
-	struct pmc *pm;
-	struct mips24k_cpu *pc;
-	uint32_t r, r0, r2;
-
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips24k,%d] CPU %d out of range", __LINE__, cpu));
-
-	retval =3D 0;
-	pc =3D mips24k_pcpu[cpu];
-
-	/* Stop PMCs without clearing the counter */
-	r0 =3D mips_rd_perfcnt0();
-	mips_wr_perfcnt0(r0 & ~(0x1f));
-	r2 =3D mips_rd_perfcnt2();
-	mips_wr_perfcnt2(r2 & ~(0x1f));
-
-	for (ri =3D 0; ri < mips24k_npmcs; ri++) {
-		pm =3D mips24k_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
-		if (pm =3D=3D NULL)
-			continue;
-		if (! PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)))
-			continue;
-
-		r =3D mips24k_pmcn_read(ri);
-
-		/* If bit 31 is set, the counter has overflowed */
-		if ((r & 0x80000000) =3D=3D 0)
-			continue;
-
-		retval =3D 1;
-		if (pm->pm_state !=3D PMC_STATE_RUNNING)
-			continue;
-		error =3D pmc_process_interrupt(cpu, pm, tf,
-		    TRAPF_USERMODE(tf));
-		if (error) {
-			/* Clear/disable the relevant counter */
-			if (ri =3D=3D 0)
-				r0 =3D 0;
-			else if (ri =3D=3D 1)
-				r2 =3D 0;
-			mips24k_stop_pmc(cpu, ri);
-		}
-
-		/* Reload sampling count */
-		mips24k_write_pmc(cpu, ri, pm->pm_sc.pm_reloadcount);
-	}
-
-	/*
-	 * Re-enable the PMC counters where they left off.
-	 *
-	 * Any counter which overflowed will have its sample count
-	 * reloaded in the loop above.
-	 */
-	mips_wr_perfcnt0(r0);
-	mips_wr_perfcnt2(r2);
-
-	return retval;
-}
-
-static int
-mips24k_describe(int cpu, int ri, struct pmc_info *pi, struct pmc **ppmc)
-{
-	int error;
-	struct pmc_hw *phw;
-	char mips24k_name[PMC_NAME_MAX];
-
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips,%d], illegal CPU %d", __LINE__, cpu));
-	KASSERT(ri >=3D 0 && ri < mips24k_npmcs,
-	    ("[mips,%d] row-index %d out of range", __LINE__, ri));
-
-	phw =3D &mips24k_pcpu[cpu]->pc_mipspmcs[ri];
-	snprintf(mips24k_name, sizeof(mips24k_name), "MIPS-%d", ri);
-	if ((error =3D copystr(mips24k_name, pi->pm_name, PMC_NAME_MAX,
-	    NULL)) !=3D 0)
-		return error;
-	pi->pm_class =3D PMC_CLASS_MIPS24K;
-	if (phw->phw_state & PMC_PHW_FLAG_IS_ENABLED) {
-		pi->pm_enabled =3D TRUE;
-		*ppmc          =3D phw->phw_pmc;
-	} else {
-		pi->pm_enabled =3D FALSE;
-		*ppmc	       =3D NULL;
-	}
-
-	return (0);
-}
-
-static int
-mips24k_get_config(int cpu, int ri, struct pmc **ppm)
-{
-	*ppm =3D mips24k_pcpu[cpu]->pc_mipspmcs[ri].phw_pmc;
-
-	return 0;
-}
-
-/*
- * XXX don't know what we should do here.
- */
-static int
-mips24k_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
-{
-	return 0;
-}
-
-static int
-mips24k_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
-{
-	return 0;
-}
-
-static int
-mips24k_pcpu_init(struct pmc_mdep *md, int cpu)
-{
-	int first_ri, i;
-	struct pmc_cpu *pc;
-	struct mips24k_cpu *pac;
-	struct pmc_hw  *phw;
-
-	KASSERT(cpu >=3D 0 && cpu < pmc_cpu_max(),
-	    ("[mips,%d] wrong cpu number %d", __LINE__, cpu));
-	PMCDBG(MDP,INI,1,"mips-init cpu=3D%d", cpu);
-
-	mips24k_pcpu[cpu] =3D pac =3D malloc(sizeof(struct mips24k_cpu), M_PMC,
-	    M_WAITOK|M_ZERO);
-	pac->pc_mipspmcs =3D malloc(sizeof(struct pmc_hw) * mips24k_npmcs,
-	    M_PMC, M_WAITOK|M_ZERO);
-	pc =3D pmc_pcpu[cpu];
-	first_ri =3D md->pmd_classdep[PMC_MDEP_CLASS_INDEX_MIPS24K].pcd_ri;
-	KASSERT(pc !=3D NULL, ("[mips,%d] NULL per-cpu pointer", __LINE__));
-
-	for (i =3D 0, phw =3D pac->pc_mipspmcs; i < mips24k_npmcs; i++, phw++) {
-		phw->phw_state    =3D PMC_PHW_FLAG_IS_ENABLED |
-		    PMC_PHW_CPU_TO_STATE(cpu) | PMC_PHW_INDEX_TO_STATE(i);
-		phw->phw_pmc      =3D NULL;
-		pc->pc_hwpmcs[i + first_ri] =3D phw;
-	}
-
-	/*
-	 * Clear the counter control register which has the effect
-	 * of disabling counting.
-	 */
-	for (i =3D 0; i < mips24k_npmcs; i++)
-		mips24k_pmcn_write(i, 0);
-
-	return 0;
-}
-
-static int
-mips24k_pcpu_fini(struct pmc_mdep *md, int cpu)
-{
-	return 0;
-}
-
-struct pmc_mdep *
-pmc_mips24k_initialize()
-{
-	struct pmc_mdep *pmc_mdep;
-	struct pmc_classdep *pcd;
-=09
-	/*=20
-	 * Read the counter control registers from CP0=20
-	 * to determine the number of available PMCs.
-	 * The control registers use bit 31 as a "more" bit.
-	 *
-	 * XXX: With the current macros it is hard to read the
-	 * CP0 registers in any varied way. =20
-	 */
-	mips24k_npmcs =3D 2;
-=09
-	PMCDBG(MDP,INI,1,"mips-init npmcs=3D%d", mips24k_npmcs);
-
-	/*
-	 * Allocate space for pointers to PMC HW descriptors and for
-	 * the MDEP structure used by MI code.
-	 */
-	mips24k_pcpu =3D malloc(sizeof(struct mips24k_cpu *) * pmc_cpu_max(), M_P=
MC,
-			   M_WAITOK|M_ZERO);
-
-	/* Just one class */
-	pmc_mdep =3D malloc(sizeof(struct pmc_mdep) + sizeof(struct pmc_classdep),
-			  M_PMC, M_WAITOK|M_ZERO);
-
-	pmc_mdep->pmd_cputype =3D PMC_CPU_MIPS_24K;
-	pmc_mdep->pmd_nclass  =3D 1;
-
-	pcd =3D &pmc_mdep->pmd_classdep[PMC_MDEP_CLASS_INDEX_MIPS24K];
-	pcd->pcd_caps  =3D MIPS24K_PMC_CAPS;
-	pcd->pcd_class =3D PMC_CLASS_MIPS24K;
-	pcd->pcd_num   =3D mips24k_npmcs;
-	pcd->pcd_ri    =3D pmc_mdep->pmd_npmc;
-	pcd->pcd_width =3D 32; /* XXX: Fix for 64 bit MIPS */
-
-	pcd->pcd_allocate_pmc   =3D mips24k_allocate_pmc;
-	pcd->pcd_config_pmc     =3D mips24k_config_pmc;
-	pcd->pcd_pcpu_fini      =3D mips24k_pcpu_fini;
-	pcd->pcd_pcpu_init      =3D mips24k_pcpu_init;
-	pcd->pcd_describe       =3D mips24k_describe;
-	pcd->pcd_get_config	=3D mips24k_get_config;
-	pcd->pcd_read_pmc       =3D mips24k_read_pmc;
-	pcd->pcd_release_pmc    =3D mips24k_release_pmc;
-	pcd->pcd_start_pmc      =3D mips24k_start_pmc;
-	pcd->pcd_stop_pmc       =3D mips24k_stop_pmc;
- 	pcd->pcd_write_pmc      =3D mips24k_write_pmc;
-
-	pmc_mdep->pmd_intr       =3D mips24k_intr;
-	pmc_mdep->pmd_switch_in  =3D mips24k_switch_in;
-	pmc_mdep->pmd_switch_out =3D mips24k_switch_out;
-=09
-	pmc_mdep->pmd_npmc   +=3D mips24k_npmcs;
-
-	return (pmc_mdep);
-}
-
-void
-pmc_mips24k_finalize(struct pmc_mdep *md)
-{
-	(void) md;
-}
-
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_mod.c
--- a/head/sys/dev/hwpmc/hwpmc_mod.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_mod.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mod.c 226514 2011-10-18 15:25=
:43Z fabient $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_mod.c 233628 2012-03-28 20:58=
:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/eventhandler.h>
@@ -70,6 +70,8 @@
 #include <vm/vm_map.h>
 #include <vm/vm_object.h>
=20
+#include "hwpmc_soft.h"
+
 /*
  * Types
  */
@@ -182,7 +184,7 @@
 static int	pmc_can_allocate_rowindex(struct proc *p, unsigned int ri,
     int cpu);
 static int	pmc_can_attach(struct pmc *pm, struct proc *p);
-static void	pmc_capture_user_callchain(int cpu, struct trapframe *tf);
+static void	pmc_capture_user_callchain(int cpu, int soft, struct trapframe=
 *tf);
 static void	pmc_cleanup(void);
 static int	pmc_detach_process(struct proc *p, struct pmc *pm);
 static int	pmc_detach_one_process(struct proc *p, struct pmc *pm,
@@ -206,7 +208,7 @@
 static void	pmc_process_exit(void *arg, struct proc *p);
 static void	pmc_process_fork(void *arg, struct proc *p1,
     struct proc *p2, int n);
-static void	pmc_process_samples(int cpu);
+static void	pmc_process_samples(int cpu, int soft);
 static void	pmc_release_pmc_descriptor(struct pmc *pmc);
 static void	pmc_remove_owner(struct pmc_owner *po);
 static void	pmc_remove_process_descriptor(struct pmc_process *pp);
@@ -218,12 +220,16 @@
 static int	pmc_syscall_handler(struct thread *td, void *syscall_args);
 static void	pmc_unlink_target_process(struct pmc *pmc,
     struct pmc_process *pp);
+static int generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp);
+static int generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp);
+static struct pmc_mdep *pmc_generic_cpu_initialize(void);
+static void pmc_generic_cpu_finalize(struct pmc_mdep *md);
=20
 /*
  * Kernel tunables and sysctl(8) interface.
  */
=20
-SYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
+SYSCTL_DECL(_kern_hwpmc);
=20
 static int pmc_callchaindepth =3D PMC_CALLCHAIN_DEPTH;
 TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "callchaindepth", &pmc_callchaindepth);
@@ -1833,7 +1839,9 @@
 	"KLDUNLOAD",
 	"MMAP",
 	"MUNMAP",
-	"CALLCHAIN"
+	"CALLCHAIN-NMI",
+	"CALLCHAIN-SOFT",
+	"SOFTSAMPLING"
 };
 #endif
=20
@@ -1992,7 +2000,8 @@
 		 * lose the interrupt sample.
 		 */
 		CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmc_cpumask);
-		pmc_process_samples(PCPU_GET(cpuid));
+		pmc_process_samples(PCPU_GET(cpuid), PMC_HR);
+		pmc_process_samples(PCPU_GET(cpuid), PMC_SR);
 		break;
=20
=20
@@ -2022,11 +2031,30 @@
 		 */
 		KASSERT(td =3D=3D curthread, ("[pmc,%d] td !=3D curthread",
 		    __LINE__));
-		pmc_capture_user_callchain(PCPU_GET(cpuid),
+
+		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_HR,
 		    (struct trapframe *) arg);
 		td->td_pflags &=3D ~TDP_CALLCHAIN;
 		break;
=20
+	case PMC_FN_USER_CALLCHAIN_SOFT:
+		/*
+		 * Record a call chain.
+		 */
+		KASSERT(td =3D=3D curthread, ("[pmc,%d] td !=3D curthread",
+		    __LINE__));
+		pmc_capture_user_callchain(PCPU_GET(cpuid), PMC_SR,
+		    (struct trapframe *) arg);
+		td->td_pflags &=3D ~TDP_CALLCHAIN;
+		break;
+
+	case PMC_FN_SOFT_SAMPLING:
+		/*
+		 * Call soft PMC sampling intr.
+		 */
+		pmc_soft_intr((struct pmckern_soft *) arg);
+		break;
+
 	default:
 #ifdef	DEBUG
 		KASSERT(0, ("[pmc,%d] unknown hook %d\n", __LINE__, function));
@@ -2221,18 +2249,17 @@
 static void
 pmc_wait_for_pmc_idle(struct pmc *pm)
 {
-#ifdef	DEBUG
+#ifdef DEBUG
 	volatile int maxloop;
=20
 	maxloop =3D 100 * pmc_cpu_max();
 #endif
-
 	/*
 	 * Loop (with a forced context switch) till the PMC's runcount
 	 * comes down to zero.
 	 */
 	while (atomic_load_acq_32(&pm->pm_runcount) > 0) {
-#ifdef	DEBUG
+#ifdef DEBUG
 		maxloop--;
 		KASSERT(maxloop > 0,
 		    ("[pmc,%d] (ri%d, rc%d) waiting too long for "
@@ -2972,6 +2999,53 @@
 	}
 	break;
=20
+	/*
+	 * Retrieve soft events list.
+	 */
+	case PMC_OP_GETDYNEVENTINFO:
+	{
+		enum pmc_class			cl;
+		enum pmc_event			ev;
+		struct pmc_op_getdyneventinfo	*gei;
+		struct pmc_dyn_event_descr	dev;
+		struct pmc_soft			*ps;
+		uint32_t			nevent;
+
+		sx_assert(&pmc_sx, SX_LOCKED);
+
+		gei =3D (struct pmc_op_getdyneventinfo *) arg;
+
+		if ((error =3D copyin(&gei->pm_class, &cl, sizeof(cl))) !=3D 0)
+			break;
+
+		/* Only SOFT class is dynamic. */
+		if (cl !=3D PMC_CLASS_SOFT) {
+			error =3D EINVAL;
+			break;
+		}
+
+		nevent =3D 0;
+		for (ev =3D PMC_EV_SOFT_FIRST; ev <=3D PMC_EV_SOFT_LAST; ev++) {
+			ps =3D pmc_soft_ev_acquire(ev);
+			if (ps =3D=3D NULL)
+				continue;
+			bcopy(&ps->ps_ev, &dev, sizeof(dev));
+			pmc_soft_ev_release(ps);
+
+			error =3D copyout(&dev,
+			    &gei->pm_events[nevent],
+			    sizeof(struct pmc_dyn_event_descr));
+			if (error !=3D 0)
+				break;
+			nevent++;
+		}
+		if (error !=3D 0)
+			break;
+
+		error =3D copyout(&nevent, &gei->pm_nevent,
+		    sizeof(nevent));
+	}
+	break;
=20
 	/*
 	 * Get module statistics
@@ -4022,7 +4096,7 @@
  */
=20
 int
-pmc_process_interrupt(int cpu, struct pmc *pm, struct trapframe *tf,
+pmc_process_interrupt(int cpu, int ring, struct pmc *pm, struct trapframe =
*tf,
     int inuserspace)
 {
 	int error, callchaindepth;
@@ -4035,7 +4109,7 @@
 	/*
 	 * Allocate space for a sample buffer.
 	 */
-	psb =3D pmc_pcpu[cpu]->pc_sb;
+	psb =3D pmc_pcpu[cpu]->pc_sb[ring];
=20
 	ps =3D psb->ps_write;
 	if (ps->ps_nsamples) {	/* in use, reader hasn't caught up */
@@ -4061,6 +4135,7 @@
 		pm->pm_runcount));
=20
 	atomic_add_rel_int(&pm->pm_runcount, 1);	/* hold onto PMC */
+
 	ps->ps_pmc =3D pm;
 	if ((td =3D curthread) && td->td_proc)
 		ps->ps_pid =3D td->td_proc->p_pid;
@@ -4080,11 +4155,11 @@
 		 * Kernel stack traversals can be done immediately,
 		 * while we defer to an AST for user space traversals.
 		 */
-		if (!inuserspace)
+		if (!inuserspace) {
 			callchaindepth =3D
 			    pmc_save_kernel_callchain(ps->ps_pc,
 				callchaindepth, tf);
-		else {
+		} else {
 			pmc_post_callchain_callback();
 			callchaindepth =3D PMC_SAMPLE_INUSE;
 		}
@@ -4113,7 +4188,7 @@
  */
=20
 static void
-pmc_capture_user_callchain(int cpu, struct trapframe *tf)
+pmc_capture_user_callchain(int cpu, int ring, struct trapframe *tf)
 {
 	int i;
 	struct pmc *pm;
@@ -4124,9 +4199,7 @@
 	int ncallchains;
 #endif
=20
-	sched_unpin();	/* Can migrate safely now. */
-
-	psb =3D pmc_pcpu[cpu]->pc_sb;
+	psb =3D pmc_pcpu[cpu]->pc_sb[ring];
 	td =3D curthread;
=20
 	KASSERT(td->td_pflags & TDP_CALLCHAIN,
@@ -4172,23 +4245,25 @@
 #ifdef	INVARIANTS
 		ncallchains++;
 #endif
-
 	}
=20
 	KASSERT(ncallchains > 0,
 	    ("[pmc,%d] cpu %d didn't find a sample to collect", __LINE__,
 		cpu));
=20
+	KASSERT(td->td_pinned > 0,
+	    ("[pmc,%d] invalid td_pinned value", __LINE__));
+	sched_unpin();	/* Can migrate safely now. */
+
 	return;
 }
=20
-
 /*
  * Process saved PC samples.
  */
=20
 static void
-pmc_process_samples(int cpu)
+pmc_process_samples(int cpu, int ring)
 {
 	struct pmc *pm;
 	int adjri, n;
@@ -4202,35 +4277,37 @@
 	    ("[pmc,%d] not on the correct CPU pcpu=3D%d cpu=3D%d", __LINE__,
 		PCPU_GET(cpuid), cpu));
=20
-	psb =3D pmc_pcpu[cpu]->pc_sb;
+	psb =3D pmc_pcpu[cpu]->pc_sb[ring];
=20
 	for (n =3D 0; n < pmc_nsamples; n++) { /* bound on #iterations */
=20
 		ps =3D psb->ps_read;
 		if (ps->ps_nsamples =3D=3D PMC_SAMPLE_FREE)
 			break;
+
+		pm =3D ps->ps_pmc;
+
+		KASSERT(pm->pm_runcount > 0,
+		    ("[pmc,%d] pm=3D%p runcount %d", __LINE__, (void *) pm,
+			pm->pm_runcount));
+
+		po =3D pm->pm_owner;
+
+		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
+		    ("[pmc,%d] pmc=3D%p non-sampling mode=3D%d", __LINE__,
+			pm, PMC_TO_MODE(pm)));
+
+		/* Ignore PMCs that have been switched off */
+		if (pm->pm_state !=3D PMC_STATE_RUNNING)
+			goto entrydone;
+
+		/* If there is a pending AST wait for completion */
 		if (ps->ps_nsamples =3D=3D PMC_SAMPLE_INUSE) {
 			/* Need a rescan at a later time. */
 			CPU_SET_ATOMIC(cpu, &pmc_cpumask);
 			break;
 		}
=20
-		pm =3D ps->ps_pmc;
-
-		KASSERT(pm->pm_runcount > 0,
-		    ("[pmc,%d] pm=3D%p runcount %d", __LINE__, (void *) pm,
-			pm->pm_runcount));
-
-		po =3D pm->pm_owner;
-
-		KASSERT(PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm)),
-		    ("[pmc,%d] pmc=3D%p non-sampling mode=3D%d", __LINE__,
-			pm, PMC_TO_MODE(pm)));
-
-		/* Ignore PMCs that have been switched off */
-		if (pm->pm_state !=3D PMC_STATE_RUNNING)
-			goto entrydone;
-
 		PMCDBG(SAM,OPS,1,"cpu=3D%d pm=3D%p n=3D%d fl=3D%x wr=3D%d rd=3D%d", cpu,
 		    pm, ps->ps_nsamples, ps->ps_flags,
 		    (int) (psb->ps_write - psb->ps_samples),
@@ -4256,11 +4333,10 @@
 		 * or a system-wide sampling PMC.  Dispatch a log
 		 * entry to the PMC's owner process.
 		 */
-
 		pmclog_process_callchain(pm, ps);
=20
 	entrydone:
-		ps->ps_nsamples =3D 0;	/* mark entry as free */
+		ps->ps_nsamples =3D 0; /* mark entry as free */
 		atomic_subtract_rel_int(&pm->pm_runcount, 1);
=20
 		/* increment read pointer, modulo sample size */
@@ -4584,6 +4660,76 @@
 	__PMC_CLASSES()
 };
=20
+/*
+ * Base class initializer: allocate structure and set default classes.
+ */
+struct pmc_mdep *
+pmc_mdep_alloc(int nclasses)
+{
+	struct pmc_mdep *md;
+	int	n;
+
+	/* SOFT + md classes */
+	n =3D 1 + nclasses;
+	md =3D malloc(sizeof(struct pmc_mdep) + n *
+	    sizeof(struct pmc_classdep), M_PMC, M_WAITOK|M_ZERO);
+	if (md !=3D NULL) {
+		md->pmd_nclass =3D n;
+
+		/* Add base class. */
+		pmc_soft_initialize(md);
+	}
+
+	return md;
+}
+
+void
+pmc_mdep_free(struct pmc_mdep *md)
+{
+	pmc_soft_finalize(md);
+	free(md, M_PMC);
+}
+
+static int
+generic_switch_in(struct pmc_cpu *pc, struct pmc_process *pp)
+{
+	(void) pc; (void) pp;
+
+	return (0);
+}
+
+static int
+generic_switch_out(struct pmc_cpu *pc, struct pmc_process *pp)
+{
+	(void) pc; (void) pp;
+
+	return (0);
+}
+
+static struct pmc_mdep *
+pmc_generic_cpu_initialize(void)
+{
+	struct pmc_mdep *md;
+
+	md =3D pmc_mdep_alloc(0);
+
+	md->pmd_cputype    =3D PMC_CPU_GENERIC;
+
+	md->pmd_pcpu_init  =3D NULL;
+	md->pmd_pcpu_fini  =3D NULL;
+	md->pmd_switch_in  =3D generic_switch_in;
+	md->pmd_switch_out =3D generic_switch_out;
+
+	return (md);
+}
+
+static void
+pmc_generic_cpu_finalize(struct pmc_mdep *md)
+{
+	(void) md;
+}
+
+
 static int
 pmc_initialize(void)
 {
@@ -4643,9 +4789,12 @@
 	}
=20
 	md =3D pmc_md_initialize();
-
-	if (md =3D=3D NULL)
-		return (ENOSYS);
+	if (md =3D=3D NULL) {
+		/* Default to generic CPU. */
+		md =3D pmc_generic_cpu_initialize();
+		if (md =3D=3D NULL)
+			return (ENOSYS);
+        }
=20
 	KASSERT(md->pmd_nclass >=3D 1 && md->pmd_npmc >=3D 1,
 	    ("[pmc,%d] no classes or pmcs", __LINE__));
@@ -4717,7 +4866,25 @@
 			ps->ps_pc =3D sb->ps_callchains +
 			    (n * pmc_callchaindepth);
=20
-		pmc_pcpu[cpu]->pc_sb =3D sb;
+		pmc_pcpu[cpu]->pc_sb[PMC_HR] =3D sb;
+
+		sb =3D malloc(sizeof(struct pmc_samplebuffer) +
+		    pmc_nsamples * sizeof(struct pmc_sample), M_PMC,
+		    M_WAITOK|M_ZERO);
+		sb->ps_read =3D sb->ps_write =3D sb->ps_samples;
+		sb->ps_fence =3D sb->ps_samples + pmc_nsamples;
+
+		KASSERT(pmc_pcpu[cpu] !=3D NULL,
+		    ("[pmc,%d] cpu=3D%d Null per-cpu data", __LINE__, cpu));
+
+		sb->ps_callchains =3D malloc(pmc_callchaindepth * pmc_nsamples *
+		    sizeof(uintptr_t), M_PMC, M_WAITOK|M_ZERO);
+
+		for (n =3D 0, ps =3D sb->ps_samples; n < pmc_nsamples; n++, ps++)
+			ps->ps_pc =3D sb->ps_callchains +
+			    (n * pmc_callchaindepth);
+
+		pmc_pcpu[cpu]->pc_sb[PMC_SR] =3D sb;
 	}
=20
 	/* allocate space for the row disposition array */
@@ -4887,9 +5054,12 @@
 				md->pmd_pcpu_fini(md, cpu);
 		}
=20
-		pmc_md_finalize(md);
-
-		free(md, M_PMC);
+		if (md->pmd_cputype =3D=3D PMC_CPU_GENERIC)
+			pmc_generic_cpu_finalize(md);
+		else
+			pmc_md_finalize(md);
+
+		pmc_mdep_free(md);
 		md =3D NULL;
 		pmc_restore_cpu_binding(&pb);
 	}
@@ -4898,11 +5068,16 @@
 	for (cpu =3D 0; cpu < maxcpu; cpu++) {
 		if (!pmc_cpu_is_active(cpu))
 			continue;
-		KASSERT(pmc_pcpu[cpu]->pc_sb !=3D NULL,
-		    ("[pmc,%d] Null cpu sample buffer cpu=3D%d", __LINE__,
+		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_HR] !=3D NULL,
+		    ("[pmc,%d] Null hw cpu sample buffer cpu=3D%d", __LINE__,
 			cpu));
-		free(pmc_pcpu[cpu]->pc_sb->ps_callchains, M_PMC);
-		free(pmc_pcpu[cpu]->pc_sb, M_PMC);
+		KASSERT(pmc_pcpu[cpu]->pc_sb[PMC_SR] !=3D NULL,
+		    ("[pmc,%d] Null sw cpu sample buffer cpu=3D%d", __LINE__,
+			cpu));
+		free(pmc_pcpu[cpu]->pc_sb[PMC_HR]->ps_callchains, M_PMC);
+		free(pmc_pcpu[cpu]->pc_sb[PMC_HR], M_PMC);
+		free(pmc_pcpu[cpu]->pc_sb[PMC_SR]->ps_callchains, M_PMC);
+		free(pmc_pcpu[cpu]->pc_sb[PMC_SR], M_PMC);
 		free(pmc_pcpu[cpu], M_PMC);
 	}
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_piv.c
--- a/head/sys/dev/hwpmc/hwpmc_piv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_piv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_piv.c 233628 2012-03-28 20:58=
:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -1463,7 +1463,7 @@
 			    !PMC_IS_SAMPLING_MODE(PMC_TO_MODE(pm))) {
 				continue;
 			}
-			(void) pmc_process_interrupt(cpu, pm, tf,
+			(void) pmc_process_interrupt(cpu, PMC_HR, pm, tf,
 			    TRAPF_USERMODE(tf));
 			continue;
 		}
@@ -1513,7 +1513,7 @@
 		 * Process the interrupt.  Re-enable the PMC if
 		 * processing was successful.
 		 */
-		error =3D pmc_process_interrupt(cpu, pm, tf,
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
 		    TRAPF_USERMODE(tf));
=20
 		/*
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_powerpc.c
--- a/head/sys/dev/hwpmc/hwpmc_powerpc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_powerpc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_powerpc.c 228874 2011-12-25 1=
4:29:36Z bz $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_powerpc.c 233628 2012-03-28 2=
0:58:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/pmc.h>
@@ -690,7 +690,8 @@
 		powerpc_pmcn_write(i, v);
=20
 		/* Restart the counter if logging succeeded. */
-		error =3D pmc_process_interrupt(cpu, pm, tf, TRAPF_USERMODE(tf));
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
+		    TRAPF_USERMODE(tf));
 		mtspr(SPR_MMCR0, config);
 		if (error !=3D 0)
 			powerpc_stop_pmc(cpu, i);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_ppro.c
--- a/head/sys/dev/hwpmc/hwpmc_ppro.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_ppro.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_ppro.c 233628 2012-03-28 20:5=
8:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -704,7 +704,7 @@
 		if (pm->pm_state !=3D PMC_STATE_RUNNING)
 			continue;
=20
-		error =3D pmc_process_interrupt(cpu, pm, tf,
+		error =3D pmc_process_interrupt(cpu, PMC_HR, pm, tf,
 		    TRAPF_USERMODE(tf));
 		if (error)
 			P6_MARK_STOPPED(pc,ri);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_tsc.c
--- a/head/sys/dev/hwpmc/hwpmc_tsc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_tsc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_tsc.c 233628 2012-03-28 20:58=
:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/pmc.h>
@@ -190,9 +190,6 @@
=20
 	ri =3D md->pmd_classdep[PMC_MDEP_CLASS_INDEX_TSC].pcd_ri;
=20
-	KASSERT(ri =3D=3D 0 && ri < TSC_NPMCS, ("[tsc,%d] ri=3D%d", __LINE__,
-	    ri));
-
 	pc =3D pmc_pcpu[cpu];
 	pc->pc_hwpmcs[ri] =3D NULL;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_x86.c
--- a/head/sys/dev/hwpmc/hwpmc_x86.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_x86.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_x86.c 230636 2012-01-28 01:38=
:48Z emaste $");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_x86.c 233628 2012-03-28 20:58=
:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -48,6 +48,8 @@
 #include <vm/vm_param.h>
 #include <vm/pmap.h>
=20
+#include "hwpmc_soft.h"
+
 /*
  * Attempt to walk a user call stack using a too-simple algorithm.
  * In the general case we need unwind information associated with
@@ -251,8 +253,11 @@
=20
 	/* disallow sampling if we do not have an LAPIC */
 	if (md !=3D NULL && !lapic_enable_pmc())
-		for (i =3D 1; i < md->pmd_nclass; i++)
+		for (i =3D 0; i < md->pmd_nclass; i++) {
+			if (i =3D=3D PMC_CLASS_INDEX_SOFT)
+				continue;
 			md->pmd_classdep[i].pcd_caps &=3D ~PMC_CAP_INTERRUPT;
+		}
=20
 	return (md);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/hwpmc_xscale.c
--- a/head/sys/dev/hwpmc/hwpmc_xscale.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/hwpmc_xscale.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_xscale.c 233628 2012-03-28 20=
:58:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -638,11 +638,9 @@
             M_WAITOK|M_ZERO);
=20
 	/* Just one class */
-	pmc_mdep =3D malloc(sizeof(struct pmc_mdep) + sizeof(struct pmc_classdep),
-	    M_PMC, M_WAITOK|M_ZERO);
+	pmc_mdep =3D pmc_mdep_alloc(1);
=20
 	pmc_mdep->pmd_cputype =3D PMC_CPU_INTEL_XSCALE;
-	pmc_mdep->pmd_nclass  =3D 1;
=20
 	pcd =3D &pmc_mdep->pmd_classdep[PMC_MDEP_CLASS_INDEX_XSCALE];
 	pcd->pcd_caps  =3D XSCALE_PMC_CAPS;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/hwpmc/pmc_events.h
--- a/head/sys/dev/hwpmc/pmc_events.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/hwpmc/pmc_events.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/hwpmc/pmc_events.h 232366 2012-03-01 21:23:26Z d=
avide $
+ * $FreeBSD: head/sys/dev/hwpmc/pmc_events.h 233628 2012-03-28 20:58:30Z f=
abient $
  */
=20
 #ifndef _DEV_HWPMC_PMC_EVENTS_H_
@@ -2599,6 +2599,15 @@
 #define	PMC_EV_TSC_FIRST	PMC_EV_TSC_TSC
 #define	PMC_EV_TSC_LAST		PMC_EV_TSC_TSC
=20
+/*
+ * Software events are dynamicaly defined.
+ */
+
+#define	PMC_EV_DYN_COUNT	0x1000
+
+#define	PMC_EV_SOFT_FIRST	0x20000
+#define	PMC_EV_SOFT_LAST	(PMC_EV_SOFT_FIRST + PMC_EV_DYN_COUNT - 1)
+
 #define	__PMC_EV_UCF()				\
 __PMC_EV(UCF, UCLOCK)
=20
@@ -3411,6 +3420,67 @@
 #define	PMC_EV_MIPS24K_FIRST	PMC_EV_MIPS24K_CYCLE
 #define	PMC_EV_MIPS24K_LAST	PMC_EV_MIPS24K_WBB_FULL_PIPELINE_STALLS
=20
+/*
+ * Cavium Octeon counters. Obtained from cvmx-core.h
+ */
+#define __PMC_EV_OCTEON()                         \
+    __PMC_EV(OCTEON, CLK)                         \
+    __PMC_EV(OCTEON, ISSUE)                       \
+    __PMC_EV(OCTEON, RET)                         \
+    __PMC_EV(OCTEON, NISSUE)                      \
+    __PMC_EV(OCTEON, SISSUE)                      \
+    __PMC_EV(OCTEON, DISSUE)                      \
+    __PMC_EV(OCTEON, IFI)                         \
+    __PMC_EV(OCTEON, BR)                          \
+    __PMC_EV(OCTEON, BRMIS)                       \
+    __PMC_EV(OCTEON, J)                           \
+    __PMC_EV(OCTEON, JMIS)                        \
+    __PMC_EV(OCTEON, REPLAY)                      \
+    __PMC_EV(OCTEON, IUNA)                        \
+    __PMC_EV(OCTEON, TRAP)                        \
+    __PMC_EV(OCTEON, UULOAD)                      \
+    __PMC_EV(OCTEON, UUSTORE)                     \
+    __PMC_EV(OCTEON, ULOAD)                       \
+    __PMC_EV(OCTEON, USTORE)                      \
+    __PMC_EV(OCTEON, EC)                          \
+    __PMC_EV(OCTEON, MC)                          \
+    __PMC_EV(OCTEON, CC)                          \
+    __PMC_EV(OCTEON, CSRC)                        \
+    __PMC_EV(OCTEON, CFETCH)                      \
+    __PMC_EV(OCTEON, CPREF)                       \
+    __PMC_EV(OCTEON, ICA)                         \
+    __PMC_EV(OCTEON, II)                          \
+    __PMC_EV(OCTEON, IP)                          \
+    __PMC_EV(OCTEON, CIMISS)                      \
+    __PMC_EV(OCTEON, WBUF)                        \
+    __PMC_EV(OCTEON, WDAT)                        \
+    __PMC_EV(OCTEON, WBUFLD)                      \
+    __PMC_EV(OCTEON, WBUFFL)                      \
+    __PMC_EV(OCTEON, WBUFTR)                      \
+    __PMC_EV(OCTEON, BADD)                        \
+    __PMC_EV(OCTEON, BADDL2)                      \
+    __PMC_EV(OCTEON, BFILL)                       \
+    __PMC_EV(OCTEON, DDIDS)                       \
+    __PMC_EV(OCTEON, IDIDS)                       \
+    __PMC_EV(OCTEON, DIDNA)                       \
+    __PMC_EV(OCTEON, LDS)                         \
+    __PMC_EV(OCTEON, LMLDS)                       \
+    __PMC_EV(OCTEON, IOLDS)                       \
+    __PMC_EV(OCTEON, DMLDS)                       \
+    __PMC_EV(OCTEON, STS)                         \
+    __PMC_EV(OCTEON, LMSTS)                       \
+    __PMC_EV(OCTEON, IOSTS)                       \
+    __PMC_EV(OCTEON, IOBDMA)                      \
+    __PMC_EV(OCTEON, DTLB)                        \
+    __PMC_EV(OCTEON, DTLBAD)                      \
+    __PMC_EV(OCTEON, ITLB)                        \
+    __PMC_EV(OCTEON, SYNC)                        \
+    __PMC_EV(OCTEON, SYNCIOB)                     \
+    __PMC_EV(OCTEON, SYNCW)
+
+#define	PMC_EV_OCTEON_FIRST	PMC_EV_OCTEON_CLK
+#define	PMC_EV_OCTEON_LAST	PMC_EV_OCTEON_SYNCW
+
 #define __PMC_EV_PPC7450() \
 	__PMC_EV(PPC7450, CYCLE)	\
 	__PMC_EV(PPC7450, INSTR_COMPLETED)	\
@@ -3655,6 +3725,7 @@
  * 0x11100	0x0100		INTEL Pentium Pro/P-II/P-III/Pentium-M events
  * 0x11200	0x00FF		INTEL XScale events
  * 0x11300      0x00FF          MIPS 24K events
+ * 0x20000	0x1000		Software events
  */
 #define	__PMC_EVENTS()				\
 	__PMC_EV_BLOCK(TSC,	0x01000)	\
@@ -3677,6 +3748,8 @@
 	__PMC_EV_XSCALE()                       \
 	__PMC_EV_BLOCK(MIPS24K,	0x11300)	\
 	__PMC_EV_MIPS24K()			\
+	__PMC_EV_BLOCK(OCTEON,	0x11400)	\
+	__PMC_EV_OCTEON()			\
 	__PMC_EV_BLOCK(UCF,	0x12000)	\
 	__PMC_EV_UCF()				\
 	__PMC_EV_BLOCK(UCP,	0x12080)	\
@@ -3685,6 +3758,6 @@
 	__PMC_EV_PPC7450()			\
=20
 #define	PMC_EVENT_FIRST	PMC_EV_TSC_TSC
-#define	PMC_EVENT_LAST	PMC_EV_UCP_LAST
+#define	PMC_EVENT_LAST	PMC_EV_SOFT_LAST
=20
 #endif /* _DEV_HWPMC_PMC_EVENTS_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ipw/if_ipw.c
--- a/head/sys/dev/ipw/if_ipw.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ipw/if_ipw.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/*	$FreeBSD: head/sys/dev/ipw/if_ipw.c 232874 2012-03-12 18:15:08Z scottl =
$	*/
+/*	$FreeBSD: head/sys/dev/ipw/if_ipw.c 233387 2012-03-23 19:32:30Z bschmid=
t $	*/
=20
 /*-
  * Copyright (c) 2004-2006
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ipw/if_ipw.c 232874 2012-03-12 18:15:08Z =
scottl $");
+__FBSDID("$FreeBSD: head/sys/dev/ipw/if_ipw.c 233387 2012-03-23 19:32:30Z =
bschmidt $");
=20
 /*-
  * Intel(R) PRO/Wireless 2100 MiniPCI driver
@@ -835,9 +835,9 @@
 ipw_suspend(device_t dev)
 {
 	struct ipw_softc *sc =3D device_get_softc(dev);
-
-	ipw_stop(sc);
-
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
+
+	ieee80211_suspend_all(ic);
 	return 0;
 }
=20
@@ -845,13 +845,11 @@
 ipw_resume(device_t dev)
 {
 	struct ipw_softc *sc =3D device_get_softc(dev);
-	struct ifnet *ifp =3D sc->sc_ifp;
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
=20
 	pci_write_config(dev, 0x41, 0, 1);
=20
-	if (ifp->if_flags & IFF_UP)
-		ipw_init(sc);
-
+	ieee80211_resume_all(ic);
 	return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/isci/isci.h
--- a/head/sys/dev/isci/isci.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/isci/isci.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/isci/isci.h 231296 2012-02-09 17:50:24Z jimharri=
s $
+ * $FreeBSD: head/sys/dev/isci/isci.h 234106 2012-04-10 16:33:19Z jimharri=
s $
  */
=20
 #include <sys/param.h>
@@ -86,13 +86,14 @@
 	BOOL				is_resetting;
 	uint32_t			frozen_lun_mask;
 	SCI_FAST_LIST_ELEMENT_T		pending_device_reset_element;
+	TAILQ_HEAD(,ccb_hdr)		queued_ccbs;
 };
=20
 struct ISCI_DOMAIN {
-	struct ISCI_CONTROLLER	*controller;
-	SCI_DOMAIN_HANDLE_T	sci_object;
-	uint8_t			index;
-
+	struct ISCI_CONTROLLER		*controller;
+	SCI_DOMAIN_HANDLE_T		sci_object;
+	uint8_t				index;
+	struct ISCI_REMOTE_DEVICE	*da_remote_device;
 };
=20
 struct ISCI_MEMORY
@@ -122,6 +123,7 @@
 	SCI_CONTROLLER_HANDLE_T	scif_controller_handle;
 	struct ISCI_DOMAIN	domain[SCI_MAX_DOMAINS];
 	BOOL			is_started;
+	BOOL			has_been_scanned;
 	uint32_t		initial_discovery_mask;
 	BOOL			is_frozen;
 	uint8_t			*remote_device_memory;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/isci/isci_controller.c
--- a/head/sys/dev/isci/isci_controller.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/isci/isci_controller.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,13 +29,16 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/isci/isci_controller.c 231860 2012-02-17 =
06:47:16Z sbruno $");
+__FBSDID("$FreeBSD: head/sys/dev/isci/isci_controller.c 234106 2012-04-10 =
16:33:19Z jimharris $");
=20
 #include <dev/isci/isci.h>
=20
 #include <sys/conf.h>
 #include <sys/malloc.h>
=20
+#include <cam/cam_periph.h>
+#include <cam/cam_xpt_periph.h>
+
 #include <dev/isci/scil/sci_memory_descriptor_list.h>
 #include <dev/isci/scil/sci_memory_descriptor_list_decorator.h>
=20
@@ -300,6 +303,16 @@
 	TUNABLE_INT_FETCH("hw.isci.io_shortage", &io_shortage);
 	controller->sim_queue_depth +=3D io_shortage;
=20
+	/* Attach to CAM using xpt_bus_register now, then immediately freeze
+	 *  the simq.  It will get released later when initial domain discovery
+	 *  is complete.
+	 */
+	controller->has_been_scanned =3D FALSE;
+	mtx_lock(&controller->lock);
+	isci_controller_attach_to_cam(controller);
+	xpt_freeze_simq(controller->sim, 1);
+	mtx_unlock(&controller->lock);
+
 	return (scif_controller_initialize(controller->scif_controller_handle));
 }
=20
@@ -417,7 +430,19 @@
 		remote_device->frozen_lun_mask =3D 0;
 		sci_fast_list_element_init(remote_device,
 		    &remote_device->pending_device_reset_element);
-		sci_pool_put(controller->remote_device_pool, remote_device);
+		TAILQ_INIT(&remote_device->queued_ccbs);
+
+		/*
+		 * For the first SCI_MAX_DOMAINS device objects, do not put
+		 *  them in the pool, rather assign them to each domain.  This
+		 *  ensures that any device attached directly to port "i" will
+		 *  always get CAM target id "i".
+		 */
+		if (i < SCI_MAX_DOMAINS)
+			controller->domain[i].da_remote_device =3D remote_device;
+		else
+			sci_pool_put(controller->remote_device_pool,
+			    remote_device);
 		remote_device_memory_ptr +=3D remote_device_size;
 	}
=20
@@ -441,13 +466,13 @@
 void isci_controller_domain_discovery_complete(
     struct ISCI_CONTROLLER *isci_controller, struct ISCI_DOMAIN *isci_doma=
in)
 {
-	if (isci_controller->sim =3D=3D NULL)
+	if (!isci_controller->has_been_scanned)
 	{
-		/* Controller has not been attached to CAM yet.  We'll clear
+		/* Controller has not been scanned yet.  We'll clear
 		 *  the discovery bit for this domain, then check if all bits
 		 *  are now clear.  That would indicate that all domains are
-		 *  done with discovery and we can then attach the controller
-		 *  to CAM.
+		 *  done with discovery and we can then proceed with initial
+		 *  scan.
 		 */
=20
 		isci_controller->initial_discovery_mask &=3D
@@ -457,7 +482,25 @@
 			struct isci_softc *driver =3D isci_controller->isci;
 			uint8_t next_index =3D isci_controller->index + 1;
=20
-			isci_controller_attach_to_cam(isci_controller);
+			isci_controller->has_been_scanned =3D TRUE;
+
+			/* Unfreeze simq to allow initial scan to proceed. */
+			xpt_release_simq(isci_controller->sim, TRUE);
+
+#if __FreeBSD_version < 800000
+			/* When driver is loaded after boot, we need to
+			 *  explicitly rescan here for versions <8.0, because
+			 *  CAM only automatically scans new buses at boot
+			 *  time.
+			 */
+			union ccb *ccb =3D xpt_alloc_ccb_nowait();
+
+			xpt_create_path(&ccb->ccb_h.path, xpt_periph,
+			    cam_sim_path(isci_controller->sim),
+			    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
+
+			xpt_rescan(ccb);
+#endif
=20
 			if (next_index < driver->controller_count) {
 				/*  There are more controllers that need to
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/isci/isci_domain.c
--- a/head/sys/dev/isci/isci_domain.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/isci/isci_domain.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/isci/isci_domain.c 231136 2012-02-07 17:4=
3:58Z jimharris $");
+__FBSDID("$FreeBSD: head/sys/dev/isci/isci_domain.c 233622 2012-03-28 18:3=
8:13Z jimharris $");
=20
 #include <dev/isci/isci.h>
=20
@@ -202,10 +202,14 @@
 	struct ISCI_REMOTE_DEVICE *remote_device;
 	struct ISCI_DOMAIN *isci_domain =3D
 	    (struct ISCI_DOMAIN *)sci_object_get_association(domain);
-	struct ISCI_CONTROLLER *isci_controller =3D
-	    (struct ISCI_CONTROLLER *)sci_object_get_association(controller);
=20
-	sci_pool_get(isci_controller->remote_device_pool, remote_device);
+	/*
+	 * For direct-attached devices, do not pull the device object from
+	 *  the pool.  Rather, use the one stored in the domain object which
+	 *  will ensure that we always get consistent target ids for direct
+	 *  attached devices.
+	 */
+	remote_device =3D isci_domain->da_remote_device;
=20
 	scif_remote_device_construct(domain,
 	    (uint8_t*)remote_device + sizeof(struct ISCI_REMOTE_DEVICE),
@@ -287,6 +291,8 @@
 {
 	struct ISCI_REMOTE_DEVICE *isci_remote_device =3D
 	    (struct ISCI_REMOTE_DEVICE *)sci_object_get_association(remote_device=
);
+	struct ISCI_DOMAIN *isci_domain =3D
+	    (struct ISCI_DOMAIN *)sci_object_get_association(domain);
 	struct ISCI_CONTROLLER *isci_controller =3D
 	    (struct ISCI_CONTROLLER *)sci_object_get_association(controller);
 	uint32_t path =3D cam_sim_path(isci_controller->sim);
@@ -301,7 +307,13 @@
=20
 	scif_remote_device_destruct(remote_device);
=20
-	sci_pool_put(isci_controller->remote_device_pool, isci_remote_device);
+	/*
+	 * Only put the remote device back into the pool if it was an
+	 *  expander-attached device.
+	 */
+	if (isci_remote_device !=3D isci_domain->da_remote_device)
+		sci_pool_put(isci_controller->remote_device_pool,
+		    isci_remote_device);
 }
=20
 void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/isci/isci_io_request.c
--- a/head/sys/dev/isci/isci_io_request.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/isci/isci_io_request.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/isci/isci_io_request.c 231296 2012-02-09 =
17:50:24Z jimharris $");
+__FBSDID("$FreeBSD: head/sys/dev/isci/isci_io_request.c 234106 2012-04-10 =
16:33:19Z jimharris $");
=20
 #include <dev/isci/isci.h>
=20
@@ -85,7 +85,9 @@
 	struct ISCI_CONTROLLER *isci_controller;
 	struct ISCI_REMOTE_DEVICE *isci_remote_device;
 	union ccb *ccb;
+	BOOL complete_ccb;
=20
+	complete_ccb =3D TRUE;
 	isci_controller =3D (struct ISCI_CONTROLLER *) sci_object_get_association=
(scif_controller);
 	isci_remote_device =3D
 		(struct ISCI_REMOTE_DEVICE *) sci_object_get_association(remote_device);
@@ -163,9 +165,7 @@
=20
 	case SCI_IO_FAILURE_INVALID_STATE:
 	case SCI_IO_FAILURE_INSUFFICIENT_RESOURCES:
-		ccb->ccb_h.status |=3D CAM_REQUEUE_REQ;
-		isci_remote_device_freeze_lun_queue(isci_remote_device,
-		    ccb->ccb_h.target_lun);
+		complete_ccb =3D FALSE;
 		break;
=20
 	case SCI_IO_FAILURE_INVALID_REMOTE_DEVICE:
@@ -189,7 +189,7 @@
 			    scif_remote_device_get_max_queue_depth(remote_device);
 			xpt_action((union ccb *)&ccb_relsim);
 			xpt_free_path(path);
-			ccb->ccb_h.status |=3D CAM_REQUEUE_REQ;
+			complete_ccb =3D FALSE;
 		}
 		break;
=20
@@ -209,17 +209,6 @@
 		break;
 	}
=20
-	if (ccb->ccb_h.status !=3D CAM_REQ_CMP) {
-		/* ccb will be completed with some type of non-success
-		 *  status.  So temporarily freeze the queue until the
-		 *  upper layers can act on the status.  The CAM_DEV_QFRZN
-		 *  flag will then release the queue after the status is
-		 *  acted upon.
-		 */
-		ccb->ccb_h.status |=3D CAM_DEV_QFRZN;
-		xpt_freeze_devq(ccb->ccb_h.path, 1);
-	}
-
 	callout_stop(&isci_request->parent.timer);
 	bus_dmamap_sync(isci_request->parent.dma_tag,
 	    isci_request->parent.dma_map,
@@ -228,20 +217,43 @@
 	bus_dmamap_unload(isci_request->parent.dma_tag,
 	    isci_request->parent.dma_map);
=20
-	if (isci_remote_device->frozen_lun_mask !=3D 0 &&
-	    !(ccb->ccb_h.status & CAM_REQUEUE_REQ))
-		isci_remote_device_release_device_queue(isci_remote_device);
-
-	xpt_done(ccb);
 	isci_request->ccb =3D NULL;
=20
-	if (isci_controller->is_frozen =3D=3D TRUE) {
-		isci_controller->is_frozen =3D FALSE;
-		xpt_release_simq(isci_controller->sim, TRUE);
-	}
-
 	sci_pool_put(isci_controller->request_pool,
 	    (struct ISCI_REQUEST *)isci_request);
+
+	if (complete_ccb) {
+		if (ccb->ccb_h.status !=3D CAM_REQ_CMP) {
+			/* ccb will be completed with some type of non-success
+			 *  status.  So temporarily freeze the queue until the
+			 *  upper layers can act on the status.  The
+			 *  CAM_DEV_QFRZN flag will then release the queue
+			 *  after the status is acted upon.
+			 */
+			ccb->ccb_h.status |=3D CAM_DEV_QFRZN;
+			xpt_freeze_devq(ccb->ccb_h.path, 1);
+		}
+
+		if (isci_remote_device->frozen_lun_mask !=3D 0) {
+			isci_remote_device_release_device_queue(isci_remote_device);
+		}
+
+		xpt_done(ccb);
+
+		if (isci_controller->is_frozen =3D=3D TRUE) {
+			isci_controller->is_frozen =3D FALSE;
+			xpt_release_simq(isci_controller->sim, TRUE);
+		}
+	} else {
+		isci_remote_device_freeze_lun_queue(isci_remote_device,
+		    ccb->ccb_h.target_lun);
+
+		isci_log_message(1, "ISCI", "queue %p %x\n", ccb,
+		    ccb->csio.cdb_io.cdb_bytes[0]);
+		ccb->ccb_h.status |=3D CAM_SIM_QUEUED;
+		TAILQ_INSERT_TAIL(&isci_remote_device->queued_ccbs,
+		    &ccb->ccb_h, sim_links.tqe);
+	}
 }
=20
 /**
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/isci/isci_remote_device.c
--- a/head/sys/dev/isci/isci_remote_device.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/isci/isci_remote_device.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/isci/isci_remote_device.c 231296 2012-02-=
09 17:50:24Z jimharris $");
+__FBSDID("$FreeBSD: head/sys/dev/isci/isci_remote_device.c 234106 2012-04-=
10 16:33:19Z jimharris $");
=20
 #include <dev/isci/isci.h>
=20
@@ -74,13 +74,12 @@
 		isci_controller->remote_device[device_index] =3D
 		    isci_remote_device;
=20
-		if (isci_controller->sim !=3D NULL) {
-			/* The sim object is not NULL, meaning we have attached
-			 *  the controller to CAM already.  In that case, create
-			 *  a CCB to instruct CAM to rescan this device.
-			 * If the sim object is NULL, this device will get
-			 *  scanned as part of the initial scan when the
-			 *  controller is attached to CAM.
+		if (isci_controller->has_been_scanned) {
+			/* The sim object has been scanned at least once
+			 *  already.  In that case, create a CCB to instruct
+			 *  CAM to rescan this device.
+			 * If the sim object has not been scanned, this device
+			 *  will get scanned as part of the initial scan.
 			 */
 			union ccb *ccb =3D xpt_alloc_ccb_nowait();
=20
@@ -290,9 +289,22 @@
=20
 void
 isci_remote_device_release_device_queue(
-    struct ISCI_REMOTE_DEVICE *remote_device)
+    struct ISCI_REMOTE_DEVICE *device)
 {
-	lun_id_t lun;
-	for (lun =3D 0; lun < ISCI_MAX_LUN; lun++)
-		isci_remote_device_release_lun_queue(remote_device, lun);
+	if (TAILQ_EMPTY(&device->queued_ccbs)) {
+		lun_id_t lun;
+
+		for (lun =3D 0; lun < ISCI_MAX_LUN; lun++)
+			isci_remote_device_release_lun_queue(device, lun);
+	} else {
+		struct ccb_hdr *ccb_h;
+
+		ccb_h =3D TAILQ_FIRST(&device->queued_ccbs);
+		TAILQ_REMOVE(&device->queued_ccbs, ccb_h, sim_links.tqe);
+		ccb_h->status &=3D ~CAM_SIM_QUEUED;
+		isci_log_message(1, "ISCI", "release %p %x\n", ccb_h,
+		    ((union ccb*)ccb_h)->csio.cdb_io.cdb_bytes[0]);
+		isci_io_request_execute_scsi_io((union ccb *)ccb_h,
+		    device->domain->controller);
+	}
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/isci/isci_task_request.c
--- a/head/sys/dev/isci/isci_task_request.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/isci/isci_task_request.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/isci/isci_task_request.c 231136 2012-02-0=
7 17:43:58Z jimharris $");
+__FBSDID("$FreeBSD: head/sys/dev/isci/isci_task_request.c 233710 2012-03-3=
0 22:52:08Z dim $");
=20
 #include <dev/isci/isci.h>
=20
@@ -188,7 +188,7 @@
=20
 	isci_remote_device->is_resetting =3D FALSE;
=20
-	switch (completion_status) {
+	switch ((int)completion_status) {
 	case SCI_TASK_SUCCESS:
 	case SCI_TASK_FAILURE_RESPONSE_VALID:
 		break;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/isci/scil/sati_read_capac=
ity.c
--- a/head/sys/dev/isci/scil/sati_read_capacity.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sys/dev/isci/scil/sati_read_capacity.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -51,7 +51,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/isci/scil/sati_read_capacity.c 231136 201=
2-02-07 17:43:58Z jimharris $");
+__FBSDID("$FreeBSD: head/sys/dev/isci/scil/sati_read_capacity.c 233663 201=
2-03-29 15:43:07Z jimharris $");
=20
 /**
  * @file
@@ -308,6 +308,10 @@
    sati_set_data_byte(sequence, scsi_io, 10, (U8)((sector_size >> 8)  & 0x=
FF));
    sati_set_data_byte(sequence, scsi_io, 11, (U8)(sector_size & 0xFF));
=20
+   //Explicitly set byte 12 to 0.  SATI requires that all bytes in the data
+   //response be explicitly set to some value.
+   sati_set_data_byte(sequence, scsi_io, 12, 0);
+
    //Check Bit 13 of ATA_IDENTIFY_DEVICE_DATA physical_logical_sector_info
    //(Word 106) is enabled
    physical_per_logical_enable_bit =3D (identify_device_data->physical_log=
ical_sector_info
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/iscsi/initiator/isc_subr.c
--- a/head/sys/dev/iscsi/initiator/isc_subr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/iscsi/initiator/isc_subr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2005-2010 Daniel Braniss <danny at cs.huji.ac.il>
+ * Copyright (c) 2005-2011 Daniel Braniss <danny at cs.huji.ac.il>
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/iscsi/initiator/isc_subr.c 227293 2011-11=
-07 06:44:47Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/iscsi/initiator/isc_subr.c 234233 2012-04=
-13 18:21:56Z jpaetzel $");
=20
 #include "opt_iscsi_initiator.h"
=20
@@ -77,6 +77,104 @@
=20
      return q;
 }
+#if __FreeBSD_version < 800000
+/*****************************************************************/
+/*                                                               */
+/* CRC LOOKUP TABLE                                              */
+/* =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D                       =
                       */
+/* The following CRC lookup table was generated automagically    */
+/* by the Rocksoft^tm Model CRC Algorithm Table Generation       */
+/* Program V1.0 using the following model parameters:            */
+/*                                                               */
+/*    Width   : 4 bytes.                                         */
+/*    Poly    : 0x1EDC6F41L                                      */
+/*    Reverse : TRUE.                                            */
+/*                                                               */
+/* For more information on the Rocksoft^tm Model CRC Algorithm,  */
+/* see the document titled "A Painless Guide to CRC Error        */
+/* Detection Algorithms" by Ross Williams                        */
+/* (ross at guest.adelaide.edu.au.). This document is likely to be  */
+/* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft".        */
+/*                                                               */
+/*****************************************************************/
+
+static uint32_t crc32Table[256] =3D {
+    0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L,
+    0xC79A971FL, 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL,
+    0x8AD958CFL, 0x78B2DBCCL, 0x6BE22838L, 0x9989AB3BL,
+    0x4D43CFD0L, 0xBF284CD3L, 0xAC78BF27L, 0x5E133C24L,
+    0x105EC76FL, 0xE235446CL, 0xF165B798L, 0x030E349BL,
+    0xD7C45070L, 0x25AFD373L, 0x36FF2087L, 0xC494A384L,
+    0x9A879FA0L, 0x68EC1CA3L, 0x7BBCEF57L, 0x89D76C54L,
+    0x5D1D08BFL, 0xAF768BBCL, 0xBC267848L, 0x4E4DFB4BL,
+    0x20BD8EDEL, 0xD2D60DDDL, 0xC186FE29L, 0x33ED7D2AL,
+    0xE72719C1L, 0x154C9AC2L, 0x061C6936L, 0xF477EA35L,
+    0xAA64D611L, 0x580F5512L, 0x4B5FA6E6L, 0xB93425E5L,
+    0x6DFE410EL, 0x9F95C20DL, 0x8CC531F9L, 0x7EAEB2FAL,
+    0x30E349B1L, 0xC288CAB2L, 0xD1D83946L, 0x23B3BA45L,
+    0xF779DEAEL, 0x05125DADL, 0x1642AE59L, 0xE4292D5AL,
+    0xBA3A117EL, 0x4851927DL, 0x5B016189L, 0xA96AE28AL,
+    0x7DA08661L, 0x8FCB0562L, 0x9C9BF696L, 0x6EF07595L,
+    0x417B1DBCL, 0xB3109EBFL, 0xA0406D4BL, 0x522BEE48L,
+    0x86E18AA3L, 0x748A09A0L, 0x67DAFA54L, 0x95B17957L,
+    0xCBA24573L, 0x39C9C670L, 0x2A993584L, 0xD8F2B687L,
+    0x0C38D26CL, 0xFE53516FL, 0xED03A29BL, 0x1F682198L,
+    0x5125DAD3L, 0xA34E59D0L, 0xB01EAA24L, 0x42752927L,
+    0x96BF4DCCL, 0x64D4CECFL, 0x77843D3BL, 0x85EFBE38L,
+    0xDBFC821CL, 0x2997011FL, 0x3AC7F2EBL, 0xC8AC71E8L,
+    0x1C661503L, 0xEE0D9600L, 0xFD5D65F4L, 0x0F36E6F7L,
+    0x61C69362L, 0x93AD1061L, 0x80FDE395L, 0x72966096L,
+    0xA65C047DL, 0x5437877EL, 0x4767748AL, 0xB50CF789L,
+    0xEB1FCBADL, 0x197448AEL, 0x0A24BB5AL, 0xF84F3859L,
+    0x2C855CB2L, 0xDEEEDFB1L, 0xCDBE2C45L, 0x3FD5AF46L,
+    0x7198540DL, 0x83F3D70EL, 0x90A324FAL, 0x62C8A7F9L,
+    0xB602C312L, 0x44694011L, 0x5739B3E5L, 0xA55230E6L,
+    0xFB410CC2L, 0x092A8FC1L, 0x1A7A7C35L, 0xE811FF36L,
+    0x3CDB9BDDL, 0xCEB018DEL, 0xDDE0EB2AL, 0x2F8B6829L,
+    0x82F63B78L, 0x709DB87BL, 0x63CD4B8FL, 0x91A6C88CL,
+    0x456CAC67L, 0xB7072F64L, 0xA457DC90L, 0x563C5F93L,
+    0x082F63B7L, 0xFA44E0B4L, 0xE9141340L, 0x1B7F9043L,
+    0xCFB5F4A8L, 0x3DDE77ABL, 0x2E8E845FL, 0xDCE5075CL,
+    0x92A8FC17L, 0x60C37F14L, 0x73938CE0L, 0x81F80FE3L,
+    0x55326B08L, 0xA759E80BL, 0xB4091BFFL, 0x466298FCL,
+    0x1871A4D8L, 0xEA1A27DBL, 0xF94AD42FL, 0x0B21572CL,
+    0xDFEB33C7L, 0x2D80B0C4L, 0x3ED04330L, 0xCCBBC033L,
+    0xA24BB5A6L, 0x502036A5L, 0x4370C551L, 0xB11B4652L,
+    0x65D122B9L, 0x97BAA1BAL, 0x84EA524EL, 0x7681D14DL,
+    0x2892ED69L, 0xDAF96E6AL, 0xC9A99D9EL, 0x3BC21E9DL,
+    0xEF087A76L, 0x1D63F975L, 0x0E330A81L, 0xFC588982L,
+    0xB21572C9L, 0x407EF1CAL, 0x532E023EL, 0xA145813DL,
+    0x758FE5D6L, 0x87E466D5L, 0x94B49521L, 0x66DF1622L,
+    0x38CC2A06L, 0xCAA7A905L, 0xD9F75AF1L, 0x2B9CD9F2L,
+    0xFF56BD19L, 0x0D3D3E1AL, 0x1E6DCDEEL, 0xEC064EEDL,
+    0xC38D26C4L, 0x31E6A5C7L, 0x22B65633L, 0xD0DDD530L,
+    0x0417B1DBL, 0xF67C32D8L, 0xE52CC12CL, 0x1747422FL,
+    0x49547E0BL, 0xBB3FFD08L, 0xA86F0EFCL, 0x5A048DFFL,
+    0x8ECEE914L, 0x7CA56A17L, 0x6FF599E3L, 0x9D9E1AE0L,
+    0xD3D3E1ABL, 0x21B862A8L, 0x32E8915CL, 0xC083125FL,
+    0x144976B4L, 0xE622F5B7L, 0xF5720643L, 0x07198540L,
+    0x590AB964L, 0xAB613A67L, 0xB831C993L, 0x4A5A4A90L,
+    0x9E902E7BL, 0x6CFBAD78L, 0x7FAB5E8CL, 0x8DC0DD8FL,
+    0xE330A81AL, 0x115B2B19L, 0x020BD8EDL, 0xF0605BEEL,
+    0x24AA3F05L, 0xD6C1BC06L, 0xC5914FF2L, 0x37FACCF1L,
+    0x69E9F0D5L, 0x9B8273D6L, 0x88D28022L, 0x7AB90321L,
+    0xAE7367CAL, 0x5C18E4C9L, 0x4F48173DL, 0xBD23943EL,
+    0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L,
+    0x34F4F86AL, 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL,
+    0x79B737BAL, 0x8BDCB4B9L, 0x988C474DL, 0x6AE7C44EL,
+    0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, 0xAD7D5351L
+};
+
+static __inline int
+calculate_crc32c(uint32_t crc, const void *buf, size_t size)
+{
+     const uint8_t *p =3D buf;
+
+     while (size--)
+	  crc =3D crc32Table[(crc ^ *p++) & 0xff] ^ (crc >> 8);
+     return crc;
+}
+#endif
=20
 static uint32_t
 i_crc32c(const void *buf, size_t size, uint32_t crc)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/iscsi/initiator/iscsi.c
--- a/head/sys/dev/iscsi/initiator/iscsi.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/iscsi/initiator/iscsi.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2005-2010 Daniel Braniss <danny at cs.huji.ac.il>
+ * Copyright (c) 2005-2011 Daniel Braniss <danny at cs.huji.ac.il>
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/iscsi/initiator/iscsi.c 227293 2011-11-07=
 06:44:47Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/iscsi/initiator/iscsi.c 234233 2012-04-13=
 18:21:56Z jpaetzel $");
=20
 #include "opt_iscsi_initiator.h"
=20
@@ -60,7 +60,7 @@
=20
 #include <dev/iscsi/initiator/iscsi.h>
 #include <dev/iscsi/initiator/iscsivar.h>
-static char *iscsi_driver_version =3D "2.2.4.2";
+static char *iscsi_driver_version =3D "2.3.1";
=20
 static struct isc_softc *isc;
=20
@@ -231,8 +231,8 @@
 	  if(error =3D=3D 0) {
 	       sp->proc =3D td->td_proc;
 	       SYSCTL_ADD_INT(&sp->clist, SYSCTL_CHILDREN(sp->oid),
-		   OID_AUTO, "pid", CTLFLAG_RD,
-		   &sp->proc->p_pid, sizeof(pid_t), "control process id");
+			       OID_AUTO, "pid", CTLFLAG_RD,
+			       &sp->proc->p_pid, sizeof(pid_t), "control process id");
 	  }
 	  break;
=20
@@ -290,8 +290,7 @@
 	       sprintf(buf, "%03d] '%s' '%s'\n", i++, sp->opt.targetAddress, sp->=
opt.targetName);
 	       uiomove(buf, strlen(buf), uio);
 	  }
-	  sprintf(buf, "%d/%d /---- free -----/\n", sc->npdu_alloc, sc->npdu_max);
-	  i =3D 0;
+	  sprintf(buf, "free npdu_alloc=3D%d, npdu_max=3D%d\n", sc->npdu_alloc, s=
c->npdu_max);
 	  uiomove(buf, strlen(buf), uio);
      }
      else {
@@ -696,7 +695,6 @@
 static void
 free_pdus(struct isc_softc *sc)
 {
-
      debug_called(8);
=20
      if(sc->pdu_zone !=3D NULL) {
@@ -777,6 +775,10 @@
 		    sizeof(isc->nsess),
 		    "number of active session");
=20
+#ifdef ISCSI_INITIATOR_DEBUG
+     mtx_init(&iscsi_dbg_mtx, "iscsi_dbg", NULL, MTX_DEF);
+#endif
+
      printf("iscsi: version %s\n", iscsi_driver_version);
 }
=20
@@ -814,6 +816,11 @@
 	  xdebug("sysctl_ctx_free failed");
=20
      iscsi_shutdown(isc); // XXX: check EVENTHANDLER_ ...
+
+#ifdef ISCSI_INITIATOR_DEBUG
+     mtx_destroy(&iscsi_dbg_mtx);
+#endif
+
      free(isc, M_ISCSI);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/iscsi/initiator/iscsi_sub=
r.c
--- a/head/sys/dev/iscsi/initiator/iscsi_subr.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/sys/dev/iscsi/initiator/iscsi_subr.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/iscsi/initiator/iscsi_subr.c 226208 2011-=
10-10 13:26:53Z kib $");
+__FBSDID("$FreeBSD: head/sys/dev/iscsi/initiator/iscsi_subr.c 234233 2012-=
04-13 18:21:56Z jpaetzel $");
=20
 #include "opt_iscsi_initiator.h"
=20
@@ -154,7 +154,7 @@
      scsi_rsp_t		*cmd =3D &pp->ipdu.scsi_rsp;
      caddr_t		bp;
      int		sense_len, mustfree =3D 0;
-     int		error_code, sense_key, asc, ascq;
+     int                error_code, sense_key, asc, ascq;
=20
      bp =3D mtod(pq->mp, caddr_t);
      if((sense_len =3D scsi_2btoul(bp)) =3D=3D 0)
@@ -176,9 +176,8 @@
      scsi->sense_resid =3D 0;
      if(cmd->flag & (BIT(1)|BIT(2)))
 	  scsi->sense_resid =3D ntohl(pp->ipdu.scsi_rsp.rcnt);
-
      scsi_extract_sense_len(sense, scsi->sense_len - scsi->sense_resid,
-	&error_code, &sense_key, &asc, &ascq, /*show_errors*/ 1);
+       &error_code, &sense_key, &asc, &ascq, /*show_errors*/ 1);
=20
      debug(3, "sense_len=3D%d rcnt=3D%d sense_resid=3D%d dsl=3D%d error_co=
de=3D%x flags=3D%x",
 	   sense_len,
@@ -479,6 +478,8 @@
      cmd =3D &pq->pdu.ipdu.scsi_req;
      cmd->opcode =3D ISCSI_SCSI_CMD;
      cmd->F =3D 1;
+#if 0
+// this breaks at least Isilon's iscsi target.
      /*
       | map tag option, default is UNTAGGED
       */
@@ -488,6 +489,9 @@
      case MSG_ORDERED_Q_TAG:	cmd->attr =3D iSCSI_TASK_ORDER;	break;
      case MSG_ACA_TASK:		cmd->attr =3D iSCSI_TASK_ACA;	break;
      }
+#else
+     cmd->attr =3D iSCSI_TASK_SIMPLE;
+#endif
=20
      dwl(sp, ccb_h->target_lun, (u_char *)&cmd->lun);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/iscsi/initiator/iscsivar.h
--- a/head/sys/dev/iscsi/initiator/iscsivar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/iscsi/initiator/iscsivar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2005-2010 Daniel Braniss <danny at cs.huji.ac.il>
+ * Copyright (c) 2005-2011 Daniel Braniss <danny at cs.huji.ac.il>
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/iscsi/initiator/iscsivar.h 227267 2011-11-06 20:=
16:50Z ed $
+ * $FreeBSD: head/sys/dev/iscsi/initiator/iscsivar.h 234233 2012-04-13 18:=
21:56Z jpaetzel $
  */
=20
 /*
@@ -203,6 +203,8 @@
      struct sx 		unit_sx;
=20
      uma_zone_t		pdu_zone;	// pool of free pdu's
+     TAILQ_HEAD(,pduq)	freepdu;
+
 #ifdef  ISCSI_INITIATOR_DEBUG
      int		 npdu_alloc, npdu_max; // for instrumentation
 #endif
@@ -305,9 +307,11 @@
 	  return NULL;
      }
 #ifdef ISCSI_INITIATOR_DEBUG
+     mtx_lock(&iscsi_dbg_mtx);
      isc->npdu_alloc++;
      if(isc->npdu_alloc > isc->npdu_max)
 	  isc->npdu_max =3D isc->npdu_alloc;
+     mtx_unlock(&iscsi_dbg_mtx);
 #endif
      memset(pq, 0, sizeof(pduq_t));
=20
@@ -323,10 +327,12 @@
      if(pq->buf !=3D NULL)
 	  free(pq->buf, M_ISCSIBUF);
 #endif
+     uma_zfree(isc->pdu_zone, pq);
 #ifdef ISCSI_INITIATOR_DEBUG
+     mtx_lock(&iscsi_dbg_mtx);
      isc->npdu_alloc--;
+     mtx_unlock(&iscsi_dbg_mtx);
 #endif
-     uma_zfree(isc->pdu_zone, pq);
 }
=20
 static __inline void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/iwi/if_iwi.c
--- a/head/sys/dev/iwi/if_iwi.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/iwi/if_iwi.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/iwi/if_iwi.c 232785 2012-03-10 17:08:57Z =
iwasaki $");
+__FBSDID("$FreeBSD: head/sys/dev/iwi/if_iwi.c 233387 2012-03-23 19:32:30Z =
bschmidt $");
=20
 /*-
  * Intel(R) PRO/Wireless 2200BG/2225BG/2915ABG driver
@@ -863,9 +863,9 @@
 iwi_suspend(device_t dev)
 {
 	struct iwi_softc *sc =3D device_get_softc(dev);
-
-	iwi_stop(sc);
-
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
+
+	ieee80211_suspend_all(ic);
 	return 0;
 }
=20
@@ -873,13 +873,11 @@
 iwi_resume(device_t dev)
 {
 	struct iwi_softc *sc =3D device_get_softc(dev);
-	struct ifnet *ifp =3D sc->sc_ifp;
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
=20
 	pci_write_config(dev, 0x41, 0, 1);
=20
-	if (ifp->if_flags & IFF_UP)
-		iwi_init(sc);
-
+	ieee80211_resume_all(ic);
 	return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/iwn/if_iwn.c
--- a/head/sys/dev/iwn/if_iwn.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/iwn/if_iwn.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/iwn/if_iwn.c 230620 2012-01-27 17:39:02Z =
bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/iwn/if_iwn.c 234324 2012-04-15 20:29:39Z =
adrian $");
=20
 #include <sys/param.h>
 #include <sys/sockio.h>
@@ -79,33 +79,35 @@
 };
=20
 static const struct iwn_ident iwn_ident_table[] =3D {
-	{ 0x8086, 0x0082, "Intel(R) Centrino(R) Advanced-N 6205"	 },
-	{ 0x8086, 0x0083, "Intel(R) Centrino(R) Wireless-N 1000"	 },
-	{ 0x8086, 0x0084, "Intel(R) Centrino(R) Wireless-N 1000"	 },
-	{ 0x8086, 0x0085, "Intel(R) Centrino(R) Advanced-N 6205"	 },
-	{ 0x8086, 0x0087, "Intel(R) Centrino(R) Advanced-N + WiMAX 6250" },
-	{ 0x8086, 0x0089, "Intel(R) Centrino(R) Advanced-N + WiMAX 6250" },
-	{ 0x8086, 0x008a, "Intel(R) Centrino(R) Wireless-N 1030"	 },
-	{ 0x8086, 0x008b, "Intel(R) Centrino(R) Wireless-N 1030"	 },
-	{ 0x8086, 0x0090, "Intel(R) Centrino(R) Advanced-N 6230"	 },
-	{ 0x8086, 0x0091, "Intel(R) Centrino(R) Advanced-N 6230"	 },
-	{ 0x8086, 0x0896, "Intel(R) Centrino(R) Wireless-N 130"		 },
-	{ 0x8086, 0x4229, "Intel(R) Wireless WiFi Link 4965"		 },
-	{ 0x8086, 0x422b, "Intel(R) Centrino(R) Ultimate-N 6300"	 },
-	{ 0x8086, 0x422c, "Intel(R) Centrino(R) Advanced-N 6200"	 },
-	{ 0x8086, 0x422d, "Intel(R) Wireless WiFi Link 4965"		 },
-	{ 0x8086, 0x4230, "Intel(R) Wireless WiFi Link 4965"		 },
-	{ 0x8086, 0x4232, "Intel(R) WiFi Link 5100"			 },
-	{ 0x8086, 0x4233, "Intel(R) Wireless WiFi Link 4965"		 },
-	{ 0x8086, 0x4235, "Intel(R) Ultimate N WiFi Link 5300"		 },
-	{ 0x8086, 0x4236, "Intel(R) Ultimate N WiFi Link 5300"		 },
-	{ 0x8086, 0x4237, "Intel(R) WiFi Link 5100"			 },
-	{ 0x8086, 0x4238, "Intel(R) Centrino(R) Ultimate-N 6300"	 },
-	{ 0x8086, 0x4239, "Intel(R) Centrino(R) Advanced-N 6200"	 },
-	{ 0x8086, 0x423a, "Intel(R) WiMAX/WiFi Link 5350"		 },
-	{ 0x8086, 0x423b, "Intel(R) WiMAX/WiFi Link 5350"		 },
-	{ 0x8086, 0x423c, "Intel(R) WiMAX/WiFi Link 5150"		 },
-	{ 0x8086, 0x423d, "Intel(R) WiMAX/WiFi Link 5150"		 },
+	{ 0x8086, 0x0082, "Intel Centrino Advanced-N 6205"		},
+	{ 0x8086, 0x0083, "Intel Centrino Wireless-N 1000"		},
+	{ 0x8086, 0x0084, "Intel Centrino Wireless-N 1000"		},
+	{ 0x8086, 0x0085, "Intel Centrino Advanced-N 6205"		},
+	{ 0x8086, 0x0087, "Intel Centrino Advanced-N + WiMAX 6250"	},
+	{ 0x8086, 0x0089, "Intel Centrino Advanced-N + WiMAX 6250"	},
+	{ 0x8086, 0x008a, "Intel Centrino Wireless-N 1030"		},
+	{ 0x8086, 0x008b, "Intel Centrino Wireless-N 1030"		},
+	{ 0x8086, 0x0090, "Intel Centrino Advanced-N 6230"		},
+	{ 0x8086, 0x0091, "Intel Centrino Advanced-N 6230"		},
+	{ 0x8086, 0x0885, "Intel Centrino Wireless-N + WiMAX 6150"	},
+	{ 0x8086, 0x0886, "Intel Centrino Wireless-N + WiMAX 6150"	},
+	{ 0x8086, 0x0896, "Intel Centrino Wireless-N 130"		},
+	{ 0x8086, 0x4229, "Intel Wireless WiFi Link 4965"		},
+	{ 0x8086, 0x422b, "Intel Centrino Ultimate-N 6300"		},
+	{ 0x8086, 0x422c, "Intel Centrino Advanced-N 6200"		},
+	{ 0x8086, 0x422d, "Intel Wireless WiFi Link 4965"		},
+	{ 0x8086, 0x4230, "Intel Wireless WiFi Link 4965"		},
+	{ 0x8086, 0x4232, "Intel WiFi Link 5100"			},
+	{ 0x8086, 0x4233, "Intel Wireless WiFi Link 4965"		},
+	{ 0x8086, 0x4235, "Intel Ultimate N WiFi Link 5300"		},
+	{ 0x8086, 0x4236, "Intel Ultimate N WiFi Link 5300"		},
+	{ 0x8086, 0x4237, "Intel WiFi Link 5100"			},
+	{ 0x8086, 0x4238, "Intel Centrino Ultimate-N 6300"		},
+	{ 0x8086, 0x4239, "Intel Centrino Advanced-N 6200"		},
+	{ 0x8086, 0x423a, "Intel WiMAX/WiFi Link 5350"			},
+	{ 0x8086, 0x423b, "Intel WiMAX/WiFi Link 5350"			},
+	{ 0x8086, 0x423c, "Intel WiMAX/WiFi Link 5150"			},
+	{ 0x8086, 0x423d, "Intel WiMAX/WiFi Link 5150"			},
 	{ 0, 0, NULL }
 };
=20
@@ -945,13 +947,9 @@
 iwn_suspend(device_t dev)
 {
 	struct iwn_softc *sc =3D device_get_softc(dev);
-	struct ifnet *ifp =3D sc->sc_ifp;
-	struct ieee80211com *ic =3D ifp->if_l2com;
-	struct ieee80211vap *vap =3D TAILQ_FIRST(&ic->ic_vaps);
-
-	iwn_stop(sc);
-	if (vap !=3D NULL)
-		ieee80211_stop(vap);
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
+
+	ieee80211_suspend_all(ic);
 	return 0;
 }
=20
@@ -959,20 +957,12 @@
 iwn_resume(device_t dev)
 {
 	struct iwn_softc *sc =3D device_get_softc(dev);
-	struct ifnet *ifp =3D sc->sc_ifp;
-	struct ieee80211com *ic =3D ifp->if_l2com;
-	struct ieee80211vap *vap =3D TAILQ_FIRST(&ic->ic_vaps);
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
=20
 	/* Clear device-specific "PCI retry timeout" register (41h). */
 	pci_write_config(dev, 0x41, 0, 1);
=20
-	if (ifp->if_flags & IFF_UP) {
-		iwn_init(sc);
-		if (vap !=3D NULL)
-			ieee80211_init(vap);
-		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
-			iwn_start(ifp);
-	}
+	ieee80211_resume_all(ic);
 	return 0;
 }
=20
@@ -2455,7 +2445,7 @@
=20
 	txq =3D &sc->txq[le16toh(ba->qid)];
 	tap =3D sc->qid2tap[le16toh(ba->qid)];
-	tid =3D WME_AC_TO_TID(tap->txa_ac);
+	tid =3D tap->txa_tid;
 	ni =3D tap->txa_ni;
 	wn =3D (void *)ni;
=20
@@ -2814,7 +2804,7 @@
 	}
 	tap =3D sc->qid2tap[qid];
 	if (tap !=3D NULL) {
-		tid =3D WME_AC_TO_TID(tap->txa_ac);
+		tid =3D tap->txa_tid;
 		wn =3D (void *)tap->txa_ni;
 		wn->agg[tid].bitmap =3D bitmap;
 		wn->agg[tid].startidx =3D start;
@@ -3318,18 +3308,15 @@
 		tid =3D 0;
 	}
 	ac =3D M_WME_GETAC(m);
-
-	if (IEEE80211_QOS_HAS_SEQ(wh) &&
-	    IEEE80211_AMPDU_RUNNING(&ni->ni_tx_ampdu[ac])) {
+	if (m->m_flags & M_AMPDU_MPDU) {
 		struct ieee80211_tx_ampdu *tap =3D &ni->ni_tx_ampdu[ac];
=20
-		ring =3D &sc->txq[*(int *)tap->txa_private];
+		ac =3D *(int *)tap->txa_private;
 		*(uint16_t *)wh->i_seq =3D
 		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
 		ni->ni_txseqs[tid]++;
-	} else {
-		ring =3D &sc->txq[ac];
-	}
+	}
+	ring =3D &sc->txq[ac];
 	desc =3D &ring->desc[ring->cur];
 	data =3D &ring->data[ring->cur];
=20
@@ -5598,7 +5585,7 @@
 {
 	struct iwn_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
 	int qid =3D *(int *)tap->txa_private;
-	uint8_t tid =3D WME_AC_TO_TID(tap->txa_ac);
+	uint8_t tid =3D tap->txa_tid;
 	int ret;
=20
 	if (code =3D=3D IEEE80211_STATUS_SUCCESS) {
@@ -5622,7 +5609,7 @@
 iwn_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
     uint8_t tid)
 {
-	struct ieee80211_tx_ampdu *tap =3D &ni->ni_tx_ampdu[TID_TO_WME_AC(tid)];
+	struct ieee80211_tx_ampdu *tap =3D &ni->ni_tx_ampdu[tid];
 	struct iwn_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
 	struct iwn_ops *ops =3D &sc->ops;
 	struct iwn_node *wn =3D (void *)ni;
@@ -5655,7 +5642,7 @@
 {
 	struct iwn_softc *sc =3D ni->ni_ic->ic_ifp->if_softc;
 	struct iwn_ops *ops =3D &sc->ops;
-	uint8_t tid =3D WME_AC_TO_TID(tap->txa_ac);
+	uint8_t tid =3D tap->txa_tid;
 	int qid;
=20
 	if (tap->txa_private =3D=3D NULL)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/ixgbe/ixgbe.c
--- a/head/sys/dev/ixgbe/ixgbe.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/ixgbe/ixgbe.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
=20
 **************************************************************************=
****/
-/*$FreeBSD: head/sys/dev/ixgbe/ixgbe.c 232874 2012-03-12 18:15:08Z scottl =
$*/
+/*$FreeBSD: head/sys/dev/ixgbe/ixgbe.c 234229 2012-04-13 16:42:54Z luigi $=
*/
=20
 #ifdef HAVE_KERNEL_OPTION_HEADERS
 #include "opt_inet.h"
@@ -1143,6 +1143,14 @@
 		txdctl |=3D IXGBE_TXDCTL_ENABLE;
 		/* Set WTHRESH to 8, burst writeback */
 		txdctl |=3D (8 << 16);
+		/*
+		 * When the internal queue falls below PTHRESH (32),
+		 * start prefetching as long as there are at least
+		 * HTHRESH (1) buffers ready. The values are taken
+		 * from the Intel linux driver 3.8.21.
+		 * Prefetching enables tx line rate even with 1 queue.
+		 */
+		txdctl |=3D (16 << 0) | (1 << 8);
 		IXGBE_WRITE_REG(hw, IXGBE_TXDCTL(i), txdctl);
 	}
=20
@@ -3804,6 +3812,9 @@
=20
 	rdrxctl =3D IXGBE_READ_REG(hw, IXGBE_RDRXCTL);
 	rdrxctl &=3D ~IXGBE_RDRXCTL_RSCFRSTSIZE;
+#ifdef DEV_NETMAP /* crcstrip is optional in netmap */
+	if (adapter->ifp->if_capenable & IFCAP_NETMAP && !ix_crcstrip)
+#endif /* DEV_NETMAP */
 	rdrxctl |=3D IXGBE_RDRXCTL_CRCSTRIP;
 	rdrxctl |=3D IXGBE_RDRXCTL_RSCACKC;
 	IXGBE_WRITE_REG(hw, IXGBE_RDRXCTL, rdrxctl);
@@ -4096,6 +4107,13 @@
 		hlreg |=3D IXGBE_HLREG0_JUMBOEN;
 	else
 		hlreg &=3D ~IXGBE_HLREG0_JUMBOEN;
+#ifdef DEV_NETMAP
+	/* crcstrip is conditional in netmap (in RDRXCTL too ?) */
+	if (ifp->if_capenable & IFCAP_NETMAP && !ix_crcstrip)
+		hlreg &=3D ~IXGBE_HLREG0_RXCRCSTRP;
+	else
+		hlreg |=3D IXGBE_HLREG0_RXCRCSTRP;
+#endif /* DEV_NETMAP */
 	IXGBE_WRITE_REG(hw, IXGBE_HLREG0, hlreg);
=20
 	bufsz =3D (adapter->rx_mbuf_sz +
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfi.c
--- a/head/sys/dev/mfi/mfi.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfi.c	Tue Apr 17 11:51:51 2012 +0300
@@ -51,8 +51,9 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi.c 227562 2011-11-16 15:39:27Z jhb=
 $");
-
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi.c 233711 2012-03-30 23:05:48Z amb=
risko $");
+
+#include "opt_compat.h"
 #include "opt_mfi.h"
=20
 #include <sys/param.h>
@@ -72,6 +73,7 @@
 #include <sys/uio.h>
 #include <sys/proc.h>
 #include <sys/signalvar.h>
+#include <sys/taskqueue.h>
=20
 #include <machine/bus.h>
 #include <machine/resource.h>
@@ -79,10 +81,11 @@
 #include <dev/mfi/mfireg.h>
 #include <dev/mfi/mfi_ioctl.h>
 #include <dev/mfi/mfivar.h>
+#include <sys/interrupt.h>
+#include <sys/priority.h>
=20
 static int	mfi_alloc_commands(struct mfi_softc *);
 static int	mfi_comms_init(struct mfi_softc *);
-static int	mfi_wait_command(struct mfi_softc *, struct mfi_command *);
 static int	mfi_get_controller_info(struct mfi_softc *);
 static int	mfi_get_log_state(struct mfi_softc *,
 		    struct mfi_evt_log_state **);
@@ -93,29 +96,39 @@
 static void	mfi_startup(void *arg);
 static void	mfi_intr(void *arg);
 static void	mfi_ldprobe(struct mfi_softc *sc);
+static void	mfi_syspdprobe(struct mfi_softc *sc);
+static void	mfi_handle_evt(void *context, int pending);
 static int	mfi_aen_register(struct mfi_softc *sc, int seq, int locale);
 static void	mfi_aen_complete(struct mfi_command *);
-static int	mfi_aen_setup(struct mfi_softc *, uint32_t);
 static int	mfi_add_ld(struct mfi_softc *sc, int);
 static void	mfi_add_ld_complete(struct mfi_command *);
+static int	mfi_add_sys_pd(struct mfi_softc *sc, int);
+static void	mfi_add_sys_pd_complete(struct mfi_command *);
 static struct mfi_command * mfi_bio_command(struct mfi_softc *);
 static void	mfi_bio_complete(struct mfi_command *);
-static int	mfi_mapcmd(struct mfi_softc *, struct mfi_command *);
+static struct mfi_command *mfi_build_ldio(struct mfi_softc *,struct bio*);
+static struct mfi_command *mfi_build_syspdio(struct mfi_softc *,struct bio=
*);
 static int	mfi_send_frame(struct mfi_softc *, struct mfi_command *);
-static void	mfi_complete(struct mfi_softc *, struct mfi_command *);
 static int	mfi_abort(struct mfi_softc *, struct mfi_command *);
 static int	mfi_linux_ioctl_int(struct cdev *, u_long, caddr_t, int, struct=
 thread *);
 static void	mfi_timeout(void *);
 static int	mfi_user_command(struct mfi_softc *,
 		    struct mfi_ioc_passthru *);
-static void 	mfi_enable_intr_xscale(struct mfi_softc *sc);
-static void 	mfi_enable_intr_ppc(struct mfi_softc *sc);
-static int32_t 	mfi_read_fw_status_xscale(struct mfi_softc *sc);
-static int32_t 	mfi_read_fw_status_ppc(struct mfi_softc *sc);
-static int 	mfi_check_clear_intr_xscale(struct mfi_softc *sc);
-static int 	mfi_check_clear_intr_ppc(struct mfi_softc *sc);
-static void 	mfi_issue_cmd_xscale(struct mfi_softc *sc,uint32_t bus_add,ui=
nt32_t frame_cnt);
-static void 	mfi_issue_cmd_ppc(struct mfi_softc *sc,uint32_t bus_add,uint3=
2_t frame_cnt);
+static void	mfi_enable_intr_xscale(struct mfi_softc *sc);
+static void	mfi_enable_intr_ppc(struct mfi_softc *sc);
+static int32_t	mfi_read_fw_status_xscale(struct mfi_softc *sc);
+static int32_t	mfi_read_fw_status_ppc(struct mfi_softc *sc);
+static int	mfi_check_clear_intr_xscale(struct mfi_softc *sc);
+static int	mfi_check_clear_intr_ppc(struct mfi_softc *sc);
+static void 	mfi_issue_cmd_xscale(struct mfi_softc *sc, bus_addr_t bus_add,
+		    uint32_t frame_cnt);
+static void 	mfi_issue_cmd_ppc(struct mfi_softc *sc, bus_addr_t bus_add,
+		    uint32_t frame_cnt);
+static int mfi_config_lock(struct mfi_softc *sc, uint32_t opcode);
+static void mfi_config_unlock(struct mfi_softc *sc, int locked);
+static int mfi_check_command_pre(struct mfi_softc *sc, struct mfi_command =
*cm);
+static void mfi_check_command_post(struct mfi_softc *sc, struct mfi_comman=
d *cm);
+static int mfi_check_for_sscd(struct mfi_softc *sc, struct mfi_command *cm=
);
=20
 SYSCTL_NODE(_hw, OID_AUTO, mfi, CTLFLAG_RD, 0, "MFI driver parameters");
 static int	mfi_event_locale =3D MFI_EVT_LOCALE_ALL;
@@ -133,6 +146,11 @@
 SYSCTL_INT(_hw_mfi, OID_AUTO, max_cmds, CTLFLAG_RD, &mfi_max_cmds,
 	   0, "Max commands");
=20
+static int	mfi_detect_jbod_change =3D 1;
+TUNABLE_INT("hw.mfi.detect_jbod_change", &mfi_detect_jbod_change);
+SYSCTL_INT(_hw_mfi, OID_AUTO, detect_jbod_change, CTLFLAG_RW,
+	   &mfi_detect_jbod_change, 0, "Detect a change to a JBOD");
+
 /* Management interface */
 static d_open_t		mfi_open;
 static d_close_t	mfi_close;
@@ -152,6 +170,7 @@
 MALLOC_DEFINE(M_MFIBUF, "mfibuf", "Buffers for the MFI driver");
=20
 #define MFI_INQ_LENGTH SHORT_INQUIRY_LENGTH
+struct mfi_skinny_dma_info mfi_skinny;
=20
 static void
 mfi_enable_intr_xscale(struct mfi_softc *sc)
@@ -162,12 +181,17 @@
 static void
 mfi_enable_intr_ppc(struct mfi_softc *sc)
 {
-	MFI_WRITE4(sc, MFI_ODCR0, 0xFFFFFFFF);
 	if (sc->mfi_flags & MFI_FLAGS_1078) {
+		MFI_WRITE4(sc, MFI_ODCR0, 0xFFFFFFFF);
 		MFI_WRITE4(sc, MFI_OMSK, ~MFI_1078_EIM);
-	} else if (sc->mfi_flags & MFI_FLAGS_GEN2) {
+	}
+	else if (sc->mfi_flags & MFI_FLAGS_GEN2) {
+		MFI_WRITE4(sc, MFI_ODCR0, 0xFFFFFFFF);
 		MFI_WRITE4(sc, MFI_OMSK, ~MFI_GEN2_EIM);
 	}
+	else if (sc->mfi_flags & MFI_FLAGS_SKINNY) {
+		MFI_WRITE4(sc, MFI_OMSK, ~0x00000001);
+	}
 }
=20
 static int32_t
@@ -205,35 +229,51 @@
 		if (!(status & MFI_1078_RM)) {
 			return 1;
 		}
-	} else if (sc->mfi_flags & MFI_FLAGS_GEN2) {
+	}
+	else if (sc->mfi_flags & MFI_FLAGS_GEN2) {
 		if (!(status & MFI_GEN2_RM)) {
 			return 1;
 		}
 	}
-
-	MFI_WRITE4(sc, MFI_ODCR0, status);
+	else if (sc->mfi_flags & MFI_FLAGS_SKINNY) {
+		if (!(status & MFI_SKINNY_RM)) {
+			return 1;
+		}
+	}
+	if (sc->mfi_flags & MFI_FLAGS_SKINNY)
+		MFI_WRITE4(sc, MFI_OSTS, status);
+	else
+		MFI_WRITE4(sc, MFI_ODCR0, status);
 	return 0;
 }
=20
 static void
-mfi_issue_cmd_xscale(struct mfi_softc *sc,uint32_t bus_add,uint32_t frame_=
cnt)
+mfi_issue_cmd_xscale(struct mfi_softc *sc, bus_addr_t bus_add, uint32_t fr=
ame_cnt)
 {
 	MFI_WRITE4(sc, MFI_IQP,(bus_add >>3)|frame_cnt);
 }
=20
 static void
-mfi_issue_cmd_ppc(struct mfi_softc *sc,uint32_t bus_add,uint32_t frame_cnt)
+mfi_issue_cmd_ppc(struct mfi_softc *sc, bus_addr_t bus_add, uint32_t frame=
_cnt)
 {
-	MFI_WRITE4(sc, MFI_IQP, (bus_add |frame_cnt <<1)|1 );
+	if (sc->mfi_flags & MFI_FLAGS_SKINNY) {
+	    MFI_WRITE4(sc, MFI_IQPL, (bus_add | frame_cnt <<1)|1 );
+	    MFI_WRITE4(sc, MFI_IQPH, 0x00000000);
+	} else {
+	    MFI_WRITE4(sc, MFI_IQP, (bus_add | frame_cnt <<1)|1 );
+	}
 }
=20
-static int
+int
 mfi_transition_firmware(struct mfi_softc *sc)
 {
 	uint32_t fw_state, cur_state;
 	int max_wait, i;
-
-	fw_state =3D sc->mfi_read_fw_status(sc)& MFI_FWSTATE_MASK;
+	uint32_t cur_abs_reg_val =3D 0;
+	uint32_t prev_abs_reg_val =3D 0;
+
+	cur_abs_reg_val =3D sc->mfi_read_fw_status(sc);
+	fw_state =3D cur_abs_reg_val & MFI_FWSTATE_MASK;
 	while (fw_state !=3D MFI_FWSTATE_READY) {
 		if (bootverbose)
 			device_printf(sc->mfi_dev, "Waiting for firmware to "
@@ -244,38 +284,60 @@
 			device_printf(sc->mfi_dev, "Firmware fault\n");
 			return (ENXIO);
 		case MFI_FWSTATE_WAIT_HANDSHAKE:
-			MFI_WRITE4(sc, MFI_IDB, MFI_FWINIT_CLEAR_HANDSHAKE);
-			max_wait =3D 2;
+			if (sc->mfi_flags & MFI_FLAGS_SKINNY || sc->mfi_flags & MFI_FLAGS_TBOLT)
+			    MFI_WRITE4(sc, MFI_SKINNY_IDB, MFI_FWINIT_CLEAR_HANDSHAKE);
+			else
+			    MFI_WRITE4(sc, MFI_IDB, MFI_FWINIT_CLEAR_HANDSHAKE);
+			max_wait =3D MFI_RESET_WAIT_TIME;
 			break;
 		case MFI_FWSTATE_OPERATIONAL:
-			MFI_WRITE4(sc, MFI_IDB, MFI_FWINIT_READY);
-			max_wait =3D 10;
+			if (sc->mfi_flags & MFI_FLAGS_SKINNY || sc->mfi_flags & MFI_FLAGS_TBOLT)
+			    MFI_WRITE4(sc, MFI_SKINNY_IDB, 7);
+			else
+			    MFI_WRITE4(sc, MFI_IDB, MFI_FWINIT_READY);
+			max_wait =3D MFI_RESET_WAIT_TIME;
 			break;
 		case MFI_FWSTATE_UNDEFINED:
 		case MFI_FWSTATE_BB_INIT:
-			max_wait =3D 2;
+			max_wait =3D MFI_RESET_WAIT_TIME;
+			break;
+		case MFI_FWSTATE_FW_INIT_2:
+			max_wait =3D MFI_RESET_WAIT_TIME;
 			break;
 		case MFI_FWSTATE_FW_INIT:
+		case MFI_FWSTATE_FLUSH_CACHE:
+			max_wait =3D MFI_RESET_WAIT_TIME;
+			break;
 		case MFI_FWSTATE_DEVICE_SCAN:
-		case MFI_FWSTATE_FLUSH_CACHE:
-			max_wait =3D 20;
+			max_wait =3D MFI_RESET_WAIT_TIME; /* wait for 180 seconds */
+			prev_abs_reg_val =3D cur_abs_reg_val;
 			break;
 		case MFI_FWSTATE_BOOT_MESSAGE_PENDING:
-			MFI_WRITE4(sc, MFI_IDB, MFI_FWINIT_HOTPLUG);
-			max_wait =3D 10;
+			if (sc->mfi_flags & MFI_FLAGS_SKINNY || sc->mfi_flags & MFI_FLAGS_TBOLT)
+			    MFI_WRITE4(sc, MFI_SKINNY_IDB, MFI_FWINIT_HOTPLUG);
+			else
+			    MFI_WRITE4(sc, MFI_IDB, MFI_FWINIT_HOTPLUG);
+			max_wait =3D MFI_RESET_WAIT_TIME;
 			break;
 		default:
-			device_printf(sc->mfi_dev,"Unknown firmware state %#x\n",
+			device_printf(sc->mfi_dev, "Unknown firmware state %#x\n",
 			    fw_state);
 			return (ENXIO);
 		}
 		for (i =3D 0; i < (max_wait * 10); i++) {
-			fw_state =3D sc->mfi_read_fw_status(sc) & MFI_FWSTATE_MASK;
+			cur_abs_reg_val =3D sc->mfi_read_fw_status(sc);
+			fw_state =3D cur_abs_reg_val & MFI_FWSTATE_MASK;
 			if (fw_state =3D=3D cur_state)
 				DELAY(100000);
 			else
 				break;
 		}
+		if (fw_state =3D=3D MFI_FWSTATE_DEVICE_SCAN) {
+			/* Check the device scanning progress */
+			if (prev_abs_reg_val !=3D cur_abs_reg_val) {
+				continue;
+			}
+		}
 		if (fw_state =3D=3D cur_state) {
 			device_printf(sc->mfi_dev, "Firmware stuck in state "
 			    "%#x\n", fw_state);
@@ -286,26 +348,35 @@
 }
=20
 static void
-mfi_addr32_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
+mfi_addr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
 {
-	uint32_t *addr;
+	bus_addr_t *addr;
=20
 	addr =3D arg;
 	*addr =3D segs[0].ds_addr;
 }
=20
+
 int
 mfi_attach(struct mfi_softc *sc)
 {
 	uint32_t status;
 	int error, commsz, framessz, sensesz;
 	int frames, unit, max_fw_sge;
-
-	device_printf(sc->mfi_dev, "Megaraid SAS driver Ver 3.00 \n");
+	uint32_t tb_mem_size =3D 0;
+
+	if (sc =3D=3D NULL)
+		return EINVAL;
+
+	device_printf(sc->mfi_dev, "Megaraid SAS driver Ver %s \n",
+	    MEGASAS_VERSION);
=20
 	mtx_init(&sc->mfi_io_lock, "MFI I/O lock", NULL, MTX_DEF);
 	sx_init(&sc->mfi_config_lock, "MFI config");
 	TAILQ_INIT(&sc->mfi_ld_tqh);
+	TAILQ_INIT(&sc->mfi_syspd_tqh);
+	TAILQ_INIT(&sc->mfi_evt_queue);
+	TASK_INIT(&sc->mfi_evt_task, 0, mfi_handle_evt, sc);
 	TAILQ_INIT(&sc->mfi_aen_pids);
 	TAILQ_INIT(&sc->mfi_cam_ccbq);
=20
@@ -314,15 +385,29 @@
 	mfi_initq_busy(sc);
 	mfi_initq_bio(sc);
=20
+	sc->adpreset =3D 0;
+	sc->last_seq_num =3D 0;
+	sc->disableOnlineCtrlReset =3D 1;
+	sc->issuepend_done =3D 1;
+	sc->hw_crit_error =3D 0;
+
 	if (sc->mfi_flags & MFI_FLAGS_1064R) {
 		sc->mfi_enable_intr =3D mfi_enable_intr_xscale;
 		sc->mfi_read_fw_status =3D mfi_read_fw_status_xscale;
 		sc->mfi_check_clear_intr =3D mfi_check_clear_intr_xscale;
 		sc->mfi_issue_cmd =3D mfi_issue_cmd_xscale;
-	}
-	else {
+	} else if (sc->mfi_flags & MFI_FLAGS_TBOLT) {
+		sc->mfi_enable_intr =3D mfi_tbolt_enable_intr_ppc;
+		sc->mfi_disable_intr =3D mfi_tbolt_disable_intr_ppc;
+		sc->mfi_read_fw_status =3D mfi_tbolt_read_fw_status_ppc;
+		sc->mfi_check_clear_intr =3D mfi_tbolt_check_clear_intr_ppc;
+		sc->mfi_issue_cmd =3D mfi_tbolt_issue_cmd_ppc;
+		sc->mfi_adp_reset =3D mfi_tbolt_adp_reset;
+		sc->mfi_tbolt =3D 1;
+		TAILQ_INIT(&sc->mfi_cmd_tbolt_tqh);
+	} else {
 		sc->mfi_enable_intr =3D  mfi_enable_intr_ppc;
- 		sc->mfi_read_fw_status =3D mfi_read_fw_status_ppc;
+		sc->mfi_read_fw_status =3D mfi_read_fw_status_ppc;
 		sc->mfi_check_clear_intr =3D mfi_check_clear_intr_ppc;
 		sc->mfi_issue_cmd =3D mfi_issue_cmd_ppc;
 	}
@@ -335,6 +420,32 @@
 		return (ENXIO);
 	}
=20
+	/* Start: LSIP200113393 */
+	if (bus_dma_tag_create( sc->mfi_parent_dmat,	/* parent */
+				1, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+				MEGASAS_MAX_NAME*sizeof(bus_addr_t),			/* maxsize */
+				1,			/* msegments */
+				MEGASAS_MAX_NAME*sizeof(bus_addr_t),			/* maxsegsize */
+				0,			/* flags */
+				NULL, NULL,		/* lockfunc, lockarg */
+				&sc->verbuf_h_dmat)) {
+		device_printf(sc->mfi_dev, "Cannot allocate verbuf_h_dmat DMA tag\n");
+		return (ENOMEM);
+	}
+	if (bus_dmamem_alloc(sc->verbuf_h_dmat, (void **)&sc->verbuf,
+	    BUS_DMA_NOWAIT, &sc->verbuf_h_dmamap)) {
+		device_printf(sc->mfi_dev, "Cannot allocate verbuf_h_dmamap memory\n");
+		return (ENOMEM);
+	}
+	bzero(sc->verbuf, MEGASAS_MAX_NAME*sizeof(bus_addr_t));
+	bus_dmamap_load(sc->verbuf_h_dmat, sc->verbuf_h_dmamap,
+	    sc->verbuf, MEGASAS_MAX_NAME*sizeof(bus_addr_t),
+	    mfi_addr_cb, &sc->verbuf_h_busaddr, 0);
+	/* End: LSIP200113393 */
+
 	/*
 	 * Get information needed for sizing the contiguous memory for the
 	 * frame pool.  Size down the sgl parameter since we know that
@@ -347,6 +458,100 @@
 	max_fw_sge =3D (status & MFI_FWSTATE_MAXSGL_MASK) >> 16;
 	sc->mfi_max_sge =3D min(max_fw_sge, ((MFI_MAXPHYS / PAGE_SIZE) + 1));
=20
+	/* ThunderBolt Support get the contiguous memory */
+
+	if (sc->mfi_flags & MFI_FLAGS_TBOLT) {
+		mfi_tbolt_init_globals(sc);
+		device_printf(sc->mfi_dev, "MaxCmd =3D %x MaxSgl =3D %x state =3D %x \n",
+		    sc->mfi_max_fw_cmds, sc->mfi_max_sge, status);
+		tb_mem_size =3D mfi_tbolt_get_memory_requirement(sc);
+
+		if (bus_dma_tag_create( sc->mfi_parent_dmat,	/* parent */
+				1, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+				tb_mem_size,		/* maxsize */
+				1,			/* msegments */
+				tb_mem_size,		/* maxsegsize */
+				0,			/* flags */
+				NULL, NULL,		/* lockfunc, lockarg */
+				&sc->mfi_tb_dmat)) {
+			device_printf(sc->mfi_dev, "Cannot allocate comms DMA tag\n");
+			return (ENOMEM);
+		}
+		if (bus_dmamem_alloc(sc->mfi_tb_dmat, (void **)&sc->request_message_pool,
+		BUS_DMA_NOWAIT, &sc->mfi_tb_dmamap)) {
+			device_printf(sc->mfi_dev, "Cannot allocate comms memory\n");
+			return (ENOMEM);
+		}
+		bzero(sc->request_message_pool, tb_mem_size);
+		bus_dmamap_load(sc->mfi_tb_dmat, sc->mfi_tb_dmamap,
+		sc->request_message_pool, tb_mem_size, mfi_addr_cb, &sc->mfi_tb_busaddr,=
 0);
+
+		/* For ThunderBolt memory init */
+		if (bus_dma_tag_create( sc->mfi_parent_dmat,	/* parent */
+				0x100, 0,		/* alignmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+				MFI_FRAME_SIZE,		/* maxsize */
+				1,			/* msegments */
+				MFI_FRAME_SIZE,		/* maxsegsize */
+				0,			/* flags */
+				NULL, NULL,		/* lockfunc, lockarg */
+				&sc->mfi_tb_init_dmat)) {
+		device_printf(sc->mfi_dev, "Cannot allocate init DMA tag\n");
+		return (ENOMEM);
+		}
+		if (bus_dmamem_alloc(sc->mfi_tb_init_dmat, (void **)&sc->mfi_tb_init,
+		    BUS_DMA_NOWAIT, &sc->mfi_tb_init_dmamap)) {
+			device_printf(sc->mfi_dev, "Cannot allocate init memory\n");
+			return (ENOMEM);
+		}
+		bzero(sc->mfi_tb_init, MFI_FRAME_SIZE);
+		bus_dmamap_load(sc->mfi_tb_init_dmat, sc->mfi_tb_init_dmamap,
+		sc->mfi_tb_init, MFI_FRAME_SIZE, mfi_addr_cb,
+		    &sc->mfi_tb_init_busaddr, 0);
+		if (mfi_tbolt_init_desc_pool(sc, sc->request_message_pool,
+		    tb_mem_size)) {
+			device_printf(sc->mfi_dev,
+			    "Thunderbolt pool preparation error\n");
+			return 0;
+		}
+
+		/*
+		  Allocate DMA memory mapping for MPI2 IOC Init descriptor,
+		  we are taking it diffrent from what we have allocated for Request
+		  and reply descriptors to avoid confusion later
+		*/
+		tb_mem_size =3D sizeof(struct MPI2_IOC_INIT_REQUEST);
+		if (bus_dma_tag_create( sc->mfi_parent_dmat,	/* parent */
+				1, 0,			/* algnmnt, boundary */
+				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+				BUS_SPACE_MAXADDR,	/* highaddr */
+				NULL, NULL,		/* filter, filterarg */
+				tb_mem_size,		/* maxsize */
+				1,			/* msegments */
+				tb_mem_size,		/* maxsegsize */
+				0,			/* flags */
+				NULL, NULL,		/* lockfunc, lockarg */
+				&sc->mfi_tb_ioc_init_dmat)) {
+			device_printf(sc->mfi_dev,
+			    "Cannot allocate comms DMA tag\n");
+			return (ENOMEM);
+		}
+		if (bus_dmamem_alloc(sc->mfi_tb_ioc_init_dmat,
+		    (void **)&sc->mfi_tb_ioc_init_desc,
+		    BUS_DMA_NOWAIT, &sc->mfi_tb_ioc_init_dmamap)) {
+			device_printf(sc->mfi_dev, "Cannot allocate comms memory\n");
+			return (ENOMEM);
+		}
+		bzero(sc->mfi_tb_ioc_init_desc, tb_mem_size);
+		bus_dmamap_load(sc->mfi_tb_ioc_init_dmat, sc->mfi_tb_ioc_init_dmamap,
+		sc->mfi_tb_ioc_init_desc, tb_mem_size, mfi_addr_cb,
+		    &sc->mfi_tb_ioc_init_busaddr, 0);
+	}
 	/*
 	 * Create the dma tag for data buffers.  Used both for block I/O
 	 * and for various internal data queries.
@@ -396,8 +601,7 @@
 	}
 	bzero(sc->mfi_comms, commsz);
 	bus_dmamap_load(sc->mfi_comms_dmat, sc->mfi_comms_dmamap,
-	    sc->mfi_comms, commsz, mfi_addr32_cb, &sc->mfi_comms_busaddr, 0);
-
+	    sc->mfi_comms, commsz, mfi_addr_cb, &sc->mfi_comms_busaddr, 0);
 	/*
 	 * Allocate DMA memory for the command frames.  Keep them in the
 	 * lower 4GB for efficiency.  Calculate the size of the commands at
@@ -414,6 +618,8 @@
 	} else {
 		sc->mfi_sge_size =3D sizeof(struct mfi_sg32);
 	}
+	if (sc->mfi_flags & MFI_FLAGS_SKINNY)
+		sc->mfi_sge_size =3D sizeof(struct mfi_sg_skinny);
 	frames =3D (sc->mfi_sge_size * sc->mfi_max_sge - 1) / MFI_FRAME_SIZE + 2;
 	sc->mfi_cmd_size =3D frames * MFI_FRAME_SIZE;
 	framessz =3D sc->mfi_cmd_size * sc->mfi_max_fw_cmds;
@@ -438,8 +644,7 @@
 	}
 	bzero(sc->mfi_frames, framessz);
 	bus_dmamap_load(sc->mfi_frames_dmat, sc->mfi_frames_dmamap,
-	    sc->mfi_frames, framessz, mfi_addr32_cb, &sc->mfi_frames_busaddr,0);
-
+	    sc->mfi_frames, framessz, mfi_addr_cb, &sc->mfi_frames_busaddr,0);
 	/*
 	 * Allocate DMA memory for the frame sense data.  Keep them in the
 	 * lower 4GB for efficiency
@@ -465,32 +670,47 @@
 		return (ENOMEM);
 	}
 	bus_dmamap_load(sc->mfi_sense_dmat, sc->mfi_sense_dmamap,
-	    sc->mfi_sense, sensesz, mfi_addr32_cb, &sc->mfi_sense_busaddr, 0);
-
+	    sc->mfi_sense, sensesz, mfi_addr_cb, &sc->mfi_sense_busaddr, 0);
 	if ((error =3D mfi_alloc_commands(sc)) !=3D 0)
 		return (error);
=20
-	if ((error =3D mfi_comms_init(sc)) !=3D 0)
-		return (error);
-
+	/* Before moving the FW to operational state, check whether
+	 * hostmemory is required by the FW or not
+	 */
+
+	/* ThunderBolt MFI_IOC2 INIT */
+	if (sc->mfi_flags & MFI_FLAGS_TBOLT) {
+		sc->mfi_disable_intr(sc);
+		if ((error =3D mfi_tbolt_init_MFI_queue(sc)) !=3D 0) {
+			device_printf(sc->mfi_dev,
+			    "TB Init has failed with error %d\n",error);
+			return error;
+		}
+
+		if ((error =3D mfi_tbolt_alloc_cmd(sc)) !=3D 0)
+			return error;
+		if (bus_setup_intr(sc->mfi_dev, sc->mfi_irq,
+		    INTR_MPSAFE|INTR_TYPE_BIO, NULL, mfi_intr_tbolt, sc,
+		    &sc->mfi_intr)) {
+			device_printf(sc->mfi_dev, "Cannot set up interrupt\n");
+			return (EINVAL);
+		}
+		sc->mfi_enable_intr(sc);
+		sc->map_id =3D 0;
+	} else {
+		if ((error =3D mfi_comms_init(sc)) !=3D 0)
+			return (error);
+
+		if (bus_setup_intr(sc->mfi_dev, sc->mfi_irq,
+		    INTR_MPSAFE|INTR_TYPE_BIO, NULL, mfi_intr, sc, &sc->mfi_intr)) {
+			device_printf(sc->mfi_dev, "Cannot set up interrupt\n");
+			return (EINVAL);
+		}
+		sc->mfi_enable_intr(sc);
+	}
 	if ((error =3D mfi_get_controller_info(sc)) !=3D 0)
 		return (error);
-
-	mtx_lock(&sc->mfi_io_lock);
-	if ((error =3D mfi_aen_setup(sc, 0), 0) !=3D 0) {
-		mtx_unlock(&sc->mfi_io_lock);
-		return (error);
-	}
-	mtx_unlock(&sc->mfi_io_lock);
-
-	/*
-	 * Set up the interrupt handler.
-	 */
-	if (bus_setup_intr(sc->mfi_dev, sc->mfi_irq, INTR_MPSAFE|INTR_TYPE_BIO,
-	    NULL, mfi_intr, sc, &sc->mfi_intr)) {
-		device_printf(sc->mfi_dev, "Cannot set up interrupt\n");
-		return (EINVAL);
-	}
+	sc->disableOnlineCtrlReset =3D 0;
=20
 	/* Register a config hook to probe the bus for arrays */
 	sc->mfi_ich.ich_func =3D mfi_startup;
@@ -500,6 +720,10 @@
 		    "hook\n");
 		return (EINVAL);
 	}
+	if ((error =3D mfi_aen_setup(sc, 0), 0) !=3D 0) {
+		mtx_unlock(&sc->mfi_io_lock);
+		return (error);
+	}
=20
 	/*
 	 * Register a shutdown handler.
@@ -571,8 +795,11 @@
 		cm->cm_sc =3D sc;
 		cm->cm_index =3D i;
 		if (bus_dmamap_create(sc->mfi_buffer_dmat, 0,
-		    &cm->cm_dmamap) =3D=3D 0)
+		    &cm->cm_dmamap) =3D=3D 0) {
+			mtx_lock(&sc->mfi_io_lock);
 			mfi_release_command(cm);
+			mtx_unlock(&sc->mfi_io_lock);
+		}
 		else
 			break;
 		sc->mfi_total_cmds++;
@@ -587,6 +814,8 @@
 	struct mfi_frame_header *hdr;
 	uint32_t *hdr_data;
=20
+	mtx_assert(&cm->cm_sc->mfi_io_lock, MA_OWNED);
+
 	/*
 	 * Zero out the important fields of the frame, but make sure the
 	 * context field is preserved.  For efficiency, handle the fields
@@ -611,24 +840,31 @@
 	cm->cm_data =3D NULL;
 	cm->cm_sg =3D 0;
 	cm->cm_total_frame_size =3D 0;
+	cm->retry_for_fw_reset =3D 0;
=20
 	mfi_enqueue_free(cm);
 }
=20
 static int
-mfi_dcmd_command(struct mfi_softc *sc, struct mfi_command **cmp, uint32_t =
opcode,
-    void **bufp, size_t bufsize)
+mfi_dcmd_command(struct mfi_softc *sc, struct mfi_command **cmp,
+    uint32_t opcode, void **bufp, size_t bufsize)
 {
 	struct mfi_command *cm;
 	struct mfi_dcmd_frame *dcmd;
 	void *buf =3D NULL;
-=09
+	uint32_t context =3D 0;
+
 	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
-=09
+
 	cm =3D mfi_dequeue_free(sc);
 	if (cm =3D=3D NULL)
 		return (EBUSY);
=20
+	/* Zero out the MFI frame */
+	context =3D cm->cm_frame->header.context;
+	bzero(cm->cm_frame, sizeof(union mfi_frame));
+	cm->cm_frame->header.context =3D context;
+
 	if ((bufsize > 0) && (bufp !=3D NULL)) {
 		if (*bufp =3D=3D NULL) {
 			buf =3D malloc(bufsize, M_MFIBUF, M_NOWAIT|M_ZERO);
@@ -648,6 +884,7 @@
 	dcmd->header.timeout =3D 0;
 	dcmd->header.flags =3D 0;
 	dcmd->header.data_len =3D bufsize;
+	dcmd->header.scsi_status =3D 0;
 	dcmd->opcode =3D opcode;
 	cm->cm_sg =3D &dcmd->sgl;
 	cm->cm_total_frame_size =3D MFI_DCMD_FRAME_SIZE;
@@ -669,11 +906,17 @@
 	struct mfi_init_frame *init;
 	struct mfi_init_qinfo *qinfo;
 	int error;
+	uint32_t context =3D 0;
=20
 	mtx_lock(&sc->mfi_io_lock);
 	if ((cm =3D mfi_dequeue_free(sc)) =3D=3D NULL)
 		return (EBUSY);
=20
+	/* Zero out the MFI frame */
+	context =3D cm->cm_frame->header.context;
+	bzero(cm->cm_frame, sizeof(union mfi_frame));
+	cm->cm_frame->header.context =3D context;
+
 	/*
 	 * Abuse the SG list area of the frame to hold the init_qinfo
 	 * object;
@@ -734,9 +977,11 @@
 	    BUS_DMASYNC_POSTREAD);
 	bus_dmamap_unload(sc->mfi_buffer_dmat, cm->cm_dmamap);
=20
-	max_sectors_1 =3D (1 << ci->stripe_sz_ops.min) * ci->max_strips_per_io;
+	max_sectors_1 =3D (1 << ci->stripe_sz_ops.max) * ci->max_strips_per_io;
 	max_sectors_2 =3D ci->max_request_size;
 	sc->mfi_max_io =3D min(max_sectors_1, max_sectors_2);
+	sc->disableOnlineCtrlReset =3D
+	    ci->properties.OnOffProperties.disableOnlineCtrlReset;
=20
 out:
 	if (ci)
@@ -753,6 +998,7 @@
 	struct mfi_command *cm =3D NULL;
 	int error;
=20
+	mtx_lock(&sc->mfi_io_lock);
 	error =3D mfi_dcmd_command(sc, &cm, MFI_DCMD_CTRL_EVENT_GETINFO,
 	    (void **)log_state, sizeof(**log_state));
 	if (error)
@@ -771,11 +1017,12 @@
 out:
 	if (cm)
 		mfi_release_command(cm);
+	mtx_unlock(&sc->mfi_io_lock);
=20
 	return (error);
 }
=20
-static int
+int
 mfi_aen_setup(struct mfi_softc *sc, uint32_t seq_start)
 {
 	struct mfi_evt_log_state *log_state =3D NULL;
@@ -789,6 +1036,7 @@
=20
 	if (seq_start =3D=3D 0) {
 		error =3D mfi_get_log_state(sc, &log_state);
+		sc->mfi_boot_seq_num =3D log_state->boot_seq_num;
 		if (error) {
 			if (log_state)
 				free(log_state, M_MFIBUF);
@@ -810,7 +1058,7 @@
 	return 0;
 }
=20
-static int
+int
 mfi_wait_command(struct mfi_softc *sc, struct mfi_command *cm)
 {
=20
@@ -883,6 +1131,64 @@
 	if (sc->mfi_comms_dmat !=3D NULL)
 		bus_dma_tag_destroy(sc->mfi_comms_dmat);
=20
+	/* ThunderBolt contiguous memory free here */
+	if (sc->mfi_flags & MFI_FLAGS_TBOLT) {
+		if (sc->mfi_tb_busaddr !=3D 0)
+			bus_dmamap_unload(sc->mfi_tb_dmat, sc->mfi_tb_dmamap);
+		if (sc->request_message_pool !=3D NULL)
+			bus_dmamem_free(sc->mfi_tb_dmat, sc->request_message_pool,
+			    sc->mfi_tb_dmamap);
+		if (sc->mfi_tb_dmat !=3D NULL)
+			bus_dma_tag_destroy(sc->mfi_tb_dmat);
+
+		/* Version buffer memory free */
+		/* Start LSIP200113393 */
+		if (sc->verbuf_h_busaddr !=3D 0)
+			bus_dmamap_unload(sc->verbuf_h_dmat, sc->verbuf_h_dmamap);
+		if (sc->verbuf !=3D NULL)
+			bus_dmamem_free(sc->verbuf_h_dmat, sc->verbuf,
+			    sc->verbuf_h_dmamap);
+		if (sc->verbuf_h_dmat !=3D NULL)
+			bus_dma_tag_destroy(sc->verbuf_h_dmat);
+
+		/* End LSIP200113393 */
+		/* ThunderBolt INIT packet memory Free */
+		if (sc->mfi_tb_init_busaddr !=3D 0)
+			bus_dmamap_unload(sc->mfi_tb_init_dmat, sc->mfi_tb_init_dmamap);
+		if (sc->mfi_tb_init !=3D NULL)
+			bus_dmamem_free(sc->mfi_tb_init_dmat, sc->mfi_tb_init,
+			    sc->mfi_tb_init_dmamap);
+		if (sc->mfi_tb_init_dmat !=3D NULL)
+			bus_dma_tag_destroy(sc->mfi_tb_init_dmat);
+
+		/* ThunderBolt IOC Init Desc memory free here */
+		if (sc->mfi_tb_ioc_init_busaddr !=3D 0)
+			bus_dmamap_unload(sc->mfi_tb_ioc_init_dmat,
+			    sc->mfi_tb_ioc_init_dmamap);
+		if (sc->mfi_tb_ioc_init_desc !=3D NULL)
+			bus_dmamem_free(sc->mfi_tb_ioc_init_dmat,
+			    sc->mfi_tb_ioc_init_desc,
+			    sc->mfi_tb_ioc_init_dmamap);
+		if (sc->mfi_tb_ioc_init_dmat !=3D NULL)
+			bus_dma_tag_destroy(sc->mfi_tb_ioc_init_dmat);
+		for (int i =3D 0; i < sc->mfi_max_fw_cmds; i++) {
+			if (sc->mfi_cmd_pool_tbolt !=3D NULL) {
+				if (sc->mfi_cmd_pool_tbolt[i] !=3D NULL) {
+					free(sc->mfi_cmd_pool_tbolt[i],
+					    M_MFIBUF);
+					sc->mfi_cmd_pool_tbolt[i] =3D NULL;
+				}
+			}
+		}
+		if (sc->mfi_cmd_pool_tbolt !=3D NULL) {
+			free(sc->mfi_cmd_pool_tbolt, M_MFIBUF);
+			sc->mfi_cmd_pool_tbolt =3D NULL;
+		}
+		if (sc->request_desc_pool !=3D NULL) {
+			free(sc->request_desc_pool, M_MFIBUF);
+			sc->request_desc_pool =3D NULL;
+		}
+	}
 	if (sc->mfi_buffer_dmat !=3D NULL)
 		bus_dma_tag_destroy(sc->mfi_buffer_dmat);
 	if (sc->mfi_parent_dmat !=3D NULL)
@@ -909,6 +1215,8 @@
 	sx_xlock(&sc->mfi_config_lock);
 	mtx_lock(&sc->mfi_io_lock);
 	mfi_ldprobe(sc);
+	if (sc->mfi_flags & MFI_FLAGS_SKINNY)
+	    mfi_syspdprobe(sc);
 	mtx_unlock(&sc->mfi_io_lock);
 	sx_xunlock(&sc->mfi_config_lock);
 }
@@ -925,12 +1233,7 @@
 	if (sc->mfi_check_clear_intr(sc))
 		return;
=20
-	/*
-	 * Do a dummy read to flush the interrupt ACK that we just performed,
-	 * ensuring that everything is really, truly consistent.
-	 */
-	(void)sc->mfi_read_fw_status(sc);
-
+restart:
 	pi =3D sc->mfi_comms->hw_pi;
 	ci =3D sc->mfi_comms->hw_ci;
 	mtx_lock(&sc->mfi_io_lock);
@@ -955,6 +1258,14 @@
 	mfi_startio(sc);
 	mtx_unlock(&sc->mfi_io_lock);
=20
+	/*
+	 * Dummy read to flush the bus; this ensures that the indexes are up
+	 * to date.  Restart processing if more commands have come it.
+	 */
+	(void)sc->mfi_read_fw_status(sc);
+	if (pi !=3D sc->mfi_comms->hw_pi)
+		goto restart;
+
 	return;
 }
=20
@@ -975,6 +1286,9 @@
 	if (sc->mfi_aen_cm !=3D NULL)
 		mfi_abort(sc, sc->mfi_aen_cm);
=20
+	if (sc->map_update_cmd !=3D NULL)
+		mfi_abort(sc, sc->map_update_cmd);
+
 	dcmd =3D &cm->cm_frame->dcmd;
 	dcmd->header.flags =3D MFI_FRAME_DIR_NONE;
 	cm->cm_flags =3D MFI_CMD_POLLED;
@@ -990,6 +1304,81 @@
 }
=20
 static void
+mfi_syspdprobe(struct mfi_softc *sc)
+{
+	struct mfi_frame_header *hdr;
+	struct mfi_command *cm =3D NULL;
+	struct mfi_pd_list *pdlist =3D NULL;
+	struct mfi_system_pd *syspd, *tmp;
+	int error, i, found;
+
+	sx_assert(&sc->mfi_config_lock, SA_XLOCKED);
+	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
+	/* Add SYSTEM PD's */
+	error =3D mfi_dcmd_command(sc, &cm, MFI_DCMD_PD_LIST_QUERY,
+	    (void **)&pdlist, sizeof(*pdlist));
+	if (error){
+		device_printf(sc->mfi_dev,
+		    "Error while forming SYSTEM PD list\n");
+		goto out;
+	}
+
+	cm->cm_flags =3D MFI_CMD_DATAIN | MFI_CMD_POLLED;
+	cm->cm_frame->dcmd.mbox[0] =3D MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
+	cm->cm_frame->dcmd.mbox[1] =3D 0;
+	if (mfi_mapcmd(sc, cm) !=3D 0) {
+		device_printf(sc->mfi_dev,
+		    "Failed to get syspd device listing\n");
+		goto out;
+	}
+	bus_dmamap_sync(sc->mfi_buffer_dmat,cm->cm_dmamap,
+	    BUS_DMASYNC_POSTREAD);
+	bus_dmamap_unload(sc->mfi_buffer_dmat, cm->cm_dmamap);
+	hdr =3D &cm->cm_frame->header;
+	if (hdr->cmd_status !=3D MFI_STAT_OK) {
+		device_printf(sc->mfi_dev,
+		    "MFI_DCMD_PD_LIST_QUERY failed %x\n", hdr->cmd_status);
+		goto out;
+	}
+	/* Get each PD and add it to the system */
+	for (i =3D 0; i < pdlist->count; i++) {
+		if (pdlist->addr[i].device_id =3D=3D
+		    pdlist->addr[i].encl_device_id)
+			continue;
+		found =3D 0;
+		TAILQ_FOREACH(syspd, &sc->mfi_syspd_tqh, pd_link) {
+			if (syspd->pd_id =3D=3D pdlist->addr[i].device_id)
+				found =3D 1;
+		}
+		if (found =3D=3D 0)
+			mfi_add_sys_pd(sc, pdlist->addr[i].device_id);
+	}
+	/* Delete SYSPD's whose state has been changed */
+	TAILQ_FOREACH_SAFE(syspd, &sc->mfi_syspd_tqh, pd_link, tmp) {
+		found =3D 0;
+		for (i =3D 0; i < pdlist->count; i++) {
+			if (syspd->pd_id =3D=3D pdlist->addr[i].device_id)
+				found =3D 1;
+		}
+		if (found =3D=3D 0) {
+			printf("DELETE\n");
+			mtx_unlock(&sc->mfi_io_lock);
+			mtx_lock(&Giant);
+			device_delete_child(sc->mfi_dev, syspd->pd_dev);
+			mtx_unlock(&Giant);
+			mtx_lock(&sc->mfi_io_lock);
+		}
+	}
+out:
+	if (pdlist)
+	    free(pdlist, M_MFIBUF);
+	if (cm)
+	    mfi_release_command(cm);
+
+	return;
+}
+
+static void
 mfi_ldprobe(struct mfi_softc *sc)
 {
 	struct mfi_frame_header *hdr;
@@ -1083,10 +1472,124 @@
 static void
 mfi_decode_evt(struct mfi_softc *sc, struct mfi_evt_detail *detail)
 {
+	struct mfi_system_pd *syspd =3D NULL;
=20
 	device_printf(sc->mfi_dev, "%d (%s/0x%04x/%s) - %s\n", detail->seq,
 	    format_timestamp(detail->time), detail->evt_class.members.locale,
-	    format_class(detail->evt_class.members.evt_class), detail->descriptio=
n);
+	    format_class(detail->evt_class.members.evt_class),
+	    detail->description);
+
+        /* Don't act on old AEN's or while shutting down */
+        if (detail->seq < sc->mfi_boot_seq_num || sc->mfi_detaching)
+                return;
+
+	switch (detail->arg_type) {
+	case MR_EVT_ARGS_NONE:
+		if (detail->code =3D=3D MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED) {
+		    device_printf(sc->mfi_dev, "HostBus scan raised\n");
+			if (mfi_detect_jbod_change) {
+				/*
+				 * Probe for new SYSPD's and Delete
+				 * invalid SYSPD's
+				 */
+				sx_xlock(&sc->mfi_config_lock);
+				mtx_lock(&sc->mfi_io_lock);
+				mfi_syspdprobe(sc);
+				mtx_unlock(&sc->mfi_io_lock);
+				sx_xunlock(&sc->mfi_config_lock);
+			}
+		}
+		break;
+	case MR_EVT_ARGS_LD_STATE:
+		/* During load time driver reads all the events starting
+		 * from the one that has been logged after shutdown. Avoid
+		 * these old events.
+		 */
+		if (detail->args.ld_state.new_state =3D=3D MFI_LD_STATE_OFFLINE ) {
+			/* Remove the LD */
+			struct mfi_disk *ld;
+			TAILQ_FOREACH(ld, &sc->mfi_ld_tqh, ld_link) {
+				if (ld->ld_id =3D=3D
+				    detail->args.ld_state.ld.target_id)
+					break;
+			}
+			/*
+			Fix: for kernel panics when SSCD is removed
+			KASSERT(ld !=3D NULL, ("volume dissappeared"));
+			*/
+			if (ld !=3D NULL) {
+				mtx_lock(&Giant);
+				device_delete_child(sc->mfi_dev, ld->ld_dev);
+				mtx_unlock(&Giant);
+			}
+		}
+		break;
+	case MR_EVT_ARGS_PD:
+		if (detail->code =3D=3D MR_EVT_PD_REMOVED) {
+			if (mfi_detect_jbod_change) {
+				/*
+				 * If the removed device is a SYSPD then
+				 * delete it
+				 */
+				TAILQ_FOREACH(syspd, &sc->mfi_syspd_tqh,
+				    pd_link) {
+					if (syspd->pd_id =3D=3D
+					    detail->args.pd.device_id) {
+						mtx_lock(&Giant);
+						device_delete_child(
+						    sc->mfi_dev,
+						    syspd->pd_dev);
+						mtx_unlock(&Giant);
+						break;
+					}
+				}
+			}
+		}
+		if (detail->code =3D=3D MR_EVT_PD_INSERTED) {
+			if (mfi_detect_jbod_change) {
+				/* Probe for new SYSPD's */
+				sx_xlock(&sc->mfi_config_lock);
+				mtx_lock(&sc->mfi_io_lock);
+				mfi_syspdprobe(sc);
+				mtx_unlock(&sc->mfi_io_lock);
+				sx_xunlock(&sc->mfi_config_lock);
+			}
+		}
+		break;
+	}
+}
+
+static void
+mfi_queue_evt(struct mfi_softc *sc, struct mfi_evt_detail *detail)
+{
+	struct mfi_evt_queue_elm *elm;
+
+	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
+	elm =3D malloc(sizeof(*elm), M_MFIBUF, M_NOWAIT|M_ZERO);
+	if (elm =3D=3D NULL)
+		return;
+	memcpy(&elm->detail, detail, sizeof(*detail));
+	TAILQ_INSERT_TAIL(&sc->mfi_evt_queue, elm, link);
+	taskqueue_enqueue(taskqueue_swi, &sc->mfi_evt_task);
+}
+
+static void
+mfi_handle_evt(void *context, int pending)
+{
+	TAILQ_HEAD(,mfi_evt_queue_elm) queue;
+	struct mfi_softc *sc;
+	struct mfi_evt_queue_elm *elm;
+
+	sc =3D context;
+	TAILQ_INIT(&queue);
+	mtx_lock(&sc->mfi_io_lock);
+	TAILQ_CONCAT(&queue, &sc->mfi_evt_queue, link);
+	mtx_unlock(&sc->mfi_io_lock);
+	while ((elm =3D TAILQ_FIRST(&queue)) !=3D NULL) {
+		TAILQ_REMOVE(&queue, elm, link);
+		mfi_decode_evt(sc, &elm->detail);
+		free(elm, M_MFIBUF);
+	}
 }
=20
 static int
@@ -1112,12 +1615,16 @@
 			    < current_aen.members.evt_class)
 				current_aen.members.evt_class =3D
 				    prior_aen.members.evt_class;
+			mtx_lock(&sc->mfi_io_lock);
 			mfi_abort(sc, sc->mfi_aen_cm);
+			mtx_unlock(&sc->mfi_io_lock);
 		}
 	}
=20
+	mtx_lock(&sc->mfi_io_lock);
 	error =3D mfi_dcmd_command(sc, &cm, MFI_DCMD_CTRL_EVENT_WAIT,
 	    (void **)&ed, sizeof(*ed));
+	mtx_unlock(&sc->mfi_io_lock);
 	if (error) {
 		goto out;
 	}
@@ -1128,10 +1635,13 @@
 	cm->cm_flags =3D MFI_CMD_DATAIN;
 	cm->cm_complete =3D mfi_aen_complete;
=20
+	sc->last_seq_num =3D seq;
 	sc->mfi_aen_cm =3D cm;
=20
+	mtx_lock(&sc->mfi_io_lock);
 	mfi_enqueue_ready(cm);
 	mfi_startio(sc);
+	mtx_unlock(&sc->mfi_io_lock);
=20
 out:
 	return (error);
@@ -1147,6 +1657,8 @@
 	int seq =3D 0, aborted =3D 0;
=20
 	sc =3D cm->cm_sc;
+	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
+
 	hdr =3D &cm->cm_frame->header;
=20
 	if (sc->mfi_aen_cm =3D=3D NULL)
@@ -1163,13 +1675,10 @@
 			selwakeup(&sc->mfi_select);
 		}
 		detail =3D cm->cm_data;
-		/*
-		 * XXX If this function is too expensive or is recursive, then
-		 * events should be put onto a queue and processed later.
-		 */
-		mfi_decode_evt(sc, detail);
+		mfi_queue_evt(sc, detail);
 		seq =3D detail->seq + 1;
-		TAILQ_FOREACH_SAFE(mfi_aen_entry, &sc->mfi_aen_pids, aen_link, tmp) {
+		TAILQ_FOREACH_SAFE(mfi_aen_entry, &sc->mfi_aen_pids, aen_link,
+		    tmp) {
 			TAILQ_REMOVE(&sc->mfi_aen_pids, mfi_aen_entry,
 			    aen_link);
 			PROC_LOCK(mfi_aen_entry->p);
@@ -1186,7 +1695,9 @@
=20
 	/* set it up again so the driver can catch more events */
 	if (!aborted) {
+		mtx_unlock(&sc->mfi_io_lock);
 		mfi_aen_setup(sc, seq);
+		mtx_lock(&sc->mfi_io_lock);
 	}
 }
=20
@@ -1212,10 +1723,13 @@
 		return (ENOMEM);
=20
 	for (seq =3D start_seq;;) {
+		mtx_lock(&sc->mfi_io_lock);
 		if ((cm =3D mfi_dequeue_free(sc)) =3D=3D NULL) {
 			free(el, M_MFIBUF);
+			mtx_unlock(&sc->mfi_io_lock);
 			return (EBUSY);
 		}
+		mtx_unlock(&sc->mfi_io_lock);
=20
 		dcmd =3D &cm->cm_frame->dcmd;
 		bzero(dcmd->mbox, MFI_MBOX_SIZE);
@@ -1231,29 +1745,38 @@
 		cm->cm_data =3D el;
 		cm->cm_len =3D size;
=20
+		mtx_lock(&sc->mfi_io_lock);
 		if ((error =3D mfi_mapcmd(sc, cm)) !=3D 0) {
 			device_printf(sc->mfi_dev,
 			    "Failed to get controller entries\n");
 			mfi_release_command(cm);
+			mtx_unlock(&sc->mfi_io_lock);
 			break;
 		}
=20
+		mtx_unlock(&sc->mfi_io_lock);
 		bus_dmamap_sync(sc->mfi_buffer_dmat, cm->cm_dmamap,
 		    BUS_DMASYNC_POSTREAD);
 		bus_dmamap_unload(sc->mfi_buffer_dmat, cm->cm_dmamap);
=20
 		if (dcmd->header.cmd_status =3D=3D MFI_STAT_NOT_FOUND) {
+			mtx_lock(&sc->mfi_io_lock);
 			mfi_release_command(cm);
+			mtx_unlock(&sc->mfi_io_lock);
 			break;
 		}
 		if (dcmd->header.cmd_status !=3D MFI_STAT_OK) {
 			device_printf(sc->mfi_dev,
 			    "Error %d fetching controller entries\n",
 			    dcmd->header.cmd_status);
+			mtx_lock(&sc->mfi_io_lock);
 			mfi_release_command(cm);
+			mtx_unlock(&sc->mfi_io_lock);
 			break;
 		}
+		mtx_lock(&sc->mfi_io_lock);
 		mfi_release_command(cm);
+		mtx_unlock(&sc->mfi_io_lock);
=20
 		for (i =3D 0; i < el->count; i++) {
 			/*
@@ -1269,7 +1792,9 @@
 				else if (el->event[i].seq < start_seq)
 					break;
 			}
-			mfi_decode_evt(sc, &el->event[i]);
+			mtx_lock(&sc->mfi_io_lock);
+			mfi_queue_evt(sc, &el->event[i]);
+			mtx_unlock(&sc->mfi_io_lock);
 		}
 		seq =3D el->event[el->count - 1].seq + 1;
 	}
@@ -1306,8 +1831,13 @@
 		free(ld_info, M_MFIBUF);
 		return (0);
 	}
-
-	mfi_add_ld_complete(cm);
+	if (ld_info->ld_config.params.isSSCD !=3D 1)
+		mfi_add_ld_complete(cm);
+	else {
+		mfi_release_command(cm);
+		if (ld_info)		/* SSCD drives ld_info free here */
+			free(ld_info, M_MFIBUF);
+	}
 	return (0);
 }
=20
@@ -1347,22 +1877,183 @@
 	mtx_lock(&sc->mfi_io_lock);
 }
=20
+static int mfi_add_sys_pd(struct mfi_softc *sc, int id)
+{
+	struct mfi_command *cm;
+	struct mfi_dcmd_frame *dcmd =3D NULL;
+	struct mfi_pd_info *pd_info =3D NULL;
+	int error;
+
+	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
+
+	error =3D mfi_dcmd_command(sc, &cm, MFI_DCMD_PD_GET_INFO,
+		(void **)&pd_info, sizeof(*pd_info));
+	if (error) {
+		device_printf(sc->mfi_dev,
+		    "Failed to allocated for MFI_DCMD_PD_GET_INFO %d\n",
+		    error);
+		if (pd_info)
+			free(pd_info, M_MFIBUF);
+		return (error);
+	}
+	cm->cm_flags =3D MFI_CMD_DATAIN | MFI_CMD_POLLED;
+	dcmd =3D &cm->cm_frame->dcmd;
+	dcmd->mbox[0]=3Did;
+	dcmd->header.scsi_status =3D 0;
+	dcmd->header.pad0 =3D 0;
+	if (mfi_mapcmd(sc, cm) !=3D 0) {
+		device_printf(sc->mfi_dev,
+		    "Failed to get physical drive info %d\n", id);
+		free(pd_info, M_MFIBUF);
+		return (0);
+	}
+	bus_dmamap_sync(sc->mfi_buffer_dmat, cm->cm_dmamap,
+	    BUS_DMASYNC_POSTREAD);
+	bus_dmamap_unload(sc->mfi_buffer_dmat, cm->cm_dmamap);
+	mfi_add_sys_pd_complete(cm);
+	return (0);
+}
+
+static void
+mfi_add_sys_pd_complete(struct mfi_command *cm)
+{
+	struct mfi_frame_header *hdr;
+	struct mfi_pd_info *pd_info;
+	struct mfi_softc *sc;
+	device_t child;
+
+	sc =3D cm->cm_sc;
+	hdr =3D &cm->cm_frame->header;
+	pd_info =3D cm->cm_private;
+
+	if (hdr->cmd_status !=3D MFI_STAT_OK) {
+		free(pd_info, M_MFIBUF);
+		mfi_release_command(cm);
+		return;
+	}
+	if (pd_info->fw_state !=3D MFI_PD_STATE_SYSTEM) {
+		device_printf(sc->mfi_dev, "PD=3D%x is not SYSTEM PD\n",
+		    pd_info->ref.v.device_id);
+		free(pd_info, M_MFIBUF);
+		mfi_release_command(cm);
+		return;
+	}
+	mfi_release_command(cm);
+
+	mtx_unlock(&sc->mfi_io_lock);
+	mtx_lock(&Giant);
+	if ((child =3D device_add_child(sc->mfi_dev, "mfisyspd", -1)) =3D=3D NULL=
) {
+		device_printf(sc->mfi_dev, "Failed to add system pd\n");
+		free(pd_info, M_MFIBUF);
+		mtx_unlock(&Giant);
+		mtx_lock(&sc->mfi_io_lock);
+		return;
+	}
+
+	device_set_ivars(child, pd_info);
+	device_set_desc(child, "MFI System PD");
+	bus_generic_attach(sc->mfi_dev);
+	mtx_unlock(&Giant);
+	mtx_lock(&sc->mfi_io_lock);
+}
 static struct mfi_command *
 mfi_bio_command(struct mfi_softc *sc)
 {
+	struct bio *bio;
+	struct mfi_command *cm =3D NULL;
+
+	/*reserving two commands to avoid starvation for IOCTL*/
+	if (sc->mfi_qstat[MFIQ_FREE].q_length < 2){
+		return (NULL);
+	}
+	if ((bio =3D mfi_dequeue_bio(sc)) =3D=3D NULL) {
+		return (NULL);
+	}
+	if ((uintptr_t)bio->bio_driver2 =3D=3D MFI_LD_IO) {
+		cm =3D mfi_build_ldio(sc, bio);
+	} else if ((uintptr_t) bio->bio_driver2 =3D=3D MFI_SYS_PD_IO) {
+		cm =3D mfi_build_syspdio(sc, bio);
+	}
+	if (!cm)
+	    mfi_enqueue_bio(sc, bio);
+	return cm;
+}
+static struct mfi_command *
+mfi_build_syspdio(struct mfi_softc *sc, struct bio *bio)
+{
+	struct mfi_command *cm;
+	struct mfi_pass_frame *pass;
+	int flags =3D 0, blkcount =3D 0;
+	uint32_t context =3D 0;
+
+	if ((cm =3D mfi_dequeue_free(sc)) =3D=3D NULL)
+	    return (NULL);
+
+	/* Zero out the MFI frame */
+ 	context =3D cm->cm_frame->header.context;
+	bzero(cm->cm_frame, sizeof(union mfi_frame));
+	cm->cm_frame->header.context =3D context;
+	pass =3D &cm->cm_frame->pass;
+	bzero(pass->cdb, 16);
+	pass->header.cmd =3D MFI_CMD_PD_SCSI_IO;
+	switch (bio->bio_cmd & 0x03) {
+	case BIO_READ:
+#define SCSI_READ 0x28
+		pass->cdb[0] =3D SCSI_READ;
+		flags =3D MFI_CMD_DATAIN;
+		break;
+	case BIO_WRITE:
+#define SCSI_WRITE 0x2a
+		pass->cdb[0] =3D SCSI_WRITE;
+		flags =3D MFI_CMD_DATAOUT;
+		break;
+	default:
+		panic("Invalid bio command");
+	}
+
+	/* Cheat with the sector length to avoid a non-constant division */
+	blkcount =3D (bio->bio_bcount + MFI_SECTOR_LEN - 1) / MFI_SECTOR_LEN;
+	/* Fill the LBA and Transfer length in CDB */
+	pass->cdb[2] =3D (bio->bio_pblkno & 0xff000000) >> 24;
+	pass->cdb[3] =3D (bio->bio_pblkno & 0x00ff0000) >> 16;
+	pass->cdb[4] =3D (bio->bio_pblkno & 0x0000ff00) >> 8;
+	pass->cdb[5] =3D bio->bio_pblkno & 0x000000ff;
+	pass->cdb[7] =3D (blkcount & 0xff00) >> 8;
+	pass->cdb[8] =3D (blkcount & 0x00ff);
+	pass->header.target_id =3D (uintptr_t)bio->bio_driver1;
+	pass->header.timeout =3D 0;
+	pass->header.flags =3D 0;
+	pass->header.scsi_status =3D 0;
+	pass->header.sense_len =3D MFI_SENSE_LEN;
+	pass->header.data_len =3D bio->bio_bcount;
+	pass->header.cdb_len =3D 10;
+	pass->sense_addr_lo =3D (uint32_t)cm->cm_sense_busaddr;
+	pass->sense_addr_hi =3D (uint32_t)((uint64_t)cm->cm_sense_busaddr >> 32);
+	cm->cm_complete =3D mfi_bio_complete;
+	cm->cm_private =3D bio;
+	cm->cm_data =3D bio->bio_data;
+	cm->cm_len =3D bio->bio_bcount;
+	cm->cm_sg =3D &pass->sgl;
+	cm->cm_total_frame_size =3D MFI_PASS_FRAME_SIZE;
+	cm->cm_flags =3D flags;
+	return (cm);
+}
+
+static struct mfi_command *
+mfi_build_ldio(struct mfi_softc *sc, struct bio *bio)
+{
 	struct mfi_io_frame *io;
 	struct mfi_command *cm;
-	struct bio *bio;
 	int flags, blkcount;
+	uint32_t context =3D 0;
=20
 	if ((cm =3D mfi_dequeue_free(sc)) =3D=3D NULL)
-		return (NULL);
-
-	if ((bio =3D mfi_dequeue_bio(sc)) =3D=3D NULL) {
-		mfi_release_command(cm);
-		return (NULL);
-	}
-
+	    return (NULL);
+
+	/* Zero out the MFI frame */
+	context =3D cm->cm_frame->header.context;
+	bzero(cm->cm_frame, sizeof(union mfi_frame));
+	cm->cm_frame->header.context =3D context;
 	io =3D &cm->cm_frame->io;
 	switch (bio->bio_cmd & 0x03) {
 	case BIO_READ:
@@ -1382,10 +2073,11 @@
 	io->header.target_id =3D (uintptr_t)bio->bio_driver1;
 	io->header.timeout =3D 0;
 	io->header.flags =3D 0;
+	io->header.scsi_status =3D 0;
 	io->header.sense_len =3D MFI_SENSE_LEN;
 	io->header.data_len =3D blkcount;
-	io->sense_addr_lo =3D cm->cm_sense_busaddr;
-	io->sense_addr_hi =3D 0;
+	io->sense_addr_lo =3D (uint32_t)cm->cm_sense_busaddr;
+	io->sense_addr_hi =3D (uint32_t)((uint64_t)cm->cm_sense_busaddr >> 32);
 	io->lba_hi =3D (bio->bio_pblkno & 0xffffffff00000000) >> 32;
 	io->lba_lo =3D bio->bio_pblkno & 0xffffffff;
 	cm->cm_complete =3D mfi_bio_complete;
@@ -1458,14 +2150,14 @@
 	}
 }
=20
-static int
+int
 mfi_mapcmd(struct mfi_softc *sc, struct mfi_command *cm)
 {
 	int error, polled;
=20
 	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
=20
-	if (cm->cm_data !=3D NULL) {
+	if ((cm->cm_data !=3D NULL) && (cm->cm_frame->header.cmd !=3D MFI_CMD_STP=
 )) {
 		polled =3D (cm->cm_flags & MFI_CMD_POLLED) ? BUS_DMA_NOWAIT : 0;
 		error =3D bus_dmamap_load(sc->mfi_buffer_dmat, cm->cm_dmamap,
 		    cm->cm_data, cm->cm_len, mfi_data_cb, cm, polled);
@@ -1474,7 +2166,10 @@
 			return (0);
 		}
 	} else {
-		error =3D mfi_send_frame(sc, cm);
+		if (sc->MFA_enabled)
+			error =3D mfi_tbolt_send_frame(sc, cm);
+		else
+			error =3D mfi_send_frame(sc, cm);
 	}
=20
 	return (error);
@@ -1488,6 +2183,7 @@
 	union mfi_sgl *sgl;
 	struct mfi_softc *sc;
 	int i, j, first, dir;
+	int sge_size;
=20
 	cm =3D (struct mfi_command *)arg;
 	sc =3D cm->cm_sc;
@@ -1500,34 +2196,54 @@
 		mfi_complete(sc, cm);
 		return;
 	}
-
-	j =3D 0;
-	if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP) {
-		first =3D cm->cm_stp_len;
+	/* Use IEEE sgl only for IO's on a SKINNY controller
+	 * For other commands on a SKINNY controller use either
+	 * sg32 or sg64 based on the sizeof(bus_addr_t).
+	 * Also calculate the total frame size based on the type
+	 * of SGL used.
+	 */
+	if (((cm->cm_frame->header.cmd =3D=3D MFI_CMD_PD_SCSI_IO) ||
+	    (cm->cm_frame->header.cmd =3D=3D MFI_CMD_LD_READ) ||
+	    (cm->cm_frame->header.cmd =3D=3D MFI_CMD_LD_WRITE)) &&
+	    (sc->mfi_flags & MFI_FLAGS_SKINNY)) {
+		for (i =3D 0; i < nsegs; i++) {
+			sgl->sg_skinny[i].addr =3D segs[i].ds_addr;
+			sgl->sg_skinny[i].len =3D segs[i].ds_len;
+			sgl->sg_skinny[i].flag =3D 0;
+		}
+		hdr->flags |=3D MFI_FRAME_IEEE_SGL | MFI_FRAME_SGL64;
+		sge_size =3D sizeof(struct mfi_sg_skinny);
+		hdr->sg_count =3D nsegs;
+	} else {
+		j =3D 0;
+		if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP) {
+			first =3D cm->cm_stp_len;
+			if ((sc->mfi_flags & MFI_FLAGS_SG64) =3D=3D 0) {
+				sgl->sg32[j].addr =3D segs[0].ds_addr;
+				sgl->sg32[j++].len =3D first;
+			} else {
+				sgl->sg64[j].addr =3D segs[0].ds_addr;
+				sgl->sg64[j++].len =3D first;
+			}
+		} else
+			first =3D 0;
 		if ((sc->mfi_flags & MFI_FLAGS_SG64) =3D=3D 0) {
-			sgl->sg32[j].addr =3D segs[0].ds_addr;
-			sgl->sg32[j++].len =3D first;
+			for (i =3D 0; i < nsegs; i++) {
+				sgl->sg32[j].addr =3D segs[i].ds_addr + first;
+				sgl->sg32[j++].len =3D segs[i].ds_len - first;
+				first =3D 0;
+			}
 		} else {
-			sgl->sg64[j].addr =3D segs[0].ds_addr;
-			sgl->sg64[j++].len =3D first;
+			for (i =3D 0; i < nsegs; i++) {
+				sgl->sg64[j].addr =3D segs[i].ds_addr + first;
+				sgl->sg64[j++].len =3D segs[i].ds_len - first;
+				first =3D 0;
+			}
+			hdr->flags |=3D MFI_FRAME_SGL64;
 		}
-	} else
-		first =3D 0;
-	if ((sc->mfi_flags & MFI_FLAGS_SG64) =3D=3D 0) {
-		for (i =3D 0; i < nsegs; i++) {
-			sgl->sg32[j].addr =3D segs[i].ds_addr + first;
-			sgl->sg32[j++].len =3D segs[i].ds_len - first;
-			first =3D 0;
-		}
-	} else {
-		for (i =3D 0; i < nsegs; i++) {
-			sgl->sg64[j].addr =3D segs[i].ds_addr + first;
-			sgl->sg64[j++].len =3D segs[i].ds_len - first;
-			first =3D 0;
-		}
-		hdr->flags |=3D MFI_FRAME_SGL64;
+		hdr->sg_count =3D j;
+		sge_size =3D sc->mfi_sge_size;
 	}
-	hdr->sg_count =3D j;
=20
 	dir =3D 0;
 	if (cm->cm_flags & MFI_CMD_DATAIN) {
@@ -1538,8 +2254,6 @@
 		dir |=3D BUS_DMASYNC_PREWRITE;
 		hdr->flags |=3D MFI_FRAME_DIR_WRITE;
 	}
-	if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP)
-		dir |=3D BUS_DMASYNC_PREWRITE;
 	bus_dmamap_sync(sc->mfi_buffer_dmat, cm->cm_dmamap, dir);
 	cm->cm_flags |=3D MFI_CMD_MAPPED;
=20
@@ -1552,7 +2266,10 @@
 	cm->cm_total_frame_size +=3D (sc->mfi_sge_size * nsegs);
 	cm->cm_extra_frames =3D (cm->cm_total_frame_size - 1) / MFI_FRAME_SIZE;
=20
-	mfi_send_frame(sc, cm);
+	if (sc->MFA_enabled)
+			mfi_tbolt_send_frame(sc, cm);
+	else
+		mfi_send_frame(sc, cm);
=20
 	return;
 }
@@ -1588,7 +2305,7 @@
 	if (cm->cm_extra_frames > 7)
 		cm->cm_extra_frames =3D 7;
=20
-	sc->mfi_issue_cmd(sc,cm->cm_frame_busaddr,cm->cm_extra_frames);
+	sc->mfi_issue_cmd(sc, cm->cm_frame_busaddr, cm->cm_extra_frames);
=20
 	if ((cm->cm_flags & MFI_CMD_POLLED) =3D=3D 0)
 		return (0);
@@ -1603,14 +2320,15 @@
=20
 	if (hdr->cmd_status =3D=3D MFI_STAT_INVALID_STATUS) {
 		device_printf(sc->mfi_dev, "Frame %p timed out "
-			      "command 0x%X\n", hdr, cm->cm_frame->dcmd.opcode);
+		    "command 0x%X\n", hdr, cm->cm_frame->dcmd.opcode);
 		return (ETIMEDOUT);
 	}
=20
 	return (0);
 }
=20
-static void
+
+void
 mfi_complete(struct mfi_softc *sc, struct mfi_command *cm)
 {
 	int dir;
@@ -1642,6 +2360,7 @@
 	struct mfi_command *cm;
 	struct mfi_abort_frame *abort;
 	int i =3D 0;
+	uint32_t context =3D 0;
=20
 	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
=20
@@ -1649,21 +2368,30 @@
 		return (EBUSY);
 	}
=20
+	/* Zero out the MFI frame */
+	context =3D cm->cm_frame->header.context;
+	bzero(cm->cm_frame, sizeof(union mfi_frame));
+	cm->cm_frame->header.context =3D context;
+
 	abort =3D &cm->cm_frame->abort;
 	abort->header.cmd =3D MFI_CMD_ABORT;
 	abort->header.flags =3D 0;
+	abort->header.scsi_status =3D 0;
 	abort->abort_context =3D cm_abort->cm_frame->header.context;
-	abort->abort_mfi_addr_lo =3D cm_abort->cm_frame_busaddr;
-	abort->abort_mfi_addr_hi =3D 0;
+	abort->abort_mfi_addr_lo =3D (uint32_t)cm_abort->cm_frame_busaddr;
+	abort->abort_mfi_addr_hi =3D
+	    (uint32_t)((uint64_t)cm_abort->cm_frame_busaddr >> 32);
 	cm->cm_data =3D NULL;
 	cm->cm_flags =3D MFI_CMD_POLLED;
=20
-	sc->mfi_aen_cm->cm_aen_abort =3D 1;
+	if (sc->mfi_aen_cm)
+		sc->mfi_aen_cm->cm_aen_abort =3D 1;
 	mfi_mapcmd(sc, cm);
 	mfi_release_command(cm);
=20
 	while (i < 5 && sc->mfi_aen_cm !=3D NULL) {
-		msleep(&sc->mfi_aen_cm, &sc->mfi_io_lock, 0, "mfiabort", 5 * hz);
+		msleep(&sc->mfi_aen_cm, &sc->mfi_io_lock, 0, "mfiabort",
+		    5 * hz);
 		i++;
 	}
=20
@@ -1671,24 +2399,32 @@
 }
=20
 int
-mfi_dump_blocks(struct mfi_softc *sc, int id, uint64_t lba, void *virt, in=
t len)
+mfi_dump_blocks(struct mfi_softc *sc, int id, uint64_t lba, void *virt,
+     int len)
 {
 	struct mfi_command *cm;
 	struct mfi_io_frame *io;
 	int error;
+	uint32_t context =3D 0;
=20
 	if ((cm =3D mfi_dequeue_free(sc)) =3D=3D NULL)
 		return (EBUSY);
=20
+	/* Zero out the MFI frame */
+	context =3D cm->cm_frame->header.context;
+	bzero(cm->cm_frame, sizeof(union mfi_frame));
+	cm->cm_frame->header.context =3D context;
+
 	io =3D &cm->cm_frame->io;
 	io->header.cmd =3D MFI_CMD_LD_WRITE;
 	io->header.target_id =3D id;
 	io->header.timeout =3D 0;
 	io->header.flags =3D 0;
+	io->header.scsi_status =3D 0;
 	io->header.sense_len =3D MFI_SENSE_LEN;
 	io->header.data_len =3D (len + MFI_SECTOR_LEN - 1) / MFI_SECTOR_LEN;
-	io->sense_addr_lo =3D cm->cm_sense_busaddr;
-	io->sense_addr_hi =3D 0;
+	io->sense_addr_lo =3D (uint32_t)cm->cm_sense_busaddr;
+	io->sense_addr_hi =3D (uint32_t)((uint64_t)cm->cm_sense_busaddr >> 32);
 	io->lba_hi =3D (lba & 0xffffffff00000000) >> 32;
 	io->lba_lo =3D lba & 0xffffffff;
 	cm->cm_data =3D virt;
@@ -1706,6 +2442,53 @@
 	return (error);
 }
=20
+int
+mfi_dump_syspd_blocks(struct mfi_softc *sc, int id, uint64_t lba, void *vi=
rt,
+    int len)
+{
+	struct mfi_command *cm;
+	struct mfi_pass_frame *pass;
+	int error;
+	int blkcount =3D 0;
+
+	if ((cm =3D mfi_dequeue_free(sc)) =3D=3D NULL)
+		return (EBUSY);
+
+	pass =3D &cm->cm_frame->pass;
+	bzero(pass->cdb, 16);
+	pass->header.cmd =3D MFI_CMD_PD_SCSI_IO;
+	pass->cdb[0] =3D SCSI_WRITE;
+	pass->cdb[2] =3D (lba & 0xff000000) >> 24;
+	pass->cdb[3] =3D (lba & 0x00ff0000) >> 16;
+	pass->cdb[4] =3D (lba & 0x0000ff00) >> 8;
+	pass->cdb[5] =3D (lba & 0x000000ff);
+	blkcount =3D (len + MFI_SECTOR_LEN - 1) / MFI_SECTOR_LEN;
+	pass->cdb[7] =3D (blkcount & 0xff00) >> 8;
+	pass->cdb[8] =3D (blkcount & 0x00ff);
+	pass->header.target_id =3D id;
+	pass->header.timeout =3D 0;
+	pass->header.flags =3D 0;
+	pass->header.scsi_status =3D 0;
+	pass->header.sense_len =3D MFI_SENSE_LEN;
+	pass->header.data_len =3D len;
+	pass->header.cdb_len =3D 10;
+	pass->sense_addr_lo =3D (uint32_t)cm->cm_sense_busaddr;
+	pass->sense_addr_hi =3D (uint32_t)((uint64_t)cm->cm_sense_busaddr >> 32);
+	cm->cm_data =3D virt;
+	cm->cm_len =3D len;
+	cm->cm_sg =3D &pass->sgl;
+	cm->cm_total_frame_size =3D MFI_PASS_FRAME_SIZE;
+	cm->cm_flags =3D MFI_CMD_POLLED | MFI_CMD_DATAOUT;
+
+	error =3D mfi_mapcmd(sc, cm);
+	bus_dmamap_sync(sc->mfi_buffer_dmat, cm->cm_dmamap,
+	    BUS_DMASYNC_POSTWRITE);
+	bus_dmamap_unload(sc->mfi_buffer_dmat, cm->cm_dmamap);
+	mfi_release_command(cm);
+
+	return (error);
+}
+
 static int
 mfi_open(struct cdev *dev, int flags, int fmt, struct thread *td)
 {
@@ -1771,12 +2554,18 @@
 		sx_xunlock(&sc->mfi_config_lock);
 }
=20
-/* Perform pre-issue checks on commands from userland and possibly veto th=
em. */
+/*
+ * Perform pre-issue checks on commands from userland and possibly veto
+ * them.
+ */
 static int
 mfi_check_command_pre(struct mfi_softc *sc, struct mfi_command *cm)
 {
 	struct mfi_disk *ld, *ld2;
 	int error;
+	struct mfi_system_pd *syspd =3D NULL;
+	uint16_t syspd_id;
+	uint16_t *mbox;
=20
 	mtx_assert(&sc->mfi_io_lock, MA_OWNED);
 	error =3D 0;
@@ -1805,6 +2594,20 @@
 			}
 		}
 		break;
+	case MFI_DCMD_PD_STATE_SET:
+		mbox =3D (uint16_t *) cm->cm_frame->dcmd.mbox;
+		syspd_id =3D mbox[0];
+		if (mbox[2] =3D=3D MFI_PD_STATE_UNCONFIGURED_GOOD) {
+			TAILQ_FOREACH(syspd, &sc->mfi_syspd_tqh, pd_link) {
+				if (syspd->pd_id =3D=3D syspd_id)
+					break;
+			}
+		}
+		else
+			break;
+		if (syspd)
+			error =3D mfi_syspd_disable(syspd);
+		break;
 	default:
 		break;
 	}
@@ -1816,6 +2619,9 @@
 mfi_check_command_post(struct mfi_softc *sc, struct mfi_command *cm)
 {
 	struct mfi_disk *ld, *ldn;
+	struct mfi_system_pd *syspd =3D NULL;
+	uint16_t syspd_id;
+	uint16_t *mbox;
=20
 	switch (cm->cm_frame->dcmd.opcode) {
 	case MFI_DCMD_LD_DELETE:
@@ -1853,9 +2659,158 @@
 	case MFI_DCMD_CFG_FOREIGN_IMPORT:
 		mfi_ldprobe(sc);
 		break;
+	case MFI_DCMD_PD_STATE_SET:
+		mbox =3D (uint16_t *) cm->cm_frame->dcmd.mbox;
+		syspd_id =3D mbox[0];
+		if (mbox[2] =3D=3D MFI_PD_STATE_UNCONFIGURED_GOOD) {
+			TAILQ_FOREACH(syspd, &sc->mfi_syspd_tqh,pd_link) {
+				if (syspd->pd_id =3D=3D syspd_id)
+					break;
+			}
+		}
+		else
+			break;
+		/* If the transition fails then enable the syspd again */
+		if (syspd && cm->cm_frame->header.cmd_status !=3D MFI_STAT_OK)
+			mfi_syspd_enable(syspd);
+		break;
 	}
 }
=20
+static int mfi_check_for_sscd(struct mfi_softc *sc, struct mfi_command *cm)
+{
+	struct mfi_config_data *conf_data=3D(struct mfi_config_data *)cm->cm_data;
+	struct mfi_command *ld_cm =3D NULL;
+	struct mfi_ld_info *ld_info =3D NULL;
+	int error =3D 0;
+
+	if ((cm->cm_frame->dcmd.opcode =3D=3D MFI_DCMD_CFG_ADD) &&
+	    (conf_data->ld[0].params.isSSCD =3D=3D 1)){
+		error =3D 1;
+	} else if (cm->cm_frame->dcmd.opcode =3D=3D MFI_DCMD_LD_DELETE) {
+		error =3D mfi_dcmd_command (sc, &ld_cm, MFI_DCMD_LD_GET_INFO,
+		    (void **)&ld_info, sizeof(*ld_info));
+		if (error){
+			device_printf(sc->mfi_dev, "Failed to allocate"
+			    "MFI_DCMD_LD_GET_INFO %d", error);
+			if (ld_info)
+				free(ld_info, M_MFIBUF);
+			return 0;
+		}
+		ld_cm->cm_flags =3D MFI_CMD_DATAIN;
+		ld_cm->cm_frame->dcmd.mbox[0]=3D cm->cm_frame->dcmd.mbox[0];
+		ld_cm->cm_frame->header.target_id =3D cm->cm_frame->dcmd.mbox[0];
+		if (mfi_wait_command(sc, ld_cm) !=3D 0){
+			device_printf(sc->mfi_dev, "failed to get log drv\n");
+			mfi_release_command(ld_cm);
+			free(ld_info, M_MFIBUF);
+			return 0;
+		}
+
+		if (ld_cm->cm_frame->header.cmd_status !=3D MFI_STAT_OK) {
+			free(ld_info, M_MFIBUF);
+			mfi_release_command(ld_cm);
+			return 0;
+		}
+		else
+			ld_info =3D (struct mfi_ld_info *)ld_cm->cm_private;
+
+		if (ld_info->ld_config.params.isSSCD =3D=3D 1)
+			error =3D 1;
+
+		mfi_release_command(ld_cm);
+		free(ld_info, M_MFIBUF);
+
+	}
+	return error;
+}
+
+static int
+mfi_stp_cmd(struct mfi_softc *sc, struct mfi_command *cm,caddr_t arg)
+{
+	uint8_t i;
+	struct mfi_ioc_packet *ioc;
+	ioc =3D (struct mfi_ioc_packet *)arg;
+	int sge_size, error;
+	struct megasas_sge *kern_sge;
+
+	memset(sc->kbuff_arr, 0, sizeof(sc->kbuff_arr));
+	kern_sge =3D(struct megasas_sge *) ((uintptr_t)cm->cm_frame + ioc->mfi_sg=
l_off);
+	cm->cm_frame->header.sg_count =3D ioc->mfi_sge_count;
+
+	if (sizeof(bus_addr_t) =3D=3D 8) {
+		cm->cm_frame->header.flags |=3D MFI_FRAME_SGL64;
+		cm->cm_extra_frames =3D 2;
+		sge_size =3D sizeof(struct mfi_sg64);
+	} else {
+		cm->cm_extra_frames =3D  (cm->cm_total_frame_size - 1) / MFI_FRAME_SIZE;
+		sge_size =3D sizeof(struct mfi_sg32);
+	}
+
+	cm->cm_total_frame_size +=3D (sge_size * ioc->mfi_sge_count);
+	for (i =3D 0; i < ioc->mfi_sge_count; i++) {
+			if (bus_dma_tag_create( sc->mfi_parent_dmat,	/* parent */
+			1, 0,			/* algnmnt, boundary */
+			BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
+			BUS_SPACE_MAXADDR,	/* highaddr */
+			NULL, NULL,		/* filter, filterarg */
+			ioc->mfi_sgl[i].iov_len,/* maxsize */
+			2,			/* nsegments */
+			ioc->mfi_sgl[i].iov_len,/* maxsegsize */
+			BUS_DMA_ALLOCNOW,	/* flags */
+			NULL, NULL,		/* lockfunc, lockarg */
+			&sc->mfi_kbuff_arr_dmat[i])) {
+			device_printf(sc->mfi_dev,
+			    "Cannot allocate mfi_kbuff_arr_dmat tag\n");
+			return (ENOMEM);
+		}
+
+		if (bus_dmamem_alloc(sc->mfi_kbuff_arr_dmat[i],
+		    (void **)&sc->kbuff_arr[i], BUS_DMA_NOWAIT,
+		    &sc->mfi_kbuff_arr_dmamap[i])) {
+			device_printf(sc->mfi_dev,
+			    "Cannot allocate mfi_kbuff_arr_dmamap memory\n");
+			return (ENOMEM);
+		}
+
+		bus_dmamap_load(sc->mfi_kbuff_arr_dmat[i],
+		    sc->mfi_kbuff_arr_dmamap[i], sc->kbuff_arr[i],
+		    ioc->mfi_sgl[i].iov_len, mfi_addr_cb,
+		    &sc->mfi_kbuff_arr_busaddr[i], 0);
+
+		if (!sc->kbuff_arr[i]) {
+			device_printf(sc->mfi_dev,
+			    "Could not allocate memory for kbuff_arr info\n");
+			return -1;
+		}
+		kern_sge[i].phys_addr =3D sc->mfi_kbuff_arr_busaddr[i];
+		kern_sge[i].length =3D ioc->mfi_sgl[i].iov_len;
+
+		if (sizeof(bus_addr_t) =3D=3D 8) {
+			cm->cm_frame->stp.sgl.sg64[i].addr =3D
+			    kern_sge[i].phys_addr;
+			cm->cm_frame->stp.sgl.sg64[i].len =3D
+			    ioc->mfi_sgl[i].iov_len;
+		} else {
+			cm->cm_frame->stp.sgl.sg32[i].len =3D
+			    kern_sge[i].phys_addr;
+			cm->cm_frame->stp.sgl.sg32[i].len =3D
+			    ioc->mfi_sgl[i].iov_len;
+		}
+
+		error =3D copyin(ioc->mfi_sgl[i].iov_base,
+		    sc->kbuff_arr[i],
+		    ioc->mfi_sgl[i].iov_len);
+		if (error !=3D 0) {
+			device_printf(sc->mfi_dev, "Copy in failed\n");
+			return error;
+		}
+	}
+
+	cm->cm_flags |=3DMFI_CMD_MAPPED;
+	return 0;
+}
+
 static int
 mfi_user_command(struct mfi_softc *sc, struct mfi_ioc_passthru *ioc)
 {
@@ -1924,11 +2879,7 @@
 	return (error);
 }
=20
-#ifdef __amd64__
 #define	PTRIN(p)		((void *)(uintptr_t)(p))
-#else
-#define	PTRIN(p)		(p)
-#endif
=20
 static int
 mfi_ioctl(struct cdev *dev, u_long cmd, caddr_t arg, int flag, struct thre=
ad *td)
@@ -1936,26 +2887,35 @@
 	struct mfi_softc *sc;
 	union mfi_statrequest *ms;
 	struct mfi_ioc_packet *ioc;
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 	struct mfi_ioc_packet32 *ioc32;
 #endif
 	struct mfi_ioc_aen *aen;
 	struct mfi_command *cm =3D NULL;
-	uint32_t context;
+	uint32_t context =3D 0;
 	union mfi_sense_ptr sense_ptr;
-	uint8_t *data =3D NULL, *temp, *addr;
+	uint8_t *data =3D NULL, *temp, *addr, skip_pre_post =3D 0;
 	size_t len;
-	int i;
+	int i, res;
 	struct mfi_ioc_passthru *iop =3D (struct mfi_ioc_passthru *)arg;
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 	struct mfi_ioc_passthru32 *iop32 =3D (struct mfi_ioc_passthru32 *)arg;
 	struct mfi_ioc_passthru iop_swab;
 #endif
 	int error, locked;
-
+	union mfi_sgl *sgl;
 	sc =3D dev->si_drv1;
 	error =3D 0;
=20
+	if (sc->adpreset)
+		return EBUSY;
+
+	if (sc->hw_crit_error)
+		return EBUSY;
+
+	if (sc->issuepend_done =3D=3D 0)
+		return EBUSY;
+
 	switch (cmd) {
 	case MFIIO_STATS:
 		ms =3D (union mfi_statrequest *)arg;
@@ -1997,7 +2957,7 @@
 		break;
 	}
 	case MFI_CMD:
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 	case MFI_CMD32:
 #endif
 		{
@@ -2023,15 +2983,19 @@
 		 * will clobber some data
 		 */
 		context =3D cm->cm_frame->header.context;
+		cm->cm_frame->header.context =3D cm->cm_index;
=20
 		bcopy(ioc->mfi_frame.raw, cm->cm_frame,
-		    2 * MFI_DCMD_FRAME_SIZE);  /* this isn't quite right */
+		    2 * MEGAMFI_FRAME_SIZE);
 		cm->cm_total_frame_size =3D (sizeof(union mfi_sgl)
 		    * ioc->mfi_sge_count) + ioc->mfi_sgl_off;
+		cm->cm_frame->header.scsi_status =3D 0;
+		cm->cm_frame->header.pad0 =3D 0;
 		if (ioc->mfi_sge_count) {
 			cm->cm_sg =3D
 			    (union mfi_sgl *)&cm->cm_frame->bytes[ioc->mfi_sgl_off];
 		}
+		sgl =3D cm->cm_sg;
 		cm->cm_flags =3D 0;
 		if (cm->cm_frame->header.flags & MFI_FRAME_DATAIN)
 			cm->cm_flags |=3D MFI_CMD_DATAIN;
@@ -2042,12 +3006,12 @@
 			cm->cm_flags |=3D MFI_CMD_DATAIN | MFI_CMD_DATAOUT;
 		cm->cm_len =3D cm->cm_frame->header.data_len;
 		if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP) {
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 			if (cmd =3D=3D MFI_CMD) {
 #endif
 				/* Native */
 				cm->cm_stp_len =3D ioc->mfi_sgl[0].iov_len;
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 			} else {
 				/* 32bit on 64bit */
 				ioc32 =3D (struct mfi_ioc_packet32 *)ioc;
@@ -2071,84 +3035,97 @@
 		/* restore header context */
 		cm->cm_frame->header.context =3D context;
=20
-		temp =3D data;
-		if ((cm->cm_flags & MFI_CMD_DATAOUT) ||
-		    (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP)) {
-			for (i =3D 0; i < ioc->mfi_sge_count; i++) {
-#ifdef __amd64__
-				if (cmd =3D=3D MFI_CMD) {
+		if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP) {
+			res =3D mfi_stp_cmd(sc, cm, arg);
+			if (res !=3D 0)
+				goto out;
+		} else {
+			temp =3D data;
+			if ((cm->cm_flags & MFI_CMD_DATAOUT) ||
+			    (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP)) {
+				for (i =3D 0; i < ioc->mfi_sge_count; i++) {
+#ifdef COMPAT_FREEBSD32
+					if (cmd =3D=3D MFI_CMD) {
 #endif
-					/* Native */
-					addr =3D ioc->mfi_sgl[i].iov_base;
-					len =3D ioc->mfi_sgl[i].iov_len;
-#ifdef __amd64__
-				} else {
-					/* 32bit on 64bit */
-					ioc32 =3D (struct mfi_ioc_packet32 *)ioc;
-					addr =3D PTRIN(ioc32->mfi_sgl[i].iov_base);
-					len =3D ioc32->mfi_sgl[i].iov_len;
+						/* Native */
+						addr =3D ioc->mfi_sgl[i].iov_base;
+						len =3D ioc->mfi_sgl[i].iov_len;
+#ifdef COMPAT_FREEBSD32
+					} else {
+						/* 32bit on 64bit */
+						ioc32 =3D (struct mfi_ioc_packet32 *)ioc;
+						addr =3D PTRIN(ioc32->mfi_sgl[i].iov_base);
+						len =3D ioc32->mfi_sgl[i].iov_len;
+					}
+#endif
+					error =3D copyin(addr, temp, len);
+					if (error !=3D 0) {
+						device_printf(sc->mfi_dev,
+						    "Copy in failed\n");
+						goto out;
+					}
+					temp =3D &temp[len];
 				}
-#endif
-				error =3D copyin(addr, temp, len);
-				if (error !=3D 0) {
-					device_printf(sc->mfi_dev,
-					    "Copy in failed\n");
-					goto out;
-				}
-				temp =3D &temp[len];
 			}
 		}
=20
 		if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_DCMD)
-			locked =3D mfi_config_lock(sc, cm->cm_frame->dcmd.opcode);
+			locked =3D mfi_config_lock(sc,
+			     cm->cm_frame->dcmd.opcode);
=20
 		if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_PD_SCSI_IO) {
-			cm->cm_frame->pass.sense_addr_lo =3D cm->cm_sense_busaddr;
-			cm->cm_frame->pass.sense_addr_hi =3D 0;
+			cm->cm_frame->pass.sense_addr_lo =3D
+			    (uint32_t)cm->cm_sense_busaddr;
+			cm->cm_frame->pass.sense_addr_hi =3D
+			    (uint32_t)((uint64_t)cm->cm_sense_busaddr >> 32);
 		}
-
 		mtx_lock(&sc->mfi_io_lock);
-		error =3D mfi_check_command_pre(sc, cm);
-		if (error) {
-			mtx_unlock(&sc->mfi_io_lock);
-			goto out;
+		skip_pre_post =3D mfi_check_for_sscd (sc, cm);
+		if (!skip_pre_post) {
+			error =3D mfi_check_command_pre(sc, cm);
+			if (error) {
+				mtx_unlock(&sc->mfi_io_lock);
+				goto out;
+			}
 		}
-
 		if ((error =3D mfi_wait_command(sc, cm)) !=3D 0) {
 			device_printf(sc->mfi_dev,
 			    "Controller polled failed\n");
 			mtx_unlock(&sc->mfi_io_lock);
 			goto out;
 		}
-
-		mfi_check_command_post(sc, cm);
+		if (!skip_pre_post) {
+			mfi_check_command_post(sc, cm);
+		}
 		mtx_unlock(&sc->mfi_io_lock);
=20
-		temp =3D data;
-		if ((cm->cm_flags & MFI_CMD_DATAIN) ||
-		    (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP)) {
-			for (i =3D 0; i < ioc->mfi_sge_count; i++) {
-#ifdef __amd64__
-				if (cmd =3D=3D MFI_CMD) {
+		if (cm->cm_frame->header.cmd !=3D MFI_CMD_STP) {
+			temp =3D data;
+			if ((cm->cm_flags & MFI_CMD_DATAIN) ||
+			    (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP)) {
+				for (i =3D 0; i < ioc->mfi_sge_count; i++) {
+#ifdef COMPAT_FREEBSD32
+					if (cmd =3D=3D MFI_CMD) {
 #endif
-					/* Native */
-					addr =3D ioc->mfi_sgl[i].iov_base;
-					len =3D ioc->mfi_sgl[i].iov_len;
-#ifdef __amd64__
-				} else {
-					/* 32bit on 64bit */
-					ioc32 =3D (struct mfi_ioc_packet32 *)ioc;
-					addr =3D PTRIN(ioc32->mfi_sgl[i].iov_base);
-					len =3D ioc32->mfi_sgl[i].iov_len;
+						/* Native */
+						addr =3D ioc->mfi_sgl[i].iov_base;
+						len =3D ioc->mfi_sgl[i].iov_len;
+#ifdef COMPAT_FREEBSD32
+					} else {
+						/* 32bit on 64bit */
+						ioc32 =3D (struct mfi_ioc_packet32 *)ioc;
+						addr =3D PTRIN(ioc32->mfi_sgl[i].iov_base);
+						len =3D ioc32->mfi_sgl[i].iov_len;
+					}
+#endif
+					error =3D copyout(temp, addr, len);
+					if (error !=3D 0) {
+						device_printf(sc->mfi_dev,
+						    "Copy out failed\n");
+						goto out;
+					}
+					temp =3D &temp[len];
 				}
-#endif
-				error =3D copyout(temp, addr, len);
-				if (error !=3D 0) {
-					device_printf(sc->mfi_dev,
-					    "Copy out failed\n");
-					goto out;
-				}
-				temp =3D &temp[len];
 			}
 		}
=20
@@ -2157,7 +3134,7 @@
 			bcopy(&ioc->mfi_frame.raw[ioc->mfi_sense_off],
 			    &sense_ptr.sense_ptr_data[0],
 			    sizeof(sense_ptr.sense_ptr_data));
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 			if (cmd !=3D MFI_CMD) {
 				/*
 				 * not 64bit native so zero out any address
@@ -2179,6 +3156,26 @@
 		mfi_config_unlock(sc, locked);
 		if (data)
 			free(data, M_MFIBUF);
+		if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_STP) {
+			for (i =3D 0; i < 2; i++) {
+				if (sc->kbuff_arr[i]) {
+					if (sc->mfi_kbuff_arr_busaddr !=3D 0)
+						bus_dmamap_unload(
+						    sc->mfi_kbuff_arr_dmat[i],
+						    sc->mfi_kbuff_arr_dmamap[i]
+						    );
+					if (sc->kbuff_arr[i] !=3D NULL)
+						bus_dmamem_free(
+						    sc->mfi_kbuff_arr_dmat[i],
+						    sc->kbuff_arr[i],
+						    sc->mfi_kbuff_arr_dmamap[i]
+						    );
+					if (sc->mfi_kbuff_arr_dmat[i] !=3D NULL)
+						bus_dma_tag_destroy(
+						    sc->mfi_kbuff_arr_dmat[i]);
+				}
+			}
+		}
 		if (cm) {
 			mtx_lock(&sc->mfi_io_lock);
 			mfi_release_command(cm);
@@ -2235,7 +3232,7 @@
 			    cmd, arg, flag, td));
 			break;
 		}
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 	case MFIIO_PASSTHRU32:
 		iop_swab.ioc_frame	=3D iop32->ioc_frame;
 		iop_swab.buf_size	=3D iop32->buf_size;
@@ -2245,7 +3242,7 @@
 #endif
 	case MFIIO_PASSTHRU:
 		error =3D mfi_user_command(sc, iop);
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 		if (cmd =3D=3D MFIIO_PASSTHRU32)
 			iop32->ioc_frame =3D iop_swab.ioc_frame;
 #endif
@@ -2268,7 +3265,7 @@
 	struct mfi_command *cm =3D NULL;
 	struct mfi_aen *mfi_aen_entry;
 	union mfi_sense_ptr sense_ptr;
-	uint32_t context;
+	uint32_t context =3D 0;
 	uint8_t *data =3D NULL, *temp;
 	int i;
 	int error, locked;
@@ -2303,6 +3300,8 @@
 		      2 * MFI_DCMD_FRAME_SIZE);	/* this isn't quite right */
 		cm->cm_total_frame_size =3D (sizeof(union mfi_sgl)
 		      * l_ioc.lioc_sge_count) + l_ioc.lioc_sgl_off;
+		cm->cm_frame->header.scsi_status =3D 0;
+		cm->cm_frame->header.pad0 =3D 0;
 		if (l_ioc.lioc_sge_count)
 			cm->cm_sg =3D
 			    (union mfi_sgl *)&cm->cm_frame->bytes[l_ioc.lioc_sgl_off];
@@ -2346,8 +3345,10 @@
 			locked =3D mfi_config_lock(sc, cm->cm_frame->dcmd.opcode);
=20
 		if (cm->cm_frame->header.cmd =3D=3D MFI_CMD_PD_SCSI_IO) {
-			cm->cm_frame->pass.sense_addr_lo =3D cm->cm_sense_busaddr;
-			cm->cm_frame->pass.sense_addr_hi =3D 0;
+			cm->cm_frame->pass.sense_addr_lo =3D
+			    (uint32_t)cm->cm_sense_busaddr;
+			cm->cm_frame->pass.sense_addr_hi =3D
+			    (uint32_t)((uint64_t)cm->cm_sense_busaddr >> 32);
 		}
=20
 		mtx_lock(&sc->mfi_io_lock);
@@ -2486,7 +3487,6 @@
 	return revents;
 }
=20
-
 static void
 mfi_dump_all(void)
 {
@@ -2514,8 +3514,8 @@
 		TAILQ_FOREACH(cm, &sc->mfi_busy, cm_link) {
 			if (cm->cm_timestamp < deadline) {
 				device_printf(sc->mfi_dev,
-				    "COMMAND %p TIMEOUT AFTER %d SECONDS\n", cm,
-				    (int)(time_uptime - cm->cm_timestamp));
+				    "COMMAND %p TIMEOUT AFTER %d SECONDS\n",
+				    cm, (int)(time_uptime - cm->cm_timestamp));
 				MFI_PRINT_CMD(cm);
 				timedout++;
 			}
@@ -2541,17 +3541,28 @@
 	int timedout =3D 0;
=20
 	deadline =3D time_uptime - MFI_CMD_TIMEOUT;
+	if (sc->adpreset =3D=3D 0) {
+		if (!mfi_tbolt_reset(sc)) {
+			callout_reset(&sc->mfi_watchdog_callout, MFI_CMD_TIMEOUT * hz, mfi_time=
out, sc);
+			return;
+		}
+	}
 	mtx_lock(&sc->mfi_io_lock);
 	TAILQ_FOREACH(cm, &sc->mfi_busy, cm_link) {
 		if (sc->mfi_aen_cm =3D=3D cm)
 			continue;
 		if ((sc->mfi_aen_cm !=3D cm) && (cm->cm_timestamp < deadline)) {
-			device_printf(sc->mfi_dev,
-			    "COMMAND %p TIMEOUT AFTER %d SECONDS\n", cm,
-			    (int)(time_uptime - cm->cm_timestamp));
-			MFI_PRINT_CMD(cm);
-			MFI_VALIDATE_CMD(sc, cm);
-			timedout++;
+			if (sc->adpreset !=3D 0 && sc->issuepend_done =3D=3D 0) {
+				cm->cm_timestamp =3D time_uptime;
+			} else {
+				device_printf(sc->mfi_dev,
+				    "COMMAND %p TIMEOUT AFTER %d SECONDS\n",
+				     cm, (int)(time_uptime - cm->cm_timestamp)
+				     );
+				MFI_PRINT_CMD(cm);
+				MFI_VALIDATE_CMD(sc, cm);
+				timedout++;
+			}
 		}
 	}
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfi_cam.c
--- a/head/sys/dev/mfi/mfi_cam.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfi_cam.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_cam.c 227562 2011-11-16 15:39:27Z=
 jhb $");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_cam.c 233711 2012-03-30 23:05:48Z=
 ambrisko $");
=20
 #include "opt_mfi.h"
=20
@@ -270,12 +270,18 @@
 	struct mfip_softc *sc;
 	struct mfi_pass_frame *pt;
 	struct mfi_command *cm;
+	uint32_t context =3D 0;
=20
 	sc =3D ccbh->ccb_mfip_ptr;
=20
 	if ((cm =3D mfi_dequeue_free(sc->mfi_sc)) =3D=3D NULL)
 		return (NULL);
=20
+	/* Zero out the MFI frame */
+	context =3D cm->cm_frame->header.context;
+	bzero(cm->cm_frame, sizeof(union mfi_frame));
+	cm->cm_frame->header.context =3D context;
+
 	pt =3D &cm->cm_frame->pass;
 	pt->header.cmd =3D MFI_CMD_PD_SCSI_IO;
 	pt->header.cmd_status =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfi_debug.c
--- a/head/sys/dev/mfi/mfi_debug.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfi_debug.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_debug.c 227577 2011-11-16 18:42:3=
9Z kib $");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_debug.c 233711 2012-03-30 23:05:4=
8Z ambrisko $");
=20
 #include "opt_mfi.h"
=20
@@ -63,7 +63,8 @@
 	    "\2SGL64"
 	    "\3SENSE64"
 	    "\4WRITE"
-	    "\5READ");
+	    "\5READ"
+	    "\6IEEESGL");
 }
=20
 static void
@@ -73,7 +74,15 @@
=20
 	printf("SG List:\n");
 	for (i =3D 0; i < count; i++) {
-		if (hdr->flags & MFI_FRAME_SGL64) {
+		if (hdr->flags & MFI_FRAME_IEEE_SGL) {
+			printf("0x%lx:%06d ", (u_long)sgl->sg_skinny[i].addr,
+			    sgl->sg_skinny[i].len);
+			columns +=3D 26;
+			if (columns > 77) {
+				printf("\n");
+				columns =3D 0;
+			}
+		} else if (hdr->flags & MFI_FRAME_SGL64) {
 			printf("0x%lx:%06d ", (u_long)sgl->sg64[i].addr,
 			    sgl->sg64[i].len);
 			columns +=3D 26;
@@ -240,7 +249,12 @@
 	hdr =3D &cm->cm_frame->header;
 	count =3D 0;
 	for (i =3D 0; i < hdr->sg_count; i++) {
-		count +=3D cm->cm_sg->sg32[i].len;
+		if (hdr->flags & MFI_FRAME_IEEE_SGL)
+			count +=3D cm->cm_sg->sg_skinny[i].len;
+		else if (hdr->flags & MFI_FRAME_SGL64)
+			count +=3D cm->cm_sg->sg64[i].len;
+		else
+			count +=3D cm->cm_sg->sg32[i].len;
 	}
 	/*
 	count++;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfi_disk.c
--- a/head/sys/dev/mfi/mfi_disk.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfi_disk.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_disk.c 227562 2011-11-16 15:39:27=
Z jhb $");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_disk.c 233711 2012-03-30 23:05:48=
Z ambrisko $");
=20
 #include "opt_mfi.h"
=20
@@ -224,7 +224,7 @@
 	if (sc->ld_flags & MFI_DISK_FLAGS_OPEN) {
 		if (sc->ld_controller->mfi_delete_busy_volumes)
 			return (0);
-		device_printf(sc->ld_dev, "Unable to delete busy device\n");
+		device_printf(sc->ld_dev, "Unable to delete busy ld device\n");
 		return (EBUSY);
 	}
 	sc->ld_flags |=3D MFI_DISK_FLAGS_DISABLED;
@@ -246,6 +246,7 @@
 	struct mfi_softc *controller;
=20
 	sc =3D bio->bio_disk->d_drv1;
+	controller =3D sc->ld_controller;
=20
 	if (sc =3D=3D NULL) {
 		bio->bio_error =3D EINVAL;
@@ -255,8 +256,24 @@
 		return;
 	}
=20
-	controller =3D sc->ld_controller;
+	if (controller->adpreset){
+		bio->bio_error =3D EBUSY;
+		return;
+	}
+
+	if (controller->hw_crit_error){
+		bio->bio_error =3D EBUSY;
+		return;
+	}
+
+	if (controller->issuepend_done =3D=3D 0){
+		bio->bio_error =3D EBUSY;
+		return;
+	}
+
 	bio->bio_driver1 =3D (void *)(uintptr_t)sc->ld_id;
+	/* Mark it as LD IO */
+	bio->bio_driver2 =3D (void *)MFI_LD_IO;
 	mtx_lock(&controller->mfi_io_lock);
 	mfi_enqueue_bio(controller, bio);
 	mfi_startio(controller);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfi_ioctl.h
--- a/head/sys/dev/mfi/mfi_ioctl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfi_ioctl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -25,16 +25,14 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_ioctl.h 233805 2012-04-02 19:13:0=
2Z ambrisko $");
=20
 #include <dev/mfi/mfireg.h>
=20
-#if defined(__amd64__) /* Assume amd64 wants 32 bit Linux */
 struct iovec32 {
 	u_int32_t	iov_base;
 	int		iov_len;
 };
-#endif
=20
 #define MFIQ_FREE	0
 #define MFIQ_BIO	1
@@ -79,7 +77,7 @@
 	struct iovec mfi_sgl[MAX_IOCTL_SGE];
 } __packed;
=20
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 struct mfi_ioc_packet32 {
 	uint16_t	mfi_adapter_no;
 	uint16_t	mfi_pad1;
@@ -104,7 +102,7 @@
 } __packed;
=20
 #define MFI_CMD		_IOWR('M', 1, struct mfi_ioc_packet)
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 #define MFI_CMD32	_IOWR('M', 1, struct mfi_ioc_packet32)
 #endif
 #define MFI_SET_AEN	_IOW('M', 3, struct mfi_ioc_aen)
@@ -136,7 +134,7 @@
 	uint8_t			*buf;
 } __packed;
=20
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 struct mfi_ioc_passthru32 {
 	struct mfi_dcmd_frame	ioc_frame;
 	uint32_t		buf_size;
@@ -146,7 +144,7 @@
=20
 #define MFIIO_STATS	_IOWR('Q', 101, union mfi_statrequest)
 #define MFIIO_PASSTHRU	_IOWR('C', 102, struct mfi_ioc_passthru)
-#ifdef __amd64__
+#ifdef COMPAT_FREEBSD32
 #define MFIIO_PASSTHRU32	_IOWR('C', 102, struct mfi_ioc_passthru32)
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfi_linux.c
--- a/head/sys/dev/mfi/mfi_linux.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfi_linux.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_linux.c 224778 2011-08-11 12:30:2=
3Z rwatson $");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_linux.c 233711 2012-03-30 23:05:4=
8Z ambrisko $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -35,6 +35,7 @@
 #include <sys/module.h>
 #include <sys/file.h>
 #include <sys/proc.h>
+#include <machine/bus.h>
=20
 #if defined(__amd64__) /* Assume amd64 wants 32 bit Linux */
 #include <machine/../linux32/linux.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfi_pci.c
--- a/head/sys/dev/mfi/mfi_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfi_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -51,7 +51,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_pci.c 232854 2012-03-12 08:03:51Z=
 scottl $");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfi_pci.c 233711 2012-03-30 23:05:48Z=
 ambrisko $");
=20
 /* PCI/PCI-X/PCIe bus interface for the LSI MegaSAS controllers */
=20
@@ -107,7 +107,7 @@
 DRIVER_MODULE(mfi, pci, mfi_pci_driver, mfi_devclass, 0, 0);
 MODULE_VERSION(mfi, 1);
=20
-static int	mfi_msi =3D 0;
+static int	mfi_msi =3D 1;
 TUNABLE_INT("hw.mfi.msi", &mfi_msi);
 SYSCTL_INT(_hw_mfi, OID_AUTO, msi, CTLFLAG_RDTUN, &mfi_msi, 0,
     "Enable use of MSI interrupts");
@@ -120,14 +120,28 @@
 	int		flags;
 	const char	*desc;
 } mfi_identifiers[] =3D {
+	{0x1000, 0x005b, 0x1028, 0x1f2d, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H810 Adapter"},
+	{0x1000, 0x005b, 0x1028, 0x1f30, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H710 Embedded"},
+	{0x1000, 0x005b, 0x1028, 0x1f31, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H710P Adapter"},
+	{0x1000, 0x005b, 0x1028, 0x1f33, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H710P Mini (blades)"},
+	{0x1000, 0x005b, 0x1028, 0x1f34, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H710P Mini (monolithics)"},
+	{0x1000, 0x005b, 0x1028, 0x1f35, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H710 Adapter"},
+	{0x1000, 0x005b, 0x1028, 0x1f37, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H710 Mini (blades)"},
+	{0x1000, 0x005b, 0x1028, 0x1f38, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Dell=
 PERC H710 Mini (monolithics)"},
+	{0x1000, 0x005b, 0x8086, 0x9265, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Inte=
l (R) RAID Controller RS25DB080"},
+	{0x1000, 0x005b, 0x8086, 0x9285, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Inte=
l (R) RAID Controller RS25NB008"},
+	{0x1000, 0x005b, 0xffff, 0xffff, MFI_FLAGS_SKINNY| MFI_FLAGS_TBOLT, "Thun=
derBolt"},
 	{0x1000, 0x0060, 0x1028, 0xffff, MFI_FLAGS_1078,  "Dell PERC 6"},
 	{0x1000, 0x0060, 0xffff, 0xffff, MFI_FLAGS_1078,  "LSI MegaSAS 1078"},
+	{0x1000, 0x0071, 0xffff, 0xffff, MFI_FLAGS_SKINNY, "Drake Skinny"},
+	{0x1000, 0x0073, 0xffff, 0xffff, MFI_FLAGS_SKINNY, "Drake Skinny"},
 	{0x1000, 0x0078, 0xffff, 0xffff, MFI_FLAGS_GEN2,  "LSI MegaSAS Gen2"},
 	{0x1000, 0x0079, 0x1028, 0x1f15, MFI_FLAGS_GEN2,  "Dell PERC H800 Adapter=
"},
 	{0x1000, 0x0079, 0x1028, 0x1f16, MFI_FLAGS_GEN2,  "Dell PERC H700 Adapter=
"},
 	{0x1000, 0x0079, 0x1028, 0x1f17, MFI_FLAGS_GEN2,  "Dell PERC H700 Integra=
ted"},
 	{0x1000, 0x0079, 0x1028, 0x1f18, MFI_FLAGS_GEN2,  "Dell PERC H700 Modular=
"},
 	{0x1000, 0x0079, 0x1028, 0x1f19, MFI_FLAGS_GEN2,  "Dell PERC H700"},
+	{0x1000, 0x0079, 0x1028, 0x1f1a, MFI_FLAGS_GEN2,  "Dell PERC H800 Proto A=
dapter"},
 	{0x1000, 0x0079, 0x1028, 0x1f1b, MFI_FLAGS_GEN2,  "Dell PERC H800"},
 	{0x1000, 0x0079, 0x1028, 0xffff, MFI_FLAGS_GEN2,  "Dell PERC Gen2"},
 	{0x1000, 0x0079, 0xffff, 0xffff, MFI_FLAGS_GEN2,  "LSI MegaSAS Gen2"},
@@ -201,8 +215,11 @@
 	    (sc->mfi_flags & MFI_FLAGS_1078)) {
 		/* 1068/1078: Memory mapped BAR is at offset 0x10 */
 		sc->mfi_regs_rid =3D PCIR_BAR(0);
-	} else if (sc->mfi_flags & MFI_FLAGS_GEN2) {
-		/* GEN2: Memory mapped BAR is at offset 0x14 */
+	}
+	else if ((sc->mfi_flags & MFI_FLAGS_GEN2) ||
+		 (sc->mfi_flags & MFI_FLAGS_SKINNY) ||
+		(sc->mfi_flags & MFI_FLAGS_TBOLT)) {=20
+		/* Gen2/Skinny: Memory mapped BAR is at offset 0x14 */
 		sc->mfi_regs_rid =3D PCIR_BAR(1);
 	}
 	if ((sc->mfi_regs_resource =3D bus_alloc_resource_any(sc->mfi_dev,
@@ -259,8 +276,8 @@
 mfi_pci_detach(device_t dev)
 {
 	struct mfi_softc *sc;
-	struct mfi_disk *ld;
-	int error;
+	int error, devcount, i;
+	device_t *devlist;
=20
 	sc =3D device_get_softc(dev);
=20
@@ -274,13 +291,13 @@
 	sc->mfi_detaching =3D 1;
 	mtx_unlock(&sc->mfi_io_lock);
=20
-	while ((ld =3D TAILQ_FIRST(&sc->mfi_ld_tqh)) !=3D NULL) {
-		if ((error =3D device_delete_child(dev, ld->ld_dev)) !=3D 0) {
-			sc->mfi_detaching =3D 0;
-			sx_xunlock(&sc->mfi_config_lock);
-			return (error);
-		}
+	if ((error =3D device_get_children(sc->mfi_dev, &devlist, &devcount)) !=
=3D 0) {
+		sx_xunlock(&sc->mfi_config_lock);
+		return error;
 	}
+	for (i =3D 0; i < devcount; i++)
+		device_delete_child(sc->mfi_dev, devlist[i]);
+	free(devlist, M_TEMP);
 	sx_xunlock(&sc->mfi_config_lock);
=20
 	EVENTHANDLER_DEREGISTER(shutdown_final, sc->mfi_eh);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfireg.h
--- a/head/sys/dev/mfi/mfireg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfireg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -54,7 +54,7 @@
 #define _MFIREG_H
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfireg.h 224041 2011-07-14 20:20:33Z =
jhb $");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfireg.h 233711 2012-03-30 23:05:48Z =
ambrisko $");
=20
 /*
  * MegaRAID SAS MFI firmware definitions
@@ -64,7 +64,7 @@
  * reason why this interface should be limited to just SAS.  In any case, =
LSI
  * seems to also call this interface 'MFI', so that will be used here.
  */
-
+#define MEGAMFI_FRAME_SIZE              64
 /*
  * Start with the register set.  All registers are 32 bits wide.
  * The usual Intel IOP style setup.
@@ -83,25 +83,50 @@
 #define MFI_OQP		0x44	/* Outbound queue port */
=20
 /*
+*  ThunderBolt specific Register
+*/
+
+#define MFI_RPI		0x6c 		/* reply_post_host_index */
+#define MFI_ILQP 	0xc0		/* inbound_low_queue_port */
+#define MFI_IHQP 	0xc4		/* inbound_high_queue_port */
+
+/*
  * 1078 specific related register
  */
 #define MFI_ODR0	0x9c 		/* outbound doorbell register0 */
 #define MFI_ODCR0	0xa0 		/* outbound doorbell clear register0  */
 #define MFI_OSP0	0xb0 		/* outbound scratch pad0  */
 #define MFI_1078_EIM	0x80000004 	/* 1078 enable intrrupt mask  */
-#define MFI_RMI		0x2 		/* reply message interrupt  */      =20
+#define MFI_RMI		0x2 		/* reply message interrupt  */
 #define MFI_1078_RM	0x80000000 	/* reply 1078 message interrupt  */
 #define MFI_ODC		0x4 		/* outbound doorbell change interrupt */
=20
+/* OCR registers */
+#define MFI_WSR		0x004		/* write sequence register */
+#define MFI_HDR		0x008		/* host diagnostic register */
+#define MFI_RSR		0x3c3		/* Reset Status Register */
+
 /*
  * GEN2 specific changes
  */
 #define MFI_GEN2_EIM	0x00000005	/* GEN2 enable interrupt mask */
 #define MFI_GEN2_RM	0x00000001	/* reply GEN2 message interrupt */
=20
+/*
+ * skinny specific changes
+ */
+#define MFI_SKINNY_IDB	0x00	/* Inbound doorbell is at 0x00 for skinny */
+#define MFI_IQPL	0x000000c0
+#define MFI_IQPH	0x000000c4
+#define MFI_SKINNY_RM	0x00000001	/* reply skinny message interrupt */
+
 /* Bits for MFI_OSTS */
 #define MFI_OSTS_INTR_VALID	0x00000002
=20
+/* OCR specific flags */
+#define MFI_FIRMWARE_STATE_CHANGE	0x00000002
+#define MFI_STATE_CHANGE_INTERRUPT	0x00000004  /* MFI state change interrr=
upt */
+
 /*
  * Firmware state values.  Found in OMSG0 during initialization.
  */
@@ -119,6 +144,16 @@
 #define MFI_FWSTATE_FAULT		0xf0000000
 #define MFI_FWSTATE_MAXSGL_MASK		0x00ff0000
 #define MFI_FWSTATE_MAXCMD_MASK		0x0000ffff
+#define MFI_FWSTATE_HOSTMEMREQD_MASK	0x08000000
+#define MFI_FWSTATE_BOOT_MESSAGE_PENDING	0x90000000
+#define MFI_RESET_REQUIRED		0x00000001
+
+/* ThunderBolt Support */
+#define MFI_FWSTATE_TB_MASK		0xf0000000
+#define MFI_FWSTATE_TB_RESET		0x00000000
+#define MFI_FWSTATE_TB_READY		0x10000000
+#define MFI_FWSTATE_TB_OPERATIONAL	0x20000000
+#define MFI_FWSTATE_TB_FAULT		0x40000000
=20
 /*
  * Control bits to drive the card to ready state.  These go into the IDB
@@ -130,6 +165,12 @@
 #define MFI_FWINIT_CLEAR_HANDSHAKE 0x00000008 /* Respond to WAIT_HANDSHAKE=
 */
 #define MFI_FWINIT_HOTPLUG	0x00000010
=20
+/* ADP reset flags */
+#define MFI_STOP_ADP		0x00000020
+#define MFI_ADP_RESET		0x00000040
+#define DIAG_WRITE_ENABLE	0x00000080
+#define DIAG_RESET_ADAPTER	0x00000004
+
 /* MFI Commands */
 typedef enum {
 	MFI_CMD_INIT =3D		0x00,
@@ -146,6 +187,7 @@
 /* Direct commands */
 typedef enum {
 	MFI_DCMD_CTRL_GETINFO =3D		0x01010000,
+	MFI_DCMD_CTRL_MFI_HOST_MEM_ALLOC =3D0x0100e100,
 	MFI_DCMD_CTRL_MFC_DEFAULTS_GET =3D0x010e0201,
 	MFI_DCMD_CTRL_MFC_DEFAULTS_SET =3D0x010e0202,
 	MFI_DCMD_CTRL_FLUSHCACHE =3D	0x01101000,
@@ -164,6 +206,7 @@
 	MFI_DCMD_FLASH_FW_FLASH =3D	0x010f0300,
 	MFI_DCMD_FLASH_FW_CLOSE =3D	0x010f0400,
 	MFI_DCMD_PD_GET_LIST =3D		0x02010000,
+	MFI_DCMD_PD_LIST_QUERY =3D	0x02010100,
 	MFI_DCMD_PD_GET_INFO =3D 		0x02020000,
 	MFI_DCMD_PD_STATE_SET =3D		0x02030100,
 	MFI_DCMD_PD_REBUILD_START =3D	0x02040100,
@@ -173,6 +216,8 @@
 	MFI_DCMD_PD_GET_PROGRESS =3D	0x02060000,
 	MFI_DCMD_PD_LOCATE_START =3D	0x02070100,
 	MFI_DCMD_PD_LOCATE_STOP =3D	0x02070200,
+	MFI_DCMD_LD_MAP_GET_INFO =3D	0x0300e101,
+	MFI_DCMD_LD_SYNC =3D		0x0300e102,
 	MFI_DCMD_LD_GET_LIST =3D		0x03010000,
 	MFI_DCMD_LD_GET_INFO =3D		0x03020000,
 	MFI_DCMD_LD_GET_PROP =3D		0x03030000,
@@ -183,7 +228,7 @@
 	MFI_DCMD_CFG_ADD =3D		0x04020000,
 	MFI_DCMD_CFG_CLEAR =3D		0x04030000,
 	MFI_DCMD_CFG_MAKE_SPARE =3D	0x04040000,
-	MFI_DCMD_CFG_REMOVE_SPARE =3D	0x04050000,=09
+	MFI_DCMD_CFG_REMOVE_SPARE =3D	0x04050000,
 	MFI_DCMD_CFG_FOREIGN_IMPORT =3D	0x04060400,
 	MFI_DCMD_BBU_GET_STATUS =3D	0x05010000,
 	MFI_DCMD_BBU_GET_CAPACITY_INFO =3D0x05020000,
@@ -213,6 +258,36 @@
 #define MFI_FRAME_DIR_WRITE			0x0008
 #define MFI_FRAME_DIR_READ			0x0010
 #define MFI_FRAME_DIR_BOTH			0x0018
+#define MFI_FRAME_IEEE_SGL			0x0020
+
+/* ThunderBolt Specific */
+
+/*
+ * Pre-TB command size and TB command size.
+ * We will be checking it at the load time for the time being
+ */
+#define MR_COMMAND_SIZE (MFI_FRAME_SIZE*20) /* 1280 bytes */
+
+#define MEGASAS_THUNDERBOLT_MSG_ALLIGNMENT  256
+/*
+ * We are defining only 128 byte message to reduce memory move over head
+ * and also it will reduce the SRB extension size by 128byte compared with
+ * 256 message size
+ */
+#define MEGASAS_THUNDERBOLT_NEW_MSG_SIZE	256
+#define MEGASAS_THUNDERBOLT_MAX_COMMANDS	1024
+#define MEGASAS_THUNDERBOLT_MAX_REPLY_COUNT	1024
+#define MEGASAS_THUNDERBOLT_REPLY_SIZE		8
+#define MEGASAS_THUNDERBOLT_MAX_CHAIN_COUNT	1
+#define MEGASAS_MAX_SZ_CHAIN_FRAME		1024
+
+#define MPI2_FUNCTION_PASSTHRU_IO_REQUEST       0xF0
+#define MPI2_FUNCTION_LD_IO_REQUEST             0xF1
+
+#define MR_INTERNAL_MFI_FRAMES_SMID             1
+#define MR_CTRL_EVENT_WAIT_SMID                 2
+#define MR_INTERNAL_DRIVER_RESET_SMID           3
+
=20
 /* MFI Status codes */
 typedef enum {
@@ -325,6 +400,10 @@
 	MR_EVT_ARGS_ECC
 } mfi_evt_args;
=20
+#define MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED	0x0152
+#define MR_EVT_PD_REMOVED			0x0070
+#define MR_EVT_PD_INSERTED			0x005b
+
 typedef enum {
 	MR_LD_CACHE_WRITE_BACK =3D	0x01,
 	MR_LD_CACHE_WRITE_ADAPTIVE =3D	0x02,
@@ -352,6 +431,15 @@
 	MR_PD_CACHE_DISABLE =3D		2
 } mfi_pd_cache;
=20
+typedef enum {
+	MR_PD_QUERY_TYPE_ALL =3D		0,
+	MR_PD_QUERY_TYPE_STATE =3D	1,
+	MR_PD_QUERY_TYPE_POWER_STATE =3D	2,
+	MR_PD_QUERY_TYPE_MEDIA_TYPE =3D	3,
+	MR_PD_QUERY_TYPE_SPEED =3D	4,
+	MR_PD_QUERY_TYPE_EXPOSED_TO_HOST =3D 5 /*query for system drives */
+} mfi_pd_query_type;
+
 /*
  * Other propertities and definitions
  */
@@ -384,9 +472,16 @@
 	uint32_t	len;
 } __packed;
=20
+struct mfi_sg_skinny {
+	uint64_t	addr;
+	uint32_t	len;
+	uint32_t	flag;
+} __packed;
+
 union mfi_sgl {
-	struct mfi_sg32	sg32[1];
-	struct mfi_sg64	sg64[1];
+	struct mfi_sg32		sg32[1];
+	struct mfi_sg64		sg64[1];
+	struct mfi_sg_skinny	sg_skinny[1];
 } __packed;
=20
 /* Message frames.  All messages have a common header */
@@ -400,6 +495,10 @@
 	uint8_t		cdb_len;
 	uint8_t		sg_count;
 	uint32_t	context;
+	/*
+	 * pad0 is MSI Specific. Not used by Driver. Zero the value before
+	 * sending the command to f/w.
+	 */
 	uint32_t	pad0;
 	uint16_t	flags;
 #define MFI_FRAME_DATAOUT	0x08
@@ -414,9 +513,29 @@
 	uint32_t	qinfo_new_addr_hi;
 	uint32_t	qinfo_old_addr_lo;
 	uint32_t	qinfo_old_addr_hi;
-	uint32_t	reserved[6];
+	// Start LSIP200113393
+	uint32_t	driver_ver_lo;      /*28h */
+	uint32_t	driver_ver_hi;      /*2Ch */
+
+	uint32_t	reserved[4];
+	// End LSIP200113393
 } __packed;
=20
+/*
+ * Define MFI Address Context union.
+ */
+#ifdef MFI_ADDRESS_IS_uint64_t
+    typedef uint64_t     MFI_ADDRESS;
+#else
+    typedef union _MFI_ADDRESS {
+        struct {
+            uint32_t     addressLow;
+            uint32_t     addressHigh;
+        } u;
+        uint64_t     address;
+    } MFI_ADDRESS, *PMFI_ADDRESS;
+#endif
+
 #define MFI_IO_FRAME_SIZE 40
 struct mfi_io_frame {
 	struct mfi_frame_header	header;
@@ -447,10 +566,11 @@
 struct mfi_abort_frame {
 	struct mfi_frame_header header;
 	uint32_t	abort_context;
-	uint32_t	pad;
+	/* pad is changed to reserved.*/
+	uint32_t	reserved0;
 	uint32_t	abort_mfi_addr_lo;
 	uint32_t	abort_mfi_addr_hi;
-	uint32_t	reserved[6];
+	uint32_t	reserved1[6];
 } __packed;
=20
 struct mfi_smp_frame {
@@ -475,6 +595,7 @@
 union mfi_frame {
 	struct mfi_frame_header header;
 	struct mfi_init_frame	init;
+	/* ThunderBolt Initialization */
 	struct mfi_io_frame	io;
 	struct mfi_pass_frame	pass;
 	struct mfi_dcmd_frame	dcmd;
@@ -524,7 +645,61 @@
 	uint16_t	ecc_bucket_leak_rate;
 	uint8_t		restore_hotspare_on_insertion;
 	uint8_t		expose_encl_devices;
-	uint8_t		reserved[38];
+	uint8_t		maintainPdFailHistory;
+	uint8_t		disallowHostRequestReordering;
+	/* set TRUE to abort CC on detecting an inconsistency */
+	uint8_t		abortCCOnError;
+	/* load balance mode (MR_LOAD_BALANCE_MODE) */
+	uint8_t		loadBalanceMode;
+	/*
+	 * 0 - use auto detect logic of backplanes like SGPIO, i2c SEP using
+	 *     h/w mechansim like GPIO pins
+	 * 1 - disable auto detect SGPIO,
+	 * 2 - disable i2c SEP auto detect
+	 * 3 - disable both auto detect
+	 */
+	uint8_t		disableAutoDetectBackplane;
+	/*
+	 * % of source LD to be reserved for a VDs snapshot in snapshot
+	 * repository, for metadata and user data: 1=3D5%, 2=3D10%, 3=3D15% and s=
o on
+	 */
+	uint8_t		snapVDSpace;
+
+	/*
+	 * Add properties that can be controlled by a bit in the following
+	 * structure.
+	 */
+	struct {
+		/* set TRUE to disable copyBack (0=3Dcopback enabled) */
+		uint32_t	copyBackDisabled		:1;
+		uint32_t	SMARTerEnabled			:1;
+		uint32_t	prCorrectUnconfiguredAreas	:1;
+		uint32_t	useFdeOnly			:1;
+		uint32_t	disableNCQ			:1;
+		uint32_t	SSDSMARTerEnabled		:1;
+		uint32_t	SSDPatrolReadEnabled		:1;
+		uint32_t	enableSpinDownUnconfigured	:1;
+		uint32_t	autoEnhancedImport		:1;
+		uint32_t	enableSecretKeyControl		:1;
+		uint32_t	disableOnlineCtrlReset		:1;
+		uint32_t	allowBootWithPinnedCache	:1;
+		uint32_t	disableSpinDownHS		:1;
+		uint32_t	enableJBOD			:1;
+		uint32_t	reserved			:18;
+	} OnOffProperties;
+	/*
+	 * % of source LD to be reserved for auto snapshot in snapshot
+	 * repository, for metadata and user data: 1=3D5%, 2=3D10%, 3=3D15% and s=
o on.
+	 */
+	uint8_t		autoSnapVDSpace;
+	/*
+	 * Snapshot writeable VIEWs capacity as a % of source LD capacity:
+	 * 0=3DREAD only, 1=3D5%, 2=3D10%, 3=3D15% and so on.
+	 */
+	uint8_t		viewSpace;
+	/* # of idle minutes before device is spun down (0=3Duse FW defaults) */
+	uint16_t	spinDownTime;
+	uint8_t		reserved[24];
 } __packed;
=20
 /* PCI information about the card. */
@@ -964,10 +1139,11 @@
 	uint64_t		sas_addr[2];
 } __packed;
=20
+#define MAX_SYS_PDS 240
 struct mfi_pd_list {
 	uint32_t		size;
 	uint32_t		count;
-	struct mfi_pd_address	addr[0];
+	struct mfi_pd_address	addr[MAX_SYS_PDS];
 } __packed;
=20
 enum mfi_pd_state {
@@ -982,6 +1158,12 @@
 	MFI_PD_STATE_SYSTEM =3D 0x40
 };
=20
+/*
+ * "SYSTEM" disk appears to be "JBOD" support from the RAID controller.
+ * Adding a #define to denote this.
+ */
+#define MFI_PD_STATE_JBOD MFI_PD_STATE_SYSTEM
+
 union mfi_ld_ref {
 	struct {
 		uint8_t		target_id;
@@ -1040,7 +1222,9 @@
 #define	MFI_LD_PARAMS_INIT_QUICK	1
 #define	MFI_LD_PARAMS_INIT_FULL		2
 	uint8_t			is_consistent;
-	uint8_t			reserved[23];
+	uint8_t			reserved1[6];
+	uint8_t			isSSCD;
+	uint8_t			reserved2[16];
 } __packed;
=20
 struct mfi_ld_progress {
@@ -1081,7 +1265,7 @@
 	uint8_t			reserved2[16];
 } __packed;
=20
-#define MAX_ARRAYS 16
+#define MFI_MAX_ARRAYS 16
 struct mfi_spare {
 	union mfi_pd_ref	ref;
 	uint8_t			spare_type;
@@ -1090,9 +1274,10 @@
 #define	MFI_SPARE_ENCL_AFFINITY	(1 << 2)
 	uint8_t			reserved[2];
 	uint8_t			array_count;
-	uint16_t		array_ref[MAX_ARRAYS];
+	uint16_t		array_ref[MFI_MAX_ARRAYS];
 } __packed;
=20
+#define MFI_MAX_ROW_SIZE 32
 struct mfi_array {
 	uint64_t			size;
 	uint8_t				num_drives;
@@ -1106,7 +1291,7 @@
 			uint8_t		pd;
 			uint8_t		slot;
 		} encl;
-	} pd[0];
+	} pd[MFI_MAX_ROW_SIZE];
 } __packed;
=20
 struct mfi_config_data {
@@ -1182,7 +1367,7 @@
 	uint8_t			battery_type;
 #define	MFI_BBU_TYPE_NONE	0
 #define	MFI_BBU_TYPE_IBBU	1
-#define	MFI_BBU_TYPE_BBU	2=09
+#define	MFI_BBU_TYPE_BBU	2
 	uint8_t			reserved;
 	uint16_t		voltage;
 	int16_t			current;
@@ -1230,6 +1415,450 @@
 	uint32_t		clear_freq;
 };
=20
+/* ThunderBolt support */
+
+/*
+ * Raid Context structure which describes MegaRAID specific IO Paramenters
+ * This resides at offset 0x60 where the SGL normally starts in MPT IO Fra=
mes
+ */
+typedef struct _MPI2_SCSI_IO_VENDOR_UNIQUE {
+	uint16_t	resvd0;		/* 0x00 - 0x01 */
+	uint16_t	timeoutValue;	/* 0x02 - 0x03 */
+	uint8_t		regLockFlags;
+	uint8_t		armId;
+	uint16_t	TargetID;	/* 0x06 - 0x07 */
+
+	uint64_t	RegLockLBA;	/* 0x08 - 0x0F */
+
+	uint32_t	RegLockLength;	/* 0x10 - 0x13 */
+
+	uint16_t	SMID;		/* 0x14 - 0x15 nextLMId */
+	uint8_t		exStatus;	/* 0x16 */
+	uint8_t		Status;		/* 0x17 status */
+
+	uint8_t		RAIDFlags;	/* 0x18 */
+	uint8_t		numSGE;		/* 0x19 numSge */
+	uint16_t	configSeqNum;	/* 0x1A - 0x1B */
+	uint8_t		spanArm;	/* 0x1C */
+	uint8_t		resvd2[3];	/* 0x1D - 0x1F */
+} MPI2_SCSI_IO_VENDOR_UNIQUE, MPI25_SCSI_IO_VENDOR_UNIQUE;
+
+/*************************************************************************=
****
+*
+*        Message Functions
+*
+**************************************************************************=
***/
+
+#define NA_MPI2_FUNCTION_SCSI_IO_REQUEST            (0x00) /* SCSI IO */
+#define MPI2_FUNCTION_SCSI_TASK_MGMT                (0x01) /* SCSI Task Ma=
nagement */
+#define MPI2_FUNCTION_IOC_INIT                      (0x02) /* IOC Init */
+#define MPI2_FUNCTION_IOC_FACTS                     (0x03) /* IOC Facts */
+#define MPI2_FUNCTION_CONFIG                        (0x04) /* Configuratio=
n */
+#define MPI2_FUNCTION_PORT_FACTS                    (0x05) /* Port Facts */
+#define MPI2_FUNCTION_PORT_ENABLE                   (0x06) /* Port Enable =
*/
+#define MPI2_FUNCTION_EVENT_NOTIFICATION            (0x07) /* Event Notifi=
cation */
+#define MPI2_FUNCTION_EVENT_ACK                     (0x08) /* Event Acknow=
ledge */
+#define MPI2_FUNCTION_FW_DOWNLOAD                   (0x09) /* FW Download =
*/
+#define MPI2_FUNCTION_TARGET_ASSIST                 (0x0B) /* Target Assis=
t */
+#define MPI2_FUNCTION_TARGET_STATUS_SEND            (0x0C) /* Target Statu=
s Send */
+#define MPI2_FUNCTION_TARGET_MODE_ABORT             (0x0D) /* Target Mode =
Abort */
+#define MPI2_FUNCTION_FW_UPLOAD                     (0x12) /* FW Upload */
+#define MPI2_FUNCTION_RAID_ACTION                   (0x15) /* RAID Action =
*/
+#define MPI2_FUNCTION_RAID_SCSI_IO_PASSTHROUGH      (0x16) /* SCSI IO RAID=
 Passthrough */
+#define MPI2_FUNCTION_TOOLBOX                       (0x17) /* Toolbox */
+#define MPI2_FUNCTION_SCSI_ENCLOSURE_PROCESSOR      (0x18) /* SCSI Enclosu=
re Processor */
+#define MPI2_FUNCTION_SMP_PASSTHROUGH               (0x1A) /* SMP Passthro=
ugh */
+#define MPI2_FUNCTION_SAS_IO_UNIT_CONTROL           (0x1B) /* SAS IO Unit =
Control */
+#define MPI2_FUNCTION_SATA_PASSTHROUGH              (0x1C) /* SATA Passthr=
ough */
+#define MPI2_FUNCTION_DIAG_BUFFER_POST              (0x1D) /* Diagnostic B=
uffer Post */
+#define MPI2_FUNCTION_DIAG_RELEASE                  (0x1E) /* Diagnostic R=
elease */
+#define MPI2_FUNCTION_TARGET_CMD_BUF_BASE_POST      (0x24) /* Target Comma=
nd Buffer Post Base */
+#define MPI2_FUNCTION_TARGET_CMD_BUF_LIST_POST      (0x25) /* Target Comma=
nd Buffer Post List */
+#define MPI2_FUNCTION_RAID_ACCELERATOR              (0x2C) /* RAID Acceler=
ator */
+#define MPI2_FUNCTION_HOST_BASED_DISCOVERY_ACTION   (0x2F) /* Host Based D=
iscovery Action */
+#define MPI2_FUNCTION_PWR_MGMT_CONTROL              (0x30) /* Power Manage=
ment Control */
+#define MPI2_FUNCTION_MIN_PRODUCT_SPECIFIC          (0xF0) /* beginning of=
 product-specific range */
+#define MPI2_FUNCTION_MAX_PRODUCT_SPECIFIC          (0xFF) /* end of produ=
ct-specific range */
+
+/* Doorbell functions */
+#define MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET        (0x40)
+#define MPI2_FUNCTION_HANDSHAKE                     (0x42)
+
+/*************************************************************************=
****
+*
+*        MPI Version Definitions
+*
+**************************************************************************=
***/
+
+#define MPI2_VERSION_MAJOR                  (0x02)
+#define MPI2_VERSION_MINOR                  (0x00)
+#define MPI2_VERSION_MAJOR_MASK             (0xFF00)
+#define MPI2_VERSION_MAJOR_SHIFT            (8)
+#define MPI2_VERSION_MINOR_MASK             (0x00FF)
+#define MPI2_VERSION_MINOR_SHIFT            (0)
+#define MPI2_VERSION ((MPI2_VERSION_MAJOR << MPI2_VERSION_MAJOR_SHIFT) |  =
 \
+                                      MPI2_VERSION_MINOR)
+
+#define MPI2_VERSION_02_00                  (0x0200)
+
+/* versioning for this MPI header set */
+#define MPI2_HEADER_VERSION_UNIT            (0x10)
+#define MPI2_HEADER_VERSION_DEV             (0x00)
+#define MPI2_HEADER_VERSION_UNIT_MASK       (0xFF00)
+#define MPI2_HEADER_VERSION_UNIT_SHIFT      (8)
+#define MPI2_HEADER_VERSION_DEV_MASK        (0x00FF)
+#define MPI2_HEADER_VERSION_DEV_SHIFT       (0)
+#define MPI2_HEADER_VERSION ((MPI2_HEADER_VERSION_UNIT << 8) |		\
+					MPI2_HEADER_VERSION_DEV)
+
+
+/* IOCInit Request message */
+struct MPI2_IOC_INIT_REQUEST {
+	uint8_t		WhoInit;                        /* 0x00 */
+	uint8_t		Reserved1;                      /* 0x01 */
+	uint8_t		ChainOffset;                    /* 0x02 */
+	uint8_t		Function;                       /* 0x03 */
+	uint16_t	Reserved2;                      /* 0x04 */
+	uint8_t		Reserved3;                      /* 0x06 */
+	uint8_t		MsgFlags;                       /* 0x07 */
+	uint8_t		VP_ID;                          /* 0x08 */
+	uint8_t		VF_ID;                          /* 0x09 */
+	uint16_t	Reserved4;                      /* 0x0A */
+	uint16_t	MsgVersion;                     /* 0x0C */
+	uint16_t	HeaderVersion;                  /* 0x0E */
+	uint32_t	Reserved5;                      /* 0x10 */
+	uint16_t	Reserved6;                      /* 0x14 */
+	uint8_t		Reserved7;                      /* 0x16 */
+	uint8_t		HostMSIxVectors;                /* 0x17 */
+	uint16_t	Reserved8;                      /* 0x18 */
+	uint16_t	SystemRequestFrameSize;         /* 0x1A */
+	uint16_t	ReplyDescriptorPostQueueDepth;  /* 0x1C */
+	uint16_t	ReplyFreeQueueDepth;            /* 0x1E */
+	uint32_t	SenseBufferAddressHigh;         /* 0x20 */
+	uint32_t	SystemReplyAddressHigh;         /* 0x24 */
+	uint64_t	SystemRequestFrameBaseAddress;  /* 0x28 */
+	uint64_t	ReplyDescriptorPostQueueAddress;/* 0x30 */
+	uint64_t	ReplyFreeQueueAddress;          /* 0x38 */
+	uint64_t	TimeStamp;                      /* 0x40 */
+};
+
+/* WhoInit values */
+#define MPI2_WHOINIT_NOT_INITIALIZED            (0x00)
+#define MPI2_WHOINIT_SYSTEM_BIOS                (0x01)
+#define MPI2_WHOINIT_ROM_BIOS                   (0x02)
+#define MPI2_WHOINIT_PCI_PEER                   (0x03)
+#define MPI2_WHOINIT_HOST_DRIVER                (0x04)
+#define MPI2_WHOINIT_MANUFACTURER               (0x05)
+
+struct MPI2_SGE_CHAIN_UNION {
+	uint16_t	Length;
+	uint8_t		NextChainOffset;
+	uint8_t		Flags;
+	union {
+		uint32_t	Address32;
+		uint64_t	Address64;
+	} u;
+};
+
+struct MPI2_IEEE_SGE_SIMPLE32 {
+	uint32_t	Address;
+	uint32_t	FlagsLength;
+};
+
+struct MPI2_IEEE_SGE_SIMPLE64 {
+	uint64_t	Address;
+	uint32_t	Length;
+	uint16_t	Reserved1;
+	uint8_t		Reserved2;
+	uint8_t		Flags;
+};
+
+typedef union _MPI2_IEEE_SGE_SIMPLE_UNION {
+	struct MPI2_IEEE_SGE_SIMPLE32	Simple32;
+	struct MPI2_IEEE_SGE_SIMPLE64	Simple64;
+} MPI2_IEEE_SGE_SIMPLE_UNION;
+
+typedef struct _MPI2_SGE_SIMPLE_UNION {
+	uint32_t	FlagsLength;
+	union {
+		uint32_t	Address32;
+		uint64_t	Address64;
+	} u;
+} MPI2_SGE_SIMPLE_UNION;
+
+/*************************************************************************=
***
+*  IEEE SGE field definitions and masks
+**************************************************************************=
**/
+
+/* Flags field bit definitions */
+
+#define MPI2_IEEE_SGE_FLAGS_ELEMENT_TYPE_MASK   (0x80)
+
+#define MPI2_IEEE32_SGE_FLAGS_SHIFT             (24)
+
+#define MPI2_IEEE32_SGE_LENGTH_MASK             (0x00FFFFFF)
+
+/* Element Type */
+
+#define MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT      (0x00)
+#define MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT       (0x80)
+
+/* Data Location Address Space */
+
+#define MPI2_IEEE_SGE_FLAGS_ADDR_MASK           (0x03)
+#define MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR         (0x00)
+#define MPI2_IEEE_SGE_FLAGS_IOCDDR_ADDR         (0x01)
+#define MPI2_IEEE_SGE_FLAGS_IOCPLB_ADDR         (0x02)
+#define MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR      (0x03)
+
+/* Address Size */
+
+#define MPI2_SGE_FLAGS_32_BIT_ADDRESSING        (0x00)
+#define MPI2_SGE_FLAGS_64_BIT_ADDRESSING        (0x02)
+
+/*******************/
+/* SCSI IO Control bits */
+#define MPI2_SCSIIO_CONTROL_ADDCDBLEN_MASK      (0xFC000000)
+#define MPI2_SCSIIO_CONTROL_ADDCDBLEN_SHIFT     (26)
+
+#define MPI2_SCSIIO_CONTROL_DATADIRECTION_MASK  (0x03000000)
+#define MPI2_SCSIIO_CONTROL_NODATATRANSFER      (0x00000000)
+#define MPI2_SCSIIO_CONTROL_WRITE               (0x01000000)
+#define MPI2_SCSIIO_CONTROL_READ                (0x02000000)
+#define MPI2_SCSIIO_CONTROL_BIDIRECTIONAL       (0x03000000)
+
+#define MPI2_SCSIIO_CONTROL_TASKPRI_MASK        (0x00007800)
+#define MPI2_SCSIIO_CONTROL_TASKPRI_SHIFT       (11)
+
+#define MPI2_SCSIIO_CONTROL_TASKATTRIBUTE_MASK  (0x00000700)
+#define MPI2_SCSIIO_CONTROL_SIMPLEQ             (0x00000000)
+#define MPI2_SCSIIO_CONTROL_HEADOFQ             (0x00000100)
+#define MPI2_SCSIIO_CONTROL_ORDEREDQ            (0x00000200)
+#define MPI2_SCSIIO_CONTROL_ACAQ                (0x00000400)
+
+#define MPI2_SCSIIO_CONTROL_TLR_MASK            (0x000000C0)
+#define MPI2_SCSIIO_CONTROL_NO_TLR              (0x00000000)
+#define MPI2_SCSIIO_CONTROL_TLR_ON              (0x00000040)
+#define MPI2_SCSIIO_CONTROL_TLR_OFF             (0x00000080)
+
+/*******************/
+
+typedef struct {
+	uint8_t		CDB[20];                    /* 0x00 */
+	uint32_t	PrimaryReferenceTag;        /* 0x14 */
+	uint16_t	PrimaryApplicationTag;      /* 0x18 */
+	uint16_t	PrimaryApplicationTagMask;  /* 0x1A */
+	uint32_t	TransferLength;             /* 0x1C */
+} MPI2_SCSI_IO_CDB_EEDP32;
+
+
+typedef union _MPI2_IEEE_SGE_CHAIN_UNION {
+	struct MPI2_IEEE_SGE_SIMPLE32	Chain32;
+	struct MPI2_IEEE_SGE_SIMPLE64	Chain64;
+} MPI2_IEEE_SGE_CHAIN_UNION;
+
+typedef union _MPI2_SIMPLE_SGE_UNION {
+	MPI2_SGE_SIMPLE_UNION		MpiSimple;
+	MPI2_IEEE_SGE_SIMPLE_UNION	IeeeSimple;
+} MPI2_SIMPLE_SGE_UNION;
+
+typedef union _MPI2_SGE_IO_UNION {
+	MPI2_SGE_SIMPLE_UNION		MpiSimple;
+	struct MPI2_SGE_CHAIN_UNION	MpiChain;
+	MPI2_IEEE_SGE_SIMPLE_UNION	IeeeSimple;
+	MPI2_IEEE_SGE_CHAIN_UNION	IeeeChain;
+} MPI2_SGE_IO_UNION;
+
+typedef union {
+	uint8_t			CDB32[32];
+	MPI2_SCSI_IO_CDB_EEDP32	EEDP32;
+	MPI2_SGE_SIMPLE_UNION	SGE;
+} MPI2_SCSI_IO_CDB_UNION;
+
+
+/* MPI 2.5 SGLs */
+
+#define MPI25_IEEE_SGE_FLAGS_END_OF_LIST        (0x40)
+
+typedef struct _MPI25_IEEE_SGE_CHAIN64 {
+	uint64_t	Address;
+	uint32_t	Length;
+	uint16_t	Reserved1;
+	uint8_t		NextChainOffset;
+	uint8_t		Flags;
+} MPI25_IEEE_SGE_CHAIN64, *pMpi25IeeeSgeChain64_t;
+
+/* use MPI2_IEEE_SGE_FLAGS_ defines for the Flags field */
+
+
+/********/
+
+/*
+ * RAID SCSI IO Request Message
+ * Total SGE count will be one less than  _MPI2_SCSI_IO_REQUEST
+ */
+struct mfi_mpi2_request_raid_scsi_io {
+	uint16_t		DevHandle;                      /* 0x00 */
+	uint8_t			ChainOffset;                    /* 0x02 */
+	uint8_t			Function;                       /* 0x03 */
+	uint16_t		Reserved1;                      /* 0x04 */
+	uint8_t			Reserved2;                      /* 0x06 */
+	uint8_t			MsgFlags;                       /* 0x07 */
+	uint8_t			VP_ID;                          /* 0x08 */
+	uint8_t			VF_ID;                          /* 0x09 */
+	uint16_t		Reserved3;                      /* 0x0A */
+	uint32_t		SenseBufferLowAddress;          /* 0x0C */
+	uint16_t		SGLFlags;                       /* 0x10 */
+	uint8_t			SenseBufferLength;              /* 0x12 */
+	uint8_t			Reserved4;                      /* 0x13 */
+	uint8_t			SGLOffset0;                     /* 0x14 */
+	uint8_t			SGLOffset1;                     /* 0x15 */
+	uint8_t			SGLOffset2;                     /* 0x16 */
+	uint8_t			SGLOffset3;                     /* 0x17 */
+	uint32_t		SkipCount;                      /* 0x18 */
+	uint32_t		DataLength;                     /* 0x1C */
+	uint32_t		BidirectionalDataLength;        /* 0x20 */
+	uint16_t		IoFlags;                        /* 0x24 */
+	uint16_t		EEDPFlags;                      /* 0x26 */
+	uint32_t		EEDPBlockSize;                  /* 0x28 */
+	uint32_t		SecondaryReferenceTag;          /* 0x2C */
+	uint16_t		SecondaryApplicationTag;        /* 0x30 */
+	uint16_t		ApplicationTagTranslationMask;  /* 0x32 */
+	uint8_t			LUN[8];                         /* 0x34 */
+	uint32_t		Control;                        /* 0x3C */
+	MPI2_SCSI_IO_CDB_UNION	CDB;                            /* 0x40 */
+	MPI2_SCSI_IO_VENDOR_UNIQUE	RaidContext;              /* 0x60 */
+	MPI2_SGE_IO_UNION	SGL;                            /* 0x80 */
+} __packed;
+
+/*
+ * MPT RAID MFA IO Descriptor.
+ */
+typedef struct _MFI_RAID_MFA_IO_DESCRIPTOR {
+	uint32_t	RequestFlags : 8;
+	uint32_t	MessageAddress1 : 24; /* bits 31:8*/
+	uint32_t	MessageAddress2;      /* bits 61:32 */
+} MFI_RAID_MFA_IO_REQUEST_DESCRIPTOR,*PMFI_RAID_MFA_IO_REQUEST_DESCRIPTOR;
+
+struct mfi_mpi2_request_header {
+	uint8_t		RequestFlags;       /* 0x00 */
+	uint8_t		MSIxIndex;          /* 0x01 */
+	uint16_t	SMID;               /* 0x02 */
+	uint16_t	LMID;               /* 0x04 */
+};
+
+/* defines for the RequestFlags field */
+#define MPI2_REQ_DESCRIPT_FLAGS_TYPE_MASK               (0x0E)
+#define MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO                 (0x00)
+#define MPI2_REQ_DESCRIPT_FLAGS_SCSI_TARGET             (0x02)
+#define MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY           (0x06)
+#define MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE            (0x08)
+#define MPI2_REQ_DESCRIPT_FLAGS_RAID_ACCELERATOR        (0x0A)
+
+#define MPI2_REQ_DESCRIPT_FLAGS_IOC_FIFO_MARKER (0x01)
+
+struct mfi_mpi2_request_high_priority {
+	struct mfi_mpi2_request_header	header;
+	uint16_t			reserved;
+};
+
+struct mfi_mpi2_request_scsi_io {
+	struct mfi_mpi2_request_header	header;
+	uint16_t			scsi_io_dev_handle;
+};
+
+struct mfi_mpi2_request_scsi_target {
+	struct mfi_mpi2_request_header	header;
+	uint16_t			scsi_target_io_index;
+};
+
+/* Request Descriptors */
+union mfi_mpi2_request_descriptor {
+	struct mfi_mpi2_request_header		header;
+	struct mfi_mpi2_request_high_priority	high_priority;
+	struct mfi_mpi2_request_scsi_io		scsi_io;
+	struct mfi_mpi2_request_scsi_target	scsi_target;
+	uint64_t				words;
+};
+
+
+struct mfi_mpi2_reply_header {
+	uint8_t		ReplyFlags;                 /* 0x00 */
+	uint8_t		MSIxIndex;                  /* 0x01 */
+	uint16_t	SMID;                       /* 0x02 */
+};
+
+/* defines for the ReplyFlags field */
+#define MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK                   (0x0F)
+#define MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS             (0x00)
+#define MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY               (0x01)
+#define MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS        (0x02)
+#define MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER       (0x03)
+#define MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS    (0x05)
+#define MPI2_RPY_DESCRIPT_FLAGS_UNUSED                      (0x0F)
+
+/* values for marking a reply descriptor as unused */
+#define MPI2_RPY_DESCRIPT_UNUSED_WORD0_MARK             (0xFFFFFFFF)
+#define MPI2_RPY_DESCRIPT_UNUSED_WORD1_MARK             (0xFFFFFFFF)
+
+struct mfi_mpi2_reply_default {
+	struct mfi_mpi2_reply_header	header;
+	uint32_t			DescriptorTypeDependent2;
+};
+
+struct mfi_mpi2_reply_address {
+	struct mfi_mpi2_reply_header	header;
+	uint32_t			ReplyFrameAddress;
+};
+
+struct mfi_mpi2_reply_scsi_io {
+	struct mfi_mpi2_reply_header	header;
+	uint16_t			TaskTag;		/* 0x04 */
+	uint16_t			Reserved1;		/* 0x06 */
+};
+
+struct mfi_mpi2_reply_target_assist {
+	struct mfi_mpi2_reply_header	header;
+	uint8_t				SequenceNumber;		/* 0x04 */
+	uint8_t				Reserved1;		/* 0x04 */
+	uint16_t			IoIndex;		/* 0x06 */
+};
+
+struct mfi_mpi2_reply_target_cmd_buffer {
+	struct mfi_mpi2_reply_header	header;
+	uint8_t				SequenceNumber;		/* 0x04 */
+	uint8_t				Flags;			/* 0x04 */
+	uint16_t			InitiatorDevHandle;	/* 0x06 */
+	uint16_t			IoIndex;		/* 0x06 */
+};
+
+struct mfi_mpi2_reply_raid_accel {
+	struct mfi_mpi2_reply_header	header;
+	uint8_t				SequenceNumber;		/* 0x04 */
+	uint32_t			Reserved;		/* 0x04 */
+};
+
+/* union of Reply Descriptors */
+union mfi_mpi2_reply_descriptor {
+	struct mfi_mpi2_reply_header		header;
+	struct mfi_mpi2_reply_scsi_io		scsi_io;
+	struct mfi_mpi2_reply_target_assist	target_assist;
+	struct mfi_mpi2_reply_target_cmd_buffer	target_cmd;
+	struct mfi_mpi2_reply_raid_accel	raid_accel;
+	struct mfi_mpi2_reply_default		reply_default;
+	uint64_t				words;
+};
+
+struct IO_REQUEST_INFO {
+	uint64_t	ldStartBlock;
+	uint32_t	numBlocks;
+	uint16_t	ldTgtId;
+	uint8_t		isRead;
+	uint16_t	devHandle;
+	uint64_t	pdBlock;
+	uint8_t		fpOkForIo;
+};
+
 #define MFI_SCSI_MAX_TARGETS	128
 #define MFI_SCSI_MAX_LUNS	8
 #define MFI_SCSI_INITIATOR_ID	255
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mfi/mfivar.h
--- a/head/sys/dev/mfi/mfivar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mfi/mfivar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -54,11 +54,14 @@
 #define _MFIVAR_H
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mfi/mfivar.h 227562 2011-11-16 15:39:27Z =
jhb $");
+__FBSDID("$FreeBSD: head/sys/dev/mfi/mfivar.h 233877 2012-04-04 16:15:40Z =
jkim $");
=20
 #include <sys/lock.h>
 #include <sys/sx.h>
=20
+#include <sys/types.h>
+#include <sys/taskqueue.h>
+
 /*
  * SCSI structures and definitions are used from here, but no linking
  * requirements are made to CAM.
@@ -70,6 +73,8 @@
 	uint32_t		hw_ci;
 	uint32_t		hw_reply_q[1];
 };
+#define	MEGASAS_MAX_NAME	32
+#define	MEGASAS_VERSION		"4.23"
=20
 struct mfi_softc;
 struct disk;
@@ -80,9 +85,9 @@
 	time_t			cm_timestamp;
 	struct mfi_softc	*cm_sc;
 	union mfi_frame		*cm_frame;
-	uint32_t		cm_frame_busaddr;
+	bus_addr_t		cm_frame_busaddr;
 	struct mfi_sense	*cm_sense;
-	uint32_t		cm_sense_busaddr;
+	bus_addr_t		cm_sense_busaddr;
 	bus_dmamap_t		cm_dmamap;
 	union mfi_sgl		*cm_sg;
 	void			*cm_data;
@@ -101,6 +106,7 @@
 #define MFI_ON_MFIQ_BUSY	(1<<7)
 #define MFI_ON_MFIQ_MASK	((1<<5)|(1<<6)|(1<<7))
 	int			cm_aen_abort;
+	uint8_t			retry_for_fw_reset;
 	void			(* cm_complete)(struct mfi_command *cm);
 	void			*cm_private;
 	int			cm_index;
@@ -120,11 +126,42 @@
 #define	MFI_DISK_FLAGS_DISABLED	0x02
 };
=20
+struct mfi_system_pd {
+	TAILQ_ENTRY(mfi_system_pd) pd_link;
+	device_t	pd_dev;
+	int		pd_id;
+	int		pd_unit;
+	struct mfi_softc *pd_controller;
+	struct mfi_pd_info *pd_info;
+	struct disk	*pd_disk;
+	int		pd_flags;
+};
+
+struct mfi_evt_queue_elm {
+	TAILQ_ENTRY(mfi_evt_queue_elm)	link;
+	struct mfi_evt_detail		detail;
+};
+
 struct mfi_aen {
 	TAILQ_ENTRY(mfi_aen) aen_link;
 	struct proc			*p;
 };
=20
+struct mfi_skinny_dma_info {
+	bus_dma_tag_t			dmat[514];
+	bus_dmamap_t			dmamap[514];
+	uint32_t			mem[514];
+	int				noofmaps;
+};
+
+struct megasas_sge
+{
+	bus_addr_t			phys_addr;
+	uint32_t			length;
+};
+
+struct mfi_cmd_tbolt;
+
 struct mfi_softc {
 	device_t			mfi_dev;
 	int				mfi_flags;
@@ -135,11 +172,22 @@
 #define MFI_FLAGS_1064R		(1<<4)
 #define MFI_FLAGS_1078		(1<<5)
 #define MFI_FLAGS_GEN2		(1<<6)
+#define MFI_FLAGS_SKINNY	(1<<7)
+#define MFI_FLAGS_TBOLT		(1<<8)
+	// Start: LSIP200113393
+	bus_dma_tag_t			verbuf_h_dmat;
+	bus_dmamap_t			verbuf_h_dmamap;
+	uint32_t			verbuf_h_busaddr;
+	uint32_t			*verbuf;
+	void				*kbuff_arr[MAX_IOCTL_SGE];
+	bus_dma_tag_t			mfi_kbuff_arr_dmat[2];
+	bus_dmamap_t			mfi_kbuff_arr_dmamap[2];
+	bus_addr_t			mfi_kbuff_arr_busaddr[2];
=20
 	struct mfi_hwcomms		*mfi_comms;
 	TAILQ_HEAD(,mfi_command)	mfi_free;
 	TAILQ_HEAD(,mfi_command)	mfi_ready;
-	TAILQ_HEAD(,mfi_command)	mfi_busy;
+	TAILQ_HEAD(BUSYQ,mfi_command)	mfi_busy;
 	struct bio_queue_head		mfi_bioq;
 	struct mfi_qstat		mfi_qstat[MFIQ_COUNT];
=20
@@ -153,17 +201,27 @@
=20
 	bus_dma_tag_t			mfi_comms_dmat;
 	bus_dmamap_t			mfi_comms_dmamap;
-	uint32_t			mfi_comms_busaddr;
+	bus_addr_t			mfi_comms_busaddr;
=20
 	bus_dma_tag_t			mfi_frames_dmat;
 	bus_dmamap_t			mfi_frames_dmamap;
-	uint32_t			mfi_frames_busaddr;
+	bus_addr_t			mfi_frames_busaddr;
 	union mfi_frame			*mfi_frames;
=20
+	bus_dma_tag_t			mfi_tb_init_dmat;
+	bus_dmamap_t			mfi_tb_init_dmamap;
+	bus_addr_t			mfi_tb_init_busaddr;
+	bus_addr_t			mfi_tb_ioc_init_busaddr;
+	union mfi_frame			*mfi_tb_init;
+
+	TAILQ_HEAD(,mfi_evt_queue_elm)	mfi_evt_queue;
+	struct task			mfi_evt_task;
 	TAILQ_HEAD(,mfi_aen)		mfi_aen_pids;
 	struct mfi_command		*mfi_aen_cm;
+	struct mfi_command		*mfi_skinny_cm;
 	uint32_t			mfi_aen_triggered;
 	uint32_t			mfi_poll_waiting;
+	uint32_t			mfi_boot_seq_num;
 	struct selinfo			mfi_select;
 	int				mfi_delete_busy_volumes;
 	int				mfi_keep_deleted_volumes;
@@ -180,6 +238,13 @@
=20
 	struct intr_config_hook		mfi_ich;
 	eventhandler_tag		eh;
+	/* OCR flags */
+	uint8_t adpreset;
+	uint8_t issuepend_done;
+	uint8_t disableOnlineCtrlReset;
+	uint32_t mfiStatus;
+	uint32_t last_seq_num;
+	uint32_t volatile hw_crit_error;
=20
 	/*
 	 * Allocation for the command array.  Used as an indexable array to
@@ -196,7 +261,7 @@
 	 */
 	int				mfi_max_fw_cmds;
 	/*
-	 * How many S/G elements we'll ever actually use=20
+	 * How many S/G elements we'll ever actually use
 	 */
 	int				mfi_max_sge;
 	/*
@@ -215,6 +280,7 @@
 	uint32_t			mfi_max_io;
=20
 	TAILQ_HEAD(,mfi_disk)		mfi_ld_tqh;
+	TAILQ_HEAD(,mfi_system_pd)	mfi_syspd_tqh;
 	eventhandler_tag		mfi_eh;
 	struct cdev			*mfi_cdev;
=20
@@ -226,9 +292,98 @@
=20
 	/* Controller type specific interfaces */
 	void	(*mfi_enable_intr)(struct mfi_softc *sc);
+	void	(*mfi_disable_intr)(struct mfi_softc *sc);
 	int32_t	(*mfi_read_fw_status)(struct mfi_softc *sc);
 	int	(*mfi_check_clear_intr)(struct mfi_softc *sc);
- 	void	(*mfi_issue_cmd)(struct mfi_softc *sc,uint32_t bus_add,uint32_t fra=
me_cnt);
+	void	(*mfi_issue_cmd)(struct mfi_softc *sc, bus_addr_t bus_add,
+		    uint32_t frame_cnt);
+	int	(*mfi_adp_reset)(struct mfi_softc *sc);
+	int	(*mfi_adp_check_reset)(struct mfi_softc *sc);
+
+	/* ThunderBolt */
+	uint32_t			mfi_tbolt;
+	uint32_t			MFA_enabled;
+	uint64_t			map_id;
+	struct mfi_command 		*map_update_cmd;
+	/* Single Reply structure size */
+	uint16_t			reply_size;
+	/* Singler message size. */
+	uint16_t			raid_io_msg_size;
+	TAILQ_HEAD(TB, mfi_cmd_tbolt)	mfi_cmd_tbolt_tqh;
+	/* ThunderBolt base contiguous memory mapping. */
+	bus_dma_tag_t			mfi_tb_dmat;
+	bus_dmamap_t			mfi_tb_dmamap;
+	bus_addr_t			mfi_tb_busaddr;
+	/* ThunderBolt Contiguous DMA memory Mapping */
+	uint8_t	*			request_message_pool;
+	uint8_t *			request_message_pool_align;
+	uint8_t *			request_desc_pool;
+	//uint32_t			request_desc_busaddr;
+	bus_addr_t			request_msg_busaddr;
+	bus_addr_t			reply_frame_busaddr;
+	bus_addr_t			sg_frame_busaddr;
+	/* ThunderBolt IOC Init Descriptor */
+	bus_dma_tag_t			mfi_tb_ioc_init_dmat;
+	bus_dmamap_t			mfi_tb_ioc_init_dmamap;
+	uint8_t *			mfi_tb_ioc_init_desc;
+	struct mfi_cmd_tbolt		**mfi_cmd_pool_tbolt;
+	/* Virtual address of reply Frame Pool */
+	struct mfi_mpi2_reply_header*	reply_frame_pool;
+	struct mfi_mpi2_reply_header*	reply_frame_pool_align;
+
+	/* Last reply frame address */
+	uint8_t *			reply_pool_limit;
+	uint16_t			last_reply_idx;
+	uint8_t				max_SGEs_in_chain_message;
+	uint8_t				max_SGEs_in_main_message;
+	uint8_t				chain_offset_value_for_main_message;
+	uint8_t				chain_offset_value_for_mpt_ptmsg;
+};
+
+union desc_value {
+	uint64_t	word;
+	struct {
+		uint32_t	low;
+		uint32_t	high;
+	}u;
+};
+
+// TODO find the right definition
+#define XXX_MFI_CMD_OP_INIT2                    0x9
+/*
+ * Request descriptor types
+ */
+#define MFI_REQ_DESCRIPT_FLAGS_LD_IO           0x7
+#define MFI_REQ_DESCRIPT_FLAGS_MFA             0x1
+#define MFI_REQ_DESCRIPT_FLAGS_TYPE_SHIFT	0x1
+#define MFI_FUSION_FP_DEFAULT_TIMEOUT		0x14
+#define MFI_LOAD_BALANCE_FLAG			0x1
+#define MFI_DCMD_MBOX_PEND_FLAG			0x1
+
+//#define MR_PROT_INFO_TYPE_CONTROLLER	0x08
+#define	MEGASAS_SCSI_VARIABLE_LENGTH_CMD	0x7f
+#define MEGASAS_SCSI_SERVICE_ACTION_READ32	0x9
+#define MEGASAS_SCSI_SERVICE_ACTION_WRITE32	0xB
+#define	MEGASAS_SCSI_ADDL_CDB_LEN   		0x18
+#define MEGASAS_RD_WR_PROTECT_CHECK_ALL		0x20
+#define MEGASAS_RD_WR_PROTECT_CHECK_NONE	0x60
+#define MEGASAS_EEDPBLOCKSIZE			512
+struct mfi_cmd_tbolt {
+	union mfi_mpi2_request_descriptor *request_desc;
+	struct mfi_mpi2_request_raid_scsi_io *io_request;
+	bus_addr_t		io_request_phys_addr;
+	bus_addr_t		sg_frame_phys_addr;
+	bus_addr_t 		sense_phys_addr;
+	MPI2_SGE_IO_UNION	*sg_frame;
+	uint8_t			*sense;
+	TAILQ_ENTRY(mfi_cmd_tbolt) next;
+	/*
+	 * Context for a MFI frame.
+	 * Used to get the mfi cmd from list when a MFI cmd is completed
+	 */
+	uint32_t		sync_cmd_idx;
+	uint16_t		index;
+	uint8_t			status;
 };
=20
 extern int mfi_attach(struct mfi_softc *);
@@ -239,6 +394,30 @@
 extern int mfi_disk_disable(struct mfi_disk *);
 extern void mfi_disk_enable(struct mfi_disk *);
 extern int mfi_dump_blocks(struct mfi_softc *, int id, uint64_t, void *, i=
nt);
+extern int mfi_syspd_disable(struct mfi_system_pd *);
+extern void mfi_syspd_enable(struct mfi_system_pd *);
+extern int mfi_dump_syspd_blocks(struct mfi_softc *, int id, uint64_t, voi=
d *,
+    int);
+extern int mfi_transition_firmware(struct mfi_softc *sc);
+extern int mfi_aen_setup(struct mfi_softc *sc, uint32_t seq_start);
+extern void mfi_complete(struct mfi_softc *sc, struct mfi_command *cm);
+extern int mfi_mapcmd(struct mfi_softc *sc,struct mfi_command *cm);
+extern int mfi_wait_command(struct mfi_softc *sc, struct mfi_command *cm);
+extern void mfi_tbolt_enable_intr_ppc(struct mfi_softc *);
+extern void mfi_tbolt_disable_intr_ppc(struct mfi_softc *);
+extern int32_t mfi_tbolt_read_fw_status_ppc(struct mfi_softc *);
+extern int32_t mfi_tbolt_check_clear_intr_ppc(struct mfi_softc *);
+extern void mfi_tbolt_issue_cmd_ppc(struct mfi_softc *, bus_addr_t, uint32=
_t);
+extern void mfi_tbolt_init_globals(struct mfi_softc*);
+extern uint32_t mfi_tbolt_get_memory_requirement(struct mfi_softc *);
+extern int mfi_tbolt_init_desc_pool(struct mfi_softc *, uint8_t *, uint32_=
t);
+extern int mfi_tbolt_init_MFI_queue(struct mfi_softc *);
+extern void mfi_intr_tbolt(void *arg);
+extern int mfi_tbolt_alloc_cmd(struct mfi_softc *sc);
+extern int mfi_tbolt_send_frame(struct mfi_softc *sc, struct mfi_command *=
cm);
+extern int mfi_tbolt_adp_reset(struct mfi_softc *sc);
+extern int mfi_tbolt_reset(struct mfi_softc *sc);
+extern int mfi_tbolt_sync_map_info(struct mfi_softc *sc);
=20
 #define MFIQ_ADD(sc, qname)					\
 	do {							\
@@ -397,7 +576,11 @@
 MALLOC_DECLARE(M_MFIBUF);
 SYSCTL_DECL(_hw_mfi);
=20
+#define MFI_RESET_WAIT_TIME 180
 #define MFI_CMD_TIMEOUT 30
+#define MFI_SYS_PD_IO	0
+#define MFI_LD_IO	1
+#define MFI_SKINNY_MEMORY 0x02000000
 #define MFI_MAXPHYS (128 * 1024)
=20
 #ifdef MFI_DEBUG
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi.h
--- a/head/sys/dev/mpt/mpilib/mpi.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi.h 233425 2012-03-24 16:23:21Z mar=
ius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
@@ -33,7 +33,7 @@
  *          Title:  MPI Message independent structures and definitions
  *  Creation Date:  July 27, 2000
  *
- *    mpi.h Version:  01.05.13
+ *    mpi.h Version:  01.05.17
  *
  *  Version History
  *  ---------------
@@ -106,6 +106,10 @@
  *  03-27-06  01.05.11  Bumped MPI_HEADER_VERSION_UNIT.
  *  10-11-06  01.05.12  Bumped MPI_HEADER_VERSION_UNIT.
  *  05-24-07  01.05.13  Bumped MPI_HEADER_VERSION_UNIT.
+ *  08-07-07  01.05.14  Bumped MPI_HEADER_VERSION_UNIT.
+ *  01-15-08  01.05.15  Bumped MPI_HEADER_VERSION_UNIT.
+ *  03-28-08  01.05.16  Bumped MPI_HEADER_VERSION_UNIT.
+ *  07-11-08  01.05.17  Bumped MPI_HEADER_VERSION_UNIT.
  *  ----------------------------------------------------------------------=
----
  */
=20
@@ -136,7 +140,7 @@
 /* Note: The major versions of 0xe0 through 0xff are reserved */
=20
 /* versioning for this MPI header set */
-#define MPI_HEADER_VERSION_UNIT             (0x10)
+#define MPI_HEADER_VERSION_UNIT             (0x14)
 #define MPI_HEADER_VERSION_DEV              (0x00)
 #define MPI_HEADER_VERSION_UNIT_MASK        (0xFF00)
 #define MPI_HEADER_VERSION_UNIT_SHIFT       (8)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_cnfg.h
--- a/head/sys/dev/mpt/mpilib/mpi_cnfg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_cnfg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_cnfg.h 233425 2012-03-24 16:23:21=
Z marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
@@ -33,7 +33,7 @@
  *          Title:  MPI Config message, structures, and Pages
  *  Creation Date:  July 27, 2000
  *
- *    mpi_cnfg.h Version:  01.05.15
+ *    mpi_cnfg.h Version:  01.05.19
  *
  *  Version History
  *  ---------------
@@ -335,6 +335,28 @@
  *                      Expander Page 0 Flags field.
  *                      Fixed define for
  *                      MPI_SAS_EXPANDER1_DISCINFO_BAD_PHY_DISABLED.
+ *  08-07-07  01.05.16  Added MPI_IOCPAGE6_CAP_FLAGS_MULTIPORT_DRIVE_SUPPO=
RT
+ *                      define.
+ *                      Added BIOS Page 4 structure.
+ *                      Added MPI_RAID_PHYS_DISK1_PATH_MAX define for RAID
+ *                      Physcial Disk Page 1.
+ *  01-15-07  01.05.17  Added additional bit defines for ExtFlags field of
+ *                      Manufacturing Page 4.
+ *                      Added Solid State Drives Supported bit to IOC Page=
 6
+ *                      Capabilities Flags.
+ *                      Added new value for AccessStatus field of SAS Devi=
ce
+ *                      Page 0 (_SATA_NEEDS_INITIALIZATION).
+ *  03-28-08  01.05.18  Defined new bits in Manufacturing Page 4 ExtFlags =
field
+ *                      to control coercion size and the mixing of SAS and=
 SATA
+ *                      SSD drives.
+ *  07-11-08  01.05.19  Added defines MPI_MANPAGE4_EXTFLAGS_RAID0_SINGLE_D=
RIVE
+ *                      and MPI_MANPAGE4_EXTFLAGS_SSD_SCRUB_DISABLE for Ex=
tFlags
+ *                      field of Manufacturing Page 4.
+ *                      Added defines for a new bit in BIOS Page 1 BiosOpt=
ions
+ *                      field to control adapter scan order.
+ *                      Added BootDeviceWaitTime field to SAS IO Unit Page=
 2.
+ *                      Added MPI_SAS_PHY0_PHYINFO_PHY_VACANT for use in P=
hyInfo
+ *                      field of SAS Expander Page 1.
  *  ----------------------------------------------------------------------=
----
  */
=20
@@ -713,6 +735,16 @@
 #define MPI_MANPAGE4_IR_NO_MIX_SAS_SATA                 (0x01)
=20
 /* defines for the ExtFlags field */
+#define MPI_MANPAGE4_EXTFLAGS_RAID0_SINGLE_DRIVE        (0x0400)
+#define MPI_MANPAGE4_EXTFLAGS_SSD_SCRUB_DISABLE         (0x0200)
+#define MPI_MANPAGE4_EXTFLAGS_MASK_COERCION_SIZE        (0x0180)
+#define MPI_MANPAGE4_EXTFLAGS_SHIFT_COERCION_SIZE       (7)
+#define MPI_MANPAGE4_EXTFLAGS_1GB_COERCION_SIZE         (0)
+#define MPI_MANPAGE4_EXTFLAGS_128MB_COERCION_SIZE       (1)
+
+#define MPI_MANPAGE4_EXTFLAGS_NO_MIX_SSD_SAS_SATA       (0x0040)
+#define MPI_MANPAGE4_EXTFLAGS_MIX_SSD_AND_NON_SSD       (0x0020)
+#define MPI_MANPAGE4_EXTFLAGS_DUAL_PORT_SUPPORT         (0x0010)
 #define MPI_MANPAGE4_EXTFLAGS_HIDE_NON_IR_METADATA      (0x0008)
 #define MPI_MANPAGE4_EXTFLAGS_SAS_CACHE_DISABLE         (0x0004)
 #define MPI_MANPAGE4_EXTFLAGS_SATA_CACHE_DISABLE        (0x0002)
@@ -1186,6 +1218,8 @@
=20
 /* IOC Page 6 Capabilities Flags */
=20
+#define MPI_IOCPAGE6_CAP_FLAGS_SSD_SUPPORT              (0x00000020)
+#define MPI_IOCPAGE6_CAP_FLAGS_MULTIPORT_DRIVE_SUPPORT  (0x00000010)
 #define MPI_IOCPAGE6_CAP_FLAGS_DISABLE_SMART_POLLING    (0x00000008)
=20
 #define MPI_IOCPAGE6_CAP_FLAGS_MASK_METADATA_SIZE       (0x00000006)
@@ -1222,6 +1256,10 @@
 #define MPI_BIOSPAGE1_OPTIONS_SPI_ENABLE                (0x00000400)
 #define MPI_BIOSPAGE1_OPTIONS_FC_ENABLE                 (0x00000200)
 #define MPI_BIOSPAGE1_OPTIONS_SAS_ENABLE                (0x00000100)
+
+#define MPI_BIOSPAGE1_OPTIONS_SCAN_HIGH_TO_LOW          (0x00000002)
+#define MPI_BIOSPAGE1_OPTIONS_SCAN_LOW_TO_HIGH          (0x00000000)
+
 #define MPI_BIOSPAGE1_OPTIONS_DISABLE_BIOS              (0x00000001)
=20
 /* values for the IOCSettings field */
@@ -1455,6 +1493,15 @@
 #define MPI_BIOSPAGE2_FORM_SAS_WWN                      (0x05)
 #define MPI_BIOSPAGE2_FORM_ENCLOSURE_SLOT               (0x06)
=20
+typedef struct _CONFIG_PAGE_BIOS_4
+{
+    CONFIG_PAGE_HEADER      Header;                     /* 00h */
+    U64                     ReassignmentBaseWWID;       /* 04h */
+} CONFIG_PAGE_BIOS_4, MPI_POINTER PTR_CONFIG_PAGE_BIOS_4,
+  BIOSPage4_t, MPI_POINTER pBIOSPage4_t;
+
+#define MPI_BIOSPAGE4_PAGEVERSION                       (0x00)
+
=20
 /*************************************************************************=
***
 *   SCSI Port Config Pages
@@ -2446,6 +2493,15 @@
 #define MPI_RAID_PHYSDISK1_FLAG_BROKEN          (0x0002)
 #define MPI_RAID_PHYSDISK1_FLAG_INVALID         (0x0001)
=20
+
+/*
+ * Host code (drivers, BIOS, utilities, etc.) should leave this define set=
 to
+ * one and check Header.PageLength or NumPhysDiskPaths at runtime.
+ */
+#ifndef MPI_RAID_PHYS_DISK1_PATH_MAX
+#define MPI_RAID_PHYS_DISK1_PATH_MAX    (1)
+#endif
+
 typedef struct _CONFIG_PAGE_RAID_PHYS_DISK_1
 {
     CONFIG_PAGE_HEADER              Header;             /* 00h */
@@ -2453,7 +2509,7 @@
     U8                              PhysDiskNum;        /* 05h */
     U16                             Reserved2;          /* 06h */
     U32                             Reserved1;          /* 08h */
-    RAID_PHYS_DISK1_PATH            Path[1];            /* 0Ch */
+    RAID_PHYS_DISK1_PATH            Path[MPI_RAID_PHYS_DISK1_PATH_MAX];/* =
0Ch */
 } CONFIG_PAGE_RAID_PHYS_DISK_1, MPI_POINTER PTR_CONFIG_PAGE_RAID_PHYS_DISK=
_1,
   RaidPhysDiskPage1_t, MPI_POINTER pRaidPhysDiskPage1_t;
=20
@@ -2578,6 +2634,7 @@
 #define MPI_SAS_IOUNIT0_RATE_SATA_OOB_COMPLETE              (0x03)
 #define MPI_SAS_IOUNIT0_RATE_1_5                            (0x08)
 #define MPI_SAS_IOUNIT0_RATE_3_0                            (0x09)
+#define MPI_SAS_IOUNIT0_RATE_6_0                            (0x0A)
=20
 /* see mpi_sas.h for values for SAS IO Unit Page 0 ControllerPhyDeviceInfo=
 values */
=20
@@ -2697,7 +2754,7 @@
 {
     CONFIG_EXTENDED_PAGE_HEADER         Header;                 /* 00h */
     U8                                  NumDevsPerEnclosure;    /* 08h */
-    U8                                  Reserved1;              /* 09h */
+    U8                                  BootDeviceWaitTime;     /* 09h */
     U16                                 Reserved2;              /* 0Ah */
     U16                                 MaxPersistentIDs;       /* 0Ch */
     U16                                 NumPersistentIDsUsed;   /* 0Eh */
@@ -2707,7 +2764,7 @@
 } CONFIG_PAGE_SAS_IO_UNIT_2, MPI_POINTER PTR_CONFIG_PAGE_SAS_IO_UNIT_2,
   SasIOUnitPage2_t, MPI_POINTER pSasIOUnitPage2_t;
=20
-#define MPI_SASIOUNITPAGE2_PAGEVERSION      (0x06)
+#define MPI_SASIOUNITPAGE2_PAGEVERSION      (0x07)
=20
 /* values for SAS IO Unit Page 2 Status field */
 #define MPI_SAS_IOUNIT2_STATUS_DEVICE_LIMIT_EXCEEDED        (0x08)
@@ -2871,6 +2928,7 @@
 #define MPI_SAS_DEVICE0_ASTATUS_SATA_INIT_FAILED            (0x01)
 #define MPI_SAS_DEVICE0_ASTATUS_SATA_CAPABILITY_FAILED      (0x02)
 #define MPI_SAS_DEVICE0_ASTATUS_SATA_AFFILIATION_CONFLICT   (0x03)
+#define MPI_SAS_DEVICE0_ASTATUS_SATA_NEEDS_INITIALIZATION   (0x04)
 /* specific values for SATA Init failures */
 #define MPI_SAS_DEVICE0_ASTATUS_SIF_UNKNOWN                 (0x10)
 #define MPI_SAS_DEVICE0_ASTATUS_SIF_AFFILIATION_CONFLICT    (0x11)
@@ -2981,6 +3039,7 @@
 #define MPI_SAS_PHY0_FLAGS_SGPIO_DIRECT_ATTACH_ENC              (0x01)
=20
 /* values for SAS PHY Page 0 PhyInfo field */
+#define MPI_SAS_PHY0_PHYINFO_PHY_VACANT                         (0x8000000=
0)
 #define MPI_SAS_PHY0_PHYINFO_SATA_PORT_ACTIVE                   (0x0000400=
0)
 #define MPI_SAS_PHY0_PHYINFO_SATA_PORT_SELECTOR                 (0x0000200=
0)
 #define MPI_SAS_PHY0_PHYINFO_VIRTUAL_PHY                        (0x0000100=
0)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_fc.h
--- a/head/sys/dev/mpt/mpilib/mpi_fc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_fc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_fc.h 233425 2012-03-24 16:23:21Z =
marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_init.h
--- a/head/sys/dev/mpt/mpilib/mpi_init.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_init.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_init.h 233425 2012-03-24 16:23:21=
Z marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_ioc.h
--- a/head/sys/dev/mpt/mpilib/mpi_ioc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_ioc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_ioc.h 224761 2011-08-10 19:05:22Z=
 marius $ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_ioc.h 233425 2012-03-24 16:23:21Z=
 marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
@@ -868,6 +868,7 @@
 #define MPI_EVENT_SAS_PLS_LR_RATE_SATA_OOB_COMPLETE         (0x03)
 #define MPI_EVENT_SAS_PLS_LR_RATE_1_5                       (0x08)
 #define MPI_EVENT_SAS_PLS_LR_RATE_3_0                       (0x09)
+#define MPI_EVENT_SAS_PLS_LR_RATE_6_0                       (0x0A)
=20
 /* SAS Discovery Event data */
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_lan.h
--- a/head/sys/dev/mpt/mpilib/mpi_lan.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_lan.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_lan.h 233425 2012-03-24 16:23:21Z=
 marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_raid.h
--- a/head/sys/dev/mpt/mpilib/mpi_raid.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_raid.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_raid.h 233425 2012-03-24 16:23:21=
Z marius $ */
 /*-
  * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
  * All rights reserved.
@@ -33,7 +33,7 @@
  *          Title:  MPI RAID message and structures
  *  Creation Date:  February 27, 2001
  *
- *    mpi_raid.h Version:  01.05.03
+ *    mpi_raid.h Version:  01.05.05
  *
  *  Version History
  *  ---------------
@@ -61,6 +61,9 @@
  *                      _SET_RESYNC_RATE and _SET_DATA_SCRUB_RATE.
  *  02-28-07  01.05.03  Added new RAID Action, Device FW Update Mode, and
  *                      associated defines.
+ *  08-07-07  01.05.04  Added Disable Full Rebuild bit to the ActionDataWo=
rd
+ *                      for the RAID Action MPI_RAID_ACTION_DISABLE_VOLUME.
+ *  01-15-08  01.05.05  Added define for MPI_RAID_ACTION_SET_VOLUME_NAME.
  *  ----------------------------------------------------------------------=
----
  */
=20
@@ -120,6 +123,7 @@
 #define MPI_RAID_ACTION_SET_RESYNC_RATE             (0x13)
 #define MPI_RAID_ACTION_SET_DATA_SCRUB_RATE         (0x14)
 #define MPI_RAID_ACTION_DEVICE_FW_UPDATE_MODE       (0x15)
+#define MPI_RAID_ACTION_SET_VOLUME_NAME             (0x16)
=20
 /* ActionDataWord defines for use with MPI_RAID_ACTION_CREATE_VOLUME actio=
n */
 #define MPI_RAID_ACTION_ADATA_DO_NOT_SYNC           (0x00000001)
@@ -132,6 +136,9 @@
 #define MPI_RAID_ACTION_ADATA_KEEP_LBA0             (0x00000000)
 #define MPI_RAID_ACTION_ADATA_ZERO_LBA0             (0x00000002)
=20
+/* ActionDataWord defines for use with MPI_RAID_ACTION_DISABLE_VOLUME acti=
on */
+#define MPI_RAID_ACTION_ADATA_DISABLE_FULL_REBUILD  (0x00000001)
+
 /* ActionDataWord defines for use with MPI_RAID_ACTION_ACTIVATE_VOLUME act=
ion */
 #define MPI_RAID_ACTION_ADATA_INACTIVATE_ALL        (0x00000001)
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_sas.h
--- a/head/sys/dev/mpt/mpilib/mpi_sas.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_sas.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_sas.h 233425 2012-03-24 16:23:21Z=
 marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
@@ -33,7 +33,7 @@
  *          Title:  MPI Serial Attached SCSI structures and definitions
  *  Creation Date:  August 19, 2004
  *
- *    mpi_sas.h Version:  01.05.04
+ *    mpi_sas.h Version:  01.05.05
  *
  *  Version History
  *  ---------------
@@ -50,6 +50,10 @@
  *                      reply.
  *  10-11-06  01.05.04  Fixed the name of a define for Operation field of =
SAS IO
  *                      Unit Control request.
+ *  01-15-08  01.05.05  Added support for MPI_SAS_OP_SET_IOC_PARAMETER,
+ *                      including adding IOCParameter and IOCParameter val=
ue
+ *                      fields to SAS IO Unit Control Request.
+ *                      Added MPI_SAS_DEVICE_INFO_PRODUCT_SPECIFIC define.
  *  ----------------------------------------------------------------------=
----
  */
=20
@@ -87,6 +91,8 @@
  * Values for the SAS DeviceInfo field used in SAS Device Status Change Ev=
ent
  * data and SAS IO Unit Configuration pages.
  */
+#define MPI_SAS_DEVICE_INFO_PRODUCT_SPECIFIC    (0xF0000000)
+
 #define MPI_SAS_DEVICE_INFO_SEP                 (0x00004000)
 #define MPI_SAS_DEVICE_INFO_ATAPI_DEVICE        (0x00002000)
 #define MPI_SAS_DEVICE_INFO_LSI_DEVICE          (0x00001000)
@@ -243,7 +249,7 @@
     U8                      ChainOffset;        /* 02h */
     U8                      Function;           /* 03h */
     U16                     DevHandle;          /* 04h */
-    U8                      Reserved3;          /* 06h */
+    U8                      IOCParameter;       /* 06h */
     U8                      MsgFlags;           /* 07h */
     U32                     MsgContext;         /* 08h */
     U8                      TargetID;           /* 0Ch */
@@ -252,7 +258,7 @@
     U8                      PrimFlags;          /* 0Fh */
     U32                     Primitive;          /* 10h */
     U64                     SASAddress;         /* 14h */
-    U32                     Reserved4;          /* 1Ch */
+    U32                     IOCParameterValue;  /* 1Ch */
 } MSG_SAS_IOUNIT_CONTROL_REQUEST, MPI_POINTER PTR_MSG_SAS_IOUNIT_CONTROL_R=
EQUEST,
   SasIoUnitControlRequest_t, MPI_POINTER pSasIoUnitControlRequest_t;
=20
@@ -268,6 +274,8 @@
 #define MPI_SAS_OP_TRANSMIT_PORT_SELECT_SIGNAL  (0x0C)
 #define MPI_SAS_OP_TRANSMIT_REMOVE_DEVICE       (0x0D)  /* obsolete name */
 #define MPI_SAS_OP_REMOVE_DEVICE                (0x0D)
+#define MPI_SAS_OP_SET_IOC_PARAMETER            (0x0E)
+#define MPI_SAS_OP_PRODUCT_SPECIFIC_MIN         (0x80)
=20
 /* values for the PrimFlags field */
 #define MPI_SAS_PRIMFLAGS_SINGLE                (0x08)
@@ -283,7 +291,7 @@
     U8                      MsgLength;          /* 02h */
     U8                      Function;           /* 03h */
     U16                     DevHandle;          /* 04h */
-    U8                      Reserved3;          /* 06h */
+    U8                      IOCParameter;       /* 06h */
     U8                      MsgFlags;           /* 07h */
     U32                     MsgContext;         /* 08h */
     U16                     Reserved4;          /* 0Ch */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_targ.h
--- a/head/sys/dev/mpt/mpilib/mpi_targ.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_targ.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_targ.h 233425 2012-03-24 16:23:21=
Z marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_tool.h
--- a/head/sys/dev/mpt/mpilib/mpi_tool.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_tool.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_tool.h 233425 2012-03-24 16:23:21=
Z marius $ */
 /*-
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpilib/mpi_type.h
--- a/head/sys/dev/mpt/mpilib/mpi_type.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpilib/mpi_type.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_type.h 231678 2012-02-14 12:50:20=
Z tijl $ */
+/* $FreeBSD: head/sys/dev/mpt/mpilib/mpi_type.h 233425 2012-03-24 16:23:21=
Z marius $ */
 /*
- * Copyright (c) 2000-2005, LSI Logic Corporation and its contributors.
+ * Copyright (c) 2000-2010, LSI Logic Corporation and its contributors.
  * All rights reserved.
  *=20
  * Redistribution and use in source and binary forms, with or without
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpt.h
--- a/head/sys/dev/mpt/mpt.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpt.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/mpt/mpt.h 231518 2012-02-11 12:03:44Z marius $ */
+/* $FreeBSD: head/sys/dev/mpt/mpt.h 233403 2012-03-24 00:30:17Z marius $ */
 /*-
  * Generic defines for LSI '909 FC  adapters.
  * FreeBSD Version.
@@ -716,7 +716,9 @@
 	int			pci_msi_count;
 	struct resource *	pci_irq;	/* Interrupt map for chip */
 	void *			ih;		/* Interrupt handle */
+#if 0
 	struct mpt_pci_cfg	pci_cfg;	/* saved PCI conf registers */
+#endif
=20
 	/*
 	 * DMA Mapping Stuff
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mpt/mpt_pci.c
--- a/head/sys/dev/mpt/mpt_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mpt/mpt_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -99,7 +99,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mpt/mpt_pci.c 232411 2012-03-02 22:00:40Z=
 ken $");
+__FBSDID("$FreeBSD: head/sys/dev/mpt/mpt_pci.c 233886 2012-04-04 20:42:45Z=
 marius $");
=20
 #include <dev/mpt/mpt.h>
 #include <dev/mpt/mpt_cam.h>
@@ -113,104 +113,40 @@
 #define	pci_release_msi(x)	do { ; } while (0)
 #endif
=20
-#ifndef	PCI_VENDOR_LSI
-#define	PCI_VENDOR_LSI			0x1000
+/*
+ * XXX it seems no other MPT driver knows about the following chips.
+ */
+
+#ifndef	MPI_MANUFACTPAGE_DEVICEID_FC909_FB
+#define	MPI_MANUFACTPAGE_DEVICEID_FC909_FB	0x0620
 #endif
=20
-#ifndef	PCI_PRODUCT_LSI_FC909
-#define	PCI_PRODUCT_LSI_FC909		0x0620
+#ifndef	MPI_MANUFACTPAGE_DEVICEID_FC919_LAN_FB
+#define	MPI_MANUFACTPAGE_DEVICEID_FC919_LAN_FB	0x0625
 #endif
=20
-#ifndef	PCI_PRODUCT_LSI_FC909A
-#define	PCI_PRODUCT_LSI_FC909A		0x0621
+#ifndef	MPI_MANUFACTPAGE_DEVICEID_FC929_LAN_FB
+#define	MPI_MANUFACTPAGE_DEVICEID_FC929_LAN_FB	0x0623
 #endif
=20
-#ifndef	PCI_PRODUCT_LSI_FC919
-#define	PCI_PRODUCT_LSI_FC919		0x0624
+#ifndef	MPI_MANUFACTPAGE_DEVICEID_FC929X_LAN_FB
+#define	MPI_MANUFACTPAGE_DEVICEID_FC929X_LAN_FB	0x0627
 #endif
=20
-#ifndef	PCI_PRODUCT_LSI_FC919_LAN
-#define	PCI_PRODUCT_LSI_FC919_LAN	0x0625
+#ifndef	MPI_MANUFACTPAGE_DEVICEID_FC919X_LAN_FB
+#define	MPI_MANUFACTPAGE_DEVICEID_FC919X_LAN_FB	0x0629
 #endif
=20
-#ifndef	PCI_PRODUCT_LSI_FC929
-#define	PCI_PRODUCT_LSI_FC929		0x0622
+#ifndef MPI_MANUFACTPAGE_DEVID_SAS1068A_FB
+#define MPI_MANUFACTPAGE_DEVID_SAS1068A_FB	0x0055
 #endif
=20
-#ifndef	PCI_PRODUCT_LSI_FC929_LAN
-#define	PCI_PRODUCT_LSI_FC929_LAN	0x0623
+#ifndef	MPI_MANUFACTPAGE_DEVID_SAS1068E_FB
+#define	MPI_MANUFACTPAGE_DEVID_SAS1068E_FB	0x0059
 #endif
=20
-#ifndef	PCI_PRODUCT_LSI_FC929X
-#define	PCI_PRODUCT_LSI_FC929X		0x0626
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_FC929X_LAN
-#define	PCI_PRODUCT_LSI_FC929X_LAN	0x0627
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_FC919X
-#define	PCI_PRODUCT_LSI_FC919X		0x0628
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_FC919X_LAN
-#define	PCI_PRODUCT_LSI_FC919X_LAN	0x0629
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_FC7X04X
-#define	PCI_PRODUCT_LSI_FC7X04X		0x0640
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_FC646
-#define	PCI_PRODUCT_LSI_FC646		0x0646
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_1030
-#define	PCI_PRODUCT_LSI_1030		0x0030
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_1030ZC
-#define	PCI_PRODUCT_LSI_1030ZC		0x0031
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_SAS1064
-#define PCI_PRODUCT_LSI_SAS1064		0x0050
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1064A
-#define PCI_PRODUCT_LSI_SAS1064A	0x005C
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1064E
-#define PCI_PRODUCT_LSI_SAS1064E	0x0056
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1066
-#define PCI_PRODUCT_LSI_SAS1066		0x005E
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1066E
-#define PCI_PRODUCT_LSI_SAS1066E	0x005A
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1068
-#define PCI_PRODUCT_LSI_SAS1068		0x0054
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1068A
-#define PCI_PRODUCT_LSI_SAS1068A	0x0055
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1068E
-#define PCI_PRODUCT_LSI_SAS1068E	0x0058
-#endif
-
-#ifndef PCI_PRODUCT_LSI_SAS1078
-#define PCI_PRODUCT_LSI_SAS1078		0x0062
-#endif
-
-#ifndef	PCI_PRODUCT_LSI_SAS1078DE
-#define	PCI_PRODUCT_LSI_SAS1078DE	0x007C
+#ifndef	MPI_MANUFACTPAGE_DEVID_SAS1078DE_FB
+#define	MPI_MANUFACTPAGE_DEVID_SAS1078DE_FB	0x007C
 #endif
=20
 #ifndef	PCIM_CMD_SERRESPEN
@@ -224,8 +160,8 @@
 static int mpt_pci_shutdown(device_t);
 static int mpt_dma_mem_alloc(struct mpt_softc *mpt);
 static void mpt_dma_mem_free(struct mpt_softc *mpt);
+#if 0
 static void mpt_read_config_regs(struct mpt_softc *mpt);
-#if 0
 static void mpt_set_config_regs(struct mpt_softc *mpt);
 #endif
 static void mpt_pci_intr(void *);
@@ -236,77 +172,85 @@
 	DEVMETHOD(device_attach,	mpt_pci_attach),
 	DEVMETHOD(device_detach,	mpt_pci_detach),
 	DEVMETHOD(device_shutdown,	mpt_pci_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t mpt_driver =3D {
 	"mpt", mpt_methods, sizeof(struct mpt_softc)
 };
 static devclass_t mpt_devclass;
-DRIVER_MODULE(mpt, pci, mpt_driver, mpt_devclass, 0, 0);
+DRIVER_MODULE(mpt, pci, mpt_driver, mpt_devclass, NULL, NULL);
 MODULE_DEPEND(mpt, pci, 1, 1, 1);
 MODULE_VERSION(mpt, 1);
=20
 static int
 mpt_pci_probe(device_t dev)
 {
-	char *desc;
+	const char *desc;
+	int rval;
=20
-	if (pci_get_vendor(dev) !=3D PCI_VENDOR_LSI) {
+	if (pci_get_vendor(dev) !=3D MPI_MANUFACTPAGE_VENDORID_LSILOGIC)
 		return (ENXIO);
-	}
=20
+	rval =3D BUS_PROBE_DEFAULT;
 	switch (pci_get_device(dev)) {
-	case PCI_PRODUCT_LSI_FC909:
+	case MPI_MANUFACTPAGE_DEVICEID_FC909_FB:
 		desc =3D "LSILogic FC909 FC Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC909A:
+	case MPI_MANUFACTPAGE_DEVICEID_FC909:
 		desc =3D "LSILogic FC909A FC Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC919:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919:
 		desc =3D "LSILogic FC919 FC Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC919_LAN:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919_LAN_FB:
 		desc =3D "LSILogic FC919 LAN Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC929:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929:
 		desc =3D "Dual LSILogic FC929 FC Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC929_LAN:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929_LAN_FB:
 		desc =3D "Dual LSILogic FC929 LAN Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC919X:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919X:
 		desc =3D "LSILogic FC919 FC PCI-X Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC919X_LAN:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919X_LAN_FB:
 		desc =3D "LSILogic FC919 LAN PCI-X Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC929X:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929X:
 		desc =3D "Dual LSILogic FC929X 2Gb/s FC PCI-X Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC929X_LAN:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929X_LAN_FB:
 		desc =3D "Dual LSILogic FC929X LAN PCI-X Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC646:
+	case MPI_MANUFACTPAGE_DEVICEID_FC949E:
 		desc =3D "Dual LSILogic FC7X04X 4Gb/s FC PCI-Express Adapter";
 		break;
-	case PCI_PRODUCT_LSI_FC7X04X:
+	case MPI_MANUFACTPAGE_DEVICEID_FC949X:
 		desc =3D "Dual LSILogic FC7X04X 4Gb/s FC PCI-X Adapter";
 		break;
-	case PCI_PRODUCT_LSI_1030:
-	case PCI_PRODUCT_LSI_1030ZC:
+	case MPI_MANUFACTPAGE_DEVID_53C1030:
+	case MPI_MANUFACTPAGE_DEVID_53C1030ZC:
 		desc =3D "LSILogic 1030 Ultra4 Adapter";
 		break;
-	case PCI_PRODUCT_LSI_SAS1064:
-	case PCI_PRODUCT_LSI_SAS1064A:
-	case PCI_PRODUCT_LSI_SAS1064E:
-	case PCI_PRODUCT_LSI_SAS1066:
-	case PCI_PRODUCT_LSI_SAS1066E:
-	case PCI_PRODUCT_LSI_SAS1068:
-	case PCI_PRODUCT_LSI_SAS1068A:
-	case PCI_PRODUCT_LSI_SAS1068E:
-	case PCI_PRODUCT_LSI_SAS1078:
-	case PCI_PRODUCT_LSI_SAS1078DE:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068E_FB:
+		/*
+		 * Allow mfi(4) to claim this device in case it's in MegaRAID
+		 * mode.
+		 */
+		rval =3D BUS_PROBE_LOW_PRIORITY;
+		/* FALLTHROUGH */
+	case MPI_MANUFACTPAGE_DEVID_SAS1064:
+	case MPI_MANUFACTPAGE_DEVID_SAS1064A:
+	case MPI_MANUFACTPAGE_DEVID_SAS1064E:
+	case MPI_MANUFACTPAGE_DEVID_SAS1066:
+	case MPI_MANUFACTPAGE_DEVID_SAS1066E:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068A_FB:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068E:
+	case MPI_MANUFACTPAGE_DEVID_SAS1078:
+	case MPI_MANUFACTPAGE_DEVID_SAS1078DE_FB:
 		desc =3D "LSILogic SAS/SATA Adapter";
 		break;
 	default:
@@ -314,7 +258,7 @@
 	}
=20
 	device_set_desc(dev, desc);
-	return (0);
+	return (rval);
 }
=20
 #if	__FreeBSD_version < 500000 =20
@@ -459,40 +403,36 @@
 	uint32_t	  data, cmd;
 	int		  mpt_io_bar, mpt_mem_bar;
=20
-	/* Allocate the softc structure */
 	mpt  =3D (struct mpt_softc*)device_get_softc(dev);
-	if (mpt =3D=3D NULL) {
-		device_printf(dev, "cannot allocate softc\n");
-		return (ENOMEM);
-	}
-	memset(mpt, 0, sizeof(struct mpt_softc));
+
 	switch (pci_get_device(dev)) {
-	case PCI_PRODUCT_LSI_FC909:
-	case PCI_PRODUCT_LSI_FC909A:
-	case PCI_PRODUCT_LSI_FC919:
-	case PCI_PRODUCT_LSI_FC919_LAN:
-	case PCI_PRODUCT_LSI_FC929:
-	case PCI_PRODUCT_LSI_FC929_LAN:
-	case PCI_PRODUCT_LSI_FC929X:
-	case PCI_PRODUCT_LSI_FC929X_LAN:
-	case PCI_PRODUCT_LSI_FC919X:
-	case PCI_PRODUCT_LSI_FC919X_LAN:
-	case PCI_PRODUCT_LSI_FC646:
-	case PCI_PRODUCT_LSI_FC7X04X:
+	case MPI_MANUFACTPAGE_DEVICEID_FC909_FB:
+	case MPI_MANUFACTPAGE_DEVICEID_FC909:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919_LAN_FB:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929_LAN_FB:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929X:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929X_LAN_FB:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919X:
+	case MPI_MANUFACTPAGE_DEVICEID_FC919X_LAN_FB:
+	case MPI_MANUFACTPAGE_DEVICEID_FC949E:
+	case MPI_MANUFACTPAGE_DEVICEID_FC949X:
 		mpt->is_fc =3D 1;
 		break;
-	case PCI_PRODUCT_LSI_SAS1078:
-	case PCI_PRODUCT_LSI_SAS1078DE:
+	case MPI_MANUFACTPAGE_DEVID_SAS1078:
+	case MPI_MANUFACTPAGE_DEVID_SAS1078DE_FB:
 		mpt->is_1078 =3D 1;
 		/* FALLTHROUGH */
-	case PCI_PRODUCT_LSI_SAS1064:
-	case PCI_PRODUCT_LSI_SAS1064A:
-	case PCI_PRODUCT_LSI_SAS1064E:
-	case PCI_PRODUCT_LSI_SAS1066:
-	case PCI_PRODUCT_LSI_SAS1066E:
-	case PCI_PRODUCT_LSI_SAS1068:
-	case PCI_PRODUCT_LSI_SAS1068A:
-	case PCI_PRODUCT_LSI_SAS1068E:
+	case MPI_MANUFACTPAGE_DEVID_SAS1064:
+	case MPI_MANUFACTPAGE_DEVID_SAS1064A:
+	case MPI_MANUFACTPAGE_DEVID_SAS1064E:
+	case MPI_MANUFACTPAGE_DEVID_SAS1066:
+	case MPI_MANUFACTPAGE_DEVID_SAS1066E:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068A_FB:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068E:
+	case MPI_MANUFACTPAGE_DEVID_SAS1068E_FB:
 		mpt->is_sas =3D 1;
 		break;
 	default:
@@ -544,12 +484,12 @@
 	 * If so, link with our partner (around yet)
 	 */
 	switch (pci_get_device(dev)) {
-	case PCI_PRODUCT_LSI_FC929:
-	case PCI_PRODUCT_LSI_FC929_LAN:
-	case PCI_PRODUCT_LSI_FC646:
-	case PCI_PRODUCT_LSI_FC7X04X:
-	case PCI_PRODUCT_LSI_1030:
-	case PCI_PRODUCT_LSI_1030ZC:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929:
+	case MPI_MANUFACTPAGE_DEVICEID_FC929_LAN_FB:
+	case MPI_MANUFACTPAGE_DEVICEID_FC949E:
+	case MPI_MANUFACTPAGE_DEVICEID_FC949X:
+	case MPI_MANUFACTPAGE_DEVID_53C1030:
+	case MPI_MANUFACTPAGE_DEVID_53C1030ZC:
 		mpt_link_peer(mpt);
 		break;
 	default:
@@ -588,7 +528,6 @@
 		mpt->pci_pio_sh =3D rman_get_bushandle(mpt->pci_pio_reg);
 	}
=20
-	/* Allocate kernel virtual memory for the 9x9's Mem0 region */
 	mpt_mem_bar =3D PCIR_BAR(mpt_mem_bar);
 	mpt->pci_reg =3D bus_alloc_resource_any(dev, SYS_RES_MEMORY,
 	    &mpt_mem_bar, RF_ACTIVE);
@@ -660,6 +599,7 @@
 		goto bad;
 	}
=20
+#if 0
 	/*
 	 * Save the PCI config register values
  	 *
@@ -671,6 +611,7 @@
 	 */
=20
 	mpt_read_config_regs(mpt);
+#endif
=20
 	/*
 	 * Disable PIO until we need it
@@ -888,6 +829,7 @@
 	mpt->request_pool =3D NULL;
 }
=20
+#if 0
 /* Reads modifiable (via PCI transactions) config registers */
 static void
 mpt_read_config_regs(struct mpt_softc *mpt)
@@ -906,7 +848,6 @@
 	mpt->pci_cfg.PMCSR =3D pci_read_config(mpt->dev, 0x44, 4);
 }
=20
-#if 0
 /* Sets modifiable config registers */
 static void
 mpt_set_config_regs(struct mpt_softc *mpt)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mwl/if_mwl.c
--- a/head/sys/dev/mwl/if_mwl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mwl/if_mwl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mwl/if_mwl.c 228621 2011-12-17 10:23:17Z =
bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/mwl/if_mwl.c 234368 2012-04-17 04:52:57Z =
adrian $");
=20
 /*
  * Driver for the Marvell 88W8363 Wireless LAN controller.
@@ -37,6 +37,7 @@
=20
 #include "opt_inet.h"
 #include "opt_mwl.h"
+#include "opt_wlan.h"
=20
 #include <sys/param.h>
 #include <sys/systm.h>=20
@@ -309,6 +310,12 @@
 	}
 	ic =3D ifp->if_l2com;
=20
+	/*
+	 * Setup the RX free list lock early, so it can be consistently
+	 * removed.
+	 */
+	MWL_RXFREE_INIT(sc);
+
 	/* set these up early for if_printf use */
 	if_initname(ifp, device_get_name(sc->sc_dev),
 		device_get_unit(sc->sc_dev));
@@ -530,6 +537,7 @@
 bad1:
 	mwl_hal_detach(mh);
 bad:
+	MWL_RXFREE_DESTROY(sc);
 	if_free(ifp);
 	sc->sc_invalid =3D 1;
 	return error;
@@ -560,6 +568,7 @@
 	ieee80211_ifdetach(ic);
 	callout_drain(&sc->sc_watchdog);
 	mwl_dma_cleanup(sc);
+	MWL_RXFREE_DESTROY(sc);
 	mwl_tx_cleanup(sc);
 	mwl_hal_detach(sc->sc_mh);
 	if_free(ifp);
@@ -2273,7 +2282,6 @@
 		SLIST_INSERT_HEAD(&sc->sc_rxfree, rbuf, next);
 		sc->sc_nrxfree++;
 	}
-	MWL_RXFREE_INIT(sc);
 	return 0;
 }
 #undef DS2PHYS
@@ -2297,7 +2305,6 @@
 	}
 	if (sc->sc_rxdma.dd_desc_len !=3D 0)
 		mwl_desc_cleanup(sc, &sc->sc_rxdma);
-	MWL_RXFREE_DESTROY(sc);
 }
=20
 static int
@@ -3739,7 +3746,7 @@
 		/* NB: no held reference to ni */
 		sp =3D mwl_hal_bastream_alloc(MWL_VAP(vap)->mv_hvap,
 		    (baparamset & IEEE80211_BAPS_POLICY_IMMEDIATE) !=3D 0,
-		    ni->ni_macaddr, WME_AC_TO_TID(tap->txa_ac), ni->ni_htparam,
+		    ni->ni_macaddr, tap->txa_tid, ni->ni_htparam,
 		    ni, tap);
 		if (sp =3D=3D NULL) {
 			/*
@@ -3776,8 +3783,8 @@
 	if (bas =3D=3D NULL) {
 		/* XXX should not happen */
 		DPRINTF(sc, MWL_DEBUG_AMPDU,
-		    "%s: no BA stream allocated, AC %d\n",
-		    __func__, tap->txa_ac);
+		    "%s: no BA stream allocated, TID %d\n",
+		    __func__, tap->txa_tid);
 		sc->sc_stats.mst_addba_nostream++;
 		return 0;
 	}
@@ -3805,18 +3812,18 @@
 			tap->txa_private =3D NULL;
=20
 			DPRINTF(sc, MWL_DEBUG_AMPDU,
-			    "%s: create failed, error %d, bufsiz %d AC %d "
+			    "%s: create failed, error %d, bufsiz %d TID %d "
 			    "htparam 0x%x\n", __func__, error, bufsiz,
-			    tap->txa_ac, ni->ni_htparam);
+			    tap->txa_tid, ni->ni_htparam);
 			sc->sc_stats.mst_bacreate_failed++;
 			return 0;
 		}
 		/* NB: cache txq to avoid ptr indirect */
-		mwl_bastream_setup(bas, tap->txa_ac, bas->bastream->txq);
+		mwl_bastream_setup(bas, tap->txa_tid, bas->bastream->txq);
 		DPRINTF(sc, MWL_DEBUG_AMPDU,
-		    "%s: bastream %p assigned to txq %d AC %d bufsiz %d "
+		    "%s: bastream %p assigned to txq %d TID %d bufsiz %d "
 		    "htparam 0x%x\n", __func__, bas->bastream,
-		    bas->txq, tap->txa_ac, bufsiz, ni->ni_htparam);
+		    bas->txq, tap->txa_tid, bufsiz, ni->ni_htparam);
 	} else {
 		/*
 		 * Other side NAK'd us; return the resources.
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/mwl/if_mwlvar.h
--- a/head/sys/dev/mwl/if_mwlvar.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/mwl/if_mwlvar.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/dev/mwl/if_mwlvar.h 234324 2012-04-15 20:29:39Z adri=
an $
  */
=20
 /*
@@ -187,10 +187,10 @@
 };
=20
 static __inline__ void
-mwl_bastream_setup(struct mwl_bastate *bas, int ac, int txq)
+mwl_bastream_setup(struct mwl_bastate *bas, int tid, int txq)
 {
 	bas->txq =3D txq;
-	bas->qos =3D htole16(WME_AC_TO_TID(ac) | IEEE80211_QOS_ACKPOLICY_BA);
+	bas->qos =3D htole16(tid | IEEE80211_QOS_ACKPOLICY_BA);
 }
=20
 static __inline__ void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/netmap/if_re_netmap.h
--- a/head/sys/dev/netmap/if_re_netmap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/netmap/if_re_netmap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 /*
- * $FreeBSD: head/sys/dev/netmap/if_re_netmap.h 232238 2012-02-27 19:05:01=
Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/if_re_netmap.h 234225 2012-04-13 15:33:12=
Z luigi $
  * $Id: if_re_netmap.h 10609 2012-02-22 19:44:58Z luigi $
  *
  * netmap support for "re"
@@ -284,7 +284,7 @@
 		for (n =3D 0; j !=3D k; n++) {
 			struct netmap_slot *slot =3D ring->slot + j;
 			struct rl_desc *desc =3D &sc->rl_ldata.rl_rx_list[l];
-			int cmd =3D na->buff_size | RL_RDESC_CMD_OWN;
+			int cmd =3D NETMAP_BUF_SIZE | RL_RDESC_CMD_OWN;
 			uint64_t paddr;
 			void *addr =3D PNMB(slot, &paddr);
=20
@@ -391,7 +391,7 @@
 		    sc->rl_ldata.rl_rx_desc[i].rx_dmamap, BUS_DMASYNC_PREREAD);
 		desc[i].rl_bufaddr_lo =3D htole32(RL_ADDR_LO(paddr));
 		desc[i].rl_bufaddr_hi =3D htole32(RL_ADDR_HI(paddr));
-		cmdstat =3D na->buff_size;
+		cmdstat =3D NETMAP_BUF_SIZE;
 		if (i =3D=3D n - 1) /* mark the end of ring */
 			cmdstat |=3D RL_RDESC_CMD_EOR;
 		if (i < max_avail)
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/netmap/ixgbe_netmap.h
--- a/head/sys/dev/netmap/ixgbe_netmap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/netmap/ixgbe_netmap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 /*
- * $FreeBSD: head/sys/dev/netmap/ixgbe_netmap.h 232238 2012-02-27 19:05:01=
Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/ixgbe_netmap.h 234229 2012-04-13 16:42:54=
Z luigi $
  * $Id: ixgbe_netmap.h 10627 2012-02-23 19:37:15Z luigi $
  *
  * netmap modifications for ixgbe
@@ -49,6 +49,32 @@
  */
 #include <dev/netmap/netmap_kern.h>
=20
+/*
+ * ix_crcstrip: 0: keep CRC in rx frames (default), 1: strip it.
+ *	During regular operations the CRC is stripped, but on some
+ *	hardware reception of frames not multiple of 64 is slower,
+ *	so using crcstrip=3D0 helps in benchmarks.
+ *
+ * ix_rx_miss, ix_rx_miss_bufs:
+ *	count packets that might be missed due to lost interrupts.
+ *
+ * ix_use_dd
+ *	use the dd bit for completed tx transmissions.
+ *	This is tricky, much better to use TDH for now.
+ */
+SYSCTL_DECL(_dev_netmap);
+static int ix_write_len;
+SYSCTL_INT(_dev_netmap, OID_AUTO, ix_write_len,
+    CTLFLAG_RW, &ix_write_len, 0, "write rx len");
+static int ix_rx_miss, ix_rx_miss_bufs, ix_use_dd, ix_crcstrip;
+SYSCTL_INT(_dev_netmap, OID_AUTO, ix_crcstrip,
+    CTLFLAG_RW, &ix_crcstrip, 0, "strip CRC on rx frames");
+SYSCTL_INT(_dev_netmap, OID_AUTO, ix_use_dd,
+    CTLFLAG_RW, &ix_use_dd, 0, "use dd instead of tdh to detect tx frames"=
);
+SYSCTL_INT(_dev_netmap, OID_AUTO, ix_rx_miss,
+    CTLFLAG_RW, &ix_rx_miss, 0, "potentially missed rx intr");
+SYSCTL_INT(_dev_netmap, OID_AUTO, ix_rx_miss_bufs,
+    CTLFLAG_RW, &ix_rx_miss_bufs, 0, "potentially missed rx intr bufs");
=20
 /*
  * wrapper to export locks to the generic netmap code.
@@ -82,6 +108,43 @@
 }
=20
=20
+static void
+set_crcstrip(struct ixgbe_hw *hw, int onoff)
+{
+	/* crc stripping is set in two places:
+	 * IXGBE_HLREG0 (modified on init_locked and hw reset)
+	 * IXGBE_RDRXCTL (set by the original driver in
+	 *	ixgbe_setup_hw_rsc() called in init_locked.
+	 *	We disable the setting when netmap is compiled in).
+	 * We update the values here, but also in ixgbe.c because
+	 * init_locked sometimes is called outside our control.
+	 */
+	uint32_t hl, rxc;
+
+	hl =3D IXGBE_READ_REG(hw, IXGBE_HLREG0);
+	rxc =3D IXGBE_READ_REG(hw, IXGBE_RDRXCTL);
+	if (netmap_verbose)
+		D("%s read  HLREG 0x%x rxc 0x%x",
+			onoff ? "enter" : "exit", hl, rxc);
+	/* hw requirements ... */
+	rxc &=3D ~IXGBE_RDRXCTL_RSCFRSTSIZE;
+	rxc |=3D IXGBE_RDRXCTL_RSCACKC;
+	if (onoff && !ix_crcstrip) {
+		/* keep the crc. Fast rx */
+		hl &=3D ~IXGBE_HLREG0_RXCRCSTRP;
+		rxc &=3D ~IXGBE_RDRXCTL_CRCSTRIP;
+	} else {
+		/* reset default mode */
+		hl |=3D IXGBE_HLREG0_RXCRCSTRP;
+		rxc |=3D IXGBE_RDRXCTL_CRCSTRIP;
+	}
+	if (netmap_verbose)
+		D("%s write HLREG 0x%x rxc 0x%x",
+			onoff ? "enter" : "exit", hl, rxc);
+	IXGBE_WRITE_REG(hw, IXGBE_HLREG0, hl);
+	IXGBE_WRITE_REG(hw, IXGBE_RDRXCTL, rxc);
+}
+
 /*
  * Register/unregister. We are already under core lock.
  * Only called on the first register or the last unregister.
@@ -101,6 +164,7 @@
 	/* Tell the stack that the interface is no longer active */
 	ifp->if_drv_flags &=3D ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
=20
+	set_crcstrip(&adapter->hw, onoff);
 	if (onoff) { /* enable netmap mode */
 		ifp->if_capenable |=3D IFCAP_NETMAP;
=20
@@ -125,6 +189,7 @@
 		/* initialize the card, this time in standard mode */
 		ixgbe_init_locked(adapter);	/* also enables intr */
 	}
+	set_crcstrip(&adapter->hw, onoff);
 	return (error);
 }
=20
@@ -325,12 +390,26 @@
 		 * For the time being we use TDH, as we do it infrequently
 		 * enough not to pose performance problems.
 		 */
+	    if (ix_use_dd) {
+		struct ixgbe_legacy_tx_desc *txd =3D
+		    (struct ixgbe_legacy_tx_desc *)txr->tx_base;
+
+		l =3D txr->next_to_clean;
+		k =3D netmap_idx_k2n(kring, kring->nr_hwcur);
+		delta =3D 0;
+		while (l !=3D k &&
+		    txd[l].upper.fields.status & IXGBE_TXD_STAT_DD) {
+		    delta++;
+		    l =3D (l =3D=3D lim) ? 0 : l + 1;
+		}
+	    } else {
 		l =3D IXGBE_READ_REG(&adapter->hw, IXGBE_TDH(ring_nr));
 		if (l >=3D kring->nkr_num_slots) { /* XXX can happen */
 			D("TDH wrap %d", l);
 			l -=3D kring->nkr_num_slots;
 		}
 		delta =3D l - txr->next_to_clean;
+	    }
 		if (delta) {
 			/* some tx completed, increment avail */
 			if (delta < 0)
@@ -402,23 +481,36 @@
 	 *
 	 * rxr->next_to_check is set to 0 on a ring reinit
 	 */
-	l =3D rxr->next_to_check;
-	j =3D netmap_idx_n2k(kring, l);
+	if (netmap_no_pendintr || force_update) {
+		/* XXX apparently the length field in advanced descriptors
+		 * does not include the CRC irrespective of the setting
+		 * of CRCSTRIP. The data sheets say differently.
+		 * Very strange.
+		 */
+		int crclen =3D ix_crcstrip ? 0 : 4;
+		l =3D rxr->next_to_check;
+		j =3D netmap_idx_n2k(kring, l);
=20
-	if (netmap_no_pendintr || force_update) {
 		for (n =3D 0; ; n++) {
 			union ixgbe_adv_rx_desc *curr =3D &rxr->rx_base[l];
 			uint32_t staterr =3D le32toh(curr->wb.upper.status_error);
=20
 			if ((staterr & IXGBE_RXD_STAT_DD) =3D=3D 0)
 				break;
-			ring->slot[j].len =3D le16toh(curr->wb.upper.length);
+			ring->slot[j].len =3D le16toh(curr->wb.upper.length) - crclen;
+			if (ix_write_len)
+				D("rx[%d] len %d", j, ring->slot[j].len);
 			bus_dmamap_sync(rxr->ptag,
 			    rxr->rx_buffers[l].pmap, BUS_DMASYNC_POSTREAD);
 			j =3D (j =3D=3D lim) ? 0 : j + 1;
 			l =3D (l =3D=3D lim) ? 0 : l + 1;
 		}
 		if (n) { /* update the state variables */
+			if (netmap_no_pendintr && !force_update) {
+				/* diagnostics */
+				ix_rx_miss ++;
+				ix_rx_miss_bufs +=3D n;
+			}
 			rxr->next_to_check =3D l;
 			kring->nr_hwavail +=3D n;
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/netmap/netmap.c
--- a/head/sys/dev/netmap/netmap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/netmap/netmap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -53,7 +53,7 @@
  */
=20
 #include <sys/cdefs.h> /* prerequisite */
-__FBSDID("$FreeBSD: head/sys/dev/netmap/netmap.c 232238 2012-02-27 19:05:0=
1Z luigi $");
+__FBSDID("$FreeBSD: head/sys/dev/netmap/netmap.c 234227 2012-04-13 16:03:0=
7Z luigi $");
=20
 #include <sys/types.h>
 #include <sys/module.h>
@@ -111,512 +111,18 @@
     CTLFLAG_RD, &netmap_buf_size, 0, "Size of packet buffers");
 int netmap_mitigate =3D 1;
 SYSCTL_INT(_dev_netmap, OID_AUTO, mitigate, CTLFLAG_RW, &netmap_mitigate, =
0, "");
-int netmap_no_pendintr;
+int netmap_no_pendintr =3D 1;
 SYSCTL_INT(_dev_netmap, OID_AUTO, no_pendintr,
     CTLFLAG_RW, &netmap_no_pendintr, 0, "Always look for new received pack=
ets.");
=20
=20
-
-/*----- memory allocator -----------------*/
-/*
- * Here we have the low level routines for memory allocator
- * and its primary users.
- */
-
-/*
- * Default amount of memory pre-allocated by the module.
- * We start with a large size and then shrink our demand
- * according to what is avalable when the module is loaded.
- * At the moment the block is contiguous, but we can easily
- * restrict our demand to smaller units (16..64k)
- */
-#define NETMAP_MEMORY_SIZE (64 * 1024 * PAGE_SIZE)
-static void * netmap_malloc(size_t size, const char *msg);
-static void netmap_free(void *addr, const char *msg);
-
-#define netmap_if_malloc(len)   netmap_malloc(len, "nifp")
-#define netmap_if_free(v)	netmap_free((v), "nifp")
-
-#define netmap_ring_malloc(len) netmap_malloc(len, "ring")
-#define netmap_free_rings(na)		\
-	netmap_free((na)->tx_rings[0].ring, "shadow rings");
-
-/*
- * Allocator for a pool of packet buffers. For each buffer we have
- * one entry in the bitmap to signal the state. Allocation scans
- * the bitmap, but since this is done only on attach, we are not
- * too worried about performance
- * XXX if we need to allocate small blocks, a translation
- * table is used both for kernel virtual address and physical
- * addresses.
- */
-struct netmap_buf_pool {
-	u_int total_buffers;	/* total buffers. */
-	u_int free;
-	u_int bufsize;
-	char *base;		/* buffer base address */
-	uint32_t *bitmap;	/* one bit per buffer, 1 means free */
-};
-struct netmap_buf_pool nm_buf_pool;
-SYSCTL_INT(_dev_netmap, OID_AUTO, total_buffers,
-    CTLFLAG_RD, &nm_buf_pool.total_buffers, 0, "total_buffers");
-SYSCTL_INT(_dev_netmap, OID_AUTO, free_buffers,
-    CTLFLAG_RD, &nm_buf_pool.free, 0, "free_buffers");
-
-
-
-
-/*
- * Allocate n buffers from the ring, and fill the slot.
- * Buffer 0 is the 'junk' buffer.
- */
-static void
-netmap_new_bufs(struct netmap_if *nifp __unused,
-		struct netmap_slot *slot, u_int n)
-{
-	struct netmap_buf_pool *p =3D &nm_buf_pool;
-	uint32_t bi =3D 0;		/* index in the bitmap */
-	uint32_t mask, j, i =3D 0;	/* slot counter */
-
-	if (n > p->free) {
-		D("only %d out of %d buffers available", i, n);
-		return;
-	}
-	/* termination is guaranteed by p->free */
-	while (i < n && p->free > 0) {
-		uint32_t cur =3D p->bitmap[bi];
-		if (cur =3D=3D 0) { /* bitmask is fully used */
-			bi++;
-			continue;
-		}
-		/* locate a slot */
-		for (j =3D 0, mask =3D 1; (cur & mask) =3D=3D 0; j++, mask <<=3D 1) ;
-		p->bitmap[bi] &=3D ~mask;		/* slot in use */
-		p->free--;
-		slot[i].buf_idx =3D bi*32+j;
-		slot[i].len =3D p->bufsize;
-		slot[i].flags =3D NS_BUF_CHANGED;
-		i++;
-	}
-	ND("allocated %d buffers, %d available", n, p->free);
-}
-
-
-static void
-netmap_free_buf(struct netmap_if *nifp __unused, uint32_t i)
-{
-	struct netmap_buf_pool *p =3D &nm_buf_pool;
-
-	uint32_t pos, mask;
-	if (i >=3D p->total_buffers) {
-		D("invalid free index %d", i);
-		return;
-	}
-	pos =3D i / 32;
-	mask =3D 1 << (i % 32);
-	if (p->bitmap[pos] & mask) {
-		D("slot %d already free", i);
-		return;
-	}
-	p->bitmap[pos] |=3D mask;
-	p->free++;
-}
-
-
-/* Descriptor of the memory objects handled by our memory allocator. */
-struct netmap_mem_obj {
-	TAILQ_ENTRY(netmap_mem_obj) nmo_next; /* next object in the
-						 chain. */
-	int nmo_used; /* flag set on used memory objects. */
-	size_t nmo_size; /* size of the memory area reserved for the
-			    object. */
-	void *nmo_data; /* pointer to the memory area. */
-};
-
-/* Wrap our memory objects to make them ``chainable``. */
-TAILQ_HEAD(netmap_mem_obj_h, netmap_mem_obj);
-
-
-/* Descriptor of our custom memory allocator. */
-struct netmap_mem_d {
-	struct mtx nm_mtx; /* lock used to handle the chain of memory
-			      objects. */
-	struct netmap_mem_obj_h nm_molist; /* list of memory objects */
-	size_t nm_size; /* total amount of memory used for rings etc. */
-	size_t nm_totalsize; /* total amount of allocated memory
-		(the difference is used for buffers) */
-	size_t nm_buf_start; /* offset of packet buffers.
-			This is page-aligned. */
-	size_t nm_buf_len; /* total memory for buffers */
-	void *nm_buffer; /* pointer to the whole pre-allocated memory
-			    area. */
-};
-
-/* Shorthand to compute a netmap interface offset. */
-#define netmap_if_offset(v)                                     \
-    ((char *) (v) - (char *) nm_mem->nm_buffer)
-/* .. and get a physical address given a memory offset */
-#define netmap_ofstophys(o)                                     \
-    (vtophys(nm_mem->nm_buffer) + (o))
-
-
-/*------ netmap memory allocator -------*/
-/*
- * Request for a chunk of memory.
- *
- * Memory objects are arranged into a list, hence we need to walk this
- * list until we find an object with the needed amount of data free.
- * This sounds like a completely inefficient implementation, but given
- * the fact that data allocation is done once, we can handle it
- * flawlessly.
- *
- * Return NULL on failure.
- */
-static void *
-netmap_malloc(size_t size, __unused const char *msg)
-{
-	struct netmap_mem_obj *mem_obj, *new_mem_obj;
-	void *ret =3D NULL;
-
-	NMA_LOCK();
-	TAILQ_FOREACH(mem_obj, &nm_mem->nm_molist, nmo_next) {
-		if (mem_obj->nmo_used !=3D 0 || mem_obj->nmo_size < size)
-			continue;
-
-		new_mem_obj =3D malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
-				     M_WAITOK | M_ZERO);
-		TAILQ_INSERT_BEFORE(mem_obj, new_mem_obj, nmo_next);
-
-		new_mem_obj->nmo_used =3D 1;
-		new_mem_obj->nmo_size =3D size;
-		new_mem_obj->nmo_data =3D mem_obj->nmo_data;
-		memset(new_mem_obj->nmo_data, 0, new_mem_obj->nmo_size);
-
-		mem_obj->nmo_size -=3D size;
-		mem_obj->nmo_data =3D (char *) mem_obj->nmo_data + size;
-		if (mem_obj->nmo_size =3D=3D 0) {
-			TAILQ_REMOVE(&nm_mem->nm_molist, mem_obj,
-				     nmo_next);
-			free(mem_obj, M_NETMAP);
-		}
-
-		ret =3D new_mem_obj->nmo_data;
-
-		break;
-	}
-	NMA_UNLOCK();
-	ND("%s: %d bytes at %p", msg, size, ret);
-
-	return (ret);
-}
-
-/*
- * Return the memory to the allocator.
- *
- * While freeing a memory object, we try to merge adjacent chunks in
- * order to reduce memory fragmentation.
- */
-static void
-netmap_free(void *addr, const char *msg)
-{
-	size_t size;
-	struct netmap_mem_obj *cur, *prev, *next;
-
-	if (addr =3D=3D NULL) {
-		D("NULL addr for %s", msg);
-		return;
-	}
-
-	NMA_LOCK();
-	TAILQ_FOREACH(cur, &nm_mem->nm_molist, nmo_next) {
-		if (cur->nmo_data =3D=3D addr && cur->nmo_used)
-			break;
-	}
-	if (cur =3D=3D NULL) {
-		NMA_UNLOCK();
-		D("invalid addr %s %p", msg, addr);
-		return;
-	}
-
-	size =3D cur->nmo_size;
-	cur->nmo_used =3D 0;
-
-	/* merge current chunk of memory with the previous one,
-	   if present. */
-	prev =3D TAILQ_PREV(cur, netmap_mem_obj_h, nmo_next);
-	if (prev && prev->nmo_used =3D=3D 0) {
-		TAILQ_REMOVE(&nm_mem->nm_molist, cur, nmo_next);
-		prev->nmo_size +=3D cur->nmo_size;
-		free(cur, M_NETMAP);
-		cur =3D prev;
-	}
-
-	/* merge with the next one */
-	next =3D TAILQ_NEXT(cur, nmo_next);
-	if (next && next->nmo_used =3D=3D 0) {
-		TAILQ_REMOVE(&nm_mem->nm_molist, next, nmo_next);
-		cur->nmo_size +=3D next->nmo_size;
-		free(next, M_NETMAP);
-	}
-	NMA_UNLOCK();
-	ND("freed %s %d bytes at %p", msg, size, addr);
-}
-
-
-/*
- * Create and return a new ``netmap_if`` object, and possibly also
- * rings and packet buffors.
- *
- * Return NULL on failure.
- */
-static void *
-netmap_if_new(const char *ifname, struct netmap_adapter *na)
-{
-	struct netmap_if *nifp;
-	struct netmap_ring *ring;
-	struct netmap_kring *kring;
-	char *buff;
-	u_int i, len, ofs, numdesc;
-	u_int nrx =3D na->num_rx_queues + 1; /* shorthand, include stack queue */
-	u_int ntx =3D na->num_tx_queues + 1; /* shorthand, include stack queue */
-
-	/*
-	 * the descriptor is followed inline by an array of offsets
-	 * to the tx and rx rings in the shared memory region.
-	 */
-	len =3D sizeof(struct netmap_if) + (nrx + ntx) * sizeof(ssize_t);
-	nifp =3D netmap_if_malloc(len);
-	if (nifp =3D=3D NULL)
-		return (NULL);
-
-	/* initialize base fields */
-	*(int *)(uintptr_t)&nifp->ni_rx_queues =3D na->num_rx_queues;
-	*(int *)(uintptr_t)&nifp->ni_tx_queues =3D na->num_tx_queues;
-	strncpy(nifp->ni_name, ifname, IFNAMSIZ);
-
-	(na->refcount)++;	/* XXX atomic ? we are under lock */
-	if (na->refcount > 1)
-		goto final;
-
-	/*
-	 * First instance. Allocate the netmap rings
-	 * (one for each hw queue, one pair for the host).
-	 * The rings are contiguous, but have variable size.
-	 * The entire block is reachable at
-	 *	na->tx_rings[0]
-	 */
-	len =3D (ntx + nrx) * sizeof(struct netmap_ring) +
-	      (ntx * na->num_tx_desc + nrx * na->num_rx_desc) *
-		   sizeof(struct netmap_slot);
-	buff =3D netmap_ring_malloc(len);
-	if (buff =3D=3D NULL) {
-		D("failed to allocate %d bytes for %s shadow ring",
-			len, ifname);
-error:
-		(na->refcount)--;
-		netmap_if_free(nifp);
-		return (NULL);
-	}
-	/* Check whether we have enough buffers */
-	len =3D ntx * na->num_tx_desc + nrx * na->num_rx_desc;
-	NMA_LOCK();
-	if (nm_buf_pool.free < len) {
-		NMA_UNLOCK();
-		netmap_free(buff, "not enough bufs");
-		goto error;
-	}
-	/*
-	 * in the kring, store the pointers to the shared rings
-	 * and initialize the rings. We are under NMA_LOCK().
-	 */
-	ofs =3D 0;
-	for (i =3D 0; i < ntx; i++) { /* Transmit rings */
-		kring =3D &na->tx_rings[i];
-		numdesc =3D na->num_tx_desc;
-		bzero(kring, sizeof(*kring));
-		kring->na =3D na;
-
-		ring =3D kring->ring =3D (struct netmap_ring *)(buff + ofs);
-		*(ssize_t *)(uintptr_t)&ring->buf_ofs =3D
-			nm_buf_pool.base - (char *)ring;
-		ND("txring[%d] at %p ofs %d", i, ring, ring->buf_ofs);
-		*(uint32_t *)(uintptr_t)&ring->num_slots =3D
-			kring->nkr_num_slots =3D numdesc;
-
-		/*
-		 * IMPORTANT:
-		 * Always keep one slot empty, so we can detect new
-		 * transmissions comparing cur and nr_hwcur (they are
-		 * the same only if there are no new transmissions).
-		 */
-		ring->avail =3D kring->nr_hwavail =3D numdesc - 1;
-		ring->cur =3D kring->nr_hwcur =3D 0;
-		*(uint16_t *)(uintptr_t)&ring->nr_buf_size =3D NETMAP_BUF_SIZE;
-		netmap_new_bufs(nifp, ring->slot, numdesc);
-
-		ofs +=3D sizeof(struct netmap_ring) +
-			numdesc * sizeof(struct netmap_slot);
-	}
-
-	for (i =3D 0; i < nrx; i++) { /* Receive rings */
-		kring =3D &na->rx_rings[i];
-		numdesc =3D na->num_rx_desc;
-		bzero(kring, sizeof(*kring));
-		kring->na =3D na;
-
-		ring =3D kring->ring =3D (struct netmap_ring *)(buff + ofs);
-		*(ssize_t *)(uintptr_t)&ring->buf_ofs =3D
-			nm_buf_pool.base - (char *)ring;
-		ND("rxring[%d] at %p offset %d", i, ring, ring->buf_ofs);
-		*(uint32_t *)(uintptr_t)&ring->num_slots =3D
-			kring->nkr_num_slots =3D numdesc;
-		ring->cur =3D kring->nr_hwcur =3D 0;
-		ring->avail =3D kring->nr_hwavail =3D 0; /* empty */
-		*(uint16_t *)(uintptr_t)&ring->nr_buf_size =3D NETMAP_BUF_SIZE;
-		netmap_new_bufs(nifp, ring->slot, numdesc);
-		ofs +=3D sizeof(struct netmap_ring) +
-			numdesc * sizeof(struct netmap_slot);
-	}
-	NMA_UNLOCK();
-	// XXX initialize the selrecord structs.
-
-final:
-	/*
-	 * fill the slots for the rx and tx queues. They contain the offset
-	 * between the ring and nifp, so the information is usable in
-	 * userspace to reach the ring from the nifp.
-	 */
-	for (i =3D 0; i < ntx; i++) {
-		*(ssize_t *)(uintptr_t)&nifp->ring_ofs[i] =3D
-			(char *)na->tx_rings[i].ring - (char *)nifp;
-	}
-	for (i =3D 0; i < nrx; i++) {
-		*(ssize_t *)(uintptr_t)&nifp->ring_ofs[i+ntx] =3D
-			(char *)na->rx_rings[i].ring - (char *)nifp;
-	}
-	return (nifp);
-}
-
-/*
- * Initialize the memory allocator.
- *
- * Create the descriptor for the memory , allocate the pool of memory
- * and initialize the list of memory objects with a single chunk
- * containing the whole pre-allocated memory marked as free.
- *
- * Start with a large size, then halve as needed if we fail to
- * allocate the block. While halving, always add one extra page
- * because buffers 0 and 1 are used for special purposes.
- * Return 0 on success, errno otherwise.
- */
-static int
-netmap_memory_init(void)
-{
-	struct netmap_mem_obj *mem_obj;
-	void *buf =3D NULL;
-	int i, n, sz =3D NETMAP_MEMORY_SIZE;
-	int extra_sz =3D 0; // space for rings and two spare buffers
-
-	for (; sz >=3D 1<<20; sz >>=3D1) {
-		extra_sz =3D sz/200;
-		extra_sz =3D (extra_sz + 2*PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
-	        buf =3D contigmalloc(sz + extra_sz,
-			     M_NETMAP,
-			     M_WAITOK | M_ZERO,
-			     0, /* low address */
-			     -1UL, /* high address */
-			     PAGE_SIZE, /* alignment */
-			     0 /* boundary */
-			    );
-		if (buf)
-			break;
-	}
-	if (buf =3D=3D NULL)
-		return (ENOMEM);
-	sz +=3D extra_sz;
-	nm_mem =3D malloc(sizeof(struct netmap_mem_d), M_NETMAP,
-			      M_WAITOK | M_ZERO);
-	mtx_init(&nm_mem->nm_mtx, "netmap memory allocator lock", NULL,
-		 MTX_DEF);
-	TAILQ_INIT(&nm_mem->nm_molist);
-	nm_mem->nm_buffer =3D buf;
-	nm_mem->nm_totalsize =3D sz;
-
-	/*
-	 * A buffer takes 2k, a slot takes 8 bytes + ring overhead,
-	 * so the ratio is 200:1. In other words, we can use 1/200 of
-	 * the memory for the rings, and the rest for the buffers,
-	 * and be sure we never run out.
-	 */
-	nm_mem->nm_size =3D sz/200;
-	nm_mem->nm_buf_start =3D
-		(nm_mem->nm_size + PAGE_SIZE - 1) & ~(PAGE_SIZE-1);
-	nm_mem->nm_buf_len =3D sz - nm_mem->nm_buf_start;
-
-	nm_buf_pool.base =3D nm_mem->nm_buffer;
-	nm_buf_pool.base +=3D nm_mem->nm_buf_start;
-	netmap_buffer_base =3D nm_buf_pool.base;
-	D("netmap_buffer_base %p (offset %d)",
-		netmap_buffer_base, (int)nm_mem->nm_buf_start);
-	/* number of buffers, they all start as free */
-
-	netmap_total_buffers =3D nm_buf_pool.total_buffers =3D
-		nm_mem->nm_buf_len / NETMAP_BUF_SIZE;
-	nm_buf_pool.bufsize =3D NETMAP_BUF_SIZE;
-
-	D("Have %d MB, use %dKB for rings, %d buffers at %p",
-		(sz >> 20), (int)(nm_mem->nm_size >> 10),
-		nm_buf_pool.total_buffers, nm_buf_pool.base);
-
-	/* allocate and initialize the bitmap. Entry 0 is considered
-	 * always busy (used as default when there are no buffers left).
-	 */
-	n =3D (nm_buf_pool.total_buffers + 31) / 32;
-	nm_buf_pool.bitmap =3D malloc(sizeof(uint32_t) * n, M_NETMAP,
-			 M_WAITOK | M_ZERO);
-	nm_buf_pool.bitmap[0] =3D ~3; /* slot 0 and 1 always busy */
-	for (i =3D 1; i < n; i++)
-		nm_buf_pool.bitmap[i] =3D ~0;
-	nm_buf_pool.free =3D nm_buf_pool.total_buffers - 2;
-=09
-	mem_obj =3D malloc(sizeof(struct netmap_mem_obj), M_NETMAP,
-			 M_WAITOK | M_ZERO);
-	TAILQ_INSERT_HEAD(&nm_mem->nm_molist, mem_obj, nmo_next);
-	mem_obj->nmo_used =3D 0;
-	mem_obj->nmo_size =3D nm_mem->nm_size;
-	mem_obj->nmo_data =3D nm_mem->nm_buffer;
-
-	return (0);
-}
-
-
-/*
- * Finalize the memory allocator.
- *
- * Free all the memory objects contained inside the list, and deallocate
- * the pool of memory; finally free the memory allocator descriptor.
- */
-static void
-netmap_memory_fini(void)
-{
-	struct netmap_mem_obj *mem_obj;
-
-	while (!TAILQ_EMPTY(&nm_mem->nm_molist)) {
-		mem_obj =3D TAILQ_FIRST(&nm_mem->nm_molist);
-		TAILQ_REMOVE(&nm_mem->nm_molist, mem_obj, nmo_next);
-		if (mem_obj->nmo_used =3D=3D 1) {
-			printf("netmap: leaked %d bytes at %p\n",
-			       (int)mem_obj->nmo_size,
-			       mem_obj->nmo_data);
-		}
-		free(mem_obj, M_NETMAP);
-	}
-	contigfree(nm_mem->nm_buffer, nm_mem->nm_totalsize, M_NETMAP);
-	// XXX mutex_destroy(nm_mtx);
-	free(nm_mem, M_NETMAP);
-}
-/*------------- end of memory allocator -----------------*/
-
+/*------------- memory allocator -----------------*/
+#ifdef NETMAP_MEM2
+#include "netmap_mem2.c"
+#else /* !NETMAP_MEM2 */
+#include "netmap_mem1.c"
+#endif /* !NETMAP_MEM2 */
+/*------------ end of memory allocator ----------*/
=20
 /* Structure associated to each thread which registered an interface. */
 struct netmap_priv_d {
@@ -667,21 +173,21 @@
 		/* Wake up any sleeping threads. netmap_poll will
 		 * then return POLLERR
 		 */
-		for (i =3D 0; i < na->num_tx_queues + 1; i++)
+		for (i =3D 0; i < na->num_tx_rings + 1; i++)
 			selwakeuppri(&na->tx_rings[i].si, PI_NET);
-		for (i =3D 0; i < na->num_rx_queues + 1; i++)
+		for (i =3D 0; i < na->num_rx_rings + 1; i++)
 			selwakeuppri(&na->rx_rings[i].si, PI_NET);
 		selwakeuppri(&na->tx_si, PI_NET);
 		selwakeuppri(&na->rx_si, PI_NET);
 		/* release all buffers */
 		NMA_LOCK();
-		for (i =3D 0; i < na->num_tx_queues + 1; i++) {
+		for (i =3D 0; i < na->num_tx_rings + 1; i++) {
 			struct netmap_ring *ring =3D na->tx_rings[i].ring;
 			lim =3D na->tx_rings[i].nkr_num_slots;
 			for (j =3D 0; j < lim; j++)
 				netmap_free_buf(nifp, ring->slot[j].buf_idx);
 		}
-		for (i =3D 0; i < na->num_rx_queues + 1; i++) {
+		for (i =3D 0; i < na->num_rx_rings + 1; i++) {
 			struct netmap_ring *ring =3D na->rx_rings[i].ring;
 			lim =3D na->rx_rings[i].nkr_num_slots;
 			for (j =3D 0; j < lim; j++)
@@ -754,7 +260,7 @@
 static void
 netmap_sync_to_host(struct netmap_adapter *na)
 {
-	struct netmap_kring *kring =3D &na->tx_rings[na->num_tx_queues];
+	struct netmap_kring *kring =3D &na->tx_rings[na->num_tx_rings];
 	struct netmap_ring *ring =3D kring->ring;
 	struct mbuf *head =3D NULL, *tail =3D NULL, *m;
 	u_int k, n, lim =3D kring->nkr_num_slots - 1;
@@ -814,7 +320,7 @@
 static void
 netmap_sync_from_host(struct netmap_adapter *na, struct thread *td)
 {
-	struct netmap_kring *kring =3D &na->rx_rings[na->num_rx_queues];
+	struct netmap_kring *kring =3D &na->rx_rings[na->num_rx_rings];
 	struct netmap_ring *ring =3D kring->ring;
 	u_int j, n, lim =3D kring->nkr_num_slots;
 	u_int k =3D ring->cur, resvd =3D ring->reserved;
@@ -837,7 +343,7 @@
 	if (j !=3D k) {
 		n =3D k >=3D j ? k - j : k + lim - j;
 		kring->nr_hwavail -=3D n;
-	kring->nr_hwcur =3D k;
+		kring->nr_hwcur =3D k;
 	}
 	k =3D ring->avail =3D kring->nr_hwavail - resvd;
 	if (k =3D=3D 0 && td)
@@ -909,7 +415,7 @@
 	}
 	if (errors) {
 		int pos =3D kring - kring->na->tx_rings;
-		int n =3D kring->na->num_tx_queues + 1;
+		int n =3D kring->na->num_tx_rings + 1;
=20
 		D("total %d errors", errors);
 		errors++;
@@ -937,10 +443,10 @@
 	u_int i =3D ringid & NETMAP_RING_MASK;
 	/* initially (np_qfirst =3D=3D np_qlast) we don't want to lock */
 	int need_lock =3D (priv->np_qfirst !=3D priv->np_qlast);
-	int lim =3D na->num_rx_queues;
+	int lim =3D na->num_rx_rings;
=20
-	if (na->num_tx_queues > lim)
-		lim =3D na->num_tx_queues;
+	if (na->num_tx_rings > lim)
+		lim =3D na->num_tx_rings;
 	if ( (ringid & NETMAP_HW_RING) && i >=3D lim) {
 		D("invalid ring id %d", i);
 		return (EINVAL);
@@ -1025,8 +531,8 @@
 		if (error)
 			break;
 		na =3D NA(ifp); /* retrieve netmap_adapter */
-		nmr->nr_rx_rings =3D na->num_rx_queues;
-		nmr->nr_tx_rings =3D na->num_tx_queues;
+		nmr->nr_rx_rings =3D na->num_rx_rings;
+		nmr->nr_tx_rings =3D na->num_tx_rings;
 		nmr->nr_rx_slots =3D na->num_rx_desc;
 		nmr->nr_tx_slots =3D na->num_tx_desc;
 		if_rele(ifp);	/* return the refcount */
@@ -1113,8 +619,8 @@
 		}
=20
 		/* return the offset of the netmap_if object */
-		nmr->nr_rx_rings =3D na->num_rx_queues;
-		nmr->nr_tx_rings =3D na->num_tx_queues;
+		nmr->nr_rx_rings =3D na->num_rx_rings;
+		nmr->nr_tx_rings =3D na->num_tx_rings;
 		nmr->nr_rx_slots =3D na->num_rx_desc;
 		nmr->nr_tx_slots =3D na->num_tx_desc;
 		nmr->nr_memsize =3D nm_mem->nm_totalsize;
@@ -1150,27 +656,28 @@
 		/* find the last ring to scan */
 		lim =3D priv->np_qlast;
 		if (lim =3D=3D NETMAP_HW_RING)
-		    lim =3D (cmd =3D=3D NIOCTXSYNC) ? na->num_tx_queues : na->num_rx_que=
ues;
+			lim =3D (cmd =3D=3D NIOCTXSYNC) ?
+			    na->num_tx_rings : na->num_rx_rings;
=20
 		for (i =3D priv->np_qfirst; i < lim; i++) {
-		    if (cmd =3D=3D NIOCTXSYNC) {
-			struct netmap_kring *kring =3D &na->tx_rings[i];
-			if (netmap_verbose & NM_VERB_TXSYNC)
-				D("sync tx ring %d cur %d hwcur %d",
-					i, kring->ring->cur,
-					kring->nr_hwcur);
-                        na->nm_txsync(ifp, i, 1 /* do lock */);
-			if (netmap_verbose & NM_VERB_TXSYNC)
-				D("after sync tx ring %d cur %d hwcur %d",
-					i, kring->ring->cur,
-					kring->nr_hwcur);
-		    } else {
-			na->nm_rxsync(ifp, i, 1 /* do lock */);
-			microtime(&na->rx_rings[i].ring->ts);
-		    }
+			if (cmd =3D=3D NIOCTXSYNC) {
+				struct netmap_kring *kring =3D &na->tx_rings[i];
+				if (netmap_verbose & NM_VERB_TXSYNC)
+					D("pre txsync ring %d cur %d hwcur %d",
+					    i, kring->ring->cur,
+					    kring->nr_hwcur);
+				na->nm_txsync(ifp, i, 1 /* do lock */);
+				if (netmap_verbose & NM_VERB_TXSYNC)
+					D("post txsync ring %d cur %d hwcur %d",
+					    i, kring->ring->cur,
+					    kring->nr_hwcur);
+			} else {
+				na->nm_rxsync(ifp, i, 1 /* do lock */);
+				microtime(&na->rx_rings[i].ring->ts);
+			}
 		}
=20
-                break;
+		break;
=20
 	case BIOCIMMEDIATE:
 	case BIOCGHDRCMPLT:
@@ -1235,8 +742,8 @@
=20
 	na =3D NA(ifp); /* retrieve netmap adapter */
=20
-	lim_tx =3D na->num_tx_queues;
-	lim_rx =3D na->num_rx_queues;
+	lim_tx =3D na->num_tx_rings;
+	lim_rx =3D na->num_rx_rings;
 	/* how many queues we are scanning */
 	if (priv->np_qfirst =3D=3D NETMAP_SW_RING) {
 		if (priv->np_txpoll || want_tx) {
@@ -1458,7 +965,7 @@
  * kring	N+1	is only used for the selinfo for all queues.
  * Return 0 on success, ENOMEM otherwise.
  *
- * na->num_tx_queues can be set for cards with different tx/rx setups
+ * na->num_tx_rings can be set for cards with different tx/rx setups
  */
 int
 netmap_attach(struct netmap_adapter *na, int num_queues)
@@ -1473,22 +980,21 @@
 	}
 	/* clear other fields ? */
 	na->refcount =3D 0;
-	if (na->num_tx_queues =3D=3D 0)
-		na->num_tx_queues =3D num_queues;
-	na->num_rx_queues =3D num_queues;
+	if (na->num_tx_rings =3D=3D 0)
+		na->num_tx_rings =3D num_queues;
+	na->num_rx_rings =3D num_queues;
 	/* on each direction we have N+1 resources
 	 * 0..n-1	are the hardware rings
 	 * n		is the ring attached to the stack.
 	 */
-	n =3D na->num_rx_queues + na->num_tx_queues + 2;
+	n =3D na->num_rx_rings + na->num_tx_rings + 2;
 	size =3D sizeof(*na) + n * sizeof(struct netmap_kring);
=20
 	buf =3D malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
 	if (buf) {
 		WNA(ifp) =3D buf;
 		na->tx_rings =3D (void *)((char *)buf + sizeof(*na));
-		na->rx_rings =3D na->tx_rings + na->num_tx_queues + 1;
-		na->buff_size =3D NETMAP_BUF_SIZE;
+		na->rx_rings =3D na->tx_rings + na->num_tx_rings + 1;
 		bcopy(na, buf, sizeof(*na));
 		ifp->if_capabilities |=3D IFCAP_NETMAP;
=20
@@ -1496,9 +1002,9 @@
 		if (na->nm_lock =3D=3D NULL)
 			na->nm_lock =3D netmap_lock_wrapper;
 		mtx_init(&na->core_lock, "netmap core lock", NULL, MTX_DEF);
-		for (i =3D 0 ; i < na->num_tx_queues + 1; i++)
+		for (i =3D 0 ; i < na->num_tx_rings + 1; i++)
 			mtx_init(&na->tx_rings[i].q_lock, "netmap txq lock", NULL, MTX_DEF);
-		for (i =3D 0 ; i < na->num_rx_queues + 1; i++)
+		for (i =3D 0 ; i < na->num_rx_rings + 1; i++)
 			mtx_init(&na->rx_rings[i].q_lock, "netmap rxq lock", NULL, MTX_DEF);
 	}
 #ifdef linux
@@ -1526,11 +1032,11 @@
 	if (!na)
 		return;
=20
-	for (i =3D 0; i < na->num_tx_queues + 1; i++) {
+	for (i =3D 0; i < na->num_tx_rings + 1; i++) {
 		knlist_destroy(&na->tx_rings[i].si.si_note);
 		mtx_destroy(&na->tx_rings[i].q_lock);
 	}
-	for (i =3D 0; i < na->num_rx_queues + 1; i++) {
+	for (i =3D 0; i < na->num_rx_rings + 1; i++) {
 		knlist_destroy(&na->rx_rings[i].si.si_note);
 		mtx_destroy(&na->rx_rings[i].q_lock);
 	}
@@ -1551,7 +1057,7 @@
 netmap_start(struct ifnet *ifp, struct mbuf *m)
 {
 	struct netmap_adapter *na =3D NA(ifp);
-	struct netmap_kring *kring =3D &na->rx_rings[na->num_rx_queues];
+	struct netmap_kring *kring =3D &na->rx_rings[na->num_rx_rings];
 	u_int i, len =3D MBUF_LEN(m);
 	int error =3D EBUSY, lim =3D kring->nkr_num_slots - 1;
 	struct netmap_slot *slot;
@@ -1578,7 +1084,7 @@
 	slot->len =3D len;
 	kring->nr_hwavail++;
 	if (netmap_verbose  & NM_VERB_HOST)
-		D("wake up host ring %s %d", na->ifp->if_xname, na->num_rx_queues);
+		D("wake up host ring %s %d", na->ifp->if_xname, na->num_rx_rings);
 	selwakeuppri(&kring->si, PI_NET);
 	error =3D 0;
 done:
@@ -1645,13 +1151,13 @@
  * Default functions to handle rx/tx interrupts
  * we have 4 cases:
  * 1 ring, single lock:
- *     lock(core); wake(i=3D0); unlock(core)
+ *	lock(core); wake(i=3D0); unlock(core)
  * N rings, single lock:
- *     lock(core); wake(i); wake(N+1) unlock(core)
+ *	lock(core); wake(i); wake(N+1) unlock(core)
  * 1 ring, separate locks: (i=3D0)
- *     lock(i); wake(i); unlock(i)
+ *	lock(i); wake(i); unlock(i)
  * N rings, separate locks:
- *     lock(i); wake(i); unlock(i); lock(core) wake(N+1) unlock(core)
+ *	lock(i); wake(i); unlock(i); lock(core) wake(N+1) unlock(core)
  * work_done is non-null on the RX path.
  */
 int
@@ -1667,10 +1173,10 @@
 	if (work_done) { /* RX path */
 		r =3D na->rx_rings + q;
 		r->nr_kflags |=3D NKR_PENDINTR;
-		main_wq =3D (na->num_rx_queues > 1) ? &na->tx_si : NULL;
+		main_wq =3D (na->num_rx_rings > 1) ? &na->rx_si : NULL;
 	} else { /* tx path */
 		r =3D na->tx_rings + q;
-		main_wq =3D (na->num_tx_queues > 1) ? &na->rx_si : NULL;
+		main_wq =3D (na->num_tx_rings > 1) ? &na->tx_si : NULL;
 		work_done =3D &q; /* dummy */
 	}
 	if (na->separate_locks) {
@@ -1689,7 +1195,7 @@
 			selwakeuppri(main_wq, PI_NET);
 		mtx_unlock(&na->core_lock);
 	}
-		*work_done =3D 1; /* do not fire napi again */
+	*work_done =3D 1; /* do not fire napi again */
 	return 1;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/netmap/netmap_kern.h
--- a/head/sys/dev/netmap/netmap_kern.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/netmap/netmap_kern.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 /*
- * $FreeBSD: head/sys/dev/netmap/netmap_kern.h 232238 2012-02-27 19:05:01Z=
 luigi $
+ * $FreeBSD: head/sys/dev/netmap/netmap_kern.h 234227 2012-04-13 16:03:07Z=
 luigi $
  * $Id: netmap_kern.h 10602 2012-02-21 16:47:55Z luigi $
  *
  * The header contains the definitions of constants and function
@@ -34,6 +34,8 @@
 #ifndef _NET_NETMAP_KERN_H_
 #define _NET_NETMAP_KERN_H_
=20
+#define NETMAP_MEM2    // use the new memory allocator
+
 #if defined(__FreeBSD__)
 #define	NM_LOCK_T	struct mtx
 #define	NM_SELINFO_T	struct selinfo
@@ -86,7 +88,7 @@
 	u_int nr_hwcur;
 	int nr_hwavail;
 	u_int nr_kflags;	/* private driver flags */
-#define NKR_PENDINTR   0x1     // Pending interrupt.
+#define NKR_PENDINTR	0x1	// Pending interrupt.
 	u_int nkr_num_slots;
=20
 	int	nkr_hwofs;	/* offset between NIC and netmap ring */
@@ -104,20 +106,25 @@
 	int refcount; /* number of user-space descriptors using this
 			 interface, which is equal to the number of
 			 struct netmap_if objs in the mapped region. */
+	/*
+	 * The selwakeup in the interrupt thread can use per-ring
+	 * and/or global wait queues. We track how many clients
+	 * of each type we have so we can optimize the drivers,
+	 * and especially avoid huge contention on the locks.
+	 */
+	int na_single;	/* threads attached to a single hw queue */
+	int na_multi;	/* threads attached to multiple hw queues */
=20
 	int separate_locks; /* set if the interface suports different
 			       locks for rx, tx and core. */
=20
-	u_int num_rx_queues; /* number of tx/rx queue pairs: this is
-			   a duplicate field needed to simplify the
-			   signature of ``netmap_detach``. */
-	u_int num_tx_queues;	// if nonzero, overrides num_queues XXX
+	u_int num_rx_rings; /* number of tx/rx ring pairs */
+	u_int num_tx_rings; // if nonzero, overrides num_rx_rings
=20
 	u_int num_tx_desc; /* number of descriptor in each queue */
 	u_int num_rx_desc;
-	u_int buff_size;	// XXX deprecate, use NETMAP_BUF_SIZE
+	//u_int buff_size;	// XXX deprecate, use NETMAP_BUF_SIZE
=20
-	//u_int	flags;	// XXX unused
 	/* tx_rings and rx_rings are private but allocated
 	 * as a contiguous chunk of memory. Each array has
 	 * N+1 entries, for the adapter queues and for the host queue.
@@ -129,9 +136,7 @@
=20
 	/* copy of if_qflush and if_transmit pointers, to intercept
 	 * packets from the network stack when netmap is active.
-	 * XXX probably if_qflush is not necessary.
 	 */
-	//void    (*if_qflush)(struct ifnet *);	// XXX unused
 	int     (*if_transmit)(struct ifnet *, struct mbuf *);
=20
 	/* references to the ifnet and device routines, used by
@@ -208,7 +213,7 @@
 int netmap_ring_reinit(struct netmap_kring *);
=20
 extern int netmap_buf_size;
-#define NETMAP_BUF_SIZE netmap_buf_size
+#define NETMAP_BUF_SIZE	netmap_buf_size
 extern int netmap_mitigate;
 extern int netmap_no_pendintr;
 extern u_int netmap_total_buffers;
@@ -294,6 +299,21 @@
 }
=20
=20
+#ifdef NETMAP_MEM2
+/* Entries of the look-up table. */
+struct lut_entry {
+	void *vaddr;		/* virtual address. */
+	vm_paddr_t paddr;	/* phisical address. */
+};
+
+struct netmap_obj_pool;
+extern struct lut_entry *netmap_buffer_lut;
+#define NMB_VA(i)	(netmap_buffer_lut[i].vaddr)
+#define NMB_PA(i)	(netmap_buffer_lut[i].paddr)
+#else /* NETMAP_MEM1 */
+#define NMB_VA(i)	(netmap_buffer_base + (i * NETMAP_BUF_SIZE) )
+#endif /* NETMAP_MEM2 */
+
 /*
  * NMB return the virtual address of a buffer (buffer 0 on bad index)
  * PNMB also fills the physical address
@@ -302,25 +322,23 @@
 NMB(struct netmap_slot *slot)
 {
 	uint32_t i =3D slot->buf_idx;
-	return (i >=3D netmap_total_buffers) ? netmap_buffer_base :
-		netmap_buffer_base + (i *NETMAP_BUF_SIZE);
+	return (i >=3D netmap_total_buffers) ?  NMB_VA(0) : NMB_VA(i);
 }
=20
 static inline void *
 PNMB(struct netmap_slot *slot, uint64_t *pp)
 {
 	uint32_t i =3D slot->buf_idx;
-	void *ret =3D (i >=3D netmap_total_buffers) ? netmap_buffer_base :
-		netmap_buffer_base + (i *NETMAP_BUF_SIZE);
+	void *ret =3D (i >=3D netmap_total_buffers) ? NMB_VA(0) : NMB_VA(i);
+#ifdef NETMAP_MEM2
+	*pp =3D (i >=3D netmap_total_buffers) ? NMB_PA(0) : NMB_PA(i);
+#else
 	*pp =3D vtophys(ret);
+#endif
 	return ret;
 }
=20
 /* default functions to handle rx/tx interrupts */
 int netmap_rx_irq(struct ifnet *, int, int *);
 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
-#ifdef __linux__
-#define bus_dmamap_sync(_a, _b, _c) // wmb() or rmb() ?
-netdev_tx_t netmap_start_linux(struct sk_buff *skb, struct net_device *dev=
);
-#endif
 #endif /* _NET_NETMAP_KERN_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/pci/pci.c
--- a/head/sys/dev/pci/pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/pci/pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/pci/pci.c 232991 2012-03-14 23:25:46Z jki=
m $");
+__FBSDID("$FreeBSD: head/sys/dev/pci/pci.c 233678 2012-03-29 19:29:24Z jki=
m $");
=20
 #include "opt_bus.h"
=20
@@ -751,7 +751,7 @@
 		}
 	}
=20
-#if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
+#if defined(__powerpc__)
 	/*
 	 * Enable the MSI mapping window for all HyperTransport
 	 * slaves.  PCI-PCI bridges have their windows enabled via
@@ -2817,16 +2817,15 @@
 	    prefetch ? RF_PREFETCHABLE : 0);
 	if (res =3D=3D NULL) {
 		/*
-		 * If the allocation fails, clear the BAR and delete
-		 * the resource list entry to force
-		 * pci_alloc_resource() to allocate resources from the
-		 * parent.
+		 * If the allocation fails, delete the resource list entry
+		 * to force pci_alloc_resource() to allocate resources
+		 * from the parent.
 		 */
 		resource_list_delete(rl, type, reg);
-		start =3D 0;
-	} else
+	} else {
 		start =3D rman_get_start(res);
-	pci_write_bar(dev, pm, start);
+		pci_write_bar(dev, pm, start);
+	}
 	return (barlen);
 }
=20
@@ -3895,7 +3894,7 @@
 	if ((desc =3D malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
=3D
 	    NULL)
 		sprintf(desc, "%s, %s", vp, dp);
- out:
+out:
 	if (vp !=3D NULL)
 		free(vp, M_DEVBUF);
 	if (dp !=3D NULL)
@@ -4171,7 +4170,7 @@
 		    count, *rid, type, rman_get_start(res));
 	map =3D rman_get_start(res);
 	pci_write_bar(child, pm, map);
-out:;
+out:
 	return (res);
 }
=20
@@ -4360,19 +4359,6 @@
 			    type, rid, rman_get_start(rle->res));
 			return;
 		}
-
-#ifndef __PCI_BAR_ZERO_VALID
-		/*
-		 * If this is a BAR, clear the BAR so it stops
-		 * decoding before releasing the resource.
-		 */
-		switch (type) {
-		case SYS_RES_IOPORT:
-		case SYS_RES_MEMORY:
-			pci_write_bar(child, pci_find_bar(child, rid), 0);
-			break;
-		}
-#endif
 		resource_list_unreserve(rl, dev, child, type, rid);
 	}
 	resource_list_delete(rl, type, rid);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/sfxge/sfxge_rx.c
--- a/head/sys/dev/sfxge/sfxge_rx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/sfxge/sfxge_rx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/sfxge/sfxge_rx.c 227569 2011-11-16 17:11:=
13Z philip $");
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/sfxge_rx.c 234086 2012-04-10 06:52:=
21Z glebius $");
=20
 #include <sys/types.h>
 #include <sys/mbuf.h>
@@ -176,10 +176,10 @@
 	/* Allocate mbuf structure */
 	args.flags =3D M_PKTHDR;
 	args.type =3D MT_DATA;
-	m =3D (struct mbuf *)uma_zalloc_arg(zone_mbuf, &args, M_DONTWAIT);
+	m =3D (struct mbuf *)uma_zalloc_arg(zone_mbuf, &args, M_NOWAIT);
=20
 	/* Allocate (and attach) packet buffer */
-	if (m && !uma_zalloc_arg(sc->rx_buffer_zone, m, M_DONTWAIT)) {
+	if (m && !uma_zalloc_arg(sc->rx_buffer_zone, m, M_NOWAIT)) {
 		uma_zfree(zone_mbuf, m);
 		m =3D NULL;
 	}
@@ -586,7 +586,7 @@
 		c =3D TAILQ_FIRST(&st->free_conns);
 		TAILQ_REMOVE(&st->free_conns, c, link);
 	} else {
-		c =3D malloc(sizeof(*c), M_SFXGE, M_DONTWAIT);
+		c =3D malloc(sizeof(*c), M_SFXGE, M_NOWAIT);
 		if (c =3D=3D NULL)
 			return;
 		c->mbuf =3D NULL;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/smc/if_smc.c
--- a/head/sys/dev/smc/if_smc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/smc/if_smc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/smc/if_smc.c 226995 2011-11-01 16:13:59Z =
marius $");
+__FBSDID("$FreeBSD: head/sys/dev/smc/if_smc.c 233991 2012-04-07 06:56:38Z =
stas $");
=20
 /*
  * Driver for SMSC LAN91C111, may work for older variants.
@@ -1237,9 +1237,10 @@
 {
 	struct ifnet	*ifp;
=20
+	SMC_ASSERT_LOCKED(sc);
 	ifp =3D sc->smc_ifp;
-
-	SMC_ASSERT_LOCKED(sc);
+	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) !=3D 0)
+		return;
=20
 	smc_reset(sc);
 	smc_enable(sc);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/sound/pci/emu10kx.c
--- a/head/sys/dev/sound/pci/emu10kx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/sound/pci/emu10kx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/sound/pci/emu10kx.c 230137 2012-01-15 13:36:47Z =
joel $
+ * $FreeBSD: head/sys/dev/sound/pci/emu10kx.c 233362 2012-03-23 12:34:39Z =
jhb $
  */
=20
 #include <sys/param.h>
@@ -1137,7 +1137,7 @@
 	ofs =3D 0;
 	for (idx =3D start; idx < start + blksz; idx++) {
 		mem->bmap[idx >> 3] |=3D 1 << (idx & 7);
-		tmp =3D (uint32_t) (u_long) ((uint8_t *) blk->buf_addr + ofs);
+		tmp =3D (uint32_t) (blk->buf_addr + ofs);
 		mem->ptb_pages[idx] =3D (tmp << 1) | idx;
 		ofs +=3D EMUPAGESIZE;
 	}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/sound/pci/hda/hdaa.c
--- a/head/sys/dev/sound/pci/hda/hdaa.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/sound/pci/hda/hdaa.c	Tue Apr 17 11:51:51 2012 +0300
@@ -45,7 +45,7 @@
=20
 #include "mixer_if.h"
=20
-SND_DECLARE_FILE("$FreeBSD: head/sys/dev/sound/pci/hda/hdaa.c 230641 2012-=
01-28 09:24:57Z mav $");
+SND_DECLARE_FILE("$FreeBSD: head/sys/dev/sound/pci/hda/hdaa.c 233692 2012-=
03-30 08:33:08Z mav $");
=20
 #define hdaa_lock(devinfo)	snd_mtxlock((devinfo)->lock)
 #define hdaa_unlock(devinfo)	snd_mtxunlock((devinfo)->lock)
@@ -612,10 +612,11 @@
 		if (w =3D=3D NULL || w->enable =3D=3D 0 || w->type !=3D
 		    HDA_PARAM_AUDIO_WIDGET_CAP_TYPE_PIN_COMPLEX)
 			continue;
-		if (HDA_PARAM_AUDIO_WIDGET_CAP_UNSOL_CAP(w->param.widget_cap) &&
-		    w->unsol < 0) {
-			w->unsol =3D HDAC_UNSOL_ALLOC(
-			    device_get_parent(devinfo->dev), devinfo->dev, w->nid);
+		if (HDA_PARAM_AUDIO_WIDGET_CAP_UNSOL_CAP(w->param.widget_cap)) {
+			if (w->unsol < 0)
+				w->unsol =3D HDAC_UNSOL_ALLOC(
+				    device_get_parent(devinfo->dev),
+				    devinfo->dev, w->nid);
 			hda_command(devinfo->dev,
 			    HDA_CMD_SET_UNSOLICITED_RESPONSE(0, w->nid,
 			    HDA_CMD_SET_UNSOLICITED_RESPONSE_ENABLE | w->unsol));
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/sound/pci/hda/hdac.c
--- a/head/sys/dev/sound/pci/hda/hdac.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/sound/pci/hda/hdac.c	Tue Apr 17 11:51:51 2012 +0300
@@ -48,7 +48,7 @@
=20
 #define HDA_DRV_TEST_REV	"20120126_0002"
=20
-SND_DECLARE_FILE("$FreeBSD: head/sys/dev/sound/pci/hda/hdac.c 230807 2012-=
01-31 12:57:21Z mav $");
+SND_DECLARE_FILE("$FreeBSD: head/sys/dev/sound/pci/hda/hdac.c 233606 2012-=
03-28 13:28:09Z mav $");
=20
 #define hdac_lock(sc)		snd_mtxlock((sc)->lock)
 #define hdac_unlock(sc)		snd_mtxunlock((sc)->lock)
@@ -1558,8 +1558,10 @@
 	HDA_BOOTHVERBOSE(
 		device_printf(dev, "Reset controller...\n");
 	);
+	callout_stop(&sc->poll_callout);
 	hdac_reset(sc, 0);
 	hdac_unlock(sc);
+	callout_drain(&sc->poll_callout);
 	taskqueue_drain(taskqueue_thread, &sc->unsolq_task);
 	HDA_BOOTHVERBOSE(
 		device_printf(dev, "Suspend done\n");
@@ -1608,6 +1610,7 @@
 	    HDAC_GCTL_UNSOL);
 	HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, HDAC_INTCTL_CIE | HDAC_INTCTL_GIE);
 	DELAY(1000);
+	hdac_poll_reinit(sc);
 	hdac_unlock(sc);
=20
 	error =3D bus_generic_resume(dev);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/sound/usb/uaudio.c
--- a/head/sys/dev/sound/usb/uaudio.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/sound/usb/uaudio.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*	$NetBSD: uaudio.c,v 1.91 2004/11/05 17:46:14 kent Exp $	*/
-/*	$FreeBSD: head/sys/dev/sound/usb/uaudio.c 232039 2012-02-23 07:56:19Z h=
selasky $ */
+/*	$FreeBSD: head/sys/dev/sound/usb/uaudio.c 233774 2012-04-02 10:50:42Z h=
selasky $ */
=20
 /*-
  * Copyright (c) 1999 The NetBSD Foundation, Inc.
@@ -32,7 +32,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/sound/usb/uaudio.c 232039 2012-02-23 07:5=
6:19Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/sound/usb/uaudio.c 233774 2012-04-02 10:5=
0:42Z hselasky $");
=20
 /*
  * USB audio specs: http://www.usb.org/developers/devclass_docs/audio10.pdf
@@ -1272,15 +1272,15 @@
 {
 	struct uaudio_chan *ch =3D usbd_xfer_softc(xfer);
 	struct usb_page_cache *pc;
-	uint32_t n;
-	uint32_t m;
-	uint32_t blockcount;
 	uint32_t offset0;
 	uint32_t offset1;
 	uint32_t mfl;
+	int m;
+	int n;
 	int len;
 	int actlen;
 	int nframes;
+	int blockcount;
=20
 	usbd_xfer_status(xfer, &actlen, NULL, NULL, &nframes);
 	mfl =3D usbd_xfer_max_framelen(xfer);
@@ -1307,9 +1307,9 @@
=20
 				m =3D (ch->end - ch->cur);
=20
-				if (m > len) {
+				if (m > len)
 					m =3D len;
-				}
+
 				usbd_copy_out(pc, offset1, ch->cur, m);
=20
 				len -=3D m;
@@ -1884,10 +1884,10 @@
=20
 static uint32_t
 uaudio_mixer_feature_get_bmaControls(const struct usb_audio_feature_unit *=
d,
-    uint8_t index)
+    uint8_t i)
 {
 	uint32_t temp =3D 0;
-	uint32_t offset =3D (index * d->bControlSize);
+	uint32_t offset =3D (i * d->bControlSize);
=20
 	if (d->bControlSize > 0) {
 		temp |=3D d->bmaControls[offset];
@@ -2636,8 +2636,8 @@
 	return (uat->feature);
 }
=20
-const static struct uaudio_terminal_node *
-uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t ind=
ex)
+static const struct uaudio_terminal_node *
+uaudio_mixer_get_input(const struct uaudio_terminal_node *iot, uint8_t i)
 {
 	struct uaudio_terminal_node *root =3D iot->root;
 	uint8_t n;
@@ -2645,17 +2645,16 @@
 	n =3D iot->usr.id_max;
 	do {
 		if (iot->usr.bit_input[n / 8] & (1 << (n % 8))) {
-			if (!index--) {
+			if (!i--)
 				return (root + n);
-			}
 		}
 	} while (n--);
=20
 	return (NULL);
 }
=20
-const static struct uaudio_terminal_node *
-uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t in=
dex)
+static const struct uaudio_terminal_node *
+uaudio_mixer_get_output(const struct uaudio_terminal_node *iot, uint8_t i)
 {
 	struct uaudio_terminal_node *root =3D iot->root;
 	uint8_t n;
@@ -2663,9 +2662,8 @@
 	n =3D iot->usr.id_max;
 	do {
 		if (iot->usr.bit_output[n / 8] & (1 << (n % 8))) {
-			if (!index--) {
+			if (!i--)
 				return (root + n);
-			}
 		}
 	} while (n--);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/sound/usb/uaudioreg.h
--- a/head/sys/dev/sound/usb/uaudioreg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/sound/usb/uaudioreg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*	$NetBSD: uaudioreg.h,v 1.12 2004/11/05 19:08:29 kent Exp $	*/
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/sound/usb/uaudioreg.h 233774 2012-04-02 10:50:42=
Z hselasky $ */
=20
 /*-
  * Copyright (c) 1999 The NetBSD Foundation, Inc.
@@ -113,9 +113,9 @@
 	uByte	bSamFreqType;
 #define	UA_SAMP_CONTNUOUS 0
 	uByte	tSamFreq[0];
-#define	UA_GETSAMP(p, n) (((p)->tSamFreq[((n)*3)+0]) |	    \
+#define	UA_GETSAMP(p, n) ((uint32_t)((((p)->tSamFreq[((n)*3)+0]) | \
 			  ((p)->tSamFreq[((n)*3)+1] << 8) | \
-			  ((p)->tSamFreq[((n)*3)+2] << 16))
+			  ((p)->tSamFreq[((n)*3)+2] << 16))))
 #define	UA_SAMP_LO(p) UA_GETSAMP(p, 0)
 #define	UA_SAMP_HI(p) UA_GETSAMP(p, 1)
 } __packed;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/syscons/syscons.c
--- a/head/sys/dev/syscons/syscons.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/syscons/syscons.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/syscons/syscons.c 230132 2012-01-15 13:23=
:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/syscons/syscons.c 233664 2012-03-29 15:47=
:29Z hselasky $");
=20
 #include "opt_compat.h"
 #include "opt_syscons.h"
@@ -86,6 +86,9 @@
=20
 #define KEYCODE_BS		0x0e		/* "<-- Backspace" key, XXX */
=20
+/* NULL-safe version of "tty_opened()" */
+#define	tty_opened_ns(tp)	((tp) !=3D NULL && tty_opened(tp))
+
 typedef struct default_attr {
 	int		std_color;		/* normal hardware color */
 	int		rev_color;		/* reverse hardware color */
@@ -740,7 +743,7 @@
     while ((c =3D scgetc(sc, SCGETC_NONBLOCK)) !=3D NOKEY) {
=20
 	cur_tty =3D SC_DEV(sc, sc->cur_scp->index);
-	if (!tty_opened(cur_tty))
+	if (!tty_opened_ns(cur_tty))
 	    continue;
=20
 	if ((*sc->cur_scp->tsw->te_input)(sc->cur_scp, c, cur_tty))
@@ -1134,7 +1137,7 @@
     case VT_OPENQRY:    	/* return free virtual console */
 	for (i =3D sc->first_vty; i < sc->first_vty + sc->vtys; i++) {
 	    tp =3D SC_DEV(sc, i);
-	    if (!tty_opened(tp)) {
+	    if (!tty_opened_ns(tp)) {
 		*(int *)data =3D i + 1;
 		return 0;
 	    }
@@ -1694,6 +1697,7 @@
 	 * spinlock.
 	 */
 	tp =3D SC_DEV(scp->sc, scp->index);
+	/* XXX "tp" can be NULL */
 	tty_lock(tp);
 	if (tty_opened(tp))
 	    sctty_outwakeup(tp);
@@ -2414,7 +2418,7 @@
      */
     tp =3D SC_DEV(sc, cur_scp->index);
     if ((cur_scp->index !=3D next_scr)
-	&& tty_opened(tp)
+	&& tty_opened_ns(tp)
 	&& (cur_scp->smode.mode =3D=3D VT_AUTO)
 	&& ISGRAPHSC(cur_scp)) {
 	splx(s);
@@ -2431,7 +2435,7 @@
      */
     if ((sc_console =3D=3D NULL) || (next_scr !=3D sc_console->index)) {
 	tp =3D SC_DEV(sc, next_scr);
-	if (!tty_opened(tp)) {
+	if (!tty_opened_ns(tp)) {
 	    splx(s);
 	    sc_bell(cur_scp, bios_value.bell_pitch, BELL_DURATION);
 	    DPRINTF(5, ("error 2, requested vty isn't open!\n"));
@@ -3470,7 +3474,7 @@
 			    sc_draw_cursor_image(scp);
 			}
 			tp =3D SC_DEV(sc, scp->index);
-			if (!kdb_active && tty_opened(tp))
+			if (!kdb_active && tty_opened_ns(tp))
 			    sctty_outwakeup(tp);
 #endif
 		    }
@@ -3565,7 +3569,7 @@
 			sc->first_vty + i !=3D this_scr;=20
 			i =3D (i + 1)%sc->vtys) {
 		    struct tty *tp =3D SC_DEV(sc, sc->first_vty + i);
-		    if (tty_opened(tp)) {
+		    if (tty_opened_ns(tp)) {
 			sc_switch_scr(scp->sc, sc->first_vty + i);
 			break;
 		    }
@@ -3578,7 +3582,7 @@
 			sc->first_vty + i !=3D this_scr;
 			i =3D (i + sc->vtys - 1)%sc->vtys) {
 		    struct tty *tp =3D SC_DEV(sc, sc->first_vty + i);
-		    if (tty_opened(tp)) {
+		    if (tty_opened_ns(tp)) {
 			sc_switch_scr(scp->sc, sc->first_vty + i);
 			break;
 		    }
@@ -3774,7 +3778,7 @@
     u_char *rmap;
=20
     tp =3D SC_DEV(scp->sc, scp->sc->cur_scp->index);
-    if (!tty_opened(tp))
+    if (!tty_opened_ns(tp))
 	return;
     rmap =3D scp->sc->scr_rmap;
     for (; count > 0; --count)
@@ -3788,7 +3792,7 @@
     struct tty *tp;
=20
     tp =3D SC_DEV(scp->sc, scp->sc->cur_scp->index);
-    if (!tty_opened(tp))
+    if (!tty_opened_ns(tp))
 	return;
     ttydisc_rint_simple(tp, p, count);
     if (wakeup) {
@@ -3830,7 +3834,7 @@
 	scp->sc->blink_in_progress =3D 0;
     	mark_all(scp);
 	tp =3D SC_DEV(scp->sc, scp->index);
-	if (tty_opened(tp))
+	if (tty_opened_ns(tp))
 	    sctty_outwakeup(tp);
 	if (scp->sc->delayed_next_scr)
 	    sc_switch_scr(scp->sc, scp->sc->delayed_next_scr - 1);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/uart/uart_bus.h
--- a/head/sys/dev/uart/uart_bus.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/uart/uart_bus.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/dev/uart/uart_bus.h 234194 2012-04-12 18:46:48Z greh=
an $
  */
=20
 #ifndef _DEV_UART_BUS_H_
@@ -87,6 +87,7 @@
 	struct resource *sc_ires;	/* Interrupt resource. */
 	void		*sc_icookie;
 	int		sc_irid;
+	struct callout	sc_timer;
=20
 	int		sc_callout:1;	/* This UART is opened for callout. */
 	int		sc_fastintr:1;	/* This UART uses fast interrupts. */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/uart/uart_core.c
--- a/head/sys/dev/uart/uart_core.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/uart/uart_core.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/uart/uart_core.c 227293 2011-11-07 06:44:=
47Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/uart/uart_core.c 234194 2012-04-12 18:46:=
48Z grehan $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -58,6 +58,12 @@
=20
 static MALLOC_DEFINE(M_UART, "UART", "UART driver");
=20
+#ifndef	UART_POLL_FREQ
+#define	UART_POLL_FREQ		50
+#endif
+static int uart_poll_freq =3D UART_POLL_FREQ;
+TUNABLE_INT("debug.uart_poll_freq", &uart_poll_freq);
+
 void
 uart_add_sysdev(struct uart_devinfo *di)
 {
@@ -257,6 +263,12 @@
 		if (ipend & SER_INT_TXIDLE)
 			uart_intr_txidle(sc);	=09
 	}
+
+	if (sc->sc_polled) {
+		callout_reset(&sc->sc_timer, hz / uart_poll_freq,
+		    (timeout_t *)uart_intr, sc);
+	}
+
 	return((flag)?FILTER_HANDLED:FILTER_STRAY);
 }
=20
@@ -440,8 +452,9 @@
 		}
 	}
 	if (sc->sc_ires =3D=3D NULL) {
-		/* XXX no interrupt resource. Force polled mode. */
+		/* No interrupt resource. Force polled mode. */
 		sc->sc_polled =3D 1;
+		callout_init(&sc->sc_timer, 1);
 	}
=20
 	sc->sc_rxbufsz =3D 384;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/uart/uart_if.m
--- a/head/sys/dev/uart/uart_if.m	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/uart/uart_if.m	Tue Apr 17 11:51:51 2012 +0300
@@ -23,9 +23,10 @@
 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 #
-# $FreeBSD$
+# $FreeBSD: head/sys/dev/uart/uart_if.m 234194 2012-04-12 18:46:48Z grehan=
 $
=20
 #include <sys/param.h>
+#include <sys/systm.h>
 #include <sys/lock.h>
 #include <sys/mutex.h>
 #include <sys/bus.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/at91dci.c
--- a/head/sys/dev/usb/controller/at91dci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/at91dci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/at91dci.c 228483 2011-12-1=
4 00:28:54Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/at91dci.c 233774 2012-04-0=
2 10:50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 2007-2008 Hans Petter Selasky. All rights reserved.
@@ -1725,14 +1725,13 @@
 	},
 };
=20
+#define	HSETW(ptr, val) ptr =3D { (uint8_t)(val), (uint8_t)((val) >> 8) }
+
 static const struct usb_hub_descriptor_min at91dci_hubd =3D {
 	.bDescLength =3D sizeof(at91dci_hubd),
 	.bDescriptorType =3D UDESC_HUB,
 	.bNbrPorts =3D 1,
-	.wHubCharacteristics[0] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) & 0xFF,
-	.wHubCharacteristics[1] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) >> 8,
+	HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)),
 	.bPwrOn2PwrGood =3D 50,
 	.bHubContrCurrent =3D 0,
 	.DeviceRemovable =3D {0},		/* port is removable */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/atmegadci.c
--- a/head/sys/dev/usb/controller/atmegadci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/atmegadci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/atmegadci.c 228483 2011-12=
-14 00:28:54Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/atmegadci.c 233774 2012-04=
-02 10:50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 2009 Hans Petter Selasky. All rights reserved.
@@ -1548,14 +1548,13 @@
 	},
 };
=20
+#define	HSETW(ptr, val) ptr =3D { (uint8_t)(val), (uint8_t)((val) >> 8) }
+
 static const struct usb_hub_descriptor_min atmegadci_hubd =3D {
 	.bDescLength =3D sizeof(atmegadci_hubd),
 	.bDescriptorType =3D UDESC_HUB,
 	.bNbrPorts =3D 1,
-	.wHubCharacteristics[0] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) & 0xFF,
-	.wHubCharacteristics[1] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) >> 8,
+	HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)),
 	.bPwrOn2PwrGood =3D 50,
 	.bHubContrCurrent =3D 0,
 	.DeviceRemovable =3D {0},		/* port is removable */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/avr32dci.c
--- a/head/sys/dev/usb/controller/avr32dci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/avr32dci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/avr32dci.c 228483 2011-12-=
14 00:28:54Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/avr32dci.c 233774 2012-04-=
02 10:50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 2009 Hans Petter Selasky. All rights reserved.
@@ -1489,14 +1489,13 @@
 	},
 };
=20
+#define	HSETW(ptr, val) ptr =3D { (uint8_t)(val), (uint8_t)((val) >> 8) }
+
 static const struct usb_hub_descriptor_min avr32dci_hubd =3D {
 	.bDescLength =3D sizeof(avr32dci_hubd),
 	.bDescriptorType =3D UDESC_HUB,
 	.bNbrPorts =3D 1,
-	.wHubCharacteristics[0] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) & 0xFF,
-	.wHubCharacteristics[1] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) >> 8,
+	HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)),
 	.bPwrOn2PwrGood =3D 50,
 	.bHubContrCurrent =3D 0,
 	.DeviceRemovable =3D {0},		/* port is removable */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/dwc_otg.c
--- a/head/sys/dev/usb/controller/dwc_otg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/dwc_otg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -42,7 +42,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/dwc_otg.c 232539 2012-03-0=
5 06:41:44Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/dwc_otg.c 233774 2012-04-0=
2 10:50:42Z hselasky $");
=20
 #include <sys/stdint.h>
 #include <sys/stddef.h>
@@ -2057,14 +2057,13 @@
 	},
 };
=20
+#define	HSETW(ptr, val) ptr =3D { (uint8_t)(val), (uint8_t)((val) >> 8) }
+
 static const struct usb_hub_descriptor_min dwc_otg_hubd =3D {
 	.bDescLength =3D sizeof(dwc_otg_hubd),
 	.bDescriptorType =3D UDESC_HUB,
 	.bNbrPorts =3D 1,
-	.wHubCharacteristics[0] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) & 0xFF,
-	.wHubCharacteristics[1] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) >> 8,
+	HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)),
 	.bPwrOn2PwrGood =3D 50,
 	.bHubContrCurrent =3D 0,
 	.DeviceRemovable =3D {0},		/* port is removable */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/ehci.c
--- a/head/sys/dev/usb/controller/ehci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/ehci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -44,7 +44,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/ehci.c 228483 2011-12-14 0=
0:28:54Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/ehci.c 233774 2012-04-02 1=
0:50:42Z hselasky $");
=20
 #include <sys/stdint.h>
 #include <sys/stddef.h>
@@ -3011,13 +3011,8 @@
 static const
 struct usb_hub_descriptor ehci_hubd =3D
 {
-	0,				/* dynamic length */
-	UDESC_HUB,
-	0,
-	{0, 0},
-	0,
-	0,
-	{0},
+	.bDescLength =3D 0,		/* dynamic length */
+	.bDescriptorType =3D UDESC_HUB,
 };
=20
 static void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/musb_otg.c
--- a/head/sys/dev/usb/controller/musb_otg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/musb_otg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/controller/musb_otg.c 228483 2011-12-14 00:2=
8:54Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/controller/musb_otg.c 233774 2012-04-02 10:5=
0:42Z hselasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  *
@@ -2192,14 +2192,13 @@
 	},
 };
=20
+#define	HSETW(ptr, val) ptr =3D { (uint8_t)(val), (uint8_t)((val) >> 8) }
+
 static const struct usb_hub_descriptor_min musbotg_hubd =3D {
 	.bDescLength =3D sizeof(musbotg_hubd),
 	.bDescriptorType =3D UDESC_HUB,
 	.bNbrPorts =3D 1,
-	.wHubCharacteristics[0] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) & 0xFF,
-	.wHubCharacteristics[1] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) >> 16,
+	HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)),
 	.bPwrOn2PwrGood =3D 50,
 	.bHubContrCurrent =3D 0,
 	.DeviceRemovable =3D {0},		/* port is removable */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/ohci.c
--- a/head/sys/dev/usb/controller/ohci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/ohci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/ohci.c 228483 2011-12-14 0=
0:28:54Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/ohci.c 233774 2012-04-02 1=
0:50:42Z hselasky $");
=20
 /*
  * USB Open Host Controller driver.
@@ -2093,13 +2093,8 @@
 static const
 struct usb_hub_descriptor ohci_hubd =3D
 {
-	0,				/* dynamic length */
-	UDESC_HUB,
-	0,
-	{0, 0},
-	0,
-	0,
-	{0},
+	.bDescLength =3D 0,	/* dynamic length */
+	.bDescriptorType =3D UDESC_HUB,
 };
=20
 static usb_error_t
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/uhci.c
--- a/head/sys/dev/usb/controller/uhci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/uhci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/uhci.c 228483 2011-12-14 0=
0:28:54Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/uhci.c 233774 2012-04-02 1=
0:50:42Z hselasky $");
=20
 /*
  * USB Universal Host Controller driver.
@@ -2351,13 +2351,11 @@
 static const
 struct usb_hub_descriptor_min uhci_hubd_piix =3D
 {
-	sizeof(uhci_hubd_piix),
-	UDESC_HUB,
-	2,
-	{UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL, 0},
-	50,				/* power on to power good */
-	0,
-	{0x00},				/* both ports are removable */
+	.bDescLength =3D sizeof(uhci_hubd_piix),
+	.bDescriptorType =3D UDESC_HUB,
+	.bNbrPorts =3D 2,
+	.wHubCharacteristics =3D {UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL, 0},
+	.bPwrOn2PwrGood =3D 50,
 };
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/uss820dci.c
--- a/head/sys/dev/usb/controller/uss820dci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/uss820dci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/controller/uss820dci.c 228483 2011-12-14 00:=
28:54Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/controller/uss820dci.c 233774 2012-04-02 10:=
50:42Z hselasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky <hselasky at FreeBSD.org>
  * All rights reserved.
@@ -1789,14 +1789,13 @@
 	},
 };
=20
+#define	HSETW(ptr, val) ptr =3D { (uint8_t)(val), (uint8_t)((val) >> 8) }
+
 static const struct usb_hub_descriptor_min uss820dci_hubd =3D {
 	.bDescLength =3D sizeof(uss820dci_hubd),
 	.bDescriptorType =3D UDESC_HUB,
 	.bNbrPorts =3D 1,
-	.wHubCharacteristics[0] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) & 0xFF,
-	.wHubCharacteristics[1] =3D
-	(UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL) >> 8,
+	HSETW(.wHubCharacteristics, (UHD_PWR_NO_SWITCH | UHD_OC_INDIVIDUAL)),
 	.bPwrOn2PwrGood =3D 50,
 	.bHubContrCurrent =3D 0,
 	.DeviceRemovable =3D {0},		/* port is removable */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/controller/xhci.c
--- a/head/sys/dev/usb/controller/xhci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/controller/xhci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/controller/xhci.c 230090 2012-01-13 2=
2:19:14Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/controller/xhci.c 233774 2012-04-02 1=
0:50:42Z hselasky $");
=20
 #include <sys/stdint.h>
 #include <sys/stddef.h>
@@ -821,7 +821,7 @@
 		offset =3D td_event - td->td_self;
=20
 		if (offset >=3D 0 &&
-		    offset < sizeof(td->td_trb)) {
+		    offset < (int64_t)sizeof(td->td_trb)) {
=20
 			usb_pc_cpu_invalidate(td->page_cache);
=20
@@ -2805,7 +2805,7 @@
  * Simulate a hardware HUB by handling all the necessary requests.
  *------------------------------------------------------------------------=
*/
=20
-#define	HSETW(ptr, val) ptr[0] =3D (uint8_t)(val), ptr[1] =3D (uint8_t)((v=
al) >> 8)
+#define	HSETW(ptr, val) ptr =3D { (uint8_t)(val), (uint8_t)((val) >> 8) }
=20
 static const
 struct usb_device_descriptor xhci_devd =3D
@@ -2848,8 +2848,7 @@
 		HSETW(.wSpeedsSupported, 0x000C),
 		.bFunctionalitySupport =3D 8,
 		.bU1DevExitLat =3D 255,	/* dummy - not used */
-		.wU2DevExitLat[0] =3D 0x00,
-		.wU2DevExitLat[1] =3D 0x08,
+		.wU2DevExitLat =3D { 0x00, 0x08 },
 	},
 	.cidd =3D {
 		.bLength =3D sizeof(xhci_bosd.cidd),
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/input/atp.c
--- a/head/sys/dev/usb/input/atp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/input/atp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/input/atp.c 227309 2011-11-07 15:43:1=
1Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/input/atp.c 233774 2012-04-02 10:50:4=
2Z hselasky $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -761,7 +761,7 @@
 		 * threshold; this will reduce the contribution from
 		 * lower pressure readings.
 		 */
-		if (p[i] <=3D atp_sensor_noise_threshold)
+		if ((u_int)p[i] <=3D atp_sensor_noise_threshold)
 			p[i] =3D 0; /* filter away noise */
 		else
 			p[i] -=3D atp_sensor_noise_threshold;
@@ -887,7 +887,7 @@
=20
 	delta_mickeys =3D pspan->loc - component->loc;
=20
-	if (abs(delta_mickeys) > atp_max_delta_mickeys)
+	if ((u_int)abs(delta_mickeys) > atp_max_delta_mickeys)
 		return (FALSE); /* the finger span is too far out; no match */
=20
 	component->loc          =3D pspan->loc;
@@ -1164,9 +1164,10 @@
 atp_add_new_strokes(struct atp_softc *sc, atp_pspan *pspans_x,
     u_int n_xpspans, atp_pspan *pspans_y, u_int n_ypspans)
 {
-	int       i, j;
 	atp_pspan spans[2][ATP_MAX_PSPANS_PER_AXIS];
-	u_int     nspans[2];
+	u_int nspans[2];
+	u_int i;
+	u_int j;
=20
 	/* Copy unmatched pspans into the local arrays. */
 	for (i =3D 0, nspans[X] =3D 0; i < n_xpspans; i++) {
@@ -1373,9 +1374,9 @@
 static __inline boolean_t
 atp_stroke_has_small_movement(const atp_stroke *stroke)
 {
-	return ((abs(stroke->components[X].delta_mickeys) <=3D
+	return (((u_int)abs(stroke->components[X].delta_mickeys) <=3D
 		atp_small_movement_threshold) &&
-	    (abs(stroke->components[Y].delta_mickeys) <=3D
+	    ((u_int)abs(stroke->components[Y].delta_mickeys) <=3D
 		atp_small_movement_threshold));
 }
=20
@@ -1388,7 +1389,7 @@
 atp_update_pending_mickeys(atp_stroke_component *component)
 {
 	component->pending +=3D component->delta_mickeys;
-	if (abs(component->pending) <=3D atp_small_movement_threshold)
+	if ((u_int)abs(component->pending) <=3D atp_small_movement_threshold)
 		component->delta_mickeys =3D 0;
 	else {
 		/*
@@ -1690,7 +1691,7 @@
=20
 	if (usb_fifo_attach(sc->sc_usb_device, sc, &sc->sc_mutex,
 		&atp_fifo_methods, &sc->sc_fifo,
-		device_get_unit(dev), 0 - 1, uaa->info.bIfaceIndex,
+		device_get_unit(dev), -1, uaa->info.bIfaceIndex,
 		UID_ROOT, GID_OPERATOR, 0644)) {
 		goto detach;
 	}
@@ -1764,13 +1765,13 @@
=20
 	switch (USB_GET_STATE(xfer)) {
 	case USB_ST_TRANSFERRED:
-		if (len > sc->sc_params->data_len) {
+		if (len > (int)sc->sc_params->data_len) {
 			DPRINTFN(ATP_LLEVEL_ERROR,
 			    "truncating large packet from %u to %u bytes\n",
 			    len, sc->sc_params->data_len);
 			len =3D sc->sc_params->data_len;
 		}
-		if (len < sc->sc_params->data_len)
+		if (len < (int)sc->sc_params->data_len)
 			goto tr_setup;
=20
 		pc =3D usbd_xfer_get_frame(xfer, 0);
@@ -2213,9 +2214,9 @@
 };
=20
 static driver_t atp_driver =3D {
-	ATP_DRIVER_NAME,
-	atp_methods,
-	sizeof(struct atp_softc)
+	.name =3D ATP_DRIVER_NAME,
+	.methods =3D atp_methods,
+	.size =3D sizeof(struct atp_softc)
 };
=20
 static devclass_t atp_devclass;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/input/uep.c
--- a/head/sys/dev/usb/input/uep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/input/uep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/usb/input/uep.c 227309 2011-11-07 15:43:11Z ed $
+ * $FreeBSD: head/sys/dev/usb/input/uep.c 233774 2012-04-02 10:50:42Z hsel=
asky $
  */
=20
 /*
@@ -202,7 +202,7 @@
 		u_char buf[17], *p;
 		int pkt_len;
=20
-		if (len > sizeof(buf)) {
+		if (len > (int)sizeof(buf)) {
 			DPRINTF("bad input length %d\n", len);
 			goto tr_setup;
 		}
@@ -329,7 +329,7 @@
 	}
=20
 	error =3D usb_fifo_attach(uaa->device, sc, &sc->mtx, &uep_fifo_methods,
-	    &sc->fifo, device_get_unit(dev), 0 - 1, uaa->info.bIfaceIndex,
+	    &sc->fifo, device_get_unit(dev), -1, uaa->info.bIfaceIndex,
 	    UID_ROOT, GID_OPERATOR, 0644);
=20
         if (error) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/input/uhid.c
--- a/head/sys/dev/usb/input/uhid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/input/uhid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -5,7 +5,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/input/uhid.c 227309 2011-11-07 15:43:=
11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/input/uhid.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
 /*-
  * Copyright (c) 1998 The NetBSD Foundation, Inc.
@@ -170,10 +170,10 @@
 		 * If the ID byte is non zero we allow descriptors
 		 * having multiple sizes:
 		 */
-		if ((actlen >=3D sc->sc_isize) ||
+		if ((actlen >=3D (int)sc->sc_isize) ||
 		    ((actlen > 0) && (sc->sc_iid !=3D 0))) {
 			/* limit report length to the maximum */
-			if (actlen > sc->sc_isize)
+			if (actlen > (int)sc->sc_isize)
 				actlen =3D sc->sc_isize;
 			usb_fifo_put_data(sc->sc_fifo.fp[USB_FIFO_RX], pc,
 			    0, actlen, 1);
@@ -768,7 +768,7 @@
=20
 	error =3D usb_fifo_attach(uaa->device, sc, &sc->sc_mtx,
 	    &uhid_fifo_methods, &sc->sc_fifo,
-	    unit, 0 - 1, uaa->info.bIfaceIndex,
+	    unit, -1, uaa->info.bIfaceIndex,
 	    UID_ROOT, GID_OPERATOR, 0644);
 	if (error) {
 		goto detach;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/input/ukbd.c
--- a/head/sys/dev/usb/input/ukbd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/input/ukbd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/input/ukbd.c 228765 2011-12-21 11:49:=
33Z avg $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/input/ukbd.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
=20
 /*-
@@ -2047,7 +2047,7 @@
 		0x5c,	/* Keyboard Intl' 6 (Keypad ,) (For PC-9821 layout) */
 	};
=20
-	if ((code >=3D 89) && (code < (89 + (sizeof(scan) / sizeof(scan[0]))))) {
+	if ((code >=3D 89) && (code < (int)(89 + (sizeof(scan) / sizeof(scan[0]))=
))) {
 		code =3D scan[code - 89];
 	}
 	/* Pause/Break */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/input/ums.c
--- a/head/sys/dev/usb/input/ums.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/input/ums.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/input/ums.c 227309 2011-11-07 15:43:1=
1Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/input/ums.c 233774 2012-04-02 10:50:4=
2Z hselasky $");
=20
 /*
  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
@@ -201,7 +201,7 @@
 	case USB_ST_TRANSFERRED:
 		DPRINTFN(6, "sc=3D%p actlen=3D%d\n", sc, len);
=20
-		if (len > sizeof(sc->sc_temp)) {
+		if (len > (int)sizeof(sc->sc_temp)) {
 			DPRINTFN(6, "truncating large packet to %zu bytes\n",
 			    sizeof(sc->sc_temp));
 			len =3D sizeof(sc->sc_temp);
@@ -644,7 +644,7 @@
 		/* Some wheels need the Z axis reversed. */
 		info->sc_flags |=3D UMS_FLAG_REVZ;
 	}
-	if (isize > usbd_xfer_max_framelen(sc->sc_xfer[UMS_INTR_DT])) {
+	if (isize > (int)usbd_xfer_max_framelen(sc->sc_xfer[UMS_INTR_DT])) {
 		DPRINTF("WARNING: report size, %d bytes, is larger "
 		    "than interrupt size, %d bytes!\n", isize,
 		    usbd_xfer_max_framelen(sc->sc_xfer[UMS_INTR_DT]));
@@ -698,7 +698,7 @@
=20
 	err =3D usb_fifo_attach(uaa->device, sc, &sc->sc_mtx,
 	    &ums_fifo_methods, &sc->sc_fifo,
-	    device_get_unit(dev), 0 - 1, uaa->info.bIfaceIndex,
+	    device_get_unit(dev), -1, uaa->info.bIfaceIndex,
   	    UID_ROOT, GID_OPERATOR, 0644);
 	if (err) {
 		goto detach;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/misc/ufm.c
--- a/head/sys/dev/usb/misc/ufm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/misc/ufm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/misc/ufm.c 223515 2011-06-24 19:32:29=
Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/misc/ufm.c 233774 2012-04-02 10:50:42=
Z hselasky $");
=20
=20
 #include <sys/stdint.h>
@@ -156,7 +156,7 @@
=20
 	error =3D usb_fifo_attach(uaa->device, sc, &sc->sc_mtx,
 	    &ufm_fifo_methods, &sc->sc_fifo,
-	    device_get_unit(dev), 0 - 1, uaa->info.bIfaceIndex,
+	    device_get_unit(dev), -1, uaa->info.bIfaceIndex,
 	    UID_ROOT, GID_OPERATOR, 0644);
 	if (error) {
 		goto detach;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_aue.c
--- a/head/sys/dev/usb/net/if_aue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_aue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_aue.c 227843 2011-11-22 21:28:=
20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_aue.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
 /*
  * ADMtek AN986 Pegasus and AN8511 Pegasus II USB to ethernet driver.
@@ -740,7 +740,7 @@
 	case USB_ST_TRANSFERRED:
=20
 		if ((ifp->if_drv_flags & IFF_DRV_RUNNING) &&
-		    actlen >=3D sizeof(pkt)) {
+		    actlen >=3D (int)sizeof(pkt)) {
=20
 			pc =3D usbd_xfer_get_frame(xfer, 0);
 			usbd_copy_out(pc, 0, &pkt, sizeof(pkt));
@@ -793,7 +793,7 @@
 			}
 		} else {
=20
-			if (actlen <=3D sizeof(stat) + ETHER_CRC_LEN) {
+			if (actlen <=3D (int)(sizeof(stat) + ETHER_CRC_LEN)) {
 				ifp->if_ierrors++;
 				goto tr_setup;
 			}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_axe.c
--- a/head/sys/dev/usb/net/if_axe.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_axe.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_axe.c 228637 2011-12-17 15:38:=
16Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_axe.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
 /*
  * ASIX Electronics AX88172/AX88178/AX88778 USB 2.0 ethernet driver.
@@ -1037,7 +1037,7 @@
 	error =3D 0;
 	if ((sc->sc_flags & AXE_FLAG_STD_FRAME) !=3D 0) {
 		while (pos < actlen) {
-			if ((pos + sizeof(hdr)) > actlen) {
+			if ((int)(pos + sizeof(hdr)) > actlen) {
 				/* too little data */
 				error =3D EINVAL;
 				break;
@@ -1061,7 +1061,7 @@
 		}
 	} else if ((sc->sc_flags & AXE_FLAG_CSUM_FRAME) !=3D 0) {
 		while (pos < actlen) {
-			if ((pos + sizeof(csum_hdr)) > actlen) {
+			if ((int)(pos + sizeof(csum_hdr)) > actlen) {
 				/* too little data */
 				error =3D EINVAL;
 				break;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_cdce.c
--- a/head/sys/dev/usb/net/if_cdce.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_cdce.c	Tue Apr 17 11:51:51 2012 +0300
@@ -46,7 +46,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_cdce.c 227309 2011-11-07 15:43=
:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_cdce.c 233774 2012-04-02 10:50=
:42Z hselasky $");
=20
 #include <sys/stdint.h>
 #include <sys/stddef.h>
@@ -303,8 +303,8 @@
 	int err;
=20
 	ufd =3D usbd_find_descriptor(sc->sc_ue.ue_udev, NULL,
-	    sc->sc_ifaces_index[1], UDESC_CS_INTERFACE, 0 - 1,
-	    UCDC_NCM_FUNC_DESC_SUBTYPE, 0 - 1);
+	    sc->sc_ifaces_index[1], UDESC_CS_INTERFACE, 0xFF,
+	    UCDC_NCM_FUNC_DESC_SUBTYPE, 0xFF);
=20
 	/* verify length of NCM functional descriptor */
 	if (ufd !=3D NULL) {
@@ -514,7 +514,7 @@
=20
 	ud =3D usbd_find_descriptor
 	    (uaa->device, NULL, uaa->info.bIfaceIndex,
-	    UDESC_CS_INTERFACE, 0 - 1, UDESCSUB_CDC_UNION, 0 - 1);
+	    UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_UNION, 0xFF);
=20
 	if ((ud =3D=3D NULL) || (ud->bLength < sizeof(*ud)) ||
 	    (sc->sc_flags & CDCE_FLAG_NO_UNION)) {
@@ -598,7 +598,7 @@
=20
 	ued =3D usbd_find_descriptor
 	    (uaa->device, NULL, uaa->info.bIfaceIndex,
-	    UDESC_CS_INTERFACE, 0 - 1, UDESCSUB_CDC_ENF, 0 - 1);
+	    UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_ENF, 0xFF);
=20
 	if ((ued =3D=3D NULL) || (ued->bLength < sizeof(*ued))) {
 		error =3D USB_ERR_INVAL;
@@ -892,7 +892,9 @@
 	struct cdce_softc *sc =3D usbd_xfer_softc(xfer);
 	struct mbuf *m;
 	uint8_t x;
-	int actlen, aframes, len;
+	int actlen;
+	int aframes;
+	int len;
=20
 	usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
=20
@@ -911,7 +913,7 @@
 			if ((sc->sc_flags & CDCE_FLAG_ZAURUS) && len >=3D 14)
 				len -=3D 4;
=20
-			if (len < sizeof(struct ether_header)) {
+			if (len < (int)sizeof(struct ether_header)) {
 				m_freem(m);
 				continue;
 			}
@@ -1096,7 +1098,7 @@
 			break;
 		}
=20
-		if (m->m_pkthdr.len > rem) {
+		if (m->m_pkthdr.len > (int)rem) {
 			if (n =3D=3D 0) {
 				/* The frame won't fit in our buffer */
 				DPRINTFN(1, "Frame too big to be transmitted!\n");
@@ -1278,7 +1280,7 @@
 		DPRINTFN(1, "received %u bytes in %u frames\n",
 		    actlen, aframes);
=20
-		if (actlen < (sizeof(sc->sc_ncm.hdr) +
+		if (actlen < (int)(sizeof(sc->sc_ncm.hdr) +
 		    sizeof(sc->sc_ncm.dpt))) {
 			DPRINTFN(1, "frame too short\n");
 			goto tr_setup;
@@ -1305,7 +1307,7 @@
 			goto tr_stall;
 		}
 		temp =3D UGETW(sc->sc_ncm.hdr.wDptIndex);
-		if ((temp + sizeof(sc->sc_ncm.dpt)) > actlen) {
+		if ((int)(temp + sizeof(sc->sc_ncm.dpt)) > actlen) {
 			DPRINTFN(1, "invalid DPT index: 0x%04x\n", temp);
 			goto tr_stall;
 		}
@@ -1354,7 +1356,7 @@
 			temp =3D UGETW(sc->sc_ncm.dp[x].wFrameLength);
=20
 			if ((offset =3D=3D 0) ||
-			    (temp < sizeof(struct ether_header)) ||
+			    (temp < (int)sizeof(struct ether_header)) ||
 			    (temp > (MCLBYTES - ETHER_ALIGN))) {
 				DPRINTFN(1, "NULL frame detected at %d\n", x);
 				m =3D NULL;
@@ -1366,7 +1368,7 @@
 				m =3D NULL;
 				/* silently ignore this frame */
 				continue;
-			} else if (temp > (MHLEN - ETHER_ALIGN)) {
+			} else if (temp > (int)(MHLEN - ETHER_ALIGN)) {
 				m =3D m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
 			} else {
 				m =3D m_gethdr(M_DONTWAIT, MT_DATA);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_cue.c
--- a/head/sys/dev/usb/net/if_cue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_cue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_cue.c 227309 2011-11-07 15:43:=
11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_cue.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
 /*
  * CATC USB-EL1210A USB to ethernet driver. Used in the CATC Netmate
@@ -457,7 +457,7 @@
 	switch (USB_GET_STATE(xfer)) {
 	case USB_ST_TRANSFERRED:
=20
-		if (actlen <=3D (2 + sizeof(struct ether_header))) {
+		if (actlen <=3D (int)(2 + sizeof(struct ether_header))) {
 			ifp->if_ierrors++;
 			goto tr_setup;
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_ipheth.c
--- a/head/sys/dev/usb/net/if_ipheth.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_ipheth.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_ipheth.c 227309 2011-11-07 15:=
43:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_ipheth.c 233774 2012-04-02 10:=
50:42Z hselasky $");
=20
 #include <sys/stdint.h>
 #include <sys/stddef.h>
@@ -471,7 +471,7 @@
 			sc->sc_rx_buf[x] =3D NULL;
 			len =3D usbd_xfer_frame_len(xfer, x);
=20
-			if (len < (sizeof(struct ether_header) +
+			if (len < (int)(sizeof(struct ether_header) +
 			    IPHETH_RX_ADJ)) {
 				m_freem(m);
 				continue;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_kue.c
--- a/head/sys/dev/usb/net/if_kue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_kue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_kue.c 227461 2011-11-12 08:16:=
45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_kue.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
 /*
  * Kawasaki LSI KL5KUSB101B USB to ethernet adapter driver.
@@ -545,7 +545,7 @@
 	switch (USB_GET_STATE(xfer)) {
 	case USB_ST_TRANSFERRED:
=20
-		if (actlen <=3D (2 + sizeof(struct ether_header))) {
+		if (actlen <=3D (int)(2 + sizeof(struct ether_header))) {
 			ifp->if_ierrors++;
 			goto tr_setup;
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_rue.c
--- a/head/sys/dev/usb/net/if_rue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_rue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -57,7 +57,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_rue.c 227843 2011-11-22 21:28:=
20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_rue.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
 /*
  * RealTek RTL8150 USB to fast ethernet controller driver.
@@ -638,7 +638,7 @@
 	case USB_ST_TRANSFERRED:
=20
 		if (ifp && (ifp->if_drv_flags & IFF_DRV_RUNNING) &&
-		    actlen >=3D sizeof(pkt)) {
+		    actlen >=3D (int)sizeof(pkt)) {
=20
 			pc =3D usbd_xfer_get_frame(xfer, 0);
 			usbd_copy_out(pc, 0, &pkt, sizeof(pkt));
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_udav.c
--- a/head/sys/dev/usb/net/if_udav.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_udav.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 /*	$NetBSD: if_udav.c,v 1.2 2003/09/04 15:17:38 tsutsui Exp $	*/
 /*	$nabe: if_udav.c,v 1.3 2003/08/21 16:57:19 nabe Exp $	*/
-/*	$FreeBSD: head/sys/dev/usb/net/if_udav.c 227843 2011-11-22 21:28:20Z ma=
rius $	*/
+/*	$FreeBSD: head/sys/dev/usb/net/if_udav.c 233774 2012-04-02 10:50:42Z hs=
elasky $	*/
 /*-
  * Copyright (c) 2003
  *     Shingo WATANABE <nabe at nabechan.org>.  All rights reserved.
@@ -44,7 +44,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_udav.c 227843 2011-11-22 21:28=
:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_udav.c 233774 2012-04-02 10:50=
:42Z hselasky $");
=20
 #include <sys/stdint.h>
 #include <sys/stddef.h>
@@ -642,7 +642,7 @@
 	switch (USB_GET_STATE(xfer)) {
 	case USB_ST_TRANSFERRED:
=20
-		if (actlen < sizeof(stat) + ETHER_CRC_LEN) {
+		if (actlen < (int)(sizeof(stat) + ETHER_CRC_LEN)) {
 			ifp->if_ierrors++;
 			goto tr_setup;
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/if_usie.c
--- a/head/sys/dev/usb/net/if_usie.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/if_usie.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_usie.c 227309 2011-11-07 15:43=
:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/if_usie.c 233774 2012-04-02 10:50=
:42Z hselasky $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -918,7 +918,7 @@
 		if (m =3D=3D NULL)
 			break;
=20
-		if (m->m_pkthdr.len > (MCLBYTES - ETHER_HDR_LEN +
+		if (m->m_pkthdr.len > (int)(MCLBYTES - ETHER_HDR_LEN +
 		    ETHER_CRC_LEN - sizeof(sc->sc_txd))) {
 			DPRINTF("packet len is too big: %d\n",
 			    m->m_pkthdr.len);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/ruephy.c
--- a/head/sys/dev/usb/net/ruephy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/ruephy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/ruephy.c 227908 2011-11-23 20:27:=
26Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/ruephy.c 233774 2012-04-02 10:50:=
42Z hselasky $");
=20
 /*
  * driver for RealTek RTL8150 internal PHY
@@ -67,9 +67,9 @@
 static devclass_t ruephy_devclass;
=20
 static driver_t ruephy_driver =3D {
-	"ruephy",
-	ruephy_methods,
-	sizeof(struct mii_softc)
+	.name =3D "ruephy",
+	.methods =3D ruephy_methods,
+	.size =3D sizeof(struct mii_softc)
 };
=20
 DRIVER_MODULE(ruephy, miibus, ruephy_driver, ruephy_devclass, 0, 0);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/net/uhso.c
--- a/head/sys/dev/usb/net/uhso.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/net/uhso.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  *
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/uhso.c 227461 2011-11-12 08:16:45=
Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/uhso.c 233774 2012-04-02 10:50:42=
Z hselasky $");
=20
 #include <sys/param.h>
 #include <sys/types.h>
@@ -482,9 +482,9 @@
 };
=20
 static driver_t uhso_driver =3D {
-	"uhso",
-	uhso_methods,
-	sizeof(struct uhso_softc)
+	.name =3D "uhso",
+	.methods =3D uhso_methods,
+	.size =3D sizeof(struct uhso_softc)
 };
=20
 static devclass_t uhso_devclass;
@@ -1366,7 +1366,7 @@
 			UHSO_DPRINTF(0, "UCDC notification too short: %d\n", actlen);
 			goto tr_setup;
 		}
-		else if (actlen > sizeof(struct usb_cdc_notification)) {
+		else if (actlen > (int)sizeof(struct usb_cdc_notification)) {
 			UHSO_DPRINTF(0, "UCDC notification too large: %d\n", actlen);
 			actlen =3D sizeof(struct usb_cdc_notification);
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/ubsa.c
--- a/head/sys/dev/usb/serial/ubsa.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/ubsa.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ubsa.c 227309 2011-11-07 15:43=
:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ubsa.c 233774 2012-04-02 10:50=
:42Z hselasky $");
 /*-
  * Copyright (c) 2001 The NetBSD Foundation, Inc.
  * All rights reserved.
@@ -627,7 +627,7 @@
 	switch (USB_GET_STATE(xfer)) {
 	case USB_ST_TRANSFERRED:
=20
-		if (actlen >=3D sizeof(buf)) {
+		if (actlen >=3D (int)sizeof(buf)) {
 			pc =3D usbd_xfer_get_frame(xfer, 0);
 			usbd_copy_out(pc, 0, buf, sizeof(buf));
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/uchcom.c
--- a/head/sys/dev/usb/serial/uchcom.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/uchcom.c	Tue Apr 17 11:51:51 2012 +0300
@@ -63,7 +63,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/uchcom.c 227309 2011-11-07 15:=
43:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/uchcom.c 233774 2012-04-02 10:=
50:42Z hselasky $");
=20
 /*
  * Driver for WinChipHead CH341/340, the worst USB-serial chip in the
@@ -846,9 +846,9 @@
 };
=20
 static driver_t uchcom_driver =3D {
-	"ucom",
-	uchcom_methods,
-	sizeof(struct uchcom_softc)
+	.name =3D "ucom",
+	.methods =3D uchcom_methods,
+	.size =3D sizeof(struct uchcom_softc)
 };
=20
 static devclass_t uchcom_devclass;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/ucycom.c
--- a/head/sys/dev/usb/serial/ucycom.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/ucycom.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ucycom.c 230132 2012-01-15 13:=
23:18Z uqs $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ucycom.c 233774 2012-04-02 10:=
50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 2004 Dag-Erling Co=C3=AFdan Sm=C3=B8rgrav
@@ -519,7 +519,7 @@
 	struct usb_page_cache *pc;
 	uint8_t buf[2];
 	uint32_t offset;
-	uint32_t len;
+	int len;
 	int actlen;
=20
 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/ufoma.c
--- a/head/sys/dev/usb/serial/ufoma.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/ufoma.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 /*	$NetBSD: umodem.c,v 1.45 2002/09/23 05:51:23 simonb Exp $	*/
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ufoma.c 227461 2011-11-12 08:1=
6:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ufoma.c 233774 2012-04-02 10:5=
0:42Z hselasky $");
 #define UFOMA_HANDSFREE
 /*-
  * Copyright (c) 2005, Takanori Watanabe
@@ -684,7 +684,7 @@
 			DPRINTF("too short message\n");
 			goto tr_setup;
 		}
-		if (actlen > sizeof(pkt)) {
+		if (actlen > (int)sizeof(pkt)) {
 			DPRINTF("truncating message\n");
 			actlen =3D sizeof(pkt);
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/ulpt.c
--- a/head/sys/dev/usb/serial/ulpt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/ulpt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ulpt.c 227309 2011-11-07 15:43=
:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/ulpt.c 233774 2012-04-02 10:50=
:42Z hselasky $");
=20
 /*	$NetBSD: ulpt.c,v 1.60 2003/10/04 21:19:50 augustss Exp $	*/
=20
@@ -543,7 +543,7 @@
 	/* search through all the descriptors looking for bidir mode */
=20
 	id =3D usbd_get_interface_descriptor(uaa->iface);
-	alt_index =3D 0 - 1;
+	alt_index =3D 0xFF;
 	while (1) {
 		if (id =3D=3D NULL) {
 			break;
@@ -631,14 +631,14 @@
=20
 	error =3D usb_fifo_attach(uaa->device, sc, &sc->sc_mtx,
 	    &ulpt_fifo_methods, &sc->sc_fifo,
-	    unit, 0 - 1, uaa->info.bIfaceIndex,
+	    unit, -1, uaa->info.bIfaceIndex,
 	    UID_ROOT, GID_OPERATOR, 0644);
 	if (error) {
 		goto detach;
 	}
 	error =3D usb_fifo_attach(uaa->device, sc, &sc->sc_mtx,
 	    &unlpt_fifo_methods, &sc->sc_fifo_noreset,
-	    unit, 0 - 1, uaa->info.bIfaceIndex,
+	    unit, -1, uaa->info.bIfaceIndex,
 	    UID_ROOT, GID_OPERATOR, 0644);
 	if (error) {
 		goto detach;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/umodem.c
--- a/head/sys/dev/usb/serial/umodem.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/umodem.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 /*	$NetBSD: umodem.c,v 1.45 2002/09/23 05:51:23 simonb Exp $	*/
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/umodem.c 227461 2011-11-12 08:=
16:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/umodem.c 233774 2012-04-02 10:=
50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 2003, M. Warner Losh <imp at FreeBSD.org>.
@@ -317,7 +317,7 @@
=20
 		cud =3D usbd_find_descriptor(uaa->device, NULL,
 		    uaa->info.bIfaceIndex, UDESC_CS_INTERFACE,
-		    0 - 1, UDESCSUB_CDC_UNION, 0 - 1);
+		    0xFF, UDESCSUB_CDC_UNION, 0xFF);
=20
 		if ((cud =3D=3D NULL) || (cud->bLength < sizeof(*cud))) {
 			DPRINTF("Missing descriptor. "
@@ -702,7 +702,7 @@
 			    "%d bytes\n", actlen);
 			goto tr_setup;
 		}
-		if (actlen > sizeof(pkt)) {
+		if (actlen > (int)sizeof(pkt)) {
 			DPRINTF("truncating message\n");
 			actlen =3D sizeof(pkt);
 		}
@@ -842,7 +842,7 @@
 umodem_get_desc(struct usb_attach_arg *uaa, uint8_t type, uint8_t subtype)
 {
 	return (usbd_find_descriptor(uaa->device, NULL, uaa->info.bIfaceIndex,
-	    type, 0 - 1, subtype, 0 - 1));
+	    type, 0xFF, subtype, 0xFF));
 }
=20
 static usb_error_t
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/uplcom.c
--- a/head/sys/dev/usb/serial/uplcom.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/uplcom.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 /*	$NetBSD: uplcom.c,v 1.21 2001/11/13 06:24:56 lukem Exp $	*/
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/uplcom.c 227461 2011-11-12 08:=
16:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/uplcom.c 233774 2012-04-02 10:=
50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 2001-2003, 2005 Shunsuke Akiyama <akiyama at jp.FreeBSD.org>.
@@ -606,7 +606,7 @@
 	    &req, NULL, 0, 1000);
 }
=20
-static const int32_t uplcom_rates[] =3D {
+static const uint32_t uplcom_rates[] =3D {
 	75, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, 14400,
 	19200, 28800, 38400, 57600, 115200,
 	/*
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/usb_serial.c
--- a/head/sys/dev/usb/serial/usb_serial.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/usb_serial.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/serial/usb_serial.c 230209 2012-01-16=
 10:42:43Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/serial/usb_serial.c 233774 2012-04-02=
 10:50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 1998, 2000 The NetBSD Foundation, Inc.
@@ -236,14 +236,14 @@
  */
 int
 ucom_attach(struct ucom_super_softc *ssc, struct ucom_softc *sc,
-    uint32_t subunits, void *parent,
+    int subunits, void *parent,
     const struct ucom_callback *callback, struct mtx *mtx)
 {
-	uint32_t subunit;
+	int subunit;
 	int error =3D 0;
=20
 	if ((sc =3D=3D NULL) ||
-	    (subunits =3D=3D 0) ||
+	    (subunits <=3D 0) ||
 	    (callback =3D=3D NULL)) {
 		return (EINVAL);
 	}
@@ -293,7 +293,7 @@
 void
 ucom_detach(struct ucom_super_softc *ssc, struct ucom_softc *sc)
 {
-	uint32_t subunit;
+	int subunit;
=20
 	if (ssc->sc_subunits =3D=3D 0)
 		return;		/* not initialized */
@@ -1082,11 +1082,6 @@
 	DPRINTF("sc =3D %p\n", sc);
=20
 	/* Check requested parameters. */
-	if (t->c_ospeed < 0) {
-		DPRINTF("negative ospeed\n");
-		error =3D EINVAL;
-		goto done;
-	}
 	if (t->c_ispeed && (t->c_ispeed !=3D t->c_ospeed)) {
 		DPRINTF("mismatch ispeed and ospeed\n");
 		error =3D EINVAL;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/serial/usb_serial.h
--- a/head/sys/dev/usb/serial/usb_serial.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/serial/usb_serial.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*	$NetBSD: ucomvar.h,v 1.9 2001/01/23 21:56:17 augustss Exp $	*/
-/*	$FreeBSD: head/sys/dev/usb/serial/usb_serial.h 230209 2012-01-16 10:42:=
43Z hselasky $	*/
+/*	$FreeBSD: head/sys/dev/usb/serial/usb_serial.h 233774 2012-04-02 10:50:=
42Z hselasky $	*/
=20
 /*-
  * Copyright (c) 2001-2002, Shunsuke Akiyama <akiyama at jp.FreeBSD.org>.
@@ -166,7 +166,7 @@
 	struct tty *sc_tty;
 	struct mtx *sc_mtx;
 	void   *sc_parent;
-	uint32_t sc_subunit;
+	int sc_subunit;
 	uint16_t sc_portno;
 	uint16_t sc_flag;
 #define	UCOM_FLAG_RTS_IFLOW	0x01	/* use RTS input flow control */
@@ -194,7 +194,7 @@
     usbd_do_request_proc(udev,&(com)->sc_super->sc_tq,req,ptr,flags,NULL,t=
imo)
=20
 int	ucom_attach(struct ucom_super_softc *,
-	    struct ucom_softc *, uint32_t, void *,
+	    struct ucom_softc *, int, void *,
 	    const struct ucom_callback *callback, struct mtx *);
 void	ucom_detach(struct ucom_super_softc *, struct ucom_softc *);
 void	ucom_set_pnpinfo_usb(struct ucom_super_softc *, device_t);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/storage/umass.c
--- a/head/sys/dev/usb/storage/umass.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/storage/umass.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/storage/umass.c 232361 2012-03-01 20:=
25:17Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/storage/umass.c 233774 2012-04-02 10:=
50:42Z hselasky $");
=20
 /*-
  * Copyright (c) 1999 MAEKAWA Masahide <bishop at rr.iij4u.or.jp>,
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	$FreeBSD: head/sys/dev/usb/storage/umass.c 232361 2012-03-01 20:25:17Z =
hselasky $
+ *	$FreeBSD: head/sys/dev/usb/storage/umass.c 233774 2012-04-02 10:50:42Z =
hselasky $
  *	$NetBSD: umass.c,v 1.28 2000/04/02 23:46:53 augustss Exp $
  */
=20
@@ -1452,7 +1452,7 @@
=20
 		/* Zero missing parts of the CSW: */
=20
-		if (actlen < sizeof(sc->csw))
+		if (actlen < (int)sizeof(sc->csw))
 			memset(&sc->csw, 0, sizeof(sc->csw));
=20
 		pc =3D usbd_xfer_get_frame(xfer, 0);
@@ -1961,7 +1961,7 @@
 	switch (USB_GET_STATE(xfer)) {
 	case USB_ST_TRANSFERRED:
=20
-		if (actlen < sizeof(sc->sbl)) {
+		if (actlen < (int)sizeof(sc->sbl)) {
 			goto tr_setup;
 		}
 		pc =3D usbd_xfer_get_frame(xfer, 0);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/storage/urio.c
--- a/head/sys/dev/usb/storage/urio.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/storage/urio.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/storage/urio.c 227461 2011-11-12 08:1=
6:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/storage/urio.c 233774 2012-04-02 10:5=
0:42Z hselasky $");
=20
=20
 /*
@@ -246,7 +246,7 @@
=20
 	error =3D usb_fifo_attach(uaa->device, sc, &sc->sc_mtx,
 	    &urio_fifo_methods, &sc->sc_fifo,
-	    device_get_unit(dev), 0 - 1, uaa->info.bIfaceIndex,
+	    device_get_unit(dev), -1, uaa->info.bIfaceIndex,
 	    UID_ROOT, GID_OPERATOR, 0644);
 	if (error) {
 		goto detach;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/storage/ustorage_fs.c
--- a/head/sys/dev/usb/storage/ustorage_fs.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/storage/ustorage_fs.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/storage/ustorage_fs.c 227462 2011-11-12 08:1=
9:36Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/storage/ustorage_fs.c 233774 2012-04-02 10:5=
0:42Z hselasky $ */
 /*-
  * Copyright (C) 2003-2005 Alan Stern
  * Copyright (C) 2008 Hans Petter Selasky
@@ -967,7 +967,7 @@
 	}
 	/* XXX TODO: verify that data is readable */
 done:
-	return (ustorage_fs_min_len(sc, 0, 0 - 1));
+	return (ustorage_fs_min_len(sc, 0, -1U));
 }
=20
 /*------------------------------------------------------------------------*
@@ -989,7 +989,7 @@
 		memset(buf, 0, 36);
 		buf[0] =3D 0x7f;
 		/* Unsupported, no device - type */
-		return (ustorage_fs_min_len(sc, 36, 0 - 1));
+		return (ustorage_fs_min_len(sc, 36, -1U));
 	}
 	memset(buf, 0, 8);
 	/* Non - removable, direct - access device */
@@ -1008,7 +1008,7 @@
 #if (USTORAGE_QDATA_MAX < 36)
 #error "(USTORAGE_QDATA_MAX < 36)"
 #endif
-	return (ustorage_fs_min_len(sc, 36, 0 - 1));
+	return (ustorage_fs_min_len(sc, 36, -1U));
 }
=20
 /*------------------------------------------------------------------------*
@@ -1077,7 +1077,7 @@
 #if (USTORAGE_QDATA_MAX < 18)
 #error "(USTORAGE_QDATA_MAX < 18)"
 #endif
-	return (ustorage_fs_min_len(sc, 18, 0 - 1));
+	return (ustorage_fs_min_len(sc, 18, -1U));
 }
=20
 /*------------------------------------------------------------------------*
@@ -1108,7 +1108,7 @@
 #if (USTORAGE_QDATA_MAX < 8)
 #error "(USTORAGE_QDATA_MAX < 8)"
 #endif
-	return (ustorage_fs_min_len(sc, 8, 0 - 1));
+	return (ustorage_fs_min_len(sc, 8, -1U));
 }
=20
 /*------------------------------------------------------------------------*
@@ -1215,7 +1215,7 @@
 #if (USTORAGE_QDATA_MAX < 24)
 #error "(USTORAGE_QDATA_MAX < 24)"
 #endif
-	return (ustorage_fs_min_len(sc, len, 0 - 1));
+	return (ustorage_fs_min_len(sc, len, -1U));
 }
=20
 /*------------------------------------------------------------------------*
@@ -1305,7 +1305,7 @@
 #if (USTORAGE_QDATA_MAX < 12)
 #error "(USTORAGE_QDATA_MAX < 12)"
 #endif
-	return (ustorage_fs_min_len(sc, 12, 0 - 1));
+	return (ustorage_fs_min_len(sc, 12, -1U));
 }
=20
 /*------------------------------------------------------------------------*
@@ -1618,7 +1618,7 @@
 	switch (sc->sc_cmd_data[0]) {
 	case SC_INQUIRY:
 		sc->sc_transfer.cmd_dir =3D DIR_WRITE;
-		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], 0 - 1);
+		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], -1U);
 		if (error) {
 			break;
 		}
@@ -1633,7 +1633,7 @@
=20
 	case SC_MODE_SELECT_6:
 		sc->sc_transfer.cmd_dir =3D DIR_READ;
-		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], 0 - 1);
+		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], -1U);
 		if (error) {
 			break;
 		}
@@ -1649,7 +1649,7 @@
 	case SC_MODE_SELECT_10:
 		sc->sc_transfer.cmd_dir =3D DIR_READ;
 		error =3D ustorage_fs_min_len(sc,
-		    get_be16(&sc->sc_cmd_data[7]), 0 - 1);
+		    get_be16(&sc->sc_cmd_data[7]), -1U);
 		if (error) {
 			break;
 		}
@@ -1664,7 +1664,7 @@
=20
 	case SC_MODE_SENSE_6:
 		sc->sc_transfer.cmd_dir =3D DIR_WRITE;
-		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], 0 - 1);
+		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], -1U);
 		if (error) {
 			break;
 		}
@@ -1680,7 +1680,7 @@
 	case SC_MODE_SENSE_10:
 		sc->sc_transfer.cmd_dir =3D DIR_WRITE;
 		error =3D ustorage_fs_min_len(sc,
-		    get_be16(&sc->sc_cmd_data[7]), 0 - 1);
+		    get_be16(&sc->sc_cmd_data[7]), -1U);
 		if (error) {
 			break;
 		}
@@ -1694,7 +1694,7 @@
 		break;
=20
 	case SC_PREVENT_ALLOW_MEDIUM_REMOVAL:
-		error =3D ustorage_fs_min_len(sc, 0, 0 - 1);
+		error =3D ustorage_fs_min_len(sc, 0, -1U);
 		if (error) {
 			break;
 		}
@@ -1776,7 +1776,7 @@
 	case SC_READ_FORMAT_CAPACITIES:
 		sc->sc_transfer.cmd_dir =3D DIR_WRITE;
 		error =3D ustorage_fs_min_len(sc,
-		    get_be16(&sc->sc_cmd_data[7]), 0 - 1);
+		    get_be16(&sc->sc_cmd_data[7]), -1U);
 		if (error) {
 			break;
 		}
@@ -1791,7 +1791,7 @@
=20
 	case SC_REQUEST_SENSE:
 		sc->sc_transfer.cmd_dir =3D DIR_WRITE;
-		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], 0 - 1);
+		error =3D ustorage_fs_min_len(sc, sc->sc_cmd_data[4], -1U);
 		if (error) {
 			break;
 		}
@@ -1805,7 +1805,7 @@
 		break;
=20
 	case SC_START_STOP_UNIT:
-		error =3D ustorage_fs_min_len(sc, 0, 0 - 1);
+		error =3D ustorage_fs_min_len(sc, 0, -1U);
 		if (error) {
 			break;
 		}
@@ -1819,7 +1819,7 @@
 		break;
=20
 	case SC_SYNCHRONIZE_CACHE:
-		error =3D ustorage_fs_min_len(sc, 0, 0 - 1);
+		error =3D ustorage_fs_min_len(sc, 0, -1U);
 		if (error) {
 			break;
 		}
@@ -1833,7 +1833,7 @@
 		break;
=20
 	case SC_TEST_UNIT_READY:
-		error =3D ustorage_fs_min_len(sc, 0, 0 - 1);
+		error =3D ustorage_fs_min_len(sc, 0, -1U);
 		if (error) {
 			break;
 		}
@@ -1846,7 +1846,7 @@
 		 * We support a minimal version: BytChk must be 0.
 		 */
 	case SC_VERIFY:
-		error =3D ustorage_fs_min_len(sc, 0, 0 - 1);
+		error =3D ustorage_fs_min_len(sc, 0, -1U);
 		if (error) {
 			break;
 		}
@@ -1928,7 +1928,7 @@
 		/* Fallthrough */
=20
 	default:
-		error =3D ustorage_fs_min_len(sc, 0, 0 - 1);
+		error =3D ustorage_fs_min_len(sc, 0, -1U);
 		if (error) {
 			break;
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/template/usb_template=
.c
--- a/head/sys/dev/usb/template/usb_template.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/dev/usb/template/usb_template.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/template/usb_template.c 228304 2011-12-06 08=
:08:52Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/template/usb_template.c 233774 2012-04-02 10=
:50:42Z hselasky $ */
 /*-
  * Copyright (c) 2007 Hans Petter Selasky. All rights reserved.
  *
@@ -374,7 +374,7 @@
=20
 	/* Reset some counters */
=20
-	temp->bInterfaceNumber =3D 0 - 1;
+	temp->bInterfaceNumber =3D 0xFF;
 	temp->bAlternateSetting =3D 0;
=20
 	/* Scan all the USB interfaces */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb.h
--- a/head/sys/dev/usb/usb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb.h 230032 2012-01-12 21:21:20Z hselasky $=
 */
+/* $FreeBSD: head/sys/dev/usb/usb.h 233771 2012-04-02 07:51:30Z hselasky $=
 */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
@@ -225,7 +225,8 @@
 #define	UR_RESET_TT		0x09
 #define	UR_GET_TT_STATE		0x0a
 #define	UR_STOP_TT		0x0b
-#define	UR_SET_HUB_DEPTH	0x0c
+#define	UR_SET_AND_TEST		0x0c	/* USB 2.0 only */
+#define	UR_SET_HUB_DEPTH	0x0c	/* USB 3.0 only */
 #define	USB_SS_HUB_DEPTH_MAX	5
 #define	UR_GET_PORT_ERR_COUNT	0x0d
=20
@@ -248,6 +249,7 @@
 #define	UHF_PORT_LINK_STATE	5
 #define	UHF_PORT_POWER		8
 #define	UHF_PORT_LOW_SPEED	9
+#define	UHF_PORT_L1		10
 #define	UHF_C_PORT_CONNECTION	16
 #define	UHF_C_PORT_ENABLE	17
 #define	UHF_C_PORT_SUSPEND	18
@@ -255,6 +257,7 @@
 #define	UHF_C_PORT_RESET	20
 #define	UHF_PORT_TEST		21
 #define	UHF_PORT_INDICATOR	22
+#define	UHF_C_PORT_L1		23
=20
 /* SuperSpeed HUB specific features */
 #define	UHF_PORT_U1_TIMEOUT	23
@@ -324,7 +327,12 @@
 	uByte	bDescriptorType;
 	uByte	bDevCapabilityType;
 	uDWord	bmAttributes;
-#define	USB_V2EXT_LPM 0x02
+#define	USB_V2EXT_LPM (1U << 1)
+#define	USB_V2EXT_BESL_SUPPORTED (1U << 2)
+#define	USB_V2EXT_BESL_BASELINE_VALID (1U << 3)
+#define	USB_V2EXT_BESL_DEEP_VALID (1U << 4)
+#define	USB_V2EXT_BESL_BASELINE_GET(x) (((x) >> 8) & 0xF)
+#define	USB_V2EXT_BESL_DEEP_GET(x) (((x) >> 12) & 0xF)
 } __packed;
 typedef struct usb_devcap_usb2ext_descriptor usb_devcap_usb2ext_descriptor=
_t;
=20
@@ -671,6 +679,7 @@
 #define	UPS_SUSPEND			0x0004
 #define	UPS_OVERCURRENT_INDICATOR	0x0008
 #define	UPS_RESET			0x0010
+#define	UPS_PORT_L1			0x0020	/* USB 2.0 only */
 /* The link-state bits are valid for Super-Speed USB HUBs */
 #define	UPS_PORT_LINK_STATE_GET(x)	(((x) >> 5) & 0xF)
 #define	UPS_PORT_LINK_STATE_SET(x)	(((x) & 0xF) << 5)
@@ -701,7 +710,8 @@
 #define	UPS_C_SUSPEND			0x0004
 #define	UPS_C_OVERCURRENT_INDICATOR	0x0008
 #define	UPS_C_PORT_RESET		0x0010
-#define	UPS_C_BH_PORT_RESET		0x0020
+#define	UPS_C_PORT_L1			0x0020	/* USB 2.0 only */
+#define	UPS_C_BH_PORT_RESET		0x0020	/* USB 3.0 only */
 #define	UPS_C_PORT_LINK_STATE		0x0040
 #define	UPS_C_PORT_CONFIG_ERROR		0x0080
 } __packed;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_busdma.c
--- a/head/sys/dev/usb/usb_busdma.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_busdma.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_busdma.c 227461 2011-11-12 08:16:45Z hse=
lasky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_busdma.c 233774 2012-04-02 10:50:42Z hse=
lasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  *
@@ -108,7 +108,7 @@
 			res->length =3D USB_PAGE_SIZE - offset;
 			res->physaddr =3D page->physaddr + offset;
 		} else {
-			res->length =3D 0 - 1;
+			res->length =3D (usb_size_t)-1;
 			res->physaddr =3D page->physaddr + offset;
 		}
 		if (!pc->buffer) {
@@ -123,7 +123,7 @@
 	/* Case 2 - Plain PIO */
=20
 	res->buffer =3D USB_ADD_BYTES(pc->buffer, offset);
-	res->length =3D 0 - 1;
+	res->length =3D (usb_size_t)-1;
 #if USB_HAVE_BUSDMA
 	res->physaddr =3D 0;
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_compat_linux.c
--- a/head/sys/dev/usb/usb_compat_linux.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_compat_linux.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_compat_linux.c 227461 2011-11-12 08:16:4=
5Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_compat_linux.c 233774 2012-04-02 10:50:4=
2Z hselasky $ */
 /*-
  * Copyright (c) 2007 Luigi Rizzo - Universita` di Pisa. All rights reserv=
ed.
  * Copyright (c) 2007 Hans Petter Selasky. All rights reserved.
@@ -880,7 +880,7 @@
 	 */
 	for (pass =3D 0; pass < 2; pass++) {
=20
-		iface_no_curr =3D 0 - 1;
+		iface_no_curr =3D 0xFFFF;
 		niface_total =3D 0;
 		iface_index =3D 0;
 		nedesc =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_dev.c
--- a/head/sys/dev/usb/usb_dev.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_dev.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_dev.c 231378 2012-02-10 12:35:57Z ed $ */
+/* $FreeBSD: head/sys/dev/usb/usb_dev.c 233774 2012-04-02 10:50:42Z hselas=
ky $ */
 /*-
  * Copyright (c) 2006-2008 Hans Petter Selasky. All rights reserved.
  *
@@ -1653,7 +1653,7 @@
 int
 usb_fifo_attach(struct usb_device *udev, void *priv_sc,
     struct mtx *priv_mtx, struct usb_fifo_methods *pm,
-    struct usb_fifo_sc *f_sc, uint16_t unit, uint16_t subunit,
+    struct usb_fifo_sc *f_sc, uint16_t unit, int16_t subunit,
     uint8_t iface_index, uid_t uid, gid_t gid, int mode)
 {
 	struct usb_fifo *f_tx;
@@ -1730,7 +1730,7 @@
 		if (pm->basename[n] =3D=3D NULL) {
 			continue;
 		}
-		if (subunit =3D=3D 0xFFFF) {
+		if (subunit < 0) {
 			if (snprintf(devname, sizeof(devname),
 			    "%s%u%s", pm->basename[n],
 			    unit, pm->postfix[n] ?
@@ -1739,7 +1739,7 @@
 			}
 		} else {
 			if (snprintf(devname, sizeof(devname),
-			    "%s%u.%u%s", pm->basename[n],
+			    "%s%u.%d%s", pm->basename[n],
 			    unit, subunit, pm->postfix[n] ?
 			    pm->postfix[n] : "")) {
 				/* ignore */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_device.c
--- a/head/sys/dev/usb/usb_device.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_device.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_device.c 226903 2011-10-29 12:32:13Z hse=
lasky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_device.c 233774 2012-04-02 10:50:42Z hse=
lasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  *
@@ -1496,7 +1496,6 @@
 	struct usb_device *adev;
 	struct usb_device *hub;
 	uint8_t *scratch_ptr;
-	size_t scratch_size;
 	usb_error_t err;
 	uint8_t device_index;
 	uint8_t config_index;
@@ -1721,7 +1720,6 @@
 	 * simply disable all USB strings.
 	 */
 	scratch_ptr =3D udev->bus->scratch[0].data;
-	scratch_size =3D sizeof(udev->bus->scratch[0].data);
=20
 	if (udev->ddesc.iManufacturer ||
 	    udev->ddesc.iProduct ||
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_handle_request.c
--- a/head/sys/dev/usb/usb_handle_request.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_handle_request.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/usb/usb_handle_request.c 233774 2012-04-02 10:50=
:42Z hselasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  *
@@ -466,7 +466,6 @@
 	uint16_t rem;			/* data remainder */
 	uint16_t max_len;		/* max fragment length */
 	uint16_t wValue;
-	uint16_t wIndex;
 	uint8_t state;
 	uint8_t is_complete =3D 1;
 	usb_error_t err;
@@ -532,11 +531,10 @@
 	/* get some request fields decoded */
=20
 	wValue =3D UGETW(req.wValue);
-	wIndex =3D UGETW(req.wIndex);
=20
 	DPRINTF("req 0x%02x 0x%02x 0x%04x 0x%04x "
 	    "off=3D0x%x rem=3D0x%x, state=3D%d\n", req.bmRequestType,
-	    req.bRequest, wValue, wIndex, off, rem, state);
+	    req.bRequest, wValue, UGETW(req.wIndex), off, rem, state);
=20
 	/* demultiplex the control request */
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_hid.c
--- a/head/sys/dev/usb/usb_hid.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_hid.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
=20
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/usb_hid.c 223755 2011-07-04 07:37:28Z=
 hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/usb_hid.c 233774 2012-04-02 10:50:42Z=
 hselasky $");
 /*-
  * Copyright (c) 1998 The NetBSD Foundation, Inc.
  * All rights reserved.
@@ -612,7 +612,7 @@
  *	hid_locate
  *------------------------------------------------------------------------=
*/
 int
-hid_locate(const void *desc, usb_size_t size, uint32_t u, enum hid_kind k,
+hid_locate(const void *desc, usb_size_t size, int32_t u, enum hid_kind k,
     uint8_t index, struct hid_location *loc, uint32_t *flags, uint8_t *id)
 {
 	struct hid_data *d;
@@ -742,7 +742,7 @@
  *	hid_is_collection
  *------------------------------------------------------------------------=
*/
 int
-hid_is_collection(const void *desc, usb_size_t size, uint32_t usage)
+hid_is_collection(const void *desc, usb_size_t size, int32_t usage)
 {
 	struct hid_data *hd;
 	struct hid_item hi;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_hub.c
--- a/head/sys/dev/usb/usb_hub.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_hub.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_hub.c 230091 2012-01-13 22:26:13Z hselas=
ky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_hub.c 233774 2012-04-02 10:50:42Z hselas=
ky $ */
 /*-
  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
@@ -1431,7 +1431,7 @@
 usb_intr_find_best_slot(usb_size_t *ptr, uint8_t start,
     uint8_t end, uint8_t mask)
 {
-	usb_size_t min =3D 0 - 1;
+	usb_size_t min =3D (usb_size_t)-1;
 	usb_size_t sum;
 	uint8_t x;
 	uint8_t y;
@@ -2149,7 +2149,7 @@
=20
 	/* reset counters */
=20
-	mintime =3D 0 - 1;
+	mintime =3D (usb_ticks_t)-1;
 	type_refs[0] =3D 0;
 	type_refs[1] =3D 0;
 	type_refs[2] =3D 0;
@@ -2186,7 +2186,7 @@
 		}
 	}
=20
-	if (mintime >=3D (1 * hz)) {
+	if (mintime >=3D (usb_ticks_t)(1 * hz)) {
 		/* recompute power masks */
 		DPRINTF("Recomputing power masks\n");
 		bus->hw_power_state =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_msctest.c
--- a/head/sys/dev/usb/usb_msctest.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_msctest.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_msctest.c 228232 2011-12-03 14:54:44Z hs=
elasky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_msctest.c 233774 2012-04-02 10:50:42Z hs=
elasky $ */
 /*-
  * Copyright (c) 2008,2011 Hans Petter Selasky. All rights reserved.
  *
@@ -418,7 +418,8 @@
 bbb_status_callback(struct usb_xfer *xfer, usb_error_t error)
 {
 	struct bbb_transfer *sc =3D usbd_xfer_softc(xfer);
-	int actlen, sumlen;
+	int actlen;
+	int sumlen;
=20
 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
=20
@@ -427,7 +428,7 @@
=20
 		/* very simple status check */
=20
-		if (actlen < sizeof(sc->csw)) {
+		if (actlen < (int)sizeof(sc->csw)) {
 			bbb_done(sc, USB_ERR_SHORT_XFER);
 		} else if (sc->csw.bCSWStatus =3D=3D CSWSTATUS_GOOD) {
 			bbb_done(sc, 0);	/* success */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_request.c
--- a/head/sys/dev/usb/usb_request.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_request.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_request.c 230091 2012-01-13 22:26:13Z hs=
elasky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_request.c 233774 2012-04-02 10:50:42Z hs=
elasky $ */
 /*-
  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
@@ -1312,7 +1312,7 @@
 		goto done;
 	}
 	/* Extra sanity checking */
-	if (UGETW(d->wTotalLength) < sizeof(*d)) {
+	if (UGETW(d->wTotalLength) < (uint16_t)sizeof(*d)) {
 		err =3D USB_ERR_INVAL;
 	}
 done:
@@ -2226,3 +2226,57 @@
 	USETW(req.wLength, 0);
 	return (usbd_do_request(udev, mtx, &req, 0));
 }
+
+/*------------------------------------------------------------------------*
+ *		usbd_req_set_lpm_info
+ *
+ * USB 2.0 specific request for Link Power Management.
+ *
+ * Returns:
+ * 0:				Success
+ * USB_ERR_PENDING_REQUESTS:	NYET
+ * USB_ERR_TIMEOUT:		TIMEOUT
+ * USB_ERR_STALL:		STALL
+ * Else:			Failure
+ *------------------------------------------------------------------------=
*/
+usb_error_t
+usbd_req_set_lpm_info(struct usb_device *udev, struct mtx *mtx,
+    uint8_t port, uint8_t besl, uint8_t addr, uint8_t rwe)
+{
+	struct usb_device_request req;
+	usb_error_t err;
+	uint8_t buf[1];
+
+	req.bmRequestType =3D UT_WRITE_CLASS_OTHER;
+	req.bRequest =3D UR_SET_AND_TEST;
+	USETW(req.wValue, UHF_PORT_L1);
+	req.wIndex[0] =3D (port & 0xF) | ((besl & 0xF) << 4);
+	req.wIndex[1] =3D (addr & 0x7F) | (rwe ? 0x80 : 0x00);
+	USETW(req.wLength, sizeof(buf));
+
+	/* set default value in case of short transfer */
+	buf[0] =3D 0x00;
+
+	err =3D usbd_do_request(udev, mtx, &req, buf);
+	if (err)
+		return (err);
+
+	switch (buf[0]) {
+	case 0x00:	/* SUCCESS */
+		break;
+	case 0x10:	/* NYET */
+		err =3D USB_ERR_PENDING_REQUESTS;
+		break;
+	case 0x11:	/* TIMEOUT */
+		err =3D USB_ERR_TIMEOUT;
+		break;
+	case 0x30:	/* STALL */
+		err =3D USB_ERR_STALLED;
+		break;
+	default:	/* reserved */
+		err =3D USB_ERR_IOERROR;
+		break;
+	}
+	return (err);
+}
+
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_request.h
--- a/head/sys/dev/usb/usb_request.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_request.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_request.h 230032 2012-01-12 21:21:20Z hs=
elasky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_request.h 233771 2012-04-02 07:51:30Z hs=
elasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  *
@@ -91,5 +91,7 @@
 		    uint8_t port, uint8_t addr, uint8_t type, uint8_t endpoint);
 usb_error_t usbd_req_set_port_link_state(struct usb_device *udev,
 		    struct mtx *mtx, uint8_t port, uint8_t link_state);
+usb_error_t usbd_req_set_lpm_info(struct usb_device *udev, struct mtx *mtx,
+		    uint8_t port, uint8_t besl, uint8_t addr, uint8_t rwe);
=20
 #endif					/* _USB_REQUEST_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usb_transfer.c
--- a/head/sys/dev/usb/usb_transfer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usb_transfer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_transfer.c 230643 2012-01-28 14:00:21Z a=
ttilio $ */
+/* $FreeBSD: head/sys/dev/usb/usb_transfer.c 233774 2012-04-02 10:50:42Z h=
selasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  *
@@ -2700,7 +2700,8 @@
 				(bus->methods->start_dma_delay) (xfer);
 			} else {
 				usbd_transfer_timeout_ms(xfer,
-				    (void *)&usb_dma_delay_done_cb, temp);
+				    (void (*)(void *))&usb_dma_delay_done_cb,
+				    temp);
 			}
 			USB_BUS_UNLOCK(bus);
 			return (1);	/* wait for new callback */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usbdi.h
--- a/head/sys/dev/usb/usbdi.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usbdi.h	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/usb/usbdi.h 225469 2011-09-10 15:55:36Z hselasky=
 $
+ * $FreeBSD: head/sys/dev/usb/usbdi.h 233774 2012-04-02 10:50:42Z hselasky=
 $
  */
 #ifndef _USB_USBDI_H_
 #define _USB_USBDI_H_
@@ -567,7 +567,7 @@
=20
 int	usb_fifo_attach(struct usb_device *udev, void *priv_sc,
 	    struct mtx *priv_mtx, struct usb_fifo_methods *pm,
-	    struct usb_fifo_sc *f_sc, uint16_t unit, uint16_t subunit,
+	    struct usb_fifo_sc *f_sc, uint16_t unit, int16_t subunit,
 	    uint8_t iface_index, uid_t uid, gid_t gid, int mode);
 void	usb_fifo_detach(struct usb_fifo_sc *f_sc);
 int	usb_fifo_alloc_buffer(struct usb_fifo *f, uint32_t bufsize,
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/usbhid.h
--- a/head/sys/dev/usb/usbhid.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/usbhid.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usbhid.h 223755 2011-07-04 07:37:28Z hselask=
y $ */
+/* $FreeBSD: head/sys/dev/usb/usbhid.h 233774 2012-04-02 10:50:42Z hselask=
y $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
@@ -226,7 +226,7 @@
 int	hid_get_item(struct hid_data *s, struct hid_item *h);
 int	hid_report_size(const void *buf, usb_size_t len, enum hid_kind k,
 	    uint8_t *id);
-int	hid_locate(const void *desc, usb_size_t size, uint32_t usage,
+int	hid_locate(const void *desc, usb_size_t size, int32_t usage,
 	    enum hid_kind kind, uint8_t index, struct hid_location *loc,
 	    uint32_t *flags, uint8_t *id);
 int32_t hid_get_data(const uint8_t *buf, usb_size_t len,
@@ -235,7 +235,7 @@
 	    struct hid_location *loc);
 void hid_put_data_unsigned(uint8_t *buf, usb_size_t len,
 	    struct hid_location *loc, unsigned int value);
-int	hid_is_collection(const void *desc, usb_size_t size, uint32_t usage);
+int	hid_is_collection(const void *desc, usb_size_t size, int32_t usage);
 struct usb_hid_descriptor *hid_get_descriptor_from_usb(
 	    struct usb_config_descriptor *cd,
 	    struct usb_interface_descriptor *id);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/wlan/if_rum.c
--- a/head/sys/dev/usb/wlan/if_rum.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/wlan/if_rum.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/*	$FreeBSD: head/sys/dev/usb/wlan/if_rum.c 228621 2011-12-17 10:23:17Z bs=
chmidt $	*/
+/*	$FreeBSD: head/sys/dev/usb/wlan/if_rum.c 233774 2012-04-02 10:50:42Z hs=
elasky $	*/
=20
 /*-
  * Copyright (c) 2005-2007 Damien Bergamini <damien.bergamini at free.fr>
@@ -19,7 +19,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_rum.c 228621 2011-12-17 10:23=
:17Z bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_rum.c 233774 2012-04-02 10:50=
:42Z hselasky $");
=20
 /*-
  * Ralink Technology RT2501USB/RT2601USB chipset driver
@@ -85,6 +85,8 @@
     "Debug level");
 #endif
=20
+#define N(a)	((int)(sizeof (a) / sizeof ((a)[0])))
+
 static const STRUCT_USB_HOST_ID rum_devs[] =3D {
 #define	RUM_DEV(v,p)  { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
     RUM_DEV(ABOCOM, HWU54DM),
@@ -789,7 +791,7 @@
 			STAILQ_REMOVE_HEAD(&sc->tx_q, next);
 			m =3D data->m;
=20
-			if (m->m_pkthdr.len > (MCLBYTES + RT2573_TX_DESC_SIZE)) {
+			if (m->m_pkthdr.len > (int)(MCLBYTES + RT2573_TX_DESC_SIZE)) {
 				DPRINTFN(0, "data overflow, %u bytes\n",
 				    m->m_pkthdr.len);
 				m->m_pkthdr.len =3D (MCLBYTES + RT2573_TX_DESC_SIZE);
@@ -875,7 +877,7 @@
=20
 		DPRINTFN(15, "rx done, actlen=3D%d\n", len);
=20
-		if (len < RT2573_RX_DESC_SIZE + IEEE80211_MIN_LEN) {
+		if (len < (int)(RT2573_RX_DESC_SIZE + IEEE80211_MIN_LEN)) {
 			DPRINTF("%s: xfer too short %d\n",
 			    device_get_nameunit(sc->sc_dev), len);
 			ifp->if_ierrors++;
@@ -1407,7 +1409,7 @@
 {
 	struct usb_device_request req;
 	usb_error_t error;
-	int offset;
+	size_t offset;
=20
 	req.bmRequestType =3D UT_WRITE_VENDOR_DEVICE;
 	req.bRequest =3D RT2573_WRITE_MULTI_MAC;
@@ -1934,7 +1936,6 @@
 static int
 rum_bbp_init(struct rum_softc *sc)
 {
-#define N(a)	(sizeof (a) / sizeof ((a)[0]))
 	int i, ntries;
=20
 	/* wait for BBP to be ready */
@@ -1962,13 +1963,11 @@
 	}
=20
 	return 0;
-#undef N
 }
=20
 static void
 rum_init_locked(struct rum_softc *sc)
 {
-#define N(a)	(sizeof (a) / sizeof ((a)[0]))
 	struct ifnet *ifp =3D sc->sc_ifp;
 	struct ieee80211com *ic =3D ifp->if_l2com;
 	uint32_t tmp;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/wlan/if_run.c
--- a/head/sys/dev/usb/wlan/if_run.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/wlan/if_run.c	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_run.c 230333 2012-01-19 18:03=
:52Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_run.c 233774 2012-04-02 10:50=
:42Z hselasky $");
=20
 /*-
  * Ralink Technology RT2700U/RT2800U/RT3000U chipset driver.
@@ -74,7 +74,7 @@
 #include <dev/usb/wlan/if_runreg.h>
 #include <dev/usb/wlan/if_runvar.h>
=20
-#define nitems(_a)      (sizeof((_a)) / sizeof((_a)[0]))
+#define	N(_a) ((int)(sizeof((_a)) / sizeof((_a)[0])))
=20
 #ifdef	USB_DEBUG
 #define RUN_DEBUG
@@ -600,12 +600,6 @@
 	    sc->mac_ver, sc->mac_rev, run_get_rf(sc->rf_rev),
 	    sc->ntxchains, sc->nrxchains, ether_sprintf(sc->sc_bssid));
=20
-	if ((error =3D run_load_microcode(sc)) !=3D 0) {
-		device_printf(sc->sc_dev, "could not load 8051 microcode\n");
-		RUN_UNLOCK(sc);
-		goto detach;
-	}
-
 	RUN_UNLOCK(sc);
=20
 	ifp =3D sc->sc_ifp =3D if_alloc(IFT_IEEE80211);
@@ -664,7 +658,7 @@
 	    sc->rf_rev =3D=3D RT2860_RF_2850 ||
 	    sc->rf_rev =3D=3D RT3070_RF_3052) {
 		/* set supported .11a rates */
-		for (i =3D 14; i < nitems(rt2860_rf2850); i++) {
+		for (i =3D 14; i < N(rt2860_rf2850); i++) {
 			uint8_t chan =3D rt2860_rf2850[i].chan;
 			ic->ic_channels[ic->ic_nchans].ic_freq =3D
 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_A);
@@ -1050,8 +1044,9 @@
 		error =3D ETIMEDOUT;
 		goto fail;
 	}
-	device_printf(sc->sc_dev, "firmware %s loaded\n",
-	    (base =3D=3D fw->data) ? "RT2870" : "RT3071");
+	device_printf(sc->sc_dev, "firmware %s ver. %u.%u loaded\n",
+	    (base =3D=3D fw->data) ? "RT2870" : "RT3071",
+	    *(base + 4092), *(base + 4093));
=20
 fail:
 	firmware_put(fw, FIRMWARE_UNLOAD);
@@ -2579,8 +2574,8 @@
=20
 		DPRINTFN(15, "rx done, actlen=3D%d\n", xferlen);
=20
-		if (xferlen < sizeof (uint32_t) +
-		    sizeof (struct rt2860_rxwi) + sizeof (struct rt2870_rxd)) {
+		if (xferlen < (int)(sizeof(uint32_t) +
+		    sizeof(struct rt2860_rxwi) + sizeof(struct rt2870_rxd))) {
 			DPRINTF("xfer too short %d\n", xferlen);
 			goto tr_setup;
 		}
@@ -2645,11 +2640,12 @@
 	for(;;) {
 		dmalen =3D le32toh(*mtod(m, uint32_t *)) & 0xffff;
=20
-		if ((dmalen =3D=3D 0) || ((dmalen & 3) !=3D 0)) {
+		if ((dmalen >=3D (uint32_t)-8) || (dmalen =3D=3D 0) ||
+		    ((dmalen & 3) !=3D 0)) {
 			DPRINTF("bad DMA length %u\n", dmalen);
 			break;
 		}
-		if ((dmalen + 8) > xferlen) {
+		if ((dmalen + 8) > (uint32_t)xferlen) {
 			DPRINTF("bad DMA length %u > %d\n",
 			dmalen + 8, xferlen);
 			break;
@@ -4311,7 +4307,7 @@
 		return (ETIMEDOUT);
=20
 	/* initialize BBP registers to default values */
-	for (i =3D 0; i < nitems(rt2860_def_bbp); i++) {
+	for (i =3D 0; i < N(rt2860_def_bbp); i++) {
 		run_bbp_write(sc, rt2860_def_bbp[i].reg,
 		    rt2860_def_bbp[i].val);
 	}
@@ -4346,12 +4342,12 @@
=20
 	/* initialize RF registers to default value */
 	if (sc->mac_ver =3D=3D 0x3572) {
-		for (i =3D 0; i < nitems(rt3572_def_rf); i++) {
+		for (i =3D 0; i < N(rt3572_def_rf); i++) {
 			run_rt3070_rf_write(sc, rt3572_def_rf[i].reg,
 			    rt3572_def_rf[i].val);
 		}
 	} else {
-		for (i =3D 0; i < nitems(rt3070_def_rf); i++) {
+		for (i =3D 0; i < N(rt3070_def_rf); i++) {
 			run_rt3070_rf_write(sc, rt3070_def_rf[i].reg,
 			    rt3070_def_rf[i].val);
 		}
@@ -4677,6 +4673,11 @@
=20
 	run_stop(sc);
=20
+	if (run_load_microcode(sc) !=3D 0) {
+		device_printf(sc->sc_dev, "could not load 8051 microcode\n");
+		goto fail;
+	}
+
 	for (ntries =3D 0; ntries < 100; ntries++) {
 		if (run_read(sc, RT2860_ASIC_VER_ID, &tmp) !=3D 0)
 			goto fail;
@@ -4729,7 +4730,7 @@
 		run_write(sc, RT2860_TX_PWR_CFG(ridx), sc->txpow20mhz[ridx]);
 	}
=20
-	for (i =3D 0; i < nitems(rt2870_def_mac); i++)
+	for (i =3D 0; i < N(rt2870_def_mac); i++)
 		run_write(sc, rt2870_def_mac[i].reg, rt2870_def_mac[i].val);
 	run_write(sc, RT2860_WMM_AIFSN_CFG, 0x00002273);
 	run_write(sc, RT2860_WMM_CWMIN_CFG, 0x00002344);
@@ -4949,9 +4950,9 @@
 };
=20
 static driver_t run_driver =3D {
-	"run",
-	run_methods,
-	sizeof(struct run_softc)
+	.name =3D "run",
+	.methods =3D run_methods,
+	.size =3D sizeof(struct run_softc)
 };
=20
 static devclass_t run_devclass;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/wlan/if_uath.c
--- a/head/sys/dev/usb/wlan/if_uath.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/wlan/if_uath.c	Tue Apr 17 11:51:51 2012 +0300
@@ -49,7 +49,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_uath.c 228621 2011-12-17 10:2=
3:17Z bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_uath.c 233774 2012-04-02 10:5=
0:42Z hselasky $");
=20
 /*-
  * Driver for Atheros AR5523 USB parts.
@@ -2309,6 +2309,11 @@
 	/* reply to a read command */
 	default:
 		dlen =3D hdr->len - sizeof(*hdr);
+		if (dlen < 0) {
+			device_printf(sc->sc_dev,
+			    "Invalid header length %d\n", dlen);
+			return;
+		}
 		DPRINTF(sc, UATH_DEBUG_RX_PROC | UATH_DEBUG_RECV_ALL,
 		    "%s: code %d data len %u\n",
 		    __func__, hdr->code & 0xff, dlen);
@@ -2334,7 +2339,7 @@
 			 * number of bytes--unless it's 0 in which
 			 * case a single 32-bit word should be present.
 			 */
-			if (dlen >=3D sizeof(uint32_t)) {
+			if (dlen >=3D (int)sizeof(uint32_t)) {
 				olen =3D be32toh(rp[0]);
 				dlen -=3D sizeof(uint32_t);
 				if (olen =3D=3D 0) {
@@ -2346,7 +2351,7 @@
 				olen =3D 0;
 			if (cmd->odata !=3D NULL) {
 				/* NB: cmd->olen validated in uath_cmd */
-				if (olen > cmd->olen) {
+				if (olen > (u_int)cmd->olen) {
 					/* XXX complain? */
 					device_printf(sc->sc_dev,
 					    "%s: cmd 0x%x olen %u cmd olen %u\n",
@@ -2354,7 +2359,7 @@
 					    cmd->olen);
 					olen =3D cmd->olen;
 				}
-				if (olen > dlen) {
+				if (olen > (u_int)dlen) {
 					/* XXX complain, shouldn't happen */
 					device_printf(sc->sc_dev,
 					    "%s: cmd 0x%x olen %u dlen %u\n",
@@ -2376,7 +2381,7 @@
 			return;
 		}
 		dlen =3D hdr->len - sizeof(*hdr);
-		if (dlen !=3D sizeof(uint32_t)) {
+		if (dlen !=3D (int)sizeof(uint32_t)) {
 			/* XXX something wrong */
 			return;
 		}
@@ -2423,7 +2428,7 @@
 		STAILQ_INSERT_TAIL(&sc->sc_cmd_inactive, cmd, next);
 		UATH_STAT_INC(sc, st_cmd_inactive);
=20
-		KASSERT(actlen >=3D sizeof(struct uath_cmd_hdr),
+		KASSERT(actlen >=3D (int)sizeof(struct uath_cmd_hdr),
 		    ("short xfer error"));
 		pc =3D usbd_xfer_get_frame(xfer, 0);
 		usbd_copy_out(pc, 0, cmd->buf, actlen);
@@ -2542,7 +2547,7 @@
=20
 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
=20
-	if (actlen < UATH_MIN_RXBUFSZ) {
+	if (actlen < (int)UATH_MIN_RXBUFSZ) {
 		DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
 		    "%s: wrong xfer size (len=3D%d)\n", __func__, actlen);
 		ifp->if_ierrors++;
@@ -2888,9 +2893,9 @@
 	{ 0, 0 }
 };
 static driver_t uath_driver =3D {
-	"uath",
-	uath_methods,
-	sizeof(struct uath_softc)
+	.name =3D "uath",
+	.methods =3D uath_methods,
+	.size =3D sizeof(struct uath_softc)
 };
 static devclass_t uath_devclass;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/wlan/if_upgt.c
--- a/head/sys/dev/usb/wlan/if_upgt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/wlan/if_upgt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*	$OpenBSD: if_upgt.c,v 1.35 2008/04/16 18:32:15 damien Exp $ */
-/*	$FreeBSD: head/sys/dev/usb/wlan/if_upgt.c 228621 2011-12-17 10:23:17Z b=
schmidt $ */
+/*	$FreeBSD: head/sys/dev/usb/wlan/if_upgt.c 233774 2012-04-02 10:50:42Z h=
selasky $ */
=20
 /*
  * Copyright (c) 2007 Marcus Glocker <mglocker at openbsd.org>
@@ -1221,7 +1221,7 @@
=20
 	for (i =3D 0; i < elements; i++) {
 		channel =3D ieee80211_mhz2ieee(le16toh(freq3[i].freq), 0);
-		if (!(channel >=3D 0 && channel < IEEE80211_CHAN_MAX))
+		if (channel >=3D IEEE80211_CHAN_MAX)
 			continue;
=20
 		sc->sc_eeprom_freq3[channel] =3D freq3[i];
@@ -1254,7 +1254,7 @@
=20
 	for (i =3D 0; i < elements; i++) {
 		channel =3D ieee80211_mhz2ieee(le16toh(freq4_1[i].freq), 0);
-		if (!(channel >=3D 0 && channel < IEEE80211_CHAN_MAX))
+		if (channel >=3D IEEE80211_CHAN_MAX)
 			continue;
=20
 		freq4_2 =3D (struct upgt_eeprom_freq4_2 *)freq4_1[i].data;
@@ -1282,7 +1282,7 @@
=20
 	for (i =3D 0; i < elements; i++) {
 		channel =3D ieee80211_mhz2ieee(le16toh(freq6[i].freq), 0);
-		if (!(channel >=3D 0 && channel < IEEE80211_CHAN_MAX))
+		if (channel >=3D IEEE80211_CHAN_MAX)
 			continue;
=20
 		sc->sc_eeprom_freq6[channel] =3D freq6[i];
@@ -1403,7 +1403,7 @@
 		return (NULL);
 	}
=20
-	if (actlen < UPGT_RX_MINSZ)
+	if (actlen < (int)UPGT_RX_MINSZ)
 		return (NULL);
=20
 	/*
@@ -1461,7 +1461,7 @@
 static uint32_t
 upgt_chksum_le(const uint32_t *buf, size_t size)
 {
-	int i;
+	size_t i;
 	uint32_t crc =3D 0;
=20
 	for (i =3D 0; i < size; i +=3D sizeof(uint32_t)) {
@@ -1602,7 +1602,10 @@
 	struct upgt_data *data_cmd;
 	struct upgt_fw_x2_header *x2;
 	char start_fwload_cmd[] =3D { 0x3c, 0x0d };
-	int error =3D 0, offset, bsize, n;
+	int error =3D 0;
+	size_t offset;
+	int bsize;
+	int n;
 	uint32_t crc32;
=20
 	fw =3D firmware_get(upgt_fwname);
@@ -1783,7 +1786,9 @@
 	const uint8_t *p;
 	const uint32_t *uc;
 	uint32_t bra_option_type, bra_option_len;
-	int offset, bra_end =3D 0, error =3D 0;
+	size_t offset;
+	int bra_end =3D 0;
+	int error =3D 0;
=20
 	fw =3D firmware_get(upgt_fwname);
 	if (fw =3D=3D NULL) {
@@ -2382,9 +2387,9 @@
 };
=20
 static driver_t upgt_driver =3D {
-        "upgt",
-        upgt_methods,
-        sizeof(struct upgt_softc)
+	.name =3D "upgt",
+	.methods =3D upgt_methods,
+	.size =3D sizeof(struct upgt_softc)
 };
=20
 static devclass_t upgt_devclass;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/wlan/if_ural.c
--- a/head/sys/dev/usb/wlan/if_ural.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/wlan/if_ural.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/*	$FreeBSD: head/sys/dev/usb/wlan/if_ural.c 228621 2011-12-17 10:23:17Z b=
schmidt $	*/
+/*	$FreeBSD: head/sys/dev/usb/wlan/if_ural.c 233774 2012-04-02 10:50:42Z h=
selasky $	*/
=20
 /*-
  * Copyright (c) 2005, 2006
@@ -21,7 +21,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_ural.c 228621 2011-12-17 10:2=
3:17Z bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_ural.c 233774 2012-04-02 10:5=
0:42Z hselasky $");
=20
 /*-
  * Ralink Technology RT2500USB chipset driver
@@ -800,7 +800,7 @@
 			STAILQ_REMOVE_HEAD(&sc->tx_q, next);
 			m =3D data->m;
=20
-			if (m->m_pkthdr.len > (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) {
+			if (m->m_pkthdr.len > (int)(RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) {
 				DPRINTFN(0, "data overflow, %u bytes\n",
 				    m->m_pkthdr.len);
 				m->m_pkthdr.len =3D (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE);
@@ -881,7 +881,7 @@
=20
 		DPRINTFN(15, "rx done, actlen=3D%d\n", len);
=20
-		if (len < RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN) {
+		if (len < (int)(RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN)) {
 			DPRINTF("%s: xfer too short %d\n",
 			    device_get_nameunit(sc->sc_dev), len);
 			ifp->if_ierrors++;
@@ -1950,7 +1950,7 @@
 static int
 ural_bbp_init(struct ural_softc *sc)
 {
-#define N(a)	(sizeof (a) / sizeof ((a)[0]))
+#define N(a)	((int)(sizeof (a) / sizeof ((a)[0])))
 	int i, ntries;
=20
 	/* wait for BBP to be ready */
@@ -2034,7 +2034,7 @@
 static void
 ural_init_locked(struct ural_softc *sc)
 {
-#define N(a)	(sizeof (a) / sizeof ((a)[0]))
+#define N(a)	((int)(sizeof (a) / sizeof ((a)[0])))
 	struct ifnet *ifp =3D sc->sc_ifp;
 	struct ieee80211com *ic =3D ifp->if_l2com;
 	uint16_t tmp;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/wlan/if_urtw.c
--- a/head/sys/dev/usb/wlan/if_urtw.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/wlan/if_urtw.c	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_urtw.c 228621 2011-12-17 10:2=
3:17Z bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_urtw.c 233774 2012-04-02 10:5=
0:42Z hselasky $");
 #include <sys/param.h>
 #include <sys/sockio.h>
 #include <sys/sysctl.h>
@@ -676,8 +676,8 @@
 static void		urtw_watchdog(void *);
 static void		urtw_set_multi(void *);
 static int		urtw_isbmode(uint16_t);
-static uint16_t		urtw_rate2rtl(int);
-static uint16_t		urtw_rtl2rate(int);
+static uint16_t		urtw_rate2rtl(uint32_t);
+static uint16_t		urtw_rtl2rate(uint32_t);
 static usb_error_t	urtw_set_rate(struct urtw_softc *);
 static usb_error_t	urtw_update_msr(struct urtw_softc *);
 static usb_error_t	urtw_read8_c(struct urtw_softc *, int, uint8_t *);
@@ -1092,7 +1092,7 @@
 static usb_error_t
 urtw_adapter_start_b(struct urtw_softc *sc)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	uint8_t data8;
 	usb_error_t error;
=20
@@ -1939,9 +1939,9 @@
 }
=20
 static uint16_t
-urtw_rate2rtl(int rate)
+urtw_rate2rtl(uint32_t rate)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int i;
=20
 	for (i =3D 0; i < N(urtw_ratetable); i++) {
@@ -1954,9 +1954,9 @@
 }
=20
 static uint16_t
-urtw_rtl2rate(int rate)
+urtw_rtl2rate(uint32_t rate)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int i;
=20
 	for (i =3D 0; i < N(urtw_ratetable); i++) {
@@ -2481,7 +2481,7 @@
 static usb_error_t
 urtw_8225_rf_init(struct urtw_softc *sc)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int i;
 	uint16_t data;
 	usb_error_t error;
@@ -2878,7 +2878,7 @@
 static usb_error_t
 urtw_8225v2_rf_init(struct urtw_softc *sc)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int i;
 	uint16_t data;
 	uint32_t data32;
@@ -3212,7 +3212,7 @@
 static usb_error_t
 urtw_8225v2b_rf_init(struct urtw_softc *sc)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int i;
 	uint8_t data8;
 	usb_error_t error;
@@ -3958,7 +3958,7 @@
=20
 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
=20
-	if (actlen < URTW_MIN_RXBUFSZ) {
+	if (actlen < (int)URTW_MIN_RXBUFSZ) {
 		ifp->if_ierrors++;
 		return (NULL);
 	}
@@ -4434,9 +4434,9 @@
 	{ 0, 0 }
 };
 static driver_t urtw_driver =3D {
-	"urtw",
-	urtw_methods,
-	sizeof(struct urtw_softc)
+	.name =3D "urtw",
+	.methods =3D urtw_methods,
+	.size =3D sizeof(struct urtw_softc)
 };
 static devclass_t urtw_devclass;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/usb/wlan/if_zyd.c
--- a/head/sys/dev/usb/wlan/if_zyd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/usb/wlan/if_zyd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 /*	$OpenBSD: if_zyd.c,v 1.52 2007/02/11 00:08:04 jsg Exp $	*/
 /*	$NetBSD: if_zyd.c,v 1.7 2007/06/21 04:04:29 kiyohara Exp $	*/
-/*	$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 228621 2011-12-17 10:23:17Z bs=
chmidt $	*/
+/*	$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 233774 2012-04-02 10:50:42Z hs=
elasky $	*/
=20
 /*-
  * Copyright (c) 2006 by Damien Bergamini <damien.bergamini at free.fr>
@@ -20,7 +20,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 228621 2011-12-17 10:23=
:17Z bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 233774 2012-04-02 10:50=
:42Z hselasky $");
=20
 /*
  * ZyDAS ZD1211/ZD1211B USB WLAN driver.
@@ -670,17 +670,18 @@
 			datalen -=3D 2;	/* XXX: padding? */
=20
 			STAILQ_FOREACH(rqp, &sc->sc_rqh, rq) {
-				int i, cnt;
+				int i;
+				int count;
=20
 				if (rqp->olen !=3D datalen)
 					continue;
-				cnt =3D rqp->olen / sizeof(struct zyd_pair);
-				for (i =3D 0; i < cnt; i++) {
+				count =3D rqp->olen / sizeof(struct zyd_pair);
+				for (i =3D 0; i < count; i++) {
 					if (*(((const uint16_t *)rqp->idata) + i) !=3D
 					    (((struct zyd_pair *)cmd->data) + i)->reg)
 						break;
 				}
-				if (i !=3D cnt)
+				if (i !=3D count)
 					continue;
 				/* copy answer into caller-supplied buffer */
 				memcpy(rqp->odata, cmd->data, rqp->olen);
@@ -779,7 +780,7 @@
 	struct zyd_rq rq;
 	int error;
=20
-	if (ilen > sizeof(cmd.data))
+	if (ilen > (int)sizeof(cmd.data))
 		return (EINVAL);
=20
 	cmd.code =3D htole16(code);
@@ -929,7 +930,7 @@
 static int
 zyd_rfmd_init(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phyini[] =3D ZYD_RFMD_PHY;
 	static const uint32_t rfini[] =3D ZYD_RFMD_RF;
@@ -988,7 +989,7 @@
 static int
 zyd_al2230_init(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phyini[] =3D ZYD_AL2230_PHY;
 	static const struct zyd_phy_pair phy2230s[] =3D ZYD_AL2230S_PHY_INIT;
@@ -1046,7 +1047,7 @@
 static int
 zyd_al2230_fini(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int error, i;
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phy[] =3D ZYD_AL2230_PHY_FINI_PART1;
@@ -1066,7 +1067,7 @@
 static int
 zyd_al2230_init_b(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phy1[] =3D ZYD_AL2230_PHY_PART1;
 	static const struct zyd_phy_pair phy2[] =3D ZYD_AL2230_PHY_PART2;
@@ -1149,7 +1150,7 @@
 static int
 zyd_al2230_set_channel(struct zyd_rf *rf, uint8_t chan)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int error, i;
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phy1[] =3D {
@@ -1179,7 +1180,7 @@
 static int
 zyd_al2230_set_channel_b(struct zyd_rf *rf, uint8_t chan)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int error, i;
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phy1[] =3D ZYD_AL2230_PHY_PART1;
@@ -1214,7 +1215,7 @@
 static int
 zyd_al2230_bandedge6(struct zyd_rf *rf, struct ieee80211_channel *c)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int error =3D 0, i;
 	struct zyd_softc *sc =3D rf->rf_sc;
 	struct ifnet *ifp =3D sc->sc_ifp;
@@ -1238,7 +1239,7 @@
 static int
 zyd_al7230B_init(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phyini_1[] =3D ZYD_AL7230B_PHY_1;
 	static const struct zyd_phy_pair phyini_2[] =3D ZYD_AL7230B_PHY_2;
@@ -1290,7 +1291,7 @@
 static int
 zyd_al7230B_set_channel(struct zyd_rf *rf, uint8_t chan)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct {
 		uint32_t	r1, r2;
@@ -1336,7 +1337,7 @@
 static int
 zyd_al2210_init(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phyini[] =3D ZYD_AL2210_PHY;
 	static const uint32_t rfini[] =3D ZYD_AL2210_RF;
@@ -1409,7 +1410,7 @@
 zyd_gct_init(struct zyd_rf *rf)
 {
 #define	ZYD_GCT_INTR_REG	0x85c1
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phyini[] =3D ZYD_GCT_PHY;
 	static const uint32_t rfini[] =3D ZYD_GCT_RF;
@@ -1431,7 +1432,7 @@
 	if (error !=3D 0)
 		return (error);
=20
-	for (i =3D 0; i < N(vco) - 1; i++) {
+	for (i =3D 0; i < (int)(N(vco) - 1); i++) {
 		error =3D zyd_gct_set_channel_synth(rf, 1, 0);
 		if (error !=3D 0)
 			goto fail;
@@ -1465,7 +1466,7 @@
 static int
 zyd_gct_mode(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const uint32_t mode[] =3D {
 		0x25f98, 0x25f9a, 0x25f94, 0x27fd4
@@ -1507,7 +1508,6 @@
 static int
 zyd_gct_switch_radio(struct zyd_rf *rf, int on)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
 	int error;
 	struct zyd_softc *sc =3D rf->rf_sc;
=20
@@ -1525,7 +1525,7 @@
 static int
 zyd_gct_set_channel(struct zyd_rf *rf, uint8_t chan)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	int error, i;
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair cmd[] =3D {
@@ -1579,7 +1579,7 @@
 static int
 zyd_maxim2_init(struct zyd_rf *rf)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phyini[] =3D ZYD_MAXIM2_PHY;
 	static const uint32_t rfini[] =3D ZYD_MAXIM2_RF;
@@ -1616,7 +1616,7 @@
 static int
 zyd_maxim2_set_channel(struct zyd_rf *rf, uint8_t chan)
 {
-#define N(a)	(sizeof(a) / sizeof((a)[0]))
+#define N(a)	((int)(sizeof(a) / sizeof((a)[0])))
 	struct zyd_softc *sc =3D rf->rf_sc;
 	static const struct zyd_phy_pair phyini[] =3D ZYD_MAXIM2_PHY;
 	static const uint32_t rfini[] =3D ZYD_MAXIM2_RF;
@@ -2185,12 +2185,12 @@
 	    sizeof(struct zyd_rx_stat) - IEEE80211_CRC_LEN;
=20
 	/* allocate a mbuf to store the frame */
-	if (rlen > MCLBYTES) {
+	if (rlen > (int)MCLBYTES) {
 		DPRINTF(sc, ZYD_DEBUG_RECV, "%s: frame too long (length=3D%d)\n",
 		    device_get_nameunit(sc->sc_dev), rlen);
 		ifp->if_ierrors++;
 		return;
-	} else if (rlen > MHLEN)
+	} else if (rlen > (int)MHLEN)
 		m =3D m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
 	else
 		m =3D m_gethdr(M_DONTWAIT, MT_DATA);
@@ -2391,7 +2391,7 @@
 			STAILQ_REMOVE_HEAD(&sc->tx_q, next);
 			m =3D data->m;
=20
-			if (m->m_pkthdr.len > ZYD_MAX_TXBUFSZ) {
+			if (m->m_pkthdr.len > (int)ZYD_MAX_TXBUFSZ) {
 				DPRINTF(sc, ZYD_DEBUG_ANY, "data overflow, %u bytes\n",
 				    m->m_pkthdr.len);
 				m->m_pkthdr.len =3D ZYD_MAX_TXBUFSZ;
@@ -2933,9 +2933,9 @@
 };
=20
 static driver_t zyd_driver =3D {
-        "zyd",
-        zyd_methods,
-        sizeof(struct zyd_softc)
+	.name =3D "zyd",
+	.methods =3D zyd_methods,
+	.size =3D sizeof(struct zyd_softc)
 };
=20
 static devclass_t zyd_devclass;
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/virtio/balloon/virtio_bal=
loon.c
--- a/head/sys/dev/virtio/balloon/virtio_balloon.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/sys/dev/virtio/balloon/virtio_balloon.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -27,7 +27,7 @@
 /* Driver for VirtIO memory balloon devices. */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/balloon/virtio_balloon.c 228301 20=
11-12-06 06:28:32Z grehan $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/balloon/virtio_balloon.c 234270 20=
12-04-14 05:48:04Z grehan $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -122,6 +122,9 @@
  */
 #define VTBALLOON_PAGES_PER_REQUEST	256
=20
+/* Must be able to fix all pages frames in one page (segment). */
+CTASSERT(VTBALLOON_PAGES_PER_REQUEST * sizeof(uint32_t) <=3D PAGE_SIZE);
+
 #define VTBALLOON_MTX(_sc)		&(_sc)->vtballoon_mtx
 #define VTBALLOON_LOCK_INIT(_sc, _name)	mtx_init(VTBALLOON_MTX((_sc)), _na=
me, \
 					    "VirtIO Balloon Lock", MTX_SPIN)
@@ -138,7 +141,7 @@
 	/* VirtIO methods. */
 	DEVMETHOD(virtio_config_change, vtballoon_config_change),
=20
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t vtballoon_driver =3D {
@@ -402,13 +405,13 @@
=20
 	error =3D virtqueue_enqueue(vq, vq, &sg, 1, 0);
 	KASSERT(error =3D=3D 0, ("error enqueuing page frames to virtqueue"));
+	virtqueue_notify(vq);
=20
 	/*
 	 * Inflate and deflate operations are done synchronously. The
 	 * interrupt handler will wake us up.
 	 */
 	VTBALLOON_LOCK(sc);
-	virtqueue_notify(vq);
=20
 	while ((c =3D virtqueue_dequeue(vq, NULL)) =3D=3D NULL)
 		msleep_spin(sc, VTBALLOON_MTX(sc), "vtbspf", 0);
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/virtio/block/virtio_blk.c
--- a/head/sys/dev/virtio/block/virtio_blk.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/virtio/block/virtio_blk.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 /* Driver for VirtIO block devices. */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/block/virtio_blk.c 228301 2011-12-=
06 06:28:32Z grehan $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/block/virtio_blk.c 234349 2012-04-=
16 18:29:12Z grehan $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -70,8 +70,8 @@
 	uint32_t		 vtblk_flags;
 #define VTBLK_FLAG_INDIRECT	0x0001
 #define VTBLK_FLAG_READONLY	0x0002
-#define VTBLK_FLAG_DETACHING	0x0004
-#define VTBLK_FLAG_SUSPENDED	0x0008
+#define VTBLK_FLAG_DETACH	0x0004
+#define VTBLK_FLAG_SUSPEND	0x0008
 #define VTBLK_FLAG_DUMPING	0x0010
=20
 	struct virtqueue	*vtblk_vq;
@@ -82,7 +82,7 @@
 	TAILQ_HEAD(, vtblk_request)
 				 vtblk_req_free;
 	TAILQ_HEAD(, vtblk_request)
-				 vtblk_req_ready;
+				vtblk_req_ready;
=20
 	struct taskqueue	*vtblk_tq;
 	struct task		 vtblk_intr_task;
@@ -116,6 +116,13 @@
 static int	vtblk_resume(device_t);
 static int	vtblk_shutdown(device_t);
=20
+static int	vtblk_open(struct disk *);
+static int	vtblk_close(struct disk *);
+static int	vtblk_ioctl(struct disk *, u_long, void *, int,
+	            struct thread *);
+static int	vtblk_dump(void *, void *, vm_offset_t, off_t, size_t);
+static void	vtblk_strategy(struct bio *);
+
 static void	vtblk_negotiate_features(struct vtblk_softc *);
 static int	vtblk_maximum_segments(struct vtblk_softc *,
 		    struct virtio_blk_config *);
@@ -124,13 +131,7 @@
 		    struct virtio_blk_config *);
 static void	vtblk_create_disk(struct vtblk_softc *);
=20
-static int	vtblk_open(struct disk *);
-static int	vtblk_close(struct disk *);
-static int	vtblk_ioctl(struct disk *, u_long, void *, int,
-		    struct thread *);
-static int	vtblk_dump(void *, void *, vm_offset_t, off_t, size_t);
-static void	vtblk_strategy(struct bio *);
-
+static int	vtblk_quiesce(struct vtblk_softc *);
 static void	vtblk_startio(struct vtblk_softc *);
 static struct vtblk_request * vtblk_bio_request(struct vtblk_softc *);
 static int	vtblk_execute_request(struct vtblk_softc *,
@@ -148,6 +149,7 @@
 static int	vtblk_poll_request(struct vtblk_softc *,
 		    struct vtblk_request *);
=20
+static void	vtblk_finish_completed(struct vtblk_softc *);
 static void	vtblk_drain_vq(struct vtblk_softc *, int);
 static void	vtblk_drain(struct vtblk_softc *);
=20
@@ -161,7 +163,8 @@
 static void	vtblk_enqueue_ready(struct vtblk_softc *,
 		    struct vtblk_request *);
=20
-static void	vtblk_bio_error(struct bio *, int);
+static int	vtblk_request_error(struct vtblk_request *);
+static void	vtblk_finish_bio(struct bio *, int);
=20
 /* Tunables. */
 static int vtblk_no_ident =3D 0;
@@ -189,9 +192,8 @@
 #define VTBLK_LOCK_ASSERT_NOTOWNED(_sc) \
 				mtx_assert(VTBLK_MTX((_sc)), MA_NOTOWNED)
=20
-#define VTBLK_BIO_SEGMENTS(_bp)	sglist_count((_bp)->bio_data, (_bp)->bio_b=
count)
-
 #define VTBLK_DISK_NAME		"vtbd"
+#define	VTBLK_QUIESCE_TIMEOUT	(30 * hz)
=20
 /*
  * Each block request uses at least two segments - one for the header
@@ -210,7 +212,7 @@
 	DEVMETHOD(device_resume,	vtblk_resume),
 	DEVMETHOD(device_shutdown,	vtblk_shutdown),
=20
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t vtblk_driver =3D {
@@ -314,11 +316,13 @@
 	}
=20
 	sc->vtblk_max_nsegs =3D vtblk_maximum_segments(sc, &blkcfg);
+        if (sc->vtblk_max_nsegs <=3D VTBLK_MIN_SEGMENTS) {
+		error =3D EINVAL;
+		device_printf(dev, "fewer than minimum number of segments "
+		    "allowed: %d\n", sc->vtblk_max_nsegs);
+		goto fail;
+	}
=20
-	/*
-	 * Allocate working sglist. The number of segments may be too
-	 * large to safely store on the stack.
-	 */
 	sc->vtblk_sglist =3D sglist_alloc(sc->vtblk_max_nsegs, M_NOWAIT);
 	if (sc->vtblk_sglist =3D=3D NULL) {
 		error =3D ENOMEM;
@@ -376,7 +380,7 @@
 	sc =3D device_get_softc(dev);
=20
 	VTBLK_LOCK(sc);
-	sc->vtblk_flags |=3D VTBLK_FLAG_DETACHING;
+	sc->vtblk_flags |=3D VTBLK_FLAG_DETACH;
 	if (device_is_attached(dev))
 		vtblk_stop(sc);
 	VTBLK_UNLOCK(sc);
@@ -408,15 +412,19 @@
 vtblk_suspend(device_t dev)
 {
 	struct vtblk_softc *sc;
+	int error;
=20
 	sc =3D device_get_softc(dev);
=20
 	VTBLK_LOCK(sc);
-	sc->vtblk_flags |=3D VTBLK_FLAG_SUSPENDED;
-	/* TODO Wait for any inflight IO to complete? */
+	sc->vtblk_flags |=3D VTBLK_FLAG_SUSPEND;
+	/* XXX BMV: virtio_stop(), etc needed here? */
+	error =3D vtblk_quiesce(sc);
+	if (error)
+		sc->vtblk_flags &=3D ~VTBLK_FLAG_SUSPEND;
 	VTBLK_UNLOCK(sc);
=20
-	return (0);
+	return (error);
 }
=20
 static int
@@ -427,8 +435,9 @@
 	sc =3D device_get_softc(dev);
=20
 	VTBLK_LOCK(sc);
-	sc->vtblk_flags &=3D ~VTBLK_FLAG_SUSPENDED;
-	/* TODO Resume IO? */
+	/* XXX BMV: virtio_reinit(), etc needed here? */
+	sc->vtblk_flags &=3D ~VTBLK_FLAG_SUSPEND;
+	vtblk_startio(sc);
 	VTBLK_UNLOCK(sc);
=20
 	return (0);
@@ -449,7 +458,7 @@
 	if ((sc =3D dp->d_drv1) =3D=3D NULL)
 		return (ENXIO);
=20
-	return (sc->vtblk_flags & VTBLK_FLAG_DETACHING ? ENXIO : 0);
+	return (sc->vtblk_flags & VTBLK_FLAG_DETACH ? ENXIO : 0);
 }
=20
 static int
@@ -489,6 +498,8 @@
 	if ((sc =3D dp->d_drv1) =3D=3D NULL)
 		return (ENXIO);
=20
+	VTBLK_LOCK(sc);
+
 	if ((sc->vtblk_flags & VTBLK_FLAG_DUMPING) =3D=3D 0) {
 		vtblk_prepare_dump(sc);
 		sc->vtblk_flags |=3D VTBLK_FLAG_DUMPING;
@@ -498,6 +509,10 @@
 		error =3D vtblk_write_dump(sc, virtual, offset, length);
 	else if (virtual =3D=3D NULL && offset =3D=3D 0)
 		error =3D vtblk_flush_dump(sc);
+	else {
+		error =3D EINVAL;
+		sc->vtblk_flags &=3D ~VTBLK_FLAG_DUMPING;
+	}
=20
 	VTBLK_UNLOCK(sc);
=20
@@ -510,7 +525,7 @@
 	struct vtblk_softc *sc;
=20
 	if ((sc =3D bp->bio_disk->d_drv1) =3D=3D NULL) {
-		vtblk_bio_error(bp, EINVAL);
+		vtblk_finish_bio(bp, EINVAL);
 		return;
 	}
=20
@@ -520,29 +535,37 @@
 	 */
 	if (sc->vtblk_flags & VTBLK_FLAG_READONLY &&
 	    (bp->bio_cmd =3D=3D BIO_WRITE || bp->bio_cmd =3D=3D BIO_FLUSH)) {
-		vtblk_bio_error(bp, EROFS);
+		vtblk_finish_bio(bp, EROFS);
 		return;
 	}
=20
+#ifdef	INVARIANTS
 	/*
 	 * Prevent read/write buffers spanning too many segments from
 	 * getting into the queue. This should only trip if d_maxsize
 	 * was incorrectly set.
 	 */
 	if (bp->bio_cmd =3D=3D BIO_READ || bp->bio_cmd =3D=3D BIO_WRITE) {
-		KASSERT(VTBLK_BIO_SEGMENTS(bp) <=3D sc->vtblk_max_nsegs -
-		    VTBLK_MIN_SEGMENTS,
+		int nsegs, max_nsegs;
+	=09
+		nsegs =3D sglist_count(bp->bio_data, bp->bio_bcount);
+		max_nsegs =3D sc->vtblk_max_nsegs - VTBLK_MIN_SEGMENTS;
+
+		KASSERT(nsegs <=3D max_nsegs,
 		    ("bio spanned too many segments: %d, max: %d",
-		    VTBLK_BIO_SEGMENTS(bp),
-		    sc->vtblk_max_nsegs - VTBLK_MIN_SEGMENTS));
+		    nsegs, max_nsegs));
 	}
+#endif
=20
 	VTBLK_LOCK(sc);
-	if ((sc->vtblk_flags & VTBLK_FLAG_DETACHING) =3D=3D 0) {
+	if (sc->vtblk_flags & VTBLK_FLAG_DETACH)
+		vtblk_finish_bio(bp, ENXIO);
+	else {
 		bioq_disksort(&sc->vtblk_bioq, bp);
-		vtblk_startio(sc);
-	} else
-		vtblk_bio_error(bp, ENXIO);
+
+		if ((sc->vtblk_flags & VTBLK_FLAG_SUSPEND) =3D=3D 0)
+			vtblk_startio(sc);
+	}
 	VTBLK_UNLOCK(sc);
 }
=20
@@ -669,6 +692,26 @@
 	disk_create(dp, DISK_VERSION);
 }
=20
+static int
+vtblk_quiesce(struct vtblk_softc *sc)
+{
+	int error;
+
+	error =3D 0;
+
+	VTBLK_LOCK_ASSERT(sc);
+
+	while (!virtqueue_empty(sc->vtblk_vq)) {
+		if (mtx_sleep(&sc->vtblk_vq, VTBLK_MTX(sc), PRIBIO, "vtblkq",
+		    VTBLK_QUIESCE_TIMEOUT) =3D=3D EWOULDBLOCK) {
+			error =3D EBUSY;
+			break;
+		}
+	}
+
+	return (error);
+}
+
 static void
 vtblk_startio(struct vtblk_softc *sc)
 {
@@ -681,9 +724,6 @@
=20
 	VTBLK_LOCK_ASSERT(sc);
=20
-	if (sc->vtblk_flags & VTBLK_FLAG_SUSPENDED)
-		return;
-
 	while (!virtqueue_full(vq)) {
 		if ((req =3D vtblk_dequeue_ready(sc)) =3D=3D NULL)
 			req =3D vtblk_bio_request(sc);
@@ -736,9 +776,8 @@
 		req->vbr_hdr.sector =3D bp->bio_offset / 512;
 		break;
 	default:
-		KASSERT(0, ("bio with unhandled cmd: %d", bp->bio_cmd));
-		req->vbr_hdr.type =3D -1;
-		break;
+		panic("%s: bio with unhandled cmd: %d", __FUNCTION__,
+		    bp->bio_cmd);
 	}
=20
 	if (bp->bio_flags & BIO_ORDERED)
@@ -752,7 +791,7 @@
 {
 	struct sglist *sg;
 	struct bio *bp;
-	int writable, error;
+	int readable, writable, error;
=20
 	sg =3D sc->vtblk_sglist;
 	bp =3D req->vbr_bp;
@@ -783,10 +822,9 @@
 	KASSERT(sg->sg_nseg >=3D VTBLK_MIN_SEGMENTS,
 	    ("fewer than min segments: %d", sg->sg_nseg));
=20
-	error =3D virtqueue_enqueue(sc->vtblk_vq, req, sg,
-	    sg->sg_nseg - writable, writable);
+	readable =3D sg->sg_nseg - writable;
=20
-	return (error);
+	return (virtqueue_enqueue(sc->vtblk_vq, req, sg, readable, writable));
 }
=20
 static int
@@ -806,37 +844,23 @@
 vtblk_intr_task(void *arg, int pending)
 {
 	struct vtblk_softc *sc;
-	struct vtblk_request *req;
 	struct virtqueue *vq;
-	struct bio *bp;
=20
 	sc =3D arg;
 	vq =3D sc->vtblk_vq;
=20
 	VTBLK_LOCK(sc);
-	if (sc->vtblk_flags & VTBLK_FLAG_DETACHING) {
+	if (sc->vtblk_flags & VTBLK_FLAG_DETACH) {
 		VTBLK_UNLOCK(sc);
 		return;
 	}
=20
-	while ((req =3D virtqueue_dequeue(vq, NULL)) !=3D NULL) {
-		bp =3D req->vbr_bp;
+	vtblk_finish_completed(sc);
=20
-		if (req->vbr_ack =3D=3D VIRTIO_BLK_S_OK)
-			bp->bio_resid =3D 0;
-		else {
-			bp->bio_flags |=3D BIO_ERROR;
-			if (req->vbr_ack =3D=3D VIRTIO_BLK_S_UNSUPP)
-				bp->bio_error =3D ENOTSUP;
-			else
-				bp->bio_error =3D EIO;
-		}
-
-		biodone(bp);
-		vtblk_enqueue_request(sc, req);
-	}
-
-	vtblk_startio(sc);
+	if ((sc->vtblk_flags & VTBLK_FLAG_SUSPEND) =3D=3D 0)
+		vtblk_startio(sc);
+	else
+		wakeup(&sc->vtblk_vq);
=20
 	if (virtqueue_enable_intr(vq) !=3D 0) {
 		virtqueue_disable_intr(vq);
@@ -991,17 +1015,35 @@
 	r =3D virtqueue_poll(vq, NULL);
 	KASSERT(r =3D=3D req, ("unexpected request response"));
=20
-	if (req->vbr_ack !=3D VIRTIO_BLK_S_OK) {
-		error =3D req->vbr_ack =3D=3D VIRTIO_BLK_S_UNSUPP ? ENOTSUP : EIO;
-		if (bootverbose)
-			device_printf(dev,
-			    "vtblk_poll_request: IO error: %d\n", error);
+	error =3D vtblk_request_error(req);
+	if (error && bootverbose) {
+		device_printf(dev, "vtblk_poll_request: IO error: %d\n",
+		    error);
 	}
=20
 	return (error);
 }
=20
 static void
+vtblk_finish_completed(struct vtblk_softc *sc)
+{
+	struct vtblk_request *req;
+	struct bio *bp;
+	int error;
+
+	while ((req =3D virtqueue_dequeue(sc->vtblk_vq, NULL)) !=3D NULL) {
+		bp =3D req->vbr_bp;
+
+		error =3D vtblk_request_error(req);
+		if (error)
+			disk_err(bp, "hard error", -1, 1);
+
+		vtblk_finish_bio(bp, error);
+		vtblk_enqueue_request(sc, req);
+	}
+}
+
+static void
 vtblk_drain_vq(struct vtblk_softc *sc, int skip_done)
 {
 	struct virtqueue *vq;
@@ -1013,7 +1055,7 @@
=20
 	while ((req =3D virtqueue_drain(vq, &last)) !=3D NULL) {
 		if (!skip_done)
-			vtblk_bio_error(req->vbr_bp, ENXIO);
+			vtblk_finish_bio(req->vbr_bp, ENXIO);
=20
 		vtblk_enqueue_request(sc, req);
 	}
@@ -1030,17 +1072,19 @@
=20
 	bioq =3D &sc->vtblk_bioq;
=20
-	if (sc->vtblk_vq !=3D NULL)
+	if (sc->vtblk_vq !=3D NULL) {
+		vtblk_finish_completed(sc);
 		vtblk_drain_vq(sc, 0);
+	}
=20
 	while ((req =3D vtblk_dequeue_ready(sc)) !=3D NULL) {
-		vtblk_bio_error(req->vbr_bp, ENXIO);
+		vtblk_finish_bio(req->vbr_bp, ENXIO);
 		vtblk_enqueue_request(sc, req);
 	}
=20
 	while (bioq_first(bioq) !=3D NULL) {
 		bp =3D bioq_takefirst(bioq);
-		vtblk_bio_error(bp, ENXIO);
+		vtblk_finish_bio(bp, ENXIO);
 	}
=20
 	vtblk_free_requests(sc);
@@ -1050,9 +1094,9 @@
 vtblk_alloc_requests(struct vtblk_softc *sc)
 {
 	struct vtblk_request *req;
-	int i, size;
+	int i, nreqs;
=20
-	size =3D virtqueue_size(sc->vtblk_vq);
+	nreqs =3D virtqueue_size(sc->vtblk_vq);
=20
 	/*
 	 * Preallocate sufficient requests to keep the virtqueue full. Each
@@ -1060,9 +1104,9 @@
 	 * the number allocated when indirect descriptors are not available.
 	 */
 	if ((sc->vtblk_flags & VTBLK_FLAG_INDIRECT) =3D=3D 0)
-		size /=3D VTBLK_MIN_SEGMENTS;
+		nreqs /=3D VTBLK_MIN_SEGMENTS;
=20
-	for (i =3D 0; i < size; i++) {
+	for (i =3D 0; i < nreqs; i++) {
 		req =3D uma_zalloc(vtblk_req_zone, M_NOWAIT);
 		if (req =3D=3D NULL)
 			return (ENOMEM);
@@ -1079,6 +1123,9 @@
 {
 	struct vtblk_request *req;
=20
+	KASSERT(TAILQ_EMPTY(&sc->vtblk_req_ready),
+	    ("ready requests left on queue"));
+
 	while ((req =3D vtblk_dequeue_request(sc)) !=3D NULL) {
 		sc->vtblk_request_count--;
 		uma_zfree(vtblk_req_zone, req);
@@ -1126,9 +1173,35 @@
 	TAILQ_INSERT_HEAD(&sc->vtblk_req_ready, req, vbr_link);
 }
=20
+static int
+vtblk_request_error(struct vtblk_request *req)
+{
+	int error;
+
+	switch (req->vbr_ack) {
+	case VIRTIO_BLK_S_OK:
+		error =3D 0;
+		break;
+	case VIRTIO_BLK_S_UNSUPP:
+		error =3D ENOTSUP;
+		break;
+	default:
+		error =3D EIO;
+		break;
+	}
+
+	return (error);
+}
+
 static void
-vtblk_bio_error(struct bio *bp, int error)
+vtblk_finish_bio(struct bio *bp, int error)
 {
=20
-	biofinish(bp, NULL, error);
+	if (error) {
+		bp->bio_resid =3D bp->bio_bcount;
+		bp->bio_error =3D error;
+		bp->bio_flags |=3D BIO_ERROR;
+	}
+
+	biodone(bp);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/virtio/network/if_vtnet.c
--- a/head/sys/dev/virtio/network/if_vtnet.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/virtio/network/if_vtnet.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 /* Driver for VirtIO network devices. */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/network/if_vtnet.c 228301 2011-12-=
06 06:28:32Z grehan $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/network/if_vtnet.c 234270 2012-04-=
14 05:48:04Z grehan $");
=20
 #ifdef HAVE_KERNEL_OPTION_HEADERS
 #include "opt_device_polling.h"
@@ -223,7 +223,7 @@
 	/* VirtIO methods. */
 	DEVMETHOD(virtio_config_change, vtnet_config_change),
=20
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t vtnet_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/virtio/pci/virtio_pci.c
--- a/head/sys/dev/virtio/pci/virtio_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/virtio/pci/virtio_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 /* Driver for the VirtIO PCI interface. */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/pci/virtio_pci.c 232470 2012-03-03=
 18:03:50Z jhb $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/pci/virtio_pci.c 234270 2012-04-14=
 05:48:04Z grehan $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -189,7 +189,7 @@
 	DEVMETHOD(virtio_bus_read_device_config,  vtpci_read_dev_config),
 	DEVMETHOD(virtio_bus_write_device_config, vtpci_write_dev_config),
=20
-	{ 0, 0 }
+	DEVMETHOD_END
 };
=20
 static driver_t vtpci_driver =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/virtio/virtio_ring.h
--- a/head/sys/dev/virtio/virtio_ring.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/virtio/virtio_ring.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/virtio/virtio_ring.h 228301 2011-12-06 06:28:32Z=
 grehan $
+ * $FreeBSD: head/sys/dev/virtio/virtio_ring.h 234270 2012-04-14 05:48:04Z=
 grehan $
  */
=20
 #ifndef VIRTIO_RING_H
@@ -103,6 +103,7 @@
  *      __u16 avail_flags;
  *      __u16 avail_idx;
  *      __u16 available[num];
+ *      __u16 used_event_idx;
  *
  *      // Padding to the next align boundary.
  *      char pad[];
@@ -111,11 +112,19 @@
  *      __u16 used_flags;
  *      __u16 used_idx;
  *      struct vring_used_elem used[num];
+ *      __u16 avail_event_idx;
  * };
  *
  * NOTE: for VirtIO PCI, align is 4096.
  */
=20
+/*
+ * We publish the used event index at the end of the available ring, and v=
ice
+ * versa. They are at the end for backwards compatibility.
+ */
+#define	vring_used_event(vr)	((vr)->avail->ring[(vr)->num])
+#define	vring_avail_event(vr)	(*(uint16_t *)&(vr)->used->ring[(vr)->num])
+
 static inline int
 vring_size(unsigned int num, unsigned long align)
 {
@@ -140,4 +149,18 @@
         vr->used =3D (void *)
 	    (((unsigned long) &vr->avail->ring[num] + align-1) & ~(align-1));
 }
+
+/*
+ * The following is used with VIRTIO_RING_F_EVENT_IDX.
+ *
+ * Assuming a given event_idx value from the other size, if we have
+ * just incremented index from old to new_idx, should we trigger an
+ * event?
+ */
+static inline int
+vring_need_event(uint16_t event_idx, uint16_t new_idx, uint16_t old)
+{
+
+	return (uint16_t)(new_idx - event_idx - 1) < (uint16_t)(new_idx - old);
+}
 #endif /* VIRTIO_RING_H */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/virtio/virtqueue.c
--- a/head/sys/dev/virtio/virtqueue.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/virtio/virtqueue.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/virtqueue.c 227652 2011-11-18 05:4=
3:43Z grehan $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/virtqueue.c 234270 2012-04-14 05:4=
8:04Z grehan $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -60,6 +60,7 @@
 	uint16_t		 vq_nentries;
 	uint32_t		 vq_flags;
 #define	VIRTQUEUE_FLAG_INDIRECT	 0x0001
+#define	VIRTQUEUE_FLAG_EVENT_IDX 0x0002
=20
 	int			 vq_alignment;
 	int			 vq_ring_size;
@@ -126,7 +127,8 @@
 static int	vq_ring_use_indirect(struct virtqueue *, int);
 static void	vq_ring_enqueue_indirect(struct virtqueue *, void *,
 		    struct sglist *, int, int);
-static void	vq_ring_notify_host(struct virtqueue *, int);
+static int	vq_ring_must_notify_host(struct virtqueue *);
+static void	vq_ring_notify_host(struct virtqueue *);
 static void	vq_ring_free_chain(struct virtqueue *, uint16_t);
=20
 uint64_t
@@ -136,6 +138,7 @@
=20
 	mask =3D (1 << VIRTIO_TRANSPORT_F_START) - 1;
 	mask |=3D VIRTIO_RING_F_INDIRECT_DESC;
+	mask |=3D VIRTIO_RING_F_EVENT_IDX;
=20
 	return (features & mask);
 }
@@ -184,6 +187,9 @@
 	vq->vq_intrhand =3D info->vqai_intr;
 	vq->vq_intrhand_arg =3D info->vqai_intr_arg;
=20
+	if (VIRTIO_BUS_WITH_FEATURE(dev, VIRTIO_RING_F_EVENT_IDX) !=3D 0)
+		vq->vq_flags |=3D VIRTQUEUE_FLAG_EVENT_IDX;
+
 	if (info->vqai_maxindirsz > 1) {
 		error =3D virtqueue_init_indirect(vq, info->vqai_maxindirsz);
 		if (error)
@@ -384,9 +390,12 @@
 void
 virtqueue_notify(struct virtqueue *vq)
 {
+	/* Ensure updated avail->idx is visible to host. */
+	mb();
=20
+	if (vq_ring_must_notify_host(vq))
+		vq_ring_notify_host(vq);
 	vq->vq_queued_cnt =3D 0;
-	vq_ring_notify_host(vq, 0);
 }
=20
 int
@@ -395,11 +404,8 @@
 	uint16_t used_idx, nused;
=20
 	used_idx =3D vq->vq_ring.used->idx;
-	if (used_idx >=3D vq->vq_used_cons_idx)
-		nused =3D used_idx - vq->vq_used_cons_idx;
-	else
-		nused =3D UINT16_MAX - vq->vq_used_cons_idx +
-		    used_idx + 1;
+
+	nused =3D (uint16_t)(used_idx - vq->vq_used_cons_idx);
 	VQASSERT(vq, nused <=3D vq->vq_nentries, "used more than available");
=20
 	return (nused);
@@ -427,6 +433,10 @@
 	 * index of what's already been consumed.
 	 */
 	vq->vq_ring.avail->flags &=3D ~VRING_AVAIL_F_NO_INTERRUPT;
+	if (vq->vq_flags & VIRTQUEUE_FLAG_EVENT_IDX)
+		vring_used_event(&vq->vq_ring) =3D vq->vq_used_cons_idx;
+       else
+	       vq->vq_ring.avail->flags &=3D ~VRING_AVAIL_F_NO_INTERRUPT;
=20
 	mb();
=20
@@ -441,6 +451,37 @@
 	return (0);
 }
=20
+int
+virtqueue_postpone_intr(struct virtqueue *vq)
+{
+	uint16_t ndesc;
+
+	/*
+	 * Postpone until at least half of the available descriptors
+	 * have been consumed.
+	 *
+	 * XXX Adaptive factor? (Linux uses 3/4)
+	 */
+	ndesc =3D (uint16_t)(vq->vq_ring.avail->idx - vq->vq_used_cons_idx) / 2;
+
+	if (vq->vq_flags & VIRTQUEUE_FLAG_EVENT_IDX)
+		vring_used_event(&vq->vq_ring) =3D vq->vq_used_cons_idx + ndesc;
+	else
+		vq->vq_ring.avail->flags &=3D ~VRING_AVAIL_F_NO_INTERRUPT;
+
+	mb();
+
+	/*
+	 * Enough items may have already been consumed to meet our
+	 * threshold since we last checked. Let our caller know so
+	 * it processes the new entries.
+	 */
+	if (virtqueue_nused(vq) > ndesc)
+		return (1);
+
+	return (0);
+}
+
 void
 virtqueue_disable_intr(struct virtqueue *vq)
 {
@@ -448,7 +489,8 @@
 	/*
 	 * Note this is only considered a hint to the host.
 	 */
-	vq->vq_ring.avail->flags |=3D VRING_AVAIL_F_NO_INTERRUPT;
+	if ((vq->vq_flags & VIRTQUEUE_FLAG_EVENT_IDX) =3D=3D 0)
+		vq->vq_ring.avail->flags |=3D VRING_AVAIL_F_NO_INTERRUPT;
 }
=20
 int
@@ -618,7 +660,7 @@
 	mb();
 	vq->vq_ring.avail->idx++;
=20
-	/* Keep pending count until virtqueue_notify() for debugging. */
+	/* Keep pending count until virtqueue_notify(). */
 	vq->vq_queued_cnt++;
 }
=20
@@ -709,15 +751,27 @@
 	vq_ring_update_avail(vq, head_idx);
 }
=20
+static int
+vq_ring_must_notify_host(struct virtqueue *vq)
+{
+	uint16_t new_idx, prev_idx, event_idx;
+
+	if (vq->vq_flags & VIRTQUEUE_FLAG_EVENT_IDX) {
+		new_idx =3D vq->vq_ring.avail->idx;
+		prev_idx =3D new_idx - vq->vq_queued_cnt;
+		event_idx =3D vring_avail_event(&vq->vq_ring);
+
+		return (vring_need_event(event_idx, new_idx, prev_idx) !=3D 0);
+	}
+
+	return ((vq->vq_ring.used->flags & VRING_USED_F_NO_NOTIFY) =3D=3D 0);
+}
+
 static void
-vq_ring_notify_host(struct virtqueue *vq, int force)
+vq_ring_notify_host(struct virtqueue *vq)
 {
=20
-	mb();
-
-	if (force ||
-	    (vq->vq_ring.used->flags & VRING_USED_F_NO_NOTIFY) =3D=3D 0)
-		VIRTIO_BUS_NOTIFY_VQ(vq->vq_dev, vq->vq_queue_index);
+	VIRTIO_BUS_NOTIFY_VQ(vq->vq_dev, vq->vq_queue_index);
 }
=20
 static void
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/virtio/virtqueue.h
--- a/head/sys/dev/virtio/virtqueue.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/virtio/virtqueue.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/virtio/virtqueue.h 227652 2011-11-18 05:43:43Z g=
rehan $
+ * $FreeBSD: head/sys/dev/virtio/virtqueue.h 234270 2012-04-14 05:48:04Z g=
rehan $
  */
=20
 #ifndef _VIRTIO_VIRTQUEUE_H
@@ -78,6 +78,7 @@
=20
 int	 virtqueue_intr(struct virtqueue *vq);
 int	 virtqueue_enable_intr(struct virtqueue *vq);
+int	 virtqueue_postpone_intr(struct virtqueue *vq);
 void	 virtqueue_disable_intr(struct virtqueue *vq);
=20
 /* Get physical address of the virtqueue ring. */
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/wpi/if_wpi.c
--- a/head/sys/dev/wpi/if_wpi.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/wpi/if_wpi.c	Tue Apr 17 11:51:51 2012 +0300
@@ -19,7 +19,7 @@
 #define VERSION "20071127"
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/wpi/if_wpi.c 228621 2011-12-17 10:23:17Z =
bschmidt $");
+__FBSDID("$FreeBSD: head/sys/dev/wpi/if_wpi.c 233387 2012-03-23 19:32:30Z =
bschmidt $");
=20
 /*
  * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
@@ -1218,8 +1218,9 @@
 wpi_suspend(device_t dev)
 {
 	struct wpi_softc *sc =3D device_get_softc(dev);
-
-	wpi_stop(sc);
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
+
+	ieee80211_suspend_all(ic);
 	return 0;
 }
=20
@@ -1227,15 +1228,11 @@
 wpi_resume(device_t dev)
 {
 	struct wpi_softc *sc =3D device_get_softc(dev);
-	struct ifnet *ifp =3D sc->sc_ifp;
+	struct ieee80211com *ic =3D sc->sc_ifp->if_l2com;
=20
 	pci_write_config(dev, 0x41, 0, 1);
=20
-	if (ifp->if_flags & IFF_UP) {
-		wpi_init(ifp->if_softc);
-		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
-			wpi_start(ifp);
-	}
+	ieee80211_resume_all(ic);
 	return 0;
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/xen/balloon/balloon.c
--- a/head/sys/dev/xen/balloon/balloon.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/xen/balloon/balloon.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/xen/balloon/balloon.c 227309 2011-11-07 1=
5:43:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/dev/xen/balloon/balloon.c 233939 2012-04-06 0=
8:13:29Z pluknet $");
=20
 #include <sys/param.h>
 #include <sys/lock.h>
@@ -140,7 +140,7 @@
 	STAILQ_REMOVE_HEAD(&ballooned_pages, list);
=20
 	page =3D entry->page;
-	free(entry, M_DEVBUF);
+	free(entry, M_BALLOON);
 =09
 	bs.balloon_low--;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/dev/xen/blkfront/blkfront.c
--- a/head/sys/dev/xen/blkfront/blkfront.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/dev/xen/blkfront/blkfront.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/xen/blkfront/blkfront.c 232883 2012-03-12=
 19:29:35Z scottl $");
+__FBSDID("$FreeBSD: head/sys/dev/xen/blkfront/blkfront.c 233465 2012-03-25=
 14:20:43Z gibbs $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -698,21 +698,25 @@
 		return;
=20
 	/* Support both backend schemes for relaying ring page limits. */
-	error =3D xs_printf(XST_NIL, node_path,
-			 "num-ring-pages","%u", sc->ring_pages);
-	if (error) {
-		xenbus_dev_fatal(sc->xb_dev, error,
-				 "writing %s/num-ring-pages",
-				 node_path);
-		return;
-	}
-	error =3D xs_printf(XST_NIL, node_path,
-			 "ring-page-order","%u", fls(sc->ring_pages) - 1);
-	if (error) {
-		xenbus_dev_fatal(sc->xb_dev, error,
-				 "writing %s/ring-page-order",
-				 node_path);
-		return;
+	if (sc->ring_pages > 1) {
+		error =3D xs_printf(XST_NIL, node_path,
+				 "num-ring-pages","%u", sc->ring_pages);
+		if (error) {
+			xenbus_dev_fatal(sc->xb_dev, error,
+					 "writing %s/num-ring-pages",
+					 node_path);
+			return;
+		}
+
+		error =3D xs_printf(XST_NIL, node_path,
+				 "ring-page-order", "%u",
+				 fls(sc->ring_pages) - 1);
+		if (error) {
+			xenbus_dev_fatal(sc->xb_dev, error,
+					 "writing %s/ring-page-order",
+					 node_path);
+			return;
+		}
 	}
=20
 	error =3D xs_printf(XST_NIL, node_path,
diff -r 428842767fa6 -r f2935497fa04 head/sys/fs/ext2fs/ext2_vnops.c
--- a/head/sys/fs/ext2fs/ext2_vnops.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/fs/ext2fs/ext2_vnops.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  *
  *	@(#)ufs_vnops.c	8.7 (Berkeley) 2/3/94
  *	@(#)ufs_vnops.c 8.27 (Berkeley) 5/27/95
- * $FreeBSD: head/sys/fs/ext2fs/ext2_vnops.c 232821 2012-03-11 12:19:58Z k=
ib $
+ * $FreeBSD: head/sys/fs/ext2fs/ext2_vnops.c 234203 2012-04-13 05:48:31Z j=
h $
  */
=20
 #include "opt_suiddir.h"
@@ -424,23 +424,19 @@
 		 * if securelevel > 0 and any existing system flags are set.
 		 */
 		if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
-			if (ip->i_flags
-			    & (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
+			if (ip->i_flags & (SF_IMMUTABLE | SF_APPEND)) {
 				error =3D securelevel_gt(cred, 0);
 				if (error)
 					return (error);
 			}
-			ip->i_flags =3D vap->va_flags;
 		} else {
-			if (ip->i_flags
-			    & (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
-			    (vap->va_flags & UF_SETTABLE) !=3D vap->va_flags)
+			if (ip->i_flags & (SF_IMMUTABLE | SF_APPEND) ||
+			    ((vap->va_flags ^ ip->i_flags) & SF_SETTABLE))
 				return (EPERM);
-			ip->i_flags &=3D SF_SETTABLE;
-			ip->i_flags |=3D (vap->va_flags & UF_SETTABLE);
 		}
+		ip->i_flags =3D vap->va_flags;
 		ip->i_flag |=3D IN_CHANGE;
-		if (vap->va_flags & (IMMUTABLE | APPEND))
+		if (ip->i_flags & (IMMUTABLE | APPEND))
 			return (0);
 	}
 	if (ip->i_flags & (IMMUTABLE | APPEND))
diff -r 428842767fa6 -r f2935497fa04 head/sys/fs/msdosfs/msdosfs_vfsops.c
--- a/head/sys/fs/msdosfs/msdosfs_vfsops.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/fs/msdosfs/msdosfs_vfsops.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/fs/msdosfs/msdosfs_vfsops.c 232483 2012-03-04 09:38:=
20Z kevlo $ */
+/* $FreeBSD: head/sys/fs/msdosfs/msdosfs_vfsops.c 234025 2012-04-08 06:18:=
18Z mckusick $ */
 /*	$NetBSD: msdosfs_vfsops.c,v 1.51 1997/11/17 15:36:58 ws Exp $	*/
=20
 /*-
@@ -401,6 +401,8 @@
 		return error;
 	}
=20
+	if (devvp->v_type =3D=3D VCHR && devvp->v_rdev !=3D NULL)
+		devvp->v_rdev->si_mountpt =3D mp;
 	vfs_mountedfrom(mp, from);
 #ifdef MSDOSFS_DEBUG
 	printf("msdosfs_mount(): mp %p, pmp %p, inusemap %p\n", mp, pmp, pmp->pm_=
inusemap);
@@ -843,6 +845,8 @@
 	}
 #endif
 	DROP_GIANT();
+	if (pmp->pm_devvp->v_type =3D=3D VCHR && pmp->pm_devvp->v_rdev !=3D NULL)
+		pmp->pm_devvp->v_rdev->si_mountpt =3D NULL;
 	g_topology_lock();
 	g_vfs_close(pmp->pm_cp);
 	g_topology_unlock();
diff -r 428842767fa6 -r f2935497fa04 head/sys/fs/tmpfs/tmpfs.h
--- a/head/sys/fs/tmpfs/tmpfs.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/fs/tmpfs/tmpfs.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF =
THE
  * POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/fs/tmpfs/tmpfs.h 230180 2012-01-16 00:26:49Z alc $
+ * $FreeBSD: head/sys/fs/tmpfs/tmpfs.h 234346 2012-04-16 18:07:42Z jh $
  */
=20
 #ifndef _FS_TMPFS_TMPFS_H_
@@ -337,11 +337,10 @@
 	 * system, set during mount time.  This variable must never be
 	 * used directly as it may be bigger than the current amount of
 	 * free memory; in the extreme case, it will hold the SIZE_MAX
-	 * value.  Instead, use the TMPFS_PAGES_MAX macro. */
+	 * value. */
 	size_t			tm_pages_max;
=20
-	/* Number of pages in use by the file system.  Cannot be bigger
-	 * than the value returned by TMPFS_PAGES_MAX in any case. */
+	/* Number of pages in use by the file system. */
 	size_t			tm_pages_used;
=20
 	/* Pointer to the node representing the root directory of this
@@ -388,6 +387,9 @@
 	 * tmpfs_pool.c. */
 	uma_zone_t		tm_dirent_pool;
 	uma_zone_t		tm_node_pool;
+
+	/* Read-only status. */
+	int			tm_ronly;
 };
 #define TMPFS_LOCK(tm) mtx_lock(&(tm)->allnode_lock)
 #define TMPFS_UNLOCK(tm) mtx_unlock(&(tm)->allnode_lock)
@@ -486,57 +488,15 @@
  * Memory management stuff.
  */
=20
-/* Amount of memory pages to reserve for the system (e.g., to not use by
+/*
+ * Amount of memory pages to reserve for the system (e.g., to not use by
  * tmpfs).
- * XXX: Should this be tunable through sysctl, for instance? */
-#define TMPFS_PAGES_RESERVED (4 * 1024 * 1024 / PAGE_SIZE)
+ */
+#define TMPFS_PAGES_MINRESERVED		(4 * 1024 * 1024 / PAGE_SIZE)
=20
-/*
- * Returns information about the number of available memory pages,
- * including physical and virtual ones.
- *
- * Remember to remove TMPFS_PAGES_RESERVED from the returned value to avoid
- * excessive memory usage.
- *
- */
-static __inline size_t
-tmpfs_mem_info(void)
-{
+size_t tmpfs_mem_avail(void);
=20
-	return (swap_pager_avail + cnt.v_free_count + cnt.v_cache_count);
-}
-
-/* Returns the maximum size allowed for a tmpfs file system.  This macro
- * must be used instead of directly retrieving the value from tm_pages_max.
- * The reason is that the size of a tmpfs file system is dynamic: it lets
- * the user store files as long as there is enough free memory (including
- * physical memory and swap space).  Therefore, the amount of memory to be
- * used is either the limit imposed by the user during mount time or the
- * amount of available memory, whichever is lower.  To avoid consuming all
- * the memory for a given mount point, the system will always reserve a
- * minimum of TMPFS_PAGES_RESERVED pages, which is also taken into account
- * by this macro (see above). */
-static __inline size_t
-TMPFS_PAGES_MAX(struct tmpfs_mount *tmp)
-{
-	size_t freepages;
-
-	freepages =3D tmpfs_mem_info();
-	freepages -=3D freepages < TMPFS_PAGES_RESERVED ?
-	    freepages : TMPFS_PAGES_RESERVED;
-
-	return MIN(tmp->tm_pages_max, freepages + tmp->tm_pages_used);
-}
-
-/* Returns the available space for the given file system. */
-#define TMPFS_META_PAGES(tmp) (howmany((tmp)->tm_nodes_inuse * (sizeof(str=
uct tmpfs_node) \
-				+ sizeof(struct tmpfs_dirent)), PAGE_SIZE))
-#define TMPFS_FILE_PAGES(tmp) ((tmp)->tm_pages_used)
-
-#define TMPFS_PAGES_AVAIL(tmp) (TMPFS_PAGES_MAX(tmp) > \
-			TMPFS_META_PAGES(tmp)+TMPFS_FILE_PAGES(tmp)? \
-			TMPFS_PAGES_MAX(tmp) - TMPFS_META_PAGES(tmp) \
-			- TMPFS_FILE_PAGES(tmp):0)
+size_t tmpfs_pages_used(struct tmpfs_mount *tmp);
=20
 #endif
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/fs/tmpfs/tmpfs_subr.c
--- a/head/sys/fs/tmpfs/tmpfs_subr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/fs/tmpfs/tmpfs_subr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  * Efficient memory file system supporting functions.
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/fs/tmpfs/tmpfs_subr.c 232960 2012-03-14 09:15=
:50Z gleb $");
+__FBSDID("$FreeBSD: head/sys/fs/tmpfs/tmpfs_subr.c 234347 2012-04-16 18:10=
:34Z jh $");
=20
 #include <sys/param.h>
 #include <sys/namei.h>
@@ -59,6 +59,70 @@
=20
 SYSCTL_NODE(_vfs, OID_AUTO, tmpfs, CTLFLAG_RW, 0, "tmpfs file system");
=20
+static long tmpfs_pages_reserved =3D TMPFS_PAGES_MINRESERVED;
+
+static int
+sysctl_mem_reserved(SYSCTL_HANDLER_ARGS)
+{
+	int error;
+	long pages, bytes;
+
+	pages =3D *(long *)arg1;
+	bytes =3D pages * PAGE_SIZE;
+
+	error =3D sysctl_handle_long(oidp, &bytes, 0, req);
+	if (error || !req->newptr)
+		return (error);
+
+	pages =3D bytes / PAGE_SIZE;
+	if (pages < TMPFS_PAGES_MINRESERVED)
+		return (EINVAL);
+
+	*(long *)arg1 =3D pages;
+	return (0);
+}
+
+SYSCTL_PROC(_vfs_tmpfs, OID_AUTO, memory_reserved, CTLTYPE_LONG|CTLFLAG_RW,
+    &tmpfs_pages_reserved, 0, sysctl_mem_reserved, "L",
+    "Amount of available memory and swap below which tmpfs growth stops");
+
+size_t
+tmpfs_mem_avail(void)
+{
+	vm_ooffset_t avail;
+
+	avail =3D swap_pager_avail + cnt.v_free_count + cnt.v_cache_count -
+	    tmpfs_pages_reserved;
+	if (__predict_false(avail < 0))
+		avail =3D 0;
+	return (avail);
+}
+
+size_t
+tmpfs_pages_used(struct tmpfs_mount *tmp)
+{
+	const size_t node_size =3D sizeof(struct tmpfs_node) +
+	    sizeof(struct tmpfs_dirent);
+	size_t meta_pages;
+
+	meta_pages =3D howmany((uintmax_t)tmp->tm_nodes_inuse * node_size,
+	    PAGE_SIZE);
+	return (meta_pages + tmp->tm_pages_used);
+}
+
+static size_t
+tmpfs_pages_check_avail(struct tmpfs_mount *tmp, size_t req_pages)
+{
+	if (tmpfs_mem_avail() < req_pages)
+		return (0);
+
+	if (tmp->tm_pages_max !=3D SIZE_MAX &&
+	    tmp->tm_pages_max < req_pages + tmpfs_pages_used(tmp))
+			return (0);
+
+	return (1);
+}
+
 /* --------------------------------------------------------------------- */
=20
 /*
@@ -99,6 +163,8 @@
=20
 	if (tmp->tm_nodes_inuse >=3D tmp->tm_nodes_max)
 		return (ENOSPC);
+	if (tmpfs_pages_check_avail(tmp, 1) =3D=3D 0)
+		return (ENOSPC);
=20
 	nnode =3D (struct tmpfs_node *)uma_zalloc_arg(
 				tmp->tm_node_pool, tmp, M_WAITOK);
@@ -917,7 +983,7 @@
 	MPASS(oldpages =3D=3D uobj->size);
 	newpages =3D OFF_TO_IDX(newsize + PAGE_MASK);
 	if (newpages > oldpages &&
-	    newpages - oldpages > TMPFS_PAGES_AVAIL(tmp))
+	    tmpfs_pages_check_avail(tmp, newpages - oldpages) =3D=3D 0)
 		return (ENOSPC);
=20
 	VM_OBJECT_LOCK(uobj);
@@ -1012,6 +1078,11 @@
=20
 	node =3D VP_TO_TMPFS_NODE(vp);
=20
+	if ((flags & ~(UF_NODUMP | UF_IMMUTABLE | UF_APPEND | UF_OPAQUE |
+	    UF_NOUNLINK | SF_ARCHIVED | SF_IMMUTABLE | SF_APPEND |
+	    SF_NOUNLINK | SF_SNAPSHOT)) !=3D 0)
+		return (EOPNOTSUPP);
+
 	/* Disallow this operation if the file system is mounted read-only. */
 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
 		return EROFS;
@@ -1027,27 +1098,22 @@
 	 * flags, or modify flags if any system flags are set.
 	 */
 	if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
-		if (node->tn_flags
-		  & (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
+		if (node->tn_flags &
+		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
 			error =3D securelevel_gt(cred, 0);
 			if (error)
 				return (error);
 		}
-		/* Snapshot flag cannot be set or cleared */
-		if (((flags & SF_SNAPSHOT) !=3D 0 &&
-		  (node->tn_flags & SF_SNAPSHOT) =3D=3D 0) ||
-		  ((flags & SF_SNAPSHOT) =3D=3D 0 &&
-		  (node->tn_flags & SF_SNAPSHOT) !=3D 0))
+		/* The snapshot flag cannot be toggled. */
+		if ((flags ^ node->tn_flags) & SF_SNAPSHOT)
 			return (EPERM);
-		node->tn_flags =3D flags;
 	} else {
-		if (node->tn_flags
-		  & (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
-		  (flags & UF_SETTABLE) !=3D flags)
+		if (node->tn_flags &
+		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
+		    ((flags ^ node->tn_flags) & SF_SETTABLE))
 			return (EPERM);
-		node->tn_flags &=3D SF_SETTABLE;
-		node->tn_flags |=3D (flags & UF_SETTABLE);
 	}
+	node->tn_flags =3D flags;
 	node->tn_status |=3D TMPFS_NODE_CHANGED;
=20
 	MPASS(VOP_ISLOCKED(vp));
diff -r 428842767fa6 -r f2935497fa04 head/sys/fs/tmpfs/tmpfs_vfsops.c
--- a/head/sys/fs/tmpfs/tmpfs_vfsops.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/fs/tmpfs/tmpfs_vfsops.c	Tue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
  * allocate and release resources.
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/fs/tmpfs/tmpfs_vfsops.c 230252 2012-01-17 01:=
25:53Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/fs/tmpfs/tmpfs_vfsops.c 234346 2012-04-16 18:=
07:42Z jh $");
=20
 #include <sys/param.h>
 #include <sys/limits.h>
@@ -82,6 +82,10 @@
 	NULL
 };
=20
+static const char *tmpfs_updateopts[] =3D {
+	"from", "export", NULL
+};
+
 /* --------------------------------------------------------------------- */
=20
 static int
@@ -130,14 +134,14 @@
 static int
 tmpfs_mount(struct mount *mp)
 {
+	const size_t nodes_per_page =3D howmany(PAGE_SIZE,
+	    sizeof(struct tmpfs_dirent) + sizeof(struct tmpfs_node));
 	struct tmpfs_mount *tmp;
 	struct tmpfs_node *root;
-	size_t pages;
-	uint32_t nodes;
 	int error;
 	/* Size counters. */
-	u_int nodes_max;
-	u_quad_t size_max, maxfilesize;
+	u_quad_t pages;
+	off_t nodes_max, size_max, maxfilesize;
=20
 	/* Root node attributes. */
 	uid_t root_uid;
@@ -150,12 +154,13 @@
 		return (EINVAL);
=20
 	if (mp->mnt_flag & MNT_UPDATE) {
-		/*
-		 * Only support update mounts for NFS export.
-		 */
-		if (vfs_flagopt(mp->mnt_optnew, "export", NULL, 0))
-			return (0);
-		return (EOPNOTSUPP);
+		/* Only support update mounts for certain options. */
+		if (vfs_filteropt(mp->mnt_optnew, tmpfs_updateopts) !=3D 0)
+			return (EOPNOTSUPP);
+		if (vfs_flagopt(mp->mnt_optnew, "ro", NULL, 0) !=3D
+		    ((struct tmpfs_mount *)mp->mnt_data)->tm_ronly)
+			return (EOPNOTSUPP);
+		return (0);
 	}
=20
 	vn_lock(mp->mnt_vnodecovered, LK_SHARED | LK_RETRY);
@@ -173,46 +178,47 @@
 	if (mp->mnt_cred->cr_ruid !=3D 0 ||
 	    vfs_scanopt(mp->mnt_optnew, "mode", "%ho", &root_mode) !=3D 1)
 		root_mode =3D va.va_mode;
-	if (vfs_scanopt(mp->mnt_optnew, "inodes", "%u", &nodes_max) !=3D 1)
+	if (vfs_getopt_size(mp->mnt_optnew, "inodes", &nodes_max) !=3D 0)
 		nodes_max =3D 0;
-	if (vfs_scanopt(mp->mnt_optnew, "size", "%qu", &size_max) !=3D 1)
+	if (vfs_getopt_size(mp->mnt_optnew, "size", &size_max) !=3D 0)
 		size_max =3D 0;
-	if (vfs_scanopt(mp->mnt_optnew, "maxfilesize", "%qu",
-	    &maxfilesize) !=3D 1)
+	if (vfs_getopt_size(mp->mnt_optnew, "maxfilesize", &maxfilesize) !=3D 0)
 		maxfilesize =3D 0;
=20
 	/* Do not allow mounts if we do not have enough memory to preserve
 	 * the minimum reserved pages. */
-	if (tmpfs_mem_info() < TMPFS_PAGES_RESERVED)
+	if (tmpfs_mem_avail() < TMPFS_PAGES_MINRESERVED)
 		return ENOSPC;
=20
 	/* Get the maximum number of memory pages this file system is
 	 * allowed to use, based on the maximum size the user passed in
 	 * the mount structure.  A value of zero is treated as if the
 	 * maximum available space was requested. */
-	if (size_max < PAGE_SIZE || size_max > SIZE_MAX - PAGE_SIZE)
+	if (size_max < PAGE_SIZE || size_max > OFF_MAX - PAGE_SIZE ||
+	    (SIZE_MAX < OFF_MAX && size_max / PAGE_SIZE >=3D SIZE_MAX))
 		pages =3D SIZE_MAX;
 	else
 		pages =3D howmany(size_max, PAGE_SIZE);
 	MPASS(pages > 0);
=20
 	if (nodes_max <=3D 3) {
-		if (pages > UINT32_MAX - 3)
-			nodes =3D UINT32_MAX;
+		if (pages < INT_MAX / nodes_per_page)
+			nodes_max =3D pages * nodes_per_page;
 		else
-			nodes =3D pages + 3;
-	} else
-		nodes =3D nodes_max;
-	MPASS(nodes >=3D 3);
+			nodes_max =3D INT_MAX;
+	}
+	if (nodes_max > INT_MAX)
+		nodes_max =3D INT_MAX;
+	MPASS(nodes_max >=3D 3);
=20
 	/* Allocate the tmpfs mount structure and fill it. */
 	tmp =3D (struct tmpfs_mount *)malloc(sizeof(struct tmpfs_mount),
 	    M_TMPFSMNT, M_WAITOK | M_ZERO);
=20
 	mtx_init(&tmp->allnode_lock, "tmpfs allnode lock", NULL, MTX_DEF);
-	tmp->tm_nodes_max =3D nodes;
+	tmp->tm_nodes_max =3D nodes_max;
 	tmp->tm_nodes_inuse =3D 0;
-	tmp->tm_maxfilesize =3D maxfilesize > 0 ? maxfilesize : UINT64_MAX;
+	tmp->tm_maxfilesize =3D maxfilesize > 0 ? maxfilesize : OFF_MAX;
 	LIST_INIT(&tmp->tm_nodes_used);
=20
 	tmp->tm_pages_max =3D pages;
@@ -227,6 +233,7 @@
 	    tmpfs_node_ctor, tmpfs_node_dtor,
 	    tmpfs_node_init, tmpfs_node_fini,
 	    UMA_ALIGN_PTR, 0);
+	tmp->tm_ronly =3D (mp->mnt_flag & MNT_RDONLY) !=3D 0;
=20
 	/* Allocate the root node. */
 	error =3D tmpfs_alloc_node(tmp, VDIR, root_uid,
@@ -382,22 +389,30 @@
 static int
 tmpfs_statfs(struct mount *mp, struct statfs *sbp)
 {
-	fsfilcnt_t freenodes;
 	struct tmpfs_mount *tmp;
+	size_t used;
=20
 	tmp =3D VFS_TO_TMPFS(mp);
=20
 	sbp->f_iosize =3D PAGE_SIZE;
 	sbp->f_bsize =3D PAGE_SIZE;
=20
-	sbp->f_blocks =3D TMPFS_PAGES_MAX(tmp);
-	sbp->f_bavail =3D sbp->f_bfree =3D TMPFS_PAGES_AVAIL(tmp);
-
-	freenodes =3D MIN(tmp->tm_nodes_max - tmp->tm_nodes_inuse,
-	    TMPFS_PAGES_AVAIL(tmp) * PAGE_SIZE / sizeof(struct tmpfs_node));
-
-	sbp->f_files =3D freenodes + tmp->tm_nodes_inuse;
-	sbp->f_ffree =3D freenodes;
+	used =3D tmpfs_pages_used(tmp);
+	if (tmp->tm_pages_max !=3D SIZE_MAX)
+		 sbp->f_blocks =3D tmp->tm_pages_max;
+	else
+		 sbp->f_blocks =3D used + tmpfs_mem_avail();
+	if (sbp->f_blocks <=3D used)
+		sbp->f_bavail =3D 0;
+	else
+		sbp->f_bavail =3D sbp->f_blocks - used;
+	sbp->f_bfree =3D sbp->f_bavail;
+	used =3D tmp->tm_nodes_inuse;
+	sbp->f_files =3D tmp->tm_nodes_max;
+	if (sbp->f_files <=3D used)
+		sbp->f_ffree =3D 0;
+	else
+		sbp->f_ffree =3D sbp->f_files - used;
 	/* sbp->f_owner =3D tmp->tn_uid; */
=20
 	return 0;
diff -r 428842767fa6 -r f2935497fa04 head/sys/fs/tmpfs/tmpfs_vnops.c
--- a/head/sys/fs/tmpfs/tmpfs_vnops.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/fs/tmpfs/tmpfs_vnops.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  * tmpfs vnode interface.
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/fs/tmpfs/tmpfs_vnops.c 232960 2012-03-14 09:1=
5:50Z gleb $");
+__FBSDID("$FreeBSD: head/sys/fs/tmpfs/tmpfs_vnops.c 234064 2012-04-09 17:0=
5:18Z attilio $");
=20
 #include <sys/param.h>
 #include <sys/fcntl.h>
@@ -662,7 +662,7 @@
 		VM_OBJECT_UNLOCK(vobj);
 		error =3D uiomove_fromphys(&vpg, offset, tlen, uio);
 	} else {
-		if (__predict_false(vobj->cache !=3D NULL))
+		if (vm_page_is_cached(vobj, idx))
 			vm_page_cache_free(vobj, idx, idx + 1);
 		VM_OBJECT_UNLOCK(vobj);
 		vpg =3D NULL;
diff -r 428842767fa6 -r f2935497fa04 head/sys/gdb/gdb_main.c
--- a/head/sys/gdb/gdb_main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/gdb/gdb_main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/gdb/gdb_main.c 234196 2012-04-12 21:34:58Z jh=
b $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -44,7 +44,7 @@
 static dbbe_init_f gdb_init;
 static dbbe_trap_f gdb_trap;
=20
-KDB_BACKEND(gdb, gdb_init, NULL, gdb_trap);
+KDB_BACKEND(gdb, gdb_init, NULL, NULL, gdb_trap);
=20
 static struct gdb_dbgport null_gdb_dbgport;
 DATA_SET(gdb_dbgport_set, null_gdb_dbgport);
diff -r 428842767fa6 -r f2935497fa04 head/sys/geom/geom_vfs.c
--- a/head/sys/geom/geom_vfs.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/geom/geom_vfs.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/geom/geom_vfs.c 228204 2011-12-02 17:09:48Z m=
av $");
+__FBSDID("$FreeBSD: head/sys/geom/geom_vfs.c 234026 2012-04-08 06:20:21Z m=
ckusick $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -95,6 +95,48 @@
 	struct g_vfs_softc *sc;
 	struct buf *bp;
 	int vfslocked, destroy;
+	struct mount *mp;
+	struct vnode *vp;
+	struct cdev *cdevp;
+
+	/*
+	 * Collect statistics on synchronous and asynchronous read
+	 * and write counts for disks that have associated filesystems.
+	 * Since this run by the g_up thread it is single threaded and
+	 * we do not need to use atomic increments on the counters.
+	 */
+	bp =3D bip->bio_caller2;
+	vp =3D bp->b_vp;
+	if (vp =3D=3D NULL) {
+		mp =3D NULL;
+	} else {
+		/*
+		 * If not a disk vnode, use its associated mount point
+		 * otherwise use the mountpoint associated with the disk.
+		 */
+		VI_LOCK(vp);
+		if (vp->v_type !=3D VCHR ||
+		    (cdevp =3D vp->v_rdev) =3D=3D NULL ||
+		    cdevp->si_devsw =3D=3D NULL ||
+		    (cdevp->si_devsw->d_flags & D_DISK) =3D=3D 0)
+			mp =3D vp->v_mount;
+		else
+			mp =3D cdevp->si_mountpt;
+		VI_UNLOCK(vp);
+	}
+	if (mp !=3D NULL) {
+		if (bp->b_iocmd =3D=3D BIO_WRITE) {
+			if (LK_HOLDER(bp->b_lock.lk_lock) =3D=3D LK_KERNPROC)
+				mp->mnt_stat.f_asyncwrites++;
+			else
+				mp->mnt_stat.f_syncwrites++;
+		} else {
+			if (LK_HOLDER(bp->b_lock.lk_lock) =3D=3D LK_KERNPROC)
+				mp->mnt_stat.f_asyncreads++;
+			else
+				mp->mnt_stat.f_syncreads++;
+		}
+	}
=20
 	cp =3D bip->bio_from;
 	sc =3D cp->geom->softc;
@@ -103,7 +145,6 @@
 		g_print_bio(bip);
 		printf("error =3D %d\n", bip->bio_error);
 	}
-	bp =3D bip->bio_caller2;
 	bp->b_error =3D bip->bio_error;
 	bp->b_ioflags =3D bip->bio_flags;
 	if (bip->bio_error)
diff -r 428842767fa6 -r f2935497fa04 head/sys/geom/part/g_part.c
--- a/head/sys/geom/part/g_part.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/geom/part/g_part.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/geom/part/g_part.c 233175 2012-03-19 12:57:52=
Z ae $");
+__FBSDID("$FreeBSD: head/sys/geom/part/g_part.c 233342 2012-03-23 07:26:17=
Z ae $");
=20
 #include <sys/param.h>
 #include <sys/bio.h>
@@ -2211,23 +2211,32 @@
 int
 g_part_modevent(module_t mod, int type, struct g_part_scheme *scheme)
 {
+	struct g_part_scheme *iter;
 	uintptr_t arg;
 	int error;
=20
+	error =3D 0;
 	switch (type) {
 	case MOD_LOAD:
-		TAILQ_INSERT_TAIL(&g_part_schemes, scheme, scheme_list);
-
-		error =3D g_retaste(&g_part_class);
-		if (error)
-			TAILQ_REMOVE(&g_part_schemes, scheme, scheme_list);
+		TAILQ_FOREACH(iter, &g_part_schemes, scheme_list) {
+			if (scheme =3D=3D iter) {
+				printf("GEOM_PART: scheme %s is already "
+				    "registered!\n", scheme->name);
+				break;
+			}
+		}
+		if (iter =3D=3D NULL) {
+			TAILQ_INSERT_TAIL(&g_part_schemes, scheme,
+			    scheme_list);
+			g_retaste(&g_part_class);
+		}
 		break;
 	case MOD_UNLOAD:
 		arg =3D (uintptr_t)scheme;
 		error =3D g_waitfor_event(g_part_unload_event, &arg, M_WAITOK,
 		    NULL);
-		if (!error)
-			error =3D (arg =3D=3D (uintptr_t)scheme) ? EDOOFUS : arg;
+		if (error =3D=3D 0)
+			error =3D arg;
 		break;
 	default:
 		error =3D EOPNOTSUPP;
diff -r 428842767fa6 -r f2935497fa04 head/sys/geom/part/g_part_ldm.c
--- a/head/sys/geom/part/g_part_ldm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/geom/part/g_part_ldm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/geom/part/g_part_ldm.c 233181 2012-03-19 13:2=
1:10Z ae $");
+__FBSDID("$FreeBSD: head/sys/geom/part/g_part_ldm.c 233652 2012-03-29 07:2=
9:27Z ae $");
=20
 #include <sys/param.h>
 #include <sys/bio.h>
@@ -495,7 +495,7 @@
 		g_free(buf);
 		if (hdr.start > last ||
 		    hdr.start + hdr.size - 1 > last ||
-		    (hdr.start + hdr.size - 1 > hdr.db_offset && is_gpt) ||
+		    (hdr.start + hdr.size - 1 > hdr.db_offset && !is_gpt) ||
 		    hdr.db_size !=3D LDM_DB_SIZE ||
 		    hdr.db_offset + LDM_DB_SIZE - 1 > last ||
 		    hdr.th_offset[0] >=3D LDM_DB_SIZE ||
@@ -1371,14 +1371,15 @@
 	/* Read and parse LDM private headers. */
 	error =3D ldm_privhdr_check(&db, cp, table->is_gpt);
 	if (error !=3D 0)
-		return (error);
+		goto gpt_cleanup;
 	basetable->gpt_first =3D table->is_gpt ? 0: db.ph.start;
 	basetable->gpt_last =3D basetable->gpt_first + db.ph.size - 1;
 	table->db_offset =3D db.ph.db_offset;
 	/* Make additional checks for GPT */
 	if (table->is_gpt) {
-		if (ldm_gpt_check(&db, cp) !=3D 0)
-			return (ENXIO);
+		error =3D ldm_gpt_check(&db, cp);
+		if (error !=3D 0)
+			goto gpt_cleanup;
 		/*
 		 * Now we should reset database offset to zero, because our
 		 * consumer cp is attached to the ms-ldm-metadata partition
@@ -1389,12 +1390,25 @@
 	/* Read and parse LDM TOC headers. */
 	error =3D ldm_tochdr_check(&db, cp);
 	if (error !=3D 0)
-		return (error);
+		goto gpt_cleanup;
 	/* Read and parse LDM VMDB header. */
 	error =3D ldm_vmdbhdr_check(&db, cp);
 	if (error !=3D 0)
-		return (error);
+		goto gpt_cleanup;
 	error =3D ldm_vmdb_parse(&db, cp);
+	/*
+	 * For the GPT case we must detach and destroy
+	 * second consumer before return.
+	 */
+gpt_cleanup:
+	if (table->is_gpt) {
+		g_topology_lock();
+		g_access(cp, -1, 0, 0);
+		g_detach(cp);
+		g_destroy_consumer(cp);
+		g_topology_unlock();
+		cp =3D cp2;
+	}
 	if (error !=3D 0)
 		return (error);
 	/* Search current disk in the disk list. */
@@ -1408,15 +1422,6 @@
 		ldm_vmdb_free(&db);
 		return (ENXIO);
 	}
-	if (table->is_gpt) {
-		/* Second consumer is no longer needed. */
-		g_topology_lock();
-		g_access(cp, -1, 0, 0);
-		g_detach(cp);
-		g_destroy_consumer(cp);
-		g_topology_unlock();
-		cp =3D cp2;
-	}
 	index =3D 1;
 	LIST_FOREACH(vol, &db.volumes, entry) {
 		LIST_FOREACH(comp, &vol->components, entry) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/gnu/fs/reiserfs/reiserfs_vfso=
ps.c
--- a/head/sys/gnu/fs/reiserfs/reiserfs_vfsops.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/sys/gnu/fs/reiserfs/reiserfs_vfsops.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -4,7 +4,7 @@
  *=20
  * Ported to FreeBSD by Jean-S=C3=A9bastien P=C3=A9dron <jspedron at club-int=
ernet.fr>
  *=20
- * $FreeBSD: head/sys/gnu/fs/reiserfs/reiserfs_vfsops.c 230249 2012-01-17 =
01:08:01Z mckusick $
+ * $FreeBSD: head/sys/gnu/fs/reiserfs/reiserfs_vfsops.c 233575 2012-03-27 =
20:36:03Z dumbbell $
  */
=20
 #include <gnu/fs/reiserfs/reiserfs_fs.h>
@@ -231,6 +231,7 @@
 	g_topology_unlock();
 	PICKUP_GIANT();
 	vrele(rmp->rm_devvp);
+	dev_rel(rmp->rm_dev);
=20
 	if (sbi) {
 		reiserfs_log(LOG_DEBUG, "free sbi\n");
@@ -430,21 +431,25 @@
 	struct reiserfs_mount *rmp;
 	struct reiserfs_sb_info *sbi;
 	struct reiserfs_super_block *rs;
-	struct cdev *dev =3D devvp->v_rdev;
+	struct cdev *dev;
=20
 	struct g_consumer *cp;
 	struct bufobj *bo;
=20
 	//ronly =3D (mp->mnt_flag & MNT_RDONLY) !=3D 0;
=20
+	dev =3D devvp->v_rdev;
+	dev_ref(dev);
 	DROP_GIANT();
 	g_topology_lock();
 	error =3D g_vfs_open(devvp, &cp, "reiserfs", /* read-only */ 0);
 	g_topology_unlock();
 	PICKUP_GIANT();
 	VOP_UNLOCK(devvp, 0);
-	if (error)
+	if (error) {
+		dev_rel(dev);
 		return (error);
+	}
=20
 	bo =3D &devvp->v_bufobj;
 	bo->bo_private =3D cp;
@@ -575,6 +580,7 @@
 	mp->mnt_stat.f_fsid.val[1] =3D mp->mnt_vfc->vfc_typenum;
 	MNT_ILOCK(mp);
 	mp->mnt_flag |=3D MNT_LOCAL;
+	mp->mnt_kern_flag |=3D MNTK_MPSAFE;
 	MNT_IUNLOCK(mp);
 #if defined(si_mountpoint)
 	devvp->v_rdev->si_mountpoint =3D mp;
@@ -590,7 +596,8 @@
 			for (i =3D 0; i < SB_BMAP_NR(sbi); i++) {
 				if (!SB_AP_BITMAP(sbi)[i].bp_data)
 					break;
-				free(SB_AP_BITMAP(sbi)[i].bp_data, M_REISERFSMNT);
+				free(SB_AP_BITMAP(sbi)[i].bp_data,
+				    M_REISERFSMNT);
 			}
 			free(SB_AP_BITMAP(sbi), M_REISERFSMNT);
 		}
@@ -613,6 +620,7 @@
 		free(sbi, M_REISERFSMNT);
 	if (rmp)
 		free(rmp, M_REISERFSMNT);
+	dev_rel(dev);
 	return (error);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/acpica/acpi_wakeup.c
--- a/head/sys/i386/acpica/acpi_wakeup.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/acpica/acpi_wakeup.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/acpica/acpi_wakeup.c 232742 2012-03-09 1=
9:20:19Z jhb $");
+__FBSDID("$FreeBSD: head/sys/i386/acpica/acpi_wakeup.c 233250 2012-03-20 2=
1:37:52Z jkim $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -262,7 +262,7 @@
 		if (state =3D=3D ACPI_STATE_S4 && sc->acpi_s4bios)
 			status =3D AcpiEnterSleepStateS4bios();
 		else
-			status =3D AcpiEnterSleepState(state);
+			status =3D AcpiEnterSleepState(state, acpi_sleep_flags);
=20
 		if (status !=3D AE_OK) {
 			device_printf(sc->acpi_dev,
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/conf/GENERIC
--- a/head/sys/i386/conf/GENERIC	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/conf/GENERIC	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check first
 # in NOTES.
 #
-# $FreeBSD: head/sys/i386/conf/GENERIC 232561 2012-03-05 18:47:42Z jkim $
+# $FreeBSD: head/sys/i386/conf/GENERIC 233427 2012-03-24 18:08:28Z marius $
=20
 cpu		I486_CPU
 cpu		I586_CPU
@@ -228,9 +228,12 @@
 device		bce		# Broadcom BCM5706/BCM5708 Gigabit Ethernet
 device		bfe		# Broadcom BCM440x 10/100 Ethernet
 device		bge		# Broadcom BCM570xx Gigabit Ethernet
+device		cas		# Sun Cassini/Cassini+ and NS DP83065 Saturn
 device		dc		# DEC/Intel 21143 and various workalikes
 device		et		# Agere ET1310 10/100/Gigabit Ethernet
 device		fxp		# Intel EtherExpress PRO/100B (82557, 82558)
+device		gem		# Sun GEM/Sun ERI/Apple GMAC
+device		hme		# Sun HME (Happy Meal Ethernet)
 device		jme		# JMicron JMC250 Gigabit/JMC260 Fast Ethernet
 device		lge		# Level 1 LXT1001 gigabit Ethernet
 device		msk		# Marvell/SysKonnect Yukon II Gigabit Ethernet
@@ -298,7 +301,6 @@
 device		ether		# Ethernet support
 device		vlan		# 802.1Q VLAN support
 device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 device		md		# Memory "disks"
 device		gif		# IPv6 and IPv4 tunneling
 device		faith		# IPv6-to-IPv4 relaying (translation)
@@ -330,6 +332,9 @@
=20
 # Sound support
 device		sound		# Generic sound driver (required)
+device		snd_cmi		# CMedia CMI8338/CMI8738
+device		snd_csa		# Crystal Semiconductor CS461x/428x
+device		snd_emu10kx	# Creative SoundBlaster Live! and Audigy
 device		snd_es137x	# Ensoniq AudioPCI ES137x
 device		snd_hda		# Intel High Definition Audio
 device		snd_ich		# Intel, NVidia and other ICH AC'97 Audio
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/conf/NOTES
--- a/head/sys/i386/conf/NOTES	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/conf/NOTES	Tue Apr 17 11:51:51 2012 +0300
@@ -4,7 +4,7 @@
 # This file contains machine dependent kernel configuration notes.  For
 # machine independent notes, look in /sys/conf/NOTES.
 #
-# $FreeBSD: head/sys/i386/conf/NOTES 232614 2012-03-06 18:44:52Z bz $
+# $FreeBSD: head/sys/i386/conf/NOTES 234183 2012-04-12 14:01:06Z jhb $
 #
=20
 #
@@ -260,6 +260,19 @@
=20
 options 	BPF_JITTER
=20
+# OpenFabrics Enterprise Distribution (Infiniband).
+options 	OFED
+options 	OFED_DEBUG_INIT
+
+# Sockets Direct Protocol
+options 	SDP
+options 	SDP_DEBUG
+
+# IP over Inifiband
+options 	IPOIB
+options 	IPOIB_DEBUG
+options 	IPOIB_CM
+
 =0C
 #####################################################################
 # CLOCK OPTIONS
@@ -561,6 +574,9 @@
 #	Requires the iwi firmware module
 # iwn:	Intel Wireless WiFi Link 4965AGN 802.11 network adapters
 #	Requires the iwn firmware module
+# mlx4ib: Mellanox ConnectX HCA InfiniBand
+# mlxen: Mellanox ConnectX HCA Ethernet
+# mthca: Mellanox HCA InfiniBand
 # mwl:	Marvell 88W8363 IEEE 802.11 adapter
 #	Requires the mwl firmware module
 # nfe:	nVidia nForce MCP on-board Ethernet Networking (BSD open source)
@@ -574,7 +590,7 @@
=20
 device		ce
 device		cp
-device		cs
+device		cs		# Crystal Semiconductor CS89x0 NIC
 hint.cs.0.at=3D"isa"
 hint.cs.0.port=3D"0x300"
 device		ctau
@@ -583,7 +599,7 @@
 hint.ctau.0.irq=3D"15"
 hint.ctau.0.drq=3D"7"
 #options 	NETGRAPH_CRONYX		# Enable NETGRAPH support for Cronyx adapter(s)
-device		ed
+device		ed		# NE[12]000, SMC Ultra, 3c503, DS8390 cards
 options 	ED_3C503
 options 	ED_HPP
 options 	ED_SIC
@@ -591,21 +607,25 @@
 hint.ed.0.port=3D"0x280"
 hint.ed.0.irq=3D"5"
 hint.ed.0.maddr=3D"0xd8000"
-device		ie			# Hints only required for Starlan
+device		ie		# EtherExpress 8/16, 3C507, StarLAN 10 etc.
+# Hints only required for Starlan
 hint.ie.2.at=3D"isa"
 hint.ie.2.port=3D"0x300"
 hint.ie.2.irq=3D"5"
 hint.ie.2.maddr=3D"0xd0000"
-device		ipw
-device		iwi
-device		iwn
+device		ipw		# Intel 2100 wireless NICs.
+device		iwi		# Intel 2200BG/2225BG/2915ABG wireless NICs.
+device		iwn		# Intel 4965/1000/5000/6000 wireless NICs.
 # Hint for the i386-only ISA front-end of le(4).
 hint.le.0.at=3D"isa"
 hint.le.0.port=3D"0x280"
 hint.le.0.irq=3D"10"
 hint.le.0.drq=3D"0"
-device		mwl
-device		nfe		# nVidia nForce MCP on-board Ethernet Networking
+device  	mlx4ib		# Mellanox ConnectX HCA InfiniBand
+device  	mlxen		# Mellanox ConnectX HCA Ethernet
+device  	mthca		# Mellanox HCA InfiniBand
+device		mwl		# Marvell 88W8363 802.11n wireless NICs.
+device		nfe		# nVidia nForce MCP on-board Ethernet
 device		nve		# nVidia nForce MCP on-board Ethernet Networking
 device		sbni
 hint.sbni.0.at=3D"isa"
@@ -617,7 +637,7 @@
 hint.wl.0.port=3D"0x300"
 options 	WLCACHE		# enables the signal-strength cache
 options 	WLDEBUG		# enables verbose debugging output
-device		wpi
+device		wpi		# Intel 3945ABG wireless NICs.
=20
 # IEEE 802.11 adapter firmware modules
=20
@@ -976,6 +996,10 @@
=20
 options 	KSTACK_PAGES=3D3
=20
+# Enable detailed accounting by the PV entry allocator.
+
+options 	PV_STATS
+
 #####################################################################
=20
 # More undocumented options for linting.
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/conf/XBOX
--- a/head/sys/i386/conf/XBOX	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/conf/XBOX	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # XBOX -- kernel for an XBOX
 #
-# $FreeBSD: head/sys/i386/conf/XBOX 232521 2012-03-04 21:31:13Z rmh $
+# $FreeBSD: head/sys/i386/conf/XBOX 233271 2012-03-21 08:38:42Z ed $
 cpu		I686_CPU		# Celeron
 ident		XBOX
=20
@@ -65,7 +65,6 @@
 device		random		# Entropy device
 device		ether		# Ethernet support
 #device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 #device		md		# Memory "disks"
 #device		gif		# IPv6 and IPv4 tunneling
 #device		faith		# IPv6-to-IPv4 relaying (translation)
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/conf/XEN
--- a/head/sys/i386/conf/XEN	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/conf/XEN	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # XEN -- Kernel configuration for i386 XEN DomU
 #
-# $FreeBSD: head/sys/i386/conf/XEN 229789 2012-01-07 19:38:26Z adrian $
+# $FreeBSD: head/sys/i386/conf/XEN 233271 2012-03-21 08:38:42Z ed $
=20
 cpu		I686_CPU
 ident		XEN
@@ -78,7 +78,6 @@
 device		random		# Entropy device
 device		ether		# Ethernet support
 device		tun		# Packet tunnel.
-device		pty		# Pseudo-ttys (telnet etc)
 device		md		# Memory "disks"
 device		gif		# IPv6 and IPv4 tunneling
 device		faith		# IPv6-to-IPv4 relaying (translation)
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/i386/identcpu.c
--- a/head/sys/i386/i386/identcpu.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/i386/identcpu.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/i386/identcpu.c 222043 2011-05-17 22:36:=
16Z jkim $");
+__FBSDID("$FreeBSD: head/sys/i386/i386/identcpu.c 234059 2012-04-09 15:20:=
16Z jhb $");
=20
 #include "opt_cpu.h"
=20
@@ -779,7 +779,7 @@
 				"\034OSXSAVE"	/* OS-Enabled State Management*/
 				"\035AVX"	/* Advanced Vector Extensions */
 				"\036F16C"	/* Half-precision conversions */
-				"\037<b30>"
+				"\037RDRAND"	/* RDRAND Instruction */
 				"\040HV"	/* Hypervisor */
 				);
 			}
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/i386/machdep.c
--- a/head/sys/i386/i386/machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/i386/machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -38,7 +38,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/i386/machdep.c 233031 2012-03-16 12:13:4=
4Z nyan $");
+__FBSDID("$FreeBSD: head/sys/i386/i386/machdep.c 234105 2012-04-10 16:08:4=
6Z marius $");
=20
 #include "opt_apic.h"
 #include "opt_atalk.h"
@@ -336,6 +336,13 @@
 #ifndef XEN
 	cpu_setregs();
 #endif
+
+#ifdef SMP
+	/*
+	 * Add BSP as an interrupt target.
+	 */
+	intr_add_cpu(0);
+#endif
 }
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/i386/mp_machdep.c
--- a/head/sys/i386/i386/mp_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/i386/mp_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/i386/mp_machdep.c 228535 2011-12-15 17:5=
4:23Z alc $");
+__FBSDID("$FreeBSD: head/sys/i386/i386/mp_machdep.c 234208 2012-04-13 07:1=
8:19Z avg $");
=20
 #include "opt_apic.h"
 #include "opt_cpu.h"
@@ -819,8 +819,6 @@
  * We tell the I/O APIC code about all the CPUs we want to receive
  * interrupts.  If we don't want certain CPUs to receive IRQs we
  * can simply not tell the I/O APIC code about them in this function.
- * We also do not tell it about the BSP since it tells itself about
- * the BSP internally to work with UP kernels and on UP machines.
  */
 static void
 set_interrupt_apic_ids(void)
@@ -831,8 +829,6 @@
 		apic_id =3D cpu_apic_ids[i];
 		if (apic_id =3D=3D -1)
 			continue;
-		if (cpu_info[apic_id].cpu_bsp)
-			continue;
 		if (cpu_info[apic_id].cpu_disabled)
 			continue;
=20
@@ -1534,6 +1530,8 @@
 		intrcnt_add(buf, &ipi_invlrng_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
 		intrcnt_add(buf, &ipi_invlpg_counts[i]);
+		snprintf(buf, sizeof(buf), "cpu%d:invlcache", i);
+		intrcnt_add(buf, &ipi_invlcache_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
 		intrcnt_add(buf, &ipi_preempt_counts[i]);
 		snprintf(buf, sizeof(buf), "cpu%d:ast", i);
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/i386/pmap.c
--- a/head/sys/i386/i386/pmap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/i386/pmap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -75,7 +75,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/i386/pmap.c 233168 2012-03-19 09:34:22Z =
kib $");
+__FBSDID("$FreeBSD: head/sys/i386/i386/pmap.c 233433 2012-03-24 19:43:49Z =
alc $");
=20
 /*
  *	Manages physical address maps.
@@ -172,7 +172,6 @@
 #define PMAP_INLINE
 #endif
=20
-#define PV_STATS
 #ifdef PV_STATS
 #define PV_STAT(x)	do { x ; } while (0)
 #else
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/i386/trap.c
--- a/head/sys/i386/i386/trap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/i386/trap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -38,7 +38,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/i386/trap.c 232851 2012-03-12 05:28:02Z =
alc $");
+__FBSDID("$FreeBSD: head/sys/i386/i386/trap.c 233781 2012-04-02 15:07:22Z =
jhb $");
=20
 /*
  * 386 Trap and System call handling
@@ -73,6 +73,9 @@
 #include <sys/vmmeter.h>
 #ifdef HWPMC_HOOKS
 #include <sys/pmckern.h>
+PMC_SOFT_DEFINE( , , page_fault, all);
+PMC_SOFT_DEFINE( , , page_fault, read);
+PMC_SOFT_DEFINE( , , page_fault, write);
 #endif
 #include <security/audit/audit.h>
=20
@@ -251,8 +254,7 @@
 #endif
=20
 	if (type =3D=3D T_MCHK) {
-		if (!mca_intr())
-			trap_fatal(frame, 0);
+		mca_intr();
 		goto out;
 	}
=20
@@ -330,28 +332,13 @@
 		 * For some Cyrix CPUs, %cr2 is clobbered by
 		 * interrupts.  This problem is worked around by using
 		 * an interrupt gate for the pagefault handler.  We
-		 * are finally ready to read %cr2 and then must
-		 * reenable interrupts.
-		 *
-		 * If we get a page fault while in a critical section, then
-		 * it is most likely a fatal kernel page fault.  The kernel
-		 * is already going to panic trying to get a sleep lock to
-		 * do the VM lookup, so just consider it a fatal trap so the
-		 * kernel can print out a useful trap message and even get
-		 * to the debugger.
-		 *
-		 * If we get a page fault while holding a non-sleepable
-		 * lock, then it is most likely a fatal kernel page fault.
-		 * If WITNESS is enabled, then it's going to whine about
-		 * bogus LORs with various VM locks, so just skip to the
-		 * fatal trap handling directly.
+		 * are finally ready to read %cr2 and conditionally
+		 * reenable interrupts.  If we hold a spin lock, then
+		 * we must not reenable interrupts.  This might be a
+		 * spurious page fault.
 		 */
 		eva =3D rcr2();
-		if (td->td_critnest !=3D 0 ||
-		    WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
-		    "Kernel page fault") !=3D 0)
-			trap_fatal(frame, eva);
-		else
+		if (td->td_md.md_spinlock_count =3D=3D 0)
 			enable_intr();
 	}
=20
@@ -804,6 +791,50 @@
 	struct thread *td =3D curthread;
 	struct proc *p =3D td->td_proc;
=20
+	if (__predict_false((td->td_pflags & TDP_NOFAULTING) !=3D 0)) {
+		/*
+		 * Due to both processor errata and lazy TLB invalidation when
+		 * access restrictions are removed from virtual pages, memory
+		 * accesses that are allowed by the physical mapping layer may
+		 * nonetheless cause one spurious page fault per virtual page.=20
+		 * When the thread is executing a "no faulting" section that
+		 * is bracketed by vm_fault_{disable,enable}_pagefaults(),
+		 * every page fault is treated as a spurious page fault,
+		 * unless it accesses the same virtual address as the most
+		 * recent page fault within the same "no faulting" section.
+		 */
+		if (td->td_md.md_spurflt_addr !=3D eva ||
+		    (td->td_pflags & TDP_RESETSPUR) !=3D 0) {
+			/*
+			 * Do nothing to the TLB.  A stale TLB entry is
+			 * flushed automatically by a page fault.
+			 */
+			td->td_md.md_spurflt_addr =3D eva;
+			td->td_pflags &=3D ~TDP_RESETSPUR;
+			return (0);
+		}
+	} else {
+		/*
+		 * If we get a page fault while in a critical section, then
+		 * it is most likely a fatal kernel page fault.  The kernel
+		 * is already going to panic trying to get a sleep lock to
+		 * do the VM lookup, so just consider it a fatal trap so the
+		 * kernel can print out a useful trap message and even get
+		 * to the debugger.
+		 *
+		 * If we get a page fault while holding a non-sleepable
+		 * lock, then it is most likely a fatal kernel page fault.
+		 * If WITNESS is enabled, then it's going to whine about
+		 * bogus LORs with various VM locks, so just skip to the
+		 * fatal trap handling directly.
+		 */
+		if (td->td_critnest !=3D 0 ||
+		    WITNESS_CHECK(WARN_SLEEPOK | WARN_GIANTOK, NULL,
+		    "Kernel page fault") !=3D 0) {
+			trap_fatal(frame, eva);
+			return (-1);
+		}
+	}
 	va =3D trunc_page(eva);
 	if (va >=3D KERNBASE) {
 		/*
@@ -881,8 +912,20 @@
 		 */
 		rv =3D vm_fault(map, va, ftype, VM_FAULT_NORMAL);
 	}
-	if (rv =3D=3D KERN_SUCCESS)
+	if (rv =3D=3D KERN_SUCCESS) {
+#ifdef HWPMC_HOOKS
+		if (ftype =3D=3D VM_PROT_READ || ftype =3D=3D VM_PROT_WRITE) {
+			PMC_SOFT_CALL_TF( , , page_fault, all, frame);
+			if (ftype =3D=3D VM_PROT_READ)
+				PMC_SOFT_CALL_TF( , , page_fault, read,
+				    frame);
+			else
+				PMC_SOFT_CALL_TF( , , page_fault, write,
+				    frame);
+		}
+#endif
 		return (0);
+	}
 nogo:
 	if (!usermode) {
 		if (td->td_intr_nesting_level =3D=3D 0 &&
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/i386/vm86.c
--- a/head/sys/i386/i386/vm86.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/i386/vm86.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/i386/i386/vm86.c 234350 2012-04-16 19:31:44Z =
jkim $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -512,22 +512,27 @@
 void
 vm86_prepcall(struct vm86frame *vmf)
 {
-	uintptr_t addr[] =3D { 0xA00, 0x1000 };	/* code, stack */
-	u_char intcall[] =3D {
-		CLI, INTn, 0x00, STI, HLT
-	};
 	struct vm86_kernel *vm86;
+	uint32_t *stack;
+	uint8_t *code;
=20
+	code =3D (void *)0xa00;
+	stack =3D (void *)(0x1000 - 2);	/* keep aligned */
 	if ((vmf->vmf_trapno & PAGE_MASK) <=3D 0xff) {
 		/* interrupt call requested */
-		intcall[2] =3D (u_char)(vmf->vmf_trapno & 0xff);
-		memcpy((void *)addr[0], (void *)intcall, sizeof(intcall));
-		vmf->vmf_ip =3D addr[0];
+		code[0] =3D INTn;
+		code[1] =3D vmf->vmf_trapno & 0xff;
+		code[2] =3D HLT;
+		vmf->vmf_ip =3D (uintptr_t)code;
 		vmf->vmf_cs =3D 0;
+	} else {
+		code[0] =3D HLT;
+		stack--;
+		stack[0] =3D MAKE_VEC(0, (uintptr_t)code);
 	}
-	vmf->vmf_sp =3D addr[1] - 2;              /* keep aligned */
+	vmf->vmf_sp =3D (uintptr_t)stack;
+	vmf->vmf_ss =3D 0;
 	vmf->kernel_fs =3D vmf->kernel_es =3D vmf->kernel_ds =3D 0;
-	vmf->vmf_ss =3D 0;
 	vmf->vmf_eflags =3D PSL_VIF | PSL_VM | PSL_USER;
=20
 	vm86 =3D &PCPU_GET(curpcb)->pcb_ext->ext_vm86;
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/include/intr_machdep.h
--- a/head/sys/i386/include/intr_machdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/include/intr_machdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/i386/include/intr_machdep.h 232744 2012-03-09 19:42:=
48Z jhb $
+ * $FreeBSD: head/sys/i386/include/intr_machdep.h 234207 2012-04-13 07:15:=
40Z avg $
  */
=20
 #ifndef __MACHINE_INTR_MACHDEP_H__
@@ -60,10 +60,10 @@
  * - 1 ??? dummy counter.
  * - 2 counters for each I/O interrupt.
  * - 1 counter for each CPU for lapic timer.
- * - 7 counters for each CPU for IPI counters for SMP.
+ * - 9 counters for each CPU for IPI counters for SMP.
  */
 #ifdef SMP
-#define	INTRCNT_COUNT	(1 + NUM_IO_INTS * 2 + (1 + 7) * MAXCPU)
+#define	INTRCNT_COUNT	(1 + NUM_IO_INTS * 2 + (1 + 9) * MAXCPU)
 #else
 #define	INTRCNT_COUNT	(1 + NUM_IO_INTS * 2 + 1)
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/include/pmc_mdep.h
--- a/head/sys/i386/include/pmc_mdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/include/pmc_mdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/i386/include/pmc_mdep.h 233628 2012-03-28 20:58:30Z =
fabient $
  */
=20
 #ifndef _MACHINE_PMC_MDEP_H
@@ -66,16 +66,16 @@
  * measurement architecture have PMCs of the following classes: TSC,
  * IAF, IAP, UCF and UCP.
  */
-#define	PMC_MDEP_CLASS_INDEX_TSC	0
-#define	PMC_MDEP_CLASS_INDEX_K7		1
-#define	PMC_MDEP_CLASS_INDEX_K8		1
-#define	PMC_MDEP_CLASS_INDEX_P4		1
-#define	PMC_MDEP_CLASS_INDEX_P5		1
-#define	PMC_MDEP_CLASS_INDEX_P6		1
-#define	PMC_MDEP_CLASS_INDEX_IAP	1
-#define	PMC_MDEP_CLASS_INDEX_IAF	2
-#define PMC_MDEP_CLASS_INDEX_UCP	3
-#define PMC_MDEP_CLASS_INDEX_UCF	4
+#define	PMC_MDEP_CLASS_INDEX_TSC	1
+#define	PMC_MDEP_CLASS_INDEX_K7		2
+#define	PMC_MDEP_CLASS_INDEX_K8		2
+#define	PMC_MDEP_CLASS_INDEX_P4		2
+#define	PMC_MDEP_CLASS_INDEX_P5		2
+#define	PMC_MDEP_CLASS_INDEX_P6		2
+#define	PMC_MDEP_CLASS_INDEX_IAP	2
+#define	PMC_MDEP_CLASS_INDEX_IAF	3
+#define	PMC_MDEP_CLASS_INDEX_UCP	4
+#define	PMC_MDEP_CLASS_INDEX_UCF	5
=20
 /*
  * Architecture specific extensions to <sys/pmc.h> structures.
@@ -154,6 +154,15 @@
 #define	PMC_AT_FUNCTION_EPILOGUE_RET(I)			\
 	(((I) & 0xFF) =3D=3D 0xC3)		   /* ret */
=20
+/* Build a fake kernel trapframe from current instruction pointer. */
+#define PMC_FAKE_TRAPFRAME(TF)						\
+	do {								\
+	(TF)->tf_cs =3D 0; (TF)->tf_eflags =3D 0;				\
+	__asm __volatile("movl %%ebp,%0" : "=3Dr" ((TF)->tf_ebp));	\
+	__asm __volatile("movl %%esp,%0" : "=3Dr" ((TF)->tf_esp));	\
+	__asm __volatile("call 1f \n\t1: pop %0" : "=3Dr"((TF)->tf_eip));	\
+	} while (0)
+
 /*
  * Prototypes
  */
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/include/proc.h
--- a/head/sys/i386/include/proc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/include/proc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	from: @(#)proc.h	7.1 (Berkeley) 5/15/91
- * $FreeBSD: head/sys/i386/include/proc.h 226112 2011-10-07 16:09:44Z kib $
+ * $FreeBSD: head/sys/i386/include/proc.h 233291 2012-03-22 04:52:51Z alc $
  */
=20
 #ifndef _MACHINE_PROC_H_
@@ -51,6 +51,7 @@
 struct mdthread {
 	int	md_spinlock_count;	/* (k) */
 	register_t md_saved_flags;	/* (k) */
+	register_t md_spurflt_addr;	/* (k) Spurious page fault address. */
 };
=20
 struct mdproc {
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/include/vm.h
--- a/head/sys/i386/include/vm.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/include/vm.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/i386/include/vm.h 233671 2012-03-29 16:51:22Z jhb $
  */
=20
 #ifndef _MACHINE_VM_H_
@@ -38,7 +38,7 @@
 #define	VM_MEMATTR_WRITE_THROUGH	((vm_memattr_t)PAT_WRITE_THROUGH)
 #define	VM_MEMATTR_WRITE_PROTECTED	((vm_memattr_t)PAT_WRITE_PROTECTED)
 #define	VM_MEMATTR_WRITE_BACK		((vm_memattr_t)PAT_WRITE_BACK)
-#define	VM_MEMATTR_UNCACHED		((vm_memattr_t)PAT_UNCACHED)
+#define	VM_MEMATTR_WEAK_UNCACHEABLE	((vm_memattr_t)PAT_UNCACHED)
=20
 #define	VM_MEMATTR_DEFAULT		VM_MEMATTR_WRITE_BACK
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/linux_dummy.c
--- a/head/sys/i386/linux/linux_dummy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/linux/linux_dummy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/linux/linux_dummy.c 232799 2012-03-10 23=
:10:18Z netchild $");
+__FBSDID("$FreeBSD: head/sys/i386/linux/linux_dummy.c 234352 2012-04-16 21=
:22:02Z jkim $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -113,7 +113,6 @@
 DUMMY(eventfd2);
 DUMMY(epoll_create1);
 DUMMY(dup3);
-DUMMY(pipe2);
 DUMMY(inotify_init1);
 /* linux 2.6.30: */
 DUMMY(preadv);
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/linux_machdep.c
--- a/head/sys/i386/linux/linux_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/linux/linux_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/i386/linux/linux_machdep.c 225617 2011-09-16 =
13:58:51Z kmacy $");
+__FBSDID("$FreeBSD: head/sys/i386/linux/linux_machdep.c 234352 2012-04-16 =
21:22:02Z jkim $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -587,25 +587,6 @@
 }
=20
 int
-linux_pipe(struct thread *td, struct linux_pipe_args *args)
-{
-	int error;
-	int fildes[2];
-
-#ifdef DEBUG
-	if (ldebug(pipe))
-		printf(ARGS(pipe, "*"));
-#endif
-
-	error =3D kern_pipe(td, fildes);
-	if (error)
-		return (error);
-
-	/* XXX: Close descriptors on error. */
-	return (copyout(fildes, args->pipefds, sizeof fildes));
-}
-
-int
 linux_ioperm(struct thread *td, struct linux_ioperm_args *args)
 {
 	int error;
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/linux_proto.h
--- a/head/sys/i386/linux/linux_proto.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/linux/linux_proto.h	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,8 @@
  * System call prototypes.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/i386/linux/linux_proto.h 232800 2012-03-10 23:11:21Z=
 netchild $
- * created from FreeBSD: head/sys/i386/linux/syscalls.master 232799 2012-0=
3-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/i386/linux/linux_proto.h 234360 2012-04-16 23:17:29Z=
 jkim $
+ * created from FreeBSD: head/sys/i386/linux/syscalls.master 234359 2012-0=
4-16 23:16:18Z jkim=20
  */
=20
 #ifndef _LINUX_SYSPROTO_H_
@@ -157,7 +157,7 @@
 	char path_l_[PADL_(char *)]; char * path; char path_r_[PADR_(char *)];
 };
 struct linux_pipe_args {
-	char pipefds_l_[PADL_(l_ulong *)]; l_ulong * pipefds; char pipefds_r_[PAD=
R_(l_ulong *)];
+	char pipefds_l_[PADL_(l_int *)]; l_int * pipefds; char pipefds_r_[PADR_(l=
_int *)];
 };
 struct linux_times_args {
 	char buf_l_[PADL_(struct l_times_argv *)]; struct l_times_argv * buf; cha=
r buf_r_[PADR_(struct l_times_argv *)];
@@ -344,7 +344,7 @@
 	register_t dummy;
 };
 struct linux_iopl_args {
-	char level_l_[PADL_(l_ulong)]; l_ulong level; char level_r_[PADR_(l_ulong=
)];
+	char level_l_[PADL_(l_int)]; l_int level; char level_r_[PADR_(l_int)];
 };
 struct linux_vhangup_args {
 	register_t dummy;
@@ -625,19 +625,16 @@
 	char length_l_[PADL_(l_loff_t)]; l_loff_t length; char length_r_[PADR_(l_=
loff_t)];
 };
 struct linux_stat64_args {
-	char filename_l_[PADL_(char *)]; char * filename; char filename_r_[PADR_(=
char *)];
+	char filename_l_[PADL_(const char *)]; const char * filename; char filena=
me_r_[PADR_(const char *)];
 	char statbuf_l_[PADL_(struct l_stat64 *)]; struct l_stat64 * statbuf; cha=
r statbuf_r_[PADR_(struct l_stat64 *)];
-	char flags_l_[PADL_(l_long)]; l_long flags; char flags_r_[PADR_(l_long)];
 };
 struct linux_lstat64_args {
-	char filename_l_[PADL_(char *)]; char * filename; char filename_r_[PADR_(=
char *)];
+	char filename_l_[PADL_(const char *)]; const char * filename; char filena=
me_r_[PADR_(const char *)];
 	char statbuf_l_[PADL_(struct l_stat64 *)]; struct l_stat64 * statbuf; cha=
r statbuf_r_[PADR_(struct l_stat64 *)];
-	char flags_l_[PADL_(l_long)]; l_long flags; char flags_r_[PADR_(l_long)];
 };
 struct linux_fstat64_args {
-	char fd_l_[PADL_(l_ulong)]; l_ulong fd; char fd_r_[PADR_(l_ulong)];
+	char fd_l_[PADL_(l_int)]; l_int fd; char fd_r_[PADR_(l_int)];
 	char statbuf_l_[PADL_(struct l_stat64 *)]; struct l_stat64 * statbuf; cha=
r statbuf_r_[PADR_(struct l_stat64 *)];
-	char flags_l_[PADL_(l_long)]; l_long flags; char flags_r_[PADR_(l_long)];
 };
 struct linux_lchown_args {
 	char path_l_[PADL_(char *)]; char * path; char path_r_[PADR_(char *)];
@@ -1065,7 +1062,8 @@
 	register_t dummy;
 };
 struct linux_pipe2_args {
-	register_t dummy;
+	char pipefds_l_[PADL_(l_int *)]; l_int * pipefds; char pipefds_r_[PADR_(l=
_int *)];
+	char flags_l_[PADL_(l_int)]; l_int flags; char flags_r_[PADR_(l_int)];
 };
 struct linux_inotify_init1_args {
 	register_t dummy;
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/linux_syscall.h
--- a/head/sys/i386/linux/linux_syscall.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/linux/linux_syscall.h	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,8 @@
  * System call numbers.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/i386/linux/linux_syscall.h 232800 2012-03-10 23:11:2=
1Z netchild $
- * created from FreeBSD: head/sys/i386/linux/syscalls.master 232799 2012-0=
3-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/i386/linux/linux_syscall.h 234360 2012-04-16 23:17:2=
9Z jkim $
+ * created from FreeBSD: head/sys/i386/linux/syscalls.master 234359 2012-0=
4-16 23:16:18Z jkim=20
  */
=20
 #define	LINUX_SYS_exit	1
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/linux_syscalls.c
--- a/head/sys/i386/linux/linux_syscalls.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/linux/linux_syscalls.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,8 @@
  * System call names.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/i386/linux/linux_syscalls.c 232800 2012-03-10 23:11:=
21Z netchild $
- * created from FreeBSD: head/sys/i386/linux/syscalls.master 232799 2012-0=
3-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/i386/linux/linux_syscalls.c 234360 2012-04-16 23:17:=
29Z jkim $
+ * created from FreeBSD: head/sys/i386/linux/syscalls.master 234359 2012-0=
4-16 23:16:18Z jkim=20
  */
=20
 const char *linux_syscallnames[] =3D {
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/linux_sysent.c
--- a/head/sys/i386/linux/linux_sysent.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/linux/linux_sysent.c	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,8 @@
  * System call switch table.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/i386/linux/linux_sysent.c 232800 2012-03-10 23:11:21=
Z netchild $
- * created from FreeBSD: head/sys/i386/linux/syscalls.master 232799 2012-0=
3-10 23:10:18Z netchild=20
+ * $FreeBSD: head/sys/i386/linux/linux_sysent.c 234360 2012-04-16 23:17:29=
Z jkim $
+ * created from FreeBSD: head/sys/i386/linux/syscalls.master 234359 2012-0=
4-16 23:16:18Z jkim=20
  */
=20
 #include <sys/param.h>
@@ -349,7 +349,7 @@
 	{ 0, (sy_call_t *)linux_eventfd2, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC =
},	/* 328 =3D linux_eventfd2 */
 	{ 0, (sy_call_t *)linux_epoll_create1, AUE_NULL, NULL, 0, 0, 0, SY_THR_ST=
ATIC },	/* 329 =3D linux_epoll_create1 */
 	{ 0, (sy_call_t *)linux_dup3, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	/=
* 330 =3D linux_dup3 */
-	{ 0, (sy_call_t *)linux_pipe2, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },	=
/* 331 =3D linux_pipe2 */
+	{ AS(linux_pipe2_args), (sy_call_t *)linux_pipe2, AUE_NULL, NULL, 0, 0, 0=
, SY_THR_STATIC },	/* 331 =3D linux_pipe2 */
 	{ 0, (sy_call_t *)linux_inotify_init1, AUE_NULL, NULL, 0, 0, 0, SY_THR_ST=
ATIC },	/* 332 =3D linux_inotify_init1 */
 	{ 0, (sy_call_t *)linux_preadv, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC },=
	/* 333 =3D linux_preadv */
 	{ 0, (sy_call_t *)linux_pwritev, AUE_NULL, NULL, 0, 0, 0, SY_THR_STATIC }=
,	/* 334 =3D linux_pwritev */
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/linux_systrace_arg=
s.c
--- a/head/sys/i386/linux/linux_systrace_args.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/sys/i386/linux/linux_systrace_args.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -2,7 +2,7 @@
  * System call argument to DTrace register array converstion.
  *
  * DO NOT EDIT-- this file is automatically generated.
- * $FreeBSD: head/sys/i386/linux/linux_systrace_args.c 232800 2012-03-10 2=
3:11:21Z netchild $
+ * $FreeBSD: head/sys/i386/linux/linux_systrace_args.c 234360 2012-04-16 2=
3:17:29Z jkim $
  * This file is part of the DTrace syscall provider.
  */
=20
@@ -295,7 +295,7 @@
 	/* linux_pipe */
 	case 42: {
 		struct linux_pipe_args *p =3D params;
-		uarg[0] =3D (intptr_t) p->pipefds; /* l_ulong * */
+		uarg[0] =3D (intptr_t) p->pipefds; /* l_int * */
 		*n_args =3D 1;
 		break;
 	}
@@ -772,7 +772,7 @@
 	/* linux_iopl */
 	case 110: {
 		struct linux_iopl_args *p =3D params;
-		iarg[0] =3D p->level; /* l_ulong */
+		iarg[0] =3D p->level; /* l_int */
 		*n_args =3D 1;
 		break;
 	}
@@ -1398,28 +1398,25 @@
 	/* linux_stat64 */
 	case 195: {
 		struct linux_stat64_args *p =3D params;
-		uarg[0] =3D (intptr_t) p->filename; /* char * */
+		uarg[0] =3D (intptr_t) p->filename; /* const char * */
 		uarg[1] =3D (intptr_t) p->statbuf; /* struct l_stat64 * */
-		iarg[2] =3D p->flags; /* l_long */
-		*n_args =3D 3;
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_lstat64 */
 	case 196: {
 		struct linux_lstat64_args *p =3D params;
-		uarg[0] =3D (intptr_t) p->filename; /* char * */
+		uarg[0] =3D (intptr_t) p->filename; /* const char * */
 		uarg[1] =3D (intptr_t) p->statbuf; /* struct l_stat64 * */
-		iarg[2] =3D p->flags; /* l_long */
-		*n_args =3D 3;
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_fstat64 */
 	case 197: {
 		struct linux_fstat64_args *p =3D params;
-		iarg[0] =3D p->fd; /* l_ulong */
+		iarg[0] =3D p->fd; /* l_int */
 		uarg[1] =3D (intptr_t) p->statbuf; /* struct l_stat64 * */
-		iarg[2] =3D p->flags; /* l_long */
-		*n_args =3D 3;
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_lchown */
@@ -2263,7 +2260,10 @@
 	}
 	/* linux_pipe2 */
 	case 331: {
-		*n_args =3D 0;
+		struct linux_pipe2_args *p =3D params;
+		uarg[0] =3D (intptr_t) p->pipefds; /* l_int * */
+		iarg[1] =3D p->flags; /* l_int */
+		*n_args =3D 2;
 		break;
 	}
 	/* linux_inotify_init1 */
@@ -2793,7 +2793,7 @@
 	case 42:
 		switch(ndx) {
 		case 0:
-			p =3D "l_ulong *";
+			p =3D "l_int *";
 			break;
 		default:
 			break;
@@ -3522,7 +3522,7 @@
 	case 110:
 		switch(ndx) {
 		case 0:
-			p =3D "l_ulong";
+			p =3D "l_int";
 			break;
 		default:
 			break;
@@ -4491,14 +4491,11 @@
 	case 195:
 		switch(ndx) {
 		case 0:
-			p =3D "char *";
+			p =3D "const char *";
 			break;
 		case 1:
 			p =3D "struct l_stat64 *";
 			break;
-		case 2:
-			p =3D "l_long";
-			break;
 		default:
 			break;
 		};
@@ -4507,14 +4504,11 @@
 	case 196:
 		switch(ndx) {
 		case 0:
-			p =3D "char *";
+			p =3D "const char *";
 			break;
 		case 1:
 			p =3D "struct l_stat64 *";
 			break;
-		case 2:
-			p =3D "l_long";
-			break;
 		default:
 			break;
 		};
@@ -4523,14 +4517,11 @@
 	case 197:
 		switch(ndx) {
 		case 0:
-			p =3D "l_ulong";
+			p =3D "l_int";
 			break;
 		case 1:
 			p =3D "struct l_stat64 *";
 			break;
-		case 2:
-			p =3D "l_long";
-			break;
 		default:
 			break;
 		};
@@ -5664,6 +5655,16 @@
 		break;
 	/* linux_pipe2 */
 	case 331:
+		switch(ndx) {
+		case 0:
+			p =3D "l_int *";
+			break;
+		case 1:
+			p =3D "l_int";
+			break;
+		default:
+			break;
+		};
 		break;
 	/* linux_inotify_init1 */
 	case 332:
@@ -6979,6 +6980,9 @@
 	case 330:
 	/* linux_pipe2 */
 	case 331:
+		if (ndx =3D=3D 0 || ndx =3D=3D 1)
+			p =3D "int";
+		break;
 	/* linux_inotify_init1 */
 	case 332:
 	/* linux_preadv */
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/linux/syscalls.master
--- a/head/sys/i386/linux/syscalls.master	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/linux/syscalls.master	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
- $FreeBSD: head/sys/i386/linux/syscalls.master 232799 2012-03-10 23:10:18Z=
 netchild $
+ $FreeBSD: head/sys/i386/linux/syscalls.master 234359 2012-04-16 23:16:18Z=
 jkim $
=20
 ;	@(#)syscalls.master	8.1 (Berkeley) 7/19/93
 ; System call name/number master file (or rather, slave, from LINUX).
@@ -95,7 +95,7 @@
 39	AUE_MKDIR	STD	{ int linux_mkdir(char *path, l_int mode); }
 40	AUE_RMDIR	STD	{ int linux_rmdir(char *path); }
 41	AUE_DUP		NOPROTO	{ int dup(u_int fd); }
-42	AUE_PIPE	STD	{ int linux_pipe(l_ulong *pipefds); }
+42	AUE_PIPE	STD	{ int linux_pipe(l_int *pipefds); }
 43	AUE_NULL	STD	{ int linux_times(struct l_times_argv *buf); }
 44	AUE_NULL	UNIMPL	prof
 45	AUE_NULL	STD	{ int linux_brk(l_ulong dsend); }
@@ -203,7 +203,7 @@
 				    struct l_newstat *buf); }
 ; 109: olduname
 109	AUE_NULL	STD	{ int linux_uname(void); }
-110	AUE_NULL	STD	{ int linux_iopl(l_ulong level); }
+110	AUE_NULL	STD	{ int linux_iopl(l_int level); }
 111	AUE_NULL	STD	{ int linux_vhangup(void); }
 112	AUE_NULL	UNIMPL	idle
 113	AUE_NULL	STD	{ int linux_vm86old(void); }
@@ -353,12 +353,12 @@
 				    l_loff_t length); }
 194	AUE_FTRUNCATE	STD	{ int linux_ftruncate64(l_uint fd, \
 				    l_loff_t length); }
-195	AUE_STAT	STD	{ int linux_stat64(char *filename, \
-				    struct l_stat64 *statbuf, l_long flags); }
-196	AUE_LSTAT	STD	{ int linux_lstat64(char *filename, \
-				    struct l_stat64 *statbuf, l_long flags); }
-197	AUE_FSTAT	STD	{ int linux_fstat64(l_ulong fd, \
-				    struct l_stat64 *statbuf, l_long flags); }
+195	AUE_STAT	STD	{ int linux_stat64(const char *filename, \
+				    struct l_stat64 *statbuf); }
+196	AUE_LSTAT	STD	{ int linux_lstat64(const char *filename, \
+				    struct l_stat64 *statbuf); }
+197	AUE_FSTAT	STD	{ int linux_fstat64(l_int fd, \
+				    struct l_stat64 *statbuf); }
 198	AUE_LCHOWN	STD	{ int linux_lchown(char *path, l_uid_t uid, \
 				    l_gid_t gid); }
 199	AUE_GETUID	STD	{ int linux_getuid(void); }
@@ -546,7 +546,7 @@
 328	AUE_NULL	STD	{ int linux_eventfd2(void); }
 329	AUE_NULL	STD	{ int linux_epoll_create1(void); }
 330	AUE_NULL	STD	{ int linux_dup3(void); }
-331	AUE_NULL	STD	{ int linux_pipe2(void); }
+331	AUE_NULL	STD	{ int linux_pipe2(l_int *pipefds, l_int flags); }
 332	AUE_NULL	STD	{ int linux_inotify_init1(void); }
 ; linux 2.6.30:
 333	AUE_NULL	STD	{ int linux_preadv(void); }
diff -r 428842767fa6 -r f2935497fa04 head/sys/i386/xbox/xboxfb.c
--- a/head/sys/i386/xbox/xboxfb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/i386/xbox/xboxfb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/i386/xbox/xboxfb.c 233707 2012-03-30 19:10:14=
Z jhb $");
=20
 /*
  * This is the syscon(4)-ized version of the Xbox Frame Buffer driver. It
@@ -54,7 +54,7 @@
 #include <vm/pmap.h>
 #include <machine/bus.h>
 #include <machine/xbox.h>
-#include <machine/legacyvar.h>
+#include <x86/legacyvar.h>
 #include <dev/fb/fbreg.h>
 #include <dev/fb/gfb.h>
 #include <dev/syscons/syscons.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/ia64/conf/GENERIC
--- a/head/sys/ia64/conf/GENERIC	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ia64/conf/GENERIC	Tue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
 #
 # For hardware specific information check HARDWARE.TXT
 #
-# $FreeBSD: head/sys/ia64/conf/GENERIC 229997 2012-01-12 00:34:33Z ken $
+# $FreeBSD: head/sys/ia64/conf/GENERIC 233271 2012-03-21 08:38:42Z ed $
=20
 cpu		ITANIUM2
 ident		GENERIC
@@ -201,7 +201,6 @@
 device		gif		# IPv6 and IPv4 tunneling
 device		loop		# Network loopback
 device		md		# Memory "disks"
-device		pty		# BSD-style compatibility pseudo ttys
 device		puc		# Multi I/O cards and multi-channel UARTs
 device		random		# Entropy device
 device		tun		# Packet tunnel.
diff -r 428842767fa6 -r f2935497fa04 head/sys/ia64/conf/SKI
--- a/head/sys/ia64/conf/SKI	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ia64/conf/SKI	Tue Apr 17 11:51:51 2012 +0300
@@ -17,7 +17,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check
 # first in NOTES.
 #
-# $FreeBSD$
+# $FreeBSD: head/sys/ia64/conf/SKI 233271 2012-03-21 08:38:42Z ed $
=20
 cpu		ITANIUM
 ident		SKI
@@ -53,7 +53,6 @@
 device		ether		# Ethernet support
 device		loop		# Network loopback
 device		md		# Memory "disks"
-device		pty		# BSD-style compatibility pseudo ttys
 device		random		# Entropy device
 device		tun		# Packet tunnel.
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_clock.c
--- a/head/sys/kern/kern_clock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_clock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_clock.c 232783 2012-03-10 14:57:21Z=
 mav $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_clock.c 233628 2012-03-28 20:58:30Z=
 fabient $");
=20
 #include "opt_kdb.h"
 #include "opt_device_polling.h"
@@ -74,6 +74,8 @@
=20
 #ifdef HWPMC_HOOKS
 #include <sys/pmckern.h>
+PMC_SOFT_DEFINE( , , clock, hard);
+PMC_SOFT_DEFINE( , , clock, stat);
 #endif
=20
 #ifdef DEVICE_POLLING
@@ -446,9 +448,11 @@
 	td->td_flags |=3D flags;
 	thread_unlock(td);
=20
-#ifdef	HWPMC_HOOKS
+#ifdef HWPMC_HOOKS
 	if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
 		PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
+	if (td->td_intr_frame !=3D NULL)
+		PMC_SOFT_CALL_TF( , , clock, hard, td->td_intr_frame);
 #endif
 	callout_tick();
 }
@@ -537,6 +541,8 @@
 #ifdef	HWPMC_HOOKS
 	if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
 		PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
+	if (td->td_intr_frame !=3D NULL)
+		PMC_SOFT_CALL_TF( , , clock, hard, td->td_intr_frame);
 #endif
 	callout_tick();
 	/* We are in charge to handle this tick duty. */
@@ -758,6 +764,10 @@
 	for ( ; cnt > 0; cnt--)
 		sched_clock(td);
 	thread_unlock(td);
+#ifdef HWPMC_HOOKS
+	if (td->td_intr_frame !=3D NULL)
+		PMC_SOFT_CALL_TF( , , clock, stat, td->td_intr_frame);
+#endif
 }
=20
 void
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_descrip.c
--- a/head/sys/kern/kern_descrip.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_descrip.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_descrip.c 232702 2012-03-08 20:34:1=
3Z pho $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_descrip.c 234131 2012-04-11 14:08:0=
9Z eadler $");
=20
 #include "opt_capsicum.h"
 #include "opt_compat.h"
@@ -58,6 +58,7 @@
 #include <sys/limits.h>
 #include <sys/lock.h>
 #include <sys/malloc.h>
+#include <sys/mman.h>
 #include <sys/mount.h>
 #include <sys/mqueue.h>
 #include <sys/mutex.h>
@@ -126,6 +127,7 @@
 static int	fill_pipe_info(struct pipe *pi, struct kinfo_file *kif);
 static int	fill_procdesc_info(struct procdesc *pdp,
     struct kinfo_file *kif);
+static int	fill_shm_info(struct file *fp, struct kinfo_file *kif);
=20
 /*
  * A process is initially started out with NDFILE descriptors stored within
@@ -815,7 +817,7 @@
 	maxfd =3D min((int)lim_cur(p, RLIMIT_NOFILE), maxfilesperproc);
 	PROC_UNLOCK(p);
 	if (new >=3D maxfd)
-		return (flags & DUP_FCNTL ? EINVAL : EMFILE);
+		return (flags & DUP_FCNTL ? EINVAL : EBADF);
=20
 	FILEDESC_XLOCK(fdp);
 	if (old >=3D fdp->fd_nfiles || fdp->fd_ofiles[old] =3D=3D NULL) {
@@ -2958,6 +2960,7 @@
 	struct kinfo_ofile *kif;
 	struct filedesc *fdp;
 	int error, i, *name;
+	struct shmfd *shmfd;
 	struct socket *so;
 	struct vnode *vp;
 	struct file *fp;
@@ -2995,6 +2998,7 @@
 		vp =3D NULL;
 		so =3D NULL;
 		tp =3D NULL;
+		shmfd =3D NULL;
 		kif->kf_fd =3D i;
=20
 #ifdef CAPABILITIES
@@ -3046,6 +3050,7 @@
=20
 		case DTYPE_SHM:
 			kif->kf_type =3D KF_TYPE_SHM;
+			shmfd =3D fp->f_data;
 			break;
=20
 		case DTYPE_SEM:
@@ -3159,6 +3164,8 @@
 			strlcpy(kif->kf_path, tty_devname(tp),
 			    sizeof(kif->kf_path));
 		}
+		if (shmfd !=3D NULL)
+			shm_path(shmfd, kif->kf_path, sizeof(kif->kf_path));
 		error =3D SYSCTL_OUT(req, kif, sizeof(*kif));
 		if (error)
 			break;
@@ -3229,6 +3236,9 @@
 	case KF_TYPE_PROCDESC:
 		error =3D fill_procdesc_info((struct procdesc *)data, kif);
 		break;
+	case KF_TYPE_SHM:
+		error =3D fill_shm_info((struct file *)data, kif);
+		break;
 	default:
 		error =3D 0;
 	}
@@ -3398,6 +3408,7 @@
=20
 		case DTYPE_SHM:
 			type =3D KF_TYPE_SHM;
+			data =3D fp;
 			break;
=20
 		case DTYPE_SEM:
@@ -3621,6 +3632,23 @@
 	return (0);
 }
=20
+static int
+fill_shm_info(struct file *fp, struct kinfo_file *kif)
+{
+	struct thread *td;
+	struct stat sb;
+
+	td =3D curthread;
+	if (fp->f_data =3D=3D NULL)
+		return (1);
+	if (fo_stat(fp, &sb, td->td_ucred, td) !=3D 0)
+		return (1);
+	shm_path(fp->f_data, kif->kf_path, sizeof(kif->kf_path));
+	kif->kf_un.kf_file.kf_file_mode =3D sb.st_mode;
+	kif->kf_un.kf_file.kf_file_size =3D sb.st_size;
+	return (0);
+}
+
 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, CTLFLAG_RD,
     sysctl_kern_proc_filedesc, "Process filedesc entries");
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_event.c
--- a/head/sys/kern/kern_event.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_event.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_event.c 225617 2011-09-16 13:58:51Z=
 kmacy $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_event.c 233505 2012-03-26 09:34:17Z=
 melifaro $");
=20
 #include "opt_ktrace.h"
=20
@@ -37,6 +37,7 @@
 #include <sys/kernel.h>
 #include <sys/lock.h>
 #include <sys/mutex.h>
+#include <sys/rwlock.h>
 #include <sys/proc.h>
 #include <sys/malloc.h>
 #include <sys/unistd.h>
@@ -1869,6 +1870,7 @@
 int
 knlist_empty(struct knlist *knl)
 {
+
 	KNL_ASSERT_LOCKED(knl);
 	return SLIST_EMPTY(&knl->kl_list);
 }
@@ -1882,27 +1884,59 @@
 static void
 knlist_mtx_lock(void *arg)
 {
+
 	mtx_lock((struct mtx *)arg);
 }
=20
 static void
 knlist_mtx_unlock(void *arg)
 {
+
 	mtx_unlock((struct mtx *)arg);
 }
=20
 static void
 knlist_mtx_assert_locked(void *arg)
 {
+
 	mtx_assert((struct mtx *)arg, MA_OWNED);
 }
=20
 static void
 knlist_mtx_assert_unlocked(void *arg)
 {
+
 	mtx_assert((struct mtx *)arg, MA_NOTOWNED);
 }
=20
+static void
+knlist_rw_rlock(void *arg)
+{
+
+	rw_rlock((struct rwlock *)arg);
+}
+
+static void
+knlist_rw_runlock(void *arg)
+{
+
+	rw_runlock((struct rwlock *)arg);
+}
+
+static void
+knlist_rw_assert_locked(void *arg)
+{
+
+	rw_assert((struct rwlock *)arg, RA_LOCKED);
+}
+
+static void
+knlist_rw_assert_unlocked(void *arg)
+{
+
+	rw_assert((struct rwlock *)arg, RA_UNLOCKED);
+}
+
 void
 knlist_init(struct knlist *knl, void *lock, void (*kl_lock)(void *),
     void (*kl_unlock)(void *),
@@ -1942,6 +1976,14 @@
 }
=20
 void
+knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock)
+{
+
+	knlist_init(knl, lock, knlist_rw_rlock, knlist_rw_runlock,
+	    knlist_rw_assert_locked, knlist_rw_assert_unlocked);
+}
+
+void
 knlist_destroy(struct knlist *knl)
 {
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_exit.c
--- a/head/sys/kern/kern_exit.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_exit.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_exit.c 232975 2012-03-14 15:52:23Z =
jh $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_exit.c 233809 2012-04-02 19:35:36Z =
kib $");
=20
 #include "opt_compat.h"
 #include "opt_kdtrace.h"
@@ -100,6 +100,18 @@
 /* Hook for NFS teardown procedure. */
 void (*nlminfo_release_p)(struct proc *p);
=20
+static void
+clear_orphan(struct proc *p)
+{
+
+	PROC_LOCK_ASSERT(p, MA_OWNED);
+
+	if (p->p_flag & P_ORPHAN) {
+		LIST_REMOVE(p, p_orphan);
+		p->p_flag &=3D ~P_ORPHAN;
+	}
+}
+
 /*
  * exit -- death of process.
  */
@@ -418,6 +430,13 @@
 		if (q->p_flag & P_TRACED) {
 			struct thread *temp;
=20
+			/*
+			 * Since q was found on our children list, the
+			 * proc_reparent() call moved q to the orphan
+			 * list due to present P_TRACED flag. Clear
+			 * orphan link for q now while q is locked.
+			 */
+			clear_orphan(q);
 			q->p_flag &=3D ~(P_TRACED | P_STOPPED_TRACE);
 			FOREACH_THREAD_IN_PROC(q, temp)
 				temp->td_dbgflags &=3D ~TDB_SUSPEND;
@@ -426,6 +445,15 @@
 		PROC_UNLOCK(q);
 	}
=20
+	/*
+	 * Also get rid of our orphans.
+	 */
+	while ((q =3D LIST_FIRST(&p->p_orphans)) !=3D NULL) {
+		PROC_LOCK(q);
+		clear_orphan(q);
+		PROC_UNLOCK(q);
+	}
+
 	/* Save exit status. */
 	PROC_LOCK(p);
 	p->p_xthread =3D td;
@@ -739,10 +767,7 @@
 	sx_xunlock(&allproc_lock);
 	LIST_REMOVE(p, p_sibling);
 	PROC_LOCK(p);
-	if (p->p_flag & P_ORPHAN) {
-		LIST_REMOVE(p, p_orphan);
-		p->p_flag &=3D ~P_ORPHAN;
-	}
+	clear_orphan(p);
 	PROC_UNLOCK(p);
 	leavepgrp(p);
 #ifdef PROCDESC
@@ -987,10 +1012,7 @@
 	LIST_REMOVE(child, p_sibling);
 	LIST_INSERT_HEAD(&parent->p_children, child, p_sibling);
=20
-	if (child->p_flag & P_ORPHAN) {
-		LIST_REMOVE(child, p_orphan);
-		child->p_flag &=3D ~P_ORPHAN;
-	}
+	clear_orphan(child);
 	if (child->p_flag & P_TRACED) {
 		LIST_INSERT_HEAD(&child->p_pptr->p_orphans, child, p_orphan);
 		child->p_flag |=3D P_ORPHAN;
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_ktrace.c
--- a/head/sys/kern/kern_ktrace.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_ktrace.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_ktrace.c 231949 2012-02-21 01:05:12=
Z kib $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_ktrace.c 233925 2012-04-05 17:13:14=
Z jhb $");
=20
 #include "opt_ktrace.h"
=20
@@ -101,6 +101,8 @@
 		struct	ktr_genio ktr_genio;
 		struct	ktr_psig ktr_psig;
 		struct	ktr_csw ktr_csw;
+		struct	ktr_fault ktr_fault;
+		struct	ktr_faultend ktr_faultend;
 	} ktr_data;
 	STAILQ_ENTRY(ktr_request) ktr_list;
 };
@@ -119,6 +121,8 @@
 	sizeof(struct ktr_proc_ctor),		/* KTR_PROCCTOR */
 	0,					/* KTR_PROCDTOR */
 	sizeof(struct ktr_cap_fail),		/* KTR_CAPFAIL */
+	sizeof(struct ktr_fault),		/* KTR_FAULT */
+	sizeof(struct ktr_faultend),		/* KTR_FAULTEND */
 };
=20
 static STAILQ_HEAD(, ktr_request) ktr_free;
@@ -791,6 +795,42 @@
 	ktr_enqueuerequest(td, req);
 	ktrace_exit(td);
 }
+
+void
+ktrfault(vaddr, type)
+	vm_offset_t vaddr;
+	int type;
+{
+	struct thread *td =3D curthread;
+	struct ktr_request *req;
+	struct ktr_fault *kf;
+
+	req =3D ktr_getrequest(KTR_FAULT);
+	if (req =3D=3D NULL)
+		return;
+	kf =3D &req->ktr_data.ktr_fault;
+	kf->vaddr =3D vaddr;
+	kf->type =3D type;
+	ktr_enqueuerequest(td, req);
+	ktrace_exit(td);
+}
+
+void
+ktrfaultend(result)
+	int result;
+{
+	struct thread *td =3D curthread;
+	struct ktr_request *req;
+	struct ktr_faultend *kf;
+
+	req =3D ktr_getrequest(KTR_FAULTEND);
+	if (req =3D=3D NULL)
+		return;
+	kf =3D &req->ktr_data.ktr_faultend;
+	kf->result =3D result;
+	ktr_enqueuerequest(td, req);
+	ktrace_exit(td);
+}
 #endif /* KTRACE */
=20
 /* Interface and common routines */
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_linker.c
--- a/head/sys/kern/kern_linker.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_linker.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_linker.c 232999 2012-03-15 06:01:21=
Z ae $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_linker.c 234186 2012-04-12 14:49:25=
Z jhb $");
=20
 #include "opt_ddb.h"
 #include "opt_kld.h"
@@ -312,7 +312,7 @@
 {
 	struct sysctl_oid **start, **stop, **oidp;
=20
-	KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs"
+	KLD_DPF(FILE, ("linker_file_unregister_sysctls: unregistering SYSCTLs"
 	    " for %s\n", lf->filename));
=20
 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) !=3D 0)
@@ -380,7 +380,7 @@
 {
 	linker_class_t lc;
 	linker_file_t lf;
-	int foundfile, error;
+	int foundfile, error, modules;
=20
 	/* Refuse to load modules if securelevel raised */
 	if (prison0.pr_securelevel > 0)
@@ -419,11 +419,22 @@
 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
 				return (error);
 			}
+			modules =3D !TAILQ_EMPTY(&lf->modules);
 			KLD_UNLOCK();
 			linker_file_register_sysctls(lf);
 			linker_file_sysinit(lf);
 			KLD_LOCK();
 			lf->flags |=3D LINKER_FILE_LINKED;
+
+			/*
+			 * If all of the modules in this file failed
+			 * to load, unload the file and return an
+			 * error of ENOEXEC.
+			 */
+			if (modules && TAILQ_EMPTY(&lf->modules)) {
+				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
+				return (ENOEXEC);
+			}
 			*result =3D lf;
 			return (0);
 		}
@@ -627,7 +638,7 @@
=20
 	/*
 	 * Inform any modules associated with this file that they are
-	 * being be unloaded.
+	 * being unloaded.
 	 */
 	MOD_XLOCK;
 	for (mod =3D TAILQ_FIRST(&file->modules); mod; mod =3D next) {
@@ -638,8 +649,12 @@
 		 * Give the module a chance to veto the unload.
 		 */
 		if ((error =3D module_unload(mod)) !=3D 0) {
+#ifdef KLD_DEBUG
+			MOD_SLOCK;
 			KLD_DPF(FILE, ("linker_file_unload: module %s"
 			    " failed unload\n", module_getname(mod)));
+			MOD_SUNLOCK;
+#endif
 			return (error);
 		}
 		MOD_XLOCK;
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_lock.c
--- a/head/sys/kern/kern_lock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_lock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,10 +28,11 @@
=20
 #include "opt_adaptive_lockmgrs.h"
 #include "opt_ddb.h"
+#include "opt_hwpmc_hooks.h"
 #include "opt_kdtrace.h"
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_lock.c 232547 2012-03-05 14:19:43Z =
ivoras $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_lock.c 233628 2012-03-28 20:58:30Z =
fabient $");
=20
 #include <sys/param.h>
 #include <sys/ktr.h>
@@ -53,6 +54,11 @@
 #include <ddb/ddb.h>
 #endif
=20
+#ifdef HWPMC_HOOKS
+#include <sys/pmckern.h>
+PMC_SOFT_DECLARE( , , lock, failed);
+#endif
+
 CTASSERT(((LK_ADAPTIVE | LK_NOSHARE) & LO_CLASSFLAGS) =3D=3D
     (LK_ADAPTIVE | LK_NOSHARE));
 CTASSERT(LK_UNLOCKED =3D=3D (LK_UNLOCKED &
@@ -514,6 +520,9 @@
 					break;
 				continue;
 			}
+#ifdef HWPMC_HOOKS
+			PMC_SOFT_CALL( , , lock, failed);
+#endif
 			lock_profile_obtain_lock_failed(&lk->lock_object,
 			    &contested, &waittime);
=20
@@ -744,6 +753,9 @@
=20
 		while (!atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED,
 		    tid)) {
+#ifdef HWPMC_HOOKS
+			PMC_SOFT_CALL( , , lock, failed);
+#endif
 			lock_profile_obtain_lock_failed(&lk->lock_object,
 			    &contested, &waittime);
=20
@@ -1056,6 +1068,9 @@
 		}
=20
 		while (!atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid)) {
+#ifdef HWPMC_HOOKS
+			PMC_SOFT_CALL( , , lock, failed);
+#endif
 			lock_profile_obtain_lock_failed(&lk->lock_object,
 			    &contested, &waittime);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_mutex.c
--- a/head/sys/kern/kern_mutex.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_mutex.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,11 +34,12 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_mutex.c 228424 2011-12-11 21:02:01Z=
 avg $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_mutex.c 233628 2012-03-28 20:58:30Z=
 fabient $");
=20
 #include "opt_adaptive_mutexes.h"
 #include "opt_ddb.h"
 #include "opt_global.h"
+#include "opt_hwpmc_hooks.h"
 #include "opt_kdtrace.h"
 #include "opt_sched.h"
=20
@@ -76,6 +77,11 @@
 #define	ADAPTIVE_MUTEXES
 #endif
=20
+#ifdef HWPMC_HOOKS
+#include <sys/pmckern.h>
+PMC_SOFT_DEFINE( , , lock, failed);
+#endif
+
 /*
  * Internal utility macros.
  */
@@ -364,6 +370,9 @@
 		return;
 	}
=20
+#ifdef HWPMC_HOOKS
+	PMC_SOFT_CALL( , , lock, failed);
+#endif
 	lock_profile_obtain_lock_failed(&m->lock_object,
 		    &contested, &waittime);
 	if (LOCK_LOG_TEST(&m->lock_object, opts))
@@ -529,6 +538,9 @@
 	if (LOCK_LOG_TEST(&m->lock_object, opts))
 		CTR1(KTR_LOCK, "_mtx_lock_spin: %p spinning", m);
=20
+#ifdef HWPMC_HOOKS
+	PMC_SOFT_CALL( , , lock, failed);
+#endif
 	lock_profile_obtain_lock_failed(&m->lock_object, &contested, &waittime);
 	while (!_mtx_obtain_lock(m, tid)) {
=20
@@ -600,6 +612,9 @@
 				m->mtx_recurse++;
 				break;
 			}
+#ifdef HWPMC_HOOKS
+			PMC_SOFT_CALL( , , lock, failed);
+#endif
 			lock_profile_obtain_lock_failed(&m->lock_object,
 			    &contested, &waittime);
 			/* Give interrupts a chance while we spin. */
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_pmc.c
--- a/head/sys/kern/kern_pmc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_pmc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,15 +29,22 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_pmc.c 222813 2011-06-07 08:46:13Z a=
ttilio $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_pmc.c 233628 2012-03-28 20:58:30Z f=
abient $");
=20
 #include "opt_hwpmc_hooks.h"
=20
 #include <sys/types.h>
+#include <sys/ctype.h>
+#include <sys/param.h>
+#include <sys/malloc.h>
+#include <sys/kernel.h>
+#include <sys/lock.h>
+#include <sys/mutex.h>
 #include <sys/pmc.h>
 #include <sys/pmckern.h>
 #include <sys/smp.h>
 #include <sys/sysctl.h>
+#include <sys/systm.h>
=20
 #ifdef	HWPMC_HOOKS
 FEATURE(hwpmc_hooks, "Kernel support for HW PMC");
@@ -46,6 +53,9 @@
 #define	PMC_KERNEL_VERSION	0
 #endif
=20
+MALLOC_DECLARE(M_PMCHOOKS);
+MALLOC_DEFINE(M_PMCHOOKS, "pmchooks", "Memory space for PMC hooks");
+
 const int pmc_kernel_version =3D PMC_KERNEL_VERSION;
=20
 /* Hook variable. */
@@ -74,6 +84,28 @@
  */
 struct sx pmc_sx;
=20
+/*
+ * PMC Soft per cpu trapframe.
+ */
+struct trapframe pmc_tf[MAXCPU];
+
+/*
+ * PMC Soft use a global table to store registered events.
+ */
+
+SYSCTL_NODE(_kern, OID_AUTO, hwpmc, CTLFLAG_RW, 0, "HWPMC parameters");
+
+static int pmc_softevents =3D 16;
+TUNABLE_INT(PMC_SYSCTL_NAME_PREFIX "softevents", &pmc_softevents);
+SYSCTL_INT(_kern_hwpmc, OID_AUTO, softevents, CTLFLAG_TUN|CTLFLAG_RD,
+    &pmc_softevents, 0, "maximum number of soft events");
+
+struct mtx pmc_softs_mtx;
+int pmc_softs_count;
+struct pmc_soft **pmc_softs;
+
+MTX_SYSINIT(pmc_soft_mtx, &pmc_softs_mtx, "pmc-softs", MTX_SPIN);
+
 static void
 pmc_init_sx(void)
 {
@@ -182,3 +214,132 @@
 }
=20
 #endif
+
+/*
+ * Cleanup event name:
+ * - remove duplicate '_'
+ * - all uppercase
+ */
+static void
+pmc_soft_namecleanup(char *name)
+{
+	char *p, *q;
+
+	p =3D q =3D name;
+
+	for ( ; *p =3D=3D '_' ; p++)
+		;
+	for ( ; *p ; p++) {
+		if (*p =3D=3D '_' && (*(p + 1) =3D=3D '_' || *(p + 1) =3D=3D '\0'))
+			continue;
+		else
+			*q++ =3D toupper(*p);
+	}
+	*q =3D '\0';
+}
+
+void
+pmc_soft_ev_register(struct pmc_soft *ps)
+{
+	static int warned =3D 0;
+	int n;
+
+	ps->ps_running  =3D 0;
+	ps->ps_ev.pm_ev_code =3D 0; /* invalid */
+	pmc_soft_namecleanup(ps->ps_ev.pm_ev_name);
+
+	mtx_lock_spin(&pmc_softs_mtx);
+
+	if (pmc_softs_count >=3D pmc_softevents) {
+		/*
+		 * XXX Reusing events can enter a race condition where
+		 * new allocated event will be used as an old one.
+		 */
+		for (n =3D 0; n < pmc_softevents; n++)
+			if (pmc_softs[n] =3D=3D NULL)
+				break;
+		if (n =3D=3D pmc_softevents) {
+			mtx_unlock_spin(&pmc_softs_mtx);
+			if (!warned) {
+				printf("hwpmc: too many soft events, "
+				    "increase kern.hwpmc.softevents tunable\n");
+				warned =3D 1;
+			}
+			return;
+		}
+
+		ps->ps_ev.pm_ev_code =3D PMC_EV_SOFT_FIRST + n;
+		pmc_softs[n] =3D ps;
+	} else {
+		ps->ps_ev.pm_ev_code =3D PMC_EV_SOFT_FIRST + pmc_softs_count;
+		pmc_softs[pmc_softs_count++] =3D ps;
+	}
+
+	mtx_unlock_spin(&pmc_softs_mtx);
+}
+
+void
+pmc_soft_ev_deregister(struct pmc_soft *ps)
+{
+
+	KASSERT(ps !=3D NULL, ("pmc_soft_deregister: called with NULL"));
+
+	mtx_lock_spin(&pmc_softs_mtx);
+
+	if (ps->ps_ev.pm_ev_code !=3D 0 &&
+	    (ps->ps_ev.pm_ev_code - PMC_EV_SOFT_FIRST) < pmc_softevents) {
+		KASSERT(ps->ps_ev.pm_ev_code >=3D PMC_EV_SOFT_FIRST &&
+		    ps->ps_ev.pm_ev_code <=3D PMC_EV_SOFT_LAST,
+		    ("pmc_soft_deregister: invalid event value"));
+		pmc_softs[ps->ps_ev.pm_ev_code - PMC_EV_SOFT_FIRST] =3D NULL;
+	}
+
+	mtx_unlock_spin(&pmc_softs_mtx);
+}
+
+struct pmc_soft *
+pmc_soft_ev_acquire(enum pmc_event ev)
+{
+	struct pmc_soft *ps;
+
+	if (ev =3D=3D 0 || (ev - PMC_EV_SOFT_FIRST) >=3D pmc_softevents)
+		return NULL;
+
+	KASSERT(ev >=3D PMC_EV_SOFT_FIRST &&
+	    ev <=3D PMC_EV_SOFT_LAST,
+	    ("event out of range"));
+
+	mtx_lock_spin(&pmc_softs_mtx);
+
+	ps =3D pmc_softs[ev - PMC_EV_SOFT_FIRST];
+	if (ps =3D=3D NULL)
+		mtx_unlock_spin(&pmc_softs_mtx);
+
+	return ps;
+}
+
+void
+pmc_soft_ev_release(struct pmc_soft *ps)
+{
+
+	mtx_unlock_spin(&pmc_softs_mtx);
+}
+
+/*
+ *  Initialise hwpmc.
+ */
+static void
+init_hwpmc(void *dummy __unused)
+{
+	if (pmc_softevents <=3D 0 ||
+	    pmc_softevents > PMC_EV_DYN_COUNT) {
+		(void) printf("hwpmc: tunable \"softevents\"=3D%d out of "
+		    "range.\n", pmc_softevents);
+		pmc_softevents =3D PMC_EV_DYN_COUNT;
+	}
+	pmc_softs =3D malloc(pmc_softevents * sizeof(struct pmc_soft *), M_PMCHOO=
KS, M_NOWAIT|M_ZERO);
+	KASSERT(pmc_softs !=3D NULL, ("cannot allocate soft events table"));
+}
+
+SYSINIT(hwpmc, SI_SUB_KDTRACE, SI_ORDER_FIRST, init_hwpmc, NULL);
+
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_proc.c
--- a/head/sys/kern/kern_proc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_proc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_proc.c 232455 2012-03-03 11:53:35Z =
trociny $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_proc.c 233389 2012-03-23 20:05:41Z =
trociny $");
=20
 #include "opt_compat.h"
 #include "opt_ddb.h"
@@ -2499,6 +2499,52 @@
 	return (error);
 }
=20
+/*
+ * This sysctl allows a process to set and retrieve binary osreldate of
+ * another process.
+ */
+static int
+sysctl_kern_proc_osrel(SYSCTL_HANDLER_ARGS)
+{
+	int *name =3D (int *)arg1;
+	u_int namelen =3D arg2;
+	struct proc *p;
+	int flags, error, osrel;
+
+	if (namelen !=3D 1)
+		return (EINVAL);
+
+	if (req->newptr !=3D NULL && req->newlen !=3D sizeof(osrel))
+		return (EINVAL);
+
+	flags =3D PGET_HOLD | PGET_NOTWEXIT;
+	if (req->newptr !=3D NULL)
+		flags |=3D PGET_CANDEBUG;
+	else
+		flags |=3D PGET_CANSEE;
+	error =3D pget((pid_t)name[0], flags, &p);
+	if (error !=3D 0)
+		return (error);
+
+	error =3D SYSCTL_OUT(req, &p->p_osrel, sizeof(p->p_osrel));
+	if (error !=3D 0)
+		goto errout;
+
+	if (req->newptr !=3D NULL) {
+		error =3D SYSCTL_IN(req, &osrel, sizeof(osrel));
+		if (error !=3D 0)
+			goto errout;
+		if (osrel < 0) {
+			error =3D EINVAL;
+			goto errout;
+		}
+		p->p_osrel =3D osrel;
+	}
+errout:
+	PRELE(p);
+	return (error);
+}
+
 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
=20
 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT|
@@ -2603,3 +2649,7 @@
=20
 static SYSCTL_NODE(_kern_proc, KERN_PROC_UMASK, umask, CTLFLAG_RD |
 	CTLFLAG_MPSAFE, sysctl_kern_proc_umask, "Process umask");
+
+static SYSCTL_NODE(_kern_proc, KERN_PROC_OSREL, osrel, CTLFLAG_RW |
+	CTLFLAG_ANYBODY | CTLFLAG_MPSAFE, sysctl_kern_proc_osrel,
+	"Process binary osreldate");
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_rwlock.c
--- a/head/sys/kern/kern_rwlock.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_rwlock.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,9 +32,10 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_rwlock.c 228424 2011-12-11 21:02:01=
Z avg $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_rwlock.c 233628 2012-03-28 20:58:30=
Z fabient $");
=20
 #include "opt_ddb.h"
+#include "opt_hwpmc_hooks.h"
 #include "opt_kdtrace.h"
 #include "opt_no_adaptive_rwlocks.h"
=20
@@ -55,6 +56,11 @@
 #define	ADAPTIVE_RWLOCKS
 #endif
=20
+#ifdef HWPMC_HOOKS
+#include <sys/pmckern.h>
+PMC_SOFT_DECLARE( , , lock, failed);
+#endif
+
 #ifdef ADAPTIVE_RWLOCKS
 static int rowner_retries =3D 10;
 static int rowner_loops =3D 10000;
@@ -366,6 +372,9 @@
 			}
 			continue;
 		}
+#ifdef HWPMC_HOOKS
+		PMC_SOFT_CALL( , , lock, failed);
+#endif
 		lock_profile_obtain_lock_failed(&rw->lock_object,
 		    &contested, &waittime);
=20
@@ -687,6 +696,9 @@
 #ifdef KDTRACE_HOOKS
 		spin_cnt++;
 #endif
+#ifdef HWPMC_HOOKS
+		PMC_SOFT_CALL( , , lock, failed);
+#endif
 		lock_profile_obtain_lock_failed(&rw->lock_object,
 		    &contested, &waittime);
 #ifdef ADAPTIVE_RWLOCKS
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_sdt.c
--- a/head/sys/kern/kern_sdt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_sdt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/kern/kern_sdt.c 233552 2012-03-27 15:07:43Z rstone $
  *
  * Backend for the Statically Defined Tracing (SDT) kernel support. This is
  * required to allow a module to load even though DTrace kernel support may
@@ -59,6 +59,16 @@
  */
 sdt_probe_func_t sdt_probe_func =3D sdt_probe_stub;
=20
+static sdt_provider_listall_func_t sdt_provider_register_func =3D NULL;
+static sdt_provider_listall_func_t sdt_provider_deregister_func =3D NULL;
+static sdt_probe_listall_func_t sdt_probe_register_func =3D NULL;
+
+static void *sdt_provider_register_arg;
+static void *sdt_provider_deregister_arg;
+static void *sdt_probe_register_arg;
+
+static int sdt_provider_listall_locked(sdt_provider_listall_func_t, void *=
);
+
 /*
  * This is a stub for probe calls in case kernel DTrace support isn't
  * compiled in. It should never get called because there is no DTrace
@@ -85,6 +95,9 @@
=20
 	TAILQ_INIT(&prov->probe_list);
=20
+	if (sdt_provider_register_func !=3D NULL)
+		sdt_provider_register_func(prov, sdt_provider_register_arg);
+
 	sx_xunlock(&sdt_sx);
 }
=20
@@ -100,6 +113,9 @@
=20
 	TAILQ_REMOVE(&sdt_provider_list, prov, prov_entry);
=20
+	if (sdt_provider_deregister_func !=3D NULL)
+		sdt_provider_deregister_func(prov, sdt_provider_deregister_arg);
+
 	sx_xunlock(&sdt_sx);
 }
=20
@@ -128,6 +144,9 @@
=20
 	probe->state =3D SDT_INIT;
=20
+	if (sdt_probe_register_func !=3D NULL)
+		sdt_probe_register_func(probe, sdt_provider_register_arg);
+
 	sx_xunlock(&sdt_sx);
 }
=20
@@ -203,20 +222,31 @@
  * List statically defined tracing providers.
  */
 int
-sdt_provider_listall(sdt_provider_listall_func_t callback_func,void *arg)
+sdt_provider_listall(sdt_provider_listall_func_t callback_func, void *arg)
+{
+	int error;
+
+	sx_xlock(&sdt_sx);
+	error =3D sdt_provider_listall_locked(callback_func, arg);
+	sx_xunlock(&sdt_sx);
+
+	return (error);
+}
+
+static int
+sdt_provider_listall_locked(sdt_provider_listall_func_t callback_func,
+    void *arg)
 {
 	int error =3D 0;
 	struct sdt_provider *prov;
=20
-	sx_xlock(&sdt_sx);
+	sx_assert(&sdt_sx, SX_XLOCKED);
=20
 	TAILQ_FOREACH(prov, &sdt_provider_list, prov_entry) {
 		if ((error =3D callback_func(prov, arg)) !=3D 0)
 			break;
 	}
=20
-	sx_xunlock(&sdt_sx);
-
 	return (error);
 }
=20
@@ -271,3 +301,39 @@
=20
 	return (error);
 }
+
+void sdt_register_callbacks(sdt_provider_listall_func_t register_prov,=20
+    void *reg_prov_arg, sdt_provider_listall_func_t deregister_prov,=20
+    void *dereg_prov_arg, sdt_probe_listall_func_t register_probe,=20
+    void * reg_probe_arg)
+{
+
+	sx_xlock(&sdt_sx);
+	sdt_provider_register_func =3D register_prov;
+	sdt_provider_deregister_func =3D deregister_prov;
+	sdt_probe_register_func =3D register_probe;
+
+	sdt_provider_register_arg =3D reg_prov_arg;
+	sdt_provider_deregister_arg =3D dereg_prov_arg;
+	sdt_probe_register_arg =3D reg_probe_arg;
+
+	sdt_provider_listall_locked(register_prov, reg_prov_arg);
+	sx_xunlock(&sdt_sx);
+}
+
+void sdt_deregister_callbacks(void)
+{
+
+	sx_xlock(&sdt_sx);
+	sdt_provider_listall_locked(sdt_provider_deregister_func,=20
+	    sdt_provider_deregister_arg);
+
+	sdt_provider_register_func =3D NULL;
+	sdt_provider_deregister_func =3D NULL;
+	sdt_probe_register_func =3D NULL;
+
+	sdt_provider_register_arg =3D NULL;
+	sdt_provider_deregister_arg =3D NULL;
+	sdt_probe_register_arg =3D NULL;
+	sx_xunlock(&sdt_sx);
+}
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_sig.c
--- a/head/sys/kern/kern_sig.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_sig.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_sig.c 227309 2011-11-07 15:43:11Z e=
d $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_sig.c 234172 2012-04-12 10:48:43Z k=
ib $");
=20
 #include "opt_compat.h"
 #include "opt_kdtrace.h"
@@ -194,40 +194,39 @@
 #define	SA_IGNORE	0x10		/* ignore by default */
 #define	SA_CONT		0x20		/* continue if suspended */
 #define	SA_CANTMASK	0x40		/* non-maskable, catchable */
-#define	SA_PROC		0x80		/* deliverable to any thread */
=20
 static int sigproptbl[NSIG] =3D {
-        SA_KILL|SA_PROC,		/* SIGHUP */
-        SA_KILL|SA_PROC,		/* SIGINT */
-        SA_KILL|SA_CORE|SA_PROC,	/* SIGQUIT */
+        SA_KILL,			/* SIGHUP */
+        SA_KILL,			/* SIGINT */
+        SA_KILL|SA_CORE,		/* SIGQUIT */
         SA_KILL|SA_CORE,		/* SIGILL */
         SA_KILL|SA_CORE,		/* SIGTRAP */
         SA_KILL|SA_CORE,		/* SIGABRT */
-        SA_KILL|SA_CORE|SA_PROC,	/* SIGEMT */
+        SA_KILL|SA_CORE,		/* SIGEMT */
         SA_KILL|SA_CORE,		/* SIGFPE */
-        SA_KILL|SA_PROC,		/* SIGKILL */
+        SA_KILL,			/* SIGKILL */
         SA_KILL|SA_CORE,		/* SIGBUS */
         SA_KILL|SA_CORE,		/* SIGSEGV */
         SA_KILL|SA_CORE,		/* SIGSYS */
-        SA_KILL|SA_PROC,		/* SIGPIPE */
-        SA_KILL|SA_PROC,		/* SIGALRM */
-        SA_KILL|SA_PROC,		/* SIGTERM */
-        SA_IGNORE|SA_PROC,		/* SIGURG */
-        SA_STOP|SA_PROC,		/* SIGSTOP */
-        SA_STOP|SA_TTYSTOP|SA_PROC,	/* SIGTSTP */
-        SA_IGNORE|SA_CONT|SA_PROC,	/* SIGCONT */
-        SA_IGNORE|SA_PROC,		/* SIGCHLD */
-        SA_STOP|SA_TTYSTOP|SA_PROC,	/* SIGTTIN */
-        SA_STOP|SA_TTYSTOP|SA_PROC,	/* SIGTTOU */
-        SA_IGNORE|SA_PROC,		/* SIGIO */
+        SA_KILL,			/* SIGPIPE */
+        SA_KILL,			/* SIGALRM */
+        SA_KILL,			/* SIGTERM */
+        SA_IGNORE,			/* SIGURG */
+        SA_STOP,			/* SIGSTOP */
+        SA_STOP|SA_TTYSTOP,		/* SIGTSTP */
+        SA_IGNORE|SA_CONT,		/* SIGCONT */
+        SA_IGNORE,			/* SIGCHLD */
+        SA_STOP|SA_TTYSTOP,		/* SIGTTIN */
+        SA_STOP|SA_TTYSTOP,		/* SIGTTOU */
+        SA_IGNORE,			/* SIGIO */
         SA_KILL,			/* SIGXCPU */
         SA_KILL,			/* SIGXFSZ */
-        SA_KILL|SA_PROC,		/* SIGVTALRM */
-        SA_KILL|SA_PROC,		/* SIGPROF */
-        SA_IGNORE|SA_PROC,		/* SIGWINCH  */
-        SA_IGNORE|SA_PROC,		/* SIGINFO */
-        SA_KILL|SA_PROC,		/* SIGUSR1 */
-        SA_KILL|SA_PROC,		/* SIGUSR2 */
+        SA_KILL,			/* SIGVTALRM */
+        SA_KILL,			/* SIGPROF */
+        SA_IGNORE,			/* SIGWINCH  */
+        SA_IGNORE,			/* SIGINFO */
+        SA_KILL,			/* SIGUSR1 */
+        SA_KILL,			/* SIGUSR2 */
 };
=20
 static void reschedule_signals(struct proc *p, sigset_t block, int flags);
@@ -1466,6 +1465,8 @@
 		mtx_unlock(&p->p_sigacts->ps_mtx);
 	}
 	PROC_UNLOCK(p);
+	td->td_errno =3D EINTR;
+	td->td_pflags |=3D TDP_NERRNO;
 	return (EJUSTRETURN);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_sx.c
--- a/head/sys/kern/kern_sx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_sx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -37,11 +37,12 @@
  */
=20
 #include "opt_ddb.h"
+#include "opt_hwpmc_hooks.h"
 #include "opt_kdtrace.h"
 #include "opt_no_adaptive_sx.h"
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_sx.c 228433 2011-12-12 10:05:13Z av=
g $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_sx.c 233628 2012-03-28 20:58:30Z fa=
bient $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -67,6 +68,11 @@
=20
 CTASSERT((SX_NOADAPTIVE & LO_CLASSFLAGS) =3D=3D SX_NOADAPTIVE);
=20
+#ifdef HWPMC_HOOKS
+#include <sys/pmckern.h>
+PMC_SOFT_DECLARE( , , lock, failed);
+#endif
+
 /* Handy macros for sleep queues. */
 #define	SQ_EXCLUSIVE_QUEUE	0
 #define	SQ_SHARED_QUEUE		1
@@ -524,6 +530,9 @@
 #ifdef KDTRACE_HOOKS
 		spin_cnt++;
 #endif
+#ifdef HWPMC_HOOKS
+		PMC_SOFT_CALL( , , lock, failed);
+#endif
 		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
 		    &waittime);
 #ifdef ADAPTIVE_SX
@@ -811,6 +820,9 @@
 			}
 			continue;
 		}
+#ifdef HWPMC_HOOKS
+		PMC_SOFT_CALL( , , lock, failed);
+#endif
 		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
 		    &waittime);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_sysctl.c
--- a/head/sys/kern/kern_sysctl.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_sysctl.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_sysctl.c 225617 2011-09-16 13:58:51=
Z kmacy $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_sysctl.c 233291 2012-03-22 04:52:51=
Z alc $");
=20
 #include "opt_capsicum.h"
 #include "opt_compat.h"
@@ -1294,8 +1294,8 @@
 static int
 sysctl_old_user(struct sysctl_req *req, const void *p, size_t l)
 {
-	int error =3D 0;
 	size_t i, len, origidx;
+	int error;
=20
 	origidx =3D req->oldidx;
 	req->oldidx +=3D l;
@@ -1316,10 +1316,14 @@
 	else {
 		if (i > len - origidx)
 			i =3D len - origidx;
-		error =3D copyout(p, (char *)req->oldptr + origidx, i);
+		if (req->lock =3D=3D REQ_WIRED) {
+			error =3D copyout_nofault(p, (char *)req->oldptr +
+			    origidx, i);
+		} else
+			error =3D copyout(p, (char *)req->oldptr + origidx, i);
+		if (error !=3D 0)
+			return (error);
 	}
-	if (error)
-		return (error);
 	if (i < l)
 		return (ENOMEM);
 	return (0);
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/kern_umtx.c
--- a/head/sys/kern/kern_umtx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/kern_umtx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_umtx.c 233045 2012-03-16 20:32:11Z =
davide $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_umtx.c 234302 2012-04-14 23:53:31Z =
davide $");
=20
 #include "opt_compat.h"
 #include "opt_umtx_profiling.h"
@@ -187,6 +187,12 @@
=20
 #define BUSY_SPINS		200
=20
+struct abs_timeout {
+	int clockid;
+	struct timespec cur;
+	struct timespec end;
+};
+
 static uma_zone_t		umtx_pi_zone;
 static struct umtxq_chain	umtxq_chains[2][UMTX_CHAINS];
 static MALLOC_DEFINE(M_UMTX, "umtx", "UMTX queue memory");
@@ -211,7 +217,7 @@
 static void umtxq_unbusy(struct umtx_key *key);
 static void umtxq_insert_queue(struct umtx_q *uq, int q);
 static void umtxq_remove_queue(struct umtx_q *uq, int q);
-static int umtxq_sleep(struct umtx_q *uq, const char *wmesg, int timo);
+static int umtxq_sleep(struct umtx_q *uq, const char *wmesg, struct abs_ti=
meout *);
 static int umtxq_count(struct umtx_key *key);
 static struct umtx_pi *umtx_pi_alloc(int);
 static void umtx_pi_free(struct umtx_pi *pi);
@@ -265,15 +271,15 @@
 			TAILQ_INIT(&umtxq_chains[i][j].uc_pi_list);
 			umtxq_chains[i][j].uc_busy =3D 0;
 			umtxq_chains[i][j].uc_waiters =3D 0;
-			#ifdef UMTX_PROFILING
+#ifdef UMTX_PROFILING
 			umtxq_chains[i][j].length =3D 0;
 			umtxq_chains[i][j].max_length =3D 0;=09
-			#endif
+#endif
 		}
 	}
-	#ifdef UMTX_PROFILING
+#ifdef UMTX_PROFILING
 	umtx_init_profiling();
-	#endif
+#endif
 	mtx_init(&umtx_lock, "umtx lock", NULL, MTX_SPIN);
 	EVENTHANDLER_REGISTER(process_exec, umtx_exec_hook, NULL,
 	    EVENTHANDLER_PRI_ANY);
@@ -424,14 +430,14 @@
=20
 	TAILQ_INSERT_TAIL(&uh->head, uq, uq_link);
 	uh->length++;
-	#ifdef UMTX_PROFILING
+#ifdef UMTX_PROFILING
 	uc->length++;
 	if (uc->length > uc->max_length) {
 		uc->max_length =3D uc->length;
 		if (uc->max_length > max_length)
 			max_length =3D uc->max_length;=09
 	}
-	#endif
+#endif
 	uq->uq_flags |=3D UQF_UMTXQ;
 	uq->uq_cur_queue =3D uh;
 	return;
@@ -449,9 +455,9 @@
 		uh =3D uq->uq_cur_queue;
 		TAILQ_REMOVE(&uh->head, uq, uq_link);
 		uh->length--;
-		#ifdef UMTX_PROFILING
+#ifdef UMTX_PROFILING
 		uc->length--;
-		#endif
+#endif
 		uq->uq_flags &=3D ~UQF_UMTXQ;
 		if (TAILQ_EMPTY(&uh->head)) {
 			KASSERT(uh->length =3D=3D 0,
@@ -547,23 +553,84 @@
 	wakeup(uq);
 }
=20
+static inline int=20
+tstohz(const struct timespec *tsp)
+{
+	struct timeval tv;
+
+	TIMESPEC_TO_TIMEVAL(&tv, tsp);
+	return tvtohz(&tv);
+}
+
+static void
+abs_timeout_init(struct abs_timeout *timo, int clockid, int absolute,
+	const struct timespec *timeout)
+{
+
+	timo->clockid =3D clockid;
+	if (!absolute) {
+		kern_clock_gettime(curthread, clockid, &timo->end);
+		timo->cur =3D timo->end;
+		timespecadd(&timo->end, timeout);
+	} else {
+		timo->end =3D *timeout;
+		kern_clock_gettime(curthread, clockid, &timo->cur);
+	}
+}
+
+static void
+abs_timeout_init2(struct abs_timeout *timo, const struct _umtx_time *umtxt=
ime)
+{
+
+	abs_timeout_init(timo, umtxtime->_clockid,
+		(umtxtime->_flags & UMTX_ABSTIME) !=3D 0,
+		&umtxtime->_timeout);
+}
+
+static int
+abs_timeout_update(struct abs_timeout *timo)
+{
+	kern_clock_gettime(curthread, timo->clockid, &timo->cur);
+	return (timespeccmp(&timo->cur, &timo->end, >=3D));
+}
+
+static int
+abs_timeout_gethz(struct abs_timeout *timo)
+{
+	struct timespec tts;
+
+	tts =3D timo->end;
+	timespecsub(&tts, &timo->cur);
+	return (tstohz(&tts));
+}
+
 /*
  * Put thread into sleep state, before sleeping, check if
  * thread was removed from umtx queue.
  */
 static inline int
-umtxq_sleep(struct umtx_q *uq, const char *wmesg, int timo)
+umtxq_sleep(struct umtx_q *uq, const char *wmesg, struct abs_timeout *timo)
 {
 	struct umtxq_chain *uc;
 	int error;
=20
 	uc =3D umtxq_getchain(&uq->uq_key);
 	UMTXQ_LOCKED_ASSERT(uc);
-	if (!(uq->uq_flags & UQF_UMTXQ))
-		return (0);
-	error =3D msleep(uq, &uc->uc_lock, PCATCH, wmesg, timo);
-	if (error =3D=3D EWOULDBLOCK)
-		error =3D ETIMEDOUT;
+	for (;;) {
+		if (!(uq->uq_flags & UQF_UMTXQ))
+			return (0);
+		error =3D msleep(uq, &uc->uc_lock, PCATCH, wmesg,
+		    timo =3D=3D NULL ? 0 : abs_timeout_gethz(timo));
+		if (error !=3D EWOULDBLOCK)
+			break;
+		umtxq_unlock(&uq->uq_key);
+		if (abs_timeout_update(timo)) {
+			error =3D ETIMEDOUT;
+			umtxq_lock(&uq->uq_key);
+			break;
+		}
+		umtxq_lock(&uq->uq_key);
+	}
 	return (error);
 }
=20
@@ -627,14 +694,18 @@
  * Lock a umtx object.
  */
 static int
-_do_lock_umtx(struct thread *td, struct umtx *umtx, u_long id, int timo)
+do_lock_umtx(struct thread *td, struct umtx *umtx, u_long id,
+	const struct timespec *timeout)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
 	u_long owner;
 	u_long old;
 	int error =3D 0;
=20
 	uq =3D td->td_umtxq;
+	if (timeout !=3D NULL)
+		abs_timeout_init(&timo, CLOCK_REALTIME, 0, timeout);
=20
 	/*
 	 * Care must be exercised when dealing with umtx structure. It
@@ -675,7 +746,7 @@
 		 * exit immediately.
 		 */
 		if (error !=3D 0)
-			return (error);
+			break;
=20
 		if ((error =3D umtx_key_get(umtx, TYPE_SIMPLE_LOCK,
 			AUTO_SHARE, &uq->uq_key)) !=3D 0)
@@ -711,48 +782,18 @@
 		 */
 		umtxq_lock(&uq->uq_key);
 		if (old =3D=3D owner)
-			error =3D umtxq_sleep(uq, "umtx", timo);
+			error =3D umtxq_sleep(uq, "umtx", timeout =3D=3D NULL ? NULL :
+			    &timo);
 		umtxq_remove(uq);
 		umtxq_unlock(&uq->uq_key);
 		umtx_key_release(&uq->uq_key);
 	}
=20
-	return (0);
-}
-
-/*
- * Lock a umtx object.
- */
-static int
-do_lock_umtx(struct thread *td, struct umtx *umtx, u_long id,
-	struct timespec *timeout)
-{
-	struct timespec ts, ts2, ts3;
-	struct timeval tv;
-	int error;
-
 	if (timeout =3D=3D NULL) {
-		error =3D _do_lock_umtx(td, umtx, id, 0);
 		/* Mutex locking is restarted if it is interrupted. */
 		if (error =3D=3D EINTR)
 			error =3D ERESTART;
 	} else {
-		getnanouptime(&ts);
-		timespecadd(&ts, timeout);
-		TIMESPEC_TO_TIMEVAL(&tv, timeout);
-		for (;;) {
-			error =3D _do_lock_umtx(td, umtx, id, tvtohz(&tv));
-			if (error !=3D ETIMEDOUT)
-				break;
-			getnanouptime(&ts2);
-			if (timespeccmp(&ts2, &ts, >=3D)) {
-				error =3D ETIMEDOUT;
-				break;
-			}
-			ts3 =3D ts;
-			timespecsub(&ts3, &ts2);
-			TIMESPEC_TO_TIMEVAL(&tv, &ts3);
-		}
 		/* Timed-locking is not restarted. */
 		if (error =3D=3D ERESTART)
 			error =3D EINTR;
@@ -827,8 +868,10 @@
  * Lock a umtx object.
  */
 static int
-_do_lock_umtx32(struct thread *td, uint32_t *m, uint32_t id, int timo)
+do_lock_umtx32(struct thread *td, uint32_t *m, uint32_t id,
+	const struct timespec *timeout)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
 	uint32_t owner;
 	uint32_t old;
@@ -836,6 +879,9 @@
=20
 	uq =3D td->td_umtxq;
=20
+	if (timeout !=3D NULL)
+		abs_timeout_init(&timo, CLOCK_REALTIME, 0, timeout);
+
 	/*
 	 * Care must be exercised when dealing with umtx structure. It
 	 * can fault on any access.
@@ -910,48 +956,18 @@
 		 */
 		umtxq_lock(&uq->uq_key);
 		if (old =3D=3D owner)
-			error =3D umtxq_sleep(uq, "umtx", timo);
+			error =3D umtxq_sleep(uq, "umtx", timeout =3D=3D NULL ?
+			    NULL : &timo);
 		umtxq_remove(uq);
 		umtxq_unlock(&uq->uq_key);
 		umtx_key_release(&uq->uq_key);
 	}
=20
-	return (0);
-}
-
-/*
- * Lock a umtx object.
- */
-static int
-do_lock_umtx32(struct thread *td, void *m, uint32_t id,
-	struct timespec *timeout)
-{
-	struct timespec ts, ts2, ts3;
-	struct timeval tv;
-	int error;
-
 	if (timeout =3D=3D NULL) {
-		error =3D _do_lock_umtx32(td, m, id, 0);
 		/* Mutex locking is restarted if it is interrupted. */
 		if (error =3D=3D EINTR)
 			error =3D ERESTART;
 	} else {
-		getnanouptime(&ts);
-		timespecadd(&ts, timeout);
-		TIMESPEC_TO_TIMEVAL(&tv, timeout);
-		for (;;) {
-			error =3D _do_lock_umtx32(td, m, id, tvtohz(&tv));
-			if (error !=3D ETIMEDOUT)
-				break;
-			getnanouptime(&ts2);
-			if (timespeccmp(&ts2, &ts, >=3D)) {
-				error =3D ETIMEDOUT;
-				break;
-			}
-			ts3 =3D ts;
-			timespecsub(&ts3, &ts2);
-			TIMESPEC_TO_TIMEVAL(&tv, &ts3);
-		}
 		/* Timed-locking is not restarted. */
 		if (error =3D=3D ERESTART)
 			error =3D EINTR;
@@ -1021,15 +1037,6 @@
 }
 #endif
=20
-static inline int=20
-tstohz(const struct timespec *tsp)
-{
-	struct timeval tv;
-
-	TIMESPEC_TO_TIMEVAL(&tv, tsp);
-	return tvtohz(&tv);
-}
-
 /*
  * Fetch and compare value, sleep on the address if value is not changed.
  */
@@ -1037,8 +1044,8 @@
 do_wait(struct thread *td, void *addr, u_long id,
 	struct _umtx_time *timeout, int compat32, int is_private)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
-	struct timespec ets, cts, tts;
 	u_long tmp;
 	int error =3D 0;
=20
@@ -1047,6 +1054,9 @@
 		is_private ? THREAD_SHARE : AUTO_SHARE, &uq->uq_key)) !=3D 0)
 		return (error);
=20
+	if (timeout !=3D NULL)
+		abs_timeout_init2(&timo, timeout);
+
 	umtxq_lock(&uq->uq_key);
 	umtxq_insert(uq);
 	umtxq_unlock(&uq->uq_key);
@@ -1054,45 +1064,15 @@
 		tmp =3D fuword(addr);
         else
 		tmp =3D (unsigned int)fuword32(addr);
-	if (tmp !=3D id) {
-		umtxq_lock(&uq->uq_key);
+	umtxq_lock(&uq->uq_key);
+	if (tmp =3D=3D id)
+		error =3D umtxq_sleep(uq, "uwait", timeout =3D=3D NULL ?
+		    NULL : &timo);
+	if ((uq->uq_flags & UQF_UMTXQ) =3D=3D 0)
+		error =3D 0;
+	else
 		umtxq_remove(uq);
-		umtxq_unlock(&uq->uq_key);
-	} else if (timeout =3D=3D NULL) {
-		umtxq_lock(&uq->uq_key);
-		error =3D umtxq_sleep(uq, "uwait", 0);
-		umtxq_remove(uq);
-		umtxq_unlock(&uq->uq_key);
-	} else {
-		kern_clock_gettime(td, timeout->_clockid, &cts);
-		if ((timeout->_flags & UMTX_ABSTIME) =3D=3D 0) {
-			ets =3D cts;
-			timespecadd(&ets, &timeout->_timeout);
-		} else {
-			ets =3D timeout->_timeout;
-		}
-		umtxq_lock(&uq->uq_key);
-		for (;;) {
-			if (timespeccmp(&cts, &ets, >=3D)) {
-				error =3D ETIMEDOUT;
-				break;
-			}
-			tts =3D ets;
-			timespecsub(&tts, &cts);
-			error =3D umtxq_sleep(uq, "uwait", tstohz(&tts));
-			if (!(uq->uq_flags & UQF_UMTXQ)) {
-				error =3D 0;
-				break;
-			}
-			if (error !=3D ETIMEDOUT)
-				break;
-			umtxq_unlock(&uq->uq_key);
-			kern_clock_gettime(td, timeout->_clockid, &cts);
-			umtxq_lock(&uq->uq_key);
-		}
-		umtxq_remove(uq);
-		umtxq_unlock(&uq->uq_key);
-	}
+	umtxq_unlock(&uq->uq_key);
 	umtx_key_release(&uq->uq_key);
 	if (error =3D=3D ERESTART)
 		error =3D EINTR;
@@ -1122,9 +1102,10 @@
  * Lock PTHREAD_PRIO_NONE protocol POSIX mutex.
  */
 static int
-_do_lock_normal(struct thread *td, struct umutex *m, uint32_t flags, int t=
imo,
-	int mode)
+do_lock_normal(struct thread *td, struct umutex *m, uint32_t flags,
+	struct _umtx_time *timeout, int mode)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
 	uint32_t owner, old, id;
 	int error =3D 0;
@@ -1132,6 +1113,9 @@
 	id =3D td->td_tid;
 	uq =3D td->td_umtxq;
=20
+	if (timeout !=3D NULL)
+		abs_timeout_init2(&timo, timeout);
+
 	/*
 	 * Care must be exercised when dealing with umtx structure. It
 	 * can fault on any access.
@@ -1221,7 +1205,8 @@
 		umtxq_lock(&uq->uq_key);
 		umtxq_unbusy(&uq->uq_key);
 		if (old =3D=3D owner)
-			error =3D umtxq_sleep(uq, "umtxn", timo);
+			error =3D umtxq_sleep(uq, "umtxn", timeout =3D=3D NULL ?
+			    NULL : &timo);
 		umtxq_remove(uq);
 		umtxq_unlock(&uq->uq_key);
 		umtx_key_release(&uq->uq_key);
@@ -1231,9 +1216,6 @@
 }
=20
 /*
- * Lock PTHREAD_PRIO_NONE protocol POSIX mutex.
- */
-/*
  * Unlock PTHREAD_PRIO_NONE protocol POSIX mutex.
  */
 static int
@@ -1337,6 +1319,78 @@
 	return (0);
 }
=20
+/*
+ * Check if the mutex has waiters and tries to fix contention bit.
+ */
+static int
+do_wake2_umutex(struct thread *td, struct umutex *m, uint32_t flags)
+{
+	struct umtx_key key;
+	uint32_t owner, old;
+	int type;
+	int error;
+	int count;
+
+	switch(flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT)) {
+	case 0:
+		type =3D TYPE_NORMAL_UMUTEX;
+		break;
+	case UMUTEX_PRIO_INHERIT:
+		type =3D TYPE_PI_UMUTEX;
+		break;
+	case UMUTEX_PRIO_PROTECT:
+		type =3D TYPE_PP_UMUTEX;
+		break;
+	default:
+		return (EINVAL);
+	}
+	if ((error =3D umtx_key_get(m, type, GET_SHARE(flags),
+	    &key)) !=3D 0)
+		return (error);
+
+	owner =3D 0;
+	umtxq_lock(&key);
+	umtxq_busy(&key);
+	count =3D umtxq_count(&key);
+	umtxq_unlock(&key);
+	/*
+	 * Only repair contention bit if there is a waiter, this means the mutex
+	 * is still being referenced by userland code, otherwise don't update
+	 * any memory.
+	 */
+	if (count > 1) {
+		owner =3D fuword32(__DEVOLATILE(uint32_t *, &m->m_owner));
+		while ((owner & UMUTEX_CONTESTED) =3D=3D0) {
+			old =3D casuword32(&m->m_owner, owner,
+			    owner|UMUTEX_CONTESTED);
+			if (old =3D=3D owner)
+				break;
+			owner =3D old;
+		}
+	} else if (count =3D=3D 1) {
+		owner =3D fuword32(__DEVOLATILE(uint32_t *, &m->m_owner));
+		while ((owner & ~UMUTEX_CONTESTED) !=3D 0 &&
+		       (owner & UMUTEX_CONTESTED) =3D=3D 0) {
+			old =3D casuword32(&m->m_owner, owner,
+			    owner|UMUTEX_CONTESTED);
+			if (old =3D=3D owner)
+				break;
+			owner =3D old;
+		}
+	}
+	umtxq_lock(&key);
+	if (owner =3D=3D -1) {
+		error =3D EFAULT;
+		umtxq_signal(&key, INT_MAX);
+	}
+	else if (count !=3D 0 && (owner & ~UMUTEX_CONTESTED) =3D=3D 0)
+		umtxq_signal(&key, 1);
+	umtxq_unbusy(&key);
+	umtxq_unlock(&key);
+	umtx_key_release(&key);
+	return (error);
+}
+
 static inline struct umtx_pi *
 umtx_pi_alloc(int flags)
 {
@@ -1563,7 +1617,7 @@
  */
 static int
 umtxq_sleep_pi(struct umtx_q *uq, struct umtx_pi *pi,
-	uint32_t owner, const char *wmesg, int timo)
+	uint32_t owner, const char *wmesg, struct abs_timeout *timo)
 {
 	struct umtxq_chain *uc;
 	struct thread *td, *td1;
@@ -1609,14 +1663,9 @@
 	mtx_unlock_spin(&umtx_lock);
 	umtxq_unbusy(&uq->uq_key);
=20
-	if (uq->uq_flags & UQF_UMTXQ) {
-		error =3D msleep(uq, &uc->uc_lock, PCATCH, wmesg, timo);
-		if (error =3D=3D EWOULDBLOCK)
-			error =3D ETIMEDOUT;
-		if (uq->uq_flags & UQF_UMTXQ) {
-			umtxq_remove(uq);
-		}
-	}
+	error =3D umtxq_sleep(uq, wmesg, timo);
+	umtxq_remove(uq);
+
 	mtx_lock_spin(&umtx_lock);
 	uq->uq_pi_blocked =3D NULL;
 	thread_lock(td);
@@ -1707,9 +1756,10 @@
  * Lock a PI mutex.
  */
 static int
-_do_lock_pi(struct thread *td, struct umutex *m, uint32_t flags, int timo,
-	int try)
+do_lock_pi(struct thread *td, struct umutex *m, uint32_t flags,
+    struct _umtx_time *timeout, int try)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
 	struct umtx_pi *pi, *new_pi;
 	uint32_t id, owner, old;
@@ -1721,6 +1771,10 @@
 	if ((error =3D umtx_key_get(m, TYPE_PI_UMUTEX, GET_SHARE(flags),
 	    &uq->uq_key)) !=3D 0)
 		return (error);
+
+	if (timeout !=3D NULL)
+		abs_timeout_init2(&timo, timeout);
+
 	umtxq_lock(&uq->uq_key);
 	pi =3D umtx_pi_lookup(&uq->uq_key);
 	if (pi =3D=3D NULL) {
@@ -1837,7 +1891,7 @@
 		 */
 		if (old =3D=3D owner)
 			error =3D umtxq_sleep_pi(uq, pi, owner & ~UMUTEX_CONTESTED,
-				 "umtxpi", timo);
+			    "umtxpi", timeout =3D=3D NULL ? NULL : &timo);
 		else {
 			umtxq_unbusy(&uq->uq_key);
 			umtxq_unlock(&uq->uq_key);
@@ -1956,9 +2010,10 @@
  * Lock a PP mutex.
  */
 static int
-_do_lock_pp(struct thread *td, struct umutex *m, uint32_t flags, int timo,
-	int try)
+do_lock_pp(struct thread *td, struct umutex *m, uint32_t flags,
+    struct _umtx_time *timeout, int try)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq, *uq2;
 	struct umtx_pi *pi;
 	uint32_t ceiling;
@@ -1970,6 +2025,10 @@
 	if ((error =3D umtx_key_get(m, TYPE_PP_UMUTEX, GET_SHARE(flags),
 	    &uq->uq_key)) !=3D 0)
 		return (error);
+
+	if (timeout !=3D NULL)
+		abs_timeout_init2(&timo, timeout);
+
 	su =3D (priv_check(td, PRIV_SCHED_RTPRIO) =3D=3D 0);
 	for (;;) {
 		old_inherited_pri =3D uq->uq_inherited_pri;
@@ -2033,7 +2092,8 @@
 		umtxq_lock(&uq->uq_key);
 		umtxq_insert(uq);
 		umtxq_unbusy(&uq->uq_key);
-		error =3D umtxq_sleep(uq, "umtxpp", timo);
+		error =3D umtxq_sleep(uq, "umtxpp", timeout =3D=3D NULL ?
+		    NULL : &timo);
 		umtxq_remove(uq);
 		umtxq_unlock(&uq->uq_key);
=20
@@ -2233,7 +2293,7 @@
 		umtxq_lock(&uq->uq_key);
 		umtxq_insert(uq);
 		umtxq_unbusy(&uq->uq_key);
-		error =3D umtxq_sleep(uq, "umtxpp", 0);
+		error =3D umtxq_sleep(uq, "umtxpp", NULL);
 		umtxq_remove(uq);
 		umtxq_unlock(&uq->uq_key);
 	}
@@ -2248,29 +2308,13 @@
 	return (error);
 }
=20
-static int
-_do_lock_umutex(struct thread *td, struct umutex *m, int flags, int timo,
-	int mode)
-{
-	switch(flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT)) {
-	case 0:
-		return (_do_lock_normal(td, m, flags, timo, mode));
-	case UMUTEX_PRIO_INHERIT:
-		return (_do_lock_pi(td, m, flags, timo, mode));
-	case UMUTEX_PRIO_PROTECT:
-		return (_do_lock_pp(td, m, flags, timo, mode));
-	}
-	return (EINVAL);
-}
-
 /*
  * Lock a userland POSIX mutex.
  */
 static int
 do_lock_umutex(struct thread *td, struct umutex *m,
-	struct _umtx_time *timeout, int mode)
+    struct _umtx_time *timeout, int mode)
 {
-	struct timespec cts, ets, tts;
 	uint32_t flags;
 	int error;
=20
@@ -2278,32 +2322,23 @@
 	if (flags =3D=3D -1)
 		return (EFAULT);
=20
+	switch(flags & (UMUTEX_PRIO_INHERIT | UMUTEX_PRIO_PROTECT)) {
+	case 0:
+		error =3D do_lock_normal(td, m, flags, timeout, mode);
+		break;
+	case UMUTEX_PRIO_INHERIT:
+		error =3D do_lock_pi(td, m, flags, timeout, mode);
+		break;
+	case UMUTEX_PRIO_PROTECT:
+		error =3D do_lock_pp(td, m, flags, timeout, mode);
+		break;
+	default:
+		return (EINVAL);
+	}
 	if (timeout =3D=3D NULL) {
-		error =3D _do_lock_umutex(td, m, flags, 0, mode);
-		/* Mutex locking is restarted if it is interrupted. */
 		if (error =3D=3D EINTR && mode !=3D _UMUTEX_WAIT)
 			error =3D ERESTART;
 	} else {
-		kern_clock_gettime(td, timeout->_clockid, &cts);
-		if ((timeout->_flags & UMTX_ABSTIME) =3D=3D 0) {
-			ets =3D cts;
-			timespecadd(&ets, &timeout->_timeout);
-			tts =3D timeout->_timeout;
-		} else {
-			ets =3D timeout->_timeout;
-			tts =3D timeout->_timeout;
-			timespecsub(&tts, &cts);
-		}
-		for (;;) {
-			error =3D _do_lock_umutex(td, m, flags, tstohz(&tts), mode);
-			if (error !=3D ETIMEDOUT)
-				break;
-			kern_clock_gettime(td, timeout->_clockid, &cts);
-			if (timespeccmp(&cts, &ets, >=3D))
-				break;
-			tts =3D ets;
-			timespecsub(&tts, &cts);
-		}
 		/* Timed-locking is not restarted. */
 		if (error =3D=3D ERESTART)
 			error =3D EINTR;
@@ -2339,8 +2374,8 @@
 do_cv_wait(struct thread *td, struct ucond *cv, struct umutex *m,
 	struct timespec *timeout, u_long wflags)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
-	struct timespec cts, ets, tts;
 	uint32_t flags;
 	uint32_t clockid;
 	int error;
@@ -2379,35 +2414,15 @@
 	umtxq_unlock(&uq->uq_key);
=20
 	error =3D do_unlock_umutex(td, m);
+
+	if (timeout !=3D NULL)
+		abs_timeout_init(&timo, clockid, ((wflags & CVWAIT_ABSTIME) !=3D 0),
+			timeout);
 =09
 	umtxq_lock(&uq->uq_key);
 	if (error =3D=3D 0) {
-		if (timeout =3D=3D NULL) {
-			error =3D umtxq_sleep(uq, "ucond", 0);
-		} else {
-			if ((wflags & CVWAIT_ABSTIME) =3D=3D 0) {
-				kern_clock_gettime(td, clockid, &ets);
-				timespecadd(&ets, timeout);
-				tts =3D *timeout;
-			} else { /* absolute time */
-				ets =3D *timeout;
-				tts =3D *timeout;
-				kern_clock_gettime(td, clockid, &cts);
-				timespecsub(&tts, &cts);
-			}
-			for (;;) {
-				error =3D umtxq_sleep(uq, "ucond", tstohz(&tts));
-				if (error !=3D ETIMEDOUT)
-					break;
-				kern_clock_gettime(td, clockid, &cts);
-				if (timespeccmp(&cts, &ets, >=3D)) {
-					error =3D ETIMEDOUT;
-					break;
-				}
-				tts =3D ets;
-				timespecsub(&tts, &cts);
-			}
-		}
+		error =3D umtxq_sleep(uq, "ucond", timeout =3D=3D NULL ?
+		    NULL : &timo);
 	}
=20
 	if ((uq->uq_flags & UQF_UMTXQ) =3D=3D 0)
@@ -2496,8 +2511,9 @@
 }
=20
 static int
-do_rw_rdlock(struct thread *td, struct urwlock *rwlock, long fflag, int ti=
mo)
+do_rw_rdlock(struct thread *td, struct urwlock *rwlock, long fflag, struct=
 _umtx_time *timeout)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
 	uint32_t flags, wrflags;
 	int32_t state, oldstate;
@@ -2510,6 +2526,9 @@
 	if (error !=3D 0)
 		return (error);
=20
+	if (timeout !=3D NULL)
+		abs_timeout_init2(&timo, timeout);
+
 	wrflags =3D URWLOCK_WRITE_OWNER;
 	if (!(fflag & URWLOCK_PREFER_READER) && !(flags & URWLOCK_PREFER_READER))
 		wrflags |=3D URWLOCK_WRITE_WAITERS;
@@ -2570,7 +2589,8 @@
 			umtxq_insert(uq);
 			umtxq_unbusy(&uq->uq_key);
=20
-			error =3D umtxq_sleep(uq, "urdlck", timo);
+			error =3D umtxq_sleep(uq, "urdlck", timeout =3D=3D NULL ?
+			    NULL : &timo);
=20
 			umtxq_busy(&uq->uq_key);
 			umtxq_remove(uq);
@@ -2599,43 +2619,15 @@
 		umtxq_unlock(&uq->uq_key);
 	}
 	umtx_key_release(&uq->uq_key);
-	return (error);
-}
-
-static int
-do_rw_rdlock2(struct thread *td, void *obj, long val, struct _umtx_time *t=
imeout)
-{
-	struct timespec cts, ets, tts;
-	int error;
-
-	kern_clock_gettime(td, timeout->_clockid, &cts);
-	if ((timeout->_flags & UMTX_ABSTIME) =3D=3D 0) {
-		ets =3D cts;
-		timespecadd(&ets, &timeout->_timeout);
-		tts =3D timeout->_timeout;
-	} else {
-		ets =3D timeout->_timeout;
-		tts =3D timeout->_timeout;
-		timespecsub(&tts, &cts);
-	}
-	for (;;) {
-		error =3D do_rw_rdlock(td, obj, val, tstohz(&tts));
-		if (error !=3D ETIMEDOUT)
-			break;
-		kern_clock_gettime(td, timeout->_clockid, &cts);
-		if (timespeccmp(&cts, &ets, >=3D))
-			break;
-		tts =3D ets;
-		timespecsub(&tts, &cts);
-	}
 	if (error =3D=3D ERESTART)
 		error =3D EINTR;
 	return (error);
 }
=20
 static int
-do_rw_wrlock(struct thread *td, struct urwlock *rwlock, int timo)
+do_rw_wrlock(struct thread *td, struct urwlock *rwlock, struct _umtx_time =
*timeout)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
 	uint32_t flags;
 	int32_t state, oldstate;
@@ -2649,6 +2641,9 @@
 	if (error !=3D 0)
 		return (error);
=20
+	if (timeout !=3D NULL)
+		abs_timeout_init2(&timo, timeout);
+
 	blocked_readers =3D 0;
 	for (;;) {
 		state =3D fuword32(__DEVOLATILE(int32_t *, &rwlock->rw_state));
@@ -2708,7 +2703,8 @@
 			umtxq_insert_queue(uq, UMTX_EXCLUSIVE_QUEUE);
 			umtxq_unbusy(&uq->uq_key);
=20
-			error =3D umtxq_sleep(uq, "uwrlck", timo);
+			error =3D umtxq_sleep(uq, "uwrlck", timeout =3D=3D NULL ?
+			    NULL : &timo);
=20
 			umtxq_busy(&uq->uq_key);
 			umtxq_remove_queue(uq, UMTX_EXCLUSIVE_QUEUE);
@@ -2739,35 +2735,6 @@
 	}
=20
 	umtx_key_release(&uq->uq_key);
-	return (error);
-}
-
-static int
-do_rw_wrlock2(struct thread *td, void *obj, struct _umtx_time *timeout)
-{
-	struct timespec cts, ets, tts;
-	int error;
-
-	kern_clock_gettime(td, timeout->_clockid, &cts);
-	if ((timeout->_flags & UMTX_ABSTIME) =3D=3D 0) {
-		ets =3D cts;
-		timespecadd(&ets, &timeout->_timeout);
-		tts =3D timeout->_timeout;
-	} else {
-		ets =3D timeout->_timeout;
-		tts =3D timeout->_timeout;
-		timespecsub(&tts, &cts);
-	}
-	for (;;) {
-		error =3D do_rw_wrlock(td, obj, tstohz(&tts));
-		if (error !=3D ETIMEDOUT)
-			break;
-		kern_clock_gettime(td, timeout->_clockid, &cts);
-		if (timespeccmp(&cts, &ets, >=3D))
-			break;
-		tts =3D ets;
-		timespecsub(&tts, &cts);
-	}
 	if (error =3D=3D ERESTART)
 		error =3D EINTR;
 	return (error);
@@ -2855,8 +2822,8 @@
 static int
 do_sem_wait(struct thread *td, struct _usem *sem, struct _umtx_time *timeo=
ut)
 {
+	struct abs_timeout timo;
 	struct umtx_q *uq;
-	struct timespec cts, ets, tts;
 	uint32_t flags, count;
 	int error;
=20
@@ -2865,13 +2832,15 @@
 	error =3D umtx_key_get(sem, TYPE_SEM, GET_SHARE(flags), &uq->uq_key);
 	if (error !=3D 0)
 		return (error);
+
+	if (timeout !=3D NULL)
+		abs_timeout_init2(&timo, timeout);
+
 	umtxq_lock(&uq->uq_key);
 	umtxq_busy(&uq->uq_key);
 	umtxq_insert(uq);
 	umtxq_unlock(&uq->uq_key);
-
 	casuword32(__DEVOLATILE(uint32_t *, &sem->_has_waiters), 0, 1);
-	rmb();
 	count =3D fuword32(__DEVOLATILE(uint32_t *, &sem->_count));
 	if (count !=3D 0) {
 		umtxq_lock(&uq->uq_key);
@@ -2881,37 +2850,10 @@
 		umtx_key_release(&uq->uq_key);
 		return (0);
 	}
-
 	umtxq_lock(&uq->uq_key);
 	umtxq_unbusy(&uq->uq_key);
=20
-	if (timeout =3D=3D NULL) {
-		error =3D umtxq_sleep(uq, "usem", 0);
-	} else {
-		umtxq_unlock(&uq->uq_key);
-		kern_clock_gettime(td, timeout->_clockid, &cts);
-		if ((timeout->_flags & UMTX_ABSTIME) =3D=3D 0) {
-			ets =3D cts;
-			timespecadd(&ets, &timeout->_timeout);
-		} else {
-			ets =3D timeout->_timeout;
-		}
-		umtxq_lock(&uq->uq_key);
-		for (;;) {
-			if (timespeccmp(&cts, &ets, >=3D)) {
-				error =3D ETIMEDOUT;
-				break;
-			}
-			tts =3D ets;
-			timespecsub(&tts, &cts);
-			error =3D umtxq_sleep(uq, "usem", tstohz(&tts));
-			if (error !=3D ETIMEDOUT)
-				break;
-			umtxq_unlock(&uq->uq_key);
-			kern_clock_gettime(td, timeout->_clockid, &cts);
-			umtxq_lock(&uq->uq_key);
-		}
-	}
+	error =3D umtxq_sleep(uq, "usem", timeout =3D=3D NULL ? NULL : &timo);
=20
 	if ((uq->uq_flags & UQF_UMTXQ) =3D=3D 0)
 		error =3D 0;
@@ -2932,7 +2874,7 @@
 do_sem_wake(struct thread *td, struct _usem *sem)
 {
 	struct umtx_key key;
-	int error, cnt, nwake;
+	int error, cnt;
 	uint32_t flags;
=20
 	flags =3D fuword32(&sem->_flags);
@@ -2941,12 +2883,19 @@
 	umtxq_lock(&key);
 	umtxq_busy(&key);
 	cnt =3D umtxq_count(&key);
-	nwake =3D umtxq_signal(&key, 1);
-	if (cnt <=3D nwake) {
-		umtxq_unlock(&key);
-		error =3D suword32(
-		    __DEVOLATILE(uint32_t *, &sem->_has_waiters), 0);
-		umtxq_lock(&key);
+	if (cnt > 0) {
+		umtxq_signal(&key, 1);
+		/*
+		 * Check if count is greater than 0, this means the memory is
+		 * still being referenced by user code, so we can safely
+		 * update _has_waiters flag.
+		 */
+		if (cnt =3D=3D 1) {
+			umtxq_unlock(&key);
+			error =3D suword32(
+			    __DEVOLATILE(uint32_t *, &sem->_has_waiters), 0);
+			umtxq_lock(&key);
+		}
 	}
 	umtxq_unbusy(&key);
 	umtxq_unlock(&key);
@@ -2958,7 +2907,7 @@
 sys__umtx_lock(struct thread *td, struct _umtx_lock_args *uap)
     /* struct umtx *umtx */
 {
-	return _do_lock_umtx(td, uap->umtx, td->td_tid, 0);
+	return do_lock_umtx(td, uap->umtx, td->td_tid, 0);
 }
=20
 int
@@ -3224,7 +3173,7 @@
 		   (size_t)uap->uaddr1, &timeout);
 		if (error !=3D 0)
 			return (error);
-		error =3D do_rw_rdlock2(td, uap->obj, uap->val, &timeout);
+		error =3D do_rw_rdlock(td, uap->obj, uap->val, &timeout);
 	}
 	return (error);
 }
@@ -3244,7 +3193,7 @@
 		if (error !=3D 0)
 			return (error);
=20
-		error =3D do_rw_wrlock2(td, uap->obj, &timeout);
+		error =3D do_rw_wrlock(td, uap->obj, &timeout);
 	}
 	return (error);
 }
@@ -3280,6 +3229,12 @@
 	return do_sem_wake(td, uap->obj);
 }
=20
+static int
+__umtx_op_wake2_umutex(struct thread *td, struct _umtx_op_args *uap)
+{
+	return do_wake2_umutex(td, uap->obj, uap->val);
+}
+
 typedef int (*_umtx_op_func)(struct thread *td, struct _umtx_op_args *uap);
=20
 static _umtx_op_func op_table[] =3D {
@@ -3304,7 +3259,8 @@
 	__umtx_op_wake_umutex,		/* UMTX_OP_UMUTEX_WAKE */
 	__umtx_op_sem_wait,		/* UMTX_OP_SEM_WAIT */
 	__umtx_op_sem_wake,		/* UMTX_OP_SEM_WAKE */
-	__umtx_op_nwake_private		/* UMTX_OP_NWAKE_PRIVATE */
+	__umtx_op_nwake_private,	/* UMTX_OP_NWAKE_PRIVATE */
+	__umtx_op_wake2_umutex		/* UMTX_OP_UMUTEX_WAKE2 */
 };
=20
 int
@@ -3497,7 +3453,7 @@
 		    (size_t)uap->uaddr1, &timeout);
 		if (error !=3D 0)
 			return (error);
-		error =3D do_rw_rdlock2(td, uap->obj, uap->val, &timeout);
+		error =3D do_rw_rdlock(td, uap->obj, uap->val, &timeout);
 	}
 	return (error);
 }
@@ -3516,7 +3472,7 @@
 		    (size_t)uap->uaddr1, &timeout);
 		if (error !=3D 0)
 			return (error);
-		error =3D do_rw_wrlock2(td, uap->obj, &timeout);
+		error =3D do_rw_wrlock(td, uap->obj, &timeout);
 	}
 	return (error);
 }
@@ -3606,7 +3562,8 @@
 	__umtx_op_wake_umutex,		/* UMTX_OP_UMUTEX_WAKE */
 	__umtx_op_sem_wait_compat32,	/* UMTX_OP_SEM_WAIT */
 	__umtx_op_sem_wake,		/* UMTX_OP_SEM_WAKE */
-	__umtx_op_nwake_private32	/* UMTX_OP_NWAKE_PRIVATE */
+	__umtx_op_nwake_private32,	/* UMTX_OP_NWAKE_PRIVATE */
+	__umtx_op_wake2_umutex		/* UMTX_OP_UMUTEX_WAKE2 */
 };
=20
 int
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/sched_ule.c
--- a/head/sys/kern/sched_ule.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/sched_ule.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 232917 2012-03-13 08:18:54Z =
mav $");
+__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 234066 2012-04-09 18:24:58Z =
mav $");
=20
 #include "opt_hwpmc_hooks.h"
 #include "opt_kdtrace.h"
@@ -594,32 +594,34 @@
 	cpuset_t cpumask;
 	struct cpu_group *child;
 	struct tdq *tdq;
-	int cpu, i, hload, lload, load, total, rnd;
+	int cpu, i, hload, lload, load, total, rnd, *rndptr;
=20
 	total =3D 0;
 	cpumask =3D cg->cg_mask;
 	if (match & CPU_SEARCH_LOWEST) {
 		lload =3D INT_MAX;
-		low->cs_load =3D INT_MAX;
 		lgroup =3D *low;
 	}
 	if (match & CPU_SEARCH_HIGHEST) {
-		hload =3D -1;
-		high->cs_load =3D -1;
+		hload =3D INT_MIN;
 		hgroup =3D *high;
 	}
=20
 	/* Iterate through the child CPU groups and then remaining CPUs. */
-	for (i =3D 0, cpu =3D 0; i <=3D cg->cg_children; ) {
-		if (i >=3D cg->cg_children) {
-			while (cpu <=3D mp_maxid && !CPU_ISSET(cpu, &cpumask))
-				cpu++;
-			if (cpu > mp_maxid)
+	for (i =3D cg->cg_children, cpu =3D mp_maxid; i >=3D 0; ) {
+		if (i =3D=3D 0) {
+			while (cpu >=3D 0 && !CPU_ISSET(cpu, &cpumask))
+				cpu--;
+			if (cpu < 0)
 				break;
 			child =3D NULL;
 		} else
-			child =3D &cg->cg_child[i];
+			child =3D &cg->cg_child[i - 1];
=20
+		if (match & CPU_SEARCH_LOWEST)
+			lgroup.cs_cpu =3D -1;
+		if (match & CPU_SEARCH_HIGHEST)
+			hgroup.cs_cpu =3D -1;
 		if (child) {			/* Handle child CPU group. */
 			CPU_NAND(&cpumask, &child->cg_mask);
 			switch (match) {
@@ -636,23 +638,23 @@
 		} else {			/* Handle child CPU. */
 			tdq =3D TDQ_CPU(cpu);
 			load =3D tdq->tdq_load * 256;
-			rnd =3D DPCPU_SET(randomval,
-			    DPCPU_GET(randomval) * 69069 + 5) >> 26;
+			rndptr =3D DPCPU_PTR(randomval);
+			rnd =3D (*rndptr =3D *rndptr * 69069 + 5) >> 26;
 			if (match & CPU_SEARCH_LOWEST) {
 				if (cpu =3D=3D low->cs_prefer)
 					load -=3D 64;
 				/* If that CPU is allowed and get data. */
-				if (CPU_ISSET(cpu, &lgroup.cs_mask) &&
-				    tdq->tdq_lowpri > lgroup.cs_pri &&
-				    tdq->tdq_load <=3D lgroup.cs_limit) {
+				if (tdq->tdq_lowpri > lgroup.cs_pri &&
+				    tdq->tdq_load <=3D lgroup.cs_limit &&
+				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
 					lgroup.cs_cpu =3D cpu;
 					lgroup.cs_load =3D load - rnd;
 				}
 			}
 			if (match & CPU_SEARCH_HIGHEST)
-				if (CPU_ISSET(cpu, &hgroup.cs_mask) &&
-				    tdq->tdq_load >=3D hgroup.cs_limit &&
-				    tdq->tdq_transferable) {
+				if (tdq->tdq_load >=3D hgroup.cs_limit &&
+				    tdq->tdq_transferable &&
+				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
 					hgroup.cs_cpu =3D cpu;
 					hgroup.cs_load =3D load - rnd;
 				}
@@ -661,7 +663,7 @@
=20
 		/* We have info about child item. Compare it. */
 		if (match & CPU_SEARCH_LOWEST) {
-			if (lgroup.cs_load !=3D INT_MAX &&
+			if (lgroup.cs_cpu >=3D 0 &&
 			    (load < lload ||
 			     (load =3D=3D lload && lgroup.cs_load < low->cs_load))) {
 				lload =3D load;
@@ -670,17 +672,19 @@
 			}
 		}
 		if (match & CPU_SEARCH_HIGHEST)
-			if (hgroup.cs_load >=3D 0 &&
+			if (hgroup.cs_cpu >=3D 0 &&
 			    (load > hload ||
 			     (load =3D=3D hload && hgroup.cs_load > high->cs_load))) {
 				hload =3D load;
 				high->cs_cpu =3D hgroup.cs_cpu;
 				high->cs_load =3D hgroup.cs_load;
 			}
-		if (child)
-			i++;
-		else
-			cpu++;
+		if (child) {
+			i--;
+			if (i =3D=3D 0 && CPU_EMPTY(&cpumask))
+				break;
+		} else
+			cpu--;
 	}
 	return (total);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_bus.c
--- a/head/sys/kern/subr_bus.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_bus.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_bus.c 232265 2012-02-28 19:16:02Z j=
hb $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_bus.c 234152 2012-04-11 20:57:41Z j=
hb $");
=20
 #include "opt_bus.h"
=20
@@ -2571,12 +2571,13 @@
 void
 device_busy(device_t dev)
 {
-	if (dev->state < DS_ATTACHED)
+	if (dev->state < DS_ATTACHING)
 		panic("device_busy: called for unattached device");
 	if (dev->busy =3D=3D 0 && dev->parent)
 		device_busy(dev->parent);
 	dev->busy++;
-	dev->state =3D DS_BUSY;
+	if (dev->state =3D=3D DS_ATTACHED)
+		dev->state =3D DS_BUSY;
 }
=20
 /**
@@ -2585,14 +2586,16 @@
 void
 device_unbusy(device_t dev)
 {
-	if (dev->state !=3D DS_BUSY)
+	if (dev->busy !=3D 0 && dev->state !=3D DS_BUSY &&
+	    dev->state !=3D DS_ATTACHING)
 		panic("device_unbusy: called for non-busy device %s",
 		    device_get_nameunit(dev));
 	dev->busy--;
 	if (dev->busy =3D=3D 0) {
 		if (dev->parent)
 			device_unbusy(dev->parent);
-		dev->state =3D DS_ATTACHED;
+		if (dev->state =3D=3D DS_BUSY)
+			dev->state =3D DS_ATTACHED;
 	}
 }
=20
@@ -2828,6 +2831,7 @@
 	device_sysctl_init(dev);
 	if (!device_is_quiet(dev))
 		device_print_child(dev->parent, dev);
+	dev->state =3D DS_ATTACHING;
 	if ((error =3D DEVICE_ATTACH(dev)) !=3D 0) {
 		printf("device_attach: %s%d attach returned %d\n",
 		    dev->driver->name, dev->unit, error);
@@ -2835,11 +2839,15 @@
 			devclass_delete_device(dev->devclass, dev);
 		(void)device_set_driver(dev, NULL);
 		device_sysctl_fini(dev);
+		KASSERT(dev->busy =3D=3D 0, ("attach failed but busy"));
 		dev->state =3D DS_NOTPRESENT;
 		return (error);
 	}
 	device_sysctl_update(dev);
-	dev->state =3D DS_ATTACHED;
+	if (dev->busy)
+		dev->state =3D DS_BUSY;
+	else
+		dev->state =3D DS_ATTACHED;
 	dev->flags &=3D ~DF_DONENOMATCH;
 	devadded(dev);
 	return (0);
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_firmware.c
--- a/head/sys/kern/subr_firmware.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_firmware.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_firmware.c 227689 2011-11-19 00:20:=
28Z np $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_firmware.c 234201 2012-04-13 04:22:=
42Z adrian $");
=20
 #include <sys/param.h>
 #include <sys/kernel.h>
@@ -175,6 +175,9 @@
     unsigned int version, const struct firmware *parent)
 {
 	struct priv_fw *match, *frp;
+	char *str;
+
+	str =3D strdup(imagename, M_TEMP);
=20
 	mtx_lock(&firmware_mtx);
 	/*
@@ -185,16 +188,18 @@
 		mtx_unlock(&firmware_mtx);
 		printf("%s: image %s already registered!\n",
 			__func__, imagename);
+		free(str, M_TEMP);
 		return NULL;
 	}
 	if (frp =3D=3D NULL) {
 		mtx_unlock(&firmware_mtx);
 		printf("%s: cannot register image %s, firmware table full!\n",
 		    __func__, imagename);
+		free(str, M_TEMP);
 		return NULL;
 	}
 	bzero(frp, sizeof(frp));	/* start from a clean record */
-	frp->fw.name =3D imagename;
+	frp->fw.name =3D str;
 	frp->fw.data =3D data;
 	frp->fw.datasize =3D datasize;
 	frp->fw.version =3D version;
@@ -230,7 +235,7 @@
 		err =3D 0;
 	} else if (fp->refcnt !=3D 0) {	/* cannot unregister */
 		err =3D EBUSY;
-	}  else {
+	} else {
 		linker_file_t x =3D fp->file;	/* save value */
=20
 		/*
@@ -238,6 +243,7 @@
 		 * do not forget anything. Then restore 'file' which is
 		 * non-null for autoloaded images.
 		 */
+		free((void *) (uintptr_t) fp->fw.name, M_TEMP);
 		bzero(fp, sizeof(struct priv_fw));
 		fp->file =3D x;
 		err =3D 0;
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_kdb.c
--- a/head/sys/kern/subr_kdb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_kdb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_kdb.c 228632 2011-12-17 15:11:22Z a=
vg $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_kdb.c 234190 2012-04-12 17:43:59Z j=
hb $");
=20
 #include "opt_kdb.h"
 #include "opt_stack.h"
@@ -73,7 +73,7 @@
 static int	kdb_break_to_debugger =3D KDB_BREAK_TO_DEBUGGER;
 static int	kdb_alt_break_to_debugger =3D KDB_ALT_BREAK_TO_DEBUGGER;
=20
-KDB_BACKEND(null, NULL, NULL, NULL);
+KDB_BACKEND(null, NULL, NULL, NULL, NULL);
 SET_DECLARE(kdb_dbbe_set, struct kdb_dbbe);
=20
 static int kdb_sysctl_available(SYSCTL_HANDLER_ARGS);
@@ -376,6 +376,7 @@
 		struct stack st;
=20
 		printf("KDB: stack backtrace:\n");
+		stack_zero(&st);
 		stack_save(&st);
 		stack_print_ddb(&st);
 	}
@@ -383,6 +384,30 @@
 }
=20
 /*
+ * Similar to kdb_backtrace() except that it prints a backtrace of an
+ * arbitrary thread rather than the calling thread.
+ */
+void
+kdb_backtrace_thread(struct thread *td)
+{
+
+	if (kdb_dbbe !=3D NULL && kdb_dbbe->dbbe_trace_thread !=3D NULL) {
+		printf("KDB: stack backtrace of thread %d:\n", td->td_tid);
+		kdb_dbbe->dbbe_trace_thread(td);
+	}
+#ifdef STACK
+	else {
+		struct stack st;
+
+		printf("KDB: stack backtrace of thread %d:\n", td->td_tid);
+		stack_zero(&st);
+		stack_save_td(&st, td);
+		stack_print_ddb(&st);
+	}
+#endif
+}
+
+/*
  * Set/change the current backend.
  */
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_syscall.c
--- a/head/sys/kern/subr_syscall.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_syscall.c	Tue Apr 17 11:51:51 2012 +0300
@@ -42,7 +42,7 @@
 #include "opt_ktrace.h"
 #include "opt_kdtrace.h"
=20
-__FBSDID("$FreeBSD: head/sys/kern/subr_syscall.c 232240 2012-02-27 21:10:1=
0Z kib $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_syscall.c 234172 2012-04-12 10:48:4=
3Z kib $");
=20
 #include <sys/capability.h>
 #include <sys/ktr.h>
@@ -136,7 +136,8 @@
 		AUDIT_SYSCALL_EXIT(error, td);
=20
 		/* Save the latest error return value. */
-		td->td_errno =3D error;
+		if ((td->td_pflags & TDP_NERRNO) =3D=3D 0)
+			td->td_errno =3D error;
=20
 #ifdef KDTRACE_HOOKS
 		/*
@@ -191,9 +192,12 @@
 	    syscallname(p, sa->code), td, td->td_proc->p_pid, td->td_name);
=20
 #ifdef KTRACE
-	if (KTRPOINT(td, KTR_SYSRET))
-		ktrsysret(sa->code, error, td->td_retval[0]);
+	if (KTRPOINT(td, KTR_SYSRET)) {
+		ktrsysret(sa->code, (td->td_pflags & TDP_NERRNO) =3D=3D 0 ?
+		    error : td->td_errno, td->td_retval[0]);
+	}
 #endif
+	td->td_pflags &=3D ~TDP_NERRNO;
=20
 	if (p->p_flag & P_TRACED) {
 		traced =3D 1;
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_trap.c
--- a/head/sys/kern/subr_trap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_trap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -42,9 +42,10 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_trap.c 225942 2011-10-03 16:58:58Z =
kib $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_trap.c 233628 2012-03-28 20:58:30Z =
fabient $");
=20
 #include "opt_capsicum.h"
+#include "opt_hwpmc_hooks.h"
 #include "opt_ktrace.h"
 #include "opt_kdtrace.h"
 #include "opt_sched.h"
@@ -86,6 +87,10 @@
 #include <vm/pmap.h>
 #endif
=20
+#ifdef	HWPMC_HOOKS
+#include <sys/pmckern.h>
+#endif
+
 #include <security/mac/mac_framework.h>
=20
 /*
@@ -192,6 +197,11 @@
 		td->td_profil_ticks =3D 0;
 		td->td_pflags &=3D ~TDP_OWEUPC;
 	}
+#ifdef HWPMC_HOOKS
+	/* Handle Software PMC callchain capture. */
+	if (PMC_IS_PENDING_CALLCHAIN(td))
+		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_USER_CALLCHAIN_SOFT, (void *) framep);
+#endif
 	if (flags & TDF_ALRMPEND) {
 		PROC_LOCK(p);
 		kern_psignal(p, SIGVTALRM);
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_turnstile.c
--- a/head/sys/kern/subr_turnstile.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_turnstile.c	Tue Apr 17 11:51:51 2012 +0300
@@ -57,7 +57,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_turnstile.c 227309 2011-11-07 15:43=
:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_turnstile.c 234303 2012-04-14 23:59=
:58Z davide $");
=20
 #include "opt_ddb.h"
 #include "opt_turnstile_profiling.h"
@@ -65,6 +65,7 @@
=20
 #include <sys/param.h>
 #include <sys/systm.h>
+#include <sys/kdb.h>
 #include <sys/kernel.h>
 #include <sys/ktr.h>
 #include <sys/lock.h>
@@ -78,7 +79,6 @@
 #include <vm/uma.h>
=20
 #ifdef DDB
-#include <sys/kdb.h>
 #include <ddb/ddb.h>
 #include <sys/lockmgr.h>
 #include <sys/sx.h>
@@ -143,7 +143,7 @@
 static SYSCTL_NODE(_debug_turnstile, OID_AUTO, chains, CTLFLAG_RD, 0,
     "turnstile chain stats");
 SYSCTL_UINT(_debug_turnstile, OID_AUTO, max_depth, CTLFLAG_RD,
-    &turnstile_max_depth, 0, "maxmimum depth achieved of a single chain");
+    &turnstile_max_depth, 0, "maximum depth achieved of a single chain");
 #endif
 static struct mtx td_contested_lock;
 static struct turnstile_chain turnstile_chains[TC_TABLESIZE];
@@ -217,9 +217,7 @@
 			printf(
 		"Sleeping thread (tid %d, pid %d) owns a non-sleepable lock\n",
 			    td->td_tid, td->td_proc->p_pid);
-#ifdef DDB
-			db_trace_thread(td, -1);
-#endif
+			kdb_backtrace_thread(td);
 			panic("sleeping thread");
 		}
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_uio.c
--- a/head/sys/kern/subr_uio.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_uio.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_uio.c 231949 2012-02-21 01:05:12Z k=
ib $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_uio.c 233291 2012-03-22 04:52:51Z a=
lc $");
=20
 #include "opt_zero.h"
=20
@@ -187,8 +187,12 @@
=20
 	/* XXX does it make a sense to set TDP_DEADLKTREAT for UIO_SYSSPACE ? */
 	newflags =3D TDP_DEADLKTREAT;
-	if (uio->uio_segflg =3D=3D UIO_USERSPACE && nofault)
-		newflags |=3D TDP_NOFAULTING;
+	if (uio->uio_segflg =3D=3D UIO_USERSPACE && nofault) {
+		/*
+		 * Fail if a non-spurious page fault occurs.
+		 */
+		newflags |=3D TDP_NOFAULTING | TDP_RESETSPUR;
+	}
 	save =3D curthread_pflags_set(newflags);
=20
 	while (n > 0 && uio->uio_resid) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/subr_witness.c
--- a/head/sys/kern/subr_witness.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/subr_witness.c	Tue Apr 17 11:51:51 2012 +0300
@@ -85,7 +85,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_witness.c 229873 2012-01-09 19:34:1=
2Z jhb $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_witness.c 233937 2012-04-06 06:53:5=
8Z melifaro $");
=20
 #include "opt_ddb.h"
 #include "opt_hwpmc_hooks.h"
@@ -563,8 +563,8 @@
 	 * BPF
 	 */
 	{ "bpf global lock", &lock_class_mtx_sleep },
-	{ "bpf interface lock", &lock_class_mtx_sleep },
-	{ "bpf cdev lock", &lock_class_mtx_sleep },
+	{ "bpf interface lock", &lock_class_rw },
+	{ "bpf cdev lock", &lock_class_rw },
 	{ NULL, NULL },
 	/*
 	 * NFS server
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/sys_pipe.c
--- a/head/sys/kern/sys_pipe.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/sys_pipe.c	Tue Apr 17 11:51:51 2012 +0300
@@ -90,7 +90,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/sys_pipe.c 232821 2012-03-11 12:19:58Z k=
ib $");
+__FBSDID("$FreeBSD: head/sys/kern/sys_pipe.c 234352 2012-04-16 21:22:02Z j=
kim $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -129,6 +129,9 @@
 #include <vm/vm_page.h>
 #include <vm/uma.h>
=20
+/* XXX */
+int	do_pipe(struct thread *td, int fildes[2], int flags);
+
 /*
  * Use this define if you want to disable *fancy* VM things.  Expect an
  * approx 30% decrease in transfer rate.  This could be useful for
@@ -405,11 +408,18 @@
 int
 kern_pipe(struct thread *td, int fildes[2])
 {
+
+	return (do_pipe(td, fildes, 0));
+}
+
+int
+do_pipe(struct thread *td, int fildes[2], int flags)
+{
 	struct filedesc *fdp;=20
 	struct file *rf, *wf;
 	struct pipe *rpipe, *wpipe;
 	struct pipepair *pp;
-	int fd, error;
+	int fd, fflags, error;
=20
 	fdp =3D td->td_proc->p_fd;
 	error =3D pipe_paircreate(td, &pp);
@@ -417,7 +427,7 @@
 		return (error);
 	rpipe =3D &pp->pp_rpipe;
 	wpipe =3D &pp->pp_wpipe;
-	error =3D falloc(td, &rf, &fd, 0);
+	error =3D falloc(td, &rf, &fd, flags);
 	if (error) {
 		pipeclose(rpipe);
 		pipeclose(wpipe);
@@ -426,14 +436,18 @@
 	/* An extra reference on `rf' has been held for us by falloc(). */
 	fildes[0] =3D fd;
=20
+	fflags =3D FREAD | FWRITE;
+	if ((flags & O_NONBLOCK) !=3D 0)
+		fflags |=3D FNONBLOCK;
+
 	/*
 	 * Warning: once we've gotten past allocation of the fd for the
 	 * read-side, we can only drop the read side via fdrop() in order
 	 * to avoid races against processes which manage to dup() the read
 	 * side while we are blocked trying to allocate the write side.
 	 */
-	finit(rf, FREAD | FWRITE, DTYPE_PIPE, rpipe, &pipeops);
-	error =3D falloc(td, &wf, &fd, 0);
+	finit(rf, fflags, DTYPE_PIPE, rpipe, &pipeops);
+	error =3D falloc(td, &wf, &fd, flags);
 	if (error) {
 		fdclose(fdp, rf, fildes[0], td);
 		fdrop(rf, td);
@@ -442,7 +456,7 @@
 		return (error);
 	}
 	/* An extra reference on `wf' has been held for us by falloc(). */
-	finit(wf, FREAD | FWRITE, DTYPE_PIPE, wpipe, &pipeops);
+	finit(wf, fflags, DTYPE_PIPE, wpipe, &pipeops);
 	fdrop(wf, td);
 	fildes[1] =3D fd;
 	fdrop(rf, td);
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/uipc_shm.c
--- a/head/sys/kern/uipc_shm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/uipc_shm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -42,7 +42,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/uipc_shm.c 229821 2012-01-08 20:09:26Z a=
lc $");
+__FBSDID("$FreeBSD: head/sys/kern/uipc_shm.c 233760 2012-04-01 18:22:48Z j=
hb $");
=20
 #include "opt_capsicum.h"
=20
@@ -468,6 +468,7 @@
 	map->sm_path =3D path;
 	map->sm_fnv =3D fnv;
 	map->sm_shmfd =3D shm_hold(shmfd);
+	shmfd->shm_path =3D path;
 	LIST_INSERT_HEAD(SHM_HASH(fnv), map, sm_link);
 }
=20
@@ -490,6 +491,7 @@
 			    FREAD | FWRITE);
 			if (error)
 				return (error);
+			map->sm_shmfd->shm_path =3D NULL;
 			LIST_REMOVE(map, sm_link);
 			shm_drop(map->sm_shmfd);
 			free(map->sm_path, M_SHMFD);
@@ -844,3 +846,15 @@
 	VM_OBJECT_UNLOCK(obj);
 	return (0);
 }
+
+void
+shm_path(struct shmfd *shmfd, char *path, size_t size)
+{
+
+	if (shmfd->shm_path =3D=3D NULL)
+		return;
+	sx_slock(&shm_dict_lock);
+	if (shmfd->shm_path !=3D NULL)
+		strlcpy(path, shmfd->shm_path, size);
+	sx_sunlock(&shm_dict_lock);
+}
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/uipc_socket.c
--- a/head/sys/kern/uipc_socket.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/uipc_socket.c	Tue Apr 17 11:51:51 2012 +0300
@@ -101,7 +101,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/uipc_socket.c 232179 2012-02-26 13:55:43=
Z kib $");
+__FBSDID("$FreeBSD: head/sys/kern/uipc_socket.c 233850 2012-04-03 18:38:00=
Z np $");
=20
 #include "opt_inet.h"
 #include "opt_inet6.h"
@@ -2504,20 +2504,19 @@
 		case SO_SETFIB:
 			error =3D sooptcopyin(sopt, &optval, sizeof optval,
 					    sizeof optval);
+			if (error)
+				goto bad;
+
 			if (optval < 0 || optval >=3D rt_numfibs) {
 				error =3D EINVAL;
 				goto bad;
 			}
 			if (((so->so_proto->pr_domain->dom_family =3D=3D PF_INET) ||
 			   (so->so_proto->pr_domain->dom_family =3D=3D PF_INET6) ||
-			   (so->so_proto->pr_domain->dom_family =3D=3D PF_ROUTE))) {
+			   (so->so_proto->pr_domain->dom_family =3D=3D PF_ROUTE)))
 				so->so_fibnum =3D optval;
-				/* Note: ignore error */
-				if (so->so_proto->pr_ctloutput)
-					(*so->so_proto->pr_ctloutput)(so, sopt);
-			} else {
+			else
 				so->so_fibnum =3D 0;
-			}
 			break;
=20
 		case SO_USER_COOKIE:
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/vfs_mount.c
--- a/head/sys/kern/vfs_mount.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/vfs_mount.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/vfs_mount.c 232709 2012-03-09 00:12:05Z =
kib $");
+__FBSDID("$FreeBSD: head/sys/kern/vfs_mount.c 233999 2012-04-07 15:27:34Z =
gleb $");
=20
 #include "opt_vfs_allow_nonmpsafe.h"
=20
@@ -1520,6 +1520,48 @@
 	return (-1);
 }
=20
+int
+vfs_getopt_size(struct vfsoptlist *opts, const char *name, off_t *value)
+{
+	char *opt_value, *vtp;
+	quad_t iv;
+	int error, opt_len;
+
+	error =3D vfs_getopt(opts, name, (void **)&opt_value, &opt_len);
+	if (error !=3D 0)
+		return (error);
+	if (opt_len =3D=3D 0 || opt_value =3D=3D NULL)
+		return (EINVAL);
+	if (opt_value[0] =3D=3D '\0' || opt_value[opt_len - 1] !=3D '\0')
+		return (EINVAL);
+	iv =3D strtoq(opt_value, &vtp, 0);
+	if (vtp =3D=3D opt_value || (vtp[0] !=3D '\0' && vtp[1] !=3D '\0'))
+		return (EINVAL);
+	if (iv < 0)
+		return (EINVAL);
+	switch (vtp[0]) {
+	case 't':
+	case 'T':
+		iv *=3D 1024;
+	case 'g':
+	case 'G':
+		iv *=3D 1024;
+	case 'm':
+	case 'M':
+		iv *=3D 1024;
+	case 'k':
+	case 'K':
+		iv *=3D 1024;
+	case '\0':
+		break;
+	default:
+		return (EINVAL);
+	}
+	*value =3D iv;
+
+	return (0);
+}
+
 char *
 vfs_getopts(struct vfsoptlist *opts, const char *name, int *error)
 {
diff -r 428842767fa6 -r f2935497fa04 head/sys/kern/vfs_subr.c
--- a/head/sys/kern/vfs_subr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/kern/vfs_subr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/vfs_subr.c 232709 2012-03-09 00:12:05Z k=
ib $");
+__FBSDID("$FreeBSD: head/sys/kern/vfs_subr.c 234158 2012-04-11 23:01:11Z m=
ckusick $");
=20
 #include "opt_ddb.h"
 #include "opt_watchdog.h"
@@ -103,7 +103,6 @@
 static void	syncer_shutdown(void *arg, int howto);
 static int	vtryrecycle(struct vnode *vp);
 static void	vbusy(struct vnode *vp);
-static void	vinactive(struct vnode *, struct thread *);
 static void	v_incr_usecount(struct vnode *);
 static void	v_decr_usecount(struct vnode *);
 static void	v_decr_useonly(struct vnode *);
@@ -2401,7 +2400,7 @@
  * OWEINACT tracks whether a vnode missed a call to inactive due to a
  * failed lock upgrade.
  */
-static void
+void
 vinactive(struct vnode *vp, struct thread *td)
 {
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/libkern/crc32.c
--- a/head/sys/libkern/crc32.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/libkern/crc32.c	Tue Apr 17 11:51:51 2012 +0300
@@ -43,12 +43,12 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/libkern/crc32.c 233517 2012-03-26 18:22:04Z m=
arius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
=20
-uint32_t crc32_tab[] =3D {
+const uint32_t crc32_tab[] =3D {
 	0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
 	0xe963a535, 0x9e6495a3,	0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
 	0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
@@ -134,7 +134,7 @@
 /*                                                               */
 /*****************************************************************/
=20
-static uint32_t crc32Table[256] =3D {
+static const uint32_t crc32Table[256] =3D {
 	0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L,
 	0xC79A971FL, 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL,
 	0x8AD958CFL, 0x78B2DBCCL, 0x6BE22838L, 0x9989AB3BL,
@@ -240,7 +240,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o32[256] =3D
+static const uint32_t sctp_crc_tableil8_o32[256] =3D
 {
 	0x00000000, 0xF26B8303, 0xE13B70F7, 0x1350F3F4, 0xC79A971F, 0x35F1141C, 0=
x26A1E7E8, 0xD4CA64EB,
 	0x8AD958CF, 0x78B2DBCC, 0x6BE22838, 0x9989AB3B, 0x4D43CFD0, 0xBF284CD3, 0=
xAC78BF27, 0x5E133C24,
@@ -296,7 +296,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o40[256] =3D
+static const uint32_t sctp_crc_tableil8_o40[256] =3D
 {
 	0x00000000, 0x13A29877, 0x274530EE, 0x34E7A899, 0x4E8A61DC, 0x5D28F9AB, 0=
x69CF5132, 0x7A6DC945,
 	0x9D14C3B8, 0x8EB65BCF, 0xBA51F356, 0xA9F36B21, 0xD39EA264, 0xC03C3A13, 0=
xF4DB928A, 0xE7790AFD,
@@ -352,7 +352,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o48[256] =3D
+static const uint32_t sctp_crc_tableil8_o48[256] =3D
 {
 	0x00000000, 0xA541927E, 0x4F6F520D, 0xEA2EC073, 0x9EDEA41A, 0x3B9F3664, 0=
xD1B1F617, 0x74F06469,
 	0x38513EC5, 0x9D10ACBB, 0x773E6CC8, 0xD27FFEB6, 0xA68F9ADF, 0x03CE08A1, 0=
xE9E0C8D2, 0x4CA15AAC,
@@ -408,7 +408,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o56[256] =3D
+static const uint32_t sctp_crc_tableil8_o56[256] =3D
 {
 	0x00000000, 0xDD45AAB8, 0xBF672381, 0x62228939, 0x7B2231F3, 0xA6679B4B, 0=
xC4451272, 0x1900B8CA,
 	0xF64463E6, 0x2B01C95E, 0x49234067, 0x9466EADF, 0x8D665215, 0x5023F8AD, 0=
x32017194, 0xEF44DB2C,
@@ -464,7 +464,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o64[256] =3D
+static const uint32_t sctp_crc_tableil8_o64[256] =3D
 {
 	0x00000000, 0x38116FAC, 0x7022DF58, 0x4833B0F4, 0xE045BEB0, 0xD854D11C, 0=
x906761E8, 0xA8760E44,
 	0xC5670B91, 0xFD76643D, 0xB545D4C9, 0x8D54BB65, 0x2522B521, 0x1D33DA8D, 0=
x55006A79, 0x6D1105D5,
@@ -520,7 +520,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o72[256] =3D
+static const uint32_t sctp_crc_tableil8_o72[256] =3D
 {
 	0x00000000, 0xEF306B19, 0xDB8CA0C3, 0x34BCCBDA, 0xB2F53777, 0x5DC55C6E, 0=
x697997B4, 0x8649FCAD,
 	0x6006181F, 0x8F367306, 0xBB8AB8DC, 0x54BAD3C5, 0xD2F32F68, 0x3DC34471, 0=
x097F8FAB, 0xE64FE4B2,
@@ -576,7 +576,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o80[256] =3D
+static const uint32_t sctp_crc_tableil8_o80[256] =3D
 {
 	0x00000000, 0x68032CC8, 0xD0065990, 0xB8057558, 0xA5E0C5D1, 0xCDE3E919, 0=
x75E69C41, 0x1DE5B089,
 	0x4E2DFD53, 0x262ED19B, 0x9E2BA4C3, 0xF628880B, 0xEBCD3882, 0x83CE144A, 0=
x3BCB6112, 0x53C84DDA,
@@ -632,7 +632,7 @@
  * File Name =3D ............................ 8x256_tables.c
  */
=20
-static uint32_t sctp_crc_tableil8_o88[256] =3D
+static const uint32_t sctp_crc_tableil8_o88[256] =3D
 {
 	0x00000000, 0x493C7D27, 0x9278FA4E, 0xDB448769, 0x211D826D, 0x6821FF4A, 0=
xB3657823, 0xFA590504,
 	0x423B04DA, 0x0B0779FD, 0xD043FE94, 0x997F83B3, 0x632686B7, 0x2A1AFB90, 0=
xF15E7CF9, 0xB86201DE,
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/atheros/apb.c
--- a/head/sys/mips/atheros/apb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/atheros/apb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/apb.c 233104 2012-03-18 01:43:41=
Z gonzo $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/apb.c 233318 2012-03-22 17:47:52=
Z gonzo $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -348,7 +348,6 @@
 	uint32_t reg, irq;
 	struct thread *td;
 	struct trapframe *tf;
-	register_t s;
=20
 	reg =3D ATH_READ_REG(AR71XX_MISC_INTR_STATUS);
 	for (irq =3D 0; irq < APB_NIRQS; irq++) {
@@ -373,28 +372,12 @@
 					td =3D PCPU_GET(curthread);
 					tf =3D td->td_intr_frame;
=20
-					s =3D intr_disable();
+					if (pmc_intr)
+						(*pmc_intr)(PCPU_GET(cpuid), tf);
+
 					mips_intrcnt_inc(sc->sc_intr_counter[irq]);
=20
-					if (pmc_intr) {
-						/*
-						 * Make sure at least one of counters=20
-						 * generated this interrupt
-						 */
-						if (!(*pmc_intr)(PCPU_GET(cpuid), tf)) {
-							intr_restore(s);
-							continue;
-						}
-					}
-
-					intr_restore(s);
-
-					if (pmc_hook && (td->td_pflags & TDP_CALLCHAIN))
-						pmc_hook(PCPU_GET(curthread),
-							PMC_FN_USER_CALLCHAIN, tf);
-			=09
 					continue;
-
 				}
 				/* Ignore timer interrupts */
 				if (irq !=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/atheros/ar71xx_chip.c
--- a/head/sys/mips/atheros/ar71xx_chip.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/atheros/ar71xx_chip.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_chip.c 233081 2012-03-17 =
07:25:23Z adrian $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_chip.c 234326 2012-04-15 =
22:34:22Z adrian $");
=20
 #include "opt_ddb.h"
=20
@@ -137,7 +137,7 @@
 	return ((reg & mask) =3D=3D mask);
 }
=20
-static void
+void
 ar71xx_chip_set_mii_speed(uint32_t unit, uint32_t speed)
 {
 	uint32_t val, reg, ctrl;
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/atheros/ar71xx_chip.h
--- a/head/sys/mips/atheros/ar71xx_chip.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/atheros/ar71xx_chip.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,11 +24,12 @@
  * SUCH DAMAGE.
  */
=20
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/mips/atheros/ar71xx_chip.h 234326 2012-04-15 22:34:2=
2Z adrian $ */
=20
 #ifndef	__AR71XX_CHIP_H__
 #define	__AR71XX_CHIP_H__
=20
 extern struct ar71xx_cpu_def ar71xx_chip_def;
+extern void ar71xx_chip_set_mii_speed(uint32_t unit, uint32_t speed);
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/atheros/ar71xx_pci.c
--- a/head/sys/mips/atheros/ar71xx_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/atheros/ar71xx_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_pci.c 230195 2012-01-16 0=
5:07:32Z adrian $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_pci.c 234366 2012-04-17 0=
1:34:49Z adrian $");
=20
 #include "opt_ar71xx.h"
=20
@@ -39,6 +39,8 @@
 #include <sys/kernel.h>
 #include <sys/module.h>
 #include <sys/rman.h>
+#include <sys/lock.h>
+#include <sys/mutex.h>
=20
 #include <vm/vm.h>
 #include <vm/pmap.h>
@@ -60,13 +62,22 @@
=20
 #include <mips/atheros/ar71xx_cpudef.h>
=20
-#undef AR71XX_PCI_DEBUG
-#ifdef AR71XX_PCI_DEBUG
-#define dprintf printf
+#ifdef	AR71XX_ATH_EEPROM
+#include <sys/linker.h>
+#include <sys/firmware.h>
+#endif	/* AR71XX_ATH_EEPROM */
+
+#undef	AR71XX_PCI_DEBUG
+#ifdef	AR71XX_PCI_DEBUG
+#define	dprintf printf
 #else
-#define dprintf(x, arg...)
+#define	dprintf(x, arg...)
 #endif
=20
+struct mtx ar71xx_pci_mtx;
+MTX_SYSINIT(ar71xx_pci_mtx, &ar71xx_pci_mtx, "ar71xx PCI space mutex",
+    MTX_SPIN);
+
 struct ar71xx_pci_softc {
 	device_t		sc_dev;
=20
@@ -86,39 +97,42 @@
 		    void *);
 static int ar71xx_pci_intr(void *);
=20
-static void=20
+static void
 ar71xx_pci_mask_irq(void *source)
 {
 	uint32_t reg;
 	unsigned int irq =3D (unsigned int)source;
=20
+	/* XXX is the PCI lock required here? */
 	reg =3D ATH_READ_REG(AR71XX_PCI_INTR_MASK);
 	/* flush */
 	reg =3D ATH_READ_REG(AR71XX_PCI_INTR_MASK);
 	ATH_WRITE_REG(AR71XX_PCI_INTR_MASK, reg & ~(1 << irq));
 }
=20
-static void=20
+static void
 ar71xx_pci_unmask_irq(void *source)
 {
 	uint32_t reg;
 	unsigned int irq =3D (unsigned int)source;
=20
+	/* XXX is the PCI lock required here? */
 	reg =3D ATH_READ_REG(AR71XX_PCI_INTR_MASK);
 	ATH_WRITE_REG(AR71XX_PCI_INTR_MASK, reg | (1 << irq));
 	/* flush */
 	reg =3D ATH_READ_REG(AR71XX_PCI_INTR_MASK);
 }
=20
-/*=20
- * get bitmask for bytes of interest:=20
- *   0 - we want this byte, 1 - ignore it. e.g: we read 1 byte=20
+/*
+ * get bitmask for bytes of interest:
+ *   0 - we want this byte, 1 - ignore it. e.g: we read 1 byte
  *   from register 7. Bitmask would be: 0111
  */
 static uint32_t
 ar71xx_get_bytes_to_read(int reg, int bytes)
 {
 	uint32_t bytes_to_read =3D 0;
+
 	if ((bytes % 4) =3D=3D 0)
 		bytes_to_read =3D 0;
 	else if ((bytes % 4) =3D=3D 1)
@@ -131,10 +145,13 @@
 	return (bytes_to_read);
 }
=20
-static int=20
+static int
 ar71xx_pci_check_bus_error(void)
 {
 	uint32_t error, addr, has_errors =3D 0;
+
+	mtx_assert(&ar71xx_pci_mtx, MA_OWNED);
+
 	error =3D ATH_READ_REG(AR71XX_PCI_ERROR) & 0x3;
 	dprintf("%s: PCI error =3D %02x\n", __func__, error);
 	if (error) {
@@ -169,18 +186,20 @@
 	if (bus =3D=3D 0) {
 		return ((1 << slot) | (func << 8) | (reg & ~3));
 	} else {
-		return ((bus << 16) | (slot << 11) | (func << 8)=20
+		return ((bus << 16) | (slot << 11) | (func << 8)
 		    | (reg  & ~3) | 1);
 	}
 }
=20
 static int
-ar71xx_pci_conf_setup(int bus, int slot, int func, int reg, int bytes,=20
+ar71xx_pci_conf_setup(int bus, int slot, int func, int reg, int bytes,
     uint32_t cmd)
 {
 	uint32_t addr =3D ar71xx_pci_make_addr(bus, slot, func, (reg & ~3));
+
+	mtx_assert(&ar71xx_pci_mtx, MA_OWNED);
+
 	cmd |=3D (ar71xx_get_bytes_to_read(reg, bytes) << 4);
-=09
 	ATH_WRITE_REG(AR71XX_PCI_CONF_ADDR, addr);
 	ATH_WRITE_REG(AR71XX_PCI_CONF_CMD, cmd);
=20
@@ -191,63 +210,72 @@
 }
=20
 static uint32_t
-ar71xx_pci_read_config(device_t dev, u_int bus, u_int slot, u_int func,=20
+ar71xx_pci_read_config(device_t dev, u_int bus, u_int slot, u_int func,
     u_int reg, int bytes)
 {
 	uint32_t data;
-	uint32_t cmd, shift, mask;
+	uint32_t shift, mask;
=20
 	/* register access is 32-bit aligned */
 	shift =3D (reg & 3) * 8;
-	if (shift)
-		mask =3D (1 << shift) - 1;
+
+	/* Create a mask based on the width, post-shift */
+	if (bytes =3D=3D 2)
+		mask =3D 0xffff;
+	else if (bytes =3D=3D 1)
+		mask =3D 0xff;
 	else
 		mask =3D 0xffffffff;
=20
 	dprintf("%s: tag (%x, %x, %x) reg %d(%d)\n", __func__, bus, slot,=20
 	    func, reg, bytes);
=20
-	if ((bus =3D=3D 0) && (slot =3D=3D 0) && (func =3D=3D 0)) {
-		cmd =3D PCI_LCONF_CMD_READ | (reg & ~3);
-		ATH_WRITE_REG(AR71XX_PCI_LCONF_CMD, cmd);
-		data =3D ATH_READ_REG(AR71XX_PCI_LCONF_READ_DATA);
-	} else {
-		 if (ar71xx_pci_conf_setup(bus, slot, func, reg, bytes,=20
-		     PCI_CONF_CMD_READ) =3D=3D 0)
-			 data =3D ATH_READ_REG(AR71XX_PCI_CONF_READ_DATA);
-		 else
-			 data =3D -1;
-	}
+	mtx_lock_spin(&ar71xx_pci_mtx);
+	 if (ar71xx_pci_conf_setup(bus, slot, func, reg, bytes,=20
+	     PCI_CONF_CMD_READ) =3D=3D 0)
+		 data =3D ATH_READ_REG(AR71XX_PCI_CONF_READ_DATA);
+	 else
+		 data =3D -1;
+	mtx_unlock_spin(&ar71xx_pci_mtx);
=20
 	/* get request bytes from 32-bit word */
 	data =3D (data >> shift) & mask;
=20
- 	dprintf("%s: read 0x%x\n", __func__, data);
+	dprintf("%s: read 0x%x\n", __func__, data);
=20
 	return (data);
 }
=20
 static void
-ar71xx_pci_write_config(device_t dev, u_int bus, u_int slot, u_int func,=20
-    u_int reg, uint32_t data, int bytes)
+ar71xx_pci_local_write(device_t dev, uint32_t reg, uint32_t data, int byte=
s)
 {
 	uint32_t cmd;
=20
-	dprintf("%s: tag (%x, %x, %x) reg %d(%d)\n", __func__, bus, slot,=20
+	dprintf("%s: local write reg %d(%d)\n", __func__, reg, bytes);
+
+	data =3D data << (8*(reg % 4));
+	cmd =3D PCI_LCONF_CMD_WRITE | (reg & ~3);
+	cmd |=3D (ar71xx_get_bytes_to_read(reg, bytes) << 20);
+	mtx_lock_spin(&ar71xx_pci_mtx);
+	ATH_WRITE_REG(AR71XX_PCI_LCONF_CMD, cmd);
+	ATH_WRITE_REG(AR71XX_PCI_LCONF_WRITE_DATA, data);
+	mtx_unlock_spin(&ar71xx_pci_mtx);
+}
+
+static void
+ar71xx_pci_write_config(device_t dev, u_int bus, u_int slot, u_int func,
+    u_int reg, uint32_t data, int bytes)
+{
+
+	dprintf("%s: tag (%x, %x, %x) reg %d(%d)\n", __func__, bus, slot,
 	    func, reg, bytes);
=20
 	data =3D data << (8*(reg % 4));
-
-	if ((bus =3D=3D 0) && (slot =3D=3D 0) && (func =3D=3D 0)) {
-		cmd =3D PCI_LCONF_CMD_WRITE | (reg & ~3);
-		cmd |=3D ar71xx_get_bytes_to_read(reg, bytes) << 20;
-		ATH_WRITE_REG(AR71XX_PCI_LCONF_CMD, cmd);
-		ATH_WRITE_REG(AR71XX_PCI_LCONF_WRITE_DATA, data);
-	} else {
-		 if (ar71xx_pci_conf_setup(bus, slot, func, reg, bytes,=20
-		     PCI_CONF_CMD_WRITE) =3D=3D 0)
-			 ATH_WRITE_REG(AR71XX_PCI_CONF_WRITE_DATA, data);
-	}
+	mtx_lock_spin(&ar71xx_pci_mtx);
+	 if (ar71xx_pci_conf_setup(bus, slot, func, reg, bytes,
+	     PCI_CONF_CMD_WRITE) =3D=3D 0)
+		 ATH_WRITE_REG(AR71XX_PCI_CONF_WRITE_DATA, data);
+	mtx_unlock_spin(&ar71xx_pci_mtx);
 }
=20
 #ifdef	AR71XX_ATH_EEPROM
@@ -265,8 +293,9 @@
 	uint16_t *cal_data =3D (uint16_t *) MIPS_PHYS_TO_KSEG1(flash_addr);
 	uint32_t reg, val, bar0;
=20
-	printf("%s: flash_addr=3D%lx, cal_data=3D%p\n",
-	    __func__, flash_addr, cal_data);
+	if (bootverbose)
+		device_printf(dev, "%s: flash_addr=3D%lx, cal_data=3D%p\n",
+		    __func__, flash_addr, cal_data);
=20
 	/* XXX check 0xa55a */
 	/* Save bar(0) address - just to flush bar(0) (SoC WAR) ? */
@@ -283,7 +312,8 @@
 		reg =3D *cal_data++;
 		val =3D *cal_data++;
 		val |=3D (*cal_data++) << 16;
-		printf("  reg: %x, val=3D%x\n", reg, val);
+		if (bootverbose)
+			printf("  reg: %x, val=3D%x\n", reg, val);
=20
 		/* Write eeprom fixup data to device memory */
 		ATH_WRITE_REG(AR71XX_PCI_MEM_BASE + reg, val);
@@ -298,6 +328,62 @@
 	ar71xx_pci_write_config(dev, bus, slot, func, PCIR_BAR(0), bar0, 4);
 }
=20
+/*
+ * Take a copy of the EEPROM contents and squirrel it away in a firmware.
+ * The SPI flash will eventually cease to be memory-mapped, so we need
+ * to take a copy of this before the SPI driver initialises.
+ */
+static void
+ar71xx_pci_slot_create_eeprom_firmware(device_t dev, u_int bus, u_int slot,
+    u_int func, long int flash_addr)
+{
+	char buf[64];
+	uint16_t *cal_data =3D (uint16_t *) MIPS_PHYS_TO_KSEG1(flash_addr);
+	void *eeprom =3D NULL;
+	const struct firmware *fw =3D NULL;
+	int len;
+
+	snprintf(buf, sizeof(buf), "bus.%d.%d.%d.ath_fixup_size",
+	    bus, slot, func);
+
+	if (resource_int_value(device_get_name(dev), device_get_unit(dev),
+	    buf, &len) !=3D 0) {
+		device_printf(dev, "%s: missing hint '%s', aborting EEPROM\n",
+		    __func__, buf);
+		return;
+	}
+
+	device_printf(dev, "EEPROM firmware: 0x%lx @ %d bytes\n",
+	    flash_addr, len);
+
+	eeprom =3D malloc(len, M_DEVBUF, M_WAITOK | M_ZERO);
+	if (! eeprom) {
+		device_printf(dev,
+			    "%s: malloc failed for '%s', aborting EEPROM\n",
+			    __func__, buf);
+			return;
+	}
+
+	memcpy(eeprom, cal_data, len);
+
+	/*
+	 * Generate a flash EEPROM 'firmware' from the given memory
+	 * region.  Since the SPI controller will eventually
+	 * go into port-IO mode instead of memory-mapped IO
+	 * mode, a copy of the EEPROM contents is required.
+	 */
+	snprintf(buf, sizeof(buf), "%s.%d.bus.%d.%d.%d.eeprom_firmware",
+	    device_get_name(dev), device_get_unit(dev), bus, slot, func);
+	fw =3D firmware_register(buf, eeprom, len, 1, NULL);
+	if (fw =3D=3D NULL) {
+		device_printf(dev, "%s: firmware_register (%s) failed\n",
+		    __func__, buf);
+		free(eeprom, M_DEVBUF);
+		return;
+	}
+	device_printf(dev, "device EEPROM '%s' registered\n", buf);
+}
+
 static void
 ar71xx_pci_slot_fixup(device_t dev, u_int bus, u_int slot, u_int func)
 {
@@ -307,16 +393,19 @@
 	/*
 	 * Check whether the given slot has a hint to poke.
 	 */
-	printf("%s: checking dev %s, %d/%d/%d\n",
+	if (bootverbose)
+	device_printf(dev, "%s: checking dev %s, %d/%d/%d\n",
 	    __func__, device_get_nameunit(dev), bus, slot, func);
 	snprintf(buf, sizeof(buf), "bus.%d.%d.%d.ath_fixup_addr",
 	    bus, slot, func);
=20
 	if (resource_long_value(device_get_name(dev), device_get_unit(dev),
 	    buf, &flash_addr) =3D=3D 0) {
-		printf("%s: found fixupaddr at %lx: updating\n",
-		    __func__, flash_addr);
+		device_printf(dev, "found EEPROM at 0x%lx on %d.%d.%d\n",
+		    flash_addr, bus, slot, func);
 		ar71xx_pci_fixup(dev, bus, slot, func, flash_addr);
+		ar71xx_pci_slot_create_eeprom_firmware(dev, bus, slot, func,
+		    flash_addr);
 	}
 }
 #endif	/* AR71XX_ATH_EEPROM */
@@ -363,7 +452,7 @@
=20
 	if ((bus_setup_intr(dev, sc->sc_irq, INTR_TYPE_MISC,
 			    ar71xx_pci_intr, NULL, sc, &sc->sc_ih))) {
-		device_printf(dev,=20
+		device_printf(dev,
 		    "WARNING: unable to register interrupt handler\n");
 		return ENXIO;
 	}
@@ -386,13 +475,15 @@
 	ATH_WRITE_REG(AR71XX_PCI_WINDOW7, PCI_WINDOW7_CONF_ADDR);
 	DELAY(100000);
=20
+	mtx_lock_spin(&ar71xx_pci_mtx);
 	ar71xx_pci_check_bus_error();
+	mtx_unlock_spin(&ar71xx_pci_mtx);
=20
 	/* Fixup internal PCI bridge */
-	ar71xx_pci_write_config(dev, 0, 0, 0, PCIR_COMMAND,=20
-            PCIM_CMD_BUSMASTEREN | PCIM_CMD_MEMEN=20
+	ar71xx_pci_local_write(dev, PCIR_COMMAND,
+            PCIM_CMD_BUSMASTEREN | PCIM_CMD_MEMEN
 	    | PCIM_CMD_SERRESPEN | PCIM_CMD_BACKTOBACK
-	    | PCIM_CMD_PERRESPEN | PCIM_CMD_MWRICEN, 2);
+	    | PCIM_CMD_PERRESPEN | PCIM_CMD_MWRICEN, 4);
=20
 #ifdef	AR71XX_ATH_EEPROM
 	/*
@@ -409,7 +500,8 @@
 }
=20
 static int
-ar71xx_pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *r=
esult)
+ar71xx_pci_read_ivar(device_t dev, device_t child, int which,
+    uintptr_t *result)
 {
 	struct ar71xx_pci_softc *sc =3D device_get_softc(dev);
=20
@@ -426,7 +518,8 @@
 }
=20
 static int
-ar71xx_pci_write_ivar(device_t dev, device_t child, int which, uintptr_t r=
esult)
+ar71xx_pci_write_ivar(device_t dev, device_t child, int which,
+    uintptr_t result)
 {
 	struct ar71xx_pci_softc * sc =3D device_get_softc(dev);
=20
@@ -444,7 +537,7 @@
     u_long start, u_long end, u_long count, u_int flags)
 {
=20
-	struct ar71xx_pci_softc *sc =3D device_get_softc(bus);=09
+	struct ar71xx_pci_softc *sc =3D device_get_softc(bus);
 	struct resource *rv;
 	struct rman *rm;
=20
@@ -471,13 +564,10 @@
 			rman_release_resource(rv);
 			return (NULL);
 		}
-	}=20
-
-
+	}
 	return (rv);
 }
=20
-
 static int
 ar71xx_pci_activate_resource(device_t bus, device_t child, int type, int r=
id,
     struct resource *r)
@@ -493,16 +583,13 @@
 			break;
 		}
 	}
-
 	return (res);
 }
=20
-
-
 static int
 ar71xx_pci_setup_intr(device_t bus, device_t child, struct resource *ires,
-		int flags, driver_filter_t *filt, driver_intr_t *handler,
-		void *arg, void **cookiep)
+	    int flags, driver_filter_t *filt, driver_intr_t *handler,
+	    void *arg, void **cookiep)
 {
 	struct ar71xx_pci_softc *sc =3D device_get_softc(bus);
 	struct intr_event *event;
@@ -525,7 +612,7 @@
 			    mips_intrcnt_create(event->ie_name);
 		}
 		else
-			return error;
+			return (error);
 	}
=20
 	intr_event_add_handler(event, device_get_nameunit(child), filt,
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/atheros/ar91xx_chip.c
--- a/head/sys/mips/atheros/ar91xx_chip.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/atheros/ar91xx_chip.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/ar91xx_chip.c 233081 2012-03-17 =
07:25:23Z adrian $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/ar91xx_chip.c 234326 2012-04-15 =
22:34:22Z adrian $");
=20
 #include "opt_ddb.h"
=20
@@ -54,6 +54,7 @@
=20
 #include <mips/atheros/ar71xxreg.h>
 #include <mips/atheros/ar71xx_cpudef.h>
+#include <mips/atheros/ar71xx_chip.h>
 #include <mips/atheros/ar91xxreg.h>
 #include <mips/atheros/ar91xx_chip.h>
=20
@@ -112,13 +113,6 @@
 }
=20
 static void
-ar91xx_chip_set_mii_speed(uint32_t unit, uint32_t speed)
-{
-	/* XXX TODO */
-}
-
-
-static void
 ar91xx_chip_set_pll_ge(int unit, int speed)
 {
 	uint32_t pll;
@@ -217,7 +211,7 @@
 	&ar91xx_chip_device_start,
 	&ar91xx_chip_device_stopped,
 	&ar91xx_chip_set_pll_ge,
-	&ar91xx_chip_set_mii_speed,
+	&ar71xx_chip_set_mii_speed,
 	&ar91xx_chip_ddr_flush_ge,
 	&ar91xx_chip_get_eth_pll,
 	&ar91xx_chip_ddr_flush_ip2,
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/atheros/files.ar71xx
--- a/head/sys/mips/atheros/files.ar71xx	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/atheros/files.ar71xx	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/mips/atheros/files.ar71xx 221254 2011-04-30 11:36:16Z=
 adrian $
+# $FreeBSD: head/sys/mips/atheros/files.ar71xx 233319 2012-03-22 18:01:23Z=
 gonzo $
=20
 mips/atheros/apb.c		standard
 mips/atheros/ar71xx_gpio.c	optional gpio
@@ -22,3 +22,5 @@
 mips/atheros/ar71xx_chip.c	standard
 mips/atheros/ar724x_chip.c	standard
 mips/atheros/ar91xx_chip.c	standard
+
+dev/hwpmc/hwpmc_mips24k.c	optional hwpmc
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/atheros/std.ar71xx
--- a/head/sys/mips/atheros/std.ar71xx	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/atheros/std.ar71xx	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,8 @@
-# $FreeBSD: head/sys/mips/atheros/std.ar71xx 232896 2012-03-12 21:25:32Z j=
mallett $
+# $FreeBSD: head/sys/mips/atheros/std.ar71xx 233644 2012-03-29 02:54:35Z j=
mallett $
 #
 # standard config for all ar71xx based kernels.
=20
 files		"../atheros/files.ar71xx"
=20
-machine		mips mipseb
+machine		mips mips
 cpu		CPU_MIPS4KC
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/cavium/cvmx_config.h
--- a/head/sys/mips/cavium/cvmx_config.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/cavium/cvmx_config.h	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  * For any questions regarding licensing please contact marketing at caviumne=
tworks.com
  *
  ***********************license end**************************************/
-/* $FreeBSD: head/sys/mips/cavium/cvmx_config.h 217214 2011-01-10 03:48:41=
Z jmallett $ */
+/* $FreeBSD: head/sys/mips/cavium/cvmx_config.h 233639 2012-03-29 02:05:11=
Z jmallett $ */
=20
 #ifndef	_CVMX_CONFIG_H
 #define	_CVMX_CONFIG_H
@@ -159,6 +159,9 @@
 #define CVMX_ENABLE_PKO_FUNCTIONS
 #endif
=20
+/* Enable debug and informational printfs */
+#define CVMX_CONFIG_ENABLE_DEBUG_PRINTS 	1
+
 /************************* Config Specific Defines ***********************=
*/
 #define CVMX_LLM_NUM_PORTS 1
 #define CVMX_PKO_QUEUES_PER_PORT_INTERFACE0 1			/**< PKO queues per port f=
or interface 0 (ports 0-15) */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/cavium/files.octeon1
--- a/head/sys/mips/cavium/files.octeon1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/cavium/files.octeon1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/mips/cavium/files.octeon1 232816 2012-03-11 06:55:17Z=
 jmallett $
+# $FreeBSD: head/sys/mips/cavium/files.octeon1 233336 2012-03-23 00:11:54Z=
 gonzo $
 # Octeon Support Files
 #
 mips/cavium/asm_octeon.S			optional smp
@@ -8,6 +8,7 @@
 mips/cavium/octeon_ebt3000_cf.c			optional cf
 mips/cavium/octeon_machdep.c			standard
 mips/cavium/octeon_mp.c				optional smp
+mips/cavium/octeon_pmc.c			optional hwpmc
 mips/cavium/octeon_rtc.c			standard
 mips/cavium/uart_bus_octeonusart.c		optional uart
 mips/cavium/uart_cpu_octeonusart.c		optional uart
@@ -90,3 +91,6 @@
 contrib/octeon-sdk/cvmx-twsi.c			standard
 contrib/octeon-sdk/cvmx-warn.c			standard
 contrib/octeon-sdk/octeon-model.c		standard
+
+# HWPMC=20
+dev/hwpmc/hwpmc_octeon.c			optional hwpmc
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/cavium/octeon_ebt3000_cf=
.c
--- a/head/sys/mips/cavium/octeon_ebt3000_cf.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/mips/cavium/octeon_ebt3000_cf.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -42,7 +42,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/cavium/octeon_ebt3000_cf.c 226024 2011-1=
0-04 20:17:43Z marcel $");
+__FBSDID("$FreeBSD: head/sys/mips/cavium/octeon_ebt3000_cf.c 233278 2012-0=
3-21 10:27:12Z jmallett $");
=20
 #include <sys/param.h>
 #include <sys/bio.h>
@@ -133,17 +133,6 @@
 	"True IDE"
 };
=20
-/* Device softc */
-struct cf_priv {
-	device_t dev;
-	struct drive_param *drive_param;
-
-	struct bio_queue_head cf_bq;
-	struct g_geom *cf_geom;
-	struct g_provider *cf_provider;
-
-};
-
 /* Device parameters */
 struct drive_param{
 	union {
@@ -157,8 +146,18 @@
 	uint16_t heads;
 	uint16_t tracks;
 	uint16_t sec_track;
+};
=20
-} drive_param;
+/* Device softc */
+struct cf_priv {
+	device_t dev;
+	struct drive_param drive_param;
+
+	struct bio_queue_head cf_bq;
+	struct g_geom *cf_geom;
+	struct g_provider *cf_provider;
+
+};
=20
 /* GEOM class implementation */
 static g_access_t       cf_access;
@@ -179,15 +178,14 @@
 static int	cf_probe(device_t);
 static void	cf_identify(driver_t *, device_t);
 static int	cf_attach(device_t);
-static int	cf_attach_geom(void *, int);
+static void	cf_attach_geom(void *, int);
=20
 /* ATA methods */
-static int	cf_cmd_identify(void);
+static int	cf_cmd_identify(struct cf_priv *);
 static int	cf_cmd_write(uint32_t, uint32_t, void *);
 static int	cf_cmd_read(uint32_t, uint32_t, void *);
 static int	cf_wait_busy(void);
 static int	cf_send_cmd(uint32_t, uint8_t);
-static void	cf_attach_geom_proxy(void *arg, int flag);
=20
 /* Miscelenous */
 static void	cf_swap_ascii(unsigned char[], char[]);
@@ -198,11 +196,6 @@
  * ------------------------------------------------------------------- */
 static int cf_access (struct g_provider *pp, int r, int w, int e)
 {
-
-	pp->sectorsize =3D drive_param.sector_size;
-        pp->stripesize =3D drive_param.heads * drive_param.sec_track * dri=
ve_param.sector_size;
-        pp->mediasize  =3D pp->stripesize * drive_param.tracks;
-
 	return (0);
 }
=20
@@ -212,17 +205,20 @@
  * ------------------------------------------------------------------- */
 static void cf_start (struct bio *bp)
 {
+	struct cf_priv *cf_priv;
 	int error;
=20
+	cf_priv =3D bp->bio_to->geom->softc;
+
 	/*
 	* Handle actual I/O requests. The request is passed down through
 	* the bio struct.
 	*/
=20
 	if(bp->bio_cmd & BIO_GETATTR) {
-		if (g_handleattr_int(bp, "GEOM::fwsectors", drive_param.sec_track))
+		if (g_handleattr_int(bp, "GEOM::fwsectors", cf_priv->drive_param.sec_tra=
ck))
                         return;
-                if (g_handleattr_int(bp, "GEOM::fwheads",   drive_param.he=
ads))
+                if (g_handleattr_int(bp, "GEOM::fwheads", cf_priv->drive_p=
aram.heads))
                         return;
                 g_io_deliver(bp, ENOIOCTL);
                 return;
@@ -231,11 +227,11 @@
 	if ((bp->bio_cmd & (BIO_READ | BIO_WRITE))) {
=20
 		if (bp->bio_cmd & BIO_READ) {
-			error =3D cf_cmd_read(bp->bio_length / drive_param.sector_size,
-			    bp->bio_offset / drive_param.sector_size, bp->bio_data);
+			error =3D cf_cmd_read(bp->bio_length / cf_priv->drive_param.sector_size,
+			    bp->bio_offset / cf_priv->drive_param.sector_size, bp->bio_data);
 		} else if (bp->bio_cmd & BIO_WRITE) {
-			error =3D cf_cmd_write(bp->bio_length / drive_param.sector_size,
-			    bp->bio_offset/drive_param.sector_size, bp->bio_data);
+			error =3D cf_cmd_write(bp->bio_length / cf_priv->drive_param.sector_siz=
e,
+			    bp->bio_offset/cf_priv->drive_param.sector_size, bp->bio_data);
 		} else {
 			printf("%s: unrecognized bio_cmd %x.\n", __func__, bp->bio_cmd);
 			error =3D ENOTSUP;
@@ -443,7 +439,7 @@
  * it in the drive_param structure
  *
  */
-static int cf_cmd_identify (void)
+static int cf_cmd_identify(struct cf_priv *cf_priv)
 {
 	int count;
 	int error;
@@ -457,7 +453,7 @@
 	{
 	case CF_8:
 		for (count =3D 0; count < SECTOR_SIZE; count++)=20
-			drive_param.u.buf[count] =3D cf_inb_8(TF_DATA);
+			cf_priv->drive_param.u.buf[count] =3D cf_inb_8(TF_DATA);
 		break;
 	case CF_TRUE_IDE_8:
 	case CF_16:
@@ -467,25 +463,25 @@
 			temp =3D cf_inw_16(TF_DATA);
 			=09
 			/* endianess will be swapped below */
-			drive_param.u.buf[count]   =3D (temp & 0xff);
-			drive_param.u.buf[count + 1] =3D (temp & 0xff00) >> 8;
+			cf_priv->drive_param.u.buf[count]   =3D (temp & 0xff);
+			cf_priv->drive_param.u.buf[count + 1] =3D (temp & 0xff00) >> 8;
 		}
 		break;
 	}
=20
-	cf_swap_ascii(drive_param.u.driveid.model, drive_param.model);
+	cf_swap_ascii(cf_priv->drive_param.u.driveid.model, cf_priv->drive_param.=
model);
=20
-	drive_param.sector_size =3D  512;   //=3D  SWAP_SHORT (drive_param.u.driv=
eid.sector_bytes);
-	drive_param.heads 	=3D  SWAP_SHORT (drive_param.u.driveid.current_heads);
-	drive_param.tracks	=3D  SWAP_SHORT (drive_param.u.driveid.current_cylinde=
rs);=20
-	drive_param.sec_track   =3D  SWAP_SHORT (drive_param.u.driveid.current_se=
ctors);
-	drive_param.nr_sectors  =3D (uint32_t)SWAP_SHORT (drive_param.u.driveid.l=
ba_size_1) |
-	    ((uint32_t)SWAP_SHORT (drive_param.u.driveid.lba_size_2));
+	cf_priv->drive_param.sector_size =3D  512;   //=3D  SWAP_SHORT (cf_priv->=
drive_param.u.driveid.sector_bytes);
+	cf_priv->drive_param.heads 	=3D  SWAP_SHORT (cf_priv->drive_param.u.drive=
id.current_heads);
+	cf_priv->drive_param.tracks	=3D  SWAP_SHORT (cf_priv->drive_param.u.drive=
id.current_cylinders);=20
+	cf_priv->drive_param.sec_track   =3D  SWAP_SHORT (cf_priv->drive_param.u.=
driveid.current_sectors);
+	cf_priv->drive_param.nr_sectors  =3D (uint32_t)SWAP_SHORT (cf_priv->drive=
_param.u.driveid.lba_size_1) |
+	    ((uint32_t)SWAP_SHORT (cf_priv->drive_param.u.driveid.lba_size_2));
 	if (bootverbose) {
-		printf("    model %s\n", drive_param.model);
+		printf("    model %s\n", cf_priv->drive_param.model);
 		printf("    heads %d tracks %d sec_tracks %d sectors %d\n",
-			drive_param.heads, drive_param.tracks,
-			drive_param.sec_track, drive_param.nr_sectors);
+			cf_priv->drive_param.heads, cf_priv->drive_param.tracks,
+			cf_priv->drive_param.sec_track, cf_priv->drive_param.nr_sectors);
 	}
=20
 	return (0);
@@ -627,7 +623,7 @@
=20
         device_set_desc(dev, "Octeon Compact Flash Driver");
=20
-	return (cf_cmd_identify());
+	return (0);
 }
=20
 /* ------------------------------------------------------------------- *
@@ -644,12 +640,12 @@
 	int bus_region;
 	int count =3D 0;
 	cvmx_mio_boot_reg_cfgx_t cfg;
-
-	uint64_t phys_base =3D cvmx_sysinfo_get()->compact_flash_common_base_addr;
-
+	uint64_t phys_base;
+=09
     	if (octeon_is_simulation())
 		return;
=20
+	phys_base =3D cvmx_sysinfo_get()->compact_flash_common_base_addr;
 	base_addr =3D cvmx_phys_to_ptr(phys_base);
=20
         for (bus_region =3D 0; bus_region < 8; bus_region++)
@@ -700,45 +696,41 @@
  *                      cf_attach_geom()                               *
  * ------------------------------------------------------------------- */
=20
-static int cf_attach_geom (void *arg, int flag)
+static void cf_attach_geom (void *arg, int flag)
 {
 	struct cf_priv *cf_priv;
=20
 	cf_priv =3D (struct cf_priv *) arg;
 	cf_priv->cf_geom =3D g_new_geomf(&g_cf_class, "cf%d", device_get_unit(cf_=
priv->dev));
+	cf_priv->cf_geom->softc =3D cf_priv;
 	cf_priv->cf_provider =3D g_new_providerf(cf_priv->cf_geom, cf_priv->cf_ge=
om->name);
-	cf_priv->cf_geom->softc =3D cf_priv;
+	cf_priv->cf_provider->sectorsize =3D cf_priv->drive_param.sector_size;
+	cf_priv->cf_provider->mediasize =3D cf_priv->drive_param.nr_sectors * cf_=
priv->cf_provider->sectorsize;
         g_error_provider(cf_priv->cf_provider, 0);
-
-        return (0);
 }
=20
 /* ------------------------------------------------------------------- *
- *                      cf_attach_geom()                               *
- * ------------------------------------------------------------------- */
-static void cf_attach_geom_proxy (void *arg, int flag)
-{
-	cf_attach_geom(arg, flag);
-}
-
-
-
-/* ------------------------------------------------------------------- *
  *                      cf_attach()                                    *
  * ------------------------------------------------------------------- */
=20
 static int cf_attach (device_t dev)
 {
 	struct cf_priv *cf_priv;
+	int error;
=20
     	if (octeon_is_simulation())
 		return (ENXIO);
=20
 	cf_priv =3D device_get_softc(dev);
 	cf_priv->dev =3D dev;
-	cf_priv->drive_param =3D &drive_param;
=20
-	g_post_event(cf_attach_geom_proxy, cf_priv, M_WAITOK, NULL);
+	error =3D cf_cmd_identify(cf_priv);
+	if (error !=3D 0) {
+		device_printf(dev, "cf_cmd_identify failed: %d\n", error);
+		return (error);
+	}
+
+	g_post_event(cf_attach_geom, cf_priv, M_WAITOK, NULL);
 	bioq_init(&cf_priv->cf_bq);
=20
         return 0;
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/cavium/octeon_irq.h
--- a/head/sys/mips/cavium/octeon_irq.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/cavium/octeon_irq.h	Tue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
 #define __OCTEON_IRQ_H__
=20
 /*
- * $FreeBSD: head/sys/mips/cavium/octeon_irq.h 232812 2012-03-11 06:17:49Z=
 jmallett $
+ * $FreeBSD: head/sys/mips/cavium/octeon_irq.h 233417 2012-03-24 06:28:15Z=
 gonzo $
  */
=20
 /**
@@ -176,4 +176,6 @@
     /* Interrupts 129 - 135 are reserved */
 } octeon_irq_t;
=20
+#define	OCTEON_PMC_IRQ	OCTEON_IRQ_4
+
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/cavium/octeon_machdep.c
--- a/head/sys/mips/cavium/octeon_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/cavium/octeon_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,10 +23,10 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/mips/cavium/octeon_machdep.c 232812 2012-03-11 06:17=
:49Z jmallett $
+ * $FreeBSD: head/sys/mips/cavium/octeon_machdep.c 233417 2012-03-24 06:28=
:15Z gonzo $
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/cavium/octeon_machdep.c 232812 2012-03-1=
1 06:17:49Z jmallett $");
+__FBSDID("$FreeBSD: head/sys/mips/cavium/octeon_machdep.c 233417 2012-03-2=
4 06:28:15Z gonzo $");
=20
 #include <sys/param.h>
 #include <sys/conf.h>
@@ -260,6 +260,8 @@
 void
 octeon_ciu_reset(void)
 {
+	uint64_t cvmctl;
+
 	/* Disable all CIU interrupts by default */
 	cvmx_write_csr(CVMX_CIU_INTX_EN0(cvmx_get_core_num()*2), 0);
 	cvmx_write_csr(CVMX_CIU_INTX_EN0(cvmx_get_core_num()*2+1), 0);
@@ -272,6 +274,14 @@
 		       (1ull << (OCTEON_IRQ_MBOX0 - 8)) |
 		       (1ull << (OCTEON_IRQ_MBOX1 - 8)));
 #endif
+
+	/*=20
+	 * Move the Performance Counter interrupt to OCTEON_PMC_IRQ
+	 */
+	cvmctl =3D mips_rd_cvmctl();
+	cvmctl &=3D ~(7 << 7);
+	cvmctl |=3D (OCTEON_PMC_IRQ + 2) << 7;
+	mips_wr_cvmctl(cvmctl);
 }
=20
 static void
@@ -363,6 +373,8 @@
 	 * entirely.
 	 */
=20
+	mips_postboot_fixup();
+
 	/* Initialize pcpu stuff */
 	mips_pcpu0_init();
 	mips_timer_early_init(OCTEON_CLOCK_DEFAULT);
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/cavium/std.octeon1
--- a/head/sys/mips/cavium/std.octeon1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/cavium/std.octeon1	Tue Apr 17 11:51:51 2012 +0300
@@ -2,8 +2,8 @@
 #  *    This product includes software developed by the University of
 #  *    California, Berkeley and its contributors."
 # */
-# $FreeBSD: head/sys/mips/cavium/std.octeon1 215270 2010-11-13 22:34:12Z i=
mp $
+# $FreeBSD: head/sys/mips/cavium/std.octeon1 233644 2012-03-29 02:54:35Z j=
mallett $
 #=20
 files	"../cavium/files.octeon1"
-machine	mips mips64eb
+machine	mips mips64
 cpu		CPU_CNMIPS
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/AR71XX_BASE
--- a/head/sys/mips/conf/AR71XX_BASE	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/AR71XX_BASE	Tue Apr 17 11:51:51 2012 +0300
@@ -4,10 +4,10 @@
 # This includes all the common drivers for the AR71XX boards along with
 # the usb, net80211 and atheros driver code.
 #
-# $FreeBSD: head/sys/mips/conf/AR71XX_BASE 232897 2012-03-12 21:26:09Z jma=
llett $
+# $FreeBSD: head/sys/mips/conf/AR71XX_BASE 233644 2012-03-29 02:54:35Z jma=
llett $
 #
=20
-machine		mips mipseb
+machine		mips mips
 ident		AR71XX_BASE
 cpu		CPU_MIPS4KC
 makeoptions	KERNLOADADDR=3D0x80050000
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/AR91XX_BASE
--- a/head/sys/mips/conf/AR91XX_BASE	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/AR91XX_BASE	Tue Apr 17 11:51:51 2012 +0300
@@ -7,10 +7,10 @@
 # override the default options (adding devices as needed) and adding
 # hints as needed (for example, the GPIO and LAN PHY.)
 #
-# $FreeBSD: head/sys/mips/conf/AR91XX_BASE 232896 2012-03-12 21:25:32Z jma=
llett $
+# $FreeBSD: head/sys/mips/conf/AR91XX_BASE 233644 2012-03-29 02:54:35Z jma=
llett $
 #
=20
-machine         mips mipseb
+machine         mips mips
 ident		AR91XX_BASE
 cpu		CPU_MIPS4KC
 makeoptions	KERNLOADADDR=3D0x80050000
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/OCTEON1
--- a/head/sys/mips/conf/OCTEON1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/OCTEON1	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check first
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/OCTEON1 232913 2012-03-13 06:22:49Z jmallet=
t $
+# $FreeBSD: head/sys/mips/conf/OCTEON1 233271 2012-03-21 08:38:42Z ed $
=20
 ident		OCTEON1
=20
@@ -278,7 +278,6 @@
 device		ether		# Ethernet support
 device		vlan		# 802.1Q VLAN support
 device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 device		md		# Memory "disks"
 device		gif		# IPv6 and IPv4 tunneling
 device		faith		# IPv6-to-IPv4 relaying (translation)
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/RT305X
--- a/head/sys/mips/conf/RT305X	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/RT305X	Tue Apr 17 11:51:51 2012 +0300
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/RT305X 224009 2011-07-14 11:53:23Z ray $
+# $FreeBSD: head/sys/mips/conf/RT305X 233271 2012-03-21 08:38:42Z ed $
=20
 ident		RT305X
=20
@@ -95,7 +95,6 @@
 # RT3050F, RT3052F have only pseudo PHYs, so mii not required
 device		rt
=20
-device 		pty			# Pseudo-ttys (telnet etc)
 device		ether
 device 		bpf			# Berkeley packet filter
 device		vlan
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/SWARM
--- a/head/sys/mips/conf/SWARM	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/SWARM	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,12 @@
 #
-# $FreeBSD: head/sys/mips/conf/SWARM 232896 2012-03-12 21:25:32Z jmallett $
+# $FreeBSD: head/sys/mips/conf/SWARM 233644 2012-03-29 02:54:35Z jmallett $
 #
=20
 include		"std.SWARM"
=20
 ident		SWARM
=20
-machine		mips mipseb
+machine		mips mips
=20
 makeoptions	ARCH_FLAGS=3D"-mabi=3D32 -march=3Dmips32"
 makeoptions	LDSCRIPT_NAME=3D	ldscript.mips.cfe
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/SWARM64
--- a/head/sys/mips/conf/SWARM64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/SWARM64	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,12 @@
 #
-# $FreeBSD: head/sys/mips/conf/SWARM64 232840 2012-03-11 22:17:01Z jmallet=
t $
+# $FreeBSD: head/sys/mips/conf/SWARM64 233644 2012-03-29 02:54:35Z jmallet=
t $
 #
=20
 include		"std.SWARM"
=20
 ident		SWARM64
=20
-machine		mips mips64eb
+machine		mips mips64
 makeoptions	ARCH_FLAGS=3D"-mabi=3D64 -march=3Dmips64"
 makeoptions	LDSCRIPT_NAME=3Dldscript.mips.cfe
 makeoptions	KERNLOADADDR=3D0xffffffff80001000
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/SWARM64_SMP
--- a/head/sys/mips/conf/SWARM64_SMP	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/SWARM64_SMP	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/sys/mips/conf/SWARM64_SMP 232840 2012-03-11 22:17:01Z jma=
llett $
+# $FreeBSD: head/sys/mips/conf/SWARM64_SMP 233644 2012-03-29 02:54:35Z jma=
llett $
 #
=20
 include		"std.SWARM"
@@ -9,7 +9,7 @@
 options		SMP
 options		PRINTF_BUFR_SIZE=3D128
=20
-machine		mips mips64eb
+machine		mips mips64
 makeoptions	ARCH_FLAGS=3D"-mabi=3D64 -march=3Dmips64"
 makeoptions	LDSCRIPT_NAME=3Dldscript.mips.cfe
 makeoptions	KERNLOADADDR=3D0xffffffff80001000
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/SWARM_SMP
--- a/head/sys/mips/conf/SWARM_SMP	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/SWARM_SMP	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/sys/mips/conf/SWARM_SMP 232896 2012-03-12 21:25:32Z jmall=
ett $
+# $FreeBSD: head/sys/mips/conf/SWARM_SMP 233644 2012-03-29 02:54:35Z jmall=
ett $
 #
=20
 include		"std.SWARM"
@@ -9,7 +9,7 @@
 options		SMP
 options		PRINTF_BUFR_SIZE=3D128
=20
-machine		mips mipseb
+machine		mips mips
=20
 makeoptions	ARCH_FLAGS=3D"-mabi=3D32 -march=3Dmips32"
 makeoptions	LDSCRIPT_NAME=3D	ldscript.mips.cfe
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/XLP
--- a/head/sys/mips/conf/XLP	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/XLP	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,9 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/XLP 232896 2012-03-12 21:25:32Z jmallett $
+# $FreeBSD: head/sys/mips/conf/XLP 233644 2012-03-29 02:54:35Z jmallett $
=20
-machine 	mips mipseb
+machine 	mips mips
 ident           XLP
=20
 makeoptions	KERNLOADADDR=3D0x80100000
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/XLP64
--- a/head/sys/mips/conf/XLP64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/XLP64	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,9 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/XLP64 232896 2012-03-12 21:25:32Z jmallett $
+# $FreeBSD: head/sys/mips/conf/XLP64 233644 2012-03-29 02:54:35Z jmallett $
=20
-machine 	mips mips64eb
+machine 	mips mips64
 ident           XLP64
=20
 makeoptions	ARCH_FLAGS=3D"-march=3Dmips64r2 -mabi=3D64"
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/XLPN32
--- a/head/sys/mips/conf/XLPN32	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/XLPN32	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,9 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/XLPN32 232896 2012-03-12 21:25:32Z jmallett=
 $
+# $FreeBSD: head/sys/mips/conf/XLPN32 233644 2012-03-29 02:54:35Z jmallett=
 $
=20
-machine 	mips mipsn32eb
+machine 	mips mipsn32
 ident           XLPN32
=20
 makeoptions	ARCH_FLAGS=3D"-march=3Dmips64 -mabi=3Dn32"
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/XLR
--- a/head/sys/mips/conf/XLR	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/XLR	Tue Apr 17 11:51:51 2012 +0300
@@ -43,9 +43,9 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/XLR 232896 2012-03-12 21:25:32Z jmallett $
+# $FreeBSD: head/sys/mips/conf/XLR 233644 2012-03-29 02:54:35Z jmallett $
=20
-machine 	mips mipseb
+machine 	mips mips
 ident 		XLR
 include		"../rmi/std.xlr"
=20
@@ -112,7 +112,6 @@
 device 		loop
 device 		random
 device 		md
-device 		pty
 device		bpf
=20
 # Network
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/XLR64
--- a/head/sys/mips/conf/XLR64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/XLR64	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,9 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/XLR64 232896 2012-03-12 21:25:32Z jmallett $
+# $FreeBSD: head/sys/mips/conf/XLR64 233644 2012-03-29 02:54:35Z jmallett $
=20
-machine 	mips mips64eb
+machine 	mips mips64
 ident 		XLR64
 include		"../rmi/std.xlr"
=20
@@ -86,7 +86,6 @@
 device 		loop
 device 		random
 device 		md
-device 		pty
 device		bpf
=20
 # Network
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/XLRN32
--- a/head/sys/mips/conf/XLRN32	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/XLRN32	Tue Apr 17 11:51:51 2012 +0300
@@ -15,9 +15,9 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/XLRN32 232896 2012-03-12 21:25:32Z jmallett=
 $
+# $FreeBSD: head/sys/mips/conf/XLRN32 233644 2012-03-29 02:54:35Z jmallett=
 $
=20
-machine 	mips mipsn32eb
+machine 	mips mipsn32
 ident 		XLRN32
 include		"../rmi/std.xlr"
=20
@@ -87,7 +87,6 @@
 device 		loop
 device 		random
 device 		md
-device 		pty
 device		bpf
=20
 # Network
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/conf/std.XLP
--- a/head/sys/mips/conf/std.XLP	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/conf/std.XLP	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,12 @@
-# $FreeBSD: head/sys/mips/conf/std.XLP 227725 2011-11-19 14:33:14Z jchandr=
a $
+# $FreeBSD: head/sys/mips/conf/std.XLP 233564 2012-03-27 15:43:32Z jchandr=
a $
=20
 include		"../nlm/std.xlp"
 makeoptions	MODULES_OVERRIDE=3D""
 makeoptions	DEBUG=3D-g		# Build kernel with gdb(1) debug symbols
 #profile 	2
=20
+hints		"XLP.hints"
+
 options 	SCHED_ULE		# ULE scheduler
 #options 	VERBOSE_SYSINIT
 #options 	SCHED_4BSD		# 4BSD scheduler
@@ -55,16 +57,21 @@
=20
 options 	GEOM_UZIP
=20
+# Device tree
+options 	FDT
+options 	FDT_DTB_STATIC
+makeoptions	FDT_DTS_FILE=3Dxlp-basic.dts
+
 # Pseudo
 device		loop
 device		random
 device		md
-device		pty
 device		bpf
=20
 # Network
 device		miibus
 device		ether
+device		xlpge
 #device		re
 device		msk
 device		em
@@ -84,6 +91,27 @@
 #device		uhid			# "Human Interface Devices"
 device		umass			# Requires scbus and da
=20
-options 	FDT
-options 	FDT_DTB_STATIC
-makeoptions	FDT_DTS_FILE=3Dxlp-basic.dts
+# i2c driver and devices
+device		iic
+device		iicbus
+device		iicoc
+device		ds1374			# RTC on XLP boards
+
+# Crypto
+device		crypto
+device		cryptodev
+device		nlmsec
+device		nlmrsa
+
+# Options that use crypto
+options 	IPSEC
+options 	GEOM_ELI
+
+# NOR
+device		cfi
+device		cfid
+
+# MMC/SD
+device		mmc			# MMC/SD bus
+device		mmcsd			# MMC/SD memory card
+device		sdhci			# Generic PCI SD Host Controller
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/include/param.h
--- a/head/sys/mips/include/param.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/include/param.h	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  *	from: Utah Hdr: machparam.h 1.11 89/08/14
  *	from: @(#)param.h	8.1 (Berkeley) 6/10/93
  *	JNPR: param.h,v 1.6.2.1 2007/09/10 07:49:36 girish
- * $FreeBSD: head/sys/mips/include/param.h 232449 2012-03-03 08:19:18Z jma=
llett $
+ * $FreeBSD: head/sys/mips/include/param.h 233644 2012-03-29 02:54:35Z jma=
llett $
  */
=20
 #ifndef _MIPS_INCLUDE_PARAM_H_
@@ -59,14 +59,14 @@
 #ifndef MACHINE_ARCH
 #if _BYTE_ORDER =3D=3D _BIG_ENDIAN
 #ifdef __mips_n64
-#define	MACHINE_ARCH	"mips64eb"
+#define	MACHINE_ARCH	"mips64"
 #ifndef	MACHINE_ARCH32
-#define	MACHINE_ARCH32	"mipseb"
+#define	MACHINE_ARCH32	"mips"
 #endif
 #elif defined(__mips_n32)
-#define	MACHINE_ARCH	"mipsn32eb"
+#define	MACHINE_ARCH	"mipsn32"
 #else
-#define	MACHINE_ARCH	"mipseb"
+#define	MACHINE_ARCH	"mips"
 #endif
 #else
 #ifdef __mips_n64
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/include/pmap.h
--- a/head/sys/mips/include/pmap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/include/pmap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -40,7 +40,7 @@
  *	from: @(#)pmap.h	7.4 (Berkeley) 5/12/91
  *	from: src/sys/i386/include/pmap.h,v 1.65.2.2 2000/11/30 01:54:42 peter
  *	JNPR: pmap.h,v 1.7.2.1 2007/09/10 07:44:12 girish
- *      $FreeBSD: head/sys/mips/include/pmap.h 232855 2012-03-12 08:13:04Z=
 jmallett $
+ *      $FreeBSD: head/sys/mips/include/pmap.h 233381 2012-03-23 18:07:12Z=
 gonzo $
  */
=20
 #ifndef _MACHINE_PMAP_H_
@@ -99,7 +99,7 @@
 #ifdef	_KERNEL
=20
 pt_entry_t *pmap_pte(pmap_t, vm_offset_t);
-vm_offset_t pmap_kextract(vm_offset_t va);
+vm_paddr_t pmap_kextract(vm_offset_t va);
=20
 #define	vtophys(va)	pmap_kextract(((vm_offset_t) (va)))
 #define	pmap_asid(pmap)	(pmap)->pm_asid[PCPU_GET(cpuid)].asid
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/include/pmc_mdep.h
--- a/head/sys/mips/include/pmc_mdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/include/pmc_mdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -2,37 +2,79 @@
  * This file is in the public domain.
  *
  *	from: src/sys/alpha/include/pmc_mdep.h,v 1.2 2005/06/09 19:45:06 jkoshy
- * $FreeBSD$
+ * $FreeBSD: head/sys/mips/include/pmc_mdep.h 233628 2012-03-28 20:58:30Z =
fabient $
  */
=20
 #ifndef _MACHINE_PMC_MDEP_H_
 #define	_MACHINE_PMC_MDEP_H_
=20
-#define	PMC_MDEP_CLASS_INDEX_MIPS24K	0
-#include <dev/hwpmc/hwpmc_mips24k.h>
+#define	PMC_MDEP_CLASS_INDEX_MIPS	1
=20
 union pmc_md_op_pmcallocate {
 	uint64_t	__pad[4];
 };
=20
 /* Logging */
+#if defined(__mips_n64)
+#define	PMCLOG_READADDR		PMCLOG_READ64
+#define	PMCLOG_EMITADDR		PMCLOG_EMIT64
+#else
 #define	PMCLOG_READADDR		PMCLOG_READ32
 #define	PMCLOG_EMITADDR		PMCLOG_EMIT32
+#endif
=20
 #if	_KERNEL
+
+/*
+ * MIPS event codes are encoded with a select bit.  The
+ * select bit is used when writing to CP0 so that we=20
+ * can select either counter 0/2 or 1/3.  The cycle
+ * and instruction counters are special in that they
+ * can be counted on either 0/2 or 1/3.
+ */
+
+#define MIPS_CTR_ALL	255 /* Count events in any counter. */
+#define MIPS_CTR_0	0 /* Counter 0 Event */
+#define MIPS_CTR_1	1 /* Counter 1 Event */
+
+struct mips_event_code_map {
+	uint32_t	pe_ev;       /* enum value */
+	uint8_t         pe_counter;  /* Which counter this can be counted in. */
+	uint8_t		pe_code;     /* numeric code */
+};
+
+struct mips_pmc_spec {
+	uint32_t	ps_cpuclass;
+	uint32_t	ps_cputype;
+	uint32_t	ps_capabilities;
+	int		ps_counter_width;
+};
+
 union pmc_md_pmc {
-	struct pmc_md_mips24k_pmc	pm_mips24k;
+	uint32_t	pm_mips_evsel;
 };
=20
 #define	PMC_TRAPFRAME_TO_PC(TF)	((TF)->pc)
-#define	PMC_TRAPFRAME_TO_FP(TF)	((TF)->tf_usr_lr)
-#define	PMC_TRAPFRAME_TO_SP(TF)	((TF)->tf_usr_sp)
+
+extern const struct mips_event_code_map mips_event_codes[];
+extern const int mips_event_codes_size;
+extern int mips_npmcs;
+extern struct mips_pmc_spec mips_pmc_spec;
=20
 /*
  * Prototypes
  */
-struct pmc_mdep *pmc_mips24k_initialize(void);
-void		pmc_mips24k_finalize(struct pmc_mdep *_md);
+struct pmc_mdep *pmc_mips_initialize(void);
+void		pmc_mips_finalize(struct pmc_mdep *_md);
+
+/*
+ * CPU-specific functions
+ */
+
+uint32_t	mips_get_perfctl(int cpu, int ri, uint32_t event, uint32_t caps);
+uint64_t	mips_pmcn_read(unsigned int pmc);
+uint64_t	mips_pmcn_write(unsigned int pmc, uint64_t v);
+
 #endif /* _KERNEL */
=20
 #endif /* !_MACHINE_PMC_MDEP_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/include/vm.h
--- a/head/sys/mips/include/vm.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/include/vm.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/mips/include/vm.h 233670 2012-03-29 16:48:36Z jhb $
  */
=20
 #ifndef _MACHINE_VM_H_
@@ -32,7 +32,7 @@
 #include <machine/pte.h>
=20
 /* Memory attributes. */
-#define	VM_MEMATTR_UNCACHED	((vm_memattr_t)PTE_C_UNCACHED)
+#define	VM_MEMATTR_UNCACHEABLE	((vm_memattr_t)PTE_C_UNCACHED)
 #define	VM_MEMATTR_DEFAULT	((vm_memattr_t)PTE_C_CACHE)
=20
 #endif /* !_MACHINE_VM_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/mips/bus_space_generic.c
--- a/head/sys/mips/mips/bus_space_generic.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/mips/bus_space_generic.c	Tue Apr 17 11:51:51 2012 +0300
@@ -136,7 +136,7 @@
 	NULL,
=20
 	/* write region */
-	NULL,
+	generic_bs_wr_1,
 	generic_bs_wr_2,
 	generic_bs_wr_4,
 	NULL,
@@ -148,7 +148,7 @@
 	NULL,
=20
 	/* set region */
-	NULL,
+	generic_bs_sr_1,
 	generic_bs_sr_2,
 	generic_bs_sr_4,
 	NULL,
@@ -190,7 +190,7 @@
 	NULL,
=20
 	/* write region stream */
-	NULL,
+	generic_bs_wr_1,
 	generic_bs_wr_2,
 	generic_bs_wr_4,
 	NULL,
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/mips/exception.S
--- a/head/sys/mips/mips/exception.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/mips/exception.S	Tue Apr 17 11:51:51 2012 +0300
@@ -46,7 +46,7 @@
  *	v 1.1 89/07/10 14:27:41 nelson Exp  SPRITE (DECWRL)
  *	from: @(#)locore.s	8.5 (Berkeley) 1/4/94
  *	JNPR: exception.S,v 1.5 2007/01/08 04:58:37 katta
- * $FreeBSD: head/sys/mips/mips/exception.S 232896 2012-03-12 21:25:32Z jm=
allett $
+ * $FreeBSD: head/sys/mips/mips/exception.S 233412 2012-03-24 05:17:38Z go=
nzo $
  */
=20
 /*
@@ -55,6 +55,7 @@
  */
=20
 #include "opt_ddb.h"
+#include "opt_kdtrace.h"
 #include <machine/asm.h>
 #include <machine/cpu.h>
 #include <machine/regnum.h>
@@ -65,6 +66,26 @@
=20
 	.set	noreorder		# Noreorder is default style!
=20
+#ifdef KDTRACE_HOOKS
+	.data
+	.globl	dtrace_invop_jump_addr
+	.align	4
+	.type	dtrace_invop_jump_addr, @object
+        .size	dtrace_invop_jump_addr, 8
+dtrace_invop_jump_addr:
+	.word	0
+	.word	0
+	.globl	dtrace_invop_calltrap_addr
+	.align	4
+	.type	dtrace_invop_calltrap_addr, @object
+        .size	dtrace_invop_calltrap_addr, 8
+dtrace_invop_calltrap_addr:
+	.word	0
+	.word	0
+
+	.text
+#endif
+
 /*
  * Reasonable limit
  */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/mips/intr_machdep.c
--- a/head/sys/mips/mips/intr_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/mips/intr_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,12 +27,16 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/mips/mips/intr_machdep.c 233318 2012-03-22 17=
:47:52Z gonzo $");
+
+#include "opt_hwpmc_hooks.h"
=20
 #include <sys/param.h>
 #include <sys/systm.h>
 #include <sys/bus.h>
 #include <sys/interrupt.h>
+#include <sys/pmc.h>
+#include <sys/pmckern.h>
=20
 #include <machine/clock.h>
 #include <machine/cpu.h>
@@ -266,4 +270,9 @@
 	KASSERT(i =3D=3D 0, ("all interrupts handled"));
=20
 	critical_exit();
+
+#ifdef HWPMC_HOOKS
+	if (pmc_hook && (PCPU_GET(curthread)->td_pflags & TDP_CALLCHAIN))
+		pmc_hook(PCPU_GET(curthread), PMC_FN_USER_CALLCHAIN, tf);
+#endif
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/mips/machdep.c
--- a/head/sys/mips/mips/machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/mips/machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -40,7 +40,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/mips/machdep.c 233019 2012-03-15 23:53:2=
4Z gonzo $");
+__FBSDID("$FreeBSD: head/sys/mips/mips/machdep.c 233776 2012-04-02 11:41:3=
3Z jchandra $");
=20
 #include "opt_ddb.h"
 #include "opt_md.h"
@@ -346,7 +346,7 @@
 	bcopy(MipsTLBMiss, (void *)MIPS_UTLB_MISS_EXC_VEC,
 	      MipsTLBMissEnd - MipsTLBMiss);
=20
-#ifdef __mips_n64
+#if defined(__mips_n64) || defined(CPU_RMI) || defined(CPU_NLM)
 	bcopy(MipsTLBMiss, (void *)MIPS_XTLB_MISS_EXC_VEC,
 	      MipsTLBMissEnd - MipsTLBMiss);
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/mips/pmap.c
--- a/head/sys/mips/mips/pmap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/mips/pmap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -66,7 +66,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/mips/pmap.c 227623 2011-11-17 13:14:59Z =
jchandra $");
+__FBSDID("$FreeBSD: head/sys/mips/mips/pmap.c 233308 2012-03-22 15:14:10Z =
jchandra $");
=20
 #include "opt_ddb.h"
=20
@@ -3209,7 +3209,7 @@
  *		Extract the physical page address associated
  *		virtual address.
  */
- /* PMAP_INLINE */ vm_offset_t
+vm_paddr_t
 pmap_kextract(vm_offset_t va)
 {
 	int mapped;
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/mips/trap.c
--- a/head/sys/mips/mips/trap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/mips/trap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,12 +39,13 @@
  *	JNPR: trap.c,v 1.13.2.2 2007/08/29 10:03:49 girish
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/mips/trap.c 232615 2012-03-06 19:01:32Z =
jmallett $");
+__FBSDID("$FreeBSD: head/sys/mips/mips/trap.c 233638 2012-03-29 02:04:15Z =
jmallett $");
=20
 #include "opt_compat.h"
 #include "opt_ddb.h"
 #include "opt_global.h"
 #include "opt_ktrace.h"
+#include "opt_kdtrace.h"
=20
 #define	NO_REG_DEFS	1	/* Prevent asm.h from including regdef.h */
 #include <sys/param.h>
@@ -93,6 +94,33 @@
 #include <sys/kdb.h>
 #endif
=20
+#ifdef KDTRACE_HOOKS
+#include <sys/dtrace_bsd.h>
+
+/*
+ * This is a hook which is initialised by the dtrace module
+ * to handle traps which might occur during DTrace probe
+ * execution.
+ */
+dtrace_trap_func_t	dtrace_trap_func;
+
+dtrace_doubletrap_func_t	dtrace_doubletrap_func;
+
+/*
+ * This is a hook which is initialised by the systrace module
+ * when it is loaded. This keeps the DTrace syscall provider
+ * implementation opaque.=20
+ */
+systrace_probe_func_t	systrace_probe_func;
+
+/*
+ * These hooks are necessary for the pid, usdt and fasttrap providers.
+ */
+dtrace_fasttrap_probe_ptr_t	dtrace_fasttrap_probe_ptr;
+dtrace_pid_probe_ptr_t		dtrace_pid_probe_ptr;
+dtrace_return_probe_ptr_t	dtrace_return_probe_ptr;
+#endif
+
 #ifdef TRAP_DEBUG
 int trap_debug =3D 0;
 SYSCTL_INT(_machdep, OID_AUTO, trap_debug, CTLFLAG_RW,
@@ -262,6 +290,20 @@
 SYSCTL_INT(_vm, OID_AUTO, allow_unaligned_acc, CTLFLAG_RW,
     &allow_unaligned_acc, 0, "Allow unaligned accesses");
=20
+/*
+ * FP emulation is assumed to work on O32, but the code is outdated and cr=
ufty
+ * enough that it's a more sensible default to have it disabled when using
+ * other ABIs.  At the very least, it needs a lot of help in using
+ * type-semantic ABI-oblivious macros for everything it does.
+ */
+#if defined(__mips_o32)
+static int emulate_fp =3D 1;
+#else
+static int emulate_fp =3D 0;
+#endif
+SYSCTL_INT(_machdep, OID_AUTO, emulate_fp, CTLFLAG_RW,
+    &allow_unaligned_acc, 0, "Emulate unimplemented FPU instructions");
+
 static int emulate_unaligned_access(struct trapframe *frame, int mode);
=20
 extern void fswintrberr(void); /* XXX */
@@ -529,6 +571,29 @@
 		}
 	}
 #endif
+
+#ifdef KDTRACE_HOOKS
+	/*
+	 * A trap can occur while DTrace executes a probe. Before
+	 * executing the probe, DTrace blocks re-scheduling and sets
+	 * a flag in it's per-cpu flags to indicate that it doesn't
+	 * want to fault. On returning from the probe, the no-fault
+	 * flag is cleared and finally re-scheduling is enabled.
+	 *
+	 * If the DTrace kernel module has registered a trap handler,
+	 * call it and if it returns non-zero, assume that it has
+	 * handled the trap and modified the trap frame so that this
+	 * function can return normally.
+	 */
+	/*
+	 * XXXDTRACE: add fasttrap and pid  probes handlers here (if ever)
+	 */
+	if (!usermode) {
+		if (dtrace_trap_func !=3D NULL && (*dtrace_trap_func)(trapframe, type))
+			return (trapframe->pc);
+	}
+#endif
+
 	switch (type) {
 	case T_MCHECK:
 #ifdef DDB
@@ -633,6 +698,9 @@
 			PROC_LOCK(p);
 			--p->p_lock;
 			PROC_UNLOCK(p);
+			/*
+			 * XXXDTRACE: add dtrace_doubletrap_func here?
+			 */
 #ifdef VMFAULT_TRACE
 			printf("vm_fault(%p (pmap %p), %p (%p), %x, %d) -> %x at pc %p\n",
 			    map, &vm->vm_pmap, (void *)va, (void *)(intptr_t)trapframe->badvadd=
r,
@@ -934,6 +1002,11 @@
 #endif
=20
 	case T_FPE + T_USER:
+		if (!emulate_fp) {
+			i =3D SIGILL;
+			addr =3D trapframe->pc;
+			break;
+		}
 		MipsFPTrap(trapframe->sr, trapframe->cause, trapframe->pc);
 		goto out;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/board.c
--- a/head/sys/mips/nlm/board.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/board.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * NETLOGIC_BSD */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/board.c 225394 2011-09-05 10:45:29Z =
jchandra $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/board.c 233545 2012-03-27 14:05:12Z =
jchandra $");
 #include <sys/param.h>
 #include <sys/systm.h>
 #include <sys/bus.h>
@@ -36,44 +36,490 @@
 #include <sys/lock.h>
 #include <sys/mutex.h>
=20
+#include <net/ethernet.h>
+
 #include <mips/nlm/hal/mips-extns.h>
 #include <mips/nlm/hal/haldefs.h>
 #include <mips/nlm/hal/iomap.h>
 #include <mips/nlm/hal/fmn.h>
 #include <mips/nlm/hal/pic.h>
+#include <mips/nlm/hal/sys.h>
+#include <mips/nlm/hal/nae.h>
 #include <mips/nlm/hal/uart.h>
+#include <mips/nlm/hal/poe.h>
=20
+#include <mips/nlm/xlp.h>
 #include <mips/nlm/board.h>
+#include <mips/nlm/msgring.h>
+
+static uint8_t board_eeprom_buf[EEPROM_SIZE];
+static int board_eeprom_set;
=20
 struct xlp_board_info xlp_board_info;
=20
-int nlm_setup_xlp_board(void);
+struct vfbid_tbl {
+	int vfbid;
+	int dest_vc;
+};
+
+/* XXXJC : this should be derived from msg thread mask */
+static struct vfbid_tbl nlm_vfbid[] =3D {
+	/* NULL FBID should map to cpu0 to detect NAE send msg errors */
+	{127,   0}, /* NAE <-> NAE mappings */
+	{51, 1019}, {50, 1018}, {49, 1017}, {48, 1016},
+	{47, 1015}, {46, 1014}, {45, 1013}, {44, 1012},
+	{43, 1011}, {42, 1010}, {41, 1009}, {40, 1008},
+	{39, 1007}, {38, 1006}, {37, 1005}, {36, 1004},
+	{35, 1003}, {34, 1002}, {33, 1001}, {32, 1000},
+	/* NAE <-> CPU mappings, freeback got to vc 3 of each thread */=20
+	{31,  127}, {30,  123}, {29,  119}, {28,  115},
+	{27,  111}, {26,  107}, {25,  103}, {24,   99},
+	{23,   95}, {22,   91}, {21,   87}, {20,   83},
+	{19,   79}, {18,   75}, {17,   71}, {16,   67},
+	{15,   63}, {14,   59}, {13,   55}, {12,   51},
+	{11,   47}, {10,   43}, { 9,   39}, { 8,   35},
+	{ 7,   31}, { 6,   27}, { 5,   23}, { 4,   19},
+	{ 3,   15}, { 2,   11}, { 1,    7}, { 0,    3},
+};
+
+static struct vfbid_tbl nlm3xx_vfbid[] =3D {
+	/* NULL FBID should map to cpu0 to detect NAE send msg errors */
+	{127,   0}, /* NAE <-> NAE mappings */
+	{39,  503}, {38,  502}, {37,  501}, {36,  500},
+	{35,  499}, {34,  498}, {33,  497}, {32,  496},
+	/* NAE <-> CPU mappings, freeback got to vc 3 of each thread */=20
+	{31,  127}, {30,  123}, {29,  119}, {28,  115},
+	{27,  111}, {26,  107}, {25,  103}, {24,   99},
+	{23,   95}, {22,   91}, {21,   87}, {20,   83},
+	{19,   79}, {18,   75}, {17,   71}, {16,   67},
+	{15,   63}, {14,   59}, {13,   55}, {12,   51},
+	{11,   47}, {10,   43}, { 9,   39}, { 8,   35},
+	{ 7,   31}, { 6,   27}, { 5,   23}, { 4,   19},
+	{ 3,   15}, { 2,   11}, { 1,    7}, { 0,    3},
+};
+
+int
+nlm_get_vfbid_mapping(int vfbid)
+{
+	int i, nentries;
+	struct vfbid_tbl *p;
+
+	if (nlm_is_xlp3xx()) {
+		nentries =3D sizeof(nlm3xx_vfbid)/sizeof(struct vfbid_tbl);
+		p =3D nlm3xx_vfbid;
+	} else {
+		nentries =3D sizeof(nlm_vfbid)/sizeof(struct vfbid_tbl);
+		p =3D nlm_vfbid;
+	}
+
+	for (i =3D 0; i < nentries; i++) {
+		if (p[i].vfbid =3D=3D vfbid)
+		    return (p[i].dest_vc);
+	}
+
+	return (-1);
+}
+
+int
+nlm_get_poe_distvec(int vec, uint32_t *distvec)
+{
+
+	if (vec !=3D 0)
+		return (-1);  /* we support just vec 0 */
+	nlm_calc_poe_distvec(xlp_msg_thread_mask, 0, 0, 0,
+	    0x1 << XLPGE_RX_VC, distvec);
+	return (0);
+}
=20
 /*
  * All our knowledge of chip and board that cannot be detected by probing
  * at run-time goes here
  */
=20
-int
+void
+xlpge_get_macaddr(uint8_t *macaddr)
+{
+
+	if (board_eeprom_set =3D=3D 0) {
+		/* No luck, take some reasonable value */
+		macaddr[0] =3D 0x00; macaddr[1] =3D 0x0f; macaddr[2] =3D 0x30;
+		macaddr[3] =3D 0x20; macaddr[4] =3D 0x0d; macaddr[5] =3D 0x5b;
+	} else
+		memcpy(macaddr, &board_eeprom_buf[EEPROM_MACADDR_OFFSET],
+		    ETHER_ADDR_LEN);
+}
+
+static void
+nlm_setup_port_defaults(struct xlp_port_ivars *p)
+{
+	p->loopback_mode =3D 0;
+	p->num_channels =3D 1;
+	p->free_desc_sizes =3D 2048;
+	p->vlan_pri_en =3D 0;
+	p->hw_parser_en =3D 1;
+	p->ieee1588_userval =3D 0;
+	p->ieee1588_ptpoff =3D 0;
+	p->ieee1588_tmr1 =3D 0;
+	p->ieee1588_tmr2 =3D 0;
+	p->ieee1588_tmr3 =3D 0;
+	p->ieee1588_inc_intg =3D 0;
+	p->ieee1588_inc_den =3D 1;
+	p->ieee1588_inc_num =3D 1;
+
+	if (nlm_is_xlp3xx()) {
+		p->stg2_fifo_size =3D XLP3XX_STG2_FIFO_SZ;
+		p->eh_fifo_size =3D XLP3XX_EH_FIFO_SZ;
+		p->frout_fifo_size =3D XLP3XX_FROUT_FIFO_SZ;
+		p->ms_fifo_size =3D XLP3XX_MS_FIFO_SZ;
+		p->pkt_fifo_size =3D XLP3XX_PKT_FIFO_SZ;
+		p->pktlen_fifo_size =3D XLP3XX_PKTLEN_FIFO_SZ;
+		p->max_stg2_offset =3D XLP3XX_MAX_STG2_OFFSET;
+		p->max_eh_offset =3D XLP3XX_MAX_EH_OFFSET;
+		p->max_frout_offset =3D XLP3XX_MAX_FREE_OUT_OFFSET;
+		p->max_ms_offset =3D XLP3XX_MAX_MS_OFFSET;
+		p->max_pmem_offset =3D XLP3XX_MAX_PMEM_OFFSET;
+		p->stg1_2_credit =3D XLP3XX_STG1_2_CREDIT;
+		p->stg2_eh_credit =3D XLP3XX_STG2_EH_CREDIT;
+		p->stg2_frout_credit =3D XLP3XX_STG2_FROUT_CREDIT;
+		p->stg2_ms_credit =3D XLP3XX_STG2_MS_CREDIT;
+	} else {
+		p->stg2_fifo_size =3D XLP8XX_STG2_FIFO_SZ;
+		p->eh_fifo_size =3D XLP8XX_EH_FIFO_SZ;
+		p->frout_fifo_size =3D XLP8XX_FROUT_FIFO_SZ;
+		p->ms_fifo_size =3D XLP8XX_MS_FIFO_SZ;
+		p->pkt_fifo_size =3D XLP8XX_PKT_FIFO_SZ;
+		p->pktlen_fifo_size =3D XLP8XX_PKTLEN_FIFO_SZ;
+		p->max_stg2_offset =3D XLP8XX_MAX_STG2_OFFSET;
+		p->max_eh_offset =3D XLP8XX_MAX_EH_OFFSET;
+		p->max_frout_offset =3D XLP8XX_MAX_FREE_OUT_OFFSET;
+		p->max_ms_offset =3D XLP8XX_MAX_MS_OFFSET;
+		p->max_pmem_offset =3D XLP8XX_MAX_PMEM_OFFSET;
+		p->stg1_2_credit =3D XLP8XX_STG1_2_CREDIT;
+		p->stg2_eh_credit =3D XLP8XX_STG2_EH_CREDIT;
+		p->stg2_frout_credit =3D XLP8XX_STG2_FROUT_CREDIT;
+		p->stg2_ms_credit =3D XLP8XX_STG2_MS_CREDIT;
+	}
+
+	switch (p->type) {
+	case SGMIIC:
+		p->num_free_descs =3D 52;
+		p->iface_fifo_size =3D 13;
+		p->rxbuf_size =3D 128;
+		p->rx_slots_reqd =3D SGMII_CAL_SLOTS;
+		p->tx_slots_reqd =3D SGMII_CAL_SLOTS;
+		if (nlm_is_xlp3xx())
+		    p->pseq_fifo_size =3D 30;
+		else
+		    p->pseq_fifo_size =3D 62;
+		break;
+	case ILC:
+		p->num_free_descs =3D 150;
+		p->rxbuf_size =3D 944;
+		p->rx_slots_reqd =3D IL8_CAL_SLOTS;
+		p->tx_slots_reqd =3D IL8_CAL_SLOTS;
+		p->pseq_fifo_size =3D 225;
+		p->iface_fifo_size =3D 55;
+		break;
+	case XAUIC:
+	default:
+		p->num_free_descs =3D 150;
+		p->rxbuf_size =3D 944;
+		p->rx_slots_reqd =3D XAUI_CAL_SLOTS;
+		p->tx_slots_reqd =3D XAUI_CAL_SLOTS;
+		if (nlm_is_xlp3xx()) {
+		    p->pseq_fifo_size =3D 120;
+		    p->iface_fifo_size =3D 52;
+		} else {
+		    p->pseq_fifo_size =3D 225;
+		    p->iface_fifo_size =3D 55;
+		}
+		break;
+	}
+}
+
+/* XLP 8XX evaluation boards have the following phy-addr
+ * assignment. There are two external mdio buses in XLP --
+ * bus 0 and bus 1. The management ports (16 and 17) are
+ * on mdio bus 0 while blocks/complexes[0 to 3] are all=20
+ * on mdio bus 1. The phy_addr on bus 0 (mgmt ports 16
+ * and 17) match the port numbers.
+ * These are the details:
+ * block  port   phy_addr   mdio_bus
+ * =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
+ * 0         0     4          1
+ * 0         1     7          1
+ * 0         2     6          1
+ * 0         3     5          1
+ * 1         0     8          1
+ * 1         1     11         1
+ * 1         2     10         1
+ * 1         3     9          1
+ * 2         0     0          1
+ * 2         1     3          1
+ * 2         2     2          1
+ * 2         3     1          1
+ * 3         0     12         1
+ * 3         1     15         1
+ * 3         2     14         1
+ * 3         3     13         1
+ *
+ * 4         0     16         0=20
+ * 4         1     17         0
+ *
+ * The XLP 3XX evaluation boards have the following phy-addr
+ * assignments.
+ * block  port   phy_addr   mdio_bus
+ * =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
+ * 0         0     4          0
+ * 0         1     7          0
+ * 0         2     6          0
+ * 0         3     5          0
+ * 1         0     8          0
+ * 1         1     11         0
+ * 1         2     10         0
+ * 1         3     9          0
+ */
+static void
+nlm_board_get_phyaddr(int block, int port, int *mdio, int *phyaddr)
+{
+
+	/* XXXJC: this is a board feature, check for chip not proper */
+	if (nlm_is_xlp3xx() || (nlm_is_xlp8xx() && block =3D=3D 4))
+	    *mdio =3D 0;
+	else
+	    *mdio =3D 1;
+
+	switch (block) {
+	case 0: switch (port) {
+		case 0: *phyaddr =3D 4; break;
+		case 1: *phyaddr =3D 7; break;
+		case 2: *phyaddr =3D 6; break;
+		case 3: *phyaddr =3D 5; break;
+		}
+		break;
+	case 1: switch (port) {
+		case 0: *phyaddr =3D 8; break;
+		case 1: *phyaddr =3D 11; break;
+		case 2: *phyaddr =3D 10; break;
+		case 3: *phyaddr =3D 9; break;
+		}
+		break;
+	case 2: switch (port) {
+		case 0: *phyaddr =3D 0; break;
+		case 1: *phyaddr =3D 3; break;
+		case 2: *phyaddr =3D 2; break;
+		case 3: *phyaddr =3D 1; break;
+		}
+		break;
+	case 3: switch (port) {
+		case 0: *phyaddr =3D 12; break;
+		case 1: *phyaddr =3D 15; break;
+		case 2: *phyaddr =3D 14; break;
+		case 3: *phyaddr =3D 13; break;
+		}
+		break;
+	case 4: switch (port) { /* management SGMII */
+		case 0: *phyaddr =3D 16; break;
+		case 1: *phyaddr =3D 17; break;
+		}
+		break;
+	}
+}
+
+
+static void
+nlm_print_processor_info(void)
+{
+	uint32_t procid;
+	int prid, rev;
+	char *chip, *revstr;
+
+	procid =3D mips_rd_prid();
+	prid =3D (procid >> 8) & 0xff;
+	rev =3D procid & 0xff;
+
+	switch (prid) {
+	case CHIP_PROCESSOR_ID_XLP_8XX:
+		chip =3D "XLP 832";
+		break;
+	case CHIP_PROCESSOR_ID_XLP_3XX:
+		chip =3D "XLP 3xx";
+		break;
+	case CHIP_PROCESSOR_ID_XLP_432:
+	case CHIP_PROCESSOR_ID_XLP_416:
+		chip =3D "XLP 4xx";
+		break;
+	default:
+		chip =3D "XLP ?xx";
+		break;
+	}
+	switch (rev) {
+	case 0:
+		revstr =3D "A0"; break;
+	case 1:
+		revstr =3D "A1"; break;
+	case 2:
+		revstr =3D "A2"; break;
+	case 3:
+		revstr =3D "B0"; break;
+	default:
+		revstr =3D "??"; break;
+	}
+
+	printf("Processor info:\n");
+	printf("  Netlogic %s %s [%x]\n", chip, revstr, procid);
+}
+
+/*
+ * All our knowledge of chip and board that cannot be detected by probing=20
+ * at run-time goes here
+ */
+static int
 nlm_setup_xlp_board(void)
 {
 	struct xlp_board_info	*boardp;
-	int	node;
+	struct xlp_node_info	*nodep;
+	struct xlp_nae_ivars	*naep;
+	struct xlp_block_ivars	*blockp;
+	struct xlp_port_ivars	*portp;
+	uint64_t cpldbase, nae_pcibase;
+	int	node, block, port, rv, dbtype, usecpld;
+	uint8_t *b;
=20
 	/* start with a clean slate */
 	boardp =3D &xlp_board_info;
 	memset(boardp, 0, sizeof(xlp_board_info));
 	boardp->nodemask =3D 0x1;	/* only node 0 */
+	nlm_print_processor_info();
+
+	b =3D  board_eeprom_buf;
+	rv =3D nlm_board_eeprom_read(0, EEPROM_I2CBUS, EEPROM_I2CADDR, 0, b,
+	    EEPROM_SIZE);
+	if (rv =3D=3D 0) {
+		board_eeprom_set =3D 1;
+		printf("Board info (EEPROM on i2c@%d at %#X):\n",
+		    EEPROM_I2CBUS, EEPROM_I2CADDR);
+		printf("  Model:      %7.7s %2.2s\n", &b[16], &b[24]);
+		printf("  Serial #:   %3.3s-%2.2s\n", &b[27], &b[31]);
+		printf("  MAC addr:   %02x:%02x:%02x:%02x:%02x:%02x\n",
+		    b[2], b[3], b[4], b[5], b[6], b[7]);
+	} else
+		printf("Board Info: Error on EEPROM read (i2c@%d %#X).\n",
+		    EEPROM_I2CBUS, EEPROM_I2CADDR);
+
+
+	/* XXXJC: check for boards with right CPLD, for now
+	 *        4xx PCI cards don't have CPLD with daughter
+	 *        card info */
+	usecpld =3D !nlm_is_xlp4xx();
=20
 	for (node =3D 0; node < XLP_MAX_NODES; node++) {
 		if ((boardp->nodemask & (1 << node)) =3D=3D 0)
 			continue;
+		nae_pcibase =3D nlm_get_nae_pcibase(node);
+		nodep =3D &boardp->nodes[node];
+		naep =3D &nodep->nae_ivars;
+		naep->node =3D node;
+
+		naep->nblocks =3D nae_num_complex(nae_pcibase);
+		/* 3xx chips lie shamelessly about this */
+		if (nlm_is_xlp3xx())
+			naep->nblocks =3D naep->nblocks - 1;
+		naep->blockmask =3D (1 << naep->nblocks) - 1;	/* XXXJC: redundant */
+		naep->xauimask =3D 0x0;	/* set this based on daughter card */
+		naep->sgmiimask =3D 0x0;	/* set this based on daughter card */
+
+		/* frequency at which network block runs */
+		naep->freq =3D 500;
+
+		/* CRC16 polynomial used for flow table generation */
+		naep->flow_crc_poly =3D 0xffff;
+		naep->hw_parser_en =3D 1;
+		naep->prepad_en =3D 1;
+		naep->prepad_size =3D 3; /* size in 16 byte units */
+
+		naep->ieee_1588_en =3D 1;
+		cpldbase =3D nlm_board_cpld_base(node, XLP_EVB_CPLD_CHIPSELECT);
+
+		for (block =3D 0; block < naep->nblocks; block++) {
+			blockp =3D &naep->block_ivars[block];
+			blockp->block =3D block;
+			if (usecpld)
+				dbtype =3D nlm_board_cpld_dboard_type(cpldbase,
+				    block);
+			else
+				dbtype =3D DCARD_XAUI;  /* default XAUI */
+
+			if (block =3D=3D 4) {
+				/* management block 4 on 8xx */
+				blockp->type =3D SGMIIC;
+				blockp->portmask =3D 0x3;
+				naep->sgmiimask |=3D (1 << block);
+			} else {
+				switch (dbtype) {
+				case DCARD_ILAKEN:
+					blockp->type =3D ILC;
+					blockp->portmask =3D 0x1;
+					naep->xauimask |=3D (1 << block);
+					break;
+				case DCARD_SGMII:
+					blockp->type =3D SGMIIC;
+					blockp->portmask =3D 0xf;
+					naep->sgmiimask |=3D (1 << block);
+					break;
+				case DCARD_XAUI:
+				default:
+					blockp->type =3D XAUIC;
+					blockp->portmask =3D 0x1;
+					naep->xauimask |=3D (1 << block);
+					break;
+				}
+			}
+			for (port =3D 0; port < PORTS_PER_CMPLX; port++) {
+				if ((blockp->portmask & (1 << port)) =3D=3D 0)
+					continue;
+				portp =3D &blockp->port_ivars[port];
+				nlm_board_get_phyaddr(block, port,
+				    &portp->mdio_bus, &portp->phy_addr);
+				portp->port =3D port;
+				portp->block =3D block;
+				portp->node =3D node;
+				portp->type =3D blockp->type;
+				nlm_setup_port_defaults(portp);
+			}
+		}
 	}
-	return 0;
+
+	/* pretty print network config */
+	printf("Network config");
+	if (usecpld)
+		printf("(from CPLD@%d):\n", XLP_EVB_CPLD_CHIPSELECT);
+	else
+		printf("(defaults):\n");
+	for (node =3D 0; node < XLP_MAX_NODES; node++) {
+		if ((boardp->nodemask & (1 << node)) =3D=3D 0)
+			continue;
+		nodep =3D &boardp->nodes[node];
+		naep =3D &nodep->nae_ivars;
+		printf("  NAE@%d Blocks: ", node);
+		for (block =3D 0; block < naep->nblocks; block++) {
+			char *s =3D "???";
+
+			blockp =3D &naep->block_ivars[block];
+			switch (blockp->type) {
+				case SGMIIC : s =3D "SGMII"; break;
+				case XAUIC  : s =3D "XAUI"; break;
+				case ILC    : s =3D "IL"; break;
+			}
+			printf(" [%d %s]", block, s);
+		}
+		printf("\n");
+	}
+	return (0);
 }
=20
-int nlm_board_info_setup()
+int nlm_board_info_setup(void)
 {
 	nlm_setup_xlp_board();
-	return 0;
+	return (0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/board.h
--- a/head/sys/mips/nlm/board.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/board.h	Tue Apr 17 11:51:51 2012 +0300
@@ -5,7 +5,7 @@
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
  * met:
- *
+ *=20
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
@@ -26,7 +26,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/board.h 225394 2011-09-05 10:45:29Z jchandr=
a $
+ * $FreeBSD: head/sys/mips/nlm/board.h 233549 2012-03-27 14:48:40Z jchandr=
a $
  */
=20
 #ifndef __NLM_BOARD_H__
@@ -34,19 +34,75 @@
=20
 #define XLP_NAE_NBLOCKS		5
 #define XLP_NAE_NPORTS		4
-#define	XLP_I2C_MAXDEVICES	8
=20
-struct xlp_i2c_devinfo {
-	u_int	addr;		/* keep first, for i2c ivars to work */
-	int	bus;
-	char	*device;
-};
+/*
+ * EVP board EEPROM info
+ */
+#define	EEPROM_I2CBUS		1
+#define	EEPROM_I2CADDR		0xAE
+#define	EEPROM_SIZE	 	48
+#define	EEPROM_MACADDR_OFFSET	2
+
+/* used if there is no FDT */
+#define	BOARD_CONSOLE_SPEED	115200
+#define	BOARD_CONSOLE_UART	0
+
+/*
+ * EVP board CPLD chip select and daughter card info field
+ */
+#define XLP_EVB_CPLD_CHIPSELECT	2
+
+#define DCARD_ILAKEN		0x0
+#define DCARD_SGMII		0x1
+#define DCARD_XAUI		0x2
+#define DCARD_NOT_PRSNT		0x3
+
+#if !defined(LOCORE) && !defined(__ASSEMBLY__)
+/*
+ * NAE configuration
+ */
=20
 struct xlp_port_ivars {
 	int	port;
 	int	block;
+	int	node;
 	int	type;
 	int	phy_addr;
+	int	mdio_bus;
+	int	loopback_mode;
+	int	num_channels;
+	int	free_desc_sizes;
+	int	num_free_descs;
+	int	pseq_fifo_size;
+	int	iface_fifo_size;
+	int	rxbuf_size;
+	int	rx_slots_reqd;
+	int	tx_slots_reqd;
+	int	vlan_pri_en;
+	int	stg2_fifo_size;
+	int	eh_fifo_size;
+	int	frout_fifo_size;
+	int	ms_fifo_size;
+	int	pkt_fifo_size;
+	int	pktlen_fifo_size;
+	int	max_stg2_offset;
+	int	max_eh_offset;
+	int	max_frout_offset;
+	int	max_ms_offset;
+	int	max_pmem_offset;
+	int	stg1_2_credit;
+	int	stg2_eh_credit;
+	int	stg2_frout_credit;
+	int	stg2_ms_credit;
+	int	hw_parser_en;
+	u_int	ieee1588_inc_intg;
+	u_int	ieee1588_inc_den;
+	u_int	ieee1588_inc_num;
+	uint64_t ieee1588_userval;
+	uint64_t ieee1588_ptpoff;
+	uint64_t ieee1588_tmr1;
+	uint64_t ieee1588_tmr2;
+	uint64_t ieee1588_tmr3;
 };
=20
 struct xlp_block_ivars {
@@ -58,19 +114,43 @@
=20
 struct xlp_nae_ivars {
 	int 	node;
+	int	nblocks;
 	u_int	blockmask;
+	u_int	xauimask;
+	u_int	sgmiimask;
+	int	freq;
+	u_int	flow_crc_poly;
+	u_int	hw_parser_en;
+	u_int	prepad_en;
+	u_int	prepad_size;	/* size in 16 byte units */
+	u_int	ieee_1588_en;
 	struct xlp_block_ivars	block_ivars[XLP_NAE_NBLOCKS];
 };
=20
 struct xlp_board_info {
 	u_int	nodemask;
 	struct xlp_node_info {
-		struct xlp_i2c_devinfo	i2c_devs[XLP_I2C_MAXDEVICES];
 		struct xlp_nae_ivars	nae_ivars;
 	} nodes[XLP_MAX_NODES];
 };
=20
 extern struct xlp_board_info xlp_board_info;
+
+/* Network configuration */
+int nlm_get_vfbid_mapping(int);
+int nlm_get_poe_distvec(int vec, uint32_t *distvec);
+void xlpge_get_macaddr(uint8_t *macaddr);
+
 int nlm_board_info_setup(void);
=20
+/* EEPROM & CPLD */
+int nlm_board_eeprom_read(int node, int i2cbus, int addr, int offs,
+    uint8_t *buf,int sz);
+uint64_t nlm_board_cpld_base(int node, int chipselect);
+int nlm_board_cpld_majorversion(uint64_t cpldbase);
+int nlm_board_cpld_minorversion(uint64_t cpldbase);
+void nlm_board_cpld_reset(uint64_t cpldbase);
+int nlm_board_cpld_dboard_type(uint64_t cpldbase, int slot);
+
 #endif
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/cms.c
--- a/head/sys/mips/nlm/cms.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/cms.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * NETLOGIC_BSD */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/cms.c 227783 2011-11-21 08:12:36Z jc=
handra $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/cms.c 233534 2012-03-27 07:47:13Z jc=
handra $");
 #include <sys/types.h>
 #include <sys/systm.h>
 #include <sys/param.h>
@@ -65,9 +65,8 @@
 #include <mips/nlm/msgring.h>
 #include <mips/nlm/interrupt.h>
 #include <mips/nlm/xlp.h>
-#include <mips/nlm/board.h>
=20
-#define MSGRNG_NSTATIONS 1024
+#define	MSGRNG_NSTATIONS	1024
 /*
  * Keep track of our message ring handler threads, each core has a
  * different message station. Ideally we will need to start a few
@@ -92,7 +91,7 @@
 static struct tx_stn_handler msgmap[MSGRNG_NSTATIONS];
 static struct mtx	msgmap_lock;
 uint32_t xlp_msg_thread_mask;
-static int xlp_msg_threads_per_core =3D 3;
+static int xlp_msg_threads_per_core =3D XLP_MAX_THREADS;
=20
 static void create_msgring_thread(int hwtid);
 static int msgring_process_fast_intr(void *arg);
@@ -105,7 +104,7 @@
 static int fmn_loops[XLP_MAX_CORES * XLP_MAX_THREADS];
=20
 /* Whether polled driver implementation */
-static int polled =3D 1;
+static int polled =3D 0;
=20
 /* We do only i/o device credit setup here. CPU credit setup is now
  * moved to xlp_msgring_cpu_init() so that the credits get setup=20
@@ -125,7 +124,7 @@
 	for (i =3D 0; i < XLP_MAX_NODES; i++) {
 		cmspcibase =3D nlm_get_cms_pcibase(i);
 		if (!nlm_dev_exists(XLP_IO_CMS_OFFSET(i)))
-		    continue;
+			continue;
 		cmsbase =3D nlm_get_cms_regbase(i);
 		maxqid =3D nlm_read_reg(cmspcibase, XLP_PCI_DEVINFO_REG0);
 		for (dev =3D 0; dev < 8; dev++) {
@@ -136,7 +135,7 @@
 				pcibase =3D nlm_pcicfg_base(devoffset);
 				src =3D nlm_qidstart(pcibase);
 				if (src =3D=3D 0)
-				    continue;
+					continue;
 #if 0 /* Debug */
 				printf("Setup CMS credits for queues ");
 				printf("[%d to %d] from src %d\n", 0,
@@ -163,7 +162,7 @@
 	if((cpu % 4) =3D=3D 0) {
 		src =3D cpu << 2; /* each thread has 4 vc's */
 		for (qid =3D 0; qid < maxqid; qid++)
-		    nlm_cms_setup_credits(cmsbase, qid, src, credit);
+			nlm_cms_setup_credits(cmsbase, qid, src, credit);
 	}
 }
=20
@@ -181,7 +180,6 @@
 	int n_msgs =3D 0, vc, m, hwtid;
 	u_int msgmask;
=20
-
 	hwtid =3D nlm_cpuid();
 	for (;;) {
 		/* check if VC empty */
@@ -211,8 +209,9 @@
 			}
 			he =3D &msgmap[srcid];
 			if(he->action !=3D NULL)
-				(he->action)(vc, size, code, srcid, &msg, he->arg);
-#if 1 /* defined DEBUG */
+				(he->action)(vc, size, code, srcid, &msg,
+				he->arg);
+#if 0
 			else
 				printf("[%s]: No Handler for msg from stn %d,"
 				    " vc=3D%d, size=3D%d, msg0=3D%jx, droppinge\n",
@@ -226,7 +225,7 @@
 			break;	/* nothing done in this iter */
 		n_msgs +=3D m;
 		if (max_msgs > 0 && n_msgs >=3D max_msgs)
-		    break;
+			break;
 	}
=20
 	return (n_msgs);
@@ -248,7 +247,7 @@
=20
 			/* break if there is no msg or error */
 			if (status !=3D 0)
-			    break;
+				break;
 		}
 	}
 }
@@ -382,9 +381,6 @@
 	sched_class(td, PRI_ITHD);
 	sched_add(td, SRQ_INTR);
 	thread_unlock(td);
-	if (bootverbose)
-		printf("Msgring handler create on cpu %d (%s)\n",
-		    hwtid, td->td_name);
 }
=20
 int
@@ -393,7 +389,9 @@
 {
 	int	i;
=20
-	printf("Register handler %d-%d %p(%p)\n", startb, endb, action, arg);
+	if (bootverbose)
+		printf("Register handler %d-%d %p(%p)\n",
+		    startb, endb, action, arg);
 	KASSERT(startb >=3D 0 && startb <=3D endb && endb < MSGRNG_NSTATIONS,
 	    ("Invalid value for bucket range %d,%d", startb, endb));
=20
@@ -421,11 +419,18 @@
 	unsigned int thrmask, mask;
 	int i;
=20
+	/* used polled handler for Ax silion */
+	if (nlm_is_xlp8xx_ax())
+		polled =3D 1;
+
+	/* Don't poll on all threads, if polled */
+	if (polled)
+		xlp_msg_threads_per_core -=3D 1;
+
 	mtx_init(&msgmap_lock, "msgring", NULL, MTX_SPIN);
 	if (xlp_threads_per_core < xlp_msg_threads_per_core)
 		xlp_msg_threads_per_core =3D xlp_threads_per_core;
 	thrmask =3D ((1 << xlp_msg_threads_per_core) - 1);
-	/*thrmask <<=3D xlp_threads_per_core - xlp_msg_threads_per_core;*/
 	mask =3D 0;
 	for (i =3D 0; i < XLP_MAX_CORES; i++) {
 		mask <<=3D XLP_MAX_THREADS;
@@ -436,11 +441,6 @@
 	printf("CMS Message handler thread mask %#jx\n",
 	    (uintmax_t)xlp_msg_thread_mask);
 #endif
-
-	if (nlm_is_xlp3xx())
-	    polled =3D 0;		/* switch to interrupt driven driver */
-
-/*	nlm_cms_default_setup(0,0,0,0); */
 	xlp_cms_credit_setup(CMS_DEFAULT_CREDIT);
 	create_msgring_thread(0);
 	cpu_establish_hardintr("msgring", msgring_process_fast_intr, NULL,
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/files.xlp
--- a/head/sys/mips/nlm/files.xlp	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/files.xlp	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/mips/nlm/files.xlp 227783 2011-11-21 08:12:36Z jchand=
ra $
+# $FreeBSD: head/sys/mips/nlm/files.xlp 233637 2012-03-29 02:03:06Z jmalle=
tt $
 mips/nlm/hal/nlm_hal.c				standard
 mips/nlm/hal/fmn.c				standard
 mips/nlm/xlp_machdep.c				standard
@@ -9,8 +9,34 @@
 mips/nlm/bus_space_rmi.c			standard
 mips/nlm/bus_space_rmi_pci.c			standard
 mips/nlm/mpreset.S				standard
+mips/nlm/board_eeprom.c				standard
+mips/nlm/board_cpld.c				standard
 mips/nlm/xlp_pci.c				optional pci
-mips/nlm/intern_dev.c				optional pci
-mips/nlm/uart_pci_xlp.c				optional uart
 mips/nlm/uart_cpu_xlp.c				optional uart
 mips/nlm/usb_init.c				optional usb
+#
+# Simple SoC devices
+mips/nlm/dev/uart_pci_xlp.c			optional uart
+mips/nlm/dev/cfi_pci_xlp.c			optional cfi
+#
+# Network driver and micro-core code
+mips/nlm/dev/net/nae.c				optional xlpge
+mips/nlm/dev/net/mdio.c				optional xlpge
+mips/nlm/dev/net/sgmii.c			optional xlpge
+mips/nlm/dev/net/xaui.c				optional xlpge
+mips/nlm/dev/net/xlpge.c			optional xlpge
+ucore_app.bin					optional xlpge	\
+	compile-with	"${CC} -EB -march=3Dmips32 -mabi=3D32 -msoft-float -I. -I$S =
-O3 -funroll-loops -finline-limit=3D20000 -fno-tree-loop-optimize -fomit-fr=
ame-pointer -mno-branch-likely -fno-pic -mno-abicalls -ffunction-sections -=
fdata-sections -G0 -Wall -Werror -c $S/$M/nlm/dev/net/ucore/crt0_basic.S  $=
S/$M/nlm/dev/net/ucore/ucore_app.c && ${LD} -melf32btsmip_fbsd -d -warn-com=
mon -T$S/$M/nlm/dev/net/ucore/ld.ucore.S crt0_basic.o ucore_app.o -o ucore_=
app && ${OBJCOPY} -S -O binary -R .note -R .comment ucore_app ${.TARGET}" \
+	no-obj no-implicit-rule	before-depend			\
+	clean		"crt0_basic.o ucore_app.o ucore_app ucore_app.bin"
+ucore_app_bin.h					optional xlpge	\
+	dependency	"ucore_app.bin"				\
+	compile-with	"file2c -sx 'static char ucore_app_bin[] =3D {' '};' < ucore=
_app.bin > ${.TARGET}" \
+	no-obj no-implicit-rule	before-depend			\
+	clean		"ucore_app_bin.h"
+#
+# Security Driver
+#
+mips/nlm/dev/sec/nlmsec.c			optional nlmsec
+mips/nlm/dev/sec/nlmseclib.c			optional nlmsec
+mips/nlm/dev/sec/nlmrsa.c			optional nlmrsa
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/hal/iomap.h
--- a/head/sys/mips/nlm/hal/iomap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/hal/iomap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/hal/iomap.h 227783 2011-11-21 08:12:36Z jch=
andra $
+ * $FreeBSD: head/sys/mips/nlm/hal/iomap.h 233545 2012-03-27 14:05:12Z jch=
andra $
  */
=20
 #ifndef __NLM_HAL_IOMAP_H__
@@ -36,6 +36,7 @@
 #define	NMI_BASE			0xbfc00000
 #define	XLP_IO_CLK			133333333
=20
+#define	XLP_L2L3_CACHELINE_SIZE		64
 #define	XLP_PCIE_CFG_SIZE		0x1000		/* 4K */
 #define	XLP_PCIE_DEV_BLK_SIZE		(8 * XLP_PCIE_CFG_SIZE)
 #define	XLP_PCIE_BUS_BLK_SIZE		(256 * XLP_PCIE_DEV_BLK_SIZE)
@@ -185,11 +186,21 @@
 }
=20
 static __inline__ int
-nlm_uenginenum(uint64_t pcibase)
+nlm_num_uengines(uint64_t pcibase)
 {
 	return nlm_read_reg(pcibase, XLP_PCI_UCODEINFO_REG);
 }
=20
+/*
+ * Find node on which a given Soc device is located.
+ * input is the pci device (slot) number.
+ */
+static __inline__ int
+nlm_get_device_node(int device)
+{
+	return (device / 8);
+}
+
 #endif /* !LOCORE or !__ASSEMBLY */
=20
 #endif /* __NLM_HAL_IOMAP_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/hal/nlm_hal.c
--- a/head/sys/mips/nlm/hal/nlm_hal.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/hal/nlm_hal.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * NETLOGIC_BSD */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/hal/nlm_hal.c 227783 2011-11-21 08:1=
2:36Z jchandra $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/hal/nlm_hal.c 233563 2012-03-27 15:3=
9:55Z jchandra $");
 #include <sys/param.h>
 #include <sys/types.h>
 #include <sys/systm.h>
@@ -37,134 +37,73 @@
 #include <mips/nlm/hal/haldefs.h>
 #include <mips/nlm/hal/iomap.h>
 #include <mips/nlm/hal/sys.h>
-#include <mips/nlm/hal/pic.h>
 #include <mips/nlm/xlp.h>
=20
-#include <mips/nlm/hal/uart.h>
-#include <mips/nlm/hal/mmu.h>
-#include <mips/nlm/hal/pcibus.h>
-#include <mips/nlm/hal/usb.h>
-
-int pic_irt_ehci0;
-int pic_irt_ehci1;
-int pic_irt_uart0;
-int pic_irt_uart1;
-int pic_irt_pcie_lnk0;
-int pic_irt_pcie_lnk1;
-int pic_irt_pcie_lnk2;
-int pic_irt_pcie_lnk3;
-
 uint32_t
-xlp_get_cpu_frequency(int core)
+xlp_get_cpu_frequency(int node, int core)
 {
-	uint64_t sysbase =3D nlm_get_sys_regbase(nlm_nodeid());
-	uint64_t num;
+	uint64_t sysbase =3D nlm_get_sys_regbase(node);
 	unsigned int pll_divf, pll_divr, dfs_div, ext_div;
-	unsigned int rstval, dfsval, denom;
+	unsigned int rstval, dfsval;
=20
 	rstval =3D nlm_read_sys_reg(sysbase, SYS_POWER_ON_RESET_CFG);
 	dfsval =3D nlm_read_sys_reg(sysbase, SYS_CORE_DFS_DIV_VALUE);
 	pll_divf =3D ((rstval >> 10) & 0x7f) + 1;
 	pll_divr =3D ((rstval >> 8)  & 0x3) + 1;
-	ext_div  =3D ((rstval >> 30) & 0x3) + 1;
-	dfs_div  =3D ((dfsval >> (core * 4)) & 0xf) + 1;
+	if (!nlm_is_xlp8xx_ax())
+		ext_div =3D ((rstval >> 30) & 0x3) + 1;
+	else
+		ext_div =3D 1;
+	dfs_div  =3D ((dfsval >> (core << 2)) & 0xf) + 1;
=20
-	num =3D 800000000ULL * pll_divf;
-	denom =3D 3 * pll_divr * ext_div * dfs_div;
-	num =3D num/denom;
-	return (num);
+	return ((800000000ULL * pll_divf)/(3 * pll_divr * ext_div * dfs_div));
 }
=20
-void
-nlm_pic_irt_init(void)
+static u_int
+nlm_get_device_frequency(uint64_t sysbase, int devtype)
 {
-	pic_irt_ehci0 =3D nlm_irtstart(nlm_get_usb_pcibase(nlm_nodeid(), 0));
-	pic_irt_ehci1 =3D nlm_irtstart(nlm_get_usb_pcibase(nlm_nodeid(), 3));
-	pic_irt_uart0 =3D nlm_irtstart(nlm_get_uart_pcibase(nlm_nodeid(), 0));
-	pic_irt_uart1 =3D nlm_irtstart(nlm_get_uart_pcibase(nlm_nodeid(), 1));
+	uint32_t pllctrl, dfsdiv, spf, spr, div_val;
+	int extra_div;
=20
-	/* Hardcoding the PCIE IRT information as PIC doesn't=20
-	   understand any value other than 78,79,80,81 for PCIE0/1/2/3 */
-	pic_irt_pcie_lnk0 =3D 78;
-	pic_irt_pcie_lnk1 =3D 79;
-	pic_irt_pcie_lnk2 =3D 80;
-	pic_irt_pcie_lnk3 =3D 81;
-}
-/*
- * Find the IRQ for the link, each link has a different interrupt=20
- * at the XLP pic
- */
-int xlp_pcie_link_irt(int link)
-{
+	pllctrl =3D nlm_read_sys_reg(sysbase, SYS_PLL_CTRL);
+	if (devtype <=3D 7)
+		div_val =3D nlm_read_sys_reg(sysbase, SYS_DFS_DIV_VALUE0);
+	else {
+		devtype -=3D 8;
+		div_val =3D nlm_read_sys_reg(sysbase, SYS_DFS_DIV_VALUE1);
+	}
+	dfsdiv =3D ((div_val >> (devtype << 2)) & 0xf) + 1;
+	spf =3D (pllctrl >> 3 & 0x7f) + 1;
+	spr =3D (pllctrl >> 1 & 0x03) + 1;
+	extra_div =3D nlm_is_xlp8xx_ax() ? 1 : 2;
=20
-	if( (link < 0) || (link > 3))
-		return (-1);
-
-	return (pic_irt_pcie_lnk0 + link);
+	return ((400 * spf) / (3 * extra_div * spr * dfsdiv));
 }
=20
 int
-xlp_irt_to_irq(int irt)
+nlm_set_device_frequency(int node, int devtype, int frequency)
 {
-	if (irt =3D=3D pic_irt_ehci0)
-	    return PIC_EHCI_0_IRQ;
-	else if (irt =3D=3D pic_irt_ehci1)
-	    return PIC_EHCI_1_IRQ;
-	else if (irt =3D=3D pic_irt_uart0)
-	    return PIC_UART_0_IRQ;
-	else if (irt =3D=3D pic_irt_uart1)
-	    return PIC_UART_1_IRQ;
-	else if (irt =3D=3D pic_irt_pcie_lnk0)
-	    return PIC_PCIE_0_IRQ;
-	else if (irt =3D=3D pic_irt_pcie_lnk1)
-	    return PIC_PCIE_1_IRQ;
-	else if (irt =3D=3D pic_irt_pcie_lnk2)
-	    return PIC_PCIE_2_IRQ;
-	else if (irt =3D=3D pic_irt_pcie_lnk3)
-	    return PIC_PCIE_3_IRQ;
-	else {
-	    printf("Cannot find irq for IRT %d\n", irt);
-	    return 0;
-	 }
+	uint64_t sysbase;
+	u_int cur_freq;
+	int dec_div;
+
+	sysbase =3D nlm_get_sys_regbase(node);
+	cur_freq =3D nlm_get_device_frequency(sysbase, devtype);
+	if (cur_freq < (frequency - 5))
+		dec_div =3D 1;
+	else
+		dec_div =3D 0;
+
+	for(;;) {
+		if ((cur_freq >=3D (frequency - 5)) && (cur_freq <=3D frequency))
+			break;
+		if (dec_div)
+			nlm_write_sys_reg(sysbase, SYS_DFS_DIV_DEC_CTRL,
+			    (1 << devtype));
+		else
+			nlm_write_sys_reg(sysbase, SYS_DFS_DIV_INC_CTRL,
+			    (1 << devtype));
+		cur_freq =3D nlm_get_device_frequency(sysbase, devtype);
+	}
+	return (nlm_get_device_frequency(sysbase, devtype));
 }
-
-int
-xlp_irq_to_irt(int irq)
-{
-	switch (irq) {
- 		case PIC_EHCI_0_IRQ :
- 			return pic_irt_ehci0;
- 		case PIC_EHCI_1_IRQ :
- 			return pic_irt_ehci1;
-		case PIC_UART_0_IRQ :
-			return pic_irt_uart0;
-		case PIC_UART_1_IRQ :
-			return pic_irt_uart1;
-		case PIC_PCIE_0_IRQ :
-			return pic_irt_pcie_lnk0;
-		case PIC_PCIE_1_IRQ :
-			return pic_irt_pcie_lnk1;
-		case PIC_PCIE_2_IRQ :
-			return pic_irt_pcie_lnk2;
-		case PIC_PCIE_3_IRQ :
-			return pic_irt_pcie_lnk3;
-		default: panic("Bad IRQ %d\n", irq);
-	}
-}
-
-int
-xlp_irq_is_picintr(int irq)
-{
-	switch (irq) {
-		case PIC_MMC_IRQ : return 1;
- 		case PIC_EHCI_0_IRQ : return 1;
- 		case PIC_EHCI_1_IRQ : return 1;
-		case PIC_UART_0_IRQ : return 1;
-		case PIC_UART_1_IRQ : return 1;
-		case PIC_PCIE_0_IRQ : return 1;
-		case PIC_PCIE_1_IRQ : return 1;
-		case PIC_PCIE_2_IRQ : return 1;
-		case PIC_PCIE_3_IRQ : return 1;
-		default: return 0;
-	}
-}
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/hal/pcibus.h
--- a/head/sys/mips/nlm/hal/pcibus.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/hal/pcibus.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/hal/pcibus.h 227783 2011-11-21 08:12:36Z jc=
handra $
+ * $FreeBSD: head/sys/mips/nlm/hal/pcibus.h 233563 2012-03-27 15:39:55Z jc=
handra $
  */
=20
 #ifndef __XLP_PCIBUS_H__
@@ -57,16 +57,26 @@
=20
 #define	MSI_MIPS_DATA_INTVEC		0x000000ff
=20
-#define	PCIE_BRIDGE_CMD		0x1
-#define	PCIE_BRIDGE_MSI_CAP	0x14
-#define	PCIE_BRIDGE_MSI_ADDRL	0x15
-#define	PCIE_BRIDGE_MSI_ADDRH	0x16
-#define	PCIE_BRIDGE_MSI_DATA	0x17
+/* PCIE Memory and IO regions */
+#define	PCIE_MEM_BASE			0xd0000000ULL
+#define	PCIE_MEM_LIMIT			0xdfffffffULL
+#define	PCIE_IO_BASE			0x14000000ULL
+#define	PCIE_IO_LIMIT			0x15ffffffULL
+
+#define	PCIE_BRIDGE_CMD			0x1
+#define	PCIE_BRIDGE_MSI_CAP		0x14
+#define	PCIE_BRIDGE_MSI_ADDRL		0x15
+#define	PCIE_BRIDGE_MSI_ADDRH		0x16
+#define	PCIE_BRIDGE_MSI_DATA		0x17
=20
 /* XLP Global PCIE configuration space registers */
-#define	PCIE_MSI_STATUS		0x25A
-#define	PCIE_MSI_EN		0x25B
-#define	PCIE_INT_EN0		0x261
+#define	PCIE_BYTE_SWAP_MEM_BASE		0x247
+#define	PCIE_BYTE_SWAP_MEM_LIM		0x248
+#define	PCIE_BYTE_SWAP_IO_BASE		0x249
+#define	PCIE_BYTE_SWAP_IO_LIM		0x24A
+#define	PCIE_MSI_STATUS			0x25A
+#define	PCIE_MSI_EN			0x25B
+#define	PCIE_INT_EN0			0x261
=20
 /* PCIE_MSI_EN */
 #define	PCIE_MSI_VECTOR_INT_EN		0xFFFFFFFF
@@ -74,6 +84,9 @@
 /* PCIE_INT_EN0 */
 #define	PCIE_MSI_INT_EN			(1 << 9)
=20
+/* XXXJC: Ax workaround */
+#define	PCIE_LINK0_IRT			78
+
 #if !defined(LOCORE) && !defined(__ASSEMBLY__)
=20
 #define	nlm_read_pcie_reg(b, r)		nlm_read_reg(b, r)
@@ -83,6 +96,15 @@
 #define	nlm_get_pcie_regbase(node, inst)	\
 				(nlm_get_pcie_base(node, inst) + XLP_IO_PCI_HDRSZ)
=20
+static __inline int
+xlp_pcie_link_irt(int link)
+{
+	if ((link < 0) || (link > 3))
+		return (-1);
+
+	return (PCIE_LINK0_IRT + link);
+}
+
 /*
  * Build Intel MSI message and data values from a source.  AMD64 systems
  * seem to be compatible, so we use the same function for both.
@@ -96,8 +118,4 @@
 	 MSI_MIPS_DATA_ASSERT | (irq))
=20
 #endif
-
-#ifndef LOCORE
-int xlp_pcie_link_irt(int link);
-#endif
 #endif /* __XLP_PCIBUS_H__ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/hal/pic.h
--- a/head/sys/mips/nlm/hal/pic.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/hal/pic.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/hal/pic.h 227783 2011-11-21 08:12:36Z jchan=
dra $
+ * $FreeBSD: head/sys/mips/nlm/hal/pic.h 233563 2012-03-27 15:39:55Z jchan=
dra $
  */
=20
 #ifndef _NLM_HAL_PIC_H
@@ -174,7 +174,7 @@
=20
 #define	PIC_IRT_FIRST_IRQ		(PIC_IRQ_BASE)
 #define	PIC_IRT_LAST_IRQ		63
-#define	PIC_IRQ_IS_IRT(irq)		((irq) >=3D PIC_IRT_FIRST_IRQ)
+#define	XLP_IRQ_IS_PICINTR(irq)		((irq) >=3D PIC_IRT_FIRST_IRQ)
=20
 /*
  *   Misc
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/hal/sys.h
--- a/head/sys/mips/nlm/hal/sys.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/hal/sys.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,11 +26,11 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/hal/sys.h 225394 2011-09-05 10:45:29Z jchan=
dra $
+ * $FreeBSD: head/sys/mips/nlm/hal/sys.h 233533 2012-03-27 07:39:05Z jchan=
dra $
  */
=20
 #ifndef __NLM_HAL_SYS_H__
-#define __NLM_HAL_SYS_H__
+#define	__NLM_HAL_SYS_H__
=20
 /**
 * @file_name sys.h
@@ -121,5 +121,24 @@
 #define	nlm_get_sys_pcibase(node) nlm_pcicfg_base(XLP_IO_SYS_OFFSET(node))
 #define	nlm_get_sys_regbase(node) (nlm_get_sys_pcibase(node) + XLP_IO_PCI_=
HDRSZ)
=20
+enum {
+	/* Don't change order and it must start from zero */
+	DFS_DEVICE_NAE =3D 0,
+	DFS_DEVICE_SAE,
+	DFS_DEVICE_RSA,
+	DFS_DEVICE_DTRE,
+	DFS_DEVICE_CMP,
+	DFS_DEVICE_KBP,
+	DFS_DEVICE_DMC,
+	DFS_DEVICE_NAND,
+	DFS_DEVICE_MMC,
+	DFS_DEVICE_NOR,
+	DFS_DEVICE_CORE,
+	DFS_DEVICE_REGEX_SLOW,
+	DFS_DEVICE_REGEX_FAST,
+	DFS_DEVICE_SATA,
+	INVALID_DFS_DEVICE =3D 0xFF
+};
+
 #endif
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/intr_machdep.c
--- a/head/sys/mips/nlm/intr_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/intr_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * NETLOGIC_BSD */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/intr_machdep.c 225394 2011-09-05 10:=
45:29Z jchandra $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/intr_machdep.c 233563 2012-03-27 15:=
39:55Z jchandra $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -141,13 +141,13 @@
 		 * PIC based interrupts need ack in PIC, and some SoC
 		 * components need additional acks (e.g. PCI)
 		 */
-		if (xlp_irq_is_picintr(irq))
+		if (XLP_IRQ_IS_PICINTR(irq))
 			errcode =3D intr_event_create(&ie, src, 0, irq,
 			    xlp_pre_ithread, xlp_post_ithread, xlp_post_filter,
 			    NULL, "hard intr%d:", irq);
 		else {
 			if (filt =3D=3D NULL)
-				panic("Not supported - non filter percpu intr");
+				panic("Unsupported non filter percpu intr %d", irq);
 			errcode =3D intr_event_create(&ie, src, 0, irq,
 			    NULL, NULL, NULL, NULL, "hard intr%d:", irq);
 		}
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/mpreset.S
--- a/head/sys/mips/nlm/mpreset.S	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/mpreset.S	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/mpreset.S 227799 2011-11-21 16:43:24Z jchan=
dra $
+ * $FreeBSD: head/sys/mips/nlm/mpreset.S 233535 2012-03-27 07:51:42Z jchan=
dra $
  */
=20
 #include <machine/asm.h>
@@ -55,24 +55,24 @@
 	.set	noreorder
 	li	$8, LSU_DEBUG_DATA0 /* use register number to handle */
 	li	$9, LSU_DEBUG_ADDR  /* different ABIs */
-	li	t2, 0
-	li	t3, 0x200
+	li	t2, 0		/* index */
+	li	t3, 0x1000	/* loop count, 512 sets * 8 whatever? */
 1:
 	sll	v0, t2, 5
 	MTCR(0, 8)
-	ori	v1, v0, 0x3
+	ori	v1, v0, 0x3	/* way0 | write_enable | write_active */
 	MTCR(3, 9)
 2:
 	MFCR(3, 9)
-	andi	v1, 0x1
+	andi	v1, 0x1		/* wait for write_active =3D=3D 0 */
 	bnez	v1, 2b
 	nop
 	MTCR(0, 8)
-	ori	v1, v0, 0x7
+	ori	v1, v0, 0x7	/* way1 | write_enable | write_active */
 	MTCR(3, 9)
 3:
 	MFCR(3, 9)
-	andi	v1, 0x1
+	andi	v1, 0x1		/* wait for write_active =3D=3D 0 */
 	bnez	v1, 3b
 	nop
 	addi	t2, 1
@@ -195,7 +195,7 @@
 	mfc0	t1, MIPS_COP_0_STATUS
=20
 	move	sp, t0		/* Restore the real SP */
-	jr	ra
+	jr.hb	ra
 	nop
 END(xlp_enable_threads)
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/msgring.h
--- a/head/sys/mips/nlm/msgring.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/msgring.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,15 +26,27 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/msgring.h 227783 2011-11-21 08:12:36Z jchan=
dra $
+ * $FreeBSD: head/sys/mips/nlm/msgring.h 233545 2012-03-27 14:05:12Z jchan=
dra $
  */
=20
+#ifndef _NLM_MSGRING_H
+#define	_NLM_MSGRING_H
 #define	CMS_DEFAULT_CREDIT	50
+/*
+ * packets are sent to VC 0 of a thread
+ * freebacks are sent to VC 3 of a thread
+ */
+#define	XLPGE_RX_VC		0
+#define	XLPGE_FB_VC		3
=20
 extern uint32_t xlp_msg_thread_mask;
+
+struct nlm_fmn_msg;
 typedef void (*msgring_handler)(int, int, int, int, struct nlm_fmn_msg *, =
void *);
+
 int register_msgring_handler(int startb, int endb, msgring_handler action,
 		                    void *arg);
 int xlp_handle_msg_vc(u_int vcmask, int max_msgs);
 void xlp_msgring_cpu_init(int, int, int);
 void xlp_cms_enable_intr(int , int , int , int);
+#endif /* _NLM_MSGRING_H */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/uart_cpu_xlp.c
--- a/head/sys/mips/nlm/uart_cpu_xlp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/uart_cpu_xlp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -40,7 +40,7 @@
 #include "opt_uart.h"
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/uart_cpu_xlp.c 226501 2011-10-18 08:=
10:23Z jchandra $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/uart_cpu_xlp.c 233549 2012-03-27 14:=
48:40Z jchandra $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -58,15 +58,18 @@
=20
 #include <mips/nlm/hal/haldefs.h>
 #include <mips/nlm/hal/iomap.h>
+#include <mips/nlm/hal/mips-extns.h>
 #include <mips/nlm/hal/uart.h>
=20
+#include <mips/nlm/board.h>
+
 bus_space_tag_t uart_bus_space_io;
 bus_space_tag_t uart_bus_space_mem;
=20
 int
 uart_cpu_eqres(struct uart_bas *b1, struct uart_bas *b2)
 {
-	return ((b1->bsh =3D=3D b2->bsh && b1->bst =3D=3D b2->bst) ? 1 : 0);
+	return (b1->bsh =3D=3D b2->bsh && b1->bst =3D=3D b2->bst);
 }
=20
 int
@@ -75,12 +78,12 @@
 	di->ops =3D uart_getops(&uart_ns8250_class);
 	di->bas.chan =3D 0;
 	di->bas.bst =3D rmi_uart_bus_space;
-	di->bas.bsh =3D nlm_get_uart_regbase(0, 0);
+	di->bas.bsh =3D nlm_get_uart_regbase(0, BOARD_CONSOLE_UART);
 =09
 	di->bas.regshft =3D 2;
 	/* divisor =3D rclk / (baudrate * 16); */
-	di->bas.rclk =3D 133000000;
-	di->baudrate =3D 115200;
+	di->bas.rclk =3D XLP_IO_CLK;
+	di->baudrate =3D BOARD_CONSOLE_SPEED;
 	di->databits =3D 8;
 	di->stopbits =3D 1;
 	di->parity =3D UART_PARITY_NONE;
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/xlp.h
--- a/head/sys/mips/nlm/xlp.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/xlp.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/xlp.h 227783 2011-11-21 08:12:36Z jchandra $
+ * $FreeBSD: head/sys/mips/nlm/xlp.h 233563 2012-03-27 15:39:55Z jchandra $
  */
=20
 #ifndef __NLM_XLP_H__
@@ -34,21 +34,23 @@
 #include <mips/nlm/hal/mips-extns.h>
 #include <mips/nlm/hal/iomap.h>
=20
-#define PIC_UART_0_IRQ	9
-#define PIC_UART_1_IRQ	10
+#define	PIC_UART_0_IRQ	9
=20
-#define PIC_PCIE_0_IRQ	11
-#define PIC_PCIE_1_IRQ	12
-#define PIC_PCIE_2_IRQ	13
-#define PIC_PCIE_3_IRQ	14
+#define	PIC_PCIE_0_IRQ	11
+#define	PIC_PCIE_1_IRQ	12
+#define	PIC_PCIE_2_IRQ	13
+#define	PIC_PCIE_3_IRQ	14
=20
-#define PIC_EHCI_0_IRQ	39=20
-#define PIC_EHCI_1_IRQ	42=20
-#define PIC_MMC_IRQ	43
+#define	PIC_EHCI_0_IRQ	16=20
+#define	PIC_MMC_IRQ	21
+/* 41 used by IRQ_SMP */
+
=20
 /* XLP 8xx/4xx A0, A1, A2 CPU COP0 PRIDs */
 #define	CHIP_PROCESSOR_ID_XLP_8XX		0x10
 #define	CHIP_PROCESSOR_ID_XLP_3XX		0x11
+#define	CHIP_PROCESSOR_ID_XLP_416		0x94
+#define	CHIP_PROCESSOR_ID_XLP_432		0x14
=20
 /* Revision id's */
 #define	XLP_REVISION_A0				0x00
@@ -69,24 +71,49 @@
 #ifdef SMP
 extern void xlp_enable_threads(int code);
 #endif
-uint32_t xlp_get_cpu_frequency(int core);
-void nlm_pic_irt_init(void);
+uint32_t xlp_get_cpu_frequency(int node, int core);
+int nlm_set_device_frequency(int node, int devtype, int frequency);
 int xlp_irt_to_irq(int irt);
 int xlp_irq_to_irt(int irq);
-int xlp_irq_is_picintr(int irq);
+
+static __inline int nlm_processor_id(void)
+{
+	return ((mips_rd_prid() >> 8) & 0xff);
+}
=20
 static __inline int nlm_is_xlp3xx(void)
 {
-	int prid =3D (mips_rd_prid() >> 8) & 0xff;
=20
-	return (prid =3D=3D CHIP_PROCESSOR_ID_XLP_3XX);
+	return (nlm_processor_id() =3D=3D CHIP_PROCESSOR_ID_XLP_3XX);
+}
+
+static __inline int nlm_is_xlp4xx(void)
+{
+	int prid =3D nlm_processor_id();
+
+	return (prid =3D=3D CHIP_PROCESSOR_ID_XLP_432 ||
+	    prid =3D=3D CHIP_PROCESSOR_ID_XLP_416);
 }
=20
 static __inline int nlm_is_xlp8xx(void)
 {
-	int prid =3D (mips_rd_prid() >> 8) & 0xff;
+	int prid =3D nlm_processor_id();
=20
-	return (prid =3D=3D CHIP_PROCESSOR_ID_XLP_8XX);
+	return (prid =3D=3D CHIP_PROCESSOR_ID_XLP_8XX ||
+	    prid =3D=3D CHIP_PROCESSOR_ID_XLP_432 ||
+	    prid =3D=3D CHIP_PROCESSOR_ID_XLP_416);
+}
+
+static __inline int nlm_is_xlp8xx_ax(void)
+{
+	uint32_t procid =3D mips_rd_prid();
+	int prid =3D (procid >> 8) & 0xff;
+	int rev =3D procid & 0xff;
+
+	return ((prid =3D=3D CHIP_PROCESSOR_ID_XLP_8XX ||
+	    prid =3D=3D CHIP_PROCESSOR_ID_XLP_432 ||
+	    prid =3D=3D CHIP_PROCESSOR_ID_XLP_416) &&
+	    (rev < XLP_REVISION_B0));
 }
=20
 #endif /* LOCORE */
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/xlp_machdep.c
--- a/head/sys/mips/nlm/xlp_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/xlp_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * NETLOGIC_BSD */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/xlp_machdep.c 232853 2012-03-12 07:3=
4:15Z jmallett $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/xlp_machdep.c 233563 2012-03-27 15:3=
9:55Z jchandra $");
=20
 #include "opt_ddb.h"
 #include "opt_platform.h"
@@ -98,7 +98,7 @@
 char boot1_env[4096];
=20
 uint64_t xlp_cpu_frequency;
-uint64_t xlp_io_base =3D MIPS_PHYS_TO_KSEG1(XLP_DEFAULT_IO_BASE);
+uint64_t xlp_io_base =3D MIPS_PHYS_TO_DIRECT_UNCACHED(XLP_DEFAULT_IO_BASE);
=20
 int xlp_ncores;
 int xlp_threads_per_core;
@@ -196,9 +196,15 @@
 		goto unsupp;
 	}
=20
-	/* Take out cores which do not exist on chip */
+	/* Try to find the enabled cores from SYS block */
 	sysbase =3D nlm_get_sys_regbase(0);
 	cpu_rst_mask =3D nlm_read_sys_reg(sysbase, SYS_CPU_RESET) & 0xff;
+
+	/* XLP 416 does not report this correctly, fix */
+	if (nlm_processor_id() =3D=3D CHIP_PROCESSOR_ID_XLP_416)
+		cpu_rst_mask =3D 0xe;
+
+	/* Take out cores which do not exist on chip */
 	for (i =3D 1; i < XLP_MAX_CORES; i++) {
 		if ((cpu_rst_mask & (1 << i)) =3D=3D 0)
 			cpu_map &=3D ~(0xfu << (4 * i));
@@ -358,14 +364,14 @@
 	mips_cpu_init();
 	cpuinfo.cache_coherent_dma =3D TRUE;
 	pmap_bootstrap();
+	mips_proc0_init();
+	mutex_init();
 #ifdef DDB
 	kdb_init();
 	if (boothowto & RB_KDB) {
 		kdb_enter("Boot flags requested debugger", NULL);
 	}
 #endif
-	mips_proc0_init();
-	mutex_init();
 }
=20
 unsigned int
@@ -433,8 +439,12 @@
=20
 		/* first bar, start a bit after end */
 		if (base =3D=3D 0) {
-			base =3D (vm_paddr_t)MIPS_KSEG0_TO_PHYS(&_end) + 0x20000;
-			lim  =3D 0x0c000000;  /* TODO : hack to avoid uboot packet mem */
+			base =3D (vm_paddr_t)MIPS_KSEG0_TO_PHYS(&_end);
+			base =3D round_page(base) + 0x20000; /* round up */
+			/* TODO : hack to avoid uboot packet mem, network
+			 * interface will write here if not reset correctly
+			 * by u-boot */
+			lim  =3D 0x0c000000;
 		}
 		if (base >=3D XLP_MEM_LIM) {
 			printf("Mem [%d]: Ignore %#jx - %#jx\n", i,
@@ -456,7 +466,7 @@
 		 * Exclude reset entry memory range 0x1fc00000 - 0x20000000
 		 * from free memory
 		 */
-		if (base <=3D 0x1fc00000 && (base + lim) > 0x1fc00000) {
+		if (base < 0x20000000 && lim > 0x1fc00000) {
 			uint64_t base0, lim0, base1, lim1;
=20
 			base0 =3D base;
@@ -511,12 +521,11 @@
 	/* initialize console so that we have printf */
 	boothowto |=3D (RB_SERIAL | RB_MULTIPLE);	/* Use multiple consoles */
=20
-	nlm_pic_irt_init(); /* complete before interrupts or console init */
 	init_static_kenv(boot1_env, sizeof(boot1_env));
 	xlp_bootargs_init(a0);
=20
 	/* clockrate used by delay, so initialize it here */
-	xlp_cpu_frequency =3D xlp_get_cpu_frequency(0);
+	xlp_cpu_frequency =3D xlp_get_cpu_frequency(0, 0);
 	cpu_clock =3D xlp_cpu_frequency / 1000000;
 	mips_timer_early_init(xlp_cpu_frequency);
=20
@@ -542,6 +551,9 @@
 	/* setup for the startup core */
 	xlp_setup_mmu();
=20
+	/* Read/Guess/setup board information */
+	nlm_board_info_setup();
+
 	/* MIPS generic init */
 	mips_init();
=20
@@ -549,7 +561,6 @@
 	 * XLP specific post initialization
  	 * initialize other on chip stuff
 	 */
-	nlm_board_info_setup();
 	xlp_pic_init();
=20
 	mips_timer_init_params(xlp_cpu_frequency, 0);
diff -r 428842767fa6 -r f2935497fa04 head/sys/mips/nlm/xlp_pci.c
--- a/head/sys/mips/nlm/xlp_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/mips/nlm/xlp_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,34 +1,33 @@
 /*-
- * Copyright (c) 2003-2009 RMI Corporation
- * All rights reserved.
+ * Copyright (c) 2003-2012 Broadcom Corporation
+ * All Rights Reserved
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
+ *
  * 1. Redistributions of source code must retain the above copyright
  *    notice, this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of RMI Corporation, nor the names of its contributo=
rs,
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURP=
OSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENT=
IAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STR=
ICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY W=
AY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * NETLOGIC_BSD */
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *=20
+ * THIS SOFTWARE IS PROVIDED BY BROADCOM ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL BROADCOM OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+ * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/xlp_pci.c 227843 2011-11-22 21:28:20=
Z marius $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/xlp_pci.c 233570 2012-03-27 18:26:35=
Z jchandra $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -39,14 +38,16 @@
 #include <sys/bus.h>
 #include <sys/endian.h>
 #include <sys/rman.h>
+#include <sys/pciio.h>
=20
 #include <vm/vm.h>
 #include <vm/vm_param.h>
 #include <vm/pmap.h>
=20
-#include <sys/pciio.h>
 #include <dev/pci/pcivar.h>
 #include <dev/pci/pcireg.h>
+#include <dev/pci/pci_private.h>
+
 #include <dev/uart/uart.h>
 #include <dev/uart/uart_bus.h>
 #include <dev/uart/uart_cpu.h>
@@ -61,23 +62,285 @@
 #include <mips/nlm/hal/iomap.h>
 #include <mips/nlm/hal/mips-extns.h>
 #include <mips/nlm/hal/pic.h>
+#include <mips/nlm/hal/bridge.h>
+#include <mips/nlm/hal/gbu.h>
 #include <mips/nlm/hal/pcibus.h>
 #include <mips/nlm/hal/uart.h>
 #include <mips/nlm/xlp.h>
=20
 #include "pcib_if.h"
+#include "pci_if.h"
=20
-struct xlp_pcib_softc {
-	bus_dma_tag_t	sc_pci_dmat;	/* PCI DMA tag pointer */
+#define	EMUL_MEM_START	0x16000000UL
+#define	EMUL_MEM_END	0x18ffffffUL
+
+/* SoC device qurik handling */
+static int irt_irq_map[4 * 256];
+static int irq_irt_map[64];
+
+static void
+xlp_add_irq(int node, int irt, int irq)
+{
+	int nodeirt =3D node * 256 + irt;
+
+	irt_irq_map[nodeirt] =3D irq;
+	irq_irt_map[irq] =3D nodeirt;
+}
+
+int
+xlp_irq_to_irt(int irq)
+{
+	return irq_irt_map[irq];
+}
+
+int
+xlp_irt_to_irq(int nodeirt)
+{
+	return irt_irq_map[nodeirt];
+}
+
+/* Override PCI a bit for SoC devices */
+
+enum {
+	INTERNAL_DEV	=3D 0x1,	/* internal device, skip on enumeration */
+	MEM_RES_EMUL	=3D 0x2,	/* no MEM or IO bar, custom res alloc */
+	SHARED_IRQ	=3D 0x4,
+	DEV_MMIO32	=3D 0x8,	/* byte access not allowed to mmio */
 };
=20
+struct soc_dev_desc {
+	u_int	devid;		/* device ID */
+	int	irqbase;	/* start IRQ */
+	u_int	flags;		/* flags */
+	int	ndevs;		/* to keep track of number of devices */
+};
+
+struct soc_dev_desc xlp_dev_desc[] =3D {
+	{ PCI_DEVICE_ID_NLM_ICI,               0, INTERNAL_DEV },
+	{ PCI_DEVICE_ID_NLM_PIC,               0, INTERNAL_DEV },
+	{ PCI_DEVICE_ID_NLM_FMN,               0, INTERNAL_DEV },
+	{ PCI_DEVICE_ID_NLM_UART, PIC_UART_0_IRQ, MEM_RES_EMUL | DEV_MMIO32},
+	{ PCI_DEVICE_ID_NLM_I2C,               0, MEM_RES_EMUL | DEV_MMIO32 },
+	{ PCI_DEVICE_ID_NLM_NOR,               0, MEM_RES_EMUL },
+	{ PCI_DEVICE_ID_NLM_MMC,     PIC_MMC_IRQ, MEM_RES_EMUL },
+	{ PCI_DEVICE_ID_NLM_EHCI, PIC_EHCI_0_IRQ, 0 }
+};
+
+struct  xlp_devinfo {
+	struct pci_devinfo pcidev;
+	int	irq;
+	int	flags;
+	u_long	mem_res_start;
+};
+
+static __inline struct soc_dev_desc *
+xlp_find_soc_desc(int devid)
+{
+	struct soc_dev_desc *p;
+	int i, n;
+
+	n =3D sizeof(xlp_dev_desc) / sizeof(xlp_dev_desc[0]);
+	for (i =3D 0, p =3D xlp_dev_desc; i < n; i++, p++)
+		if (p->devid =3D=3D devid)
+			return (p);
+	return (NULL);
+}
+
+static struct resource *
+xlp_pci_alloc_resource(device_t bus, device_t child, int type, int *rid,
+    u_long start, u_long end, u_long count, u_int flags)
+{
+	struct resource *r;
+	struct xlp_devinfo *xlp_devinfo;
+	int busno;
+
+	/*
+	 * Do custom allocation for MEMORY resource for SoC device if=20
+	 * MEM_RES_EMUL flag is set
+	 */
+	busno =3D pci_get_bus(child);
+	if ((type =3D=3D SYS_RES_MEMORY || type =3D=3D SYS_RES_IOPORT) && busno =
=3D=3D 0) {
+		xlp_devinfo =3D (struct xlp_devinfo *)device_get_ivars(child);
+		if ((xlp_devinfo->flags & MEM_RES_EMUL) !=3D 0) {
+			/* no emulation for IO ports */
+			if (type =3D=3D SYS_RES_IOPORT)
+				return (NULL);
+
+			start =3D xlp_devinfo->mem_res_start;
+			count =3D XLP_PCIE_CFG_SIZE - XLP_IO_PCI_HDRSZ;
+
+			/* MMC needs to 2 slots with rids 16 and 20 and a
+			 * fixup for size */
+			if (pci_get_device(child) =3D=3D PCI_DEVICE_ID_NLM_MMC) {
+				count =3D 0x100;
+				if (*rid =3D=3D 16)
+					; /* first slot already setup */
+				else if (*rid =3D=3D 20)
+					start +=3D 0x100; /* second slot */
+				else
+					return (NULL);
+			}
+
+			end =3D start + count - 1;
+			r =3D BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
+			    type, rid, start, end, count, flags);
+			if (r =3D=3D NULL)
+				return (NULL);
+			if ((xlp_devinfo->flags & DEV_MMIO32) !=3D 0)
+				rman_set_bustag(r, rmi_uart_bus_space);
+			return (r);
+		}
+	}
+
+	/* Not custom alloc, use PCI code */
+	return (pci_alloc_resource(bus, child, type, rid, start, end, count,
+	    flags));
+}
+
+static int
+xlp_pci_release_resource(device_t bus, device_t child, int type, int rid,
+    struct resource *r)
+{
+	u_long start;
+
+	/* If custom alloc, handle that */
+	start =3D rman_get_start(r);
+	if (type =3D=3D SYS_RES_MEMORY && pci_get_bus(child) =3D=3D 0 &&
+	    start >=3D EMUL_MEM_START && start <=3D EMUL_MEM_END)
+		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
+		    type, rid, r));
+
+	/* use default PCI function */
+	return (bus_generic_rl_release_resource(bus, child, type, rid, r));
+}
+
+static void
+xlp_add_soc_child(device_t pcib, device_t dev, int b, int s, int f)
+{
+	struct pci_devinfo *dinfo;
+	struct xlp_devinfo *xlp_dinfo;
+	struct soc_dev_desc *si;
+	uint64_t pcibase;
+	int domain, node, irt, irq, flags, devoffset, num;
+	uint16_t devid;
+
+	domain =3D pcib_get_domain(dev);
+	node =3D s / 8;
+	devoffset =3D XLP_HDR_OFFSET(node, 0, s % 8, f);
+	if (!nlm_dev_exists(devoffset))
+		return;
+
+	/* Find if there is a desc for the SoC device */
+	devid =3D PCIB_READ_CONFIG(pcib, b, s, f, PCIR_DEVICE, 2);
+	si =3D xlp_find_soc_desc(devid);
+
+	/* update flags and irq from desc if available */
+	irq =3D 0;
+	flags =3D 0;
+	if (si !=3D NULL) {
+		if (si->irqbase !=3D 0)
+			irq =3D si->irqbase + si->ndevs;
+		flags =3D si->flags;
+		si->ndevs++;
+	}
+
+	/* skip internal devices */
+	if ((flags & INTERNAL_DEV) !=3D 0)
+		return;
+
+	/* PCIe interfaces are special, bug in Ax */
+	if (devid =3D=3D PCI_DEVICE_ID_NLM_PCIE) {
+		xlp_add_irq(node, xlp_pcie_link_irt(f), PIC_PCIE_0_IRQ + f);
+	} else {
+		/* Stash intline and pin in shadow reg for devices */
+		pcibase =3D nlm_pcicfg_base(devoffset);
+		irt =3D nlm_irtstart(pcibase);
+		num =3D nlm_irtnum(pcibase);
+		if (irq !=3D 0 && num > 0) {
+			xlp_add_irq(node, irt, irq);
+			nlm_write_reg(pcibase, XLP_PCI_DEVSCRATCH_REG0,
+			    (1 << 8) | irq);
+		}
+	}
+	dinfo =3D pci_read_device(pcib, domain, b, s, f, sizeof(*xlp_dinfo));
+	if (dinfo =3D=3D NULL)
+		return;
+	xlp_dinfo =3D (struct xlp_devinfo *)dinfo;
+	xlp_dinfo->irq =3D irq;
+	xlp_dinfo->flags =3D flags;
+
+	/* memory resource from ecfg space, if MEM_RES_EMUL is set */
+	if ((flags & MEM_RES_EMUL) !=3D 0)
+		xlp_dinfo->mem_res_start =3D XLP_DEFAULT_IO_BASE + devoffset +
+		    XLP_IO_PCI_HDRSZ;
+	pci_add_child(dev, dinfo);
+}
+
+static int
+xlp_pci_attach(device_t dev)
+{
+	device_t pcib =3D device_get_parent(dev);
+	int maxslots, s, f, pcifunchigh;
+	int busno;
+	uint8_t hdrtype;
+
+	/*
+	 * The on-chip devices are on a bus that is almost, but not
+	 * quite, completely like PCI. Add those things by hand.
+	 */
+	busno =3D pcib_get_bus(dev);
+	maxslots =3D PCIB_MAXSLOTS(pcib);
+	for (s =3D 0; s <=3D maxslots; s++) {
+		pcifunchigh =3D 0;
+		f =3D 0;
+		hdrtype =3D PCIB_READ_CONFIG(pcib, busno, s, f, PCIR_HDRTYPE, 1);
+		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
+			continue;
+		if (hdrtype & PCIM_MFDEV)
+			pcifunchigh =3D PCI_FUNCMAX;
+		for (f =3D 0; f <=3D pcifunchigh; f++)
+			xlp_add_soc_child(pcib, dev, busno, s, f);
+	}
+	return (bus_generic_attach(dev));
+}
+
+static int
+xlp_pci_probe(device_t dev)
+{
+	device_t pcib;
+
+	pcib =3D device_get_parent(dev);
+	/*
+	 * Only the top level bus has SoC devices, leave the rest to
+	 * Generic PCI code
+	 */
+	if (strcmp(device_get_nameunit(pcib), "pcib0") !=3D 0)
+		return (ENXIO);
+	device_set_desc(dev, "XLP SoCbus");
+	return (BUS_PROBE_DEFAULT);
+}
+
+static devclass_t pci_devclass;
+static device_method_t xlp_pci_methods[] =3D {
+	/* Device interface */
+	DEVMETHOD(device_probe,		xlp_pci_probe),
+	DEVMETHOD(device_attach,	xlp_pci_attach),
+	DEVMETHOD(bus_alloc_resource,	xlp_pci_alloc_resource),
+	DEVMETHOD(bus_release_resource, xlp_pci_release_resource),
+
+	DEVMETHOD_END
+};
+
+DEFINE_CLASS_1(pci, xlp_pci_driver, xlp_pci_methods, sizeof(struct pci_sof=
tc),
+    pci_driver);
+DRIVER_MODULE(xlp_pci, pcib, xlp_pci_driver, pci_devclass, 0, 0);
+
 static devclass_t pcib_devclass;
 static struct rman irq_rman, port_rman, mem_rman, emul_rman;
=20
 static void
-xlp_pci_init_resources(void)
+xlp_pcib_init_resources(void)
 {
-
 	irq_rman.rm_start =3D 0;
 	irq_rman.rm_end =3D 255;
 	irq_rman.rm_type =3D RMAN_ARRAY;
@@ -91,7 +354,7 @@
 	port_rman.rm_type =3D RMAN_ARRAY;
 	port_rman.rm_descr =3D "I/O ports";
 	if (rman_init(&port_rman)
-	    || rman_manage_region(&port_rman, 0x14000000UL, 0x15ffffffUL))
+	    || rman_manage_region(&port_rman, PCIE_IO_BASE, PCIE_IO_LIMIT))
 		panic("pci_init_resources port_rman");
=20
 	mem_rman.rm_start =3D 0;
@@ -99,15 +362,19 @@
 	mem_rman.rm_type =3D RMAN_ARRAY;
 	mem_rman.rm_descr =3D "I/O memory";
 	if (rman_init(&mem_rman)
-	    || rman_manage_region(&mem_rman, 0xd0000000ULL, 0xdfffffffULL))
+	    || rman_manage_region(&mem_rman, PCIE_MEM_BASE, PCIE_MEM_LIMIT))
 		panic("pci_init_resources mem_rman");
=20
+	/*
+	 * This includes the GBU (nor flash) memory range and the PCIe
+	 * memory area.=20
+	 */
 	emul_rman.rm_start =3D 0;
 	emul_rman.rm_end =3D ~0ul;
 	emul_rman.rm_type =3D RMAN_ARRAY;
 	emul_rman.rm_descr =3D "Emulated MEMIO";
 	if (rman_init(&emul_rman)
-	    || rman_manage_region(&emul_rman, 0x18000000ULL, 0x18ffffffULL))
+	    || rman_manage_region(&emul_rman, EMUL_MEM_START, EMUL_MEM_END))
 		panic("pci_init_resources emul_rman");
 }
=20
@@ -116,7 +383,7 @@
 {
=20
 	device_set_desc(dev, "XLP PCI bus");
-	xlp_pci_init_resources();
+	xlp_pcib_init_resources();
 	return (0);
 }
=20
@@ -168,20 +435,15 @@
 	else if ((width =3D=3D 4) && (reg & 3))
 		return 0xFFFFFFFF;
=20
+	/*=20
+	 * The intline and int pin of SoC devices are DOA, except
+	 * for bridges (slot %8 =3D=3D 1).
+	 * use the values we stashed in a writable PCI scratch reg.
+	 */
+	if (b =3D=3D 0 && regindex =3D=3D 0xf && s % 8 > 1)
+		regindex =3D XLP_PCI_DEVSCRATCH_REG0;
+
 	data =3D nlm_read_pci_reg(cfgaddr, regindex);
-
-	/*=20
-	 * Fix up read data in some SoC devices=20
-	 * to emulate complete PCIe header
-	 */
-	if (b =3D=3D 0) {
-		int dev =3D s % 8;
-
-		/* Fake intpin on config read for UART/I2C, USB, SD/Flash */
-		if (regindex =3D=3D 0xf &&=20
-		    (dev =3D=3D 6 || dev =3D=3D 2 || dev =3D=3D 7))
-			data |=3D 0x1 << 8;	/* Fake int pin */
-	}
 	if (width =3D=3D 1)
 		return ((data >> ((reg & 3) << 3)) & 0xff);
 	else if (width =3D=3D 2)
@@ -216,19 +478,56 @@
 		data =3D val;
 	}
=20
+	/*
+	 * use shadow reg for intpin/intline which are dead
+	 */
+	if (b =3D=3D 0 && regindex =3D=3D 0xf && s % 8 > 1)
+		regindex =3D XLP_PCI_DEVSCRATCH_REG0;
 	nlm_write_pci_reg(cfgaddr, regindex, data);
-	return;
+}
+
+/*
+ * Enable byte swap in hardware. Program a link's PCIe SWAP regions
+ * from the link's IO and MEM address ranges.
+ */
+static void
+xlp_pcib_hardware_swap_enable(int node, int link)
+{
+	uint64_t bbase, linkpcibase;
+	uint32_t bar;
+	int pcieoffset;
+
+	pcieoffset =3D XLP_IO_PCIE_OFFSET(node, link);
+	if (!nlm_dev_exists(pcieoffset))
+		return;
+
+	bbase =3D nlm_get_bridge_regbase(node);
+	linkpcibase =3D nlm_pcicfg_base(pcieoffset);
+	bar =3D nlm_read_bridge_reg(bbase, BRIDGE_PCIEMEM_BASE0 + link);
+	nlm_write_pci_reg(linkpcibase, PCIE_BYTE_SWAP_MEM_BASE, bar);
+
+	bar =3D nlm_read_bridge_reg(bbase, BRIDGE_PCIEMEM_LIMIT0 + link);
+	nlm_write_pci_reg(linkpcibase, PCIE_BYTE_SWAP_MEM_LIM, bar);
+
+	bar =3D nlm_read_bridge_reg(bbase, BRIDGE_PCIEIO_BASE0 + link);
+	nlm_write_pci_reg(linkpcibase, PCIE_BYTE_SWAP_IO_BASE, bar);
+
+	bar =3D nlm_read_bridge_reg(bbase, BRIDGE_PCIEIO_LIMIT0 + link);
+	nlm_write_pci_reg(linkpcibase, PCIE_BYTE_SWAP_IO_LIM, bar);
 }
=20
 static int=20
 xlp_pcib_attach(device_t dev)
 {
-	struct xlp_pcib_softc *sc;
-	sc =3D device_get_softc(dev);
+	int node, link;
+
+	/* enable hardware swap on all nodes/links */
+	for (node =3D 0; node < XLP_MAX_NODES; node++)
+		for (link =3D 0; link < 4; link++)
+			xlp_pcib_hardware_swap_enable(node, link);
=20
 	device_add_child(dev, "pci", 0);
 	bus_generic_attach(dev);
-
 	return (0);
 }
=20
@@ -249,10 +548,6 @@
 	device_t parent, tmp;
=20
 	/* find the lane on which the slot is connected to */
-#if 0 /* Debug */
-	printf("xlp_pcie_link : bus %s dev %s\n", device_get_nameunit(pcib),
-		device_get_nameunit(dev));
-#endif
 	tmp =3D dev;
 	while (1) {
 		parent =3D device_get_parent(tmp);
@@ -295,8 +590,6 @@
 static int
 xlp_release_msi(device_t pcib, device_t dev, int count, int *irqs)
 {
-	device_printf(dev, "%s: msi release %d\n", device_get_nameunit(pcib),
-	    count);
 	return (0);
 }
=20
@@ -352,7 +645,7 @@
 }
=20
 static int
-mips_platform_pci_setup_intr(device_t dev, device_t child,
+mips_platform_pcib_setup_intr(device_t dev, device_t child,
     struct resource *irq, int flags, driver_filter_t *filt,
     driver_intr_t *intr, void *arg, void **cookiep)
 {
@@ -369,12 +662,11 @@
 		return (EINVAL);
 	}
 	xlpirq =3D rman_get_start(irq);
-	device_printf(dev, "setup intr %d\n", xlpirq);
+	if (xlpirq =3D=3D 0)
+		return (0);
=20
-	if (strcmp(device_get_name(dev), "pcib") !=3D 0) {
-		device_printf(dev, "ret 0 on dev\n");
+	if (strcmp(device_get_name(dev), "pcib") !=3D 0)
 		return (0);
-	}
=20
 	/*=20
 	 * temporary hack for MSI, we support just one device per
@@ -389,7 +681,7 @@
 			return (0);
=20
 		node =3D nlm_nodeid();
-		link =3D (xlpirq / 32);
+		link =3D xlpirq / 32;
 		base =3D nlm_pcicfg_base(XLP_IO_PCIE_OFFSET(node,link));
=20
 		/* MSI Interrupt Vector enable at bridge's configuration */
@@ -398,24 +690,23 @@
 		val =3D nlm_read_pci_reg(base, PCIE_INT_EN0);
 		/* MSI Interrupt enable at bridge's configuration */
 		nlm_write_pci_reg(base, PCIE_INT_EN0,
-				(val | PCIE_MSI_INT_EN));
+		    (val | PCIE_MSI_INT_EN));
=20
 		/* legacy interrupt disable at bridge */
 		val =3D nlm_read_pci_reg(base, PCIE_BRIDGE_CMD);
 		nlm_write_pci_reg(base, PCIE_BRIDGE_CMD,
-				(val | PCIM_CMD_INTxDIS));
+		    (val | PCIM_CMD_INTxDIS));
=20
 		/* MSI address update at bridge */
-		val =3D nlm_read_pci_reg(base, PCIE_BRIDGE_MSI_ADDRL);
 		nlm_write_pci_reg(base, PCIE_BRIDGE_MSI_ADDRL,
-				(val | MSI_MIPS_ADDR_BASE));
+		    MSI_MIPS_ADDR_BASE);
+		nlm_write_pci_reg(base, PCIE_BRIDGE_MSI_ADDRH, 0);
=20
 		val =3D nlm_read_pci_reg(base, PCIE_BRIDGE_MSI_CAP);
 		/* MSI capability enable at bridge */
 		nlm_write_pci_reg(base, PCIE_BRIDGE_MSI_CAP,=20
-				(val |
-				(PCIM_MSICTRL_MSI_ENABLE << 16) |
-				(PCIM_MSICTRL_MMC_32 << 16)));
+		    (val | (PCIM_MSICTRL_MSI_ENABLE << 16) |
+		        (PCIM_MSICTRL_MMC_32 << 16)));
=20
 		xlpirq =3D xlp_pcie_link_irt(xlpirq / 32);
 		if (xlpirq =3D=3D -1)
@@ -423,12 +714,10 @@
 		xlpirq =3D xlp_irt_to_irq(xlpirq);
 	}
 	/* Set all irqs to CPU 0 for now */
-	printf("set up intr %d->%d(%d)\n", xlp_irq_to_irt(xlpirq), xlpirq, (int)r=
man_get_start(irq));
 	nlm_pic_write_irt_direct(xlp_pic_base, xlp_irq_to_irt(xlpirq), 1, 0,
-				 PIC_LOCAL_SCHEDULING, xlpirq, 0);
+	    PIC_LOCAL_SCHEDULING, xlpirq, 0);
 	extra_ack =3D NULL;
-	if (xlpirq >=3D PIC_PCIE_0_IRQ &&
-	    xlpirq <=3D PIC_PCIE_3_IRQ)
+	if (xlpirq >=3D PIC_PCIE_0_IRQ && xlpirq <=3D PIC_PCIE_3_IRQ)
 		extra_ack =3D bridge_pcie_ack;
 	xlp_establish_intr(device_get_name(child), filt,
 	    intr, arg, xlpirq, flags, cookiep, extra_ack);
@@ -437,7 +726,7 @@
 }
=20
 static int
-mips_platform_pci_teardown_intr(device_t dev, device_t child,
+mips_platform_pcib_teardown_intr(device_t dev, device_t child,
     struct resource *irq, void *cookie)
 {
 	if (strcmp(device_get_name(child), "pci") =3D=3D 0) {
@@ -447,124 +736,65 @@
 	return (bus_generic_teardown_intr(dev, child, irq, cookie));
 }
=20
-static void
-assign_soc_resource(device_t child, int type, u_long *startp, u_long *endp,
-    u_long *countp, struct rman **rm, bus_space_tag_t *bst, vm_offset_t *v=
a)
-{
-	int devid =3D pci_get_device(child);
-	int inst =3D pci_get_function(child);
-	int node =3D pci_get_slot(child) / 8;
-	int dev =3D pci_get_slot(child) % 8;
-
-	*rm =3D NULL;
-	*va =3D 0;
-	*bst =3D 0;
-	if (type =3D=3D SYS_RES_IRQ) {
-		printf("%s: %d %d %d : start %d, end %d\n", __func__,
-				node, dev, inst, (int)*startp, (int)*endp);
-	} else if (type =3D=3D SYS_RES_MEMORY) {
-		switch (devid) {
-		case PCI_DEVICE_ID_NLM_UART:
-			*va =3D nlm_get_uart_regbase(node, inst);
-			*startp =3D MIPS_KSEG1_TO_PHYS(va);
-			*countp =3D 0x100;
-			*rm =3D &emul_rman;
-			*bst =3D uart_bus_space_mem;
-			break;
-		}
-
-	} else
-		printf("Unknown type %d in req for [%x%x]\n",
-			type, devid, inst);
-	/* default to rmi_bus_space for SoC resources */
-	if (type =3D=3D SYS_RES_MEMORY && *bst =3D=3D 0)
-		*bst =3D rmi_bus_space;
-}
-
 static struct resource *
-xlp_pci_alloc_resource(device_t bus, device_t child, int type, int *rid,
+xlp_pcib_alloc_resource(device_t bus, device_t child, int type, int *rid,
     u_long start, u_long end, u_long count, u_int flags)
 {
 	struct rman *rm =3D NULL;
 	struct resource *rv;
-	vm_offset_t va =3D 0;
+	void *va;
 	int needactivate =3D flags & RF_ACTIVE;
-	bus_space_tag_t bst =3D 0;
=20
-	/*
-	 * For SoC PCI devices, we have to assign resources correctly
-	 * since the IRQ and MEM resources depend on the block.
-	 * If the address is not from BAR0, then we use emul_rman
-	 */
-	if (pci_get_bus(child) =3D=3D 0 &&
-	    pci_get_vendor(child) =3D=3D PCI_VENDOR_NETLOGIC)
-      		assign_soc_resource(child, type, &start, &end,
-		    &count, &rm, &bst, &va);
-	if (rm =3D=3D NULL) {
-		switch (type) {
-		case SYS_RES_IRQ:
-			rm =3D &irq_rman;
-			break;
+	switch (type) {
+	case SYS_RES_IRQ:
+		rm =3D &irq_rman;
+		break;
 =09
-		case SYS_RES_IOPORT:
-			rm =3D &port_rman;
-			break;
+	case SYS_RES_IOPORT:
+		rm =3D &port_rman;
+		break;
=20
-		case SYS_RES_MEMORY:
+	case SYS_RES_MEMORY:
+		if (start >=3D EMUL_MEM_START && start <=3D EMUL_MEM_END)
+			rm =3D &emul_rman;
+		else
 			rm =3D &mem_rman;
 			break;
=20
-		default:
-			return (0);
-		}
+	default:
+		return (0);
 	}
=20
 	rv =3D rman_reserve_resource(rm, start, end, count, flags, child);
-	if (rv =3D=3D 0)
-		return (0);
+	if (rv =3D=3D NULL)
+		return (NULL);
=20
 	rman_set_rid(rv, *rid);
=20
 	if (type =3D=3D SYS_RES_MEMORY || type =3D=3D SYS_RES_IOPORT) {
-		if (va =3D=3D 0)
-			va =3D (vm_offset_t)pmap_mapdev(start, count);
-		if (bst =3D=3D 0)
-			bst =3D rmi_pci_bus_space;
-
-		rman_set_bushandle(rv, va);
-		rman_set_virtual(rv, (void *)va);
-		rman_set_bustag(rv, bst);
+		va =3D pmap_mapdev(start, count);
+		rman_set_bushandle(rv, (bus_space_handle_t)va);
+		rman_set_bustag(rv, rmi_bus_space);
 	}
-
 	if (needactivate) {
 		if (bus_activate_resource(child, type, *rid, rv)) {
 			rman_release_resource(rv);
 			return (NULL);
 		}
 	}
-
 	return (rv);
 }
=20
 static int
-xlp_pci_release_resource(device_t bus, device_t child, int type, int rid,
+xlp_pcib_release_resource(device_t bus, device_t child, int type, int rid,
     struct resource *r)
 {
=20
 	return (rman_release_resource(r));
 }
=20
-static bus_dma_tag_t
-xlp_pci_get_dma_tag(device_t bus, device_t child)
-{
-	struct xlp_pcib_softc *sc;
-
-	sc =3D device_get_softc(bus);
-	return (sc->sc_pci_dmat);
-}
-
 static int
-xlp_pci_activate_resource(device_t bus, device_t child, int type, int rid,
+xlp_pcib_activate_resource(device_t bus, device_t child, int type, int rid,
     struct resource *r)
 {
=20
@@ -572,7 +802,7 @@
 }
=20
 static int
-xlp_pci_deactivate_resource(device_t bus, device_t child, int type, int ri=
d,
+xlp_pcib_deactivate_resource(device_t bus, device_t child, int type, int r=
id,
     struct resource *r)
 {
=20
@@ -580,7 +810,7 @@
 }
=20
 static int
-mips_pci_route_interrupt(device_t bus, device_t dev, int pin)
+mips_pcib_route_interrupt(device_t bus, device_t dev, int pin)
 {
 	int irt, link;
=20
@@ -590,7 +820,6 @@
 	if ((pin < 1) || (pin > 4))
 		return (255);
=20
-	device_printf(bus, "route  %s %d", device_get_nameunit(dev), pin);
 	if (pci_get_bus(dev) =3D=3D 0 &&
 	    pci_get_vendor(dev) =3D=3D PCI_VENDOR_NETLOGIC) {
 		/* SoC devices */
@@ -636,19 +865,18 @@
 	/* Bus interface */
 	DEVMETHOD(bus_read_ivar, xlp_pcib_read_ivar),
 	DEVMETHOD(bus_write_ivar, xlp_pcib_write_ivar),
-	DEVMETHOD(bus_alloc_resource, xlp_pci_alloc_resource),
-	DEVMETHOD(bus_release_resource, xlp_pci_release_resource),
-	DEVMETHOD(bus_get_dma_tag, xlp_pci_get_dma_tag),
-	DEVMETHOD(bus_activate_resource, xlp_pci_activate_resource),
-	DEVMETHOD(bus_deactivate_resource, xlp_pci_deactivate_resource),
-	DEVMETHOD(bus_setup_intr, mips_platform_pci_setup_intr),
-	DEVMETHOD(bus_teardown_intr, mips_platform_pci_teardown_intr),
+	DEVMETHOD(bus_alloc_resource, xlp_pcib_alloc_resource),
+	DEVMETHOD(bus_release_resource, xlp_pcib_release_resource),
+	DEVMETHOD(bus_activate_resource, xlp_pcib_activate_resource),
+	DEVMETHOD(bus_deactivate_resource, xlp_pcib_deactivate_resource),
+	DEVMETHOD(bus_setup_intr, mips_platform_pcib_setup_intr),
+	DEVMETHOD(bus_teardown_intr, mips_platform_pcib_teardown_intr),
=20
 	/* pcib interface */
 	DEVMETHOD(pcib_maxslots, xlp_pcib_maxslots),
 	DEVMETHOD(pcib_read_config, xlp_pcib_read_config),
 	DEVMETHOD(pcib_write_config, xlp_pcib_write_config),
-	DEVMETHOD(pcib_route_interrupt, mips_pci_route_interrupt),
+	DEVMETHOD(pcib_route_interrupt, mips_pcib_route_interrupt),
=20
 	DEVMETHOD(pcib_alloc_msi, xlp_alloc_msi),
 	DEVMETHOD(pcib_release_msi, xlp_release_msi),
@@ -660,7 +888,7 @@
 static driver_t xlp_pcib_driver =3D {
 	"pcib",
 	xlp_pcib_methods,
-	sizeof(struct xlp_pcib_softc),
+	1, /* no softc */
 };
=20
 DRIVER_MODULE(pcib, nexus, xlp_pcib_driver, pcib_devclass, 0, 0);
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/cyclic/Makefile
--- a/head/sys/modules/cyclic/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/cyclic/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/cyclic/Makefile 233411 2012-03-24 05:16:26Z g=
onzo $
=20
 .PATH: ${.CURDIR}/../../cddl/dev/cyclic
=20
@@ -10,7 +10,7 @@
 CFLAGS+=3D	-I${.CURDIR}/../../cddl/compat/opensolaris		\
 		-I${.CURDIR}/../../cddl/contrib/opensolaris/uts/common	\
 		-I${.CURDIR}/../..					\
-		-I${.CURDIR}/../../cddl/dev/cyclic/${MACHINE_CPUARCH:S/amd64/i386/}
+		-I${.CURDIR}/../../cddl/dev/cyclic/i386
=20
 CFLAGS+=3D	-DDEBUG=3D1
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/dtrace/Makefile
--- a/head/sys/modules/dtrace/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/dtrace/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/modules/dtrace/Makefile 223280 2011-06-18 23:02:53Z r=
macklem $
+# $FreeBSD: head/sys/modules/dtrace/Makefile 233410 2012-03-24 05:15:14Z g=
onzo $
=20
 .include <bsd.own.mk>
 .include "Makefile.inc"
@@ -9,14 +9,12 @@
 		dtrace		\
 		dtraceall	\
 		dtrace_test	\
-		lockstat	\
-		profile		\
 		prototype	\
 		sdt		\
 		systrace
=20
 .if ${MACHINE_CPUARCH} =3D=3D "amd64" || ${MACHINE_CPUARCH} =3D=3D "i386"
-SUBDIR+=3D	fasttrap fbt systrace_linux32
+SUBDIR+=3D	fasttrap fbt lockstat profile systrace_linux32
 .endif
 .if ${MACHINE_CPUARCH} =3D=3D "amd64"
 SUBDIR+=3D	systrace_freebsd32
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/hwpmc/Makefile
--- a/head/sys/modules/hwpmc/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/hwpmc/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,12 @@
 #
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/hwpmc/Makefile 233628 2012-03-28 20:58:30Z fa=
bient $
 #
=20
 .PATH: ${.CURDIR}/../../dev/hwpmc
=20
 KMOD=3D	hwpmc
=20
-SRCS=3D	hwpmc_mod.c hwpmc_logging.c vnode_if.h
+SRCS=3D	hwpmc_mod.c hwpmc_logging.c hwpmc_soft.c vnode_if.h
=20
 .if ${MACHINE_CPUARCH} =3D=3D "amd64"
 SRCS+=3D	hwpmc_amd.c hwpmc_core.c hwpmc_intel.c hwpmc_piv.c hwpmc_tsc.c
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/iscsi/initiator/Makef=
ile
--- a/head/sys/modules/iscsi/initiator/Makefile	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/sys/modules/iscsi/initiator/Makefile	Tue Apr 17 11:51:51 2012 +0=
300
@@ -1,14 +1,16 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/iscsi/initiator/Makefile 234284 2012-04-14 13=
:40:39Z bz $
=20
-.PATH: ${.CURDIR}/../../../dev/iscsi/initiator
+S=3D      ${.CURDIR}/../../..
+.PATH: $S/dev/iscsi/initiator
+
 KMOD=3Discsi_initiator
=20
 SRCS=3D  iscsi.h iscsivar.h
 SRCS+=3D iscsi.c isc_cam.c isc_soc.c isc_sm.c isc_subr.c iscsi_subr.c
 SRCS+=3D opt_cam.h opt_iscsi_initiator.h
 SRCS+=3D bus_if.h device_if.h
-
-# Debugging
-# CFLAGS+=3D -DISCSI_INITIATOR_DEBUG=3D9
-
+#CFLAGS+=3D -DNO_USE_MBUF
+#CFLAGS+=3D -DISCSI_INITIATOR_DEBUG=3D2
+CFLAGS+=3D -I$S
+CFLAGS+=3D -DINVARIANTS
 .include <bsd.kmod.mk>
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/mfi/Makefile
--- a/head/sys/modules/mfi/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/mfi/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/mfi/Makefile 233711 2012-03-30 23:05:48Z ambr=
isko $
=20
 .PATH: ${.CURDIR}/../../dev/mfi
=20
@@ -9,8 +9,8 @@
 .endif
=20
 KMOD=3D	mfi
-SRCS=3D	mfi.c mfi_pci.c mfi_disk.c mfi_debug.c
-SRCS+=3D	opt_mfi.h opt_cam.h
+SRCS=3D	mfi.c mfi_pci.c mfi_disk.c mfi_debug.c mfi_syspd.c mfi_tbolt.c
+SRCS+=3D	opt_mfi.h opt_cam.h opt_compat.h
 SRCS+=3D	device_if.h bus_if.h pci_if.h
=20
 #CFLAGS +=3D -DMFI_DEBUG
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/mlx4/Makefile
--- a/head/sys/modules/mlx4/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/mlx4/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,13 +1,28 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/mlx4/Makefile 234183 2012-04-12 14:01:06Z jhb=
 $
 .PATH:  ${.CURDIR}/../../ofed/drivers/net/mlx4
+
+.include <bsd.own.mk>
+
 KMOD    =3D mlx4
 SRCS    =3D device_if.h bus_if.h pci_if.h vnode_if.h
 SRCS+=3D	alloc.c catas.c cmd.c cq.c eq.c fw.c icm.c intf.c main.c mcg.c mr=
.c
 SRCS+=3D	pd.c port.c profile.c qp.c reset.c sense.c srq.c xrcd.c
+SRCS+=3D	opt_inet.h opt_inet6.h
=20
 CFLAGS+=3D -I${.CURDIR}/../../ofed/drivers/net/mlx4
 CFLAGS+=3D -I${.CURDIR}/../../ofed/include/
-CFLAGS+=3D -DINET6
+
+.if !defined(KERNBUILDDIR)
+.if ${MK_INET_SUPPORT} !=3D "no"
+opt_inet.h:
+	@echo "#define INET 1" > ${.TARGET}
+.endif
+
+.if ${MK_INET6_SUPPORT} !=3D "no"
+opt_inet6.h:
+	@echo "#define INET6 1" > ${.TARGET}
+.endif
+.endif
=20
 .include <bsd.kmod.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/mlx4ib/Makefile
--- a/head/sys/modules/mlx4ib/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/mlx4ib/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,26 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/mlx4ib/Makefile 234183 2012-04-12 14:01:06Z j=
hb $
 .PATH:  ${.CURDIR}/../../ofed/drivers/infiniband/hw/mlx4
+
+.include <bsd.own.mk>
+
 KMOD    =3D mlx4ib
 SRCS    =3D device_if.h bus_if.h pci_if.h vnode_if.h
 SRCS+=3D	ah.c cq.c doorbell.c mad.c main.c mr.c qp.c srq.c wc.c
+SRCS+=3D	opt_inet.h opt_inet6.h
=20
-CFLAGS+=3D -I${.CURDIR}/../../ofed/include/ -DINET6
+CFLAGS+=3D -I${.CURDIR}/../../ofed/include/
+
+.if !defined(KERNBUILDDIR)
+.if ${MK_INET_SUPPORT} !=3D "no"
+opt_inet.h:
+	@echo "#define INET 1" > ${.TARGET}
+.endif
+
+.if ${MK_INET6_SUPPORT} !=3D "no"
+opt_inet6.h:
+	@echo "#define INET6 1" > ${.TARGET}
+.endif
+.endif
=20
 .include <bsd.kmod.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/mlxen/Makefile
--- a/head/sys/modules/mlxen/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/mlxen/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,12 +1,27 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/mlxen/Makefile 234183 2012-04-12 14:01:06Z jh=
b $
 .PATH:  ${.CURDIR}/../../ofed/drivers/net/mlx4
+
+.include <bsd.own.mk>
+
 KMOD    =3D mlxen
 SRCS    =3D device_if.h bus_if.h pci_if.h vnode_if.h
 SRCS	+=3D en_cq.c en_frag.c en_main.c en_netdev.c en_port.c en_resources.c
 SRCS	+=3D en_rx.c en_tx.c
+SRCS	+=3D opt_inet.h opt_inet6.h
 CFLAGS+=3D -I${.CURDIR}/../../ofed/drivers/net/mlx4
 CFLAGS+=3D -I${.CURDIR}/../../ofed/include/
-CFLAGS+=3D -DINET6
+
+.if !defined(KERNBUILDDIR)
+.if ${MK_INET_SUPPORT} !=3D "no"
+opt_inet.h:
+	@echo "#define INET 1" > ${.TARGET}
+.endif
+
+.if ${MK_INET6_SUPPORT} !=3D "no"
+opt_inet6.h:
+	@echo "#define INET6 1" > ${.TARGET}
+.endif
+.endif
=20
 .include <bsd.kmod.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/mps/Makefile
--- a/head/sys/modules/mps/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/mps/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/modules/mps/Makefile 233049 2012-03-16 21:46:02Z rmh $
+# $FreeBSD: head/sys/modules/mps/Makefile 233354 2012-03-23 11:35:01Z dim $
=20
 .PATH: ${.CURDIR}/../../dev/mps
=20
@@ -11,3 +11,6 @@
 #CFLAGS +=3D -DMPS_DEBUG
=20
 .include <bsd.kmod.mk>
+
+CWARNFLAGS.mps_sas.c=3D	${NO_WUNNEEDED_INTERNAL_DECL}
+CWARNFLAGS+=3D		${CWARNFLAGS.${.IMPSRC:T}}
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/mthca/Makefile
--- a/head/sys/modules/mthca/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/mthca/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,14 +1,30 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/mthca/Makefile 234183 2012-04-12 14:01:06Z jh=
b $
=20
 .PATH:  ${.CURDIR}/../../ofed/drivers/infiniband/hw/mthca
+
+.include <bsd.own.mk>
+
 KMOD    =3D mthca
 SRCS    =3D device_if.h bus_if.h pci_if.h vnode_if.h
 SRCS+=3D	mthca_allocator.c mthca_av.c mthca_catas.c mthca_cmd.c mthca_cq.c
 SRCS+=3D	mthca_eq.c mthca_mad.c mthca_main.c mthca_mcg.c mthca_memfree.c
 SRCS+=3D	mthca_mr.c mthca_pd.c mthca_profile.c mthca_provider.c mthca_qp.c
 SRCS+=3D	mthca_reset.c mthca_srq.c mthca_uar.c
+SRCS+=3D	opt_inet.h opt_inet6.h
=20
-CFLAGS+=3D -I${.CURDIR}/../../ofed/include/ -DINET6
+CFLAGS+=3D -I${.CURDIR}/../../ofed/include
+
+.if !defined(KERNBUILDDIR)
+.if ${MK_INET_SUPPORT} !=3D "no"
+opt_inet.h:
+	@echo "#define INET 1" > ${.TARGET}
+.endif
+
+.if ${MK_INET6_SUPPORT} !=3D "no"
+opt_inet6.h:
+	@echo "#define INET6 1" > ${.TARGET}
+.endif
+.endif
=20
 .include <bsd.kmod.mk>
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/ral/Makefile
--- a/head/sys/modules/ral/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/ral/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,13 +1,9 @@
 # $FreeBSD$
=20
 .PATH: ${.CURDIR}/../../dev/ral
-MK_CLANG_IS_CC=3Dno # XXX
=20
 KMOD=3D	if_ral
-SRCS=3D	rt2560.c rt2661.c if_ral_pci.c
+SRCS=3D	rt2560.c rt2661.c rt2860.c if_ral_pci.c
 SRCS+=3D	device_if.h bus_if.h pci_if.h
-# Ralink RT2860 Family
-SRCS+=3D	rt2860.c
-
=20
 .include <bsd.kmod.mk>
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/ralfw/Makefile.inc
--- a/head/sys/modules/ralfw/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/ralfw/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/ralfw/Makefile.inc 178354 2008-04-20 20:35:46=
Z sam $
=20
 #
 # Common rules for building firmware.  Note this gets auto-included
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/ralfw/rt2561/Makefile
--- a/head/sys/modules/ralfw/rt2561/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/ralfw/rt2561/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/ralfw/rt2561/Makefile 178354 2008-04-20 20:35=
:46Z sam $
=20
 IMG=3D	rt2561
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/ralfw/rt2561s/Makefile
--- a/head/sys/modules/ralfw/rt2561s/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/ralfw/rt2561s/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/ralfw/rt2561s/Makefile 178354 2008-04-20 20:3=
5:46Z sam $
=20
 IMG=3D	rt2561s
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/modules/ralfw/rt2661/Makefile
--- a/head/sys/modules/ralfw/rt2661/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/modules/ralfw/rt2661/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/sys/modules/ralfw/rt2661/Makefile 178354 2008-04-20 20:35=
:46Z sam $
=20
 IMG=3D	rt2661
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/bpf.c
--- a/head/sys/net/bpf.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/bpf.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net/bpf.c 232449 2012-03-03 08:19:18Z jmallet=
t $");
+__FBSDID("$FreeBSD: head/sys/net/bpf.c 233946 2012-04-06 13:34:19Z melifar=
o $");
=20
 #include "opt_bpf.h"
 #include "opt_compat.h"
@@ -43,6 +43,8 @@
=20
 #include <sys/types.h>
 #include <sys/param.h>
+#include <sys/lock.h>
+#include <sys/rwlock.h>
 #include <sys/systm.h>
 #include <sys/conf.h>
 #include <sys/fcntl.h>
@@ -66,6 +68,7 @@
 #include <sys/socket.h>
=20
 #include <net/if.h>
+#define	BPF_INTERNAL
 #include <net/bpf.h>
 #include <net/bpf_buffer.h>
 #ifdef BPF_JITTER
@@ -173,6 +176,12 @@
 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
     bpf_stats_sysctl, "bpf statistics portal");
=20
+static VNET_DEFINE(int, bpf_optimize_writers) =3D 0;
+#define	V_bpf_optimize_writers VNET(bpf_optimize_writers)
+SYSCTL_VNET_INT(_net_bpf, OID_AUTO, optimize_writers,
+    CTLFLAG_RW, &VNET_NAME(bpf_optimize_writers), 0,
+    "Do not send packets until BPF program is set");
+
 static	d_open_t	bpfopen;
 static	d_read_t	bpfread;
 static	d_write_t	bpfwrite;
@@ -207,7 +216,7 @@
     u_int len)
 {
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	switch (d->bd_bufmode) {
 	case BPF_BUFMODE_BUFFER:
@@ -227,7 +236,7 @@
     u_int len)
 {
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	switch (d->bd_bufmode) {
 	case BPF_BUFMODE_BUFFER:
@@ -249,7 +258,7 @@
 bpf_buf_reclaimed(struct bpf_d *d)
 {
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	switch (d->bd_bufmode) {
 	case BPF_BUFMODE_BUFFER:
@@ -290,7 +299,6 @@
 static int
 bpf_canwritebuf(struct bpf_d *d)
 {
-
 	BPFD_LOCK_ASSERT(d);
=20
 	switch (d->bd_bufmode) {
@@ -309,7 +317,7 @@
 bpf_buffull(struct bpf_d *d)
 {
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	switch (d->bd_bufmode) {
 	case BPF_BUFMODE_ZBUF:
@@ -325,7 +333,7 @@
 bpf_bufheld(struct bpf_d *d)
 {
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	switch (d->bd_bufmode) {
 	case BPF_BUFMODE_ZBUF:
@@ -570,16 +578,65 @@
 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
 {
 	/*
-	 * Point d at bp, and add d to the interface's list of listeners.
-	 * Finally, point the driver's bpf cookie at the interface so
-	 * it will divert packets to bpf.
+	 * Point d at bp, and add d to the interface's list.
+	 * Since there are many applicaiotns using BPF for
+	 * sending raw packets only (dhcpd, cdpd are good examples)
+	 * we can delay adding d to the list of active listeners until
+	 * some filter is configured.
 	 */
-	BPFIF_LOCK(bp);
 	d->bd_bif =3D bp;
+
+	BPFIF_WLOCK(bp);
+
+	if (V_bpf_optimize_writers !=3D 0) {
+		/* Add to writers-only list */
+		LIST_INSERT_HEAD(&bp->bif_wlist, d, bd_next);
+		/*
+		 * We decrement bd_writer on every filter set operation.
+		 * First BIOCSETF is done by pcap_open_live() to set up
+		 * snap length. After that appliation usually sets its own filter
+		 */
+		d->bd_writer =3D 2;
+	} else
+		LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
+
+	BPFIF_WUNLOCK(bp);
+
+	BPF_LOCK();
+	bpf_bpfd_cnt++;
+	BPF_UNLOCK();
+
+	CTR3(KTR_NET, "%s: bpf_attach called by pid %d, adding to %s list",
+	    __func__, d->bd_pid, d->bd_writer ? "writer" : "active");
+
+	if (V_bpf_optimize_writers =3D=3D 0)
+		EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
+}
+
+/*
+ * Add d to the list of active bp filters.
+ * Reuqires bpf_attachd() to be called before
+ */
+static void
+bpf_upgraded(struct bpf_d *d)
+{
+	struct bpf_if *bp;
+
+	bp =3D d->bd_bif;
+
+	BPFIF_WLOCK(bp);
+	BPFD_WLOCK(d);
+
+	/* Remove from writers-only list */
+	LIST_REMOVE(d, bd_next);
 	LIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
+	/* Mark d as reader */
+	d->bd_writer =3D 0;
=20
-	bpf_bpfd_cnt++;
-	BPFIF_UNLOCK(bp);
+	BPFD_WUNLOCK(d);
+	BPFIF_WUNLOCK(bp);
+
+	CTR2(KTR_NET, "%s: upgrade required by pid %d", __func__, d->bd_pid);
=20
 	EVENTHANDLER_INVOKE(bpf_track, bp->bif_ifp, bp->bif_dlt, 1);
 }
@@ -594,22 +651,33 @@
 	struct bpf_if *bp;
 	struct ifnet *ifp;
=20
+	CTR2(KTR_NET, "%s: detach required by pid %d", __func__, d->bd_pid);
+
+	BPF_LOCK_ASSERT();
+
 	bp =3D d->bd_bif;
-	BPFIF_LOCK(bp);
-	BPFD_LOCK(d);
-	ifp =3D d->bd_bif->bif_ifp;
+	BPFIF_WLOCK(bp);
+	BPFD_WLOCK(d);
+
+	/* Save bd_writer value */
+	error =3D d->bd_writer;
=20
 	/*
 	 * Remove d from the interface's descriptor list.
 	 */
 	LIST_REMOVE(d, bd_next);
=20
+	ifp =3D bp->bif_ifp;
+	d->bd_bif =3D NULL;
+	BPFD_WUNLOCK(d);
+	BPFIF_WUNLOCK(bp);
+
+	/* We're already protected by global lock. */
 	bpf_bpfd_cnt--;
-	d->bd_bif =3D NULL;
-	BPFD_UNLOCK(d);
-	BPFIF_UNLOCK(bp);
=20
-	EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
+	/* Call event handler iff d is attached */
+	if (error =3D=3D 0)
+		EVENTHANDLER_INVOKE(bpf_track, ifp, bp->bif_dlt, 0);
=20
 	/*
 	 * Check if this descriptor had requested promiscuous mode.
@@ -642,16 +710,16 @@
 {
 	struct bpf_d *d =3D data;
=20
-	BPFD_LOCK(d);
+	BPFD_WLOCK(d);
 	if (d->bd_state =3D=3D BPF_WAITING)
 		callout_stop(&d->bd_callout);
 	d->bd_state =3D BPF_IDLE;
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
 	funsetown(&d->bd_sigio);
-	mtx_lock(&bpf_mtx);
+	BPF_LOCK();
 	if (d->bd_bif)
 		bpf_detachd(d);
-	mtx_unlock(&bpf_mtx);
+	BPF_UNLOCK();
 #ifdef MAC
 	mac_bpfdesc_destroy(d);
 #endif /* MAC */
@@ -689,14 +757,14 @@
 	d->bd_bufmode =3D BPF_BUFMODE_BUFFER;
 	d->bd_sig =3D SIGIO;
 	d->bd_direction =3D BPF_D_INOUT;
-	d->bd_pid =3D td->td_proc->p_pid;
+	BPF_PID_REFRESH(d, td);
 #ifdef MAC
 	mac_bpfdesc_init(d);
 	mac_bpfdesc_create(td->td_ucred, d);
 #endif
-	mtx_init(&d->bd_mtx, devtoname(dev), "bpf cdev lock", MTX_DEF);
-	callout_init_mtx(&d->bd_callout, &d->bd_mtx, 0);
-	knlist_init_mtx(&d->bd_sel.si_note, &d->bd_mtx);
+	rw_init(&d->bd_lock, "bpf cdev lock");
+	callout_init_rw(&d->bd_callout, &d->bd_lock, 0);
+	knlist_init_rw_reader(&d->bd_sel.si_note, &d->bd_lock);
=20
 	return (0);
 }
@@ -725,10 +793,10 @@
=20
 	non_block =3D ((ioflag & O_NONBLOCK) !=3D 0);
=20
-	BPFD_LOCK(d);
-	d->bd_pid =3D curthread->td_proc->p_pid;
+	BPFD_WLOCK(d);
+	BPF_PID_REFRESH_CUR(d);
 	if (d->bd_bufmode !=3D BPF_BUFMODE_BUFFER) {
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
 		return (EOPNOTSUPP);
 	}
 	if (d->bd_state =3D=3D BPF_WAITING)
@@ -764,18 +832,18 @@
 		 * it before using it again.
 		 */
 		if (d->bd_bif =3D=3D NULL) {
-			BPFD_UNLOCK(d);
+			BPFD_WUNLOCK(d);
 			return (ENXIO);
 		}
=20
 		if (non_block) {
-			BPFD_UNLOCK(d);
+			BPFD_WUNLOCK(d);
 			return (EWOULDBLOCK);
 		}
-		error =3D msleep(d, &d->bd_mtx, PRINET|PCATCH,
+		error =3D rw_sleep(d, &d->bd_lock, PRINET|PCATCH,
 		     "bpf", d->bd_rtout);
 		if (error =3D=3D EINTR || error =3D=3D ERESTART) {
-			BPFD_UNLOCK(d);
+			BPFD_WUNLOCK(d);
 			return (error);
 		}
 		if (error =3D=3D EWOULDBLOCK) {
@@ -793,7 +861,7 @@
 				break;
=20
 			if (d->bd_slen =3D=3D 0) {
-				BPFD_UNLOCK(d);
+				BPFD_WUNLOCK(d);
 				return (0);
 			}
 			ROTATE_BUFFERS(d);
@@ -803,7 +871,7 @@
 	/*
 	 * At this point, we know we have something in the hold slot.
 	 */
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
=20
 	/*
 	 * Move data from hold buffer into user space.
@@ -816,12 +884,12 @@
 	 */
 	error =3D bpf_uiomove(d, d->bd_hbuf, d->bd_hlen, uio);
=20
-	BPFD_LOCK(d);
+	BPFD_WLOCK(d);
 	d->bd_fbuf =3D d->bd_hbuf;
 	d->bd_hbuf =3D NULL;
 	d->bd_hlen =3D 0;
 	bpf_buf_reclaimed(d);
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
=20
 	return (error);
 }
@@ -833,7 +901,7 @@
 bpf_wakeup(struct bpf_d *d)
 {
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
 	if (d->bd_state =3D=3D BPF_WAITING) {
 		callout_stop(&d->bd_callout);
 		d->bd_state =3D BPF_IDLE;
@@ -851,7 +919,7 @@
 {
 	struct bpf_d *d =3D (struct bpf_d *)arg;
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	if (callout_pending(&d->bd_callout) || !callout_active(&d->bd_callout))
 		return;
@@ -866,7 +934,7 @@
 bpf_ready(struct bpf_d *d)
 {
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	if (!bpf_canfreebuf(d) && d->bd_hlen !=3D 0)
 		return (1);
@@ -889,7 +957,7 @@
 	if (error !=3D 0)
 		return (error);
=20
-	d->bd_pid =3D curthread->td_proc->p_pid;
+	BPF_PID_REFRESH_CUR(d);
 	d->bd_wcount++;
 	if (d->bd_bif =3D=3D NULL) {
 		d->bd_wdcount++;
@@ -937,11 +1005,11 @@
=20
 	CURVNET_SET(ifp->if_vnet);
 #ifdef MAC
-	BPFD_LOCK(d);
+	BPFD_WLOCK(d);
 	mac_bpfdesc_create_mbuf(d, m);
 	if (mc !=3D NULL)
 		mac_bpfdesc_create_mbuf(d, mc);
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
 #endif
=20
 	error =3D (*ifp->if_output)(ifp, m, &dst, NULL);
@@ -970,7 +1038,7 @@
 reset_d(struct bpf_d *d)
 {
=20
-	mtx_assert(&d->bd_mtx, MA_OWNED);
+	BPFD_WLOCK_ASSERT(d);
=20
 	if ((d->bd_hbuf !=3D NULL) &&
 	    (d->bd_bufmode !=3D BPF_BUFMODE_ZBUF || bpf_canfreebuf(d))) {
@@ -1037,12 +1105,12 @@
 	/*
 	 * Refresh PID associated with this descriptor.
 	 */
-	BPFD_LOCK(d);
-	d->bd_pid =3D td->td_proc->p_pid;
+	BPFD_WLOCK(d);
+	BPF_PID_REFRESH(d, td);
 	if (d->bd_state =3D=3D BPF_WAITING)
 		callout_stop(&d->bd_callout);
 	d->bd_state =3D BPF_IDLE;
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
=20
 	if (d->bd_locked =3D=3D 1) {
 		switch (cmd) {
@@ -1108,11 +1176,11 @@
 		{
 			int n;
=20
-			BPFD_LOCK(d);
+			BPFD_WLOCK(d);
 			n =3D d->bd_slen;
 			if (d->bd_hbuf)
 				n +=3D d->bd_hlen;
-			BPFD_UNLOCK(d);
+			BPFD_WUNLOCK(d);
=20
 			*(int *)addr =3D n;
 			break;
@@ -1163,9 +1231,9 @@
 	 * Flush read packet buffer.
 	 */
 	case BIOCFLUSH:
-		BPFD_LOCK(d);
+		BPFD_WLOCK(d);
 		reset_d(d);
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
 		break;
=20
 	/*
@@ -1488,15 +1556,15 @@
 			return (EINVAL);
 		}
=20
-		BPFD_LOCK(d);
+		BPFD_WLOCK(d);
 		if (d->bd_sbuf !=3D NULL || d->bd_hbuf !=3D NULL ||
 		    d->bd_fbuf !=3D NULL || d->bd_bif !=3D NULL) {
-			BPFD_UNLOCK(d);
+			BPFD_WUNLOCK(d);
 			CURVNET_RESTORE();
 			return (EBUSY);
 		}
 		d->bd_bufmode =3D *(u_int *)addr;
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
 		break;
=20
 	case BIOCGETZMAX:
@@ -1527,6 +1595,7 @@
 #ifdef BPF_JITTER
 	bpf_jit_filter *ofunc;
 #endif
+	int need_upgrade;
 #ifdef COMPAT_FREEBSD32
 	struct bpf_program32 *fp32;
 	struct bpf_program fp_swab;
@@ -1556,7 +1625,12 @@
 	if (fp->bf_insns =3D=3D NULL) {
 		if (fp->bf_len !=3D 0)
 			return (EINVAL);
-		BPFD_LOCK(d);
+		/*=20
+		 * Protect filter change by interface lock, too.
+		 * The same lock order is used by bpf_detachd().
+		 */
+		BPFIF_WLOCK(d->bd_bif);
+		BPFD_WLOCK(d);
 		if (wfilter)
 			d->bd_wfilter =3D NULL;
 		else {
@@ -1567,7 +1641,8 @@
 			if (cmd =3D=3D BIOCSETF)
 				reset_d(d);
 		}
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
+		BPFIF_WUNLOCK(d->bd_bif);
 		if (old !=3D NULL)
 			free((caddr_t)old, M_BPF);
 #ifdef BPF_JITTER
@@ -1580,11 +1655,17 @@
 	if (flen > bpf_maxinsns)
 		return (EINVAL);
=20
+	need_upgrade =3D 0;
 	size =3D flen * sizeof(*fp->bf_insns);
 	fcode =3D (struct bpf_insn *)malloc(size, M_BPF, M_WAITOK);
 	if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) =3D=3D 0 &&
 	    bpf_validate(fcode, (int)flen)) {
-		BPFD_LOCK(d);
+		/*=20
+		 * Protect filter change by interface lock, too
+		 * The same lock order is used by bpf_detachd().
+		 */
+		BPFIF_WLOCK(d->bd_bif);
+		BPFD_WLOCK(d);
 		if (wfilter)
 			d->bd_wfilter =3D fcode;
 		else {
@@ -1594,8 +1675,19 @@
 #endif
 			if (cmd =3D=3D BIOCSETF)
 				reset_d(d);
+
+			/*
+			 * Do not require upgrade by first BIOCSETF
+			 * (used to set snaplen) by pcap_open_live()
+			 */
+			if ((d->bd_writer !=3D 0) && (--d->bd_writer =3D=3D 0))
+				need_upgrade =3D 1;
+			CTR4(KTR_NET, "%s: filter function set by pid %d, "
+			    "bd_writer counter %d, need_upgrade %d",
+			    __func__, d->bd_pid, d->bd_writer, need_upgrade);
 		}
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
+		BPFIF_WUNLOCK(d->bd_bif);
 		if (old !=3D NULL)
 			free((caddr_t)old, M_BPF);
 #ifdef BPF_JITTER
@@ -1603,6 +1695,10 @@
 			bpf_destroy_jit_filter(ofunc);
 #endif
=20
+		/* Move d to active readers list */
+		if (need_upgrade !=3D 0)
+			bpf_upgraded(d);
+
 		return (0);
 	}
 	free((caddr_t)fcode, M_BPF);
@@ -1659,9 +1755,9 @@
=20
 		bpf_attachd(d, bp);
 	}
-	BPFD_LOCK(d);
+	BPFD_WLOCK(d);
 	reset_d(d);
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
 	return (0);
 }
=20
@@ -1685,8 +1781,8 @@
 	 * Refresh PID associated with this descriptor.
 	 */
 	revents =3D events & (POLLOUT | POLLWRNORM);
-	BPFD_LOCK(d);
-	d->bd_pid =3D td->td_proc->p_pid;
+	BPFD_WLOCK(d);
+	BPF_PID_REFRESH(d, td);
 	if (events & (POLLIN | POLLRDNORM)) {
 		if (bpf_ready(d))
 			revents |=3D events & (POLLIN | POLLRDNORM);
@@ -1700,7 +1796,7 @@
 			}
 		}
 	}
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
 	return (revents);
 }
=20
@@ -1720,12 +1816,12 @@
 	/*
 	 * Refresh PID associated with this descriptor.
 	 */
-	BPFD_LOCK(d);
-	d->bd_pid =3D curthread->td_proc->p_pid;
+	BPFD_WLOCK(d);
+	BPF_PID_REFRESH_CUR(d);
 	kn->kn_fop =3D &bpfread_filtops;
 	kn->kn_hook =3D d;
 	knlist_add(&d->bd_sel.si_note, kn, 1);
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
=20
 	return (0);
 }
@@ -1744,7 +1840,7 @@
 	struct bpf_d *d =3D (struct bpf_d *)kn->kn_hook;
 	int ready;
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
 	ready =3D bpf_ready(d);
 	if (ready) {
 		kn->kn_data =3D d->bd_slen;
@@ -1819,9 +1915,19 @@
 	int gottime;
=20
 	gottime =3D BPF_TSTAMP_NONE;
-	BPFIF_LOCK(bp);
+
+	BPFIF_RLOCK(bp);
+
 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
-		BPFD_LOCK(d);
+		/*
+		 * We are not using any locks for d here because:
+		 * 1) any filter change is protected by interface
+		 * write lock
+		 * 2) destroying/detaching d is protected by interface
+		 * write lock, too
+		 */
+
+		/* XXX: Do not protect counter for the sake of performance. */
 		++d->bd_rcount;
 		/*
 		 * NB: We dont call BPF_CHECK_DIRECTION() here since there is no
@@ -1837,6 +1943,11 @@
 #endif
 		slen =3D bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
 		if (slen !=3D 0) {
+			/*
+			 * Filter matches. Let's to acquire write lock.
+			 */
+			BPFD_WLOCK(d);
+
 			d->bd_fcount++;
 			if (gottime < bpf_ts_quality(d->bd_tstamp))
 				gottime =3D bpf_gettime(&bt, d->bd_tstamp, NULL);
@@ -1845,10 +1956,10 @@
 #endif
 				catchpacket(d, pkt, pktlen, slen,
 				    bpf_append_bytes, &bt);
+			BPFD_WUNLOCK(d);
 		}
-		BPFD_UNLOCK(d);
 	}
-	BPFIF_UNLOCK(bp);
+	BPFIF_RUNLOCK(bp);
 }
=20
 #define	BPF_CHECK_DIRECTION(d, r, i)				\
@@ -1857,6 +1968,7 @@
=20
 /*
  * Incoming linkage from device drivers, when packet is in an mbuf chain.
+ * Locking model is explained in bpf_tap().
  */
 void
 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
@@ -1876,13 +1988,13 @@
 	}
=20
 	pktlen =3D m_length(m, NULL);
+	gottime =3D BPF_TSTAMP_NONE;
=20
-	gottime =3D BPF_TSTAMP_NONE;
-	BPFIF_LOCK(bp);
+	BPFIF_RLOCK(bp);
+
 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
 		if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
 			continue;
-		BPFD_LOCK(d);
 		++d->bd_rcount;
 #ifdef BPF_JITTER
 		bf =3D bpf_jitter_enable !=3D 0 ? d->bd_bfilter : NULL;
@@ -1893,6 +2005,8 @@
 #endif
 		slen =3D bpf_filter(d->bd_rfilter, (u_char *)m, pktlen, 0);
 		if (slen !=3D 0) {
+			BPFD_WLOCK(d);
+
 			d->bd_fcount++;
 			if (gottime < bpf_ts_quality(d->bd_tstamp))
 				gottime =3D bpf_gettime(&bt, d->bd_tstamp, m);
@@ -1901,10 +2015,10 @@
 #endif
 				catchpacket(d, (u_char *)m, pktlen, slen,
 				    bpf_append_mbuf, &bt);
+			BPFD_WUNLOCK(d);
 		}
-		BPFD_UNLOCK(d);
 	}
-	BPFIF_UNLOCK(bp);
+	BPFIF_RUNLOCK(bp);
 }
=20
 /*
@@ -1938,14 +2052,17 @@
 	pktlen +=3D dlen;
=20
 	gottime =3D BPF_TSTAMP_NONE;
-	BPFIF_LOCK(bp);
+
+	BPFIF_RLOCK(bp);
+
 	LIST_FOREACH(d, &bp->bif_dlist, bd_next) {
 		if (BPF_CHECK_DIRECTION(d, m->m_pkthdr.rcvif, bp->bif_ifp))
 			continue;
-		BPFD_LOCK(d);
 		++d->bd_rcount;
 		slen =3D bpf_filter(d->bd_rfilter, (u_char *)&mb, pktlen, 0);
 		if (slen !=3D 0) {
+			BPFD_WLOCK(d);
+
 			d->bd_fcount++;
 			if (gottime < bpf_ts_quality(d->bd_tstamp))
 				gottime =3D bpf_gettime(&bt, d->bd_tstamp, m);
@@ -1954,10 +2071,10 @@
 #endif
 				catchpacket(d, (u_char *)&mb, pktlen, slen,
 				    bpf_append_mbuf, &bt);
+			BPFD_WUNLOCK(d);
 		}
-		BPFD_UNLOCK(d);
 	}
-	BPFIF_UNLOCK(bp);
+	BPFIF_RUNLOCK(bp);
 }
=20
 #undef	BPF_CHECK_DIRECTION
@@ -2049,7 +2166,7 @@
 	int do_timestamp;
 	int tstype;
=20
-	BPFD_LOCK_ASSERT(d);
+	BPFD_WLOCK_ASSERT(d);
=20
 	/*
 	 * Detect whether user space has released a buffer back to us, and if
@@ -2196,7 +2313,7 @@
 	}
 	if (d->bd_wfilter !=3D NULL)
 		free((caddr_t)d->bd_wfilter, M_BPF);
-	mtx_destroy(&d->bd_mtx);
+	rw_destroy(&d->bd_lock);
 }
=20
 /*
@@ -2226,15 +2343,16 @@
 		panic("bpfattach");
=20
 	LIST_INIT(&bp->bif_dlist);
+	LIST_INIT(&bp->bif_wlist);
 	bp->bif_ifp =3D ifp;
 	bp->bif_dlt =3D dlt;
-	mtx_init(&bp->bif_mtx, "bpf interface lock", NULL, MTX_DEF);
+	rw_init(&bp->bif_lock, "bpf interface lock");
 	KASSERT(*driverp =3D=3D NULL, ("bpfattach2: driverp already initialized")=
);
 	*driverp =3D bp;
=20
-	mtx_lock(&bpf_mtx);
+	BPF_LOCK();
 	LIST_INSERT_HEAD(&bpf_iflist, bp, bif_next);
-	mtx_unlock(&bpf_mtx);
+	BPF_UNLOCK();
=20
 	bp->bif_hdrlen =3D hdrlen;
=20
@@ -2261,14 +2379,14 @@
=20
 	/* Find all bpf_if struct's which reference ifp and detach them. */
 	do {
-		mtx_lock(&bpf_mtx);
+		BPF_LOCK();
 		LIST_FOREACH(bp, &bpf_iflist, bif_next) {
 			if (ifp =3D=3D bp->bif_ifp)
 				break;
 		}
 		if (bp !=3D NULL)
 			LIST_REMOVE(bp, bif_next);
-		mtx_unlock(&bpf_mtx);
+		BPF_UNLOCK();
=20
 		if (bp !=3D NULL) {
 #ifdef INVARIANTS
@@ -2276,11 +2394,11 @@
 #endif
 			while ((d =3D LIST_FIRST(&bp->bif_dlist)) !=3D NULL) {
 				bpf_detachd(d);
-				BPFD_LOCK(d);
+				BPFD_WLOCK(d);
 				bpf_wakeup(d);
-				BPFD_UNLOCK(d);
+				BPFD_WUNLOCK(d);
 			}
-			mtx_destroy(&bp->bif_mtx);
+			rw_destroy(&bp->bif_lock);
 			free(bp, M_BPF);
 		}
 	} while (bp !=3D NULL);
@@ -2304,13 +2422,13 @@
 	ifp =3D d->bd_bif->bif_ifp;
 	n =3D 0;
 	error =3D 0;
-	mtx_lock(&bpf_mtx);
+	BPF_LOCK();
 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
 		if (bp->bif_ifp !=3D ifp)
 			continue;
 		if (bfl->bfl_list !=3D NULL) {
 			if (n >=3D bfl->bfl_len) {
-				mtx_unlock(&bpf_mtx);
+				BPF_UNLOCK();
 				return (ENOMEM);
 			}
 			error =3D copyout(&bp->bif_dlt,
@@ -2318,7 +2436,7 @@
 		}
 		n++;
 	}
-	mtx_unlock(&bpf_mtx);
+	BPF_UNLOCK();
 	bfl->bfl_len =3D n;
 	return (error);
 }
@@ -2336,19 +2454,19 @@
 	if (d->bd_bif->bif_dlt =3D=3D dlt)
 		return (0);
 	ifp =3D d->bd_bif->bif_ifp;
-	mtx_lock(&bpf_mtx);
+	BPF_LOCK();
 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
 		if (bp->bif_ifp =3D=3D ifp && bp->bif_dlt =3D=3D dlt)
 			break;
 	}
-	mtx_unlock(&bpf_mtx);
+	BPF_UNLOCK();
 	if (bp !=3D NULL) {
 		opromisc =3D d->bd_promisc;
 		bpf_detachd(d);
 		bpf_attachd(d, bp);
-		BPFD_LOCK(d);
+		BPFD_WLOCK(d);
 		reset_d(d);
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
 		if (opromisc) {
 			error =3D ifpromisc(bp->bif_ifp, 1);
 			if (error)
@@ -2386,22 +2504,22 @@
 	struct bpf_if *bp;
 	struct bpf_d *bd;
=20
-	mtx_lock(&bpf_mtx);
+	BPF_LOCK();
 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
-		BPFIF_LOCK(bp);
+		BPFIF_RLOCK(bp);
 		LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
-			BPFD_LOCK(bd);
+			BPFD_WLOCK(bd);
 			bd->bd_rcount =3D 0;
 			bd->bd_dcount =3D 0;
 			bd->bd_fcount =3D 0;
 			bd->bd_wcount =3D 0;
 			bd->bd_wfcount =3D 0;
 			bd->bd_zcopy =3D 0;
-			BPFD_UNLOCK(bd);
+			BPFD_WUNLOCK(bd);
 		}
-		BPFIF_UNLOCK(bp);
+		BPFIF_RUNLOCK(bp);
 	}
-	mtx_unlock(&bpf_mtx);
+	BPF_UNLOCK();
 }
=20
 static void
@@ -2472,24 +2590,31 @@
 	if (bpf_bpfd_cnt =3D=3D 0)
 		return (SYSCTL_OUT(req, 0, 0));
 	xbdbuf =3D malloc(req->oldlen, M_BPF, M_WAITOK);
-	mtx_lock(&bpf_mtx);
+	BPF_LOCK();
 	if (req->oldlen < (bpf_bpfd_cnt * sizeof(*xbd))) {
-		mtx_unlock(&bpf_mtx);
+		BPF_UNLOCK();
 		free(xbdbuf, M_BPF);
 		return (ENOMEM);
 	}
 	index =3D 0;
 	LIST_FOREACH(bp, &bpf_iflist, bif_next) {
-		BPFIF_LOCK(bp);
+		BPFIF_RLOCK(bp);
+		/* Send writers-only first */
+		LIST_FOREACH(bd, &bp->bif_wlist, bd_next) {
+			xbd =3D &xbdbuf[index++];
+			BPFD_RLOCK(bd);
+			bpfstats_fill_xbpf(xbd, bd);
+			BPFD_RUNLOCK(bd);
+		}
 		LIST_FOREACH(bd, &bp->bif_dlist, bd_next) {
 			xbd =3D &xbdbuf[index++];
-			BPFD_LOCK(bd);
+			BPFD_RLOCK(bd);
 			bpfstats_fill_xbpf(xbd, bd);
-			BPFD_UNLOCK(bd);
+			BPFD_RUNLOCK(bd);
 		}
-		BPFIF_UNLOCK(bp);
+		BPFIF_RUNLOCK(bp);
 	}
-	mtx_unlock(&bpf_mtx);
+	BPF_UNLOCK();
 	error =3D SYSCTL_OUT(req, xbdbuf, index * sizeof(*xbd));
 	free(xbdbuf, M_BPF);
 	return (error);
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/bpf.h
--- a/head/sys/net/bpf.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/bpf.h	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  *      @(#)bpf.h	8.1 (Berkeley) 6/10/93
  *	@(#)bpf.h	1.34 (LBL)     6/16/96
  *
- * $FreeBSD: head/sys/net/bpf.h 229073 2011-12-31 07:21:28Z lstewart $
+ * $FreeBSD: head/sys/net/bpf.h 233938 2012-04-06 06:55:21Z melifaro $
  */
=20
 #ifndef _NET_BPF_H_
@@ -1092,14 +1092,20 @@
=20
 /*
  * Descriptor associated with each attached hardware interface.
+ * FIXME: this structure is exposed to external callers to speed up
+ * bpf_peers_present() call. However we cover all fields not needed by
+ * this function via BPF_INTERNAL define
  */
 struct bpf_if {
 	LIST_ENTRY(bpf_if)	bif_next;	/* list of all interfaces */
 	LIST_HEAD(, bpf_d)	bif_dlist;	/* descriptor list */
+#ifdef BPF_INTERNAL
 	u_int bif_dlt;				/* link layer type */
 	u_int bif_hdrlen;		/* length of link header */
 	struct ifnet *bif_ifp;		/* corresponding interface */
-	struct mtx	bif_mtx;	/* mutex for interface */
+	struct rwlock bif_lock;		/* interface lock */
+	LIST_HEAD(, bpf_d)	bif_wlist;	/* writer-only list */
+#endif
 };
=20
 void	 bpf_bufheld(struct bpf_d *d);
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/bpf_buffer.c
--- a/head/sys/net/bpf_buffer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/bpf_buffer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -62,7 +62,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net/bpf_buffer.c 230108 2012-01-14 17:07:52Z =
eadler $");
+__FBSDID("$FreeBSD: head/sys/net/bpf_buffer.c 233937 2012-04-06 06:53:58Z =
melifaro $");
=20
 #include "opt_bpf.h"
=20
@@ -184,9 +184,9 @@
 {
 	u_int size;
=20
-	BPFD_LOCK(d);
+	BPFD_WLOCK(d);
 	if (d->bd_bif !=3D NULL) {
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
 		return (EINVAL);
 	}
 	size =3D *i;
@@ -195,7 +195,7 @@
 	else if (size < BPF_MINBUFSIZE)
 		*i =3D size =3D BPF_MINBUFSIZE;
 	d->bd_bufsize =3D size;
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
 	return (0);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/bpf_zerocopy.c
--- a/head/sys/net/bpf_zerocopy.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/bpf_zerocopy.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net/bpf_zerocopy.c 230108 2012-01-14 17:07:52=
Z eadler $");
+__FBSDID("$FreeBSD: head/sys/net/bpf_zerocopy.c 233937 2012-04-06 06:53:58=
Z melifaro $");
=20
 #include "opt_bpf.h"
=20
@@ -515,14 +515,14 @@
 	struct zbuf *bzh;
=20
 	bzero(bz, sizeof(*bz));
-	BPFD_LOCK(d);
+	BPFD_WLOCK(d);
 	if (d->bd_hbuf =3D=3D NULL && d->bd_slen !=3D 0) {
 		ROTATE_BUFFERS(d);
 		bzh =3D (struct zbuf *)d->bd_hbuf;
 		bz->bz_bufa =3D (void *)bzh->zb_uaddr;
 		bz->bz_buflen =3D d->bd_hlen;
 	}
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
 	return (0);
 }
=20
@@ -570,10 +570,10 @@
 	 * We only allow buffers to be installed once, so atomically check
 	 * that no buffers are currently installed and install new buffers.
 	 */
-	BPFD_LOCK(d);
+	BPFD_WLOCK(d);
 	if (d->bd_hbuf !=3D NULL || d->bd_sbuf !=3D NULL || d->bd_fbuf !=3D NULL =
||
 	    d->bd_bif !=3D NULL) {
-		BPFD_UNLOCK(d);
+		BPFD_WUNLOCK(d);
 		zbuf_free(zba);
 		zbuf_free(zbb);
 		return (EINVAL);
@@ -593,6 +593,6 @@
 	 * shared management region.
 	 */
 	d->bd_bufsize =3D bz->bz_buflen - sizeof(struct bpf_zbuf_header);
-	BPFD_UNLOCK(d);
+	BPFD_WUNLOCK(d);
 	return (0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/bpfdesc.h
--- a/head/sys/net/bpfdesc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/bpfdesc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
  *
  *      @(#)bpfdesc.h	8.1 (Berkeley) 6/10/93
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/net/bpfdesc.h 233938 2012-04-06 06:55:21Z melifaro $
  */
=20
 #ifndef _NET_BPFDESC_H_
@@ -79,6 +79,7 @@
 	u_char		bd_promisc;	/* true if listening promiscuously */
 	u_char		bd_state;	/* idle, waiting, or timed out */
 	u_char		bd_immediate;	/* true to return on packet arrival */
+	u_char		bd_writer;	/* non-zero if d is writer-only */
 	int		bd_hdrcmplt;	/* false to fill in src lladdr automatically */
 	int		bd_direction;	/* select packet direction */
 	int		bd_tstamp;	/* select time stamping function */
@@ -87,7 +88,7 @@
 	int		bd_sig;		/* signal to send upon packet reception */
 	struct sigio *	bd_sigio;	/* information for async I/O */
 	struct selinfo	bd_sel;		/* bsd select info */
-	struct mtx	bd_mtx;		/* mutex for this descriptor */
+	struct rwlock	bd_lock;	/* per-descriptor lock */
 	struct callout	bd_callout;	/* for BPF timeouts with select */
 	struct label	*bd_label;	/* MAC label for descriptor */
 	u_int64_t	bd_fcount;	/* number of packets which matched filter */
@@ -106,10 +107,19 @@
 #define BPF_WAITING	1		/* waiting for read timeout in select */
 #define BPF_TIMED_OUT	2		/* read timeout has expired in select */
=20
-#define BPFD_LOCK(bd)		mtx_lock(&(bd)->bd_mtx)
-#define BPFD_UNLOCK(bd)		mtx_unlock(&(bd)->bd_mtx)
-#define BPFD_LOCK_ASSERT(bd)	mtx_assert(&(bd)->bd_mtx, MA_OWNED)
+#define BPFD_RLOCK(bd)		rw_rlock(&(bd)->bd_lock)
+#define BPFD_RUNLOCK(bd)	rw_runlock(&(bd)->bd_lock)
+#define BPFD_WLOCK(bd)		rw_wlock(&(bd)->bd_lock)
+#define BPFD_WUNLOCK(bd)	rw_wunlock(&(bd)->bd_lock)
+#define BPFD_WLOCK_ASSERT(bd)	rw_assert(&(bd)->bd_lock, RA_WLOCKED)
+#define BPFD_LOCK_ASSERT(bd)	rw_assert(&(bd)->bd_lock, RA_LOCKED)
=20
+#define BPF_PID_REFRESH(bd, td)	(bd)->bd_pid =3D (td)->td_proc->p_pid
+#define BPF_PID_REFRESH_CUR(bd)	(bd)->bd_pid =3D curthread->td_proc->p_pid
+
+#define BPF_LOCK()		mtx_lock(&bpf_mtx)
+#define BPF_UNLOCK()		mtx_unlock(&bpf_mtx)
+#define BPF_LOCK_ASSERT()	mtx_assert(&bpf_mtx, MA_OWNED)
 /*
  * External representation of the bpf descriptor
  */
@@ -144,7 +154,9 @@
 	u_int64_t	bd_spare[4];
 };
=20
-#define BPFIF_LOCK(bif)		mtx_lock(&(bif)->bif_mtx)
-#define BPFIF_UNLOCK(bif)	mtx_unlock(&(bif)->bif_mtx)
+#define BPFIF_RLOCK(bif)	rw_rlock(&(bif)->bif_lock)
+#define BPFIF_RUNLOCK(bif)	rw_runlock(&(bif)->bif_lock)
+#define BPFIF_WLOCK(bif)	rw_wlock(&(bif)->bif_lock)
+#define BPFIF_WUNLOCK(bif)	rw_wunlock(&(bif)->bif_lock)
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/if_lagg.c
--- a/head/sys/net/if_lagg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/if_lagg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -18,7 +18,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net/if_lagg.c 232640 2012-03-07 07:22:53Z tho=
mpsa $");
+__FBSDID("$FreeBSD: head/sys/net/if_lagg.c 234163 2012-04-12 01:07:17Z tho=
mpsa $");
=20
 #include "opt_inet.h"
 #include "opt_inet6.h"
@@ -950,11 +950,11 @@
 			error =3D EPROTONOSUPPORT;
 			break;
 		}
+		LAGG_WLOCK(sc);
 		if (sc->sc_proto !=3D LAGG_PROTO_NONE) {
-			LAGG_WLOCK(sc);
+			/* Reset protocol first in case detach unlocks */
+			sc->sc_proto =3D LAGG_PROTO_NONE;
 			error =3D sc->sc_detach(sc);
-			/* Reset protocol and pointers */
-			sc->sc_proto =3D LAGG_PROTO_NONE;
 			sc->sc_detach =3D NULL;
 			sc->sc_start =3D NULL;
 			sc->sc_input =3D NULL;
@@ -966,10 +966,14 @@
 			sc->sc_lladdr =3D NULL;
 			sc->sc_req =3D NULL;
 			sc->sc_portreq =3D NULL;
+		} else if (sc->sc_input !=3D NULL) {
+			/* Still detaching */
+			error =3D EBUSY;
+		}
+		if (error !=3D 0) {
 			LAGG_WUNLOCK(sc);
+			break;
 		}
-		if (error !=3D 0)
-			break;
 		for (int i =3D 0; i < (sizeof(lagg_protos) /
 		    sizeof(lagg_protos[0])); i++) {
 			if (lagg_protos[i].ti_proto =3D=3D ra->ra_proto) {
@@ -977,7 +981,6 @@
 					printf("%s: using proto %u\n",
 					    sc->sc_ifname,
 					    lagg_protos[i].ti_proto);
-				LAGG_WLOCK(sc);
 				sc->sc_proto =3D lagg_protos[i].ti_proto;
 				if (sc->sc_proto !=3D LAGG_PROTO_NONE)
 					error =3D lagg_protos[i].ti_attach(sc);
@@ -985,6 +988,7 @@
 				return (error);
 			}
 		}
+		LAGG_WUNLOCK(sc);
 		error =3D EPROTONOSUPPORT;
 		break;
 	case SIOCGLAGGFLAGS:
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/if_media.h
--- a/head/sys/net/if_media.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/if_media.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*	$NetBSD: if_media.h,v 1.3 1997/03/26 01:19:27 thorpej Exp $	*/
-/* $FreeBSD: head/sys/net/if_media.h 229698 2012-01-06 12:05:43Z glebius $=
 */
+/* $FreeBSD: head/sys/net/if_media.h 234098 2012-04-10 13:59:35Z jhb $ */
=20
 /*-
  * Copyright (c) 1997
@@ -150,6 +150,9 @@
 #define	IFM_10G_LRM	24		/* 10GBase-LRM 850nm Multi-mode */
 #define	IFM_UNKNOWN	25		/* media types not defined yet */
 #define	IFM_10G_T	26		/* 10GBase-T - RJ45 */
+#define	IFM_40G_CR4	27		/* 40GBase-CR4 */
+#define	IFM_40G_SR4	28		/* 40GBase-SR4 */
+#define	IFM_40G_LR4	29		/* 40GBase-LR4 */
=20
 /* note 31 is the max! */
=20
@@ -360,6 +363,9 @@
 	{ IFM_10G_TWINAX_LONG,	"10Gbase-Twinax-Long" },		\
 	{ IFM_UNKNOWN,	"Unknown" },					\
 	{ IFM_10G_T,	"10Gbase-T" },					\
+	{ IFM_40G_CR4,	"40Gbase-CR4" },				\
+	{ IFM_40G_SR4,	"40Gbase-SR4" },				\
+	{ IFM_40G_LR4,	"40Gbase-LR4" },				\
 	{ 0, NULL },							\
 }
=20
@@ -658,6 +664,9 @@
 	{ IFM_ETHER | IFM_10G_TWINAX_LONG,	IF_Gbps(10ULL) },	\
 	{ IFM_ETHER | IFM_10G_LRM,	IF_Gbps(10ULL) },		\
 	{ IFM_ETHER | IFM_10G_T,	IF_Gbps(10ULL) },		\
+	{ IFM_ETHER | IFM_40G_CR4,	IF_Gbps(40ULL) },		\
+	{ IFM_ETHER | IFM_40G_SR4,	IF_Gbps(40ULL) },		\
+	{ IFM_ETHER | IFM_40G_LR4,	IF_Gbps(40ULL) },		\
 									\
 	{ IFM_TOKEN | IFM_TOK_STP4,	IF_Mbps(4) },			\
 	{ IFM_TOKEN | IFM_TOK_STP16,	IF_Mbps(16) },			\
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/netmap.h
--- a/head/sys/net/netmap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/netmap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 /*
- * $FreeBSD: head/sys/net/netmap.h 232238 2012-02-27 19:05:01Z luigi $
+ * $FreeBSD: head/sys/net/netmap.h 234227 2012-04-13 16:03:07Z luigi $
  * $Id: netmap.h 10601 2012-02-21 16:40:14Z luigi $
  *
  * Definitions of constants and the structures used by the netmap
@@ -83,8 +83,8 @@
                                              / | cur         |
    NETMAP_IF  (nifp, one per file desc.)    /  | avail       |
     +---------------+                      /   | buf_ofs     |
-    | ni_num_queues |                     /    +=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D+
-    |               |                    /     | buf_idx     | slot[0]
+    | ni_tx_rings   |                     /    +=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D+
+    | ni_rx_rings   |                    /     | buf_idx     | slot[0]
     |               |                   /      | len, flags  |
     |               |                  /       +-------------+
     +=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D+                 /     =
   | buf_idx     | slot[1]
@@ -221,8 +221,8 @@
 struct netmap_if {
 	char		ni_name[IFNAMSIZ]; /* name of the interface. */
 	const u_int	ni_version;	/* API version, currently unused */
-	const u_int	ni_rx_queues;	/* number of rx queue pairs */
-	const u_int	ni_tx_queues;	/* if zero, same as ni_tx_queues */
+	const u_int	ni_rx_rings;	/* number of rx rings */
+	const u_int	ni_tx_rings;	/* if zero, same as ni_rx_rings */
 	/*
 	 * The following array contains the offset of each netmap ring
 	 * from this structure. The first ni_tx_queues+1 entries refer
@@ -234,10 +234,6 @@
 	const ssize_t	ring_ofs[0];
 };
=20
-#ifndef IFCAP_NETMAP
-#define IFCAP_NETMAP	0x100000	/* used on linux */
-#endif
-
 #ifndef NIOCREGIF=09
 /*
  * ioctl names and related fields
@@ -261,7 +257,7 @@
 struct nmreq {
 	char		nr_name[IFNAMSIZ];
 	uint32_t	nr_version;	/* API version */
-#define	NETMAP_API	2		/* current version */
+#define	NETMAP_API	3		/* current version */
 	uint32_t	nr_offset;	/* nifp offset in the shared region */
 	uint32_t	nr_memsize;	/* size of the shared region */
 	uint32_t	nr_tx_slots;	/* slots in tx rings */
diff -r 428842767fa6 -r f2935497fa04 head/sys/net/netmap_user.h
--- a/head/sys/net/netmap_user.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net/netmap_user.h	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 /*
- * $FreeBSD: head/sys/net/netmap_user.h 232824 2012-03-11 17:35:12Z luigi $
+ * $FreeBSD: head/sys/net/netmap_user.h 234227 2012-04-13 16:03:07Z luigi $
  * $Id: netmap_user.h 10597 2012-02-21 05:08:32Z luigi $
  *
  * This header contains the macros used to manipulate netmap structures
@@ -70,7 +70,7 @@
=20
 #define NETMAP_RXRING(nifp, index)			\
 	((struct netmap_ring *)((char *)(nifp) +	\
-	    (nifp)->ring_ofs[index + (nifp)->ni_tx_queues+1] ) )
+	    (nifp)->ring_ofs[index + (nifp)->ni_tx_rings + 1] ) )
=20
 #define NETMAP_BUF(ring, index)				\
 	((char *)(ring) + (ring)->buf_ofs + ((index)*(ring)->nr_buf_size))
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211.c
--- a/head/sys/net80211/ieee80211.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211.c 230447 2012-01-22 05:30:=
29Z adrian $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211.c 233452 2012-03-25 03:11:=
57Z adrian $");
=20
 /*
  * IEEE 802.11 generic handler
@@ -256,6 +256,13 @@
 	m_freem(m);
 }
=20
+static void
+null_update_chw(struct ieee80211com *ic)
+{
+
+	if_printf(ic->ic_ifp, "%s: need callback\n", __func__);
+}
+
 /*
  * Attach/setup the common net80211 state.  Called by
  * the driver on attach to prior to creating any vap's.
@@ -287,6 +294,7 @@
=20
 	ic->ic_update_mcast =3D null_update_mcast;
 	ic->ic_update_promisc =3D null_update_promisc;
+	ic->ic_update_chw =3D null_update_chw;
=20
 	ic->ic_hash_key =3D arc4random();
 	ic->ic_bintval =3D IEEE80211_BINTVAL_DEFAULT;
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_ddb.c
--- a/head/sys/net80211/ieee80211_ddb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_ddb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_ddb.c 196019 2009-08-01 19=
:26:27Z rwatson $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_ddb.c 234324 2012-04-15 20=
:29:39Z adrian $");
=20
 #include "opt_ddb.h"
 #include "opt_wlan.h"
@@ -202,7 +202,7 @@
 {
 	db_printf("%stxampdu[%d]: %p flags %b %s\n",
 		sep, ix, tap, tap->txa_flags, IEEE80211_AGGR_BITS,
-		ieee80211_wme_acnames[tap->txa_ac]);
+		ieee80211_wme_acnames[TID_TO_WME_AC(tap->txa_tid)]);
 	db_printf("%s  token %u lastsample %d pkts %d avgpps %d qbytes %d qframes=
 %d\n",
 		sep, tap->txa_token, tap->txa_lastsample, tap->txa_pkts,
 		tap->txa_avgpps, tap->txa_qbytes, tap->txa_qframes);
@@ -293,7 +293,7 @@
 		ni->ni_htopmode, ni->ni_htstbc, ni->ni_chw);
=20
 	/* XXX ampdu state */
-	for (i =3D 0; i < WME_NUM_AC; i++)
+	for (i =3D 0; i < WME_NUM_TID; i++)
 		if (ni->ni_tx_ampdu[i].txa_flags & IEEE80211_AGGR_SETUP)
 			_db_show_txampdu("\t", i, &ni->ni_tx_ampdu[i]);
 	for (i =3D 0; i < WME_NUM_TID; i++)
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_freebsd.c
--- a/head/sys/net80211/ieee80211_freebsd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_freebsd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_freebsd.c 233050 2012-03-1=
6 23:08:13Z adrian $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_freebsd.c 233531 2012-03-2=
7 04:15:38Z adrian $");
=20
 /*
  * IEEE 802.11 support (FreeBSD-specific code)
@@ -572,7 +572,7 @@
=20
 	IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO, wh->i_addr2,
 	    "%s replay detected tid %d <rsc %ju, csc %ju, keyix %u rxkeyix %u>",
-	    tid, k->wk_cipher->ic_name, (intmax_t) rsc,
+	    k->wk_cipher->ic_name, tid, (intmax_t) rsc,
 	    (intmax_t) k->wk_keyrsc[tid],
 	    k->wk_keyix, k->wk_rxkeyix);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_ht.c
--- a/head/sys/net80211/ieee80211_ht.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_ht.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
=20
 #include <sys/cdefs.h>
 #ifdef __FreeBSD__
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_ht.c 229284 2012-01-02 16:=
02:30Z bschmidt $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_ht.c 234324 2012-04-15 20:=
29:39Z adrian $");
 #endif
=20
 /*
@@ -1023,7 +1023,7 @@
 ieee80211_ht_node_init(struct ieee80211_node *ni)
 {
 	struct ieee80211_tx_ampdu *tap;
-	int ac;
+	int tid;
=20
 	if (ni->ni_flags & IEEE80211_NODE_HT) {
 		/*
@@ -1033,9 +1033,9 @@
 		 */
 		ieee80211_ht_node_cleanup(ni);
 	}
-	for (ac =3D 0; ac < WME_NUM_AC; ac++) {
-		tap =3D &ni->ni_tx_ampdu[ac];
-		tap->txa_ac =3D ac;
+	for (tid =3D 0; tid < WME_NUM_TID; tid++) {
+		tap =3D &ni->ni_tx_ampdu[tid];
+		tap->txa_tid =3D tid;
 		tap->txa_ni =3D ni;
 		/* NB: further initialization deferred */
 	}
@@ -1055,7 +1055,7 @@
 	KASSERT(ni->ni_flags & IEEE80211_NODE_HT, ("not an HT node"));
=20
 	/* XXX optimize this */
-	for (i =3D 0; i < WME_NUM_AC; i++) {
+	for (i =3D 0; i < WME_NUM_TID; i++) {
 		struct ieee80211_tx_ampdu *tap =3D &ni->ni_tx_ampdu[i];
 		if (tap->txa_flags & IEEE80211_AGGR_SETUP)
 			ampdu_tx_stop(tap);
@@ -1160,7 +1160,7 @@
 {
 	struct ieee80211vap *vap =3D ni->ni_vap;
 	struct ieee80211_tx_ampdu *tap;
-	int ac;
+	int tid;
=20
 	KASSERT(vap->iv_flags_ht & IEEE80211_FHT_HT, ("no HT requested"));
=20
@@ -1198,9 +1198,9 @@
 	ni->ni_htopmode =3D 0;		/* XXX need protection state */
 	ni->ni_htstbc =3D 0;		/* XXX need info */
=20
-	for (ac =3D 0; ac < WME_NUM_AC; ac++) {
-		tap =3D &ni->ni_tx_ampdu[ac];
-		tap->txa_ac =3D ac;
+	for (tid =3D 0; tid < WME_NUM_TID; tid++) {
+		tap =3D &ni->ni_tx_ampdu[tid];
+		tap->txa_tid =3D tid;
 	}
 	/* NB: AMPDU tx/rx governed by IEEE80211_FHT_AMPDU_{TX,RX} */
 	ni->ni_flags |=3D IEEE80211_NODE_HT | IEEE80211_NODE_AMPDU;
@@ -1428,12 +1428,13 @@
  * required channel change is done (e.g. in sta mode when
  * parsing the contents of a beacon frame).
  */
-static void
+static int
 htinfo_update_chw(struct ieee80211_node *ni, int htflags)
 {
 	struct ieee80211com *ic =3D ni->ni_ic;
 	struct ieee80211_channel *c;
 	int chanflags;
+	int ret =3D 0;
=20
 	chanflags =3D (ni->ni_chan->ic_flags &~ IEEE80211_CHAN_HT) | htflags;
 	if (chanflags !=3D ni->ni_chan->ic_flags) {
@@ -1460,11 +1461,13 @@
 			    IEEE80211_IS_CHAN_HT40(c) ? 40 : 20,
 			    c->ic_freq, c->ic_flags);
 			ni->ni_chan =3D c;
+			ret =3D 1;
 		}
 		/* NB: caller responsible for forcing any channel change */
 	}
 	/* update node's tx channel width */
 	ni->ni_chw =3D IEEE80211_IS_CHAN_HT40(ni->ni_chan)? 40 : 20;
+	return (ret);
 }
=20
 /*
@@ -1515,13 +1518,14 @@
  * Parse and update HT-related state extracted from
  * the HT cap and info ie's.
  */
-void
+int
 ieee80211_ht_updateparams(struct ieee80211_node *ni,
 	const uint8_t *htcapie, const uint8_t *htinfoie)
 {
 	struct ieee80211vap *vap =3D ni->ni_vap;
 	const struct ieee80211_ie_htinfo *htinfo;
 	int htflags;
+	int ret =3D 0;
=20
 	ieee80211_parse_htcap(ni, htcapie);
 	if (vap->iv_htcaps & IEEE80211_HTCAP_SMPS)
@@ -1543,13 +1547,16 @@
 		else if (ni->ni_ht2ndchan =3D=3D IEEE80211_HTINFO_2NDCHAN_BELOW)
 			htflags =3D IEEE80211_CHAN_HT40D;
 	}
-	htinfo_update_chw(ni, htflags);
+	if (htinfo_update_chw(ni, htflags))
+		ret =3D 1;
=20
 	if ((htinfo->hi_byte1 & IEEE80211_HTINFO_RIFSMODE_PERM) &&
 	    (vap->iv_flags_ht & IEEE80211_FHT_RIFS))
 		ni->ni_flags |=3D IEEE80211_NODE_RIFS;
 	else
 		ni->ni_flags &=3D ~IEEE80211_NODE_RIFS;
+
+	return (ret);
 }
=20
 /*
@@ -1578,7 +1585,7 @@
 		else if (IEEE80211_IS_CHAN_HT40D(vap->iv_bss->ni_chan))
 			htflags =3D IEEE80211_CHAN_HT40D;
 	}
-	htinfo_update_chw(ni, htflags);
+	(void) htinfo_update_chw(ni, htflags);
 }
=20
 /*
@@ -1678,7 +1685,8 @@
 	struct ieee80211com *ic =3D ni->ni_ic;
=20
 	KASSERT(tap->txa_flags & IEEE80211_AGGR_SETUP,
-	    ("txa_flags 0x%x ac %d", tap->txa_flags, tap->txa_ac));
+	    ("txa_flags 0x%x tid %d ac %d", tap->txa_flags, tap->txa_tid,
+	    TID_TO_WME_AC(tap->txa_tid)));
=20
 	/*
 	 * Stop BA stream if setup so driver has a chance
@@ -1891,7 +1899,7 @@
 	struct ieee80211_tx_ampdu *tap;
 	uint8_t dialogtoken, policy;
 	uint16_t baparamset, batimeout, code;
-	int tid, ac, bufsiz;
+	int tid, bufsiz;
=20
 	dialogtoken =3D frm[2];
 	code =3D LE_READ_2(frm+3);
@@ -1901,8 +1909,7 @@
 	policy =3D MS(baparamset, IEEE80211_BAPS_POLICY);
 	batimeout =3D LE_READ_2(frm+7);
=20
-	ac =3D TID_TO_WME_AC(tid);
-	tap =3D &ni->ni_tx_ampdu[ac];
+	tap =3D &ni->ni_tx_ampdu[tid];
 	if ((tap->txa_flags & IEEE80211_AGGR_XCHGPEND) =3D=3D 0) {
 		IEEE80211_DISCARD_MAC(vap,
 		    IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
@@ -1965,7 +1972,7 @@
 	struct ieee80211_rx_ampdu *rap;
 	struct ieee80211_tx_ampdu *tap;
 	uint16_t baparamset, code;
-	int tid, ac;
+	int tid;
=20
 	baparamset =3D LE_READ_2(frm+2);
 	code =3D LE_READ_2(frm+4);
@@ -1978,8 +1985,7 @@
 	    MS(baparamset, IEEE80211_DELBAPS_INIT), code);
=20
 	if ((baparamset & IEEE80211_DELBAPS_INIT) =3D=3D 0) {
-		ac =3D TID_TO_WME_AC(tid);
-		tap =3D &ni->ni_tx_ampdu[ac];
+		tap =3D &ni->ni_tx_ampdu[tid];
 		ic->ic_addba_stop(ni, tap);
 	} else {
 		rap =3D &ni->ni_rx_ampdu[tid];
@@ -2051,7 +2057,8 @@
 {
 	struct ieee80211vap *vap =3D ni->ni_vap;
=20
-	if (tap->txa_avgpps < vap->iv_ampdu_mintraffic[tap->txa_ac])
+	if (tap->txa_avgpps <
+	    vap->iv_ampdu_mintraffic[TID_TO_WME_AC(tap->txa_tid)])
 		return 0;
 	/* XXX check rssi? */
 	if (tap->txa_attempts >=3D ieee80211_addba_maxtries &&
@@ -2064,8 +2071,9 @@
 		return 0;
 	}
 	IEEE80211_NOTE(vap, IEEE80211_MSG_11N, ni,
-	    "enable AMPDU on %s, avgpps %d pkts %d",
-	    ieee80211_wme_acnames[tap->txa_ac], tap->txa_avgpps, tap->txa_pkts);
+	    "enable AMPDU on tid %d (%s), avgpps %d pkts %d",
+	    tap->txa_tid, ieee80211_wme_acnames[TID_TO_WME_AC(tap->txa_tid)],
+	    tap->txa_avgpps, tap->txa_pkts);
 	return 1;
 }
=20
@@ -2092,7 +2100,7 @@
 	tap->txa_flags &=3D ~IEEE80211_AGGR_NAK;
=20
 	dialogtoken =3D (tokens+1) % 63;		/* XXX */
-	tid =3D WME_AC_TO_TID(tap->txa_ac);
+	tid =3D tap->txa_tid;
 	tap->txa_start =3D ni->ni_txseqs[tid];
=20
 	args[0] =3D dialogtoken;
@@ -2106,8 +2114,8 @@
 	if (!ic->ic_addba_request(ni, tap, dialogtoken, args[2], args[3])) {
 		/* unable to setup state, don't make request */
 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
-		    ni, "%s: could not setup BA stream for AC %d",
-		    __func__, tap->txa_ac);
+		    ni, "%s: could not setup BA stream for TID %d AC %d",
+		    __func__, tap->txa_tid, TID_TO_WME_AC(tap->txa_tid));
 		/* defer next try so we don't slam the driver with requests */
 		tap->txa_attempts =3D ieee80211_addba_maxtries;
 		/* NB: check in case driver wants to override */
@@ -2140,20 +2148,20 @@
 	tap->txa_flags &=3D ~IEEE80211_AGGR_BARPEND;
 	if (IEEE80211_AMPDU_RUNNING(tap)) {
 		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
-		    ni, "%s: stop BA stream for AC %d (reason %d)",
-		    __func__, tap->txa_ac, reason);
+		    ni, "%s: stop BA stream for TID %d (reason %d)",
+		    __func__, tap->txa_tid, reason);
 		vap->iv_stats.is_ampdu_stop++;
=20
 		ic->ic_addba_stop(ni, tap);
-		args[0] =3D WME_AC_TO_TID(tap->txa_ac);
+		args[0] =3D tap->txa_tid;
 		args[1] =3D IEEE80211_DELBAPS_INIT;
 		args[2] =3D reason;			/* XXX reason code */
 		ic->ic_send_action(ni, IEEE80211_ACTION_CAT_BA,
 			IEEE80211_ACTION_BA_DELBA, args);
 	} else {
 		IEEE80211_NOTE(vap, IEEE80211_MSG_ACTION | IEEE80211_MSG_11N,
-		    ni, "%s: BA stream for AC %d not running (reason %d)",
-		    __func__, tap->txa_ac, reason);
+		    ni, "%s: BA stream for TID %d not running (reason %d)",
+		    __func__, tap->txa_tid, reason);
 		vap->iv_stats.is_ampdu_stop_failed++;
 	}
 }
@@ -2169,16 +2177,19 @@
=20
 	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
 	    ni, "%s: tid %u flags 0x%x attempts %d", __func__,
-	    tap->txa_ac, tap->txa_flags, tap->txa_attempts);
+	    tap->txa_tid, tap->txa_flags, tap->txa_attempts);
=20
 	/* guard against race with bar_tx_complete */
 	if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) =3D=3D 0)
 		return;
 	/* XXX ? */
-	if (tap->txa_attempts >=3D ieee80211_bar_maxtries)
+	if (tap->txa_attempts >=3D ieee80211_bar_maxtries) {
+		ni->ni_vap->iv_stats.is_ampdu_bar_tx_fail++;
 		ieee80211_ampdu_stop(ni, tap, IEEE80211_REASON_TIMEOUT);
-	else
+	} else {
+		ni->ni_vap->iv_stats.is_ampdu_bar_tx_retry++;
 		ieee80211_send_bar(ni, tap, tap->txa_seqpending);
+	}
 }
=20
 static void
@@ -2200,9 +2211,10 @@
=20
 	IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_11N,
 	    ni, "%s: tid %u flags 0x%x pending %d status %d",
-	    __func__, tap->txa_ac, tap->txa_flags,
+	    __func__, tap->txa_tid, tap->txa_flags,
 	    callout_pending(&tap->txa_timer), status);
=20
+	ni->ni_vap->iv_stats.is_ampdu_bar_tx++;
 	/* XXX locking */
 	if ((tap->txa_flags & IEEE80211_AGGR_BARPEND) &&
 	    callout_pending(&tap->txa_timer)) {
@@ -2226,7 +2238,7 @@
 		    tap->txa_start,
 		    IEEE80211_SEQ_ADD(tap->txa_start, tap->txa_wnd-1),
 		    tap->txa_qframes, tap->txa_seqpending,
-		    WME_AC_TO_TID(tap->txa_ac));
+		    tap->txa_tid);
=20
 		/* NB: timer already stopped in bar_tx_complete */
 		tap->txa_start =3D tap->txa_seqpending;
@@ -2281,7 +2293,7 @@
 	IEEE80211_ADDR_COPY(bar->i_ra, ni->ni_macaddr);
 	IEEE80211_ADDR_COPY(bar->i_ta, vap->iv_myaddr);
=20
-	tid =3D WME_AC_TO_TID(tap->txa_ac);
+	tid =3D tap->txa_tid;
 	barctl 	=3D (tap->txa_flags & IEEE80211_AGGR_IMMEDIATE ?
 			0 : IEEE80211_BAR_NOACK)
 		| IEEE80211_BAR_COMP
@@ -2318,6 +2330,7 @@
 	if (ret !=3D 0) {
 		/* xmit failed, clear state flag */
 		tap->txa_flags &=3D ~IEEE80211_AGGR_BARPEND;
+		vap->iv_stats.is_ampdu_bar_tx_fail++;
 		return ret;
 	}
 	/* XXX hack against tx complete happening before timer is started */
@@ -2325,6 +2338,7 @@
 		bar_start_timer(tap);
 	return 0;
 bad:
+	vap->iv_stats.is_ampdu_bar_tx_fail++;
 	ieee80211_free_node(ni);
 	return ret;
 #undef senderr
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_ht.h
--- a/head/sys/net80211/ieee80211_ht.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_ht.h	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/net80211/ieee80211_ht.h 219456 2011-03-10 18:17:24Z =
bschmidt $
+ * $FreeBSD: head/sys/net80211/ieee80211_ht.h 234324 2012-04-15 20:29:39Z =
adrian $
  */
 #ifndef _NET80211_IEEE80211_HT_H_
 #define _NET80211_IEEE80211_HT_H_
@@ -44,7 +44,7 @@
 #define	IEEE80211_AGGR_SETUP		0x0008	/* deferred state setup */
 #define	IEEE80211_AGGR_NAK		0x0010	/* peer NAK'd ADDBA request */
 #define	IEEE80211_AGGR_BARPEND		0x0020	/* BAR response pending */
-	uint8_t		txa_ac;
+	uint8_t		txa_tid;
 	uint8_t		txa_token;	/* dialog token */
 	int		txa_lastsample;	/* ticks @ last traffic sample */
 	int		txa_pkts;	/* packets over last sample interval */
@@ -184,7 +184,7 @@
 void	ieee80211_ht_timeout(struct ieee80211com *);
 void	ieee80211_parse_htcap(struct ieee80211_node *, const uint8_t *);
 void	ieee80211_parse_htinfo(struct ieee80211_node *, const uint8_t *);
-void	ieee80211_ht_updateparams(struct ieee80211_node *, const uint8_t *,
+int	ieee80211_ht_updateparams(struct ieee80211_node *, const uint8_t *,
 		const uint8_t *);
 void	ieee80211_ht_updatehtcap(struct ieee80211_node *, const uint8_t *);
 int	ieee80211_ampdu_request(struct ieee80211_node *,
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_ioctl.h
--- a/head/sys/net80211/ieee80211_ioctl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_ioctl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/net80211/ieee80211_ioctl.h 232244 2012-02-28 04:05:3=
5Z adrian $
+ * $FreeBSD: head/sys/net80211/ieee80211_ioctl.h 234018 2012-04-08 04:51:2=
5Z adrian $
  */
 #ifndef _NET80211_IEEE80211_IOCTL_H_
 #define _NET80211_IEEE80211_IOCTL_H_
@@ -242,8 +242,11 @@
 	uint32_t	is_rx_badalign;		/* dropped 'cuz misaligned */
 	uint32_t	is_hwmp_proxy;		/* PREP for proxy route */
 	uint32_t	is_beacon_bad;		/* Number of bad beacons */
-=09
-	uint32_t	is_spare[10];
+	uint32_t	is_ampdu_bar_tx;	/* A-MPDU BAR frames TXed */
+	uint32_t	is_ampdu_bar_tx_retry;	/* A-MPDU BAR frames TX rtry */
+	uint32_t	is_ampdu_bar_tx_fail;	/* A-MPDU BAR frames TX fail */
+
+	uint32_t	is_spare[7];
 };
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_node.c
--- a/head/sys/net80211/ieee80211_node.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_node.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_node.c 220935 2011-04-22 0=
0:44:27Z adrian $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_node.c 233452 2012-03-25 0=
3:11:57Z adrian $");
=20
 #include "opt_wlan.h"
=20
@@ -685,6 +685,14 @@
 	ieee80211_runtask(ic, &ic->ic_chan_task);
 }
=20
+void
+ieee80211_update_chw(struct ieee80211com *ic)
+{
+
+	ieee80211_setupcurchan(ic, ic->ic_curchan);
+	ieee80211_runtask(ic, &ic->ic_chw_task);
+}
+
 /*
  * Join the specified IBSS/BSS network.  The node is assumed to
  * be passed in with a held reference.
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_node.h
--- a/head/sys/net80211/ieee80211_node.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_node.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/net80211/ieee80211_node.h 231939 2012-02-20 15:05:21=
Z ray $
+ * $FreeBSD: head/sys/net80211/ieee80211_node.h 234324 2012-04-15 20:29:39=
Z adrian $
  */
 #ifndef _NET80211_IEEE80211_NODE_H_
 #define _NET80211_IEEE80211_NODE_H_
@@ -214,7 +214,7 @@
 	uint8_t			ni_htstbc;	/* HT */
 	uint8_t			ni_chw;		/* negotiated channel width */
 	struct ieee80211_htrateset ni_htrates;	/* negotiated ht rate set */
-	struct ieee80211_tx_ampdu ni_tx_ampdu[WME_NUM_AC];
+	struct ieee80211_tx_ampdu ni_tx_ampdu[WME_NUM_TID];
 	struct ieee80211_rx_ampdu ni_rx_ampdu[WME_NUM_TID];
=20
 	/* others */
@@ -324,6 +324,7 @@
 void	ieee80211_setupcurchan(struct ieee80211com *,
 	    struct ieee80211_channel *);
 void	ieee80211_setcurchan(struct ieee80211com *, struct ieee80211_channel =
*);
+void	ieee80211_update_chw(struct ieee80211com *);
 int	ieee80211_ibss_merge(struct ieee80211_node *);
 struct ieee80211_scan_entry;
 int	ieee80211_sta_join(struct ieee80211vap *, struct ieee80211_channel *,
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_output.c
--- a/head/sys/net80211/ieee80211_output.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_output.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_output.c 232480 2012-03-04=
 05:52:26Z adrian $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_output.c 234324 2012-04-15=
 20:29:39Z adrian $");
=20
 #include "opt_inet.h"
 #include "opt_inet6.h"
@@ -323,8 +323,8 @@
 		if ((ni->ni_flags & IEEE80211_NODE_AMPDU_TX) &&
 		    (vap->iv_flags_ht & IEEE80211_FHT_AMPDU_TX) &&
 		    (m->m_flags & M_EAPOL) =3D=3D 0) {
-			const int ac =3D M_WME_GETAC(m);
-			struct ieee80211_tx_ampdu *tap =3D &ni->ni_tx_ampdu[ac];
+			int tid =3D WME_AC_TO_TID(M_WME_GETAC(m));
+			struct ieee80211_tx_ampdu *tap =3D &ni->ni_tx_ampdu[tid];
=20
 			ieee80211_txampdu_count_packet(tap);
 			if (IEEE80211_AMPDU_RUNNING(tap)) {
@@ -589,7 +589,7 @@
 	}
 	*(uint16_t *)&wh->i_dur[0] =3D 0;
=20
-	tap =3D &ni->ni_tx_ampdu[TID_TO_WME_AC(tid)];
+	tap =3D &ni->ni_tx_ampdu[tid];
 	if (tid !=3D IEEE80211_NONQOS_TID && IEEE80211_AMPDU_RUNNING(tap))
 		m->m_flags |=3D M_AMPDU_MPDU;
 	else {
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_proto.c
--- a/head/sys/net80211/ieee80211_proto.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_proto.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_proto.c 232096 2012-02-24 =
05:39:00Z adrian $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_proto.c 233452 2012-03-25 =
03:11:57Z adrian $");
=20
 /*
  * IEEE 802.11 protocol support.
@@ -105,6 +105,7 @@
 static void update_mcast(void *, int);
 static void update_promisc(void *, int);
 static void update_channel(void *, int);
+static void update_chw(void *, int);
 static void ieee80211_newstate_cb(void *, int);
 static int ieee80211_new_state_locked(struct ieee80211vap *,
 	enum ieee80211_state, int);
@@ -144,6 +145,7 @@
 	TASK_INIT(&ic->ic_promisc_task, 0, update_promisc, ic);
 	TASK_INIT(&ic->ic_chan_task, 0, update_channel, ic);
 	TASK_INIT(&ic->ic_bmiss_task, 0, beacon_miss, ic);
+	TASK_INIT(&ic->ic_chw_task, 0, update_chw, ic);
=20
 	ic->ic_wme.wme_hipri_switch_hysteresis =3D
 		AGGRESSIVE_MODE_SWITCH_HYSTERESIS;
@@ -1147,6 +1149,17 @@
 	ieee80211_radiotap_chan_change(ic);
 }
=20
+static void
+update_chw(void *arg, int npending)
+{
+	struct ieee80211com *ic =3D arg;
+
+	/*
+	 * XXX should we defer the channel width _config_ update until now?
+	 */
+	ic->ic_update_chw(ic);
+}
+
 /*
  * Block until the parent is in a known state.  This is
  * used after any operations that dispatch a task (e.g.
@@ -1161,6 +1174,7 @@
 	ieee80211_draintask(ic, &ic->ic_promisc_task);
 	ieee80211_draintask(ic, &ic->ic_chan_task);
 	ieee80211_draintask(ic, &ic->ic_bmiss_task);
+	ieee80211_draintask(ic, &ic->ic_chw_task);
 	taskqueue_unblock(ic->ic_tq);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_regdomain.c
--- a/head/sys/net80211/ieee80211_regdomain.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_regdomain.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_regdomain.c 188782 2009-02=
-19 05:21:54Z sam $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_regdomain.c 233845 2012-04=
-03 17:48:42Z bschmidt $");
=20
 /*
  * IEEE 802.11 regdomain support.
@@ -105,7 +105,12 @@
 	c->ic_freq =3D ieee80211_ieee2mhz(ieee, flags);
 	c->ic_ieee =3D ieee;
 	c->ic_flags =3D flags;
-	c->ic_extieee =3D 0;
+	if (flags & IEEE80211_CHAN_HT40U)
+		c->ic_extieee =3D ieee + 4;
+	else if (flags & IEEE80211_CHAN_HT40D)
+		c->ic_extieee =3D ieee - 4;
+	else
+		c->ic_extieee =3D 0;
 }
=20
 /*
@@ -123,7 +128,8 @@
 	/* XXX just do something for now */
 	ic->ic_nchans =3D 0;
 	if (isset(bands, IEEE80211_MODE_11B) ||
-	    isset(bands, IEEE80211_MODE_11G)) {
+	    isset(bands, IEEE80211_MODE_11G) ||
+	    isset(bands, IEEE80211_MODE_11NG)) {
 		int maxchan =3D 11;
 		if (rd !=3D NULL && rd->ecm)
 			maxchan =3D 14;
@@ -132,15 +138,67 @@
 				addchan(ic, i, IEEE80211_CHAN_B);
 			if (isset(bands, IEEE80211_MODE_11G))
 				addchan(ic, i, IEEE80211_CHAN_G);
+			if (isset(bands, IEEE80211_MODE_11NG)) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_G | IEEE80211_CHAN_HT20);
+			}
+			if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) =3D=3D 0)
+				continue;
+			if (i <=3D 7) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U);
+				addchan(ic, i + 4,
+				    IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D);
+			}
 		}
 	}
-	if (isset(bands, IEEE80211_MODE_11A)) {
-		for (i =3D 36; i <=3D 64; i +=3D 4)
+	if (isset(bands, IEEE80211_MODE_11A) ||
+	    isset(bands, IEEE80211_MODE_11NA)) {
+		for (i =3D 36; i <=3D 64; i +=3D 4) {
 			addchan(ic, i, IEEE80211_CHAN_A);
-		for (i =3D 100; i <=3D 140; i +=3D 4)
+			if (isset(bands, IEEE80211_MODE_11NA)) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT20);
+			}
+			if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) =3D=3D 0)
+				continue;
+			if ((i % 8) =3D=3D 4) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U);
+				addchan(ic, i + 4,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D);
+			}
+		}
+		for (i =3D 100; i <=3D 140; i +=3D 4) {
 			addchan(ic, i, IEEE80211_CHAN_A);
-		for (i =3D 149; i <=3D 161; i +=3D 4)
+			if (isset(bands, IEEE80211_MODE_11NA)) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT20);
+			}
+			if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) =3D=3D 0)
+				continue;
+			if ((i % 8) =3D=3D 4 && i !=3D 140) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U);
+				addchan(ic, i + 4,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D);
+			}
+		}
+		for (i =3D 149; i <=3D 161; i +=3D 4) {
 			addchan(ic, i, IEEE80211_CHAN_A);
+			if (isset(bands, IEEE80211_MODE_11NA)) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT20);
+			}
+			if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) =3D=3D 0)
+				continue;
+			if ((i % 8) =3D=3D 5) {
+				addchan(ic, i,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U);
+				addchan(ic, i + 4,
+				    IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D);
+			}
+		}
 	}
 	if (rd !=3D NULL)
 		ic->ic_regdomain =3D *rd;
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_sta.c
--- a/head/sys/net80211/ieee80211_sta.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_sta.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
=20
 #include <sys/cdefs.h>
 #ifdef __FreeBSD__
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_sta.c 232270 2012-02-28 21=
:43:29Z adrian $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_sta.c 233452 2012-03-25 03=
:11:57Z adrian $");
 #endif
=20
 /*
@@ -1285,6 +1285,7 @@
 	uint8_t *frm, *efrm;
 	uint8_t *rates, *xrates, *wme, *htcap, *htinfo;
 	uint8_t rate;
+	int ht_state_change =3D 0;
=20
 	wh =3D mtod(m0, struct ieee80211_frame *);
 	frm =3D (uint8_t *)&wh[1];
@@ -1372,9 +1373,10 @@
 #endif
 			if (scan.htcap !=3D NULL && scan.htinfo !=3D NULL &&
 			    (vap->iv_flags_ht & IEEE80211_FHT_HT)) {
-				ieee80211_ht_updateparams(ni,
-				    scan.htcap, scan.htinfo);
 				/* XXX state changes? */
+				if (ieee80211_ht_updateparams(ni,
+				    scan.htcap, scan.htinfo))
+					ht_state_change =3D 1;
 			}
 			if (scan.quiet)
 				ic->ic_set_quiet(ni, scan.quiet);
@@ -1441,6 +1443,13 @@
 #endif
 				ieee80211_bg_scan(vap, 0);
 			}
+
+			/*
+			 * If we've had a channel width change (eg HT20<->HT40)
+			 * then schedule a delayed driver notification.
+			 */
+			if (ht_state_change)
+				ieee80211_update_chw(ic);
 			return;
 		}
 		/*
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_superg.c
--- a/head/sys/net80211/ieee80211_superg.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_superg.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_superg.c 193115 2009-05-30=
 20:11:23Z sam $");
+__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_superg.c 234324 2012-04-15=
 20:29:39Z adrian $");
=20
 #include "opt_wlan.h"
=20
@@ -562,9 +562,11 @@
 	IEEE80211_LOCK(ic);
 	head =3D sq->head;
 	while ((m =3D sq->head) !=3D NULL && M_AGE_GET(m) < quanta) {
+		int tid =3D WME_AC_TO_TID(M_WME_GETAC(m));
+
 		/* clear tap ref to frame */
 		ni =3D (struct ieee80211_node *) m->m_pkthdr.rcvif;
-		tap =3D &ni->ni_tx_ampdu[M_WME_GETAC(m)];
+		tap =3D &ni->ni_tx_ampdu[tid];
 		KASSERT(tap->txa_private =3D=3D m, ("staging queue empty"));
 		tap->txa_private =3D NULL;
=20
@@ -670,7 +672,7 @@
 	 *     be aggregated with other types of frames when encryption is on?
 	 */
 	IEEE80211_LOCK(ic);
-	tap =3D &ni->ni_tx_ampdu[pri];
+	tap =3D &ni->ni_tx_ampdu[WME_AC_TO_TID(pri)];
 	mstaged =3D tap->txa_private;		/* NB: we reuse AMPDU state */
 	ieee80211_txampdu_count_packet(tap);
=20
@@ -783,12 +785,14 @@
 	struct ieee80211_superg *sg =3D ic->ic_superg;
 	struct ieee80211_tx_ampdu *tap;
 	struct mbuf *m, *head;
-	int ac;
+	int tid;
=20
 	IEEE80211_LOCK(ic);
 	head =3D NULL;
-	for (ac =3D 0; ac < WME_NUM_AC; ac++) {
-		tap =3D &ni->ni_tx_ampdu[ac];
+	for (tid =3D 0; tid < WME_NUM_TID; tid++) {
+		int ac =3D TID_TO_WME_AC(tid);
+
+		tap =3D &ni->ni_tx_ampdu[tid];
 		m =3D tap->txa_private;
 		if (m !=3D NULL) {
 			tap->txa_private =3D NULL;
diff -r 428842767fa6 -r f2935497fa04 head/sys/net80211/ieee80211_var.h
--- a/head/sys/net80211/ieee80211_var.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/net80211/ieee80211_var.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/net80211/ieee80211_var.h 228621 2011-12-17 10:23:17Z=
 bschmidt $
+ * $FreeBSD: head/sys/net80211/ieee80211_var.h 233452 2012-03-25 03:11:57Z=
 adrian $
  */
 #ifndef _NET80211_IEEE80211_VAR_H_
 #define _NET80211_IEEE80211_VAR_H_
@@ -130,6 +130,7 @@
 	struct task		ic_mcast_task;	/* deferred mcast update */
 	struct task		ic_chan_task;	/* deferred channel change */
 	struct task		ic_bmiss_task;	/* deferred beacon miss hndlr */
+	struct task		ic_chw_task;	/* deferred HT CHW update */
=20
 	uint32_t		ic_flags;	/* state flags */
 	uint32_t		ic_flags_ext;	/* extended state flags */
@@ -322,6 +323,10 @@
 				    int batimeout, int baseqctl);
 	void			(*ic_ampdu_rx_stop)(struct ieee80211_node *,
 				    struct ieee80211_rx_ampdu *);
+
+	/* The channel width has changed (20<->2040) */
+	void			(*ic_update_chw)(struct ieee80211com *);
+
 	uint64_t		ic_spare[7];
 };
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/netgraph/bluetooth/drivers/ub=
t/ng_ubt.c
--- a/head/sys/netgraph/bluetooth/drivers/ubt/ng_ubt.c	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/sys/netgraph/bluetooth/drivers/ubt/ng_ubt.c	Tue Apr 17 11:51:51 =
2012 +0300
@@ -28,7 +28,7 @@
  * SUCH DAMAGE.
  *
  * $Id: ng_ubt.c,v 1.16 2003/10/10 19:15:06 max Exp $
- * $FreeBSD: head/sys/netgraph/bluetooth/drivers/ubt/ng_ubt.c 223486 2011-=
06-24 02:30:02Z hselasky $
+ * $FreeBSD: head/sys/netgraph/bluetooth/drivers/ubt/ng_ubt.c 233774 2012-=
04-02 10:50:42Z hselasky $
  */
=20
 /*
@@ -726,7 +726,7 @@
 			actlen);
=20
 		/* Validate packet and send it up the stack */
-		if (m->m_pkthdr.len < sizeof(*hdr)) {
+		if (m->m_pkthdr.len < (int)sizeof(*hdr)) {
 			UBT_INFO(sc, "HCI event packet is too short\n");
=20
 			UBT_STAT_IERROR(sc);
@@ -788,8 +788,8 @@
 	struct mbuf		*m;
 	ng_hci_acldata_pkt_t	*hdr;
 	struct usb_page_cache	*pc;
-	uint16_t		len;
-	int			actlen;
+	int len;
+	int actlen;
=20
 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
=20
@@ -826,7 +826,7 @@
 			actlen);
=20
 		/* Validate packet and send it up the stack */
-		if (m->m_pkthdr.len < sizeof(*hdr)) {
+		if (m->m_pkthdr.len < (int)sizeof(*hdr)) {
 			UBT_INFO(sc, "HCI ACL packet is too short\n");
=20
 			UBT_STAT_IERROR(sc);
@@ -835,7 +835,7 @@
=20
 		hdr =3D mtod(m, ng_hci_acldata_pkt_t *);
 		len =3D le16toh(hdr->length);
-		if (len !=3D (m->m_pkthdr.len - sizeof(*hdr))) {
+		if (len !=3D (int)(m->m_pkthdr.len - sizeof(*hdr))) {
 			UBT_ERR(sc, "Invalid ACL packet size, length=3D%d, " \
 				"pktlen=3D%d\n", len, m->m_pkthdr.len);
=20
@@ -1650,7 +1650,7 @@
 	/* Process HCI frame */
 	switch (*mtod(m, uint8_t *)) {	/* XXX call m_pullup ? */
 	case NG_HCI_CMD_PKT:
-		if (m->m_pkthdr.len - 1 > UBT_CTRL_BUFFER_SIZE)
+		if (m->m_pkthdr.len - 1 > (int)UBT_CTRL_BUFFER_SIZE)
 			panic("HCI command frame size is too big! " \
 				"buffer size=3D%zd, packet len=3D%d\n",
 				UBT_CTRL_BUFFER_SIZE, m->m_pkthdr.len);
diff -r 428842767fa6 -r f2935497fa04 head/sys/netgraph/ng_source.c
--- a/head/sys/netgraph/ng_source.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netgraph/ng_source.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netgraph/ng_source.c 220768 2011-04-18 09:12:=
27Z glebius $");
+__FBSDID("$FreeBSD: head/sys/netgraph/ng_source.c 234341 2012-04-16 13:41:=
46Z zec $");
=20
 /*
  * This node is used for high speed packet geneneration.  It queues
@@ -68,7 +68,6 @@
 #include <sys/syslog.h>
 #include <net/if.h>
 #include <net/if_var.h>
-#include <net/vnet.h>
 #include <netgraph/ng_message.h>
 #include <netgraph/netgraph.h>
 #include <netgraph/ng_parse.h>
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/in.c
--- a/head/sys/netinet/in.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/in.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/in.c 232054 2012-02-23 18:21:37Z kmac=
y $");
+__FBSDID("$FreeBSD: head/sys/netinet/in.c 234087 2012-04-10 06:52:39Z gleb=
ius $");
=20
 #include "opt_mpath.h"
=20
@@ -1279,7 +1279,7 @@
 {
 	struct in_llentry *lle;
=20
-	lle =3D malloc(sizeof(struct in_llentry), M_LLTABLE, M_DONTWAIT | M_ZERO);
+	lle =3D malloc(sizeof(struct in_llentry), M_LLTABLE, M_NOWAIT | M_ZERO);
 	if (lle =3D=3D NULL)		/* NB: caller generates msg */
 		return NULL;
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/ip_carp.c
--- a/head/sys/netinet/ip_carp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/ip_carp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/ip_carp.c 231201 2012-02-08 13:39:38Z=
 glebius $");
+__FBSDID("$FreeBSD: head/sys/netinet/ip_carp.c 234130 2012-04-11 12:26:30Z=
 glebius $");
=20
 #include "opt_bpf.h"
 #include "opt_inet.h"
@@ -223,6 +223,13 @@
 #define	CIF_LOCK_ASSERT(cif)	mtx_assert(&(cif)->cif_mtx, MA_OWNED)
 #define	CIF_LOCK(cif)		mtx_lock(&(cif)->cif_mtx)
 #define	CIF_UNLOCK(cif)		mtx_unlock(&(cif)->cif_mtx)
+#define	CIF_FREE(cif)	do {				\
+		CIF_LOCK_ASSERT(cif);			\
+		if (TAILQ_EMPTY(&(cif)->cif_vrs))	\
+			carp_free_if(cif);		\
+		else					\
+			CIF_UNLOCK(cif);		\
+} while (0)
=20
 #define	CARP_LOG(...)	do {				\
 	if (carp_log > 0)				\
@@ -257,6 +264,7 @@
 static void	carp_input_c(struct mbuf *, struct carp_header *, sa_family_t);
 static struct carp_softc
 		*carp_alloc(struct ifnet *);
+static void	carp_detach_locked(struct ifaddr *);
 static void	carp_destroy(struct carp_softc *);
 static struct carp_if
 		*carp_alloc_if(struct ifnet *);
@@ -1214,12 +1222,13 @@
  * Setup multicast structures.
  */
 static int
-carp_multicast_setup(struct carp_softc *sc, sa_family_t sa)
+carp_multicast_setup(struct carp_if *cif, sa_family_t sa)
 {
-	struct ifnet *ifp =3D sc->sc_carpdev;
-	struct carp_if *cif =3D ifp->if_carp;
+	struct ifnet *ifp =3D cif->cif_ifp;
 	int error =3D 0;
=20
+	CIF_LOCK_ASSERT(cif);
+
 	switch (sa) {
 #ifdef INET
 	case AF_INET:
@@ -1232,7 +1241,9 @@
=20
 		imo->imo_membership =3D (struct in_multi **)malloc(
 		    (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_CARP,
-		    M_WAITOK);
+		    M_NOWAIT);
+		if (imo->imo_membership =3D=3D NULL)
+			return (ENOMEM);
 		imo->imo_mfilters =3D NULL;
 		imo->imo_max_memberships =3D IP_MIN_MEMBERSHIPS;
 		imo->imo_multicast_vif =3D -1;
@@ -1262,7 +1273,9 @@
=20
 		im6o->im6o_membership =3D (struct in6_multi **)malloc(
 		    (sizeof(struct in6_multi *) * IPV6_MIN_MEMBERSHIPS), M_CARP,
-		    M_ZERO|M_WAITOK);
+		    M_ZERO | M_NOWAIT);
+		if (im6o->im6o_membership =3D=3D NULL)
+			return (ENOMEM);
 		im6o->im6o_mfilters =3D NULL;
 		im6o->im6o_max_memberships =3D IPV6_MIN_MEMBERSHIPS;
 		im6o->im6o_multicast_hlim =3D CARP_DFLTTL;
@@ -1316,15 +1329,14 @@
  * Free multicast structures.
  */
 static void
-carp_multicast_cleanup(struct carp_softc *sc, sa_family_t sa)
+carp_multicast_cleanup(struct carp_if *cif, sa_family_t sa)
 {
-	struct ifnet *ifp =3D sc->sc_carpdev;
-	struct carp_if *cif =3D ifp->if_carp;
=20
+	CIF_LOCK_ASSERT(cif);
 	switch (sa) {
 #ifdef INET
 	case AF_INET:
-		if (sc->sc_naddrs =3D=3D 0) {
+		if (cif->cif_naddrs =3D=3D 0) {
 			struct ip_moptions *imo =3D &cif->cif_imo;
=20
 			in_leavegroup(imo->imo_membership[0], NULL);
@@ -1338,7 +1350,7 @@
 #endif
 #ifdef INET6
 	case AF_INET6:
-		if (sc->sc_naddrs6 =3D=3D 0) {
+		if (cif->cif_naddrs6 =3D=3D 0) {
 			struct ip6_moptions *im6o =3D &cif->cif_im6o;
=20
 			in6_mc_leave(im6o->im6o_membership[0], NULL);
@@ -1384,6 +1396,7 @@
 	/* Set the source MAC address to the Virtual Router MAC Address. */
 	switch (ifp->if_type) {
 	case IFT_ETHER:
+	case IFT_BRIDGE:
 	case IFT_L2VLAN: {
 			struct ether_header *eh;
=20
@@ -1495,12 +1508,9 @@
 	struct ifnet *ifp =3D sc->sc_carpdev;
 	struct carp_if *cif =3D ifp->if_carp;
=20
-	CIF_LOCK(cif);
+	CIF_LOCK_ASSERT(cif);
+
 	TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
-	if (TAILQ_EMPTY(&cif->cif_vrs))
-		carp_free_if(cif);
-	else
-		CIF_UNLOCK(cif);
=20
 	mtx_lock(&carp_mtx);
 	LIST_REMOVE(sc, sc_next);
@@ -1604,6 +1614,7 @@
 	switch (ifp->if_type) {
 	case IFT_ETHER:
 	case IFT_L2VLAN:
+	case IFT_BRIDGE:
 	case IFT_FDDI:
 	case IFT_ISO88025:
 		break;
@@ -1775,6 +1786,7 @@
 carp_attach(struct ifaddr *ifa, int vhid)
 {
 	struct ifnet *ifp =3D ifa->ifa_ifp;
+	struct carp_if *cif =3D ifp->if_carp;
 	struct carp_softc *sc;
 	int index, error;
=20
@@ -1793,43 +1805,51 @@
 		return (EPROTOTYPE);
 	}
=20
-	CIF_LOCK(ifp->if_carp);
+	CIF_LOCK(cif);
 	IFNET_FOREACH_CARP(ifp, sc)
 		if (sc->sc_vhid =3D=3D vhid)
 			break;
-	CIF_UNLOCK(ifp->if_carp);
-	if (sc =3D=3D NULL)
+	if (sc =3D=3D NULL) {
+		CIF_UNLOCK(cif);
 		return (ENOENT);
+	}
=20
 	if (ifa->ifa_carp) {
 		if (ifa->ifa_carp->sc_vhid !=3D vhid)
-			carp_detach(ifa);
-		else
+			carp_detach_locked(ifa);
+		else {
+			CIF_UNLOCK(cif);
 			return (0);
+		}
 	}
=20
-	error =3D carp_multicast_setup(sc, ifa->ifa_addr->sa_family);
-	if (error)
+	error =3D carp_multicast_setup(cif, ifa->ifa_addr->sa_family);
+	if (error) {
+		CIF_FREE(cif);
 		return (error);
+	}
=20
 	CARP_LOCK(sc);
 	index =3D sc->sc_naddrs + sc->sc_naddrs6 + 1;
 	if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
 		if ((error =3D carp_grow_ifas(sc)) !=3D 0) {
-			carp_multicast_cleanup(sc,
+			carp_multicast_cleanup(cif,
 			    ifa->ifa_addr->sa_family);
 			CARP_UNLOCK(sc);
+			CIF_FREE(cif);
 			return (error);
 		}
=20
 	switch (ifa->ifa_addr->sa_family) {
 #ifdef INET
 	case AF_INET:
+		cif->cif_naddrs++;
 		sc->sc_naddrs++;
 		break;
 #endif
 #ifdef INET6
 	case AF_INET6:
+		cif->cif_naddrs6++;
 		sc->sc_naddrs6++;
 		break;
 #endif
@@ -1843,6 +1863,7 @@
 	carp_sc_state(sc);
=20
 	CARP_UNLOCK(sc);
+	CIF_UNLOCK(cif);
=20
 	return (0);
 }
@@ -1850,11 +1871,25 @@
 void
 carp_detach(struct ifaddr *ifa)
 {
+	struct ifnet *ifp =3D ifa->ifa_ifp;
+	struct carp_if *cif =3D ifp->if_carp;
+
+	CIF_LOCK(cif);
+	carp_detach_locked(ifa);
+	CIF_FREE(cif);
+}
+
+static void
+carp_detach_locked(struct ifaddr *ifa)
+{
+	struct ifnet *ifp =3D ifa->ifa_ifp;
+	struct carp_if *cif =3D ifp->if_carp;
 	struct carp_softc *sc =3D ifa->ifa_carp;
 	int i, index;
=20
 	KASSERT(sc !=3D NULL, ("%s: %p not attached", __func__, ifa));
=20
+	CIF_LOCK_ASSERT(cif);
 	CARP_LOCK(sc);
=20
 	/* Shift array. */
@@ -1870,18 +1905,20 @@
 	switch (ifa->ifa_addr->sa_family) {
 #ifdef INET
 	case AF_INET:
+		cif->cif_naddrs--;
 		sc->sc_naddrs--;
 		break;
 #endif
 #ifdef INET6
 	case AF_INET6:
+		cif->cif_naddrs6--;
 		sc->sc_naddrs6--;
 		break;
 #endif
 	}
=20
 	carp_ifa_delroute(ifa);
-	carp_multicast_cleanup(sc, ifa->ifa_addr->sa_family);
+	carp_multicast_cleanup(cif, ifa->ifa_addr->sa_family);
=20
 	ifa->ifa_carp =3D NULL;
 	ifa_free(ifa);
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/ip_fw.h
--- a/head/sys/netinet/ip_fw.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/ip_fw.h	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/netinet/ip_fw.h 232865 2012-03-12 14:07:57Z melifaro=
 $
+ * $FreeBSD: head/sys/netinet/ip_fw.h 233478 2012-03-25 20:37:59Z melifaro=
 $
  */
=20
 #ifndef _IPFW2_H
@@ -39,7 +39,8 @@
 /*
  * Default number of ipfw tables.
  */
-#define	IPFW_TABLES_MAX		128
+#define	IPFW_TABLES_MAX		65535
+#define	IPFW_TABLES_DEFAULT	128
=20
 /*
  * Most commands (queue, pipe, tag, untag, limit...) can have a 16-bit
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/ipfw/ip_fw2.c
--- a/head/sys/netinet/ipfw/ip_fw2.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/ipfw/ip_fw2.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw2.c 232868 2012-03-12 15:41=
:36Z melifaro $");
+__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw2.c 233478 2012-03-25 20:37=
:59Z melifaro $");
=20
 /*
  * The FreeBSD IP packet firewall, main file
@@ -116,8 +116,9 @@
 VNET_DEFINE(int, autoinc_step);
 VNET_DEFINE(int, fw_one_pass) =3D 1;
=20
+VNET_DEFINE(unsigned int, fw_tables_max);
 /* Use 128 tables by default */
-int fw_tables_max =3D IPFW_TABLES_MAX;
+static unsigned int default_fw_tables =3D IPFW_TABLES_DEFAULT;
=20
 /*
  * Each rule belongs to one of 32 different sets (0..31).
@@ -148,6 +149,7 @@
=20
 #ifdef SYSCTL_NODE
 uint32_t dummy_def =3D IPFW_DEFAULT_RULE;
+static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
=20
 SYSBEGIN(f3)
=20
@@ -167,14 +169,14 @@
 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
     &dummy_def, 0,
     "The default/max possible rule number.");
-SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
-    &V_fw_tables_max, 0,
-    "The maximum number of tables.");
+SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
+    CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
+    "Maximum number of tables");
 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
     &default_to_accept, 0,
     "Make the default rule accept all packets.");
 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
-TUNABLE_INT("net.inet.ip.fw.tables_max", &V_fw_tables_max);
+TUNABLE_INT("net.inet.ip.fw.tables_max", &default_fw_tables);
 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
     CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
     "Number of static rules");
@@ -2488,6 +2490,26 @@
 }
=20
 /*
+ * Set maximum number of tables that can be used in given VNET ipfw instan=
ce.
+ */
+#ifdef SYSCTL_NODE
+static int
+sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
+{
+	int error;
+	unsigned int ntables;
+
+	ntables =3D V_fw_tables_max;
+
+	error =3D sysctl_handle_int(oidp, &ntables, 0, req);
+	/* Read operation or some error */
+	if ((error !=3D 0) || (req->newptr =3D=3D NULL))
+		return (error);
+
+	return (ipfw_resize_tables(&V_layer3_chain, ntables));
+}
+#endif
+/*
  * Module and VNET glue
  */
=20
@@ -2543,6 +2565,10 @@
 		printf("limited to %d packets/entry by default\n",
 		    V_verbose_limit);
=20
+	/* Check user-supplied table count for validness */
+	if (default_fw_tables > IPFW_TABLES_MAX)
+	  default_fw_tables =3D IPFW_TABLES_MAX;
+
 	ipfw_log_bpf(1); /* init */
 	return (error);
 }
@@ -2585,18 +2611,15 @@
 	LIST_INIT(&chain->nat);
 #endif
=20
-	/* Check user-supplied number for validness */
-	if (V_fw_tables_max < 0)
-	  V_fw_tables_max =3D IPFW_TABLES_MAX;
-	if (V_fw_tables_max > 65534)
-	  V_fw_tables_max =3D 65534;
-
 	/* insert the default rule and create the initial map */
 	chain->n_rules =3D 1;
 	chain->static_len =3D sizeof(struct ip_fw);
 	chain->map =3D malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
 	if (chain->map)
 		rule =3D malloc(chain->static_len, M_IPFW, M_WAITOK | M_ZERO);
+
+	/* Set initial number of tables */
+	V_fw_tables_max =3D default_fw_tables;
 	error =3D ipfw_init_tables(chain);
 	if (error) {
 		printf("ipfw2: setting up tables failed\n");
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/ipfw/ip_fw_private.h
--- a/head/sys/netinet/ipfw/ip_fw_private.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/ipfw/ip_fw_private.h	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/netinet/ipfw/ip_fw_private.h 232868 2012-03-12 15:41=
:36Z melifaro $
+ * $FreeBSD: head/sys/netinet/ipfw/ip_fw_private.h 233478 2012-03-25 20:37=
:59Z melifaro $
  */
=20
 #ifndef _IPFW2_PRIVATE_H
@@ -209,8 +209,8 @@
 VNET_DECLARE(int, autoinc_step);
 #define V_autoinc_step		VNET(autoinc_step)
=20
-extern int fw_tables_max;
-#define V_fw_tables_max		fw_tables_max
+VNET_DECLARE(unsigned int, fw_tables_max);
+#define V_fw_tables_max		VNET(fw_tables_max)
=20
 struct ip_fw_chain {
 	struct ip_fw	*rules;		/* list of rules */
@@ -292,6 +292,7 @@
 int ipfw_dump_table(struct ip_fw_chain *ch, ipfw_table *tbl);
 int ipfw_count_xtable(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt);
 int ipfw_dump_xtable(struct ip_fw_chain *ch, ipfw_xtable *tbl);
+int ipfw_resize_tables(struct ip_fw_chain *ch, unsigned int ntables);
=20
 /* In ip_fw_nat.c -- XXX to be moved to ip_var.h */
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/ipfw/ip_fw_sockopt.c
--- a/head/sys/netinet/ipfw/ip_fw_sockopt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/ipfw/ip_fw_sockopt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw_sockopt.c 232865 2012-03-1=
2 14:07:57Z melifaro $");
+__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw_sockopt.c 233745 2012-03-3=
1 11:20:48Z glebius $");
=20
 /*
  * Sockopt support for ipfw. The routines here implement
@@ -163,8 +163,6 @@
=20
 	l =3D RULESIZE(input_rule);
 	rule =3D malloc(l, M_IPFW, M_WAITOK | M_ZERO);
-	if (rule =3D=3D NULL)
-		return (ENOSPC);
 	/* get_map returns with IPFW_UH_WLOCK if successful */
 	map =3D get_map(chain, 1, 0 /* not locked */);
 	if (map =3D=3D NULL) {
@@ -1010,8 +1008,6 @@
 			if (size >=3D sopt->sopt_valsize)
 				break;
 			buf =3D malloc(size, M_TEMP, M_WAITOK);
-			if (buf =3D=3D NULL)
-				break;
 			IPFW_UH_RLOCK(chain);
 			/* check again how much space we need */
 			want =3D chain->static_len + ipfw_dyn_len();
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/ipfw/ip_fw_table.c
--- a/head/sys/netinet/ipfw/ip_fw_table.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/ipfw/ip_fw_table.c	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw_table.c 232865 2012-03-12 =
14:07:57Z melifaro $");
+__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw_table.c 233478 2012-03-25 =
20:37:59Z melifaro $");
=20
 /*
  * Lookup table support for ipfw
@@ -460,6 +460,68 @@
 }
=20
 int
+ipfw_resize_tables(struct ip_fw_chain *ch, unsigned int ntables)
+{
+	struct radix_node_head **tables, **xtables, *rnh;
+	struct radix_node_head **tables_old, **xtables_old;
+	uint8_t *tabletype, *tabletype_old;
+	unsigned int ntables_old, tbl;
+
+	/* Check new value for validity */
+	if (ntables > IPFW_TABLES_MAX)
+		ntables =3D IPFW_TABLES_MAX;
+
+	/* Allocate new pointers */
+	tables =3D malloc(ntables * sizeof(void *), M_IPFW, M_WAITOK | M_ZERO);
+	xtables =3D malloc(ntables * sizeof(void *), M_IPFW, M_WAITOK | M_ZERO);
+	tabletype =3D malloc(ntables * sizeof(uint8_t), M_IPFW, M_WAITOK | M_ZERO=
);
+
+	IPFW_WLOCK(ch);
+
+	tbl =3D (ntables >=3D V_fw_tables_max) ? V_fw_tables_max : ntables;
+
+	/* Copy old table pointers */
+	memcpy(tables, ch->tables, sizeof(void *) * tbl);
+	memcpy(xtables, ch->xtables, sizeof(void *) * tbl);
+	memcpy(tabletype, ch->tabletype, sizeof(uint8_t) * tbl);
+
+	/* Change pointers and number of tables */
+	tables_old =3D ch->tables;
+	xtables_old =3D ch->xtables;
+	tabletype_old =3D ch->tabletype;
+	ch->tables =3D tables;
+	ch->xtables =3D xtables;
+	ch->tabletype =3D tabletype;
+
+	ntables_old =3D V_fw_tables_max;
+	V_fw_tables_max =3D ntables;
+
+	IPFW_WUNLOCK(ch);
+
+	/* Check if we need to destroy radix trees */
+	if (ntables < ntables_old) {
+		for (tbl =3D ntables; tbl < ntables_old; tbl++) {
+			if ((rnh =3D tables_old[tbl]) !=3D NULL) {
+				rnh->rnh_walktree(rnh, flush_table_entry, rnh);
+				rn_detachhead((void **)&rnh);
+			}
+
+			if ((rnh =3D xtables_old[tbl]) !=3D NULL) {
+				rnh->rnh_walktree(rnh, flush_table_entry, rnh);
+				rn_detachhead((void **)&rnh);
+			}
+		}
+	}
+
+	/* Free old pointers */
+	free(tables_old, M_IPFW);
+	free(xtables_old, M_IPFW);
+	free(tabletype_old, M_IPFW);
+
+	return (0);
+}
+
+int
 ipfw_lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
     uint32_t *val)
 {
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp.h
--- a/head/sys/netinet/sctp.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
 /* $KAME: sctp.h,v 1.18 2005/03/06 16:04:16 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp.h 228653 2011-12-17 19:21:40Z tu=
exen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp.h 233660 2012-03-29 13:36:53Z rr=
s $");
=20
 #ifndef _NETINET_SCTP_H_
 #define _NETINET_SCTP_H_
@@ -155,8 +155,22 @@
  * field.
  */
=20
-/* these should probably go into sockets API */
-#define SCTP_RESET_STREAMS		0x00001004	/* wo */
+#define SCTP_ENABLE_STREAM_RESET	0x00000900	/* struct
+							 * sctp_assoc_value */
+#define SCTP_RESET_STREAMS		0x00000901	/* struct
+							 * sctp_reset_streams */
+#define SCTP_RESET_ASSOC		0x00000902	/* sctp_assoc_t */
+#define SCTP_ADD_STREAMS		0x00000903	/* struct
+							 * sctp_add_streams */
+
+/* For enable stream reset */
+#define SCTP_ENABLE_RESET_STREAM_REQ 	0x00000001
+#define SCTP_ENABLE_RESET_ASSOC_REQ 	0x00000002
+#define SCTP_ENABLE_CHANGE_ASSOC_REQ 	0x00000004
+#define SCTP_ENABLE_VALUE_MASK		0x00000007
+/* For reset streams */
+#define SCTP_STREAM_RESET_INCOMING	0x00000001
+#define SCTP_STREAM_RESET_OUTGOING	0x00000002
=20
=20
 /* here on down are more implementation specific */
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_constants.h
--- a/head/sys/netinet/sctp_constants.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_constants.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_constants.h,v 1.17 2005/03/06 16:04:17 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_constants.h 228907 2011-12-27 10=
:16:24Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_constants.h 233660 2012-03-29 13=
:36:53Z rrs $");
=20
 #ifndef __sctp_constants_h__
 #define __sctp_constants_h__
@@ -418,7 +418,8 @@
 #define SCTP_STR_RESET_IN_REQUEST	0x000e
 #define SCTP_STR_RESET_TSN_REQUEST	0x000f
 #define SCTP_STR_RESET_RESPONSE		0x0010
-#define SCTP_STR_RESET_ADD_STREAMS	0x0011
+#define SCTP_STR_RESET_ADD_OUT_STREAMS	0x0011
+#define SCTP_STR_RESET_ADD_IN_STREAMS   0x0012
=20
 #define SCTP_MAX_RESET_PARAMS 2
 #define SCTP_STREAM_RESET_TSN_DELTA    0x1000
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_header.h
--- a/head/sys/netinet/sctp_header.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_header.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_header.h,v 1.14 2005/03/06 16:04:17 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_header.h 228653 2011-12-17 19:21=
:40Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_header.h 233660 2012-03-29 13:36=
:53Z rrs $");
=20
 #ifndef __sctp_header_h__
 #define __sctp_header_h__
@@ -501,7 +501,7 @@
=20
 #define SCTP_STREAM_RESET_NOTHING   0x00000000	/* Nothing for me to do */
 #define SCTP_STREAM_RESET_PERFORMED 0x00000001	/* Did it */
-#define SCTP_STREAM_RESET_DENIED    0x00000002	/* refused to do it */
+#define SCTP_STREAM_RESET_REJECT    0x00000002	/* refused to do it */
 #define SCTP_STREAM_RESET_ERROR_STR 0x00000003	/* bad Stream no */
 #define SCTP_STREAM_RESET_TRY_LATER 0x00000004	/* collision, try again */
 #define SCTP_STREAM_RESET_BAD_SEQNO 0x00000005	/* bad str-reset seq no */
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_input.c
--- a/head/sys/netinet/sctp_input.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_input.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_input.c,v 1.27 2005/03/06 16:04:17 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_input.c 230379 2012-01-20 13:26:=
11Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_input.c 233660 2012-03-29 13:36:=
53Z rrs $");
=20
 #include <netinet/sctp_os.h>
 #include <netinet/sctp_var.h>
@@ -2790,6 +2790,7 @@
 			inp->sctp_ecn_enable =3D (*inp_p)->sctp_ecn_enable;
 			inp->partial_delivery_point =3D (*inp_p)->partial_delivery_point;
 			inp->sctp_context =3D (*inp_p)->sctp_context;
+			inp->local_strreset_support =3D (*inp_p)->local_strreset_support;
 			inp->inp_starting_point_for_iterator =3D NULL;
 			/*
 			 * copy in the authentication parameters from the
@@ -3612,20 +3613,35 @@
 				if (asoc->stream_reset_outstanding)
 					asoc->stream_reset_outstanding--;
 				if (action !=3D SCTP_STREAM_RESET_PERFORMED) {
-					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_FAILED_IN, stcb, number_entries=
, srparam->list_of_streams, SCTP_SO_NOT_LOCKED);
+					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_FAILED_IN, stcb,
+					    number_entries, srparam->list_of_streams, SCTP_SO_NOT_LOCKED);
 				}
-			} else if (type =3D=3D SCTP_STR_RESET_ADD_STREAMS) {
+			} else if (type =3D=3D SCTP_STR_RESET_ADD_OUT_STREAMS) {
 				/* Ok we now may have more streams */
+				int num_stream;
+
+				num_stream =3D stcb->asoc.strm_pending_add_size;
+				if (num_stream > (stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcn=
t)) {
+					/* TSNH */
+					num_stream =3D stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcnt;
+				}
+				stcb->asoc.strm_pending_add_size =3D 0;
 				if (asoc->stream_reset_outstanding)
 					asoc->stream_reset_outstanding--;
 				if (action =3D=3D SCTP_STREAM_RESET_PERFORMED) {
 					/* Put the new streams into effect */
-					stcb->asoc.streamoutcnt =3D stcb->asoc.strm_realoutsize;
-					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_ADD_OK, stcb,
-					    (uint32_t) stcb->asoc.streamoutcnt, NULL, SCTP_SO_NOT_LOCKED);
+					stcb->asoc.streamoutcnt +=3D num_stream;
+					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc=
.streamoutcnt, 0);
 				} else {
-					sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_ADD_FAIL, stcb,
-					    (uint32_t) stcb->asoc.streamoutcnt, NULL, SCTP_SO_NOT_LOCKED);
+					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc=
.streamoutcnt,
+					    SCTP_STREAM_CHANGED_DENIED);
+				}
+			} else if (type =3D=3D SCTP_STR_RESET_ADD_IN_STREAMS) {
+				if (asoc->stream_reset_outstanding)
+					asoc->stream_reset_outstanding--;
+				if (action !=3D SCTP_STREAM_RESET_PERFORMED) {
+					sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc=
.streamoutcnt,
+					    SCTP_STREAM_CHANGED_DENIED);
 				}
 			} else if (type =3D=3D SCTP_STR_RESET_TSN_REQUEST) {
 				/**
@@ -3667,7 +3683,10 @@
=20
 					sctp_reset_out_streams(stcb, 0, (uint16_t *) NULL);
 					sctp_reset_in_stream(stcb, 0, (uint16_t *) NULL);
-
+					sctp_notify_stream_reset_tsn(stcb, stcb->asoc.sending_seq, (stcb->aso=
c.mapping_array_base_tsn + 1), 0);
+				} else {
+					sctp_notify_stream_reset_tsn(stcb, stcb->asoc.sending_seq, (stcb->aso=
c.mapping_array_base_tsn + 1),
+					    SCTP_STREAM_RESET_FAILED);
 				}
 			}
 			/* get rid of the request and get the request flags */
@@ -3700,8 +3719,7 @@
 		if (trunc) {
 			/* Can't do it, since they exceeded our buffer size  */
 			asoc->last_reset_action[1] =3D asoc->last_reset_action[0];
-			asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_DENIED;
-			sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
+			asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_REJECT;
 		} else if (stcb->asoc.stream_reset_out_is_outstanding =3D=3D 0) {
 			len =3D ntohs(req->ph.param_length);
 			number_entries =3D ((len - sizeof(struct sctp_stream_reset_in_request))=
 / sizeof(uint16_t));
@@ -3723,8 +3741,8 @@
 			/* Can't do it, since we have sent one out */
 			asoc->last_reset_action[1] =3D asoc->last_reset_action[0];
 			asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_TRY_LATER;
-			sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
 		}
+		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
 		asoc->str_reset_seq_in++;
 	} else if (asoc->str_reset_seq_in - 1 =3D=3D seq) {
 		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
@@ -3786,7 +3804,7 @@
 		sctp_reset_in_stream(stcb, 0, (uint16_t *) NULL);
 		stcb->asoc.last_reset_action[1] =3D stcb->asoc.last_reset_action[0];
 		stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_PERFORMED;
-
+		sctp_notify_stream_reset_tsn(stcb, stcb->asoc.sending_seq, (stcb->asoc.m=
apping_array_base_tsn + 1), 0);
 		asoc->str_reset_seq_in++;
 	} else if (asoc->str_reset_seq_in - 1 =3D=3D seq) {
 		sctp_add_stream_reset_result_tsn(chk, seq, asoc->last_reset_action[0],
@@ -3831,12 +3849,10 @@
 		/* move the reset action back one */
 		asoc->last_reset_action[1] =3D asoc->last_reset_action[0];
 		if (trunc) {
-			sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_DENIED);
-			asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_DENIED;
+			asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_REJECT;
 		} else if (SCTP_TSN_GE(asoc->cumulative_tsn, tsn)) {
 			/* we can do it now */
 			sctp_reset_in_stream(stcb, number_entries, req->list_of_streams);
-			sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_PERFORMED);
 			asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_PERFORMED;
 		} else {
 			/*
@@ -3851,8 +3867,8 @@
 			    siz, SCTP_M_STRESET);
 			if (liste =3D=3D NULL) {
 				/* gak out of memory */
-				sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_DENIED);
-				asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_DENIED;
+				sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_REJECT);
+				asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_REJECT;
 				return;
 			}
 			liste->tsn =3D tsn;
@@ -3860,9 +3876,9 @@
 			memcpy(&liste->req, req,
 			    (sizeof(struct sctp_stream_reset_out_request) + (number_entries * s=
izeof(uint16_t))));
 			TAILQ_INSERT_TAIL(&asoc->resetHead, liste, next_resp);
-			sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_PERFORMED);
 			asoc->last_reset_action[0] =3D SCTP_STREAM_RESET_PERFORMED;
 		}
+		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
 		asoc->str_reset_seq_in++;
 	} else if ((asoc->str_reset_seq_in - 1) =3D=3D seq) {
 		/*
@@ -3889,7 +3905,7 @@
 	 * Peer is requesting to add more streams. If its within our
 	 * max-streams we will allow it.
 	 */
-	uint16_t num_stream, i;
+	uint32_t num_stream, i;
 	uint32_t seq;
 	struct sctp_association *asoc =3D &stcb->asoc;
 	struct sctp_queued_to_read *ctl, *nctl;
@@ -3900,12 +3916,12 @@
 	/* Now what would be the new total? */
 	if (asoc->str_reset_seq_in =3D=3D seq) {
 		num_stream +=3D stcb->asoc.streamincnt;
-		if (num_stream > stcb->asoc.max_inbound_streams) {
+		if ((num_stream > stcb->asoc.max_inbound_streams) ||
+		    (num_stream > 0xffff)) {
 			/* We must reject it they ask for to many */
 	denied:
-			sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_DENIED);
 			stcb->asoc.last_reset_action[1] =3D stcb->asoc.last_reset_action[0];
-			stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_DENIED;
+			stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_REJECT;
 		} else {
 			/* Ok, we can do that :-) */
 			struct sctp_stream_in *oldstrm;
@@ -3941,13 +3957,12 @@
 			SCTP_FREE(oldstrm, SCTP_M_STRMI);
 			/* update the size */
 			stcb->asoc.streamincnt =3D num_stream;
-			/* Send the ack */
-			sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_PERFORMED);
 			stcb->asoc.last_reset_action[1] =3D stcb->asoc.last_reset_action[0];
 			stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_PERFORMED;
-			sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_INSTREAM_ADD_OK, stcb,
-			    (uint32_t) stcb->asoc.streamincnt, NULL, SCTP_SO_NOT_LOCKED);
+			sctp_notify_stream_reset_add(stcb, stcb->asoc.streamincnt, stcb->asoc.s=
treamoutcnt, 0);
 		}
+		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
+		asoc->str_reset_seq_in++;
 	} else if ((asoc->str_reset_seq_in - 1) =3D=3D seq) {
 		/*
 		 * one seq back, just echo back last action since my
@@ -3966,6 +3981,63 @@
 	}
 }
=20
+static void
+sctp_handle_str_reset_add_out_strm(struct sctp_tcb *stcb, struct sctp_tmit=
_chunk *chk,
+    struct sctp_stream_reset_add_strm *str_add)
+{
+	/*
+	 * Peer is requesting to add more streams. If its within our
+	 * max-streams we will allow it.
+	 */
+	uint16_t num_stream;
+	uint32_t seq;
+	struct sctp_association *asoc =3D &stcb->asoc;
+
+	/* Get the number. */
+	seq =3D ntohl(str_add->request_seq);
+	num_stream =3D ntohs(str_add->number_of_streams);
+	/* Now what would be the new total? */
+	if (asoc->str_reset_seq_in =3D=3D seq) {
+		if (stcb->asoc.stream_reset_outstanding) {
+			/* We must reject it we have something pending */
+			stcb->asoc.last_reset_action[1] =3D stcb->asoc.last_reset_action[0];
+			stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_REJECT;
+		} else {
+			/* Ok, we can do that :-) */
+			int mychk;
+
+			mychk =3D stcb->asoc.streamoutcnt;
+			mychk +=3D num_stream;
+			if (mychk < 0x10000) {
+				stcb->asoc.last_reset_action[1] =3D stcb->asoc.last_reset_action[0];
+				stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_PERFORMED;
+				if (sctp_send_str_reset_req(stcb, 0, NULL, 0, 0, 0, 1, num_stream, 0, =
1)) {
+					stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_REJECT;
+				}
+			} else {
+				stcb->asoc.last_reset_action[1] =3D stcb->asoc.last_reset_action[0];
+				stcb->asoc.last_reset_action[0] =3D SCTP_STREAM_RESET_REJECT;
+			}
+		}
+		sctp_add_stream_reset_result(chk, seq, stcb->asoc.last_reset_action[0]);
+		asoc->str_reset_seq_in++;
+	} else if ((asoc->str_reset_seq_in - 1) =3D=3D seq) {
+		/*
+		 * one seq back, just echo back last action since my
+		 * response was lost.
+		 */
+		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[0]);
+	} else if ((asoc->str_reset_seq_in - 2) =3D=3D seq) {
+		/*
+		 * two seq back, just echo back last action since my
+		 * response was lost.
+		 */
+		sctp_add_stream_reset_result(chk, seq, asoc->last_reset_action[1]);
+	} else {
+		sctp_add_stream_reset_result(chk, seq, SCTP_STREAM_RESET_BAD_SEQNO);
+	}
+}
+
 #ifdef __GNUC__
 __attribute__((noinline))
 #endif
@@ -3977,7 +4049,7 @@
 	struct sctp_paramhdr pstore;
 	uint8_t cstore[SCTP_CHUNK_BUFFER_SIZE];
=20
-	uint32_t seq;
+	uint32_t seq =3D 0;
 	int num_req =3D 0;
 	int trunc =3D 0;
 	struct sctp_tmit_chunk *chk;
@@ -4041,7 +4113,6 @@
 		} else {
 			trunc =3D 0;
 		}
-
 		if (num_param > SCTP_MAX_RESET_PARAMS) {
 			/* hit the max of parameters already sorry.. */
 			break;
@@ -4059,26 +4130,29 @@
 				}
 			}
 			sctp_handle_str_reset_request_out(stcb, chk, req_out, trunc);
-		} else if (ptype =3D=3D SCTP_STR_RESET_ADD_STREAMS) {
+		} else if (ptype =3D=3D SCTP_STR_RESET_ADD_OUT_STREAMS) {
 			struct sctp_stream_reset_add_strm *str_add;
=20
 			str_add =3D (struct sctp_stream_reset_add_strm *)ph;
 			num_req++;
 			sctp_handle_str_reset_add_strm(stcb, chk, str_add);
+		} else if (ptype =3D=3D SCTP_STR_RESET_ADD_IN_STREAMS) {
+			struct sctp_stream_reset_add_strm *str_add;
+
+			str_add =3D (struct sctp_stream_reset_add_strm *)ph;
+			num_req++;
+			sctp_handle_str_reset_add_out_strm(stcb, chk, str_add);
 		} else if (ptype =3D=3D SCTP_STR_RESET_IN_REQUEST) {
 			struct sctp_stream_reset_in_request *req_in;
=20
 			num_req++;
-
 			req_in =3D (struct sctp_stream_reset_in_request *)ph;
-
 			sctp_handle_str_reset_request_in(stcb, chk, req_in, trunc);
 		} else if (ptype =3D=3D SCTP_STR_RESET_TSN_REQUEST) {
 			struct sctp_stream_reset_tsn_request *req_tsn;
=20
 			num_req++;
 			req_tsn =3D (struct sctp_stream_reset_tsn_request *)ph;
-
 			if (sctp_handle_str_reset_request_tsn(stcb, chk, req_tsn)) {
 				ret_code =3D 1;
 				goto strres_nochunk;
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_output.c
--- a/head/sys/netinet/sctp_output.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_output.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_output.c,v 1.46 2005/03/06 16:04:17 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_output.c 231672 2012-02-14 12:00=
:34Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_output.c 233660 2012-03-29 13:36=
:53Z rrs $");
=20
 #include <netinet/sctp_os.h>
 #include <sys/proc.h>
@@ -53,6 +53,7 @@
 #include <netinet/sctp_input.h>
 #include <netinet/sctp_crc32.h>
 #include <netinet/udp.h>
+#include <netinet/udp_var.h>
 #include <machine/in_cksum.h>
=20
=20
@@ -4064,7 +4065,11 @@
 				udp->uh_sport =3D htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
 				udp->uh_dport =3D port;
 				udp->uh_ulen =3D htons(packet_length - sizeof(struct ip));
-				udp->uh_sum =3D in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, udp->u=
h_ulen + htons(IPPROTO_UDP));
+				if (V_udp_cksum) {
+					udp->uh_sum =3D in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, udp->=
uh_ulen + htons(IPPROTO_UDP));
+				} else {
+					udp->uh_sum =3D 0;
+				}
 				sctphdr =3D (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
 			} else {
 				sctphdr =3D (struct sctphdr *)((caddr_t)ip + sizeof(struct ip));
@@ -4127,7 +4132,9 @@
 					SCTP_STAT_INCR(sctps_sendnocrc);
 				}
 #endif
-				SCTP_ENABLE_UDP_CSUM(o_pak);
+				if (V_udp_cksum) {
+					SCTP_ENABLE_UDP_CSUM(o_pak);
+				}
 			} else {
 #if defined(SCTP_WITH_NO_CSUM)
 				SCTP_STAT_INCR(sctps_sendnocrc);
@@ -11007,8 +11014,13 @@
 		udp->uh_dport =3D port;
 		udp->uh_ulen =3D htons(sizeof(struct sctp_shutdown_complete_msg) + sizeo=
f(struct udphdr));
 #ifdef INET
-		if (iph_out)
-			udp->uh_sum =3D in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_add=
r, udp->uh_ulen + htons(IPPROTO_UDP));
+		if (iph_out) {
+			if (V_udp_cksum) {
+				udp->uh_sum =3D in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_ad=
dr, udp->uh_ulen + htons(IPPROTO_UDP));
+			} else {
+				udp->uh_sum =3D 0;
+			}
+		}
 #endif
 		offset_out +=3D sizeof(struct udphdr);
 		comp_cp =3D (struct sctp_shutdown_complete_msg *)((caddr_t)comp_cp + siz=
eof(struct udphdr));
@@ -11047,7 +11059,9 @@
 			comp_cp->sh.checksum =3D sctp_calculate_cksum(mout, offset_out);
 			SCTP_STAT_INCR(sctps_sendswcrc);
 #endif
-			SCTP_ENABLE_UDP_CSUM(mout);
+			if (V_udp_cksum) {
+				SCTP_ENABLE_UDP_CSUM(mout);
+			}
 		} else {
 #if defined(SCTP_WITH_NO_CSUM)
 			SCTP_STAT_INCR(sctps_sendnocrc);
@@ -11702,7 +11716,7 @@
 }
=20
 static void
-sctp_add_a_stream(struct sctp_tmit_chunk *chk,
+sctp_add_an_out_stream(struct sctp_tmit_chunk *chk,
     uint32_t seq,
     uint16_t adding)
 {
@@ -11719,7 +11733,7 @@
 	len =3D sizeof(struct sctp_stream_reset_add_strm);
=20
 	/* Fill it out. */
-	addstr->ph.param_type =3D htons(SCTP_STR_RESET_ADD_STREAMS);
+	addstr->ph.param_type =3D htons(SCTP_STR_RESET_ADD_OUT_STREAMS);
 	addstr->ph.param_length =3D htons(len);
 	addstr->request_seq =3D htonl(seq);
 	addstr->number_of_streams =3D htons(adding);
@@ -11734,15 +11748,49 @@
 	return;
 }
=20
+static void
+sctp_add_an_in_stream(struct sctp_tmit_chunk *chk,
+    uint32_t seq,
+    uint16_t adding)
+{
+	int len, old_len;
+	struct sctp_chunkhdr *ch;
+	struct sctp_stream_reset_add_strm *addstr;
+
+	ch =3D mtod(chk->data, struct sctp_chunkhdr *);
+	old_len =3D len =3D SCTP_SIZE32(ntohs(ch->chunk_length));
+
+	/* get to new offset for the param. */
+	addstr =3D (struct sctp_stream_reset_add_strm *)((caddr_t)ch + len);
+	/* now how long will this param be? */
+	len =3D sizeof(struct sctp_stream_reset_add_strm);
+	/* Fill it out. */
+	addstr->ph.param_type =3D htons(SCTP_STR_RESET_ADD_IN_STREAMS);
+	addstr->ph.param_length =3D htons(len);
+	addstr->request_seq =3D htonl(seq);
+	addstr->number_of_streams =3D htons(adding);
+	addstr->reserved =3D 0;
+
+	/* now fix the chunk length */
+	ch->chunk_length =3D htons(len + old_len);
+	chk->send_size =3D len + old_len;
+	chk->book_size =3D SCTP_SIZE32(chk->send_size);
+	chk->book_size_scale =3D 0;
+	SCTP_BUF_LEN(chk->data) =3D SCTP_SIZE32(chk->send_size);
+	return;
+}
+
+
+
 int
 sctp_send_str_reset_req(struct sctp_tcb *stcb,
     int number_entries, uint16_t * list,
     uint8_t send_out_req,
-    uint32_t resp_seq,
     uint8_t send_in_req,
     uint8_t send_tsn_req,
     uint8_t add_stream,
-    uint16_t adding
+    uint16_t adding_o,
+    uint16_t adding_i, uint8_t peer_asked
 )
 {
=20
@@ -11809,18 +11857,86 @@
 	seq =3D stcb->asoc.str_reset_seq_out;
 	if (send_out_req) {
 		sctp_add_stream_reset_out(chk, number_entries, list,
-		    seq, resp_seq, (stcb->asoc.sending_seq - 1));
+		    seq, (stcb->asoc.str_reset_seq_in - 1), (stcb->asoc.sending_seq - 1)=
);
 		asoc->stream_reset_out_is_outstanding =3D 1;
 		seq++;
 		asoc->stream_reset_outstanding++;
 	}
-	if (add_stream) {
-		sctp_add_a_stream(chk, seq, adding);
+	if ((add_stream & 1) &&
+	    ((stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcnt) < adding_o))=
 {
+		/* Need to allocate more */
+		struct sctp_stream_out *oldstream;
+		struct sctp_stream_queue_pending *sp, *nsp;
+		int i;
+
+		oldstream =3D stcb->asoc.strmout;
+		/* get some more */
+		SCTP_MALLOC(stcb->asoc.strmout, struct sctp_stream_out *,
+		    ((stcb->asoc.streamoutcnt + adding_o) * sizeof(struct sctp_stream_ou=
t)),
+		    SCTP_M_STRMO);
+		if (stcb->asoc.strmout =3D=3D NULL) {
+			uint8_t x;
+
+			stcb->asoc.strmout =3D oldstream;
+			/* Turn off the bit */
+			x =3D add_stream & 0xfe;
+			add_stream =3D x;
+			goto skip_stuff;
+		}
+		/*
+		 * Ok now we proceed with copying the old out stuff and
+		 * initializing the new stuff.
+		 */
+		SCTP_TCB_SEND_LOCK(stcb);
+		stcb->asoc.ss_functions.sctp_ss_clear(stcb, &stcb->asoc, 0, 1);
+		for (i =3D 0; i < stcb->asoc.streamoutcnt; i++) {
+			TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
+			stcb->asoc.strmout[i].next_sequence_sent =3D oldstream[i].next_sequence=
_sent;
+			stcb->asoc.strmout[i].last_msg_incomplete =3D oldstream[i].last_msg_inc=
omplete;
+			stcb->asoc.strmout[i].stream_no =3D i;
+			stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], &ol=
dstream[i]);
+			/* now anything on those queues? */
+			TAILQ_FOREACH_SAFE(sp, &oldstream[i].outqueue, next, nsp) {
+				TAILQ_REMOVE(&oldstream[i].outqueue, sp, next);
+				TAILQ_INSERT_TAIL(&stcb->asoc.strmout[i].outqueue, sp, next);
+			}
+			/* Now move assoc pointers too */
+			if (stcb->asoc.last_out_stream =3D=3D &oldstream[i]) {
+				stcb->asoc.last_out_stream =3D &stcb->asoc.strmout[i];
+			}
+			if (stcb->asoc.locked_on_sending =3D=3D &oldstream[i]) {
+				stcb->asoc.locked_on_sending =3D &stcb->asoc.strmout[i];
+			}
+		}
+		/* now the new streams */
+		stcb->asoc.ss_functions.sctp_ss_init(stcb, &stcb->asoc, 1);
+		for (i =3D stcb->asoc.streamoutcnt; i < (stcb->asoc.streamoutcnt + addin=
g_o); i++) {
+			stcb->asoc.strmout[i].next_sequence_sent =3D 0x0;
+			TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
+			stcb->asoc.strmout[i].stream_no =3D i;
+			stcb->asoc.strmout[i].last_msg_incomplete =3D 0;
+			stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], NUL=
L);
+		}
+		stcb->asoc.strm_realoutsize =3D stcb->asoc.streamoutcnt + adding_o;
+		SCTP_FREE(oldstream, SCTP_M_STRMO);
+		SCTP_TCB_SEND_UNLOCK(stcb);
+	}
+skip_stuff:
+	if ((add_stream & 1) && (adding_o > 0)) {
+		asoc->strm_pending_add_size =3D adding_o;
+		asoc->peer_req_out =3D peer_asked;
+		sctp_add_an_out_stream(chk, seq, adding_o);
 		seq++;
 		asoc->stream_reset_outstanding++;
 	}
+	if ((add_stream & 2) && (adding_i > 0)) {
+		sctp_add_an_in_stream(chk, seq, adding_i);
+		seq++;
+		asoc->stream_reset_outstanding++;
+	}
 	if (send_in_req) {
 		sctp_add_stream_reset_in(chk, number_entries, list, seq);
+		seq++;
 		asoc->stream_reset_outstanding++;
 	}
 	if (send_tsn_req) {
@@ -11828,7 +11944,6 @@
 		asoc->stream_reset_outstanding++;
 	}
 	asoc->str_reset =3D chk;
-
 	/* insert the chunk for sending */
 	TAILQ_INSERT_TAIL(&asoc->control_send_queue,
 	    chk,
@@ -12024,7 +12139,11 @@
 		bzero(&ro, sizeof ro);
 		if (port) {
 			udp->uh_ulen =3D htons(len - sizeof(struct ip));
-			udp->uh_sum =3D in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_add=
r, udp->uh_ulen + htons(IPPROTO_UDP));
+			if (V_udp_cksum) {
+				udp->uh_sum =3D in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_ad=
dr, udp->uh_ulen + htons(IPPROTO_UDP));
+			} else {
+				udp->uh_sum =3D 0;
+			}
 		}
 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "sctp_send_abort calling ip_output:\n");
 		SCTPDBG_PKT(SCTP_DEBUG_OUTPUT2, iph_out, &abm->sh);
@@ -12043,7 +12162,9 @@
 			abm->sh.checksum =3D sctp_calculate_cksum(mout, iphlen_out);
 			SCTP_STAT_INCR(sctps_sendswcrc);
 #endif
-			SCTP_ENABLE_UDP_CSUM(o_pak);
+			if (V_udp_cksum) {
+				SCTP_ENABLE_UDP_CSUM(o_pak);
+			}
 		} else {
 #if defined(SCTP_WITH_NO_CSUM)
 			SCTP_STAT_INCR(sctps_sendnocrc);
@@ -12286,7 +12407,11 @@
 		bzero(&ro, sizeof ro);
 		if (port) {
 			udp->uh_ulen =3D htons(len - sizeof(struct ip));
-			udp->uh_sum =3D in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_add=
r, udp->uh_ulen + htons(IPPROTO_UDP));
+			if (V_udp_cksum) {
+				udp->uh_sum =3D in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_ad=
dr, udp->uh_ulen + htons(IPPROTO_UDP));
+			} else {
+				udp->uh_sum =3D 0;
+			}
 		}
 		/* set IPv4 length */
 		iph_out->ip_len =3D len;
@@ -12303,7 +12428,9 @@
 			sh_out->checksum =3D sctp_calculate_cksum(mout, iphlen_out);
 			SCTP_STAT_INCR(sctps_sendswcrc);
 #endif
-			SCTP_ENABLE_UDP_CSUM(o_pak);
+			if (V_udp_cksum) {
+				SCTP_ENABLE_UDP_CSUM(o_pak);
+			}
 		} else {
 #if defined(SCTP_WITH_NO_CSUM)
 			SCTP_STAT_INCR(sctps_sendnocrc);
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_output.h
--- a/head/sys/netinet/sctp_output.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_output.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_output.h,v 1.14 2005/03/06 16:04:18 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_output.h 228653 2011-12-17 19:21=
:40Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_output.h 233660 2012-03-29 13:36=
:53Z rrs $");
=20
 #ifndef __sctp_output_h__
 #define __sctp_output_h__
@@ -194,15 +194,13 @@
=20
 int
 sctp_send_str_reset_req(struct sctp_tcb *stcb,
-    int number_entries,
-    uint16_t * list,
+    int number_entries, uint16_t * list,
     uint8_t send_out_req,
-    uint32_t resp_seq,
     uint8_t send_in_req,
     uint8_t send_tsn_req,
-    uint8_t add_str,
-    uint16_t adding);
-
+    uint8_t add_stream,
+    uint16_t adding_o,
+    uint16_t adding_i, uint8_t from_peer);
=20
 void
 sctp_send_abort(struct mbuf *, int, struct sctphdr *, uint32_t,
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_pcb.h
--- a/head/sys/netinet/sctp_pcb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_pcb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
 /* $KAME: sctp_pcb.h,v 1.21 2005/07/16 01:18:47 suz Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.h 228653 2011-12-17 19:21:40=
Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.h 233660 2012-03-29 13:36:53=
Z rrs $");
=20
 #ifndef __sctp_pcb_h__
 #define __sctp_pcb_h__
@@ -399,6 +399,7 @@
 	uint32_t sctp_frag_point;
 	uint32_t partial_delivery_point;
 	uint32_t sctp_context;
+	uint8_t local_strreset_support;
 	uint32_t sctp_cmt_on_off;
 	uint32_t sctp_ecn_enable;
 	struct sctp_nonpad_sndrcvinfo def_send;
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_peeloff.c
--- a/head/sys/netinet/sctp_peeloff.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_peeloff.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
 /* $KAME: sctp_peeloff.c,v 1.13 2005/03/06 16:04:18 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_peeloff.c 233004 2012-03-15 14:1=
3:38Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_peeloff.c 233660 2012-03-29 13:3=
6:53Z rrs $");
 #include <netinet/sctp_os.h>
 #include <netinet/sctp_pcb.h>
 #include <netinet/sctputil.h>
@@ -127,6 +127,7 @@
 	n_inp->sctp_ecn_enable =3D inp->sctp_ecn_enable;
 	n_inp->partial_delivery_point =3D inp->partial_delivery_point;
 	n_inp->sctp_context =3D inp->sctp_context;
+	n_inp->local_strreset_support =3D inp->local_strreset_support;
 	n_inp->inp_starting_point_for_iterator =3D NULL;
 	/* copy in the authentication parameters from the original endpoint */
 	if (n_inp->sctp_ep.local_hmacs)
@@ -202,6 +203,7 @@
 	n_inp->sctp_ecn_enable =3D inp->sctp_ecn_enable;
 	n_inp->partial_delivery_point =3D inp->partial_delivery_point;
 	n_inp->sctp_context =3D inp->sctp_context;
+	n_inp->local_strreset_support =3D inp->local_strreset_support;
 	n_inp->inp_starting_point_for_iterator =3D NULL;
=20
 	/* copy in the authentication parameters from the original endpoint */
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_structs.h
--- a/head/sys/netinet/sctp_structs.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_structs.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_structs.h,v 1.13 2005/03/06 16:04:18 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_structs.h 231074 2012-02-06 10:4=
7:12Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_structs.h 233660 2012-03-29 13:3=
6:53Z rrs $");
=20
 #ifndef __sctp_structs_h__
 #define __sctp_structs_h__
@@ -1095,6 +1095,7 @@
 	uint16_t streamincnt;
 	uint16_t streamoutcnt;
 	uint16_t strm_realoutsize;
+	uint16_t strm_pending_add_size;
 	/* my maximum number of retrans of INIT and SEND */
 	/* copied from SCTP but should be individually setable */
 	uint16_t max_init_times;
@@ -1156,6 +1157,9 @@
 	/* Flag to tell if ECN is allowed */
 	uint8_t ecn_allowed;
=20
+	/* Did the peer make the stream config (add out) request */
+	uint8_t peer_req_out;
+
 	/* flag to indicate if peer can do asconf */
 	uint8_t peer_supports_asconf;
 	/* EY - flag to indicate if peer can do nr_sack */
@@ -1166,6 +1170,7 @@
 	uint8_t peer_supports_auth;
 	/* stream resets are supported by the peer */
 	uint8_t peer_supports_strreset;
+	uint8_t local_strreset_support;
=20
 	uint8_t peer_supports_nat;
 	/*
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_timer.c
--- a/head/sys/netinet/sctp_timer.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_timer.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_timer.c,v 1.29 2005/03/06 16:04:18 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_timer.c 228907 2011-12-27 10:16:=
24Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_timer.c 234297 2012-04-14 21:01:=
44Z tuexen $");
=20
 #define _IP_VHL
 #include <netinet/sctp_os.h>
@@ -1438,7 +1438,23 @@
 		 * when move to PF during threshold mangement, a HB has been
 		 * queued in that routine
 		 */
-		sctp_send_hb(stcb, net, SCTP_SO_NOT_LOCKED);
+		uint32_t ms_gone_by;
+
+		if ((net->last_sent_time.tv_sec > 0) ||
+		    (net->last_sent_time.tv_usec > 0)) {
+			struct timeval diff;
+
+			SCTP_GETTIME_TIMEVAL(&diff);
+			timevalsub(&diff, &net->last_sent_time);
+			ms_gone_by =3D (uint32_t) (diff.tv_sec * 1000) +
+			    (uint32_t) (diff.tv_usec / 1000);
+		} else {
+			ms_gone_by =3D 0xffffffff;
+		}
+		if ((ms_gone_by >=3D net->heart_beat_delay) ||
+		    (net->dest_state & SCTP_ADDR_PF)) {
+			sctp_send_hb(stcb, net, SCTP_SO_NOT_LOCKED);
+		}
 	}
 	return (0);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_uio.h
--- a/head/sys/netinet/sctp_uio.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_uio.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
=20
 /* $KAME: sctp_uio.h,v 1.11 2005/03/06 16:04:18 itojun Exp $	 */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_uio.h 228653 2011-12-17 19:21:40=
Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_uio.h 233660 2012-03-29 13:36:53=
Z rrs $");
=20
 #ifndef __sctp_uio_h__
 #define __sctp_uio_h__
@@ -438,23 +438,51 @@
=20
=20
 /*
- * stream reset event
+ * Stream reset event - subscribe to SCTP_STREAM_RESET_EVENT
  */
 struct sctp_stream_reset_event {
 	uint16_t strreset_type;
 	uint16_t strreset_flags;
 	uint32_t strreset_length;
 	sctp_assoc_t strreset_assoc_id;
-	uint16_t strreset_list[];
+	uint16_t strreset_stream_list[];
 };
=20
-/* flags in strreset_flags field */
-#define SCTP_STRRESET_INBOUND_STR  0x0001
-#define SCTP_STRRESET_OUTBOUND_STR 0x0002
-#define SCTP_STRRESET_ALL_STREAMS  0x0004
-#define SCTP_STRRESET_STREAM_LIST  0x0008
-#define SCTP_STRRESET_FAILED       0x0010
-#define SCTP_STRRESET_ADD_STREAM   0x0020
+/* flags in stream_reset_event (strreset_flags) */
+#define SCTP_STREAM_RESET_DENIED        0x0004	/* SCTP_STRRESET_FAILED */
+#define SCTP_STREAM_RESET_FAILED        0x0008	/* SCTP_STRRESET_FAILED */
+#define SCTP_STREAM_CHANGED_DENIED	0x0010
+
+/*
+ * Assoc reset event - subscribe to SCTP_ASSOC_RESET_EVENT
+ */
+struct sctp_assoc_reset_event {
+	uint16_t assocreset_type;
+	uint16_t assocreset_flags;
+	uint32_t assocreset_length;
+	sctp_assoc_t assocreset_assoc_id;
+	uint32_t assocreset_local_tsn;
+	uint32_t assocreset_remote_tsn;
+};
+
+#define SCTP_ASSOC_RESET_DENIED		0x0004
+#define SCTP_ASSOC_RESET_FAILED		0x0008
+
+/*
+ * Stream change event - subscribe to SCTP_STREAM_CHANGE_EVENT
+ */
+struct sctp_stream_change_event {
+	uint16_t strchange_type;
+	uint16_t strchange_flags;
+	uint32_t strchange_length;
+	sctp_assoc_t strchange_assoc_id;
+	uint16_t strchange_instrms;
+	uint16_t strchange_outstrms;
+};
+
+#define SCTP_STREAM_CHANGE_DENIED	0x0004
+#define SCTP_STREAM_CHANGE_FAILED	0x0008
+
=20
 /* SCTP notification event */
 struct sctp_tlv {
@@ -477,6 +505,9 @@
 	struct sctp_authkey_event sn_auth_event;
 	struct sctp_sender_dry_event sn_sender_dry_event;
 	struct sctp_stream_reset_event sn_strreset_event;
+	struct sctp_assoc_reset_event sn_assocreset_event;
+	struct sctp_stream_change_event sn_strchange_event;
+
 };
=20
 /* notification types */
@@ -493,6 +524,9 @@
 #define SCTP_STREAM_RESET_EVENT			0x0009
 #define SCTP_SENDER_DRY_EVENT			0x000a
 #define SCTP_NOTIFICATIONS_STOPPED_EVENT	0x000b	/* we don't send this */
+#define SCTP_ASSOC_RESET_EVENT			0x000c
+#define SCTP_STREAM_CHANGE_EVENT		0x000d
+
 /*
  * socket option structs
  */
@@ -707,19 +741,18 @@
  */
 #define SCTP_MAX_EXPLICT_STR_RESET   1000
=20
-#define SCTP_RESET_LOCAL_RECV  0x0001
-#define SCTP_RESET_LOCAL_SEND  0x0002
-#define SCTP_RESET_BOTH        0x0003
-#define SCTP_RESET_TSN         0x0004
-#define SCTP_RESET_ADD_STREAMS 0x0005
-
-struct sctp_stream_reset {
-	sctp_assoc_t strrst_assoc_id;
-	uint16_t strrst_flags;
-	uint16_t strrst_num_streams;	/* 0 =3D=3D ALL */
-	uint16_t strrst_list[];	/* list if strrst_num_streams is not 0 */
+struct sctp_reset_streams {
+	sctp_assoc_t srs_assoc_id;
+	uint16_t srs_flags;
+	uint16_t srs_number_streams;	/* 0 =3D=3D ALL */
+	uint16_t srs_stream_list[];	/* list if strrst_num_streams is not 0 */
 };
=20
+struct sctp_add_streams {
+	sctp_assoc_t sas_assoc_id;
+	uint16_t sas_instrms;
+	uint16_t sas_outstrms;
+};
=20
 struct sctp_get_nonce_values {
 	sctp_assoc_t gn_assoc_id;
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctp_usrreq.c
--- a/head/sys/netinet/sctp_usrreq.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctp_usrreq.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctp_usrreq.c,v 1.48 2005/03/07 23:26:08 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_usrreq.c 233005 2012-03-15 14:22=
:05Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_usrreq.c 233940 2012-04-06 09:03=
:02Z tuexen $");
 #include <netinet/sctp_os.h>
 #include <sys/proc.h>
 #include <netinet/sctp_pcb.h>
@@ -3581,7 +3581,6 @@
=20
 			SCTP_CHECK_AND_CAST(av, optval, struct sctp_assoc_value, optsize);
 			if ((av->assoc_value !=3D SCTP_SS_DEFAULT) &&
-			    (av->assoc_value !=3D SCTP_SS_DEFAULT) &&
 			    (av->assoc_value !=3D SCTP_SS_ROUND_ROBIN) &&
 			    (av->assoc_value !=3D SCTP_SS_ROUND_ROBIN_PACKET) &&
 			    (av->assoc_value !=3D SCTP_SS_PRIORITY) &&
@@ -4088,17 +4087,52 @@
 			}
 			break;
 		}
-
+	case SCTP_ENABLE_STREAM_RESET:
+		{
+			struct sctp_assoc_value *av;
+			uint8_t set_value =3D 0;
+
+			SCTP_CHECK_AND_CAST(av, optval, struct sctp_assoc_value, optsize);
+			if (av->assoc_value & (~SCTP_ENABLE_VALUE_MASK)) {
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EINVAL);
+				error =3D EINVAL;
+				break;
+			}
+			set_value =3D av->assoc_value & SCTP_ENABLE_VALUE_MASK;
+			SCTP_FIND_STCB(inp, stcb, av->assoc_id);
+			if (stcb) {
+				stcb->asoc.local_strreset_support =3D set_value;
+				SCTP_TCB_UNLOCK(stcb);
+			} else {
+				if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
+				    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) ||
+				    (av->assoc_id =3D=3D SCTP_FUTURE_ASSOC) ||
+				    (av->assoc_id =3D=3D SCTP_ALL_ASSOC)) {
+					SCTP_INP_WLOCK(inp);
+					inp->local_strreset_support =3D set_value;
+					SCTP_INP_WUNLOCK(inp);
+				}
+				if ((av->assoc_id =3D=3D SCTP_CURRENT_ASSOC) ||
+				    (av->assoc_id =3D=3D SCTP_ALL_ASSOC)) {
+					SCTP_INP_RLOCK(inp);
+					LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
+						SCTP_TCB_LOCK(stcb);
+						stcb->asoc.local_strreset_support =3D set_value;
+						SCTP_TCB_UNLOCK(stcb);
+					}
+					SCTP_INP_RUNLOCK(inp);
+				}
+			}
+			break;
+		}
 	case SCTP_RESET_STREAMS:
 		{
-			struct sctp_stream_reset *strrst;
-			uint8_t send_in =3D 0, send_tsn =3D 0, send_out =3D 0,
-			        addstream =3D 0;
-			uint16_t addstrmcnt =3D 0;
-			int i;
-
-			SCTP_CHECK_AND_CAST(strrst, optval, struct sctp_stream_reset, optsize);
-			SCTP_FIND_STCB(inp, stcb, strrst->strrst_assoc_id);
+			struct sctp_reset_streams *strrst;
+			int i, send_out =3D 0;
+			int send_in =3D 0;
+
+			SCTP_CHECK_AND_CAST(strrst, optval, struct sctp_reset_streams, optsize);
+			SCTP_FIND_STCB(inp, stcb, strrst->srs_assoc_id);
=20
 			if (stcb =3D=3D NULL) {
 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOENT);
@@ -4107,13 +4141,19 @@
 			}
 			if (stcb->asoc.peer_supports_strreset =3D=3D 0) {
 				/*
-				 * Peer does not support it, we return
-				 * protocol not supported since this is true
-				 * for this feature and this peer, not the
-				 * socket request in general.
+				 * Peer does not support the chunk type.
 				 */
-				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EPROTONOSU=
PPORT);
-				error =3D EPROTONOSUPPORT;
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EOPNOTSUPP=
);
+				error =3D EOPNOTSUPP;
+				SCTP_TCB_UNLOCK(stcb);
+				break;
+			}
+			if (!(stcb->asoc.local_strreset_support & SCTP_ENABLE_RESET_STREAM_REQ)=
) {
+				/*
+				 * User did not enable the operation.
+				 */
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EPERM);
+				error =3D EPERM;
 				SCTP_TCB_UNLOCK(stcb);
 				break;
 			}
@@ -4123,129 +4163,137 @@
 				SCTP_TCB_UNLOCK(stcb);
 				break;
 			}
-			if (strrst->strrst_flags =3D=3D SCTP_RESET_LOCAL_RECV) {
+			if (strrst->srs_flags & SCTP_STREAM_RESET_INCOMING) {
 				send_in =3D 1;
-			} else if (strrst->strrst_flags =3D=3D SCTP_RESET_LOCAL_SEND) {
+			}
+			if (strrst->srs_flags & SCTP_STREAM_RESET_OUTGOING) {
 				send_out =3D 1;
-			} else if (strrst->strrst_flags =3D=3D SCTP_RESET_BOTH) {
-				send_in =3D 1;
-				send_out =3D 1;
-			} else if (strrst->strrst_flags =3D=3D SCTP_RESET_TSN) {
-				send_tsn =3D 1;
-			} else if (strrst->strrst_flags =3D=3D SCTP_RESET_ADD_STREAMS) {
-				if (send_tsn ||
-				    send_in ||
-				    send_out) {
-					/* We can't do that and add streams */
-					error =3D EINVAL;
-					goto skip_stuff;
-				}
-				if (stcb->asoc.stream_reset_outstanding) {
-					error =3D EBUSY;
-					goto skip_stuff;
-				}
-				addstream =3D 1;
-				/* We allocate here */
-				addstrmcnt =3D strrst->strrst_num_streams;
-				if ((int)(addstrmcnt + stcb->asoc.streamoutcnt) > 0xffff) {
-					/* You can't have more than 64k */
-					error =3D EINVAL;
-					goto skip_stuff;
-				}
-				if ((stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcnt) < addstrmc=
nt) {
-					/* Need to allocate more */
-					struct sctp_stream_out *oldstream;
-					struct sctp_stream_queue_pending *sp,
-					                         *nsp;
-
-					oldstream =3D stcb->asoc.strmout;
-					/* get some more */
-					SCTP_MALLOC(stcb->asoc.strmout, struct sctp_stream_out *,
-					    ((stcb->asoc.streamoutcnt + addstrmcnt) * sizeof(struct sctp_stre=
am_out)),
-					    SCTP_M_STRMO);
-					if (stcb->asoc.strmout =3D=3D NULL) {
-						stcb->asoc.strmout =3D oldstream;
-						error =3D ENOMEM;
-						goto skip_stuff;
-					}
-					/*
-					 * Ok now we proceed with copying
-					 * the old out stuff and
-					 * initializing the new stuff.
-					 */
-					SCTP_TCB_SEND_LOCK(stcb);
-					stcb->asoc.ss_functions.sctp_ss_clear(stcb, &stcb->asoc, 0, 1);
-					for (i =3D 0; i < stcb->asoc.streamoutcnt; i++) {
-						TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
-						stcb->asoc.strmout[i].next_sequence_sent =3D oldstream[i].next_seque=
nce_sent;
-						stcb->asoc.strmout[i].last_msg_incomplete =3D oldstream[i].last_msg_=
incomplete;
-						stcb->asoc.strmout[i].stream_no =3D i;
-						stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], =
&oldstream[i]);
-						/*
-						 * now anything on those
-						 * queues?
-						 */
-						TAILQ_FOREACH_SAFE(sp, &oldstream[i].outqueue, next, nsp) {
-							TAILQ_REMOVE(&oldstream[i].outqueue, sp, next);
-							TAILQ_INSERT_TAIL(&stcb->asoc.strmout[i].outqueue, sp, next);
-						}
-						/*
-						 * Now move assoc pointers
-						 * too
-						 */
-						if (stcb->asoc.last_out_stream =3D=3D &oldstream[i]) {
-							stcb->asoc.last_out_stream =3D &stcb->asoc.strmout[i];
-						}
-						if (stcb->asoc.locked_on_sending =3D=3D &oldstream[i]) {
-							stcb->asoc.locked_on_sending =3D &stcb->asoc.strmout[i];
-						}
-					}
-					/* now the new streams */
-					stcb->asoc.ss_functions.sctp_ss_init(stcb, &stcb->asoc, 1);
-					for (i =3D stcb->asoc.streamoutcnt; i < (stcb->asoc.streamoutcnt + ad=
dstrmcnt); i++) {
-						stcb->asoc.strmout[i].next_sequence_sent =3D 0x0;
-						TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
-						stcb->asoc.strmout[i].stream_no =3D i;
-						stcb->asoc.strmout[i].last_msg_incomplete =3D 0;
-						stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], =
NULL);
-					}
-					stcb->asoc.strm_realoutsize =3D stcb->asoc.streamoutcnt + addstrmcnt;
-					SCTP_FREE(oldstream, SCTP_M_STRMO);
-				}
-				SCTP_TCB_SEND_UNLOCK(stcb);
-				goto skip_stuff;
-			} else {
+			}
+			if ((send_in =3D=3D 0) && (send_out =3D=3D 0)) {
 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EINVAL);
 				error =3D EINVAL;
 				SCTP_TCB_UNLOCK(stcb);
 				break;
 			}
-			for (i =3D 0; i < strrst->strrst_num_streams; i++) {
+			for (i =3D 0; i < strrst->srs_number_streams; i++) {
 				if ((send_in) &&
-
-				    (strrst->strrst_list[i] > stcb->asoc.streamincnt)) {
+				    (strrst->srs_stream_list[i] > stcb->asoc.streamincnt)) {
 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EINVAL);
 					error =3D EINVAL;
-					goto get_out;
+					break;
 				}
 				if ((send_out) &&
-				    (strrst->strrst_list[i] > stcb->asoc.streamoutcnt)) {
+				    (strrst->srs_stream_list[i] > stcb->asoc.streamoutcnt)) {
 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EINVAL);
 					error =3D EINVAL;
-					goto get_out;
-				}
-			}
-	skip_stuff:
+					break;
+				}
+			}
 			if (error) {
-		get_out:
 				SCTP_TCB_UNLOCK(stcb);
 				break;
 			}
-			error =3D sctp_send_str_reset_req(stcb, strrst->strrst_num_streams,
-			    strrst->strrst_list,
-			    send_out, (stcb->asoc.str_reset_seq_in - 3),
-			    send_in, send_tsn, addstream, addstrmcnt);
-
+			error =3D sctp_send_str_reset_req(stcb, strrst->srs_number_streams,
+			    strrst->srs_stream_list,
+			    send_out, send_in, 0, 0, 0, 0, 0);
+
+			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_STRRST_REQ, SCTP_SO_LOCKE=
D);
+			SCTP_TCB_UNLOCK(stcb);
+			break;
+		}
+	case SCTP_ADD_STREAMS:
+		{
+			struct sctp_add_streams *stradd;
+			uint8_t addstream =3D 0;
+			uint16_t add_o_strmcnt =3D 0;
+			uint16_t add_i_strmcnt =3D 0;
+
+			SCTP_CHECK_AND_CAST(stradd, optval, struct sctp_add_streams, optsize);
+			SCTP_FIND_STCB(inp, stcb, stradd->sas_assoc_id);
+			if (stcb =3D=3D NULL) {
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOENT);
+				error =3D ENOENT;
+				break;
+			}
+			if ((stradd->sas_outstrms =3D=3D 0) &&
+			    (stradd->sas_instrms =3D=3D 0)) {
+				error =3D EINVAL;
+				goto skip_stuff;
+			}
+			if (stradd->sas_outstrms) {
+				addstream =3D 1;
+				/* We allocate here */
+				add_o_strmcnt =3D stradd->sas_outstrms;
+				if ((((int)add_o_strmcnt) + ((int)stcb->asoc.streamoutcnt)) > 0x0000ff=
ff) {
+					/* You can't have more than 64k */
+					error =3D EINVAL;
+					goto skip_stuff;
+				}
+			}
+			if (stradd->sas_instrms) {
+				int cnt;
+
+				addstream |=3D 2;
+				/*
+				 * We allocate inside
+				 * sctp_send_str_reset_req()
+				 */
+				add_i_strmcnt =3D stradd->sas_instrms;
+				cnt =3D add_i_strmcnt;
+				cnt +=3D stcb->asoc.streamincnt;
+				if (cnt > 0x0000ffff) {
+					/* You can't have more than 64k */
+					error =3D EINVAL;
+					goto skip_stuff;
+				}
+				if (cnt > (int)stcb->asoc.max_inbound_streams) {
+					/* More than you are allowed */
+					error =3D EINVAL;
+					goto skip_stuff;
+				}
+			}
+			error =3D sctp_send_str_reset_req(stcb, 0, NULL, 0, 0, 0, addstream, ad=
d_o_strmcnt, add_i_strmcnt, 0);
+			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_STRRST_REQ, SCTP_SO_LOCKE=
D);
+	skip_stuff:
+			SCTP_TCB_UNLOCK(stcb);
+			break;
+		}
+	case SCTP_RESET_ASSOC:
+		{
+			uint32_t *value;
+
+			SCTP_CHECK_AND_CAST(value, optval, uint32_t, optsize);
+			SCTP_FIND_STCB(inp, stcb, (sctp_assoc_t) * value);
+			if (stcb =3D=3D NULL) {
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, ENOENT);
+				error =3D ENOENT;
+				break;
+			}
+			if (stcb->asoc.peer_supports_strreset =3D=3D 0) {
+				/*
+				 * Peer does not support the chunk type.
+				 */
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EOPNOTSUPP=
);
+				error =3D EOPNOTSUPP;
+				SCTP_TCB_UNLOCK(stcb);
+				break;
+			}
+			if (!(stcb->asoc.local_strreset_support & SCTP_ENABLE_RESET_ASSOC_REQ))=
 {
+				/*
+				 * User did not enable the operation.
+				 */
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EPERM);
+				error =3D EPERM;
+				SCTP_TCB_UNLOCK(stcb);
+				break;
+			}
+			if (stcb->asoc.stream_reset_outstanding) {
+				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EALREADY);
+				error =3D EALREADY;
+				SCTP_TCB_UNLOCK(stcb);
+				break;
+			}
+			error =3D sctp_send_str_reset_req(stcb, 0, NULL, 0, 0, 1, 0, 0, 0, 0);
 			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_STRRST_REQ, SCTP_SO_LOCKE=
D);
 			SCTP_TCB_UNLOCK(stcb);
 			break;
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctputil.c
--- a/head/sys/netinet/sctputil.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctputil.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
 /* $KAME: sctputil.c,v 1.37 2005/03/07 23:26:09 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctputil.c 230136 2012-01-15 13:35:55=
Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctputil.c 233660 2012-03-29 13:36:53=
Z rrs $");
=20
 #include <netinet/sctp_os.h>
 #include <netinet/sctp_pcb.h>
@@ -978,8 +978,8 @@
 	asoc->free_chunk_cnt =3D 0;
=20
 	asoc->iam_blocking =3D 0;
-
 	asoc->context =3D m->sctp_context;
+	asoc->local_strreset_support =3D m->local_strreset_support;
 	asoc->def_send =3D m->def_send;
 	asoc->delayed_ack =3D TICKS_TO_MSEC(m->sctp_ep.sctp_timeoutticks[SCTP_TIM=
ER_RECV]);
 	asoc->sack_freq =3D m->sctp_ep.sctp_sack_freq;
@@ -3206,8 +3206,127 @@
 }
=20
=20
+void
+sctp_notify_stream_reset_add(struct sctp_tcb *stcb, uint16_t numberin, uin=
t16_t numberout, int flag)
+{
+	struct mbuf *m_notify;
+	struct sctp_queued_to_read *control;
+	struct sctp_stream_change_event *stradd;
+	int len;
+
+	if (sctp_is_feature_off(stcb->sctp_ep, SCTP_PCB_FLAGS_STREAM_RESETEVNT)) {
+		/* event not enabled */
+		return;
+	}
+	if ((stcb->asoc.peer_req_out) && flag) {
+		/* Peer made the request, don't tell the local user */
+		stcb->asoc.peer_req_out =3D 0;
+		return;
+	}
+	stcb->asoc.peer_req_out =3D 0;
+	m_notify =3D sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
+	if (m_notify =3D=3D NULL)
+		/* no space left */
+		return;
+	SCTP_BUF_LEN(m_notify) =3D 0;
+	len =3D sizeof(struct sctp_stream_change_event);
+	if (len > M_TRAILINGSPACE(m_notify)) {
+		/* never enough room */
+		sctp_m_freem(m_notify);
+		return;
+	}
+	stradd =3D mtod(m_notify, struct sctp_stream_change_event *);
+	stradd->strchange_type =3D SCTP_STREAM_CHANGE_EVENT;
+	stradd->strchange_flags =3D flag;
+	stradd->strchange_length =3D len;
+	stradd->strchange_assoc_id =3D sctp_get_associd(stcb);
+	stradd->strchange_instrms =3D numberin;
+	stradd->strchange_outstrms =3D numberout;
+	SCTP_BUF_LEN(m_notify) =3D len;
+	SCTP_BUF_NEXT(m_notify) =3D NULL;
+	if (sctp_sbspace(&stcb->asoc, &stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(=
m_notify)) {
+		/* no space */
+		sctp_m_freem(m_notify);
+		return;
+	}
+	/* append to socket */
+	control =3D sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
+	    0, 0, stcb->asoc.context, 0, 0, 0,
+	    m_notify);
+	if (control =3D=3D NULL) {
+		/* no memory */
+		sctp_m_freem(m_notify);
+		return;
+	}
+	control->spec_flags =3D M_NOTIFICATION;
+	control->length =3D SCTP_BUF_LEN(m_notify);
+	/* not that we need this */
+	control->tail_mbuf =3D m_notify;
+	sctp_add_to_readq(stcb->sctp_ep, stcb,
+	    control,
+	    &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_L=
OCKED);
+}
+
+void
+sctp_notify_stream_reset_tsn(struct sctp_tcb *stcb, uint32_t sending_tsn, =
uint32_t recv_tsn, int flag)
+{
+	struct mbuf *m_notify;
+	struct sctp_queued_to_read *control;
+	struct sctp_assoc_reset_event *strasoc;
+	int len;
+
+	if (sctp_is_feature_off(stcb->sctp_ep, SCTP_PCB_FLAGS_STREAM_RESETEVNT)) {
+		/* event not enabled */
+		return;
+	}
+	m_notify =3D sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
+	if (m_notify =3D=3D NULL)
+		/* no space left */
+		return;
+	SCTP_BUF_LEN(m_notify) =3D 0;
+	len =3D sizeof(struct sctp_assoc_reset_event);
+	if (len > M_TRAILINGSPACE(m_notify)) {
+		/* never enough room */
+		sctp_m_freem(m_notify);
+		return;
+	}
+	strasoc =3D mtod(m_notify, struct sctp_assoc_reset_event *);
+	strasoc->assocreset_type =3D SCTP_ASSOC_RESET_EVENT;
+	strasoc->assocreset_flags =3D flag;
+	strasoc->assocreset_length =3D len;
+	strasoc->assocreset_assoc_id =3D sctp_get_associd(stcb);
+	strasoc->assocreset_local_tsn =3D sending_tsn;
+	strasoc->assocreset_remote_tsn =3D recv_tsn;
+	SCTP_BUF_LEN(m_notify) =3D len;
+	SCTP_BUF_NEXT(m_notify) =3D NULL;
+	if (sctp_sbspace(&stcb->asoc, &stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(=
m_notify)) {
+		/* no space */
+		sctp_m_freem(m_notify);
+		return;
+	}
+	/* append to socket */
+	control =3D sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
+	    0, 0, stcb->asoc.context, 0, 0, 0,
+	    m_notify);
+	if (control =3D=3D NULL) {
+		/* no memory */
+		sctp_m_freem(m_notify);
+		return;
+	}
+	control->spec_flags =3D M_NOTIFICATION;
+	control->length =3D SCTP_BUF_LEN(m_notify);
+	/* not that we need this */
+	control->tail_mbuf =3D m_notify;
+	sctp_add_to_readq(stcb->sctp_ep, stcb,
+	    control,
+	    &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_L=
OCKED);
+}
+
+
+
 static void
-sctp_notify_stream_reset_add(struct sctp_tcb *stcb, int number_entries, in=
t flag)
+sctp_notify_stream_reset(struct sctp_tcb *stcb,
+    int number_entries, uint16_t * list, int flag)
 {
 	struct mbuf *m_notify;
 	struct sctp_queued_to_read *control;
@@ -3231,75 +3350,14 @@
 	}
 	strreset =3D mtod(m_notify, struct sctp_stream_reset_event *);
 	strreset->strreset_type =3D SCTP_STREAM_RESET_EVENT;
-	strreset->strreset_flags =3D SCTP_STRRESET_ADD_STREAM | flag;
-	strreset->strreset_length =3D len;
-	strreset->strreset_assoc_id =3D sctp_get_associd(stcb);
-	strreset->strreset_list[0] =3D number_entries;
-
-	SCTP_BUF_LEN(m_notify) =3D len;
-	SCTP_BUF_NEXT(m_notify) =3D NULL;
-	if (sctp_sbspace(&stcb->asoc, &stcb->sctp_socket->so_rcv) < SCTP_BUF_LEN(=
m_notify)) {
-		/* no space */
-		sctp_m_freem(m_notify);
-		return;
-	}
-	/* append to socket */
-	control =3D sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
-	    0, 0, stcb->asoc.context, 0, 0, 0,
-	    m_notify);
-	if (control =3D=3D NULL) {
-		/* no memory */
-		sctp_m_freem(m_notify);
-		return;
-	}
-	control->spec_flags =3D M_NOTIFICATION;
-	control->length =3D SCTP_BUF_LEN(m_notify);
-	/* not that we need this */
-	control->tail_mbuf =3D m_notify;
-	sctp_add_to_readq(stcb->sctp_ep, stcb,
-	    control,
-	    &stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, SCTP_SO_NOT_L=
OCKED);
-}
-
-
-static void
-sctp_notify_stream_reset(struct sctp_tcb *stcb,
-    int number_entries, uint16_t * list, int flag)
-{
-	struct mbuf *m_notify;
-	struct sctp_queued_to_read *control;
-	struct sctp_stream_reset_event *strreset;
-	int len;
-
-	if (sctp_is_feature_off(stcb->sctp_ep, SCTP_PCB_FLAGS_STREAM_RESETEVNT)) {
-		/* event not enabled */
-		return;
-	}
-	m_notify =3D sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
-	if (m_notify =3D=3D NULL)
-		/* no space left */
-		return;
-	SCTP_BUF_LEN(m_notify) =3D 0;
-	len =3D sizeof(struct sctp_stream_reset_event) + (number_entries * sizeof=
(uint16_t));
-	if (len > M_TRAILINGSPACE(m_notify)) {
-		/* never enough room */
-		sctp_m_freem(m_notify);
-		return;
-	}
-	strreset =3D mtod(m_notify, struct sctp_stream_reset_event *);
-	strreset->strreset_type =3D SCTP_STREAM_RESET_EVENT;
-	if (number_entries =3D=3D 0) {
-		strreset->strreset_flags =3D flag | SCTP_STRRESET_ALL_STREAMS;
-	} else {
-		strreset->strreset_flags =3D flag | SCTP_STRRESET_STREAM_LIST;
-	}
+	strreset->strreset_flags =3D flag;
 	strreset->strreset_length =3D len;
 	strreset->strreset_assoc_id =3D sctp_get_associd(stcb);
 	if (number_entries) {
 		int i;
=20
 		for (i =3D 0; i < number_entries; i++) {
-			strreset->strreset_list[i] =3D ntohs(list[i]);
+			strreset->strreset_stream_list[i] =3D ntohs(list[i]);
 		}
 	}
 	SCTP_BUF_LEN(m_notify) =3D len;
@@ -3439,27 +3497,19 @@
 		break;
 	case SCTP_NOTIFY_HB_RESP:
 		break;
-	case SCTP_NOTIFY_STR_RESET_INSTREAM_ADD_OK:
-		sctp_notify_stream_reset_add(stcb, error, SCTP_STRRESET_INBOUND_STR);
-		break;
-	case SCTP_NOTIFY_STR_RESET_ADD_OK:
-		sctp_notify_stream_reset_add(stcb, error, SCTP_STRRESET_OUTBOUND_STR);
-		break;
-	case SCTP_NOTIFY_STR_RESET_ADD_FAIL:
-		sctp_notify_stream_reset_add(stcb, error, (SCTP_STRRESET_FAILED | SCTP_S=
TRRESET_OUTBOUND_STR));
-		break;
-
 	case SCTP_NOTIFY_STR_RESET_SEND:
-		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data), SCTP_STRRESET=
_OUTBOUND_STR);
+		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data), SCTP_STREAM_R=
ESET_INCOMING);
 		break;
 	case SCTP_NOTIFY_STR_RESET_RECV:
-		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data), SCTP_STRRESET=
_INBOUND_STR);
+		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data), SCTP_STREAM_R=
ESET_OUTGOING);
 		break;
 	case SCTP_NOTIFY_STR_RESET_FAILED_OUT:
-		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data), (SCTP_STRRESE=
T_OUTBOUND_STR | SCTP_STRRESET_FAILED));
+		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data),
+		    (SCTP_STREAM_RESET_OUTGOING | SCTP_STREAM_RESET_INCOMING));
 		break;
 	case SCTP_NOTIFY_STR_RESET_FAILED_IN:
-		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data), (SCTP_STRRESE=
T_INBOUND_STR | SCTP_STRRESET_FAILED));
+		sctp_notify_stream_reset(stcb, error, ((uint16_t *) data),
+		    (SCTP_STREAM_RESET_OUTGOING | SCTP_STREAM_RESET_INCOMING));
 		break;
 	case SCTP_NOTIFY_ASCONF_ADD_IP:
 		sctp_notify_peer_addr_change(stcb, SCTP_ADDR_ADDED, data,
@@ -5443,28 +5493,31 @@
 	}
 #endif
 	if (fromlen && from) {
-		struct sockaddr *to;
-
+		cp_len =3D min((size_t)fromlen, (size_t)control->whoFrom->ro._l_addr.sa.=
sa_len);
+		switch (control->whoFrom->ro._l_addr.sa.sa_family) {
+#ifdef INET6
+		case AF_INET6:
+			((struct sockaddr_in6 *)from)->sin6_port =3D control->port_from;
+			break;
+#endif
 #ifdef INET
-		cp_len =3D min((size_t)fromlen, (size_t)control->whoFrom->ro._l_addr.sin=
.sin_len);
+		case AF_INET:
+			((struct sockaddr_in *)from)->sin_port =3D control->port_from;
+			break;
+#endif
+		default:
+			break;
+		}
 		memcpy(from, &control->whoFrom->ro._l_addr, cp_len);
-		((struct sockaddr_in *)from)->sin_port =3D control->port_from;
-#else
-		/* No AF_INET use AF_INET6 */
-		cp_len =3D min((size_t)fromlen, (size_t)control->whoFrom->ro._l_addr.sin=
6.sin6_len);
-		memcpy(from, &control->whoFrom->ro._l_addr, cp_len);
-		((struct sockaddr_in6 *)from)->sin6_port =3D control->port_from;
-#endif
-
-		to =3D from;
+
 #if defined(INET) && defined(INET6)
 		if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NEEDS_MAPPED_V4)) &&
-		    (to->sa_family =3D=3D AF_INET) &&
+		    (from->sa_family =3D=3D AF_INET) &&
 		    ((size_t)fromlen >=3D sizeof(struct sockaddr_in6))) {
 			struct sockaddr_in *sin;
 			struct sockaddr_in6 sin6;
=20
-			sin =3D (struct sockaddr_in *)to;
+			sin =3D (struct sockaddr_in *)from;
 			bzero(&sin6, sizeof(sin6));
 			sin6.sin6_family =3D AF_INET6;
 			sin6.sin6_len =3D sizeof(struct sockaddr_in6);
@@ -5473,15 +5526,15 @@
 			    &sin6.sin6_addr.s6_addr32[3],
 			    sizeof(sin6.sin6_addr.s6_addr32[3]));
 			sin6.sin6_port =3D sin->sin_port;
-			memcpy(from, (caddr_t)&sin6, sizeof(sin6));
+			memcpy(from, &sin6, sizeof(struct sockaddr_in6));
 		}
 #endif
 #if defined(INET6)
 		{
-			struct sockaddr_in6 lsa6, *to6;
-
-			to6 =3D (struct sockaddr_in6 *)to;
-			sctp_recover_scope_mac(to6, (&lsa6));
+			struct sockaddr_in6 lsa6, *from6;
+
+			from6 =3D (struct sockaddr_in6 *)from;
+			sctp_recover_scope_mac(from6, (&lsa6));
 		}
 #endif
 	}
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/sctputil.h
--- a/head/sys/netinet/sctputil.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/sctputil.h	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
 /* $KAME: sctputil.h,v 1.15 2005/03/06 16:04:19 itojun Exp $	 */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctputil.h 228653 2011-12-17 19:21:40=
Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctputil.h 233660 2012-03-29 13:36:53=
Z rrs $");
 #ifndef __sctputil_h__
 #define __sctputil_h__
=20
@@ -88,6 +88,12 @@
 void sctp_fill_random_store(struct sctp_pcb *);
=20
 void
+sctp_notify_stream_reset_add(struct sctp_tcb *stcb, uint16_t numberin,
+    uint16_t numberout, int flag);
+void
+     sctp_notify_stream_reset_tsn(struct sctp_tcb *stcb, uint32_t sending_=
tsn, uint32_t recv_tsn, int flag);
+
+void
 sctp_timer_start(int, struct sctp_inpcb *, struct sctp_tcb *,
     struct sctp_nets *);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/tcp_input.c
--- a/head/sys/netinet/tcp_input.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/tcp_input.c	Tue Apr 17 11:51:51 2012 +0300
@@ -48,7 +48,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/tcp_input.c 231767 2012-02-15 16:09:5=
6Z bz $");
+__FBSDID("$FreeBSD: head/sys/netinet/tcp_input.c 234342 2012-04-16 13:49:0=
3Z glebius $");
=20
 #include "opt_ipfw.h"		/* for ipfw_fwd	*/
 #include "opt_inet.h"
@@ -3288,22 +3288,19 @@
  * are present.  Store the upper limit of the length of options plus
  * data in maxopd.
  *
- * In case of T/TCP, we call this routine during implicit connection
- * setup as well (offer =3D -1), to initialize maxseg from the cached
- * MSS of our peer.
- *
  * NOTE that this routine is only called when we process an incoming
- * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
+ * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
+ * settings are handled in tcp_mssopt().
  */
 void
-tcp_mss_update(struct tcpcb *tp, int offer,
+tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
     struct hc_metrics_lite *metricptr, int *mtuflags)
 {
 	int mss =3D 0;
 	u_long maxmtu =3D 0;
 	struct inpcb *inp =3D tp->t_inpcb;
 	struct hc_metrics_lite metrics;
-	int origoffer =3D offer;
+	int origoffer;
 #ifdef INET6
 	int isipv6 =3D ((inp->inp_vflag & INP_IPV6) !=3D 0) ? 1 : 0;
 	size_t min_protoh =3D isipv6 ?
@@ -3315,6 +3312,12 @@
=20
 	INP_WLOCK_ASSERT(tp->t_inpcb);
=20
+	if (mtuoffer !=3D -1) {
+		KASSERT(offer =3D=3D -1, ("%s: conflict", __func__));
+		offer =3D mtuoffer - min_protoh;
+	}
+	origoffer =3D offer;
+
 	/* Initialize. */
 #ifdef INET6
 	if (isipv6) {
@@ -3473,7 +3476,7 @@
=20
 	KASSERT(tp !=3D NULL, ("%s: tp =3D=3D NULL", __func__));
 =09
-	tcp_mss_update(tp, offer, &metrics, &mtuflags);
+	tcp_mss_update(tp, offer, -1, &metrics, &mtuflags);
=20
 	mss =3D tp->t_maxseg;
 	inp =3D tp->t_inpcb;
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/tcp_output.c
--- a/head/sys/netinet/tcp_output.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/tcp_output.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/tcp_output.c 231767 2012-02-15 16:09:=
56Z bz $");
+__FBSDID("$FreeBSD: head/sys/netinet/tcp_output.c 234342 2012-04-16 13:49:=
03Z glebius $");
=20
 #include "opt_inet.h"
 #include "opt_inet6.h"
@@ -1293,7 +1293,7 @@
 			 */
 			if (tso)
 				tp->t_flags &=3D ~TF_TSO;
-			tcp_mtudisc(tp->t_inpcb, 0);
+			tcp_mtudisc(tp->t_inpcb, -1);
 			return (0);
 		case EHOSTDOWN:
 		case EHOSTUNREACH:
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/tcp_subr.c
--- a/head/sys/netinet/tcp_subr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/tcp_subr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/tcp_subr.c 231852 2012-02-17 02:39:58=
Z bz $");
+__FBSDID("$FreeBSD: head/sys/netinet/tcp_subr.c 234342 2012-04-16 13:49:03=
Z glebius $");
=20
 #include "opt_compat.h"
 #include "opt_inet.h"
@@ -222,6 +222,7 @@
 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
=20
 static struct inpcb *tcp_notify(struct inpcb *, int);
+static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
 static char *	tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
 		    void *ip4hdr, const void *ip6hdr);
=20
@@ -1337,7 +1338,7 @@
 		return;
=20
 	if (cmd =3D=3D PRC_MSGSIZE)
-		notify =3D tcp_mtudisc;
+		notify =3D tcp_mtudisc_notify;
 	else if (V_icmp_may_rst && (cmd =3D=3D PRC_UNREACH_ADMIN_PROHIB ||
 		cmd =3D=3D PRC_UNREACH_PORT || cmd =3D=3D PRC_TIMXCEED_INTRANS) && ip)
 		notify =3D tcp_drop_syn_sent;
@@ -1410,9 +1411,10 @@
 					     */
 					    if (mtu <=3D tcp_maxmtu(&inc, NULL))
 						tcp_hc_updatemtu(&inc, mtu);
-					}
-
-					inp =3D (*notify)(inp, inetctlerrmap[cmd]);
+					    tcp_mtudisc(inp, mtu);
+					} else
+						inp =3D (*notify)(inp,
+						    inetctlerrmap[cmd]);
 				}
 			}
 			if (inp !=3D NULL)
@@ -1452,7 +1454,7 @@
 		return;
=20
 	if (cmd =3D=3D PRC_MSGSIZE)
-		notify =3D tcp_mtudisc;
+		notify =3D tcp_mtudisc_notify;
 	else if (!PRC_IS_REDIRECT(cmd) &&
 		 ((unsigned)cmd >=3D PRC_NCMDS || inet6ctlerrmap[cmd] =3D=3D 0))
 		return;
@@ -1653,12 +1655,19 @@
=20
 /*
  * When `need fragmentation' ICMP is received, update our idea of the MSS
- * based on the new value in the route.  Also nudge TCP to send something,
- * since we know the packet we just sent was dropped.
+ * based on the new value. Also nudge TCP to send something, since we
+ * know the packet we just sent was dropped.
  * This duplicates some code in the tcp_mss() function in tcp_input.c.
  */
+static struct inpcb *
+tcp_mtudisc_notify(struct inpcb *inp, int error)
+{
+
+	return (tcp_mtudisc(inp, -1));
+}
+
 struct inpcb *
-tcp_mtudisc(struct inpcb *inp, int errno)
+tcp_mtudisc(struct inpcb *inp, int mtuoffer)
 {
 	struct tcpcb *tp;
 	struct socket *so;
@@ -1671,7 +1680,7 @@
 	tp =3D intotcpcb(inp);
 	KASSERT(tp !=3D NULL, ("tcp_mtudisc: tp =3D=3D NULL"));
=20
-	tcp_mss_update(tp, -1, NULL, NULL);
+	tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
  =20
 	so =3D inp->inp_socket;
 	SOCKBUF_LOCK(&so->so_snd);
@@ -2184,7 +2193,7 @@
 	return (error);
 }
=20
-SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
+SYSCTL_VNET_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
     CTLTYPE_STRUCT|CTLFLAG_WR|CTLFLAG_SKIP, NULL,
     0, sysctl_drop, "", "Drop TCP connection");
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/tcp_var.h
--- a/head/sys/netinet/tcp_var.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/tcp_var.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)tcp_var.h	8.4 (Berkeley) 5/24/95
- * $FreeBSD: head/sys/netinet/tcp_var.h 231025 2012-02-05 16:53:02Z glebiu=
s $
+ * $FreeBSD: head/sys/netinet/tcp_var.h 234342 2012-04-16 13:49:03Z glebiu=
s $
  */
=20
 #ifndef _NETINET_TCP_VAR_H_
@@ -675,7 +675,8 @@
 void	 tcp_input(struct mbuf *, int);
 u_long	 tcp_maxmtu(struct in_conninfo *, int *);
 u_long	 tcp_maxmtu6(struct in_conninfo *, int *);
-void	 tcp_mss_update(struct tcpcb *, int, struct hc_metrics_lite *, int *);
+void	 tcp_mss_update(struct tcpcb *, int, int, struct hc_metrics_lite *,
+	    int *);
 void	 tcp_mss(struct tcpcb *, int);
 int	 tcp_mssopt(struct in_conninfo *);
 struct inpcb *
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/udp_usrreq.c
--- a/head/sys/netinet/udp_usrreq.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/udp_usrreq.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/udp_usrreq.c 225044 2011-08-20 17:05:=
11Z bz $");
+__FBSDID("$FreeBSD: head/sys/netinet/udp_usrreq.c 233554 2012-03-27 15:14:=
29Z bz $");
=20
 #include "opt_ipfw.h"
 #include "opt_inet.h"
@@ -105,9 +105,9 @@
  * packets that would otherwise be discarded due to bad checksums, and may
  * cause problems (especially for NFS data blocks).
  */
-static int	udp_cksum =3D 1;
-SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW, &udp_cksu=
m,
-    0, "compute udp checksum");
+VNET_DEFINE(int, udp_cksum) =3D 1;
+SYSCTL_VNET_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW,
+    &VNET_NAME(udp_cksum), 0, "compute udp checksum");
=20
 int	udp_log_in_vain =3D 0;
 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
@@ -1212,7 +1212,7 @@
 	/*
 	 * Set up checksum and output datagram.
 	 */
-	if (udp_cksum) {
+	if (V_udp_cksum) {
 		if (inp->inp_flags & INP_ONESBCAST)
 			faddr.s_addr =3D INADDR_BROADCAST;
 		ui->ui_sum =3D in_pseudo(ui->ui_src.s_addr, faddr.s_addr,
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet/udp_var.h
--- a/head/sys/netinet/udp_var.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet/udp_var.h	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)udp_var.h	8.1 (Berkeley) 6/10/93
- * $FreeBSD: head/sys/netinet/udp_var.h 226431 2011-10-16 10:58:00Z ed $
+ * $FreeBSD: head/sys/netinet/udp_var.h 233554 2012-03-27 15:14:29Z bz $
  */
=20
 #ifndef _NETINET_UDP_VAR_H_
@@ -139,8 +139,10 @@
=20
 extern u_long			udp_sendspace;
 extern u_long			udp_recvspace;
+VNET_DECLARE(int, udp_cksum);
 VNET_DECLARE(struct udpstat, udpstat);
 VNET_DECLARE(int, udp_blackhole);
+#define	V_udp_cksum		VNET(udp_cksum)
 #define	V_udpstat		VNET(udpstat)
 #define	V_udp_blackhole		VNET(udp_blackhole)
 extern int			udp_log_in_vain;
diff -r 428842767fa6 -r f2935497fa04 head/sys/netinet6/in6_pcb.c
--- a/head/sys/netinet6/in6_pcb.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/netinet6/in6_pcb.c	Tue Apr 17 11:51:51 2012 +0300
@@ -65,7 +65,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet6/in6_pcb.c 227449 2011-11-11 14:09:09=
Z trociny $");
+__FBSDID("$FreeBSD: head/sys/netinet6/in6_pcb.c 233272 2012-03-21 08:43:38=
Z glebius $");
=20
 #include "opt_inet.h"
 #include "opt_inet6.h"
@@ -245,8 +245,8 @@
 				if (tw =3D=3D NULL ||
 				    (reuseport & tw->tw_so_options) =3D=3D 0)
 					return (EADDRINUSE);
-			} else if (t && (reuseport & t->inp_socket->so_options)
-			    =3D=3D 0) {
+			} else if (t && (reuseport =3D=3D 0 ||
+			    (t->inp_flags2 & INP_REUSEPORT) =3D=3D 0)) {
 				return (EADDRINUSE);
 			}
 #ifdef INET
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/infiniband/core/=
addr.c
--- a/head/sys/ofed/drivers/infiniband/core/addr.c	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/sys/ofed/drivers/infiniband/core/addr.c	Tue Apr 17 11:51:51 2012=
 +0300
@@ -136,6 +136,7 @@
 	}
=20
 	switch (addr->sa_family) {
+#ifdef INET
 	case AF_INET:
 		dev =3D ip_dev_find(NULL,
 			((struct sockaddr_in *) addr)->sin_addr.s_addr);
@@ -146,6 +147,7 @@
 		ret =3D rdma_copy_addr(dev_addr, dev, NULL);
 		dev_put(dev);
 		break;
+#endif
=20
 #if defined(INET6)
 	case AF_INET6:
@@ -346,7 +348,9 @@
 	struct sockaddr_in6 *sin6;
 	struct ifaddr *ifa;
 	struct ifnet *ifp;
+#if defined(INET) || defined(INET6)
 	struct llentry *lle;
+#endif
 	struct rtentry *rte;
 	in_port_t port;
 	u_char edst[MAX_ADDR_LEN];
@@ -365,6 +369,7 @@
 	ifp =3D NULL;
 	rte =3D NULL;
 	switch (dst_in->sa_family) {
+#ifdef INET
 	case AF_INET:
 		sin =3D (struct sockaddr_in *)dst_in;
 		if (sin->sin_addr.s_addr =3D=3D INADDR_BROADCAST)
@@ -383,6 +388,7 @@
 		} else
 			src_in =3D NULL;=20
 		break;
+#endif
 #ifdef INET6
 	case AF_INET6:
 		sin6 =3D (struct sockaddr_in6 *)dst_in;
@@ -459,12 +465,21 @@
 	/*
 	 * Resolve the link local address.
 	 */
+	switch (dst_in->sa_family) {
+#ifdef INET
+	case AF_INET:
+		error =3D arpresolve(ifp, rte, NULL, dst_in, edst, &lle);
+		break;
+#endif
 #ifdef INET6
-	if (dst_in->sa_family =3D=3D AF_INET6)
+	case AF_INET6:
 		error =3D nd6_storelladdr(ifp, NULL, dst_in, (u_char *)edst, &lle);
-	else
+		break;
 #endif
-		error =3D arpresolve(ifp, rte, NULL, dst_in, edst, &lle);
+	default:
+		/* XXX: Shouldn't happen. */
+		error =3D -EINVAL;
+	}
 	RTFREE(rte);
 	if (error =3D=3D 0)
 		return rdma_copy_addr(addr, ifp, edst);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/infiniband/core/=
cma.c
--- a/head/sys/ofed/drivers/infiniband/core/cma.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/sys/ofed/drivers/infiniband/core/cma.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -96,7 +96,9 @@
 static DEFINE_IDR(tcp_ps);
 static DEFINE_IDR(udp_ps);
 static DEFINE_IDR(ipoib_ps);
+#if defined(INET)
 static int next_port;
+#endif
=20
 struct cma_device {
 	struct list_head	list;
@@ -2137,6 +2139,7 @@
=20
 static int cma_alloc_any_port(struct idr *ps, struct rdma_id_private *id_p=
riv)
 {
+#if defined(INET)
 	struct rdma_bind_list *bind_list;
 	int port, ret, low, high;
=20
@@ -2178,6 +2181,9 @@
 err1:
 	kfree(bind_list);
 	return ret;
+#else
+	return -ENOSPC;
+#endif
 }
=20
 static int cma_use_port(struct idr *ps, struct rdma_id_private *id_priv)
@@ -2919,9 +2925,13 @@
 static void cma_set_mgid(struct rdma_id_private *id_priv,
 			 struct sockaddr *addr, union ib_gid *mgid)
 {
+#if defined(INET) || defined(INET6)
 	unsigned char mc_map[MAX_ADDR_LEN];
 	struct rdma_dev_addr *dev_addr =3D &id_priv->id.route.addr.dev_addr;
+#endif
+#ifdef INET
 	struct sockaddr_in *sin =3D (struct sockaddr_in *) addr;
+#endif
 #ifdef INET6
 	struct sockaddr_in6 *sin6 =3D (struct sockaddr_in6 *) addr;
 #endif
@@ -2940,11 +2950,13 @@
 			mc_map[7] =3D 0x01;	/* Use RDMA CM signature */
 		*mgid =3D *(union ib_gid *) (mc_map + 4);
 #endif
+#ifdef INET
 	} else {
 		ip_ib_mc_map(sin->sin_addr.s_addr, dev_addr->broadcast, mc_map);
 		if (id_priv->id.ps =3D=3D RDMA_PS_UDP)
 			mc_map[7] =3D 0x01;	/* Use RDMA CM signature */
 		*mgid =3D *(union ib_gid *) (mc_map + 4);
+#endif
 	}
 }
=20
@@ -3347,12 +3359,15 @@
=20
 static int cma_init(void)
 {
-	int ret, low, high, remaining;
+	int ret;
+#if defined(INET)
+	int low, high, remaining;
=20
 	get_random_bytes(&next_port, sizeof next_port);
 	inet_get_local_port_range(&low, &high);
 	remaining =3D (high - low) + 1;
 	next_port =3D ((unsigned int) next_port % remaining) + low;
+#endif
=20
 	cma_wq =3D create_singlethread_workqueue("rdma_cm");
 	if (!cma_wq)
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/infiniband/ulp/i=
poib/ipoib_cm.c
--- a/head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_cm.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_cm.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -682,7 +682,6 @@
=20
 	/* FIXME: is this right? Shouldn't we only increment on success? */
 	++dev->if_opackets;
-	dev->if_obytes +=3D tx_req->mb->m_pkthdr.len;
=20
 	m_freem(tx_req->mb);
=20
@@ -1248,7 +1247,9 @@
 						   cm.mb_task);
 	struct mbuf *mb;
 	unsigned long flags;
+#if defined(INET) || defined(INET6)
 	unsigned mtu =3D priv->mcast_mtu;
+#endif
 	uint16_t proto;
=20
 	spin_lock_irqsave(&priv->lock, flags);
@@ -1261,14 +1262,20 @@
=20
 		proto =3D htons(*mtod(mb, uint16_t *));
 		m_adj(mb, IPOIB_ENCAP_LEN);
-		if (proto =3D=3D ETHERTYPE_IP)
+		switch (proto) {
+#if defined(INET)
+		case ETHERTYPE_IP:
 			icmp_error(mb, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0, mtu);
+			break;
+#endif
 #if defined(INET6)
-		else if (proto =3D=3D ETHERTYPE_IPV6)
+		case ETHERTYPE_IPV6:
 			icmp6_error(mb, ICMP6_PACKET_TOO_BIG, 0, mtu);
+			break;
 #endif
-		else
+		default:
 			m_freem(mb);
+		}
=20
 		spin_lock_irqsave(&priv->lock, flags);
 	}
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/infiniband/ulp/i=
poib/ipoib_ib.c
--- a/head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_ib.c	Tue Apr 17 11:3=
6:47 2012 +0300
+++ b/head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_ib.c	Tue Apr 17 11:5=
1:51 2012 +0300
@@ -345,7 +345,6 @@
 	ipoib_dma_unmap_tx(priv->ca, tx_req);
=20
 	++dev->if_opackets;
-	dev->if_obytes +=3D tx_req->mb->m_pkthdr.len;
=20
 	m_freem(tx_req->mb);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/infiniband/ulp/i=
poib/ipoib_main.c
--- a/head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c	Tue Apr 17 11=
:36:47 2012 +0300
+++ b/head/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c	Tue Apr 17 11=
:51:51 2012 +0300
@@ -876,7 +876,7 @@
 	dev->if_output =3D ipoib_output;
 	dev->if_input =3D ipoib_input;
 	dev->if_resolvemulti =3D ipoib_resolvemulti;
-	dev->if_baudrate =3D IF_Gbps(10LL);
+	dev->if_baudrate =3D IF_Gbps(10UL);
 	dev->if_broadcastaddr =3D priv->broadcastaddr;
 	dev->if_snd.ifq_maxlen =3D ipoib_sendq_size * 2;
 	sdl =3D (struct sockaddr_dl *)dev->if_addr->ifa_addr;
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/net/mlx4/en_frag=
.c
--- a/head/sys/ofed/drivers/net/mlx4/en_frag.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/ofed/drivers/net/mlx4/en_frag.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -31,8 +31,11 @@
  *
  */
=20
+#include "opt_inet.h"
 #include "mlx4_en.h"
=20
+#ifdef INET
+
 #include <net/ethernet.h>
 #include <netinet/ip.h>
 #include <machine/in_cksum.h>
@@ -186,3 +189,4 @@
 			flush_session(priv, session, IP_MF);
 	}
 }
+#endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/net/mlx4/en_netd=
ev.c
--- a/head/sys/ofed/drivers/net/mlx4/en_netdev.c	Tue Apr 17 11:36:47 2012 +=
0300
+++ b/head/sys/ofed/drivers/net/mlx4/en_netdev.c	Tue Apr 17 11:51:51 2012 +=
0300
@@ -991,12 +991,20 @@
 	active |=3D IFM_FDX;
 	trans_type =3D priv->port_state.transciver;
 	/* XXX I don't know all of the transceiver values. */
-	if (priv->port_state.link_speed =3D=3D 1000)
+	switch (priv->port_state.link_speed) {
+	case 1000:
 		active |=3D IFM_1000_T;
-	else if (trans_type > 0 && trans_type <=3D 0xC)
-		active |=3D IFM_10G_SR;
-	else if (trans_type =3D=3D 0x80 || trans_type =3D=3D 0)
-		active |=3D IFM_10G_CX4;
+		break;
+	case 10000:
+		if (trans_type > 0 && trans_type <=3D 0xC)
+			active |=3D IFM_10G_SR;
+		else if (trans_type =3D=3D 0x80 || trans_type =3D=3D 0)
+			active |=3D IFM_10G_CX4;
+		break;
+	case 40000:
+		active |=3D IFM_40G_CR4;
+		break;
+	}
 	if (priv->prof->tx_pause)
 		active |=3D IFM_ETH_TXPAUSE;
 	if (priv->prof->rx_pause)
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/net/mlx4/en_port=
.c
--- a/head/sys/ofed/drivers/net/mlx4/en_port.c	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/ofed/drivers/net/mlx4/en_port.c	Tue Apr 17 11:51:51 2012 +03=
00
@@ -152,11 +152,21 @@
 	/* This command is always accessed from Ethtool context
 	 * already synchronized, no need in locking */
 	state->link_state =3D !!(qport_context->link_up & MLX4_EN_LINK_UP_MASK);
-	if ((qport_context->link_speed & MLX4_EN_SPEED_MASK) =3D=3D
-	    MLX4_EN_1G_SPEED)
+	switch (qport_context->link_speed & MLX4_EN_SPEED_MASK) {
+	case MLX4_EN_1G_SPEED:
 		state->link_speed =3D 1000;
-	else
+		break;
+	case MLX4_EN_10G_SPEED_XAUI:
+	case MLX4_EN_10G_SPEED_XFI:
 		state->link_speed =3D 10000;
+		break;
+	case MLX4_EN_40G_SPEED:
+		state->link_speed =3D 40000;
+		break;
+	default:
+		state->link_speed =3D -1;
+		break;
+	}
 	state->transciver =3D qport_context->transceiver;
 	if (be32_to_cpu(qport_context->transceiver_code_hi) & 0x400)
 		state->transciver =3D 0x80;
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/net/mlx4/en_port=
.h
--- a/head/sys/ofed/drivers/net/mlx4/en_port.h	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/sys/ofed/drivers/net/mlx4/en_port.h	Tue Apr 17 11:51:51 2012 +03=
00
@@ -85,6 +85,14 @@
 	MLX4_MCAST_ENABLE       =3D 2,
 };
=20
+enum {
+	MLX4_EN_1G_SPEED	=3D 0x02,
+	MLX4_EN_10G_SPEED_XFI	=3D 0x01,
+	MLX4_EN_10G_SPEED_XAUI	=3D 0x00,
+	MLX4_EN_40G_SPEED	=3D 0x40,
+	MLX4_EN_OTHER_SPEED	=3D 0x0f,
+};
+
 struct mlx4_en_query_port_context {
 	u8 link_up;
 #define MLX4_EN_LINK_UP_MASK	0x80
@@ -92,8 +100,7 @@
 	__be16 mtu;
 	u8 reserved2;
 	u8 link_speed;
-#define MLX4_EN_SPEED_MASK	0x3
-#define MLX4_EN_1G_SPEED	0x2
+#define MLX4_EN_SPEED_MASK	0x43
 	u16 reserved3[5];
 	__be64 mac;
 	u8 transceiver;
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/drivers/net/mlx4/en_rx.c
--- a/head/sys/ofed/drivers/net/mlx4/en_rx.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ofed/drivers/net/mlx4/en_rx.c	Tue Apr 17 11:51:51 2012 +0300
@@ -31,6 +31,7 @@
  *
  */
=20
+#include "opt_inet.h"
 #include "mlx4_en.h"
=20
 #include <linux/mlx4/cq.h>
@@ -287,6 +288,7 @@
 		/* Initailize all descriptors */
 		for (i =3D 0; i < ring->size; i++)
 			mlx4_en_init_rx_desc(priv, ring, i);
+#ifdef INET
 		/* Configure lro mngr */
 		if (priv->dev->if_capenable & IFCAP_LRO) {
 			if (tcp_lro_init(&ring->lro))
@@ -294,6 +296,7 @@
 			else
 				ring->lro.ifp =3D priv->dev;
 		}
+#endif
 	}
 	err =3D mlx4_en_fill_rx_buffers(priv);
 	if (err)
@@ -330,7 +333,9 @@
 void mlx4_en_deactivate_rx_ring(struct mlx4_en_priv *priv,
 				struct mlx4_en_rx_ring *ring)
 {
+#ifdef INET
 	tcp_lro_free(&ring->lro);
+#endif
 	mlx4_en_free_rx_buf(priv, ring);
 	if (ring->stride <=3D TXBB_SIZE)
 		ring->buf -=3D TXBB_SIZE;
@@ -446,7 +451,9 @@
 	struct mbuf **mb_list;
 	struct mlx4_en_rx_desc *rx_desc;
 	struct mbuf *mb;
+#ifdef INET
 	struct lro_entry *queued;
+#endif
 	int index;
 	unsigned int length;
 	int polled =3D 0;
@@ -515,22 +522,26 @@
 			 * - without IP options
 			 * - not an IP fragment
 			 */
+#ifdef INET
 			if (mlx4_en_can_lro(cqe->status) &&
 			    (dev->if_capenable & IFCAP_LRO)) {
 				if (ring->lro.lro_cnt !=3D 0 &&
 				    tcp_lro_rx(&ring->lro, mb, 0) =3D=3D 0)
 					goto next;
 			}
+#endif
=20
 			/* LRO not possible, complete processing here */
 			INC_PERF_COUNTER(priv->pstats.lro_misses);
 		} else {
 			mb->m_pkthdr.csum_flags =3D 0;
 			priv->port_stats.rx_chksum_none++;
+#ifdef INET
 			if (priv->ip_reasm &&
 			    cqe->status & cpu_to_be16(MLX4_CQE_STATUS_IPV4) &&
 			    !mlx4_en_rx_frags(priv, ring, mb, cqe))
 				goto next;
+#endif
 		}
=20
 		/* Push it up the stack */
@@ -545,11 +556,13 @@
 	}
 	/* Flush all pending IP reassembly sessions */
 out:
+#ifdef INET
 	mlx4_en_flush_frags(priv, ring);
 	while ((queued =3D SLIST_FIRST(&ring->lro.lro_active)) !=3D NULL) {
 		SLIST_REMOVE_HEAD(&ring->lro.lro_active, next);
 		tcp_lro_flush(&ring->lro, queued);
 	}
+#endif
 	AVG_PERF_COUNTER(priv->pstats.rx_coal_avg, polled);
 	mlx4_cq_set_ci(&cq->mcq);
 	wmb(); /* ensure HW sees CQ consumer before we post new buffers */
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/include/linux/in.h
--- a/head/sys/ofed/include/linux/in.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ofed/include/linux/in.h	Tue Apr 17 11:51:51 2012 +0300
@@ -28,6 +28,8 @@
 #ifndef	_LINUX_IN_H_
 #define	_LINUX_IN_H_
=20
+#include "opt_inet.h"
+
 #include <netinet/in.h>
 #include <asm/byteorder.h>
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/include/linux/in6.h
--- a/head/sys/ofed/include/linux/in6.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ofed/include/linux/in6.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,8 +29,6 @@
 #ifndef	_LINUX_IN6_H_
 #define	_LINUX_IN6_H_
=20
-#ifndef KLD_MODULE
 #include "opt_inet6.h"
-#endif
=20
 #endif	/* _LINUX_IN6_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/include/linux/io.h
--- a/head/sys/ofed/include/linux/io.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ofed/include/linux/io.h	Tue Apr 17 11:51:51 2012 +0300
@@ -90,7 +90,7 @@
=20
 void *_ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr);
 #define	ioremap_nocache(addr, size)					\
-    _ioremap_attr((addr), (size), VM_MEMATTR_UNCACHED)
+    _ioremap_attr((addr), (size), VM_MEMATTR_UNCACHEABLE)
 #define	ioremap_wc(addr, size)						\
     _ioremap_attr((addr), (size), VM_MEMATTR_WRITE_COMBINING)
 #define	ioremap	ioremap_nocache
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/include/linux/page.h
--- a/head/sys/ofed/include/linux/page.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ofed/include/linux/page.h	Tue Apr 17 11:51:51 2012 +0300
@@ -40,7 +40,7 @@
 #define	virt_to_page(x)	PHYS_TO_VM_PAGE(vtophys((x)))
=20
 #define	clear_page(page)		memset((page), 0, PAGE_SIZE)
-#define	pgprot_noncached(prot)		VM_MEMATTR_UNCACHED
+#define	pgprot_noncached(prot)		VM_MEMATTR_UNCACHEABLE
 #define	pgprot_writecombine(prot)	VM_MEMATTR_WRITE_COMBINING
=20
 #undef	PAGE_MASK
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/include/net/ip.h
--- a/head/sys/ofed/include/net/ip.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ofed/include/net/ip.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,6 +29,8 @@
 #ifndef _LINUX_NET_IP_H_
 #define	_LINUX_NET_IP_H_
=20
+#include "opt_inet.h"
+
 #include <sys/types.h>
 #include <sys/socket.h>
=20
@@ -39,6 +41,7 @@
 #include <netinet/in.h>
 #include <netinet/in_pcb.h>
=20
+#ifdef INET
 static inline void inet_get_local_port_range(int *low, int *high)
 {
 	*low =3D V_ipport_firstauto;
@@ -73,5 +76,6 @@
 	buf[18] =3D (addr >> 8) & 0xff;
 	buf[19] =3D addr & 0xff;
 }
+#endif
=20
 #endif	/* _LINUX_NET_IP_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/ofed/include/net/ipv6.h
--- a/head/sys/ofed/include/net/ipv6.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ofed/include/net/ipv6.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,9 +29,7 @@
 #ifndef _LINUX_NET_IPV6_H_
 #define	_LINUX_NET_IPV6_H_
=20
-#ifndef KLD_MODULE
 #include "opt_inet6.h"
-#endif
=20
 #define	ipv6_addr_loopback IN6_IS_ADDR_LOOPBACK
 #define	ipv6_addr_copy(dst, src)					\
diff -r 428842767fa6 -r f2935497fa04 head/sys/pc98/conf/GENERIC
--- a/head/sys/pc98/conf/GENERIC	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/pc98/conf/GENERIC	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check first
 # in NOTES.
 #
-# $FreeBSD: head/sys/pc98/conf/GENERIC 231276 2012-02-09 14:15:56Z nyan $
+# $FreeBSD: head/sys/pc98/conf/GENERIC 233271 2012-03-21 08:38:42Z ed $
=20
 cpu		I486_CPU
 cpu		I586_CPU
@@ -222,7 +222,6 @@
 device		ether		# Ethernet support
 device		vlan		# 802.1Q VLAN support
 device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 device		md		# Memory "disks"
 device		gif		# IPv6 and IPv4 tunneling
 device		faith		# IPv6-to-IPv4 relaying (translation)
diff -r 428842767fa6 -r f2935497fa04 head/sys/pci/intpm.c
--- a/head/sys/pci/intpm.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/pci/intpm.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/pci/intpm.c 227843 2011-11-22 21:28:20Z mariu=
s $");
+__FBSDID("$FreeBSD: head/sys/pci/intpm.c 234338 2012-04-16 10:33:46Z avg $=
");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -98,7 +98,13 @@
 #endif
 		device_set_desc(dev, "Intel PIIX4 SMBUS Interface");
 		break;
+	case 0x43721002:
+		device_set_desc(dev, "ATI IXP400 SMBus Controller");
+		break;
 	case 0x43851002:
+		/* SB800 and newer can not be configured in a compatible way. */
+		if (pci_get_revid(dev) >=3D 0x40)
+			return (ENXIO);
 		device_set_desc(dev, "AMD SB600/700/710/750 SMBus Controller");
 		/* XXX Maybe force polling right here? */
 		break;
@@ -269,7 +275,7 @@
 	case SMB_RELEASE_BUS:
 		break;
 	default:
-		error =3D EINVAL;
+		error =3D SMB_EINVAL;
 	}
=20
 	return (error);
@@ -516,7 +522,7 @@
 		data |=3D LSB;
 		break;
 	default:
-		return (EINVAL);
+		return (SMB_EINVAL);
 	}
=20
 	INTSMB_LOCK(sc);
@@ -771,7 +777,7 @@
 			}
 			*count =3D nread;
 		} else
-			error =3D EIO;
+			error =3D SMB_EBUSERR;
 	}
 	INTSMB_UNLOCK(sc);
 	return (error);
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/aim/machdep.c
--- a/head/sys/powerpc/aim/machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/aim/machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -55,7 +55,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/powerpc/aim/machdep.c 230123 2012-01-15 00:08=
:14Z nwhitehorn $");
+__FBSDID("$FreeBSD: head/sys/powerpc/aim/machdep.c 234156 2012-04-11 22:23=
:50Z nwhitehorn $");
=20
 #include "opt_compat.h"
 #include "opt_ddb.h"
@@ -405,6 +405,9 @@
 		cacheline_size =3D 32;
 	}
=20
+	/* Make sure the kernel icache is valid before we go too much further */
+	__syncicache((caddr_t)startkernel, endkernel - startkernel);
+
 	#ifndef __powerpc64__
 	/*
 	 * Figure out whether we need to use the 64 bit PMAP. This works by
@@ -735,36 +738,6 @@
 		intr_restore(msr);
 }
=20
-/*
- * kcopy(const void *src, void *dst, size_t len);
- *
- * Copy len bytes from src to dst, aborting if we encounter a fatal
- * page fault.
- *
- * kcopy() _must_ save and restore the old fault handler since it is
- * called by uiomove(), which may be in the path of servicing a non-fatal
- * page fault.
- */
-int
-kcopy(const void *src, void *dst, size_t len)
-{
-	struct thread	*td;
-	faultbuf	env, *oldfault;
-	int		rv;
-
-	td =3D curthread;
-	oldfault =3D td->td_pcb->pcb_onfault;
-	if ((rv =3D setfault(env)) !=3D 0) {
-		td->td_pcb->pcb_onfault =3D oldfault;
-		return rv;
-	}
-
-	memcpy(dst, src, len);
-
-	td->td_pcb->pcb_onfault =3D oldfault;
-	return (0);
-}
-
 int db_trap_glue(struct trapframe *);		/* Called from trap_subr.S */
=20
 int
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/aim/mmu_oea.c
--- a/head/sys/powerpc/aim/mmu_oea.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/aim/mmu_oea.c	Tue Apr 17 11:51:51 2012 +0300
@@ -91,7 +91,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/powerpc/aim/mmu_oea.c 232980 2012-03-14 20:19=
:49Z nwhitehorn $");
+__FBSDID("$FreeBSD: head/sys/powerpc/aim/mmu_oea.c 234156 2012-04-11 22:23=
:50Z nwhitehorn $");
=20
 /*
  * Manages physical address maps.
@@ -1023,7 +1023,7 @@
 	dst =3D VM_PAGE_TO_PHYS(mdst);
 	src =3D VM_PAGE_TO_PHYS(msrc);
=20
-	kcopy((void *)src, (void *)dst, PAGE_SIZE);
+	bcopy((void *)src, (void *)dst, PAGE_SIZE);
 }
=20
 /*
@@ -1087,7 +1087,7 @@
 	struct		pvo_head *pvo_head;
 	uma_zone_t	zone;
 	vm_page_t	pg;
-	u_int		pte_lo, pvo_flags, was_exec;
+	u_int		pte_lo, pvo_flags;
 	int		error;
=20
 	if (!moea_initialized) {
@@ -1095,13 +1095,11 @@
 		zone =3D moea_upvo_zone;
 		pvo_flags =3D 0;
 		pg =3D NULL;
-		was_exec =3D PTE_EXEC;
 	} else {
 		pvo_head =3D vm_page_to_pvoh(m);
 		pg =3D m;
 		zone =3D moea_mpvo_zone;
 		pvo_flags =3D PVO_MANAGED;
-		was_exec =3D 0;
 	}
 	if (pmap_bootstrapped)
 		mtx_assert(&vm_page_queue_mtx, MA_OWNED);
@@ -1117,18 +1115,6 @@
 		zone =3D moea_upvo_zone;
 	}
=20
-	/*
-	 * If this is a managed page, and it's the first reference to the page,
-	 * clear the execness of the page.  Otherwise fetch the execness.
-	 */
-	if ((pg !=3D NULL) && ((m->oflags & VPO_UNMANAGED) =3D=3D 0)) {
-		if (LIST_EMPTY(pvo_head)) {
-			moea_attr_clear(pg, PTE_EXEC);
-		} else {
-			was_exec =3D moea_attr_fetch(pg) & PTE_EXEC;
-		}
-	}
-
 	pte_lo =3D moea_calc_wimg(VM_PAGE_TO_PHYS(m), pmap_page_get_memattr(m));
=20
 	if (prot & VM_PROT_WRITE) {
@@ -1149,22 +1135,14 @@
 	    pte_lo, pvo_flags);
=20
 	/*
-	 * Flush the real page from the instruction cache if this page is
-	 * mapped executable and cacheable and was not previously mapped (or
-	 * was not mapped executable).
+	 * Flush the real page from the instruction cache. This has be done
+	 * for all user mappings to prevent information leakage via the
+	 * instruction cache. moea_pvo_enter() returns ENOENT for the first
+	 * mapping for a page.
 	 */
-	if (error =3D=3D 0 && (pvo_flags & PVO_EXECUTABLE) &&
-	    (pte_lo & PTE_I) =3D=3D 0 && was_exec =3D=3D 0) {
-		/*
-		 * Flush the real memory from the cache.
-		 */
+	if (pmap !=3D kernel_pmap && error =3D=3D ENOENT &&
+	    (pte_lo & (PTE_I | PTE_G)) =3D=3D 0)
 		moea_syncicache(VM_PAGE_TO_PHYS(m), PAGE_SIZE);
-		if (pg !=3D NULL)
-			moea_attr_save(pg, PTE_EXEC);
-	}
-
-	/* XXX syncicache always until problems are sorted */
-	moea_syncicache(VM_PAGE_TO_PHYS(m), PAGE_SIZE);
 }
=20
 /*
@@ -1486,12 +1464,6 @@
 		panic("moea_kenter: failed to enter va %#x pa %#x: %d", va,
 		    pa, error);
=20
-	/*
-	 * Flush the real memory from the instruction cache.
-	 */
-	if ((pte_lo & (PTE_I | PTE_G)) =3D=3D 0) {
-		moea_syncicache(pa, PAGE_SIZE);
-	}
 	PMAP_UNLOCK(kernel_pmap);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/aim/mmu_oea64.c
--- a/head/sys/powerpc/aim/mmu_oea64.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/aim/mmu_oea64.c	Tue Apr 17 11:51:51 2012 +0300
@@ -91,7 +91,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/powerpc/aim/mmu_oea64.c 233117 2012-03-18 13:=
22:42Z nwhitehorn $");
+__FBSDID("$FreeBSD: head/sys/powerpc/aim/mmu_oea64.c 234156 2012-04-11 22:=
23:50Z nwhitehorn $");
=20
 /*
  * Manages physical address maps.
@@ -126,6 +126,7 @@
 #include <sys/msgbuf.h>
 #include <sys/mutex.h>
 #include <sys/proc.h>
+#include <sys/rwlock.h>
 #include <sys/sched.h>
 #include <sys/sysctl.h>
 #include <sys/systm.h>
@@ -173,9 +174,20 @@
 #define	VSID_TO_HASH(vsid)	(((vsid) >> 4) & 0xfffff)
 #define	VSID_HASH_MASK		0x0000007fffffffffULL
=20
-#define LOCK_TABLE() mtx_lock(&moea64_table_mutex)
-#define UNLOCK_TABLE() mtx_unlock(&moea64_table_mutex);
-#define ASSERT_TABLE_LOCK() mtx_assert(&moea64_table_mutex, MA_OWNED)
+/*
+ * Locking semantics:
+ * -- Read lock: if no modifications are being made to either the PVO lists
+ *    or page table or if any modifications being made result in internal
+ *    changes (e.g. wiring, protection) such that the existence of the PVOs
+ *    is unchanged and they remain associated with the same pmap (in which
+ *    case the changes should be protected by the pmap lock)
+ * -- Write lock: required if PTEs/PVOs are being inserted or removed.
+ */
+
+#define LOCK_TABLE_RD() rw_rlock(&moea64_table_lock)
+#define UNLOCK_TABLE_RD() rw_runlock(&moea64_table_lock)
+#define LOCK_TABLE_WR() rw_wlock(&moea64_table_lock)
+#define UNLOCK_TABLE_WR() rw_wunlock(&moea64_table_lock)
=20
 struct ofw_map {
 	cell_t	om_va;
@@ -198,7 +210,7 @@
 /*
  * Lock for the pteg and pvo tables.
  */
-struct mtx	moea64_table_mutex;
+struct rwlock	moea64_table_lock;
 struct mtx	moea64_slb_mutex;
=20
 /*
@@ -272,8 +284,6 @@
 /*
  * Utility routines.
  */
-static void		moea64_enter_locked(mmu_t, pmap_t, vm_offset_t,
-			    vm_page_t, vm_prot_t, boolean_t);
 static boolean_t	moea64_query_bit(mmu_t, vm_page_t, u_int64_t);
 static u_int		moea64_clear_bit(mmu_t, vm_page_t, u_int64_t);
 static void		moea64_kremove(mmu_t, vm_offset_t);
@@ -396,35 +406,10 @@
 }
=20
 static __inline void
-moea64_attr_clear(vm_page_t m, u_int64_t ptebit)
-{
-
-	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
-	m->md.mdpg_attrs &=3D ~ptebit;
-}
-
-static __inline u_int64_t
-moea64_attr_fetch(vm_page_t m)
-{
-
-	return (m->md.mdpg_attrs);
-}
-
-static __inline void
-moea64_attr_save(vm_page_t m, u_int64_t ptebit)
-{
-
-	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
-	m->md.mdpg_attrs |=3D ptebit;
-}
-
-static __inline void
 moea64_pte_create(struct lpte *pt, uint64_t vsid, vm_offset_t va,=20
     uint64_t pte_lo, int flags)
 {
=20
-	ASSERT_TABLE_LOCK();
-
 	/*
 	 * Construct a PTE.  Default to IMB initially.  Valid bit only gets
 	 * set when the real pte is set in memory.
@@ -617,6 +602,7 @@
=20
 	DISABLE_TRANS(msr);
 	if (hw_direct_map) {
+		LOCK_TABLE_WR();
 		PMAP_LOCK(kernel_pmap);
 		for (i =3D 0; i < pregions_sz; i++) {
 		  for (pa =3D pregions[i].mr_start; pa < pregions[i].mr_start +
@@ -641,6 +627,7 @@
 		  }
 		}
 		PMAP_UNLOCK(kernel_pmap);
+		UNLOCK_TABLE_WR();
 	} else {
 		size =3D sizeof(struct pvo_head) * moea64_pteg_count;
 		off =3D (vm_offset_t)(moea64_pvo_table);
@@ -799,8 +786,7 @@
 	 * Initialize the lock that synchronizes access to the pteg and pvo
 	 * tables.
 	 */
-	mtx_init(&moea64_table_mutex, "pmap table", NULL, MTX_DEF |
-	    MTX_RECURSE);
+	rw_init_flags(&moea64_table_lock, "pmap tables", RW_RECURSE);
 	mtx_init(&moea64_slb_mutex, "SLB table", NULL, MTX_DEF);
=20
 	/*
@@ -979,7 +965,7 @@
=20
 			moea64_scratchpage_pvo[i] =3D moea64_pvo_find_va(
 			    kernel_pmap, (vm_offset_t)moea64_scratchpage_va[i]);
-			LOCK_TABLE();
+			LOCK_TABLE_RD();
 			moea64_scratchpage_pte[i] =3D MOEA64_PVO_TO_PTE(
 			    mmup, moea64_scratchpage_pvo[i]);
 			moea64_scratchpage_pvo[i]->pvo_pte.lpte.pte_hi
@@ -987,7 +973,7 @@
 			MOEA64_PTE_CHANGE(mmup, moea64_scratchpage_pte[i],
 			    &moea64_scratchpage_pvo[i]->pvo_pte.lpte,
 			    moea64_scratchpage_pvo[i]->pvo_vpn);
-			UNLOCK_TABLE();
+			UNLOCK_TABLE_RD();
 		}
 	}
 }
@@ -1033,11 +1019,11 @@
 	uint64_t vsid;
 	int	i, ptegidx;
=20
+	LOCK_TABLE_WR();
 	PMAP_LOCK(pm);
 	pvo =3D moea64_pvo_find_va(pm, va & ~ADDR_POFF);
=20
 	if (pvo !=3D NULL) {
-		LOCK_TABLE();
 		pt =3D MOEA64_PVO_TO_PTE(mmu, pvo);
=20
 		if (wired) {
@@ -1073,8 +1059,8 @@
 			}
 		}
 		=09
-		UNLOCK_TABLE();
 	}
+	UNLOCK_TABLE_WR();
 	PMAP_UNLOCK(pm);
 }
=20
@@ -1111,14 +1097,14 @@
 	src =3D VM_PAGE_TO_PHYS(msrc);
=20
 	if (hw_direct_map) {
-		kcopy((void *)src, (void *)dst, PAGE_SIZE);
+		bcopy((void *)src, (void *)dst, PAGE_SIZE);
 	} else {
 		mtx_lock(&moea64_scratchpage_mtx);
=20
 		moea64_set_scratchpage_pa(mmu, 0, src);
 		moea64_set_scratchpage_pa(mmu, 1, dst);
=20
-		kcopy((void *)moea64_scratchpage_va[0],=20
+		bcopy((void *)moea64_scratchpage_va[0],=20
 		    (void *)moea64_scratchpage_va[1], PAGE_SIZE);
=20
 		mtx_unlock(&moea64_scratchpage_mtx);
@@ -1180,30 +1166,11 @@
  * target pmap with the protection requested.  If specified the page
  * will be wired down.
  */
+
 void
 moea64_enter(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,=20
     vm_prot_t prot, boolean_t wired)
 {
-
-	vm_page_lock_queues();
-	PMAP_LOCK(pmap);
-	moea64_enter_locked(mmu, pmap, va, m, prot, wired);
-	vm_page_unlock_queues();
-	PMAP_UNLOCK(pmap);
-}
-
-/*
- * Map the given physical page at the specified virtual address in the
- * target pmap with the protection requested.  If specified the page
- * will be wired down.
- *
- * The page queues and pmap must be locked.
- */
-
-static void
-moea64_enter_locked(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
-    vm_prot_t prot, boolean_t wired)
-{
 	struct		pvo_head *pvo_head;
 	uma_zone_t	zone;
 	vm_page_t	pg;
@@ -1223,12 +1190,9 @@
 		pvo_flags =3D PVO_MANAGED;
 	}
=20
-	if (pmap_bootstrapped)
-		mtx_assert(&vm_page_queue_mtx, MA_OWNED);
-	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 	KASSERT((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) !=3D 0 ||
 	    VM_OBJECT_LOCKED(m->object),
-	    ("moea64_enter_locked: page %p is not busy", m));
+	    ("moea64_enter: page %p is not busy", m));
=20
 	/* XXX change the pvo head for fake pages */
 	if ((m->oflags & VPO_UNMANAGED) !=3D 0) {
@@ -1253,15 +1217,22 @@
 	if (wired)
 		pvo_flags |=3D PVO_WIRED;
=20
+	LOCK_TABLE_WR();
+	PMAP_LOCK(pmap);
 	error =3D moea64_pvo_enter(mmu, pmap, zone, pvo_head, va,
 	    VM_PAGE_TO_PHYS(m), pte_lo, pvo_flags);
+	PMAP_UNLOCK(pmap);
+	UNLOCK_TABLE_WR();
=20
 	/*
 	 * Flush the page from the instruction cache if this page is
 	 * mapped executable and cacheable.
 	 */
-	if ((pte_lo & (LPTE_I | LPTE_G | LPTE_NOEXEC)) =3D=3D 0)
+	if (pmap !=3D kernel_pmap && !(m->aflags & PGA_EXECUTABLE) &&
+	    (pte_lo & (LPTE_I | LPTE_G | LPTE_NOEXEC)) =3D=3D 0) {
+		vm_page_aflag_set(m, PGA_EXECUTABLE);
 		moea64_syncicache(mmu, pmap, va, VM_PAGE_TO_PHYS(m), PAGE_SIZE);
+	}
 }
=20
 static void
@@ -1322,15 +1293,11 @@
=20
 	psize =3D atop(end - start);
 	m =3D m_start;
-	vm_page_lock_queues();
-	PMAP_LOCK(pm);
 	while (m !=3D NULL && (diff =3D m->pindex - m_start->pindex) < psize) {
-		moea64_enter_locked(mmu, pm, start + ptoa(diff), m, prot &
+		moea64_enter(mmu, pm, start + ptoa(diff), m, prot &
 		    (VM_PROT_READ | VM_PROT_EXECUTE), FALSE);
 		m =3D TAILQ_NEXT(m, listq);
 	}
-	vm_page_unlock_queues();
-	PMAP_UNLOCK(pm);
 }
=20
 void
@@ -1338,12 +1305,8 @@
     vm_prot_t prot)
 {
=20
-	vm_page_lock_queues();
-	PMAP_LOCK(pm);
-	moea64_enter_locked(mmu, pm, va, m,
+	moea64_enter(mmu, pm, va, m,
 	    prot & (VM_PROT_READ | VM_PROT_EXECUTE), FALSE);
-	vm_page_unlock_queues();
-	PMAP_UNLOCK(pm);
 }
=20
 vm_paddr_t
@@ -1352,6 +1315,7 @@
 	struct	pvo_entry *pvo;
 	vm_paddr_t pa;
=20
+	LOCK_TABLE_RD();
 	PMAP_LOCK(pm);
 	pvo =3D moea64_pvo_find_va(pm, va);
 	if (pvo =3D=3D NULL)
@@ -1359,6 +1323,7 @@
 	else
 		pa =3D (pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN) |
 		    (va - PVO_VADDR(pvo));
+	UNLOCK_TABLE_RD();
 	PMAP_UNLOCK(pm);
 	return (pa);
 }
@@ -1377,6 +1342,7 @@
        =20
 	m =3D NULL;
 	pa =3D 0;
+	LOCK_TABLE_RD();
 	PMAP_LOCK(pmap);
 retry:
 	pvo =3D moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
@@ -1390,6 +1356,7 @@
 		vm_page_hold(m);
 	}
 	PA_UNLOCK_COND(pa);
+	UNLOCK_TABLE_RD();
 	PMAP_UNLOCK(pmap);
 	return (m);
 }
@@ -1413,9 +1380,6 @@
 	*flags =3D UMA_SLAB_PRIV;
 	needed_lock =3D !PMAP_LOCKED(kernel_pmap);
=20
-	if (needed_lock)
-		PMAP_LOCK(kernel_pmap);
-
         if ((wait & (M_NOWAIT|M_USE_RESERVE)) =3D=3D M_NOWAIT)
                 pflags =3D VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED;
         else
@@ -1435,12 +1399,17 @@
=20
 	va =3D VM_PAGE_TO_PHYS(m);
=20
+	LOCK_TABLE_WR();
+	if (needed_lock)
+		PMAP_LOCK(kernel_pmap);
+
 	moea64_pvo_enter(installed_mmu, kernel_pmap, moea64_upvo_zone,
 	    &moea64_pvo_kunmanaged, va, VM_PAGE_TO_PHYS(m), LPTE_M,
 	    PVO_WIRED | PVO_BOOTSTRAP);
=20
 	if (needed_lock)
 		PMAP_UNLOCK(kernel_pmap);
+	UNLOCK_TABLE_WR();
 =09
 	if ((wait & M_ZERO) && (m->flags & PG_ZERO) =3D=3D 0)
                 bzero((void *)va, PAGE_SIZE);
@@ -1510,10 +1479,12 @@
 	struct pvo_entry *pvo;
 	boolean_t rv;
=20
+	LOCK_TABLE_RD();
 	PMAP_LOCK(pmap);
 	pvo =3D moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
 	rv =3D pvo =3D=3D NULL || (pvo->pvo_pte.lpte.pte_hi & LPTE_VALID) =3D=3D =
0;
 	PMAP_UNLOCK(pmap);
+	UNLOCK_TABLE_RD();
 	return (rv);
 }
=20
@@ -1555,7 +1526,7 @@
 	struct	pvo_entry *pvo;
 	uintptr_t pt;
 	pmap_t	pmap;
-	uint64_t lo;
+	uint64_t lo =3D 0;
=20
 	KASSERT((m->oflags & VPO_UNMANAGED) =3D=3D 0,
 	    ("moea64_remove_write: page %p is not managed", m));
@@ -1569,13 +1540,11 @@
 	if ((m->oflags & VPO_BUSY) =3D=3D 0 &&
 	    (m->aflags & PGA_WRITEABLE) =3D=3D 0)
 		return;
-	vm_page_lock_queues();
-	lo =3D moea64_attr_fetch(m);
 	powerpc_sync();
+	LOCK_TABLE_RD();
 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
 		pmap =3D pvo->pvo_pmap;
 		PMAP_LOCK(pmap);
-		LOCK_TABLE();
 		if ((pvo->pvo_pte.lpte.pte_lo & LPTE_PP) !=3D LPTE_BR) {
 			pt =3D MOEA64_PVO_TO_PTE(mmu, pvo);
 			pvo->pvo_pte.lpte.pte_lo &=3D ~LPTE_PP;
@@ -1590,15 +1559,12 @@
 					isync();
 			}
 		}
-		UNLOCK_TABLE();
+		if ((lo & LPTE_CHG) !=3D 0)=20
+			vm_page_dirty(m);
 		PMAP_UNLOCK(pmap);
 	}
-	if ((lo & LPTE_CHG) !=3D 0) {
-		moea64_attr_clear(m, LPTE_CHG);
-		vm_page_dirty(m);
-	}
+	UNLOCK_TABLE_RD();
 	vm_page_aflag_clear(m, PGA_WRITEABLE);
-	vm_page_unlock_queues();
 }
=20
 /*
@@ -1639,13 +1605,12 @@
 		return;
 	}
=20
-	vm_page_lock_queues();
 	pvo_head =3D vm_page_to_pvoh(m);
 	lo =3D moea64_calc_wimg(VM_PAGE_TO_PHYS(m), ma);
+	LOCK_TABLE_RD();
 	LIST_FOREACH(pvo, pvo_head, pvo_vlink) {
 		pmap =3D pvo->pvo_pmap;
 		PMAP_LOCK(pmap);
-		LOCK_TABLE();
 		pt =3D MOEA64_PVO_TO_PTE(mmu, pvo);
 		pvo->pvo_pte.lpte.pte_lo &=3D ~LPTE_WIMG;
 		pvo->pvo_pte.lpte.pte_lo |=3D lo;
@@ -1655,11 +1620,10 @@
 			if (pvo->pvo_pmap =3D=3D kernel_pmap)
 				isync();
 		}
-		UNLOCK_TABLE();
 		PMAP_UNLOCK(pmap);
 	}
+	UNLOCK_TABLE_RD();
 	m->md.mdpg_cache_attrs =3D ma;
-	vm_page_unlock_queues();
 }
=20
 /*
@@ -1673,20 +1637,16 @@
=20
 	pte_lo =3D moea64_calc_wimg(pa, ma);
=20
+	LOCK_TABLE_WR();
 	PMAP_LOCK(kernel_pmap);
 	error =3D moea64_pvo_enter(mmu, kernel_pmap, moea64_upvo_zone,
 	    &moea64_pvo_kunmanaged, va, pa, pte_lo, PVO_WIRED);
+	PMAP_UNLOCK(kernel_pmap);
+	UNLOCK_TABLE_WR();
=20
 	if (error !=3D 0 && error !=3D ENOENT)
 		panic("moea64_kenter: failed to enter va %#zx pa %#zx: %d", va,
 		    pa, error);
-
-	/*
-	 * Flush the memory from the instruction cache.
-	 */
-	if ((pte_lo & (LPTE_I | LPTE_G)) =3D=3D 0)
-		__syncicache((void *)va, PAGE_SIZE);
-	PMAP_UNLOCK(kernel_pmap);
 }
=20
 void
@@ -1713,11 +1673,13 @@
 	if (va < VM_MIN_KERNEL_ADDRESS)
 		return (va);
=20
+	LOCK_TABLE_RD();
 	PMAP_LOCK(kernel_pmap);
 	pvo =3D moea64_pvo_find_va(kernel_pmap, va);
 	KASSERT(pvo !=3D NULL, ("moea64_kextract: no addr found for %#" PRIxPTR,
 	    va));
 	pa =3D (pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN) | (va - PVO_VADDR(pvo));
+	UNLOCK_TABLE_RD();
 	PMAP_UNLOCK(kernel_pmap);
 	return (pa);
 }
@@ -1773,7 +1735,7 @@
 	    ("moea64_page_exists_quick: page %p is not managed", m));
 	loops =3D 0;
 	rv =3D FALSE;
-	vm_page_lock_queues();
+	LOCK_TABLE_RD();
 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
 		if (pvo->pvo_pmap =3D=3D pmap) {
 			rv =3D TRUE;
@@ -1782,7 +1744,7 @@
 		if (++loops >=3D 16)
 			break;
 	}
-	vm_page_unlock_queues();
+	UNLOCK_TABLE_RD();
 	return (rv);
 }
=20
@@ -1799,11 +1761,11 @@
 	count =3D 0;
 	if ((m->oflags & VPO_UNMANAGED) !=3D 0)
 		return (count);
-	vm_page_lock_queues();
+	LOCK_TABLE_RD();
 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink)
 		if ((pvo->pvo_vaddr & PVO_WIRED) !=3D 0)
 			count++;
-	vm_page_unlock_queues();
+	UNLOCK_TABLE_RD();
 	return (count);
 }
=20
@@ -1915,37 +1877,59 @@
 moea64_pvo_protect(mmu_t mmu,  pmap_t pm, struct pvo_entry *pvo, vm_prot_t=
 prot)
 {
 	uintptr_t pt;
+	struct	vm_page *pg;
+	uint64_t oldlo;
+
+	PMAP_LOCK_ASSERT(pm, MA_OWNED);
=20
 	/*
 	 * Grab the PTE pointer before we diddle with the cached PTE
 	 * copy.
 	 */
-	LOCK_TABLE();
 	pt =3D MOEA64_PVO_TO_PTE(mmu, pvo);
=20
 	/*
 	 * Change the protection of the page.
 	 */
+	oldlo =3D pvo->pvo_pte.lpte.pte_lo;
 	pvo->pvo_pte.lpte.pte_lo &=3D ~LPTE_PP;
-	pvo->pvo_pte.lpte.pte_lo |=3D LPTE_BR;
 	pvo->pvo_pte.lpte.pte_lo &=3D ~LPTE_NOEXEC;
 	if ((prot & VM_PROT_EXECUTE) =3D=3D 0)=20
 		pvo->pvo_pte.lpte.pte_lo |=3D LPTE_NOEXEC;
+	if (prot & VM_PROT_WRITE)=20
+		pvo->pvo_pte.lpte.pte_lo |=3D LPTE_BW;
+	else
+		pvo->pvo_pte.lpte.pte_lo |=3D LPTE_BR;
+
+	pg =3D PHYS_TO_VM_PAGE(pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN);
=20
 	/*
 	 * If the PVO is in the page table, update that pte as well.
 	 */
-	if (pt !=3D -1) {
+	if (pt !=3D -1)
 		MOEA64_PTE_CHANGE(mmu, pt, &pvo->pvo_pte.lpte,
 		    pvo->pvo_vpn);
-		if ((pvo->pvo_pte.lpte.pte_lo &=20
-		    (LPTE_I | LPTE_G | LPTE_NOEXEC)) =3D=3D 0) {
-			moea64_syncicache(mmu, pm, PVO_VADDR(pvo),
-			    pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN,
-			    PAGE_SIZE);
+	if (pm !=3D kernel_pmap && pg !=3D NULL && !(pg->aflags & PGA_EXECUTABLE)=
 &&
+	    (pvo->pvo_pte.lpte.pte_lo & (LPTE_I | LPTE_G | LPTE_NOEXEC)) =3D=3D 0=
) {
+		if ((pg->oflags & VPO_UNMANAGED) =3D=3D 0)
+			vm_page_aflag_set(pg, PGA_EXECUTABLE);
+		moea64_syncicache(mmu, pm, PVO_VADDR(pvo),
+		    pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN, PAGE_SIZE);
+	}
+
+	/*
+	 * Update vm about the REF/CHG bits if the page is managed and we have
+	 * removed write access.
+	 */
+	if ((pvo->pvo_vaddr & PVO_MANAGED) =3D=3D PVO_MANAGED &&=20
+	    (oldlo & LPTE_PP) !=3D LPTE_BR && !(prot && VM_PROT_WRITE)) {
+		if (pg !=3D NULL) {
+			if (pvo->pvo_pte.lpte.pte_lo & LPTE_CHG)
+				vm_page_dirty(pg);
+			if (pvo->pvo_pte.lpte.pte_lo & LPTE_REF)
+				vm_page_aflag_set(pg, PGA_REFERENCED);
 		}
 	}
-	UNLOCK_TABLE();
 }
=20
 void
@@ -1965,12 +1949,21 @@
 		return;
 	}
=20
+	LOCK_TABLE_RD();
 	PMAP_LOCK(pm);
 	if ((eva - sva)/PAGE_SIZE < pm->pm_stats.resident_count) {
-		for (; sva < eva; sva +=3D PAGE_SIZE) {
+		while (sva < eva) {
+			#ifdef __powerpc64__
+			if (pm !=3D kernel_pmap &&
+			    user_va_to_slb_entry(pm, sva) =3D=3D NULL) {
+				sva =3D roundup2(sva + 1, SEGMENT_LENGTH);
+				continue;
+			}
+			#endif
 			pvo =3D moea64_pvo_find_va(pm, sva);
 			if (pvo !=3D NULL)
 				moea64_pvo_protect(mmu, pm, pvo, prot);
+			sva +=3D PAGE_SIZE;
 		}
 	} else {
 		LIST_FOREACH_SAFE(pvo, &pm->pmap_pvo, pvo_plink, tpvo) {
@@ -1979,6 +1972,7 @@
 			moea64_pvo_protect(mmu, pm, pvo, prot);
 		}
 	}
+	UNLOCK_TABLE_RD();
 	PMAP_UNLOCK(pm);
 }
=20
@@ -2053,11 +2047,13 @@
 {
 	struct	pvo_entry *pvo, *tpvo;
=20
-	vm_page_lock_queues();
+	LOCK_TABLE_WR();
 	PMAP_LOCK(pm);
-	LIST_FOREACH_SAFE(pvo, &pm->pmap_pvo, pvo_plink, tpvo)
-		moea64_pvo_remove(mmu, pvo);
-	vm_page_unlock_queues();
+	LIST_FOREACH_SAFE(pvo, &pm->pmap_pvo, pvo_plink, tpvo) {
+		if (!(pvo->pvo_vaddr & PVO_WIRED))
+			moea64_pvo_remove(mmu, pvo);
+	}
+	UNLOCK_TABLE_WR();
 	PMAP_UNLOCK(pm);
 }
=20
@@ -2075,13 +2071,21 @@
 	if (pm->pm_stats.resident_count =3D=3D 0)
 		return;
=20
-	vm_page_lock_queues();
+	LOCK_TABLE_WR();
 	PMAP_LOCK(pm);
 	if ((eva - sva)/PAGE_SIZE < pm->pm_stats.resident_count) {
-		for (; sva < eva; sva +=3D PAGE_SIZE) {
+		while (sva < eva) {
+			#ifdef __powerpc64__
+			if (pm !=3D kernel_pmap &&
+			    user_va_to_slb_entry(pm, sva) =3D=3D NULL) {
+				sva =3D roundup2(sva + 1, SEGMENT_LENGTH);
+				continue;
+			}
+			#endif
 			pvo =3D moea64_pvo_find_va(pm, sva);
 			if (pvo !=3D NULL)
 				moea64_pvo_remove(mmu, pvo);
+			sva +=3D PAGE_SIZE;
 		}
 	} else {
 		LIST_FOREACH_SAFE(pvo, &pm->pmap_pvo, pvo_plink, tpvo) {
@@ -2090,7 +2094,7 @@
 			moea64_pvo_remove(mmu, pvo);
 		}
 	}
-	vm_page_unlock_queues();
+	UNLOCK_TABLE_WR();
 	PMAP_UNLOCK(pm);
 }
=20
@@ -2101,26 +2105,21 @@
 void
 moea64_remove_all(mmu_t mmu, vm_page_t m)
 {
-	struct  pvo_head *pvo_head;
 	struct	pvo_entry *pvo, *next_pvo;
 	pmap_t	pmap;
=20
-	vm_page_lock_queues();
-	pvo_head =3D vm_page_to_pvoh(m);
-	for (pvo =3D LIST_FIRST(pvo_head); pvo !=3D NULL; pvo =3D next_pvo) {
-		next_pvo =3D LIST_NEXT(pvo, pvo_vlink);
-
+	LOCK_TABLE_WR();
+	LIST_FOREACH_SAFE(pvo, vm_page_to_pvoh(m), pvo_vlink, next_pvo) {
 		pmap =3D pvo->pvo_pmap;
 		PMAP_LOCK(pmap);
 		moea64_pvo_remove(mmu, pvo);
 		PMAP_UNLOCK(pmap);
 	}
-	if ((m->aflags & PGA_WRITEABLE) && moea64_is_modified(mmu, m)) {
-		moea64_attr_clear(m, LPTE_CHG);
+	UNLOCK_TABLE_WR();
+	if ((m->aflags & PGA_WRITEABLE) && moea64_is_modified(mmu, m))
 		vm_page_dirty(m);
-	}
 	vm_page_aflag_clear(m, PGA_WRITEABLE);
-	vm_page_unlock_queues();
+	vm_page_aflag_clear(m, PGA_EXECUTABLE);
 }
=20
 /*
@@ -2196,6 +2195,9 @@
 	if (!moea64_initialized)
 		bootstrap =3D 1;
=20
+	PMAP_LOCK_ASSERT(pm, MA_OWNED);
+	rw_assert(&moea64_table_lock, RA_WLOCKED);
+
 	/*
 	 * Compute the PTE Group index.
 	 */
@@ -2207,8 +2209,6 @@
 	 * Remove any existing mapping for this page.  Reuse the pvo entry if
 	 * there is a mapping.
 	 */
-	LOCK_TABLE();
-
 	moea64_pvo_enter_calls++;
=20
 	LIST_FOREACH(pvo, &moea64_pvo_table[ptegidx], pvo_olink) {
@@ -2224,7 +2224,6 @@
 						PVO_PTEGIDX_SET(pvo, i);
 					moea64_pte_overflow--;
 				}
-				UNLOCK_TABLE();
 				return (0);
 			}
 			moea64_pvo_remove(mmu, pvo);
@@ -2251,15 +2250,11 @@
 		 * table. The mapping we are working with is already
 		 * protected by the PMAP lock.
 		 */
-		UNLOCK_TABLE();
 		pvo =3D uma_zalloc(zone, M_NOWAIT);
-		LOCK_TABLE();
 	}
=20
-	if (pvo =3D=3D NULL) {
-		UNLOCK_TABLE();
+	if (pvo =3D=3D NULL)
 		return (ENOMEM);
-	}
=20
 	moea64_pvo_entries++;
 	pvo->pvo_vaddr =3D va;
@@ -2314,8 +2309,6 @@
 	if (pm =3D=3D kernel_pmap)
 		isync();
=20
-	UNLOCK_TABLE();
-
 #ifdef __powerpc64__
 	/*
 	 * Make sure all our bootstrap mappings are in the SLB as soon
@@ -2331,13 +2324,16 @@
 static void
 moea64_pvo_remove(mmu_t mmu, struct pvo_entry *pvo)
 {
+	struct	vm_page *pg;
 	uintptr_t pt;
=20
+	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
+	rw_assert(&moea64_table_lock, RA_WLOCKED);
+
 	/*
 	 * If there is an active pte entry, we need to deactivate it (and
 	 * save the ref & cfg bits).
 	 */
-	LOCK_TABLE();
 	pt =3D MOEA64_PVO_TO_PTE(mmu, pvo);
 	if (pt !=3D -1) {
 		MOEA64_PTE_UNSET(mmu, pt, &pvo->pvo_pte.lpte, pvo->pvo_vpn);
@@ -2354,19 +2350,6 @@
 		pvo->pvo_pmap->pm_stats.wired_count--;
=20
 	/*
-	 * Save the REF/CHG bits into their cache if the page is managed.
-	 */
-	if ((pvo->pvo_vaddr & PVO_MANAGED) =3D=3D PVO_MANAGED) {
-		struct	vm_page *pg;
-
-		pg =3D PHYS_TO_VM_PAGE(pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN);
-		if (pg !=3D NULL) {
-			moea64_attr_save(pg, pvo->pvo_pte.lpte.pte_lo &
-			    (LPTE_REF | LPTE_CHG));
-		}
-	}
-
-	/*
 	 * Remove this PVO from the PV and pmap lists.
 	 */
 	LIST_REMOVE(pvo, pvo_vlink);
@@ -2378,11 +2361,27 @@
 	 */
 	LIST_REMOVE(pvo, pvo_olink);
=20
+	/*
+	 * Update vm about the REF/CHG bits if the page is managed.
+	 */
+	pg =3D PHYS_TO_VM_PAGE(pvo->pvo_pte.lpte.pte_lo & LPTE_RPGN);
+
+	if ((pvo->pvo_vaddr & PVO_MANAGED) =3D=3D PVO_MANAGED && pg !=3D NULL) {
+		if ((pvo->pvo_pte.lpte.pte_lo & LPTE_PP) !=3D LPTE_BR) {
+			if (pvo->pvo_pte.lpte.pte_lo & LPTE_CHG)
+				vm_page_dirty(pg);
+			if (pvo->pvo_pte.lpte.pte_lo & LPTE_REF)
+				vm_page_aflag_set(pg, PGA_REFERENCED);
+			if (LIST_EMPTY(vm_page_to_pvoh(pg)))
+				vm_page_aflag_clear(pg, PGA_WRITEABLE);
+		}
+		if (LIST_EMPTY(vm_page_to_pvoh(pg)))
+			vm_page_aflag_clear(pg, PGA_EXECUTABLE);
+	}
+
 	moea64_pvo_entries--;
 	moea64_pvo_remove_calls++;
=20
-	UNLOCK_TABLE();
-
 	if (!(pvo->pvo_vaddr & PVO_BOOTSTRAP))
 		uma_zfree((pvo->pvo_vaddr & PVO_MANAGED) ? moea64_mpvo_zone :
 		    moea64_upvo_zone, pvo);
@@ -2420,12 +2419,10 @@
 	ptegidx =3D va_to_pteg(vsid, va, 0);
 	#endif
=20
-	LOCK_TABLE();
 	LIST_FOREACH(pvo, &moea64_pvo_table[ptegidx], pvo_olink) {
 		if (pvo->pvo_pmap =3D=3D pm && PVO_VADDR(pvo) =3D=3D va)
 			break;
 	}
-	UNLOCK_TABLE();
=20
 	return (pvo);
 }
@@ -2436,20 +2433,13 @@
 	struct	pvo_entry *pvo;
 	uintptr_t pt;
=20
-	if (moea64_attr_fetch(m) & ptebit)
-		return (TRUE);
-
-	vm_page_lock_queues();
-
+	LOCK_TABLE_RD();
 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
-
 		/*
-		 * See if we saved the bit off.  If so, cache it and return
-		 * success.
+		 * See if we saved the bit off.  If so, return success.
 		 */
 		if (pvo->pvo_pte.lpte.pte_lo & ptebit) {
-			moea64_attr_save(m, ptebit);
-			vm_page_unlock_queues();
+			UNLOCK_TABLE_RD();
 			return (TRUE);
 		}
 	}
@@ -2465,24 +2455,22 @@
 		/*
 		 * See if this pvo has a valid PTE.  if so, fetch the
 		 * REF/CHG bits from the valid PTE.  If the appropriate
-		 * ptebit is set, cache it and return success.
+		 * ptebit is set, return success.
 		 */
-		LOCK_TABLE();
+		PMAP_LOCK(pvo->pvo_pmap);
 		pt =3D MOEA64_PVO_TO_PTE(mmu, pvo);
 		if (pt !=3D -1) {
 			MOEA64_PTE_SYNCH(mmu, pt, &pvo->pvo_pte.lpte);
 			if (pvo->pvo_pte.lpte.pte_lo & ptebit) {
-				UNLOCK_TABLE();
-
-				moea64_attr_save(m, ptebit);
-				vm_page_unlock_queues();
+				PMAP_UNLOCK(pvo->pvo_pmap);
+				UNLOCK_TABLE_RD();
 				return (TRUE);
 			}
 		}
-		UNLOCK_TABLE();
+		PMAP_UNLOCK(pvo->pvo_pmap);
 	}
=20
-	vm_page_unlock_queues();
+	UNLOCK_TABLE_RD();
 	return (FALSE);
 }
=20
@@ -2493,13 +2481,6 @@
 	struct	pvo_entry *pvo;
 	uintptr_t pt;
=20
-	vm_page_lock_queues();
-
-	/*
-	 * Clear the cached value.
-	 */
-	moea64_attr_clear(m, ptebit);
-
 	/*
 	 * Sync so that any pending REF/CHG bits are flushed to the PTEs (so
 	 * we can reset the right ones).  note that since the pvo entries and
@@ -2514,9 +2495,9 @@
 	 * valid pte clear the ptebit from the valid pte.
 	 */
 	count =3D 0;
+	LOCK_TABLE_RD();
 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
-
-		LOCK_TABLE();
+		PMAP_LOCK(pvo->pvo_pmap);
 		pt =3D MOEA64_PVO_TO_PTE(mmu, pvo);
 		if (pt !=3D -1) {
 			MOEA64_PTE_SYNCH(mmu, pt, &pvo->pvo_pte.lpte);
@@ -2527,10 +2508,10 @@
 			}
 		}
 		pvo->pvo_pte.lpte.pte_lo &=3D ~ptebit;
-		UNLOCK_TABLE();
+		PMAP_UNLOCK(pvo->pvo_pmap);
 	}
=20
-	vm_page_unlock_queues();
+	UNLOCK_TABLE_RD();
 	return (count);
 }
=20
@@ -2541,6 +2522,7 @@
 	vm_offset_t ppa;
 	int error =3D 0;
=20
+	LOCK_TABLE_RD();
 	PMAP_LOCK(kernel_pmap);
 	for (ppa =3D pa & ~ADDR_POFF; ppa < pa + size; ppa +=3D PAGE_SIZE) {
 		pvo =3D moea64_pvo_find_va(kernel_pmap, ppa);
@@ -2550,6 +2532,7 @@
 			break;
 		}
 	}
+	UNLOCK_TABLE_RD();
 	PMAP_UNLOCK(kernel_pmap);
=20
 	return (error);
@@ -2568,7 +2551,7 @@
=20
 	ppa =3D trunc_page(pa);
 	offset =3D pa & PAGE_MASK;
-	size =3D roundup(offset + size, PAGE_SIZE);
+	size =3D roundup2(offset + size, PAGE_SIZE);
=20
 	va =3D kmem_alloc_nofault(kernel_map, size);
=20
@@ -2599,7 +2582,7 @@
=20
 	base =3D trunc_page(va);
 	offset =3D va & PAGE_MASK;
-	size =3D roundup(offset + size, PAGE_SIZE);
+	size =3D roundup2(offset + size, PAGE_SIZE);
=20
 	kmem_free(kernel_map, base, size);
 }
@@ -2612,6 +2595,7 @@
 	vm_paddr_t pa;
 	vm_size_t len;
=20
+	LOCK_TABLE_RD();
 	PMAP_LOCK(pm);
 	while (sz > 0) {
 		lim =3D round_page(va);
@@ -2625,5 +2609,6 @@
 		va +=3D len;
 		sz -=3D len;
 	}
+	UNLOCK_TABLE_RD();
 	PMAP_UNLOCK(pm);
 }
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/aim/moea64_native.c
--- a/head/sys/powerpc/aim/moea64_native.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/aim/moea64_native.c	Tue Apr 17 11:51:51 2012 +0300
@@ -91,7 +91,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/powerpc/aim/moea64_native.c 222614 2011-06-02=
 14:15:44Z nwhitehorn $");
+__FBSDID("$FreeBSD: head/sys/powerpc/aim/moea64_native.c 233964 2012-04-06=
 22:33:13Z nwhitehorn $");
=20
 /*
  * Native 64-bit page table operations for running without a hypervisor.
@@ -103,6 +103,7 @@
 #include <sys/lock.h>
 #include <sys/mutex.h>
 #include <sys/proc.h>
+#include <sys/sched.h>
 #include <sys/sysctl.h>
 #include <sys/systm.h>
=20
@@ -138,7 +139,7 @@
  * Just to add to the fun, exceptions must be off as well
  * so that we can't trap in 64-bit mode. What a pain.
  */
-struct mtx	tlbie_mutex;
+static struct mtx	tlbie_mutex;
=20
 static __inline void
 TLBIE(uint64_t vpn) {
@@ -151,25 +152,22 @@
 	vpn <<=3D ADDR_PIDX_SHFT;
 	vpn &=3D ~(0xffffULL << 48);
=20
-	mtx_lock_spin(&tlbie_mutex);
 #ifdef __powerpc64__
-	__asm __volatile("\
-	    ptesync; \
-	    tlbie %0; \
-	    eieio; \
-	    tlbsync; \
-	    ptesync;"=20
-	:: "r"(vpn) : "memory");
+	mtx_lock(&tlbie_mutex);
+	__asm __volatile("tlbie %0" :: "r"(vpn) : "memory");
+	mtx_unlock(&tlbie_mutex);
+	__asm __volatile("eieio; tlbsync; ptesync");
 #else
 	vpn_hi =3D (uint32_t)(vpn >> 32);
 	vpn_lo =3D (uint32_t)vpn;
=20
+	/* Note: spin mutex is to disable exceptions while fiddling MSR */
+	mtx_lock_spin(&tlbie_mutex);
 	__asm __volatile("\
 	    mfmsr %0; \
 	    mr %1, %0; \
 	    insrdi %1,%5,1,0; \
 	    mtmsrd %1; isync; \
-	    ptesync; \
 	    \
 	    sld %1,%2,%4; \
 	    or %1,%1,%3; \
@@ -181,8 +179,8 @@
 	    ptesync;"=20
 	: "=3Dr"(msr), "=3Dr"(scratch) : "r"(vpn_hi), "r"(vpn_lo), "r"(32), "r"(1)
 	    : "memory");
+	mtx_unlock_spin(&tlbie_mutex);
 #endif
-	mtx_unlock_spin(&tlbie_mutex);
 }
=20
 #define DISABLE_TRANS(msr)	msr =3D mfmsr(); mtmsr(msr & ~PSL_DR)
@@ -263,7 +261,9 @@
 	 * As shown in Section 7.6.3.2.3
 	 */
 	pt->pte_lo &=3D ~ptebit;
+	sched_pin();
 	TLBIE(vpn);
+	sched_unpin();
 }
=20
 static void
@@ -293,21 +293,16 @@
 {
 	struct lpte *pt =3D (struct lpte *)pt_cookie;
=20
-	pvo_pt->pte_hi &=3D ~LPTE_VALID;
-
-	/* Finish all pending operations */
-	isync();
-
-	/*
-	 * Force the reg & chg bits back into the PTEs.
-	 */
-	SYNC();
-
 	/*
 	 * Invalidate the pte.
 	 */
+	isync();
+	sched_pin();
+	pvo_pt->pte_hi &=3D ~LPTE_VALID;
 	pt->pte_hi &=3D ~LPTE_VALID;
+	PTESYNC();
 	TLBIE(vpn);
+	sched_unpin();
=20
 	/*
 	 * Save the reg & chg bits.
@@ -413,7 +408,11 @@
 	/*
 	 * Initialize the TLBIE lock. TLBIE can only be executed by one CPU.
 	 */
-	mtx_init(&tlbie_mutex, "tlbie mutex", NULL, MTX_SPIN);
+#ifdef __powerpc64__
+	mtx_init(&tlbie_mutex, "tlbie", NULL, MTX_DEF);
+#else
+	mtx_init(&tlbie_mutex, "tlbie", NULL, MTX_SPIN);
+#endif
=20
 	moea64_mid_bootstrap(mmup, kernelstart, kernelend);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/conf/GENERIC
--- a/head/sys/powerpc/conf/GENERIC	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/conf/GENERIC	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/powerpc/conf/GENERIC 232177 2012-02-26 13:45:25Z jhib=
bits $
+# $FreeBSD: head/sys/powerpc/conf/GENERIC 233271 2012-03-21 08:38:42Z ed $
=20
 cpu		AIM
 ident		GENERIC
@@ -141,7 +141,6 @@
 device		ether		# Ethernet support
 device		vlan		# 802.1Q VLAN support
 device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 device		md		# Memory "disks"
 device		ofwd		# Open Firmware disks
 device		gif		# IPv6 and IPv4 tunneling
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/conf/GENERIC64
--- a/head/sys/powerpc/conf/GENERIC64	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/conf/GENERIC64	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check firs=
t=20
 # in NOTES.
 #
-# $FreeBSD: head/sys/powerpc/conf/GENERIC64 232177 2012-02-26 13:45:25Z jh=
ibbits $
+# $FreeBSD: head/sys/powerpc/conf/GENERIC64 233271 2012-03-21 08:38:42Z ed=
 $
=20
 cpu		AIM
 ident		GENERIC
@@ -138,7 +138,6 @@
 device		ether		# Ethernet support
 device		vlan		# 802.1Q VLAN support
 device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 device		md		# Memory "disks"
 device		ofwd		# Open Firmware disks
 device		gif		# IPv6 and IPv4 tunneling
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/conf/MPC85XX
--- a/head/sys/powerpc/conf/MPC85XX	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/conf/MPC85XX	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
 #
 # Custom kernel for Freescale MPC85XX development boards like the CDS etc.
 #
-# $FreeBSD: head/sys/powerpc/conf/MPC85XX 224553 2011-07-31 18:34:38Z marc=
el $
+# $FreeBSD: head/sys/powerpc/conf/MPC85XX 233271 2012-03-21 08:38:42Z ed $
 #
=20
 cpu		E500
@@ -74,7 +74,6 @@
 device		miibus
 device		pass
 device		pci
-device		pty
 device		quicc
 device		random
 #device		rl
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/include/cpu.h
--- a/head/sys/powerpc/include/cpu.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/include/cpu.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  *	$NetBSD: cpu.h,v 1.11 2000/05/26 21:19:53 thorpej Exp $
- * $FreeBSD$
+ * $FreeBSD: head/sys/powerpc/include/cpu.h 234156 2012-04-11 22:23:50Z nw=
hitehorn $
  */
=20
 #ifndef _MACHINE_CPU_H_
@@ -100,6 +100,5 @@
=20
 /* XXX the following should not be here. */
 void	savectx(struct pcb *);
-int	kcopy(const void *, void *, size_t);
=20
 #endif	/* _MACHINE_CPU_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/include/pmap.h
--- a/head/sys/powerpc/include/pmap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/include/pmap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/powerpc/include/pmap.h 228412 2011-12-11 17:19:48Z n=
whitehorn $
+ * $FreeBSD: head/sys/powerpc/include/pmap.h 233948 2012-04-06 16:00:37Z n=
whitehorn $
  */
 /*-
  * Copyright (C) 1995, 1996 Wolfgang Solfrank.
@@ -212,8 +212,9 @@
 #define	PMAP_LOCK_ASSERT(pmap, type) \
 				mtx_assert(&(pmap)->pm_mtx, (type))
 #define	PMAP_LOCK_DESTROY(pmap)	mtx_destroy(&(pmap)->pm_mtx)
-#define	PMAP_LOCK_INIT(pmap)	mtx_init(&(pmap)->pm_mtx, "pmap", \
-				    NULL, MTX_DEF)
+#define	PMAP_LOCK_INIT(pmap)	mtx_init(&(pmap)->pm_mtx, \
+				    (pmap =3D=3D kernel_pmap) ? "kernelpmap" : \
+				    "pmap", NULL, MTX_DEF)
 #define	PMAP_LOCKED(pmap)	mtx_owned(&(pmap)->pm_mtx)
 #define	PMAP_MTX(pmap)		(&(pmap)->pm_mtx)
 #define	PMAP_TRYLOCK(pmap)	mtx_trylock(&(pmap)->pm_mtx)
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/include/pmc_mdep.h
--- a/head/sys/powerpc/include/pmc_mdep.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/include/pmc_mdep.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,13 +1,14 @@
 /*-
  * This file is in the public domain.
  *
- * $FreeBSD: head/sys/powerpc/include/pmc_mdep.h 228869 2011-12-24 19:34:5=
2Z jhibbits $
+ * $FreeBSD: head/sys/powerpc/include/pmc_mdep.h 233628 2012-03-28 20:58:3=
0Z fabient $
  */
=20
 #ifndef _MACHINE_PMC_MDEP_H_
 #define	_MACHINE_PMC_MDEP_H_
=20
-#define PMC_MDEP_CLASS_INDEX_PPC7450	0
+#define PMC_MDEP_CLASS_INDEX_PPC7450	1
+
 union pmc_md_op_pmcallocate {
 	uint64_t		__pad[4];
 };
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/include/trap.h
--- a/head/sys/powerpc/include/trap.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/include/trap.h	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/powerpc/include/trap.h 233635 2012-03-29 02:02:14Z n=
whitehorn $ */
=20
 #if defined(AIM)
 #include <machine/trap_aim.h>
@@ -6,7 +6,3 @@
 #include <machine/trap_booke.h>
 #endif
=20
-#ifndef LOCORE
-struct trapframe;
-void    trap(struct trapframe *);
-#endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/include/trap_aim.h
--- a/head/sys/powerpc/include/trap_aim.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/include/trap_aim.h	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  * $NetBSD: trap.h,v 1.7 2002/02/22 13:51:40 kleink Exp $
- * $FreeBSD$
+ * $FreeBSD: head/sys/powerpc/include/trap_aim.h 233635 2012-03-29 02:02:1=
4Z nwhitehorn $
  */
=20
 #ifndef	_POWERPC_TRAP_H_
@@ -119,4 +119,9 @@
 #define	EXC_PGM_PRIV		(1UL << 18)
 #define	EXC_PGM_TRAP		(1UL << 17)
=20
+#ifndef LOCORE
+struct	trapframe;
+void    trap(struct trapframe *);
+#endif
+
 #endif	/* _POWERPC_TRAP_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/include/trap_booke.h
--- a/head/sys/powerpc/include/trap_booke.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/include/trap_booke.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/powerpc/include/trap_booke.h 233635 2012-03-29 02:02=
:14Z nwhitehorn $
  */
=20
 #ifndef	_POWERPC_TRAP_H_
@@ -52,4 +52,9 @@
=20
 #define	EXC_LAST	255
=20
+#ifndef LOCORE
+struct	trapframe;
+void    trap(struct trapframe *);
+#endif
+
 #endif	/* _POWERPC_TRAP_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/include/vm.h
--- a/head/sys/powerpc/include/vm.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/include/vm.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/powerpc/include/vm.h 233671 2012-03-29 16:51:22Z jhb=
 $
  */
=20
 #ifndef _MACHINE_VM_H_
@@ -34,7 +34,6 @@
 /* Memory attributes. */
 #define	VM_MEMATTR_DEFAULT		0
 #define	VM_MEMATTR_UNCACHEABLE		0x01
-#define	VM_MEMATTR_UNCACHED		VM_MEMATTR_UNCACHEABLE
 #define	VM_MEMATTR_CACHEABLE		0x02
 #define	VM_MEMATTR_WRITE_COMBINING	0x04
 #define	VM_MEMATTR_WRITE_BACK		0x08
diff -r 428842767fa6 -r f2935497fa04 head/sys/powerpc/powerpc/exec_machdep.c
--- a/head/sys/powerpc/powerpc/exec_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/powerpc/powerpc/exec_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -55,7 +55,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/powerpc/powerpc/exec_machdep.c 225617 2011-09=
-16 13:58:51Z kmacy $");
+__FBSDID("$FreeBSD: head/sys/powerpc/powerpc/exec_machdep.c 234115 2012-04=
-11 00:00:40Z nwhitehorn $");
=20
 #include "opt_compat.h"
=20
@@ -441,6 +441,7 @@
 {
 	struct pcb *pcb;
 	struct trapframe *tf;
+	register_t tls;
=20
 	pcb =3D td->td_pcb;
 	tf =3D td->td_frame;
@@ -448,16 +449,25 @@
 	if (mcp->mc_vers !=3D _MC_VERSION || mcp->mc_len !=3D sizeof(*mcp))
 		return (EINVAL);
=20
-	#ifdef AIM
+#ifdef AIM
 	/*
 	 * Don't let the user set privileged MSR bits
 	 */
 	if ((mcp->mc_srr1 & PSL_USERSTATIC) !=3D (tf->srr1 & PSL_USERSTATIC)) {
 		return (EINVAL);
 	}
-	#endif
+#endif
=20
+	/* Copy trapframe, preserving TLS pointer across context change */
+	if (SV_PROC_FLAG(td->td_proc, SV_LP64))
+		tls =3D tf->fixreg[13];
+	else
+		tls =3D tf->fixreg[2];
 	memcpy(tf, mcp->mc_frame, sizeof(mcp->mc_frame));
+	if (SV_PROC_FLAG(td->td_proc, SV_LP64))
+		tf->fixreg[13] =3D tls;
+	else
+		tf->fixreg[2] =3D tls;
=20
 #ifdef AIM
 	if (mcp->mc_flags & _MC_FP_VALID) {
diff -r 428842767fa6 -r f2935497fa04 head/sys/security/mac/mac_net.c
--- a/head/sys/security/mac/mac_net.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/security/mac/mac_net.c	Tue Apr 17 11:51:51 2012 +0300
@@ -43,7 +43,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/security/mac/mac_net.c 233937 2012-04-06 06:5=
3:58Z melifaro $");
=20
 #include "opt_kdtrace.h"
 #include "opt_mac.h"
@@ -319,6 +319,7 @@
 {
 	struct label *label;
=20
+	/* Assume reader lock is enough. */
 	BPFD_LOCK_ASSERT(d);
=20
 	if (mac_policy_count =3D=3D 0)
@@ -354,6 +355,7 @@
 {
 	int error;
=20
+	/* Assume reader lock is enough. */
 	BPFD_LOCK_ASSERT(d);
=20
 	if (mac_policy_count =3D=3D 0)
diff -r 428842767fa6 -r f2935497fa04 head/sys/security/mac/mac_syscalls.c
--- a/head/sys/security/mac/mac_syscalls.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/security/mac/mac_syscalls.c	Tue Apr 17 11:51:51 2012 +0300
@@ -43,7 +43,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/security/mac/mac_syscalls.c 225617 2011-09-16=
 13:58:51Z kmacy $");
+__FBSDID("$FreeBSD: head/sys/security/mac/mac_syscalls.c 234032 2012-04-08=
 11:01:49Z rwatson $");
=20
 #include "opt_mac.h"
=20
@@ -256,8 +256,10 @@
 	switch (fp->f_type) {
 	case DTYPE_FIFO:
 	case DTYPE_VNODE:
-		if (!(mac_labeled & MPC_OBJECT_VNODE))
-			return (EINVAL);
+		if (!(mac_labeled & MPC_OBJECT_VNODE)) {
+			error =3D EINVAL;
+			goto out_fdrop;
+		}
 		vp =3D fp->f_vnode;
 		intlabel =3D mac_vnode_label_alloc();
 		vfslocked =3D VFS_LOCK_GIANT(vp->v_mount);
@@ -271,8 +273,10 @@
 		break;
=20
 	case DTYPE_PIPE:
-		if (!(mac_labeled & MPC_OBJECT_PIPE))
-			return (EINVAL);
+		if (!(mac_labeled & MPC_OBJECT_PIPE)) {
+			error =3D EINVAL;
+			goto out_fdrop;
+		}
 		pipe =3D fp->f_data;
 		intlabel =3D mac_pipe_label_alloc();
 		PIPE_LOCK(pipe);
@@ -284,8 +288,10 @@
 		break;
=20
 	case DTYPE_SOCKET:
-		if (!(mac_labeled & MPC_OBJECT_SOCKET))
-			return (EINVAL);
+		if (!(mac_labeled & MPC_OBJECT_SOCKET)) {
+			error =3D EINVAL;
+			goto out_fdrop;
+		}
 		so =3D fp->f_data;
 		intlabel =3D mac_socket_label_alloc(M_WAITOK);
 		SOCK_LOCK(so);
@@ -299,10 +305,10 @@
 	default:
 		error =3D EINVAL;
 	}
-	fdrop(fp, td);
 	if (error =3D=3D 0)
 		error =3D copyout(buffer, mac.m_string, strlen(buffer)+1);
-
+out_fdrop:
+	fdrop(fp, td);
 out:
 	free(buffer, M_MACTEMP);
 	free(elements, M_MACTEMP);
@@ -450,8 +456,10 @@
 	switch (fp->f_type) {
 	case DTYPE_FIFO:
 	case DTYPE_VNODE:
-		if (!(mac_labeled & MPC_OBJECT_VNODE))
-			return (EINVAL);
+		if (!(mac_labeled & MPC_OBJECT_VNODE)) {
+			error =3D EINVAL;
+			goto out_fdrop;
+		}
 		intlabel =3D mac_vnode_label_alloc();
 		error =3D mac_vnode_internalize_label(intlabel, buffer);
 		if (error) {
@@ -475,8 +483,10 @@
 		break;
=20
 	case DTYPE_PIPE:
-		if (!(mac_labeled & MPC_OBJECT_PIPE))
-			return (EINVAL);
+		if (!(mac_labeled & MPC_OBJECT_PIPE)) {
+			error =3D EINVAL;
+			goto out_fdrop;
+		}
 		intlabel =3D mac_pipe_label_alloc();
 		error =3D mac_pipe_internalize_label(intlabel, buffer);
 		if (error =3D=3D 0) {
@@ -490,8 +500,10 @@
 		break;
=20
 	case DTYPE_SOCKET:
-		if (!(mac_labeled & MPC_OBJECT_SOCKET))
-			return (EINVAL);
+		if (!(mac_labeled & MPC_OBJECT_SOCKET)) {
+			error =3D EINVAL;
+			goto out_fdrop;
+		}
 		intlabel =3D mac_socket_label_alloc(M_WAITOK);
 		error =3D mac_socket_internalize_label(intlabel, buffer);
 		if (error =3D=3D 0) {
@@ -505,6 +517,7 @@
 	default:
 		error =3D EINVAL;
 	}
+out_fdrop:
 	fdrop(fp, td);
 out:
 	free(buffer, M_MACTEMP);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sparc64/conf/GENERIC
--- a/head/sys/sparc64/conf/GENERIC	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sparc64/conf/GENERIC	Tue Apr 17 11:51:51 2012 +0300
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check first
 # in NOTES.
 #
-# $FreeBSD: head/sys/sparc64/conf/GENERIC 229997 2012-01-12 00:34:33Z ken $
+# $FreeBSD: head/sys/sparc64/conf/GENERIC 234348 2012-04-16 18:29:07Z mari=
us $
=20
 cpu		SUN4U
 ident		GENERIC
@@ -27,7 +27,7 @@
 #	At this time all platforms are supported, as-is.
=20
 options 	SCHED_ULE		# ULE scheduler
-#options 	PREEMPTION		# Enable kernel thread preemption
+options 	PREEMPTION		# Enable kernel thread preemption
 options 	INET			# InterNETworking
 options 	INET6			# IPv6 communications protocols
 options 	SCTP			# Stream Control Transmission Protocol
@@ -218,7 +218,6 @@
 device		ether		# Ethernet support
 device		vlan		# 802.1Q VLAN support
 device		tun		# Packet tunnel.
-device		pty		# BSD-style compatibility pseudo ttys
 device		md		# Memory "disks"
 device		gif		# IPv6 and IPv4 tunneling
 device		faith		# IPv6-to-IPv4 relaying (translation)
diff -r 428842767fa6 -r f2935497fa04 head/sys/sparc64/pci/fire.c
--- a/head/sys/sparc64/pci/fire.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sparc64/pci/fire.c	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/sparc64/pci/fire.c 227843 2011-11-22 21:28:20=
Z marius $");
+__FBSDID("$FreeBSD: head/sys/sparc64/pci/fire.c 233701 2012-03-30 15:08:09=
Z marius $");
=20
 /*
  * Driver for `Fire' JBus to PCI Express and `Oberon' Uranus to PCI Express
@@ -443,10 +443,11 @@
 			lw =3D 0;
 		}
 		mps =3D (FIRE_PCI_READ_8(sc, FO_PCI_TLU_CTRL) &
-		    FO_PCI_TLU_CTRL_CFG_MASK) >> FO_PCI_TLU_CTRL_CFG_SHFT;
+		    FO_PCI_TLU_CTRL_CFG_MPS_MASK) >>
+		    FO_PCI_TLU_CTRL_CFG_MPS_SHFT;
 		i =3D sizeof(fire_freq_nak_tmr_thrs) /
 		    sizeof(*fire_freq_nak_tmr_thrs);
-		if (mps >=3D i);
+		if (mps >=3D i)
 			mps =3D i - 1;
 		FIRE_PCI_SET(sc, FO_PCI_LPU_TXLNK_FREQ_LAT_TMR_THRS,
 		    (fire_freq_nak_tmr_thrs[mps][lw] <<
@@ -764,7 +765,7 @@
 	if (sc->sc_pci_cfgt =3D=3D NULL)
 		panic("%s: could not allocate PCI configuration space tag",
 		    __func__);
-	if (bus_dma_tag_create(bus_get_dma_tag(dev), 8, 0,
+	if (bus_dma_tag_create(bus_get_dma_tag(dev), 8, 0x100000000,
 	    sc->sc_is.is_pmaxaddr, ~0, NULL, NULL, sc->sc_is.is_pmaxaddr,
 	    0xff, 0xffffffff, 0, NULL, NULL, &sc->sc_pci_dmat) !=3D 0)
 		panic("%s: could not create PCI DMA tag", __func__);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sparc64/pci/firereg.h
--- a/head/sys/sparc64/pci/firereg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sparc64/pci/firereg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/sparc64/pci/firereg.h 233701 2012-03-30 15:08:09Z ma=
rius $
  */
=20
 #ifndef _SPARC64_PCI_FIREREG_H_
@@ -345,6 +345,13 @@
 #define	FO_PCI_TLU_CTRL_CFG_MASK		0x000000000000ffffULL
 #define	FO_PCI_TLU_CTRL_CFG_SHFT		0
 #define	FO_PCI_TLU_CTRL_CFG_REMAIN_DETECT_QUIET	0x0000000000000100ULL
+#define	FO_PCI_TLU_CTRL_CFG_PAD_LOOPBACK_EN	0x0000000000000080ULL
+#define	FO_PCI_TLU_CTRL_CFG_EWRAP_LOOPBACK_EN	0x0000000000000040ULL
+#define	FO_PCI_TLU_CTRL_CFG_DIGITAL_LOOPBACK_EN	0x0000000000000020ULL
+#define	FO_PCI_TLU_CTRL_CFG_MPS_MASK		0x000000000000001cULL
+#define	FO_PCI_TLU_CTRL_CFG_MPS_SHFT		2
+#define	FO_PCI_TLU_CTRL_CFG_COMMON_CLK_CFG	0x0000000000000002ULL
+#define	FO_PCI_TLU_CTRL_CFG_PORT		0x0000000000000001ULL
=20
 /*
  * PCI TLU other event interrupt enable, interrupt status and status clear
diff -r 428842767fa6 -r f2935497fa04 head/sys/sparc64/sparc64/intr_machdep.c
--- a/head/sys/sparc64/sparc64/intr_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sparc64/sparc64/intr_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -59,7 +59,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/intr_machdep.c 224187 2011-07=
-18 15:19:40Z attilio $");
+__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/intr_machdep.c 234247 2012-04=
-13 22:58:23Z marius $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -528,9 +528,6 @@
 	struct intr_vector *iv;
 	int i;
=20
-	/* The BSP is always a valid target. */
-	CPU_SETOF(0, &intr_cpus);
-
 	/* Don't bother on UP. */
 	if (mp_ncpus =3D=3D 1)
 		return;
diff -r 428842767fa6 -r f2935497fa04 head/sys/sparc64/sparc64/machdep.c
--- a/head/sys/sparc64/sparc64/machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sparc64/sparc64/machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/machdep.c 230633 2012-01-27 2=
3:21:54Z marius $");
+__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/machdep.c 234247 2012-04-13 2=
2:58:23Z marius $");
=20
 #include "opt_compat.h"
 #include "opt_ddb.h"
@@ -196,6 +196,13 @@
 		printf("machine: %s\n", sparc64_model);
=20
 	cpu_identify(rdpr(ver), PCPU_GET(clock), curcpu);
+
+#ifdef SMP
+	/*
+	 * Add BSP as an interrupt target.
+	 */
+	intr_add_cpu(0);
+#endif
 }
=20
 void
diff -r 428842767fa6 -r f2935497fa04 head/sys/sparc64/sparc64/trap.c
--- a/head/sys/sparc64/sparc64/trap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sparc64/sparc64/trap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -36,7 +36,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/trap.c 225474 2011-09-11 16:0=
5:09Z kib $");
+__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/trap.c 233748 2012-03-31 14:0=
3:16Z marius $");
=20
 #include "opt_ddb.h"
 #include "opt_ktr.h"
@@ -215,6 +215,9 @@
 	-1,			/* kernel stack fault */
 };
=20
+CTASSERT(sizeof(trap_msg) / sizeof(*trap_msg) =3D=3D T_MAX);
+CTASSERT(sizeof(trap_sig) / sizeof(*trap_sig) =3D=3D T_MAX);
+
 CTASSERT(sizeof(struct trapframe) =3D=3D 256);
=20
 int debugger_on_signal =3D 0;
@@ -298,7 +301,7 @@
 			sig =3D trap_cecc();
 			break;
 		default:
-			if (tf->tf_type < 0 || tf->tf_type >=3D T_MAX)
+			if (tf->tf_type > T_MAX)
 				panic("trap: bad trap type %#lx (user)",
 				    tf->tf_type);
 			else if (trap_sig[tf->tf_type] =3D=3D -1)
@@ -402,12 +405,10 @@
=20
 		if (error !=3D 0) {
 			tf->tf_type &=3D ~T_KERNEL;
-			if (tf->tf_type < 0 || tf->tf_type >=3D T_MAX)
+			if (tf->tf_type > T_MAX)
 				panic("trap: bad trap type %#lx (kernel)",
 				    tf->tf_type);
-			else if (trap_sig[tf->tf_type] =3D=3D -1)
-				panic("trap: %s (kernel)",
-				    trap_msg[tf->tf_type]);
+			panic("trap: %s (kernel)", trap_msg[tf->tf_type]);
 		}
 	}
 	CTR1(KTR_TRAP, "trap: td=3D%p return", td);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/bus.h
--- a/head/sys/sys/bus.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/bus.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/bus.h 227849 2011-11-22 21:56:55Z hselasky $
+ * $FreeBSD: head/sys/sys/bus.h 234152 2012-04-11 20:57:41Z jhb $
  */
=20
 #ifndef _SYS_BUS_H_
@@ -53,6 +53,7 @@
 typedef enum device_state {
 	DS_NOTPRESENT =3D 10,		/**< @brief not probed or probe failed */
 	DS_ALIVE =3D 20,			/**< @brief probe succeeded */
+	DS_ATTACHING =3D 25,		/**< @brief currently attaching */
 	DS_ATTACHED =3D 30,		/**< @brief attach method called */
 	DS_BUSY =3D 40			/**< @brief device is open */
 } device_state_t;
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/conf.h
--- a/head/sys/sys/conf.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/conf.h	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)conf.h	8.5 (Berkeley) 1/9/95
- * $FreeBSD: head/sys/sys/conf.h 231379 2012-02-10 12:40:50Z ed $
+ * $FreeBSD: head/sys/sys/conf.h 233627 2012-03-28 20:49:11Z mckusick $
  */
=20
 #ifndef _SYS_CONF_H_
@@ -52,7 +52,7 @@
 struct file;
=20
 struct cdev {
-	void		*__si_reserved;
+	void		*si_spare0;
 	u_int		si_flags;
 #define	SI_ETERNAL	0x0001	/* never destroyed */
 #define	SI_ALIAS	0x0002	/* carrier of alias name */
@@ -78,7 +78,7 @@
 	LIST_HEAD(, cdev)	si_children;
 	LIST_ENTRY(cdev)	si_siblings;
 	struct cdev *si_parent;
-	void		*si_spare0;
+	struct mount	*si_mountpt;
 	void		*si_drv1, *si_drv2;
 	struct cdevsw	*si_devsw;
 	int		si_iosize_max;	/* maximum I/O size (for physio &al) */
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/elf_common.h
--- a/head/sys/sys/elf_common.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/elf_common.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/elf_common.h 231617 2012-02-14 00:12:55Z gonzo $
+ * $FreeBSD: head/sys/sys/elf_common.h 233523 2012-03-26 21:26:23Z gonzo $
  */
=20
 #ifndef _SYS_ELF_COMMON_H_
@@ -296,6 +296,8 @@
 #define	SHT_HIOS		0x6fffffff	/* Last of OS specific semantics */
 #define	SHT_LOPROC		0x70000000	/* reserved range for processor */
 #define	SHT_AMD64_UNWIND	0x70000001	/* unwind information */
+#define	SHT_MIPS_REGINFO	0x70000006
+#define	SHT_MIPS_OPTIONS	0x7000000d
 #define	SHT_MIPS_DWARF		0x7000001e	/* MIPS gcc uses MIPS_DWARF */
 #define	SHT_HIPROC		0x7fffffff	/* specific section header types */
 #define	SHT_LOUSER		0x80000000	/* reserved range for application */
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/event.h
--- a/head/sys/sys/event.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/event.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/event.h 227267 2011-11-06 20:16:50Z ed $
+ * $FreeBSD: head/sys/sys/event.h 233505 2012-03-26 09:34:17Z melifaro $
  */
=20
 #ifndef _SYS_EVENT_H_
@@ -234,6 +234,7 @@
 struct proc;
 struct knlist;
 struct mtx;
+struct rwlock;
=20
 extern void	knote(struct knlist *list, long hint, int lockflags);
 extern void	knote_fork(struct knlist *list, int pid);
@@ -245,6 +246,7 @@
     void (*kl_lock)(void *), void (*kl_unlock)(void *),
     void (*kl_assert_locked)(void *), void (*kl_assert_unlocked)(void *));
 extern void	knlist_init_mtx(struct knlist *knl, struct mtx *lock);
+extern void	knlist_init_rw_reader(struct knlist *knl, struct rwlock *lock);
 extern void	knlist_destroy(struct knlist *knl);
 extern void	knlist_cleardel(struct knlist *knl, struct thread *td,
 	int islocked, int killkn);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/kdb.h
--- a/head/sys/sys/kdb.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/kdb.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/kdb.h 225203 2011-08-26 21:46:36Z rwatson $
+ * $FreeBSD: head/sys/sys/kdb.h 234190 2012-04-12 17:43:59Z jhb $
  */
=20
 #ifndef _SYS_KDB_H_
@@ -31,31 +31,34 @@
=20
 #include <machine/setjmp.h>
=20
+struct pcb;
+struct thread;
+struct trapframe;
+
 typedef int dbbe_init_f(void);
 typedef void dbbe_trace_f(void);
+typedef void dbbe_trace_thread_f(struct thread *);
 typedef int dbbe_trap_f(int, int);
=20
 struct kdb_dbbe {
 	const char	*dbbe_name;
 	dbbe_init_f	*dbbe_init;
 	dbbe_trace_f	*dbbe_trace;
+	dbbe_trace_thread_f *dbbe_trace_thread;
 	dbbe_trap_f	*dbbe_trap;
 	int		dbbe_active;
 };
=20
-#define	KDB_BACKEND(name, init, trace, trap)		\
+#define	KDB_BACKEND(name, init, trace, trace_thread, trap) \
 	static struct kdb_dbbe name##_dbbe =3D {		\
 		.dbbe_name =3D #name,			\
 		.dbbe_init =3D init,			\
 		.dbbe_trace =3D trace,			\
+		.dbbe_trace_thread =3D trace_thread,	\
 		.dbbe_trap =3D trap			\
 	};						\
 	DATA_SET(kdb_dbbe_set, name##_dbbe)
=20
-struct pcb;
-struct thread;
-struct trapframe;
-
 extern int kdb_active;			/* Non-zero while in debugger. */
 extern int debugger_on_panic;		/* enter the debugger on panic. */
 extern struct kdb_dbbe *kdb_dbbe;	/* Default debugger backend or NULL. */
@@ -67,6 +70,7 @@
 int	kdb_alt_break_gdb(int, int *);
 int	kdb_break(void);
 void	kdb_backtrace(void);
+void	kdb_backtrace_thread(struct thread *);
 int	kdb_dbbe_select(const char *);
 void	kdb_enter(const char *, const char *);
 void	kdb_init(void);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/ktrace.h
--- a/head/sys/sys/ktrace.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/ktrace.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)ktrace.h	8.1 (Berkeley) 6/2/93
- * $FreeBSD: head/sys/sys/ktrace.h 226495 2011-10-18 07:28:58Z des $
+ * $FreeBSD: head/sys/sys/ktrace.h 233925 2012-04-05 17:13:14Z jhb $
  */
=20
 #ifndef _SYS_KTRACE_H_
@@ -194,6 +194,23 @@
 };
=20
 /*
+ * KTR_FAULT - page fault record
+ */
+#define KTR_FAULT	13
+struct ktr_fault {
+	vm_offset_t vaddr;
+	int type;
+};
+
+/*
+ * KTR_FAULTEND - end of page fault record
+ */
+#define KTR_FAULTEND	14
+struct ktr_faultend {
+	int result;
+};
+
+/*
  * KTR_DROP - If this bit is set in ktr_type, then at least one event
  * between the previous record and this record was dropped.
  */
@@ -215,6 +232,8 @@
 #define KTRFAC_PROCCTOR	(1<<KTR_PROCCTOR)
 #define KTRFAC_PROCDTOR	(1<<KTR_PROCDTOR)
 #define KTRFAC_CAPFAIL	(1<<KTR_CAPFAIL)
+#define KTRFAC_FAULT	(1<<KTR_FAULT)
+#define KTRFAC_FAULTEND	(1<<KTR_FAULTEND)
=20
 /*
  * trace flags (also in p_traceflags)
@@ -227,6 +246,8 @@
 void	ktrnamei(char *);
 void	ktrcsw(int, int);
 void	ktrpsig(int, sig_t, sigset_t *, int);
+void	ktrfault(vm_offset_t, int);
+void	ktrfaultend(int);
 void	ktrgenio(int, enum uio_rw, struct uio *, int);
 void	ktrsyscall(int, int narg, register_t args[]);
 void	ktrsysctl(int *name, u_int namelen);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/libkern.h
--- a/head/sys/sys/libkern.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/libkern.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)libkern.h	8.1 (Berkeley) 6/10/93
- * $FreeBSD: head/sys/sys/libkern.h 229366 2012-01-03 07:05:30Z ed $
+ * $FreeBSD: head/sys/sys/libkern.h 233517 2012-03-26 18:22:04Z marius $
  */
=20
 #ifndef _SYS_LIBKERN_H_
@@ -121,7 +121,7 @@
 char	*strstr(const char *, const char *);
 int	 strvalid(const char *, size_t);
=20
-extern uint32_t crc32_tab[];
+extern const uint32_t crc32_tab[];
=20
 static __inline uint32_t
 crc32_raw(const void *buf, size_t size, uint32_t crc)
@@ -143,8 +143,8 @@
 }
=20
 uint32_t
-calculate_crc32c(uint32_t crc32c, const unsigned char *buffer,=20
-        unsigned int length);
+calculate_crc32c(uint32_t crc32c, const unsigned char *buffer,
+    unsigned int length);
=20
=20
 LIBKERN_INLINE void *memset(void *, int, size_t);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/mman.h
--- a/head/sys/sys/mman.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/mman.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)mman.h	8.2 (Berkeley) 1/9/95
- * $FreeBSD: head/sys/sys/mman.h 228509 2011-12-14 22:22:19Z jhb $
+ * $FreeBSD: head/sys/sys/mman.h 233760 2012-04-01 18:22:48Z jhb $
  */
=20
 #ifndef _SYS_MMAN_H_
@@ -178,7 +178,7 @@
 #define	_SIZE_T_DECLARED
 #endif
=20
-#ifdef _KERNEL
+#if defined(_KERNEL) || defined(_WANT_FILE)
 #include <vm/vm.h>
=20
 struct file;
@@ -202,12 +202,16 @@
 	struct timespec	shm_birthtime;
=20
 	struct label	*shm_label;		/* MAC label */
+	const char	*shm_path;
 };
+#endif
=20
+#ifdef _KERNEL
 int	shm_mmap(struct shmfd *shmfd, vm_size_t objsize, vm_ooffset_t foff,
 	    vm_object_t *obj);
 int	shm_map(struct file *fp, size_t size, off_t offset, void **memp);
 int	shm_unmap(struct file *fp, void *mem, size_t size);
+void	shm_path(struct shmfd *shmfd, char *path, size_t size);
=20
 #else /* !_KERNEL */
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/mount.h
--- a/head/sys/sys/mount.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/mount.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)mount.h	8.21 (Berkeley) 5/20/95
- * $FreeBSD: head/sys/sys/mount.h 232709 2012-03-09 00:12:05Z kib $
+ * $FreeBSD: head/sys/sys/mount.h 234157 2012-04-11 22:43:40Z mckusick $
  */
=20
 #ifndef _SYS_MOUNT_H_
@@ -199,10 +199,10 @@
 	__mnt_vnode_markerfree(&(mvp), (mp))
=20
 #define MNT_VNODE_FOREACH_ABORT(mp, mvp)				\
-        do {								\
-	  MNT_ILOCK(mp);						\
-          MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);			\
-	  MNT_IUNLOCK(mp);						\
+	do {								\
+		MNT_ILOCK(mp);						\
+		MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);		\
+		MNT_IUNLOCK(mp);					\
 	} while (0)
=20
 #define	MNT_ILOCK(mp)	mtx_lock(&(mp)->mnt_mtx)
@@ -211,7 +211,7 @@
 #define	MNT_MTX(mp)	(&(mp)->mnt_mtx)
 #define	MNT_REF(mp)	(mp)->mnt_ref++
 #define	MNT_REL(mp)	do {						\
-	KASSERT((mp)->mnt_ref > 0, ("negative mnt_ref"));			\
+	KASSERT((mp)->mnt_ref > 0, ("negative mnt_ref"));		\
 	(mp)->mnt_ref--;						\
 	if ((mp)->mnt_ref =3D=3D 0)						\
 		wakeup((mp));						\
@@ -718,6 +718,8 @@
 	    uint64_t val);
 int	vfs_getopt(struct vfsoptlist *, const char *, void **, int *);
 int	vfs_getopt_pos(struct vfsoptlist *opts, const char *name);
+int	vfs_getopt_size(struct vfsoptlist *opts, const char *name,
+	    off_t *value);
 char	*vfs_getopts(struct vfsoptlist *, const char *, int *error);
 int	vfs_copyopt(struct vfsoptlist *, const char *, void *, int);
 int	vfs_filteropt(struct vfsoptlist *, const char **legal);
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/param.h
--- a/head/sys/sys/param.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/param.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)param.h	8.3 (Berkeley) 4/4/95
- * $FreeBSD: head/sys/sys/param.h 232154 2012-02-25 11:03:13Z mm $
+ * $FreeBSD: head/sys/sys/param.h 234355 2012-04-16 21:28:04Z dim $
  */
=20
 #ifndef _SYS_PARAM_H_
@@ -58,7 +58,7 @@
  *		in the range 5 to 9.
  */
 #undef __FreeBSD_version
-#define __FreeBSD_version 1000009	/* Master, propagated to newvers */
+#define __FreeBSD_version 1000011	/* Master, propagated to newvers */
=20
 /*
  * __FreeBSD_kernel__ indicates that this system uses the kernel of FreeBS=
D,
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/pmc.h
--- a/head/sys/sys/pmc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/pmc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/pmc.h 232366 2012-03-01 21:23:26Z davide $
+ * $FreeBSD: head/sys/sys/pmc.h 233628 2012-03-28 20:58:30Z fabient $
  */
=20
 #ifndef _SYS_PMC_H_
@@ -39,8 +39,8 @@
 #include <machine/profile.h>
=20
 #define	PMC_MODULE_NAME		"hwpmc"
-#define	PMC_NAME_MAX		16 /* HW counter name size */
-#define	PMC_CLASS_MAX		6  /* max #classes of PMCs per-system */
+#define	PMC_NAME_MAX		64 /* HW counter name size */
+#define	PMC_CLASS_MAX		8  /* max #classes of PMCs per-system */
=20
 /*
  * Kernel<->userland API version number [MMmmpppp]
@@ -83,13 +83,15 @@
 	__PMC_CPU(INTEL_CORE,	0x87,	"Intel Core Solo/Duo")	\
 	__PMC_CPU(INTEL_CORE2,	0x88,	"Intel Core2")		\
 	__PMC_CPU(INTEL_CORE2EXTREME,	0x89,	"Intel Core2 Extreme")	\
-	__PMC_CPU(INTEL_ATOM,	0x8A,	"Intel Atom") \
-	__PMC_CPU(INTEL_COREI7, 0x8B,   "Intel Core i7") \
-	__PMC_CPU(INTEL_WESTMERE, 0x8C,   "Intel Westmere") \
-	__PMC_CPU(INTEL_SANDYBRIDGE, 0x8D,   "Intel Sandy Bridge") \
-	__PMC_CPU(INTEL_XSCALE,	0x100,	"Intel XScale") \
-	__PMC_CPU(MIPS_24K,     0x200,  "MIPS 24K")  \
-	__PMC_CPU(PPC_7450,     0x300,  "PowerPC MPC7450")
+	__PMC_CPU(INTEL_ATOM,	0x8A,	"Intel Atom")		\
+	__PMC_CPU(INTEL_COREI7, 0x8B,   "Intel Core i7")	\
+	__PMC_CPU(INTEL_WESTMERE, 0x8C,   "Intel Westmere")	\
+	__PMC_CPU(INTEL_SANDYBRIDGE, 0x8D,   "Intel Sandy Bridge")	\
+	__PMC_CPU(INTEL_XSCALE,	0x100,	"Intel XScale")		\
+	__PMC_CPU(MIPS_24K,     0x200,  "MIPS 24K")		\
+	__PMC_CPU(MIPS_OCTEON,  0x201,  "Cavium Octeon")	\
+	__PMC_CPU(PPC_7450,     0x300,  "PowerPC MPC7450")	\
+	__PMC_CPU(GENERIC, 	0x400,  "Generic")
=20
 enum pmc_cputype {
 #undef	__PMC_CPU
@@ -98,7 +100,7 @@
 };
=20
 #define	PMC_CPU_FIRST	PMC_CPU_AMD_K7
-#define	PMC_CPU_LAST	PMC_CPU_PPC_7450
+#define	PMC_CPU_LAST	PMC_CPU_GENERIC
=20
 /*
  * Classes of PMCs
@@ -116,8 +118,10 @@
 	__PMC_CLASS(UCF)	/* Intel Uncore fixed function */	\
 	__PMC_CLASS(UCP)	/* Intel Uncore programmable */		\
 	__PMC_CLASS(XSCALE)	/* Intel XScale counters */		\
-	__PMC_CLASS(MIPS24K)    /* MIPS 24K */ \
-	__PMC_CLASS(PPC7450)	/* Motorola MPC7450 class */
+	__PMC_CLASS(MIPS24K)	/* MIPS 24K */				\
+	__PMC_CLASS(OCTEON)	/* Cavium Octeon */			\
+	__PMC_CLASS(PPC7450)	/* Motorola MPC7450 class */		\
+	__PMC_CLASS(SOFT)	/* Software events */
=20
 enum pmc_class {
 #undef  __PMC_CLASS
@@ -126,7 +130,7 @@
 };
=20
 #define	PMC_CLASS_FIRST	PMC_CLASS_TSC
-#define	PMC_CLASS_LAST	PMC_CLASS_PPC7450
+#define	PMC_CLASS_LAST	PMC_CLASS_SOFT
=20
 /*
  * A PMC can be in the following states:
@@ -306,7 +310,8 @@
 	__PMC_OP(PMCSTART, "Start a PMC")				\
 	__PMC_OP(PMCSTOP, "Stop a PMC")					\
 	__PMC_OP(WRITELOG, "Write a cookie to the log file")		\
-	__PMC_OP(CLOSELOG, "Close log file")
+	__PMC_OP(CLOSELOG, "Close log file")				\
+	__PMC_OP(GETDYNEVENTINFO, "Get dynamic events list")
=20
=20
 enum pmc_ops {
@@ -336,6 +341,7 @@
 #define	PMC_F_ATTACH_DONE	0x00040000 /*attached at least once */
=20
 #define	PMC_CALLCHAIN_DEPTH_MAX	32
+
 #define	PMC_CC_F_USERSPACE	0x01	   /*userspace callchain*/
=20
 /*
@@ -484,6 +490,7 @@
  * Retrieve system CPU information.
  */
=20
+
 struct pmc_classinfo {
 	enum pmc_class	pm_class;	/* class id */
 	uint32_t	pm_caps;	/* counter capabilities */
@@ -560,6 +567,23 @@
 	pmc_id_t	pm_pmcid;	/* allocated pmc id */
 };
=20
+/*
+ * OP GETDYNEVENTINFO
+ *
+ * Retrieve a PMC dynamic class events list.
+ */
+
+struct pmc_dyn_event_descr {
+	char		pm_ev_name[PMC_NAME_MAX];
+	enum pmc_event	pm_ev_code;
+};
+
+struct pmc_op_getdyneventinfo {
+	enum pmc_class			pm_class;
+	unsigned int			pm_nevent;
+	struct pmc_dyn_event_descr	pm_events[PMC_EV_DYN_COUNT];
+};
+
 #ifdef _KERNEL
=20
 #include <sys/malloc.h>
@@ -570,8 +594,8 @@
 #define	PMC_HASH_SIZE				16
 #define	PMC_MTXPOOL_SIZE			32
 #define	PMC_LOG_BUFFER_SIZE			4
-#define	PMC_NLOGBUFFERS				16
-#define	PMC_NSAMPLES				32
+#define	PMC_NLOGBUFFERS				64
+#define	PMC_NSAMPLES				512
 #define	PMC_CALLCHAIN_DEPTH			8
=20
 #define PMC_SYSCTL_NAME_PREFIX "kern." PMC_MODULE_NAME "."
@@ -589,7 +613,7 @@
  */
=20
 struct pmc_syscall_args {
-	uint32_t	pmop_code;	/* one of PMC_OP_* */
+	register_t	pmop_code;	/* one of PMC_OP_* */
 	void		*pmop_data;	/* syscall parameter */
 };
=20
@@ -827,8 +851,8 @@
 	uintptr_t		*ps_pc;		/* (const) callchain start */
 };
=20
-#define	PMC_SAMPLE_FREE		((uint16_t) 0)
-#define	PMC_SAMPLE_INUSE	((uint16_t) 0xFFFF)
+#define 	PMC_SAMPLE_FREE		((uint16_t) 0)
+#define 	PMC_SAMPLE_INUSE	((uint16_t) 0xFFFF)
=20
 struct pmc_samplebuffer {
 	struct pmc_sample * volatile ps_read;	/* read pointer */
@@ -848,7 +872,7 @@
=20
 struct pmc_cpu {
 	uint32_t	pc_state;	/* physical cpu number + flags */
-	struct pmc_samplebuffer *pc_sb; /* space for samples */
+	struct pmc_samplebuffer *pc_sb[2]; /* space for samples */
 	struct pmc_hw	*pc_hwpmcs[];	/* 'npmc' pointers */
 };
=20
@@ -956,7 +980,7 @@
 /* driver statistics */
 extern struct pmc_op_getdriverstats pmc_stats;
=20
-#if	defined(DEBUG) && DEBUG
+#if	defined(DEBUG)
=20
 /* debug flags, major flag groups */
 struct pmc_debugflags {
@@ -1059,11 +1083,13 @@
 struct pmc_mdep *pmc_md_initialize(void);	/* MD init function */
 void	pmc_md_finalize(struct pmc_mdep *_md);	/* MD fini function */
 int	pmc_getrowdisp(int _ri);
-int	pmc_process_interrupt(int _cpu, struct pmc *_pm,
+int	pmc_process_interrupt(int _cpu, int _soft, struct pmc *_pm,
     struct trapframe *_tf, int _inuserspace);
 int	pmc_save_kernel_callchain(uintptr_t *_cc, int _maxsamples,
     struct trapframe *_tf);
 int	pmc_save_user_callchain(uintptr_t *_cc, int _maxsamples,
     struct trapframe *_tf);
+struct pmc_mdep *pmc_mdep_alloc(int nclasses);
+void pmc_mdep_free(struct pmc_mdep *md);
 #endif /* _KERNEL */
 #endif /* _SYS_PMC_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/pmckern.h
--- a/head/sys/sys/pmckern.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/pmckern.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/pmckern.h 222813 2011-06-07 08:46:13Z attilio $
+ * $FreeBSD: head/sys/sys/pmckern.h 233628 2012-03-28 20:58:30Z fabient $
  */
=20
 /*
@@ -38,10 +38,14 @@
 #define _SYS_PMCKERN_H_
=20
 #include <sys/param.h>
+#include <sys/systm.h>
 #include <sys/kernel.h>
 #include <sys/lock.h>
 #include <sys/proc.h>
 #include <sys/sx.h>
+#include <sys/pmc.h>
+
+#include <machine/cpufunc.h>
=20
 #define	PMC_FN_PROCESS_EXEC		1
 #define	PMC_FN_CSW_IN			2
@@ -52,6 +56,11 @@
 #define	PMC_FN_MMAP			7
 #define	PMC_FN_MUNMAP			8
 #define	PMC_FN_USER_CALLCHAIN		9
+#define	PMC_FN_USER_CALLCHAIN_SOFT	10
+#define	PMC_FN_SOFT_SAMPLING		11
+
+#define	PMC_HR	0	/* Hardware ring buffer */
+#define	PMC_SR	1	/* Software ring buffer */
=20
 struct pmckern_procexec {
 	int		pm_credentialschanged;
@@ -68,6 +77,79 @@
 	size_t		pm_size;	/* size of unmapped region */
 };
=20
+struct pmckern_soft {
+	enum pmc_event		pm_ev;
+	int			pm_cpu;
+	struct trapframe 	*pm_tf;
+};
+
+/*
+ * Soft PMC.
+ */
+
+#define PMC_SOFT_DEFINE(prov, mod, func, name)					\
+	struct pmc_soft pmc_##prov##_##mod##_##func##_##name =3D			\
+	    { 0, { #prov "_" #mod "_" #func "." #name, 0 } };			\
+	SYSINIT(pmc_##prov##_##mod##_##func##_##name##_init, SI_SUB_KDTRACE, 	\
+	    SI_ORDER_SECOND + 1, pmc_soft_ev_register, 				\
+	    &pmc_##prov##_##mod##_##func##_##name );				\
+	SYSUNINIT(pmc_##prov##_##mod##_##func##_##name##_uninit, 		\
+	    SI_SUB_KDTRACE, SI_ORDER_SECOND + 1, pmc_soft_ev_deregister,	\
+	    &pmc_##prov##_##mod##_##func##_##name )
+
+#define PMC_SOFT_DECLARE(prov, mod, func, name)					\
+	extern struct pmc_soft pmc_##prov##_##mod##_##func##_##name
+
+/*
+ * PMC_SOFT_CALL can be used anywhere in the kernel.
+ * Require md defined PMC_FAKE_TRAPFRAME.
+ */
+#ifdef PMC_FAKE_TRAPFRAME
+#define PMC_SOFT_CALL(pr, mo, fu, na)						\
+do {										\
+	if (pmc_##pr##_##mo##_##fu##_##na.ps_running) {				\
+		struct pmckern_soft ks;						\
+		register_t intr;						\
+		intr =3D intr_disable();						\
+		PMC_FAKE_TRAPFRAME(&pmc_tf[curcpu]);				\
+		ks.pm_ev =3D pmc_##pr##_##mo##_##fu##_##na.ps_ev.pm_ev_code;	\
+		ks.pm_cpu =3D PCPU_GET(cpuid);					\
+		ks.pm_tf =3D &pmc_tf[curcpu];					\
+		PMC_CALL_HOOK_UNLOCKED(curthread,				\
+		    PMC_FN_SOFT_SAMPLING, (void *) &ks);			\
+		intr_restore(intr);						\
+	}									\
+} while (0)
+#else
+#define PMC_SOFT_CALL(pr, mo, fu, na)						\
+do {										\
+} while (0)
+#endif
+
+/*
+ * PMC_SOFT_CALL_TF need to be used carefully.
+ * Userland capture will be done during AST processing.
+ */
+#define PMC_SOFT_CALL_TF(pr, mo, fu, na, tf)					\
+do {										\
+	if (pmc_##pr##_##mo##_##fu##_##na.ps_running) {				\
+		struct pmckern_soft ks;						\
+		register_t intr;						\
+		intr =3D intr_disable();						\
+		ks.pm_ev =3D pmc_##pr##_##mo##_##fu##_##na.ps_ev.pm_ev_code;	\
+		ks.pm_cpu =3D PCPU_GET(cpuid);					\
+		ks.pm_tf =3D tf;							\
+		PMC_CALL_HOOK_UNLOCKED(curthread,				\
+		    PMC_FN_SOFT_SAMPLING, (void *) &ks);			\
+		intr_restore(intr);						\
+	}									\
+} while (0)
+
+struct pmc_soft {
+	int				ps_running;
+	struct pmc_dyn_event_descr	ps_ev;
+};
+
 /* hook */
 extern int (*pmc_hook)(struct thread *_td, int _function, void *_arg);
 extern int (*pmc_intr)(int _cpu, struct trapframe *_frame);
@@ -84,6 +166,9 @@
 /* kernel version number */
 extern const int pmc_kernel_version;
=20
+/* PMC soft per cpu trapframe */
+extern struct trapframe pmc_tf[MAXCPU];
+
 /* Hook invocation; for use within the kernel */
 #define	PMC_CALL_HOOK(t, cmd, arg)		\
 do {						\
@@ -119,6 +204,10 @@
 	(__predict_false(atomic_load_acq_int(&(p)->p_flag) &	\
 	    P_HWPMC))
=20
+/* Check if a thread have pending user capture. */
+#define PMC_IS_PENDING_CALLCHAIN(p)				\
+	(__predict_false((p)->td_pflags & TDP_CALLCHAIN))
+
 #define	PMC_SYSTEM_SAMPLING_ACTIVE()		(pmc_ss_count > 0)
=20
 /* Check if a CPU has recorded samples. */
@@ -137,4 +226,12 @@
 int		pmc_cpu_max_active(void);
 #endif
=20
+/*
+ * Soft events functions.
+ */
+void pmc_soft_ev_register(struct pmc_soft *ps);
+void pmc_soft_ev_deregister(struct pmc_soft *ps);
+struct pmc_soft *pmc_soft_ev_acquire(enum pmc_event ev);
+void pmc_soft_ev_release(struct pmc_soft *ps);
+
 #endif /* _SYS_PMCKERN_H_ */
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/pmclog.h
--- a/head/sys/sys/pmclog.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/pmclog.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/pmclog.h 226514 2011-10-18 15:25:43Z fabient $
+ * $FreeBSD: head/sys/sys/pmclog.h 233628 2012-03-28 20:58:30Z fabient $
  */
=20
 #ifndef	_SYS_PMCLOG_H_
@@ -60,7 +60,13 @@
 	 */
 	PMCLOG_TYPE_MAP_IN,
 	PMCLOG_TYPE_MAP_OUT,
-	PMCLOG_TYPE_CALLCHAIN
+	PMCLOG_TYPE_CALLCHAIN,
+	/*
+	 * V3 ABI
+	 *
+	 * New variant of PMCLOG_TYPE_PMCALLOCATE for dynamic event.
+	 */
+	PMCLOG_TYPE_PMCALLOCATEDYN
 };
=20
 /*
@@ -204,6 +210,14 @@
 	uint32_t		pl_userdata;
 } __packed;
=20
+struct pmclog_pmcallocatedyn {
+	PMCLOG_ENTRY_HEADER
+	uint32_t		pl_pmcid;
+	uint32_t		pl_event;
+	uint32_t		pl_flags;
+	char			pl_evname[PMC_NAME_MAX];
+} __packed;
+
 union pmclog_entry {		/* only used to size scratch areas */
 	struct pmclog_callchain		pl_cc;
 	struct pmclog_closelog		pl_cl;
@@ -213,6 +227,7 @@
 	struct pmclog_map_out		pl_mo;
 	struct pmclog_pcsample		pl_s;
 	struct pmclog_pmcallocate	pl_a;
+	struct pmclog_pmcallocatedyn	pl_ad;
 	struct pmclog_pmcattach		pl_t;
 	struct pmclog_pmcdetach		pl_d;
 	struct pmclog_proccsw		pl_c;
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/proc.h
--- a/head/sys/sys/proc.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/proc.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)proc.h	8.15 (Berkeley) 5/19/95
- * $FreeBSD: head/sys/sys/proc.h 232240 2012-02-27 21:10:10Z kib $
+ * $FreeBSD: head/sys/sys/proc.h 234172 2012-04-12 10:48:43Z kib $
  */
=20
 #ifndef _SYS_PROC_H_
@@ -417,6 +417,8 @@
 #define	TDP_IGNSUSP	0x00800000 /* Permission to ignore the MNTK_SUSPEND* */
 #define	TDP_AUDITREC	0x01000000 /* Audit record pending on thread */
 #define	TDP_RFPPWAIT	0x02000000 /* Handle RFPPWAIT on syscall exit */
+#define	TDP_RESETSPUR	0x04000000 /* Reset spurious page fault history. */
+#define	TDP_NERRNO	0x08000000 /* Last errno is already in td_errno */
=20
 /*
  * Reasons that the current thread can not be run yet.
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/sdt.h
--- a/head/sys/sys/sdt.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/sdt.h	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/sdt.h 227294 2011-11-07 07:09:38Z ed $
+ * $FreeBSD: head/sys/sys/sdt.h 233552 2012-03-27 15:07:43Z rstone $
  *
  * Statically Defined Tracing (SDT) definitions.
  *
@@ -258,6 +258,10 @@
 int sdt_probe_listall(struct sdt_provider *, sdt_probe_listall_func_t, voi=
d *);
 int sdt_provider_listall(sdt_provider_listall_func_t,void *);
=20
+void sdt_register_callbacks(sdt_provider_listall_func_t, void *,
+    sdt_provider_listall_func_t, void *, sdt_probe_listall_func_t, void *);
+void sdt_deregister_callbacks(void);
+
 #endif /* KDTRACE_HOOKS */
=20
 #endif /* _KERNEL */
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/signal.h
--- a/head/sys/sys/signal.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/signal.h	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)signal.h	8.4 (Berkeley) 5/4/95
- * $FreeBSD: head/sys/sys/signal.h 230857 2012-02-01 02:53:06Z davidxu $
+ * $FreeBSD: head/sys/sys/signal.h 233519 2012-03-26 19:12:09Z rmh $
  */
=20
 #ifndef _SYS_SIGNAL_H_
@@ -111,6 +111,7 @@
 #if __BSD_VISIBLE
 #define	SIGTHR		32	/* reserved by thread library. */
 #define	SIGLWP		SIGTHR
+#define	SIGLIBRT	33	/* reserved by real-time library. */
 #endif
=20
 #define	SIGRTMIN	65
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/sysctl.h
--- a/head/sys/sys/sysctl.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/sysctl.h	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)sysctl.h	8.1 (Berkeley) 6/2/93
- * $FreeBSD: head/sys/sys/sysctl.h 232449 2012-03-03 08:19:18Z jmallett $
+ * $FreeBSD: head/sys/sys/sysctl.h 233389 2012-03-23 20:05:41Z trociny $
  */
=20
 #ifndef _SYS_SYSCTL_H_
@@ -565,6 +565,7 @@
 #define	KERN_PROC_RLIMIT	37	/* process resource limits */
 #define	KERN_PROC_PS_STRINGS	38	/* get ps_strings location */
 #define	KERN_PROC_UMASK		39	/* process umask */
+#define	KERN_PROC_OSREL		40	/* osreldate for process binary */
=20
 /*
  * KERN_IPC identifiers
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/tty.h
--- a/head/sys/sys/tty.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/tty.h	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/tty.h 223722 2011-07-02 13:54:20Z ed $
+ * $FreeBSD: head/sys/sys/tty.h 233664 2012-03-29 15:47:29Z hselasky $
  */
=20
 #ifndef _SYS_TTY_H_
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/umtx.h
--- a/head/sys/sys/umtx.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/umtx.h	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/umtx.h 232144 2012-02-25 02:12:17Z davidxu $
+ * $FreeBSD: head/sys/sys/umtx.h 233912 2012-04-05 02:24:08Z davidxu $
  *
  */
=20
@@ -76,11 +76,12 @@
 #define	UMTX_OP_WAIT_UINT_PRIVATE	15
 #define	UMTX_OP_WAKE_PRIVATE	16
 #define	UMTX_OP_MUTEX_WAIT	17
-#define	UMTX_OP_MUTEX_WAKE	18
+#define	UMTX_OP_MUTEX_WAKE	18	/* deprecated */
 #define	UMTX_OP_SEM_WAIT	19
 #define	UMTX_OP_SEM_WAKE	20
 #define	UMTX_OP_NWAKE_PRIVATE   21
-#define	UMTX_OP_MAX		22
+#define	UMTX_OP_MUTEX_WAKE2	22
+#define	UMTX_OP_MAX		23
=20
 /* Flags for UMTX_OP_CV_WAIT */
 #define	CVWAIT_CHECK_UNPARKING	0x01
diff -r 428842767fa6 -r f2935497fa04 head/sys/sys/vnode.h
--- a/head/sys/sys/vnode.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/sys/vnode.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)vnode.h	8.7 (Berkeley) 2/4/94
- * $FreeBSD: head/sys/sys/vnode.h 232821 2012-03-11 12:19:58Z kib $
+ * $FreeBSD: head/sys/sys/vnode.h 234158 2012-04-11 23:01:11Z mckusick $
  */
=20
 #ifndef _SYS_VNODE_H_
@@ -380,7 +380,6 @@
 #define	SKIPSYSTEM	0x0001	/* vflush: skip vnodes marked VSYSTEM */
 #define	FORCECLOSE	0x0002	/* vflush: force file closure */
 #define	WRITECLOSE	0x0004	/* vflush: only close writable files */
-#define	DOCLOSE		0x0008	/* vclean: close active files */
 #define	V_SAVE		0x0001	/* vinvalbuf: sync file first */
 #define	V_ALT		0x0002	/* vinvalbuf: invalidate only alternate bufs */
 #define	V_NORMAL	0x0004	/* vinvalbuf: invalidate only regular bufs */
@@ -633,6 +632,7 @@
 void	vgone(struct vnode *vp);
 void	vhold(struct vnode *);
 void	vholdl(struct vnode *);
+void	vinactive(struct vnode *, struct thread *);
 int	vinvalbuf(struct vnode *vp, int save, int slpflag, int slptimeo);
 int	vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
 	    off_t length, int blksize);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_balloc.c
--- a/head/sys/ufs/ffs/ffs_balloc.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_balloc.c	Tue Apr 17 11:51:51 2012 +0300
@@ -60,7 +60,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_balloc.c 223888 2011-07-09 15:16:=
07Z kib $");
+__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_balloc.c 233438 2012-03-25 00:02:=
37Z mckusick $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -450,7 +450,7 @@
 	 *
 	 * XXX Still have to journal the free below
 	 */
-	(void) ffs_syncvnode(vp, MNT_WAIT);
+	(void) ffs_syncvnode(vp, MNT_WAIT, 0);
 	for (deallocated =3D 0, blkp =3D allociblk, lbns_remfree =3D lbns;
 	     blkp < allocblk; blkp++, lbns_remfree++) {
 		/*
@@ -497,7 +497,7 @@
 		dp->di_blocks -=3D btodb(deallocated);
 		ip->i_flag |=3D IN_CHANGE | IN_UPDATE;
 	}
-	(void) ffs_syncvnode(vp, MNT_WAIT);
+	(void) ffs_syncvnode(vp, MNT_WAIT, 0);
 	/*
 	 * After the buffers are invalidated and on-disk pointers are
 	 * cleared, free the blocks.
@@ -994,7 +994,7 @@
 	 *
 	 * XXX Still have to journal the free below
 	 */
-	(void) ffs_syncvnode(vp, MNT_WAIT);
+	(void) ffs_syncvnode(vp, MNT_WAIT, 0);
 	for (deallocated =3D 0, blkp =3D allociblk, lbns_remfree =3D lbns;
 	     blkp < allocblk; blkp++, lbns_remfree++) {
 		/*
@@ -1041,7 +1041,7 @@
 		dp->di_blocks -=3D btodb(deallocated);
 		ip->i_flag |=3D IN_CHANGE | IN_UPDATE;
 	}
-	(void) ffs_syncvnode(vp, MNT_WAIT);
+	(void) ffs_syncvnode(vp, MNT_WAIT, 0);
 	/*
 	 * After the buffers are invalidated and on-disk pointers are
 	 * cleared, free the blocks.
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_extern.h
--- a/head/sys/ufs/ffs/ffs_extern.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_extern.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)ffs_extern.h	8.6 (Berkeley) 3/30/95
- * $FreeBSD: head/sys/ufs/ffs/ffs_extern.h 232351 2012-03-01 18:45:25Z mck=
usick $
+ * $FreeBSD: head/sys/ufs/ffs/ffs_extern.h 233438 2012-03-25 00:02:37Z mck=
usick $
  */
=20
 #ifndef _UFS_FFS_EXTERN_H
@@ -92,7 +92,7 @@
 void	ffs_snapshot_unmount(struct mount *mp);
 void	process_deferred_inactive(struct mount *mp);
 void	ffs_sync_snap(struct mount *, int);
-int	ffs_syncvnode(struct vnode *vp, int waitfor);
+int	ffs_syncvnode(struct vnode *vp, int waitfor, int flags);
 int	ffs_truncate(struct vnode *, off_t, int, struct ucred *, struct thread=
 *);
 int	ffs_update(struct vnode *, int);
 int	ffs_valloc(struct vnode *, int, struct ucred *, struct vnode **);
@@ -168,12 +168,11 @@
 #define FLUSH_BLOCKS		3
 #define FLUSH_BLOCKS_WAIT	4
 /*
- * Flag to ffs_syncinode() to request flushing of data only,
+ * Flag to ffs_syncvnode() to request flushing of data only,
  * but skip the ffs_update() on the inode itself. Used to avoid
  * deadlock when flushing snapshot inodes while holding snaplk.
- * Avoid bit conflicts with MNT_WAIT values in sys/mount.h
  */
-#define	NO_INO_UPDT		0x10
+#define	NO_INO_UPDT		0x00000001
=20
 int	ffs_rdonly(struct inode *);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_inode.c
--- a/head/sys/ufs/ffs/ffs_inode.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_inode.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_inode.c 232837 2012-03-11 21:25:4=
2Z kib $");
+__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_inode.c 233629 2012-03-28 21:21:1=
9Z mckusick $");
=20
 #include "opt_quota.h"
=20
@@ -106,6 +106,7 @@
 	flags =3D 0;
 	if (IS_SNAPSHOT(ip))
 		flags =3D GB_LOCK_NOWAIT;
+loop:
 	error =3D breadn_flags(ip->i_devvp,
 	     fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
 	     (int) fs->fs_bsize, 0, 0, 0, NOCRED, flags, &bp);
@@ -115,13 +116,27 @@
 			return (error);
 		}
 		KASSERT((IS_SNAPSHOT(ip)), ("EBUSY from non-snapshot"));
-		vref(vp);	/* Protect against ffs_snapgone() */
+		/*
+		 * Wait for our inode block to become available.
+		 *
+		 * Hold a reference to the vnode to protect against
+		 * ffs_snapgone(). Since we hold a reference, it can only
+		 * get reclaimed (VI_DOOMED flag) in a forcible downgrade
+		 * or unmount. For an unmount, the entire filesystem will be
+		 * gone, so we cannot attempt to touch anything associated
+		 * with it while the vnode is unlocked; all we can do is=20
+		 * pause briefly and try again. If when we relock the vnode
+		 * we discover that it has been reclaimed, updating it is no
+		 * longer necessary and we can just return an error.
+		 */
+		vref(vp);
 		VOP_UNLOCK(vp, 0);
-		(void) bread(ip->i_devvp,
-		     fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
-		     (int) fs->fs_bsize, NOCRED, &bp);
+		pause("ffsupd", 1);
 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
 		vrele(vp);
+		if ((vp->v_iflag & VI_DOOMED) !=3D 0)
+			return (ENOENT);
+		goto loop;
 	}
 	if (DOINGSOFTDEP(vp))
 		softdep_update_inodeblock(ip, bp, waitfor);
@@ -228,7 +243,7 @@
 				goto extclean;
 			needextclean =3D 1;
 		} else {
-			if ((error =3D ffs_syncvnode(vp, MNT_WAIT)) !=3D 0)
+			if ((error =3D ffs_syncvnode(vp, MNT_WAIT, 0)) !=3D 0)
 				return (error);
 #ifdef QUOTA
 			(void) chkdq(ip, -extblocks, NOCRED, 0);
@@ -321,7 +336,7 @@
 			 * rarely, we solve the problem by syncing the file
 			 * so that it will have no data structures left.
 			 */
-			if ((error =3D ffs_syncvnode(vp, MNT_WAIT)) !=3D 0)
+			if ((error =3D ffs_syncvnode(vp, MNT_WAIT, 0)) !=3D 0)
 				return (error);
 		} else {
 			flags =3D IO_NORMAL | (needextclean ? IO_EXT: 0);
@@ -366,7 +381,7 @@
 		 */
 		if (DOINGSOFTDEP(vp) && lbn < NDADDR &&
 		    fragroundup(fs, blkoff(fs, length)) < fs->fs_bsize &&
-		    (error =3D ffs_syncvnode(vp, MNT_WAIT)) !=3D 0)
+		    (error =3D ffs_syncvnode(vp, MNT_WAIT, 0)) !=3D 0)
 			return (error);
 		ip->i_size =3D length;
 		DIP_SET(ip, i_size, length);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_rawread.c
--- a/head/sys/ufs/ffs/ffs_rawread.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_rawread.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_rawread.c 233438 2012-03-25 00:02=
:37Z mckusick $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -163,7 +163,7 @@
 		/* Flush dirty buffers */
 		if (bo->bo_dirty.bv_cnt > 0) {
 			BO_UNLOCK(bo);
-			if ((error =3D ffs_syncvnode(vp, MNT_WAIT)) !=3D 0) {
+			if ((error =3D ffs_syncvnode(vp, MNT_WAIT, 0)) !=3D 0) {
 				if (upgraded !=3D 0)
 					VOP_LOCK(vp, LK_DOWNGRADE);
 				vn_finished_write(mp);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_snapshot.c
--- a/head/sys/ufs/ffs/ffs_snapshot.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_snapshot.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_snapshot.c 232351 2012-03-01 18:4=
5:25Z mckusick $");
+__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_snapshot.c 234158 2012-04-11 23:0=
1:11Z mckusick $");
=20
 #include "opt_quota.h"
=20
@@ -362,7 +362,7 @@
 			goto out;
 		bawrite(nbp);
 		if (cg % 10 =3D=3D 0)
-			ffs_syncvnode(vp, MNT_WAIT);
+			ffs_syncvnode(vp, MNT_WAIT, 0);
 	}
 	/*
 	 * Copy all the cylinder group maps. Although the
@@ -385,7 +385,7 @@
 		error =3D cgaccount(cg, vp, nbp, 1);
 		bawrite(nbp);
 		if (cg % 10 =3D=3D 0)
-			ffs_syncvnode(vp, MNT_WAIT);
+			ffs_syncvnode(vp, MNT_WAIT, 0);
 		if (error)
 			goto out;
 	}
@@ -400,7 +400,7 @@
 	 * Since we have marked it as a snapshot it is safe to
 	 * unlock it as no process will be allowed to write to it.
 	 */
-	if ((error =3D ffs_syncvnode(vp, MNT_WAIT)) !=3D 0)
+	if ((error =3D ffs_syncvnode(vp, MNT_WAIT, 0)) !=3D 0)
 		goto out;
 	VOP_UNLOCK(vp, 0);
 	/*
@@ -861,7 +861,7 @@
 	MNT_IUNLOCK(mp);
 	if (error)
 		(void) ffs_truncate(vp, (off_t)0, 0, NOCRED, td);
-	(void) ffs_syncvnode(vp, MNT_WAIT);
+	(void) ffs_syncvnode(vp, MNT_WAIT, 0);
 	if (error)
 		vput(vp);
 	else
@@ -1714,7 +1714,7 @@
 	 * may find indirect pointers using the magic BLK_* values.
 	 */
 	if (DOINGSOFTDEP(vp))
-		ffs_syncvnode(vp, MNT_WAIT);
+		ffs_syncvnode(vp, MNT_WAIT, 0);
 #ifdef QUOTA
 	/*
 	 * Reenable disk quotas for ex-snapshot file.
@@ -1908,7 +1908,7 @@
 			bawrite(cbp);
 			if ((vtype =3D=3D VDIR || dopersistence) &&
 			    ip->i_effnlink > 0)
-				(void) ffs_syncvnode(vp, MNT_WAIT|NO_INO_UPDT);
+				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
 			continue;
 		}
 		/*
@@ -1919,7 +1919,7 @@
 			bawrite(cbp);
 			if ((vtype =3D=3D VDIR || dopersistence) &&
 			    ip->i_effnlink > 0)
-				(void) ffs_syncvnode(vp, MNT_WAIT|NO_INO_UPDT);
+				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
 			break;
 		}
 		savedcbp =3D cbp;
@@ -1937,7 +1937,7 @@
 		bawrite(savedcbp);
 		if ((vtype =3D=3D VDIR || dopersistence) &&
 		    VTOI(vp)->i_effnlink > 0)
-			(void) ffs_syncvnode(vp, MNT_WAIT|NO_INO_UPDT);
+			(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
 	}
 	/*
 	 * If we have been unable to allocate a block in which to do
@@ -2000,7 +2000,7 @@
 			} else {
 				reason =3D "old format snapshot";
 				(void)ffs_truncate(vp, (off_t)0, 0, NOCRED, td);
-				(void)ffs_syncvnode(vp, MNT_WAIT);
+				(void)ffs_syncvnode(vp, MNT_WAIT, 0);
 			}
 			printf("ffs_snapshot_mount: %s inode %d\n",
 			    reason, fs->fs_snapinum[snaploc]);
@@ -2401,7 +2401,7 @@
 			bawrite(cbp);
 			if ((devvp =3D=3D bp->b_vp || bp->b_vp->v_type =3D=3D VDIR ||
 			    dopersistence) && ip->i_effnlink > 0)
-				(void) ffs_syncvnode(vp, MNT_WAIT|NO_INO_UPDT);
+				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
 			else
 				launched_async_io =3D 1;
 			continue;
@@ -2414,7 +2414,7 @@
 			bawrite(cbp);
 			if ((devvp =3D=3D bp->b_vp || bp->b_vp->v_type =3D=3D VDIR ||
 			    dopersistence) && ip->i_effnlink > 0)
-				(void) ffs_syncvnode(vp, MNT_WAIT|NO_INO_UPDT);
+				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
 			else
 				launched_async_io =3D 1;
 			break;
@@ -2434,7 +2434,7 @@
 		bawrite(savedcbp);
 		if ((devvp =3D=3D bp->b_vp || bp->b_vp->v_type =3D=3D VDIR ||
 		    dopersistence) && VTOI(vp)->i_effnlink > 0)
-			(void) ffs_syncvnode(vp, MNT_WAIT|NO_INO_UPDT);
+			(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
 		else
 			launched_async_io =3D 1;
 	}
@@ -2484,7 +2484,7 @@
 	}
 	TAILQ_FOREACH(ip, &sn->sn_head, i_nextsnap) {
 		vp =3D ITOV(ip);
-		ffs_syncvnode(vp, waitfor|NO_INO_UPDT);
+		ffs_syncvnode(vp, waitfor, NO_INO_UPDT);
 	}
 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
 }
@@ -2572,20 +2572,9 @@
 			MNT_ILOCK(mp);
 			continue;
 		}
-	=09
-		VNASSERT((vp->v_iflag & VI_DOINGINACT) =3D=3D 0, vp,
-			 ("process_deferred_inactive: "
-			  "recursed on VI_DOINGINACT"));
-		vp->v_iflag |=3D VI_DOINGINACT;
-		vp->v_iflag &=3D ~VI_OWEINACT;
-		VI_UNLOCK(vp);
-		(void) VOP_INACTIVE(vp, td);
-		VI_LOCK(vp);
-		VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
-			 ("process_deferred_inactive: lost VI_DOINGINACT"));
+		vinactive(vp, td);
 		VNASSERT((vp->v_iflag & VI_OWEINACT) =3D=3D 0, vp,
 			 ("process_deferred_inactive: got VI_OWEINACT"));
-		vp->v_iflag &=3D ~VI_DOINGINACT;
 		VI_UNLOCK(vp);
 		VOP_UNLOCK(vp, 0);
 		vdrop(vp);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_softdep.c
--- a/head/sys/ufs/ffs/ffs_softdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_softdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -40,7 +40,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_softdep.c 232948 2012-03-13 22:04=
:27Z kib $");
+__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_softdep.c 233817 2012-04-02 21:58=
:37Z mckusick $");
=20
 #include "opt_ffs.h"
 #include "opt_quota.h"
@@ -2848,7 +2848,7 @@
 	 * work attached to it.
 	 */
 	if ((curthread->td_pflags & TDP_COWINPROGRESS) =3D=3D 0)
-		ffs_syncvnode(vp, waitok);
+		ffs_syncvnode(vp, waitok, 0);
 	ACQUIRE_LOCK(&lk);
 	process_removes(vp);
 	process_truncates(vp);
@@ -2887,8 +2887,8 @@
 	stat_journal_low++;
 	FREE_LOCK(&lk);
 	if (vp)
-		ffs_syncvnode(vp, MNT_NOWAIT);
-	ffs_syncvnode(dvp, MNT_WAIT);
+		ffs_syncvnode(vp, MNT_NOWAIT, 0);
+	ffs_syncvnode(dvp, MNT_WAIT, 0);
 	ACQUIRE_LOCK(&lk);
 	/* Process vp before dvp as it may create .. removes. */
 	if (vp) {
@@ -4323,6 +4323,7 @@
 	(void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags,
 	    &inodedep);
 	inodedep->id_nlinkdelta =3D ip->i_nlink - ip->i_effnlink;
+	KASSERT((inodedep->id_state & UNLINKED) =3D=3D 0, ("inode unlinked"));
=20
 	return (inodedep);
 }
@@ -8455,6 +8456,7 @@
 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
 	    &inodedep) =3D=3D 0)
 		panic("softdep_setup_remove: Lost inodedep.");
+	KASSERT((inodedep->id_state & UNLINKED) =3D=3D 0, ("inode unlinked"));
 	dirrem->dm_state |=3D ONDEPLIST;
 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
=20
@@ -8987,6 +8989,7 @@
 	struct inodedep *inodedep;
 	struct inodedep *idp;
=20
+	mtx_assert(&lk, MA_OWNED);
 	for (inodedep =3D TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
 	    inodedep; inodedep =3D idp) {
 		if ((inodedep->id_state & UNLINKNEXT) =3D=3D 0)
@@ -8995,11 +8998,8 @@
 		if (idp =3D=3D NULL || (idp->id_state & UNLINKNEXT) =3D=3D 0)
 			break;
 		if ((inodedep->id_state & UNLINKPREV) =3D=3D 0)
-			panic("first_unlinked_inodedep: prev !=3D next");
-	}
-	if (inodedep =3D=3D NULL)
-		return (NULL);
-
+			break;
+	}
 	return (inodedep);
 }
=20
@@ -9038,8 +9038,12 @@
 	struct mount *mp;
 	struct fs *fs;
=20
+	mtx_assert(&lk, MA_OWNED);
 	fs =3D sbdep->sb_fs;
 	mp =3D UFSTOVFS(sbdep->sb_ump);
+	/*
+	 * If the superblock doesn't match the in-memory list start over.
+	 */
 	inodedep =3D first_unlinked_inodedep(sbdep->sb_ump);
 	if ((inodedep && fs->fs_sujfree !=3D inodedep->id_ino) ||
 	    (inodedep =3D=3D NULL && fs->fs_sujfree !=3D 0)) {
@@ -9049,8 +9053,6 @@
 	WORKITEM_FREE(sbdep, D_SBDEP);
 	if (fs->fs_sujfree =3D=3D 0)
 		return (0);
-	if (inodedep_lookup(mp, fs->fs_sujfree, 0, &inodedep) =3D=3D 0)
-		panic("handle_written_sbdep: lost inodedep");
 	/*
 	 * Now that we have a record of this inode in stable store allow it
 	 * to be written to free up pending work.  Inodes may see a lot of
@@ -9078,10 +9080,13 @@
 {
 	struct ufsmount *ump;
=20
+	mtx_assert(&lk, MA_OWNED);
 	if (MOUNTEDSUJ(mp) =3D=3D 0)
 		return;
 	ump =3D VFSTOUFS(mp);
 	ump->um_fs->fs_fmod =3D 1;
+	if (inodedep->id_state & UNLINKED)
+		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
 	inodedep->id_state |=3D UNLINKED;
 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
 }
@@ -9109,6 +9114,10 @@
 	ino =3D inodedep->id_ino;
 	error =3D 0;
 	for (;;) {
+		mtx_assert(&lk, MA_OWNED);
+		KASSERT((inodedep->id_state & UNLINKED) !=3D 0,
+		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
+		    inodedep));
 		/*
 		 * If nothing has yet been written simply remove us from
 		 * the in memory list and return.  This is the most common
@@ -9166,36 +9175,19 @@
 			ACQUIRE_LOCK(&lk);
 			continue;
 		}
+		nino =3D 0;
+		idn =3D TAILQ_NEXT(inodedep, id_unlinked);
+		if (idn)
+			nino =3D idn->id_ino;
 		/*
 		 * Remove us from the in memory list.  After this we cannot
 		 * access the inodedep.
 		 */
-		idn =3D TAILQ_NEXT(inodedep, id_unlinked);
-		inodedep->id_state &=3D ~(UNLINKED | UNLINKLINKS);
+		KASSERT((inodedep->id_state & UNLINKED) !=3D 0,
+		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
+		    inodedep));
+		inodedep->id_state &=3D ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
-		/*
-		 * Determine the next inode number.
-		 */
-		nino =3D 0;
-		if (idn) {
-			/*
-			 * If next isn't on the list we can just clear prev's
-			 * state and schedule it to be fixed later.  No need
-			 * to synchronously write if we're not in the real
-			 * list.
-			 */
-			if ((idn->id_state & UNLINKPREV) =3D=3D 0 && pino !=3D 0) {
-				idp->id_state &=3D ~UNLINKNEXT;
-				if ((idp->id_state & ONWORKLIST) =3D=3D 0)
-					WORKLIST_INSERT(&bp->b_dep,
-					    &idp->id_list);
-				FREE_LOCK(&lk);
-				bawrite(bp);
-				ACQUIRE_LOCK(&lk);
-				return;
-			}
-			nino =3D idn->id_ino;
-		}
 		FREE_LOCK(&lk);
 		/*
 		 * The predecessor's next pointer is manually updated here
@@ -9234,13 +9226,14 @@
 			bwrite(bp);
 			ACQUIRE_LOCK(&lk);
 		}
+
 		if (fs->fs_sujfree !=3D ino)
 			return;
 		panic("clear_unlinked_inodedep: Failed to clear free head");
 	}
 	if (inodedep->id_ino =3D=3D fs->fs_sujfree)
 		panic("clear_unlinked_inodedep: Freeing head of free list");
-	inodedep->id_state &=3D ~(UNLINKED | UNLINKLINKS);
+	inodedep->id_state &=3D ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
 	return;
 }
@@ -9839,18 +9832,6 @@
 		inon =3D TAILQ_NEXT(inodedep, id_unlinked);
 		dp->di_freelink =3D inon ? inon->id_ino : 0;
 	}
-	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) =3D=3D
-	    (UNLINKED | UNLINKNEXT)) {
-		struct inodedep *inon;
-		ino_t freelink;
-
-		inon =3D TAILQ_NEXT(inodedep, id_unlinked);
-		freelink =3D inon ? inon->id_ino : 0;
-		if (freelink !=3D dp->di_freelink)
-			panic("ino %p(0x%X) %d, %d !=3D %d",
-			    inodedep, inodedep->id_state, inodedep->id_ino,
-			    freelink, dp->di_freelink);
-	}
 	/*
 	 * If the bitmap is not yet written, then the allocated
 	 * inode cannot be written to disk.
@@ -10849,10 +10830,9 @@
 		freelink =3D dp2->di_freelink;
 	}
 	/*
-	 * If we wrote a valid freelink pointer during the last write
-	 * record it here.
-	 */
-	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) =3D=3D UNLINKED) {
+	 * Leave this inodeblock dirty until it's in the list.
+	 */
+	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) =3D=3D UNLINKED) {
 		struct inodedep *inon;
=20
 		inon =3D TAILQ_NEXT(inodedep, id_unlinked);
@@ -10861,12 +10841,9 @@
 			if (inon)
 				inon->id_state |=3D UNLINKPREV;
 			inodedep->id_state |=3D UNLINKNEXT;
-		} else
-			hadchanges =3D 1;
-	}
-	/* Leave this inodeblock dirty until it's in the list. */
-	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) =3D=3D UNLINKED)
+		}
 		hadchanges =3D 1;
+	}
 	/*
 	 * If we had to rollback the inode allocation because of
 	 * bitmaps being incomplete, then simply restore it.
@@ -11841,8 +11818,8 @@
 					pagedep_new_block =3D pagedep->pd_state & NEWBLOCK;
 					FREE_LOCK(&lk);
 					locked =3D 0;
-					if (pagedep_new_block &&
-					    (error =3D ffs_syncvnode(pvp, MNT_WAIT))) {
+					if (pagedep_new_block && (error =3D
+					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
 						vput(pvp);
 						return (error);
 					}
@@ -12683,7 +12660,7 @@
 				MNT_ILOCK(mp);
 				continue;
 			}
-			(void) ffs_syncvnode(lvp, MNT_NOWAIT);
+			(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
 			vput(lvp);
 			MNT_ILOCK(mp);
 		}
@@ -12856,7 +12833,7 @@
 				softdep_error("clear_remove: vget", error);
 				goto finish_write;
 			}
-			if ((error =3D ffs_syncvnode(vp, MNT_NOWAIT)))
+			if ((error =3D ffs_syncvnode(vp, MNT_NOWAIT, 0)))
 				softdep_error("clear_remove: fsync", error);
 			bo =3D &vp->v_bufobj;
 			BO_LOCK(bo);
@@ -12939,10 +12916,10 @@
 		}
 		vfs_unbusy(mp);
 		if (ino =3D=3D lastino) {
-			if ((error =3D ffs_syncvnode(vp, MNT_WAIT)))
+			if ((error =3D ffs_syncvnode(vp, MNT_WAIT, 0)))
 				softdep_error("clear_inodedeps: fsync1", error);
 		} else {
-			if ((error =3D ffs_syncvnode(vp, MNT_NOWAIT)))
+			if ((error =3D ffs_syncvnode(vp, MNT_NOWAIT, 0)))
 				softdep_error("clear_inodedeps: fsync2", error);
 			BO_LOCK(&vp->v_bufobj);
 			drain_output(vp);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_vfsops.c
--- a/head/sys/ufs/ffs/ffs_vfsops.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_vfsops.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_vfsops.c 231160 2012-02-07 20:43:=
28Z mckusick $");
+__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_vfsops.c 234036 2012-04-08 13:44:=
55Z trasz $");
=20
 #include "opt_quota.h"
 #include "opt_ufs.h"
@@ -80,6 +80,8 @@
 static void	ffs_oldfscompat_read(struct fs *, struct ufsmount *,
 		    ufs2_daddr_t);
 static void	ffs_ifree(struct ufsmount *ump, struct inode *ip);
+static int	ffs_sync_lazy(struct mount *mp);
+
 static vfs_init_t ffs_init;
 static vfs_uninit_t ffs_uninit;
 static vfs_extattrctl_t ffs_extattrctl;
@@ -673,8 +675,14 @@
 	/*
 	 * Step 3: re-read summary information from disk.
 	 */
-	blks =3D howmany(fs->fs_cssize, fs->fs_fsize);
-	space =3D fs->fs_csp;
+	size =3D fs->fs_cssize;
+	blks =3D howmany(size, fs->fs_fsize);
+	if (fs->fs_contigsumsize > 0)
+		size +=3D fs->fs_ncg * sizeof(int32_t);
+	size +=3D fs->fs_ncg * sizeof(u_int8_t);
+	free(fs->fs_csp, M_UFSMNT);
+	space =3D malloc((u_long)size, M_UFSMNT, M_WAITOK);
+	fs->fs_csp =3D space;
 	for (i =3D 0; i < blks; i +=3D fs->fs_frag) {
 		size =3D fs->fs_bsize;
 		if (i + fs->fs_frag > blks)
@@ -1048,6 +1056,8 @@
 			ffs_flushfiles(mp, FORCECLOSE, td);
 			goto out;
 		}
+		if (devvp->v_type =3D=3D VCHR && devvp->v_rdev !=3D NULL)
+			devvp->v_rdev->si_mountpt =3D mp;
 		if (fs->fs_snapinum[0] !=3D 0)
 			ffs_snapshot_mount(mp);
 		fs->fs_fmod =3D 1;
@@ -1293,6 +1303,8 @@
 	g_vfs_close(ump->um_cp);
 	g_topology_unlock();
 	PICKUP_GIANT();
+	if (ump->um_devvp->v_type =3D=3D VCHR && ump->um_devvp->v_rdev !=3D NULL)
+		ump->um_devvp->v_rdev->si_mountpt =3D NULL;
 	vrele(ump->um_devvp);
 	dev_rel(ump->um_dev);
 	mtx_destroy(UFS_MTX(ump));
@@ -1411,11 +1423,77 @@
 }
=20
 /*
+ * For a lazy sync, we only care about access times, quotas and the
+ * superblock.  Other filesystem changes are already converted to
+ * cylinder group blocks or inode blocks updates and are written to
+ * disk by syncer.
+ */
+static int
+ffs_sync_lazy(mp)
+     struct mount *mp;
+{
+	struct vnode *mvp, *vp;
+	struct inode *ip;
+	struct thread *td;
+	int allerror, error;
+
+	allerror =3D 0;
+	td =3D curthread;
+	if ((mp->mnt_flag & MNT_NOATIME) !=3D 0)
+		goto qupdate;
+	MNT_ILOCK(mp);
+	MNT_VNODE_FOREACH(vp, mp, mvp) {
+		VI_LOCK(vp);
+		if (vp->v_iflag & VI_DOOMED || vp->v_type =3D=3D VNON) {
+			VI_UNLOCK(vp);
+			continue;
+		}
+		ip =3D VTOI(vp);
+
+		/*
+		 * The IN_ACCESS flag is converted to IN_MODIFIED by
+		 * ufs_close() and ufs_getattr() by the calls to
+		 * ufs_itimes_locked(), without subsequent UFS_UPDATE().
+		 * Test also all the other timestamp flags too, to pick up
+		 * any other cases that could be missed.
+		 */
+		if ((ip->i_flag & (IN_ACCESS | IN_CHANGE | IN_MODIFIED |
+		    IN_UPDATE)) =3D=3D 0) {
+			VI_UNLOCK(vp);
+			continue;
+		}
+		MNT_IUNLOCK(mp);
+		if ((error =3D vget(vp, LK_EXCLUSIVE | LK_NOWAIT | LK_INTERLOCK,
+		    td)) !=3D 0) {
+			MNT_ILOCK(mp);
+			continue;
+		}
+		error =3D ffs_update(vp, 0);
+		if (error !=3D 0)
+			allerror =3D error;
+		vput(vp);
+		MNT_ILOCK(mp);
+	}
+	MNT_IUNLOCK(mp);
+
+qupdate:
+#ifdef QUOTA
+	qsync(mp);
+#endif
+
+	if (VFSTOUFS(mp)->um_fs->fs_fmod !=3D 0 &&
+	    (error =3D ffs_sbupdate(VFSTOUFS(mp), MNT_LAZY, 0)) !=3D 0)
+		allerror =3D error;
+	return (allerror);
+}
+
+/*
  * Go through the disk queues to initiate sandbagged IO;
  * go through the inodes to write those that have been modified;
  * initiate the writing of the super block if it has been modified.
  *
- * Note: we are always called with the filesystem marked `MPBUSY'.
+ * Note: we are always called with the filesystem marked busy using
+ * vfs_busy().
  */
 static int
 ffs_sync(mp, waitfor)
@@ -1444,15 +1522,9 @@
 	if (fs->fs_fmod !=3D 0 && fs->fs_ronly !=3D 0 && ump->um_fsckpid =3D=3D 0)
 		panic("%s: ffs_sync: modification on read-only filesystem",
 		    fs->fs_fsmnt);
-	/*
-	 * For a lazy sync, we just care about the filesystem metadata.
-	 */
-	if (waitfor =3D=3D MNT_LAZY) {
-		secondary_accwrites =3D 0;
-		secondary_writes =3D 0;
-		lockreq =3D 0;
-		goto metasync;
-	}
+	if (waitfor =3D=3D MNT_LAZY)
+		return (ffs_sync_lazy(mp));
+
 	/*
 	 * Write back each (modified) inode.
 	 */
@@ -1479,7 +1551,7 @@
=20
 	MNT_VNODE_FOREACH(vp, mp, mvp) {
 		/*
-		 * Depend on the mntvnode_slock to keep things stable enough
+		 * Depend on the vnode interlock to keep things stable enough
 		 * for a quick test.  Since there might be hundreds of
 		 * thousands of vnodes, we cannot afford even a subroutine
 		 * call unless there's a good chance that we have work to do.
@@ -1505,7 +1577,7 @@
 			}
 			continue;
 		}
-		if ((error =3D ffs_syncvnode(vp, waitfor)) !=3D 0)
+		if ((error =3D ffs_syncvnode(vp, waitfor, 0)) !=3D 0)
 			allerror =3D error;
 		vput(vp);
 		MNT_ILOCK(mp);
@@ -1527,7 +1599,6 @@
 	qsync(mp);
 #endif
=20
-metasync:
 	devvp =3D ump->um_devvp;
 	bo =3D &devvp->v_bufobj;
 	BO_LOCK(bo);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ffs/ffs_vnops.c
--- a/head/sys/ufs/ffs/ffs_vnops.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ffs/ffs_vnops.c	Tue Apr 17 11:51:51 2012 +0300
@@ -62,7 +62,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_vnops.c 232948 2012-03-13 22:04:2=
7Z kib $");
+__FBSDID("$FreeBSD: head/sys/ufs/ffs/ffs_vnops.c 233438 2012-03-25 00:02:3=
7Z mckusick $");
=20
 #include <sys/param.h>
 #include <sys/bio.h>
@@ -184,7 +184,7 @@
 	vp =3D ap->a_vp;
 	bo =3D &vp->v_bufobj;
 retry:
-	error =3D ffs_syncvnode(vp, ap->a_waitfor);
+	error =3D ffs_syncvnode(vp, ap->a_waitfor, 0);
 	if (error)
 		return (error);
 	if (ap->a_waitfor =3D=3D MNT_WAIT && DOINGSOFTDEP(vp)) {
@@ -209,17 +209,15 @@
 }
=20
 int
-ffs_syncvnode(struct vnode *vp, int waitfor)
+ffs_syncvnode(struct vnode *vp, int waitfor, int flags)
 {
 	struct inode *ip;
 	struct bufobj *bo;
 	struct buf *bp;
 	struct buf *nbp;
 	ufs_lbn_t lbn;
-	int error, wait, passes, noupdate;
+	int error, wait, passes;
=20
-	noupdate =3D waitfor & NO_INO_UPDT;
-	waitfor &=3D ~NO_INO_UPDT;
 	ip =3D VTOI(vp);
 	ip->i_flag &=3D ~IN_NEEDSYNC;
 	bo =3D &vp->v_bufobj;
@@ -302,7 +300,7 @@
 	}
 	if (waitfor !=3D MNT_WAIT) {
 		BO_UNLOCK(bo);
-		if (noupdate)
+		if ((flags & NO_INO_UPDT) !=3D 0)
 			return (0);
 		else
 			return (ffs_update(vp, 0));
@@ -322,7 +320,7 @@
 	 */
 	if (bo->bo_dirty.bv_cnt > 0) {
 		/* Write the inode after sync passes to flush deps. */
-		if (wait && DOINGSOFTDEP(vp) && noupdate =3D=3D 0) {
+		if (wait && DOINGSOFTDEP(vp) && (flags & NO_INO_UPDT) =3D=3D 0) {
 			BO_UNLOCK(bo);
 			ffs_update(vp, 1);
 			BO_LOCK(bo);
@@ -338,7 +336,7 @@
 	}
 	BO_UNLOCK(bo);
 	error =3D 0;
-	if (noupdate =3D=3D 0)
+	if ((flags & NO_INO_UPDT) =3D=3D 0)
 		error =3D ffs_update(vp, 1);
 	if (DOINGSUJ(vp))
 		softdep_journal_fsync(VTOI(vp));
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ufs/ufs_quota.c
--- a/head/sys/ufs/ufs/ufs_quota.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ufs/ufs_quota.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ufs/ufs_quota.c 232003 2012-02-22 20:03:5=
1Z kib $");
+__FBSDID("$FreeBSD: head/sys/ufs/ufs/ufs_quota.c 233608 2012-03-28 13:56:1=
8Z kib $");
=20
 #include "opt_ffs.h"
=20
@@ -1061,12 +1061,11 @@
 again:
 	MNT_VNODE_FOREACH(vp, mp, mvp) {
 		VI_LOCK(vp);
-		MNT_IUNLOCK(mp);
 		if (vp->v_type =3D=3D VNON) {
 			VI_UNLOCK(vp);
-			MNT_ILOCK(mp);
 			continue;
 		}
+		MNT_IUNLOCK(mp);
 		error =3D vget(vp, LK_EXCLUSIVE | LK_INTERLOCK, td);
 		if (error) {
 			MNT_ILOCK(mp);
diff -r 428842767fa6 -r f2935497fa04 head/sys/ufs/ufs/ufs_vnops.c
--- a/head/sys/ufs/ufs/ufs_vnops.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/ufs/ufs/ufs_vnops.c	Tue Apr 17 11:51:51 2012 +0300
@@ -35,7 +35,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/ufs/ufs/ufs_vnops.c 232821 2012-03-11 12:19:5=
8Z kib $");
+__FBSDID("$FreeBSD: head/sys/ufs/ufs/ufs_vnops.c 234103 2012-04-10 15:59:3=
7Z jh $");
=20
 #include "opt_quota.h"
 #include "opt_suiddir.h"
@@ -526,6 +526,10 @@
 		return (EINVAL);
 	}
 	if (vap->va_flags !=3D VNOVAL) {
+		if ((vap->va_flags & ~(UF_NODUMP | UF_IMMUTABLE | UF_APPEND |
+		    UF_OPAQUE | UF_NOUNLINK | SF_ARCHIVED | SF_IMMUTABLE |
+		    SF_APPEND | SF_NOUNLINK | SF_SNAPSHOT)) !=3D 0)
+			return (EOPNOTSUPP);
 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
 			return (EROFS);
 		/*
@@ -545,34 +549,34 @@
 		 * processes.
 		 */
 		if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
-			if (ip->i_flags
-			    & (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
+			if (ip->i_flags &
+			    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
 				error =3D securelevel_gt(cred, 0);
 				if (error)
 					return (error);
 			}
-			/* Snapshot flag cannot be set or cleared */
-			if (((vap->va_flags & SF_SNAPSHOT) !=3D 0 &&
-			     (ip->i_flags & SF_SNAPSHOT) =3D=3D 0) ||
-			    ((vap->va_flags & SF_SNAPSHOT) =3D=3D 0 &&
-			     (ip->i_flags & SF_SNAPSHOT) !=3D 0))
+			/* The snapshot flag cannot be toggled. */
+			if ((vap->va_flags ^ ip->i_flags) & SF_SNAPSHOT)
 				return (EPERM);
-			ip->i_flags =3D vap->va_flags;
-			DIP_SET(ip, i_flags, vap->va_flags);
 		} else {
-			if (ip->i_flags
-			    & (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
-			    (vap->va_flags & UF_SETTABLE) !=3D vap->va_flags)
+			if (ip->i_flags &
+			    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
+			    ((vap->va_flags ^ ip->i_flags) & SF_SETTABLE))
 				return (EPERM);
-			ip->i_flags &=3D SF_SETTABLE;
-			ip->i_flags |=3D (vap->va_flags & UF_SETTABLE);
-			DIP_SET(ip, i_flags, ip->i_flags);
 		}
+		ip->i_flags =3D vap->va_flags;
+		DIP_SET(ip, i_flags, vap->va_flags);
 		ip->i_flag |=3D IN_CHANGE;
 		error =3D UFS_UPDATE(vp, 0);
-		if (vap->va_flags & (IMMUTABLE | APPEND))
+		if (ip->i_flags & (IMMUTABLE | APPEND))
 			return (error);
 	}
+	/*
+	 * If immutable or append, no one can change any of its attributes
+	 * except the ones already handled (exec atime and, in some cases
+	 * for the superuser, file flags including the immutability flags
+	 * themselves).
+	 */
 	if (ip->i_flags & (IMMUTABLE | APPEND))
 		return (EPERM);
 	/*
@@ -1000,6 +1004,14 @@
 		error =3D EMLINK;
 		goto out;
 	}
+	/*
+	 * The file may have been removed after namei droped the original
+	 * lock.
+	 */
+	if (ip->i_effnlink =3D=3D 0) {
+		error =3D ENOENT;
+		goto out;
+	}
 	if (ip->i_flags & (IMMUTABLE | APPEND)) {
 		error =3D EPERM;
 		goto out;
diff -r 428842767fa6 -r f2935497fa04 head/sys/vm/vm_fault.c
--- a/head/sys/vm/vm_fault.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/vm/vm_fault.c	Tue Apr 17 11:51:51 2012 +0300
@@ -72,8 +72,9 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vm_fault.c 225840 2011-09-28 14:57:50Z kib=
 $");
+__FBSDID("$FreeBSD: head/sys/vm/vm_fault.c 233925 2012-04-05 17:13:14Z jhb=
 $");
=20
+#include "opt_ktrace.h"
 #include "opt_vm.h"
=20
 #include <sys/param.h>
@@ -86,6 +87,9 @@
 #include <sys/sysctl.h>
 #include <sys/vmmeter.h>
 #include <sys/vnode.h>
+#ifdef KTRACE
+#include <sys/ktrace.h>
+#endif
=20
 #include <vm/vm.h>
 #include <vm/vm_param.h>
@@ -208,10 +212,23 @@
 vm_fault(vm_map_t map, vm_offset_t vaddr, vm_prot_t fault_type,
     int fault_flags)
 {
+	struct thread *td;
+	int result;
=20
-	if ((curthread->td_pflags & TDP_NOFAULTING) !=3D 0)
+	td =3D curthread;
+	if ((td->td_pflags & TDP_NOFAULTING) !=3D 0)
 		return (KERN_PROTECTION_FAILURE);
-	return (vm_fault_hold(map, vaddr, fault_type, fault_flags, NULL));
+#ifdef KTRACE
+	if (map !=3D kernel_map && KTRPOINT(td, KTR_FAULT))
+		ktrfault(vaddr, fault_type);
+#endif
+	result =3D vm_fault_hold(map, trunc_page(vaddr), fault_type, fault_flags,
+	    NULL);
+#ifdef KTRACE
+	if (map !=3D kernel_map && KTRPOINT(td, KTR_FAULTEND))
+		ktrfaultend(result);
+#endif
+	return (result);
 }
=20
 int
@@ -1468,11 +1485,17 @@
 	return i;
 }
=20
+/*
+ * Block entry into the machine-independent layer's page fault handler by
+ * the calling thread.  Subsequent calls to vm_fault() by that thread will
+ * return KERN_PROTECTION_FAILURE.  Enable machine-dependent handling of
+ * spurious page faults.=20
+ */
 int
 vm_fault_disable_pagefaults(void)
 {
=20
-	return (curthread_pflags_set(TDP_NOFAULTING));
+	return (curthread_pflags_set(TDP_NOFAULTING | TDP_RESETSPUR));
 }
=20
 void
diff -r 428842767fa6 -r f2935497fa04 head/sys/vm/vm_mmap.c
--- a/head/sys/vm/vm_mmap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/vm/vm_mmap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vm_mmap.c 233100 2012-03-17 23:00:32Z kib =
$");
+__FBSDID("$FreeBSD: head/sys/vm/vm_mmap.c 234039 2012-04-08 18:25:12Z alc =
$");
=20
 #include "opt_compat.h"
 #include "opt_hwpmc_hooks.h"
@@ -888,6 +888,9 @@
 					pindex =3D OFF_TO_IDX(current->offset +
 					    (addr - current->start));
 					m =3D vm_page_lookup(object, pindex);
+					if (m =3D=3D NULL &&
+					    vm_page_is_cached(object, pindex))
+						mincoreinfo =3D MINCORE_INCORE;
 					if (m !=3D NULL && m->valid =3D=3D 0)
 						m =3D NULL;
 					if (m !=3D NULL)
diff -r 428842767fa6 -r f2935497fa04 head/sys/vm/vm_page.c
--- a/head/sys/vm/vm_page.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/vm/vm_page.c	Tue Apr 17 11:51:51 2012 +0300
@@ -77,7 +77,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 230623 2012-01-27 20:18:31Z kmac=
y $");
+__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 234064 2012-04-09 17:05:18Z atti=
lio $");
=20
 #include "opt_vm.h"
=20
@@ -1181,7 +1181,7 @@
  *
  *	The free page queue must be locked.
  */
-void
+static void
 vm_page_cache_remove(vm_page_t m)
 {
 	vm_object_t object;
@@ -1285,6 +1285,33 @@
 }
=20
 /*
+ *	Returns TRUE if a cached page is associated with the given object and
+ *	offset, and FALSE otherwise.
+ *
+ *	The object must be locked.
+ */
+boolean_t
+vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
+{
+	vm_page_t m;
+
+	/*
+	 * Insertion into an object's collection of cached pages requires the
+	 * object to be locked.  Therefore, if the object is locked and the
+	 * object's collection is empty, there is no need to acquire the free
+	 * page queues lock in order to prove that the specified page doesn't
+	 * exist.
+	 */
+	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
+	if (__predict_true(object->cache =3D=3D NULL))
+		return (FALSE);
+	mtx_lock(&vm_page_queue_free_mtx);
+	m =3D vm_page_cache_lookup(object, pindex);
+	mtx_unlock(&vm_page_queue_free_mtx);
+	return (m !=3D NULL);
+}
+
+/*
  *	vm_page_alloc:
  *
  *	Allocate and return a page that is associated with the specified
diff -r 428842767fa6 -r f2935497fa04 head/sys/vm/vm_page.h
--- a/head/sys/vm/vm_page.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/vm/vm_page.h	Tue Apr 17 11:51:51 2012 +0300
@@ -57,7 +57,7 @@
  * any improvements or extensions that they make and grant Carnegie the
  * rights to redistribute these changes.
  *
- * $FreeBSD: head/sys/vm/vm_page.h 230623 2012-01-27 20:18:31Z kmacy $
+ * $FreeBSD: head/sys/vm/vm_page.h 234039 2012-04-08 18:25:12Z alc $
  */
=20
 /*
@@ -248,9 +248,13 @@
  *
  * PGA_WRITEABLE is set exclusively on managed pages by pmap_enter().  Whe=
n it
  * does so, the page must be VPO_BUSY.
+ *
+ * PGA_EXECUTABLE may be set by pmap routines, and indicates that a page h=
as
+ * at least one executable mapping. It is not consumed by the VM layer.
  */
 #define	PGA_WRITEABLE	0x01		/* page may be mapped writeable */
 #define	PGA_REFERENCED	0x02		/* page has been referenced */
+#define	PGA_EXECUTABLE	0x04		/* page may be mapped executable */
=20
 /*
  * Page flags.  If changed at any other time than page allocation or
@@ -380,7 +384,6 @@
 vm_page_t vm_page_grab (vm_object_t, vm_pindex_t, int);
 void vm_page_cache(vm_page_t);
 void vm_page_cache_free(vm_object_t, vm_pindex_t, vm_pindex_t);
-void vm_page_cache_remove(vm_page_t);
 void vm_page_cache_transfer(vm_object_t, vm_pindex_t, vm_object_t);
 int vm_page_try_to_cache (vm_page_t);
 int vm_page_try_to_free (vm_page_t);
@@ -389,6 +392,7 @@
 vm_page_t vm_page_find_least(vm_object_t, vm_pindex_t);
 vm_page_t vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr);
 void vm_page_insert (vm_page_t, vm_object_t, vm_pindex_t);
+boolean_t vm_page_is_cached(vm_object_t object, vm_pindex_t pindex);
 vm_page_t vm_page_lookup (vm_object_t, vm_pindex_t);
 vm_page_t vm_page_next(vm_page_t m);
 int vm_page_pa_tryrelock(pmap_t, vm_paddr_t, vm_paddr_t *);
diff -r 428842767fa6 -r f2935497fa04 head/sys/vm/vm_reserv.c
--- a/head/sys/vm/vm_reserv.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/vm/vm_reserv.c	Tue Apr 17 11:51:51 2012 +0300
@@ -37,7 +37,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vm_reserv.c 228287 2011-12-05 18:29:25Z al=
c $");
+__FBSDID("$FreeBSD: head/sys/vm/vm_reserv.c 234038 2012-04-08 17:00:46Z al=
c $");
=20
 #include "opt_vm.h"
=20
@@ -652,11 +652,13 @@
=20
 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
 	rv =3D vm_reserv_from_page(m);
-	if (rv->object !=3D NULL) {
-		vm_reserv_depopulate(rv);
-		return (TRUE);
-	}
-	return (FALSE);
+	if (rv->object =3D=3D NULL)
+		return (FALSE);
+	if ((m->flags & PG_CACHED) !=3D 0 && m->pool !=3D VM_FREEPOOL_CACHE)
+		vm_phys_set_pool(VM_FREEPOOL_CACHE, rv->pages,
+		    VM_LEVEL_0_ORDER);
+	vm_reserv_depopulate(rv);
+	return (TRUE);
 }
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/vm/vnode_pager.c
--- a/head/sys/vm/vnode_pager.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/vm/vnode_pager.c	Tue Apr 17 11:51:51 2012 +0300
@@ -51,7 +51,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vnode_pager.c 232701 2012-03-08 20:27:20Z =
jhb $");
+__FBSDID("$FreeBSD: head/sys/vm/vnode_pager.c 233627 2012-03-28 20:49:11Z =
mckusick $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -543,6 +543,7 @@
 			bp->b_data =3D (caddr_t)sf_buf_kva(sf) + i * bsize;
 			bp->b_blkno =3D fileaddr;
 			pbgetbo(bo, bp);
+			bp->b_vp =3D vp;
 			bp->b_bcount =3D bsize;
 			bp->b_bufsize =3D bsize;
 			bp->b_runningbufspace =3D bp->b_bufsize;
@@ -560,6 +561,7 @@
 			/*
 			 * free the buffer header back to the swap buffer pool
 			 */
+			bp->b_vp =3D NULL;
 			pbrelbo(bp);
 			relpbuf(bp, &vnode_pbuf_freecnt);
 			if (error)
@@ -918,6 +920,7 @@
 	bp->b_wcred =3D crhold(curthread->td_ucred);
 	bp->b_blkno =3D firstaddr;
 	pbgetbo(bo, bp);
+	bp->b_vp =3D vp;
 	bp->b_bcount =3D size;
 	bp->b_bufsize =3D size;
 	bp->b_runningbufspace =3D bp->b_bufsize;
@@ -944,6 +947,7 @@
 	/*
 	 * free the buffer header back to the swap buffer pool
 	 */
+	bp->b_vp =3D NULL;
 	pbrelbo(bp);
 	relpbuf(bp, &vnode_pbuf_freecnt);
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/acpica/madt.c
--- a/head/sys/x86/acpica/madt.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/acpica/madt.c	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/x86/acpica/madt.c 227293 2011-11-07 06:44:47Z=
 ed $");
+__FBSDID("$FreeBSD: head/sys/x86/acpica/madt.c 233623 2012-03-28 18:53:48Z=
 jhb $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -50,12 +50,12 @@
 #include <dev/pci/pcivar.h>
=20
 /* These two arrays are indexed by APIC IDs. */
-struct ioapic_info {
+static struct {
 	void *io_apic;
 	UINT32 io_vector;
-} ioapics[MAX_APIC_ID + 1];
+} *ioapics;
=20
-struct lapic_info {
+static struct lapic_info {
 	u_int la_enabled:1;
 	u_int la_acpi_id:8;
 } lapics[MAX_APIC_ID + 1];
@@ -162,7 +162,10 @@
 		printf("Try disabling either ACPI or apic support.\n");
 		panic("Using MADT but ACPI doesn't work");
 	}
-		   =20
+
+	ioapics =3D malloc(sizeof(*ioapics) * (MAX_APIC_ID + 1), M_MADT,
+	    M_WAITOK | M_ZERO);
+
 	/* First, we run through adding I/O APIC's. */
 	madt_walk_table(madt_parse_apics, NULL);
=20
@@ -194,6 +197,9 @@
 	/* Finally, we throw the switch to enable the I/O APIC's. */
 	acpi_SetDefaultIntrModel(ACPI_INTR_APIC);
=20
+	free(ioapics, M_MADT);
+	ioapics =3D NULL;
+
 	return (0);
 }
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/include/endian.h
--- a/head/sys/x86/include/endian.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/include/endian.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)endian.h	7.8 (Berkeley) 4/3/91
- * $FreeBSD: head/sys/x86/include/endian.h 232745 2012-03-09 20:34:31Z dim=
 $
+ * $FreeBSD: head/sys/x86/include/endian.h 233684 2012-03-29 23:31:48Z dim=
 $
  */
=20
 #ifndef _MACHINE_ENDIAN_H_
@@ -65,9 +65,9 @@
=20
 #define	__bswap16_gen(x)	(__uint16_t)((x) << 8 | (x) >> 8)
 #define	__bswap32_gen(x)		\
-	(((__uint32_t)__bswap16(x) << 16) | __bswap16((x) >> 16))
+	(((__uint32_t)__bswap16((x) & 0xffff) << 16) | __bswap16((x) >> 16))
 #define	__bswap64_gen(x)		\
-	(((__uint64_t)__bswap32(x) << 32) | __bswap32((x) >> 32))
+	(((__uint64_t)__bswap32((x) & 0xffffffff) << 32) | __bswap32((x) >> 32))
=20
 #ifdef __GNUCLIKE_BUILTIN_CONSTANT_P
 #define	__bswap16(x)				\
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/include/mca.h
--- a/head/sys/x86/include/mca.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/include/mca.h	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/x86/include/mca.h 233781 2012-04-02 15:07:22Z jhb $
  */
=20
 #ifndef __X86_MCA_H__
@@ -48,7 +48,7 @@
=20
 void	cmc_intr(void);
 void	mca_init(void);
-int	mca_intr(void);
+void	mca_intr(void);
 void	mca_resume(void);
=20
 #endif
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/include/segments.h
--- a/head/sys/x86/include/segments.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/include/segments.h	Tue Apr 17 11:51:51 2012 +0300
@@ -31,7 +31,7 @@
  * SUCH DAMAGE.
  *
  *	from: @(#)segments.h	7.1 (Berkeley) 5/9/91
- * $FreeBSD: head/sys/x86/include/segments.h 233203 2012-03-19 21:24:50Z t=
ijl $
+ * $FreeBSD: head/sys/x86/include/segments.h 233613 2012-03-28 16:32:17Z j=
hb $
  */
=20
 #ifndef _X86_SEGMENTS_H_
@@ -215,8 +215,8 @@
 #define	IDT_MC		18	/* #MC: Machine Check */
 #define	IDT_XF		19	/* #XF: SIMD Floating-Point Exception */
 #define	IDT_IO_INTS	NRSVIDT	/* Base of IDT entries for I/O interrupts. */
-#define	IDT_DTRACE_RET	0x20	/* DTrace pid provider Interrupt Vector */
 #define	IDT_SYSCALL	0x80	/* System Call Interrupt Vector */
+#define	IDT_DTRACE_RET	0x92	/* DTrace pid provider Interrupt Vector */
=20
 #if defined(__i386__) || defined(__ia64__)
 /*
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/include/specialreg.h
--- a/head/sys/x86/include/specialreg.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/include/specialreg.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	from: @(#)specialreg.h	7.1 (Berkeley) 5/9/91
- * $FreeBSD: head/sys/x86/include/specialreg.h 233207 2012-03-19 21:34:11Z=
 tijl $
+ * $FreeBSD: head/sys/x86/include/specialreg.h 234364 2012-04-17 00:54:38Z=
 grehan $
  */
=20
 #ifndef _MACHINE_SPECIALREG_H_
@@ -153,6 +153,7 @@
 #define	CPUID2_OSXSAVE	0x08000000
 #define	CPUID2_AVX	0x10000000
 #define	CPUID2_F16C	0x20000000
+#define	CPUID2_RDRAND	0x40000000
 #define	CPUID2_HV	0x80000000
=20
 /*
@@ -358,10 +359,44 @@
 #define	MSR_MC4_MISC		0x413
=20
 /*
+ * X2APIC MSRs
+ */
+#define	MSR_APIC_ID		0x802
+#define	MSR_APIC_VERSION	0x803
+#define	MSR_APIC_TPR		0x808
+#define	MSR_APIC_EOI		0x80b
+#define	MSR_APIC_LDR		0x80d
+#define	MSR_APIC_SVR		0x80f
+#define	MSR_APIC_ISR0		0x810
+#define	MSR_APIC_ISR1		0x811
+#define	MSR_APIC_ISR2		0x812
+#define	MSR_APIC_ISR3		0x813
+#define	MSR_APIC_ISR4		0x814
+#define	MSR_APIC_ISR5		0x815
+#define	MSR_APIC_ISR6		0x816
+#define	MSR_APIC_ISR7		0x817
+#define	MSR_APIC_TMR0		0x818
+#define	MSR_APIC_IRR0		0x820
+#define	MSR_APIC_ESR		0x828
+#define	MSR_APIC_LVT_CMCI	0x82F
+#define	MSR_APIC_ICR		0x830
+#define	MSR_APIC_LVT_TIMER	0x832
+#define	MSR_APIC_LVT_THERMAL	0x833
+#define	MSR_APIC_LVT_PCINT	0x834
+#define	MSR_APIC_LVT_LINT0	0x835
+#define	MSR_APIC_LVT_LINT1	0x836
+#define	MSR_APIC_LVT_ERROR	0x837
+#define	MSR_APIC_ICR_TIMER	0x838
+#define	MSR_APIC_CCR_TIMER	0x839
+#define	MSR_APIC_DCR_TIMER	0x83e
+#define	MSR_APIC_SELF_IPI	0x83f
+
+/*
  * Constants related to MSR's.
  */
-#define	APICBASE_RESERVED	0x000006ff
+#define	APICBASE_RESERVED	0x000002ff
 #define	APICBASE_BSP		0x00000100
+#define	APICBASE_X2APIC		0x00000400
 #define	APICBASE_ENABLED	0x00000800
 #define	APICBASE_ADDRESS	0xfffff000
=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/isa/isa_dma.c
--- a/head/sys/x86/isa/isa_dma.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/isa/isa_dma.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/x86/isa/isa_dma.c 233675 2012-03-29 18:58:02Z=
 jhb $");
=20
 /*
  * code to manage AT bus
@@ -237,8 +237,6 @@
 	caddr_t newaddr;
 	int dma_range_checked;
=20
-	/* translate to physical */
-	phys =3D pmap_extract(kernel_pmap, (vm_offset_t)addr);
 	dma_range_checked =3D isa_dmarangecheck(addr, nbytes, chan);
=20
 #ifdef DIAGNOSTIC
@@ -281,6 +279,9 @@
 		addr =3D newaddr;
 	}
=20
+	/* translate to physical */
+	phys =3D pmap_extract(kernel_pmap, (vm_offset_t)addr);
+
 	if (flags & ISADMA_RAW) {
 	    dma_auto_mode |=3D (1 << chan);
 	} else {=20
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/pci/pci_bus.c
--- a/head/sys/x86/pci/pci_bus.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/pci/pci_bus.c	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/x86/pci/pci_bus.c 227843 2011-11-22 21:28:20Z=
 marius $");
+__FBSDID("$FreeBSD: head/sys/x86/pci/pci_bus.c 234153 2012-04-11 21:00:33Z=
 jhb $");
=20
 #include "opt_cpu.h"
=20
@@ -45,7 +45,7 @@
 #ifdef CPU_ELAN
 #include <machine/md_var.h>
 #endif
-#include <machine/legacyvar.h>
+#include <x86/legacyvar.h>
 #include <machine/pci_cfgreg.h>
 #include <machine/resource.h>
=20
@@ -112,14 +112,27 @@
 	return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
 }
=20
-static int
+int
 legacy_pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
     uint32_t *data)
 {
-	device_t bus;
+	device_t bus, hostb;
+	int error, func, slot;
=20
 	bus =3D device_get_parent(pcib);
-	return (PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data));
+	error =3D PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data);
+	if (error)
+		return (error);
+
+	slot =3D legacy_get_pcislot(pcib);
+	func =3D legacy_get_pcifunc(pcib);
+	if (slot =3D=3D -1 || func =3D=3D -1)
+		return (0);
+	hostb =3D pci_find_bsf(0, slot, func);
+	KASSERT(hostb !=3D NULL, ("%s: missing hostb for 0:%d:%d", __func__,
+	    slot, func));
+	pci_ht_map_msi(hostb, *addr);
+	return (0);
 }
=20
 static const char *
@@ -453,6 +466,8 @@
 					      "pcib", busnum);
 			device_set_desc(child, s);
 			legacy_set_pcibus(child, busnum);
+			legacy_set_pcislot(child, slot);
+			legacy_set_pcifunc(child, func);
=20
 			found =3D 1;
 			if (id =3D=3D 0x12258086)
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/x86/intr_machdep.c
--- a/head/sys/x86/x86/intr_machdep.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/x86/intr_machdep.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/x86/x86/intr_machdep.c 233031 2012-03-16 12:13:44Z n=
yan $
+ * $FreeBSD: head/sys/x86/x86/intr_machdep.c 233961 2012-04-06 21:19:28Z g=
ibbs $
  */
=20
 /*
@@ -525,9 +525,6 @@
 	return;
 #endif
=20
-	/* The BSP is always a valid target. */
-	CPU_SETOF(0, &intr_cpus);
-
 	/* Don't bother on UP. */
 	if (mp_ncpus =3D=3D 1)
 		return;
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/x86/mca.c
--- a/head/sys/x86/x86/mca.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/x86/mca.c	Tue Apr 17 11:51:51 2012 +0300
@@ -30,7 +30,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/x86/x86/mca.c 227309 2011-11-07 15:43:11Z ed =
$");
+__FBSDID("$FreeBSD: head/sys/x86/x86/mca.c 233793 2012-04-02 17:26:21Z jhb=
 $");
=20
 #ifdef __amd64__
 #define	DEV_APIC
@@ -85,6 +85,7 @@
 static MALLOC_DEFINE(M_MCA, "MCA", "Machine Check Architecture");
=20
 static int mca_count;		/* Number of records stored. */
+static int mca_banks;		/* Number of per-CPU register banks. */
=20
 static SYSCTL_NODE(_hw, OID_AUTO, mca, CTLFLAG_RD, NULL,
     "Machine Check Architecture");
@@ -103,16 +104,17 @@
 SYSCTL_INT(_hw_mca, OID_AUTO, erratum383, CTLFLAG_RD, &workaround_erratum3=
83, 0,
     "Is the workaround for Erratum 383 on AMD Family 10h processors enable=
d?");
=20
+static STAILQ_HEAD(, mca_internal) mca_freelist;
+static int mca_freecount;
 static STAILQ_HEAD(, mca_internal) mca_records;
 static struct callout mca_timer;
 static int mca_ticks =3D 3600;	/* Check hourly by default. */
 static struct taskqueue *mca_tq;
-static struct task mca_task;
+static struct task mca_refill_task, mca_scan_task;
 static struct mtx mca_lock;
=20
 #ifdef DEV_APIC
 static struct cmc_state **cmc_state;	/* Indexed by cpuid, bank */
-static int cmc_banks;
 static int cmc_throttle =3D 60;	/* Time in seconds to throttle CMCI. */
 #endif
=20
@@ -416,24 +418,63 @@
 	return (1);
 }
=20
-static void __nonnull(1)
-mca_record_entry(const struct mca_record *record)
+static void
+mca_fill_freelist(void)
+{
+	struct mca_internal *rec;
+	int desired;
+
+	/*
+	 * Ensure we have at least one record for each bank and one
+	 * record per CPU.
+	 */
+	desired =3D imax(mp_ncpus, mca_banks);
+	mtx_lock_spin(&mca_lock);
+	while (mca_freecount < desired) {
+		mtx_unlock_spin(&mca_lock);
+		rec =3D malloc(sizeof(*rec), M_MCA, M_WAITOK);
+		mtx_lock_spin(&mca_lock);
+		STAILQ_INSERT_TAIL(&mca_freelist, rec, link);
+		mca_freecount++;
+	}
+	mtx_unlock_spin(&mca_lock);
+}
+
+static void
+mca_refill(void *context, int pending)
+{
+
+	mca_fill_freelist();
+}
+
+static void __nonnull(2)
+mca_record_entry(enum scan_mode mode, const struct mca_record *record)
 {
 	struct mca_internal *rec;
=20
-	rec =3D malloc(sizeof(*rec), M_MCA, M_NOWAIT);
-	if (rec =3D=3D NULL) {
-		printf("MCA: Unable to allocate space for an event.\n");
-		mca_log(record);
-		return;
+	if (mode =3D=3D POLLED) {
+		rec =3D malloc(sizeof(*rec), M_MCA, M_WAITOK);
+		mtx_lock_spin(&mca_lock);
+	} else {
+		mtx_lock_spin(&mca_lock);
+		rec =3D STAILQ_FIRST(&mca_freelist);
+		if (rec =3D=3D NULL) {
+			printf("MCA: Unable to allocate space for an event.\n");
+			mca_log(record);
+			mtx_unlock_spin(&mca_lock);
+			return;
+		}
+		STAILQ_REMOVE_HEAD(&mca_freelist, link);
+		mca_freecount--;
 	}
=20
 	rec->rec =3D *record;
 	rec->logged =3D 0;
-	mtx_lock_spin(&mca_lock);
 	STAILQ_INSERT_TAIL(&mca_records, rec, link);
 	mca_count++;
 	mtx_unlock_spin(&mca_lock);
+	if (mode =3D=3D CMCI)
+		taskqueue_enqueue_fast(mca_tq, &mca_refill_task);
 }
=20
 #ifdef DEV_APIC
@@ -550,9 +591,11 @@
 			count++;
 			if (rec.mr_status & ucmask) {
 				recoverable =3D 0;
+				mtx_lock_spin(&mca_lock);
 				mca_log(&rec);
+				mtx_unlock_spin(&mca_lock);
 			}
-			mca_record_entry(&rec);
+			mca_record_entry(mode, &rec);
 		}
 =09
 #ifdef DEV_APIC
@@ -564,6 +607,8 @@
 			cmci_update(mode, i, valid, &rec);
 #endif
 	}
+	if (mode =3D=3D POLLED)
+		mca_fill_freelist();
 	return (mode =3D=3D MCE ? recoverable : count);
 }
=20
@@ -579,6 +624,7 @@
 	struct thread *td;
 	int count, cpu;
=20
+	mca_fill_freelist();
 	td =3D curthread;
 	count =3D 0;
 	thread_lock(td);
@@ -595,9 +641,7 @@
 		STAILQ_FOREACH(mca, &mca_records, link) {
 			if (!mca->logged) {
 				mca->logged =3D 1;
-				mtx_unlock_spin(&mca_lock);
 				mca_log(&mca->rec);
-				mtx_lock_spin(&mca_lock);
 			}
 		}
 		mtx_unlock_spin(&mca_lock);
@@ -608,7 +652,7 @@
 mca_periodic_scan(void *arg)
 {
=20
-	taskqueue_enqueue(mca_tq, &mca_task);
+	taskqueue_enqueue_fast(mca_tq, &mca_scan_task);
 	callout_reset(&mca_timer, mca_ticks * hz, mca_periodic_scan, NULL);
 }
=20
@@ -622,36 +666,43 @@
 	if (error)
 		return (error);
 	if (i)
-		taskqueue_enqueue(mca_tq, &mca_task);
+		taskqueue_enqueue_fast(mca_tq, &mca_scan_task);
 	return (0);
 }
=20
 static void
+mca_createtq(void *dummy)
+{
+	if (mca_banks <=3D 0)
+		return;
+
+	mca_tq =3D taskqueue_create_fast("mca", M_WAITOK,
+	    taskqueue_thread_enqueue, &mca_tq);
+	taskqueue_start_threads(&mca_tq, 1, PI_SWI(SWI_TQ), "mca taskq");
+}
+SYSINIT(mca_createtq, SI_SUB_CONFIGURE, SI_ORDER_ANY, mca_createtq, NULL);
+
+static void
 mca_startup(void *dummy)
 {
=20
-	if (!mca_enabled || !(cpu_feature & CPUID_MCA))
+	if (mca_banks <=3D 0)
 		return;
=20
-	mca_tq =3D taskqueue_create("mca", M_WAITOK, taskqueue_thread_enqueue,
-	    &mca_tq);
-	taskqueue_start_threads(&mca_tq, 1, PI_SWI(SWI_TQ), "mca taskq");
-	callout_reset(&mca_timer, mca_ticks * hz, mca_periodic_scan,
-		    NULL);
+	callout_reset(&mca_timer, mca_ticks * hz, mca_periodic_scan, NULL);
 }
 SYSINIT(mca_startup, SI_SUB_SMP, SI_ORDER_ANY, mca_startup, NULL);
=20
 #ifdef DEV_APIC
 static void
-cmci_setup(uint64_t mcg_cap)
+cmci_setup(void)
 {
 	int i;
=20
 	cmc_state =3D malloc((mp_maxid + 1) * sizeof(struct cmc_state **),
 	    M_MCA, M_WAITOK);
-	cmc_banks =3D mcg_cap & MCG_CAP_COUNT;
 	for (i =3D 0; i <=3D mp_maxid; i++)
-		cmc_state[i] =3D malloc(sizeof(struct cmc_state) * cmc_banks,
+		cmc_state[i] =3D malloc(sizeof(struct cmc_state) * mca_banks,
 		    M_MCA, M_WAITOK | M_ZERO);
 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
 	    "cmc_throttle", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
@@ -673,10 +724,14 @@
 	    CPUID_TO_FAMILY(cpu_id) =3D=3D 0x10 && amd10h_L1TP)
 		workaround_erratum383 =3D 1;
=20
+	mca_banks =3D mcg_cap & MCG_CAP_COUNT;
 	mtx_init(&mca_lock, "mca", NULL, MTX_SPIN);
 	STAILQ_INIT(&mca_records);
-	TASK_INIT(&mca_task, 0, mca_scan_cpus, NULL);
+	TASK_INIT(&mca_scan_task, 0, mca_scan_cpus, NULL);
 	callout_init(&mca_timer, CALLOUT_MPSAFE);
+	STAILQ_INIT(&mca_freelist);
+	TASK_INIT(&mca_refill_task, 0, mca_refill, NULL);
+	mca_fill_freelist();
 	SYSCTL_ADD_INT(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
 	    "count", CTLFLAG_RD, &mca_count, 0, "Record count");
 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
@@ -690,7 +745,7 @@
 	    sysctl_mca_scan, "I", "Force an immediate scan for machine checks");
 #ifdef DEV_APIC
 	if (mcg_cap & MCG_CAP_CMCI_P)
-		cmci_setup(mcg_cap);
+		cmci_setup();
 #endif
 }
=20
@@ -708,7 +763,7 @@
 	struct cmc_state *cc;
 	uint64_t ctl;
=20
-	KASSERT(i < cmc_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
+	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
=20
 	ctl =3D rdmsr(MSR_MC_CTL2(i));
 	if (ctl & MC_CTL2_CMCI_EN)
@@ -752,7 +807,7 @@
 	struct cmc_state *cc;
 	uint64_t ctl;
=20
-	KASSERT(i < cmc_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
+	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
=20
 	/* Ignore banks not monitored by this CPU. */
 	if (!(PCPU_GET(cmci_mask) & 1 << i))
@@ -880,7 +935,7 @@
 SYSINIT(mca_init_bsp, SI_SUB_CPU, SI_ORDER_ANY, mca_init_bsp, NULL);
=20
 /* Called when a machine check exception fires. */
-int
+void
 mca_intr(void)
 {
 	uint64_t mcg_status;
@@ -894,7 +949,7 @@
 		printf("MC Type: 0x%jx  Address: 0x%jx\n",
 		    (uintmax_t)rdmsr(MSR_P5_MC_TYPE),
 		    (uintmax_t)rdmsr(MSR_P5_MC_ADDR));
-		return (0);
+		panic("Machine check");
 	}
=20
 	/* Scan the banks and check for any non-recoverable errors. */
@@ -905,7 +960,8 @@
=20
 	/* Clear MCIP. */
 	wrmsr(MSR_MCG_STATUS, mcg_status & ~MCG_STATUS_MCIP);
-	return (recoverable);
+	if (!recoverable)
+		panic("Unrecoverable machine check exception");
 }
=20
 #ifdef DEV_APIC
@@ -928,9 +984,7 @@
 		STAILQ_FOREACH(mca, &mca_records, link) {
 			if (!mca->logged) {
 				mca->logged =3D 1;
-				mtx_unlock_spin(&mca_lock);
 				mca_log(&mca->rec);
-				mtx_lock_spin(&mca_lock);
 			}
 		}
 		mtx_unlock_spin(&mca_lock);
diff -r 428842767fa6 -r f2935497fa04 head/sys/x86/x86/mptable_pci.c
--- a/head/sys/x86/x86/mptable_pci.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/sys/x86/x86/mptable_pci.c	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/x86/x86/mptable_pci.c 227843 2011-11-22 21:28=
:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/x86/x86/mptable_pci.c 233707 2012-03-30 19:10=
:14Z jhb $");
=20
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -46,7 +46,7 @@
 #include <dev/pci/pcivar.h>
 #include <dev/pci/pcib_private.h>
 #include <x86/mptable.h>
-#include <machine/legacyvar.h>
+#include <x86/legacyvar.h>
 #include <machine/pci_cfgreg.h>
=20
 #include "pcib_if.h"
@@ -97,16 +97,6 @@
 	return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
 }
=20
-static int
-mptable_hostb_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
-    uint32_t *data)
-{
-	device_t bus;
-
-	bus =3D device_get_parent(pcib);
-	return (PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data));
-}
-
 #ifdef NEW_PCIB
 static int
 mptable_is_isa_range(u_long start, u_long end)
@@ -214,7 +204,7 @@
 	DEVMETHOD(pcib_release_msi,	pcib_release_msi),
 	DEVMETHOD(pcib_alloc_msix,	mptable_hostb_alloc_msix),
 	DEVMETHOD(pcib_release_msix,	pcib_release_msix),
-	DEVMETHOD(pcib_map_msi,		mptable_hostb_map_msi),
+	DEVMETHOD(pcib_map_msi,		legacy_pcib_map_msi),
=20
 	DEVMETHOD_END
 };
diff -r 428842767fa6 -r f2935497fa04 head/tools/build/mk/OptionalObsoleteFi=
les.inc
--- a/head/tools/build/mk/OptionalObsoleteFiles.inc	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/tools/build/mk/OptionalObsoleteFiles.inc	Tue Apr 17 11:51:51 201=
2 +0300
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/tools/build/mk/OptionalObsoleteFiles.inc 231530 2012-02-1=
1 20:28:42Z ed $
+# $FreeBSD: head/tools/build/mk/OptionalObsoleteFiles.inc 234289 2012-04-1=
4 16:42:17Z dim $
 #
 # This file add support for the WITHOUT_* and WITH_* knobs in src.conf(5) =
to
 # the check-old and delete-old* targets.
@@ -1409,6 +1409,42 @@
 OLD_FILES+=3Dusr/share/man/man8/unstr.8.gz
 .endif
=20
+.if ${MK_GCC} =3D=3D no
+OLD_FILES+=3Dusr/bin/c++filt
+OLD_FILES+=3Dusr/bin/g++
+OLD_FILES+=3Dusr/bin/gcc
+OLD_FILES+=3Dusr/bin/gcov
+OLD_FILES+=3Dusr/bin/gcpp
+.if ${TARGET_ARCH} =3D=3D "amd64" || ${TARGET_ARCH} =3D=3D "i386"
+OLD_FILES+=3Dusr/include/gcc/4.2/emmintrin.h
+OLD_FILES+=3Dusr/include/gcc/4.2/mm_malloc.h
+OLD_FILES+=3Dusr/include/gcc/4.2/mmintrin.h
+OLD_FILES+=3Dusr/include/gcc/4.2/pmmintrin.h
+OLD_FILES+=3Dusr/include/gcc/4.2/tmmintrin.h
+OLD_FILES+=3Dusr/include/gcc/4.2/xmmintrin.h
+.elif ${TARGET_ARCH} =3D=3D "ia64"
+OLD_FILES+=3Dusr/include/gcc/4.2/ia64intrin.h
+.elif ${TARGET_ARCH} =3D=3D "arm"
+OLD_FILES+=3Dusr/include/gcc/4.2/mmintrin.h
+.elif ${TARGET_ARCH} =3D=3D "powerpc" || ${TARGET_ARCH} =3D=3D "powerpc64"
+OLD_FILES+=3Dusr/include/gcc/4.2/altivec.h
+OLD_FILES+=3Dusr/include/gcc/4.2/ppc-asm.h
+OLD_FILES+=3Dusr/include/gcc/4.2/spe.h
+.endif
+OLD_DIRS+=3Dusr/include/gcc/4.2
+OLD_DIRS+=3Dusr/include/gcc
+OLD_FILES+=3Dusr/libexec/cc1
+OLD_FILES+=3Dusr/libexec/cc1plus
+OLD_FILES+=3Dusr/share/info/cpp.info.gz
+OLD_FILES+=3Dusr/share/info/cppinternals.info.gz
+OLD_FILES+=3Dusr/share/info/gcc.info.gz
+OLD_FILES+=3Dusr/share/info/gccint.info.gz
+OLD_FILES+=3Dusr/share/man/man1/g++.1.gz
+OLD_FILES+=3Dusr/share/man/man1/gcc.1.gz
+OLD_FILES+=3Dusr/share/man/man1/gcov.1.gz
+OLD_FILES+=3Dusr/share/man/man1/gcpp.1.gz
+.endif
+
 .if ${MK_GCOV} =3D=3D no
 OLD_FILES+=3Dusr/bin/gcov
 OLD_FILES+=3Dusr/share/man/man1/gcov.1.gz
@@ -2184,19 +2220,31 @@
 .endif
=20
 .if ${MK_KERBEROS} =3D=3D no
+OLD_FILES+=3Dusr/bin/compile_et
+OLD_FILES+=3Dusr/bin/hxtool
 OLD_FILES+=3Dusr/bin/kadmin
 OLD_FILES+=3Dusr/bin/kdestroy
+OLD_FILES+=3Dusr/bin/kf
+OLD_FILES+=3Dusr/bin/kgetcred
 OLD_FILES+=3Dusr/bin/kinit
 OLD_FILES+=3Dusr/bin/klist
 OLD_FILES+=3Dusr/bin/kpasswd
 OLD_FILES+=3Dusr/bin/krb5-config
 OLD_FILES+=3Dusr/bin/ksu
+OLD_FILES+=3Dusr/bin/kswitch
+OLD_FILES+=3Dusr/bin/string2key
 OLD_FILES+=3Dusr/bin/verify_krb5_conf
+OLD_FILES+=3Dusr/include/asn1-common.h
 OLD_FILES+=3Dusr/include/asn1_err.h
+OLD_FILES+=3Dusr/include/base64.h
 OLD_FILES+=3Dusr/include/cms_asn1.h
+OLD_FILES+=3Dusr/include/crmf_asn1.h
+OLD_FILES+=3Dusr/include/der-private.h
+OLD_FILES+=3Dusr/include/der-protos.h
+OLD_FILES+=3Dusr/include/der.h
 OLD_FILES+=3Dusr/include/digest_asn1.h
+OLD_FILES+=3Dusr/include/getarg.h
 OLD_FILES+=3Dusr/include/gssapi/gssapi_krb5.h
-OLD_FILES+=3Dusr/include/hdb-private.h
 OLD_FILES+=3Dusr/include/hdb-protos.h
 OLD_FILES+=3Dusr/include/hdb.h
 OLD_FILES+=3Dusr/include/hdb_asn1.h
@@ -2204,8 +2252,10 @@
 OLD_FILES+=3Dusr/include/heim_asn1.h
 OLD_FILES+=3Dusr/include/heim_err.h
 OLD_FILES+=3Dusr/include/heim_threads.h
+OLD_FILES+=3Dusr/include/heimbase.h
 OLD_FILES+=3Dusr/include/heimntlm-protos.h
 OLD_FILES+=3Dusr/include/heimntlm.h
+OLD_FILES+=3Dusr/include/hex.h
 OLD_FILES+=3Dusr/include/hx509-private.h
 OLD_FILES+=3Dusr/include/hx509-protos.h
 OLD_FILES+=3Dusr/include/hx509.h
@@ -2214,30 +2264,50 @@
 OLD_FILES+=3Dusr/include/kadm5/admin.h
 OLD_FILES+=3Dusr/include/kadm5/kadm5-private.h
 OLD_FILES+=3Dusr/include/kadm5/kadm5-protos.h
+OLD_FILES+=3Dusr/include/kadm5/kadm5-pwcheck.h
 OLD_FILES+=3Dusr/include/kadm5/kadm5_err.h
 OLD_FILES+=3Dusr/include/kadm5/private.h
 OLD_FILES+=3Dusr/include/kafs.h
+OLD_FILES+=3Dusr/include/kdc-protos.h
+OLD_FILES+=3Dusr/include/kdc.h
+OLD_FILES+=3Dusr/include/krb5-private.h
 OLD_FILES+=3Dusr/include/krb5-protos.h
 OLD_FILES+=3Dusr/include/krb5-types.h
-OLD_FILES+=3Dusr/include/krb5-v4compat.h
 OLD_FILES+=3Dusr/include/krb5.h
+OLD_FILES+=3Dusr/include/krb5/ccache_plugin.h
+OLD_FILES+=3Dusr/include/krb5/locate_plugin.h
+OLD_FILES+=3Dusr/include/krb5/send_to_kdc_plugin.h
+OLD_FILES+=3Dusr/include/krb5/windc_plugin.h
 OLD_FILES+=3Dusr/include/krb5_asn1.h
+OLD_FILES+=3Dusr/include/krb5_ccapi.h
 OLD_FILES+=3Dusr/include/krb5_err.h
-OLD_FILES+=3Dusr/include/krb_err.h
 OLD_FILES+=3Dusr/include/kx509_asn1.h
+OLD_FILES+=3Dusr/include/ntlm_err.h
 OLD_FILES+=3Dusr/include/ocsp_asn1.h
+OLD_FILES+=3Dusr/include/parse_bytes.h
+OLD_FILES+=3Dusr/include/parse_time.h
+OLD_FILES+=3Dusr/include/parse_units.h
 OLD_FILES+=3Dusr/include/pkcs10_asn1.h
 OLD_FILES+=3Dusr/include/pkcs12_asn1.h
 OLD_FILES+=3Dusr/include/pkcs8_asn1.h
 OLD_FILES+=3Dusr/include/pkcs9_asn1.h
 OLD_FILES+=3Dusr/include/pkinit_asn1.h
+OLD_FILES+=3Dusr/include/resolve.h
 OLD_FILES+=3Dusr/include/rfc2459_asn1.h
 OLD_FILES+=3Dusr/include/roken-common.h
-OLD_FILES+=3Dusr/include/roken.h
+OLD_FILES+=3Dusr/include/rtbl.h
+OLD_FILES+=3Dusr/include/wind.h
+OLD_FILES+=3Dusr/include/wind_err.h
+OLD_FILES+=3Dusr/include/xdbm.h
 OLD_FILES+=3Dusr/lib/libasn1.a
 OLD_FILES+=3Dusr/lib/libasn1.so
-OLD_LIBS+=3Dusr/lib/libasn1.so.10
+OLD_LIBS+=3Dusr/lib/libasn1.so.11
 OLD_FILES+=3Dusr/lib/libasn1_p.a
+OLD_FILES+=3Dusr/lib/libcom_err.a
+OLD_FILES+=3Dusr/lib/libcom_err.so
+OLD_LIBS+=3Dusr/lib/libcom_err.so.5
+OLD_FILES+=3Dusr/lib/libcom_err_p.a
+OLD_FILES+=3Dusr/lib/libcom_err_p.a
 OLD_FILES+=3Dusr/lib/libgssapi_krb5.a
 OLD_FILES+=3Dusr/lib/libgssapi_krb5.so
 OLD_LIBS+=3Dusr/lib/libgssapi_krb5.so.10
@@ -2252,36 +2322,52 @@
 OLD_FILES+=3Dusr/lib/libgssapi_spnego_p.a
 OLD_FILES+=3Dusr/lib/libhdb.a
 OLD_FILES+=3Dusr/lib/libhdb.so
-OLD_LIBS+=3Dusr/lib/libhdb.so.10
+OLD_LIBS+=3Dusr/lib/libhdb.so.11
 OLD_FILES+=3Dusr/lib/libhdb_p.a
+OLD_FILES+=3Dusr/lib/libheimbase.a
+OLD_FILES+=3Dusr/lib/libheimbase.so
+OLD_LIBS+=3Dusr/lib/libheimbase.so.11
+OLD_FILES+=3Dusr/lib/libheimbase_p.a
 OLD_FILES+=3Dusr/lib/libheimntlm.a
 OLD_FILES+=3Dusr/lib/libheimntlm.so
-OLD_LIBS+=3Dusr/lib/libheimntlm.so.10
+OLD_LIBS+=3Dusr/lib/libheimntlm.so.11
 OLD_FILES+=3Dusr/lib/libheimntlm_p.a
+OLD_FILES+=3Dusr/lib/libheimsqlite.a
+OLD_FILES+=3Dusr/lib/libheimsqlite.so
+OLD_LIBS+=3Dusr/lib/libheimsqlite.so.11
+OLD_FILES+=3Dusr/lib/libheimsqlite_p.a
 OLD_FILES+=3Dusr/lib/libhx509.a
 OLD_FILES+=3Dusr/lib/libhx509.so
-OLD_LIBS+=3Dusr/lib/libhx509.so.10
+OLD_LIBS+=3Dusr/lib/libhx509.so.11
 OLD_FILES+=3Dusr/lib/libhx509_p.a
 OLD_FILES+=3Dusr/lib/libkadm5clnt.a
 OLD_FILES+=3Dusr/lib/libkadm5clnt.so
-OLD_LIBS+=3Dusr/lib/libkadm5clnt.so.10
+OLD_LIBS+=3Dusr/lib/libkadm5clnt.so.11
 OLD_FILES+=3Dusr/lib/libkadm5clnt_p.a
 OLD_FILES+=3Dusr/lib/libkadm5srv.a
 OLD_FILES+=3Dusr/lib/libkadm5srv.so
-OLD_LIBS+=3Dusr/lib/libkadm5srv.so.10
+OLD_LIBS+=3Dusr/lib/libkadm5srv.so.11
 OLD_FILES+=3Dusr/lib/libkadm5srv_p.a
 OLD_FILES+=3Dusr/lib/libkafs5.a
 OLD_FILES+=3Dusr/lib/libkafs5.so
-OLD_LIBS+=3Dusr/lib/libkafs5.so.10
+OLD_LIBS+=3Dusr/lib/libkafs5.so.11
 OLD_FILES+=3Dusr/lib/libkafs5_p.a
+OLD_FILES+=3Dusr/lib/libkdc.a
+OLD_FILES+=3Dusr/lib/libkdc.so
+OLD_LIBS+=3Dusr/lib/libkdc.so.11
+OLD_FILES+=3Dusr/lib/libkdc_p.a
 OLD_FILES+=3Dusr/lib/libkrb5.a
 OLD_FILES+=3Dusr/lib/libkrb5.so
-OLD_LIBS+=3Dusr/lib/libkrb5.so.10
+OLD_LIBS+=3Dusr/lib/libkrb5.so.11
 OLD_FILES+=3Dusr/lib/libkrb5_p.a
 OLD_FILES+=3Dusr/lib/libroken.a
 OLD_FILES+=3Dusr/lib/libroken.so
-OLD_LIBS+=3Dusr/lib/libroken.so.10
+OLD_LIBS+=3Dusr/lib/libroken.so.11
 OLD_FILES+=3Dusr/lib/libroken_p.a
+OLD_FILES+=3Dusr/lib/libwind.a
+OLD_FILES+=3Dusr/lib/libwind.so
+OLD_LIBS+=3Dusr/lib/libwind.so.11
+OLD_FILES+=3Dusr/lib/libwind_p.a
 OLD_FILES+=3Dusr/lib/pam_krb5.so
 OLD_LIBS+=3Dusr/lib/pam_krb5.so.5
 OLD_FILES+=3Dusr/lib/pam_ksu.so
@@ -2289,7 +2375,7 @@
 .if ${TARGET_ARCH} =3D=3D "amd64" || ${TARGET_ARCH} =3D=3D "powerpc64"
 OLD_FILES+=3Dusr/lib32/libasn1.a
 OLD_FILES+=3Dusr/lib32/libasn1.so
-OLD_LIBS+=3Dusr/lib32/libasn1.so.10
+OLD_LIBS+=3Dusr/lib32/libasn1.so.11
 OLD_FILES+=3Dusr/lib32/libasn1_p.a
 OLD_FILES+=3Dusr/lib32/libgssapi_krb5.a
 OLD_FILES+=3Dusr/lib32/libgssapi_krb5.so
@@ -2305,41 +2391,58 @@
 OLD_FILES+=3Dusr/lib32/libgssapi_spnego_p.a
 OLD_FILES+=3Dusr/lib32/libhdb.a
 OLD_FILES+=3Dusr/lib32/libhdb.so
-OLD_LIBS+=3Dusr/lib32/libhdb.so.10
+OLD_LIBS+=3Dusr/lib32/libhdb.so.11
 OLD_FILES+=3Dusr/lib32/libhdb_p.a
+OLD_FILES+=3Dusr/lib32/libheimbase.a
+OLD_FILES+=3Dusr/lib32/libheimbase.so
+OLD_LIBS+=3Dusr/lib32/libheimbase.so.11
+OLD_FILES+=3Dusr/lib32/libheimbase_p.a
 OLD_FILES+=3Dusr/lib32/libheimntlm.a
 OLD_FILES+=3Dusr/lib32/libheimntlm.so
-OLD_LIBS+=3Dusr/lib32/libheimntlm.so.10
+OLD_LIBS+=3Dusr/lib32/libheimntlm.so.11
 OLD_FILES+=3Dusr/lib32/libheimntlm_p.a
+OLD_FILES+=3Dusr/lib32/libheimsqlite.a
+OLD_FILES+=3Dusr/lib32/libheimsqlite.so
+OLD_LIBS+=3Dusr/lib32/libheimsqlite.so.11
+OLD_FILES+=3Dusr/lib32/libheimsqlite_p.a
 OLD_FILES+=3Dusr/lib32/libhx509.a
 OLD_FILES+=3Dusr/lib32/libhx509.so
-OLD_LIBS+=3Dusr/lib32/libhx509.so.10
+OLD_LIBS+=3Dusr/lib32/libhx509.so.11
 OLD_FILES+=3Dusr/lib32/libhx509_p.a
 OLD_FILES+=3Dusr/lib32/libkadm5clnt.a
 OLD_FILES+=3Dusr/lib32/libkadm5clnt.so
-OLD_LIBS+=3Dusr/lib32/libkadm5clnt.so.10
+OLD_LIBS+=3Dusr/lib32/libkadm5clnt.so.11
 OLD_FILES+=3Dusr/lib32/libkadm5clnt_p.a
 OLD_FILES+=3Dusr/lib32/libkadm5srv.a
 OLD_FILES+=3Dusr/lib32/libkadm5srv.so
-OLD_LIBS+=3Dusr/lib32/libkadm5srv.so.10
+OLD_LIBS+=3Dusr/lib32/libkadm5srv.so.11
 OLD_FILES+=3Dusr/lib32/libkadm5srv_p.a
 OLD_FILES+=3Dusr/lib32/libkafs5.a
 OLD_FILES+=3Dusr/lib32/libkafs5.so
-OLD_LIBS+=3Dusr/lib32/libkafs5.so.10
+OLD_LIBS+=3Dusr/lib32/libkafs5.so.11
 OLD_FILES+=3Dusr/lib32/libkafs5_p.a
+OLD_FILES+=3Dusr/lib32/libkdc.a
+OLD_FILES+=3Dusr/lib32/libkdc.so
+OLD_LIBS+=3Dusr/lib32/libkdc.so.11
+OLD_FILES+=3Dusr/lib32/libkdc_p.a
 OLD_FILES+=3Dusr/lib32/libkrb5.a
 OLD_FILES+=3Dusr/lib32/libkrb5.so
-OLD_LIBS+=3Dusr/lib32/libkrb5.so.10
+OLD_LIBS+=3Dusr/lib32/libkrb5.so.11
 OLD_FILES+=3Dusr/lib32/libkrb5_p.a
 OLD_FILES+=3Dusr/lib32/libroken.a
 OLD_FILES+=3Dusr/lib32/libroken.so
-OLD_LIBS+=3Dusr/lib32/libroken.so.10
+OLD_LIBS+=3Dusr/lib32/libroken.so.11
 OLD_FILES+=3Dusr/lib32/libroken_p.a
+OLD_FILES+=3Dusr/lib32/libwind.a
+OLD_FILES+=3Dusr/lib32/libwind.so
+OLD_LIBS+=3Dusr/lib32/libwind.so.11
+OLD_FILES+=3Dusr/lib32/libwind_p.a
 OLD_FILES+=3Dusr/lib32/pam_krb5.so
 OLD_LIBS+=3Dusr/lib32/pam_krb5.so.5
 OLD_FILES+=3Dusr/lib32/pam_ksu.so
 OLD_LIBS+=3Dusr/lib32/pam_ksu.so.5
 .endif
+OLD_FILES+=3Dusr/libexec/digest-service
 OLD_FILES+=3Dusr/libexec/hprop
 OLD_FILES+=3Dusr/libexec/hpropd
 OLD_FILES+=3Dusr/libexec/ipropd-master
@@ -2347,42 +2450,273 @@
 OLD_FILES+=3Dusr/libexec/kadmind
 OLD_FILES+=3Dusr/libexec/kcm
 OLD_FILES+=3Dusr/libexec/kdc
+OLD_FILES+=3Dusr/libexec/kdigest
+OLD_FILES+=3Dusr/libexec/kfd
+OLD_FILES+=3Dusr/libexec/kimpersonate
 OLD_FILES+=3Dusr/libexec/kpasswdd
 OLD_FILES+=3Dusr/sbin/kstash
 OLD_FILES+=3Dusr/sbin/ktutil
+OLD_FILES+=3Dusr/sbin/iprop-log
 OLD_FILES+=3Dusr/share/info/heimdal.info.gz
 OLD_FILES+=3Dusr/share/man/man1/kdestroy.1.gz
+OLD_FILES+=3Dusr/share/man/man1/kf.1.gz
 OLD_FILES+=3Dusr/share/man/man1/kinit.1.gz
 OLD_FILES+=3Dusr/share/man/man1/klist.1.gz
 OLD_FILES+=3Dusr/share/man/man1/kpasswd.1.gz
 OLD_FILES+=3Dusr/share/man/man1/krb5-config.1.gz
+OLD_FILES+=3Dusr/share/man/man1/kswitch.1.gz
+OLD_FILES+=3Dusr/share/man/man3/HDB.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb__del.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb__get.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb__put.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_auth_status.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_check_constrained_delegation.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_check_pkinit_ms_upn_match.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_check_s4u2self.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_close.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_destroy.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_entry_ex.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_fetch_kvno.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_firstkey.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_get_realms.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_lock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_nextkey.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_open.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_password.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_remove.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_rename.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_store.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hdb_unlock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_build_ntlm1_master.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_build_ntlm2_master.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_calculate_lm2.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_calculate_ntlm1.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_calculate_ntlm2.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_decode_targetinfo.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_encode_targetinfo.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_encode_type1.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_encode_type2.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_encode_type3.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_free_buf.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_free_targetinfo.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_free_type1.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_free_type2.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_free_type3.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_keyex_unwrap.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_nt_key.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_ntlmv2_key.3.gz
+OLD_FILES+=3Dusr/share/man/man3/heim_ntlm_verify_ntlm2.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_bitstring_print.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_sign.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_sign_self.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_crl_dp_uri.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_eku.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_san_hostname.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_san_jid.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_san_ms_upn.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_san_otherName.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_san_pkinit.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_add_san_rfc822name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_ca.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_domaincontroller.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_notAfter.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_notAfter_lifetime.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_notBefore.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_proxy.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_serialnumber.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_spki.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_subject.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_template.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_set_unique.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_subject_expand.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ca_tbs_template_units.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_binary.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_check_eku.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_cmp.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_find_subjectAltName_otherName.3=
.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_SPKI.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_SPKI_AlgorithmIdentifier.3.=
gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_attribute.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_base_subject.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_friendly_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_issuer.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_issuer_unique_id.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_notAfter.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_notBefore.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_serialnumber.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_subject.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_get_subject_unique_id.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_init_data.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_keyusage_print.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_ref.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cert_set_friendly_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_add.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_append.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_end_seq.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_filter.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_find.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_info.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_iter_f.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_merge.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_next_cert.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_start_seq.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_certs_store.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ci_print_names.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_clear_error_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cms.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cms_create_signed_1.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cms_envelope_1.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cms_unenvelope.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cms_unwrap_ContentInfo.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cms_verify_signed.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_cms_wrap_ContentInfo.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_context_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_context_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_context_set_missing_revoke.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_crl_add_revoked_certs.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_crl_alloc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_crl_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_crl_lifetime.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_crl_sign.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_crypto.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_env.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_env_add.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_env_add_binding.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_env_find.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_env_find_binding.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_env_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_env_lfind.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_err.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_error.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_free_error_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_free_octet_string_list.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_general_name_unparse.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_get_error_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_get_one_cert.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_keyset.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_lock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_misc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_binary.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_cmp.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_copy.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_expand.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_is_null_p.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_to_Name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_name_to_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ocsp_request.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_ocsp_verify.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_oid_print.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_oid_sprint.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_parse_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_peer.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_peer_info_add_cms_alg.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_peer_info_alloc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_peer_info_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_peer_info_set_cert.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_peer_info_set_cms_algs.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_print.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_print_cert.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_print_stdout.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_alloc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_match_cmp_func.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_match_eku.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_match_friendly_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_match_issuer_serial.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_match_option.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_statistic_file.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_query_unparse_stats.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_revoke.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_revoke_add_crl.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_revoke_add_ocsp.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_revoke_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_revoke_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_revoke_ocsp_print.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_revoke_verify.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_set_error_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_set_error_stringv.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_unparse_der_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_validate_cert.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_validate_ctx_add_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_validate_ctx_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_validate_ctx_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_validate_ctx_set_print.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_attach_anchors.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_attach_revoke.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_ctx_f_allow_default_trustanch=
ors.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_destroy_ctx.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_hostname.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_init_ctx.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_path.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_set_max_depth.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_set_proxy_certificate.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_set_strict_rfc3280_verificati=
on.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_set_time.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_verify_signature.3.gz
+OLD_FILES+=3Dusr/share/man/man3/hx509_xfree.3.gz
+OLD_FILES+=3Dusr/share/man/man3/k_afs_cell_of_file.3.gz
 OLD_FILES+=3Dusr/share/man/man3/k_afs_cell_of_file.3.gz
 OLD_FILES+=3Dusr/share/man/man3/k_hasafs.3.gz
+OLD_FILES+=3Dusr/share/man/man3/k_hasafs.3.gz
+OLD_FILES+=3Dusr/share/man/man3/k_pioctl.3.gz
 OLD_FILES+=3Dusr/share/man/man3/k_pioctl.3.gz
 OLD_FILES+=3Dusr/share/man/man3/k_setpag.3.gz
+OLD_FILES+=3Dusr/share/man/man3/k_setpag.3.gz
 OLD_FILES+=3Dusr/share/man/man3/k_unlog.3.gz
+OLD_FILES+=3Dusr/share/man/man3/k_unlog.3.gz
+OLD_FILES+=3Dusr/share/man/man3/kadm5_pwcheck.3.gz
+OLD_FILES+=3Dusr/share/man/man3/kafs.3.gz
 OLD_FILES+=3Dusr/share/man/man3/kafs.3.gz
 OLD_FILES+=3Dusr/share/man/man3/kafs5.3.gz
+OLD_FILES+=3Dusr/share/man/man3/kafs5.3.gz
+OLD_FILES+=3Dusr/share/man/man3/kafs_set_verbose.3.gz
 OLD_FILES+=3Dusr/share/man/man3/kafs_set_verbose.3.gz
 OLD_FILES+=3Dusr/share/man/man3/kafs_settoken.3.gz
+OLD_FILES+=3Dusr/share/man/man3/kafs_settoken.3.gz
 OLD_FILES+=3Dusr/share/man/man3/kafs_settoken5.3.gz
+OLD_FILES+=3Dusr/share/man/man3/kafs_settoken5.3.gz
+OLD_FILES+=3Dusr/share/man/man3/kafs_settoken_rxkad.3.gz
 OLD_FILES+=3Dusr/share/man/man3/kafs_settoken_rxkad.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb524_convert_creds_kdc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb524_convert_creds_kdc_ccache.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_425_conv_principal.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_425_conv_principal_ext.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_524_conv_principal.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_acc_ops.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_acl_match_file.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_acl_match_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_add_et_list.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_add_extra_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_add_ignore_addresses.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_addlog_dest.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_addlog_func.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_addr2sockaddr.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_address.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_address_compare.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_address_order.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_address_prefixlen_boundary.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_address_search.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_afslog.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_afslog.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_afslog_uid.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_afslog_uid.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_allow_weak_crypto.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_aname_to_localname.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_anyaddr.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_appdefault.3.gz
@@ -2390,6 +2724,7 @@
 OLD_FILES+=3Dusr/share/man/man3/krb5_appdefault_string.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_appdefault_time.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_append_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_auth.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_con_free.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_con_genaddrs.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_con_getaddrs.3.gz
@@ -2416,6 +2751,7 @@
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_getkeytype.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_getlocalseqnumber.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_getremoteseqnumber.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_auth_getremoteseqnumber.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_setcksumtype.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_setkeytype.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_auth_setlocalseqnumber.3.gz
@@ -2424,104 +2760,233 @@
 OLD_FILES+=3Dusr/share/man/man3/krb5_build_principal_ext.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_build_principal_va.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_build_principal_va_ext.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_c_enctype_compare.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_c_make_checksum.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_cache_end_seq_get.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_cache_get_first.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_cache_match.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_cache_next.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_clear_mcred.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_close.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_copy_cache.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_cc_cursor.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_copy_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_copy_match_f.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_default.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_default_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_destroy.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_end_seq_get.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_gen_new.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_config.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_friendly_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_full_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_kdc_offset.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_lifetime.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_ops.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_prefix_ops.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_principal.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_type.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_get_version.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_initialize.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_last_change_time.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_move.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_new_unique.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_next_cred.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_cc_ops.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_register.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_remove_cred.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_resolve.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_retrieve_cred.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_set_config.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_set_default_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_set_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_set_friendly_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_set_kdc_offset.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_start_seq_get.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_cc_store_cred.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_support_switch.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cc_switch.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_ccache.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ccache_intro.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cccol_cursor_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cccol_cursor_new.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cccol_cursor_next.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cccol_last_change_time.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_change_password.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_check_transited.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_checksum_is_collision_proof.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_checksum_is_keyed.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_checksumsize.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_cksumtype_to_enctype.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_clear_error_message.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_clear_error_string.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_closelog.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_compare_creds.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_config.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_file_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_free_strings.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_bool.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_bool_default.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_int_default.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_list.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_string.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_string_default.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_strings.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_time.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_config_get_time_default.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_context.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_parse_file_multi.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_parse_string_multi.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_bool.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_bool_default.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_list.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_string_default.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_strings.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_time.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_config_vget_time_default.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_copy_address.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_copy_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_copy_context.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_copy_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_copy_creds_contents.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_copy_data.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_copy_host_realm.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_copy_keyblock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_copy_keyblock_contents.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_copy_principal.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_copy_ticket.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_create_checksum.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_create_checksum_iov.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_credential.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_creds_get_ticket_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_crypto.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_destroy.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_fx_cf2.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_getblocksize.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_getconfoundersize.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_getenctype.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_getpadsize.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_init.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_data.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_crypto_iov.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_data_alloc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_data_cmp.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_data_copy.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_data_ct_cmp.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_data_free.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_data_realloc.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_data_zero.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_decrypt.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_decrypt_EncryptedData.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_decrypt_iov_ivec.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_deprecated.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_digest.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_digest_probe.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_eai_to_heim_errno.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_encrypt.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_encrypt_EncryptedData.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_err.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_errx.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_encrypt_iov_ivec.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_enctype_disable.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_enctype_enable.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_enctype_valid.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_enctypes_compatible_keys.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_error.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_expand_hostname.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_expand_hostname_realms.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_fcc_ops.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_fileformats.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_find_padata.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_address.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_config_files.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_context.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_context.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_cred_contents.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_creds_contents.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_data.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_data_contents.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_error_string.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_host_realm.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_host_realm.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_keyblock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_keyblock_contents.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_krbhst.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_free_principal.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_ticket.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_free_unparsed_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_fwd_tgt_creds.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_generate_random_block.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_generate_subkey.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_generate_subkey_extended.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_all_client_addrs.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_all_server_addrs.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_cred_from_kdc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_cred_from_kdc_opt.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_credentials.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_default_config_files.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_default_in_tkt_etypes.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_default_principal.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_default_realm.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_default_realms.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_dns_canonicalize_hostname.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_extra_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_fcache_version.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_forwarded_creds.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_host_realm.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_ignore_addresses.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_in_cred.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_in_tkt_with_keytab.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_in_tkt_with_password.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_in_tkt_with_skey.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds_keyblock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds_keytab.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds_opt_alloc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds_opt_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds_opt_get_error.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds_opt_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_init_creds_password.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_kdc_sec_offset.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_krb524hst.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_krb_admin_hst.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_krb_changepw_hst.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_get_krbhst.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_max_time_skew.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_use_admin_kdc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_get_validated_creds.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_getportbyname.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_h_addr2addr.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_h_addr2sockaddr.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_h_errno_to_heim_errno.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_init_context.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_get.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_get_error.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_intro.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_set_keytab.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_set_password.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_set_service.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_creds_step.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_init_ets.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_initlog.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_introduction.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_is_config_principal.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_is_thread_safe.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_keyblock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_kerberos_enctypes.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keyblock_get_enctype.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keyblock_init.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keyblock_zero.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_keytab.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_keytab_entry.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keytab_intro.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keytab_key_proc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keytype_to_enctypes.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keytype_to_enctypes_default.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_keytype_to_string.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_krbhst_format_string.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_krbhst_free.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_krbhst_get_addrinfo.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_krbhst_get_addrinfo.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_krbhst_init.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_krbhst_next.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_krbhst_next_as_string.3.gz
@@ -2530,16 +2995,18 @@
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_close.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_compare.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_copy_entry_contents.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_kt_cursor.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_default.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_kt_default_modify_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_default_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_kt_destroy.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_end_seq_get.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_free_entry.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_get_entry.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_kt_get_full_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_get_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_get_type.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_kt_have_content.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_next_entry.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_kt_ops.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_read_service_key.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_register.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_kt_remove_entry.3.gz
@@ -2555,36 +3022,128 @@
 OLD_FILES+=3Dusr/share/man/man3/krb5_mk_req.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_mk_safe.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_openlog.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_pac.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_pac_get_buffer.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_pac_verify.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_parse_address.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_parse_name.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_parse_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_parse_name_flags.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_parse_nametype.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_password_key_proc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_plugin_register.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_prepend_config_files_default.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_princ_realm.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_princ_realm.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_princ_set_realm.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_princ_set_realm.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal_compare.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal_compare_any_realm.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal_get_comp_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_principal_get_num_comp.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal_get_realm.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal_get_type.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_principal_intro.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_principal_is_krbtgt.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal_match.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_principal_set_realm.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_principal_set_type.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_print_address.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_random_to_key.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_rcache.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_rd_error.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_rd_req_ctx.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_rd_req_in_ctx_alloc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_rd_req_in_set_keytab.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_rd_req_in_set_pac_check.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_rd_req_out_ctx_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_rd_req_out_get_server.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_rd_safe.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_realm_compare.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_address.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_addrs.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_authdata.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_creds_tag.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_data.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_int16.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_int32.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_int8.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_keyblock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_principal.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_stringz.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_times.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_uint16.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_uint32.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ret_uint8.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_config_files.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_default_in_tkt_etypes.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_set_default_realm.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_dns_canonicalize_hostname.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_error_message.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_error_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_extra_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_fcache_version.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_home_dir_access.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_ignore_addresses.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_kdc_sec_offset.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_max_time_skew.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_set_password.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_set_warn_dest.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_real_time.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_set_use_admin_kdc.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_sname_to_principal.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_sock_to_principal.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_sockaddr2address.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_sockaddr2port.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_sockaddr_uninteresting.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_storage.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_clear_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_emem.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_free.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_from_data.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_from_fd.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_from_mem.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_from_readonly_mem.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_get_byteorder.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_get_eof_code.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_is_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_read.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_seek.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_set_byteorder.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_set_eof_code.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_set_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_set_max_alloc.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_to_data.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_truncate.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_storage_write.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_address.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_addrs.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_authdata.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_creds.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_creds_tag.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_data.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_int16.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_int32.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_int8.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_keyblock.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_principal.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_string.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_stringz.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_times.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_uint16.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_uint32.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_store_uint8.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_string_to_key.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_string_to_keytype.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_support.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_ticket.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ticket_get_authorization_data_type.3.=
gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ticket_get_client.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ticket_get_endtime.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ticket_get_flags.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_ticket_get_server.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_timeofday.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_unparse_name.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_unparse_name_fixed.3.gz
@@ -2593,7 +3152,9 @@
 OLD_FILES+=3Dusr/share/man/man3/krb5_unparse_name_flags.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_unparse_name_short.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_us_timeofday.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_v4compat.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_verify_checksum.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_verify_checksum_iov.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_verify_init_creds.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_verify_opt_init.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_verify_opt_set_flags.3.gz
@@ -2603,29 +3164,38 @@
 OLD_FILES+=3Dusr/share/man/man3/krb5_verify_user.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_verify_user_lrealm.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_verify_user_opt.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_verr.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_verrx.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_vlog.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_vlog_msg.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb5_vset_error_string.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb5_vwarn.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_vwarnx.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_warn.3.gz
-OLD_FILES+=3Dusr/share/man/man3/krb5_warnx.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb_afslog.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb_afslog.3.gz
 OLD_FILES+=3Dusr/share/man/man3/krb_afslog_uid.3.gz
+OLD_FILES+=3Dusr/share/man/man3/krb_afslog_uid.3.gz
+OLD_FILES+=3Dusr/share/man/man3/ntlm_buf.3.gz
+OLD_FILES+=3Dusr/share/man/man3/ntlm_core.3.gz
+OLD_FILES+=3Dusr/share/man/man3/ntlm_type1.3.gz
+OLD_FILES+=3Dusr/share/man/man3/ntlm_type2.3.gz
+OLD_FILES+=3Dusr/share/man/man3/ntlm_type3.3.gz
 OLD_FILES+=3Dusr/share/man/man5/krb5.conf.5.gz
 OLD_FILES+=3Dusr/share/man/man8/hprop.8.gz
 OLD_FILES+=3Dusr/share/man/man8/hpropd.8.gz
+OLD_FILES+=3Dusr/share/man/man8/iprop-log.8.gz
+OLD_FILES+=3Dusr/share/man/man8/iprop.8.gz
 OLD_FILES+=3Dusr/share/man/man8/kadmin.8.gz
 OLD_FILES+=3Dusr/share/man/man8/kadmind.8.gz
 OLD_FILES+=3Dusr/share/man/man8/kcm.8.gz
 OLD_FILES+=3Dusr/share/man/man8/kdc.8.gz
+OLD_FILES+=3Dusr/share/man/man8/kdigest.8.gz
 OLD_FILES+=3Dusr/share/man/man8/kerberos.8.gz
+OLD_FILES+=3Dusr/share/man/man8/kimpersonate.8.gz
 OLD_FILES+=3Dusr/share/man/man8/kpasswdd.8.gz
 OLD_FILES+=3Dusr/share/man/man8/kstash.8.gz
 OLD_FILES+=3Dusr/share/man/man8/ktutil.8.gz
 OLD_FILES+=3Dusr/share/man/man8/pam_krb5.8.gz
 OLD_FILES+=3Dusr/share/man/man8/pam_ksu.8.gz
+OLD_FILES+=3Dusr/share/man/man8/string2key.8.gz
+OLD_FILES+=3Dusr/share/man/man8/verify_krb5_conf.8.gz
 OLD_FILES+=3Dusr/share/man/man8/verify_krb5_conf.8.gz
 .endif
=20
@@ -2993,6 +3563,8 @@
 OLD_FILES+=3Dusr/lib/libgssapi_krb5_p.a
 OLD_FILES+=3Dusr/lib/libgssapi_p.a
 OLD_FILES+=3Dusr/lib/libhdb_p.a
+OLD_FILES+=3Dusr/lib/libheimbase_p.a
+OLD_FILES+=3Dusr/lib/libheimsqlite_p.a
 OLD_FILES+=3Dusr/lib/libhistory_p.a
 OLD_FILES+=3Dusr/lib/libipsec_p.a
 OLD_FILES+=3Dusr/lib/libipx_p.a
@@ -3000,6 +3572,7 @@
 OLD_FILES+=3Dusr/lib/libkadm5clnt_p.a
 OLD_FILES+=3Dusr/lib/libkadm5srv_p.a
 OLD_FILES+=3Dusr/lib/libkafs5_p.a
+OLD_FILES+=3Dusr/lib/libkdc_p.a
 OLD_FILES+=3Dusr/lib/libkiconv_p.a
 OLD_FILES+=3Dusr/lib/libkrb5_p.a
 OLD_FILES+=3Dusr/lib/libkvm_p.a
@@ -3052,6 +3625,7 @@
 OLD_FILES+=3Dusr/lib/libusbhid_p.a
 OLD_FILES+=3Dusr/lib/libutil_p.a
 OLD_FILES+=3Dusr/lib/libvgl_p.a
+OLD_FILES+=3Dusr/lib/libwind_p.a
 OLD_FILES+=3Dusr/lib/libwrap_p.a
 OLD_FILES+=3Dusr/lib/liby_p.a
 OLD_FILES+=3Dusr/lib/libypclnt_p.a
diff -r 428842767fa6 -r f2935497fa04 head/tools/make_libdeps.sh
--- a/head/tools/make_libdeps.sh	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/tools/make_libdeps.sh	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 # SUCH DAMAGE.
 #
-# $FreeBSD: head/tools/make_libdeps.sh 225778 2011-09-27 07:14:12Z stas $
+# $FreeBSD: head/tools/make_libdeps.sh 233294 2012-03-22 08:48:42Z stas $
=20
 export PATH=3D/bin:/usr/bin
=20
@@ -52,7 +52,7 @@
     -e's;-l(ncurses|termcap)!;lib/ncurses/ncurses;g'
     -e's;-l(gcc)!;gnu/lib/lib\1;g'
     -e's;-lssp_nonshared!;gnu/lib/libssp/libssp_nonshared;g'
-    -e's;-l(asn1|hdb|heimntlm|hx509|krb5|roken)!;kerberos5/lib/lib\1;g'
+    -e's;-l(asn1|hdb|kdc|heimbase|heimntlm|heimsqlite|hx509|krb5|roken|win=
d)!;kerberos5/lib/lib\1;g'
     -e's;-l(crypto|ssh|ssl)!;secure/lib/lib\1;g'
     -e's;-l([^!]+)!;lib/lib\1;g'
 "
diff -r 428842767fa6 -r f2935497fa04 head/tools/regression/lib/msun/test-re=
m.c
--- a/head/tools/regression/lib/msun/test-rem.c	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/tools/regression/lib/msun/test-rem.c	Tue Apr 17 11:51:51 2012 +0=
300
@@ -31,7 +31,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/tools/regression/lib/msun/test-rem.c 233974 2012-=
04-07 04:00:30Z das $");
=20
 #include <assert.h>
 #include <float.h>
@@ -55,7 +55,7 @@
 main(int argc, char *argv[])
 {
=20
-	printf("1..2\n");
+	printf("1..3\n");
=20
 	test_invalid(0.0, 0.0);
 	test_invalid(1.0, 0.0);
@@ -96,6 +96,14 @@
=20
 	printf("ok 2 - rem\n");
=20
+	test(0x1.66666cp+120, 0x1p+71, 0.0, 1476395008);
+	testd(-0x1.0000000000003p+0, 0x1.0000000000003p+0, -0.0, -1);
+	testl(-0x1.0000000000003p+0, 0x1.0000000000003p+0, -0.0, -1);
+	testd(-0x1.0000000000001p-749, 0x1.4p-1072, 0x1p-1074, -1288490189);
+	testl(-0x1.0000000000001p-749, 0x1.4p-1072, 0x1p-1074, -1288490189);
+
+	printf("ok 3 - rem\n");
+
 	return (0);
 }
=20
@@ -136,10 +144,16 @@
 testl(long double x, long double y, long double expected_rem, int expected=
_quo)
 {
 	int q;
+	long double rem;
=20
 	q =3D random();
-	assert(remainderl(x, y) =3D=3D expected_rem);
-	assert(remquol(x, y, &q) =3D=3D expected_rem);
+	rem =3D remainderl(x, y);
+	assert(rem =3D=3D expected_rem);
+	assert(!signbit(rem) =3D=3D !signbit(expected_rem));
+	rem =3D remquol(x, y, &q);
+	assert(rem =3D=3D expected_rem);
+	assert(!signbit(rem) =3D=3D !signbit(expected_rem));
+	assert((q ^ expected_quo) >=3D 0); /* sign(q) =3D=3D sign(expected_quo) */
 	assert((q & 0x7) =3D=3D (expected_quo & 0x7));
 	if (q !=3D 0) {
 		assert((q > 0) ^ !(expected_quo > 0));
@@ -152,10 +166,16 @@
 testd(double x, double y, double expected_rem, int expected_quo)
 {
 	int q;
+	double rem;
=20
 	q =3D random();
-	assert(remainder(x, y) =3D=3D expected_rem);
-	assert(remquo(x, y, &q) =3D=3D expected_rem);
+	rem =3D remainder(x, y);
+	assert(rem =3D=3D expected_rem);
+	assert(!signbit(rem) =3D=3D !signbit(expected_rem));
+	rem =3D remquo(x, y, &q);
+	assert(rem =3D=3D expected_rem);
+	assert(!signbit(rem) =3D=3D !signbit(expected_rem));
+	assert((q ^ expected_quo) >=3D 0); /* sign(q) =3D=3D sign(expected_quo) */
 	assert((q & 0x7) =3D=3D (expected_quo & 0x7));
 	if (q !=3D 0) {
 		assert((q > 0) ^ !(expected_quo > 0));
@@ -168,10 +188,16 @@
 testf(float x, float y, float expected_rem, int expected_quo)
 {
 	int q;
+	float rem;
=20
 	q =3D random();
-	assert(remainderf(x, y) =3D=3D expected_rem);
-	assert(remquof(x, y, &q) =3D=3D expected_rem);
+	rem =3D remainderf(x, y);
+	assert(rem =3D=3D expected_rem);
+	assert(!signbit(rem) =3D=3D !signbit(expected_rem));
+	rem =3D remquof(x, y, &q);
+	assert(rem =3D=3D expected_rem);
+	assert(!signbit(rem) =3D=3D !signbit(expected_rem));
+	assert((q ^ expected_quo) >=3D 0); /* sign(q) =3D=3D sign(expected_quo) */
 	assert((q & 0x7) =3D=3D (expected_quo & 0x7));
 	if (q !=3D 0) {
 		assert((q > 0) ^ !(expected_quo > 0));
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/ath/athdecode/main.c
--- a/head/tools/tools/ath/athdecode/main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/tools/tools/ath/athdecode/main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: head/tools/tools/ath/athdecode/main.c 217680 2011-01-21 02:53=
:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athdecode/main.c 233887 2012-04-04 20:46=
:20Z adrian $
  */
 #include "diag.h"
=20
@@ -375,7 +375,7 @@
 	const char* bits;
 	int i;
=20
-	fprintf(fd, "\n%05d: ", recnum);
+	fprintf(fd, "\n%05d: [%d] ", recnum, r->threadid);
 	dr =3D findreg(r->reg);
 	if (dr !=3D NULL && dr->name !=3D NULL) {
 		snprintf(buf, sizeof (buf), "AR_%s (0x%x)", dr->name, r->reg);
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/ath/athrd/athrd.1
--- a/head/tools/tools/ath/athrd/athrd.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/tools/tools/ath/athrd/athrd.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGES.
 .\"
-.\" $FreeBSD: head/tools/tools/ath/athrd/athrd.1 187904 2009-01-29 23:24:2=
1Z sam $
+.\" $FreeBSD: head/tools/tools/ath/athrd/athrd.1 233648 2012-03-29 05:02:1=
2Z eadler $
 .\"/
 .Dd January 27, 2009
 .Dt ATHRD 1
@@ -82,10 +82,10 @@
 Mark passive scan channels with lower case letters and active
 scan channels with upper case letters.
 .It Fl r
-Mark channels that require DFS with a=20
+Mark channels that require DFS with a
 .Ql * .
 .It Fl 4
-Mark channels that have a 4ms packet limit with a=20
+Mark channels that have a 4ms packet limit with a
 .Ql 4 .
 .It Fl c
 Display IEEE channel numbers instead of frequencies.
@@ -117,10 +117,10 @@
 .Ql B ,
 .Ql A ,
 or
-.Ql T=20
+.Ql T
 according to whether the channel is usable with 802.11g, 802.11b,
 802.11a, or Atheros Turbo mode.
-All channels listed as=20
+All channels listed as
 .Ql G
 are also usable in
 .Ql B .
@@ -158,7 +158,7 @@
 use the HAL to calculate the set of channels.
 The transmit power calculations are done by emulating
 how the HAL works.
-Because=20
+Because
 .Nm
 does not
 read the actual EEPROM contents from a device this emulation may lag
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/ath/common/dumpregs_5=
416.c
--- a/head/tools/tools/ath/common/dumpregs_5416.c	Tue Apr 17 11:36:47 2012 =
+0300
+++ b/head/tools/tools/ath/common/dumpregs_5416.c	Tue Apr 17 11:51:51 2012 =
+0300
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: head/tools/tools/ath/common/dumpregs_5416.c 206848 2010-04-19=
 17:16:23Z rpaulo $
+ * $FreeBSD: head/tools/tools/ath/common/dumpregs_5416.c 234015 2012-04-08=
 04:42:53Z adrian $
  */
 #include "diag.h"
=20
@@ -76,6 +76,7 @@
 	  "\30CABTO\31DTIM"),
     DEFINT(AR_ISR_S3,		"ISR_S3"),
     DEFINT(AR_ISR_S4,		"ISR_S4"),
+    DEFINT(AR_ISR_S5,		"ISR_S5"),
     DEFINTfmt(AR_IMR,		"IMR",
 	  "\20\1RXOK\2RXDESC\3RXERR\4RXNOPKT\5RXEOL\6RXORN\7TXOK\10TXDESC"
 	  "\11TXERR\12TXNOPKT\13TXEOL\14TXURN\15MIB\16SWI\17RXPHY\20RXKCM"
@@ -95,6 +96,7 @@
     DEFINT(AR_ISR_S2_S,		"ISR_S2_S"),
     DEFINT(AR_ISR_S3_S,		"ISR_S3_S"),
     DEFINT(AR_ISR_S4_S,		"ISR_S4_S"),
+    DEFINT(AR_ISR_S5_S,		"ISR_S5_S"),
=20
     DEFBASIC(AR_DMADBG_0,	"DMADBG0"),
     DEFBASIC(AR_DMADBG_1,	"DMADBG1"),
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/ether_reflect/ether_r=
eflect.1
--- a/head/tools/tools/ether_reflect/ether_reflect.1	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/tools/tools/ether_reflect/ether_reflect.1	Tue Apr 17 11:51:51 20=
12 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/tools/tools/ether_reflect/ether_reflect.1 222286 2011-0=
5-25 14:13:53Z ru $
+.\" $FreeBSD: head/tools/tools/ether_reflect/ether_reflect.1 233648 2012-0=
3-29 05:02:12Z eadler $
 .\"
 .Dd December 23, 2008
 .Dt ETHER_REFLECT 1
@@ -39,7 +39,7 @@
 .Op Fl p
 .Op Fl d
 .Sh DESCRIPTION
-The=20
+The
 .Nm
 command implements a simple ethernet packet reflector using the
 .Xr PCAP 3
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/net80211/wlanstats/wl=
anstats.c
--- a/head/tools/tools/net80211/wlanstats/wlanstats.c	Tue Apr 17 11:36:47 2=
012 +0300
+++ b/head/tools/tools/net80211/wlanstats/wlanstats.c	Tue Apr 17 11:51:51 2=
012 +0300
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: head/tools/tools/net80211/wlanstats/wlanstats.c 232245 2012-0=
2-28 04:06:42Z adrian $
+ * $FreeBSD: head/tools/tools/net80211/wlanstats/wlanstats.c 234019 2012-0=
4-08 04:51:43Z adrian $
  */
=20
 /*
@@ -372,6 +372,12 @@
 	{ 5,	"signal",	"sig",		"current signal (dBm)" },
 #define	S_BEACON_BAD		AFTER(S_SIGNAL)
 	{ 9,	"beacon_bad",	"beaconbad",	"bad beacons received" },
+#define	S_AMPDU_BARTX		AFTER(S_BEACON_BAD)
+	{ 5,	"ampdu_bartx",	"bartx",	"BAR frames sent" },
+#define	S_AMPDU_BARTX_FAIL	AFTER(S_AMPDU_BARTX)
+	{ 9,	"ampdu_bartxfail",	"bartx_fail",	"BAR frames failed to send" },
+#define	S_AMPDU_BARTX_RETRY	AFTER(S_AMPDU_BARTX_FAIL)
+	{ 10,	"ampdu_bartxretry",	"bartx_retry",	"BAR frames retried" },
 };
=20
 struct wlanstatfoo_p {
@@ -817,6 +823,9 @@
 	case S_TX_UCAST:	NSTAT(tx_ucast);
 	case S_TX_MCAST:	NSTAT(tx_mcast);
 	case S_BEACON_BAD:	STAT(beacon_bad);
+	case S_AMPDU_BARTX:	STAT(ampdu_bar_tx);
+	case S_AMPDU_BARTX_RETRY:	STAT(ampdu_bar_tx_retry);
+	case S_AMPDU_BARTX_FAIL:	STAT(ampdu_bar_tx_fail);
 	}
 	return wlan_getinfo(wf, s, b, bs);
 #undef NSTAT
@@ -976,6 +985,9 @@
 	case S_TX_UCAST:	NSTAT(tx_ucast);
 	case S_TX_MCAST:	NSTAT(tx_mcast);
 	case S_BEACON_BAD:	STAT(beacon_bad);
+	case S_AMPDU_BARTX:	STAT(ampdu_bar_tx);
+	case S_AMPDU_BARTX_RETRY:	STAT(ampdu_bar_tx_retry);
+	case S_AMPDU_BARTX_FAIL:	STAT(ampdu_bar_tx_fail);
 	}
 	return wlan_getinfo(wf, s, b, bs);
 #undef NSTAT
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/netmap/bridge.c
--- a/head/tools/tools/netmap/bridge.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/tools/tools/netmap/bridge.c	Tue Apr 17 11:51:51 2012 +0300
@@ -6,7 +6,7 @@
  * A netmap client to bridge two network interfaces
  * (or one interface and the host stack).
  *
- * $FreeBSD: head/tools/tools/netmap/bridge.c 232238 2012-02-27 19:05:01Z =
luigi $
+ * $FreeBSD: head/tools/tools/netmap/bridge.c 234227 2012-04-13 16:03:07Z =
luigi $
  */
=20
 #include <errno.h>
@@ -48,7 +48,7 @@
 	} while (0)
=20
=20
-char *version =3D "$Id: bridge.c 10637 2012-02-24 16:36:25Z luigi $";
+char *version =3D "$Id: bridge.c 10857 2012-04-06 12:18:22Z luigi $";
=20
 static int do_abort =3D 0;
=20
@@ -300,12 +300,20 @@
 	if (0 && verbose && tot && !tx)
 		D("ring %s %s %s has %d avail at %d",
 			me->ifname, tx ? "tx": "rx",
-			me->end > me->nifp->ni_rx_queues ?
+			me->end >=3D me->nifp->ni_tx_rings ? // XXX who comes first ?
 				"host":"net",
 			tot, NETMAP_TXRING(me->nifp, me->begin)->cur);
 	return tot;
 }
=20
+static void
+usage(void)
+{
+	fprintf(stderr,
+	    "usage: bridge [-v] [-i ifa] [-i ifb] [-b burst] [-w wait_time] [ifac=
e]\n");
+	exit(1);
+}
+
 /*
  * bridge [-v] if1 [if2]
  *
@@ -317,36 +325,74 @@
 main(int argc, char **argv)
 {
 	struct pollfd pollfd[2];
-	int i;
-	u_int burst =3D 1024;
+	int i, ch;
+	u_int burst =3D 1024, wait_link =3D 4;
 	struct my_ring me[2];
+	char *ifa =3D NULL, *ifb =3D NULL;
=20
 	fprintf(stderr, "%s %s built %s %s\n",
 		argv[0], version, __DATE__, __TIME__);
=20
 	bzero(me, sizeof(me));
=20
-	while (argc > 1 && !strcmp(argv[1], "-v")) {
-		verbose++;
-		argv++;
-		argc--;
+	while ( (ch =3D getopt(argc, argv, "b:i:vw:")) !=3D -1) {
+		switch (ch) {
+			D("bad option %c %s", ch, optarg);
+			usage();
+			break;
+		case 'b':	/* burst */
+			burst =3D atoi(optarg);
+			break;
+		case 'i':	/* interface */
+			if (ifa =3D=3D NULL)
+				ifa =3D optarg;
+			else if (ifb =3D=3D NULL)
+				ifb =3D optarg;
+			else
+				D("%s ignored, already have 2 interfaces",
+					optarg);
+			break;
+		case 'v':
+			verbose++;
+			break;
+		case 'w':
+			wait_link =3D atoi(optarg);
+			break;
+		}
+
 	}
+	argc -=3D optind;
+	argv +=3D optind;
=20
-	if (argc < 2 || argc > 4) {
-		D("Usage: %s IFNAME1 [IFNAME2 [BURST]]", argv[0]);
-		return (1);
+	if (argc > 1)
+		ifa =3D argv[1];
+	if (argc > 2)
+		ifb =3D argv[2];
+	if (argc > 3)
+		burst =3D atoi(argv[3]);
+	if (!ifb)
+		ifb =3D ifa;
+	if (!ifa) {
+		D("missing interface");
+		usage();
 	}
-
+	if (burst < 1 || burst > 8192) {
+		D("invalid burst %d, set to 1024", burst);
+		burst =3D 1024;
+	}
+	if (wait_link > 100) {
+		D("invalid wait_link %d, set to 4", wait_link);
+		wait_link =3D 4;
+	}
 	/* setup netmap interface #1. */
-	me[0].ifname =3D argv[1];
-	if (argc =3D=3D 2 || !strcmp(argv[1], argv[2])) {
+	me[0].ifname =3D ifa;
+	me[1].ifname =3D ifb;
+	if (!strcmp(ifa, ifb)) {
 		D("same interface, endpoint 0 goes to host");
 		i =3D NETMAP_SW_RING;
-		me[1].ifname =3D argv[1];
 	} else {
 		/* two different interfaces. Take all rings on if1 */
 		i =3D 0;	// all hw rings
-		me[1].ifname =3D argv[2];
 	}
 	if (netmap_open(me, i))
 		return (1);
@@ -385,8 +431,6 @@
 	me[1].if_reqcap =3D me[1].if_curcap;
 	me[1].if_reqcap &=3D ~(IFCAP_HWCSUM | IFCAP_TSO | IFCAP_TOE);
 	do_ioctl(me+1, SIOCSIFCAP);
-	if (argc > 3)
-		burst =3D atoi(argv[3]);	/* packets burst size. */
=20
 	/* setup poll(2) variables. */
 	memset(pollfd, 0, sizeof(pollfd));
@@ -395,11 +439,11 @@
 		pollfd[i].events =3D (POLLIN);
 	}
=20
-	D("Wait 2 secs for link to come up...");
-	sleep(2);
+	D("Wait %d secs for link to come up...", wait_link);
+	sleep(wait_link);
 	D("Ready to go, %s 0x%x/%d <-> %s 0x%x/%d.",
-		me[0].ifname, me[0].queueid, me[0].nifp->ni_rx_queues,
-		me[1].ifname, me[1].queueid, me[1].nifp->ni_rx_queues);
+		me[0].ifname, me[0].queueid, me[0].nifp->ni_rx_rings,
+		me[1].ifname, me[1].queueid, me[1].nifp->ni_rx_rings);
=20
 	/* main loop */
 	signal(SIGINT, sigint_h);
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/netmap/pcap.c
--- a/head/tools/tools/netmap/pcap.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/tools/tools/netmap/pcap.c	Tue Apr 17 11:51:51 2012 +0300
@@ -7,7 +7,7 @@
  * This is not 100% complete but enough to let tcpdump, trafshow
  * and other apps work.
  *
- * $FreeBSD: head/tools/tools/netmap/pcap.c 232238 2012-02-27 19:05:01Z lu=
igi $
+ * $FreeBSD: head/tools/tools/netmap/pcap.c 233947 2012-04-06 14:26:05Z lu=
igi $
  */
=20
 #include <errno.h>
@@ -232,6 +232,7 @@
 	bzero(&req, sizeof(req));
 	strncpy(req.nr_name, me->nmr.nr_name, sizeof(req.nr_name));
 	req.nr_ringid =3D ringid;
+	req.nr_version =3D NETMAP_API;
 	err =3D ioctl(fd, NIOCGINFO, &req);
 	if (err) {
 		D("cannot get info on %s", me->nmr.nr_name);
diff -r 428842767fa6 -r f2935497fa04 head/tools/tools/vimage/vimage.8
--- a/head/tools/tools/vimage/vimage.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/tools/tools/vimage/vimage.8	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/tools/tools/vimage/vimage.8 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd August 25, 2009
 .Dt VIMAGE 8
@@ -82,7 +82,7 @@
 .Ss Invocation
 If invoked with no modifiers, the
 .Nm
-command spawns a new interactive shell in virtual image=20
+command spawns a new interactive shell in virtual image
 .Ar vname .
 If optional additional arguments following
 .Ar vname
@@ -106,7 +106,7 @@
 .Ar vname ,
 using the same syntax as with the -c form of the command.
 .It Fl d
-Delete the virtual image=20
+Delete the virtual image
 .Ar vname .
 No processes and/or sockets should exist in the target virtual image
 in order for the delete request to succeed.  Non-loopback interfaces
@@ -142,7 +142,7 @@
 is provided.
 .El
 .Sh EXAMPLES
-Create a new virtual image named=20
+Create a new virtual image named
 .So v1
 .Sc ,
 which is allowed to create and manage an own subhierarchy of vimages:
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/Makefile
--- a/head/usr.bin/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	From: @(#)Makefile	8.3 (Berkeley) 1/7/94
-# $FreeBSD: head/usr.bin/Makefile 230060 2012-01-13 15:40:49Z ed $
+# $FreeBSD: head/usr.bin/Makefile 233337 2012-03-23 03:16:35Z stas $
=20
 .include <bsd.own.mk>
=20
@@ -261,6 +261,10 @@
 SUBDIR+=3D	locate
 .endif
=20
+.if ${MK_KERBEROS_SUPPORT} !=3D "no"
+SUBDIR+=3D	compile_et
+.endif
+
 # XXX msgs?
 .if ${MK_MAIL} !=3D "no"
 SUBDIR+=3D	biff
@@ -317,7 +321,6 @@
 SUBDIR+=3D	ar
 SUBDIR+=3D	c89
 SUBDIR+=3D	c99
-SUBDIR+=3D	compile_et
 SUBDIR+=3D	ctags
 SUBDIR+=3D	file2c
 SUBDIR+=3D	gprof
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/bsdiff/bsdiff/bsdiff.1
--- a/head/usr.bin/bsdiff/bsdiff/bsdiff.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/bsdiff/bsdiff/bsdiff.1	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/bsdiff/bsdiff/bsdiff.1 233648 2012-03-29 05:02:=
12Z eadler $
 .\"
 .Dd May 18, 2003
 .Dt BSDIFF 1
@@ -72,7 +72,7 @@
 .Nm
 utility does not store the hashes of
 .Ar oldfile
-or=20
+or
 .Ar newfile
 in
 .Ar patchfile .
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/calendar/calendar.1
--- a/head/usr.bin/calendar/calendar.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/calendar/calendar.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)calendar.1  8.1 (Berkeley) 6/29/93
-.\" $FreeBSD: head/usr.bin/calendar/calendar.1 227370 2011-11-09 01:40:46Z=
 grog $
+.\" $FreeBSD: head/usr.bin/calendar/calendar.1 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd June 13, 2002
 .Dt CALENDAR 1
@@ -91,7 +91,7 @@
 as the default calendar file.
 .It Fl l Ar longitude
 Perform lunar and solar calculations from this longitude.
-If neither longitude nor UTC offset is specified, the calculations will=20
+If neither longitude nor UTC offset is specified, the calculations will
 be based on the difference between UTC time and localtime.
 If both are specified, UTC offset overrides longitude.
 .It Xo Fl t
@@ -105,7 +105,7 @@
 Perform lunar and solar calculations from this UTC offset.
 If neither UTC offset nor longitude is specified, the calculations
 will be based on the difference between UTC time and localtime.
-If both are specified, UTC offset overrides longitude.=20
+If both are specified, UTC offset overrides longitude.
 .It Fl W Ar num
 Print lines from today and the next
 .Ar num
@@ -113,7 +113,6 @@
 Ignore weekends when calculating the number of days.
 .El
 .Sh FILE FORMAT
-.Pp
 To handle calendars in your national code table you can specify
 .Dq LANG=3D<locale_name>
 in the calendar file as early as possible.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/calendar/calendars/calend=
ar.freebsd
--- a/head/usr.bin/calendar/calendars/calendar.freebsd	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/usr.bin/calendar/calendars/calendar.freebsd	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,7 +1,7 @@
 /*
  * FreeBSD
  *
- * $FreeBSD: head/usr.bin/calendar/calendars/calendar.freebsd 232353 2012-=
03-01 19:17:56Z davide $
+ * $FreeBSD: head/usr.bin/calendar/calendars/calendar.freebsd 234320 2012-=
04-15 17:28:47Z madpilot $
  */
=20
 #ifndef _calendar_freebsd_
@@ -126,6 +126,7 @@
 04/12	Ed Schouten <ed at FreeBSD.org> born in Oss, the Netherlands, 1986
 04/13	Oliver Braun <obraun at FreeBSD.org> born in Nuremberg, Bavaria, German=
y, 1972
 04/14	Crist J. Clark <cjc at FreeBSD.org> born in Milwaukee, Wisconsin, Unite=
d States, 1970
+04/14	Glen J. Barber <gjb at FreeBSD.org> born in Wilkes-Barre, Pennsylvania,=
 United States, 1981
 04/15	David Malone <dwmalone at FreeBSD.org> born in Dublin, Ireland, 1973
 04/17	Dryice Liu <dryice at FreeBSD.org> born in Jinan, Shandong, China, 1975
 04/22	Joerg Wunsch <joerg at FreeBSD.org> born in Dresden, Sachsen, Germany, =
1962
@@ -344,6 +345,7 @@
 12/22	Maxim Sobolev <sobomax at FreeBSD.org> born in Dnepropetrovsk, Ukraine,=
 1976
 12/23	Sean Chittenden <seanc at FreeBSD.org> born in Seattle, Washington, Uni=
ted States, 1979
 12/23	Alejandro Pulver <alepulver at FreeBSD.org> born in Buenos Aires, Argen=
tina, 1989
+12/24	Guido Falsi <madpilot at FreeBSD.org> born in Firenze, Italy, 1978
 12/28	Soren Schmidt <sos at FreeBSD.org> born in Maribo, Denmark, 1960
 12/28	Ade Lovett <ade at FreeBSD.org> born in London, England, 1969
 12/28	Marius Strobl <marius at FreeBSD.org> born in Cham, Bavaria, Germany, 1=
978
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/bugpoint/Makefile
--- a/head/usr.bin/clang/bugpoint/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/bugpoint/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.bin/clang/bugpoint/Makefile 231057 2012-02-05 23:56:2=
2Z dim $
+# $FreeBSD: head/usr.bin/clang/bugpoint/Makefile 234353 2012-04-16 21:23:2=
5Z dim $
=20
 PROG_CXX=3Dbugpoint
=20
@@ -19,6 +19,7 @@
 	llvmarchive \
 	llvmbitreader \
 	llvmipo \
+	llvmvectorize \
 	llvmscalaropts \
 	llvminstcombine \
 	llvminstrumentation \
@@ -27,6 +28,7 @@
 	llvmanalysis \
 	llvmtarget \
 	llvmmc \
+	llvmobject \
 	llvmasmparser \
 	llvmcore \
 	llvmsupport
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/bugpoint/bugpoint.1
--- a/head/usr.bin/clang/bugpoint/bugpoint.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/bugpoint/bugpoint.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/bugpoint/bugpoint.1 231057 2012-02-05 23:=
56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/bugpoint/bugpoint.1 234353 2012-04-16 21:=
23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "BUGPOINT 1"
-.TH BUGPOINT 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH BUGPOINT 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/clang/Makefile
--- a/head/usr.bin/clang/clang/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/clang/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.bin/clang/clang/Makefile 232322 2012-02-29 22:58:51Z =
dim $
+# $FreeBSD: head/usr.bin/clang/clang/Makefile 234353 2012-04-16 21:23:25Z =
dim $
=20
 .include <bsd.own.mk>
=20
@@ -44,32 +44,36 @@
 	clangindex \
 	clangarcmigrate \
 	clangrewrite \
+	clangedit \
 	clangast \
 	clanglex \
 	clangbasic \
+	llvmlinker \
+	llvmarchive \
 	llvmipo \
+	llvmvectorize \
 	llvminstrumentation \
 	llvmbitwriter \
 	llvmbitreader \
 	llvmasmparser \
+	llvmmipsasmparser \
+	llvmmipscodegen \
+	llvmmipsdesc \
+	llvmmipsinfo \
+	llvmmipsinstprinter \
 	llvmarmdisassembler \
 	llvmarmasmparser \
 	llvmarmcodegen \
 	llvmarmdesc \
+	llvmarminfo \
 	llvmarminstprinter \
-	llvmarminfo \
-	llvmmipscodegen \
-	llvmmipsdesc \
-	llvmmipsinstprinter \
-	llvmmipsinfo \
 	llvmpowerpccodegen \
 	llvmpowerpcdesc \
+	llvmpowerpcinfo \
 	llvmpowerpcinstprinter \
-	llvmpowerpcinfo \
+	llvmx86asmparser \
 	llvmx86disassembler \
-	llvmx86asmparser \
 	llvmx86codegen \
-	llvmx86desc \
 	llvmselectiondag \
 	llvmasmprinter \
 	llvmmcparser \
@@ -79,12 +83,14 @@
 	llvmtransformutils \
 	llvmipa \
 	llvmanalysis \
+	llvmx86desc \
+	llvmx86info \
 	llvmtarget \
 	llvmx86instprinter \
+	llvmmc \
+	llvmobject \
 	llvmx86utils \
 	llvmcore \
-	llvmx86info \
-	llvmmc \
 	llvmsupport
=20
 .include "../clang.prog.mk"
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/clang/clang.1
--- a/head/usr.bin/clang/clang/clang.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/clang/clang.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/clang/clang.1 226633 2011-10-22 14:08:43Z=
 dim $
+.\" $FreeBSD: head/usr.bin/clang/clang/clang.1 234353 2012-04-16 21:23:25Z=
 dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "CLANG 1"
-.TH CLANG 1 "2011-10-17" "clang 3.0" "Clang Tools Documentation"
+.TH CLANG 1 "2012-04-05" "clang 3.1" "Clang Tools Documentation"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
@@ -461,7 +461,7 @@
 .IP "\fB\-nostdlibinc\fR" 4
 .IX Item "-nostdlibinc"
 Do not search the standard system directories for include files, but do se=
arch
-compiler builting include directories.
+compiler builtin include directories.
 .IP "\fB\-nobuiltininc\fR" 4
 .IX Item "-nobuiltininc"
 Do not search clang's builtin directory for include files.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llc/llc.1
--- a/head/usr.bin/clang/llc/llc.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/llc/llc.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llc/llc.1 231057 2012-02-05 23:56:22Z dim=
 $
+.\" $FreeBSD: head/usr.bin/clang/llc/llc.1 234353 2012-04-16 21:23:25Z dim=
 $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLC 1"
-.TH LLC 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLC 1 "2012-04-06" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
@@ -167,7 +167,7 @@
 .IP "\fB\-O\fR=3D\fIuint\fR" 4
 .IX Item "-O=3Duint"
 Generate code at different optimization levels. These correspond to the \f=
I\-O0\fR,
-\&\fI\-O1\fR, \fI\-O2\fR, \fI\-O3\fR, and \fI\-O4\fR optimization levels u=
sed by \fBllvm-gcc\fR and
+\&\fI\-O1\fR, \fI\-O2\fR, and \fI\-O3\fR optimization levels used by \fBll=
vm-gcc\fR and
 \&\fBclang\fR.
 .IP "\fB\-mtriple\fR=3D\fItarget triple\fR" 4
 .IX Item "-mtriple=3Dtarget triple"
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/lli/Makefile
--- a/head/usr.bin/clang/lli/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/lli/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.bin/clang/lli/Makefile 231057 2012-02-05 23:56:22Z di=
m $
+# $FreeBSD: head/usr.bin/clang/lli/Makefile 234353 2012-04-16 21:23:25Z di=
m $
=20
 PROG_CXX=3Dlli
=20
@@ -25,10 +25,10 @@
 	llvmanalysis \
 	llvmmcjit \
 	llvmruntimedyld \
-	llvmobject \
 	llvmexecutionengine \
 	llvmtarget \
 	llvmmc \
+	llvmobject \
 	llvmcore \
 	llvmsupport
=20
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/lli/lli.1
--- a/head/usr.bin/clang/lli/lli.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/lli/lli.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/lli/lli.1 231057 2012-02-05 23:56:22Z dim=
 $
+.\" $FreeBSD: head/usr.bin/clang/lli/lli.1 234353 2012-04-16 21:23:25Z dim=
 $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLI 1"
-.TH LLI 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLI 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-ar/llvm-ar.1
--- a/head/usr.bin/clang/llvm-ar/llvm-ar.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/llvm-ar/llvm-ar.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-ar/llvm-ar.1 231057 2012-02-05 23:56=
:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-ar/llvm-ar.1 234353 2012-04-16 21:23=
:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-AR 1"
-.TH LLVM-AR 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-AR 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-as/llvm-as.1
--- a/head/usr.bin/clang/llvm-as/llvm-as.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/llvm-as/llvm-as.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-as/llvm-as.1 231057 2012-02-05 23:56=
:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-as/llvm-as.1 234353 2012-04-16 21:23=
:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-AS 1"
-.TH LLVM-AS 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-AS 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-bcanalyzer/llv=
m-bcanalyzer.1
--- a/head/usr.bin/clang/llvm-bcanalyzer/llvm-bcanalyzer.1	Tue Apr 17 11:36=
:47 2012 +0300
+++ b/head/usr.bin/clang/llvm-bcanalyzer/llvm-bcanalyzer.1	Tue Apr 17 11:51=
:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-bcanalyzer/llvm-bcanalyzer.1 231057 =
2012-02-05 23:56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-bcanalyzer/llvm-bcanalyzer.1 234353 =
2012-04-16 21:23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-BCANALYZER 1"
-.TH LLVM-BCANALYZER 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-BCANALYZER 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-diff/llvm-diff=
.1
--- a/head/usr.bin/clang/llvm-diff/llvm-diff.1	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/usr.bin/clang/llvm-diff/llvm-diff.1	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-diff/llvm-diff.1 231057 2012-02-05 2=
3:56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-diff/llvm-diff.1 234353 2012-04-16 2=
1:23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-DIFF 1"
-.TH LLVM-DIFF 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-DIFF 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-dis/llvm-dis.1
--- a/head/usr.bin/clang/llvm-dis/llvm-dis.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/llvm-dis/llvm-dis.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-dis/llvm-dis.1 231057 2012-02-05 23:=
56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-dis/llvm-dis.1 234353 2012-04-16 21:=
23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-DIS 1"
-.TH LLVM-DIS 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-DIS 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-extract/llvm-e=
xtract.1
--- a/head/usr.bin/clang/llvm-extract/llvm-extract.1	Tue Apr 17 11:36:47 20=
12 +0300
+++ b/head/usr.bin/clang/llvm-extract/llvm-extract.1	Tue Apr 17 11:51:51 20=
12 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-extract/llvm-extract.1 231057 2012-0=
2-05 23:56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-extract/llvm-extract.1 234353 2012-0=
4-16 21:23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-EXTRACT 1"
-.TH LLVM-EXTRACT 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-EXTRACT 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-ld/Makefile
--- a/head/usr.bin/clang/llvm-ld/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/llvm-ld/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.bin/clang/llvm-ld/Makefile 231057 2012-02-05 23:56:22=
Z dim $
+# $FreeBSD: head/usr.bin/clang/llvm-ld/Makefile 234353 2012-04-16 21:23:25=
Z dim $
=20
 PROG_CXX=3Dllvm-ld
=20
@@ -12,6 +12,7 @@
 	llvmarchive \
 	llvmbitreader \
 	llvmipo \
+	llvmvectorize \
 	llvmscalaropts \
 	llvminstcombine \
 	llvmtransformutils \
@@ -19,6 +20,7 @@
 	llvmanalysis \
 	llvmtarget \
 	llvmmc \
+	llvmobject \
 	llvmcore \
 	llvmsupport
=20
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-ld/llvm-ld.1
--- a/head/usr.bin/clang/llvm-ld/llvm-ld.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/llvm-ld/llvm-ld.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-ld/llvm-ld.1 231057 2012-02-05 23:56=
:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-ld/llvm-ld.1 234353 2012-04-16 21:23=
:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-LD 1"
-.TH LLVM-LD 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-LD 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-link/llvm-link=
.1
--- a/head/usr.bin/clang/llvm-link/llvm-link.1	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/usr.bin/clang/llvm-link/llvm-link.1	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-link/llvm-link.1 231057 2012-02-05 2=
3:56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-link/llvm-link.1 234353 2012-04-16 2=
1:23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-LINK 1"
-.TH LLVM-LINK 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-LINK 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-nm/llvm-nm.1
--- a/head/usr.bin/clang/llvm-nm/llvm-nm.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/llvm-nm/llvm-nm.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-nm/llvm-nm.1 231057 2012-02-05 23:56=
:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-nm/llvm-nm.1 234353 2012-04-16 21:23=
:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-NM 1"
-.TH LLVM-NM 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-NM 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-prof/llvm-prof=
.1
--- a/head/usr.bin/clang/llvm-prof/llvm-prof.1	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/usr.bin/clang/llvm-prof/llvm-prof.1	Tue Apr 17 11:51:51 2012 +03=
00
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-prof/llvm-prof.1 231057 2012-02-05 2=
3:56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-prof/llvm-prof.1 234353 2012-04-16 2=
1:23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-PROF 1"
-.TH LLVM-PROF 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-PROF 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/llvm-ranlib/llvm-ra=
nlib.1
--- a/head/usr.bin/clang/llvm-ranlib/llvm-ranlib.1	Tue Apr 17 11:36:47 2012=
 +0300
+++ b/head/usr.bin/clang/llvm-ranlib/llvm-ranlib.1	Tue Apr 17 11:51:51 2012=
 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/llvm-ranlib/llvm-ranlib.1 231057 2012-02-=
05 23:56:22Z dim $
+.\" $FreeBSD: head/usr.bin/clang/llvm-ranlib/llvm-ranlib.1 234353 2012-04-=
16 21:23:25Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "LLVM-RANLIB 1"
-.TH LLVM-RANLIB 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH LLVM-RANLIB 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/opt/Makefile
--- a/head/usr.bin/clang/opt/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/opt/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.bin/clang/opt/Makefile 231057 2012-02-05 23:56:22Z di=
m $
+# $FreeBSD: head/usr.bin/clang/opt/Makefile 234353 2012-04-16 21:23:25Z di=
m $
=20
 PROG_CXX=3Dopt
=20
@@ -10,6 +10,7 @@
=20
 TGHDRS=3D	Intrinsics
 LIBDEPS=3Dllvmipo \
+	llvmvectorize \
 	llvmscalaropts \
 	llvminstcombine \
 	llvminstrumentation \
@@ -18,6 +19,7 @@
 	llvmanalysis \
 	llvmtarget \
 	llvmmc \
+	llvmobject \
 	llvmasmparser \
 	llvmbitwriter \
 	llvmbitreader \
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/opt/opt.1
--- a/head/usr.bin/clang/opt/opt.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/opt/opt.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/opt/opt.1 231057 2012-02-05 23:56:22Z dim=
 $
+.\" $FreeBSD: head/usr.bin/clang/opt/opt.1 234353 2012-04-16 21:23:25Z dim=
 $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "OPT 1"
-.TH OPT 1 "2011-10-17" "LLVM 3.0" "LLVM Command Guide"
+.TH OPT 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/tblgen/Makefile
--- a/head/usr.bin/clang/tblgen/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/tblgen/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,10 +1,9 @@
-# $FreeBSD: head/usr.bin/clang/tblgen/Makefile 226633 2011-10-22 14:08:43Z=
 dim $
+# $FreeBSD: head/usr.bin/clang/tblgen/Makefile 234353 2012-04-16 21:23:25Z=
 dim $
=20
 PROG_CXX=3Dtblgen
=20
 SRCDIR=3D	utils/TableGen
-SRCS=3D	ARMDecoderEmitter.cpp \
-	AsmMatcherEmitter.cpp \
+SRCS=3D	AsmMatcherEmitter.cpp \
 	AsmWriterEmitter.cpp \
 	AsmWriterInst.cpp \
 	CallingConvEmitter.cpp \
@@ -18,11 +17,11 @@
 	DAGISelMatcherEmitter.cpp \
 	DAGISelMatcherGen.cpp \
 	DAGISelMatcherOpt.cpp \
+	DFAPacketizerEmitter.cpp \
 	DisassemblerEmitter.cpp \
 	EDEmitter.cpp \
 	FastISelEmitter.cpp \
 	FixedLenDecoderEmitter.cpp \
-	InstrEnumEmitter.cpp \
 	InstrInfoEmitter.cpp \
 	IntrinsicEmitter.cpp \
 	PseudoLoweringEmitter.cpp \
@@ -33,6 +32,7 @@
 	TGValueTypes.cpp \
 	TableGen.cpp \
 	X86DisassemblerTables.cpp \
+	X86ModRMFilters.cpp \
 	X86RecognizableInstr.cpp
 LLVM_REQUIRES_EH=3D
=20
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/clang/tblgen/tblgen.1
--- a/head/usr.bin/clang/tblgen/tblgen.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/clang/tblgen/tblgen.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/clang/tblgen/tblgen.1 221347 2011-05-02 21:10:1=
3Z dim $
+.\" $FreeBSD: head/usr.bin/clang/tblgen/tblgen.1 234353 2012-04-16 21:23:2=
5Z dim $
 .\" Automatically generated by Pod::Man 2.23 (Pod::Simple 3.14)
 .\"
 .\" Standard preamble:
@@ -125,7 +125,7 @@
 .\" =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
 .\"
 .IX Title "TBLGEN 1"
-.TH TBLGEN 1 "2011-04-23" "LLVM 3.0" "LLVM Command Guide"
+.TH TBLGEN 1 "2012-04-05" "LLVM 3.1" "LLVM Command Guide"
 .\" For nroff, turn off justification.  Always turn off hyphenation; it ma=
kes
 .\" way too many mistakes in technical documents.
 .if n .ad l
@@ -161,6 +161,9 @@
 Specify where to find other target description files for inclusion. The
 \&\fIdirectory\fR value should be a full or partial path to a directory th=
at contains
 target description files.
+.IP "\fB\-asmparsernum\fR \fIN\fR" 4
+.IX Item "-asmparsernum N"
+Make \-gen\-asm\-parser emit assembly writer number \fIN\fR.
 .IP "\fB\-asmwriternum\fR \fIN\fR" 4
 .IX Item "-asmwriternum N"
 Make \-gen\-asm\-writer emit assembly writer number \fIN\fR.
@@ -173,36 +176,51 @@
 .IP "\fB\-print\-enums\fR" 4
 .IX Item "-print-enums"
 Print enumeration values for a class
+.IP "\fB\-print\-sets\fR" 4
+.IX Item "-print-sets"
+Print expanded sets for testing \s-1DAG\s0 exprs.
 .IP "\fB\-gen\-emitter\fR" 4
 .IX Item "-gen-emitter"
 Generate machine code emitter.
-.IP "\fB\-gen\-register\-enums\fR" 4
-.IX Item "-gen-register-enums"
-Generate the enumeration values for all registers.
-.IP "\fB\-gen\-register\-desc\fR" 4
-.IX Item "-gen-register-desc"
-Generate a register info description for each register.
-.IP "\fB\-gen\-register\-desc\-header\fR" 4
-.IX Item "-gen-register-desc-header"
-Generate a register info description header for each register.
-.IP "\fB\-gen\-instr\-enums\fR" 4
-.IX Item "-gen-instr-enums"
-Generate enumeration values for instructions.
-.IP "\fB\-gen\-instr\-desc\fR" 4
-.IX Item "-gen-instr-desc"
+.IP "\fB\-gen\-register\-info\fR" 4
+.IX Item "-gen-register-info"
+Generate registers and register classes info.
+.IP "\fB\-gen\-instr\-info\fR" 4
+.IX Item "-gen-instr-info"
 Generate instruction descriptions.
 .IP "\fB\-gen\-asm\-writer\fR" 4
 .IX Item "-gen-asm-writer"
 Generate the assembly writer.
+.IP "\fB\-gen\-disassembler\fR" 4
+.IX Item "-gen-disassembler"
+Generate disassembler.
+.IP "\fB\-gen\-pseudo\-lowering\fR" 4
+.IX Item "-gen-pseudo-lowering"
+Generate pseudo instruction lowering.
 .IP "\fB\-gen\-dag\-isel\fR" 4
 .IX Item "-gen-dag-isel"
 Generate a \s-1DAG\s0 (Directed Acycle Graph) instruction selector.
+.IP "\fB\-gen\-asm\-matcher\fR" 4
+.IX Item "-gen-asm-matcher"
+Generate assembly instruction matcher.
+.IP "\fB\-gen\-dfa\-packetizer\fR" 4
+.IX Item "-gen-dfa-packetizer"
+Generate \s-1DFA\s0 Packetizer for \s-1VLIW\s0 targets.
+.IP "\fB\-gen\-fast\-isel\fR" 4
+.IX Item "-gen-fast-isel"
+Generate a \*(L"fast\*(R" instruction selector.
 .IP "\fB\-gen\-subtarget\fR" 4
 .IX Item "-gen-subtarget"
 Generate subtarget enumerations.
 .IP "\fB\-gen\-intrinsic\fR" 4
 .IX Item "-gen-intrinsic"
 Generate intrinsic information.
+.IP "\fB\-gen\-tgt\-intrinsic\fR" 4
+.IX Item "-gen-tgt-intrinsic"
+Generate target intrinsic information.
+.IP "\fB\-gen\-enhanced\-disassembly\-info\fR" 4
+.IX Item "-gen-enhanced-disassembly-info"
+Generate enhanced disassembly info.
 .IP "\fB\-version\fR" 4
 .IX Item "-version"
 Show the version number of this program.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/comm/comm.1
--- a/head/usr.bin/comm/comm.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/comm/comm.1	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)comm.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD: head/usr.bin/comm/comm.1 227589 2011-11-16 22:02:59Z imp $
+.\" $FreeBSD: head/usr.bin/comm/comm.1 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd December 12, 2009
 .Dt COMM 1
@@ -61,7 +61,7 @@
 The following options are available:
 .Bl -tag -width indent
 .It Fl 1
-Suppress printing of column 1, lines only in=20
+Suppress printing of column 1, lines only in
 .Ar file1 .
 .It Fl 2
 Suppress printing of column 2, lines only in
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/compile_et/Makefile
--- a/head/usr.bin/compile_et/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/compile_et/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,9 +1,13 @@
-# $FreeBSD$
+# $FreeBSD: head/usr.bin/compile_et/Makefile 233294 2012-03-22 08:48:42Z s=
tas $
=20
 .PATH: ${.CURDIR}/../../contrib/com_err
=20
+LIBVERS=3D	${.OBJDIR}/../../kerberos5/lib/libvers/libvers.a
+
 PROG=3D	compile_et
-SRCS=3D	compile_et.c parse.y lex.l getarg.c
+SRCS=3D	compile_et.c parse.y lex.l
+LDADD=3D	-lroken ${LIBVERS}
+DPADD=3D	${LIBROKEN} ${LIBVERS}
 CFLAGS+=3D-I. -I${.CURDIR}/../../contrib/com_err
=20
 WARNS?=3D	0
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/csup/cpasswd.1
--- a/head/usr.bin/csup/cpasswd.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/csup/cpasswd.1	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
 .\" $Id: cvpasswd.1,v 1.4 2003/03/04 18:24:42 jdp Exp $
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/csup/cpasswd.1 233648 2012-03-29 05:02:12Z eadl=
er $
 .\"
 .Dd June 27, 2007
 .Dt CPASSWD 1
@@ -52,7 +52,7 @@
 names, e.g.,
 .Ql BillyJoe at FreeBSD.org .
 Client names are case-insensitive.
-.Pp=20
+.Pp
 .Ar ServerName
 is the name of the
 .Nm CVSup
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/csup/csup.1
--- a/head/usr.bin/csup/csup.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/csup/csup.1	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
 .\" $Id: cvsup.1,v 1.70 2003/03/04 18:23:46 jdp Exp $
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/csup/csup.1 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd February 1, 2006
 .Dt CSUP 1
@@ -649,9 +649,9 @@
 If
 .Ql Makefile
 from that directory is not required then the line
-.Pp=20
+.Pp
 .Bl -item -compact -offset indent
-.It=20
+.It
 .Pa doc/Makefile
 .El
 .Pp
@@ -662,8 +662,8 @@
 .Bl -item -compact -offset indent
 .It
 .Pa doc/Makefile*
-.El=20
-.Pp=20
+.El
+.Pp
 which will match whether
 .Ql Makefile
 is an RCS file or not.
@@ -679,7 +679,7 @@
 .Pa doc/ru*
 .It
 .Pa doc/zh*
-.El=20
+.El
 .Pp
 As many as three refuse files are examined for each
 .Ar supfile
@@ -710,7 +710,7 @@
 .Ar base
 and
 .Ar sup
-for=20
+for
 .Ar collDir
 but it is possible to override both of these. The value of
 .Ar base
@@ -720,11 +720,11 @@
 .Ar base=3Dpathname
 entry in the
 .Ar supfile .
-(If both are used the=20
+(If both are used the
 .Fl b
 option will override the
 .Ar supfile
-entry.)  The value of=20
+entry.)  The value of
 .Ar collDir
 can only be changed with the
 .Fl c
@@ -779,11 +779,11 @@
 .Pp
 .Bl -item -compact -offset indent
 .It
-.Pa /bar/sup/refuse               =20
+.Pa /bar/sup/refuse
 .It
-.Pa /bar/sup/src-all/refuse               =20
+.Pa /bar/sup/src-all/refuse
 .It
-.Pa /bar/sup/src-all/refuse.cvs:RELENG_3               =20
+.Pa /bar/sup/src-all/refuse.cvs:RELENG_3
 .El
 .Pp
 and with
@@ -794,7 +794,7 @@
 .Bl -item -compact -offset indent
 .It
 .Pa /bar/stool/refuse
-.It=20
+.It
 .Pa /bar/stool/src-all/refuse
 .It
 .Pa /bar/stool/src-all/refuse.cvs:RELENG_3
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/find/find.1
--- a/head/usr.bin/find/find.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/find/find.1	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)find.1	8.7 (Berkeley) 5/9/95
-.\" $FreeBSD: head/usr.bin/find/find.1 225847 2011-09-28 18:53:36Z ed $
+.\" $FreeBSD: head/usr.bin/find/find.1 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd September 28, 2011
 .Dt FIND 1
@@ -177,7 +177,6 @@
 primary.
 .El
 .Sh PRIMARIES
-.Pp
 All primaries which take a numeric argument allow the number to be
 preceded by a plus sign
 .Pq Dq Li +
@@ -302,7 +301,7 @@
 .Ic -atime
 primary description for information on supported time units.
 .It Ic -d
-Same as=20
+Same as
 .Ic depth .
 GNU find implements this as a primary in mistaken emulation of
 .Fx
@@ -451,12 +450,12 @@
 mounted read-only.
 .It Ic -gid Ar gname
 The same thing as
-.Ar -group Ar gname=20
+.Ar -group Ar gname
 for compatibility with GNU find.
 GNU find imposes a restriction that
-.Ar gname=20
+.Ar gname
 is numeric, while
-.Xr find 1=20
+.Xr find 1
 does not.
 .It Ic -group Ar gname
 True if the file belongs to the group
@@ -489,7 +488,7 @@
 .Ic -regex ,
 but the match is case insensitive.
 .It Ic -iwholename Ar pattern
-The same thing as=20
+The same thing as
 .Ic -ipath ,
 for GNU find compatibility.
 .It Ic -links Ar n
@@ -545,7 +544,7 @@
 Same as
 .Ic -newer .
 .It Ic -mount
-The same thing as=20
+The same thing as
 .Ic -xdev ,
 for GNU find compatibility.
 .It Ic -mtime Ar n Ns Op Cm smhdw
@@ -618,7 +617,7 @@
 This option is for GNU find compatibility and is ignored.
 .It Ic -noleaf
 This option is for GNU find compatibility.
-In GNU find it disables an optimization not relevant to=20
+In GNU find it disables an optimization not relevant to
 .Xr find 1 ,
 so it is ignored.
 .It Ic -nouser
@@ -754,7 +753,7 @@
 If the command option
 .Ic -L
 is specified, it is also true if the file is a symbolic link and
-points to=20
+points to
 .Ar name .
 .It Ic -size Ar n Ns Op Cm ckMGTP
 True if the file's size, rounded up, in 512-byte blocks is
@@ -807,12 +806,12 @@
 .El
 .It Ic -uid Ar uname
 The same thing as
-.Ar -user Ar uname=20
+.Ar -user Ar uname
 for compatibility with GNU find.
 GNU find imposes a restriction that
-.Ar uname=20
+.Ar uname
 is numeric, while
-.Xr find 1=20
+.Xr find 1
 does not.
 .It Ic -user Ar uname
 True if the file belongs to the user
@@ -823,7 +822,7 @@
 .Ar uname
 is treated as a user ID.
 .It Ic -wholename Ar pattern
-The same thing as=20
+The same thing as
 .Ic -path ,
 for GNU find compatibility.
 .El
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/fstat/fstat.c
--- a/head/usr.bin/fstat/fstat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/fstat/fstat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/fstat/fstat.c 232233 2012-02-27 17:39:34Z=
 pluknet $");
+__FBSDID("$FreeBSD: head/usr.bin/fstat/fstat.c 233760 2012-04-01 18:22:48Z=
 jhb $");
=20
 #include <sys/param.h>
 #include <sys/user.h>
@@ -84,6 +84,8 @@
     struct filestat *fst);
 static void	print_pts_info(struct procstat *procstat,
     struct filestat *fst);
+static void	print_shm_info(struct procstat *procstat,
+    struct filestat *fst);
 static void	print_socket_info(struct procstat *procstat,
     struct filestat *fst);
 static void	print_vnode_info(struct procstat *procstat,
@@ -289,6 +291,9 @@
 	case PS_FST_TYPE_PTS:
 		print_pts_info(procstat, fst);
 		break;
+	case PS_FST_TYPE_SHM:
+		print_shm_info(procstat, fst);
+		break;
 	default:=09
 		if (vflg)
 			fprintf(stderr,
@@ -419,6 +424,30 @@
 }
=20
 static void
+print_shm_info(struct procstat *procstat, struct filestat *fst)
+{
+	struct shmstat shm;
+	char errbuf[_POSIX2_LINE_MAX];
+	char mode[15];
+	int error;
+
+	error =3D procstat_get_shm_info(procstat, fst, &shm, errbuf);
+	if (error !=3D 0) {
+		printf("* error");
+		return;
+	}
+	if (nflg) {
+		printf("             ");
+		(void)snprintf(mode, sizeof(mode), "%o", shm.mode);
+	} else {
+		printf(" %-15s", fst->fs_path !=3D NULL ? fst->fs_path : "-");
+		strmode(shm.mode, mode);
+	}
+	printf(" %10s %6ju", mode, shm.size);
+	print_access_flags(fst->fs_fflags);
+}
+
+static void
 print_vnode_info(struct procstat *procstat, struct filestat *fst)
 {
 	struct vnstat vn;
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/fstat/fuser.1
--- a/head/usr.bin/fstat/fuser.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/fstat/fuser.1	Tue Apr 17 11:51:51 2012 +0300
@@ -22,14 +22,14 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.bin/fstat/fuser.1 222600 2011-06-02 09:56:53Z uqs $
+.\" $FreeBSD: head/usr.bin/fstat/fuser.1 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd May 13, 2011
 .Dt FUSER 1
 .Os
 .Sh NAME
 .Nm fuser
-.Nd list IDs of all processes that have one or more files open=20
+.Nd list IDs of all processes that have one or more files open
 .Sh SYNOPSIS
 .Nm
 .Op Fl cfkmu
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/hexdump/hexdump.1
--- a/head/usr.bin/hexdump/hexdump.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/hexdump/hexdump.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)hexdump.1	8.2 (Berkeley) 4/18/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/hexdump/hexdump.1 233992 2012-04-07 09:05:30Z j=
oel $
 .\"
 .Dd February 18, 2010
 .Dt HEXDUMP 1
@@ -200,14 +200,14 @@
 described in the C standard are supported:
 .Bd -ragged -offset indent -compact
 .Bl -column <alert_character>
-.It "NUL	\e0
-.It "<alert character>	\ea
-.It "<backspace>	\eb
-.It "<form-feed>	\ef
-.It "<newline>	\en
-.It "<carriage return>	\er
-.It "<tab>	\et
-.It "<vertical tab>	\ev
+.It "NUL	\e0"
+.It "<alert character>	\ea"
+.It "<backspace>	\eb"
+.It "<form-feed>	\ef"
+.It "<newline>	\en"
+.It "<carriage return>	\er"
+.It "<tab>	\et"
+.It "<vertical tab>	\ev"
 .El
 .Ed
 .El
@@ -248,13 +248,13 @@
 displayed using the following, lower-case, names.
 Characters greater than 0xff, hexadecimal, are displayed as hexadecimal
 strings.
-.Bl -column \&000_nu \&001_so \&002_st \&003_et \&004_eo
-.It "\&000\ NUL\t001\ SOH\t002\ STX\t003\ ETX\t004\ EOT\t005\ ENQ
-.It "\&006\ ACK\t007\ BEL\t008\ BS\t009\ HT\t00A\ LF\t00B\ VT
-.It "\&00C\ FF\t00D\ CR\t00E\ SO\t00F\ SI\t010\ DLE\t011\ DC1
-.It "\&012\ DC2\t013\ DC3\t014\ DC4\t015\ NAK\t016\ SYN\t017\ ETB
-.It "\&018\ CAN\t019\ EM\t01A\ SUB\t01B\ ESC\t01C\ FS\t01D\ GS
-.It "\&01E\ RS\t01F\ US\t07F\ DEL
+.Bl -column 000_nu 001_so 002_st 003_et 004_eo
+.It "000 NUL" Ta "001 SOH" Ta "002 STX" Ta "003 ETX" Ta "004 EOT" Ta "005 =
ENQ"
+.It "006 ACK" Ta "007 BEL" Ta "008 BS" Ta "009 HT" Ta "00A LF" Ta "00B VT"
+.It "00C FF" Ta "00D CR" Ta "00E\ SO" Ta "00F SI" Ta "010 DLE" Ta "011 DC1"
+.It "012 DC2" Ta "013 DC3" Ta "014 DC4" Ta "015\ NAK" Ta "016 SYN" Ta "017=
 ETB"
+.It "018 CAN" Ta "019 EM" Ta "01A SUB" Ta "01B ESC" Ta "01C FS" Ta "01D GS"
+.It "01E RS" Ta "01F US" Ta "07F DEL" Ta \& Ta \& Ta \&
 .El
 .El
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/hexdump/od.1
--- a/head/usr.bin/hexdump/od.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/hexdump/od.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)od.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD: head/usr.bin/hexdump/od.1 228823 2011-12-23 00:29:01Z gjb $
+.\" $FreeBSD: head/usr.bin/hexdump/od.1 233992 2012-04-07 09:05:30Z joel $
 .\"
 .Dd December 22, 2011
 .Dt OD 1
@@ -151,7 +151,7 @@
 .It "00C FF	00D CR	00E SO	00F SI	010 DLE	011 DC1"
 .It "012 DC2	013 DC3	014 DC4	015 NAK	016 SYN	017 ETB"
 .It "018 CAN	019 EM	01A SUB	01B ESC	01C FS	01D GS"
-.It "01E RS	01F US	020 SP	07F DEL"
+.It "01E RS	01F US	020 SP	07F DEL	\&	\&"
 .El
 .It Cm c
 Characters in the default character set.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/indent/indent.1
--- a/head/usr.bin/indent/indent.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/indent/indent.1	Tue Apr 17 11:51:51 2012 +0300
@@ -32,7 +32,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)indent.1	8.1 (Berkeley) 7/1/93
-.\" $FreeBSD: head/usr.bin/indent/indent.1 232471 2012-03-03 18:07:53Z ead=
ler $
+.\" $FreeBSD: head/usr.bin/indent/indent.1 233456 2012-03-25 09:19:25Z joe=
l $
 .\"
 .Dd March 3, 2012
 .Dt INDENT 1
@@ -488,7 +488,6 @@
 utility fits as many words (separated by blanks, tabs, or newlines) on a
 line as possible.
 Blank lines break paragraphs.
-.Pp
 .Ss Comment indentation
 If a comment is on a line with code it is started in the `comment column',
 which is set by the
@@ -504,7 +503,6 @@
 If the code on a line extends past the comment
 column, the comment starts further to the right, and the right margin may =
be
 automatically extended in extreme cases.
-.Pp
 .Ss Preprocessor lines
 In general,
 .Nm
@@ -519,7 +517,6 @@
 .Nm
 attempts to correctly
 compensate for the syntactic peculiarities introduced.
-.Pp
 .Ss C syntax
 The
 .Nm
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/ipcrm/ipcrm.1
--- a/head/usr.bin/ipcrm/ipcrm.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/ipcrm/ipcrm.1	Tue Apr 17 11:51:51 2012 +0300
@@ -21,7 +21,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/ipcrm/ipcrm.1 233648 2012-03-29 05:02:12Z eadle=
r $
 .\""
 .Dd December 12, 2007
 .Dt IPCRM 1
@@ -114,6 +114,6 @@
 The wiping of all System V IPC objects was first implemented in
 .Fx 6.4 and 7.1.
 .Sh AUTHORS
-The original author was Adam Glass.=20
+The original author was Adam Glass.
 The wiping of all System V IPC objects was thought up by Callum
 Gibson and extended and implemented by Edwin Groothuis.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/jot/jot.1
--- a/head/usr.bin/jot/jot.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/jot/jot.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)jot.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/jot/jot.1 233456 2012-03-25 09:19:25Z joel $
 .\"
 .Dd June 2, 2010
 .Dt JOT 1
@@ -242,7 +242,6 @@
 .Bd -literal -offset indent
 $ jot -w %d 6 1 10 0.5
 .Ed
-.Pp
 .Sh EXIT STATUS
 .Ex -std
 .Sh EXAMPLES
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/kdump/Makefile
--- a/head/usr.bin/kdump/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/kdump/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	@(#)Makefile	8.1 (Berkeley) 6/6/93
-# $FreeBSD: head/usr.bin/kdump/Makefile 226608 2011-10-21 11:08:25Z des $
+# $FreeBSD: head/usr.bin/kdump/Makefile 234058 2012-04-09 14:47:18Z dim $
=20
 .if (${MACHINE_ARCH} =3D=3D "amd64")
 SFX=3D		32
@@ -21,7 +21,7 @@
 CLEANFILES=3D	ioctl.c kdump_subr.c kdump_subr.h linux_syscalls.c
=20
 ioctl.c: mkioctls
-	env MACHINE=3D${MACHINE} \
+	env MACHINE=3D${MACHINE} CPP=3D"${CPP}" \
 	    sh ${.CURDIR}/mkioctls print ${DESTDIR}/usr/include > ${.TARGET}
=20
 kdump_subr.h: mksubr
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/kdump/kdump.1
--- a/head/usr.bin/kdump/kdump.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/kdump/kdump.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,9 +26,9 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)kdump.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/kdump/kdump.1 233925 2012-04-05 17:13:14Z jhb $
 .\"
-.Dd February 23, 2008
+.Dd April 5, 2012
 .Dt KDUMP 1
 .Os
 .Sh NAME
@@ -171,6 +171,8 @@
 .It Li USER Ta data from user process Ta the data
 .It Li STRU Ta various syscalls Ta structure
 .It Li SCTL Ta Xr sysctl 3 requests Ta MIB name
+.It Li PFLT Ta enter page fault Ta fault address and type
+.It Li PRET Ta return from page fault Ta fault result
 .El
 .Sh SEE ALSO
 .Xr ktrace 1
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/kdump/kdump.c
--- a/head/usr.bin/kdump/kdump.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/kdump/kdump.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
 #endif
 #endif /* not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/kdump/kdump.c 232128 2012-02-24 20:12:53Z=
 jhb $");
+__FBSDID("$FreeBSD: head/usr.bin/kdump/kdump.c 233925 2012-04-05 17:13:14Z=
 jhb $");
=20
 #define _KERNEL
 extern int errno;
@@ -102,6 +102,8 @@
 void ktrstat(struct stat *);
 void ktrstruct(char *, size_t);
 void ktrcapfail(struct ktr_cap_fail *);
+void ktrfault(struct ktr_fault *);
+void ktrfaultend(struct ktr_faultend *);
 void usage(void);
 void ioctlname(unsigned long, int);
=20
@@ -306,6 +308,13 @@
 			break;
 		case KTR_CAPFAIL:
 			ktrcapfail((struct ktr_cap_fail *)m);
+			break;
+		case KTR_FAULT:
+			ktrfault((struct ktr_fault *)m);
+			break;
+		case KTR_FAULTEND:
+			ktrfaultend((struct ktr_faultend *)m);
+			break;
 		default:
 			printf("\n");
 			break;
@@ -448,6 +457,12 @@
 	case KTR_CAPFAIL:
 		type =3D "CAP ";
 		break;
+	case KTR_FAULT:
+		type =3D "PFLT";
+		break;
+	case KTR_FAULTEND:
+		type =3D "PRET";
+		break;
 	default:
 		sprintf(unknown, "UNKNOWN(%d)", kth->ktr_type);
 		type =3D unknown;
@@ -1631,6 +1646,24 @@
 		capname((intmax_t)ktr->cap_held);
 		break;
 	}
+	printf("\n");
+}
+
+void
+ktrfault(struct ktr_fault *ktr)
+{
+
+	printf("0x%jx ", ktr->vaddr);
+	vmprotname(ktr->type);
+	printf("\n");
+}
+
+void
+ktrfaultend(struct ktr_faultend *ktr)
+{
+
+	vmresultname(ktr->result);
+	printf("\n");
 }
=20
 #if defined(__amd64__) || defined(__i386__)
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/kdump/mkioctls
--- a/head/usr.bin/kdump/mkioctls	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/kdump/mkioctls	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# $FreeBSD: head/usr.bin/kdump/mkioctls 226608 2011-10-21 11:08:25Z des $
+# $FreeBSD: head/usr.bin/kdump/mkioctls 234058 2012-04-09 14:47:18Z dim $
 #
 # When editing this script, keep in mind that truss also uses it.
 #
@@ -38,7 +38,7 @@
 esac
=20
 awk -v x=3D"$ioctl_includes" 'BEGIN {print x}' |
-	gcc -E -I$1 -dM -DCOMPAT_43TTY - |
+	$CPP -I$1 -dM -DCOMPAT_43TTY - |
 	awk -v ioctl_includes=3D"$ioctl_includes" -v style=3D"$style" '
 BEGIN {
 	print "/* XXX obnoxious prerequisites. */"
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/kdump/mksubr
--- a/head/usr.bin/kdump/mksubr	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/kdump/mksubr	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 # SUCH DAMAGE.
 #
-# $FreeBSD: head/usr.bin/kdump/mksubr 232072 2012-02-23 21:08:21Z jhb $
+# $FreeBSD: head/usr.bin/kdump/mksubr 233925 2012-04-05 17:13:14Z jhb $
 #
 # Generates kdump_subr.c
 # mkioctls is a special-purpose script, and works fine as it is
@@ -187,6 +187,8 @@
 #include <nfsserver/nfs.h>
 #include <ufs/ufs/quota.h>
 #include <sys/capability.h>
+#include <vm/vm.h>
+#include <vm/vm_param.h>
=20
 #include "kdump_subr.h"
=20
@@ -334,6 +336,26 @@
 	}
 }
=20
+/*
+ * MANUAL
+ *
+ * Used for page fault type.  Cannot use auto_or_type since the macro
+ * values contain a cast.  Also, VM_PROT_NONE has to be handled specially.
+ */
+void
+vmprotname (int type)
+{
+	int	or =3D 0;
+
+	if (type =3D=3D VM_PROT_NONE) {
+		(void)printf("VM_PROT_NONE");
+		return;
+	}
+	if_print_or(type, VM_PROT_READ, or);
+	if_print_or(type, VM_PROT_WRITE, or);
+	if_print_or(type, VM_PROT_EXECUTE, or);
+	if_print_or(type, VM_PROT_COPY, or);
+}
 _EOF_
=20
 auto_or_type     "accessmodename"      "[A-Z]_OK[[:space:]]+0?x?[0-9A-Fa-f=
]+"         "sys/unistd.h"
@@ -373,6 +395,7 @@
 auto_switch_type "sockoptname"         "SO_[A-Z]+[[:space:]]+0x[0-9]+"    =
            "sys/socket.h"
 auto_switch_type "socktypename"        "SOCK_[A-Z]+[[:space:]]+[1-9]+[0-9]=
*"          "sys/socket.h"
 auto_or_type     "thrcreateflagsname"  "THR_[A-Z]+[[:space:]]+0x[0-9]+"   =
            "sys/thr.h"
+auto_switch_type "vmresultname"        "KERN_[A-Z]+[[:space:]]+[0-9]+"    =
            "vm/vm_param.h"
 auto_or_type     "wait4optname"        "W[A-Z]+[[:space:]]+[0-9]+"        =
            "sys/wait.h"
 auto_switch_type "whencename"          "SEEK_[A-Z]+[[:space:]]+[0-9]+"    =
            "sys/unistd.h"
=20
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/killall/killall.1
--- a/head/usr.bin/killall/killall.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/killall/killall.1	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/killall/killall.1 233510 2012-03-26 15:18:14Z j=
oel $
 .\"
 .Dd December 25, 2009
 .Dt KILLALL 1
@@ -118,7 +118,7 @@
 So use
 .Xr kill 1
 for this job (e.g.\&
-.Dq Li "kill -TERM -1
+.Dq Li "kill -TERM -1"
 or as root
 .Dq Li "echo kill -TERM -1 | su -m <user>" ) .
 .Sh IMPLEMENTATION NOTES
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/ktrace/ktrace.1
--- a/head/usr.bin/ktrace/ktrace.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/ktrace/ktrace.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,9 +26,9 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)ktrace.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD: head/usr.bin/ktrace/ktrace.1 226269 2011-10-11 20:37:10Z des=
 $
+.\" $FreeBSD: head/usr.bin/ktrace/ktrace.1 233925 2012-04-05 17:13:14Z jhb=
 $
 .\"
-.Dd October 10, 2011
+.Dd April 5, 2012
 .Dt KTRACE 1
 .Os
 .Sh NAME
@@ -108,6 +108,8 @@
 .Bl -tag -width flag -compact
 .It Cm c
 trace system calls
+.It Cm f
+trace page faults
 .It Cm i
 trace
 .Tn I/O
@@ -129,7 +131,7 @@
 requests
 .It Cm +
 trace the default set of trace points -
-.Cm c , i , n , p , s , t , u , y
+.Cm c , f , i , n , p , s , t , u , y
 .El
 .It Ar command
 Execute
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/ktrace/ktrace.h
--- a/head/usr.bin/ktrace/ktrace.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/ktrace/ktrace.h	Tue Apr 17 11:51:51 2012 +0300
@@ -27,12 +27,13 @@
  * SUCH DAMAGE.
  *
  *	@(#)ktrace.h	8.1 (Berkeley) 6/6/93
- * $FreeBSD: head/usr.bin/ktrace/ktrace.h 226269 2011-10-11 20:37:10Z des $
+ * $FreeBSD: head/usr.bin/ktrace/ktrace.h 233925 2012-04-05 17:13:14Z jhb $
  */
=20
 #define DEF_POINTS (KTRFAC_SYSCALL | KTRFAC_SYSRET | KTRFAC_NAMEI | \
 		    KTRFAC_GENIO | KTRFAC_PSIG | KTRFAC_USER | \
-		    KTRFAC_STRUCT | KTRFAC_SYSCTL | KTRFAC_CAPFAIL)
+		    KTRFAC_STRUCT | KTRFAC_SYSCTL | KTRFAC_CAPFAIL | \
+		    KTRFAC_FAULT | KTRFAC_FAULTEND)
=20
 #define PROC_ABI_POINTS (KTRFAC_PROCCTOR | KTRFAC_PROCDTOR)
=20
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/ktrace/subr.c
--- a/head/usr.bin/ktrace/subr.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/ktrace/subr.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
 #endif
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/ktrace/subr.c 226269 2011-10-11 20:37:10Z=
 des $");
+__FBSDID("$FreeBSD: head/usr.bin/ktrace/subr.c 233925 2012-04-05 17:13:14Z=
 jhb $");
=20
 #include <sys/param.h>
 #include <sys/file.h>
@@ -64,6 +64,9 @@
 		case 'i':
 			facs |=3D KTRFAC_GENIO;
 			break;
+		case 'f':
+			facs |=3D KTRFAC_FAULT | KTRFAC_FAULTEND;
+			break;
 		case 'n':
 			facs |=3D KTRFAC_NAMEI;
 			break;
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/lex/flex.skl
--- a/head/usr.bin/lex/flex.skl	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/lex/flex.skl	Tue Apr 17 11:51:51 2012 +0300
@@ -2,7 +2,7 @@
=20
 /* Scanner skeleton version:
  * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48=
 vern Exp $
- * $FreeBSD$
+ * $FreeBSD: head/usr.bin/lex/flex.skl 234101 2012-04-10 15:29:28Z schweik=
h $
  */
=20
 #if defined(__FreeBSD__)
@@ -122,7 +122,7 @@
 #define EOB_ACT_LAST_MATCH 2
=20
 /* The funky do-while in the following #define is used to turn the definit=
ion
- * int a single C statement (which needs a semi-colon terminator).  This
+ * into a single C statement (which needs a semi-colon terminator).  This
  * avoids problems with code like:
  *
  * 	if ( condition_holds )
@@ -143,12 +143,12 @@
 		/* Undo effects of setting up yytext. */ \
 		*yy_cp =3D yy_hold_char; \
 		YY_RESTORE_YY_MORE_OFFSET \
-		yy_c_buf_p =3D yy_cp =3D yy_bp + n - YY_MORE_ADJ; \
+		yy_c_buf_p =3D yy_cp =3D yy_bp + (n) - YY_MORE_ADJ; \
 		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
 		} \
 	while ( 0 )
=20
-#define unput(c) yyunput( c, yytext_ptr )
+#define unput(c) yyunput( (c), yytext_ptr )
=20
 /* The following is because we cannot portably get our hands on size_t
  * (without autoconf's help, which isn't available because we want
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/locale/locale.1
--- a/head/usr.bin/locale/locale.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/locale/locale.1	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/locale/locale.1 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd November 1, 2005
 .Dt LOCALE 1
@@ -35,11 +35,11 @@
 .Nm
 .Op Fl a | m
 .Nm
-.Fl k=20
+.Fl k
 .Ic list
 .Op Ar prefix
 .Nm
-.Op Fl ck=20
+.Op Fl ck
 .Ar keyword ...
 .Sh DESCRIPTION
 The
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/lockf/lockf.1
--- a/head/usr.bin/lockf/lockf.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/lockf/lockf.1	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/lockf/lockf.1 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd July 7, 1998
 .Dt LOCKF 1
@@ -139,7 +139,7 @@
 .Xr fork 2 )
 failed unexpectedly.
 .It Dv EX_SOFTWARE
-The=20
+The
 .Ar command
 did not exit normally,
 but may have been signaled or stopped.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/m4/eval.c
--- a/head/usr.bin/m4/eval.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/m4/eval.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/m4/eval.c 228701 2011-12-19 08:50:17Z bz =
$");
+__FBSDID("$FreeBSD: head/usr.bin/m4/eval.c 234310 2012-04-15 13:25:51Z bap=
t $");
=20
=20
 /*
@@ -269,10 +269,11 @@
 	case INCLTYPE:
 		if (argc > 2)
 			if (!doincl(argv[2])) {
-				if (mimic_gnu)=20
+				if (mimic_gnu) {
 					warn("%s at line %lu: include(%s)",
 					    CURRENT_NAME, CURRENT_LINE, argv[2]);
-				else
+					exit_code =3D 1;
+				} else
 					err(1, "%s at line %lu: include(%s)",
 					    CURRENT_NAME, CURRENT_LINE, argv[2]);
 			}
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/m4/extern.h
--- a/head/usr.bin/m4/extern.h	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/m4/extern.h	Tue Apr 17 11:51:51 2012 +0300
@@ -33,7 +33,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)extern.h	8.1 (Berkeley) 6/6/93
- * $FreeBSD: head/usr.bin/m4/extern.h 228063 2011-11-28 13:32:39Z bapt $
+ * $FreeBSD: head/usr.bin/m4/extern.h 234310 2012-04-15 13:25:51Z bapt $
  */
=20
 /* eval.c */
@@ -87,6 +87,7 @@
 /* main.c */
 extern void outputstr(const char *);
 extern void do_emit_synchline(void);
+extern int exit_code;
 #define emit_synchline() do { if (synch_lines) do_emit_synchline(); } whil=
e(0)
=20
 /* misc.c */
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/m4/main.c
--- a/head/usr.bin/m4/main.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/m4/main.c	Tue Apr 17 11:51:51 2012 +0300
@@ -39,7 +39,7 @@
  * by: oz
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/m4/main.c 228063 2011-11-28 13:32:39Z bap=
t $");
+__FBSDID("$FreeBSD: head/usr.bin/m4/main.c 234310 2012-04-15 13:25:51Z bap=
t $");
=20
 #include <assert.h>
 #include <signal.h>
@@ -164,6 +164,8 @@
=20
 int main(int, char *[]);
=20
+int exit_code =3D 0;
+
 int
 main(int argc, char *argv[])
 {
@@ -282,7 +284,7 @@
 		(void) fclose(outfile[0]);
 	}
=20
-	return 0;
+	return exit_code;
 }
=20
 /*
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/man/man.conf.5
--- a/head/usr.bin/man/man.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/man/man.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -23,11 +23,11 @@
 .\"  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\"  SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.bin/man/man.conf.5 222650 2011-06-03 13:45:11Z ru $
+.\" $FreeBSD: head/usr.bin/man/man.conf.5 233520 2012-03-26 19:23:57Z joel=
 $
 .\"
 .Dd June 3, 2011
+.Dt MAN.CONF 5
 .Os
-.Dt MAN.CONF 5
 .Sh NAME
 .Nm man.conf
 .Nd
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/ministat/ministat.1
--- a/head/usr.bin/ministat/ministat.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/ministat/ministat.1	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/ministat/ministat.1 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
 .Dd June 28, 2010
 .Dt MINISTAT 1
@@ -119,12 +119,12 @@
 .Sh HISTORY
 The
 .Nm
-command was written by Poul-Henning Kamp out of frustration=20
+command was written by Poul-Henning Kamp out of frustration
 over all the bogus benchmark claims made by people with no
 understanding of the importance of uncertainty and statistics.
 .Pp
 From
-.Fx 5.2=20
+.Fx 5.2
 it has lived in the source tree as a developer tool, graduating
 to the installed system from
 .Fx 8.0 .
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/mkulzma/mkulzma.8
--- a/head/usr.bin/mkulzma/mkulzma.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/mkulzma/mkulzma.8	Tue Apr 17 11:51:51 2012 +0300
@@ -7,10 +7,10 @@
 .\" this stuff is worth it, you can buy me a beer in return.       Maxim S=
obolev
 .\" ----------------------------------------------------------------------=
------
 .\"
-.\" $FreeBSD: head/usr.bin/mkulzma/mkulzma.8 229538 2012-01-04 23:45:10Z r=
ay $
+.\" $FreeBSD: head/usr.bin/mkulzma/mkulzma.8 233473 2012-03-25 19:34:05Z j=
oel $
 .\"
 .Dd March 17, 2006
-.Dt mkulzma 8
+.Dt MKULZMA 8
 .Os
 .Sh NAME
 .Nm mkulzma
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/netstat/if.c
--- a/head/usr.bin/netstat/if.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/netstat/if.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
 #endif
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/netstat/if.c 229909 2012-01-10 02:58:36Z =
eadler $");
+__FBSDID("$FreeBSD: head/usr.bin/netstat/if.c 233863 2012-04-04 08:30:32Z =
glebius $");
=20
 #include <sys/types.h>
 #include <sys/protosw.h>
@@ -93,10 +93,10 @@
 	if (live) {
 		if (zflag)
 			memset(&zerostat, 0, len);
-		if (sysctlbyname("net.inet.pfsync.stats", &pfsyncstat, &len,
+		if (sysctlbyname("net.pfsync.stats", &pfsyncstat, &len,
 		    zflag ? &zerostat : NULL, zflag ? len : 0) < 0) {
 			if (errno !=3D ENOENT)
-				warn("sysctl: net.inet.pfsync.stats");
+				warn("sysctl: net.pfsync.stats");
 			return;
 		}
 	} else
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/netstat/inet.c
--- a/head/usr.bin/netstat/inet.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/netstat/inet.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
 #endif
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/netstat/inet.c 229403 2012-01-03 18:51:58=
Z ed $");
+__FBSDID("$FreeBSD: head/usr.bin/netstat/inet.c 234245 2012-04-13 22:35:53=
Z delphij $");
=20
 #include <sys/param.h>
 #include <sys/queue.h>
@@ -1068,7 +1068,7 @@
  * Dump IGMP statistics structure (pre 8.x kernel).
  */
 static void
-igmp_stats_live_old(u_long off, const char *name)
+igmp_stats_live_old(const char *name)
 {
 	struct oigmpstat oigmpstat, zerostat;
 	size_t len =3D sizeof(oigmpstat);
@@ -1128,7 +1128,7 @@
 			return;
 		}
 		if (len < sizeof(igmpstat)) {
-			igmp_stats_live_old(off, name);
+			igmp_stats_live_old(name);
 			return;
 		}
 	}
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/printf/printf.1
--- a/head/usr.bin/printf/printf.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/printf/printf.1	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)printf.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD: head/usr.bin/printf/printf.1 222421 2011-05-28 14:32:47Z jil=
les $
+.\" $FreeBSD: head/usr.bin/printf/printf.1 233648 2012-03-29 05:02:12Z ead=
ler $
 .\"
 .Dd May 28, 2011
 .Dt PRINTF 1
@@ -344,7 +344,7 @@
 .Nm
 to interpret the dash as a program argument.
 .Nm --
-must be used before=20
+must be used before
 .Ar format .
 .Pp
 If the locale contains multibyte characters
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/procstat/procstat.1
--- a/head/usr.bin/procstat/procstat.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/procstat/procstat.1	Tue Apr 17 11:51:51 2012 +0300
@@ -23,9 +23,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.bin/procstat/procstat.1 232300 2012-02-29 15:06:40Z=
 pluknet $
+.\" $FreeBSD: head/usr.bin/procstat/procstat.1 233648 2012-03-29 05:02:12Z=
 eadler $
 .\"
-.Dd February 29, 2012
+.Dd March 23, 2012
 .Dt PROCSTAT 1
 .Os
 .Sh NAME
@@ -54,7 +54,7 @@
 .Bl -tag -width indent
 .It Fl b
 Display binary information for the process.
-.It Fl c=20
+.It Fl c
 Display command line arguments for the process.
 .It Fl e
 Display environment variables for the process.
@@ -110,6 +110,8 @@
 process ID
 .It COMM
 command
+.It OSREL
+osreldate for process binary
 .It PATH
 path to process binary (if available)
 .El
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/procstat/procstat_bin.c
--- a/head/usr.bin/procstat/procstat_bin.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/procstat/procstat_bin.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.bin/procstat/procstat_bin.c 221807 2011-05-12 10:11:=
39Z stas $
+ * $FreeBSD: head/usr.bin/procstat/procstat_bin.c 233390 2012-03-23 20:09:=
21Z trociny $
  */
=20
 #include <sys/param.h>
@@ -43,11 +43,11 @@
 procstat_bin(struct kinfo_proc *kipp)
 {
 	char pathname[PATH_MAX];
-	int error, name[4];
+	int error, osrel, name[4];
 	size_t len;
=20
 	if (!hflag)
-		printf("%5s %-16s %-53s\n", "PID", "COMM", "PATH");
+		printf("%5s %-16s %8s %s\n", "PID", "COMM", "OSREL", "PATH");
=20
 	name[0] =3D CTL_KERN;
 	name[1] =3D KERN_PROC;
@@ -65,7 +65,19 @@
 	if (len =3D=3D 0 || strlen(pathname) =3D=3D 0)
 		strcpy(pathname, "-");
=20
+	name[2] =3D KERN_PROC_OSREL;
+
+	len =3D sizeof(osrel);
+	error =3D sysctl(name, 4, &osrel, &len, NULL, 0);
+	if (error < 0 && errno !=3D ESRCH) {
+		warn("sysctl: kern.proc.osrel: %d", kipp->ki_pid);
+		return;
+	}
+	if (error < 0)
+		return;
+
 	printf("%5d ", kipp->ki_pid);
 	printf("%-16s ", kipp->ki_comm);
+	printf("%8d ", osrel);
 	printf("%s\n", pathname);
 }
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/procstat/procstat_files.c
--- a/head/usr.bin/procstat/procstat_files.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/procstat/procstat_files.c	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.bin/procstat/procstat_files.c 224859 2011-08-14 00:4=
2:09Z rwatson $
+ * $FreeBSD: head/usr.bin/procstat/procstat_files.c 233760 2012-04-01 18:2=
2:48Z jhb $
  */
=20
 #include <sys/param.h>
@@ -440,13 +440,6 @@
 			printf(" ");
 		}
 		switch (fst->fs_type) {
-		case PS_FST_TYPE_VNODE:
-		case PS_FST_TYPE_FIFO:
-		case PS_FST_TYPE_PTS:
-			printf("%-3s ", "-");
-			printf("%-18s", fst->fs_path !=3D NULL ? fst->fs_path : "-");
-			break;
-
 		case PS_FST_TYPE_SOCKET:
 			error =3D procstat_get_socket_info(procstat, fst, &sock, NULL);
 			if (error !=3D 0)
@@ -477,7 +470,8 @@
 			break;
=20
 		default:
-			printf("%-18s", "-");
+			printf("%-3s ", "-");
+			printf("%-18s", fst->fs_path !=3D NULL ? fst->fs_path : "-");
 		}
=20
 		printf("\n");
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/rctl/rctl.8
--- a/head/usr.bin/rctl/rctl.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/rctl/rctl.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF=
 THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.bin/rctl/rctl.8 232329 2012-03-01 10:21:10Z trasz $
+.\" $FreeBSD: head/usr.bin/rctl/rctl.8 233667 2012-03-29 16:07:22Z joel $
 .\"
 .Dd March 1, 2012
 .Dt RCTL 8
@@ -119,36 +119,34 @@
 A filter that matches all the login classes would be "loginclass:".
 A filter that matches all defined rules for maxproc resource would be
 "::maxproc".
-.Pp
 .Sh RESOURCES
 .Bl -column -offset 3n "pseudoterminals"
-.It "cputime		CPU time, in seconds"
-.It "datasize		data size, in bytes"
-.It "stacksize		stack size, in bytes"
-.It "coredumpsize	core dump size, in bytes"
-.It "memoryuse		resident set size, in bytes"
-.It "memorylocked	locked memory, in bytes"
-.It "maxproc		number of processes"
-.It "openfiles		file descriptor table size"
-.It "vmemoryuse		address space limit, in bytes"
-.It "pseudoterminals	number of PTYs"
-.It "swapuse		swap usage, in bytes"
-.It "nthr		number of threads"
-.It "msgqqueued		number of queued SysV messages"
-.It "msgqsize		SysV message queue size, in bytes"
-.It "nmsgq		number of SysV message queues"
-.It "nsem		number of SysV semaphores"
-.It "nsemop		number of SysV semaphores modified in a single semop(2) call"
-.It "nshm		number of SysV shared memory segments"
-.It "shmsize		SysV shared memory size, in bytes"
-.It "wallclock		wallclock time, in seconds"
+.It cputime Ta "CPU time, in seconds"
+.It datasize Ta "data size, in bytes"
+.It stacksize Ta "stack size, in bytes"
+.It coredumpsize Ta "core dump size, in bytes"
+.It memoryuse Ta "resident set size, in bytes"
+.It memorylocked Ta "locked memory, in bytes"
+.It maxproc Ta "number of processes"
+.It openfiles Ta "file descriptor table size"
+.It vmemoryuse Ta "address space limit, in bytes"
+.It pseudoterminals Ta "number of PTYs"
+.It swapuse Ta "swap usage, in bytes"
+.It nthr Ta "number of threads"
+.It msgqqueued Ta "number of queued SysV messages"
+.It msgqsize Ta "SysV message queue size, in bytes"
+.It nmsgq Ta "number of SysV message queues"
+.It nsem Ta "number of SysV semaphores"
+.It nsemop Ta "number of SysV semaphores modified in a single semop(2) cal=
l"
+.It nshm Ta "number of SysV shared memory segments"
+.It shmsize Ta "SysV shared memory size, in bytes"
+.It wallclock Ta "wallclock time, in seconds"
 .El
-.Pp
 .Sh ACTIONS
 .Bl -column -offset 3n "pseudoterminals"
-.It "deny	deny the allocation; not supported for cpu and wallclock"
-.It "log		log a warning to the console"
-.It "devctl	send notification to"
+.It deny Ta "deny the allocation; not supported for cpu and wallclock"
+.It log Ta "log a warning to the console"
+.It devctl Ta "send notification to"
 .Xr devd 8
 .It "sig*	e.g. sigterm; send a signal to the offending process"
 .El
@@ -162,7 +160,6 @@
 in error.
 .Pp
 Note that limiting RSS may kill the machine due to thrashing.
-.Pp
 .Sh EXIT STATUS
 .Ex -std
 .Sh EXAMPLES
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/sed/sed.1
--- a/head/usr.bin/sed/sed.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/sed/sed.1	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)sed.1	8.2 (Berkeley) 12/30/93
-.\" $FreeBSD: head/usr.bin/sed/sed.1 226895 2011-10-29 06:13:47Z ache $
+.\" $FreeBSD: head/usr.bin/sed/sed.1 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd May 24, 2009
 .Dt SED 1
@@ -146,7 +146,7 @@
 option suppresses this behavior.
 .It Fl r
 Same as
-.Fl E=20
+.Fl E
 for compatibility with GNU sed.
 .El
 .Pp
@@ -195,7 +195,7 @@
 .It
 a context address
 that consists of a regular expression preceded and followed by a
-delimiter. The closing delimiter can also optionally be followed by the=20
+delimiter. The closing delimiter can also optionally be followed by the
 .Dq I
 character, to indicate that the regular expression is to be matched
 in a case-insensitive way.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/setchannel/setchannel.1
--- a/head/usr.bin/setchannel/setchannel.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/setchannel/setchannel.1	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\" $Id: cxm.4,v 1.1 2004/10/16 00:12:35 mavetju Exp $
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/setchannel/setchannel.1 233456 2012-03-25 09:19=
:25Z joel $
 .\"
 .Dd November 30, 2006
 .Dt PVR250-SETCHANNEL 1
@@ -33,7 +33,6 @@
 .Nd Hauppage PVR250/350 channel selector
 .Sh SYNOPSIS
 .Cd pvr250-setchannel [-a {on | off}] [-c | -r | -s | -t] [-g geom] [-m ch=
annel_set] [channel | freq]
-.Pp
 .Sh DESCRIPTION
 .Nm
 provides support for selecting channels on Hauppauge WinTV cards,
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/tftp/tftp.1
--- a/head/usr.bin/tftp/tftp.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/tftp/tftp.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)tftp.1	8.2 (Berkeley) 4/18/94
-.\" $FreeBSD: head/usr.bin/tftp/tftp.1 223491 2011-06-24 05:41:38Z rodrigc=
 $
+.\" $FreeBSD: head/usr.bin/tftp/tftp.1 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd June 22, 2011
 .Dt TFTP 1
@@ -83,7 +83,7 @@
 to
 .Ar [size] .
 Values are restricted to powers of 2 between 8 and 32768.  This is a
-non-standard TFTP option.=20
+non-standard TFTP option.
 .Pp
 .It Cm connect Ar host Op Ar port
 Set the
@@ -109,7 +109,7 @@
 commands.
 .Pp
 .It Cm debug Ar level
-Enable or disable debugging levels during verbose output.  The value of=20
+Enable or disable debugging levels during verbose output.  The value of
 .Ar level
 can be one of
 .Cm packet, simple, options,
@@ -186,7 +186,7 @@
 .Cm off
 (disable RFC 2347 options), and
 .Cm extra
-(toggle support for non-RFC defined options).  =20
+(toggle support for non-RFC defined options).
 .Pp
 .It Cm quit
 Exit
@@ -222,24 +222,19 @@
 .Pp
 The following RFC's are supported:
 .Rs
-RFC 1350
-.%T The TFTP Protocol (Revision 2)
+.%T RFC 1350: The TFTP Protocol (Revision 2)
 .Re
 .Rs
-RFC 2347
-.%T TFTP Option Extension
+.%T RFC 2347: TFTP Option Extension
 .Re
 .Rs
-RFC 2348
-.%T TFTP Blocksize Option
+.%T RFC 2348: TFTP Blocksize Option
 .Re
 .Rs
-RFC 2349
-.%T TFTP Timeout Interval and Transfer Size Options
+.%T RFC 2349: TFTP Timeout Interval and Transfer Size Options
 .Re
 .Rs
-RFC 3617
-.%T Uniform Resource Identifier (URI) Scheme and Applicability Statement f=
or the Trivial File Transfer Protocol (TFTP)=20
+.%T RFC 3617: Uniform Resource Identifier (URI) Scheme and Applicability S=
tatement for the Trivial File Transfer Protocol (TFTP)
 .Re
 .Pp
 The non-standard
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/top/top.local.1
--- a/head/usr.bin/top/top.local.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/top/top.local.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/top/top.local.1 222532 2011-05-31 15:41:10Z jhb=
 $=20
+.\" $FreeBSD: head/usr.bin/top/top.local.1 233648 2012-03-29 05:02:12Z ead=
ler $
 .SH "FreeBSD NOTES"
=20
 .SH DESCRIPTION OF MEMORY
@@ -33,20 +33,20 @@
 .B Buf:
 number of bytes used for BIO-level disk caching
 .TP
-.B Free:=20
+.B Free:
 number of bytes free
 .TP
-.B Total:=20
+.B Total:
 total available swap usage
-.TP=20
-.B Free:=20
+.TP
+.B Free:
 total free swap usage
-.TP=20
-.B Inuse:=20
+.TP
+.B Inuse:
 swap usage
-.TP=20
-.B In:=20
+.TP
+.B In:
 bytes paged in from swap devices (last interval)
 .TP
-.B Out:=20
+.B Out:
 bytes paged out to swap devices (last interval)
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/touch/touch.1
--- a/head/usr.bin/touch/touch.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/touch/touch.1	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)touch.1	8.3 (Berkeley) 4/28/95
-.\" $FreeBSD: head/usr.bin/touch/touch.1 230979 2012-02-04 13:37:31Z jh $
+.\" $FreeBSD: head/usr.bin/touch/touch.1 233648 2012-03-29 05:02:12Z eadle=
r $
 .\"
 .Dd February 4, 2012
 .Dt TOUCH 1
@@ -51,27 +51,27 @@
 If any file does not exist, it is created with default permissions.
 .Pp
 By default,
-.Nm=20
+.Nm
 changes both modification and access times.  The
 .Fl a
-and=20
+and
 .Fl m
 flags may be used to select the access time or the modification time
 individually.
 Selecting both is equivalent to the default.
 By default, the timestamps are set to the current time.
-The=20
+The
 .Fl t
 flag explicitly specifies a different time, and the
 .Fl r
 flag specifies to set the times those of the specified file.
-The=20
+The
 .Fl A
 flag adjusts the values by a specified amount.
 .Pp
 The following options are available:
 .Bl -tag -width Ds
-.It Fl A=20
+.It Fl A
 Adjust the access and modification time stamps for the file by the
 specified value.
 This flag is intended for use in modifying files with incorrectly set
@@ -95,7 +95,7 @@
 .Pp
 The
 .Fl A
-flag implies the=20
+flag implies the
 .Fl c
 flag: if any file specified does not exist, it will be silently ignored.
 .It Fl a
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/tr/tr.1
--- a/head/usr.bin/tr/tr.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/tr/tr.1	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)tr.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/tr/tr.1 233510 2012-03-26 15:18:14Z joel $
 .\"
 .Dd October 13, 2006
 .Dt TR 1
@@ -145,15 +145,14 @@
 .It \echaracter
 A backslash followed by certain special characters maps to special
 values.
-.Pp
 .Bl -column "\ea"
-.It "\ea	<alert character>
-.It "\eb	<backspace>
-.It "\ef	<form-feed>
-.It "\en	<newline>
-.It "\er	<carriage return>
-.It "\et	<tab>
-.It "\ev	<vertical tab>
+.It "\ea	<alert character>"
+.It "\eb	<backspace>"
+.It "\ef	<form-feed>"
+.It "\en	<newline>"
+.It "\er	<carriage return>"
+.It "\et	<tab>"
+.It "\ev	<vertical tab>"
 .El
 .Pp
 A backslash followed by any other character maps to that character.
@@ -177,24 +176,23 @@
 .It [:class:]
 Represents all characters belonging to the defined character class.
 Class names are:
-.Pp
 .Bl -column "phonogram"
-.It "alnum	<alphanumeric characters>
-.It "alpha	<alphabetic characters>
-.It "blank	<whitespace characters>
-.It "cntrl	<control characters>
-.It "digit	<numeric characters>
-.It "graph	<graphic characters>
-.It "ideogram	<ideographic characters>
-.It "lower	<lower-case alphabetic characters>
-.It "phonogram	<phonographic characters>
-.It "print	<printable characters>
-.It "punct	<punctuation characters>
-.It "rune	<valid characters>
-.It "space	<space characters>
-.It "special	<special characters>
-.It "upper	<upper-case characters>
-.It "xdigit	<hexadecimal characters>
+.It "alnum	<alphanumeric characters>"
+.It "alpha	<alphabetic characters>"
+.It "blank	<whitespace characters>"
+.It "cntrl	<control characters>"
+.It "digit	<numeric characters>"
+.It "graph	<graphic characters>"
+.It "ideogram	<ideographic characters>"
+.It "lower	<lower-case alphabetic characters>"
+.It "phonogram	<phonographic characters>"
+.It "print	<printable characters>"
+.It "punct	<punctuation characters>"
+.It "rune	<valid characters>"
+.It "space	<space characters>"
+.It "special	<special characters>"
+.It "upper	<upper-case characters>"
+.It "xdigit	<hexadecimal characters>"
 .El
 .Pp
 .\" All classes may be used in
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/truss/Makefile
--- a/head/usr.bin/truss/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/truss/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.bin/truss/Makefile 226608 2011-10-21 11:08:25Z des $
+# $FreeBSD: head/usr.bin/truss/Makefile 234060 2012-04-09 15:34:22Z dim $
=20
 NO_WERROR=3D
 PROG=3D	truss
@@ -23,7 +23,7 @@
 		${.CURDIR}/i386.conf
=20
 ioctl.c: ${.CURDIR}/../kdump/mkioctls
-	env MACHINE=3D${MACHINE} \
+	env MACHINE=3D${MACHINE} CPP=3D"${CPP}" \
 		/bin/sh ${.CURDIR}/../kdump/mkioctls return ${DESTDIR}/usr/include > ${.=
TARGET}
=20
 .if ${MACHINE_CPUARCH} =3D=3D "i386"
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/unifdef/unifdef.1
--- a/head/usr.bin/unifdef/unifdef.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/unifdef/unifdef.1	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/unifdef/unifdef.1 233456 2012-03-25 09:19:25Z j=
oel $
 .\"
 .Dd March 11, 2010
 .Dt UNIFDEF 1
@@ -164,7 +164,6 @@
 .Nm
 with appropriate arguments to process the file.
 .Sh OPTIONS
-.Pp
 .Bl -tag -width indent -compact
 .It Fl D Ns Ar sym Ns =3D Ns Ar val
 Specify that a symbol is defined to a given value
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/units/units.1
--- a/head/usr.bin/units/units.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/units/units.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.bin/units/units.1 225596 2011-09-15 19:52:43Z dwmal=
one $
+.\" $FreeBSD: head/usr.bin/units/units.1 233510 2012-03-26 15:18:14Z joel $
 .Dd July 14, 1993
 .Dt UNITS 1
 .Os
@@ -95,15 +95,15 @@
 Some constants of nature included are:
 .Pp
 .Bl -column -offset indent -compact "mercury"
-.It "pi	ratio of circumference to diameter
-.It "c	speed of light
-.It "e	charge on an electron
-.It "g	acceleration of gravity
-.It "force	same as g
-.It "mole	Avogadro's number
-.It "water	pressure per unit height of water
-.It "mercury	pressure per unit height of mercury
-.It "au	astronomical unit
+.It "pi	ratio of circumference to diameter"
+.It "c	speed of light"
+.It "e	charge on an electron"
+.It "g	acceleration of gravity"
+.It "force	same as g"
+.It "mole	Avogadro's number"
+.It "water	pressure per unit height of water"
+.It "mercury	pressure per unit height of mercury"
+.It "au	astronomical unit"
 .El
 .Pp
 The unit 'pound' is a unit of mass.
@@ -148,14 +148,14 @@
 units.
 .Pp
 .Bl -column -offset indent -compact "minute"
-.It "m	!a!
-.It "sec	!b!
-.It "micro-	1e-6
-.It "minute	60 sec
-.It "hour	60 min
-.It "inch	0.0254 m
-.It "ft	12 inches
-.It "mile	5280 ft
+.It "m	!a!"
+.It "sec	!b!"
+.It "micro-	1e-6"
+.It "minute	60 sec"
+.It "hour	60 min"
+.It "inch	0.0254 m"
+.It "ft	12 inches"
+.It "mile	5280 ft"
 .El
 .Sh FILES
 .Bl -tag -width /usr/share/misc/units.lib -compact
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/unzip/unzip.1
--- a/head/usr.bin/unzip/unzip.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/unzip/unzip.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 .\"-
-.\" Copyright (c) 2007-2008 Dag-Erling Co=C3=AFdan Sm=C3=B8rgrav
+.\" Copyright (c) 2007-2008 Dag-Erling Sm=C3=B8rgrav
 .\" All rights reserved.
 .\"
 .\" Redistribution and use in source and binary forms, with or without
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.bin/unzip/unzip.1 228991 2011-12-30 10:59:15Z uqs $
+.\" $FreeBSD: head/usr.bin/unzip/unzip.1 234311 2012-04-15 13:39:39Z des $
 .\"
 .Dd October 21, 2010
 .Dt UNZIP 1
@@ -38,7 +38,6 @@
 .Ar zipfile
 .Sh DESCRIPTION
 .\" ...
-.Pp
 The following options are available:
 .Bl -tag -width Fl
 .It Fl a
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/unzip/unzip.c
--- a/head/usr.bin/unzip/unzip.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/unzip/unzip.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
 /*-
  * Copyright (c) 2009 Joerg Sonnenberger <joerg at NetBSD.org>
- * Copyright (c) 2007-2008 Dag-Erling Co=C3=AFdan Sm=C3=B8rgrav
+ * Copyright (c) 2007-2008 Dag-Erling Sm=C3=B8rgrav
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.bin/unzip/unzip.c 230044 2012-01-13 06:51:15Z kevlo $
+ * $FreeBSD: head/usr.bin/unzip/unzip.c 234311 2012-04-15 13:39:39Z des $
  *
  * This file would be much shorter if we didn't care about command-line
  * compatibility with Info-ZIP's UnZip, which requires us to duplicate
@@ -65,6 +65,7 @@
 static int		 t_opt;		/* test */
 static int		 u_opt;		/* update */
 static int		 v_opt;		/* verbose/list */
+static int		 Z1_opt;	/* zipinfo mode list files only */
=20
 /* time when unzip started */
 static time_t		 now;
@@ -72,6 +73,9 @@
 /* debug flag */
 static int		 unzip_debug;
=20
+/* zipinfo mode */
+static int		 zipinfo_mode;
+
 /* running on tty? */
 static int		 tty;
=20
@@ -802,17 +806,22 @@
 	mtime =3D archive_entry_mtime(e);
 	strftime(buf, sizeof(buf), "%m-%d-%g %R", localtime(&mtime));
=20
-	if (v_opt =3D=3D 1) {
-		printf(" %8ju  %s   %s\n",
-		    (uintmax_t)archive_entry_size(e),
-		    buf, archive_entry_pathname(e));
-	} else if (v_opt =3D=3D 2) {
-		printf("%8ju  Stored  %7ju   0%%  %s  %08x  %s\n",
-		    (uintmax_t)archive_entry_size(e),
-		    (uintmax_t)archive_entry_size(e),
-		    buf,
-		    0U,
-		    archive_entry_pathname(e));
+	if (!zipinfo_mode) {
+		if (v_opt =3D=3D 1) {
+			printf(" %8ju  %s   %s\n",
+			    (uintmax_t)archive_entry_size(e),
+			    buf, archive_entry_pathname(e));
+		} else if (v_opt =3D=3D 2) {
+			printf("%8ju  Stored  %7ju   0%%  %s  %08x  %s\n",
+			    (uintmax_t)archive_entry_size(e),
+			    (uintmax_t)archive_entry_size(e),
+			    buf,
+			    0U,
+			    archive_entry_pathname(e));
+		}
+	} else {
+		if (Z1_opt)
+			printf("%s\n",archive_entry_pathname(e));
 	}
 	ac(archive_read_data_skip(a));
 }
@@ -870,14 +879,16 @@
 	ac(archive_read_support_format_zip(a));
 	ac(archive_read_open_fd(a, fd, 8192));
=20
-	if (!p_opt && !q_opt)
-		printf("Archive:  %s\n", fn);
-	if (v_opt =3D=3D 1) {
-		printf("  Length     Date   Time    Name\n");
-		printf(" --------    ----   ----    ----\n");
-	} else if (v_opt =3D=3D 2) {
-		printf(" Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n=
");
-		printf("--------  ------  ------- -----   ----   ----   ------    ----\n=
");
+	if (!zipinfo_mode) {
+		if (!p_opt && !q_opt)
+			printf("Archive:  %s\n", fn);
+		if (v_opt =3D=3D 1) {
+			printf("  Length     Date   Time    Name\n");
+			printf(" --------    ----   ----    ----\n");
+		} else if (v_opt =3D=3D 2) {
+			printf(" Length   Method    Size  Ratio   Date   Time   CRC-32    Name\=
n");
+			printf("--------  ------  ------- -----   ----   ----   ------    ----\=
n");
+		}
 	}
=20
 	total_size =3D 0;
@@ -888,28 +899,35 @@
 		if (ret =3D=3D ARCHIVE_EOF)
 			break;
 		ac(ret);
-		if (t_opt)
-			error_count +=3D test(a, e);
-		else if (v_opt)
-			list(a, e);
-		else if (p_opt || c_opt)
-			extract_stdout(a, e);
-		else
-			extract(a, e);
+		if (!zipinfo_mode) {
+			if (t_opt)
+				error_count +=3D test(a, e);
+			else if (v_opt)
+				list(a, e);
+			else if (p_opt || c_opt)
+				extract_stdout(a, e);
+			else
+				extract(a, e);
+		} else {
+			if (Z1_opt)
+				list(a, e);
+		}
=20
 		total_size +=3D archive_entry_size(e);
 		++file_count;
 	}
=20
-	if (v_opt =3D=3D 1) {
-		printf(" --------                   -------\n");
-		printf(" %8ju                   %ju file%s\n",
-		    total_size, file_count, file_count !=3D 1 ? "s" : "");
-	} else if (v_opt =3D=3D 2) {
-		printf("--------          -------  ---                            ------=
-\n");
-		printf("%8ju          %7ju   0%%                            %ju file%s\n=
",
-		    total_size, total_size, file_count,
-		    file_count !=3D 1 ? "s" : "");
+	if (zipinfo_mode) {
+		if (v_opt =3D=3D 1) {
+			printf(" --------                   -------\n");
+			printf(" %8ju                   %ju file%s\n",
+			    total_size, file_count, file_count !=3D 1 ? "s" : "");
+		} else if (v_opt =3D=3D 2) {
+			printf("--------          -------  ---                            -----=
--\n");
+			printf("%8ju          %7ju   0%%                            %ju file%s\=
n",
+			    total_size, total_size, file_count,
+			    file_count !=3D 1 ? "s" : "");
+		}
 	}
=20
 	ac(archive_read_close(a));
@@ -933,7 +951,7 @@
 usage(void)
 {
=20
-	fprintf(stderr, "usage: unzip [-aCcfjLlnopqtuv] [-d dir] [-x pattern] zip=
file\n");
+	fprintf(stderr, "usage: unzip [-aCcfjLlnopqtuvZ1] [-d dir] [-x pattern] z=
ipfile\n");
 	exit(1);
 }
=20
@@ -943,8 +961,11 @@
 	int opt;
=20
 	optreset =3D optind =3D 1;
-	while ((opt =3D getopt(argc, argv, "aCcd:fjLlnopqtuvx:")) !=3D -1)
+	while ((opt =3D getopt(argc, argv, "aCcd:fjLlnopqtuvx:Z1")) !=3D -1)
 		switch (opt) {
+		case '1':
+			Z1_opt =3D 1;
+			break;
 		case 'a':
 			a_opt =3D 1;
 			break;
@@ -995,6 +1016,9 @@
 		case 'x':
 			add_pattern(&exclude, optarg);
 			break;
+		case 'Z':
+			zipinfo_mode =3D 1;
+			break;
 		default:
 			usage();
 		}
@@ -1024,6 +1048,15 @@
 	 */
 	nopts =3D getopts(argc, argv);
=20
+	/*=20
+	 * When more of the zipinfo mode options are implemented, this
+	 * will need to change.
+	 */
+	if (zipinfo_mode && !Z1_opt) {
+		printf("Zipinfo mode needs additional options\n");
+		exit(1);
+	}
+
 	if (argc <=3D nopts)
 		usage();
 	zipfile =3D argv[nopts++];
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/vgrind/vgrindefs.5
--- a/head/usr.bin/vgrind/vgrindefs.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/vgrind/vgrindefs.5	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)vgrindefs.5	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/vgrind/vgrindefs.5 233510 2012-03-26 15:18:14Z =
joel $
 .\"
 .Dd June 6, 1993
 .Dt VGRINDEFS 5
@@ -48,9 +48,8 @@
 .Xr termcap 5 .
 .Sh FIELDS
 The following table names and describes each field.
-.Pp
 .Bl -column Namexxx Tpexxx
-.It Sy "Name	Type	Description
+.It Sy "Name	Type	Description"
 .It "ab	str	regular expression for the start of an alternate comment"
 .It "ae	str	regular expression for the end of an alternate comment"
 .It "pb	str	regular expression for start of a procedure"
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/vmstat/vmstat.c
--- a/head/usr.bin/vmstat/vmstat.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/vmstat/vmstat.c	Tue Apr 17 11:51:51 2012 +0300
@@ -40,7 +40,7 @@
 #endif
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/vmstat/vmstat.c 228654 2011-12-17 19:22:2=
4Z dim $");
+__FBSDID("$FreeBSD: head/usr.bin/vmstat/vmstat.c 233298 2012-03-22 09:47:1=
4Z pluknet $");
=20
 #include <sys/param.h>
 #include <sys/proc.h>
@@ -81,26 +81,20 @@
 static struct nlist namelist[] =3D {
 #define X_SUM		0
 	{ "_cnt" },
-#define	X_BOOTTIME	1
-	{ "_boottime" },
-#define X_HZ		2
+#define X_HZ		1
 	{ "_hz" },
-#define X_STATHZ	3
+#define X_STATHZ	2
 	{ "_stathz" },
-#define X_NCHSTATS	4
+#define X_NCHSTATS	3
 	{ "_nchstats" },
-#define	X_INTRNAMES	5
+#define	X_INTRNAMES	4
 	{ "_intrnames" },
-#define	X_SINTRNAMES	6
+#define	X_SINTRNAMES	5
 	{ "_sintrnames" },
-#define	X_INTRCNT	7
+#define	X_INTRCNT	6
 	{ "_intrcnt" },
-#define	X_SINTRCNT	8
+#define	X_SINTRCNT	7
 	{ "_sintrcnt" },
-#define	X_KMEMSTATS	9
-	{ "_kmemstatistics" },
-#define	X_KMEMZONES	10
-	{ "_kmemzones" },
 #ifdef notyet
 #define	X_DEFICIT	XXX
 	{ "_deficit" },
@@ -112,7 +106,7 @@
 	{ "_xstats" },
 #define X_END		XXX
 #else
-#define X_END		11
+#define X_END		8
 #endif
 	{ "" },
 };
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/wall/wall.1
--- a/head/usr.bin/wall/wall.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/wall/wall.1	Tue Apr 17 11:51:51 2012 +0300
@@ -26,9 +26,9 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)wall.1	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.bin/wall/wall.1 233269 2012-03-21 08:03:07Z glebius=
 $
 .\"
-.Dd July 17, 2004
+.Dd February 24, 2012
 .Dt WALL 1
 .Os
 .Sh NAME
@@ -73,7 +73,3 @@
 terminal, not the receiver's (which
 .Nm
 has no way of knowing).
-.Pp
-The
-.Nm
-utility does not recognize multibyte characters.
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/wall/wall.c
--- a/head/usr.bin/wall/wall.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/wall/wall.c	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
=20
 #include <sys/cdefs.h>
=20
-__FBSDID("$FreeBSD: head/usr.bin/wall/wall.c 227200 2011-11-06 08:18:55Z e=
d $");
+__FBSDID("$FreeBSD: head/usr.bin/wall/wall.c 233269 2012-03-21 08:03:07Z g=
lebius $");
=20
 #ifndef lint
 static const char copyright[] =3D
@@ -62,6 +62,8 @@
 #include <time.h>
 #include <unistd.h>
 #include <utmpx.h>
+#include <wchar.h>
+#include <wctype.h>
=20
 #include "ttymsg.h"
=20
@@ -185,14 +187,15 @@
 makemsg(char *fname)
 {
 	int cnt;
-	unsigned char ch;
+	wchar_t ch;
 	struct tm *lt;
 	struct passwd *pw;
 	struct stat sbuf;
 	time_t now;
 	FILE *fp;
 	int fd;
-	char *p, hostname[MAXHOSTNAMELEN], lbuf[256], tmpname[64];
+	char hostname[MAXHOSTNAMELEN], tmpname[64];
+	wchar_t *p, *tmp, lbuf[256], codebuf[13];
 	const char *tty;
 	const char *whom;
 	gid_t egid;
@@ -220,78 +223,61 @@
 		 * Which means that we may leave a non-blank character
 		 * in column 80, but that can't be helped.
 		 */
-		(void)fprintf(fp, "\r%79s\r\n", " ");
-		(void)snprintf(lbuf, sizeof(lbuf),=20
-		    "Broadcast Message from %s@%s",
+		(void)fwprintf(fp, L"\r%79s\r\n", " ");
+		(void)swprintf(lbuf, sizeof(lbuf)/sizeof(wchar_t),
+		    L"Broadcast Message from %s@%s",
 		    whom, hostname);
-		(void)fprintf(fp, "%-79.79s\007\007\r\n", lbuf);
-		(void)snprintf(lbuf, sizeof(lbuf),
-		    "        (%s) at %d:%02d %s...", tty,
+		(void)fwprintf(fp, L"%-79.79S\007\007\r\n", lbuf);
+		(void)swprintf(lbuf, sizeof(lbuf)/sizeof(wchar_t),
+		    L"        (%s) at %d:%02d %s...", tty,
 		    lt->tm_hour, lt->tm_min, lt->tm_zone);
-		(void)fprintf(fp, "%-79.79s\r\n", lbuf);
+		(void)fwprintf(fp, L"%-79.79S\r\n", lbuf);
 	}
-	(void)fprintf(fp, "%79s\r\n", " ");
+	(void)fwprintf(fp, L"%79s\r\n", " ");
=20
 	if (fname) {
 		egid =3D getegid();
 		setegid(getgid());
-	       	if (freopen(fname, "r", stdin) =3D=3D NULL)
+		if (freopen(fname, "r", stdin) =3D=3D NULL)
 			err(1, "can't read %s", fname);
 		setegid(egid);
 	}
 	cnt =3D 0;
-	while (fgets(lbuf, sizeof(lbuf), stdin)) {
-		for (p =3D lbuf; (ch =3D *p) !=3D '\0'; ++p, ++cnt) {
-			if (ch =3D=3D '\r') {
-				putc('\r', fp);
+	while (fgetws(lbuf, sizeof(lbuf)/sizeof(wchar_t), stdin)) {
+		for (p =3D lbuf; (ch =3D *p) !=3D L'\0'; ++p, ++cnt) {
+			if (ch =3D=3D L'\r') {
+				putwc(L'\r', fp);
 				cnt =3D 0;
 				continue;
-			} else if (ch =3D=3D '\n') {
+			} else if (ch =3D=3D L'\n') {
 				for (; cnt < 79; ++cnt)
-					putc(' ', fp);
-				putc('\r', fp);
-				putc('\n', fp);
+					putwc(L' ', fp);
+				putwc(L'\r', fp);
+				putwc(L'\n', fp);
 				break;
 			}
 			if (cnt =3D=3D 79) {
-				putc('\r', fp);
-				putc('\n', fp);
+				putwc(L'\r', fp);
+				putwc(L'\n', fp);
 				cnt =3D 0;
 			}
-			if (((ch & 0x80) && ch < 0xA0) ||
-				   /* disable upper controls */
-				   (!isprint(ch) && !isspace(ch) &&
-				    ch !=3D '\a' && ch !=3D '\b')
-				  ) {
-				if (ch & 0x80) {
-					ch &=3D 0x7F;
-					putc('M', fp);
+			if (iswprint(ch) || iswspace(ch) || ch =3D=3D L'\a' || ch =3D=3D L'\b')=
 {
+				putwc(ch, fp);
+			} else {
+				(void)swprintf(codebuf, sizeof(codebuf)/sizeof(wchar_t), L"<0x%X>", ch=
);
+				for (tmp =3D codebuf; *tmp !=3D L'\0'; ++tmp) {
+					putwc(*tmp, fp);
 					if (++cnt =3D=3D 79) {
-						putc('\r', fp);
-						putc('\n', fp);
-						cnt =3D 0;
-					}
-					putc('-', fp);
-					if (++cnt =3D=3D 79) {
-						putc('\r', fp);
-						putc('\n', fp);
+						putwc(L'\r', fp);
+						putwc(L'\n', fp);
 						cnt =3D 0;
 					}
 				}
-				if (iscntrl(ch)) {
-					ch ^=3D 040;
-					putc('^', fp);
-					if (++cnt =3D=3D 79) {
-						putc('\r', fp);
-						putc('\n', fp);
-						cnt =3D 0;
-					}
-				}
+				--cnt;
 			}
-			putc(ch, fp);
 		}
 	}
-	(void)fprintf(fp, "%79s\r\n", " ");
+	(void)fwprintf(fp, L"%79s\r\n", " ");
 	rewind(fp);
=20
 	if (fstat(fd, &sbuf))
diff -r 428842767fa6 -r f2935497fa04 head/usr.bin/xlint/Makefile.inc
--- a/head/usr.bin/xlint/Makefile.inc	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.bin/xlint/Makefile.inc	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	$NetBSD: Makefile.inc,v 1.8 2002/02/04 00:18:32 thorpej Exp $
-# $FreeBSD$
+# $FreeBSD: head/usr.bin/xlint/Makefile.inc 233644 2012-03-29 02:54:35Z jm=
allett $
=20
 WARNS?=3D		0
=20
@@ -8,7 +8,7 @@
 # These assignments duplicate much of the functionality of
 # MACHINE_CPUARCH, but there's no easy way to export make functions...
 .if defined(TARGET_ARCH)
-TARGET_CPUARCH=3D	${TARGET_ARCH:C/mips.*e[bl]/mips/:C/armeb/arm/}
+TARGET_CPUARCH=3D	${TARGET_ARCH:C/mips(n32|64)?(el)?/mips/:C/armeb/arm/}
 .else
 TARGET_CPUARCH=3D	${MACHINE_CPUARCH}
 TARGET_ARCH=3D	${MACHINE_ARCH}
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/Makefile
--- a/head/usr.sbin/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 #	From: @(#)Makefile	5.20 (Berkeley) 6/12/93
-# $FreeBSD: head/usr.sbin/Makefile 231530 2012-02-11 20:28:42Z ed $
+# $FreeBSD: head/usr.sbin/Makefile 234313 2012-04-15 15:13:36Z bapt $
=20
 .include <bsd.own.mk>
=20
@@ -256,6 +256,7 @@
=20
 .if ${MK_PKGTOOLS} !=3D "no"
 SUBDIR+=3D	pkg_install
+SUBDIR+=3D	pkg
 .endif
=20
 # XXX MK_TOOLCHAIN?
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/Makefile.mips
--- a/head/usr.sbin/Makefile.mips	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/Makefile.mips	Tue Apr 17 11:51:51 2012 +0300
@@ -1,6 +1,6 @@
-# $FreeBSD: head/usr.sbin/Makefile.mips 232908 2012-03-13 00:45:27Z jmalle=
tt $
+# $FreeBSD: head/usr.sbin/Makefile.mips 233644 2012-03-29 02:54:35Z jmalle=
tt $
=20
-# uathload broken for n32 and n64 due to toolchain issues
-.if ${MACHINE_ARCH:Mmipse[lb]} =3D=3D ""
+# uathload broken for n32 and n64 due to toolchain issues, only build for =
o32
+.if ${MACHINE_ARCH} !=3D "mips" && ${MACHINE_ARCH} !=3D "mipsel"
 SUBDIR:=3D	${SUBDIR:Nuathload}
 .endif
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/ac/ac.8
--- a/head/usr.sbin/ac/ac.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/ac/ac.8	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/ac/ac.8 233522 2012-03-26 21:22:53Z joel $
 .\"
 .Dd March 15, 1994
 .Dt AC 8
@@ -112,7 +112,7 @@
 does not exist.
 .Pp
 For example,
-.Bd -literal -offset
+.Bd -literal -offset indent
 ac -p -t "ttyd*" > modems
 ac -p -t "!ttyd*" > other
 .Ed
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/acpi/iasl/Makefile
--- a/head/usr.sbin/acpi/iasl/Makefile	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/acpi/iasl/Makefile	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.sbin/acpi/iasl/Makefile 232676 2012-03-07 23:57:49Z j=
kim $
+# $FreeBSD: head/usr.sbin/acpi/iasl/Makefile 233250 2012-03-20 21:37:52Z j=
kim $
=20
 PROG=3D	iasl
 SRCS=3D	adfile.c adisasm.c adwalk.c
@@ -20,7 +20,8 @@
 	aslutils.c asluuid.c aslwalks.c dtcompile.c dtexpress.c	\
 	dtfield.c dtio.c dtparser.y.h dtparserlex.c		\
 	dtparserparse.c dtsubtable.c dttable.c dttemplate.c	\
-	dtutils.c
+	dtutils.c prexpress.c prmacros.c prparser.y.h		\
+	prparserlex.c prparserparse.c prscan.c prutils.c
=20
 # components/debugger
 SRCS+=3D	dbfileio.c
@@ -92,4 +93,14 @@
 dtparser.y.h: dtparserparse.h
 	ln -f ${.ALLSRC} ${.TARGET}
=20
+prparserlex.c: prparser.l
+	${LEX} ${LFLAGS} -PPrParser -o${.TARGET} ${.ALLSRC}
+
+.ORDER: prparserparse.c prparserparse.h
+prparserparse.c prparserparse.h: prparser.y
+	${YACC} ${YFLAGS} -pPrParser -oprparserparse.c ${.ALLSRC}
+
+prparser.y.h: prparserparse.h
+	ln -f ${.ALLSRC} ${.TARGET}
+
 .include <bsd.prog.mk>
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/adduser/adduser.conf.5
--- a/head/usr.sbin/adduser/adduser.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/adduser/adduser.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/adduser/adduser.conf.5 233648 2012-03-29 05:02=
:12Z eadler $
 .\"
 .Dd April 12, 2007
 .Dt ADDUSER.CONF 5
@@ -34,7 +34,7 @@
 .Xr adduser 8
 configuration file
 .Sh DESCRIPTION
-The=20
+The
 .Pa /etc/adduser.conf
 file is automatically generated by the
 .Xr adduser 8
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/apmd/apmd.8
--- a/head/usr.sbin/apmd/apmd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/apmd/apmd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)apmd.8	1.1 (FreeBSD) 6/28/99
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/apmd/apmd.8 233522 2012-03-26 21:22:53Z joel $
 .\"
 .Dd June 28, 1999
 .Dt APMD 8 i386
@@ -66,7 +66,7 @@
 The
 .Nm
 utility recognizes the following runtime options:
-.Bl -tag -width -f_file
+.Bl -tag -width f_file
 .It Fl d
 Starts in debug mode.
 This causes
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/arp/arp.4
--- a/head/usr.sbin/arp/arp.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/arp/arp.4	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)arp4.4	6.5 (Berkeley) 4/18/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/arp/arp.4 233510 2012-03-26 15:18:14Z joel $
 .\"
 .Dd March 28, 2007
 .Dt ARP 4
@@ -186,6 +186,6 @@
 .Rs
 .%A Leffler, S.J.
 .%A Karels, M.J.
-.%B "Trailer Encapsulations
+.%B "Trailer Encapsulations"
 .%T RFC893
 .Re
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/arp/arp.c
--- a/head/usr.sbin/arp/arp.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/arp/arp.c	Tue Apr 17 11:51:51 2012 +0300
@@ -42,7 +42,7 @@
 #endif /* not lint */
 #endif
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/usr.sbin/arp/arp.c 233773 2012-04-02 10:44:25Z gl=
ebius $");
=20
 /*
  * arp - display, set, and delete arp table entries
@@ -387,10 +387,6 @@
 	}
 	addr =3D (struct sockaddr_inarp *)(rtm + 1);
 	sdl =3D (struct sockaddr_dl *)(SA_SIZE(addr) + (char *)addr);
-	if (addr->sin_addr.s_addr =3D=3D dst->sin_addr.s_addr) {
-		printf("set: proxy entry exists for non 802 device\n");
-		return (1);
-	}
=20
 	if ((sdl->sdl_family !=3D AF_LINK) ||
 	    (rtm->rtm_flags & RTF_GATEWAY) ||
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/bluetooth/ath3kfw/ath3kf=
w.8
--- a/head/usr.sbin/bluetooth/ath3kfw/ath3kfw.8	Tue Apr 17 11:36:47 2012 +0=
300
+++ b/head/usr.sbin/bluetooth/ath3kfw/ath3kfw.8	Tue Apr 17 11:51:51 2012 +0=
300
@@ -22,9 +22,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/bluetooth/ath3kfw/ath3kfw.8 233648 2012-03-29 =
05:02:12Z eadler $
 .\"
-.Dd Novermber 9, 2010
+.Dd November 9, 2010
 .Dt ATH3KFW 8
 .Os
 .Sh NAME
@@ -58,7 +58,7 @@
 .Bl -tag -width indent
 .It Fl d Ar device_name
 Specify
-.Xr ugen 4=20
+.Xr ugen 4
 device name.
 .It Fl f Ar firmware_file_name
 Specify firmware file name for download.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/boot0cfg/boot0cfg.8
--- a/head/usr.sbin/boot0cfg/boot0cfg.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/boot0cfg/boot0cfg.8	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 .\" EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/boot0cfg/boot0cfg.8 230978 2012-02-04 13:12:52=
Z kib $
+.\" $FreeBSD: head/usr.sbin/boot0cfg/boot0cfg.8 233455 2012-03-25 09:18:34=
Z joel $
 .\"
 .Dd February 4, 2012
 .Dt BOOT0CFG 8
@@ -184,7 +184,6 @@
 to install the default MBR:
 .Pp
 .Dl "fdisk -B ad0"
-.Pp
 .Sh SEE ALSO
 .Xr geom 4 ,
 .Xr boot 8 ,
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/bootparamd/bootparamd/bo=
otparamd.8
--- a/head/usr.sbin/bootparamd/bootparamd/bootparamd.8	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/usr.sbin/bootparamd/bootparamd/bootparamd.8	Tue Apr 17 11:51:51 =
2012 +0300
@@ -1,5 +1,5 @@
 .\" @(#)bootparamd.8
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/bootparamd/bootparamd/bootparamd.8 233510 2012=
-03-26 15:18:14Z joel $
 .Dd December 14, 2000
 .Dt BOOTPARAMD 8
 .Os
@@ -58,7 +58,7 @@
 To accommodate this behaviour add an alias address
 that responds to an all-0 broadcast.
 So, add something like
-.Ql "ifconfig xl0 192.168.200.254 netmask 255.255.255.255 broadcast 192.16=
8.200.0 alias
+.Ql "ifconfig xl0 192.168.200.254 netmask 255.255.255.255 broadcast 192.16=
8.200.0 alias"
 on the relevant network interface on your
 .Nm
 server.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/bsdinstall/bsdinstall.8
--- a/head/usr.sbin/bsdinstall/bsdinstall.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/bsdinstall/bsdinstall.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,10 +23,10 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/bsdinstall/bsdinstall.8 223012 2011-06-12 15:1=
9:38Z nwhitehorn $
+.\" $FreeBSD: head/usr.sbin/bsdinstall/bsdinstall.8 233648 2012-03-29 05:0=
2:12Z eadler $
 .\"
 .Dd June 11, 2011
-.Dt bsdinstall 8
+.Dt BSDINSTALL 8
 .Os
 .Sh NAME
 .Nm bsdinstall
@@ -85,7 +85,7 @@
 Interactively configures network interfaces (first invoking
 .Cm wlanconfig
 on wireless interfaces), saving the result to the new system's
-.Pa rc.conf=20
+.Pa rc.conf
 and
 .Pa resolv.conf .
 If
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/bsdinstall/partedit/gpar=
t_ops.c
--- a/head/usr.sbin/bsdinstall/partedit/gpart_ops.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/usr.sbin/bsdinstall/partedit/gpart_ops.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.sbin/bsdinstall/partedit/gpart_ops.c 228048 2011-11-=
28 05:34:16Z kevlo $
+ * $FreeBSD: head/usr.sbin/bsdinstall/partedit/gpart_ops.c 233904 2012-04-=
04 23:14:01Z nwhitehorn $
  */
=20
 #include <sys/param.h>
@@ -147,7 +147,7 @@
 				strcat(command, "-F 32 ");
 			else if (strcmp(items[i].name, "FAT16") =3D=3D 0)
 				strcat(command, "-F 16 ");
-			else if (strcmp(items[i].name, "SUJ") =3D=3D 0)
+			else if (strcmp(items[i].name, "FAT12") =3D=3D 0)
 				strcat(command, "-F 12 ");
 		}
 	} else {
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/bsnmpd/modules/snmp_netg=
raph/snmp_netgraph.3
--- a/head/usr.sbin/bsnmpd/modules/snmp_netgraph/snmp_netgraph.3	Tue Apr 17=
 11:36:47 2012 +0300
+++ b/head/usr.sbin/bsnmpd/modules/snmp_netgraph/snmp_netgraph.3	Tue Apr 17=
 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOF=
TWARE,
 .\" EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/bsnmpd/modules/snmp_netgraph/snmp_netgraph.3 2=
31564 2012-02-12 18:29:56Z ed $
+.\" $FreeBSD: head/usr.sbin/bsnmpd/modules/snmp_netgraph/snmp_netgraph.3 2=
33510 2012-03-26 15:18:14Z joel $
 .\"
 .Dd November 14, 2003
 .Dt SNMP_NETGRAPH 3
@@ -65,7 +65,7 @@
 .Nm ng_node_name ,
 .Nm ng_node_type ,
 .Nm ng_peer_hook_id
-.Nd "netgraph module for snmpd.
+.Nd "netgraph module for snmpd"
 .Sh LIBRARY
 .Pq begemotSnmpdModulePath."netgraph" =3D "/usr/lib/snmp_netgraph.so"
 .Sh SYNOPSIS
@@ -283,7 +283,6 @@
 .Fn ng_unregister_module
 removes all control and data registrations for that module.
 .Ss FINDING NODES AND NODE CHARACTERISTICS
-.Pp
 The function
 .Fn ng_node_id
 returns the id of the node addressed by
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/bsnmpd/modules/snmp_wlan=
/snmp_wlan.3
--- a/head/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3	Tue Apr 17 11:36:4=
7 2012 +0300
+++ b/head/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3	Tue Apr 17 11:51:5=
1 2012 +0300
@@ -1,7 +1,7 @@
 .\"-
 .\" Copyright (C) 2010 The FreeBSD Foundation
 .\" All rights reserved.
-.\"=20
+.\"
 .\" This documentation was written by Shteryana Sotirova Shopova under
 .\" sponsorship from the FreeBSD Foundation.
 .\"
@@ -13,7 +13,7 @@
 .\" 2. Redistributions in binary form must reproduce the above copyright
 .\"    notice, this list of conditions and the following disclaimer in the
 .\"    documentation and/or other materials provided with the distribution.
-.\"=20
+.\"
 .\" THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PUR=
POSE
@@ -26,14 +26,14 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3 222286 20=
11-05-25 14:13:53Z ru $
+.\" $FreeBSD: head/usr.sbin/bsnmpd/modules/snmp_wlan/snmp_wlan.3 233648 20=
12-03-29 05:02:12Z eadler $
 .\"
 .Dd June 28, 2010
 .Dt SNMP_WLAN 3
 .Os
 .Sh NAME
 .Nm snmp_wlan
-.Nd "wireless networking module for
+.Nd "wireless networking module for"
 .Xr bsnmpd 1
 .Sh LIBRARY
 .Pq begemotSnmpdModulePath."wlan" =3D "/usr/lib/snmp_wlan.so"
@@ -61,10 +61,10 @@
 .Va wlanParentIfName
 column. Any optional parameters may be set
 via the
-.Va wlanIfaceOperatingMode,=20
-.Va wlanIfaceFlags,=20
+.Va wlanIfaceOperatingMode,
+.Va wlanIfaceFlags,
 .Va wlanIfaceBssid
-and=20
+and
 .Va wlanIfaceLocalAddress
 columns.
 To finally create the interface in the system, a SET with value of active(=
1) to
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/bsnmpd/tools/bsnmptools/=
bsnmpget.1
--- a/head/usr.sbin/bsnmpd/tools/bsnmptools/bsnmpget.1	Tue Apr 17 11:36:47 =
2012 +0300
+++ b/head/usr.sbin/bsnmpd/tools/bsnmptools/bsnmpget.1	Tue Apr 17 11:51:51 =
2012 +0300
@@ -31,7 +31,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/bsnmpd/tools/bsnmptools/bsnmpget.1 229933 2012=
-01-10 15:29:03Z syrinx $
+.\" $FreeBSD: head/usr.sbin/bsnmpd/tools/bsnmptools/bsnmpget.1 233648 2012=
-03-29 05:02:12Z eadler $
 .\"
 .Dd January 10, 2012
 .Dt BSNMPGET 1
@@ -121,7 +121,6 @@
 syntaxes and values of the objects whose values are to be set and waits fo=
r a
 response from server.
 .Sh OPTIONS
-.Pp
 The options are as follows (not all apply to all three programs):
 .Bl -tag -width ".It Fl D Ar options"
 .It Fl A Ar options
@@ -253,7 +252,7 @@
 The PDU type to send by
 .Nm bsmpget
 and
-.Nm bsnmpwalk .=20
+.Nm bsnmpwalk .
 Default is get
 for
 .Nm bsmpget
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/cdcontrol/cdcontrol.1
--- a/head/usr.sbin/cdcontrol/cdcontrol.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/cdcontrol/cdcontrol.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/cdcontrol/cdcontrol.1 233648 2012-03-29 05:02:=
12Z eadler $
 .\"
 .Dd June 27, 2008
 .Dt CDCONTROL 1
@@ -131,7 +131,7 @@
 .It Ic close
 Inject the disc.
 .It Ic volume
-Same as=20
+Same as
 .Em status volume
 command.
 .It Ic volume Ar level
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/config/config.8
--- a/head/usr.sbin/config/config.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/config/config.8	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)config.8	8.2 (Berkeley) 4/19/94
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/config/config.8 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd May 8, 2007
 .Dt CONFIG 8
@@ -86,7 +86,7 @@
 .It Fl x Ar kernel
 Print kernel configuration file embedded into a kernel
 file.
-This option makes sense only if=20
+This option makes sense only if
 .Cd "options INCLUDE_CONFIG_FILE"
 entry was present in your configuration file.
 .It Fl p
@@ -246,7 +246,7 @@
 utility appeared in
 .Bx 4.1 .
 .Pp
-Before support for=20
+Before support for
 .Fl x
 was introduced,
 .Cd "options INCLUDE_CONFIG_FILE"
@@ -255,7 +255,7 @@
 This meant that
 .Xr strings 1
 could be used to extract it from a kernel:
-to extract the configuration information, you had to use=20
+to extract the configuration information, you had to use
 the command:
 .Pp
 .Dl "strings -n 3 kernel | sed -n 's/^___//p'"
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/ctladm/ctladm.8
--- a/head/usr.sbin/ctladm/ctladm.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/ctladm/ctladm.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,7 +1,7 @@
-.\"=20
+.\"
 .\" Copyright (c) 2003 Silicon Graphics International Corp.
 .\" All rights reserved.
-.\"=20
+.\"
 .\" Redistribution and use in source and binary forms, with or without
 .\" modification, are permitted provided that the following conditions
 .\" are met:
@@ -13,7 +13,7 @@
 .\"    ("Disclaimer") and any redistribution must be conditioned upon
 .\"    including a substantially similar Disclaimer requirement for further
 .\"    binary redistribution.
-.\"=20
+.\"
 .\" NO WARRANTY
 .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 .\" "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@@ -26,13 +26,13 @@
 .\" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 .\" IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGES.
-.\"=20
+.\"
 .\" ctladm utility man page.
 .\"
 .\" Author: Ken Merry <ken at FreeBSD.org>
 .\"
 .\" $Id: //depot/users/kenm/FreeBSD-test2/usr.sbin/ctladm/ctladm.8#3 $
-.\" $FreeBSD: head/usr.sbin/ctladm/ctladm.8 232604 2012-03-06 13:43:57Z tr=
asz $
+.\" $FreeBSD: head/usr.sbin/ctladm/ctladm.8 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd March 6, 2012
 .Dt CTLADM 8
@@ -227,7 +227,6 @@
 Many of the primary functions of the
 .Nm
 utility take the following optional arguments:
-.Pp
 .Bl -tag -width 10n
 .It Fl C Ar retries
 Specify the number of times to retry a command in the event of failure.
@@ -296,7 +295,7 @@
 can be calculated accurately.  The blocksize can be obtained via the
 .Tn SCSI
 READ CAPACITY command.
-.It Fl N=20
+.It Fl N
 Do not copy data to
 .Nm
 from the kernel when doing a read, just execute the command without copying
@@ -460,7 +459,7 @@
 .It Fl o
 Set the Copan proprietary on/offline bit in the CDB.  When this flag is
 used, the LUN will be spun down and taken offline ("Logical unit not ready,
-manual intervention required").  See the description of the=20
+manual intervention required").  See the description of the
 .Ic shutdown
 and
 .Ic startup
@@ -468,7 +467,7 @@
 .El
 .It Ic synccache
 Send the
-.Tn SCSI=20
+.Tn SCSI
 SYNCHRONIZE CACHE command to the device.  By default, SYNCHRONIZE
 CACHE(10) is used.  If the specified starting LBA is greater than
 0xffffffff or the length is greater than 0xffff, though,
@@ -551,7 +550,7 @@
 and just prior to sending status to the host
 .Pq Dq done .
 One of the two must be supplied as an argument to the
-.Fl l=20
+.Fl l
 option.  The
 .Fl t
 option must also be specified.
@@ -585,7 +584,7 @@
 will show whether SYNCHRONIZE CACHE commands are being sent to the backend
 or not.
 The default is to send SYNCHRONIZE CACHE commands to the backend.
-The=20
+The
 .Sq on
 argument will cause all SYNCHRONIZE CACHE commands sent to all LUNs to be
 sent to the backend.
@@ -627,7 +626,7 @@
 .Fl c
 flag is specified, all commands matching the pattern will be returned with
 the specified error until the error injection command is deleted with
-.Fl d=20
+.Fl d
 flag.
 .Bl -tag -width 17n
 .It Fl i Ar action
@@ -710,7 +709,7 @@
 One of
 .Fl l ,
 .Fl o ,
-or=20
+or
 .Fl w
 or
 .Fl W
@@ -724,7 +723,7 @@
 Turn the specified CTL frontend ports off or on.
 If no port number or port type is specified, all ports are turned on or
 off.
-.It Fl p Ar targ_port=20
+.It Fl p Ar targ_port
 Specify the frontend port number.
 The port numbers can be found in the frontend port list.
 .It Fl q
@@ -744,7 +743,7 @@
 .It Fl w Ar wwnn
 Set the World Wide Node Name for the given port.
 The
-.Fl n=20
+.Fl n
 argument must be specified, since this is only possible to implement on a
 single port.
 As a general rule, the WWNN should be the same across all ports on the
@@ -905,7 +904,6 @@
 Display the saved version of the Control mode page (page 10) on LUN 0.
 Disable fetching block descriptors, and use a 10 byte MODE SENSE command
 instead of the default 6 byte command.
-.Pp
 .Bd -literal
 ctladm read 0:2 -l 0 -d 1 -b 512 -f - > foo
 .Ed
@@ -959,14 +957,13 @@
 .Dl ctladm lunlist
 .Pp
 List all LUNs in the system, along with their inquiry data and device type.
-This only works when the FETDs are enabled, since the commands go through =
the=20
+This only works when the FETDs are enabled, since the commands go through =
the
 ioctl port.
 .Pp
 .Dl ctladm inject 0:6 -i mediumerr -p read -r 0,512 -c
 .Pp
 Inject a medium error on LUN 6 for every read that covers the first 512
 blocks of the LUN.
-.Pp
 .Bd -literal -offset indent
 ctladm inject 0:6 -i custom -p tur -s 18 "f0 0 02 s12 04 02"
 .Ed
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/edquota/edquota.8
--- a/head/usr.sbin/edquota/edquota.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/edquota/edquota.8	Tue Apr 17 11:51:51 2012 +0300
@@ -29,7 +29,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"	@(#)edquota.8	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/edquota/edquota.8 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd June 6, 1993
 .Dt EDQUOTA 8
@@ -106,7 +106,7 @@
 If no units are specified, the number of inodes specified are used.
 If the
 .Fl h
-flag is specified, the editor will always display the=20
+flag is specified, the editor will always display the
 block usage and limits in a more human readable format
 rather than displaying them in the historic kilobyte format.
 Setting a quota to zero indicates that no quota should be imposed.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/faithd/faithd.8
--- a/head/usr.sbin/faithd/faithd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/faithd/faithd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/faithd/faithd.8 224609 2011-08-02 11:35:28Z gj=
b $
+.\" $FreeBSD: head/usr.sbin/faithd/faithd.8 233522 2012-03-26 21:22:53Z jo=
el $
 .\"
 .Dd August 2, 2011
 .Dt FAITHD 8
@@ -281,7 +281,7 @@
 the
 .Xr faith 4
 interface has to be configured properly.
-.Bd -literal -offset
+.Bd -literal -offset indent
 # sysctl net.inet6.ip6.accept_rtadv=3D0
 # sysctl net.inet6.ip6.forwarding=3D1
 # sysctl net.inet6.ip6.keepfaith=3D1
@@ -295,7 +295,7 @@
 service, and provide no local telnet service, invoke
 .Nm
 as follows:
-.Bd -literal -offset
+.Bd -literal -offset indent
 # faithd telnet
 .Ed
 .Pp
@@ -304,12 +304,12 @@
 on
 .Pa /usr/libexec/telnetd ,
 use the following command line:
-.Bd -literal -offset
+.Bd -literal -offset indent
 # faithd telnet /usr/libexec/telnetd telnetd
 .Ed
 .Pp
 If you would like to pass extra arguments to the local daemon:
-.Bd -literal -offset
+.Bd -literal -offset indent
 # faithd ftp /usr/libexec/ftpd ftpd -l
 .Ed
 .Pp
@@ -317,7 +317,7 @@
 You may need
 .Fl p
 if the service checks the source port range.
-.Bd -literal -offset
+.Bd -literal -offset indent
 # faithd ssh
 # faithd telnet /usr/libexec/telnetd telnetd
 .Ed
@@ -325,7 +325,7 @@
 Add the following lines into
 .Xr inetd.conf 5 .
 Syntax may vary depending upon your operating system.
-.Bd -literal -offset
+.Bd -literal -offset indent
 telnet  stream  tcp6/faith  nowait  root  faithd  telnetd
 ftp     stream  tcp6/faith  nowait  root  faithd  ftpd -l
 ssh     stream  tcp6/faith  nowait  root  faithd  /usr/sbin/sshd -i
@@ -349,7 +349,7 @@
 The following illustrates a simple
 .Pa faithd.conf
 setting.
-.Bd -literal -offset
+.Bd -literal -offset indent
 # permit anyone from 3ffe:501:ffff::/48 to use the translator,
 # to connect to the following IPv4 destinations:
 # - any location except 10.0.0.0/8 and 127.0.0.0/8.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/fdwrite/fdwrite.1
--- a/head/usr.sbin/fdwrite/fdwrite.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/fdwrite/fdwrite.1	Tue Apr 17 11:51:51 2012 +0300
@@ -6,7 +6,7 @@
 .\" this stuff is worth it, you can buy me a beer in return.   Poul-Hennin=
g Kamp
 .\" ----------------------------------------------------------------------=
------
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/fdwrite/fdwrite.1 233510 2012-03-26 15:18:14Z =
joel $
 .\"
 .\"
 .Dd September 16, 1993
@@ -87,7 +87,7 @@
 was planned as a tool to make life easier when writing a set of floppies,
 one such use could be to write a tar-archive:
 .Pp
-.Dl "tar cf - . | gzip -9 | fdwrite -d /dev/fd0.1720 -v
+.Dl tar cf - . | gzip -9 | fdwrite -d /dev/fd0.1720 -v
 .Pp
 The main difference from using
 .Xr tar 1 Ns 's
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/freebsd-update/freebsd-u=
pdate.8
--- a/head/usr.sbin/freebsd-update/freebsd-update.8	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/usr.sbin/freebsd-update/freebsd-update.8	Tue Apr 17 11:51:51 201=
2 +0300
@@ -23,7 +23,7 @@
 .\" IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/freebsd-update/freebsd-update.8 233648 2012-03=
-29 05:02:12Z eadler $
 .\"
 .Dd July 14, 2010
 .Dt FREEBSD-UPDATE 8
@@ -49,7 +49,7 @@
 Note that updates are only available if they are being built for the
 FreeBSD release and architecture being used; in particular, the
 .Fx
-Security Team only builds updates for releases shipped in binary form=20
+Security Team only builds updates for releases shipped in binary form
 by the
 .Fx
 Release Engineering Team, e.g.,
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/fwcontrol/fwcontrol.8
--- a/head/usr.sbin/fwcontrol/fwcontrol.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/fwcontrol/fwcontrol.8	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 .\" POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/fwcontrol/fwcontrol.8 233510 2012-03-26 15:18:=
14Z joel $
 .\"
 .Dd September 12, 2008
 .Dt FWCONTROL 8
@@ -171,7 +171,7 @@
 with
 .Dq Li bs=3D144000 .
 .Pp
-.Dl "fwcontrol -R file.m2t
+.Dl "fwcontrol -R file.m2t"
 .Pp
 Receive an MPEG TS stream from a camera producing MPEG transport stream.
 This has been tested with SONY HDR-FX1E camera that produces HD MPEG-2
@@ -179,7 +179,7 @@
 .Pp
 To send the stream from the camera over the network using TCP (which
 surprisingly works better with vlc), you can use
-.Dl "fwcontrol -R - | nc 192.168.10.11 9000
+.Dl "fwcontrol -R - | nc 192.168.10.11 9000"
 with
 .Nm netcat
 from ports and to receive the stream, use
@@ -190,7 +190,7 @@
 program from ports, since vlc is not fast enough to read UDP packets from
 buffers and thus it experiences dropouts when run directly.
 The sending side can use
-.Dl "fwcontrol -R - | nc 192.168.10.11 9000
+.Dl "fwcontrol -R - | nc 192.168.10.11 9000"
 and to receive the stream, use
 .Dl nc -l -u -p 9000 | buffer -s 10k -b 1000 -m 20m -p 5 | vlc -
 .Pp
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/gpioctl/gpioctl.8
--- a/head/usr.sbin/gpioctl/gpioctl.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/gpioctl/gpioctl.8	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/gpioctl/gpioctl.8 222290 2011-05-25 21:04:11Z =
bcr $
+.\" $FreeBSD: head/usr.sbin/gpioctl/gpioctl.8 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd May 25, 2011
 .Dt GPIOCTL 1
@@ -37,11 +37,13 @@
 .Nm
 .Cm -g
 .Op Fl q
+.Cm -l
 .Fl f Ar ctldev
 .Op Fl v
 .Nm
 .Cm -l
 .Op Fl q
+.Cm -t
 .Fl f Ar ctldev
 .Op Fl v
 .Nm
@@ -52,9 +54,10 @@
 .Nm
 .Cm -c
 .Op Fl q
+.Cm -c
 .Fl f Ar ctldev
 .Ar pin
-.Ar flag=20
+.Ar flag
 .Op flag ...
 .Nm
 .Cm [-q] -f Ar ctldev=20
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/i2c/i2c.8
--- a/head/usr.sbin/i2c/i2c.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/i2c/i2c.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,14 +23,14 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$=20
+.\" $FreeBSD: head/usr.sbin/i2c/i2c.8 233648 2012-03-29 05:02:12Z eadler $
 .\"
 .Dd January 23, 2009
 .Dt I2C 8
 .Os
 .Sh NAME
 .Nm i2c
-.Nd test I2C bus and slave devices=20
+.Nd test I2C bus and slave devices
 .Sh SYNOPSIS
 .Nm
 .Cm -a Ar address
@@ -120,12 +120,12 @@
 .Pp
 i2c -s
 .It
-Scan the default bus (/dev/iic0) for devices and skip addresses 0x56 and=20
+Scan the default bus (/dev/iic0) for devices and skip addresses 0x56 and
 0x45.
 .Pp
 i2c -s -n 0x56:0x45
 .It
-Scan the default bus (/dev/iic0) for devices and skip address range=20
+Scan the default bus (/dev/iic0) for devices and skip address range
 0x34 to 0x56.
 .Pp
 i2c -s -n 0x34..0x56
@@ -161,6 +161,6 @@
 utility and this manual page were written by
 .An Bartlomiej Sieka
 .Aq tur at semihalf.com
-and=20
+and
 .An Michal Hajduk
 .Aq mih at semihalf.com .
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/ifmcstat/ifmcstat.8
--- a/head/usr.sbin/ifmcstat/ifmcstat.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/ifmcstat/ifmcstat.8	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/ifmcstat/ifmcstat.8 222025 2011-05-17 14:46:28=
Z pluknet $
+.\" $FreeBSD: head/usr.sbin/ifmcstat/ifmcstat.8 233455 2012-03-25 09:18:34=
Z joel $
 .\"
 .Dd May 27, 2009
 .Dt IFMCSTAT 8
@@ -123,7 +123,6 @@
 is more limited.
 This support is recommended for debugging purposes.
 It requires super-user privilege if used to inspect a running kernel.
-.Pp
 .Sh SEE ALSO
 .Xr netstat 1 ,
 .Xr getifaddrs 3 ,
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/lmcconfig/lmcconfig.8
--- a/head/usr.sbin/lmcconfig/lmcconfig.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/lmcconfig/lmcconfig.8	Tue Apr 17 11:51:51 2012 +0300
@@ -40,7 +40,7 @@
 .\" this program; if not, write to the Free Software Foundation, Inc., 59=20
 .\" Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/lmcconfig/lmcconfig.8 233992 2012-04-07 09:05:=
30Z joel $
 .\"
 .Dd October 3, 2005
 .Dt LMCCONFIG 8
@@ -186,7 +186,7 @@
 .Ar number .
 .Pp
 .Bl -column "99" "payload" "inward thru drvrs/rcvrsxxx" "HSSI, SSI" -offse=
t 1m -compact=20
-.It  "1" Ta "none"    Ta "default"
+.It  "1" Ta "none"    Ta "default"                 Ta \&
 .It  "2" Ta "payload" Ta "outward thru framer"     Ta "T1E1. T3"
 .It  "3" Ta "line"    Ta "outward thru line if"    Ta "T1E1, T3, HSSIc"
 .It  "4" Ta "other"   Ta "inward thru line if"     Ta "T1E1, T3"
@@ -443,7 +443,7 @@
 .It " 16" Ta "7.5 dB"  Ta "FCC option B"
 .It " 32" Ta "15 dB"   Ta "FCC option C"
 .It " 48" Ta "22.5 dB" Ta "final span"
-.It "255" Ta "auto-set based on cable length (default)"
+.It "255" Ta "auto-set based on cable length (default)" Ta \&
 .El
 .Pp
 This is only applicable if the pulse shape is T1-CSU.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/lpr/lpc/cmds.c
--- a/head/usr.sbin/lpr/lpc/cmds.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/lpr/lpc/cmds.c	Tue Apr 17 11:51:51 2012 +0300
@@ -41,7 +41,7 @@
 #endif
=20
 #include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
-__FBSDID("$FreeBSD: head/usr.sbin/lpr/lpc/cmds.c 231723 2012-02-15 02:01:2=
4Z kevlo $");
+__FBSDID("$FreeBSD: head/usr.sbin/lpr/lpc/cmds.c 234244 2012-04-13 22:34:0=
1Z delphij $");
=20
 /*
  * lpc -- line printer control program -- commands:
@@ -79,7 +79,7 @@
 static int	 doarg(char *_job);
 static int	 doselect(const struct dirent *_d);
 static int	 kill_qtask(const char *lf);
-static int	 sortq(const void *_a, const void *_b);
+static int	 sortq(const struct dirent **a, const struct dirent **b);
 static int	 touch(struct jobqueue *_jq);
 static void	 unlinkf(char *_name);
 static void	 upstat(struct printer *_pp, const char *_msg, int _notify);
@@ -486,14 +486,14 @@
  *   filenames (they will have datafile names which start with `dfB*').
  */
 static int
-sortq(const void *a, const void *b)
+sortq(const struct dirent **a, const struct dirent **b)
 {
 	const int a_lt_b =3D -1, a_gt_b =3D 1, cat_other =3D 10;
 	const char *fname_a, *fname_b, *jnum_a, *jnum_b;
 	int cat_a, cat_b, ch, res, seq_a, seq_b;
=20
-	fname_a =3D (*(const struct dirent * const *)a)->d_name;
-	fname_b =3D (*(const struct dirent * const *)b)->d_name;
+	fname_a =3D (*a)->d_name;
+	fname_b =3D (*b)->d_name;
=20
 	/*
 	 * First separate filenames into categories.  Categories are
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/lpr/lpr/printcap.5
--- a/head/usr.sbin/lpr/lpr/printcap.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/lpr/lpr/printcap.5	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)printcap.5	8.2 (Berkeley) 12/11/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/lpr/lpr/printcap.5 233510 2012-03-26 15:18:14Z=
 joel $
 .\"
 .Dd October 11, 2000
 .Dt PRINTCAP 5
@@ -72,7 +72,7 @@
 .Xr termcap 5
 for a description of the file layout.
 .Bl -column Namexxx Typexx "/var/spool/lpdxxxxx"
-.Sy "Name	Type	Default	Description
+.Sy "Name	Type	Default	Description"
 .It "af	str" Ta Dv NULL Ta No "name of accounting file"
 .It "br	num	none	if lp is a tty, set the baud rate"
 .Xr ( ioctl 2
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/makefs/cd9660/cd9660_elt=
orito.c
--- a/head/usr.sbin/makefs/cd9660/cd9660_eltorito.c	Tue Apr 17 11:36:47 201=
2 +0300
+++ b/head/usr.sbin/makefs/cd9660/cd9660_eltorito.c	Tue Apr 17 11:51:51 201=
2 +0300
@@ -36,7 +36,7 @@
 #include "cd9660_eltorito.h"
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.sbin/makefs/cd9660/cd9660_eltorito.c 228990 2=
011-12-30 10:58:14Z uqs $");
+__FBSDID("$FreeBSD: head/usr.sbin/makefs/cd9660/cd9660_eltorito.c 233783 2=
012-04-02 16:26:32Z andreast $");
=20
 #ifdef DEBUG
 #define	ELTORITO_DPRINTF(__x)	printf __x
@@ -538,9 +538,19 @@
     off_t sector_start, off_t nsectors, off_t sector_size,
     const char *part_name, const char *part_type)
 {
-	uint32_t apm32;
+	uint32_t apm32, part_status;
 	uint16_t apm16;
=20
+	/* See Apple Tech Note 1189 for the details about the pmPartStatus
+	 * flags.
+	 * Below the flags which are default:
+	 * - IsValid     0x01
+	 * - IsAllocated 0x02
+	 * - IsReadable  0x10
+	 * - IsWritable  0x20
+	 */
+	part_status =3D 0x01 | 0x02 | 0x10 | 0x20;
+
 	if (fseeko(fd, (off_t)(idx + 1) * sector_size, SEEK_SET) =3D=3D -1)
 		err(1, "fseeko");
=20
@@ -562,6 +572,17 @@
 	fwrite(part_name, strlen(part_name) + 1, 1, fd);
 	fseek(fd, 32 - strlen(part_name) - 1, SEEK_CUR);
 	fwrite(part_type, strlen(part_type) + 1, 1, fd);
+	fseek(fd, 32 - strlen(part_type) - 1, SEEK_CUR);
+
+	apm32 =3D 0;
+	/* pmLgDataStart */
+        fwrite(&apm32, sizeof(apm32), 1, fd);
+	/* pmDataCnt */=20
+	apm32 =3D htobe32(nsectors);
+        fwrite(&apm32, sizeof(apm32), 1, fd);
+	/* pmPartStatus */
+	apm32 =3D htobe32(part_status);
+        fwrite(&apm32, sizeof(apm32), 1, fd);
=20
 	return 0;
 }
@@ -666,12 +687,6 @@
 		cd9660_write_apm_partition_entry(fd, 0, total_parts, 1,
 		    total_parts, 512, "Apple", "Apple_partition_map");
=20
-		/* Write ISO9660 descriptor, enclosing the whole disk */
-		cd9660_write_apm_partition_entry(fd, 1, total_parts, 0,
-		    diskStructure.totalSectors *
-		    (diskStructure.sectorSize / 512), 512, "ISO9660",
-		    "CD_ROM_Mode_1");
-
 		/* Write all partition entries */
 		apm_partitions =3D 0;
 		TAILQ_FOREACH(t, &diskStructure.boot_images, image_list) {
@@ -679,11 +694,16 @@
 				continue;
=20
 			cd9660_write_apm_partition_entry(fd,
-			    2 + apm_partitions++, total_parts,
+			    1 + apm_partitions++, total_parts,
 			    t->sector * (diskStructure.sectorSize / 512),
 			    t->num_sectors * (diskStructure.sectorSize / 512),
 			    512, "CD Boot", "Apple_Bootstrap");
 		}
+		/* Write ISO9660 descriptor, enclosing the whole disk */
+                cd9660_write_apm_partition_entry(fd, 2 + apm_partitions,
+		    total_parts, 0, diskStructure.totalSectors *
+		    (diskStructure.sectorSize / 512), 512, "ISO9660",
+		    "CD_ROM_Mode_1");
 	}
=20
 	return 0;
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/mfiutil/mfi_config.c
--- a/head/usr.sbin/mfiutil/mfi_config.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/mfiutil/mfi_config.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.sbin/mfiutil/mfi_config.c 228119 2011-11-29 08:16:14=
Z delphij $
+ * $FreeBSD: head/usr.sbin/mfiutil/mfi_config.c 233713 2012-03-30 23:39:39=
Z ambrisko $
  */
=20
 #include <sys/param.h>
@@ -211,9 +211,8 @@
 }
 MFI_COMMAND(top, clear, clear_config);
=20
-#define	MFI_ARRAY_SIZE		288
-#define	MAX_DRIVES_PER_ARRAY						\
-	((MFI_ARRAY_SIZE - sizeof(struct mfi_array)) / 8)
+#define MAX_DRIVES_PER_ARRAY MFI_MAX_ROW_SIZE
+#define MFI_ARRAY_SIZE sizeof(struct mfi_array)
=20
 #define	RT_RAID0	0
 #define	RT_RAID1	1
@@ -305,7 +304,7 @@
=20
 	/* Validate the number of drives for this array. */
 	if (count >=3D MAX_DRIVES_PER_ARRAY) {
-		warnx("Too many drives for a single array: max is %zu",
+		warnx("Too many drives for a single array: max is %d",
 		    MAX_DRIVES_PER_ARRAY);
 		return (EINVAL);
 	}
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/mfiutil/mfi_drive.c
--- a/head/usr.sbin/mfiutil/mfi_drive.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/mfiutil/mfi_drive.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.sbin/mfiutil/mfi_drive.c 223345 2011-06-20 21:28:50Z=
 bz $
+ * $FreeBSD: head/usr.sbin/mfiutil/mfi_drive.c 233713 2012-03-30 23:39:39Z=
 ambrisko $
  */
=20
 #include <sys/types.h>
@@ -149,7 +149,7 @@
 	case MFI_PD_STATE_COPYBACK:
 		return ("COPYBACK");
 	case MFI_PD_STATE_SYSTEM:
-		return ("SYSTEM");
+		return ("JBOD");
 	default:
 		sprintf(buf, "PSTATE 0x%04x", state);
 		return (buf);
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/mfiutil/mfiutil.8
--- a/head/usr.sbin/mfiutil/mfiutil.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/mfiutil/mfiutil.8	Tue Apr 17 11:51:51 2012 +0300
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/mfiutil/mfiutil.8 225331 2011-09-02 16:00:51Z =
jhb $
+.\" $FreeBSD: head/usr.sbin/mfiutil/mfiutil.8 233522 2012-03-26 21:22:53Z =
joel $
 .\"
 .Dd September 2, 2011
 .Dt MFIUTIL 8
@@ -250,7 +250,7 @@
 The default class is
 .Dq warn .
 The available classes from lowest priority to highest are:
-.Bl -tag -width -indent
+.Bl -tag -width indent
 .It Cm debug
 Debug messages.
 .It Cm progress
@@ -300,7 +300,7 @@
 parameters.
 Each of these parameters can either be specified as a log entry number or =
as
 one of the following aliases:
-.Bl -tag -width -indent
+.Bl -tag -width indent
 .It Cm newest
 The newest entry in the event log.
 .It Cm oldest
@@ -597,7 +597,6 @@
 patrol read starting in 5 minutes:
 .Pp
 .Dl Nm Cm patrol auto 604800 300
-.Pp
 .Sh SEE ALSO
 .Xr mfi 4
 .Sh HISTORY
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/mountd/exports.5
--- a/head/usr.sbin/mountd/exports.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/mountd/exports.5	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)exports.5	8.3 (Berkeley) 3/29/95
-.\" $FreeBSD: head/usr.sbin/mountd/exports.5 223954 2011-07-12 14:04:36Z r=
macklem $
+.\" $FreeBSD: head/usr.sbin/mountd/exports.5 233648 2012-03-29 05:02:12Z e=
adler $
 .\"
 .Dd July 12, 2011
 .Dt EXPORTS 5
@@ -73,7 +73,7 @@
 The first is to list all mount points as absolute
 directory paths separated by whitespace.
 This list of directory paths should be considered an
-.Dq administrative control ,=20
+.Dq administrative control ,
 since it is only enforced by the
 .Xr mountd 8
 daemon and not the kernel.
@@ -90,7 +90,7 @@
 .Xr mountd 8 .
 Because NFSv4 does not use the mount protocol,
 the
-.Dq administrative controls=20
+.Dq administrative controls
 are not applied.
 Thus, all the above export line(s) should be considered to have the
 .Fl alldirs
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/mptutil/mptutil.8
--- a/head/usr.sbin/mptutil/mptutil.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/mptutil/mptutil.8	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/mptutil/mptutil.8 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd August 16, 2009
 .Dt MPTUTIL 8
@@ -70,7 +70,7 @@
 .Cm volume status Ar volume
 .Nm
 .Op Fl u Ar unit
-.Cm volume cache Ar volume=20
+.Cm volume cache Ar volume
 .Ar enable|disable
 .Nm
 .Op Fl u Ar unit
@@ -354,7 +354,6 @@
 utility first appeared in
 .Fx 8.0 .
 .Sh BUGS
-.Pp
 The handling of spare drives appears to be unreliable.
 The
 .Xr mpt 4
@@ -387,7 +386,7 @@
 .Pp
 The mpt version 1 API that is used by
 .Nm
-and=20
+and
 .Xr mpt 4
 doesn't support volumes above two terabytes.
 This is a limitation of the API.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/mtest/mtest.8
--- a/head/usr.sbin/mtest/mtest.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/mtest/mtest.8	Tue Apr 17 11:51:51 2012 +0300
@@ -24,7 +24,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE =
OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/mtest/mtest.8 233455 2012-03-25 09:18:34Z joel=
 $
 .\"
 .Dd April 29, 2009
 .Dt MTEST 8
@@ -159,7 +159,6 @@
 For IPv4, the program will perform
 a lookup of the primary IP address based on the interface name.
 This may fail if no primary IP address is assigned.
-.Pp
 .Sh SEE ALSO
 .Rs
 .%A D. Thaler
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/mtree/mtree.5
--- a/head/usr.sbin/mtree/mtree.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/mtree/mtree.5	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     From: @(#)mtree.8       8.2 (Berkeley) 12/11/93
-.\" $FreeBSD: head/usr.sbin/mtree/mtree.5 227489 2011-11-13 17:06:33Z eadl=
er $
+.\" $FreeBSD: head/usr.sbin/mtree/mtree.5 233455 2012-03-25 09:18:34Z joel=
 $
 .\"
 .Dd December 31, 2007
 .Dt MTREE 5
@@ -223,7 +223,6 @@
 socket
 .El
 .El
-.Pp
 .Sh SEE ALSO
 .Xr cksum 1 ,
 .Xr find 1 ,
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/newsyslog/newsyslog.c
--- a/head/usr.sbin/newsyslog/newsyslog.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/newsyslog/newsyslog.c	Tue Apr 17 11:51:51 2012 +0300
@@ -54,7 +54,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 229654 2012-01-05 =
21:36:36Z uqs $");
+__FBSDID("$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 233257 2012-03-21 =
06:51:45Z glebius $");
=20
 #define	OSF
=20
@@ -484,12 +484,14 @@
 	fk_entry free_or_keep;
 	double diffsecs;
 	char temp_reason[REASON_MAX];
+	int oversized;
=20
 	free_or_keep =3D FREE_ENT;
 	if (verbose)
 		printf("%s <%d%s>: ", ent->log, ent->numlogs,
 		    compress_type[ent->compress].flag);
 	ent->fsize =3D sizefile(ent->log);
+	oversized =3D ((ent->trsize > 0) && (ent->fsize >=3D ent->trsize));
 	modtime =3D age_old_log(ent->log);
 	ent->rotate =3D 0;
 	ent->firstcreate =3D 0;
@@ -518,7 +520,8 @@
 			printf("does not exist, skipped%s.\n", temp_reason);
 		}
 	} else {
-		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
+		if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
+		    !oversized) {
 			diffsecs =3D ptimeget_diff(timenow, ent->trim_at);
 			if (diffsecs < 0.0) {
 				/* trim_at is some time in the future. */
@@ -574,7 +577,7 @@
 		} else if (force) {
 			ent->rotate =3D 1;
 			snprintf(temp_reason, REASON_MAX, " due to -F request");
-		} else if ((ent->trsize > 0) && (ent->fsize >=3D ent->trsize)) {
+		} else if (oversized) {
 			ent->rotate =3D 1;
 			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
 			    ent->trsize);
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/newsyslog/newsyslog.conf=
.5
--- a/head/usr.sbin/newsyslog/newsyslog.conf.5	Tue Apr 17 11:36:47 2012 +03=
00
+++ b/head/usr.sbin/newsyslog/newsyslog.conf.5	Tue Apr 17 11:51:51 2012 +03=
00
@@ -5,7 +5,7 @@
 .\" This file contains changes from the Open Software Foundation.
 .\"
 .\"     from: @(#)newsyslog.8
-.\" $FreeBSD: head/usr.sbin/newsyslog/newsyslog.conf.5 221873 2011-05-14 0=
3:00:55Z sobomax $
+.\" $FreeBSD: head/usr.sbin/newsyslog/newsyslog.conf.5 233648 2012-03-29 0=
5:02:12Z eadler $
 .\"
 .\" Copyright 1988, 1989 by the Massachusetts Institute of Technology
 .\"
@@ -21,7 +21,7 @@
 .\" the suitability of this software for any purpose.  It is
 .\" provided "as is" without express or implied warranty.
 .\"
-.Dd February 25, 2011
+.Dd March 21, 2012
 .Dt NEWSYSLOG.CONF 5
 .Os
 .Sh NAME
@@ -130,7 +130,7 @@
 sign along with a rotation time specification of once
 a day, once a week, or once a month.
 .Pp
-If a time is specified, the log file will only be trimmed if
+Time based trimming happens only if
 .Xr newsyslog 8
 is run within one hour of the specified time.
 If an interval is specified, the log file will be trimmed if that many
@@ -304,7 +304,7 @@
 .It Cm R
 if this flag is set the
 .Xr newsyslog 8
-will run shell command defined in=20
+will run shell command defined in
 .Ar path_to_pid_cmd_file
 after rotation instead of trying to send signal to a process id
 stored in the file.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/nfsd/nfsv4.4
--- a/head/usr.sbin/nfsd/nfsv4.4	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/nfsd/nfsv4.4	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/nfsd/nfsv4.4 221976 2011-05-15 22:46:45Z rmack=
lem $
+.\" $FreeBSD: head/usr.sbin/nfsd/nfsv4.4 233455 2012-03-25 09:18:34Z joel $
 .\"
 .Dd May 15, 2011
 .Dt NFSV4 4
@@ -152,7 +152,6 @@
 with RPCSEC_GSS (sec=3Dkrb5, krb5i, krb5p), only names and KerberosV ticke=
ts
 will go on the wire.
 .Sh SERVER SETUP
-.Pp
 To set up the NFS server that supports
 .Nm ,
 you will need to either set the variables in
@@ -219,7 +218,6 @@
 .Xr config 5
 file.
 .Sh CLIENT MOUNTS
-.Pp
 To do an
 .Nm
 mount, specify the ``nfsv4'' option on the
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/ntp/doc/ntp-keygen.8
--- a/head/usr.sbin/ntp/doc/ntp-keygen.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/ntp/doc/ntp-keygen.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/ntp/doc/ntp-keygen.8 233455 2012-03-25 09:18:3=
4Z joel $
 .\"
 .Dd May 17, 2006
 .Dt NTP-KEYGEN 8
@@ -197,7 +197,6 @@
 as the subject and issuer fields, respectively, of the certificate.
 The owner name is also used for the host and sign key files,
 while the trusted name is used for the identity files.
-.Pp
 .Ss Trusted Hosts and Groups
 Each cryptographic configuration involves selection of a signature scheme
 and identification scheme, called a cryptotype,
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/ntp/doc/ntpdate.8
--- a/head/usr.sbin/ntp/doc/ntpdate.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/ntp/doc/ntpdate.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/ntp/doc/ntpdate.8 233455 2012-03-25 09:18:34Z =
joel $
 .\"
 .Dd May 17, 2006
 .Dt NTPDATE 8
@@ -18,7 +18,6 @@
 .Op Fl t Ar timeout
 .Ar server ...
 .Sh DESCRIPTION
-.Pp
 .Em Note :
 The functionality of this program is now available
 in the
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/pciconf/pciconf.8
--- a/head/usr.sbin/pciconf/pciconf.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/pciconf/pciconf.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/pciconf/pciconf.8 233648 2012-03-29 05:02:12Z =
eadler $
 .\"
 .Dd November 7, 2007
 .Dt PCICONF 8
@@ -185,7 +185,7 @@
 .Li pci Ns Va bus Ns \&: Ns Va device Ns \&: Ns Va function Ns , or
 .Li pci Ns Va bus Ns \&: Ns Va device Ns .
 In case of an abridged form, omitted selector components are assumed to be=
 0.
-An optional leading device name followed by @ and an optional final colon=20
+An optional leading device name followed by @ and an optional final colon
 will be ignored; this is so that the first column in the output of
 .Nm
 .Fl l
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/pkg_install/updating/pkg=
_updating.1
--- a/head/usr.sbin/pkg_install/updating/pkg_updating.1	Tue Apr 17 11:36:47=
 2012 +0300
+++ b/head/usr.sbin/pkg_install/updating/pkg_updating.1	Tue Apr 17 11:51:51=
 2012 +0300
@@ -1,6 +1,6 @@
 .\"
-.\" FreeBSD updating - Scan the installed ports and show all UPDATING entr=
ies=20
-.\"	that affect one of the installed ports. Alternative a list of portname=
s=20
+.\" FreeBSD updating - Scan the installed ports and show all UPDATING entr=
ies
+.\"	that affect one of the installed ports. Alternative a list of portnames
 .\" could be passed to pkg_updating
 .\"
 .\" "THE BEER-WARE LICENSE" (Revision 42):
@@ -8,7 +8,7 @@
 .\" can do whatever you want with this stuff. If we meet some day, and you=
 think
 .\" this stuff is worth it, you can buy me a beer in return.          Beat=
 G=C3=A4tzi
 .\"
-.\" $FreeBSD: head/usr.sbin/pkg_install/updating/pkg_updating.1 228976 201=
1-12-30 00:59:08Z uqs $
+.\" $FreeBSD: head/usr.sbin/pkg_install/updating/pkg_updating.1 233648 201=
2-03-29 05:02:12Z eadler $
 .\"
 .Dd May 30, 2008
 .Dt PKG_UPDATING 1
@@ -37,7 +37,7 @@
 Only entries newer than
 .Ar date
 are shown. Use a YYYYMMDD date format.
-.It Fl f , -file Ar file=20
+.It Fl f , -file Ar file
 Defines a alternative location of the UPDATING
 .Ar file .
 .It Fl h , -help
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/pmcstat/pmcpl_calltree.c
--- a/head/usr.sbin/pmcstat/pmcpl_calltree.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/pmcstat/pmcpl_calltree.c	Tue Apr 17 11:51:51 2012 +0300
@@ -1,5 +1,5 @@
 /*-
- * Copyright (c) 2009, Fabien Thomas
+ * Copyright (c) 2012, Fabien Thomas
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -32,7 +32,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.sbin/pmcstat/pmcpl_calltree.c 228990 2011-12-=
30 10:58:14Z uqs $");
+__FBSDID("$FreeBSD: head/usr.sbin/pmcstat/pmcpl_calltree.c 233611 2012-03-=
28 16:23:40Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/endian.h>
@@ -58,20 +58,18 @@
 #include "pmcstat_top.h"
 #include "pmcpl_calltree.h"
=20
-#define PMCPL_CT_GROWSIZE	4
-
-static pmcstat_interned_string pmcpl_ct_prevfn;
+#define	PMCPL_CT_GROWSIZE	4
=20
 static int pmcstat_skiplink =3D 0;
=20
 struct pmcpl_ct_node;
=20
 /* Get the sample value for PMC a. */
-#define PMCPL_CT_SAMPLE(a, b) \
+#define	PMCPL_CT_SAMPLE(a, b) \
 	((a) < (b)->npmcs ? (b)->sb[a] : 0)
=20
 /* Get the sample value in percent related to rsamples. */
-#define PMCPL_CT_SAMPLEP(a, b) \
+#define	PMCPL_CT_SAMPLEP(a, b) \
 	(PMCPL_CT_SAMPLE(a, b) * 100.0 / rsamples->sb[a])
=20
 struct pmcpl_ct_sample {
@@ -95,10 +93,13 @@
  * Each calltree node is tracked by a pmcpl_ct_node struct.
  */
 struct pmcpl_ct_node {
-#define PMCPL_PCT_TAG	0x00000001	/* Loop detection. */
-	uint32_t		pct_flags;
 	struct pmcstat_image	*pct_image;
 	uintfptr_t		pct_func;
+
+	struct pmcstat_symbol	*pct_sym;
+	pmcstat_interned_string	pct_ifl;
+	pmcstat_interned_string	pct_ifn;
+
 	struct pmcpl_ct_sample	pct_samples;
=20
 	int			pct_narc;
@@ -109,17 +110,25 @@
 	int			pct_ninstr;
 	int			pct_instr_c;
 	struct pmcpl_ct_instr	*pct_instr;
+
+#define PMCPL_PCT_ADDR	0
+#define PMCPL_PCT_NAME	1
+	char			pct_type;
+#define	PMCPL_PCT_WHITE	0
+#define	PMCPL_PCT_GREY	1
+#define	PMCPL_PCT_BLACK	2
+	char			pct_color;
 };
=20
 struct pmcpl_ct_node_hash {
 	struct pmcpl_ct_node  *pch_ctnode;
-	LIST_ENTRY(pmcpl_ct_node_hash) pch_next;
+	STAILQ_ENTRY(pmcpl_ct_node_hash) pch_next;
 };
=20
 struct pmcpl_ct_sample pmcpl_ct_callid;
=20
-#define PMCPL_CT_MAXCOL		PMC_CALLCHAIN_DEPTH_MAX=09
-#define PMCPL_CT_MAXLINE	1024	/* TODO: dynamic. */
+#define	PMCPL_CT_MAXCOL		PMC_CALLCHAIN_DEPTH_MAX
+#define	PMCPL_CT_MAXLINE	1024	/* TODO: dynamic. */
=20
 struct pmcpl_ct_line {
 	unsigned	ln_sum;
@@ -127,12 +136,13 @@
 };
=20
 struct pmcpl_ct_line	pmcpl_ct_topmax[PMCPL_CT_MAXLINE+1];
-struct pmcpl_ct_node	*pmcpl_ct_topscreen[PMCPL_CT_MAXCOL+1][PMCPL_CT_MAXLI=
NE+1];
+struct pmcpl_ct_node
+    *pmcpl_ct_topscreen[PMCPL_CT_MAXCOL+1][PMCPL_CT_MAXLINE+1];
=20
 /*
  * All nodes indexed by function/image name are placed in a hash table.
  */
-static LIST_HEAD(,pmcpl_ct_node_hash) pmcpl_ct_node_hash[PMCSTAT_NHASH];
+static STAILQ_HEAD(,pmcpl_ct_node_hash) pmcpl_ct_node_hash[PMCSTAT_NHASH];
=20
 /*
  * Root node for the graph.
@@ -256,7 +266,8 @@
  */
=20
 static void
-pmcpl_ct_instr_add(struct pmcpl_ct_node *ct, int pmcin, uintfptr_t pc)
+pmcpl_ct_instr_add(struct pmcpl_ct_node *ct, int pmcin,
+    uintfptr_t pc, unsigned v)
 {
 	int i;
 	struct pmcpl_ct_instr *in;
@@ -265,7 +276,7 @@
 		if (ct->pct_instr[i].pctf_func =3D=3D pc) {
 			in =3D &ct->pct_instr[i];
 			pmcpl_ct_samples_grow(&in->pctf_samples);
-			in->pctf_samples.sb[pmcin]++;
+			in->pctf_samples.sb[pmcin] +=3D v;
 			return;
 		}
 	}
@@ -275,7 +286,7 @@
 	in->pctf_func =3D pc;
 	pmcpl_ct_samples_init(&in->pctf_samples);
 	pmcpl_ct_samples_grow(&in->pctf_samples);
-	in->pctf_samples.sb[pmcin] =3D 1;
+	in->pctf_samples.sb[pmcin] =3D v;
 	ct->pct_ninstr++;
 }
=20
@@ -284,18 +295,18 @@
  */
=20
 static struct pmcpl_ct_node *
-pmcpl_ct_node_allocate(struct pmcstat_image *image, uintfptr_t pc)
+pmcpl_ct_node_allocate(void)
 {
 	struct pmcpl_ct_node *ct;
=20
 	if ((ct =3D malloc(sizeof(*ct))) =3D=3D NULL)
 		err(EX_OSERR, "ERROR: Cannot allocate callgraph node");
=20
-	ct->pct_flags	=3D 0;
-	ct->pct_image 	=3D image;
-	ct->pct_func	=3D pc;
+	pmcpl_ct_samples_init(&ct->pct_samples);
=20
-	pmcpl_ct_samples_init(&ct->pct_samples);
+	ct->pct_sym	=3D NULL;
+	ct->pct_image	=3D NULL;
+	ct->pct_func	=3D 0;
=20
 	ct->pct_narc	=3D 0;
 	ct->pct_arc_c	=3D 0;
@@ -305,6 +316,8 @@
 	ct->pct_instr_c	=3D 0;
 	ct->pct_instr	=3D NULL;
=20
+	ct->pct_color   =3D PMCPL_PCT_WHITE;
+
 	return (ct);
 }
=20
@@ -338,10 +351,10 @@
 	struct pmcpl_ct_node_hash *pch;
=20
 	for (i =3D 0; i < PMCSTAT_NHASH; i++)
-		LIST_FOREACH(pch, &pmcpl_ct_node_hash[i], pch_next)
-			pch->pch_ctnode->pct_flags &=3D ~PMCPL_PCT_TAG;
+		STAILQ_FOREACH(pch, &pmcpl_ct_node_hash[i], pch_next)
+			pch->pch_ctnode->pct_color =3D PMCPL_PCT_WHITE;
=20
-	pmcpl_ct_root->pct_flags &=3D ~PMCPL_PCT_TAG;
+	pmcpl_ct_root->pct_color =3D PMCPL_PCT_WHITE;
 }
=20
 /*
@@ -355,11 +368,9 @@
 	int i, terminal;
 	struct pmcpl_ct_arc *arc;
=20
-	if (ct->pct_flags & PMCPL_PCT_TAG)
+	if (ct->pct_color =3D=3D PMCPL_PCT_GREY)
 		return 0;
=20
-	ct->pct_flags |=3D PMCPL_PCT_TAG;
-
 	if (x >=3D PMCPL_CT_MAXCOL) {
 		pmcpl_ct_topscreen[x][*y] =3D NULL;
 		return 1;
@@ -374,11 +385,11 @@
 	terminal =3D 1;
 	for (i =3D 0; i < ct->pct_narc; i++) {
 		arc =3D &ct->pct_arc[i];
-		if (PMCPL_CT_SAMPLE(pmcin,
+		if (arc->pcta_child->pct_color !=3D PMCPL_PCT_GREY &&
+		    PMCPL_CT_SAMPLE(pmcin,
 		    &arc->pcta_samples) !=3D 0 &&
 		    PMCPL_CT_SAMPLEP(pmcin,
-		    &arc->pcta_samples) > pmcstat_threshold &&
-		    (arc->pcta_child->pct_flags & PMCPL_PCT_TAG) =3D=3D 0) {
+		    &arc->pcta_samples) > pmcstat_threshold) {
 			terminal =3D 0;
 			break;
 		}
@@ -395,6 +406,7 @@
 		return 0;
 	}
=20
+	ct->pct_color =3D PMCPL_PCT_GREY;
 	for (i =3D 0; i < ct->pct_narc; i++) {
 		if (PMCPL_CT_SAMPLE(pmcin,
 		    &ct->pct_arc[i].pcta_samples) =3D=3D 0)
@@ -403,10 +415,13 @@
 		    &ct->pct_arc[i].pcta_samples) > pmcstat_threshold) {
 			if (pmcpl_ct_node_dumptop(pmcin,
 			        ct->pct_arc[i].pcta_child,
-			        rsamples, x+1, y))
+			        rsamples, x+1, y)) {
+				ct->pct_color =3D PMCPL_PCT_BLACK;
 				return 1;
+			}
 		}
 	}
+	ct->pct_color =3D PMCPL_PCT_BLACK;
=20
 	return 0;
 }
@@ -446,7 +461,6 @@
 	float v;
 	char ns[30], vs[10], is[20];
 	struct pmcpl_ct_node *ct;
-	struct pmcstat_symbol *sym;
 	const char *space =3D " ";
=20
 	/*
@@ -503,10 +517,9 @@
 				strlcpy(ns, ".", sizeof(ns));
 				ns_len =3D 1;
 			} else {
-			sym =3D pmcstat_symbol_search(ct->pct_image, ct->pct_func);
-			if (sym !=3D NULL) {
+			if (ct->pct_sym !=3D NULL) {
 				ns_len =3D snprintf(ns, sizeof(ns), "%s",
-				    pmcstat_string_unintern(sym->ps_name));
+				    pmcstat_string_unintern(ct->pct_sym->ps_name));
 			} else
 				ns_len =3D snprintf(ns, sizeof(ns), "%p",
 				    (void *)ct->pct_func);
@@ -547,7 +560,6 @@
=20
 	rsamples =3D &r;
 	pmcpl_ct_samples_root(rsamples);
-
 	pmcpl_ct_node_cleartag();
=20
 	PMCSTAT_PRINTW("%5.5s %s\n", "%SAMP", "CALLTREE");
@@ -589,81 +601,92 @@
  * `ppm'.
  */
=20
-static struct pmcpl_ct_node *
-pmcpl_ct_node_hash_lookup_pc(struct pmcpl_ct_node *parent,
-    struct pmcstat_pcmap *ppm, uintfptr_t pc, int pmcin)
+static void
+pmcpl_ct_node_update(struct pmcpl_ct_node *parent,
+    struct pmcpl_ct_node *child, int pmcin, unsigned v, int cd)
 {
-	struct pmcstat_symbol *sym;
-	struct pmcstat_image *image;
-	struct pmcpl_ct_node *ct;
-	struct pmcpl_ct_node_hash *h;
 	struct pmcpl_ct_arc *arc;
-	uintfptr_t loadaddress;
 	int i;
-	unsigned int hash;
=20
 	assert(parent !=3D NULL);
=20
-	image =3D ppm->ppm_image;
-
-	loadaddress =3D ppm->ppm_lowpc + image->pi_vaddr - image->pi_start;
-	pc -=3D loadaddress;	/* Convert to an offset in the image. */
+	/*
+	 * Find related arc in parent node and
+	 * increment the sample count.
+	 */
+	for (i =3D 0; i < parent->pct_narc; i++) {
+		if (parent->pct_arc[i].pcta_child =3D=3D child) {
+			arc =3D &parent->pct_arc[i];
+			pmcpl_ct_samples_grow(&arc->pcta_samples);
+			arc->pcta_samples.sb[pmcin] +=3D v;
+			/* Estimate call count. */
+			if (cd) {
+			pmcpl_ct_samples_grow(&arc->pcta_callid);
+			if (pmcpl_ct_callid.sb[pmcin] -
+			    arc->pcta_callid.sb[pmcin] > 1)
+				arc->pcta_call++;
+			arc->pcta_callid.sb[pmcin] =3D
+			    pmcpl_ct_callid.sb[pmcin];
+			}
+			return;
+		}
+	}
=20
 	/*
-	 * Try determine the function at this offset.  If we can't
-	 * find a function round leave the `pc' value alone.
+	 * No arc found for us, add ourself to the parent.
 	 */
-	if ((sym =3D pmcstat_symbol_search(image, pc)) !=3D NULL)
-		pc =3D sym->ps_start;
-	else
-		pmcstat_stats.ps_samples_unknown_function++;
+	pmcpl_ct_arc_grow(parent->pct_narc,
+	    &parent->pct_arc_c, &parent->pct_arc);
+	arc =3D &parent->pct_arc[parent->pct_narc];
+	pmcpl_ct_samples_grow(&arc->pcta_samples);
+	arc->pcta_samples.sb[pmcin] =3D v;
+	arc->pcta_call =3D 1;
+	if (cd) {
+		pmcpl_ct_samples_grow(&arc->pcta_callid);
+		arc->pcta_callid.sb[pmcin] =3D pmcpl_ct_callid.sb[pmcin];
+	}
+	arc->pcta_child =3D child;
+	parent->pct_narc++;
+}
+
+/*
+ * Lookup by image/pc.
+ */
+
+static struct pmcpl_ct_node *
+pmcpl_ct_node_hash_lookup(struct pmcstat_image *image, uintfptr_t pc,
+    struct pmcstat_symbol *sym, char *fl, char *fn)
+{
+	int i;
+	unsigned int hash;
+	struct pmcpl_ct_node *ct;
+	struct pmcpl_ct_node_hash *h;
+	pmcstat_interned_string	ifl, ifn;
+
+	if (fn !=3D NULL) {
+		ifl =3D pmcstat_string_intern(fl);
+		ifn =3D pmcstat_string_intern(fn);
+	} else {
+		ifl =3D 0;
+		ifn =3D 0;
+	}
=20
 	for (hash =3D i =3D 0; i < (int)sizeof(uintfptr_t); i++)
 		hash +=3D (pc >> i) & 0xFF;
=20
 	hash &=3D PMCSTAT_HASH_MASK;
=20
-	ct =3D NULL;
-	LIST_FOREACH(h, &pmcpl_ct_node_hash[hash], pch_next) {
+	STAILQ_FOREACH(h, &pmcpl_ct_node_hash[hash], pch_next) {
 		ct =3D h->pch_ctnode;
=20
 		assert(ct !=3D NULL);
=20
 		if (ct->pct_image =3D=3D image && ct->pct_func =3D=3D pc) {
-			/*
-			 * Find related arc in parent node and
-			 * increment the sample count.
-			 */
-			for (i =3D 0; i < parent->pct_narc; i++) {
-				if (parent->pct_arc[i].pcta_child =3D=3D ct) {
-					arc =3D &parent->pct_arc[i];
-					pmcpl_ct_samples_grow(&arc->pcta_samples);
-					arc->pcta_samples.sb[pmcin]++;
-					/* Estimate call count. */
-					pmcpl_ct_samples_grow(&arc->pcta_callid);
-					if (pmcpl_ct_callid.sb[pmcin] -
-					    arc->pcta_callid.sb[pmcin] > 1)
-						arc->pcta_call++;
-					arc->pcta_callid.sb[pmcin] =3D
-					    pmcpl_ct_callid.sb[pmcin];
-					return (ct);
-				}
-			}
-
-			/*
-			 * No arc found for us, add ourself to the parent.
-			 */
-			pmcpl_ct_arc_grow(parent->pct_narc,
-			    &parent->pct_arc_c, &parent->pct_arc);
-			arc =3D &parent->pct_arc[parent->pct_narc];
-			pmcpl_ct_samples_grow(&arc->pcta_samples);
-			arc->pcta_samples.sb[pmcin] =3D 1;
-			arc->pcta_call =3D 1;
-			pmcpl_ct_samples_grow(&arc->pcta_callid);
-			arc->pcta_callid.sb[pmcin] =3D pmcpl_ct_callid.sb[pmcin];
-			arc->pcta_child =3D ct;
-			parent->pct_narc++;
-			return (ct);
+			if (fn =3D=3D NULL)
+				return (ct);
+			if (ct->pct_type =3D=3D PMCPL_PCT_NAME &&
+			    ct->pct_ifl =3D=3D ifl && ct->pct_ifn =3D=3D ifn)
+				return (ct);
 		}
 	}
=20
@@ -671,23 +694,22 @@
 	 * We haven't seen this (pmcid, pc) tuple yet, so allocate a
 	 * new callgraph node and a new hash table entry for it.
 	 */
-	ct =3D pmcpl_ct_node_allocate(image, pc);
+	ct =3D pmcpl_ct_node_allocate();
 	if ((h =3D malloc(sizeof(*h))) =3D=3D NULL)
 		err(EX_OSERR, "ERROR: Could not allocate callgraph node");
=20
+	if (fn !=3D NULL) {
+		ct->pct_type =3D PMCPL_PCT_NAME;
+		ct->pct_ifl =3D ifl;
+		ct->pct_ifn =3D ifn;
+	} else
+		ct->pct_type =3D PMCPL_PCT_ADDR;
+	ct->pct_image =3D image;
+	ct->pct_func =3D pc;
+	ct->pct_sym =3D sym;
+
 	h->pch_ctnode =3D ct;
-	LIST_INSERT_HEAD(&pmcpl_ct_node_hash[hash], h, pch_next);
-
-	pmcpl_ct_arc_grow(parent->pct_narc,
-	    &parent->pct_arc_c, &parent->pct_arc);
-	arc =3D &parent->pct_arc[parent->pct_narc];
-	pmcpl_ct_samples_grow(&arc->pcta_samples);
-	arc->pcta_samples.sb[pmcin] =3D 1;
-	arc->pcta_call =3D 1;
-	pmcpl_ct_samples_grow(&arc->pcta_callid);
-	arc->pcta_callid.sb[pmcin] =3D pmcpl_ct_callid.sb[pmcin];
-	arc->pcta_child =3D ct;
-	parent->pct_narc++;
+	STAILQ_INSERT_HEAD(&pmcpl_ct_node_hash[hash], h, pch_next);
 	return (ct);
 }
=20
@@ -699,10 +721,14 @@
 pmcpl_ct_process(struct pmcstat_process *pp, struct pmcstat_pmcrecord *pmc=
r,
     uint32_t nsamples, uintfptr_t *cc, int usermode, uint32_t cpu)
 {
-	int n, pmcin;
+	int i, n, pmcin;
+	uintfptr_t pc, loadaddress;
+	struct pmcstat_image *image;
+	struct pmcstat_symbol *sym;
 	struct pmcstat_pcmap *ppm[PMC_CALLCHAIN_DEPTH_MAX];
 	struct pmcstat_process *km;
-	struct pmcpl_ct_node *parent, *child;
+	struct pmcpl_ct_node *ct;
+	struct pmcpl_ct_node *ctl[PMC_CALLCHAIN_DEPTH_MAX+1];
=20
 	(void) cpu;
=20
@@ -741,30 +767,114 @@
 	pmcpl_ct_callid.sb[pmcin]++;
=20
 	/*
-	 * Iterate remaining addresses.
+	 * Build node list.
 	 */
-	for (parent =3D pmcpl_ct_root, child =3D NULL; n >=3D 0; n--) {
-		child =3D pmcpl_ct_node_hash_lookup_pc(parent, ppm[n], cc[n],
-		    pmcin);
-		if (child =3D=3D NULL) {
+	ctl[0] =3D pmcpl_ct_root;
+	for (i =3D 1; n >=3D 0; n--) {
+		image =3D ppm[n]->ppm_image;
+		loadaddress =3D ppm[n]->ppm_lowpc +
+		    image->pi_vaddr - image->pi_start;
+		/* Convert to an offset in the image. */
+		pc =3D cc[n] - loadaddress;
+		/*
+		 * Try determine the function at this offset.  If we can't
+		 * find a function round leave the `pc' value alone.
+		 */
+		if ((sym =3D pmcstat_symbol_search(image, pc)) !=3D NULL)
+			pc =3D sym->ps_start;
+		else
+			pmcstat_stats.ps_samples_unknown_function++;
+
+		ct =3D pmcpl_ct_node_hash_lookup(image, pc, sym, NULL, NULL);
+		if (ct =3D=3D NULL) {
 			pmcstat_stats.ps_callchain_dubious_frames++;
 			continue;
 		}
-		parent =3D child;
+		ctl[i++] =3D ct;
 	}
+	/* No valid node found. */
+	if (i =3D=3D 1)
+		return;
+	n =3D i;
+
+	ct =3D ctl[0];
+	for (i =3D 1; i < n; i++)
+		pmcpl_ct_node_update(ctl[i-1], ctl[i], pmcin, 1, 1);
=20
 	/*
 	 * Increment the sample count for this PMC.
 	 */
-	if (child !=3D NULL) {
-		pmcpl_ct_samples_grow(&child->pct_samples);
-		child->pct_samples.sb[pmcin]++;
+	pmcpl_ct_samples_grow(&ctl[n-1]->pct_samples);
+	ctl[n-1]->pct_samples.sb[pmcin]++;
=20
-		/* Update per instruction sample if required. */
-		if (args.pa_ctdumpinstr)
-			pmcpl_ct_instr_add(child, pmcin, cc[0] -
-			    (ppm[0]->ppm_lowpc + ppm[0]->ppm_image->pi_vaddr -
-			     ppm[0]->ppm_image->pi_start));
+	/* Update per instruction sample if required. */
+	if (args.pa_ctdumpinstr)
+		pmcpl_ct_instr_add(ctl[n-1], pmcin, cc[0] -
+		    (ppm[0]->ppm_lowpc + ppm[0]->ppm_image->pi_vaddr -
+		     ppm[0]->ppm_image->pi_start), 1);
+}
+
+/*
+ * Print node child cost.
+ */
+
+static void
+pmcpl_ct_node_printchild(struct pmcpl_ct_node *ct, uintfptr_t paddr,
+    int pline)
+{
+	int i, j, line;
+	uintfptr_t addr;
+	struct pmcpl_ct_node *child;
+	char sourcefile[PATH_MAX];
+	char funcname[PATH_MAX];
+
+	/*
+	 * Child cost.
+	 * TODO: attach child cost to the real position in the funtion.
+	 * TODO: cfn=3D<fn> / call <ncall> addr(<fn>) / addr(call <fn>) <arccost>
+	 */
+	for (i=3D0 ; i<ct->pct_narc; i++) {
+		child =3D ct->pct_arc[i].pcta_child;
+		/* Object binary. */
+		fprintf(args.pa_graphfile, "cob=3D%s\n",
+		    pmcstat_string_unintern(child->pct_image->pi_fullpath));
+		/* Child function name. */
+		addr =3D child->pct_image->pi_vaddr + child->pct_func;
+		line =3D 0;
+		/* Child function source file. */
+		if (child->pct_type =3D=3D PMCPL_PCT_NAME) {
+			fprintf(args.pa_graphfile, "cfi=3D%s\ncfn=3D%s\n",
+			    pmcstat_string_unintern(child->pct_ifl),
+			    pmcstat_string_unintern(child->pct_ifn));
+		} else if (pmcstat_image_addr2line(child->pct_image, addr,
+		    sourcefile, sizeof(sourcefile), &line,
+		    funcname, sizeof(funcname))) {
+			fprintf(args.pa_graphfile, "cfi=3D%s\ncfn=3D%s\n",
+				sourcefile, funcname);
+		} else {
+			if (child->pct_sym !=3D NULL)
+				fprintf(args.pa_graphfile,
+				    "cfi=3D???\ncfn=3D%s\n",
+				    pmcstat_string_unintern(
+				        child->pct_sym->ps_name));
+			else
+				fprintf(args.pa_graphfile,
+				    "cfi=3D???\ncfn=3D%p\n", (void *)addr);
+		}
+
+		/* Child function address, line and call count. */
+		fprintf(args.pa_graphfile, "calls=3D%u %p %u\n",
+		    ct->pct_arc[i].pcta_call, (void *)addr, line);
+
+		/*
+		 * Call address, line, sample.
+		 * TODO: Associate call address to the right location.
+		 */
+		fprintf(args.pa_graphfile, "%p %u", (void *)paddr, pline);
+		for (j =3D 0; j<pmcstat_npmcs; j++)
+			fprintf(args.pa_graphfile, " %u",
+			    PMCPL_CT_SAMPLE(j, &ct->pct_arc[i].pcta_samples));
+		fprintf(args.pa_graphfile, "\n");
 	}
 }
=20
@@ -775,40 +885,37 @@
 static void
 pmcpl_ct_node_printself(struct pmcpl_ct_node *ct)
 {
-	int i, j, line;
-	uintptr_t addr;
-	struct pmcstat_symbol *sym;
+	int i, j, fline, line;
+	uintfptr_t faddr, addr;
 	char sourcefile[PATH_MAX];
 	char funcname[PATH_MAX];
=20
 	/*
 	 * Object binary.
 	 */
-#ifdef PMCPL_CT_OPTIMIZEFN
-	if (pmcpl_ct_prevfn !=3D ct->pct_image->pi_fullpath) {
-#endif
-		pmcpl_ct_prevfn =3D ct->pct_image->pi_fullpath;
-		fprintf(args.pa_graphfile, "ob=3D%s\n",
-		    pmcstat_string_unintern(pmcpl_ct_prevfn));
-#ifdef PMCPL_CT_OPTIMIZEFN
-	}
-#endif
+	fprintf(args.pa_graphfile, "ob=3D%s\n",
+	    pmcstat_string_unintern(ct->pct_image->pi_fullpath));
=20
 	/*
 	 * Function name.
 	 */
-	if (pmcstat_image_addr2line(ct->pct_image, ct->pct_func,
-	    sourcefile, sizeof(sourcefile), &line,
+	faddr =3D ct->pct_image->pi_vaddr + ct->pct_func;
+	fline =3D 0;
+	if (ct->pct_type =3D=3D PMCPL_PCT_NAME) {
+		fprintf(args.pa_graphfile, "fl=3D%s\nfn=3D%s\n",
+		    pmcstat_string_unintern(ct->pct_ifl),
+		    pmcstat_string_unintern(ct->pct_ifn));
+	} else if (pmcstat_image_addr2line(ct->pct_image, faddr,
+	    sourcefile, sizeof(sourcefile), &fline,
 	    funcname, sizeof(funcname))) {
-		fprintf(args.pa_graphfile, "fn=3D%s\n",
-		    funcname);
+		fprintf(args.pa_graphfile, "fl=3D%s\nfn=3D%s\n",
+		    sourcefile, funcname);
 	} else {
-		sym =3D pmcstat_symbol_search(ct->pct_image, ct->pct_func);
-		if (sym !=3D NULL)
-			fprintf(args.pa_graphfile, "fn=3D%s\n",
-			    pmcstat_string_unintern(sym->ps_name));
+		if (ct->pct_sym !=3D NULL)
+			fprintf(args.pa_graphfile, "fl=3D???\nfn=3D%s\n",
+			    pmcstat_string_unintern(ct->pct_sym->ps_name));
 		else
-			fprintf(args.pa_graphfile, "fn=3D%p\n",
+			fprintf(args.pa_graphfile, "fl=3D???\nfn=3D%p\n",
 			    (void *)(ct->pct_image->pi_vaddr + ct->pct_func));
 	}
=20
@@ -816,15 +923,18 @@
 	 * Self cost.
 	 */
 	if (ct->pct_ninstr > 0) {
+		/*
+		 * Per location cost.
+		 */
 		for (i =3D 0; i < ct->pct_ninstr; i++) {
 			addr =3D ct->pct_image->pi_vaddr +
 			    ct->pct_instr[i].pctf_func;
 			line =3D 0;
-			if (pmcstat_image_addr2line(ct->pct_image, addr,
+			pmcstat_image_addr2line(ct->pct_image, addr,
 			    sourcefile, sizeof(sourcefile), &line,
-			    funcname, sizeof(funcname)))
-				fprintf(args.pa_graphfile, "fl=3D%s\n", sourcefile);
-			fprintf(args.pa_graphfile, "%p %u", (void *)addr, line);
+			    funcname, sizeof(funcname));
+			fprintf(args.pa_graphfile, "%p %u",
+			    (void *)addr, line);
 			for (j =3D 0; j<pmcstat_npmcs; j++)
 				fprintf(args.pa_graphfile, " %u",
 				    PMCPL_CT_SAMPLE(j,
@@ -832,92 +942,153 @@
 			fprintf(args.pa_graphfile, "\n");
 		}
 	} else {
-		addr =3D ct->pct_image->pi_vaddr + ct->pct_func;
-		line =3D 0;
-		if (pmcstat_image_addr2line(ct->pct_image, addr,
-		    sourcefile, sizeof(sourcefile), &line,
-		    funcname, sizeof(funcname)))
-			fprintf(args.pa_graphfile, "fl=3D%s\n", sourcefile);
-		fprintf(args.pa_graphfile, "* *");
+		/* Global cost function cost. */
+		fprintf(args.pa_graphfile, "%p %u", (void *)faddr, fline);
 		for (i =3D 0; i<pmcstat_npmcs ; i++)
 			fprintf(args.pa_graphfile, " %u",
 			    PMCPL_CT_SAMPLE(i, &ct->pct_samples));
 		fprintf(args.pa_graphfile, "\n");
 	}
+
+	pmcpl_ct_node_printchild(ct, faddr, fline);
+}
+
+static void
+pmcpl_ct_printnode(struct pmcpl_ct_node *ct)
+{
+	int i;
+
+	if (ct =3D=3D pmcpl_ct_root) {
+		fprintf(args.pa_graphfile, "fn=3Droot\n");
+		fprintf(args.pa_graphfile, "0x0 1");
+		for (i =3D 0; i<pmcstat_npmcs ; i++)
+			fprintf(args.pa_graphfile, " 0");
+		fprintf(args.pa_graphfile, "\n");
+		pmcpl_ct_node_printchild(ct, 0, 0);
+	} else
+		pmcpl_ct_node_printself(ct);
 }
=20
 /*
- * Print node child cost.
+ * Breadth first traversal.
  */
=20
 static void
-pmcpl_ct_node_printchild(struct pmcpl_ct_node *ct)
+pmcpl_ct_bfs(struct pmcpl_ct_node *ct)
 {
-	int i, j, line;
-	uintptr_t addr;
-	struct pmcstat_symbol *sym;
+	int i;
+	struct pmcpl_ct_node_hash *pch, *pchc;
 	struct pmcpl_ct_node *child;
+	STAILQ_HEAD(,pmcpl_ct_node_hash) q;
+
+	STAILQ_INIT(&q);
+	if ((pch =3D malloc(sizeof(*pch))) =3D=3D NULL)
+		err(EX_OSERR, "ERROR: Cannot allocate queue");
+	pch->pch_ctnode =3D ct;
+	STAILQ_INSERT_TAIL(&q, pch, pch_next);
+	ct->pct_color =3D PMCPL_PCT_BLACK;
+
+	while (!STAILQ_EMPTY(&q)) {
+		pch =3D STAILQ_FIRST(&q);
+		STAILQ_REMOVE_HEAD(&q, pch_next);
+		pmcpl_ct_printnode(pch->pch_ctnode);
+		for (i =3D 0; i<pch->pch_ctnode->pct_narc; i++) {
+			child =3D pch->pch_ctnode->pct_arc[i].pcta_child;
+			if (child->pct_color =3D=3D PMCPL_PCT_WHITE) {
+				child->pct_color =3D PMCPL_PCT_BLACK;
+				if ((pchc =3D malloc(sizeof(*pchc))) =3D=3D NULL)
+					err(EX_OSERR,
+					    "ERROR: Cannot allocate queue");
+				pchc->pch_ctnode =3D child;
+				STAILQ_INSERT_TAIL(&q, pchc, pch_next);
+			}
+		}
+		free(pch);
+	}
+}
+
+/*
+ * Detect and fix inlined location.
+ */
+
+static void
+_pmcpl_ct_expand_inline(struct pmcpl_ct_node *ct)
+{
+	int i, j;
+	unsigned fline, line, v;
+	uintfptr_t faddr, addr, pc;
 	char sourcefile[PATH_MAX];
-	char funcname[PATH_MAX];
+	char ffuncname[PATH_MAX], funcname[PATH_MAX];
+	char buffer[PATH_MAX];
+	struct pmcpl_ct_node *child;
=20
 	/*
-	 * Child cost.
-	 * TODO: attach child cost to the real position in the function.
-	 * TODO: cfn=3D<fn> / call <ncall> addr(<fn>) / addr(call <fn>) <arccost>
+	 * Resolve parent and compare to each instr location.
 	 */
-	for (i=3D0 ; i<ct->pct_narc; i++) {
-		child =3D ct->pct_arc[i].pcta_child;
+	faddr =3D ct->pct_image->pi_vaddr + ct->pct_func;
+	fline =3D 0;
+	if (!pmcstat_image_addr2line(ct->pct_image, faddr,
+	    sourcefile, sizeof(sourcefile), &fline,
+	    ffuncname, sizeof(ffuncname)))
+		return;
=20
-		/* Object binary. */
-#ifdef PMCPL_CT_OPTIMIZEFN
-		if (pmcpl_ct_prevfn !=3D child->pct_image->pi_fullpath) {
-#endif
-			pmcpl_ct_prevfn =3D child->pct_image->pi_fullpath;
-			fprintf(args.pa_graphfile, "cob=3D%s\n",
-			    pmcstat_string_unintern(pmcpl_ct_prevfn));
-#if PMCPL_CT_OPTIMIZEFN
+	for (i =3D 0; i < ct->pct_ninstr; i++) {
+		addr =3D ct->pct_image->pi_vaddr +
+		    ct->pct_instr[i].pctf_func;
+		line =3D 0;
+		if (!pmcstat_image_addr2line(ct->pct_image, addr,
+		    sourcefile, sizeof(sourcefile), &line,
+		    funcname, sizeof(funcname)))
+			continue;
+
+		if (strcmp(funcname, ffuncname) =3D=3D 0)
+			continue;
+
+		/*
+		 * - Lookup/create inline node by function name.
+		 * - Move instr PMCs to the inline node.
+		 * - Link nodes.
+		 * The lookup create a specific node per image/pc.
+		 */
+		if (args.pa_verbosity >=3D 2)
+			fprintf(args.pa_printfile,
+			    "WARNING: inlined function at %p %s in %s\n",
+			    (void *)addr, funcname, ffuncname);
+
+		snprintf(buffer, sizeof(buffer), "%s@%s",
+			funcname, ffuncname);
+		child =3D pmcpl_ct_node_hash_lookup(ct->pct_image,
+		    ct->pct_func, ct->pct_sym, sourcefile, buffer);
+		assert(child !=3D NULL);
+		pc =3D ct->pct_instr[i].pctf_func;
+		for (j =3D 0; j<pmcstat_npmcs; j++) {
+			v =3D PMCPL_CT_SAMPLE(j,
+			    &ct->pct_instr[i].pctf_samples);
+			if (v =3D=3D 0)
+				continue;
+			pmcpl_ct_instr_add(child, j, pc, v);
+			pmcpl_ct_node_update(ct, child, j, v, 0);
+			if (j < ct->pct_samples.npmcs)
+				ct->pct_samples.sb[j] -=3D
+				    ct->pct_instr[i].pctf_samples.sb[j];
+			ct->pct_instr[i].pctf_samples.sb[j] =3D 0;
 		}
-#endif
-		/* Child function name. */
-		addr =3D child->pct_image->pi_vaddr + child->pct_func;
-		/* Child function source file. */
-		if (pmcstat_image_addr2line(child->pct_image, addr,
-		    sourcefile, sizeof(sourcefile), &line,
-		    funcname, sizeof(funcname))) {
-			fprintf(args.pa_graphfile, "cfn=3D%s\n", funcname);
-			fprintf(args.pa_graphfile, "cfl=3D%s\n", sourcefile);
-		} else {
-			sym =3D pmcstat_symbol_search(child->pct_image,
-			    child->pct_func);
-			if (sym !=3D NULL)
-				fprintf(args.pa_graphfile, "cfn=3D%s\n",
-				    pmcstat_string_unintern(sym->ps_name));
-			else
-				fprintf(args.pa_graphfile, "cfn=3D%p\n", (void *)addr);
-		}
+	}
+}
=20
-		/* Child function address, line and call count. */
-		fprintf(args.pa_graphfile, "calls=3D%u %p %u\n",
-		    ct->pct_arc[i].pcta_call, (void *)addr, line);
+static void
+pmcpl_ct_expand_inline(void)
+{
+	int i;
+	struct pmcpl_ct_node_hash *pch;
=20
-		if (ct->pct_image !=3D NULL) {
-			/* Call address, line, sample. */
-			addr =3D ct->pct_image->pi_vaddr + ct->pct_func;
-			line =3D 0;
-			if (pmcstat_image_addr2line(ct->pct_image, addr, sourcefile,
-			    sizeof(sourcefile), &line,
-			    funcname, sizeof(funcname)))
-				fprintf(args.pa_graphfile, "%p %u", (void *)addr, line);
-			else
-				fprintf(args.pa_graphfile, "* *");
-		}
-		else
-			fprintf(args.pa_graphfile, "* *");
-		for (j =3D 0; j<pmcstat_npmcs; j++)
-			fprintf(args.pa_graphfile, " %u",
-			    PMCPL_CT_SAMPLE(j, &ct->pct_arc[i].pcta_samples));
-		fprintf(args.pa_graphfile, "\n");
-	}
+	if (!args.pa_ctdumpinstr)
+		return;
+
+	for (i =3D 0; i < PMCSTAT_NHASH; i++)
+		STAILQ_FOREACH(pch, &pmcpl_ct_node_hash[i], pch_next)
+			if (pch->pch_ctnode->pct_type =3D=3D PMCPL_PCT_ADDR)
+				_pmcpl_ct_expand_inline(pch->pch_ctnode);
 }
=20
 /*
@@ -941,13 +1112,12 @@
 static void
 pmcpl_ct_print(void)
 {
-	int n, i;
-	struct pmcpl_ct_node_hash *pch;
+	int i;
+	char name[40];
 	struct pmcpl_ct_sample rsamples;
-	char name[40];
=20
 	pmcpl_ct_samples_root(&rsamples);
-	pmcpl_ct_prevfn =3D NULL;
+	pmcpl_ct_expand_inline();
=20
 	fprintf(args.pa_graphfile,
 		"version: 1\n"
@@ -964,25 +1134,8 @@
 	for (i=3D0; i<pmcstat_npmcs ; i++)
 		fprintf(args.pa_graphfile, " %u",
 		    PMCPL_CT_SAMPLE(i, &rsamples));
-	fprintf(args.pa_graphfile, "\n\n");
-
-	/*
-	 * Fake root node
-	 */
-	fprintf(args.pa_graphfile, "ob=3DFreeBSD\n");
-	fprintf(args.pa_graphfile, "fn=3DROOT\n");
-	fprintf(args.pa_graphfile, "* *");
-	for (i =3D 0; i<pmcstat_npmcs ; i++)
-		fprintf(args.pa_graphfile, " 0");
 	fprintf(args.pa_graphfile, "\n");
-	pmcpl_ct_node_printchild(pmcpl_ct_root);
-
-	for (n =3D 0; n < PMCSTAT_NHASH; n++)
-		LIST_FOREACH(pch, &pmcpl_ct_node_hash[n], pch_next) {
-			pmcpl_ct_node_printself(pch->pch_ctnode);
-			pmcpl_ct_node_printchild(pch->pch_ctnode);
-	}
-
+	pmcpl_ct_bfs(pmcpl_ct_root);
 	pmcpl_ct_samples_free(&rsamples);
 }
=20
@@ -1003,11 +1156,10 @@
 {
 	int i;
=20
-	pmcpl_ct_prevfn =3D NULL;
-	pmcpl_ct_root =3D pmcpl_ct_node_allocate(NULL, 0);
+	pmcpl_ct_root =3D pmcpl_ct_node_allocate();
=20
 	for (i =3D 0; i < PMCSTAT_NHASH; i++)
-		LIST_INIT(&pmcpl_ct_node_hash[i]);
+		STAILQ_INIT(&pmcpl_ct_node_hash[i]);
=20
 	pmcpl_ct_samples_init(&pmcpl_ct_callid);
=20
@@ -1030,7 +1182,7 @@
 	 */
=20
 	for (i =3D 0; i < PMCSTAT_NHASH; i++) {
-		LIST_FOREACH_SAFE(pch, &pmcpl_ct_node_hash[i], pch_next,
+		STAILQ_FOREACH_SAFE(pch, &pmcpl_ct_node_hash[i], pch_next,
 		    pchtmp) {
 			pmcpl_ct_node_free(pch->pch_ctnode);
 			free(pch);
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/pmcstat/pmcstat.8
--- a/head/usr.sbin/pmcstat/pmcstat.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/pmcstat/pmcstat.8	Tue Apr 17 11:51:51 2012 +0300
@@ -23,7 +23,7 @@
 .\" out of the use of this software, even if advised of the possibility of
 .\" such damage.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/pmcstat/pmcstat.8 233522 2012-03-26 21:22:53Z =
joel $
 .\"
 .Dd September 19, 2008
 .Dt PMCSTAT 8
@@ -388,7 +388,7 @@
 is specified,
 .Nm
 may issue the following diagnostic messages:
-.Bl -diag -width indent
+.Bl -diag
 .It "#callchain/dubious-frames"
 The number of callchain records that had an
 .Dq impossible
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/pmcstat/pmcstat_log.c
--- a/head/usr.sbin/pmcstat/pmcstat_log.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/pmcstat/pmcstat_log.c	Tue Apr 17 11:51:51 2012 +0300
@@ -34,7 +34,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.sbin/pmcstat/pmcstat_log.c 228990 2011-12-30 =
10:58:14Z uqs $");
+__FBSDID("$FreeBSD: head/usr.sbin/pmcstat/pmcstat_log.c 233628 2012-03-28 =
20:58:30Z fabient $");
=20
 #include <sys/param.h>
 #include <sys/endian.h>
@@ -429,7 +429,9 @@
=20
 	if ((fd =3D open(buffer, O_RDONLY, 0)) < 0 ||
 	    (nbytes =3D read(fd, &ex, sizeof(ex))) < 0) {
-		warn("WARNING: Cannot determine type of \"%s\"", path);
+		if (args.pa_verbosity >=3D 2)
+			warn("WARNING: Cannot determine type of \"%s\"",
+			    path);
 		image->pi_type =3D PMCSTAT_IMAGE_INDETERMINABLE;
 		if (fd !=3D -1)
 			(void) close(fd);
@@ -639,8 +641,9 @@
 	if ((fd =3D open(buffer, O_RDONLY, 0)) < 0 ||
 	    (e =3D elf_begin(fd, ELF_C_READ, NULL)) =3D=3D NULL ||
 	    (elf_kind(e) !=3D ELF_K_ELF)) {
-		warnx("WARNING: Cannot determine the type of \"%s\".",
-		    buffer);
+		if (args.pa_verbosity >=3D 2)
+			warnx("WARNING: Cannot determine the type of \"%s\".",
+			    buffer);
 		goto done;
 	}
=20
@@ -697,8 +700,8 @@
 				        ph.p_offset);
 				break;
 			case PT_LOAD:
-				if (ph.p_offset =3D=3D 0)
-					image->pi_vaddr =3D ph.p_vaddr;
+				if ((ph.p_offset & (-ph.p_align)) =3D=3D 0)
+					image->pi_vaddr =3D ph.p_vaddr & (-ph.p_align);
 				break;
 			}
 		}
@@ -946,6 +949,7 @@
     char *funcname, size_t funcname_len)
 {
 	static int addr2line_warn =3D 0;
+	unsigned l;
=20
 	char *sep, cmdline[PATH_MAX], imagepath[PATH_MAX];
 	int fd;
@@ -961,6 +965,11 @@
 			    pmcstat_string_unintern(image->pi_fullpath));
 		} else
 			close(fd);
+		/*
+		 * New addr2line support recursive inline function with -i
+		 * but the format does not add a marker when no more entries
+		 * are available.
+		 */
 		snprintf(cmdline, sizeof(cmdline), "addr2line -Cfe \"%s\"",
 		    imagepath);
 		image->pi_addr2line =3D popen(cmdline, "r+");
@@ -1002,10 +1011,10 @@
 		return (0);
 	}
 	*sep =3D '\0';
-	*sourceline =3D atoi(sep+1);
-	if (*sourceline =3D=3D 0)
+	l =3D atoi(sep+1);
+	if (l =3D=3D 0)
 		return (0);
-
+	*sourceline =3D l;
 	return (1);
 }
=20
@@ -1482,6 +1491,15 @@
 			    pmcstat_string_intern(ev.pl_u.pl_a.pl_evname));
 			break;
=20
+		case PMCLOG_TYPE_PMCALLOCATEDYN:
+			/*
+			 * Record the association pmc id between this
+			 * PMC and its name.
+			 */
+			pmcstat_pmcid_add(ev.pl_u.pl_ad.pl_pmcid,
+			    pmcstat_string_intern(ev.pl_u.pl_ad.pl_evname));
+			break;
+
 		case PMCLOG_TYPE_PROCEXEC:
=20
 			/*
@@ -1632,6 +1650,12 @@
 			    ev.pl_u.pl_a.pl_evname,
 			    ev.pl_u.pl_a.pl_flags);
 			break;
+		case PMCLOG_TYPE_PMCALLOCATEDYN:
+			PMCSTAT_PRINT_ENTRY("allocatedyn","0x%x \"%s\" 0x%x",
+			    ev.pl_u.pl_ad.pl_pmcid,
+			    ev.pl_u.pl_ad.pl_evname,
+			    ev.pl_u.pl_ad.pl_flags);
+			break;
 		case PMCLOG_TYPE_PMCATTACH:
 			PMCSTAT_PRINT_ENTRY("attach","0x%x %d \"%s\"",
 			    ev.pl_u.pl_t.pl_pmcid,
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/powerd/powerd.c
--- a/head/usr.sbin/powerd/powerd.c	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/powerd/powerd.c	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
  */
=20
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.sbin/powerd/powerd.c 228416 2011-12-11 19:22:=
42Z ed $");
+__FBSDID("$FreeBSD: head/usr.sbin/powerd/powerd.c 234070 2012-04-09 20:59:=
14Z rmh $");
=20
 #include <sys/param.h>
 #include <sys/ioctl.h>
@@ -44,6 +44,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sysexits.h>
 #include <unistd.h>
=20
 #ifdef __i386__
@@ -536,7 +537,7 @@
 		err(1, "lookup kern.cp_times");
 	len =3D 4;
 	if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
-		err(1, "lookup freq");
+		err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
 	len =3D 4;
 	if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
 		err(1, "lookup freq_levels");
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/rtadvd/rtadvd.8
--- a/head/usr.sbin/rtadvd/rtadvd.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/rtadvd/rtadvd.8	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/rtadvd/rtadvd.8 224144 2011-07-17 19:24:54Z hr=
s $
+.\" $FreeBSD: head/usr.sbin/rtadvd/rtadvd.8 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd July 14, 2011
 .Dt RTADVD 8
@@ -158,7 +158,7 @@
 .Pa /etc/rtadvd.conf .
 If an invalid parameter is found in the configuration file upon the reload,
 the entry will be ignored and the old configuration will be used.
-When parameters in an existing entry are updated,=20
+When parameters in an existing entry are updated,
 .Nm
 will send Router Advertisement messages with the old configuration but
 zero router lifetime to the interface first, and then start to send a new
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/rtadvd/rtadvd.conf.5
--- a/head/usr.sbin/rtadvd/rtadvd.conf.5	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/rtadvd/rtadvd.conf.5	Tue Apr 17 11:51:51 2012 +0300
@@ -27,7 +27,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/rtadvd/rtadvd.conf.5 222732 2011-06-06 03:06:4=
3Z hrs $
+.\" $FreeBSD: head/usr.sbin/rtadvd/rtadvd.conf.5 233522 2012-03-26 21:22:5=
3Z joel $
 .\"
 .Dd June 4, 2011
 .Dt RTADVD.CONF 5
@@ -449,7 +449,7 @@
 overrides the router lifetime parameter for the
 .Li ne0
 interface.
-.Bd -literal -offset
+.Bd -literal -offset indent
 ne0:\\
 	:rltime#0:
 .Ed
@@ -461,7 +461,7 @@
 .Fl s
 option to
 .Xr rtadvd 8 .
-.Bd -literal -offset
+.Bd -literal -offset indent
 ef0:\\
 	:addr=3D"2001:db8:ffff:1000::":prefixlen#64:
 .Ed
@@ -470,7 +470,7 @@
 .Li wlan0
 interface and adds two DNS servers and a DNS domain search options
 using the default option lifetime values.
-.Bd -literal -offset
+.Bd -literal -offset indent
 wlan0:\\
 	:addr=3D"2001:db8:ffff:1000::":prefixlen#64:\\
 	:rdnss=3D"2001:db8:ffff::10,2001:db8:ffff::2:43":\\
@@ -480,7 +480,7 @@
 The following example presents the default values in an explicit manner.
 The configuration is provided just for reference purposes;
 YOU DO NOT NEED TO HAVE IT AT ALL.
-.Bd -literal -offset
+.Bd -literal -offset indent
 default:\\
 	:chlim#64:raflags#0:rltime#1800:rtime#0:retrans#0:\\
 	:pinfoflags=3D"la":vltime#2592000:pltime#604800:mtu#0:
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/setfib/setfib.1
--- a/head/usr.sbin/setfib/setfib.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/setfib/setfib.1	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/setfib/setfib.1 233648 2012-03-29 05:02:12Z ea=
dler $
 .\"
 .Dd April 9, 2008
 .Dt SETFIB 1
@@ -32,7 +32,7 @@
 .Nd execute a utility with an altered default network view
 .Sh SYNOPSIS
 .Nm
-.Op Fl F=20
+.Op Fl F
 .Ar fib
 .Ar utility
 .Op Ar argument ...
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/tcpdump/tcpdump/tcpdump.1
--- a/head/usr.sbin/tcpdump/tcpdump/tcpdump.1	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/tcpdump/tcpdump/tcpdump.1	Tue Apr 17 11:51:51 2012 +0300
@@ -1,4 +1,4 @@
-.\" $FreeBSD: head/usr.sbin/tcpdump/tcpdump/tcpdump.1 228990 2011-12-30 10=
:58:14Z uqs $
+.\" $FreeBSD: head/usr.sbin/tcpdump/tcpdump/tcpdump.1 233648 2012-03-29 05=
:02:12Z eadler $
 .\" @(#) $Header: /tcpdump/master/tcpdump/tcpdump.1.in,v 1.2 2008-11-09 23=
:35:03 mcr Exp $ (LBL)
 .\"
 .\"	$NetBSD: tcpdump.8,v 1.9 2003/03/31 00:18:17 perry Exp $
@@ -272,7 +272,7 @@
 The ability to decrypt packets is only present if \fItcpdump\fP was compil=
ed
 with cryptography enabled.
 .IP
-\fIsecret\fP is the ASCII text for ESP secret key.=20
+\fIsecret\fP is the ASCII text for ESP secret key.
 If preceded by 0x, then a hex value will be read.
 .IP
 The option assumes RFC2406 ESP, not RFC1827 ESP.
@@ -284,7 +284,7 @@
 and other occasions.
 .IP
 In addition to the above syntax, the syntax \fIfile name\fP may be used
-to have tcpdump read the provided file in. The file is opened upon=20
+to have tcpdump read the provided file in. The file is opened upon
 receiving the first ESP packet, so any special permissions that tcpdump
 may have been given should already have been given up.
 .TP
@@ -540,16 +540,16 @@
 for a description of the file format.
 .TP
 .B \-W
-Used in conjunction with the=20
-.B \-C=20
+Used in conjunction with the
+.B \-C
 option, this will limit the number
 of files created to the specified number, and begin overwriting files
-from the beginning, thus creating a 'rotating' buffer.=20
+from the beginning, thus creating a 'rotating' buffer.
 In addition, it will name
 the files with enough leading 0s to support the maximum number of
 files, allowing them to sort correctly.
 .IP
-Used in conjunction with the=20
+Used in conjunction with the
 .B \-G
 option, this will limit the number of rotated dump files that get
 created, exiting with status 0 when reaching the limit. If used with
@@ -559,7 +559,7 @@
 .B \-x
 When parsing and printing,
 in addition to printing the headers of each packet, print the data of
-each packet (minus its link level header) in hex.=20
+each packet (minus its link level header) in hex.
 The smaller of the entire packet or
 .I snaplen
 bytes will be printed.  Note that this is the entire link-layer
@@ -1156,7 +1156,7 @@
 .PP
 This can be demonstrated as:
 .RS
-.B=20
+.B
      tcpdump -i xl0 'tcp[tcpflags] & tcp-push !=3D 0'
 .RE
 .PP
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/timed/timed/timed.8
--- a/head/usr.sbin/timed/timed/timed.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/timed/timed/timed.8	Tue Apr 17 11:51:51 2012 +0300
@@ -26,7 +26,7 @@
 .\" SUCH DAMAGE.
 .\"
 .\"     @(#)timed.8	8.1 (Berkeley) 6/6/93
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/timed/timed/timed.8 233648 2012-03-29 05:02:12=
Z eadler $
 .\"
 .Dd February 11, 2008
 .Dt TIMED 8
@@ -86,20 +86,20 @@
 will suppress incoming messages from that host
 and call for a new election.
 .It
-Use real host names (resolvable by RDNS) not aliases (eg in=20
+Use real host names (resolvable by RDNS) not aliases (eg in
 .Xr named 8
 parlance: use A names, not C names).
 .It
 Use full names eg time1.domain.com not time1.
 .It
 .Fl F
-automatically includes the functionality of=20
+automatically includes the functionality of
 .Fl M
 (so
 .Fl M
 does not need to asserted).
 .It
-If=20
+If
 .Fl F
 is not specified,
 all hosts on connected networks are treated as trustworthy.
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/utx/utx.8
--- a/head/usr.sbin/utx/utx.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/utx/utx.8	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.sbin/utx/utx.8 231530 2012-02-11 20:28:42Z ed $
+.\" $FreeBSD: head/usr.sbin/utx/utx.8 233455 2012-03-25 09:18:34Z joel $
 .\"
 .Dd February 11, 2012
 .Dt UTX 8
@@ -89,7 +89,6 @@
 command.
 .El
 .Pp
-.Pp
 Because this utility requires write-access to the user accounting
 database, its use is limited to the super-user.
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/wlandebug/wlandebug.8
--- a/head/usr.sbin/wlandebug/wlandebug.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/wlandebug/wlandebug.8	Tue Apr 17 11:51:51 2012 +0300
@@ -22,7 +22,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/wlandebug/wlandebug.8 233648 2012-03-29 05:02:=
12Z eadler $
 .\"
 .Dd July 17, 2009
 .Dt WLANDEBUG 8
@@ -119,7 +119,7 @@
 .It Ar mesh
 trace operation of 802.11s mesh protocol processing.
 .It Ar wpa
-trace operation of the WPA protocol;=20
+trace operation of the WPA protocol;
 only partly meaningful as WPA protocol
 support is mostly implemented in user mode by the
 .Xr hostapd 8
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/wlconfig/wlconfig.8
--- a/head/usr.sbin/wlconfig/wlconfig.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/wlconfig/wlconfig.8	Tue Apr 17 11:51:51 2012 +0300
@@ -1,8 +1,8 @@
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/wlconfig/wlconfig.8 233522 2012-03-26 21:22:53=
Z joel $
 .\"
 .Dd December 26, 1996
+.Dt WLCONFIG 8 i386
 .Os
-.Dt WLCONFIG 8 i386
 .Sh NAME
 .Nm wlconfig
 .Nd read/write wavelan config parameters
@@ -97,12 +97,12 @@
 value.
 .Sh EXAMPLES
 Set the NWID to 0x1234:
-.Bd -literal -offset
+.Bd -literal -offset indent
 # wlconfig wl0 nwid 0x1234
 .Ed
 .Pp
 Show the current settings:
-.Bd -literal -offset
+.Bd -literal -offset indent
 # wlconfig wl0
 Board type            : ISA
 Base address options  : 0x300, 0x390, 0x3c0, 0x3e0
@@ -128,7 +128,7 @@
 .Ed
 .Pp
 Print a scaled version of the signal strength cache:
-.Bd -literal -offset
+.Bd -literal -offset indent
 # wlconfig wl0 cache scale
 .Ed
 .Sh SEE ALSO
diff -r 428842767fa6 -r f2935497fa04 head/usr.sbin/ypserv/ypserv.8
--- a/head/usr.sbin/ypserv/ypserv.8	Tue Apr 17 11:36:47 2012 +0300
+++ b/head/usr.sbin/ypserv/ypserv.8	Tue Apr 17 11:51:51 2012 +0300
@@ -28,7 +28,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/ypserv/ypserv.8 233455 2012-03-25 09:18:34Z jo=
el $
 .\"
 .Dd December 13, 2009
 .Dt YPSERV 8
@@ -220,7 +220,6 @@
 authentication through
 .Tn NIS .
 .El
-.Pp
 .Ss Security
 In general, any remote user can issue an RPC to
 .Nm
@@ -292,7 +291,6 @@
 to
 .Dq IP spoofing
 attacks.
-.Pp
 .Ss NIS v1 compatibility
 This version of
 .Nm



More information about the Zrouter-src-freebsd mailing list